From 854589ddbe4416504a69283b80fe68c4a4c673ed Mon Sep 17 00:00:00 2001 From: svipal Date: Fri, 10 Apr 2020 20:40:52 +0200 Subject: [PATCH] clean up --- .gitignore | 38 +- CHANGELOG.md | 6742 +- README.md | 1262 +- dist/phaser-arcade-physics.js | 18562 +- dist/phaser-arcade-physics.min.js | 2 +- dist/phaser-facebook-instant-games.js | 203022 +++++++++++++++ dist/phaser-facebook-instant-games.min.js | 1 + dist/phaser.js | 23714 +- dist/phaser.min.js | 2 +- package-lock.json | 11246 +- package.json | 176 +- .../src/FacebookInstantGamesPlugin.js | 4628 +- plugins/impact/Body.js | 1190 +- plugins/impact/COLLIDES.js | 146 +- plugins/impact/CollisionMap.js | 716 +- plugins/impact/DefaultDefs.js | 130 +- plugins/impact/Factory.js | 302 +- plugins/impact/GetVelocity.js | 100 +- plugins/impact/ImpactBody.js | 254 +- plugins/impact/ImpactImage.js | 304 +- plugins/impact/ImpactPhysics.js | 422 +- plugins/impact/ImpactSprite.js | 310 +- plugins/impact/SeparateX.js | 100 +- plugins/impact/SeparateY.js | 158 +- plugins/impact/Solver.js | 140 +- plugins/impact/TYPE.js | 124 +- plugins/impact/UpdateMotion.js | 178 +- plugins/impact/World.js | 1958 +- plugins/impact/components/Acceleration.js | 142 +- plugins/impact/components/BodyScale.js | 136 +- plugins/impact/components/BodyType.js | 156 +- plugins/impact/components/Bounce.js | 148 +- plugins/impact/components/CheckAgainst.js | 232 +- plugins/impact/components/Collides.js | 300 +- plugins/impact/components/Debug.js | 238 +- plugins/impact/components/Friction.js | 142 +- plugins/impact/components/Gravity.js | 112 +- plugins/impact/components/Offset.js | 88 +- plugins/impact/components/SetGameObject.js | 140 +- plugins/impact/components/Velocity.js | 188 +- plugins/impact/components/index.js | 52 +- plugins/impact/events/COLLIDE_EVENT.js | 42 +- plugins/impact/events/PAUSE_EVENT.js | 34 +- plugins/impact/events/RESUME_EVENT.js | 34 +- plugins/impact/events/index.js | 34 +- plugins/impact/index.js | 72 +- plugins/impact/typedefs/CollisionOptions.js | 28 +- plugins/impact/typedefs/JSONImpactBody.js | 36 +- plugins/impact/typedefs/WorldConfig.js | 60 +- plugins/impact/typedefs/WorldDefaults.js | 32 +- plugins/impact/typedefs/WorldWalls.js | 18 +- plugins/impact/typedefs/index.js | 18 +- scripts/tsgen/bin/Parser.js | 1018 +- scripts/tsgen/src/Parser.ts | 1214 +- src/actions/AlignTo.js | 84 +- src/actions/Angle.js | 70 +- src/actions/Call.js | 66 +- src/actions/GetFirst.js | 104 +- src/actions/GetLast.js | 104 +- src/actions/GridAlign.js | 186 +- src/actions/IncAlpha.js | 70 +- src/actions/IncX.js | 70 +- src/actions/IncXY.js | 82 +- src/actions/IncY.js | 70 +- src/actions/PlaceOnCircle.js | 86 +- src/actions/PlaceOnEllipse.js | 92 +- src/actions/PlaceOnLine.js | 76 +- src/actions/PlaceOnRectangle.js | 104 +- src/actions/PlaceOnTriangle.js | 110 +- src/actions/PlayAnimation.js | 62 +- src/actions/PropertyValueInc.js | 122 +- src/actions/PropertyValueSet.js | 122 +- src/actions/RandomCircle.js | 68 +- src/actions/RandomEllipse.js | 68 +- src/actions/RandomLine.js | 68 +- src/actions/RandomRectangle.js | 64 +- src/actions/RandomTriangle.js | 68 +- src/actions/Rotate.js | 70 +- src/actions/RotateAround.js | 80 +- src/actions/RotateAroundDistance.js | 86 +- src/actions/ScaleX.js | 70 +- src/actions/ScaleXY.js | 82 +- src/actions/ScaleY.js | 70 +- src/actions/SetAlpha.js | 70 +- src/actions/SetBlendMode.js | 68 +- src/actions/SetDepth.js | 70 +- src/actions/SetHitArea.js | 66 +- src/actions/SetOrigin.js | 82 +- src/actions/SetRotation.js | 70 +- src/actions/SetScale.js | 82 +- src/actions/SetScaleX.js | 70 +- src/actions/SetScaleY.js | 70 +- src/actions/SetScrollFactor.js | 82 +- src/actions/SetScrollFactorX.js | 70 +- src/actions/SetScrollFactorY.js | 70 +- src/actions/SetTint.js | 66 +- src/actions/SetVisible.js | 64 +- src/actions/SetX.js | 70 +- src/actions/SetXY.js | 82 +- src/actions/SetY.js | 70 +- src/actions/ShiftPosition.js | 248 +- src/actions/Shuffle.js | 54 +- src/actions/SmoothStep.js | 104 +- src/actions/SmootherStep.js | 104 +- src/actions/Spread.js | 114 +- src/actions/ToggleVisible.js | 60 +- src/actions/WrapInRectangle.js | 86 +- src/actions/index.js | 134 +- src/actions/typedefs/index.js | 18 +- src/animations/Animation.js | 1908 +- src/animations/AnimationFrame.js | 336 +- src/animations/AnimationManager.js | 1352 +- src/animations/events/ADD_ANIMATION_EVENT.js | 42 +- .../events/ANIMATION_COMPLETE_EVENT.js | 44 +- .../events/ANIMATION_REPEAT_EVENT.js | 42 +- .../events/ANIMATION_RESTART_EVENT.js | 44 +- .../events/ANIMATION_START_EVENT.js | 44 +- src/animations/events/PAUSE_ALL_EVENT.js | 36 +- .../events/REMOVE_ANIMATION_EVENT.js | 36 +- src/animations/events/RESUME_ALL_EVENT.js | 34 +- .../events/SPRITE_ANIMATION_COMPLETE_EVENT.js | 46 +- .../SPRITE_ANIMATION_KEY_COMPLETE_EVENT.js | 44 +- .../SPRITE_ANIMATION_KEY_REPEAT_EVENT.js | 46 +- .../SPRITE_ANIMATION_KEY_RESTART_EVENT.js | 44 +- .../SPRITE_ANIMATION_KEY_START_EVENT.js | 44 +- .../SPRITE_ANIMATION_KEY_UPDATE_EVENT.js | 46 +- .../events/SPRITE_ANIMATION_REPEAT_EVENT.js | 48 +- .../events/SPRITE_ANIMATION_RESTART_EVENT.js | 46 +- .../events/SPRITE_ANIMATION_START_EVENT.js | 46 +- .../events/SPRITE_ANIMATION_UPDATE_EVENT.js | 48 +- src/animations/events/index.js | 64 +- src/animations/index.js | 36 +- src/animations/typedefs/AnimationFrame.js | 18 +- src/animations/typedefs/GenerateFrameNames.js | 24 +- src/animations/typedefs/JSONAnimation.js | 34 +- src/animations/typedefs/index.js | 18 +- src/cache/BaseCache.js | 360 +- src/cache/CacheManager.js | 456 +- src/cache/events/ADD_EVENT.js | 38 +- src/cache/events/REMOVE_EVENT.js | 38 +- src/cache/events/index.js | 32 +- src/cache/index.js | 34 +- src/cameras/2d/BaseCamera.js | 3830 +- src/cameras/2d/Camera.js | 2024 +- src/cameras/2d/CameraManager.js | 1484 +- src/cameras/2d/effects/Fade.js | 764 +- src/cameras/2d/effects/Flash.js | 690 +- src/cameras/2d/effects/Pan.js | 638 +- src/cameras/2d/effects/Shake.js | 626 +- src/cameras/2d/effects/Zoom.js | 574 +- src/cameras/2d/effects/index.js | 38 +- src/cameras/2d/events/DESTROY_EVENT.js | 34 +- .../2d/events/FADE_IN_COMPLETE_EVENT.js | 40 +- src/cameras/2d/events/FADE_IN_START_EVENT.js | 48 +- .../2d/events/FADE_OUT_COMPLETE_EVENT.js | 40 +- src/cameras/2d/events/FADE_OUT_START_EVENT.js | 48 +- src/cameras/2d/events/FLASH_COMPLETE_EVENT.js | 36 +- src/cameras/2d/events/FLASH_START_EVENT.js | 44 +- src/cameras/2d/events/PAN_COMPLETE_EVENT.js | 36 +- src/cameras/2d/events/PAN_START_EVENT.js | 42 +- src/cameras/2d/events/POST_RENDER_EVENT.js | 40 +- src/cameras/2d/events/PRE_RENDER_EVENT.js | 40 +- src/cameras/2d/events/SHAKE_COMPLETE_EVENT.js | 36 +- src/cameras/2d/events/SHAKE_START_EVENT.js | 40 +- src/cameras/2d/events/ZOOM_COMPLETE_EVENT.js | 36 +- src/cameras/2d/events/ZOOM_START_EVENT.js | 40 +- src/cameras/2d/events/index.js | 58 +- src/cameras/2d/index.js | 38 +- src/cameras/2d/typedefs/index.js | 18 +- src/cameras/controls/FixedKeyControl.js | 600 +- src/cameras/controls/SmoothedKeyControl.js | 954 +- src/cameras/controls/index.js | 32 +- src/cameras/controls/typedefs/index.js | 18 +- src/cameras/index.js | 40 +- src/const.js | 386 +- src/core/Config.js | 1150 +- src/core/CreateRenderer.js | 276 +- src/core/DebugHeader.js | 248 +- src/core/Game.js | 1422 +- src/core/TimeStep.js | 1448 +- src/core/VisibilityHandler.js | 170 +- src/core/events/BLUR_EVENT.js | 34 +- src/core/events/BOOT_EVENT.js | 32 +- src/core/events/CONTEXT_LOST_EVENT.js | 34 +- src/core/events/CONTEXT_RESTORED_EVENT.js | 34 +- src/core/events/DESTROY_EVENT.js | 34 +- src/core/events/FOCUS_EVENT.js | 32 +- src/core/events/HIDDEN_EVENT.js | 40 +- src/core/events/PAUSE_EVENT.js | 30 +- src/core/events/POST_RENDER_EVENT.js | 40 +- src/core/events/POST_STEP_EVENT.js | 38 +- src/core/events/PRE_RENDER_EVENT.js | 38 +- src/core/events/PRE_STEP_EVENT.js | 38 +- src/core/events/READY_EVENT.js | 32 +- src/core/events/RESUME_EVENT.js | 30 +- src/core/events/STEP_EVENT.js | 38 +- src/core/events/VISIBLE_EVENT.js | 36 +- src/core/events/index.js | 60 +- src/core/index.js | 40 +- src/core/typedefs/PhysicsConfig.js | 16 +- src/core/typedefs/index.js | 18 +- src/create/GenerateTexture.js | 232 +- src/create/index.js | 32 +- src/create/palettes/Arne16.js | 64 +- src/create/palettes/C64.js | 64 +- src/create/palettes/CGA.js | 64 +- src/create/palettes/JMP.js | 64 +- src/create/palettes/MSX.js | 64 +- src/create/palettes/index.js | 38 +- src/create/typedefs/GenerateTextureConfig.js | 44 +- src/create/typedefs/index.js | 18 +- src/curves/CubicBezierCurve.js | 442 +- src/curves/Curve.js | 1228 +- src/curves/EllipseCurve.js | 1236 +- src/curves/LineCurve.js | 598 +- src/curves/QuadraticBezierCurve.js | 416 +- src/curves/SplineCurve.js | 438 +- src/curves/index.js | 40 +- src/curves/path/MoveTo.js | 268 +- src/curves/path/Path.js | 1686 +- src/curves/typedefs/index.js | 18 +- src/data/DataManager.js | 1270 +- src/data/DataManagerPlugin.js | 242 +- src/data/events/CHANGE_DATA_EVENT.js | 52 +- src/data/events/CHANGE_DATA_KEY_EVENT.js | 48 +- src/data/events/REMOVE_DATA_EVENT.js | 44 +- src/data/events/SET_DATA_EVENT.js | 44 +- src/data/events/index.js | 36 +- src/data/index.js | 34 +- src/device/Audio.js | 238 +- src/device/Browser.js | 208 +- src/device/CanvasFeatures.js | 216 +- src/device/Features.js | 372 +- src/device/Fullscreen.js | 196 +- src/device/Input.js | 138 +- src/device/OS.js | 330 +- src/device/Video.js | 162 +- src/device/index.js | 82 +- src/display/align/const.js | 256 +- src/display/align/in/BottomCenter.js | 76 +- src/display/align/in/BottomLeft.js | 76 +- src/display/align/in/BottomRight.js | 76 +- src/display/align/in/Center.js | 72 +- src/display/align/in/LeftCenter.js | 76 +- src/display/align/in/QuickSet.js | 94 +- src/display/align/in/RightCenter.js | 76 +- src/display/align/in/TopCenter.js | 76 +- src/display/align/in/TopLeft.js | 76 +- src/display/align/in/TopRight.js | 76 +- src/display/align/in/index.js | 48 +- src/display/align/index.js | 48 +- src/display/align/to/BottomCenter.js | 76 +- src/display/align/to/BottomLeft.js | 76 +- src/display/align/to/BottomRight.js | 76 +- src/display/align/to/LeftBottom.js | 76 +- src/display/align/to/LeftCenter.js | 76 +- src/display/align/to/LeftTop.js | 76 +- src/display/align/to/QuickSet.js | 92 +- src/display/align/to/RightBottom.js | 76 +- src/display/align/to/RightCenter.js | 76 +- src/display/align/to/RightTop.js | 76 +- src/display/align/to/TopCenter.js | 76 +- src/display/align/to/TopLeft.js | 76 +- src/display/align/to/TopRight.js | 76 +- src/display/align/to/index.js | 54 +- src/display/bounds/CenterOn.js | 62 +- src/display/bounds/GetBottom.js | 44 +- src/display/bounds/GetCenterX.js | 44 +- src/display/bounds/GetCenterY.js | 44 +- src/display/bounds/GetLeft.js | 44 +- src/display/bounds/GetOffsetX.js | 48 +- src/display/bounds/GetOffsetY.js | 48 +- src/display/bounds/GetRight.js | 44 +- src/display/bounds/GetTop.js | 44 +- src/display/bounds/SetBottom.js | 54 +- src/display/bounds/SetCenterX.js | 58 +- src/display/bounds/SetCenterY.js | 58 +- src/display/bounds/SetLeft.js | 54 +- src/display/bounds/SetRight.js | 54 +- src/display/bounds/SetTop.js | 54 +- src/display/bounds/index.js | 58 +- src/display/canvas/CanvasInterpolation.js | 114 +- src/display/canvas/CanvasPool.js | 510 +- src/display/canvas/Smoothing.js | 252 +- src/display/canvas/TouchAction.js | 58 +- src/display/canvas/UserSelect.js | 82 +- src/display/canvas/index.js | 38 +- src/display/color/Color.js | 1714 +- src/display/color/ColorToRGBA.js | 68 +- src/display/color/ComponentToHex.js | 48 +- src/display/color/GetColor.js | 48 +- src/display/color/GetColor32.js | 50 +- src/display/color/HSLToColor.js | 88 +- src/display/color/HSVColorWheel.js | 70 +- src/display/color/HSVToRGB.js | 190 +- src/display/color/HexStringToColor.js | 94 +- src/display/color/HueToComponent.js | 100 +- src/display/color/IntegerToColor.js | 54 +- src/display/color/IntegerToRGB.js | 84 +- src/display/color/Interpolate.js | 204 +- src/display/color/ObjectToColor.js | 48 +- src/display/color/RGBStringToColor.js | 80 +- src/display/color/RGBToHSV.js | 148 +- src/display/color/RGBToString.js | 76 +- src/display/color/RandomRGB.js | 60 +- src/display/color/ValueToColor.js | 100 +- src/display/color/index.js | 56 +- src/display/index.js | 40 +- src/display/mask/BitmapMask.js | 574 +- src/display/mask/GeometryMask.js | 618 +- src/display/mask/index.js | 32 +- src/display/shader/BaseShader.js | 236 +- src/dom/AddToDOM.js | 104 +- src/dom/CreateDOMContainer.js | 76 +- src/dom/DOMContentLoaded.js | 114 +- src/dom/GetInnerHeight.js | 106 +- src/dom/GetScreenOrientation.js | 120 +- src/dom/GetTarget.js | 90 +- src/dom/ParseXML.js | 102 +- src/dom/RemoveFromDOM.js | 46 +- src/dom/RequestAnimationFrame.js | 416 +- src/dom/index.js | 46 +- src/events/EventEmitter.js | 356 +- src/events/index.js | 22 +- src/gameobjects/BuildGameObject.js | 244 +- src/gameobjects/BuildGameObjectAnimation.js | 166 +- src/gameobjects/DisplayList.js | 398 +- src/gameobjects/GameObject.js | 1270 +- src/gameobjects/GameObjectCreator.js | 324 +- src/gameobjects/GameObjectFactory.js | 424 +- src/gameobjects/UpdateList.js | 590 +- .../bitmaptext/GetBitmapTextSize.js | 894 +- src/gameobjects/bitmaptext/ParseFromAtlas.js | 94 +- src/gameobjects/bitmaptext/ParseRetroFont.js | 220 +- .../bitmaptext/ParseXMLBitmapFont.js | 266 +- src/gameobjects/bitmaptext/RetroFont.js | 40 +- src/gameobjects/bitmaptext/const.js | 220 +- .../bitmaptext/dynamic/DynamicBitmapText.js | 454 +- .../DynamicBitmapTextCanvasRenderer.js | 410 +- .../dynamic/DynamicBitmapTextCreator.js | 90 +- .../dynamic/DynamicBitmapTextFactory.js | 126 +- .../dynamic/DynamicBitmapTextRender.js | 50 +- .../dynamic/DynamicBitmapTextWebGLRenderer.js | 600 +- .../bitmaptext/static/BitmapText.js | 1446 +- .../static/BitmapTextCanvasRenderer.js | 352 +- .../bitmaptext/static/BitmapTextCreator.js | 94 +- .../bitmaptext/static/BitmapTextFactory.js | 116 +- .../bitmaptext/static/BitmapTextRender.js | 50 +- .../static/BitmapTextWebGLRenderer.js | 460 +- src/gameobjects/bitmaptext/typedefs/index.js | 18 +- src/gameobjects/blitter/Blitter.js | 586 +- .../blitter/BlitterCanvasRenderer.js | 248 +- src/gameobjects/blitter/BlitterCreator.js | 88 +- src/gameobjects/blitter/BlitterFactory.js | 72 +- src/gameobjects/blitter/BlitterRender.js | 50 +- .../blitter/BlitterWebGLRenderer.js | 248 +- src/gameobjects/blitter/Bob.js | 848 +- src/gameobjects/components/Alpha.js | 578 +- src/gameobjects/components/AlphaSingle.js | 208 +- src/gameobjects/components/Animation.js | 2344 +- src/gameobjects/components/BlendMode.js | 232 +- src/gameobjects/components/ComputedSize.js | 286 +- src/gameobjects/components/Crop.js | 238 +- src/gameobjects/components/Depth.js | 174 +- src/gameobjects/components/Flip.js | 316 +- src/gameobjects/components/GetBounds.js | 706 +- src/gameobjects/components/Mask.js | 282 +- src/gameobjects/components/Origin.js | 394 +- src/gameobjects/components/PathFollower.js | 800 +- src/gameobjects/components/Pipeline.js | 246 +- src/gameobjects/components/ScrollFactor.js | 202 +- src/gameobjects/components/Size.js | 362 +- src/gameobjects/components/Texture.js | 248 +- src/gameobjects/components/TextureCrop.js | 404 +- src/gameobjects/components/Tint.js | 668 +- src/gameobjects/components/ToJSON.js | 110 +- src/gameobjects/components/Transform.js | 1066 +- src/gameobjects/components/TransformMatrix.js | 1924 +- src/gameobjects/components/Visible.js | 166 +- src/gameobjects/components/index.js | 72 +- src/gameobjects/container/Container.js | 2638 +- .../container/ContainerCanvasRenderer.js | 182 +- src/gameobjects/container/ContainerCreator.js | 86 +- src/gameobjects/container/ContainerFactory.js | 56 +- src/gameobjects/container/ContainerRender.js | 52 +- .../container/ContainerWebGLRenderer.js | 286 +- src/gameobjects/domelement/CSSBlendModes.js | 70 +- src/gameobjects/domelement/DOMElement.js | 1936 +- .../domelement/DOMElementCSSRenderer.js | 232 +- .../domelement/DOMElementFactory.js | 168 +- .../domelement/DOMElementRender.js | 50 +- src/gameobjects/events/DESTROY_EVENT.js | 38 +- .../events/VIDEO_COMPLETE_EVENT.js | 52 +- src/gameobjects/events/VIDEO_CREATED_EVENT.js | 46 +- src/gameobjects/events/VIDEO_ERROR_EVENT.js | 40 +- src/gameobjects/events/VIDEO_LOOP_EVENT.js | 52 +- src/gameobjects/events/VIDEO_PLAY_EVENT.js | 44 +- src/gameobjects/events/VIDEO_SEEKED_EVENT.js | 38 +- src/gameobjects/events/VIDEO_SEEKING_EVENT.js | 40 +- src/gameobjects/events/VIDEO_STOP_EVENT.js | 40 +- src/gameobjects/events/VIDEO_TIMEOUT_EVENT.js | 40 +- .../events/VIDEO_UNLOCKED_EVENT.js | 40 +- src/gameobjects/events/index.js | 50 +- src/gameobjects/extern/Extern.js | 180 +- src/gameobjects/extern/ExternFactory.js | 72 +- src/gameobjects/extern/ExternRender.js | 50 +- src/gameobjects/extern/ExternWebGLRenderer.js | 126 +- src/gameobjects/graphics/Commands.js | 62 +- src/gameobjects/graphics/Graphics.js | 3088 +- .../graphics/GraphicsCanvasRenderer.js | 488 +- src/gameobjects/graphics/GraphicsCreator.js | 84 +- src/gameobjects/graphics/GraphicsFactory.js | 66 +- src/gameobjects/graphics/GraphicsRender.js | 56 +- .../graphics/GraphicsWebGLRenderer.js | 718 +- src/gameobjects/graphics/typedefs/index.js | 18 +- src/gameobjects/group/Group.js | 3264 +- src/gameobjects/group/GroupCreator.js | 54 +- src/gameobjects/group/GroupFactory.js | 52 +- src/gameobjects/group/typedefs/index.js | 18 +- src/gameobjects/image/Image.js | 190 +- src/gameobjects/image/ImageCanvasRenderer.js | 54 +- src/gameobjects/image/ImageCreator.js | 88 +- src/gameobjects/image/ImageFactory.js | 72 +- src/gameobjects/image/ImageRender.js | 50 +- src/gameobjects/image/ImageWebGLRenderer.js | 54 +- src/gameobjects/index.js | 274 +- src/gameobjects/lights/Light.js | 514 +- src/gameobjects/lights/LightsManager.js | 714 +- src/gameobjects/lights/LightsPlugin.js | 220 +- src/gameobjects/mesh/Mesh.js | 330 +- src/gameobjects/mesh/MeshCanvasRenderer.js | 46 +- src/gameobjects/mesh/MeshCreator.js | 98 +- src/gameobjects/mesh/MeshFactory.js | 88 +- src/gameobjects/mesh/MeshRender.js | 50 +- src/gameobjects/mesh/MeshWebGLRenderer.js | 224 +- src/gameobjects/particles/EmitterOp.js | 1170 +- src/gameobjects/particles/GravityWell.js | 426 +- src/gameobjects/particles/Particle.js | 1126 +- src/gameobjects/particles/ParticleEmitter.js | 4130 +- .../particles/ParticleEmitterManager.js | 966 +- .../ParticleManagerCanvasRenderer.js | 234 +- .../particles/ParticleManagerCreator.js | 102 +- .../particles/ParticleManagerFactory.js | 80 +- .../particles/ParticleManagerRender.js | 50 +- .../particles/ParticleManagerWebGLRenderer.js | 306 +- src/gameobjects/particles/index.js | 38 +- src/gameobjects/particles/typedefs/index.js | 18 +- src/gameobjects/particles/zones/DeathZone.js | 144 +- src/gameobjects/particles/zones/EdgeZone.js | 476 +- src/gameobjects/particles/zones/RandomZone.js | 134 +- src/gameobjects/particles/zones/index.js | 34 +- src/gameobjects/pathfollower/PathFollower.js | 152 +- .../pathfollower/PathFollowerFactory.js | 84 +- .../pathfollower/typedefs/index.js | 18 +- src/gameobjects/quad/Quad.js | 1310 +- src/gameobjects/quad/QuadCreator.js | 88 +- src/gameobjects/quad/QuadFactory.js | 80 +- .../rendertexture/RenderTexture.js | 2466 +- .../RenderTextureCanvasRenderer.js | 54 +- .../rendertexture/RenderTextureCreator.js | 92 +- .../rendertexture/RenderTextureFactory.js | 68 +- .../rendertexture/RenderTextureRender.js | 50 +- .../RenderTextureWebGLRenderer.js | 114 +- .../rendertexture/typedefs/index.js | 18 +- src/gameobjects/rope/Rope.js | 2200 +- src/gameobjects/rope/RopeCanvasRenderer.js | 46 +- src/gameobjects/rope/RopeCreator.js | 98 +- src/gameobjects/rope/RopeFactory.js | 96 +- src/gameobjects/rope/RopeRender.js | 50 +- src/gameobjects/rope/RopeWebGLRenderer.js | 266 +- src/gameobjects/shader/Shader.js | 2434 +- .../shader/ShaderCanvasRenderer.js | 46 +- src/gameobjects/shader/ShaderCreator.js | 94 +- src/gameobjects/shader/ShaderFactory.js | 70 +- src/gameobjects/shader/ShaderRender.js | 50 +- src/gameobjects/shader/ShaderWebGLRenderer.js | 156 +- src/gameobjects/shape/FillPathWebGL.js | 116 +- src/gameobjects/shape/FillStyleCanvas.js | 62 +- src/gameobjects/shape/LineStyleCanvas.js | 64 +- src/gameobjects/shape/Shape.js | 588 +- src/gameobjects/shape/StrokePathWebGL.js | 138 +- src/gameobjects/shape/arc/Arc.js | 806 +- .../shape/arc/ArcCanvasRenderer.js | 140 +- src/gameobjects/shape/arc/ArcFactory.js | 134 +- src/gameobjects/shape/arc/ArcRender.js | 50 +- src/gameobjects/shape/arc/ArcWebGLRenderer.js | 144 +- src/gameobjects/shape/curve/Curve.js | 352 +- .../shape/curve/CurveCanvasRenderer.js | 164 +- src/gameobjects/shape/curve/CurveFactory.js | 88 +- src/gameobjects/shape/curve/CurveRender.js | 50 +- .../shape/curve/CurveWebGLRenderer.js | 144 +- src/gameobjects/shape/ellipse/Ellipse.js | 362 +- .../shape/ellipse/EllipseCanvasRenderer.js | 158 +- .../shape/ellipse/EllipseFactory.js | 92 +- .../shape/ellipse/EllipseRender.js | 50 +- .../shape/ellipse/EllipseWebGLRenderer.js | 144 +- src/gameobjects/shape/grid/Grid.js | 552 +- .../shape/grid/GridCanvasRenderer.js | 366 +- src/gameobjects/shape/grid/GridFactory.js | 98 +- src/gameobjects/shape/grid/GridRender.js | 50 +- .../shape/grid/GridWebGLRenderer.js | 440 +- src/gameobjects/shape/isobox/IsoBox.js | 418 +- .../shape/isobox/IsoBoxCanvasRenderer.js | 190 +- src/gameobjects/shape/isobox/IsoBoxFactory.js | 90 +- src/gameobjects/shape/isobox/IsoBoxRender.js | 50 +- .../shape/isobox/IsoBoxWebGLRenderer.js | 304 +- .../shape/isotriangle/IsoTriangle.js | 480 +- .../isotriangle/IsoTriangleCanvasRenderer.js | 216 +- .../shape/isotriangle/IsoTriangleFactory.js | 94 +- .../shape/isotriangle/IsoTriangleRender.js | 50 +- .../isotriangle/IsoTriangleWebGLRenderer.js | 342 +- src/gameobjects/shape/line/Line.js | 322 +- .../shape/line/LineCanvasRenderer.js | 102 +- src/gameobjects/shape/line/LineFactory.js | 90 +- src/gameobjects/shape/line/LineRender.js | 50 +- .../shape/line/LineWebGLRenderer.js | 174 +- src/gameobjects/shape/polygon/Polygon.js | 266 +- .../shape/polygon/PolygonCanvasRenderer.js | 158 +- .../shape/polygon/PolygonFactory.js | 94 +- .../shape/polygon/PolygonRender.js | 50 +- .../shape/polygon/PolygonWebGLRenderer.js | 144 +- src/gameobjects/shape/rectangle/Rectangle.js | 212 +- .../rectangle/RectangleCanvasRenderer.js | 136 +- .../shape/rectangle/RectangleFactory.js | 78 +- .../shape/rectangle/RectangleRender.js | 50 +- .../shape/rectangle/RectangleWebGLRenderer.js | 172 +- src/gameobjects/shape/star/Star.js | 564 +- .../shape/star/StarCanvasRenderer.js | 158 +- src/gameobjects/shape/star/StarFactory.js | 92 +- src/gameobjects/shape/star/StarRender.js | 50 +- .../shape/star/StarWebGLRenderer.js | 144 +- src/gameobjects/shape/triangle/Triangle.js | 274 +- .../shape/triangle/TriangleCanvasRenderer.js | 138 +- .../shape/triangle/TriangleFactory.js | 90 +- .../shape/triangle/TriangleRender.js | 50 +- .../shape/triangle/TriangleWebGLRenderer.js | 194 +- src/gameobjects/sprite/Sprite.js | 344 +- .../sprite/SpriteCanvasRenderer.js | 54 +- src/gameobjects/sprite/SpriteCreator.js | 94 +- src/gameobjects/sprite/SpriteFactory.js | 82 +- src/gameobjects/sprite/SpriteRender.js | 50 +- src/gameobjects/sprite/SpriteWebGLRenderer.js | 54 +- src/gameobjects/sprite/typedefs/index.js | 18 +- src/gameobjects/text/GetTextSize.js | 152 +- src/gameobjects/text/MeasureText.js | 258 +- src/gameobjects/text/TextStyle.js | 2094 +- src/gameobjects/text/static/Text.js | 2806 +- .../text/static/TextCanvasRenderer.js | 64 +- src/gameobjects/text/static/TextCreator.js | 162 +- src/gameobjects/text/static/TextFactory.js | 118 +- src/gameobjects/text/static/TextRender.js | 50 +- .../text/static/TextWebGLRenderer.js | 118 +- src/gameobjects/text/typedefs/index.js | 18 +- src/gameobjects/tilesprite/TileSprite.js | 1292 +- .../tilesprite/TileSpriteCanvasRenderer.js | 58 +- .../tilesprite/TileSpriteCreator.js | 92 +- .../tilesprite/TileSpriteFactory.js | 76 +- .../tilesprite/TileSpriteRender.js | 50 +- .../tilesprite/TileSpriteWebGLRenderer.js | 108 +- src/gameobjects/tilesprite/typedefs/index.js | 18 +- src/gameobjects/typedefs/index.js | 18 +- src/gameobjects/video/Video.js | 3526 +- src/gameobjects/video/VideoCanvasRenderer.js | 60 +- src/gameobjects/video/VideoCreator.js | 86 +- src/gameobjects/video/VideoFactory.js | 82 +- src/gameobjects/video/VideoRender.js | 50 +- src/gameobjects/video/VideoWebGLRenderer.js | 60 +- src/gameobjects/zone/Zone.js | 614 +- src/gameobjects/zone/ZoneCreator.js | 66 +- src/gameobjects/zone/ZoneFactory.js | 72 +- src/geom/circle/Area.js | 44 +- src/geom/circle/Circle.js | 738 +- src/geom/circle/Circumference.js | 44 +- src/geom/circle/CircumferencePoint.js | 66 +- src/geom/circle/Clone.js | 48 +- src/geom/circle/Contains.js | 70 +- src/geom/circle/ContainsPoint.js | 50 +- src/geom/circle/ContainsRect.js | 60 +- src/geom/circle/CopyFrom.js | 52 +- src/geom/circle/Equals.js | 56 +- src/geom/circle/GetBounds.js | 68 +- src/geom/circle/GetPoint.js | 74 +- src/geom/circle/GetPoints.js | 92 +- src/geom/circle/Offset.js | 58 +- src/geom/circle/OffsetPoint.js | 56 +- src/geom/circle/Random.js | 76 +- src/geom/circle/index.js | 50 +- src/geom/const.js | 148 +- src/geom/ellipse/Area.js | 56 +- src/geom/ellipse/Circumference.js | 52 +- src/geom/ellipse/CircumferencePoint.js | 72 +- src/geom/ellipse/Clone.js | 48 +- src/geom/ellipse/Contains.js | 72 +- src/geom/ellipse/ContainsPoint.js | 50 +- src/geom/ellipse/ContainsRect.js | 60 +- src/geom/ellipse/CopyFrom.js | 52 +- src/geom/ellipse/Ellipse.js | 752 +- src/geom/ellipse/Equals.js | 58 +- src/geom/ellipse/GetBounds.js | 68 +- src/geom/ellipse/GetPoint.js | 74 +- src/geom/ellipse/GetPoints.js | 96 +- src/geom/ellipse/Offset.js | 58 +- src/geom/ellipse/OffsetPoint.js | 56 +- src/geom/ellipse/Random.js | 70 +- src/geom/ellipse/index.js | 50 +- src/geom/index.js | 60 +- src/geom/intersects/CircleToCircle.js | 50 +- src/geom/intersects/CircleToRectangle.js | 96 +- src/geom/intersects/GetCircleToCircle.js | 176 +- src/geom/intersects/GetCircleToRectangle.js | 88 +- src/geom/intersects/GetLineToCircle.js | 172 +- src/geom/intersects/GetLineToRectangle.js | 108 +- .../intersects/GetRectangleIntersection.js | 86 +- .../intersects/GetRectangleToRectangle.js | 90 +- src/geom/intersects/GetRectangleToTriangle.js | 84 +- src/geom/intersects/GetTriangleToCircle.js | 86 +- src/geom/intersects/GetTriangleToLine.js | 106 +- src/geom/intersects/GetTriangleToTriangle.js | 86 +- src/geom/intersects/LineToCircle.js | 156 +- src/geom/intersects/LineToLine.js | 140 +- src/geom/intersects/LineToRectangle.js | 190 +- src/geom/intersects/PointToLine.js | 128 +- src/geom/intersects/PointToLineSegment.js | 70 +- src/geom/intersects/RectangleToRectangle.js | 64 +- src/geom/intersects/RectangleToTriangle.js | 174 +- src/geom/intersects/RectangleToValues.js | 68 +- src/geom/intersects/TriangleToCircle.js | 118 +- src/geom/intersects/TriangleToLine.js | 100 +- src/geom/intersects/TriangleToTriangle.js | 168 +- src/geom/intersects/index.js | 74 +- src/geom/line/Angle.js | 44 +- src/geom/line/BresenhamPoints.js | 136 +- src/geom/line/CenterOn.js | 68 +- src/geom/line/Clone.js | 48 +- src/geom/line/CopyFrom.js | 50 +- src/geom/line/Equals.js | 56 +- src/geom/line/Extend.js | 104 +- src/geom/line/GetEasedPoints.js | 228 +- src/geom/line/GetMidPoint.js | 64 +- src/geom/line/GetNearestPoint.js | 98 +- src/geom/line/GetNormal.js | 76 +- src/geom/line/GetPoint.js | 66 +- src/geom/line/GetPoints.js | 118 +- src/geom/line/GetShortestDistance.js | 82 +- src/geom/line/Height.js | 44 +- src/geom/line/Length.js | 44 +- src/geom/line/Line.js | 662 +- src/geom/line/NormalAngle.js | 56 +- src/geom/line/NormalX.js | 50 +- src/geom/line/NormalY.js | 52 +- src/geom/line/Offset.js | 64 +- src/geom/line/PerpSlope.js | 44 +- src/geom/line/Random.js | 68 +- src/geom/line/ReflectAngle.js | 56 +- src/geom/line/Rotate.js | 60 +- src/geom/line/RotateAroundPoint.js | 56 +- src/geom/line/RotateAroundXY.js | 84 +- src/geom/line/SetToAngle.js | 68 +- src/geom/line/Slope.js | 44 +- src/geom/line/Width.js | 44 +- src/geom/line/index.js | 78 +- src/geom/point/Ceil.js | 48 +- src/geom/point/Clone.js | 48 +- src/geom/point/CopyFrom.js | 50 +- src/geom/point/Equals.js | 46 +- src/geom/point/Floor.js | 48 +- src/geom/point/GetCentroid.js | 116 +- src/geom/point/GetMagnitude.js | 44 +- src/geom/point/GetMagnitudeSq.js | 44 +- src/geom/point/GetRectangleFromPoints.js | 128 +- src/geom/point/Interpolate.js | 70 +- src/geom/point/Invert.js | 48 +- src/geom/point/Negative.js | 58 +- src/geom/point/Point.js | 174 +- src/geom/point/Project.js | 82 +- src/geom/point/ProjectUnit.js | 78 +- src/geom/point/SetMagnitude.js | 76 +- src/geom/point/index.js | 50 +- src/geom/polygon/Clone.js | 48 +- src/geom/polygon/Contains.js | 86 +- src/geom/polygon/ContainsPoint.js | 50 +- src/geom/polygon/Earcut.js | 1350 +- src/geom/polygon/GetAABB.js | 100 +- src/geom/polygon/GetNumberArray.js | 74 +- src/geom/polygon/GetPoints.js | 142 +- src/geom/polygon/Perimeter.js | 84 +- src/geom/polygon/Polygon.js | 456 +- src/geom/polygon/Reverse.js | 52 +- src/geom/polygon/Smooth.js | 140 +- src/geom/polygon/index.js | 38 +- src/geom/rectangle/Area.js | 44 +- src/geom/rectangle/Ceil.js | 54 +- src/geom/rectangle/CeilAll.js | 58 +- src/geom/rectangle/CenterOn.js | 62 +- src/geom/rectangle/Clone.js | 48 +- src/geom/rectangle/Contains.js | 58 +- src/geom/rectangle/ContainsPoint.js | 50 +- src/geom/rectangle/ContainsRect.js | 68 +- src/geom/rectangle/CopyFrom.js | 50 +- src/geom/rectangle/Decompose.js | 62 +- src/geom/rectangle/Equals.js | 56 +- src/geom/rectangle/FitInside.js | 94 +- src/geom/rectangle/FitOutside.js | 94 +- src/geom/rectangle/Floor.js | 54 +- src/geom/rectangle/FloorAll.js | 58 +- src/geom/rectangle/FromPoints.js | 160 +- src/geom/rectangle/GetAspectRatio.js | 44 +- src/geom/rectangle/GetCenter.js | 64 +- src/geom/rectangle/GetPoint.js | 150 +- src/geom/rectangle/GetPoints.js | 96 +- src/geom/rectangle/GetSize.js | 68 +- src/geom/rectangle/Inflate.js | 72 +- src/geom/rectangle/Intersection.js | 90 +- src/geom/rectangle/MarchingAnts.js | 226 +- src/geom/rectangle/MergePoints.js | 86 +- src/geom/rectangle/MergeRect.js | 82 +- src/geom/rectangle/MergeXY.js | 76 +- src/geom/rectangle/Offset.js | 58 +- src/geom/rectangle/OffsetPoint.js | 56 +- src/geom/rectangle/Overlaps.js | 56 +- src/geom/rectangle/Perimeter.js | 44 +- src/geom/rectangle/PerimeterPoint.js | 102 +- src/geom/rectangle/Random.js | 64 +- src/geom/rectangle/RandomOutside.js | 130 +- src/geom/rectangle/Rectangle.js | 1010 +- src/geom/rectangle/SameDimensions.js | 46 +- src/geom/rectangle/Scale.js | 66 +- src/geom/rectangle/Union.js | 72 +- src/geom/rectangle/index.js | 94 +- src/geom/triangle/Area.js | 66 +- src/geom/triangle/BuildEquilateral.js | 76 +- src/geom/triangle/BuildFromPolygon.js | 140 +- src/geom/triangle/BuildRight.js | 86 +- src/geom/triangle/CenterOn.js | 94 +- src/geom/triangle/Centroid.js | 76 +- src/geom/triangle/CircumCenter.js | 140 +- src/geom/triangle/CircumCircle.js | 154 +- src/geom/triangle/Clone.js | 48 +- src/geom/triangle/Contains.js | 94 +- src/geom/triangle/ContainsArray.js | 162 +- src/geom/triangle/ContainsPoint.js | 50 +- src/geom/triangle/CopyFrom.js | 50 +- src/geom/triangle/Decompose.js | 58 +- src/geom/triangle/Equals.js | 60 +- src/geom/triangle/GetPoint.js | 162 +- src/geom/triangle/GetPoints.js | 174 +- src/geom/triangle/InCenter.js | 118 +- src/geom/triangle/Offset.js | 70 +- src/geom/triangle/Perimeter.js | 58 +- src/geom/triangle/Random.js | 100 +- src/geom/triangle/Rotate.js | 60 +- src/geom/triangle/RotateAroundPoint.js | 56 +- src/geom/triangle/RotateAroundXY.js | 96 +- src/geom/triangle/Triangle.js | 882 +- src/geom/triangle/index.js | 68 +- src/input/CreateInteractiveObject.js | 130 +- src/input/CreatePixelPerfectHandler.js | 60 +- src/input/InputManager.js | 2152 +- src/input/InputPlugin.js | 6292 +- src/input/InputPluginCache.js | 204 +- src/input/Pointer.js | 2544 +- src/input/const.js | 184 +- src/input/events/BOOT_EVENT.js | 30 +- src/input/events/DESTROY_EVENT.js | 30 +- src/input/events/DRAG_END_EVENT.js | 44 +- src/input/events/DRAG_ENTER_EVENT.js | 50 +- src/input/events/DRAG_EVENT.js | 52 +- src/input/events/DRAG_LEAVE_EVENT.js | 50 +- src/input/events/DRAG_OVER_EVENT.js | 56 +- src/input/events/DRAG_START_EVENT.js | 48 +- src/input/events/DROP_EVENT.js | 46 +- src/input/events/GAMEOBJECT_DOWN_EVENT.js | 70 +- src/input/events/GAMEOBJECT_DRAG_END_EVENT.js | 50 +- .../events/GAMEOBJECT_DRAG_ENTER_EVENT.js | 48 +- src/input/events/GAMEOBJECT_DRAG_EVENT.js | 50 +- .../events/GAMEOBJECT_DRAG_LEAVE_EVENT.js | 48 +- .../events/GAMEOBJECT_DRAG_OVER_EVENT.js | 54 +- .../events/GAMEOBJECT_DRAG_START_EVENT.js | 56 +- src/input/events/GAMEOBJECT_DROP_EVENT.js | 48 +- src/input/events/GAMEOBJECT_MOVE_EVENT.js | 70 +- src/input/events/GAMEOBJECT_OUT_EVENT.js | 70 +- src/input/events/GAMEOBJECT_OVER_EVENT.js | 70 +- .../events/GAMEOBJECT_POINTER_DOWN_EVENT.js | 70 +- .../events/GAMEOBJECT_POINTER_MOVE_EVENT.js | 70 +- .../events/GAMEOBJECT_POINTER_OUT_EVENT.js | 66 +- .../events/GAMEOBJECT_POINTER_OVER_EVENT.js | 70 +- .../events/GAMEOBJECT_POINTER_UP_EVENT.js | 70 +- .../events/GAMEOBJECT_POINTER_WHEEL_EVENT.js | 72 +- src/input/events/GAMEOBJECT_UP_EVENT.js | 70 +- src/input/events/GAMEOBJECT_WHEEL_EVENT.js | 76 +- src/input/events/GAME_OUT_EVENT.js | 42 +- src/input/events/GAME_OVER_EVENT.js | 42 +- src/input/events/MANAGER_BOOT_EVENT.js | 30 +- src/input/events/MANAGER_PROCESS_EVENT.js | 38 +- src/input/events/MANAGER_UPDATE_EVENT.js | 30 +- src/input/events/POINTERLOCK_CHANGE_EVENT.js | 36 +- src/input/events/POINTER_DOWN_EVENT.js | 58 +- .../events/POINTER_DOWN_OUTSIDE_EVENT.js | 56 +- src/input/events/POINTER_MOVE_EVENT.js | 58 +- src/input/events/POINTER_OUT_EVENT.js | 58 +- src/input/events/POINTER_OVER_EVENT.js | 58 +- src/input/events/POINTER_UP_EVENT.js | 58 +- src/input/events/POINTER_UP_OUTSIDE_EVENT.js | 56 +- src/input/events/POINTER_WHEEL_EVENT.js | 64 +- src/input/events/PRE_UPDATE_EVENT.js | 32 +- src/input/events/SHUTDOWN_EVENT.js | 30 +- src/input/events/START_EVENT.js | 32 +- src/input/events/UPDATE_EVENT.js | 38 +- src/input/events/index.js | 120 +- src/input/gamepad/Axis.js | 238 +- src/input/gamepad/Button.js | 280 +- src/input/gamepad/Gamepad.js | 1504 +- src/input/gamepad/GamepadPlugin.js | 1264 +- .../gamepad/configs/SNES_USB_Controller.js | 66 +- .../configs/Sony_PlayStation_DualShock_4.js | 88 +- .../gamepad/configs/XBox360_Controller.js | 90 +- src/input/gamepad/configs/index.js | 34 +- src/input/gamepad/events/BUTTON_DOWN_EVENT.js | 46 +- src/input/gamepad/events/BUTTON_UP_EVENT.js | 46 +- src/input/gamepad/events/CONNECTED_EVENT.js | 50 +- .../gamepad/events/DISCONNECTED_EVENT.js | 40 +- .../events/GAMEPAD_BUTTON_DOWN_EVENT.js | 52 +- .../gamepad/events/GAMEPAD_BUTTON_UP_EVENT.js | 52 +- src/input/gamepad/events/index.js | 40 +- src/input/gamepad/index.js | 40 +- src/input/gamepad/typedefs/index.js | 18 +- src/input/index.js | 64 +- src/input/keyboard/KeyboardManager.js | 888 +- src/input/keyboard/KeyboardPlugin.js | 1760 +- src/input/keyboard/combo/AdvanceKeyCombo.js | 72 +- src/input/keyboard/combo/KeyCombo.js | 574 +- src/input/keyboard/combo/ProcessKeyCombo.js | 150 +- src/input/keyboard/combo/ResetKeyCombo.js | 58 +- .../keyboard/events/ANY_KEY_DOWN_EVENT.js | 60 +- src/input/keyboard/events/ANY_KEY_UP_EVENT.js | 46 +- .../keyboard/events/COMBO_MATCH_EVENT.js | 56 +- src/input/keyboard/events/DOWN_EVENT.js | 56 +- src/input/keyboard/events/KEY_DOWN_EVENT.js | 66 +- src/input/keyboard/events/KEY_UP_EVENT.js | 52 +- src/input/keyboard/events/UP_EVENT.js | 56 +- src/input/keyboard/events/index.js | 42 +- src/input/keyboard/index.js | 56 +- src/input/keyboard/keys/DownDuration.js | 56 +- src/input/keyboard/keys/JustDown.js | 72 +- src/input/keyboard/keys/JustUp.js | 72 +- src/input/keyboard/keys/Key.js | 792 +- src/input/keyboard/keys/KeyCodes.js | 1800 +- src/input/keyboard/keys/KeyMap.js | 32 +- src/input/keyboard/keys/UpDuration.js | 56 +- src/input/keyboard/typedefs/index.js | 18 +- src/input/mouse/MouseManager.js | 960 +- src/input/mouse/index.js | 34 +- src/input/touch/TouchManager.js | 814 +- src/input/touch/index.js | 34 +- src/input/typedefs/EventData.js | 34 +- src/input/typedefs/index.js | 18 +- src/loader/File.js | 1070 +- src/loader/FileTypesManager.js | 126 +- src/loader/GetURL.js | 70 +- src/loader/LoaderPlugin.js | 2144 +- src/loader/MergeXHRSettings.js | 84 +- src/loader/MultiFile.js | 456 +- src/loader/XHRLoader.js | 134 +- src/loader/XHRSettings.js | 126 +- src/loader/const.js | 292 +- src/loader/events/ADD_EVENT.js | 48 +- src/loader/events/COMPLETE_EVENT.js | 44 +- src/loader/events/FILE_COMPLETE_EVENT.js | 46 +- src/loader/events/FILE_KEY_COMPLETE_EVENT.js | 96 +- src/loader/events/FILE_LOAD_ERROR_EVENT.js | 38 +- src/loader/events/FILE_LOAD_EVENT.js | 40 +- src/loader/events/FILE_PROGRESS_EVENT.js | 42 +- src/loader/events/POST_PROCESS_EVENT.js | 46 +- src/loader/events/PROGRESS_EVENT.js | 38 +- src/loader/events/START_EVENT.js | 42 +- src/loader/events/index.js | 48 +- src/loader/filetypes/AnimationJSONFile.js | 394 +- src/loader/filetypes/AtlasJSONFile.js | 486 +- src/loader/filetypes/AtlasXMLFile.js | 474 +- src/loader/filetypes/AudioFile.js | 530 +- src/loader/filetypes/AudioSpriteFile.js | 568 +- src/loader/filetypes/BinaryFile.js | 352 +- src/loader/filetypes/BitmapFontFile.js | 474 +- src/loader/filetypes/CSSFile.js | 324 +- src/loader/filetypes/GLSLFile.js | 810 +- src/loader/filetypes/HTML5AudioFile.js | 384 +- src/loader/filetypes/HTMLFile.js | 338 +- src/loader/filetypes/HTMLTextureFile.js | 504 +- src/loader/filetypes/ImageFile.js | 536 +- src/loader/filetypes/JSONFile.js | 448 +- src/loader/filetypes/MultiAtlasFile.js | 654 +- src/loader/filetypes/MultiScriptFile.js | 422 +- src/loader/filetypes/PackFile.js | 424 +- src/loader/filetypes/PluginFile.js | 412 +- src/loader/filetypes/SVGFile.js | 666 +- src/loader/filetypes/SceneFile.js | 430 +- src/loader/filetypes/ScenePluginFile.js | 400 +- src/loader/filetypes/ScriptFile.js | 330 +- src/loader/filetypes/SpriteSheetFile.js | 370 +- src/loader/filetypes/TextFile.js | 338 +- src/loader/filetypes/TilemapCSVFile.js | 378 +- src/loader/filetypes/TilemapImpactFile.js | 300 +- src/loader/filetypes/TilemapJSONFile.js | 300 +- src/loader/filetypes/UnityAtlasFile.js | 472 +- src/loader/filetypes/VideoFile.js | 770 +- src/loader/filetypes/XMLFile.js | 358 +- src/loader/filetypes/index.js | 88 +- .../typedefs/MultiAtlasFileConfig.js | 24 +- src/loader/filetypes/typedefs/index.js | 18 +- src/loader/index.js | 68 +- src/loader/typedefs/XHRSettingsObject.js | 30 +- src/loader/typedefs/index.js | 18 +- src/math/Average.js | 58 +- src/math/Bernstein.js | 50 +- src/math/Between.js | 46 +- src/math/CatmullRom.js | 62 +- src/math/CeilTo.js | 62 +- src/math/Clamp.js | 48 +- src/math/DegToRad.js | 48 +- src/math/Difference.js | 46 +- src/math/Factorial.js | 68 +- src/math/FloatBetween.js | 46 +- src/math/FloorTo.js | 62 +- src/math/FromPercent.js | 56 +- src/math/GetSpeed.js | 54 +- src/math/IsEven.js | 50 +- src/math/IsEvenStrict.js | 46 +- src/math/Linear.js | 48 +- src/math/Matrix3.js | 1174 +- src/math/Matrix4.js | 2912 +- src/math/MaxAdd.js | 48 +- src/math/MinSub.js | 48 +- src/math/Percent.js | 106 +- src/math/Quaternion.js | 1532 +- src/math/RadToDeg.js | 48 +- src/math/RandomXY.js | 68 +- src/math/RandomXYZ.js | 66 +- src/math/RandomXYZW.js | 62 +- src/math/Rotate.js | 58 +- src/math/RotateAround.js | 68 +- src/math/RotateAroundDistance.js | 62 +- src/math/RotateVec3.js | 84 +- src/math/RoundAwayFromZero.js | 46 +- src/math/RoundTo.js | 92 +- src/math/SinCosTableGenerator.js | 94 +- src/math/SmoothStep.js | 82 +- src/math/SmootherStep.js | 66 +- src/math/ToXY.js | 104 +- src/math/TransformXY.js | 98 +- src/math/Vector2.js | 1266 +- src/math/Vector3.js | 1608 +- src/math/Vector4.js | 1078 +- src/math/Within.js | 48 +- src/math/Wrap.js | 52 +- src/math/angle/Between.js | 50 +- src/math/angle/BetweenPoints.js | 50 +- src/math/angle/BetweenPointsY.js | 52 +- src/math/angle/BetweenY.js | 56 +- src/math/angle/CounterClockwise.js | 78 +- src/math/angle/Normalize.js | 62 +- src/math/angle/Reverse.js | 48 +- src/math/angle/RotateTo.js | 122 +- src/math/angle/ShortestBetween.js | 86 +- src/math/angle/Wrap.js | 52 +- src/math/angle/WrapDegrees.js | 52 +- src/math/angle/index.js | 50 +- src/math/const.js | 172 +- src/math/distance/DistanceBetween.js | 56 +- src/math/distance/DistanceBetweenPoints.js | 52 +- .../distance/DistanceBetweenPointsSquared.js | 52 +- src/math/distance/DistanceChebyshev.js | 56 +- src/math/distance/DistancePower.js | 56 +- src/math/distance/DistanceSnake.js | 56 +- src/math/distance/DistanceSquared.js | 56 +- src/math/distance/index.js | 42 +- src/math/easing/EaseMap.js | 150 +- src/math/easing/back/In.js | 50 +- src/math/easing/back/InOut.js | 68 +- src/math/easing/back/Out.js | 50 +- src/math/easing/back/index.js | 34 +- src/math/easing/bounce/In.js | 78 +- src/math/easing/bounce/InOut.js | 116 +- src/math/easing/bounce/Out.js | 74 +- src/math/easing/bounce/index.js | 34 +- src/math/easing/circular/In.js | 44 +- src/math/easing/circular/InOut.js | 58 +- src/math/easing/circular/Out.js | 44 +- src/math/easing/circular/index.js | 34 +- src/math/easing/cubic/In.js | 44 +- src/math/easing/cubic/InOut.js | 58 +- src/math/easing/cubic/Out.js | 44 +- src/math/easing/cubic/index.js | 34 +- src/math/easing/elastic/In.js | 98 +- src/math/easing/elastic/InOut.js | 112 +- src/math/easing/elastic/Out.js | 98 +- src/math/easing/elastic/index.js | 34 +- src/math/easing/expo/In.js | 44 +- src/math/easing/expo/InOut.js | 58 +- src/math/easing/expo/Out.js | 44 +- src/math/easing/expo/index.js | 34 +- src/math/easing/index.js | 52 +- src/math/easing/linear/Linear.js | 44 +- src/math/easing/linear/index.js | 22 +- src/math/easing/quadratic/In.js | 44 +- src/math/easing/quadratic/InOut.js | 58 +- src/math/easing/quadratic/Out.js | 44 +- src/math/easing/quadratic/index.js | 34 +- src/math/easing/quartic/In.js | 44 +- src/math/easing/quartic/InOut.js | 58 +- src/math/easing/quartic/Out.js | 44 +- src/math/easing/quartic/index.js | 34 +- src/math/easing/quintic/In.js | 44 +- src/math/easing/quintic/InOut.js | 58 +- src/math/easing/quintic/Out.js | 44 +- src/math/easing/quintic/index.js | 34 +- src/math/easing/sine/In.js | 66 +- src/math/easing/sine/InOut.js | 66 +- src/math/easing/sine/Out.js | 66 +- src/math/easing/sine/index.js | 34 +- src/math/easing/stepped/Stepped.js | 72 +- src/math/easing/stepped/index.js | 22 +- src/math/fuzzy/Ceil.js | 50 +- src/math/fuzzy/Equal.js | 56 +- src/math/fuzzy/Floor.js | 50 +- src/math/fuzzy/GreaterThan.js | 56 +- src/math/fuzzy/LessThan.js | 56 +- src/math/fuzzy/index.js | 38 +- src/math/index.js | 164 +- src/math/interpolation/BezierInterpolation.js | 66 +- .../interpolation/CatmullRomInterpolation.js | 102 +- .../interpolation/CubicBezierInterpolation.js | 128 +- src/math/interpolation/LinearInterpolation.js | 82 +- .../QuadraticBezierInterpolation.js | 106 +- .../interpolation/SmoothStepInterpolation.js | 54 +- .../SmootherStepInterpolation.js | 54 +- src/math/interpolation/index.js | 42 +- src/math/pow2/GetPowerOfTwo.js | 48 +- src/math/pow2/IsSizePowerOfTwo.js | 48 +- src/math/pow2/IsValuePowerOfTwo.js | 44 +- src/math/pow2/index.js | 34 +- .../RandomDataGenerator.js | 1008 +- src/math/snap/SnapCeil.js | 76 +- src/math/snap/SnapFloor.js | 76 +- src/math/snap/SnapTo.js | 74 +- src/math/snap/index.js | 34 +- src/math/typedefs/index.js | 18 +- src/phaser-arcade-physics.js | 156 +- src/phaser-core.js | 246 +- src/phaser.js | 188 +- src/physics/arcade/ArcadeImage.js | 188 +- src/physics/arcade/ArcadePhysics.js | 1366 +- src/physics/arcade/ArcadeSprite.js | 190 +- src/physics/arcade/Body.js | 4658 +- src/physics/arcade/Collider.js | 354 +- src/physics/arcade/Factory.js | 530 +- src/physics/arcade/GetOverlapX.js | 204 +- src/physics/arcade/GetOverlapY.js | 204 +- src/physics/arcade/PhysicsGroup.js | 558 +- src/physics/arcade/SeparateX.js | 170 +- src/physics/arcade/SeparateY.js | 170 +- src/physics/arcade/StaticBody.js | 1966 +- src/physics/arcade/StaticPhysicsGroup.js | 370 +- src/physics/arcade/World.js | 4766 +- src/physics/arcade/components/Acceleration.js | 138 +- src/physics/arcade/components/Angular.js | 152 +- src/physics/arcade/components/Bounce.js | 186 +- src/physics/arcade/components/Debug.js | 242 +- src/physics/arcade/components/Drag.js | 254 +- src/physics/arcade/components/Enable.js | 236 +- src/physics/arcade/components/Friction.js | 144 +- src/physics/arcade/components/Gravity.js | 144 +- src/physics/arcade/components/Immovable.js | 72 +- src/physics/arcade/components/Mass.js | 68 +- src/physics/arcade/components/Size.js | 152 +- src/physics/arcade/components/Velocity.js | 186 +- src/physics/arcade/components/index.js | 52 +- src/physics/arcade/const.js | 246 +- src/physics/arcade/events/COLLIDE_EVENT.js | 54 +- src/physics/arcade/events/OVERLAP_EVENT.js | 54 +- src/physics/arcade/events/PAUSE_EVENT.js | 34 +- src/physics/arcade/events/RESUME_EVENT.js | 34 +- .../arcade/events/TILE_COLLIDE_EVENT.js | 52 +- .../arcade/events/TILE_OVERLAP_EVENT.js | 52 +- .../arcade/events/WORLD_BOUNDS_EVENT.js | 52 +- src/physics/arcade/events/WORLD_STEP_EVENT.js | 40 +- src/physics/arcade/events/index.js | 44 +- src/physics/arcade/index.js | 82 +- .../arcade/tilemap/ProcessTileCallbacks.js | 70 +- .../arcade/tilemap/ProcessTileSeparationX.js | 82 +- .../arcade/tilemap/ProcessTileSeparationY.js | 82 +- src/physics/arcade/tilemap/SeparateTile.js | 228 +- src/physics/arcade/tilemap/TileCheckX.js | 168 +- src/physics/arcade/tilemap/TileCheckY.js | 168 +- .../arcade/tilemap/TileIntersectsBody.js | 60 +- src/physics/arcade/typedefs/index.js | 18 +- src/physics/index.js | 40 +- src/physics/matter-js/BodyBounds.js | 800 +- src/physics/matter-js/CustomMain.js | 102 +- src/physics/matter-js/Factory.js | 1848 +- src/physics/matter-js/MatterGameObject.js | 240 +- src/physics/matter-js/MatterImage.js | 260 +- src/physics/matter-js/MatterPhysics.js | 2926 +- src/physics/matter-js/MatterSprite.js | 272 +- src/physics/matter-js/MatterTileBody.js | 628 +- src/physics/matter-js/PhysicsEditorParser.js | 272 +- src/physics/matter-js/PhysicsJSONParser.js | 222 +- src/physics/matter-js/PointerConstraint.js | 764 +- src/physics/matter-js/World.js | 4430 +- src/physics/matter-js/components/Bounce.js | 68 +- src/physics/matter-js/components/Collision.js | 360 +- src/physics/matter-js/components/Force.js | 300 +- src/physics/matter-js/components/Friction.js | 168 +- src/physics/matter-js/components/Gravity.js | 68 +- src/physics/matter-js/components/Mass.js | 152 +- src/physics/matter-js/components/Sensor.js | 96 +- src/physics/matter-js/components/SetBody.js | 568 +- src/physics/matter-js/components/Sleep.js | 296 +- src/physics/matter-js/components/Static.js | 98 +- src/physics/matter-js/components/Transform.js | 618 +- src/physics/matter-js/components/Velocity.js | 190 +- src/physics/matter-js/components/index.js | 52 +- .../matter-js/events/AFTER_ADD_EVENT.js | 56 +- .../matter-js/events/AFTER_REMOVE_EVENT.js | 56 +- .../matter-js/events/AFTER_UPDATE_EVENT.js | 54 +- .../matter-js/events/BEFORE_ADD_EVENT.js | 56 +- .../matter-js/events/BEFORE_REMOVE_EVENT.js | 56 +- .../matter-js/events/BEFORE_UPDATE_EVENT.js | 54 +- .../events/COLLISION_ACTIVE_EVENT.js | 62 +- .../matter-js/events/COLLISION_END_EVENT.js | 62 +- .../matter-js/events/COLLISION_START_EVENT.js | 62 +- .../matter-js/events/DRAG_END_EVENT.js | 42 +- src/physics/matter-js/events/DRAG_EVENT.js | 42 +- .../matter-js/events/DRAG_START_EVENT.js | 44 +- src/physics/matter-js/events/PAUSE_EVENT.js | 34 +- src/physics/matter-js/events/RESUME_EVENT.js | 34 +- .../matter-js/events/SLEEP_END_EVENT.js | 54 +- .../matter-js/events/SLEEP_START_EVENT.js | 54 +- src/physics/matter-js/events/index.js | 60 +- src/physics/matter-js/index.js | 50 +- src/physics/matter-js/lib/body/Body.js | 2752 +- src/physics/matter-js/lib/body/Composite.js | 1376 +- src/physics/matter-js/lib/core/Engine.js | 974 +- src/physics/matter-js/typedefs/MatterBody.js | 8 +- .../matter-js/typedefs/MatterBodyConfig.js | 74 +- .../typedefs/MatterBodyRenderConfig.js | 30 +- .../matter-js/typedefs/MatterChamferConfig.js | 18 +- .../matter-js/typedefs/MatterCollisionData.js | 44 +- .../typedefs/MatterCollisionFilter.js | 58 +- .../matter-js/typedefs/MatterCollisionPair.js | 42 +- .../typedefs/MatterConstraintConfig.js | 36 +- .../typedefs/MatterConstraintRenderConfig.js | 26 +- .../matter-js/typedefs/MatterDebugConfig.js | 102 +- .../matter-js/typedefs/MatterSetBodyConfig.js | 38 +- .../matter-js/typedefs/MatterTileOptions.js | 16 +- .../matter-js/typedefs/MatterWorldConfig.js | 72 +- src/physics/matter-js/typedefs/index.js | 18 +- src/plugins/BasePlugin.js | 248 +- src/plugins/DefaultPlugins.js | 198 +- src/plugins/PluginCache.js | 406 +- src/plugins/PluginManager.js | 1792 +- src/plugins/ScenePlugin.js | 244 +- src/plugins/index.js | 38 +- src/plugins/typedefs/index.js | 18 +- src/renderer/BlendModes.js | 666 +- src/renderer/ScaleModes.js | 96 +- src/renderer/canvas/CanvasRenderer.js | 1582 +- src/renderer/canvas/index.js | 34 +- src/renderer/canvas/utils/GetBlendModes.js | 116 +- src/renderer/canvas/utils/SetTransform.js | 164 +- src/renderer/index.js | 42 +- src/renderer/snapshot/CanvasSnapshot.js | 174 +- src/renderer/snapshot/WebGLSnapshot.js | 208 +- src/renderer/snapshot/index.js | 32 +- src/renderer/snapshot/typedefs/index.js | 18 +- src/renderer/webgl/Utils.js | 258 +- src/renderer/webgl/WebGLPipeline.js | 1526 +- src/renderer/webgl/WebGLRenderer.js | 5966 +- src/renderer/webgl/index.js | 50 +- .../webgl/pipelines/BitmapMaskPipeline.js | 518 +- .../pipelines/ForwardDiffuseLightPipeline.js | 1030 +- .../webgl/pipelines/TextureTintPipeline.js | 3004 +- .../pipelines/TextureTintStripPipeline.js | 808 +- .../components/ModelViewProjection.js | 1488 +- src/renderer/webgl/pipelines/index.js | 38 +- src/scale/ScaleManager.js | 3422 +- src/scale/const/CENTER_CONST.js | 160 +- src/scale/const/ORIENTATION_CONST.js | 94 +- src/scale/const/SCALE_MODE_CONST.js | 184 +- src/scale/const/ZOOM_CONST.js | 136 +- src/scale/const/index.js | 32 +- src/scale/events/ENTER_FULLSCREEN_EVENT.js | 26 +- src/scale/events/FULLSCREEN_FAILED_EVENT.js | 26 +- .../events/FULLSCREEN_UNSUPPORTED_EVENT.js | 26 +- src/scale/events/LEAVE_FULLSCREEN_EVENT.js | 28 +- src/scale/events/ORIENTATION_CHANGE_EVENT.js | 30 +- src/scale/events/RESIZE_EVENT.js | 50 +- src/scale/events/index.js | 40 +- src/scale/index.js | 100 +- src/scene/GetPhysicsPlugins.js | 112 +- src/scene/GetScenePlugins.js | 82 +- src/scene/InjectionMap.js | 118 +- src/scene/Scene.js | 580 +- src/scene/SceneManager.js | 3268 +- src/scene/ScenePlugin.js | 2008 +- src/scene/Settings.js | 180 +- src/scene/Systems.js | 1554 +- src/scene/const.js | 234 +- src/scene/events/BOOT_EVENT.js | 38 +- src/scene/events/CREATE_EVENT.js | 46 +- src/scene/events/DESTROY_EVENT.js | 42 +- src/scene/events/PAUSE_EVENT.js | 42 +- src/scene/events/POST_UPDATE_EVENT.js | 62 +- src/scene/events/PRE_UPDATE_EVENT.js | 62 +- src/scene/events/READY_EVENT.js | 44 +- src/scene/events/RENDER_EVENT.js | 60 +- src/scene/events/RESUME_EVENT.js | 42 +- src/scene/events/SHUTDOWN_EVENT.js | 48 +- src/scene/events/SLEEP_EVENT.js | 42 +- src/scene/events/START_EVENT.js | 38 +- src/scene/events/TRANSITION_COMPLETE_EVENT.js | 60 +- src/scene/events/TRANSITION_INIT_EVENT.js | 62 +- src/scene/events/TRANSITION_OUT_EVENT.js | 56 +- src/scene/events/TRANSITION_START_EVENT.js | 68 +- src/scene/events/TRANSITION_WAKE_EVENT.js | 58 +- src/scene/events/UPDATE_EVENT.js | 62 +- src/scene/events/WAKE_EVENT.js | 42 +- src/scene/events/index.js | 66 +- src/scene/index.js | 54 +- src/scene/typedefs/index.js | 18 +- src/sound/BaseSound.js | 988 +- src/sound/BaseSoundManager.js | 1238 +- src/sound/SoundManagerCreator.js | 92 +- src/sound/events/COMPLETE_EVENT.js | 50 +- src/sound/events/DECODED_ALL_EVENT.js | 52 +- src/sound/events/DECODED_EVENT.js | 48 +- src/sound/events/DESTROY_EVENT.js | 52 +- src/sound/events/DETUNE_EVENT.js | 54 +- src/sound/events/GLOBAL_DETUNE_EVENT.js | 44 +- src/sound/events/GLOBAL_MUTE_EVENT.js | 42 +- src/sound/events/GLOBAL_RATE_EVENT.js | 44 +- src/sound/events/GLOBAL_VOLUME_EVENT.js | 42 +- src/sound/events/LOOPED_EVENT.js | 56 +- src/sound/events/LOOP_EVENT.js | 56 +- src/sound/events/MUTE_EVENT.js | 54 +- src/sound/events/PAUSE_ALL_EVENT.js | 42 +- src/sound/events/PAUSE_EVENT.js | 52 +- src/sound/events/PLAY_EVENT.js | 50 +- src/sound/events/RATE_EVENT.js | 54 +- src/sound/events/RESUME_ALL_EVENT.js | 42 +- src/sound/events/RESUME_EVENT.js | 54 +- src/sound/events/SEEK_EVENT.js | 54 +- src/sound/events/STOP_ALL_EVENT.js | 42 +- src/sound/events/STOP_EVENT.js | 52 +- src/sound/events/UNLOCKED_EVENT.js | 42 +- src/sound/events/VOLUME_EVENT.js | 54 +- src/sound/events/index.js | 74 +- src/sound/html5/HTML5AudioSound.js | 1838 +- src/sound/html5/HTML5AudioSoundManager.js | 918 +- src/sound/index.js | 60 +- src/sound/noaudio/NoAudioSound.js | 242 +- src/sound/noaudio/NoAudioSoundManager.js | 224 +- src/sound/typedefs/index.js | 18 +- src/sound/webaudio/WebAudioSound.js | 1800 +- src/sound/webaudio/WebAudioSoundManager.js | 906 +- src/structs/List.js | 1620 +- src/structs/Map.js | 734 +- src/structs/ProcessQueue.js | 570 +- src/structs/RTree.js | 1210 +- src/structs/Set.js | 886 +- src/structs/Size.js | 1544 +- src/structs/events/PROCESS_QUEUE_ADD_EVENT.js | 42 +- .../events/PROCESS_QUEUE_REMOVE_EVENT.js | 42 +- src/structs/events/index.js | 32 +- src/structs/index.js | 40 +- src/textures/CanvasTexture.js | 1250 +- src/textures/Frame.js | 1626 +- src/textures/Texture.js | 1028 +- src/textures/TextureManager.js | 2392 +- src/textures/TextureSource.js | 670 +- src/textures/const.js | 76 +- src/textures/events/ADD_EVENT.js | 40 +- src/textures/events/ERROR_EVENT.js | 40 +- src/textures/events/LOAD_EVENT.js | 46 +- src/textures/events/READY_EVENT.js | 34 +- src/textures/events/REMOVE_EVENT.js | 44 +- src/textures/events/index.js | 38 +- src/textures/index.js | 94 +- src/textures/parsers/AtlasXML.js | 150 +- src/textures/parsers/Canvas.js | 58 +- src/textures/parsers/Image.js | 58 +- src/textures/parsers/JSONArray.js | 202 +- src/textures/parsers/JSONHash.js | 186 +- src/textures/parsers/SpriteSheet.js | 238 +- src/textures/parsers/SpriteSheetFromAtlas.js | 370 +- src/textures/parsers/UnityYAML.js | 328 +- src/textures/parsers/index.js | 44 +- src/textures/typedefs/index.js | 18 +- src/tilemaps/Formats.js | 98 +- src/tilemaps/ImageCollection.js | 332 +- src/tilemaps/ParseToTilemap.js | 160 +- src/tilemaps/Tile.js | 1706 +- src/tilemaps/Tilemap.js | 5150 +- src/tilemaps/TilemapCreator.js | 76 +- src/tilemaps/TilemapFactory.js | 120 +- src/tilemaps/Tileset.js | 796 +- src/tilemaps/components/CalculateFacesAt.js | 140 +- .../components/CalculateFacesWithin.js | 120 +- src/tilemaps/components/CheckIsoBounds.js | 68 +- src/tilemaps/components/Copy.js | 118 +- src/tilemaps/components/CreateFromTiles.js | 156 +- src/tilemaps/components/CullTiles.js | 554 +- src/tilemaps/components/Fill.js | 96 +- src/tilemaps/components/FilterTiles.js | 84 +- src/tilemaps/components/FindByIndex.js | 164 +- src/tilemaps/components/FindTile.js | 96 +- src/tilemaps/components/ForEachTile.js | 88 +- src/tilemaps/components/GetTileAt.js | 100 +- src/tilemaps/components/GetTileAtWorldXY.js | 66 +- src/tilemaps/components/GetTilesWithin.js | 156 +- .../components/GetTilesWithinShape.js | 182 +- .../components/GetTilesWithinWorldXY.js | 90 +- src/tilemaps/components/HasTileAt.js | 74 +- src/tilemaps/components/HasTileAtWorldXY.js | 64 +- src/tilemaps/components/IsInLayerBounds.js | 50 +- src/tilemaps/components/PutTileAt.js | 148 +- src/tilemaps/components/PutTileAtWorldXY.js | 72 +- src/tilemaps/components/PutTilesAt.js | 118 +- src/tilemaps/components/Randomize.js | 104 +- src/tilemaps/components/RemoveTileAt.js | 114 +- .../components/RemoveTileAtWorldXY.js | 70 +- src/tilemaps/components/RenderDebug.js | 166 +- src/tilemaps/components/ReplaceByIndex.js | 78 +- src/tilemaps/components/SetCollision.js | 126 +- .../components/SetCollisionBetween.js | 138 +- .../components/SetCollisionByExclusion.js | 102 +- .../components/SetCollisionByProperty.js | 138 +- .../SetCollisionFromCollisionGroup.js | 108 +- .../components/SetLayerCollisionIndex.js | 66 +- src/tilemaps/components/SetTileCollision.js | 60 +- .../components/SetTileIndexCallback.js | 82 +- .../components/SetTileLocationCallback.js | 74 +- src/tilemaps/components/Shuffle.js | 78 +- src/tilemaps/components/SwapByIndex.js | 90 +- src/tilemaps/components/TileToWorldX.js | 122 +- src/tilemaps/components/TileToWorldXY.js | 418 +- src/tilemaps/components/TileToWorldY.js | 266 +- src/tilemaps/components/WeightedRandomize.js | 148 +- src/tilemaps/components/WorldToTileX.js | 138 +- src/tilemaps/components/WorldToTileXY.js | 462 +- src/tilemaps/components/WorldToTileY.js | 312 +- src/tilemaps/components/index.js | 112 +- .../dynamiclayer/DynamicTilemapLayer.js | 2656 +- .../DynamicTilemapLayerCanvasRenderer.js | 278 +- .../dynamiclayer/DynamicTilemapLayerRender.js | 50 +- .../DynamicTilemapLayerWebGLRenderer.js | 250 +- src/tilemaps/index.js | 64 +- src/tilemaps/mapdata/LayerData.js | 468 +- src/tilemaps/mapdata/MapData.js | 458 +- src/tilemaps/mapdata/ObjectLayer.js | 232 +- src/tilemaps/parsers/Parse.js | 128 +- src/tilemaps/parsers/Parse2DArray.js | 170 +- src/tilemaps/parsers/ParseCSV.js | 84 +- .../parsers/impact/ParseTileLayers.js | 156 +- src/tilemaps/parsers/impact/ParseTilesets.js | 90 +- .../parsers/impact/ParseWeltmeister.js | 122 +- src/tilemaps/parsers/impact/index.js | 34 +- src/tilemaps/parsers/index.js | 40 +- .../parsers/tiled/AssignTileProperties.js | 134 +- src/tilemaps/parsers/tiled/Base64Decode.js | 74 +- .../parsers/tiled/BuildTilesetIndex.js | 134 +- .../parsers/tiled/CreateGroupLayer.js | 110 +- src/tilemaps/parsers/tiled/ParseGID.js | 168 +- .../parsers/tiled/ParseImageLayers.js | 164 +- src/tilemaps/parsers/tiled/ParseJSONTiled.js | 180 +- src/tilemaps/parsers/tiled/ParseObject.js | 152 +- .../parsers/tiled/ParseObjectLayers.js | 186 +- src/tilemaps/parsers/tiled/ParseTileLayers.js | 528 +- src/tilemaps/parsers/tiled/ParseTilesets.js | 326 +- src/tilemaps/parsers/tiled/index.js | 48 +- .../staticlayer/StaticTilemapLayer.js | 3004 +- .../StaticTilemapLayerCanvasRenderer.js | 256 +- .../staticlayer/StaticTilemapLayerRender.js | 50 +- .../StaticTilemapLayerWebGLRenderer.js | 132 +- src/tilemaps/typedefs/index.js | 18 +- src/time/Clock.js | 800 +- src/time/TimerEvent.js | 614 +- src/time/index.js | 32 +- src/time/typedefs/index.js | 18 +- src/tweens/Timeline.js | 1798 +- src/tweens/TweenManager.js | 1532 +- src/tweens/builders/GetBoolean.js | 70 +- src/tweens/builders/GetEaseFunction.js | 206 +- src/tweens/builders/GetNewValue.js | 116 +- src/tweens/builders/GetProps.js | 110 +- src/tweens/builders/GetTargets.js | 86 +- src/tweens/builders/GetTweens.js | 84 +- src/tweens/builders/GetValueOp.js | 524 +- src/tweens/builders/NumberTweenBuilder.js | 248 +- src/tweens/builders/StaggerBuilder.js | 480 +- src/tweens/builders/TimelineBuilder.js | 292 +- src/tweens/builders/TweenBuilder.js | 254 +- src/tweens/builders/index.js | 50 +- src/tweens/events/TIMELINE_COMPLETE_EVENT.js | 60 +- src/tweens/events/TIMELINE_LOOP_EVENT.js | 62 +- src/tweens/events/TIMELINE_PAUSE_EVENT.js | 62 +- src/tweens/events/TIMELINE_RESUME_EVENT.js | 62 +- src/tweens/events/TIMELINE_START_EVENT.js | 60 +- src/tweens/events/TIMELINE_UPDATE_EVENT.js | 62 +- src/tweens/events/TWEEN_ACTIVE_EVENT.js | 68 +- src/tweens/events/TWEEN_COMPLETE_EVENT.js | 70 +- src/tweens/events/TWEEN_LOOP_EVENT.js | 76 +- src/tweens/events/TWEEN_REPEAT_EVENT.js | 78 +- src/tweens/events/TWEEN_START_EVENT.js | 68 +- src/tweens/events/TWEEN_UPDATE_EVENT.js | 74 +- src/tweens/events/TWEEN_YOYO_EVENT.js | 80 +- src/tweens/events/index.js | 54 +- src/tweens/index.js | 58 +- src/tweens/tween/Defaults.js | 76 +- src/tweens/tween/ReservedProps.js | 138 +- src/tweens/tween/Tween.js | 3276 +- src/tweens/tween/TweenData.js | 242 +- src/tweens/tween/const.js | 332 +- src/tweens/typedefs/TweenBuilderConfig.js | 120 +- src/tweens/typedefs/TweenDataConfig.js | 64 +- src/tweens/typedefs/index.js | 18 +- src/utils/Class.js | 496 +- src/utils/NOOP.js | 42 +- src/utils/array/Add.js | 222 +- src/utils/array/AddAt.js | 232 +- src/utils/array/BringToTop.js | 64 +- src/utils/array/CountAllMatching.js | 92 +- src/utils/array/Each.js | 80 +- src/utils/array/EachInRange.js | 100 +- src/utils/array/FindClosestInSorted.js | 156 +- src/utils/array/GetAll.js | 112 +- src/utils/array/GetFirst.js | 106 +- src/utils/array/GetRandom.js | 58 +- src/utils/array/MoveDown.js | 72 +- src/utils/array/MoveTo.js | 82 +- src/utils/array/MoveUp.js | 72 +- src/utils/array/NumberArray.js | 116 +- src/utils/array/NumberArrayStep.js | 142 +- src/utils/array/QuickSelect.js | 232 +- src/utils/array/Range.js | 264 +- src/utils/array/Remove.js | 170 +- src/utils/array/RemoveAt.js | 90 +- src/utils/array/RemoveBetween.js | 114 +- src/utils/array/RemoveRandomElement.js | 64 +- src/utils/array/Replace.js | 76 +- src/utils/array/RotateLeft.js | 68 +- src/utils/array/RotateRight.js | 68 +- src/utils/array/SafeRange.js | 86 +- src/utils/array/SendToBack.js | 64 +- src/utils/array/SetAll.js | 98 +- src/utils/array/Shuffle.js | 70 +- src/utils/array/SpliceOne.js | 80 +- src/utils/array/StableSort.js | 282 +- src/utils/array/Swap.js | 84 +- src/utils/array/index.js | 94 +- src/utils/array/matrix/CheckMatrix.js | 110 +- src/utils/array/matrix/MatrixToString.js | 150 +- src/utils/array/matrix/ReverseColumns.js | 50 +- src/utils/array/matrix/ReverseRows.js | 60 +- src/utils/array/matrix/Rotate180.js | 54 +- src/utils/array/matrix/RotateLeft.js | 54 +- src/utils/array/matrix/RotateMatrix.js | 132 +- src/utils/array/matrix/RotateRight.js | 54 +- src/utils/array/matrix/TransposeMatrix.js | 84 +- src/utils/array/matrix/index.js | 46 +- src/utils/base64/ArrayBufferToBase64.js | 104 +- src/utils/base64/Base64ToArrayBuffer.js | 138 +- src/utils/base64/index.js | 32 +- src/utils/index.js | 36 +- src/utils/object/Clone.js | 72 +- src/utils/object/Extend.js | 186 +- src/utils/object/GetAdvancedValue.js | 162 +- src/utils/object/GetFastValue.js | 74 +- src/utils/object/GetMinMaxValue.js | 66 +- src/utils/object/GetValue.js | 130 +- src/utils/object/HasAll.js | 62 +- src/utils/object/HasAny.js | 62 +- src/utils/object/HasValue.js | 46 +- src/utils/object/IsPlainObject.js | 100 +- src/utils/object/Merge.js | 78 +- src/utils/object/MergeRight.js | 74 +- src/utils/object/Pick.js | 76 +- src/utils/object/SetValue.js | 154 +- src/utils/object/index.js | 56 +- src/utils/string/Format.js | 58 +- src/utils/string/Pad.js | 140 +- src/utils/string/Reverse.js | 46 +- src/utils/string/UUID.js | 58 +- src/utils/string/UppercaseFirst.js | 62 +- src/utils/string/index.js | 38 +- types/SpineFile.d.ts | 36 +- types/SpineGameObject.d.ts | 250 +- types/SpinePlugin.d.ts | 118 +- types/matter.d.ts | 10042 +- types/phaser.d.ts | 177922 ++++++------- 1499 files changed, 518809 insertions(+), 317404 deletions(-) create mode 100644 dist/phaser-facebook-instant-games.js create mode 100644 dist/phaser-facebook-instant-games.min.js diff --git a/.gitignore b/.gitignore index 3afe179fc..33e76489f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,20 @@ -# System and IDE files -Thumbs.db -.DS_Store -.idea -.vscode -*.suo -*.sublime-project -*.sublime-workspace - -# Vendors -node_modules/ - -# Build -/npm-debug.log -build/ -out/ -scripts/tsgen/test/bin/ -scripts/tsgen/test/output.txt - +# System and IDE files +Thumbs.db +.DS_Store +.idea +.vscode +*.suo +*.sublime-project +*.sublime-workspace + +# Vendors +node_modules/ + +# Build +/npm-debug.log +build/ +out/ +scripts/tsgen/test/bin/ +scripts/tsgen/test/output.txt + plugins/spine/spine-runtimes/ \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 503b0660d..4b9425fe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3371 +1,3371 @@ -# Change Log - -## Version 3.23 - Ginro - in development - -### JSDocs - -The following sections now have 100% complete JSDoc coverage: - -* Animations -* Create -* Geom -* Math -* Renderer -* Textures - -### Removed - -The following features have been removed in this version of Phaser: - -* Impact Physics has been removed completely and is no longer a choice of physics system. The resulting `Scene.impact` property and Impact config object have also been removed. - -### Deprecated - -The following features are now deprecated and will be removed in a future version of Phaser: - -* The Light Pipeline and associated components will be removed. This feature was never properly finished and adds too much redundant, non-optional code into the core API. The ability to load normal maps alongside textures will _remain_, for use in your own lighting shaders, which gives you far more control over the final effect. - - -### New Features - -* `Line.GetEasedPoints` is a new function that will take a Line, a quantity, and an ease function, and returns an array of points where each point has been spaced out across the length of the Line based on the ease function given. -* `XHRSettings.withCredentials` is a new boolean property that controls the `withCredentials` setting of the XHR Request made by the Loader. It indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. You can set this on a per-file basis, or global in the Game Config. -* `Config.loaderWithCredentials` is the new global setting for `XHRSettings.withCredentials`. -* `Camera.renderToGame` is a new property used in conjunction with `renderToTexture`. It controls if the Camera should still render to the Game canvas after rendering to its own texture or not. By default, it will render to both, but you can now toggle this at run-time. -* `Camera.setRenderToTexture` has a new optional parameter `renderToGame` which sets the `Camera.renderToGame` property, controlling if the Camera should render to both its texture and the Game canvas, or just its texture. - -### Updates - -* `XHRLoader` will now use the `XHRSettings.withCredentials` as set in the file or global loader config. -* `Animation.setCurrentFrame` will no longer try to call `setOrigin` or `updateDisplayOrigin` if the Game Object doesn't have the Origin component, preventing unknown function errors. -* `MatterTileBody` now extends `EventEmitter`, meaning you can listen to collision events from Tiles directly and it will no longer throw errors about `gameObject.emit` not working. Fix #4967 (thanks @reinildo) -* Added `MatterJS.BodyType` to `GameObject.body` type. Fix #4962 (thanks @meisterpeeps) - -### Bug Fixes - -* The conditional checking if the `PathFollower` was at the end of the path or not was incorrect (thanks @samme) -* Creating an `Arcade Physics Body` from a scaled Game Object would use the un-scaled dimensions for the body. They now use the scaled dimensions. This may be a breaking change in some games, so please be aware of it (thanks @samme) -* Creating an `Arcade Physics Static Body` from a scaled Game Object would use the un-scaled dimensions for the body. They now use the scaled dimensions. This may be a breaking change in some games, so please be aware of it (thanks @samme) -* The `Arcade Physics Static Body` center was incorrect after construction. Probably caused problems with circle collisions. Fix #4770 (thanks @samme) -* An Arcade Physics Body `center` and `position` are now correct after construction and before preUpdate(), for any Game Object origin or scale (thanks @samme) -* When calling `Body.setSize` with the `center` parameter as `true` the calculated offset would be incorrect for scaled Game Objects. The offset now takes scaling into consideration (thanks @samme) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@JasonHK @supertommy - -## Version 3.22 - Kohaku - January 15th 2020 - -### Matter Physics - -All of the following are specific to the Matter Physics implementation used by Phaser: - -#### Matter Physics New Features - -* Matter Physics now has 100% JSDoc coverage! Woohoo :) -* Matter Physics now has brand new TypeScript defs included in the `types` folder :) -* `MatterDebugConfig` is a new configuration object that contains all of the following new Matter debug settings: -* `showAxes`- Render all of the body axes? -* `showAngleIndicator`- Render just a single body axis? -* `angleColor`- The color of the body angle / axes lines. -* `showBroadphase`- Render the broadphase grid? -* `broadphaseColor`- The color of the broadphase grid. -* `showBounds`- Render the bounds of the bodies in the world? -* `boundsColor`- The color of the body bounds. -* `showVelocity`- Render the velocity of the bodies in the world? -* `velocityColor`- The color of the body velocity line. -* `showCollisions`- Render the collision points and normals for colliding pairs. -* `collisionColor`- The color of the collision points. -* `showSeparation`- Render lines showing the separation between bodies. -* `separationColor`- The color of the body separation line. -* `showBody`- Render the dynamic bodies in the world to the Graphics object? -* `showStaticBody`- Render the static bodies in the world to the Graphics object? -* `showInternalEdges`- When rendering bodies, render the internal edges as well? -* `renderFill`- Render the bodies using a fill color. -* `renderLine`- Render the bodies using a line stroke. -* `fillColor`- The color value of the fill when rendering dynamic bodies. -* `fillOpacity`- The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. -* `lineColor`- The color value of the line stroke when rendering dynamic bodies. -* `lineOpacity`- The opacity of the line when rendering dynamic bodies, a value between 0 and 1. -* `lineThickness`- If rendering lines, the thickness of the line. -* `staticFillColor`- The color value of the fill when rendering static bodies. -* `staticLineColor`- The color value of the line stroke when rendering static bodies. -* `showSleeping`- Render any sleeping bodies (dynamic or static) in the world to the Graphics object? -* `staticBodySleepOpacity`] - The amount to multiply the opacity of sleeping static bodies by. -* `sleepFillColor`- The color value of the fill when rendering sleeping dynamic bodies. -* `sleepLineColor`- The color value of the line stroke when rendering sleeping dynamic bodies. -* `showSensors`- Render bodies or body parts that are flagged as being a sensor? -* `sensorFillColor`- The fill color when rendering body sensors. -* `sensorLineColor`- The line color when rendering body sensors. -* `showPositions`- Render the position of non-static bodies? -* `positionSize`- The size of the rectangle drawn when rendering the body position. -* `positionColor`- The color value of the rectangle drawn when rendering the body position. -* `showJoint`- Render all world constraints to the Graphics object? -* `jointColor`- The color value of joints when `showJoint` is set. -* `jointLineOpacity`- The line opacity when rendering joints, a value between 0 and 1. -* `jointLineThickness`- The line thickness when rendering joints. -* `pinSize`- The size of the circles drawn when rendering pin constraints. -* `pinColor`- The color value of the circles drawn when rendering pin constraints. -* `springColor`- The color value of spring constraints. -* `anchorColor`- The color value of constraint anchors. -* `anchorSize`- The size of the circles drawn as the constraint anchors. -* `showConvexHulls`- When rendering polygon bodies, render the convex hull as well? -* `hullColor`- The color value of hulls when `showConvexHulls` is set. -* `World.renderBody` is a new method that will render a single Matter Body to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which bodies are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. -* `World.renderConstraint` is a new method that will render a single Matter Constraint, such as a pin or a spring, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which constraints are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. -* `World.renderConvexHull` is a new method that will render the convex hull of a single Matter Body, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which hulls are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. -* `World.renderGrid` is a new method that will render the broadphase Grid to the given graphics instance. -* `World.renderBodyBounds` is a new method that will render the bounds of all the given bodies to the given graphics instance. -* `World.renderBodyAxes` is a new method that will render the axes of all the given bodies to the given graphics instance. -* `World.renderBodyVelocity` is a new method that will render a velocity line for all the given bodies to the given graphics instance. -* `World.renderSeparations` is a new method that will render the separations in the current pairs list to the given graphics instance. -* `World.renderCollisions` is a new method that will render the collision points and normals in the current pairs list to the given graphics instance. -* `World.getAllBodies` is a new method that will return all bodies in the Matter World. -* `World.getAllConstraints` is a new method that will return all constraints in the Matter World. -* `World.getAllComposites` is a new method that will return all composites in the Matter World. -* `MatterPhysics.composite` is a new reference to the `Matter.Composite` module for easy access from within a Scene. -* `MatterPhysics.detector` is a new reference to the `Matter.Dectector` module for easy access from within a Scene. -* `MatterPhysics.grid` is a new reference to the `Matter.Grid` module for easy access from within a Scene. -* `MatterPhysics.pair` is a new reference to the `Matter.Pair` module for easy access from within a Scene. -* `MatterPhysics.pairs` is a new reference to the `Matter.Pairs` module for easy access from within a Scene. -* `MatterPhysics.query` is a new reference to the `Matter.Query` module for easy access from within a Scene. -* `MatterPhysics.resolver` is a new reference to the `Matter.Resolver` module for easy access from within a Scene. -* `MatterPhysics.sat` is a new reference to the `Matter.SAT` module for easy access from within a Scene. -* `MatterPhysics.constraint` is a new reference to the `Matter.Constraint` module for easy access from within a Scene. -* `MatterPhysics.composites` is a new reference to the `Matter.Composites` module for easy access from within a Scene. -* `MatterPhysics.axes` is a new reference to the `Matter.Axes` module for easy access from within a Scene. -* `MatterPhysics.bounds` is a new reference to the `Matter.Bounds` module for easy access from within a Scene. -* `MatterPhysics.svg` is a new reference to the `Matter.Svg` module for easy access from within a Scene. -* `MatterPhysics.vector` is a new reference to the `Matter.Vector` module for easy access from within a Scene. -* `MatterPhysics.vertices` is a new reference to the `Matter.Vertices` module for easy access from within a Scene. -* `BEFORE_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be added to the World. -* `AFTER_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint has been added to the World. -* `BEFORE_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be removed from the World. -* `AFTER_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint has been removed from the World. -* `Body.render.lineOpacity` is a new property on the Matter Body object that allows for custom debug rendering. -* `Body.render.lineThickness` is a new property on the Matter Body object that allows for custom debug rendering. -* `Body.render.fillOpacity` is a new property on the Matter Body object that allows for custom debug rendering. -* `World.setCompositeRenderStyle` is a new method that lets you quickly set the render style values on the children of the given compposite. -* `World.setBodyRenderStyle` is a new method that lets you quickly set the render style values on the given Body. -* `World.setConstraintRenderStyle` is a new method that lets you quickly set the render style values on the given Constraint. -* You can now set `restingThresh` in the Matter Configuration file to adjust the Resolver property. -* You can now set `restingThreshTangent` in the Matter Configuration file to adjust the Resolver property. -* You can now set `positionDampen` in the Matter Configuration file to adjust the Resolver property. -* You can now set `positionWarming` in the Matter Configuration file to adjust the Resolver property. -* You can now set `frictionNormalMultiplier` in the Matter Configuration file to adjust the Resolver property. -* `MatterPhysics.containsPoint` is a new method that returns a boolean if any of the given bodies intersect with the given point. -* `MatterPhysics.intersectPoint` is a new method that checks which bodies intersect with the given point and returns them. -* `MatterPhysics.intersectRect` is a new method that checks which bodies intersect with the given rectangular area, and returns them. Optionally, it can check which bodies are outside of the area. -* `MatterPhysics.intersectRay` is a new method that checks which bodies intersect with the given ray segment and returns them. Optionally, you can set the width of the ray. -* `MatterPhysics.intersectBody` is a new method that checks which bodies intersect with the given body and returns them. If the bodies are set to not collide this can be used as an overlaps check. -* `MatterPhysics.overlap` is a new method that takes a target body and checks to see if it overlaps with any of the bodies given. If they do, optional `process` and `overlap` callbacks are invoked, passing the overlapping bodies to them, along with additional collision data. -* `MatterPhysics.setCollisionCategory` is a new method that will set the collision filter category to the value given, on all of the bodies given. This allows you to easily set the category on bodies that don't have a Phaser Matter Collision component. -* `MatterPhysics.setCollisionGroup` is a new method that will set the collision filter group to the value given, on all of the bodies given. This allows you to easily set the group on bodies that don't have a Phaser Matter Collision component. -* `MatterPhysics.setCollidesWith` is a new method that will set the collision filter mask to the value given, on all of the bodies given. This allows you to easily set the filter mask on bodies that don't have a Phaser Matter Collision component. -* `Matter.Body.centerOfMass` is a new vec2 property added to the Matter Body object that retains the center of mass coordinates when the Body is first created, or has parts added to it. These are float values, derived from the body position and bounds. -* `Matter.Body.centerOffset` is a new vec2 property added to the Matter Body object that retains the center offset coordinates when the Body is first created, or has parts added to it. These are pixel values. -* `Constraint.pointAWorld` is a new method added to Matter that returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`. -* `Constraint.pointBWorld` is a new method added to Matter that returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`. -* `Body.setCentre` is a new method added to Matter that allows you to set the center of mass of a Body (please note the English spelling of this function.) -* `Body.scale` is a new read-only vector that holds the most recent scale values as passed to `Body.scale`. -* `Matter.Bodies.flagCoincidentParts` is a new function that will flags all internal edges (coincident parts) on an array of body parts. This was previously part of the `fromVertices` function, but has been made external for outside use. -* `Matter.getMatterBodies` is a new function that will return an array of Matter JS Bodies from the given input array, which can be Matter Game Objects, or any class that extends them. -* `Matter.World.has` is a new method that will take a Matter Body, or Game Object, and search the world for it. If found, it will return `true`. -* Matter now has the option to use the Runner that it ships with. The Matter Runner operates in two modes: fixed and variable. In the fixed mode, the Matter Engine updates at a fixed delta value every frame (which is what Phaser has used since the first version). In variable mode, the delta will be smoothed and capped each frame to keep the simulation constant, but at the cost of determininism. You can configure the runner by setting the `runner` property in the Matter Config object, both of which are fully covered with JSDocs. As of 3.22 the runner is now used by default in variable (non-fixed) mode. If you wish to return to the previous behavior, set `runner: { isFixed: true }`. -* `Body.onCollideCallback` is a new Matter Body property that can point to a callback to invoke when the body starts colliding. -* `Body.onCollideEndCallback` is a new Matter Body property that can point to a callback to invoke when the body stops colliding. -* `Body.onCollideActiveCallback` is a new Matter Body property that can point to a callback to invoke for the duration the body is colliding. -* `Body.onCollideWith` is a new Matter Body property that holds a mapping between bodies and collision callbacks. -* `MatterGameObject.setOnCollide` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body collides with another. -* `MatterGameObject.setOnCollideEnd` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body stops colliding. -* `MatterGameObject.setOnCollideActive` is a new method available on any Matter Game Object, that sets a callback which is invoked for the duration of the bodies collision with another. -* `MatterGameObject.setOnCollideWith` is a new method available on any Matter Game Object, that allows you to set a callback to be invoked whenever the body collides with another specific body, or array of bodies. -* `Body.gravityScale` is a new vector property that allows you to scale the effect of world gravity on a specific Body. -* `MatterPhysics._tempVec2` is a new private internal vector used for velocity and force calculations. -* `MatterPhysics.setVelocity` is a new method that will set both the horizontal and vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.setVelocityX` is a new method that will set the horizontal linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.setVelocityY` is a new method that will set the vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.setAngularVelocity` is a new method that will set the angular velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.applyForce` is a new method that applies a force to a body, at the bodies current position, including resulting torque. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.applyForceFromPosition` is a new method that applies a force to a body from the given world position, including resulting torque. If no angle is given, the current body angle is used. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.fromSVG` is a new method that allows you to create a Body from the given SVG path data. -* The `Matter.Factory.velocity` method has been removed. Please now use `MatterPhysics.setVelocity` instead. -* The `Matter.Factory.angularVelocity` method has been removed. Please now use `MatterPhysics.setAngularVelocity` instead. -* The `Matter.Factory.force` method has been removed. Please now use `MatterPhysics.applyForce` instead. -* `MatterBodyConfig` is a new type def that contains all of the Body configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterBodyRenderConfig` is a new type def that contains all of the Body debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterChamferConfig` is a new type def that contains all of the chamfer configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterCollisionFilter` is a new type def that contains all of the collision configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterConstraintConfig` is a new type def that contains all of the constraint configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterConstraintRenderConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterSetBodyConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterPhysics.getConstraintLength` is a new method that will return the length of the given constraint, as this is something you cannot get from the constraint properties directly. -* `MatterPhysics.alignBody` is a new method that will align a Body, or Matter Game Object, against the given coordinates, using the given alignment constant. For example, this allows you to easily position a body to the `BOTTOM_LEFT`, or `TOP_CENTER`, or a coordinate. Alignment is based on the body bounds. -* `Phaser.Types.Physics.Matter.MatterBody` is a new type def that contains all of the valid Matter Body objects. This is now used through-out the JSDocs to aid in code-completion. -* `Matter.BodyBounds` is a new class that contains methods to help you extract 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 new class via `this.matter.bodyBounds`. -* The method signature for `Matter.PhysicsEditorParser.parseBody` has changed. It now takes `(x, y, config, options)` and no longer has `width` and `height` parameters. Please see the updated documentation for more details if you were calling this method directly. -* `MatterPhysics.fromPhysicsEditor` is a new method that allows you to create a Matter Body based on the given PhysicsEditor shape data. Previously, you could only using PhysicsEditor data with a Matter Game Object, but now you can create a body directly using it. -* `Matter.PhysicsJSONParser` is a new parser that will create Matter bodies from JSON physics data files. Currently onto the Phaser Physics Tracer app exports in this format, but details are published in the JSDocs, so any app can do so. -* `Matter.Factory.fromJSON` is a new method that will create a body from a JSON physics data file. -* The `SetBody` Matter component can now automatically use shapes created in the Phaser Physics Tracer App in the JSON data format. -* `Matter.Components.Sleep.setToSleep` is a new method available on any Matter Game Object that will send the body to sleep, if Engine sleeping has been enabled. -* `Matter.Components.Sleep.setAwake` is a new method available on any Matter Game Object that will awake a body from sleep, if Engine sleeping has been enabled. - -#### Matter Physics Updates - -* The `debug` property in the Matter World Config is now a `MatterDebugConfig` option instead of a boolean. However, if a boolean is given, it will use the default debug config values. -* The following `MatterWorldConfig` options have now been removed: `debugShowBody`, `debugShowStaticBody`, `debugBodyColor`, `debugBodyFillColor`, `debugStaticBodyColor`, `debugShowJoint`, `debugJointColor`, `debugWireframes`, `debugShowInternalEdges`, `debugShowConvexHulls`, `debugConvexHullColor` and `debugShowSleeping`. These can all be set via the new `MatterDebugConfig` object instead. -* The object `World.defaults` has been removed. Defaults are now access via `World.debugDefaults`. -* `World.renderBodies` has been rewritten to cache commonly-used values and avoid a situation when a single body would be rendered twice. -* The private method `World.renderConvexHulls` has been removed as it's no longer used internally. -* The private method `World.renderWireframes` has been removed as it's no longer used internally. -* The method `World.fromPath` has been removed. This was never used internally and you can get the same results by calling `Vertices.fromPath`. -* The `World.setBounds` argument `thickness` now defaults to 64, not 128, to keep it matching the Matter World Config. -* The `Body.render.fillStyle` property that existed on the Matter Body object has been removed and replaced with `fillColor`. -* The `Body.render.strokeStyle` property that existed on the Matter Body object has been removed and replaced with `lineColor`. -* `Matter.Body.render.sprite.xOffset` and `yOffset` are no longer set to anything when a Body is created. They are left as zero, or you can override them in the Body config, in which case the value is added to the sprite origin offset during a call to `setExistingBody`. -* The `Matter.Mass.centerOfMass` component property now returns the pre-calculated Body `centerOfMass` property, which is much more accurate than the previous bounds offset value. -* `Matter.setExistingBody`, which is called interally whenever a Body is set on a Game Object, now uses the new `centerOffset` values to ensure that the texture frame is correctly centered based on the center of mass, not the Body bounds, allowing for much more accurate body to texture mapping with complex multi-part compound bodies. -* The `Matter.PhysicsEditorParser` has been updated so it no longer needs to set the render offsets, and instead uses the center of mass values. -* If the `Matter.Body` config doesn't contain a `position` property, it will now default to using `Vertices.centre(body.vertices)` as the position. In most cases, this is what you need, so it saves having to pass it in the config object. -* Bumped Matter Plugin versions to avoid console logs from Common.info and Common.warn. -* `PhysicsEditorParser.parseVertices` now uses `Bodies.flagCoincidentParts` to avoid duplicating code. -* `MatterGameObject` has a new optional boolean constructor parameter `addToWorld` which lets you control if the Body should be added to the world or not. Useful for toggling off should you be merging pre-existing bodies with Game Objects. -* The `Matter.SetBody.setExistingBody` function, which all Matter Game Objects have, has a new parameter `addToWorld` which allows you to control when the body is added to the Matter world should you not require it immediately. It will also only add the body to the world if it doesn't already exist within it, or any of its composites. -* `PointerConstraint` has been recoded so that when pressed down, it only polls the World for a body hit test during the next game update. This stops it coming out of sync with the state of the world. Use of the constraint remains the same as before. -* You can now set `gravity: false` in your Matter Config and it will reset gravity from the defaults to zero. -* The internal Matter `Composite.setModified` function will now emit a `compositeModified` event, which the Matter World listens for, if debug draw is enabled, so it can update the composite children render styles. -* `Matter.PhysicsEditorParser.parseBody` can now accept a MatterBodyConfig file as a 4th parameter. This allows you to set Body properties when the body is created, overriding whatever values may have been set in the PhysicsEditor JSON. - -#### Matter Physics Bug Fixes - -* Due to the rewrite of the debug rendering, it is now possible to render _just_ constraints, where-as before this was only possible if bodies were being rendered as well. Fix #4880 (thanks @roberto257) -* `Matter.PhysicsEditorParser` had a bug where it would allow fixtures with non-clockwise sorted vertices through, which would break pointer constraint interaction with these bodies. The parser now sorts the vertices properly. Fix #4261 (thanks @Sanchez3) - -### New Features - -* `TimeStep.smoothStep` is a new boolean property that controls if any delta smoothing takes place during the game step. Delta smoothing has been enabled in Phaser since the first version and helps avoid delta spikes and dips, especially after loss of focus. However, you can now easily toggle if this happens via this property and the corresponding `FPSConfig` property. -* `Phaser.Math.Distance.BetweenPoints` is a new function that will return the distance between two Vector2-like objects (thanks @samme) -* `Phaser.Math.Distance.BetweenPointsSquared` is a new function that will return the squared distance between two Vector2-like objects (thanks @samme) -* `Phaser.Math.Distance.Chebyshev` is a new function that will return the Chebyshev (or chessboard) distance between two Vector2-like objects (thanks @samme) -* `Phaser.Math.Distance.Snake` is a new function that will return the rectilinear distance between two Vector2-like objects (thanks @samme) -* `ParticleEmitter.setTint` is a new method that will set the tint of emitted particles for the given Emitter only (thanks @samme) -* `ParticleEmitter.remove` is a new method that will remove the Emitter from its Emitter Manager (thanks @samme) -* `ParticleEmitterManager.removeEmitter` is a new method that will remove the given emitter from the manager, if the emitter belongs to it (thanks @samme) -* `AlphaSingle` is a new Game Object Component that allows a Game Object to set its alpha values, but only as a single uniform value, not on a per-quad basis. -* `Actions.AlignTo` (in combination with the new `Display.Align.To.QuickSet` function) allows you to align an array of Game Objects so they sit next to each other, one at a time. The first item isn't moved, the second is moved to sit next to the first, and so on. You can align them using any of the alignment constants (thanks @samme) -* `Scene.Systems.getData` is a new method that will return any data that was sent to the Scene by another Scene, i.e. during a `run` or `launch` command. You can access it via `this.sys.getData()` from within your Scene. -* `Group.internalCreateCallback` is a new optional callback that is invoked whenever a child is added to a Group. This is the same as `createCallback` except it's only for use by the parent class, allowing a parent to invoke a creation callback and for you to still provide one via the Group config. -* `Group.internalRemoveCallback` is a new optional callback that is invoked whenever a child is removed from a Group. This is the same as `removeCallback` except it's only for use by the parent class, allowing a parent to invoke a callback and for you to still provide one via the Group config. - -### Updates - -* `Body.deltaXFinal` is a new method on Arcade Physics Bodies that will return the final change in the horizontal position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) -* `Body.deltaYFinal` is a new method on Arcade Physics Bodies that will return the final change in the vertical position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) -* `Body._tx` is a new internal private var, holding the Arcade Physics Body combined total delta x value. -* `Body._ty` is a new internal private var, holding the Arcade Physics Body combined total delta y value. -* `LineCurve.getUtoTmapping` has been updated to return `u` directly to avoid calculations as it's identical to `t` in a Line (thanks @rexrainbow) -* `Curve.getSpacedPoints` will now take an optional array as the 3rd parameter to store the points results in (thanks @rexrainbow) -* Trying to play or resume an audio file with an incorrect key will now throw a runtime error, instead of a console warning (thanks @samme) -* The `Shape` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the shape, rather than a quad alpha, which never worked for Shape objects. -* The `Container` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the container, rather than a quad alpha, which never worked consistently across Container children. Fix #4916 (thanks @laineus) -* The `DOMElement` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. -* The `Graphics` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. -* `TweenData` has a new property called `previous` which holds the eased property value prior to the update. -* The `TWEEN_UPDATE` event now sends two new parameters to the handler: `current` and `previous` which contain the current and previous property values. -* During `collideSpriteVsGroup` checks it will now skip bodies that are disabled to save doing a `contains` test (thanks @samme) -* `Display.Align.In.QuickSet` now accepts `LEFT_BOTTOM` as `BOTTOM_LEFT`, `LEFT_TOP` as `TOP_LEFT`, `RIGHT_BOTTOM` as `BOTTOM_RIGHT` and `RIGHT_TOP` as `TOP_RIGHT`. Fix #4927 (thanks @zaniar) -* `PhysicsGroup` now uses the new `internalCreateCallback` and `internalRemoveCallback` to handle its body creation and destruction, allowing you to use your own `createCallback` and `removeCallback` as defined in the Group config. Fix #4420 #4657 #4822 (thanks @S4n60w3n @kendistiller @scrubperson) -* `DOMElement` has a new private method `handleSceneEvent` which will handle toggling the display setting of the element when a Scene sleeps and wakes. A DOM Element will now listen for the Scene sleep and wake events. These event listeners are removed in the `preDestroy` method. -* A `DOMElement` will now set the display mode to 'none' during its render if the Scene in which it belongs is no longer visible. - -### Bug Fixes - -* BitmapText with a `maxWidth` set wouldn't update the text correctly if it was modified post-creation. You can now update the text and/or width independantly and it'll update correctly. Fix #4881 (thanks @oxguy3) -* Text objects will no longer add any white-space when word-wrapping if the last line is only one word long. Fix #4867 (thanks @gaamoo @rexrainbow) -* When `Game.destroy` is running, Scenes are now destroyed _before_ plugins, avoiding bugs when closing down plugins and deleting Render Textures. Fix #4849 #4876 (thanks @rexrainbow @siyuanqiao) -* The `Mesh` and `Quad` Game Objects have had the `GetBounds` component removed as it cannot operate on a Mesh as they don't have origins. Fix #4902 (thanks @samme) -* Setting `lineSpacing` in the Text Game Object style config would set the value but not apply it to the Text, leaving you to call `updateText` yourself. If set, it's now applied on instantiation. Fix #4901 (thanks @FantaZZ) -* External calls to the Fullscreen API using `element.requestFullscreen()` would be blocked by the Scale Manager. The Scale Manager will no longer call `stopFullScreen` should it be triggered outside of Phaser (thanks @AdamXA) -* The `Tilemaps.Tile.tint` property wasn't working correctly as it expected the colors in the wrong order (BGR instead of RGB). It will now expect them in the correct RGB order (thanks @Aedalus @plissken2013es) -* The `ScaleManager.destroy` method wasn't being called when the Game `DESTROY` event was dispatched, causing minor gc to build up. The destroy method will now be called properly on game destruction. Fix #4944 (thanks @sunshineuoow) -* `FacebookInstantGamesPlugin.showAd` and `showVideo` will now break out of the ad iteration search once a valid ad has been found and called. Previously, it would carry on interating if the async didn't complete quickly. Fix #4888 (thanks @east62687) -* When playing an Animation, if you were to play another, then pause it, then play another the internal `_paused` wouldn't get reset, preventing you from them pausing the animations from that point on. You can now play and pause animations at will. Fix #4835 (thanks @murteira) -* In `Actions.GridAlign` if you set `width` to -1 it would align the items vertically, instead of horizontally. It now aligns them horizontally if `width` is set, or vertically if `height` is set. Fix #4899 (thanks @BenjaVR) -* A `PathFollower` with a very short duration would often not end in the correct place, which is the very end of the Path, due to the tween handling the movement not running one final update when the tween was complete. It will now always end at the final point of the path, no matter how short the duration. Fix #4950 (thanks @bramp) -* A `DOMElement` would still remain visible even if the Scene in which it belongs to was sent to sleep. A sleeping Scene shouldn't render anything. DOM Elements will now respond to sleep and wake events from their parent Scene. Fix #4870 (thanks @peonmodel) -* If a config object was passed to `MultiAtlasFile` it expected the atlas URL to be in the `url` property, however the docs and file config expected it in `atlasURL`. You can now use either of these properties to declare the url. Fix #4815 (thanks @xense) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@fselcukcan Bambosh @louisth @hexus @javigaralva @samme @BeLi4L @jcyuan @javigaralva @T-Grave @bramp @Chnapy @dranitski @RollinSafary @xense - -The Matter TypeScript defs have been updated to include lots of missing classes, removed some redundant elements and general fixes. The Phaser TypeScript defs now reference the Matter defs directly and no longer try to parse them from the JSDocs. This allows the `MatterJS` namespace to work in TypeScript projects without any compilation warnings. - -The Spine Plugin now has new TypeScript defs in the `types` folder thanks to @supertommy - -## Version 3.21.0 - Senku - 22nd November 2019 - -### New Features - -* You can now specify the mipmap filter level to be used when creating WebGL textures. This can be set in the Game Config using the new `mipmapFilter` property, which is a string, such as 'NEAREST_MIPMAP_NEAREST'. Or, you can set the new `WebGLRenderer.mipmapFilter` property to a valid GLenum. If you set it on the renderer, it will only impact any textures loaded _after_ it has been set, so do so in your Scene `init` method if you want it to be used for textures you're about to load. By changing the mipmap level you can drastically improve the quality when reducing large textures. Please note, due to WebGL1 limitations, this only works on power-of-two sized textures. It also works on textures created from Canvas, Videos or RenderTextures. -* `BitmapText.setMaxWidth` is a new method that allows you to set a maximum width (in pixels) for the BitmapText to take up when rendering. Lines of text longer than `maxWidth` will be wrapped, based on whitespace, to the next line. This allows you to do word-wrapping on BitmapText objects, something only previously possible on Text objects. -* `BitmapText.wordWrapCharCode` is a new property that works with `setMaxWidth` that allows you to control which character code causes a line-wrap. By default it is 32 (a space character). -* `ArcadePhysics.closest` now has an optional `targets` argument. The targets can be any Arcade Physics Game Object, Body or Static Body and it will return only the closet target from those given (thanks @samme) -* `ArcadePhysics.furthest` now has an optional `targets` argument. The targets can be any Arcade Physics Game Object, Body or Static Body and it will return only the furthest target from those given (thanks @samme) -* `Tilemaps.Parsers.Tiled.CreateGroupLayer` is a new function that parses a Tiled group layer and adds in support for Tiled layer groups (introduced in Tiled 1.2.0). Feature #4099 (thanks @Babeetlebum @Olliebrown) -* The Tilemap system now supports infinite Tilemaps from the Tiled map editor (thanks @Olliebrown) -* `Tilemap.getImageLayerNames` is a new method that returns a list of all valid imagelayer names loaded in the Tilemap (thanks @Olliebrown) -* `Tilemap.getObjectLayerNames` is a new method that returns a list of all valid objectgroup names loaded in the Tilemap (thanks @Olliebrown) -* `Tilemap.getTileLayerNames` is a new method that returns a list of all valid tilelayer names loaded in the Tilemap (thanks @Olliebrown) -* When `forceSetTimeOut` is set to `true` in the Game Config, you can now set the target frame rate by setting the `fps.target` value (thanks @pavels) -* Videos can now be loaded from a data URI, allowing for base64 encoded videos to be used in the Loader instead of file based ones. Although, as with all base64 encoded data, we strongly recommend against this (thanks @apasov) -* `Math.MIN_SAFE_INTEGER` is a new math const that stores the minimum safe integer for browsers that don't provide this, such as IE (thanks @jronn) -* `Math.MAX_SAFE_INTEGER` is a new math const that stores the maximum safe integer for browsers that don't provide this, such as IE (thanks @jronn) -* `KeyCodes.NUMPAD_ADD` has been added to the keycodes list (thanks @Martin-Antonov) -* `KeyCodes.NUMPAD_SUBTRACT` has been added to the keycodes list (thanks @Martin-Antonov) -* `Video.removeVideoElementOnDestroy` is a new boolean property that allows you to control if the Video element is removed from the DOM when the Video Game Object is destroyed. -* `Actions.SetScrollFactor` is a new Action that will set the scroll factor on an array of Game Objects, including stepped incremental changes per item (thanks @rexrainbow) -* `Actions.SetScrollFactorX` is a new Action that will set the horizontal scroll factor on an array of Game Objects, including stepped incremental changes per item (thanks @rexrainbow) -* `Actions.SetScrollFactorY` is a new Action that will set the horizontal scroll factor on an array of Game Objects, including stepped incremental changes per item (thanks @rexrainbow) -* The `Group` config object now supports use of the `setScrollFactor` property to set the value on each child of the Group (thanks @rexrainbow) -* `Group.propertyValueSet` is a new method that sets a given property on each Group member (thanks @rexrainbow) -* `Group.propertyValueInc` is a new method that adds an amount to a given property on each Group member (thanks @rexrainbow) -* `Group.setX` is a new method that sets the x coordinate on each Group member (thanks @rexrainbow) -* `Group.setY` is a new method that sets the y coordinate on each Group member (thanks @rexrainbow) -* `Group.setXY` is a new method that sets the x and y coordinate on each Group member (thanks @rexrainbow) -* `Group.incX` is a new method that increments the x coordinate on each Group member (thanks @rexrainbow) -* `Group.incY` is a new method that increments the y coordinate on each Group member (thanks @rexrainbow) -* `Group.incXY` is a new method that increments the x and y coordinate on each Group member (thanks @rexrainbow) -* `Group.shiftPosition` is a new method that iterates the Group members and shifts the position of each to the previous members position (thanks @rexrainbow) -* `Group.angle` is a new method that sets the angle property on each Group member (thanks @rexrainbow) -* `Group.rotate` is a new method that sets the rotation property on each Group member (thanks @rexrainbow) -* `Group.rotateAround` is a new method that rotates each Group member around the given point, by the given angle (thanks @rexrainbow) -* `Group.rotateAroundDistance` is a new method that rotates each Group member around the given point, by the given angle and distance (thanks @rexrainbow) -* `Group.setAlpha` is a new method that sets the alpha property on each Group member (thanks @rexrainbow) -* `Group.setTint` is a new method that sets the tint property on each Group member (thanks @rexrainbow) -* `Group.setOrigin` is a new method that sets the origin property on each Group member (thanks @rexrainbow) -* `Group.scaleX` is a new method that sets the x scale on each Group member (thanks @rexrainbow) -* `Group.scaleY` is a new method that sets the y scale on each Group member (thanks @rexrainbow) -* `Group.scaleXY` is a new method that sets the x and y scale on each Group member (thanks @rexrainbow) -* `Group.setBlendMode` is a new method that sets the blend mode on each Group member (thanks @rexrainbow) -* `Group.setHitArea` is a new method that passes all Group members to the Input Plugin to enable them for input (thanks @rexrainbow) -* `Group.shuffle` is a new method that shuffles all of the Group members in place (thanks @rexrainbow) -* `Group.setVisible` is a new method that sets the visible state on each Group member (thanks @rexrainbow) -* `WebAudioSoundManager.setAudioContext` is a new method that allows you to set the Sound Manager Audio Context to a different context instance. It will also disconnect and re-create the gain nodes on the new context. -* `Group.type` is a new property that holds a string-based name of the Game Object type, as with other GO's (thanks @samme) -* `Arade.Group.type` is a new property that holds a string-based name of the Game Object type, as with other GO's (thanks @samme) -* `Arcade.StaticGroup.type` is a new property that holds a string-based name of the Game Object type, as with other GO's (thanks @samme) -* `ArcadePhysics.overlapCirc` is a new method that allows you to return an array of all Arcade Physics bodies that overlap with the given circular area of the world. It can return either dynamic or static bodies, or a mixture of both (thanks @samme) - -### Updates - -* `Curve.getPoints` can now take an optional array as the 3rd parameter in which to store the points results (thanks @rexrainbow) -* `Line.arcLengthDivisions` now overrides the default Curve value and is set to 1 to optimize the amount of points returned for a Line curve (thanks @rexrainbow) -* `ArcadePhysics.closest` will now no longer ever return the source in the target results (thanks @samme) -* `ArcadePhysics.furthest` will now no longer ever return the source in the target results (thanks @samme) -* `RequestAnimationFrame.target` is a new property that controls the fps rate (in ms) when setTimeout is used (thanks @pavels) -* The `WebAudioSoundManager.unlock` method will now listen for `keydown` events in order to unlock the Audio Context, as well as touch and pointer events, making it more accessible (thanks Nick Tipping) -* The `requestAnimationFrame` polyfill no longer expects a Browserify environment and uses `window` through-out, it also no longer adds in the same as performance.now does. -* `BitmapText.getTextBounds` didn't reset the dirty flag, causing the `GetBitmapTextSize` function to be called every time the Bitmap Text was rendered. With enough text objects on-screen this could negatively impact performance. The flag is now reset every time the bounds are recalculated. - -### Bug Fixes - -* The Spine Plugin was not clearing down the resize event listener in WebGL, causing it to still fire even if the Scene was closed. Fix #4808 (thanks @RollinSafary) -* When a game is created with the HEADLESS renderer, `Game.destroy()` had no effect and the game kept on running. Now it destroys itself properly. Fix #4804 (thanks @samme) -* `DOM.GetScreenOrientation` was returning the wrong consts from the Scale Manager (thanks @jcyuan) -* When using `Input.enableDebug` on Game Objects it would not render the debug graphic correctly if the hit area had been offset. It now adjusts the debug correctly for all common hit-area geometry types. Fix #4722 (thanks @HaoboZ @Olliebrown) -* Light2D was not properly working for DynamicTilemapLayers due to a change in the way tilesets were stored, throwing an Uncaught TypeError at runtime. This is now handled correctly. Fix #4167 #4079 (thanks @koljakutschera @blackjack26 @kainage) -* `Input.dragDistanceThreshold` was not working correctly since 3.18, snapping to the wrong drag state unless the time threshold was also set. Fix #4667 (thanks @muliawanw @Olliebrown) -* `Tilemap.convertLayerToStatic` would throw an error when used multiple times, due to an error with the layer index count. Fix #4737 (thanks @Olliebrown @Vegita2) -* The `Tween` class now uses a cached MAX_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) -* The `StaggerBuilder` class now uses a cached MAX_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) -* The `Rectangle.FromPoints` function now uses a cached MIN_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) -* The `Video` class now uses a cached MIN_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) -* The `Path` class now uses a cached MIN_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) -* `Video.destroy` has been renamed to `Video.preDestroy`, so that it now destroys properly like all other Game Objects. Fix #4821 (thanks @rexrainbow) -* The Video Game Object will now check to see if the browser supports the `HTMLVideoElement` before creating one (thanks @jcyuan) -* The `DOM.GetScreenOrientation` functions would return out-dated consts (thanks @jcyuan) -* When calling `TileSprite.setTexture` or `setFrame`, if the new frame size didn't match the old one, the new fill pattern would become distorted and the `potWidth` and `potHeight` values would be incorrect. -* Timeline callbacks with extra parameters like `onStart` would miss the first parameter when the callback was invoked. Fix #4810 (thanks @samme) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@samme (for contributing loads of new Arcade Physics examples) @dranitski @jcyuan @RollinSafary @ilyaryabchinski @jsoref @jcyuan @ghclark2 - -## Version 3.20.1 - Fitoria - 15th October 2019 - -### Updates - -* The `remove-files-webpack-plugin` plugin has been moved to a devDependency (thanks @noseglid) - -### Bug Fixes - -* `UpdateList.shutdown` wasn't removing the Scene Update event listener, causing actions to be multiplied on Scene restart (such as animation playback). Fix #4799 (thanks @jronn) -* `Container.mask` wouldn't render in WebGL due to a change in the way child masks were handled. Container masking now works again as in 3.19. Fix #4803 (thanks @paulsymphony) -* `DynamicTilemapLayer.setCollision` would cause an `indexOf` error when trying to access the layer data. Fix #4800 (thanks @PavelMishin) -* `SceneManager.run` (and consequently `ScenePlugin.run`) was using an out-dated way of checking if a Scene was paused before trying to resume it, causing a Scene to be started again instead of resumed. It now uses the `Systems.isPaused` function instead. Fix #3931 (thanks @alexeymolchan) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@xSke - -## Version 3.20.0 - Fitoria - 11th October 2019 - -### Video Game Object - -This is a new Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, -or playing a video based on a given URL. Videos can be either local, or streamed: - -```javascript -preload () { - this.load.video('pixar', 'nemo.mp4'); -} - -create () { - this.add.video(400, 300, 'pixar'); -} -``` - -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 willl render -in-game with full transparency. - -You can also save a video to the Texture Manager, allowing other Game Objects to use it as their texture, -including using it as a sampler2D input for a shader. - -See the Video Game Object class for more details. Other Video related changes are as follows: - -* `Loader.FileTypes.VideoFile` is a new Video File Loader File Type, used for preloading videos as streams or blobs. -* `WebGLRenderer.createVideoTexture` is a new method that will create a WebGL Texture from the given Video Element. -* `WebGLRenderer.updateVideoTexture` is a new method that will update a WebGL Texture from the given Video Element. -* `TextureSource.isVideo` is a new boolean property that is set when the Texture Source is backed by an HTML Video Element. -* `Cache.video` is a new global cache that store loaded Video content. -* `Device.Video.h264Video` has been renamed to `Device.Video.h264` to keep it in-line with the Audio Device names. -* `Device.Video.hlsVideo` has been renamed to `Device.Video.hls` to keep it in-line with the Audio Device names. -* `Device.Video.mp4Video` has been renamed to `Device.Video.mp4` to keep it in-line with the Audio Device names. -* `Device.Video.oggVideo` has been renamed to `Device.Video.ogg` to keep it in-line with the Audio Device names. -* `Device.Video.vp9Video` has been renamed to `Device.Video.vp9` to keep it in-line with the Audio Device names. -* `Device.Video.webmVideo` has been renamed to `Device.Video.webm` to keep it in-line with the Audio Device names. - -### Spine Plugin - -* The Spine runtimes have been updated to 3.8. Please note that Spine runtimes are _not_ backwards compatible. Animations exported with Spine 3.7 (or earlier) will need re-exporting with 3.8 in order to work with the new runtimes. -* Fixed a bug with the binding of the Spine Plugin causing the GameObjectFactory to remain bound to the first instance of the plugin, causing Scene changes to result in blank Spine Game Objects. Fix #4716 (thanks @olilanz) -* Fixed a bug with the caching of the Spine Texture Atlases, causing shader errors when returning from one Scene to another with a cached Texture Atlas. -* The WebGL Scene Renderer is now only disposed if the Scene is destroyed, not just shut-down. -* The Spine Game Object will no longer set the default skin name to be 'default', it will leave the name empty. Fix #4764 (thanks @Jonchun @badlogic) -* Thanks to a fix inside the Container WebGLRenderer, a bug was crushed which involved multiple Containers in a Scene, with Spine objects, from causing run-time errors. Fix #4710 (thanks @nalgorry) -* Using `Loader.setPath` to define the Spine assets locations could error if trying to load multiple files from different folders. It will now retain the path state at the time of invocation, rather than during the load. -* When loading Spine files that used the same internal image file names, only the first file would successfully load. Now, all files load correctly. - -### Facebook Instant Games Plugin - -* Calling `showAd` or `showVideoAd` will now check to see if the ad has already been displayed, and skip it when iterating the ads array, allowing you to display an ad with the same Placement ID without preloading it again. Fix #4728 (thanks @NokFrt) -* Calling `gameStarted` in a game that doesn't load any assets would cause the error `{code: "INVALID_OPERATION", message: "Can not perform this operation before game start."}`. The plugin will now has a new internal method `gameStartedHandler` and will redirect the flow accordingly based on asset loading. Fix #4550 (thanks @bchee) -* The documentation for the `chooseContext` method has been fixed. Fix #4425 (thanks @krzysztof-grzybek) -* `Leaderboard.getConnectedScores` incorrectly specified two parameters, neither of which were used. Fix #4702 (thanks @NokFrt) -* `Leaderboard` extends Event Emitter, which was missing in the TypeScript defs. Fix #4703 (thanks @NokFrt) - -### Arcade Physics Updates - -@BenjaminDRichards and the GameFroot team contributed the following updates to Arcade Physics, which fixes 3 issues encountered when the framerate drops below 60 (technically, any time when multiple physics steps run per frame, so if physics FPS is above 60 this will also occur.) - -Issue 1: Friction starts to flip out. Objects on moving platforms get pushed ahead of the platform and "catch" on the leading edge. -Issue 2: Physics objects start to dip into the floor. In the "Before" demo, the camera is locked to the player, so this appears as the entire world starting to shake up and down. -Issue 3: When objects dip into the floor, their "rest velocity" is non-zero. This can affect debug and other logic. - -* `Body.prevFrame` is a new vector allowing a Body to distinguish between frame-length changes and step-length changes. Several steps may run for every frame, particularly when fps is low. -* `Body._reset` flag was removed and replaced it with a check of `Body.moves`. The flag only turned on when `moves` was true, and never turned off. -* Added a reset of `prev` in Arcade.Body#step. This fixes the friction issue. -* Stopped the `Body.postUpdate` method from setting `_dx`, `_dy`, and `prev`. They remain in the state they were at the end of the last physics step. This will affect the delta methods, which are documented to provide step-based data (not frame-based data); they now do so. However, because several steps may run per frame, you can't interrogate every step unless you're running functions based on physics events like collisions. You'll just see the latest step. This should partially balance out the extra load of resetting prev. -* Added a zero-out of stepsLastFrame in Arcade.World#postUpdate, which would otherwise never zero out and keep running at least one pass per frame. This should improve performance when frames can be skipped. -* Removed `blocked` checks from `TileCheckX` and `TileCheckY`. Originally, this prevented multiple checks when an object had come to rest on a floor. However, when multiple steps run per frame, the object will accelerate again, the floor won't stop it on steps 2+, and it will end the frame a short distance into the floor. Removing the blocked checks will fix the floor dip issue and the rest velocity issue. Although this opens up multiple checks, this is probably very rare: how many times does an object hit two different floors in a single frame? - -In combination these updates fix issues #4732 and #4672. My thanks to @BenjaminDRichards and @falifm. - -### New Features - -* `GameConfig.antialiasGL` is a new boolean that allows you to set the `antialias` property of the WebGL context during creation, without impacting any subsequent textures or the canvas CSS. -* `InteractiveObject.alwaysEnabled` is a new boolean that allows an interactive Game Object to always receive input events, even if it's invisible or won't render. -* `Bob.setTint` is a new method that allows you to set the tint of a Bob object within a Blitter. This is then used by the Blitter WebGL Renderer (thanks @rexrainbow) -* The `UpdateList` now emits two new events: 'add' and 'remove' when children are added and removed from it. Fix #3487 (thanks @hexus) -* The `Tilemap.setCollision` method has a new optional boolean parameter `updateLayer`. If set to `true`, it will update all of the collision settings of all tiles on the layer. If `false` it will skip doing this, which can be a huge performance boost in situations where the layer tiles haven't been modified and you're just changing collision flags. This is especially suitable for maps using procedural generated tilemaps, infinite tilemaps, multiplayer tilemaps, particularly large tilemaps (especially those dyanmic in nature) or who otherwise intend to index collisions before the tiles are loaded. This update also added the new parameter to the `SetCollision`, `SetCollisionBetween` and `DynamicTilemapLayer.setCollision` methods (thanks @tarsupin) -* `ArcadePhysics.Body.setBoundsRectangle` is a new method that allows you to set a custom bounds rectangle for any Body to use, rather than the World bounds, which is the default (thanks @francois-n-dream) -* `ArcadePhysics.Body.customBoundsRectangle` is a new property used for custom bounds collision (thanks @francois-n-dream) -* The Arcade Physics Group has a new config object property `customBoundsRectangle` which, if set, will set the custom world bounds for all Bodies that Group creates (thanks @francois-n-dream) -* `WebGLRenderer.createTexture2D` has a new optional parameter `flipY` which sets the `UNPACK_FLIP_Y_WEBGL` flag of the uploaded texture. -* `WebGLRenderer.canvasToTexture` has a new optional parameter `flipY` which sets the `UNPACK_FLIP_Y_WEBGL` flag of the uploaded texture. -* `WebGLRenderer.createCanvasTexture` is a new method that will create a WebGL Texture based on the given Canvas Element. -* `WebGLRenderer.updateCanvasTexture` is a new method that will update an existing WebGL Texture based on the given Canvas Element. -* `WebGLRenderer.createVideoTexture` is a new method that will create a WebGL Texture based on the given Video Element. -* `WebGLRenderer.updateVideoTexture` is a new method that will update an existing WebGL Texture based on the given Video Element. -* `TextureSource.flipY` is a new boolean that controls if the `UNPACK_FLIP_Y_WEBGL` flag is set when a WebGL Texture is uploaded. -* `TextureSource.setFlipY` is a new method that toggles the `TextureSource.flipY` property. - -### Updates - -* When calling `Shader.setRenderToTexture()` it will now draw the shader just once, immediately to the texture, to avoid the texture being blank for a single frame (thanks Kyle) -* The private `Shader._savedKey` property has been removed as it wasn't used anywhere internally. -* A `hasOwnProperty` check has been applied to the `SceneManager.createSceneFromObject` method when parsing additional properties in the `extend` object (thanks @halilcakar) -* The `Blitter.dirty` flag is no longer set if the render state of a Bob is changed to make it invisible (thanks @rexrainbow) -* `WebGLPipeline.addAttribute` will now automatically update the vertextComponentCount for you, without you having to do it manually any more (thanks @yhwh) -* `MultiFile` has three new internal properties: `baseURL`, `path` and `prefix` which allow them to retain the state of the loader at the time of creation, to be passed on to all child-files. Fix #4679. -* `LoaderPlugin` and `MultiFile` have a new private property `multiKeyIndex` which multi-files use and increment when batching sub-file loads. -* TileSprites will now throw a console warning if you try to use a RenderTexture or GLTexture as their frame source. Fix #4719 (thanks @pavel-shirobok) -* `TextureSource.isGLTexture` now checks if the browser supports `WebGLTexture` before checking to see if source is an instance of one. This should fix issues with Phaser in HEADLESS mode running under node / jsdom, or where WebGLTexture isn't present. Fix #4711 (thanks @tsphillips) -* `GameObject.ToJSON` will no longer output the `scaleMode` in the json because it's not a valid Game Object property. -* `TextureSource.setFilter` will now set the `scaleMode` to the given filter. -* `CanvasInterpolation` has updated the order of the CSS properties so that `crisp-edges` comes after the browser prefix versions. -* The `CanvasRenderer.scaleMode` property has been removed as it was never set or used internally. -* The `CanvasRenderer.currentScaleMode` property has been removed as it was never set or used internally. -* The `BuildGameObject` function will no longer set `scaleMode` because it's not a valid Game Object property. -* `CanvasRenderer.antialias` is a new property, populated by the game config property of the same name (or via the `pixelArt` property) that will tell the canvas renderer what to set image interpolation to during rendering of Sprites. -* `SetTransform` will now set the imageSmoothingEnabled context value based on the renderer and texture source scale mode. -* The Blitter Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. -* The Particle Emitter Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. -* The Static Tilemap Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. -* The Dynamic Tilemap Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. -* All Game Objects that use the Canvas Set Transform function (which is most of them) will aos now respect the game config anti-alias / pixel art settings and render accordingly. This means you can now have properly scaled Bitmap Text, Text, Sprites, Render Textures, etc when pixel art is enabled in your game. Fix #4701 (thanks @agar3s) -* Containers are now able to set the alpha quadrant values (topLeft, topRight, bottomLeft and bottomRight) and have these passed onto children which are capable of supporting them, such as Sprites. Fix #4714 (thanks @MrcSnm) -* The `ProcessQueue` struct now extends Event Emitter and will emit `PROCESS_QUEUE_ADD_EVENT` when a new item is added to it. -* The `ProcessQueue` struct now extends Event Emitter and will emit `PROCESS_QUEUE_REMOVE_EVENT` when an item is removed from it. -* `ProcessQueue.removeAll` is a new method that will remove all active entries from the queue. -* `ProcessQueue.length` is a new property that returns the size of the active list. -* `UpdateList` now extends the `ProcessQueue` struct and uses all of its methods for list management, instead of doing it directly. This means private properties such as `UpdateList._list` no longer exist. It also fixes an issue re: memory management where list items would remain until the end of a Scene. Fix #4721 (thanks @darkgod6) -* `BaseSoundManager.forEachActiveSound` will now only invoke the callback if the sound actually exists and isn't pending removal. Fix #3383 (thanks @DouglasLapsley) -* `MouseManager.target` can now be defined as either a string or by passing an HTMLElement directly. Fix #4353 (thanks @BigZaphod) -* The `BasePlugin.boot` method has been removed and moved to `ScenePlugin.boot` as it's a Scene-level method only (thanks @samme) -* The `BasePlugin.scene` and `BasePlugin.systems` properties have been removed and are defined in `ScenePlugin`, as they are Scene-level properties only (thanks @samme) -* The `Tween.getValue` method has been updated so you can specify the index of the Tween Data to get the value of. Previously, it only returned the first TweenData from the data array, ignoring any subsequent properties or targets. Fix #4717 (thanks @chepe263) -* `WebGLRenderer.createTexture2D` has a new optional parameter `forceSize`, which will force the gl texture creation to use the dimensions passed to the method, instead of extracting them from the pixels object, if provided. -* The `GameObject.setTexture` method can now accept either a string, in which case it looks for the texture in the Texture Manager, or a Texture instance, in which case that instance is set as the Game Object's texture. -* `TextureManager.get` can now accept either a string-based key, or a Texture instance, as its parameter. -* `SceneManager.stop` and the matching `ScenePlugin.stop` now have an optional `data` parameter, which is passed to the Scene shutdown method. Fix #4510 (thanks @Olliebrown @GetsukenStudios) -* `Cameras.BaseCamera` is now exposed in the namespace, allowing you to access them directly (thanks @rexrainbow) -* Shaders have a new optional constructor parameter `textureData` which allows you to specify additional texture data, especially for NPOT textures (thanks @cristlee) -* `TouchManager.disableContextMenu` is a new method that will try to disable the context menu on touch devices, if the Game Config `disableContextMenu` is set. Previously, it only tried to do it for the Mouse Manager, but now does it for touch as well. Fix #4778 (thanks @simplewei) - -### Bug Fixes - -* `SpineCanvasPlugin.shutdown` would try to dispose of the `sceneRenderer`, but the property isn't set for Canvas. -* `ArcadePhysics.Body.checkWorldBounds` would incorrectly report as being on the World bounds if the `blocked.none` flag had been toggled elsewhere in the Body. It now only sets if it toggles a new internal flag (thanks Pablo) -* `RenderTexture.resize` wouldn't update the CanvasTexture width and height, causing the cal to draw or drawFrame to potentially distort the texture (thanks @yhwh) -* `InputPlugin.processDragMove` has been updated so that the resulting `dragX` and `dragY` values, sent to the event handler, now compensate for the scale of the Game Objects parent container, if inside of one. This means dragging a child of a scale Container will now still drag at 'full' speed. -* The RenderTextures `displayOrigin` values are now automatically updated if you call `setSize` on the Render Texture. Fix #4757 (thanks @rexrainbow) -* `onTouchStart`, `onTouchEnd` and `onTouchMove` will now check for `event.cancelable` before calling preventDefault on the touch event, fixing issues with "Ignored attempt to cancel a touchstart event with cancelable=false, for example because scrolling is in progress and cannot be interrupted." errors in some situations. Fix #4706 (thanks @MatthewAlner) -* `MatterPhysics.shutdown` could try to access properties that may have been previously removed during the Game.destroy process, causing a console error. It now checks properties before removing events from them (thanks @nagyv) -* `ArcadePhysics.Body.hitTest` would use CircleContains to do a hit test, which assumex x/y was the Circle center, but for a Body it's the top-left, causing the hit test to be off. Fix #4748 (thanks @funnisimo) -* `ArcadePhysics.World.separateCircle` has had the velocity scaling moved to after the angle is calculated, fixing a weird collision issue when `Body.bounce=0`. Also, if both bodies are movable, they now only offset by half the offset and use the center of the body for angle calculation, allowing for any offsets to be included. Fix #4751 (thanks @funnisimo @hizzd) -* `Tween.updateTo` would break out of the TweenData iteration as soon as it adjusted the first matching key, causing tweens acting on multiple targets to only update the first target. It now updates them all. Fix #4763 (thanks @RBrNx) -* The Container WebGLRenderer will now handle child mask batching properly, based on the renderers current mask. -* The Container WebGLRenderer will now handle child new type switching, allowing you to carry on with a batch of same-type Game Objects even if they're nested within Containers. Fix #4710 (thanks @nalgorry) -* `MultiAtlasFiles` that loaded their own external images would obtain incorrect path and URL values if the path had been changed by another file in the queue. They now retain the loader state and apply it to all child files during load. -* If more than one `MultiAtlasFile` used the same internal file name for its images, subsequent multi-atlases would fail to load. Fix #4330 (thanks @giviz) -* `MultiAtlasFiles` would incorrectly add the atlas JSON into the JSON cache, causing you to not be able to destroy and reload the texture using the same atlas key as before. Fix #4720 (thanks @giviz) -* `RenderTexture.fill` wasn't setting the camera up before drawing the fill rect, causing it to appear in the wrong place and the wrong size. Fix #4390 (thanks @Jerenaux) -* `DynamicBitmapText.setOrigin` wouldn't change the origin when using the Canvas Renderer, only in WebGL. It now sets the origin regardless of renderer. Fix #4108 (thanks @garethwhittaker) -* `DynamicBitmapText` wouldn't respect the multi-line alignment values when using the Canvas Renderer. It now uses them in the line calculations. -* `DynamicBitmapText` and `BitmapText` wouldn't render at the correct position when using scaled BitmapText and an origin. Fix #4054 (thanks @Aveyder) -* Incorrect lighting on batched Sprites. The lighting was not correct when batching several sprites with different rotations. Each sprite now uses its own `uInverseRotationMatrix` to compute the lighting correctly (thanks @gogoprog) -* Matter.js Body wasn't setting the part angles correctly in `Body.update` (thanks @Frozzy6) -* `ScaleManager.startFullscreen` now checks to see if the call returns a Promise, rather than checking if the browser supports them, before waiting for promise resolution. This fixes a runtime console warning in Microsoft Edge. Fix #4795 (thanks @maksdk) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@krzysztof-grzybek @NokFrt @r-onodera @colorcube @neon-dev @SavedByZero @arnekeller - -### Thanks - -Thank you to the following people for contributing ideas for new features to be added to Phaser 3. Because we've now started Phaser 4 development, I am closing off old feature requests that I personally will not work on for Phaser 3 itself. They may be considered for v4 and, of course, if someone from the community wishes to submit a PR to add them, I will be only too happy to look at that. So, if you want to get involved, filter the GitHub issues by the [Feature Request tag](https://github.com/photonstorm/phaser/issues?q=is%3Aissue+is%3Aopen+label%3A%22%F0%9F%92%96+Feature+Request%22) and dig in. In the meantime, thank you to the following people for suggesting features, even if they didn't make it this time around: - -@njt1982 @TheTrope @allanbreyes @alexandernst @Secretmapper @murteira @oktayacikalin @TadejZupancic @SBCGames @hadikcz @jcyuan @pinkkis @Aedalus @jestarray @BigZaphod @Secretmapper @francois-n-dream @G-Rath - -## Version 3.19.0 - Naofumi - 8th August 2019 - -### Tween Updates - -* All Tween classes and functions have 100% complete JSDocs :) -* `StaggerBuilder` is a new function that allows you to define a staggered tween property. For example, as part of a tween config: `delay: this.tweens.stagger(500)` would stagger the delay by 500ms for every target of the tween. You can also provide a range: `delay: this.tweens.stagger([ 500, 1000 ])` which is spread across all targets. Finally, you can provide a Stagger Config object as the second argument. This allows you to define a stagger grid, direction, starting value and more. Please see the API Docs and new Examples for further details. -* `Tween` now extends the Event Emitter class, allowing it to emit its own events and be listened to. -* `Tween.ACTIVE_EVENT` is a new event that is dispatched when a tween becomes active. Listen to it with `tween.on('active')`. -* `Tween.COMPLETE_EVENT` is a new event that is dispatched when a tween completes or is stopped. Listen to it with `tween.on('complete')`. -* `Tween.LOOP_EVENT` is a new event that is dispatched when a tween loops, after any loop delay expires. Listen to it with `tween.on('loop')`. -* `Tween.REPEAT_EVENT` is a new event that is dispatched when a tween property repeats, after any repeat delay expires. Listen to it with `tween.on('repeat')`. -* `Tween.START_EVENT` is a new event that is dispatched when a tween starts. Listen to it with `tween.on('start')`. -* `Tween.UPDATE_EVENT` is a new event that is dispatched when a tween property updates. Listen to it with `tween.on('update')`. -* `Tween.YOYO_EVENT` is a new event that is dispatched when a tween property yoyos, after any hold delay expires. Listen to it with `tween.on('yoyo')`. -* `Tween.onActive` is a new callback that is invoked the moment the Tween Manager brings the tween to life, even though it may not have yet started actively tweening anything due to delay settings. -* `Tween.onStart` is now only invoked when the Tween actually starts tweening a value. Previously, it was invoked as soon as the Tween Manager activated the Tween. This has been recoded and this action is now handled by the `onActive` callback. Fix #3330 (thanks @wtravO) -* `Tween.seek` has been rewritten so you can now seek to any point in the Tween, regardless of repeats, loops, delays and hold settings. Seeking will not invoke any callbacks or events during the seek. Fix #4409 (thanks @cristib84) -* You can now set `from` and `to` values for a property, i.e. `alpha: { from: 0, to: 1 }` which would set the alpha of the target to 0 and then tween it to 1 _after_ any delays have expired. Fix #4493 (thanks @BigZaphod) -* You can now set `start` and `to` values for a property, i.e. `alpha: { start: 0, to: 1 }` which would set the alpha of the target to 0 immediately, as soon as the Tween becomes active, and then tween it to 1 over the duration of the tween. -* You can now set `start`, `from` and `to` values for a property, i.e. `alpha: { start: 0, from: 0.5, to: 1 }` which would set the alpha of the target to 0 immediately, as soon as the Tween becomes active, then after any delays it would set the alpha to 0.5 and then tween it to 1 over the duration of the Tween. -* `Tween.hasStarted` is a new property that holds a flag signifying if the Tween has started or not. A Tween that has started is one that is actively tweening a property and not just in a delayed state. -* `Tween.startDelay` is a new property that is set during the Tween init to hold the shortest possible time before the Tween will start tweening a value. It is decreased each update until it hits zero, after which the `onStart` callback is invoked. -* `Tween.init` and `Tween.play` have been rewritten so they are not run multiple times when a Tween is paused before playback, or is part of a Timeline. This didn't cause any problems previously, but it was a redundant duplication of calls. -* `Tween.onLoop` will now be invoked _after_ the `loopDelay` has expired, if any was set. -* `Tween.onRepeat` will now be invoked _after_ the `repeatDelay` has expired, if any was set. -* `easeParams` would be ignored for tweens that _didn't_ use a string for the ease function name. Fix #3826 (thanks @SBCGames) -* You can now specify `easeParams` for any custom easing function you wish to use. Fix #3826 (thanks @SBCGames) -* All changes to `Tween.state` are now set _before_ any events or callbacks, allowing you to modify the state of the Tween in those handlers (thanks @Cudabear) -* `Tween.dispatchTweenEvent` is a new internal method that handles dispatching the new Tween Events and callbacks. This consolidates a lot of duplicate code into a single method. -* `Tween.dispatchTweenDataEvent` is a new internal method that handles dispatching the new TweenData Events and callbacks. This consolidates a lot of duplicate code into a single method. -* `Tween.isSeeking` is a new internal boolean flag that is used to keep track of the seek progress of a Tween. -* `Timeline.onLoop` will now be invoked _after_ the `loopDelay` has expired, if any was set. -* `Timeline.onComplete` will now be invoked _after_ the `completeDelay` has expired, if any was set. -* All changes to `Timeline.state` are now set _before_ any events or callbacks, allowing you to modify the state of the Timeline in those handlers. -* The `TIMELINE_LOOP_EVENT` has had the `loopCounter` argument removed from it. It didn't actually send the number of times the Timeline had looped (it actually sent the total remaining). -* When a TweenData completes it will now set the `current` property to be exactly either `start` or `end` depending on playback direction. -* When a TweenData completes it will set the exact `start` or `end` value into the target property. -* `TweenData` has a new function signature, with the new `index` and `getActive`arguments added to it. `TweenBuilder` has been updated to set these, but if you create any TweenData objects directly, use the new signature. -* `TweenData.getActiveValue` is a new property that, if not null, returns a value to immediately sets the property value to on activation. -* `GetEaseFunction`, and by extension anything that uses it, such as setting the ease for a Tween, will now accept a variety of input strings as valid. You can now use lower-case, such as `back`, and omit the 'ease' part of the direction, such as `back.in` or `back.inout`. -* The signature of `getStart` and `getEnd` custom property functions has changed to `(target, key, value, targetIndex, totalTargets, tween)`, previously it was just `(target, key, value)`. Custom functions don't need to change as the new arguments are in addition to those sent previously. -* The signature of the LoadValue generator functions (such as `delay` and `repeat`) has changed to `(target, key, value, targetIndex, totalTargets, tween)` to match those of the custom property functions. If you used a custom generator function for your Tween configs you'll need to modify the signature to the new one. -* Tweens created via `TweenManager.create` wouldn't start when `Tween.play` was called without first making them active manually. They now start automatically. Fix #4632 (thanks @mikewesthad) - -### Spine Updates - -The Spine Plugin is now 100% complete. It has been updated to use the Spine 3.7 Runtimes. Improvements have been made across the entire plugin, including proper batched rendering support in WebGL, cleaner skin and slot functions and lots and lots of updates. It's fully documented and there are lots of examples to be found. The following legacy bugs have also been fixed: - -* Adding Spine to physics causes position to become NaN. Fix #4501 (thanks @hizzd) -* Destroying a Phaser Game instance and then re-creating it would cause an error trying to re-create Spine Game Objects ("Cannot read property get of null"). Fix #4532 (thanks @Alex-Badea) -* Rendering a Spine object when a Camera has `renderToTexture` enabled on it would cause the object to be vertically flipped. It now renders correctly in both cases. Fix #4647 (thanks @probt) - -### New Features - -* `Shader.setRenderToTexture` is a new method that will redirect the Shader to render to its own framebuffer / WebGLTexture instead of to the display list. This allows you to use the output of the shader as an input for another shader, by mapping a sampler2D uniform to it. It also allows you to save the Shader to the Texture Manager, allowing you to use it as a texture for any other texture based Game Object such as a Sprite. -* `Shader.setSampler2DBuffer` is a new method that allows you to pass a WebGLTexture directly into a Shader as a sampler2D uniform, such as when linking shaders together as buffers for each other. -* `Shader.renderToTexture` is a new property flag that is set if you set the Shader to render to a texture. -* `Shader.framebuffer` is a new property that contains a WebGLFramebuffer reference which is set if you set the Shader to render to a texture. -* `Shader.glTexture` is a new property that contains a WebGLTexture reference which is set if you set the Shader to render to a texture. -* `Shader.texture` is a new property that contains a Phaser Texture reference which is set if you set the Shader to save to the Texture Manager. -* `TextureManager.addGLTexture` is a new method that allows you to add a WebGLTexture directly into the Texture Manager, saved under the given key. -* `TextureSource.isGLTexture` is a new boolean property that reflects if the data backing the underlying Texture Source is a WebGLTexture or not. -* `TextureTintPipeline.batchSprite` will now flip the UV if the TextureSource comes from a GLTexture. -* `Math.ToXY` is a new mini function that will take a given index and return a Vector2 containing the x and y coordinates of that index within a grid. -* `RenderTexture.glTexture` is a new property that holds a reference to the WebGL Texture being used by the Render Texture. Useful for passing to a shader as a sampler2D. -* `GroupCreateConfig.quantity` - when creating a Group using a config object you can now use the optional property `quantity` to set the number of objects to be created. Use this for quickly creating groups of single frame objects that don't need the advanced capabilities of `frameQuantity` and `repeat`. -* `Pointer.locked` is a new read-only property that indicates if the pointer has been Pointer Locked, or not, via the Pointer Lock API. -* `WebGLRenderer.snapshotFramebuffer`, and the corresponding utility function `WebGLSnapshot`, allows you to take a snapshot of a given WebGL framebuffer, such as the one used by a Render Texture or Shader, and either get a single pixel from it as a Color value, or get an area of it as an Image object, which can then optionally be saved to the Texture Manager for use by Game Object textures. -* `CanvasRenderer.snapshotCanvas` allows you to take a snapshot of a given Canvas object, such as the one used by a Render Texture, and either get a single pixel from it as a Color value, or get an area of it as an Image object, which can then optionally be saved to the Texture Manager for use by Game Object textures. -* `RenderTexture.snapshot` is a new method that will take a snapshot of the whole current state of the Render Texture and return it as an Image object, which could then be saved to the Texture Manager if needed. -* `RenderTexture.snapshotArea` is a new method that will take a snapshot of an area of a Render Texture and return it as an Image object, which could then be saved to the Texture Manager if needed. -* `RenderTexture.snapshotPixel` is a new method that will take extract a single pixel color value from a Render Texture and return it as a Color object. -* The `SnapshotState` object has three new properties: `isFramebuffer` boolean and `bufferWidth` and `bufferHeight` integers. -* `Game.CONTEXT_LOST_EVENT` is a new event that is dispatched by the Game instance when the WebGL Renderer webgl context is lost. Use this instead of the old 'lostContextCallbacks' for cleaner context handling. -* `Game.CONTEXT_RESTORED_EVENT` is a new event that is dispatched by the Game instance when the WebGL Renderer webgl context is restored. Use this instead of the old 'restoredContextCallbacks' for cleaner context handling. -* `WebGLRenderer.currentType` contains the type of the Game Object currently being rendered. -* `WebGLRenderer.newType` is a boolean that indicates if the current Game Object has a new type, i.e. different to the previous one in the display list. -* `WebGLRenderer.nextTypeMatch` is a boolean that indicates if the _next_ Game Object in the display list has the same type as the one being currently rendered. This allows you to build batching into separated Game Objects. -* `PluginManager.removeGameObject` is a new method that allows you to de-register custom Game Object types from the global Game Object Factory and/or Creator. Useful for when custom plugins are destroyed and need to clean-up after themselves. -* `GEOM_CONST` is a new constants object that contains the different types of Geometry Objects, such as `RECTANGLE` and `CIRCLE`. -* `Circle.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `Ellipse.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `Line.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `Point.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `Polygon.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `Rectangle.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `Triangle.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. -* `InputPlugin.enableDebug` is a new method that will create a debug shape for the given Game Objects hit area. This allows you to quickly check the size and placement of an input hit area. You can customzie the shape outline color. The debug shape will automatically track the Game Object to which it is bound. -* `InputPlugion.removeDebug` will remove a Debug Input Shape from the given Game Object and destroy it. -* `Pointer.updateWorldPoint` is a new method that takes a Camera and then updates the Pointers `worldX` and `worldY` values based on the cameras transform (thanks @Nick-lab) -* `ScaleManager._resetZoom` is a new internal flag that is set when the game zoom factor changes. -* `Texture.remove` is a new method that allows you to remove a Frame from a Texture based on its name. Fix #4460 (thanks @BigZaphod) - -### Updates - -* When calling `setHitArea` and not providing a shape (i.e. a texture based hit area), it will now set `customHitArea` to `false` by default (thanks @rexrainbow) -* The Shader will no longer set uniforms if the values are `null`, saving on GL ops. -* The Animation Manager will now emit a console warning if you try and play an animation on a Sprite that doesn't exist. -* The Animation component will no longer start an animation on a Sprite if the animation doesn't exist. Previously it would throw an error saying "Unable to read the property getFirstTick of null". -* `InputManager.onPointerLockChange` is a new method that handles pointer lock change events and dispatches the lock event. -* `CanvasTexture` has been added to the `Textures` namespace so it can be created without needing to import it. The correct way to create a `CanvasTexture` is via the Texture Manager, but you can now do it directly if required. Fix #4651 (thanks @Jugacu) -* The `SmoothedKeyControl` minimum zoom a Camera can go to is now 0.001. Previously it was 0.1. This is to make it match the minimum zoom a Base Camera can go to. Fix #4649 (thanks @giviz) -* `WebGLRenderer.lostContextCallbacks` and the `onContextLost` method have been removed. Please use the new `CONTEXT_LOST` event instead. -* `WebGLRenderer.restoredContextCallbacks` and the `onContextRestored` method have been removed. Please use the new `CONTEXT_RESTORED` event instead. -* `TextureManager.getBase64` will now emit a console warning if you try to get a base64 from a non-image based texture, such as a WebGL Texture. -* The `WebAudioSoundManager` will now remove the document touch handlers even if the Promise fails, preventing it from throwing a rejection handler error. -* `GameObjectFactory.remove` is a new static function that will remove a custom Game Object factory type. -* `GameObjectCreator.remove` is a new static function that will remove a custom Game Object creator type. -* `CanvasTexture.getPixels` now defaults to 0x0 by width x height as the default area, allowing you to call the method with no arguments to get all the pixels for the canvas. -* `CreateDOMContainer` will now use `div.style.cssText` to set the inline styles of the container, so it now works on IE11. Fix #4674 (thanks @DanLiamco) -* `TransformMatrix.rotation` now returns the properly normalized rotation value. -* `PhysicsEditorParser` has now been exposed under the `Phaser.Physics.Matter` namespace, so you can call methods on it directly. -* Calling `CanvasTexture.update` will now automatically call `refresh` if running under WebGL. This happens for both `draw` and `drawFrame`, meaning you no longer need to remember to call `refresh` after drawing to a Canvas Texture in WebGL, keeping it consistent with the Canvas renderer. -* `Frame.destroy` will now null the Frames reference to its parent texture, glTexture and clear the data and customData objects. -* The Container renderer functions will now read the childs `alpha` property, instead of `_alpha`, allowing it to work with more variety of custom children. - -### Bug Fixes - -* The Scale Manager would throw the error 'TypeError: this.removeFullscreenTarget is not a function' when entering full-screen mode. It would still enter fullscreen, but the error would appear in the console. Fix #4605 (thanks @darklightcode) -* `Tilemap.renderDebug` was calling out-dated Graphics API methods, which would cause the debug to fail (thanks @Fabadiculous) -* The `Matter.Factory.constraint`, `joint` and `worldConstraint` methods wouldn't allow a zero length constraint to be created due to a falsey check of the length argument. You can now set length to be any value, including zero, or leave it undefined to have it automatically calculated (thanks @olilanz) -* `Pointer.getDuration` would return a negative / static value on desktop, or NaN on mobile, because the base time wasn't being pulled in from the Input Manager properly. Fix #4612 (thanks @BobtheUltimateProgrammer) -* `Pointer.downTime`, `Pointer.upTime` and `Pointer.moveTime` would be set to NaN on mobile browsers where Touch.timeStamp didn't exist. Fix #4612 (thanks @BobtheUltimateProgrammer) -* `WebGLRenderer.setScissor` will default the `drawingBufferHeight` if no argument is provided, stopping NaN scissor heights. -* If you called `Scene.destroy` within a Game Object `pointerdown` or `pointerup` handler, it would cause the error "Cannot read property 'game' of null" if the event wasn't cancelled in your handler. It now checks if the manager is still there before accessing its property. Fix #4436 (thanks @jcyuan) -* The `Arc / Circle` Game Object wasn't rendering centered correctly in WebGL due to an issue in a previous size related commit, it would be half a radius off. Fix #4620 (thanks @CipSoft-Components @rexrainbow) -* Destroying a Scene in HEADLESS mode would throw an error as it tried to access the gl renderer in the Camera class. Fix #4467 (thanks @AndreaBoeAbrahamsen @samme) -* `Tilemap.createFromObjects` would ignore the `scene` argument passed in to the method. It's now used (thanks @samme) -* Fixed a bug in the WebGL and Canvas Renderers where a Sprite with a `flipX` or `flipY` value set would render the offset frames slightly out of place, causing the animation to appear jittery. Also, the sprite would be out of place by its origin. Fix #4636 #3813 (thanks @jronn @B3L7) -* Animations with custom pivots, like those created in Texture Packer with the pivot option enabled, would be mis-aligned if flipped. They now render in the correct position, regardless of scale or flip on either axis. Fix #4155 (thanks @Zax37) -* Removing a frame from a 2 frame animation would cause an error when a Sprite using that animation next tried to render. Fix #4621 (thanks @orlicgms) -* Calling `Animation.setRepeat()` wouldn't reset the `repeatCounter` properly, causing Sprite bound animation instances to fail to change their repeat rate. Fix #4553 (thanks @SavedByZero) -* The `UpdateList.remove` method wouldn't flag the Game Object for removal properly if it was active. It now checks that the Game Object is in the current update list and hasn't already been inserted into the 'pending removal' list before flagging it. Fix #4544 (thanks @jcyuan) -* `DynamicTilemapLayer.destroy` will now no longer run its destroy sequence again if it has already been run once. Fix #4634 (thanks @CipSoft-Components) -* `StaticTilemapLayer.destroy` will now no longer run its destroy sequence again if it has already been run once. -* `Shader.uniforms` now uses Extend instead of Clone to perform a deep object copy, instead of a shallow one, avoiding multiple instances of the same shader sharing uniforms. Fix #4641 (thanks @davidmball) -* Calling `input.mouse.requestPointerLock()` will no longer throw an error about being unable to push to the Input Manager events queue. -* The `POINTERLOCK_CHANGE` event is now dispatched by the Input Manager again. -* The `Pointer.movementX` and `Pointer.movementY` properties are now taken directly from the DOM pointer event values, if the pointer is locked, and no longer incremental. Fix #4611 (thanks @davidmball) -* The `Pointer.velocity` and `Pointer.midPoint` values are now updated every frame. Based on the `motionFactor` setting they are smoothed towards zero, for velocity, and the pointer position for the mid point. This now happens regardless if the Pointer moves or not, which is how it was originally intended to behave. -* The `DESTROY` event hook wasn't removed from Group children when destroying the Group and `destroyChildren` was set to false. Now, the hook is removed regardless (thanks @rexrainbow) -* The WebGL Lost and Restored Context callbacks were never removed, which could cause them to hold onto stale references. Fix #3610 (thanks @Twilrom) -* `Origin.updateDisplayOrigin` no longer applies a Math.floor to the display origins, allowing you to have a 0.x origin for a Game Object that only has a width or height of 1. This fixes issues with things like 1x1 rectangles displaying incorrectly during rendering. Fix #4126 (thanks @rexrainbow) -* `InputManager.resetCursor` will now check if the canvas element still exists before resetting the cursor on it. Fix #4662 (thanks @fromnowhereuser) -* It was not possible to set the zoom value of the Scale Manager back to 1 again, having changed it to a different value. Fix #4633 (thanks @lgibson02 @BinaryMoon) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@vacarsu @KennethGomez @samme @ldd @Jazcash @jcyuan @LearningCode2023 @PhaserEditor2D - -## Version 3.18.1 - Raphtalia - 20th June 2019 - -### Bug Fixes - -* `InputManager.preRender` didn't get the `time` property correctly, causing input plugin methods that relied on it to fail. -* `KeyboardPlugin.time` wasn't being set to the correct value, causing `checkDown` to fail constantly. - -## Version 3.18.0 - Raphtalia - 19th June 2019 - -### Input System Changes - -#### Mouse Wheel Support - -3.18 now includes native support for reading mouse wheel events. - -* `POINTER_WHEEL` is a new event dispatched by the Input Plugin allowing you to listen for global wheel events. -* `GAMEOBJECT_WHEEL` is a new event dispatched by the Input Plugin allowing you to listen for global wheel events over all interactive Game Objects in a Scene. -* `GAMEOBJECT_POINTER_WHEEL` is a new event dispatched by a Game Object allowing you to listen for wheel events specifically on that Game Object. -* `Pointer.deltaX` is a new property that holds the horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. -* `Pointer.deltaY` is a new property that holds the vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. -* `Pointer.deltaZ` is a new property that holds the z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. -* `Pointer.wheel` is a new internal method that handles the wheel event. -* `InputManager.onMouseWheel` is a new internal method that handles processing the wheel event. -* `InputManager.processWheelEvent` is a new internal method that handles processing the wheel event sent by the Input Manager. - -#### Button Released Support - -* `Pointer.button` is a new property that indicates which button was pressed, or released, on the pointer during the most recent event. It is only set during `up` and `down` events and is always 0 for Touch inputs. -* `Pointer.leftButtonReleased` is a new method that returns `true` if it was the left mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. -* `Pointer.rightButtonReleased` is a new method that returns `true` if it was the right mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released (thanks @BobtheUltimateProgrammer) -* `Pointer.middleButtonReleased` is a new method that returns `true` if it was the middle mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. -* `Pointer.backButtonReleased` is a new method that returns `true` if it was the back mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. -* `Pointer.forwardButtonReleased` is a new method that returns `true` if it was the forward mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. - -#### Input System Bug Fixes - -* Calling `setPollAlways()` would cause the `'pointerdown'` event to fire multiple times. Fix #4541 (thanks @Neyromantik) -* The pointer events were intermittently not registered, causing `pointerup` to often fail. Fix #4538 (thanks @paulsymphony) -* Due to a regression in 3.16 the drag events were not performing as fast as before, causing drags to feel lagged. Fix #4500 (thanks @aliblong) -* The Touch Manager will now listen for Touch Cancel events on the Window object (if `inputWindowEvents` is enabled in the game config, which it is by default). This allows it to prevent touch cancel actions, like opening the dock on iOS, from causing genuinely active pointers to enter an active locked state. -* Over and Out events now work for any number of pointers in multi-touch environments, not just the first touch pointer registered. They also now fire correctly on touch start and touch end / cancel events. -* If you enable a Game Object for drag and place it inside a rotated Container (of any depth), the `dragX` and `dragY` values sent to the `drag` callback didn't factor the rotation in, so you had to do it manually. This is now done automatically, so the values account for parent rotation before being sent to the event handler. Fix #4437 (thanks @aliblong) - -#### Input System API Changes - -The old 'input queue' legacy system, which was deprecated in 3.16, has been removed entirely in order to tidy-up the API and keep input events consistent. This means the following changes: - -* Removed the `inputQueue` Game config property. -* Removed the `useQueue`, `queue` and `_updatedThisFrame` properties from the Input Manager. -* Removed the `legacyUpdate` and `update` methods from the Input Manager. -* Removed the `ignoreEvents` property as this should now be handled on a per-event basis. -* The Input Manager no longer listens for the `GameEvents.POST_STEP` event. -* The following Input Manager methods are no longer required so have been removed: `startPointer`, `updatePointer`, `stopPointer` and `cancelPointer`. - -As a result, all of the following Input Manager methods have been renamed: - -* `queueTouchStart` is now called `onTouchStart` and invoked by the Touch Manager. -* `queueTouchMove` is now called `onTouchMove` and invoked by the Touch Manager. -* `queueTouchEnd` is now called `onTouchEnd` and invoked by the Touch Manager. -* `queueTouchCancel` is now called `onTouchCancel` and invoked by the Touch Manager. -* `queueMouseDown` is now called `onMouseDown` and invoked by the Mouse Manager. -* `queueMouseMove` is now called `onMouseMove` and invoked by the Mouse Manager. -* `queueMouseUp` is now called `onMouseUp` and invoked by the Mouse Manager. - -Each of these handlers used to check the `enabled` state of the Input Manager, but this now handled directly in the Touch and Mouse Managers instead, leading to less branching and cleaner tests. They also all used to run an IIFE that updated motion on the changed pointers array, but this is now handled directly in the event handler, allowing it to be removed from here. - -Because the legacy queue mode is gone, there is no longer any need for the DOM Callbacks: - -* Removed the `_hasUpCallback`, `_hasDownCallback` and `_hasMoveCallback` properties from the Input Manager -* Removed the `processDomCallbacks`, `addDownCallback`, `addUpCallback`, `addMoveCallback`, `domCallbacks`, `addDownCallback`, `addUpCallback` and `addMoveCallback` methods. - -Also, CSS cursors can now be set directly: - -* Cursors are now set and reset immediately on the canvas, leading to the removal of `_setCursor` and `_customCursor` properties. - -The following changes took place in the Input Plugin class: - -* The method `processDragEvents` has been removed as it's now split across smaller, more explicit methods. -* `processDragDownEvent` is a new method that handles a down event for drag enabled Game Objects. -* `processDragMoveEvent` is a new method that handles a move event for drag enabled Game Objects. -* `processDragUpEvent` is a new method that handles an up event for drag enabled Game Objects. -* `processDragStartList` is a new internal method that builds a drag list for a pointer. -* `processDragThresholdEvent` is a new internal method that tests when a pointer with drag thresholds can drag. -* `processOverEvents` is a new internal method that handles when a touch pointer starts and checks for over events. -* `processOutEvents` is a new internal method that handles when a touch pointer stops and checks for out events. - -The following changes took place in the Pointer class: - -* `Pointer.dirty` has been removed as it's no longer required. -* `Pointer.justDown` has been removed as it's not used internally and makes no sense under the DOM event system. -* `Pointer.justUp` has been removed as it's not used internally and makes no sense under the DOM event system. -* `Pointer.justMoved` has been removed as it's not used internally and makes no sense under the DOM event system. -* The `Pointer.reset` method has been removed as it's no longer required internally. -* `Pointer.touchstart` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). -* `Pointer.touchmove` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). -* `Pointer.touchend` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). -* `Pointer.touchcancel` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). - -### New Features - -* `Matter.Factory.velocity` is a new method that allows you to set the velocity on a Matter Body directly. -* `Matter.Factory.angularVelocity` is a new method that allows you to set the angular velocity on a Matter Body directly. -* `Matter.Factory.force` is a new method that allows you to apply a force from a world position on a Matter Body directly. -* `GetBounds.getTopCenter` is a new method that will return the top-center point from the bounds of a Game Object. -* `GetBounds.getBottomCenter` is a new method that will return the bottom-center point from the bounds of a Game Object. -* `GetBounds.getLeftCenter` is a new method that will return the left-center point from the bounds of a Game Object. -* `GetBounds.getRightCenter` is a new method that will return the right-center point from the bounds of a Game Object. -* You can now create a desynchronized 2D or WebGL canvas by setting the Game Config property `desynchronized` to `true` (the default is `false`). For more details about what this means see https://developers.google.com/web/updates/2019/05/desynchronized. -* The CanvasRenderer can now use the `transparent` Game Config property in order to tell the browser an opaque background is in use, leading to faster rendering in a 2D context. -* `GameObject.scale` is a new property, that exists as part of the Transform component, that allows you to set the horizontal and vertical scale of a Game Object via a setter, rather than using the `setScale` method. This is handy for uniformly scaling objects via tweens, for example. -* `Base64ToArrayBuffer` is a new utility function that will convert a base64 string into an ArrayBuffer. It works with plain base64 strings, or those with data uri headers attached to them. The resulting ArrayBuffer can be fed to any suitable function that may need it, such as audio decoding. -* `ArrayBufferToBase64` is a new utility function that converts an ArrayBuffer into a base64 string. You can also optionally included a media type, such as `image/jpeg` which will result in a data uri being returned instead of a plain base64 string. -*`WebAudioSoundManager.decodeAudio` is a new method that allows you to decode audio data into a format ready for playback and stored in the audio cache. The audio data can be provided as an ArrayBuffer, a base64 string or a data uri. Listen for the events to know when the data is ready for use. -* `Phaser.Sound.Events#DECODED` is a new event emitted by the Web Audio Sound Manager when it has finished decoding audio data. -* `Phaser.Sound.Events#DECODED_ALL` is a new event emitted by the Web Audio Sound Manager when it has finished decoding all of the audio data files passed to the `decodeAudio` method. -* `Phaser.Utils.Objects.Pick` is a new function that will take an object and an array of keys and return a new object containing just the keys provided in the array. -* `Text.align` and `Text.setAlign` can now accept `justify` as a type. It will apply basic justification to multi-line text, adding in extra spaces in order to justify the content. Fix #4291 (thanks @andrewbaranov @Donerkebap13 @dude78GH) -* `Arcade.Events.WORLD_STEP` is a new event you can listen to. It is emitted by the Arcade Physics World every time the world steps once. It is emitted _after_ the bodies and colliders have been updated. Fix #4289 (thanks @fant0m) - -### Updates - -* `Zones` will now use the new `customHitArea` property introduced in 3.17 to avoid their hit areas from being resized if you specified your own custom hit area (thanks @rexrainbow) -* The default `BaseShader` vertex shader has a new uniform `uResolution` which is set during the Shader init and load to be the size of the Game Object to which the shader is bound. -* The default `BaseShader` vertex shader will now set the `fragCoord` varying to be the Game Object height minus the y inPosition. This will give the correct y axis in the fragment shader, causing 'inverted' shaders to display normally when using the default vertex code. -* There was some test code left in the `DOMElementCSSRenderer` file that caused `getBoundingClientRect` to be called every render. This has been removed, which increases performance significantly for DOM heavy games. -* The `TimeStep` will no longer set its `frame` property to zero in the `resetDelta` method. Instead, this property is incremented every step, no matter what, giving an accurate indication of exactly which frame something happened on internally. -* The `TimeStep.step` method no longer uses the time value passed to the raf callback, as it's not actually the current point in time, but rather the time that the main thread began at. Which doesn't help if we're comparing it to event timestamps. -* `TimeStep.now` is a new property that holds the exact `performance.now` value, as set at the start of the current game step. -* `Matter.Factory.fromVertices` can now take a vertices path string as its `vertexSets` argument, as well as an array of vertices. -* `GetBounds.prepareBoundsOutput` is a new private method that handles processing the output point. All of the bounds methods now use this, allowing us to remove a lot of duplicated code. -* The PluginManager will now display a console warning if it skips installing a plugin (during boot) because the plugin value is missing or empty (thanks @samme) -* When creating a Matter Constraint via the Factory you can now optionally provide a `length`. If not given, it will determine the length automatically from the position of the two bodies. -* When creating a Matter Game Object you can now pass in a pre-created Matter body instead of a config object. -* When Debug Draw is enabled for Arcade Physics it will now use `Graphics.defaultStrokeWidth` to drawn the body with, this makes static bodies consistent with dynamic ones (thanks @samme) -* `Group.name` is a new property that allows you to set a name for a Group, just like you can with all other Game Objects. Phaser itself doesn't use this, it's there for you to take advantage of (thanks @samme) -* Calling `ScaleManager.setGameSize` will now adjust the size of the canvas element as well. Fix #4482 (thanks @sudhirquestai) -* `Scale.Events.RESIZE` now sends two new arguments to the handler: `previousWidth` and `previousHeight`. If, and only if, the Game Size has changed, these arguments contain the previous size, before the change took place. -* The Camera Manager has a new method `onSize` which is invoked by handling the Scale Manager `RESIZE` event. When it receives it, it will iterate the cameras it manages. If the camera _doesn't_ have a custom offset and _is_ the size of the game, then it will be automatically resized for you. This means you no longer need to call `this.cameras.resize(width, height)` from within your own resize handler, although you can still do so if you wish, as that will resize _every_ Camera being managed to the new size, instead of just 'full size' cameras. -* `Graphics.translate` has been renamed to `Graphics.translateCanvas` to make it clearer what it's actually translating (i.e. the drawing buffer, not the Graphics object itself) -* `Graphics.scale` has been renamed to `Graphics.scaleCanvas` to make it clearer what it's actually scaling (i.e. the drawing buffer, not the Graphics object itself) -* `Graphics.rotate` has been renamed to `Graphics.rotateCanvas` to make it clearer what it's actually rotating (i.e. the drawing buffer, not the Graphics object itself) -* The `width` and `height` of an Arc / Circle Shape Game Object is now set to be the diameter of the arc, not the radius (thanks @rexrainbow) -* `LineStyleCanvas` now takes an `altColor` argument which is used to override the context color. -* `LineStyleCanvas` now takes an `altAlpha` argument which is used to override the context alpha. -* `FillStyleCanvas` now takes an `altAlpha` argument which is used to override the context alpha. -* `StaticPhysicsGroup` can now take a `classType` property in its Group Config and will use the value of it, rather than override it. If none is provided it'll default to `ArcadeSprite`. Fix #4401 (thanks @Legomite) -* `Phaser.Tilemaps.Parsers.Tiled` used to run the static function `ParseJSONTiled`. `Parsers.Tiled` is now just a namespace, so access the function within it: `Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled`. -* `Phaser.Tilemaps.Parsers.Impact` used to run the static function `ParseWeltmeister`. `Parsers.Impact` is now just a namespace, so access the function within it: `Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister`. -* `Phaser.Tilemaps.Parsers.Tiled.AssignTileProperties` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.Base64Decode` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.BuildTilesetIndex` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseGID` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseImageLayers` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseObject` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseObjectLayers` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseTileLayers` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseTilesets` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.ParseTilesets` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Impact.ParseTileLayers` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Impact.ParseTilesets` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister` is now a public static function, available to be called directly. -* `Phaser.Tilemaps.Parsers.Tiled.Pick` has been removed. It is now available under `Phaser.Utils.Objects.Pick`, which is a more logical place for it. -* You can now call `this.scene.remove` at the end of a Scene's `create` method without it throwing an error. Why you'd ever want to do this is beyond me, but you now can (thanks @samme) -* The `Arcade.StaticBody.setSize` arguments have changed from `(width, height, offsetX, offsetY)` to `(width, height, center)`. They now match Dynamic Body setSize and the Size Component method (thanks @samme) -* When enabling Arcade Physics Body debug it will now draw only the faces marked for collision, allowing you to easily see if a face is disabled or not (thanks @BdR76) -* `Transform.getParentRotation` is a new method available to all GameObjects that will return the sum total rotation of all of the Game Objects parent Containers, if it has any. -* `Tween.restart` now sets the Tween properties `elapsed`, `progress`, `totalElapsed` and `totalProgress` to zero when called, rather than adding to existing values should the tween already be running. -* `ArcadePhysics.Body.resetFlags` is a new method that prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. -* `ArcadePhysics.Body.preUpdate` has two new arguments `willStep` and `delta`. If `willStep` is true then the body will call resetFlags, sync with the parent Game Object and then run one iteration of `Body.update`, using the provided delta. If false, only the Game Object sync takes place. -* `ArcadePhysics.World.update` will now determine if a physics step is going to happen this frame or not. If not, it no longer calls `World.step` (fix #4529, thanks @ampled). If a step _is_ going to happen, then it now handles this with one iteration of the bodies array, instead of two. It has also inlined a single world step, avoiding branching out. If extra world steps are required this frame (such as in high Hz environments) then `World.step` is called accordingly. -* `ArcadePhysics.World.postUpdate` will no longer call `Body.postUpdate` on all of the bodies if no World step has taken place this frame. -* `ArcadePhysics.World.step` will now increment the `stepsLastFrame` counter, allowing `postUpdate` to determine if bodies should be processed should World.step have been invoked manually. - -### Bug Fixes - -* Tweens created in a paused state couldn't be started by a call to `play`. Fix #4525 (thanks @TonioParis) -* If both Arcade Physics circle body positions and the delta equaled zero, the `separateCircle` function would cause the position to be set `NaN` (thanks @hizzd) -* The `CameraManager` would incorrectly destroy the `default` Camera in its shutdown method, meaning that if you used a fixed mask camera and stopped then resumed a Scene, the masks would stop working. The default camera is now destroyed only in the `destroy` method. Fix #4520 (thanks @telinc1) -* Passing a Frame object to `Bob.setFrame` would fail, as it expected a string or integer. It now checks the type of object, and if a Frame it checks to make sure it's a Frame belonging to the parent Blitter's texture, and if so sets it. Fix #4516 (thanks @NokFrt) -* The ScaleManager full screen call had an arrow function in it. Despite being within a conditional block of code it still broke really old browsers like IE11, so has been removed. Fix #4530 (thanks @jorbascrumps @CNDW) -* `Game.getTime` would return `NaN` because it incorrectly accessed the time value from the TimeStep. -* Text with a `fixedWidth` or `fixedHeight` could cause the canvas to be cropped if less than the size of the Text itself (thanks @rexrainbow) -* Changing the `radius` of an Arc Game Object wouldn't update the size, causing origin issues. It now updates the size and origin correctly in WebGL. Fix #4542 (thanks @@PhaserEditor2D) -* Setting `padding` in a Text style configuration object would cause an error about calling split on undefined. Padding can now be applied both in the config and via `setPadding`. -* `Tilemap.createBlankDynamicLayer` would fail if you provided a string for the tileset as the base tile width and height were incorrectly read from the tileset argument. Fix #4495 (thanks @jppresents) -* `Tilemap.createDynamicLayer` would fail if you called it without setting the `x` and `y` arguments, even though they were flagged as being optional. Fix #4508 (thanks @jackfreak) -* `RenderTexture.draw` didn't work if no `x` and `y` arguments were provided, even though they are optional, due to a problem with the way the frame cut values were added. The class has been refactored to prevent this, fixing issues like `RenderTexture.erase` not working with Groups. Fix #4528 (thanks @jbgomez21 @telinc1) -* The `Grid` Game Object wouldn't render in Canvas mode at all. Fix #4585 (thanks @fyyyyy) -* If you had a `Graphics` object in the display list immediately after an object with a Bitmap Mask it would throw an error `Uncaught TypeError: Cannot set property 'TL' of undefined`. Fix #4581 (thanks @Petah @Loonride) -* Calling Arcade Physics `Body.reset` on a Game Object that doesn't have any bounds, like a Container, would throw an error about being unable to access `getTopLeft`. If this is the case, it will now set the position to the given x/y values (thanks Jazz) -* All of the `Tilemaps.Parsers.Tiled` static functions are now available to be called directly. Fix #4318 (thanks @jestarray) -* `Arcade.StaticBody.setSize` now centers the body correctly, as with the other similar methods. Fix #4213 (thanks @samme) -* Setting `random: false` in a Particle Emitter config option no longer causes it to think random is true (thanks @samme) -* `Zone.setSize` didn't update the displayOrigin, causing touch events to be inaccurate as the origin was out. Fix #4131 (thanks @rexrainbow) -* `Tween.restart` wouldn't restart the tween properly. Fix #4594 (thanks @NokFrt) -* Looped Tween Timelines would mess-up the tween values on every loop repeat, causing the loop to fail. They now loop correctly due to a fix in the Tween.play method. Fix #4558 (thanks @peteroravec) -* `Timeline.setTimeScale` would only impact the Timeline loop and completion delays, not the actively running Tweens. It now scales the time for all child tweens as well. Fix #4164 (thanks @garethwhittaker) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@PhaserEditor2D @samme @Nallebeorn @Punkiebe @rootasjey @Sun0fABeach - -## Version 3.17.0 - Motoko - 10th May 2019 - -### Shaders - -'Shader' is a new type of Game Object which allows you to easily add a quad with its own shader into the display list, and manipulate it as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other Game Object. They can also be made interactive and used for input events. - -They work by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can be created dynamically at runtime, or loaded in via the updated GLSL File Loader: - -```javascript -function preload () -{ - this.load.glsl('fire', 'shaders/fire.glsl.js'); -} - -function create () -{ - this.add.shader('fire', 400, 300, 512, 512); -} -``` - -Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. - -* `Display.BaseShader` is a new type of object that contain the fragment and vertex source, together with any uniforms the shader needs, and are used when creating the new `Shader` Game Objects. They are stored in the Shader cache. -* The Shader Cache `this.cache.shader` has been updated. Rather than holding plain text fragments, it now holds instances of the new `BaseShader` objects. As a result, using `cache.shader.get(key)` will now return a `BaseShader` instead of a text file. -* The `GLSLFile` loader has been updated with new arguments. As well as a URL to the shader file you can also specify if the file is a fragment or vertex shader. It then uses this value to help create or update a `BaseShader` instance in the shader cache. -* The `GLSLFile` loader now supports shader bundles. These allow for multiple shaders to be stored in a single file, with each shader separated by a block of front-matter that represents its contents. Example shader bundles can be found in the Phaser 3 Examples repo. - -### DOM Elements - -DOM Elements have finally left the experimental stage and are now part of the full Phaser release. - -DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. In order for DOM Elements to display you have to enable them by adding the following to your game configuration object: - -```javascript -dom { - createContainer: true -} -``` - -When this is added, Phaser will automatically create a DOM Container div that is positioned over the top of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of settings within the Scale Manager, the dom container is resized accordingly. - -You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing -Element that you wish to be placed under the control of Phaser. For example: - -```javascript -this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); -``` - -The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. - -You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control alignment and positioning of the elements next to regular game content. - -Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other methods available in this class to help construct your elements. - -Once the element has been created you can then control it like you would any other Game Object. You can set its position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have a DOM Element, then a Sprite, then another DOM Element behind it. - -You can find lots of examples on using DOM Elements in the Phaser 3 Examples repo. - -### Geometry and Bitmap Masks - -* `Camera.setMask` is a new method that allows you to set a geometry or bitmap mask on any camera. The mask can be set to remain fixed in position, or to translate along with the camera. It will impact anything the camera renders. A reference to the mask is stored in the `Camera.mask` property. -* `Camera.clearMask` is a new method that clears a previously set mask on a Camera. -* There is a new Game Config property `input.windowEvents` which is true by default. It controls if Phaser will listen for any input events on the Window. If you disable this, Phaser will stop being able to emit events like `POINTER_UP_OUTSIDE`, or be aware of anything that happens outside of the Canvas re: input. -* Containers can now contain masked children and have those masks respected, including the mask on the Container itself (if any). Masks work on any depth of child up to 255 children deep. -* Geometry Masks are now batched. Previously, using the same mask on multiple Game Objects would create brand new stencil operations for every single Game Object, causing performance to tank. Now, the mask is only set if it's different from the previously masked object in the display list, allowing you to mask thousands of Game Objects and retain batching through-out. -* `GeometryMask.setInvertAlpha` is a new method that allows you to set the `invertAlpha` property in a chainable call. -* Previously, setting a mask on a Particle Emitter wouldn't work (it had to be set on the Emitter Manager instance), even though the mask methods and properties existed. You can now set a geometry or bitmap mask directly on an emitter. -* The Particle Emitter Manager was missing the Mask component, even though it fully supported masking. The Mask component has now been added. You can now mask the manager, which impacts all emitters you create through it, or a specific emitter. Different emitters can have different masks, although they override the parent mask, if set. -* You can now apply a Bitmap Mask to a Camera or Container and a Geometry Mask to a child and have it work correctly. -* `WebGLRenderer.maskCount` is a new internal property that tracks the number of masks in the stack. -* `WebGLRenderer.maskStack` is a new internal array that contains the current mask stack. - -### Arcade Physics - -#### New Features - -* `overlapTiles` is a new method that allows you to check for overlaps between a physics enabled Game Object and an array of Tiles. The Tiles don't have to have been enable for collision, or even be on the same layer, for the overlap check to work. You can provide your own process callback and/or overlap callback. This is handy for testing for overlap for a specific Tile in your map, not just based on a tile index. This is available via `this.physics.overlapTiles` and the World instance. -* `collideTiles` is a new method that allows you to check for collision between a physics enabled Game Object and an array of Tiles. The Tiles don't have to have been enable for collision, or even be on the same layer, for the collision to work. You can provide your own process callback and/or overlap callback. There are some limitations in using this method, please consult the API Docs for details, but on the whole, it allows for dynamic collision on small sets of Tile instances. This is available via `this.physics.collideTiles` and the World instance. -* `overlapRect` is a new method that allows you to return an array of all physics bodies within the given rectangular region of the World. It can return dynamic or static bodies and will use the RTree for super-fast searching, if enabled (which it is by default) -* The `Body.setCollideWorldBounds` method has two new optional arguments `bounceX` and `bounceY` which, if given, will set the World Bounce values for the body. - -#### Updates - -* `Body.preUpdate` is a new method that is called only once per game step. It resets all collision status properties and syncs the Body with the parent Game Object. -* `Body.update` has been rewritten to just perform one single physics step and no longer re-syncs with the Game Object. It can be called multiple times per game step, depending on the World FPS rate. -* `Body.postUpdate` has been rewritten to make it more compact. It syncs the body data back to the parent Game Object and is only called once per game step now (previously it was called whenever the Body updated) -* The `World.late` Set has been removed and is no longer populated, as it's no longer required. -* `World.update` now calls `Body.preUpdate` just once per game step, then calls `Body.update` as many times as is required as per the FPS setting, and no longer calls `Body.postUpdate` at all. -* `World.collideSpriteVsTilemapLayer` now returns a boolean if a collision or overlap happens, where-as before it didn't. -* `World.collideSpriteVsTilemapLayerHandler` is a new private method that handles all tilemap collision checks. -* The internal method `SeparateTile` now has a new argument `isLayer` which controls if the set comes from a layer or an array. -* The internal method `TileCheckX` now has a new argument `isLayer` which controls if the set comes from a layer or an array. -* The internal method `TileCheckY` now has a new argument `isLayer` which controls if the set comes from a layer or an array. -* `Body.isMoving` has been removed as it was never used internally. -* `Body.stopVelocityOnCollide` has been removed as it was never used internally. -* All of the Arcade Physics Components are now available directly under the `Phaser.Physics.Arcade.Components` namespace. Fix #4440 (thanks @jackfreak) -* `Phaser.Physics.Arcade.Events` is now exposed in the namespace, preventing it from erroring if you use them in TypeScript. Fix #4481 (thanks @danielalves) -* The Matter World configuration value `bodyDebugFillColor` has been renamed to `debugBodyFillColor` to be consistent with the rest of the options. -* The Matter World configuration has a new property: `debugStaticBodyColor` that sets the static body debug color. - -#### Bug Fixes - -* The `Body.delta` values are now able to be read and acted upon during a Scene update, due to the new game step flow. This means you can now call `this.physics.collide` during a Scene `update` and it will work properly again. Fix #4370 (thanks @NokFrt) -* `ArcadePhysics.furthest` now iterates the bodies Set, rather than the RTree, which keeps it working even if the RTree has been disabled. -* `ArcadePhysics.closest` now iterates the bodies Set, rather than the RTree, which keeps it working even if the RTree has been disabled. -* `Body.setVelocity` caused the `speed` property to be set to `NaN` if you didn't provide a `y` argument. -* Passing an _array_ of configuration objects to `physics.add.group` would ignore them and none of the children would be assigned a physics body. Fix #4511 (thanks @rgk) -* A Body with `damping` and `drag` enabled would fail to move if it went from zero velocity to a new velocity inside an `update` loop. It will now reset its speed accordingly and retain its new velocity (thanks StealthGary) - -### Facebook Instant Games Plugin - -* The method `consumePurchases` has been renamed to `consumePurchase` to bring it in-line with the Facebook API. -* `getProduct` is a new method that will return a single Product from the product catalog based on the given Product ID. You can use this to look-up product details based on a purchase list. - -### New Features - -* A Scene will now emit the new `CREATE` event after it has been created by the Scene Manager. If the Scene has a `create` method this event comes after that, so is useful to knowing when a Scene may have finished creating Game Objects, etc. (thanks @jackfreak) -* `Tilemap.removeTile` is a new method that allows you to remove a tile, or an array of tiles, by passing in references to the tiles themselves, rather than coordinates. The tiles can be replaced with new tiles of the given index, or removed entirely, and the method can optionally recalculate interesting faces on the layer. -* `TweenManager.remove` is a new method that immediately removes the given Tween from all of its internal arrays. -* `Tween.remove` is a new method that immediately removes the Tween from the TweenManager, regardless of what state the tween is in. Once called the tween will no longer exist within any internal TweenManager arrays. -* `SceneManager.isPaused` is a new method that will return if the given Scene is currently paused or not (thanks @samme) -* `ScenePlugin.isPaused` is a new method that will return if the given Scene is currently paused or not (thanks @samme) -* `TextureManager.removeKey` is a new method that will remove a key from the Texture Manager without destroying the texture itself. -* `Matter.World.resetCollisionIDs` is a new method that will reset the collision IDs that Matter JS uses for body collision groups. You should call this before destroying your game if you need to restart the game again on the same page, without first reloading the page. Or, if you wish to consistently destroy a Scene that contains Matter.js and then run it again (thanks @clesquir) -* RenderTexture has two new optional constructor arguments `key` and `frame`. This allows you to create a RenderTexture pre-populated with the size and frame from an existing texture (thanks @TadejZupancic) -* `GameObjects.Components.PathFollower` is a new component that manages any type of Game Object following a path. The original Path Follower Game Object has been updated to use this new component directly, but it can be applied to any custom Game Object class. -* `Tilemap.removeLayer` is a new method that allows you to remove a specific layer from a Tilemap without destroying it. -* `Tilemap.destroyLayer` is a new method that allows you to destroy a layer and remove it from a Tilemap. -* `Tilemap.renderDebugFull` is a new method that will debug render all layers in the Tilemap to the given Graphics object. -* `Geom.Intersects.GetCircleToCircle` is a new function that will return the point/s of intersection between two circles (thanks @florianvazelle) -* `Geom.Intersects.GetCircleToRectangle` is a new function that will return the point/s of intersection between a circle and a rectangle (thanks @florianvazelle) -* `Geom.Intersects.GetLineToCircle` is a new function that will return the point/s of intersection between a line and a circle (thanks @florianvazelle) -* `Geom.Intersects.GetLineToRectangle` is a new function that will return the point/s of intersection between a line and a rectangle (thanks @florianvazelle) -* `Geom.Intersects.GetRectangleToRectangle` is a new function that will return the point/s of intersection between two rectangles (thanks @florianvazelle) -* `Geom.Intersects.GetRectangleToTriangle` is a new function that will return the point/s of intersection between a rectangle and a triangle (thanks @florianvazelle) -* `Geom.Intersects.GetTriangleToCircle` is a new function that will return the point/s of intersection between a triangle and a circle (thanks @florianvazelle) -* `Geom.Intersects.GetTriangleToLine` is a new function that will return the point/s of intersection between a triangle and a line (thanks @florianvazelle) -* `Geom.Intersects.GetTriangleToTriangle` is a new function that will return the point/s of intersection between two triangles (thanks @florianvazelle) -* `Size.setCSS` is a new method that will set the Size components width and height to the respective CSS style properties of the given element. -* `CSSFile` is a new Loader FileType that allows you to load css into the current document via the normal Phaser Loader, using the `load.css` method. As such, you can chain it with other load calls, load via config, use as part of a pack load or any other option available to all loader filetypes. The CSS is applied immediately to the document. -* `MultiScriptFile` is a new Loader FileType that allows you to load multiple script files into the document via the Phaser Loader, using the new `load.scripts` method. The difference between this and `load.script` is that you must pass an array of script file URLs to this method and they will be loaded in parallel but _processed_ (i.e. added to the document) in the exact order specified in the array. This allows you to load a bundle of scripts that have dependencies on each other. -* `Key.getDuration` is a new method that will return the duration, in ms, that the Key has been held down for. If the Key isn't down it will return zero. -* The `Container.setScrollFactor` method has a new optional argument `updateChildren`. If set, it will change the `scrollFactor` values of all the Container children as well as the Container. Fix #4466 #4475 (thanks @pinkkis @enriqueto) -* There is a new webpack config `FEATURE_SOUND` which is set to `true` by default, but if set to `false` it will exclude the Sound Manager and all of its systems from the build files. Fix #4428 (thanks @goldfire) -* `Scene.Systems.renderer` is a new property that is a reference to the current renderer the game is using. -* `Utils.Objects.SetValue` is a new function that allows you to set a value in an object by specifying a property key. The function can set a value to any depth by using dot-notation for the key, i.e. `SetValue(data, 'world.position.x', 100)`. -* `WebGLRenderer.glFuncMap` is a new object, populated during the `init` method, that contains uniform mappings from key to the corresponding gl function, i.e. `mat2` to `gl.uniformMatrix2fv`. -* `BaseCache.getKeys` is a new method that will return all keys in use in the current cache, i.e. `this.cache.shader.getKeys()`. - -### Updates - -* Removed all references to CocoonJS from the API, including in the Device.OS object and elsewhere, as Cocoon is no longer. -* The MouseManager and TouchManager now use separate handlers for the Window level input events, which check to see if the canvas is the target or not, and redirect processing accordingly. -* `AnimationManager.generateFrameNumbers` can now accept a start number greater than the end number, and will generate them in reverse (thanks @cruzdanilo) -* The return from the `ScenePlugin.add` method has changed. Previously, it would return the ScenePlugin, but now it returns a reference to the Scene that was added to the Scene Manager, keeping it in-line with all other `add` methods in the API. Fix #4359 (thanks @BigZaphod) -* The `PluginManager.installScenePlugin` method has a new optional boolean parameter `fromLoader` which controls if the plugin is coming in from the result of a Loader operation or not. If it is, it no longer throws a console warning if the plugin already exists. This fixes an issue where if you return to a Scene that loads a Scene Plugin it would throw a warning and then not install the plugin to the Scene. -* The Scale Manager has a new event `FULLSCREEN_FAILED` which is fired if you try to enter fullscreen mode, but the browser rejects it for some reason. -* The `ScaleMode` Component has been removed from every Game Object, and along with it the `scaleMode` property and `setScaleMode` method. These did nothing anyway as they were not hooked to the render pipeline and scale mode should be set on the texture, not the Game Object. Fix #4413 (thanks @jcyuan) -* The `Clock.now` property value is now synced to be the `TimeStep.time` value when the Clock plugin boots and is no longer `Date.now()` until the first update (thanks @Antriel) -* `Graphics.strokePoints` has renamed the second argument from `autoClose` to `closeShape`. There is also a new third argument `closePath`, which defaults to `true` and automatically closes the path before stroking it. The `endIndex` argument is now the fourth argument, instead of the third. -* `Graphics.fillPoints` has renamed the second argument from `autoClose` to `closeShape`. There is also a new third argument `closePath`, which defaults to `true` and automatically closes the path before filling it. The `endIndex` argument is now the fourth argument, instead of the third. -* Calling `Texture.destroy` will now call `TextureManager.removeKey` to ensure the key is removed from the manager, should you destroy a texture directly, rather than going via `TextureManager.remove`. Fix #4461 (thanks @BigZaphod) -* `SpriteSheetFromAtlas` now adds in a `__BASE` entry for the Sprite Sheet it creates, keeping it consistent with the other frame parsers (thanks @Cirras) -* The `from` and `to` properties in the PathFollower Config can now be used to set the span of the follow duration (thanks @kensleebos) -* `Graphics.lineFxTo` and `Graphics.moveFxTo` have been removed as they were not being rendered anyway. -* You can now use "infinite" tilemaps as created in Tiled v1.1 and above. Support is basic in that it takes the chunk data and builds one giant map from it. However, at least you are still able to now load and use infinite maps, even if they don't chunk during the game (thanks @Upperfoot) -* `MapData.infinite` is a new boolean that controls if the map data is infinite or not. -* `DynamicTilemapLayer.destroy` will now remove the layer from the Tilemap it belongs to, clearing it from the layers array. Fix #4319 (thanks @APXEOLOG) -* `StaticTilemapLayer.destroy` will now remove the layer from the Tilemap it belongs to, clearing it from the layers array. Fix #4319 (thanks @APXEOLOG) -* `DynamicTilemapLayer.destroy` has a new optional boolean argument `removeFromTilemap` which will control if the layer is removed from the parent map or not. -* `StaticTilemapLayer.destroy` has a new optional boolean argument `removeFromTilemap` which will control if the layer is removed from the parent map or not. -* `Tilemap.copy` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.fill` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.forEachTile` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.putTilesAt` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.randomize` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.calculateFacesAt` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.renderDebug` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.replaceByIndex` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setCollision` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setCollisionBetween` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setCollisionByProperty` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setCollisionByExclusion` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setCollisionFromCollisionGroup` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setTileIndexCallback` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.setTileLocationCallback` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.shuffle` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.swapByIndex` now actually returns `null` if an invalid layer was given, as per the docs. -* `Tilemap.weightedRandomize` now actually returns `null` if an invalid layer was given, as per the docs. -* `BaseCamera.cameraManager` is a new property that is a reference to the Camera Manager, set in the `setScene` method. -* `CameraManager.default` is a new property that contains a single un-transformed instance of a Camera, that exists outside of the camera list and doesn't render. It's used by other systems as a default camera matrix. -* The `Graphics` Game Object now has 3 new Transform Matrix instances called `_tempMatrix1` to `_tempMatrix3`, which are used by it during the WebGL Rendering process. This is because Graphics objects can be used as Geometry Masks, which need to retain their own matrix state mid-render of another object, so cannot share the renderer temp matrices that other Game Objects can use. This also indirectly fixes an issue where masked children (such as emitters or container children) would get incorrect camera scroll values. -* The `Key` method signature has changed. It now expects to receive a reference to the KeyboardPlugin instance that is creating the Key as the first argument. This is now stored in the new `Key.plugin` property, and cleared in `destroy`. -* `KeyboardPlugin.removeKey` has a new optional argument `destroy` that will, if set, destroy the Key object being removed from the plugin. -* `InteractiveObject.customHitArea` is a new property that records if the hitArea for the Interactive Object was created based on texture size (false), or a custom shape (true) -* A Camera will pause following a Game Object for the duration of the Camera Pan Effect, as the two will clash over the Camera scroll position (thanks fruitbatinshades). -* `ParseXMLBitmapFont` has now been exposed as a static function on the `BitmapText` object, so you can access it easily from your own code (thanks @jcyuan) -* The math used in the circle to circle Arcade Physics collision has been updated to better handle horizontal collision, giving a more realistic response. Fix #4256 (thanks @akuskis @JeSuisUnCaillou) - -### Bug Fixes - -* The parent bounds are reset when exiting fullscreen mode in the Scale Manager. This fixes an issue when leaving fullscreen mode by pressing ESC (instead of programmatically) would leave the canvas in the full screen size. Fix #4357 (thanks @khutchins and @HeyStevenXu) -* `GetAdvancedValue` now uses the correct Math RND reference, which means anything that used the `randInt` or `randFloat` features of this function, such as creating a Sprite from a Config object, or Bitmap Text sizing, will no longer throw an error about a null object reference. Fix #4369 (thanks @sanadov) -* Trying to enter Fullscreen mode on Android / Chrome, or iOS / Safari, would throw an error regarding an unhandled Promise and a failure to invoke the event from a user gesture. This has been tightened up, using a proper Promise handler internally and the documentation clarified to explicitly say that you must call the function from a `pointerup` handler, and not `pointerdown`. Fix #4355 (thanks @matrizet) -* Camera fadeIn and fadeOut would sometimes leave a very low alpha-valued rectangle rendering to the camera. Fix #3833 (thanks @bdaenen) -* `Actions.Spread` would only use the `min` value to work out the step value but not apply it to the property being set (thanks @galman33) -* Calling `Tween.pause` returns the Tween instance, however, if it was already paused, it would return `undefined`, causing problems when chaining Tween methods (thanks @kyranet) -* Calling `TweenManager.makeActive` returns the TweenManager instance, however, if you create a tween externally and call `makeActive` with it, this would return `undefined`. -* Setting the `fixedWidth` and / or `fixedHeight` properties in the configuration of a `Text` would be ignored, they were only supported when calling the `setFixedSize` method. They now work via either option. Fix #4424 (thanks @rexrainbow) -* When calculating the width of a Text object for word wrapping it would ignore the extra spaces added from the wrap. It now accounts for these in the width. Fix #4187 (thanks @rexrainbow) -* `Utils.Array.Add` would act incorrectly when adding an object into an array in which it already belonged. This would manifest if, for example, adding a child into a display list it was already a part of. Fix #4411 (thanks @mudala @LoolzRules) -* `Tile.getCenterX` and `Tile.getCenterY` would return the wrong values for tiles on scaled layers. Fix #3845 (thanks @oloflarsson @florianvazelle) -* `Camera.startFollow` will now ensure that if the Camera is using bounds that the `scrollX` and `scrollY` values set after first following the Game Object do not exceed the bounds (thanks @snowbillr) -* Creating a Tween with a `duration` of zero would cause the tweened object properties to be set to `NaN`. Now they will tween for one single frame before being set to progress 1. Fix #4235 (thanks @BigZaphod) -* The First frame of a Texture would take on the appearance of the second frame in a Sprite Sheet created from trimmed Texture Atlas frames. Fix #4088 (thanks @Cirras) -* `Tween.stop` assumed that the parent was the TweenManager. If the Tween has been added to the Timeline, that was not true and the stop method crashed (thanks @TadejZupancic) -* Calling `Tween.restart` multiple times in a row would cause the tween to freeze. It will now disregard all additional calls to `restart` if it's already in a pending state (thanks @rgk) -* Tween Timelines would only apply the `delay` value of a child tween once and not on loop. Fix #3841 (thanks @Edwin222 @Antriel) -* `Texture.add` will no longer let you add a frame to a texture with the same name or index as one that already exists in the texture. Doing so will now return `null` instead of a Frame object, and the `frameTotal` will never be incremented. Fix #4459 (thanks @BigZaphod) -* The InputPlugin will now dispatch an update event, allowing the Gamepad Plugin to update itself every frame, regardless of DOM events. This allows Gamepads to work correctly again. Fix #4414 (thanks @CipSoft-Components) -* Calling `Tween.play` on a tween that had already finished and was pending removal will stop the tween from getting stuck in an `isPlaying` state and will restart the tween again from the beginning. Calling `play` on a Tween that is already playing does nothing. Fix #4184 (thanks @SamCode) -* Declared `Audio.dataset`, which fixes Internet Explorer 10 crashing when trying to access the dataset property of the object (thanks @SirLink) -* The `InputManager.update` method is now called every frame, as long as a native DOM event hasn't already fired it, which allows things like `setPollRate` to work again. Fix #4405 (thanks @Shucki) -* `Pointer.getDuration` would only return zero until the pointer was released, or moved (basically any action that generated a DOM event). It now returns the duration regardless of the DOM events. Fix #4444 (thanks @plazicx) -* `Keyboard.UpDuration` has been changed so the `duration` being checked is now against the current game clock. This means you can use it to check if a Key was released within `duration` ms ago, based on the time now, not the historic value of the Key. -* `Keyboard.DownDuration` has been changed so the `duration` being checked is now against the current game clock. This fixes an issue where it couldn't be used while the Key was actively being held down. Fix #4484 (thanks @belen-albeza) -* Keys would lose track of the state of a Scene when the Scene became paused. They're now updated regardless, stopping them from getting stuck if you pause and resume a Scene while holding them down. Fix #3822 (thanks @DannyT) -* Changing any aspect of a Text object, such as the font size or content, wouldn't update its `hitArea` if it had been enabled for input, causing it to carry on using the old hit area size. Now, as long as the Text was created _without_ a custom hitArea, the hitArea size will be changed to match the new texture size on update. If you have provided your own custom hitArea shape, you need to modify it when the Text changes size yourself. Fix #4456 (thanks @thanh-taro and @rexrainbow) -* `Camera.clearRenderToTexture` will check to see if the Scene is available before proceeding, avoiding potential errors when a Camera is destroyed multiple times during a Scene shutdown. -* Destroying a Game object during its `pointerup` event handler on a touch device will no longer cause `Uncaught TypeError: Cannot read property 'localX' of undefined`. All InputPlugin process handlers now check to see if the Game Object has been destroyed at any stage and abort if it has. Fix #4463 (thanks @PatrickSachs) -* `InputPlugin.clear` has a new argument `skipQueue` which is used to avoid clearing a Game Object twice. This, combined with the fix for 4463 means you will no longer get a `Cannot read property 'dragState'` error if you destroy a Game Object enabled for drag where another draggable object exists. Fix #4228 (thanks @YannCaron) -* `UpdateList.remove` will now move the removed child to the internal `_pendingRemoval` array, instead of slicing it directly out of the active list. The pending list is cleared at the start of the next game frame. Fix #4365 (thanks @jcyuan) -* Setting `pixelPerfect` when input enabling a Container would cause it to crash, because Containers don't have a texture to check. It will now throw a run-time warning and skip the Container for input. You should use a custom input callback instead. Fix #4492 (thanks @BigZaphod) -* Setting `fixedWidth` and `fixedHeight` on a Text object will now clamp the size of the canvas being created, as well as the width and height properties of the Text object itself (thanks @rexrainbow) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@sky-coding @G-Rath @S4n60w3n @rootasjey @englercj @josephmbustamante @Jason-Cooke @Zamiell @krzysztof-grzybek @S4n60w3n @m31271n @peterellisjones @martinlindhe @TylerMorley @samme @schomatis @BeLi4L @hizzd @OmarShehata @antoine-pous @digitsensitive - -Also, thanks to @Osmose there is a new Dashing config added to the Phaser 3 Docs Repo, with a new command `build-docset` which will build a [Dash](https://kapeli.com/dash) compatible docset for those who like to use Dash for their docs. - -## Version 3.16.2 - Ishikawa - 11th February 2019 - -This is point release primarily fixes a few important issues that surfaced in 3.16.0. - -### Matter Pointer Constraint Changes - -The following changes all effect the Matter JS Pointer Constraint class: - -* Pointer handling has been changed to make more sense. In the previous version, pressing down and then moving the Pointer _over_ a body would start it being dragged, even if the pointer was pressed down well outside of the body bounds. Now, a body can only be dragged by actually pressing down on it, or any of its parts, which is more in-line with how input events should work. -* Previously, releasing ANY pointer would stop an object being dragged, even if it wasn't the one actually dragging a body, as in a multi-touch game. Bodies are now bound to the pointer which started their drag and only the release of that pointer will stop them. -* There is a new Matter Physics Event `DRAG_START` which is emitted by a Pointer Constraint when it starts dragging a body. Listen for this event from the Matter World instance. -* There is a new Matter Physics Event `DRAG` which is emitted by a Pointer Constraint as it drags a body. Listen for this event from the Matter World instance. -* There is a new Matter Physics Event `DRAG_END` which is emitted by a Pointer Constraint when it stops dragging a body. Listen for this event from the Matter World instance. -* The `camera` property can no longer be set in the config object. Instead it is set every time the Pointer is pressed down on a Body, this resolves issues where you have a multi-camera Scene and want to drag a body in the non-main camera. -* `body` is a new property that holds a reference to the Body being dragged, if any. -* `part` is a new property that holds a reference to the Body part that was clicked on which started the drag. -* The internal `getBodyPart` method has been renamed to `hitTestBody` to more accurately reflect what it does. -* The class no longer listens for the pointer `up` event, instead of tracks the active pointer and waits for that to be released. This has reduced the complexity and size of the `update` method considerably. -* `stopDrag` is a new method that allows you to manually stop an object being dragged, even if the pointer isn't released. -* This class now has 100% JSDocs. - -### Updates - -* `TileSprite.setTileScale` has been updated so that the `y` argument is optional and set to match the `x` argument, like `setScale` elsewhere in the API. -* `InputManager.time` is a new property that holds the most recent time it was updated from the Game step, which plugins can access. -* `InputManager.preStep` is a new method that populates some internal properties every step. -* `KeyboardPlugin.time` has moved from being a property to being a getter, which returns the time from the InputManager. -* The `scale` property has been added to the `Scene` class (thanks @strangeweekend) -* `Matter.World.remove` now uses the `Composite.remove` method internally. Previously, it used `Composite.removeBody` which only allowed it to remove bodies from the simulation. Now, it can remove any type of Matter object. -* When the Matter World creates its wall bounds, the left and right walls now extend further up and down than before, so that in a 4-wall setting there are no gaps in the corners, which previously allowed for fast moving objects that hit a corner intersection point to sometimes travel through it. -* Touch inputs will now trigger a `POINTER_OUT` event if they leave the game (i.e. are released), where-as before they would only trigger the `POINTER_UP` event. Now, both happen (thanks @rgk) - -### Bug Fixes - -* The `Mesh.setAlpha` method has been restored, even though it's empty and does nothing, to prevent runtime errors when adding a Mesh or Quad object to a Container. Fix #4338 #4343 (thanks @pfdtravalmatic @charmingny) -* `KeyboardPlugin.checkDown` would always fail if using the new event system, because the time value it was checking wasn't updated. -* Entering `Fullscreen` mode in the Scale Manager and then pressing ESC would leave the injected fullsceen div in the DOM, causing it to throw a node insertion failure the second time you wanted to enter fullscreen mode. Fix #4352 (thanks @ngdevr) -* Due to the changes in the Input event system, the `GAME_OUT` event would never fire unless the input system was in legacy mode. The OUT and OVER handlers have been refactored and will now fire as soon as the DOM event happens. As a result the `InputManager._emitIsOverEvent` property has been removed, as the native event is sent directly to the handler and doesn't need storing locally any more. Fix #4344 (thanks @RademCZ) -* Added `Zone.setBlendMode` method as a NOOP function, fixing a bug where if you added a Zone to a Container when running under Canvas it would fail. Fix #4295 (thanks @emanuel15) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@maretana @CipSoft-Components @brian-lui - -## Version 3.16.0 / 3.16.1 - Ishikawa - 5th February 2019 - -Phaser 3.16 is a massive update. The single largest in the history of Phaser 3 and it contains _breaking changes_. If you're upgrading from an earlier version please do check the log entries below. - -Please note: there is no difference between 3.16.0 and 3.16.1. The version bump was just to get around a stupid npm semver policy. - -### Important Namespace Changes - -* The `Phaser.Boot` namespace has been renamed to `Phaser.Core`. As a result, the `boot` folder has been renamed to `core`. This impacts the `TimeStep` class and `VisibilityHandler` function, which have been moved to be under the new namespace. -* The `Phaser.Animations` namespace was incorrectly exposed in the Phaser entrypoints as `Animation` (note the lack of plural). This means that if you are creating any custom classes that extend Animation objects using the Phaser namespace, then please update them from `Phaser.Animation` to `Phaser.Animations`, i.e. `Phaser.Animation.AnimationFrame` to `Phaser.Animations.AnimationFrame`. This doesn't impact you if you created animations directly via the Animation Manager. -* The keyed Data Manager change data event string has changed from `changedata_` to `changedata-` to keep it consistent with other keyed events. Note the change from `_` to `-`. -* The Keyboard Plugin `keydown` dynamic event string has changed from `keydown_` to `keydown-` to keep it consistent with other keyed events. Note the change from `_` to `-`. -* The Keyboard Plugin `keyup` dynamic event string has changed from `keyup_` to `keyup-` to keep it consistent with other keyed events. Note the change from `_` to `-`. -* The `texturesready` event emitted by the Texture Manager has been renamed to `ready`. -* The `loadcomplete` event emitted by the Loader Plugin has been renamed to `postprocess` to be reflect what it's used for. -* Game Objects used to emit a `collide` event if they had an Arcade Physics Body with `onCollide` set, that collided with a Tile. This has changed. The event has been renamed to `tilecollide` and you should now listen for this event from the Arcade Physics World itself: `this.physics.world.on('tilecollide')`. Game Objects no longer emit this event. -* Game Objects used to emit an `overlap` event if they had an Arcade Physics Body with `onOverlap` set, that overlapped with a Tile. This has changed. The event has been renamed to `tileoverlap` and you should now listen for this event from the Arcade Physics World itself: `this.physics.world.on('tileoverlap')`. Game Objects no longer emit this event. -* The function `Phaser.Physics.Impact.SeperateX` has been renamed to `SeparateX` to correct the spelling mistake. -* The function `Phaser.Physics.Impact.SeperateY` has been renamed to `SeparateY` to correct the spelling mistake. -* The `ended` event in `WebAudioSound` has been renamed to `complete` to make it more consistent with the rest of the API. -* The `ended` event in `HTML5AudioSound` has been renamed to `complete` to make it more consistent with the rest of the API. -* The `Phaser.Utils.Objects` namespace was incorrectly exposed in the Phaser entrypoints as `Object` (note the lack of plural), this has now been fixed so all associated functions are properly namespaced. -* `Phaser.GameObjects.Blitter.Bob` has been renamed to `Phaser.GameObjects.Bob` to avoid namespace conflicts in TypeScript. -* `Phaser.GameObjects.Text.TextStyle` has been renamed to `Phaser.GameObjects.TextStyle` to avoid namespace conflicts in TypeScript. - -### Important Changes to the Input System - -In Phaser 3.15 and earlier the Input system worked using an event queue. All native DOM input events, such as from the Mouse, Touch or Keyboard, were picked up by event handlers and stored in a queue within the Input Manager. This queue was then processed during the next game step, all the events were dealt with and then it was cleared, ready to receive more events. As they were processed, the internal Phaser events such as `pointerdown` or `keyup` were dispatched to your game code. - -This worked fine in that you were able to guarantee _exactly_ when the events would arrive, because it was always at the same time in the game step. However, it had the side effect of you not being able to do things like open external browser windows, or go into Full Screen mode, during your event handlers - because they weren't "real" events, so didn't pass the browser security checks. To this end, methods like `addUpCallback` were added to try and provide this support (although it was never possible for keyboard events). - -In 3.16 this has changed. The DOM Events now trigger the respective internal events immediately, in the same invocation. So if you click on the canvas, the `pointerdown` event you receive in your game is still part of the 'native' event handler, so you're now free to do things like go into full screen mode, or open external windows, without any browser warnings or work-arounds. - -It does, however, mean that the point at which these handlers are called is no longer always consistent, and is no longer bound to the speed of the Request Animation Frame update. We've tested as much as possible, and so far, things carry on working as before. We've noticed a slight increase in responsiveness, due to the removal of the fractional delay in processing the events, which feels good. However, if for whatever reason this change has broken your game then you're able to easily switch back to the previous version. In your Game Config, create an `input` object and give it the property `queue: true`. This will tell Phaser to use the legacy event queue system. - -Please note that we _will_ remove this legacy system in the near future. So, please try and adapt your games to use the new system. If you've found an edge-case where something breaks because of it, please report it so we can look into it. - -As a result of this change, the following are now deprecated: - -* `InputPlugin.addUpCallback` method. -* `InputPlugin.addDownCallback` method. -* `InputPlugin.addMoveCallback` method. -* `InputManager.queue` property. -* `InputManager.domCallbacks` property. -* `InputManager._hasUpCallback` property. -* `InputManager._hasDownCallback` property. -* `InputManager._hasMoveCallback` property. -* `InputManager.processDomCallbacks` method. -* `InputManager.addUpCallback` method. -* `InputManager.addDownCallback` method. -* `InputManager.addMoveCallback` method. - -### keydown and keyup changes - -Due to unification across the event system, the `keydown_` and `keyup_` dynamic event strings have changed. - -* In all cases the `keydown_KEY` event name has changed to `keydown-KEY`. Note the change from an underscore to a hyphen. -* In all cases the `keyup_KEY` event name has changed to `keyup-KEY`. Note the change from an underscore to a hyphen. - -You should update your game code accordingly. - -### Keyboard Input - New Features - -The specificity of the Keyboard events has been changed to allow you more control over event handling. Previously, the Keyboard Plugin would emit the global `keydown-CODE` event first (where CODE was a keycode string, like `keydown-A`), then it would emit the global `keydown` event. In previous versions, `Key` objects, created via `this.input.keyboard.addKey()`, didn't emit events. - -The `Key` class now extends EventEmitter and emits two new events directly: `down` and `up`. This means you can listen for an event from a Key you've created, i.e.: `yourKey.on('up', handler)`. - -The order has also now changed. If it exists, the Key object will dispatch its `down` event first. Then the Keyboard Plugin will dispatch `keydown_CODE` and finally the least specific of them all, `keydown` will be dispatched. - -You also now have the ability to cancel this at any stage either on a local or global level. All event handlers are sent an event object which you can call `event.stopImmediatePropagation()` on. This will immediately stop any further listeners from being invoked in the current Scene. Therefore, if you call `stopImmediatePropagation()` in the `Key.on` handler, then the Keyboard Plugin will not emit either the `keydown-CODE` or `keydown` global events. You can also call `stopImmediatePropagation()` during the `keydown-CODE` handler, to stop it reaching the global `keydown` handler. As `keydown` is last, calling it there has no effect. - -There is also the `stopPropagation()` function. This works in the same way as `stopImmediatePropagation` but instead of being local, it works across all of the Scenes in your game. For example, if you had 3 active Scenes (A, B and C, with A at the top of the Scene list), all listening for the same key, calling `stopPropagation()` in Scene A would stop the event from reaching any handlers in Scenes B or C. Remember that events flow down the Scene list from top to bottom. So, the top-most rendering Scene in the Scene list has priority over any Scene below it. - -All the above also works for `keyup` events. - -New in 3.16 is the ability to receive a global `keydown` or `keyup` event from any key on the keyboard. Previously, it would only emit the event if it came from one of the keys listed in the KeyCodes file. Now, those global events will fire for any key, regardless of location. - -#### Keyboard Captures - -Key capturing is the way in which you stop a keyboard DOM event from activating anything else in the browser by calling `preventDefault` on it. For example, in tall web pages, pressing the SPACE BAR causes the page to scroll down. Obviously, if this is also the fire or jump button in your game, you don't want this to happen. So the key needs to be 'captured' to prevent it. Equally, you may wish to also capture the arrow keys, for similar reasons. Key capturing is done on a global level. If you set-up the capture of a key in one Scene, it will be captured globally across the whole game. - -In 3.16 you now do this using the new `KeyboardPlugin.addCapture` method. This takes keycodes as its argument. You can either pass in a single key code (i.e. 32 for the Space Bar), an array of key codes, or a comma-delimited string - in which case the string is parsed and each code it can work out is captured. - -To remove a capture you can use the `KeyboardPlugin.removeCapture` method, which takes the same style arguments as adding captures. To clear all captures call `KeyboardPlugin.clearCaptures`. Again, remember that these actions are global. - -You can also temporarily enable and disable capturing using `KeyboardPlugin.enableGlobalCapture` and `KeyboardPlugin.disableGlobalCapture`. This means if you set-up a bunch of key captures, but then need to disable them all for a while (perhaps you swap focus to a DOM text field), you can call `disableGlobalCapture` to do this, and when finished in the DOM you can enable captures again with `enableGlobalCapture`, without having to clear and re-create them all. - -Default captures can be defined in the Game Config in the `input.keyboard.captures` object. The captures are actually stored in the `KeyboardManager` class. The `KeyboardPlugin` is just a proxy to methods in the Keyboard Manager, but is how you should interface with it. - -* `KeyboardPlugin.addCapture` is a new method that allows you to define a set of keycodes to have the default browser behaviors disabled on. -* `KeyboardPlugin.removeCapture` is a new method that removes specific previously set key captures. -* `KeyboardPlugin.clearCaptures` is a new method that removes all key captures. -* `KeyboardPlugin.getCaptures` is a new method that returns an array of all current key captures. -* `KeyboardPlugin.enableGlobalCapture` is a new method that enables any key captures that have been created. -* `KeyboardPlugin.disableGlobalCapture` is a new method that disables any key captures that have been created, without removing them from the captures list. -* `KeyboardPlugin.addKey` has a new boolean argument `enableCapture`, which is true by default, that will add a key capture for the Key being created. -* `KeyboardPlugin.addKeys` has a new boolean argument `enableCapture`, which is true by default, that will add a key capture for any Key created by the method. - -#### Other Keyboard Updates and Fixes - -* There is a new class called `KeyboardManager`. This class is created by the global Input Manager if keyboard access has been enabled in the Game config. It's responsible for handling all browser keyboard events. Previously, the `KeyboardPlugin` did this which meant that every Scene that had its own Keyboard Plugin was binding more native keyboard events. This was causing problems with parallel Scenes when needing to capture keys. the `KeyboardPlugin` class still exists, and is still the main point of interface when you call `this.input.keyboard` in a Scene, but DOM event handling responsibility has been taken away from it. This means there's now only -one set of bindings ever created, which makes things a lot cleaner. -* There is a new Game and Scene Config setting `input.keyboard.capture` which is an array of KeyCodes that the Keyboard Plugin will capture all non-modified key events on. By default it is empty. You can populate it in the config, or use the new capture methods. -* The Keyboard Manager will now call `preventDefault` only on non-modified key presses, stopping the keyboard event from hitting the browser. Previously, capturing the R key, for example, would block a CTRL+R page reload, but it now ignores it because of the key modifier. -* If the browser Window loses focus, either from switching to another app, or another tab, all active Keys will be reset. This prevents issues with keys still reporting as being held down after leaving the game and returning to it again. Fix #4134 (thanks @Simplonium) -* `Key.emitOnRepeat` is a new boolean property that controls if the Key will continuously emit a `down` event while being held down (true), or emit the event just once, on first press, and then skip future events (false). -* `Key.setEmitOnRepeat` is a new chainable method for setting the `emitOnRepeat` property. -* The `KeyboardPlugin.addKeys` method has a new optional boolean `emitOnRepeat` which sets that property on all Key objects it creates as part of the call. It defaults to `false`. -* The `KeyboardPlugin.addKey` method has a new optional boolean `emitOnRepeat` which sets that property on the Key object it creates. It defaults to `false`. -* The `Key` class now extends EventEmitter and emits two events directly: `down` and `up`. This means you can listen for an event from a Key you've created, i.e.: `yourKey.on('up', handler)`. -* The following Key Codes have been added, which include some missing alphabet letters in Persian and Arabic: `SEMICOLON_FIREFOX`, `COLON`, `COMMA_FIREFOX_WINDOWS`, `COMMA_FIREFOX`, `BRACKET_RIGHT_FIREFOX` and `BRACKET_LEFT_FIREFOX` (thanks @wmateam) -* `Key.onDown` is a new method that handles the Key being pressed down, including down repeats. -* `Key.onUp` is a new method that handles the Key being released. -* `Key.destroy` is a new method that handles Key instance destruction. It is called automatically in `KeyboardPlugin.destroy`. -* The `Key.preventDefault` property has been removed. This is now handled by the global keyboard capture methods. -* `Key.metaKey` is a new boolean property which indicates if the Meta Key was held down when the Key was pressed. On a Mac the Meta Key is Command. On a Windows keyboard, it's the Windows key. -* `InputManager.keyboard` is a new property that instantiates the global Keyboard Manager, if enabled in the game config. -* The `KeyboardPlugin.addKey` method has a new boolean property `enableCapture` which automatically prevents default on the Key being created. -* The `KeyboardPlugin.addKeys` method has a new boolean property `enableCapture` which automatically prevents default on Keys being created. -* `Phaser.Input.Keyboard.ProcessKeyDown` has been removed as it's no longer required, `Key.onDown` handles it instead. -* `Phaser.Input.Keyboard.ProcessKeyUp` has been removed as it's no longer required, `Key.onUp` handles it instead. -* The Keyboard Manager has a property called `captures` which is an array of keycodes, as populated by the Game Config. Any key code in the array will have `preventDefault` called on it if pressed. -* `KeyboardPlugin.manager` is a new property that references the Keyboard Manager and is used internally. -* `KeyboardPlugin.target` has been removed as it's no longer used by the class. -* `KeyboardPlugin.queue` has been removed as it's no longer used by the class. -* `KeyboardPlugin.onKeyHandler` has been removed as it's no longer used by the class. -* `KeyboardPlugin.startListeners` has been removed as it's no longer used by the class. -* `KeyboardPlugin.stopListeners` has been removed as it's no longer used by the class. - -### Mouse and Touch Input - New Features, Updates and Fixes - -* The Mouse Manager class has been updated to remove some commented out code and refine the `startListeners` method. -* When enabling a Game Object for input it will now use the `width` and `height` properties of the Game Object first, falling back to the frame size if not found. This stops a bug when enabling BitmapText objects for input and it using the font texture as the hit area size, rather than the text itself. -* `Pointer.smoothFactor` is a float-value that allows you to automatically apply smoothing to the Pointer position as it moves. This is ideal when you want something smoothly tracking a pointer in a game, or are need a smooth drawing motion for an art package. The default value is zero, meaning disabled. Set to a small number, such as 0.2, to enable. -* `Config.inputSmoothFactor` is a new property that allows you to set the smoothing factor for all Pointers the game creates. The default value is zero, which is disabled. Set in the game config as `input: { smoothFactor: value }`. -* `InputManager.transformPointer` has a new boolean argument `wasMove`, which controls if the pointer is being transformed after a move or up/down event. -* `Pointer.velocity` is a new Vector2 that contains the velocity of the Pointer, based on the current and previous positions. The velocity is smoothed out each frame according to the `Pointer.motionFactor` property. This is done for more accurate gesture recognition. The velocity is updated based on Pointer movement and doesn't require a button to be pressed first. -* `Pointer.angle` is a new property that contains the angle of the Pointer, in radians, based on the current and previous positions. The angle is smoothed out each frame according to the `Pointer.motionFactor` property. This is done for more accurate gesture recognition. The angle is updated based on Pointer movement and doesn't require a button to be pressed first. -* `Pointer.distance` is a new property that contains the distance of the Pointer, in radians, based on the current and previous positions. The distance is smoothed out each frame according to the `Pointer.motionFactor` property. This is done for more accurate gesture recognition. The distance is updated based on Pointer movement and doesn't require a button to be pressed first. -* `Pointer.motionFactor` is a new property that controls how much smoothing to apply to the Pointer positions each frame. This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, angle and distance of the Pointer. It's applied every frame until the midPoint reaches the current position of the Pointer. The default value is 0.2. -* The Input Plugin was emitting a `preUpdate` event, with the capital U, instead of `preupdate`. This has now been corrected. Fix #4185 (thanks @gadelan) -* `Pointer.updateMotion` is a new method that is called automatically, each step, by the Input Manager. It's responsible for calculating the Pointer velocity, angle and distance properties. -* `Pointer.time` is a new property that holds the time the Pointer was last updated by the Game step. -* `Pointer.getDistance` has been updated. If called while a button is being held down, it will return the distance between the Pointer's current position and it's down position. If called when a Pointer doesn't have a button down, it will return the historic distance between the up and down positions. -* `Pointer.getDistanceX` is a new method that will return the horizontal distance between the Pointer's previous and current coordinates. If called while a button is being held down, it will return the distance between the Pointer's current position and it's down position. If called when a Pointer doesn't have a button down, it will return the historic distance between the up and down positions. -* `Pointer.getDistanceY` is a new method that will return the horizontal distance between the Pointer's previous and current coordinates. If called while a button is being held down, it will return the distance between the Pointer's current position and it's down position. If called when a Pointer doesn't have a button down, it will return the historic distance between the up and down positions. -* `Pointer.getDuration` is a new method that will return the duration the Pointer was held down for. If the Pointer has a button pressed down at the time this method is called, it will return the duration since the Pointer's button was pressed down. If no button is held down, it will return the last recorded duration, based on the time the Pointer button was released. -* `Pointer.getAngle` is a new method that will return the angle between the Pointer coordinates. 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. -* In previous versions, the VisibilityHandler would create a `mousedown` listener for the game canvas and then call `window.focus` when detected (assuming the game config `autoFocus` property was `true`). Responsibility for this has now been moved to the Mouse Manager `onMouseDown` handler. -* In previous versions, the VisibilityHandler would create a `mouseout` listener for the game canvas and then set `game.isOver` when detected. Responsibility for this has now been moved to the Mouse Manager, which sets the new Input Manager `isOver` property directly. -* In previous versions, the VisibilityHandler would create a `mouseover` listener for the game canvas and then set `game.isOver` when detected. Responsibility for this has now been moved to the Mouse Manager, which sets the new Input Manager `isOver` property directly. -* The `Phaser.Game.isOver` property has been moved. You can now find it in the Input Manager and it's also accessible via the Input Plugin, which means you can do `this.input.isOver` from within a Scene. This makes more sense as it's input related and not a game level property. -* The Input Plugin has a new event you can listen to: `gameover`, which is triggered whenever the mouse or a pointer is moved over the Game canvas. Listen to it with `this.input.on('gameover')` from within a Scene. -* The Input Plugin has a new event you can listen to: `gameout`, which is triggered whenever the mouse or a pointer leaves the Game canvas. Listen to it with `this.input.on('gameout')` from within a Scene. -* The Game used to emit a `mouseover` event when the mouse entered the game canvas. This is no longer emitted by the Game itself and can instead be listened for using the new Input Plugin event `gameover`. -* The Game used to emit a `mouseout` event when the mouse left the game canvas. This is no longer emitted by the Game itself and can instead be listened for using the new Input Plugin event `gameout`. -* If the `window` object exists (which it will in normal browser environments) new `mouseup` and `touchend` event listeners are bound to it and trigger the normal `mouseup` or `touchend` events within the internal input system. This means you will now get a `pointerup` event from the Input Plugin even if the pointer is released outside of the game canvas. Pointers will also no longer think they are still 'down' if released outside the canvas and then moved inside again in their new state. -* The window will now have focus called on it by the Touch Manager, as well as the Mouse Manager, if the `autoFocus` game config property is enabled. -* The Input Plugin has a new event you can listen to: `pointerdownoutside`, which is triggered whenever the mouse or a pointer is pressed down while outside of the Game canvas. Listen to it with `this.input.on('pointerdownoutside')` from within a Scene. -* The Input Plugin has a new event you can listen to: `pointerupoutside`, which is triggered whenever the mouse or a pointer is released while outside of the Game canvas. Listen to it with `this.input.on('pointerupoutside')` from within a Scene. -* `Pointer.downElement` is a new property that holds the target of the DOM Event that triggered when the Pointer was pressed down. If this is within the game, this will be the game canvas element. -* `Pointer.upElement` is a new property that holds the target of the DOM Event that triggered when the Pointer was released. If this is within the game, this will be the game canvas element. -* The `Pointer.dragState` property has been removed. This is no longer used internally as it has to be tracked per Scene, not on a global level. -* `InputPlugin.setDragState` is a new internal method that sets the drag state for the given Pointer. -* `InputPlugin.getDragState` is a new internal method that gets the drag state for the given Pointer. -* Draggable Game Objects would not work if you had multiple Scenes running in parallel, with draggable objects in both of them. Only the top-most Scene would work fully. Items in the bottom Scene would never finish their drag cycle, causing them to get stuck. Fix #4249 #4278 (thanks @probt @iArePJ) -* `Pointer.leftButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). -* `Pointer.rightButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). -* `Pointer.middleButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). -* `Pointer.backButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). -* `Pointer.forwardButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). -* `Pointer.up`, `Pointer.move` and `Pointer.down` now use `in` to check for the existance of the `buttons` property on the event, causing it to be set even if equal to zero, which it is when there are no buttons down. This also fixes an issue where the buttons didn't update during a move event (thanks @SonnyCampbell @rexrainbow) - -### Changes as a result of the new Scale Manager - -3.16 introduces the completed Scale Manager. This is fully documented, but the class, all methods and all properties. It also includes a folder full of examples in the Phaser Labs, so you're strongly recommended to start there. - -* If you set the Game Config property `zoom` to be > 1 then it will automatically enable `pixelArt` mode, unless you set `pixelArt: false` in the config. -* There is a new property in the Game Config called `autoRound`, which controls if the canvas size and style sizes are passed through Math.floor or not. On some devices this can help with performance and anti-aliasing. The default is `false` (turned off). -* The Game Config property `autoResize` has been removed as it's now redundant. -* The WebGL and Canvas Renderers no longer change the Canvas size in their `resize` methods. They just update internal properties. -* The WebGL and Canvas Renderers now read the `width`, `height` and `resolution` values from the Scale Manager, not the Game Config. -* `CameraManager.baseScale` property has been removed as it's no longer used anywhere. -* The BaseCamera and Camera `preRender` methods now only take a resolution argument and use it internally for their transforms. -* `InputManager.scaleManager` is a new property that is a reference to the Scale Manager. This is populated in the `boot` method. -* The `InputManager.transformX` method has been removed. This is now available in the ScaleManager. -* The `InputManager.transformY` method has been removed. This is now available in the ScaleManager. -* The `InputManager.scale` property has been removed. This is now available in the ScaleManager under `displayScale`. -* The `InputManager.resize` method has been removed as this process is now handled by the ScaleManager. -* The `InputManager.bounds` property has been removed as this process is now handled by the ScaleManager. -* The `InputManager.updateBounds` method has been removed as this process is now handled by the ScaleManager. -* The `InputManager.getOffsetX` method has been removed as it's no longer required. -* The `InputManager.getOffsetY` method has been removed as it's no longer required. -* The `InputManager.getScaleX` method has been removed as it's no longer required. -* The `InputManager.getScaleY` method has been removed as it's no longer required. -* The `SceneManager.resize` method has been removed as it's no longer required. -* The `Scene.Systems.resize` method has been removed as it's no longer required. -* Scenes will no longer dispatch the `resize` event. You should now listen for this event from the Scale Manager instead. -* `BaseCamera.config` has been removed as it's no longer required. -* `BaseCamera.scaleManager` is a new property that references the Scale Manager and is used internally for size checks. -* The `Game.resize` method has been removed as it's no longer required. You should now call `ScaleManager.resize` instead. -* The Game will no longer dispatch the `resize` event. You should now listen for this event from the Scale Manager instead. - -### Facebook Instant Games Updates and Fixes - -* Added the `Leaderboard.getConnectedScores` method, to get a list of scores from player connected entries. -* The `loadPlayerPhoto` function in the Instant Games plugin now listens for the updated Loader event correctly, causing the `photocomplete` event to fire properly. -* `Leaderboard.setScore` now emits the LeaderboardScore object with the `setscore` event, as the documentation said it did. -* `Leaderboard.getPlayerScore` now only populates the `playerScore` property if the entry isn't `null`. -* If the `setScore` or `getPlayerScore` calls fail, it will return `null` as the score instance, instead of causing a run-time error. -* You can now pass an object or a string to `setScore` and objects will be automatically stringified. -* The `preloadAds` method will now only create an AdInstance object if the interstitial `loadSync` promise resolves. -* The `preloadVideoAds` method will now only create an AdInstance object if the interstitial `loadSync` promise resolves. -* The `preloadAds` method will now emit the `adsnofill` event, if there are no ads in the inventory to load. -* The `preloadVideoAds` method will now emit the `adsnofill` event, if there are no ads in the inventory to load. -* The `showAd` method will now emit the `adsnotloaded` event, if there are no ads loaded matching the given Placement ID. -* The `showVideo` method will now emit the `adsnotloaded` event, if there are no ads loaded matching the given Placement ID. -* Showing an ad will emit the `adfinished` event when the ad is closed, previously this event was called `showad` but the new name better reflects what has happened. -* The Facebook Plugin is now available in the `Phaser.Scene` class template under the `facebook` property (thanks @bryanwood) -* Fixed the `Leaderboard.getScores` method to now take the arguments into account. Fix #4271 (thanks @Oramy) -* Fixed an API validation error in the `chooseContext` method. Fix #4248 (thanks @yadurajiv) - -### New Features - -* You can now load external Scene files using the new `load.sceneFile` method. This allows you to dynamically load a Scene into the Scene Manager of your game, and swap to it at will. Please see the documentation and examples for further details. -* The data object being sent to the Dynamic Bitmap Text callback now has a new property `parent`, which is a reference to the Bitmap Text instance that owns the data object (thanks ornyth) -* The WebGL Renderer has a new method `clearPipeline`, which will clear down the current pipeline and reset the blend mode, ready for the context to be passed to a 3rd party library. -* The WebGL Renderer has a new method `rebindPipeline`, which will rebind the given pipeline instance, reset the blank texture and reset the blend mode. This is useful for recovering from 3rd party libs that have modified the gl context. -* Game Objects have a new property called `state`. Use this to track the state of a Game Object during its lifetime. For example, it could move from a state of 'moving', to 'attacking', to 'dead'. Phaser itself will never set this property, although plugins are allowed to. -* Game Objects have a new method called `setState` which will set the state property in a chainable call. -* `BlendModes.ERASE` is a new blend mode that will erase the object being drawn. When used in conjunction with a Render Texture it allows for effects that require you to erase parts of the texture, in either Canvas or WebGL. When used with a transparent game canvas, it allows you to erase parts of the canvas, showing the web page background through. -* `BlendModes.SOURCE_IN` is a new Canvas-only blend mode that allows you to use the `source-in` composite operation when rendering Game Objects. -* `BlendModes.SOURCE_OUT` is a new Canvas-only blend mode that allows you to use the `source-out` composite operation when rendering Game Objects. -* `BlendModes.SOURCE_ATOP` is a new Canvas-only blend mode that allows you to use the `source-atop` composite operation when rendering Game Objects. -* `BlendModes.DESTINATION_OVER` is a new Canvas-only blend mode that allows you to use the `destination-over` composite operation when rendering Game Objects. -* `BlendModes.DESTINATION_IN` is a new Canvas-only blend mode that allows you to use the `destination-in` composite operation when rendering Game Objects. -* `BlendModes.DESTINATION_OUT` is a new Canvas-only blend mode that allows you to use the `destination-out` composite operation when rendering Game Objects. -* `BlendModes.DESTINATION_ATOP` is a new Canvas-only blend mode that allows you to use the `destination-atop` composite operation when rendering Game Objects. -* `BlendModes.LIGHTER` is a new Canvas-only blend mode that allows you to use the `lighter` composite operation when rendering Game Objects. -* `BlendModes.COPY` is a new Canvas-only blend mode that allows you to use the `copy` composite operation when rendering Game Objects. -* `BlendModes.XOR` is a new Canvas-only blend mode that allows you to use the `xor` composite operation when rendering Game Objects. -* `RenderTexture.erase` is a new method that will take an object, or array of objects, and draw them to the Render Texture using an ERASE blend mode, resulting in them being removed from the Render Texture. This is really handy for making a bitmap masked texture in Canvas or WebGL (without using an actual mask), or for 'cutting away' part of a texture. -* There is a new boolean Game Config property called `customEnvironment`. If set to `true` it will skip the internal Feature checks when working out which type of renderer to create, allowing you to run Phaser under non-native web environments. If using this value, you _must_ set an explicit `renderType` of either CANVAS or WEBGL. It cannot be left as AUTO. Fix #4166 (thanks @jcyuan) -* `Animation.nextFrame` will advance an animation to the next frame in the sequence instantly, regardless of the animation time or state. You can call this on a Sprite: `sprite.anims.nextFrame()` (thanks rgk25) -* `Animation.previousFrame` will set an animation to the previous frame in the sequence instantly, regardless of the animation time or state. You can call this on a Sprite: `sprite.anims.previousFrame()` (thanks rgk25) -* `Geom.Intersects.PointToLine` has a new optional argument `lineThickness` (which defaults to 1). This allows you to determine if the point intersects a line of a given thickness, where the line-ends are circular (not square). -* `Geom.Line.GetNearestPoint` is a new static method that will return the nearest point on a line to the given point. -* `Geom.Line.GetShortestDistance` is a new static method that will return the shortest distance from a line to the given point. -* `Camera.getBounds` is a new method that will return a rectangle containing the bounds of the camera. -* `Camera.centerOnX` will move the camera horizontally to be centered on the given coordinate without changing its vertical placement. -* `Camera.centerOnY` will move the camera vertically to be centered on the given coordinate without changing its horizontally placement. -* `AnimationManager.exists` is a new method that will check to see if an Animation using the given key already exists or not and returns a boolean. -* `animationstart-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationstart-explode`. -* `animationrestart-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationrestart-explode`. -* `animationcomplete-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationcomplete-explode`. -* `animationupdate-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationupdate-explode`. -* The Animation class now extends the Event Emitter and dispatches events itself. This allows you to listen for events from a specific Animation, rather than via a Game Object. This is handy, for example, if you had an explosion animation that you wanted to trigger a sound effect when it started. You can now listen for the events from the Animation object directly. -* The Animation class now emits the `start` event when played (either forward, or in reverse) by any Game Object. -* The Animation class now emits the `restart` event when it restarts playing on any Game Object. -* The Animation class now emits the `complete` event when it finishes playing on any Game Object. -* The Animation Component has a new method called `chain` which allows you to line-up another animation to start playing as soon as the current one stops, no matter how it stops (either by reaching its natural end, or directly by having stop called on it). You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. -* `CanvasTexture.drawFrame` is a new method that allows you to draw a texture frame to the CanvasTexture based on the texture key and frame given. -* `CanvasTexture.getIndex` is a new method that will take an x/y coordinate and return the Image Data index offset used to retrieve the pixel values. -* `CanvasTexture.getPixels` is a new method that will take a region as an x/y and width/height and return all of the pixels in that region from the CanvasTexture. -* `CanvasTexture.setPixel` is a new method that sets the given pixel in the CanvasTexture to the color and alpha values provided. -* `CanvasTexture.getData` is a new method that will extract an ImageData block from the CanvasTexture from the region given. -* `CanvasTexture.putData` is a new method that will put an ImageData block at the given coordinates in a CanvasTexture. -* `Line.Extend` is a new static function that allows you extend the start and/or end points of a Line by the given amounts. -* `Vector2.LEFT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector2.RIGHT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector2.UP` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector2.DOWN` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector2.ONE` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.ZERO` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.LEFT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.RIGHT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.UP` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.DOWN` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.FORWARD` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.BACK` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* `Vector3.ONE` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) -* Geometery Mask has a new property called `invertAlpha` in WebGL, which works in the same way as the flag on the Bitmap Mask and allows you to invert the function of the stencil buffer, i.e. non-drawn shapes become invisible, and drawn shapes visible (thanks @tfelix) -* The Arcade Physics Body has a new property `maxSpeed` which limits the vector length of the Body velocity. You can set it via the method `setMaxSpeed` and it is applied in the `World.computeVelocity` method (thanks @Edwin222 @rexrainbow) -* `WebGLRenderer.snapshotArea` is a new method that allows you to grab an image of the given region of the canvas during the post-render step and have it sent to your defined callback. This is the same as `snapshot` except you control the area being grabbed, so is more efficient if you only need a smaller area. -* `WebGLRenderer.snapshotPixel` is a new method that allows you to grab a single pixel from the game canvas, post-render. It returns the result as a `Color` object to your specified callback. -* `CanvasRenderer.snapshotArea` is a new method that allows you to grab an image of the given region of the canvas during the post-render step and have it sent to your defined callback. This is the same as `snapshot` except you control the area being grabbed, so is more efficient if you only need a smaller area. -* `CanvasRenderer.snapshotPixel` is a new method that allows you to grab a single pixel from the game canvas, post-render. It returns the result as a `Color` object to your specified callback. -* `SceneManager.getScenes` is a new method that will return all current Scenes being managed by the Scene Manager. You can optionally return only active scenes and reverse the order in which they are returned in the array. -* `DOM.GetTarget` is a new helper function that will return a reference to a DOM Element based on the given string or node. -* `GameObjects.Extern` is a new special type of Game Object that allows you to pass rendering off to a 3rd party. When you create an Extern and place it in the display list of a Scene, the renderer will process the list as usual. When it finds an Extern it will flush the current batch, clear down the pipeline and prepare a transform matrix which your render function can take advantage of, if required. The Extern Game Object is used heavily by the Spine Plugin, but can also be used by other libraries such as three.js, allowing them to render directly into a Phaser game. - -### Updates - -* You can now modify `this.physics.world.debugGraphic.defaultStrokeWidth` to set the stroke width of any debug drawn body, previously it was always 1 (thanks @samme) -* `TextStyle.setFont` has a new optional argument `updateText` which will sets if the text should be automatically updated or not (thanks @DotTheGreat) -* `ProcessQueue.destroy` now sets the internal `toProcess` counter to zero. -* The `PathFollower.pathRotationVerticalAdjust` property has been removed. It was supposed to flipY a follower when it reversed path direction, but after some testing it appears it has never worked and it's easier to do this using events, so the property and associated config value are removed. The `verticalAdjust` argument from the `setRotateToPath` method has been removed as well. -* The config value `preserveDrawingBuffer` has been removed as it has never been used by the WebGL Renderer. -* `PluginManager.install` returns `null` if the plugin failed to install in all cases. -* `PluginFile` will now install the plugin into the _current_ Scene as long as the `start` or `mapping` arguments are provided. -* MATH_CONST no longer requires or sets the Random Data Generator, this is now done in the Game Config, allowing you to require the math constants without pulling in a whole copy of the RNG with it. -* The Dynamic Bitmap Text Canvas Renderer was creating a new data object every frame for the callback. It now uses the `callbackData` object instead, like the WebGL renderer does. -* `WebGLRenderer.setBlendMode` has a new optional argument `force`, which will force the given blend mode to be set, regardless of the current settings. -* The method `DisplayList.sortGameObjects` has been removed. It has thrown a runtime error since v3.3.0(!) which no-one even spotted which is a good indication of how little the method was used. The display list is automatically sorted anyway, so if you need to sort a small section of it, just use the standard JavaScript Array sort method (thanks ornyth) -* The method `DisplayList.getTopGameObject` has been removed. It has thrown a runtime error since v3.3.0(!) which no-one even spotted which is a good indication of how little the method was used (thanks ornyth) -* `WebGLRenderer.setFramebuffer` has a new optional boolean argument `updateScissor`, which will reset the scissor to match the framebuffer size, or clear it. -* `WebAudioSoundManager.onFocus` will not try to resume the Audio Context if it's still locked. -* `WebAudioSoundManager.onBlur` will not try to suspend the Audio Context if it's still locked. -* When using `ScenePlugin.add`, to add a new Scene to the Scene Manager, it didn't allow you to include the optional Scene data object. You can now pass this in the call (thanks @kainage) -* `Graphics.stroke` is a new alias for the `strokePath` method, to keep the calls consistent with the Canvas Rendering Context API. -* `Graphics.fill` is a new alias for the `fillPath` method, to keep the calls consistent with the Canvas Rendering Context API. -* `LoaderPlugin.sceneManager` is a new property that is a reference to the global Scene Manager, useful for Plugins. -* Whenever `Camera.roundPixels` was enabled it would use a bitwise operation to truncate the float (`x |= 0`) - this has been replaced across all files that used it, with a call to `Math.round` instead. This gives far better results when zooming cameras both in and out of a Scene, stopping thin gaps appearing between closely packed Game Objects. -* `AnimationManager.create` will now return a boolean `false` if the given key is invalid (i.e. undefined or falsey). -* `AnimationManager.create` will no longer raise a console warning if the animation key is already in use. Instead, it will return the animation belonging to that key. A brand new animation will only be created if the key isn't already in use. When this happens, the `add` event is emitted by the Animation Manager. If no event is emitted, the animation already existed. -* `ArcadePhysics.Body.destroy` will now only add itself to the World `pendingDestroy` list if the world property exists. This prevents `Cannot read property 'pendingDestroy' of undefined` errors if you try to delete a physics body in a callback and then immediately change Scene (which tells the physics work to also delete all bodies) -* The Animation Component `restart` method has had is sole `key` argument removed. Previously, you had to pass in the key of the animation you wished to reverse, but now you can just call the method directly, and as long as there is an animation playing, it will automatically start playing in reverse, without the nee for a key (the way it should have been originally) -* `Animation.play` and `playReverse` will now accept either a string-based key of the animation to play (like before), or you can pass in an Animation instance, and it will play that animation. -* `CanvasTexture.clear` now has 4 new optional arguments: `x, y, width, height` which allow you to define the region of the texture to be cleared. If not provided it will clear the whole texture, which is the same behavior as before. -* EarCut, the polygon triangulation library used by the Graphics and WebGL classes, has been upgraded from 2.1.1 to 2.1.4. 2.1.2 fixed a few race conditions where bad input would cause an error. 2.1.3 improved performance for bigger inputs (5-12%) and 2.1.4 fixed a race condition that could lead to a freeze on degenerate input. -* `TextureTintPipeline.batchQuad` and `batchTri` have two new optional arguments `texture` and `unit` which are used to re-set the batch texture should the method cause a batch flush. -* `TextureTintPipeline.requireTextureBatch` is a new internal method that helps speed-up the creation of texture batches. It is used in conjunction with `setTexture2D` and `pushBatch`. -* `TextureTintPipeline.flush` and `TextureTintPipeline.pushBatch` have been optimized to handle zero based texture units as priority. They've also been refactored to avoid creation of empty texture batches. -* The `WebGLRenderer.setTexture2D` method has a new optional argument `flush` which controls if the pipeline is flushed if the given texture is new, or not. This is used internally to skip flushing during an existing flush. -* The Tilemap Layer `width` and `height` properties are now based on the tilemap tile sizes multiplied by the layer dimensions. This corrects an issue with layer sizes being wrong if you called `setBaseTileSize` on a Map. -* The WebGLRenderer will now clear the framebuffer at the start of every render. -* `WebGLRenderer.setScissor` now has a new optional argument `drawingBufferHeight` which allows you to specify the drawing buffer height, rather than use the renderers default value. -* `WebGLRenderer.pushScissor` now has a new optional argument `drawingBufferHeight` which allows you to specify the drawing buffer height, rather than use the renderers default value. -* `WebGLRenderer.preRender` now calls `gl.clearColor` in order to restore the background clear color in case something, like a Render Texture, has changed it. -* `Map.set` will now update an existing value if you provide it with a key that already exists within the Map. Previously, if you tried to set the value of a key that existed it would be skipped. -* `MatterSprite` would set its `type` property to be `Image`. It now sets it to be `Sprite` as it should do. -* `Matter.TileBody.setFromTileCollision` no longer checks if the shape is concave or convex before modifying the vertices, as the update to the Matter.js lib in 3.12 stopped this from working with Tiled collision shapes. -* The Scene `transitionstart` event is now dispatched by the Target Scene of a transition, regardless if the Scene has a `create` method or not. Previously, it was only dispatched if the Scene had a create method. -* The Loader will now allow an XHR status of 0 as success too. Normally only status 200 would be accepted as success, but 0 is returned when a file is loaded from the local filesystem (file://). This happens, for example, when opening the index.html of a game in a browser directly, or when using Cordova on iOS. Fix #3464 (thanks @Ithamar) -* `Tween.restart` now returns the Tween instance (thanks @rexrainbow) -* `Tween.play` now returns the Tween instance (thanks @rexrainbow) -* `Tween.seek` now returns the Tween instance (thanks @rexrainbow) -* `Tween.complete` now returns the Tween instance (thanks @rexrainbow) -* `Tween.stop` now returns the Tween instance (thanks @rexrainbow) -* `List.sort` now has an optional parameter `handler` which allows you to provide your own sort handling function (thanks @jcyuan) -* `Container.sort` now has an optional parameter `handler` which allows you to provide your own sort handling function (thanks @jcyuan) -* The WebGLRenderer method `canvasToTexture` will now only set the filter to be `NEAREST` if `antialias` is disabled in the game config (i.e. when running in pixelArt mode). This means that Text objects, and other Canvas backed textures, now render with anti-aliasing if everything else does. You can disable this on a per-object basis by calling `texture.setFilter(1)` on them. -* `CanvasRenderer.snapshotCallback`, `snapshotType` and `snapshotEncoder` have all been removed as they are no longer required. -* `CanvasRenderer.snapshotState` is a new object that contains the snapshot configuration data, the same as the WebGL Renderer. -* The signature of the `WebGLSnapshot` function has changed. It now takes a Snapshot Configuration object as the second parameter. -* The signature of the `CanvasSnapshot` function has changed. It now takes a Snapshot Configuration object as the second parameter. -* A Tween Timeline will now set it's internal destroy state _before_ calling either the `onComplete` callback or sending the `COMPLETE` event. This means you can now call methods that will change the state of the Timeline, such as `play`, during the callback handlers, where-as before doing this would have had the internal state changed immediately, preventing it (thanks Lucas Knight) -* The `AddToDOM` method has had the `overflowHidden` argument removed. The DOM element the canvas is inserted into no longer has `overflow: hidden` applied to its style. If you wish to have this, please add it directly via CSS. - -### Bug Fixes - -* The Rectangle Shape object wouldn't render if it didn't have a stroke, or any other objects on the display list (thanks mliko) -* When using a font string instead of setting `fontFamily`, `fontSize` and `fontStyle` in either `Text.setStyle` or `setFont`, the style properties wouldn't get set. This isn't a problem while creating the text object, only if modifying it later (thanks @DotTheGreat) -* `Text.toJSON` wasn't saving the font style when using the "font" shorthand to create it. It now saves it correctly. Fix #4141 (thanks @divillysausages) -* Disabling camera bounds and then moving the camera to an area in a Tilemap that did not have any tile information would throw an `Uncaught Reference error` as it tried to access tiles that did not exist (thanks @Siyalatas) -* Fixed an issue where Sprite Sheets being extracted from a texture atlas would fail if the sheet was either just a single column or single row of sprites. Fix #4096 (thanks @Cirras) -* If you created an Arcade Physics Group without passing a configuration object, and passing an array of non-standard children, it would throw a classType runtime error. It now creates a default config object correctly (thanks @pierpo) -* The `Camera.cull` method has been restructured so it now calculates if a Game Object is correctly in view or not before culling it. Although not used internally, if you need to cull objects for a camera, you can now safely use this method. Fix #4092 (thanks @Cirras) -* The Tiled Parser would ignore animated tile data if it was in the new Tiled 1.2 format. This is now accounted for, as well as 1.0 (thanks @nkholski) -* `Array.Matrix.ReverseRows` was actually reversing the columns, but now reverses the rows. -* `Array.Matrix.ReverseColumns` was actually reversing the rows, but now reverses the columns. -* UnityAtlas now sets the correct file type key if using a config file object. -* Starting with version 3.13 in the Canvas Renderer, it was possible for long-running scripts to start to get bogged-down in `fillRect` calls if the game had a background color set. The context is now saved properly to avoid this. Fix #4056 (thanks @Aveyder) -* Render Textures created larger than the size of the default canvas would be automatically clipped when drawn to in WebGL. They now reset the gl scissor and drawing height property in order to draw to their full size, regardless of the canvas size. Fix #4139 (thanks @chaoyang805 @iamchristopher) -* The `cameraFilter` property of a Game Object will now allow full bitmasks to be set (a value of -1), instead of just those > 0 (thanks @stuartkeith) -* The `PathFollower.startFollow` method now properly uses the `startAt` argument to the method, so you can start a follower off at any point along the path. Fix #3688 (thanks @DannyT @diteix) -* Static Circular Arcade Physics Bodies now render as circles in the debug display instead of showing their rectangle bounds (thanks @maikthomas) -* Changing the mute flag on an `HTML5AudioSound` instance, via the `mute` setter, now works as it does via the Sound Manager (thanks @Waclaw-I @neon-dev) -* Changing the volume on an `HTML5AudioSound` instance, via the `volume` setter, now works as it does via the Sound Manager (thanks @Waclaw-I) -* The Dynamic Tilemap Layer WebGL renderer was drawing tiles at the incorrect position if the layer was scaled. Fix #4104 (thanks @the-realest-stu) -* `Tile.tileset` now returns the specific Tileset associated with the tile rather than an array of them. Fix #4095 (thanks @quadrupleslap) -* `Tile.getCollisionGroup` wouldn't return the correct Group after the change to support multiple Tilesets. It now returns the group properly (thanks @jbpuryear) -* `Tile.getTileData` wouldn't return the correct data after the change to support multiple Tilesets. It now returns the tile data properly (thanks @jbpuryear) -* The `GetTileAt` and `RemoveTileAt` components would error with "Cannot read property 'index' of undefined" if the tile was undefined rather than null. It now handles both cases (thanks @WaSa42) -* Changing `TileSprite.width` or `TileSprite.height` will now flag the texture as dirty and call `updateDisplayOrigin`, allowing you to resize TileSprites dynamically in both Canvas and WebGL. -* `RandomDataGenerator.shuffle` has been fixed to use the proper modifier in the calculation allowing for a more even distribution (thanks wayfinder) -* The Particle Emitter was not recycling dead particles correctly so it was creating new objects every time it emitted (the old particles were then left to the browsers gc to clear up). This has now been recoded so the emitter will properly keep track of dead particles and re-use them (thanks @Waclaw-I for the initial PR) -* `ParticleEmitter.indexSortCallback` has been removed as it's no longer required. -* `Particle.index` has been removed as it's no longer required. Particles don't need to keep track of their index any more. -* The Particle Emitter no longer needs to call the StableSort.inplace during its preUpdate, saving cpu. -* `Particle.resetPosition` is a new method that is called when a particle dies preparing it for firing again in the future. -* The Canvas `SetTransform` method would save the context state, but it wasn't restored at the end in the following Game Objects: Dynamic Bitmap Text, Graphics, Arc, Curve, Ellipse, Grid, IsoBox, IsoTriangle, Line, Polygon, Rectangle, Star and Triangle. These now all restore the context, meaning if you're using non-canvas sized cameras in Canvas mode, it will now render beyond just the first custom camera. -* `Utils.Array.MoveUp` wouldn't let you move an array element to the top-most index in the array. This also impacted `Container.moveUp`. -* The Texture Tint Pipeline had a logic error that would cause every 2001st quad to either be invisible, or pick-up the texture of the 2000th quad by mistake. The `batchQuad` and `batchTri` methods how handle re-assigning the batch texture if they cause a batch flush as part of their process. -* Rotating Sprites that used a Normal Map wouldn't rotate the normal map with it causing the lighting effects to become irregular. The normal map vectors are now rotated correctly (thanks @sercant for the PR and @fazzamatazz and @ysraelJMM for the report) -* Changing `scaleX` or `scaleY` on a `MatterImage` or `MatterSprite` would cause the body scale to become distorted as the setters didn't use the correct factor when resetting the initial scale. Fix #4206 (thanks @YannCaron) -* `StaticBody.reset` in Arcade Physics would ignore the `x` and `y` values given to it. If given, they're now used to reset the parent Game Object before the body is updated. Fix #4224 (thanks @samme) -* Static Tilemap Layers wouldn't render correctly if the layer used a tileset with a different size to the base map data (set via `setBaseTileSize`). They now render correctly in WebGL and Canvas regardless of the base tile size. -* When using `RenderTexture.fill`, the `alpha` argument would be ignored in Canvas mode. It's now used when filling the RenderTexture. -* Fixed an issue in `WebGLRenderer.setScissor` where it was possible to try and compare the scissor size to a non-current scissor if called outside of the render loop (i.e. from `RenderTexture.fill`) (thanks @hackhat) -* `RenderTexture.fill` in WebGL would use `gl.clear` and a clear color to try and fill the Render Texture. This only worked for full-canvas sized RenderTextures that didn't have a camera zoom applied. It has now been swapped to use the `drawFillRect` method of the Texture Tint Pipeline, allowing it to work properly regardless of camera zoom or size. -* `Container.getFirst` was using an incorrect Array Utils function `GetFirstElement` when it should have been using `GetFirst`. It now uses the correct function. Fix #4244 (thanks @miran248) -* `List.getFirst` was using an incorrect Array Utils function `GetFirstElement` when it should have been using `GetFirst`. It now uses the correct function. Fix #4244 (thanks @miran248) -* Fixed an issue where changing the viewport or size of a Camera belonging to a RenderTexture wouldn't impact the rendering and objects will still render outside of the viewport range. It's now converted to a proper gl scissor rect by the renderer, meaning you can limit the area rendered to by adjusting the internal Render Texture cameras viewport. Fix #4243 (thanks @hackhat) -* `CanvasTexture.destroy` is a new method that specifically handles the destruction of the CanvasTexture and all of its associated typed arrays. This prevents a memory leak when creating and destroying lots of RenderTextures (which are CanvasTexture backed). Fix #4239 (thanks @sjb933) -* The Alpha, Flip and Origin components have been removed from the Mesh Game Object (and by extension, Quad as well) as they are not used in the renderer and should be manipulated via the Mesh properties. Fix #4188 (thanks @enriqueto) -* The `processDomCallbacks` method in the Input Manager wasn't correctly clearing the `once` arrays. Responsibility for this has now been passed to the queue methods `queueTouchStart`, `queueTouchMove`, `queueTouchEnd`, `queueMouseDown`, `queueMouseMove` and `queueMouseUp`. Fix #4257 (thanks @iArePJ) -* Arcade Physics now manages when `postUpdate` should be applied better, stopping it from gaining a zero delta during a further check in the same frame. This fixes various issues, including the mass collision test demo. Fix #4154 (thanks @samme) -* Arcade Physics could trigger a `collide` event on a Body even if it performing an overlap check, if the `onCollide` property was true (thanks @samme) -* TileSprites no longer cause a crash when using the Headless mode renderer. Fix #4297 (thanks @clesquir) -* The WebGLRenderer will now apply a transparent background if `transparent = true` in the game config (thanks @gomachan7) -* `List.sort` was missing the scope required for the sort handler, this is now correctly provided internally. Fix #4241 (thanks @jcyuan) -* `Container.sort` was missing the scope required for the sort handler, this is now correctly provided internally. Fix #4241 (thanks @jcyuan) -* `DataManager.pop` would emit the DataManager instance, instead of the parent, as the first event argument. It now emits the parent as it should do. Fix #4186 (thanks @gadelan) -* The `GetValue` function wasn't checking for the existance of '.' in the config property name correctly, causing the branch to always be taken (thanks @kyranet) -* Safari had permission problems playing HTML5 Audio files on Mac OS. Due to the changes in the input event system audio now plays properly based on user interactions. You still can't play it automatically, though, it will always require a user gesture to begin. Fix #4217 (thanks @increpare) - -### Examples and TypeScript - -Thanks to the following for helping with the Phaser 3 Examples and TypeScript definitions, either by reporting errors, or even better, fixing them: - -@guilhermehto @samvieten @darkwebdev @RoryO @snowbillr @slothyrulez @jcyuan @jestarray @CzBiX - -### Phaser Doc Jam - -The Phaser Doc Jam was a community-backed effort to try and get the Phaser 3 API documentation to 100% coverage. The Doc Jam is now over and I offer my thanks to the following who helped with docs in this release: - -@16patsle - @gurungrahul2 - @icbat - @samme - @telinc1 - anandu pavanan - blackhawx - candelibas - Diego Romero - doronlinder - Elliott Wallace - eric - Georges Gabereau - Haobo Zhang - henriacle - jak6jak - Jake Jensen - James Van Roose - JamesSkemp - joelahoover - Joey - madclaws - marc136 - Mihail Ilinov - naum303 - NicolasRoehm - nuane - rejacobson - Robert Kowalski - rodri042 - rootasjey - sawamara - scottwestover - sir13tommy - stetso - therealsamf - Tigran - willblackmore - zenwaichi - -Also, the following helped with the docs outside of the Doc Jam: - -@bryanwood @jestarray @matosummer @tfelix @imilo @BigZaphod @OmarShehata @16patsle @jcyuan @iam13islucky @FractalBobz Endre - -## Version 3.15.1 - Batou - 16th October 2018 - -* Re-enabled Input Manager resizing, which had been left disabled by mistake. - -## Version 3.15.0 - Batou - 16th October 2018 - -Note: We are releasing this version ahead of schedule in order to make some very important iOS performance and input related fixes available. It does not contain the new Scale Manager or Spine support, both of which have been moved to 3.16 as they require a few more weeks of development. - -### New Features - -* You can now set the `maxLights` value in the Game Config, which controls the total number of lights the Light2D shader can render in a single pass. The default is 10. Be careful about pushing this too far. More lights = less performance. Close #4081 (thanks @FrancescoNegri) -* `Rectangle.SameDimensions` determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. -* An ArcadePhysics Group can now pass `{ enable: false }` in its config to disable all the member bodies (thanks @samme) -* `Body.setEnable` is a new chainable method that allows you to toggle the enable state of an Arcade Physics Body (thanks @samme) -* `KeyboardPlugin.resetKeys` is a new method that will reset the state of any Key object created by a Scene's Keyboard Plugin. -* `Pointer.wasCanceled` is a new boolean property that allows you to tell if a Pointer was cleared due to a `touchcancel` event. This flag is reset during the next `touchstart` event for the Pointer. -* `Pointer.touchcancel` is a new internal method specifically for handling touch cancel events. It has the same result as `touchend` without setting any of the up properties, to avoid triggering up event handlers. It will also set the `wasCanceled` property to `true`. - -### Updates - -* `WebGLRenderer.deleteTexture` will check to see if the texture it is being asked to delete is the currently bound texture or not. If it is, it'll set the blank texture to be bound after deletion. This should stop `RENDER WARNING: there is no texture bound to the unit 0` errors if you destroy a Game Object, such as Text or TileSprite, from an async or timed process (thanks jamespierce) -* The `RequestAnimationFrame.step` and `stepTimeout` functions have been updated so that the new Frame is requested from raf before the main game step is called. This allows you to now stop the raf callback from within the game update or render loop. Fix #3952 (thanks @tolimeh) -* If you pass zero as the width or height when creating a TileSprite it will now use the dimensions of the texture frame as the size of the TileSprite. Fix #4073 (thanks @jcyuan) -* `TileSprite.setFrame` has had both the `updateSize` and `updateOrigin` arguments removed as they didn't do anything for TileSprites and were misleading. -* `CameraManager.remove` has a new argument `runDestroy` which, if set, will automatically call `Camera.destroy` on the Cameras removed from the Camera Manager. You should nearly always allow this to happen (thanks jamespierce) -* Device.OS has been restructured to allow fake UAs from Chrome dev tools to register iOS devices. -* Texture batching during the batch flush has been implemented in the TextureTintPipeline which resolves the issues of very low frame rates, especially on iOS devices, when using non-batched textures such as those used by Text or TileSprites. Fix #4110 #4086 (thanks @ivanpopelyshev @sachinhosmani @maximtsai @alexeymolchan) -* The WebGLRenderer method `canvasToTexture` has a new optional argument `noRepeat` which will stop it from using `gl.REPEAT` entirely. This is now used by the Text object to avoid it potentially switching between a REPEAT and CLAMP texture, causing texture black-outs (thanks @ivanpopelyshev) -* `KeyboardPlugin.resetKeys` is now called automatically as part of the Keyboard Plugin `shutdown` method. This means, when the plugin shuts down, such as when stopping a Scene, it will reset the state of any key held in the plugin. It will also clear the queue of any pending events. -* The `Touch Manager` has been rewritten to use declared functions for all touch event handlers, rather than bound functions. This means they will now clear properly when the TouchManager is shut down. -* There is a new Input constant `TOUCH_CANCEL` which represents canceled touch events. - -### Bug Fixes - -* Fixed a bug in the canvas rendering of both the Static and Dynamic Tilemap Layers where the camera matrix was being multiplied twice with the layer, causing the scale and placement to be off (thanks galerijanamar) -* If you set `pixelArt` to true in your game config (or `antialias` to false) then TileSprites will now respect this when using the Canvas Renderer and disable smoothing on the internal fill canvas. -* TileSprites that were set to be interactive before they had rendered once wouldn't receive a valid input hit area, causing input to fail. They now define their size immediately, allowing them to be made interactive without having rendered. Fix #4085 (thanks @DotTheGreat) -* The Particle Emitter Manager has been given a NOOP method called `setBlendMode` to stop warnings from being thrown if you added an emitter to a Container in the Canvas renderer. Fix #4083 (thanks @maximtsai) -* The `game.context` property would be incorrectly set to `null` after the WebGLRenderer instance was created (thanks @samme) -* The Touch Manager, Input Manager and Pointer classes all now handle the `touchcancel` event, such as triggered on iOS when activating an out of browser UI gesture, or in Facebook Instant Games when displaying an overlay ad. This should prevent issues with touch input becoming locked on iOS specifically. Fix #3756 (thanks @sftsk @sachinhosmani @kooappsdevs) - -## Version 3.14.0 - Tachikoma - 1st October 2018 - -### Tilemap New Features, Updates and Fixes - -* Both Static and Dynamic Tilemap layers now support rendering multiple tilesets per layer in both Canvas and WebGL. To use multiple tilesets pass in an array of Tileset objects, or strings, to the `createStaticLayer` and `createDynamicLayer` methods respectively. -* `Tilemap.createStaticLayer` now supports passing either a Tileset reference, or a string, or an array of them as the 2nd argument. If strings, the string should be the Tileset name (usually defined in Tiled). -* `Tilemap.createDynamicLayer` now supports passing either a Tileset reference, or a string, or an array of them as the 2nd argument. If strings, the string should be the Tileset name (usually defined in Tiled). -* `Tilemap.createBlankDynamicLayer` now supports passing either a Tileset reference, or a string, or an array of them as the 2nd argument. If strings, the string should be the Tileset name (usually defined in Tiled). -* Static Tilemap Layers now support tile rotation and flipping. Previously this was a feature only for Dynamic Tilemap Layers, but now both have it. Close #4037 (thanks @thisredone) -* `Tilemap.getTileset` is a new method that will return a Tileset based on its name. -* `ParseTilesets` has been rewritten so it will convert the new data structures of Tiled 1.2 into the format expected by Phaser, allowing you to use either Tiled 1.2.x or Tiled 1.1 JSON exports. Fix #3998 (thanks @martin-pabst @halgorithm) -* `Tilemap.setBaseTileSize` now sets the size into the LayerData `baseTileWidth` and `baseTileHeight` properties accordingly. Fix #4057 (thanks @imilo) -* Calling `Tilemap.renderDebug` ignored the layer world position when drawing to the Graphics object. It will now translate to the layer position before drawing. Fix #4061 (thanks @Zax37) -* Calling `Tilemap.renderDebug` ignored the layer scale when drawing to the Graphics object. It will now scale the layer before drawing. Fix #4026 (thanks @JasonHK) -* The Static Tilemap Layer would stop drawing all tiles from that point on, if it encountered a tile which had invalid texture coordinates (such as a tile from another tileset). It now skips invalid tiles properly again. Fix #4002 (thanks @jdotrjs) -* If you used a RenderTexture as a tileset then Dynamic Tilemap Layers would render the tiles inversed on the y-axis in WebGL. Fix #4017 (thanks @s-s) -* If you used a scaled Dynamic Tilemap Layer and rotated or flipped tiles, the tiles that were rotated or flipped would be positioned incorrectly in WebGL. Fix #3778 (thanks @nkholski) -* `StaticTilemapLayer.tileset` is now an array of Tileset objects, where-as before it was a single reference. -* `StaticTilemapLayer.vertexBuffer` is now an array of WebGLBuffer objects, where-as before it was a single instance. -* `StaticTilemapLayer.bufferData` is now an array of ArrayBuffer objects, where-as before it was a single instance. -* `StaticTilemapLayer.vertexViewF32` is now an array of Float3Array objects, where-as before it was a single instance. -* `StaticTilemapLayer.vertexViewU32` is now an array of Uint32Array objects, where-as before it was a single instance. -* `StaticTilemapLayer.dirty` is now an array of booleans, where-as before it was a single boolean. -* `StaticTilemapLayer.vertextCount` is now an array of integers, where-as before it was a single integer. -* `StaticTilemapLayer.updateVBOData()` is a new private method that creates the internal VBO data arrays for the WebGL renderer. -* The `StaticTilemapLayer.upload()` method has a new parameter `tilesetIndex` which controls which tileset to prepare the VBO data for. -* The `StaticTilemapLayer.batchTile()` method has a new parameter `tilesetIndex` which controls which tileset to batch the tile for. -* `StaticTilemapLayer.setTilesets()` is a new private method that creates the internal tileset references array. -* `DynamicTilemapLayer.tileset` is now an array of Tileset objects, where-as before it was a single reference. -* `DynamicTilemapLayer.setTilesets()` is a new private method that creates the internal tileset references array. - -### New Features - -* `bodyDebugFillColor` is a new Matter Physics debug option that allows you to set a color used when drawing filled bodies to the debug Graphic. -* `debugWireframes` is a new Matter Physics debug option that allows you to control if the wireframes of the bodies are used when drawing to the debug Graphic. The default is `true`. If enabled bodies are not filled. -* `debugShowInternalEdges` is a new Matter Physics debug option that allows you to set if the internal edges of a body are rendered to the debug Graphic. -* `debugShowConvexHulls` is a new Matter Physics debug option that allows you to control if the convex hull of a body is drawn to the debug Graphic. The default is `false`. -* `debugConvexHullColor` is a new Matter Physics debug option that lets you set the color of the convex hull, if being drawn to the debug Graphic. -* `debugShowSleeping` is a new Matter Physics debug option that lets you draw sleeping bodies at 50% opacity. -* `Curves.Ellipse.angle` is a new getter / setter that handles the rotation of the curve in degrees instead of radians. - -### Updates - -* The Loader has been updated to handle the impact of you destroying the game instance while still processing files. It will no longer throw cache and texture related errors. Fix #4049 (thanks @pantoninho) -* `Polygon.setTo` can now take a string of space separated numbers when creating the polygon data, i.e.: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'`. This update also impacts the Polygon Shape object, which can now also take this format as well. -* The `poly-decomp` library, as used by Matter.js, has been updated to 0.3.0. -* `Matter.verts`, available via `this.matter.verts` from within a Scene, is a quick way of accessing the Matter Vertices functions. -* You can now specify the vertices for a Matter `fromVerts` body as a string. -* `TextureTintPipeline.batchTexture` has a new optional argument `skipFlip` which allows you to control the internal render texture flip Y check. -* The Device.OS check for `node` will now do a `typeof` first to avoid issues with rollup packaged builds needing to shim the variable out. Fix #4058 (thanks @hollowdoor) -* Arcade Physics Bodies will now sync the display origin of the parent Game Object to the body properties as part of the `updateBounds` call. This means if you change the origin of an AP enabled Game Object, after creation of the body, it will be reflected in the body position. This may or may not be a breaking change for your game. Previously it was expected that the origin should always be 0.5 and you adjust the body using `setOffset`, but this change makes a bit more sense logically. If you find that your bodies are offset after upgrading to this version then this is likely why. Close #4052 (thanks @SolarOmni) -* The `Texture.getFramesFromTextureSource` method has a new boolean argument `includeBase`, which defaults to `false` and allows you to set if the base frame should be returned into the array or not. -* There is a new Animation Event that is dispatched when an animation restarts. Listen for it via `Sprite.on('animationrestart')`. -* All of the Animation Events now pass the Game Object as the final argument, this includes `animationstart`, `animationrestart`, `animationrepeat`, `animationupdate` and `animationcomplete`. -* `Curves.Ellipse.rotation` is a getter / setter that holds the rotation of the curve. Previously it expected the value in degrees and when getting it returned the value in radians. It now expects the value in radians and returns radians to keep it logical. -* `Set.size` will now only set the new size if the value is smaller than the current size, truncating the Set in the process. Values larger than the current size are ignored. -* Arcade Physics `shutdown` will check to see if the world instance still exists and only try removing it if so. This prevents errors when stopping a world and then destroying it at a later date. -* `Text.setFont`, `Text.setFontFamily`, `Text.setFontStyle` and `Text.setStroke` will no longer re-measure the parent Text object if their values have not changed. - -### Bug Fixes - -* GameObjects added to and removed from Containers no longer listen for the `shutdown` event at all (thanks Vitali) -* Sprites now have `preDestroy` method, which is called automatically by `destroy`. The method destroys the Animation component, unregistering the `remove` event in the process and freeing-up resources. Fix #4051 (thanks @Aveyder) -* `UpdateList.shutdown` wasn't correctly iterating over the pending lists (thanks @felipeprov) -* Input detection was known to be broken when the game resolution was !== 1 and the Camera zoom level was !== 1. Fix #4010 (thanks @s-s) -* The `Shape.Line` object was missing a `lineWidth` property unless you called the `setLineWidth` method, causing the line to not render in Canvas only. Fix #4068 (thanks @netgfx) -* All parts of Matter Body now have the `gameObject` property set correctly. Previously only the first part of the Body did. -* When using `MatterGameObject` and `fromVerts` as the shape type it wouldn't pass the values to `Bodies.fromVertices` because of a previous conditional. It now passes them over correctly and the body is only set if the result is valid. -* The `Texture.getFramesFromTextureSource` method was returning an array of Frame names by mistake, instead of Frame references. It now returns the Frames themselves. -* When using `CanvasTexture.refresh` or `Graphics.generateTexture` it would throw WebGL warnings like 'bindTexture: Attempt to bind a deleted texture'. This was due to the Frames losing sync with the glTexture reference used by their TextureSource. Fix #4050 (thanks @kanthi0802) -* Fixed an error in the `batchSprite` methods in the Canvas and WebGL Renderers that would incorrectly set the frame dimensions on Sprites with the crop component. This was particularly noticeable on Sprites with trimmed animation frames (thanks @sergeod9) -* Fixed a bug where the gl scissor wasn't being reset during a renderer resize, causing it to appear as if the canvas didn't resize properly when `autoResize` was set to `true` in the game config. Fix #4066 (thanks @Quinten @hsan999) -* If a Game instance is destroyed without using the `removeCanvas` argument, it would throw exceptions in the `MouseManager` after the destroy process has run, as the event listeners were not unbound. They're not unbound, regardless of if the parent canvas is removed or not. Fix #4015 (thanks @garethwhittaker) - -### Examples and TypeScript - -A huge thanks to @presidenten for his work on the Phaser 3 Examples. You'll notice they now have a lovely screen shots for every example and the scripts generate them automatically :) - -Also, thanks to the following for helping with the Phaser 3 Examples and TypeScript definitions, either by reporting errors, or even better, fixing them: - -@madanus @truncs @samme - -### Phaser Doc Jam - -The [Phaser Doc Jam](http://docjam.phaser.io) is an on-going effort to ensure that the Phaser 3 API has 100% documentation coverage. Thanks to the monumental effort of myself and the following people we're now really close to that goal! My thanks to: - -31826615 - @16patsle - @bobonthenet - @rgk - @samme - @shaneMLK - @wemyss - ajmetal - andiCR - Arian Fornaris - bsparks - Carl - cyantree - DannyT - Elliott Wallace - felixnemis - griga - Hardylr - henriacle - Hsaka - icbat - Kanthi - Kyle - Lee - Nathaniel Foldan - Peter Pedersen - rootasjey - Sam Frantz - SBCGames - snowbillr - Stephen Hamilton - STuFF - TadejZupancic - telinc1 - -If you'd like to help finish off the last parts of documentation then take a look at the [Doc Jam site](http://docjam.phaser.io). - -## Version 3.13.0 - Yuuki - 20th September 2018 - -### Facebook Instant Games Plugin - -Phaser 3.13 introduces the new Facebook Instant Games Plugin. The plugin provides a seamless bridge between Phaser and version 6.2 of the Facebook Instant Games SDK. Every single SDK function is available via the plugin and we will keep track of the official SDK to make sure they stay in sync. - -The plugin offers the following features: - -* Easy integration with the Phaser Loader so load events update the Facebook progress circle. -* Events for every plugin method, allowing the async calls of the SDK to be correctly inserted into the Phaser game flow. When SDK calls resolve they will surface naturally as a Phaser event and you'll know you can safely act upon them without potentially doing something mid-way through the game step. -* All Plugin methods check if the call is part of the supported APIs available in the SDK, without needing to launch an async request first. -* Instant access to platform, player and locale data. -* Easily load player photos directly into the Texture Manager, ready for use with a Game Object. -* Subscribe to game bots. -* The plugin has a built-in Data Manager which makes dealing with data stored on Facebook seamless. Just create whatever data properties you need and they are automatically synced. -* Support for FB stats, to retrieve, store and increment stats into cloud storage. -* Save Session data with built-in session length validation. -* Easy context switching, to swap between game instances and session data retrieval. -* Easily open a Facebook share, invite, request or game challenge window and populate the text and image content using any image stored in the Texture cache. -* Full Leaderboard support. Retrieve, scan and update leaderboard entries, as well as player matching. -* Support for in-app purchases, with product catalogs, the ability to handle purchases, get past purchases and consume previously unlocked purchases. -* Easily preload a set of interstitial ads, in both banner and video form, then display the ad at any point in your game, with in-built tracking of ads displayed and inventory available. -* Plus other features, such as logging to FB Analytics, creating short cuts, switching games, etc. - -The plugin is fully documented and official tutorials and project templates will follow shortly. - -### New Shape Game Objects - -Phaser 3.13 has a new Game Object called `Shape`, which by itself isn't much use because it's a base class. However, extending that class are 11 different types of Shape (with more to come) and you can use it to create your own custom Shapes as well. Shapes are added to the display list in the exact same way as any other Game Object. For example: - -``` -this.add.rectangle(400, 300, 500, 120, 0x00ff00); -``` - -Here we're creating a new Rectangle shape. It's positioned at 400 x 300 in the Scene and has a size of 500 x 120 pixels. The final value is the fill color. - -The thing to remember is that you can treat this Shape just like you'd treat any other Game Object. You can scale it, rotate it, alpha it, blend mode it, change its origin, give it a Camera scroll factor, put it inside a Container or Group, give it input abilities or even give it a physics body. It is, to all intents and purposes, a normal Game Object. The only difference is that when rendering it uses its own special bit of display code. - -The shapes available are as follows: - -* `GameObject.Arc` - The arc allows you to draw either a circle, or part of a circle. You can set the start and end angle, if the rotation is clockwise or not, and even set the number of iterations the arc will use during rendering. -* `GameObject.Curve` - The Curve Shape can take any Phaser Curve object, such as a Spline or Bezier Curve, and add it to the display list. -* `GameObject.Ellipse` - An ellipse shape, which is essentially a circle with a differing width and height. It can be filled or stroked (or both!) and as with the arc you can set the 'smoothness' of it, allowing you to decrease the number of points used when creating its polygon data. -* `GameObject.Grid` - The Grid Shape object allows you to generate them. You can set the width and height of the grid itself, as well as for the grid cells. The grid can either have a single color, or alternating cell colors and even have outline spacing between the cells, or not. -* `GameObject.Line` - Create a Line Shape drawn between any two points, with a color and thickness. In WebGL you can also specify a different thickness for the start and end of the line. -* `GameObject.Polygon` - A Polygon is effectively a list of points that is drawn between. The points can be provided in a number of different ways (as Vec2 objects, as an array, etc) and then you can either fill or stroke the resulting shape, or both. -* `GameObject.Rectangle` - Simple, but powerful and endlessly useful. Set a width and height and it'll display a Rectangle, with control over the size, fill color and stroke color. -* `GameObject.Star` - The Star shape does as its name suggests: it displays a star. You can control the number of points in the star as well as the inner and outer radius of it. -* `GameObject.Triangle` - A Triangular shape with full control over the points used to make it and its fill and stroke colors. Internally it uses the `batchFillTriangle` method in WebGL, making it actually faster to draw than a Quad! Use them happily for bullets or abstract space ships, or anything else you feel like. -* `GameObject.IsoTriangle` - This draws an isometric triangle, like a pyramid. You can control the colors of each face, if the pyramid is upside down or not and the width and height of it. -* `GameObject.IsoBox` - This draws an isometric box. You can set the colors for each face of the box, as well as the projection angle and also which of the 3 faces are drawn. - -All of the Shape objects render in both Canvas and WebGL and are available via the Game Object Factory. - -### Pointer and Input Event Updates - -The specificity if the input events has been changed to allow you more control over event handling. Previously, the InputPlugin would emit the global `pointerdown` event first, and then the Game Object itself would emit the `pointerdown` event and finally the InputPlugin would emit the `gameobjectdown` event. - -The order has now changed. The Game Object will dispatch its `pointerdown` event first. The InputPlugin will then dispatch `gameobjectdown` and finally the less specific of them all, `pointerdown` will be dispatched. - -New in 3.13 is the ability to cancel this at any stage. All events are now sent an event object which you can call `event.stopPropagation()` on. This will immediately stop any further listeners from being invoked. If you call `stopPropagation()` after the first Game Object `pointerdown` event, then no more Game Object's will receive their callbacks and the InputPlugin will not dispatch either of its events. - -This change has been introduced for `pointerdown`, `pointerup`, `pointermove`, `pointerover` and `pointerout`. No other data is included in the `event` object in this release. - -* The Game Object `pointerdown` callback signature has changed. It used to send `pointer, x, y, camera` to the listener. It now sends `pointer, x, y, event` to the listener. If you still need the `camera` property you can get it from `pointer.camera`. -* The Game Object `gameobjectdown` callback signature has a new argument. It now sends `event` as the 3rd argument. -* The `pointerdown` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerdown` and `gameobjectdown`). This gives you the chance to cancel the event before the global listener receives it. -* The Game Object `pointerup` callback signature has a new argument. It now sends the `event` as the 4th argument. -* The Game Object `gameobjectup` callback signature has a new argument. It now sends `event` as the 3rd argument. -* The `pointerup` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerup` and `gameobjectup`). This gives you the chance to cancel the event before the global listener receives it. -* The Game Object `pointermove` callback signature has a new argument. It now sends the `event` as the 4th argument. -* The Game Object `gameobjectmove` callback signature has a new argument. It now sends `event` as the 3rd argument. -* The `pointermove` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointermove` and `gameobjectmove`). This gives you the chance to cancel the event before the global listener receives it. -* The Game Object `pointerover` callback signature has a new argument. It now sends the `event` as the 4th argument. -* The Game Object `gameobjectover` callback signature has a new argument. It now sends `event` as the 3rd argument. -* The `pointerover` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerover` and `gameobjectover`). This gives you the chance to cancel the event before the global listener receives it. -* The Game Object `pointerout` callback signature has a new argument. It now sends the `event` as the 2nd argument. -* The Game Object `gameobjectout` callback signature has a new argument. It now sends `event` as the 3rd argument. -* The `pointerout` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerout` and `gameobjectout`). This gives you the chance to cancel the event before the global listener receives it. - -### Game Object List Updates - -When Sprite's are created they are added to two lists within the Scene - the Display List and the Update List. Under 3.12 when a Scene was shut down it would emit a `shutdown` event, which Sprites listened out for. When they received it, they would destroy themselves. - -After [profiling and testing](https://github.com/photonstorm/phaser/issues/4028) this process has changed slightly. Game Object's no longer listen for the Scene `shutdown` event. Instead, the Display List and Update List will iterate their children and call `destroy` on them in turn. If being destroyed by a Scene in this way, the child will skip several expensive operations in its destroy function. More importantly, in busy Scenes you no longer need thousands of event listeners registered. The result is that changing Scene is now up to 100% faster than before. You need not change your code to benefit from this, however, if you were relying on custom Game Objects listening for the Scene `shutdown` event natively, then this is no longer the case and you'll have to manually add that listener to your classes. - -* The UpdateList will now clear out its internal `_list`, `_pendingRemoval` and `_pendingInsertion` lists on shutdown. Before, it would only clear `_list`. -* `GameObject.destroy` has a new optional boolean argument `fromScene`, which controls how the destroy process flows. - -### Camera Render to Texture - -In 3.12 a new Camera method called `setRenderToTexture` was introduced. However, it had known issues so was placed under the experimental flag and you were advised not to use it unless in testing. - -Thanks to several fixes in this release the experimental flag has been dropped and it's now safe to try using this new feature in production. - -The method sets the Camera to render to a texture instead of to the main canvas. The Camera will redirect all Game Objects it's asked to render to this texture. During the render sequence, the texture itself will then be rendered to the main canvas. - -Doing this gives you the ability to modify the texture before this happens, allowing for special effects such as Camera specific shaders, or post-processing on the texture. - -* `Camera.setRenderToTexture` is a new method that enables the Camera to render to a target texture instead of the main canvas, allowing for application of special effects at run-time. -* `Camera.clearRenderToTexture` is a new method that stops a Camera from rendering to a texture and frees-up all associated resources. -* `Camera.setPipeline` allows you to change the WebGL pipeline being used if the Camera is rendering to a texture, effectively swapping the active shader. Call with no arguments to clear the pipeline. -* `Camera.renderToTexture` is a boolean property that controls where the Camera renders. It can be toggled on the fly. -* `Camera.canvas` is a Canvas Element that the Camera will render to if running under the Canvas Renderer and rendering to a texture. -* `Camera.context` is a Rendering Context that the Camera will render to if running under the Canvas Renderer and rendering to a texture. -* `Camera.glTexture` is a WebGL Texture that the Camera will render to if running under the WebGL Renderer and rendering to a texture. -* `Camera.framebuffer` is a WebGL Frame Buffer that the Camera will render to if running under the WebGL Renderer and rendering to a texture. -* `Camera.pipeline` is the Pipeline that the Camera will render with if running under the WebGL Renderer and rendering to a texture with a pipeline set. -* If you set a Camera to render to a texture then it will emit 2 events during the render loop. First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before it appears in-game. - -### New Features - -* The `Color` object has a new property `h` which represents the hue of the color. You can tween or adjust this property in real-time and it will automatically update the internal RGB values with it. -* The `Color` object has a new property `s` which represents the saturation of the color. You can tween or adjust this property in real-time and it will automatically update the internal RGB values with it. -* The `Color` object has a new property `v` which represents the lightness value of the color. You can tween or adjust this property in real-time and it will automatically update the internal RGB values with it. -* `Color.setFromHSV` is a new method that will set the color values based on the HSV values given. -* `Color.gray` is a new method that will set the color to be a shade of gray based on the amount given. -* `Color.random` is a new method that will set the color to be a random hue based on the min and max values given. -* `Color.randomGray` is a new method that will set the color to be a random grayscale based on the min and max values given. -* `Color.saturate` is a new method that will saturate the color based on the amount given. This is a chainable version of adjusting the saturation property directly. -* `Color.desaturate` is a new method that will desaturate the color based on the amount given. This is a chainable version of adjusting the saturation property directly. -* `Color.lighten` is a new method that will lighten the color based on the amount given. This is a chainable version of adjusting the value property directly. -* `Color.darken` is a new method that will darken the color based on the amount given. This is a chainable version of adjusting the value property directly. -* `Color.brighten` is a new method that will brighten the color based on the amount given. -* The `CanvasTexture` class has a new property `imageData` which contains the ImageData of the texture. -* The `CanvasTexture` class has a new property `data` which is a Uint8ClampedArray view into the `buffer`. -* The `CanvasTexture` class has a new property `pixels` which is a Uint32Array view into the `buffer`. -* The `CanvasTexture` class has a new property `buffer` which is an ArrayBuffer the same size as the context ImageData. -* The `CanvasTexture` class has a new method `update` which refreshes the ImageData and ArrayBuffer based on the texture contents. -* The `CanvasTexture` class has a new method `draw` which draws the given Image or Canvas element to the CanvasTexture, then updates the internal ImageData buffer and arrays. -* The `CanvasTexture` class has a new method `getPixel` which will get the color of a specific pixel from the Canvas Texture and store it in the returned Color object. It uses the ArrayBuffer to do this, which is extremely fast, allowing for quick iteration across the canvas data. -* The WebGLPipeline and WebGLRenderer have new a method `setFloat1v` which allows you to set a `uniform1fv` uniform value (thanks @Mattykins) -* The WebGLPipeline and WebGLRenderer have new a method `setFloat2v` which allows you to set a `uniform2fv` uniform value (thanks @Mattykins) -* The WebGLPipeline and WebGLRenderer have new a method `setFloat3v` which allows you to set a `uniform3fv` uniform value (thanks @Mattykins) -* The WebGLPipeline and WebGLRenderer have new a method `setFloat4v` which allows you to set a `uniform4fv` uniform value (thanks @Mattykins) -* `Text.setLineSpacing` is a new method that allows you to easily set the line spacing value of a Text object in a chainable call (thanks @RafelSanso) - -### Updates - -* The Graphics Canvas Renderer will now automatically call `beginPath` on the target context before processing the command stack. This has the effect of clearing off any sub-paths that may have persisted on the stack from previous Graphics objects or frames. This makes it more in-line with WebGL re: expectations when calling `Graphics.clear`. -* `initPipeline` now defaults to the Texture Tint Pipeline if nothing else is specified. This allowed me to remove explicit strings from 11 different Game Objects, saving some bytes in the process. -* The `RGBToHSV` function can now take an optional `out` argument, which is either a `HSVColorObject` or a `Color` object, and the results will be set into that object instead of creating a new one. -* The `HSVToRGB` function can now take an optional `out` argument, which is either a `HSVColorObject` or a `Color` object, and the results will be set into that object instead of creating a new one. -* `Color.setTo` has a new argument `updateHSV` which allows you to control if the internal HSV values are updated during the same call or not. -* The `Text._lineSpacing` property has been renamed to `lineSpacing` and made public, not private. You still set it in the same way, by passing a `lineSpacing` property to the Text configuration object, but internally it's now clearer. -* If a Scene is already active (i.e. running) and you call `start` on it (such as from another Scene) then it will shutdown the Scene first, before starting it again. - -### Bug Fixes - -* TileSprite.setTileScale would set the tile position by mistake, instead of the scale. Using the properties directly worked, but the method was incorrect (thanks @alexeymolchan) -* Calling `Text.setStyle` would make the Text vanish if you didn't provide a `resolution` property in the style configuration object. Calling `setStyle` now only changes the properties given in the object, leaving any previously changed properties as-is. Fix #4011 (thanks @okcompewter) -* In Matter.js if a body had its debug `render.visible` property set to `false` it wouldn't then render any other debug body beyond it. Now it will just skip bodies with hidden debug graphics (thanks @jf908) -* If you flagged a Tween as `paused` in its config, never started it, and then called `Tween.stop` it wouldn't ever be removed from the `_pending` array. It's now moved to the Tween Manager's destroy list, ready for removal on the next frame. Fix #4023 (thanks @goldfire) -* Game Objects would not remove themselves from the Scene's `shutdown` event handler when destroyed, leading to a build-up over time (thanks @goldfire) -* The WebGL Renderer will no longer try and just resize a canvas backed texture, instead it will properly delete it then re-create it. Fix #4016 (thanks @alexeymolchan) -* The Camera background for mini-Cameras (those positioned deep inside another Camera) would be offset incorrectly in WebGL, causing the background fills to be displaced (thanks @aaronfc) -* The WebGL Renderer now always enables the `SCISSOR_TEST`, this allows Game Objects that use the scissor (such as custom objects, or Bitmap Text) to render properly again. -* The Cameras `setScene` method, which is called automatically when a new Camera is created, will now call `updateSystem` which correctly increases the custom viewport counter. This fixes an issue with mini-cams inside of larger cameras not clipping their contents properly. If a Camera is moved to another Scene it also now correctly shrinks the total custom viewport counter. -* Due to the two fixes above another bug was fixed: The ability for you to swap between Cameras with and without `setRenderToTexture` enabled with custom shaders. Previously if you used this with a custom shader then only the first Camera using the shader would render, the rest would appear black. Now, all Cameras using the custom shader work correctly. As a result all of the 'experimental' Camera rendering properties from 3.12 have been moved to stable. -* If you destroyed a Game Object that had a custom cursor set during one of its input events the cursor didn't correctly reset. Fix #4033 (thanks @pantoninho) -* `RenderTexture.resize` wouldn't correctly resize the texture under WebGL. Fix #4034 (thanks @jbpuryear) -* Calling `setFrame` on a TileSprite wouldn't change the frame, it would just change the frame size. Fix #4039 (thanks @Jerenaux) -* `Zone.setRectangleDropZone` used the wrong `x` and `y` coordinates for the hit area, causing it to be offset from the zone itself after the changes made for issue #3865 in the 3.12 release. - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@johanlindfors @Arthur3DLHC @JamesSkemp - -## Version 3.12.0 - Silica - 4th September 2018 - -### FlatTintPipeline Updates - -In 3.11 I overhauled the TextureTintPipeline, the WebGL batch used to render all texture based Game Objects, such as Sprites. In this release I did the same to the FlatTintPipeline. This pipeline was used exclusively by the Graphics Game Object to draw filled and stroked primitives in WebGL. It was also used by classes such as the Camera in order to draw their colored backgrounds and flash / fade effects. - -When I looked closely at the shaders being used by the texture and graphics pipelines I noticed they were virtually identical. Yet if you were to mix Graphics objects and Sprites in your game, it would cause a complete batch flush as it switched between the them as it rebound the shaders, adding to both the draw calls and gl ops per frame. - -The more I looked through the graphics pipeline, the more I saw the same kind of things the texture one previously had: duplicate vars, in-line matrix operations and so on. So I worked through the process of refactoring it, boiling it down to just a handful of core methods and re-using methods the texture pipeline already had. The end result is that I've been able to remove the FlatTintPipeline entirely. This saves 42.3KB (unminifed) and removes 1000 lines of code from the build. Of course, lots of the methods were added to the texture pipeline, but that only increased from 730 sloc to 1087 sloc, a fraction of the amount before! And the benefits don't end there. - -If you had any custom pipelines that extended the FlatTintPipeline please update them to extend the TextureTintPipeline instead. You'll likely need to remap a few methods, but most of them remain the same. Double-check the method signatures though. - -The same pipeline can now draw both graphics and sprites, with the same shader and no texture swapping either. This means you can happily mix Graphics objects alongside Sprites and it won't cost any extra overhead at all. There are more benefits too, which are outlined in the list below. - -* The TextureTintPipeline now has 100% jsdoc coverage. -* The removal of the FlatTintPipeline shaves 42.3KB and 1000 sloc from the bundle size. -* The Graphics fill and line styles are now cached in the pipeline, rather than being re-calculated for every primitive drawn. -* The new `batchTri` method will add a triangle to the vertex batch, either textured or filled. -* `drawFillRect` is a new method that will add an untransformed rectangle to the batch. These are used by things like Cameras to fill in background colors. -* `batchFillRect` has been moved to the TextureTintPipeline and has a new much more concise method signature. -* `batchFillTriangle` has been moved to the TextureTintPipeline and has a new much more concise method signature. -* `batchFillPath` has been moved to the TextureTintPipeline and has a new much more concise method signature. -* `batchLine` has been moved to the TextureTintPipeline. -* When drawing Graphics paths with a line width of 1 it will no longer spend any time drawing the line joins, speeding-up the rendering of 1px lines. - -### WebGL Scissor Update - -The process of managing scissors in the WebGLRenderer has been completely rewritten. Previously, the gl scissor was being constantly enabled and disabled for every Camera in your game, leading to pointless gl operations. - -* Cameras have a new internal method `updateSystem` which is automatically called if you change any Camera viewport values. This in turn tells the Scene Manager if there are any cameras with custom viewports, in any Scene of your game. If there are not then the scissor is never even enabled or set, meaning zero gl ops! If your game uses full sized Cameras it now doesn't cost anything at all with regard to scissoring. -* If a new scissor is set it will now check to see if it's the same size and position as the current scissor, and if so, it'll skip setting it at all. - -### Render Texture New Features and Updates - -The Render Texture class has been rewritten from scratch and all Game Objects have been updated to support it. Previously it was very restricted in what you could do with it. It used to have a matrix stack for internal transforms, but this has been replaced with a Camera instead. This means you have the full power of a Camera system (scrolling, zooming, rotation) but it only impacts the contents of the Render Texture. - -* The biggest update is the change in what the `draw` method can accept. Previously you had to pass in a texture and frame reference. This has changed, as has the method signature. It can now accept any of the following: - - - Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. - - Dynamic and Static 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. Pass in `Scene.children` to draw the whole display list. - - Another Render Texture. - - A Texture Frame instance. - - A string. This is used to look-up a texture from the Texture Manager. - -* There is a new method `drawFrame` which allows you to pass in a string-based texture and frame key and have it drawn to the Render Texture. -* The new method `saveTexture` allows you to save the Render Texture into the Texture Manager using your own key. You can then use the Render Texture for any Game Object that accepts textures as a source, such as Sprites or even Tilemap Layers. You can add frame data to a Render Texture using the `RenderTexture.texture.add` method. -* The new `camera` property is an instance of a complete 2D Camera. You can use it to change the view into your Render Texture. Scroll, rotate, zoom, just like you would with a normal Camera, except it will only influence the objects being drawn to the Render Texture. -* All of the matrix-style methods have been removed: `save`, `translate`, `restore`, `scale`, `rotate`. You can now achieve the same thing by either transforming the object you want to draw to the Render Texture, or using the built-in Camera. -* You can now crop a Render Texture. Use the `setCrop` method to define the crop region. - -See the fully complete documentation for more details and the extensive examples and tests created. - -### Text Game Object New Features and Updates - -The Text Game Object has been given an internal overhaul to make it more flexible. Some properties have been renamed or moved and new features added: - -* Text can now be cropped in WebGL and Canvas! Use the `setCrop` method to crop the text. -* Text now keeps a reference to the renderer in the `renderer` property. -* The `canvasTexture` property has been removed. -* Text now has internal `texture` and `frame` properties. These replace the old `canvasTexture` but perform the same task, while allowing for texture cropping and much smaller renderer code. -* Previously, changing a Text object by setting its `text` property directly wouldn't change the text being rendered as using `setText` was the expected way to change what was being displayed. Internally the `text` property has been renamed to `_text` and flagged as private, and a new getter / setter for `text` has been added, which hands over to the `setText` method, meaning you can now use both ways of setting the text. Fix #3919 (thanks @hackhat @samid737) - -### Tile Sprite Object New Features and Updates - -The Tile Sprite Game Object has been given an internal overhaul to make it more flexible. Some properties have been renamed or moved and new features added: - -* Tile Sprites can now be cropped in WebGL and Canvas! Use the `setCrop` method to crop the tile sprite. -* There is a new method `setTileScale` which will set the tile scale in a chainable call. -* There is a new internal `canvas` property. Tile Sprites work differently than before in Canvas mode: Previously they would use the `fillRect` command on the game canvas to draw themselves every frame, even if they hadn't changed. They now draw to an internal canvas only when their position or scale changes. This canvas is then drawn to the game canvas instead. It's faster, as it doesn't fillRect every frame and also allows you to draw them to other contexts, such as Render Textures. -* There are two new internal properties `_tilePosition` and `_tileScale` which are Vector 2s that hold the position and scale. Getters have been added, so use the same properties as before in your code. -* There are two new properties `displayTexture` and `displayFrame`. These replace the previous `texture` and `frame` properties and hold references to the source texture the Tile Sprite is using. -* The `canvasPattern` property has been renamed to `fillPattern`. -* The `oldFrame` property has been removed. -* The `canvasBuffer` property has been renamed to `fillCanvas`. -* The `canvasBufferCtx` property has been renamed to `fillContext`. - -### Tilemap New Features and Updates - -The Tilemap and Dynamic and Static Tilemap Layer classes now all support 4 different modes of render order for drawing the tiles. This allows you to control the z-order of the tiles during render. This feature was requested by @etienne (who provided the test maps too) - see the new examples in the Labs for better understand the impact this has. - -The default is 'right-down', meaning it will order the tiles starting from the top-left, drawing to the right and then moving down to the next row. - -The four draw orders are: - -0 = right-down -1 = left-down -2 = right-up -3 = left-up - -* Tilemap has a new property `renderOrder` which is a string based version of the render order, as used when new layers are created via the map. If the map is created from Tiled JSON data, it will use whatever render order has been specified in the map data. -* Tilemap has a new method `setRenderOrder`. This takes either an integer or a string-based version of the render order and stores it locally. It's then used during the creation of any layers from that point on. -* The DynamicTilemapLayer has a new method `setRenderOrder`. This takes either an integer or a string-based version of the render order and stores it locally. It's then used during rendering of the layer. You can change the value on the fly. -* The StaticTilemapLayer has a new method `setRenderOrder`. This takes either an integer or a string-based version of the render order and stores it locally. Under WebGL it will re-create the whole vertex buffer, using the new draw order. Under Canvas it uses it at run-time during rendering. You can change it on the fly. -* ParseJSONTiled now extracts the `renderorder` property from the Tiled JSON. -* MapData has a new `renderOrder` property, which is populated by the Tiled Parser. - -### Matter.js Updates - -The version of Matter.js used by Phaser has been updated from 0.13.1 to 0.14.2. To clarify why we don't include Matter via npm, it's because we use a customized version of Matter that includes extra features and optimizations not yet found in the official library. - -Most of the updates were about documentation and module namespacing, however those relevant to Phaser are listed below. You can also view the full [Matter Change Log](https://github.com/liabru/matter-js/blob/master/CHANGELOG.md). - -* fix Composite.bounds global issue, closes #627, closes #544 ([f7f77b4](https://github.com/liabru/matter-js/commit/f7f77b4)), closes [#627](https://github.com/liabru/matter-js/issues/627) [#544](https://github.com/liabru/matter-js/issues/544) -* updated pathseg library, closes #548, closes #602, closes #424 ([1e5758f](https://github.com/liabru/matter-js/commit/1e5758f)), closes [#548](https://github.com/liabru/matter-js/issues/548) [#602](https://github.com/liabru/matter-js/issues/602) [#424](https://github.com/liabru/matter-js/issues/424) -* fix Common.isElement on node, closes #535 ([ec38eeb](https://github.com/liabru/matter-js/commit/ec38eeb)), closes [#535](https://github.com/liabru/matter-js/issues/535) -* added Query.collides, closes #478 ([6593a72](https://github.com/liabru/matter-js/commit/6593a72)), closes [#478](https://github.com/liabru/matter-js/issues/478) -* fix `point` argument of Body.scale, closes #428 ([894c1ef](https://github.com/liabru/matter-js/commit/894c1ef)), closes [#428](https://github.com/liabru/matter-js/issues/428) -* fix Body.scale for compound bodies ([50a89d0](https://github.com/liabru/matter-js/commit/50a89d0)) -* fix centroid for static compound bodies, closes #483 ([ece66e6](https://github.com/liabru/matter-js/commit/ece66e6)), closes [#483](https://github.com/liabru/matter-js/issues/483) -* fix Common.isElement, closes #501, closes #507, closes #459, closes #468, closes #517 ([18a0845](https://github.com/liabru/matter-js/commit/18a0845)), closes [#501](https://github.com/liabru/matter-js/issues/501) [#507](https://github.com/liabru/matter-js/issues/507) [#459](https://github.com/liabru/matter-js/issues/459) [#468](https://github.com/liabru/matter-js/issues/468) [#517](https://github.com/liabru/matter-js/issues/517) -* fix inertia change in Body.setMass, closes #378 ([f7d1877](https://github.com/liabru/matter-js/commit/f7d1877)), closes [#378](https://github.com/liabru/matter-js/issues/378) -* fix Vertices.chamfer radius argument, closes #467 ([3bceef4](https://github.com/liabru/matter-js/commit/3bceef4)), closes [#467](https://github.com/liabru/matter-js/issues/467) - -### Camera 3D Plugin - -Support for Camera 3D and Sprite 3D Game Objects have been removed from the core Phaser bundle and moved to an optional plugin. - -You can find the source for Camera 3D in the new `plugins/camera3d` folder, along with a README file explaining how to now use the plugin in your games. - -* When a Sprite3D object is added to a Camera via `Camera.add` it is now added to the Display and Update Lists. Fix #3945 (thanks @vvega) - -### New Features - -* `Camera.resolution` is a new read-only property that holds the current game config resolution that the camera is using. This is used internally for viewport calculations. -* `Text.resolution` and the method `Text.setResolution` allows you to control the resolution of a Static Text Game Object. By default it will be set to match the resolution set in the Game Config, but you can override it yourself via the TextStyle. It allows for much clearer text on High DPI devices, at the cost of larger internal Canvas textures for the Text - so please use with caution, as the more high res Text you have, the more memory it uses up. Fix #3528 (thanks @kirillbunin) -* `TransformMatrix.getCSSMatrix` will return a CSS transform matrix formatted string from the current matrix values. -* `CacheManager` now creates a new cache called `html` which is used to store all loaded HTML snippets. -* `FileType.HTML` is a new file type loader that will load an HTML snippet and store it in the new `html` cache. Access it via `load.html` (this method was previously used to load html to textures, please see `load.htmlTexture` for this feature now) -* `TransformMatrix.getX` is a new method that return the x component from the given x and y values based on the current matrix. This is used heavily in the pipelines. -* `TransformMatrix.getY` is a new method that return the y component from the given x and y values based on the current matrix. This is used heavily in the pipelines. -* `TransformMatrix.copyToArray` is a new method that will copy the matrix values to the given array. It's the counter-part of `copyFromArray`. -* `Graphics.setTexture` is a new WebGL only method that allows you to set a texture to be used when drawing the shapes on the Graphics object. You can also specify how the texture should be blended with the current fill or gradient colors. Note that the texture is not tiled, it is stretched to fit the shape being drawn. -* `Graphics.fillGradientStyle` is a new WebGL only method that allows you to set a gradient for the shapes being filled. You can control the colors at the 4 corners of a rectangle. The colors are then blended automatically in the shader. Use of this feature is limited. For example, you cannot gradient fill a whole path or an arc, as it's made up of lots of triangles. But for quick gradient backgrounds or buttons it's perfect. -* `Graphics.lineGradientStyle` is a new WebGL only method that allows you to set a gradient for the shapes being stroked. You can control the colors at the 4 corners of a rectangle. The colors are then blended automatically in the shader. Use of this feature is limited. For example, you cannot gradient stroke a whole path or an arc, as it's made up of lots of triangles. But for quick gradient lines it's perfect. -* `TextureManager.getBase64` is a new method that will take a texture frame key and return a base64 encoded version of the frame. You can also provide the image type and encoder options. -* Global Plugins now have a new optional `data` object, the contents of which are passed to the plugins `init` method. This allows users to pass data directly into a plugin when added in the config: `{ key: 'BankPlugin', plugin: BankPluginV3, start: true, data: { gold: 5000 } }` or when adding a plugin via the `install` method (thanks @samme) -* You can now play animations in reverse! Use the new `Sprite.anims.playReverse` method to play a pre-defined animation in reverse from its starting frame. Or call `Sprite.anims.reverse` to immediately reverse the flow of an already running animation. Animations running in reverse still count towards the repeat total and respect the yoyo flag (thanks @khaleb85 @Ben-Millions) -* The `ParticleEmitterManager` now has the Transform component. This means you can now set the position, rotation or scale of the Emitter Manager, and it will influence every Emitter it is rendering. The Managers transform is mixed with that of the Camera. This works in both Canvas and WebGL. -* `TextureManager.addRenderTexture` is a new method that will add a Render Texture into the Texture Manager, allowing you to use it as the texture for Game Objects just by using the texture key. Modifying the source Render Texture will immediately modify any Game Objects using it. -* TextureSource has a new boolean property `isRenderTexture` which is set automatically when it's created. -* The Canvas Renderer has a new method `setContext` which allows it to swap the context being drawn to by all draw operations. Call the method with no arguments to reset it to the default game canvas. -* If you set `window.FORCE_WEBGL` or `window.FORCE_CANVAS` in the window in which the Phaser game is loaded it will over-ride the renderer type setting in your game config, and force either WebGL or Canvas. This is handy for quickly testing the differences between renderers without having to do a new build each time. -* `TextureSource.source` is a new property that contains the original source of the Texture image. It is cleared when the source is destroyed. -* `TransformMatrix.copyToContext` is a new method that will copy the values from the Matrix to the given Canvas Rendering Context. -* `Phaser.Utils.String.UUID` will return an RFC4122 complaint UUID as a string. This is used internally to avoid cache key conflicts, but is exposed for your own use as well. -* There is a new `Crop` Component which is used by non-texture based Game Objects, such as Text and TileSprite. You either use `TextureCrop` or `Crop`, not both together on the same object. -* `TransformMatrix.setToContext` is a new method that will set the values from the Matrix to the given Canvas Rendering Context using setTransform rather than transform. -* `SetTransform` is a new Canvas Renderer function that consolidates the process of preparing a Game Object for rendering, without actually rendering it. This is used internally by the Graphics and Bitmap Text classes. -* The Texture Manager has a new method called `renameTexture` which will let you rename a texture, changing the key to the new one given. All existing Game Objects will still maintain their reference, even after a rename. -* When loading an SVG file you can now change the size of the SVG during the load process, before it is rendered to a texture. This is really helpful if you wish to increase SVGs that have small viewBoxes set, or want to try and reduce memory consumption from SVGs with extra large dimensions. You can either pass in a fixed width and height: `this.load.svg('morty', 'file.svg', { width: 300, height: 600 })` or you can provide a scale factor instead: `this.load.svg('morty', 'file.svg', { scale: 4 })` (thanks @ysraelJMM) -* `Polygon.Perimeter` will return the perimeter for the given Polygon (thanks @iamchristopher) -* `Polygon.GetPoints` will return an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, based on the given quantity or stepRate values. This is available as a static function and as the `getPoints` method on a Polygon (thanks @iamchristopher) - -### Updates - -* The Camera class has been split into two: `BaseCamera` which contains all of the core Camera functions and properties, and would serve as a great base for you to extend for your own custom Cameras, and `Camera` which is the same class name as previously. `Camera` extends the Base Camera and adds in follower support and the Special Effects. You don't need to update your code, even if currently extending a Camera, as they work the same as before. -* `Camera.x` and `Camera.y` have been turned into getters / setters, mapped to the internal private values `_x` and `_y` respectively. This is so that setting the Camera viewport position directly will now update the new internal resolution calculation vars too. -* `Camera.setScene` will now set the Cameras `resolution` property at the same time and update the internal viewport vars. -* The `Cull Tiles` method used by the Dynamic Tilemap Layer has had a nice and significant optimization. It will now use the cull area dimensions to restrict the amount of tile iteration that takes place per layer, resulting in dramatic reductions in processing time on large layers, or multiple layers (thanks @tarsupin) -* `GameObject.willRender` now takes a Camera as its only argument and uses it within the check. This has allowed me to remove 23 duplicate checks spread across the various Game Objects, all of which did the same thing, saving both KB and CPU time as the flags were being checked twice in most cases. -* The file type loader `HTML` has been renamed to `HTMLTexture`. If you were using this then please change your calls from `load.html` to `load.htmlTexture`. The arguments remain the same. -* The `setBlendMode` method in the WebGL Renderer now returns a boolean. True if a new blend mode was set, otherwise false. Previously it returned a reference to the renderer instance. -* The method `batchVertices` in the TextureTintPipeline has been renamed to `batchQuad` which more accurately describes what it does. -* In ArcadePhysics `Body.setSize` you can now choose to not pass width and height values to the method. If you do this it will check to see if the parent Game Object has a texture frame, and if so, it will use the frame sizes for the Body dimensions (thanks @tarsupin) -* `PluginCache.destroyCorePlugins` will remove all core plugins from the cache. Be very careful calling this as Phaser cannot restart or create any new Scenes once this has been called. -* `PluginCache.destroyCustomPlugins` will remove all custom plugins from the cache. -* `PluginManager.destroy` will now clear all custom plugins from the Plugin Cache. This fixes an issue with not being able to destroy a Phaser game instance and restart it if it used a custom plugin (thanks jd.joshuadavison) -* `Game.destroy` has a new boolean argument `noReturn`. If set it will remove all Core plugins when the game instance is destroyed. You cannot restart Phaser on the same web page after doing this, so only set it if you know you're done and don't need to run Phaser again. -* The `MouseManager` will no longer process its native events if the manager reference has been removed (i.e. you move the pointer as the game is destroying itself) -* The `TouchManager` will no longer process its native events if the manager reference has been removed (i.e. you move the pointer as the game is destroying itself) -* `Particle.color` has been removed as it's now calculated during rendering to allow for Camera alpha support. -* The Game boot event flow has changed slightly. The Game will now listen for a `texturesready` event, which is dispatched by the Texture Manager when the default textures have finished processing. Upon receiving this, the Game will emit the `ready` event, which all the other systems listen for and respond to. The difference is that the Renderer uses the `texturesready` event to ensure that it is the first thing to be activated, before any other system. -* The WebGLRenderer has a new property `blankTexture` which is a reference to an empty 32x32 transparent WebGL Texture. This is used internally for things like rendering Graphics with no texture fills and where no other texture has been set. -* The WebGLRenderer has a new method `setBlankTexture` which forces it to set the blank texture as the current texture. This is used after drawing a Render Texture to ensure no other object tries to draw to itself. -* The StaticTilemapLayer has had the following properties and methods added to it: `skipCull`, `tilesDrawn`, `tilesTotal`, `cullPaddingX`, `cullPaddingY`, `cullCallback`, `setSkipCull` and `setCullPadding` as these are all used by the Canvas Static Layer renderer. Static Layers in 3.11 didn't render in Canvas because the cull values were missing, but now render correctly and can also be rendered to other targets, like a Render Texture. -* The Math.Snap methods `Snap.Floor`, `Snap.Ceil` and `Snap.To` have all gained a new optional boolean argument `divide`. If set the resulting snapped value will be divided by the gap amount before returning. This is handy if you're trying to quickly snap a value into a grid or array location. -* The `currentBlendMode` property has been removed from the Canvas Renderer and is no longer checked by any class. Blend modes are now set directly on the context to avoid state saving invalidation. -* The `currentAlpha` property has been removed from the Canvas Renderer and is no longer checked by any class. Alpha values are now set directly on the context to avoid state saving invalidation. -* `TextureCrop` and `Crop` have a new method `resetCropObject` which generates the crop data object required by Game Objects that support cropping. This allows us to remove duplicate code from a number of Game Objects and replace it with a single function call. -* The Canvas Renderer has a new `batchSprite` method that consolidates the process of drawing a texture-based Game Object to the canvas. It processes the alpha, blend mode and matrix calculations in a single function and now is used by nearly all Game Object canvas renderers. -* The `batchTexture` method in the Texture Tint Pipeline now supports cropped Game Objects and will adjust the drawn texture frame accordingly. -* The `Matrix Stack` Component has been removed. It's no longer used internally and was just wasting space. -* You can now specify the `lineHeight` of a Retro Font in the Retro Font Config object (thanks @FelixNemis) -* When a Static Tilemap Layer is generated in WebGL it will use the Cameras `roundPixels` value to clamp the tile coordinates. -* The `CanvasRenderer.DrawImage` function has been removed, as has the associated `drawImage` property from the Canvas Renderer as they're no longer used. -* The `CanvasRenderer.BlitImage` function has been removed, as has the associated `blitImage` property from the Canvas Renderer as they're no longer used. -* You can now access the Game instance directly from a Scene using `this.game` as long as it exists in the Scene's Injection Map, which it does by default. Be very careful what you do here: there's next to nothing you should actually use this for. -* `Camera.ignore` can now take nested-arrays of Game Objects and also supports both Groups and Containers. -* The `changedata` event dispatched by the Data Manager now includes the previous value as the 4th argument to the callback, so the event signature is now: `parent, key, value, previousValue` (thanks @iamchristopher) -* The call to `gl.clearColor` is now skipped when `clearBeforeRender` is set to `false` (thanks @goldfire) -* The calls to `DistanceBetween` have been replaced with `DistanceSquared` in the `closest` and `furthest` functions within Arcade Physics (thanks @Mursaat) -* The RandomDataGenerator will now create a default random seed if you instantiate your own version of the class (instead of using `Phaser.Math.RND`) and don't provide a seed for it (thanks michaeld) -* The Tilemap `createFromObjects` method will now add custom properties to the Game Objects. It works by checking if the property exists or not, and if not, it sets it in the Game Objects Data Manager (thanks @scalemailted @samme) -* In Matter.js if you scaled a Body it would only scale correctly once, due to the way Matter handles scaling internally. We now automatically reset the Matter scale before applying the new value, which allows you to keep the Phaser and Matter object scales in sync. Fix #3785 #3951 (thanks @bergben) -* The default Container Blend Mode is now `SKIP_TEST`. This allows you to either set a blend mode for a Container, in which case all children use that blend mode. Or, you can set a blend mode on the children and the children will render using their own blend modes, as the Container doesn't have one set. The WebGL and Canvas Renderer functions have also been updated to support this change. Fix #3684 (thanks @TadejZupancic) -* Previously the Input Manager would create a Touch handler unless the Game Config had `input.touch` set to `false` (the default was true). If no such property is set, it no longer defaults to `true` and instead is set to whatever `Device.input.touch` returns. On non-touchscreen desktops this means it will now only create one single Pointer, rather than two. -* The Arcade Physics Body `_tempMatrix` property has been removed. It was only used if the Body's Game Object had a parent. The matrix has been moved to the World instance instead, shared by all bodies. -* Arcade Physics World has gained two new private properties `_tempMatrix` and `_tempMatrix2`. These are used by all bodies in the simulation that need a temporal matrix for calculations, rather than having their own instances. -* The Input Manager has gained a new private property `_tempMatrix2`. This is used internally in the hitTest checks to avoid constant matrix creation. -* The Transform Matrix has a new method `applyInverse` which will take an x/y position and inverse translate it through the current matrix. -* Using `keyboard.addKeys("W, A, S, D")` would fail because of the spacing between the characters. `addKeys` will now trim the input allowing you to space characters out if you prefer (thanks @dhruvyad) -* Calling `setTimeScale` on the Sprite's Animation component will now set the time scale value and keep it set until you change it again. Previously it would be reset to 1 when a new animation was loaded into the component, but this no longer happens - once the time scale is set it remains in effect, regardless of which animations are played on the Sprite. - -### Game Config Resolution Specific Bug Fixes - -Setting the `resolution` property in the Game Config to a value other than 1 would cause various errors in the API. The following have been fixed: - -* The game canvas would be sized incorrectly, unless you had enabled auto resizing. It now scales the canvas to the size given, maintaining the resolution. Fix #3468 (thanks @Legomite) -* Cameras with background colors set would display the filled color area at the wrong size. Camera fills now respect the resolution. -* The Camera Fade Effect would display the fade fill rectangle at the wrong size. Camera fades now respect the resolution. -* The Camera Flash Effect would display the fade fill rectangle at the wrong size. Camera flashes now respect the resolution. -* The Camera Shake Effect would shake the Camera using the wrong width values. Camera Shakes now respect the resolution. -* Input calculations would not factor in the Game Resolution correctly. If a Camera viewport was not at 0x0 or not the full size, or the Camera was rotated or zoomed, the input areas would be wrong if `resolution` was > 1. These are now factored in correctly and changing the resolution no longer breaks input. Fix #3606 (thanks @Secretmapper @thanh-taro) - -### Bug Fixes - -* The `setCrop` method stored its crop object on the prototype chain by mistake, causing all Images or Sprites that were cropped to display the same frame. The crop data has been moved to the Game Object instance, where it should be, fixing this issue (thanks NoxBrutalis) -* If an AudioFile failed to load and throw an incomplete error, it would cause the console.log to crash JavaScript when trying to log the error. It now only logs the message if it exists. Fix #3830 (thanks @kelostrada) -* Particles using a blend mode wouldn't render correctly after the updates in 3.11. If the blend mode changes during the processing of an emitter manager it'll now correctly rebind the texture, stopping the particles from vanishing. Fix #3851 (thanks @maxailloud) -* Adding an array of children to a Group would cause it to mistakenly think you were passing a config object. Fix #3854 (thanks @pedro-w) -* Graphics paths in WebGL would not render the line join between the final and the first path if the path was closed, leaving a noticeable gap if you used particularly thick strokes. If the path is closed it will now render the final line join properly. -* If a Mesh caused a batch flush it would fail to render as its texture was lost. It's now rebound correctly after the flush. -* `ArcadePhysics.closest` and `ArcadePhysics.furthest` used the wrong tree reference, causing them to throw errors (thanks @samme) -* `BlitterCanvasRenderer` would fail to render a Bob in Canvas mode if it was flipped (thanks @SBCGames) -* `RenderTexture.draw` would fail to draw the frame in Canvas mode (thanks @SBCGames) -* `ParticleEmitter` would fail to draw a textured particle in Canvas mode (thanks @SBCGames) -* `RenderTexture.preDestroy` will now release the canvas back to the CanvasPool if running in canvas mode (thanks @SBCGames) -* The `alpha` value is now always set for Render Textures in canvas mode, regardless of the previous alpha value in the renderer (thanks @SBCGames) -* Zone now calls `updateDisplayOrigin` in its constructor, causing the `displayOriginX` and `displayOriginY` values to now be correct if you create a Zone and then don't resize it. Fix #3865 (thanks @rexrainbow) -* The `CameraManager` was accidentally adding extra destroy event calls when a Scene was restarted, causing an `Uncaught TypeError: Cannot read property 'events' of null` when trying to destroy a game instance having swapped from a Scene to another, and back again. Fix #3878 (thanks @mbunby) -* RenderTextures in WebGL will now set the viewport size, stopping the console warning in Firefox. Fix #3823 (thanks @SBCGames) -* Particles now take the Cameras alpha value into consideration when calculating their final alpha values in WebGL. They previously ignored it. If you now alpha a Camera out all particles will change accordingly. -* The `CullTiles` updates from 3.11 didn't factor in the position of the Tilemap Layer to its bounds calculations, causing Static layers displayed out of the Camera viewport to never render in Canvas mode. The method has also been optimized further, with less divisions and less checks if culling is disabled. -* The Particle Emitter when running in Canvas wouldn't allow more than 1 emitter to use a blend mode (as seen in the Electric examples). The blend mode is properly set for each emitter now. -* The Blend Mode is now set directly in all Canvas Renderers without comparing it to what's stored in the Canvas Renderer. This fixes problems where the blend mode would be lost between two different Game Objects because they restored the context, but didn't update the renderer flag. Game Objects in Canvas can now mix and match blend modes across the display list. -* Matter.js has received a tiny update that prevents `collisionEnd` from triggering many times when it should only trigger once (thanks @mikewesthad) -* Graphics objects couldn't be set to be ignored by Cameras. Now every renderable Game Object can be ignored by a Camera, either directly or via a Container. The exception are Groups because they don't render and are non-exclusive parents. -* The Tilemap Culling function now uses the Tilemap tile dimensions for its bounds calculations, instead of the layer tile sizes, as they two don't have to match and it's the underlying grid size that takes precedence when calculating visible tiles. Fix #3893 (thanks @Zax37) -* The Arcade Physics `Body.speed` property is now set whenever you set the velocity via `setVelocity` or `setVelocityX` or `setVelocityY` which stops the body velocity being reset to zero if `useDamping` is enabled. Fix #3888 (thanks @samme) -* The `getPixelAlpha` method in the Texture Manager wasn't using the correct frame name. This is now passed in correctly. Fix #3937 (thanks @goldfire) -* The `getPixelAlpha` and `getPixel` methods in the Texture Manager would allow x/y coordinates from outside the cut area of a frame. It now tests to ensure they're within the frame. Fix #3937 (thanks @goldfire) -* A Game Object couldn't have a blend mode of `SKIP_TEST` set by using the getter or the `setBlendMode` method. -* In Arcade Physics the `World.disable` call was passing the wrong argument, so never disabling the actual body (thanks @samme) -* There was a visual bug with Rounded Rectangles in Canvas mode, due to the addition of the `overshoot` argument in the Graphics arc call. This has been fixed, so arcs will now render correctly and consistently in WebGL and Canvas and Rounded Rectangles are back to normal again too. Fix #3912 (thanks @valse) -* The `InputManager.inputCandidate` method, which determines if a Game Object can be interacted with by a given Pointer and Camera combination, now takes the full camera status into consideration. This means if a Camera is set to ignore a Game Object you can now no longer interact with it, or if the Camera is ignoring a Container with an interactive Game Object inside it, you cannot interact with the Container children anymore. Previously they would interact regardless of the Camera state. Fix #3984 (thanks @NemoStein @samid737) -* `Transform.getWorldTransformMatrix` has been recoded to iterate the transform parents correctly, applying the matrix multiplications as it goes. This (along with some changes in the Input Manager) fix the issue with Game Objects inside of Containers failing hit tests between certain angles. Fix #3920 (thanks @chaping @hackhat) -* Calling Arcade Physics `collide` during an `update` method wouldn't inject the results back into the Body parent, causing the bodies to carry on moving. Using Colliders worked, but manually checking did not. Now, both methods work. Fix #3777 (thanks @samme) -* The `setTintFill` method would ignore the `alpha` value of the Game Object in the shader. The alpha value is now blended with the tint fill, allowing you to properly alpha out tint-filled Game Objects. Fix #3992 (thanks @trl-bsd) -* Arcade Physics World `collideSpriteVsTilemapLayer` now syncs the collision results back to the body, allowing you to call `collide` from within an update loop once again. Fix #3999 (thanks @nkholski @mikewesthad) -* Arcade Physics Body `deltaX` and `deltaY` methods will now return the previous steps delta values, rather than zero. Fix #3987 (thanks @HaoboZ) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@SBCGames @rgk @rook2pawn @robbintt @bguyl @halilcakarr @PhaserEditor2D @Edwin222 @tfelix @Yudikubota @hexus @guzmonne @ampled @thanh-taro @dcbriccetti @Dreaded-Gnu @padme-amidala @rootasjey @ampled @thejonanshow @polarstoat @jdjoshuadavison @alexeymolchan @samme @PBird @spontoreau @hypertrifle @kid-wumeng - -Thanks to @khaleb85 for fixing the super-annoying lag on the API Docs pages when it hung the browser while indexing the search field. - - -## Version 3.11.0 - Leafa - 13th July 2018 - -### Camera - New Features, Updates and Fixes - -* All of the 2D Camera classes are now 100% covered by JSDocs! -* All of the 3D Camera classes are now deprecated and will be removed in the next version. They will be moved to a stand-alone plugin. -* `Camera.alpha` (and its related method `Camera.setAlpha`) allows you to set an alpha level for the entire camera. This impacts everything it is rendering, even if those objects also have their own alpha values too. You can tween the property to make the camera contents fade in / out, or otherwise set it as needed in your game. -* `Camera.deadzone` (and its related method `Camera.setDeadzone`) allows you to specify the deadzone for a camera. The deadzone is a rectangular region used when a camera is following a target. If the target is within the deadzone then the camera will not scroll. As soon as the target leaves the deadzone, the camera will begin tracking it (applying lerp if needed.) It allows you to set a region of the camera in which a player can move freely before tracking begins. The deadzone is re-centered on the camera mid point every frame, meaning you can also use the rectangle for other in-game checks as needed. -* `Camera.pan` is a new Camera Effect that allows you to control automatic camera pans between points in your game world. You can specify a duration and ease type for the pan, and it'll emit events just like all other camera effects, so you can hook into the start, update and completion of the pan. See the examples and docs for more details. -* `Camera.zoom` is a new Camera Effect that allows you to control automatic camera zooming. You can specify a duration and ease type for the zoom, as well as the zoom factor of course, and it'll emit events just like all other camera effects, so you can hook into the start, update and completion of the zoom. Used in combination with the new Pan effect you can zoom and pan around with ease. See the examples and docs for more details. -* `Camera.midPoint` is a new Vec2 property that is updated every frame. Use it to obtain exactly where in the world the center of the camera is currently looking. -* `Camera.displayWidth` is a new property that returns the display width of the camera, factoring in the current zoom level. -* `Camera.displayHeight` is a new property that returns the display height of the camera, factoring in the current zoom level. -* `Camera.worldView` is a new property, an instance of a Rectangle, that contains the dimensions of the area of the world currently visible by the camera. You can use it for intersection or culling tests that don't need to factor in camera rotation. -* `Camera.dirty` is a new boolean property. A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. The flag is reset in the `postCameraRender` method, but until that point can be checked and used. -* `Camera.centerOn` is a new method that will move the camera so its viewport is centered on the given coordinates. A handy way of jumping to different points around a map without needing to calculate the scroll offsets. -* The Camera bounds didn't factor in the camera zoom properly, meaning you would often not be able to reach the corners of a camera bound world at a zoom level other than 1. The bounds are now calculated each frame to ensure they match the zoom level and it will no longer allow you to scroll off the edge of the bounds. Fix #3547 (thanks @nkholski) -* `Camera.centerToBounds` didn't take the bounds offset into account, so bounds at non-zero positions wouldn't center properly. All bounds now center correctly. Fix #3706 (thanks @cyantree) -* `Camera.setBounds` has a new optional argument `centerOn`. If specified it will automatically center the camera on the new bounds given. -* The Camera will no longer stutter when following Game Objects at high zoom levels. -* `Camera._id` has been renamed to `Camera.id`, a read-only bitmask used for camera exclusion from Game Objects. -* The Camera Manager `cameraPool` has been removed entirely. It was mostly pointless in practice as Cameras are not regenerated frequently enough to need pooling. It also didn't maintain the bitmask list correctly before. -* `CameraManager.resetAll` now destroys all current Cameras, resets the camera ID marker to 1 and adds a single new Camera. -* `CameraManager.currentCameraId` has been removed. IDs are assigned more intelligently now, via the `getNextID` internal method. -* `CameraManager.addExisting` no longer needs to be passed a Camera that already exists in the pool (as the pool has been removed), meaning you can now create your own Cameras and pass them to `addExisting` and have them treated as normal cameras and not be ignored by the manager. They are also assigned a proper ID when added. -* `CameraManager.addExisting` has a new boolean argument `makeMain` which will make the new camera the main one. -* `CameraManager.getTotal` is a new method that will return the total number of Cameras being managed, with an optional `isVisible` argument, that only counts visible cameras if set. -* `CameraManager.remove` can now take an array of cameras to be removed from the manager, as well as a single camera. -* `CameraManager.remove` would previously not allow you to remove a camera if it meant there would be no cameras left in the Camera Manager. This restriction has been removed. A Camera Manager can now run even with zero cameras. Your game obviously won't display anything, but it's still now possible. -* `CameraManager.remove` will now return the total number of Cameras removed. - -### Round Pixels Changes - -Before explaining the changes it's worth covering what the three different game config properties do: - -`roundPixels` - this will cause the renderer to draw most Game Objects at whole integer positions. Their actual positions can be anything, but the renderer will floor the values to ensure they are integers immediately before drawing. It only works on texture based Game Objects. Graphics objects, for instance, ignore this property. - -`antialias` - when set to `true` WebGL textures are created using `gl.LINEAR`, which allows WebGL to try its best to interpolate the texture when rendered at non-texture frame sizes. This can happen if you scale a Game Object, or zoom a Camera. In both cases it will need to interpolate the pixel values to accommodate the new size. If this property is set to `false` then it will use `gl.NEAREST` instead. This uses a nearest neighbor method of interpolation, and is nearly always the better option if you need to keep the textures crisp, such as when using scaled pixel art. Disabling `antialias` invokes nearest-neighbor interpolation on the game canvas itself as well. If you need a mixture of aliased and anti-aliased textures in your game, then you can change them on a per-texture basis by using `Texture.setFilter`. - -There is a third game config property called `pixelArt`. If set to `true` it's the same thing as enabling `roundPixels` and disabling `antialias`. This is the optimum setting for pixel art games. - -* Both renderers will now check for `pixelArt` OR `antialias` before setting the canvas scale mode. Both values are checked during texture creation as well. -* If in your game config you have enabled either pixel art mode or roundPixels, then all Cameras will have their `roundPixels` values set to `true` by default. You can toggle this by changing the `CameraManager.roundPixels` property, or change it on a camera-by-camera basis, as needed. -* `Camera.roundPixels` is now used across all rendering code for both Canvas and WebGL. Previously, it would check the renderer config value, but now all renderer code uses the camera value to decide if it should floor the drawing position or not. - -### Texture Tint Pipeline - New Features, Updates and Fixes - -The Texture Tint Pipeline has been rewritten to tidy up hundreds of lines of duplicate code and to move the responsibility of drawing to the Game Objects themselves. Previously, had you excluded say Tilemaps from your build of Phaser, the renderer would still include masses of code dealing with the drawing of them. This task has been moved to the Game Objects and the pipeline just provides a set of clean utility functions for batching, flushing and drawing. - -The decision to make this change was not taken lightly. However, I felt that none of the pipelines actually lived up to their name. You could never actually pass objects through one pipeline to another as they didn't have entry and exit points and were instead just glorified singular batches. Although you could change the pipeline being used on a Game Object this action meant that every pipeline had to be responsible for every single type of Game Object, both now and in the future, and they were full of redundant stub functions as a result. The payload size was also considerable. It has now gone from 1,961 lines of code at 76 KB down to 729 lines of code and 27 KB. It's not the only file to benefit either. The `ForwardDiffuseLightPipeline` also reduced from 402 lines (15.7 KB) down to 159 lines and 6 KB. Sizes include comments and are un-minified. In a production bundle the difference will be even greater. This is work we will continue in the next release as we do the same updates to the FlatTintPipeline, responsible for rendering Graphics objects, and look at consolidating the shaders allowing you to use Graphics and Sprites mixed in the display list with no shader swapping cost. - -* You can now set the WebGL batch size in the Game Config via the property `batchSize`. The default is 2000 before the batch will flush, which is a happy average between desktop and mobile. If targeting desktop specifically, you may wish to increase this value to reduce draw calls. -* There is a new method `batchVertices` which will add a vertices block to the current batch. This is now used internally by nearly all render functions. -* The shader has a new attribute: `tintEffect`. This is a single FLOAT. -* The vertex size has increased by 1 FLOAT to account for the extra shader attribute. -* All of the rendering functions now use the `TransformMatrix` class far more than before. This allows the matrix operations to be run-time compiled and cut down on masses of code. -* The `drawTexture` method has been removed. It has been replaced by `drawTextureFrame` which has a new and more concise signature. See the API docs for details. -* The `batchTileSprite` method has been removed. It is now handled in the TileSprite WebGL Render function. -* The `drawStaticTilemapLayer` method has been removed. It is now handled in the Static Tilemap Layer WebGL Render function. -* The `drawEmitterManager` method has been removed. It is now handled in the Particle Manager WebGL Render function. -* The `batchText` method has been removed. It is now handled in the Static Text WebGL Render function. -* The `batchDynamicTilemapLayer` method has been removed. It is now handled in the Dynamic Tilemap Layer WebGL Render function. -* The `batchMesh` method has been removed. It is now handled in the Mesh WebGL Render function. -* The `batchBitmapText` method has been removed. It is now handled in the BitmapText WebGL Render function. -* The `batchDynamicBitmapText` method has been removed. It is now handled in the DynamicBitmapText WebGL Render function. -* The `batchBlitter` method has been removed. It is now handled in the Blitter WebGL Render function. - -Due to the changes in the Texture Tint Pipeline the `Textures.Frame` class has also been updated. The following changes concern the Frame UV data: - -* Previously, the UV data spanned 8 properties: `x0`, `y0`, `x1`, `y1`, `x2`, `y2`, `x3` and `y3` and was stored in the `data.uvs` object. These have been replaced with directly accessible properties: `u0`, `v0`, `u1` and `v1`. These 4 properties are used directly in all renderer code now. Although it was clearer having 8 properties, 4 of them were just duplicates, so we've traded a little clarity for a smaller overall object and less dictionary look-ups. -* `Frame.uvs` (and the corresponding `Frame.data.uvs`) object has been removed. - -### New Tint Effects - -As well as tidying the Texture Tint Pipeline, I also updated the shader. It now has a new attribute 'tintEffect' which allows you to control how a tint is applied to a Game Object. The default way tinting worked was for the tint color values to be multiplied with the texture pixel values. This meant you were unable to do things like tint a Game Object white, because multiplying a color by white doesn't change it. The new tint mode allows you to literally replace the pixel color values. - -* `setTintFill` is a new method available to all Game Objects that have the Tint component. It differs from `setTint` in that the colors literally replace the pixel values from the texture (while still respecting the alpha). This means you can now create effects such as flashing a sprite white if it gets hit, or red for damage, etc. You can still use different colors per corner of the Game Object, allowing you to create nice seamless gradient effects. -* `tintFill` is a new boolean property that allows you to toggle between the two different tint types: multiply or replace. -* `isTinted` is a new read-only boolean indicating if a Game Object is tinted or not. Handy for knowing if you need to clear a tint after an effect. -* `Mesh.tintFill` allows you to control the tint effect applied to the Mesh vertices when color blending. - -The Tint component documentation has been overhauled to explain these differences in more detail, and you can find lots of new examples as well. - -### New Texture Crop Component - -There is a new Game Object Component called `TextureCrop`. It replaces the Texture Component (which still exists) and adds in the ability to crop the texture being used. This component is now being used by the `Sprite` and `Image` Game Objects. - -* You can crop the frame being used via the new `setCrop` method. The crop is a rectangle that limits the area of the texture frame that is visible during rendering. Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just changes what is shown when rendered. This is ideal for hiding part of a Sprite without using a mask, or for effects like displaying a progress or loading bar. Cropping works even when the Game Object is flipped, or is a trimmed frame from an atlas. -* You can toggle the crop on a Game Object by changing the `isCropped` boolean at any point. -* The crop is automatically re-applied when the texture or frame of a Game Object is changed. If you wish to disable this, turn off the crop before changing the frame. - -### BitmapText New Features, Updates and Bug Fixes - -* Multi-line BitmapText objects can now be aligned. The constructor has a new argument `align` which can accept either left-aligned (the default), center aligned, or right-aligned. Alignment works by calculating the longest line of text in the object and then offsetting the other lines to match it. -* `BitmapText.setCenterAlign` is a new chainable method to center-align the text. -* `BitmapText.setLeftAlign` is a new chainable method to left-align the text. -* `BitmapText.setRightAlign` is a new chainable method to right-align the text. -* `BitmapText.align` is a new property that holds the alignment of the text. -* `BitmapText.setFont` is a new method that allows you to change the font it is rendering with. -* Internally all of the BitmapText properties have been renamed with an underscore (i.e. `letterSpacing` is now `_letterSpacing`), so as to not change the API, getters and setters for them all have been added. -* Internally there is a new `dirty` flag that tracks if any part of the BitmapText has changed. This is used when getting the BitmapText's bounds object, as used in the renderer for line alignment, and in properties like `width` and `height`. The dirty flag ensures the bounds are only recalculated if something has changed, cutting down on un-necessary calculations. -* `GetBitmapTextSize`, which is used internally in the BitmapText Game Objects, will now produce different bounds from the previous version. Previously, the bounds were tight against the letters in the text. However, this meant the bounds were not properly aligned with the origin of the BitmapText, and consequently you'd get different bounds if the text consisted of different characters. The bounds are now calculated purely based on the glyph data and letter spacing values. This will give a far more consistent overall experience, but it does mean if you were using the bounds to position text previously, you'll need to revisit that code again. See issue #3799 for more details (and to discuss this further if you wish) (thanks @SBCGames) -* `GetBitmapTextSize` and its exposed method `BitmapText.getTextBounds` now factor in the display origin of the BitmapText into the `global` position returned. -* The `BitmapText` WebGL Renderer incorrectly calculated the font scale at very small sizes, causing characters to overlap when they shouldn't. Scale is now applied to the correct component parts in the render code. -* Under WebGL `BitmapText` would be cut off if you specified a resolution value > 1. Fix #3642 (thanks @kanthi0802) -* Under WebGL, `DynamicBitmapText` that had a crop set on it would fail to render if anything was above it on the display list. It now crops properly, no matter what is above or below it on the display list. -* The `DynamicBitmapText` class now extends the `BitmapText` class. This saves on lots of space in the bundle and consolidates functionality between the two. Please be aware of it if you have classes that extend either of them. -* If you were using the `displayCallback` in the `DynamicBitmapText` class it would generate a brand new object containing all the glyph data, every frame, for every glyph, and send it to the callback. This has been changed so it now uses a new cached local object: `callbackData`. This object is recycled for every glyph, stopping un-needed gc from building up. - -### Dynamic Tilemap Layer New Features, Updates and Bug Fixes - -* `DynamicTilemapLayer.tilesDrawn` is a read-only property that contains the number of tiles sent to the renderer in the previous frame. -* `DynamicTilemapLayer.tilesTotal` is a read-only property that contains the total number of tiles in the layer, updated every frame. -* `DynamicTilemapLayer.skipCull` and its associated chainable method `setSkipCull` allows you to control if the cameras should cull the layer tiles before rendering them or not. By default they will cull, to avoid over-rendering, but in some circumstances you may wish to disable this and can now do so by toggling this property. -* The `CullTiles` component, as used by the Dynamic Tilemap, has been recoded from scratch to take advantage of updates in the Camera system. It will now properly cull tiles, irrespective of the layer scale, or camera zoom. It also now supports the layers `skipCull` property, allowing you to override the culling. The Dungeon Generator labs demo now works again as a result of this fix, and has been updated with a debug mode and camera control UI. You can edit the example source to swap between 4 different dungeon layouts, from 2500 tiles up to 1 million tiles. There are limitations to the way the culling works though. If you rotate the camera you may find you see the cull edge. You can disable this using the new `skipCull` property. Fixing this also fixed #3818 (thanks @Mursaat) -* `DynamicTilemapLayer.cullPaddingX`, `cullPaddingY` and the associated chainable method `setCullPadding` allows you to control how many additional tiles are added into the cull rectangle when it is calculated. If you find that your camera size and zoom settings are causing tiles to get prematurely culled, resulting in clipping during scrolling, then set the `cullPadding` values to add extra layers of tiles to the calculations in both directions without needing to disable culling entirely. -* `DynamicTilemapLayer.cullCallback` allows you to change the function that is used to perform the tile culling. By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. It is sent 3 arguments: the layer data, the camera and the array to store the tiles in. Using this feature you can now create whatever culling system you require, should the default one prove to not be suitable for your game. Fix #3811 (thanks @georgzoeller) -* Dynamic Tilemap Layers now properly support the Lights2D Pipeline. This means you can provide a normal map for the layer tileset and it'll illuminate with the Lights shader properly. See the new `light map` example in the labs for a demonstration. Note that there are limits on the number of tiles that can be rendered with lighting enabled. Fix #3544 (thanks @FrancescoNegri) - -### New Features - -* `Graphics.fillRoundedRect` will draw a stroked rounded rectangle to a Graphics object. The radius of the corners can be either a number, or an object, allowing you to specify different radius per corner (thanks @TadejZupancic) -* `Graphics.strokeRoundedRect` will draw a filled rounded rectangle to a Graphics object. The radius of the corners can be either a number, or an object, allowing you to specify different radius per corner (thanks @TadejZupancic) -* `ParticleEmitter.stop` is a new chainable method to stop a particle emitter. It's the same as setting `on` to `false` but means you don't have to break the method flow to do so (thanks @samme) -* `ScenePlugin.pause` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'pause' event. -* `ScenePlugin.resume` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'resume' event. -* `ScenePlugin.sleep` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'sleep' event. -* `ScenePlugin.wake` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'wake' event. -* `ScenePlugin.setActive` now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'pause' or 'resume' events. -* `TileSprite.tileScaleX` and `tileScaleY` are two new properties that allow you to control the scale of the texture within the Tile Sprite. This impacts the way the repeating texture is scaled, and is independent to scaling the Tile Sprite itself. It works in both Canvas and WebGL mode. -* `TransformMatrix.copyFrom` is a new method that will copy the given matrix into the values of the current one. -* `TransformMatrix.multiplyWithOffset` is a new method that will multiply the given matrix with the current one, factoring in an additional offset to the results. This is used internally by the renderer code in various places. -* `Rectangle.Intersection` will take two Rectangle objects and return the area of intersection between them. If there is no intersection, an empty Rectangle is returned. -* `Pointer.prevPosition` is a new Vector2 that stores the previous position of the Pointer, prior to the most recent DOM event. You can use this when performing calculations between the old and current positions, such as for tracking the pointer speed. -* `Pointer.getInterpolatedPosition` is a new method that will return an array of smoothly interpolated values between the old and previous position of the Pointer. You can configure how many interpolation steps should take place (the default is 10) and provide an output array to store them in. This method is handy if you've got an object tracking a pointer and you want to ensure it has smooth movement (as the DOM will often process pointer events at a faster rate than the game loop can update). -* `TransformMatrix.copyFromArray` will populate a matrix from the given array of values. Where 0, 1, 2, 3, 4 and 5 map to a, b, c, d, e and f. -* `WebGLPipeline` has a new over-rideable method called `boot` which is called when the renderer and all core game systems have finished being set-up. -* `KeyboardPlugin.checkDown` is a new method that allows you to check if a Key is being pressed down or not in an update loop. The difference between this method and checking the `Key.isDown` property directly is that you can provide a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it will only return `true` every 100ms. - -### Updates - -* DataManager.removeValue (and by extension the `remove` method too) will not emit the parent of the DataManager as the 2nd argument in the `removedata` event, to keep it consistent with the set events (thanks @rexrainbow) -* The docs for the Loader `filecomplete` event said that you could listen for a specific file using its type and key, i.e.: `filecomplete-image-monster`, however, the code used an underscore instead of a hyphen. We feel the hyphen looks cleaner, so the Loader code has been updated, meaning you can now use the hyphen version of the event properly (thanks @NokFrt) -* If a Game Object is already being dragged, it cannot be dragged by another pointer (in multi-touch mode) until the original pointer has released it (thanks @rexrainbow) -* Calling `Tween.play` on a tween created via `TweenManager.create` wouldn't actually start playback until the tween was first added to the Tween Manager. Now, calling `play` will have it automatically add itself to the Tween Manager if it's not already in there. Fix #3763 (thanks @pantoninho) -* If the Blitter object has no Bobs to render it will now abort immediately, avoiding several context calls in Canvas mode. -* `Scene.run` will now pass the optional `data` object in all cases, no matter if it's waking, resuming or starting a Scene (thanks @rook2pawn) -* `ScenePlugin.start` and `ScenePlugin.restart` will now always queue the op with the Scene Manager, regardless of the state of the Scene, in order to avoid issues where plugins carry on running for a frame before closing down. Fix #3776 (thanks @jjalonso) -* `Tileset.glTexture` is a new property that maps to the WebGL Texture for the Tileset image. It's used internally by the renderer to avoid expensive object look-ups and is set automatically in the `Tileset.setImage` method. -* `Frame.glTexture` is a new property that maps to the WebGL Texture for the Frames Texture Source image. It's used internally by the renderer to avoid expensive object look-ups and is set automatically in the `Frame` constructor. -* `TransformMatrix.e` and `TransformMatrix.f` are two new properties that are an alias for the `tx` and `ty` values. -* `Graphics.arc` has a new optional argument `overshoot`. This is a small value that is added onto the end of the `endAngle` and allows you to extend the arc further than the default 360 degrees. You may wish to do this if you're trying to draw an arc with an especially thick line stroke, to ensure there are no gaps. Fix #3798 (thanks @jjalonso) -* The TextureManager Sprite Sheet Parser will now throw a concise console warning if you specify invalid frame sizes that would result in no frames being generated (thanks @andygroff) -* The `Quad` Game Object now has a new `setFrame` method that allows you to change the frame being rendered by the Quad, including using frames that are part of a texture atlas. Fix #3161 (thanks @halgorithm) -* The `ScenePlugin` will now queue all of the following ops with the Scene Manager: `start`, `run`, `pause`, `resume`, `sleep`, `wake`, `switch` and `stop`. This means for all of these calls the Scene Manager will add the call into its queue and process it at the start of the next frame. This fixes #3812 and keeps things more predictable (thanks @Waclaw-I) -* `TransformMatrix.multiply` has a new optional argument `out` which is a matrix to store the multiplication results in. If not given it will act as before, multiplying the current matrix. -* `Zones` now have a NOOP `setAlpha` method, which allows them to be added into Containers (thanks @TadejZupancic) -* The `setPipeline` method now returns the instance of the Game Object on which it was called. It used to return the pipeline that was set, but this made it non-chainable which broke with the conventions set in all the other `set` methods. If you use `setPipeline` in your code anywhere to retrieve the pipeline reference, please use the `pipeline` property of the Game Object instead. - -### Bug Fixes - -* The DataManager `changedata` event was emitting the original value of the data instead of new value (thanks @iamchristopher) -* The LoaderPlugin didn't emit the `filecomplete` event if any of files failed to load, causing it to fail to run the Scene `create` function as well. Fix #3750 (thanks @NokFrt) -* Fix setter calls in BuildGameObjectAnimation so it will now properly set the delay, repeat, repeat delay and yoyo of a config based animation (thanks @DannyT) -* The Arcade Body `blocked.none` property is now set to `false` after separation with static bodies or tiles. Previously, the blocked direction was set correctly, but the `none` remained `true` (thanks @samme) -* `Bob.setFrame` didn't actually set the frame on the Bob, now it does. Fix #3774 (thanks @NokFrt) -* `Bob.alpha` was ignored by the canvas renderer, only working in WebGL. This has now been fixed. -* Although the Blitter object had the Alpha component, setting it made no difference. Setting Blitter alpha now impacts the rendering of all children, in both Canvas and WebGL, and you can also specify an alpha per Bob as well. -* `SceneManager.run` would ignore scenes that are currently in the queue of scenes pending to be added. This has now been fixed so that the scene is queued to be started once it's ready (thanks @rook2pawn) -* `GameObject.disableInteractive` was toggling input. Every second call would turn the input back on (thanks @TadejZupancic) -* The position of the TilemapLayer wasn't taken into account when culling tiles for the Camera. It's now calculated as part of the cull flow (thanks @Upperfoot) -* Fix extra argument passing in Array.Each (thanks @samme) -* TileSprite was using the Size component instead of ComputedSize, meaning its `getBounds` and `displayWidth` and `displayHeight` results were incorrect. Fix #3789 (thanks @jjalonso) -* `ArrayUtils.AddAt` didn't calculate the array offset correctly if you passed an array in to be merged with an existing array. This also caused Container.addAt to fail if an array was passed to it. Fix #3788 (thanks @jjalonso) -* The `Pointer.camera` property would only be set if there was a viable Game Object in the camera view. Now it is set regardless, to always be the Camera the Pointer interacted with. -* Added the Mask component to Container. It worked without it, but this brings it in-line with the documentation and other Game Objects. Fix #3797 (thanks @zilbuz) -* The DataManager couldn't redefine previously removed properties. Fix #3803 (thanks @AleBles @oo7ph) -* The Canvas DrawImage function has been recoded entirely so it now correctly supports parent matrix and camera matrix calculations. This fixes an issue where children inside Containers would lose their rotation, and other issues, when in the Canvas Renderer. Fix #3728 (thanks @samid737) -* `clearMask(true)` would throw an exception if the Game Object didn't have a mask. Now it checks first before destroying the mask. Fix #3809 (thanks @NokFrt) -* In the WebGL `GeometryMask` the stencil has been changed from `INVERT` to `KEEP` in order to fix issues when masking Graphics objects and other complex objects. Fix #3807. This also fixes the issue where children in Containers would display incorrectly outside of a Geometry mask. Fix #3746 (thanks @zilbuz @oklar) -* `BitmapMask.destroy` will now remove the textures and framebuffers that it created from the WebGL Renderer as part of the destroy process. Fix #3771 (thanks @nunof07) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@DannyT @squilibob @dvdbrink @t1gu1 @cyantree @DrevanTonder @mikewesthad @tarsupin @shadowofsoul - -Also, a special mention to @andygroff for his excellent work enhancing the search box on the examples site, and @hexus for his assistance completing the documentation for the Game Objects. - -## Version 3.10.1 - Hayashi - 13th June 2018 - -### Bug Fixes - -* The InputManager would only create 1 Pointer, even if Touch input was enabled in the config, which meant you couldn't use touch events unless you first called `addPointer` or specified one in the config. Now, it Touch is enabled in the config, it'll always create 2 pointers by default. - -## Version 3.10.0 - Hayashi - 13th June 2018 - -### Input System New Features + Updates - -* All Input classes are now covered 100% by JSDocs. -* The Input Manager and Input Plugin have been updated to support multiple simultaneous Pointers. Before, only one active pointer (mouse or touch) was supported. Now, you can have as many active pointers as you need, allowing for complex multi-touch games. These are stored in the Input Manager `pointers` array. -* `addPointer` allows you to add one, or more, new pointers to the Input Manager. There is no hard-coded limit to the amount you can have, although realistically you should never need more than 10. This method is available on both the Input Manager and Plugin, allowing you to use `this.input.addPointer` from within your game code. -* InputManager `pointersTotal` contains the total number of active pointers, which can be set in the Game Config using the `input.activePointers` property. Phaser will create 2 pointers on start unless a different value is given in the config, or you can add them at run-time. -* `mousePointer` is a new property that is specifically allocated for mouse use only. This is perfect for desktop only games but should be ignored if you're creating a mouse + touch game (use activePointer instead). -* `activePointer` will now reflect the most recently active pointer on the game, which is considered as being the pointer to have interacted with the game canvas most recently. -* The InputManager and InputPlugin have three new methods: `addUpCallback`, `addDownCallback` and `addMoveCallback`. These methods allow you to add callbacks to be invoked whenever native DOM mouse or touch events are received. Callbacks passed to this method are invoked _immediately_ when the DOM event happens, within the scope of the DOM event handler. Therefore, they are considered as 'native' from the perspective of the browser. This means they can be used for tasks such as opening new browser windows, or anything which explicitly requires user input to activate. However, as a result of this, they come with their own risks, and as such should not be used for general game input, but instead be reserved for special circumstances. The callbacks can be set as `isOnce` so you can control if the callback is called once then removed, or every time the DOM event occurs. -* Pointer has two new properties `worldX` and `worldY` which contain the position of the Pointer, translated into the coordinate space of the most recent Camera it interacted with. -* When checking to see if a Pointer has interacted with any objects it will now iterate through the Camera list. Previously, it would only check against the top-most Camera in the list, but now if the top-most camera doesn't return anything, it will move to the next camera and so on. This also addresses #3631 (thanks @samid737) -* `InputManager.dirty` is a new internal property that reflects if any of the Pointers have updated this frame. -* `InputManager.update` now uses constants internally for the event type checking, rather than string-based like before. -* `InputManager.startPointer` is a new internal method, called automatically by the update loop, that handles touch start events. -* `InputManager.updatePointer` is a new internal method, called automatically by the update loop, that handles touch move events. -* `InputManager.stopPointer` is a new internal method, called automatically by the update loop, that handles touch end events. -* `InputManager.hitTest` has had its arguments changed. It no longer takes x/y properties as the first two arguments, but instead takes a Pointer object (from which the x/y coordinates are extracted). -* `TouchManager.handler` has been removed as it's no longer used internally. -* `TouchManager.onTouchStart`, `onTouchMove` and `onTouchEnd` are the new DOM Touch Event handlers. They pass the events on to the InputManagers `queueTouchStart`, `queueTouchMove` and `queueTouchEnd` methods respectively. -* `MouseManager.handler` has been removed as it's no longer used internally. -* `MouseManager.onMouseDown`, `onMouseMove` and `onMouseUp` are the new DOM Mouse Event handlers. They pass the events on to the InputManagers `queueMouseDown`, `queueMouseMove` and `queueMouseUp` methods respectively. -* Setting `enabled` to false on either the TouchManager, MouseManager or KeyboardManager will prevent it from handling any native DOM events until you set it back again. -* InputPlugin has the following new read-only properties: `mousePointer`, `pointer1`, `pointer2`, `pointer3`, `pointer4`, `pointer5`, `pointer6`, `pointer7`, `pointer8`, `pointer9` and `pointer10`. Most of these will be undefined unless you call `addPointer` first, or set the active pointers quantity in your Game Config. -* InputManager has a new method `transformPointer` which will set the transformed x and y properties of a Pointer in one call, rather than the 2 calls it took before. This is now used by all Pointer event handlers. -* InputPlugin has a new method `makePixelPerfect` which allows you to specify a texture-based Game Object as being pixel perfect when performing all input checks against it. You use it like this: `this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect())`, or the easier: `setInteractive({ pixelPerfect: true })` - you can also pass or set an optional alpha tolerance level. See the method docs for full details and the new examples to see it in action. Note that as a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from the given coordinates and checking its color values. This is an expensive process, so should only be enabled on Game Objects that really need it. - -### Input - Custom Cursors - -* You can now set a custom cursor for your game via `this.input.setDefaultCursor()`. This will take any valid CSS cursor string, including URLs to cursor image files. -* You can now set a custom cursor for specific Game Objects. This will take any valid CSS cursor string, including URLs to cursor image files, and is used when-ever a pointer is over that Game Object. For example, to have a hand cursor appear when over a button Sprite, you can do: `button.input.cursor = 'pointer'`, or to have a help cursor appear: `button.input.cursor = 'help'`, or to have a custom image: `button.input.cursor = 'url(assets/cursors/sword.cur), pointer'`. -* You can also set a custom cursor in the new Input Configuration Object. To use the `pointer` (hand cursor) there is a new short-cut: `setInteractive({ useHandCursor: true })`. To use anything else: `setInteractive({ cursor: CSSString })` where `CSSString` is any valid CSS for setting a cursor. -* Please be aware of limitations when it comes to image based cursors between browsers. It's up to you to find a suitable format and size that fits the browsers you wish to support (note: virtually all modern browsers no longer support animated CSS cursors.) - -### Input - Configuration Objects - -* The `setInteractive` method can now take an Input Configuration object as its only argument. This allows you to set multiple input related properties in a single call, i.e.: `setInteractive({ draggable: true, pixelPerfect: true })`. The available properties are: -* `hitArea` - The object / shape to use as the Hit Area. If not given it will try to create a Rectangle based on the texture frame. -* `hitAreaCallback` - The callback that determines if the pointer is within the Hit Area shape or not. -* `draggable` - If `true` the Interactive Object will be set to be draggable and emit drag events. -* `dropZone` - If `true` the Interactive Object will be set to be a drop zone for draggable objects. -* `useHandCursor` - If `true` the Interactive Object will set the `pointer` hand cursor when a pointer is over it. This is a short-cut for setting `cursor: 'pointer'`. -* `cursor` - The CSS string to be used when the cursor is over this Interactive Object. -* `pixelPerfect` - If `true` the a pixel perfect function will be set for the hit area callback. Only works with texture based Game Objects. -* `alphaTolerance` - If `pixelPerfect` is set, this is the alpha tolerance threshold value used in the callback. - -### Input - Keyboard Manager Updates - -* The `KeyboardManager` class has been removed. It has been replaced with `KeyboardPlugin` which is now an Input level plugin, that registers itself with the new `InputPluginCache`. The Input Plugin class (which belongs to a Scene) will now automatically inject registered plugins into itself on boot. Every Scene has its own instance of the Input Plugin (if enabled in the scene plugins), which in turn has its own instance of the KeyboardPlugin. The `InputManager` no longer has any reference to the Keyboard class at all. The benefits of this are two-fold: First, it allows you to now entirely exclude all of the keyboard classes from a custom build, saving a lot of space if not required. Secondly, it means that the Scenes themselves are now responsible for keyboard events, where-as before they were entirely global. This means a Scene can be paused and stop processing keyboard events, and stop having its Key objects updated, while another Scene can still carry on doing this. It also prevents key related callbacks in sleeping Scenes from being fired (which resolves issue #3733, thanks @JoeMoov2) -* `KeyboardManager.handler` has been renamed to `onKeyHandler`. -* The `KeyboardManager.captures` property has been removed as it can be more effectively handled by polling the `keys` object instead. -* The Keyboard Manager will no longer process key down or up events if its `enabled` property is set to false, or if the Scene to which it belongs is not active. -* The Keyboard Manager will now call `event.preventDefault` on the native DOM event as long as the Key exists in the keys array and has its `preventDefault` property set to `true` (which is the default). This means you can now control specifically which key prevents default on the browser, where-as before every key added did so. -* KeyboardManager `addKeyCapture` and `removeKeyCapture` have been removed as you now control which keys prevent capture by using the `addKey` or `addKeys` methods (see entry above). The act of creating a Key is now enough to enable capture of it and can be toggled (at run-time) on a per-Key basis. -* `KeyboardManager.addKeys` can now take either an object, or key codes, or a comma-separated string as its input. This means you can now do: `keyboard.addKeys('W,S,A,D')` and get an object back with the properties WSAD mapped to the relevant Key objects. -* `KeyboardManager.addKey` can now take either a Key object, a string, such as `A` or `SPACE`, or a key code value. -* `KeyboardManager.removeKey` can now take either a Key object, a string, such as `A` or `SPACE`, or a key code value. - -### Input - Gamepad Manager Updates - -* The `GamepadManager` class has been removed. It has been replaced with `GamepadPlugin` which is now an Input level plugin, that registers itself with the new `InputPluginCache`. The Input Plugin class (which belongs to a Scene) will now automatically inject the registered plugins into itself on boot. Every Scene has its own instance of the Input Plugin (if enabled in the scene plugins), which in turn has its own instance of the GamepadPlugin. The `InputManager` no longer has any reference to the Gamepad class at all. The benefits of this are two-fold: First, it allows you to now entirely exclude all of the gamepad classes from a custom build, saving a lot of space if not required. Secondly, it means that the Scenes themselves are now responsible for gamepad events, where-as before they were entirely global. This means a Scene can be paused and stop processing gamepad events, and stop having its Gamepad objects updated, while another Scene can still carry on doing this. It also prevents gamepad related callbacks in sleeping Scenes from being fired. -* The Gamepad Plugin has been rewritten from scratch. It now offers a lot more features and far easier access to the Gamepads and their properties. You can now access the first 4 gamepads connected to the browser via the `pad1` to `pad4` properties, meaning you can do: `this.input.gamepad.pad1` for direct access to a pad once it's connected. -* The Gamepad class has also been rewritten from scratch. It will no longer create Buttons or Axes dynamically, instead doing so on instantiation. -* The Gamepad class now has a bunch of new properties for easy access to the various standard mapping buttons. These include `left`, `right`, `up`, `down` for directions, `A`, `Y`, `X` and `B` for buttons, `L1`, `L2`, `R1` and `R2` for shoulder buttons, and `leftStick` and `rightStick` for the axis sticks. You can still use `Gamepad.getButtonValue()` to get the value from a button and `Gamepad.getButtonTotal()` to get the total number of buttons available on the pad. -* `Gamepad.getAxisTotal` and `Gamepad.getAxisValue` will return the total number of axis, and an axis value, accordingly. -* `Gamepad.setAxisThreshold` will now let you set the threshold across all axis of a Gamepad in one call. -* The Gamepad `Button` objects will now emit 2 events, one from the button itself and another from the Gamepad. This means you can listen for button events in 3 ways: 1) By directly polling the button value in an update loop, 2) Listening for events on the Gamepad Plugin: `this.input.gamepad.on('down')`, or 3) By listening for events on the Gamepad itself: `gamepadReference.on('down')`. - -### Arcade Physics New Features + Updates - -* Arcade Physics now uses a fixed time-step for all internal calculations. There is a new `fps` config value and property (defaults to 60fps), which you can change at run-time using the `setFPS` method. The core update loop has been recoded so that it steps based entirely on the given frame rate, and not the wall-clock or game step delta. This fixed time step allows for a straightforward implementation of a deterministic game state. Meaning you can now set the fps rate to a high value such as 240, regardless of the browser update speed (it will simply perform more physics steps per game step). This is handy if you want to increase the accuracy of the simulation in certain cases. -* You can also optionally call the `step` function directly, to manually advance the simulation. -* There is a new property `timeScale` which will scale all time-step calculations at run-time, allowing you to speed-up or slow-down your simulation at will, without adjusting the frame rate. -* You can now disable the use of the RTree for dynamic bodies via the config property `useTree`. In certain situations, i.e. densely packed worlds, this may give better performance. Static bodies will always use an RTree. -* `collideSpriteVsGroup` has been rewritten. If you are using an RTree it now uses the results directly from the tree search, instead of iterating all children in the Group, which dramatically reduces the work it does. If you have disabled the RTree it performs a brute-force O(N2) Sprite vs. Group iteration sweep. We tested multiple axis sorting variants but the cost of the array allocation and/or sorting, with large amounts of bodies (10,000+), far outweighed the simple math involved in the separation logic. -* `Body.useDamping` is a new boolean property that allows you to use a damping effect for drag, rather than the default linear deceleration. This gives much better results if you need smooth deceleration across both axis, such as the way the ship slows down in the game Asteroids, without the tell-tale axis drift associated with linear drag. -* `GetOverlapX` and `GetOverlapY` now use the calculated delta values, not the deltaX/Y methods. -* `collideSpriteVsGroup` aborts early if the Sprite body has been disabled. -* `updateMotion` has a new argument `delta` which should typically be a fixed-time delta value. -* `intersects` has been restructured to prioritize rect vs. rect checks. -* Body `update` and `postUpdate` have been recoded to handle the new fixed time-step system in place. `update` now takes a new argument, delta, which is used internally for calculations. -* `Body.dirty` has been removed as a property as it's no longer used internally. -* `Body.deltaAbsX` and `deltaAbsY` now return the cached absolute delta value from the previous update, and no longer calculate it during the actual call. -* `World.enable` has been recoded to remove all the `hasOwnProperty` checks and streamline the internal flow. -* `World.disable` has been recoded to remove all the `hasOwnProperty` checks and streamline the internal flow. -* `World.add` is a new method that adds an existing body to the simulation and `enableBody` now passes its newly created bodies to this method. -* `World.disableGameObjectBody` has been removed as it duplicated what the `disable` method did. -* There is a new internal flow with regard to the creation and disabling of bodies. Calling `World.enable` will pass the objects to `enableBody`, which will create a new Body object, if required, and finally pass it to `add`. `World.disable` does the same, but removes the bodies from the simulation. It passes the bodies to `disableBody`, which in turn passes it to `remove`. Both of these work for single objects, an array of objects, Groups or even arrays of Groups. -* `World.computeAngularVelocity` is a new method that specifically calculates the angular velocity of a Body. -* `World.computeVelocity` has had its signature changed. Rather than taking a bunch of arguments all it now takes is a Body and a delta value. Internally it now calculates both the x and y velocity components together in the same single call, where-as before it was split into two calls and multiple assignments. -* `World.computeVelocity` no longer returns the new velocities, they are now set directly on the body within the method. -* `World.computeVelocity` has been recoded to use Fuzzy Greater Than and Less Than calls when applying drag to a previously accelerated body. Using a fuzzy epsilon allows us to mitigate the ping-pong issue, where a decelerating body would constantly flip between a small negative and positive velocity value and never come to an actual rest. -* `World.computeVelocity` now checks the `Body.useDamping` property to perform either linear deceleration or damping on the Body. -* `World.updateMotion` has changed to call the new `computeAngularVelocity` and `computeVelocity` methods. -* Bodies set to bounce would eventually run out of velocity and stop. This has been fixed as part of the refactoring of the time step and compute velocity updates. Fix #3593 (thanks @helmi77) -* If a Body collides with a Static Body it will now set the `blocked` properties accordingly (before it only set the `touching` properties.) This means you can now use checks like `Body.onFloor()` when traversing static bodies (thanks @fariazz) - -### Data Manager New Features and Updates - -* You can now access anything set in the DataManager using the new `values` property. For example, if you set a new value such as this: `data.set('gold', 50)` you can now access it via: `data.values.gold`, where it is treated as a normal property, allowing you to use it in conditional evaluations `if (data.values.level === 2)`, or modify it: `data.values.gold += 50`. -* Each time a value is updated it emits a `changedata` event, regardless if it is changed via the `set` method, or the new `values` approach. -* Each time a value is updated it emits a new event named after the value. For example, if the value was called `PlayerLives`, it will emit the event `changedata_PlayerLives`. This happens regardless if it is changed via the `set` method, or the new `values` approach. -* The `set` method can now take an object containing key value pairs as the first argument. This means you can now set a bunch of values all at once, i.e: `data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 })`. -* The `get` method can now take an array of keys, and will return an array of matching values. This is handy for array destructuring in ES6. -* The `remove` method can now take an array of keys, and will remove all matching values, emitting the `removedata` event for each. -* The order of events has been updated. When a value is first set, and doesn't already exist in the Data Manager, it will emit a `setdata` event. If a value is set that already exists, it instead emits a `changedata` and related `changedata_key` event. Setting a new value no longer emits both events. -* The `resetFunction` function has been removed from the `changedata` event arguments. Previously this was used to allow you to stop a value being updated by calling the reset function instead. However, it created brand new anonymous functions every single time a value was updated. As you can now access stored data via the `values` property you can use this for much easier conditional checks and sets. -* The `blockSet` property has been removed as it's no longer used internally. - -### Loader and Scene Updates - -* Internally, the Loader has changed slightly. Rather than have each file cause the new batch to load, an `update` method is polled every frame, which does the same job instead. This avoids load-time race conditions where pre-populated files would trigger loads part way during an existing load, fixing #3705 in the process (thanks @the-simian) -* The Scene Manager has been updated so that it will call Scene.Systems.step during the `init`, `preload` and `create` phase of your Scene. This means that any plugins, or custom code, written to use the Scene Systems `preupdate`, `update` or `postupdate` events will need to be aware that these are now fired from `init` onwards, not just once `create` has finished. -* As a result of these two changes, there is a new Systems property called `sceneUpdate`, which is a reference that maps to your `Scene.update` function. During `init`, `preload` and `create` this is always mapped to NOOP. Once `create` has finished it gets re-mapped to your Scene's update function. If your Scene doesn't have one, it remains mapped to NOOP. In practise, this means nothing has changed from before. `Scene.update` never ran until `create` was completed, and it still doesn't. However, because the internal Scene systems are now updating right from `init`, it means that things like the update list and physics systems are fully operational _during_ your Preloader. This allows you to create far more elaborate preloaders than ever before. Although, with great power comes great responsibility, as the onus is now on you to be careful which events you consume (especially input events) during your preloader. -* Another side-effect of these changes is that Scenes no longer need an 'update' function at all. Previously, if they were missing one, the Scene Manager would inject one into them automatically. It no longer does this. - -### New Features - -* `RenderTexture.resize` will allow you to resize the underlying Render Texture to the new dimensions given. Doing this also clears the Render Texture at the same time (thanks @saqsun). -* `Rectangle.RandomOutside` is a new function that takes two Rectangles, `outer` and `inner`, and returns a random point that falls within the outer rectangle but is always outside of the inner rectangle. -* The Update List has a new read-only property `length`, making it consistent with the Display List (thanks @samme) -* The 2D Camera class has two new read-only properties `centerX` and `centerY` which return the coordinates of the center of the viewport, relative to the canvas (thanks @samme) -* Camera has a new property `visible`. An invisible Camera will skip rendering and input tests of everything it can see. This allows you to create say a mini-cam and then toggle it on and off without needing to re-create it each time. -* Camera has a new method `setVisible` which toggles its visible property. -* `CameraManager.fromJSON` will now set the visible property is defined in the config. -* `ScenePlugin.run` is a new method that will run the given Scene and not change the state of the current Scene at all. If the scene is asleep, it will be woken. If it's paused, it will be resumed. If not running at all, it will be started. -* `TextureManager.getPixelAlpha` is a new method that will return the alpha value of a pixel from the given texture and frame. It will return `null` if the coordinates were out of bounds, otherwise a value between 0 and 255. -* `Game.isOver` is a new read-only boolean property that indicates if the mouse pointer is currently over the game canvas or not. It is set by the VisibilityHandler and is only reliable on desktop systems. -* A new event `Game.mouseout` is dispatched if the mouse leaves the game canvas. You can listen to it from `this.sys.game.events.on('mouseout')` from within a Scene. -* A new event `Game.mouseover` is dispatched if the mouse enters the game canvas, having previously been outside of it. You can listen to it from `this.sys.game.events.on('mouseover')` from within a Scene. -* You can now use PhysicsEditor (https://www.codeandweb.com/physicseditor) to create complex Matter.js bodies. Load them as normal JSON and then just pass it to the Matter Sprite as a shape property: `this.matter.add.sprite(x, y, texture, frame, { shape: shapes.banana })` (where `shapes.banana` is one of the exported PhysicsEditor shapes in the JSON you loaded). See the 'physics/matterjs/advanced shape creation.js' example for more details. - -### Updates - -* The `ForwardDiffuseLightPipeline`, used by the Lights system, now sets a flag if the Scene doesn't contain any lights. All of the Game Objects now check this flag and don't even bother adding themselves to the batch if there are no lights in the Scene, as they'd never render anyway. This also avoids the ghost-image problem if you swap Scenes to a new Scene with the Light Manager enabled, but no actual lights defined. Fix #3707 (thanks @samvieten). -* `CameraManager.getCameraBelowPointer` has been renamed to `getCamerasBelowPointer` and it now returns an array of all the cameras below the given pointer, not just the top-most one. The array is sorted so that the top-most camera is at the start of the array. -* In `TimeStep.step` the `rawDelta` and `delta` values are checked to make sure they are non-negative, which can happen in Chrome when the delta is reset and out of sync with the value passed to Request Animation Frame. Fix #3088 (thanks @Antriel) -* `Cameras.Controls.Fixed` has been removed. It's was deprecated a few versions ago. Please use `FixedKeyControl` instead. -* `Cameras.Controls.Smoothed` has been removed. It's was deprecated a few versions ago. Please use `SmoothedKeyControl` instead. - -### Bug Fixes - -* The Canvas `RenderTexture.drawImage` method incorrectly set the values of the frame, causing them to appear wrongly scaled in the canvas renderer. Fix #3710 (thanks @saqsun). -* Fixed `Math.Matrix4.makeRotationAxis()` (thanks @hexus) -* Fixed an incorrect usage of `Math.abs()` in `Math.Quaternion.calculateW()` (thanks @qxzkjp). -* Particle Emitter Managers can now be added to Containers (thanks @TadejZupancic) -* Fixed a method signature issue with the Animation component's `remove()` handler when `Animation`s are removed from the `AnimationManager`. This prevented removed animations from stopping correctly. -* If you set Phaser to use a pre-existing Canvas element it is no longer re-added to the DOM (thanks @NQNStudios) -* The `TweenManager.getTweensOf` method has been fixed to remove a potential endless loop should multiple targets be passed in to it (thanks @cyantree) -* Interactive Objects inside of Containers would still fire their input events even if the Container (or any ancestor) was set to be invisible. Objects now check their ancestor tree during the input cull and now properly skip input events if not visible. Fix #3620 (thanks @NemoStein) -* Fixed Device.os incorrectly reporting Linux as OS on Android devices (thanks @AleBles) - -### Examples, Documentation and TypeScript - -Thanks to the work of @hexus we have now documented all of the Math namespace and made good progress on the Game Objects. - -I personally have also documented the entire Input system, which was 328 classes, properties and methods to describe, as well as lots of other areas. - -## Version 3.9.0 - Yui - 24th May 2018 - -### New Features - -* The command `npm run help` will display a friendly list of all the scripts available (run `npm install` first) -* Game has a new property `hasFocus` which is a read-only boolean that lets you know if the window the game is embedded in (including in an iframe) currently has focus or not. -* Game.Config has a new property `autoFocus`, which is `true` by default, and will automatically call `window.focus()` when the game starts. -* Clicking on the canvas will automatically call `window.focus`. This means in games that use keyboard controls if you tab or click away from the game, then click back on it again, the keys will carry on working (where-as before they would remain unfocused) -* Arcade Physics Body has a new method `setAllowDrag` which toggles the `allowDrag` property (thanks @samme) -* Arcade Physics Body has a new method `setAllowGravity` which toggles the `allowGravity` property (thanks @samme) -* Arcade Physics Body has a new method `setAllowRotation` which toggles the `allowRotation` property (thanks @samme) -* Arcade Physics Group Config has 3 new properties you can use: `allowDrag`, `allowGravity` and `allowRotation` (thanks @samme) -* PluginManager.registerFileType has a new property `addToScene` which allows you to inject the new file type into the LoaderPlugin of the given Scene. You could use this to add the file type into the Scene in which it was loaded. -* PluginManager.install has a new property `mapping`. This allows you to give a Global Plugin a property key, so that it is automatically injected into any Scenes as a Scene level instance. This allows you to have a single global plugin running in the PluginManager, that is injected into every Scene automatically. -* Camera.lerp has been implemented and allows you to specify the linear interpolation value used when following a target, to provide for smoothed camera tracking. -* Camera.setLerp is a chainable method to set the Camera.lerp property. -* Camera.followOffset is a new property that allows you to specify an offset from the target position that the camera is following (thanks @hermbit) -* Camera.setFollowOffset is a chainable method to set the Camera.followOffset property. -* Camera.startFollow has 4 new arguments: `lerpX` and `lerpY` which allow you to set the interpolation value used when following the target. The default is 1 (no interpolation) and `offsetX` and `offsetY` which allow you to set the follow offset values. -* Camera.startFollow will now immediately set the camera `scrollX` and `scrollY` values to be that of the target position to avoid a large initial lerps during the first few preUpdates. -* Math.Interpolation.SmoothStep is a new method that will return the smooth step interpolated value based on the given percentage and left and right edges. -* Math.Interpolation.SmootherStep is a new method that will return the smoother step interpolated value based on the given percentage and left and right edges. - -### Updates - -* Container.setInteractive can now be called without any arguments as long as you have called Container.setSize first (thanks rex) -* Bob.reset will now reset the position, frame, flip, visible and alpha values of the Bob. -* VisibilityHandler now takes a game instance as its sole argument, instead of an event emitter. -* PluginManager.createEntry is a new private method to create a plugin entry and return it. This avoids code duplication in several other methods, which now use this instead. -* The Plugin File Type has a new optional argument `mapping`, which allows a global plugin to be injected into a Scene as a reference. -* TileSprite.destroy has been renamed to `preDestroy` to take advantage of the preDestroy callback system. -* RenderTexture.destroy has been renamed to `preDestroy` to take advantage of the preDestroy callback system. -* Group.destroy now respects the `ignoreDestroy` property. -* Graphics.preDestroy now clears the command buffer array. -* Container addHandler will now remove a child's Scene shutdown listener and only listens to `destroy` once. -* Container removeHandler will re-instate a child's Scene shutdown listener. -* Container preDestroy now handles the pre-destroy calls, such as clearing the container. -* Blitter preDestroy will now clear the children List and renderList. -* The AudioContextMonkeyPatch has been updated to use an iife. Fix #3437 (thanks @NebSehemvi) - -### Bug Fixes - -* PluginManager.destroy didn't reference the plugin correctly, throwing an Uncaught TypeError if you tried to destroy a game instance. Fix #3668 (thanks @Telokis) -* If a Container and its child were both input enabled they will now be sorted correctly in the InputPlugin (thanks rex) -* Fix TypeError when colliding a Group as the only argument in Arcade Physics. Fix #3665 (thanks @samme) -* The Particle tint value was incorrectly calculated, causing the color channels to be inversed. Fix #3643 (thanks @rgk) -* All Game Objects that were in Containers were being destroyed twice when a Scene was shutdown. Although not required it still worked in most cases, except with TileSprites. TileSprites specifically have been hardened against this now but all Game Objects inside Containers now have a different event flow, stopping them from being destroyed twice (thanks @laptou @PaNaVTEC) -* Camera.cull will now accurately return only the Game Objects in the camera view, instead of them all. Fix #3646 (thanks @KingCosmic @Yora) -* The `dragend` event would be broadcast even if the drag distance or drag time thresholds were not met. Fix #3686 (thanks @RollinSafary) -* Restarting a Tween immediately after creating it, without it having first started, would cause it to get stuck permanently in the Tween Managers add queue (thanks @Antriel @zacharysarette) -* Setting an existing Game Object as a static Arcade Physics body would sometimes incorrectly pick-up the dimensions of the object, such as with TileSprites. Fix #3690 (thanks @fariazz) -* Interactive Objects were not fully removed from the Input Plugin when cleared, causing the internal list array to grow. Fix #3645 (thanks @tjb295 for the fix and @rexrainbow for the issue) -* Camera.shake would not effect dynamic tilemap layers. Fix #3669 (thanks @kainage) - -### Examples, Documentation and TypeScript - -Thanks to the work of @hexus we have now documented nearly all of the Math namespace. This is hundreds of functions now covered by full docs and is work we'll continue in the coming weeks. - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@mikez @wtravO @thomastanck - -## Version 3.8.0 - Klein - 16th May 2018 - -### New Plugin Manager - -New in this release is a revamped Plugin Manager. Phaser has always used plugins extensively internally but this release opens them up and builds in a lot of new features making them easy for you to both create and digest. - -There is a new `Phaser.Plugins` namespace in which the classes live. The functions of the old PluginManager have moved to the new PluginCache and the PluginManager, which is available under `this.plugins` from all Scenes by default, now allows you to install and access any plugin. - -Plugins are split into two different types: A Global Plugin and a Scene Plugin. - -A **Global Plugin** is a plugin that lives within the Plugin Manager rather than a Scene. You can get access to it by calling `PluginManager.get` and providing a key. Any Scenes that request a plugin in this way all get access to the same plugin instance, allowing you to use a single plugin across multiple Scenes. - -A **Scene Plugin** is a plugin dedicated to running within a Scene. These are different to Global Plugins in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. - -Plugins can now be installed in 3 different ways: 1) You can preload them, using the `load.plugin` and the new `load.scenePlugin` methods. This will allow you to load externally hosted plugins into your game, or pull down a plugin dynamically at run-time. 2) You can install global and scene plugins in your Game Configuration. The plugin code can be bundled with your game code into a single bundle. By specifying plugins in the game config they're instantly available as soon as your game boots. Finally, you can install plugins at run-time directly from within a Scene. - -Plugins can also create brand new Game Objects and File Types, which install themselves into the respective factories. This means you can now write a plugin that adds a new file type and Game Object in a single package. - -The new Plugin Manager and associated classes are 100% covered by JSDocs and there are stacks of new examples in the `plugins` folder in the Phaser 3 Labs too, so please dig in and have a play with these powerful new things! - -### New Features - -* You can pass in your own `canvas` and `context` elements in your Game Config and Phaser will use those to render with instead of creating its own. This also allows you to pass in a WebGL 2 context. Fix #3653 (thanks @tgrajewski) -* WebGLRenderer.config has a new property `maxTextures` which is derived from `gl.MAX_TEXTURE_IMAGE_UNITS`, you can get it via the new method `getMaxTextures()`. -* WebGLRenderer.config has a new property `maxTextureSize` which is derived from `gl.MAX_TEXTURE_SIZE`, you can get it via the new method `getMaxTextureSize()` -* WebGLRenderer has a new property `compression` which holds the browser / devices compressed texture support gl extensions, which is populated during `init`. -* When calling `generateFrameNames` to define an animation from a texture atlas you can now leave out all of the config properties and it will create an animation using every frame found in the atlas. Please understand you've no control over the sequence of these frames if you do this and it's entirely dictated by the json data (thanks @Aram19) -* The keycodes for 0 to 9 on the numeric keypad have been added. You can now use them in events, i.e. `this.input.keyboard.on('keydown_NUMPAD_ZERO')` (thanks @Gaushao) -* All Game Objects have a new method `setRandomPosition` which will randomly position them anywhere within the defined area, or if no area is given, anywhere within the game size. - -### Updates - -* Game.step now emits a `prestep` event, which some of the global systems hook in to, like Sound and Input. You can use it to perform pre-step tasks, ideally from plugins. -* Game.step now emits a `step` event. This is emitted once per frame. You can hook into it from plugins or code that exists outside of a Scene. -* Game.step now emits a `poststep` event. This is the last chance you get to do things before the render process begins. -* Optimized TextureTintPipeline.drawBlitter so it skips bobs that have alpha of zero and only calls `setTexture2D` if the bob sourceIndex has changed, previously it called it for every single bob. -* Game.context used to be undefined if running in WebGL. It is now set to be the `WebGLRenderingContext` during WebGLRenderer.init. If you provided your own custom context, it is set to this instead. -* The Game `onStepCallback` has been removed. You can now listen for the new step events instead. -* Phaser.EventEmitter was incorrectly namespaced, it's now only available under Phaser.Events.EventEmitter (thanks Tigran) - -### Bug Fixes - -* The Script File type in the Loader didn't create itself correctly as it was missing an argument (thanks @TadejZupancic) -* The Plugin File type in the Loader didn't create itself correctly as it was missing an argument. -* WebAudioSoundManager.unlock will now check if `document.body` is available before setting the listeners on it. Fixes old versions of Firefox, apparently. #3649 (thanks @squilibob) -* Utils.Array.BringToTop failed to move the penultimate item in an array due to an index error. Fix #3658 (thanks @agar3s) -* The Headless renderer was broken due to an invalid access during TextureSource.init. -* Animation.yoyo was ignored when calculating the next frame to advance to, breaking the yoyo effect. It now yoyos properly (thanks Tomas) -* Corrected an error in Container.getBoundsTransformMatrix that called a missing method, causing a `getBounds` on a nested container to fail. Fix #3624 (thanks @poasher) -* Calling a creator, such as GraphicsCreator, without passing in a config object, would cause an error to be thrown. All Game Object creators now catch against this. - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@samme @mzguimaraes @NaNdreas @Matthew-Herman @melissaelopez @TheColorRed - -## Version 3.7.1 - Sinon - 8th May 2018 - -### New Features - -* The Phaser 3 Labs has gained a nifty 'search' feature box thanks to @NemoStein - it allows you to filter out the example categories. -* We've added a Mask component, which is available on nearly all Game Objects. It includes the methods `setMask`, `clearMask`, `createBitmapMask` and `createGeometryMask`. -* CanvasTexture is a new extension of the Texture object specifically created for when you've got a Canvas element as the backing source of the texture that you wish to draw to programmatically using the Canvas API. This was possible in previous versions, as a Texture object supported having a Canvas as its source, but we've streamlined the process and made it a lot easier for you to refresh the resulting WebGLTexture on the GPU. To create a CanvasTexture just call the `TextureManager.createCanvas` method as before, only this time you'll get a CanvasTexture back which has helper properties and methods. See the complete JSDocs for more details. -* RandomDataGenerator has a new method: `shuffle` which allows you to shuffle an array using the current RNG seed (thanks @wtravO) -* The Texture Manager now supports normal maps for Atlas JSON (in both hash and array formats), Atlas XML and Atlas Unity. -* All Game Objects have a new method `disableInteractive` which will disable the Interactive Object bound to them. You can toggle it back again by calling `setInteractive` with no arguments. -* All Game Objects have a new method `removeInteractive` which will destroy the Interactive Object bound to them entirely. Use this if a Game Object no longer needs any input at all but you don't want to destroy the Game Object itself. - -### Loader New Features and Important Updates - -The Loader has been given an overhaul to improve its performance and extensibility and gains the following new features: - -* A popular feature from Phaser 2 is back: Loader Packs. These are JSON files that contain a bunch of files to load. You can now load a pack into the Loader, and it will parse it and then add the contents into the current load queue automatically. Those contents can be anything the Loader can handle, including other packs! Please see the documentation and examples for more details. -* The Loader is no longer locked during load. New files can be added into the load queue, even while a load is in process. Indeed, this is how the new Pack files feature works. A side effect is that if you do it a lot, your progress bar may jump around, as it's based on the number of files in the loader at that point in time. So if you add a bunch more it may look like it has reduced. It's up to you to handle this in your code, or create a type of loader graphic that doesn't highlight this (such as a spinning circle instead of a progress bar). -* The Loader now handles the flow slightly differently. Before, it would load every file, and once they were all complete it would then process them in turn. Which would add them into the various caches, create textures, and so on. This now happens as soon as the file has loaded because the browser is likely mostly idle during this time anyway, so it allows us to distribute the file processing throughout the load time, rather than in one lump at the end. -* Loading an Audio Sprite has changed. You now specify the JSON file first, and if you wish you can leave out the audio file URLs and let the Loader figure it out from the JSON meta data. -* The Loader has a new file type: `atlasXML` which will load a Shoebox / Starling / Flash CC format XML Texture Atlas. -* The Loader `multiatlas` file type has changed. You no longer have to specify the URLs of the images, instead it reads them from the JSON data and adds them into the loader automatically. -* Every file type the Loader supports can now be loaded either via the method arguments, or a configuration object, or an array of configuration objects. Before only some of them could, but they all use the same code now. See the new examples demonstrating this. -* If you used a Scene files payload then the format of the object has changed. It used to be a property in the Scene Config called `files` which was an array of files to load. It has been renamed to `pack` and it's an object that exactly matches the new Pack File format. Please see the loader example `scene files payload.js` for an example. In short, where you had: `files: []` before, just change it to `pack: { files: [] }` and it'll work. -* The Loader now supports Texture Atlases with normal maps. Before it would only support single images loaded with normal maps, but now you can provide them for all the atlas formats (json, xml and Unity) -* The Loader `multiatlas` feature will now automatically load texture normal maps, if specified in the json. -* Binary Files have a new optional `dataType` argument and property which will cast the binary data to that format after load, before inserting it into the cache, i.e.: `load.binary('mod', 'music.mod', Uint8Array)` -* The method `LoaderPlugin.tilemapWeltmeister` has been renamed to the far more friendly `LoaderPlugin.tilemapImpact`. Everything else about it remains the same, but please update to use the new method name. - -### Loader Updates - -* The Loader and all associated file types are now covered 100% by JSDocs. -* LinkFile is a new type of file used by the Loader that handles multiple files that need to be joined together. For example, loading a JSON and an Image for a Texture Atlas. This is now handled by a LinkFile. -* File has a new argument in its constructor which is an instance of the LoaderPlugin. It stores this in the `loader` property. It also has a new property `cache` which is a reference to the cache that the file type will be stored in. -* File has a new method `hasCacheConflict` which checks if a key matching the one used by this file exists in the target Cache or not. -* File has a new method `addToCache` which will add the file to its target cache and then emit a `filecomplete` event, passing its key and a reference to itself to the listener (thanks to @kalebwalton for a related PR) -* The Loader has a new property `cacheManager` which is a reference to the global game cache and is used by the File Types. -* The Loader has a new property `textureManager` which is a reference to the global Texture Manager and is used by the File Types. -* The Loader will now check to see if loading a file would cache a cache conflict or not, and prevent it if it will. -* The Loader now hands off processing of the file data to the file itself, which will now self-add itself to its target cache. -* The Loader will now call 'destroy' on all Files when it finishes processing them. They now tidy-up references and extra data, freeing them for gc. -* The File Types are now responsible for adding themselves to their respective caches and any extra processing that needs to happen. This has removed all of the code from the Loader that was doing this, meaning the file types are now properly abstracted away and the Loader is no longer bound to them. This allows you to exclude file types if you don't need them, creating smaller bundles as a result. It also means we can drop in new file types easily without touching the Loader itself and Plugins can register new file types. -* The XMLFile type will no longer throw an error if it can't parse the XML, instead it'll log a console warning and not add the XML to the cache. -* Loading a BitmapFont will add the image used as the font texture into the Texture Manager and the XML into the XML cache, using the key you specified for the font, so you can extract it more easily if needed. -* The default number of max parallel file loads has increased from 4 to 32. You can still change it in the game config. -* Normal Maps can now be loaded using a config object: `load.image({ key: 'shinyRobot', url: 'rob.png', normalMap: 'rob_n.png' });` - you can still use the previous array method too. -* Loader.enableParallel has been removed. If you don't want parallel file loads then set the maximum parallel limit to 1. Related to this, the Game Config `loaderEnableParallel` property has been removed. -* You can now set the `X-Requested-With` header in the XHR requests by specifying it in your XHRSettings config, either in the game, scene or file configs. -* Files will consider themselves as errored if the xhr status is >= 400 and <= 599, even if they didn't throw an onerror event. - -### Updates - -* If you're using Webpack with Phaser you'll need to update your config to match our new one. The two changes are: We've removed the need for `raw-loader` and we've changed the syntax of the DefinePlugin calls: -* We've swapped use of the Webpack DefinePlugin so instead of setting a global flag for the compilation of the Canvas and WebGL renderers, we use a typeof check instead. This means you should now be able to ingest the Phaser source more easily outside of Webpack without having to define any global vars (thanks @tgrajewski) -* Under Webpack we still no longer use `raw-loader` to import our shader source. Instead it's compiled to plain JS files during our in-house workflow. This should allow you to bundle Phaser with packages other than Webpack more easily. -* The Texture Manager will now emit an `addtexture` event whenever you add a new texture to it, which includes when you load image files from the Loader (as it automatically populates the Texture Manager). Once you receive an `addtexture` event you know the image is loaded and the texture is safe to be applied to a Game Object. -* BitmapMask and GeometryMask both have new `destroy` methods which clear their references, freeing them for gc. -* CanvasPool has a new argument `selfParent` which allows the canvas itself to be the parent key, used for later removal. -* Frame has a new method `setSize` which allows you to set the frame x, y, width and height and have it update all of the internal properties automatically. This is now called directly in the constructor. -* When a TextureSource is destroyed if it's got a canvas texture it's removed from the CanvasPool. -* TextureManager.checkKey will check if a texture key is in-use and log a console error if it is and then return a boolean. This is now used extensively internally to prevent you from adding textures that already exist into the manager. If you wish to just check if a key is in use without the error, use the `TextureManager.exists` method as before. -* TextureManager.remove will allow you to remove a texture from the manager. The texture is destroyed and it emits a `removetexture` event. -* TextureSource has a new property `renderer` as it's used a lot internally and is useful if you extend the class. -* TextureSource will now remove its respective WebGLTexture from the renderer when destroyed. -* TextureSource will now automatically create a glTexture from its canvas if using one. -* WebGLRenderer will now remove a GL texture from its local `nativeTextures` array when you call the `deleteTexture` method. -* The BaseCache has a new method `exists` that will return a boolean if an entry for the given key exists in the cache or not. -* ScenePlugin.getIndex will return the index of the given Scene in the Scene List. -* The Scene Systems will emit a `ready` event when it has fully finished starting up and all plugins are available. Re: #3636 (thanks @Yazir) -* All Game Object Creators now have an extra boolean argument `addToScene`. If you set this to `true` it will add the Game Object being created to the Scene automatically, while `false` will do the opposite, i.e.: `this.make.image(config, false)`. You can still specify the `add` property in the Config object too, but if the argument is provided it will override the property. -* We have removed the TextureManager.addAtlasPyxel method and related parser. It didn't work anyway and no-one seems to use Pyxel any more. If we get enough demand we can consider adding it back. -* When adding an Audio Sprite to the Sound Manager it will now respect the `loop` property, if set in the source JSON. -* The Texture class has a new method `getDataSourceImage` which will return the raw image data of the data source. -* The WebAudioSoundManager will now listen for 'click' events on the document body, as well as touch events, before resuming the AudioContext, in order to deal with the changes made in Chrome v66 not playing audio until a user gesture is received, even on desktop. - -### Bug Fixes - -* DataManagerPlugin would throw an error on Game.destroy if you had any Scenes in the Scene Manager had not been run. Fix #3596 (thanks @kuoruan) -* If you created a Game with no Scenes defined, and then added one via `Game.scene.add` and passed in a data object, the data would be ignored when starting the Scene. -* Adding a Group with an array of children in the constructor was broken since 3.5. Fix #3612 (thanks @fariazz @samme) -* Fix ParticleEmitter toJSON output, it was missing the `angle` property and the Emitter Ops were being cast wrong (thanks @samme) -* Fixed loading normals with multi image load (thanks @iamchristopher) -* Array.AddAt would fail if it branched to the fast-path within a Container due to an invalid property. Fix #3617 (thanks @poasher) -* Polygon.setTo would fail if given an array of arrays as a list of points. Fix #3619 (thanks @PaulTodd) -* Text objects with word wrapping enabled would gain an extra space at the end of the line. These are now only added when the word index is greater than the previous one. Fix #3626 (thanks @rexrainbow) -* Container.getBounds now checks if it can call `getBounds` on its children before doing so, as some do not have this method (such as Graphics objects) so they no longer cause the call to crash. Fix #3623 (thanks @poasher) -* The Animation Component `setProgress` method was setting the frame on the wrong object. Fix #3633 (thanks @benhhopkins) -* SceneManager.moveAbove wouldn't move the Scene if it was already above the target Scene. Now it moves to be directly above the target Scene no matter where in the Scene List it is. -* SceneManager.moveBelow wouldn't move the Scene if it was already below the target Scene. Now it moves to be directly below the target Scene no matter where in the Scene List it is. -* Emitter.setEmitZone was rejecting custom objects passed as the source argument because it was checking for the wrong methods (thanks @samme) -* ScenePlugin.setActive would only toggle the current Scene, not any given Scene. -* ScenePlugin.setVisible would only toggle the current Scene, not any given Scene. -* The Graphics Creator would automatically add the Graphics to the display list by mistake. The default should be to remain hidden. Fix #3637 (thanks @mikuso) -* BitmapText, both static and dynamic, can now take any data-type, including numbers, for the `text` argument in the constructor. Before they only worked via `setText` (thanks @Jelaw21) -* The Forward Diffuse Light Pipeline was hard coded to assume the normal map would be stored in the source index zero. It now correctly obtains the normal map from the frame source index, which means all Game Objects that used frames from multi-atlas textures will now work with lights properly. -* The Tiled Base64Decode function worked off the wrong array length, causing extra undefined values at the end (thanks @tamagokun) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@wtravO @Fabadiculous @zilbuz @samme @iamchristopher @erd0s @PaNaVTEC @ksmai @snowbillr - -## Version 3.7.0 - Sinon - 4th May 2018 - -A beta release of the 3.7.0 version. See 3.7.1 for details. - -## Version 3.6.0 - Asuna - 19th April 2018 - -### New Features - -* Containers are now fully available! We have removed the beta warning and fixed the way in which they work with Cameras, input and scroll factors. They are also fully documented, so please see their docs and examples for use. -* Group.getLast will return the last member in the Group matching the search criteria. -* Group.getFirstNth will return the nth member in the Group, scanning from top to bottom, that matches the search criteria. -* Group.getLastNth will return the nth member in the Group, scanning in reverse, that matches the search criteria. -* Group.remove has a new optional argument `destroyChild` that will call `destroy` on the child after removing it. -* Group.clear has a new optional argument `destroyChild` that will call `destroy` on all children in the Group after removing them. - -### Updates - -* Impact Physics Game Objects have changed `setLite` to `setLiteCollision`. -* Impact Physics Game Objects have changed `setPassive` to `setPassiveCollision`. -* Impact Physics Game Objects have changed `setFixed` to `setFixedCollision`. -* Impact Physics Game Objects have changed `setActive` to `setActiveCollision`, previously the `setActive` collision method was overwriting the Game Objects `setActive` method, hence the renaming. -* The modifications made to the RTree class in Phaser 3.4.0 to avoid CSP policy violations caused a significant performance hit once a substantial number of bodies were involved. We have recoded how the class deals with its accessor formats and returned to 3.3 level performance while still maintaining CSP policy adherence. Fix #3594 (thanks @16patsle) -* The Retro Font namespace has changed to `Phaser.GameObjects.RetroFont`. Previously, you would access the parser and constants via `BitmapText`, i.e.: `Phaser.GameObjects.BitmapText.ParseRetroFont.TEXT_SET6`. This has now changed to its own namespace, so the same line would be: `Phaser.GameObjects.RetroFont.TEXT_SET6`. The Parser is available via `Phaser.GameObjects.RetroFont.Parse`. This keeps things cleaner and also unbinds RetroFont from BitmapText, allowing you to cleanly exclude it from your build should you wish. All examples have been updated to reflect this. -* If using the `removeFromScene` option in Group.remove or Group.clear it will remove the child/ren from the Scene to which they belong, not the Scene the Group belongs to. - -### Bug Fixes - -* Fixed a bug that caused data to not be passed to another Scene if you used a transition to start it. Fix #3586 (thanks @willywu) -* Group.getHandler would return any member of the Group, regardless of the state, causing pools to remain fixed at once member. Fix #3592 (thanks @samme) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@Fabadiculous @Antriel - -## Version 3.5.1 - Kirito - 17th April 2018 - -### Updates - -* The change made in 3.5.0 with how the Scene systems lifecycle is handled has been tweaked. When a Scene is instantiated it will now emit a boot event, as before, and Systems that need it will listen for this event and set-up their internal properties as required. They'll also do the same under the 'start' event, allowing them to restart properly once shutdown. In 3.5 if a Scene was previously not launched or started you wouldn't be able to access all of its internal systems fully, but in 3.5.1 you can. - -### Bug Fixes - -* LoaderPlugin.destroy would try and remove an incorrect event listener. -* TileSprites would try to call `deleteTexture` on both renderers, but it's only available in WebGL (thanks @jmcriat) -* Using a geometry mask stopped working in WebGL. Fix #3582 (thanks @rafelsanso) -* The particle emitter incorrectly adjusted the vertex count, causing WebGL rendering issues. Fix #3583 (thanks @murteira) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@NemoStein @gabegordon @gazpachu @samme @cristlee @melissaelopez @dazigemm @tgrajewski - -## Version 3.5.0 - Kirito - 16th April 2018 - -### Changes to Cameras - -* The Camera class and all Camera effects are now fully covered by 100% complete JS Docs. -* All Camera effects have been recoded from scratch. They now follow a unified effects structure and each effect is encapsulated in its own class found in the 'effects' folder. Currently there are Fade, Flash and Shake effects. -* The new effects classes are accessed via the Camera properties `fadeEffect`, `flashEffect` and `shakeEffect`. You can still use the friendly Camera level methods: `shake`, `fade` and `flash`. -* The new structure means you can replace the default effects with your own by simply overwriting the properties with your own class. -* The effects now work properly under any combination. For example, you can fade out then in, or in then out, and still flash or shake while a fade is happening. The renderers now properly stack the effects in order to allow this. -* All of the effect related Camera properties (like `_fadeAlpha`) have been removed. If you need access to these values you can get it much more cleanly via the camera effects classes themselves. They were always private anyway, but we know some of you needed to modify them, so have been doing so from your code. This code will now need updating. -* Removed Camera.clearBeforeRender property as it was never used internally. This setting can be enabled on a Game-wide basis. -* Camera now extends the Event Emitter, allowing it to emit events. -* Camera.cullHitTest has been removed. It was never used internally and duplicates the code in `Camera.cull`. -* The `callback` property of the Camera effects methods has changed purpose. It is no longer an `onComplete` callback, but is now an `onUpdate` callback. It is invoked every frame for the duration of the effect. See the docs for argument details. -* Camera effects now dispatch events. They dispatch 'start' and 'complete' events, which can be used to handle any actions you may previously have been doing in the callback. See the effects docs and examples for the event names and arguments. -* The Camera Shake effect now lets you specify a different intensities for the x and y dimensions. -* You can track the progress of all events via the `progress` property on the effect instance, allowing you to sync effect duration with other in-game events. - -### New Feature: Scene Transitions - -There is a new method available in the ScenePlugin, available via: `this.scene.transition` which allows you to transition from one Scene to another over the duration specified. The method takes a configuration object which lets you control various aspects of the transition, from moving the Scenes around the display list, to specifying an onUpdate callback. - -The calling Scene can be sent to sleep, stopped or removed entirely from the Scene Manager at the end of the transition, and you can even lock down input events in both Scenes while the transition is happening, if required. There are various events dispatched from both the calling and target Scene, which combined with the onUpdate callback give you the flexibility to create some truly impressive transition effects both into and out of Scenes. - -Please see the complete JSDocs for the ScenePlugin for more details, as well as the new examples in the Phaser 3 Labs. - -### More New Features - -* GameObject.ignoreDestroy allows you to control if a Game Object is destroyed or not. Setting the flag will tell it to ignore destroy requests from Groups, Containers and even the Scene itself. See the docs for more details. -* The Scene Input Plugin has a new property `enabled` which allows you to enable or disable input processing on per Scene basis. - -### Bug Fixes - -* MatterEvents.off() would cause a TypeError if you destroyed the Matter world. Fix #3562 (thanks @pixelscripter) -* DynamicBitmapText was missing the `letterSpacing` property, causing it to only render the first character in WebGL (thanks @Antriel) -* The Animation component didn't properly check for the animation state in its update, causing pause / resume to fail. Fix #3556 (thanks @Antriel @siolfyr) -* The Scene Manager would never reach an `isBooted` state if you didn't add any Scenes into the Game Config. Fix #3553 (thanks @rgk) -* Fixed issue in HTMLAudioSound where `mute` would get into a recursive loop. -* Every RenderTexture would draw the same content due to a mis-use of the CanvasPool (this also impacted TileSprites). Fix #3555 (thanks @kuoruan) -* Group.add and Group.addMultiple now respect the Group.maxSize property, stopping you from over-populating a Group (thanks @samme) -* When using HTML5 Audio, sound manager now tries to unlock audio after every scene loads, instead of only after first one. Fix #3309 (thanks @pavle-goloskokovic) -* Group.createMultiple would insert null entries if the Group became full during the operation, causing errors later. Now it stops creating objects if the Group becomes full (thanks @samme) -* Group.remove didn't check if the passed Game Object was already a member of the group and would call `removeCallback` and (if specified) `destroy` in any case. Now it does nothing if the Game Object isn't a member of the group (thanks @samme) -* If a Group size exceeded `maxSize` (which can happen if you reduce maxSize beneath the current size), `isFull` would return false and the group could continue to grow. Now `isFull` returns true in that case (thanks @samme) -* Camera.fadeIn following a fadeOut wouldn't work, but is now fixed as a result of the Camera effects rewrite. Fix #3527 (thanks @Jerenaux) -* Particle Emitters with large volumes of particles would throw the error `GL_INVALID_OPERATION: Vertex buffer is not big enough for the draw call` in WebGL. -* Fixed issue with Game.destroy not working correctly under WebGL since 3.4. Fix #3569 (thanks @Huararanga) - -### Updates - -* Removed the following properties from BaseSound as they are no longer required. Each class that extends BaseSound implements them directly as getters: `mute`, `loop`, `seek` and `volume`. -* The Device.OS test to see if Phaser is running under node.js has been strengthened to support node-like environments like Vue (thanks @Chumper) -* Every Plugin has been updated to correctly follow the same flow through the Scene lifecycle. Instead of listening for the Scene 'boot' event, which is only dispatched once (when the Scene is first created), they will now listen for the Scene 'start' event, which occurs every time the Scene is started. All plugins now consistently follow the same Shutdown and Destroy patterns too, meaning they tidy-up after themselves on a shutdown, not just a destroy. Overall, this change means that there should be less issues when returning to previously closed Scenes, as the plugins will restart themselves properly. -* When shutting down a Scene all Game Objects that belong to the scene will now automatically destroy themselves. They would previously be removed from the display and update lists, but the objects themselves didn't self-destruct. You can control this on a per-object basis with the `ignoreDestroy` property. -* A Matter Mouse Spring will disable debug draw of its constraint by default (you can override it by passing in your own config) -* The RandomDataGenerator class is now exposed under Phaser.Math should you wish to instantiate it yourself. Fix #3576 (thanks @wtravO) -* Refined the Game.destroy sequence, so it will now only destroy the game at the start of the next frame, not during processing. - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@samme @Antriel - -## Version 3.4.0 - Miyako - 12th April 2018 - -### New Features - -A beta release of the new Container Game Object arrives in this version. We've flagged it as beta because there are known issues in using Containers in Scenes that have multiple cameras or irregular camera viewports. However, in all other instances we've tested they are operating normally, so we felt it would be best to release them into this build to give developers a chance to get used to them. Using a Container will issue a single console warning as a reminder. We will remove this once they leave beta in a future release. In the meantime they are fully documented and you can find numerous examples in the Phaser 3 Examples repo too. - -* A new property was added to Matter.World, `correction` which is used in the Engine.update call and allows you to adjust the time being passed to the simulation. The default value is 1 to remain consistent with previous releases. -* Matter Physics now has a new config property `getDelta` which allows you to specify your own function to calculate the delta value given to the Matter Engine when it updates. -* Matter Physics has two new methods: `set60Hz` and `set30Hz` which will set an Engine update rate of 60Hz and 30Hz respectively. 60Hz being the default. -* Matter Physics has a new config and run-time property `autoUpdate`, which defaults to `true`. When enabled the Matter Engine will update in sync with the game step (set by Request Animation Frame). The delta value given to Matter is now controlled by the `getDelta` function. -* Matter Physics has a new method `step` which manually advances the physics simulation by one iteration, using whatever delta and correction values you pass in to it. When used in combination with `autoUpdate=false` you can now explicitly control the update frequency of the physics simulation and unbind it from the game step. -* Matter Physics has two new debug properties: `debugShowJoint` and `debugJointColor`. If defined they will display joints in Matter bodies during the postUpdate debug phase (only if debug is enabled) (thanks @OmarShehata) -* Group.destroy has a new optional argument `destroyChildren` which will automatically call `destroy` on all children of a Group if set to true (the default is false, hence it doesn't change the public API). Fix #3246 (thanks @DouglasLapsley) -* WebAudioSound.setMute is a chainable way to mute a single Sound instance. -* WebAudioSound.setVolume is a chainable way to set the volume of a single Sound instance. -* WebAudioSound.setSeek is a chainable way to set seek to a point of a single Sound instance. -* WebAudioSound.setLoop is a chainable way to set the loop state of a single Sound instance. -* HTML5AudioSound.setMute is a chainable way to mute a single Sound instance. -* HTML5AudioSound.setVolume is a chainable way to set the volume of a single Sound instance. -* HTML5AudioSound.setSeek is a chainable way to set seek to a point of a single Sound instance. -* HTML5AudioSound.setLoop is a chainable way to set the loop state of a single Sound instance. -* BitmapText has a new property `letterSpacing` which accepts a positive or negative number to add / reduce spacing between characters (thanks @wtravO) -* You can now pass a Sprite Sheet or Canvas as the Texture key to `Tilemap.addTileset` and it will work in WebGL, where-as before it would display a corrupted tilemap. Fix #3407 (thanks @Zykino) -* Graphics.slice allows you to easily draw a Pacman, or slice of pie shape to a Graphics object. -* List.addCallback is a new optional callback that is invoked every time a new child is added to the List. You can use this to have a callback fire when children are added to the Display List. -* List.removeCallback is a new optional callback that is invoked every time a new child is removed from the List. You can use this to have a callback fire when children are removed from the Display List. -* ScenePlugin.restart allows you to restart the current Scene. It's the same result as calling `ScenePlugin.start` without any arguments, but is more clear. -* Utils.Array.Add allows you to add one or more items safely to an array, with optional limits and callbacks. -* Utils.Array.AddAt allows you to add one or more items safely to an array at a specified position, with optional limits and callbacks. -* Utils.Array.BringToTop allows you to bring an array element to the top of the array. -* Utils.Array.CountAllMatching will scan an array and count all elements with properties matching the given value. -* Utils.Array.Each will pass each element of an array to a given callback, with optional arguments. -* Utils.Array.EachInRange will pass each element of an array in a given range to a callback, with optional arguments. -* Utils.Array.GetAll will return all elements from an array, with optional property and value comparisons. -* Utils.Array.GetFirst will return the first element in an array, with optional property and value comparisons. -* Utils.Array.GetRandomElement has been renamed to GetRandom and will return a random element from an array. -* Utils.Array.MoveDown will move the given array element down one position in the array. -* Utils.Array.MoveTo will move the given array element to the given position in the array. -* Utils.Array.MoveUp will move the given array element up one position in the array. -* Utils.Array.Remove will remove the given element or array of elements from the array, with an optional callback. -* Utils.Array.RemoveAt will remove the element from the given position in the array, with an optional callback. -* Utils.Array.RemoveBetween will remove the elements between the given range in the array, with an optional callback. -* Utils.Array.Replace will replace an existing element in an array with a new one. -* Utils.Array.SendToBack allows you to send an array element to the bottom of the array. -* Utils.Array.SetAll will set a property on all elements of an array to the given value, with optional range limits. -* Utils.Array.Swap will swap the position of two elements in an array. -* TransformMatrix.destroy is a new method that will clear out the array and object used by a Matrix internally. -* BaseSound, and by extension WebAudioSound and HTMLAudioSound, will now emit a `destroy` event when they are destroyed (thanks @rexrainbow) -* A new property was added to the Scene config: `mapAdd` which is used to extend the default injection map of a scene instead of overwriting it (thanks @sebashwa) -* GetBounds `getTopLeft`, `getTopRight`, `getBottomLeft` and `getBottomRight` all have a new optional argument `includeParent` which will factor in all ancestor transforms to the returned point. - -### Bug Fixes - -* In the WebGL Render Texture the tint of the texture was always set to 0xffffff and therefore the alpha values were ignored. The tint is now calculated using the alpha value. Fix #3385 (thanks @ger1995) -* The RenderTexture now uses the ComputedSize component instead of Size (which requires a frame), allowing calls to getBounds to work. Fix #3451 (thanks @kuoruan) -* PathFollower.start has been renamed to `startFollow`, but PathFollower.setPath was still using `PathFollower.start` (thanks @samid737) -* BaseSoundManager.rate and BaseSoundManager.detune would incorrectly called `setRate` on its sounds, instead of `calculateRate`. -* The Gamepad Axis `getValue` method now correctly applies the threshold and zeroes out the returned value. -* The HueToComponent module was not correctly exporting itself. Fix #3482 (thanks @jdotrjs) -* Matter.World was using `setZ` instead of `setDepth` for the Debug Graphics Layer, causing it to appear behind objects in some display lists. -* Game.destroy now checks to see if the `renderer` exists before calling destroy on it. Fix #3498 (thanks @Huararanga) -* Keyboard.JustDown and Keyboard.JustUp were being reset too early, causing them to fail when called in `update` loops. Fix #3490 (thanks @belen-albeza) -* RenderTexture.destroy no longer throws an error when called. Fix #3475 (thanks @kuoruan) -* The WebGL TileSprite batch now modulates the tilePosition to avoid large values being passed into the UV data, fixing corruption when scrolling TileSprites over a long period of time. Fix #3402 (thanks @vinerz @FrancescoNegri) -* LineCurve.getResolution was missing the `divisions` argument and always returning 1, which made it fail when used as part of a Path. It now defaults to return 1 unless specified otherwise (thanks _ok) -* A Game Object enabled for drag would no longer fire over and out events after being dragged, now it does (thanks @jmcriat) -* Line.getPointA and Line.getPointB incorrectly set the values into the Vector2 (thanks @Tomas2h) -* DynamicTilemapLayer now uses the ComputedSize component, which stops it breaking if you call `setDisplaySize` (thanks Babsobar) -* StaticTilemapLayer now uses the ComputedSize component, which stops it breaking if you call `setDisplaySize` (thanks Babsobar) -* CanvasPool.first always returned `null`, and now returns the first available Canvas. Fix #3520 (thanks @mchiasson) -* When starting a new Scene with an optional `data` argument it wouldn't get passed through if the Scene was not yet available (i.e. the game had not fully booted). The data is now passed to the Scene `init` and `create` methods and stored in the Scene Settings `data` property. Fix #3363 (thanks @pixelhijack) -* Tween.restart handles removed tweens properly and reads them back into the active queue for the TweenManager (thanks @wtravO) -* Tween.resume will now call `Tween.play` on a tween that was paused due to its config object, not as a result of having its paused method called. Fix #3452 (thanks @jazen) -* LoaderPlugin.isReady referenced a constant that no longer exists. Fix #3503 (thanks @Twilrom) -* Tween Timeline.destroy was trying to call `destroy` on Tweens instead of `stop` (thanks @Antriel) -* Calling `setOffset` on a Static Arcade Physics Body would break because the method was missing. It has been added and now functions as expected. Fix #3465 (thanks @josephjaniga and @DouglasLapsley) -* Calling Impact.World.remove(body) during a Body.updateCallback would cause the internal loop to crash when trying to access a now missing body. Two extra checks are in place to avoid this (thanks @iamDecode) -* If `setInteractive` is called on a Game Object that fails to set a hit area, it will no longer try to assign `dropZone` to an undefined `input` property. -* The Matter SetBody Component will no longer try to call `setOrigin` unless the Game Object has the origin component (which not all do, like Graphics and Container) -* Matter Image and Matter Sprite didn't define a `destroy` method, causing an error when trying to destroy the parent Game Object. Fix #3516 (thanks @RollinSafary) - -### Updates - -* The RTree library (rbush) used by Phaser 3 suffered from violating CSP policies by dynamically creating Functions at run-time in an eval-like manner. These are now defined via generators. Fix #3441 (thanks @jamierocks @Colbydude @jdotrjs) -* BaseSound has had its `rate` and `detune` properties removed as they are always set in the overriding class. -* BaseSound `setRate` and `setDetune` from the 3.3.0 release have moved to the WebAudioSound and HTML5AudioSound classes respectively, as they each handle the values differently. -* The file `InteractiveObject.js` has been renamed to `CreateInteractiveObject.js` to more accurately reflect what it does and to avoid type errors in the docs. -* Renamed the Camera Controls module exports for `Fixed` to `FixedKeyControl` and `Smoothed` to `SmoothedKeyControl` to match the class names. Fix #3463 (thanks @seivan) -* The ComputedSize Component now has `setSize` and `setDisplaySize` methods. This component is used for Game Objects that have a non-texture based size. -* The GamepadManager now extends EventEmitter directly, just like the KeyboardManager does. -* The Gamepad Axis threshold has been increased from 0.05 to 0.1. -* Utils.Array.FindClosestInSorted has a new optional argument `key` which will allow you to scan a top-level property of any object in the given sorted array and get the closest match to it. -* Vector2.setTo is a method alias for Vector2.set allowing it to be used inter-changeably with Geom.Point. -* List.add can now take an array or a single child. If an array is given it's passed over to List.addMultiple. -* List.add has a new optional argument `skipCallback`. -* List.addAt has a new optional argument `skipCallback`. -* List.addMultiple has a new optional argument `skipCallback`. -* List.remove has a new optional argument `skipCallback`. -* List.removeAt has a new optional argument `skipCallback`. -* List.removeBetween has a new optional argument `skipCallback`. -* List.removeAll has a new optional argument `skipCallback`. -* When using the `extend` property of a Scene config object it will now block overwriting the Scene `sys` property. -* When using the `extend` property of a Scene config object, if you define a property called `data` that has an object set, it will populate the Scenes Data Manager with those values. -* SceneManager._processing has been renamed to `isProcessing` which is now a boolean, not an integer. It's also now public and read-only. -* SceneManager.isBooted is a new boolean read-only property that lets you know if the Scene Manager has performed its initial boot sequence. -* TransformMatrix has the following new getter and setters: `a`, `b`, `c`, `d`, `tx` and `ty`. It also has the following new getters: `scaleX`, `scaleY` and `rotation`. -* List.getByKey has been removed. Use `List.getFirst` instead which offers the exact same functionality. -* List.sortIndexHandler has been removed because it's no longer required. -* List.sort no longer takes an array as its argument, instead it only sorts the List contents by the defined property. -* List.addMultiple has been removed. Used `List.add` instead which offers the exact same functionality. -* List is now internally using all of the new Utils.Array functions. -* Rectangle.Union will now cache all vars internally so you can use one of the input rectangles as the output rectangle without corrupting it. -* When shutting down a Matter World it will now call MatterEvents.off, clearing all events, and also `removeAllListeners` for any local events. -* Removed InputPlugin.sortInteractiveObjects because the method isn't used anywhere internally. - -### Animation System Updates - -We have refactored the Animation API to make it more consistent with the rest of Phaser 3 and to fix some issues. All of the following changes apply to the Animation Component: - -* Animation durations, delays and repeatDelays are all now specified in milliseconds, not seconds like before. This makes them consistent with Tweens, Sounds and other parts of v3. You can still use the `frameRate` property to set the speed of an animation in frames per second. -* All of the Animation callbacks have been removed, including `onStart`, `onRepeat`, `onUpdate` and `onComplete` and the corresponding params arrays like `onStartParams` and the property `callbackScope`. The reason for this is that they were all set on a global level, meaning that if you had 100 Sprites sharing the same animation, it was impossible to set the callbacks to fire for just one of those Sprites, but instead they would fire for all 100 and it was up to you to figure out which Sprite you wanted to update. Instead of callbacks animations now dispatch events on the Game Objects in which they are running. This means you can now do `sprite.on('animationstart')` and it will be invoked at the same point the old `onStart` callback would have been. The new events are: `animationstart`, `animtionrepeat`, `animationupdate` and `animationcomplete`. They're all dispatched from the Game Object that has the animation playing, not from the animation itself. This allows you far more control over what happens in the callbacks and we believe generally makes them more useful. -* The AnimationFrame.onUpdate callback has been removed. You can now use the `animationupdate` event dispatched from the Game Object itself and check the 2nd argument, which is the animation frame. -* Animation.stopAfterDelay is a new method that will stop a Sprites animation after the given time in ms. -* Animation.stopOnRepeat is a new method that will stop a Sprites animation when it goes to repeat. -* Animation.stopOnFrame is a new method that will stop a Sprites animation when it sets the given frame. -* Animation.stop no longer has the `dispatchCallbacks` argument, because it dispatches an event which you can choose to ignore. -* `delay` method has been removed. -* `setDelay` allows you to define the delay before playback begins. -* `getDelay` returns the animation playback delay value. -* `delayedPlay` now returns the parent Game Object instead of the component. -* `load` now returns the parent Game Object instead of the component. -* `pause` now returns the parent Game Object instead of the component. -* `resume` now returns the parent Game Object instead of the component. -* `isPaused` returns a boolean indicating the paused state of the animation. -* `paused` method has been removed. -* `play` now returns the parent Game Object instead of the component. -* `progress` method has been removed. -* `getProgress` returns the animation progress value. -* `setProgress` lets you jump the animation to a specific progress point. -* `repeat` method has been removed. -* `getRepeat` returns the animation repeat value. -* `setRepeat` sets the number of times the current animation will repeat. -* `repeatDelay` method has been removed. -* `getRepeatDelay` returns the animation repeat delay value. -* `setRepeatDelay` sets the delay time between each repeat. -* `restart` now returns the parent Game Object instead of the component. -* `stop` now returns the parent Game Object instead of the component. -* `timeScale` method has been removed. -* `getTimeScale` returns the animation time scale value. -* `setTimeScale` sets the time scale value. -* `totalFrames` method has been removed. -* `getTotalFrames` returns the total number of frames in the animation. -* `totalProgres` method has been removed as it did nothing and was mis-spelt. -* `yoyo` method has been removed. -* `getYoyo` returns if the animation will yoyo or not. -* `setYoyo` sets if the animation will yoyo or not. -* `updateFrame` will now call `setSizeToFrame` on the Game Object, which will adjust the Game Objects `width` and `height` properties to match the frame size. Fix #3473 (thanks @wtravO @jp-gc) -* `updateFrame` now supports animation frames with custom pivot points and injects these into the Game Object origin. -* `destroy` now removes events, references to the Animation Manager and parent Game Object, clears the current animation and frame and empties internal arrays. -* Changing the `yoyo` property on an Animation Component would have no effect as it only ever checked the global property, it now checks the local one properly allowing you to specify a `yoyo` on a per Game Object basis. -* Animation.destroy now properly clears the global animation object. -* Animation.getFrameByProgress will return the Animation Frame that is closest to the given progress value. For example, in a 5 frame animation calling this method with a value of 0.5 would return the middle frame. - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@gabegordon @melissaelopez @samid737 @nbs @tgrajewski @pagesrichie @hexus @mbrickn @erd0s @icbat @Matthew-Herman @ampled @mkimmet @PaNaVTEC - -## Version 3.3.0 - Tetsuo - 22nd March 2018 - -A special mention must go to @orblazer for their outstanding assistance in helping to complete the JSDoc data-types, callbacks and type defs across the API. - -### New Features - -* TextStyle has two new properties: `baselineX` and `baselineY` which allow you to customize the 'magic' value used in calculating the text metrics. -* Game.Config.preserveDrawingBuffer is now passed to the WebGL Renderer (default `false`). -* Game.Config.failIfMajorPerformanceCaveat is now passed to the WebGL Renderer (default `false`). -* Game.Config.powerPreference is now passed to the WebGL Renderer (default `default`). -* Game.Config.antialias is now passed to the WebGL Renderer as the antialias context property (default `true`). -* Game.Config.pixelArt is now only used by the WebGL Renderer when creating new textures. -* Game.Config.premultipliedAlpha is now passed to the WebGL Renderer as the premultipliedAlpha context property (default `true`). -* You can now specify all of the renderer config options within a `render` object in the config. If no `render` object is found, it will scan the config object directly for the properties. -* Group.create has a new optional argument: `active` which will set the active state of the child being created (thanks @samme) -* Group.create has a new optional argument: `active` which will set the active state of the child being created (thanks @samme) -* Group.createMultiple now allows you to include the `active` property in the config object (thanks @samme) -* TileSprite has a new method: `setTilePosition` which allows you to set the tile position in a chained called (thanks @samme) -* Added the new Action - WrapInRectangle. This will wrap each items coordinates within a rectangles area (thanks @samme) -* Arcade Physics has the new methods `wrap`, `wrapArray` and `wrapObject` which allow you to wrap physics bodies around the world bounds (thanks @samme) -* The Tweens Timeline has a new method: `makeActive` which delegates control to the Tween Manager (thanks @allanbreyes) -* Actions.GetLast will return the last element in the items array matching the conditions. -* Actions.PropertyValueInc is a new action that will increment any property of an array of objects by the given amount, using an optional step value, index and iteration direction. Most Actions have been updated to use this internally. -* Actions.PropertyValueSet is a new action that will set any property of an array of objects to the given value, using an optional step value, index and iteration direction. Most Actions have been updated to use this internally. -* Camera.shake now has an optional `callback` argument that is invoked when the effect completes (thanks @pixelscripter) -* Camera.fade now has an optional `callback` argument that is invoked when the effect completes (thanks @pixelscripter) -* Camera.flash now has an optional `callback` argument that is invoked when the effect completes (thanks @pixelscripter) -* Camera.fadeIn is a new method that will fade the camera in from a given color (black by default) and then optionally invoke a callback. This is the same as using Camera.flash but with an easier to grok method name. Fix #3412 (thanks @Jerenaux) -* Camera.fadeOut is a new method that will fade the camera out to a given color (black by default) and then optionally invoke a callback. This is the same as using Camera.fade but with an easier to grok method name. Fix #3412 (thanks @Jerenaux) -* Groups will now listen for a `destroy` event from any Game Object added to them, and if received will automatically remove that GameObject from the Group. Fix #3418 (thanks @hadikcz) -* MatterGameObject is a new function, available via the Matter Factory in `this.matter.add.gameObject`, that will inject a Matter JS Body into any Game Object, such as a Text or TileSprite object. -* Matter.SetBody and SetExistingBody will now set the origin of the Game Object to be the Matter JS sprite.xOffset and yOffset values, which will auto-center the Game Object to the origin of the body, regardless of shape. -* SoundManager.setRate is a chainable method to allow you to set the global playback rate of all sounds in the SoundManager. -* SoundManager.setDetune is a chainable method to allow you to set the global detuning of all sounds in the SoundManager. -* SoundManager.setMute is a chainable method to allow you to set the global mute state of the SoundManager. -* SoundManager.setVolume is a chainable method to allow you to set the global volume of the SoundManager. -* BaseSound.setRate is a chainable method to allow you to set the playback rate of the BaseSound. -* BaseSound.setDetune is a chainable method to allow you to set the detuning value of the BaseSound. - -### Bug Fixes - -* Fixed the Debug draw of a scaled circle body in Arcade Physics (thanks @pixelpicosean) -* Fixed bug in `DataManager.merge` where it would copy the object reference instead of its value (thanks @rexrainbow) -* The SceneManager no longer copies over the `shutdown` and `destroy` callbacks in createSceneFromObject, as these are not called automatically and should be invoked via the Scene events (thanks @samme) -* The default Gamepad Button threshold has been changed from 0 to 1. Previously the value of 0 was making all gamepad buttons appear as if they were always pressed down (thanks @jmcriat) -* InputManager.hitTest will now factor the game resolution into account, stopping the tests from being offset if resolution didn't equal 1 (thanks @sftsk) -* CameraManager.getCamera now returns the Camera based on its name (thanks @bigbozo) -* Fixed Tile Culling for zoomed Cameras. When a Camera was zoomed the tiles would be aggressively culled as the dimensions didn't factor in the zoom level (thanks @bigbozo) -* When calling ScenePlugin.start any additional data passed to the method would be lost if the scene wasn't in an active running state (thanks @stuff) -* When calling Timeline.resetTweens, while the tweens are pending removal or completed, it would throw a TypeError about the undefined `makeActive` (thanks @allanbreyes) -* The WebGL Context would set `antialias` to `undefined` as it wasn't set in the Game Config. Fix #3386 (thanks @samme) -* The TweenManager will now check the state of a tween before playing it. If not in a pending state it will be skipped. This allows you to stop a tween immediately after creating it and not have it play through once anyway. Fix #3405 (thanks @Twilrom) -* The InputPlugin.processOverOutEvents method wasn't correctly working out the total of the number of objects interacted with, which caused input events to be disabled in Scenes further down the scene list if something was being dragged in an upper scene. Fix #3399 (thanks @Jerenaux) -* The InputPlugin.processDragEvents wasn't always returning an integer. -* LoaderPlugin.progress and the corresponding event now factor in both the list size and the inflight size when calculating the percentage complete. Fix #3384 (thanks @vinerz @rblopes @samme) -* Phaser.Utils.Array.Matrix.RotateLeft actually rotated to the right (thanks @Tomas2h) -* Phaser.Utils.Array.Matrix.RotateRight actually rotated to the left (thanks @Tomas2h) -* When deleting a Scene from the SceneManager it would set the key in the scenes has to `undefined`, preventing you from registering a new Scene with the same key. It's now properly removed from the hash(thanks @macbury) -* Graphics.alpha was being ignored in the WebGL renderer and is now applied properly to strokes and fills. Fix #3426 (thanks @Ziao) -* The font is now synced to the context in Text before running a word wrap, this ensures the wrapping result between updating the text and getting the wrapped text is the same. Fix #3389 (thanks @rexrainbow) -* Added the ComputedSize component to the Text Game Object, which allows Text.getBounds, and related methods, to work again instead of returning NaN. -* Group.remove now calls the `removeCallback` and passes it the child that was removed (thanks @orblazer) - -### Updates - -* The Text testString has changed from `|MÉqgy` to `|MÉqgy`. -* The WebGLRenderer width and height values are now floored when multiplied by the resolution. -* The WebGL Context now sets `premultipliedAlpha` to `true` by default, this prevents the WebGL context from rendering as plain white under certain versions of macOS Safari. -* The Phaser.Display.Align constants are now exposed on the namespace. Fix #3387 (thanks @samme) -* The Phaser.Loader constants are now exposed on the namespace. Fix #3387 (thanks @samme) -* The Phaser.Physics.Arcade constants are now exposed on the namespace. Fix #3387 (thanks @samme) -* The Phaser.Scene constants are now exposed on the namespace. Fix #3387 (thanks @samme) -* The Phaser.Tweens constants are now exposed on the namespace. Fix #3387 (thanks @samme) -* The Array Matrix utils are now exposed and available via `Phaser.Utils.Array.Matrix`. -* Actions.Angle has 3 new arguments: `step`, `index` and `direction`. -* Actions.IncAlpha has 3 new arguments: `step`, `index` and `direction`. -* Actions.IncX has 3 new arguments: `step`, `index` and `direction`. -* Actions.IncY has 3 new arguments: `step`, `index` and `direction`. -* Actions.IncXY has 4 new arguments: `stepX`, `stepY`, `index` and `direction`. -* Actions.Rotate has 3 new arguments: `step`, `index` and `direction`. -* Actions.ScaleX has 3 new arguments: `step`, `index` and `direction`. -* Actions.ScaleXY has 4 new arguments: `stepX`, `stepY`, `index` and `direction`. -* Actions.ScaleY has 3 new arguments: `step`, `index` and `direction`. -* Actions.SetAlpha has 2 new arguments: `index` and `direction`. -* Actions.SetBlendMode has 2 new arguments: `index` and `direction`. -* Actions.SetDepth has 2 new arguments: `index` and `direction`. -* Actions.SetOrigin has 4 new arguments: `stepX`, `stepY`, `index` and `direction`. -* Actions.SetRotation has 2 new arguments: `index` and `direction`. -* Actions.SetScale has 2 new arguments: `index` and `direction`. -* Actions.SetScaleX has 2 new arguments: `index` and `direction`. -* Actions.SetScaleY has 2 new arguments: `index` and `direction`. -* Actions.SetVisible has 2 new arguments: `index` and `direction`. -* Actions.SetX has 2 new arguments: `index` and `direction`. -* Actions.SetXY has 2 new arguments: `index` and `direction`. -* Actions.SetY has 2 new arguments: `index` and `direction`. -* Line.getPointA now returns a Vector2 instead of an untyped object. It also now has an optional argument that allows you to pass a vec2 in to be populated, rather than creating a new one. -* Line.getPointB now returns a Vector2 instead of an untyped object. It also now has an optional argument that allows you to pass a vec2 in to be populated, rather than creating a new one. -* Rectangle.getLineA now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* Rectangle.getLineB now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* Rectangle.getLineC now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* Rectangle.getLineD now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* Triangle.getLineA now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* Triangle.getLineB now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* Triangle.getLineC now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. -* The GameObject `destroy` event is now emitted at the start of the destroy process, before things like the body or input managers have been removed, so you're able to use the event handler to extract any information you require from the GameObject before it's actually disposed of. Previously, the event was dispatched at the very end of the process. -* Phaser 3 is now built with Webpack v4.1.1 and all related packages have been updated (thanks @orblazer) -* On WebGL the currentScissor is now updated when the renderer `resize` method is called (thanks @jmcriat) -* PathFollower.start has been renamed to `startFollow` to avoid conflicting with the Animation component. -* PathFollower.pause has been renamed to `pauseFollow` to avoid conflicting with the Animation component. -* PathFollower.resume has been renamed to `resumeFollow` to avoid conflicting with the Animation component. -* PathFollower.stop has been renamed to `stopFollow` to avoid conflicting with the Animation component. -* BaseSound.setRate has been renamed to `calculateRate` to avoid confusion over the setting of the sounds rate. - -## Version 3.2.1 - 12th March 2018 - -### Bug Fixes - -* Fixed issue with Render Texture tinting. Fix #3336 (thanks @rexrainbow) -* Fixed Utils.String.Format (thanks @samme) -* The Matter Debug Layer wouldn't clear itself in canvas mode. Fix #3345 (thanks @samid737) -* TimerEvent.remove would dispatch the Timer event immediately based on the opposite of the method argument, making it behave the opposite of what was expected. It now only fires when requested (thanks @migiyubi) -* The TileSprite Canvas Renderer did not support rotation, scaling or flipping. Fix #3231 (thanks @TCatshoek) -* Fixed Group doesn't remove children from Scene when cleared with the `removeFromScene` argument set (thanks @iamchristopher) -* Fixed an error in the lights pipeline when no Light Manager has been defined (thanks @samme) -* The ForwardDiffuseLightPipeline now uses `sys.lights` instead of the Scene variable to avoid errors due to injection removal. -* Phaser.Display.Color.Interpolate would return NaN values because it was loading the wrong Linear function. Fix #3372 (thanks @samid737) -* RenderTexture.draw was only drawing the base frame of a Texture. Fix #3374 (thanks @samid737) -* TileSprite scaling differed between WebGL and Canvas. Fix #3338 (thanks @TCatshoek) -* Text.setFixedSize was incorrectly setting the `text` property instead of the `parent` property. Fix #3375 (thanks @rexrainbow) -* RenderTexture.clear on canvas was using the last transform state, instead of clearing the whole texture. - -### Updates - -* The SceneManager.render will now render a Scene as long as it's in a LOADING state or higher. Before it would only render RUNNING scenes, but this precluded those that were loading assets. -* A Scene can now be restarted by calling `scene.start()` and providing no arguments (thanks @migiyubi) -* The class GameObject has now been exposed, available via `Phaser.GameObjects.GameObject` (thanks @rexrainbow) -* A Camera following a Game Object will now take the zoom factor of the camera into consideration when scrolling. Fix #3353 (thanks @brandonvdongen) -* Calling `setText` on a BitmapText object will now recalculate its display origin values. Fix #3350 (thanks @migiyubi) -* You can now pass an object to Loader.atlas, like you you can with images. Fix #3268 (thanks @TCatshoek) -* The `onContextRestored` callback won't be defined any more unless the WebGL Renderer is in use in the following objects: BitmapMask, Static Tilemap, TileSprite and Text. This should allow those objects to now work in HEADLESS mode. Fix #3368 (thanks @16patsle) -* The SetFrame method now has two optional arguments: `updateSize` and `updateOrigin` (both true by default) which will update the size and origin of the Game Object respectively. Fix #3339 (thanks @Jerenaux) - -## Version 3.2.0 - Kaori - 5th March 2018 - -### New Features - -* The new Render Texture Game Object is now available. You can clear, fill and draw texture frames to it. The Render Texture itself can be displayed in-game with its own transform, or you can use it as a Bitmap Mask for another Game Object. -* Game.resize allows you to resize the game config, renderer and input system in one call. -* When Game.resize is called it causes all Scene.Systems to have their resize method called. This is turn emits a `resize` event which your Scene can respond to. It will be sent the new width and height of the canvas as the only two parameters. -* InputManager.resize allows you to update the bounds def and input scale in one call. -* Game.Config.roundPixels property added to prevent sub-pixel interpolation during rendering of Game Objects in WebGL and Canvas. -* Load.plugin now accepts a class as an argument as well as a URL string (thanks @nkholski) -* Tween.complete will allow you to flag a tween as being complete, no matter what stage it is at. If an onComplete callback has been defined it will be invoked. You can set an optional delay before this happens (thanks @Jerenaux for the idea) -* The Headless render mode has been implemented. You can now set HEADLESS as the `renderType` in the Game Config and it will run a special game step that skips rendering. It will still create a Canvas element, as lots of internal systems (like input) rely on it, but it will not draw anything to it. Fix #3256 (thanks @rgk) -* GameObject.setInteractive has a new boolean argument `dropZone` which will allow you to set the object as being a drop zone right from the method. -* Sprites can now be drop zones and have other Game Objects dragged onto them as targets. -* The SceneManager has a new method: `remove` which allows you to remove and destroy a Scene, freeing up the Scene key for use by future scenes and potentially clearing the Scene from active memory for gc. -* SceneManager.moveAbove will move a Scene to be directly above another Scene in the Scenes list. This is also exposed in the ScenePlugin. -* SceneManager.moveBelow will move a Scene to be directly below another Scene in the Scenes list. This is also exposed in the ScenePlugin. -* Quadratic Bezier Interpolation has been added to the Math.Interpolation functions (thanks @RiCoTeRoX) -* A new Quadratic Bezier Curve class has been added, expanding the available Curve types (thanks @RiCoTeRoX) -* Path.quadraticBezierTo allows you to add a Quadratic Bezier Curve into your Path. -* Loader.multiatlas now supports Texture Packers new JSON atlas format which exports one combined atlas for all image files. This is available if you use the new Phaser 3 Export from within Texture Packer (thanks @CodeAndWeb) -* Modified WebGLPipeline to make it easier to extend and easier to create custom rendering passes. - -### Bug Fixes - -* Arcade Physics Bodies didn't apply the results of `allowRotation` to the parent Game Object. -* InputManager.updateBounds wouldn't correctly get the bounds of the canvas if it had horizontal or vertical translation in the page, causing the scale factor to be off (and subsequently input values to mis-fire) -* TileSprite.setFrame now works and allows you to change the frame to any other in the texture. Fix #3232 (thanks @Jerenaux) -* Swapped the queue loop in the SceneManager to to use `_queue.length` rather than a cached length (thanks @srobertson421) -* When calling `ScenePlugin.launch` the `data` argument is now passed to the queued scenes (thanks @gaudeon) -* Rectangle.top wouldn't reset the `y` position if the value given never exceed the Rectangles bottom. Fix #3290 (thanks @chancezeus) -* The implementation of `topOnly` within the Input Manager had broken the way drop zones worked, as they were now filtered out of the display list before processing. Drop zones are now treated on their own in the Input Plugin meaning you can still have `topOnly` set and still drop an item into a drop zone. This indirectly fixed #3291 (thanks @rexrainbow) -* InputPlugin.clear now properly removes a Game Object from all internal arrays, not just the _list. -* InputPlugin.processOverOut no longer considers an item as being 'out' if it's in the internal `_drag` array. -* When a Game Object is scaled, its Arcade Physics body was still calculating its position based on its original size instead of scaled one (thanks @pixelpicosean) -* The RandomDataGenerator classes randomness has been improved thanks to the correct caching of a class property. Fix #3289 (thanks @migiyubi) -* The RandomDataGenerator `sign` property had a method collision. Fix #3323 (thanks @vinerz and @samme) -* In Arcade Physics World if you collided a group with itself it would call a missing method (`collideGroupVsSelf`), it now calls `collideGroupVsGroup` correctly (thanks @patrickgalbraith) -* The HTML5 Sound Manager would unlock the Sound API on a touch event but only if the audio files were loaded in the first Scene, if they were loaded in a subsequent Scene the audio system would never unlock. It now unlocks only if there are audio files in the cache. Fix #3311 (thanks @chancezeus) -* The Text.lineSpacing value was not taken into account when rendering the Text. Fix #3215 (thanks @sftsk) -* InputPlugin.update now takes the totals from the drag and pointerup events into consideration when deciding to fall through to the Scene below. Fix #3333 (thanks @chancezeus) - -### Updates - -* AnimationComponent.play now calls `setSizeToFrame()` and `updateDisplayOrigin()` on the parent Game Object in order to catch situations where you've started playing an animation on a Game Object that uses a different size to the previously set frame. -* Text.setText will check if the value given is falsey but not a zero and set to an empty string if so. -* BitmapText.setText will check if the value given is falsey but not a zero and set to an empty string if so. -* BitmapText.setText will now cast the given value to a string before setting. -* BitmapText.setText will not change the text via `setText` unless the new text is different to the old one. -* If you set `transparent` in the Game Config but didn't provide a `backgroundColor` then it would render as black. It will now be properly transparent. If you do provide a color value then it must include an alpha component. -* You can now pass normal Groups to Arcade Physics collide / overlap, as well as Physics Groups. Fix #3277 (thanks @nkholski) -* Texture.get has been optimized to fail first, then error, with a new falsey check. This allows you to skip out specifying animation frames in the animation config without generating a console warning. -* The `setFrame` method of the Texture component has been updated so that it will now automatically reset the `width` and `height` of a Game Object to match that of the new Frame. Related, it will also adjust the display origin values, because they are size based. If the Frame has a custom pivot it will set the origin to match the custom pivot instead. -* ScenePlugin.swapPosition now allows you to use it to swap the positions of any two Scenes. Before the change it only allowed you to swap the position of the calling Scene and another one, but a new optional `keyB` argument opens this up. -* The SceneManager no longer renders a Scene unless it is visible AND either running or paused. This now skips Scenes that are in an `init` state. -* The Keyboard Manager will now no longer emit `keydown` events if you keep holding a key down. Fix #3239 (thanks @squaresun) -* The SceneManager now employs a new queue for all pending Scenes, creating them and booting them in strict sequence. This should prevent errors where Scenes were unable to reference other Scenes further down the boot list in their create functions. Fix #3314 (thanks @max1701 @rblopes) -* Game.preBoot and Game.postBoot callbacks now pass an instance of the game to the callback (thanks @rblopes) -* Graphics.arc in WebGL mode now works more like arc does in Canvas (thanks @Twilrom) -* GameObjects now emit a 'destroy' event when they are destroyed, which you can use to perform any additional processing you require. Fix #3251 (thanks @rexrainbow) -* If an HTML5AudioSound sound fails to play it will now issue a console.warn (thanks @samme) -* Phaser is now running Travis CI build testing again (thanks @vpmedia) -* Documentation updates: thanks to @melissaelopez @samme @jblang94 - -## Version 3.1.2 - 23rd February 2018 - -### Updates - -* Hundreds of JSDoc fixes across the whole API. -* Tween.updateTweenData will now check to see if the Tween target still exists before trying to update its properties. -* If you try to use a local data URI in the Loader it now console warns instead of logs (thanks @samme) - -### Bug Fixes - -* The KeyCode `FORWAD_SLASH` had a typo and has been changed to `FORWARD_SLASH`. Fix #3271 (thanks @josedarioxyz) -* Fixed issue with vertex buffer creation on Static Tilemap Layer, causing tilemap layers to appear black. Fix #3266 (thanks @akleemans) -* Implemented Static Tilemap Layer scaling and Tile alpha support. -* Fixed issue with null texture on Particle Emitter batch generation. This would manifest if you had particles with blend modes on-top of other images not appearing. -* Added missing data parameter to ScenePlugin. Fixes #3810 (thanks @AleBles) - -## Version 3.1.1 - 20th February 2018 - -### Updates - -* The entire codebase now passes our eslint config (which helped highlight a few errors), if you're submitting a PR, please ensure your PR passes the config too. -* The Web Audio Context is now suspended instead of closed to allow for prevention of 'Failed to construct AudioContext: maximum number of hardware contexts reached' errors from Chrome in a hot reload environment. We still strongly recommend reusing the same context in a production environment. See [this example](http://labs.phaser.io/view.html?src=src%5Caudio%5CWeb%20Audio%5CReuse%20AudioContext.js) for details. Fixes #3238 (thanks @z0y1 @Ziao) -* The Webpack shell plugin now fires on `onBuildExit`, meaning it'll update the examples if you use `webpack watch` (thanks @rblopes) -* Added `root: true` flag to the eslint config to stop it scanning further-up the filesystem. - -### Bug Fixes - -* Math.Fuzzy.Floor had an incorrect method signature. -* Arcade Physics World didn't import GetOverlapX or GetOverlapY, causing `separateCircle` to break. -* TileSprite was missing a gl reference, causing it to fail during a context loss and restore. -* The Mesh Game Object Factory entry had incorrect arguments passed to Mesh constructor. -* Removed unused `_queue` property from `ScenePlugin` class (thanks @rblopes) -* The variable `static` is no longer used in Arcade Physics, fixing the 'static is a reserved word' in strict mode error (thanks @samme) -* Fixed `Set.union`, `Set.intersect` and `Set.difference` (thanks @yupaul) -* The corner tints were being applied in the wrong order. Fixes #3252 (thanks @Rybar) -* BitmapText objects would ignore calls to setOrigin. Fixes #3249 (thanks @amkazan) -* Fixed a 1px camera jitter and bleeding issue in the renderer. Fixes #3245 (thanks @bradharms) -* Fixed the error `WebGL: INVALID_ENUM: blendEquation: invalid mode.` that would arise on iOS. Fixes #3244 (thanks @Ziao) -* The `drawBlitter` function would crash if `roundPixels` was true. Fixes #3243 (thanks @Jerenaux and @vulcanoidlogic) - -## Version 3.1.0 - Onishi - 16th February 2018 - -### Updates - -* Vertex resource handling code updated, further optimizing the WebGL batching. You should now see less gl ops per frame across all batches. -* The `Blitter` game object has been updated to use the `List` structure instead of `DisplayList`. -* Arcade Physics World `disableBody` has been renamed `disableGameObjectBody` to more accurately reflect what it does. -* Lots of un-used properties were removed from the Arcade Physics Static Body object. -* Arcade Physics Static Body can now refresh itself from its parent via `refreshBody`. - -### Bug Fixes - -* A couple of accidental uses of `let` existed, which broke Image loading in Safari # (thanks Yat Hin Wong) -* Added the static property `Graphics.TargetCamera` was added back in which fixed `Graphics.generateTexture`. -* The SetHitArea Action now calls `setInteractive`, fixing `Group.createMultiple` when a hitArea has been set. -* Removed rogue Tween emit calls. Fix #3222 (thanks @ZaDarkSide) -* Fixed incorrect call to TweenManager.makeActive. Fix #3219 (thanks @ZaDarkSide) -* The Depth component was missing from the Zone Game Object. Fix #3213 (thanks @Twilrom) -* Fixed issue with `Blitter` overwriting previous objects vertex data. -* The `Tile` game object tinting was fixed, so tiles now honor alpha values correctly. -* The `BitmapMask` would sometimes incorrectly bind its resources. -* Fixed the wrong Extend target in MergeXHRSettings (thanks @samme) - -### New Features - -* Destroying a Game Object will now call destroy on its physics body, if it has one set. -* Arcade Physics Colliders have a new `name` property and corresponding `setName` method. -* Matter.js bodies now have an inlined destroy method that removes them from the World. -* Impact bodies now remove themselves from the World when destroyed. -* Added Vector2.ZERO static property. +# Change Log + +## Version 3.23 - Ginro - in development + +### JSDocs + +The following sections now have 100% complete JSDoc coverage: + +* Animations +* Create +* Geom +* Math +* Renderer +* Textures + +### Removed + +The following features have been removed in this version of Phaser: + +* Impact Physics has been removed completely and is no longer a choice of physics system. The resulting `Scene.impact` property and Impact config object have also been removed. + +### Deprecated + +The following features are now deprecated and will be removed in a future version of Phaser: + +* The Light Pipeline and associated components will be removed. This feature was never properly finished and adds too much redundant, non-optional code into the core API. The ability to load normal maps alongside textures will _remain_, for use in your own lighting shaders, which gives you far more control over the final effect. + + +### New Features + +* `Line.GetEasedPoints` is a new function that will take a Line, a quantity, and an ease function, and returns an array of points where each point has been spaced out across the length of the Line based on the ease function given. +* `XHRSettings.withCredentials` is a new boolean property that controls the `withCredentials` setting of the XHR Request made by the Loader. It indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. You can set this on a per-file basis, or global in the Game Config. +* `Config.loaderWithCredentials` is the new global setting for `XHRSettings.withCredentials`. +* `Camera.renderToGame` is a new property used in conjunction with `renderToTexture`. It controls if the Camera should still render to the Game canvas after rendering to its own texture or not. By default, it will render to both, but you can now toggle this at run-time. +* `Camera.setRenderToTexture` has a new optional parameter `renderToGame` which sets the `Camera.renderToGame` property, controlling if the Camera should render to both its texture and the Game canvas, or just its texture. + +### Updates + +* `XHRLoader` will now use the `XHRSettings.withCredentials` as set in the file or global loader config. +* `Animation.setCurrentFrame` will no longer try to call `setOrigin` or `updateDisplayOrigin` if the Game Object doesn't have the Origin component, preventing unknown function errors. +* `MatterTileBody` now extends `EventEmitter`, meaning you can listen to collision events from Tiles directly and it will no longer throw errors about `gameObject.emit` not working. Fix #4967 (thanks @reinildo) +* Added `MatterJS.BodyType` to `GameObject.body` type. Fix #4962 (thanks @meisterpeeps) + +### Bug Fixes + +* The conditional checking if the `PathFollower` was at the end of the path or not was incorrect (thanks @samme) +* Creating an `Arcade Physics Body` from a scaled Game Object would use the un-scaled dimensions for the body. They now use the scaled dimensions. This may be a breaking change in some games, so please be aware of it (thanks @samme) +* Creating an `Arcade Physics Static Body` from a scaled Game Object would use the un-scaled dimensions for the body. They now use the scaled dimensions. This may be a breaking change in some games, so please be aware of it (thanks @samme) +* The `Arcade Physics Static Body` center was incorrect after construction. Probably caused problems with circle collisions. Fix #4770 (thanks @samme) +* An Arcade Physics Body `center` and `position` are now correct after construction and before preUpdate(), for any Game Object origin or scale (thanks @samme) +* When calling `Body.setSize` with the `center` parameter as `true` the calculated offset would be incorrect for scaled Game Objects. The offset now takes scaling into consideration (thanks @samme) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@JasonHK @supertommy + +## Version 3.22 - Kohaku - January 15th 2020 + +### Matter Physics + +All of the following are specific to the Matter Physics implementation used by Phaser: + +#### Matter Physics New Features + +* Matter Physics now has 100% JSDoc coverage! Woohoo :) +* Matter Physics now has brand new TypeScript defs included in the `types` folder :) +* `MatterDebugConfig` is a new configuration object that contains all of the following new Matter debug settings: +* `showAxes`- Render all of the body axes? +* `showAngleIndicator`- Render just a single body axis? +* `angleColor`- The color of the body angle / axes lines. +* `showBroadphase`- Render the broadphase grid? +* `broadphaseColor`- The color of the broadphase grid. +* `showBounds`- Render the bounds of the bodies in the world? +* `boundsColor`- The color of the body bounds. +* `showVelocity`- Render the velocity of the bodies in the world? +* `velocityColor`- The color of the body velocity line. +* `showCollisions`- Render the collision points and normals for colliding pairs. +* `collisionColor`- The color of the collision points. +* `showSeparation`- Render lines showing the separation between bodies. +* `separationColor`- The color of the body separation line. +* `showBody`- Render the dynamic bodies in the world to the Graphics object? +* `showStaticBody`- Render the static bodies in the world to the Graphics object? +* `showInternalEdges`- When rendering bodies, render the internal edges as well? +* `renderFill`- Render the bodies using a fill color. +* `renderLine`- Render the bodies using a line stroke. +* `fillColor`- The color value of the fill when rendering dynamic bodies. +* `fillOpacity`- The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. +* `lineColor`- The color value of the line stroke when rendering dynamic bodies. +* `lineOpacity`- The opacity of the line when rendering dynamic bodies, a value between 0 and 1. +* `lineThickness`- If rendering lines, the thickness of the line. +* `staticFillColor`- The color value of the fill when rendering static bodies. +* `staticLineColor`- The color value of the line stroke when rendering static bodies. +* `showSleeping`- Render any sleeping bodies (dynamic or static) in the world to the Graphics object? +* `staticBodySleepOpacity`] - The amount to multiply the opacity of sleeping static bodies by. +* `sleepFillColor`- The color value of the fill when rendering sleeping dynamic bodies. +* `sleepLineColor`- The color value of the line stroke when rendering sleeping dynamic bodies. +* `showSensors`- Render bodies or body parts that are flagged as being a sensor? +* `sensorFillColor`- The fill color when rendering body sensors. +* `sensorLineColor`- The line color when rendering body sensors. +* `showPositions`- Render the position of non-static bodies? +* `positionSize`- The size of the rectangle drawn when rendering the body position. +* `positionColor`- The color value of the rectangle drawn when rendering the body position. +* `showJoint`- Render all world constraints to the Graphics object? +* `jointColor`- The color value of joints when `showJoint` is set. +* `jointLineOpacity`- The line opacity when rendering joints, a value between 0 and 1. +* `jointLineThickness`- The line thickness when rendering joints. +* `pinSize`- The size of the circles drawn when rendering pin constraints. +* `pinColor`- The color value of the circles drawn when rendering pin constraints. +* `springColor`- The color value of spring constraints. +* `anchorColor`- The color value of constraint anchors. +* `anchorSize`- The size of the circles drawn as the constraint anchors. +* `showConvexHulls`- When rendering polygon bodies, render the convex hull as well? +* `hullColor`- The color value of hulls when `showConvexHulls` is set. +* `World.renderBody` is a new method that will render a single Matter Body to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which bodies are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. +* `World.renderConstraint` is a new method that will render a single Matter Constraint, such as a pin or a spring, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which constraints are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. +* `World.renderConvexHull` is a new method that will render the convex hull of a single Matter Body, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which hulls are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. +* `World.renderGrid` is a new method that will render the broadphase Grid to the given graphics instance. +* `World.renderBodyBounds` is a new method that will render the bounds of all the given bodies to the given graphics instance. +* `World.renderBodyAxes` is a new method that will render the axes of all the given bodies to the given graphics instance. +* `World.renderBodyVelocity` is a new method that will render a velocity line for all the given bodies to the given graphics instance. +* `World.renderSeparations` is a new method that will render the separations in the current pairs list to the given graphics instance. +* `World.renderCollisions` is a new method that will render the collision points and normals in the current pairs list to the given graphics instance. +* `World.getAllBodies` is a new method that will return all bodies in the Matter World. +* `World.getAllConstraints` is a new method that will return all constraints in the Matter World. +* `World.getAllComposites` is a new method that will return all composites in the Matter World. +* `MatterPhysics.composite` is a new reference to the `Matter.Composite` module for easy access from within a Scene. +* `MatterPhysics.detector` is a new reference to the `Matter.Dectector` module for easy access from within a Scene. +* `MatterPhysics.grid` is a new reference to the `Matter.Grid` module for easy access from within a Scene. +* `MatterPhysics.pair` is a new reference to the `Matter.Pair` module for easy access from within a Scene. +* `MatterPhysics.pairs` is a new reference to the `Matter.Pairs` module for easy access from within a Scene. +* `MatterPhysics.query` is a new reference to the `Matter.Query` module for easy access from within a Scene. +* `MatterPhysics.resolver` is a new reference to the `Matter.Resolver` module for easy access from within a Scene. +* `MatterPhysics.sat` is a new reference to the `Matter.SAT` module for easy access from within a Scene. +* `MatterPhysics.constraint` is a new reference to the `Matter.Constraint` module for easy access from within a Scene. +* `MatterPhysics.composites` is a new reference to the `Matter.Composites` module for easy access from within a Scene. +* `MatterPhysics.axes` is a new reference to the `Matter.Axes` module for easy access from within a Scene. +* `MatterPhysics.bounds` is a new reference to the `Matter.Bounds` module for easy access from within a Scene. +* `MatterPhysics.svg` is a new reference to the `Matter.Svg` module for easy access from within a Scene. +* `MatterPhysics.vector` is a new reference to the `Matter.Vector` module for easy access from within a Scene. +* `MatterPhysics.vertices` is a new reference to the `Matter.Vertices` module for easy access from within a Scene. +* `BEFORE_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be added to the World. +* `AFTER_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint has been added to the World. +* `BEFORE_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be removed from the World. +* `AFTER_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint has been removed from the World. +* `Body.render.lineOpacity` is a new property on the Matter Body object that allows for custom debug rendering. +* `Body.render.lineThickness` is a new property on the Matter Body object that allows for custom debug rendering. +* `Body.render.fillOpacity` is a new property on the Matter Body object that allows for custom debug rendering. +* `World.setCompositeRenderStyle` is a new method that lets you quickly set the render style values on the children of the given compposite. +* `World.setBodyRenderStyle` is a new method that lets you quickly set the render style values on the given Body. +* `World.setConstraintRenderStyle` is a new method that lets you quickly set the render style values on the given Constraint. +* You can now set `restingThresh` in the Matter Configuration file to adjust the Resolver property. +* You can now set `restingThreshTangent` in the Matter Configuration file to adjust the Resolver property. +* You can now set `positionDampen` in the Matter Configuration file to adjust the Resolver property. +* You can now set `positionWarming` in the Matter Configuration file to adjust the Resolver property. +* You can now set `frictionNormalMultiplier` in the Matter Configuration file to adjust the Resolver property. +* `MatterPhysics.containsPoint` is a new method that returns a boolean if any of the given bodies intersect with the given point. +* `MatterPhysics.intersectPoint` is a new method that checks which bodies intersect with the given point and returns them. +* `MatterPhysics.intersectRect` is a new method that checks which bodies intersect with the given rectangular area, and returns them. Optionally, it can check which bodies are outside of the area. +* `MatterPhysics.intersectRay` is a new method that checks which bodies intersect with the given ray segment and returns them. Optionally, you can set the width of the ray. +* `MatterPhysics.intersectBody` is a new method that checks which bodies intersect with the given body and returns them. If the bodies are set to not collide this can be used as an overlaps check. +* `MatterPhysics.overlap` is a new method that takes a target body and checks to see if it overlaps with any of the bodies given. If they do, optional `process` and `overlap` callbacks are invoked, passing the overlapping bodies to them, along with additional collision data. +* `MatterPhysics.setCollisionCategory` is a new method that will set the collision filter category to the value given, on all of the bodies given. This allows you to easily set the category on bodies that don't have a Phaser Matter Collision component. +* `MatterPhysics.setCollisionGroup` is a new method that will set the collision filter group to the value given, on all of the bodies given. This allows you to easily set the group on bodies that don't have a Phaser Matter Collision component. +* `MatterPhysics.setCollidesWith` is a new method that will set the collision filter mask to the value given, on all of the bodies given. This allows you to easily set the filter mask on bodies that don't have a Phaser Matter Collision component. +* `Matter.Body.centerOfMass` is a new vec2 property added to the Matter Body object that retains the center of mass coordinates when the Body is first created, or has parts added to it. These are float values, derived from the body position and bounds. +* `Matter.Body.centerOffset` is a new vec2 property added to the Matter Body object that retains the center offset coordinates when the Body is first created, or has parts added to it. These are pixel values. +* `Constraint.pointAWorld` is a new method added to Matter that returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`. +* `Constraint.pointBWorld` is a new method added to Matter that returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`. +* `Body.setCentre` is a new method added to Matter that allows you to set the center of mass of a Body (please note the English spelling of this function.) +* `Body.scale` is a new read-only vector that holds the most recent scale values as passed to `Body.scale`. +* `Matter.Bodies.flagCoincidentParts` is a new function that will flags all internal edges (coincident parts) on an array of body parts. This was previously part of the `fromVertices` function, but has been made external for outside use. +* `Matter.getMatterBodies` is a new function that will return an array of Matter JS Bodies from the given input array, which can be Matter Game Objects, or any class that extends them. +* `Matter.World.has` is a new method that will take a Matter Body, or Game Object, and search the world for it. If found, it will return `true`. +* Matter now has the option to use the Runner that it ships with. The Matter Runner operates in two modes: fixed and variable. In the fixed mode, the Matter Engine updates at a fixed delta value every frame (which is what Phaser has used since the first version). In variable mode, the delta will be smoothed and capped each frame to keep the simulation constant, but at the cost of determininism. You can configure the runner by setting the `runner` property in the Matter Config object, both of which are fully covered with JSDocs. As of 3.22 the runner is now used by default in variable (non-fixed) mode. If you wish to return to the previous behavior, set `runner: { isFixed: true }`. +* `Body.onCollideCallback` is a new Matter Body property that can point to a callback to invoke when the body starts colliding. +* `Body.onCollideEndCallback` is a new Matter Body property that can point to a callback to invoke when the body stops colliding. +* `Body.onCollideActiveCallback` is a new Matter Body property that can point to a callback to invoke for the duration the body is colliding. +* `Body.onCollideWith` is a new Matter Body property that holds a mapping between bodies and collision callbacks. +* `MatterGameObject.setOnCollide` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body collides with another. +* `MatterGameObject.setOnCollideEnd` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body stops colliding. +* `MatterGameObject.setOnCollideActive` is a new method available on any Matter Game Object, that sets a callback which is invoked for the duration of the bodies collision with another. +* `MatterGameObject.setOnCollideWith` is a new method available on any Matter Game Object, that allows you to set a callback to be invoked whenever the body collides with another specific body, or array of bodies. +* `Body.gravityScale` is a new vector property that allows you to scale the effect of world gravity on a specific Body. +* `MatterPhysics._tempVec2` is a new private internal vector used for velocity and force calculations. +* `MatterPhysics.setVelocity` is a new method that will set both the horizontal and vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.setVelocityX` is a new method that will set the horizontal linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.setVelocityY` is a new method that will set the vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.setAngularVelocity` is a new method that will set the angular velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.applyForce` is a new method that applies a force to a body, at the bodies current position, including resulting torque. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.applyForceFromPosition` is a new method that applies a force to a body from the given world position, including resulting torque. If no angle is given, the current body angle is used. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.fromSVG` is a new method that allows you to create a Body from the given SVG path data. +* The `Matter.Factory.velocity` method has been removed. Please now use `MatterPhysics.setVelocity` instead. +* The `Matter.Factory.angularVelocity` method has been removed. Please now use `MatterPhysics.setAngularVelocity` instead. +* The `Matter.Factory.force` method has been removed. Please now use `MatterPhysics.applyForce` instead. +* `MatterBodyConfig` is a new type def that contains all of the Body configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterBodyRenderConfig` is a new type def that contains all of the Body debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterChamferConfig` is a new type def that contains all of the chamfer configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterCollisionFilter` is a new type def that contains all of the collision configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterConstraintConfig` is a new type def that contains all of the constraint configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterConstraintRenderConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterSetBodyConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterPhysics.getConstraintLength` is a new method that will return the length of the given constraint, as this is something you cannot get from the constraint properties directly. +* `MatterPhysics.alignBody` is a new method that will align a Body, or Matter Game Object, against the given coordinates, using the given alignment constant. For example, this allows you to easily position a body to the `BOTTOM_LEFT`, or `TOP_CENTER`, or a coordinate. Alignment is based on the body bounds. +* `Phaser.Types.Physics.Matter.MatterBody` is a new type def that contains all of the valid Matter Body objects. This is now used through-out the JSDocs to aid in code-completion. +* `Matter.BodyBounds` is a new class that contains methods to help you extract 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 new class via `this.matter.bodyBounds`. +* The method signature for `Matter.PhysicsEditorParser.parseBody` has changed. It now takes `(x, y, config, options)` and no longer has `width` and `height` parameters. Please see the updated documentation for more details if you were calling this method directly. +* `MatterPhysics.fromPhysicsEditor` is a new method that allows you to create a Matter Body based on the given PhysicsEditor shape data. Previously, you could only using PhysicsEditor data with a Matter Game Object, but now you can create a body directly using it. +* `Matter.PhysicsJSONParser` is a new parser that will create Matter bodies from JSON physics data files. Currently onto the Phaser Physics Tracer app exports in this format, but details are published in the JSDocs, so any app can do so. +* `Matter.Factory.fromJSON` is a new method that will create a body from a JSON physics data file. +* The `SetBody` Matter component can now automatically use shapes created in the Phaser Physics Tracer App in the JSON data format. +* `Matter.Components.Sleep.setToSleep` is a new method available on any Matter Game Object that will send the body to sleep, if Engine sleeping has been enabled. +* `Matter.Components.Sleep.setAwake` is a new method available on any Matter Game Object that will awake a body from sleep, if Engine sleeping has been enabled. + +#### Matter Physics Updates + +* The `debug` property in the Matter World Config is now a `MatterDebugConfig` option instead of a boolean. However, if a boolean is given, it will use the default debug config values. +* The following `MatterWorldConfig` options have now been removed: `debugShowBody`, `debugShowStaticBody`, `debugBodyColor`, `debugBodyFillColor`, `debugStaticBodyColor`, `debugShowJoint`, `debugJointColor`, `debugWireframes`, `debugShowInternalEdges`, `debugShowConvexHulls`, `debugConvexHullColor` and `debugShowSleeping`. These can all be set via the new `MatterDebugConfig` object instead. +* The object `World.defaults` has been removed. Defaults are now access via `World.debugDefaults`. +* `World.renderBodies` has been rewritten to cache commonly-used values and avoid a situation when a single body would be rendered twice. +* The private method `World.renderConvexHulls` has been removed as it's no longer used internally. +* The private method `World.renderWireframes` has been removed as it's no longer used internally. +* The method `World.fromPath` has been removed. This was never used internally and you can get the same results by calling `Vertices.fromPath`. +* The `World.setBounds` argument `thickness` now defaults to 64, not 128, to keep it matching the Matter World Config. +* The `Body.render.fillStyle` property that existed on the Matter Body object has been removed and replaced with `fillColor`. +* The `Body.render.strokeStyle` property that existed on the Matter Body object has been removed and replaced with `lineColor`. +* `Matter.Body.render.sprite.xOffset` and `yOffset` are no longer set to anything when a Body is created. They are left as zero, or you can override them in the Body config, in which case the value is added to the sprite origin offset during a call to `setExistingBody`. +* The `Matter.Mass.centerOfMass` component property now returns the pre-calculated Body `centerOfMass` property, which is much more accurate than the previous bounds offset value. +* `Matter.setExistingBody`, which is called interally whenever a Body is set on a Game Object, now uses the new `centerOffset` values to ensure that the texture frame is correctly centered based on the center of mass, not the Body bounds, allowing for much more accurate body to texture mapping with complex multi-part compound bodies. +* The `Matter.PhysicsEditorParser` has been updated so it no longer needs to set the render offsets, and instead uses the center of mass values. +* If the `Matter.Body` config doesn't contain a `position` property, it will now default to using `Vertices.centre(body.vertices)` as the position. In most cases, this is what you need, so it saves having to pass it in the config object. +* Bumped Matter Plugin versions to avoid console logs from Common.info and Common.warn. +* `PhysicsEditorParser.parseVertices` now uses `Bodies.flagCoincidentParts` to avoid duplicating code. +* `MatterGameObject` has a new optional boolean constructor parameter `addToWorld` which lets you control if the Body should be added to the world or not. Useful for toggling off should you be merging pre-existing bodies with Game Objects. +* The `Matter.SetBody.setExistingBody` function, which all Matter Game Objects have, has a new parameter `addToWorld` which allows you to control when the body is added to the Matter world should you not require it immediately. It will also only add the body to the world if it doesn't already exist within it, or any of its composites. +* `PointerConstraint` has been recoded so that when pressed down, it only polls the World for a body hit test during the next game update. This stops it coming out of sync with the state of the world. Use of the constraint remains the same as before. +* You can now set `gravity: false` in your Matter Config and it will reset gravity from the defaults to zero. +* The internal Matter `Composite.setModified` function will now emit a `compositeModified` event, which the Matter World listens for, if debug draw is enabled, so it can update the composite children render styles. +* `Matter.PhysicsEditorParser.parseBody` can now accept a MatterBodyConfig file as a 4th parameter. This allows you to set Body properties when the body is created, overriding whatever values may have been set in the PhysicsEditor JSON. + +#### Matter Physics Bug Fixes + +* Due to the rewrite of the debug rendering, it is now possible to render _just_ constraints, where-as before this was only possible if bodies were being rendered as well. Fix #4880 (thanks @roberto257) +* `Matter.PhysicsEditorParser` had a bug where it would allow fixtures with non-clockwise sorted vertices through, which would break pointer constraint interaction with these bodies. The parser now sorts the vertices properly. Fix #4261 (thanks @Sanchez3) + +### New Features + +* `TimeStep.smoothStep` is a new boolean property that controls if any delta smoothing takes place during the game step. Delta smoothing has been enabled in Phaser since the first version and helps avoid delta spikes and dips, especially after loss of focus. However, you can now easily toggle if this happens via this property and the corresponding `FPSConfig` property. +* `Phaser.Math.Distance.BetweenPoints` is a new function that will return the distance between two Vector2-like objects (thanks @samme) +* `Phaser.Math.Distance.BetweenPointsSquared` is a new function that will return the squared distance between two Vector2-like objects (thanks @samme) +* `Phaser.Math.Distance.Chebyshev` is a new function that will return the Chebyshev (or chessboard) distance between two Vector2-like objects (thanks @samme) +* `Phaser.Math.Distance.Snake` is a new function that will return the rectilinear distance between two Vector2-like objects (thanks @samme) +* `ParticleEmitter.setTint` is a new method that will set the tint of emitted particles for the given Emitter only (thanks @samme) +* `ParticleEmitter.remove` is a new method that will remove the Emitter from its Emitter Manager (thanks @samme) +* `ParticleEmitterManager.removeEmitter` is a new method that will remove the given emitter from the manager, if the emitter belongs to it (thanks @samme) +* `AlphaSingle` is a new Game Object Component that allows a Game Object to set its alpha values, but only as a single uniform value, not on a per-quad basis. +* `Actions.AlignTo` (in combination with the new `Display.Align.To.QuickSet` function) allows you to align an array of Game Objects so they sit next to each other, one at a time. The first item isn't moved, the second is moved to sit next to the first, and so on. You can align them using any of the alignment constants (thanks @samme) +* `Scene.Systems.getData` is a new method that will return any data that was sent to the Scene by another Scene, i.e. during a `run` or `launch` command. You can access it via `this.sys.getData()` from within your Scene. +* `Group.internalCreateCallback` is a new optional callback that is invoked whenever a child is added to a Group. This is the same as `createCallback` except it's only for use by the parent class, allowing a parent to invoke a creation callback and for you to still provide one via the Group config. +* `Group.internalRemoveCallback` is a new optional callback that is invoked whenever a child is removed from a Group. This is the same as `removeCallback` except it's only for use by the parent class, allowing a parent to invoke a callback and for you to still provide one via the Group config. + +### Updates + +* `Body.deltaXFinal` is a new method on Arcade Physics Bodies that will return the final change in the horizontal position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) +* `Body.deltaYFinal` is a new method on Arcade Physics Bodies that will return the final change in the vertical position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) +* `Body._tx` is a new internal private var, holding the Arcade Physics Body combined total delta x value. +* `Body._ty` is a new internal private var, holding the Arcade Physics Body combined total delta y value. +* `LineCurve.getUtoTmapping` has been updated to return `u` directly to avoid calculations as it's identical to `t` in a Line (thanks @rexrainbow) +* `Curve.getSpacedPoints` will now take an optional array as the 3rd parameter to store the points results in (thanks @rexrainbow) +* Trying to play or resume an audio file with an incorrect key will now throw a runtime error, instead of a console warning (thanks @samme) +* The `Shape` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the shape, rather than a quad alpha, which never worked for Shape objects. +* The `Container` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the container, rather than a quad alpha, which never worked consistently across Container children. Fix #4916 (thanks @laineus) +* The `DOMElement` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. +* The `Graphics` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. +* `TweenData` has a new property called `previous` which holds the eased property value prior to the update. +* The `TWEEN_UPDATE` event now sends two new parameters to the handler: `current` and `previous` which contain the current and previous property values. +* During `collideSpriteVsGroup` checks it will now skip bodies that are disabled to save doing a `contains` test (thanks @samme) +* `Display.Align.In.QuickSet` now accepts `LEFT_BOTTOM` as `BOTTOM_LEFT`, `LEFT_TOP` as `TOP_LEFT`, `RIGHT_BOTTOM` as `BOTTOM_RIGHT` and `RIGHT_TOP` as `TOP_RIGHT`. Fix #4927 (thanks @zaniar) +* `PhysicsGroup` now uses the new `internalCreateCallback` and `internalRemoveCallback` to handle its body creation and destruction, allowing you to use your own `createCallback` and `removeCallback` as defined in the Group config. Fix #4420 #4657 #4822 (thanks @S4n60w3n @kendistiller @scrubperson) +* `DOMElement` has a new private method `handleSceneEvent` which will handle toggling the display setting of the element when a Scene sleeps and wakes. A DOM Element will now listen for the Scene sleep and wake events. These event listeners are removed in the `preDestroy` method. +* A `DOMElement` will now set the display mode to 'none' during its render if the Scene in which it belongs is no longer visible. + +### Bug Fixes + +* BitmapText with a `maxWidth` set wouldn't update the text correctly if it was modified post-creation. You can now update the text and/or width independantly and it'll update correctly. Fix #4881 (thanks @oxguy3) +* Text objects will no longer add any white-space when word-wrapping if the last line is only one word long. Fix #4867 (thanks @gaamoo @rexrainbow) +* When `Game.destroy` is running, Scenes are now destroyed _before_ plugins, avoiding bugs when closing down plugins and deleting Render Textures. Fix #4849 #4876 (thanks @rexrainbow @siyuanqiao) +* The `Mesh` and `Quad` Game Objects have had the `GetBounds` component removed as it cannot operate on a Mesh as they don't have origins. Fix #4902 (thanks @samme) +* Setting `lineSpacing` in the Text Game Object style config would set the value but not apply it to the Text, leaving you to call `updateText` yourself. If set, it's now applied on instantiation. Fix #4901 (thanks @FantaZZ) +* External calls to the Fullscreen API using `element.requestFullscreen()` would be blocked by the Scale Manager. The Scale Manager will no longer call `stopFullScreen` should it be triggered outside of Phaser (thanks @AdamXA) +* The `Tilemaps.Tile.tint` property wasn't working correctly as it expected the colors in the wrong order (BGR instead of RGB). It will now expect them in the correct RGB order (thanks @Aedalus @plissken2013es) +* The `ScaleManager.destroy` method wasn't being called when the Game `DESTROY` event was dispatched, causing minor gc to build up. The destroy method will now be called properly on game destruction. Fix #4944 (thanks @sunshineuoow) +* `FacebookInstantGamesPlugin.showAd` and `showVideo` will now break out of the ad iteration search once a valid ad has been found and called. Previously, it would carry on interating if the async didn't complete quickly. Fix #4888 (thanks @east62687) +* When playing an Animation, if you were to play another, then pause it, then play another the internal `_paused` wouldn't get reset, preventing you from them pausing the animations from that point on. You can now play and pause animations at will. Fix #4835 (thanks @murteira) +* In `Actions.GridAlign` if you set `width` to -1 it would align the items vertically, instead of horizontally. It now aligns them horizontally if `width` is set, or vertically if `height` is set. Fix #4899 (thanks @BenjaVR) +* A `PathFollower` with a very short duration would often not end in the correct place, which is the very end of the Path, due to the tween handling the movement not running one final update when the tween was complete. It will now always end at the final point of the path, no matter how short the duration. Fix #4950 (thanks @bramp) +* A `DOMElement` would still remain visible even if the Scene in which it belongs to was sent to sleep. A sleeping Scene shouldn't render anything. DOM Elements will now respond to sleep and wake events from their parent Scene. Fix #4870 (thanks @peonmodel) +* If a config object was passed to `MultiAtlasFile` it expected the atlas URL to be in the `url` property, however the docs and file config expected it in `atlasURL`. You can now use either of these properties to declare the url. Fix #4815 (thanks @xense) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@fselcukcan Bambosh @louisth @hexus @javigaralva @samme @BeLi4L @jcyuan @javigaralva @T-Grave @bramp @Chnapy @dranitski @RollinSafary @xense + +The Matter TypeScript defs have been updated to include lots of missing classes, removed some redundant elements and general fixes. The Phaser TypeScript defs now reference the Matter defs directly and no longer try to parse them from the JSDocs. This allows the `MatterJS` namespace to work in TypeScript projects without any compilation warnings. + +The Spine Plugin now has new TypeScript defs in the `types` folder thanks to @supertommy + +## Version 3.21.0 - Senku - 22nd November 2019 + +### New Features + +* You can now specify the mipmap filter level to be used when creating WebGL textures. This can be set in the Game Config using the new `mipmapFilter` property, which is a string, such as 'NEAREST_MIPMAP_NEAREST'. Or, you can set the new `WebGLRenderer.mipmapFilter` property to a valid GLenum. If you set it on the renderer, it will only impact any textures loaded _after_ it has been set, so do so in your Scene `init` method if you want it to be used for textures you're about to load. By changing the mipmap level you can drastically improve the quality when reducing large textures. Please note, due to WebGL1 limitations, this only works on power-of-two sized textures. It also works on textures created from Canvas, Videos or RenderTextures. +* `BitmapText.setMaxWidth` is a new method that allows you to set a maximum width (in pixels) for the BitmapText to take up when rendering. Lines of text longer than `maxWidth` will be wrapped, based on whitespace, to the next line. This allows you to do word-wrapping on BitmapText objects, something only previously possible on Text objects. +* `BitmapText.wordWrapCharCode` is a new property that works with `setMaxWidth` that allows you to control which character code causes a line-wrap. By default it is 32 (a space character). +* `ArcadePhysics.closest` now has an optional `targets` argument. The targets can be any Arcade Physics Game Object, Body or Static Body and it will return only the closet target from those given (thanks @samme) +* `ArcadePhysics.furthest` now has an optional `targets` argument. The targets can be any Arcade Physics Game Object, Body or Static Body and it will return only the furthest target from those given (thanks @samme) +* `Tilemaps.Parsers.Tiled.CreateGroupLayer` is a new function that parses a Tiled group layer and adds in support for Tiled layer groups (introduced in Tiled 1.2.0). Feature #4099 (thanks @Babeetlebum @Olliebrown) +* The Tilemap system now supports infinite Tilemaps from the Tiled map editor (thanks @Olliebrown) +* `Tilemap.getImageLayerNames` is a new method that returns a list of all valid imagelayer names loaded in the Tilemap (thanks @Olliebrown) +* `Tilemap.getObjectLayerNames` is a new method that returns a list of all valid objectgroup names loaded in the Tilemap (thanks @Olliebrown) +* `Tilemap.getTileLayerNames` is a new method that returns a list of all valid tilelayer names loaded in the Tilemap (thanks @Olliebrown) +* When `forceSetTimeOut` is set to `true` in the Game Config, you can now set the target frame rate by setting the `fps.target` value (thanks @pavels) +* Videos can now be loaded from a data URI, allowing for base64 encoded videos to be used in the Loader instead of file based ones. Although, as with all base64 encoded data, we strongly recommend against this (thanks @apasov) +* `Math.MIN_SAFE_INTEGER` is a new math const that stores the minimum safe integer for browsers that don't provide this, such as IE (thanks @jronn) +* `Math.MAX_SAFE_INTEGER` is a new math const that stores the maximum safe integer for browsers that don't provide this, such as IE (thanks @jronn) +* `KeyCodes.NUMPAD_ADD` has been added to the keycodes list (thanks @Martin-Antonov) +* `KeyCodes.NUMPAD_SUBTRACT` has been added to the keycodes list (thanks @Martin-Antonov) +* `Video.removeVideoElementOnDestroy` is a new boolean property that allows you to control if the Video element is removed from the DOM when the Video Game Object is destroyed. +* `Actions.SetScrollFactor` is a new Action that will set the scroll factor on an array of Game Objects, including stepped incremental changes per item (thanks @rexrainbow) +* `Actions.SetScrollFactorX` is a new Action that will set the horizontal scroll factor on an array of Game Objects, including stepped incremental changes per item (thanks @rexrainbow) +* `Actions.SetScrollFactorY` is a new Action that will set the horizontal scroll factor on an array of Game Objects, including stepped incremental changes per item (thanks @rexrainbow) +* The `Group` config object now supports use of the `setScrollFactor` property to set the value on each child of the Group (thanks @rexrainbow) +* `Group.propertyValueSet` is a new method that sets a given property on each Group member (thanks @rexrainbow) +* `Group.propertyValueInc` is a new method that adds an amount to a given property on each Group member (thanks @rexrainbow) +* `Group.setX` is a new method that sets the x coordinate on each Group member (thanks @rexrainbow) +* `Group.setY` is a new method that sets the y coordinate on each Group member (thanks @rexrainbow) +* `Group.setXY` is a new method that sets the x and y coordinate on each Group member (thanks @rexrainbow) +* `Group.incX` is a new method that increments the x coordinate on each Group member (thanks @rexrainbow) +* `Group.incY` is a new method that increments the y coordinate on each Group member (thanks @rexrainbow) +* `Group.incXY` is a new method that increments the x and y coordinate on each Group member (thanks @rexrainbow) +* `Group.shiftPosition` is a new method that iterates the Group members and shifts the position of each to the previous members position (thanks @rexrainbow) +* `Group.angle` is a new method that sets the angle property on each Group member (thanks @rexrainbow) +* `Group.rotate` is a new method that sets the rotation property on each Group member (thanks @rexrainbow) +* `Group.rotateAround` is a new method that rotates each Group member around the given point, by the given angle (thanks @rexrainbow) +* `Group.rotateAroundDistance` is a new method that rotates each Group member around the given point, by the given angle and distance (thanks @rexrainbow) +* `Group.setAlpha` is a new method that sets the alpha property on each Group member (thanks @rexrainbow) +* `Group.setTint` is a new method that sets the tint property on each Group member (thanks @rexrainbow) +* `Group.setOrigin` is a new method that sets the origin property on each Group member (thanks @rexrainbow) +* `Group.scaleX` is a new method that sets the x scale on each Group member (thanks @rexrainbow) +* `Group.scaleY` is a new method that sets the y scale on each Group member (thanks @rexrainbow) +* `Group.scaleXY` is a new method that sets the x and y scale on each Group member (thanks @rexrainbow) +* `Group.setBlendMode` is a new method that sets the blend mode on each Group member (thanks @rexrainbow) +* `Group.setHitArea` is a new method that passes all Group members to the Input Plugin to enable them for input (thanks @rexrainbow) +* `Group.shuffle` is a new method that shuffles all of the Group members in place (thanks @rexrainbow) +* `Group.setVisible` is a new method that sets the visible state on each Group member (thanks @rexrainbow) +* `WebAudioSoundManager.setAudioContext` is a new method that allows you to set the Sound Manager Audio Context to a different context instance. It will also disconnect and re-create the gain nodes on the new context. +* `Group.type` is a new property that holds a string-based name of the Game Object type, as with other GO's (thanks @samme) +* `Arade.Group.type` is a new property that holds a string-based name of the Game Object type, as with other GO's (thanks @samme) +* `Arcade.StaticGroup.type` is a new property that holds a string-based name of the Game Object type, as with other GO's (thanks @samme) +* `ArcadePhysics.overlapCirc` is a new method that allows you to return an array of all Arcade Physics bodies that overlap with the given circular area of the world. It can return either dynamic or static bodies, or a mixture of both (thanks @samme) + +### Updates + +* `Curve.getPoints` can now take an optional array as the 3rd parameter in which to store the points results (thanks @rexrainbow) +* `Line.arcLengthDivisions` now overrides the default Curve value and is set to 1 to optimize the amount of points returned for a Line curve (thanks @rexrainbow) +* `ArcadePhysics.closest` will now no longer ever return the source in the target results (thanks @samme) +* `ArcadePhysics.furthest` will now no longer ever return the source in the target results (thanks @samme) +* `RequestAnimationFrame.target` is a new property that controls the fps rate (in ms) when setTimeout is used (thanks @pavels) +* The `WebAudioSoundManager.unlock` method will now listen for `keydown` events in order to unlock the Audio Context, as well as touch and pointer events, making it more accessible (thanks Nick Tipping) +* The `requestAnimationFrame` polyfill no longer expects a Browserify environment and uses `window` through-out, it also no longer adds in the same as performance.now does. +* `BitmapText.getTextBounds` didn't reset the dirty flag, causing the `GetBitmapTextSize` function to be called every time the Bitmap Text was rendered. With enough text objects on-screen this could negatively impact performance. The flag is now reset every time the bounds are recalculated. + +### Bug Fixes + +* The Spine Plugin was not clearing down the resize event listener in WebGL, causing it to still fire even if the Scene was closed. Fix #4808 (thanks @RollinSafary) +* When a game is created with the HEADLESS renderer, `Game.destroy()` had no effect and the game kept on running. Now it destroys itself properly. Fix #4804 (thanks @samme) +* `DOM.GetScreenOrientation` was returning the wrong consts from the Scale Manager (thanks @jcyuan) +* When using `Input.enableDebug` on Game Objects it would not render the debug graphic correctly if the hit area had been offset. It now adjusts the debug correctly for all common hit-area geometry types. Fix #4722 (thanks @HaoboZ @Olliebrown) +* Light2D was not properly working for DynamicTilemapLayers due to a change in the way tilesets were stored, throwing an Uncaught TypeError at runtime. This is now handled correctly. Fix #4167 #4079 (thanks @koljakutschera @blackjack26 @kainage) +* `Input.dragDistanceThreshold` was not working correctly since 3.18, snapping to the wrong drag state unless the time threshold was also set. Fix #4667 (thanks @muliawanw @Olliebrown) +* `Tilemap.convertLayerToStatic` would throw an error when used multiple times, due to an error with the layer index count. Fix #4737 (thanks @Olliebrown @Vegita2) +* The `Tween` class now uses a cached MAX_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) +* The `StaggerBuilder` class now uses a cached MAX_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) +* The `Rectangle.FromPoints` function now uses a cached MIN_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) +* The `Video` class now uses a cached MIN_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) +* The `Path` class now uses a cached MIN_SAFE_INTEGER making it compatible with Internet Explorer (thanks @jronn) +* `Video.destroy` has been renamed to `Video.preDestroy`, so that it now destroys properly like all other Game Objects. Fix #4821 (thanks @rexrainbow) +* The Video Game Object will now check to see if the browser supports the `HTMLVideoElement` before creating one (thanks @jcyuan) +* The `DOM.GetScreenOrientation` functions would return out-dated consts (thanks @jcyuan) +* When calling `TileSprite.setTexture` or `setFrame`, if the new frame size didn't match the old one, the new fill pattern would become distorted and the `potWidth` and `potHeight` values would be incorrect. +* Timeline callbacks with extra parameters like `onStart` would miss the first parameter when the callback was invoked. Fix #4810 (thanks @samme) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@samme (for contributing loads of new Arcade Physics examples) @dranitski @jcyuan @RollinSafary @ilyaryabchinski @jsoref @jcyuan @ghclark2 + +## Version 3.20.1 - Fitoria - 15th October 2019 + +### Updates + +* The `remove-files-webpack-plugin` plugin has been moved to a devDependency (thanks @noseglid) + +### Bug Fixes + +* `UpdateList.shutdown` wasn't removing the Scene Update event listener, causing actions to be multiplied on Scene restart (such as animation playback). Fix #4799 (thanks @jronn) +* `Container.mask` wouldn't render in WebGL due to a change in the way child masks were handled. Container masking now works again as in 3.19. Fix #4803 (thanks @paulsymphony) +* `DynamicTilemapLayer.setCollision` would cause an `indexOf` error when trying to access the layer data. Fix #4800 (thanks @PavelMishin) +* `SceneManager.run` (and consequently `ScenePlugin.run`) was using an out-dated way of checking if a Scene was paused before trying to resume it, causing a Scene to be started again instead of resumed. It now uses the `Systems.isPaused` function instead. Fix #3931 (thanks @alexeymolchan) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@xSke + +## Version 3.20.0 - Fitoria - 11th October 2019 + +### Video Game Object + +This is a new Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, +or playing a video based on a given URL. Videos can be either local, or streamed: + +```javascript +preload () { + this.load.video('pixar', 'nemo.mp4'); +} + +create () { + this.add.video(400, 300, 'pixar'); +} +``` + +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 willl render +in-game with full transparency. + +You can also save a video to the Texture Manager, allowing other Game Objects to use it as their texture, +including using it as a sampler2D input for a shader. + +See the Video Game Object class for more details. Other Video related changes are as follows: + +* `Loader.FileTypes.VideoFile` is a new Video File Loader File Type, used for preloading videos as streams or blobs. +* `WebGLRenderer.createVideoTexture` is a new method that will create a WebGL Texture from the given Video Element. +* `WebGLRenderer.updateVideoTexture` is a new method that will update a WebGL Texture from the given Video Element. +* `TextureSource.isVideo` is a new boolean property that is set when the Texture Source is backed by an HTML Video Element. +* `Cache.video` is a new global cache that store loaded Video content. +* `Device.Video.h264Video` has been renamed to `Device.Video.h264` to keep it in-line with the Audio Device names. +* `Device.Video.hlsVideo` has been renamed to `Device.Video.hls` to keep it in-line with the Audio Device names. +* `Device.Video.mp4Video` has been renamed to `Device.Video.mp4` to keep it in-line with the Audio Device names. +* `Device.Video.oggVideo` has been renamed to `Device.Video.ogg` to keep it in-line with the Audio Device names. +* `Device.Video.vp9Video` has been renamed to `Device.Video.vp9` to keep it in-line with the Audio Device names. +* `Device.Video.webmVideo` has been renamed to `Device.Video.webm` to keep it in-line with the Audio Device names. + +### Spine Plugin + +* The Spine runtimes have been updated to 3.8. Please note that Spine runtimes are _not_ backwards compatible. Animations exported with Spine 3.7 (or earlier) will need re-exporting with 3.8 in order to work with the new runtimes. +* Fixed a bug with the binding of the Spine Plugin causing the GameObjectFactory to remain bound to the first instance of the plugin, causing Scene changes to result in blank Spine Game Objects. Fix #4716 (thanks @olilanz) +* Fixed a bug with the caching of the Spine Texture Atlases, causing shader errors when returning from one Scene to another with a cached Texture Atlas. +* The WebGL Scene Renderer is now only disposed if the Scene is destroyed, not just shut-down. +* The Spine Game Object will no longer set the default skin name to be 'default', it will leave the name empty. Fix #4764 (thanks @Jonchun @badlogic) +* Thanks to a fix inside the Container WebGLRenderer, a bug was crushed which involved multiple Containers in a Scene, with Spine objects, from causing run-time errors. Fix #4710 (thanks @nalgorry) +* Using `Loader.setPath` to define the Spine assets locations could error if trying to load multiple files from different folders. It will now retain the path state at the time of invocation, rather than during the load. +* When loading Spine files that used the same internal image file names, only the first file would successfully load. Now, all files load correctly. + +### Facebook Instant Games Plugin + +* Calling `showAd` or `showVideoAd` will now check to see if the ad has already been displayed, and skip it when iterating the ads array, allowing you to display an ad with the same Placement ID without preloading it again. Fix #4728 (thanks @NokFrt) +* Calling `gameStarted` in a game that doesn't load any assets would cause the error `{code: "INVALID_OPERATION", message: "Can not perform this operation before game start."}`. The plugin will now has a new internal method `gameStartedHandler` and will redirect the flow accordingly based on asset loading. Fix #4550 (thanks @bchee) +* The documentation for the `chooseContext` method has been fixed. Fix #4425 (thanks @krzysztof-grzybek) +* `Leaderboard.getConnectedScores` incorrectly specified two parameters, neither of which were used. Fix #4702 (thanks @NokFrt) +* `Leaderboard` extends Event Emitter, which was missing in the TypeScript defs. Fix #4703 (thanks @NokFrt) + +### Arcade Physics Updates + +@BenjaminDRichards and the GameFroot team contributed the following updates to Arcade Physics, which fixes 3 issues encountered when the framerate drops below 60 (technically, any time when multiple physics steps run per frame, so if physics FPS is above 60 this will also occur.) + +Issue 1: Friction starts to flip out. Objects on moving platforms get pushed ahead of the platform and "catch" on the leading edge. +Issue 2: Physics objects start to dip into the floor. In the "Before" demo, the camera is locked to the player, so this appears as the entire world starting to shake up and down. +Issue 3: When objects dip into the floor, their "rest velocity" is non-zero. This can affect debug and other logic. + +* `Body.prevFrame` is a new vector allowing a Body to distinguish between frame-length changes and step-length changes. Several steps may run for every frame, particularly when fps is low. +* `Body._reset` flag was removed and replaced it with a check of `Body.moves`. The flag only turned on when `moves` was true, and never turned off. +* Added a reset of `prev` in Arcade.Body#step. This fixes the friction issue. +* Stopped the `Body.postUpdate` method from setting `_dx`, `_dy`, and `prev`. They remain in the state they were at the end of the last physics step. This will affect the delta methods, which are documented to provide step-based data (not frame-based data); they now do so. However, because several steps may run per frame, you can't interrogate every step unless you're running functions based on physics events like collisions. You'll just see the latest step. This should partially balance out the extra load of resetting prev. +* Added a zero-out of stepsLastFrame in Arcade.World#postUpdate, which would otherwise never zero out and keep running at least one pass per frame. This should improve performance when frames can be skipped. +* Removed `blocked` checks from `TileCheckX` and `TileCheckY`. Originally, this prevented multiple checks when an object had come to rest on a floor. However, when multiple steps run per frame, the object will accelerate again, the floor won't stop it on steps 2+, and it will end the frame a short distance into the floor. Removing the blocked checks will fix the floor dip issue and the rest velocity issue. Although this opens up multiple checks, this is probably very rare: how many times does an object hit two different floors in a single frame? + +In combination these updates fix issues #4732 and #4672. My thanks to @BenjaminDRichards and @falifm. + +### New Features + +* `GameConfig.antialiasGL` is a new boolean that allows you to set the `antialias` property of the WebGL context during creation, without impacting any subsequent textures or the canvas CSS. +* `InteractiveObject.alwaysEnabled` is a new boolean that allows an interactive Game Object to always receive input events, even if it's invisible or won't render. +* `Bob.setTint` is a new method that allows you to set the tint of a Bob object within a Blitter. This is then used by the Blitter WebGL Renderer (thanks @rexrainbow) +* The `UpdateList` now emits two new events: 'add' and 'remove' when children are added and removed from it. Fix #3487 (thanks @hexus) +* The `Tilemap.setCollision` method has a new optional boolean parameter `updateLayer`. If set to `true`, it will update all of the collision settings of all tiles on the layer. If `false` it will skip doing this, which can be a huge performance boost in situations where the layer tiles haven't been modified and you're just changing collision flags. This is especially suitable for maps using procedural generated tilemaps, infinite tilemaps, multiplayer tilemaps, particularly large tilemaps (especially those dyanmic in nature) or who otherwise intend to index collisions before the tiles are loaded. This update also added the new parameter to the `SetCollision`, `SetCollisionBetween` and `DynamicTilemapLayer.setCollision` methods (thanks @tarsupin) +* `ArcadePhysics.Body.setBoundsRectangle` is a new method that allows you to set a custom bounds rectangle for any Body to use, rather than the World bounds, which is the default (thanks @francois-n-dream) +* `ArcadePhysics.Body.customBoundsRectangle` is a new property used for custom bounds collision (thanks @francois-n-dream) +* The Arcade Physics Group has a new config object property `customBoundsRectangle` which, if set, will set the custom world bounds for all Bodies that Group creates (thanks @francois-n-dream) +* `WebGLRenderer.createTexture2D` has a new optional parameter `flipY` which sets the `UNPACK_FLIP_Y_WEBGL` flag of the uploaded texture. +* `WebGLRenderer.canvasToTexture` has a new optional parameter `flipY` which sets the `UNPACK_FLIP_Y_WEBGL` flag of the uploaded texture. +* `WebGLRenderer.createCanvasTexture` is a new method that will create a WebGL Texture based on the given Canvas Element. +* `WebGLRenderer.updateCanvasTexture` is a new method that will update an existing WebGL Texture based on the given Canvas Element. +* `WebGLRenderer.createVideoTexture` is a new method that will create a WebGL Texture based on the given Video Element. +* `WebGLRenderer.updateVideoTexture` is a new method that will update an existing WebGL Texture based on the given Video Element. +* `TextureSource.flipY` is a new boolean that controls if the `UNPACK_FLIP_Y_WEBGL` flag is set when a WebGL Texture is uploaded. +* `TextureSource.setFlipY` is a new method that toggles the `TextureSource.flipY` property. + +### Updates + +* When calling `Shader.setRenderToTexture()` it will now draw the shader just once, immediately to the texture, to avoid the texture being blank for a single frame (thanks Kyle) +* The private `Shader._savedKey` property has been removed as it wasn't used anywhere internally. +* A `hasOwnProperty` check has been applied to the `SceneManager.createSceneFromObject` method when parsing additional properties in the `extend` object (thanks @halilcakar) +* The `Blitter.dirty` flag is no longer set if the render state of a Bob is changed to make it invisible (thanks @rexrainbow) +* `WebGLPipeline.addAttribute` will now automatically update the vertextComponentCount for you, without you having to do it manually any more (thanks @yhwh) +* `MultiFile` has three new internal properties: `baseURL`, `path` and `prefix` which allow them to retain the state of the loader at the time of creation, to be passed on to all child-files. Fix #4679. +* `LoaderPlugin` and `MultiFile` have a new private property `multiKeyIndex` which multi-files use and increment when batching sub-file loads. +* TileSprites will now throw a console warning if you try to use a RenderTexture or GLTexture as their frame source. Fix #4719 (thanks @pavel-shirobok) +* `TextureSource.isGLTexture` now checks if the browser supports `WebGLTexture` before checking to see if source is an instance of one. This should fix issues with Phaser in HEADLESS mode running under node / jsdom, or where WebGLTexture isn't present. Fix #4711 (thanks @tsphillips) +* `GameObject.ToJSON` will no longer output the `scaleMode` in the json because it's not a valid Game Object property. +* `TextureSource.setFilter` will now set the `scaleMode` to the given filter. +* `CanvasInterpolation` has updated the order of the CSS properties so that `crisp-edges` comes after the browser prefix versions. +* The `CanvasRenderer.scaleMode` property has been removed as it was never set or used internally. +* The `CanvasRenderer.currentScaleMode` property has been removed as it was never set or used internally. +* The `BuildGameObject` function will no longer set `scaleMode` because it's not a valid Game Object property. +* `CanvasRenderer.antialias` is a new property, populated by the game config property of the same name (or via the `pixelArt` property) that will tell the canvas renderer what to set image interpolation to during rendering of Sprites. +* `SetTransform` will now set the imageSmoothingEnabled context value based on the renderer and texture source scale mode. +* The Blitter Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. +* The Particle Emitter Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. +* The Static Tilemap Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. +* The Dynamic Tilemap Canvas Renderer will now respect the game config anti-alias / pixel art settings and render accordingly. +* All Game Objects that use the Canvas Set Transform function (which is most of them) will aos now respect the game config anti-alias / pixel art settings and render accordingly. This means you can now have properly scaled Bitmap Text, Text, Sprites, Render Textures, etc when pixel art is enabled in your game. Fix #4701 (thanks @agar3s) +* Containers are now able to set the alpha quadrant values (topLeft, topRight, bottomLeft and bottomRight) and have these passed onto children which are capable of supporting them, such as Sprites. Fix #4714 (thanks @MrcSnm) +* The `ProcessQueue` struct now extends Event Emitter and will emit `PROCESS_QUEUE_ADD_EVENT` when a new item is added to it. +* The `ProcessQueue` struct now extends Event Emitter and will emit `PROCESS_QUEUE_REMOVE_EVENT` when an item is removed from it. +* `ProcessQueue.removeAll` is a new method that will remove all active entries from the queue. +* `ProcessQueue.length` is a new property that returns the size of the active list. +* `UpdateList` now extends the `ProcessQueue` struct and uses all of its methods for list management, instead of doing it directly. This means private properties such as `UpdateList._list` no longer exist. It also fixes an issue re: memory management where list items would remain until the end of a Scene. Fix #4721 (thanks @darkgod6) +* `BaseSoundManager.forEachActiveSound` will now only invoke the callback if the sound actually exists and isn't pending removal. Fix #3383 (thanks @DouglasLapsley) +* `MouseManager.target` can now be defined as either a string or by passing an HTMLElement directly. Fix #4353 (thanks @BigZaphod) +* The `BasePlugin.boot` method has been removed and moved to `ScenePlugin.boot` as it's a Scene-level method only (thanks @samme) +* The `BasePlugin.scene` and `BasePlugin.systems` properties have been removed and are defined in `ScenePlugin`, as they are Scene-level properties only (thanks @samme) +* The `Tween.getValue` method has been updated so you can specify the index of the Tween Data to get the value of. Previously, it only returned the first TweenData from the data array, ignoring any subsequent properties or targets. Fix #4717 (thanks @chepe263) +* `WebGLRenderer.createTexture2D` has a new optional parameter `forceSize`, which will force the gl texture creation to use the dimensions passed to the method, instead of extracting them from the pixels object, if provided. +* The `GameObject.setTexture` method can now accept either a string, in which case it looks for the texture in the Texture Manager, or a Texture instance, in which case that instance is set as the Game Object's texture. +* `TextureManager.get` can now accept either a string-based key, or a Texture instance, as its parameter. +* `SceneManager.stop` and the matching `ScenePlugin.stop` now have an optional `data` parameter, which is passed to the Scene shutdown method. Fix #4510 (thanks @Olliebrown @GetsukenStudios) +* `Cameras.BaseCamera` is now exposed in the namespace, allowing you to access them directly (thanks @rexrainbow) +* Shaders have a new optional constructor parameter `textureData` which allows you to specify additional texture data, especially for NPOT textures (thanks @cristlee) +* `TouchManager.disableContextMenu` is a new method that will try to disable the context menu on touch devices, if the Game Config `disableContextMenu` is set. Previously, it only tried to do it for the Mouse Manager, but now does it for touch as well. Fix #4778 (thanks @simplewei) + +### Bug Fixes + +* `SpineCanvasPlugin.shutdown` would try to dispose of the `sceneRenderer`, but the property isn't set for Canvas. +* `ArcadePhysics.Body.checkWorldBounds` would incorrectly report as being on the World bounds if the `blocked.none` flag had been toggled elsewhere in the Body. It now only sets if it toggles a new internal flag (thanks Pablo) +* `RenderTexture.resize` wouldn't update the CanvasTexture width and height, causing the cal to draw or drawFrame to potentially distort the texture (thanks @yhwh) +* `InputPlugin.processDragMove` has been updated so that the resulting `dragX` and `dragY` values, sent to the event handler, now compensate for the scale of the Game Objects parent container, if inside of one. This means dragging a child of a scale Container will now still drag at 'full' speed. +* The RenderTextures `displayOrigin` values are now automatically updated if you call `setSize` on the Render Texture. Fix #4757 (thanks @rexrainbow) +* `onTouchStart`, `onTouchEnd` and `onTouchMove` will now check for `event.cancelable` before calling preventDefault on the touch event, fixing issues with "Ignored attempt to cancel a touchstart event with cancelable=false, for example because scrolling is in progress and cannot be interrupted." errors in some situations. Fix #4706 (thanks @MatthewAlner) +* `MatterPhysics.shutdown` could try to access properties that may have been previously removed during the Game.destroy process, causing a console error. It now checks properties before removing events from them (thanks @nagyv) +* `ArcadePhysics.Body.hitTest` would use CircleContains to do a hit test, which assumex x/y was the Circle center, but for a Body it's the top-left, causing the hit test to be off. Fix #4748 (thanks @funnisimo) +* `ArcadePhysics.World.separateCircle` has had the velocity scaling moved to after the angle is calculated, fixing a weird collision issue when `Body.bounce=0`. Also, if both bodies are movable, they now only offset by half the offset and use the center of the body for angle calculation, allowing for any offsets to be included. Fix #4751 (thanks @funnisimo @hizzd) +* `Tween.updateTo` would break out of the TweenData iteration as soon as it adjusted the first matching key, causing tweens acting on multiple targets to only update the first target. It now updates them all. Fix #4763 (thanks @RBrNx) +* The Container WebGLRenderer will now handle child mask batching properly, based on the renderers current mask. +* The Container WebGLRenderer will now handle child new type switching, allowing you to carry on with a batch of same-type Game Objects even if they're nested within Containers. Fix #4710 (thanks @nalgorry) +* `MultiAtlasFiles` that loaded their own external images would obtain incorrect path and URL values if the path had been changed by another file in the queue. They now retain the loader state and apply it to all child files during load. +* If more than one `MultiAtlasFile` used the same internal file name for its images, subsequent multi-atlases would fail to load. Fix #4330 (thanks @giviz) +* `MultiAtlasFiles` would incorrectly add the atlas JSON into the JSON cache, causing you to not be able to destroy and reload the texture using the same atlas key as before. Fix #4720 (thanks @giviz) +* `RenderTexture.fill` wasn't setting the camera up before drawing the fill rect, causing it to appear in the wrong place and the wrong size. Fix #4390 (thanks @Jerenaux) +* `DynamicBitmapText.setOrigin` wouldn't change the origin when using the Canvas Renderer, only in WebGL. It now sets the origin regardless of renderer. Fix #4108 (thanks @garethwhittaker) +* `DynamicBitmapText` wouldn't respect the multi-line alignment values when using the Canvas Renderer. It now uses them in the line calculations. +* `DynamicBitmapText` and `BitmapText` wouldn't render at the correct position when using scaled BitmapText and an origin. Fix #4054 (thanks @Aveyder) +* Incorrect lighting on batched Sprites. The lighting was not correct when batching several sprites with different rotations. Each sprite now uses its own `uInverseRotationMatrix` to compute the lighting correctly (thanks @gogoprog) +* Matter.js Body wasn't setting the part angles correctly in `Body.update` (thanks @Frozzy6) +* `ScaleManager.startFullscreen` now checks to see if the call returns a Promise, rather than checking if the browser supports them, before waiting for promise resolution. This fixes a runtime console warning in Microsoft Edge. Fix #4795 (thanks @maksdk) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@krzysztof-grzybek @NokFrt @r-onodera @colorcube @neon-dev @SavedByZero @arnekeller + +### Thanks + +Thank you to the following people for contributing ideas for new features to be added to Phaser 3. Because we've now started Phaser 4 development, I am closing off old feature requests that I personally will not work on for Phaser 3 itself. They may be considered for v4 and, of course, if someone from the community wishes to submit a PR to add them, I will be only too happy to look at that. So, if you want to get involved, filter the GitHub issues by the [Feature Request tag](https://github.com/photonstorm/phaser/issues?q=is%3Aissue+is%3Aopen+label%3A%22%F0%9F%92%96+Feature+Request%22) and dig in. In the meantime, thank you to the following people for suggesting features, even if they didn't make it this time around: + +@njt1982 @TheTrope @allanbreyes @alexandernst @Secretmapper @murteira @oktayacikalin @TadejZupancic @SBCGames @hadikcz @jcyuan @pinkkis @Aedalus @jestarray @BigZaphod @Secretmapper @francois-n-dream @G-Rath + +## Version 3.19.0 - Naofumi - 8th August 2019 + +### Tween Updates + +* All Tween classes and functions have 100% complete JSDocs :) +* `StaggerBuilder` is a new function that allows you to define a staggered tween property. For example, as part of a tween config: `delay: this.tweens.stagger(500)` would stagger the delay by 500ms for every target of the tween. You can also provide a range: `delay: this.tweens.stagger([ 500, 1000 ])` which is spread across all targets. Finally, you can provide a Stagger Config object as the second argument. This allows you to define a stagger grid, direction, starting value and more. Please see the API Docs and new Examples for further details. +* `Tween` now extends the Event Emitter class, allowing it to emit its own events and be listened to. +* `Tween.ACTIVE_EVENT` is a new event that is dispatched when a tween becomes active. Listen to it with `tween.on('active')`. +* `Tween.COMPLETE_EVENT` is a new event that is dispatched when a tween completes or is stopped. Listen to it with `tween.on('complete')`. +* `Tween.LOOP_EVENT` is a new event that is dispatched when a tween loops, after any loop delay expires. Listen to it with `tween.on('loop')`. +* `Tween.REPEAT_EVENT` is a new event that is dispatched when a tween property repeats, after any repeat delay expires. Listen to it with `tween.on('repeat')`. +* `Tween.START_EVENT` is a new event that is dispatched when a tween starts. Listen to it with `tween.on('start')`. +* `Tween.UPDATE_EVENT` is a new event that is dispatched when a tween property updates. Listen to it with `tween.on('update')`. +* `Tween.YOYO_EVENT` is a new event that is dispatched when a tween property yoyos, after any hold delay expires. Listen to it with `tween.on('yoyo')`. +* `Tween.onActive` is a new callback that is invoked the moment the Tween Manager brings the tween to life, even though it may not have yet started actively tweening anything due to delay settings. +* `Tween.onStart` is now only invoked when the Tween actually starts tweening a value. Previously, it was invoked as soon as the Tween Manager activated the Tween. This has been recoded and this action is now handled by the `onActive` callback. Fix #3330 (thanks @wtravO) +* `Tween.seek` has been rewritten so you can now seek to any point in the Tween, regardless of repeats, loops, delays and hold settings. Seeking will not invoke any callbacks or events during the seek. Fix #4409 (thanks @cristib84) +* You can now set `from` and `to` values for a property, i.e. `alpha: { from: 0, to: 1 }` which would set the alpha of the target to 0 and then tween it to 1 _after_ any delays have expired. Fix #4493 (thanks @BigZaphod) +* You can now set `start` and `to` values for a property, i.e. `alpha: { start: 0, to: 1 }` which would set the alpha of the target to 0 immediately, as soon as the Tween becomes active, and then tween it to 1 over the duration of the tween. +* You can now set `start`, `from` and `to` values for a property, i.e. `alpha: { start: 0, from: 0.5, to: 1 }` which would set the alpha of the target to 0 immediately, as soon as the Tween becomes active, then after any delays it would set the alpha to 0.5 and then tween it to 1 over the duration of the Tween. +* `Tween.hasStarted` is a new property that holds a flag signifying if the Tween has started or not. A Tween that has started is one that is actively tweening a property and not just in a delayed state. +* `Tween.startDelay` is a new property that is set during the Tween init to hold the shortest possible time before the Tween will start tweening a value. It is decreased each update until it hits zero, after which the `onStart` callback is invoked. +* `Tween.init` and `Tween.play` have been rewritten so they are not run multiple times when a Tween is paused before playback, or is part of a Timeline. This didn't cause any problems previously, but it was a redundant duplication of calls. +* `Tween.onLoop` will now be invoked _after_ the `loopDelay` has expired, if any was set. +* `Tween.onRepeat` will now be invoked _after_ the `repeatDelay` has expired, if any was set. +* `easeParams` would be ignored for tweens that _didn't_ use a string for the ease function name. Fix #3826 (thanks @SBCGames) +* You can now specify `easeParams` for any custom easing function you wish to use. Fix #3826 (thanks @SBCGames) +* All changes to `Tween.state` are now set _before_ any events or callbacks, allowing you to modify the state of the Tween in those handlers (thanks @Cudabear) +* `Tween.dispatchTweenEvent` is a new internal method that handles dispatching the new Tween Events and callbacks. This consolidates a lot of duplicate code into a single method. +* `Tween.dispatchTweenDataEvent` is a new internal method that handles dispatching the new TweenData Events and callbacks. This consolidates a lot of duplicate code into a single method. +* `Tween.isSeeking` is a new internal boolean flag that is used to keep track of the seek progress of a Tween. +* `Timeline.onLoop` will now be invoked _after_ the `loopDelay` has expired, if any was set. +* `Timeline.onComplete` will now be invoked _after_ the `completeDelay` has expired, if any was set. +* All changes to `Timeline.state` are now set _before_ any events or callbacks, allowing you to modify the state of the Timeline in those handlers. +* The `TIMELINE_LOOP_EVENT` has had the `loopCounter` argument removed from it. It didn't actually send the number of times the Timeline had looped (it actually sent the total remaining). +* When a TweenData completes it will now set the `current` property to be exactly either `start` or `end` depending on playback direction. +* When a TweenData completes it will set the exact `start` or `end` value into the target property. +* `TweenData` has a new function signature, with the new `index` and `getActive`arguments added to it. `TweenBuilder` has been updated to set these, but if you create any TweenData objects directly, use the new signature. +* `TweenData.getActiveValue` is a new property that, if not null, returns a value to immediately sets the property value to on activation. +* `GetEaseFunction`, and by extension anything that uses it, such as setting the ease for a Tween, will now accept a variety of input strings as valid. You can now use lower-case, such as `back`, and omit the 'ease' part of the direction, such as `back.in` or `back.inout`. +* The signature of `getStart` and `getEnd` custom property functions has changed to `(target, key, value, targetIndex, totalTargets, tween)`, previously it was just `(target, key, value)`. Custom functions don't need to change as the new arguments are in addition to those sent previously. +* The signature of the LoadValue generator functions (such as `delay` and `repeat`) has changed to `(target, key, value, targetIndex, totalTargets, tween)` to match those of the custom property functions. If you used a custom generator function for your Tween configs you'll need to modify the signature to the new one. +* Tweens created via `TweenManager.create` wouldn't start when `Tween.play` was called without first making them active manually. They now start automatically. Fix #4632 (thanks @mikewesthad) + +### Spine Updates + +The Spine Plugin is now 100% complete. It has been updated to use the Spine 3.7 Runtimes. Improvements have been made across the entire plugin, including proper batched rendering support in WebGL, cleaner skin and slot functions and lots and lots of updates. It's fully documented and there are lots of examples to be found. The following legacy bugs have also been fixed: + +* Adding Spine to physics causes position to become NaN. Fix #4501 (thanks @hizzd) +* Destroying a Phaser Game instance and then re-creating it would cause an error trying to re-create Spine Game Objects ("Cannot read property get of null"). Fix #4532 (thanks @Alex-Badea) +* Rendering a Spine object when a Camera has `renderToTexture` enabled on it would cause the object to be vertically flipped. It now renders correctly in both cases. Fix #4647 (thanks @probt) + +### New Features + +* `Shader.setRenderToTexture` is a new method that will redirect the Shader to render to its own framebuffer / WebGLTexture instead of to the display list. This allows you to use the output of the shader as an input for another shader, by mapping a sampler2D uniform to it. It also allows you to save the Shader to the Texture Manager, allowing you to use it as a texture for any other texture based Game Object such as a Sprite. +* `Shader.setSampler2DBuffer` is a new method that allows you to pass a WebGLTexture directly into a Shader as a sampler2D uniform, such as when linking shaders together as buffers for each other. +* `Shader.renderToTexture` is a new property flag that is set if you set the Shader to render to a texture. +* `Shader.framebuffer` is a new property that contains a WebGLFramebuffer reference which is set if you set the Shader to render to a texture. +* `Shader.glTexture` is a new property that contains a WebGLTexture reference which is set if you set the Shader to render to a texture. +* `Shader.texture` is a new property that contains a Phaser Texture reference which is set if you set the Shader to save to the Texture Manager. +* `TextureManager.addGLTexture` is a new method that allows you to add a WebGLTexture directly into the Texture Manager, saved under the given key. +* `TextureSource.isGLTexture` is a new boolean property that reflects if the data backing the underlying Texture Source is a WebGLTexture or not. +* `TextureTintPipeline.batchSprite` will now flip the UV if the TextureSource comes from a GLTexture. +* `Math.ToXY` is a new mini function that will take a given index and return a Vector2 containing the x and y coordinates of that index within a grid. +* `RenderTexture.glTexture` is a new property that holds a reference to the WebGL Texture being used by the Render Texture. Useful for passing to a shader as a sampler2D. +* `GroupCreateConfig.quantity` - when creating a Group using a config object you can now use the optional property `quantity` to set the number of objects to be created. Use this for quickly creating groups of single frame objects that don't need the advanced capabilities of `frameQuantity` and `repeat`. +* `Pointer.locked` is a new read-only property that indicates if the pointer has been Pointer Locked, or not, via the Pointer Lock API. +* `WebGLRenderer.snapshotFramebuffer`, and the corresponding utility function `WebGLSnapshot`, allows you to take a snapshot of a given WebGL framebuffer, such as the one used by a Render Texture or Shader, and either get a single pixel from it as a Color value, or get an area of it as an Image object, which can then optionally be saved to the Texture Manager for use by Game Object textures. +* `CanvasRenderer.snapshotCanvas` allows you to take a snapshot of a given Canvas object, such as the one used by a Render Texture, and either get a single pixel from it as a Color value, or get an area of it as an Image object, which can then optionally be saved to the Texture Manager for use by Game Object textures. +* `RenderTexture.snapshot` is a new method that will take a snapshot of the whole current state of the Render Texture and return it as an Image object, which could then be saved to the Texture Manager if needed. +* `RenderTexture.snapshotArea` is a new method that will take a snapshot of an area of a Render Texture and return it as an Image object, which could then be saved to the Texture Manager if needed. +* `RenderTexture.snapshotPixel` is a new method that will take extract a single pixel color value from a Render Texture and return it as a Color object. +* The `SnapshotState` object has three new properties: `isFramebuffer` boolean and `bufferWidth` and `bufferHeight` integers. +* `Game.CONTEXT_LOST_EVENT` is a new event that is dispatched by the Game instance when the WebGL Renderer webgl context is lost. Use this instead of the old 'lostContextCallbacks' for cleaner context handling. +* `Game.CONTEXT_RESTORED_EVENT` is a new event that is dispatched by the Game instance when the WebGL Renderer webgl context is restored. Use this instead of the old 'restoredContextCallbacks' for cleaner context handling. +* `WebGLRenderer.currentType` contains the type of the Game Object currently being rendered. +* `WebGLRenderer.newType` is a boolean that indicates if the current Game Object has a new type, i.e. different to the previous one in the display list. +* `WebGLRenderer.nextTypeMatch` is a boolean that indicates if the _next_ Game Object in the display list has the same type as the one being currently rendered. This allows you to build batching into separated Game Objects. +* `PluginManager.removeGameObject` is a new method that allows you to de-register custom Game Object types from the global Game Object Factory and/or Creator. Useful for when custom plugins are destroyed and need to clean-up after themselves. +* `GEOM_CONST` is a new constants object that contains the different types of Geometry Objects, such as `RECTANGLE` and `CIRCLE`. +* `Circle.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `Ellipse.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `Line.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `Point.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `Polygon.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `Rectangle.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `Triangle.type` is a new property containing the shapes geometry type, which can be used for quick type comparisons. +* `InputPlugin.enableDebug` is a new method that will create a debug shape for the given Game Objects hit area. This allows you to quickly check the size and placement of an input hit area. You can customzie the shape outline color. The debug shape will automatically track the Game Object to which it is bound. +* `InputPlugion.removeDebug` will remove a Debug Input Shape from the given Game Object and destroy it. +* `Pointer.updateWorldPoint` is a new method that takes a Camera and then updates the Pointers `worldX` and `worldY` values based on the cameras transform (thanks @Nick-lab) +* `ScaleManager._resetZoom` is a new internal flag that is set when the game zoom factor changes. +* `Texture.remove` is a new method that allows you to remove a Frame from a Texture based on its name. Fix #4460 (thanks @BigZaphod) + +### Updates + +* When calling `setHitArea` and not providing a shape (i.e. a texture based hit area), it will now set `customHitArea` to `false` by default (thanks @rexrainbow) +* The Shader will no longer set uniforms if the values are `null`, saving on GL ops. +* The Animation Manager will now emit a console warning if you try and play an animation on a Sprite that doesn't exist. +* The Animation component will no longer start an animation on a Sprite if the animation doesn't exist. Previously it would throw an error saying "Unable to read the property getFirstTick of null". +* `InputManager.onPointerLockChange` is a new method that handles pointer lock change events and dispatches the lock event. +* `CanvasTexture` has been added to the `Textures` namespace so it can be created without needing to import it. The correct way to create a `CanvasTexture` is via the Texture Manager, but you can now do it directly if required. Fix #4651 (thanks @Jugacu) +* The `SmoothedKeyControl` minimum zoom a Camera can go to is now 0.001. Previously it was 0.1. This is to make it match the minimum zoom a Base Camera can go to. Fix #4649 (thanks @giviz) +* `WebGLRenderer.lostContextCallbacks` and the `onContextLost` method have been removed. Please use the new `CONTEXT_LOST` event instead. +* `WebGLRenderer.restoredContextCallbacks` and the `onContextRestored` method have been removed. Please use the new `CONTEXT_RESTORED` event instead. +* `TextureManager.getBase64` will now emit a console warning if you try to get a base64 from a non-image based texture, such as a WebGL Texture. +* The `WebAudioSoundManager` will now remove the document touch handlers even if the Promise fails, preventing it from throwing a rejection handler error. +* `GameObjectFactory.remove` is a new static function that will remove a custom Game Object factory type. +* `GameObjectCreator.remove` is a new static function that will remove a custom Game Object creator type. +* `CanvasTexture.getPixels` now defaults to 0x0 by width x height as the default area, allowing you to call the method with no arguments to get all the pixels for the canvas. +* `CreateDOMContainer` will now use `div.style.cssText` to set the inline styles of the container, so it now works on IE11. Fix #4674 (thanks @DanLiamco) +* `TransformMatrix.rotation` now returns the properly normalized rotation value. +* `PhysicsEditorParser` has now been exposed under the `Phaser.Physics.Matter` namespace, so you can call methods on it directly. +* Calling `CanvasTexture.update` will now automatically call `refresh` if running under WebGL. This happens for both `draw` and `drawFrame`, meaning you no longer need to remember to call `refresh` after drawing to a Canvas Texture in WebGL, keeping it consistent with the Canvas renderer. +* `Frame.destroy` will now null the Frames reference to its parent texture, glTexture and clear the data and customData objects. +* The Container renderer functions will now read the childs `alpha` property, instead of `_alpha`, allowing it to work with more variety of custom children. + +### Bug Fixes + +* The Scale Manager would throw the error 'TypeError: this.removeFullscreenTarget is not a function' when entering full-screen mode. It would still enter fullscreen, but the error would appear in the console. Fix #4605 (thanks @darklightcode) +* `Tilemap.renderDebug` was calling out-dated Graphics API methods, which would cause the debug to fail (thanks @Fabadiculous) +* The `Matter.Factory.constraint`, `joint` and `worldConstraint` methods wouldn't allow a zero length constraint to be created due to a falsey check of the length argument. You can now set length to be any value, including zero, or leave it undefined to have it automatically calculated (thanks @olilanz) +* `Pointer.getDuration` would return a negative / static value on desktop, or NaN on mobile, because the base time wasn't being pulled in from the Input Manager properly. Fix #4612 (thanks @BobtheUltimateProgrammer) +* `Pointer.downTime`, `Pointer.upTime` and `Pointer.moveTime` would be set to NaN on mobile browsers where Touch.timeStamp didn't exist. Fix #4612 (thanks @BobtheUltimateProgrammer) +* `WebGLRenderer.setScissor` will default the `drawingBufferHeight` if no argument is provided, stopping NaN scissor heights. +* If you called `Scene.destroy` within a Game Object `pointerdown` or `pointerup` handler, it would cause the error "Cannot read property 'game' of null" if the event wasn't cancelled in your handler. It now checks if the manager is still there before accessing its property. Fix #4436 (thanks @jcyuan) +* The `Arc / Circle` Game Object wasn't rendering centered correctly in WebGL due to an issue in a previous size related commit, it would be half a radius off. Fix #4620 (thanks @CipSoft-Components @rexrainbow) +* Destroying a Scene in HEADLESS mode would throw an error as it tried to access the gl renderer in the Camera class. Fix #4467 (thanks @AndreaBoeAbrahamsen @samme) +* `Tilemap.createFromObjects` would ignore the `scene` argument passed in to the method. It's now used (thanks @samme) +* Fixed a bug in the WebGL and Canvas Renderers where a Sprite with a `flipX` or `flipY` value set would render the offset frames slightly out of place, causing the animation to appear jittery. Also, the sprite would be out of place by its origin. Fix #4636 #3813 (thanks @jronn @B3L7) +* Animations with custom pivots, like those created in Texture Packer with the pivot option enabled, would be mis-aligned if flipped. They now render in the correct position, regardless of scale or flip on either axis. Fix #4155 (thanks @Zax37) +* Removing a frame from a 2 frame animation would cause an error when a Sprite using that animation next tried to render. Fix #4621 (thanks @orlicgms) +* Calling `Animation.setRepeat()` wouldn't reset the `repeatCounter` properly, causing Sprite bound animation instances to fail to change their repeat rate. Fix #4553 (thanks @SavedByZero) +* The `UpdateList.remove` method wouldn't flag the Game Object for removal properly if it was active. It now checks that the Game Object is in the current update list and hasn't already been inserted into the 'pending removal' list before flagging it. Fix #4544 (thanks @jcyuan) +* `DynamicTilemapLayer.destroy` will now no longer run its destroy sequence again if it has already been run once. Fix #4634 (thanks @CipSoft-Components) +* `StaticTilemapLayer.destroy` will now no longer run its destroy sequence again if it has already been run once. +* `Shader.uniforms` now uses Extend instead of Clone to perform a deep object copy, instead of a shallow one, avoiding multiple instances of the same shader sharing uniforms. Fix #4641 (thanks @davidmball) +* Calling `input.mouse.requestPointerLock()` will no longer throw an error about being unable to push to the Input Manager events queue. +* The `POINTERLOCK_CHANGE` event is now dispatched by the Input Manager again. +* The `Pointer.movementX` and `Pointer.movementY` properties are now taken directly from the DOM pointer event values, if the pointer is locked, and no longer incremental. Fix #4611 (thanks @davidmball) +* The `Pointer.velocity` and `Pointer.midPoint` values are now updated every frame. Based on the `motionFactor` setting they are smoothed towards zero, for velocity, and the pointer position for the mid point. This now happens regardless if the Pointer moves or not, which is how it was originally intended to behave. +* The `DESTROY` event hook wasn't removed from Group children when destroying the Group and `destroyChildren` was set to false. Now, the hook is removed regardless (thanks @rexrainbow) +* The WebGL Lost and Restored Context callbacks were never removed, which could cause them to hold onto stale references. Fix #3610 (thanks @Twilrom) +* `Origin.updateDisplayOrigin` no longer applies a Math.floor to the display origins, allowing you to have a 0.x origin for a Game Object that only has a width or height of 1. This fixes issues with things like 1x1 rectangles displaying incorrectly during rendering. Fix #4126 (thanks @rexrainbow) +* `InputManager.resetCursor` will now check if the canvas element still exists before resetting the cursor on it. Fix #4662 (thanks @fromnowhereuser) +* It was not possible to set the zoom value of the Scale Manager back to 1 again, having changed it to a different value. Fix #4633 (thanks @lgibson02 @BinaryMoon) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@vacarsu @KennethGomez @samme @ldd @Jazcash @jcyuan @LearningCode2023 @PhaserEditor2D + +## Version 3.18.1 - Raphtalia - 20th June 2019 + +### Bug Fixes + +* `InputManager.preRender` didn't get the `time` property correctly, causing input plugin methods that relied on it to fail. +* `KeyboardPlugin.time` wasn't being set to the correct value, causing `checkDown` to fail constantly. + +## Version 3.18.0 - Raphtalia - 19th June 2019 + +### Input System Changes + +#### Mouse Wheel Support + +3.18 now includes native support for reading mouse wheel events. + +* `POINTER_WHEEL` is a new event dispatched by the Input Plugin allowing you to listen for global wheel events. +* `GAMEOBJECT_WHEEL` is a new event dispatched by the Input Plugin allowing you to listen for global wheel events over all interactive Game Objects in a Scene. +* `GAMEOBJECT_POINTER_WHEEL` is a new event dispatched by a Game Object allowing you to listen for wheel events specifically on that Game Object. +* `Pointer.deltaX` is a new property that holds the horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. +* `Pointer.deltaY` is a new property that holds the vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. +* `Pointer.deltaZ` is a new property that holds the z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. +* `Pointer.wheel` is a new internal method that handles the wheel event. +* `InputManager.onMouseWheel` is a new internal method that handles processing the wheel event. +* `InputManager.processWheelEvent` is a new internal method that handles processing the wheel event sent by the Input Manager. + +#### Button Released Support + +* `Pointer.button` is a new property that indicates which button was pressed, or released, on the pointer during the most recent event. It is only set during `up` and `down` events and is always 0 for Touch inputs. +* `Pointer.leftButtonReleased` is a new method that returns `true` if it was the left mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. +* `Pointer.rightButtonReleased` is a new method that returns `true` if it was the right mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released (thanks @BobtheUltimateProgrammer) +* `Pointer.middleButtonReleased` is a new method that returns `true` if it was the middle mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. +* `Pointer.backButtonReleased` is a new method that returns `true` if it was the back mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. +* `Pointer.forwardButtonReleased` is a new method that returns `true` if it was the forward mouse button that was just released. This can be checked in a `pointerup` event handler to find out which button was released. + +#### Input System Bug Fixes + +* Calling `setPollAlways()` would cause the `'pointerdown'` event to fire multiple times. Fix #4541 (thanks @Neyromantik) +* The pointer events were intermittently not registered, causing `pointerup` to often fail. Fix #4538 (thanks @paulsymphony) +* Due to a regression in 3.16 the drag events were not performing as fast as before, causing drags to feel lagged. Fix #4500 (thanks @aliblong) +* The Touch Manager will now listen for Touch Cancel events on the Window object (if `inputWindowEvents` is enabled in the game config, which it is by default). This allows it to prevent touch cancel actions, like opening the dock on iOS, from causing genuinely active pointers to enter an active locked state. +* Over and Out events now work for any number of pointers in multi-touch environments, not just the first touch pointer registered. They also now fire correctly on touch start and touch end / cancel events. +* If you enable a Game Object for drag and place it inside a rotated Container (of any depth), the `dragX` and `dragY` values sent to the `drag` callback didn't factor the rotation in, so you had to do it manually. This is now done automatically, so the values account for parent rotation before being sent to the event handler. Fix #4437 (thanks @aliblong) + +#### Input System API Changes + +The old 'input queue' legacy system, which was deprecated in 3.16, has been removed entirely in order to tidy-up the API and keep input events consistent. This means the following changes: + +* Removed the `inputQueue` Game config property. +* Removed the `useQueue`, `queue` and `_updatedThisFrame` properties from the Input Manager. +* Removed the `legacyUpdate` and `update` methods from the Input Manager. +* Removed the `ignoreEvents` property as this should now be handled on a per-event basis. +* The Input Manager no longer listens for the `GameEvents.POST_STEP` event. +* The following Input Manager methods are no longer required so have been removed: `startPointer`, `updatePointer`, `stopPointer` and `cancelPointer`. + +As a result, all of the following Input Manager methods have been renamed: + +* `queueTouchStart` is now called `onTouchStart` and invoked by the Touch Manager. +* `queueTouchMove` is now called `onTouchMove` and invoked by the Touch Manager. +* `queueTouchEnd` is now called `onTouchEnd` and invoked by the Touch Manager. +* `queueTouchCancel` is now called `onTouchCancel` and invoked by the Touch Manager. +* `queueMouseDown` is now called `onMouseDown` and invoked by the Mouse Manager. +* `queueMouseMove` is now called `onMouseMove` and invoked by the Mouse Manager. +* `queueMouseUp` is now called `onMouseUp` and invoked by the Mouse Manager. + +Each of these handlers used to check the `enabled` state of the Input Manager, but this now handled directly in the Touch and Mouse Managers instead, leading to less branching and cleaner tests. They also all used to run an IIFE that updated motion on the changed pointers array, but this is now handled directly in the event handler, allowing it to be removed from here. + +Because the legacy queue mode is gone, there is no longer any need for the DOM Callbacks: + +* Removed the `_hasUpCallback`, `_hasDownCallback` and `_hasMoveCallback` properties from the Input Manager +* Removed the `processDomCallbacks`, `addDownCallback`, `addUpCallback`, `addMoveCallback`, `domCallbacks`, `addDownCallback`, `addUpCallback` and `addMoveCallback` methods. + +Also, CSS cursors can now be set directly: + +* Cursors are now set and reset immediately on the canvas, leading to the removal of `_setCursor` and `_customCursor` properties. + +The following changes took place in the Input Plugin class: + +* The method `processDragEvents` has been removed as it's now split across smaller, more explicit methods. +* `processDragDownEvent` is a new method that handles a down event for drag enabled Game Objects. +* `processDragMoveEvent` is a new method that handles a move event for drag enabled Game Objects. +* `processDragUpEvent` is a new method that handles an up event for drag enabled Game Objects. +* `processDragStartList` is a new internal method that builds a drag list for a pointer. +* `processDragThresholdEvent` is a new internal method that tests when a pointer with drag thresholds can drag. +* `processOverEvents` is a new internal method that handles when a touch pointer starts and checks for over events. +* `processOutEvents` is a new internal method that handles when a touch pointer stops and checks for out events. + +The following changes took place in the Pointer class: + +* `Pointer.dirty` has been removed as it's no longer required. +* `Pointer.justDown` has been removed as it's not used internally and makes no sense under the DOM event system. +* `Pointer.justUp` has been removed as it's not used internally and makes no sense under the DOM event system. +* `Pointer.justMoved` has been removed as it's not used internally and makes no sense under the DOM event system. +* The `Pointer.reset` method has been removed as it's no longer required internally. +* `Pointer.touchstart` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). +* `Pointer.touchmove` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). +* `Pointer.touchend` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). +* `Pointer.touchcancel` now has two arguments, the Touch List entry and the Touch Event. The full Touch Event is now stored in `Pointer.event` (instead of the Touch List entry). + +### New Features + +* `Matter.Factory.velocity` is a new method that allows you to set the velocity on a Matter Body directly. +* `Matter.Factory.angularVelocity` is a new method that allows you to set the angular velocity on a Matter Body directly. +* `Matter.Factory.force` is a new method that allows you to apply a force from a world position on a Matter Body directly. +* `GetBounds.getTopCenter` is a new method that will return the top-center point from the bounds of a Game Object. +* `GetBounds.getBottomCenter` is a new method that will return the bottom-center point from the bounds of a Game Object. +* `GetBounds.getLeftCenter` is a new method that will return the left-center point from the bounds of a Game Object. +* `GetBounds.getRightCenter` is a new method that will return the right-center point from the bounds of a Game Object. +* You can now create a desynchronized 2D or WebGL canvas by setting the Game Config property `desynchronized` to `true` (the default is `false`). For more details about what this means see https://developers.google.com/web/updates/2019/05/desynchronized. +* The CanvasRenderer can now use the `transparent` Game Config property in order to tell the browser an opaque background is in use, leading to faster rendering in a 2D context. +* `GameObject.scale` is a new property, that exists as part of the Transform component, that allows you to set the horizontal and vertical scale of a Game Object via a setter, rather than using the `setScale` method. This is handy for uniformly scaling objects via tweens, for example. +* `Base64ToArrayBuffer` is a new utility function that will convert a base64 string into an ArrayBuffer. It works with plain base64 strings, or those with data uri headers attached to them. The resulting ArrayBuffer can be fed to any suitable function that may need it, such as audio decoding. +* `ArrayBufferToBase64` is a new utility function that converts an ArrayBuffer into a base64 string. You can also optionally included a media type, such as `image/jpeg` which will result in a data uri being returned instead of a plain base64 string. +*`WebAudioSoundManager.decodeAudio` is a new method that allows you to decode audio data into a format ready for playback and stored in the audio cache. The audio data can be provided as an ArrayBuffer, a base64 string or a data uri. Listen for the events to know when the data is ready for use. +* `Phaser.Sound.Events#DECODED` is a new event emitted by the Web Audio Sound Manager when it has finished decoding audio data. +* `Phaser.Sound.Events#DECODED_ALL` is a new event emitted by the Web Audio Sound Manager when it has finished decoding all of the audio data files passed to the `decodeAudio` method. +* `Phaser.Utils.Objects.Pick` is a new function that will take an object and an array of keys and return a new object containing just the keys provided in the array. +* `Text.align` and `Text.setAlign` can now accept `justify` as a type. It will apply basic justification to multi-line text, adding in extra spaces in order to justify the content. Fix #4291 (thanks @andrewbaranov @Donerkebap13 @dude78GH) +* `Arcade.Events.WORLD_STEP` is a new event you can listen to. It is emitted by the Arcade Physics World every time the world steps once. It is emitted _after_ the bodies and colliders have been updated. Fix #4289 (thanks @fant0m) + +### Updates + +* `Zones` will now use the new `customHitArea` property introduced in 3.17 to avoid their hit areas from being resized if you specified your own custom hit area (thanks @rexrainbow) +* The default `BaseShader` vertex shader has a new uniform `uResolution` which is set during the Shader init and load to be the size of the Game Object to which the shader is bound. +* The default `BaseShader` vertex shader will now set the `fragCoord` varying to be the Game Object height minus the y inPosition. This will give the correct y axis in the fragment shader, causing 'inverted' shaders to display normally when using the default vertex code. +* There was some test code left in the `DOMElementCSSRenderer` file that caused `getBoundingClientRect` to be called every render. This has been removed, which increases performance significantly for DOM heavy games. +* The `TimeStep` will no longer set its `frame` property to zero in the `resetDelta` method. Instead, this property is incremented every step, no matter what, giving an accurate indication of exactly which frame something happened on internally. +* The `TimeStep.step` method no longer uses the time value passed to the raf callback, as it's not actually the current point in time, but rather the time that the main thread began at. Which doesn't help if we're comparing it to event timestamps. +* `TimeStep.now` is a new property that holds the exact `performance.now` value, as set at the start of the current game step. +* `Matter.Factory.fromVertices` can now take a vertices path string as its `vertexSets` argument, as well as an array of vertices. +* `GetBounds.prepareBoundsOutput` is a new private method that handles processing the output point. All of the bounds methods now use this, allowing us to remove a lot of duplicated code. +* The PluginManager will now display a console warning if it skips installing a plugin (during boot) because the plugin value is missing or empty (thanks @samme) +* When creating a Matter Constraint via the Factory you can now optionally provide a `length`. If not given, it will determine the length automatically from the position of the two bodies. +* When creating a Matter Game Object you can now pass in a pre-created Matter body instead of a config object. +* When Debug Draw is enabled for Arcade Physics it will now use `Graphics.defaultStrokeWidth` to drawn the body with, this makes static bodies consistent with dynamic ones (thanks @samme) +* `Group.name` is a new property that allows you to set a name for a Group, just like you can with all other Game Objects. Phaser itself doesn't use this, it's there for you to take advantage of (thanks @samme) +* Calling `ScaleManager.setGameSize` will now adjust the size of the canvas element as well. Fix #4482 (thanks @sudhirquestai) +* `Scale.Events.RESIZE` now sends two new arguments to the handler: `previousWidth` and `previousHeight`. If, and only if, the Game Size has changed, these arguments contain the previous size, before the change took place. +* The Camera Manager has a new method `onSize` which is invoked by handling the Scale Manager `RESIZE` event. When it receives it, it will iterate the cameras it manages. If the camera _doesn't_ have a custom offset and _is_ the size of the game, then it will be automatically resized for you. This means you no longer need to call `this.cameras.resize(width, height)` from within your own resize handler, although you can still do so if you wish, as that will resize _every_ Camera being managed to the new size, instead of just 'full size' cameras. +* `Graphics.translate` has been renamed to `Graphics.translateCanvas` to make it clearer what it's actually translating (i.e. the drawing buffer, not the Graphics object itself) +* `Graphics.scale` has been renamed to `Graphics.scaleCanvas` to make it clearer what it's actually scaling (i.e. the drawing buffer, not the Graphics object itself) +* `Graphics.rotate` has been renamed to `Graphics.rotateCanvas` to make it clearer what it's actually rotating (i.e. the drawing buffer, not the Graphics object itself) +* The `width` and `height` of an Arc / Circle Shape Game Object is now set to be the diameter of the arc, not the radius (thanks @rexrainbow) +* `LineStyleCanvas` now takes an `altColor` argument which is used to override the context color. +* `LineStyleCanvas` now takes an `altAlpha` argument which is used to override the context alpha. +* `FillStyleCanvas` now takes an `altAlpha` argument which is used to override the context alpha. +* `StaticPhysicsGroup` can now take a `classType` property in its Group Config and will use the value of it, rather than override it. If none is provided it'll default to `ArcadeSprite`. Fix #4401 (thanks @Legomite) +* `Phaser.Tilemaps.Parsers.Tiled` used to run the static function `ParseJSONTiled`. `Parsers.Tiled` is now just a namespace, so access the function within it: `Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled`. +* `Phaser.Tilemaps.Parsers.Impact` used to run the static function `ParseWeltmeister`. `Parsers.Impact` is now just a namespace, so access the function within it: `Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister`. +* `Phaser.Tilemaps.Parsers.Tiled.AssignTileProperties` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.Base64Decode` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.BuildTilesetIndex` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseGID` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseImageLayers` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseObject` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseObjectLayers` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseTileLayers` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseTilesets` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.ParseTilesets` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Impact.ParseTileLayers` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Impact.ParseTilesets` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister` is now a public static function, available to be called directly. +* `Phaser.Tilemaps.Parsers.Tiled.Pick` has been removed. It is now available under `Phaser.Utils.Objects.Pick`, which is a more logical place for it. +* You can now call `this.scene.remove` at the end of a Scene's `create` method without it throwing an error. Why you'd ever want to do this is beyond me, but you now can (thanks @samme) +* The `Arcade.StaticBody.setSize` arguments have changed from `(width, height, offsetX, offsetY)` to `(width, height, center)`. They now match Dynamic Body setSize and the Size Component method (thanks @samme) +* When enabling Arcade Physics Body debug it will now draw only the faces marked for collision, allowing you to easily see if a face is disabled or not (thanks @BdR76) +* `Transform.getParentRotation` is a new method available to all GameObjects that will return the sum total rotation of all of the Game Objects parent Containers, if it has any. +* `Tween.restart` now sets the Tween properties `elapsed`, `progress`, `totalElapsed` and `totalProgress` to zero when called, rather than adding to existing values should the tween already be running. +* `ArcadePhysics.Body.resetFlags` is a new method that prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. +* `ArcadePhysics.Body.preUpdate` has two new arguments `willStep` and `delta`. If `willStep` is true then the body will call resetFlags, sync with the parent Game Object and then run one iteration of `Body.update`, using the provided delta. If false, only the Game Object sync takes place. +* `ArcadePhysics.World.update` will now determine if a physics step is going to happen this frame or not. If not, it no longer calls `World.step` (fix #4529, thanks @ampled). If a step _is_ going to happen, then it now handles this with one iteration of the bodies array, instead of two. It has also inlined a single world step, avoiding branching out. If extra world steps are required this frame (such as in high Hz environments) then `World.step` is called accordingly. +* `ArcadePhysics.World.postUpdate` will no longer call `Body.postUpdate` on all of the bodies if no World step has taken place this frame. +* `ArcadePhysics.World.step` will now increment the `stepsLastFrame` counter, allowing `postUpdate` to determine if bodies should be processed should World.step have been invoked manually. + +### Bug Fixes + +* Tweens created in a paused state couldn't be started by a call to `play`. Fix #4525 (thanks @TonioParis) +* If both Arcade Physics circle body positions and the delta equaled zero, the `separateCircle` function would cause the position to be set `NaN` (thanks @hizzd) +* The `CameraManager` would incorrectly destroy the `default` Camera in its shutdown method, meaning that if you used a fixed mask camera and stopped then resumed a Scene, the masks would stop working. The default camera is now destroyed only in the `destroy` method. Fix #4520 (thanks @telinc1) +* Passing a Frame object to `Bob.setFrame` would fail, as it expected a string or integer. It now checks the type of object, and if a Frame it checks to make sure it's a Frame belonging to the parent Blitter's texture, and if so sets it. Fix #4516 (thanks @NokFrt) +* The ScaleManager full screen call had an arrow function in it. Despite being within a conditional block of code it still broke really old browsers like IE11, so has been removed. Fix #4530 (thanks @jorbascrumps @CNDW) +* `Game.getTime` would return `NaN` because it incorrectly accessed the time value from the TimeStep. +* Text with a `fixedWidth` or `fixedHeight` could cause the canvas to be cropped if less than the size of the Text itself (thanks @rexrainbow) +* Changing the `radius` of an Arc Game Object wouldn't update the size, causing origin issues. It now updates the size and origin correctly in WebGL. Fix #4542 (thanks @@PhaserEditor2D) +* Setting `padding` in a Text style configuration object would cause an error about calling split on undefined. Padding can now be applied both in the config and via `setPadding`. +* `Tilemap.createBlankDynamicLayer` would fail if you provided a string for the tileset as the base tile width and height were incorrectly read from the tileset argument. Fix #4495 (thanks @jppresents) +* `Tilemap.createDynamicLayer` would fail if you called it without setting the `x` and `y` arguments, even though they were flagged as being optional. Fix #4508 (thanks @jackfreak) +* `RenderTexture.draw` didn't work if no `x` and `y` arguments were provided, even though they are optional, due to a problem with the way the frame cut values were added. The class has been refactored to prevent this, fixing issues like `RenderTexture.erase` not working with Groups. Fix #4528 (thanks @jbgomez21 @telinc1) +* The `Grid` Game Object wouldn't render in Canvas mode at all. Fix #4585 (thanks @fyyyyy) +* If you had a `Graphics` object in the display list immediately after an object with a Bitmap Mask it would throw an error `Uncaught TypeError: Cannot set property 'TL' of undefined`. Fix #4581 (thanks @Petah @Loonride) +* Calling Arcade Physics `Body.reset` on a Game Object that doesn't have any bounds, like a Container, would throw an error about being unable to access `getTopLeft`. If this is the case, it will now set the position to the given x/y values (thanks Jazz) +* All of the `Tilemaps.Parsers.Tiled` static functions are now available to be called directly. Fix #4318 (thanks @jestarray) +* `Arcade.StaticBody.setSize` now centers the body correctly, as with the other similar methods. Fix #4213 (thanks @samme) +* Setting `random: false` in a Particle Emitter config option no longer causes it to think random is true (thanks @samme) +* `Zone.setSize` didn't update the displayOrigin, causing touch events to be inaccurate as the origin was out. Fix #4131 (thanks @rexrainbow) +* `Tween.restart` wouldn't restart the tween properly. Fix #4594 (thanks @NokFrt) +* Looped Tween Timelines would mess-up the tween values on every loop repeat, causing the loop to fail. They now loop correctly due to a fix in the Tween.play method. Fix #4558 (thanks @peteroravec) +* `Timeline.setTimeScale` would only impact the Timeline loop and completion delays, not the actively running Tweens. It now scales the time for all child tweens as well. Fix #4164 (thanks @garethwhittaker) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@PhaserEditor2D @samme @Nallebeorn @Punkiebe @rootasjey @Sun0fABeach + +## Version 3.17.0 - Motoko - 10th May 2019 + +### Shaders + +'Shader' is a new type of Game Object which allows you to easily add a quad with its own shader into the display list, and manipulate it as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other Game Object. They can also be made interactive and used for input events. + +They work by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can be created dynamically at runtime, or loaded in via the updated GLSL File Loader: + +```javascript +function preload () +{ + this.load.glsl('fire', 'shaders/fire.glsl.js'); +} + +function create () +{ + this.add.shader('fire', 400, 300, 512, 512); +} +``` + +Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. + +* `Display.BaseShader` is a new type of object that contain the fragment and vertex source, together with any uniforms the shader needs, and are used when creating the new `Shader` Game Objects. They are stored in the Shader cache. +* The Shader Cache `this.cache.shader` has been updated. Rather than holding plain text fragments, it now holds instances of the new `BaseShader` objects. As a result, using `cache.shader.get(key)` will now return a `BaseShader` instead of a text file. +* The `GLSLFile` loader has been updated with new arguments. As well as a URL to the shader file you can also specify if the file is a fragment or vertex shader. It then uses this value to help create or update a `BaseShader` instance in the shader cache. +* The `GLSLFile` loader now supports shader bundles. These allow for multiple shaders to be stored in a single file, with each shader separated by a block of front-matter that represents its contents. Example shader bundles can be found in the Phaser 3 Examples repo. + +### DOM Elements + +DOM Elements have finally left the experimental stage and are now part of the full Phaser release. + +DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. In order for DOM Elements to display you have to enable them by adding the following to your game configuration object: + +```javascript +dom { + createContainer: true +} +``` + +When this is added, Phaser will automatically create a DOM Container div that is positioned over the top of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of settings within the Scale Manager, the dom container is resized accordingly. + +You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing +Element that you wish to be placed under the control of Phaser. For example: + +```javascript +this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); +``` + +The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + +You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control alignment and positioning of the elements next to regular game content. + +Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other methods available in this class to help construct your elements. + +Once the element has been created you can then control it like you would any other Game Object. You can set its position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have a DOM Element, then a Sprite, then another DOM Element behind it. + +You can find lots of examples on using DOM Elements in the Phaser 3 Examples repo. + +### Geometry and Bitmap Masks + +* `Camera.setMask` is a new method that allows you to set a geometry or bitmap mask on any camera. The mask can be set to remain fixed in position, or to translate along with the camera. It will impact anything the camera renders. A reference to the mask is stored in the `Camera.mask` property. +* `Camera.clearMask` is a new method that clears a previously set mask on a Camera. +* There is a new Game Config property `input.windowEvents` which is true by default. It controls if Phaser will listen for any input events on the Window. If you disable this, Phaser will stop being able to emit events like `POINTER_UP_OUTSIDE`, or be aware of anything that happens outside of the Canvas re: input. +* Containers can now contain masked children and have those masks respected, including the mask on the Container itself (if any). Masks work on any depth of child up to 255 children deep. +* Geometry Masks are now batched. Previously, using the same mask on multiple Game Objects would create brand new stencil operations for every single Game Object, causing performance to tank. Now, the mask is only set if it's different from the previously masked object in the display list, allowing you to mask thousands of Game Objects and retain batching through-out. +* `GeometryMask.setInvertAlpha` is a new method that allows you to set the `invertAlpha` property in a chainable call. +* Previously, setting a mask on a Particle Emitter wouldn't work (it had to be set on the Emitter Manager instance), even though the mask methods and properties existed. You can now set a geometry or bitmap mask directly on an emitter. +* The Particle Emitter Manager was missing the Mask component, even though it fully supported masking. The Mask component has now been added. You can now mask the manager, which impacts all emitters you create through it, or a specific emitter. Different emitters can have different masks, although they override the parent mask, if set. +* You can now apply a Bitmap Mask to a Camera or Container and a Geometry Mask to a child and have it work correctly. +* `WebGLRenderer.maskCount` is a new internal property that tracks the number of masks in the stack. +* `WebGLRenderer.maskStack` is a new internal array that contains the current mask stack. + +### Arcade Physics + +#### New Features + +* `overlapTiles` is a new method that allows you to check for overlaps between a physics enabled Game Object and an array of Tiles. The Tiles don't have to have been enable for collision, or even be on the same layer, for the overlap check to work. You can provide your own process callback and/or overlap callback. This is handy for testing for overlap for a specific Tile in your map, not just based on a tile index. This is available via `this.physics.overlapTiles` and the World instance. +* `collideTiles` is a new method that allows you to check for collision between a physics enabled Game Object and an array of Tiles. The Tiles don't have to have been enable for collision, or even be on the same layer, for the collision to work. You can provide your own process callback and/or overlap callback. There are some limitations in using this method, please consult the API Docs for details, but on the whole, it allows for dynamic collision on small sets of Tile instances. This is available via `this.physics.collideTiles` and the World instance. +* `overlapRect` is a new method that allows you to return an array of all physics bodies within the given rectangular region of the World. It can return dynamic or static bodies and will use the RTree for super-fast searching, if enabled (which it is by default) +* The `Body.setCollideWorldBounds` method has two new optional arguments `bounceX` and `bounceY` which, if given, will set the World Bounce values for the body. + +#### Updates + +* `Body.preUpdate` is a new method that is called only once per game step. It resets all collision status properties and syncs the Body with the parent Game Object. +* `Body.update` has been rewritten to just perform one single physics step and no longer re-syncs with the Game Object. It can be called multiple times per game step, depending on the World FPS rate. +* `Body.postUpdate` has been rewritten to make it more compact. It syncs the body data back to the parent Game Object and is only called once per game step now (previously it was called whenever the Body updated) +* The `World.late` Set has been removed and is no longer populated, as it's no longer required. +* `World.update` now calls `Body.preUpdate` just once per game step, then calls `Body.update` as many times as is required as per the FPS setting, and no longer calls `Body.postUpdate` at all. +* `World.collideSpriteVsTilemapLayer` now returns a boolean if a collision or overlap happens, where-as before it didn't. +* `World.collideSpriteVsTilemapLayerHandler` is a new private method that handles all tilemap collision checks. +* The internal method `SeparateTile` now has a new argument `isLayer` which controls if the set comes from a layer or an array. +* The internal method `TileCheckX` now has a new argument `isLayer` which controls if the set comes from a layer or an array. +* The internal method `TileCheckY` now has a new argument `isLayer` which controls if the set comes from a layer or an array. +* `Body.isMoving` has been removed as it was never used internally. +* `Body.stopVelocityOnCollide` has been removed as it was never used internally. +* All of the Arcade Physics Components are now available directly under the `Phaser.Physics.Arcade.Components` namespace. Fix #4440 (thanks @jackfreak) +* `Phaser.Physics.Arcade.Events` is now exposed in the namespace, preventing it from erroring if you use them in TypeScript. Fix #4481 (thanks @danielalves) +* The Matter World configuration value `bodyDebugFillColor` has been renamed to `debugBodyFillColor` to be consistent with the rest of the options. +* The Matter World configuration has a new property: `debugStaticBodyColor` that sets the static body debug color. + +#### Bug Fixes + +* The `Body.delta` values are now able to be read and acted upon during a Scene update, due to the new game step flow. This means you can now call `this.physics.collide` during a Scene `update` and it will work properly again. Fix #4370 (thanks @NokFrt) +* `ArcadePhysics.furthest` now iterates the bodies Set, rather than the RTree, which keeps it working even if the RTree has been disabled. +* `ArcadePhysics.closest` now iterates the bodies Set, rather than the RTree, which keeps it working even if the RTree has been disabled. +* `Body.setVelocity` caused the `speed` property to be set to `NaN` if you didn't provide a `y` argument. +* Passing an _array_ of configuration objects to `physics.add.group` would ignore them and none of the children would be assigned a physics body. Fix #4511 (thanks @rgk) +* A Body with `damping` and `drag` enabled would fail to move if it went from zero velocity to a new velocity inside an `update` loop. It will now reset its speed accordingly and retain its new velocity (thanks StealthGary) + +### Facebook Instant Games Plugin + +* The method `consumePurchases` has been renamed to `consumePurchase` to bring it in-line with the Facebook API. +* `getProduct` is a new method that will return a single Product from the product catalog based on the given Product ID. You can use this to look-up product details based on a purchase list. + +### New Features + +* A Scene will now emit the new `CREATE` event after it has been created by the Scene Manager. If the Scene has a `create` method this event comes after that, so is useful to knowing when a Scene may have finished creating Game Objects, etc. (thanks @jackfreak) +* `Tilemap.removeTile` is a new method that allows you to remove a tile, or an array of tiles, by passing in references to the tiles themselves, rather than coordinates. The tiles can be replaced with new tiles of the given index, or removed entirely, and the method can optionally recalculate interesting faces on the layer. +* `TweenManager.remove` is a new method that immediately removes the given Tween from all of its internal arrays. +* `Tween.remove` is a new method that immediately removes the Tween from the TweenManager, regardless of what state the tween is in. Once called the tween will no longer exist within any internal TweenManager arrays. +* `SceneManager.isPaused` is a new method that will return if the given Scene is currently paused or not (thanks @samme) +* `ScenePlugin.isPaused` is a new method that will return if the given Scene is currently paused or not (thanks @samme) +* `TextureManager.removeKey` is a new method that will remove a key from the Texture Manager without destroying the texture itself. +* `Matter.World.resetCollisionIDs` is a new method that will reset the collision IDs that Matter JS uses for body collision groups. You should call this before destroying your game if you need to restart the game again on the same page, without first reloading the page. Or, if you wish to consistently destroy a Scene that contains Matter.js and then run it again (thanks @clesquir) +* RenderTexture has two new optional constructor arguments `key` and `frame`. This allows you to create a RenderTexture pre-populated with the size and frame from an existing texture (thanks @TadejZupancic) +* `GameObjects.Components.PathFollower` is a new component that manages any type of Game Object following a path. The original Path Follower Game Object has been updated to use this new component directly, but it can be applied to any custom Game Object class. +* `Tilemap.removeLayer` is a new method that allows you to remove a specific layer from a Tilemap without destroying it. +* `Tilemap.destroyLayer` is a new method that allows you to destroy a layer and remove it from a Tilemap. +* `Tilemap.renderDebugFull` is a new method that will debug render all layers in the Tilemap to the given Graphics object. +* `Geom.Intersects.GetCircleToCircle` is a new function that will return the point/s of intersection between two circles (thanks @florianvazelle) +* `Geom.Intersects.GetCircleToRectangle` is a new function that will return the point/s of intersection between a circle and a rectangle (thanks @florianvazelle) +* `Geom.Intersects.GetLineToCircle` is a new function that will return the point/s of intersection between a line and a circle (thanks @florianvazelle) +* `Geom.Intersects.GetLineToRectangle` is a new function that will return the point/s of intersection between a line and a rectangle (thanks @florianvazelle) +* `Geom.Intersects.GetRectangleToRectangle` is a new function that will return the point/s of intersection between two rectangles (thanks @florianvazelle) +* `Geom.Intersects.GetRectangleToTriangle` is a new function that will return the point/s of intersection between a rectangle and a triangle (thanks @florianvazelle) +* `Geom.Intersects.GetTriangleToCircle` is a new function that will return the point/s of intersection between a triangle and a circle (thanks @florianvazelle) +* `Geom.Intersects.GetTriangleToLine` is a new function that will return the point/s of intersection between a triangle and a line (thanks @florianvazelle) +* `Geom.Intersects.GetTriangleToTriangle` is a new function that will return the point/s of intersection between two triangles (thanks @florianvazelle) +* `Size.setCSS` is a new method that will set the Size components width and height to the respective CSS style properties of the given element. +* `CSSFile` is a new Loader FileType that allows you to load css into the current document via the normal Phaser Loader, using the `load.css` method. As such, you can chain it with other load calls, load via config, use as part of a pack load or any other option available to all loader filetypes. The CSS is applied immediately to the document. +* `MultiScriptFile` is a new Loader FileType that allows you to load multiple script files into the document via the Phaser Loader, using the new `load.scripts` method. The difference between this and `load.script` is that you must pass an array of script file URLs to this method and they will be loaded in parallel but _processed_ (i.e. added to the document) in the exact order specified in the array. This allows you to load a bundle of scripts that have dependencies on each other. +* `Key.getDuration` is a new method that will return the duration, in ms, that the Key has been held down for. If the Key isn't down it will return zero. +* The `Container.setScrollFactor` method has a new optional argument `updateChildren`. If set, it will change the `scrollFactor` values of all the Container children as well as the Container. Fix #4466 #4475 (thanks @pinkkis @enriqueto) +* There is a new webpack config `FEATURE_SOUND` which is set to `true` by default, but if set to `false` it will exclude the Sound Manager and all of its systems from the build files. Fix #4428 (thanks @goldfire) +* `Scene.Systems.renderer` is a new property that is a reference to the current renderer the game is using. +* `Utils.Objects.SetValue` is a new function that allows you to set a value in an object by specifying a property key. The function can set a value to any depth by using dot-notation for the key, i.e. `SetValue(data, 'world.position.x', 100)`. +* `WebGLRenderer.glFuncMap` is a new object, populated during the `init` method, that contains uniform mappings from key to the corresponding gl function, i.e. `mat2` to `gl.uniformMatrix2fv`. +* `BaseCache.getKeys` is a new method that will return all keys in use in the current cache, i.e. `this.cache.shader.getKeys()`. + +### Updates + +* Removed all references to CocoonJS from the API, including in the Device.OS object and elsewhere, as Cocoon is no longer. +* The MouseManager and TouchManager now use separate handlers for the Window level input events, which check to see if the canvas is the target or not, and redirect processing accordingly. +* `AnimationManager.generateFrameNumbers` can now accept a start number greater than the end number, and will generate them in reverse (thanks @cruzdanilo) +* The return from the `ScenePlugin.add` method has changed. Previously, it would return the ScenePlugin, but now it returns a reference to the Scene that was added to the Scene Manager, keeping it in-line with all other `add` methods in the API. Fix #4359 (thanks @BigZaphod) +* The `PluginManager.installScenePlugin` method has a new optional boolean parameter `fromLoader` which controls if the plugin is coming in from the result of a Loader operation or not. If it is, it no longer throws a console warning if the plugin already exists. This fixes an issue where if you return to a Scene that loads a Scene Plugin it would throw a warning and then not install the plugin to the Scene. +* The Scale Manager has a new event `FULLSCREEN_FAILED` which is fired if you try to enter fullscreen mode, but the browser rejects it for some reason. +* The `ScaleMode` Component has been removed from every Game Object, and along with it the `scaleMode` property and `setScaleMode` method. These did nothing anyway as they were not hooked to the render pipeline and scale mode should be set on the texture, not the Game Object. Fix #4413 (thanks @jcyuan) +* The `Clock.now` property value is now synced to be the `TimeStep.time` value when the Clock plugin boots and is no longer `Date.now()` until the first update (thanks @Antriel) +* `Graphics.strokePoints` has renamed the second argument from `autoClose` to `closeShape`. There is also a new third argument `closePath`, which defaults to `true` and automatically closes the path before stroking it. The `endIndex` argument is now the fourth argument, instead of the third. +* `Graphics.fillPoints` has renamed the second argument from `autoClose` to `closeShape`. There is also a new third argument `closePath`, which defaults to `true` and automatically closes the path before filling it. The `endIndex` argument is now the fourth argument, instead of the third. +* Calling `Texture.destroy` will now call `TextureManager.removeKey` to ensure the key is removed from the manager, should you destroy a texture directly, rather than going via `TextureManager.remove`. Fix #4461 (thanks @BigZaphod) +* `SpriteSheetFromAtlas` now adds in a `__BASE` entry for the Sprite Sheet it creates, keeping it consistent with the other frame parsers (thanks @Cirras) +* The `from` and `to` properties in the PathFollower Config can now be used to set the span of the follow duration (thanks @kensleebos) +* `Graphics.lineFxTo` and `Graphics.moveFxTo` have been removed as they were not being rendered anyway. +* You can now use "infinite" tilemaps as created in Tiled v1.1 and above. Support is basic in that it takes the chunk data and builds one giant map from it. However, at least you are still able to now load and use infinite maps, even if they don't chunk during the game (thanks @Upperfoot) +* `MapData.infinite` is a new boolean that controls if the map data is infinite or not. +* `DynamicTilemapLayer.destroy` will now remove the layer from the Tilemap it belongs to, clearing it from the layers array. Fix #4319 (thanks @APXEOLOG) +* `StaticTilemapLayer.destroy` will now remove the layer from the Tilemap it belongs to, clearing it from the layers array. Fix #4319 (thanks @APXEOLOG) +* `DynamicTilemapLayer.destroy` has a new optional boolean argument `removeFromTilemap` which will control if the layer is removed from the parent map or not. +* `StaticTilemapLayer.destroy` has a new optional boolean argument `removeFromTilemap` which will control if the layer is removed from the parent map or not. +* `Tilemap.copy` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.fill` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.forEachTile` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.putTilesAt` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.randomize` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.calculateFacesAt` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.renderDebug` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.replaceByIndex` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setCollision` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setCollisionBetween` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setCollisionByProperty` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setCollisionByExclusion` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setCollisionFromCollisionGroup` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setTileIndexCallback` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.setTileLocationCallback` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.shuffle` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.swapByIndex` now actually returns `null` if an invalid layer was given, as per the docs. +* `Tilemap.weightedRandomize` now actually returns `null` if an invalid layer was given, as per the docs. +* `BaseCamera.cameraManager` is a new property that is a reference to the Camera Manager, set in the `setScene` method. +* `CameraManager.default` is a new property that contains a single un-transformed instance of a Camera, that exists outside of the camera list and doesn't render. It's used by other systems as a default camera matrix. +* The `Graphics` Game Object now has 3 new Transform Matrix instances called `_tempMatrix1` to `_tempMatrix3`, which are used by it during the WebGL Rendering process. This is because Graphics objects can be used as Geometry Masks, which need to retain their own matrix state mid-render of another object, so cannot share the renderer temp matrices that other Game Objects can use. This also indirectly fixes an issue where masked children (such as emitters or container children) would get incorrect camera scroll values. +* The `Key` method signature has changed. It now expects to receive a reference to the KeyboardPlugin instance that is creating the Key as the first argument. This is now stored in the new `Key.plugin` property, and cleared in `destroy`. +* `KeyboardPlugin.removeKey` has a new optional argument `destroy` that will, if set, destroy the Key object being removed from the plugin. +* `InteractiveObject.customHitArea` is a new property that records if the hitArea for the Interactive Object was created based on texture size (false), or a custom shape (true) +* A Camera will pause following a Game Object for the duration of the Camera Pan Effect, as the two will clash over the Camera scroll position (thanks fruitbatinshades). +* `ParseXMLBitmapFont` has now been exposed as a static function on the `BitmapText` object, so you can access it easily from your own code (thanks @jcyuan) +* The math used in the circle to circle Arcade Physics collision has been updated to better handle horizontal collision, giving a more realistic response. Fix #4256 (thanks @akuskis @JeSuisUnCaillou) + +### Bug Fixes + +* The parent bounds are reset when exiting fullscreen mode in the Scale Manager. This fixes an issue when leaving fullscreen mode by pressing ESC (instead of programmatically) would leave the canvas in the full screen size. Fix #4357 (thanks @khutchins and @HeyStevenXu) +* `GetAdvancedValue` now uses the correct Math RND reference, which means anything that used the `randInt` or `randFloat` features of this function, such as creating a Sprite from a Config object, or Bitmap Text sizing, will no longer throw an error about a null object reference. Fix #4369 (thanks @sanadov) +* Trying to enter Fullscreen mode on Android / Chrome, or iOS / Safari, would throw an error regarding an unhandled Promise and a failure to invoke the event from a user gesture. This has been tightened up, using a proper Promise handler internally and the documentation clarified to explicitly say that you must call the function from a `pointerup` handler, and not `pointerdown`. Fix #4355 (thanks @matrizet) +* Camera fadeIn and fadeOut would sometimes leave a very low alpha-valued rectangle rendering to the camera. Fix #3833 (thanks @bdaenen) +* `Actions.Spread` would only use the `min` value to work out the step value but not apply it to the property being set (thanks @galman33) +* Calling `Tween.pause` returns the Tween instance, however, if it was already paused, it would return `undefined`, causing problems when chaining Tween methods (thanks @kyranet) +* Calling `TweenManager.makeActive` returns the TweenManager instance, however, if you create a tween externally and call `makeActive` with it, this would return `undefined`. +* Setting the `fixedWidth` and / or `fixedHeight` properties in the configuration of a `Text` would be ignored, they were only supported when calling the `setFixedSize` method. They now work via either option. Fix #4424 (thanks @rexrainbow) +* When calculating the width of a Text object for word wrapping it would ignore the extra spaces added from the wrap. It now accounts for these in the width. Fix #4187 (thanks @rexrainbow) +* `Utils.Array.Add` would act incorrectly when adding an object into an array in which it already belonged. This would manifest if, for example, adding a child into a display list it was already a part of. Fix #4411 (thanks @mudala @LoolzRules) +* `Tile.getCenterX` and `Tile.getCenterY` would return the wrong values for tiles on scaled layers. Fix #3845 (thanks @oloflarsson @florianvazelle) +* `Camera.startFollow` will now ensure that if the Camera is using bounds that the `scrollX` and `scrollY` values set after first following the Game Object do not exceed the bounds (thanks @snowbillr) +* Creating a Tween with a `duration` of zero would cause the tweened object properties to be set to `NaN`. Now they will tween for one single frame before being set to progress 1. Fix #4235 (thanks @BigZaphod) +* The First frame of a Texture would take on the appearance of the second frame in a Sprite Sheet created from trimmed Texture Atlas frames. Fix #4088 (thanks @Cirras) +* `Tween.stop` assumed that the parent was the TweenManager. If the Tween has been added to the Timeline, that was not true and the stop method crashed (thanks @TadejZupancic) +* Calling `Tween.restart` multiple times in a row would cause the tween to freeze. It will now disregard all additional calls to `restart` if it's already in a pending state (thanks @rgk) +* Tween Timelines would only apply the `delay` value of a child tween once and not on loop. Fix #3841 (thanks @Edwin222 @Antriel) +* `Texture.add` will no longer let you add a frame to a texture with the same name or index as one that already exists in the texture. Doing so will now return `null` instead of a Frame object, and the `frameTotal` will never be incremented. Fix #4459 (thanks @BigZaphod) +* The InputPlugin will now dispatch an update event, allowing the Gamepad Plugin to update itself every frame, regardless of DOM events. This allows Gamepads to work correctly again. Fix #4414 (thanks @CipSoft-Components) +* Calling `Tween.play` on a tween that had already finished and was pending removal will stop the tween from getting stuck in an `isPlaying` state and will restart the tween again from the beginning. Calling `play` on a Tween that is already playing does nothing. Fix #4184 (thanks @SamCode) +* Declared `Audio.dataset`, which fixes Internet Explorer 10 crashing when trying to access the dataset property of the object (thanks @SirLink) +* The `InputManager.update` method is now called every frame, as long as a native DOM event hasn't already fired it, which allows things like `setPollRate` to work again. Fix #4405 (thanks @Shucki) +* `Pointer.getDuration` would only return zero until the pointer was released, or moved (basically any action that generated a DOM event). It now returns the duration regardless of the DOM events. Fix #4444 (thanks @plazicx) +* `Keyboard.UpDuration` has been changed so the `duration` being checked is now against the current game clock. This means you can use it to check if a Key was released within `duration` ms ago, based on the time now, not the historic value of the Key. +* `Keyboard.DownDuration` has been changed so the `duration` being checked is now against the current game clock. This fixes an issue where it couldn't be used while the Key was actively being held down. Fix #4484 (thanks @belen-albeza) +* Keys would lose track of the state of a Scene when the Scene became paused. They're now updated regardless, stopping them from getting stuck if you pause and resume a Scene while holding them down. Fix #3822 (thanks @DannyT) +* Changing any aspect of a Text object, such as the font size or content, wouldn't update its `hitArea` if it had been enabled for input, causing it to carry on using the old hit area size. Now, as long as the Text was created _without_ a custom hitArea, the hitArea size will be changed to match the new texture size on update. If you have provided your own custom hitArea shape, you need to modify it when the Text changes size yourself. Fix #4456 (thanks @thanh-taro and @rexrainbow) +* `Camera.clearRenderToTexture` will check to see if the Scene is available before proceeding, avoiding potential errors when a Camera is destroyed multiple times during a Scene shutdown. +* Destroying a Game object during its `pointerup` event handler on a touch device will no longer cause `Uncaught TypeError: Cannot read property 'localX' of undefined`. All InputPlugin process handlers now check to see if the Game Object has been destroyed at any stage and abort if it has. Fix #4463 (thanks @PatrickSachs) +* `InputPlugin.clear` has a new argument `skipQueue` which is used to avoid clearing a Game Object twice. This, combined with the fix for 4463 means you will no longer get a `Cannot read property 'dragState'` error if you destroy a Game Object enabled for drag where another draggable object exists. Fix #4228 (thanks @YannCaron) +* `UpdateList.remove` will now move the removed child to the internal `_pendingRemoval` array, instead of slicing it directly out of the active list. The pending list is cleared at the start of the next game frame. Fix #4365 (thanks @jcyuan) +* Setting `pixelPerfect` when input enabling a Container would cause it to crash, because Containers don't have a texture to check. It will now throw a run-time warning and skip the Container for input. You should use a custom input callback instead. Fix #4492 (thanks @BigZaphod) +* Setting `fixedWidth` and `fixedHeight` on a Text object will now clamp the size of the canvas being created, as well as the width and height properties of the Text object itself (thanks @rexrainbow) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@sky-coding @G-Rath @S4n60w3n @rootasjey @englercj @josephmbustamante @Jason-Cooke @Zamiell @krzysztof-grzybek @S4n60w3n @m31271n @peterellisjones @martinlindhe @TylerMorley @samme @schomatis @BeLi4L @hizzd @OmarShehata @antoine-pous @digitsensitive + +Also, thanks to @Osmose there is a new Dashing config added to the Phaser 3 Docs Repo, with a new command `build-docset` which will build a [Dash](https://kapeli.com/dash) compatible docset for those who like to use Dash for their docs. + +## Version 3.16.2 - Ishikawa - 11th February 2019 + +This is point release primarily fixes a few important issues that surfaced in 3.16.0. + +### Matter Pointer Constraint Changes + +The following changes all effect the Matter JS Pointer Constraint class: + +* Pointer handling has been changed to make more sense. In the previous version, pressing down and then moving the Pointer _over_ a body would start it being dragged, even if the pointer was pressed down well outside of the body bounds. Now, a body can only be dragged by actually pressing down on it, or any of its parts, which is more in-line with how input events should work. +* Previously, releasing ANY pointer would stop an object being dragged, even if it wasn't the one actually dragging a body, as in a multi-touch game. Bodies are now bound to the pointer which started their drag and only the release of that pointer will stop them. +* There is a new Matter Physics Event `DRAG_START` which is emitted by a Pointer Constraint when it starts dragging a body. Listen for this event from the Matter World instance. +* There is a new Matter Physics Event `DRAG` which is emitted by a Pointer Constraint as it drags a body. Listen for this event from the Matter World instance. +* There is a new Matter Physics Event `DRAG_END` which is emitted by a Pointer Constraint when it stops dragging a body. Listen for this event from the Matter World instance. +* The `camera` property can no longer be set in the config object. Instead it is set every time the Pointer is pressed down on a Body, this resolves issues where you have a multi-camera Scene and want to drag a body in the non-main camera. +* `body` is a new property that holds a reference to the Body being dragged, if any. +* `part` is a new property that holds a reference to the Body part that was clicked on which started the drag. +* The internal `getBodyPart` method has been renamed to `hitTestBody` to more accurately reflect what it does. +* The class no longer listens for the pointer `up` event, instead of tracks the active pointer and waits for that to be released. This has reduced the complexity and size of the `update` method considerably. +* `stopDrag` is a new method that allows you to manually stop an object being dragged, even if the pointer isn't released. +* This class now has 100% JSDocs. + +### Updates + +* `TileSprite.setTileScale` has been updated so that the `y` argument is optional and set to match the `x` argument, like `setScale` elsewhere in the API. +* `InputManager.time` is a new property that holds the most recent time it was updated from the Game step, which plugins can access. +* `InputManager.preStep` is a new method that populates some internal properties every step. +* `KeyboardPlugin.time` has moved from being a property to being a getter, which returns the time from the InputManager. +* The `scale` property has been added to the `Scene` class (thanks @strangeweekend) +* `Matter.World.remove` now uses the `Composite.remove` method internally. Previously, it used `Composite.removeBody` which only allowed it to remove bodies from the simulation. Now, it can remove any type of Matter object. +* When the Matter World creates its wall bounds, the left and right walls now extend further up and down than before, so that in a 4-wall setting there are no gaps in the corners, which previously allowed for fast moving objects that hit a corner intersection point to sometimes travel through it. +* Touch inputs will now trigger a `POINTER_OUT` event if they leave the game (i.e. are released), where-as before they would only trigger the `POINTER_UP` event. Now, both happen (thanks @rgk) + +### Bug Fixes + +* The `Mesh.setAlpha` method has been restored, even though it's empty and does nothing, to prevent runtime errors when adding a Mesh or Quad object to a Container. Fix #4338 #4343 (thanks @pfdtravalmatic @charmingny) +* `KeyboardPlugin.checkDown` would always fail if using the new event system, because the time value it was checking wasn't updated. +* Entering `Fullscreen` mode in the Scale Manager and then pressing ESC would leave the injected fullsceen div in the DOM, causing it to throw a node insertion failure the second time you wanted to enter fullscreen mode. Fix #4352 (thanks @ngdevr) +* Due to the changes in the Input event system, the `GAME_OUT` event would never fire unless the input system was in legacy mode. The OUT and OVER handlers have been refactored and will now fire as soon as the DOM event happens. As a result the `InputManager._emitIsOverEvent` property has been removed, as the native event is sent directly to the handler and doesn't need storing locally any more. Fix #4344 (thanks @RademCZ) +* Added `Zone.setBlendMode` method as a NOOP function, fixing a bug where if you added a Zone to a Container when running under Canvas it would fail. Fix #4295 (thanks @emanuel15) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@maretana @CipSoft-Components @brian-lui + +## Version 3.16.0 / 3.16.1 - Ishikawa - 5th February 2019 + +Phaser 3.16 is a massive update. The single largest in the history of Phaser 3 and it contains _breaking changes_. If you're upgrading from an earlier version please do check the log entries below. + +Please note: there is no difference between 3.16.0 and 3.16.1. The version bump was just to get around a stupid npm semver policy. + +### Important Namespace Changes + +* The `Phaser.Boot` namespace has been renamed to `Phaser.Core`. As a result, the `boot` folder has been renamed to `core`. This impacts the `TimeStep` class and `VisibilityHandler` function, which have been moved to be under the new namespace. +* The `Phaser.Animations` namespace was incorrectly exposed in the Phaser entrypoints as `Animation` (note the lack of plural). This means that if you are creating any custom classes that extend Animation objects using the Phaser namespace, then please update them from `Phaser.Animation` to `Phaser.Animations`, i.e. `Phaser.Animation.AnimationFrame` to `Phaser.Animations.AnimationFrame`. This doesn't impact you if you created animations directly via the Animation Manager. +* The keyed Data Manager change data event string has changed from `changedata_` to `changedata-` to keep it consistent with other keyed events. Note the change from `_` to `-`. +* The Keyboard Plugin `keydown` dynamic event string has changed from `keydown_` to `keydown-` to keep it consistent with other keyed events. Note the change from `_` to `-`. +* The Keyboard Plugin `keyup` dynamic event string has changed from `keyup_` to `keyup-` to keep it consistent with other keyed events. Note the change from `_` to `-`. +* The `texturesready` event emitted by the Texture Manager has been renamed to `ready`. +* The `loadcomplete` event emitted by the Loader Plugin has been renamed to `postprocess` to be reflect what it's used for. +* Game Objects used to emit a `collide` event if they had an Arcade Physics Body with `onCollide` set, that collided with a Tile. This has changed. The event has been renamed to `tilecollide` and you should now listen for this event from the Arcade Physics World itself: `this.physics.world.on('tilecollide')`. Game Objects no longer emit this event. +* Game Objects used to emit an `overlap` event if they had an Arcade Physics Body with `onOverlap` set, that overlapped with a Tile. This has changed. The event has been renamed to `tileoverlap` and you should now listen for this event from the Arcade Physics World itself: `this.physics.world.on('tileoverlap')`. Game Objects no longer emit this event. +* The function `Phaser.Physics.Impact.SeperateX` has been renamed to `SeparateX` to correct the spelling mistake. +* The function `Phaser.Physics.Impact.SeperateY` has been renamed to `SeparateY` to correct the spelling mistake. +* The `ended` event in `WebAudioSound` has been renamed to `complete` to make it more consistent with the rest of the API. +* The `ended` event in `HTML5AudioSound` has been renamed to `complete` to make it more consistent with the rest of the API. +* The `Phaser.Utils.Objects` namespace was incorrectly exposed in the Phaser entrypoints as `Object` (note the lack of plural), this has now been fixed so all associated functions are properly namespaced. +* `Phaser.GameObjects.Blitter.Bob` has been renamed to `Phaser.GameObjects.Bob` to avoid namespace conflicts in TypeScript. +* `Phaser.GameObjects.Text.TextStyle` has been renamed to `Phaser.GameObjects.TextStyle` to avoid namespace conflicts in TypeScript. + +### Important Changes to the Input System + +In Phaser 3.15 and earlier the Input system worked using an event queue. All native DOM input events, such as from the Mouse, Touch or Keyboard, were picked up by event handlers and stored in a queue within the Input Manager. This queue was then processed during the next game step, all the events were dealt with and then it was cleared, ready to receive more events. As they were processed, the internal Phaser events such as `pointerdown` or `keyup` were dispatched to your game code. + +This worked fine in that you were able to guarantee _exactly_ when the events would arrive, because it was always at the same time in the game step. However, it had the side effect of you not being able to do things like open external browser windows, or go into Full Screen mode, during your event handlers - because they weren't "real" events, so didn't pass the browser security checks. To this end, methods like `addUpCallback` were added to try and provide this support (although it was never possible for keyboard events). + +In 3.16 this has changed. The DOM Events now trigger the respective internal events immediately, in the same invocation. So if you click on the canvas, the `pointerdown` event you receive in your game is still part of the 'native' event handler, so you're now free to do things like go into full screen mode, or open external windows, without any browser warnings or work-arounds. + +It does, however, mean that the point at which these handlers are called is no longer always consistent, and is no longer bound to the speed of the Request Animation Frame update. We've tested as much as possible, and so far, things carry on working as before. We've noticed a slight increase in responsiveness, due to the removal of the fractional delay in processing the events, which feels good. However, if for whatever reason this change has broken your game then you're able to easily switch back to the previous version. In your Game Config, create an `input` object and give it the property `queue: true`. This will tell Phaser to use the legacy event queue system. + +Please note that we _will_ remove this legacy system in the near future. So, please try and adapt your games to use the new system. If you've found an edge-case where something breaks because of it, please report it so we can look into it. + +As a result of this change, the following are now deprecated: + +* `InputPlugin.addUpCallback` method. +* `InputPlugin.addDownCallback` method. +* `InputPlugin.addMoveCallback` method. +* `InputManager.queue` property. +* `InputManager.domCallbacks` property. +* `InputManager._hasUpCallback` property. +* `InputManager._hasDownCallback` property. +* `InputManager._hasMoveCallback` property. +* `InputManager.processDomCallbacks` method. +* `InputManager.addUpCallback` method. +* `InputManager.addDownCallback` method. +* `InputManager.addMoveCallback` method. + +### keydown and keyup changes + +Due to unification across the event system, the `keydown_` and `keyup_` dynamic event strings have changed. + +* In all cases the `keydown_KEY` event name has changed to `keydown-KEY`. Note the change from an underscore to a hyphen. +* In all cases the `keyup_KEY` event name has changed to `keyup-KEY`. Note the change from an underscore to a hyphen. + +You should update your game code accordingly. + +### Keyboard Input - New Features + +The specificity of the Keyboard events has been changed to allow you more control over event handling. Previously, the Keyboard Plugin would emit the global `keydown-CODE` event first (where CODE was a keycode string, like `keydown-A`), then it would emit the global `keydown` event. In previous versions, `Key` objects, created via `this.input.keyboard.addKey()`, didn't emit events. + +The `Key` class now extends EventEmitter and emits two new events directly: `down` and `up`. This means you can listen for an event from a Key you've created, i.e.: `yourKey.on('up', handler)`. + +The order has also now changed. If it exists, the Key object will dispatch its `down` event first. Then the Keyboard Plugin will dispatch `keydown_CODE` and finally the least specific of them all, `keydown` will be dispatched. + +You also now have the ability to cancel this at any stage either on a local or global level. All event handlers are sent an event object which you can call `event.stopImmediatePropagation()` on. This will immediately stop any further listeners from being invoked in the current Scene. Therefore, if you call `stopImmediatePropagation()` in the `Key.on` handler, then the Keyboard Plugin will not emit either the `keydown-CODE` or `keydown` global events. You can also call `stopImmediatePropagation()` during the `keydown-CODE` handler, to stop it reaching the global `keydown` handler. As `keydown` is last, calling it there has no effect. + +There is also the `stopPropagation()` function. This works in the same way as `stopImmediatePropagation` but instead of being local, it works across all of the Scenes in your game. For example, if you had 3 active Scenes (A, B and C, with A at the top of the Scene list), all listening for the same key, calling `stopPropagation()` in Scene A would stop the event from reaching any handlers in Scenes B or C. Remember that events flow down the Scene list from top to bottom. So, the top-most rendering Scene in the Scene list has priority over any Scene below it. + +All the above also works for `keyup` events. + +New in 3.16 is the ability to receive a global `keydown` or `keyup` event from any key on the keyboard. Previously, it would only emit the event if it came from one of the keys listed in the KeyCodes file. Now, those global events will fire for any key, regardless of location. + +#### Keyboard Captures + +Key capturing is the way in which you stop a keyboard DOM event from activating anything else in the browser by calling `preventDefault` on it. For example, in tall web pages, pressing the SPACE BAR causes the page to scroll down. Obviously, if this is also the fire or jump button in your game, you don't want this to happen. So the key needs to be 'captured' to prevent it. Equally, you may wish to also capture the arrow keys, for similar reasons. Key capturing is done on a global level. If you set-up the capture of a key in one Scene, it will be captured globally across the whole game. + +In 3.16 you now do this using the new `KeyboardPlugin.addCapture` method. This takes keycodes as its argument. You can either pass in a single key code (i.e. 32 for the Space Bar), an array of key codes, or a comma-delimited string - in which case the string is parsed and each code it can work out is captured. + +To remove a capture you can use the `KeyboardPlugin.removeCapture` method, which takes the same style arguments as adding captures. To clear all captures call `KeyboardPlugin.clearCaptures`. Again, remember that these actions are global. + +You can also temporarily enable and disable capturing using `KeyboardPlugin.enableGlobalCapture` and `KeyboardPlugin.disableGlobalCapture`. This means if you set-up a bunch of key captures, but then need to disable them all for a while (perhaps you swap focus to a DOM text field), you can call `disableGlobalCapture` to do this, and when finished in the DOM you can enable captures again with `enableGlobalCapture`, without having to clear and re-create them all. + +Default captures can be defined in the Game Config in the `input.keyboard.captures` object. The captures are actually stored in the `KeyboardManager` class. The `KeyboardPlugin` is just a proxy to methods in the Keyboard Manager, but is how you should interface with it. + +* `KeyboardPlugin.addCapture` is a new method that allows you to define a set of keycodes to have the default browser behaviors disabled on. +* `KeyboardPlugin.removeCapture` is a new method that removes specific previously set key captures. +* `KeyboardPlugin.clearCaptures` is a new method that removes all key captures. +* `KeyboardPlugin.getCaptures` is a new method that returns an array of all current key captures. +* `KeyboardPlugin.enableGlobalCapture` is a new method that enables any key captures that have been created. +* `KeyboardPlugin.disableGlobalCapture` is a new method that disables any key captures that have been created, without removing them from the captures list. +* `KeyboardPlugin.addKey` has a new boolean argument `enableCapture`, which is true by default, that will add a key capture for the Key being created. +* `KeyboardPlugin.addKeys` has a new boolean argument `enableCapture`, which is true by default, that will add a key capture for any Key created by the method. + +#### Other Keyboard Updates and Fixes + +* There is a new class called `KeyboardManager`. This class is created by the global Input Manager if keyboard access has been enabled in the Game config. It's responsible for handling all browser keyboard events. Previously, the `KeyboardPlugin` did this which meant that every Scene that had its own Keyboard Plugin was binding more native keyboard events. This was causing problems with parallel Scenes when needing to capture keys. the `KeyboardPlugin` class still exists, and is still the main point of interface when you call `this.input.keyboard` in a Scene, but DOM event handling responsibility has been taken away from it. This means there's now only +one set of bindings ever created, which makes things a lot cleaner. +* There is a new Game and Scene Config setting `input.keyboard.capture` which is an array of KeyCodes that the Keyboard Plugin will capture all non-modified key events on. By default it is empty. You can populate it in the config, or use the new capture methods. +* The Keyboard Manager will now call `preventDefault` only on non-modified key presses, stopping the keyboard event from hitting the browser. Previously, capturing the R key, for example, would block a CTRL+R page reload, but it now ignores it because of the key modifier. +* If the browser Window loses focus, either from switching to another app, or another tab, all active Keys will be reset. This prevents issues with keys still reporting as being held down after leaving the game and returning to it again. Fix #4134 (thanks @Simplonium) +* `Key.emitOnRepeat` is a new boolean property that controls if the Key will continuously emit a `down` event while being held down (true), or emit the event just once, on first press, and then skip future events (false). +* `Key.setEmitOnRepeat` is a new chainable method for setting the `emitOnRepeat` property. +* The `KeyboardPlugin.addKeys` method has a new optional boolean `emitOnRepeat` which sets that property on all Key objects it creates as part of the call. It defaults to `false`. +* The `KeyboardPlugin.addKey` method has a new optional boolean `emitOnRepeat` which sets that property on the Key object it creates. It defaults to `false`. +* The `Key` class now extends EventEmitter and emits two events directly: `down` and `up`. This means you can listen for an event from a Key you've created, i.e.: `yourKey.on('up', handler)`. +* The following Key Codes have been added, which include some missing alphabet letters in Persian and Arabic: `SEMICOLON_FIREFOX`, `COLON`, `COMMA_FIREFOX_WINDOWS`, `COMMA_FIREFOX`, `BRACKET_RIGHT_FIREFOX` and `BRACKET_LEFT_FIREFOX` (thanks @wmateam) +* `Key.onDown` is a new method that handles the Key being pressed down, including down repeats. +* `Key.onUp` is a new method that handles the Key being released. +* `Key.destroy` is a new method that handles Key instance destruction. It is called automatically in `KeyboardPlugin.destroy`. +* The `Key.preventDefault` property has been removed. This is now handled by the global keyboard capture methods. +* `Key.metaKey` is a new boolean property which indicates if the Meta Key was held down when the Key was pressed. On a Mac the Meta Key is Command. On a Windows keyboard, it's the Windows key. +* `InputManager.keyboard` is a new property that instantiates the global Keyboard Manager, if enabled in the game config. +* The `KeyboardPlugin.addKey` method has a new boolean property `enableCapture` which automatically prevents default on the Key being created. +* The `KeyboardPlugin.addKeys` method has a new boolean property `enableCapture` which automatically prevents default on Keys being created. +* `Phaser.Input.Keyboard.ProcessKeyDown` has been removed as it's no longer required, `Key.onDown` handles it instead. +* `Phaser.Input.Keyboard.ProcessKeyUp` has been removed as it's no longer required, `Key.onUp` handles it instead. +* The Keyboard Manager has a property called `captures` which is an array of keycodes, as populated by the Game Config. Any key code in the array will have `preventDefault` called on it if pressed. +* `KeyboardPlugin.manager` is a new property that references the Keyboard Manager and is used internally. +* `KeyboardPlugin.target` has been removed as it's no longer used by the class. +* `KeyboardPlugin.queue` has been removed as it's no longer used by the class. +* `KeyboardPlugin.onKeyHandler` has been removed as it's no longer used by the class. +* `KeyboardPlugin.startListeners` has been removed as it's no longer used by the class. +* `KeyboardPlugin.stopListeners` has been removed as it's no longer used by the class. + +### Mouse and Touch Input - New Features, Updates and Fixes + +* The Mouse Manager class has been updated to remove some commented out code and refine the `startListeners` method. +* When enabling a Game Object for input it will now use the `width` and `height` properties of the Game Object first, falling back to the frame size if not found. This stops a bug when enabling BitmapText objects for input and it using the font texture as the hit area size, rather than the text itself. +* `Pointer.smoothFactor` is a float-value that allows you to automatically apply smoothing to the Pointer position as it moves. This is ideal when you want something smoothly tracking a pointer in a game, or are need a smooth drawing motion for an art package. The default value is zero, meaning disabled. Set to a small number, such as 0.2, to enable. +* `Config.inputSmoothFactor` is a new property that allows you to set the smoothing factor for all Pointers the game creates. The default value is zero, which is disabled. Set in the game config as `input: { smoothFactor: value }`. +* `InputManager.transformPointer` has a new boolean argument `wasMove`, which controls if the pointer is being transformed after a move or up/down event. +* `Pointer.velocity` is a new Vector2 that contains the velocity of the Pointer, based on the current and previous positions. The velocity is smoothed out each frame according to the `Pointer.motionFactor` property. This is done for more accurate gesture recognition. The velocity is updated based on Pointer movement and doesn't require a button to be pressed first. +* `Pointer.angle` is a new property that contains the angle of the Pointer, in radians, based on the current and previous positions. The angle is smoothed out each frame according to the `Pointer.motionFactor` property. This is done for more accurate gesture recognition. The angle is updated based on Pointer movement and doesn't require a button to be pressed first. +* `Pointer.distance` is a new property that contains the distance of the Pointer, in radians, based on the current and previous positions. The distance is smoothed out each frame according to the `Pointer.motionFactor` property. This is done for more accurate gesture recognition. The distance is updated based on Pointer movement and doesn't require a button to be pressed first. +* `Pointer.motionFactor` is a new property that controls how much smoothing to apply to the Pointer positions each frame. This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, angle and distance of the Pointer. It's applied every frame until the midPoint reaches the current position of the Pointer. The default value is 0.2. +* The Input Plugin was emitting a `preUpdate` event, with the capital U, instead of `preupdate`. This has now been corrected. Fix #4185 (thanks @gadelan) +* `Pointer.updateMotion` is a new method that is called automatically, each step, by the Input Manager. It's responsible for calculating the Pointer velocity, angle and distance properties. +* `Pointer.time` is a new property that holds the time the Pointer was last updated by the Game step. +* `Pointer.getDistance` has been updated. If called while a button is being held down, it will return the distance between the Pointer's current position and it's down position. If called when a Pointer doesn't have a button down, it will return the historic distance between the up and down positions. +* `Pointer.getDistanceX` is a new method that will return the horizontal distance between the Pointer's previous and current coordinates. If called while a button is being held down, it will return the distance between the Pointer's current position and it's down position. If called when a Pointer doesn't have a button down, it will return the historic distance between the up and down positions. +* `Pointer.getDistanceY` is a new method that will return the horizontal distance between the Pointer's previous and current coordinates. If called while a button is being held down, it will return the distance between the Pointer's current position and it's down position. If called when a Pointer doesn't have a button down, it will return the historic distance between the up and down positions. +* `Pointer.getDuration` is a new method that will return the duration the Pointer was held down for. If the Pointer has a button pressed down at the time this method is called, it will return the duration since the Pointer's button was pressed down. If no button is held down, it will return the last recorded duration, based on the time the Pointer button was released. +* `Pointer.getAngle` is a new method that will return the angle between the Pointer coordinates. 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. +* In previous versions, the VisibilityHandler would create a `mousedown` listener for the game canvas and then call `window.focus` when detected (assuming the game config `autoFocus` property was `true`). Responsibility for this has now been moved to the Mouse Manager `onMouseDown` handler. +* In previous versions, the VisibilityHandler would create a `mouseout` listener for the game canvas and then set `game.isOver` when detected. Responsibility for this has now been moved to the Mouse Manager, which sets the new Input Manager `isOver` property directly. +* In previous versions, the VisibilityHandler would create a `mouseover` listener for the game canvas and then set `game.isOver` when detected. Responsibility for this has now been moved to the Mouse Manager, which sets the new Input Manager `isOver` property directly. +* The `Phaser.Game.isOver` property has been moved. You can now find it in the Input Manager and it's also accessible via the Input Plugin, which means you can do `this.input.isOver` from within a Scene. This makes more sense as it's input related and not a game level property. +* The Input Plugin has a new event you can listen to: `gameover`, which is triggered whenever the mouse or a pointer is moved over the Game canvas. Listen to it with `this.input.on('gameover')` from within a Scene. +* The Input Plugin has a new event you can listen to: `gameout`, which is triggered whenever the mouse or a pointer leaves the Game canvas. Listen to it with `this.input.on('gameout')` from within a Scene. +* The Game used to emit a `mouseover` event when the mouse entered the game canvas. This is no longer emitted by the Game itself and can instead be listened for using the new Input Plugin event `gameover`. +* The Game used to emit a `mouseout` event when the mouse left the game canvas. This is no longer emitted by the Game itself and can instead be listened for using the new Input Plugin event `gameout`. +* If the `window` object exists (which it will in normal browser environments) new `mouseup` and `touchend` event listeners are bound to it and trigger the normal `mouseup` or `touchend` events within the internal input system. This means you will now get a `pointerup` event from the Input Plugin even if the pointer is released outside of the game canvas. Pointers will also no longer think they are still 'down' if released outside the canvas and then moved inside again in their new state. +* The window will now have focus called on it by the Touch Manager, as well as the Mouse Manager, if the `autoFocus` game config property is enabled. +* The Input Plugin has a new event you can listen to: `pointerdownoutside`, which is triggered whenever the mouse or a pointer is pressed down while outside of the Game canvas. Listen to it with `this.input.on('pointerdownoutside')` from within a Scene. +* The Input Plugin has a new event you can listen to: `pointerupoutside`, which is triggered whenever the mouse or a pointer is released while outside of the Game canvas. Listen to it with `this.input.on('pointerupoutside')` from within a Scene. +* `Pointer.downElement` is a new property that holds the target of the DOM Event that triggered when the Pointer was pressed down. If this is within the game, this will be the game canvas element. +* `Pointer.upElement` is a new property that holds the target of the DOM Event that triggered when the Pointer was released. If this is within the game, this will be the game canvas element. +* The `Pointer.dragState` property has been removed. This is no longer used internally as it has to be tracked per Scene, not on a global level. +* `InputPlugin.setDragState` is a new internal method that sets the drag state for the given Pointer. +* `InputPlugin.getDragState` is a new internal method that gets the drag state for the given Pointer. +* Draggable Game Objects would not work if you had multiple Scenes running in parallel, with draggable objects in both of them. Only the top-most Scene would work fully. Items in the bottom Scene would never finish their drag cycle, causing them to get stuck. Fix #4249 #4278 (thanks @probt @iArePJ) +* `Pointer.leftButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). +* `Pointer.rightButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). +* `Pointer.middleButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). +* `Pointer.backButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). +* `Pointer.forwardButtonDown` will now return an actual boolean, rather than the result of the bitwise op (which still evaluated as a boolean, but this is cleaner). +* `Pointer.up`, `Pointer.move` and `Pointer.down` now use `in` to check for the existance of the `buttons` property on the event, causing it to be set even if equal to zero, which it is when there are no buttons down. This also fixes an issue where the buttons didn't update during a move event (thanks @SonnyCampbell @rexrainbow) + +### Changes as a result of the new Scale Manager + +3.16 introduces the completed Scale Manager. This is fully documented, but the class, all methods and all properties. It also includes a folder full of examples in the Phaser Labs, so you're strongly recommended to start there. + +* If you set the Game Config property `zoom` to be > 1 then it will automatically enable `pixelArt` mode, unless you set `pixelArt: false` in the config. +* There is a new property in the Game Config called `autoRound`, which controls if the canvas size and style sizes are passed through Math.floor or not. On some devices this can help with performance and anti-aliasing. The default is `false` (turned off). +* The Game Config property `autoResize` has been removed as it's now redundant. +* The WebGL and Canvas Renderers no longer change the Canvas size in their `resize` methods. They just update internal properties. +* The WebGL and Canvas Renderers now read the `width`, `height` and `resolution` values from the Scale Manager, not the Game Config. +* `CameraManager.baseScale` property has been removed as it's no longer used anywhere. +* The BaseCamera and Camera `preRender` methods now only take a resolution argument and use it internally for their transforms. +* `InputManager.scaleManager` is a new property that is a reference to the Scale Manager. This is populated in the `boot` method. +* The `InputManager.transformX` method has been removed. This is now available in the ScaleManager. +* The `InputManager.transformY` method has been removed. This is now available in the ScaleManager. +* The `InputManager.scale` property has been removed. This is now available in the ScaleManager under `displayScale`. +* The `InputManager.resize` method has been removed as this process is now handled by the ScaleManager. +* The `InputManager.bounds` property has been removed as this process is now handled by the ScaleManager. +* The `InputManager.updateBounds` method has been removed as this process is now handled by the ScaleManager. +* The `InputManager.getOffsetX` method has been removed as it's no longer required. +* The `InputManager.getOffsetY` method has been removed as it's no longer required. +* The `InputManager.getScaleX` method has been removed as it's no longer required. +* The `InputManager.getScaleY` method has been removed as it's no longer required. +* The `SceneManager.resize` method has been removed as it's no longer required. +* The `Scene.Systems.resize` method has been removed as it's no longer required. +* Scenes will no longer dispatch the `resize` event. You should now listen for this event from the Scale Manager instead. +* `BaseCamera.config` has been removed as it's no longer required. +* `BaseCamera.scaleManager` is a new property that references the Scale Manager and is used internally for size checks. +* The `Game.resize` method has been removed as it's no longer required. You should now call `ScaleManager.resize` instead. +* The Game will no longer dispatch the `resize` event. You should now listen for this event from the Scale Manager instead. + +### Facebook Instant Games Updates and Fixes + +* Added the `Leaderboard.getConnectedScores` method, to get a list of scores from player connected entries. +* The `loadPlayerPhoto` function in the Instant Games plugin now listens for the updated Loader event correctly, causing the `photocomplete` event to fire properly. +* `Leaderboard.setScore` now emits the LeaderboardScore object with the `setscore` event, as the documentation said it did. +* `Leaderboard.getPlayerScore` now only populates the `playerScore` property if the entry isn't `null`. +* If the `setScore` or `getPlayerScore` calls fail, it will return `null` as the score instance, instead of causing a run-time error. +* You can now pass an object or a string to `setScore` and objects will be automatically stringified. +* The `preloadAds` method will now only create an AdInstance object if the interstitial `loadSync` promise resolves. +* The `preloadVideoAds` method will now only create an AdInstance object if the interstitial `loadSync` promise resolves. +* The `preloadAds` method will now emit the `adsnofill` event, if there are no ads in the inventory to load. +* The `preloadVideoAds` method will now emit the `adsnofill` event, if there are no ads in the inventory to load. +* The `showAd` method will now emit the `adsnotloaded` event, if there are no ads loaded matching the given Placement ID. +* The `showVideo` method will now emit the `adsnotloaded` event, if there are no ads loaded matching the given Placement ID. +* Showing an ad will emit the `adfinished` event when the ad is closed, previously this event was called `showad` but the new name better reflects what has happened. +* The Facebook Plugin is now available in the `Phaser.Scene` class template under the `facebook` property (thanks @bryanwood) +* Fixed the `Leaderboard.getScores` method to now take the arguments into account. Fix #4271 (thanks @Oramy) +* Fixed an API validation error in the `chooseContext` method. Fix #4248 (thanks @yadurajiv) + +### New Features + +* You can now load external Scene files using the new `load.sceneFile` method. This allows you to dynamically load a Scene into the Scene Manager of your game, and swap to it at will. Please see the documentation and examples for further details. +* The data object being sent to the Dynamic Bitmap Text callback now has a new property `parent`, which is a reference to the Bitmap Text instance that owns the data object (thanks ornyth) +* The WebGL Renderer has a new method `clearPipeline`, which will clear down the current pipeline and reset the blend mode, ready for the context to be passed to a 3rd party library. +* The WebGL Renderer has a new method `rebindPipeline`, which will rebind the given pipeline instance, reset the blank texture and reset the blend mode. This is useful for recovering from 3rd party libs that have modified the gl context. +* Game Objects have a new property called `state`. Use this to track the state of a Game Object during its lifetime. For example, it could move from a state of 'moving', to 'attacking', to 'dead'. Phaser itself will never set this property, although plugins are allowed to. +* Game Objects have a new method called `setState` which will set the state property in a chainable call. +* `BlendModes.ERASE` is a new blend mode that will erase the object being drawn. When used in conjunction with a Render Texture it allows for effects that require you to erase parts of the texture, in either Canvas or WebGL. When used with a transparent game canvas, it allows you to erase parts of the canvas, showing the web page background through. +* `BlendModes.SOURCE_IN` is a new Canvas-only blend mode that allows you to use the `source-in` composite operation when rendering Game Objects. +* `BlendModes.SOURCE_OUT` is a new Canvas-only blend mode that allows you to use the `source-out` composite operation when rendering Game Objects. +* `BlendModes.SOURCE_ATOP` is a new Canvas-only blend mode that allows you to use the `source-atop` composite operation when rendering Game Objects. +* `BlendModes.DESTINATION_OVER` is a new Canvas-only blend mode that allows you to use the `destination-over` composite operation when rendering Game Objects. +* `BlendModes.DESTINATION_IN` is a new Canvas-only blend mode that allows you to use the `destination-in` composite operation when rendering Game Objects. +* `BlendModes.DESTINATION_OUT` is a new Canvas-only blend mode that allows you to use the `destination-out` composite operation when rendering Game Objects. +* `BlendModes.DESTINATION_ATOP` is a new Canvas-only blend mode that allows you to use the `destination-atop` composite operation when rendering Game Objects. +* `BlendModes.LIGHTER` is a new Canvas-only blend mode that allows you to use the `lighter` composite operation when rendering Game Objects. +* `BlendModes.COPY` is a new Canvas-only blend mode that allows you to use the `copy` composite operation when rendering Game Objects. +* `BlendModes.XOR` is a new Canvas-only blend mode that allows you to use the `xor` composite operation when rendering Game Objects. +* `RenderTexture.erase` is a new method that will take an object, or array of objects, and draw them to the Render Texture using an ERASE blend mode, resulting in them being removed from the Render Texture. This is really handy for making a bitmap masked texture in Canvas or WebGL (without using an actual mask), or for 'cutting away' part of a texture. +* There is a new boolean Game Config property called `customEnvironment`. If set to `true` it will skip the internal Feature checks when working out which type of renderer to create, allowing you to run Phaser under non-native web environments. If using this value, you _must_ set an explicit `renderType` of either CANVAS or WEBGL. It cannot be left as AUTO. Fix #4166 (thanks @jcyuan) +* `Animation.nextFrame` will advance an animation to the next frame in the sequence instantly, regardless of the animation time or state. You can call this on a Sprite: `sprite.anims.nextFrame()` (thanks rgk25) +* `Animation.previousFrame` will set an animation to the previous frame in the sequence instantly, regardless of the animation time or state. You can call this on a Sprite: `sprite.anims.previousFrame()` (thanks rgk25) +* `Geom.Intersects.PointToLine` has a new optional argument `lineThickness` (which defaults to 1). This allows you to determine if the point intersects a line of a given thickness, where the line-ends are circular (not square). +* `Geom.Line.GetNearestPoint` is a new static method that will return the nearest point on a line to the given point. +* `Geom.Line.GetShortestDistance` is a new static method that will return the shortest distance from a line to the given point. +* `Camera.getBounds` is a new method that will return a rectangle containing the bounds of the camera. +* `Camera.centerOnX` will move the camera horizontally to be centered on the given coordinate without changing its vertical placement. +* `Camera.centerOnY` will move the camera vertically to be centered on the given coordinate without changing its horizontally placement. +* `AnimationManager.exists` is a new method that will check to see if an Animation using the given key already exists or not and returns a boolean. +* `animationstart-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationstart-explode`. +* `animationrestart-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationrestart-explode`. +* `animationcomplete-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationcomplete-explode`. +* `animationupdate-key` is a new Animation key specific event emitted by a Game Object. For example, if you had an animation with a key of 'explode' you can now listen for `animationupdate-explode`. +* The Animation class now extends the Event Emitter and dispatches events itself. This allows you to listen for events from a specific Animation, rather than via a Game Object. This is handy, for example, if you had an explosion animation that you wanted to trigger a sound effect when it started. You can now listen for the events from the Animation object directly. +* The Animation class now emits the `start` event when played (either forward, or in reverse) by any Game Object. +* The Animation class now emits the `restart` event when it restarts playing on any Game Object. +* The Animation class now emits the `complete` event when it finishes playing on any Game Object. +* The Animation Component has a new method called `chain` which allows you to line-up another animation to start playing as soon as the current one stops, no matter how it stops (either by reaching its natural end, or directly by having stop called on it). You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. +* `CanvasTexture.drawFrame` is a new method that allows you to draw a texture frame to the CanvasTexture based on the texture key and frame given. +* `CanvasTexture.getIndex` is a new method that will take an x/y coordinate and return the Image Data index offset used to retrieve the pixel values. +* `CanvasTexture.getPixels` is a new method that will take a region as an x/y and width/height and return all of the pixels in that region from the CanvasTexture. +* `CanvasTexture.setPixel` is a new method that sets the given pixel in the CanvasTexture to the color and alpha values provided. +* `CanvasTexture.getData` is a new method that will extract an ImageData block from the CanvasTexture from the region given. +* `CanvasTexture.putData` is a new method that will put an ImageData block at the given coordinates in a CanvasTexture. +* `Line.Extend` is a new static function that allows you extend the start and/or end points of a Line by the given amounts. +* `Vector2.LEFT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector2.RIGHT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector2.UP` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector2.DOWN` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector2.ONE` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.ZERO` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.LEFT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.RIGHT` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.UP` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.DOWN` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.FORWARD` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.BACK` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* `Vector3.ONE` is a new constant that can be used in Vector comparison operations (thanks @Aedalus) +* Geometery Mask has a new property called `invertAlpha` in WebGL, which works in the same way as the flag on the Bitmap Mask and allows you to invert the function of the stencil buffer, i.e. non-drawn shapes become invisible, and drawn shapes visible (thanks @tfelix) +* The Arcade Physics Body has a new property `maxSpeed` which limits the vector length of the Body velocity. You can set it via the method `setMaxSpeed` and it is applied in the `World.computeVelocity` method (thanks @Edwin222 @rexrainbow) +* `WebGLRenderer.snapshotArea` is a new method that allows you to grab an image of the given region of the canvas during the post-render step and have it sent to your defined callback. This is the same as `snapshot` except you control the area being grabbed, so is more efficient if you only need a smaller area. +* `WebGLRenderer.snapshotPixel` is a new method that allows you to grab a single pixel from the game canvas, post-render. It returns the result as a `Color` object to your specified callback. +* `CanvasRenderer.snapshotArea` is a new method that allows you to grab an image of the given region of the canvas during the post-render step and have it sent to your defined callback. This is the same as `snapshot` except you control the area being grabbed, so is more efficient if you only need a smaller area. +* `CanvasRenderer.snapshotPixel` is a new method that allows you to grab a single pixel from the game canvas, post-render. It returns the result as a `Color` object to your specified callback. +* `SceneManager.getScenes` is a new method that will return all current Scenes being managed by the Scene Manager. You can optionally return only active scenes and reverse the order in which they are returned in the array. +* `DOM.GetTarget` is a new helper function that will return a reference to a DOM Element based on the given string or node. +* `GameObjects.Extern` is a new special type of Game Object that allows you to pass rendering off to a 3rd party. When you create an Extern and place it in the display list of a Scene, the renderer will process the list as usual. When it finds an Extern it will flush the current batch, clear down the pipeline and prepare a transform matrix which your render function can take advantage of, if required. The Extern Game Object is used heavily by the Spine Plugin, but can also be used by other libraries such as three.js, allowing them to render directly into a Phaser game. + +### Updates + +* You can now modify `this.physics.world.debugGraphic.defaultStrokeWidth` to set the stroke width of any debug drawn body, previously it was always 1 (thanks @samme) +* `TextStyle.setFont` has a new optional argument `updateText` which will sets if the text should be automatically updated or not (thanks @DotTheGreat) +* `ProcessQueue.destroy` now sets the internal `toProcess` counter to zero. +* The `PathFollower.pathRotationVerticalAdjust` property has been removed. It was supposed to flipY a follower when it reversed path direction, but after some testing it appears it has never worked and it's easier to do this using events, so the property and associated config value are removed. The `verticalAdjust` argument from the `setRotateToPath` method has been removed as well. +* The config value `preserveDrawingBuffer` has been removed as it has never been used by the WebGL Renderer. +* `PluginManager.install` returns `null` if the plugin failed to install in all cases. +* `PluginFile` will now install the plugin into the _current_ Scene as long as the `start` or `mapping` arguments are provided. +* MATH_CONST no longer requires or sets the Random Data Generator, this is now done in the Game Config, allowing you to require the math constants without pulling in a whole copy of the RNG with it. +* The Dynamic Bitmap Text Canvas Renderer was creating a new data object every frame for the callback. It now uses the `callbackData` object instead, like the WebGL renderer does. +* `WebGLRenderer.setBlendMode` has a new optional argument `force`, which will force the given blend mode to be set, regardless of the current settings. +* The method `DisplayList.sortGameObjects` has been removed. It has thrown a runtime error since v3.3.0(!) which no-one even spotted which is a good indication of how little the method was used. The display list is automatically sorted anyway, so if you need to sort a small section of it, just use the standard JavaScript Array sort method (thanks ornyth) +* The method `DisplayList.getTopGameObject` has been removed. It has thrown a runtime error since v3.3.0(!) which no-one even spotted which is a good indication of how little the method was used (thanks ornyth) +* `WebGLRenderer.setFramebuffer` has a new optional boolean argument `updateScissor`, which will reset the scissor to match the framebuffer size, or clear it. +* `WebAudioSoundManager.onFocus` will not try to resume the Audio Context if it's still locked. +* `WebAudioSoundManager.onBlur` will not try to suspend the Audio Context if it's still locked. +* When using `ScenePlugin.add`, to add a new Scene to the Scene Manager, it didn't allow you to include the optional Scene data object. You can now pass this in the call (thanks @kainage) +* `Graphics.stroke` is a new alias for the `strokePath` method, to keep the calls consistent with the Canvas Rendering Context API. +* `Graphics.fill` is a new alias for the `fillPath` method, to keep the calls consistent with the Canvas Rendering Context API. +* `LoaderPlugin.sceneManager` is a new property that is a reference to the global Scene Manager, useful for Plugins. +* Whenever `Camera.roundPixels` was enabled it would use a bitwise operation to truncate the float (`x |= 0`) - this has been replaced across all files that used it, with a call to `Math.round` instead. This gives far better results when zooming cameras both in and out of a Scene, stopping thin gaps appearing between closely packed Game Objects. +* `AnimationManager.create` will now return a boolean `false` if the given key is invalid (i.e. undefined or falsey). +* `AnimationManager.create` will no longer raise a console warning if the animation key is already in use. Instead, it will return the animation belonging to that key. A brand new animation will only be created if the key isn't already in use. When this happens, the `add` event is emitted by the Animation Manager. If no event is emitted, the animation already existed. +* `ArcadePhysics.Body.destroy` will now only add itself to the World `pendingDestroy` list if the world property exists. This prevents `Cannot read property 'pendingDestroy' of undefined` errors if you try to delete a physics body in a callback and then immediately change Scene (which tells the physics work to also delete all bodies) +* The Animation Component `restart` method has had is sole `key` argument removed. Previously, you had to pass in the key of the animation you wished to reverse, but now you can just call the method directly, and as long as there is an animation playing, it will automatically start playing in reverse, without the nee for a key (the way it should have been originally) +* `Animation.play` and `playReverse` will now accept either a string-based key of the animation to play (like before), or you can pass in an Animation instance, and it will play that animation. +* `CanvasTexture.clear` now has 4 new optional arguments: `x, y, width, height` which allow you to define the region of the texture to be cleared. If not provided it will clear the whole texture, which is the same behavior as before. +* EarCut, the polygon triangulation library used by the Graphics and WebGL classes, has been upgraded from 2.1.1 to 2.1.4. 2.1.2 fixed a few race conditions where bad input would cause an error. 2.1.3 improved performance for bigger inputs (5-12%) and 2.1.4 fixed a race condition that could lead to a freeze on degenerate input. +* `TextureTintPipeline.batchQuad` and `batchTri` have two new optional arguments `texture` and `unit` which are used to re-set the batch texture should the method cause a batch flush. +* `TextureTintPipeline.requireTextureBatch` is a new internal method that helps speed-up the creation of texture batches. It is used in conjunction with `setTexture2D` and `pushBatch`. +* `TextureTintPipeline.flush` and `TextureTintPipeline.pushBatch` have been optimized to handle zero based texture units as priority. They've also been refactored to avoid creation of empty texture batches. +* The `WebGLRenderer.setTexture2D` method has a new optional argument `flush` which controls if the pipeline is flushed if the given texture is new, or not. This is used internally to skip flushing during an existing flush. +* The Tilemap Layer `width` and `height` properties are now based on the tilemap tile sizes multiplied by the layer dimensions. This corrects an issue with layer sizes being wrong if you called `setBaseTileSize` on a Map. +* The WebGLRenderer will now clear the framebuffer at the start of every render. +* `WebGLRenderer.setScissor` now has a new optional argument `drawingBufferHeight` which allows you to specify the drawing buffer height, rather than use the renderers default value. +* `WebGLRenderer.pushScissor` now has a new optional argument `drawingBufferHeight` which allows you to specify the drawing buffer height, rather than use the renderers default value. +* `WebGLRenderer.preRender` now calls `gl.clearColor` in order to restore the background clear color in case something, like a Render Texture, has changed it. +* `Map.set` will now update an existing value if you provide it with a key that already exists within the Map. Previously, if you tried to set the value of a key that existed it would be skipped. +* `MatterSprite` would set its `type` property to be `Image`. It now sets it to be `Sprite` as it should do. +* `Matter.TileBody.setFromTileCollision` no longer checks if the shape is concave or convex before modifying the vertices, as the update to the Matter.js lib in 3.12 stopped this from working with Tiled collision shapes. +* The Scene `transitionstart` event is now dispatched by the Target Scene of a transition, regardless if the Scene has a `create` method or not. Previously, it was only dispatched if the Scene had a create method. +* The Loader will now allow an XHR status of 0 as success too. Normally only status 200 would be accepted as success, but 0 is returned when a file is loaded from the local filesystem (file://). This happens, for example, when opening the index.html of a game in a browser directly, or when using Cordova on iOS. Fix #3464 (thanks @Ithamar) +* `Tween.restart` now returns the Tween instance (thanks @rexrainbow) +* `Tween.play` now returns the Tween instance (thanks @rexrainbow) +* `Tween.seek` now returns the Tween instance (thanks @rexrainbow) +* `Tween.complete` now returns the Tween instance (thanks @rexrainbow) +* `Tween.stop` now returns the Tween instance (thanks @rexrainbow) +* `List.sort` now has an optional parameter `handler` which allows you to provide your own sort handling function (thanks @jcyuan) +* `Container.sort` now has an optional parameter `handler` which allows you to provide your own sort handling function (thanks @jcyuan) +* The WebGLRenderer method `canvasToTexture` will now only set the filter to be `NEAREST` if `antialias` is disabled in the game config (i.e. when running in pixelArt mode). This means that Text objects, and other Canvas backed textures, now render with anti-aliasing if everything else does. You can disable this on a per-object basis by calling `texture.setFilter(1)` on them. +* `CanvasRenderer.snapshotCallback`, `snapshotType` and `snapshotEncoder` have all been removed as they are no longer required. +* `CanvasRenderer.snapshotState` is a new object that contains the snapshot configuration data, the same as the WebGL Renderer. +* The signature of the `WebGLSnapshot` function has changed. It now takes a Snapshot Configuration object as the second parameter. +* The signature of the `CanvasSnapshot` function has changed. It now takes a Snapshot Configuration object as the second parameter. +* A Tween Timeline will now set it's internal destroy state _before_ calling either the `onComplete` callback or sending the `COMPLETE` event. This means you can now call methods that will change the state of the Timeline, such as `play`, during the callback handlers, where-as before doing this would have had the internal state changed immediately, preventing it (thanks Lucas Knight) +* The `AddToDOM` method has had the `overflowHidden` argument removed. The DOM element the canvas is inserted into no longer has `overflow: hidden` applied to its style. If you wish to have this, please add it directly via CSS. + +### Bug Fixes + +* The Rectangle Shape object wouldn't render if it didn't have a stroke, or any other objects on the display list (thanks mliko) +* When using a font string instead of setting `fontFamily`, `fontSize` and `fontStyle` in either `Text.setStyle` or `setFont`, the style properties wouldn't get set. This isn't a problem while creating the text object, only if modifying it later (thanks @DotTheGreat) +* `Text.toJSON` wasn't saving the font style when using the "font" shorthand to create it. It now saves it correctly. Fix #4141 (thanks @divillysausages) +* Disabling camera bounds and then moving the camera to an area in a Tilemap that did not have any tile information would throw an `Uncaught Reference error` as it tried to access tiles that did not exist (thanks @Siyalatas) +* Fixed an issue where Sprite Sheets being extracted from a texture atlas would fail if the sheet was either just a single column or single row of sprites. Fix #4096 (thanks @Cirras) +* If you created an Arcade Physics Group without passing a configuration object, and passing an array of non-standard children, it would throw a classType runtime error. It now creates a default config object correctly (thanks @pierpo) +* The `Camera.cull` method has been restructured so it now calculates if a Game Object is correctly in view or not before culling it. Although not used internally, if you need to cull objects for a camera, you can now safely use this method. Fix #4092 (thanks @Cirras) +* The Tiled Parser would ignore animated tile data if it was in the new Tiled 1.2 format. This is now accounted for, as well as 1.0 (thanks @nkholski) +* `Array.Matrix.ReverseRows` was actually reversing the columns, but now reverses the rows. +* `Array.Matrix.ReverseColumns` was actually reversing the rows, but now reverses the columns. +* UnityAtlas now sets the correct file type key if using a config file object. +* Starting with version 3.13 in the Canvas Renderer, it was possible for long-running scripts to start to get bogged-down in `fillRect` calls if the game had a background color set. The context is now saved properly to avoid this. Fix #4056 (thanks @Aveyder) +* Render Textures created larger than the size of the default canvas would be automatically clipped when drawn to in WebGL. They now reset the gl scissor and drawing height property in order to draw to their full size, regardless of the canvas size. Fix #4139 (thanks @chaoyang805 @iamchristopher) +* The `cameraFilter` property of a Game Object will now allow full bitmasks to be set (a value of -1), instead of just those > 0 (thanks @stuartkeith) +* The `PathFollower.startFollow` method now properly uses the `startAt` argument to the method, so you can start a follower off at any point along the path. Fix #3688 (thanks @DannyT @diteix) +* Static Circular Arcade Physics Bodies now render as circles in the debug display instead of showing their rectangle bounds (thanks @maikthomas) +* Changing the mute flag on an `HTML5AudioSound` instance, via the `mute` setter, now works as it does via the Sound Manager (thanks @Waclaw-I @neon-dev) +* Changing the volume on an `HTML5AudioSound` instance, via the `volume` setter, now works as it does via the Sound Manager (thanks @Waclaw-I) +* The Dynamic Tilemap Layer WebGL renderer was drawing tiles at the incorrect position if the layer was scaled. Fix #4104 (thanks @the-realest-stu) +* `Tile.tileset` now returns the specific Tileset associated with the tile rather than an array of them. Fix #4095 (thanks @quadrupleslap) +* `Tile.getCollisionGroup` wouldn't return the correct Group after the change to support multiple Tilesets. It now returns the group properly (thanks @jbpuryear) +* `Tile.getTileData` wouldn't return the correct data after the change to support multiple Tilesets. It now returns the tile data properly (thanks @jbpuryear) +* The `GetTileAt` and `RemoveTileAt` components would error with "Cannot read property 'index' of undefined" if the tile was undefined rather than null. It now handles both cases (thanks @WaSa42) +* Changing `TileSprite.width` or `TileSprite.height` will now flag the texture as dirty and call `updateDisplayOrigin`, allowing you to resize TileSprites dynamically in both Canvas and WebGL. +* `RandomDataGenerator.shuffle` has been fixed to use the proper modifier in the calculation allowing for a more even distribution (thanks wayfinder) +* The Particle Emitter was not recycling dead particles correctly so it was creating new objects every time it emitted (the old particles were then left to the browsers gc to clear up). This has now been recoded so the emitter will properly keep track of dead particles and re-use them (thanks @Waclaw-I for the initial PR) +* `ParticleEmitter.indexSortCallback` has been removed as it's no longer required. +* `Particle.index` has been removed as it's no longer required. Particles don't need to keep track of their index any more. +* The Particle Emitter no longer needs to call the StableSort.inplace during its preUpdate, saving cpu. +* `Particle.resetPosition` is a new method that is called when a particle dies preparing it for firing again in the future. +* The Canvas `SetTransform` method would save the context state, but it wasn't restored at the end in the following Game Objects: Dynamic Bitmap Text, Graphics, Arc, Curve, Ellipse, Grid, IsoBox, IsoTriangle, Line, Polygon, Rectangle, Star and Triangle. These now all restore the context, meaning if you're using non-canvas sized cameras in Canvas mode, it will now render beyond just the first custom camera. +* `Utils.Array.MoveUp` wouldn't let you move an array element to the top-most index in the array. This also impacted `Container.moveUp`. +* The Texture Tint Pipeline had a logic error that would cause every 2001st quad to either be invisible, or pick-up the texture of the 2000th quad by mistake. The `batchQuad` and `batchTri` methods how handle re-assigning the batch texture if they cause a batch flush as part of their process. +* Rotating Sprites that used a Normal Map wouldn't rotate the normal map with it causing the lighting effects to become irregular. The normal map vectors are now rotated correctly (thanks @sercant for the PR and @fazzamatazz and @ysraelJMM for the report) +* Changing `scaleX` or `scaleY` on a `MatterImage` or `MatterSprite` would cause the body scale to become distorted as the setters didn't use the correct factor when resetting the initial scale. Fix #4206 (thanks @YannCaron) +* `StaticBody.reset` in Arcade Physics would ignore the `x` and `y` values given to it. If given, they're now used to reset the parent Game Object before the body is updated. Fix #4224 (thanks @samme) +* Static Tilemap Layers wouldn't render correctly if the layer used a tileset with a different size to the base map data (set via `setBaseTileSize`). They now render correctly in WebGL and Canvas regardless of the base tile size. +* When using `RenderTexture.fill`, the `alpha` argument would be ignored in Canvas mode. It's now used when filling the RenderTexture. +* Fixed an issue in `WebGLRenderer.setScissor` where it was possible to try and compare the scissor size to a non-current scissor if called outside of the render loop (i.e. from `RenderTexture.fill`) (thanks @hackhat) +* `RenderTexture.fill` in WebGL would use `gl.clear` and a clear color to try and fill the Render Texture. This only worked for full-canvas sized RenderTextures that didn't have a camera zoom applied. It has now been swapped to use the `drawFillRect` method of the Texture Tint Pipeline, allowing it to work properly regardless of camera zoom or size. +* `Container.getFirst` was using an incorrect Array Utils function `GetFirstElement` when it should have been using `GetFirst`. It now uses the correct function. Fix #4244 (thanks @miran248) +* `List.getFirst` was using an incorrect Array Utils function `GetFirstElement` when it should have been using `GetFirst`. It now uses the correct function. Fix #4244 (thanks @miran248) +* Fixed an issue where changing the viewport or size of a Camera belonging to a RenderTexture wouldn't impact the rendering and objects will still render outside of the viewport range. It's now converted to a proper gl scissor rect by the renderer, meaning you can limit the area rendered to by adjusting the internal Render Texture cameras viewport. Fix #4243 (thanks @hackhat) +* `CanvasTexture.destroy` is a new method that specifically handles the destruction of the CanvasTexture and all of its associated typed arrays. This prevents a memory leak when creating and destroying lots of RenderTextures (which are CanvasTexture backed). Fix #4239 (thanks @sjb933) +* The Alpha, Flip and Origin components have been removed from the Mesh Game Object (and by extension, Quad as well) as they are not used in the renderer and should be manipulated via the Mesh properties. Fix #4188 (thanks @enriqueto) +* The `processDomCallbacks` method in the Input Manager wasn't correctly clearing the `once` arrays. Responsibility for this has now been passed to the queue methods `queueTouchStart`, `queueTouchMove`, `queueTouchEnd`, `queueMouseDown`, `queueMouseMove` and `queueMouseUp`. Fix #4257 (thanks @iArePJ) +* Arcade Physics now manages when `postUpdate` should be applied better, stopping it from gaining a zero delta during a further check in the same frame. This fixes various issues, including the mass collision test demo. Fix #4154 (thanks @samme) +* Arcade Physics could trigger a `collide` event on a Body even if it performing an overlap check, if the `onCollide` property was true (thanks @samme) +* TileSprites no longer cause a crash when using the Headless mode renderer. Fix #4297 (thanks @clesquir) +* The WebGLRenderer will now apply a transparent background if `transparent = true` in the game config (thanks @gomachan7) +* `List.sort` was missing the scope required for the sort handler, this is now correctly provided internally. Fix #4241 (thanks @jcyuan) +* `Container.sort` was missing the scope required for the sort handler, this is now correctly provided internally. Fix #4241 (thanks @jcyuan) +* `DataManager.pop` would emit the DataManager instance, instead of the parent, as the first event argument. It now emits the parent as it should do. Fix #4186 (thanks @gadelan) +* The `GetValue` function wasn't checking for the existance of '.' in the config property name correctly, causing the branch to always be taken (thanks @kyranet) +* Safari had permission problems playing HTML5 Audio files on Mac OS. Due to the changes in the input event system audio now plays properly based on user interactions. You still can't play it automatically, though, it will always require a user gesture to begin. Fix #4217 (thanks @increpare) + +### Examples and TypeScript + +Thanks to the following for helping with the Phaser 3 Examples and TypeScript definitions, either by reporting errors, or even better, fixing them: + +@guilhermehto @samvieten @darkwebdev @RoryO @snowbillr @slothyrulez @jcyuan @jestarray @CzBiX + +### Phaser Doc Jam + +The Phaser Doc Jam was a community-backed effort to try and get the Phaser 3 API documentation to 100% coverage. The Doc Jam is now over and I offer my thanks to the following who helped with docs in this release: + +@16patsle - @gurungrahul2 - @icbat - @samme - @telinc1 - anandu pavanan - blackhawx - candelibas - Diego Romero - doronlinder - Elliott Wallace - eric - Georges Gabereau - Haobo Zhang - henriacle - jak6jak - Jake Jensen - James Van Roose - JamesSkemp - joelahoover - Joey - madclaws - marc136 - Mihail Ilinov - naum303 - NicolasRoehm - nuane - rejacobson - Robert Kowalski - rodri042 - rootasjey - sawamara - scottwestover - sir13tommy - stetso - therealsamf - Tigran - willblackmore - zenwaichi + +Also, the following helped with the docs outside of the Doc Jam: + +@bryanwood @jestarray @matosummer @tfelix @imilo @BigZaphod @OmarShehata @16patsle @jcyuan @iam13islucky @FractalBobz Endre + +## Version 3.15.1 - Batou - 16th October 2018 + +* Re-enabled Input Manager resizing, which had been left disabled by mistake. + +## Version 3.15.0 - Batou - 16th October 2018 + +Note: We are releasing this version ahead of schedule in order to make some very important iOS performance and input related fixes available. It does not contain the new Scale Manager or Spine support, both of which have been moved to 3.16 as they require a few more weeks of development. + +### New Features + +* You can now set the `maxLights` value in the Game Config, which controls the total number of lights the Light2D shader can render in a single pass. The default is 10. Be careful about pushing this too far. More lights = less performance. Close #4081 (thanks @FrancescoNegri) +* `Rectangle.SameDimensions` determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* An ArcadePhysics Group can now pass `{ enable: false }` in its config to disable all the member bodies (thanks @samme) +* `Body.setEnable` is a new chainable method that allows you to toggle the enable state of an Arcade Physics Body (thanks @samme) +* `KeyboardPlugin.resetKeys` is a new method that will reset the state of any Key object created by a Scene's Keyboard Plugin. +* `Pointer.wasCanceled` is a new boolean property that allows you to tell if a Pointer was cleared due to a `touchcancel` event. This flag is reset during the next `touchstart` event for the Pointer. +* `Pointer.touchcancel` is a new internal method specifically for handling touch cancel events. It has the same result as `touchend` without setting any of the up properties, to avoid triggering up event handlers. It will also set the `wasCanceled` property to `true`. + +### Updates + +* `WebGLRenderer.deleteTexture` will check to see if the texture it is being asked to delete is the currently bound texture or not. If it is, it'll set the blank texture to be bound after deletion. This should stop `RENDER WARNING: there is no texture bound to the unit 0` errors if you destroy a Game Object, such as Text or TileSprite, from an async or timed process (thanks jamespierce) +* The `RequestAnimationFrame.step` and `stepTimeout` functions have been updated so that the new Frame is requested from raf before the main game step is called. This allows you to now stop the raf callback from within the game update or render loop. Fix #3952 (thanks @tolimeh) +* If you pass zero as the width or height when creating a TileSprite it will now use the dimensions of the texture frame as the size of the TileSprite. Fix #4073 (thanks @jcyuan) +* `TileSprite.setFrame` has had both the `updateSize` and `updateOrigin` arguments removed as they didn't do anything for TileSprites and were misleading. +* `CameraManager.remove` has a new argument `runDestroy` which, if set, will automatically call `Camera.destroy` on the Cameras removed from the Camera Manager. You should nearly always allow this to happen (thanks jamespierce) +* Device.OS has been restructured to allow fake UAs from Chrome dev tools to register iOS devices. +* Texture batching during the batch flush has been implemented in the TextureTintPipeline which resolves the issues of very low frame rates, especially on iOS devices, when using non-batched textures such as those used by Text or TileSprites. Fix #4110 #4086 (thanks @ivanpopelyshev @sachinhosmani @maximtsai @alexeymolchan) +* The WebGLRenderer method `canvasToTexture` has a new optional argument `noRepeat` which will stop it from using `gl.REPEAT` entirely. This is now used by the Text object to avoid it potentially switching between a REPEAT and CLAMP texture, causing texture black-outs (thanks @ivanpopelyshev) +* `KeyboardPlugin.resetKeys` is now called automatically as part of the Keyboard Plugin `shutdown` method. This means, when the plugin shuts down, such as when stopping a Scene, it will reset the state of any key held in the plugin. It will also clear the queue of any pending events. +* The `Touch Manager` has been rewritten to use declared functions for all touch event handlers, rather than bound functions. This means they will now clear properly when the TouchManager is shut down. +* There is a new Input constant `TOUCH_CANCEL` which represents canceled touch events. + +### Bug Fixes + +* Fixed a bug in the canvas rendering of both the Static and Dynamic Tilemap Layers where the camera matrix was being multiplied twice with the layer, causing the scale and placement to be off (thanks galerijanamar) +* If you set `pixelArt` to true in your game config (or `antialias` to false) then TileSprites will now respect this when using the Canvas Renderer and disable smoothing on the internal fill canvas. +* TileSprites that were set to be interactive before they had rendered once wouldn't receive a valid input hit area, causing input to fail. They now define their size immediately, allowing them to be made interactive without having rendered. Fix #4085 (thanks @DotTheGreat) +* The Particle Emitter Manager has been given a NOOP method called `setBlendMode` to stop warnings from being thrown if you added an emitter to a Container in the Canvas renderer. Fix #4083 (thanks @maximtsai) +* The `game.context` property would be incorrectly set to `null` after the WebGLRenderer instance was created (thanks @samme) +* The Touch Manager, Input Manager and Pointer classes all now handle the `touchcancel` event, such as triggered on iOS when activating an out of browser UI gesture, or in Facebook Instant Games when displaying an overlay ad. This should prevent issues with touch input becoming locked on iOS specifically. Fix #3756 (thanks @sftsk @sachinhosmani @kooappsdevs) + +## Version 3.14.0 - Tachikoma - 1st October 2018 + +### Tilemap New Features, Updates and Fixes + +* Both Static and Dynamic Tilemap layers now support rendering multiple tilesets per layer in both Canvas and WebGL. To use multiple tilesets pass in an array of Tileset objects, or strings, to the `createStaticLayer` and `createDynamicLayer` methods respectively. +* `Tilemap.createStaticLayer` now supports passing either a Tileset reference, or a string, or an array of them as the 2nd argument. If strings, the string should be the Tileset name (usually defined in Tiled). +* `Tilemap.createDynamicLayer` now supports passing either a Tileset reference, or a string, or an array of them as the 2nd argument. If strings, the string should be the Tileset name (usually defined in Tiled). +* `Tilemap.createBlankDynamicLayer` now supports passing either a Tileset reference, or a string, or an array of them as the 2nd argument. If strings, the string should be the Tileset name (usually defined in Tiled). +* Static Tilemap Layers now support tile rotation and flipping. Previously this was a feature only for Dynamic Tilemap Layers, but now both have it. Close #4037 (thanks @thisredone) +* `Tilemap.getTileset` is a new method that will return a Tileset based on its name. +* `ParseTilesets` has been rewritten so it will convert the new data structures of Tiled 1.2 into the format expected by Phaser, allowing you to use either Tiled 1.2.x or Tiled 1.1 JSON exports. Fix #3998 (thanks @martin-pabst @halgorithm) +* `Tilemap.setBaseTileSize` now sets the size into the LayerData `baseTileWidth` and `baseTileHeight` properties accordingly. Fix #4057 (thanks @imilo) +* Calling `Tilemap.renderDebug` ignored the layer world position when drawing to the Graphics object. It will now translate to the layer position before drawing. Fix #4061 (thanks @Zax37) +* Calling `Tilemap.renderDebug` ignored the layer scale when drawing to the Graphics object. It will now scale the layer before drawing. Fix #4026 (thanks @JasonHK) +* The Static Tilemap Layer would stop drawing all tiles from that point on, if it encountered a tile which had invalid texture coordinates (such as a tile from another tileset). It now skips invalid tiles properly again. Fix #4002 (thanks @jdotrjs) +* If you used a RenderTexture as a tileset then Dynamic Tilemap Layers would render the tiles inversed on the y-axis in WebGL. Fix #4017 (thanks @s-s) +* If you used a scaled Dynamic Tilemap Layer and rotated or flipped tiles, the tiles that were rotated or flipped would be positioned incorrectly in WebGL. Fix #3778 (thanks @nkholski) +* `StaticTilemapLayer.tileset` is now an array of Tileset objects, where-as before it was a single reference. +* `StaticTilemapLayer.vertexBuffer` is now an array of WebGLBuffer objects, where-as before it was a single instance. +* `StaticTilemapLayer.bufferData` is now an array of ArrayBuffer objects, where-as before it was a single instance. +* `StaticTilemapLayer.vertexViewF32` is now an array of Float3Array objects, where-as before it was a single instance. +* `StaticTilemapLayer.vertexViewU32` is now an array of Uint32Array objects, where-as before it was a single instance. +* `StaticTilemapLayer.dirty` is now an array of booleans, where-as before it was a single boolean. +* `StaticTilemapLayer.vertextCount` is now an array of integers, where-as before it was a single integer. +* `StaticTilemapLayer.updateVBOData()` is a new private method that creates the internal VBO data arrays for the WebGL renderer. +* The `StaticTilemapLayer.upload()` method has a new parameter `tilesetIndex` which controls which tileset to prepare the VBO data for. +* The `StaticTilemapLayer.batchTile()` method has a new parameter `tilesetIndex` which controls which tileset to batch the tile for. +* `StaticTilemapLayer.setTilesets()` is a new private method that creates the internal tileset references array. +* `DynamicTilemapLayer.tileset` is now an array of Tileset objects, where-as before it was a single reference. +* `DynamicTilemapLayer.setTilesets()` is a new private method that creates the internal tileset references array. + +### New Features + +* `bodyDebugFillColor` is a new Matter Physics debug option that allows you to set a color used when drawing filled bodies to the debug Graphic. +* `debugWireframes` is a new Matter Physics debug option that allows you to control if the wireframes of the bodies are used when drawing to the debug Graphic. The default is `true`. If enabled bodies are not filled. +* `debugShowInternalEdges` is a new Matter Physics debug option that allows you to set if the internal edges of a body are rendered to the debug Graphic. +* `debugShowConvexHulls` is a new Matter Physics debug option that allows you to control if the convex hull of a body is drawn to the debug Graphic. The default is `false`. +* `debugConvexHullColor` is a new Matter Physics debug option that lets you set the color of the convex hull, if being drawn to the debug Graphic. +* `debugShowSleeping` is a new Matter Physics debug option that lets you draw sleeping bodies at 50% opacity. +* `Curves.Ellipse.angle` is a new getter / setter that handles the rotation of the curve in degrees instead of radians. + +### Updates + +* The Loader has been updated to handle the impact of you destroying the game instance while still processing files. It will no longer throw cache and texture related errors. Fix #4049 (thanks @pantoninho) +* `Polygon.setTo` can now take a string of space separated numbers when creating the polygon data, i.e.: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'`. This update also impacts the Polygon Shape object, which can now also take this format as well. +* The `poly-decomp` library, as used by Matter.js, has been updated to 0.3.0. +* `Matter.verts`, available via `this.matter.verts` from within a Scene, is a quick way of accessing the Matter Vertices functions. +* You can now specify the vertices for a Matter `fromVerts` body as a string. +* `TextureTintPipeline.batchTexture` has a new optional argument `skipFlip` which allows you to control the internal render texture flip Y check. +* The Device.OS check for `node` will now do a `typeof` first to avoid issues with rollup packaged builds needing to shim the variable out. Fix #4058 (thanks @hollowdoor) +* Arcade Physics Bodies will now sync the display origin of the parent Game Object to the body properties as part of the `updateBounds` call. This means if you change the origin of an AP enabled Game Object, after creation of the body, it will be reflected in the body position. This may or may not be a breaking change for your game. Previously it was expected that the origin should always be 0.5 and you adjust the body using `setOffset`, but this change makes a bit more sense logically. If you find that your bodies are offset after upgrading to this version then this is likely why. Close #4052 (thanks @SolarOmni) +* The `Texture.getFramesFromTextureSource` method has a new boolean argument `includeBase`, which defaults to `false` and allows you to set if the base frame should be returned into the array or not. +* There is a new Animation Event that is dispatched when an animation restarts. Listen for it via `Sprite.on('animationrestart')`. +* All of the Animation Events now pass the Game Object as the final argument, this includes `animationstart`, `animationrestart`, `animationrepeat`, `animationupdate` and `animationcomplete`. +* `Curves.Ellipse.rotation` is a getter / setter that holds the rotation of the curve. Previously it expected the value in degrees and when getting it returned the value in radians. It now expects the value in radians and returns radians to keep it logical. +* `Set.size` will now only set the new size if the value is smaller than the current size, truncating the Set in the process. Values larger than the current size are ignored. +* Arcade Physics `shutdown` will check to see if the world instance still exists and only try removing it if so. This prevents errors when stopping a world and then destroying it at a later date. +* `Text.setFont`, `Text.setFontFamily`, `Text.setFontStyle` and `Text.setStroke` will no longer re-measure the parent Text object if their values have not changed. + +### Bug Fixes + +* GameObjects added to and removed from Containers no longer listen for the `shutdown` event at all (thanks Vitali) +* Sprites now have `preDestroy` method, which is called automatically by `destroy`. The method destroys the Animation component, unregistering the `remove` event in the process and freeing-up resources. Fix #4051 (thanks @Aveyder) +* `UpdateList.shutdown` wasn't correctly iterating over the pending lists (thanks @felipeprov) +* Input detection was known to be broken when the game resolution was !== 1 and the Camera zoom level was !== 1. Fix #4010 (thanks @s-s) +* The `Shape.Line` object was missing a `lineWidth` property unless you called the `setLineWidth` method, causing the line to not render in Canvas only. Fix #4068 (thanks @netgfx) +* All parts of Matter Body now have the `gameObject` property set correctly. Previously only the first part of the Body did. +* When using `MatterGameObject` and `fromVerts` as the shape type it wouldn't pass the values to `Bodies.fromVertices` because of a previous conditional. It now passes them over correctly and the body is only set if the result is valid. +* The `Texture.getFramesFromTextureSource` method was returning an array of Frame names by mistake, instead of Frame references. It now returns the Frames themselves. +* When using `CanvasTexture.refresh` or `Graphics.generateTexture` it would throw WebGL warnings like 'bindTexture: Attempt to bind a deleted texture'. This was due to the Frames losing sync with the glTexture reference used by their TextureSource. Fix #4050 (thanks @kanthi0802) +* Fixed an error in the `batchSprite` methods in the Canvas and WebGL Renderers that would incorrectly set the frame dimensions on Sprites with the crop component. This was particularly noticeable on Sprites with trimmed animation frames (thanks @sergeod9) +* Fixed a bug where the gl scissor wasn't being reset during a renderer resize, causing it to appear as if the canvas didn't resize properly when `autoResize` was set to `true` in the game config. Fix #4066 (thanks @Quinten @hsan999) +* If a Game instance is destroyed without using the `removeCanvas` argument, it would throw exceptions in the `MouseManager` after the destroy process has run, as the event listeners were not unbound. They're not unbound, regardless of if the parent canvas is removed or not. Fix #4015 (thanks @garethwhittaker) + +### Examples and TypeScript + +A huge thanks to @presidenten for his work on the Phaser 3 Examples. You'll notice they now have a lovely screen shots for every example and the scripts generate them automatically :) + +Also, thanks to the following for helping with the Phaser 3 Examples and TypeScript definitions, either by reporting errors, or even better, fixing them: + +@madanus @truncs @samme + +### Phaser Doc Jam + +The [Phaser Doc Jam](http://docjam.phaser.io) is an on-going effort to ensure that the Phaser 3 API has 100% documentation coverage. Thanks to the monumental effort of myself and the following people we're now really close to that goal! My thanks to: + +31826615 - @16patsle - @bobonthenet - @rgk - @samme - @shaneMLK - @wemyss - ajmetal - andiCR - Arian Fornaris - bsparks - Carl - cyantree - DannyT - Elliott Wallace - felixnemis - griga - Hardylr - henriacle - Hsaka - icbat - Kanthi - Kyle - Lee - Nathaniel Foldan - Peter Pedersen - rootasjey - Sam Frantz - SBCGames - snowbillr - Stephen Hamilton - STuFF - TadejZupancic - telinc1 + +If you'd like to help finish off the last parts of documentation then take a look at the [Doc Jam site](http://docjam.phaser.io). + +## Version 3.13.0 - Yuuki - 20th September 2018 + +### Facebook Instant Games Plugin + +Phaser 3.13 introduces the new Facebook Instant Games Plugin. The plugin provides a seamless bridge between Phaser and version 6.2 of the Facebook Instant Games SDK. Every single SDK function is available via the plugin and we will keep track of the official SDK to make sure they stay in sync. + +The plugin offers the following features: + +* Easy integration with the Phaser Loader so load events update the Facebook progress circle. +* Events for every plugin method, allowing the async calls of the SDK to be correctly inserted into the Phaser game flow. When SDK calls resolve they will surface naturally as a Phaser event and you'll know you can safely act upon them without potentially doing something mid-way through the game step. +* All Plugin methods check if the call is part of the supported APIs available in the SDK, without needing to launch an async request first. +* Instant access to platform, player and locale data. +* Easily load player photos directly into the Texture Manager, ready for use with a Game Object. +* Subscribe to game bots. +* The plugin has a built-in Data Manager which makes dealing with data stored on Facebook seamless. Just create whatever data properties you need and they are automatically synced. +* Support for FB stats, to retrieve, store and increment stats into cloud storage. +* Save Session data with built-in session length validation. +* Easy context switching, to swap between game instances and session data retrieval. +* Easily open a Facebook share, invite, request or game challenge window and populate the text and image content using any image stored in the Texture cache. +* Full Leaderboard support. Retrieve, scan and update leaderboard entries, as well as player matching. +* Support for in-app purchases, with product catalogs, the ability to handle purchases, get past purchases and consume previously unlocked purchases. +* Easily preload a set of interstitial ads, in both banner and video form, then display the ad at any point in your game, with in-built tracking of ads displayed and inventory available. +* Plus other features, such as logging to FB Analytics, creating short cuts, switching games, etc. + +The plugin is fully documented and official tutorials and project templates will follow shortly. + +### New Shape Game Objects + +Phaser 3.13 has a new Game Object called `Shape`, which by itself isn't much use because it's a base class. However, extending that class are 11 different types of Shape (with more to come) and you can use it to create your own custom Shapes as well. Shapes are added to the display list in the exact same way as any other Game Object. For example: + +``` +this.add.rectangle(400, 300, 500, 120, 0x00ff00); +``` + +Here we're creating a new Rectangle shape. It's positioned at 400 x 300 in the Scene and has a size of 500 x 120 pixels. The final value is the fill color. + +The thing to remember is that you can treat this Shape just like you'd treat any other Game Object. You can scale it, rotate it, alpha it, blend mode it, change its origin, give it a Camera scroll factor, put it inside a Container or Group, give it input abilities or even give it a physics body. It is, to all intents and purposes, a normal Game Object. The only difference is that when rendering it uses its own special bit of display code. + +The shapes available are as follows: + +* `GameObject.Arc` - The arc allows you to draw either a circle, or part of a circle. You can set the start and end angle, if the rotation is clockwise or not, and even set the number of iterations the arc will use during rendering. +* `GameObject.Curve` - The Curve Shape can take any Phaser Curve object, such as a Spline or Bezier Curve, and add it to the display list. +* `GameObject.Ellipse` - An ellipse shape, which is essentially a circle with a differing width and height. It can be filled or stroked (or both!) and as with the arc you can set the 'smoothness' of it, allowing you to decrease the number of points used when creating its polygon data. +* `GameObject.Grid` - The Grid Shape object allows you to generate them. You can set the width and height of the grid itself, as well as for the grid cells. The grid can either have a single color, or alternating cell colors and even have outline spacing between the cells, or not. +* `GameObject.Line` - Create a Line Shape drawn between any two points, with a color and thickness. In WebGL you can also specify a different thickness for the start and end of the line. +* `GameObject.Polygon` - A Polygon is effectively a list of points that is drawn between. The points can be provided in a number of different ways (as Vec2 objects, as an array, etc) and then you can either fill or stroke the resulting shape, or both. +* `GameObject.Rectangle` - Simple, but powerful and endlessly useful. Set a width and height and it'll display a Rectangle, with control over the size, fill color and stroke color. +* `GameObject.Star` - The Star shape does as its name suggests: it displays a star. You can control the number of points in the star as well as the inner and outer radius of it. +* `GameObject.Triangle` - A Triangular shape with full control over the points used to make it and its fill and stroke colors. Internally it uses the `batchFillTriangle` method in WebGL, making it actually faster to draw than a Quad! Use them happily for bullets or abstract space ships, or anything else you feel like. +* `GameObject.IsoTriangle` - This draws an isometric triangle, like a pyramid. You can control the colors of each face, if the pyramid is upside down or not and the width and height of it. +* `GameObject.IsoBox` - This draws an isometric box. You can set the colors for each face of the box, as well as the projection angle and also which of the 3 faces are drawn. + +All of the Shape objects render in both Canvas and WebGL and are available via the Game Object Factory. + +### Pointer and Input Event Updates + +The specificity if the input events has been changed to allow you more control over event handling. Previously, the InputPlugin would emit the global `pointerdown` event first, and then the Game Object itself would emit the `pointerdown` event and finally the InputPlugin would emit the `gameobjectdown` event. + +The order has now changed. The Game Object will dispatch its `pointerdown` event first. The InputPlugin will then dispatch `gameobjectdown` and finally the less specific of them all, `pointerdown` will be dispatched. + +New in 3.13 is the ability to cancel this at any stage. All events are now sent an event object which you can call `event.stopPropagation()` on. This will immediately stop any further listeners from being invoked. If you call `stopPropagation()` after the first Game Object `pointerdown` event, then no more Game Object's will receive their callbacks and the InputPlugin will not dispatch either of its events. + +This change has been introduced for `pointerdown`, `pointerup`, `pointermove`, `pointerover` and `pointerout`. No other data is included in the `event` object in this release. + +* The Game Object `pointerdown` callback signature has changed. It used to send `pointer, x, y, camera` to the listener. It now sends `pointer, x, y, event` to the listener. If you still need the `camera` property you can get it from `pointer.camera`. +* The Game Object `gameobjectdown` callback signature has a new argument. It now sends `event` as the 3rd argument. +* The `pointerdown` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerdown` and `gameobjectdown`). This gives you the chance to cancel the event before the global listener receives it. +* The Game Object `pointerup` callback signature has a new argument. It now sends the `event` as the 4th argument. +* The Game Object `gameobjectup` callback signature has a new argument. It now sends `event` as the 3rd argument. +* The `pointerup` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerup` and `gameobjectup`). This gives you the chance to cancel the event before the global listener receives it. +* The Game Object `pointermove` callback signature has a new argument. It now sends the `event` as the 4th argument. +* The Game Object `gameobjectmove` callback signature has a new argument. It now sends `event` as the 3rd argument. +* The `pointermove` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointermove` and `gameobjectmove`). This gives you the chance to cancel the event before the global listener receives it. +* The Game Object `pointerover` callback signature has a new argument. It now sends the `event` as the 4th argument. +* The Game Object `gameobjectover` callback signature has a new argument. It now sends `event` as the 3rd argument. +* The `pointerover` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerover` and `gameobjectover`). This gives you the chance to cancel the event before the global listener receives it. +* The Game Object `pointerout` callback signature has a new argument. It now sends the `event` as the 2nd argument. +* The Game Object `gameobjectout` callback signature has a new argument. It now sends `event` as the 3rd argument. +* The `pointerout` event, as dispatched by the InputPlugin, is now sent _after_ the Game Object specific events (`GameObject.pointerout` and `gameobjectout`). This gives you the chance to cancel the event before the global listener receives it. + +### Game Object List Updates + +When Sprite's are created they are added to two lists within the Scene - the Display List and the Update List. Under 3.12 when a Scene was shut down it would emit a `shutdown` event, which Sprites listened out for. When they received it, they would destroy themselves. + +After [profiling and testing](https://github.com/photonstorm/phaser/issues/4028) this process has changed slightly. Game Object's no longer listen for the Scene `shutdown` event. Instead, the Display List and Update List will iterate their children and call `destroy` on them in turn. If being destroyed by a Scene in this way, the child will skip several expensive operations in its destroy function. More importantly, in busy Scenes you no longer need thousands of event listeners registered. The result is that changing Scene is now up to 100% faster than before. You need not change your code to benefit from this, however, if you were relying on custom Game Objects listening for the Scene `shutdown` event natively, then this is no longer the case and you'll have to manually add that listener to your classes. + +* The UpdateList will now clear out its internal `_list`, `_pendingRemoval` and `_pendingInsertion` lists on shutdown. Before, it would only clear `_list`. +* `GameObject.destroy` has a new optional boolean argument `fromScene`, which controls how the destroy process flows. + +### Camera Render to Texture + +In 3.12 a new Camera method called `setRenderToTexture` was introduced. However, it had known issues so was placed under the experimental flag and you were advised not to use it unless in testing. + +Thanks to several fixes in this release the experimental flag has been dropped and it's now safe to try using this new feature in production. + +The method sets the Camera to render to a texture instead of to the main canvas. The Camera will redirect all Game Objects it's asked to render to this texture. During the render sequence, the texture itself will then be rendered to the main canvas. + +Doing this gives you the ability to modify the texture before this happens, allowing for special effects such as Camera specific shaders, or post-processing on the texture. + +* `Camera.setRenderToTexture` is a new method that enables the Camera to render to a target texture instead of the main canvas, allowing for application of special effects at run-time. +* `Camera.clearRenderToTexture` is a new method that stops a Camera from rendering to a texture and frees-up all associated resources. +* `Camera.setPipeline` allows you to change the WebGL pipeline being used if the Camera is rendering to a texture, effectively swapping the active shader. Call with no arguments to clear the pipeline. +* `Camera.renderToTexture` is a boolean property that controls where the Camera renders. It can be toggled on the fly. +* `Camera.canvas` is a Canvas Element that the Camera will render to if running under the Canvas Renderer and rendering to a texture. +* `Camera.context` is a Rendering Context that the Camera will render to if running under the Canvas Renderer and rendering to a texture. +* `Camera.glTexture` is a WebGL Texture that the Camera will render to if running under the WebGL Renderer and rendering to a texture. +* `Camera.framebuffer` is a WebGL Frame Buffer that the Camera will render to if running under the WebGL Renderer and rendering to a texture. +* `Camera.pipeline` is the Pipeline that the Camera will render with if running under the WebGL Renderer and rendering to a texture with a pipeline set. +* If you set a Camera to render to a texture then it will emit 2 events during the render loop. First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before it appears in-game. + +### New Features + +* The `Color` object has a new property `h` which represents the hue of the color. You can tween or adjust this property in real-time and it will automatically update the internal RGB values with it. +* The `Color` object has a new property `s` which represents the saturation of the color. You can tween or adjust this property in real-time and it will automatically update the internal RGB values with it. +* The `Color` object has a new property `v` which represents the lightness value of the color. You can tween or adjust this property in real-time and it will automatically update the internal RGB values with it. +* `Color.setFromHSV` is a new method that will set the color values based on the HSV values given. +* `Color.gray` is a new method that will set the color to be a shade of gray based on the amount given. +* `Color.random` is a new method that will set the color to be a random hue based on the min and max values given. +* `Color.randomGray` is a new method that will set the color to be a random grayscale based on the min and max values given. +* `Color.saturate` is a new method that will saturate the color based on the amount given. This is a chainable version of adjusting the saturation property directly. +* `Color.desaturate` is a new method that will desaturate the color based on the amount given. This is a chainable version of adjusting the saturation property directly. +* `Color.lighten` is a new method that will lighten the color based on the amount given. This is a chainable version of adjusting the value property directly. +* `Color.darken` is a new method that will darken the color based on the amount given. This is a chainable version of adjusting the value property directly. +* `Color.brighten` is a new method that will brighten the color based on the amount given. +* The `CanvasTexture` class has a new property `imageData` which contains the ImageData of the texture. +* The `CanvasTexture` class has a new property `data` which is a Uint8ClampedArray view into the `buffer`. +* The `CanvasTexture` class has a new property `pixels` which is a Uint32Array view into the `buffer`. +* The `CanvasTexture` class has a new property `buffer` which is an ArrayBuffer the same size as the context ImageData. +* The `CanvasTexture` class has a new method `update` which refreshes the ImageData and ArrayBuffer based on the texture contents. +* The `CanvasTexture` class has a new method `draw` which draws the given Image or Canvas element to the CanvasTexture, then updates the internal ImageData buffer and arrays. +* The `CanvasTexture` class has a new method `getPixel` which will get the color of a specific pixel from the Canvas Texture and store it in the returned Color object. It uses the ArrayBuffer to do this, which is extremely fast, allowing for quick iteration across the canvas data. +* The WebGLPipeline and WebGLRenderer have new a method `setFloat1v` which allows you to set a `uniform1fv` uniform value (thanks @Mattykins) +* The WebGLPipeline and WebGLRenderer have new a method `setFloat2v` which allows you to set a `uniform2fv` uniform value (thanks @Mattykins) +* The WebGLPipeline and WebGLRenderer have new a method `setFloat3v` which allows you to set a `uniform3fv` uniform value (thanks @Mattykins) +* The WebGLPipeline and WebGLRenderer have new a method `setFloat4v` which allows you to set a `uniform4fv` uniform value (thanks @Mattykins) +* `Text.setLineSpacing` is a new method that allows you to easily set the line spacing value of a Text object in a chainable call (thanks @RafelSanso) + +### Updates + +* The Graphics Canvas Renderer will now automatically call `beginPath` on the target context before processing the command stack. This has the effect of clearing off any sub-paths that may have persisted on the stack from previous Graphics objects or frames. This makes it more in-line with WebGL re: expectations when calling `Graphics.clear`. +* `initPipeline` now defaults to the Texture Tint Pipeline if nothing else is specified. This allowed me to remove explicit strings from 11 different Game Objects, saving some bytes in the process. +* The `RGBToHSV` function can now take an optional `out` argument, which is either a `HSVColorObject` or a `Color` object, and the results will be set into that object instead of creating a new one. +* The `HSVToRGB` function can now take an optional `out` argument, which is either a `HSVColorObject` or a `Color` object, and the results will be set into that object instead of creating a new one. +* `Color.setTo` has a new argument `updateHSV` which allows you to control if the internal HSV values are updated during the same call or not. +* The `Text._lineSpacing` property has been renamed to `lineSpacing` and made public, not private. You still set it in the same way, by passing a `lineSpacing` property to the Text configuration object, but internally it's now clearer. +* If a Scene is already active (i.e. running) and you call `start` on it (such as from another Scene) then it will shutdown the Scene first, before starting it again. + +### Bug Fixes + +* TileSprite.setTileScale would set the tile position by mistake, instead of the scale. Using the properties directly worked, but the method was incorrect (thanks @alexeymolchan) +* Calling `Text.setStyle` would make the Text vanish if you didn't provide a `resolution` property in the style configuration object. Calling `setStyle` now only changes the properties given in the object, leaving any previously changed properties as-is. Fix #4011 (thanks @okcompewter) +* In Matter.js if a body had its debug `render.visible` property set to `false` it wouldn't then render any other debug body beyond it. Now it will just skip bodies with hidden debug graphics (thanks @jf908) +* If you flagged a Tween as `paused` in its config, never started it, and then called `Tween.stop` it wouldn't ever be removed from the `_pending` array. It's now moved to the Tween Manager's destroy list, ready for removal on the next frame. Fix #4023 (thanks @goldfire) +* Game Objects would not remove themselves from the Scene's `shutdown` event handler when destroyed, leading to a build-up over time (thanks @goldfire) +* The WebGL Renderer will no longer try and just resize a canvas backed texture, instead it will properly delete it then re-create it. Fix #4016 (thanks @alexeymolchan) +* The Camera background for mini-Cameras (those positioned deep inside another Camera) would be offset incorrectly in WebGL, causing the background fills to be displaced (thanks @aaronfc) +* The WebGL Renderer now always enables the `SCISSOR_TEST`, this allows Game Objects that use the scissor (such as custom objects, or Bitmap Text) to render properly again. +* The Cameras `setScene` method, which is called automatically when a new Camera is created, will now call `updateSystem` which correctly increases the custom viewport counter. This fixes an issue with mini-cams inside of larger cameras not clipping their contents properly. If a Camera is moved to another Scene it also now correctly shrinks the total custom viewport counter. +* Due to the two fixes above another bug was fixed: The ability for you to swap between Cameras with and without `setRenderToTexture` enabled with custom shaders. Previously if you used this with a custom shader then only the first Camera using the shader would render, the rest would appear black. Now, all Cameras using the custom shader work correctly. As a result all of the 'experimental' Camera rendering properties from 3.12 have been moved to stable. +* If you destroyed a Game Object that had a custom cursor set during one of its input events the cursor didn't correctly reset. Fix #4033 (thanks @pantoninho) +* `RenderTexture.resize` wouldn't correctly resize the texture under WebGL. Fix #4034 (thanks @jbpuryear) +* Calling `setFrame` on a TileSprite wouldn't change the frame, it would just change the frame size. Fix #4039 (thanks @Jerenaux) +* `Zone.setRectangleDropZone` used the wrong `x` and `y` coordinates for the hit area, causing it to be offset from the zone itself after the changes made for issue #3865 in the 3.12 release. + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@johanlindfors @Arthur3DLHC @JamesSkemp + +## Version 3.12.0 - Silica - 4th September 2018 + +### FlatTintPipeline Updates + +In 3.11 I overhauled the TextureTintPipeline, the WebGL batch used to render all texture based Game Objects, such as Sprites. In this release I did the same to the FlatTintPipeline. This pipeline was used exclusively by the Graphics Game Object to draw filled and stroked primitives in WebGL. It was also used by classes such as the Camera in order to draw their colored backgrounds and flash / fade effects. + +When I looked closely at the shaders being used by the texture and graphics pipelines I noticed they were virtually identical. Yet if you were to mix Graphics objects and Sprites in your game, it would cause a complete batch flush as it switched between the them as it rebound the shaders, adding to both the draw calls and gl ops per frame. + +The more I looked through the graphics pipeline, the more I saw the same kind of things the texture one previously had: duplicate vars, in-line matrix operations and so on. So I worked through the process of refactoring it, boiling it down to just a handful of core methods and re-using methods the texture pipeline already had. The end result is that I've been able to remove the FlatTintPipeline entirely. This saves 42.3KB (unminifed) and removes 1000 lines of code from the build. Of course, lots of the methods were added to the texture pipeline, but that only increased from 730 sloc to 1087 sloc, a fraction of the amount before! And the benefits don't end there. + +If you had any custom pipelines that extended the FlatTintPipeline please update them to extend the TextureTintPipeline instead. You'll likely need to remap a few methods, but most of them remain the same. Double-check the method signatures though. + +The same pipeline can now draw both graphics and sprites, with the same shader and no texture swapping either. This means you can happily mix Graphics objects alongside Sprites and it won't cost any extra overhead at all. There are more benefits too, which are outlined in the list below. + +* The TextureTintPipeline now has 100% jsdoc coverage. +* The removal of the FlatTintPipeline shaves 42.3KB and 1000 sloc from the bundle size. +* The Graphics fill and line styles are now cached in the pipeline, rather than being re-calculated for every primitive drawn. +* The new `batchTri` method will add a triangle to the vertex batch, either textured or filled. +* `drawFillRect` is a new method that will add an untransformed rectangle to the batch. These are used by things like Cameras to fill in background colors. +* `batchFillRect` has been moved to the TextureTintPipeline and has a new much more concise method signature. +* `batchFillTriangle` has been moved to the TextureTintPipeline and has a new much more concise method signature. +* `batchFillPath` has been moved to the TextureTintPipeline and has a new much more concise method signature. +* `batchLine` has been moved to the TextureTintPipeline. +* When drawing Graphics paths with a line width of 1 it will no longer spend any time drawing the line joins, speeding-up the rendering of 1px lines. + +### WebGL Scissor Update + +The process of managing scissors in the WebGLRenderer has been completely rewritten. Previously, the gl scissor was being constantly enabled and disabled for every Camera in your game, leading to pointless gl operations. + +* Cameras have a new internal method `updateSystem` which is automatically called if you change any Camera viewport values. This in turn tells the Scene Manager if there are any cameras with custom viewports, in any Scene of your game. If there are not then the scissor is never even enabled or set, meaning zero gl ops! If your game uses full sized Cameras it now doesn't cost anything at all with regard to scissoring. +* If a new scissor is set it will now check to see if it's the same size and position as the current scissor, and if so, it'll skip setting it at all. + +### Render Texture New Features and Updates + +The Render Texture class has been rewritten from scratch and all Game Objects have been updated to support it. Previously it was very restricted in what you could do with it. It used to have a matrix stack for internal transforms, but this has been replaced with a Camera instead. This means you have the full power of a Camera system (scrolling, zooming, rotation) but it only impacts the contents of the Render Texture. + +* The biggest update is the change in what the `draw` method can accept. Previously you had to pass in a texture and frame reference. This has changed, as has the method signature. It can now accept any of the following: + + - Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + - Dynamic and Static 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. Pass in `Scene.children` to draw the whole display list. + - Another Render Texture. + - A Texture Frame instance. + - A string. This is used to look-up a texture from the Texture Manager. + +* There is a new method `drawFrame` which allows you to pass in a string-based texture and frame key and have it drawn to the Render Texture. +* The new method `saveTexture` allows you to save the Render Texture into the Texture Manager using your own key. You can then use the Render Texture for any Game Object that accepts textures as a source, such as Sprites or even Tilemap Layers. You can add frame data to a Render Texture using the `RenderTexture.texture.add` method. +* The new `camera` property is an instance of a complete 2D Camera. You can use it to change the view into your Render Texture. Scroll, rotate, zoom, just like you would with a normal Camera, except it will only influence the objects being drawn to the Render Texture. +* All of the matrix-style methods have been removed: `save`, `translate`, `restore`, `scale`, `rotate`. You can now achieve the same thing by either transforming the object you want to draw to the Render Texture, or using the built-in Camera. +* You can now crop a Render Texture. Use the `setCrop` method to define the crop region. + +See the fully complete documentation for more details and the extensive examples and tests created. + +### Text Game Object New Features and Updates + +The Text Game Object has been given an internal overhaul to make it more flexible. Some properties have been renamed or moved and new features added: + +* Text can now be cropped in WebGL and Canvas! Use the `setCrop` method to crop the text. +* Text now keeps a reference to the renderer in the `renderer` property. +* The `canvasTexture` property has been removed. +* Text now has internal `texture` and `frame` properties. These replace the old `canvasTexture` but perform the same task, while allowing for texture cropping and much smaller renderer code. +* Previously, changing a Text object by setting its `text` property directly wouldn't change the text being rendered as using `setText` was the expected way to change what was being displayed. Internally the `text` property has been renamed to `_text` and flagged as private, and a new getter / setter for `text` has been added, which hands over to the `setText` method, meaning you can now use both ways of setting the text. Fix #3919 (thanks @hackhat @samid737) + +### Tile Sprite Object New Features and Updates + +The Tile Sprite Game Object has been given an internal overhaul to make it more flexible. Some properties have been renamed or moved and new features added: + +* Tile Sprites can now be cropped in WebGL and Canvas! Use the `setCrop` method to crop the tile sprite. +* There is a new method `setTileScale` which will set the tile scale in a chainable call. +* There is a new internal `canvas` property. Tile Sprites work differently than before in Canvas mode: Previously they would use the `fillRect` command on the game canvas to draw themselves every frame, even if they hadn't changed. They now draw to an internal canvas only when their position or scale changes. This canvas is then drawn to the game canvas instead. It's faster, as it doesn't fillRect every frame and also allows you to draw them to other contexts, such as Render Textures. +* There are two new internal properties `_tilePosition` and `_tileScale` which are Vector 2s that hold the position and scale. Getters have been added, so use the same properties as before in your code. +* There are two new properties `displayTexture` and `displayFrame`. These replace the previous `texture` and `frame` properties and hold references to the source texture the Tile Sprite is using. +* The `canvasPattern` property has been renamed to `fillPattern`. +* The `oldFrame` property has been removed. +* The `canvasBuffer` property has been renamed to `fillCanvas`. +* The `canvasBufferCtx` property has been renamed to `fillContext`. + +### Tilemap New Features and Updates + +The Tilemap and Dynamic and Static Tilemap Layer classes now all support 4 different modes of render order for drawing the tiles. This allows you to control the z-order of the tiles during render. This feature was requested by @etienne (who provided the test maps too) - see the new examples in the Labs for better understand the impact this has. + +The default is 'right-down', meaning it will order the tiles starting from the top-left, drawing to the right and then moving down to the next row. + +The four draw orders are: + +0 = right-down +1 = left-down +2 = right-up +3 = left-up + +* Tilemap has a new property `renderOrder` which is a string based version of the render order, as used when new layers are created via the map. If the map is created from Tiled JSON data, it will use whatever render order has been specified in the map data. +* Tilemap has a new method `setRenderOrder`. This takes either an integer or a string-based version of the render order and stores it locally. It's then used during the creation of any layers from that point on. +* The DynamicTilemapLayer has a new method `setRenderOrder`. This takes either an integer or a string-based version of the render order and stores it locally. It's then used during rendering of the layer. You can change the value on the fly. +* The StaticTilemapLayer has a new method `setRenderOrder`. This takes either an integer or a string-based version of the render order and stores it locally. Under WebGL it will re-create the whole vertex buffer, using the new draw order. Under Canvas it uses it at run-time during rendering. You can change it on the fly. +* ParseJSONTiled now extracts the `renderorder` property from the Tiled JSON. +* MapData has a new `renderOrder` property, which is populated by the Tiled Parser. + +### Matter.js Updates + +The version of Matter.js used by Phaser has been updated from 0.13.1 to 0.14.2. To clarify why we don't include Matter via npm, it's because we use a customized version of Matter that includes extra features and optimizations not yet found in the official library. + +Most of the updates were about documentation and module namespacing, however those relevant to Phaser are listed below. You can also view the full [Matter Change Log](https://github.com/liabru/matter-js/blob/master/CHANGELOG.md). + +* fix Composite.bounds global issue, closes #627, closes #544 ([f7f77b4](https://github.com/liabru/matter-js/commit/f7f77b4)), closes [#627](https://github.com/liabru/matter-js/issues/627) [#544](https://github.com/liabru/matter-js/issues/544) +* updated pathseg library, closes #548, closes #602, closes #424 ([1e5758f](https://github.com/liabru/matter-js/commit/1e5758f)), closes [#548](https://github.com/liabru/matter-js/issues/548) [#602](https://github.com/liabru/matter-js/issues/602) [#424](https://github.com/liabru/matter-js/issues/424) +* fix Common.isElement on node, closes #535 ([ec38eeb](https://github.com/liabru/matter-js/commit/ec38eeb)), closes [#535](https://github.com/liabru/matter-js/issues/535) +* added Query.collides, closes #478 ([6593a72](https://github.com/liabru/matter-js/commit/6593a72)), closes [#478](https://github.com/liabru/matter-js/issues/478) +* fix `point` argument of Body.scale, closes #428 ([894c1ef](https://github.com/liabru/matter-js/commit/894c1ef)), closes [#428](https://github.com/liabru/matter-js/issues/428) +* fix Body.scale for compound bodies ([50a89d0](https://github.com/liabru/matter-js/commit/50a89d0)) +* fix centroid for static compound bodies, closes #483 ([ece66e6](https://github.com/liabru/matter-js/commit/ece66e6)), closes [#483](https://github.com/liabru/matter-js/issues/483) +* fix Common.isElement, closes #501, closes #507, closes #459, closes #468, closes #517 ([18a0845](https://github.com/liabru/matter-js/commit/18a0845)), closes [#501](https://github.com/liabru/matter-js/issues/501) [#507](https://github.com/liabru/matter-js/issues/507) [#459](https://github.com/liabru/matter-js/issues/459) [#468](https://github.com/liabru/matter-js/issues/468) [#517](https://github.com/liabru/matter-js/issues/517) +* fix inertia change in Body.setMass, closes #378 ([f7d1877](https://github.com/liabru/matter-js/commit/f7d1877)), closes [#378](https://github.com/liabru/matter-js/issues/378) +* fix Vertices.chamfer radius argument, closes #467 ([3bceef4](https://github.com/liabru/matter-js/commit/3bceef4)), closes [#467](https://github.com/liabru/matter-js/issues/467) + +### Camera 3D Plugin + +Support for Camera 3D and Sprite 3D Game Objects have been removed from the core Phaser bundle and moved to an optional plugin. + +You can find the source for Camera 3D in the new `plugins/camera3d` folder, along with a README file explaining how to now use the plugin in your games. + +* When a Sprite3D object is added to a Camera via `Camera.add` it is now added to the Display and Update Lists. Fix #3945 (thanks @vvega) + +### New Features + +* `Camera.resolution` is a new read-only property that holds the current game config resolution that the camera is using. This is used internally for viewport calculations. +* `Text.resolution` and the method `Text.setResolution` allows you to control the resolution of a Static Text Game Object. By default it will be set to match the resolution set in the Game Config, but you can override it yourself via the TextStyle. It allows for much clearer text on High DPI devices, at the cost of larger internal Canvas textures for the Text - so please use with caution, as the more high res Text you have, the more memory it uses up. Fix #3528 (thanks @kirillbunin) +* `TransformMatrix.getCSSMatrix` will return a CSS transform matrix formatted string from the current matrix values. +* `CacheManager` now creates a new cache called `html` which is used to store all loaded HTML snippets. +* `FileType.HTML` is a new file type loader that will load an HTML snippet and store it in the new `html` cache. Access it via `load.html` (this method was previously used to load html to textures, please see `load.htmlTexture` for this feature now) +* `TransformMatrix.getX` is a new method that return the x component from the given x and y values based on the current matrix. This is used heavily in the pipelines. +* `TransformMatrix.getY` is a new method that return the y component from the given x and y values based on the current matrix. This is used heavily in the pipelines. +* `TransformMatrix.copyToArray` is a new method that will copy the matrix values to the given array. It's the counter-part of `copyFromArray`. +* `Graphics.setTexture` is a new WebGL only method that allows you to set a texture to be used when drawing the shapes on the Graphics object. You can also specify how the texture should be blended with the current fill or gradient colors. Note that the texture is not tiled, it is stretched to fit the shape being drawn. +* `Graphics.fillGradientStyle` is a new WebGL only method that allows you to set a gradient for the shapes being filled. You can control the colors at the 4 corners of a rectangle. The colors are then blended automatically in the shader. Use of this feature is limited. For example, you cannot gradient fill a whole path or an arc, as it's made up of lots of triangles. But for quick gradient backgrounds or buttons it's perfect. +* `Graphics.lineGradientStyle` is a new WebGL only method that allows you to set a gradient for the shapes being stroked. You can control the colors at the 4 corners of a rectangle. The colors are then blended automatically in the shader. Use of this feature is limited. For example, you cannot gradient stroke a whole path or an arc, as it's made up of lots of triangles. But for quick gradient lines it's perfect. +* `TextureManager.getBase64` is a new method that will take a texture frame key and return a base64 encoded version of the frame. You can also provide the image type and encoder options. +* Global Plugins now have a new optional `data` object, the contents of which are passed to the plugins `init` method. This allows users to pass data directly into a plugin when added in the config: `{ key: 'BankPlugin', plugin: BankPluginV3, start: true, data: { gold: 5000 } }` or when adding a plugin via the `install` method (thanks @samme) +* You can now play animations in reverse! Use the new `Sprite.anims.playReverse` method to play a pre-defined animation in reverse from its starting frame. Or call `Sprite.anims.reverse` to immediately reverse the flow of an already running animation. Animations running in reverse still count towards the repeat total and respect the yoyo flag (thanks @khaleb85 @Ben-Millions) +* The `ParticleEmitterManager` now has the Transform component. This means you can now set the position, rotation or scale of the Emitter Manager, and it will influence every Emitter it is rendering. The Managers transform is mixed with that of the Camera. This works in both Canvas and WebGL. +* `TextureManager.addRenderTexture` is a new method that will add a Render Texture into the Texture Manager, allowing you to use it as the texture for Game Objects just by using the texture key. Modifying the source Render Texture will immediately modify any Game Objects using it. +* TextureSource has a new boolean property `isRenderTexture` which is set automatically when it's created. +* The Canvas Renderer has a new method `setContext` which allows it to swap the context being drawn to by all draw operations. Call the method with no arguments to reset it to the default game canvas. +* If you set `window.FORCE_WEBGL` or `window.FORCE_CANVAS` in the window in which the Phaser game is loaded it will over-ride the renderer type setting in your game config, and force either WebGL or Canvas. This is handy for quickly testing the differences between renderers without having to do a new build each time. +* `TextureSource.source` is a new property that contains the original source of the Texture image. It is cleared when the source is destroyed. +* `TransformMatrix.copyToContext` is a new method that will copy the values from the Matrix to the given Canvas Rendering Context. +* `Phaser.Utils.String.UUID` will return an RFC4122 complaint UUID as a string. This is used internally to avoid cache key conflicts, but is exposed for your own use as well. +* There is a new `Crop` Component which is used by non-texture based Game Objects, such as Text and TileSprite. You either use `TextureCrop` or `Crop`, not both together on the same object. +* `TransformMatrix.setToContext` is a new method that will set the values from the Matrix to the given Canvas Rendering Context using setTransform rather than transform. +* `SetTransform` is a new Canvas Renderer function that consolidates the process of preparing a Game Object for rendering, without actually rendering it. This is used internally by the Graphics and Bitmap Text classes. +* The Texture Manager has a new method called `renameTexture` which will let you rename a texture, changing the key to the new one given. All existing Game Objects will still maintain their reference, even after a rename. +* When loading an SVG file you can now change the size of the SVG during the load process, before it is rendered to a texture. This is really helpful if you wish to increase SVGs that have small viewBoxes set, or want to try and reduce memory consumption from SVGs with extra large dimensions. You can either pass in a fixed width and height: `this.load.svg('morty', 'file.svg', { width: 300, height: 600 })` or you can provide a scale factor instead: `this.load.svg('morty', 'file.svg', { scale: 4 })` (thanks @ysraelJMM) +* `Polygon.Perimeter` will return the perimeter for the given Polygon (thanks @iamchristopher) +* `Polygon.GetPoints` will return an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, based on the given quantity or stepRate values. This is available as a static function and as the `getPoints` method on a Polygon (thanks @iamchristopher) + +### Updates + +* The Camera class has been split into two: `BaseCamera` which contains all of the core Camera functions and properties, and would serve as a great base for you to extend for your own custom Cameras, and `Camera` which is the same class name as previously. `Camera` extends the Base Camera and adds in follower support and the Special Effects. You don't need to update your code, even if currently extending a Camera, as they work the same as before. +* `Camera.x` and `Camera.y` have been turned into getters / setters, mapped to the internal private values `_x` and `_y` respectively. This is so that setting the Camera viewport position directly will now update the new internal resolution calculation vars too. +* `Camera.setScene` will now set the Cameras `resolution` property at the same time and update the internal viewport vars. +* The `Cull Tiles` method used by the Dynamic Tilemap Layer has had a nice and significant optimization. It will now use the cull area dimensions to restrict the amount of tile iteration that takes place per layer, resulting in dramatic reductions in processing time on large layers, or multiple layers (thanks @tarsupin) +* `GameObject.willRender` now takes a Camera as its only argument and uses it within the check. This has allowed me to remove 23 duplicate checks spread across the various Game Objects, all of which did the same thing, saving both KB and CPU time as the flags were being checked twice in most cases. +* The file type loader `HTML` has been renamed to `HTMLTexture`. If you were using this then please change your calls from `load.html` to `load.htmlTexture`. The arguments remain the same. +* The `setBlendMode` method in the WebGL Renderer now returns a boolean. True if a new blend mode was set, otherwise false. Previously it returned a reference to the renderer instance. +* The method `batchVertices` in the TextureTintPipeline has been renamed to `batchQuad` which more accurately describes what it does. +* In ArcadePhysics `Body.setSize` you can now choose to not pass width and height values to the method. If you do this it will check to see if the parent Game Object has a texture frame, and if so, it will use the frame sizes for the Body dimensions (thanks @tarsupin) +* `PluginCache.destroyCorePlugins` will remove all core plugins from the cache. Be very careful calling this as Phaser cannot restart or create any new Scenes once this has been called. +* `PluginCache.destroyCustomPlugins` will remove all custom plugins from the cache. +* `PluginManager.destroy` will now clear all custom plugins from the Plugin Cache. This fixes an issue with not being able to destroy a Phaser game instance and restart it if it used a custom plugin (thanks jd.joshuadavison) +* `Game.destroy` has a new boolean argument `noReturn`. If set it will remove all Core plugins when the game instance is destroyed. You cannot restart Phaser on the same web page after doing this, so only set it if you know you're done and don't need to run Phaser again. +* The `MouseManager` will no longer process its native events if the manager reference has been removed (i.e. you move the pointer as the game is destroying itself) +* The `TouchManager` will no longer process its native events if the manager reference has been removed (i.e. you move the pointer as the game is destroying itself) +* `Particle.color` has been removed as it's now calculated during rendering to allow for Camera alpha support. +* The Game boot event flow has changed slightly. The Game will now listen for a `texturesready` event, which is dispatched by the Texture Manager when the default textures have finished processing. Upon receiving this, the Game will emit the `ready` event, which all the other systems listen for and respond to. The difference is that the Renderer uses the `texturesready` event to ensure that it is the first thing to be activated, before any other system. +* The WebGLRenderer has a new property `blankTexture` which is a reference to an empty 32x32 transparent WebGL Texture. This is used internally for things like rendering Graphics with no texture fills and where no other texture has been set. +* The WebGLRenderer has a new method `setBlankTexture` which forces it to set the blank texture as the current texture. This is used after drawing a Render Texture to ensure no other object tries to draw to itself. +* The StaticTilemapLayer has had the following properties and methods added to it: `skipCull`, `tilesDrawn`, `tilesTotal`, `cullPaddingX`, `cullPaddingY`, `cullCallback`, `setSkipCull` and `setCullPadding` as these are all used by the Canvas Static Layer renderer. Static Layers in 3.11 didn't render in Canvas because the cull values were missing, but now render correctly and can also be rendered to other targets, like a Render Texture. +* The Math.Snap methods `Snap.Floor`, `Snap.Ceil` and `Snap.To` have all gained a new optional boolean argument `divide`. If set the resulting snapped value will be divided by the gap amount before returning. This is handy if you're trying to quickly snap a value into a grid or array location. +* The `currentBlendMode` property has been removed from the Canvas Renderer and is no longer checked by any class. Blend modes are now set directly on the context to avoid state saving invalidation. +* The `currentAlpha` property has been removed from the Canvas Renderer and is no longer checked by any class. Alpha values are now set directly on the context to avoid state saving invalidation. +* `TextureCrop` and `Crop` have a new method `resetCropObject` which generates the crop data object required by Game Objects that support cropping. This allows us to remove duplicate code from a number of Game Objects and replace it with a single function call. +* The Canvas Renderer has a new `batchSprite` method that consolidates the process of drawing a texture-based Game Object to the canvas. It processes the alpha, blend mode and matrix calculations in a single function and now is used by nearly all Game Object canvas renderers. +* The `batchTexture` method in the Texture Tint Pipeline now supports cropped Game Objects and will adjust the drawn texture frame accordingly. +* The `Matrix Stack` Component has been removed. It's no longer used internally and was just wasting space. +* You can now specify the `lineHeight` of a Retro Font in the Retro Font Config object (thanks @FelixNemis) +* When a Static Tilemap Layer is generated in WebGL it will use the Cameras `roundPixels` value to clamp the tile coordinates. +* The `CanvasRenderer.DrawImage` function has been removed, as has the associated `drawImage` property from the Canvas Renderer as they're no longer used. +* The `CanvasRenderer.BlitImage` function has been removed, as has the associated `blitImage` property from the Canvas Renderer as they're no longer used. +* You can now access the Game instance directly from a Scene using `this.game` as long as it exists in the Scene's Injection Map, which it does by default. Be very careful what you do here: there's next to nothing you should actually use this for. +* `Camera.ignore` can now take nested-arrays of Game Objects and also supports both Groups and Containers. +* The `changedata` event dispatched by the Data Manager now includes the previous value as the 4th argument to the callback, so the event signature is now: `parent, key, value, previousValue` (thanks @iamchristopher) +* The call to `gl.clearColor` is now skipped when `clearBeforeRender` is set to `false` (thanks @goldfire) +* The calls to `DistanceBetween` have been replaced with `DistanceSquared` in the `closest` and `furthest` functions within Arcade Physics (thanks @Mursaat) +* The RandomDataGenerator will now create a default random seed if you instantiate your own version of the class (instead of using `Phaser.Math.RND`) and don't provide a seed for it (thanks michaeld) +* The Tilemap `createFromObjects` method will now add custom properties to the Game Objects. It works by checking if the property exists or not, and if not, it sets it in the Game Objects Data Manager (thanks @scalemailted @samme) +* In Matter.js if you scaled a Body it would only scale correctly once, due to the way Matter handles scaling internally. We now automatically reset the Matter scale before applying the new value, which allows you to keep the Phaser and Matter object scales in sync. Fix #3785 #3951 (thanks @bergben) +* The default Container Blend Mode is now `SKIP_TEST`. This allows you to either set a blend mode for a Container, in which case all children use that blend mode. Or, you can set a blend mode on the children and the children will render using their own blend modes, as the Container doesn't have one set. The WebGL and Canvas Renderer functions have also been updated to support this change. Fix #3684 (thanks @TadejZupancic) +* Previously the Input Manager would create a Touch handler unless the Game Config had `input.touch` set to `false` (the default was true). If no such property is set, it no longer defaults to `true` and instead is set to whatever `Device.input.touch` returns. On non-touchscreen desktops this means it will now only create one single Pointer, rather than two. +* The Arcade Physics Body `_tempMatrix` property has been removed. It was only used if the Body's Game Object had a parent. The matrix has been moved to the World instance instead, shared by all bodies. +* Arcade Physics World has gained two new private properties `_tempMatrix` and `_tempMatrix2`. These are used by all bodies in the simulation that need a temporal matrix for calculations, rather than having their own instances. +* The Input Manager has gained a new private property `_tempMatrix2`. This is used internally in the hitTest checks to avoid constant matrix creation. +* The Transform Matrix has a new method `applyInverse` which will take an x/y position and inverse translate it through the current matrix. +* Using `keyboard.addKeys("W, A, S, D")` would fail because of the spacing between the characters. `addKeys` will now trim the input allowing you to space characters out if you prefer (thanks @dhruvyad) +* Calling `setTimeScale` on the Sprite's Animation component will now set the time scale value and keep it set until you change it again. Previously it would be reset to 1 when a new animation was loaded into the component, but this no longer happens - once the time scale is set it remains in effect, regardless of which animations are played on the Sprite. + +### Game Config Resolution Specific Bug Fixes + +Setting the `resolution` property in the Game Config to a value other than 1 would cause various errors in the API. The following have been fixed: + +* The game canvas would be sized incorrectly, unless you had enabled auto resizing. It now scales the canvas to the size given, maintaining the resolution. Fix #3468 (thanks @Legomite) +* Cameras with background colors set would display the filled color area at the wrong size. Camera fills now respect the resolution. +* The Camera Fade Effect would display the fade fill rectangle at the wrong size. Camera fades now respect the resolution. +* The Camera Flash Effect would display the fade fill rectangle at the wrong size. Camera flashes now respect the resolution. +* The Camera Shake Effect would shake the Camera using the wrong width values. Camera Shakes now respect the resolution. +* Input calculations would not factor in the Game Resolution correctly. If a Camera viewport was not at 0x0 or not the full size, or the Camera was rotated or zoomed, the input areas would be wrong if `resolution` was > 1. These are now factored in correctly and changing the resolution no longer breaks input. Fix #3606 (thanks @Secretmapper @thanh-taro) + +### Bug Fixes + +* The `setCrop` method stored its crop object on the prototype chain by mistake, causing all Images or Sprites that were cropped to display the same frame. The crop data has been moved to the Game Object instance, where it should be, fixing this issue (thanks NoxBrutalis) +* If an AudioFile failed to load and throw an incomplete error, it would cause the console.log to crash JavaScript when trying to log the error. It now only logs the message if it exists. Fix #3830 (thanks @kelostrada) +* Particles using a blend mode wouldn't render correctly after the updates in 3.11. If the blend mode changes during the processing of an emitter manager it'll now correctly rebind the texture, stopping the particles from vanishing. Fix #3851 (thanks @maxailloud) +* Adding an array of children to a Group would cause it to mistakenly think you were passing a config object. Fix #3854 (thanks @pedro-w) +* Graphics paths in WebGL would not render the line join between the final and the first path if the path was closed, leaving a noticeable gap if you used particularly thick strokes. If the path is closed it will now render the final line join properly. +* If a Mesh caused a batch flush it would fail to render as its texture was lost. It's now rebound correctly after the flush. +* `ArcadePhysics.closest` and `ArcadePhysics.furthest` used the wrong tree reference, causing them to throw errors (thanks @samme) +* `BlitterCanvasRenderer` would fail to render a Bob in Canvas mode if it was flipped (thanks @SBCGames) +* `RenderTexture.draw` would fail to draw the frame in Canvas mode (thanks @SBCGames) +* `ParticleEmitter` would fail to draw a textured particle in Canvas mode (thanks @SBCGames) +* `RenderTexture.preDestroy` will now release the canvas back to the CanvasPool if running in canvas mode (thanks @SBCGames) +* The `alpha` value is now always set for Render Textures in canvas mode, regardless of the previous alpha value in the renderer (thanks @SBCGames) +* Zone now calls `updateDisplayOrigin` in its constructor, causing the `displayOriginX` and `displayOriginY` values to now be correct if you create a Zone and then don't resize it. Fix #3865 (thanks @rexrainbow) +* The `CameraManager` was accidentally adding extra destroy event calls when a Scene was restarted, causing an `Uncaught TypeError: Cannot read property 'events' of null` when trying to destroy a game instance having swapped from a Scene to another, and back again. Fix #3878 (thanks @mbunby) +* RenderTextures in WebGL will now set the viewport size, stopping the console warning in Firefox. Fix #3823 (thanks @SBCGames) +* Particles now take the Cameras alpha value into consideration when calculating their final alpha values in WebGL. They previously ignored it. If you now alpha a Camera out all particles will change accordingly. +* The `CullTiles` updates from 3.11 didn't factor in the position of the Tilemap Layer to its bounds calculations, causing Static layers displayed out of the Camera viewport to never render in Canvas mode. The method has also been optimized further, with less divisions and less checks if culling is disabled. +* The Particle Emitter when running in Canvas wouldn't allow more than 1 emitter to use a blend mode (as seen in the Electric examples). The blend mode is properly set for each emitter now. +* The Blend Mode is now set directly in all Canvas Renderers without comparing it to what's stored in the Canvas Renderer. This fixes problems where the blend mode would be lost between two different Game Objects because they restored the context, but didn't update the renderer flag. Game Objects in Canvas can now mix and match blend modes across the display list. +* Matter.js has received a tiny update that prevents `collisionEnd` from triggering many times when it should only trigger once (thanks @mikewesthad) +* Graphics objects couldn't be set to be ignored by Cameras. Now every renderable Game Object can be ignored by a Camera, either directly or via a Container. The exception are Groups because they don't render and are non-exclusive parents. +* The Tilemap Culling function now uses the Tilemap tile dimensions for its bounds calculations, instead of the layer tile sizes, as they two don't have to match and it's the underlying grid size that takes precedence when calculating visible tiles. Fix #3893 (thanks @Zax37) +* The Arcade Physics `Body.speed` property is now set whenever you set the velocity via `setVelocity` or `setVelocityX` or `setVelocityY` which stops the body velocity being reset to zero if `useDamping` is enabled. Fix #3888 (thanks @samme) +* The `getPixelAlpha` method in the Texture Manager wasn't using the correct frame name. This is now passed in correctly. Fix #3937 (thanks @goldfire) +* The `getPixelAlpha` and `getPixel` methods in the Texture Manager would allow x/y coordinates from outside the cut area of a frame. It now tests to ensure they're within the frame. Fix #3937 (thanks @goldfire) +* A Game Object couldn't have a blend mode of `SKIP_TEST` set by using the getter or the `setBlendMode` method. +* In Arcade Physics the `World.disable` call was passing the wrong argument, so never disabling the actual body (thanks @samme) +* There was a visual bug with Rounded Rectangles in Canvas mode, due to the addition of the `overshoot` argument in the Graphics arc call. This has been fixed, so arcs will now render correctly and consistently in WebGL and Canvas and Rounded Rectangles are back to normal again too. Fix #3912 (thanks @valse) +* The `InputManager.inputCandidate` method, which determines if a Game Object can be interacted with by a given Pointer and Camera combination, now takes the full camera status into consideration. This means if a Camera is set to ignore a Game Object you can now no longer interact with it, or if the Camera is ignoring a Container with an interactive Game Object inside it, you cannot interact with the Container children anymore. Previously they would interact regardless of the Camera state. Fix #3984 (thanks @NemoStein @samid737) +* `Transform.getWorldTransformMatrix` has been recoded to iterate the transform parents correctly, applying the matrix multiplications as it goes. This (along with some changes in the Input Manager) fix the issue with Game Objects inside of Containers failing hit tests between certain angles. Fix #3920 (thanks @chaping @hackhat) +* Calling Arcade Physics `collide` during an `update` method wouldn't inject the results back into the Body parent, causing the bodies to carry on moving. Using Colliders worked, but manually checking did not. Now, both methods work. Fix #3777 (thanks @samme) +* The `setTintFill` method would ignore the `alpha` value of the Game Object in the shader. The alpha value is now blended with the tint fill, allowing you to properly alpha out tint-filled Game Objects. Fix #3992 (thanks @trl-bsd) +* Arcade Physics World `collideSpriteVsTilemapLayer` now syncs the collision results back to the body, allowing you to call `collide` from within an update loop once again. Fix #3999 (thanks @nkholski @mikewesthad) +* Arcade Physics Body `deltaX` and `deltaY` methods will now return the previous steps delta values, rather than zero. Fix #3987 (thanks @HaoboZ) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@SBCGames @rgk @rook2pawn @robbintt @bguyl @halilcakarr @PhaserEditor2D @Edwin222 @tfelix @Yudikubota @hexus @guzmonne @ampled @thanh-taro @dcbriccetti @Dreaded-Gnu @padme-amidala @rootasjey @ampled @thejonanshow @polarstoat @jdjoshuadavison @alexeymolchan @samme @PBird @spontoreau @hypertrifle @kid-wumeng + +Thanks to @khaleb85 for fixing the super-annoying lag on the API Docs pages when it hung the browser while indexing the search field. + + +## Version 3.11.0 - Leafa - 13th July 2018 + +### Camera - New Features, Updates and Fixes + +* All of the 2D Camera classes are now 100% covered by JSDocs! +* All of the 3D Camera classes are now deprecated and will be removed in the next version. They will be moved to a stand-alone plugin. +* `Camera.alpha` (and its related method `Camera.setAlpha`) allows you to set an alpha level for the entire camera. This impacts everything it is rendering, even if those objects also have their own alpha values too. You can tween the property to make the camera contents fade in / out, or otherwise set it as needed in your game. +* `Camera.deadzone` (and its related method `Camera.setDeadzone`) allows you to specify the deadzone for a camera. The deadzone is a rectangular region used when a camera is following a target. If the target is within the deadzone then the camera will not scroll. As soon as the target leaves the deadzone, the camera will begin tracking it (applying lerp if needed.) It allows you to set a region of the camera in which a player can move freely before tracking begins. The deadzone is re-centered on the camera mid point every frame, meaning you can also use the rectangle for other in-game checks as needed. +* `Camera.pan` is a new Camera Effect that allows you to control automatic camera pans between points in your game world. You can specify a duration and ease type for the pan, and it'll emit events just like all other camera effects, so you can hook into the start, update and completion of the pan. See the examples and docs for more details. +* `Camera.zoom` is a new Camera Effect that allows you to control automatic camera zooming. You can specify a duration and ease type for the zoom, as well as the zoom factor of course, and it'll emit events just like all other camera effects, so you can hook into the start, update and completion of the zoom. Used in combination with the new Pan effect you can zoom and pan around with ease. See the examples and docs for more details. +* `Camera.midPoint` is a new Vec2 property that is updated every frame. Use it to obtain exactly where in the world the center of the camera is currently looking. +* `Camera.displayWidth` is a new property that returns the display width of the camera, factoring in the current zoom level. +* `Camera.displayHeight` is a new property that returns the display height of the camera, factoring in the current zoom level. +* `Camera.worldView` is a new property, an instance of a Rectangle, that contains the dimensions of the area of the world currently visible by the camera. You can use it for intersection or culling tests that don't need to factor in camera rotation. +* `Camera.dirty` is a new boolean property. A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. The flag is reset in the `postCameraRender` method, but until that point can be checked and used. +* `Camera.centerOn` is a new method that will move the camera so its viewport is centered on the given coordinates. A handy way of jumping to different points around a map without needing to calculate the scroll offsets. +* The Camera bounds didn't factor in the camera zoom properly, meaning you would often not be able to reach the corners of a camera bound world at a zoom level other than 1. The bounds are now calculated each frame to ensure they match the zoom level and it will no longer allow you to scroll off the edge of the bounds. Fix #3547 (thanks @nkholski) +* `Camera.centerToBounds` didn't take the bounds offset into account, so bounds at non-zero positions wouldn't center properly. All bounds now center correctly. Fix #3706 (thanks @cyantree) +* `Camera.setBounds` has a new optional argument `centerOn`. If specified it will automatically center the camera on the new bounds given. +* The Camera will no longer stutter when following Game Objects at high zoom levels. +* `Camera._id` has been renamed to `Camera.id`, a read-only bitmask used for camera exclusion from Game Objects. +* The Camera Manager `cameraPool` has been removed entirely. It was mostly pointless in practice as Cameras are not regenerated frequently enough to need pooling. It also didn't maintain the bitmask list correctly before. +* `CameraManager.resetAll` now destroys all current Cameras, resets the camera ID marker to 1 and adds a single new Camera. +* `CameraManager.currentCameraId` has been removed. IDs are assigned more intelligently now, via the `getNextID` internal method. +* `CameraManager.addExisting` no longer needs to be passed a Camera that already exists in the pool (as the pool has been removed), meaning you can now create your own Cameras and pass them to `addExisting` and have them treated as normal cameras and not be ignored by the manager. They are also assigned a proper ID when added. +* `CameraManager.addExisting` has a new boolean argument `makeMain` which will make the new camera the main one. +* `CameraManager.getTotal` is a new method that will return the total number of Cameras being managed, with an optional `isVisible` argument, that only counts visible cameras if set. +* `CameraManager.remove` can now take an array of cameras to be removed from the manager, as well as a single camera. +* `CameraManager.remove` would previously not allow you to remove a camera if it meant there would be no cameras left in the Camera Manager. This restriction has been removed. A Camera Manager can now run even with zero cameras. Your game obviously won't display anything, but it's still now possible. +* `CameraManager.remove` will now return the total number of Cameras removed. + +### Round Pixels Changes + +Before explaining the changes it's worth covering what the three different game config properties do: + +`roundPixels` - this will cause the renderer to draw most Game Objects at whole integer positions. Their actual positions can be anything, but the renderer will floor the values to ensure they are integers immediately before drawing. It only works on texture based Game Objects. Graphics objects, for instance, ignore this property. + +`antialias` - when set to `true` WebGL textures are created using `gl.LINEAR`, which allows WebGL to try its best to interpolate the texture when rendered at non-texture frame sizes. This can happen if you scale a Game Object, or zoom a Camera. In both cases it will need to interpolate the pixel values to accommodate the new size. If this property is set to `false` then it will use `gl.NEAREST` instead. This uses a nearest neighbor method of interpolation, and is nearly always the better option if you need to keep the textures crisp, such as when using scaled pixel art. Disabling `antialias` invokes nearest-neighbor interpolation on the game canvas itself as well. If you need a mixture of aliased and anti-aliased textures in your game, then you can change them on a per-texture basis by using `Texture.setFilter`. + +There is a third game config property called `pixelArt`. If set to `true` it's the same thing as enabling `roundPixels` and disabling `antialias`. This is the optimum setting for pixel art games. + +* Both renderers will now check for `pixelArt` OR `antialias` before setting the canvas scale mode. Both values are checked during texture creation as well. +* If in your game config you have enabled either pixel art mode or roundPixels, then all Cameras will have their `roundPixels` values set to `true` by default. You can toggle this by changing the `CameraManager.roundPixels` property, or change it on a camera-by-camera basis, as needed. +* `Camera.roundPixels` is now used across all rendering code for both Canvas and WebGL. Previously, it would check the renderer config value, but now all renderer code uses the camera value to decide if it should floor the drawing position or not. + +### Texture Tint Pipeline - New Features, Updates and Fixes + +The Texture Tint Pipeline has been rewritten to tidy up hundreds of lines of duplicate code and to move the responsibility of drawing to the Game Objects themselves. Previously, had you excluded say Tilemaps from your build of Phaser, the renderer would still include masses of code dealing with the drawing of them. This task has been moved to the Game Objects and the pipeline just provides a set of clean utility functions for batching, flushing and drawing. + +The decision to make this change was not taken lightly. However, I felt that none of the pipelines actually lived up to their name. You could never actually pass objects through one pipeline to another as they didn't have entry and exit points and were instead just glorified singular batches. Although you could change the pipeline being used on a Game Object this action meant that every pipeline had to be responsible for every single type of Game Object, both now and in the future, and they were full of redundant stub functions as a result. The payload size was also considerable. It has now gone from 1,961 lines of code at 76 KB down to 729 lines of code and 27 KB. It's not the only file to benefit either. The `ForwardDiffuseLightPipeline` also reduced from 402 lines (15.7 KB) down to 159 lines and 6 KB. Sizes include comments and are un-minified. In a production bundle the difference will be even greater. This is work we will continue in the next release as we do the same updates to the FlatTintPipeline, responsible for rendering Graphics objects, and look at consolidating the shaders allowing you to use Graphics and Sprites mixed in the display list with no shader swapping cost. + +* You can now set the WebGL batch size in the Game Config via the property `batchSize`. The default is 2000 before the batch will flush, which is a happy average between desktop and mobile. If targeting desktop specifically, you may wish to increase this value to reduce draw calls. +* There is a new method `batchVertices` which will add a vertices block to the current batch. This is now used internally by nearly all render functions. +* The shader has a new attribute: `tintEffect`. This is a single FLOAT. +* The vertex size has increased by 1 FLOAT to account for the extra shader attribute. +* All of the rendering functions now use the `TransformMatrix` class far more than before. This allows the matrix operations to be run-time compiled and cut down on masses of code. +* The `drawTexture` method has been removed. It has been replaced by `drawTextureFrame` which has a new and more concise signature. See the API docs for details. +* The `batchTileSprite` method has been removed. It is now handled in the TileSprite WebGL Render function. +* The `drawStaticTilemapLayer` method has been removed. It is now handled in the Static Tilemap Layer WebGL Render function. +* The `drawEmitterManager` method has been removed. It is now handled in the Particle Manager WebGL Render function. +* The `batchText` method has been removed. It is now handled in the Static Text WebGL Render function. +* The `batchDynamicTilemapLayer` method has been removed. It is now handled in the Dynamic Tilemap Layer WebGL Render function. +* The `batchMesh` method has been removed. It is now handled in the Mesh WebGL Render function. +* The `batchBitmapText` method has been removed. It is now handled in the BitmapText WebGL Render function. +* The `batchDynamicBitmapText` method has been removed. It is now handled in the DynamicBitmapText WebGL Render function. +* The `batchBlitter` method has been removed. It is now handled in the Blitter WebGL Render function. + +Due to the changes in the Texture Tint Pipeline the `Textures.Frame` class has also been updated. The following changes concern the Frame UV data: + +* Previously, the UV data spanned 8 properties: `x0`, `y0`, `x1`, `y1`, `x2`, `y2`, `x3` and `y3` and was stored in the `data.uvs` object. These have been replaced with directly accessible properties: `u0`, `v0`, `u1` and `v1`. These 4 properties are used directly in all renderer code now. Although it was clearer having 8 properties, 4 of them were just duplicates, so we've traded a little clarity for a smaller overall object and less dictionary look-ups. +* `Frame.uvs` (and the corresponding `Frame.data.uvs`) object has been removed. + +### New Tint Effects + +As well as tidying the Texture Tint Pipeline, I also updated the shader. It now has a new attribute 'tintEffect' which allows you to control how a tint is applied to a Game Object. The default way tinting worked was for the tint color values to be multiplied with the texture pixel values. This meant you were unable to do things like tint a Game Object white, because multiplying a color by white doesn't change it. The new tint mode allows you to literally replace the pixel color values. + +* `setTintFill` is a new method available to all Game Objects that have the Tint component. It differs from `setTint` in that the colors literally replace the pixel values from the texture (while still respecting the alpha). This means you can now create effects such as flashing a sprite white if it gets hit, or red for damage, etc. You can still use different colors per corner of the Game Object, allowing you to create nice seamless gradient effects. +* `tintFill` is a new boolean property that allows you to toggle between the two different tint types: multiply or replace. +* `isTinted` is a new read-only boolean indicating if a Game Object is tinted or not. Handy for knowing if you need to clear a tint after an effect. +* `Mesh.tintFill` allows you to control the tint effect applied to the Mesh vertices when color blending. + +The Tint component documentation has been overhauled to explain these differences in more detail, and you can find lots of new examples as well. + +### New Texture Crop Component + +There is a new Game Object Component called `TextureCrop`. It replaces the Texture Component (which still exists) and adds in the ability to crop the texture being used. This component is now being used by the `Sprite` and `Image` Game Objects. + +* You can crop the frame being used via the new `setCrop` method. The crop is a rectangle that limits the area of the texture frame that is visible during rendering. Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just changes what is shown when rendered. This is ideal for hiding part of a Sprite without using a mask, or for effects like displaying a progress or loading bar. Cropping works even when the Game Object is flipped, or is a trimmed frame from an atlas. +* You can toggle the crop on a Game Object by changing the `isCropped` boolean at any point. +* The crop is automatically re-applied when the texture or frame of a Game Object is changed. If you wish to disable this, turn off the crop before changing the frame. + +### BitmapText New Features, Updates and Bug Fixes + +* Multi-line BitmapText objects can now be aligned. The constructor has a new argument `align` which can accept either left-aligned (the default), center aligned, or right-aligned. Alignment works by calculating the longest line of text in the object and then offsetting the other lines to match it. +* `BitmapText.setCenterAlign` is a new chainable method to center-align the text. +* `BitmapText.setLeftAlign` is a new chainable method to left-align the text. +* `BitmapText.setRightAlign` is a new chainable method to right-align the text. +* `BitmapText.align` is a new property that holds the alignment of the text. +* `BitmapText.setFont` is a new method that allows you to change the font it is rendering with. +* Internally all of the BitmapText properties have been renamed with an underscore (i.e. `letterSpacing` is now `_letterSpacing`), so as to not change the API, getters and setters for them all have been added. +* Internally there is a new `dirty` flag that tracks if any part of the BitmapText has changed. This is used when getting the BitmapText's bounds object, as used in the renderer for line alignment, and in properties like `width` and `height`. The dirty flag ensures the bounds are only recalculated if something has changed, cutting down on un-necessary calculations. +* `GetBitmapTextSize`, which is used internally in the BitmapText Game Objects, will now produce different bounds from the previous version. Previously, the bounds were tight against the letters in the text. However, this meant the bounds were not properly aligned with the origin of the BitmapText, and consequently you'd get different bounds if the text consisted of different characters. The bounds are now calculated purely based on the glyph data and letter spacing values. This will give a far more consistent overall experience, but it does mean if you were using the bounds to position text previously, you'll need to revisit that code again. See issue #3799 for more details (and to discuss this further if you wish) (thanks @SBCGames) +* `GetBitmapTextSize` and its exposed method `BitmapText.getTextBounds` now factor in the display origin of the BitmapText into the `global` position returned. +* The `BitmapText` WebGL Renderer incorrectly calculated the font scale at very small sizes, causing characters to overlap when they shouldn't. Scale is now applied to the correct component parts in the render code. +* Under WebGL `BitmapText` would be cut off if you specified a resolution value > 1. Fix #3642 (thanks @kanthi0802) +* Under WebGL, `DynamicBitmapText` that had a crop set on it would fail to render if anything was above it on the display list. It now crops properly, no matter what is above or below it on the display list. +* The `DynamicBitmapText` class now extends the `BitmapText` class. This saves on lots of space in the bundle and consolidates functionality between the two. Please be aware of it if you have classes that extend either of them. +* If you were using the `displayCallback` in the `DynamicBitmapText` class it would generate a brand new object containing all the glyph data, every frame, for every glyph, and send it to the callback. This has been changed so it now uses a new cached local object: `callbackData`. This object is recycled for every glyph, stopping un-needed gc from building up. + +### Dynamic Tilemap Layer New Features, Updates and Bug Fixes + +* `DynamicTilemapLayer.tilesDrawn` is a read-only property that contains the number of tiles sent to the renderer in the previous frame. +* `DynamicTilemapLayer.tilesTotal` is a read-only property that contains the total number of tiles in the layer, updated every frame. +* `DynamicTilemapLayer.skipCull` and its associated chainable method `setSkipCull` allows you to control if the cameras should cull the layer tiles before rendering them or not. By default they will cull, to avoid over-rendering, but in some circumstances you may wish to disable this and can now do so by toggling this property. +* The `CullTiles` component, as used by the Dynamic Tilemap, has been recoded from scratch to take advantage of updates in the Camera system. It will now properly cull tiles, irrespective of the layer scale, or camera zoom. It also now supports the layers `skipCull` property, allowing you to override the culling. The Dungeon Generator labs demo now works again as a result of this fix, and has been updated with a debug mode and camera control UI. You can edit the example source to swap between 4 different dungeon layouts, from 2500 tiles up to 1 million tiles. There are limitations to the way the culling works though. If you rotate the camera you may find you see the cull edge. You can disable this using the new `skipCull` property. Fixing this also fixed #3818 (thanks @Mursaat) +* `DynamicTilemapLayer.cullPaddingX`, `cullPaddingY` and the associated chainable method `setCullPadding` allows you to control how many additional tiles are added into the cull rectangle when it is calculated. If you find that your camera size and zoom settings are causing tiles to get prematurely culled, resulting in clipping during scrolling, then set the `cullPadding` values to add extra layers of tiles to the calculations in both directions without needing to disable culling entirely. +* `DynamicTilemapLayer.cullCallback` allows you to change the function that is used to perform the tile culling. By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. It is sent 3 arguments: the layer data, the camera and the array to store the tiles in. Using this feature you can now create whatever culling system you require, should the default one prove to not be suitable for your game. Fix #3811 (thanks @georgzoeller) +* Dynamic Tilemap Layers now properly support the Lights2D Pipeline. This means you can provide a normal map for the layer tileset and it'll illuminate with the Lights shader properly. See the new `light map` example in the labs for a demonstration. Note that there are limits on the number of tiles that can be rendered with lighting enabled. Fix #3544 (thanks @FrancescoNegri) + +### New Features + +* `Graphics.fillRoundedRect` will draw a stroked rounded rectangle to a Graphics object. The radius of the corners can be either a number, or an object, allowing you to specify different radius per corner (thanks @TadejZupancic) +* `Graphics.strokeRoundedRect` will draw a filled rounded rectangle to a Graphics object. The radius of the corners can be either a number, or an object, allowing you to specify different radius per corner (thanks @TadejZupancic) +* `ParticleEmitter.stop` is a new chainable method to stop a particle emitter. It's the same as setting `on` to `false` but means you don't have to break the method flow to do so (thanks @samme) +* `ScenePlugin.pause` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'pause' event. +* `ScenePlugin.resume` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'resume' event. +* `ScenePlugin.sleep` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'sleep' event. +* `ScenePlugin.wake` (and the corresponding methods in Scene Systems and the Scene Manager) now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'wake' event. +* `ScenePlugin.setActive` now has a new optional `data` argument, which is passed to the target Scene and emitted in its 'pause' or 'resume' events. +* `TileSprite.tileScaleX` and `tileScaleY` are two new properties that allow you to control the scale of the texture within the Tile Sprite. This impacts the way the repeating texture is scaled, and is independent to scaling the Tile Sprite itself. It works in both Canvas and WebGL mode. +* `TransformMatrix.copyFrom` is a new method that will copy the given matrix into the values of the current one. +* `TransformMatrix.multiplyWithOffset` is a new method that will multiply the given matrix with the current one, factoring in an additional offset to the results. This is used internally by the renderer code in various places. +* `Rectangle.Intersection` will take two Rectangle objects and return the area of intersection between them. If there is no intersection, an empty Rectangle is returned. +* `Pointer.prevPosition` is a new Vector2 that stores the previous position of the Pointer, prior to the most recent DOM event. You can use this when performing calculations between the old and current positions, such as for tracking the pointer speed. +* `Pointer.getInterpolatedPosition` is a new method that will return an array of smoothly interpolated values between the old and previous position of the Pointer. You can configure how many interpolation steps should take place (the default is 10) and provide an output array to store them in. This method is handy if you've got an object tracking a pointer and you want to ensure it has smooth movement (as the DOM will often process pointer events at a faster rate than the game loop can update). +* `TransformMatrix.copyFromArray` will populate a matrix from the given array of values. Where 0, 1, 2, 3, 4 and 5 map to a, b, c, d, e and f. +* `WebGLPipeline` has a new over-rideable method called `boot` which is called when the renderer and all core game systems have finished being set-up. +* `KeyboardPlugin.checkDown` is a new method that allows you to check if a Key is being pressed down or not in an update loop. The difference between this method and checking the `Key.isDown` property directly is that you can provide a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it will only return `true` every 100ms. + +### Updates + +* DataManager.removeValue (and by extension the `remove` method too) will not emit the parent of the DataManager as the 2nd argument in the `removedata` event, to keep it consistent with the set events (thanks @rexrainbow) +* The docs for the Loader `filecomplete` event said that you could listen for a specific file using its type and key, i.e.: `filecomplete-image-monster`, however, the code used an underscore instead of a hyphen. We feel the hyphen looks cleaner, so the Loader code has been updated, meaning you can now use the hyphen version of the event properly (thanks @NokFrt) +* If a Game Object is already being dragged, it cannot be dragged by another pointer (in multi-touch mode) until the original pointer has released it (thanks @rexrainbow) +* Calling `Tween.play` on a tween created via `TweenManager.create` wouldn't actually start playback until the tween was first added to the Tween Manager. Now, calling `play` will have it automatically add itself to the Tween Manager if it's not already in there. Fix #3763 (thanks @pantoninho) +* If the Blitter object has no Bobs to render it will now abort immediately, avoiding several context calls in Canvas mode. +* `Scene.run` will now pass the optional `data` object in all cases, no matter if it's waking, resuming or starting a Scene (thanks @rook2pawn) +* `ScenePlugin.start` and `ScenePlugin.restart` will now always queue the op with the Scene Manager, regardless of the state of the Scene, in order to avoid issues where plugins carry on running for a frame before closing down. Fix #3776 (thanks @jjalonso) +* `Tileset.glTexture` is a new property that maps to the WebGL Texture for the Tileset image. It's used internally by the renderer to avoid expensive object look-ups and is set automatically in the `Tileset.setImage` method. +* `Frame.glTexture` is a new property that maps to the WebGL Texture for the Frames Texture Source image. It's used internally by the renderer to avoid expensive object look-ups and is set automatically in the `Frame` constructor. +* `TransformMatrix.e` and `TransformMatrix.f` are two new properties that are an alias for the `tx` and `ty` values. +* `Graphics.arc` has a new optional argument `overshoot`. This is a small value that is added onto the end of the `endAngle` and allows you to extend the arc further than the default 360 degrees. You may wish to do this if you're trying to draw an arc with an especially thick line stroke, to ensure there are no gaps. Fix #3798 (thanks @jjalonso) +* The TextureManager Sprite Sheet Parser will now throw a concise console warning if you specify invalid frame sizes that would result in no frames being generated (thanks @andygroff) +* The `Quad` Game Object now has a new `setFrame` method that allows you to change the frame being rendered by the Quad, including using frames that are part of a texture atlas. Fix #3161 (thanks @halgorithm) +* The `ScenePlugin` will now queue all of the following ops with the Scene Manager: `start`, `run`, `pause`, `resume`, `sleep`, `wake`, `switch` and `stop`. This means for all of these calls the Scene Manager will add the call into its queue and process it at the start of the next frame. This fixes #3812 and keeps things more predictable (thanks @Waclaw-I) +* `TransformMatrix.multiply` has a new optional argument `out` which is a matrix to store the multiplication results in. If not given it will act as before, multiplying the current matrix. +* `Zones` now have a NOOP `setAlpha` method, which allows them to be added into Containers (thanks @TadejZupancic) +* The `setPipeline` method now returns the instance of the Game Object on which it was called. It used to return the pipeline that was set, but this made it non-chainable which broke with the conventions set in all the other `set` methods. If you use `setPipeline` in your code anywhere to retrieve the pipeline reference, please use the `pipeline` property of the Game Object instead. + +### Bug Fixes + +* The DataManager `changedata` event was emitting the original value of the data instead of new value (thanks @iamchristopher) +* The LoaderPlugin didn't emit the `filecomplete` event if any of files failed to load, causing it to fail to run the Scene `create` function as well. Fix #3750 (thanks @NokFrt) +* Fix setter calls in BuildGameObjectAnimation so it will now properly set the delay, repeat, repeat delay and yoyo of a config based animation (thanks @DannyT) +* The Arcade Body `blocked.none` property is now set to `false` after separation with static bodies or tiles. Previously, the blocked direction was set correctly, but the `none` remained `true` (thanks @samme) +* `Bob.setFrame` didn't actually set the frame on the Bob, now it does. Fix #3774 (thanks @NokFrt) +* `Bob.alpha` was ignored by the canvas renderer, only working in WebGL. This has now been fixed. +* Although the Blitter object had the Alpha component, setting it made no difference. Setting Blitter alpha now impacts the rendering of all children, in both Canvas and WebGL, and you can also specify an alpha per Bob as well. +* `SceneManager.run` would ignore scenes that are currently in the queue of scenes pending to be added. This has now been fixed so that the scene is queued to be started once it's ready (thanks @rook2pawn) +* `GameObject.disableInteractive` was toggling input. Every second call would turn the input back on (thanks @TadejZupancic) +* The position of the TilemapLayer wasn't taken into account when culling tiles for the Camera. It's now calculated as part of the cull flow (thanks @Upperfoot) +* Fix extra argument passing in Array.Each (thanks @samme) +* TileSprite was using the Size component instead of ComputedSize, meaning its `getBounds` and `displayWidth` and `displayHeight` results were incorrect. Fix #3789 (thanks @jjalonso) +* `ArrayUtils.AddAt` didn't calculate the array offset correctly if you passed an array in to be merged with an existing array. This also caused Container.addAt to fail if an array was passed to it. Fix #3788 (thanks @jjalonso) +* The `Pointer.camera` property would only be set if there was a viable Game Object in the camera view. Now it is set regardless, to always be the Camera the Pointer interacted with. +* Added the Mask component to Container. It worked without it, but this brings it in-line with the documentation and other Game Objects. Fix #3797 (thanks @zilbuz) +* The DataManager couldn't redefine previously removed properties. Fix #3803 (thanks @AleBles @oo7ph) +* The Canvas DrawImage function has been recoded entirely so it now correctly supports parent matrix and camera matrix calculations. This fixes an issue where children inside Containers would lose their rotation, and other issues, when in the Canvas Renderer. Fix #3728 (thanks @samid737) +* `clearMask(true)` would throw an exception if the Game Object didn't have a mask. Now it checks first before destroying the mask. Fix #3809 (thanks @NokFrt) +* In the WebGL `GeometryMask` the stencil has been changed from `INVERT` to `KEEP` in order to fix issues when masking Graphics objects and other complex objects. Fix #3807. This also fixes the issue where children in Containers would display incorrectly outside of a Geometry mask. Fix #3746 (thanks @zilbuz @oklar) +* `BitmapMask.destroy` will now remove the textures and framebuffers that it created from the WebGL Renderer as part of the destroy process. Fix #3771 (thanks @nunof07) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@DannyT @squilibob @dvdbrink @t1gu1 @cyantree @DrevanTonder @mikewesthad @tarsupin @shadowofsoul + +Also, a special mention to @andygroff for his excellent work enhancing the search box on the examples site, and @hexus for his assistance completing the documentation for the Game Objects. + +## Version 3.10.1 - Hayashi - 13th June 2018 + +### Bug Fixes + +* The InputManager would only create 1 Pointer, even if Touch input was enabled in the config, which meant you couldn't use touch events unless you first called `addPointer` or specified one in the config. Now, it Touch is enabled in the config, it'll always create 2 pointers by default. + +## Version 3.10.0 - Hayashi - 13th June 2018 + +### Input System New Features + Updates + +* All Input classes are now covered 100% by JSDocs. +* The Input Manager and Input Plugin have been updated to support multiple simultaneous Pointers. Before, only one active pointer (mouse or touch) was supported. Now, you can have as many active pointers as you need, allowing for complex multi-touch games. These are stored in the Input Manager `pointers` array. +* `addPointer` allows you to add one, or more, new pointers to the Input Manager. There is no hard-coded limit to the amount you can have, although realistically you should never need more than 10. This method is available on both the Input Manager and Plugin, allowing you to use `this.input.addPointer` from within your game code. +* InputManager `pointersTotal` contains the total number of active pointers, which can be set in the Game Config using the `input.activePointers` property. Phaser will create 2 pointers on start unless a different value is given in the config, or you can add them at run-time. +* `mousePointer` is a new property that is specifically allocated for mouse use only. This is perfect for desktop only games but should be ignored if you're creating a mouse + touch game (use activePointer instead). +* `activePointer` will now reflect the most recently active pointer on the game, which is considered as being the pointer to have interacted with the game canvas most recently. +* The InputManager and InputPlugin have three new methods: `addUpCallback`, `addDownCallback` and `addMoveCallback`. These methods allow you to add callbacks to be invoked whenever native DOM mouse or touch events are received. Callbacks passed to this method are invoked _immediately_ when the DOM event happens, within the scope of the DOM event handler. Therefore, they are considered as 'native' from the perspective of the browser. This means they can be used for tasks such as opening new browser windows, or anything which explicitly requires user input to activate. However, as a result of this, they come with their own risks, and as such should not be used for general game input, but instead be reserved for special circumstances. The callbacks can be set as `isOnce` so you can control if the callback is called once then removed, or every time the DOM event occurs. +* Pointer has two new properties `worldX` and `worldY` which contain the position of the Pointer, translated into the coordinate space of the most recent Camera it interacted with. +* When checking to see if a Pointer has interacted with any objects it will now iterate through the Camera list. Previously, it would only check against the top-most Camera in the list, but now if the top-most camera doesn't return anything, it will move to the next camera and so on. This also addresses #3631 (thanks @samid737) +* `InputManager.dirty` is a new internal property that reflects if any of the Pointers have updated this frame. +* `InputManager.update` now uses constants internally for the event type checking, rather than string-based like before. +* `InputManager.startPointer` is a new internal method, called automatically by the update loop, that handles touch start events. +* `InputManager.updatePointer` is a new internal method, called automatically by the update loop, that handles touch move events. +* `InputManager.stopPointer` is a new internal method, called automatically by the update loop, that handles touch end events. +* `InputManager.hitTest` has had its arguments changed. It no longer takes x/y properties as the first two arguments, but instead takes a Pointer object (from which the x/y coordinates are extracted). +* `TouchManager.handler` has been removed as it's no longer used internally. +* `TouchManager.onTouchStart`, `onTouchMove` and `onTouchEnd` are the new DOM Touch Event handlers. They pass the events on to the InputManagers `queueTouchStart`, `queueTouchMove` and `queueTouchEnd` methods respectively. +* `MouseManager.handler` has been removed as it's no longer used internally. +* `MouseManager.onMouseDown`, `onMouseMove` and `onMouseUp` are the new DOM Mouse Event handlers. They pass the events on to the InputManagers `queueMouseDown`, `queueMouseMove` and `queueMouseUp` methods respectively. +* Setting `enabled` to false on either the TouchManager, MouseManager or KeyboardManager will prevent it from handling any native DOM events until you set it back again. +* InputPlugin has the following new read-only properties: `mousePointer`, `pointer1`, `pointer2`, `pointer3`, `pointer4`, `pointer5`, `pointer6`, `pointer7`, `pointer8`, `pointer9` and `pointer10`. Most of these will be undefined unless you call `addPointer` first, or set the active pointers quantity in your Game Config. +* InputManager has a new method `transformPointer` which will set the transformed x and y properties of a Pointer in one call, rather than the 2 calls it took before. This is now used by all Pointer event handlers. +* InputPlugin has a new method `makePixelPerfect` which allows you to specify a texture-based Game Object as being pixel perfect when performing all input checks against it. You use it like this: `this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect())`, or the easier: `setInteractive({ pixelPerfect: true })` - you can also pass or set an optional alpha tolerance level. See the method docs for full details and the new examples to see it in action. Note that as a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from the given coordinates and checking its color values. This is an expensive process, so should only be enabled on Game Objects that really need it. + +### Input - Custom Cursors + +* You can now set a custom cursor for your game via `this.input.setDefaultCursor()`. This will take any valid CSS cursor string, including URLs to cursor image files. +* You can now set a custom cursor for specific Game Objects. This will take any valid CSS cursor string, including URLs to cursor image files, and is used when-ever a pointer is over that Game Object. For example, to have a hand cursor appear when over a button Sprite, you can do: `button.input.cursor = 'pointer'`, or to have a help cursor appear: `button.input.cursor = 'help'`, or to have a custom image: `button.input.cursor = 'url(assets/cursors/sword.cur), pointer'`. +* You can also set a custom cursor in the new Input Configuration Object. To use the `pointer` (hand cursor) there is a new short-cut: `setInteractive({ useHandCursor: true })`. To use anything else: `setInteractive({ cursor: CSSString })` where `CSSString` is any valid CSS for setting a cursor. +* Please be aware of limitations when it comes to image based cursors between browsers. It's up to you to find a suitable format and size that fits the browsers you wish to support (note: virtually all modern browsers no longer support animated CSS cursors.) + +### Input - Configuration Objects + +* The `setInteractive` method can now take an Input Configuration object as its only argument. This allows you to set multiple input related properties in a single call, i.e.: `setInteractive({ draggable: true, pixelPerfect: true })`. The available properties are: +* `hitArea` - The object / shape to use as the Hit Area. If not given it will try to create a Rectangle based on the texture frame. +* `hitAreaCallback` - The callback that determines if the pointer is within the Hit Area shape or not. +* `draggable` - If `true` the Interactive Object will be set to be draggable and emit drag events. +* `dropZone` - If `true` the Interactive Object will be set to be a drop zone for draggable objects. +* `useHandCursor` - If `true` the Interactive Object will set the `pointer` hand cursor when a pointer is over it. This is a short-cut for setting `cursor: 'pointer'`. +* `cursor` - The CSS string to be used when the cursor is over this Interactive Object. +* `pixelPerfect` - If `true` the a pixel perfect function will be set for the hit area callback. Only works with texture based Game Objects. +* `alphaTolerance` - If `pixelPerfect` is set, this is the alpha tolerance threshold value used in the callback. + +### Input - Keyboard Manager Updates + +* The `KeyboardManager` class has been removed. It has been replaced with `KeyboardPlugin` which is now an Input level plugin, that registers itself with the new `InputPluginCache`. The Input Plugin class (which belongs to a Scene) will now automatically inject registered plugins into itself on boot. Every Scene has its own instance of the Input Plugin (if enabled in the scene plugins), which in turn has its own instance of the KeyboardPlugin. The `InputManager` no longer has any reference to the Keyboard class at all. The benefits of this are two-fold: First, it allows you to now entirely exclude all of the keyboard classes from a custom build, saving a lot of space if not required. Secondly, it means that the Scenes themselves are now responsible for keyboard events, where-as before they were entirely global. This means a Scene can be paused and stop processing keyboard events, and stop having its Key objects updated, while another Scene can still carry on doing this. It also prevents key related callbacks in sleeping Scenes from being fired (which resolves issue #3733, thanks @JoeMoov2) +* `KeyboardManager.handler` has been renamed to `onKeyHandler`. +* The `KeyboardManager.captures` property has been removed as it can be more effectively handled by polling the `keys` object instead. +* The Keyboard Manager will no longer process key down or up events if its `enabled` property is set to false, or if the Scene to which it belongs is not active. +* The Keyboard Manager will now call `event.preventDefault` on the native DOM event as long as the Key exists in the keys array and has its `preventDefault` property set to `true` (which is the default). This means you can now control specifically which key prevents default on the browser, where-as before every key added did so. +* KeyboardManager `addKeyCapture` and `removeKeyCapture` have been removed as you now control which keys prevent capture by using the `addKey` or `addKeys` methods (see entry above). The act of creating a Key is now enough to enable capture of it and can be toggled (at run-time) on a per-Key basis. +* `KeyboardManager.addKeys` can now take either an object, or key codes, or a comma-separated string as its input. This means you can now do: `keyboard.addKeys('W,S,A,D')` and get an object back with the properties WSAD mapped to the relevant Key objects. +* `KeyboardManager.addKey` can now take either a Key object, a string, such as `A` or `SPACE`, or a key code value. +* `KeyboardManager.removeKey` can now take either a Key object, a string, such as `A` or `SPACE`, or a key code value. + +### Input - Gamepad Manager Updates + +* The `GamepadManager` class has been removed. It has been replaced with `GamepadPlugin` which is now an Input level plugin, that registers itself with the new `InputPluginCache`. The Input Plugin class (which belongs to a Scene) will now automatically inject the registered plugins into itself on boot. Every Scene has its own instance of the Input Plugin (if enabled in the scene plugins), which in turn has its own instance of the GamepadPlugin. The `InputManager` no longer has any reference to the Gamepad class at all. The benefits of this are two-fold: First, it allows you to now entirely exclude all of the gamepad classes from a custom build, saving a lot of space if not required. Secondly, it means that the Scenes themselves are now responsible for gamepad events, where-as before they were entirely global. This means a Scene can be paused and stop processing gamepad events, and stop having its Gamepad objects updated, while another Scene can still carry on doing this. It also prevents gamepad related callbacks in sleeping Scenes from being fired. +* The Gamepad Plugin has been rewritten from scratch. It now offers a lot more features and far easier access to the Gamepads and their properties. You can now access the first 4 gamepads connected to the browser via the `pad1` to `pad4` properties, meaning you can do: `this.input.gamepad.pad1` for direct access to a pad once it's connected. +* The Gamepad class has also been rewritten from scratch. It will no longer create Buttons or Axes dynamically, instead doing so on instantiation. +* The Gamepad class now has a bunch of new properties for easy access to the various standard mapping buttons. These include `left`, `right`, `up`, `down` for directions, `A`, `Y`, `X` and `B` for buttons, `L1`, `L2`, `R1` and `R2` for shoulder buttons, and `leftStick` and `rightStick` for the axis sticks. You can still use `Gamepad.getButtonValue()` to get the value from a button and `Gamepad.getButtonTotal()` to get the total number of buttons available on the pad. +* `Gamepad.getAxisTotal` and `Gamepad.getAxisValue` will return the total number of axis, and an axis value, accordingly. +* `Gamepad.setAxisThreshold` will now let you set the threshold across all axis of a Gamepad in one call. +* The Gamepad `Button` objects will now emit 2 events, one from the button itself and another from the Gamepad. This means you can listen for button events in 3 ways: 1) By directly polling the button value in an update loop, 2) Listening for events on the Gamepad Plugin: `this.input.gamepad.on('down')`, or 3) By listening for events on the Gamepad itself: `gamepadReference.on('down')`. + +### Arcade Physics New Features + Updates + +* Arcade Physics now uses a fixed time-step for all internal calculations. There is a new `fps` config value and property (defaults to 60fps), which you can change at run-time using the `setFPS` method. The core update loop has been recoded so that it steps based entirely on the given frame rate, and not the wall-clock or game step delta. This fixed time step allows for a straightforward implementation of a deterministic game state. Meaning you can now set the fps rate to a high value such as 240, regardless of the browser update speed (it will simply perform more physics steps per game step). This is handy if you want to increase the accuracy of the simulation in certain cases. +* You can also optionally call the `step` function directly, to manually advance the simulation. +* There is a new property `timeScale` which will scale all time-step calculations at run-time, allowing you to speed-up or slow-down your simulation at will, without adjusting the frame rate. +* You can now disable the use of the RTree for dynamic bodies via the config property `useTree`. In certain situations, i.e. densely packed worlds, this may give better performance. Static bodies will always use an RTree. +* `collideSpriteVsGroup` has been rewritten. If you are using an RTree it now uses the results directly from the tree search, instead of iterating all children in the Group, which dramatically reduces the work it does. If you have disabled the RTree it performs a brute-force O(N2) Sprite vs. Group iteration sweep. We tested multiple axis sorting variants but the cost of the array allocation and/or sorting, with large amounts of bodies (10,000+), far outweighed the simple math involved in the separation logic. +* `Body.useDamping` is a new boolean property that allows you to use a damping effect for drag, rather than the default linear deceleration. This gives much better results if you need smooth deceleration across both axis, such as the way the ship slows down in the game Asteroids, without the tell-tale axis drift associated with linear drag. +* `GetOverlapX` and `GetOverlapY` now use the calculated delta values, not the deltaX/Y methods. +* `collideSpriteVsGroup` aborts early if the Sprite body has been disabled. +* `updateMotion` has a new argument `delta` which should typically be a fixed-time delta value. +* `intersects` has been restructured to prioritize rect vs. rect checks. +* Body `update` and `postUpdate` have been recoded to handle the new fixed time-step system in place. `update` now takes a new argument, delta, which is used internally for calculations. +* `Body.dirty` has been removed as a property as it's no longer used internally. +* `Body.deltaAbsX` and `deltaAbsY` now return the cached absolute delta value from the previous update, and no longer calculate it during the actual call. +* `World.enable` has been recoded to remove all the `hasOwnProperty` checks and streamline the internal flow. +* `World.disable` has been recoded to remove all the `hasOwnProperty` checks and streamline the internal flow. +* `World.add` is a new method that adds an existing body to the simulation and `enableBody` now passes its newly created bodies to this method. +* `World.disableGameObjectBody` has been removed as it duplicated what the `disable` method did. +* There is a new internal flow with regard to the creation and disabling of bodies. Calling `World.enable` will pass the objects to `enableBody`, which will create a new Body object, if required, and finally pass it to `add`. `World.disable` does the same, but removes the bodies from the simulation. It passes the bodies to `disableBody`, which in turn passes it to `remove`. Both of these work for single objects, an array of objects, Groups or even arrays of Groups. +* `World.computeAngularVelocity` is a new method that specifically calculates the angular velocity of a Body. +* `World.computeVelocity` has had its signature changed. Rather than taking a bunch of arguments all it now takes is a Body and a delta value. Internally it now calculates both the x and y velocity components together in the same single call, where-as before it was split into two calls and multiple assignments. +* `World.computeVelocity` no longer returns the new velocities, they are now set directly on the body within the method. +* `World.computeVelocity` has been recoded to use Fuzzy Greater Than and Less Than calls when applying drag to a previously accelerated body. Using a fuzzy epsilon allows us to mitigate the ping-pong issue, where a decelerating body would constantly flip between a small negative and positive velocity value and never come to an actual rest. +* `World.computeVelocity` now checks the `Body.useDamping` property to perform either linear deceleration or damping on the Body. +* `World.updateMotion` has changed to call the new `computeAngularVelocity` and `computeVelocity` methods. +* Bodies set to bounce would eventually run out of velocity and stop. This has been fixed as part of the refactoring of the time step and compute velocity updates. Fix #3593 (thanks @helmi77) +* If a Body collides with a Static Body it will now set the `blocked` properties accordingly (before it only set the `touching` properties.) This means you can now use checks like `Body.onFloor()` when traversing static bodies (thanks @fariazz) + +### Data Manager New Features and Updates + +* You can now access anything set in the DataManager using the new `values` property. For example, if you set a new value such as this: `data.set('gold', 50)` you can now access it via: `data.values.gold`, where it is treated as a normal property, allowing you to use it in conditional evaluations `if (data.values.level === 2)`, or modify it: `data.values.gold += 50`. +* Each time a value is updated it emits a `changedata` event, regardless if it is changed via the `set` method, or the new `values` approach. +* Each time a value is updated it emits a new event named after the value. For example, if the value was called `PlayerLives`, it will emit the event `changedata_PlayerLives`. This happens regardless if it is changed via the `set` method, or the new `values` approach. +* The `set` method can now take an object containing key value pairs as the first argument. This means you can now set a bunch of values all at once, i.e: `data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 })`. +* The `get` method can now take an array of keys, and will return an array of matching values. This is handy for array destructuring in ES6. +* The `remove` method can now take an array of keys, and will remove all matching values, emitting the `removedata` event for each. +* The order of events has been updated. When a value is first set, and doesn't already exist in the Data Manager, it will emit a `setdata` event. If a value is set that already exists, it instead emits a `changedata` and related `changedata_key` event. Setting a new value no longer emits both events. +* The `resetFunction` function has been removed from the `changedata` event arguments. Previously this was used to allow you to stop a value being updated by calling the reset function instead. However, it created brand new anonymous functions every single time a value was updated. As you can now access stored data via the `values` property you can use this for much easier conditional checks and sets. +* The `blockSet` property has been removed as it's no longer used internally. + +### Loader and Scene Updates + +* Internally, the Loader has changed slightly. Rather than have each file cause the new batch to load, an `update` method is polled every frame, which does the same job instead. This avoids load-time race conditions where pre-populated files would trigger loads part way during an existing load, fixing #3705 in the process (thanks @the-simian) +* The Scene Manager has been updated so that it will call Scene.Systems.step during the `init`, `preload` and `create` phase of your Scene. This means that any plugins, or custom code, written to use the Scene Systems `preupdate`, `update` or `postupdate` events will need to be aware that these are now fired from `init` onwards, not just once `create` has finished. +* As a result of these two changes, there is a new Systems property called `sceneUpdate`, which is a reference that maps to your `Scene.update` function. During `init`, `preload` and `create` this is always mapped to NOOP. Once `create` has finished it gets re-mapped to your Scene's update function. If your Scene doesn't have one, it remains mapped to NOOP. In practise, this means nothing has changed from before. `Scene.update` never ran until `create` was completed, and it still doesn't. However, because the internal Scene systems are now updating right from `init`, it means that things like the update list and physics systems are fully operational _during_ your Preloader. This allows you to create far more elaborate preloaders than ever before. Although, with great power comes great responsibility, as the onus is now on you to be careful which events you consume (especially input events) during your preloader. +* Another side-effect of these changes is that Scenes no longer need an 'update' function at all. Previously, if they were missing one, the Scene Manager would inject one into them automatically. It no longer does this. + +### New Features + +* `RenderTexture.resize` will allow you to resize the underlying Render Texture to the new dimensions given. Doing this also clears the Render Texture at the same time (thanks @saqsun). +* `Rectangle.RandomOutside` is a new function that takes two Rectangles, `outer` and `inner`, and returns a random point that falls within the outer rectangle but is always outside of the inner rectangle. +* The Update List has a new read-only property `length`, making it consistent with the Display List (thanks @samme) +* The 2D Camera class has two new read-only properties `centerX` and `centerY` which return the coordinates of the center of the viewport, relative to the canvas (thanks @samme) +* Camera has a new property `visible`. An invisible Camera will skip rendering and input tests of everything it can see. This allows you to create say a mini-cam and then toggle it on and off without needing to re-create it each time. +* Camera has a new method `setVisible` which toggles its visible property. +* `CameraManager.fromJSON` will now set the visible property is defined in the config. +* `ScenePlugin.run` is a new method that will run the given Scene and not change the state of the current Scene at all. If the scene is asleep, it will be woken. If it's paused, it will be resumed. If not running at all, it will be started. +* `TextureManager.getPixelAlpha` is a new method that will return the alpha value of a pixel from the given texture and frame. It will return `null` if the coordinates were out of bounds, otherwise a value between 0 and 255. +* `Game.isOver` is a new read-only boolean property that indicates if the mouse pointer is currently over the game canvas or not. It is set by the VisibilityHandler and is only reliable on desktop systems. +* A new event `Game.mouseout` is dispatched if the mouse leaves the game canvas. You can listen to it from `this.sys.game.events.on('mouseout')` from within a Scene. +* A new event `Game.mouseover` is dispatched if the mouse enters the game canvas, having previously been outside of it. You can listen to it from `this.sys.game.events.on('mouseover')` from within a Scene. +* You can now use PhysicsEditor (https://www.codeandweb.com/physicseditor) to create complex Matter.js bodies. Load them as normal JSON and then just pass it to the Matter Sprite as a shape property: `this.matter.add.sprite(x, y, texture, frame, { shape: shapes.banana })` (where `shapes.banana` is one of the exported PhysicsEditor shapes in the JSON you loaded). See the 'physics/matterjs/advanced shape creation.js' example for more details. + +### Updates + +* The `ForwardDiffuseLightPipeline`, used by the Lights system, now sets a flag if the Scene doesn't contain any lights. All of the Game Objects now check this flag and don't even bother adding themselves to the batch if there are no lights in the Scene, as they'd never render anyway. This also avoids the ghost-image problem if you swap Scenes to a new Scene with the Light Manager enabled, but no actual lights defined. Fix #3707 (thanks @samvieten). +* `CameraManager.getCameraBelowPointer` has been renamed to `getCamerasBelowPointer` and it now returns an array of all the cameras below the given pointer, not just the top-most one. The array is sorted so that the top-most camera is at the start of the array. +* In `TimeStep.step` the `rawDelta` and `delta` values are checked to make sure they are non-negative, which can happen in Chrome when the delta is reset and out of sync with the value passed to Request Animation Frame. Fix #3088 (thanks @Antriel) +* `Cameras.Controls.Fixed` has been removed. It's was deprecated a few versions ago. Please use `FixedKeyControl` instead. +* `Cameras.Controls.Smoothed` has been removed. It's was deprecated a few versions ago. Please use `SmoothedKeyControl` instead. + +### Bug Fixes + +* The Canvas `RenderTexture.drawImage` method incorrectly set the values of the frame, causing them to appear wrongly scaled in the canvas renderer. Fix #3710 (thanks @saqsun). +* Fixed `Math.Matrix4.makeRotationAxis()` (thanks @hexus) +* Fixed an incorrect usage of `Math.abs()` in `Math.Quaternion.calculateW()` (thanks @qxzkjp). +* Particle Emitter Managers can now be added to Containers (thanks @TadejZupancic) +* Fixed a method signature issue with the Animation component's `remove()` handler when `Animation`s are removed from the `AnimationManager`. This prevented removed animations from stopping correctly. +* If you set Phaser to use a pre-existing Canvas element it is no longer re-added to the DOM (thanks @NQNStudios) +* The `TweenManager.getTweensOf` method has been fixed to remove a potential endless loop should multiple targets be passed in to it (thanks @cyantree) +* Interactive Objects inside of Containers would still fire their input events even if the Container (or any ancestor) was set to be invisible. Objects now check their ancestor tree during the input cull and now properly skip input events if not visible. Fix #3620 (thanks @NemoStein) +* Fixed Device.os incorrectly reporting Linux as OS on Android devices (thanks @AleBles) + +### Examples, Documentation and TypeScript + +Thanks to the work of @hexus we have now documented all of the Math namespace and made good progress on the Game Objects. + +I personally have also documented the entire Input system, which was 328 classes, properties and methods to describe, as well as lots of other areas. + +## Version 3.9.0 - Yui - 24th May 2018 + +### New Features + +* The command `npm run help` will display a friendly list of all the scripts available (run `npm install` first) +* Game has a new property `hasFocus` which is a read-only boolean that lets you know if the window the game is embedded in (including in an iframe) currently has focus or not. +* Game.Config has a new property `autoFocus`, which is `true` by default, and will automatically call `window.focus()` when the game starts. +* Clicking on the canvas will automatically call `window.focus`. This means in games that use keyboard controls if you tab or click away from the game, then click back on it again, the keys will carry on working (where-as before they would remain unfocused) +* Arcade Physics Body has a new method `setAllowDrag` which toggles the `allowDrag` property (thanks @samme) +* Arcade Physics Body has a new method `setAllowGravity` which toggles the `allowGravity` property (thanks @samme) +* Arcade Physics Body has a new method `setAllowRotation` which toggles the `allowRotation` property (thanks @samme) +* Arcade Physics Group Config has 3 new properties you can use: `allowDrag`, `allowGravity` and `allowRotation` (thanks @samme) +* PluginManager.registerFileType has a new property `addToScene` which allows you to inject the new file type into the LoaderPlugin of the given Scene. You could use this to add the file type into the Scene in which it was loaded. +* PluginManager.install has a new property `mapping`. This allows you to give a Global Plugin a property key, so that it is automatically injected into any Scenes as a Scene level instance. This allows you to have a single global plugin running in the PluginManager, that is injected into every Scene automatically. +* Camera.lerp has been implemented and allows you to specify the linear interpolation value used when following a target, to provide for smoothed camera tracking. +* Camera.setLerp is a chainable method to set the Camera.lerp property. +* Camera.followOffset is a new property that allows you to specify an offset from the target position that the camera is following (thanks @hermbit) +* Camera.setFollowOffset is a chainable method to set the Camera.followOffset property. +* Camera.startFollow has 4 new arguments: `lerpX` and `lerpY` which allow you to set the interpolation value used when following the target. The default is 1 (no interpolation) and `offsetX` and `offsetY` which allow you to set the follow offset values. +* Camera.startFollow will now immediately set the camera `scrollX` and `scrollY` values to be that of the target position to avoid a large initial lerps during the first few preUpdates. +* Math.Interpolation.SmoothStep is a new method that will return the smooth step interpolated value based on the given percentage and left and right edges. +* Math.Interpolation.SmootherStep is a new method that will return the smoother step interpolated value based on the given percentage and left and right edges. + +### Updates + +* Container.setInteractive can now be called without any arguments as long as you have called Container.setSize first (thanks rex) +* Bob.reset will now reset the position, frame, flip, visible and alpha values of the Bob. +* VisibilityHandler now takes a game instance as its sole argument, instead of an event emitter. +* PluginManager.createEntry is a new private method to create a plugin entry and return it. This avoids code duplication in several other methods, which now use this instead. +* The Plugin File Type has a new optional argument `mapping`, which allows a global plugin to be injected into a Scene as a reference. +* TileSprite.destroy has been renamed to `preDestroy` to take advantage of the preDestroy callback system. +* RenderTexture.destroy has been renamed to `preDestroy` to take advantage of the preDestroy callback system. +* Group.destroy now respects the `ignoreDestroy` property. +* Graphics.preDestroy now clears the command buffer array. +* Container addHandler will now remove a child's Scene shutdown listener and only listens to `destroy` once. +* Container removeHandler will re-instate a child's Scene shutdown listener. +* Container preDestroy now handles the pre-destroy calls, such as clearing the container. +* Blitter preDestroy will now clear the children List and renderList. +* The AudioContextMonkeyPatch has been updated to use an iife. Fix #3437 (thanks @NebSehemvi) + +### Bug Fixes + +* PluginManager.destroy didn't reference the plugin correctly, throwing an Uncaught TypeError if you tried to destroy a game instance. Fix #3668 (thanks @Telokis) +* If a Container and its child were both input enabled they will now be sorted correctly in the InputPlugin (thanks rex) +* Fix TypeError when colliding a Group as the only argument in Arcade Physics. Fix #3665 (thanks @samme) +* The Particle tint value was incorrectly calculated, causing the color channels to be inversed. Fix #3643 (thanks @rgk) +* All Game Objects that were in Containers were being destroyed twice when a Scene was shutdown. Although not required it still worked in most cases, except with TileSprites. TileSprites specifically have been hardened against this now but all Game Objects inside Containers now have a different event flow, stopping them from being destroyed twice (thanks @laptou @PaNaVTEC) +* Camera.cull will now accurately return only the Game Objects in the camera view, instead of them all. Fix #3646 (thanks @KingCosmic @Yora) +* The `dragend` event would be broadcast even if the drag distance or drag time thresholds were not met. Fix #3686 (thanks @RollinSafary) +* Restarting a Tween immediately after creating it, without it having first started, would cause it to get stuck permanently in the Tween Managers add queue (thanks @Antriel @zacharysarette) +* Setting an existing Game Object as a static Arcade Physics body would sometimes incorrectly pick-up the dimensions of the object, such as with TileSprites. Fix #3690 (thanks @fariazz) +* Interactive Objects were not fully removed from the Input Plugin when cleared, causing the internal list array to grow. Fix #3645 (thanks @tjb295 for the fix and @rexrainbow for the issue) +* Camera.shake would not effect dynamic tilemap layers. Fix #3669 (thanks @kainage) + +### Examples, Documentation and TypeScript + +Thanks to the work of @hexus we have now documented nearly all of the Math namespace. This is hundreds of functions now covered by full docs and is work we'll continue in the coming weeks. + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@mikez @wtravO @thomastanck + +## Version 3.8.0 - Klein - 16th May 2018 + +### New Plugin Manager + +New in this release is a revamped Plugin Manager. Phaser has always used plugins extensively internally but this release opens them up and builds in a lot of new features making them easy for you to both create and digest. + +There is a new `Phaser.Plugins` namespace in which the classes live. The functions of the old PluginManager have moved to the new PluginCache and the PluginManager, which is available under `this.plugins` from all Scenes by default, now allows you to install and access any plugin. + +Plugins are split into two different types: A Global Plugin and a Scene Plugin. + +A **Global Plugin** is a plugin that lives within the Plugin Manager rather than a Scene. You can get access to it by calling `PluginManager.get` and providing a key. Any Scenes that request a plugin in this way all get access to the same plugin instance, allowing you to use a single plugin across multiple Scenes. + +A **Scene Plugin** is a plugin dedicated to running within a Scene. These are different to Global Plugins in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. + +Plugins can now be installed in 3 different ways: 1) You can preload them, using the `load.plugin` and the new `load.scenePlugin` methods. This will allow you to load externally hosted plugins into your game, or pull down a plugin dynamically at run-time. 2) You can install global and scene plugins in your Game Configuration. The plugin code can be bundled with your game code into a single bundle. By specifying plugins in the game config they're instantly available as soon as your game boots. Finally, you can install plugins at run-time directly from within a Scene. + +Plugins can also create brand new Game Objects and File Types, which install themselves into the respective factories. This means you can now write a plugin that adds a new file type and Game Object in a single package. + +The new Plugin Manager and associated classes are 100% covered by JSDocs and there are stacks of new examples in the `plugins` folder in the Phaser 3 Labs too, so please dig in and have a play with these powerful new things! + +### New Features + +* You can pass in your own `canvas` and `context` elements in your Game Config and Phaser will use those to render with instead of creating its own. This also allows you to pass in a WebGL 2 context. Fix #3653 (thanks @tgrajewski) +* WebGLRenderer.config has a new property `maxTextures` which is derived from `gl.MAX_TEXTURE_IMAGE_UNITS`, you can get it via the new method `getMaxTextures()`. +* WebGLRenderer.config has a new property `maxTextureSize` which is derived from `gl.MAX_TEXTURE_SIZE`, you can get it via the new method `getMaxTextureSize()` +* WebGLRenderer has a new property `compression` which holds the browser / devices compressed texture support gl extensions, which is populated during `init`. +* When calling `generateFrameNames` to define an animation from a texture atlas you can now leave out all of the config properties and it will create an animation using every frame found in the atlas. Please understand you've no control over the sequence of these frames if you do this and it's entirely dictated by the json data (thanks @Aram19) +* The keycodes for 0 to 9 on the numeric keypad have been added. You can now use them in events, i.e. `this.input.keyboard.on('keydown_NUMPAD_ZERO')` (thanks @Gaushao) +* All Game Objects have a new method `setRandomPosition` which will randomly position them anywhere within the defined area, or if no area is given, anywhere within the game size. + +### Updates + +* Game.step now emits a `prestep` event, which some of the global systems hook in to, like Sound and Input. You can use it to perform pre-step tasks, ideally from plugins. +* Game.step now emits a `step` event. This is emitted once per frame. You can hook into it from plugins or code that exists outside of a Scene. +* Game.step now emits a `poststep` event. This is the last chance you get to do things before the render process begins. +* Optimized TextureTintPipeline.drawBlitter so it skips bobs that have alpha of zero and only calls `setTexture2D` if the bob sourceIndex has changed, previously it called it for every single bob. +* Game.context used to be undefined if running in WebGL. It is now set to be the `WebGLRenderingContext` during WebGLRenderer.init. If you provided your own custom context, it is set to this instead. +* The Game `onStepCallback` has been removed. You can now listen for the new step events instead. +* Phaser.EventEmitter was incorrectly namespaced, it's now only available under Phaser.Events.EventEmitter (thanks Tigran) + +### Bug Fixes + +* The Script File type in the Loader didn't create itself correctly as it was missing an argument (thanks @TadejZupancic) +* The Plugin File type in the Loader didn't create itself correctly as it was missing an argument. +* WebAudioSoundManager.unlock will now check if `document.body` is available before setting the listeners on it. Fixes old versions of Firefox, apparently. #3649 (thanks @squilibob) +* Utils.Array.BringToTop failed to move the penultimate item in an array due to an index error. Fix #3658 (thanks @agar3s) +* The Headless renderer was broken due to an invalid access during TextureSource.init. +* Animation.yoyo was ignored when calculating the next frame to advance to, breaking the yoyo effect. It now yoyos properly (thanks Tomas) +* Corrected an error in Container.getBoundsTransformMatrix that called a missing method, causing a `getBounds` on a nested container to fail. Fix #3624 (thanks @poasher) +* Calling a creator, such as GraphicsCreator, without passing in a config object, would cause an error to be thrown. All Game Object creators now catch against this. + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@samme @mzguimaraes @NaNdreas @Matthew-Herman @melissaelopez @TheColorRed + +## Version 3.7.1 - Sinon - 8th May 2018 + +### New Features + +* The Phaser 3 Labs has gained a nifty 'search' feature box thanks to @NemoStein - it allows you to filter out the example categories. +* We've added a Mask component, which is available on nearly all Game Objects. It includes the methods `setMask`, `clearMask`, `createBitmapMask` and `createGeometryMask`. +* CanvasTexture is a new extension of the Texture object specifically created for when you've got a Canvas element as the backing source of the texture that you wish to draw to programmatically using the Canvas API. This was possible in previous versions, as a Texture object supported having a Canvas as its source, but we've streamlined the process and made it a lot easier for you to refresh the resulting WebGLTexture on the GPU. To create a CanvasTexture just call the `TextureManager.createCanvas` method as before, only this time you'll get a CanvasTexture back which has helper properties and methods. See the complete JSDocs for more details. +* RandomDataGenerator has a new method: `shuffle` which allows you to shuffle an array using the current RNG seed (thanks @wtravO) +* The Texture Manager now supports normal maps for Atlas JSON (in both hash and array formats), Atlas XML and Atlas Unity. +* All Game Objects have a new method `disableInteractive` which will disable the Interactive Object bound to them. You can toggle it back again by calling `setInteractive` with no arguments. +* All Game Objects have a new method `removeInteractive` which will destroy the Interactive Object bound to them entirely. Use this if a Game Object no longer needs any input at all but you don't want to destroy the Game Object itself. + +### Loader New Features and Important Updates + +The Loader has been given an overhaul to improve its performance and extensibility and gains the following new features: + +* A popular feature from Phaser 2 is back: Loader Packs. These are JSON files that contain a bunch of files to load. You can now load a pack into the Loader, and it will parse it and then add the contents into the current load queue automatically. Those contents can be anything the Loader can handle, including other packs! Please see the documentation and examples for more details. +* The Loader is no longer locked during load. New files can be added into the load queue, even while a load is in process. Indeed, this is how the new Pack files feature works. A side effect is that if you do it a lot, your progress bar may jump around, as it's based on the number of files in the loader at that point in time. So if you add a bunch more it may look like it has reduced. It's up to you to handle this in your code, or create a type of loader graphic that doesn't highlight this (such as a spinning circle instead of a progress bar). +* The Loader now handles the flow slightly differently. Before, it would load every file, and once they were all complete it would then process them in turn. Which would add them into the various caches, create textures, and so on. This now happens as soon as the file has loaded because the browser is likely mostly idle during this time anyway, so it allows us to distribute the file processing throughout the load time, rather than in one lump at the end. +* Loading an Audio Sprite has changed. You now specify the JSON file first, and if you wish you can leave out the audio file URLs and let the Loader figure it out from the JSON meta data. +* The Loader has a new file type: `atlasXML` which will load a Shoebox / Starling / Flash CC format XML Texture Atlas. +* The Loader `multiatlas` file type has changed. You no longer have to specify the URLs of the images, instead it reads them from the JSON data and adds them into the loader automatically. +* Every file type the Loader supports can now be loaded either via the method arguments, or a configuration object, or an array of configuration objects. Before only some of them could, but they all use the same code now. See the new examples demonstrating this. +* If you used a Scene files payload then the format of the object has changed. It used to be a property in the Scene Config called `files` which was an array of files to load. It has been renamed to `pack` and it's an object that exactly matches the new Pack File format. Please see the loader example `scene files payload.js` for an example. In short, where you had: `files: []` before, just change it to `pack: { files: [] }` and it'll work. +* The Loader now supports Texture Atlases with normal maps. Before it would only support single images loaded with normal maps, but now you can provide them for all the atlas formats (json, xml and Unity) +* The Loader `multiatlas` feature will now automatically load texture normal maps, if specified in the json. +* Binary Files have a new optional `dataType` argument and property which will cast the binary data to that format after load, before inserting it into the cache, i.e.: `load.binary('mod', 'music.mod', Uint8Array)` +* The method `LoaderPlugin.tilemapWeltmeister` has been renamed to the far more friendly `LoaderPlugin.tilemapImpact`. Everything else about it remains the same, but please update to use the new method name. + +### Loader Updates + +* The Loader and all associated file types are now covered 100% by JSDocs. +* LinkFile is a new type of file used by the Loader that handles multiple files that need to be joined together. For example, loading a JSON and an Image for a Texture Atlas. This is now handled by a LinkFile. +* File has a new argument in its constructor which is an instance of the LoaderPlugin. It stores this in the `loader` property. It also has a new property `cache` which is a reference to the cache that the file type will be stored in. +* File has a new method `hasCacheConflict` which checks if a key matching the one used by this file exists in the target Cache or not. +* File has a new method `addToCache` which will add the file to its target cache and then emit a `filecomplete` event, passing its key and a reference to itself to the listener (thanks to @kalebwalton for a related PR) +* The Loader has a new property `cacheManager` which is a reference to the global game cache and is used by the File Types. +* The Loader has a new property `textureManager` which is a reference to the global Texture Manager and is used by the File Types. +* The Loader will now check to see if loading a file would cache a cache conflict or not, and prevent it if it will. +* The Loader now hands off processing of the file data to the file itself, which will now self-add itself to its target cache. +* The Loader will now call 'destroy' on all Files when it finishes processing them. They now tidy-up references and extra data, freeing them for gc. +* The File Types are now responsible for adding themselves to their respective caches and any extra processing that needs to happen. This has removed all of the code from the Loader that was doing this, meaning the file types are now properly abstracted away and the Loader is no longer bound to them. This allows you to exclude file types if you don't need them, creating smaller bundles as a result. It also means we can drop in new file types easily without touching the Loader itself and Plugins can register new file types. +* The XMLFile type will no longer throw an error if it can't parse the XML, instead it'll log a console warning and not add the XML to the cache. +* Loading a BitmapFont will add the image used as the font texture into the Texture Manager and the XML into the XML cache, using the key you specified for the font, so you can extract it more easily if needed. +* The default number of max parallel file loads has increased from 4 to 32. You can still change it in the game config. +* Normal Maps can now be loaded using a config object: `load.image({ key: 'shinyRobot', url: 'rob.png', normalMap: 'rob_n.png' });` - you can still use the previous array method too. +* Loader.enableParallel has been removed. If you don't want parallel file loads then set the maximum parallel limit to 1. Related to this, the Game Config `loaderEnableParallel` property has been removed. +* You can now set the `X-Requested-With` header in the XHR requests by specifying it in your XHRSettings config, either in the game, scene or file configs. +* Files will consider themselves as errored if the xhr status is >= 400 and <= 599, even if they didn't throw an onerror event. + +### Updates + +* If you're using Webpack with Phaser you'll need to update your config to match our new one. The two changes are: We've removed the need for `raw-loader` and we've changed the syntax of the DefinePlugin calls: +* We've swapped use of the Webpack DefinePlugin so instead of setting a global flag for the compilation of the Canvas and WebGL renderers, we use a typeof check instead. This means you should now be able to ingest the Phaser source more easily outside of Webpack without having to define any global vars (thanks @tgrajewski) +* Under Webpack we still no longer use `raw-loader` to import our shader source. Instead it's compiled to plain JS files during our in-house workflow. This should allow you to bundle Phaser with packages other than Webpack more easily. +* The Texture Manager will now emit an `addtexture` event whenever you add a new texture to it, which includes when you load image files from the Loader (as it automatically populates the Texture Manager). Once you receive an `addtexture` event you know the image is loaded and the texture is safe to be applied to a Game Object. +* BitmapMask and GeometryMask both have new `destroy` methods which clear their references, freeing them for gc. +* CanvasPool has a new argument `selfParent` which allows the canvas itself to be the parent key, used for later removal. +* Frame has a new method `setSize` which allows you to set the frame x, y, width and height and have it update all of the internal properties automatically. This is now called directly in the constructor. +* When a TextureSource is destroyed if it's got a canvas texture it's removed from the CanvasPool. +* TextureManager.checkKey will check if a texture key is in-use and log a console error if it is and then return a boolean. This is now used extensively internally to prevent you from adding textures that already exist into the manager. If you wish to just check if a key is in use without the error, use the `TextureManager.exists` method as before. +* TextureManager.remove will allow you to remove a texture from the manager. The texture is destroyed and it emits a `removetexture` event. +* TextureSource has a new property `renderer` as it's used a lot internally and is useful if you extend the class. +* TextureSource will now remove its respective WebGLTexture from the renderer when destroyed. +* TextureSource will now automatically create a glTexture from its canvas if using one. +* WebGLRenderer will now remove a GL texture from its local `nativeTextures` array when you call the `deleteTexture` method. +* The BaseCache has a new method `exists` that will return a boolean if an entry for the given key exists in the cache or not. +* ScenePlugin.getIndex will return the index of the given Scene in the Scene List. +* The Scene Systems will emit a `ready` event when it has fully finished starting up and all plugins are available. Re: #3636 (thanks @Yazir) +* All Game Object Creators now have an extra boolean argument `addToScene`. If you set this to `true` it will add the Game Object being created to the Scene automatically, while `false` will do the opposite, i.e.: `this.make.image(config, false)`. You can still specify the `add` property in the Config object too, but if the argument is provided it will override the property. +* We have removed the TextureManager.addAtlasPyxel method and related parser. It didn't work anyway and no-one seems to use Pyxel any more. If we get enough demand we can consider adding it back. +* When adding an Audio Sprite to the Sound Manager it will now respect the `loop` property, if set in the source JSON. +* The Texture class has a new method `getDataSourceImage` which will return the raw image data of the data source. +* The WebAudioSoundManager will now listen for 'click' events on the document body, as well as touch events, before resuming the AudioContext, in order to deal with the changes made in Chrome v66 not playing audio until a user gesture is received, even on desktop. + +### Bug Fixes + +* DataManagerPlugin would throw an error on Game.destroy if you had any Scenes in the Scene Manager had not been run. Fix #3596 (thanks @kuoruan) +* If you created a Game with no Scenes defined, and then added one via `Game.scene.add` and passed in a data object, the data would be ignored when starting the Scene. +* Adding a Group with an array of children in the constructor was broken since 3.5. Fix #3612 (thanks @fariazz @samme) +* Fix ParticleEmitter toJSON output, it was missing the `angle` property and the Emitter Ops were being cast wrong (thanks @samme) +* Fixed loading normals with multi image load (thanks @iamchristopher) +* Array.AddAt would fail if it branched to the fast-path within a Container due to an invalid property. Fix #3617 (thanks @poasher) +* Polygon.setTo would fail if given an array of arrays as a list of points. Fix #3619 (thanks @PaulTodd) +* Text objects with word wrapping enabled would gain an extra space at the end of the line. These are now only added when the word index is greater than the previous one. Fix #3626 (thanks @rexrainbow) +* Container.getBounds now checks if it can call `getBounds` on its children before doing so, as some do not have this method (such as Graphics objects) so they no longer cause the call to crash. Fix #3623 (thanks @poasher) +* The Animation Component `setProgress` method was setting the frame on the wrong object. Fix #3633 (thanks @benhhopkins) +* SceneManager.moveAbove wouldn't move the Scene if it was already above the target Scene. Now it moves to be directly above the target Scene no matter where in the Scene List it is. +* SceneManager.moveBelow wouldn't move the Scene if it was already below the target Scene. Now it moves to be directly below the target Scene no matter where in the Scene List it is. +* Emitter.setEmitZone was rejecting custom objects passed as the source argument because it was checking for the wrong methods (thanks @samme) +* ScenePlugin.setActive would only toggle the current Scene, not any given Scene. +* ScenePlugin.setVisible would only toggle the current Scene, not any given Scene. +* The Graphics Creator would automatically add the Graphics to the display list by mistake. The default should be to remain hidden. Fix #3637 (thanks @mikuso) +* BitmapText, both static and dynamic, can now take any data-type, including numbers, for the `text` argument in the constructor. Before they only worked via `setText` (thanks @Jelaw21) +* The Forward Diffuse Light Pipeline was hard coded to assume the normal map would be stored in the source index zero. It now correctly obtains the normal map from the frame source index, which means all Game Objects that used frames from multi-atlas textures will now work with lights properly. +* The Tiled Base64Decode function worked off the wrong array length, causing extra undefined values at the end (thanks @tamagokun) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@wtravO @Fabadiculous @zilbuz @samme @iamchristopher @erd0s @PaNaVTEC @ksmai @snowbillr + +## Version 3.7.0 - Sinon - 4th May 2018 + +A beta release of the 3.7.0 version. See 3.7.1 for details. + +## Version 3.6.0 - Asuna - 19th April 2018 + +### New Features + +* Containers are now fully available! We have removed the beta warning and fixed the way in which they work with Cameras, input and scroll factors. They are also fully documented, so please see their docs and examples for use. +* Group.getLast will return the last member in the Group matching the search criteria. +* Group.getFirstNth will return the nth member in the Group, scanning from top to bottom, that matches the search criteria. +* Group.getLastNth will return the nth member in the Group, scanning in reverse, that matches the search criteria. +* Group.remove has a new optional argument `destroyChild` that will call `destroy` on the child after removing it. +* Group.clear has a new optional argument `destroyChild` that will call `destroy` on all children in the Group after removing them. + +### Updates + +* Impact Physics Game Objects have changed `setLite` to `setLiteCollision`. +* Impact Physics Game Objects have changed `setPassive` to `setPassiveCollision`. +* Impact Physics Game Objects have changed `setFixed` to `setFixedCollision`. +* Impact Physics Game Objects have changed `setActive` to `setActiveCollision`, previously the `setActive` collision method was overwriting the Game Objects `setActive` method, hence the renaming. +* The modifications made to the RTree class in Phaser 3.4.0 to avoid CSP policy violations caused a significant performance hit once a substantial number of bodies were involved. We have recoded how the class deals with its accessor formats and returned to 3.3 level performance while still maintaining CSP policy adherence. Fix #3594 (thanks @16patsle) +* The Retro Font namespace has changed to `Phaser.GameObjects.RetroFont`. Previously, you would access the parser and constants via `BitmapText`, i.e.: `Phaser.GameObjects.BitmapText.ParseRetroFont.TEXT_SET6`. This has now changed to its own namespace, so the same line would be: `Phaser.GameObjects.RetroFont.TEXT_SET6`. The Parser is available via `Phaser.GameObjects.RetroFont.Parse`. This keeps things cleaner and also unbinds RetroFont from BitmapText, allowing you to cleanly exclude it from your build should you wish. All examples have been updated to reflect this. +* If using the `removeFromScene` option in Group.remove or Group.clear it will remove the child/ren from the Scene to which they belong, not the Scene the Group belongs to. + +### Bug Fixes + +* Fixed a bug that caused data to not be passed to another Scene if you used a transition to start it. Fix #3586 (thanks @willywu) +* Group.getHandler would return any member of the Group, regardless of the state, causing pools to remain fixed at once member. Fix #3592 (thanks @samme) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@Fabadiculous @Antriel + +## Version 3.5.1 - Kirito - 17th April 2018 + +### Updates + +* The change made in 3.5.0 with how the Scene systems lifecycle is handled has been tweaked. When a Scene is instantiated it will now emit a boot event, as before, and Systems that need it will listen for this event and set-up their internal properties as required. They'll also do the same under the 'start' event, allowing them to restart properly once shutdown. In 3.5 if a Scene was previously not launched or started you wouldn't be able to access all of its internal systems fully, but in 3.5.1 you can. + +### Bug Fixes + +* LoaderPlugin.destroy would try and remove an incorrect event listener. +* TileSprites would try to call `deleteTexture` on both renderers, but it's only available in WebGL (thanks @jmcriat) +* Using a geometry mask stopped working in WebGL. Fix #3582 (thanks @rafelsanso) +* The particle emitter incorrectly adjusted the vertex count, causing WebGL rendering issues. Fix #3583 (thanks @murteira) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@NemoStein @gabegordon @gazpachu @samme @cristlee @melissaelopez @dazigemm @tgrajewski + +## Version 3.5.0 - Kirito - 16th April 2018 + +### Changes to Cameras + +* The Camera class and all Camera effects are now fully covered by 100% complete JS Docs. +* All Camera effects have been recoded from scratch. They now follow a unified effects structure and each effect is encapsulated in its own class found in the 'effects' folder. Currently there are Fade, Flash and Shake effects. +* The new effects classes are accessed via the Camera properties `fadeEffect`, `flashEffect` and `shakeEffect`. You can still use the friendly Camera level methods: `shake`, `fade` and `flash`. +* The new structure means you can replace the default effects with your own by simply overwriting the properties with your own class. +* The effects now work properly under any combination. For example, you can fade out then in, or in then out, and still flash or shake while a fade is happening. The renderers now properly stack the effects in order to allow this. +* All of the effect related Camera properties (like `_fadeAlpha`) have been removed. If you need access to these values you can get it much more cleanly via the camera effects classes themselves. They were always private anyway, but we know some of you needed to modify them, so have been doing so from your code. This code will now need updating. +* Removed Camera.clearBeforeRender property as it was never used internally. This setting can be enabled on a Game-wide basis. +* Camera now extends the Event Emitter, allowing it to emit events. +* Camera.cullHitTest has been removed. It was never used internally and duplicates the code in `Camera.cull`. +* The `callback` property of the Camera effects methods has changed purpose. It is no longer an `onComplete` callback, but is now an `onUpdate` callback. It is invoked every frame for the duration of the effect. See the docs for argument details. +* Camera effects now dispatch events. They dispatch 'start' and 'complete' events, which can be used to handle any actions you may previously have been doing in the callback. See the effects docs and examples for the event names and arguments. +* The Camera Shake effect now lets you specify a different intensities for the x and y dimensions. +* You can track the progress of all events via the `progress` property on the effect instance, allowing you to sync effect duration with other in-game events. + +### New Feature: Scene Transitions + +There is a new method available in the ScenePlugin, available via: `this.scene.transition` which allows you to transition from one Scene to another over the duration specified. The method takes a configuration object which lets you control various aspects of the transition, from moving the Scenes around the display list, to specifying an onUpdate callback. + +The calling Scene can be sent to sleep, stopped or removed entirely from the Scene Manager at the end of the transition, and you can even lock down input events in both Scenes while the transition is happening, if required. There are various events dispatched from both the calling and target Scene, which combined with the onUpdate callback give you the flexibility to create some truly impressive transition effects both into and out of Scenes. + +Please see the complete JSDocs for the ScenePlugin for more details, as well as the new examples in the Phaser 3 Labs. + +### More New Features + +* GameObject.ignoreDestroy allows you to control if a Game Object is destroyed or not. Setting the flag will tell it to ignore destroy requests from Groups, Containers and even the Scene itself. See the docs for more details. +* The Scene Input Plugin has a new property `enabled` which allows you to enable or disable input processing on per Scene basis. + +### Bug Fixes + +* MatterEvents.off() would cause a TypeError if you destroyed the Matter world. Fix #3562 (thanks @pixelscripter) +* DynamicBitmapText was missing the `letterSpacing` property, causing it to only render the first character in WebGL (thanks @Antriel) +* The Animation component didn't properly check for the animation state in its update, causing pause / resume to fail. Fix #3556 (thanks @Antriel @siolfyr) +* The Scene Manager would never reach an `isBooted` state if you didn't add any Scenes into the Game Config. Fix #3553 (thanks @rgk) +* Fixed issue in HTMLAudioSound where `mute` would get into a recursive loop. +* Every RenderTexture would draw the same content due to a mis-use of the CanvasPool (this also impacted TileSprites). Fix #3555 (thanks @kuoruan) +* Group.add and Group.addMultiple now respect the Group.maxSize property, stopping you from over-populating a Group (thanks @samme) +* When using HTML5 Audio, sound manager now tries to unlock audio after every scene loads, instead of only after first one. Fix #3309 (thanks @pavle-goloskokovic) +* Group.createMultiple would insert null entries if the Group became full during the operation, causing errors later. Now it stops creating objects if the Group becomes full (thanks @samme) +* Group.remove didn't check if the passed Game Object was already a member of the group and would call `removeCallback` and (if specified) `destroy` in any case. Now it does nothing if the Game Object isn't a member of the group (thanks @samme) +* If a Group size exceeded `maxSize` (which can happen if you reduce maxSize beneath the current size), `isFull` would return false and the group could continue to grow. Now `isFull` returns true in that case (thanks @samme) +* Camera.fadeIn following a fadeOut wouldn't work, but is now fixed as a result of the Camera effects rewrite. Fix #3527 (thanks @Jerenaux) +* Particle Emitters with large volumes of particles would throw the error `GL_INVALID_OPERATION: Vertex buffer is not big enough for the draw call` in WebGL. +* Fixed issue with Game.destroy not working correctly under WebGL since 3.4. Fix #3569 (thanks @Huararanga) + +### Updates + +* Removed the following properties from BaseSound as they are no longer required. Each class that extends BaseSound implements them directly as getters: `mute`, `loop`, `seek` and `volume`. +* The Device.OS test to see if Phaser is running under node.js has been strengthened to support node-like environments like Vue (thanks @Chumper) +* Every Plugin has been updated to correctly follow the same flow through the Scene lifecycle. Instead of listening for the Scene 'boot' event, which is only dispatched once (when the Scene is first created), they will now listen for the Scene 'start' event, which occurs every time the Scene is started. All plugins now consistently follow the same Shutdown and Destroy patterns too, meaning they tidy-up after themselves on a shutdown, not just a destroy. Overall, this change means that there should be less issues when returning to previously closed Scenes, as the plugins will restart themselves properly. +* When shutting down a Scene all Game Objects that belong to the scene will now automatically destroy themselves. They would previously be removed from the display and update lists, but the objects themselves didn't self-destruct. You can control this on a per-object basis with the `ignoreDestroy` property. +* A Matter Mouse Spring will disable debug draw of its constraint by default (you can override it by passing in your own config) +* The RandomDataGenerator class is now exposed under Phaser.Math should you wish to instantiate it yourself. Fix #3576 (thanks @wtravO) +* Refined the Game.destroy sequence, so it will now only destroy the game at the start of the next frame, not during processing. + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@samme @Antriel + +## Version 3.4.0 - Miyako - 12th April 2018 + +### New Features + +A beta release of the new Container Game Object arrives in this version. We've flagged it as beta because there are known issues in using Containers in Scenes that have multiple cameras or irregular camera viewports. However, in all other instances we've tested they are operating normally, so we felt it would be best to release them into this build to give developers a chance to get used to them. Using a Container will issue a single console warning as a reminder. We will remove this once they leave beta in a future release. In the meantime they are fully documented and you can find numerous examples in the Phaser 3 Examples repo too. + +* A new property was added to Matter.World, `correction` which is used in the Engine.update call and allows you to adjust the time being passed to the simulation. The default value is 1 to remain consistent with previous releases. +* Matter Physics now has a new config property `getDelta` which allows you to specify your own function to calculate the delta value given to the Matter Engine when it updates. +* Matter Physics has two new methods: `set60Hz` and `set30Hz` which will set an Engine update rate of 60Hz and 30Hz respectively. 60Hz being the default. +* Matter Physics has a new config and run-time property `autoUpdate`, which defaults to `true`. When enabled the Matter Engine will update in sync with the game step (set by Request Animation Frame). The delta value given to Matter is now controlled by the `getDelta` function. +* Matter Physics has a new method `step` which manually advances the physics simulation by one iteration, using whatever delta and correction values you pass in to it. When used in combination with `autoUpdate=false` you can now explicitly control the update frequency of the physics simulation and unbind it from the game step. +* Matter Physics has two new debug properties: `debugShowJoint` and `debugJointColor`. If defined they will display joints in Matter bodies during the postUpdate debug phase (only if debug is enabled) (thanks @OmarShehata) +* Group.destroy has a new optional argument `destroyChildren` which will automatically call `destroy` on all children of a Group if set to true (the default is false, hence it doesn't change the public API). Fix #3246 (thanks @DouglasLapsley) +* WebAudioSound.setMute is a chainable way to mute a single Sound instance. +* WebAudioSound.setVolume is a chainable way to set the volume of a single Sound instance. +* WebAudioSound.setSeek is a chainable way to set seek to a point of a single Sound instance. +* WebAudioSound.setLoop is a chainable way to set the loop state of a single Sound instance. +* HTML5AudioSound.setMute is a chainable way to mute a single Sound instance. +* HTML5AudioSound.setVolume is a chainable way to set the volume of a single Sound instance. +* HTML5AudioSound.setSeek is a chainable way to set seek to a point of a single Sound instance. +* HTML5AudioSound.setLoop is a chainable way to set the loop state of a single Sound instance. +* BitmapText has a new property `letterSpacing` which accepts a positive or negative number to add / reduce spacing between characters (thanks @wtravO) +* You can now pass a Sprite Sheet or Canvas as the Texture key to `Tilemap.addTileset` and it will work in WebGL, where-as before it would display a corrupted tilemap. Fix #3407 (thanks @Zykino) +* Graphics.slice allows you to easily draw a Pacman, or slice of pie shape to a Graphics object. +* List.addCallback is a new optional callback that is invoked every time a new child is added to the List. You can use this to have a callback fire when children are added to the Display List. +* List.removeCallback is a new optional callback that is invoked every time a new child is removed from the List. You can use this to have a callback fire when children are removed from the Display List. +* ScenePlugin.restart allows you to restart the current Scene. It's the same result as calling `ScenePlugin.start` without any arguments, but is more clear. +* Utils.Array.Add allows you to add one or more items safely to an array, with optional limits and callbacks. +* Utils.Array.AddAt allows you to add one or more items safely to an array at a specified position, with optional limits and callbacks. +* Utils.Array.BringToTop allows you to bring an array element to the top of the array. +* Utils.Array.CountAllMatching will scan an array and count all elements with properties matching the given value. +* Utils.Array.Each will pass each element of an array to a given callback, with optional arguments. +* Utils.Array.EachInRange will pass each element of an array in a given range to a callback, with optional arguments. +* Utils.Array.GetAll will return all elements from an array, with optional property and value comparisons. +* Utils.Array.GetFirst will return the first element in an array, with optional property and value comparisons. +* Utils.Array.GetRandomElement has been renamed to GetRandom and will return a random element from an array. +* Utils.Array.MoveDown will move the given array element down one position in the array. +* Utils.Array.MoveTo will move the given array element to the given position in the array. +* Utils.Array.MoveUp will move the given array element up one position in the array. +* Utils.Array.Remove will remove the given element or array of elements from the array, with an optional callback. +* Utils.Array.RemoveAt will remove the element from the given position in the array, with an optional callback. +* Utils.Array.RemoveBetween will remove the elements between the given range in the array, with an optional callback. +* Utils.Array.Replace will replace an existing element in an array with a new one. +* Utils.Array.SendToBack allows you to send an array element to the bottom of the array. +* Utils.Array.SetAll will set a property on all elements of an array to the given value, with optional range limits. +* Utils.Array.Swap will swap the position of two elements in an array. +* TransformMatrix.destroy is a new method that will clear out the array and object used by a Matrix internally. +* BaseSound, and by extension WebAudioSound and HTMLAudioSound, will now emit a `destroy` event when they are destroyed (thanks @rexrainbow) +* A new property was added to the Scene config: `mapAdd` which is used to extend the default injection map of a scene instead of overwriting it (thanks @sebashwa) +* GetBounds `getTopLeft`, `getTopRight`, `getBottomLeft` and `getBottomRight` all have a new optional argument `includeParent` which will factor in all ancestor transforms to the returned point. + +### Bug Fixes + +* In the WebGL Render Texture the tint of the texture was always set to 0xffffff and therefore the alpha values were ignored. The tint is now calculated using the alpha value. Fix #3385 (thanks @ger1995) +* The RenderTexture now uses the ComputedSize component instead of Size (which requires a frame), allowing calls to getBounds to work. Fix #3451 (thanks @kuoruan) +* PathFollower.start has been renamed to `startFollow`, but PathFollower.setPath was still using `PathFollower.start` (thanks @samid737) +* BaseSoundManager.rate and BaseSoundManager.detune would incorrectly called `setRate` on its sounds, instead of `calculateRate`. +* The Gamepad Axis `getValue` method now correctly applies the threshold and zeroes out the returned value. +* The HueToComponent module was not correctly exporting itself. Fix #3482 (thanks @jdotrjs) +* Matter.World was using `setZ` instead of `setDepth` for the Debug Graphics Layer, causing it to appear behind objects in some display lists. +* Game.destroy now checks to see if the `renderer` exists before calling destroy on it. Fix #3498 (thanks @Huararanga) +* Keyboard.JustDown and Keyboard.JustUp were being reset too early, causing them to fail when called in `update` loops. Fix #3490 (thanks @belen-albeza) +* RenderTexture.destroy no longer throws an error when called. Fix #3475 (thanks @kuoruan) +* The WebGL TileSprite batch now modulates the tilePosition to avoid large values being passed into the UV data, fixing corruption when scrolling TileSprites over a long period of time. Fix #3402 (thanks @vinerz @FrancescoNegri) +* LineCurve.getResolution was missing the `divisions` argument and always returning 1, which made it fail when used as part of a Path. It now defaults to return 1 unless specified otherwise (thanks _ok) +* A Game Object enabled for drag would no longer fire over and out events after being dragged, now it does (thanks @jmcriat) +* Line.getPointA and Line.getPointB incorrectly set the values into the Vector2 (thanks @Tomas2h) +* DynamicTilemapLayer now uses the ComputedSize component, which stops it breaking if you call `setDisplaySize` (thanks Babsobar) +* StaticTilemapLayer now uses the ComputedSize component, which stops it breaking if you call `setDisplaySize` (thanks Babsobar) +* CanvasPool.first always returned `null`, and now returns the first available Canvas. Fix #3520 (thanks @mchiasson) +* When starting a new Scene with an optional `data` argument it wouldn't get passed through if the Scene was not yet available (i.e. the game had not fully booted). The data is now passed to the Scene `init` and `create` methods and stored in the Scene Settings `data` property. Fix #3363 (thanks @pixelhijack) +* Tween.restart handles removed tweens properly and reads them back into the active queue for the TweenManager (thanks @wtravO) +* Tween.resume will now call `Tween.play` on a tween that was paused due to its config object, not as a result of having its paused method called. Fix #3452 (thanks @jazen) +* LoaderPlugin.isReady referenced a constant that no longer exists. Fix #3503 (thanks @Twilrom) +* Tween Timeline.destroy was trying to call `destroy` on Tweens instead of `stop` (thanks @Antriel) +* Calling `setOffset` on a Static Arcade Physics Body would break because the method was missing. It has been added and now functions as expected. Fix #3465 (thanks @josephjaniga and @DouglasLapsley) +* Calling Impact.World.remove(body) during a Body.updateCallback would cause the internal loop to crash when trying to access a now missing body. Two extra checks are in place to avoid this (thanks @iamDecode) +* If `setInteractive` is called on a Game Object that fails to set a hit area, it will no longer try to assign `dropZone` to an undefined `input` property. +* The Matter SetBody Component will no longer try to call `setOrigin` unless the Game Object has the origin component (which not all do, like Graphics and Container) +* Matter Image and Matter Sprite didn't define a `destroy` method, causing an error when trying to destroy the parent Game Object. Fix #3516 (thanks @RollinSafary) + +### Updates + +* The RTree library (rbush) used by Phaser 3 suffered from violating CSP policies by dynamically creating Functions at run-time in an eval-like manner. These are now defined via generators. Fix #3441 (thanks @jamierocks @Colbydude @jdotrjs) +* BaseSound has had its `rate` and `detune` properties removed as they are always set in the overriding class. +* BaseSound `setRate` and `setDetune` from the 3.3.0 release have moved to the WebAudioSound and HTML5AudioSound classes respectively, as they each handle the values differently. +* The file `InteractiveObject.js` has been renamed to `CreateInteractiveObject.js` to more accurately reflect what it does and to avoid type errors in the docs. +* Renamed the Camera Controls module exports for `Fixed` to `FixedKeyControl` and `Smoothed` to `SmoothedKeyControl` to match the class names. Fix #3463 (thanks @seivan) +* The ComputedSize Component now has `setSize` and `setDisplaySize` methods. This component is used for Game Objects that have a non-texture based size. +* The GamepadManager now extends EventEmitter directly, just like the KeyboardManager does. +* The Gamepad Axis threshold has been increased from 0.05 to 0.1. +* Utils.Array.FindClosestInSorted has a new optional argument `key` which will allow you to scan a top-level property of any object in the given sorted array and get the closest match to it. +* Vector2.setTo is a method alias for Vector2.set allowing it to be used inter-changeably with Geom.Point. +* List.add can now take an array or a single child. If an array is given it's passed over to List.addMultiple. +* List.add has a new optional argument `skipCallback`. +* List.addAt has a new optional argument `skipCallback`. +* List.addMultiple has a new optional argument `skipCallback`. +* List.remove has a new optional argument `skipCallback`. +* List.removeAt has a new optional argument `skipCallback`. +* List.removeBetween has a new optional argument `skipCallback`. +* List.removeAll has a new optional argument `skipCallback`. +* When using the `extend` property of a Scene config object it will now block overwriting the Scene `sys` property. +* When using the `extend` property of a Scene config object, if you define a property called `data` that has an object set, it will populate the Scenes Data Manager with those values. +* SceneManager._processing has been renamed to `isProcessing` which is now a boolean, not an integer. It's also now public and read-only. +* SceneManager.isBooted is a new boolean read-only property that lets you know if the Scene Manager has performed its initial boot sequence. +* TransformMatrix has the following new getter and setters: `a`, `b`, `c`, `d`, `tx` and `ty`. It also has the following new getters: `scaleX`, `scaleY` and `rotation`. +* List.getByKey has been removed. Use `List.getFirst` instead which offers the exact same functionality. +* List.sortIndexHandler has been removed because it's no longer required. +* List.sort no longer takes an array as its argument, instead it only sorts the List contents by the defined property. +* List.addMultiple has been removed. Used `List.add` instead which offers the exact same functionality. +* List is now internally using all of the new Utils.Array functions. +* Rectangle.Union will now cache all vars internally so you can use one of the input rectangles as the output rectangle without corrupting it. +* When shutting down a Matter World it will now call MatterEvents.off, clearing all events, and also `removeAllListeners` for any local events. +* Removed InputPlugin.sortInteractiveObjects because the method isn't used anywhere internally. + +### Animation System Updates + +We have refactored the Animation API to make it more consistent with the rest of Phaser 3 and to fix some issues. All of the following changes apply to the Animation Component: + +* Animation durations, delays and repeatDelays are all now specified in milliseconds, not seconds like before. This makes them consistent with Tweens, Sounds and other parts of v3. You can still use the `frameRate` property to set the speed of an animation in frames per second. +* All of the Animation callbacks have been removed, including `onStart`, `onRepeat`, `onUpdate` and `onComplete` and the corresponding params arrays like `onStartParams` and the property `callbackScope`. The reason for this is that they were all set on a global level, meaning that if you had 100 Sprites sharing the same animation, it was impossible to set the callbacks to fire for just one of those Sprites, but instead they would fire for all 100 and it was up to you to figure out which Sprite you wanted to update. Instead of callbacks animations now dispatch events on the Game Objects in which they are running. This means you can now do `sprite.on('animationstart')` and it will be invoked at the same point the old `onStart` callback would have been. The new events are: `animationstart`, `animtionrepeat`, `animationupdate` and `animationcomplete`. They're all dispatched from the Game Object that has the animation playing, not from the animation itself. This allows you far more control over what happens in the callbacks and we believe generally makes them more useful. +* The AnimationFrame.onUpdate callback has been removed. You can now use the `animationupdate` event dispatched from the Game Object itself and check the 2nd argument, which is the animation frame. +* Animation.stopAfterDelay is a new method that will stop a Sprites animation after the given time in ms. +* Animation.stopOnRepeat is a new method that will stop a Sprites animation when it goes to repeat. +* Animation.stopOnFrame is a new method that will stop a Sprites animation when it sets the given frame. +* Animation.stop no longer has the `dispatchCallbacks` argument, because it dispatches an event which you can choose to ignore. +* `delay` method has been removed. +* `setDelay` allows you to define the delay before playback begins. +* `getDelay` returns the animation playback delay value. +* `delayedPlay` now returns the parent Game Object instead of the component. +* `load` now returns the parent Game Object instead of the component. +* `pause` now returns the parent Game Object instead of the component. +* `resume` now returns the parent Game Object instead of the component. +* `isPaused` returns a boolean indicating the paused state of the animation. +* `paused` method has been removed. +* `play` now returns the parent Game Object instead of the component. +* `progress` method has been removed. +* `getProgress` returns the animation progress value. +* `setProgress` lets you jump the animation to a specific progress point. +* `repeat` method has been removed. +* `getRepeat` returns the animation repeat value. +* `setRepeat` sets the number of times the current animation will repeat. +* `repeatDelay` method has been removed. +* `getRepeatDelay` returns the animation repeat delay value. +* `setRepeatDelay` sets the delay time between each repeat. +* `restart` now returns the parent Game Object instead of the component. +* `stop` now returns the parent Game Object instead of the component. +* `timeScale` method has been removed. +* `getTimeScale` returns the animation time scale value. +* `setTimeScale` sets the time scale value. +* `totalFrames` method has been removed. +* `getTotalFrames` returns the total number of frames in the animation. +* `totalProgres` method has been removed as it did nothing and was mis-spelt. +* `yoyo` method has been removed. +* `getYoyo` returns if the animation will yoyo or not. +* `setYoyo` sets if the animation will yoyo or not. +* `updateFrame` will now call `setSizeToFrame` on the Game Object, which will adjust the Game Objects `width` and `height` properties to match the frame size. Fix #3473 (thanks @wtravO @jp-gc) +* `updateFrame` now supports animation frames with custom pivot points and injects these into the Game Object origin. +* `destroy` now removes events, references to the Animation Manager and parent Game Object, clears the current animation and frame and empties internal arrays. +* Changing the `yoyo` property on an Animation Component would have no effect as it only ever checked the global property, it now checks the local one properly allowing you to specify a `yoyo` on a per Game Object basis. +* Animation.destroy now properly clears the global animation object. +* Animation.getFrameByProgress will return the Animation Frame that is closest to the given progress value. For example, in a 5 frame animation calling this method with a value of 0.5 would return the middle frame. + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@gabegordon @melissaelopez @samid737 @nbs @tgrajewski @pagesrichie @hexus @mbrickn @erd0s @icbat @Matthew-Herman @ampled @mkimmet @PaNaVTEC + +## Version 3.3.0 - Tetsuo - 22nd March 2018 + +A special mention must go to @orblazer for their outstanding assistance in helping to complete the JSDoc data-types, callbacks and type defs across the API. + +### New Features + +* TextStyle has two new properties: `baselineX` and `baselineY` which allow you to customize the 'magic' value used in calculating the text metrics. +* Game.Config.preserveDrawingBuffer is now passed to the WebGL Renderer (default `false`). +* Game.Config.failIfMajorPerformanceCaveat is now passed to the WebGL Renderer (default `false`). +* Game.Config.powerPreference is now passed to the WebGL Renderer (default `default`). +* Game.Config.antialias is now passed to the WebGL Renderer as the antialias context property (default `true`). +* Game.Config.pixelArt is now only used by the WebGL Renderer when creating new textures. +* Game.Config.premultipliedAlpha is now passed to the WebGL Renderer as the premultipliedAlpha context property (default `true`). +* You can now specify all of the renderer config options within a `render` object in the config. If no `render` object is found, it will scan the config object directly for the properties. +* Group.create has a new optional argument: `active` which will set the active state of the child being created (thanks @samme) +* Group.create has a new optional argument: `active` which will set the active state of the child being created (thanks @samme) +* Group.createMultiple now allows you to include the `active` property in the config object (thanks @samme) +* TileSprite has a new method: `setTilePosition` which allows you to set the tile position in a chained called (thanks @samme) +* Added the new Action - WrapInRectangle. This will wrap each items coordinates within a rectangles area (thanks @samme) +* Arcade Physics has the new methods `wrap`, `wrapArray` and `wrapObject` which allow you to wrap physics bodies around the world bounds (thanks @samme) +* The Tweens Timeline has a new method: `makeActive` which delegates control to the Tween Manager (thanks @allanbreyes) +* Actions.GetLast will return the last element in the items array matching the conditions. +* Actions.PropertyValueInc is a new action that will increment any property of an array of objects by the given amount, using an optional step value, index and iteration direction. Most Actions have been updated to use this internally. +* Actions.PropertyValueSet is a new action that will set any property of an array of objects to the given value, using an optional step value, index and iteration direction. Most Actions have been updated to use this internally. +* Camera.shake now has an optional `callback` argument that is invoked when the effect completes (thanks @pixelscripter) +* Camera.fade now has an optional `callback` argument that is invoked when the effect completes (thanks @pixelscripter) +* Camera.flash now has an optional `callback` argument that is invoked when the effect completes (thanks @pixelscripter) +* Camera.fadeIn is a new method that will fade the camera in from a given color (black by default) and then optionally invoke a callback. This is the same as using Camera.flash but with an easier to grok method name. Fix #3412 (thanks @Jerenaux) +* Camera.fadeOut is a new method that will fade the camera out to a given color (black by default) and then optionally invoke a callback. This is the same as using Camera.fade but with an easier to grok method name. Fix #3412 (thanks @Jerenaux) +* Groups will now listen for a `destroy` event from any Game Object added to them, and if received will automatically remove that GameObject from the Group. Fix #3418 (thanks @hadikcz) +* MatterGameObject is a new function, available via the Matter Factory in `this.matter.add.gameObject`, that will inject a Matter JS Body into any Game Object, such as a Text or TileSprite object. +* Matter.SetBody and SetExistingBody will now set the origin of the Game Object to be the Matter JS sprite.xOffset and yOffset values, which will auto-center the Game Object to the origin of the body, regardless of shape. +* SoundManager.setRate is a chainable method to allow you to set the global playback rate of all sounds in the SoundManager. +* SoundManager.setDetune is a chainable method to allow you to set the global detuning of all sounds in the SoundManager. +* SoundManager.setMute is a chainable method to allow you to set the global mute state of the SoundManager. +* SoundManager.setVolume is a chainable method to allow you to set the global volume of the SoundManager. +* BaseSound.setRate is a chainable method to allow you to set the playback rate of the BaseSound. +* BaseSound.setDetune is a chainable method to allow you to set the detuning value of the BaseSound. + +### Bug Fixes + +* Fixed the Debug draw of a scaled circle body in Arcade Physics (thanks @pixelpicosean) +* Fixed bug in `DataManager.merge` where it would copy the object reference instead of its value (thanks @rexrainbow) +* The SceneManager no longer copies over the `shutdown` and `destroy` callbacks in createSceneFromObject, as these are not called automatically and should be invoked via the Scene events (thanks @samme) +* The default Gamepad Button threshold has been changed from 0 to 1. Previously the value of 0 was making all gamepad buttons appear as if they were always pressed down (thanks @jmcriat) +* InputManager.hitTest will now factor the game resolution into account, stopping the tests from being offset if resolution didn't equal 1 (thanks @sftsk) +* CameraManager.getCamera now returns the Camera based on its name (thanks @bigbozo) +* Fixed Tile Culling for zoomed Cameras. When a Camera was zoomed the tiles would be aggressively culled as the dimensions didn't factor in the zoom level (thanks @bigbozo) +* When calling ScenePlugin.start any additional data passed to the method would be lost if the scene wasn't in an active running state (thanks @stuff) +* When calling Timeline.resetTweens, while the tweens are pending removal or completed, it would throw a TypeError about the undefined `makeActive` (thanks @allanbreyes) +* The WebGL Context would set `antialias` to `undefined` as it wasn't set in the Game Config. Fix #3386 (thanks @samme) +* The TweenManager will now check the state of a tween before playing it. If not in a pending state it will be skipped. This allows you to stop a tween immediately after creating it and not have it play through once anyway. Fix #3405 (thanks @Twilrom) +* The InputPlugin.processOverOutEvents method wasn't correctly working out the total of the number of objects interacted with, which caused input events to be disabled in Scenes further down the scene list if something was being dragged in an upper scene. Fix #3399 (thanks @Jerenaux) +* The InputPlugin.processDragEvents wasn't always returning an integer. +* LoaderPlugin.progress and the corresponding event now factor in both the list size and the inflight size when calculating the percentage complete. Fix #3384 (thanks @vinerz @rblopes @samme) +* Phaser.Utils.Array.Matrix.RotateLeft actually rotated to the right (thanks @Tomas2h) +* Phaser.Utils.Array.Matrix.RotateRight actually rotated to the left (thanks @Tomas2h) +* When deleting a Scene from the SceneManager it would set the key in the scenes has to `undefined`, preventing you from registering a new Scene with the same key. It's now properly removed from the hash(thanks @macbury) +* Graphics.alpha was being ignored in the WebGL renderer and is now applied properly to strokes and fills. Fix #3426 (thanks @Ziao) +* The font is now synced to the context in Text before running a word wrap, this ensures the wrapping result between updating the text and getting the wrapped text is the same. Fix #3389 (thanks @rexrainbow) +* Added the ComputedSize component to the Text Game Object, which allows Text.getBounds, and related methods, to work again instead of returning NaN. +* Group.remove now calls the `removeCallback` and passes it the child that was removed (thanks @orblazer) + +### Updates + +* The Text testString has changed from `|MÉqgy` to `|MÉqgy`. +* The WebGLRenderer width and height values are now floored when multiplied by the resolution. +* The WebGL Context now sets `premultipliedAlpha` to `true` by default, this prevents the WebGL context from rendering as plain white under certain versions of macOS Safari. +* The Phaser.Display.Align constants are now exposed on the namespace. Fix #3387 (thanks @samme) +* The Phaser.Loader constants are now exposed on the namespace. Fix #3387 (thanks @samme) +* The Phaser.Physics.Arcade constants are now exposed on the namespace. Fix #3387 (thanks @samme) +* The Phaser.Scene constants are now exposed on the namespace. Fix #3387 (thanks @samme) +* The Phaser.Tweens constants are now exposed on the namespace. Fix #3387 (thanks @samme) +* The Array Matrix utils are now exposed and available via `Phaser.Utils.Array.Matrix`. +* Actions.Angle has 3 new arguments: `step`, `index` and `direction`. +* Actions.IncAlpha has 3 new arguments: `step`, `index` and `direction`. +* Actions.IncX has 3 new arguments: `step`, `index` and `direction`. +* Actions.IncY has 3 new arguments: `step`, `index` and `direction`. +* Actions.IncXY has 4 new arguments: `stepX`, `stepY`, `index` and `direction`. +* Actions.Rotate has 3 new arguments: `step`, `index` and `direction`. +* Actions.ScaleX has 3 new arguments: `step`, `index` and `direction`. +* Actions.ScaleXY has 4 new arguments: `stepX`, `stepY`, `index` and `direction`. +* Actions.ScaleY has 3 new arguments: `step`, `index` and `direction`. +* Actions.SetAlpha has 2 new arguments: `index` and `direction`. +* Actions.SetBlendMode has 2 new arguments: `index` and `direction`. +* Actions.SetDepth has 2 new arguments: `index` and `direction`. +* Actions.SetOrigin has 4 new arguments: `stepX`, `stepY`, `index` and `direction`. +* Actions.SetRotation has 2 new arguments: `index` and `direction`. +* Actions.SetScale has 2 new arguments: `index` and `direction`. +* Actions.SetScaleX has 2 new arguments: `index` and `direction`. +* Actions.SetScaleY has 2 new arguments: `index` and `direction`. +* Actions.SetVisible has 2 new arguments: `index` and `direction`. +* Actions.SetX has 2 new arguments: `index` and `direction`. +* Actions.SetXY has 2 new arguments: `index` and `direction`. +* Actions.SetY has 2 new arguments: `index` and `direction`. +* Line.getPointA now returns a Vector2 instead of an untyped object. It also now has an optional argument that allows you to pass a vec2 in to be populated, rather than creating a new one. +* Line.getPointB now returns a Vector2 instead of an untyped object. It also now has an optional argument that allows you to pass a vec2 in to be populated, rather than creating a new one. +* Rectangle.getLineA now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* Rectangle.getLineB now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* Rectangle.getLineC now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* Rectangle.getLineD now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* Triangle.getLineA now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* Triangle.getLineB now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* Triangle.getLineC now returns a Line instead of an untyped object. It also now has an optional argument that allows you to pass a Line in to be populated, rather than creating a new one. +* The GameObject `destroy` event is now emitted at the start of the destroy process, before things like the body or input managers have been removed, so you're able to use the event handler to extract any information you require from the GameObject before it's actually disposed of. Previously, the event was dispatched at the very end of the process. +* Phaser 3 is now built with Webpack v4.1.1 and all related packages have been updated (thanks @orblazer) +* On WebGL the currentScissor is now updated when the renderer `resize` method is called (thanks @jmcriat) +* PathFollower.start has been renamed to `startFollow` to avoid conflicting with the Animation component. +* PathFollower.pause has been renamed to `pauseFollow` to avoid conflicting with the Animation component. +* PathFollower.resume has been renamed to `resumeFollow` to avoid conflicting with the Animation component. +* PathFollower.stop has been renamed to `stopFollow` to avoid conflicting with the Animation component. +* BaseSound.setRate has been renamed to `calculateRate` to avoid confusion over the setting of the sounds rate. + +## Version 3.2.1 - 12th March 2018 + +### Bug Fixes + +* Fixed issue with Render Texture tinting. Fix #3336 (thanks @rexrainbow) +* Fixed Utils.String.Format (thanks @samme) +* The Matter Debug Layer wouldn't clear itself in canvas mode. Fix #3345 (thanks @samid737) +* TimerEvent.remove would dispatch the Timer event immediately based on the opposite of the method argument, making it behave the opposite of what was expected. It now only fires when requested (thanks @migiyubi) +* The TileSprite Canvas Renderer did not support rotation, scaling or flipping. Fix #3231 (thanks @TCatshoek) +* Fixed Group doesn't remove children from Scene when cleared with the `removeFromScene` argument set (thanks @iamchristopher) +* Fixed an error in the lights pipeline when no Light Manager has been defined (thanks @samme) +* The ForwardDiffuseLightPipeline now uses `sys.lights` instead of the Scene variable to avoid errors due to injection removal. +* Phaser.Display.Color.Interpolate would return NaN values because it was loading the wrong Linear function. Fix #3372 (thanks @samid737) +* RenderTexture.draw was only drawing the base frame of a Texture. Fix #3374 (thanks @samid737) +* TileSprite scaling differed between WebGL and Canvas. Fix #3338 (thanks @TCatshoek) +* Text.setFixedSize was incorrectly setting the `text` property instead of the `parent` property. Fix #3375 (thanks @rexrainbow) +* RenderTexture.clear on canvas was using the last transform state, instead of clearing the whole texture. + +### Updates + +* The SceneManager.render will now render a Scene as long as it's in a LOADING state or higher. Before it would only render RUNNING scenes, but this precluded those that were loading assets. +* A Scene can now be restarted by calling `scene.start()` and providing no arguments (thanks @migiyubi) +* The class GameObject has now been exposed, available via `Phaser.GameObjects.GameObject` (thanks @rexrainbow) +* A Camera following a Game Object will now take the zoom factor of the camera into consideration when scrolling. Fix #3353 (thanks @brandonvdongen) +* Calling `setText` on a BitmapText object will now recalculate its display origin values. Fix #3350 (thanks @migiyubi) +* You can now pass an object to Loader.atlas, like you you can with images. Fix #3268 (thanks @TCatshoek) +* The `onContextRestored` callback won't be defined any more unless the WebGL Renderer is in use in the following objects: BitmapMask, Static Tilemap, TileSprite and Text. This should allow those objects to now work in HEADLESS mode. Fix #3368 (thanks @16patsle) +* The SetFrame method now has two optional arguments: `updateSize` and `updateOrigin` (both true by default) which will update the size and origin of the Game Object respectively. Fix #3339 (thanks @Jerenaux) + +## Version 3.2.0 - Kaori - 5th March 2018 + +### New Features + +* The new Render Texture Game Object is now available. You can clear, fill and draw texture frames to it. The Render Texture itself can be displayed in-game with its own transform, or you can use it as a Bitmap Mask for another Game Object. +* Game.resize allows you to resize the game config, renderer and input system in one call. +* When Game.resize is called it causes all Scene.Systems to have their resize method called. This is turn emits a `resize` event which your Scene can respond to. It will be sent the new width and height of the canvas as the only two parameters. +* InputManager.resize allows you to update the bounds def and input scale in one call. +* Game.Config.roundPixels property added to prevent sub-pixel interpolation during rendering of Game Objects in WebGL and Canvas. +* Load.plugin now accepts a class as an argument as well as a URL string (thanks @nkholski) +* Tween.complete will allow you to flag a tween as being complete, no matter what stage it is at. If an onComplete callback has been defined it will be invoked. You can set an optional delay before this happens (thanks @Jerenaux for the idea) +* The Headless render mode has been implemented. You can now set HEADLESS as the `renderType` in the Game Config and it will run a special game step that skips rendering. It will still create a Canvas element, as lots of internal systems (like input) rely on it, but it will not draw anything to it. Fix #3256 (thanks @rgk) +* GameObject.setInteractive has a new boolean argument `dropZone` which will allow you to set the object as being a drop zone right from the method. +* Sprites can now be drop zones and have other Game Objects dragged onto them as targets. +* The SceneManager has a new method: `remove` which allows you to remove and destroy a Scene, freeing up the Scene key for use by future scenes and potentially clearing the Scene from active memory for gc. +* SceneManager.moveAbove will move a Scene to be directly above another Scene in the Scenes list. This is also exposed in the ScenePlugin. +* SceneManager.moveBelow will move a Scene to be directly below another Scene in the Scenes list. This is also exposed in the ScenePlugin. +* Quadratic Bezier Interpolation has been added to the Math.Interpolation functions (thanks @RiCoTeRoX) +* A new Quadratic Bezier Curve class has been added, expanding the available Curve types (thanks @RiCoTeRoX) +* Path.quadraticBezierTo allows you to add a Quadratic Bezier Curve into your Path. +* Loader.multiatlas now supports Texture Packers new JSON atlas format which exports one combined atlas for all image files. This is available if you use the new Phaser 3 Export from within Texture Packer (thanks @CodeAndWeb) +* Modified WebGLPipeline to make it easier to extend and easier to create custom rendering passes. + +### Bug Fixes + +* Arcade Physics Bodies didn't apply the results of `allowRotation` to the parent Game Object. +* InputManager.updateBounds wouldn't correctly get the bounds of the canvas if it had horizontal or vertical translation in the page, causing the scale factor to be off (and subsequently input values to mis-fire) +* TileSprite.setFrame now works and allows you to change the frame to any other in the texture. Fix #3232 (thanks @Jerenaux) +* Swapped the queue loop in the SceneManager to to use `_queue.length` rather than a cached length (thanks @srobertson421) +* When calling `ScenePlugin.launch` the `data` argument is now passed to the queued scenes (thanks @gaudeon) +* Rectangle.top wouldn't reset the `y` position if the value given never exceed the Rectangles bottom. Fix #3290 (thanks @chancezeus) +* The implementation of `topOnly` within the Input Manager had broken the way drop zones worked, as they were now filtered out of the display list before processing. Drop zones are now treated on their own in the Input Plugin meaning you can still have `topOnly` set and still drop an item into a drop zone. This indirectly fixed #3291 (thanks @rexrainbow) +* InputPlugin.clear now properly removes a Game Object from all internal arrays, not just the _list. +* InputPlugin.processOverOut no longer considers an item as being 'out' if it's in the internal `_drag` array. +* When a Game Object is scaled, its Arcade Physics body was still calculating its position based on its original size instead of scaled one (thanks @pixelpicosean) +* The RandomDataGenerator classes randomness has been improved thanks to the correct caching of a class property. Fix #3289 (thanks @migiyubi) +* The RandomDataGenerator `sign` property had a method collision. Fix #3323 (thanks @vinerz and @samme) +* In Arcade Physics World if you collided a group with itself it would call a missing method (`collideGroupVsSelf`), it now calls `collideGroupVsGroup` correctly (thanks @patrickgalbraith) +* The HTML5 Sound Manager would unlock the Sound API on a touch event but only if the audio files were loaded in the first Scene, if they were loaded in a subsequent Scene the audio system would never unlock. It now unlocks only if there are audio files in the cache. Fix #3311 (thanks @chancezeus) +* The Text.lineSpacing value was not taken into account when rendering the Text. Fix #3215 (thanks @sftsk) +* InputPlugin.update now takes the totals from the drag and pointerup events into consideration when deciding to fall through to the Scene below. Fix #3333 (thanks @chancezeus) + +### Updates + +* AnimationComponent.play now calls `setSizeToFrame()` and `updateDisplayOrigin()` on the parent Game Object in order to catch situations where you've started playing an animation on a Game Object that uses a different size to the previously set frame. +* Text.setText will check if the value given is falsey but not a zero and set to an empty string if so. +* BitmapText.setText will check if the value given is falsey but not a zero and set to an empty string if so. +* BitmapText.setText will now cast the given value to a string before setting. +* BitmapText.setText will not change the text via `setText` unless the new text is different to the old one. +* If you set `transparent` in the Game Config but didn't provide a `backgroundColor` then it would render as black. It will now be properly transparent. If you do provide a color value then it must include an alpha component. +* You can now pass normal Groups to Arcade Physics collide / overlap, as well as Physics Groups. Fix #3277 (thanks @nkholski) +* Texture.get has been optimized to fail first, then error, with a new falsey check. This allows you to skip out specifying animation frames in the animation config without generating a console warning. +* The `setFrame` method of the Texture component has been updated so that it will now automatically reset the `width` and `height` of a Game Object to match that of the new Frame. Related, it will also adjust the display origin values, because they are size based. If the Frame has a custom pivot it will set the origin to match the custom pivot instead. +* ScenePlugin.swapPosition now allows you to use it to swap the positions of any two Scenes. Before the change it only allowed you to swap the position of the calling Scene and another one, but a new optional `keyB` argument opens this up. +* The SceneManager no longer renders a Scene unless it is visible AND either running or paused. This now skips Scenes that are in an `init` state. +* The Keyboard Manager will now no longer emit `keydown` events if you keep holding a key down. Fix #3239 (thanks @squaresun) +* The SceneManager now employs a new queue for all pending Scenes, creating them and booting them in strict sequence. This should prevent errors where Scenes were unable to reference other Scenes further down the boot list in their create functions. Fix #3314 (thanks @max1701 @rblopes) +* Game.preBoot and Game.postBoot callbacks now pass an instance of the game to the callback (thanks @rblopes) +* Graphics.arc in WebGL mode now works more like arc does in Canvas (thanks @Twilrom) +* GameObjects now emit a 'destroy' event when they are destroyed, which you can use to perform any additional processing you require. Fix #3251 (thanks @rexrainbow) +* If an HTML5AudioSound sound fails to play it will now issue a console.warn (thanks @samme) +* Phaser is now running Travis CI build testing again (thanks @vpmedia) +* Documentation updates: thanks to @melissaelopez @samme @jblang94 + +## Version 3.1.2 - 23rd February 2018 + +### Updates + +* Hundreds of JSDoc fixes across the whole API. +* Tween.updateTweenData will now check to see if the Tween target still exists before trying to update its properties. +* If you try to use a local data URI in the Loader it now console warns instead of logs (thanks @samme) + +### Bug Fixes + +* The KeyCode `FORWAD_SLASH` had a typo and has been changed to `FORWARD_SLASH`. Fix #3271 (thanks @josedarioxyz) +* Fixed issue with vertex buffer creation on Static Tilemap Layer, causing tilemap layers to appear black. Fix #3266 (thanks @akleemans) +* Implemented Static Tilemap Layer scaling and Tile alpha support. +* Fixed issue with null texture on Particle Emitter batch generation. This would manifest if you had particles with blend modes on-top of other images not appearing. +* Added missing data parameter to ScenePlugin. Fixes #3810 (thanks @AleBles) + +## Version 3.1.1 - 20th February 2018 + +### Updates + +* The entire codebase now passes our eslint config (which helped highlight a few errors), if you're submitting a PR, please ensure your PR passes the config too. +* The Web Audio Context is now suspended instead of closed to allow for prevention of 'Failed to construct AudioContext: maximum number of hardware contexts reached' errors from Chrome in a hot reload environment. We still strongly recommend reusing the same context in a production environment. See [this example](http://labs.phaser.io/view.html?src=src%5Caudio%5CWeb%20Audio%5CReuse%20AudioContext.js) for details. Fixes #3238 (thanks @z0y1 @Ziao) +* The Webpack shell plugin now fires on `onBuildExit`, meaning it'll update the examples if you use `webpack watch` (thanks @rblopes) +* Added `root: true` flag to the eslint config to stop it scanning further-up the filesystem. + +### Bug Fixes + +* Math.Fuzzy.Floor had an incorrect method signature. +* Arcade Physics World didn't import GetOverlapX or GetOverlapY, causing `separateCircle` to break. +* TileSprite was missing a gl reference, causing it to fail during a context loss and restore. +* The Mesh Game Object Factory entry had incorrect arguments passed to Mesh constructor. +* Removed unused `_queue` property from `ScenePlugin` class (thanks @rblopes) +* The variable `static` is no longer used in Arcade Physics, fixing the 'static is a reserved word' in strict mode error (thanks @samme) +* Fixed `Set.union`, `Set.intersect` and `Set.difference` (thanks @yupaul) +* The corner tints were being applied in the wrong order. Fixes #3252 (thanks @Rybar) +* BitmapText objects would ignore calls to setOrigin. Fixes #3249 (thanks @amkazan) +* Fixed a 1px camera jitter and bleeding issue in the renderer. Fixes #3245 (thanks @bradharms) +* Fixed the error `WebGL: INVALID_ENUM: blendEquation: invalid mode.` that would arise on iOS. Fixes #3244 (thanks @Ziao) +* The `drawBlitter` function would crash if `roundPixels` was true. Fixes #3243 (thanks @Jerenaux and @vulcanoidlogic) + +## Version 3.1.0 - Onishi - 16th February 2018 + +### Updates + +* Vertex resource handling code updated, further optimizing the WebGL batching. You should now see less gl ops per frame across all batches. +* The `Blitter` game object has been updated to use the `List` structure instead of `DisplayList`. +* Arcade Physics World `disableBody` has been renamed `disableGameObjectBody` to more accurately reflect what it does. +* Lots of un-used properties were removed from the Arcade Physics Static Body object. +* Arcade Physics Static Body can now refresh itself from its parent via `refreshBody`. + +### Bug Fixes + +* A couple of accidental uses of `let` existed, which broke Image loading in Safari # (thanks Yat Hin Wong) +* Added the static property `Graphics.TargetCamera` was added back in which fixed `Graphics.generateTexture`. +* The SetHitArea Action now calls `setInteractive`, fixing `Group.createMultiple` when a hitArea has been set. +* Removed rogue Tween emit calls. Fix #3222 (thanks @ZaDarkSide) +* Fixed incorrect call to TweenManager.makeActive. Fix #3219 (thanks @ZaDarkSide) +* The Depth component was missing from the Zone Game Object. Fix #3213 (thanks @Twilrom) +* Fixed issue with `Blitter` overwriting previous objects vertex data. +* The `Tile` game object tinting was fixed, so tiles now honor alpha values correctly. +* The `BitmapMask` would sometimes incorrectly bind its resources. +* Fixed the wrong Extend target in MergeXHRSettings (thanks @samme) + +### New Features + +* Destroying a Game Object will now call destroy on its physics body, if it has one set. +* Arcade Physics Colliders have a new `name` property and corresponding `setName` method. +* Matter.js bodies now have an inlined destroy method that removes them from the World. +* Impact bodies now remove themselves from the World when destroyed. +* Added Vector2.ZERO static property. diff --git a/README.md b/README.md index 6b7d2be5c..4bc4190d4 100644 --- a/README.md +++ b/README.md @@ -1,631 +1,631 @@ -# Phaser - HTML5 Game Framework - -![Phaser Header](https://phaser.io/images/github/300/phaser-header.png "Phaser 3 Header Banner") - -[![Discord chat](https://img.shields.io/discord/244245946873937922?style=for-the-badge)](https://discord.gg/phaser) -[![Twitter Follow](https://img.shields.io/twitter/follow/phaser_?style=for-the-badge)](https://twitter.com/phaser_) -![GitHub All Releases](https://img.shields.io/github/downloads/photonstorm/phaser/total?style=for-the-badge) -![npm](https://img.shields.io/npm/dy/phaser?label=npm&style=for-the-badge) - -Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop and mobile web browsers. Games can be compiled to iOS, Android and native apps by using 3rd party tools. You can use JavaScript or TypeScript for development. - -Along with the fantastic open source community, Phaser is actively developed and maintained by [Photon Storm](http://www.photonstorm.com). As a result of rapid support, and a developer friendly API, Phaser is currently one of the [most starred](https://github.com/collections/javascript-game-engines) game frameworks on GitHub. - -Thousands of developers from indie and multi-national digital agencies, and universities worldwide use Phaser. You can take a look at their incredible [games](https://phaser.io/games/). - -**Visit:** The [Phaser website](https://phaser.io) and follow on [Twitter](https://twitter.com/phaser_) (#phaserjs)
-**Learn:** [API Docs](https://photonstorm.github.io/phaser3-docs/index.html), [Support Forum][forum] and [StackOverflow](https://stackoverflow.com/questions/tagged/phaser-framework)
-**Code:** 1700+ [Examples](https://phaser.io/examples) (source available in this [repo][examples])
-**Read:** The [Phaser World](#newsletter) Newsletter
-**Chat:** [Discord](https://phaser.io/community/discord) and [Slack](https://phaser.io/community/slack)
-**Extend:** With [Phaser Plugins](https://phaser.io/shop/plugins)
-**Be awesome:** [Support](#support) the future of Phaser
- -Grab the source and join the fun! - -![What's New](https://phaser.io/images/github/div-whats-new.png "What's New") - -
- -> 15th January 2020 - -We're excited to announce the release of Phaser 3.22, the first of many in the year 2020. The main focus of 3.22 is all the work we've done on Matter Physics integration. Matter has been supported in Phaser since the first release, yet there were lots of things we wanted to do with it to make development life easier. 3.22 brings all of these to the front, including powerful new visual debugging options such as rendering contacts, velocity, the broadphase grid, sensors, joints and more. Matter also now has 100% JSDoc and TypeScripy coverage and I spent a long time rebuilding the TypeScript defs by hand, in order to make them as accurate as possible. - -As well as docs and defs there are stacks of handy new methods, including intersection tests such as `intersectPoint`, `intersectRay`, `overlap` and more. New Body level collision callbacks allow you to filter collided pairs a lot more quickly now, combined with new collision events and data type defs to give you all the information you need when resolving. There are now functions to create bodies from SVG data, JSON data or Physics Editor data directly, new Body alignment features and of course bug fixes. - -It's not all about Matter Physics, though. Thanks to the community, there are new Math Distance functions such as Chebyshev, Snake and Squared Points. You can now tint particles as they're emitted, Physics Groups finally let you use your own creation and removal callbacks and plenty more besides. There are, of course, lots of bug fixes too and I've done my best to address some of the most important ones. The documentation has improved yet again and with every release the TypeScript defs get stronger and stronger. So, as usual, please do spend some time digging through the [Change Log](#changelog). I assure you, it's worth while :) - -With 3.22 released I will now be taking some time to carry on with Phaser 4 development, while planning out the 3.23 release as well. Even though Phaser 4 is in build I will fully support Phaser 3 for the foreseeable future. You can follow the development progress of both versions on the Phaser Patreon. - -As usual, I'd like to send a massive thank-you to everyone who supports Phaser on Patreon (and now even GitHub Sponsors, too!) Your continued backing keeps allowing me to work on Phaser full-time and this great new releases is the very real result of that. If you've ever considered becoming a backer, now is the perfect time! - -If you'd like to stay abreast of developments then I publish my [Developer Logs](https://phaser.io/phaser3/devlog) in the [Phaser World](https://phaser.io/community/newsletter) newsletter. Subscribe to stay in touch and get all the latest news from the core team and the wider community. - -You can also follow Phaser on [Twitter](https://twitter.com/phaser_) and chat with fellow Phaser devs in our [Discord](https://phaser.io/community/discord) and [Slack](https://phaser.io/community/slack) channels. - -Phaser 3 wouldn't have been possible without the fantastic support of the community and Patreon. Thank you to everyone who supports our work, who shares our belief in the future of HTML5 gaming, and Phaser's role in that. - -Happy coding everyone! - -Cheers, - -Rich - [@photonstorm](https://twitter.com/photonstorm) - -![boogie](https://www.phaser.io/images/spacedancer.gif) - -![Support Phaser](https://phaser.io/images/github/div-support-phaser.png "Support Phaser") - -Because Phaser is an open source project, we cannot charge for it in the same way as traditional retail software. What's more, we don't ever want to. After all, it's built on, and was born from, open web standards. It's part of our manifesto that the core framework will always be free, even if you use it commercially, as many of you do. - -**You may not realize it, but because of this, we rely 100% on community backing to fund development.** - -Those funds allow Phaser to improve, and when it improves, everyone involved benefits. Your support helps secure a constant cycle of updates, fixes, new features and planning for the future. - -There are other benefits to [backing Phaser](https://www.patreon.com/join/photonstorm), too: - -![Backers Perks](https://phaser.io/images/github/patreon-perk-chart.png) - -We use [Patreon](https://www.patreon.com/photonstorm) to manage the backing and you can [support Phaser](https://www.patreon.com/join/photonstorm?) from $1 per month. The amount you pledge is entirely up to you and can be changed as often as you like. Patreon renews monthly, just like Netflix. You can, of course, cancel at any point. Tears will be shed on this end, but that's not your concern. - -Extra special thanks to the following companies who's support makes Phaser possible: - -* [Cerebral Fix](https://cerebralfix.com) -* [CrossInstall](https://crossinstall.com) -* [Facebook](https://www.facebook.com) -* [Game Distribution](https://gamedistribution.com) -* [GameCommerce](https://www.gamecommerce.com) -* [Mozilla](https://www.mozilla.org) -* [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) -* [Twilio](https://www.twilio.com) -* [Y8 Games](https://www.y8.com) -* [Poki](https://developers.poki.com/) - -![Sponsors](https://phaser.io/images/github/sponsors-2019-12.png "Awesome Sponsors") - -![Phaser Newsletter](https://phaser.io/images/github/div-newsletter.png "Phaser Newsletter") - -
- -We publish the [Phaser World](https://phaser.io/community/newsletter) newsletter. It's packed full of the latest Phaser games, tutorials, videos, meet-ups, talks, and more. The newsletter also contains our weekly Development Progress updates which let you know about the new features we're working on. - -Over 140 previous editions can be found on our [Back Issues](https://phaser.io/community/backissues) page. - -![Download Phaser](https://phaser.io/images/github/div-download.png "Download Phaser") - - -Phaser 3 is available via GitHub, npm and CDNs: - -* Clone the git repository via [https][clone-http], [ssh][clone-ssh] or with the GitHub [Windows][clone-ghwin] or [Mac][clone-ghmac] clients. -* Download as [zip](https://github.com/photonstorm/phaser/archive/master.zip) -* Download the build files: [phaser.js][get-js] and [phaser.min.js][get-minjs] - -### NPM - -Install via [npm](https://www.npmjs.com): - -```bash -npm install phaser -``` - -### CDN - -[![](https://data.jsdelivr.com/v1/package/gh/photonstorm/phaser/badge)](https://www.jsdelivr.com/package/gh/photonstorm/phaser) - -[Phaser is on jsDelivr](https://www.jsdelivr.com/projects/phaser) which is a "super-fast CDN for developers". Include the following in your html: - -```html - -``` - -or the minified version: - -```html - -``` - -### API Documentation - -Go to https://photonstorm.github.io/phaser3-docs/index.html to read the docs online. Use the drop-down menus at the top to navigate the namespaces, classes and Game Objects lists. - -Or, if you wish to run the docs locally you can checkout the [phaser3-docs](https://github.com/photonstorm/phaser3-docs) repository and then read the documentation by pointing your browser to the `docs/` folder. - -The documentation for Phaser 3 is an on-going project. Please help us by searching the Phaser code for any instance of the string `[description]` and then replacing it with some documentation. - -### TypeScript Definitions - -The [TypeScript definitions](https://github.com/photonstorm/phaser/tree/master/types) can be found inside the `types` folder. They are also referenced in the types entry in `package.json`. - -Depending on your project, you may need to add the following to your `tsconfig.json` file: - -```json -"typeRoots": [ - "./node_modules/phaser/types" -], -"types": [ - "Phaser" -] -``` - -We recently published a new [Phaser 3 TypeScript Project Template](https://github.com/photonstorm/phaser3-typescript-project-template), which you can use to get started with if you like. - -The TS defs are automatically generated from the JSDoc comments found in the Phaser source code. If you wish to help refine them then you must edit the Phaser JSDoc blocks directly, not the defs file. You can find more details about the parser we built in the `scripts/tsgen` folder. - -### Webpack - -We use Webpack to build Phaser and we take advantage of its conditional build flag feature to handle renderer swapping. If you wish to use Webpack with Phaser then please use our [Phaser 3 Project Template](https://github.com/photonstorm/phaser3-project-template) as it's already set-up to handle the build conditions Phaser needs. Recent changes to our build steps mean you should now be able to use any other packager, like Parcel, without any config changes. - -### License - -Phaser is released under the [MIT License](https://opensource.org/licenses/MIT). - -![Getting Started](https://phaser.io/images/github/div-getting-started.png "Getting Started") - - - - -Tutorials and guides on Phaser 3 development are being published every week. - -* [Getting Started with Phaser 3](https://phaser.io/tutorials/getting-started-phaser3) (useful if you are completely new to Phaser) -* [Making your first Phaser 3 Game](https://phaser.io/tutorials/making-your-first-phaser-3-game) -* The [Complete Phaser 3 Game Development course](https://academy.zenva.com/product/html5-game-phaser-mini-degree/?a=13) contains over 15 hours of videos covering all kinds of important topics. -* Plus, there are [over 700 Phaser tutorials](http://phaser.io/learn) listed on the official website. - -Also, please subscribe to the [Phaser World](https://phaser.io/community/newsletter) newsletter for details about new tutorials as they are published. - -### Facebook Instant Games - -Phaser 3.13 introduced the new [Facebook Instant Games](http://phaser.io/news/2018/10/facebook-instant-games-phaser-tutorial) Plugin. The plugin provides a seamless bridge between Phaser and version 6.2 of the Facebook Instant Games SDK. Every single SDK function is available via the plugin and we will keep track of the official SDK to make sure they stay in sync. - -The plugin offers the following features: - -* Easy integration with the Phaser Loader so load events update the Facebook progress circle. -* Events for every plugin method, allowing the async calls of the SDK to be correctly inserted into the Phaser game flow. When SDK calls resolve they will surface naturally as a Phaser event and you'll know you can safely act upon them without potentially doing something mid-way through the game step. -* All Plugin methods check if the call is part of the supported APIs available in the SDK, without needing to launch an async request first. -* Instant access to platform, player and locale data. -* Easily load player photos directly into the Texture Manager, ready for use with a Game Object. -* Subscribe to game bots. -* The plugin has a built-in Data Manager which makes dealing with data stored on Facebook seamless. Just create whatever data properties you need and they are automatically synced. -* Support for FB stats, to retrieve, store and increment stats into cloud storage. -* Save Session data with built-in session length validation. -* Easy context switching, to swap between game instances and session data retrieval. -* Easily open a Facebook share, invite, request or game challenge window and populate the text and image content using any image stored in the Texture cache. -* Full Leaderboard support. Retrieve, scan and update leaderboard entries, as well as player matching. -* Support for in-app purchases, with product catalogs, the ability to handle purchases, get past purchases and consume previously unlocked purchases. -* Easily preload a set of interstitial ads, in both banner and video form, then display the ad at any point in your game, with in-built tracking of ads displayed and inventory available. -* Plus other features, such as logging to FB Analytics, creating short cuts, switching games, etc. - -We've 3 tutorials related to Facebook Instant Games and Phaser: - -* [Getting Started with Facebook Instant Games](http://phaser.io/news/2018/10/facebook-instant-games-phaser-tutorial) -* [Facebook Instant Games Leaderboards Tutorial](http://phaser.io/news/2018/11/facebook-instant-games-leaderboards-tutorial) -* [Displaying Ads in your Instant Games](http://phaser.io/news/2018/12/facebook-instant-games-ads-tutorial) - -A special build of Phaser with the Facebook Instant Games Plugin ready-enabled is [available on jsDelivr](https://www.jsdelivr.com/projects/phaser). Include the following in your html: - -```html - -``` - -or the minified version: - -```html - -``` - -The build files are in the git repository in the `dist` folder, and you can also include the plugin in custom builds. - -### Source Code Examples - -During our development of Phaser 3, we created hundreds of examples with the full source code and assets ready available. These examples are now fully integrated into the [Phaser website](https://phaser.io/examples). You can also browse them on [Phaser 3 Labs](https://labs.phaser.io) via a more advanced interface, or clone the [examples repo][examples]. We are constantly adding to and refining these examples. - -### Create Your First Phaser 3 Example - -Create an `index.html` page locally and paste the following code into it: - -```html - - - - - - - - - - - -``` - -This is a standard empty webpage. You'll notice there's a script tag that is pulling in a build of Phaser 3, but otherwise this webpage doesn't do anything yet. Now let's set-up the game config. Paste the following between the `` tags: - -```javascript -var config = { - type: Phaser.AUTO, - width: 800, - height: 600, - physics: { - default: 'arcade', - arcade: { - gravity: { y: 200 } - } - }, - scene: { - preload: preload, - create: create - } -}; -``` - -`config` is a pretty standard Phaser 3 Game Configuration object. We tell `config` to use the WebGL renderer if it can, set the canvas to a size of 800x600 pixels, enable Arcade Physics, and finally call the `preload` and `create` functions. `preload` and `create` have not been implemented yet, so if you run this JavaScript code, you will have an error. Add the following after `config`: - -```javascript -var game = new Phaser.Game(config); - -function preload () -{ - this.load.setBaseURL('http://labs.phaser.io'); - - this.load.image('sky', 'assets/skies/space3.png'); - this.load.image('logo', 'assets/sprites/phaser3-logo.png'); - this.load.image('red', 'assets/particles/red.png'); -} - -function create () -{ -} -``` - -`game` is a Phaser Game instance that uses our configuration object `config`. We also add function definitions for `preload` and `create`. The `preload` function helps you easily load assets into your game. In `preload`, we set the Base URL to be the Phaser server and load 3 PNG files. - -The `create` function is empty, so it's time to fill it in: - -```javascript -function create () -{ - this.add.image(400, 300, 'sky'); - - var particles = this.add.particles('red'); - - var emitter = particles.createEmitter({ - speed: 100, - scale: { start: 1, end: 0 }, - blendMode: 'ADD' - }); - - var logo = this.physics.add.image(400, 100, 'logo'); - - logo.setVelocity(100, 200); - logo.setBounce(1, 1); - logo.setCollideWorldBounds(true); - - emitter.startFollow(logo); -} -``` - -Here we add a sky image into the game and create a Particle Emitter. The `scale` value means that the particles will initially be large and will shrink to nothing as their lifespan progresses. - -After creating the `emitter`, we add a logo image called `logo`. Since `logo` is a Physics Image, `logo` is given a physics body by default. We set some properties for `logo`: velocity, bounce (or restitution), and collision with the world bounds. These properties will make our logo bounce around the screen. Finally, we tell the particle emitter to follow the logo - so as the logo moves, the particles will flow from it. - -Run it in your browser and you'll see the following: - -![Phaser 3 Demo](https://phaser.io/images/github/300/sample1.png "Phaser 3 Demo") - -(Got an error? Here's the [full code](https://gist.github.com/photonstorm/46cb8fb4b19fc7717dcad514cdcec064)) - -This is a tiny example, and there are hundreds more for you to explore, but hopefully it shows how expressive and quick Phaser is to use. With just a few easily readable lines of code, we've got something pretty impressive up on screen! - -Subscribe to our newsletter for further tutorials and examples. - -![Building Phaser](https://phaser.io/images/github/div-building-phaser.png "Building Phaser") - -There are both plain and minified compiled versions of Phaser in the `dist` folder of the repository. The plain version is for use during development, and the minified version is for production use. You can also create your own builds. - -### Custom Builds - -Phaser 3 is built using Webpack and we take advantage of the Webpack definePlugin feature to allow for conditional building of the Canvas and WebGL renderers and extra plugins. You can custom the build process to only include the features you require. Doing so can cut the main build file size down to just 70KB. - -Read our [comprehensive guide](https://phaser.io/phaser3/devlog/127) on creating Custom Builds of Phaser 3 for full details. - -### Building from Source - -If you wish to build Phaser 3 from source, ensure you have the required packages by cloning the repository and then running `npm install` on your source directory. - -You can then run `webpack` to create a development build in the `build` folder which includes source maps for local testing. You can also `npm run dist` to create a minified packaged build in the `dist` folder. For a list of all commands available use `npm run help`. - -![Change Log](https://phaser.io/images/github/div-change-log.png "Change Log") - - -# Change Log - -## Version 3.22 - Kohaku - January 15th 2020 - -### Matter Physics - -All of the following are specific to the Matter Physics implementation used by Phaser: - -#### Matter Physics New Features - -* Matter Physics now has 100% JSDoc coverage! Woohoo :) -* Matter Physics now has brand new TypeScript defs included in the `types` folder :) -* `MatterDebugConfig` is a new configuration object that contains all of the following new Matter debug settings: -* `showAxes`- Render all of the body axes? -* `showAngleIndicator`- Render just a single body axis? -* `angleColor`- The color of the body angle / axes lines. -* `showBroadphase`- Render the broadphase grid? -* `broadphaseColor`- The color of the broadphase grid. -* `showBounds`- Render the bounds of the bodies in the world? -* `boundsColor`- The color of the body bounds. -* `showVelocity`- Render the velocity of the bodies in the world? -* `velocityColor`- The color of the body velocity line. -* `showCollisions`- Render the collision points and normals for colliding pairs. -* `collisionColor`- The color of the collision points. -* `showSeparation`- Render lines showing the separation between bodies. -* `separationColor`- The color of the body separation line. -* `showBody`- Render the dynamic bodies in the world to the Graphics object? -* `showStaticBody`- Render the static bodies in the world to the Graphics object? -* `showInternalEdges`- When rendering bodies, render the internal edges as well? -* `renderFill`- Render the bodies using a fill color. -* `renderLine`- Render the bodies using a line stroke. -* `fillColor`- The color value of the fill when rendering dynamic bodies. -* `fillOpacity`- The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. -* `lineColor`- The color value of the line stroke when rendering dynamic bodies. -* `lineOpacity`- The opacity of the line when rendering dynamic bodies, a value between 0 and 1. -* `lineThickness`- If rendering lines, the thickness of the line. -* `staticFillColor`- The color value of the fill when rendering static bodies. -* `staticLineColor`- The color value of the line stroke when rendering static bodies. -* `showSleeping`- Render any sleeping bodies (dynamic or static) in the world to the Graphics object? -* `staticBodySleepOpacity`] - The amount to multiply the opacity of sleeping static bodies by. -* `sleepFillColor`- The color value of the fill when rendering sleeping dynamic bodies. -* `sleepLineColor`- The color value of the line stroke when rendering sleeping dynamic bodies. -* `showSensors`- Render bodies or body parts that are flagged as being a sensor? -* `sensorFillColor`- The fill color when rendering body sensors. -* `sensorLineColor`- The line color when rendering body sensors. -* `showPositions`- Render the position of non-static bodies? -* `positionSize`- The size of the rectangle drawn when rendering the body position. -* `positionColor`- The color value of the rectangle drawn when rendering the body position. -* `showJoint`- Render all world constraints to the Graphics object? -* `jointColor`- The color value of joints when `showJoint` is set. -* `jointLineOpacity`- The line opacity when rendering joints, a value between 0 and 1. -* `jointLineThickness`- The line thickness when rendering joints. -* `pinSize`- The size of the circles drawn when rendering pin constraints. -* `pinColor`- The color value of the circles drawn when rendering pin constraints. -* `springColor`- The color value of spring constraints. -* `anchorColor`- The color value of constraint anchors. -* `anchorSize`- The size of the circles drawn as the constraint anchors. -* `showConvexHulls`- When rendering polygon bodies, render the convex hull as well? -* `hullColor`- The color value of hulls when `showConvexHulls` is set. -* `World.renderBody` is a new method that will render a single Matter Body to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which bodies are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. -* `World.renderConstraint` is a new method that will render a single Matter Constraint, such as a pin or a spring, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which constraints are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. -* `World.renderConvexHull` is a new method that will render the convex hull of a single Matter Body, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which hulls are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. -* `World.renderGrid` is a new method that will render the broadphase Grid to the given graphics instance. -* `World.renderBodyBounds` is a new method that will render the bounds of all the given bodies to the given graphics instance. -* `World.renderBodyAxes` is a new method that will render the axes of all the given bodies to the given graphics instance. -* `World.renderBodyVelocity` is a new method that will render a velocity line for all the given bodies to the given graphics instance. -* `World.renderSeparations` is a new method that will render the separations in the current pairs list to the given graphics instance. -* `World.renderCollisions` is a new method that will render the collision points and normals in the current pairs list to the given graphics instance. -* `World.getAllBodies` is a new method that will return all bodies in the Matter World. -* `World.getAllConstraints` is a new method that will return all constraints in the Matter World. -* `World.getAllComposites` is a new method that will return all composites in the Matter World. -* `MatterPhysics.composite` is a new reference to the `Matter.Composite` module for easy access from within a Scene. -* `MatterPhysics.detector` is a new reference to the `Matter.Dectector` module for easy access from within a Scene. -* `MatterPhysics.grid` is a new reference to the `Matter.Grid` module for easy access from within a Scene. -* `MatterPhysics.pair` is a new reference to the `Matter.Pair` module for easy access from within a Scene. -* `MatterPhysics.pairs` is a new reference to the `Matter.Pairs` module for easy access from within a Scene. -* `MatterPhysics.query` is a new reference to the `Matter.Query` module for easy access from within a Scene. -* `MatterPhysics.resolver` is a new reference to the `Matter.Resolver` module for easy access from within a Scene. -* `MatterPhysics.sat` is a new reference to the `Matter.SAT` module for easy access from within a Scene. -* `MatterPhysics.constraint` is a new reference to the `Matter.Constraint` module for easy access from within a Scene. -* `MatterPhysics.composites` is a new reference to the `Matter.Composites` module for easy access from within a Scene. -* `MatterPhysics.axes` is a new reference to the `Matter.Axes` module for easy access from within a Scene. -* `MatterPhysics.bounds` is a new reference to the `Matter.Bounds` module for easy access from within a Scene. -* `MatterPhysics.svg` is a new reference to the `Matter.Svg` module for easy access from within a Scene. -* `MatterPhysics.vector` is a new reference to the `Matter.Vector` module for easy access from within a Scene. -* `MatterPhysics.vertices` is a new reference to the `Matter.Vertices` module for easy access from within a Scene. -* `BEFORE_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be added to the World. -* `AFTER_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint has been added to the World. -* `BEFORE_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be removed from the World. -* `AFTER_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint has been removed from the World. -* `Body.render.lineOpacity` is a new property on the Matter Body object that allows for custom debug rendering. -* `Body.render.lineThickness` is a new property on the Matter Body object that allows for custom debug rendering. -* `Body.render.fillOpacity` is a new property on the Matter Body object that allows for custom debug rendering. -* `World.setCompositeRenderStyle` is a new method that lets you quickly set the render style values on the children of the given compposite. -* `World.setBodyRenderStyle` is a new method that lets you quickly set the render style values on the given Body. -* `World.setConstraintRenderStyle` is a new method that lets you quickly set the render style values on the given Constraint. -* You can now set `restingThresh` in the Matter Configuration file to adjust the Resolver property. -* You can now set `restingThreshTangent` in the Matter Configuration file to adjust the Resolver property. -* You can now set `positionDampen` in the Matter Configuration file to adjust the Resolver property. -* You can now set `positionWarming` in the Matter Configuration file to adjust the Resolver property. -* You can now set `frictionNormalMultiplier` in the Matter Configuration file to adjust the Resolver property. -* `MatterPhysics.containsPoint` is a new method that returns a boolean if any of the given bodies intersect with the given point. -* `MatterPhysics.intersectPoint` is a new method that checks which bodies intersect with the given point and returns them. -* `MatterPhysics.intersectRect` is a new method that checks which bodies intersect with the given rectangular area, and returns them. Optionally, it can check which bodies are outside of the area. -* `MatterPhysics.intersectRay` is a new method that checks which bodies intersect with the given ray segment and returns them. Optionally, you can set the width of the ray. -* `MatterPhysics.intersectBody` is a new method that checks which bodies intersect with the given body and returns them. If the bodies are set to not collide this can be used as an overlaps check. -* `MatterPhysics.overlap` is a new method that takes a target body and checks to see if it overlaps with any of the bodies given. If they do, optional `process` and `overlap` callbacks are invoked, passing the overlapping bodies to them, along with additional collision data. -* `MatterPhysics.setCollisionCategory` is a new method that will set the collision filter category to the value given, on all of the bodies given. This allows you to easily set the category on bodies that don't have a Phaser Matter Collision component. -* `MatterPhysics.setCollisionGroup` is a new method that will set the collision filter group to the value given, on all of the bodies given. This allows you to easily set the group on bodies that don't have a Phaser Matter Collision component. -* `MatterPhysics.setCollidesWith` is a new method that will set the collision filter mask to the value given, on all of the bodies given. This allows you to easily set the filter mask on bodies that don't have a Phaser Matter Collision component. -* `Matter.Body.centerOfMass` is a new vec2 property added to the Matter Body object that retains the center of mass coordinates when the Body is first created, or has parts added to it. These are float values, derived from the body position and bounds. -* `Matter.Body.centerOffset` is a new vec2 property added to the Matter Body object that retains the center offset coordinates when the Body is first created, or has parts added to it. These are pixel values. -* `Constraint.pointAWorld` is a new method added to Matter that returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`. -* `Constraint.pointBWorld` is a new method added to Matter that returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`. -* `Body.setCentre` is a new method added to Matter that allows you to set the center of mass of a Body (please note the English spelling of this function.) -* `Body.scale` is a new read-only vector that holds the most recent scale values as passed to `Body.scale`. -* `Matter.Bodies.flagCoincidentParts` is a new function that will flags all internal edges (coincident parts) on an array of body parts. This was previously part of the `fromVertices` function, but has been made external for outside use. -* `Matter.getMatterBodies` is a new function that will return an array of Matter JS Bodies from the given input array, which can be Matter Game Objects, or any class that extends them. -* `Matter.World.has` is a new method that will take a Matter Body, or Game Object, and search the world for it. If found, it will return `true`. -* Matter now has the option to use the Runner that it ships with. The Matter Runner operates in two modes: fixed and variable. In the fixed mode, the Matter Engine updates at a fixed delta value every frame (which is what Phaser has used since the first version). In variable mode, the delta will be smoothed and capped each frame to keep the simulation constant, but at the cost of determininism. You can configure the runner by setting the `runner` property in the Matter Config object, both of which are fully covered with JSDocs. As of 3.22 the runner is now used by default in variable (non-fixed) mode. If you wish to return to the previous behavior, set `runner: { isFixed: true }`. -* `Body.onCollideCallback` is a new Matter Body property that can point to a callback to invoke when the body starts colliding. -* `Body.onCollideEndCallback` is a new Matter Body property that can point to a callback to invoke when the body stops colliding. -* `Body.onCollideActiveCallback` is a new Matter Body property that can point to a callback to invoke for the duration the body is colliding. -* `Body.onCollideWith` is a new Matter Body property that holds a mapping between bodies and collision callbacks. -* `MatterGameObject.setOnCollide` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body collides with another. -* `MatterGameObject.setOnCollideEnd` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body stops colliding. -* `MatterGameObject.setOnCollideActive` is a new method available on any Matter Game Object, that sets a callback which is invoked for the duration of the bodies collision with another. -* `MatterGameObject.setOnCollideWith` is a new method available on any Matter Game Object, that allows you to set a callback to be invoked whenever the body collides with another specific body, or array of bodies. -* `Body.gravityScale` is a new vector property that allows you to scale the effect of world gravity on a specific Body. -* `MatterPhysics._tempVec2` is a new private internal vector used for velocity and force calculations. -* `MatterPhysics.setVelocity` is a new method that will set both the horizontal and vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.setVelocityX` is a new method that will set the horizontal linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.setVelocityY` is a new method that will set the vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.setAngularVelocity` is a new method that will set the angular velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.applyForce` is a new method that applies a force to a body, at the bodies current position, including resulting torque. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.applyForceFromPosition` is a new method that applies a force to a body from the given world position, including resulting torque. If no angle is given, the current body angle is used. This can be used on all Matter bodies, not just those created via the factory. -* `MatterPhysics.fromSVG` is a new method that allows you to create a Body from the given SVG path data. -* The `Matter.Factory.velocity` method has been removed. Please now use `MatterPhysics.setVelocity` instead. -* The `Matter.Factory.angularVelocity` method has been removed. Please now use `MatterPhysics.setAngularVelocity` instead. -* The `Matter.Factory.force` method has been removed. Please now use `MatterPhysics.applyForce` instead. -* `MatterBodyConfig` is a new type def that contains all of the Body configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterBodyRenderConfig` is a new type def that contains all of the Body debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterChamferConfig` is a new type def that contains all of the chamfer configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterCollisionFilter` is a new type def that contains all of the collision configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterConstraintConfig` is a new type def that contains all of the constraint configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterConstraintRenderConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterSetBodyConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. -* `MatterPhysics.getConstraintLength` is a new method that will return the length of the given constraint, as this is something you cannot get from the constraint properties directly. -* `MatterPhysics.alignBody` is a new method that will align a Body, or Matter Game Object, against the given coordinates, using the given alignment constant. For example, this allows you to easily position a body to the `BOTTOM_LEFT`, or `TOP_CENTER`, or a coordinate. Alignment is based on the body bounds. -* `Phaser.Types.Physics.Matter.MatterBody` is a new type def that contains all of the valid Matter Body objects. This is now used through-out the JSDocs to aid in code-completion. -* `Matter.BodyBounds` is a new class that contains methods to help you extract 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 new class via `this.matter.bodyBounds`. -* The method signature for `Matter.PhysicsEditorParser.parseBody` has changed. It now takes `(x, y, config, options)` and no longer has `width` and `height` parameters. Please see the updated documentation for more details if you were calling this method directly. -* `MatterPhysics.fromPhysicsEditor` is a new method that allows you to create a Matter Body based on the given PhysicsEditor shape data. Previously, you could only using PhysicsEditor data with a Matter Game Object, but now you can create a body directly using it. -* `Matter.PhysicsJSONParser` is a new parser that will create Matter bodies from JSON physics data files. Currently onto the Phaser Physics Tracer app exports in this format, but details are published in the JSDocs, so any app can do so. -* `Matter.Factory.fromJSON` is a new method that will create a body from a JSON physics data file. -* The `SetBody` Matter component can now automatically use shapes created in the Phaser Physics Tracer App in the JSON data format. -* `Matter.Components.Sleep.setToSleep` is a new method available on any Matter Game Object that will send the body to sleep, if Engine sleeping has been enabled. -* `Matter.Components.Sleep.setAwake` is a new method available on any Matter Game Object that will awake a body from sleep, if Engine sleeping has been enabled. - -#### Matter Physics Updates - -* The `debug` property in the Matter World Config is now a `MatterDebugConfig` option instead of a boolean. However, if a boolean is given, it will use the default debug config values. -* The following `MatterWorldConfig` options have now been removed: `debugShowBody`, `debugShowStaticBody`, `debugBodyColor`, `debugBodyFillColor`, `debugStaticBodyColor`, `debugShowJoint`, `debugJointColor`, `debugWireframes`, `debugShowInternalEdges`, `debugShowConvexHulls`, `debugConvexHullColor` and `debugShowSleeping`. These can all be set via the new `MatterDebugConfig` object instead. -* The object `World.defaults` has been removed. Defaults are now access via `World.debugDefaults`. -* `World.renderBodies` has been rewritten to cache commonly-used values and avoid a situation when a single body would be rendered twice. -* The private method `World.renderConvexHulls` has been removed as it's no longer used internally. -* The private method `World.renderWireframes` has been removed as it's no longer used internally. -* The method `World.fromPath` has been removed. This was never used internally and you can get the same results by calling `Vertices.fromPath`. -* The `World.setBounds` argument `thickness` now defaults to 64, not 128, to keep it matching the Matter World Config. -* The `Body.render.fillStyle` property that existed on the Matter Body object has been removed and replaced with `fillColor`. -* The `Body.render.strokeStyle` property that existed on the Matter Body object has been removed and replaced with `lineColor`. -* `Matter.Body.render.sprite.xOffset` and `yOffset` are no longer set to anything when a Body is created. They are left as zero, or you can override them in the Body config, in which case the value is added to the sprite origin offset during a call to `setExistingBody`. -* The `Matter.Mass.centerOfMass` component property now returns the pre-calculated Body `centerOfMass` property, which is much more accurate than the previous bounds offset value. -* `Matter.setExistingBody`, which is called interally whenever a Body is set on a Game Object, now uses the new `centerOffset` values to ensure that the texture frame is correctly centered based on the center of mass, not the Body bounds, allowing for much more accurate body to texture mapping with complex multi-part compound bodies. -* The `Matter.PhysicsEditorParser` has been updated so it no longer needs to set the render offsets, and instead uses the center of mass values. -* If the `Matter.Body` config doesn't contain a `position` property, it will now default to using `Vertices.centre(body.vertices)` as the position. In most cases, this is what you need, so it saves having to pass it in the config object. -* Bumped Matter Plugin versions to avoid console logs from Common.info and Common.warn. -* `PhysicsEditorParser.parseVertices` now uses `Bodies.flagCoincidentParts` to avoid duplicating code. -* `MatterGameObject` has a new optional boolean constructor parameter `addToWorld` which lets you control if the Body should be added to the world or not. Useful for toggling off should you be merging pre-existing bodies with Game Objects. -* The `Matter.SetBody.setExistingBody` function, which all Matter Game Objects have, has a new parameter `addToWorld` which allows you to control when the body is added to the Matter world should you not require it immediately. It will also only add the body to the world if it doesn't already exist within it, or any of its composites. -* `PointerConstraint` has been recoded so that when pressed down, it only polls the World for a body hit test during the next game update. This stops it coming out of sync with the state of the world. Use of the constraint remains the same as before. -* You can now set `gravity: false` in your Matter Config and it will reset gravity from the defaults to zero. -* The internal Matter `Composite.setModified` function will now emit a `compositeModified` event, which the Matter World listens for, if debug draw is enabled, so it can update the composite children render styles. -* `Matter.PhysicsEditorParser.parseBody` can now accept a MatterBodyConfig file as a 4th parameter. This allows you to set Body properties when the body is created, overriding whatever values may have been set in the PhysicsEditor JSON. - -#### Matter Physics Bug Fixes - -* Due to the rewrite of the debug rendering, it is now possible to render _just_ constraints, where-as before this was only possible if bodies were being rendered as well. Fix #4880 (thanks @roberto257) -* `Matter.PhysicsEditorParser` had a bug where it would allow fixtures with non-clockwise sorted vertices through, which would break pointer constraint interaction with these bodies. The parser now sorts the vertices properly. Fix #4261 (thanks @Sanchez3) - -### New Features - -* `TimeStep.smoothStep` is a new boolean property that controls if any delta smoothing takes place during the game step. Delta smoothing has been enabled in Phaser since the first version and helps avoid delta spikes and dips, especially after loss of focus. However, you can now easily toggle if this happens via this property and the corresponding `FPSConfig` property. -* `Phaser.Math.Distance.BetweenPoints` is a new function that will return the distance between two Vector2-like objects (thanks @samme) -* `Phaser.Math.Distance.BetweenPointsSquared` is a new function that will return the squared distance between two Vector2-like objects (thanks @samme) -* `Phaser.Math.Distance.Chebyshev` is a new function that will return the Chebyshev (or chessboard) distance between two Vector2-like objects (thanks @samme) -* `Phaser.Math.Distance.Snake` is a new function that will return the rectilinear distance between two Vector2-like objects (thanks @samme) -* `ParticleEmitter.setTint` is a new method that will set the tint of emitted particles for the given Emitter only (thanks @samme) -* `ParticleEmitter.remove` is a new method that will remove the Emitter from its Emitter Manager (thanks @samme) -* `ParticleEmitterManager.removeEmitter` is a new method that will remove the given emitter from the manager, if the emitter belongs to it (thanks @samme) -* `AlphaSingle` is a new Game Object Component that allows a Game Object to set its alpha values, but only as a single uniform value, not on a per-quad basis. -* `Actions.AlignTo` (in combination with the new `Display.Align.To.QuickSet` function) allows you to align an array of Game Objects so they sit next to each other, one at a time. The first item isn't moved, the second is moved to sit next to the first, and so on. You can align them using any of the alignment constants (thanks @samme) -* `Scene.Systems.getData` is a new method that will return any data that was sent to the Scene by another Scene, i.e. during a `run` or `launch` command. You can access it via `this.sys.getData()` from within your Scene. -* `Group.internalCreateCallback` is a new optional callback that is invoked whenever a child is added to a Group. This is the same as `createCallback` except it's only for use by the parent class, allowing a parent to invoke a creation callback and for you to still provide one via the Group config. -* `Group.internalRemoveCallback` is a new optional callback that is invoked whenever a child is removed from a Group. This is the same as `removeCallback` except it's only for use by the parent class, allowing a parent to invoke a callback and for you to still provide one via the Group config. - -### Updates - -* `Body.deltaXFinal` is a new method on Arcade Physics Bodies that will return the final change in the horizontal position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) -* `Body.deltaYFinal` is a new method on Arcade Physics Bodies that will return the final change in the vertical position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) -* `Body._tx` is a new internal private var, holding the Arcade Physics Body combined total delta x value. -* `Body._ty` is a new internal private var, holding the Arcade Physics Body combined total delta y value. -* `LineCurve.getUtoTmapping` has been updated to return `u` directly to avoid calculations as it's identical to `t` in a Line (thanks @rexrainbow) -* `Curve.getSpacedPoints` will now take an optional array as the 3rd parameter to store the points results in (thanks @rexrainbow) -* Trying to play or resume an audio file with an incorrect key will now throw a runtime error, instead of a console warning (thanks @samme) -* The `Shape` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the shape, rather than a quad alpha, which never worked for Shape objects. -* The `Container` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the container, rather than a quad alpha, which never worked consistently across Container children. Fix #4916 (thanks @laineus) -* The `DOMElement` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. -* The `Graphics` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. -* `TweenData` has a new property called `previous` which holds the eased property value prior to the update. -* The `TWEEN_UPDATE` event now sends two new parameters to the handler: `current` and `previous` which contain the current and previous property values. -* During `collideSpriteVsGroup` checks it will now skip bodies that are disabled to save doing a `contains` test (thanks @samme) -* `Display.Align.In.QuickSet` now accepts `LEFT_BOTTOM` as `BOTTOM_LEFT`, `LEFT_TOP` as `TOP_LEFT`, `RIGHT_BOTTOM` as `BOTTOM_RIGHT` and `RIGHT_TOP` as `TOP_RIGHT`. Fix #4927 (thanks @zaniar) -* `PhysicsGroup` now uses the new `internalCreateCallback` and `internalRemoveCallback` to handle its body creation and destruction, allowing you to use your own `createCallback` and `removeCallback` as defined in the Group config. Fix #4420 #4657 #4822 (thanks @S4n60w3n @kendistiller @scrubperson) -* `DOMElement` has a new private method `handleSceneEvent` which will handle toggling the display setting of the element when a Scene sleeps and wakes. A DOM Element will now listen for the Scene sleep and wake events. These event listeners are removed in the `preDestroy` method. -* A `DOMElement` will now set the display mode to 'none' during its render if the Scene in which it belongs is no longer visible. - -### Bug Fixes - -* BitmapText with a `maxWidth` set wouldn't update the text correctly if it was modified post-creation. You can now update the text and/or width independantly and it'll update correctly. Fix #4881 (thanks @oxguy3) -* Text objects will no longer add any white-space when word-wrapping if the last line is only one word long. Fix #4867 (thanks @gaamoo @rexrainbow) -* When `Game.destroy` is running, Scenes are now destroyed _before_ plugins, avoiding bugs when closing down plugins and deleting Render Textures. Fix #4849 #4876 (thanks @rexrainbow @siyuanqiao) -* The `Mesh` and `Quad` Game Objects have had the `GetBounds` component removed as it cannot operate on a Mesh as they don't have origins. Fix #4902 (thanks @samme) -* Setting `lineSpacing` in the Text Game Object style config would set the value but not apply it to the Text, leaving you to call `updateText` yourself. If set, it's now applied on instantiation. Fix #4901 (thanks @FantaZZ) -* External calls to the Fullscreen API using `element.requestFullscreen()` would be blocked by the Scale Manager. The Scale Manager will no longer call `stopFullScreen` should it be triggered outside of Phaser (thanks @AdamXA) -* The `Tilemaps.Tile.tint` property wasn't working correctly as it expected the colors in the wrong order (BGR instead of RGB). It will now expect them in the correct RGB order (thanks @Aedalus @plissken2013es) -* The `ScaleManager.destroy` method wasn't being called when the Game `DESTROY` event was dispatched, causing minor gc to build up. The destroy method will now be called properly on game destruction. Fix #4944 (thanks @sunshineuoow) -* `FacebookInstantGamesPlugin.showAd` and `showVideo` will now break out of the ad iteration search once a valid ad has been found and called. Previously, it would carry on interating if the async didn't complete quickly. Fix #4888 (thanks @east62687) -* When playing an Animation, if you were to play another, then pause it, then play another the internal `_paused` wouldn't get reset, preventing you from them pausing the animations from that point on. You can now play and pause animations at will. Fix #4835 (thanks @murteira) -* In `Actions.GridAlign` if you set `width` to -1 it would align the items vertically, instead of horizontally. It now aligns them horizontally if `width` is set, or vertically if `height` is set. Fix #4899 (thanks @BenjaVR) -* A `PathFollower` with a very short duration would often not end in the correct place, which is the very end of the Path, due to the tween handling the movement not running one final update when the tween was complete. It will now always end at the final point of the path, no matter how short the duration. Fix #4950 (thanks @bramp) -* A `DOMElement` would still remain visible even if the Scene in which it belongs to was sent to sleep. A sleeping Scene shouldn't render anything. DOM Elements will now respond to sleep and wake events from their parent Scene. Fix #4870 (thanks @peonmodel) -* If a config object was passed to `MultiAtlasFile` it expected the atlas URL to be in the `url` property, however the docs and file config expected it in `atlasURL`. You can now use either of these properties to declare the url. Fix #4815 (thanks @xense) - -### Examples, Documentation and TypeScript - -My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: - -@fselcukcan Bambosh @louisth @hexus @javigaralva @samme @BeLi4L @jcyuan @javigaralva @T-Grave @bramp @Chnapy @dranitski @RollinSafary @xense - -The Matter TypeScript defs have been updated to include lots of missing classes, removed some redundant elements and general fixes. The Phaser TypeScript defs now reference the Matter defs directly and no longer try to parse them from the JSDocs. This allows the `MatterJS` namespace to work in TypeScript projects without any compilation warnings. - -The Spine Plugin now has new TypeScript defs in the `types` folder thanks to @supertommy - -Please see the complete [Change Log](https://github.com/photonstorm/phaser/blob/master/CHANGELOG.md) for previous releases. - -![Contributing](https://phaser.io/images/github/div-contributing.png "Contributing") - - -The [Contributors Guide][contribute] contains full details on how to help with Phaser development. The main points are: - -- Found a bug? Report it on [GitHub Issues][issues] and include a code sample. Please state which version of Phaser you are using! This is vitally important. - -- Before submitting a Pull Request run your code through [ES Lint](https://eslint.org/) using our [config](https://github.com/photonstorm/phaser/blob/master/.eslintrc.json) and respect our [Editor Config](https://github.com/photonstorm/phaser/blob/master/.editorconfig). - -- Before contributing read the [code of conduct](https://github.com/photonstorm/phaser/blob/master/.github/CODE_OF_CONDUCT.md). - -Written something cool in Phaser? Please tell us about it in the [forum][forum], or email support@phaser.io - -![Created by](https://phaser.io/images/github/div-created-by.png "Created by") - -Phaser is a [Photon Storm](http://www.photonstorm.com) production. - -![storm](https://www.phaser.io/images/github/photonstorm-x2.png) - -Created by [Richard Davey](mailto:rich@photonstorm.com). Powered by coffee, anime, pixels and love. - -The Phaser logo and characters are © 2019 Photon Storm Limited. - -All rights reserved. - -"Above all, video games are meant to be just one thing: fun. Fun for everyone." - Satoru Iwata - -[get-js]: https://github.com/photonstorm/phaser/releases/download/v3.22.0/phaser.js -[get-minjs]: https://github.com/photonstorm/phaser/releases/download/v3.22.0/phaser.min.js -[clone-http]: https://github.com/photonstorm/phaser.git -[clone-ssh]: git@github.com:photonstorm/phaser.git -[clone-ghwin]: github-windows://openRepo/https://github.com/photonstorm/phaser -[clone-ghmac]: github-mac://openRepo/https://github.com/photonstorm/phaser -[phaser]: https://github.com/photonstorm/phaser -[issues]: https://github.com/photonstorm/phaser/issues -[examples]: https://github.com/photonstorm/phaser3-examples -[contribute]: https://github.com/photonstorm/phaser/blob/master/.github/CONTRIBUTING.md -[forum]: https://phaser.discourse.group/ +# Phaser - HTML5 Game Framework + +![Phaser Header](https://phaser.io/images/github/300/phaser-header.png "Phaser 3 Header Banner") + +[![Discord chat](https://img.shields.io/discord/244245946873937922?style=for-the-badge)](https://discord.gg/phaser) +[![Twitter Follow](https://img.shields.io/twitter/follow/phaser_?style=for-the-badge)](https://twitter.com/phaser_) +![GitHub All Releases](https://img.shields.io/github/downloads/photonstorm/phaser/total?style=for-the-badge) +![npm](https://img.shields.io/npm/dy/phaser?label=npm&style=for-the-badge) + +Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop and mobile web browsers. Games can be compiled to iOS, Android and native apps by using 3rd party tools. You can use JavaScript or TypeScript for development. + +Along with the fantastic open source community, Phaser is actively developed and maintained by [Photon Storm](http://www.photonstorm.com). As a result of rapid support, and a developer friendly API, Phaser is currently one of the [most starred](https://github.com/collections/javascript-game-engines) game frameworks on GitHub. + +Thousands of developers from indie and multi-national digital agencies, and universities worldwide use Phaser. You can take a look at their incredible [games](https://phaser.io/games/). + +**Visit:** The [Phaser website](https://phaser.io) and follow on [Twitter](https://twitter.com/phaser_) (#phaserjs)
+**Learn:** [API Docs](https://photonstorm.github.io/phaser3-docs/index.html), [Support Forum][forum] and [StackOverflow](https://stackoverflow.com/questions/tagged/phaser-framework)
+**Code:** 1700+ [Examples](https://phaser.io/examples) (source available in this [repo][examples])
+**Read:** The [Phaser World](#newsletter) Newsletter
+**Chat:** [Discord](https://phaser.io/community/discord) and [Slack](https://phaser.io/community/slack)
+**Extend:** With [Phaser Plugins](https://phaser.io/shop/plugins)
+**Be awesome:** [Support](#support) the future of Phaser
+ +Grab the source and join the fun! + +![What's New](https://phaser.io/images/github/div-whats-new.png "What's New") + +
+ +> 15th January 2020 + +We're excited to announce the release of Phaser 3.22, the first of many in the year 2020. The main focus of 3.22 is all the work we've done on Matter Physics integration. Matter has been supported in Phaser since the first release, yet there were lots of things we wanted to do with it to make development life easier. 3.22 brings all of these to the front, including powerful new visual debugging options such as rendering contacts, velocity, the broadphase grid, sensors, joints and more. Matter also now has 100% JSDoc and TypeScripy coverage and I spent a long time rebuilding the TypeScript defs by hand, in order to make them as accurate as possible. + +As well as docs and defs there are stacks of handy new methods, including intersection tests such as `intersectPoint`, `intersectRay`, `overlap` and more. New Body level collision callbacks allow you to filter collided pairs a lot more quickly now, combined with new collision events and data type defs to give you all the information you need when resolving. There are now functions to create bodies from SVG data, JSON data or Physics Editor data directly, new Body alignment features and of course bug fixes. + +It's not all about Matter Physics, though. Thanks to the community, there are new Math Distance functions such as Chebyshev, Snake and Squared Points. You can now tint particles as they're emitted, Physics Groups finally let you use your own creation and removal callbacks and plenty more besides. There are, of course, lots of bug fixes too and I've done my best to address some of the most important ones. The documentation has improved yet again and with every release the TypeScript defs get stronger and stronger. So, as usual, please do spend some time digging through the [Change Log](#changelog). I assure you, it's worth while :) + +With 3.22 released I will now be taking some time to carry on with Phaser 4 development, while planning out the 3.23 release as well. Even though Phaser 4 is in build I will fully support Phaser 3 for the foreseeable future. You can follow the development progress of both versions on the Phaser Patreon. + +As usual, I'd like to send a massive thank-you to everyone who supports Phaser on Patreon (and now even GitHub Sponsors, too!) Your continued backing keeps allowing me to work on Phaser full-time and this great new releases is the very real result of that. If you've ever considered becoming a backer, now is the perfect time! + +If you'd like to stay abreast of developments then I publish my [Developer Logs](https://phaser.io/phaser3/devlog) in the [Phaser World](https://phaser.io/community/newsletter) newsletter. Subscribe to stay in touch and get all the latest news from the core team and the wider community. + +You can also follow Phaser on [Twitter](https://twitter.com/phaser_) and chat with fellow Phaser devs in our [Discord](https://phaser.io/community/discord) and [Slack](https://phaser.io/community/slack) channels. + +Phaser 3 wouldn't have been possible without the fantastic support of the community and Patreon. Thank you to everyone who supports our work, who shares our belief in the future of HTML5 gaming, and Phaser's role in that. + +Happy coding everyone! + +Cheers, + +Rich - [@photonstorm](https://twitter.com/photonstorm) + +![boogie](https://www.phaser.io/images/spacedancer.gif) + +![Support Phaser](https://phaser.io/images/github/div-support-phaser.png "Support Phaser") + +Because Phaser is an open source project, we cannot charge for it in the same way as traditional retail software. What's more, we don't ever want to. After all, it's built on, and was born from, open web standards. It's part of our manifesto that the core framework will always be free, even if you use it commercially, as many of you do. + +**You may not realize it, but because of this, we rely 100% on community backing to fund development.** + +Those funds allow Phaser to improve, and when it improves, everyone involved benefits. Your support helps secure a constant cycle of updates, fixes, new features and planning for the future. + +There are other benefits to [backing Phaser](https://www.patreon.com/join/photonstorm), too: + +![Backers Perks](https://phaser.io/images/github/patreon-perk-chart.png) + +We use [Patreon](https://www.patreon.com/photonstorm) to manage the backing and you can [support Phaser](https://www.patreon.com/join/photonstorm?) from $1 per month. The amount you pledge is entirely up to you and can be changed as often as you like. Patreon renews monthly, just like Netflix. You can, of course, cancel at any point. Tears will be shed on this end, but that's not your concern. + +Extra special thanks to the following companies who's support makes Phaser possible: + +* [Cerebral Fix](https://cerebralfix.com) +* [CrossInstall](https://crossinstall.com) +* [Facebook](https://www.facebook.com) +* [Game Distribution](https://gamedistribution.com) +* [GameCommerce](https://www.gamecommerce.com) +* [Mozilla](https://www.mozilla.org) +* [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) +* [Twilio](https://www.twilio.com) +* [Y8 Games](https://www.y8.com) +* [Poki](https://developers.poki.com/) + +![Sponsors](https://phaser.io/images/github/sponsors-2019-12.png "Awesome Sponsors") + +![Phaser Newsletter](https://phaser.io/images/github/div-newsletter.png "Phaser Newsletter") + +
+ +We publish the [Phaser World](https://phaser.io/community/newsletter) newsletter. It's packed full of the latest Phaser games, tutorials, videos, meet-ups, talks, and more. The newsletter also contains our weekly Development Progress updates which let you know about the new features we're working on. + +Over 140 previous editions can be found on our [Back Issues](https://phaser.io/community/backissues) page. + +![Download Phaser](https://phaser.io/images/github/div-download.png "Download Phaser") + + +Phaser 3 is available via GitHub, npm and CDNs: + +* Clone the git repository via [https][clone-http], [ssh][clone-ssh] or with the GitHub [Windows][clone-ghwin] or [Mac][clone-ghmac] clients. +* Download as [zip](https://github.com/photonstorm/phaser/archive/master.zip) +* Download the build files: [phaser.js][get-js] and [phaser.min.js][get-minjs] + +### NPM + +Install via [npm](https://www.npmjs.com): + +```bash +npm install phaser +``` + +### CDN + +[![](https://data.jsdelivr.com/v1/package/gh/photonstorm/phaser/badge)](https://www.jsdelivr.com/package/gh/photonstorm/phaser) + +[Phaser is on jsDelivr](https://www.jsdelivr.com/projects/phaser) which is a "super-fast CDN for developers". Include the following in your html: + +```html + +``` + +or the minified version: + +```html + +``` + +### API Documentation + +Go to https://photonstorm.github.io/phaser3-docs/index.html to read the docs online. Use the drop-down menus at the top to navigate the namespaces, classes and Game Objects lists. + +Or, if you wish to run the docs locally you can checkout the [phaser3-docs](https://github.com/photonstorm/phaser3-docs) repository and then read the documentation by pointing your browser to the `docs/` folder. + +The documentation for Phaser 3 is an on-going project. Please help us by searching the Phaser code for any instance of the string `[description]` and then replacing it with some documentation. + +### TypeScript Definitions + +The [TypeScript definitions](https://github.com/photonstorm/phaser/tree/master/types) can be found inside the `types` folder. They are also referenced in the types entry in `package.json`. + +Depending on your project, you may need to add the following to your `tsconfig.json` file: + +```json +"typeRoots": [ + "./node_modules/phaser/types" +], +"types": [ + "Phaser" +] +``` + +We recently published a new [Phaser 3 TypeScript Project Template](https://github.com/photonstorm/phaser3-typescript-project-template), which you can use to get started with if you like. + +The TS defs are automatically generated from the JSDoc comments found in the Phaser source code. If you wish to help refine them then you must edit the Phaser JSDoc blocks directly, not the defs file. You can find more details about the parser we built in the `scripts/tsgen` folder. + +### Webpack + +We use Webpack to build Phaser and we take advantage of its conditional build flag feature to handle renderer swapping. If you wish to use Webpack with Phaser then please use our [Phaser 3 Project Template](https://github.com/photonstorm/phaser3-project-template) as it's already set-up to handle the build conditions Phaser needs. Recent changes to our build steps mean you should now be able to use any other packager, like Parcel, without any config changes. + +### License + +Phaser is released under the [MIT License](https://opensource.org/licenses/MIT). + +![Getting Started](https://phaser.io/images/github/div-getting-started.png "Getting Started") + + + + +Tutorials and guides on Phaser 3 development are being published every week. + +* [Getting Started with Phaser 3](https://phaser.io/tutorials/getting-started-phaser3) (useful if you are completely new to Phaser) +* [Making your first Phaser 3 Game](https://phaser.io/tutorials/making-your-first-phaser-3-game) +* The [Complete Phaser 3 Game Development course](https://academy.zenva.com/product/html5-game-phaser-mini-degree/?a=13) contains over 15 hours of videos covering all kinds of important topics. +* Plus, there are [over 700 Phaser tutorials](http://phaser.io/learn) listed on the official website. + +Also, please subscribe to the [Phaser World](https://phaser.io/community/newsletter) newsletter for details about new tutorials as they are published. + +### Facebook Instant Games + +Phaser 3.13 introduced the new [Facebook Instant Games](http://phaser.io/news/2018/10/facebook-instant-games-phaser-tutorial) Plugin. The plugin provides a seamless bridge between Phaser and version 6.2 of the Facebook Instant Games SDK. Every single SDK function is available via the plugin and we will keep track of the official SDK to make sure they stay in sync. + +The plugin offers the following features: + +* Easy integration with the Phaser Loader so load events update the Facebook progress circle. +* Events for every plugin method, allowing the async calls of the SDK to be correctly inserted into the Phaser game flow. When SDK calls resolve they will surface naturally as a Phaser event and you'll know you can safely act upon them without potentially doing something mid-way through the game step. +* All Plugin methods check if the call is part of the supported APIs available in the SDK, without needing to launch an async request first. +* Instant access to platform, player and locale data. +* Easily load player photos directly into the Texture Manager, ready for use with a Game Object. +* Subscribe to game bots. +* The plugin has a built-in Data Manager which makes dealing with data stored on Facebook seamless. Just create whatever data properties you need and they are automatically synced. +* Support for FB stats, to retrieve, store and increment stats into cloud storage. +* Save Session data with built-in session length validation. +* Easy context switching, to swap between game instances and session data retrieval. +* Easily open a Facebook share, invite, request or game challenge window and populate the text and image content using any image stored in the Texture cache. +* Full Leaderboard support. Retrieve, scan and update leaderboard entries, as well as player matching. +* Support for in-app purchases, with product catalogs, the ability to handle purchases, get past purchases and consume previously unlocked purchases. +* Easily preload a set of interstitial ads, in both banner and video form, then display the ad at any point in your game, with in-built tracking of ads displayed and inventory available. +* Plus other features, such as logging to FB Analytics, creating short cuts, switching games, etc. + +We've 3 tutorials related to Facebook Instant Games and Phaser: + +* [Getting Started with Facebook Instant Games](http://phaser.io/news/2018/10/facebook-instant-games-phaser-tutorial) +* [Facebook Instant Games Leaderboards Tutorial](http://phaser.io/news/2018/11/facebook-instant-games-leaderboards-tutorial) +* [Displaying Ads in your Instant Games](http://phaser.io/news/2018/12/facebook-instant-games-ads-tutorial) + +A special build of Phaser with the Facebook Instant Games Plugin ready-enabled is [available on jsDelivr](https://www.jsdelivr.com/projects/phaser). Include the following in your html: + +```html + +``` + +or the minified version: + +```html + +``` + +The build files are in the git repository in the `dist` folder, and you can also include the plugin in custom builds. + +### Source Code Examples + +During our development of Phaser 3, we created hundreds of examples with the full source code and assets ready available. These examples are now fully integrated into the [Phaser website](https://phaser.io/examples). You can also browse them on [Phaser 3 Labs](https://labs.phaser.io) via a more advanced interface, or clone the [examples repo][examples]. We are constantly adding to and refining these examples. + +### Create Your First Phaser 3 Example + +Create an `index.html` page locally and paste the following code into it: + +```html + + + + + + + + + + + +``` + +This is a standard empty webpage. You'll notice there's a script tag that is pulling in a build of Phaser 3, but otherwise this webpage doesn't do anything yet. Now let's set-up the game config. Paste the following between the `` tags: + +```javascript +var config = { + type: Phaser.AUTO, + width: 800, + height: 600, + physics: { + default: 'arcade', + arcade: { + gravity: { y: 200 } + } + }, + scene: { + preload: preload, + create: create + } +}; +``` + +`config` is a pretty standard Phaser 3 Game Configuration object. We tell `config` to use the WebGL renderer if it can, set the canvas to a size of 800x600 pixels, enable Arcade Physics, and finally call the `preload` and `create` functions. `preload` and `create` have not been implemented yet, so if you run this JavaScript code, you will have an error. Add the following after `config`: + +```javascript +var game = new Phaser.Game(config); + +function preload () +{ + this.load.setBaseURL('http://labs.phaser.io'); + + this.load.image('sky', 'assets/skies/space3.png'); + this.load.image('logo', 'assets/sprites/phaser3-logo.png'); + this.load.image('red', 'assets/particles/red.png'); +} + +function create () +{ +} +``` + +`game` is a Phaser Game instance that uses our configuration object `config`. We also add function definitions for `preload` and `create`. The `preload` function helps you easily load assets into your game. In `preload`, we set the Base URL to be the Phaser server and load 3 PNG files. + +The `create` function is empty, so it's time to fill it in: + +```javascript +function create () +{ + this.add.image(400, 300, 'sky'); + + var particles = this.add.particles('red'); + + var emitter = particles.createEmitter({ + speed: 100, + scale: { start: 1, end: 0 }, + blendMode: 'ADD' + }); + + var logo = this.physics.add.image(400, 100, 'logo'); + + logo.setVelocity(100, 200); + logo.setBounce(1, 1); + logo.setCollideWorldBounds(true); + + emitter.startFollow(logo); +} +``` + +Here we add a sky image into the game and create a Particle Emitter. The `scale` value means that the particles will initially be large and will shrink to nothing as their lifespan progresses. + +After creating the `emitter`, we add a logo image called `logo`. Since `logo` is a Physics Image, `logo` is given a physics body by default. We set some properties for `logo`: velocity, bounce (or restitution), and collision with the world bounds. These properties will make our logo bounce around the screen. Finally, we tell the particle emitter to follow the logo - so as the logo moves, the particles will flow from it. + +Run it in your browser and you'll see the following: + +![Phaser 3 Demo](https://phaser.io/images/github/300/sample1.png "Phaser 3 Demo") + +(Got an error? Here's the [full code](https://gist.github.com/photonstorm/46cb8fb4b19fc7717dcad514cdcec064)) + +This is a tiny example, and there are hundreds more for you to explore, but hopefully it shows how expressive and quick Phaser is to use. With just a few easily readable lines of code, we've got something pretty impressive up on screen! + +Subscribe to our newsletter for further tutorials and examples. + +![Building Phaser](https://phaser.io/images/github/div-building-phaser.png "Building Phaser") + +There are both plain and minified compiled versions of Phaser in the `dist` folder of the repository. The plain version is for use during development, and the minified version is for production use. You can also create your own builds. + +### Custom Builds + +Phaser 3 is built using Webpack and we take advantage of the Webpack definePlugin feature to allow for conditional building of the Canvas and WebGL renderers and extra plugins. You can custom the build process to only include the features you require. Doing so can cut the main build file size down to just 70KB. + +Read our [comprehensive guide](https://phaser.io/phaser3/devlog/127) on creating Custom Builds of Phaser 3 for full details. + +### Building from Source + +If you wish to build Phaser 3 from source, ensure you have the required packages by cloning the repository and then running `npm install` on your source directory. + +You can then run `webpack` to create a development build in the `build` folder which includes source maps for local testing. You can also `npm run dist` to create a minified packaged build in the `dist` folder. For a list of all commands available use `npm run help`. + +![Change Log](https://phaser.io/images/github/div-change-log.png "Change Log") + + +# Change Log + +## Version 3.22 - Kohaku - January 15th 2020 + +### Matter Physics + +All of the following are specific to the Matter Physics implementation used by Phaser: + +#### Matter Physics New Features + +* Matter Physics now has 100% JSDoc coverage! Woohoo :) +* Matter Physics now has brand new TypeScript defs included in the `types` folder :) +* `MatterDebugConfig` is a new configuration object that contains all of the following new Matter debug settings: +* `showAxes`- Render all of the body axes? +* `showAngleIndicator`- Render just a single body axis? +* `angleColor`- The color of the body angle / axes lines. +* `showBroadphase`- Render the broadphase grid? +* `broadphaseColor`- The color of the broadphase grid. +* `showBounds`- Render the bounds of the bodies in the world? +* `boundsColor`- The color of the body bounds. +* `showVelocity`- Render the velocity of the bodies in the world? +* `velocityColor`- The color of the body velocity line. +* `showCollisions`- Render the collision points and normals for colliding pairs. +* `collisionColor`- The color of the collision points. +* `showSeparation`- Render lines showing the separation between bodies. +* `separationColor`- The color of the body separation line. +* `showBody`- Render the dynamic bodies in the world to the Graphics object? +* `showStaticBody`- Render the static bodies in the world to the Graphics object? +* `showInternalEdges`- When rendering bodies, render the internal edges as well? +* `renderFill`- Render the bodies using a fill color. +* `renderLine`- Render the bodies using a line stroke. +* `fillColor`- The color value of the fill when rendering dynamic bodies. +* `fillOpacity`- The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. +* `lineColor`- The color value of the line stroke when rendering dynamic bodies. +* `lineOpacity`- The opacity of the line when rendering dynamic bodies, a value between 0 and 1. +* `lineThickness`- If rendering lines, the thickness of the line. +* `staticFillColor`- The color value of the fill when rendering static bodies. +* `staticLineColor`- The color value of the line stroke when rendering static bodies. +* `showSleeping`- Render any sleeping bodies (dynamic or static) in the world to the Graphics object? +* `staticBodySleepOpacity`] - The amount to multiply the opacity of sleeping static bodies by. +* `sleepFillColor`- The color value of the fill when rendering sleeping dynamic bodies. +* `sleepLineColor`- The color value of the line stroke when rendering sleeping dynamic bodies. +* `showSensors`- Render bodies or body parts that are flagged as being a sensor? +* `sensorFillColor`- The fill color when rendering body sensors. +* `sensorLineColor`- The line color when rendering body sensors. +* `showPositions`- Render the position of non-static bodies? +* `positionSize`- The size of the rectangle drawn when rendering the body position. +* `positionColor`- The color value of the rectangle drawn when rendering the body position. +* `showJoint`- Render all world constraints to the Graphics object? +* `jointColor`- The color value of joints when `showJoint` is set. +* `jointLineOpacity`- The line opacity when rendering joints, a value between 0 and 1. +* `jointLineThickness`- The line thickness when rendering joints. +* `pinSize`- The size of the circles drawn when rendering pin constraints. +* `pinColor`- The color value of the circles drawn when rendering pin constraints. +* `springColor`- The color value of spring constraints. +* `anchorColor`- The color value of constraint anchors. +* `anchorSize`- The size of the circles drawn as the constraint anchors. +* `showConvexHulls`- When rendering polygon bodies, render the convex hull as well? +* `hullColor`- The color value of hulls when `showConvexHulls` is set. +* `World.renderBody` is a new method that will render a single Matter Body to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which bodies are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. +* `World.renderConstraint` is a new method that will render a single Matter Constraint, such as a pin or a spring, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which constraints are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. +* `World.renderConvexHull` is a new method that will render the convex hull of a single Matter Body, to the given Graphics object. This is used internally during debug rendering but is also public. This allows you to control which hulls are rendered and to which Graphics object, should you wish to use them in-game and not just during debugging. +* `World.renderGrid` is a new method that will render the broadphase Grid to the given graphics instance. +* `World.renderBodyBounds` is a new method that will render the bounds of all the given bodies to the given graphics instance. +* `World.renderBodyAxes` is a new method that will render the axes of all the given bodies to the given graphics instance. +* `World.renderBodyVelocity` is a new method that will render a velocity line for all the given bodies to the given graphics instance. +* `World.renderSeparations` is a new method that will render the separations in the current pairs list to the given graphics instance. +* `World.renderCollisions` is a new method that will render the collision points and normals in the current pairs list to the given graphics instance. +* `World.getAllBodies` is a new method that will return all bodies in the Matter World. +* `World.getAllConstraints` is a new method that will return all constraints in the Matter World. +* `World.getAllComposites` is a new method that will return all composites in the Matter World. +* `MatterPhysics.composite` is a new reference to the `Matter.Composite` module for easy access from within a Scene. +* `MatterPhysics.detector` is a new reference to the `Matter.Dectector` module for easy access from within a Scene. +* `MatterPhysics.grid` is a new reference to the `Matter.Grid` module for easy access from within a Scene. +* `MatterPhysics.pair` is a new reference to the `Matter.Pair` module for easy access from within a Scene. +* `MatterPhysics.pairs` is a new reference to the `Matter.Pairs` module for easy access from within a Scene. +* `MatterPhysics.query` is a new reference to the `Matter.Query` module for easy access from within a Scene. +* `MatterPhysics.resolver` is a new reference to the `Matter.Resolver` module for easy access from within a Scene. +* `MatterPhysics.sat` is a new reference to the `Matter.SAT` module for easy access from within a Scene. +* `MatterPhysics.constraint` is a new reference to the `Matter.Constraint` module for easy access from within a Scene. +* `MatterPhysics.composites` is a new reference to the `Matter.Composites` module for easy access from within a Scene. +* `MatterPhysics.axes` is a new reference to the `Matter.Axes` module for easy access from within a Scene. +* `MatterPhysics.bounds` is a new reference to the `Matter.Bounds` module for easy access from within a Scene. +* `MatterPhysics.svg` is a new reference to the `Matter.Svg` module for easy access from within a Scene. +* `MatterPhysics.vector` is a new reference to the `Matter.Vector` module for easy access from within a Scene. +* `MatterPhysics.vertices` is a new reference to the `Matter.Vertices` module for easy access from within a Scene. +* `BEFORE_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be added to the World. +* `AFTER_ADD` is a new Event dispatched by `Matter.World` when a Body or Constraint has been added to the World. +* `BEFORE_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint is about to be removed from the World. +* `AFTER_REMOVE` is a new Event dispatched by `Matter.World` when a Body or Constraint has been removed from the World. +* `Body.render.lineOpacity` is a new property on the Matter Body object that allows for custom debug rendering. +* `Body.render.lineThickness` is a new property on the Matter Body object that allows for custom debug rendering. +* `Body.render.fillOpacity` is a new property on the Matter Body object that allows for custom debug rendering. +* `World.setCompositeRenderStyle` is a new method that lets you quickly set the render style values on the children of the given compposite. +* `World.setBodyRenderStyle` is a new method that lets you quickly set the render style values on the given Body. +* `World.setConstraintRenderStyle` is a new method that lets you quickly set the render style values on the given Constraint. +* You can now set `restingThresh` in the Matter Configuration file to adjust the Resolver property. +* You can now set `restingThreshTangent` in the Matter Configuration file to adjust the Resolver property. +* You can now set `positionDampen` in the Matter Configuration file to adjust the Resolver property. +* You can now set `positionWarming` in the Matter Configuration file to adjust the Resolver property. +* You can now set `frictionNormalMultiplier` in the Matter Configuration file to adjust the Resolver property. +* `MatterPhysics.containsPoint` is a new method that returns a boolean if any of the given bodies intersect with the given point. +* `MatterPhysics.intersectPoint` is a new method that checks which bodies intersect with the given point and returns them. +* `MatterPhysics.intersectRect` is a new method that checks which bodies intersect with the given rectangular area, and returns them. Optionally, it can check which bodies are outside of the area. +* `MatterPhysics.intersectRay` is a new method that checks which bodies intersect with the given ray segment and returns them. Optionally, you can set the width of the ray. +* `MatterPhysics.intersectBody` is a new method that checks which bodies intersect with the given body and returns them. If the bodies are set to not collide this can be used as an overlaps check. +* `MatterPhysics.overlap` is a new method that takes a target body and checks to see if it overlaps with any of the bodies given. If they do, optional `process` and `overlap` callbacks are invoked, passing the overlapping bodies to them, along with additional collision data. +* `MatterPhysics.setCollisionCategory` is a new method that will set the collision filter category to the value given, on all of the bodies given. This allows you to easily set the category on bodies that don't have a Phaser Matter Collision component. +* `MatterPhysics.setCollisionGroup` is a new method that will set the collision filter group to the value given, on all of the bodies given. This allows you to easily set the group on bodies that don't have a Phaser Matter Collision component. +* `MatterPhysics.setCollidesWith` is a new method that will set the collision filter mask to the value given, on all of the bodies given. This allows you to easily set the filter mask on bodies that don't have a Phaser Matter Collision component. +* `Matter.Body.centerOfMass` is a new vec2 property added to the Matter Body object that retains the center of mass coordinates when the Body is first created, or has parts added to it. These are float values, derived from the body position and bounds. +* `Matter.Body.centerOffset` is a new vec2 property added to the Matter Body object that retains the center offset coordinates when the Body is first created, or has parts added to it. These are pixel values. +* `Constraint.pointAWorld` is a new method added to Matter that returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`. +* `Constraint.pointBWorld` is a new method added to Matter that returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`. +* `Body.setCentre` is a new method added to Matter that allows you to set the center of mass of a Body (please note the English spelling of this function.) +* `Body.scale` is a new read-only vector that holds the most recent scale values as passed to `Body.scale`. +* `Matter.Bodies.flagCoincidentParts` is a new function that will flags all internal edges (coincident parts) on an array of body parts. This was previously part of the `fromVertices` function, but has been made external for outside use. +* `Matter.getMatterBodies` is a new function that will return an array of Matter JS Bodies from the given input array, which can be Matter Game Objects, or any class that extends them. +* `Matter.World.has` is a new method that will take a Matter Body, or Game Object, and search the world for it. If found, it will return `true`. +* Matter now has the option to use the Runner that it ships with. The Matter Runner operates in two modes: fixed and variable. In the fixed mode, the Matter Engine updates at a fixed delta value every frame (which is what Phaser has used since the first version). In variable mode, the delta will be smoothed and capped each frame to keep the simulation constant, but at the cost of determininism. You can configure the runner by setting the `runner` property in the Matter Config object, both of which are fully covered with JSDocs. As of 3.22 the runner is now used by default in variable (non-fixed) mode. If you wish to return to the previous behavior, set `runner: { isFixed: true }`. +* `Body.onCollideCallback` is a new Matter Body property that can point to a callback to invoke when the body starts colliding. +* `Body.onCollideEndCallback` is a new Matter Body property that can point to a callback to invoke when the body stops colliding. +* `Body.onCollideActiveCallback` is a new Matter Body property that can point to a callback to invoke for the duration the body is colliding. +* `Body.onCollideWith` is a new Matter Body property that holds a mapping between bodies and collision callbacks. +* `MatterGameObject.setOnCollide` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body collides with another. +* `MatterGameObject.setOnCollideEnd` is a new method available on any Matter Game Object, that sets a callback that is invoked when the body stops colliding. +* `MatterGameObject.setOnCollideActive` is a new method available on any Matter Game Object, that sets a callback which is invoked for the duration of the bodies collision with another. +* `MatterGameObject.setOnCollideWith` is a new method available on any Matter Game Object, that allows you to set a callback to be invoked whenever the body collides with another specific body, or array of bodies. +* `Body.gravityScale` is a new vector property that allows you to scale the effect of world gravity on a specific Body. +* `MatterPhysics._tempVec2` is a new private internal vector used for velocity and force calculations. +* `MatterPhysics.setVelocity` is a new method that will set both the horizontal and vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.setVelocityX` is a new method that will set the horizontal linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.setVelocityY` is a new method that will set the vertical linear velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.setAngularVelocity` is a new method that will set the angular velocity of the given physics bodies. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.applyForce` is a new method that applies a force to a body, at the bodies current position, including resulting torque. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.applyForceFromPosition` is a new method that applies a force to a body from the given world position, including resulting torque. If no angle is given, the current body angle is used. This can be used on all Matter bodies, not just those created via the factory. +* `MatterPhysics.fromSVG` is a new method that allows you to create a Body from the given SVG path data. +* The `Matter.Factory.velocity` method has been removed. Please now use `MatterPhysics.setVelocity` instead. +* The `Matter.Factory.angularVelocity` method has been removed. Please now use `MatterPhysics.setAngularVelocity` instead. +* The `Matter.Factory.force` method has been removed. Please now use `MatterPhysics.applyForce` instead. +* `MatterBodyConfig` is a new type def that contains all of the Body configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterBodyRenderConfig` is a new type def that contains all of the Body debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterChamferConfig` is a new type def that contains all of the chamfer configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterCollisionFilter` is a new type def that contains all of the collision configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterConstraintConfig` is a new type def that contains all of the constraint configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterConstraintRenderConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterSetBodyConfig` is a new type def that contains all of the Constraint debug rendering configuration properties. This is now used through-out the JSDocs to aid in code-completion. +* `MatterPhysics.getConstraintLength` is a new method that will return the length of the given constraint, as this is something you cannot get from the constraint properties directly. +* `MatterPhysics.alignBody` is a new method that will align a Body, or Matter Game Object, against the given coordinates, using the given alignment constant. For example, this allows you to easily position a body to the `BOTTOM_LEFT`, or `TOP_CENTER`, or a coordinate. Alignment is based on the body bounds. +* `Phaser.Types.Physics.Matter.MatterBody` is a new type def that contains all of the valid Matter Body objects. This is now used through-out the JSDocs to aid in code-completion. +* `Matter.BodyBounds` is a new class that contains methods to help you extract 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 new class via `this.matter.bodyBounds`. +* The method signature for `Matter.PhysicsEditorParser.parseBody` has changed. It now takes `(x, y, config, options)` and no longer has `width` and `height` parameters. Please see the updated documentation for more details if you were calling this method directly. +* `MatterPhysics.fromPhysicsEditor` is a new method that allows you to create a Matter Body based on the given PhysicsEditor shape data. Previously, you could only using PhysicsEditor data with a Matter Game Object, but now you can create a body directly using it. +* `Matter.PhysicsJSONParser` is a new parser that will create Matter bodies from JSON physics data files. Currently onto the Phaser Physics Tracer app exports in this format, but details are published in the JSDocs, so any app can do so. +* `Matter.Factory.fromJSON` is a new method that will create a body from a JSON physics data file. +* The `SetBody` Matter component can now automatically use shapes created in the Phaser Physics Tracer App in the JSON data format. +* `Matter.Components.Sleep.setToSleep` is a new method available on any Matter Game Object that will send the body to sleep, if Engine sleeping has been enabled. +* `Matter.Components.Sleep.setAwake` is a new method available on any Matter Game Object that will awake a body from sleep, if Engine sleeping has been enabled. + +#### Matter Physics Updates + +* The `debug` property in the Matter World Config is now a `MatterDebugConfig` option instead of a boolean. However, if a boolean is given, it will use the default debug config values. +* The following `MatterWorldConfig` options have now been removed: `debugShowBody`, `debugShowStaticBody`, `debugBodyColor`, `debugBodyFillColor`, `debugStaticBodyColor`, `debugShowJoint`, `debugJointColor`, `debugWireframes`, `debugShowInternalEdges`, `debugShowConvexHulls`, `debugConvexHullColor` and `debugShowSleeping`. These can all be set via the new `MatterDebugConfig` object instead. +* The object `World.defaults` has been removed. Defaults are now access via `World.debugDefaults`. +* `World.renderBodies` has been rewritten to cache commonly-used values and avoid a situation when a single body would be rendered twice. +* The private method `World.renderConvexHulls` has been removed as it's no longer used internally. +* The private method `World.renderWireframes` has been removed as it's no longer used internally. +* The method `World.fromPath` has been removed. This was never used internally and you can get the same results by calling `Vertices.fromPath`. +* The `World.setBounds` argument `thickness` now defaults to 64, not 128, to keep it matching the Matter World Config. +* The `Body.render.fillStyle` property that existed on the Matter Body object has been removed and replaced with `fillColor`. +* The `Body.render.strokeStyle` property that existed on the Matter Body object has been removed and replaced with `lineColor`. +* `Matter.Body.render.sprite.xOffset` and `yOffset` are no longer set to anything when a Body is created. They are left as zero, or you can override them in the Body config, in which case the value is added to the sprite origin offset during a call to `setExistingBody`. +* The `Matter.Mass.centerOfMass` component property now returns the pre-calculated Body `centerOfMass` property, which is much more accurate than the previous bounds offset value. +* `Matter.setExistingBody`, which is called interally whenever a Body is set on a Game Object, now uses the new `centerOffset` values to ensure that the texture frame is correctly centered based on the center of mass, not the Body bounds, allowing for much more accurate body to texture mapping with complex multi-part compound bodies. +* The `Matter.PhysicsEditorParser` has been updated so it no longer needs to set the render offsets, and instead uses the center of mass values. +* If the `Matter.Body` config doesn't contain a `position` property, it will now default to using `Vertices.centre(body.vertices)` as the position. In most cases, this is what you need, so it saves having to pass it in the config object. +* Bumped Matter Plugin versions to avoid console logs from Common.info and Common.warn. +* `PhysicsEditorParser.parseVertices` now uses `Bodies.flagCoincidentParts` to avoid duplicating code. +* `MatterGameObject` has a new optional boolean constructor parameter `addToWorld` which lets you control if the Body should be added to the world or not. Useful for toggling off should you be merging pre-existing bodies with Game Objects. +* The `Matter.SetBody.setExistingBody` function, which all Matter Game Objects have, has a new parameter `addToWorld` which allows you to control when the body is added to the Matter world should you not require it immediately. It will also only add the body to the world if it doesn't already exist within it, or any of its composites. +* `PointerConstraint` has been recoded so that when pressed down, it only polls the World for a body hit test during the next game update. This stops it coming out of sync with the state of the world. Use of the constraint remains the same as before. +* You can now set `gravity: false` in your Matter Config and it will reset gravity from the defaults to zero. +* The internal Matter `Composite.setModified` function will now emit a `compositeModified` event, which the Matter World listens for, if debug draw is enabled, so it can update the composite children render styles. +* `Matter.PhysicsEditorParser.parseBody` can now accept a MatterBodyConfig file as a 4th parameter. This allows you to set Body properties when the body is created, overriding whatever values may have been set in the PhysicsEditor JSON. + +#### Matter Physics Bug Fixes + +* Due to the rewrite of the debug rendering, it is now possible to render _just_ constraints, where-as before this was only possible if bodies were being rendered as well. Fix #4880 (thanks @roberto257) +* `Matter.PhysicsEditorParser` had a bug where it would allow fixtures with non-clockwise sorted vertices through, which would break pointer constraint interaction with these bodies. The parser now sorts the vertices properly. Fix #4261 (thanks @Sanchez3) + +### New Features + +* `TimeStep.smoothStep` is a new boolean property that controls if any delta smoothing takes place during the game step. Delta smoothing has been enabled in Phaser since the first version and helps avoid delta spikes and dips, especially after loss of focus. However, you can now easily toggle if this happens via this property and the corresponding `FPSConfig` property. +* `Phaser.Math.Distance.BetweenPoints` is a new function that will return the distance between two Vector2-like objects (thanks @samme) +* `Phaser.Math.Distance.BetweenPointsSquared` is a new function that will return the squared distance between two Vector2-like objects (thanks @samme) +* `Phaser.Math.Distance.Chebyshev` is a new function that will return the Chebyshev (or chessboard) distance between two Vector2-like objects (thanks @samme) +* `Phaser.Math.Distance.Snake` is a new function that will return the rectilinear distance between two Vector2-like objects (thanks @samme) +* `ParticleEmitter.setTint` is a new method that will set the tint of emitted particles for the given Emitter only (thanks @samme) +* `ParticleEmitter.remove` is a new method that will remove the Emitter from its Emitter Manager (thanks @samme) +* `ParticleEmitterManager.removeEmitter` is a new method that will remove the given emitter from the manager, if the emitter belongs to it (thanks @samme) +* `AlphaSingle` is a new Game Object Component that allows a Game Object to set its alpha values, but only as a single uniform value, not on a per-quad basis. +* `Actions.AlignTo` (in combination with the new `Display.Align.To.QuickSet` function) allows you to align an array of Game Objects so they sit next to each other, one at a time. The first item isn't moved, the second is moved to sit next to the first, and so on. You can align them using any of the alignment constants (thanks @samme) +* `Scene.Systems.getData` is a new method that will return any data that was sent to the Scene by another Scene, i.e. during a `run` or `launch` command. You can access it via `this.sys.getData()` from within your Scene. +* `Group.internalCreateCallback` is a new optional callback that is invoked whenever a child is added to a Group. This is the same as `createCallback` except it's only for use by the parent class, allowing a parent to invoke a creation callback and for you to still provide one via the Group config. +* `Group.internalRemoveCallback` is a new optional callback that is invoked whenever a child is removed from a Group. This is the same as `removeCallback` except it's only for use by the parent class, allowing a parent to invoke a callback and for you to still provide one via the Group config. + +### Updates + +* `Body.deltaXFinal` is a new method on Arcade Physics Bodies that will return the final change in the horizontal position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) +* `Body.deltaYFinal` is a new method on Arcade Physics Bodies that will return the final change in the vertical position of the body, as based on all the steps that took place this frame. This property is calculated during the `postUpdate` phase, so must be listened for accordingly (thanks Bambosh) +* `Body._tx` is a new internal private var, holding the Arcade Physics Body combined total delta x value. +* `Body._ty` is a new internal private var, holding the Arcade Physics Body combined total delta y value. +* `LineCurve.getUtoTmapping` has been updated to return `u` directly to avoid calculations as it's identical to `t` in a Line (thanks @rexrainbow) +* `Curve.getSpacedPoints` will now take an optional array as the 3rd parameter to store the points results in (thanks @rexrainbow) +* Trying to play or resume an audio file with an incorrect key will now throw a runtime error, instead of a console warning (thanks @samme) +* The `Shape` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the shape, rather than a quad alpha, which never worked for Shape objects. +* The `Container` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the container, rather than a quad alpha, which never worked consistently across Container children. Fix #4916 (thanks @laineus) +* The `DOMElement` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. +* The `Graphics` Game Object now uses the AlphaSingle component, allowing you to uniformly set the alpha of the element, rather than a quad alpha, which never worked for these objects. +* `TweenData` has a new property called `previous` which holds the eased property value prior to the update. +* The `TWEEN_UPDATE` event now sends two new parameters to the handler: `current` and `previous` which contain the current and previous property values. +* During `collideSpriteVsGroup` checks it will now skip bodies that are disabled to save doing a `contains` test (thanks @samme) +* `Display.Align.In.QuickSet` now accepts `LEFT_BOTTOM` as `BOTTOM_LEFT`, `LEFT_TOP` as `TOP_LEFT`, `RIGHT_BOTTOM` as `BOTTOM_RIGHT` and `RIGHT_TOP` as `TOP_RIGHT`. Fix #4927 (thanks @zaniar) +* `PhysicsGroup` now uses the new `internalCreateCallback` and `internalRemoveCallback` to handle its body creation and destruction, allowing you to use your own `createCallback` and `removeCallback` as defined in the Group config. Fix #4420 #4657 #4822 (thanks @S4n60w3n @kendistiller @scrubperson) +* `DOMElement` has a new private method `handleSceneEvent` which will handle toggling the display setting of the element when a Scene sleeps and wakes. A DOM Element will now listen for the Scene sleep and wake events. These event listeners are removed in the `preDestroy` method. +* A `DOMElement` will now set the display mode to 'none' during its render if the Scene in which it belongs is no longer visible. + +### Bug Fixes + +* BitmapText with a `maxWidth` set wouldn't update the text correctly if it was modified post-creation. You can now update the text and/or width independantly and it'll update correctly. Fix #4881 (thanks @oxguy3) +* Text objects will no longer add any white-space when word-wrapping if the last line is only one word long. Fix #4867 (thanks @gaamoo @rexrainbow) +* When `Game.destroy` is running, Scenes are now destroyed _before_ plugins, avoiding bugs when closing down plugins and deleting Render Textures. Fix #4849 #4876 (thanks @rexrainbow @siyuanqiao) +* The `Mesh` and `Quad` Game Objects have had the `GetBounds` component removed as it cannot operate on a Mesh as they don't have origins. Fix #4902 (thanks @samme) +* Setting `lineSpacing` in the Text Game Object style config would set the value but not apply it to the Text, leaving you to call `updateText` yourself. If set, it's now applied on instantiation. Fix #4901 (thanks @FantaZZ) +* External calls to the Fullscreen API using `element.requestFullscreen()` would be blocked by the Scale Manager. The Scale Manager will no longer call `stopFullScreen` should it be triggered outside of Phaser (thanks @AdamXA) +* The `Tilemaps.Tile.tint` property wasn't working correctly as it expected the colors in the wrong order (BGR instead of RGB). It will now expect them in the correct RGB order (thanks @Aedalus @plissken2013es) +* The `ScaleManager.destroy` method wasn't being called when the Game `DESTROY` event was dispatched, causing minor gc to build up. The destroy method will now be called properly on game destruction. Fix #4944 (thanks @sunshineuoow) +* `FacebookInstantGamesPlugin.showAd` and `showVideo` will now break out of the ad iteration search once a valid ad has been found and called. Previously, it would carry on interating if the async didn't complete quickly. Fix #4888 (thanks @east62687) +* When playing an Animation, if you were to play another, then pause it, then play another the internal `_paused` wouldn't get reset, preventing you from them pausing the animations from that point on. You can now play and pause animations at will. Fix #4835 (thanks @murteira) +* In `Actions.GridAlign` if you set `width` to -1 it would align the items vertically, instead of horizontally. It now aligns them horizontally if `width` is set, or vertically if `height` is set. Fix #4899 (thanks @BenjaVR) +* A `PathFollower` with a very short duration would often not end in the correct place, which is the very end of the Path, due to the tween handling the movement not running one final update when the tween was complete. It will now always end at the final point of the path, no matter how short the duration. Fix #4950 (thanks @bramp) +* A `DOMElement` would still remain visible even if the Scene in which it belongs to was sent to sleep. A sleeping Scene shouldn't render anything. DOM Elements will now respond to sleep and wake events from their parent Scene. Fix #4870 (thanks @peonmodel) +* If a config object was passed to `MultiAtlasFile` it expected the atlas URL to be in the `url` property, however the docs and file config expected it in `atlasURL`. You can now use either of these properties to declare the url. Fix #4815 (thanks @xense) + +### Examples, Documentation and TypeScript + +My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs: + +@fselcukcan Bambosh @louisth @hexus @javigaralva @samme @BeLi4L @jcyuan @javigaralva @T-Grave @bramp @Chnapy @dranitski @RollinSafary @xense + +The Matter TypeScript defs have been updated to include lots of missing classes, removed some redundant elements and general fixes. The Phaser TypeScript defs now reference the Matter defs directly and no longer try to parse them from the JSDocs. This allows the `MatterJS` namespace to work in TypeScript projects without any compilation warnings. + +The Spine Plugin now has new TypeScript defs in the `types` folder thanks to @supertommy + +Please see the complete [Change Log](https://github.com/photonstorm/phaser/blob/master/CHANGELOG.md) for previous releases. + +![Contributing](https://phaser.io/images/github/div-contributing.png "Contributing") + + +The [Contributors Guide][contribute] contains full details on how to help with Phaser development. The main points are: + +- Found a bug? Report it on [GitHub Issues][issues] and include a code sample. Please state which version of Phaser you are using! This is vitally important. + +- Before submitting a Pull Request run your code through [ES Lint](https://eslint.org/) using our [config](https://github.com/photonstorm/phaser/blob/master/.eslintrc.json) and respect our [Editor Config](https://github.com/photonstorm/phaser/blob/master/.editorconfig). + +- Before contributing read the [code of conduct](https://github.com/photonstorm/phaser/blob/master/.github/CODE_OF_CONDUCT.md). + +Written something cool in Phaser? Please tell us about it in the [forum][forum], or email support@phaser.io + +![Created by](https://phaser.io/images/github/div-created-by.png "Created by") + +Phaser is a [Photon Storm](http://www.photonstorm.com) production. + +![storm](https://www.phaser.io/images/github/photonstorm-x2.png) + +Created by [Richard Davey](mailto:rich@photonstorm.com). Powered by coffee, anime, pixels and love. + +The Phaser logo and characters are © 2019 Photon Storm Limited. + +All rights reserved. + +"Above all, video games are meant to be just one thing: fun. Fun for everyone." - Satoru Iwata + +[get-js]: https://github.com/photonstorm/phaser/releases/download/v3.22.0/phaser.js +[get-minjs]: https://github.com/photonstorm/phaser/releases/download/v3.22.0/phaser.min.js +[clone-http]: https://github.com/photonstorm/phaser.git +[clone-ssh]: git@github.com:photonstorm/phaser.git +[clone-ghwin]: github-windows://openRepo/https://github.com/photonstorm/phaser +[clone-ghmac]: github-mac://openRepo/https://github.com/photonstorm/phaser +[phaser]: https://github.com/photonstorm/phaser +[issues]: https://github.com/photonstorm/phaser/issues +[examples]: https://github.com/photonstorm/phaser3-examples +[contribute]: https://github.com/photonstorm/phaser/blob/master/.github/CONTRIBUTING.md +[forum]: https://phaser.discourse.group/ diff --git a/dist/phaser-arcade-physics.js b/dist/phaser-arcade-physics.js index fb21c87d1..ce25cd167 100644 --- a/dist/phaser-arcade-physics.js +++ b/dist/phaser-arcade-physics.js @@ -91,7 +91,7 @@ return /******/ (function(modules) { // webpackBootstrap /******/ /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 1428); +/******/ return __webpack_require__(__webpack_require__.s = 1453); /******/ }) /************************************************************************/ /******/ ([ @@ -1161,8 +1161,8 @@ module.exports = Point; */ var Class = __webpack_require__(0); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -1566,340 +1566,6 @@ module.exports = FileTypesManager; /***/ }), /* 9 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.WebGL.Utils - * @since 3.0.0 - */ -module.exports = { - - /** - * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats - * @since 3.0.0 - * - * @param {number} r - Red component in a range from 0.0 to 1.0 - * @param {number} g - Green component in a range from 0.0 to 1.0 - * @param {number} b - Blue component in a range from 0.0 to 1.0 - * @param {number} a - Alpha component in a range from 0.0 to 1.0 - * - * @return {number} The packed RGBA values as a Uint32. - */ - getTintFromFloats: function (r, g, b, a) - { - var ur = ((r * 255.0)|0) & 0xFF; - var ug = ((g * 255.0)|0) & 0xFF; - var ub = ((b * 255.0)|0) & 0xFF; - var ua = ((a * 255.0)|0) & 0xFF; - - return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; - }, - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha - * @since 3.0.0 - * - * @param {number} rgb - Uint24 representing RGB components - * @param {number} a - Float32 representing Alpha component - * - * @return {number} Packed RGBA as Uint32 - */ - getTintAppendFloatAlpha: function (rgb, a) - { - var ua = ((a * 255.0)|0) & 0xFF; - return ((ua << 24) | rgb) >>> 0; - }, - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a - * swizzled Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap - * @since 3.0.0 - * - * @param {number} rgb - Uint24 representing RGB components - * @param {number} a - Float32 representing Alpha component - * - * @return {number} Packed RGBA as Uint32 - */ - getTintAppendFloatAlphaAndSwap: function (rgb, a) - { - var ur = ((rgb >> 16)|0) & 0xff; - var ug = ((rgb >> 8)|0) & 0xff; - var ub = (rgb|0) & 0xff; - var ua = ((a * 255.0)|0) & 0xFF; - - return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; - }, - - /** - * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 - * - * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB - * @since 3.0.0 - * - * @param {number} rgb - RGB packed as a Uint24 - * - * @return {array} Array of floats representing each component as a float - */ - getFloatsFromUintRGB: function (rgb) - { - var ur = ((rgb >> 16)|0) & 0xff; - var ug = ((rgb >> 8)|0) & 0xff; - var ub = (rgb|0) & 0xff; - - return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; - }, - - /** - * Counts how many attributes of 32 bits a vertex has - * - * @function Phaser.Renderer.WebGL.Utils.getComponentCount - * @since 3.0.0 - * - * @param {array} attributes - Array of attributes - * @param {WebGLRenderingContext} glContext - WebGLContext used for check types - * - * @return {number} Count of 32 bit attributes in vertex - */ - getComponentCount: function (attributes, glContext) - { - var count = 0; - - for (var index = 0; index < attributes.length; ++index) - { - var element = attributes[index]; - - if (element.type === glContext.FLOAT) - { - count += element.size; - } - else - { - count += 1; // We'll force any other type to be 32 bit. for now - } - } - - return count; - } - -}; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Global constants. - * - * @ignore - */ - -var CONST = { - - /** - * Phaser Release Version - * - * @name Phaser.VERSION - * @const - * @type {string} - * @since 3.0.0 - */ - VERSION: '3.23.0-beta1', - - BlendModes: __webpack_require__(52), - - ScaleModes: __webpack_require__(229), - - /** - * AUTO Detect Renderer. - * - * @name Phaser.AUTO - * @const - * @type {integer} - * @since 3.0.0 - */ - AUTO: 0, - - /** - * Canvas Renderer. - * - * @name Phaser.CANVAS - * @const - * @type {integer} - * @since 3.0.0 - */ - CANVAS: 1, - - /** - * WebGL Renderer. - * - * @name Phaser.WEBGL - * @const - * @type {integer} - * @since 3.0.0 - */ - WEBGL: 2, - - /** - * Headless Renderer. - * - * @name Phaser.HEADLESS - * @const - * @type {integer} - * @since 3.0.0 - */ - HEADLESS: 3, - - /** - * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead - * to help you remember what the value is doing in your code. - * - * @name Phaser.FOREVER - * @const - * @type {integer} - * @since 3.0.0 - */ - FOREVER: -1, - - /** - * Direction constant. - * - * @name Phaser.NONE - * @const - * @type {integer} - * @since 3.0.0 - */ - NONE: 4, - - /** - * Direction constant. - * - * @name Phaser.UP - * @const - * @type {integer} - * @since 3.0.0 - */ - UP: 5, - - /** - * Direction constant. - * - * @name Phaser.DOWN - * @const - * @type {integer} - * @since 3.0.0 - */ - DOWN: 6, - - /** - * Direction constant. - * - * @name Phaser.LEFT - * @const - * @type {integer} - * @since 3.0.0 - */ - LEFT: 7, - - /** - * Direction constant. - * - * @name Phaser.RIGHT - * @const - * @type {integer} - * @since 3.0.0 - */ - RIGHT: 8, - - - /** - * Orientation constant. - * - * @name Phaser.ORTHOGONAL - * @const - * @type {integer} - * @since 3.2.2 - */ - ORTHOGONAL: 0, - - - /** - * Orientation constant. - * - * @name Phaser.ISOMETRIC - * @const - * @type {integer} - * @since 3.2.2 - */ - ISOMETRIC: 1, - - - /** - * Orientation constant. - * - * @name Phaser.STAGGERED - * @const - * @type {integer} - * @since 3.2.2 - */ - STAGGERED: 2, - - /** - * Orientation constant. - * - * @name Phaser.HEXAGONAL - * @const - * @type {integer} - * @since 3.2.2 - */ - HEXAGONAL: 3, - - fromOrientationString: function (orientation) - { - var constor = CONST.ORTHOGONAL; - - if (orientation === 'isometric') - { - constor = CONST.ISOMETRIC; - } - else if (orientation === 'staggered') - { - constor = CONST.STAGGERED; - } - else if (orientation === 'hexagonal') - { - constor = CONST.HEXAGONAL; - } - return constor; - } -}; - -module.exports = CONST; - - -/***/ }), -/* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2242,49 +1908,142 @@ if (true) { /***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { +/* 10 */ +/***/ (function(module, exports) { /** * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** - * @namespace Phaser.GameObjects.Components + * @namespace Phaser.Renderer.WebGL.Utils + * @since 3.0.0 */ - module.exports = { - Alpha: __webpack_require__(528), - AlphaSingle: __webpack_require__(264), - Animation: __webpack_require__(499), - BlendMode: __webpack_require__(267), - ComputedSize: __webpack_require__(547), - Crop: __webpack_require__(548), - Depth: __webpack_require__(268), - Flip: __webpack_require__(549), - GetBounds: __webpack_require__(550), - Mask: __webpack_require__(272), - Origin: __webpack_require__(567), - PathFollower: __webpack_require__(568), - Pipeline: __webpack_require__(150), - ScrollFactor: __webpack_require__(275), - Size: __webpack_require__(569), - Texture: __webpack_require__(570), - TextureCrop: __webpack_require__(571), - Tint: __webpack_require__(572), - ToJSON: __webpack_require__(276), - Transform: __webpack_require__(277), - TransformMatrix: __webpack_require__(30), - Visible: __webpack_require__(278) + /** + * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats + * @since 3.0.0 + * + * @param {number} r - Red component in a range from 0.0 to 1.0 + * @param {number} g - Green component in a range from 0.0 to 1.0 + * @param {number} b - Blue component in a range from 0.0 to 1.0 + * @param {number} a - Alpha component in a range from 0.0 to 1.0 + * + * @return {number} [description] + */ + getTintFromFloats: function (r, g, b, a) + { + var ur = ((r * 255.0)|0) & 0xFF; + var ug = ((g * 255.0)|0) & 0xFF; + var ub = ((b * 255.0)|0) & 0xFF; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlpha: function (rgb, a) + { + var ua = ((a * 255.0)|0) & 0xFF; + return ((ua << 24) | rgb) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a + * swizzled Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlphaAndSwap: function (rgb, a) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; + }, + + /** + * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 + * + * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB + * @since 3.0.0 + * + * @param {number} rgb - RGB packed as a Uint24 + * + * @return {array} Array of floats representing each component as a float + */ + getFloatsFromUintRGB: function (rgb) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + + return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; + }, + + /** + * Counts how many attributes of 32 bits a vertex has + * + * @function Phaser.Renderer.WebGL.Utils.getComponentCount + * @since 3.0.0 + * + * @param {array} attributes - Array of attributes + * @param {WebGLRenderingContext} glContext - WebGLContext used for check types + * + * @return {number} Count of 32 bit attributes in vertex + */ + getComponentCount: function (attributes, glContext) + { + var count = 0; + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + + if (element.type === glContext.FLOAT) + { + count += element.size; + } + else + { + count += 1; // We'll force any other type to be 32 bit. for now + } + } + + return count; + } }; /***/ }), -/* 13 */ +/* 11 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -2295,11 +2054,11 @@ module.exports = { var Class = __webpack_require__(0); var Contains = __webpack_require__(47); -var GetPoint = __webpack_require__(146); -var GetPoints = __webpack_require__(269); +var GetPoint = __webpack_require__(149); +var GetPoints = __webpack_require__(271); var GEOM_CONST = __webpack_require__(46); var Line = __webpack_require__(56); -var Random = __webpack_require__(149); +var Random = __webpack_require__(152); /** * @classdesc @@ -2794,6 +2553,140 @@ var Rectangle = new Class({ module.exports = Rectangle; +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Components + */ + +module.exports = { + + Alpha: __webpack_require__(527), + AlphaSingle: __webpack_require__(266), + Animation: __webpack_require__(498), + BlendMode: __webpack_require__(269), + ComputedSize: __webpack_require__(546), + Crop: __webpack_require__(547), + Depth: __webpack_require__(270), + Flip: __webpack_require__(548), + GetBounds: __webpack_require__(549), + Mask: __webpack_require__(274), + Origin: __webpack_require__(566), + PathFollower: __webpack_require__(567), + Pipeline: __webpack_require__(153), + ScrollFactor: __webpack_require__(277), + Size: __webpack_require__(568), + Texture: __webpack_require__(569), + TextureCrop: __webpack_require__(570), + Tint: __webpack_require__(571), + ToJSON: __webpack_require__(278), + Transform: __webpack_require__(279), + TransformMatrix: __webpack_require__(32), + Visible: __webpack_require__(280) + +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = { + + /** + * The value of PI * 2. + * + * @name Phaser.Math.PI2 + * @type {number} + * @since 3.0.0 + */ + PI2: Math.PI * 2, + + /** + * The value of PI * 0.5. + * + * @name Phaser.Math.TAU + * @type {number} + * @since 3.0.0 + */ + TAU: Math.PI * 0.5, + + /** + * An epsilon value (1.0e-6) + * + * @name Phaser.Math.EPSILON + * @type {number} + * @since 3.0.0 + */ + EPSILON: 1.0e-6, + + /** + * For converting degrees to radians (PI / 180) + * + * @name Phaser.Math.DEG_TO_RAD + * @type {number} + * @since 3.0.0 + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * For converting radians to degrees (180 / PI) + * + * @name Phaser.Math.RAD_TO_DEG + * @type {number} + * @since 3.0.0 + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * An instance of the Random Number Generator. + * This is not set until the Game boots. + * + * @name Phaser.Math.RND + * @type {Phaser.Math.RandomDataGenerator} + * @since 3.0.0 + */ + RND: null, + + /** + * The minimum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MIN_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, + + /** + * The maximum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MAX_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 + +}; + +module.exports = MATH_CONST; + + /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { @@ -2805,10 +2698,10 @@ module.exports = Rectangle; */ var Class = __webpack_require__(0); -var ComponentsToJSON = __webpack_require__(276); -var DataManager = __webpack_require__(109); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(88); +var ComponentsToJSON = __webpack_require__(278); +var DataManager = __webpack_require__(113); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(90); /** * @classdesc @@ -2966,10 +2859,10 @@ var GameObject = new Class({ this.input = null; /** - * If this Game Object is enabled for Arcade or Matter Physics then this property will contain a reference to a Physics Body. + * If this Game Object is enabled for physics then this property will contain a reference to a Physics Body. * * @name Phaser.GameObjects.GameObject#body - * @type {?(object|Phaser.Physics.Arcade.Body|MatterJS.BodyType)} + * @type {?(object|Phaser.Physics.Arcade.Body|Phaser.Physics.Impact.Body)} * @default null * @since 3.0.0 */ @@ -3445,7 +3338,7 @@ module.exports = GameObject; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH = __webpack_require__(165); +var MATH = __webpack_require__(168); var GetValue = __webpack_require__(6); /** @@ -3524,98 +3417,6 @@ module.exports = GetAdvancedValue; /***/ }), /* 16 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = { - - /** - * The value of PI * 2. - * - * @name Phaser.Math.PI2 - * @type {number} - * @since 3.0.0 - */ - PI2: Math.PI * 2, - - /** - * The value of PI * 0.5. - * - * @name Phaser.Math.TAU - * @type {number} - * @since 3.0.0 - */ - TAU: Math.PI * 0.5, - - /** - * An epsilon value (1.0e-6) - * - * @name Phaser.Math.EPSILON - * @type {number} - * @since 3.0.0 - */ - EPSILON: 1.0e-6, - - /** - * For converting degrees to radians (PI / 180) - * - * @name Phaser.Math.DEG_TO_RAD - * @type {number} - * @since 3.0.0 - */ - DEG_TO_RAD: Math.PI / 180, - - /** - * For converting radians to degrees (180 / PI) - * - * @name Phaser.Math.RAD_TO_DEG - * @type {number} - * @since 3.0.0 - */ - RAD_TO_DEG: 180 / Math.PI, - - /** - * An instance of the Random Number Generator. - * This is not set until the Game boots. - * - * @name Phaser.Math.RND - * @type {Phaser.Math.RandomDataGenerator} - * @since 3.0.0 - */ - RND: null, - - /** - * The minimum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - * - * @name Phaser.Math.MIN_SAFE_INTEGER - * @type {number} - * @since 3.21.0 - */ - MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, - - /** - * The maximum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - * - * @name Phaser.Math.MAX_SAFE_INTEGER - * @type {number} - * @since 3.21.0 - */ - MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 - -}; - -module.exports = MATH_CONST; - - -/***/ }), -/* 17 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -3625,8 +3426,8 @@ module.exports = MATH_CONST; */ var Class = __webpack_require__(0); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -3783,7 +3584,7 @@ module.exports = GameObjectCreator; /***/ }), -/* 18 */ +/* 17 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -3882,7 +3683,7 @@ module.exports = Extend; /***/ }), -/* 19 */ +/* 18 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -3897,22 +3698,61 @@ module.exports = Extend; module.exports = { - BLUR: __webpack_require__(551), - BOOT: __webpack_require__(552), - CONTEXT_LOST: __webpack_require__(553), - CONTEXT_RESTORED: __webpack_require__(554), - DESTROY: __webpack_require__(555), - FOCUS: __webpack_require__(556), - HIDDEN: __webpack_require__(557), - PAUSE: __webpack_require__(558), - POST_RENDER: __webpack_require__(559), - POST_STEP: __webpack_require__(560), - PRE_RENDER: __webpack_require__(561), - PRE_STEP: __webpack_require__(562), - READY: __webpack_require__(563), - RESUME: __webpack_require__(564), - STEP: __webpack_require__(565), - VISIBLE: __webpack_require__(566) + BLUR: __webpack_require__(550), + BOOT: __webpack_require__(551), + CONTEXT_LOST: __webpack_require__(552), + CONTEXT_RESTORED: __webpack_require__(553), + DESTROY: __webpack_require__(554), + FOCUS: __webpack_require__(555), + HIDDEN: __webpack_require__(556), + PAUSE: __webpack_require__(557), + POST_RENDER: __webpack_require__(558), + POST_STEP: __webpack_require__(559), + PRE_RENDER: __webpack_require__(560), + PRE_STEP: __webpack_require__(561), + READY: __webpack_require__(562), + RESUME: __webpack_require__(563), + STEP: __webpack_require__(564), + VISIBLE: __webpack_require__(565) + +}; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Scenes.Events + */ + +module.exports = { + + BOOT: __webpack_require__(700), + CREATE: __webpack_require__(701), + DESTROY: __webpack_require__(702), + PAUSE: __webpack_require__(703), + POST_UPDATE: __webpack_require__(704), + PRE_UPDATE: __webpack_require__(705), + READY: __webpack_require__(706), + RENDER: __webpack_require__(707), + RESUME: __webpack_require__(708), + SHUTDOWN: __webpack_require__(709), + SLEEP: __webpack_require__(710), + START: __webpack_require__(711), + TRANSITION_COMPLETE: __webpack_require__(712), + TRANSITION_INIT: __webpack_require__(713), + TRANSITION_OUT: __webpack_require__(714), + TRANSITION_START: __webpack_require__(715), + TRANSITION_WAKE: __webpack_require__(716), + UPDATE: __webpack_require__(717), + WAKE: __webpack_require__(718) }; @@ -4081,12 +3921,12 @@ module.exports = FILE_CONST; var Class = __webpack_require__(0); var CONST = __webpack_require__(20); -var Events = __webpack_require__(80); +var Events = __webpack_require__(81); var GetFastValue = __webpack_require__(2); -var GetURL = __webpack_require__(132); -var MergeXHRSettings = __webpack_require__(210); -var XHRLoader = __webpack_require__(448); -var XHRSettings = __webpack_require__(133); +var GetURL = __webpack_require__(134); +var MergeXHRSettings = __webpack_require__(212); +var XHRLoader = __webpack_require__(447); +var XHRSettings = __webpack_require__(135); /** * @classdesc @@ -4612,45 +4452,6 @@ module.exports = File; /***/ }), /* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Scenes.Events - */ - -module.exports = { - - BOOT: __webpack_require__(701), - CREATE: __webpack_require__(702), - DESTROY: __webpack_require__(703), - PAUSE: __webpack_require__(704), - POST_UPDATE: __webpack_require__(705), - PRE_UPDATE: __webpack_require__(706), - READY: __webpack_require__(707), - RENDER: __webpack_require__(708), - RESUME: __webpack_require__(709), - SHUTDOWN: __webpack_require__(710), - SLEEP: __webpack_require__(711), - START: __webpack_require__(712), - TRANSITION_COMPLETE: __webpack_require__(713), - TRANSITION_INIT: __webpack_require__(714), - TRANSITION_OUT: __webpack_require__(715), - TRANSITION_START: __webpack_require__(716), - TRANSITION_WAKE: __webpack_require__(717), - UPDATE: __webpack_require__(718), - WAKE: __webpack_require__(719) - -}; - - -/***/ }), -/* 23 */ /***/ (function(module, exports) { /** @@ -4680,7 +4481,7 @@ module.exports = Clamp; /***/ }), -/* 24 */ +/* 23 */ /***/ (function(module, exports) { /** @@ -4889,7 +4690,7 @@ module.exports = PluginCache; /***/ }), -/* 25 */ +/* 24 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -4973,7 +4774,7 @@ module.exports = GetTilesWithin; /***/ }), -/* 26 */ +/* 25 */ /***/ (function(module, exports) { /** @@ -5040,7 +4841,7 @@ module.exports = PropertyValueSet; /***/ }), -/* 27 */ +/* 26 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -5049,8 +4850,8 @@ module.exports = PropertyValueSet; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var Smoothing = __webpack_require__(161); +var CONST = __webpack_require__(29); +var Smoothing = __webpack_require__(164); // The pool into which the canvas elements are placed. var pool = []; @@ -5300,6 +5101,94 @@ var CanvasPool = function () module.exports = CanvasPool(); +/***/ }), +/* 27 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. + * + * 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`. + */ +var SetTransform = function (renderer, ctx, src, camera, parentMatrix) +{ + var alpha = camera.alpha * src.alpha; + + if (alpha <= 0) + { + // Nothing to see, so don't waste time calculating stuff + return false; + } + + var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); + var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + var calcMatrix = renderer._tempMatrix3; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + gameObjectMatrix.e = src.x; + gameObjectMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + else + { + gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; + gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + + // Blend Mode + ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + + // Alpha + ctx.globalAlpha = alpha; + + ctx.save(); + + calcMatrix.setToContext(ctx); + + ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); + + return true; +}; + +module.exports = SetTransform; + + /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { @@ -5430,7 +5319,7 @@ module.exports = BuildGameObject; /***/ }), /* 29 */ -/***/ (function(module, exports) { +/***/ (function(module, exports, __webpack_require__) { /** * @author Richard Davey @@ -5439,81 +5328,131 @@ module.exports = BuildGameObject; */ /** - * 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: + * Global constants. * - * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. - * - * 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`. + * @ignore */ -var SetTransform = function (renderer, ctx, src, camera, parentMatrix) -{ - var alpha = camera.alpha * src.alpha; - if (alpha <= 0) - { - // Nothing to see, so don't waste time calculating stuff - return false; - } +var CONST = { - var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); - var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - var calcMatrix = renderer._tempMatrix3; + /** + * Phaser Release Version + * + * @name Phaser.VERSION + * @const + * @type {string} + * @since 3.0.0 + */ + VERSION: '3.22.0', - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + BlendModes: __webpack_require__(52), - // Undo the camera scroll - gameObjectMatrix.e = src.x; - gameObjectMatrix.f = src.y; + ScaleModes: __webpack_require__(231), - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(gameObjectMatrix, calcMatrix); - } - else - { - gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; - gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; + /** + * AUTO Detect Renderer. + * + * @name Phaser.AUTO + * @const + * @type {integer} + * @since 3.0.0 + */ + AUTO: 0, - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(gameObjectMatrix, calcMatrix); - } + /** + * Canvas Renderer. + * + * @name Phaser.CANVAS + * @const + * @type {integer} + * @since 3.0.0 + */ + CANVAS: 1, - // Blend Mode - ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + /** + * WebGL Renderer. + * + * @name Phaser.WEBGL + * @const + * @type {integer} + * @since 3.0.0 + */ + WEBGL: 2, - // Alpha - ctx.globalAlpha = alpha; + /** + * Headless Renderer. + * + * @name Phaser.HEADLESS + * @const + * @type {integer} + * @since 3.0.0 + */ + HEADLESS: 3, - ctx.save(); + /** + * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead + * to help you remember what the value is doing in your code. + * + * @name Phaser.FOREVER + * @const + * @type {integer} + * @since 3.0.0 + */ + FOREVER: -1, - calcMatrix.setToContext(ctx); + /** + * Direction constant. + * + * @name Phaser.NONE + * @const + * @type {integer} + * @since 3.0.0 + */ + NONE: 4, - ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); + /** + * Direction constant. + * + * @name Phaser.UP + * @const + * @type {integer} + * @since 3.0.0 + */ + UP: 5, + + /** + * Direction constant. + * + * @name Phaser.DOWN + * @const + * @type {integer} + * @since 3.0.0 + */ + DOWN: 6, + + /** + * Direction constant. + * + * @name Phaser.LEFT + * @const + * @type {integer} + * @since 3.0.0 + */ + LEFT: 7, + + /** + * Direction constant. + * + * @name Phaser.RIGHT + * @const + * @type {integer} + * @since 3.0.0 + */ + RIGHT: 8 - return true; }; -module.exports = SetTransform; +module.exports = CONST; /***/ }), @@ -5527,7 +5466,362 @@ module.exports = SetTransform; */ var Class = __webpack_require__(0); -var MATH_CONST = __webpack_require__(16); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var Line = __webpack_require__(56); + +/** + * @classdesc + * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. + * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. + * + * @class Shape + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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 {string} [type] - The internal type of the Shape. + * @param {any} [data] - The data of the source shape geometry, if any. + */ +var Shape = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Transform, + Components.Visible + ], + + initialize: + + function Shape (scene, type, data) + { + if (type === undefined) { type = 'Shape'; } + + GameObject.call(this, scene, type); + + /** + * The source Shape data. Typically a geometry object. + * You should not manipulate this directly. + * + * @name Phaser.GameObjects.Shape#data + * @type {any} + * @readonly + * @since 3.13.0 + */ + this.geom = data; + + /** + * Holds the polygon path data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathData + * @type {number[]} + * @readonly + * @since 3.13.0 + */ + this.pathData = []; + + /** + * Holds the earcut polygon path index data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathIndexes + * @type {integer[]} + * @readonly + * @since 3.13.0 + */ + this.pathIndexes = []; + + /** + * The fill color used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillColor + * @type {number} + * @since 3.13.0 + */ + this.fillColor = 0xffffff; + + /** + * The fill alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillAlpha + * @type {number} + * @since 3.13.0 + */ + this.fillAlpha = 1; + + /** + * The stroke color used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeColor + * @type {number} + * @since 3.13.0 + */ + this.strokeColor = 0xffffff; + + /** + * The stroke alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeAlpha + * @type {number} + * @since 3.13.0 + */ + this.strokeAlpha = 1; + + /** + * The stroke line width used by this Shape. + * + * @name Phaser.GameObjects.Shape#lineWidth + * @type {number} + * @since 3.13.0 + */ + this.lineWidth = 1; + + /** + * Controls if this Shape is filled or not. + * Note that some Shapes do not support being filled (such as Line shapes) + * + * @name Phaser.GameObjects.Shape#isFilled + * @type {boolean} + * @since 3.13.0 + */ + this.isFilled = false; + + /** + * Controls if this Shape is stroked or not. + * Note that some Shapes do not support being stroked (such as Iso Box shapes) + * + * @name Phaser.GameObjects.Shape#isStroked + * @type {boolean} + * @since 3.13.0 + */ + this.isStroked = false; + + /** + * Controls if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * @name Phaser.GameObjects.Shape#closePath + * @type {boolean} + * @since 3.13.0 + */ + this.closePath = true; + + /** + * Private internal value. + * A Line used when parsing internal path data to avoid constant object re-creation. + * + * @name Phaser.GameObjects.Curve#_tempLine + * @type {Phaser.Geom.Line} + * @private + * @since 3.13.0 + */ + this._tempLine = new Line(); + + this.initPipeline(); + }, + + /** + * Sets the fill color and alpha for this Shape. + * + * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. + * + * Note that some Shapes do not support fill colors, such as the Line shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setFillStyle + * @since 3.13.0 + * + * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. + * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (color === undefined) + { + this.isFilled = false; + } + else + { + this.fillColor = color; + this.fillAlpha = alpha; + this.isFilled = true; + } + + return this; + }, + + /** + * Sets the stroke color and alpha for this Shape. + * + * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. + * + * Note that some Shapes do not support being stroked, such as the Iso Box shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setStrokeStyle + * @since 3.13.0 + * + * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. + * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. + * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. + * + * @return {this} This Game Object instance. + */ + setStrokeStyle: function (lineWidth, color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (lineWidth === undefined) + { + this.isStroked = false; + } + else + { + this.lineWidth = lineWidth; + this.strokeColor = color; + this.strokeAlpha = alpha; + this.isStroked = true; + } + + return this; + }, + + /** + * Sets if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setClosePath + * @since 3.13.0 + * + * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. + * + * @return {this} This Game Object instance. + */ + setClosePath: function (value) + { + this.closePath = value; + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Shape#preDestroy + * @protected + * @since 3.13.0 + */ + preDestroy: function () + { + this.geom = null; + this._tempLine = null; + this.pathData = []; + this.pathIndexes = []; + } + +}); + +module.exports = Shape; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Formats + */ + +module.exports = { + + /** + * CSV Map Type + * + * @name Phaser.Tilemaps.Formats.CSV + * @type {number} + * @since 3.0.0 + */ + CSV: 0, + + /** + * Tiled JSON Map Type + * + * @name Phaser.Tilemaps.Formats.TILED_JSON + * @type {number} + * @since 3.0.0 + */ + TILED_JSON: 1, + + /** + * 2D Array Map Type + * + * @name Phaser.Tilemaps.Formats.ARRAY_2D + * @type {number} + * @since 3.0.0 + */ + ARRAY_2D: 2, + + /** + * Weltmeister (Impact.js) Map Type + * + * @name Phaser.Tilemaps.Formats.WELTMEISTER + * @type {number} + * @since 3.0.0 + */ + WELTMEISTER: 3 + +}; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var MATH_CONST = __webpack_require__(13); var Vector2 = __webpack_require__(3); /** @@ -5960,7 +6254,7 @@ var TransformMatrix = new Class({ * @param {Phaser.GameObjects.Components.TransformMatrix} rhs - The Matrix to multiply by. * @param {Phaser.GameObjects.Components.TransformMatrix} [out] - An optional Matrix to store the results in. * - * @return {(this|Phaser.GameObjects.Components.TransformMatrix)} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. + * @return {Phaser.GameObjects.Components.TransformMatrix} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. */ multiply: function (rhs, out) { @@ -6485,7 +6779,7 @@ module.exports = TransformMatrix; /***/ }), -/* 31 */ +/* 33 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -6495,310 +6789,10 @@ module.exports = TransformMatrix; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameObject = __webpack_require__(14); -var Line = __webpack_require__(56); - -/** - * @classdesc - * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. - * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. - * - * @class Shape - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.ComputedSize - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @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 {string} [type] - The internal type of the Shape. - * @param {any} [data] - The data of the source shape geometry, if any. - */ -var Shape = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.ComputedSize, - Components.Depth, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Transform, - Components.Visible - ], - - initialize: - - function Shape (scene, type, data) - { - if (type === undefined) { type = 'Shape'; } - - GameObject.call(this, scene, type); - - /** - * The source Shape data. Typically a geometry object. - * You should not manipulate this directly. - * - * @name Phaser.GameObjects.Shape#data - * @type {any} - * @readonly - * @since 3.13.0 - */ - this.geom = data; - - /** - * Holds the polygon path data for filled rendering. - * - * @name Phaser.GameObjects.Shape#pathData - * @type {number[]} - * @readonly - * @since 3.13.0 - */ - this.pathData = []; - - /** - * Holds the earcut polygon path index data for filled rendering. - * - * @name Phaser.GameObjects.Shape#pathIndexes - * @type {integer[]} - * @readonly - * @since 3.13.0 - */ - this.pathIndexes = []; - - /** - * The fill color used by this Shape. - * - * @name Phaser.GameObjects.Shape#fillColor - * @type {number} - * @since 3.13.0 - */ - this.fillColor = 0xffffff; - - /** - * The fill alpha value used by this Shape. - * - * @name Phaser.GameObjects.Shape#fillAlpha - * @type {number} - * @since 3.13.0 - */ - this.fillAlpha = 1; - - /** - * The stroke color used by this Shape. - * - * @name Phaser.GameObjects.Shape#strokeColor - * @type {number} - * @since 3.13.0 - */ - this.strokeColor = 0xffffff; - - /** - * The stroke alpha value used by this Shape. - * - * @name Phaser.GameObjects.Shape#strokeAlpha - * @type {number} - * @since 3.13.0 - */ - this.strokeAlpha = 1; - - /** - * The stroke line width used by this Shape. - * - * @name Phaser.GameObjects.Shape#lineWidth - * @type {number} - * @since 3.13.0 - */ - this.lineWidth = 1; - - /** - * Controls if this Shape is filled or not. - * Note that some Shapes do not support being filled (such as Line shapes) - * - * @name Phaser.GameObjects.Shape#isFilled - * @type {boolean} - * @since 3.13.0 - */ - this.isFilled = false; - - /** - * Controls if this Shape is stroked or not. - * Note that some Shapes do not support being stroked (such as Iso Box shapes) - * - * @name Phaser.GameObjects.Shape#isStroked - * @type {boolean} - * @since 3.13.0 - */ - this.isStroked = false; - - /** - * Controls if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * @name Phaser.GameObjects.Shape#closePath - * @type {boolean} - * @since 3.13.0 - */ - this.closePath = true; - - /** - * Private internal value. - * A Line used when parsing internal path data to avoid constant object re-creation. - * - * @name Phaser.GameObjects.Curve#_tempLine - * @type {Phaser.Geom.Line} - * @private - * @since 3.13.0 - */ - this._tempLine = new Line(); - - this.initPipeline(); - }, - - /** - * Sets the fill color and alpha for this Shape. - * - * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. - * - * Note that some Shapes do not support fill colors, such as the Line shape. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setFillStyle - * @since 3.13.0 - * - * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. - * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. - * - * @return {this} This Game Object instance. - */ - setFillStyle: function (color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - if (color === undefined) - { - this.isFilled = false; - } - else - { - this.fillColor = color; - this.fillAlpha = alpha; - this.isFilled = true; - } - - return this; - }, - - /** - * Sets the stroke color and alpha for this Shape. - * - * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. - * - * Note that some Shapes do not support being stroked, such as the Iso Box shape. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setStrokeStyle - * @since 3.13.0 - * - * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. - * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. - * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. - * - * @return {this} This Game Object instance. - */ - setStrokeStyle: function (lineWidth, color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - if (lineWidth === undefined) - { - this.isStroked = false; - } - else - { - this.lineWidth = lineWidth; - this.strokeColor = color; - this.strokeAlpha = alpha; - this.isStroked = true; - } - - return this; - }, - - /** - * Sets if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setClosePath - * @since 3.13.0 - * - * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. - * - * @return {this} This Game Object instance. - */ - setClosePath: function (value) - { - this.closePath = value; - - return this; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Shape#preDestroy - * @protected - * @since 3.13.0 - */ - preDestroy: function () - { - this.geom = null; - this._tempLine = null; - this.pathData = []; - this.pathIndexes = []; - } - -}); - -module.exports = Shape; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); -var GetColor = __webpack_require__(159); -var GetColor32 = __webpack_require__(290); -var HSVToRGB = __webpack_require__(160); -var RGBToHSV = __webpack_require__(291); +var GetColor = __webpack_require__(162); +var GetColor32 = __webpack_require__(292); +var HSVToRGB = __webpack_require__(163); +var RGBToHSV = __webpack_require__(293); /** * @namespace Phaser.Display.Color @@ -7647,61 +7641,6 @@ var Color = new Class({ module.exports = Color; -/***/ }), -/* 33 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Formats - */ - -module.exports = { - - /** - * CSV Map Type - * - * @name Phaser.Tilemaps.Formats.CSV - * @type {number} - * @since 3.0.0 - */ - CSV: 0, - - /** - * Tiled JSON Map Type - * - * @name Phaser.Tilemaps.Formats.TILED_JSON - * @type {number} - * @since 3.0.0 - */ - TILED_JSON: 1, - - /** - * 2D Array Map Type - * - * @name Phaser.Tilemaps.Formats.ARRAY_2D - * @type {number} - * @since 3.0.0 - */ - ARRAY_2D: 2, - - /** - * Weltmeister (Impact.js) Map Type - * - * @name Phaser.Tilemaps.Formats.WELTMEISTER - * @type {number} - * @since 3.0.0 - */ - WELTMEISTER: 3 - -}; - - /***/ }), /* 34 */ /***/ (function(module, exports) { @@ -7779,7 +7718,7 @@ module.exports = PropertyValueInc; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); +var CONST = __webpack_require__(13); /** * Convert the given angle from degrees, to the equivalent angle in radians. @@ -8212,21 +8151,21 @@ module.exports = Contains; module.exports = { - DESTROY: __webpack_require__(642), - FADE_IN_COMPLETE: __webpack_require__(643), - FADE_IN_START: __webpack_require__(644), - FADE_OUT_COMPLETE: __webpack_require__(645), - FADE_OUT_START: __webpack_require__(646), - FLASH_COMPLETE: __webpack_require__(647), - FLASH_START: __webpack_require__(648), - PAN_COMPLETE: __webpack_require__(649), - PAN_START: __webpack_require__(650), - POST_RENDER: __webpack_require__(651), - PRE_RENDER: __webpack_require__(652), - SHAKE_COMPLETE: __webpack_require__(653), - SHAKE_START: __webpack_require__(654), - ZOOM_COMPLETE: __webpack_require__(655), - ZOOM_START: __webpack_require__(656) + DESTROY: __webpack_require__(641), + FADE_IN_COMPLETE: __webpack_require__(642), + FADE_IN_START: __webpack_require__(643), + FADE_OUT_COMPLETE: __webpack_require__(644), + FADE_OUT_START: __webpack_require__(645), + FLASH_COMPLETE: __webpack_require__(646), + FLASH_START: __webpack_require__(647), + PAN_COMPLETE: __webpack_require__(648), + PAN_START: __webpack_require__(649), + POST_RENDER: __webpack_require__(650), + PRE_RENDER: __webpack_require__(651), + SHAKE_COMPLETE: __webpack_require__(652), + SHAKE_START: __webpack_require__(653), + ZOOM_COMPLETE: __webpack_require__(654), + ZOOM_START: __webpack_require__(655) }; @@ -8408,8 +8347,8 @@ module.exports = CONST; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTileAt = __webpack_require__(136); -var GetTilesWithin = __webpack_require__(25); +var GetTileAt = __webpack_require__(138); +var GetTilesWithin = __webpack_require__(24); /** * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the @@ -8853,52 +8792,52 @@ module.exports = DistanceBetween; module.exports = { - BOOT: __webpack_require__(812), - DESTROY: __webpack_require__(813), - DRAG_END: __webpack_require__(814), - DRAG_ENTER: __webpack_require__(815), - DRAG: __webpack_require__(816), - DRAG_LEAVE: __webpack_require__(817), - DRAG_OVER: __webpack_require__(818), - DRAG_START: __webpack_require__(819), - DROP: __webpack_require__(820), - GAME_OUT: __webpack_require__(821), - GAME_OVER: __webpack_require__(822), - GAMEOBJECT_DOWN: __webpack_require__(823), - GAMEOBJECT_DRAG_END: __webpack_require__(824), - GAMEOBJECT_DRAG_ENTER: __webpack_require__(825), - GAMEOBJECT_DRAG: __webpack_require__(826), - GAMEOBJECT_DRAG_LEAVE: __webpack_require__(827), - GAMEOBJECT_DRAG_OVER: __webpack_require__(828), - GAMEOBJECT_DRAG_START: __webpack_require__(829), - GAMEOBJECT_DROP: __webpack_require__(830), - GAMEOBJECT_MOVE: __webpack_require__(831), - GAMEOBJECT_OUT: __webpack_require__(832), - GAMEOBJECT_OVER: __webpack_require__(833), - GAMEOBJECT_POINTER_DOWN: __webpack_require__(834), - GAMEOBJECT_POINTER_MOVE: __webpack_require__(835), - GAMEOBJECT_POINTER_OUT: __webpack_require__(836), - GAMEOBJECT_POINTER_OVER: __webpack_require__(837), - GAMEOBJECT_POINTER_UP: __webpack_require__(838), - GAMEOBJECT_POINTER_WHEEL: __webpack_require__(839), - GAMEOBJECT_UP: __webpack_require__(840), - GAMEOBJECT_WHEEL: __webpack_require__(841), - MANAGER_BOOT: __webpack_require__(842), - MANAGER_PROCESS: __webpack_require__(843), - MANAGER_UPDATE: __webpack_require__(844), - POINTER_DOWN: __webpack_require__(845), - POINTER_DOWN_OUTSIDE: __webpack_require__(846), - POINTER_MOVE: __webpack_require__(847), - POINTER_OUT: __webpack_require__(848), - POINTER_OVER: __webpack_require__(849), - POINTER_UP: __webpack_require__(850), - POINTER_UP_OUTSIDE: __webpack_require__(851), - POINTER_WHEEL: __webpack_require__(852), - POINTERLOCK_CHANGE: __webpack_require__(853), - PRE_UPDATE: __webpack_require__(854), - SHUTDOWN: __webpack_require__(855), - START: __webpack_require__(856), - UPDATE: __webpack_require__(857) + BOOT: __webpack_require__(814), + DESTROY: __webpack_require__(815), + DRAG_END: __webpack_require__(816), + DRAG_ENTER: __webpack_require__(817), + DRAG: __webpack_require__(818), + DRAG_LEAVE: __webpack_require__(819), + DRAG_OVER: __webpack_require__(820), + DRAG_START: __webpack_require__(821), + DROP: __webpack_require__(822), + GAME_OUT: __webpack_require__(823), + GAME_OVER: __webpack_require__(824), + GAMEOBJECT_DOWN: __webpack_require__(825), + GAMEOBJECT_DRAG_END: __webpack_require__(826), + GAMEOBJECT_DRAG_ENTER: __webpack_require__(827), + GAMEOBJECT_DRAG: __webpack_require__(828), + GAMEOBJECT_DRAG_LEAVE: __webpack_require__(829), + GAMEOBJECT_DRAG_OVER: __webpack_require__(830), + GAMEOBJECT_DRAG_START: __webpack_require__(831), + GAMEOBJECT_DROP: __webpack_require__(832), + GAMEOBJECT_MOVE: __webpack_require__(833), + GAMEOBJECT_OUT: __webpack_require__(834), + GAMEOBJECT_OVER: __webpack_require__(835), + GAMEOBJECT_POINTER_DOWN: __webpack_require__(836), + GAMEOBJECT_POINTER_MOVE: __webpack_require__(837), + GAMEOBJECT_POINTER_OUT: __webpack_require__(838), + GAMEOBJECT_POINTER_OVER: __webpack_require__(839), + GAMEOBJECT_POINTER_UP: __webpack_require__(840), + GAMEOBJECT_POINTER_WHEEL: __webpack_require__(841), + GAMEOBJECT_UP: __webpack_require__(842), + GAMEOBJECT_WHEEL: __webpack_require__(843), + MANAGER_BOOT: __webpack_require__(844), + MANAGER_PROCESS: __webpack_require__(845), + MANAGER_UPDATE: __webpack_require__(846), + POINTER_DOWN: __webpack_require__(847), + POINTER_DOWN_OUTSIDE: __webpack_require__(848), + POINTER_MOVE: __webpack_require__(849), + POINTER_OUT: __webpack_require__(850), + POINTER_OVER: __webpack_require__(851), + POINTER_UP: __webpack_require__(852), + POINTER_UP_OUTSIDE: __webpack_require__(853), + POINTER_WHEEL: __webpack_require__(854), + POINTERLOCK_CHANGE: __webpack_require__(855), + PRE_UPDATE: __webpack_require__(856), + SHUTDOWN: __webpack_require__(857), + START: __webpack_require__(858), + UPDATE: __webpack_require__(859) }; @@ -8955,10 +8894,10 @@ module.exports = Contains; */ var Class = __webpack_require__(0); -var GetPoint = __webpack_require__(270); -var GetPoints = __webpack_require__(147); +var GetPoint = __webpack_require__(272); +var GetPoints = __webpack_require__(150); var GEOM_CONST = __webpack_require__(46); -var Random = __webpack_require__(148); +var Random = __webpack_require__(151); var Vector2 = __webpack_require__(3); /** @@ -9357,29 +9296,29 @@ module.exports = Wrap; module.exports = { - COMPLETE: __webpack_require__(880), - DECODED: __webpack_require__(881), - DECODED_ALL: __webpack_require__(882), - DESTROY: __webpack_require__(883), - DETUNE: __webpack_require__(884), - GLOBAL_DETUNE: __webpack_require__(885), - GLOBAL_MUTE: __webpack_require__(886), - GLOBAL_RATE: __webpack_require__(887), - GLOBAL_VOLUME: __webpack_require__(888), - LOOP: __webpack_require__(889), - LOOPED: __webpack_require__(890), - MUTE: __webpack_require__(891), - PAUSE_ALL: __webpack_require__(892), - PAUSE: __webpack_require__(893), - PLAY: __webpack_require__(894), - RATE: __webpack_require__(895), - RESUME_ALL: __webpack_require__(896), - RESUME: __webpack_require__(897), - SEEK: __webpack_require__(898), - STOP_ALL: __webpack_require__(899), - STOP: __webpack_require__(900), - UNLOCKED: __webpack_require__(901), - VOLUME: __webpack_require__(902) + COMPLETE: __webpack_require__(882), + DECODED: __webpack_require__(883), + DECODED_ALL: __webpack_require__(884), + DESTROY: __webpack_require__(885), + DETUNE: __webpack_require__(886), + GLOBAL_DETUNE: __webpack_require__(887), + GLOBAL_MUTE: __webpack_require__(888), + GLOBAL_RATE: __webpack_require__(889), + GLOBAL_VOLUME: __webpack_require__(890), + LOOP: __webpack_require__(891), + LOOPED: __webpack_require__(892), + MUTE: __webpack_require__(893), + PAUSE_ALL: __webpack_require__(894), + PAUSE: __webpack_require__(895), + PLAY: __webpack_require__(896), + RATE: __webpack_require__(897), + RESUME_ALL: __webpack_require__(898), + RESUME: __webpack_require__(899), + SEEK: __webpack_require__(900), + STOP_ALL: __webpack_require__(901), + STOP: __webpack_require__(902), + UNLOCKED: __webpack_require__(903), + VOLUME: __webpack_require__(904) }; @@ -9591,7 +9530,7 @@ var JSONFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('json', function (key, url, dataKey, xhrSettings) { @@ -9851,6 +9790,108 @@ module.exports = MultiFile; /***/ }), /* 62 */, /* 63 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileX + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The X location in tile units. + */ +var WorldToTileX = function (worldX, snapToFloor, camera, layer) +{ + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + } + + return snapToFloor + ? Math.floor(worldX / tileWidth) + : worldX / tileWidth; +}; + +module.exports = WorldToTileX; + + +/***/ }), +/* 64 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileY + * @private + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The Y location in tile units. + */ +var WorldToTileY = function (worldY, snapToFloor, camera, layer) +{ + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + return snapToFloor + ? Math.floor(worldY / tileHeight) + : worldY / tileHeight; +}; + +module.exports = WorldToTileY; + + +/***/ }), +/* 65 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -9861,10 +9902,10 @@ module.exports = MultiFile; var Class = __webpack_require__(0); var Contains = __webpack_require__(55); -var GetPoint = __webpack_require__(261); -var GetPoints = __webpack_require__(262); +var GetPoint = __webpack_require__(263); +var GetPoints = __webpack_require__(264); var GEOM_CONST = __webpack_require__(46); -var Random = __webpack_require__(144); +var Random = __webpack_require__(147); /** * @classdesc @@ -10225,7 +10266,7 @@ module.exports = Circle; /***/ }), -/* 64 */ +/* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10907,7 +10948,7 @@ earcut.flatten = function (data) { /***/ }), -/* 65 */ +/* 67 */ /***/ (function(module, exports) { /** @@ -10949,7 +10990,7 @@ module.exports = Clone; /***/ }), -/* 66 */ +/* 68 */ /***/ (function(module, exports) { /** @@ -10998,7 +11039,7 @@ module.exports = SafeRange; /***/ }), -/* 67 */ +/* 69 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -11007,107 +11048,176 @@ module.exports = SafeRange; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var EaseMap = __webpack_require__(163); -var UppercaseFirst = __webpack_require__(176); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var SpriteRender = __webpack_require__(960); /** - * This internal function is used to return the correct ease function for a Tween. - * - * It can take a variety of input, including an EaseMap based string, or a custom function. + * @classdesc + * A Sprite Game Object. * - * @function Phaser.Tweens.Builders.GetEaseFunction + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class Sprite + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor * @since 3.0.0 * - * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. - * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @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.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.TextureCrop + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible * - * @return {function} The ease function. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. */ -var GetEaseFunction = function (ease, easeParams) -{ - // Default ease function - var easeFunction = EaseMap.Power0; +var Sprite = new Class({ - // Prepare ease function - if (typeof ease === 'string') + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + SpriteRender + ], + + initialize: + + function Sprite (scene, x, y, texture, frame) { - // String based look-up + GameObject.call(this, scene, 'Sprite'); - // 1) They specified it correctly - if (EaseMap.hasOwnProperty(ease)) - { - easeFunction = EaseMap[ease]; - } - else - { - // Do some string manipulation to try and find it - var direction = ''; + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Sprite#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); - if (ease.indexOf('.')) - { - // quad.in = Quad.easeIn - // quad.out = Quad.easeOut - // quad.inout = Quad.easeInOut + /** + * The Animation Controller of this Sprite. + * + * @name Phaser.GameObjects.Sprite#anims + * @type {Phaser.GameObjects.Components.Animation} + * @since 3.0.0 + */ + this.anims = new Components.Animation(this); - direction = ease.substr(ease.indexOf('.') + 1); + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + }, - if (direction.toLowerCase() === 'in') - { - direction = 'easeIn'; - } - else if (direction.toLowerCase() === 'out') - { - direction = 'easeOut'; - } - else if (direction.toLowerCase() === 'inout') - { - direction = 'easeInOut'; - } - } - - ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); - - if (EaseMap.hasOwnProperty(ease)) - { - easeFunction = EaseMap[ease]; - } - } - } - else if (typeof ease === 'function') + /** + * Update this Sprite's animations. + * + * @method Phaser.GameObjects.Sprite#preUpdate + * @protected + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + preUpdate: function (time, delta) { - // Custom function - easeFunction = ease; - } - else if (Array.isArray(ease) && ease.length === 4) + this.anims.update(time, delta); + }, + + /** + * Start playing the given animation. + * + * @method Phaser.GameObjects.Sprite#play + * @since 3.0.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.Sprite} This Game Object. + */ + play: function (key, ignoreIfPlaying, startFrame) { - // Bezier function (TODO) + this.anims.play(key, ignoreIfPlaying, startFrame); + + return this; + }, + + /** + * Build a JSON representation of this Sprite. + * + * @method Phaser.GameObjects.Sprite#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ + toJSON: function () + { + var data = Components.ToJSON(this); + + // Extra Sprite data is added here + + return data; + }, + + /** + * Handles the pre-destroy step for the Sprite, which removes the Animation component. + * + * @method Phaser.GameObjects.Sprite#preDestroy + * @private + * @since 3.14.0 + */ + preDestroy: function () + { + this.anims.destroy(); + + this.anims = undefined; } - // No custom ease parameters? - if (!easeParams) - { - // Return ease function - return easeFunction; - } +}); - var cloneParams = easeParams.slice(0); - - cloneParams.unshift(0); - - // Return ease function with custom ease parameters - return function (v) - { - cloneParams[0] = v; - - return easeFunction.apply(this, cloneParams); - }; -}; - -module.exports = GetEaseFunction; +module.exports = Sprite; /***/ }), -/* 68 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -11116,7 +11226,7 @@ module.exports = GetEaseFunction; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders a stroke outline around the given Shape. @@ -11182,7 +11292,7 @@ module.exports = StrokePathWebGL; /***/ }), -/* 69 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -11192,12 +11302,12 @@ module.exports = StrokePathWebGL; */ var Class = __webpack_require__(0); -var Contains = __webpack_require__(81); -var GetPoint = __webpack_require__(418); -var GetPoints = __webpack_require__(419); +var Contains = __webpack_require__(83); +var GetPoint = __webpack_require__(417); +var GetPoints = __webpack_require__(418); var GEOM_CONST = __webpack_require__(46); var Line = __webpack_require__(56); -var Random = __webpack_require__(152); +var Random = __webpack_require__(155); /** * @classdesc @@ -11629,7 +11739,7 @@ module.exports = Triangle; /***/ }), -/* 70 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -11879,7 +11989,7 @@ var ImageFile = new Class({ * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('image', function (key, url, xhrSettings) { @@ -11903,7 +12013,7 @@ module.exports = ImageFile; /***/ }), -/* 71 */ +/* 73 */ /***/ (function(module, exports) { /** @@ -11939,7 +12049,7 @@ module.exports = SetTileCollision; /***/ }), -/* 72 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -11948,10 +12058,9 @@ module.exports = SetTileCollision; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Rectangle = __webpack_require__(437); +var Rectangle = __webpack_require__(436); /** * @classdesc @@ -12651,34 +12760,14 @@ var Tile = new Class({ */ updatePixelXY: function () { - if (this.layer.orientation === CONST.ISOMETRIC) - { - // 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. - this.pixelX = (this.x - this.y) * this.baseWidth * 0.5; - this.pixelY = (this.x + this.y) * this.baseHeight * 0.5; - } - else if (this.layer.orientation === CONST.STAGGERED) - { - this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); - this.pixelY = this.y * (this.baseHeight / 2); - } - else if (this.layer.orientation === CONST.HEXAGONAL) - { - var sidel = this.layer.hexSideLength; - var rowHeight = ((this.baseHeight - sidel) / 2 + sidel); - this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); - this.pixelY = this.y * rowHeight; - } - else if (this.layer.orientation === CONST.ORTHOGONAL) - { - // 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. - this.pixelX = this.x * this.baseWidth; - this.pixelY = this.y * this.baseHeight; - - } + // 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. + this.pixelX = this.x * this.baseWidth; + this.pixelY = this.y * this.baseHeight; + + // this.pixelY = this.y * this.baseHeight - (this.height - this.baseHeight); + return this; }, @@ -12798,185 +12887,7 @@ module.exports = Tile; /***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameObject = __webpack_require__(14); -var SpriteRender = __webpack_require__(958); - -/** - * @classdesc - * A Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * - * @class Sprite - * @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.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var Sprite = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - SpriteRender - ], - - initialize: - - function Sprite (scene, x, y, texture, frame) - { - GameObject.call(this, scene, 'Sprite'); - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.Sprite#_crop - * @type {object} - * @private - * @since 3.11.0 - */ - this._crop = this.resetCropObject(); - - /** - * The Animation Controller of this Sprite. - * - * @name Phaser.GameObjects.Sprite#anims - * @type {Phaser.GameObjects.Components.Animation} - * @since 3.0.0 - */ - this.anims = new Components.Animation(this); - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.setOriginFromFrame(); - this.initPipeline(); - }, - - /** - * Update this Sprite's animations. - * - * @method Phaser.GameObjects.Sprite#preUpdate - * @protected - * @since 3.0.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - this.anims.update(time, delta); - }, - - /** - * Start playing the given animation. - * - * @method Phaser.GameObjects.Sprite#play - * @since 3.0.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Game Object. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - this.anims.play(key, ignoreIfPlaying, startFrame); - - return this; - }, - - /** - * Build a JSON representation of this Sprite. - * - * @method Phaser.GameObjects.Sprite#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. - */ - toJSON: function () - { - var data = Components.ToJSON(this); - - // Extra Sprite data is added here - - return data; - }, - - /** - * Handles the pre-destroy step for the Sprite, which removes the Animation component. - * - * @method Phaser.GameObjects.Sprite#preDestroy - * @private - * @since 3.14.0 - */ - preDestroy: function () - { - this.anims.destroy(); - - this.anims = undefined; - } - -}); - -module.exports = Sprite; - - -/***/ }), -/* 74 */ +/* 75 */ /***/ (function(module, exports) { /** @@ -13004,7 +12915,7 @@ module.exports = GetCenterX; /***/ }), -/* 75 */ +/* 76 */ /***/ (function(module, exports) { /** @@ -13039,7 +12950,7 @@ module.exports = SetCenterX; /***/ }), -/* 76 */ +/* 77 */ /***/ (function(module, exports) { /** @@ -13067,7 +12978,7 @@ module.exports = GetCenterY; /***/ }), -/* 77 */ +/* 78 */ /***/ (function(module, exports) { /** @@ -13102,7 +13013,7 @@ module.exports = SetCenterY; /***/ }), -/* 78 */ +/* 79 */ /***/ (function(module, exports) { /** @@ -13148,7 +13059,7 @@ module.exports = SpliceOne; /***/ }), -/* 79 */ +/* 80 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13158,8 +13069,8 @@ module.exports = SpliceOne; */ var Class = __webpack_require__(0); -var FromPoints = __webpack_require__(171); -var Rectangle = __webpack_require__(13); +var FromPoints = __webpack_require__(174); +var Rectangle = __webpack_require__(11); var Vector2 = __webpack_require__(3); /** @@ -13768,7 +13679,7 @@ module.exports = Curve; /***/ }), -/* 80 */ +/* 81 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13783,22 +13694,131 @@ module.exports = Curve; module.exports = { - ADD: __webpack_require__(859), - COMPLETE: __webpack_require__(860), - FILE_COMPLETE: __webpack_require__(861), - FILE_KEY_COMPLETE: __webpack_require__(862), - FILE_LOAD_ERROR: __webpack_require__(863), - FILE_LOAD: __webpack_require__(864), - FILE_PROGRESS: __webpack_require__(865), - POST_PROCESS: __webpack_require__(866), - PROGRESS: __webpack_require__(867), - START: __webpack_require__(868) + ADD: __webpack_require__(861), + COMPLETE: __webpack_require__(862), + FILE_COMPLETE: __webpack_require__(863), + FILE_KEY_COMPLETE: __webpack_require__(864), + FILE_LOAD_ERROR: __webpack_require__(865), + FILE_LOAD: __webpack_require__(866), + FILE_PROGRESS: __webpack_require__(867), + POST_PROCESS: __webpack_require__(868), + PROGRESS: __webpack_require__(869), + START: __webpack_require__(870) }; /***/ }), -/* 81 */ +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var EaseMap = __webpack_require__(166); +var UppercaseFirst = __webpack_require__(179); + +/** + * This internal function is used to return the correct ease function for a Tween. + * + * It can take a variety of input, including an EaseMap based string, or a custom function. + * + * @function Phaser.Tweens.Builders.GetEaseFunction + * @since 3.0.0 + * + * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. + * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * + * @return {function} The ease function. + */ +var GetEaseFunction = function (ease, easeParams) +{ + // Default ease function + var easeFunction = EaseMap.Power0; + + // Prepare ease function + if (typeof ease === 'string') + { + // String based look-up + + // 1) They specified it correctly + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + else + { + // Do some string manipulation to try and find it + var direction = ''; + + if (ease.indexOf('.')) + { + // quad.in = Quad.easeIn + // quad.out = Quad.easeOut + // quad.inout =Quad.easeInOut + + direction = ease.substr(ease.indexOf('.') + 1); + + if (direction.toLowerCase() === 'in') + { + direction = 'easeIn'; + } + else if (direction.toLowerCase() === 'out') + { + direction = 'easeOut'; + } + else if (direction.toLowerCase() === 'inout') + { + direction = 'easeInOut'; + } + } + + ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); + + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + } + } + else if (typeof ease === 'function') + { + // Custom function + easeFunction = ease; + } + else if (Array.isArray(ease) && ease.length === 4) + { + // Bezier function (TODO) + } + + // No custom ease parameters? + if (!easeParams) + { + // Return ease function + return easeFunction; + } + + var cloneParams = easeParams.slice(0); + + cloneParams.unshift(0); + + // Return ease function with custom ease parameters + return function (v) + { + cloneParams[0] = v; + + return easeFunction.apply(this, cloneParams); + }; +}; + +module.exports = GetEaseFunction; + + +/***/ }), +/* 83 */ /***/ (function(module, exports) { /** @@ -13851,7 +13871,7 @@ module.exports = Contains; /***/ }), -/* 82 */ +/* 84 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13927,7 +13947,7 @@ module.exports = LineToLine; /***/ }), -/* 83 */ +/* 85 */ /***/ (function(module, exports) { /** @@ -13955,8 +13975,8 @@ module.exports = Angle; /***/ }), -/* 84 */, -/* 85 */ +/* 86 */, +/* 87 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13965,7 +13985,7 @@ module.exports = Angle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); /** * Return a value based on the range between `min` and `max` and the percentage given. @@ -13990,7 +14010,7 @@ module.exports = FromPercent; /***/ }), -/* 86 */ +/* 88 */ /***/ (function(module, exports) { /** @@ -14031,7 +14051,7 @@ module.exports = GetBoolean; /***/ }), -/* 87 */ +/* 89 */ /***/ (function(module, exports) { /** @@ -14203,7 +14223,7 @@ module.exports = TWEEN_CONST; /***/ }), -/* 88 */ +/* 90 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -14218,23 +14238,23 @@ module.exports = TWEEN_CONST; module.exports = { - DESTROY: __webpack_require__(577), - VIDEO_COMPLETE: __webpack_require__(578), - VIDEO_CREATED: __webpack_require__(579), - VIDEO_ERROR: __webpack_require__(580), - VIDEO_LOOP: __webpack_require__(581), - VIDEO_PLAY: __webpack_require__(582), - VIDEO_SEEKED: __webpack_require__(583), - VIDEO_SEEKING: __webpack_require__(584), - VIDEO_STOP: __webpack_require__(585), - VIDEO_TIMEOUT: __webpack_require__(586), - VIDEO_UNLOCKED: __webpack_require__(587) + DESTROY: __webpack_require__(576), + VIDEO_COMPLETE: __webpack_require__(577), + VIDEO_CREATED: __webpack_require__(578), + VIDEO_ERROR: __webpack_require__(579), + VIDEO_LOOP: __webpack_require__(580), + VIDEO_PLAY: __webpack_require__(581), + VIDEO_SEEKED: __webpack_require__(582), + VIDEO_SEEKING: __webpack_require__(583), + VIDEO_STOP: __webpack_require__(584), + VIDEO_TIMEOUT: __webpack_require__(585), + VIDEO_UNLOCKED: __webpack_require__(586) }; /***/ }), -/* 89 */ +/* 91 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -14246,11 +14266,11 @@ module.exports = { var Class = __webpack_require__(0); var Components = __webpack_require__(12); var DegToRad = __webpack_require__(35); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(48); -var Rectangle = __webpack_require__(13); -var TransformMatrix = __webpack_require__(30); -var ValueToColor = __webpack_require__(158); +var Rectangle = __webpack_require__(11); +var TransformMatrix = __webpack_require__(32); +var ValueToColor = __webpack_require__(161); var Vector2 = __webpack_require__(3); /** @@ -16155,7 +16175,7 @@ module.exports = BaseCamera; /***/ }), -/* 90 */ +/* 92 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -16170,18 +16190,18 @@ module.exports = BaseCamera; module.exports = { - ENTER_FULLSCREEN: __webpack_require__(695), - FULLSCREEN_FAILED: __webpack_require__(696), - FULLSCREEN_UNSUPPORTED: __webpack_require__(697), - LEAVE_FULLSCREEN: __webpack_require__(698), - ORIENTATION_CHANGE: __webpack_require__(699), - RESIZE: __webpack_require__(700) + ENTER_FULLSCREEN: __webpack_require__(694), + FULLSCREEN_FAILED: __webpack_require__(695), + FULLSCREEN_UNSUPPORTED: __webpack_require__(696), + LEAVE_FULLSCREEN: __webpack_require__(697), + ORIENTATION_CHANGE: __webpack_require__(698), + RESIZE: __webpack_require__(699) }; /***/ }), -/* 91 */ +/* 93 */ /***/ (function(module, exports) { /** @@ -16225,7 +16245,7 @@ module.exports = SnapFloor; /***/ }), -/* 92 */ +/* 94 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -16235,8 +16255,8 @@ module.exports = SnapFloor; */ var Class = __webpack_require__(0); -var Clamp = __webpack_require__(23); -var Extend = __webpack_require__(18); +var Clamp = __webpack_require__(22); +var Extend = __webpack_require__(17); /** * @classdesc @@ -17044,7 +17064,7 @@ module.exports = Frame; /***/ }), -/* 93 */ +/* 95 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -17054,11 +17074,11 @@ module.exports = Frame; */ var Class = __webpack_require__(0); -var Contains = __webpack_require__(94); -var GetPoint = __webpack_require__(391); -var GetPoints = __webpack_require__(392); +var Contains = __webpack_require__(96); +var GetPoint = __webpack_require__(390); +var GetPoints = __webpack_require__(391); var GEOM_CONST = __webpack_require__(46); -var Random = __webpack_require__(151); +var Random = __webpack_require__(154); /** * @classdesc @@ -17426,7 +17446,7 @@ module.exports = Ellipse; /***/ }), -/* 94 */ +/* 96 */ /***/ (function(module, exports) { /** @@ -17468,7 +17488,7 @@ module.exports = Contains; /***/ }), -/* 95 */ +/* 97 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -17477,15 +17497,15 @@ module.exports = Contains; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Actions = __webpack_require__(236); +var Actions = __webpack_require__(238); var Class = __webpack_require__(0); -var Events = __webpack_require__(88); +var Events = __webpack_require__(90); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); var IsPlainObject = __webpack_require__(7); -var Range = __webpack_require__(385); -var Set = __webpack_require__(127); -var Sprite = __webpack_require__(73); +var Range = __webpack_require__(384); +var Set = __webpack_require__(108); +var Sprite = __webpack_require__(69); /** * @classdesc @@ -17994,7 +18014,7 @@ var Group = new Class({ * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. * @param {boolean} [addToScene=false] - Also add the Game Object to the scene. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ add: function (child, addToScene) { @@ -18043,7 +18063,7 @@ var Group = new Class({ * @param {Phaser.GameObjects.GameObject[]} children - The Game Objects to add. * @param {boolean} [addToScene=false] - Also add the Game Objects to the scene. * - * @return {this} This group. + * @return {Phaser.GameObjects.Group} This group. */ addMultiple: function (children, addToScene) { @@ -18072,7 +18092,7 @@ var Group = new Class({ * @param {boolean} [removeFromScene=false] - Optionally remove the Group member from the Scene it belongs to. * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group member. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ remove: function (child, removeFromScene, destroyChild) { @@ -18126,7 +18146,7 @@ var Group = new Class({ * @param {boolean} [removeFromScene=false] - Optionally remove each Group member from the Scene. * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group members. * - * @return {this} This group. + * @return {Phaser.GameObjects.Group} This group. */ clear: function (removeFromScene, destroyChild) { @@ -18489,7 +18509,7 @@ var Group = new Class({ * @param {string} key - The string-based key of the animation to play. * @param {string} [startFrame=0] - Optionally start the animation playing from this frame index. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ playAnimation: function (key, startFrame) { @@ -18588,7 +18608,7 @@ var Group = new Class({ * @param {integer} [index=0] - An optional offset to start searching from within the items array. * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ propertyValueSet: function (key, value, step, index, direction) { @@ -18609,7 +18629,7 @@ var Group = new Class({ * @param {integer} [index=0] - An optional offset to start searching from within the items array. * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ propertyValueInc: function (key, value, step, index, direction) { @@ -18627,7 +18647,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setX: function (value, step) { @@ -18645,7 +18665,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setY: function (value, step) { @@ -18665,7 +18685,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setXY: function (x, y, stepX, stepY) { @@ -18683,7 +18703,7 @@ var Group = new Class({ * @param {number} value - The amount to be added to the `x` property. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ incX: function (value, step) { @@ -18701,7 +18721,7 @@ var Group = new Class({ * @param {number} value - The amount to be added to the `y` property. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ incY: function (value, step) { @@ -18721,7 +18741,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ incXY: function (x, y, stepX, stepY) { @@ -18743,7 +18763,7 @@ var Group = new Class({ * @param {number} y - The y coordinate to place the first item in the array at. * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ shiftPosition: function (x, y, direction) { @@ -18761,7 +18781,7 @@ var Group = new Class({ * @param {number} value - The amount to set the angle to, in degrees. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ angle: function (value, step) { @@ -18779,7 +18799,7 @@ var Group = new Class({ * @param {number} value - The amount to set the rotation to, in radians. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ rotate: function (value, step) { @@ -18797,7 +18817,7 @@ var Group = new Class({ * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. * @param {number} angle - The angle to rotate by, in radians. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ rotateAround: function (point, angle) { @@ -18816,7 +18836,7 @@ var Group = new Class({ * @param {number} angle - The angle to rotate by, in radians. * @param {number} distance - The distance from the point of rotation in pixels. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ rotateAroundDistance: function (point, angle, distance) { @@ -18834,7 +18854,7 @@ var Group = new Class({ * @param {number} value - The amount to set the alpha to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setAlpha: function (value, step) { @@ -18854,7 +18874,7 @@ var Group = new Class({ * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setTint: function (topLeft, topRight, bottomLeft, bottomRight) { @@ -18874,7 +18894,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setOrigin: function (originX, originY, stepX, stepY) { @@ -18892,7 +18912,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ scaleX: function (value, step) { @@ -18910,7 +18930,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ scaleY: function (value, step) { @@ -18930,7 +18950,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ scaleXY: function (scaleX, scaleY, stepX, stepY) { @@ -18948,7 +18968,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setDepth: function (value, step) { @@ -18965,7 +18985,7 @@ var Group = new Class({ * * @param {number} value - The amount to set the property to. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setBlendMode: function (value) { @@ -18983,7 +19003,7 @@ var Group = new Class({ * @param {*} 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 - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setHitArea: function (hitArea, hitAreaCallback) { @@ -18998,7 +19018,7 @@ var Group = new Class({ * @method Phaser.GameObjects.Group#shuffle * @since 3.21.0 * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ shuffle: function () { @@ -19050,7 +19070,7 @@ var Group = new Class({ * @param {integer} [index=0] - An optional offset to start searching from within the items array. * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setVisible: function (value, index, direction) { @@ -19065,7 +19085,7 @@ var Group = new Class({ * @method Phaser.GameObjects.Group#toggleVisible * @since 3.0.0 * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ toggleVisible: function () { @@ -19106,7 +19126,7 @@ module.exports = Group; /***/ }), -/* 96 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19115,7 +19135,137 @@ module.exports = Group; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var ImageRender = __webpack_require__(963); + +/** + * @classdesc + * An Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class Image + * @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.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Image = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + ImageRender + ], + + initialize: + + function Image (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Image'); + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Image#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + } + +}); + +module.exports = Image; + + +/***/ }), +/* 99 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determine whether the source object has a property with the specified key. + * + * @function Phaser.Utils.Objects.HasValue + * @since 3.0.0 + * + * @param {object} source - The source object to be checked. + * @param {string} key - The property to check for within the object + * + * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. + */ +var HasValue = function (source, key) +{ + return (source.hasOwnProperty(key)); +}; + +module.exports = HasValue; + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); /** * Renders a filled path for the given Shape. @@ -19170,9 +19320,9 @@ module.exports = FillPathWebGL; /***/ }), -/* 97 */, -/* 98 */, -/* 99 */ +/* 101 */, +/* 102 */, +/* 103 */ /***/ (function(module, exports) { /** @@ -19203,7 +19353,7 @@ module.exports = IsInLayerBounds; /***/ }), -/* 100 */ +/* 104 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19214,7 +19364,6 @@ module.exports = IsInLayerBounds; var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(2); -var CONST = __webpack_require__(10); /** * @classdesc @@ -19318,15 +19467,6 @@ var LayerData = new Class({ */ this.baseTileHeight = GetFastValue(config, 'baseTileHeight', this.tileHeight); - /** - * The layer's orientation, necessary to be able to determine a tile's pixelX and pixelY as well as the layer's width and height. - * - * @name Phaser.Tilemaps.LayerData#orientation - * @type {string} - * @since 3.23beta.PR_svipal - */ - this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); - /** * The width in pixels of the entire layer. * @@ -19425,16 +19565,6 @@ var LayerData = new Class({ * @since 3.0.0 */ this.tilemapLayer = GetFastValue(config, 'tilemapLayer', null); - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); - } }); @@ -19443,7 +19573,7 @@ module.exports = LayerData; /***/ }), -/* 101 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19454,7 +19584,6 @@ module.exports = LayerData; var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(2); -var CONST = __webpack_require__(10); /** * @classdesc @@ -19565,7 +19694,7 @@ var MapData = new Class({ * @type {string} * @since 3.0.0 */ - this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); + this.orientation = GetFastValue(config, 'orientation', 'orthogonal'); /** * Determines the draw order of tilemap. Default is right-down @@ -19661,15 +19790,6 @@ var MapData = new Class({ * @since 3.0.0 */ this.tiles = GetFastValue(config, 'tiles', []); - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); } }); @@ -19678,7 +19798,7 @@ module.exports = MapData; /***/ }), -/* 102 */ +/* 106 */ /***/ (function(module, exports) { /** @@ -19812,7 +19932,52 @@ module.exports = ALIGN_CONST; /***/ }), -/* 103 */ +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(67); + +/** + * Creates a new Object using all values from obj1 and obj2. + * If a value exists in both obj1 and obj2, the value in obj1 is used. + * + * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this + * function on shallow objects. + * + * @function Phaser.Utils.Objects.Merge + * @since 3.0.0 + * + * @param {object} obj1 - The first object. + * @param {object} obj2 - The second object. + * + * @return {object} A new object containing the union of obj1's and obj2's properties. + */ +var Merge = function (obj1, obj2) +{ + var clone = Clone(obj1); + + for (var key in obj2) + { + if (!clone.hasOwnProperty(key)) + { + clone[key] = obj2[key]; + } + } + + return clone; +}; + +module.exports = Merge; + + +/***/ }), +/* 108 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19822,128 +19987,447 @@ module.exports = ALIGN_CONST; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameObject = __webpack_require__(14); -var ImageRender = __webpack_require__(961); + +/** + * @callback EachSetCallback + * + * @param {E} entry - The Set entry. + * @param {number} index - The index of the entry within the Set. + * + * @return {?boolean} The callback result. + */ /** * @classdesc - * An Image Game Object. + * A Set is a collection of unique elements. * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * - * @class Image - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects + * @class Set + * @memberof Phaser.Structs * @constructor * @since 3.0.0 * - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @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.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.TextureCrop - * @extends Phaser.GameObjects.Components.Tint - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible + * @generic T + * @genericUse {T[]} - [elements] * - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. */ -var Image = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - ImageRender - ], +var Set = new Class({ initialize: - function Image (scene, x, y, texture, frame) + function Set (elements) { - GameObject.call(this, scene, 'Image'); - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * The entries of this Set. Stored internally as an array. * - * @name Phaser.GameObjects.Image#_crop - * @type {object} - * @private - * @since 3.11.0 + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.Set#entries + * @type {Array.<*>} + * @default [] + * @since 3.0.0 */ - this._crop = this.resetCropObject(); + this.entries = []; + + if (Array.isArray(elements)) + { + for (var i = 0; i < elements.length; i++) + { + this.set(elements[i]); + } + } + }, + + /** + * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. + * + * @method Phaser.Structs.Set#set + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to insert into this Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + set: function (value) + { + if (this.entries.indexOf(value) === -1) + { + this.entries.push(value); + } + + return this; + }, + + /** + * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. + * If no elements of this Set satisfy the condition then this method will return `null`. + * + * @method Phaser.Structs.Set#get + * @since 3.0.0 + * + * @genericUse {T} - [value,$return] + * + * @param {string} property - The property name to check on the elements of this Set. + * @param {*} value - The value to check for. + * + * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. + */ + get: function (property, value) + { + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + + if (entry[property] === value) + { + return entry; + } + } + }, + + /** + * Returns an array containing all the values in this Set. + * + * @method Phaser.Structs.Set#getArray + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} An array containing all the values in this Set. + */ + getArray: function () + { + return this.entries.slice(0); + }, + + /** + * Removes the given value from this Set if this Set contains that value. + * + * @method Phaser.Structs.Set#delete + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to remove from the Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + delete: function (value) + { + var index = this.entries.indexOf(value); + + if (index > -1) + { + this.entries.splice(index, 1); + } + + return this; + }, + + /** + * Dumps the contents of this Set to the console via `console.group`. + * + * @method Phaser.Structs.Set#dump + * @since 3.0.0 + */ + dump: function () + { + // eslint-disable-next-line no-console + console.group('Set'); + + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + console.log(entry); + } + + // eslint-disable-next-line no-console + console.groupEnd(); + }, + + /** + * Passes each value in this Set to the given callback. + * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. + * + * @method Phaser.Structs.Set#each + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + each: function (callback, callbackScope) + { + var i; + var temp = this.entries.slice(); + var len = temp.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, temp[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(temp[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Passes each value in this Set to the given callback. + * For when you absolutely know this Set won't be modified during the iteration. + * + * @method Phaser.Structs.Set#iterate + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterate: function (callback, callbackScope) + { + var i; + var len = this.entries.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, this.entries[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(this.entries[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. + * + * @method Phaser.Structs.Set#iterateLocal + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {string} callbackKey - The key of the function to be invoked on each Set entry. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterateLocal: function (callbackKey) + { + var i; + var args = []; + + for (i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + var len = this.entries.length; + + for (i = 0; i < len; i++) + { + var entry = this.entries[i]; + + entry[callbackKey].apply(entry, args); + } + + return this; + }, + + /** + * Clears this Set so that it no longer contains any values. + * + * @method Phaser.Structs.Set#clear + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @return {Phaser.Structs.Set} This Set object. + */ + clear: function () + { + this.entries.length = 0; + + return this; + }, + + /** + * Returns `true` if this Set contains the given value, otherwise returns `false`. + * + * @method Phaser.Structs.Set#contains + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {*} value - The value to check for in this Set. + * + * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. + */ + contains: function (value) + { + return (this.entries.indexOf(value) > -1); + }, + + /** + * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. + * + * @method Phaser.Structs.Set#union + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the union with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. + */ + union: function (set) + { + var newSet = new Set(); + + set.entries.forEach(function (value) + { + newSet.set(value); + }); + + this.entries.forEach(function (value) + { + newSet.set(value); + }); + + return newSet; + }, + + /** + * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. + * + * @method Phaser.Structs.Set#intersect + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to intersect this set with. + * + * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. + */ + intersect: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * Returns a new Set containing all the values in this Set which are *not* also in the given Set. + * + * @method Phaser.Structs.Set#difference + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the difference with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. + */ + difference: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (!set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * The size of this Set. This is the number of entries within it. + * Changing the size will truncate the Set if the given value is smaller than the current size. + * Increasing the size larger than the current size has no effect. + * + * @name Phaser.Structs.Set#size + * @type {integer} + * @since 3.0.0 + */ + size: { + + get: function () + { + return this.entries.length; + }, + + set: function (value) + { + if (value < this.entries.length) + { + return this.entries.length = value; + } + else + { + return this.entries.length; + } + } - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.setOriginFromFrame(); - this.initPipeline(); } }); -module.exports = Image; +module.exports = Set; /***/ }), -/* 104 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determine whether the source object has a property with the specified key. - * - * @function Phaser.Utils.Objects.HasValue - * @since 3.0.0 - * - * @param {object} source - The source object to be checked. - * @param {string} key - The property to check for within the object - * - * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. - */ -var HasValue = function (source, key) -{ - return (source.hasOwnProperty(key)); -}; - -module.exports = HasValue; - - -/***/ }), -/* 105 */, -/* 106 */ +/* 109 */, +/* 110 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19953,12 +20437,12 @@ module.exports = HasValue; */ var BlendModes = __webpack_require__(52); -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); var CircleContains = __webpack_require__(55); var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); var RectangleContains = __webpack_require__(47); /** @@ -20104,7 +20588,7 @@ var Zone = new Class({ * @param {number} height - The height of this Game Object. * @param {boolean} [resizeInput=true] - If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setSize: function (width, height, resizeInput) { @@ -20136,7 +20620,7 @@ var Zone = new Class({ * @param {number} width - The width of this Game Object. * @param {number} height - The height of this Game Object. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setDisplaySize: function (width, height) { @@ -20155,7 +20639,7 @@ var Zone = new Class({ * * @param {number} radius - The radius of the Circle that will form the Drop Zone. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setCircleDropZone: function (radius) { @@ -20172,7 +20656,7 @@ var Zone = new Class({ * @param {number} width - The width of the rectangle drop zone. * @param {number} height - The height of the rectangle drop zone. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setRectangleDropZone: function (width, height) { @@ -20188,7 +20672,7 @@ var Zone = new Class({ * @param {object} shape - A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. * @param {Phaser.Types.Input.HitAreaCallback} callback - A function that will return `true` if the given x/y coords it is sent are within the shape. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setDropZone: function (shape, callback) { @@ -20256,7 +20740,7 @@ module.exports = Zone; /***/ }), -/* 107 */ +/* 111 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -20271,30 +20755,30 @@ module.exports = Zone; module.exports = { - ADD_ANIMATION: __webpack_require__(529), - ANIMATION_COMPLETE: __webpack_require__(530), - ANIMATION_REPEAT: __webpack_require__(531), - ANIMATION_RESTART: __webpack_require__(532), - ANIMATION_START: __webpack_require__(533), - PAUSE_ALL: __webpack_require__(534), - REMOVE_ANIMATION: __webpack_require__(535), - RESUME_ALL: __webpack_require__(536), - SPRITE_ANIMATION_COMPLETE: __webpack_require__(537), - SPRITE_ANIMATION_KEY_COMPLETE: __webpack_require__(538), - SPRITE_ANIMATION_KEY_REPEAT: __webpack_require__(539), - SPRITE_ANIMATION_KEY_RESTART: __webpack_require__(540), - SPRITE_ANIMATION_KEY_START: __webpack_require__(541), - SPRITE_ANIMATION_KEY_UPDATE: __webpack_require__(542), - SPRITE_ANIMATION_REPEAT: __webpack_require__(543), - SPRITE_ANIMATION_RESTART: __webpack_require__(544), - SPRITE_ANIMATION_START: __webpack_require__(545), - SPRITE_ANIMATION_UPDATE: __webpack_require__(546) + ADD_ANIMATION: __webpack_require__(528), + ANIMATION_COMPLETE: __webpack_require__(529), + ANIMATION_REPEAT: __webpack_require__(530), + ANIMATION_RESTART: __webpack_require__(531), + ANIMATION_START: __webpack_require__(532), + PAUSE_ALL: __webpack_require__(533), + REMOVE_ANIMATION: __webpack_require__(534), + RESUME_ALL: __webpack_require__(535), + SPRITE_ANIMATION_COMPLETE: __webpack_require__(536), + SPRITE_ANIMATION_KEY_COMPLETE: __webpack_require__(537), + SPRITE_ANIMATION_KEY_REPEAT: __webpack_require__(538), + SPRITE_ANIMATION_KEY_RESTART: __webpack_require__(539), + SPRITE_ANIMATION_KEY_START: __webpack_require__(540), + SPRITE_ANIMATION_KEY_UPDATE: __webpack_require__(541), + SPRITE_ANIMATION_REPEAT: __webpack_require__(542), + SPRITE_ANIMATION_RESTART: __webpack_require__(543), + SPRITE_ANIMATION_START: __webpack_require__(544), + SPRITE_ANIMATION_UPDATE: __webpack_require__(545) }; /***/ }), -/* 108 */ +/* 112 */ /***/ (function(module, exports) { /** @@ -20322,7 +20806,7 @@ module.exports = Perimeter; /***/ }), -/* 109 */ +/* 113 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -20332,7 +20816,7 @@ module.exports = Perimeter; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(279); +var Events = __webpack_require__(281); /** * @callback DataEachCallback @@ -20963,7 +21447,7 @@ module.exports = DataManager; /***/ }), -/* 110 */ +/* 114 */ /***/ (function(module, exports) { /** @@ -21004,7 +21488,7 @@ module.exports = Shuffle; /***/ }), -/* 111 */ +/* 115 */ /***/ (function(module, exports) { /** @@ -21034,7 +21518,7 @@ module.exports = Linear; /***/ }), -/* 112 */ +/* 116 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** @@ -21203,10 +21687,10 @@ function init () module.exports = init(); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(721))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(720))) /***/ }), -/* 113 */ +/* 117 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -21215,7 +21699,7 @@ module.exports = init(); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var OS = __webpack_require__(112); +var OS = __webpack_require__(116); /** * Determines the browser type and version running this Phaser Game instance. @@ -21316,7 +21800,7 @@ module.exports = init(); /***/ }), -/* 114 */ +/* 118 */ /***/ (function(module, exports) { /** @@ -21346,7 +21830,7 @@ module.exports = IsSizePowerOfTwo; /***/ }), -/* 115 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -21371,7 +21855,7 @@ module.exports = { /***/ }), -/* 116 */ +/* 120 */ /***/ (function(module, exports) { /** @@ -21429,7 +21913,7 @@ module.exports = AddToDOM; /***/ }), -/* 117 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -21438,7 +21922,7 @@ module.exports = AddToDOM; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SpliceOne = __webpack_require__(78); +var SpliceOne = __webpack_require__(79); /** * Removes the given item, or array of items, from the array. @@ -21520,7 +22004,7 @@ module.exports = Remove; /***/ }), -/* 118 */ +/* 122 */ /***/ (function(module, exports) { /** @@ -22426,7 +22910,7 @@ module.exports = KeyCodes; /***/ }), -/* 119 */ +/* 123 */ /***/ (function(module, exports) { /** @@ -22549,52 +23033,7 @@ module.exports = CONST; /***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = __webpack_require__(65); - -/** - * Creates a new Object using all values from obj1 and obj2. - * If a value exists in both obj1 and obj2, the value in obj1 is used. - * - * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this - * function on shallow objects. - * - * @function Phaser.Utils.Objects.Merge - * @since 3.0.0 - * - * @param {object} obj1 - The first object. - * @param {object} obj2 - The second object. - * - * @return {object} A new object containing the union of obj1's and obj2's properties. - */ -var Merge = function (obj1, obj2) -{ - var clone = Clone(obj1); - - for (var key in obj2) - { - if (!clone.hasOwnProperty(key)) - { - clone[key] = obj2[key]; - } - } - - return clone; -}; - -module.exports = Merge; - - -/***/ }), -/* 121 */ +/* 124 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -22605,10 +23044,10 @@ module.exports = Merge; */ var Class = __webpack_require__(0); -var Clone = __webpack_require__(65); -var EventEmitter = __webpack_require__(11); +var Clone = __webpack_require__(67); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(59); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var NOOP = __webpack_require__(1); /** @@ -23219,7 +23658,7 @@ module.exports = BaseSoundManager; /***/ }), -/* 122 */ +/* 125 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -23230,9 +23669,9 @@ module.exports = BaseSoundManager; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(59); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); var NOOP = __webpack_require__(1); /** @@ -23719,7 +24158,7 @@ module.exports = BaseSound; /***/ }), -/* 123 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -23728,10 +24167,10 @@ module.exports = BaseSound; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayUtils = __webpack_require__(178); +var ArrayUtils = __webpack_require__(181); var Class = __webpack_require__(0); var NOOP = __webpack_require__(1); -var StableSort = __webpack_require__(125); +var StableSort = __webpack_require__(128); /** * @callback EachListCallback @@ -24535,7 +24974,7 @@ module.exports = List; /***/ }), -/* 124 */ +/* 127 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -24544,8 +24983,8 @@ module.exports = List; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CheckMatrix = __webpack_require__(179); -var TransposeMatrix = __webpack_require__(383); +var CheckMatrix = __webpack_require__(182); +var TransposeMatrix = __webpack_require__(382); /** * Rotates the array matrix based on the given rotation value. @@ -24607,7 +25046,7 @@ module.exports = RotateMatrix; /***/ }), -/* 125 */ +/* 128 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -24752,7 +25191,7 @@ else {} })(); /***/ }), -/* 126 */ +/* 129 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -24764,10 +25203,10 @@ else {} var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var GetBitmapTextSize = __webpack_require__(936); -var ParseFromAtlas = __webpack_require__(937); -var ParseXMLBitmapFont = __webpack_require__(182); -var Render = __webpack_require__(938); +var GetBitmapTextSize = __webpack_require__(938); +var ParseFromAtlas = __webpack_require__(939); +var ParseXMLBitmapFont = __webpack_require__(185); +var Render = __webpack_require__(940); /** * @classdesc @@ -25481,456 +25920,7 @@ module.exports = BitmapText; /***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); - -/** - * @callback EachSetCallback - * - * @param {E} entry - The Set entry. - * @param {number} index - The index of the entry within the Set. - * - * @return {?boolean} The callback result. - */ - -/** - * @classdesc - * A Set is a collection of unique elements. - * - * @class Set - * @memberof Phaser.Structs - * @constructor - * @since 3.0.0 - * - * @generic T - * @genericUse {T[]} - [elements] - * - * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. - */ -var Set = new Class({ - - initialize: - - function Set (elements) - { - /** - * The entries of this Set. Stored internally as an array. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.Set#entries - * @type {Array.<*>} - * @default [] - * @since 3.0.0 - */ - this.entries = []; - - if (Array.isArray(elements)) - { - for (var i = 0; i < elements.length; i++) - { - this.set(elements[i]); - } - } - }, - - /** - * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. - * - * @method Phaser.Structs.Set#set - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {*} value - The value to insert into this Set. - * - * @return {Phaser.Structs.Set} This Set object. - */ - set: function (value) - { - if (this.entries.indexOf(value) === -1) - { - this.entries.push(value); - } - - return this; - }, - - /** - * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. - * If no elements of this Set satisfy the condition then this method will return `null`. - * - * @method Phaser.Structs.Set#get - * @since 3.0.0 - * - * @genericUse {T} - [value,$return] - * - * @param {string} property - The property name to check on the elements of this Set. - * @param {*} value - The value to check for. - * - * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. - */ - get: function (property, value) - { - for (var i = 0; i < this.entries.length; i++) - { - var entry = this.entries[i]; - - if (entry[property] === value) - { - return entry; - } - } - }, - - /** - * Returns an array containing all the values in this Set. - * - * @method Phaser.Structs.Set#getArray - * @since 3.0.0 - * - * @genericUse {T[]} - [$return] - * - * @return {Array.<*>} An array containing all the values in this Set. - */ - getArray: function () - { - return this.entries.slice(0); - }, - - /** - * Removes the given value from this Set if this Set contains that value. - * - * @method Phaser.Structs.Set#delete - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {*} value - The value to remove from the Set. - * - * @return {Phaser.Structs.Set} This Set object. - */ - delete: function (value) - { - var index = this.entries.indexOf(value); - - if (index > -1) - { - this.entries.splice(index, 1); - } - - return this; - }, - - /** - * Dumps the contents of this Set to the console via `console.group`. - * - * @method Phaser.Structs.Set#dump - * @since 3.0.0 - */ - dump: function () - { - // eslint-disable-next-line no-console - console.group('Set'); - - for (var i = 0; i < this.entries.length; i++) - { - var entry = this.entries[i]; - console.log(entry); - } - - // eslint-disable-next-line no-console - console.groupEnd(); - }, - - /** - * Passes each value in this Set to the given callback. - * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. - * - * @method Phaser.Structs.Set#each - * @since 3.0.0 - * - * @genericUse {EachSetCallback.} - [callback] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. - * @param {*} [callbackScope] - The scope of the callback. - * - * @return {Phaser.Structs.Set} This Set object. - */ - each: function (callback, callbackScope) - { - var i; - var temp = this.entries.slice(); - var len = temp.length; - - if (callbackScope) - { - for (i = 0; i < len; i++) - { - if (callback.call(callbackScope, temp[i], i) === false) - { - break; - } - } - } - else - { - for (i = 0; i < len; i++) - { - if (callback(temp[i], i) === false) - { - break; - } - } - } - - return this; - }, - - /** - * Passes each value in this Set to the given callback. - * For when you absolutely know this Set won't be modified during the iteration. - * - * @method Phaser.Structs.Set#iterate - * @since 3.0.0 - * - * @genericUse {EachSetCallback.} - [callback] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. - * @param {*} [callbackScope] - The scope of the callback. - * - * @return {Phaser.Structs.Set} This Set object. - */ - iterate: function (callback, callbackScope) - { - var i; - var len = this.entries.length; - - if (callbackScope) - { - for (i = 0; i < len; i++) - { - if (callback.call(callbackScope, this.entries[i], i) === false) - { - break; - } - } - } - else - { - for (i = 0; i < len; i++) - { - if (callback(this.entries[i], i) === false) - { - break; - } - } - } - - return this; - }, - - /** - * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. - * - * @method Phaser.Structs.Set#iterateLocal - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {string} callbackKey - The key of the function to be invoked on each Set entry. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - * - * @return {Phaser.Structs.Set} This Set object. - */ - iterateLocal: function (callbackKey) - { - var i; - var args = []; - - for (i = 1; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - var len = this.entries.length; - - for (i = 0; i < len; i++) - { - var entry = this.entries[i]; - - entry[callbackKey].apply(entry, args); - } - - return this; - }, - - /** - * Clears this Set so that it no longer contains any values. - * - * @method Phaser.Structs.Set#clear - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @return {Phaser.Structs.Set} This Set object. - */ - clear: function () - { - this.entries.length = 0; - - return this; - }, - - /** - * Returns `true` if this Set contains the given value, otherwise returns `false`. - * - * @method Phaser.Structs.Set#contains - * @since 3.0.0 - * - * @genericUse {T} - [value] - * - * @param {*} value - The value to check for in this Set. - * - * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. - */ - contains: function (value) - { - return (this.entries.indexOf(value) > -1); - }, - - /** - * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. - * - * @method Phaser.Structs.Set#union - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to perform the union with. - * - * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. - */ - union: function (set) - { - var newSet = new Set(); - - set.entries.forEach(function (value) - { - newSet.set(value); - }); - - this.entries.forEach(function (value) - { - newSet.set(value); - }); - - return newSet; - }, - - /** - * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. - * - * @method Phaser.Structs.Set#intersect - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to intersect this set with. - * - * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. - */ - intersect: function (set) - { - var newSet = new Set(); - - this.entries.forEach(function (value) - { - if (set.contains(value)) - { - newSet.set(value); - } - }); - - return newSet; - }, - - /** - * Returns a new Set containing all the values in this Set which are *not* also in the given Set. - * - * @method Phaser.Structs.Set#difference - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to perform the difference with. - * - * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. - */ - difference: function (set) - { - var newSet = new Set(); - - this.entries.forEach(function (value) - { - if (!set.contains(value)) - { - newSet.set(value); - } - }); - - return newSet; - }, - - /** - * The size of this Set. This is the number of entries within it. - * Changing the size will truncate the Set if the given value is smaller than the current size. - * Increasing the size larger than the current size has no effect. - * - * @name Phaser.Structs.Set#size - * @type {integer} - * @since 3.0.0 - */ - size: { - - get: function () - { - return this.entries.length; - }, - - set: function (value) - { - if (value < this.entries.length) - { - return this.entries.length = value; - } - else - { - return this.entries.length; - } - } - - } - -}); - -module.exports = Set; - - -/***/ }), -/* 128 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -25942,7 +25932,7 @@ module.exports = Set; var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var MeshRender = __webpack_require__(1068); +var MeshRender = __webpack_require__(1065); var NOOP = __webpack_require__(1); /** @@ -26101,7 +26091,7 @@ module.exports = Mesh; /***/ }), -/* 129 */ +/* 131 */ /***/ (function(module, exports) { /** @@ -26139,7 +26129,7 @@ module.exports = RectangleToRectangle; /***/ }), -/* 130 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26247,7 +26237,7 @@ module.exports = InputPluginCache; /***/ }), -/* 131 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26262,19 +26252,19 @@ module.exports = InputPluginCache; module.exports = { - ANY_KEY_DOWN: __webpack_require__(1207), - ANY_KEY_UP: __webpack_require__(1208), - COMBO_MATCH: __webpack_require__(1209), - DOWN: __webpack_require__(1210), - KEY_DOWN: __webpack_require__(1211), - KEY_UP: __webpack_require__(1212), - UP: __webpack_require__(1213) + ANY_KEY_DOWN: __webpack_require__(1203), + ANY_KEY_UP: __webpack_require__(1204), + COMBO_MATCH: __webpack_require__(1205), + DOWN: __webpack_require__(1206), + KEY_DOWN: __webpack_require__(1207), + KEY_UP: __webpack_require__(1208), + UP: __webpack_require__(1209) }; /***/ }), -/* 132 */ +/* 134 */ /***/ (function(module, exports) { /** @@ -26315,7 +26305,7 @@ module.exports = GetURL; /***/ }), -/* 133 */ +/* 135 */ /***/ (function(module, exports) { /** @@ -26335,18 +26325,16 @@ module.exports = GetURL; * @param {string} [user=''] - Optional username for the XHR request. * @param {string} [password=''] - Optional password for the XHR request. * @param {integer} [timeout=0] - Optional XHR timeout value. - * @param {boolean} [withCredentials=false] - Optional XHR withCredentials value. * * @return {Phaser.Types.Loader.XHRSettingsObject} The XHRSettings object as used by the Loader. */ -var XHRSettings = function (responseType, async, user, password, timeout, withCredentials) +var XHRSettings = function (responseType, async, user, password, timeout) { if (responseType === undefined) { responseType = ''; } if (async === undefined) { async = true; } if (user === undefined) { user = ''; } if (password === undefined) { password = ''; } if (timeout === undefined) { timeout = 0; } - if (withCredentials === undefined) { withCredentials = false; } // Before sending a request, set the xhr.responseType to "text", // "arraybuffer", "blob", or "document", depending on your data needs. @@ -26372,10 +26360,7 @@ var XHRSettings = function (responseType, async, user, password, timeout, withCr requestedWith: false, // overrideMimeType - overrideMimeType: undefined, - - // withCredentials - withCredentials: withCredentials + overrideMimeType: undefined }; }; @@ -26384,7 +26369,7 @@ module.exports = XHRSettings; /***/ }), -/* 134 */ +/* 136 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26394,8 +26379,8 @@ module.exports = XHRSettings; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(212); -var Sprite = __webpack_require__(73); +var Components = __webpack_require__(214); +var Sprite = __webpack_require__(69); /** * @classdesc @@ -26485,7 +26470,7 @@ module.exports = ArcadeSprite; /***/ }), -/* 135 */ +/* 137 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26500,54 +26485,54 @@ module.exports = ArcadeSprite; module.exports = { - CalculateFacesAt: __webpack_require__(215), + CalculateFacesAt: __webpack_require__(217), CalculateFacesWithin: __webpack_require__(51), - Copy: __webpack_require__(1303), - CreateFromTiles: __webpack_require__(1304), - CullTiles: __webpack_require__(1305), - Fill: __webpack_require__(1307), - FilterTiles: __webpack_require__(1308), - FindByIndex: __webpack_require__(1309), - FindTile: __webpack_require__(1310), - ForEachTile: __webpack_require__(1311), - GetTileAt: __webpack_require__(136), - GetTileAtWorldXY: __webpack_require__(1312), - GetTilesWithin: __webpack_require__(25), - GetTilesWithinShape: __webpack_require__(1313), - GetTilesWithinWorldXY: __webpack_require__(1314), - HasTileAt: __webpack_require__(469), - HasTileAtWorldXY: __webpack_require__(1315), - IsInLayerBounds: __webpack_require__(99), - PutTileAt: __webpack_require__(216), - PutTileAtWorldXY: __webpack_require__(1316), - PutTilesAt: __webpack_require__(1317), - Randomize: __webpack_require__(1318), - RemoveTileAt: __webpack_require__(470), - RemoveTileAtWorldXY: __webpack_require__(1319), - RenderDebug: __webpack_require__(1320), - ReplaceByIndex: __webpack_require__(468), - SetCollision: __webpack_require__(1321), - SetCollisionBetween: __webpack_require__(1322), - SetCollisionByExclusion: __webpack_require__(1323), - SetCollisionByProperty: __webpack_require__(1324), - SetCollisionFromCollisionGroup: __webpack_require__(1325), - SetTileIndexCallback: __webpack_require__(1326), - SetTileLocationCallback: __webpack_require__(1327), - Shuffle: __webpack_require__(1328), - SwapByIndex: __webpack_require__(1329), - TileToWorldX: __webpack_require__(1330), - TileToWorldXY: __webpack_require__(1331), - TileToWorldY: __webpack_require__(1332), - WeightedRandomize: __webpack_require__(1333), - WorldToTileX: __webpack_require__(471), - WorldToTileXY: __webpack_require__(1334), - WorldToTileY: __webpack_require__(472) + Copy: __webpack_require__(1301), + CreateFromTiles: __webpack_require__(1302), + CullTiles: __webpack_require__(1303), + Fill: __webpack_require__(1304), + FilterTiles: __webpack_require__(1305), + FindByIndex: __webpack_require__(1306), + FindTile: __webpack_require__(1307), + ForEachTile: __webpack_require__(1308), + GetTileAt: __webpack_require__(138), + GetTileAtWorldXY: __webpack_require__(1309), + GetTilesWithin: __webpack_require__(24), + GetTilesWithinShape: __webpack_require__(1310), + GetTilesWithinWorldXY: __webpack_require__(1311), + HasTileAt: __webpack_require__(470), + HasTileAtWorldXY: __webpack_require__(1312), + IsInLayerBounds: __webpack_require__(103), + PutTileAt: __webpack_require__(218), + PutTileAtWorldXY: __webpack_require__(1313), + PutTilesAt: __webpack_require__(1314), + Randomize: __webpack_require__(1315), + RemoveTileAt: __webpack_require__(471), + RemoveTileAtWorldXY: __webpack_require__(1316), + RenderDebug: __webpack_require__(1317), + ReplaceByIndex: __webpack_require__(469), + SetCollision: __webpack_require__(1318), + SetCollisionBetween: __webpack_require__(1319), + SetCollisionByExclusion: __webpack_require__(1320), + SetCollisionByProperty: __webpack_require__(1321), + SetCollisionFromCollisionGroup: __webpack_require__(1322), + SetTileIndexCallback: __webpack_require__(1323), + SetTileLocationCallback: __webpack_require__(1324), + Shuffle: __webpack_require__(1325), + SwapByIndex: __webpack_require__(1326), + TileToWorldX: __webpack_require__(139), + TileToWorldXY: __webpack_require__(1327), + TileToWorldY: __webpack_require__(140), + WeightedRandomize: __webpack_require__(1328), + WorldToTileX: __webpack_require__(63), + WorldToTileXY: __webpack_require__(1329), + WorldToTileY: __webpack_require__(64) }; /***/ }), -/* 136 */ +/* 138 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26556,7 +26541,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var IsInLayerBounds = __webpack_require__(99); +var IsInLayerBounds = __webpack_require__(103); /** * Gets a tile at the given tile coordinates from the given layer. @@ -26603,7 +26588,97 @@ module.exports = GetTileAt; /***/ }), -/* 137 */ +/* 139 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldX + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var TileToWorldX = function (tileX, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + var layerWorldX = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + + tileWidth *= tilemapLayer.scaleX; + } + + return layerWorldX + tileX * tileWidth; +}; + +module.exports = TileToWorldX; + + +/***/ }), +/* 140 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldY + * @private + * @since 3.0.0 + * + * @param {integer} tileY - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var TileToWorldY = function (tileY, camera, layer) +{ + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + return layerWorldY + tileY * tileHeight; +}; + +module.exports = TileToWorldY; + + +/***/ }), +/* 141 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -27007,7 +27082,7 @@ module.exports = Tileset; /***/ }), -/* 138 */ +/* 142 */ /***/ (function(module, exports) { /** @@ -27071,7 +27146,7 @@ module.exports = GetNewValue; /***/ }), -/* 139 */ +/* 143 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -27080,17 +27155,17 @@ module.exports = GetNewValue; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Defaults = __webpack_require__(225); +var Defaults = __webpack_require__(227); var GetAdvancedValue = __webpack_require__(15); -var GetBoolean = __webpack_require__(86); -var GetEaseFunction = __webpack_require__(67); -var GetNewValue = __webpack_require__(138); -var GetProps = __webpack_require__(493); -var GetTargets = __webpack_require__(223); +var GetBoolean = __webpack_require__(88); +var GetEaseFunction = __webpack_require__(82); +var GetNewValue = __webpack_require__(142); +var GetProps = __webpack_require__(492); +var GetTargets = __webpack_require__(225); var GetValue = __webpack_require__(6); -var GetValueOp = __webpack_require__(224); -var Tween = __webpack_require__(226); -var TweenData = __webpack_require__(228); +var GetValueOp = __webpack_require__(226); +var Tween = __webpack_require__(228); +var TweenData = __webpack_require__(230); /** * Creates a new Tween. @@ -27204,7 +27279,7 @@ module.exports = TweenBuilder; /***/ }), -/* 140 */ +/* 144 */ /***/ (function(module, exports) { /** @@ -27238,777 +27313,8 @@ module.exports = Equal; /***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); -var Utils = __webpack_require__(9); - -/** - * @classdesc - * WebGLPipeline is a class that describes the way elements will be renderered - * in WebGL, specially focused on batching vertices (batching is not provided). - * Pipelines are mostly used for describing 2D rendering passes but it's - * flexible enough to be used for any type of rendering including 3D. - * Internally WebGLPipeline will handle things like compiling shaders, - * creating vertex buffers, assigning primitive topology and binding - * vertex attributes. - * - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - gl: Current WebGL context. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - vertices: An optional buffer of vertices - * - attributes: An array describing the vertex attributes - * - * The vertex attributes properties are: - * - name : String - Name of the attribute in the vertex shader - * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 - * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) - * - normalized : boolean - Is the attribute normalized - * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C - * Here you can find more information of how to describe an attribute: - * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer - * - * @class WebGLPipeline - * @memberof Phaser.Renderer.WebGL - * @constructor - * @since 3.0.0 - * - * @param {object} config - The configuration object for this WebGL Pipeline, as described above. - */ -var WebGLPipeline = new Class({ - - initialize: - - function WebGLPipeline (config) - { - /** - * Name of the Pipeline. Used for identifying - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#name - * @type {string} - * @since 3.0.0 - */ - this.name = 'WebGLPipeline'; - - /** - * The Game which owns this WebGL Pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = config.game; - - /** - * The canvas which this WebGL Pipeline renders to. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#view - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.view = config.game.canvas; - - /** - * Used to store the current game resolution - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution - * @type {number} - * @since 3.0.0 - */ - this.resolution = 1; - - /** - * Width of the current viewport - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#width - * @type {number} - * @since 3.0.0 - */ - this.width = 0; - - /** - * Height of the current viewport - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#height - * @type {number} - * @since 3.0.0 - */ - this.height = 0; - - /** - * The WebGL context this WebGL Pipeline uses. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#gl - * @type {WebGLRenderingContext} - * @since 3.0.0 - */ - this.gl = config.gl; - - /** - * How many vertices have been fed to the current pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.vertexCount = 0; - - /** - * The limit of vertices that the pipeline can hold - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity - * @type {integer} - * @since 3.0.0 - */ - this.vertexCapacity = config.vertexCapacity; - - /** - * The WebGL Renderer which owns this WebGL Pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer - * @type {Phaser.Renderer.WebGL.WebGLRenderer} - * @since 3.0.0 - */ - this.renderer = config.renderer; - - /** - * Raw byte buffer of vertices. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData - * @type {ArrayBuffer} - * @since 3.0.0 - */ - this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); - - /** - * The handle to a WebGL vertex buffer object. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer - * @type {WebGLBuffer} - * @since 3.0.0 - */ - this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); - - /** - * The handle to a WebGL program - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#program - * @type {WebGLProgram} - * @since 3.0.0 - */ - this.program = this.renderer.createProgram(config.vertShader, config.fragShader); - - /** - * Array of objects that describe the vertex attributes - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes - * @type {object} - * @since 3.0.0 - */ - this.attributes = config.attributes; - - /** - * The size in bytes of the vertex - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize - * @type {integer} - * @since 3.0.0 - */ - this.vertexSize = config.vertexSize; - - /** - * The primitive topology which the pipeline will use to submit draw calls - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#topology - * @type {integer} - * @since 3.0.0 - */ - this.topology = config.topology; - - /** - * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources - * to the GPU. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes - * @type {Uint8Array} - * @since 3.0.0 - */ - this.bytes = new Uint8Array(this.vertexData); - - /** - * This will store the amount of components of 32 bit length - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount - * @type {integer} - * @since 3.0.0 - */ - this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); - - /** - * Indicates if the current pipeline is flushing the contents to the GPU. - * When the variable is set the flush function will be locked. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked - * @type {boolean} - * @since 3.1.0 - */ - this.flushLocked = false; - - /** - * Indicates if the current pipeline is active or not for this frame only. - * Reset in the onRender method. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#active - * @type {boolean} - * @since 3.10.0 - */ - this.active = false; - }, - - /** - * Called when the Game has fully booted and the Renderer has finished setting up. - * - * By this stage all Game level systems are now in place and you can perform any final - * tasks that the pipeline may need that relied on game systems such as the Texture Manager. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#boot - * @since 3.11.0 - */ - boot: function () - { - }, - - /** - * Adds a description of vertex attribute to the pipeline - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute - * @since 3.2.0 - * - * @param {string} name - Name of the vertex attribute - * @param {integer} size - Vertex component size - * @param {integer} type - Type of the attribute - * @param {boolean} normalized - Is the value normalized to a range - * @param {integer} offset - Byte offset to the beginning of the first element in the vertex - * - * @return {this} This WebGLPipeline instance. - */ - addAttribute: function (name, size, type, normalized, offset) - { - this.attributes.push({ - name: name, - size: size, - type: this.renderer.glFormats[type], - normalized: normalized, - offset: offset - }); - - this.vertexComponentCount = Utils.getComponentCount( - this.attributes, - this.gl - ); - return this; - }, - - /** - * Check if the current batch of vertices is full. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush - * @since 3.0.0 - * - * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. - */ - shouldFlush: function () - { - return (this.vertexCount >= this.vertexCapacity); - }, - - /** - * Resizes the properties used to describe the viewport - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#resize - * @since 3.0.0 - * - * @param {number} width - The new width of this WebGL Pipeline. - * @param {number} height - The new height of this WebGL Pipeline. - * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - this.width = width * resolution; - this.height = height * resolution; - this.resolution = resolution; - - return this; - }, - - /** - * Binds the pipeline resources, including programs, vertex buffers and binds attributes - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#bind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - bind: function () - { - var gl = this.gl; - var vertexBuffer = this.vertexBuffer; - var attributes = this.attributes; - var program = this.program; - var renderer = this.renderer; - var vertexSize = this.vertexSize; - - renderer.setProgram(program); - renderer.setVertexBuffer(vertexBuffer); - - for (var index = 0; index < attributes.length; ++index) - { - var element = attributes[index]; - var location = gl.getAttribLocation(program, element.name); - - if (location >= 0) - { - gl.enableVertexAttribArray(location); - gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); - } - else if (location !== -1) - { - gl.disableVertexAttribArray(location); - } - } - - return this; - }, - - /** - * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. - * - * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - // This is for updating uniform data it's called on each bind attempt. - return this; - }, - - /** - * Called before each frame is rendered, but after the canvas has been cleared. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onPreRender: function () - { - // called once every frame - return this; - }, - - /** - * Called before a Scene's Camera is rendered. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene being rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. - * - * @return {this} This WebGLPipeline instance. - */ - onRender: function () - { - // called for each camera - return this; - }, - - /** - * Called after each frame has been completely rendered and snapshots have been taken. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onPostRender: function () - { - // called once every frame - return this; - }, - - /** - * Uploads the vertex data and emits a draw call - * for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#flush - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - flush: function () - { - if (this.flushLocked) { return this; } - - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - - if (vertexCount === 0) - { - this.flushLocked = false; - return; - } - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); - gl.drawArrays(topology, 0, vertexCount); - - this.vertexCount = 0; - this.flushLocked = false; - - return this; - }, - - /** - * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - destroy: function () - { - var gl = this.gl; - - gl.deleteProgram(this.program); - gl.deleteBuffer(this.vertexBuffer); - - delete this.program; - delete this.vertexBuffer; - delete this.gl; - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new value of the `float` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat1: function (name, x) - { - this.renderer.setFloat1(this.program, name, x); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new X component of the `vec2` uniform. - * @param {number} y - The new Y component of the `vec2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat2: function (name, x, y) - { - this.renderer.setFloat2(this.program, name, x, y); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new X component of the `vec3` uniform. - * @param {number} y - The new Y component of the `vec3` uniform. - * @param {number} z - The new Z component of the `vec3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat3: function (name, x, y, z) - { - this.renderer.setFloat3(this.program, name, x, y, z); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - X component of the uniform - * @param {number} y - Y component of the uniform - * @param {number} z - Z component of the uniform - * @param {number} w - W component of the uniform - * - * @return {this} This WebGLPipeline instance. - */ - setFloat4: function (name, x, y, z, w) - { - this.renderer.setFloat4(this.program, name, x, y, z, w); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat1v: function (name, arr) - { - this.renderer.setFloat1v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat2v: function (name, arr) - { - this.renderer.setFloat2v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat3v: function (name, arr) - { - this.renderer.setFloat3v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat4v: function (name, arr) - { - this.renderer.setFloat4v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new value of the `int` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt1: function (name, x) - { - this.renderer.setInt1(this.program, name, x); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new X component of the `ivec2` uniform. - * @param {integer} y - The new Y component of the `ivec2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt2: function (name, x, y) - { - this.renderer.setInt2(this.program, name, x, y); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new X component of the `ivec3` uniform. - * @param {integer} y - The new Y component of the `ivec3` uniform. - * @param {integer} z - The new Z component of the `ivec3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt3: function (name, x, y, z) - { - this.renderer.setInt3(this.program, name, x, y, z); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - X component of the uniform - * @param {integer} y - Y component of the uniform - * @param {integer} z - Z component of the uniform - * @param {integer} w - W component of the uniform - * - * @return {this} This WebGLPipeline instance. - */ - setInt4: function (name, x, y, z, w) - { - this.renderer.setInt4(this.program, name, x, y, z, w); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. - * @param {Float32Array} matrix - The new values for the `mat2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix2: function (name, transpose, matrix) - { - this.renderer.setMatrix2(this.program, name, transpose, matrix); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. - * @param {Float32Array} matrix - The new values for the `mat3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix3: function (name, transpose, matrix) - { - this.renderer.setMatrix3(this.program, name, transpose, matrix); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Should the matrix be transpose - * @param {Float32Array} matrix - Matrix data - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix4: function (name, transpose, matrix) - { - this.renderer.setMatrix4(this.program, name, transpose, matrix); - - return this; - } - -}); - -module.exports = WebGLPipeline; - - -/***/ }), -/* 142 */, -/* 143 */ +/* 145 */, +/* 146 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -28047,7 +27353,7 @@ module.exports = CircumferencePoint; /***/ }), -/* 144 */ +/* 147 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -28091,7 +27397,7 @@ module.exports = Random; /***/ }), -/* 145 */ +/* 148 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -28100,12 +27406,12 @@ module.exports = Random; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(107); -var FindClosestInSorted = __webpack_require__(265); -var Frame = __webpack_require__(266); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(111); +var FindClosestInSorted = __webpack_require__(267); +var Frame = __webpack_require__(268); var GetValue = __webpack_require__(6); /** @@ -28320,7 +27626,7 @@ var Animation = new Class({ * @method Phaser.Animations.Animation#addFrame * @since 3.0.0 * - * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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|Phaser.Types.Animations.AnimationFrame[])} config - [description] * * @return {Phaser.Animations.Animation} This Animation object. */ @@ -28336,7 +27642,7 @@ var Animation = new Class({ * @since 3.0.0 * * @param {integer} index - The index to insert the frame at within the animation. - * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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|Phaser.Types.Animations.AnimationFrame[])} config - [description] * * @return {Phaser.Animations.Animation} This Animation object. */ @@ -28384,14 +27690,13 @@ var Animation = new Class({ }, /** - * Called internally when this Animation completes playback. - * Optionally, hides the parent Game Object, then stops playback. + * [description] * * @method Phaser.Animations.Animation#completeAnimation * @protected * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ completeAnimation: function (component) { @@ -28404,15 +27709,14 @@ var Animation = new Class({ }, /** - * Called internally when this Animation first starts to play. - * Sets the accumulator and nextTick properties. + * [description] * * @method Phaser.Animations.Animation#getFirstTick * @protected * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - * @param {boolean} [includeDelay=true] - If `true` the Animation Components delay value will be added to the `nextTick` total. + * @param {Phaser.GameObjects.Components.Animation} component - [description] + * @param {boolean} [includeDelay=true] - [description] */ getFirstTick: function (component, includeDelay) { @@ -28445,16 +27749,16 @@ var Animation = new Class({ }, /** - * Creates AnimationFrame instances based on the given frame data. + * [description] * * @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. + * @param {Phaser.Textures.TextureManager} textureManager - [description] + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} frames - [description] + * @param {string} [defaultTextureKey] - [description] * - * @return {Phaser.Animations.AnimationFrame[]} An array of newly created AnimationFrame instances. + * @return {Phaser.Animations.AnimationFrame[]} [description] */ getFrames: function (textureManager, frames, defaultTextureKey) { @@ -28547,12 +27851,12 @@ var Animation = new Class({ }, /** - * Called internally. Sets the accumulator and nextTick values of the current Animation. + * [description] * * @method Phaser.Animations.Animation#getNextTick * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ getNextTick: function (component) { @@ -28722,13 +28026,12 @@ var Animation = new Class({ }, /** - * Called internally when the Animation is playing backwards. - * Sets the previous frame, causing a yoyo, repeat, complete or update, accordingly. + * [description] * * @method Phaser.Animations.Animation#previousFrame * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ previousFrame: function (component) { @@ -28786,13 +28089,12 @@ var Animation = new Class({ }, /** - * Removes the given AnimationFrame from this Animation instance. - * This is a global action. Any Game Object using this Animation will be impacted by this change. + * [description] * * @method Phaser.Animations.Animation#removeFrame * @since 3.0.0 * - * @param {Phaser.Animations.AnimationFrame} frame - The AnimationFrame to be removed. + * @param {Phaser.Animations.AnimationFrame} frame - [description] * * @return {Phaser.Animations.Animation} This Animation object. */ @@ -28829,8 +28131,7 @@ var Animation = new Class({ }, /** - * Called internally during playback. Forces the animation to repeat, providing there are enough counts left - * in the repeat counter. + * [description] * * @method Phaser.Animations.Animation#repeatAnimation * @fires Phaser.Animations.Events#ANIMATION_REPEAT @@ -28838,7 +28139,7 @@ var Animation = new Class({ * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ repeatAnimation: function (component) { @@ -28883,7 +28184,7 @@ var Animation = new Class({ * @method Phaser.Animations.Animation#setFrame * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ setFrame: function (component) { @@ -28904,7 +28205,7 @@ var Animation = new Class({ * @method Phaser.Animations.Animation#toJSON * @since 3.0.0 * - * @return {Phaser.Types.Animations.JSONAnimation} The resulting JSONAnimation formatted object. + * @return {Phaser.Types.Animations.JSONAnimation} [description] */ toJSON: function () { @@ -28932,7 +28233,7 @@ var Animation = new Class({ }, /** - * Called internally whenever frames are added to, or removed from, this Animation. + * [description] * * @method Phaser.Animations.Animation#updateFrameSequence * @since 3.0.0 @@ -28989,7 +28290,7 @@ var Animation = new Class({ }, /** - * Pauses playback of this Animation. The paused state is set immediately. + * [description] * * @method Phaser.Animations.Animation#pause * @since 3.0.0 @@ -29004,7 +28305,7 @@ var Animation = new Class({ }, /** - * Resumes playback of this Animation. The paused state is reset immediately. + * [description] * * @method Phaser.Animations.Animation#resume * @since 3.0.0 @@ -29019,9 +28320,7 @@ var Animation = new Class({ }, /** - * Destroys this Animation instance. It will remove all event listeners, - * remove this animation and its key from the global Animation Manager, - * and then destroy all Animation Frames in turn. + * [description] * * @method Phaser.Animations.Animation#destroy * @since 3.0.0 @@ -29051,7 +28350,7 @@ module.exports = Animation; /***/ }), -/* 146 */ +/* 149 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29060,26 +28359,22 @@ module.exports = Animation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Perimeter = __webpack_require__(108); +var Perimeter = __webpack_require__(112); var Point = __webpack_require__(4); /** - * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. - * - * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. - * - * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. + * Position is a value between 0 and 1 where 0 = the top-left of the rectangle and 0.5 = the bottom right. * * @function Phaser.Geom.Rectangle.GetPoint * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. - * @param {number} position - The normalized distance into the Rectangle's perimeter to return. - * @param {(Phaser.Geom.Point|object)} [out] - An object to update with the `x` and `y` coordinates of the point. + * @param {Phaser.Geom.Rectangle} rectangle - [description] + * @param {number} position - [description] + * @param {(Phaser.Geom.Point|object)} [out] - [description] * - * @return {Phaser.Geom.Point} The updated `output` object, or a new Point if no `output` object was given. + * @return {Phaser.Geom.Point} [description] */ var GetPoint = function (rectangle, position, out) { @@ -29132,7 +28427,7 @@ module.exports = GetPoint; /***/ }), -/* 147 */ +/* 150 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29197,7 +28492,7 @@ module.exports = GetPoints; /***/ }), -/* 148 */ +/* 151 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29237,7 +28532,7 @@ module.exports = Random; /***/ }), -/* 149 */ +/* 152 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29275,7 +28570,7 @@ module.exports = Random; /***/ }), -/* 150 */ +/* 153 */ /***/ (function(module, exports) { /** @@ -29404,7 +28699,7 @@ module.exports = Pipeline; /***/ }), -/* 151 */ +/* 154 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29445,7 +28740,7 @@ module.exports = Random; /***/ }), -/* 152 */ +/* 155 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29457,17 +28752,17 @@ module.exports = Random; var Point = __webpack_require__(4); /** - * Returns a random Point from within the area of the given Triangle. + * [description] * * @function Phaser.Geom.Triangle.Random * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get a random point from. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Triangle} triangle - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of a random position within the Triangle. + * @return {Phaser.Geom.Point} [description] */ var Random = function (triangle, out) { @@ -29501,7 +28796,7 @@ module.exports = Random; /***/ }), -/* 153 */ +/* 156 */ /***/ (function(module, exports) { /** @@ -29538,7 +28833,7 @@ module.exports = RotateAroundDistance; /***/ }), -/* 154 */ +/* 157 */ /***/ (function(module, exports) { /** @@ -29577,7 +28872,7 @@ module.exports = SmootherStep; /***/ }), -/* 155 */ +/* 158 */ /***/ (function(module, exports) { /** @@ -29624,7 +28919,7 @@ module.exports = SmoothStep; /***/ }), -/* 156 */ +/* 159 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29997,7 +29292,7 @@ module.exports = Map; /***/ }), -/* 157 */ +/* 160 */ /***/ (function(module, exports) { /** @@ -30073,7 +29368,7 @@ module.exports = Pad; /***/ }), -/* 158 */ +/* 161 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30082,10 +29377,10 @@ module.exports = Pad; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HexStringToColor = __webpack_require__(289); -var IntegerToColor = __webpack_require__(292); -var ObjectToColor = __webpack_require__(294); -var RGBStringToColor = __webpack_require__(295); +var HexStringToColor = __webpack_require__(291); +var IntegerToColor = __webpack_require__(294); +var ObjectToColor = __webpack_require__(296); +var RGBStringToColor = __webpack_require__(297); /** * Converts the given source color value into an instance of a Color class. @@ -30129,7 +29424,7 @@ module.exports = ValueToColor; /***/ }), -/* 159 */ +/* 162 */ /***/ (function(module, exports) { /** @@ -30159,7 +29454,7 @@ module.exports = GetColor; /***/ }), -/* 160 */ +/* 163 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30168,7 +29463,7 @@ module.exports = GetColor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetColor = __webpack_require__(159); +var GetColor = __webpack_require__(162); /** * Converts an HSV (hue, saturation and value) color value to RGB. @@ -30260,7 +29555,7 @@ module.exports = HSVToRGB; /***/ }), -/* 161 */ +/* 164 */ /***/ (function(module, exports) { /** @@ -30392,7 +29687,7 @@ module.exports = Smoothing(); /***/ }), -/* 162 */ +/* 165 */ /***/ (function(module, exports) { /** @@ -30429,7 +29724,7 @@ module.exports = CenterOn; /***/ }), -/* 163 */ +/* 166 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30438,18 +29733,18 @@ module.exports = CenterOn; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Back = __webpack_require__(297); -var Bounce = __webpack_require__(298); -var Circular = __webpack_require__(299); -var Cubic = __webpack_require__(300); -var Elastic = __webpack_require__(301); -var Expo = __webpack_require__(302); -var Linear = __webpack_require__(303); -var Quadratic = __webpack_require__(304); -var Quartic = __webpack_require__(305); -var Quintic = __webpack_require__(306); -var Sine = __webpack_require__(307); -var Stepped = __webpack_require__(308); +var Back = __webpack_require__(299); +var Bounce = __webpack_require__(300); +var Circular = __webpack_require__(301); +var Cubic = __webpack_require__(302); +var Elastic = __webpack_require__(303); +var Expo = __webpack_require__(304); +var Linear = __webpack_require__(305); +var Quadratic = __webpack_require__(306); +var Quartic = __webpack_require__(307); +var Quintic = __webpack_require__(308); +var Sine = __webpack_require__(309); +var Stepped = __webpack_require__(310); // EaseMap module.exports = { @@ -30510,7 +29805,7 @@ module.exports = { /***/ }), -/* 164 */ +/* 167 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30519,9 +29814,9 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var OS = __webpack_require__(112); -var Browser = __webpack_require__(113); -var CanvasPool = __webpack_require__(27); +var OS = __webpack_require__(116); +var Browser = __webpack_require__(117); +var CanvasPool = __webpack_require__(26); /** * Determines the features of the browser running this Phaser Game instance. @@ -30702,7 +29997,7 @@ module.exports = init(); /***/ }), -/* 165 */ +/* 168 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30711,8 +30006,8 @@ module.exports = init(); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(13); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Math @@ -30721,8 +30016,8 @@ var Extend = __webpack_require__(18); var PhaserMath = { // Collections of functions - Angle: __webpack_require__(726), - Distance: __webpack_require__(734), + Angle: __webpack_require__(725), + Distance: __webpack_require__(733), Easing: __webpack_require__(739), Fuzzy: __webpack_require__(740), Interpolation: __webpack_require__(743), @@ -30734,48 +30029,48 @@ var PhaserMath = { // Single functions Average: __webpack_require__(753), - Bernstein: __webpack_require__(318), - Between: __webpack_require__(167), - CatmullRom: __webpack_require__(166), + Bernstein: __webpack_require__(319), + Between: __webpack_require__(170), + CatmullRom: __webpack_require__(169), CeilTo: __webpack_require__(754), - Clamp: __webpack_require__(23), + Clamp: __webpack_require__(22), DegToRad: __webpack_require__(35), Difference: __webpack_require__(755), - Factorial: __webpack_require__(319), - FloatBetween: __webpack_require__(325), + Factorial: __webpack_require__(320), + FloatBetween: __webpack_require__(326), FloorTo: __webpack_require__(756), - FromPercent: __webpack_require__(85), + FromPercent: __webpack_require__(87), GetSpeed: __webpack_require__(757), IsEven: __webpack_require__(758), IsEvenStrict: __webpack_require__(759), - Linear: __webpack_require__(111), + Linear: __webpack_require__(115), MaxAdd: __webpack_require__(760), MinSub: __webpack_require__(761), Percent: __webpack_require__(762), - RadToDeg: __webpack_require__(168), + RadToDeg: __webpack_require__(171), RandomXY: __webpack_require__(763), RandomXYZ: __webpack_require__(764), RandomXYZW: __webpack_require__(765), - Rotate: __webpack_require__(326), - RotateAround: __webpack_require__(271), - RotateAroundDistance: __webpack_require__(153), - RoundAwayFromZero: __webpack_require__(327), + Rotate: __webpack_require__(327), + RotateAround: __webpack_require__(273), + RotateAroundDistance: __webpack_require__(156), + RoundAwayFromZero: __webpack_require__(328), RoundTo: __webpack_require__(766), SinCosTableGenerator: __webpack_require__(767), - SmootherStep: __webpack_require__(154), - SmoothStep: __webpack_require__(155), + SmootherStep: __webpack_require__(157), + SmoothStep: __webpack_require__(158), ToXY: __webpack_require__(768), - TransformXY: __webpack_require__(328), + TransformXY: __webpack_require__(329), Within: __webpack_require__(769), Wrap: __webpack_require__(58), // Vector classes Vector2: __webpack_require__(3), - Vector3: __webpack_require__(169), - Vector4: __webpack_require__(329), - Matrix3: __webpack_require__(330), - Matrix4: __webpack_require__(331), - Quaternion: __webpack_require__(332), + Vector3: __webpack_require__(172), + Vector4: __webpack_require__(330), + Matrix3: __webpack_require__(331), + Matrix4: __webpack_require__(332), + Quaternion: __webpack_require__(333), RotateVec3: __webpack_require__(770) }; @@ -30790,7 +30085,7 @@ module.exports = PhaserMath; /***/ }), -/* 166 */ +/* 169 */ /***/ (function(module, exports) { /** @@ -30800,16 +30095,16 @@ module.exports = PhaserMath; */ /** - * Calculates a Catmull-Rom value from the given points, based on an alpha of 0.5. + * Calculates a Catmull-Rom value. * * @function Phaser.Math.CatmullRom * @since 3.0.0 * - * @param {number} t - The amount to interpolate by. - * @param {number} p0 - The first control point. - * @param {number} p1 - The second control point. - * @param {number} p2 - The third control point. - * @param {number} p3 - The fourth control point. + * @param {number} t - [description] + * @param {number} p0 - [description] + * @param {number} p1 - [description] + * @param {number} p2 - [description] + * @param {number} p3 - [description] * * @return {number} The Catmull-Rom value. */ @@ -30827,7 +30122,7 @@ module.exports = CatmullRom; /***/ }), -/* 167 */ +/* 170 */ /***/ (function(module, exports) { /** @@ -30856,7 +30151,7 @@ module.exports = Between; /***/ }), -/* 168 */ +/* 171 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30865,7 +30160,7 @@ module.exports = Between; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); +var CONST = __webpack_require__(13); /** * Convert the given angle in radians, to the equivalent angle in degrees. @@ -30886,7 +30181,7 @@ module.exports = RadToDeg; /***/ }), -/* 169 */ +/* 172 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31696,7 +30991,7 @@ module.exports = Vector3; /***/ }), -/* 170 */ +/* 173 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31797,7 +31092,7 @@ module.exports = DefaultPlugins; /***/ }), -/* 171 */ +/* 174 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31806,8 +31101,8 @@ module.exports = DefaultPlugins; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var MATH_CONST = __webpack_require__(16); +var Rectangle = __webpack_require__(11); +var MATH_CONST = __webpack_require__(13); // points is an array of Point-like objects, // either 2 dimensional arrays, or objects with public x/y properties: @@ -31883,7 +31178,7 @@ module.exports = FromPoints; /***/ }), -/* 172 */ +/* 175 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31894,10 +31189,10 @@ module.exports = FromPoints; var CONST = { - CENTER: __webpack_require__(354), - ORIENTATION: __webpack_require__(355), - SCALE_MODE: __webpack_require__(356), - ZOOM: __webpack_require__(357) + CENTER: __webpack_require__(353), + ORIENTATION: __webpack_require__(354), + SCALE_MODE: __webpack_require__(355), + ZOOM: __webpack_require__(356) }; @@ -31905,7 +31200,7 @@ module.exports = CONST; /***/ }), -/* 173 */ +/* 176 */ /***/ (function(module, exports) { /** @@ -31934,7 +31229,7 @@ module.exports = RemoveFromDOM; /***/ }), -/* 174 */ +/* 177 */ /***/ (function(module, exports) { /** @@ -32032,7 +31327,7 @@ module.exports = INPUT_CONST; /***/ }), -/* 175 */ +/* 178 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -32042,13 +31337,13 @@ module.exports = INPUT_CONST; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(119); -var DefaultPlugins = __webpack_require__(170); -var Events = __webpack_require__(22); -var GetPhysicsPlugins = __webpack_require__(869); -var GetScenePlugins = __webpack_require__(870); +var CONST = __webpack_require__(123); +var DefaultPlugins = __webpack_require__(173); +var Events = __webpack_require__(19); +var GetPhysicsPlugins = __webpack_require__(871); +var GetScenePlugins = __webpack_require__(872); var NOOP = __webpack_require__(1); -var Settings = __webpack_require__(370); +var Settings = __webpack_require__(369); /** * @classdesc @@ -32806,7 +32101,7 @@ module.exports = Systems; /***/ }), -/* 176 */ +/* 179 */ /***/ (function(module, exports) { /** @@ -32843,7 +32138,7 @@ module.exports = UppercaseFirst; /***/ }), -/* 177 */ +/* 180 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -32853,8 +32148,8 @@ module.exports = UppercaseFirst; */ var Class = __webpack_require__(0); -var Frame = __webpack_require__(92); -var TextureSource = __webpack_require__(373); +var Frame = __webpack_require__(94); +var TextureSource = __webpack_require__(372); var TEXTURE_MISSING_ERROR = 'Texture.frame missing: '; @@ -33363,7 +32658,7 @@ module.exports = Texture; /***/ }), -/* 178 */ +/* 181 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33378,45 +32673,45 @@ module.exports = Texture; module.exports = { - Matrix: __webpack_require__(905), + Matrix: __webpack_require__(907), - Add: __webpack_require__(912), - AddAt: __webpack_require__(913), - BringToTop: __webpack_require__(914), - CountAllMatching: __webpack_require__(915), - Each: __webpack_require__(916), - EachInRange: __webpack_require__(917), - FindClosestInSorted: __webpack_require__(265), - GetAll: __webpack_require__(918), - GetFirst: __webpack_require__(919), - GetRandom: __webpack_require__(180), - MoveDown: __webpack_require__(920), - MoveTo: __webpack_require__(921), - MoveUp: __webpack_require__(922), - NumberArray: __webpack_require__(923), - NumberArrayStep: __webpack_require__(924), - QuickSelect: __webpack_require__(384), - Range: __webpack_require__(385), - Remove: __webpack_require__(117), - RemoveAt: __webpack_require__(925), - RemoveBetween: __webpack_require__(926), - RemoveRandomElement: __webpack_require__(927), - Replace: __webpack_require__(928), - RotateLeft: __webpack_require__(281), - RotateRight: __webpack_require__(282), - SafeRange: __webpack_require__(66), - SendToBack: __webpack_require__(929), - SetAll: __webpack_require__(930), - Shuffle: __webpack_require__(110), - SpliceOne: __webpack_require__(78), - StableSort: __webpack_require__(125), - Swap: __webpack_require__(931) + Add: __webpack_require__(914), + AddAt: __webpack_require__(915), + BringToTop: __webpack_require__(916), + CountAllMatching: __webpack_require__(917), + Each: __webpack_require__(918), + EachInRange: __webpack_require__(919), + FindClosestInSorted: __webpack_require__(267), + GetAll: __webpack_require__(920), + GetFirst: __webpack_require__(921), + GetRandom: __webpack_require__(183), + MoveDown: __webpack_require__(922), + MoveTo: __webpack_require__(923), + MoveUp: __webpack_require__(924), + NumberArray: __webpack_require__(925), + NumberArrayStep: __webpack_require__(926), + QuickSelect: __webpack_require__(383), + Range: __webpack_require__(384), + Remove: __webpack_require__(121), + RemoveAt: __webpack_require__(927), + RemoveBetween: __webpack_require__(928), + RemoveRandomElement: __webpack_require__(929), + Replace: __webpack_require__(930), + RotateLeft: __webpack_require__(283), + RotateRight: __webpack_require__(284), + SafeRange: __webpack_require__(68), + SendToBack: __webpack_require__(931), + SetAll: __webpack_require__(932), + Shuffle: __webpack_require__(114), + SpliceOne: __webpack_require__(79), + StableSort: __webpack_require__(128), + Swap: __webpack_require__(933) }; /***/ }), -/* 179 */ +/* 182 */ /***/ (function(module, exports) { /** @@ -33477,7 +32772,7 @@ module.exports = CheckMatrix; /***/ }), -/* 180 */ +/* 183 */ /***/ (function(module, exports) { /** @@ -33512,7 +32807,7 @@ module.exports = GetRandom; /***/ }), -/* 181 */ +/* 184 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33522,8 +32817,8 @@ module.exports = GetRandom; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(933); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(935); /** * @classdesc @@ -33803,7 +33098,7 @@ module.exports = ProcessQueue; /***/ }), -/* 182 */ +/* 185 */ /***/ (function(module, exports) { /** @@ -33942,7 +33237,7 @@ module.exports = ParseXMLBitmapFont; /***/ }), -/* 183 */ +/* 186 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33951,13 +33246,13 @@ module.exports = ParseXMLBitmapFont; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BlitterRender = __webpack_require__(941); -var Bob = __webpack_require__(944); +var BlitterRender = __webpack_require__(943); +var Bob = __webpack_require__(946); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Frame = __webpack_require__(92); +var Frame = __webpack_require__(94); var GameObject = __webpack_require__(14); -var List = __webpack_require__(123); +var List = __webpack_require__(126); /** * @callback CreateCallback @@ -34241,7 +33536,7 @@ module.exports = Blitter; /***/ }), -/* 184 */ +/* 187 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -34251,15 +33546,15 @@ module.exports = Blitter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayUtils = __webpack_require__(178); +var ArrayUtils = __webpack_require__(181); var BlendModes = __webpack_require__(52); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Events = __webpack_require__(88); +var Events = __webpack_require__(90); var GameObject = __webpack_require__(14); -var Rectangle = __webpack_require__(13); -var Render = __webpack_require__(945); -var Union = __webpack_require__(387); +var Rectangle = __webpack_require__(11); +var Render = __webpack_require__(947); +var Union = __webpack_require__(386); var Vector2 = __webpack_require__(3); /** @@ -34593,7 +33888,7 @@ var Container = new Class({ * * @param {boolean} [value=true] - The exclusive state of this Container. * - * @return {this} This Container. + * @return {Phaser.GameObjects.Container} This Container. */ setExclusive: function (value) { @@ -34754,7 +34049,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ add: function (child) { @@ -34776,7 +34071,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. * @param {integer} [index=0] - The position to insert the Game Object/s at. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ addAt: function (child, index) { @@ -34825,7 +34120,7 @@ var Container = new Class({ * @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 boolean. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ sort: function (property, handler) { @@ -34967,7 +34262,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject} child1 - The first Game Object to swap. * @param {Phaser.GameObjects.GameObject} child2 - The second Game Object to swap. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ swap: function (child1, child2) { @@ -34990,7 +34285,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject} child - The Game Object to move. * @param {integer} index - The new position of the Game Object in this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ moveTo: function (child, index) { @@ -35012,7 +34307,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to be removed from the Container. * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each child successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ remove: function (child, destroyChild) { @@ -35045,7 +34340,7 @@ var Container = new Class({ * @param {integer} index - The index of the Game Object to be removed. * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ removeAt: function (index, destroyChild) { @@ -35071,7 +34366,7 @@ var Container = new Class({ * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ removeBetween: function (startIndex, endIndex, destroyChild) { @@ -35098,7 +34393,7 @@ var Container = new Class({ * * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ removeAll: function (destroyChild) { @@ -35124,7 +34419,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to bring to the top of the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ bringToTop: function (child) { @@ -35142,7 +34437,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to send to the bottom of the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ sendToBack: function (child) { @@ -35159,7 +34454,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ moveUp: function (child) { @@ -35176,7 +34471,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ moveDown: function (child) { @@ -35191,7 +34486,7 @@ var Container = new Class({ * @method Phaser.GameObjects.Container#reverse * @since 3.4.0 * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ reverse: function () { @@ -35206,7 +34501,7 @@ var Container = new Class({ * @method Phaser.GameObjects.Container#shuffle * @since 3.4.0 * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ shuffle: function () { @@ -35226,7 +34521,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject} newChild - The Game Object to be added to this Container. * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ replace: function (oldChild, newChild, destroyChild) { @@ -35278,7 +34573,7 @@ var Container = new Class({ * @param {integer} [startIndex=0] - An optional start index to search from. * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ setAll: function (property, value, startIndex, endIndex) { @@ -35311,7 +34606,7 @@ var Container = new Class({ * @param {object} [context] - Value to use as `this` when executing callback. * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ each: function (callback, context) { @@ -35348,7 +34643,7 @@ var Container = new Class({ * @param {object} [context] - Value to use as `this` when executing callback. * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ iterate: function (callback, context) { @@ -35566,7 +34861,7 @@ module.exports = Container; /***/ }), -/* 185 */ +/* 188 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35575,9 +34870,9 @@ module.exports = Container; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(126); +var BitmapText = __webpack_require__(129); var Class = __webpack_require__(0); -var Render = __webpack_require__(950); +var Render = __webpack_require__(952); /** * @classdesc @@ -35726,7 +35021,7 @@ var DynamicBitmapText = new Class({ * @param {number} width - The width of the crop. * @param {number} height - The height of the crop. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setSize: function (width, height) { @@ -35750,7 +35045,7 @@ var DynamicBitmapText = new Class({ * * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallback} callback - The display callback to set. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setDisplayCallback: function (callback) { @@ -35767,7 +35062,7 @@ var DynamicBitmapText = new Class({ * * @param {number} value - The horizontal scroll position to set. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setScrollX: function (value) { @@ -35784,7 +35079,7 @@ var DynamicBitmapText = new Class({ * * @param {number} value - The vertical scroll position to set. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setScrollY: function (value) { @@ -35799,7 +35094,7 @@ module.exports = DynamicBitmapText; /***/ }), -/* 186 */ +/* 189 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35808,26 +35103,26 @@ module.exports = DynamicBitmapText; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCamera = __webpack_require__(89); +var BaseCamera = __webpack_require__(91); var Class = __webpack_require__(0); -var Commands = __webpack_require__(187); -var ComponentsAlpha = __webpack_require__(264); -var ComponentsBlendMode = __webpack_require__(267); -var ComponentsDepth = __webpack_require__(268); -var ComponentsMask = __webpack_require__(272); -var ComponentsPipeline = __webpack_require__(150); -var ComponentsTransform = __webpack_require__(277); -var ComponentsVisible = __webpack_require__(278); -var ComponentsScrollFactor = __webpack_require__(275); +var Commands = __webpack_require__(190); +var ComponentsAlpha = __webpack_require__(266); +var ComponentsBlendMode = __webpack_require__(269); +var ComponentsDepth = __webpack_require__(270); +var ComponentsMask = __webpack_require__(274); +var ComponentsPipeline = __webpack_require__(153); +var ComponentsTransform = __webpack_require__(279); +var ComponentsVisible = __webpack_require__(280); +var ComponentsScrollFactor = __webpack_require__(277); -var TransformMatrix = __webpack_require__(30); +var TransformMatrix = __webpack_require__(32); -var Ellipse = __webpack_require__(93); +var Ellipse = __webpack_require__(95); var GameObject = __webpack_require__(14); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); -var MATH_CONST = __webpack_require__(16); -var Render = __webpack_require__(956); +var MATH_CONST = __webpack_require__(13); +var Render = __webpack_require__(958); /** * @classdesc @@ -36047,7 +35342,7 @@ var Graphics = new Class({ * * @param {Phaser.Types.GameObjects.Graphics.Styles} options - The styles to set as defaults. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ setDefaultStyles: function (options) { @@ -36081,7 +35376,7 @@ var Graphics = new Class({ * @param {number} color - The stroke color. * @param {number} [alpha=1] - The stroke alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineStyle: function (lineWidth, color, alpha) { @@ -36106,7 +35401,7 @@ var Graphics = new Class({ * @param {number} color - The fill color. * @param {number} [alpha=1] - The fill alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillStyle: function (color, alpha) { @@ -36145,7 +35440,7 @@ var Graphics = new Class({ * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. * @param {number} [alpha=1] - The fill alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillGradientStyle: function (topLeft, topRight, bottomLeft, bottomRight, alpha) { @@ -36183,7 +35478,7 @@ var Graphics = new Class({ * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. * @param {number} [alpha=1] - The fill alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineGradientStyle: function (lineWidth, topLeft, topRight, bottomLeft, bottomRight, alpha) { @@ -36259,7 +35554,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#beginPath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ beginPath: function () { @@ -36276,7 +35571,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#closePath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ closePath: function () { @@ -36293,7 +35588,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#fillPath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPath: function () { @@ -36313,7 +35608,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#fill * @since 3.16.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fill: function () { @@ -36330,7 +35625,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#strokePath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokePath: function () { @@ -36350,7 +35645,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#stroke * @since 3.16.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ stroke: function () { @@ -36369,7 +35664,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Circle} circle - The circle to fill. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillCircleShape: function (circle) { @@ -36384,7 +35679,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Circle} circle - The circle to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeCircleShape: function (circle) { @@ -36401,7 +35696,7 @@ var Graphics = new Class({ * @param {number} y - The y coordinate of the center of the circle. * @param {number} radius - The radius of the circle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillCircle: function (x, y, radius) { @@ -36422,7 +35717,7 @@ var Graphics = new Class({ * @param {number} y - The y coordinate of the center of the circle. * @param {number} radius - The radius of the circle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeCircle: function (x, y, radius) { @@ -36441,7 +35736,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Rectangle} rect - The rectangle to fill. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillRectShape: function (rect) { @@ -36456,7 +35751,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Rectangle} rect - The rectangle to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeRectShape: function (rect) { @@ -36474,7 +35769,7 @@ var Graphics = new Class({ * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillRect: function (x, y, width, height) { @@ -36497,7 +35792,7 @@ var Graphics = new Class({ * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeRect: function (x, y, width, height) { @@ -36540,7 +35835,7 @@ var Graphics = new Class({ * @param {number} height - The height of the rectangle. * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillRoundedRect: function (x, y, width, height, radius) { @@ -36586,7 +35881,7 @@ var Graphics = new Class({ * @param {number} height - The height of the rectangle. * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeRoundedRect: function (x, y, width, height, radius) { @@ -36631,7 +35926,7 @@ var Graphics = new Class({ * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The point to fill. * @param {number} [size=1] - The size of the square to draw. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPointShape: function (point, size) { @@ -36650,7 +35945,7 @@ var Graphics = new Class({ * @param {number} y - The y coordinate of the point. * @param {number} [size=1] - The size of the square to draw. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPoint: function (x, y, size) { @@ -36680,7 +35975,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Triangle} triangle - The triangle to fill. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillTriangleShape: function (triangle) { @@ -36695,7 +35990,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Triangle} triangle - The triangle to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeTriangleShape: function (triangle) { @@ -36715,7 +36010,7 @@ var Graphics = new Class({ * @param {number} x2 - The x coordinate of the third point. * @param {number} y2 - The y coordinate of the third point. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillTriangle: function (x0, y0, x1, y1, x2, y2) { @@ -36740,7 +36035,7 @@ var Graphics = new Class({ * @param {number} x2 - The x coordinate of the third point. * @param {number} y2 - The y coordinate of the third point. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeTriangle: function (x0, y0, x1, y1, x2, y2) { @@ -36760,7 +36055,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Line} line - The line to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeLineShape: function (line) { @@ -36778,7 +36073,7 @@ var Graphics = new Class({ * @param {number} x2 - The x coordinate of the end point of the line. * @param {number} y2 - The y coordinate of the end point of the line. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineBetween: function (x1, y1, x2, y2) { @@ -36801,7 +36096,7 @@ var Graphics = new Class({ * @param {number} x - The x coordinate to draw the line to. * @param {number} y - The y coordinate to draw the line to. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineTo: function (x, y) { @@ -36822,7 +36117,7 @@ var Graphics = new Class({ * @param {number} x - The x coordinate to move to. * @param {number} y - The y coordinate to move to. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ moveTo: function (x, y) { @@ -36849,7 +36144,7 @@ var Graphics = new Class({ * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. * @param {integer} [endIndex] - The index of `points` to stop drawing at. Defaults to `points.length`. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokePoints: function (points, closeShape, closePath, endIndex) { @@ -36896,7 +36191,7 @@ var Graphics = new Class({ * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. * @param {integer} [endIndex] - The index of `points` to stop at. Defaults to `points.length`. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPoints: function (points, closeShape, closePath, endIndex) { @@ -36937,7 +36232,7 @@ var Graphics = new Class({ * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to stroke. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeEllipseShape: function (ellipse, smoothness) { @@ -36960,7 +36255,7 @@ var Graphics = new Class({ * @param {number} height - The height of the ellipse. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeEllipse: function (x, y, width, height, smoothness) { @@ -36982,7 +36277,7 @@ var Graphics = new Class({ * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to fill. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillEllipseShape: function (ellipse, smoothness) { @@ -37005,7 +36300,7 @@ var Graphics = new Class({ * @param {number} height - The height of the ellipse. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillEllipse: function (x, y, width, height, smoothness) { @@ -37044,7 +36339,7 @@ var Graphics = new Class({ * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. * @param {number} [overshoot=0] - This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ arc: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) { @@ -37080,7 +36375,7 @@ var Graphics = new Class({ * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. * @param {number} [overshoot=0] - This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ slice: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) { @@ -37106,7 +36401,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#save * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ save: function () { @@ -37127,7 +36422,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#restore * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ restore: function () { @@ -37153,7 +36448,7 @@ var Graphics = new Class({ * @param {number} x - The horizontal translation to apply. * @param {number} y - The vertical translation to apply. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ translateCanvas: function (x, y) { @@ -37180,7 +36475,7 @@ var Graphics = new Class({ * @param {number} x - The horizontal scale to apply. * @param {number} y - The vertical scale to apply. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ scaleCanvas: function (x, y) { @@ -37206,7 +36501,7 @@ var Graphics = new Class({ * * @param {number} radians - The rotation angle, in radians. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ rotateCanvas: function (radians) { @@ -37224,7 +36519,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#clear * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ clear: function () { @@ -37259,7 +36554,7 @@ var Graphics = new Class({ * @param {integer} [width] - The width of the graphics to generate. * @param {integer} [height] - The height of the graphics to generate. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ generateTexture: function (key, width, height) { @@ -37349,7 +36644,7 @@ module.exports = Graphics; /***/ }), -/* 187 */ +/* 190 */ /***/ (function(module, exports) { /** @@ -37386,7 +36681,7 @@ module.exports = { /***/ }), -/* 188 */ +/* 191 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -37428,7 +36723,7 @@ module.exports = CircumferencePoint; /***/ }), -/* 189 */ +/* 192 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -37440,10 +36735,10 @@ module.exports = CircumferencePoint; var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var GravityWell = __webpack_require__(395); -var List = __webpack_require__(123); -var ParticleEmitter = __webpack_require__(397); -var Render = __webpack_require__(966); +var GravityWell = __webpack_require__(394); +var List = __webpack_require__(126); +var ParticleEmitter = __webpack_require__(396); +var Render = __webpack_require__(968); /** * @classdesc @@ -37593,7 +36888,7 @@ var ParticleEmitterManager = new Class({ * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ setTexture: function (key, frame) { @@ -37614,7 +36909,7 @@ var ParticleEmitterManager = new Class({ * * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ setFrame: function (frame) { @@ -37645,7 +36940,7 @@ var ParticleEmitterManager = new Class({ * @param {(Phaser.Textures.Frame|Phaser.Textures.Frame[])} frames - The texture frames. * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The particle emitter to modify. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ setEmitterFrames: function (frames, emitter) { @@ -37765,7 +37060,7 @@ var ParticleEmitterManager = new Class({ * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ emitParticle: function (count, x, y) { @@ -37794,7 +37089,7 @@ var ParticleEmitterManager = new Class({ * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ emitParticleAt: function (x, y, count) { @@ -37811,7 +37106,7 @@ var ParticleEmitterManager = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitterManager#pause * @since 3.0.0 * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ pause: function () { @@ -37826,7 +37121,7 @@ var ParticleEmitterManager = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitterManager#resume * @since 3.0.0 * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ resume: function () { @@ -37917,7 +37212,7 @@ module.exports = ParticleEmitterManager; /***/ }), -/* 190 */ +/* 193 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -37927,16 +37222,16 @@ module.exports = ParticleEmitterManager; */ var BlendModes = __webpack_require__(52); -var Camera = __webpack_require__(89); -var CanvasPool = __webpack_require__(27); +var Camera = __webpack_require__(91); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var CONST = __webpack_require__(10); -var Frame = __webpack_require__(92); +var CONST = __webpack_require__(29); +var Frame = __webpack_require__(94); var GameObject = __webpack_require__(14); -var Render = __webpack_require__(970); -var Utils = __webpack_require__(9); -var UUID = __webpack_require__(191); +var Render = __webpack_require__(972); +var Utils = __webpack_require__(10); +var UUID = __webpack_require__(194); /** * @classdesc @@ -39156,7 +38451,7 @@ module.exports = RenderTexture; /***/ }), -/* 191 */ +/* 194 */ /***/ (function(module, exports) { /** @@ -39191,7 +38486,7 @@ module.exports = UUID; /***/ }), -/* 192 */ +/* 195 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -39200,1123 +38495,17 @@ module.exports = UUID; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ +var AddToDOM = __webpack_require__(120); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); var Components = __webpack_require__(12); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); -var RopeRender = __webpack_require__(976); -var Vector2 = __webpack_require__(3); - -/** - * @classdesc - * A Rope Game Object. - * - * A Ropes origin is always 0.5 x 0.5 and cannot be changed. - * - * @class Rope - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @webglOnly - * @since 3.23.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * @extends Phaser.GameObjects.Components.ScrollFactor - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {string} [texture] - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. If not given, `__DEFAULT` is used. - * @param {(string|integer|null)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {(integer|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. See `setPoints` to set this post-creation. - * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? - * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. - * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. - */ -var Rope = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.Mask, - Components.Pipeline, - Components.Size, - Components.Texture, - Components.Transform, - Components.Visible, - Components.ScrollFactor, - RopeRender - ], - - initialize: - - function Rope (scene, x, y, texture, frame, points, horizontal, colors, alphas) - { - if (texture === undefined) { texture = '__DEFAULT'; } - if (points === undefined) { points = 2; } - if (horizontal === undefined) { horizontal = true; } - - GameObject.call(this, scene, 'Rope'); - - /** - * The Animation Controller of this Rope. - * - * @name Phaser.GameObjects.Rope#anims - * @type {Phaser.GameObjects.Components.Animation} - * @since 3.23.0 - */ - this.anims = new Components.Animation(this); - - /** - * An array containing the points data for this Rope. - * - * Each point should be given as a Vector2Like object (i.e. a Vector2, Geom.Point or object with public x/y properties). - * - * The point coordinates are given in local space, where 0 x 0 is the start of the Rope strip. - * - * You can modify the contents of this array directly in real-time to create interesting effects. - * If you do so, be sure to call `setDirty` _after_ modifying this array, so that the vertices data is - * updated before the next render. Alternatively, you can use the `setPoints` method instead. - * - * Should you need to change the _size_ of this array, then you should always use the `setPoints` method. - * - * @name Phaser.GameObjects.Rope#points - * @type {Phaser.Math.Types.Vector2Like[]} - * @since 3.23.0 - */ - this.points = points; - - /** - * 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 - */ - this.vertices; - - /** - * 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 - */ - this.uv; - - /** - * An array containing the color data for this Rope. - * - * Colors should be given as numeric RGB values, such as 0xff0000. - * You should provide _two_ color values for every point in the Rope, one for the top and one for the bottom of each quad. - * - * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ - * of the array, then you should use the `setColors` method instead. - * - * @name Phaser.GameObjects.Rope#colors - * @type {Uint32Array} - * @since 3.23.0 - */ - this.colors; - - /** - * An array containing the alpha data for this Rope. - * - * Alphas should be given as float values, such as 0.5. - * You should provide _two_ alpha values for every point in the Rope, one for the top and one for the bottom of each quad. - * - * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ - * of the array, then you should use the `setAlphas` method instead. - * - * @name Phaser.GameObjects.Rope#alphas - * @type {Float32Array} - * @since 3.23.0 - */ - this.alphas; - - /** - * The tint fill mode. - * - * 0 = An additive tint (the default), where vertices colors are blended with the texture. - * 1 = A fill tint, where the vertices colors replace the texture, but respects texture alpha. - * 2 = A complete tint, where the vertices colors replace the texture, including alpha, entirely. - * - * @name Phaser.GameObjects.Rope#tintFill - * @type {integer} - * @since 3.23.0 - */ - this.tintFill = (texture === '__DEFAULT') ? 2 : 0; - - /** - * If the Rope is marked as `dirty` it will automatically recalculate its vertices - * the next time it renders. You can also force this by calling `updateVertices`. - * - * @name Phaser.GameObjects.Rope#dirty - * @type {boolean} - * @since 3.23.0 - */ - this.dirty = false; - - /** - * Are the Rope vertices aligned horizontally, in a strip, or vertically, in a column? - * - * This property is set during instantiation and cannot be changed directly. - * See the `setVertical` and `setHorizontal` methods. - * - * @name Phaser.GameObjects.Rope#horizontal - * @type {boolean} - * @readonly - * @since 3.23.0 - */ - this.horizontal = horizontal; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#_flipX - * @type {boolean} - * @default false - * @private - * @since 3.23.0 - */ - this._flipX = false; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipY - * @type {boolean} - * @default false - * @private - * @since 3.23.0 - */ - this._flipY = false; - - /** - * Internal Vector2 used for vertices updates. - * - * @name Phaser.GameObjects.Rope#_perp - * @type {Phaser.Math.Vector2} - * @private - * @since 3.23.0 - */ - this._perp = new Vector2(); - - /** - * You can optionally choose to render the vertices of this Rope to a Graphics instance. - * - * Achieve this by setting the `debugCallback` and the `debugGraphic` properties. - * - * You can do this in a single call via the `Rope.setDebug` method, which will use the - * built-in debug function. You can also set it to your own callback. The callback - * will be invoked _once per render_ and sent the following parameters: - * - * `debugCallback(src, meshLength, verts)` - * - * `src` is the Rope instance being debugged. - * `meshLength` is the number of mesh vertices in total. - * `verts` is an array of the translated vertex coordinates. - * - * To disable rendering, set this property back to `null`. - * - * @name Phaser.GameObjects.Rope#debugCallback - * @type {function} - * @since 3.23.0 - */ - this.debugCallback = null; - - /** - * The Graphics instance that the debug vertices will be drawn to, if `setDebug` has - * been called. - * - * @name Phaser.GameObjects.Rope#debugGraphic - * @type {Phaser.GameObjects.Graphics} - * @since 3.23.0 - */ - this.debugGraphic = null; - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.initPipeline('TextureTintStripPipeline'); - - if (Array.isArray(points)) - { - this.resizeArrays(points.length); - } - - this.setPoints(points, colors, alphas); - - this.updateVertices(); - }, - - /** - * The Rope update loop. - * - * @method Phaser.GameObjects.Rope#preUpdate - * @protected - * @since 3.23.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - var prevFrame = this.anims.currentFrame; - - this.anims.update(time, delta); - - if (this.anims.currentFrame !== prevFrame) - { - this.updateUVs(); - this.updateVertices(); - } - }, - - /** - * Start playing the given animation. - * - * @method Phaser.GameObjects.Rope#play - * @since 3.23.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Game Object. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - this.anims.play(key, ignoreIfPlaying, startFrame); - - return this; - }, - - /** - * Flags this Rope as being dirty. A dirty rope will recalculate all of its vertices data - * the _next_ time it renders. You should set this rope as dirty if you update the points - * array directly. - * - * @method Phaser.GameObjects.Rope#setDirty - * @since 3.23.0 - * - * @return {this} This Game Object instance. - */ - setDirty: function () - { - this.dirty = true; - - return this; - }, - - /** - * Sets the alignment of the points in this Rope to be horizontal, in a strip format. - * - * Calling this method will reset this Rope. The current points, vertices, colors and alpha - * values will be reset to thoes values given as parameters. - * - * @method Phaser.GameObjects.Rope#setHorizontal - * @since 3.23.0 - * - * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. - * @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. - */ - setHorizontal: function (points, colors, alphas) - { - if (points === undefined) { points = this.points.length; } - - if (this.horizontal) - { - return this; - } - - this.horizontal = true; - - return this.setPoints(points, colors, alphas); - }, - - /** - * Sets the alignment of the points in this Rope to be vertical, in a column format. - * - * Calling this method will reset this Rope. The current points, vertices, colors and alpha - * values will be reset to thoes values given as parameters. - * - * @method Phaser.GameObjects.Rope#setVertical - * @since 3.23.0 - * - * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. - * @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. - */ - setVertical: function (points, colors, alphas) - { - if (points === undefined) { points = this.points.length; } - - if (!this.horizontal) - { - return this; - } - - this.horizontal = false; - - return this.setPoints(points, colors, alphas); - }, - - /** - * Sets the tint fill mode. - * - * Mode 0 is an additive tint, the default, which blends the vertices colors with the texture. - * This mode respects the texture alpha. - * - * Mode 1 is a fill tint. Unlike an additive tint, a fill-tint literally replaces the pixel colors - * from the texture with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. This mode respects the texture alpha. - * - * Mode 2 is a complete tint. The texture colors and alpha are replaced entirely by the vertices colors. - * - * See the `setColors` method for details of how to color each of the vertices. - * - * @method Phaser.GameObjects.Rope#setTintFill - * @webglOnly - * @since 3.23.0 - * - * @param {integer} [value=0] - Set to 0 for an Additive tint, 1 for a fill tint with alpha, or 2 for a fill tint without alpha. - * - * @return {this} This Game Object instance. - */ - setTintFill: function (value) - { - if (value === undefined) { value = 0; } - - this.tintFill = value; - - return this; - }, - - /** - * Set the alpha values used by the Rope during rendering. - * - * You can provide the values in a number of ways: - * - * 1) One single numeric value: `setAlphas(0.5)` - This will set a single alpha for the whole Rope. - * 2) Two numeric value: `setAlphas(1, 0.5)` - This will set a 'top' and 'bottom' alpha value across the whole Rope. - * 3) An array of values: `setAlphas([ 1, 0.5, 0.2 ])` - * - * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it - * will use each alpha value per rope segment. - * - * If the provided array has a different number of values than `points` then it will use the values in order, from - * the first Rope segment and on, until it runs out of values. This allows you to control the alpha values at all - * vertices in the Rope. - * - * Note this method is called `setAlphas` (plural) and not `setAlpha`. - * - * @method Phaser.GameObjects.Rope#setAlphas - * @since 3.23.0 - * - * @param {(number|number[])} [alphas] - Either a single alpha value, or an array of values. If nothing is provided alpha is reset to 1. - * @param {number} [bottomAlpha] - An optional bottom alpha value. See the method description for details. - * - * @return {this} This Game Object instance. - */ - setAlphas: function (alphas, bottomAlpha) - { - var total = this.points.length; - - if (total < 1) - { - return this; - } - - var currentAlphas = this.alphas; - - if (alphas === undefined) - { - alphas = [ 1 ]; - } - else if (!Array.isArray(alphas) && bottomAlpha === undefined) - { - alphas = [ alphas ]; - } - - var i; - var index = 0; - - if (bottomAlpha !== undefined) - { - // Top / Bottom alpha pair - for (i = 0; i < total; i++) - { - index = i * 2; - - currentAlphas[index] = alphas; - currentAlphas[index + 1] = bottomAlpha; - } - } - else if (alphas.length === total) - { - // If there are exactly the same number of alphas as points, we'll combine the alphas - for (i = 0; i < total; i++) - { - index = i * 2; - - currentAlphas[index] = alphas[i]; - currentAlphas[index + 1] = alphas[i]; - } - } - else - { - var prevAlpha = alphas[0]; - - for (i = 0; i < total; i++) - { - index = i * 2; - - if (alphas.length > index) - { - prevAlpha = alphas[index]; - } - - currentAlphas[index] = prevAlpha; - - if (alphas.length > index + 1) - { - prevAlpha = alphas[index + 1]; - } - - currentAlphas[index + 1] = prevAlpha; - } - } - - return this; - - }, - - /** - * Set the color values used by the Rope during rendering. - * - * Colors are used to control the level of tint applied across the Rope texture. - * - * You can provide the values in a number of ways: - * - * * One single numeric value: `setColors(0xff0000)` - This will set a single color tint for the whole Rope. - * * An array of values: `setColors([ 0xff0000, 0x00ff00, 0x0000ff ])` - * - * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it - * will use each color per rope segment. - * - * If the provided array has a different number of values than `points` then it will use the values in order, from - * the first Rope segment and on, until it runs out of values. This allows you to control the color values at all - * vertices in the Rope. - * - * @method Phaser.GameObjects.Rope#setColors - * @since 3.23.0 - * - * @param {(number|number[])} [colors] - Either a single color value, or an array of values. If nothing is provided color is reset to 0xffffff. - * - * @return {this} This Game Object instance. - */ - setColors: function (colors) - { - var total = this.points.length; - - if (total < 1) - { - return this; - } - - var currentColors = this.colors; - - if (colors === undefined) - { - colors = [ 0xffffff ]; - } - else if (!Array.isArray(colors)) - { - colors = [ colors ]; - } - - var i; - var index = 0; - - if (colors.length === total) - { - // If there are exactly the same number of colors as points, we'll combine the colors - for (i = 0; i < total; i++) - { - index = i * 2; - - currentColors[index] = colors[i]; - currentColors[index + 1] = colors[i]; - } - } - else - { - var prevColor = colors[0]; - - for (i = 0; i < total; i++) - { - index = i * 2; - - if (colors.length > index) - { - prevColor = colors[index]; - } - - currentColors[index] = prevColor; - - if (colors.length > index + 1) - { - prevColor = colors[index + 1]; - } - - currentColors[index + 1] = prevColor; - } - } - - return this; - }, - - /** - * 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 {(integer|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. - */ - setPoints: function (points, colors, alphas) - { - if (points === undefined) { points = 2; } - - if (typeof points === 'number') - { - // Generate an array based on the points - var segments = points; - - if (segments < 2) - { - segments = 2; - } - - points = []; - - var s; - var frameSegment; - var offset; - - if (this.horizontal) - { - offset = -(this.frame.halfWidth); - frameSegment = this.frame.width / (segments - 1); - - for (s = 0; s < segments; s++) - { - points.push({ x: offset + s * frameSegment, y: 0 }); - } - } - else - { - offset = -(this.frame.halfHeight); - frameSegment = this.frame.height / (segments - 1); - - for (s = 0; s < segments; s++) - { - points.push({ x: 0, y: offset + s * frameSegment }); - } - } - } - - var total = points.length; - var currentTotal = this.points.length; - - if (total < 1) - { - console.warn('Rope: Not enough points given'); - - return this; - } - else if (total === 1) - { - points.unshift({ x: 0, y: 0 }); - total++; - } - - if (currentTotal !== total) - { - this.resizeArrays(total); - } - - this.points = points; - - this.updateUVs(); - - if (colors !== undefined && colors !== null) - { - this.setColors(colors); - } - - if (alphas !== undefined && alphas !== null) - { - this.setAlphas(alphas); - } - - return this; - }, - - /** - * 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. - */ - updateUVs: function () - { - var currentUVs = this.uv; - var total = this.points.length; - - var u0 = this.frame.u0; - var v0 = this.frame.v0; - var u1 = this.frame.u1; - var v1 = this.frame.v1; - - var partH = (u1 - u0) / (total - 1); - var partV = (v1 - v0) / (total - 1); - - for (var i = 0; i < total; i++) - { - var index = i * 4; - - var uv0; - var uv1; - var uv2; - var uv3; - - if (this.horizontal) - { - if (this._flipX) - { - uv0 = u1 - (i * partH); - uv2 = u1 - (i * partH); - } - else - { - uv0 = u0 + (i * partH); - uv2 = u0 + (i * partH); - } - - if (this._flipY) - { - uv1 = v1; - uv3 = v0; - } - else - { - uv1 = v0; - uv3 = v1; - } - } - else - { - if (this._flipX) - { - uv0 = u0; - uv2 = u1; - } - else - { - uv0 = u1; - uv2 = u0; - } - - if (this._flipY) - { - uv1 = v1 - (i * partV); - uv3 = v1 - (i * partV); - } - else - { - uv1 = v0 + (i * partV); - uv3 = v0 + (i * partV); - } - } - - currentUVs[index + 0] = uv0; - currentUVs[index + 1] = uv1; - currentUVs[index + 2] = uv2; - currentUVs[index + 3] = uv3; - } - - return this; - }, - - /** - * Resizes all of the internal arrays: `vertices`, `uv`, `colors` and `alphas` to the new - * given Rope segment total. - * - * @method Phaser.GameObjects.Rope#resizeArrays - * @since 3.23.0 - * - * @param {integer} newSize - The amount of segments to split the Rope in to. - * - * @return {this} This Game Object instance. - */ - resizeArrays: function (newSize) - { - var colors = this.colors; - var alphas = this.alphas; - - this.vertices = new Float32Array(newSize * 4); - this.uv = new Float32Array(newSize * 4); - - colors = new Uint32Array(newSize * 2); - alphas = new Float32Array(newSize * 2); - - for (var i = 0; i < newSize * 2; i++) - { - colors[i] = 0xffffff; - alphas[i] = 1; - } - - this.colors = colors; - this.alphas = alphas; - - // updateVertices during next render - this.dirty = true; - - return this; - }, - - /** - * 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. - */ - updateVertices: function () - { - var perp = this._perp; - var points = this.points; - var vertices = this.vertices; - - var total = points.length; - - this.dirty = false; - - if (total < 1) - { - return; - } - - var nextPoint; - var lastPoint = points[0]; - - var frameSize = (this.horizontal) ? this.frame.halfHeight : this.frame.halfWidth; - - for (var i = 0; i < total; i++) - { - var point = points[i]; - var index = i * 4; - - if (i < total - 1) - { - nextPoint = points[i + 1]; - } - else - { - nextPoint = point; - } - - perp.x = nextPoint.y - lastPoint.y; - perp.y = -(nextPoint.x - lastPoint.x); - - var perpLength = perp.length(); - - perp.x /= perpLength; - perp.y /= perpLength; - - perp.x *= frameSize; - perp.y *= frameSize; - - vertices[index] = point.x + perp.x; - vertices[index + 1] = point.y + perp.y; - vertices[index + 2] = point.x - perp.x; - vertices[index + 3] = point.y - perp.y; - - lastPoint = point; - } - - return this; - }, - - /** - * This method enables rendering of the Rope vertices to the given Graphics instance. - * - * If you enable this feature, you must call `Graphics.clear()` in your Scene `update`, - * otherwise the Graphics instance will fill-in with draw calls. This is not done automatically - * to allow for you to debug render multiple Rope objects to a single Graphics instance. - * - * The Rope class has a built-in debug rendering callback `Rope.renderDebugVerts`, however - * you can also provide your own callback to be used instead. Do this by setting the `callback` parameter. - * - * The callback is invoked _once per render_ and sent the following parameters: - * - * `callback(src, meshLength, verts)` - * - * `src` is the Rope instance being debugged. - * `meshLength` is the number of mesh vertices in total. - * `verts` is an array of the translated vertex coordinates. - * - * If using your own callback you do not have to provide a Graphics instance to this method. - * - * To disable debug rendering, to either your own callback or the built-in one, call this method - * with no arguments. - * - * @method Phaser.GameObjects.Rope#setDebug - * @since 3.23.0 - * - * @param {Phaser.GameObjects.Graphics} [graphic] - The Graphic instance to render to if using the built-in callback. - * @param {function} [callback] - The callback to invoke during debug render. Leave as undefined to use the built-in callback. - * - * @return {this} This Game Object instance. - */ - setDebug: function (graphic, callback) - { - this.debugGraphic = graphic; - - if (!graphic && !callback) - { - this.debugCallback = null; - } - else if (!callback) - { - this.debugCallback = this.renderDebugVerts; - } - else - { - this.debugCallback = callback; - } - - return this; - }, - - /** - * The built-in Rope vertices debug rendering method. - * - * See `Rope.setDebug` for more details. - * - * @method Phaser.GameObjects.Rope#renderDebugVerts - * @since 3.23.0 - * - * @param {Phaser.GameObjects.Rope} src - The Rope object being rendered. - * @param {integer} meshLength - The number of vertices in the mesh. - * @param {number[]} verts - An array of translated vertex coordinates. - */ - renderDebugVerts: function (src, meshLength, verts) - { - var graphic = src.debugGraphic; - - var px0 = verts[0]; - var py0 = verts[1]; - var px1 = verts[2]; - var py1 = verts[3]; - - graphic.lineBetween(px0, py0, px1, py1); - - for (var i = 4; i < meshLength; i += 4) - { - var x0 = verts[i + 0]; - var y0 = verts[i + 1]; - var x1 = verts[i + 2]; - var y1 = verts[i + 3]; - - graphic.lineBetween(px0, py0, x0, y0); - graphic.lineBetween(px1, py1, x1, y1); - graphic.lineBetween(px1, py1, x0, y0); - graphic.lineBetween(x0, y0, x1, y1); - - px0 = x0; - py0 = y0; - px1 = x1; - py1 = y1; - } - }, - - /** - * Handles the pre-destroy step for the Rope, which removes the Animation component and typed arrays. - * - * @method Phaser.GameObjects.Rope#preDestroy - * @private - * @since 3.23.0 - */ - preDestroy: function () - { - this.anims.destroy(); - - this.anims = undefined; - - this.points = null; - this.vertices = null; - this.uv = null; - this.colors = null; - this.alphas = null; - - this.debugCallback = null; - this.debugGraphic = null; - }, - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipX - * @type {boolean} - * @default false - * @since 3.23.0 - */ - flipX: { - - get: function () - { - return this._flipX; - }, - - set: function (value) - { - this._flipX = value; - - return this.updateUVs(); - } - - }, - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipY - * @type {boolean} - * @default false - * @since 3.23.0 - */ - flipY: { - - get: function () - { - return this._flipY; - }, - - set: function (value) - { - this._flipY = value; - - return this.updateUVs(); - } - - } - -}); - -module.exports = Rope; - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AddToDOM = __webpack_require__(116); -var CanvasPool = __webpack_require__(27); -var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameEvents = __webpack_require__(19); -var GameObject = __webpack_require__(14); -var GetTextSize = __webpack_require__(979); +var GetTextSize = __webpack_require__(978); var GetValue = __webpack_require__(6); -var RemoveFromDOM = __webpack_require__(173); -var TextRender = __webpack_require__(980); -var TextStyle = __webpack_require__(983); +var RemoveFromDOM = __webpack_require__(176); +var TextRender = __webpack_require__(979); +var TextStyle = __webpack_require__(982); /** * @classdesc @@ -40890,7 +39079,7 @@ var Text = new Class({ * * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this Text object. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setText: function (value) { @@ -40931,7 +39120,7 @@ var Text = new Class({ * * @param {object} style - The style settings to set. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setStyle: function (style) { @@ -40965,7 +39154,7 @@ var Text = new Class({ * * @param {string} font - The font family or font settings to set. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFont: function (font) { @@ -40994,7 +39183,7 @@ var Text = new Class({ * * @param {string} family - The font family. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFontFamily: function (family) { @@ -41009,7 +39198,7 @@ var Text = new Class({ * * @param {number} size - The font size. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFontSize: function (size) { @@ -41024,7 +39213,7 @@ var Text = new Class({ * * @param {string} style - The font style. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFontStyle: function (style) { @@ -41042,7 +39231,7 @@ var Text = new Class({ * @param {number} width - The fixed width to set. `0` disables fixed width. * @param {number} height - The fixed height to set. `0` disables fixed height. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFixedSize: function (width, height) { @@ -41057,7 +39246,7 @@ var Text = new Class({ * * @param {string} color - The background color. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setBackgroundColor: function (color) { @@ -41077,7 +39266,7 @@ var Text = new Class({ * * @param {(string|any)} color - The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFill: function (fillStyle) { @@ -41092,7 +39281,7 @@ var Text = new Class({ * * @param {string} color - The text fill color. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setColor: function (color) { @@ -41108,7 +39297,7 @@ var Text = new Class({ * @param {string} color - The stroke color. * @param {number} thickness - The stroke thickness. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setStroke: function (color, thickness) { @@ -41128,7 +39317,7 @@ var Text = new Class({ * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. * @param {boolean} [shadowFill=true] - Whether to fill the shadow. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadow: function (x, y, color, blur, shadowStroke, shadowFill) { @@ -41144,7 +39333,7 @@ var Text = new Class({ * @param {number} x - The horizontal shadow offset. * @param {number} y - The vertical shadow offset. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowOffset: function (x, y) { @@ -41159,7 +39348,7 @@ var Text = new Class({ * * @param {string} color - The shadow color. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowColor: function (color) { @@ -41174,7 +39363,7 @@ var Text = new Class({ * * @param {number} blur - The shadow blur radius. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowBlur: function (blur) { @@ -41189,7 +39378,7 @@ var Text = new Class({ * * @param {boolean} enabled - Whether shadow stroke is enabled or not. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowStroke: function (enabled) { @@ -41204,7 +39393,7 @@ var Text = new Class({ * * @param {boolean} enabled - Whether shadow fill is enabled or not. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowFill: function (enabled) { @@ -41222,7 +39411,7 @@ var Text = new Class({ * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, * spaces and whitespace are left as is. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setWordWrapWidth: function (width, useAdvancedWrap) { @@ -41241,7 +39430,7 @@ var Text = new Class({ * newline characters in place to indicate where breaks should happen. * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setWordWrapCallback: function (callback, scope) { @@ -41260,7 +39449,7 @@ var Text = new Class({ * * @param {string} [align='left'] - The text alignment for multi-line text. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setAlign: function (align) { @@ -41283,7 +39472,7 @@ var Text = new Class({ * * @param {number} value - The resolution for this Text object to use. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setResolution: function (value) { @@ -41301,7 +39490,7 @@ var Text = new Class({ * * @param {number} value - The amount to add to the font height to achieve the overall line height. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setLineSpacing: function (value) { @@ -41325,7 +39514,7 @@ var Text = new Class({ * @param {number} right - The right padding value. * @param {number} bottom - The bottom padding value. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setPadding: function (left, top, right, bottom) { @@ -41384,7 +39573,7 @@ var Text = new Class({ * * @param {integer} [max=0] - The maximum number of lines to draw. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setMaxLines: function (max) { @@ -41397,7 +39586,7 @@ var Text = new Class({ * @method Phaser.GameObjects.Text#updateText * @since 3.0.0 * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ updateText: function () { @@ -41706,7 +39895,7 @@ module.exports = Text; /***/ }), -/* 194 */ +/* 196 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -41715,14 +39904,14 @@ module.exports = Text; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); -var GetPowerOfTwo = __webpack_require__(323); -var Smoothing = __webpack_require__(161); -var TileSpriteRender = __webpack_require__(985); +var GetPowerOfTwo = __webpack_require__(324); +var Smoothing = __webpack_require__(164); +var TileSpriteRender = __webpack_require__(984); var Vector2 = __webpack_require__(3); // bitmask flag for GameObject.renderMask @@ -42358,7 +40547,7 @@ module.exports = TileSprite; /***/ }), -/* 195 */ +/* 197 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -42368,15 +40557,15 @@ module.exports = TileSprite; */ var Class = __webpack_require__(0); -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Components = __webpack_require__(12); -var Events = __webpack_require__(88); -var GameEvents = __webpack_require__(19); +var Events = __webpack_require__(90); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); var SoundEvents = __webpack_require__(59); -var UUID = __webpack_require__(191); -var VideoRender = __webpack_require__(988); -var MATH_CONST = __webpack_require__(16); +var UUID = __webpack_require__(194); +var VideoRender = __webpack_require__(987); +var MATH_CONST = __webpack_require__(13); /** * @classdesc @@ -44127,7 +42316,7 @@ module.exports = Video; /***/ }), -/* 196 */ +/* 198 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -44137,8 +42326,8 @@ module.exports = Video; */ var Class = __webpack_require__(0); -var Contains = __webpack_require__(197); -var GetPoints = __webpack_require__(412); +var Contains = __webpack_require__(199); +var GetPoints = __webpack_require__(411); var GEOM_CONST = __webpack_require__(46); /** @@ -44361,7 +42550,7 @@ module.exports = Polygon; /***/ }), -/* 197 */ +/* 199 */ /***/ (function(module, exports) { /** @@ -44410,7 +42599,7 @@ module.exports = Contains; /***/ }), -/* 198 */ +/* 200 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -44420,7 +42609,7 @@ module.exports = Contains; */ var Class = __webpack_require__(0); -var Mesh = __webpack_require__(128); +var Mesh = __webpack_require__(130); /** * @classdesc @@ -44914,7 +43103,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setTopLeft: function (x, y) { @@ -44933,7 +43122,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setTopRight: function (x, y) { @@ -44952,7 +43141,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setBottomLeft: function (x, y) { @@ -44971,7 +43160,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setBottomRight: function (x, y) { @@ -44987,7 +43176,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#resetPosition * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ resetPosition: function () { @@ -45010,7 +43199,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#resetAlpha * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ resetAlpha: function () { @@ -45032,7 +43221,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#resetColors * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ resetColors: function () { @@ -45054,7 +43243,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#reset * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ reset: function () { @@ -45071,7 +43260,7 @@ module.exports = Quad; /***/ }), -/* 199 */ +/* 201 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -45084,10 +43273,10 @@ var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); var GetFastValue = __webpack_require__(2); -var Extend = __webpack_require__(18); -var SetValue = __webpack_require__(420); -var ShaderRender = __webpack_require__(1071); -var TransformMatrix = __webpack_require__(30); +var Extend = __webpack_require__(17); +var SetValue = __webpack_require__(419); +var ShaderRender = __webpack_require__(1068); +var TransformMatrix = __webpack_require__(32); /** * @classdesc @@ -46294,7 +44483,7 @@ module.exports = Shader; /***/ }), -/* 200 */ +/* 202 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46325,7 +44514,7 @@ module.exports = CircleToCircle; /***/ }), -/* 201 */ +/* 203 */ /***/ (function(module, exports) { /** @@ -46379,7 +44568,7 @@ module.exports = CircleToRectangle; /***/ }), -/* 202 */ +/* 204 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46390,7 +44579,7 @@ module.exports = CircleToRectangle; */ var Point = __webpack_require__(4); -var LineToCircle = __webpack_require__(203); +var LineToCircle = __webpack_require__(205); /** * Checks for intersection between the line segment and circle, @@ -46471,7 +44660,7 @@ module.exports = GetLineToCircle; /***/ }), -/* 203 */ +/* 205 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46555,7 +44744,7 @@ module.exports = LineToCircle; /***/ }), -/* 204 */ +/* 206 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46566,8 +44755,8 @@ module.exports = LineToCircle; */ var Point = __webpack_require__(4); -var LineToLine = __webpack_require__(82); -var LineToRectangle = __webpack_require__(425); +var LineToLine = __webpack_require__(84); +var LineToRectangle = __webpack_require__(424); /** * Checks for intersection between the Line and a Rectangle shape, @@ -46615,7 +44804,7 @@ module.exports = GetLineToRectangle; /***/ }), -/* 205 */ +/* 207 */ /***/ (function(module, exports) { /** @@ -46702,7 +44891,7 @@ module.exports = ContainsArray; /***/ }), -/* 206 */ +/* 208 */ /***/ (function(module, exports) { /** @@ -46750,7 +44939,7 @@ module.exports = RotateAroundXY; /***/ }), -/* 207 */ +/* 209 */ /***/ (function(module, exports) { /** @@ -46778,7 +44967,7 @@ module.exports = GetAspectRatio; /***/ }), -/* 208 */ +/* 210 */ /***/ (function(module, exports) { /** @@ -46832,7 +45021,7 @@ module.exports = RotateAroundXY; /***/ }), -/* 209 */ +/* 211 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46847,18 +45036,18 @@ module.exports = RotateAroundXY; module.exports = { - BUTTON_DOWN: __webpack_require__(1193), - BUTTON_UP: __webpack_require__(1194), - CONNECTED: __webpack_require__(1195), - DISCONNECTED: __webpack_require__(1196), - GAMEPAD_BUTTON_DOWN: __webpack_require__(1197), - GAMEPAD_BUTTON_UP: __webpack_require__(1198) + BUTTON_DOWN: __webpack_require__(1189), + BUTTON_UP: __webpack_require__(1190), + CONNECTED: __webpack_require__(1191), + DISCONNECTED: __webpack_require__(1192), + GAMEPAD_BUTTON_DOWN: __webpack_require__(1193), + GAMEPAD_BUTTON_UP: __webpack_require__(1194) }; /***/ }), -/* 210 */ +/* 212 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46867,8 +45056,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); -var XHRSettings = __webpack_require__(133); +var Extend = __webpack_require__(17); +var XHRSettings = __webpack_require__(135); /** * Takes two XHRSettings Objects and creates a new XHRSettings object from them. @@ -46906,7 +45095,7 @@ module.exports = MergeXHRSettings; /***/ }), -/* 211 */ +/* 213 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46921,7 +45110,7 @@ var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); -var ParseXML = __webpack_require__(359); +var ParseXML = __webpack_require__(358); /** * @classdesc @@ -47067,7 +45256,7 @@ var XMLFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('xml', function (key, url, xhrSettings) { @@ -47091,7 +45280,7 @@ module.exports = XMLFile; /***/ }), -/* 212 */ +/* 214 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47106,24 +45295,24 @@ module.exports = XMLFile; module.exports = { - Acceleration: __webpack_require__(1253), - Angular: __webpack_require__(1254), - Bounce: __webpack_require__(1255), - Debug: __webpack_require__(1256), - Drag: __webpack_require__(1257), - Enable: __webpack_require__(1258), - Friction: __webpack_require__(1259), - Gravity: __webpack_require__(1260), - Immovable: __webpack_require__(1261), - Mass: __webpack_require__(1262), - Size: __webpack_require__(1263), - Velocity: __webpack_require__(1264) + Acceleration: __webpack_require__(1249), + Angular: __webpack_require__(1250), + Bounce: __webpack_require__(1251), + Debug: __webpack_require__(1252), + Drag: __webpack_require__(1253), + Enable: __webpack_require__(1254), + Friction: __webpack_require__(1255), + Gravity: __webpack_require__(1256), + Immovable: __webpack_require__(1257), + Mass: __webpack_require__(1258), + Size: __webpack_require__(1259), + Velocity: __webpack_require__(1260) }; /***/ }), -/* 213 */ +/* 215 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47138,21 +45327,21 @@ module.exports = { module.exports = { - COLLIDE: __webpack_require__(1266), - OVERLAP: __webpack_require__(1267), - PAUSE: __webpack_require__(1268), - RESUME: __webpack_require__(1269), - TILE_COLLIDE: __webpack_require__(1270), - TILE_OVERLAP: __webpack_require__(1271), - WORLD_BOUNDS: __webpack_require__(1272), - WORLD_STEP: __webpack_require__(1273) + COLLIDE: __webpack_require__(1262), + OVERLAP: __webpack_require__(1263), + PAUSE: __webpack_require__(1264), + RESUME: __webpack_require__(1265), + TILE_COLLIDE: __webpack_require__(1266), + TILE_OVERLAP: __webpack_require__(1267), + WORLD_BOUNDS: __webpack_require__(1268), + WORLD_STEP: __webpack_require__(1269) }; /***/ }), -/* 214 */, -/* 215 */ +/* 216 */, +/* 217 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47161,7 +45350,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTileAt = __webpack_require__(136); +var GetTileAt = __webpack_require__(138); /** * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting @@ -47228,7 +45417,7 @@ module.exports = CalculateFacesAt; /***/ }), -/* 216 */ +/* 218 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47237,10 +45426,10 @@ module.exports = CalculateFacesAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tile = __webpack_require__(72); -var IsInLayerBounds = __webpack_require__(99); -var CalculateFacesAt = __webpack_require__(215); -var SetTileCollision = __webpack_require__(71); +var Tile = __webpack_require__(74); +var IsInLayerBounds = __webpack_require__(103); +var CalculateFacesAt = __webpack_require__(217); +var SetTileCollision = __webpack_require__(73); /** * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index @@ -47272,7 +45461,7 @@ var PutTileAt = function (tile, tileX, tileY, recalculateFaces, layer) { if (layer.data[tileY][tileX] === null) { - layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, layer.tileWidth, layer.tileHeight); + layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, tile.width, tile.height); } layer.data[tileY][tileX].copy(tile); } @@ -47308,7 +45497,7 @@ module.exports = PutTileAt; /***/ }), -/* 217 */ +/* 219 */ /***/ (function(module, exports) { /** @@ -47347,7 +45536,7 @@ module.exports = SetLayerCollisionIndex; /***/ }), -/* 218 */ +/* 220 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47356,10 +45545,10 @@ module.exports = SetLayerCollisionIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var LayerData = __webpack_require__(100); -var MapData = __webpack_require__(101); -var Tile = __webpack_require__(72); +var Formats = __webpack_require__(31); +var LayerData = __webpack_require__(104); +var MapData = __webpack_require__(105); +var Tile = __webpack_require__(74); /** * Parses a 2D array of tile indexes into a new MapData object with a single layer. @@ -47386,6 +45575,7 @@ var Parse2DArray = function (name, data, tileWidth, tileHeight, insertNull) tileWidth: tileWidth, tileHeight: tileHeight }); + var mapData = new MapData({ name: name, tileWidth: tileWidth, @@ -47438,7 +45628,7 @@ module.exports = Parse2DArray; /***/ }), -/* 219 */ +/* 221 */ /***/ (function(module, exports) { /** @@ -47528,7 +45718,7 @@ module.exports = ParseGID; /***/ }), -/* 220 */ +/* 222 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47589,7 +45779,7 @@ module.exports = CreateGroupLayer; /***/ }), -/* 221 */ +/* 223 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47598,8 +45788,8 @@ module.exports = CreateGroupLayer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Pick = __webpack_require__(481); -var ParseGID = __webpack_require__(219); +var Pick = __webpack_require__(480); +var ParseGID = __webpack_require__(221); var copyPoints = function (p) { return { x: p.x, y: p.y }; }; @@ -47671,7 +45861,7 @@ module.exports = ParseObject; /***/ }), -/* 222 */ +/* 224 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47680,10 +45870,10 @@ module.exports = ParseObject; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var MapData = __webpack_require__(101); -var Parse = __webpack_require__(473); -var Tilemap = __webpack_require__(489); +var Formats = __webpack_require__(31); +var MapData = __webpack_require__(105); +var Parse = __webpack_require__(472); +var Tilemap = __webpack_require__(488); /** * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When @@ -47757,7 +45947,7 @@ module.exports = ParseToTilemap; /***/ }), -/* 223 */ +/* 225 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47806,7 +45996,7 @@ module.exports = GetTargets; /***/ }), -/* 224 */ +/* 226 */ /***/ (function(module, exports) { /** @@ -48074,7 +46264,7 @@ module.exports = GetValueOp; /***/ }), -/* 225 */ +/* 227 */ /***/ (function(module, exports) { /** @@ -48118,7 +46308,7 @@ module.exports = TWEEN_DEFAULTS; /***/ }), -/* 226 */ +/* 228 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -48128,12 +46318,12 @@ module.exports = TWEEN_DEFAULTS; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(227); -var GameObjectCreator = __webpack_require__(17); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(229); +var GameObjectCreator = __webpack_require__(16); var GameObjectFactory = __webpack_require__(5); -var TWEEN_CONST = __webpack_require__(87); -var MATH_CONST = __webpack_require__(16); +var TWEEN_CONST = __webpack_require__(89); +var MATH_CONST = __webpack_require__(13); /** * @classdesc @@ -49762,7 +47952,7 @@ module.exports = Tween; /***/ }), -/* 227 */ +/* 229 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -49777,25 +47967,25 @@ module.exports = Tween; module.exports = { - TIMELINE_COMPLETE: __webpack_require__(1351), - TIMELINE_LOOP: __webpack_require__(1352), - TIMELINE_PAUSE: __webpack_require__(1353), - TIMELINE_RESUME: __webpack_require__(1354), - TIMELINE_START: __webpack_require__(1355), - TIMELINE_UPDATE: __webpack_require__(1356), - TWEEN_ACTIVE: __webpack_require__(1357), - TWEEN_COMPLETE: __webpack_require__(1358), - TWEEN_LOOP: __webpack_require__(1359), - TWEEN_REPEAT: __webpack_require__(1360), - TWEEN_START: __webpack_require__(1361), - TWEEN_UPDATE: __webpack_require__(1362), - TWEEN_YOYO: __webpack_require__(1363) + TIMELINE_COMPLETE: __webpack_require__(1346), + TIMELINE_LOOP: __webpack_require__(1347), + TIMELINE_PAUSE: __webpack_require__(1348), + TIMELINE_RESUME: __webpack_require__(1349), + TIMELINE_START: __webpack_require__(1350), + TIMELINE_UPDATE: __webpack_require__(1351), + TWEEN_ACTIVE: __webpack_require__(1352), + TWEEN_COMPLETE: __webpack_require__(1353), + TWEEN_LOOP: __webpack_require__(1354), + TWEEN_REPEAT: __webpack_require__(1355), + TWEEN_START: __webpack_require__(1356), + TWEEN_UPDATE: __webpack_require__(1357), + TWEEN_YOYO: __webpack_require__(1358) }; /***/ }), -/* 228 */ +/* 230 */ /***/ (function(module, exports) { /** @@ -49922,7 +48112,7 @@ module.exports = TweenData; /***/ }), -/* 229 */ +/* 231 */ /***/ (function(module, exports) { /** @@ -49976,7 +48166,7 @@ module.exports = ScaleModes; /***/ }), -/* 230 */ +/* 232 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50008,7 +48198,7 @@ module.exports = Wrap; /***/ }), -/* 231 */ +/* 233 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50040,7 +48230,7 @@ module.exports = WrapDegrees; /***/ }), -/* 232 */ +/* 234 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50051,14 +48241,783 @@ module.exports = WrapDegrees; */ var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); +var Utils = __webpack_require__(10); + +/** + * @classdesc + * WebGLPipeline is a class that describes the way elements will be renderered + * in WebGL, specially focused on batching vertices (batching is not provided). + * Pipelines are mostly used for describing 2D rendering passes but it's + * flexible enough to be used for any type of rendering including 3D. + * Internally WebGLPipeline will handle things like compiling shaders, + * creating vertex buffers, assigning primitive topology and binding + * vertex attributes. + * + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - gl: Current WebGL context. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * - vertices: An optional buffer of vertices + * - attributes: An array describing the vertex attributes + * + * The vertex attributes properties are: + * - name : String - Name of the attribute in the vertex shader + * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 + * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) + * - normalized : boolean - Is the attribute normalized + * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C + * Here you can find more information of how to describe an attribute: + * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer + * + * @class WebGLPipeline + * @memberof Phaser.Renderer.WebGL + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration object for this WebGL Pipeline, as described above. + */ +var WebGLPipeline = new Class({ + + initialize: + + function WebGLPipeline (config) + { + /** + * Name of the Pipeline. Used for identifying + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'WebGLPipeline'; + + /** + * The Game which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = config.game; + + /** + * The canvas which this WebGL Pipeline renders to. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#view + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.view = config.game.canvas; + + /** + * Used to store the current game resolution + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution + * @type {number} + * @since 3.0.0 + */ + this.resolution = 1; + + /** + * Width of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#width + * @type {number} + * @since 3.0.0 + */ + this.width = 0; + + /** + * Height of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#height + * @type {number} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The WebGL context this WebGL Pipeline uses. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#gl + * @type {WebGLRenderingContext} + * @since 3.0.0 + */ + this.gl = config.gl; + + /** + * How many vertices have been fed to the current pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.vertexCount = 0; + + /** + * The limit of vertices that the pipeline can hold + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity + * @type {integer} + * @since 3.0.0 + */ + this.vertexCapacity = config.vertexCapacity; + + /** + * The WebGL Renderer which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer + * @type {Phaser.Renderer.WebGL.WebGLRenderer} + * @since 3.0.0 + */ + this.renderer = config.renderer; + + /** + * Raw byte buffer of vertices. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData + * @type {ArrayBuffer} + * @since 3.0.0 + */ + this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); + + /** + * The handle to a WebGL vertex buffer object. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer + * @type {WebGLBuffer} + * @since 3.0.0 + */ + this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); + + /** + * The handle to a WebGL program + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#program + * @type {WebGLProgram} + * @since 3.0.0 + */ + this.program = this.renderer.createProgram(config.vertShader, config.fragShader); + + /** + * Array of objects that describe the vertex attributes + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes + * @type {object} + * @since 3.0.0 + */ + this.attributes = config.attributes; + + /** + * The size in bytes of the vertex + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize + * @type {integer} + * @since 3.0.0 + */ + this.vertexSize = config.vertexSize; + + /** + * The primitive topology which the pipeline will use to submit draw calls + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#topology + * @type {integer} + * @since 3.0.0 + */ + this.topology = config.topology; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources + * to the GPU. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes + * @type {Uint8Array} + * @since 3.0.0 + */ + this.bytes = new Uint8Array(this.vertexData); + + /** + * This will store the amount of components of 32 bit length + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount + * @type {integer} + * @since 3.0.0 + */ + this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); + + /** + * Indicates if the current pipeline is flushing the contents to the GPU. + * When the variable is set the flush function will be locked. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked + * @type {boolean} + * @since 3.1.0 + */ + this.flushLocked = false; + + /** + * Indicates if the current pipeline is active or not for this frame only. + * Reset in the onRender method. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#active + * @type {boolean} + * @since 3.10.0 + */ + this.active = false; + }, + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#boot + * @since 3.11.0 + */ + boot: function () + { + }, + + /** + * Adds a description of vertex attribute to the pipeline + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute + * @since 3.2.0 + * + * @param {string} name - Name of the vertex attribute + * @param {integer} size - Vertex component size + * @param {integer} type - Type of the attribute + * @param {boolean} normalized - Is the value normalized to a range + * @param {integer} offset - Byte offset to the beginning of the first element in the vertex + * + * @return {this} This WebGLPipeline instance. + */ + addAttribute: function (name, size, type, normalized, offset) + { + this.attributes.push({ + name: name, + size: size, + type: this.renderer.glFormats[type], + normalized: normalized, + offset: offset + }); + + this.vertexComponentCount = Utils.getComponentCount( + this.attributes, + this.gl + ); + return this; + }, + + /** + * Check if the current batch of vertices is full. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush + * @since 3.0.0 + * + * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. + */ + shouldFlush: function () + { + return (this.vertexCount >= this.vertexCapacity); + }, + + /** + * Resizes the properties used to describe the viewport + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width of this WebGL Pipeline. + * @param {number} height - The new height of this WebGL Pipeline. + * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + this.width = width * resolution; + this.height = height * resolution; + this.resolution = resolution; + + return this; + }, + + /** + * Binds the pipeline resources, including programs, vertex buffers and binds attributes + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#bind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + bind: function () + { + var gl = this.gl; + var vertexBuffer = this.vertexBuffer; + var attributes = this.attributes; + var program = this.program; + var renderer = this.renderer; + var vertexSize = this.vertexSize; + + renderer.setProgram(program); + renderer.setVertexBuffer(vertexBuffer); + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + var location = gl.getAttribLocation(program, element.name); + + if (location >= 0) + { + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); + } + else if (location !== -1) + { + gl.disableVertexAttribArray(location); + } + } + + return this; + }, + + /** + * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. + * + * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + // This is for updating uniform data it's called on each bind attempt. + return this; + }, + + /** + * Called before each frame is rendered, but after the canvas has been cleared. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPreRender: function () + { + // called once every frame + return this; + }, + + /** + * Called before a Scene's Camera is rendered. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. + * + * @return {this} This WebGLPipeline instance. + */ + onRender: function () + { + // called for each camera + return this; + }, + + /** + * Called after each frame has been completely rendered and snapshots have been taken. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPostRender: function () + { + // called once every frame + return this; + }, + + /** + * Uploads the vertex data and emits a draw call + * for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#flush + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) { return this; } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + + if (vertexCount === 0) + { + this.flushLocked = false; + return; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + gl.drawArrays(topology, 0, vertexCount); + + this.vertexCount = 0; + this.flushLocked = false; + + return this; + }, + + /** + * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + destroy: function () + { + var gl = this.gl; + + gl.deleteProgram(this.program); + gl.deleteBuffer(this.vertexBuffer); + + delete this.program; + delete this.vertexBuffer; + delete this.gl; + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new value of the `float` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1: function (name, x) + { + this.renderer.setFloat1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec2` uniform. + * @param {number} y - The new Y component of the `vec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2: function (name, x, y) + { + this.renderer.setFloat2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec3` uniform. + * @param {number} y - The new Y component of the `vec3` uniform. + * @param {number} z - The new Z component of the `vec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3: function (name, x, y, z) + { + this.renderer.setFloat3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - X component of the uniform + * @param {number} y - Y component of the uniform + * @param {number} z - Z component of the uniform + * @param {number} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4: function (name, x, y, z, w) + { + this.renderer.setFloat4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1v: function (name, arr) + { + this.renderer.setFloat1v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2v: function (name, arr) + { + this.renderer.setFloat2v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3v: function (name, arr) + { + this.renderer.setFloat3v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4v: function (name, arr) + { + this.renderer.setFloat4v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new value of the `int` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt1: function (name, x) + { + this.renderer.setInt1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec2` uniform. + * @param {integer} y - The new Y component of the `ivec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt2: function (name, x, y) + { + this.renderer.setInt2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec3` uniform. + * @param {integer} y - The new Y component of the `ivec3` uniform. + * @param {integer} z - The new Z component of the `ivec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt3: function (name, x, y, z) + { + this.renderer.setInt3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - X component of the uniform + * @param {integer} y - Y component of the uniform + * @param {integer} z - Z component of the uniform + * @param {integer} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setInt4: function (name, x, y, z, w) + { + this.renderer.setInt4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix2: function (name, transpose, matrix) + { + this.renderer.setMatrix2(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix3: function (name, transpose, matrix) + { + this.renderer.setMatrix3(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Should the matrix be transpose + * @param {Float32Array} matrix - Matrix data + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix4: function (name, transpose, matrix) + { + this.renderer.setMatrix4(this.program, name, transpose, matrix); + + return this; + } + +}); + +module.exports = WebGLPipeline; + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Earcut = __webpack_require__(66); var GetFastValue = __webpack_require__(2); -var ModelViewProjection = __webpack_require__(233); -var ShaderSourceFS = __webpack_require__(335); -var ShaderSourceVS = __webpack_require__(336); -var TransformMatrix = __webpack_require__(30); -var Utils = __webpack_require__(9); -var WebGLPipeline = __webpack_require__(141); +var ModelViewProjection = __webpack_require__(506); +var ShaderSourceFS = __webpack_require__(779); +var ShaderSourceVS = __webpack_require__(780); +var TransformMatrix = __webpack_require__(32); +var Utils = __webpack_require__(10); +var WebGLPipeline = __webpack_require__(234); /** * @classdesc @@ -51548,759 +50507,9 @@ module.exports = TextureTintPipeline; /***/ }), -/* 233 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Implements a model view projection matrices. - * Pipelines can implement this for doing 2D and 3D rendering. - * - * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection - * @since 3.0.0 - */ -var ModelViewProjection = { - - /** - * Dirty flag for checking if model matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - modelMatrixDirty: false, - - /** - * Dirty flag for checking if view matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - viewMatrixDirty: false, - - /** - * Dirty flag for checking if projection matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - projectionMatrixDirty: false, - - /** - * Model matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - modelMatrix: null, - - /** - * View matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - viewMatrix: null, - - /** - * Projection matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - projectionMatrix: null, - - /** - * Initializes MVP matrices with an identity matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit - * @since 3.0.0 - */ - mvpInit: function () - { - this.modelMatrixDirty = true; - this.viewMatrixDirty = true; - this.projectionMatrixDirty = true; - - this.modelMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - this.viewMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - this.projectionMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - return this; - }, - - /** - * If dirty flags are set then the matrices are uploaded to the GPU. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate - * @since 3.0.0 - */ - mvpUpdate: function () - { - var program = this.program; - - if (this.modelMatrixDirty) - { - this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); - this.modelMatrixDirty = false; - } - - if (this.viewMatrixDirty) - { - this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); - this.viewMatrixDirty = false; - } - - if (this.projectionMatrixDirty) - { - this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); - this.projectionMatrixDirty = false; - } - - return this; - }, - - /** - * Loads an identity matrix to the model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity - * @since 3.0.0 - */ - modelIdentity: function () - { - var modelMatrix = this.modelMatrix; - - modelMatrix[0] = 1; - modelMatrix[1] = 0; - modelMatrix[2] = 0; - modelMatrix[3] = 0; - modelMatrix[4] = 0; - modelMatrix[5] = 1; - modelMatrix[6] = 0; - modelMatrix[7] = 0; - modelMatrix[8] = 0; - modelMatrix[9] = 0; - modelMatrix[10] = 1; - modelMatrix[11] = 0; - modelMatrix[12] = 0; - modelMatrix[13] = 0; - modelMatrix[14] = 0; - modelMatrix[15] = 1; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Scale model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - modelScale: function (x, y, z) - { - var modelMatrix = this.modelMatrix; - - modelMatrix[0] = modelMatrix[0] * x; - modelMatrix[1] = modelMatrix[1] * x; - modelMatrix[2] = modelMatrix[2] * x; - modelMatrix[3] = modelMatrix[3] * x; - modelMatrix[4] = modelMatrix[4] * y; - modelMatrix[5] = modelMatrix[5] * y; - modelMatrix[6] = modelMatrix[6] * y; - modelMatrix[7] = modelMatrix[7] * y; - modelMatrix[8] = modelMatrix[8] * z; - modelMatrix[9] = modelMatrix[9] * z; - modelMatrix[10] = modelMatrix[10] * z; - modelMatrix[11] = modelMatrix[11] * z; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Translate model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - modelTranslate: function (x, y, z) - { - var modelMatrix = this.modelMatrix; - - modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; - modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; - modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; - modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the X axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateX: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a10 = modelMatrix[4]; - var a11 = modelMatrix[5]; - var a12 = modelMatrix[6]; - var a13 = modelMatrix[7]; - var a20 = modelMatrix[8]; - var a21 = modelMatrix[9]; - var a22 = modelMatrix[10]; - var a23 = modelMatrix[11]; - - modelMatrix[4] = a10 * c + a20 * s; - modelMatrix[5] = a11 * c + a21 * s; - modelMatrix[6] = a12 * c + a22 * s; - modelMatrix[7] = a13 * c + a23 * s; - modelMatrix[8] = a20 * c - a10 * s; - modelMatrix[9] = a21 * c - a11 * s; - modelMatrix[10] = a22 * c - a12 * s; - modelMatrix[11] = a23 * c - a13 * s; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the Y axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateY: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = modelMatrix[0]; - var a01 = modelMatrix[1]; - var a02 = modelMatrix[2]; - var a03 = modelMatrix[3]; - var a20 = modelMatrix[8]; - var a21 = modelMatrix[9]; - var a22 = modelMatrix[10]; - var a23 = modelMatrix[11]; - - modelMatrix[0] = a00 * c - a20 * s; - modelMatrix[1] = a01 * c - a21 * s; - modelMatrix[2] = a02 * c - a22 * s; - modelMatrix[3] = a03 * c - a23 * s; - modelMatrix[8] = a00 * s + a20 * c; - modelMatrix[9] = a01 * s + a21 * c; - modelMatrix[10] = a02 * s + a22 * c; - modelMatrix[11] = a03 * s + a23 * c; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the Z axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateZ: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = modelMatrix[0]; - var a01 = modelMatrix[1]; - var a02 = modelMatrix[2]; - var a03 = modelMatrix[3]; - var a10 = modelMatrix[4]; - var a11 = modelMatrix[5]; - var a12 = modelMatrix[6]; - var a13 = modelMatrix[7]; - - modelMatrix[0] = a00 * c + a10 * s; - modelMatrix[1] = a01 * c + a11 * s; - modelMatrix[2] = a02 * c + a12 * s; - modelMatrix[3] = a03 * c + a13 * s; - modelMatrix[4] = a10 * c - a00 * s; - modelMatrix[5] = a11 * c - a01 * s; - modelMatrix[6] = a12 * c - a02 * s; - modelMatrix[7] = a13 * c - a03 * s; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Loads identity matrix into the view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity - * @since 3.0.0 - * - * @return {this} This Model View Projection. - */ - viewIdentity: function () - { - var viewMatrix = this.viewMatrix; - - viewMatrix[0] = 1; - viewMatrix[1] = 0; - viewMatrix[2] = 0; - viewMatrix[3] = 0; - viewMatrix[4] = 0; - viewMatrix[5] = 1; - viewMatrix[6] = 0; - viewMatrix[7] = 0; - viewMatrix[8] = 0; - viewMatrix[9] = 0; - viewMatrix[10] = 1; - viewMatrix[11] = 0; - viewMatrix[12] = 0; - viewMatrix[13] = 0; - viewMatrix[14] = 0; - viewMatrix[15] = 1; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Scales view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - viewScale: function (x, y, z) - { - var viewMatrix = this.viewMatrix; - - viewMatrix[0] = viewMatrix[0] * x; - viewMatrix[1] = viewMatrix[1] * x; - viewMatrix[2] = viewMatrix[2] * x; - viewMatrix[3] = viewMatrix[3] * x; - viewMatrix[4] = viewMatrix[4] * y; - viewMatrix[5] = viewMatrix[5] * y; - viewMatrix[6] = viewMatrix[6] * y; - viewMatrix[7] = viewMatrix[7] * y; - viewMatrix[8] = viewMatrix[8] * z; - viewMatrix[9] = viewMatrix[9] * z; - viewMatrix[10] = viewMatrix[10] * z; - viewMatrix[11] = viewMatrix[11] * z; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Translates view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - viewTranslate: function (x, y, z) - { - var viewMatrix = this.viewMatrix; - - viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; - viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; - viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; - viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the X axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateX: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a10 = viewMatrix[4]; - var a11 = viewMatrix[5]; - var a12 = viewMatrix[6]; - var a13 = viewMatrix[7]; - var a20 = viewMatrix[8]; - var a21 = viewMatrix[9]; - var a22 = viewMatrix[10]; - var a23 = viewMatrix[11]; - - viewMatrix[4] = a10 * c + a20 * s; - viewMatrix[5] = a11 * c + a21 * s; - viewMatrix[6] = a12 * c + a22 * s; - viewMatrix[7] = a13 * c + a23 * s; - viewMatrix[8] = a20 * c - a10 * s; - viewMatrix[9] = a21 * c - a11 * s; - viewMatrix[10] = a22 * c - a12 * s; - viewMatrix[11] = a23 * c - a13 * s; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the Y axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateY: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = viewMatrix[0]; - var a01 = viewMatrix[1]; - var a02 = viewMatrix[2]; - var a03 = viewMatrix[3]; - var a20 = viewMatrix[8]; - var a21 = viewMatrix[9]; - var a22 = viewMatrix[10]; - var a23 = viewMatrix[11]; - - viewMatrix[0] = a00 * c - a20 * s; - viewMatrix[1] = a01 * c - a21 * s; - viewMatrix[2] = a02 * c - a22 * s; - viewMatrix[3] = a03 * c - a23 * s; - viewMatrix[8] = a00 * s + a20 * c; - viewMatrix[9] = a01 * s + a21 * c; - viewMatrix[10] = a02 * s + a22 * c; - viewMatrix[11] = a03 * s + a23 * c; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the Z axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateZ: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = viewMatrix[0]; - var a01 = viewMatrix[1]; - var a02 = viewMatrix[2]; - var a03 = viewMatrix[3]; - var a10 = viewMatrix[4]; - var a11 = viewMatrix[5]; - var a12 = viewMatrix[6]; - var a13 = viewMatrix[7]; - - viewMatrix[0] = a00 * c + a10 * s; - viewMatrix[1] = a01 * c + a11 * s; - viewMatrix[2] = a02 * c + a12 * s; - viewMatrix[3] = a03 * c + a13 * s; - viewMatrix[4] = a10 * c - a00 * s; - viewMatrix[5] = a11 * c - a01 * s; - viewMatrix[6] = a12 * c - a02 * s; - viewMatrix[7] = a13 * c - a03 * s; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D - * @since 3.0.0 - * - * @param {Float32Array} matrix2D - The Matrix2D. - * - * @return {this} This Model View Projection. - */ - viewLoad2D: function (matrix2D) - { - var vm = this.viewMatrix; - - vm[0] = matrix2D[0]; - vm[1] = matrix2D[1]; - vm[2] = 0.0; - vm[3] = 0.0; - vm[4] = matrix2D[2]; - vm[5] = matrix2D[3]; - vm[6] = 0.0; - vm[7] = 0.0; - vm[8] = matrix2D[4]; - vm[9] = matrix2D[5]; - vm[10] = 1.0; - vm[11] = 0.0; - vm[12] = 0.0; - vm[13] = 0.0; - vm[14] = 0.0; - vm[15] = 1.0; - - this.viewMatrixDirty = true; - - return this; - }, - - - /** - * Copies a 4x4 matrix into the view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad - * @since 3.0.0 - * - * @param {Float32Array} matrix - The Matrix2D. - * - * @return {this} This Model View Projection. - */ - viewLoad: function (matrix) - { - var vm = this.viewMatrix; - - vm[0] = matrix[0]; - vm[1] = matrix[1]; - vm[2] = matrix[2]; - vm[3] = matrix[3]; - vm[4] = matrix[4]; - vm[5] = matrix[5]; - vm[6] = matrix[6]; - vm[7] = matrix[7]; - vm[8] = matrix[8]; - vm[9] = matrix[9]; - vm[10] = matrix[10]; - vm[11] = matrix[11]; - vm[12] = matrix[12]; - vm[13] = matrix[13]; - vm[14] = matrix[14]; - vm[15] = matrix[15]; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Loads identity matrix into the projection matrix. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity - * @since 3.0.0 - * - * @return {this} This Model View Projection. - */ - projIdentity: function () - { - var projectionMatrix = this.projectionMatrix; - - projectionMatrix[0] = 1; - projectionMatrix[1] = 0; - projectionMatrix[2] = 0; - projectionMatrix[3] = 0; - projectionMatrix[4] = 0; - projectionMatrix[5] = 1; - projectionMatrix[6] = 0; - projectionMatrix[7] = 0; - projectionMatrix[8] = 0; - projectionMatrix[9] = 0; - projectionMatrix[10] = 1; - projectionMatrix[11] = 0; - projectionMatrix[12] = 0; - projectionMatrix[13] = 0; - projectionMatrix[14] = 0; - projectionMatrix[15] = 1; - - this.projectionMatrixDirty = true; - - return this; - }, - - /** - * Sets up an orthographic projection matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho - * @since 3.0.0 - * - * @param {number} left - The left value. - * @param {number} right - The right value. - * @param {number} bottom - The bottom value. - * @param {number} top - The top value. - * @param {number} near - The near value. - * @param {number} far - The far value. - * - * @return {this} This Model View Projection. - */ - projOrtho: function (left, right, bottom, top, near, far) - { - var projectionMatrix = this.projectionMatrix; - var leftRight = 1.0 / (left - right); - var bottomTop = 1.0 / (bottom - top); - var nearFar = 1.0 / (near - far); - - projectionMatrix[0] = -2.0 * leftRight; - projectionMatrix[1] = 0.0; - projectionMatrix[2] = 0.0; - projectionMatrix[3] = 0.0; - projectionMatrix[4] = 0.0; - projectionMatrix[5] = -2.0 * bottomTop; - projectionMatrix[6] = 0.0; - projectionMatrix[7] = 0.0; - projectionMatrix[8] = 0.0; - projectionMatrix[9] = 0.0; - projectionMatrix[10] = 2.0 * nearFar; - projectionMatrix[11] = 0.0; - projectionMatrix[12] = (left + right) * leftRight; - projectionMatrix[13] = (top + bottom) * bottomTop; - projectionMatrix[14] = (far + near) * nearFar; - projectionMatrix[15] = 1.0; - - this.projectionMatrixDirty = true; - - return this; - }, - - /** - * Sets up a perspective projection matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp - * @since 3.0.0 - * - * @param {number} fovY - The fov value. - * @param {number} aspectRatio - The aspectRatio value. - * @param {number} near - The near value. - * @param {number} far - The far value. - * - * @return {this} This Model View Projection. - */ - projPersp: function (fovY, aspectRatio, near, far) - { - var projectionMatrix = this.projectionMatrix; - var fov = 1.0 / Math.tan(fovY / 2.0); - var nearFar = 1.0 / (near - far); - - projectionMatrix[0] = fov / aspectRatio; - projectionMatrix[1] = 0.0; - projectionMatrix[2] = 0.0; - projectionMatrix[3] = 0.0; - projectionMatrix[4] = 0.0; - projectionMatrix[5] = fov; - projectionMatrix[6] = 0.0; - projectionMatrix[7] = 0.0; - projectionMatrix[8] = 0.0; - projectionMatrix[9] = 0.0; - projectionMatrix[10] = (far + near) * nearFar; - projectionMatrix[11] = -1.0; - projectionMatrix[12] = 0.0; - projectionMatrix[13] = 0.0; - projectionMatrix[14] = (2.0 * far * near) * nearFar; - projectionMatrix[15] = 0.0; - - this.projectionMatrixDirty = true; - - return this; - } -}; - -module.exports = ModelViewProjection; - - -/***/ }), -/* 234 */, -/* 235 */, -/* 236 */ +/* 236 */, +/* 237 */, +/* 238 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52315,65 +50524,65 @@ module.exports = ModelViewProjection; module.exports = { - AlignTo: __webpack_require__(522), - Angle: __webpack_require__(523), - Call: __webpack_require__(524), - GetFirst: __webpack_require__(525), - GetLast: __webpack_require__(526), - GridAlign: __webpack_require__(527), - IncAlpha: __webpack_require__(588), - IncX: __webpack_require__(589), - IncXY: __webpack_require__(590), - IncY: __webpack_require__(591), - PlaceOnCircle: __webpack_require__(592), - PlaceOnEllipse: __webpack_require__(593), - PlaceOnLine: __webpack_require__(594), - PlaceOnRectangle: __webpack_require__(595), - PlaceOnTriangle: __webpack_require__(596), - PlayAnimation: __webpack_require__(597), + AlignTo: __webpack_require__(521), + Angle: __webpack_require__(522), + Call: __webpack_require__(523), + GetFirst: __webpack_require__(524), + GetLast: __webpack_require__(525), + GridAlign: __webpack_require__(526), + IncAlpha: __webpack_require__(587), + IncX: __webpack_require__(588), + IncXY: __webpack_require__(589), + IncY: __webpack_require__(590), + PlaceOnCircle: __webpack_require__(591), + PlaceOnEllipse: __webpack_require__(592), + PlaceOnLine: __webpack_require__(593), + PlaceOnRectangle: __webpack_require__(594), + PlaceOnTriangle: __webpack_require__(595), + PlayAnimation: __webpack_require__(596), PropertyValueInc: __webpack_require__(34), - PropertyValueSet: __webpack_require__(26), - RandomCircle: __webpack_require__(598), - RandomEllipse: __webpack_require__(599), - RandomLine: __webpack_require__(600), - RandomRectangle: __webpack_require__(601), - RandomTriangle: __webpack_require__(602), - Rotate: __webpack_require__(603), - RotateAround: __webpack_require__(604), - RotateAroundDistance: __webpack_require__(605), - ScaleX: __webpack_require__(606), - ScaleXY: __webpack_require__(607), - ScaleY: __webpack_require__(608), - SetAlpha: __webpack_require__(609), - SetBlendMode: __webpack_require__(610), - SetDepth: __webpack_require__(611), - SetHitArea: __webpack_require__(612), - SetOrigin: __webpack_require__(613), - SetRotation: __webpack_require__(614), - SetScale: __webpack_require__(615), - SetScaleX: __webpack_require__(616), - SetScaleY: __webpack_require__(617), - SetScrollFactor: __webpack_require__(618), - SetScrollFactorX: __webpack_require__(619), - SetScrollFactorY: __webpack_require__(620), - SetTint: __webpack_require__(621), - SetVisible: __webpack_require__(622), - SetX: __webpack_require__(623), - SetXY: __webpack_require__(624), - SetY: __webpack_require__(625), - ShiftPosition: __webpack_require__(626), - Shuffle: __webpack_require__(627), - SmootherStep: __webpack_require__(628), - SmoothStep: __webpack_require__(629), - Spread: __webpack_require__(630), - ToggleVisible: __webpack_require__(631), - WrapInRectangle: __webpack_require__(632) + PropertyValueSet: __webpack_require__(25), + RandomCircle: __webpack_require__(597), + RandomEllipse: __webpack_require__(598), + RandomLine: __webpack_require__(599), + RandomRectangle: __webpack_require__(600), + RandomTriangle: __webpack_require__(601), + Rotate: __webpack_require__(602), + RotateAround: __webpack_require__(603), + RotateAroundDistance: __webpack_require__(604), + ScaleX: __webpack_require__(605), + ScaleXY: __webpack_require__(606), + ScaleY: __webpack_require__(607), + SetAlpha: __webpack_require__(608), + SetBlendMode: __webpack_require__(609), + SetDepth: __webpack_require__(610), + SetHitArea: __webpack_require__(611), + SetOrigin: __webpack_require__(612), + SetRotation: __webpack_require__(613), + SetScale: __webpack_require__(614), + SetScaleX: __webpack_require__(615), + SetScaleY: __webpack_require__(616), + SetScrollFactor: __webpack_require__(617), + SetScrollFactorX: __webpack_require__(618), + SetScrollFactorY: __webpack_require__(619), + SetTint: __webpack_require__(620), + SetVisible: __webpack_require__(621), + SetX: __webpack_require__(622), + SetXY: __webpack_require__(623), + SetY: __webpack_require__(624), + ShiftPosition: __webpack_require__(625), + Shuffle: __webpack_require__(626), + SmootherStep: __webpack_require__(627), + SmoothStep: __webpack_require__(628), + Spread: __webpack_require__(629), + ToggleVisible: __webpack_require__(630), + WrapInRectangle: __webpack_require__(631) }; /***/ }), -/* 237 */ +/* 239 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52382,22 +50591,22 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ALIGN_CONST = __webpack_require__(102); +var ALIGN_CONST = __webpack_require__(106); var AlignToMap = []; -AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(238); -AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(239); -AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(240); -AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = __webpack_require__(241); -AlignToMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(242); -AlignToMap[ALIGN_CONST.LEFT_TOP] = __webpack_require__(243); -AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = __webpack_require__(244); -AlignToMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(245); -AlignToMap[ALIGN_CONST.RIGHT_TOP] = __webpack_require__(246); -AlignToMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(247); -AlignToMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(248); -AlignToMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(249); +AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(240); +AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(241); +AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(242); +AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = __webpack_require__(243); +AlignToMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(244); +AlignToMap[ALIGN_CONST.LEFT_TOP] = __webpack_require__(245); +AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = __webpack_require__(246); +AlignToMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(247); +AlignToMap[ALIGN_CONST.RIGHT_TOP] = __webpack_require__(248); +AlignToMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(249); +AlignToMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(250); +AlignToMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(251); /** * Takes a Game Object and aligns it next to another, at the given position. @@ -52425,7 +50634,7 @@ module.exports = QuickSet; /***/ }), -/* 238 */ +/* 240 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52435,8 +50644,8 @@ module.exports = QuickSet; */ var GetBottom = __webpack_require__(38); -var GetCenterX = __webpack_require__(74); -var SetCenterX = __webpack_require__(75); +var GetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); var SetTop = __webpack_require__(39); /** @@ -52469,7 +50678,7 @@ module.exports = BottomCenter; /***/ }), -/* 239 */ +/* 241 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52513,7 +50722,7 @@ module.exports = BottomLeft; /***/ }), -/* 240 */ +/* 242 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52557,7 +50766,7 @@ module.exports = BottomRight; /***/ }), -/* 241 */ +/* 243 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52601,7 +50810,7 @@ module.exports = LeftBottom; /***/ }), -/* 242 */ +/* 244 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52610,9 +50819,9 @@ module.exports = LeftBottom; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetLeft = __webpack_require__(40); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetRight = __webpack_require__(43); /** @@ -52645,7 +50854,7 @@ module.exports = LeftCenter; /***/ }), -/* 243 */ +/* 245 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52689,7 +50898,7 @@ module.exports = LeftTop; /***/ }), -/* 244 */ +/* 246 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52733,7 +50942,7 @@ module.exports = RightBottom; /***/ }), -/* 245 */ +/* 247 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52742,9 +50951,9 @@ module.exports = RightBottom; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetRight = __webpack_require__(42); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetLeft = __webpack_require__(41); /** @@ -52777,7 +50986,7 @@ module.exports = RightCenter; /***/ }), -/* 246 */ +/* 248 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52821,7 +51030,7 @@ module.exports = RightTop; /***/ }), -/* 247 */ +/* 249 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52830,10 +51039,10 @@ module.exports = RightTop; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterX = __webpack_require__(74); +var GetCenterX = __webpack_require__(75); var GetTop = __webpack_require__(45); var SetBottom = __webpack_require__(44); -var SetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); /** * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. @@ -52865,7 +51074,7 @@ module.exports = TopCenter; /***/ }), -/* 248 */ +/* 250 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52909,7 +51118,7 @@ module.exports = TopLeft; /***/ }), -/* 249 */ +/* 251 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52953,7 +51162,7 @@ module.exports = TopRight; /***/ }), -/* 250 */ +/* 252 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52962,19 +51171,19 @@ module.exports = TopRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ALIGN_CONST = __webpack_require__(102); +var ALIGN_CONST = __webpack_require__(106); var AlignInMap = []; -AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(251); -AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(252); -AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(253); -AlignInMap[ALIGN_CONST.CENTER] = __webpack_require__(254); -AlignInMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(256); -AlignInMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(257); -AlignInMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(258); -AlignInMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(259); -AlignInMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(260); +AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(253); +AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(254); +AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(255); +AlignInMap[ALIGN_CONST.CENTER] = __webpack_require__(256); +AlignInMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(258); +AlignInMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(259); +AlignInMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(260); +AlignInMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(261); +AlignInMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(262); AlignInMap[ALIGN_CONST.LEFT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_LEFT]; AlignInMap[ALIGN_CONST.LEFT_TOP] = AlignInMap[ALIGN_CONST.TOP_LEFT]; AlignInMap[ALIGN_CONST.RIGHT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_RIGHT]; @@ -53006,7 +51215,7 @@ module.exports = QuickSet; /***/ }), -/* 251 */ +/* 253 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53016,9 +51225,9 @@ module.exports = QuickSet; */ var GetBottom = __webpack_require__(38); -var GetCenterX = __webpack_require__(74); +var GetCenterX = __webpack_require__(75); var SetBottom = __webpack_require__(44); -var SetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); /** * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. @@ -53050,7 +51259,7 @@ module.exports = BottomCenter; /***/ }), -/* 252 */ +/* 254 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53094,7 +51303,7 @@ module.exports = BottomLeft; /***/ }), -/* 253 */ +/* 255 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53138,7 +51347,7 @@ module.exports = BottomRight; /***/ }), -/* 254 */ +/* 256 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53147,9 +51356,9 @@ module.exports = BottomRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CenterOn = __webpack_require__(255); -var GetCenterX = __webpack_require__(74); -var GetCenterY = __webpack_require__(76); +var CenterOn = __webpack_require__(257); +var GetCenterX = __webpack_require__(75); +var GetCenterY = __webpack_require__(77); /** * Takes given Game Object and aligns it so that it is positioned in the center of the other. @@ -53180,7 +51389,7 @@ module.exports = Center; /***/ }), -/* 255 */ +/* 257 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53189,8 +51398,8 @@ module.exports = Center; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetCenterX = __webpack_require__(75); -var SetCenterY = __webpack_require__(77); +var SetCenterX = __webpack_require__(76); +var SetCenterY = __webpack_require__(78); /** * Positions the Game Object so that it is centered on the given coordinates. @@ -53217,7 +51426,7 @@ module.exports = CenterOn; /***/ }), -/* 256 */ +/* 258 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53226,9 +51435,9 @@ module.exports = CenterOn; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetLeft = __webpack_require__(40); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetLeft = __webpack_require__(41); /** @@ -53261,7 +51470,7 @@ module.exports = LeftCenter; /***/ }), -/* 257 */ +/* 259 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53270,9 +51479,9 @@ module.exports = LeftCenter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetRight = __webpack_require__(42); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetRight = __webpack_require__(43); /** @@ -53305,7 +51514,7 @@ module.exports = RightCenter; /***/ }), -/* 258 */ +/* 260 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53314,9 +51523,9 @@ module.exports = RightCenter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterX = __webpack_require__(74); +var GetCenterX = __webpack_require__(75); var GetTop = __webpack_require__(45); -var SetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); var SetTop = __webpack_require__(39); /** @@ -53349,7 +51558,7 @@ module.exports = TopCenter; /***/ }), -/* 259 */ +/* 261 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53393,7 +51602,7 @@ module.exports = TopLeft; /***/ }), -/* 260 */ +/* 262 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53437,7 +51646,7 @@ module.exports = TopRight; /***/ }), -/* 261 */ +/* 263 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53446,9 +51655,9 @@ module.exports = TopRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CircumferencePoint = __webpack_require__(143); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var CircumferencePoint = __webpack_require__(146); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); var Point = __webpack_require__(4); /** @@ -53480,7 +51689,7 @@ module.exports = GetPoint; /***/ }), -/* 262 */ +/* 264 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53489,10 +51698,10 @@ module.exports = GetPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circumference = __webpack_require__(263); -var CircumferencePoint = __webpack_require__(143); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var Circumference = __webpack_require__(265); +var CircumferencePoint = __webpack_require__(146); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); /** * Returns an array of Point objects containing the coordinates of the points around the circumference of the Circle, @@ -53532,7 +51741,7 @@ module.exports = GetPoints; /***/ }), -/* 263 */ +/* 265 */ /***/ (function(module, exports) { /** @@ -53560,7 +51769,7 @@ module.exports = Circumference; /***/ }), -/* 264 */ +/* 266 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53569,7 +51778,7 @@ module.exports = Circumference; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); // bitmask flag for GameObject.renderMask var _FLAG = 2; // 0010 @@ -53670,7 +51879,7 @@ module.exports = AlphaSingle; /***/ }), -/* 265 */ +/* 267 */ /***/ (function(module, exports) { /** @@ -53754,7 +51963,7 @@ module.exports = FindClosestInSorted; /***/ }), -/* 266 */ +/* 268 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -53928,7 +52137,7 @@ module.exports = AnimationFrame; /***/ }), -/* 267 */ +/* 269 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54050,7 +52259,7 @@ module.exports = BlendMode; /***/ }), -/* 268 */ +/* 270 */ /***/ (function(module, exports) { /** @@ -54143,7 +52352,7 @@ module.exports = Depth; /***/ }), -/* 269 */ +/* 271 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54152,8 +52361,8 @@ module.exports = Depth; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetPoint = __webpack_require__(146); -var Perimeter = __webpack_require__(108); +var GetPoint = __webpack_require__(149); +var Perimeter = __webpack_require__(112); // Return an array of points from the perimeter of the rectangle // each spaced out based on the quantity or step required @@ -54197,7 +52406,7 @@ module.exports = GetPoints; /***/ }), -/* 270 */ +/* 272 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54236,7 +52445,7 @@ module.exports = GetPoint; /***/ }), -/* 271 */ +/* 273 */ /***/ (function(module, exports) { /** @@ -54276,7 +52485,7 @@ module.exports = RotateAround; /***/ }), -/* 272 */ +/* 274 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54285,8 +52494,8 @@ module.exports = RotateAround; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapMask = __webpack_require__(273); -var GeometryMask = __webpack_require__(274); +var BitmapMask = __webpack_require__(275); +var GeometryMask = __webpack_require__(276); /** * Provides methods used for getting and setting the mask of a Game Object. @@ -54423,7 +52632,7 @@ module.exports = Mask; /***/ }), -/* 273 */ +/* 275 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54433,7 +52642,7 @@ module.exports = Mask; */ var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); /** * @classdesc @@ -54716,7 +52925,7 @@ module.exports = BitmapMask; /***/ }), -/* 274 */ +/* 276 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -55031,7 +53240,7 @@ module.exports = GeometryMask; /***/ }), -/* 275 */ +/* 277 */ /***/ (function(module, exports) { /** @@ -55138,7 +53347,7 @@ module.exports = ScrollFactor; /***/ }), -/* 276 */ +/* 278 */ /***/ (function(module, exports) { /** @@ -55199,7 +53408,7 @@ module.exports = ToJSON; /***/ }), -/* 277 */ +/* 279 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -55208,10 +53417,10 @@ module.exports = ToJSON; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var TransformMatrix = __webpack_require__(30); -var WrapAngle = __webpack_require__(230); -var WrapAngleDegrees = __webpack_require__(231); +var MATH_CONST = __webpack_require__(13); +var TransformMatrix = __webpack_require__(32); +var WrapAngle = __webpack_require__(232); +var WrapAngleDegrees = __webpack_require__(233); // global bitmask flag for GameObject.renderMask (used by Scale) var _FLAG = 4; // 0100 @@ -55738,7 +53947,7 @@ module.exports = Transform; /***/ }), -/* 278 */ +/* 280 */ /***/ (function(module, exports) { /** @@ -55827,7 +54036,7 @@ module.exports = Visible; /***/ }), -/* 279 */ +/* 281 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -55842,16 +54051,16 @@ module.exports = Visible; module.exports = { - CHANGE_DATA: __webpack_require__(573), - CHANGE_DATA_KEY: __webpack_require__(574), - REMOVE_DATA: __webpack_require__(575), - SET_DATA: __webpack_require__(576) + CHANGE_DATA: __webpack_require__(572), + CHANGE_DATA_KEY: __webpack_require__(573), + REMOVE_DATA: __webpack_require__(574), + SET_DATA: __webpack_require__(575) }; /***/ }), -/* 280 */ +/* 282 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -55860,25 +54069,25 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Perimeter = __webpack_require__(108); +var Perimeter = __webpack_require__(112); var Point = __webpack_require__(4); /** - * Returns an array of points from the perimeter of the Rectangle, where each point is spaced out based - * on either the `step` value, or the `quantity`. + * Return an array of points from the perimeter of the rectangle + * each spaced out based on the quantity or step required * * @function Phaser.Geom.Rectangle.MarchingAnts * @since 3.0.0 * * @generic {Phaser.Geom.Point[]} 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 {integer} [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 {(array|Phaser.Geom.Point[])} [out] - An array in which the perimeter points will be stored. If not given, a new array instance is created. + * @param {Phaser.Geom.Rectangle} rect - [description] + * @param {number} step - [description] + * @param {integer} quantity - [description] + * @param {(array|Phaser.Geom.Point[])} [out] - [description] * - * @return {(array|Phaser.Geom.Point[])} An array containing the perimeter points from the Rectangle. + * @return {(array|Phaser.Geom.Point[])} [description] */ var MarchingAnts = function (rect, step, quantity, out) { @@ -55970,7 +54179,7 @@ module.exports = MarchingAnts; /***/ }), -/* 281 */ +/* 283 */ /***/ (function(module, exports) { /** @@ -56010,7 +54219,7 @@ module.exports = RotateLeft; /***/ }), -/* 282 */ +/* 284 */ /***/ (function(module, exports) { /** @@ -56050,7 +54259,7 @@ module.exports = RotateRight; /***/ }), -/* 283 */ +/* 285 */ /***/ (function(module, exports) { /** @@ -56124,7 +54333,7 @@ module.exports = BresenhamPoints; /***/ }), -/* 284 */ +/* 286 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56133,14 +54342,14 @@ module.exports = BresenhamPoints; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Animation = __webpack_require__(145); +var Animation = __webpack_require__(148); var Class = __webpack_require__(0); -var CustomMap = __webpack_require__(156); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(107); -var GameEvents = __webpack_require__(19); +var CustomMap = __webpack_require__(159); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(111); +var GameEvents = __webpack_require__(18); var GetValue = __webpack_require__(6); -var Pad = __webpack_require__(157); +var Pad = __webpack_require__(160); /** * @classdesc @@ -56391,34 +54600,7 @@ var AnimationManager = new Class({ }, /** - * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. - * - * Generates objects with string based frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNames}. - * - * It's a helper method, designed to make it easier for you to extract all of the frame names from texture atlases. - * If you're working with a sprite sheet, see the `generateFrameNumbers` method instead. - * - * Example: - * - * If you have a texture atlases loaded called `gems` and it contains 6 frames called `ruby_0001`, `ruby_0002`, and so on, - * then you can call this method using: `this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 })`. - * - * The `end` value tells it to look for 6 frames, incrementally numbered, all starting with the prefix `ruby_`. The `zeroPad` - * value tells it how many zeroes pad out the numbers. To create an animation using this method, you can do: - * - * ```javascript - * this.anims.create({ - * key: 'ruby', - * repeat: -1, - * frames: this.anims.generateFrameNames('gems', { - * prefix: 'ruby_', - * end: 6, - * zeroPad: 4 - * }) - * }); - * ``` - * - * Please see the animation examples for further details. + * [description] * * @method Phaser.Animations.AnimationManager#generateFrameNames * @since 3.0.0 @@ -56496,8 +54678,6 @@ var AnimationManager = new Class({ * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. * * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. - * - * If you're working with a texture atlas, see the `generateFrameNames` method instead. * * @method Phaser.Animations.AnimationManager#generateFrameNumbers * @since 3.0.0 @@ -56663,10 +54843,7 @@ var AnimationManager = new Class({ }, /** - * 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. + * Remove an animation. * * @method Phaser.Animations.AnimationManager#remove * @fires Phaser.Animations.Events#REMOVE_ANIMATION @@ -56674,7 +54851,7 @@ var AnimationManager = new Class({ * * @param {string} key - The key of the animation to remove. * - * @return {Phaser.Animations.Animation} The Animation instance that was removed from the Animation Manager. + * @return {Phaser.Animations.Animation} [description] */ remove: function (key) { @@ -56752,36 +54929,35 @@ var AnimationManager = new Class({ }, /** - * Returns the Animation data as JavaScript object based on the given key. - * Or, if not key is defined, it will return the data of all animations as array of objects. + * Get the animation data as javascript object by giving key, or get the data of all animations as array of objects, if key wasn't provided. * * @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. + * @param {string} key - [description] * - * @return {Phaser.Types.Animations.JSONAnimations} The resulting JSONAnimations formatted object. + * @return {Phaser.Types.Animations.JSONAnimations} [description] */ toJSON: function (key) { - var output = { - anims: [], - globalTimeScale: this.globalTimeScale - }; - if (key !== undefined && key !== '') { - output.anims.push(this.anims.get(key).toJSON()); + return this.anims.get(key).toJSON(); } else { + var output = { + anims: [], + globalTimeScale: this.globalTimeScale + }; + this.anims.each(function (animationKey, animation) { output.anims.push(animation.toJSON()); }); - } - return output; + return output; + } }, /** @@ -56806,7 +54982,7 @@ module.exports = AnimationManager; /***/ }), -/* 285 */ +/* 287 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56816,9 +54992,9 @@ module.exports = AnimationManager; */ var Class = __webpack_require__(0); -var CustomMap = __webpack_require__(156); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(286); +var CustomMap = __webpack_require__(159); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(288); /** * @classdesc @@ -56992,7 +55168,7 @@ module.exports = BaseCache; /***/ }), -/* 286 */ +/* 288 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57007,14 +55183,14 @@ module.exports = BaseCache; module.exports = { - ADD: __webpack_require__(635), - REMOVE: __webpack_require__(636) + ADD: __webpack_require__(634), + REMOVE: __webpack_require__(635) }; /***/ }), -/* 287 */ +/* 289 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57023,9 +55199,9 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCache = __webpack_require__(285); +var BaseCache = __webpack_require__(287); var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); /** * @classdesc @@ -57248,7 +55424,7 @@ module.exports = CacheManager; /***/ }), -/* 288 */ +/* 290 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57257,15 +55433,15 @@ module.exports = CacheManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCamera = __webpack_require__(89); -var CanvasPool = __webpack_require__(27); -var CenterOn = __webpack_require__(162); -var Clamp = __webpack_require__(23); +var BaseCamera = __webpack_require__(91); +var CanvasPool = __webpack_require__(26); +var CenterOn = __webpack_require__(165); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Effects = __webpack_require__(296); -var Linear = __webpack_require__(111); -var Rectangle = __webpack_require__(13); +var Effects = __webpack_require__(298); +var Linear = __webpack_require__(115); +var Rectangle = __webpack_require__(11); var Vector2 = __webpack_require__(3); /** @@ -57461,24 +55637,6 @@ var Camera = new Class({ */ this.renderToTexture = false; - /** - * If this Camera is rendering to a texture (via `setRenderToTexture`) then you - * have the option to control if it should also render to the Game canvas as well. - * - * By default, a Camera will render both to its texture and to the Game canvas. - * - * However, if you set ths property to `false` it will only render to the texture - * and skip rendering to the Game canvas. - * - * Setting this property if the Camera isn't rendering to a texture has no effect. - * - * @name Phaser.Cameras.Scene2D.Camera#renderToGame - * @type {boolean} - * @default true - * @since 3.23.0 - */ - this.renderToGame = true; - /** * If this Camera has been set to render to a texture then this holds a reference * to the HTML Canvas Element that the Camera is drawing to. @@ -57575,9 +55733,6 @@ var Camera = new Class({ * * You should not enable this unless you plan on actually using the texture it creates * somehow, otherwise you're just doubling the work required to render your game. - * - * If you only require the Camera to render to a texture, and not also to the Game, - * them set the `renderToGame` parameter to `false`. * * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. * @@ -57588,14 +55743,11 @@ var Camera = new Class({ * @since 3.13.0 * * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. - * @param {boolean} [renderToGame=true] - If you do not need the Camera to still render to the Game, set this parameter to `false`. * * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. */ - setRenderToTexture: function (pipeline, renderToGame) + setRenderToTexture: function (pipeline) { - if (renderToGame === undefined) { renderToGame = true; } - var renderer = this.scene.sys.game.renderer; if (renderer.gl) @@ -57610,7 +55762,6 @@ var Camera = new Class({ } this.renderToTexture = true; - this.renderToGame = renderToGame; if (pipeline) { @@ -58266,7 +56417,7 @@ module.exports = Camera; /***/ }), -/* 289 */ +/* 291 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58275,7 +56426,7 @@ module.exports = Camera; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); /** * Converts a hex string into a Phaser Color object. @@ -58319,7 +56470,7 @@ module.exports = HexStringToColor; /***/ }), -/* 290 */ +/* 292 */ /***/ (function(module, exports) { /** @@ -58350,7 +56501,7 @@ module.exports = GetColor32; /***/ }), -/* 291 */ +/* 293 */ /***/ (function(module, exports) { /** @@ -58430,7 +56581,7 @@ module.exports = RGBToHSV; /***/ }), -/* 292 */ +/* 294 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58439,8 +56590,8 @@ module.exports = RGBToHSV; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); -var IntegerToRGB = __webpack_require__(293); +var Color = __webpack_require__(33); +var IntegerToRGB = __webpack_require__(295); /** * Converts the given color value into an instance of a Color object. @@ -58463,7 +56614,7 @@ module.exports = IntegerToColor; /***/ }), -/* 293 */ +/* 295 */ /***/ (function(module, exports) { /** @@ -58511,7 +56662,7 @@ module.exports = IntegerToRGB; /***/ }), -/* 294 */ +/* 296 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58520,7 +56671,7 @@ module.exports = IntegerToRGB; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); /** * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. @@ -58541,7 +56692,7 @@ module.exports = ObjectToColor; /***/ }), -/* 295 */ +/* 297 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58550,7 +56701,7 @@ module.exports = ObjectToColor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); /** * Converts a CSS 'web' string into a Phaser Color object. @@ -58587,7 +56738,7 @@ module.exports = RGBStringToColor; /***/ }), -/* 296 */ +/* 298 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58602,57 +56753,11 @@ module.exports = RGBStringToColor; module.exports = { - Fade: __webpack_require__(657), - Flash: __webpack_require__(658), - Pan: __webpack_require__(659), - Shake: __webpack_require__(692), - Zoom: __webpack_require__(693) - -}; - - -/***/ }), -/* 297 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Back - */ - -module.exports = { - - In: __webpack_require__(660), - Out: __webpack_require__(661), - InOut: __webpack_require__(662) - -}; - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Bounce - */ - -module.exports = { - - In: __webpack_require__(663), - Out: __webpack_require__(664), - InOut: __webpack_require__(665) + Fade: __webpack_require__(656), + Flash: __webpack_require__(657), + Pan: __webpack_require__(658), + Shake: __webpack_require__(691), + Zoom: __webpack_require__(692) }; @@ -58668,14 +56773,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Circular + * @namespace Phaser.Math.Easing.Back */ module.exports = { - In: __webpack_require__(666), - Out: __webpack_require__(667), - InOut: __webpack_require__(668) + In: __webpack_require__(659), + Out: __webpack_require__(660), + InOut: __webpack_require__(661) }; @@ -58691,14 +56796,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Cubic + * @namespace Phaser.Math.Easing.Bounce */ module.exports = { - In: __webpack_require__(669), - Out: __webpack_require__(670), - InOut: __webpack_require__(671) + In: __webpack_require__(662), + Out: __webpack_require__(663), + InOut: __webpack_require__(664) }; @@ -58714,14 +56819,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Elastic + * @namespace Phaser.Math.Easing.Circular */ module.exports = { - In: __webpack_require__(672), - Out: __webpack_require__(673), - InOut: __webpack_require__(674) + In: __webpack_require__(665), + Out: __webpack_require__(666), + InOut: __webpack_require__(667) }; @@ -58737,14 +56842,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Expo + * @namespace Phaser.Math.Easing.Cubic */ module.exports = { - In: __webpack_require__(675), - Out: __webpack_require__(676), - InOut: __webpack_require__(677) + In: __webpack_require__(668), + Out: __webpack_require__(669), + InOut: __webpack_require__(670) }; @@ -58760,10 +56865,16 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Linear + * @namespace Phaser.Math.Easing.Elastic */ -module.exports = __webpack_require__(678); +module.exports = { + + In: __webpack_require__(671), + Out: __webpack_require__(672), + InOut: __webpack_require__(673) + +}; /***/ }), @@ -58777,14 +56888,14 @@ module.exports = __webpack_require__(678); */ /** - * @namespace Phaser.Math.Easing.Quadratic + * @namespace Phaser.Math.Easing.Expo */ module.exports = { - In: __webpack_require__(679), - Out: __webpack_require__(680), - InOut: __webpack_require__(681) + In: __webpack_require__(674), + Out: __webpack_require__(675), + InOut: __webpack_require__(676) }; @@ -58800,16 +56911,10 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Quartic + * @namespace Phaser.Math.Easing.Linear */ -module.exports = { - - In: __webpack_require__(682), - Out: __webpack_require__(683), - InOut: __webpack_require__(684) - -}; +module.exports = __webpack_require__(677); /***/ }), @@ -58823,14 +56928,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Quintic + * @namespace Phaser.Math.Easing.Quadratic */ module.exports = { - In: __webpack_require__(685), - Out: __webpack_require__(686), - InOut: __webpack_require__(687) + In: __webpack_require__(678), + Out: __webpack_require__(679), + InOut: __webpack_require__(680) }; @@ -58846,14 +56951,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Sine + * @namespace Phaser.Math.Easing.Quartic */ module.exports = { - In: __webpack_require__(688), - Out: __webpack_require__(689), - InOut: __webpack_require__(690) + In: __webpack_require__(681), + Out: __webpack_require__(682), + InOut: __webpack_require__(683) }; @@ -58869,16 +56974,62 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Stepped + * @namespace Phaser.Math.Easing.Quintic */ -module.exports = __webpack_require__(691); +module.exports = { + + In: __webpack_require__(684), + Out: __webpack_require__(685), + InOut: __webpack_require__(686) + +}; /***/ }), /* 309 */ /***/ (function(module, exports, __webpack_require__) { +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Sine + */ + +module.exports = { + + In: __webpack_require__(687), + Out: __webpack_require__(688), + InOut: __webpack_require__(689) + +}; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Stepped + */ + +module.exports = __webpack_require__(690); + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -58886,15 +57037,15 @@ module.exports = __webpack_require__(691); */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); -var Device = __webpack_require__(310); +var CONST = __webpack_require__(29); +var Device = __webpack_require__(312); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); var IsPlainObject = __webpack_require__(7); -var PhaserMath = __webpack_require__(165); +var PhaserMath = __webpack_require__(168); var NOOP = __webpack_require__(1); -var DefaultPlugins = __webpack_require__(170); -var ValueToColor = __webpack_require__(158); +var DefaultPlugins = __webpack_require__(173); +var ValueToColor = __webpack_require__(161); /** * @classdesc @@ -59361,11 +57512,6 @@ var Config = new Class({ */ this.loaderTimeout = GetValue(config, 'loader.timeout', 0); - /** - * @const {boolean} Phaser.Core.Config#loaderWithCredentials - Optional XHR withCredentials value. - */ - this.loaderWithCredentials = GetValue(config, 'loader.withCredentials', false); - /* * Allows `plugins` property to either be an array, in which case it just replaces * the default plugins like previously, or a config object. @@ -59457,7 +57603,7 @@ module.exports = Config; /***/ }), -/* 310 */ +/* 312 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -59491,20 +57637,20 @@ module.exports = Config; module.exports = { - os: __webpack_require__(112), - browser: __webpack_require__(113), - features: __webpack_require__(164), - input: __webpack_require__(722), - audio: __webpack_require__(723), - video: __webpack_require__(724), - fullscreen: __webpack_require__(725), - canvasFeatures: __webpack_require__(311) + os: __webpack_require__(116), + browser: __webpack_require__(117), + features: __webpack_require__(167), + input: __webpack_require__(721), + audio: __webpack_require__(722), + video: __webpack_require__(723), + fullscreen: __webpack_require__(724), + canvasFeatures: __webpack_require__(313) }; /***/ }), -/* 311 */ +/* 313 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -59513,7 +57659,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); /** * Determines the canvas features of the browser running this Phaser Game instance. @@ -59618,7 +57764,7 @@ module.exports = init(); /***/ }), -/* 312 */ +/* 314 */ /***/ (function(module, exports) { /** @@ -59649,7 +57795,7 @@ module.exports = Between; /***/ }), -/* 313 */ +/* 315 */ /***/ (function(module, exports) { /** @@ -59686,39 +57832,7 @@ module.exports = Normalize; /***/ }), -/* 314 */ -/***/ (function(module, exports) { - -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the distance between two points. - * - * @function Phaser.Math.Distance.BetweenPoints - * @since 3.22.0 - * - * @param {Phaser.Types.Math.Vector2Like} a - The first point. - * @param {Phaser.Types.Math.Vector2Like} b - The second point. - * - * @return {number} The distance between the points. - */ -var DistanceBetweenPoints = function (a, b) -{ - var dx = a.x - b.x; - var dy = a.y - b.y; - - return Math.sqrt(dx * dx + dy * dy); -}; - -module.exports = DistanceBetweenPoints; - - -/***/ }), -/* 315 */ +/* 316 */ /***/ (function(module, exports) { /** @@ -59752,7 +57866,7 @@ module.exports = DistanceSquared; /***/ }), -/* 316 */ +/* 317 */ /***/ (function(module, exports) { /** @@ -59786,7 +57900,7 @@ module.exports = GreaterThan; /***/ }), -/* 317 */ +/* 318 */ /***/ (function(module, exports) { /** @@ -59820,7 +57934,7 @@ module.exports = LessThan; /***/ }), -/* 318 */ +/* 319 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -59829,18 +57943,18 @@ module.exports = LessThan; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Factorial = __webpack_require__(319); +var Factorial = __webpack_require__(320); /** - * Calculates the Bernstein basis from the three factorial coefficients. + * [description] * * @function Phaser.Math.Bernstein * @since 3.0.0 * - * @param {number} n - The first value. - * @param {number} i - The second value. + * @param {number} n - [description] + * @param {number} i - [description] * - * @return {number} The Bernstein basis of Factorial(n) / Factorial(i) / Factorial(n - i) + * @return {number} [description] */ var Bernstein = function (n, i) { @@ -59851,7 +57965,7 @@ module.exports = Bernstein; /***/ }), -/* 319 */ +/* 320 */ /***/ (function(module, exports) { /** @@ -59891,7 +58005,7 @@ module.exports = Factorial; /***/ }), -/* 320 */ +/* 321 */ /***/ (function(module, exports) { /** @@ -59961,7 +58075,7 @@ module.exports = CubicBezierInterpolation; /***/ }), -/* 321 */ +/* 322 */ /***/ (function(module, exports) { /** @@ -60020,7 +58134,7 @@ module.exports = QuadraticBezierInterpolation; /***/ }), -/* 322 */ +/* 323 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -60029,7 +58143,7 @@ module.exports = QuadraticBezierInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SmoothStep = __webpack_require__(155); +var SmoothStep = __webpack_require__(158); /** * A Smooth Step interpolation method. @@ -60053,7 +58167,7 @@ module.exports = SmoothStepInterpolation; /***/ }), -/* 323 */ +/* 324 */ /***/ (function(module, exports) { /** @@ -60083,7 +58197,7 @@ module.exports = GetPowerOfTwo; /***/ }), -/* 324 */ +/* 325 */ /***/ (function(module, exports) { /** @@ -60127,7 +58241,7 @@ module.exports = SnapCeil; /***/ }), -/* 325 */ +/* 326 */ /***/ (function(module, exports) { /** @@ -60156,7 +58270,7 @@ module.exports = FloatBetween; /***/ }), -/* 326 */ +/* 327 */ /***/ (function(module, exports) { /** @@ -60191,7 +58305,7 @@ module.exports = Rotate; /***/ }), -/* 327 */ +/* 328 */ /***/ (function(module, exports) { /** @@ -60220,7 +58334,7 @@ module.exports = RoundAwayFromZero; /***/ }), -/* 328 */ +/* 329 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -60275,7 +58389,7 @@ module.exports = TransformXY; /***/ }), -/* 329 */ +/* 330 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -60820,7 +58934,7 @@ module.exports = Vector4; /***/ }), -/* 330 */ +/* 331 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -61333,12 +59447,12 @@ var Matrix3 = new Class({ }, /** - * Set the values of this Matrix3 to be normalized from the given Matrix4. + * [description] * * @method Phaser.Math.Matrix3#normalFromMat4 * @since 3.0.0 * - * @param {Phaser.Math.Matrix4} m - The Matrix4 to normalize the values from. + * @param {Phaser.Math.Matrix4} m - [description] * * @return {Phaser.Math.Matrix3} This Matrix3. */ @@ -61413,7 +59527,7 @@ module.exports = Matrix3; /***/ }), -/* 331 */ +/* 332 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -61977,12 +60091,12 @@ var Matrix4 = new Class({ }, /** - * Multiply the values of this Matrix4 by those given in the `src` argument. + * [description] * * @method Phaser.Math.Matrix4#multiplyLocal * @since 3.0.0 * - * @param {Phaser.Math.Matrix4} src - The source Matrix4 that this Matrix4 is multiplied by. + * @param {Phaser.Math.Matrix4} src - [description] * * @return {Phaser.Math.Matrix4} This Matrix4. */ @@ -62774,9 +60888,9 @@ var Matrix4 = new Class({ * @method Phaser.Math.Matrix4#yawPitchRoll * @since 3.0.0 * - * @param {number} yaw - The yaw value. - * @param {number} pitch - The pitch value. - * @param {number} roll - The roll value. + * @param {number} yaw - [description] + * @param {number} pitch - [description] + * @param {number} roll - [description] * * @return {Phaser.Math.Matrix4} This Matrix4. */ @@ -62875,7 +60989,7 @@ module.exports = Matrix4; /***/ }), -/* 332 */ +/* 333 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -62888,8 +61002,8 @@ module.exports = Matrix4; // and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl var Class = __webpack_require__(0); -var Vector3 = __webpack_require__(169); -var Matrix3 = __webpack_require__(330); +var Vector3 = __webpack_require__(172); +var Matrix3 = __webpack_require__(331); var EPSILON = 0.000001; @@ -63197,13 +61311,13 @@ var Quaternion = new Class({ }, /** - * Rotates this Quaternion based on the two given vectors. + * [description] * * @method Phaser.Math.Quaternion#rotationTo * @since 3.0.0 * - * @param {Phaser.Math.Vector3} a - The transform rotation vector. - * @param {Phaser.Math.Vector3} b - The target rotation vector. + * @param {Phaser.Math.Vector3} a - [description] + * @param {Phaser.Math.Vector3} b - [description] * * @return {Phaser.Math.Quaternion} This Quaternion. */ @@ -63647,7 +61761,7 @@ module.exports = Quaternion; /***/ }), -/* 333 */ +/* 334 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -63656,10 +61770,10 @@ module.exports = Quaternion; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasInterpolation = __webpack_require__(334); -var CanvasPool = __webpack_require__(27); -var CONST = __webpack_require__(10); -var Features = __webpack_require__(164); +var CanvasInterpolation = __webpack_require__(335); +var CanvasPool = __webpack_require__(26); +var CONST = __webpack_require__(29); +var Features = __webpack_require__(167); /** * Called automatically by Phaser.Game and responsible for creating the renderer it will use. @@ -63749,8 +61863,8 @@ var CreateRenderer = function (game) if (true) { - CanvasRenderer = __webpack_require__(500); - WebGLRenderer = __webpack_require__(503); + CanvasRenderer = __webpack_require__(499); + WebGLRenderer = __webpack_require__(502); // Let the config pick the renderer type, as both are included if (config.renderType === CONST.WEBGL) @@ -63775,7 +61889,7 @@ module.exports = CreateRenderer; /***/ }), -/* 334 */ +/* 335 */ /***/ (function(module, exports) { /** @@ -63837,87 +61951,8 @@ var CanvasInterpolation = { module.exports = CanvasInterpolation; -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - -module.exports = [ - '#define SHADER_NAME PHASER_TEXTURE_TINT_FS', - '', - 'precision mediump float;', - '', - 'uniform sampler2D uMainSampler;', - '', - 'varying vec2 outTexCoord;', - 'varying float outTintEffect;', - 'varying vec4 outTint;', - '', - 'void main()', - '{', - ' vec4 texture = texture2D(uMainSampler, outTexCoord);', - ' vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);', - ' vec4 color = texture;', - '', - ' if (outTintEffect == 0.0)', - ' {', - ' // Multiply texture tint', - ' color = texture * texel;', - ' }', - ' else if (outTintEffect == 1.0)', - ' {', - ' // Solid color + texture alpha', - ' color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);', - ' color.a = texture.a * texel.a;', - ' }', - ' else if (outTintEffect == 2.0)', - ' {', - ' // Solid color, no texture', - ' color = texel;', - ' }', - '', - ' gl_FragColor = color;', - '}', - '' -].join('\n'); - - /***/ }), /* 336 */ -/***/ (function(module, exports) { - -module.exports = [ - '#define SHADER_NAME PHASER_TEXTURE_TINT_VS', - '', - 'precision mediump float;', - '', - 'uniform mat4 uProjectionMatrix;', - 'uniform mat4 uViewMatrix;', - 'uniform mat4 uModelMatrix;', - '', - 'attribute vec2 inPosition;', - 'attribute vec2 inTexCoord;', - 'attribute float inTintEffect;', - 'attribute vec4 inTint;', - '', - 'varying vec2 outTexCoord;', - 'varying float outTintEffect;', - 'varying vec4 outTint;', - '', - 'void main ()', - '{', - ' gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);', - '', - ' outTexCoord = inTexCoord;', - ' outTint = inTint;', - ' outTintEffect = inTintEffect;', - '}', - '', - '' -].join('\n'); - - -/***/ }), -/* 337 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -63926,7 +61961,7 @@ module.exports = [ * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); +var CONST = __webpack_require__(29); /** * Called automatically by Phaser.Game and responsible for creating the console.log debug header. @@ -64047,7 +62082,7 @@ module.exports = DebugHeader; /***/ }), -/* 338 */ +/* 337 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64059,7 +62094,7 @@ module.exports = DebugHeader; var Class = __webpack_require__(0); var GetValue = __webpack_require__(6); var NOOP = __webpack_require__(1); -var RequestAnimationFrame = __webpack_require__(339); +var RequestAnimationFrame = __webpack_require__(338); // http://www.testufo.com/#test=animation-time-graph @@ -64777,7 +62812,7 @@ module.exports = TimeStep; /***/ }), -/* 339 */ +/* 338 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64991,7 +63026,7 @@ module.exports = RequestAnimationFrame; /***/ }), -/* 340 */ +/* 339 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -65000,7 +63035,7 @@ module.exports = RequestAnimationFrame; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Events = __webpack_require__(19); +var Events = __webpack_require__(18); /** * The Visibility Handler is responsible for listening out for document level visibility change events. @@ -65082,7 +63117,7 @@ module.exports = VisibilityHandler; /***/ }), -/* 341 */ +/* 340 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -65091,47 +63126,19 @@ module.exports = VisibilityHandler; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Arne16 = __webpack_require__(342); -var CanvasPool = __webpack_require__(27); +var Arne16 = __webpack_require__(341); +var CanvasPool = __webpack_require__(26); var GetValue = __webpack_require__(6); /** - * Generates a texture based on the given Create configuration object. - * - * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the - * data cells map to a single color. For example, if the texture config looked like this: - * - * ```javascript - * var star = [ - * '.....828.....', - * '....72227....', - * '....82228....', - * '...7222227...', - * '2222222222222', - * '8222222222228', - * '.72222222227.', - * '..787777787..', - * '..877777778..', - * '.78778887787.', - * '.27887.78872.', - * '.787.....787.' - * ]; - * - * this.textures.generate('star', { data: star, pixelWidth: 4 }); - * ``` - * - * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array - * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color - * number 8 in the palette. If a cell contains a period character `.` then it is transparent. - * - * The default palette is Arne16, but you can specify your own using the `palette` property. + * [description] * * @function Phaser.Create.GenerateTexture * @since 3.0.0 * - * @param {Phaser.Types.Create.GenerateTextureConfig} config - The Generate Texture Configuration object. + * @param {Phaser.Types.Create.GenerateTextureConfig} config - [description] * - * @return {HTMLCanvasElement} An HTMLCanvasElement which contains the generated texture drawn to it. + * @return {HTMLCanvasElement} [description] */ var GenerateTexture = function (config) { @@ -65204,7 +63211,7 @@ module.exports = GenerateTexture; /***/ }), -/* 342 */ +/* 341 */ /***/ (function(module, exports) { /** @@ -65242,7 +63249,7 @@ module.exports = { /***/ }), -/* 343 */ +/* 342 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -65254,8 +63261,8 @@ module.exports = { // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var CubicBezier = __webpack_require__(320); -var Curve = __webpack_require__(79); +var CubicBezier = __webpack_require__(321); +var Curve = __webpack_require__(80); var Vector2 = __webpack_require__(3); /** @@ -65469,7 +63476,7 @@ module.exports = CubicBezierCurve; /***/ }), -/* 344 */ +/* 343 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -65481,10 +63488,10 @@ module.exports = CubicBezierCurve; // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); +var Curve = __webpack_require__(80); var DegToRad = __webpack_require__(35); var GetValue = __webpack_require__(6); -var RadToDeg = __webpack_require__(168); +var RadToDeg = __webpack_require__(171); var Vector2 = __webpack_require__(3); /** @@ -66093,7 +64100,7 @@ module.exports = EllipseCurve; /***/ }), -/* 345 */ +/* 344 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -66105,9 +64112,9 @@ module.exports = EllipseCurve; // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); -var FromPoints = __webpack_require__(171); -var Rectangle = __webpack_require__(13); +var Curve = __webpack_require__(80); +var FromPoints = __webpack_require__(174); +var Rectangle = __webpack_require__(11); var Vector2 = __webpack_require__(3); var tmpVec2 = new Vector2(); @@ -66398,7 +64405,7 @@ module.exports = LineCurve; /***/ }), -/* 346 */ +/* 345 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -66408,8 +64415,8 @@ module.exports = LineCurve; */ var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); -var QuadraticBezierInterpolation = __webpack_require__(321); +var Curve = __webpack_require__(80); +var QuadraticBezierInterpolation = __webpack_require__(322); var Vector2 = __webpack_require__(3); /** @@ -66612,7 +64619,7 @@ module.exports = QuadraticBezier; /***/ }), -/* 347 */ +/* 346 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -66623,9 +64630,9 @@ module.exports = QuadraticBezier; // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) -var CatmullRom = __webpack_require__(166); +var CatmullRom = __webpack_require__(169); var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); +var Curve = __webpack_require__(80); var Vector2 = __webpack_require__(3); /** @@ -66837,7 +64844,7 @@ module.exports = SplineCurve; /***/ }), -/* 348 */ +/* 347 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -66961,7 +64968,7 @@ module.exports = BaseShader; /***/ }), -/* 349 */ +/* 348 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -66970,32 +64977,32 @@ module.exports = BaseShader; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); -Color.ColorToRGBA = __webpack_require__(800); -Color.ComponentToHex = __webpack_require__(350); -Color.GetColor = __webpack_require__(159); -Color.GetColor32 = __webpack_require__(290); -Color.HexStringToColor = __webpack_require__(289); -Color.HSLToColor = __webpack_require__(801); -Color.HSVColorWheel = __webpack_require__(802); -Color.HSVToRGB = __webpack_require__(160); -Color.HueToComponent = __webpack_require__(351); -Color.IntegerToColor = __webpack_require__(292); -Color.IntegerToRGB = __webpack_require__(293); -Color.Interpolate = __webpack_require__(803); -Color.ObjectToColor = __webpack_require__(294); -Color.RandomRGB = __webpack_require__(804); -Color.RGBStringToColor = __webpack_require__(295); -Color.RGBToHSV = __webpack_require__(291); -Color.RGBToString = __webpack_require__(805); -Color.ValueToColor = __webpack_require__(158); +Color.ColorToRGBA = __webpack_require__(802); +Color.ComponentToHex = __webpack_require__(349); +Color.GetColor = __webpack_require__(162); +Color.GetColor32 = __webpack_require__(292); +Color.HexStringToColor = __webpack_require__(291); +Color.HSLToColor = __webpack_require__(803); +Color.HSVColorWheel = __webpack_require__(804); +Color.HSVToRGB = __webpack_require__(163); +Color.HueToComponent = __webpack_require__(350); +Color.IntegerToColor = __webpack_require__(294); +Color.IntegerToRGB = __webpack_require__(295); +Color.Interpolate = __webpack_require__(805); +Color.ObjectToColor = __webpack_require__(296); +Color.RandomRGB = __webpack_require__(806); +Color.RGBStringToColor = __webpack_require__(297); +Color.RGBToHSV = __webpack_require__(293); +Color.RGBToString = __webpack_require__(807); +Color.ValueToColor = __webpack_require__(161); module.exports = Color; /***/ }), -/* 350 */ +/* 349 */ /***/ (function(module, exports) { /** @@ -67025,7 +65032,7 @@ module.exports = ComponentToHex; /***/ }), -/* 351 */ +/* 350 */ /***/ (function(module, exports) { /** @@ -67081,7 +65088,7 @@ module.exports = HueToComponent; /***/ }), -/* 352 */ +/* 351 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -67090,7 +65097,7 @@ module.exports = HueToComponent; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var OS = __webpack_require__(112); +var OS = __webpack_require__(116); /** * @callback ContentLoadedCallback @@ -67144,7 +65151,7 @@ module.exports = DOMContentLoaded; /***/ }), -/* 353 */ +/* 352 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -67153,7 +65160,7 @@ module.exports = DOMContentLoaded; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(172); +var CONST = __webpack_require__(175); /** * Attempts to determine the screen orientation using the Orientation API. @@ -67210,7 +65217,7 @@ module.exports = GetScreenOrientation; /***/ }), -/* 354 */ +/* 353 */ /***/ (function(module, exports) { /** @@ -67296,7 +65303,7 @@ module.exports = { /***/ }), -/* 355 */ +/* 354 */ /***/ (function(module, exports) { /** @@ -67349,7 +65356,7 @@ module.exports = { /***/ }), -/* 356 */ +/* 355 */ /***/ (function(module, exports) { /** @@ -67447,7 +65454,7 @@ module.exports = { /***/ }), -/* 357 */ +/* 356 */ /***/ (function(module, exports) { /** @@ -67521,7 +65528,7 @@ module.exports = { /***/ }), -/* 358 */ +/* 357 */ /***/ (function(module, exports) { /** @@ -67572,7 +65579,7 @@ module.exports = GetTarget; /***/ }), -/* 359 */ +/* 358 */ /***/ (function(module, exports) { /** @@ -67629,7 +65636,7 @@ module.exports = ParseXML; /***/ }), -/* 360 */ +/* 359 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -67639,16 +65646,16 @@ module.exports = ParseXML; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(174); -var EventEmitter = __webpack_require__(11); +var CONST = __webpack_require__(177); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(54); -var GameEvents = __webpack_require__(19); -var Keyboard = __webpack_require__(361); -var Mouse = __webpack_require__(362); -var Pointer = __webpack_require__(363); -var Touch = __webpack_require__(364); -var TransformMatrix = __webpack_require__(30); -var TransformXY = __webpack_require__(328); +var GameEvents = __webpack_require__(18); +var Keyboard = __webpack_require__(360); +var Mouse = __webpack_require__(361); +var Pointer = __webpack_require__(362); +var Touch = __webpack_require__(363); +var TransformMatrix = __webpack_require__(32); +var TransformXY = __webpack_require__(329); /** * @classdesc @@ -68711,7 +66718,7 @@ module.exports = InputManager; /***/ }), -/* 361 */ +/* 360 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -68720,11 +66727,11 @@ module.exports = InputManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayRemove = __webpack_require__(117); +var ArrayRemove = __webpack_require__(121); var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var InputEvents = __webpack_require__(54); -var KeyCodes = __webpack_require__(118); +var KeyCodes = __webpack_require__(122); var NOOP = __webpack_require__(0); /** @@ -69161,7 +67168,7 @@ module.exports = KeyboardManager; /***/ }), -/* 362 */ +/* 361 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -69171,7 +67178,7 @@ module.exports = KeyboardManager; */ var Class = __webpack_require__(0); -var Features = __webpack_require__(164); +var Features = __webpack_require__(167); var InputEvents = __webpack_require__(54); var NOOP = __webpack_require__(0); @@ -69647,7 +67654,7 @@ module.exports = MouseManager; /***/ }), -/* 363 */ +/* 362 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -69656,11 +67663,11 @@ module.exports = MouseManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Angle = __webpack_require__(312); +var Angle = __webpack_require__(314); var Class = __webpack_require__(0); var Distance = __webpack_require__(53); -var FuzzyEqual = __webpack_require__(140); -var SmoothStepInterpolation = __webpack_require__(322); +var FuzzyEqual = __webpack_require__(144); +var SmoothStepInterpolation = __webpack_require__(323); var Vector2 = __webpack_require__(3); /** @@ -70925,7 +68932,7 @@ module.exports = Pointer; /***/ }), -/* 364 */ +/* 363 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71338,7 +69345,7 @@ module.exports = TouchManager; /***/ }), -/* 365 */ +/* 364 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71348,14 +69355,14 @@ module.exports = TouchManager; */ var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); -var EventEmitter = __webpack_require__(11); +var GameEvents = __webpack_require__(18); +var EventEmitter = __webpack_require__(9); var FileTypesManager = __webpack_require__(8); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GameObjectFactory = __webpack_require__(5); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); -var Remove = __webpack_require__(117); +var PluginCache = __webpack_require__(23); +var Remove = __webpack_require__(121); /** * @classdesc @@ -72240,7 +70247,7 @@ module.exports = PluginManager; /***/ }), -/* 366 */ +/* 365 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -72249,18 +70256,18 @@ module.exports = PluginManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(172); +var CONST = __webpack_require__(175); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(90); -var GameEvents = __webpack_require__(19); -var GetInnerHeight = __webpack_require__(858); -var GetTarget = __webpack_require__(358); -var GetScreenOrientation = __webpack_require__(353); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(92); +var GameEvents = __webpack_require__(18); +var GetInnerHeight = __webpack_require__(860); +var GetTarget = __webpack_require__(357); +var GetScreenOrientation = __webpack_require__(352); var NOOP = __webpack_require__(1); -var Rectangle = __webpack_require__(13); -var Size = __webpack_require__(367); -var SnapFloor = __webpack_require__(91); +var Rectangle = __webpack_require__(11); +var Size = __webpack_require__(366); +var SnapFloor = __webpack_require__(93); var Vector2 = __webpack_require__(3); /** @@ -73957,7 +71964,7 @@ module.exports = ScaleManager; /***/ }), -/* 367 */ +/* 366 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -73966,9 +71973,9 @@ module.exports = ScaleManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var SnapFloor = __webpack_require__(91); +var SnapFloor = __webpack_require__(93); var Vector2 = __webpack_require__(3); /** @@ -74735,7 +72742,7 @@ module.exports = Size; /***/ }), -/* 368 */ +/* 367 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -74745,14 +72752,14 @@ module.exports = Size; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(119); -var Events = __webpack_require__(22); -var GameEvents = __webpack_require__(19); +var CONST = __webpack_require__(123); +var Events = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var GetValue = __webpack_require__(6); -var LoaderEvents = __webpack_require__(80); +var LoaderEvents = __webpack_require__(81); var NOOP = __webpack_require__(1); -var Scene = __webpack_require__(369); -var Systems = __webpack_require__(175); +var Scene = __webpack_require__(368); +var Systems = __webpack_require__(178); /** * @classdesc @@ -76375,7 +74382,7 @@ module.exports = SceneManager; /***/ }), -/* 369 */ +/* 368 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -76385,7 +74392,7 @@ module.exports = SceneManager; */ var Class = __webpack_require__(0); -var Systems = __webpack_require__(175); +var Systems = __webpack_require__(178); /** * @classdesc @@ -76605,6 +74612,16 @@ var Scene = new Class({ */ this.physics; + /** + * A scene level Impact Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#impact + * @type {Phaser.Physics.Impact.ImpactPhysics} + * @since 3.0.0 + */ + this.impact; + /** * A scene level Matter Physics Plugin. * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. @@ -76661,7 +74678,7 @@ module.exports = Scene; /***/ }), -/* 370 */ +/* 369 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -76670,10 +74687,10 @@ module.exports = Scene; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(119); +var CONST = __webpack_require__(123); var GetValue = __webpack_require__(6); -var Merge = __webpack_require__(120); -var InjectionMap = __webpack_require__(871); +var Merge = __webpack_require__(107); +var InjectionMap = __webpack_require__(873); /** * @namespace Phaser.Scenes.Settings @@ -76757,7 +74774,7 @@ module.exports = Settings; /***/ }), -/* 371 */ +/* 370 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -76766,18 +74783,18 @@ module.exports = Settings; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); -var CanvasTexture = __webpack_require__(372); +var CanvasPool = __webpack_require__(26); +var CanvasTexture = __webpack_require__(371); var Class = __webpack_require__(0); -var Color = __webpack_require__(32); -var CONST = __webpack_require__(10); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(115); -var GameEvents = __webpack_require__(19); -var GenerateTexture = __webpack_require__(341); +var Color = __webpack_require__(33); +var CONST = __webpack_require__(29); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(119); +var GameEvents = __webpack_require__(18); +var GenerateTexture = __webpack_require__(340); var GetValue = __webpack_require__(6); -var Parser = __webpack_require__(374); -var Texture = __webpack_require__(177); +var Parser = __webpack_require__(373); +var Texture = __webpack_require__(180); /** * @callback EachTextureCallback @@ -77061,8 +75078,8 @@ var TextureManager = new Class({ * * @param {string} key - The unique string-based key of the Texture. * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. - * @param {string} [type='image/png'] - A DOMString indicating the image format. The default format type is image/png. - * @param {number} [encoderOptions=0.92] - A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored. + * @param {string} [type='image/png'] - [description] + * @param {number} [encoderOptions=0.92] - [description] * * @return {string} The base64 encoded data, or an empty string if the texture frame could not be found. */ @@ -77205,44 +75222,14 @@ var TextureManager = new Class({ /** * Creates a new Texture using the given config values. - * * Generated textures consist of a Canvas element to which the texture data is drawn. - * - * Generates a texture based on the given Create configuration object. - * - * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the - * data cells map to a single color. For example, if the texture config looked like this: - * - * ```javascript - * var star = [ - * '.....828.....', - * '....72227....', - * '....82228....', - * '...7222227...', - * '2222222222222', - * '8222222222228', - * '.72222222227.', - * '..787777787..', - * '..877777778..', - * '.78778887787.', - * '.27887.78872.', - * '.787.....787.' - * ]; - * - * this.textures.generate('star', { data: star, pixelWidth: 4 }); - * ``` - * - * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array - * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color - * number 8 in the palette. If a cell contains a period character `.` then it is transparent. - * - * The default palette is Arne16, but you can specify your own using the `palette` property. + * See the Phaser.Create function for the more direct way to create textures. * * @method Phaser.Textures.TextureManager#generate * @since 3.0.0 * * @param {string} key - The unique string-based key of the Texture. - * @param {Phaser.Types.Create.GenerateTextureConfig} config - The configuration object needed to generate the texture. + * @param {object} config - The configuration object needed to generate the texture. * * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. */ @@ -77959,7 +75946,7 @@ module.exports = TextureManager; /***/ }), -/* 372 */ +/* 371 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -77969,11 +75956,11 @@ module.exports = TextureManager; */ var Class = __webpack_require__(0); -var Clamp = __webpack_require__(23); -var Color = __webpack_require__(32); -var CONST = __webpack_require__(10); -var IsSizePowerOfTwo = __webpack_require__(114); -var Texture = __webpack_require__(177); +var Clamp = __webpack_require__(22); +var Color = __webpack_require__(33); +var CONST = __webpack_require__(29); +var IsSizePowerOfTwo = __webpack_require__(118); +var Texture = __webpack_require__(180); /** * @classdesc @@ -78590,7 +76577,7 @@ module.exports = CanvasTexture; /***/ }), -/* 373 */ +/* 372 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -78599,10 +76586,10 @@ module.exports = CanvasTexture; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); -var IsSizePowerOfTwo = __webpack_require__(114); -var ScaleModes = __webpack_require__(229); +var IsSizePowerOfTwo = __webpack_require__(118); +var ScaleModes = __webpack_require__(231); /** * @classdesc @@ -78931,7 +76918,7 @@ module.exports = TextureSource; /***/ }), -/* 374 */ +/* 373 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -78946,20 +76933,20 @@ module.exports = TextureSource; module.exports = { - AtlasXML: __webpack_require__(872), - Canvas: __webpack_require__(873), - Image: __webpack_require__(874), - JSONArray: __webpack_require__(875), - JSONHash: __webpack_require__(876), - SpriteSheet: __webpack_require__(877), - SpriteSheetFromAtlas: __webpack_require__(878), - UnityYAML: __webpack_require__(879) + AtlasXML: __webpack_require__(874), + Canvas: __webpack_require__(875), + Image: __webpack_require__(876), + JSONArray: __webpack_require__(877), + JSONHash: __webpack_require__(878), + SpriteSheet: __webpack_require__(879), + SpriteSheetFromAtlas: __webpack_require__(880), + UnityYAML: __webpack_require__(881) }; /***/ }), -/* 375 */ +/* 374 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -78969,9 +76956,9 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HTML5AudioSoundManager = __webpack_require__(376); -var NoAudioSoundManager = __webpack_require__(378); -var WebAudioSoundManager = __webpack_require__(380); +var HTML5AudioSoundManager = __webpack_require__(375); +var NoAudioSoundManager = __webpack_require__(377); +var WebAudioSoundManager = __webpack_require__(379); /** * Creates a Web Audio, HTML5 Audio or No Audio Sound Manager based on config and device settings. @@ -79011,7 +76998,7 @@ module.exports = SoundManagerCreator; /***/ }), -/* 376 */ +/* 375 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -79021,10 +77008,10 @@ module.exports = SoundManagerCreator; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSoundManager = __webpack_require__(121); +var BaseSoundManager = __webpack_require__(124); var Class = __webpack_require__(0); var Events = __webpack_require__(59); -var HTML5AudioSound = __webpack_require__(377); +var HTML5AudioSound = __webpack_require__(376); /** * HTML5 Audio implementation of the Sound Manager. @@ -79476,7 +77463,7 @@ module.exports = HTML5AudioSoundManager; /***/ }), -/* 377 */ +/* 376 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -79486,7 +77473,7 @@ module.exports = HTML5AudioSoundManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSound = __webpack_require__(122); +var BaseSound = __webpack_require__(125); var Class = __webpack_require__(0); var Events = __webpack_require__(59); @@ -80401,7 +78388,7 @@ module.exports = HTML5AudioSound; /***/ }), -/* 378 */ +/* 377 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -80411,10 +78398,10 @@ module.exports = HTML5AudioSound; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSoundManager = __webpack_require__(121); +var BaseSoundManager = __webpack_require__(124); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var NoAudioSound = __webpack_require__(379); +var EventEmitter = __webpack_require__(9); +var NoAudioSound = __webpack_require__(378); var NOOP = __webpack_require__(1); /** @@ -80519,7 +78506,7 @@ module.exports = NoAudioSoundManager; /***/ }), -/* 379 */ +/* 378 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -80529,10 +78516,10 @@ module.exports = NoAudioSoundManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSound = __webpack_require__(122); +var BaseSound = __webpack_require__(125); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Extend = __webpack_require__(18); +var EventEmitter = __webpack_require__(9); +var Extend = __webpack_require__(17); /** * @classdesc @@ -80646,7 +78633,7 @@ module.exports = NoAudioSound; /***/ }), -/* 380 */ +/* 379 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -80656,11 +78643,11 @@ module.exports = NoAudioSound; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Base64ToArrayBuffer = __webpack_require__(381); -var BaseSoundManager = __webpack_require__(121); +var Base64ToArrayBuffer = __webpack_require__(380); +var BaseSoundManager = __webpack_require__(124); var Class = __webpack_require__(0); var Events = __webpack_require__(59); -var WebAudioSound = __webpack_require__(382); +var WebAudioSound = __webpack_require__(381); /** * @classdesc @@ -81105,7 +79092,7 @@ module.exports = WebAudioSoundManager; /***/ }), -/* 381 */ +/* 380 */ /***/ (function(module, exports) { /** @@ -81180,7 +79167,7 @@ module.exports = Base64ToArrayBuffer; /***/ }), -/* 382 */ +/* 381 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -81190,7 +79177,7 @@ module.exports = Base64ToArrayBuffer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSound = __webpack_require__(122); +var BaseSound = __webpack_require__(125); var Class = __webpack_require__(0); var Events = __webpack_require__(59); @@ -82086,7 +80073,7 @@ module.exports = WebAudioSound; /***/ }), -/* 383 */ +/* 382 */ /***/ (function(module, exports) { /** @@ -82134,7 +80121,7 @@ module.exports = TransposeMatrix; /***/ }), -/* 384 */ +/* 383 */ /***/ (function(module, exports) { /** @@ -82256,7 +80243,7 @@ module.exports = QuickSelect; /***/ }), -/* 385 */ +/* 384 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -82266,7 +80253,7 @@ module.exports = QuickSelect; */ var GetValue = __webpack_require__(6); -var Shuffle = __webpack_require__(110); +var Shuffle = __webpack_require__(114); var BuildChunk = function (a, b, qty) { @@ -82394,7 +80381,7 @@ module.exports = Range; /***/ }), -/* 386 */ +/* 385 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -82483,7 +80470,7 @@ module.exports = BuildGameObjectAnimation; /***/ }), -/* 387 */ +/* 386 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -82492,7 +80479,7 @@ module.exports = BuildGameObjectAnimation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. @@ -82525,7 +80512,7 @@ module.exports = Union; /***/ }), -/* 388 */ +/* 387 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -82536,12 +80523,12 @@ module.exports = Union; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var DOMElementRender = __webpack_require__(948); +var DOMElementRender = __webpack_require__(950); var GameObject = __webpack_require__(14); var IsPlainObject = __webpack_require__(7); -var RemoveFromDOM = __webpack_require__(173); -var SCENE_EVENTS = __webpack_require__(22); -var Vector4 = __webpack_require__(329); +var RemoveFromDOM = __webpack_require__(176); +var SCENE_EVENTS = __webpack_require__(19); +var Vector4 = __webpack_require__(330); /** * @classdesc @@ -83499,7 +81486,7 @@ module.exports = DOMElement; /***/ }), -/* 389 */ +/* 388 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83508,7 +81495,7 @@ module.exports = DOMElement; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CSSBlendModes = __webpack_require__(949); +var CSSBlendModes = __webpack_require__(951); var GameObject = __webpack_require__(14); /** @@ -83621,7 +81608,7 @@ module.exports = DOMElementCSSRenderer; /***/ }), -/* 390 */ +/* 389 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83633,7 +81620,7 @@ module.exports = DOMElementCSSRenderer; var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var ExternRender = __webpack_require__(953); +var ExternRender = __webpack_require__(955); /** * @classdesc @@ -83717,7 +81704,7 @@ module.exports = Extern; /***/ }), -/* 391 */ +/* 390 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83726,9 +81713,9 @@ module.exports = Extern; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CircumferencePoint = __webpack_require__(188); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var CircumferencePoint = __webpack_require__(191); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); var Point = __webpack_require__(4); /** @@ -83760,7 +81747,7 @@ module.exports = GetPoint; /***/ }), -/* 392 */ +/* 391 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83769,10 +81756,10 @@ module.exports = GetPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circumference = __webpack_require__(393); -var CircumferencePoint = __webpack_require__(188); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var Circumference = __webpack_require__(392); +var CircumferencePoint = __webpack_require__(191); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); /** * Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse, @@ -83814,7 +81801,7 @@ module.exports = GetPoints; /***/ }), -/* 393 */ +/* 392 */ /***/ (function(module, exports) { /** @@ -83846,7 +81833,7 @@ module.exports = Circumference; /***/ }), -/* 394 */ +/* 393 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83855,8 +81842,8 @@ module.exports = Circumference; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Commands = __webpack_require__(187); -var SetTransform = __webpack_require__(29); +var Commands = __webpack_require__(190); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -84096,7 +82083,7 @@ module.exports = GraphicsCanvasRenderer; /***/ }), -/* 395 */ +/* 394 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -84315,7 +82302,7 @@ module.exports = GravityWell; /***/ }), -/* 396 */ +/* 395 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -84884,7 +82871,7 @@ module.exports = Particle; /***/ }), -/* 397 */ +/* 396 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -84896,17 +82883,17 @@ module.exports = Particle; var BlendModes = __webpack_require__(52); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var DeathZone = __webpack_require__(398); -var EdgeZone = __webpack_require__(399); -var EmitterOp = __webpack_require__(965); +var DeathZone = __webpack_require__(397); +var EdgeZone = __webpack_require__(398); +var EmitterOp = __webpack_require__(967); var GetFastValue = __webpack_require__(2); -var GetRandom = __webpack_require__(180); -var HasAny = __webpack_require__(400); -var HasValue = __webpack_require__(104); -var Particle = __webpack_require__(396); -var RandomZone = __webpack_require__(401); -var Rectangle = __webpack_require__(13); -var StableSort = __webpack_require__(125); +var GetRandom = __webpack_require__(183); +var HasAny = __webpack_require__(399); +var HasValue = __webpack_require__(99); +var Particle = __webpack_require__(395); +var RandomZone = __webpack_require__(400); +var Rectangle = __webpack_require__(11); +var StableSort = __webpack_require__(128); var Vector2 = __webpack_require__(3); var Wrap = __webpack_require__(58); @@ -85659,7 +83646,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ fromJSON: function (config) { @@ -85816,7 +83803,7 @@ var ParticleEmitter = new Class({ * @param {number} [offsetY=0] - Vertical offset of the particle origin from the Game Object. * @param {boolean} [trackVisible=false] - Whether the emitter's visible state will track the target's visible state. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ startFollow: function (target, offsetX, offsetY, trackVisible) { @@ -85837,7 +83824,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#stopFollow * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ stopFollow: function () { @@ -85898,7 +83885,7 @@ var ParticleEmitter = new Class({ * @param {boolean} [pickRandom=true] - Whether frames should be assigned at random from `frames`. * @param {integer} [quantity=1] - The number of consecutive particles that will receive each frame. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setFrame: function (frames, pickRandom, quantity) { @@ -85953,7 +83940,7 @@ var ParticleEmitter = new Class({ * * @param {boolean} [value=true] - Radial mode (true) or point mode (true). * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setRadial: function (value) { @@ -85974,7 +83961,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} x - The x-coordinate of the particle origin. * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} y - The y-coordinate of the particle origin. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setPosition: function (x, y) { @@ -85997,7 +83984,7 @@ var ParticleEmitter = new Class({ * @param {number} width - The width of the boundary. * @param {number} height - The height of the boundary. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setBounds: function (x, y, width, height) { @@ -86032,7 +84019,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setSpeedX: function (value) { @@ -86053,7 +84040,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setSpeedY: function (value) { @@ -86077,7 +84064,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setSpeed: function (value) { @@ -86098,7 +84085,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setScaleX: function (value) { @@ -86115,7 +84102,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setScaleY: function (value) { @@ -86132,7 +84119,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setScale: function (value) { @@ -86150,7 +84137,7 @@ var ParticleEmitter = new Class({ * * @param {number} value - Acceleration due to gravity, in pixels per second squared. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setGravityX: function (value) { @@ -86167,7 +84154,7 @@ var ParticleEmitter = new Class({ * * @param {number} value - Acceleration due to gravity, in pixels per second squared. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setGravityY: function (value) { @@ -86185,7 +84172,7 @@ var ParticleEmitter = new Class({ * @param {number} x - Horizontal acceleration due to gravity, in pixels per second squared. * @param {number} y - Vertical acceleration due to gravity, in pixels per second squared. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setGravity: function (x, y) { @@ -86203,7 +84190,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 (transparent) and 1 (opaque). * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setAlpha: function (value) { @@ -86220,7 +84207,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 and 0xffffff. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setTint: function (value) { @@ -86237,7 +84224,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setEmitterAngle: function (value) { @@ -86254,7 +84241,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setAngle: function (value) { @@ -86271,7 +84258,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The particle lifespan, in ms. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setLifespan: function (value) { @@ -86288,7 +84275,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} quantity - The number of particles to release at each flow cycle or explosion. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setQuantity: function (quantity) { @@ -86307,7 +84294,7 @@ var ParticleEmitter = new Class({ * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [quantity] - The number of particles to release at each flow cycle or explosion. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setFrequency: function (frequency, quantity) { @@ -86335,7 +84322,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current emit zone. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setEmitZone: function (zoneConfig) { @@ -86384,7 +84371,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current death zone. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setDeathZone: function (zoneConfig) { @@ -86420,7 +84407,7 @@ var ParticleEmitter = new Class({ * * @param {integer} particleCount - The number of particles to create. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ reserve: function (particleCount) { @@ -86495,7 +84482,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. * @param {*} [context] - The calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ onParticleEmit: function (callback, context) { @@ -86527,7 +84514,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleDeathCallback} callback - The function. * @param {*} [context] - The function's calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ onParticleDeath: function (callback, context) { @@ -86556,7 +84543,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#killAll * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ killAll: function () { @@ -86580,7 +84567,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. * @param {*} context - The function's calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ forEachAlive: function (callback, context) { @@ -86605,7 +84592,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. * @param {*} context - The function's calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ forEachDead: function (callback, context) { @@ -86632,7 +84619,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#start * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ start: function () { @@ -86649,7 +84636,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#stop * @since 3.11.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ stop: function () { @@ -86664,7 +84651,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#pause * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ pause: function () { @@ -86679,7 +84666,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#resume * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ resume: function () { @@ -86694,7 +84681,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#remove * @since 3.22.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ remove: function () { @@ -86709,7 +84696,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSort * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ depthSort: function () { @@ -86729,7 +84716,7 @@ var ParticleEmitter = new Class({ * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms. * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [count=1] - The number of particles to emit at each flow cycle. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ flow: function (frequency, count) { @@ -86955,7 +84942,7 @@ module.exports = ParticleEmitter; /***/ }), -/* 398 */ +/* 397 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87033,7 +85020,7 @@ module.exports = DeathZone; /***/ }), -/* 399 */ +/* 398 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87169,7 +85156,7 @@ var EdgeZone = new Class({ * @method Phaser.GameObjects.Particles.Zones.EdgeZone#updateSource * @since 3.0.0 * - * @return {this} This Edge Zone. + * @return {Phaser.GameObjects.Particles.Zones.EdgeZone} This Edge Zone. */ updateSource: function () { @@ -87208,7 +85195,7 @@ var EdgeZone = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. * - * @return {this} This Edge Zone. + * @return {Phaser.GameObjects.Particles.Zones.EdgeZone} This Edge Zone. */ changeSource: function (source) { @@ -87277,7 +85264,7 @@ module.exports = EdgeZone; /***/ }), -/* 400 */ +/* 399 */ /***/ (function(module, exports) { /** @@ -87314,7 +85301,7 @@ module.exports = HasAny; /***/ }), -/* 401 */ +/* 400 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87387,7 +85374,7 @@ module.exports = RandomZone; /***/ }), -/* 402 */ +/* 401 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87398,7 +85385,7 @@ module.exports = RandomZone; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Sprite = __webpack_require__(73); +var Sprite = __webpack_require__(69); /** * @classdesc @@ -87469,7 +85456,7 @@ module.exports = PathFollower; /***/ }), -/* 403 */ +/* 402 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87478,13 +85465,13 @@ module.exports = PathFollower; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcRender = __webpack_require__(991); +var ArcRender = __webpack_require__(990); var Class = __webpack_require__(0); var DegToRad = __webpack_require__(35); -var Earcut = __webpack_require__(64); -var GeomCircle = __webpack_require__(63); -var MATH_CONST = __webpack_require__(16); -var Shape = __webpack_require__(31); +var Earcut = __webpack_require__(66); +var GeomCircle = __webpack_require__(65); +var MATH_CONST = __webpack_require__(13); +var Shape = __webpack_require__(30); /** * @classdesc @@ -87878,7 +85865,7 @@ module.exports = Arc; /***/ }), -/* 404 */ +/* 403 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87888,10 +85875,10 @@ module.exports = Arc; */ var Class = __webpack_require__(0); -var CurveRender = __webpack_require__(994); -var Earcut = __webpack_require__(64); -var Rectangle = __webpack_require__(13); -var Shape = __webpack_require__(31); +var CurveRender = __webpack_require__(993); +var Earcut = __webpack_require__(66); +var Rectangle = __webpack_require__(11); +var Shape = __webpack_require__(30); /** * @classdesc @@ -88060,7 +86047,7 @@ module.exports = Curve; /***/ }), -/* 405 */ +/* 404 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88070,10 +86057,10 @@ module.exports = Curve; */ var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); -var EllipseRender = __webpack_require__(997); -var GeomEllipse = __webpack_require__(93); -var Shape = __webpack_require__(31); +var Earcut = __webpack_require__(66); +var EllipseRender = __webpack_require__(996); +var GeomEllipse = __webpack_require__(95); +var Shape = __webpack_require__(30); /** * @classdesc @@ -88247,7 +86234,7 @@ module.exports = Ellipse; /***/ }), -/* 406 */ +/* 405 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88257,8 +86244,8 @@ module.exports = Ellipse; */ var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); -var GridRender = __webpack_require__(1000); +var Shape = __webpack_require__(30); +var GridRender = __webpack_require__(999); /** * @classdesc @@ -88529,7 +86516,7 @@ module.exports = Grid; /***/ }), -/* 407 */ +/* 406 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88538,9 +86525,9 @@ module.exports = Grid; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var IsoBoxRender = __webpack_require__(1003); +var IsoBoxRender = __webpack_require__(1002); var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); +var Shape = __webpack_require__(30); /** * @classdesc @@ -88744,7 +86731,7 @@ module.exports = IsoBox; /***/ }), -/* 408 */ +/* 407 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88754,8 +86741,8 @@ module.exports = IsoBox; */ var Class = __webpack_require__(0); -var IsoTriangleRender = __webpack_require__(1006); -var Shape = __webpack_require__(31); +var IsoTriangleRender = __webpack_require__(1005); +var Shape = __webpack_require__(30); /** * @classdesc @@ -88990,7 +86977,7 @@ module.exports = IsoTriangle; /***/ }), -/* 409 */ +/* 408 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89000,9 +86987,9 @@ module.exports = IsoTriangle; */ var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); +var Shape = __webpack_require__(30); var GeomLine = __webpack_require__(56); -var LineRender = __webpack_require__(1009); +var LineRender = __webpack_require__(1008); /** * @classdesc @@ -89157,7 +87144,7 @@ module.exports = Line; /***/ }), -/* 410 */ +/* 409 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89166,13 +87153,13 @@ module.exports = Line; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PolygonRender = __webpack_require__(1012); +var PolygonRender = __webpack_require__(1011); var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); -var GetAABB = __webpack_require__(411); -var GeomPolygon = __webpack_require__(196); -var Shape = __webpack_require__(31); -var Smooth = __webpack_require__(414); +var Earcut = __webpack_require__(66); +var GetAABB = __webpack_require__(410); +var GeomPolygon = __webpack_require__(198); +var Shape = __webpack_require__(30); +var Smooth = __webpack_require__(413); /** * @classdesc @@ -89296,7 +87283,7 @@ module.exports = Polygon; /***/ }), -/* 411 */ +/* 410 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89305,7 +87292,7 @@ module.exports = Polygon; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Calculates the bounding AABB rectangle of a polygon. @@ -89352,7 +87339,7 @@ module.exports = GetAABB; /***/ }), -/* 412 */ +/* 411 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89363,7 +87350,7 @@ module.exports = GetAABB; var Length = __webpack_require__(57); var Line = __webpack_require__(56); -var Perimeter = __webpack_require__(413); +var Perimeter = __webpack_require__(412); /** * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, @@ -89429,7 +87416,7 @@ module.exports = GetPoints; /***/ }), -/* 413 */ +/* 412 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89477,7 +87464,7 @@ module.exports = Perimeter; /***/ }), -/* 414 */ +/* 413 */ /***/ (function(module, exports) { /** @@ -89553,7 +87540,7 @@ module.exports = Smooth; /***/ }), -/* 415 */ +/* 414 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89563,9 +87550,9 @@ module.exports = Smooth; */ var Class = __webpack_require__(0); -var GeomRectangle = __webpack_require__(13); -var Shape = __webpack_require__(31); -var RectangleRender = __webpack_require__(1015); +var GeomRectangle = __webpack_require__(11); +var Shape = __webpack_require__(30); +var RectangleRender = __webpack_require__(1014); /** * @classdesc @@ -89665,7 +87652,7 @@ module.exports = Rectangle; /***/ }), -/* 416 */ +/* 415 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89674,10 +87661,10 @@ module.exports = Rectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var StarRender = __webpack_require__(1018); +var StarRender = __webpack_require__(1017); var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); -var Shape = __webpack_require__(31); +var Earcut = __webpack_require__(66); +var Shape = __webpack_require__(30); /** * @classdesc @@ -89953,7 +87940,7 @@ module.exports = Star; /***/ }), -/* 417 */ +/* 416 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89963,9 +87950,9 @@ module.exports = Star; */ var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); -var GeomTriangle = __webpack_require__(69); -var TriangleRender = __webpack_require__(1021); +var Shape = __webpack_require__(30); +var GeomTriangle = __webpack_require__(71); +var TriangleRender = __webpack_require__(1020); /** * @classdesc @@ -90096,7 +88083,7 @@ module.exports = Triangle; /***/ }), -/* 418 */ +/* 417 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -90183,7 +88170,7 @@ module.exports = GetPoint; /***/ }), -/* 419 */ +/* 418 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -90276,7 +88263,7 @@ module.exports = GetPoints; /***/ }), -/* 420 */ +/* 419 */ /***/ (function(module, exports) { /** @@ -90359,7 +88346,7 @@ module.exports = SetValue; /***/ }), -/* 421 */ +/* 420 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -90369,7 +88356,7 @@ module.exports = SetValue; */ var Class = __webpack_require__(0); -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * @classdesc @@ -90499,7 +88486,7 @@ var Light = new Class({ * @param {number} b - The blue color. A value between 0 and 1. * @param {number} intensity - The intensity of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ set: function (x, y, radius, r, g, b, intensity) { @@ -90529,7 +88516,7 @@ var Light = new Class({ * @param {number} x - The horizontal scroll factor of the light. * @param {number} y - The vertical scroll factor of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setScrollFactor: function (x, y) { @@ -90550,7 +88537,7 @@ var Light = new Class({ * * @param {number} rgb - The integer RGB color of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setColor: function (rgb) { @@ -90571,7 +88558,7 @@ var Light = new Class({ * * @param {number} intensity - The intensity of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setIntensity: function (intensity) { @@ -90589,7 +88576,7 @@ var Light = new Class({ * @param {number} x - The horizontal position of the light. * @param {number} y - The vertical position of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setPosition: function (x, y) { @@ -90607,7 +88594,7 @@ var Light = new Class({ * * @param {number} radius - The radius of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setRadius: function (radius) { @@ -90622,7 +88609,7 @@ module.exports = Light; /***/ }), -/* 422 */ +/* 421 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -90632,8 +88619,8 @@ module.exports = Light; */ var Class = __webpack_require__(0); -var Light = __webpack_require__(421); -var Utils = __webpack_require__(9); +var Light = __webpack_require__(420); +var Utils = __webpack_require__(10); /** * @callback LightForEach @@ -90985,7 +88972,7 @@ module.exports = LightsManager; /***/ }), -/* 423 */ +/* 422 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -90995,7 +88982,7 @@ module.exports = LightsManager; */ var CONST = __webpack_require__(46); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Geom @@ -91003,14 +88990,14 @@ var Extend = __webpack_require__(18); var Geom = { - Circle: __webpack_require__(1081), - Ellipse: __webpack_require__(1091), - Intersects: __webpack_require__(424), - Line: __webpack_require__(1110), - Point: __webpack_require__(1132), - Polygon: __webpack_require__(1146), - Rectangle: __webpack_require__(437), - Triangle: __webpack_require__(1176) + Circle: __webpack_require__(1078), + Ellipse: __webpack_require__(1088), + Intersects: __webpack_require__(423), + Line: __webpack_require__(1107), + Point: __webpack_require__(1128), + Polygon: __webpack_require__(1142), + Rectangle: __webpack_require__(436), + Triangle: __webpack_require__(1172) }; @@ -91021,7 +89008,7 @@ module.exports = Geom; /***/ }), -/* 424 */ +/* 423 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91036,35 +89023,35 @@ module.exports = Geom; module.exports = { - CircleToCircle: __webpack_require__(200), - CircleToRectangle: __webpack_require__(201), - GetCircleToCircle: __webpack_require__(1101), - GetCircleToRectangle: __webpack_require__(1102), - GetLineToCircle: __webpack_require__(202), - GetLineToRectangle: __webpack_require__(204), - GetRectangleIntersection: __webpack_require__(1103), - GetRectangleToRectangle: __webpack_require__(1104), - GetRectangleToTriangle: __webpack_require__(1105), - GetTriangleToCircle: __webpack_require__(1106), - GetTriangleToLine: __webpack_require__(429), - GetTriangleToTriangle: __webpack_require__(1107), - LineToCircle: __webpack_require__(203), - LineToLine: __webpack_require__(82), - LineToRectangle: __webpack_require__(425), - PointToLine: __webpack_require__(433), - PointToLineSegment: __webpack_require__(1108), - RectangleToRectangle: __webpack_require__(129), - RectangleToTriangle: __webpack_require__(426), - RectangleToValues: __webpack_require__(1109), - TriangleToCircle: __webpack_require__(428), - TriangleToLine: __webpack_require__(430), - TriangleToTriangle: __webpack_require__(431) + CircleToCircle: __webpack_require__(202), + CircleToRectangle: __webpack_require__(203), + GetCircleToCircle: __webpack_require__(1098), + GetCircleToRectangle: __webpack_require__(1099), + GetLineToCircle: __webpack_require__(204), + GetLineToRectangle: __webpack_require__(206), + GetRectangleIntersection: __webpack_require__(1100), + GetRectangleToRectangle: __webpack_require__(1101), + GetRectangleToTriangle: __webpack_require__(1102), + GetTriangleToCircle: __webpack_require__(1103), + GetTriangleToLine: __webpack_require__(428), + GetTriangleToTriangle: __webpack_require__(1104), + LineToCircle: __webpack_require__(205), + LineToLine: __webpack_require__(84), + LineToRectangle: __webpack_require__(424), + PointToLine: __webpack_require__(432), + PointToLineSegment: __webpack_require__(1105), + RectangleToRectangle: __webpack_require__(131), + RectangleToTriangle: __webpack_require__(425), + RectangleToValues: __webpack_require__(1106), + TriangleToCircle: __webpack_require__(427), + TriangleToLine: __webpack_require__(429), + TriangleToTriangle: __webpack_require__(430) }; /***/ }), -/* 425 */ +/* 424 */ /***/ (function(module, exports) { /** @@ -91165,7 +89152,7 @@ module.exports = LineToRectangle; /***/ }), -/* 426 */ +/* 425 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91174,10 +89161,10 @@ module.exports = LineToRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var LineToLine = __webpack_require__(82); +var LineToLine = __webpack_require__(84); var Contains = __webpack_require__(47); -var ContainsArray = __webpack_require__(205); -var Decompose = __webpack_require__(427); +var ContainsArray = __webpack_require__(207); +var Decompose = __webpack_require__(426); /** * Checks for intersection between Rectangle shape and Triangle shape. @@ -91258,7 +89245,7 @@ module.exports = RectangleToTriangle; /***/ }), -/* 427 */ +/* 426 */ /***/ (function(module, exports) { /** @@ -91295,7 +89282,7 @@ module.exports = Decompose; /***/ }), -/* 428 */ +/* 427 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91304,8 +89291,8 @@ module.exports = Decompose; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var LineToCircle = __webpack_require__(203); -var Contains = __webpack_require__(81); +var LineToCircle = __webpack_require__(205); +var Contains = __webpack_require__(83); /** * Checks if a Triangle and a Circle intersect. @@ -91360,7 +89347,7 @@ module.exports = TriangleToCircle; /***/ }), -/* 429 */ +/* 428 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91371,8 +89358,8 @@ module.exports = TriangleToCircle; */ var Point = __webpack_require__(4); -var TriangleToLine = __webpack_require__(430); -var LineToLine = __webpack_require__(82); +var TriangleToLine = __webpack_require__(429); +var LineToLine = __webpack_require__(84); /** * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. @@ -91419,7 +89406,7 @@ module.exports = GetTriangleToLine; /***/ }), -/* 430 */ +/* 429 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91428,8 +89415,8 @@ module.exports = GetTriangleToLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(81); -var LineToLine = __webpack_require__(82); +var Contains = __webpack_require__(83); +var LineToLine = __webpack_require__(84); /** * Checks if a Triangle and a Line intersect. @@ -91475,7 +89462,7 @@ module.exports = TriangleToLine; /***/ }), -/* 431 */ +/* 430 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91484,9 +89471,9 @@ module.exports = TriangleToLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ContainsArray = __webpack_require__(205); -var Decompose = __webpack_require__(432); -var LineToLine = __webpack_require__(82); +var ContainsArray = __webpack_require__(207); +var Decompose = __webpack_require__(431); +var LineToLine = __webpack_require__(84); /** * Checks if two Triangles intersect. @@ -91565,7 +89552,7 @@ module.exports = TriangleToTriangle; /***/ }), -/* 432 */ +/* 431 */ /***/ (function(module, exports) { /** @@ -91600,7 +89587,7 @@ module.exports = Decompose; /***/ }), -/* 433 */ +/* 432 */ /***/ (function(module, exports) { /** @@ -91670,7 +89657,7 @@ module.exports = PointToLine; /***/ }), -/* 434 */ +/* 433 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91679,9 +89666,9 @@ module.exports = PointToLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); var Wrap = __webpack_require__(58); -var Angle = __webpack_require__(83); +var Angle = __webpack_require__(85); /** * Get the angle of the normal of the given line in radians. @@ -91704,7 +89691,7 @@ module.exports = NormalAngle; /***/ }), -/* 435 */ +/* 434 */ /***/ (function(module, exports) { /** @@ -91732,7 +89719,7 @@ module.exports = GetMagnitude; /***/ }), -/* 436 */ +/* 435 */ /***/ (function(module, exports) { /** @@ -91760,7 +89747,7 @@ module.exports = GetMagnitudeSq; /***/ }), -/* 437 */ +/* 436 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91769,51 +89756,51 @@ module.exports = GetMagnitudeSq; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); -Rectangle.Area = __webpack_require__(1151); -Rectangle.Ceil = __webpack_require__(1152); -Rectangle.CeilAll = __webpack_require__(1153); -Rectangle.CenterOn = __webpack_require__(162); -Rectangle.Clone = __webpack_require__(1154); +Rectangle.Area = __webpack_require__(1147); +Rectangle.Ceil = __webpack_require__(1148); +Rectangle.CeilAll = __webpack_require__(1149); +Rectangle.CenterOn = __webpack_require__(165); +Rectangle.Clone = __webpack_require__(1150); Rectangle.Contains = __webpack_require__(47); -Rectangle.ContainsPoint = __webpack_require__(1155); -Rectangle.ContainsRect = __webpack_require__(438); -Rectangle.CopyFrom = __webpack_require__(1156); -Rectangle.Decompose = __webpack_require__(427); -Rectangle.Equals = __webpack_require__(1157); -Rectangle.FitInside = __webpack_require__(1158); -Rectangle.FitOutside = __webpack_require__(1159); -Rectangle.Floor = __webpack_require__(1160); -Rectangle.FloorAll = __webpack_require__(1161); -Rectangle.FromPoints = __webpack_require__(171); -Rectangle.GetAspectRatio = __webpack_require__(207); -Rectangle.GetCenter = __webpack_require__(1162); -Rectangle.GetPoint = __webpack_require__(146); -Rectangle.GetPoints = __webpack_require__(269); -Rectangle.GetSize = __webpack_require__(1163); -Rectangle.Inflate = __webpack_require__(1164); -Rectangle.Intersection = __webpack_require__(1165); -Rectangle.MarchingAnts = __webpack_require__(280); -Rectangle.MergePoints = __webpack_require__(1166); -Rectangle.MergeRect = __webpack_require__(1167); -Rectangle.MergeXY = __webpack_require__(1168); -Rectangle.Offset = __webpack_require__(1169); -Rectangle.OffsetPoint = __webpack_require__(1170); -Rectangle.Overlaps = __webpack_require__(1171); -Rectangle.Perimeter = __webpack_require__(108); -Rectangle.PerimeterPoint = __webpack_require__(1172); -Rectangle.Random = __webpack_require__(149); -Rectangle.RandomOutside = __webpack_require__(1173); -Rectangle.SameDimensions = __webpack_require__(1174); -Rectangle.Scale = __webpack_require__(1175); -Rectangle.Union = __webpack_require__(387); +Rectangle.ContainsPoint = __webpack_require__(1151); +Rectangle.ContainsRect = __webpack_require__(437); +Rectangle.CopyFrom = __webpack_require__(1152); +Rectangle.Decompose = __webpack_require__(426); +Rectangle.Equals = __webpack_require__(1153); +Rectangle.FitInside = __webpack_require__(1154); +Rectangle.FitOutside = __webpack_require__(1155); +Rectangle.Floor = __webpack_require__(1156); +Rectangle.FloorAll = __webpack_require__(1157); +Rectangle.FromPoints = __webpack_require__(174); +Rectangle.GetAspectRatio = __webpack_require__(209); +Rectangle.GetCenter = __webpack_require__(1158); +Rectangle.GetPoint = __webpack_require__(149); +Rectangle.GetPoints = __webpack_require__(271); +Rectangle.GetSize = __webpack_require__(1159); +Rectangle.Inflate = __webpack_require__(1160); +Rectangle.Intersection = __webpack_require__(1161); +Rectangle.MarchingAnts = __webpack_require__(282); +Rectangle.MergePoints = __webpack_require__(1162); +Rectangle.MergeRect = __webpack_require__(1163); +Rectangle.MergeXY = __webpack_require__(1164); +Rectangle.Offset = __webpack_require__(1165); +Rectangle.OffsetPoint = __webpack_require__(1166); +Rectangle.Overlaps = __webpack_require__(1167); +Rectangle.Perimeter = __webpack_require__(112); +Rectangle.PerimeterPoint = __webpack_require__(1168); +Rectangle.Random = __webpack_require__(152); +Rectangle.RandomOutside = __webpack_require__(1169); +Rectangle.SameDimensions = __webpack_require__(1170); +Rectangle.Scale = __webpack_require__(1171); +Rectangle.Union = __webpack_require__(386); module.exports = Rectangle; /***/ }), -/* 438 */ +/* 437 */ /***/ (function(module, exports) { /** @@ -91853,7 +89840,7 @@ module.exports = ContainsRect; /***/ }), -/* 439 */ +/* 438 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91897,7 +89884,7 @@ module.exports = Centroid; /***/ }), -/* 440 */ +/* 439 */ /***/ (function(module, exports) { /** @@ -91938,7 +89925,7 @@ module.exports = Offset; /***/ }), -/* 441 */ +/* 440 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92003,7 +89990,7 @@ module.exports = InCenter; /***/ }), -/* 442 */ +/* 441 */ /***/ (function(module, exports) { /** @@ -92074,7 +90061,7 @@ module.exports = CreateInteractiveObject; /***/ }), -/* 443 */ +/* 442 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92199,7 +90186,7 @@ module.exports = Axis; /***/ }), -/* 444 */ +/* 443 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92209,7 +90196,7 @@ module.exports = Axis; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(209); +var Events = __webpack_require__(211); /** * @classdesc @@ -92345,7 +90332,7 @@ module.exports = Button; /***/ }), -/* 445 */ +/* 444 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92354,10 +90341,10 @@ module.exports = Button; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Axis = __webpack_require__(443); -var Button = __webpack_require__(444); +var Axis = __webpack_require__(442); +var Button = __webpack_require__(443); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var Vector2 = __webpack_require__(3); /** @@ -93103,7 +91090,7 @@ module.exports = Gamepad; /***/ }), -/* 446 */ +/* 445 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93113,8 +91100,8 @@ module.exports = Gamepad; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(131); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(133); /** * @classdesc @@ -93505,7 +91492,7 @@ module.exports = Key; /***/ }), -/* 447 */ +/* 446 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93515,10 +91502,10 @@ module.exports = Key; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(131); +var Events = __webpack_require__(133); var GetFastValue = __webpack_require__(2); -var ProcessKeyCombo = __webpack_require__(1215); -var ResetKeyCombo = __webpack_require__(1217); +var ProcessKeyCombo = __webpack_require__(1211); +var ResetKeyCombo = __webpack_require__(1213); /** * @classdesc @@ -93798,7 +91785,7 @@ module.exports = KeyCombo; /***/ }), -/* 448 */ +/* 447 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93807,7 +91794,7 @@ module.exports = KeyCombo; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MergeXHRSettings = __webpack_require__(210); +var MergeXHRSettings = __webpack_require__(212); /** * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings @@ -93848,11 +91835,6 @@ var XHRLoader = function (file, globalXHRSettings) xhr.overrideMimeType(config.overrideMimeType); } - if (config.withCredentials) - { - xhr.withCredentials = true; - } - // 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.) xhr.onload = file.onLoad.bind(file, xhr); @@ -93871,7 +91853,7 @@ module.exports = XHRLoader; /***/ }), -/* 449 */ +/* 448 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93881,11 +91863,11 @@ module.exports = XHRLoader; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); +var CONST = __webpack_require__(29); var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var HTML5AudioFile = __webpack_require__(450); +var HTML5AudioFile = __webpack_require__(449); var IsPlainObject = __webpack_require__(7); /** @@ -94096,7 +92078,7 @@ AudioFile.getAudioURL = function (game, urls) * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('audio', function (key, urls, config, xhrSettings) { @@ -94142,7 +92124,7 @@ module.exports = AudioFile; /***/ }), -/* 450 */ +/* 449 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94152,10 +92134,10 @@ module.exports = AudioFile; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(80); +var Events = __webpack_require__(81); var File = __webpack_require__(21); var GetFastValue = __webpack_require__(2); -var GetURL = __webpack_require__(132); +var GetURL = __webpack_require__(134); var IsPlainObject = __webpack_require__(7); /** @@ -94340,7 +92322,7 @@ module.exports = HTML5AudioFile; /***/ }), -/* 451 */ +/* 450 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94487,7 +92469,7 @@ var ScriptFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('script', function (key, url, xhrSettings) { @@ -94511,7 +92493,7 @@ module.exports = ScriptFile; /***/ }), -/* 452 */ +/* 451 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94662,7 +92644,7 @@ var TextFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('text', function (key, url, xhrSettings) { @@ -94686,7 +92668,7 @@ module.exports = TextFile; /***/ }), -/* 453 */ +/* 452 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94695,12 +92677,12 @@ module.exports = TextFile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcadeImage = __webpack_require__(454); -var ArcadeSprite = __webpack_require__(134); +var ArcadeImage = __webpack_require__(453); +var ArcadeSprite = __webpack_require__(136); var Class = __webpack_require__(0); var CONST = __webpack_require__(50); -var PhysicsGroup = __webpack_require__(455); -var StaticPhysicsGroup = __webpack_require__(456); +var PhysicsGroup = __webpack_require__(454); +var StaticPhysicsGroup = __webpack_require__(455); /** * @classdesc @@ -94957,7 +92939,7 @@ module.exports = Factory; /***/ }), -/* 454 */ +/* 453 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94967,8 +92949,8 @@ module.exports = Factory; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(212); -var Image = __webpack_require__(103); +var Components = __webpack_require__(214); +var Image = __webpack_require__(98); /** * @classdesc @@ -95057,7 +93039,7 @@ module.exports = ArcadeImage; /***/ }), -/* 455 */ +/* 454 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95066,11 +93048,11 @@ module.exports = ArcadeImage; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcadeSprite = __webpack_require__(134); +var ArcadeSprite = __webpack_require__(136); var Class = __webpack_require__(0); var CONST = __webpack_require__(50); var GetFastValue = __webpack_require__(2); -var Group = __webpack_require__(95); +var Group = __webpack_require__(97); var IsPlainObject = __webpack_require__(7); /** @@ -95342,7 +93324,7 @@ module.exports = PhysicsGroup; /***/ }), -/* 456 */ +/* 455 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95351,11 +93333,11 @@ module.exports = PhysicsGroup; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcadeSprite = __webpack_require__(134); +var ArcadeSprite = __webpack_require__(136); var Class = __webpack_require__(0); var CONST = __webpack_require__(50); var GetFastValue = __webpack_require__(2); -var Group = __webpack_require__(95); +var Group = __webpack_require__(97); var IsPlainObject = __webpack_require__(7); /** @@ -95533,7 +93515,7 @@ module.exports = StaticPhysicsGroup; /***/ }), -/* 457 */ +/* 456 */ /***/ (function(module, exports) { /** @@ -95618,7 +93600,7 @@ module.exports = OverlapRect; /***/ }), -/* 458 */ +/* 457 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95627,31 +93609,31 @@ module.exports = OverlapRect; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Body = __webpack_require__(459); -var Clamp = __webpack_require__(23); +var Body = __webpack_require__(458); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var Collider = __webpack_require__(460); +var Collider = __webpack_require__(459); var CONST = __webpack_require__(50); var DistanceBetween = __webpack_require__(53); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(213); -var FuzzyEqual = __webpack_require__(140); -var FuzzyGreaterThan = __webpack_require__(316); -var FuzzyLessThan = __webpack_require__(317); -var GetOverlapX = __webpack_require__(461); -var GetOverlapY = __webpack_require__(462); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(215); +var FuzzyEqual = __webpack_require__(144); +var FuzzyGreaterThan = __webpack_require__(317); +var FuzzyLessThan = __webpack_require__(318); +var GetOverlapX = __webpack_require__(460); +var GetOverlapY = __webpack_require__(461); var GetValue = __webpack_require__(6); -var ProcessQueue = __webpack_require__(181); -var ProcessTileCallbacks = __webpack_require__(1274); -var Rectangle = __webpack_require__(13); -var RTree = __webpack_require__(463); -var SeparateTile = __webpack_require__(1275); -var SeparateX = __webpack_require__(1280); -var SeparateY = __webpack_require__(1281); -var Set = __webpack_require__(127); -var StaticBody = __webpack_require__(465); -var TileIntersectsBody = __webpack_require__(464); -var TransformMatrix = __webpack_require__(30); +var ProcessQueue = __webpack_require__(184); +var ProcessTileCallbacks = __webpack_require__(1270); +var Rectangle = __webpack_require__(11); +var RTree = __webpack_require__(462); +var SeparateTile = __webpack_require__(1271); +var SeparateX = __webpack_require__(1276); +var SeparateY = __webpack_require__(1277); +var Set = __webpack_require__(108); +var StaticBody = __webpack_require__(464); +var TileIntersectsBody = __webpack_require__(463); +var TransformMatrix = __webpack_require__(32); var Vector2 = __webpack_require__(3); var Wrap = __webpack_require__(58); @@ -98007,7 +95989,7 @@ module.exports = World; /***/ }), -/* 459 */ +/* 458 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -98019,9 +96001,9 @@ module.exports = World; var Class = __webpack_require__(0); var CONST = __webpack_require__(50); -var Events = __webpack_require__(213); -var RadToDeg = __webpack_require__(168); -var Rectangle = __webpack_require__(13); +var Events = __webpack_require__(215); +var RadToDeg = __webpack_require__(171); +var Rectangle = __webpack_require__(11); var RectangleContains = __webpack_require__(47); var Vector2 = __webpack_require__(3); @@ -98045,8 +96027,8 @@ var Body = new Class({ function Body (world, gameObject) { - var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; - var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; + var width = (gameObject.width) ? gameObject.width : 64; + var height = (gameObject.height) ? gameObject.height : 64; /** * The Arcade Physics simulation this Body belongs to. @@ -98160,10 +96142,7 @@ var Body = new Class({ * @type {Phaser.Math.Vector2} * @since 3.0.0 */ - this.position = new Vector2( - gameObject.x - gameObject.scaleX * gameObject.displayOriginX, - gameObject.y - gameObject.scaleY * gameObject.displayOriginY - ); + this.position = new Vector2(gameObject.x, gameObject.y); /** * The position of this Body during the previous step. @@ -98293,7 +96272,7 @@ var Body = new Class({ * @type {Phaser.Math.Vector2} * @since 3.0.0 */ - this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); /** * The Body's velocity, in pixels per second. @@ -98919,27 +96898,23 @@ var Body = new Class({ resetFlags: function () { // Store and reset collision flags - var wasTouching = this.wasTouching; - var touching = this.touching; - var blocked = this.blocked; + this.wasTouching.none = this.touching.none; + this.wasTouching.up = this.touching.up; + this.wasTouching.down = this.touching.down; + this.wasTouching.left = this.touching.left; + this.wasTouching.right = this.touching.right; - wasTouching.none = touching.none; - wasTouching.up = touching.up; - wasTouching.down = touching.down; - wasTouching.left = touching.left; - wasTouching.right = touching.right; + this.touching.none = true; + this.touching.up = false; + this.touching.down = false; + this.touching.left = false; + this.touching.right = false; - touching.none = true; - touching.up = false; - touching.down = false; - touching.left = false; - touching.right = false; - - blocked.none = true; - blocked.up = false; - blocked.down = false; - blocked.left = false; - blocked.right = false; + this.blocked.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; this.overlapR = 0; this.overlapX = 0; @@ -99252,10 +97227,10 @@ var Body = new Class({ if (center && gameObject.getCenter) { - var ox = (gameObject.width - width) / 2; - var oy = (gameObject.height - height) / 2; + var ox = gameObject.displayWidth / 2; + var oy = gameObject.displayHeight / 2; - this.offset.set(ox, oy); + this.offset.set(ox - this.halfWidth, oy - this.halfHeight); } this.isCircle = false; @@ -100342,7 +98317,7 @@ module.exports = Body; /***/ }), -/* 460 */ +/* 459 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -100525,7 +98500,7 @@ module.exports = Collider; /***/ }), -/* 461 */ +/* 460 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -100633,7 +98608,7 @@ module.exports = GetOverlapX; /***/ }), -/* 462 */ +/* 461 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -100741,7 +98716,7 @@ module.exports = GetOverlapY; /***/ }), -/* 463 */ +/* 462 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -100751,7 +98726,7 @@ module.exports = GetOverlapY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var quickselect = __webpack_require__(384); +var quickselect = __webpack_require__(383); /** * @classdesc @@ -101352,7 +99327,7 @@ function multiSelect (arr, left, right, n, compare) module.exports = rbush; /***/ }), -/* 464 */ +/* 463 */ /***/ (function(module, exports) { /** @@ -101388,7 +99363,7 @@ module.exports = TileIntersectsBody; /***/ }), -/* 465 */ +/* 464 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -101408,7 +99383,7 @@ var Vector2 = __webpack_require__(3); * A Static Arcade Physics Body. * * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. - * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Static Body manually. + * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Body manually. * * A Static Body can collide with other Bodies, but is never moved by collisions. * @@ -101428,8 +99403,8 @@ var StaticBody = new Class({ function StaticBody (world, gameObject) { - var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; - var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; + var width = (gameObject.width) ? gameObject.width : 64; + var height = (gameObject.height) ? gameObject.height : 64; /** * The Arcade Physics simulation this Static Body belongs to. @@ -101488,8 +99463,8 @@ var StaticBody = new Class({ this.isCircle = false; /** - * If this Static Body is circular, this is the radius of the boundary, as set by {@link Phaser.Physics.Arcade.StaticBody#setCircle}, in pixels. - * Equal to `halfWidth`. + * If this Static Body is circular, this is the unscaled radius of the Static Body's boundary, as set by {@link #setCircle}, in source pixels. + * The true radius is equal to `halfWidth`. * * @name Phaser.Physics.Arcade.StaticBody#radius * @type {number} @@ -101499,13 +99474,12 @@ var StaticBody = new Class({ this.radius = 0; /** - * The offset set by {@link Phaser.Physics.Arcade.StaticBody#setCircle} or {@link Phaser.Physics.Arcade.StaticBody#setSize}. + * The offset of this Static Body's actual position from any updated position. * - * This doesn't affect the Static Body's position, because a Static Body does not follow its Game Object. + * Unlike a dynamic Body, a Static Body does not follow its Game Object. As such, this offset is only applied when resizing the Static Body. * * @name Phaser.Physics.Arcade.StaticBody#offset * @type {Phaser.Math.Vector2} - * @readonly * @since 3.0.0 */ this.offset = new Vector2(); @@ -101567,7 +99541,7 @@ var StaticBody = new Class({ * @type {Phaser.Math.Vector2} * @since 3.0.0 */ - this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); /** * A constant zero velocity used by the Arcade Physics simulation for calculations. @@ -101783,7 +99757,7 @@ var StaticBody = new Class({ this.physicsType = CONST.STATIC_BODY; /** - * The calculated change in the Static Body's horizontal position during the current step. + * The calculated change in the Body's horizontal position during the current step. * For a static body this is always zero. * * @name Phaser.Physics.Arcade.StaticBody#_dx @@ -101795,7 +99769,7 @@ var StaticBody = new Class({ this._dx = 0; /** - * The calculated change in the Static Body's vertical position during the current step. + * The calculated change in the Body's vertical position during the current step. * For a static body this is always zero. * * @name Phaser.Physics.Arcade.StaticBody#_dy @@ -101844,7 +99818,7 @@ var StaticBody = new Class({ }, /** - * Syncs the Static Body's position and size with its parent Game Object. + * Syncs the Body's position and size with its parent Game Object. * * @method Phaser.Physics.Arcade.StaticBody#updateFromGameObject * @since 3.1.0 @@ -101873,13 +99847,13 @@ var StaticBody = new Class({ }, /** - * Positions the Static Body at an offset from its Game Object. + * Sets the offset of the body. * * @method Phaser.Physics.Arcade.StaticBody#setOffset * @since 3.4.0 * - * @param {number} x - The horizontal offset of the Static Body from the Game Object's `x`. - * @param {number} y - The vertical offset of the Static Body from the Game Object's `y`. + * @param {number} x - The horizontal offset of the Body from the Game Object's center. + * @param {number} y - The vertical offset of the Body from the Game Object's center. * * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. */ @@ -101905,16 +99879,15 @@ var StaticBody = new Class({ }, /** - * Sets the size of the Static Body. - * When `center` is true, also repositions it. + * Sets the size of the body. * Resets the width and height to match current frame, if no width and height provided and a frame is found. * * @method Phaser.Physics.Arcade.StaticBody#setSize * @since 3.0.0 * - * @param {integer} [width] - The width of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. - * @param {integer} [height] - The height of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. - * @param {boolean} [center=true] - Place the Static Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. + * @param {integer} [width] - The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param {integer} [height] - The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param {boolean} [center=true] - Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. * * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. */ @@ -101967,7 +99940,7 @@ var StaticBody = new Class({ }, /** - * Sets this Static Body to have a circular body and sets its size and position. + * Sets this Static Body to have a circular body and sets its sizes and position. * * @method Phaser.Physics.Arcade.StaticBody#setCircle * @since 3.0.0 @@ -102377,8 +100350,10 @@ module.exports = StaticBody; /***/ }), +/* 465 */, /* 466 */, -/* 467 */ +/* 467 */, +/* 468 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102508,7 +100483,7 @@ module.exports = BasePlugin; /***/ }), -/* 468 */ +/* 469 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102517,7 +100492,7 @@ module.exports = BasePlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching @@ -102553,7 +100528,7 @@ module.exports = ReplaceByIndex; /***/ }), -/* 469 */ +/* 470 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102562,7 +100537,7 @@ module.exports = ReplaceByIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var IsInLayerBounds = __webpack_require__(99); +var IsInLayerBounds = __webpack_require__(103); /** * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns @@ -102596,7 +100571,7 @@ module.exports = HasTileAt; /***/ }), -/* 470 */ +/* 471 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102605,9 +100580,9 @@ module.exports = HasTileAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tile = __webpack_require__(72); -var IsInLayerBounds = __webpack_require__(99); -var CalculateFacesAt = __webpack_require__(215); +var Tile = __webpack_require__(74); +var IsInLayerBounds = __webpack_require__(103); +var CalculateFacesAt = __webpack_require__(217); /** * Removes the tile at the given tile coordinates in the specified layer and updates the layer's @@ -102643,7 +100618,7 @@ var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, la } else { - layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, layer.tileWidth, layer.tileHeight); + layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, tile.width, tile.height); } // Recalculate faces only if the removed tile was a colliding tile @@ -102658,81 +100633,6 @@ var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, la module.exports = RemoveTileAt; -/***/ }), -/* 471 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = __webpack_require__(10); - -/** - * Converts from world X coordinates (pixels) to orthogonal tile X coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.WorldToTileX - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The X location in tile units. - */ -var OrthoWorldToTileX = function (worldX, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - return snapToFloor - ? Math.floor(worldX / tileWidth) - : worldX / tileWidth; - -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the WorldToTileXY function.'); - return null; -}; - -var WorldToTileX = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoWorldToTileX; - - default: - return nullFunc; - - } - -}; - -module.exports = WorldToTileX; - - /***/ }), /* 472 */ /***/ (function(module, exports, __webpack_require__) { @@ -102743,173 +100643,11 @@ module.exports = WorldToTileX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); - -/** - * Converts from world Y coordinates (pixels) to orthogonal tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.OrthoWorldToTileY - * @private - * @since 3.0.0 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var OrthoWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - return snapToFloor - ? Math.floor(worldY / tileHeight) - : worldY / tileHeight; - -}; - -/** - * Converts from world Y coordinates (pixels) to staggered tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.StagWorldToTileY - * @private - * @since 3.2.2 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var StagWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - return snapToFloor - ? Math.floor(worldY / (tileHeight / 2)) - : worldY / (tileHeight / 2); -}; - -/** - * Converts from world Y coordinates (pixels) to hexagonal tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.HexWorldToTileY - * @private - * @since 3.2.2 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var HexWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - return snapToFloor - ? Math.floor(worldY / rowHeight) - : worldY / rowHeight; -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the WorldToTileXY function.'); - return null; -}; - -var WorldToTileY = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoWorldToTileY; - - case CONST.HEXAGONAL: - return HexWorldToTileY; - - case CONST.STAGGERED: - return StagWorldToTileY; - - default: - return nullFunc; - - } - -}; - -module.exports = WorldToTileY; - - -/***/ }), -/* 473 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = __webpack_require__(33); -var Parse2DArray = __webpack_require__(218); -var ParseCSV = __webpack_require__(474); -var ParseJSONTiled = __webpack_require__(475); -var ParseWeltmeister = __webpack_require__(486); +var Formats = __webpack_require__(31); +var Parse2DArray = __webpack_require__(220); +var ParseCSV = __webpack_require__(473); +var ParseJSONTiled = __webpack_require__(474); +var ParseWeltmeister = __webpack_require__(485); /** * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format @@ -102966,7 +100704,7 @@ module.exports = Parse; /***/ }), -/* 474 */ +/* 473 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102975,8 +100713,8 @@ module.exports = Parse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var Parse2DArray = __webpack_require__(218); +var Formats = __webpack_require__(31); +var Parse2DArray = __webpack_require__(220); /** * Parses a CSV string of tile indexes into a new MapData object with a single layer. @@ -103014,7 +100752,7 @@ module.exports = ParseCSV; /***/ }), -/* 475 */ +/* 474 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103023,15 +100761,14 @@ module.exports = ParseCSV; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var Formats = __webpack_require__(33); -var MapData = __webpack_require__(101); -var ParseTileLayers = __webpack_require__(476); -var ParseImageLayers = __webpack_require__(478); -var ParseTilesets = __webpack_require__(479); -var ParseObjectLayers = __webpack_require__(482); -var BuildTilesetIndex = __webpack_require__(484); -var AssignTileProperties = __webpack_require__(485); +var Formats = __webpack_require__(31); +var MapData = __webpack_require__(105); +var ParseTileLayers = __webpack_require__(475); +var ParseImageLayers = __webpack_require__(477); +var ParseTilesets = __webpack_require__(478); +var ParseObjectLayers = __webpack_require__(481); +var BuildTilesetIndex = __webpack_require__(483); +var AssignTileProperties = __webpack_require__(484); /** * Parses a Tiled JSON object into a new MapData object. @@ -103052,21 +100789,12 @@ var AssignTileProperties = __webpack_require__(485); */ var ParseJSONTiled = function (name, json, insertNull) { - if (json.orientation === 'isometric' || json.orientation === 'staggered') + if (json.orientation !== 'orthogonal') { - console.warn('Isometric map types are WIP in this version of Phaser'); - } - else if (json.orientation === 'hexagonal') - { - console.warn('Hexagonal map types are WIP in this version of Phaser'); - } - else if (json.orientation !== 'orthogonal') - { - console.warn('Only orthogonal, hexagonal and isometric map types are supported in this version of Phaser'); + console.warn('Only orthogonal map types are supported in this version of Phaser'); return null; } - // Map data will consist of: layers, objects, images, tilesets, sizes var mapData = new MapData({ width: json.width, @@ -103074,7 +100802,7 @@ var ParseJSONTiled = function (name, json, insertNull) name: name, tileWidth: json.tilewidth, tileHeight: json.tileheight, - orientation: CONST.fromOrientationString(json.orientation), + orientation: json.orientation, format: Formats.TILED_JSON, version: json.version, properties: json.properties, @@ -103082,14 +100810,6 @@ var ParseJSONTiled = function (name, json, insertNull) infinite: json.infinite }); - - - - if (mapData.orientation === CONST.HEXAGONAL) - { - mapData.hexSideLength = json.hexsidelength; - } - mapData.layers = ParseTileLayers(json, insertNull); mapData.images = ParseImageLayers(json); @@ -103110,7 +100830,7 @@ module.exports = ParseJSONTiled; /***/ }), -/* 476 */ +/* 475 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103119,13 +100839,12 @@ module.exports = ParseJSONTiled; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var Base64Decode = __webpack_require__(477); +var Base64Decode = __webpack_require__(476); var GetFastValue = __webpack_require__(2); -var LayerData = __webpack_require__(100); -var ParseGID = __webpack_require__(219); -var Tile = __webpack_require__(72); -var CreateGroupLayer = __webpack_require__(220); +var LayerData = __webpack_require__(104); +var ParseGID = __webpack_require__(221); +var Tile = __webpack_require__(74); +var CreateGroupLayer = __webpack_require__(222); /** * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. @@ -103243,15 +100962,9 @@ var ParseTileLayers = function (json, insertNull) tileHeight: json.tileheight, alpha: (curGroupState.opacity * curl.opacity), visible: (curGroupState.visible && curl.visible), - properties: GetFastValue(curl, 'properties', {}), - orientation: CONST.fromOrientationString(json.orientation) + properties: GetFastValue(curl, 'properties', {}) }); - if (layerData.orientation === CONST.HEXAGONAL) - { - layerData.hexSideLength = json.hexsidelength; - } - for (var c = 0; c < curl.height; c++) { output.push([ null ]); @@ -103322,14 +101035,9 @@ var ParseTileLayers = function (json, insertNull) tileHeight: json.tileheight, alpha: (curGroupState.opacity * curl.opacity), visible: (curGroupState.visible && curl.visible), - properties: GetFastValue(curl, 'properties', {}), - orientation: CONST.fromOrientationString(json.orientation) + properties: GetFastValue(curl, 'properties', {}) }); - if (layerData.orientation === CONST.HEXAGONAL) - { - layerData.hexSideLength = json.hexsidelength; - } var row = []; // Loop through the data field in the JSON. @@ -103380,7 +101088,7 @@ module.exports = ParseTileLayers; /***/ }), -/* 477 */ +/* 476 */ /***/ (function(module, exports) { /** @@ -103423,7 +101131,7 @@ module.exports = Base64Decode; /***/ }), -/* 478 */ +/* 477 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103433,7 +101141,7 @@ module.exports = Base64Decode; */ var GetFastValue = __webpack_require__(2); -var CreateGroupLayer = __webpack_require__(220); +var CreateGroupLayer = __webpack_require__(222); /** * Parses a Tiled JSON object into an array of objects with details about the image layers. @@ -103511,7 +101219,7 @@ module.exports = ParseImageLayers; /***/ }), -/* 479 */ +/* 478 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103520,9 +101228,9 @@ module.exports = ParseImageLayers; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tileset = __webpack_require__(137); -var ImageCollection = __webpack_require__(480); -var ParseObject = __webpack_require__(221); +var Tileset = __webpack_require__(141); +var ImageCollection = __webpack_require__(479); +var ParseObject = __webpack_require__(223); /** * Tilesets and Image Collections @@ -103680,7 +101388,7 @@ module.exports = ParseTilesets; /***/ }), -/* 480 */ +/* 479 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103852,7 +101560,7 @@ module.exports = ImageCollection; /***/ }), -/* 481 */ +/* 480 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103861,7 +101569,7 @@ module.exports = ImageCollection; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HasValue = __webpack_require__(104); +var HasValue = __webpack_require__(99); /** * Returns a new object that only contains the `keys` that were found on the object provided. @@ -103896,7 +101604,7 @@ module.exports = Pick; /***/ }), -/* 482 */ +/* 481 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -103906,9 +101614,9 @@ module.exports = Pick; */ var GetFastValue = __webpack_require__(2); -var ParseObject = __webpack_require__(221); -var ObjectLayer = __webpack_require__(483); -var CreateGroupLayer = __webpack_require__(220); +var ParseObject = __webpack_require__(223); +var ObjectLayer = __webpack_require__(482); +var CreateGroupLayer = __webpack_require__(222); /** * Parses a Tiled JSON object into an array of ObjectLayer objects. @@ -103995,7 +101703,7 @@ module.exports = ParseObjectLayers; /***/ }), -/* 483 */ +/* 482 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -104117,7 +101825,7 @@ module.exports = ObjectLayer; /***/ }), -/* 484 */ +/* 483 */ /***/ (function(module, exports) { /** @@ -104190,7 +101898,7 @@ module.exports = BuildTilesetIndex; /***/ }), -/* 485 */ +/* 484 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -104199,7 +101907,7 @@ module.exports = BuildTilesetIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * Copy properties from tileset to tiles. @@ -104263,7 +101971,7 @@ module.exports = AssignTileProperties; /***/ }), -/* 486 */ +/* 485 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -104272,10 +101980,10 @@ module.exports = AssignTileProperties; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var MapData = __webpack_require__(101); -var ParseTileLayers = __webpack_require__(487); -var ParseTilesets = __webpack_require__(488); +var Formats = __webpack_require__(31); +var MapData = __webpack_require__(105); +var ParseTileLayers = __webpack_require__(486); +var ParseTilesets = __webpack_require__(487); /** * Parses a Weltmeister JSON object into a new MapData object. @@ -104330,7 +102038,7 @@ module.exports = ParseWeltmeister; /***/ }), -/* 487 */ +/* 486 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -104339,8 +102047,8 @@ module.exports = ParseWeltmeister; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var LayerData = __webpack_require__(100); -var Tile = __webpack_require__(72); +var LayerData = __webpack_require__(104); +var Tile = __webpack_require__(74); /** * [description] @@ -104414,7 +102122,7 @@ module.exports = ParseTileLayers; /***/ }), -/* 488 */ +/* 487 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -104423,7 +102131,7 @@ module.exports = ParseTileLayers; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tileset = __webpack_require__(137); +var Tileset = __webpack_require__(141); /** * [description] @@ -104465,7 +102173,7 @@ module.exports = ParseTilesets; /***/ }), -/* 489 */ +/* 488 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -104476,16 +102184,16 @@ module.exports = ParseTilesets; var Class = __webpack_require__(0); var DegToRad = __webpack_require__(35); -var DynamicTilemapLayer = __webpack_require__(490); -var Extend = __webpack_require__(18); -var Formats = __webpack_require__(33); -var LayerData = __webpack_require__(100); -var Rotate = __webpack_require__(326); -var SpliceOne = __webpack_require__(78); -var StaticTilemapLayer = __webpack_require__(491); -var Tile = __webpack_require__(72); -var TilemapComponents = __webpack_require__(135); -var Tileset = __webpack_require__(137); +var DynamicTilemapLayer = __webpack_require__(489); +var Extend = __webpack_require__(17); +var Formats = __webpack_require__(31); +var LayerData = __webpack_require__(104); +var Rotate = __webpack_require__(327); +var SpliceOne = __webpack_require__(79); +var StaticTilemapLayer = __webpack_require__(490); +var Tile = __webpack_require__(74); +var TilemapComponents = __webpack_require__(137); +var Tileset = __webpack_require__(141); /** * @callback TilemapFilterCallback @@ -104721,28 +102429,6 @@ var Tilemap = new Class({ * @since 3.0.0 */ this.currentLayerIndex = 0; - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = mapData.hexSideLength; - - /** - * Components used for conversions between real world coordinates and tile coordinates, - * initialized here to prevent switching between them at runtime depending on map orientation. - * refer to the components themselves for documentation. - * @since 3.2.2 - */ - this.WorldToTileXY = TilemapComponents.WorldToTileXY(this.orientation); - this.WorldToTileX = TilemapComponents.WorldToTileX(this.orientation); - this.WorldToTileY = TilemapComponents.WorldToTileY(this.orientation); - this.TileToWorldXY = TilemapComponents.TileToWorldXY(this.orientation); - this.TileToWorldX = TilemapComponents.TileToWorldX(this.orientation); - this.TileToWorldY = TilemapComponents.TileToWorldY(this.orientation); }, /** @@ -104993,8 +102679,7 @@ var Tilemap = new Class({ tileWidth: tileWidth, tileHeight: tileHeight, width: width, - height: height, - orientation: this.orientation + height: height }); var row; @@ -106838,7 +104523,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.TileToWorldX(tileX, camera, layer); + return TilemapComponents.TileToWorldX(tileX, camera, layer); }, /** @@ -106863,7 +104548,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.TileToWorldY(tileX, camera, layer); + return TilemapComponents.TileToWorldY(tileX, camera, layer); }, /** @@ -106884,14 +104569,13 @@ var Tilemap = new Class({ * * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. */ - tileToWorldXY: function (tileX, tileY, point, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null; } - return this.TileToWorldXY(tileX, tileY, point, camera, layer); + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, layer); }, /** @@ -106962,7 +104646,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.WorldToTileX(worldX, snapToFloor, camera, layer); + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, layer); }, /** @@ -106987,7 +104671,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.WorldToTileY(worldY, snapToFloor, camera, layer); + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, layer); }, /** @@ -107015,7 +104699,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); }, /** @@ -107046,7 +104730,7 @@ module.exports = Tilemap; /***/ }), -/* 490 */ +/* 489 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107057,10 +104741,9 @@ module.exports = Tilemap; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var DynamicTilemapLayerRender = __webpack_require__(1338); +var DynamicTilemapLayerRender = __webpack_require__(1333); var GameObject = __webpack_require__(14); -var TilemapComponents = __webpack_require__(135); -var Vector2 = __webpack_require__(3); +var TilemapComponents = __webpack_require__(137); /** * @classdesc @@ -107163,7 +104846,7 @@ var DynamicTilemapLayer = new Class({ // Link the LayerData with this static tilemap layer this.layer.tilemapLayer = this; - + /** * The Tileset/s associated with this layer. * @@ -107198,18 +104881,6 @@ var DynamicTilemapLayer = new Class({ */ this.skipCull = false; - /** - * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. - * By default the camera will allow 1 full tile in all directions. - * - * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#isoCullDistances - * @type {Phaser.Math.Vector2} - * @since 3.23.0 - */ - this.isoCullDistances = new Vector2(1, 1); - /** * The total number of tiles drawn by the renderer in the last frame. * @@ -108242,7 +105913,7 @@ var DynamicTilemapLayer = new Class({ */ tileToWorldX: function (tileX, camera) { - return this.tilemap.TileToWorldX(tileX, camera, this.layer); + return TilemapComponents.TileToWorldX(tileX, camera, this.layer); }, /** @@ -108259,7 +105930,7 @@ var DynamicTilemapLayer = new Class({ */ tileToWorldY: function (tileY, camera) { - return this.tilemap.TileToWorldY(tileY, camera, this.layer); + return TilemapComponents.TileToWorldY(tileY, camera, this.layer); }, /** @@ -108279,7 +105950,7 @@ var DynamicTilemapLayer = new Class({ */ tileToWorldXY: function (tileX, tileY, point, camera) { - return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer); }, /** @@ -108332,7 +106003,7 @@ var DynamicTilemapLayer = new Class({ */ worldToTileX: function (worldX, snapToFloor, camera) { - return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer); }, /** @@ -108350,7 +106021,7 @@ var DynamicTilemapLayer = new Class({ */ worldToTileY: function (worldY, snapToFloor, camera) { - return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer); }, /** @@ -108371,7 +106042,7 @@ var DynamicTilemapLayer = new Class({ */ worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) { - return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); } }); @@ -108380,7 +106051,7 @@ module.exports = DynamicTilemapLayer; /***/ }), -/* 491 */ +/* 490 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108391,13 +106062,12 @@ module.exports = DynamicTilemapLayer; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); -var StaticTilemapLayerRender = __webpack_require__(1341); -var TilemapComponents = __webpack_require__(135); -var TransformMatrix = __webpack_require__(30); -var Utils = __webpack_require__(9); -var Vector2 = __webpack_require__(3); +var StaticTilemapLayerRender = __webpack_require__(1336); +var TilemapComponents = __webpack_require__(137); +var TransformMatrix = __webpack_require__(32); +var Utils = __webpack_require__(10); /** * @classdesc @@ -108536,18 +106206,6 @@ var StaticTilemapLayer = new Class({ */ this.skipCull = false; - /** - * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. - * By default the camera will allow 1 full tile in all directions. - * - * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#isoCullDistances - * @type {Phaser.Math.Vector2} - * @since 3.23.0 - */ - this.isoCullDistances = new Vector2(1, 1); - /** * Canvas only. * @@ -108761,7 +106419,6 @@ var StaticTilemapLayer = new Class({ { this.updateVBOData(); }, this); - }, /** @@ -109732,7 +107389,7 @@ var StaticTilemapLayer = new Class({ */ tileToWorldX: function (tileX, camera) { - return this.tilemap.TileToWorldX(tileX, camera, this.layer); + return TilemapComponents.TileToWorldX(tileX, camera, this.layer); }, /** @@ -109749,7 +107406,7 @@ var StaticTilemapLayer = new Class({ */ tileToWorldY: function (tileY, camera) { - return this.tilemap.TileToWorldY(tileY, camera, this.layer); + return TilemapComponents.TileToWorldY(tileY, camera, this.layer); }, /** @@ -109769,7 +107426,7 @@ var StaticTilemapLayer = new Class({ */ tileToWorldXY: function (tileX, tileY, point, camera) { - return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer); }, /** @@ -109788,7 +107445,7 @@ var StaticTilemapLayer = new Class({ */ worldToTileX: function (worldX, snapToFloor, camera) { - return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer); }, /** @@ -109807,7 +107464,7 @@ var StaticTilemapLayer = new Class({ */ worldToTileY: function (worldY, snapToFloor, camera) { - return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer); }, /** @@ -109829,7 +107486,7 @@ var StaticTilemapLayer = new Class({ */ worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) { - return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); }, /** @@ -109888,7 +107545,7 @@ module.exports = StaticTilemapLayer; /***/ }), -/* 492 */ +/* 491 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110201,7 +107858,7 @@ module.exports = TimerEvent; /***/ }), -/* 493 */ +/* 492 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110210,7 +107867,7 @@ module.exports = TimerEvent; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RESERVED = __webpack_require__(1350); +var RESERVED = __webpack_require__(1345); /** * Internal function used by the Tween Builder to return an array of properties @@ -110262,7 +107919,7 @@ module.exports = GetProps; /***/ }), -/* 494 */ +/* 493 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110310,7 +107967,7 @@ module.exports = GetTweens; /***/ }), -/* 495 */ +/* 494 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110319,15 +107976,15 @@ module.exports = GetTweens; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Defaults = __webpack_require__(225); +var Defaults = __webpack_require__(227); var GetAdvancedValue = __webpack_require__(15); -var GetBoolean = __webpack_require__(86); -var GetEaseFunction = __webpack_require__(67); -var GetNewValue = __webpack_require__(138); +var GetBoolean = __webpack_require__(88); +var GetEaseFunction = __webpack_require__(82); +var GetNewValue = __webpack_require__(142); var GetValue = __webpack_require__(6); -var GetValueOp = __webpack_require__(224); -var Tween = __webpack_require__(226); -var TweenData = __webpack_require__(228); +var GetValueOp = __webpack_require__(226); +var Tween = __webpack_require__(228); +var TweenData = __webpack_require__(230); /** * Creates a new Number Tween. @@ -110440,7 +108097,7 @@ module.exports = NumberTweenBuilder; /***/ }), -/* 496 */ +/* 495 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110449,9 +108106,9 @@ module.exports = NumberTweenBuilder; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetEaseFunction = __webpack_require__(67); +var GetEaseFunction = __webpack_require__(82); var GetValue = __webpack_require__(6); -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); /** * Creates a Stagger function to be used by a Tween property. @@ -110686,7 +108343,7 @@ module.exports = StaggerBuilder; /***/ }), -/* 497 */ +/* 496 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110695,17 +108352,17 @@ module.exports = StaggerBuilder; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); -var Defaults = __webpack_require__(225); +var Clone = __webpack_require__(67); +var Defaults = __webpack_require__(227); var GetAdvancedValue = __webpack_require__(15); -var GetBoolean = __webpack_require__(86); -var GetEaseFunction = __webpack_require__(67); -var GetNewValue = __webpack_require__(138); -var GetTargets = __webpack_require__(223); -var GetTweens = __webpack_require__(494); +var GetBoolean = __webpack_require__(88); +var GetEaseFunction = __webpack_require__(82); +var GetNewValue = __webpack_require__(142); +var GetTargets = __webpack_require__(225); +var GetTweens = __webpack_require__(493); var GetValue = __webpack_require__(6); -var Timeline = __webpack_require__(498); -var TweenBuilder = __webpack_require__(139); +var Timeline = __webpack_require__(497); +var TweenBuilder = __webpack_require__(143); /** * Builds a Timeline of Tweens based on a configuration object. @@ -110838,7 +108495,7 @@ module.exports = TimelineBuilder; /***/ }), -/* 498 */ +/* 497 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -110848,10 +108505,10 @@ module.exports = TimelineBuilder; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(227); -var TweenBuilder = __webpack_require__(139); -var TWEEN_CONST = __webpack_require__(87); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(229); +var TweenBuilder = __webpack_require__(143); +var TWEEN_CONST = __webpack_require__(89); /** * @classdesc @@ -111743,7 +109400,7 @@ module.exports = Timeline; /***/ }), -/* 499 */ +/* 498 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -111752,9 +109409,9 @@ module.exports = Timeline; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseAnimation = __webpack_require__(145); +var BaseAnimation = __webpack_require__(148); var Class = __webpack_require__(0); -var Events = __webpack_require__(107); +var Events = __webpack_require__(111); /** * @classdesc @@ -112768,16 +110425,13 @@ var Animation = new Class({ gameObject.setSizeToFrame(); - if (gameObject._originComponent) + if (animationFrame.frame.customPivot) { - if (animationFrame.frame.customPivot) - { - gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); - } - else - { - gameObject.updateDisplayOrigin(); - } + gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); + } + else + { + gameObject.updateDisplayOrigin(); } return gameObject; @@ -112921,7 +110575,7 @@ module.exports = Animation; /***/ }), -/* 500 */ +/* 499 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -112931,13 +110585,13 @@ module.exports = Animation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasSnapshot = __webpack_require__(501); +var CanvasSnapshot = __webpack_require__(500); var CameraEvents = __webpack_require__(48); var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); -var GetBlendModes = __webpack_require__(502); -var ScaleEvents = __webpack_require__(90); -var TransformMatrix = __webpack_require__(30); +var CONST = __webpack_require__(29); +var GetBlendModes = __webpack_require__(501); +var ScaleEvents = __webpack_require__(92); +var TransformMatrix = __webpack_require__(32); /** * @classdesc @@ -113382,10 +111036,7 @@ var CanvasRenderer = new Class({ { camera.emit(CameraEvents.POST_RENDER, camera); - if (camera.renderToGame) - { - scene.sys.context.drawImage(camera.canvas, cx, cy); - } + scene.sys.context.drawImage(camera.canvas, cx, cy); } }, @@ -113718,7 +111369,7 @@ module.exports = CanvasRenderer; /***/ }), -/* 501 */ +/* 500 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -113727,8 +111378,8 @@ module.exports = CanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); -var Color = __webpack_require__(32); +var CanvasPool = __webpack_require__(26); +var Color = __webpack_require__(33); var GetFastValue = __webpack_require__(2); /** @@ -113811,7 +111462,7 @@ module.exports = CanvasSnapshot; /***/ }), -/* 502 */ +/* 501 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -113821,7 +111472,7 @@ module.exports = CanvasSnapshot; */ var modes = __webpack_require__(52); -var CanvasFeatures = __webpack_require__(311); +var CanvasFeatures = __webpack_require__(313); /** * Returns an array which maps the default blend modes to supported Canvas blend modes. @@ -113875,7 +111526,7 @@ module.exports = GetBlendModes; /***/ }), -/* 503 */ +/* 502 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -113885,25 +111536,24 @@ module.exports = GetBlendModes; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCamera = __webpack_require__(89); +var BaseCamera = __webpack_require__(91); var CameraEvents = __webpack_require__(48); var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); -var GameEvents = __webpack_require__(19); -var IsSizePowerOfTwo = __webpack_require__(114); +var CONST = __webpack_require__(29); +var GameEvents = __webpack_require__(18); +var IsSizePowerOfTwo = __webpack_require__(118); var NOOP = __webpack_require__(1); -var ScaleEvents = __webpack_require__(90); -var SpliceOne = __webpack_require__(78); -var TextureEvents = __webpack_require__(115); -var TransformMatrix = __webpack_require__(30); -var Utils = __webpack_require__(9); -var WebGLSnapshot = __webpack_require__(504); +var ScaleEvents = __webpack_require__(92); +var SpliceOne = __webpack_require__(79); +var TextureEvents = __webpack_require__(119); +var TransformMatrix = __webpack_require__(32); +var Utils = __webpack_require__(10); +var WebGLSnapshot = __webpack_require__(503); // Default Pipelines -var BitmapMaskPipeline = __webpack_require__(505); -var ForwardDiffuseLightPipeline = __webpack_require__(506); -var TextureTintPipeline = __webpack_require__(232); -var TextureTintStripPipeline = __webpack_require__(507); +var BitmapMaskPipeline = __webpack_require__(504); +var ForwardDiffuseLightPipeline = __webpack_require__(505); +var TextureTintPipeline = __webpack_require__(235); /** * @callback WebGLContextCallback @@ -114592,7 +112242,6 @@ var WebGLRenderer = new Class({ this.pipelines = {}; this.addPipeline('TextureTintPipeline', new TextureTintPipeline({ game: game, renderer: this })); - this.addPipeline('TextureTintStripPipeline', new TextureTintStripPipeline({ game: game, renderer: this })); this.addPipeline('BitmapMaskPipeline', new BitmapMaskPipeline({ game: game, renderer: this })); this.addPipeline('Light2D', new ForwardDiffuseLightPipeline({ game: game, renderer: this, maxLights: config.maxLights })); @@ -115820,36 +113469,33 @@ var WebGLRenderer = new Class({ camera.emit(CameraEvents.POST_RENDER, camera); - if (camera.renderToGame) - { - TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); + TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); - var getTint = Utils.getTintAppendFloatAlpha; - - var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; - - pipeline.batchTexture( - camera, - camera.glTexture, - camera.width, camera.height, - camera.x, camera.y, - camera.width, camera.height, - camera.zoom, camera.zoom, - camera.rotation, - camera.flipX, !camera.flipY, - 1, 1, - 0, 0, - 0, 0, camera.width, camera.height, - getTint(camera._tintTL, camera._alphaTL), - getTint(camera._tintTR, camera._alphaTR), - getTint(camera._tintBL, camera._alphaBL), - getTint(camera._tintBR, camera._alphaBR), - (camera._isTinted && camera.tintFill), - 0, 0, - this.defaultCamera, - null - ); - } + var getTint = Utils.getTintAppendFloatAlpha; + + var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; + + pipeline.batchTexture( + camera, + camera.glTexture, + camera.width, camera.height, + camera.x, camera.y, + camera.width, camera.height, + camera.zoom, camera.zoom, + camera.rotation, + camera.flipX, !camera.flipY, + 1, 1, + 0, 0, + 0, 0, camera.width, camera.height, + getTint(camera._tintTL, camera._alphaTL), + getTint(camera._tintTR, camera._alphaTR), + getTint(camera._tintBL, camera._alphaBL), + getTint(camera._tintBR, camera._alphaBR), + (camera._isTinted && camera.tintFill), + 0, 0, + this.defaultCamera, + null + ); // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it this.setBlankTexture(true); @@ -116427,16 +114073,14 @@ var WebGLRenderer = new Class({ }, /** - * Sets a 1f uniform value on the given shader. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 1f value to set on the named uniform. + * @param {number} x - [description] * * @return {this} This WebGL Renderer instance. */ @@ -116450,17 +114094,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 2f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 2f x value to set on the named uniform. - * @param {number} y - The 2f y value to set on the named uniform. + * @param {number} x - [description] + * @param {number} y - [description] * * @return {this} This WebGL Renderer instance. */ @@ -116474,18 +114116,16 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 3f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 3f x value to set on the named uniform. - * @param {number} y - The 3f y value to set on the named uniform. - * @param {number} z - The 3f z value to set on the named uniform. + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} z - [description] * * @return {this} This WebGL Renderer instance. */ @@ -116499,19 +114139,17 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 4f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets uniform of a WebGLProgram * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 4f x value to set on the named uniform. - * @param {number} y - The 4f y value to set on the named uniform. - * @param {number} z - The 4f z value to set on the named uniform. - * @param {number} w - The 4f w value to set on the named uniform. + * @param {number} x - X component + * @param {number} y - Y component + * @param {number} z - Z component + * @param {number} w - W component * * @return {this} This WebGL Renderer instance. */ @@ -116525,9 +114163,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 1fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1v * @since 3.13.0 @@ -116548,9 +114184,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 2fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2v * @since 3.13.0 @@ -116571,9 +114205,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 3fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3v * @since 3.13.0 @@ -116594,9 +114226,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 4fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4v * @since 3.13.0 @@ -116618,16 +114248,14 @@ var WebGLRenderer = new Class({ }, /** - * Sets a 1i uniform value on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt1 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 1i value to set on the named uniform. + * @param {integer} x - [description] * * @return {this} This WebGL Renderer instance. */ @@ -116641,17 +114269,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 2i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt2 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 2i x value to set on the named uniform. - * @param {integer} y - The 2i y value to set on the named uniform. + * @param {integer} x - The new X component + * @param {integer} y - The new Y component * * @return {this} This WebGL Renderer instance. */ @@ -116665,18 +114291,16 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 3i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt3 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 3i x value to set on the named uniform. - * @param {integer} y - The 3i y value to set on the named uniform. - * @param {integer} z - The 3i z value to set on the named uniform. + * @param {integer} x - The new X component + * @param {integer} y - The new Y component + * @param {integer} z - The new Z component * * @return {this} This WebGL Renderer instance. */ @@ -116690,19 +114314,17 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 4i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt4 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 4i x value to set on the named uniform. - * @param {integer} y - The 4i y value to set on the named uniform. - * @param {integer} z - The 4i z value to set on the named uniform. - * @param {integer} w - The 4i w value to set on the named uniform. + * @param {integer} x - X component + * @param {integer} y - Y component + * @param {integer} z - Z component + * @param {integer} w - W component * * @return {this} This WebGL Renderer instance. */ @@ -116716,9 +114338,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a matrix 2fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a 2x2 matrix uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix2 * @since 3.0.0 @@ -116726,7 +114346,7 @@ var WebGLRenderer = new Class({ * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 4 float values. + * @param {Float32Array} matrix - The new matrix value. * * @return {this} This WebGL Renderer instance. */ @@ -116740,17 +114360,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a matrix 3fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix3 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 9 float values. + * @param {boolean} transpose - [description] + * @param {Float32Array} matrix - [description] * * @return {this} This WebGL Renderer instance. */ @@ -116764,17 +114382,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a matrix 4fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets uniform of a WebGLProgram * * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix4 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 16 float values. + * @param {boolean} transpose - Is the matrix transposed + * @param {Float32Array} matrix - Matrix data * * @return {this} This WebGL Renderer instance. */ @@ -116864,7 +114480,7 @@ module.exports = WebGLRenderer; /***/ }), -/* 504 */ +/* 503 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -116873,8 +114489,8 @@ module.exports = WebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); -var Color = __webpack_require__(32); +var CanvasPool = __webpack_require__(26); +var Color = __webpack_require__(33); var GetFastValue = __webpack_require__(2); /** @@ -116974,7 +114590,7 @@ module.exports = WebGLSnapshot; /***/ }), -/* 505 */ +/* 504 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -116987,7 +114603,7 @@ module.exports = WebGLSnapshot; var Class = __webpack_require__(0); var ShaderSourceFS = __webpack_require__(776); var ShaderSourceVS = __webpack_require__(777); -var WebGLPipeline = __webpack_require__(141); +var WebGLPipeline = __webpack_require__(234); /** * @classdesc @@ -117105,23 +114721,21 @@ var BitmapMaskPipeline = new Class({ }, /** - * Resizes this pipeline and updates the projection. + * [description] * * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resize * @since 3.0.0 * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} resolution - [description] * * @return {this} This WebGLPipeline instance. */ resize: function (width, height, resolution) { WebGLPipeline.prototype.resize.call(this, width, height, resolution); - this.resolutionDirty = true; - return this; }, @@ -117134,7 +114748,7 @@ var BitmapMaskPipeline = new Class({ * * @param {Phaser.GameObjects.GameObject} mask - GameObject used as mask. * @param {Phaser.GameObjects.GameObject} maskedObject - GameObject masked by the mask GameObject. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera rendering the current mask. + * @param {Phaser.Cameras.Scene2D.Camera} camera - [description] */ beginMask: function (mask, maskedObject, camera) { @@ -117239,7 +114853,7 @@ module.exports = BitmapMaskPipeline; /***/ }), -/* 506 */ +/* 505 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -117251,7 +114865,7 @@ module.exports = BitmapMaskPipeline; var Class = __webpack_require__(0); var ShaderSourceFS = __webpack_require__(778); -var TextureTintPipeline = __webpack_require__(232); +var TextureTintPipeline = __webpack_require__(235); var LIGHT_COUNT = 10; @@ -117760,421 +115374,761 @@ module.exports = ForwardDiffuseLightPipeline; /***/ }), -/* 507 */ -/***/ (function(module, exports, __webpack_require__) { +/* 506 */ +/***/ (function(module, exports) { /** * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Class = __webpack_require__(0); -var GetFastValue = __webpack_require__(2); -var ModelViewProjection = __webpack_require__(233); -var ShaderSourceFS = __webpack_require__(335); -var ShaderSourceVS = __webpack_require__(336); -var TransformMatrix = __webpack_require__(30); -var WebGLPipeline = __webpack_require__(141); - /** - * @classdesc - * TextureTintStripPipeline implements the rendering infrastructure - * for displaying textured objects - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. + * Implements a model view projection matrices. + * Pipelines can implement this for doing 2D and 3D rendering. * - * @class TextureTintStripPipeline - * @extends Phaser.Renderer.WebGL.WebGLPipeline - * @memberof Phaser.Renderer.WebGL.Pipelines - * @constructor - * @since 3.23.0 - * - * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. + * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection + * @since 3.0.0 */ -var TextureTintStripPipeline = new Class({ - - Extends: WebGLPipeline, - - Mixins: [ - ModelViewProjection - ], - - initialize: - - function TextureTintStripPipeline (config) - { - var rendererConfig = config.renderer.config; - - // Vertex Size = attribute size added together (2 + 2 + 1 + 4) - - WebGLPipeline.call(this, { - game: config.game, - renderer: config.renderer, - gl: config.renderer.gl, - topology: config.renderer.gl.TRIANGLE_STRIP, - vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), - fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), - vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), - vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), - attributes: [ - { - name: 'inPosition', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: 0 - }, - { - name: 'inTexCoord', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 2 - }, - { - name: 'inTintEffect', - size: 1, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 4 - }, - { - name: 'inTint', - size: 4, - type: config.renderer.gl.UNSIGNED_BYTE, - normalized: true, - offset: Float32Array.BYTES_PER_ELEMENT * 5 - } - ] - }); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewF32 - * @type {Float32Array} - * @since 3.23.0 - */ - this.vertexViewF32 = new Float32Array(this.vertexData); - - /** - * Uint32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewU32 - * @type {Uint32Array} - * @since 3.23.0 - */ - this.vertexViewU32 = new Uint32Array(this.vertexData); - - /** - * Size of the batch. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#maxQuads - * @type {integer} - * @since 3.23.0 - */ - this.maxQuads = rendererConfig.batchSize; - - /** - * Collection of batch information - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#batches - * @type {array} - * @since 3.23.0 - */ - this.batches = []; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - this.mvpInit(); - }, +var ModelViewProjection = { /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#onBind - * @since 3.23.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - WebGLPipeline.prototype.onBind.call(this); - - this.mvpUpdate(); - - return this; - }, - - /** - * Resizes this pipeline and updates the projection. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#resize - * @since 3.23.0 - * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - WebGLPipeline.prototype.resize.call(this, width, height, resolution); - - this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); - - return this; - }, - - /** - * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#setTexture2D - * @since 3.23.0 - * - * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. - * - * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline} This pipeline instance. - */ - setTexture2D: function (texture, unit) - { - if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } - if (unit === undefined) { unit = 0; } - - if (this.requireTextureBatch(texture, unit)) - { - this.pushBatch(texture, unit); - } - - return this; - }, - - /** - * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#requireTextureBatch - * @since 3.23.0 - * - * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} unit - Texture unit to which the texture needs to be bound. - * - * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. - */ - requireTextureBatch: function (texture, unit) - { - var batches = this.batches; - var batchLength = batches.length; - - if (batchLength > 0) - { - // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property - var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; - - return !(currentTexture === texture); - } - - return true; - }, - - /** - * Creates a new batch object and pushes it to a batch array. - * The batch object contains information relevant to the current - * vertex batch like the offset in the vertex buffer, vertex count and - * the textures used by that batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#pushBatch - * @since 3.23.0 + * Dirty flag for checking if model matrix needs to be updated on GPU. * - * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. - * @param {integer} unit - Texture unit to which the texture needs to be bound. + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty + * @type {boolean} + * @since 3.0.0 */ - pushBatch: function (texture, unit) + modelMatrixDirty: false, + + /** + * Dirty flag for checking if view matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + viewMatrixDirty: false, + + /** + * Dirty flag for checking if projection matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + projectionMatrixDirty: false, + + /** + * Model matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + modelMatrix: null, + + /** + * View matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + viewMatrix: null, + + /** + * Projection matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + projectionMatrix: null, + + /** + * Initializes MVP matrices with an identity matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit + * @since 3.0.0 + */ + mvpInit: function () { - if (unit === 0) - { - this.batches.push({ - first: this.vertexCount, - texture: texture, - textures: [] - }); - } - else - { - var textures = []; - - textures[unit - 1] = texture; - - this.batches.push({ - first: this.vertexCount, - texture: null, - textures: textures - }); - } + this.modelMatrixDirty = true; + this.viewMatrixDirty = true; + this.projectionMatrixDirty = true; + + this.modelMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.viewMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.projectionMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + return this; }, /** - * Uploads the vertex data and emits a draw call for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#flush - * @since 3.23.0 - * - * @return {this} This WebGLPipeline instance. + * If dirty flags are set then the matrices are uploaded to the GPU. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate + * @since 3.0.0 */ - flush: function () + mvpUpdate: function () { - if (this.flushLocked) + var program = this.program; + + if (this.modelMatrixDirty) { - return this; + this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); + this.modelMatrixDirty = false; + } + + if (this.viewMatrixDirty) + { + this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); + this.viewMatrixDirty = false; } - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - var renderer = this.renderer; - - var batches = this.batches; - var batchCount = batches.length; - var batchVertexCount = 0; - var batch = null; - var batchNext; - var textureIndex; - var nTexture; - - if (batchCount === 0 || vertexCount === 0) + if (this.projectionMatrixDirty) { - this.flushLocked = false; - - return this; + this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + this.projectionMatrixDirty = false; } - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + return this; + }, - // Process the TEXTURE BATCHES + /** + * Loads an identity matrix to the model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity + * @since 3.0.0 + */ + modelIdentity: function () + { + var modelMatrix = this.modelMatrix; + + modelMatrix[0] = 1; + modelMatrix[1] = 0; + modelMatrix[2] = 0; + modelMatrix[3] = 0; + modelMatrix[4] = 0; + modelMatrix[5] = 1; + modelMatrix[6] = 0; + modelMatrix[7] = 0; + modelMatrix[8] = 0; + modelMatrix[9] = 0; + modelMatrix[10] = 1; + modelMatrix[11] = 0; + modelMatrix[12] = 0; + modelMatrix[13] = 0; + modelMatrix[14] = 0; + modelMatrix[15] = 1; - for (var index = 0; index < batchCount - 1; index++) - { - batch = batches[index]; - batchNext = batches[index + 1]; + this.modelMatrixDirty = true; + + return this; + }, - // Multi-texture check (for non-zero texture units) - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; + /** + * Scale model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelScale: function (x, y, z) + { + var modelMatrix = this.modelMatrix; - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } + modelMatrix[0] = modelMatrix[0] * x; + modelMatrix[1] = modelMatrix[1] * x; + modelMatrix[2] = modelMatrix[2] * x; + modelMatrix[3] = modelMatrix[3] * x; + modelMatrix[4] = modelMatrix[4] * y; + modelMatrix[5] = modelMatrix[5] * y; + modelMatrix[6] = modelMatrix[6] * y; + modelMatrix[7] = modelMatrix[7] * y; + modelMatrix[8] = modelMatrix[8] * z; + modelMatrix[9] = modelMatrix[9] * z; + modelMatrix[10] = modelMatrix[10] * z; + modelMatrix[11] = modelMatrix[11] * z; + + this.modelMatrixDirty = true; - gl.activeTexture(gl.TEXTURE0); - } + return this; + }, - batchVertexCount = batchNext.first - batch.first; + /** + * Translate model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelTranslate: function (x, y, z) + { + var modelMatrix = this.modelMatrix; - // Bail out if texture property is null (i.e. if a texture unit > 0) - if (batch.texture === null || batchVertexCount <= 0) - { - continue; - } + modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; + modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; + modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; + modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; - renderer.setTexture2D(batch.texture, 0, false); + this.modelMatrixDirty = true; - gl.drawArrays(topology, batch.first, batchVertexCount); - } + return this; + }, - // Left over data - batch = batches[batchCount - 1]; + /** + * Rotates the model matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateX: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; - // Multi-texture check (for non-zero texture units) + modelMatrix[4] = a10 * c + a20 * s; + modelMatrix[5] = a11 * c + a21 * s; + modelMatrix[6] = a12 * c + a22 * s; + modelMatrix[7] = a13 * c + a23 * s; + modelMatrix[8] = a20 * c - a10 * s; + modelMatrix[9] = a21 * c - a11 * s; + modelMatrix[10] = a22 * c - a12 * s; + modelMatrix[11] = a23 * c - a13 * s; - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; + this.modelMatrixDirty = true; - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } + return this; + }, - gl.activeTexture(gl.TEXTURE0); - } + /** + * Rotates the model matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateY: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; - batchVertexCount = vertexCount - batch.first; + modelMatrix[0] = a00 * c - a20 * s; + modelMatrix[1] = a01 * c - a21 * s; + modelMatrix[2] = a02 * c - a22 * s; + modelMatrix[3] = a03 * c - a23 * s; + modelMatrix[8] = a00 * s + a20 * c; + modelMatrix[9] = a01 * s + a21 * c; + modelMatrix[10] = a02 * s + a22 * c; + modelMatrix[11] = a03 * s + a23 * c; - if (batch.texture && batchVertexCount > 0) - { - renderer.setTexture2D(batch.texture, 0, false); + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateZ: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; - gl.drawArrays(topology, batch.first, batchVertexCount); - } + modelMatrix[0] = a00 * c + a10 * s; + modelMatrix[1] = a01 * c + a11 * s; + modelMatrix[2] = a02 * c + a12 * s; + modelMatrix[3] = a03 * c + a13 * s; + modelMatrix[4] = a10 * c - a00 * s; + modelMatrix[5] = a11 * c - a01 * s; + modelMatrix[6] = a12 * c - a02 * s; + modelMatrix[7] = a13 * c - a03 * s; - this.vertexCount = 0; + this.modelMatrixDirty = true; - batches.length = 0; + return this; + }, - this.flushLocked = false; + /** + * Loads identity matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + viewIdentity: function () + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = 1; + viewMatrix[1] = 0; + viewMatrix[2] = 0; + viewMatrix[3] = 0; + viewMatrix[4] = 0; + viewMatrix[5] = 1; + viewMatrix[6] = 0; + viewMatrix[7] = 0; + viewMatrix[8] = 0; + viewMatrix[9] = 0; + viewMatrix[10] = 1; + viewMatrix[11] = 0; + viewMatrix[12] = 0; + viewMatrix[13] = 0; + viewMatrix[14] = 0; + viewMatrix[15] = 1; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Scales view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewScale: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = viewMatrix[0] * x; + viewMatrix[1] = viewMatrix[1] * x; + viewMatrix[2] = viewMatrix[2] * x; + viewMatrix[3] = viewMatrix[3] * x; + viewMatrix[4] = viewMatrix[4] * y; + viewMatrix[5] = viewMatrix[5] * y; + viewMatrix[6] = viewMatrix[6] * y; + viewMatrix[7] = viewMatrix[7] * y; + viewMatrix[8] = viewMatrix[8] * z; + viewMatrix[9] = viewMatrix[9] * z; + viewMatrix[10] = viewMatrix[10] * z; + viewMatrix[11] = viewMatrix[11] * z; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Translates view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewTranslate: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; + viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; + viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; + viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateX: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[4] = a10 * c + a20 * s; + viewMatrix[5] = a11 * c + a21 * s; + viewMatrix[6] = a12 * c + a22 * s; + viewMatrix[7] = a13 * c + a23 * s; + viewMatrix[8] = a20 * c - a10 * s; + viewMatrix[9] = a21 * c - a11 * s; + viewMatrix[10] = a22 * c - a12 * s; + viewMatrix[11] = a23 * c - a13 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateY: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[0] = a00 * c - a20 * s; + viewMatrix[1] = a01 * c - a21 * s; + viewMatrix[2] = a02 * c - a22 * s; + viewMatrix[3] = a03 * c - a23 * s; + viewMatrix[8] = a00 * s + a20 * c; + viewMatrix[9] = a01 * s + a21 * c; + viewMatrix[10] = a02 * s + a22 * c; + viewMatrix[11] = a03 * s + a23 * c; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateZ: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + + viewMatrix[0] = a00 * c + a10 * s; + viewMatrix[1] = a01 * c + a11 * s; + viewMatrix[2] = a02 * c + a12 * s; + viewMatrix[3] = a03 * c + a13 * s; + viewMatrix[4] = a10 * c - a00 * s; + viewMatrix[5] = a11 * c - a01 * s; + viewMatrix[6] = a12 * c - a02 * s; + viewMatrix[7] = a13 * c - a03 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D + * @since 3.0.0 + * + * @param {Float32Array} matrix2D - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad2D: function (matrix2D) + { + var vm = this.viewMatrix; + + vm[0] = matrix2D[0]; + vm[1] = matrix2D[1]; + vm[2] = 0.0; + vm[3] = 0.0; + vm[4] = matrix2D[2]; + vm[5] = matrix2D[3]; + vm[6] = 0.0; + vm[7] = 0.0; + vm[8] = matrix2D[4]; + vm[9] = matrix2D[5]; + vm[10] = 1.0; + vm[11] = 0.0; + vm[12] = 0.0; + vm[13] = 0.0; + vm[14] = 0.0; + vm[15] = 1.0; + + this.viewMatrixDirty = true; + + return this; + }, + + + /** + * Copies a 4x4 matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad + * @since 3.0.0 + * + * @param {Float32Array} matrix - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad: function (matrix) + { + var vm = this.viewMatrix; + + vm[0] = matrix[0]; + vm[1] = matrix[1]; + vm[2] = matrix[2]; + vm[3] = matrix[3]; + vm[4] = matrix[4]; + vm[5] = matrix[5]; + vm[6] = matrix[6]; + vm[7] = matrix[7]; + vm[8] = matrix[8]; + vm[9] = matrix[9]; + vm[10] = matrix[10]; + vm[11] = matrix[11]; + vm[12] = matrix[12]; + vm[13] = matrix[13]; + vm[14] = matrix[14]; + vm[15] = matrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads identity matrix into the projection matrix. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + projIdentity: function () + { + var projectionMatrix = this.projectionMatrix; + + projectionMatrix[0] = 1; + projectionMatrix[1] = 0; + projectionMatrix[2] = 0; + projectionMatrix[3] = 0; + projectionMatrix[4] = 0; + projectionMatrix[5] = 1; + projectionMatrix[6] = 0; + projectionMatrix[7] = 0; + projectionMatrix[8] = 0; + projectionMatrix[9] = 0; + projectionMatrix[10] = 1; + projectionMatrix[11] = 0; + projectionMatrix[12] = 0; + projectionMatrix[13] = 0; + projectionMatrix[14] = 0; + projectionMatrix[15] = 1; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up an orthographic projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho + * @since 3.0.0 + * + * @param {number} left - The left value. + * @param {number} right - The right value. + * @param {number} bottom - The bottom value. + * @param {number} top - The top value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projOrtho: function (left, right, bottom, top, near, far) + { + var projectionMatrix = this.projectionMatrix; + var leftRight = 1.0 / (left - right); + var bottomTop = 1.0 / (bottom - top); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = -2.0 * leftRight; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = -2.0 * bottomTop; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = 2.0 * nearFar; + projectionMatrix[11] = 0.0; + projectionMatrix[12] = (left + right) * leftRight; + projectionMatrix[13] = (top + bottom) * bottomTop; + projectionMatrix[14] = (far + near) * nearFar; + projectionMatrix[15] = 1.0; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up a perspective projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp + * @since 3.0.0 + * + * @param {number} fovY - The fov value. + * @param {number} aspectRatio - The aspectRatio value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projPersp: function (fovY, aspectRatio, near, far) + { + var projectionMatrix = this.projectionMatrix; + var fov = 1.0 / Math.tan(fovY / 2.0); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = fov / aspectRatio; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = fov; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = (far + near) * nearFar; + projectionMatrix[11] = -1.0; + projectionMatrix[12] = 0.0; + projectionMatrix[13] = 0.0; + projectionMatrix[14] = (2.0 * far * near) * nearFar; + projectionMatrix[15] = 0.0; + + this.projectionMatrixDirty = true; return this; } +}; -}); - -module.exports = TextureTintStripPipeline; +module.exports = ModelViewProjection; /***/ }), +/* 507 */, /* 508 */, /* 509 */, /* 510 */, -/* 511 */, -/* 512 */ +/* 511 */ /***/ (function(module, exports) { var g; @@ -118200,9 +116154,10 @@ module.exports = g; /***/ }), -/* 513 */ +/* 512 */ /***/ (function(module, exports, __webpack_require__) { +__webpack_require__(513); __webpack_require__(514); __webpack_require__(515); __webpack_require__(516); @@ -118210,11 +116165,10 @@ __webpack_require__(517); __webpack_require__(518); __webpack_require__(519); __webpack_require__(520); -__webpack_require__(521); /***/ }), -/* 514 */ +/* 513 */ /***/ (function(module, exports) { /** @@ -118254,7 +116208,7 @@ if (!Array.prototype.forEach) /***/ }), -/* 515 */ +/* 514 */ /***/ (function(module, exports) { /** @@ -118270,7 +116224,7 @@ if (!Array.isArray) /***/ }), -/* 516 */ +/* 515 */ /***/ (function(module, exports) { /* Copyright 2013 Chris Wilson @@ -118457,7 +116411,7 @@ BiquadFilterNode.type and OscillatorNode.type. /***/ }), -/* 517 */ +/* 516 */ /***/ (function(module, exports) { /** @@ -118472,7 +116426,7 @@ if (!window.console) /***/ }), -/* 518 */ +/* 517 */ /***/ (function(module, exports) { // ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc @@ -118484,7 +116438,7 @@ if (!Math.trunc) { /***/ }), -/* 519 */ +/* 518 */ /***/ (function(module, exports) { /** @@ -118521,7 +116475,7 @@ if (!Math.trunc) { /***/ }), -/* 520 */ +/* 519 */ /***/ (function(module, exports) { // References: @@ -118578,7 +116532,7 @@ if (!window.cancelAnimationFrame) /***/ }), -/* 521 */ +/* 520 */ /***/ (function(module, exports) { /** @@ -118631,7 +116585,7 @@ if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'o /***/ }), -/* 522 */ +/* 521 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118640,7 +116594,7 @@ if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'o * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var QuickSet = __webpack_require__(237); +var QuickSet = __webpack_require__(239); /** * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. @@ -118679,7 +116633,7 @@ module.exports = AlignTo; /***/ }), -/* 523 */ +/* 522 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118720,7 +116674,7 @@ module.exports = Angle; /***/ }), -/* 524 */ +/* 523 */ /***/ (function(module, exports) { /** @@ -118759,7 +116713,7 @@ module.exports = Call; /***/ }), -/* 525 */ +/* 524 */ /***/ (function(module, exports) { /** @@ -118817,7 +116771,7 @@ module.exports = GetFirst; /***/ }), -/* 526 */ +/* 525 */ /***/ (function(module, exports) { /** @@ -118875,7 +116829,7 @@ module.exports = GetLast; /***/ }), -/* 527 */ +/* 526 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118884,11 +116838,11 @@ module.exports = GetLast; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AlignIn = __webpack_require__(250); -var CONST = __webpack_require__(102); +var AlignIn = __webpack_require__(252); +var CONST = __webpack_require__(106); var GetFastValue = __webpack_require__(2); var NOOP = __webpack_require__(1); -var Zone = __webpack_require__(106); +var Zone = __webpack_require__(110); var tempZone = new Zone({ sys: { queueDepthSort: NOOP, events: { once: NOOP } } }, 0, 0, 1, 1); @@ -118974,7 +116928,7 @@ module.exports = GridAlign; /***/ }), -/* 528 */ +/* 527 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118983,7 +116937,7 @@ module.exports = GridAlign; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); // bitmask flag for GameObject.renderMask var _FLAG = 2; // 0010 @@ -119269,7 +117223,7 @@ module.exports = Alpha; /***/ }), -/* 529 */ +/* 528 */ /***/ (function(module, exports) { /** @@ -119296,7 +117250,7 @@ module.exports = 'add'; /***/ }), -/* 530 */ +/* 529 */ /***/ (function(module, exports) { /** @@ -119324,7 +117278,7 @@ module.exports = 'complete'; /***/ }), -/* 531 */ +/* 530 */ /***/ (function(module, exports) { /** @@ -119351,7 +117305,7 @@ module.exports = 'repeat'; /***/ }), -/* 532 */ +/* 531 */ /***/ (function(module, exports) { /** @@ -119379,7 +117333,7 @@ module.exports = 'restart'; /***/ }), -/* 533 */ +/* 532 */ /***/ (function(module, exports) { /** @@ -119407,7 +117361,7 @@ module.exports = 'start'; /***/ }), -/* 534 */ +/* 533 */ /***/ (function(module, exports) { /** @@ -119431,7 +117385,7 @@ module.exports = 'pauseall'; /***/ }), -/* 535 */ +/* 534 */ /***/ (function(module, exports) { /** @@ -119455,7 +117409,7 @@ module.exports = 'remove'; /***/ }), -/* 536 */ +/* 535 */ /***/ (function(module, exports) { /** @@ -119478,7 +117432,7 @@ module.exports = 'resumeall'; /***/ }), -/* 537 */ +/* 536 */ /***/ (function(module, exports) { /** @@ -119507,7 +117461,7 @@ module.exports = 'animationcomplete'; /***/ }), -/* 538 */ +/* 537 */ /***/ (function(module, exports) { /** @@ -119535,7 +117489,7 @@ module.exports = 'animationcomplete-'; /***/ }), -/* 539 */ +/* 538 */ /***/ (function(module, exports) { /** @@ -119564,7 +117518,7 @@ module.exports = 'animationrepeat-'; /***/ }), -/* 540 */ +/* 539 */ /***/ (function(module, exports) { /** @@ -119592,7 +117546,7 @@ module.exports = 'animationrestart-'; /***/ }), -/* 541 */ +/* 540 */ /***/ (function(module, exports) { /** @@ -119620,7 +117574,7 @@ module.exports = 'animationstart-'; /***/ }), -/* 542 */ +/* 541 */ /***/ (function(module, exports) { /** @@ -119649,7 +117603,7 @@ module.exports = 'animationupdate-'; /***/ }), -/* 543 */ +/* 542 */ /***/ (function(module, exports) { /** @@ -119679,7 +117633,7 @@ module.exports = 'animationrepeat'; /***/ }), -/* 544 */ +/* 543 */ /***/ (function(module, exports) { /** @@ -119708,7 +117662,7 @@ module.exports = 'animationrestart'; /***/ }), -/* 545 */ +/* 544 */ /***/ (function(module, exports) { /** @@ -119737,7 +117691,7 @@ module.exports = 'animationstart'; /***/ }), -/* 546 */ +/* 545 */ /***/ (function(module, exports) { /** @@ -119767,7 +117721,7 @@ module.exports = 'animationupdate'; /***/ }), -/* 547 */ +/* 546 */ /***/ (function(module, exports) { /** @@ -119916,7 +117870,7 @@ module.exports = ComputedSize; /***/ }), -/* 548 */ +/* 547 */ /***/ (function(module, exports) { /** @@ -120041,7 +117995,7 @@ module.exports = Crop; /***/ }), -/* 549 */ +/* 548 */ /***/ (function(module, exports) { /** @@ -120205,7 +118159,7 @@ module.exports = Flip; /***/ }), -/* 550 */ +/* 549 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -120214,8 +118168,8 @@ module.exports = Flip; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var RotateAround = __webpack_require__(271); +var Rectangle = __webpack_require__(11); +var RotateAround = __webpack_require__(273); var Vector2 = __webpack_require__(3); /** @@ -120564,7 +118518,7 @@ module.exports = GetBounds; /***/ }), -/* 551 */ +/* 550 */ /***/ (function(module, exports) { /** @@ -120587,7 +118541,7 @@ module.exports = 'blur'; /***/ }), -/* 552 */ +/* 551 */ /***/ (function(module, exports) { /** @@ -120609,7 +118563,7 @@ module.exports = 'boot'; /***/ }), -/* 553 */ +/* 552 */ /***/ (function(module, exports) { /** @@ -120632,7 +118586,7 @@ module.exports = 'contextlost'; /***/ }), -/* 554 */ +/* 553 */ /***/ (function(module, exports) { /** @@ -120655,7 +118609,7 @@ module.exports = 'contextrestored'; /***/ }), -/* 555 */ +/* 554 */ /***/ (function(module, exports) { /** @@ -120678,7 +118632,7 @@ module.exports = 'destroy'; /***/ }), -/* 556 */ +/* 555 */ /***/ (function(module, exports) { /** @@ -120700,7 +118654,7 @@ module.exports = 'focus'; /***/ }), -/* 557 */ +/* 556 */ /***/ (function(module, exports) { /** @@ -120726,7 +118680,7 @@ module.exports = 'hidden'; /***/ }), -/* 558 */ +/* 557 */ /***/ (function(module, exports) { /** @@ -120747,7 +118701,7 @@ module.exports = 'pause'; /***/ }), -/* 559 */ +/* 558 */ /***/ (function(module, exports) { /** @@ -120773,7 +118727,7 @@ module.exports = 'postrender'; /***/ }), -/* 560 */ +/* 559 */ /***/ (function(module, exports) { /** @@ -120798,7 +118752,7 @@ module.exports = 'poststep'; /***/ }), -/* 561 */ +/* 560 */ /***/ (function(module, exports) { /** @@ -120823,7 +118777,7 @@ module.exports = 'prerender'; /***/ }), -/* 562 */ +/* 561 */ /***/ (function(module, exports) { /** @@ -120848,7 +118802,7 @@ module.exports = 'prestep'; /***/ }), -/* 563 */ +/* 562 */ /***/ (function(module, exports) { /** @@ -120870,7 +118824,7 @@ module.exports = 'ready'; /***/ }), -/* 564 */ +/* 563 */ /***/ (function(module, exports) { /** @@ -120891,7 +118845,7 @@ module.exports = 'resume'; /***/ }), -/* 565 */ +/* 564 */ /***/ (function(module, exports) { /** @@ -120916,7 +118870,7 @@ module.exports = 'step'; /***/ }), -/* 566 */ +/* 565 */ /***/ (function(module, exports) { /** @@ -120940,7 +118894,7 @@ module.exports = 'visible'; /***/ }), -/* 567 */ +/* 566 */ /***/ (function(module, exports) { /** @@ -121143,7 +119097,7 @@ module.exports = Origin; /***/ }), -/* 568 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -121153,9 +119107,9 @@ module.exports = Origin; */ var DegToRad = __webpack_require__(35); -var GetBoolean = __webpack_require__(86); +var GetBoolean = __webpack_require__(88); var GetValue = __webpack_require__(6); -var TWEEN_CONST = __webpack_require__(87); +var TWEEN_CONST = __webpack_require__(89); var Vector2 = __webpack_require__(3); /** @@ -121258,7 +119212,7 @@ var PathFollower = { * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path at a time. * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config] - Settings for the PathFollower. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ setPath: function (path, config) { @@ -121290,7 +119244,7 @@ var PathFollower = { * @param {boolean} value - Whether the PathFollower should automatically rotate to point in the direction of the Path. * @param {number} [offset=0] - Rotation offset in degrees. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ setRotateToPath: function (value, offset) { @@ -121329,7 +119283,7 @@ var PathFollower = { * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config={}] - The duration of the follow, or a PathFollower config object. * @param {number} [startAt=0] - Optional start position of the follow, between 0 and 1. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ startFollow: function (config, startAt) { @@ -121419,7 +119373,7 @@ var PathFollower = { * @method Phaser.GameObjects.Components.PathFollower#pauseFollow * @since 3.3.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ pauseFollow: function () { @@ -121441,7 +119395,7 @@ var PathFollower = { * @method Phaser.GameObjects.Components.PathFollower#resumeFollow * @since 3.3.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ resumeFollow: function () { @@ -121463,7 +119417,7 @@ var PathFollower = { * @method Phaser.GameObjects.Components.PathFollower#stopFollow * @since 3.3.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ stopFollow: function () { @@ -121494,7 +119448,7 @@ var PathFollower = { var tweenData = tween.data[0]; var pathVector = this.pathVector; - if (tweenData.state === TWEEN_CONST.COMPLETE) + if (tweenData.state !== TWEEN_CONST.COMPLETE) { this.path.getPoint(1, pathVector); @@ -121549,7 +119503,7 @@ module.exports = PathFollower; /***/ }), -/* 569 */ +/* 568 */ /***/ (function(module, exports) { /** @@ -121736,7 +119690,7 @@ module.exports = Size; /***/ }), -/* 570 */ +/* 569 */ /***/ (function(module, exports) { /** @@ -121866,7 +119820,7 @@ module.exports = Texture; /***/ }), -/* 571 */ +/* 570 */ /***/ (function(module, exports) { /** @@ -122074,7 +120028,7 @@ module.exports = TextureCrop; /***/ }), -/* 572 */ +/* 571 */ /***/ (function(module, exports) { /** @@ -122414,7 +120368,7 @@ module.exports = Tint; /***/ }), -/* 573 */ +/* 572 */ /***/ (function(module, exports) { /** @@ -122446,7 +120400,7 @@ module.exports = 'changedata'; /***/ }), -/* 574 */ +/* 573 */ /***/ (function(module, exports) { /** @@ -122476,7 +120430,7 @@ module.exports = 'changedata-'; /***/ }), -/* 575 */ +/* 574 */ /***/ (function(module, exports) { /** @@ -122504,7 +120458,7 @@ module.exports = 'removedata'; /***/ }), -/* 576 */ +/* 575 */ /***/ (function(module, exports) { /** @@ -122532,7 +120486,7 @@ module.exports = 'setdata'; /***/ }), -/* 577 */ +/* 576 */ /***/ (function(module, exports) { /** @@ -122557,7 +120511,7 @@ module.exports = 'destroy'; /***/ }), -/* 578 */ +/* 577 */ /***/ (function(module, exports) { /** @@ -122589,7 +120543,7 @@ module.exports = 'complete'; /***/ }), -/* 579 */ +/* 578 */ /***/ (function(module, exports) { /** @@ -122618,7 +120572,7 @@ module.exports = 'created'; /***/ }), -/* 580 */ +/* 579 */ /***/ (function(module, exports) { /** @@ -122644,7 +120598,7 @@ module.exports = 'error'; /***/ }), -/* 581 */ +/* 580 */ /***/ (function(module, exports) { /** @@ -122676,7 +120630,7 @@ module.exports = 'loop'; /***/ }), -/* 582 */ +/* 581 */ /***/ (function(module, exports) { /** @@ -122704,7 +120658,7 @@ module.exports = 'play'; /***/ }), -/* 583 */ +/* 582 */ /***/ (function(module, exports) { /** @@ -122729,7 +120683,7 @@ module.exports = 'seeked'; /***/ }), -/* 584 */ +/* 583 */ /***/ (function(module, exports) { /** @@ -122755,7 +120709,7 @@ module.exports = 'seeking'; /***/ }), -/* 585 */ +/* 584 */ /***/ (function(module, exports) { /** @@ -122781,7 +120735,7 @@ module.exports = 'stop'; /***/ }), -/* 586 */ +/* 585 */ /***/ (function(module, exports) { /** @@ -122807,7 +120761,7 @@ module.exports = 'timeout'; /***/ }), -/* 587 */ +/* 586 */ /***/ (function(module, exports) { /** @@ -122833,7 +120787,7 @@ module.exports = 'unlocked'; /***/ }), -/* 588 */ +/* 587 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -122874,7 +120828,7 @@ module.exports = IncAlpha; /***/ }), -/* 589 */ +/* 588 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -122915,7 +120869,7 @@ module.exports = IncX; /***/ }), -/* 590 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -122962,7 +120916,7 @@ module.exports = IncXY; /***/ }), -/* 591 */ +/* 590 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123003,7 +120957,7 @@ module.exports = IncY; /***/ }), -/* 592 */ +/* 591 */ /***/ (function(module, exports) { /** @@ -123052,7 +121006,7 @@ module.exports = PlaceOnCircle; /***/ }), -/* 593 */ +/* 592 */ /***/ (function(module, exports) { /** @@ -123104,7 +121058,7 @@ module.exports = PlaceOnEllipse; /***/ }), -/* 594 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123113,7 +121067,7 @@ module.exports = PlaceOnEllipse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetPoints = __webpack_require__(147); +var GetPoints = __webpack_require__(150); /** * Positions an array of Game Objects on evenly spaced points of a Line. @@ -123148,7 +121102,7 @@ module.exports = PlaceOnLine; /***/ }), -/* 595 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123157,9 +121111,9 @@ module.exports = PlaceOnLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MarchingAnts = __webpack_require__(280); -var RotateLeft = __webpack_require__(281); -var RotateRight = __webpack_require__(282); +var MarchingAnts = __webpack_require__(282); +var RotateLeft = __webpack_require__(283); +var RotateRight = __webpack_require__(284); /** * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. @@ -123206,7 +121160,7 @@ module.exports = PlaceOnRectangle; /***/ }), -/* 596 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123215,7 +121169,7 @@ module.exports = PlaceOnRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BresenhamPoints = __webpack_require__(283); +var BresenhamPoints = __webpack_require__(285); /** * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. @@ -123267,7 +121221,7 @@ module.exports = PlaceOnTriangle; /***/ }), -/* 597 */ +/* 596 */ /***/ (function(module, exports) { /** @@ -123304,7 +121258,7 @@ module.exports = PlayAnimation; /***/ }), -/* 598 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123313,7 +121267,7 @@ module.exports = PlayAnimation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(144); +var Random = __webpack_require__(147); /** * Takes an array of Game Objects and positions them at random locations within the Circle. @@ -123344,7 +121298,7 @@ module.exports = RandomCircle; /***/ }), -/* 599 */ +/* 598 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123353,7 +121307,7 @@ module.exports = RandomCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(151); +var Random = __webpack_require__(154); /** * Takes an array of Game Objects and positions them at random locations within the Ellipse. @@ -123384,7 +121338,7 @@ module.exports = RandomEllipse; /***/ }), -/* 600 */ +/* 599 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123393,7 +121347,7 @@ module.exports = RandomEllipse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(148); +var Random = __webpack_require__(151); /** * Takes an array of Game Objects and positions them at random locations on the Line. @@ -123424,7 +121378,7 @@ module.exports = RandomLine; /***/ }), -/* 601 */ +/* 600 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123433,7 +121387,7 @@ module.exports = RandomLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(149); +var Random = __webpack_require__(152); /** * Takes an array of Game Objects and positions them at random locations within the Rectangle. @@ -123462,7 +121416,7 @@ module.exports = RandomRectangle; /***/ }), -/* 602 */ +/* 601 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123471,7 +121425,7 @@ module.exports = RandomRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(152); +var Random = __webpack_require__(155); /** * Takes an array of Game Objects and positions them at random locations within the Triangle. @@ -123502,7 +121456,7 @@ module.exports = RandomTriangle; /***/ }), -/* 603 */ +/* 602 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123543,7 +121497,7 @@ module.exports = Rotate; /***/ }), -/* 604 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123552,7 +121506,7 @@ module.exports = Rotate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundDistance = __webpack_require__(153); +var RotateAroundDistance = __webpack_require__(156); var DistanceBetween = __webpack_require__(53); /** @@ -123589,7 +121543,7 @@ module.exports = RotateAround; /***/ }), -/* 605 */ +/* 604 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123598,7 +121552,7 @@ module.exports = RotateAround; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MathRotateAroundDistance = __webpack_require__(153); +var MathRotateAroundDistance = __webpack_require__(156); /** * Rotates an array of Game Objects around a point by the given angle and distance. @@ -123638,7 +121592,7 @@ module.exports = RotateAroundDistance; /***/ }), -/* 606 */ +/* 605 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123679,7 +121633,7 @@ module.exports = ScaleX; /***/ }), -/* 607 */ +/* 606 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123726,7 +121680,7 @@ module.exports = ScaleXY; /***/ }), -/* 608 */ +/* 607 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123767,7 +121721,7 @@ module.exports = ScaleY; /***/ }), -/* 609 */ +/* 608 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123776,7 +121730,7 @@ module.exports = ScaleY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `alpha` @@ -123808,7 +121762,7 @@ module.exports = SetAlpha; /***/ }), -/* 610 */ +/* 609 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123817,7 +121771,7 @@ module.exports = SetAlpha; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `blendMode` @@ -123848,7 +121802,7 @@ module.exports = SetBlendMode; /***/ }), -/* 611 */ +/* 610 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123857,7 +121811,7 @@ module.exports = SetBlendMode; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `depth` @@ -123889,7 +121843,7 @@ module.exports = SetDepth; /***/ }), -/* 612 */ +/* 611 */ /***/ (function(module, exports) { /** @@ -123928,7 +121882,7 @@ module.exports = SetHitArea; /***/ }), -/* 613 */ +/* 612 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123937,7 +121891,7 @@ module.exports = SetHitArea; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` @@ -123975,7 +121929,7 @@ module.exports = SetOrigin; /***/ }), -/* 614 */ +/* 613 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123984,7 +121938,7 @@ module.exports = SetOrigin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `rotation` @@ -124016,7 +121970,7 @@ module.exports = SetRotation; /***/ }), -/* 615 */ +/* 614 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124025,7 +121979,7 @@ module.exports = SetRotation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` @@ -124063,7 +122017,7 @@ module.exports = SetScale; /***/ }), -/* 616 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124072,7 +122026,7 @@ module.exports = SetScale; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scaleX` @@ -124104,7 +122058,7 @@ module.exports = SetScaleX; /***/ }), -/* 617 */ +/* 616 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124113,7 +122067,7 @@ module.exports = SetScaleX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scaleY` @@ -124145,7 +122099,7 @@ module.exports = SetScaleY; /***/ }), -/* 618 */ +/* 617 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124154,7 +122108,7 @@ module.exports = SetScaleY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` @@ -124192,7 +122146,7 @@ module.exports = SetScrollFactor; /***/ }), -/* 619 */ +/* 618 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124201,7 +122155,7 @@ module.exports = SetScrollFactor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` @@ -124233,7 +122187,7 @@ module.exports = SetScrollFactorX; /***/ }), -/* 620 */ +/* 619 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124242,7 +122196,7 @@ module.exports = SetScrollFactorX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` @@ -124274,7 +122228,7 @@ module.exports = SetScrollFactorY; /***/ }), -/* 621 */ +/* 620 */ /***/ (function(module, exports) { /** @@ -124313,7 +122267,7 @@ module.exports = SetTint; /***/ }), -/* 622 */ +/* 621 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124322,7 +122276,7 @@ module.exports = SetTint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `visible` @@ -124351,7 +122305,7 @@ module.exports = SetVisible; /***/ }), -/* 623 */ +/* 622 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124360,7 +122314,7 @@ module.exports = SetVisible; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `x` @@ -124392,7 +122346,7 @@ module.exports = SetX; /***/ }), -/* 624 */ +/* 623 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124401,7 +122355,7 @@ module.exports = SetX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` @@ -124439,7 +122393,7 @@ module.exports = SetXY; /***/ }), -/* 625 */ +/* 624 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124448,7 +122402,7 @@ module.exports = SetXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `y` @@ -124480,7 +122434,7 @@ module.exports = SetY; /***/ }), -/* 626 */ +/* 625 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124610,7 +122564,7 @@ module.exports = ShiftPosition; /***/ }), -/* 627 */ +/* 626 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124619,7 +122573,7 @@ module.exports = ShiftPosition; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayShuffle = __webpack_require__(110); +var ArrayShuffle = __webpack_require__(114); /** * Shuffles the array in place. The shuffled array is both modified and returned. @@ -124643,7 +122597,7 @@ module.exports = Shuffle; /***/ }), -/* 628 */ +/* 627 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124652,7 +122606,7 @@ module.exports = Shuffle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MathSmootherStep = __webpack_require__(154); +var MathSmootherStep = __webpack_require__(157); /** * Smootherstep is a sigmoid-like interpolation and clamping function. @@ -124701,7 +122655,7 @@ module.exports = SmootherStep; /***/ }), -/* 629 */ +/* 628 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124710,7 +122664,7 @@ module.exports = SmootherStep; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MathSmoothStep = __webpack_require__(155); +var MathSmoothStep = __webpack_require__(158); /** * Smoothstep is a sigmoid-like interpolation and clamping function. @@ -124759,7 +122713,7 @@ module.exports = SmoothStep; /***/ }), -/* 630 */ +/* 629 */ /***/ (function(module, exports) { /** @@ -124822,7 +122776,7 @@ module.exports = Spread; /***/ }), -/* 631 */ +/* 630 */ /***/ (function(module, exports) { /** @@ -124858,7 +122812,7 @@ module.exports = ToggleVisible; /***/ }), -/* 632 */ +/* 631 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124907,7 +122861,7 @@ module.exports = WrapInRectangle; /***/ }), -/* 633 */ +/* 632 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124922,16 +122876,16 @@ module.exports = WrapInRectangle; module.exports = { - Animation: __webpack_require__(145), - AnimationFrame: __webpack_require__(266), - AnimationManager: __webpack_require__(284), - Events: __webpack_require__(107) + Animation: __webpack_require__(148), + AnimationFrame: __webpack_require__(268), + AnimationManager: __webpack_require__(286), + Events: __webpack_require__(111) }; /***/ }), -/* 634 */ +/* 633 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124946,15 +122900,15 @@ module.exports = { module.exports = { - BaseCache: __webpack_require__(285), - CacheManager: __webpack_require__(287), - Events: __webpack_require__(286) + BaseCache: __webpack_require__(287), + CacheManager: __webpack_require__(289), + Events: __webpack_require__(288) }; /***/ }), -/* 635 */ +/* 634 */ /***/ (function(module, exports) { /** @@ -124979,7 +122933,7 @@ module.exports = 'add'; /***/ }), -/* 636 */ +/* 635 */ /***/ (function(module, exports) { /** @@ -125004,7 +122958,7 @@ module.exports = 'remove'; /***/ }), -/* 637 */ +/* 636 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -125023,14 +122977,14 @@ module.exports = 'remove'; module.exports = { - Controls: __webpack_require__(638), - Scene2D: __webpack_require__(641) + Controls: __webpack_require__(637), + Scene2D: __webpack_require__(640) }; /***/ }), -/* 638 */ +/* 637 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -125045,14 +122999,14 @@ module.exports = { module.exports = { - FixedKeyControl: __webpack_require__(639), - SmoothedKeyControl: __webpack_require__(640) + FixedKeyControl: __webpack_require__(638), + SmoothedKeyControl: __webpack_require__(639) }; /***/ }), -/* 639 */ +/* 638 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -125358,7 +123312,7 @@ module.exports = FixedKeyControl; /***/ }), -/* 640 */ +/* 639 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -125841,7 +123795,7 @@ module.exports = SmoothedKeyControl; /***/ }), -/* 641 */ +/* 640 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -125856,17 +123810,17 @@ module.exports = SmoothedKeyControl; module.exports = { - Camera: __webpack_require__(288), - BaseCamera: __webpack_require__(89), - CameraManager: __webpack_require__(694), - Effects: __webpack_require__(296), + Camera: __webpack_require__(290), + BaseCamera: __webpack_require__(91), + CameraManager: __webpack_require__(693), + Effects: __webpack_require__(298), Events: __webpack_require__(48) }; /***/ }), -/* 642 */ +/* 641 */ /***/ (function(module, exports) { /** @@ -125889,7 +123843,7 @@ module.exports = 'cameradestroy'; /***/ }), -/* 643 */ +/* 642 */ /***/ (function(module, exports) { /** @@ -125915,7 +123869,7 @@ module.exports = 'camerafadeincomplete'; /***/ }), -/* 644 */ +/* 643 */ /***/ (function(module, exports) { /** @@ -125945,7 +123899,7 @@ module.exports = 'camerafadeinstart'; /***/ }), -/* 645 */ +/* 644 */ /***/ (function(module, exports) { /** @@ -125971,7 +123925,7 @@ module.exports = 'camerafadeoutcomplete'; /***/ }), -/* 646 */ +/* 645 */ /***/ (function(module, exports) { /** @@ -126001,7 +123955,7 @@ module.exports = 'camerafadeoutstart'; /***/ }), -/* 647 */ +/* 646 */ /***/ (function(module, exports) { /** @@ -126025,7 +123979,7 @@ module.exports = 'cameraflashcomplete'; /***/ }), -/* 648 */ +/* 647 */ /***/ (function(module, exports) { /** @@ -126053,7 +124007,7 @@ module.exports = 'cameraflashstart'; /***/ }), -/* 649 */ +/* 648 */ /***/ (function(module, exports) { /** @@ -126077,7 +124031,7 @@ module.exports = 'camerapancomplete'; /***/ }), -/* 650 */ +/* 649 */ /***/ (function(module, exports) { /** @@ -126104,7 +124058,7 @@ module.exports = 'camerapanstart'; /***/ }), -/* 651 */ +/* 650 */ /***/ (function(module, exports) { /** @@ -126130,7 +124084,7 @@ module.exports = 'postrender'; /***/ }), -/* 652 */ +/* 651 */ /***/ (function(module, exports) { /** @@ -126156,7 +124110,7 @@ module.exports = 'prerender'; /***/ }), -/* 653 */ +/* 652 */ /***/ (function(module, exports) { /** @@ -126180,7 +124134,7 @@ module.exports = 'camerashakecomplete'; /***/ }), -/* 654 */ +/* 653 */ /***/ (function(module, exports) { /** @@ -126206,7 +124160,7 @@ module.exports = 'camerashakestart'; /***/ }), -/* 655 */ +/* 654 */ /***/ (function(module, exports) { /** @@ -126230,7 +124184,7 @@ module.exports = 'camerazoomcomplete'; /***/ }), -/* 656 */ +/* 655 */ /***/ (function(module, exports) { /** @@ -126256,7 +124210,7 @@ module.exports = 'camerazoomstart'; /***/ }), -/* 657 */ +/* 656 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -126265,7 +124219,7 @@ module.exports = 'camerazoomstart'; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Events = __webpack_require__(48); @@ -126644,7 +124598,7 @@ module.exports = Fade; /***/ }), -/* 658 */ +/* 657 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -126653,7 +124607,7 @@ module.exports = Fade; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Events = __webpack_require__(48); @@ -126995,7 +124949,7 @@ module.exports = Flash; /***/ }), -/* 659 */ +/* 658 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -127004,9 +124958,9 @@ module.exports = Flash; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var EaseMap = __webpack_require__(163); +var EaseMap = __webpack_require__(166); var Events = __webpack_require__(48); var Vector2 = __webpack_require__(3); @@ -127320,7 +125274,7 @@ module.exports = Pan; /***/ }), -/* 660 */ +/* 659 */ /***/ (function(module, exports) { /** @@ -127351,7 +125305,7 @@ module.exports = In; /***/ }), -/* 661 */ +/* 660 */ /***/ (function(module, exports) { /** @@ -127382,7 +125336,7 @@ module.exports = Out; /***/ }), -/* 662 */ +/* 661 */ /***/ (function(module, exports) { /** @@ -127422,7 +125376,7 @@ module.exports = InOut; /***/ }), -/* 663 */ +/* 662 */ /***/ (function(module, exports) { /** @@ -127467,7 +125421,7 @@ module.exports = In; /***/ }), -/* 664 */ +/* 663 */ /***/ (function(module, exports) { /** @@ -127510,7 +125464,7 @@ module.exports = Out; /***/ }), -/* 665 */ +/* 664 */ /***/ (function(module, exports) { /** @@ -127574,7 +125528,7 @@ module.exports = InOut; /***/ }), -/* 666 */ +/* 665 */ /***/ (function(module, exports) { /** @@ -127602,7 +125556,7 @@ module.exports = In; /***/ }), -/* 667 */ +/* 666 */ /***/ (function(module, exports) { /** @@ -127630,7 +125584,7 @@ module.exports = Out; /***/ }), -/* 668 */ +/* 667 */ /***/ (function(module, exports) { /** @@ -127665,7 +125619,7 @@ module.exports = InOut; /***/ }), -/* 669 */ +/* 668 */ /***/ (function(module, exports) { /** @@ -127693,7 +125647,7 @@ module.exports = In; /***/ }), -/* 670 */ +/* 669 */ /***/ (function(module, exports) { /** @@ -127721,7 +125675,7 @@ module.exports = Out; /***/ }), -/* 671 */ +/* 670 */ /***/ (function(module, exports) { /** @@ -127756,7 +125710,7 @@ module.exports = InOut; /***/ }), -/* 672 */ +/* 671 */ /***/ (function(module, exports) { /** @@ -127811,7 +125765,7 @@ module.exports = In; /***/ }), -/* 673 */ +/* 672 */ /***/ (function(module, exports) { /** @@ -127866,7 +125820,7 @@ module.exports = Out; /***/ }), -/* 674 */ +/* 673 */ /***/ (function(module, exports) { /** @@ -127928,7 +125882,7 @@ module.exports = InOut; /***/ }), -/* 675 */ +/* 674 */ /***/ (function(module, exports) { /** @@ -127956,7 +125910,7 @@ module.exports = In; /***/ }), -/* 676 */ +/* 675 */ /***/ (function(module, exports) { /** @@ -127984,7 +125938,7 @@ module.exports = Out; /***/ }), -/* 677 */ +/* 676 */ /***/ (function(module, exports) { /** @@ -128019,7 +125973,7 @@ module.exports = InOut; /***/ }), -/* 678 */ +/* 677 */ /***/ (function(module, exports) { /** @@ -128047,7 +126001,7 @@ module.exports = Linear; /***/ }), -/* 679 */ +/* 678 */ /***/ (function(module, exports) { /** @@ -128075,7 +126029,7 @@ module.exports = In; /***/ }), -/* 680 */ +/* 679 */ /***/ (function(module, exports) { /** @@ -128103,7 +126057,7 @@ module.exports = Out; /***/ }), -/* 681 */ +/* 680 */ /***/ (function(module, exports) { /** @@ -128138,7 +126092,7 @@ module.exports = InOut; /***/ }), -/* 682 */ +/* 681 */ /***/ (function(module, exports) { /** @@ -128166,7 +126120,7 @@ module.exports = In; /***/ }), -/* 683 */ +/* 682 */ /***/ (function(module, exports) { /** @@ -128194,7 +126148,7 @@ module.exports = Out; /***/ }), -/* 684 */ +/* 683 */ /***/ (function(module, exports) { /** @@ -128229,7 +126183,7 @@ module.exports = InOut; /***/ }), -/* 685 */ +/* 684 */ /***/ (function(module, exports) { /** @@ -128257,7 +126211,7 @@ module.exports = In; /***/ }), -/* 686 */ +/* 685 */ /***/ (function(module, exports) { /** @@ -128285,7 +126239,7 @@ module.exports = Out; /***/ }), -/* 687 */ +/* 686 */ /***/ (function(module, exports) { /** @@ -128320,7 +126274,7 @@ module.exports = InOut; /***/ }), -/* 688 */ +/* 687 */ /***/ (function(module, exports) { /** @@ -128359,7 +126313,7 @@ module.exports = In; /***/ }), -/* 689 */ +/* 688 */ /***/ (function(module, exports) { /** @@ -128398,7 +126352,7 @@ module.exports = Out; /***/ }), -/* 690 */ +/* 689 */ /***/ (function(module, exports) { /** @@ -128437,7 +126391,7 @@ module.exports = InOut; /***/ }), -/* 691 */ +/* 690 */ /***/ (function(module, exports) { /** @@ -128479,7 +126433,7 @@ module.exports = Stepped; /***/ }), -/* 692 */ +/* 691 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128488,7 +126442,7 @@ module.exports = Stepped; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Events = __webpack_require__(48); var Vector2 = __webpack_require__(3); @@ -128798,7 +126752,7 @@ module.exports = Shake; /***/ }), -/* 693 */ +/* 692 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128807,9 +126761,9 @@ module.exports = Shake; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var EaseMap = __webpack_require__(163); +var EaseMap = __webpack_require__(166); var Events = __webpack_require__(48); /** @@ -129091,7 +127045,7 @@ module.exports = Zoom; /***/ }), -/* 694 */ +/* 693 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129100,13 +127054,13 @@ module.exports = Zoom; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Camera = __webpack_require__(288); +var Camera = __webpack_require__(290); var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); +var PluginCache = __webpack_require__(23); var RectangleContains = __webpack_require__(47); -var ScaleEvents = __webpack_require__(90); -var SceneEvents = __webpack_require__(22); +var ScaleEvents = __webpack_require__(92); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -129839,7 +127793,7 @@ module.exports = CameraManager; /***/ }), -/* 695 */ +/* 694 */ /***/ (function(module, exports) { /** @@ -129858,7 +127812,7 @@ module.exports = 'enterfullscreen'; /***/ }), -/* 696 */ +/* 695 */ /***/ (function(module, exports) { /** @@ -129877,7 +127831,7 @@ module.exports = 'fullscreenfailed'; /***/ }), -/* 697 */ +/* 696 */ /***/ (function(module, exports) { /** @@ -129896,7 +127850,7 @@ module.exports = 'fullscreenunsupported'; /***/ }), -/* 698 */ +/* 697 */ /***/ (function(module, exports) { /** @@ -129916,7 +127870,7 @@ module.exports = 'leavefullscreen'; /***/ }), -/* 699 */ +/* 698 */ /***/ (function(module, exports) { /** @@ -129937,7 +127891,7 @@ module.exports = 'orientationchange'; /***/ }), -/* 700 */ +/* 699 */ /***/ (function(module, exports) { /** @@ -129968,7 +127922,7 @@ module.exports = 'resize'; /***/ }), -/* 701 */ +/* 700 */ /***/ (function(module, exports) { /** @@ -129993,7 +127947,7 @@ module.exports = 'boot'; /***/ }), -/* 702 */ +/* 701 */ /***/ (function(module, exports) { /** @@ -130022,7 +127976,7 @@ module.exports = 'create'; /***/ }), -/* 703 */ +/* 702 */ /***/ (function(module, exports) { /** @@ -130049,7 +128003,7 @@ module.exports = 'destroy'; /***/ }), -/* 704 */ +/* 703 */ /***/ (function(module, exports) { /** @@ -130076,7 +128030,7 @@ module.exports = 'pause'; /***/ }), -/* 705 */ +/* 704 */ /***/ (function(module, exports) { /** @@ -130113,7 +128067,7 @@ module.exports = 'postupdate'; /***/ }), -/* 706 */ +/* 705 */ /***/ (function(module, exports) { /** @@ -130150,7 +128104,7 @@ module.exports = 'preupdate'; /***/ }), -/* 707 */ +/* 706 */ /***/ (function(module, exports) { /** @@ -130178,7 +128132,7 @@ module.exports = 'ready'; /***/ }), -/* 708 */ +/* 707 */ /***/ (function(module, exports) { /** @@ -130214,7 +128168,7 @@ module.exports = 'render'; /***/ }), -/* 709 */ +/* 708 */ /***/ (function(module, exports) { /** @@ -130241,7 +128195,7 @@ module.exports = 'resume'; /***/ }), -/* 710 */ +/* 709 */ /***/ (function(module, exports) { /** @@ -130271,7 +128225,7 @@ module.exports = 'shutdown'; /***/ }), -/* 711 */ +/* 710 */ /***/ (function(module, exports) { /** @@ -130298,7 +128252,7 @@ module.exports = 'sleep'; /***/ }), -/* 712 */ +/* 711 */ /***/ (function(module, exports) { /** @@ -130323,7 +128277,7 @@ module.exports = 'start'; /***/ }), -/* 713 */ +/* 712 */ /***/ (function(module, exports) { /** @@ -130359,7 +128313,7 @@ module.exports = 'transitioncomplete'; /***/ }), -/* 714 */ +/* 713 */ /***/ (function(module, exports) { /** @@ -130396,7 +128350,7 @@ module.exports = 'transitioninit'; /***/ }), -/* 715 */ +/* 714 */ /***/ (function(module, exports) { /** @@ -130430,7 +128384,7 @@ module.exports = 'transitionout'; /***/ }), -/* 716 */ +/* 715 */ /***/ (function(module, exports) { /** @@ -130470,7 +128424,7 @@ module.exports = 'transitionstart'; /***/ }), -/* 717 */ +/* 716 */ /***/ (function(module, exports) { /** @@ -130505,7 +128459,7 @@ module.exports = 'transitionwake'; /***/ }), -/* 718 */ +/* 717 */ /***/ (function(module, exports) { /** @@ -130542,7 +128496,7 @@ module.exports = 'update'; /***/ }), -/* 719 */ +/* 718 */ /***/ (function(module, exports) { /** @@ -130569,7 +128523,7 @@ module.exports = 'wake'; /***/ }), -/* 720 */ +/* 719 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130584,18 +128538,18 @@ module.exports = 'wake'; module.exports = { - Config: __webpack_require__(309), - CreateRenderer: __webpack_require__(333), - DebugHeader: __webpack_require__(337), - Events: __webpack_require__(19), - TimeStep: __webpack_require__(338), - VisibilityHandler: __webpack_require__(340) + Config: __webpack_require__(311), + CreateRenderer: __webpack_require__(334), + DebugHeader: __webpack_require__(336), + Events: __webpack_require__(18), + TimeStep: __webpack_require__(337), + VisibilityHandler: __webpack_require__(339) }; /***/ }), -/* 721 */ +/* 720 */ /***/ (function(module, exports) { // shim for using process in browser @@ -130785,7 +128739,7 @@ process.umask = function() { return 0; }; /***/ }), -/* 722 */ +/* 721 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130794,7 +128748,7 @@ process.umask = function() { return 0; }; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Browser = __webpack_require__(113); +var Browser = __webpack_require__(117); /** * Determines the input support of the browser running this Phaser Game instance. @@ -130860,7 +128814,7 @@ module.exports = init(); /***/ }), -/* 723 */ +/* 722 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130869,7 +128823,7 @@ module.exports = init(); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Browser = __webpack_require__(113); +var Browser = __webpack_require__(117); /** * Determines the audio playback capabilities of the device running this Phaser Game instance. @@ -130985,7 +128939,7 @@ module.exports = init(); /***/ }), -/* 724 */ +/* 723 */ /***/ (function(module, exports) { /** @@ -131072,7 +129026,7 @@ module.exports = init(); /***/ }), -/* 725 */ +/* 724 */ /***/ (function(module, exports) { /** @@ -131176,7 +129130,7 @@ module.exports = init(); /***/ }), -/* 726 */ +/* 725 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131191,23 +129145,23 @@ module.exports = init(); module.exports = { - Between: __webpack_require__(312), - BetweenPoints: __webpack_require__(727), - BetweenPointsY: __webpack_require__(728), - BetweenY: __webpack_require__(729), - CounterClockwise: __webpack_require__(730), - Normalize: __webpack_require__(313), - Reverse: __webpack_require__(731), - RotateTo: __webpack_require__(732), - ShortestBetween: __webpack_require__(733), - Wrap: __webpack_require__(230), - WrapDegrees: __webpack_require__(231) + Between: __webpack_require__(314), + BetweenPoints: __webpack_require__(726), + BetweenPointsY: __webpack_require__(727), + BetweenY: __webpack_require__(728), + CounterClockwise: __webpack_require__(729), + Normalize: __webpack_require__(315), + Reverse: __webpack_require__(730), + RotateTo: __webpack_require__(731), + ShortestBetween: __webpack_require__(732), + Wrap: __webpack_require__(232), + WrapDegrees: __webpack_require__(233) }; /***/ }), -/* 727 */ +/* 726 */ /***/ (function(module, exports) { /** @@ -131224,8 +129178,8 @@ module.exports = { * @function Phaser.Math.Angle.BetweenPoints * @since 3.0.0 * - * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. - * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. + * @param {(Phaser.Geom.Point|object)} point1 - The first point. + * @param {(Phaser.Geom.Point|object)} point2 - The second point. * * @return {number} The angle in radians. */ @@ -131238,7 +129192,7 @@ module.exports = BetweenPoints; /***/ }), -/* 728 */ +/* 727 */ /***/ (function(module, exports) { /** @@ -131256,8 +129210,8 @@ module.exports = BetweenPoints; * @function Phaser.Math.Angle.BetweenPointsY * @since 3.0.0 * - * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. - * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. + * @param {(Phaser.Geom.Point|object)} point1 - The first point. + * @param {(Phaser.Geom.Point|object)} point2 - The second point. * * @return {number} The angle in radians. */ @@ -131270,7 +129224,7 @@ module.exports = BetweenPointsY; /***/ }), -/* 729 */ +/* 728 */ /***/ (function(module, exports) { /** @@ -131304,7 +129258,7 @@ module.exports = BetweenY; /***/ }), -/* 730 */ +/* 729 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131313,7 +129267,7 @@ module.exports = BetweenY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); +var CONST = __webpack_require__(13); /** * Takes an angle in Phasers default clockwise format and converts it so that @@ -131349,7 +129303,7 @@ module.exports = CounterClockwise; /***/ }), -/* 731 */ +/* 730 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131358,7 +129312,7 @@ module.exports = CounterClockwise; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Normalize = __webpack_require__(313); +var Normalize = __webpack_require__(315); /** * Reverse the given angle. @@ -131379,7 +129333,7 @@ module.exports = Reverse; /***/ }), -/* 732 */ +/* 731 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131388,7 +129342,7 @@ module.exports = Reverse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); /** * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. @@ -131446,7 +129400,7 @@ module.exports = RotateTo; /***/ }), -/* 733 */ +/* 732 */ /***/ (function(module, exports) { /** @@ -131495,7 +129449,7 @@ module.exports = ShortestBetween; /***/ }), -/* 734 */ +/* 733 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131511,16 +129465,48 @@ module.exports = ShortestBetween; module.exports = { Between: __webpack_require__(53), - BetweenPoints: __webpack_require__(314), + BetweenPoints: __webpack_require__(734), BetweenPointsSquared: __webpack_require__(735), Chebyshev: __webpack_require__(736), Power: __webpack_require__(737), Snake: __webpack_require__(738), - Squared: __webpack_require__(315) + Squared: __webpack_require__(316) }; +/***/ }), +/* 734 */ +/***/ (function(module, exports) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two points. + * + * @function Phaser.Math.Distance.BetweenPoints + * @since 3.22.0 + * + * @param {Phaser.Types.Math.Vector2Like} a - The first point. + * @param {Phaser.Types.Math.Vector2Like} b - The second point. + * + * @return {number} The distance between the points. + */ +var DistanceBetweenPoints = function (a, b) +{ + var dx = a.x - b.x; + var dy = a.y - b.y; + + return Math.sqrt(dx * dx + dy * dy); +}; + +module.exports = DistanceBetweenPoints; + + /***/ }), /* 735 */ /***/ (function(module, exports) { @@ -131671,18 +129657,18 @@ module.exports = SnakeDistance; module.exports = { - Back: __webpack_require__(297), - Bounce: __webpack_require__(298), - Circular: __webpack_require__(299), - Cubic: __webpack_require__(300), - Elastic: __webpack_require__(301), - Expo: __webpack_require__(302), - Linear: __webpack_require__(303), - Quadratic: __webpack_require__(304), - Quartic: __webpack_require__(305), - Quintic: __webpack_require__(306), - Sine: __webpack_require__(307), - Stepped: __webpack_require__(308) + Back: __webpack_require__(299), + Bounce: __webpack_require__(300), + Circular: __webpack_require__(301), + Cubic: __webpack_require__(302), + Elastic: __webpack_require__(303), + Expo: __webpack_require__(304), + Linear: __webpack_require__(305), + Quadratic: __webpack_require__(306), + Quartic: __webpack_require__(307), + Quintic: __webpack_require__(308), + Sine: __webpack_require__(309), + Stepped: __webpack_require__(310) }; @@ -131704,10 +129690,10 @@ module.exports = { module.exports = { Ceil: __webpack_require__(741), - Equal: __webpack_require__(140), + Equal: __webpack_require__(144), Floor: __webpack_require__(742), - GreaterThan: __webpack_require__(316), - LessThan: __webpack_require__(317) + GreaterThan: __webpack_require__(317), + LessThan: __webpack_require__(318) }; @@ -131792,10 +129778,10 @@ module.exports = { Bezier: __webpack_require__(744), CatmullRom: __webpack_require__(745), - CubicBezier: __webpack_require__(320), + CubicBezier: __webpack_require__(321), Linear: __webpack_require__(746), - QuadraticBezier: __webpack_require__(321), - SmoothStep: __webpack_require__(322), + QuadraticBezier: __webpack_require__(322), + SmoothStep: __webpack_require__(323), SmootherStep: __webpack_require__(747) }; @@ -131811,7 +129797,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bernstein = __webpack_require__(318); +var Bernstein = __webpack_require__(319); /** * A bezier interpolation method. @@ -131850,7 +129836,7 @@ module.exports = BezierInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CatmullRom = __webpack_require__(166); +var CatmullRom = __webpack_require__(169); /** * A Catmull-Rom interpolation method. @@ -131907,7 +129893,7 @@ module.exports = CatmullRomInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Linear = __webpack_require__(111); +var Linear = __webpack_require__(115); /** * A linear interpolation method. @@ -131954,7 +129940,7 @@ module.exports = LinearInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SmootherStep = __webpack_require__(154); +var SmootherStep = __webpack_require__(157); /** * A Smoother Step interpolation method. @@ -131993,8 +129979,8 @@ module.exports = SmootherStepInterpolation; module.exports = { - GetNext: __webpack_require__(323), - IsSize: __webpack_require__(114), + GetNext: __webpack_require__(324), + IsSize: __webpack_require__(118), IsValue: __webpack_require__(749) }; @@ -132044,8 +130030,8 @@ module.exports = IsValuePowerOfTwo; module.exports = { - Ceil: __webpack_require__(324), - Floor: __webpack_require__(91), + Ceil: __webpack_require__(325), + Floor: __webpack_require__(93), To: __webpack_require__(751) }; @@ -133273,9 +131259,9 @@ module.exports = Within; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Vector3 = __webpack_require__(169); -var Matrix4 = __webpack_require__(331); -var Quaternion = __webpack_require__(332); +var Vector3 = __webpack_require__(172); +var Matrix4 = __webpack_require__(332); +var Quaternion = __webpack_require__(333); var tmpMat4 = new Matrix4(); var tmpQuat = new Quaternion(); @@ -133559,6 +131545,85 @@ module.exports = [ /***/ }), /* 779 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_TEXTURE_TINT_FS', + '', + 'precision mediump float;', + '', + 'uniform sampler2D uMainSampler;', + '', + 'varying vec2 outTexCoord;', + 'varying float outTintEffect;', + 'varying vec4 outTint;', + '', + 'void main()', + '{', + ' vec4 texture = texture2D(uMainSampler, outTexCoord);', + ' vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);', + ' vec4 color = texture;', + '', + ' if (outTintEffect == 0.0)', + ' {', + ' // Multiply texture tint', + ' color = texture * texel;', + ' }', + ' else if (outTintEffect == 1.0)', + ' {', + ' // Solid color + texture alpha', + ' color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);', + ' color.a = texture.a * texel.a;', + ' }', + ' else if (outTintEffect == 2.0)', + ' {', + ' // Solid color, no texture', + ' color = texel;', + ' }', + '', + ' gl_FragColor = color;', + '}', + '' +].join('\n'); + + +/***/ }), +/* 780 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_TEXTURE_TINT_VS', + '', + 'precision mediump float;', + '', + 'uniform mat4 uProjectionMatrix;', + 'uniform mat4 uViewMatrix;', + 'uniform mat4 uModelMatrix;', + '', + 'attribute vec2 inPosition;', + 'attribute vec2 inTexCoord;', + 'attribute float inTintEffect;', + 'attribute vec4 inTint;', + '', + 'varying vec2 outTexCoord;', + 'varying float outTintEffect;', + 'varying vec4 outTint;', + '', + 'void main ()', + '{', + ' gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);', + '', + ' outTexCoord = inTexCoord;', + ' outTint = inTint;', + ' outTintEffect = inTintEffect;', + '}', + '', + '' +].join('\n'); + + +/***/ }), +/* 781 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -133573,14 +131638,14 @@ module.exports = [ module.exports = { - GenerateTexture: __webpack_require__(341), - Palettes: __webpack_require__(780) + GenerateTexture: __webpack_require__(340), + Palettes: __webpack_require__(782) }; /***/ }), -/* 780 */ +/* 782 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -133595,17 +131660,17 @@ module.exports = { module.exports = { - ARNE16: __webpack_require__(342), - C64: __webpack_require__(781), - CGA: __webpack_require__(782), - JMP: __webpack_require__(783), - MSX: __webpack_require__(784) + ARNE16: __webpack_require__(341), + C64: __webpack_require__(783), + CGA: __webpack_require__(784), + JMP: __webpack_require__(785), + MSX: __webpack_require__(786) }; /***/ }), -/* 781 */ +/* 783 */ /***/ (function(module, exports) { /** @@ -133643,7 +131708,7 @@ module.exports = { /***/ }), -/* 782 */ +/* 784 */ /***/ (function(module, exports) { /** @@ -133681,7 +131746,7 @@ module.exports = { /***/ }), -/* 783 */ +/* 785 */ /***/ (function(module, exports) { /** @@ -133719,7 +131784,7 @@ module.exports = { /***/ }), -/* 784 */ +/* 786 */ /***/ (function(module, exports) { /** @@ -133757,7 +131822,7 @@ module.exports = { /***/ }), -/* 785 */ +/* 787 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -133771,19 +131836,19 @@ module.exports = { */ module.exports = { - Path: __webpack_require__(786), + Path: __webpack_require__(788), - CubicBezier: __webpack_require__(343), - Curve: __webpack_require__(79), - Ellipse: __webpack_require__(344), - Line: __webpack_require__(345), - QuadraticBezier: __webpack_require__(346), - Spline: __webpack_require__(347) + CubicBezier: __webpack_require__(342), + Curve: __webpack_require__(80), + Ellipse: __webpack_require__(343), + Line: __webpack_require__(344), + QuadraticBezier: __webpack_require__(345), + Spline: __webpack_require__(346) }; /***/ }), -/* 786 */ +/* 788 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -133795,16 +131860,16 @@ module.exports = { // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var CubicBezierCurve = __webpack_require__(343); -var EllipseCurve = __webpack_require__(344); +var CubicBezierCurve = __webpack_require__(342); +var EllipseCurve = __webpack_require__(343); var GameObjectFactory = __webpack_require__(5); -var LineCurve = __webpack_require__(345); -var MovePathTo = __webpack_require__(787); -var QuadraticBezierCurve = __webpack_require__(346); -var Rectangle = __webpack_require__(13); -var SplineCurve = __webpack_require__(347); +var LineCurve = __webpack_require__(344); +var MovePathTo = __webpack_require__(789); +var QuadraticBezierCurve = __webpack_require__(345); +var Rectangle = __webpack_require__(11); +var SplineCurve = __webpack_require__(346); var Vector2 = __webpack_require__(3); -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); /** * @classdesc @@ -134632,7 +132697,7 @@ module.exports = Path; /***/ }), -/* 787 */ +/* 789 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -134772,7 +132837,7 @@ module.exports = MoveTo; /***/ }), -/* 788 */ +/* 790 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -134787,15 +132852,15 @@ module.exports = MoveTo; module.exports = { - DataManager: __webpack_require__(109), - DataManagerPlugin: __webpack_require__(789), - Events: __webpack_require__(279) + DataManager: __webpack_require__(113), + DataManagerPlugin: __webpack_require__(791), + Events: __webpack_require__(281) }; /***/ }), -/* 789 */ +/* 791 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -134805,9 +132870,9 @@ module.exports = { */ var Class = __webpack_require__(0); -var DataManager = __webpack_require__(109); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var DataManager = __webpack_require__(113); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -134922,7 +132987,7 @@ module.exports = DataManagerPlugin; /***/ }), -/* 790 */ +/* 792 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -134937,72 +133002,12 @@ module.exports = DataManagerPlugin; module.exports = { - Align: __webpack_require__(791), - BaseShader: __webpack_require__(348), - Bounds: __webpack_require__(794), - Canvas: __webpack_require__(797), - Color: __webpack_require__(349), - Masks: __webpack_require__(806) - -}; - - -/***/ }), -/* 791 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = __webpack_require__(102); -var Extend = __webpack_require__(18); - -/** - * @namespace Phaser.Display.Align - */ - -var Align = { - - In: __webpack_require__(792), - To: __webpack_require__(793) - -}; - -// Merge in the consts -Align = Extend(false, Align, CONST); - -module.exports = Align; - - -/***/ }), -/* 792 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Align.In - */ - -module.exports = { - - BottomCenter: __webpack_require__(251), - BottomLeft: __webpack_require__(252), - BottomRight: __webpack_require__(253), - Center: __webpack_require__(254), - LeftCenter: __webpack_require__(256), - QuickSet: __webpack_require__(250), - RightCenter: __webpack_require__(257), - TopCenter: __webpack_require__(258), - TopLeft: __webpack_require__(259), - TopRight: __webpack_require__(260) + Align: __webpack_require__(793), + BaseShader: __webpack_require__(347), + Bounds: __webpack_require__(796), + Canvas: __webpack_require__(799), + Color: __webpack_require__(348), + Masks: __webpack_require__(808) }; @@ -135011,6 +133016,66 @@ module.exports = { /* 793 */ /***/ (function(module, exports, __webpack_require__) { +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(106); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Display.Align + */ + +var Align = { + + In: __webpack_require__(794), + To: __webpack_require__(795) + +}; + +// Merge in the consts +Align = Extend(false, Align, CONST); + +module.exports = Align; + + +/***/ }), +/* 794 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Align.In + */ + +module.exports = { + + BottomCenter: __webpack_require__(253), + BottomLeft: __webpack_require__(254), + BottomRight: __webpack_require__(255), + Center: __webpack_require__(256), + LeftCenter: __webpack_require__(258), + QuickSet: __webpack_require__(252), + RightCenter: __webpack_require__(259), + TopCenter: __webpack_require__(260), + TopLeft: __webpack_require__(261), + TopRight: __webpack_require__(262) + +}; + + +/***/ }), +/* 795 */ +/***/ (function(module, exports, __webpack_require__) { + /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -135023,25 +133088,25 @@ module.exports = { module.exports = { - BottomCenter: __webpack_require__(238), - BottomLeft: __webpack_require__(239), - BottomRight: __webpack_require__(240), - LeftBottom: __webpack_require__(241), - LeftCenter: __webpack_require__(242), - LeftTop: __webpack_require__(243), - QuickSet: __webpack_require__(237), - RightBottom: __webpack_require__(244), - RightCenter: __webpack_require__(245), - RightTop: __webpack_require__(246), - TopCenter: __webpack_require__(247), - TopLeft: __webpack_require__(248), - TopRight: __webpack_require__(249) + BottomCenter: __webpack_require__(240), + BottomLeft: __webpack_require__(241), + BottomRight: __webpack_require__(242), + LeftBottom: __webpack_require__(243), + LeftCenter: __webpack_require__(244), + LeftTop: __webpack_require__(245), + QuickSet: __webpack_require__(239), + RightBottom: __webpack_require__(246), + RightCenter: __webpack_require__(247), + RightTop: __webpack_require__(248), + TopCenter: __webpack_require__(249), + TopLeft: __webpack_require__(250), + TopRight: __webpack_require__(251) }; /***/ }), -/* 794 */ +/* 796 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135056,18 +133121,18 @@ module.exports = { module.exports = { - CenterOn: __webpack_require__(255), + CenterOn: __webpack_require__(257), GetBottom: __webpack_require__(38), - GetCenterX: __webpack_require__(74), - GetCenterY: __webpack_require__(76), + GetCenterX: __webpack_require__(75), + GetCenterY: __webpack_require__(77), GetLeft: __webpack_require__(40), - GetOffsetX: __webpack_require__(795), - GetOffsetY: __webpack_require__(796), + GetOffsetX: __webpack_require__(797), + GetOffsetY: __webpack_require__(798), GetRight: __webpack_require__(42), GetTop: __webpack_require__(45), SetBottom: __webpack_require__(44), - SetCenterX: __webpack_require__(75), - SetCenterY: __webpack_require__(77), + SetCenterX: __webpack_require__(76), + SetCenterY: __webpack_require__(78), SetLeft: __webpack_require__(41), SetRight: __webpack_require__(43), SetTop: __webpack_require__(39) @@ -135076,7 +133141,7 @@ module.exports = { /***/ }), -/* 795 */ +/* 797 */ /***/ (function(module, exports) { /** @@ -135106,7 +133171,7 @@ module.exports = GetOffsetX; /***/ }), -/* 796 */ +/* 798 */ /***/ (function(module, exports) { /** @@ -135136,7 +133201,7 @@ module.exports = GetOffsetY; /***/ }), -/* 797 */ +/* 799 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135151,17 +133216,17 @@ module.exports = GetOffsetY; module.exports = { - CanvasInterpolation: __webpack_require__(334), - CanvasPool: __webpack_require__(27), - Smoothing: __webpack_require__(161), - TouchAction: __webpack_require__(798), - UserSelect: __webpack_require__(799) + CanvasInterpolation: __webpack_require__(335), + CanvasPool: __webpack_require__(26), + Smoothing: __webpack_require__(164), + TouchAction: __webpack_require__(800), + UserSelect: __webpack_require__(801) }; /***/ }), -/* 798 */ +/* 800 */ /***/ (function(module, exports) { /** @@ -135196,7 +133261,7 @@ module.exports = TouchAction; /***/ }), -/* 799 */ +/* 801 */ /***/ (function(module, exports) { /** @@ -135243,7 +133308,7 @@ module.exports = UserSelect; /***/ }), -/* 800 */ +/* 802 */ /***/ (function(module, exports) { /** @@ -135283,7 +133348,7 @@ module.exports = ColorToRGBA; /***/ }), -/* 801 */ +/* 803 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135292,8 +133357,8 @@ module.exports = ColorToRGBA; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); -var HueToComponent = __webpack_require__(351); +var Color = __webpack_require__(33); +var HueToComponent = __webpack_require__(350); /** * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. @@ -135333,7 +133398,7 @@ module.exports = HSLToColor; /***/ }), -/* 802 */ +/* 804 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135342,7 +133407,7 @@ module.exports = HSLToColor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HSVToRGB = __webpack_require__(160); +var HSVToRGB = __webpack_require__(163); /** * Get HSV color wheel values in an array which will be 360 elements in size. @@ -135374,7 +133439,7 @@ module.exports = HSVColorWheel; /***/ }), -/* 803 */ +/* 805 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135383,7 +133448,7 @@ module.exports = HSVColorWheel; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Linear = __webpack_require__(111); +var Linear = __webpack_require__(115); /** * @namespace Phaser.Display.Color.Interpolate @@ -135482,7 +133547,7 @@ module.exports = { /***/ }), -/* 804 */ +/* 806 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135491,8 +133556,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Between = __webpack_require__(167); -var Color = __webpack_require__(32); +var Between = __webpack_require__(170); +var Color = __webpack_require__(33); /** * Creates a new Color object where the r, g, and b values have been set to random values @@ -135518,7 +133583,7 @@ module.exports = RandomRGB; /***/ }), -/* 805 */ +/* 807 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135527,7 +133592,7 @@ module.exports = RandomRGB; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ComponentToHex = __webpack_require__(350); +var ComponentToHex = __webpack_require__(349); /** * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. @@ -135562,7 +133627,7 @@ module.exports = RGBToString; /***/ }), -/* 806 */ +/* 808 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135577,14 +133642,14 @@ module.exports = RGBToString; module.exports = { - BitmapMask: __webpack_require__(273), - GeometryMask: __webpack_require__(274) + BitmapMask: __webpack_require__(275), + GeometryMask: __webpack_require__(276) }; /***/ }), -/* 807 */ +/* 809 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135599,13 +133664,13 @@ module.exports = { var Dom = { - AddToDOM: __webpack_require__(116), - DOMContentLoaded: __webpack_require__(352), - GetScreenOrientation: __webpack_require__(353), - GetTarget: __webpack_require__(358), - ParseXML: __webpack_require__(359), - RemoveFromDOM: __webpack_require__(173), - RequestAnimationFrame: __webpack_require__(339) + AddToDOM: __webpack_require__(120), + DOMContentLoaded: __webpack_require__(351), + GetScreenOrientation: __webpack_require__(352), + GetTarget: __webpack_require__(357), + ParseXML: __webpack_require__(358), + RemoveFromDOM: __webpack_require__(176), + RequestAnimationFrame: __webpack_require__(338) }; @@ -135613,7 +133678,7 @@ module.exports = Dom; /***/ }), -/* 808 */ +/* 810 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135626,11 +133691,11 @@ module.exports = Dom; * @namespace Phaser.Events */ -module.exports = { EventEmitter: __webpack_require__(809) }; +module.exports = { EventEmitter: __webpack_require__(811) }; /***/ }), -/* 809 */ +/* 811 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135640,8 +133705,8 @@ module.exports = { EventEmitter: __webpack_require__(809) }; */ var Class = __webpack_require__(0); -var EE = __webpack_require__(11); -var PluginCache = __webpack_require__(24); +var EE = __webpack_require__(9); +var PluginCache = __webpack_require__(23); /** * @classdesc @@ -135814,7 +133879,7 @@ module.exports = EventEmitter; /***/ }), -/* 810 */ +/* 812 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135823,33 +133888,33 @@ module.exports = EventEmitter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AddToDOM = __webpack_require__(116); -var AnimationManager = __webpack_require__(284); -var CacheManager = __webpack_require__(287); -var CanvasPool = __webpack_require__(27); +var AddToDOM = __webpack_require__(120); +var AnimationManager = __webpack_require__(286); +var CacheManager = __webpack_require__(289); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); -var Config = __webpack_require__(309); -var CreateDOMContainer = __webpack_require__(811); -var CreateRenderer = __webpack_require__(333); -var DataManager = __webpack_require__(109); -var DebugHeader = __webpack_require__(337); -var Device = __webpack_require__(310); -var DOMContentLoaded = __webpack_require__(352); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(19); -var InputManager = __webpack_require__(360); -var PluginCache = __webpack_require__(24); -var PluginManager = __webpack_require__(365); -var ScaleManager = __webpack_require__(366); -var SceneManager = __webpack_require__(368); -var TextureEvents = __webpack_require__(115); -var TextureManager = __webpack_require__(371); -var TimeStep = __webpack_require__(338); -var VisibilityHandler = __webpack_require__(340); +var Config = __webpack_require__(311); +var CreateDOMContainer = __webpack_require__(813); +var CreateRenderer = __webpack_require__(334); +var DataManager = __webpack_require__(113); +var DebugHeader = __webpack_require__(336); +var Device = __webpack_require__(312); +var DOMContentLoaded = __webpack_require__(351); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(18); +var InputManager = __webpack_require__(359); +var PluginCache = __webpack_require__(23); +var PluginManager = __webpack_require__(364); +var ScaleManager = __webpack_require__(365); +var SceneManager = __webpack_require__(367); +var TextureEvents = __webpack_require__(119); +var TextureManager = __webpack_require__(370); +var TimeStep = __webpack_require__(337); +var VisibilityHandler = __webpack_require__(339); if (true) { - var SoundManagerCreator = __webpack_require__(375); + var SoundManagerCreator = __webpack_require__(374); } if (false) @@ -136517,7 +134582,7 @@ module.exports = Game; /***/ }), -/* 811 */ +/* 813 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136526,7 +134591,7 @@ module.exports = Game; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AddToDOM = __webpack_require__(116); +var AddToDOM = __webpack_require__(120); var CreateDOMContainer = function (game) { @@ -136561,7 +134626,7 @@ module.exports = CreateDOMContainer; /***/ }), -/* 812 */ +/* 814 */ /***/ (function(module, exports) { /** @@ -136582,7 +134647,7 @@ module.exports = 'boot'; /***/ }), -/* 813 */ +/* 815 */ /***/ (function(module, exports) { /** @@ -136603,7 +134668,7 @@ module.exports = 'destroy'; /***/ }), -/* 814 */ +/* 816 */ /***/ (function(module, exports) { /** @@ -136631,7 +134696,7 @@ module.exports = 'dragend'; /***/ }), -/* 815 */ +/* 817 */ /***/ (function(module, exports) { /** @@ -136662,7 +134727,7 @@ module.exports = 'dragenter'; /***/ }), -/* 816 */ +/* 818 */ /***/ (function(module, exports) { /** @@ -136694,7 +134759,7 @@ module.exports = 'drag'; /***/ }), -/* 817 */ +/* 819 */ /***/ (function(module, exports) { /** @@ -136725,7 +134790,7 @@ module.exports = 'dragleave'; /***/ }), -/* 818 */ +/* 820 */ /***/ (function(module, exports) { /** @@ -136759,7 +134824,7 @@ module.exports = 'dragover'; /***/ }), -/* 819 */ +/* 821 */ /***/ (function(module, exports) { /** @@ -136789,7 +134854,7 @@ module.exports = 'dragstart'; /***/ }), -/* 820 */ +/* 822 */ /***/ (function(module, exports) { /** @@ -136818,7 +134883,7 @@ module.exports = 'drop'; /***/ }), -/* 821 */ +/* 823 */ /***/ (function(module, exports) { /** @@ -136845,7 +134910,7 @@ module.exports = 'gameout'; /***/ }), -/* 822 */ +/* 824 */ /***/ (function(module, exports) { /** @@ -136872,7 +134937,7 @@ module.exports = 'gameover'; /***/ }), -/* 823 */ +/* 825 */ /***/ (function(module, exports) { /** @@ -136913,7 +134978,7 @@ module.exports = 'gameobjectdown'; /***/ }), -/* 824 */ +/* 826 */ /***/ (function(module, exports) { /** @@ -136944,7 +135009,7 @@ module.exports = 'dragend'; /***/ }), -/* 825 */ +/* 827 */ /***/ (function(module, exports) { /** @@ -136974,7 +135039,7 @@ module.exports = 'dragenter'; /***/ }), -/* 826 */ +/* 828 */ /***/ (function(module, exports) { /** @@ -137005,7 +135070,7 @@ module.exports = 'drag'; /***/ }), -/* 827 */ +/* 829 */ /***/ (function(module, exports) { /** @@ -137035,7 +135100,7 @@ module.exports = 'dragleave'; /***/ }), -/* 828 */ +/* 830 */ /***/ (function(module, exports) { /** @@ -137068,7 +135133,7 @@ module.exports = 'dragover'; /***/ }), -/* 829 */ +/* 831 */ /***/ (function(module, exports) { /** @@ -137102,7 +135167,7 @@ module.exports = 'dragstart'; /***/ }), -/* 830 */ +/* 832 */ /***/ (function(module, exports) { /** @@ -137132,7 +135197,7 @@ module.exports = 'drop'; /***/ }), -/* 831 */ +/* 833 */ /***/ (function(module, exports) { /** @@ -137173,7 +135238,7 @@ module.exports = 'gameobjectmove'; /***/ }), -/* 832 */ +/* 834 */ /***/ (function(module, exports) { /** @@ -137214,7 +135279,7 @@ module.exports = 'gameobjectout'; /***/ }), -/* 833 */ +/* 835 */ /***/ (function(module, exports) { /** @@ -137255,7 +135320,7 @@ module.exports = 'gameobjectover'; /***/ }), -/* 834 */ +/* 836 */ /***/ (function(module, exports) { /** @@ -137296,7 +135361,7 @@ module.exports = 'pointerdown'; /***/ }), -/* 835 */ +/* 837 */ /***/ (function(module, exports) { /** @@ -137337,7 +135402,7 @@ module.exports = 'pointermove'; /***/ }), -/* 836 */ +/* 838 */ /***/ (function(module, exports) { /** @@ -137376,7 +135441,7 @@ module.exports = 'pointerout'; /***/ }), -/* 837 */ +/* 839 */ /***/ (function(module, exports) { /** @@ -137417,7 +135482,7 @@ module.exports = 'pointerover'; /***/ }), -/* 838 */ +/* 840 */ /***/ (function(module, exports) { /** @@ -137458,7 +135523,7 @@ module.exports = 'pointerup'; /***/ }), -/* 839 */ +/* 841 */ /***/ (function(module, exports) { /** @@ -137500,7 +135565,7 @@ module.exports = 'wheel'; /***/ }), -/* 840 */ +/* 842 */ /***/ (function(module, exports) { /** @@ -137541,7 +135606,7 @@ module.exports = 'gameobjectup'; /***/ }), -/* 841 */ +/* 843 */ /***/ (function(module, exports) { /** @@ -137585,7 +135650,7 @@ module.exports = 'gameobjectwheel'; /***/ }), -/* 842 */ +/* 844 */ /***/ (function(module, exports) { /** @@ -137606,7 +135671,7 @@ module.exports = 'boot'; /***/ }), -/* 843 */ +/* 845 */ /***/ (function(module, exports) { /** @@ -137631,7 +135696,7 @@ module.exports = 'process'; /***/ }), -/* 844 */ +/* 846 */ /***/ (function(module, exports) { /** @@ -137652,7 +135717,7 @@ module.exports = 'update'; /***/ }), -/* 845 */ +/* 847 */ /***/ (function(module, exports) { /** @@ -137687,7 +135752,7 @@ module.exports = 'pointerdown'; /***/ }), -/* 846 */ +/* 848 */ /***/ (function(module, exports) { /** @@ -137721,7 +135786,7 @@ module.exports = 'pointerdownoutside'; /***/ }), -/* 847 */ +/* 849 */ /***/ (function(module, exports) { /** @@ -137756,7 +135821,7 @@ module.exports = 'pointermove'; /***/ }), -/* 848 */ +/* 850 */ /***/ (function(module, exports) { /** @@ -137791,7 +135856,7 @@ module.exports = 'pointerout'; /***/ }), -/* 849 */ +/* 851 */ /***/ (function(module, exports) { /** @@ -137826,7 +135891,7 @@ module.exports = 'pointerover'; /***/ }), -/* 850 */ +/* 852 */ /***/ (function(module, exports) { /** @@ -137861,7 +135926,7 @@ module.exports = 'pointerup'; /***/ }), -/* 851 */ +/* 853 */ /***/ (function(module, exports) { /** @@ -137895,7 +135960,7 @@ module.exports = 'pointerupoutside'; /***/ }), -/* 852 */ +/* 854 */ /***/ (function(module, exports) { /** @@ -137933,7 +135998,7 @@ module.exports = 'wheel'; /***/ }), -/* 853 */ +/* 855 */ /***/ (function(module, exports) { /** @@ -137957,7 +136022,7 @@ module.exports = 'pointerlockchange'; /***/ }), -/* 854 */ +/* 856 */ /***/ (function(module, exports) { /** @@ -137979,7 +136044,7 @@ module.exports = 'preupdate'; /***/ }), -/* 855 */ +/* 857 */ /***/ (function(module, exports) { /** @@ -138000,7 +136065,7 @@ module.exports = 'shutdown'; /***/ }), -/* 856 */ +/* 858 */ /***/ (function(module, exports) { /** @@ -138022,7 +136087,7 @@ module.exports = 'start'; /***/ }), -/* 857 */ +/* 859 */ /***/ (function(module, exports) { /** @@ -138047,7 +136112,7 @@ module.exports = 'update'; /***/ }), -/* 858 */ +/* 860 */ /***/ (function(module, exports) { /** @@ -138106,7 +136171,7 @@ module.exports = GetInnerHeight; /***/ }), -/* 859 */ +/* 861 */ /***/ (function(module, exports) { /** @@ -138136,7 +136201,7 @@ module.exports = 'addfile'; /***/ }), -/* 860 */ +/* 862 */ /***/ (function(module, exports) { /** @@ -138164,7 +136229,7 @@ module.exports = 'complete'; /***/ }), -/* 861 */ +/* 863 */ /***/ (function(module, exports) { /** @@ -138193,7 +136258,7 @@ module.exports = 'filecomplete'; /***/ }), -/* 862 */ +/* 864 */ /***/ (function(module, exports) { /** @@ -138247,7 +136312,7 @@ module.exports = 'filecomplete-'; /***/ }), -/* 863 */ +/* 865 */ /***/ (function(module, exports) { /** @@ -138272,7 +136337,7 @@ module.exports = 'loaderror'; /***/ }), -/* 864 */ +/* 866 */ /***/ (function(module, exports) { /** @@ -138298,7 +136363,7 @@ module.exports = 'load'; /***/ }), -/* 865 */ +/* 867 */ /***/ (function(module, exports) { /** @@ -138325,7 +136390,7 @@ module.exports = 'fileprogress'; /***/ }), -/* 866 */ +/* 868 */ /***/ (function(module, exports) { /** @@ -138354,7 +136419,7 @@ module.exports = 'postprocess'; /***/ }), -/* 867 */ +/* 869 */ /***/ (function(module, exports) { /** @@ -138379,7 +136444,7 @@ module.exports = 'progress'; /***/ }), -/* 868 */ +/* 870 */ /***/ (function(module, exports) { /** @@ -138406,7 +136471,7 @@ module.exports = 'start'; /***/ }), -/* 869 */ +/* 871 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138416,7 +136481,7 @@ module.exports = 'start'; */ var GetFastValue = __webpack_require__(2); -var UppercaseFirst = __webpack_require__(176); +var UppercaseFirst = __webpack_require__(179); /** * Builds an array of which physics plugins should be activated for the given Scene. @@ -138468,7 +136533,7 @@ module.exports = GetPhysicsPlugins; /***/ }), -/* 870 */ +/* 872 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138515,7 +136580,7 @@ module.exports = GetScenePlugins; /***/ }), -/* 871 */ +/* 873 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138576,7 +136641,7 @@ module.exports = InjectionMap; /***/ }), -/* 872 */ +/* 874 */ /***/ (function(module, exports) { /** @@ -138657,7 +136722,7 @@ module.exports = AtlasXML; /***/ }), -/* 873 */ +/* 875 */ /***/ (function(module, exports) { /** @@ -138692,7 +136757,7 @@ module.exports = Canvas; /***/ }), -/* 874 */ +/* 876 */ /***/ (function(module, exports) { /** @@ -138727,7 +136792,7 @@ module.exports = Image; /***/ }), -/* 875 */ +/* 877 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138736,7 +136801,7 @@ module.exports = Image; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); +var Clone = __webpack_require__(67); /** * Parses a Texture Atlas JSON Array and adds the Frames to the Texture. @@ -138834,7 +136899,7 @@ module.exports = JSONArray; /***/ }), -/* 876 */ +/* 878 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138843,7 +136908,7 @@ module.exports = JSONArray; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); +var Clone = __webpack_require__(67); /** * Parses a Texture Atlas JSON Hash and adds the Frames to the Texture. @@ -138933,7 +136998,7 @@ module.exports = JSONHash; /***/ }), -/* 877 */ +/* 879 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138957,15 +137022,15 @@ var GetFastValue = __webpack_require__(2); * * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. * @param {integer} sourceIndex - The index of the TextureSource. - * @param {integer} x - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. - * @param {integer} y - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. - * @param {integer} width - The width of the source image. - * @param {integer} height - The height of the source image. + * @param {integer} x - [description] + * @param {integer} y - [description] + * @param {integer} width - [description] + * @param {integer} height - [description] * @param {object} config - An object describing how to parse the Sprite Sheet. * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. - * @param {number} [config.startFrame=0] - The frame to start extracting from. Defaults to zero. - * @param {number} [config.endFrame=-1] - The frame to finish extracting at. Defaults to -1, which means 'all frames'. + * @param {number} [config.startFrame=0] - [description] + * @param {number} [config.endFrame=-1] - [description] * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. * @@ -139058,7 +137123,7 @@ module.exports = SpriteSheet; /***/ }), -/* 878 */ +/* 880 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -139249,7 +137314,7 @@ module.exports = SpriteSheetFromAtlas; /***/ }), -/* 879 */ +/* 881 */ /***/ (function(module, exports) { /** @@ -139419,7 +137484,7 @@ TextureImporter: /***/ }), -/* 880 */ +/* 882 */ /***/ (function(module, exports) { /** @@ -139450,7 +137515,7 @@ module.exports = 'complete'; /***/ }), -/* 881 */ +/* 883 */ /***/ (function(module, exports) { /** @@ -139480,7 +137545,7 @@ module.exports = 'decoded'; /***/ }), -/* 882 */ +/* 884 */ /***/ (function(module, exports) { /** @@ -139512,7 +137577,7 @@ module.exports = 'decodedall'; /***/ }), -/* 883 */ +/* 885 */ /***/ (function(module, exports) { /** @@ -139544,7 +137609,7 @@ module.exports = 'destroy'; /***/ }), -/* 884 */ +/* 886 */ /***/ (function(module, exports) { /** @@ -139577,7 +137642,7 @@ module.exports = 'detune'; /***/ }), -/* 885 */ +/* 887 */ /***/ (function(module, exports) { /** @@ -139605,7 +137670,7 @@ module.exports = 'detune'; /***/ }), -/* 886 */ +/* 888 */ /***/ (function(module, exports) { /** @@ -139632,7 +137697,7 @@ module.exports = 'mute'; /***/ }), -/* 887 */ +/* 889 */ /***/ (function(module, exports) { /** @@ -139660,7 +137725,7 @@ module.exports = 'rate'; /***/ }), -/* 888 */ +/* 890 */ /***/ (function(module, exports) { /** @@ -139687,7 +137752,7 @@ module.exports = 'volume'; /***/ }), -/* 889 */ +/* 891 */ /***/ (function(module, exports) { /** @@ -139721,7 +137786,7 @@ module.exports = 'loop'; /***/ }), -/* 890 */ +/* 892 */ /***/ (function(module, exports) { /** @@ -139755,7 +137820,7 @@ module.exports = 'looped'; /***/ }), -/* 891 */ +/* 893 */ /***/ (function(module, exports) { /** @@ -139788,7 +137853,7 @@ module.exports = 'mute'; /***/ }), -/* 892 */ +/* 894 */ /***/ (function(module, exports) { /** @@ -139815,7 +137880,7 @@ module.exports = 'pauseall'; /***/ }), -/* 893 */ +/* 895 */ /***/ (function(module, exports) { /** @@ -139847,7 +137912,7 @@ module.exports = 'pause'; /***/ }), -/* 894 */ +/* 896 */ /***/ (function(module, exports) { /** @@ -139878,7 +137943,7 @@ module.exports = 'play'; /***/ }), -/* 895 */ +/* 897 */ /***/ (function(module, exports) { /** @@ -139911,7 +137976,7 @@ module.exports = 'rate'; /***/ }), -/* 896 */ +/* 898 */ /***/ (function(module, exports) { /** @@ -139938,7 +138003,7 @@ module.exports = 'resumeall'; /***/ }), -/* 897 */ +/* 899 */ /***/ (function(module, exports) { /** @@ -139971,7 +138036,7 @@ module.exports = 'resume'; /***/ }), -/* 898 */ +/* 900 */ /***/ (function(module, exports) { /** @@ -140004,7 +138069,7 @@ module.exports = 'seek'; /***/ }), -/* 899 */ +/* 901 */ /***/ (function(module, exports) { /** @@ -140031,7 +138096,7 @@ module.exports = 'stopall'; /***/ }), -/* 900 */ +/* 902 */ /***/ (function(module, exports) { /** @@ -140063,7 +138128,7 @@ module.exports = 'stop'; /***/ }), -/* 901 */ +/* 903 */ /***/ (function(module, exports) { /** @@ -140090,7 +138155,7 @@ module.exports = 'unlocked'; /***/ }), -/* 902 */ +/* 904 */ /***/ (function(module, exports) { /** @@ -140123,7 +138188,7 @@ module.exports = 'volume'; /***/ }), -/* 903 */ +/* 905 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140138,105 +138203,102 @@ module.exports = 'volume'; var GameObjects = { - Events: __webpack_require__(88), + Events: __webpack_require__(90), - DisplayList: __webpack_require__(904), - GameObjectCreator: __webpack_require__(17), + DisplayList: __webpack_require__(906), + GameObjectCreator: __webpack_require__(16), GameObjectFactory: __webpack_require__(5), - UpdateList: __webpack_require__(932), + UpdateList: __webpack_require__(934), Components: __webpack_require__(12), BuildGameObject: __webpack_require__(28), - BuildGameObjectAnimation: __webpack_require__(386), + BuildGameObjectAnimation: __webpack_require__(385), GameObject: __webpack_require__(14), - BitmapText: __webpack_require__(126), - Blitter: __webpack_require__(183), - Container: __webpack_require__(184), - DOMElement: __webpack_require__(388), - DynamicBitmapText: __webpack_require__(185), - Extern: __webpack_require__(390), - Graphics: __webpack_require__(186), - Group: __webpack_require__(95), - Image: __webpack_require__(103), - Particles: __webpack_require__(964), - PathFollower: __webpack_require__(402), - RenderTexture: __webpack_require__(190), - RetroFont: __webpack_require__(973), - Rope: __webpack_require__(192), - Sprite: __webpack_require__(73), - Text: __webpack_require__(193), - TileSprite: __webpack_require__(194), - Zone: __webpack_require__(106), - Video: __webpack_require__(195), + BitmapText: __webpack_require__(129), + Blitter: __webpack_require__(186), + Container: __webpack_require__(187), + DOMElement: __webpack_require__(387), + DynamicBitmapText: __webpack_require__(188), + Extern: __webpack_require__(389), + Graphics: __webpack_require__(189), + Group: __webpack_require__(97), + Image: __webpack_require__(98), + Particles: __webpack_require__(966), + PathFollower: __webpack_require__(401), + RenderTexture: __webpack_require__(193), + RetroFont: __webpack_require__(975), + Sprite: __webpack_require__(69), + Text: __webpack_require__(195), + TileSprite: __webpack_require__(196), + Zone: __webpack_require__(110), + Video: __webpack_require__(197), // Shapes - Shape: __webpack_require__(31), - Arc: __webpack_require__(403), - Curve: __webpack_require__(404), - Ellipse: __webpack_require__(405), - Grid: __webpack_require__(406), - IsoBox: __webpack_require__(407), - IsoTriangle: __webpack_require__(408), - Line: __webpack_require__(409), - Polygon: __webpack_require__(410), - Rectangle: __webpack_require__(415), - Star: __webpack_require__(416), - Triangle: __webpack_require__(417), + Shape: __webpack_require__(30), + Arc: __webpack_require__(402), + Curve: __webpack_require__(403), + Ellipse: __webpack_require__(404), + Grid: __webpack_require__(405), + IsoBox: __webpack_require__(406), + IsoTriangle: __webpack_require__(407), + Line: __webpack_require__(408), + Polygon: __webpack_require__(409), + Rectangle: __webpack_require__(414), + Star: __webpack_require__(415), + Triangle: __webpack_require__(416), // Game Object Factories Factories: { - Blitter: __webpack_require__(1024), - Container: __webpack_require__(1025), - DOMElement: __webpack_require__(1026), - DynamicBitmapText: __webpack_require__(1027), - Extern: __webpack_require__(1028), - Graphics: __webpack_require__(1029), - Group: __webpack_require__(1030), - Image: __webpack_require__(1031), - Particles: __webpack_require__(1032), - PathFollower: __webpack_require__(1033), - RenderTexture: __webpack_require__(1034), - Rope: __webpack_require__(1035), - Sprite: __webpack_require__(1036), - StaticBitmapText: __webpack_require__(1037), - Text: __webpack_require__(1038), - TileSprite: __webpack_require__(1039), - Zone: __webpack_require__(1040), - Video: __webpack_require__(1041), + Blitter: __webpack_require__(1023), + Container: __webpack_require__(1024), + DOMElement: __webpack_require__(1025), + DynamicBitmapText: __webpack_require__(1026), + Extern: __webpack_require__(1027), + Graphics: __webpack_require__(1028), + Group: __webpack_require__(1029), + Image: __webpack_require__(1030), + Particles: __webpack_require__(1031), + PathFollower: __webpack_require__(1032), + RenderTexture: __webpack_require__(1033), + Sprite: __webpack_require__(1034), + StaticBitmapText: __webpack_require__(1035), + Text: __webpack_require__(1036), + TileSprite: __webpack_require__(1037), + Zone: __webpack_require__(1038), + Video: __webpack_require__(1039), // Shapes - Arc: __webpack_require__(1042), - Curve: __webpack_require__(1043), - Ellipse: __webpack_require__(1044), - Grid: __webpack_require__(1045), - IsoBox: __webpack_require__(1046), - IsoTriangle: __webpack_require__(1047), - Line: __webpack_require__(1048), - Polygon: __webpack_require__(1049), - Rectangle: __webpack_require__(1050), - Star: __webpack_require__(1051), - Triangle: __webpack_require__(1052) + Arc: __webpack_require__(1040), + Curve: __webpack_require__(1041), + Ellipse: __webpack_require__(1042), + Grid: __webpack_require__(1043), + IsoBox: __webpack_require__(1044), + IsoTriangle: __webpack_require__(1045), + Line: __webpack_require__(1046), + Polygon: __webpack_require__(1047), + Rectangle: __webpack_require__(1048), + Star: __webpack_require__(1049), + Triangle: __webpack_require__(1050) }, Creators: { - Blitter: __webpack_require__(1053), - Container: __webpack_require__(1054), - DynamicBitmapText: __webpack_require__(1055), - Graphics: __webpack_require__(1056), - Group: __webpack_require__(1057), - Image: __webpack_require__(1058), - Particles: __webpack_require__(1059), - RenderTexture: __webpack_require__(1060), - Rope: __webpack_require__(1061), - Sprite: __webpack_require__(1062), - StaticBitmapText: __webpack_require__(1063), - Text: __webpack_require__(1064), - TileSprite: __webpack_require__(1065), - Zone: __webpack_require__(1066), - Video: __webpack_require__(1067) + Blitter: __webpack_require__(1051), + Container: __webpack_require__(1052), + DynamicBitmapText: __webpack_require__(1053), + Graphics: __webpack_require__(1054), + Group: __webpack_require__(1055), + Image: __webpack_require__(1056), + Particles: __webpack_require__(1057), + RenderTexture: __webpack_require__(1058), + Sprite: __webpack_require__(1059), + StaticBitmapText: __webpack_require__(1060), + Text: __webpack_require__(1061), + TileSprite: __webpack_require__(1062), + Zone: __webpack_require__(1063), + Video: __webpack_require__(1064) } }; @@ -140244,29 +138306,29 @@ var GameObjects = { if (true) { // WebGL only Game Objects - GameObjects.Mesh = __webpack_require__(128); - GameObjects.Quad = __webpack_require__(198); - GameObjects.Shader = __webpack_require__(199); + GameObjects.Mesh = __webpack_require__(130); + GameObjects.Quad = __webpack_require__(200); + GameObjects.Shader = __webpack_require__(201); - GameObjects.Factories.Mesh = __webpack_require__(1074); - GameObjects.Factories.Quad = __webpack_require__(1075); - GameObjects.Factories.Shader = __webpack_require__(1076); + GameObjects.Factories.Mesh = __webpack_require__(1071); + GameObjects.Factories.Quad = __webpack_require__(1072); + GameObjects.Factories.Shader = __webpack_require__(1073); - GameObjects.Creators.Mesh = __webpack_require__(1077); - GameObjects.Creators.Quad = __webpack_require__(1078); - GameObjects.Creators.Shader = __webpack_require__(1079); + GameObjects.Creators.Mesh = __webpack_require__(1074); + GameObjects.Creators.Quad = __webpack_require__(1075); + GameObjects.Creators.Shader = __webpack_require__(1076); - GameObjects.Light = __webpack_require__(421); + GameObjects.Light = __webpack_require__(420); - __webpack_require__(422); - __webpack_require__(1080); + __webpack_require__(421); + __webpack_require__(1077); } module.exports = GameObjects; /***/ }), -/* 904 */ +/* 906 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140276,10 +138338,10 @@ module.exports = GameObjects; */ var Class = __webpack_require__(0); -var List = __webpack_require__(123); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var StableSort = __webpack_require__(125); +var List = __webpack_require__(126); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var StableSort = __webpack_require__(128); /** * @classdesc @@ -140471,7 +138533,7 @@ module.exports = DisplayList; /***/ }), -/* 905 */ +/* 907 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140486,21 +138548,21 @@ module.exports = DisplayList; module.exports = { - CheckMatrix: __webpack_require__(179), - MatrixToString: __webpack_require__(906), - ReverseColumns: __webpack_require__(907), - ReverseRows: __webpack_require__(908), - Rotate180: __webpack_require__(909), - RotateLeft: __webpack_require__(910), - RotateMatrix: __webpack_require__(124), - RotateRight: __webpack_require__(911), - TransposeMatrix: __webpack_require__(383) + CheckMatrix: __webpack_require__(182), + MatrixToString: __webpack_require__(908), + ReverseColumns: __webpack_require__(909), + ReverseRows: __webpack_require__(910), + Rotate180: __webpack_require__(911), + RotateLeft: __webpack_require__(912), + RotateMatrix: __webpack_require__(127), + RotateRight: __webpack_require__(913), + TransposeMatrix: __webpack_require__(382) }; /***/ }), -/* 906 */ +/* 908 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140509,8 +138571,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Pad = __webpack_require__(157); -var CheckMatrix = __webpack_require__(179); +var Pad = __webpack_require__(160); +var CheckMatrix = __webpack_require__(182); /** * Generates a string (which you can pass to console.log) from the given Array Matrix. @@ -140581,7 +138643,7 @@ module.exports = MatrixToString; /***/ }), -/* 907 */ +/* 909 */ /***/ (function(module, exports) { /** @@ -140612,7 +138674,7 @@ module.exports = ReverseColumns; /***/ }), -/* 908 */ +/* 910 */ /***/ (function(module, exports) { /** @@ -140648,7 +138710,7 @@ module.exports = ReverseRows; /***/ }), -/* 909 */ +/* 911 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140657,7 +138719,7 @@ module.exports = ReverseRows; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateMatrix = __webpack_require__(124); +var RotateMatrix = __webpack_require__(127); /** * Rotates the array matrix 180 degrees. @@ -140681,7 +138743,7 @@ module.exports = Rotate180; /***/ }), -/* 910 */ +/* 912 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140690,7 +138752,7 @@ module.exports = Rotate180; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateMatrix = __webpack_require__(124); +var RotateMatrix = __webpack_require__(127); /** * Rotates the array matrix to the left (or 90 degrees) @@ -140714,7 +138776,7 @@ module.exports = RotateLeft; /***/ }), -/* 911 */ +/* 913 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140723,7 +138785,7 @@ module.exports = RotateLeft; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateMatrix = __webpack_require__(124); +var RotateMatrix = __webpack_require__(127); /** * Rotates the array matrix to the left (or -90 degrees) @@ -140747,7 +138809,7 @@ module.exports = RotateRight; /***/ }), -/* 912 */ +/* 914 */ /***/ (function(module, exports) { /** @@ -140864,7 +138926,7 @@ module.exports = Add; /***/ }), -/* 913 */ +/* 915 */ /***/ (function(module, exports) { /** @@ -140986,7 +139048,7 @@ module.exports = AddAt; /***/ }), -/* 914 */ +/* 916 */ /***/ (function(module, exports) { /** @@ -141024,7 +139086,7 @@ module.exports = BringToTop; /***/ }), -/* 915 */ +/* 917 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141033,7 +139095,7 @@ module.exports = BringToTop; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Returns the total number of elements in the array which have a property matching the given value. @@ -141076,7 +139138,7 @@ module.exports = CountAllMatching; /***/ }), -/* 916 */ +/* 918 */ /***/ (function(module, exports) { /** @@ -141122,7 +139184,7 @@ module.exports = Each; /***/ }), -/* 917 */ +/* 919 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141131,7 +139193,7 @@ module.exports = Each; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Passes each element in the array, between the start and end indexes, to the given callback. @@ -141178,7 +139240,7 @@ module.exports = EachInRange; /***/ }), -/* 918 */ +/* 920 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141187,7 +139249,7 @@ module.exports = EachInRange; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Returns all elements in the array. @@ -141240,7 +139302,7 @@ module.exports = GetAll; /***/ }), -/* 919 */ +/* 921 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141249,7 +139311,7 @@ module.exports = GetAll; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Returns the first element in the array. @@ -141299,7 +139361,7 @@ module.exports = GetFirst; /***/ }), -/* 920 */ +/* 922 */ /***/ (function(module, exports) { /** @@ -141341,7 +139403,7 @@ module.exports = MoveDown; /***/ }), -/* 921 */ +/* 923 */ /***/ (function(module, exports) { /** @@ -141388,7 +139450,7 @@ module.exports = MoveTo; /***/ }), -/* 922 */ +/* 924 */ /***/ (function(module, exports) { /** @@ -141430,7 +139492,7 @@ module.exports = MoveUp; /***/ }), -/* 923 */ +/* 925 */ /***/ (function(module, exports) { /** @@ -141494,7 +139556,7 @@ module.exports = NumberArray; /***/ }), -/* 924 */ +/* 926 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141503,7 +139565,7 @@ module.exports = NumberArray; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RoundAwayFromZero = __webpack_require__(327); +var RoundAwayFromZero = __webpack_require__(328); /** * Create an array of numbers (positive and/or negative) progressing from `start` @@ -141571,7 +139633,7 @@ module.exports = NumberArrayStep; /***/ }), -/* 925 */ +/* 927 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141580,7 +139642,7 @@ module.exports = NumberArrayStep; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SpliceOne = __webpack_require__(78); +var SpliceOne = __webpack_require__(79); /** * Removes the item from the given position in the array. @@ -141622,7 +139684,7 @@ module.exports = RemoveAt; /***/ }), -/* 926 */ +/* 928 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141631,7 +139693,7 @@ module.exports = RemoveAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Removes the item within the given range in the array. @@ -141685,7 +139747,7 @@ module.exports = RemoveBetween; /***/ }), -/* 927 */ +/* 929 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141694,7 +139756,7 @@ module.exports = RemoveBetween; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SpliceOne = __webpack_require__(78); +var SpliceOne = __webpack_require__(79); /** * Removes a random object from the given array and returns it. @@ -141723,7 +139785,7 @@ module.exports = RemoveRandomElement; /***/ }), -/* 928 */ +/* 930 */ /***/ (function(module, exports) { /** @@ -141767,7 +139829,7 @@ module.exports = Replace; /***/ }), -/* 929 */ +/* 931 */ /***/ (function(module, exports) { /** @@ -141805,7 +139867,7 @@ module.exports = SendToBack; /***/ }), -/* 930 */ +/* 932 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141814,7 +139876,7 @@ module.exports = SendToBack; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Scans the array for elements with the given property. If found, the property is set to the `value`. @@ -141860,7 +139922,7 @@ module.exports = SetAll; /***/ }), -/* 931 */ +/* 933 */ /***/ (function(module, exports) { /** @@ -141908,7 +139970,7 @@ module.exports = Swap; /***/ }), -/* 932 */ +/* 934 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141918,9 +139980,9 @@ module.exports = Swap; */ var Class = __webpack_require__(0); -var ProcessQueue = __webpack_require__(181); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var ProcessQueue = __webpack_require__(184); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -142209,7 +140271,7 @@ module.exports = UpdateList; /***/ }), -/* 933 */ +/* 935 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -142224,14 +140286,14 @@ module.exports = UpdateList; module.exports = { - PROCESS_QUEUE_ADD: __webpack_require__(934), - PROCESS_QUEUE_REMOVE: __webpack_require__(935) + PROCESS_QUEUE_ADD: __webpack_require__(936), + PROCESS_QUEUE_REMOVE: __webpack_require__(937) }; /***/ }), -/* 934 */ +/* 936 */ /***/ (function(module, exports) { /** @@ -142258,7 +140320,7 @@ module.exports = 'add'; /***/ }), -/* 935 */ +/* 937 */ /***/ (function(module, exports) { /** @@ -142285,7 +140347,7 @@ module.exports = 'remove'; /***/ }), -/* 936 */ +/* 938 */ /***/ (function(module, exports) { /** @@ -142738,7 +140800,7 @@ module.exports = GetBitmapTextSize; /***/ }), -/* 937 */ +/* 939 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -142747,7 +140809,7 @@ module.exports = GetBitmapTextSize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ParseXMLBitmapFont = __webpack_require__(182); +var ParseXMLBitmapFont = __webpack_require__(185); /** * Parse an XML Bitmap Font from an Atlas. @@ -142791,7 +140853,7 @@ module.exports = ParseFromAtlas; /***/ }), -/* 938 */ +/* 940 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -142805,12 +140867,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(939); + renderWebGL = __webpack_require__(941); } if (true) { - renderCanvas = __webpack_require__(940); + renderCanvas = __webpack_require__(942); } module.exports = { @@ -142822,7 +140884,7 @@ module.exports = { /***/ }), -/* 939 */ +/* 941 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -142831,7 +140893,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -143058,7 +141120,7 @@ module.exports = BitmapTextWebGLRenderer; /***/ }), -/* 940 */ +/* 942 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143067,7 +141129,7 @@ module.exports = BitmapTextWebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -143240,7 +141302,7 @@ module.exports = BitmapTextCanvasRenderer; /***/ }), -/* 941 */ +/* 943 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143254,12 +141316,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(942); + renderWebGL = __webpack_require__(944); } if (true) { - renderCanvas = __webpack_require__(943); + renderCanvas = __webpack_require__(945); } module.exports = { @@ -143271,7 +141333,7 @@ module.exports = { /***/ }), -/* 942 */ +/* 944 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143280,7 +141342,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -143401,7 +141463,7 @@ module.exports = BlitterWebGLRenderer; /***/ }), -/* 943 */ +/* 945 */ /***/ (function(module, exports) { /** @@ -143531,7 +141593,7 @@ module.exports = BlitterCanvasRenderer; /***/ }), -/* 944 */ +/* 946 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143541,7 +141603,7 @@ module.exports = BlitterCanvasRenderer; */ var Class = __webpack_require__(0); -var Frame = __webpack_require__(92); +var Frame = __webpack_require__(94); /** * @classdesc @@ -143688,7 +141750,7 @@ var Bob = new Class({ * * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The frame to be used during rendering. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFrame: function (frame) { @@ -143714,7 +141776,7 @@ var Bob = new Class({ * @method Phaser.GameObjects.Bob#resetFlip * @since 3.0.0 * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ resetFlip: function () { @@ -143738,7 +141800,7 @@ var Bob = new Class({ * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ reset: function (x, y, frame) { @@ -143770,7 +141832,7 @@ var Bob = new Class({ * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setPosition: function (x, y) { @@ -143788,7 +141850,7 @@ var Bob = new Class({ * * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFlipX: function (value) { @@ -143805,7 +141867,7 @@ var Bob = new Class({ * * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFlipY: function (value) { @@ -143823,7 +141885,7 @@ var Bob = new Class({ * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFlip: function (x, y) { @@ -143843,7 +141905,7 @@ var Bob = new Class({ * * @param {boolean} value - The visible state of the Game Object. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setVisible: function (value) { @@ -143863,7 +141925,7 @@ var Bob = new Class({ * * @param {number} value - The alpha value used for this Bob. Between 0 and 1. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setAlpha: function (value) { @@ -143880,7 +141942,7 @@ var Bob = new Class({ * * @param {number} value - The tint value used for this Bob. Between 0 and 0xffffff. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setTint: function (value) { @@ -143961,7 +142023,7 @@ module.exports = Bob; /***/ }), -/* 945 */ +/* 947 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143976,12 +142038,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(946); + renderWebGL = __webpack_require__(948); } if (true) { - renderCanvas = __webpack_require__(947); + renderCanvas = __webpack_require__(949); } module.exports = { @@ -143993,7 +142055,7 @@ module.exports = { /***/ }), -/* 946 */ +/* 948 */ /***/ (function(module, exports) { /** @@ -144142,7 +142204,7 @@ module.exports = ContainerWebGLRenderer; /***/ }), -/* 947 */ +/* 949 */ /***/ (function(module, exports) { /** @@ -144239,7 +142301,7 @@ module.exports = ContainerCanvasRenderer; /***/ }), -/* 948 */ +/* 950 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144253,12 +142315,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(389); + renderWebGL = __webpack_require__(388); } if (true) { - renderCanvas = __webpack_require__(389); + renderCanvas = __webpack_require__(388); } module.exports = { @@ -144270,7 +142332,7 @@ module.exports = { /***/ }), -/* 949 */ +/* 951 */ /***/ (function(module, exports) { /** @@ -144311,7 +142373,7 @@ module.exports = [ /***/ }), -/* 950 */ +/* 952 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144325,12 +142387,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(951); + renderWebGL = __webpack_require__(953); } if (true) { - renderCanvas = __webpack_require__(952); + renderCanvas = __webpack_require__(954); } module.exports = { @@ -144342,7 +142404,7 @@ module.exports = { /***/ }), -/* 951 */ +/* 953 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144351,7 +142413,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -144648,7 +142710,7 @@ module.exports = DynamicBitmapTextWebGLRenderer; /***/ }), -/* 952 */ +/* 954 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144657,7 +142719,7 @@ module.exports = DynamicBitmapTextWebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -144859,7 +142921,7 @@ module.exports = DynamicBitmapTextCanvasRenderer; /***/ }), -/* 953 */ +/* 955 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144873,12 +142935,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(954); + renderWebGL = __webpack_require__(956); } if (true) { - renderCanvas = __webpack_require__(955); + renderCanvas = __webpack_require__(957); } module.exports = { @@ -144890,7 +142952,7 @@ module.exports = { /***/ }), -/* 954 */ +/* 956 */ /***/ (function(module, exports) { /** @@ -144959,13 +143021,13 @@ module.exports = ExternWebGLRenderer; /***/ }), -/* 955 */ +/* 957 */ /***/ (function(module, exports) { /***/ }), -/* 956 */ +/* 958 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144979,15 +143041,15 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(957); + renderWebGL = __webpack_require__(959); // Needed for Graphics.generateTexture - renderCanvas = __webpack_require__(394); + renderCanvas = __webpack_require__(393); } if (true) { - renderCanvas = __webpack_require__(394); + renderCanvas = __webpack_require__(393); } module.exports = { @@ -144999,7 +143061,7 @@ module.exports = { /***/ }), -/* 957 */ +/* 959 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145008,8 +143070,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Commands = __webpack_require__(187); -var Utils = __webpack_require__(9); +var Commands = __webpack_require__(190); +var Utils = __webpack_require__(10); // TODO: Remove the use of this var Point = function (x, y, width) @@ -145364,7 +143426,7 @@ module.exports = GraphicsWebGLRenderer; /***/ }), -/* 958 */ +/* 960 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145378,12 +143440,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(959); + renderWebGL = __webpack_require__(961); } if (true) { - renderCanvas = __webpack_require__(960); + renderCanvas = __webpack_require__(962); } module.exports = { @@ -145395,7 +143457,7 @@ module.exports = { /***/ }), -/* 959 */ +/* 961 */ /***/ (function(module, exports) { /** @@ -145428,7 +143490,7 @@ module.exports = SpriteWebGLRenderer; /***/ }), -/* 960 */ +/* 962 */ /***/ (function(module, exports) { /** @@ -145461,7 +143523,7 @@ module.exports = SpriteCanvasRenderer; /***/ }), -/* 961 */ +/* 963 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145475,12 +143537,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(962); + renderWebGL = __webpack_require__(964); } if (true) { - renderCanvas = __webpack_require__(963); + renderCanvas = __webpack_require__(965); } module.exports = { @@ -145492,7 +143554,7 @@ module.exports = { /***/ }), -/* 962 */ +/* 964 */ /***/ (function(module, exports) { /** @@ -145525,7 +143587,7 @@ module.exports = ImageWebGLRenderer; /***/ }), -/* 963 */ +/* 965 */ /***/ (function(module, exports) { /** @@ -145558,7 +143620,7 @@ module.exports = ImageCanvasRenderer; /***/ }), -/* 964 */ +/* 966 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145573,17 +143635,17 @@ module.exports = ImageCanvasRenderer; module.exports = { - GravityWell: __webpack_require__(395), - Particle: __webpack_require__(396), - ParticleEmitter: __webpack_require__(397), - ParticleEmitterManager: __webpack_require__(189), - Zones: __webpack_require__(969) + GravityWell: __webpack_require__(394), + Particle: __webpack_require__(395), + ParticleEmitter: __webpack_require__(396), + ParticleEmitterManager: __webpack_require__(192), + Zones: __webpack_require__(971) }; /***/ }), -/* 965 */ +/* 967 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145593,8 +143655,8 @@ module.exports = { */ var Class = __webpack_require__(0); -var FloatBetween = __webpack_require__(325); -var GetEaseFunction = __webpack_require__(67); +var FloatBetween = __webpack_require__(326); +var GetEaseFunction = __webpack_require__(82); var GetFastValue = __webpack_require__(2); var Wrap = __webpack_require__(58); @@ -145797,7 +143859,7 @@ var EmitterOp = new Class({ * * @param {number} value - The value of the property. * - * @return {this} This Emitter Op object. + * @return {Phaser.GameObjects.Particles.EmitterOp} This Emitter Op object. */ onChange: function (value) { @@ -145814,7 +143876,7 @@ var EmitterOp = new Class({ * @method Phaser.GameObjects.Particles.EmitterOp#setMethods * @since 3.0.0 * - * @return {this} This Emitter Op object. + * @return {Phaser.GameObjects.Particles.EmitterOp} This Emitter Op object. */ setMethods: function () { @@ -146174,7 +144236,7 @@ module.exports = EmitterOp; /***/ }), -/* 966 */ +/* 968 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146188,12 +144250,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(967); + renderWebGL = __webpack_require__(969); } if (true) { - renderCanvas = __webpack_require__(968); + renderCanvas = __webpack_require__(970); } module.exports = { @@ -146205,7 +144267,7 @@ module.exports = { /***/ }), -/* 967 */ +/* 969 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146214,7 +144276,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -146364,7 +144426,7 @@ module.exports = ParticleManagerWebGLRenderer; /***/ }), -/* 968 */ +/* 970 */ /***/ (function(module, exports) { /** @@ -146487,7 +144549,7 @@ module.exports = ParticleManagerCanvasRenderer; /***/ }), -/* 969 */ +/* 971 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146502,15 +144564,15 @@ module.exports = ParticleManagerCanvasRenderer; module.exports = { - DeathZone: __webpack_require__(398), - EdgeZone: __webpack_require__(399), - RandomZone: __webpack_require__(401) + DeathZone: __webpack_require__(397), + EdgeZone: __webpack_require__(398), + RandomZone: __webpack_require__(400) }; /***/ }), -/* 970 */ +/* 972 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146524,12 +144586,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(971); + renderWebGL = __webpack_require__(973); } if (true) { - renderCanvas = __webpack_require__(972); + renderCanvas = __webpack_require__(974); } module.exports = { @@ -146541,7 +144603,7 @@ module.exports = { /***/ }), -/* 971 */ +/* 973 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146550,7 +144612,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -146604,7 +144666,7 @@ module.exports = RenderTextureWebGLRenderer; /***/ }), -/* 972 */ +/* 974 */ /***/ (function(module, exports) { /** @@ -146637,7 +144699,7 @@ module.exports = RenderTextureCanvasRenderer; /***/ }), -/* 973 */ +/* 975 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146646,15 +144708,15 @@ module.exports = RenderTextureCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RETRO_FONT_CONST = __webpack_require__(974); -var Extend = __webpack_require__(18); +var RETRO_FONT_CONST = __webpack_require__(976); +var Extend = __webpack_require__(17); /** * @namespace Phaser.GameObjects.RetroFont * @since 3.6.0 */ -var RetroFont = { Parse: __webpack_require__(975) }; +var RetroFont = { Parse: __webpack_require__(977) }; // Merge in the consts RetroFont = Extend(false, RetroFont, RETRO_FONT_CONST); @@ -146663,7 +144725,7 @@ module.exports = RetroFont; /***/ }), -/* 974 */ +/* 976 */ /***/ (function(module, exports) { /** @@ -146779,7 +144841,7 @@ module.exports = RETRO_FONT_CONST; /***/ }), -/* 975 */ +/* 977 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146894,209 +144956,10 @@ var ParseRetroFont = function (scene, config) module.exports = ParseRetroFont; -/***/ }), -/* 976 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = __webpack_require__(1); -var renderCanvas = __webpack_require__(1); - -if (true) -{ - renderWebGL = __webpack_require__(977); -} - -if (true) -{ - renderCanvas = __webpack_require__(978); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; - - -/***/ }), -/* 977 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = __webpack_require__(9); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Rope#renderWebGL - * @since 3.23.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RopeWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = src.pipeline; - - renderer.setPipeline(pipeline, src); - - var camMatrix = pipeline._tempMatrix1; - var spriteMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var frame = src.frame; - var texture = frame.glTexture; - - var vertices = src.vertices; - var uvs = src.uv; - var colors = src.colors; - var alphas = src.alphas; - var alpha = src.alpha; - var getTint = Utils.getTintAppendFloatAlphaAndSwap; - var roundPixels = camera.roundPixels; - - var meshVerticesLength = vertices.length; - var vertexCount = Math.floor(meshVerticesLength * 0.5); - - // Because it's a triangle strip and we don't want lots of degenerate triangles joining things up - pipeline.flush(); - - pipeline.setTexture2D(texture, 0); - - var vertexViewF32 = pipeline.vertexViewF32; - var vertexViewU32 = pipeline.vertexViewU32; - - var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; - - var colorIndex = 0; - - var tintEffect = src.tintFill; - - if (src.dirty) - { - src.updateVertices(); - } - - var debugCallback = src.debugCallback; - var debugVerts = []; - - for (var i = 0; i < meshVerticesLength; i += 2) - { - var x = vertices[i + 0]; - var y = vertices[i + 1]; - - var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; - var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; - - if (roundPixels) - { - tx = Math.round(tx); - ty = Math.round(ty); - } - - vertexViewF32[++vertexOffset] = tx; - vertexViewF32[++vertexOffset] = ty; - vertexViewF32[++vertexOffset] = uvs[i + 0]; - vertexViewF32[++vertexOffset] = uvs[i + 1]; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = getTint(colors[colorIndex], camera.alpha * (alphas[colorIndex] * alpha)); - - colorIndex++; - - if (debugCallback) - { - debugVerts[i + 0] = tx; - debugVerts[i + 1] = ty; - } - } - - if (debugCallback) - { - debugCallback.call(src, src, meshVerticesLength, debugVerts); - } - - pipeline.vertexCount += vertexCount; -}; - -module.exports = RopeWebGLRenderer; - - /***/ }), /* 978 */ /***/ (function(module, exports) { -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This is a stub function for Rope.Render. There is no Canvas renderer for Rope objects. - * - * @method Phaser.GameObjects.Rope#renderCanvas - * @since 3.23.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var RopeCanvasRenderer = function () -{ -}; - -module.exports = RopeCanvasRenderer; - - -/***/ }), -/* 979 */ -/***/ (function(module, exports) { - /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -147176,7 +145039,7 @@ module.exports = GetTextSize; /***/ }), -/* 980 */ +/* 979 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147190,12 +145053,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(981); + renderWebGL = __webpack_require__(980); } if (true) { - renderCanvas = __webpack_require__(982); + renderCanvas = __webpack_require__(981); } module.exports = { @@ -147207,7 +145070,7 @@ module.exports = { /***/ }), -/* 981 */ +/* 980 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147216,7 +145079,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -147272,7 +145135,7 @@ module.exports = TextWebGLRenderer; /***/ }), -/* 982 */ +/* 981 */ /***/ (function(module, exports) { /** @@ -147310,7 +145173,7 @@ module.exports = TextCanvasRenderer; /***/ }), -/* 983 */ +/* 982 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147322,7 +145185,7 @@ module.exports = TextCanvasRenderer; var Class = __webpack_require__(0); var GetAdvancedValue = __webpack_require__(15); var GetValue = __webpack_require__(6); -var MeasureText = __webpack_require__(984); +var MeasureText = __webpack_require__(983); // Key: [ Object Key, Default Value ] @@ -148363,7 +146226,7 @@ module.exports = TextStyle; /***/ }), -/* 984 */ +/* 983 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148372,7 +146235,7 @@ module.exports = TextStyle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); /** * Calculates the ascent, descent and fontSize of a given font style. @@ -148498,7 +146361,7 @@ module.exports = MeasureText; /***/ }), -/* 985 */ +/* 984 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148512,12 +146375,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(986); + renderWebGL = __webpack_require__(985); } if (true) { - renderCanvas = __webpack_require__(987); + renderCanvas = __webpack_require__(986); } module.exports = { @@ -148529,7 +146392,7 @@ module.exports = { /***/ }), -/* 986 */ +/* 985 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148538,7 +146401,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -148589,7 +146452,7 @@ module.exports = TileSpriteWebGLRenderer; /***/ }), -/* 987 */ +/* 986 */ /***/ (function(module, exports) { /** @@ -148624,7 +146487,7 @@ module.exports = TileSpriteCanvasRenderer; /***/ }), -/* 988 */ +/* 987 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148638,12 +146501,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(989); + renderWebGL = __webpack_require__(988); } if (true) { - renderCanvas = __webpack_require__(990); + renderCanvas = __webpack_require__(989); } module.exports = { @@ -148655,7 +146518,7 @@ module.exports = { /***/ }), -/* 989 */ +/* 988 */ /***/ (function(module, exports) { /** @@ -148691,7 +146554,7 @@ module.exports = VideoWebGLRenderer; /***/ }), -/* 990 */ +/* 989 */ /***/ (function(module, exports) { /** @@ -148727,7 +146590,7 @@ module.exports = VideoCanvasRenderer; /***/ }), -/* 991 */ +/* 990 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148741,12 +146604,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(992); + renderWebGL = __webpack_require__(991); } if (true) { - renderCanvas = __webpack_require__(993); + renderCanvas = __webpack_require__(992); } module.exports = { @@ -148758,7 +146621,7 @@ module.exports = { /***/ }), -/* 992 */ +/* 991 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148767,8 +146630,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -148836,7 +146699,7 @@ module.exports = ArcWebGLRenderer; /***/ }), -/* 993 */ +/* 992 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148848,7 +146711,7 @@ module.exports = ArcWebGLRenderer; var DegToRad = __webpack_require__(35); var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -148912,7 +146775,7 @@ module.exports = ArcCanvasRenderer; /***/ }), -/* 994 */ +/* 993 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148926,12 +146789,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(995); + renderWebGL = __webpack_require__(994); } if (true) { - renderCanvas = __webpack_require__(996); + renderCanvas = __webpack_require__(995); } module.exports = { @@ -148943,7 +146806,7 @@ module.exports = { /***/ }), -/* 995 */ +/* 994 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148952,8 +146815,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -149021,7 +146884,7 @@ module.exports = CurveWebGLRenderer; /***/ }), -/* 996 */ +/* 995 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149032,7 +146895,7 @@ module.exports = CurveWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -149109,7 +146972,7 @@ module.exports = CurveCanvasRenderer; /***/ }), -/* 997 */ +/* 996 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149123,12 +146986,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(998); + renderWebGL = __webpack_require__(997); } if (true) { - renderCanvas = __webpack_require__(999); + renderCanvas = __webpack_require__(998); } module.exports = { @@ -149140,7 +147003,7 @@ module.exports = { /***/ }), -/* 998 */ +/* 997 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149149,8 +147012,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -149218,7 +147081,7 @@ module.exports = EllipseWebGLRenderer; /***/ }), -/* 999 */ +/* 998 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149229,7 +147092,7 @@ module.exports = EllipseWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -149303,7 +147166,7 @@ module.exports = EllipseCanvasRenderer; /***/ }), -/* 1000 */ +/* 999 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149317,12 +147180,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1001); + renderWebGL = __webpack_require__(1000); } if (true) { - renderCanvas = __webpack_require__(1002); + renderCanvas = __webpack_require__(1001); } module.exports = { @@ -149334,7 +147197,7 @@ module.exports = { /***/ }), -/* 1001 */ +/* 1000 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149343,7 +147206,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -149560,7 +147423,7 @@ module.exports = GridWebGLRenderer; /***/ }), -/* 1002 */ +/* 1001 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149571,7 +147434,7 @@ module.exports = GridWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -149749,7 +147612,7 @@ module.exports = GridCanvasRenderer; /***/ }), -/* 1003 */ +/* 1002 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149763,12 +147626,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1004); + renderWebGL = __webpack_require__(1003); } if (true) { - renderCanvas = __webpack_require__(1005); + renderCanvas = __webpack_require__(1004); } module.exports = { @@ -149780,7 +147643,7 @@ module.exports = { /***/ }), -/* 1004 */ +/* 1003 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149789,7 +147652,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -149938,7 +147801,7 @@ module.exports = IsoBoxWebGLRenderer; /***/ }), -/* 1005 */ +/* 1004 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149948,7 +147811,7 @@ module.exports = IsoBoxWebGLRenderer; */ var FillStyleCanvas = __webpack_require__(36); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -150039,7 +147902,7 @@ module.exports = IsoBoxCanvasRenderer; /***/ }), -/* 1006 */ +/* 1005 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150053,12 +147916,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1007); + renderWebGL = __webpack_require__(1006); } if (true) { - renderCanvas = __webpack_require__(1008); + renderCanvas = __webpack_require__(1007); } module.exports = { @@ -150070,7 +147933,7 @@ module.exports = { /***/ }), -/* 1007 */ +/* 1006 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150079,7 +147942,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -150247,7 +148110,7 @@ module.exports = IsoTriangleWebGLRenderer; /***/ }), -/* 1008 */ +/* 1007 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150257,7 +148120,7 @@ module.exports = IsoTriangleWebGLRenderer; */ var FillStyleCanvas = __webpack_require__(36); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -150361,7 +148224,7 @@ module.exports = IsoTriangleCanvasRenderer; /***/ }), -/* 1009 */ +/* 1008 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150375,12 +148238,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1010); + renderWebGL = __webpack_require__(1009); } if (true) { - renderCanvas = __webpack_require__(1011); + renderCanvas = __webpack_require__(1010); } module.exports = { @@ -150392,7 +148255,7 @@ module.exports = { /***/ }), -/* 1010 */ +/* 1009 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150401,7 +148264,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -150485,7 +148348,7 @@ module.exports = LineWebGLRenderer; /***/ }), -/* 1011 */ +/* 1010 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150495,7 +148358,7 @@ module.exports = LineWebGLRenderer; */ var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -150542,7 +148405,7 @@ module.exports = LineCanvasRenderer; /***/ }), -/* 1012 */ +/* 1011 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150556,12 +148419,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1013); + renderWebGL = __webpack_require__(1012); } if (true) { - renderCanvas = __webpack_require__(1014); + renderCanvas = __webpack_require__(1013); } module.exports = { @@ -150573,7 +148436,7 @@ module.exports = { /***/ }), -/* 1013 */ +/* 1012 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150582,8 +148445,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -150651,7 +148514,7 @@ module.exports = PolygonWebGLRenderer; /***/ }), -/* 1014 */ +/* 1013 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150662,7 +148525,7 @@ module.exports = PolygonWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -150736,7 +148599,7 @@ module.exports = PolygonCanvasRenderer; /***/ }), -/* 1015 */ +/* 1014 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150750,12 +148613,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1016); + renderWebGL = __webpack_require__(1015); } if (true) { - renderCanvas = __webpack_require__(1017); + renderCanvas = __webpack_require__(1016); } module.exports = { @@ -150767,7 +148630,7 @@ module.exports = { /***/ }), -/* 1016 */ +/* 1015 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150776,8 +148639,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var StrokePathWebGL = __webpack_require__(68); -var Utils = __webpack_require__(9); +var StrokePathWebGL = __webpack_require__(70); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -150859,7 +148722,7 @@ module.exports = RectangleWebGLRenderer; /***/ }), -/* 1017 */ +/* 1016 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150870,7 +148733,7 @@ module.exports = RectangleWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -150933,7 +148796,7 @@ module.exports = RectangleCanvasRenderer; /***/ }), -/* 1018 */ +/* 1017 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150947,12 +148810,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1019); + renderWebGL = __webpack_require__(1018); } if (true) { - renderCanvas = __webpack_require__(1020); + renderCanvas = __webpack_require__(1019); } module.exports = { @@ -150964,7 +148827,7 @@ module.exports = { /***/ }), -/* 1019 */ +/* 1018 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150973,8 +148836,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -151042,7 +148905,7 @@ module.exports = StarWebGLRenderer; /***/ }), -/* 1020 */ +/* 1019 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151053,7 +148916,7 @@ module.exports = StarWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -151127,7 +148990,7 @@ module.exports = StarCanvasRenderer; /***/ }), -/* 1021 */ +/* 1020 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151141,12 +149004,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1022); + renderWebGL = __webpack_require__(1021); } if (true) { - renderCanvas = __webpack_require__(1023); + renderCanvas = __webpack_require__(1022); } module.exports = { @@ -151158,7 +149021,7 @@ module.exports = { /***/ }), -/* 1022 */ +/* 1021 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151167,8 +149030,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var StrokePathWebGL = __webpack_require__(68); -var Utils = __webpack_require__(9); +var StrokePathWebGL = __webpack_require__(70); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -151261,7 +149124,7 @@ module.exports = TriangleWebGLRenderer; /***/ }), -/* 1023 */ +/* 1022 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151272,7 +149135,7 @@ module.exports = TriangleWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -151336,7 +149199,7 @@ module.exports = TriangleCanvasRenderer; /***/ }), -/* 1024 */ +/* 1023 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151345,7 +149208,7 @@ module.exports = TriangleCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Blitter = __webpack_require__(183); +var Blitter = __webpack_require__(186); var GameObjectFactory = __webpack_require__(5); /** @@ -151378,7 +149241,7 @@ GameObjectFactory.register('blitter', function (x, y, key, frame) /***/ }), -/* 1025 */ +/* 1024 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151388,7 +149251,7 @@ GameObjectFactory.register('blitter', function (x, y, key, frame) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Container = __webpack_require__(184); +var Container = __webpack_require__(187); var GameObjectFactory = __webpack_require__(5); /** @@ -151412,7 +149275,7 @@ GameObjectFactory.register('container', function (x, y, children) /***/ }), -/* 1026 */ +/* 1025 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151421,7 +149284,7 @@ GameObjectFactory.register('container', function (x, y, children) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var DOMElement = __webpack_require__(388); +var DOMElement = __webpack_require__(387); var GameObjectFactory = __webpack_require__(5); /** @@ -151502,7 +149365,7 @@ GameObjectFactory.register('dom', function (x, y, element, style, innerText) /***/ }), -/* 1027 */ +/* 1026 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151511,7 +149374,7 @@ GameObjectFactory.register('dom', function (x, y, element, style, innerText) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var DynamicBitmapText = __webpack_require__(185); +var DynamicBitmapText = __webpack_require__(188); var GameObjectFactory = __webpack_require__(5); /** @@ -151571,7 +149434,7 @@ GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size /***/ }), -/* 1028 */ +/* 1027 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151580,7 +149443,7 @@ GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extern = __webpack_require__(390); +var Extern = __webpack_require__(389); var GameObjectFactory = __webpack_require__(5); /** @@ -151613,7 +149476,7 @@ GameObjectFactory.register('extern', function () /***/ }), -/* 1029 */ +/* 1028 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151622,7 +149485,7 @@ GameObjectFactory.register('extern', function () * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Graphics = __webpack_require__(186); +var Graphics = __webpack_require__(189); var GameObjectFactory = __webpack_require__(5); /** @@ -151652,7 +149515,7 @@ GameObjectFactory.register('graphics', function (config) /***/ }), -/* 1030 */ +/* 1029 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151661,7 +149524,7 @@ GameObjectFactory.register('graphics', function (config) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Group = __webpack_require__(95); +var Group = __webpack_require__(97); var GameObjectFactory = __webpack_require__(5); /** @@ -151684,7 +149547,7 @@ GameObjectFactory.register('group', function (children, config) /***/ }), -/* 1031 */ +/* 1030 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151693,7 +149556,7 @@ GameObjectFactory.register('group', function (children, config) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Image = __webpack_require__(103); +var Image = __webpack_require__(98); var GameObjectFactory = __webpack_require__(5); /** @@ -151726,7 +149589,7 @@ GameObjectFactory.register('image', function (x, y, key, frame) /***/ }), -/* 1032 */ +/* 1031 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151736,7 +149599,7 @@ GameObjectFactory.register('image', function (x, y, key, frame) */ var GameObjectFactory = __webpack_require__(5); -var ParticleEmitterManager = __webpack_require__(189); +var ParticleEmitterManager = __webpack_require__(192); /** * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. @@ -151772,7 +149635,7 @@ GameObjectFactory.register('particles', function (key, frame, emitters) /***/ }), -/* 1033 */ +/* 1032 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151782,7 +149645,7 @@ GameObjectFactory.register('particles', function (key, frame, emitters) */ var GameObjectFactory = __webpack_require__(5); -var PathFollower = __webpack_require__(402); +var PathFollower = __webpack_require__(401); /** * Creates a new PathFollower Game Object and adds it to the Scene. @@ -151820,7 +149683,7 @@ GameObjectFactory.register('follower', function (path, x, y, key, frame) /***/ }), -/* 1034 */ +/* 1033 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151830,7 +149693,7 @@ GameObjectFactory.register('follower', function (path, x, y, key, frame) */ var GameObjectFactory = __webpack_require__(5); -var RenderTexture = __webpack_require__(190); +var RenderTexture = __webpack_require__(193); /** * Creates a new Render Texture Game Object and adds it to the Scene. @@ -151860,61 +149723,7 @@ GameObjectFactory.register('renderTexture', function (x, y, width, height, key, /***/ }), -/* 1035 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rope = __webpack_require__(192); -var GameObjectFactory = __webpack_require__(5); - -/** - * Creates a new Rope Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#mesh - * @webglOnly - * @since 3.23.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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {Phaser.Types.Math.Vector2Like[]} [points] - An array containing the vertices data for this Rope. If none is provided a simple quad is created. See `setPoints` to set this post-creation. - * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? - * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. - * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. - * - * @return {Phaser.GameObjects.Rope} The Game Object that was created. - */ -if (true) -{ - GameObjectFactory.register('rope', function (x, y, texture, frame, points, horizontal, colors, alphas) - { - var rope = new Rope(this.scene, x, y, texture, frame, points, horizontal, colors, alphas); - - this.displayList.add(rope); - - return this.updateList.add(rope); - }); -} - -// 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 - - -/***/ }), -/* 1036 */ +/* 1034 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151924,7 +149733,7 @@ if (true) */ var GameObjectFactory = __webpack_require__(5); -var Sprite = __webpack_require__(73); +var Sprite = __webpack_require__(69); /** * Creates a new Sprite Game Object and adds it to the Scene. @@ -151961,7 +149770,7 @@ GameObjectFactory.register('sprite', function (x, y, key, frame) /***/ }), -/* 1037 */ +/* 1035 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151970,7 +149779,7 @@ GameObjectFactory.register('sprite', function (x, y, key, frame) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(126); +var BitmapText = __webpack_require__(129); var GameObjectFactory = __webpack_require__(5); /** @@ -152025,7 +149834,7 @@ GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align /***/ }), -/* 1038 */ +/* 1036 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152034,7 +149843,7 @@ GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Text = __webpack_require__(193); +var Text = __webpack_require__(195); var GameObjectFactory = __webpack_require__(5); /** @@ -152090,7 +149899,7 @@ GameObjectFactory.register('text', function (x, y, text, style) /***/ }), -/* 1039 */ +/* 1037 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152099,7 +149908,7 @@ GameObjectFactory.register('text', function (x, y, text, style) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var TileSprite = __webpack_require__(194); +var TileSprite = __webpack_require__(196); var GameObjectFactory = __webpack_require__(5); /** @@ -152134,7 +149943,7 @@ GameObjectFactory.register('tileSprite', function (x, y, width, height, key, fra /***/ }), -/* 1040 */ +/* 1038 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152143,7 +149952,7 @@ GameObjectFactory.register('tileSprite', function (x, y, width, height, key, fra * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Zone = __webpack_require__(106); +var Zone = __webpack_require__(110); var GameObjectFactory = __webpack_require__(5); /** @@ -152176,7 +149985,7 @@ GameObjectFactory.register('zone', function (x, y, width, height) /***/ }), -/* 1041 */ +/* 1039 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152185,7 +149994,7 @@ GameObjectFactory.register('zone', function (x, y, width, height) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Video = __webpack_require__(195); +var Video = __webpack_require__(197); var GameObjectFactory = __webpack_require__(5); /** @@ -152223,7 +150032,7 @@ GameObjectFactory.register('video', function (x, y, key) /***/ }), -/* 1042 */ +/* 1040 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152232,7 +150041,7 @@ GameObjectFactory.register('video', function (x, y, key) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Arc = __webpack_require__(403); +var Arc = __webpack_require__(402); var GameObjectFactory = __webpack_require__(5); /** @@ -152296,7 +150105,7 @@ GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlph /***/ }), -/* 1043 */ +/* 1041 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152306,7 +150115,7 @@ GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlph */ var GameObjectFactory = __webpack_require__(5); -var Curve = __webpack_require__(404); +var Curve = __webpack_require__(403); /** * Creates a new Curve Shape Game Object and adds it to the Scene. @@ -152346,7 +150155,7 @@ GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) /***/ }), -/* 1044 */ +/* 1042 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152355,7 +150164,7 @@ GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Ellipse = __webpack_require__(405); +var Ellipse = __webpack_require__(404); var GameObjectFactory = __webpack_require__(5); /** @@ -152398,7 +150207,7 @@ GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, /***/ }), -/* 1045 */ +/* 1043 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152408,7 +150217,7 @@ GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, */ var GameObjectFactory = __webpack_require__(5); -var Grid = __webpack_require__(406); +var Grid = __webpack_require__(405); /** * Creates a new Grid Shape Game Object and adds it to the Scene. @@ -152453,7 +150262,7 @@ GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cel /***/ }), -/* 1046 */ +/* 1044 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152463,7 +150272,7 @@ GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cel */ var GameObjectFactory = __webpack_require__(5); -var IsoBox = __webpack_require__(407); +var IsoBox = __webpack_require__(406); /** * Creates a new IsoBox Shape Game Object and adds it to the Scene. @@ -152504,7 +150313,7 @@ GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fill /***/ }), -/* 1047 */ +/* 1045 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152514,7 +150323,7 @@ GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fill */ var GameObjectFactory = __webpack_require__(5); -var IsoTriangle = __webpack_require__(408); +var IsoTriangle = __webpack_require__(407); /** * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. @@ -152557,7 +150366,7 @@ GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed /***/ }), -/* 1048 */ +/* 1046 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152567,7 +150376,7 @@ GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed */ var GameObjectFactory = __webpack_require__(5); -var Line = __webpack_require__(409); +var Line = __webpack_require__(408); /** * Creates a new Line Shape Game Object and adds it to the Scene. @@ -152608,7 +150417,7 @@ GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, /***/ }), -/* 1049 */ +/* 1047 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152618,7 +150427,7 @@ GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, */ var GameObjectFactory = __webpack_require__(5); -var Polygon = __webpack_require__(410); +var Polygon = __webpack_require__(409); /** * Creates a new Polygon Shape Game Object and adds it to the Scene. @@ -152661,7 +150470,7 @@ GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlp /***/ }), -/* 1050 */ +/* 1048 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152671,7 +150480,7 @@ GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlp */ var GameObjectFactory = __webpack_require__(5); -var Rectangle = __webpack_require__(415); +var Rectangle = __webpack_require__(414); /** * Creates a new Rectangle Shape Game Object and adds it to the Scene. @@ -152706,7 +150515,7 @@ GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor /***/ }), -/* 1051 */ +/* 1049 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152715,7 +150524,7 @@ GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Star = __webpack_require__(416); +var Star = __webpack_require__(415); var GameObjectFactory = __webpack_require__(5); /** @@ -152758,7 +150567,7 @@ GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRad /***/ }), -/* 1052 */ +/* 1050 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152768,7 +150577,7 @@ GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRad */ var GameObjectFactory = __webpack_require__(5); -var Triangle = __webpack_require__(417); +var Triangle = __webpack_require__(416); /** * Creates a new Triangle Shape Game Object and adds it to the Scene. @@ -152809,7 +150618,7 @@ GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, f /***/ }), -/* 1053 */ +/* 1051 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152818,9 +150627,9 @@ GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, f * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Blitter = __webpack_require__(183); +var Blitter = __webpack_require__(186); var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); /** @@ -152859,7 +150668,7 @@ GameObjectCreator.register('blitter', function (config, addToScene) /***/ }), -/* 1054 */ +/* 1052 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152870,8 +150679,8 @@ GameObjectCreator.register('blitter', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var Container = __webpack_require__(184); -var GameObjectCreator = __webpack_require__(17); +var Container = __webpack_require__(187); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); /** @@ -152908,7 +150717,7 @@ GameObjectCreator.register('container', function (config, addToScene) /***/ }), -/* 1055 */ +/* 1053 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152917,9 +150726,9 @@ GameObjectCreator.register('container', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(185); +var BitmapText = __webpack_require__(188); var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); /** @@ -152959,7 +150768,7 @@ GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) /***/ }), -/* 1056 */ +/* 1054 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152968,8 +150777,8 @@ GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); -var Graphics = __webpack_require__(186); +var GameObjectCreator = __webpack_require__(16); +var Graphics = __webpack_require__(189); /** * Creates a new Graphics Game Object and returns it. @@ -153007,7 +150816,7 @@ GameObjectCreator.register('graphics', function (config, addToScene) /***/ }), -/* 1057 */ +/* 1055 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153016,8 +150825,8 @@ GameObjectCreator.register('graphics', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); -var Group = __webpack_require__(95); +var GameObjectCreator = __webpack_require__(16); +var Group = __webpack_require__(97); /** * Creates a new Group Game Object and returns it. @@ -153040,7 +150849,7 @@ GameObjectCreator.register('group', function (config) /***/ }), -/* 1058 */ +/* 1056 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153050,9 +150859,9 @@ GameObjectCreator.register('group', function (config) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Image = __webpack_require__(103); +var Image = __webpack_require__(98); /** * Creates a new Image Game Object and returns it. @@ -153090,7 +150899,7 @@ GameObjectCreator.register('image', function (config, addToScene) /***/ }), -/* 1059 */ +/* 1057 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153099,10 +150908,10 @@ GameObjectCreator.register('image', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); var GetFastValue = __webpack_require__(2); -var ParticleEmitterManager = __webpack_require__(189); +var ParticleEmitterManager = __webpack_require__(192); /** * Creates a new Particle Emitter Manager Game Object and returns it. @@ -153147,7 +150956,7 @@ GameObjectCreator.register('particles', function (config, addToScene) /***/ }), -/* 1060 */ +/* 1058 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153157,9 +150966,9 @@ GameObjectCreator.register('particles', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var RenderTexture = __webpack_require__(190); +var RenderTexture = __webpack_require__(193); /** * Creates a new Render Texture Game Object and returns it. @@ -153199,7 +151008,7 @@ GameObjectCreator.register('renderTexture', function (config, addToScene) /***/ }), -/* 1061 */ +/* 1059 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153209,65 +151018,10 @@ GameObjectCreator.register('renderTexture', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var BuildGameObjectAnimation = __webpack_require__(385); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var GetValue = __webpack_require__(6); -var Rope = __webpack_require__(192); - -/** - * Creates a new Rope Game Object and returns it. - * - * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#rope - * @since 3.23.0 - * - * @param {object} 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.Rope} The Game Object that was created. - */ -GameObjectCreator.register('rope', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - var horizontal = GetAdvancedValue(config, 'horizontal', true); - var points = GetValue(config, 'points', undefined); - var colors = GetValue(config, 'colors', undefined); - var alphas = GetValue(config, 'alphas', undefined); - - var rope = new Rope(this.scene, 0, 0, key, frame, points, horizontal, colors, alphas); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, rope, config); - - return rope; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. - - -/***/ }), -/* 1062 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = __webpack_require__(28); -var BuildGameObjectAnimation = __webpack_require__(386); -var GameObjectCreator = __webpack_require__(17); -var GetAdvancedValue = __webpack_require__(15); -var Sprite = __webpack_require__(73); +var Sprite = __webpack_require__(69); /** * Creates a new Sprite Game Object and returns it. @@ -153307,7 +151061,7 @@ GameObjectCreator.register('sprite', function (config, addToScene) /***/ }), -/* 1063 */ +/* 1060 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153316,9 +151070,9 @@ GameObjectCreator.register('sprite', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(126); +var BitmapText = __webpack_require__(129); var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); var GetValue = __webpack_require__(6); @@ -153360,7 +151114,7 @@ GameObjectCreator.register('bitmapText', function (config, addToScene) /***/ }), -/* 1064 */ +/* 1061 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153370,9 +151124,9 @@ GameObjectCreator.register('bitmapText', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Text = __webpack_require__(193); +var Text = __webpack_require__(195); /** * Creates a new Text Game Object and returns it. @@ -153447,7 +151201,7 @@ GameObjectCreator.register('text', function (config, addToScene) /***/ }), -/* 1065 */ +/* 1062 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153457,9 +151211,9 @@ GameObjectCreator.register('text', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var TileSprite = __webpack_require__(194); +var TileSprite = __webpack_require__(196); /** * Creates a new TileSprite Game Object and returns it. @@ -153499,7 +151253,7 @@ GameObjectCreator.register('tileSprite', function (config, addToScene) /***/ }), -/* 1066 */ +/* 1063 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153508,9 +151262,9 @@ GameObjectCreator.register('tileSprite', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Zone = __webpack_require__(106); +var Zone = __webpack_require__(110); /** * Creates a new Zone Game Object and returns it. @@ -153538,7 +151292,7 @@ GameObjectCreator.register('zone', function (config) /***/ }), -/* 1067 */ +/* 1064 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153548,9 +151302,9 @@ GameObjectCreator.register('zone', function (config) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Video = __webpack_require__(195); +var Video = __webpack_require__(197); /** * Creates a new Video Game Object and returns it. @@ -153587,7 +151341,7 @@ GameObjectCreator.register('video', function (config, addToScene) /***/ }), -/* 1068 */ +/* 1065 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153601,12 +151355,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1069); + renderWebGL = __webpack_require__(1066); } if (true) { - renderCanvas = __webpack_require__(1070); + renderCanvas = __webpack_require__(1067); } module.exports = { @@ -153618,7 +151372,7 @@ module.exports = { /***/ }), -/* 1069 */ +/* 1066 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153627,7 +151381,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -153736,7 +151490,7 @@ module.exports = MeshWebGLRenderer; /***/ }), -/* 1070 */ +/* 1067 */ /***/ (function(module, exports) { /** @@ -153765,7 +151519,7 @@ module.exports = MeshCanvasRenderer; /***/ }), -/* 1071 */ +/* 1068 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153779,12 +151533,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1072); + renderWebGL = __webpack_require__(1069); } if (true) { - renderCanvas = __webpack_require__(1073); + renderCanvas = __webpack_require__(1070); } module.exports = { @@ -153796,7 +151550,7 @@ module.exports = { /***/ }), -/* 1072 */ +/* 1069 */ /***/ (function(module, exports) { /** @@ -153880,7 +151634,7 @@ module.exports = ShaderWebGLRenderer; /***/ }), -/* 1073 */ +/* 1070 */ /***/ (function(module, exports) { /** @@ -153909,7 +151663,7 @@ module.exports = ShaderCanvasRenderer; /***/ }), -/* 1074 */ +/* 1071 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153918,7 +151672,7 @@ module.exports = ShaderCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Mesh = __webpack_require__(128); +var Mesh = __webpack_require__(130); var GameObjectFactory = __webpack_require__(5); /** @@ -153959,7 +151713,7 @@ if (true) /***/ }), -/* 1075 */ +/* 1072 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153968,7 +151722,7 @@ if (true) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Quad = __webpack_require__(198); +var Quad = __webpack_require__(200); var GameObjectFactory = __webpack_require__(5); /** @@ -154005,7 +151759,7 @@ if (true) /***/ }), -/* 1076 */ +/* 1073 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154014,7 +151768,7 @@ if (true) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Shader = __webpack_require__(199); +var Shader = __webpack_require__(201); var GameObjectFactory = __webpack_require__(5); /** @@ -154046,7 +151800,7 @@ if (true) /***/ }), -/* 1077 */ +/* 1074 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154056,10 +151810,10 @@ if (true) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); var GetValue = __webpack_require__(6); -var Mesh = __webpack_require__(128); +var Mesh = __webpack_require__(130); /** * Creates a new Mesh Game Object and returns it. @@ -154101,7 +151855,7 @@ GameObjectCreator.register('mesh', function (config, addToScene) /***/ }), -/* 1078 */ +/* 1075 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154111,9 +151865,9 @@ GameObjectCreator.register('mesh', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Quad = __webpack_require__(198); +var Quad = __webpack_require__(200); /** * Creates a new Quad Game Object and returns it. @@ -154151,7 +151905,7 @@ GameObjectCreator.register('quad', function (config, addToScene) /***/ }), -/* 1079 */ +/* 1076 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154161,9 +151915,9 @@ GameObjectCreator.register('quad', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Shader = __webpack_require__(199); +var Shader = __webpack_require__(201); /** * Creates a new Shader Game Object and returns it. @@ -154204,7 +151958,7 @@ GameObjectCreator.register('shader', function (config, addToScene) /***/ }), -/* 1080 */ +/* 1077 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154214,9 +151968,9 @@ GameObjectCreator.register('shader', function (config, addToScene) */ var Class = __webpack_require__(0); -var LightsManager = __webpack_require__(422); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var LightsManager = __webpack_require__(421); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -154320,7 +152074,7 @@ module.exports = LightsPlugin; /***/ }), -/* 1081 */ +/* 1078 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154329,29 +152083,29 @@ module.exports = LightsPlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); -Circle.Area = __webpack_require__(1082); -Circle.Circumference = __webpack_require__(263); -Circle.CircumferencePoint = __webpack_require__(143); -Circle.Clone = __webpack_require__(1083); +Circle.Area = __webpack_require__(1079); +Circle.Circumference = __webpack_require__(265); +Circle.CircumferencePoint = __webpack_require__(146); +Circle.Clone = __webpack_require__(1080); Circle.Contains = __webpack_require__(55); -Circle.ContainsPoint = __webpack_require__(1084); -Circle.ContainsRect = __webpack_require__(1085); -Circle.CopyFrom = __webpack_require__(1086); -Circle.Equals = __webpack_require__(1087); -Circle.GetBounds = __webpack_require__(1088); -Circle.GetPoint = __webpack_require__(261); -Circle.GetPoints = __webpack_require__(262); -Circle.Offset = __webpack_require__(1089); -Circle.OffsetPoint = __webpack_require__(1090); -Circle.Random = __webpack_require__(144); +Circle.ContainsPoint = __webpack_require__(1081); +Circle.ContainsRect = __webpack_require__(1082); +Circle.CopyFrom = __webpack_require__(1083); +Circle.Equals = __webpack_require__(1084); +Circle.GetBounds = __webpack_require__(1085); +Circle.GetPoint = __webpack_require__(263); +Circle.GetPoints = __webpack_require__(264); +Circle.Offset = __webpack_require__(1086); +Circle.OffsetPoint = __webpack_require__(1087); +Circle.Random = __webpack_require__(147); module.exports = Circle; /***/ }), -/* 1082 */ +/* 1079 */ /***/ (function(module, exports) { /** @@ -154379,7 +152133,7 @@ module.exports = Area; /***/ }), -/* 1083 */ +/* 1080 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154388,7 +152142,7 @@ module.exports = Area; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); /** * Creates a new Circle instance based on the values contained in the given source. @@ -154409,7 +152163,7 @@ module.exports = Clone; /***/ }), -/* 1084 */ +/* 1081 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154440,7 +152194,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1085 */ +/* 1082 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154476,7 +152230,7 @@ module.exports = ContainsRect; /***/ }), -/* 1086 */ +/* 1083 */ /***/ (function(module, exports) { /** @@ -154508,7 +152262,7 @@ module.exports = CopyFrom; /***/ }), -/* 1087 */ +/* 1084 */ /***/ (function(module, exports) { /** @@ -154542,7 +152296,7 @@ module.exports = Equals; /***/ }), -/* 1088 */ +/* 1085 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154551,7 +152305,7 @@ module.exports = Equals; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Returns the bounds of the Circle object. @@ -154582,7 +152336,7 @@ module.exports = GetBounds; /***/ }), -/* 1089 */ +/* 1086 */ /***/ (function(module, exports) { /** @@ -154617,7 +152371,7 @@ module.exports = Offset; /***/ }), -/* 1090 */ +/* 1087 */ /***/ (function(module, exports) { /** @@ -154651,7 +152405,7 @@ module.exports = OffsetPoint; /***/ }), -/* 1091 */ +/* 1088 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154660,29 +152414,29 @@ module.exports = OffsetPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Ellipse = __webpack_require__(93); +var Ellipse = __webpack_require__(95); -Ellipse.Area = __webpack_require__(1092); -Ellipse.Circumference = __webpack_require__(393); -Ellipse.CircumferencePoint = __webpack_require__(188); -Ellipse.Clone = __webpack_require__(1093); -Ellipse.Contains = __webpack_require__(94); -Ellipse.ContainsPoint = __webpack_require__(1094); -Ellipse.ContainsRect = __webpack_require__(1095); -Ellipse.CopyFrom = __webpack_require__(1096); -Ellipse.Equals = __webpack_require__(1097); -Ellipse.GetBounds = __webpack_require__(1098); -Ellipse.GetPoint = __webpack_require__(391); -Ellipse.GetPoints = __webpack_require__(392); -Ellipse.Offset = __webpack_require__(1099); -Ellipse.OffsetPoint = __webpack_require__(1100); -Ellipse.Random = __webpack_require__(151); +Ellipse.Area = __webpack_require__(1089); +Ellipse.Circumference = __webpack_require__(392); +Ellipse.CircumferencePoint = __webpack_require__(191); +Ellipse.Clone = __webpack_require__(1090); +Ellipse.Contains = __webpack_require__(96); +Ellipse.ContainsPoint = __webpack_require__(1091); +Ellipse.ContainsRect = __webpack_require__(1092); +Ellipse.CopyFrom = __webpack_require__(1093); +Ellipse.Equals = __webpack_require__(1094); +Ellipse.GetBounds = __webpack_require__(1095); +Ellipse.GetPoint = __webpack_require__(390); +Ellipse.GetPoints = __webpack_require__(391); +Ellipse.Offset = __webpack_require__(1096); +Ellipse.OffsetPoint = __webpack_require__(1097); +Ellipse.Random = __webpack_require__(154); module.exports = Ellipse; /***/ }), -/* 1092 */ +/* 1089 */ /***/ (function(module, exports) { /** @@ -154716,7 +152470,7 @@ module.exports = Area; /***/ }), -/* 1093 */ +/* 1090 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154725,7 +152479,7 @@ module.exports = Area; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Ellipse = __webpack_require__(93); +var Ellipse = __webpack_require__(95); /** * Creates a new Ellipse instance based on the values contained in the given source. @@ -154746,7 +152500,7 @@ module.exports = Clone; /***/ }), -/* 1094 */ +/* 1091 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154755,7 +152509,7 @@ module.exports = Clone; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(94); +var Contains = __webpack_require__(96); /** * Check to see if the Ellipse contains the given Point object. @@ -154777,7 +152531,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1095 */ +/* 1092 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154786,7 +152540,7 @@ module.exports = ContainsPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(94); +var Contains = __webpack_require__(96); /** * Check to see if the Ellipse contains all four points of the given Rectangle object. @@ -154813,7 +152567,7 @@ module.exports = ContainsRect; /***/ }), -/* 1096 */ +/* 1093 */ /***/ (function(module, exports) { /** @@ -154845,7 +152599,7 @@ module.exports = CopyFrom; /***/ }), -/* 1097 */ +/* 1094 */ /***/ (function(module, exports) { /** @@ -154880,7 +152634,7 @@ module.exports = Equals; /***/ }), -/* 1098 */ +/* 1095 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154889,7 +152643,7 @@ module.exports = Equals; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Returns the bounds of the Ellipse object. @@ -154920,7 +152674,7 @@ module.exports = GetBounds; /***/ }), -/* 1099 */ +/* 1096 */ /***/ (function(module, exports) { /** @@ -154955,7 +152709,7 @@ module.exports = Offset; /***/ }), -/* 1100 */ +/* 1097 */ /***/ (function(module, exports) { /** @@ -154989,7 +152743,7 @@ module.exports = OffsetPoint; /***/ }), -/* 1101 */ +/* 1098 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155000,7 +152754,7 @@ module.exports = OffsetPoint; */ var Point = __webpack_require__(4); -var CircleToCircle = __webpack_require__(200); +var CircleToCircle = __webpack_require__(202); /** * Checks if two Circles intersect and returns the intersection points as a Point object array. @@ -155083,7 +152837,7 @@ module.exports = GetCircleToCircle; /***/ }), -/* 1102 */ +/* 1099 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155093,8 +152847,8 @@ module.exports = GetCircleToCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetLineToCircle = __webpack_require__(202); -var CircleToRectangle = __webpack_require__(201); +var GetLineToCircle = __webpack_require__(204); +var CircleToRectangle = __webpack_require__(203); /** * Checks for intersection between a circle and a rectangle, @@ -155133,7 +152887,7 @@ module.exports = GetCircleToRectangle; /***/ }), -/* 1103 */ +/* 1100 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155142,8 +152896,8 @@ module.exports = GetCircleToRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var RectangleToRectangle = __webpack_require__(129); +var Rectangle = __webpack_require__(11); +var RectangleToRectangle = __webpack_require__(131); /** * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. @@ -155182,7 +152936,7 @@ module.exports = GetRectangleIntersection; /***/ }), -/* 1104 */ +/* 1101 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155192,8 +152946,8 @@ module.exports = GetRectangleIntersection; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetLineToRectangle = __webpack_require__(204); -var RectangleToRectangle = __webpack_require__(129); +var GetLineToRectangle = __webpack_require__(206); +var RectangleToRectangle = __webpack_require__(131); /** * Checks if two Rectangles intersect and returns the intersection points as a Point object array. @@ -155233,7 +152987,7 @@ module.exports = GetRectangleToRectangle; /***/ }), -/* 1105 */ +/* 1102 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155243,8 +152997,8 @@ module.exports = GetRectangleToRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RectangleToTriangle = __webpack_require__(426); -var GetLineToRectangle = __webpack_require__(204); +var RectangleToTriangle = __webpack_require__(425); +var GetLineToRectangle = __webpack_require__(206); /** * Checks for intersection between Rectangle shape and Triangle shape, @@ -155281,7 +153035,7 @@ module.exports = GetRectangleToTriangle; /***/ }), -/* 1106 */ +/* 1103 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155291,8 +153045,8 @@ module.exports = GetRectangleToTriangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetLineToCircle = __webpack_require__(202); -var TriangleToCircle = __webpack_require__(428); +var GetLineToCircle = __webpack_require__(204); +var TriangleToCircle = __webpack_require__(427); /** * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. @@ -155330,7 +153084,7 @@ module.exports = GetTriangleToCircle; /***/ }), -/* 1107 */ +/* 1104 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155340,8 +153094,8 @@ module.exports = GetTriangleToCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var TriangleToTriangle = __webpack_require__(431); -var GetTriangleToLine = __webpack_require__(429); +var TriangleToTriangle = __webpack_require__(430); +var GetTriangleToLine = __webpack_require__(428); /** * Checks if two Triangles intersect, and returns the intersection points as a Point object array. @@ -155379,7 +153133,7 @@ module.exports = GetTriangleToTriangle; /***/ }), -/* 1108 */ +/* 1105 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155388,7 +153142,7 @@ module.exports = GetTriangleToTriangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PointToLine = __webpack_require__(433); +var PointToLine = __webpack_require__(432); /** * Checks if a Point is located on the given line segment. @@ -155420,7 +153174,7 @@ module.exports = PointToLineSegment; /***/ }), -/* 1109 */ +/* 1106 */ /***/ (function(module, exports) { /** @@ -155460,7 +153214,7 @@ module.exports = RectangleToValues; /***/ }), -/* 1110 */ +/* 1107 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155471,41 +153225,40 @@ module.exports = RectangleToValues; var Line = __webpack_require__(56); -Line.Angle = __webpack_require__(83); -Line.BresenhamPoints = __webpack_require__(283); -Line.CenterOn = __webpack_require__(1111); -Line.Clone = __webpack_require__(1112); -Line.CopyFrom = __webpack_require__(1113); -Line.Equals = __webpack_require__(1114); -Line.Extend = __webpack_require__(1115); -Line.GetEasedPoints = __webpack_require__(1116); -Line.GetMidPoint = __webpack_require__(1117); -Line.GetNearestPoint = __webpack_require__(1118); -Line.GetNormal = __webpack_require__(1119); -Line.GetPoint = __webpack_require__(270); -Line.GetPoints = __webpack_require__(147); -Line.GetShortestDistance = __webpack_require__(1120); -Line.Height = __webpack_require__(1121); +Line.Angle = __webpack_require__(85); +Line.BresenhamPoints = __webpack_require__(285); +Line.CenterOn = __webpack_require__(1108); +Line.Clone = __webpack_require__(1109); +Line.CopyFrom = __webpack_require__(1110); +Line.Equals = __webpack_require__(1111); +Line.Extend = __webpack_require__(1112); +Line.GetMidPoint = __webpack_require__(1113); +Line.GetNearestPoint = __webpack_require__(1114); +Line.GetNormal = __webpack_require__(1115); +Line.GetPoint = __webpack_require__(272); +Line.GetPoints = __webpack_require__(150); +Line.GetShortestDistance = __webpack_require__(1116); +Line.Height = __webpack_require__(1117); Line.Length = __webpack_require__(57); -Line.NormalAngle = __webpack_require__(434); -Line.NormalX = __webpack_require__(1122); -Line.NormalY = __webpack_require__(1123); -Line.Offset = __webpack_require__(1124); -Line.PerpSlope = __webpack_require__(1125); -Line.Random = __webpack_require__(148); -Line.ReflectAngle = __webpack_require__(1126); -Line.Rotate = __webpack_require__(1127); -Line.RotateAroundPoint = __webpack_require__(1128); -Line.RotateAroundXY = __webpack_require__(206); -Line.SetToAngle = __webpack_require__(1129); -Line.Slope = __webpack_require__(1130); -Line.Width = __webpack_require__(1131); +Line.NormalAngle = __webpack_require__(433); +Line.NormalX = __webpack_require__(1118); +Line.NormalY = __webpack_require__(1119); +Line.Offset = __webpack_require__(1120); +Line.PerpSlope = __webpack_require__(1121); +Line.Random = __webpack_require__(151); +Line.ReflectAngle = __webpack_require__(1122); +Line.Rotate = __webpack_require__(1123); +Line.RotateAroundPoint = __webpack_require__(1124); +Line.RotateAroundXY = __webpack_require__(208); +Line.SetToAngle = __webpack_require__(1125); +Line.Slope = __webpack_require__(1126); +Line.Width = __webpack_require__(1127); module.exports = Line; /***/ }), -/* 1111 */ +/* 1108 */ /***/ (function(module, exports) { /** @@ -155545,7 +153298,7 @@ module.exports = CenterOn; /***/ }), -/* 1112 */ +/* 1109 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155575,7 +153328,7 @@ module.exports = Clone; /***/ }), -/* 1113 */ +/* 1110 */ /***/ (function(module, exports) { /** @@ -155606,7 +153359,7 @@ module.exports = CopyFrom; /***/ }), -/* 1114 */ +/* 1111 */ /***/ (function(module, exports) { /** @@ -155640,7 +153393,7 @@ module.exports = Equals; /***/ }), -/* 1115 */ +/* 1112 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155698,127 +153451,7 @@ module.exports = Extend; /***/ }), -/* 1116 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DistanceBetweenPoints = __webpack_require__(314); -var GetEaseFunction = __webpack_require__(67); -var Point = __webpack_require__(4); - -/** - * 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.Geom.Point[]} 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 {integer} 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 noisey eases. - * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. - * - * @return {Phaser.Geom.Point[]} An array of Geom.Points containing the coordinates of the points on the line. - */ -var GetEasedPoints = function (line, ease, quantity, collinearThreshold, easeParams) -{ - if (collinearThreshold === undefined) { collinearThreshold = 0; } - if (easeParams === undefined) { easeParams = []; } - - var results = []; - - var x1 = line.x1; - var y1 = line.y1; - - var spaceX = line.x2 - x1; - var spaceY = line.y2 - y1; - - var easeFunc = GetEaseFunction(ease, easeParams); - - var i; - var v; - var q = quantity - 1; - - for (i = 0; i < q; i++) - { - v = easeFunc(i / q); - - results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); - } - - // Always include the end of the line - v = easeFunc(1); - - results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); - - // Remove collinear parts - if (collinearThreshold > 0) - { - var prevPoint = results[0]; - - // Store the new results here - var sortedResults = [ prevPoint ]; - - for (i = 1; i < results.length - 1; i++) - { - var point = results[i]; - - if (DistanceBetweenPoints(prevPoint, point) >= collinearThreshold) - { - sortedResults.push(point); - prevPoint = point; - } - } - - // Top and tail - var endPoint = results[results.length - 1]; - - if (DistanceBetweenPoints(prevPoint, endPoint) < collinearThreshold) - { - sortedResults.pop(); - } - - sortedResults.push(endPoint); - - return sortedResults; - } - else - { - return results; - } -}; - -module.exports = GetEasedPoints; - - -/***/ }), -/* 1117 */ +/* 1113 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155856,7 +153489,7 @@ module.exports = GetMidPoint; /***/ }), -/* 1118 */ +/* 1114 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155911,7 +153544,7 @@ module.exports = GetNearestPoint; /***/ }), -/* 1119 */ +/* 1115 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155920,8 +153553,8 @@ module.exports = GetNearestPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var Angle = __webpack_require__(83); +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(85); var Point = __webpack_require__(4); /** @@ -155955,7 +153588,7 @@ module.exports = GetNormal; /***/ }), -/* 1120 */ +/* 1116 */ /***/ (function(module, exports) { /** @@ -156002,7 +153635,7 @@ module.exports = GetShortestDistance; /***/ }), -/* 1121 */ +/* 1117 */ /***/ (function(module, exports) { /** @@ -156030,7 +153663,7 @@ module.exports = Height; /***/ }), -/* 1122 */ +/* 1118 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156039,18 +153672,18 @@ module.exports = Height; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var Angle = __webpack_require__(83); +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(85); /** - * Returns the x component of the normal vector of the given line. + * [description] * * @function Phaser.Geom.Line.NormalX * @since 3.0.0 * * @param {Phaser.Geom.Line} line - The Line object to get the normal value from. * - * @return {number} The x component of the normal vector of the line. + * @return {number} [description] */ var NormalX = function (line) { @@ -156061,7 +153694,7 @@ module.exports = NormalX; /***/ }), -/* 1123 */ +/* 1119 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156070,8 +153703,8 @@ module.exports = NormalX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var Angle = __webpack_require__(83); +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(85); /** * The Y value of the normal of the given line. @@ -156093,7 +153726,7 @@ module.exports = NormalY; /***/ }), -/* 1124 */ +/* 1120 */ /***/ (function(module, exports) { /** @@ -156131,7 +153764,7 @@ module.exports = Offset; /***/ }), -/* 1125 */ +/* 1121 */ /***/ (function(module, exports) { /** @@ -156159,7 +153792,7 @@ module.exports = PerpSlope; /***/ }), -/* 1126 */ +/* 1122 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156168,8 +153801,8 @@ module.exports = PerpSlope; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Angle = __webpack_require__(83); -var NormalAngle = __webpack_require__(434); +var Angle = __webpack_require__(85); +var NormalAngle = __webpack_require__(433); /** * Calculate the reflected angle between two lines. @@ -156193,7 +153826,7 @@ module.exports = ReflectAngle; /***/ }), -/* 1127 */ +/* 1123 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156202,7 +153835,7 @@ module.exports = ReflectAngle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(206); +var RotateAroundXY = __webpack_require__(208); /** * Rotate a line around its midpoint by the given angle in radians. @@ -156229,7 +153862,7 @@ module.exports = Rotate; /***/ }), -/* 1128 */ +/* 1124 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156238,7 +153871,7 @@ module.exports = Rotate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(206); +var RotateAroundXY = __webpack_require__(208); /** * Rotate a line around a point by the given angle in radians. @@ -156263,7 +153896,7 @@ module.exports = RotateAroundPoint; /***/ }), -/* 1129 */ +/* 1125 */ /***/ (function(module, exports) { /** @@ -156303,7 +153936,7 @@ module.exports = SetToAngle; /***/ }), -/* 1130 */ +/* 1126 */ /***/ (function(module, exports) { /** @@ -156331,7 +153964,7 @@ module.exports = Slope; /***/ }), -/* 1131 */ +/* 1127 */ /***/ (function(module, exports) { /** @@ -156359,7 +153992,7 @@ module.exports = Width; /***/ }), -/* 1132 */ +/* 1128 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156370,27 +154003,27 @@ module.exports = Width; var Point = __webpack_require__(4); -Point.Ceil = __webpack_require__(1133); -Point.Clone = __webpack_require__(1134); -Point.CopyFrom = __webpack_require__(1135); -Point.Equals = __webpack_require__(1136); -Point.Floor = __webpack_require__(1137); -Point.GetCentroid = __webpack_require__(1138); -Point.GetMagnitude = __webpack_require__(435); -Point.GetMagnitudeSq = __webpack_require__(436); -Point.GetRectangleFromPoints = __webpack_require__(1139); -Point.Interpolate = __webpack_require__(1140); -Point.Invert = __webpack_require__(1141); -Point.Negative = __webpack_require__(1142); -Point.Project = __webpack_require__(1143); -Point.ProjectUnit = __webpack_require__(1144); -Point.SetMagnitude = __webpack_require__(1145); +Point.Ceil = __webpack_require__(1129); +Point.Clone = __webpack_require__(1130); +Point.CopyFrom = __webpack_require__(1131); +Point.Equals = __webpack_require__(1132); +Point.Floor = __webpack_require__(1133); +Point.GetCentroid = __webpack_require__(1134); +Point.GetMagnitude = __webpack_require__(434); +Point.GetMagnitudeSq = __webpack_require__(435); +Point.GetRectangleFromPoints = __webpack_require__(1135); +Point.Interpolate = __webpack_require__(1136); +Point.Invert = __webpack_require__(1137); +Point.Negative = __webpack_require__(1138); +Point.Project = __webpack_require__(1139); +Point.ProjectUnit = __webpack_require__(1140); +Point.SetMagnitude = __webpack_require__(1141); module.exports = Point; /***/ }), -/* 1133 */ +/* 1129 */ /***/ (function(module, exports) { /** @@ -156420,7 +154053,7 @@ module.exports = Ceil; /***/ }), -/* 1134 */ +/* 1130 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156450,7 +154083,7 @@ module.exports = Clone; /***/ }), -/* 1135 */ +/* 1131 */ /***/ (function(module, exports) { /** @@ -156481,7 +154114,7 @@ module.exports = CopyFrom; /***/ }), -/* 1136 */ +/* 1132 */ /***/ (function(module, exports) { /** @@ -156510,7 +154143,7 @@ module.exports = Equals; /***/ }), -/* 1137 */ +/* 1133 */ /***/ (function(module, exports) { /** @@ -156540,7 +154173,7 @@ module.exports = Floor; /***/ }), -/* 1138 */ +/* 1134 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156560,10 +154193,10 @@ var Point = __webpack_require__(4); * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the geometric center of. - * @param {Phaser.Geom.Point} [out] - A Point object to store the output coordinates in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Point[]} points - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object representing the geometric center of the given points. + * @return {Phaser.Geom.Point} [description] */ var GetCentroid = function (points, out) { @@ -156604,7 +154237,7 @@ module.exports = GetCentroid; /***/ }), -/* 1139 */ +/* 1135 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156613,7 +154246,7 @@ module.exports = GetCentroid; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. @@ -156623,10 +154256,10 @@ var Rectangle = __webpack_require__(13); * * @generic {Phaser.Geom.Rectangle} O - [out,$return] * - * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the AABB from. - * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the results in. If not given, a new Rectangle instance is created. + * @param {Phaser.Geom.Point[]} points - [description] + * @param {Phaser.Geom.Rectangle} [out] - [description] * - * @return {Phaser.Geom.Rectangle} A Rectangle object holding the AABB values for the given points. + * @return {Phaser.Geom.Rectangle} [description] */ var GetRectangleFromPoints = function (points, out) { @@ -156674,7 +154307,7 @@ module.exports = GetRectangleFromPoints; /***/ }), -/* 1140 */ +/* 1136 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156686,7 +154319,7 @@ module.exports = GetRectangleFromPoints; var Point = __webpack_require__(4); /** - * Returns the linear interpolation point between the two given points, based on `t`. + * [description] * * @function Phaser.Geom.Point.Interpolate * @since 3.0.0 @@ -156715,7 +154348,7 @@ module.exports = Interpolate; /***/ }), -/* 1141 */ +/* 1137 */ /***/ (function(module, exports) { /** @@ -156745,7 +154378,7 @@ module.exports = Invert; /***/ }), -/* 1142 */ +/* 1138 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156780,7 +154413,7 @@ module.exports = Negative; /***/ }), -/* 1143 */ +/* 1139 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156790,22 +154423,21 @@ module.exports = Negative; */ var Point = __webpack_require__(4); -var GetMagnitudeSq = __webpack_require__(436); +var GetMagnitudeSq = __webpack_require__(435); /** - * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the - * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. + * [description] * * @function Phaser.Geom.Point.Project * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. - * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Point} pointA - [description] + * @param {Phaser.Geom.Point} pointB - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. + * @return {Phaser.Geom.Point} [description] */ var Project = function (pointA, pointB, out) { @@ -156827,7 +154459,7 @@ module.exports = Project; /***/ }), -/* 1144 */ +/* 1140 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156839,19 +154471,18 @@ module.exports = Project; var Point = __webpack_require__(4); /** - * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the - * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. + * [description] * * @function Phaser.Geom.Point.ProjectUnit * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. Must be a normalized point with a magnitude of 1. - * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Point} pointA - [description] + * @param {Phaser.Geom.Point} pointB - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A unit Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. + * @return {Phaser.Geom.Point} [description] */ var ProjectUnit = function (pointA, pointB, out) { @@ -156872,7 +154503,7 @@ module.exports = ProjectUnit; /***/ }), -/* 1145 */ +/* 1141 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156881,7 +154512,7 @@ module.exports = ProjectUnit; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetMagnitude = __webpack_require__(435); +var GetMagnitude = __webpack_require__(434); /** * Changes the magnitude (length) of a two-dimensional vector without changing its direction. @@ -156916,7 +154547,7 @@ module.exports = SetMagnitude; /***/ }), -/* 1146 */ +/* 1142 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156925,23 +154556,23 @@ module.exports = SetMagnitude; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Polygon = __webpack_require__(196); +var Polygon = __webpack_require__(198); -Polygon.Clone = __webpack_require__(1147); -Polygon.Contains = __webpack_require__(197); -Polygon.ContainsPoint = __webpack_require__(1148); -Polygon.GetAABB = __webpack_require__(411); -Polygon.GetNumberArray = __webpack_require__(1149); -Polygon.GetPoints = __webpack_require__(412); -Polygon.Perimeter = __webpack_require__(413); -Polygon.Reverse = __webpack_require__(1150); -Polygon.Smooth = __webpack_require__(414); +Polygon.Clone = __webpack_require__(1143); +Polygon.Contains = __webpack_require__(199); +Polygon.ContainsPoint = __webpack_require__(1144); +Polygon.GetAABB = __webpack_require__(410); +Polygon.GetNumberArray = __webpack_require__(1145); +Polygon.GetPoints = __webpack_require__(411); +Polygon.Perimeter = __webpack_require__(412); +Polygon.Reverse = __webpack_require__(1146); +Polygon.Smooth = __webpack_require__(413); module.exports = Polygon; /***/ }), -/* 1147 */ +/* 1143 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156950,7 +154581,7 @@ module.exports = Polygon; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Polygon = __webpack_require__(196); +var Polygon = __webpack_require__(198); /** * Create a new polygon which is a copy of the specified polygon @@ -156971,7 +154602,7 @@ module.exports = Clone; /***/ }), -/* 1148 */ +/* 1144 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156980,18 +154611,18 @@ module.exports = Clone; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(197); +var Contains = __webpack_require__(199); /** - * Checks the given Point again the Polygon to see if the Point lays within its vertices. + * [description] * * @function Phaser.Geom.Polygon.ContainsPoint * @since 3.0.0 * - * @param {Phaser.Geom.Polygon} polygon - The Polygon to check. - * @param {Phaser.Geom.Point} point - The Point to check if it's within the Polygon. + * @param {Phaser.Geom.Polygon} polygon - [description] + * @param {Phaser.Geom.Point} point - [description] * - * @return {boolean} `true` if the Point is within the Polygon, otherwise `false`. + * @return {boolean} [description] */ var ContainsPoint = function (polygon, point) { @@ -157002,7 +154633,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1149 */ +/* 1145 */ /***/ (function(module, exports) { /** @@ -157045,7 +154676,7 @@ module.exports = GetNumberArray; /***/ }), -/* 1150 */ +/* 1146 */ /***/ (function(module, exports) { /** @@ -157077,7 +154708,7 @@ module.exports = Reverse; /***/ }), -/* 1151 */ +/* 1147 */ /***/ (function(module, exports) { /** @@ -157105,7 +154736,7 @@ module.exports = Area; /***/ }), -/* 1152 */ +/* 1148 */ /***/ (function(module, exports) { /** @@ -157138,7 +154769,7 @@ module.exports = Ceil; /***/ }), -/* 1153 */ +/* 1149 */ /***/ (function(module, exports) { /** @@ -157173,7 +154804,7 @@ module.exports = CeilAll; /***/ }), -/* 1154 */ +/* 1150 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157182,7 +154813,7 @@ module.exports = CeilAll; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Creates a new Rectangle which is identical to the given one. @@ -157203,7 +154834,7 @@ module.exports = Clone; /***/ }), -/* 1155 */ +/* 1151 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157234,7 +154865,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1156 */ +/* 1152 */ /***/ (function(module, exports) { /** @@ -157265,7 +154896,7 @@ module.exports = CopyFrom; /***/ }), -/* 1157 */ +/* 1153 */ /***/ (function(module, exports) { /** @@ -157299,7 +154930,7 @@ module.exports = Equals; /***/ }), -/* 1158 */ +/* 1154 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157308,7 +154939,7 @@ module.exports = Equals; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetAspectRatio = __webpack_require__(207); +var GetAspectRatio = __webpack_require__(209); /** * Adjusts the target rectangle, changing its width, height and position, @@ -157352,7 +154983,7 @@ module.exports = FitInside; /***/ }), -/* 1159 */ +/* 1155 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157361,7 +154992,7 @@ module.exports = FitInside; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetAspectRatio = __webpack_require__(207); +var GetAspectRatio = __webpack_require__(209); /** * Adjusts the target rectangle, changing its width, height and position, @@ -157405,7 +155036,7 @@ module.exports = FitOutside; /***/ }), -/* 1160 */ +/* 1156 */ /***/ (function(module, exports) { /** @@ -157438,7 +155069,7 @@ module.exports = Floor; /***/ }), -/* 1161 */ +/* 1157 */ /***/ (function(module, exports) { /** @@ -157473,7 +155104,7 @@ module.exports = FloorAll; /***/ }), -/* 1162 */ +/* 1158 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157511,7 +155142,7 @@ module.exports = GetCenter; /***/ }), -/* 1163 */ +/* 1159 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157524,18 +155155,18 @@ var Point = __webpack_require__(4); /** - * Returns the size of the Rectangle, expressed as a Point object. - * With the value of the `width` as the `x` property and the `height` as the `y` property. + * The size of the Rectangle object, expressed as a Point object + * with the values of the width and height properties. * * @function Phaser.Geom.Rectangle.GetSize * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the size from. - * @param {(Phaser.Geom.Point|object)} [out] - The Point object to store the size in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Rectangle} rect - [description] + * @param {(Phaser.Geom.Point|object)} [out] - [description] * - * @return {(Phaser.Geom.Point|object)} A Point object where `x` holds the width and `y` holds the height of the Rectangle. + * @return {(Phaser.Geom.Point|object)} [description] */ var GetSize = function (rect, out) { @@ -157551,7 +155182,7 @@ module.exports = GetSize; /***/ }), -/* 1164 */ +/* 1160 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157560,7 +155191,7 @@ module.exports = GetSize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CenterOn = __webpack_require__(162); +var CenterOn = __webpack_require__(165); /** @@ -157593,7 +155224,7 @@ module.exports = Inflate; /***/ }), -/* 1165 */ +/* 1161 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157602,8 +155233,8 @@ module.exports = Inflate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var Intersects = __webpack_require__(129); +var Rectangle = __webpack_require__(11); +var Intersects = __webpack_require__(131); /** * Takes two Rectangles and first checks to see if they intersect. @@ -157644,7 +155275,7 @@ module.exports = Intersection; /***/ }), -/* 1166 */ +/* 1162 */ /***/ (function(module, exports) { /** @@ -157693,7 +155324,7 @@ module.exports = MergePoints; /***/ }), -/* 1167 */ +/* 1163 */ /***/ (function(module, exports) { /** @@ -157740,7 +155371,7 @@ module.exports = MergeRect; /***/ }), -/* 1168 */ +/* 1164 */ /***/ (function(module, exports) { /** @@ -157784,7 +155415,7 @@ module.exports = MergeXY; /***/ }), -/* 1169 */ +/* 1165 */ /***/ (function(module, exports) { /** @@ -157819,7 +155450,7 @@ module.exports = Offset; /***/ }), -/* 1170 */ +/* 1166 */ /***/ (function(module, exports) { /** @@ -157853,7 +155484,7 @@ module.exports = OffsetPoint; /***/ }), -/* 1171 */ +/* 1167 */ /***/ (function(module, exports) { /** @@ -157887,7 +155518,7 @@ module.exports = Overlaps; /***/ }), -/* 1172 */ +/* 1168 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157900,18 +155531,18 @@ var Point = __webpack_require__(4); var DegToRad = __webpack_require__(35); /** - * Returns a Point from the perimeter of a Rectangle based on the given angle. + * [description] * * @function Phaser.Geom.Rectangle.PerimeterPoint * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. - * @param {integer} angle - The angle of the point, in degrees. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Rectangle} rectangle - [description] + * @param {integer} angle - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of the Rectangle perimeter. + * @return {Phaser.Geom.Point} [description] */ var PerimeterPoint = function (rectangle, angle, out) { @@ -157944,7 +155575,7 @@ module.exports = PerimeterPoint; /***/ }), -/* 1173 */ +/* 1169 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157953,8 +155584,8 @@ module.exports = PerimeterPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Between = __webpack_require__(167); -var ContainsRect = __webpack_require__(438); +var Between = __webpack_require__(170); +var ContainsRect = __webpack_require__(437); var Point = __webpack_require__(4); /** @@ -158015,7 +155646,7 @@ module.exports = RandomOutside; /***/ }), -/* 1174 */ +/* 1170 */ /***/ (function(module, exports) { /** @@ -158044,7 +155675,7 @@ module.exports = SameDimensions; /***/ }), -/* 1175 */ +/* 1171 */ /***/ (function(module, exports) { /** @@ -158083,7 +155714,7 @@ module.exports = Scale; /***/ }), -/* 1176 */ +/* 1172 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158092,38 +155723,38 @@ module.exports = Scale; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); -Triangle.Area = __webpack_require__(1177); -Triangle.BuildEquilateral = __webpack_require__(1178); -Triangle.BuildFromPolygon = __webpack_require__(1179); -Triangle.BuildRight = __webpack_require__(1180); -Triangle.CenterOn = __webpack_require__(1181); -Triangle.Centroid = __webpack_require__(439); -Triangle.CircumCenter = __webpack_require__(1182); -Triangle.CircumCircle = __webpack_require__(1183); -Triangle.Clone = __webpack_require__(1184); -Triangle.Contains = __webpack_require__(81); -Triangle.ContainsArray = __webpack_require__(205); -Triangle.ContainsPoint = __webpack_require__(1185); -Triangle.CopyFrom = __webpack_require__(1186); -Triangle.Decompose = __webpack_require__(432); -Triangle.Equals = __webpack_require__(1187); -Triangle.GetPoint = __webpack_require__(418); -Triangle.GetPoints = __webpack_require__(419); -Triangle.InCenter = __webpack_require__(441); -Triangle.Perimeter = __webpack_require__(1188); -Triangle.Offset = __webpack_require__(440); -Triangle.Random = __webpack_require__(152); -Triangle.Rotate = __webpack_require__(1189); -Triangle.RotateAroundPoint = __webpack_require__(1190); -Triangle.RotateAroundXY = __webpack_require__(208); +Triangle.Area = __webpack_require__(1173); +Triangle.BuildEquilateral = __webpack_require__(1174); +Triangle.BuildFromPolygon = __webpack_require__(1175); +Triangle.BuildRight = __webpack_require__(1176); +Triangle.CenterOn = __webpack_require__(1177); +Triangle.Centroid = __webpack_require__(438); +Triangle.CircumCenter = __webpack_require__(1178); +Triangle.CircumCircle = __webpack_require__(1179); +Triangle.Clone = __webpack_require__(1180); +Triangle.Contains = __webpack_require__(83); +Triangle.ContainsArray = __webpack_require__(207); +Triangle.ContainsPoint = __webpack_require__(1181); +Triangle.CopyFrom = __webpack_require__(1182); +Triangle.Decompose = __webpack_require__(431); +Triangle.Equals = __webpack_require__(1183); +Triangle.GetPoint = __webpack_require__(417); +Triangle.GetPoints = __webpack_require__(418); +Triangle.InCenter = __webpack_require__(440); +Triangle.Perimeter = __webpack_require__(1184); +Triangle.Offset = __webpack_require__(439); +Triangle.Random = __webpack_require__(155); +Triangle.Rotate = __webpack_require__(1185); +Triangle.RotateAroundPoint = __webpack_require__(1186); +Triangle.RotateAroundXY = __webpack_require__(210); module.exports = Triangle; /***/ }), -/* 1177 */ +/* 1173 */ /***/ (function(module, exports) { /** @@ -158162,7 +155793,7 @@ module.exports = Area; /***/ }), -/* 1178 */ +/* 1174 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158171,7 +155802,7 @@ module.exports = Area; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); /** * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). @@ -158206,7 +155837,7 @@ module.exports = BuildEquilateral; /***/ }), -/* 1179 */ +/* 1175 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158215,12 +155846,11 @@ module.exports = BuildEquilateral; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var EarCut = __webpack_require__(64); -var Triangle = __webpack_require__(69); +var EarCut = __webpack_require__(66); +var Triangle = __webpack_require__(71); /** - * 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. + * [description] * * @function Phaser.Geom.Triangle.BuildFromPolygon * @since 3.0.0 @@ -158229,11 +155859,11 @@ var Triangle = __webpack_require__(69); * * @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. + * @param {number} [scaleX=1] - [description] + * @param {number} [scaleY=1] - [description] + * @param {(array|Phaser.Geom.Triangle[])} [out] - [description] * - * @return {(array|Phaser.Geom.Triangle[])} An array of Triangle instances, where each triangle is based on the decomposed vertices data. + * @return {(array|Phaser.Geom.Triangle[])} [description] */ var BuildFromPolygon = function (data, holes, scaleX, scaleY, out) { @@ -158282,7 +155912,7 @@ module.exports = BuildFromPolygon; /***/ }), -/* 1180 */ +/* 1176 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158291,7 +155921,7 @@ module.exports = BuildFromPolygon; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); // 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) @@ -158331,7 +155961,7 @@ module.exports = BuildRight; /***/ }), -/* 1181 */ +/* 1177 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158340,8 +155970,8 @@ module.exports = BuildRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Centroid = __webpack_require__(439); -var Offset = __webpack_require__(440); +var Centroid = __webpack_require__(438); +var Offset = __webpack_require__(439); /** * @callback CenterFunction @@ -158384,7 +156014,7 @@ module.exports = CenterOn; /***/ }), -/* 1182 */ +/* 1178 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158428,10 +156058,10 @@ function det (m00, m01, m10, m11) * * @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. + * @param {Phaser.Geom.Triangle} triangle - [description] + * @param {Phaser.Math.Vector2} [out] - [description] * - * @return {Phaser.Math.Vector2} A Vector2 object holding the coordinates of the circumcenter of the Triangle. + * @return {Phaser.Math.Vector2} [description] */ var CircumCenter = function (triangle, out) { @@ -158460,7 +156090,7 @@ module.exports = CircumCenter; /***/ }), -/* 1183 */ +/* 1179 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158469,7 +156099,7 @@ module.exports = CircumCenter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); // Adapted from https://gist.github.com/mutoo/5617691 @@ -158543,7 +156173,7 @@ module.exports = CircumCircle; /***/ }), -/* 1184 */ +/* 1180 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158552,7 +156182,7 @@ module.exports = CircumCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); /** * Clones a Triangle object. @@ -158573,7 +156203,7 @@ module.exports = Clone; /***/ }), -/* 1185 */ +/* 1181 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158582,7 +156212,7 @@ module.exports = Clone; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(81); +var Contains = __webpack_require__(83); /** * Tests if a triangle contains a point. @@ -158604,7 +156234,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1186 */ +/* 1182 */ /***/ (function(module, exports) { /** @@ -158635,7 +156265,7 @@ module.exports = CopyFrom; /***/ }), -/* 1187 */ +/* 1183 */ /***/ (function(module, exports) { /** @@ -158671,7 +156301,7 @@ module.exports = Equals; /***/ }), -/* 1188 */ +/* 1184 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158682,16 +156312,17 @@ module.exports = Equals; var Length = __webpack_require__(57); +// The 2D area of a triangle. The area value is always non-negative. + /** * Gets the length of the perimeter of the given triangle. - * Calculated by adding together the length of each of the three sides. * * @function Phaser.Geom.Triangle.Perimeter * @since 3.0.0 * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the length from. + * @param {Phaser.Geom.Triangle} triangle - [description] * - * @return {number} The length of the Triangle. + * @return {number} [description] */ var Perimeter = function (triangle) { @@ -158706,7 +156337,7 @@ module.exports = Perimeter; /***/ }), -/* 1189 */ +/* 1185 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158715,8 +156346,8 @@ module.exports = Perimeter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(208); -var InCenter = __webpack_require__(441); +var RotateAroundXY = __webpack_require__(210); +var InCenter = __webpack_require__(440); /** * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. @@ -158742,7 +156373,7 @@ module.exports = Rotate; /***/ }), -/* 1190 */ +/* 1186 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158751,7 +156382,7 @@ module.exports = Rotate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(208); +var RotateAroundXY = __webpack_require__(210); /** * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. @@ -158776,7 +156407,7 @@ module.exports = RotateAroundPoint; /***/ }), -/* 1191 */ +/* 1187 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158785,8 +156416,8 @@ module.exports = RotateAroundPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(174); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(177); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Input @@ -158794,16 +156425,16 @@ var Extend = __webpack_require__(18); var Input = { - CreateInteractiveObject: __webpack_require__(442), + CreateInteractiveObject: __webpack_require__(441), Events: __webpack_require__(54), - Gamepad: __webpack_require__(1192), - InputManager: __webpack_require__(360), - InputPlugin: __webpack_require__(1204), - InputPluginCache: __webpack_require__(130), - Keyboard: __webpack_require__(1206), - Mouse: __webpack_require__(1223), - Pointer: __webpack_require__(363), - Touch: __webpack_require__(1224) + Gamepad: __webpack_require__(1188), + InputManager: __webpack_require__(359), + InputPlugin: __webpack_require__(1200), + InputPluginCache: __webpack_require__(132), + Keyboard: __webpack_require__(1202), + Mouse: __webpack_require__(1219), + Pointer: __webpack_require__(362), + Touch: __webpack_require__(1220) }; @@ -158814,7 +156445,7 @@ module.exports = Input; /***/ }), -/* 1192 */ +/* 1188 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158829,18 +156460,18 @@ module.exports = Input; module.exports = { - Axis: __webpack_require__(443), - Button: __webpack_require__(444), - Events: __webpack_require__(209), - Gamepad: __webpack_require__(445), - GamepadPlugin: __webpack_require__(1199), + Axis: __webpack_require__(442), + Button: __webpack_require__(443), + Events: __webpack_require__(211), + Gamepad: __webpack_require__(444), + GamepadPlugin: __webpack_require__(1195), - Configs: __webpack_require__(1200) + Configs: __webpack_require__(1196) }; /***/ }), -/* 1193 */ +/* 1189 */ /***/ (function(module, exports) { /** @@ -158869,7 +156500,7 @@ module.exports = 'down'; /***/ }), -/* 1194 */ +/* 1190 */ /***/ (function(module, exports) { /** @@ -158898,7 +156529,7 @@ module.exports = 'up'; /***/ }), -/* 1195 */ +/* 1191 */ /***/ (function(module, exports) { /** @@ -158929,7 +156560,7 @@ module.exports = 'connected'; /***/ }), -/* 1196 */ +/* 1192 */ /***/ (function(module, exports) { /** @@ -158955,7 +156586,7 @@ module.exports = 'disconnected'; /***/ }), -/* 1197 */ +/* 1193 */ /***/ (function(module, exports) { /** @@ -158987,7 +156618,7 @@ module.exports = 'down'; /***/ }), -/* 1198 */ +/* 1194 */ /***/ (function(module, exports) { /** @@ -159019,7 +156650,7 @@ module.exports = 'up'; /***/ }), -/* 1199 */ +/* 1195 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159029,11 +156660,11 @@ module.exports = 'up'; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(209); -var Gamepad = __webpack_require__(445); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(211); +var Gamepad = __webpack_require__(444); var GetValue = __webpack_require__(6); -var InputPluginCache = __webpack_require__(130); +var InputPluginCache = __webpack_require__(132); var InputEvents = __webpack_require__(54); /** @@ -159657,7 +157288,7 @@ module.exports = GamepadPlugin; /***/ }), -/* 1200 */ +/* 1196 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159672,15 +157303,15 @@ module.exports = GamepadPlugin; module.exports = { - DUALSHOCK_4: __webpack_require__(1201), - SNES_USB: __webpack_require__(1202), - XBOX_360: __webpack_require__(1203) + DUALSHOCK_4: __webpack_require__(1197), + SNES_USB: __webpack_require__(1198), + XBOX_360: __webpack_require__(1199) }; /***/ }), -/* 1201 */ +/* 1197 */ /***/ (function(module, exports) { /** @@ -159730,7 +157361,7 @@ module.exports = { /***/ }), -/* 1202 */ +/* 1198 */ /***/ (function(module, exports) { /** @@ -159769,7 +157400,7 @@ module.exports = { /***/ }), -/* 1203 */ +/* 1199 */ /***/ (function(module, exports) { /** @@ -159820,7 +157451,7 @@ module.exports = { /***/ }), -/* 1204 */ +/* 1200 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159829,27 +157460,27 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); var CircleContains = __webpack_require__(55); var Class = __webpack_require__(0); -var CONST = __webpack_require__(174); -var CreateInteractiveObject = __webpack_require__(442); -var CreatePixelPerfectHandler = __webpack_require__(1205); +var CONST = __webpack_require__(177); +var CreateInteractiveObject = __webpack_require__(441); +var CreatePixelPerfectHandler = __webpack_require__(1201); var DistanceBetween = __webpack_require__(53); -var Ellipse = __webpack_require__(93); -var EllipseContains = __webpack_require__(94); +var Ellipse = __webpack_require__(95); +var EllipseContains = __webpack_require__(96); var Events = __webpack_require__(54); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var GetFastValue = __webpack_require__(2); var GEOM_CONST = __webpack_require__(46); -var InputPluginCache = __webpack_require__(130); +var InputPluginCache = __webpack_require__(132); var IsPlainObject = __webpack_require__(7); -var PluginCache = __webpack_require__(24); -var Rectangle = __webpack_require__(13); +var PluginCache = __webpack_require__(23); +var Rectangle = __webpack_require__(11); var RectangleContains = __webpack_require__(47); -var SceneEvents = __webpack_require__(22); -var Triangle = __webpack_require__(69); -var TriangleContains = __webpack_require__(81); +var SceneEvents = __webpack_require__(19); +var Triangle = __webpack_require__(71); +var TriangleContains = __webpack_require__(83); /** * @classdesc @@ -162972,7 +160603,7 @@ module.exports = InputPlugin; /***/ }), -/* 1205 */ +/* 1201 */ /***/ (function(module, exports) { /** @@ -163008,7 +160639,7 @@ module.exports = CreatePixelPerfectHandler; /***/ }), -/* 1206 */ +/* 1202 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163023,26 +160654,26 @@ module.exports = CreatePixelPerfectHandler; module.exports = { - Events: __webpack_require__(131), + Events: __webpack_require__(133), - KeyboardManager: __webpack_require__(361), - KeyboardPlugin: __webpack_require__(1214), + KeyboardManager: __webpack_require__(360), + KeyboardPlugin: __webpack_require__(1210), - Key: __webpack_require__(446), - KeyCodes: __webpack_require__(118), + Key: __webpack_require__(445), + KeyCodes: __webpack_require__(122), - KeyCombo: __webpack_require__(447), + KeyCombo: __webpack_require__(446), - JustDown: __webpack_require__(1219), - JustUp: __webpack_require__(1220), - DownDuration: __webpack_require__(1221), - UpDuration: __webpack_require__(1222) + JustDown: __webpack_require__(1215), + JustUp: __webpack_require__(1216), + DownDuration: __webpack_require__(1217), + UpDuration: __webpack_require__(1218) }; /***/ }), -/* 1207 */ +/* 1203 */ /***/ (function(module, exports) { /** @@ -163078,7 +160709,7 @@ module.exports = 'keydown'; /***/ }), -/* 1208 */ +/* 1204 */ /***/ (function(module, exports) { /** @@ -163107,7 +160738,7 @@ module.exports = 'keyup'; /***/ }), -/* 1209 */ +/* 1205 */ /***/ (function(module, exports) { /** @@ -163141,7 +160772,7 @@ module.exports = 'keycombomatch'; /***/ }), -/* 1210 */ +/* 1206 */ /***/ (function(module, exports) { /** @@ -163175,7 +160806,7 @@ module.exports = 'down'; /***/ }), -/* 1211 */ +/* 1207 */ /***/ (function(module, exports) { /** @@ -163214,7 +160845,7 @@ module.exports = 'keydown-'; /***/ }), -/* 1212 */ +/* 1208 */ /***/ (function(module, exports) { /** @@ -163246,7 +160877,7 @@ module.exports = 'keyup-'; /***/ }), -/* 1213 */ +/* 1209 */ /***/ (function(module, exports) { /** @@ -163280,7 +160911,7 @@ module.exports = 'up'; /***/ }), -/* 1214 */ +/* 1210 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163290,17 +160921,17 @@ module.exports = 'up'; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(131); -var GameEvents = __webpack_require__(19); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(133); +var GameEvents = __webpack_require__(18); var GetValue = __webpack_require__(6); var InputEvents = __webpack_require__(54); -var InputPluginCache = __webpack_require__(130); -var Key = __webpack_require__(446); -var KeyCodes = __webpack_require__(118); -var KeyCombo = __webpack_require__(447); -var KeyMap = __webpack_require__(1218); -var SnapFloor = __webpack_require__(91); +var InputPluginCache = __webpack_require__(132); +var Key = __webpack_require__(445); +var KeyCodes = __webpack_require__(122); +var KeyCombo = __webpack_require__(446); +var KeyMap = __webpack_require__(1214); +var SnapFloor = __webpack_require__(93); /** * @classdesc @@ -164166,7 +161797,7 @@ module.exports = KeyboardPlugin; /***/ }), -/* 1215 */ +/* 1211 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164175,7 +161806,7 @@ module.exports = KeyboardPlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AdvanceKeyCombo = __webpack_require__(1216); +var AdvanceKeyCombo = __webpack_require__(1212); /** * Used internally by the KeyCombo class. @@ -164247,7 +161878,7 @@ module.exports = ProcessKeyCombo; /***/ }), -/* 1216 */ +/* 1212 */ /***/ (function(module, exports) { /** @@ -164289,7 +161920,7 @@ module.exports = AdvanceKeyCombo; /***/ }), -/* 1217 */ +/* 1213 */ /***/ (function(module, exports) { /** @@ -164324,7 +161955,7 @@ module.exports = ResetKeyCombo; /***/ }), -/* 1218 */ +/* 1214 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164333,7 +161964,7 @@ module.exports = ResetKeyCombo; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var KeyCodes = __webpack_require__(118); +var KeyCodes = __webpack_require__(122); var KeyMap = {}; @@ -164346,7 +161977,7 @@ module.exports = KeyMap; /***/ }), -/* 1219 */ +/* 1215 */ /***/ (function(module, exports) { /** @@ -164388,7 +162019,7 @@ module.exports = JustDown; /***/ }), -/* 1220 */ +/* 1216 */ /***/ (function(module, exports) { /** @@ -164430,7 +162061,7 @@ module.exports = JustUp; /***/ }), -/* 1221 */ +/* 1217 */ /***/ (function(module, exports) { /** @@ -164464,7 +162095,7 @@ module.exports = DownDuration; /***/ }), -/* 1222 */ +/* 1218 */ /***/ (function(module, exports) { /** @@ -164498,7 +162129,7 @@ module.exports = UpDuration; /***/ }), -/* 1223 */ +/* 1219 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164514,14 +162145,14 @@ module.exports = UpDuration; /* eslint-disable */ module.exports = { - MouseManager: __webpack_require__(362) + MouseManager: __webpack_require__(361) }; /* eslint-enable */ /***/ }), -/* 1224 */ +/* 1220 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164537,14 +162168,14 @@ module.exports = { /* eslint-disable */ module.exports = { - TouchManager: __webpack_require__(364) + TouchManager: __webpack_require__(363) }; /* eslint-enable */ /***/ }), -/* 1225 */ +/* 1221 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164554,7 +162185,7 @@ module.exports = { */ var CONST = __webpack_require__(20); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Loader @@ -164562,18 +162193,18 @@ var Extend = __webpack_require__(18); var Loader = { - Events: __webpack_require__(80), + Events: __webpack_require__(81), - FileTypes: __webpack_require__(1226), + FileTypes: __webpack_require__(1222), File: __webpack_require__(21), FileTypesManager: __webpack_require__(8), - GetURL: __webpack_require__(132), - LoaderPlugin: __webpack_require__(1250), - MergeXHRSettings: __webpack_require__(210), + GetURL: __webpack_require__(134), + LoaderPlugin: __webpack_require__(1246), + MergeXHRSettings: __webpack_require__(212), MultiFile: __webpack_require__(61), - XHRLoader: __webpack_require__(448), - XHRSettings: __webpack_require__(133) + XHRLoader: __webpack_require__(447), + XHRSettings: __webpack_require__(135) }; @@ -164584,7 +162215,7 @@ module.exports = Loader; /***/ }), -/* 1226 */ +/* 1222 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164599,42 +162230,42 @@ module.exports = Loader; module.exports = { - AnimationJSONFile: __webpack_require__(1227), - AtlasJSONFile: __webpack_require__(1228), - AtlasXMLFile: __webpack_require__(1229), - AudioFile: __webpack_require__(449), - AudioSpriteFile: __webpack_require__(1230), - BinaryFile: __webpack_require__(1231), - BitmapFontFile: __webpack_require__(1232), - CSSFile: __webpack_require__(1233), - GLSLFile: __webpack_require__(1234), - HTML5AudioFile: __webpack_require__(450), - HTMLFile: __webpack_require__(1235), - HTMLTextureFile: __webpack_require__(1236), - ImageFile: __webpack_require__(70), + AnimationJSONFile: __webpack_require__(1223), + AtlasJSONFile: __webpack_require__(1224), + AtlasXMLFile: __webpack_require__(1225), + AudioFile: __webpack_require__(448), + AudioSpriteFile: __webpack_require__(1226), + BinaryFile: __webpack_require__(1227), + BitmapFontFile: __webpack_require__(1228), + CSSFile: __webpack_require__(1229), + GLSLFile: __webpack_require__(1230), + HTML5AudioFile: __webpack_require__(449), + HTMLFile: __webpack_require__(1231), + HTMLTextureFile: __webpack_require__(1232), + ImageFile: __webpack_require__(72), JSONFile: __webpack_require__(60), - MultiAtlasFile: __webpack_require__(1237), - MultiScriptFile: __webpack_require__(1238), - PackFile: __webpack_require__(1239), - PluginFile: __webpack_require__(1240), - SceneFile: __webpack_require__(1241), - ScenePluginFile: __webpack_require__(1242), - ScriptFile: __webpack_require__(451), - SpriteSheetFile: __webpack_require__(1243), - SVGFile: __webpack_require__(1244), - TextFile: __webpack_require__(452), - TilemapCSVFile: __webpack_require__(1245), - TilemapImpactFile: __webpack_require__(1246), - TilemapJSONFile: __webpack_require__(1247), - UnityAtlasFile: __webpack_require__(1248), - VideoFile: __webpack_require__(1249), - XMLFile: __webpack_require__(211) + MultiAtlasFile: __webpack_require__(1233), + MultiScriptFile: __webpack_require__(1234), + PackFile: __webpack_require__(1235), + PluginFile: __webpack_require__(1236), + SceneFile: __webpack_require__(1237), + ScenePluginFile: __webpack_require__(1238), + ScriptFile: __webpack_require__(450), + SpriteSheetFile: __webpack_require__(1239), + SVGFile: __webpack_require__(1240), + TextFile: __webpack_require__(451), + TilemapCSVFile: __webpack_require__(1241), + TilemapImpactFile: __webpack_require__(1242), + TilemapJSONFile: __webpack_require__(1243), + UnityAtlasFile: __webpack_require__(1244), + VideoFile: __webpack_require__(1245), + XMLFile: __webpack_require__(213) }; /***/ }), -/* 1227 */ +/* 1223 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164646,7 +162277,7 @@ module.exports = { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(60); -var LoaderEvents = __webpack_require__(80); +var LoaderEvents = __webpack_require__(81); /** * @classdesc @@ -164810,7 +162441,7 @@ var AnimationJSONFile = new Class({ * @param {string} [dataKey] - When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('animation', function (key, url, dataKey, xhrSettings) { @@ -164837,7 +162468,7 @@ module.exports = AnimationJSONFile; /***/ }), -/* 1228 */ +/* 1224 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164849,7 +162480,7 @@ module.exports = AnimationJSONFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(60); var MultiFile = __webpack_require__(61); @@ -165053,7 +162684,7 @@ var AtlasJSONFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('atlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { @@ -165086,7 +162717,7 @@ module.exports = AtlasJSONFile; /***/ }), -/* 1229 */ +/* 1225 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -165098,10 +162729,10 @@ module.exports = AtlasJSONFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var XMLFile = __webpack_require__(211); +var XMLFile = __webpack_require__(213); /** * @classdesc @@ -165296,7 +162927,7 @@ var AtlasXMLFile = new Class({ * @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 xml file. Used in replacement of the Loaders default XHR Settings. * - * @return {this} The Loader instance. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('atlasXML', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { @@ -165329,7 +162960,7 @@ module.exports = AtlasXMLFile; /***/ }), -/* 1230 */ +/* 1226 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -165338,7 +162969,7 @@ module.exports = AtlasXMLFile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AudioFile = __webpack_require__(449); +var AudioFile = __webpack_require__(448); var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); @@ -165572,7 +163203,7 @@ var AudioSpriteFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader. */ FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) { @@ -165619,7 +163250,7 @@ FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audio /***/ }), -/* 1231 */ +/* 1227 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -165777,7 +163408,7 @@ var BinaryFile = new Class({ * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('binary', function (key, url, dataType, xhrSettings) { @@ -165801,7 +163432,7 @@ module.exports = BinaryFile; /***/ }), -/* 1232 */ +/* 1228 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -165813,11 +163444,11 @@ module.exports = BinaryFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var ParseXMLBitmapFont = __webpack_require__(182); -var XMLFile = __webpack_require__(211); +var ParseXMLBitmapFont = __webpack_require__(185); +var XMLFile = __webpack_require__(213); /** * @classdesc @@ -166011,7 +163642,7 @@ var BitmapFontFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('bitmapFont', function (key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) { @@ -166044,7 +163675,7 @@ module.exports = BitmapFontFile; /***/ }), -/* 1233 */ +/* 1229 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -166188,7 +163819,7 @@ var CSSFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('css', function (key, url, xhrSettings) { @@ -166212,7 +163843,7 @@ module.exports = CSSFile; /***/ }), -/* 1234 */ +/* 1230 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -166227,7 +163858,7 @@ var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); -var Shader = __webpack_require__(348); +var Shader = __webpack_require__(347); /** * @classdesc @@ -166599,7 +164230,7 @@ var GLSLFile = new Class({ * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('glsl', function (key, url, shaderType, xhrSettings) { @@ -166623,7 +164254,7 @@ module.exports = GLSLFile; /***/ }), -/* 1235 */ +/* 1231 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -166774,7 +164405,7 @@ var HTMLFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('html', function (key, url, xhrSettings) { @@ -166798,7 +164429,7 @@ module.exports = HTMLFile; /***/ }), -/* 1236 */ +/* 1232 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -167032,7 +164663,7 @@ var HTMLTextureFile = new Class({ * @param {integer} [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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('htmlTexture', function (key, url, width, height, xhrSettings) { @@ -167056,7 +164687,7 @@ module.exports = HTMLTextureFile; /***/ }), -/* 1237 */ +/* 1233 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -167068,7 +164699,7 @@ module.exports = HTMLTextureFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(60); var MultiFile = __webpack_require__(61); @@ -167356,7 +164987,7 @@ var MultiAtlasFile = new Class({ * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('multiatlas', function (key, atlasURL, path, baseURL, atlasXhrSettings) { @@ -167389,7 +165020,7 @@ module.exports = MultiAtlasFile; /***/ }), -/* 1238 */ +/* 1234 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -167403,7 +165034,7 @@ var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var ScriptFile = __webpack_require__(451); +var ScriptFile = __webpack_require__(450); /** * @classdesc @@ -167573,7 +165204,7 @@ var MultiScriptFile = new Class({ * @param {string} [extension='js'] - The default file extension to use if no url is provided. * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for these files. * - * @return {this} The Loader instance. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('scripts', function (key, url, xhrSettings) { @@ -167606,7 +165237,7 @@ module.exports = MultiScriptFile; /***/ }), -/* 1239 */ +/* 1235 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -167797,7 +165428,7 @@ var PackFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('pack', function (key, url, packKey, xhrSettings) { @@ -167824,7 +165455,7 @@ module.exports = PackFile; /***/ }), -/* 1240 */ +/* 1236 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168012,7 +165643,7 @@ var PluginFile = new Class({ * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('plugin', function (key, url, start, mapping, xhrSettings) { @@ -168036,7 +165667,7 @@ module.exports = PluginFile; /***/ }), -/* 1241 */ +/* 1237 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168233,7 +165864,7 @@ var SceneFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('sceneFile', function (key, url, xhrSettings) { @@ -168257,7 +165888,7 @@ module.exports = SceneFile; /***/ }), -/* 1242 */ +/* 1238 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168439,7 +166070,7 @@ var ScenePluginFile = new Class({ * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('scenePlugin', function (key, url, systemKey, sceneKey, xhrSettings) { @@ -168463,7 +166094,7 @@ module.exports = ScenePluginFile; /***/ }), -/* 1243 */ +/* 1239 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168474,7 +166105,7 @@ module.exports = ScenePluginFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); /** * @classdesc @@ -168630,7 +166261,7 @@ var SpriteSheetFile = new Class({ * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. At a minimum it should have a `frameWidth` property. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('spritesheet', function (key, url, frameConfig, xhrSettings) { @@ -168654,7 +166285,7 @@ module.exports = SpriteSheetFile; /***/ }), -/* 1244 */ +/* 1240 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168968,7 +166599,7 @@ var SVGFile = new Class({ * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('svg', function (key, url, svgConfig, xhrSettings) { @@ -168993,7 +166624,7 @@ module.exports = SVGFile; /***/ }), -/* 1245 */ +/* 1241 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169008,7 +166639,7 @@ var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); -var TILEMAP_FORMATS = __webpack_require__(33); +var TILEMAP_FORMATS = __webpack_require__(31); /** * @classdesc @@ -169164,7 +166795,7 @@ var TilemapCSVFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('tilemapCSV', function (key, url, xhrSettings) { @@ -169188,7 +166819,7 @@ module.exports = TilemapCSVFile; /***/ }), -/* 1246 */ +/* 1242 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169200,7 +166831,7 @@ module.exports = TilemapCSVFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(60); -var TILEMAP_FORMATS = __webpack_require__(33); +var TILEMAP_FORMATS = __webpack_require__(31); /** * @classdesc @@ -169320,7 +166951,7 @@ var TilemapImpactFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('tilemapImpact', function (key, url, xhrSettings) { @@ -169344,7 +166975,7 @@ module.exports = TilemapImpactFile; /***/ }), -/* 1247 */ +/* 1243 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169356,7 +166987,7 @@ module.exports = TilemapImpactFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(60); -var TILEMAP_FORMATS = __webpack_require__(33); +var TILEMAP_FORMATS = __webpack_require__(31); /** * @classdesc @@ -169476,7 +167107,7 @@ var TilemapJSONFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('tilemapTiledJSON', function (key, url, xhrSettings) { @@ -169500,7 +167131,7 @@ module.exports = TilemapJSONFile; /***/ }), -/* 1248 */ +/* 1244 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169512,10 +167143,10 @@ module.exports = TilemapJSONFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var TextFile = __webpack_require__(452); +var TextFile = __webpack_require__(451); /** * @classdesc @@ -169709,7 +167340,7 @@ var UnityAtlasFile = new Class({ * @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 data file. Used in replacement of the Loaders default XHR Settings. * - * @return {this} The Loader instance. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('unityAtlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { @@ -169742,7 +167373,7 @@ module.exports = UnityAtlasFile; /***/ }), -/* 1249 */ +/* 1245 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169752,10 +167383,10 @@ module.exports = UnityAtlasFile; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); +var CONST = __webpack_require__(29); var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); -var GetURL = __webpack_require__(132); +var GetURL = __webpack_require__(134); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); @@ -170097,7 +167728,7 @@ VideoFile.getVideoURL = function (game, urls) * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('video', function (key, urls, loadEvent, asBlob, noAudio, xhrSettings) { @@ -170133,7 +167764,7 @@ module.exports = VideoFile; /***/ }), -/* 1250 */ +/* 1246 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -170144,14 +167775,14 @@ module.exports = VideoFile; var Class = __webpack_require__(0); var CONST = __webpack_require__(20); -var CustomSet = __webpack_require__(127); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(80); +var CustomSet = __webpack_require__(108); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(81); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var XHRSettings = __webpack_require__(133); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var XHRSettings = __webpack_require__(135); /** * @classdesc @@ -170332,8 +167963,7 @@ var LoaderPlugin = new Class({ GetFastValue(sceneConfig, 'async', gameConfig.loaderAsync), GetFastValue(sceneConfig, 'user', gameConfig.loaderUser), GetFastValue(sceneConfig, 'password', gameConfig.loaderPassword), - GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout), - GetFastValue(sceneConfig, 'withCredentials', gameConfig.loaderWithCredentials) + GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout) ); /** @@ -170506,7 +168136,7 @@ var LoaderPlugin = new Class({ * * @param {string} [url] - The URL to use. Leave empty to reset. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setBaseURL: function (url) { @@ -170546,7 +168176,7 @@ var LoaderPlugin = new Class({ * * @param {string} [path] - The path to use. Leave empty to reset. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setPath: function (path) { @@ -170575,7 +168205,7 @@ var LoaderPlugin = new Class({ * * @param {string} [prefix] - The prefix to use. Leave empty to reset. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setPrefix: function (prefix) { @@ -170601,7 +168231,7 @@ var LoaderPlugin = new Class({ * * @param {string} [crossOrigin] - The value to use for the `crossOrigin` property in the load request. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setCORS: function (crossOrigin) { @@ -171090,7 +168720,7 @@ var LoaderPlugin = new Class({ * @param {*} data - The JSON data, ready parsed. * @param {string} [filename=file.json] - The name to save the JSON file as. * - * @return {this} This Loader plugin. + * @return {Phaser.Loader.LoaderPlugin} This Loader plugin. */ saveJSON: function (data, filename) { @@ -171110,7 +168740,7 @@ var LoaderPlugin = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} This Loader plugin. */ save: function (data, filename, filetype) { @@ -171211,7 +168841,7 @@ module.exports = LoaderPlugin; /***/ }), -/* 1251 */ +/* 1247 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -171221,7 +168851,7 @@ module.exports = LoaderPlugin; */ var CONST = __webpack_require__(50); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * @callback ArcadePhysicsCallback @@ -171236,18 +168866,18 @@ var Extend = __webpack_require__(18); var Arcade = { - ArcadePhysics: __webpack_require__(1252), - Body: __webpack_require__(459), - Collider: __webpack_require__(460), - Components: __webpack_require__(212), - Events: __webpack_require__(213), - Factory: __webpack_require__(453), - Group: __webpack_require__(455), - Image: __webpack_require__(454), - Sprite: __webpack_require__(134), - StaticBody: __webpack_require__(465), - StaticGroup: __webpack_require__(456), - World: __webpack_require__(458) + ArcadePhysics: __webpack_require__(1248), + Body: __webpack_require__(458), + Collider: __webpack_require__(459), + Components: __webpack_require__(214), + Events: __webpack_require__(215), + Factory: __webpack_require__(452), + Group: __webpack_require__(454), + Image: __webpack_require__(453), + Sprite: __webpack_require__(136), + StaticBody: __webpack_require__(464), + StaticGroup: __webpack_require__(455), + World: __webpack_require__(457) }; @@ -171258,7 +168888,7 @@ module.exports = Arcade; /***/ }), -/* 1252 */ +/* 1248 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -171270,16 +168900,16 @@ module.exports = Arcade; var Class = __webpack_require__(0); var DegToRad = __webpack_require__(35); var DistanceBetween = __webpack_require__(53); -var DistanceSquared = __webpack_require__(315); -var Factory = __webpack_require__(453); +var DistanceSquared = __webpack_require__(316); +var Factory = __webpack_require__(452); var GetFastValue = __webpack_require__(2); -var Merge = __webpack_require__(120); -var OverlapCirc = __webpack_require__(1265); -var OverlapRect = __webpack_require__(457); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var Merge = __webpack_require__(107); +var OverlapCirc = __webpack_require__(1261); +var OverlapRect = __webpack_require__(456); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); var Vector2 = __webpack_require__(3); -var World = __webpack_require__(458); +var World = __webpack_require__(457); /** * @classdesc @@ -171947,7 +169577,7 @@ module.exports = ArcadePhysics; /***/ }), -/* 1253 */ +/* 1249 */ /***/ (function(module, exports) { /** @@ -172022,7 +169652,7 @@ module.exports = Acceleration; /***/ }), -/* 1254 */ +/* 1250 */ /***/ (function(module, exports) { /** @@ -172104,7 +169734,7 @@ module.exports = Angular; /***/ }), -/* 1255 */ +/* 1251 */ /***/ (function(module, exports) { /** @@ -172203,7 +169833,7 @@ module.exports = Bounce; /***/ }), -/* 1256 */ +/* 1252 */ /***/ (function(module, exports) { /** @@ -172330,7 +169960,7 @@ module.exports = Debug; /***/ }), -/* 1257 */ +/* 1253 */ /***/ (function(module, exports) { /** @@ -172463,7 +170093,7 @@ module.exports = Drag; /***/ }), -/* 1258 */ +/* 1254 */ /***/ (function(module, exports) { /** @@ -172587,7 +170217,7 @@ module.exports = Enable; /***/ }), -/* 1259 */ +/* 1255 */ /***/ (function(module, exports) { /** @@ -172665,7 +170295,7 @@ module.exports = Friction; /***/ }), -/* 1260 */ +/* 1256 */ /***/ (function(module, exports) { /** @@ -172743,7 +170373,7 @@ module.exports = Gravity; /***/ }), -/* 1261 */ +/* 1257 */ /***/ (function(module, exports) { /** @@ -172785,7 +170415,7 @@ module.exports = Immovable; /***/ }), -/* 1262 */ +/* 1258 */ /***/ (function(module, exports) { /** @@ -172825,7 +170455,7 @@ module.exports = Mass; /***/ }), -/* 1263 */ +/* 1259 */ /***/ (function(module, exports) { /** @@ -172907,7 +170537,7 @@ module.exports = Size; /***/ }), -/* 1264 */ +/* 1260 */ /***/ (function(module, exports) { /** @@ -173006,13 +170636,13 @@ module.exports = Velocity; /***/ }), -/* 1265 */ +/* 1261 */ /***/ (function(module, exports, __webpack_require__) { -var OverlapRect = __webpack_require__(457); -var Circle = __webpack_require__(63); -var CircleToCircle = __webpack_require__(200); -var CircleToRectangle = __webpack_require__(201); +var OverlapRect = __webpack_require__(456); +var Circle = __webpack_require__(65); +var CircleToCircle = __webpack_require__(202); +var CircleToRectangle = __webpack_require__(203); /** * This method will search the given circular area and return an array of all physics bodies that @@ -173074,7 +170704,7 @@ module.exports = OverlapCirc; /***/ }), -/* 1266 */ +/* 1262 */ /***/ (function(module, exports) { /** @@ -173107,7 +170737,7 @@ module.exports = 'collide'; /***/ }), -/* 1267 */ +/* 1263 */ /***/ (function(module, exports) { /** @@ -173140,7 +170770,7 @@ module.exports = 'overlap'; /***/ }), -/* 1268 */ +/* 1264 */ /***/ (function(module, exports) { /** @@ -173163,7 +170793,7 @@ module.exports = 'pause'; /***/ }), -/* 1269 */ +/* 1265 */ /***/ (function(module, exports) { /** @@ -173186,7 +170816,7 @@ module.exports = 'resume'; /***/ }), -/* 1270 */ +/* 1266 */ /***/ (function(module, exports) { /** @@ -173218,7 +170848,7 @@ module.exports = 'tilecollide'; /***/ }), -/* 1271 */ +/* 1267 */ /***/ (function(module, exports) { /** @@ -173250,7 +170880,7 @@ module.exports = 'tileoverlap'; /***/ }), -/* 1272 */ +/* 1268 */ /***/ (function(module, exports) { /** @@ -173282,7 +170912,7 @@ module.exports = 'worldbounds'; /***/ }), -/* 1273 */ +/* 1269 */ /***/ (function(module, exports) { /** @@ -173308,7 +170938,7 @@ module.exports = 'worldstep'; /***/ }), -/* 1274 */ +/* 1270 */ /***/ (function(module, exports) { /** @@ -173349,7 +170979,7 @@ module.exports = ProcessTileCallbacks; /***/ }), -/* 1275 */ +/* 1271 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173358,9 +170988,9 @@ module.exports = ProcessTileCallbacks; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var TileCheckX = __webpack_require__(1276); -var TileCheckY = __webpack_require__(1278); -var TileIntersectsBody = __webpack_require__(464); +var TileCheckX = __webpack_require__(1272); +var TileCheckY = __webpack_require__(1274); +var TileIntersectsBody = __webpack_require__(463); /** * The core separation function to separate a physics body and a tile. @@ -173469,7 +171099,7 @@ module.exports = SeparateTile; /***/ }), -/* 1276 */ +/* 1272 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173478,7 +171108,7 @@ module.exports = SeparateTile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ProcessTileSeparationX = __webpack_require__(1277); +var ProcessTileSeparationX = __webpack_require__(1273); /** * Check the body against the given tile on the X axis. @@ -173559,7 +171189,7 @@ module.exports = TileCheckX; /***/ }), -/* 1277 */ +/* 1273 */ /***/ (function(module, exports) { /** @@ -173606,7 +171236,7 @@ module.exports = ProcessTileSeparationX; /***/ }), -/* 1278 */ +/* 1274 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173615,7 +171245,7 @@ module.exports = ProcessTileSeparationX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ProcessTileSeparationY = __webpack_require__(1279); +var ProcessTileSeparationY = __webpack_require__(1275); /** * Check the body against the given tile on the Y axis. @@ -173696,7 +171326,7 @@ module.exports = TileCheckY; /***/ }), -/* 1279 */ +/* 1275 */ /***/ (function(module, exports) { /** @@ -173743,7 +171373,7 @@ module.exports = ProcessTileSeparationY; /***/ }), -/* 1280 */ +/* 1276 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173752,7 +171382,7 @@ module.exports = ProcessTileSeparationY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetOverlapX = __webpack_require__(461); +var GetOverlapX = __webpack_require__(460); /** * Separates two overlapping bodies on the X-axis (horizontally). @@ -173834,7 +171464,7 @@ module.exports = SeparateX; /***/ }), -/* 1281 */ +/* 1277 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173843,7 +171473,7 @@ module.exports = SeparateX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetOverlapY = __webpack_require__(462); +var GetOverlapY = __webpack_require__(461); /** * Separates two overlapping bodies on the Y-axis (vertically). @@ -173925,6 +171555,10 @@ module.exports = SeparateY; /***/ }), +/* 1278 */, +/* 1279 */, +/* 1280 */, +/* 1281 */, /* 1282 */, /* 1283 */, /* 1284 */, @@ -173935,9 +171569,7 @@ module.exports = SeparateY; /* 1289 */, /* 1290 */, /* 1291 */, -/* 1292 */, -/* 1293 */, -/* 1294 */ +/* 1292 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173952,17 +171584,17 @@ module.exports = SeparateY; module.exports = { - BasePlugin: __webpack_require__(467), - DefaultPlugins: __webpack_require__(170), - PluginCache: __webpack_require__(24), - PluginManager: __webpack_require__(365), - ScenePlugin: __webpack_require__(1295) + BasePlugin: __webpack_require__(468), + DefaultPlugins: __webpack_require__(173), + PluginCache: __webpack_require__(23), + PluginManager: __webpack_require__(364), + ScenePlugin: __webpack_require__(1293) }; /***/ }), -/* 1295 */ +/* 1293 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173971,9 +171603,9 @@ module.exports = { * @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} */ -var BasePlugin = __webpack_require__(467); +var BasePlugin = __webpack_require__(468); var Class = __webpack_require__(0); -var SceneEvents = __webpack_require__(22); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -174090,7 +171722,7 @@ module.exports = ScenePlugin; /***/ }), -/* 1296 */ +/* 1294 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174099,8 +171731,8 @@ module.exports = ScenePlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); -var CONST = __webpack_require__(172); +var Extend = __webpack_require__(17); +var CONST = __webpack_require__(175); /** * @namespace Phaser.Scale @@ -174128,12 +171760,12 @@ var CONST = __webpack_require__(172); var Scale = { - Center: __webpack_require__(354), - Events: __webpack_require__(90), - Orientation: __webpack_require__(355), - ScaleManager: __webpack_require__(366), - ScaleModes: __webpack_require__(356), - Zoom: __webpack_require__(357) + Center: __webpack_require__(353), + Events: __webpack_require__(92), + Orientation: __webpack_require__(354), + ScaleManager: __webpack_require__(365), + ScaleModes: __webpack_require__(355), + Zoom: __webpack_require__(356) }; @@ -174146,7 +171778,7 @@ module.exports = Scale; /***/ }), -/* 1297 */ +/* 1295 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174155,8 +171787,8 @@ module.exports = Scale; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(119); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(123); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Scenes @@ -174164,11 +171796,11 @@ var Extend = __webpack_require__(18); var Scene = { - Events: __webpack_require__(22), - SceneManager: __webpack_require__(368), - ScenePlugin: __webpack_require__(1298), - Settings: __webpack_require__(370), - Systems: __webpack_require__(175) + Events: __webpack_require__(19), + SceneManager: __webpack_require__(367), + ScenePlugin: __webpack_require__(1296), + Settings: __webpack_require__(369), + Systems: __webpack_require__(178) }; @@ -174179,7 +171811,7 @@ module.exports = Scene; /***/ }), -/* 1298 */ +/* 1296 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174188,11 +171820,11 @@ module.exports = Scene; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var Events = __webpack_require__(22); +var Events = __webpack_require__(19); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); +var PluginCache = __webpack_require__(23); /** * @classdesc @@ -175189,7 +172821,7 @@ module.exports = ScenePlugin; /***/ }), -/* 1299 */ +/* 1297 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175204,18 +172836,18 @@ module.exports = ScenePlugin; module.exports = { - List: __webpack_require__(123), - Map: __webpack_require__(156), - ProcessQueue: __webpack_require__(181), - RTree: __webpack_require__(463), - Set: __webpack_require__(127), - Size: __webpack_require__(367) + List: __webpack_require__(126), + Map: __webpack_require__(159), + ProcessQueue: __webpack_require__(184), + RTree: __webpack_require__(462), + Set: __webpack_require__(108), + Size: __webpack_require__(366) }; /***/ }), -/* 1300 */ +/* 1298 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175224,8 +172856,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); -var FilterMode = __webpack_require__(1301); +var Extend = __webpack_require__(17); +var FilterMode = __webpack_require__(1299); /** * @namespace Phaser.Textures @@ -175251,14 +172883,14 @@ var FilterMode = __webpack_require__(1301); var Textures = { - CanvasTexture: __webpack_require__(372), - Events: __webpack_require__(115), + CanvasTexture: __webpack_require__(371), + Events: __webpack_require__(119), FilterMode: FilterMode, - Frame: __webpack_require__(92), - Parsers: __webpack_require__(374), - Texture: __webpack_require__(177), - TextureManager: __webpack_require__(371), - TextureSource: __webpack_require__(373) + Frame: __webpack_require__(94), + Parsers: __webpack_require__(373), + Texture: __webpack_require__(180), + TextureManager: __webpack_require__(370), + TextureSource: __webpack_require__(372) }; @@ -175268,7 +172900,7 @@ module.exports = Textures; /***/ }), -/* 1301 */ +/* 1299 */ /***/ (function(module, exports) { /** @@ -175312,7 +172944,7 @@ module.exports = CONST; /***/ }), -/* 1302 */ +/* 1300 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175327,30 +172959,30 @@ module.exports = CONST; module.exports = { - Components: __webpack_require__(135), - Parsers: __webpack_require__(1335), + Components: __webpack_require__(137), + Parsers: __webpack_require__(1330), - Formats: __webpack_require__(33), - ImageCollection: __webpack_require__(480), - ParseToTilemap: __webpack_require__(222), - Tile: __webpack_require__(72), - Tilemap: __webpack_require__(489), - TilemapCreator: __webpack_require__(1344), - TilemapFactory: __webpack_require__(1345), - Tileset: __webpack_require__(137), + Formats: __webpack_require__(31), + ImageCollection: __webpack_require__(479), + ParseToTilemap: __webpack_require__(224), + Tile: __webpack_require__(74), + Tilemap: __webpack_require__(488), + TilemapCreator: __webpack_require__(1339), + TilemapFactory: __webpack_require__(1340), + Tileset: __webpack_require__(141), - LayerData: __webpack_require__(100), - MapData: __webpack_require__(101), - ObjectLayer: __webpack_require__(483), + LayerData: __webpack_require__(104), + MapData: __webpack_require__(105), + ObjectLayer: __webpack_require__(482), - DynamicTilemapLayer: __webpack_require__(490), - StaticTilemapLayer: __webpack_require__(491) + DynamicTilemapLayer: __webpack_require__(489), + StaticTilemapLayer: __webpack_require__(490) }; /***/ }), -/* 1303 */ +/* 1301 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175359,7 +172991,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); var CalculateFacesWithin = __webpack_require__(51); /** @@ -175415,7 +173047,7 @@ module.exports = Copy; /***/ }), -/* 1304 */ +/* 1302 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175424,9 +173056,10 @@ module.exports = Copy; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ - -var GetTilesWithin = __webpack_require__(25); -var ReplaceByIndex = __webpack_require__(468); +var TileToWorldX = __webpack_require__(139); +var TileToWorldY = __webpack_require__(140); +var GetTilesWithin = __webpack_require__(24); +var ReplaceByIndex = __webpack_require__(469); /** * Creates a Sprite for every object matching the given tile indexes in the layer. You can @@ -175467,9 +173100,9 @@ var CreateFromTiles = function (indexes, replacements, spriteConfig, scene, came if (indexes.indexOf(tile.index) !== -1) { - var point = tilemapLayer.tileToWorldXY(tile.x,tile.y, undefined, camera); - spriteConfig.x = point.x; - spriteConfig.y = point.y; + spriteConfig.x = TileToWorldX(tile.x, camera, layer); + spriteConfig.y = TileToWorldY(tile.y, camera, layer); + var sprite = scene.make.sprite(spriteConfig); sprites.push(sprite); } @@ -175499,7 +173132,7 @@ module.exports = CreateFromTiles; /***/ }), -/* 1305 */ +/* 1303 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175508,10 +173141,8 @@ module.exports = CreateFromTiles; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var SnapFloor = __webpack_require__(91); -var SnapCeil = __webpack_require__(324); -var CheckIsoBounds = __webpack_require__(1306); +var SnapFloor = __webpack_require__(93); +var SnapCeil = __webpack_require__(325); /** * Returns the tiles in the given layer that are within the camera's viewport. This is used internally. @@ -175553,224 +173184,100 @@ var CullTiles = function (layer, camera, outputArray, renderOrder) if (!tilemapLayer.skipCull && tilemapLayer.scrollFactorX === 1 && tilemapLayer.scrollFactorY === 1) { - if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) - { - // Camera world view bounds, snapped for scaled tile size - // Cull Padding values are given in tiles, not pixels - var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; - var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; + // Camera world view bounds, snapped for scaled tile size + // Cull Padding values are given in tiles, not pixels - var boundsTop; - var boundsBottom; + var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; + var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; + var boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; + var boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; - if (layer.orientation === CONST.ORTHOGONAL) - { - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; - } - else if (layer.orientation === CONST.STAGGERED) - { - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH / 2, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH / 2, 0, true) + tilemapLayer.cullPaddingY; - } - else if (layer.orientation === CONST.HEXAGONAL) - { - var sidel = layer.hexSideLength; - var rowH = ((tileH - sidel) / 2 + sidel); - - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, rowH, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, rowH, 0, true) + tilemapLayer.cullPaddingY; - } - - - - - drawLeft = Math.max(0, boundsLeft); - drawRight = Math.min(mapWidth, boundsRight); - drawTop = Math.max(0, boundsTop); - - drawBottom = Math.min(mapHeight, boundsBottom); - } + drawLeft = Math.max(0, boundsLeft); + drawRight = Math.min(mapWidth, boundsRight); + drawTop = Math.max(0, boundsTop); + drawBottom = Math.min(mapHeight, boundsBottom); } + var x; var y; var tile; - - if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) + if (renderOrder === 0) { + // right-down - if (renderOrder === 0) + for (y = drawTop; y < drawBottom; y++) { - // right-down - - for (y = drawTop; y < drawBottom; y++) + for (x = drawLeft; mapData[y] && x < drawRight; x++) { - for (x = drawLeft; mapData[y] && x < drawRight; x++) + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); + continue; } - } - } - else if (renderOrder === 1) - { - // left-down - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } + outputArray.push(tile); } } } - else if (layer.orientation === CONST.ISOMETRIC) + else if (renderOrder === 1) { - if (renderOrder === 0) + // left-down + + for (y = drawTop; y < drawBottom; y++) { - // right-down - - for (y = drawTop; y < drawBottom; y++) + for (x = drawRight; mapData[y] && x >= drawLeft; x--) { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; + tile = mapData[y][x]; - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; } + + outputArray.push(tile); } } - else if (renderOrder === 1) - { - // left-down - - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - } + else if (renderOrder === 2) + { + // right-up + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } tilemapLayer.tilesDrawn = outputArray.length; tilemapLayer.tilesTotal = mapWidth * mapHeight; @@ -175782,47 +173289,7 @@ module.exports = CullTiles; /***/ }), -/* 1306 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * @function Phaser.Tilemaps.Components.CheckIsoBounds - * @private - * @since 3.2.3 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to check against. - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. - */ -var CheckIsoBounds = function (tileX,tileY,layer,camera) -{ - var tilemapLayer = layer.tilemapLayer; - var cullDistances = tilemapLayer.isoCullDistances; - var pos = tilemapLayer.tileToWorldXY(tileX,tileY,undefined,camera); - - // we always subtract 1/2 of the tile's height/width to make the culling distance start from the center of the tiles. - return pos.x > camera.worldView.x + tilemapLayer.scaleX * layer.tileWidth * (- cullDistances.x - 1 / 2) - && pos.x < camera.worldView.right + tilemapLayer.scaleX * layer.tileWidth * (cullDistances.x - 1 / 2) - && pos.y > camera.worldView.y + tilemapLayer.scaleY * layer.tileHeight * (- cullDistances.y - 1 / 2) - && pos.y < camera.worldView.bottom + tilemapLayer.scaleY * layer.tileHeight * (cullDistances.y - 1 / 2); -}; - -module.exports = CheckIsoBounds; - - -/***/ }), -/* 1307 */ +/* 1304 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175831,9 +173298,9 @@ module.exports = CheckIsoBounds; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); var CalculateFacesWithin = __webpack_require__(51); -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); /** * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the @@ -175876,7 +173343,7 @@ module.exports = Fill; /***/ }), -/* 1308 */ +/* 1305 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175885,7 +173352,7 @@ module.exports = Fill; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given @@ -175924,7 +173391,7 @@ module.exports = FilterTiles; /***/ }), -/* 1309 */ +/* 1306 */ /***/ (function(module, exports) { /** @@ -176012,7 +173479,7 @@ module.exports = FindByIndex; /***/ }), -/* 1310 */ +/* 1307 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176021,7 +173488,7 @@ module.exports = FindByIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * @callback FindTileCallback @@ -176066,7 +173533,7 @@ module.exports = FindTile; /***/ }), -/* 1311 */ +/* 1308 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176075,7 +173542,7 @@ module.exports = FindTile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * @callback EachTileCallback @@ -176116,7 +173583,7 @@ module.exports = ForEachTile; /***/ }), -/* 1312 */ +/* 1309 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176125,7 +173592,9 @@ module.exports = ForEachTile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTileAt = __webpack_require__(136); +var GetTileAt = __webpack_require__(138); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Gets a tile at the given world coordinates from the given layer. @@ -176145,9 +173614,9 @@ var GetTileAt = __webpack_require__(136); */ var GetTileAtWorldXY = function (worldX, worldY, nonNull, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + return GetTileAt(tileX, tileY, nonNull, layer); }; @@ -176155,7 +173624,7 @@ module.exports = GetTileAtWorldXY; /***/ }), -/* 1313 */ +/* 1310 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176164,11 +173633,14 @@ module.exports = GetTileAtWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Geom = __webpack_require__(423); -var GetTilesWithin = __webpack_require__(25); -var Intersects = __webpack_require__(424); +var Geom = __webpack_require__(422); +var GetTilesWithin = __webpack_require__(24); +var Intersects = __webpack_require__(423); var NOOP = __webpack_require__(1); - +var TileToWorldX = __webpack_require__(139); +var TileToWorldY = __webpack_require__(140); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); var TriangleToRectangle = function (triangle, rect) { @@ -176208,14 +173680,12 @@ var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle; } // Top left corner of the shapes's bounding box, rounded down to include partial tiles - var pointStart = layer.tilemapLayer.worldToTileXY(shape.left, shape.top, true, undefined, camera); - var xStart = pointStart.x; - var yStart = pointStart.y; + var xStart = WorldToTileX(shape.left, true, camera, layer); + var yStart = WorldToTileY(shape.top, true, camera, layer); // Bottom right corner of the shapes's bounding box, rounded up to include partial tiles - var pointEnd = layer.tilemapLayer.worldToTileXY(shape.right, shape.bottom, true, undefined, camera); - var xEnd = Math.ceil(pointEnd.x); - var yEnd = Math.ceil(pointEnd.y); + var xEnd = Math.ceil(WorldToTileX(shape.right, false, camera, layer)); + var yEnd = Math.ceil(WorldToTileY(shape.bottom, false, camera, layer)); // 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). @@ -176236,9 +173706,8 @@ var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; - var point = layer.tilemapLayer.tileToWorldXY(tile.x, tile.y, undefined, camera); - tileRect.x = point.x; - tileRect.y = point.y; + tileRect.x = TileToWorldX(tile.x, camera, layer); + tileRect.y = TileToWorldY(tile.y, camera, layer); if (intersectTest(shape, tileRect)) { results.push(tile); @@ -176252,7 +173721,7 @@ module.exports = GetTilesWithinShape; /***/ }), -/* 1314 */ +/* 1311 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176261,7 +173730,9 @@ module.exports = GetTilesWithinShape; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Gets the tiles in the given rectangular area (in world coordinates) of the layer. @@ -176285,16 +173756,13 @@ var GetTilesWithin = __webpack_require__(25); */ var GetTilesWithinWorldXY = function (worldX, worldY, width, height, filteringOptions, camera, layer) { - // Top left corner of the rect, rounded down to include partial tiles - var pointStart = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var xStart = pointStart.x; - var yStart = pointStart.y; + var xStart = WorldToTileX(worldX, true, camera, layer); + var yStart = WorldToTileY(worldY, true, camera, layer); // Bottom right corner of the rect, rounded up to include partial tiles - var pointEnd = layer.tilemapLayer.worldToTileXY(worldX + width, worldY + height, false, undefined, camera); - var xEnd = Math.ceil(pointEnd.x); - var yEnd = Math.ceil(pointEnd.y); + var xEnd = Math.ceil(WorldToTileX(worldX + width, false, camera, layer)); + var yEnd = Math.ceil(WorldToTileY(worldY + height, false, camera, layer)); return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer); }; @@ -176303,7 +173771,7 @@ module.exports = GetTilesWithinWorldXY; /***/ }), -/* 1315 */ +/* 1312 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176312,7 +173780,9 @@ module.exports = GetTilesWithinWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HasTileAt = __webpack_require__(469); +var HasTileAt = __webpack_require__(470); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns @@ -176331,9 +173801,9 @@ var HasTileAt = __webpack_require__(469); */ var HasTileAtWorldXY = function (worldX, worldY, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + return HasTileAt(tileX, tileY, layer); }; @@ -176341,7 +173811,7 @@ module.exports = HasTileAtWorldXY; /***/ }), -/* 1316 */ +/* 1313 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176350,7 +173820,9 @@ module.exports = HasTileAtWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PutTileAt = __webpack_require__(216); +var PutTileAt = __webpack_require__(218); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either @@ -176368,14 +173840,13 @@ var PutTileAt = __webpack_require__(216); * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. */ var PutTileAtWorldXY = function (tile, worldX, worldY, recalculateFaces, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); return PutTileAt(tile, tileX, tileY, recalculateFaces, layer); }; @@ -176383,7 +173854,7 @@ module.exports = PutTileAtWorldXY; /***/ }), -/* 1317 */ +/* 1314 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176393,7 +173864,7 @@ module.exports = PutTileAtWorldXY; */ var CalculateFacesWithin = __webpack_require__(51); -var PutTileAt = __webpack_require__(216); +var PutTileAt = __webpack_require__(218); /** * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified @@ -176411,7 +173882,6 @@ var PutTileAt = __webpack_require__(216); * @param {integer} tileY - The y coordinate, in tiles, not pixels. * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * */ var PutTilesAt = function (tilesArray, tileX, tileY, recalculateFaces, layer) { @@ -176448,7 +173918,7 @@ module.exports = PutTilesAt; /***/ }), -/* 1318 */ +/* 1315 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176457,8 +173927,8 @@ module.exports = PutTilesAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); -var GetRandom = __webpack_require__(180); +var GetTilesWithin = __webpack_require__(24); +var GetRandom = __webpack_require__(183); /** * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the @@ -176506,7 +173976,7 @@ module.exports = Randomize; /***/ }), -/* 1319 */ +/* 1316 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176515,8 +173985,9 @@ module.exports = Randomize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RemoveTileAt = __webpack_require__(470); - +var RemoveTileAt = __webpack_require__(471); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Removes the tile at the given world coordinates in the specified layer and updates the layer's @@ -176532,14 +174003,13 @@ var RemoveTileAt = __webpack_require__(470); * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. */ var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); }; @@ -176547,7 +174017,7 @@ module.exports = RemoveTileAtWorldXY; /***/ }), -/* 1320 */ +/* 1317 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176556,8 +174026,8 @@ module.exports = RemoveTileAtWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); -var Color = __webpack_require__(349); +var GetTilesWithin = __webpack_require__(24); +var Color = __webpack_require__(348); var defaultTileColor = new Color(105, 210, 231, 150); var defaultCollidingTileColor = new Color(243, 134, 48, 200); @@ -176636,7 +174106,7 @@ module.exports = RenderDebug; /***/ }), -/* 1321 */ +/* 1318 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176645,9 +174115,9 @@ module.exports = RenderDebug; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var SetLayerCollisionIndex = __webpack_require__(217); +var SetLayerCollisionIndex = __webpack_require__(219); /** * Sets collision on the given tile or tiles within a layer by index. You can pass in either a @@ -176705,7 +174175,7 @@ module.exports = SetCollision; /***/ }), -/* 1322 */ +/* 1319 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176714,9 +174184,9 @@ module.exports = SetCollision; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var SetLayerCollisionIndex = __webpack_require__(217); +var SetLayerCollisionIndex = __webpack_require__(219); /** * Sets collision on a range of tiles in a layer whose index is between the specified `start` and @@ -176780,7 +174250,7 @@ module.exports = SetCollisionBetween; /***/ }), -/* 1323 */ +/* 1320 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176789,9 +174259,9 @@ module.exports = SetCollisionBetween; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var SetLayerCollisionIndex = __webpack_require__(217); +var SetLayerCollisionIndex = __webpack_require__(219); /** * Sets collision on all tiles in the given layer, except for tiles that have an index specified in @@ -176837,7 +174307,7 @@ module.exports = SetCollisionByExclusion; /***/ }), -/* 1324 */ +/* 1321 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176846,9 +174316,9 @@ module.exports = SetCollisionByExclusion; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var HasValue = __webpack_require__(104); +var HasValue = __webpack_require__(99); /** * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property @@ -176912,7 +174382,7 @@ module.exports = SetCollisionByProperty; /***/ }), -/* 1325 */ +/* 1322 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176921,7 +174391,7 @@ module.exports = SetCollisionByProperty; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); /** @@ -176972,7 +174442,7 @@ module.exports = SetCollisionFromCollisionGroup; /***/ }), -/* 1326 */ +/* 1323 */ /***/ (function(module, exports) { /** @@ -177019,7 +174489,7 @@ module.exports = SetTileIndexCallback; /***/ }), -/* 1327 */ +/* 1324 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177028,7 +174498,7 @@ module.exports = SetTileIndexCallback; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. @@ -177062,7 +174532,7 @@ module.exports = SetTileLocationCallback; /***/ }), -/* 1328 */ +/* 1325 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177071,8 +174541,8 @@ module.exports = SetTileLocationCallback; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); -var ShuffleArray = __webpack_require__(110); +var GetTilesWithin = __webpack_require__(24); +var ShuffleArray = __webpack_require__(114); /** * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given @@ -177107,7 +174577,7 @@ module.exports = Shuffle; /***/ }), -/* 1329 */ +/* 1326 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177116,7 +174586,7 @@ module.exports = Shuffle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching @@ -177158,7 +174628,7 @@ module.exports = SwapByIndex; /***/ }), -/* 1330 */ +/* 1327 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177167,74 +174637,8 @@ module.exports = SwapByIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); - -/** - * Converts from orthogonal tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.TileToWorldX - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var OrthoTileToWorldX = function (tileX, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - var layerWorldX = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - - tileWidth *= tilemapLayer.scaleX; - } - - return layerWorldX + tileX * tileWidth; - - -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the TileToWorldXY function.'); - return null; -}; - -var TileToWorldX = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoTileToWorldX; - default: - return nullFunc; - } - -}; - -module.exports = TileToWorldX; - - -/***/ }), -/* 1331 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = __webpack_require__(10); +var TileToWorldX = __webpack_require__(139); +var TileToWorldY = __webpack_require__(140); var Vector2 = __webpack_require__(3); /** @@ -177242,7 +174646,7 @@ var Vector2 = __webpack_require__(3); * layer's position, scale and scroll. This will return a new Vector2 object or update the given * `point` object. * - * @function Phaser.Tilemaps.Components.OrthoTileToWorldXY + * @function Phaser.Tilemaps.Components.TileToWorldXY * @private * @since 3.0.0 * @@ -177251,196 +174655,24 @@ var Vector2 = __webpack_require__(3); * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Math.Vector2} The XY location in world coordinates. */ -var OrthoTileToWorldXY = function (tileX, tileY, point, camera, layer) +var TileToWorldXY = function (tileX, tileY, point, camera, layer) { if (point === undefined) { point = new Vector2(0, 0); } - - var tileHeight = layer.baseTileHeight; - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - var layerWorldX = 0; - var layerWorldY = 0; - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + point.x = TileToWorldX(tileX, camera, layer); + point.y = TileToWorldY(tileY, camera, layer); - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - - tileWidth *= tilemapLayer.scaleX; - - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - } - - point.x = layerWorldX + tileX * tileWidth; - point.y = layerWorldY + tileY * tileHeight; - - - return point; }; -/** - * Converts from isometric tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.IsoTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var IsoTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - point.x = layerWorldX + (tileX - tileY) * (tileWidth / 2); - point.y = layerWorldY + (tileX + tileY) * (tileHeight / 2); - - - return point; -}; - -/** - * Converts from staggered tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.StagTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var StagTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); - point.y = layerWorldY + tileY * (tileHeight / 2); - - return point; -}; - -/** - * Converts from hexagonal tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.HexTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var HexTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // similar to staggered, because Tiled uses the oddr representation. - point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); - point.y = layerWorldY + tileY * rowHeight; - - return point; -}; - -var TileToWorldXY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagTileToWorldXY; - case CONST.ISOMETRIC: - return IsoTileToWorldXY; - case CONST.HEXAGONAL: - return HexTileToWorldXY; - default: - return OrthoTileToWorldXY; - } - -}; - module.exports = TileToWorldXY; /***/ }), -/* 1332 */ +/* 1328 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177449,146 +174681,7 @@ module.exports = TileToWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ - -var CONST = __webpack_require__(10); - -/** - * Converts from orthogonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.TileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var OrthoTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - return layerWorldY + tileY * tileHeight; - -}; - - - -/** - * Converts from staggered tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.StagTileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var StagTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - return layerWorldY + tileY * (tileHeight / 2); - -}; - - -/** - * Converts from hexagonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.HexTileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var HexTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - var sidel = layer.tilemapLayer.tilemap.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // same as staggered - return layerWorldY + tileY * rowHeight; -}; - - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the TileToWorldXY function.'); - return null; -}; - -var TileToWorldY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagTileToWorldY; - case CONST.ISOMETRIC: - return nullFunc; - case CONST.HEXAGONAL: - return HexTileToWorldY; - default: - return OrthoTileToWorldY; - - } - -}; - -module.exports = TileToWorldY; - - -/***/ }), -/* 1333 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the @@ -177659,7 +174752,7 @@ module.exports = WeightedRandomize; /***/ }), -/* 1334 */ +/* 1329 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177668,17 +174761,16 @@ module.exports = WeightedRandomize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var WorldToTileX = __webpack_require__(471).func; -var WorldToTileY = __webpack_require__(472).func; +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); var Vector2 = __webpack_require__(3); /** - * Converts from world XY coordinates (pixels) to orthogonal tile XY coordinates (tile units), factoring in the + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the * layer's position, scale and scroll. This will return a new Vector2 object or update the given * `point` object. * - * @function Phaser.Tilemaps.Components.OrthoWorldToTileXY + * @function Phaser.Tilemaps.Components.WorldToTileXY * @private * @since 3.0.0 * @@ -177688,215 +174780,24 @@ var Vector2 = __webpack_require__(3); * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Math.Vector2} The XY location in tile units. */ -var OrthoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +var WorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) { if (point === undefined) { point = new Vector2(0, 0); } point.x = WorldToTileX(worldX, snapToFloor, camera, layer); point.y = WorldToTileY(worldY, snapToFloor, camera, layer); - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to isometric tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.IsoWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var IsoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - point.x = snapToFloor - ? Math.floor((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2) - : ((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2); - - point.y = snapToFloor - ? Math.floor((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2) - : ((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2); return point; }; -/** - * Converts from world XY coordinates (pixels) to hexagonal tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.HexWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var HexWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // similar to staggered, because Tiled uses the oddr representation. - point.y = snapToFloor - ? Math.floor((worldY / rowHeight)) - : (worldY / rowHeight); - point.x = snapToFloor - ? Math.floor((worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth) - : (worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth; - - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to staggered tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.StagWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var StagWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - - point.y = snapToFloor - ? Math.floor((worldY / (tileHeight / 2))) - : (worldY / (tileHeight / 2)); - point.x = snapToFloor - ? Math.floor((worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth) - : (worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth; - - - } - - return point; -}; - -var WorldToTileXY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagWorldToTileXY; - - case CONST.ISOMETRIC: - return IsoWorldToTileXY; - - case CONST.HEXAGONAL: - return HexWorldToTileXY; - - default: - return OrthoWorldToTileXY; - - } - -}; - module.exports = WorldToTileXY; /***/ }), -/* 1335 */ +/* 1330 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177911,18 +174812,18 @@ module.exports = WorldToTileXY; module.exports = { - Parse: __webpack_require__(473), - Parse2DArray: __webpack_require__(218), - ParseCSV: __webpack_require__(474), + Parse: __webpack_require__(472), + Parse2DArray: __webpack_require__(220), + ParseCSV: __webpack_require__(473), - Impact: __webpack_require__(1336), - Tiled: __webpack_require__(1337) + Impact: __webpack_require__(1331), + Tiled: __webpack_require__(1332) }; /***/ }), -/* 1336 */ +/* 1331 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177937,15 +174838,15 @@ module.exports = { module.exports = { - ParseTileLayers: __webpack_require__(487), - ParseTilesets: __webpack_require__(488), - ParseWeltmeister: __webpack_require__(486) + ParseTileLayers: __webpack_require__(486), + ParseTilesets: __webpack_require__(487), + ParseWeltmeister: __webpack_require__(485) }; /***/ }), -/* 1337 */ +/* 1332 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177960,22 +174861,22 @@ module.exports = { module.exports = { - AssignTileProperties: __webpack_require__(485), - Base64Decode: __webpack_require__(477), - BuildTilesetIndex: __webpack_require__(484), - ParseGID: __webpack_require__(219), - ParseImageLayers: __webpack_require__(478), - ParseJSONTiled: __webpack_require__(475), - ParseObject: __webpack_require__(221), - ParseObjectLayers: __webpack_require__(482), - ParseTileLayers: __webpack_require__(476), - ParseTilesets: __webpack_require__(479) + AssignTileProperties: __webpack_require__(484), + Base64Decode: __webpack_require__(476), + BuildTilesetIndex: __webpack_require__(483), + ParseGID: __webpack_require__(221), + ParseImageLayers: __webpack_require__(477), + ParseJSONTiled: __webpack_require__(474), + ParseObject: __webpack_require__(223), + ParseObjectLayers: __webpack_require__(481), + ParseTileLayers: __webpack_require__(475), + ParseTilesets: __webpack_require__(478) }; /***/ }), -/* 1338 */ +/* 1333 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -177989,12 +174890,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1339); + renderWebGL = __webpack_require__(1334); } if (true) { - renderCanvas = __webpack_require__(1340); + renderCanvas = __webpack_require__(1335); } module.exports = { @@ -178006,7 +174907,7 @@ module.exports = { /***/ }), -/* 1339 */ +/* 1334 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178015,9 +174916,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ - -var Utils = __webpack_require__(9); -var CONST = __webpack_require__(10); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -178088,26 +174987,14 @@ var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPer continue; } - var frameWidth = 0; - var frameHeight = 0; - - if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) - { - // we use the tileset width and height because in isometric maps the tileset's height is often different from the tilemap's. - frameWidth = tileset.tileWidth; - frameHeight = tileset.tileHeight; - } - else - { - frameWidth = tile.width; - frameHeight = tile.height; - } + var frameWidth = tile.width; + var frameHeight = tile.height; var frameX = tileTexCoords.x; var frameY = tileTexCoords.y; - var tw = frameWidth * 0.5; - var th = frameHeight * 0.5; + var tw = tile.width * 0.5; + var th = tile.height * 0.5; var tint = getTint(tile.tint, alpha * tile.alpha); @@ -178116,7 +175003,7 @@ var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPer texture, texture.width, texture.height, x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy), - frameWidth, frameHeight, + tile.width, tile.height, sx, sy, tile.rotation, tile.flipX, tile.flipY, @@ -178137,8 +175024,8 @@ module.exports = DynamicTilemapLayerWebGLRenderer; /***/ }), -/* 1340 */ -/***/ (function(module, exports, __webpack_require__) { +/* 1335 */ +/***/ (function(module, exports) { /** * @author Richard Davey @@ -178146,8 +175033,6 @@ module.exports = DynamicTilemapLayerWebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); - /** * Renders this Game Object with the Canvas Renderer to the given Camera. * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. @@ -178169,6 +175054,7 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe var renderTiles = src.culledTiles; var tileCount = renderTiles.length; + if (tileCount === 0) { return; @@ -178218,8 +175104,8 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe for (var i = 0; i < tileCount; i++) { - var tile = renderTiles[i]; + var tileset = gidMap[tile.index]; if (!tileset) @@ -178228,23 +175114,12 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe } var image = tileset.image.getSourceImage(); - var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); - + if (tileTexCoords) { - var width = tile.width; - var height = tile.width; - - if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) - { - // we use the tileset width and height because in isometric and hexagonal maps the tileset's height is often different from the tilemap's. - width = tileset.tileWidth; - height = tileset.tileHeight; - } - - var halfWidth = width / 2; - var halfHeight = height / 2; + var halfWidth = tile.width / 2; + var halfHeight = tile.height / 2; ctx.save(); @@ -178261,18 +175136,17 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe } ctx.globalAlpha = alpha * tile.alpha; - + ctx.drawImage( image, tileTexCoords.x, tileTexCoords.y, - tileset.tileWidth, tileset.tileHeight, + tile.width, tile.height, -halfWidth, -halfHeight, - width, height + tile.width, tile.height ); ctx.restore(); } - } ctx.restore(); @@ -178282,7 +175156,7 @@ module.exports = DynamicTilemapLayerCanvasRenderer; /***/ }), -/* 1341 */ +/* 1336 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178296,12 +175170,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1342); + renderWebGL = __webpack_require__(1337); } if (true) { - renderCanvas = __webpack_require__(1343); + renderCanvas = __webpack_require__(1338); } module.exports = { @@ -178313,7 +175187,7 @@ module.exports = { /***/ }), -/* 1342 */ +/* 1337 */ /***/ (function(module, exports) { /** @@ -178385,7 +175259,7 @@ module.exports = StaticTilemapLayerWebGLRenderer; /***/ }), -/* 1343 */ +/* 1338 */ /***/ (function(module, exports) { /** @@ -178519,7 +175393,7 @@ module.exports = StaticTilemapLayerCanvasRenderer; /***/ }), -/* 1344 */ +/* 1339 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178528,8 +175402,8 @@ module.exports = StaticTilemapLayerCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); -var ParseToTilemap = __webpack_require__(222); +var GameObjectCreator = __webpack_require__(16); +var ParseToTilemap = __webpack_require__(224); /** * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. @@ -178563,7 +175437,7 @@ GameObjectCreator.register('tilemap', function (config) /***/ }), -/* 1345 */ +/* 1340 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178573,7 +175447,7 @@ GameObjectCreator.register('tilemap', function (config) */ var GameObjectFactory = __webpack_require__(5); -var ParseToTilemap = __webpack_require__(222); +var ParseToTilemap = __webpack_require__(224); /** * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. @@ -178629,7 +175503,7 @@ GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, widt /***/ }), -/* 1346 */ +/* 1341 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178644,14 +175518,14 @@ GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, widt module.exports = { - Clock: __webpack_require__(1347), - TimerEvent: __webpack_require__(492) + Clock: __webpack_require__(1342), + TimerEvent: __webpack_require__(491) }; /***/ }), -/* 1347 */ +/* 1342 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178661,9 +175535,9 @@ module.exports = { */ var Class = __webpack_require__(0); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var TimerEvent = __webpack_require__(492); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var TimerEvent = __webpack_require__(491); /** * @classdesc @@ -179057,7 +175931,7 @@ module.exports = Clock; /***/ }), -/* 1348 */ +/* 1343 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179066,8 +175940,8 @@ module.exports = Clock; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(87); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(89); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Tweens @@ -179075,13 +175949,13 @@ var Extend = __webpack_require__(18); var Tweens = { - Builders: __webpack_require__(1349), - Events: __webpack_require__(227), + Builders: __webpack_require__(1344), + Events: __webpack_require__(229), - TweenManager: __webpack_require__(1364), - Tween: __webpack_require__(226), - TweenData: __webpack_require__(228), - Timeline: __webpack_require__(498) + TweenManager: __webpack_require__(1359), + Tween: __webpack_require__(228), + TweenData: __webpack_require__(230), + Timeline: __webpack_require__(497) }; @@ -179092,7 +175966,7 @@ module.exports = Tweens; /***/ }), -/* 1349 */ +/* 1344 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179107,23 +175981,23 @@ module.exports = Tweens; module.exports = { - GetBoolean: __webpack_require__(86), - GetEaseFunction: __webpack_require__(67), - GetNewValue: __webpack_require__(138), - GetProps: __webpack_require__(493), - GetTargets: __webpack_require__(223), - GetTweens: __webpack_require__(494), - GetValueOp: __webpack_require__(224), - NumberTweenBuilder: __webpack_require__(495), - StaggerBuilder: __webpack_require__(496), - TimelineBuilder: __webpack_require__(497), - TweenBuilder: __webpack_require__(139) + GetBoolean: __webpack_require__(88), + GetEaseFunction: __webpack_require__(82), + GetNewValue: __webpack_require__(142), + GetProps: __webpack_require__(492), + GetTargets: __webpack_require__(225), + GetTweens: __webpack_require__(493), + GetValueOp: __webpack_require__(226), + NumberTweenBuilder: __webpack_require__(494), + StaggerBuilder: __webpack_require__(495), + TimelineBuilder: __webpack_require__(496), + TweenBuilder: __webpack_require__(143) }; /***/ }), -/* 1350 */ +/* 1345 */ /***/ (function(module, exports) { /** @@ -179198,7 +176072,7 @@ module.exports = [ /***/ }), -/* 1351 */ +/* 1346 */ /***/ (function(module, exports) { /** @@ -179234,7 +176108,7 @@ module.exports = 'complete'; /***/ }), -/* 1352 */ +/* 1347 */ /***/ (function(module, exports) { /** @@ -179271,7 +176145,7 @@ module.exports = 'loop'; /***/ }), -/* 1353 */ +/* 1348 */ /***/ (function(module, exports) { /** @@ -179308,7 +176182,7 @@ module.exports = 'pause'; /***/ }), -/* 1354 */ +/* 1349 */ /***/ (function(module, exports) { /** @@ -179345,7 +176219,7 @@ module.exports = 'resume'; /***/ }), -/* 1355 */ +/* 1350 */ /***/ (function(module, exports) { /** @@ -179381,7 +176255,7 @@ module.exports = 'start'; /***/ }), -/* 1356 */ +/* 1351 */ /***/ (function(module, exports) { /** @@ -179418,7 +176292,7 @@ module.exports = 'update'; /***/ }), -/* 1357 */ +/* 1352 */ /***/ (function(module, exports) { /** @@ -179458,7 +176332,7 @@ module.exports = 'active'; /***/ }), -/* 1358 */ +/* 1353 */ /***/ (function(module, exports) { /** @@ -179499,7 +176373,7 @@ module.exports = 'complete'; /***/ }), -/* 1359 */ +/* 1354 */ /***/ (function(module, exports) { /** @@ -179543,7 +176417,7 @@ module.exports = 'loop'; /***/ }), -/* 1360 */ +/* 1355 */ /***/ (function(module, exports) { /** @@ -179588,7 +176462,7 @@ module.exports = 'repeat'; /***/ }), -/* 1361 */ +/* 1356 */ /***/ (function(module, exports) { /** @@ -179628,7 +176502,7 @@ module.exports = 'start'; /***/ }), -/* 1362 */ +/* 1357 */ /***/ (function(module, exports) { /** @@ -179671,7 +176545,7 @@ module.exports = 'update'; /***/ }), -/* 1363 */ +/* 1358 */ /***/ (function(module, exports) { /** @@ -179717,7 +176591,7 @@ module.exports = 'yoyo'; /***/ }), -/* 1364 */ +/* 1359 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179726,15 +176600,15 @@ module.exports = 'yoyo'; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayRemove = __webpack_require__(117); +var ArrayRemove = __webpack_require__(121); var Class = __webpack_require__(0); -var NumberTweenBuilder = __webpack_require__(495); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var StaggerBuilder = __webpack_require__(496); -var TimelineBuilder = __webpack_require__(497); -var TWEEN_CONST = __webpack_require__(87); -var TweenBuilder = __webpack_require__(139); +var NumberTweenBuilder = __webpack_require__(494); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var StaggerBuilder = __webpack_require__(495); +var TimelineBuilder = __webpack_require__(496); +var TWEEN_CONST = __webpack_require__(89); +var TweenBuilder = __webpack_require__(143); /** * @classdesc @@ -180489,7 +177363,7 @@ module.exports = TweenManager; /***/ }), -/* 1365 */ +/* 1360 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180504,16 +177378,16 @@ module.exports = TweenManager; module.exports = { - Array: __webpack_require__(178), - Base64: __webpack_require__(1366), - Objects: __webpack_require__(1368), - String: __webpack_require__(1372) + Array: __webpack_require__(181), + Base64: __webpack_require__(1361), + Objects: __webpack_require__(1363), + String: __webpack_require__(1367) }; /***/ }), -/* 1366 */ +/* 1361 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180528,14 +177402,14 @@ module.exports = { module.exports = { - ArrayBufferToBase64: __webpack_require__(1367), - Base64ToArrayBuffer: __webpack_require__(381) + ArrayBufferToBase64: __webpack_require__(1362), + Base64ToArrayBuffer: __webpack_require__(380) }; /***/ }), -/* 1367 */ +/* 1362 */ /***/ (function(module, exports) { /** @@ -180593,7 +177467,7 @@ module.exports = ArrayBufferToBase64; /***/ }), -/* 1368 */ +/* 1363 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180608,26 +177482,26 @@ module.exports = ArrayBufferToBase64; module.exports = { - Clone: __webpack_require__(65), - Extend: __webpack_require__(18), + Clone: __webpack_require__(67), + Extend: __webpack_require__(17), GetAdvancedValue: __webpack_require__(15), GetFastValue: __webpack_require__(2), - GetMinMaxValue: __webpack_require__(1369), + GetMinMaxValue: __webpack_require__(1364), GetValue: __webpack_require__(6), - HasAll: __webpack_require__(1370), - HasAny: __webpack_require__(400), - HasValue: __webpack_require__(104), + HasAll: __webpack_require__(1365), + HasAny: __webpack_require__(399), + HasValue: __webpack_require__(99), IsPlainObject: __webpack_require__(7), - Merge: __webpack_require__(120), - MergeRight: __webpack_require__(1371), - Pick: __webpack_require__(481), - SetValue: __webpack_require__(420) + Merge: __webpack_require__(107), + MergeRight: __webpack_require__(1366), + Pick: __webpack_require__(480), + SetValue: __webpack_require__(419) }; /***/ }), -/* 1369 */ +/* 1364 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180637,7 +177511,7 @@ module.exports = { */ var GetValue = __webpack_require__(6); -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); /** * Retrieves and clamps a numerical value from an object. @@ -180666,7 +177540,7 @@ module.exports = GetMinMaxValue; /***/ }), -/* 1370 */ +/* 1365 */ /***/ (function(module, exports) { /** @@ -180703,7 +177577,7 @@ module.exports = HasAll; /***/ }), -/* 1371 */ +/* 1366 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180712,7 +177586,7 @@ module.exports = HasAll; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); +var Clone = __webpack_require__(67); /** * Creates a new Object using all values from obj1. @@ -180746,7 +177620,7 @@ module.exports = MergeRight; /***/ }), -/* 1372 */ +/* 1367 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180761,17 +177635,17 @@ module.exports = MergeRight; module.exports = { - Format: __webpack_require__(1373), - Pad: __webpack_require__(157), - Reverse: __webpack_require__(1374), - UppercaseFirst: __webpack_require__(176), - UUID: __webpack_require__(191) + Format: __webpack_require__(1368), + Pad: __webpack_require__(160), + Reverse: __webpack_require__(1369), + UppercaseFirst: __webpack_require__(179), + UUID: __webpack_require__(194) }; /***/ }), -/* 1373 */ +/* 1368 */ /***/ (function(module, exports) { /** @@ -180806,7 +177680,7 @@ module.exports = Format; /***/ }), -/* 1374 */ +/* 1369 */ /***/ (function(module, exports) { /** @@ -180835,7 +177709,7 @@ module.exports = Reverse; /***/ }), -/* 1375 */ +/* 1370 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180851,26 +177725,31 @@ module.exports = Reverse; module.exports = { - SoundManagerCreator: __webpack_require__(375), + SoundManagerCreator: __webpack_require__(374), Events: __webpack_require__(59), - BaseSound: __webpack_require__(122), - BaseSoundManager: __webpack_require__(121), + BaseSound: __webpack_require__(125), + BaseSoundManager: __webpack_require__(124), - WebAudioSound: __webpack_require__(382), - WebAudioSoundManager: __webpack_require__(380), + WebAudioSound: __webpack_require__(381), + WebAudioSoundManager: __webpack_require__(379), - HTML5AudioSound: __webpack_require__(377), - HTML5AudioSoundManager: __webpack_require__(376), + HTML5AudioSound: __webpack_require__(376), + HTML5AudioSoundManager: __webpack_require__(375), - NoAudioSound: __webpack_require__(379), - NoAudioSoundManager: __webpack_require__(378) + NoAudioSound: __webpack_require__(378), + NoAudioSoundManager: __webpack_require__(377) }; /***/ }), +/* 1371 */, +/* 1372 */, +/* 1373 */, +/* 1374 */, +/* 1375 */, /* 1376 */, /* 1377 */, /* 1378 */, @@ -180923,7 +177802,32 @@ module.exports = { /* 1425 */, /* 1426 */, /* 1427 */, -/* 1428 */ +/* 1428 */, +/* 1429 */, +/* 1430 */, +/* 1431 */, +/* 1432 */, +/* 1433 */, +/* 1434 */, +/* 1435 */, +/* 1436 */, +/* 1437 */, +/* 1438 */, +/* 1439 */, +/* 1440 */, +/* 1441 */, +/* 1442 */, +/* 1443 */, +/* 1444 */, +/* 1445 */, +/* 1446 */, +/* 1447 */, +/* 1448 */, +/* 1449 */, +/* 1450 */, +/* 1451 */, +/* 1452 */, +/* 1453 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** @@ -180932,10 +177836,10 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -__webpack_require__(513); +__webpack_require__(512); -var CONST = __webpack_require__(10); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(29); +var Extend = __webpack_require__(17); /** * @namespace Phaser @@ -180950,37 +177854,37 @@ var Extend = __webpack_require__(18); var Phaser = { - Actions: __webpack_require__(236), - Animations: __webpack_require__(633), - Cache: __webpack_require__(634), - Cameras: __webpack_require__(637), - Core: __webpack_require__(720), + Actions: __webpack_require__(238), + Animations: __webpack_require__(632), + Cache: __webpack_require__(633), + Cameras: __webpack_require__(636), + Core: __webpack_require__(719), Class: __webpack_require__(0), - Create: __webpack_require__(779), - Curves: __webpack_require__(785), - Data: __webpack_require__(788), - Display: __webpack_require__(790), - DOM: __webpack_require__(807), - Events: __webpack_require__(808), - Game: __webpack_require__(810), - GameObjects: __webpack_require__(903), - Geom: __webpack_require__(423), - Input: __webpack_require__(1191), - Loader: __webpack_require__(1225), - Math: __webpack_require__(165), + Create: __webpack_require__(781), + Curves: __webpack_require__(787), + Data: __webpack_require__(790), + Display: __webpack_require__(792), + DOM: __webpack_require__(809), + Events: __webpack_require__(810), + Game: __webpack_require__(812), + GameObjects: __webpack_require__(905), + Geom: __webpack_require__(422), + Input: __webpack_require__(1187), + Loader: __webpack_require__(1221), + Math: __webpack_require__(168), Physics: { - Arcade: __webpack_require__(1251) + Arcade: __webpack_require__(1247) }, - Plugins: __webpack_require__(1294), - Scale: __webpack_require__(1296), - Scene: __webpack_require__(369), - Scenes: __webpack_require__(1297), - Structs: __webpack_require__(1299), - Textures: __webpack_require__(1300), - Tilemaps: __webpack_require__(1302), - Time: __webpack_require__(1346), - Tweens: __webpack_require__(1348), - Utils: __webpack_require__(1365) + Plugins: __webpack_require__(1292), + Scale: __webpack_require__(1294), + Scene: __webpack_require__(368), + Scenes: __webpack_require__(1295), + Structs: __webpack_require__(1297), + Textures: __webpack_require__(1298), + Tilemaps: __webpack_require__(1300), + Time: __webpack_require__(1341), + Tweens: __webpack_require__(1343), + Utils: __webpack_require__(1360) }; @@ -180990,7 +177894,7 @@ Phaser = Extend(false, Phaser, CONST); if (true) { - Phaser.Sound = __webpack_require__(1375); + Phaser.Sound = __webpack_require__(1370); } // Export it @@ -181005,7 +177909,7 @@ global.Phaser = Phaser; * -- Dick Brandon */ -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(512))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(511))) /***/ }) /******/ ]); diff --git a/dist/phaser-arcade-physics.min.js b/dist/phaser-arcade-physics.min.js index be499821f..1d5ef78f6 100644 --- a/dist/phaser-arcade-physics.min.js +++ b/dist/phaser-arcade-physics.min.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("Phaser",[],e):"object"==typeof exports?exports.Phaser=e():t.Phaser=e()}(window,function(){return function(t){var e={};function i(n){if(e[n])return e[n].exports;var s=e[n]={i:n,l:!1,exports:{}};return t[n].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)i.d(n,s,function(e){return t[e]}.bind(null,s));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=1428)}([function(t,e){function i(t,e,i){var n=i?t[e]:Object.getOwnPropertyDescriptor(t,e);return!i&&n.value&&"object"==typeof n.value&&(n=n.value),!(!n||!function(t){return!!t.get&&"function"==typeof t.get||!!t.set&&"function"==typeof t.set}(n))&&(void 0===n.enumerable&&(n.enumerable=!0),void 0===n.configurable&&(n.configurable=!0),n)}function n(t,e){var i=Object.getOwnPropertyDescriptor(t,e);return!!i&&(i.value&&"object"==typeof i.value&&(i=i.value),!1===i.configurable)}function s(t,e,s,r){for(var a in e)if(e.hasOwnProperty(a)){var h=i(e,a,s);if(!1!==h){if(n((r||t).prototype,a)){if(o.ignoreFinals)continue;throw new Error("cannot override final property '"+a+"', set Class.ignoreFinals = true to skip")}Object.defineProperty(t.prototype,a,h)}else t.prototype[a]=e[a]}}function r(t,e){if(e){Array.isArray(e)||(e=[e]);for(var i=0;i0&&(i=1/Math.sqrt(i),this.x=t*i,this.y=e*i),this},normalizeRightHand:function(){var t=this.x;return this.x=-1*this.y,this.y=t,this},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this},transformMat3:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this},transformMat4:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[4]*i+n[12],this.y=n[1]*e+n[5]*i+n[13],this},reset:function(){return this.x=0,this.y=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0),n.LEFT=new n(-1,0),n.UP=new n(0,-1),n.DOWN=new n(0,1),n.ONE=new n(1,1),t.exports=n},function(t,e,i){var n=i(0),s=i(46),r=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=t),this.type=s.POINT,this.x=t,this.y=e},setTo:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.x=t,this.y=e,this}});t.exports=r},function(t,e,i){var n=i(0),s=i(24),r=i(22),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},existing:function(t){return(t.renderCanvas||t.renderWebGL)&&this.displayList.add(t),t.preUpdate&&this.updateList.add(t),t},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectFactory",o,"add"),t.exports=o},function(t,e){t.exports=function(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=i,o=0;o>>0},getTintAppendFloatAlpha:function(t,e){return((255&(255*e|0))<<24|t)>>>0},getTintAppendFloatAlphaAndSwap:function(t,e){return((255&(255*e|0))<<24|(255&(0|t))<<16|(255&(t>>8|0))<<8|255&(t>>16|0))>>>0},getFloatsFromUintRGB:function(t){return[(255&(t>>16|0))/255,(255&(t>>8|0))/255,(255&(0|t))/255]},getComponentCount:function(t,e){for(var i=0,n=0;n=this.right?this.width=0:this.width=this.right-t,this.x=t}},right:{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}},top:{get:function(){return this.y},set:function(t){t>=this.bottom?this.height=0:this.height=this.bottom-t,this.y=t}},bottom:{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}},centerX:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},centerY:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=u},function(t,e,i){var n=i(0),s=i(276),r=i(109),o=i(11),a=i(88),h=new n({Extends:o,initialize:function(t,e){o.call(this),this.scene=t,this.type=e,this.state=0,this.parentContainer=null,this.name="",this.active=!0,this.tabIndex=-1,this.data=null,this.renderFlags=15,this.cameraFilter=0,this.input=null,this.body=null,this.ignoreDestroy=!1,t.sys.queueDepthSort()},setActive:function(t){return this.active=t,this},setName:function(t){return this.name=t,this},setState:function(t){return this.state=t,this},setDataEnabled:function(){return this.data||(this.data=new r(this)),this},setData:function(t,e){return this.data||(this.data=new r(this)),this.data.set(t,e),this},getData:function(t){return this.data||(this.data=new r(this)),this.data.get(t)},setInteractive:function(t,e,i){return this.scene.sys.input.enable(this,t,e,i),this},disableInteractive:function(){return this.input&&(this.input.enabled=!1),this},removeInteractive:function(){return this.scene.sys.input.clear(this),this.input=void 0,this},update:function(){},toJSON:function(){return s(this)},willRender:function(t){return!(h.RENDER_MASK!==this.renderFlags||0!==this.cameraFilter&&this.cameraFilter&t.id)},getIndexList:function(){for(var t=this,e=this.parentContainer,i=[];e&&(i.unshift(e.getIndex(t)),t=e,e.parentContainer);)e=e.parentContainer;return i.unshift(this.scene.sys.displayList.getIndex(t)),i},destroy:function(t){if(void 0===t&&(t=!1),this.scene&&!this.ignoreDestroy){this.preDestroy&&this.preDestroy.call(this),this.emit(a.DESTROY,this);var e=this.scene.sys;t||(e.displayList.remove(this),e.updateList.remove(this)),this.input&&(e.input.clear(this),this.input=void 0),this.data&&(this.data.destroy(),this.data=void 0),this.body&&(this.body.destroy(),this.body=void 0),t||e.queueDepthSort(),this.active=!1,this.visible=!1,this.scene=void 0,this.parentContainer=void 0,this.removeAllListeners()}}});h.RENDER_MASK=15,t.exports=h},function(t,e,i){var n=i(165),s=i(6);t.exports=function(t,e,i){var r=s(t,e,null);if(null===r)return i;if(Array.isArray(r))return n.RND.pick(r);if("object"==typeof r){if(r.hasOwnProperty("randInt"))return n.RND.integerInRange(r.randInt[0],r.randInt[1]);if(r.hasOwnProperty("randFloat"))return n.RND.realInRange(r.randFloat[0],r.randFloat[1])}else if("function"==typeof r)return r(e);return r}},function(t,e){var i={PI2:2*Math.PI,TAU:.5*Math.PI,EPSILON:1e-6,DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,RND:null,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER||-9007199254740991,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991};t.exports=i},function(t,e,i){var n=i(0),s=i(24),r=i(22),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectCreator",o,"make"),t.exports=o},function(t,e,i){var n=i(7),s=function(){var t,e,i,r,o,a,h=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof h&&(c=h,h=arguments[1]||{},l=2),u===l&&(h=this,--l);l=400&&t.status<=599&&(n=!1),this.resetXHR(),this.loader.nextFile(this,n)},onError:function(){this.resetXHR(),this.loader.nextFile(this,!1)},onProgress:function(t){t.lengthComputable&&(this.bytesLoaded=t.loaded,this.bytesTotal=t.total,this.percentComplete=Math.min(this.bytesLoaded/this.bytesTotal,1),this.loader.emit(r.FILE_PROGRESS,this,this.percentComplete))},onProcess:function(){this.state=s.FILE_PROCESSING,this.onProcessComplete()},onProcessComplete:function(){this.state=s.FILE_COMPLETE,this.multiFile&&this.multiFile.onFileComplete(this),this.loader.fileProcessComplete(this)},onProcessError:function(){this.state=s.FILE_ERRORED,this.multiFile&&this.multiFile.onFileFailed(this),this.loader.fileProcessComplete(this)},hasCacheConflict:function(){return this.cache&&this.cache.exists(this.key)},addToCache:function(){this.cache&&this.cache.add(this.key,this.data),this.pendingDestroy()},pendingDestroy:function(t){void 0===t&&(t=this.data);var e=this.key,i=this.type;this.loader.emit(r.FILE_COMPLETE,e,i,t),this.loader.emit(r.FILE_KEY_COMPLETE+i+"-"+e,e,i,t),this.loader.flagForRemoval(this)},destroy:function(){this.loader=null,this.cache=null,this.xhrSettings=null,this.multiFile=null,this.linkFile=null,this.data=null}});c.createObjectURL=function(t,e,i){if("function"==typeof URL)t.src=URL.createObjectURL(e);else{var n=new FileReader;n.onload=function(){t.removeAttribute("crossOrigin"),t.src="data:"+(e.type||i)+";base64,"+n.result.split(",")[1]},n.onerror=t.onerror,n.readAsDataURL(e)}},c.revokeObjectURL=function(t){"function"==typeof URL&&URL.revokeObjectURL(t.src)},t.exports=c},function(t,e,i){t.exports={BOOT:i(701),CREATE:i(702),DESTROY:i(703),PAUSE:i(704),POST_UPDATE:i(705),PRE_UPDATE:i(706),READY:i(707),RENDER:i(708),RESUME:i(709),SHUTDOWN:i(710),SLEEP:i(711),START:i(712),TRANSITION_COMPLETE:i(713),TRANSITION_INIT:i(714),TRANSITION_OUT:i(715),TRANSITION_START:i(716),TRANSITION_WAKE:i(717),UPDATE:i(718),WAKE:i(719)}},function(t,e){t.exports=function(t,e,i){return Math.max(e,Math.min(i,t))}},function(t,e){var i={},n={},s={register:function(t,e,n,s){void 0===s&&(s=!1),i[t]={plugin:e,mapping:n,custom:s}},registerCustom:function(t,e,i,s){n[t]={plugin:e,mapping:i,data:s}},hasCore:function(t){return i.hasOwnProperty(t)},hasCustom:function(t){return n.hasOwnProperty(t)},getCore:function(t){return i[t]},getCustom:function(t){return n[t]},getCustomClass:function(t){return n.hasOwnProperty(t)?n[t].plugin:null},remove:function(t){i.hasOwnProperty(t)&&delete i[t]},removeCustom:function(t){n.hasOwnProperty(t)&&delete n[t]},destroyCorePlugins:function(){for(var t in i)i.hasOwnProperty(t)&&delete i[t]},destroyCustomPlugins:function(){for(var t in n)n.hasOwnProperty(t)&&delete n[t]}};t.exports=s},function(t,e,i){var n=i(2);t.exports=function(t,e,i,s,r,o){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=o.width),void 0===s&&(s=o.height);var a=n(r,"isNotEmpty",!1),h=n(r,"isColliding",!1),l=n(r,"hasInterestingFace",!1);t<0&&(i+=t,t=0),e<0&&(s+=e,e=0),t+i>o.width&&(i=Math.max(o.width-t,0)),e+s>o.height&&(s=Math.max(o.height-e,0));for(var u=[],c=e;c=0;o--)t[o][e]=i+a*n,a++;return t}},function(t,e,i){var n,s,r,o=i(10),a=i(161),h=[],l=!1;t.exports={create2D:function(t,e,i){return n(t,e,i,o.CANVAS)},create:n=function(t,e,i,n,r){var u;void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=o.CANVAS),void 0===r&&(r=!1);var c=s(n);return null===c?(c={parent:t,canvas:document.createElement("canvas"),type:n},n===o.CANVAS&&h.push(c),u=c.canvas):(c.parent=t,u=c.canvas),r&&(c.parent=u),u.width=e,u.height=i,l&&n===o.CANVAS&&a.disable(u.getContext("2d")),u},createWebGL:function(t,e,i){return n(t,e,i,o.WEBGL)},disableSmoothing:function(){l=!0},enableSmoothing:function(){l=!1},first:s=function(t){if(void 0===t&&(t=o.CANVAS),t===o.WEBGL)return null;for(var e=0;e0?Math.acos(e/this.scaleX):-Math.acos(e/this.scaleX):n||r?s.TAU-(r>0?Math.acos(-n/this.scaleY):-Math.acos(n/this.scaleY)):0}},scaleX:{get:function(){return Math.sqrt(this.a*this.a+this.b*this.b)}},scaleY:{get:function(){return Math.sqrt(this.c*this.c+this.d*this.d)}},loadIdentity:function(){var t=this.matrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,this},translate:function(t,e){var i=this.matrix;return i[4]=i[0]*t+i[2]*e+i[4],i[5]=i[1]*t+i[3]*e+i[5],this},scale:function(t,e){var i=this.matrix;return i[0]*=t,i[1]*=t,i[2]*=e,i[3]*=e,this},rotate:function(t){var e=Math.sin(t),i=Math.cos(t),n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3];return n[0]=s*i+o*e,n[1]=r*i+a*e,n[2]=s*-e+o*i,n[3]=r*-e+a*i,this},multiply:function(t,e){var i=this.matrix,n=t.matrix,s=i[0],r=i[1],o=i[2],a=i[3],h=i[4],l=i[5],u=n[0],c=n[1],d=n[2],f=n[3],p=n[4],g=n[5],v=void 0===e?this:e;return v.a=u*s+c*o,v.b=u*r+c*a,v.c=d*s+f*o,v.d=d*r+f*a,v.e=p*s+g*o+h,v.f=p*r+g*a+l,v},multiplyWithOffset:function(t,e,i){var n=this.matrix,s=t.matrix,r=n[0],o=n[1],a=n[2],h=n[3],l=e*r+i*a+n[4],u=e*o+i*h+n[5],c=s[0],d=s[1],f=s[2],p=s[3],g=s[4],v=s[5];return n[0]=c*r+d*a,n[1]=c*o+d*h,n[2]=f*r+p*a,n[3]=f*o+p*h,n[4]=g*r+v*a+l,n[5]=g*o+v*h+u,this},transform:function(t,e,i,n,s,r){var o=this.matrix,a=o[0],h=o[1],l=o[2],u=o[3],c=o[4],d=o[5];return o[0]=t*a+e*l,o[1]=t*h+e*u,o[2]=i*a+n*l,o[3]=i*h+n*u,o[4]=s*a+r*l+c,o[5]=s*h+r*u+d,this},transformPoint:function(t,e,i){void 0===i&&(i={x:0,y:0});var n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5];return i.x=t*s+e*o+h,i.y=t*r+e*a+l,i},invert:function(){var t=this.matrix,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=e*s-i*n;return t[0]=s/a,t[1]=-i/a,t[2]=-n/a,t[3]=e/a,t[4]=(n*o-s*r)/a,t[5]=-(e*o-i*r)/a,this},copyFrom:function(t){var e=this.matrix;return e[0]=t.a,e[1]=t.b,e[2]=t.c,e[3]=t.d,e[4]=t.e,e[5]=t.f,this},copyFromArray:function(t){var e=this.matrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],this},copyToContext:function(t){var e=this.matrix;return t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t},setToContext:function(t){var e=this.matrix;return t.setTransform(e[0],e[1],e[2],e[3],e[4],e[5]),t},copyToArray:function(t){var e=this.matrix;return void 0===t?t=[e[0],e[1],e[2],e[3],e[4],e[5]]:(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]),t},setTransform:function(t,e,i,n,s,r){var o=this.matrix;return o[0]=t,o[1]=e,o[2]=i,o[3]=n,o[4]=s,o[5]=r,this},decomposeMatrix:function(){var t=this.decomposedMatrix,e=this.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(t.translateX=e[4],t.translateY=e[5],i||n){var a=Math.sqrt(i*i+n*n);t.rotation=n>0?Math.acos(i/a):-Math.acos(i/a),t.scaleX=a,t.scaleY=o/a}else if(s||r){var h=Math.sqrt(s*s+r*r);t.rotation=.5*Math.PI-(r>0?Math.acos(-s/h):-Math.acos(s/h)),t.scaleX=o/h,t.scaleY=h}else t.rotation=0,t.scaleX=0,t.scaleY=0;return t},applyITRS:function(t,e,i,n,s){var r=this.matrix,o=Math.sin(i),a=Math.cos(i);return r[4]=t,r[5]=e,r[0]=a*n,r[1]=o*n,r[2]=-o*s,r[3]=a*s,this},applyInverse:function(t,e,i){void 0===i&&(i=new r);var n=this.matrix,s=n[0],o=n[1],a=n[2],h=n[3],l=n[4],u=n[5],c=1/(s*h+a*-o);return i.x=h*c*t+-a*c*e+(u*a-l*h)*c,i.y=s*c*e+-o*c*t+(-u*s+l*o)*c,i},getX:function(t,e){return t*this.a+e*this.c+this.e},getY:function(t,e){return t*this.b+e*this.d+this.f},getCSSMatrix:function(){var t=this.matrix;return"matrix("+t[0]+","+t[1]+","+t[2]+","+t[3]+","+t[4]+","+t[5]+")"},destroy:function(){this.matrix=null,this.decomposedMatrix=null}});t.exports=o},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(56),a=new n({Extends:r,Mixins:[s.AlphaSingle,s.BlendMode,s.ComputedSize,s.Depth,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Transform,s.Visible],initialize:function(t,e,i){void 0===e&&(e="Shape"),r.call(this,t,e),this.geom=i,this.pathData=[],this.pathIndexes=[],this.fillColor=16777215,this.fillAlpha=1,this.strokeColor=16777215,this.strokeAlpha=1,this.lineWidth=1,this.isFilled=!1,this.isStroked=!1,this.closePath=!0,this._tempLine=new o,this.initPipeline()},setFillStyle:function(t,e){return void 0===e&&(e=1),void 0===t?this.isFilled=!1:(this.fillColor=t,this.fillAlpha=e,this.isFilled=!0),this},setStrokeStyle:function(t,e,i){return void 0===i&&(i=1),void 0===t?this.isStroked=!1:(this.lineWidth=t,this.strokeColor=e,this.strokeAlpha=i,this.isStroked=!0),this},setClosePath:function(t){return this.closePath=t,this},preDestroy:function(){this.geom=null,this._tempLine=null,this.pathData=[],this.pathIndexes=[]}});t.exports=a},function(t,e,i){var n=i(0),s=i(159),r=i(290),o=i(160),a=i(291),h=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=255),this.r=0,this.g=0,this.b=0,this.a=255,this._h=0,this._s=0,this._v=0,this._locked=!1,this.gl=[0,0,0,1],this._color=0,this._color32=0,this._rgba="",this.setTo(t,e,i,n)},transparent:function(){return this._locked=!0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this._locked=!1,this.update(!0)},setTo:function(t,e,i,n,s){return void 0===n&&(n=255),void 0===s&&(s=!0),this._locked=!0,this.red=t,this.green=e,this.blue=i,this.alpha=n,this._locked=!1,this.update(s)},setGLTo:function(t,e,i,n){return void 0===n&&(n=1),this._locked=!0,this.redGL=t,this.greenGL=e,this.blueGL=i,this.alphaGL=n,this._locked=!1,this.update(!0)},setFromRGB:function(t){return this._locked=!0,this.red=t.r,this.green=t.g,this.blue=t.b,t.hasOwnProperty("a")&&(this.alpha=t.a),this._locked=!1,this.update(!0)},setFromHSV:function(t,e,i){return o(t,e,i,this)},update:function(t){if(void 0===t&&(t=!1),this._locked)return this;var e=this.r,i=this.g,n=this.b,o=this.a;return this._color=s(e,i,n),this._color32=r(e,i,n,o),this._rgba="rgba("+e+","+i+","+n+","+o/255+")",t&&a(e,i,n,this),this},updateHSV:function(){var t=this.r,e=this.g,i=this.b;return a(t,e,i,this),this},clone:function(){return new h(this.r,this.g,this.b,this.a)},gray:function(t){return this.setTo(t,t,t)},random:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t)),n=Math.floor(t+Math.random()*(e-t)),s=Math.floor(t+Math.random()*(e-t));return this.setTo(i,n,s)},randomGray:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t));return this.setTo(i,i,i)},saturate:function(t){return this.s+=t/100,this},desaturate:function(t){return this.s-=t/100,this},lighten:function(t){return this.v+=t/100,this},darken:function(t){return this.v-=t/100,this},brighten:function(t){var e=this.r,i=this.g,n=this.b;return e=Math.max(0,Math.min(255,e-Math.round(-t/100*255))),i=Math.max(0,Math.min(255,i-Math.round(-t/100*255))),n=Math.max(0,Math.min(255,n-Math.round(-t/100*255))),this.setTo(e,i,n)},color:{get:function(){return this._color}},color32:{get:function(){return this._color32}},rgba:{get:function(){return this._rgba}},redGL:{get:function(){return this.gl[0]},set:function(t){this.gl[0]=Math.min(Math.abs(t),1),this.r=Math.floor(255*this.gl[0]),this.update(!0)}},greenGL:{get:function(){return this.gl[1]},set:function(t){this.gl[1]=Math.min(Math.abs(t),1),this.g=Math.floor(255*this.gl[1]),this.update(!0)}},blueGL:{get:function(){return this.gl[2]},set:function(t){this.gl[2]=Math.min(Math.abs(t),1),this.b=Math.floor(255*this.gl[2]),this.update(!0)}},alphaGL:{get:function(){return this.gl[3]},set:function(t){this.gl[3]=Math.min(Math.abs(t),1),this.a=Math.floor(255*this.gl[3]),this.update()}},red:{get:function(){return this.r},set:function(t){t=Math.floor(Math.abs(t)),this.r=Math.min(t,255),this.gl[0]=t/255,this.update(!0)}},green:{get:function(){return this.g},set:function(t){t=Math.floor(Math.abs(t)),this.g=Math.min(t,255),this.gl[1]=t/255,this.update(!0)}},blue:{get:function(){return this.b},set:function(t){t=Math.floor(Math.abs(t)),this.b=Math.min(t,255),this.gl[2]=t/255,this.update(!0)}},alpha:{get:function(){return this.a},set:function(t){t=Math.floor(Math.abs(t)),this.a=Math.min(t,255),this.gl[3]=t/255,this.update()}},h:{get:function(){return this._h},set:function(t){this._h=t,o(t,this._s,this._v,this)}},s:{get:function(){return this._s},set:function(t){this._s=t,o(this._h,t,this._v,this)}},v:{get:function(){return this._v},set:function(t){this._v=t,o(this._h,this._s,t,this)}}});t.exports=h},function(t,e){t.exports={CSV:0,TILED_JSON:1,ARRAY_2D:2,WELTMEISTER:3}},function(t,e){t.exports=function(t,e,i,n,s,r){var o;void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=1);var a=0,h=t.length;if(1===r)for(o=s;o=0;o--)t[o][e]+=i+a*n,a++;return t}},function(t,e,i){var n=i(16);t.exports=function(t){return t*n.DEG_TO_RAD}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.fillColor,r=n||e.fillAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.fillStyle="rgba("+o+","+a+","+h+","+r+")"}},,function(t,e){t.exports=function(t){return t.y+t.height-t.height*t.originY}},function(t,e){t.exports=function(t,e){return t.y=e+t.height*t.originY,t}},function(t,e){t.exports=function(t){return t.x-t.width*t.originX}},function(t,e){t.exports=function(t,e){return t.x=e+t.width*t.originX,t}},function(t,e){t.exports=function(t){return t.x+t.width-t.width*t.originX}},function(t,e){t.exports=function(t,e){return t.x=e-t.width+t.width*t.originX,t}},function(t,e){t.exports=function(t,e){return t.y=e-t.height+t.height*t.originY,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY}},function(t,e){t.exports={CIRCLE:0,ELLIPSE:1,LINE:2,POINT:3,POLYGON:4,RECTANGLE:5,TRIANGLE:6}},function(t,e){t.exports=function(t,e,i){return!(t.width<=0||t.height<=0)&&t.x<=e&&t.x+t.width>=e&&t.y<=i&&t.y+t.height>=i}},function(t,e,i){t.exports={DESTROY:i(642),FADE_IN_COMPLETE:i(643),FADE_IN_START:i(644),FADE_OUT_COMPLETE:i(645),FADE_OUT_START:i(646),FLASH_COMPLETE:i(647),FLASH_START:i(648),PAN_COMPLETE:i(649),PAN_START:i(650),POST_RENDER:i(651),PRE_RENDER:i(652),SHAKE_COMPLETE:i(653),SHAKE_START:i(654),ZOOM_COMPLETE:i(655),ZOOM_START:i(656)}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.strokeColor,r=n||e.strokeAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.strokeStyle="rgba("+o+","+a+","+h+","+r+")",t.lineWidth=e.lineWidth}},function(t,e){t.exports={DYNAMIC_BODY:0,STATIC_BODY:1,GROUP:2,TILEMAPLAYER:3,FACING_NONE:10,FACING_UP:11,FACING_DOWN:12,FACING_LEFT:13,FACING_RIGHT:14}},function(t,e,i){var n=i(136),s=i(25);t.exports=function(t,e,i,r,o){for(var a=null,h=null,l=null,u=null,c=s(t,e,i,r,null,o),d=0;d0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}},function(t,e,i){var n=i(0),s=i(270),r=i(147),o=i(46),a=i(148),h=i(3),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=o.LINE,this.x1=t,this.y1=e,this.x2=i,this.y2=n},getPoint:function(t,e){return s(this,t,e)},getPoints:function(t,e,i){return r(this,t,e,i)},getRandomPoint:function(t){return a(this,t)},setTo:function(t,e,i,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x1=t,this.y1=e,this.x2=i,this.y2=n,this},getPointA:function(t){return void 0===t&&(t=new h),t.set(this.x1,this.y1),t},getPointB:function(t){return void 0===t&&(t=new h),t.set(this.x2,this.y2),t},left:{get:function(){return Math.min(this.x1,this.x2)},set:function(t){this.x1<=this.x2?this.x1=t:this.x2=t}},right:{get:function(){return Math.max(this.x1,this.x2)},set:function(t){this.x1>this.x2?this.x1=t:this.x2=t}},top:{get:function(){return Math.min(this.y1,this.y2)},set:function(t){this.y1<=this.y2?this.y1=t:this.y2=t}},bottom:{get:function(){return Math.max(this.y1,this.y2)},set:function(t){this.y1>this.y2?this.y1=t:this.y2=t}}});t.exports=l},function(t,e){t.exports=function(t){return Math.sqrt((t.x2-t.x1)*(t.x2-t.x1)+(t.y2-t.y1)*(t.y2-t.y1))}},function(t,e){t.exports=function(t,e,i){var n=i-e;return e+((t-e)%n+n)%n}},function(t,e,i){t.exports={COMPLETE:i(880),DECODED:i(881),DECODED_ALL:i(882),DESTROY:i(883),DETUNE:i(884),GLOBAL_DETUNE:i(885),GLOBAL_MUTE:i(886),GLOBAL_RATE:i(887),GLOBAL_VOLUME:i(888),LOOP:i(889),LOOPED:i(890),MUTE:i(891),PAUSE_ALL:i(892),PAUSE:i(893),PLAY:i(894),RATE:i(895),RESUME_ALL:i(896),RESUME:i(897),SEEK:i(898),STOP_ALL:i(899),STOP:i(900),UNLOCKED:i(901),VOLUME:i(902)}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(6),l=i(7),u=new n({Extends:r,initialize:function(t,e,i,n,o){var u="json";if(l(e)){var c=e;e=a(c,"key"),i=a(c,"url"),n=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"dataKey",o)}var d={type:"json",cache:t.cacheManager.json,extension:u,responseType:"text",key:e,url:i,xhrSettings:n,config:o};r.call(this,t,d),l(i)&&(this.data=o?h(i,o):i,this.state=s.FILE_POPULATED)},onProcess:function(){if(this.state!==s.FILE_POPULATED){this.state=s.FILE_PROCESSING;var t=JSON.parse(this.xhrLoader.responseText),e=this.config;this.data="string"==typeof e?h(t,e,t):t}this.onProcessComplete()}});o.register("json",function(t,e,i,n){if(Array.isArray(t))for(var s=0;s80*i){n=h=t[0],a=l=t[1];for(var T=i;Th&&(h=u),f>l&&(l=f);g=0!==(g=Math.max(h-n,l-a))?1/g:0}return o(y,x,i,n,a,g),x}function s(t,e,i,n,s){var r,o;if(s===b(t,e,i,n)>0)for(r=e;r=e;r-=n)o=E(r,t[r],t[r+1],o);return o&&y(o,o.next)&&(_(o),o=o.next),o}function r(t,e){if(!t)return t;e||(e=t);var i,n=t;do{if(i=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(_(n),(n=e=n.prev)===n.next)break;i=!0}}while(i||n!==e);return e}function o(t,e,i,n,s,c,d){if(t){!d&&c&&function(t,e,i,n){var s=t;do{null===s.z&&(s.z=f(s.x,s.y,e,i,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,n,s,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,n=i,a=0,e=0;e0||h>0&&n;)0!==a&&(0===h||!n||i.z<=n.z)?(s=i,i=i.nextZ,a--):(s=n,n=n.nextZ,h--),r?r.nextZ=s:t=s,s.prevZ=r,r=s;i=n}r.nextZ=null,l*=2}while(o>1)}(s)}(t,n,s,c);for(var p,g,v=t;t.prev!==t.next;)if(p=t.prev,g=t.next,c?h(t,n,s,c):a(t))e.push(p.i/i),e.push(t.i/i),e.push(g.i/i),_(t),t=g.next,v=g.next;else if((t=g)===v){d?1===d?o(t=l(t,e,i),e,i,n,s,c,2):2===d&&u(t,e,i,n,s,c):o(r(t),e,i,n,s,c,1);break}}}function a(t){var e=t.prev,i=t,n=t.next;if(m(e,i,n)>=0)return!1;for(var s=t.next.next;s!==t.prev;){if(g(e.x,e.y,i.x,i.y,n.x,n.y,s.x,s.y)&&m(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function h(t,e,i,n){var s=t.prev,r=t,o=t.next;if(m(s,r,o)>=0)return!1;for(var a=s.xr.x?s.x>o.x?s.x:o.x:r.x>o.x?r.x:o.x,u=s.y>r.y?s.y>o.y?s.y:o.y:r.y>o.y?r.y:o.y,c=f(a,h,e,i,n),d=f(l,u,e,i,n),p=t.prevZ,v=t.nextZ;p&&p.z>=c&&v&&v.z<=d;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;v&&v.z<=d;){if(v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function l(t,e,i){var n=t;do{var s=n.prev,r=n.next.next;!y(s,r)&&x(s,n,n.next,r)&&T(s,r)&&T(r,s)&&(e.push(s.i/i),e.push(n.i/i),e.push(r.i/i),_(n),_(n.next),n=t=r),n=n.next}while(n!==t);return n}function u(t,e,i,n,s,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&v(h,l)){var u=w(h,l);return h=r(h,h.next),u=r(u,u.next),o(h,e,i,n,s,a),void o(u,e,i,n,s,a)}l=l.next}h=h.next}while(h!==t)}function c(t,e){return t.x-e.x}function d(t,e){if(e=function(t,e){var i,n=e,s=t.x,r=t.y,o=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){var a=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=s&&a>o){if(o=a,a===s){if(r===n.y)return n;if(r===n.next.y)return n.next}i=n.x=n.x&&n.x>=u&&s!==n.x&&g(ri.x)&&T(n,t)&&(i=n,d=h),n=n.next;return i}(t,e)){var i=w(e,t);r(i,i.next)}}function f(t,e,i,n,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*s)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*s)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function p(t){var e=t,i=t;do{e.x=0&&(t-o)*(n-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(s-o)*(n-a)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&x(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&T(t,e)&&T(e,t)&&function(t,e){var i=t,n=!1,s=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&i.next.y!==i.y&&s<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,i,n){return!!(y(t,e)&&y(i,n)||y(t,n)&&y(i,e))||m(t,e,i)>0!=m(t,e,n)>0&&m(i,n,t)>0!=m(i,n,e)>0}function T(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function w(t,e){var i=new A(t.i,t.x,t.y),n=new A(e.i,e.x,e.y),s=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,n.next=i,i.prev=n,r.next=n,n.prev=r,n}function E(t,e,i,n){var s=new A(t,e,i);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function _(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function A(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function b(t,e,i,n){for(var s=0,r=e,o=i-n;r0&&(n+=t[s-1].length,i.holes.push(n))}return i}},function(t,e){t.exports=function(t){var e={};for(var i in t)Array.isArray(t[i])?e[i]=t[i].slice(0):e[i]=t[i];return e}},function(t,e){t.exports=function(t,e,i,n){var s=t.length;if(e<0||e>s||e>=i||i>s||e+i>s){if(n)throw new Error("Range Error: Values outside acceptable range");return!1}return!0}},function(t,e,i){var n=i(163),s=i(176);t.exports=function(t,e){var i=n.Power0;if("string"==typeof t)if(n.hasOwnProperty(t))i=n[t];else{var r="";t.indexOf(".")&&("in"===(r=t.substr(t.indexOf(".")+1)).toLowerCase()?r="easeIn":"out"===r.toLowerCase()?r="easeOut":"inout"===r.toLowerCase()&&(r="easeInOut")),t=s(t.substr(0,t.indexOf(".")+1)+r),n.hasOwnProperty(t)&&(i=n[t])}else"function"==typeof t?i=t:Array.isArray(t)&&t.length;if(!e)return i;var o=e.slice(0);return o.unshift(0),function(t){return o[0]=t,i.apply(this,o)}}},function(t,e,i){var n=i(9);t.exports=function(t,e,i,s,r){var o=t.strokeTint,a=n.getTintAppendFloatAlphaAndSwap(e.strokeColor,e.strokeAlpha*i);o.TL=a,o.TR=a,o.BL=a,o.BR=a;var h=e.pathData,l=h.length-1,u=e.lineWidth,c=u/2,d=h[0]-s,f=h[1]-r;e.closePath||(l-=2);for(var p=2;p=this.x2&&this.x1>=this.x3?this.x1-t:this.x2>=this.x1&&this.x2>=this.x3?this.x2-t:this.x3-t,this.x1-=e,this.x2-=e,this.x3-=e}},top:{get:function(){return Math.min(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1<=this.y2&&this.y1<=this.y3?this.y1-t:this.y2<=this.y1&&this.y2<=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}},bottom:{get:function(){return Math.max(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1>=this.y2&&this.y1>=this.y3?this.y1-t:this.y2>=this.y1&&this.y2>=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}}});t.exports=u},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=new n({Extends:r,initialize:function t(e,i,n,s,o){var l,u="png";if(h(i)){var c=i;i=a(c,"key"),n=a(c,"url"),l=a(c,"normalMap"),s=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"frameConfig")}Array.isArray(n)&&(l=n[1],n=n[0]);var d={type:"image",cache:e.textureManager,extension:u,responseType:"blob",key:i,url:n,xhrSettings:s,config:o};if(r.call(this,e,d),l){var f=new t(e,this.key,l,s,o);f.type="normalMap",this.setLink(f),e.addFile(f)}},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=new Image,this.data.crossOrigin=this.crossOrigin;var t=this;this.data.onload=function(){r.revokeObjectURL(t.data),t.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(t.data),t.onProcessError()},r.createObjectURL(this.data,this.xhrLoader.response,"image/png")},addToCache:function(){var t,e=this.linkFile;e&&e.state===s.FILE_COMPLETE?(t="image"===this.type?this.cache.addImage(this.key,this.data,e.data):this.cache.addImage(e.key,e.data,this.data),this.pendingDestroy(t),e.pendingDestroy(t)):e||(t=this.cache.addImage(this.key,this.data),this.pendingDestroy(t))}});o.register("image",function(t,e,i){if(Array.isArray(t))for(var n=0;nthis.right||e>this.bottom)},copy:function(t){return this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.visible=t.visible,this.setFlip(t.flipX,t.flipY),this.tint=t.tint,this.rotation=t.rotation,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext,this},getCollisionGroup:function(){return this.tileset?this.tileset.getTileCollisionGroup(this.index):null},getTileData:function(){return this.tileset?this.tileset.getTileData(this.index):null},getLeft:function(t){var e=this.tilemapLayer;return e?e.tileToWorldX(this.x,t):this.x*this.baseWidth},getRight:function(t){var e=this.tilemapLayer;return e?this.getLeft(t)+this.width*e.scaleX:this.getLeft(t)+this.width},getTop:function(t){var e=this.tilemapLayer;return e?e.tileToWorldY(this.y,t)-(this.height-this.baseHeight)*e.scaleY:this.y*this.baseHeight-(this.height-this.baseHeight)},getBottom:function(t){var e=this.tilemapLayer;return e?this.getTop(t)+this.height*e.scaleY:this.getTop(t)+this.height},getBounds:function(t,e){return void 0===e&&(e=new o),e.x=this.getLeft(),e.y=this.getTop(),e.width=this.getRight()-e.x,e.height=this.getBottom()-e.y,e},getCenterX:function(t){return(this.getLeft(t)+this.getRight(t))/2},getCenterY:function(t){return(this.getTop(t)+this.getBottom(t))/2},destroy:function(){this.collisionCallback=void 0,this.collisionCallbackContext=void 0,this.properties=void 0},intersects:function(t,e,i,n){return!(i<=this.pixelX||n<=this.pixelY||t>=this.right||e>=this.bottom)},isInteresting:function(t,e){return t&&e?this.canCollide||this.hasInterestingFace:t?this.collides:!!e&&this.hasInterestingFace},resetCollision:function(t){(void 0===t&&(t=!0),this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,t)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},resetFaces:function(){return this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this},setCollision:function(t,e,i,n,s){(void 0===e&&(e=t),void 0===i&&(i=t),void 0===n&&(n=t),void 0===s&&(s=!0),this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=n,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=n,s)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},setCollisionCallback:function(t,e){return null===t?(this.collisionCallback=void 0,this.collisionCallbackContext=void 0):(this.collisionCallback=t,this.collisionCallbackContext=e),this},setSize:function(t,e,i,n){return void 0!==t&&(this.width=t),void 0!==e&&(this.height=e),void 0!==i&&(this.baseWidth=i),void 0!==n&&(this.baseHeight=n),this.updatePixelXY(),this},updatePixelXY:function(){if(this.layer.orientation===n.ISOMETRIC)this.pixelX=(this.x-this.y)*this.baseWidth*.5,this.pixelY=(this.x+this.y)*this.baseHeight*.5;else if(this.layer.orientation===n.STAGGERED)this.pixelX=this.x*this.baseWidth+this.y%2*(this.baseWidth/2),this.pixelY=this.y*(this.baseHeight/2);else if(this.layer.orientation===n.HEXAGONAL){var t=this.layer.hexSideLength,e=(this.baseHeight-t)/2+t;this.pixelX=this.x*this.baseWidth+this.y%2*(this.baseWidth/2),this.pixelY=this.y*e}else this.layer.orientation===n.ORTHOGONAL&&(this.pixelX=this.x*this.baseWidth,this.pixelY=this.y*this.baseHeight);return this},canCollide:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}},collides:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}},hasInterestingFace:{get:function(){return this.faceTop||this.faceBottom||this.faceLeft||this.faceRight}},tileset:{get:function(){var t=this.layer.tilemapLayer;if(t){var e=t.gidMap[this.index];if(e)return e}return null}},tilemapLayer:{get:function(){return this.layer.tilemapLayer}},tilemap:{get:function(){var t=this.tilemapLayer;return t?t.tilemap:null}}});t.exports=a},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(958),a=new n({Extends:r,Mixins:[s.Alpha,s.BlendMode,s.Depth,s.Flip,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Size,s.TextureCrop,s.Tint,s.Transform,s.Visible,o],initialize:function(t,e,i,n,o){r.call(this,t,"Sprite"),this._crop=this.resetCropObject(),this.anims=new s.Animation(this),this.setTexture(n,o),this.setPosition(e,i),this.setSizeToFrame(),this.setOriginFromFrame(),this.initPipeline()},preUpdate:function(t,e){this.anims.update(t,e)},play:function(t,e,i){return this.anims.play(t,e,i),this},toJSON:function(){return s.ToJSON(this)},preDestroy:function(){this.anims.destroy(),this.anims=void 0}});t.exports=a},function(t,e){t.exports=function(t){return t.x-t.width*t.originX+.5*t.width}},function(t,e){t.exports=function(t,e){var i=t.width*t.originX;return t.x=e+i-.5*t.width,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY+.5*t.height}},function(t,e){t.exports=function(t,e){var i=t.height*t.originY;return t.y=e+i-.5*t.height,t}},function(t,e){t.exports=function(t,e){if(!(e>=t.length)){for(var i=t.length-1,n=t[e],s=e;si&&(e=i/2);var n=Math.max(1,Math.round(i/e));return s(this.getSpacedPoints(n),t)},getDistancePoints:function(t){var e=this.getLength(),i=Math.max(1,e/t);return this.getSpacedPoints(i)},getEndPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(1,t)},getLength:function(){var t=this.getLengths();return t[t.length-1]},getLengths:function(t){if(void 0===t&&(t=this.arcLengthDivisions),this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,i=[],n=this.getPoint(0,this._tmpVec2A),s=0;i.push(0);for(var r=1;r<=t;r++)s+=(e=this.getPoint(r/t,this._tmpVec2B)).distance(n),i.push(s),n.copy(e);return this.cacheArcLengths=i,i},getPointAt:function(t,e){var i=this.getUtoTmapping(t);return this.getPoint(i,e)},getPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++)i.push(this.getPoint(n/t));return i},getRandomPoint:function(t){return void 0===t&&(t=new o),this.getPoint(Math.random(),t)},getSpacedPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++){var s=this.getUtoTmapping(n/t,null,t);i.push(this.getPoint(s))}return i},getStartPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(0,t)},getTangent:function(t,e){void 0===e&&(e=new o);var i=t-1e-4,n=t+1e-4;return i<0&&(i=0),n>1&&(n=1),this.getPoint(i,this._tmpVec2A),this.getPoint(n,e),e.subtract(this._tmpVec2A).normalize()},getTangentAt:function(t,e){var i=this.getUtoTmapping(t);return this.getTangent(i,e)},getTFromDistance:function(t,e){return t<=0?0:this.getUtoTmapping(0,t,e)},getUtoTmapping:function(t,e,i){var n,s=this.getLengths(i),r=0,o=s.length;n=e?Math.min(e,s[o-1]):t*s[o-1];for(var a,h=0,l=o-1;h<=l;)if((a=s[r=Math.floor(h+(l-h)/2)]-n)<0)h=r+1;else{if(!(a>0)){l=r;break}l=r-1}if(s[r=l]===n)return r/(o-1);var u=s[r];return(r+(n-u)/(s[r+1]-u))/(o-1)},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths()}});t.exports=a},function(t,e,i){t.exports={ADD:i(859),COMPLETE:i(860),FILE_COMPLETE:i(861),FILE_KEY_COMPLETE:i(862),FILE_LOAD_ERROR:i(863),FILE_LOAD:i(864),FILE_PROGRESS:i(865),POST_PROCESS:i(866),PROGRESS:i(867),START:i(868)}},function(t,e){t.exports=function(t,e,i){var n=t.x3-t.x1,s=t.y3-t.y1,r=t.x2-t.x1,o=t.y2-t.y1,a=e-t.x1,h=i-t.y1,l=n*n+s*s,u=n*r+s*o,c=n*a+s*h,d=r*r+o*o,f=r*a+o*h,p=l*d-u*u,g=0===p?0:1/p,v=(d*c-u*f)*g,m=(l*f-u*c)*g;return v>=0&&m>=0&&v+m<1}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.x1,r=t.y1,o=t.x2,a=t.y2,h=e.x1,l=e.y1,u=e.x2,c=e.y2,d=(u-h)*(r-l)-(c-l)*(s-h),f=(o-s)*(r-l)-(a-r)*(s-h),p=(c-l)*(o-s)-(u-h)*(a-r);if(0===p)return!1;var g=d/p,v=f/p;return g>=0&&g<=1&&v>=0&&v<=1&&(i.x=s+g*(o-s),i.y=r+g*(a-r),!0)}},function(t,e){t.exports=function(t){return Math.atan2(t.y2-t.y1,t.x2-t.x1)}},,function(t,e,i){var n=i(23);t.exports=function(t,e,i){return(i-e)*(t=n(t,0,1))}},function(t,e){t.exports=function(t,e,i){return t&&t.hasOwnProperty(e)?t[e]:i}},function(t,e){t.exports={CREATED:0,INIT:1,DELAY:2,OFFSET_DELAY:3,PENDING_RENDER:4,PLAYING_FORWARD:5,PLAYING_BACKWARD:6,HOLD_DELAY:7,REPEAT_DELAY:8,COMPLETE:9,PENDING_ADD:20,PAUSED:21,LOOP_DELAY:22,ACTIVE:23,COMPLETE_DELAY:24,PENDING_REMOVE:25,REMOVED:26}},function(t,e,i){t.exports={DESTROY:i(577),VIDEO_COMPLETE:i(578),VIDEO_CREATED:i(579),VIDEO_ERROR:i(580),VIDEO_LOOP:i(581),VIDEO_PLAY:i(582),VIDEO_SEEKED:i(583),VIDEO_SEEKING:i(584),VIDEO_STOP:i(585),VIDEO_TIMEOUT:i(586),VIDEO_UNLOCKED:i(587)}},function(t,e,i){var n=i(0),s=i(12),r=i(35),o=i(11),a=i(48),h=i(13),l=i(30),u=i(158),c=i(3),d=new n({Extends:o,Mixins:[s.Alpha,s.Visible],initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),o.call(this),this.scene,this.sceneManager,this.scaleManager,this.cameraManager,this.id=0,this.name="",this.resolution=1,this.roundPixels=!1,this.useBounds=!1,this.worldView=new h,this.dirty=!0,this._x=t,this._y=e,this._cx=0,this._cy=0,this._cw=0,this._ch=0,this._width=i,this._height=n,this._bounds=new h,this._scrollX=0,this._scrollY=0,this._zoom=1,this._rotation=0,this.matrix=new l,this.transparent=!0,this.backgroundColor=u("rgba(0,0,0,0)"),this.disableCull=!1,this.culledObjects=[],this.midPoint=new c(i/2,n/2),this.originX=.5,this.originY=.5,this._customViewport=!1,this.mask=null,this._maskCamera=null},setOrigin:function(t,e){return void 0===t&&(t=.5),void 0===e&&(e=t),this.originX=t,this.originY=e,this},getScroll:function(t,e,i){void 0===i&&(i=new c);var n=.5*this.width,s=.5*this.height;return i.x=t-n,i.y=e-s,this.useBounds&&(i.x=this.clampX(i.x),i.y=this.clampY(i.y)),i},centerOnX:function(t){var e=.5*this.width;return this.midPoint.x=t,this.scrollX=t-e,this.useBounds&&(this.scrollX=this.clampX(this.scrollX)),this},centerOnY:function(t){var e=.5*this.height;return this.midPoint.y=t,this.scrollY=t-e,this.useBounds&&(this.scrollY=this.clampY(this.scrollY)),this},centerOn:function(t,e){return this.centerOnX(t),this.centerOnY(e),this},centerToBounds:function(){if(this.useBounds){var t=this._bounds,e=.5*this.width,i=.5*this.height;this.midPoint.set(t.centerX,t.centerY),this.scrollX=t.centerX-e,this.scrollY=t.centerY-i}return this},centerToSize:function(){return this.scrollX=.5*this.width,this.scrollY=.5*this.height,this},cull:function(t){if(this.disableCull)return t;var e=this.matrix.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(!o)return t;var a=e[4],h=e[5],l=this.scrollX,u=this.scrollY,c=this.width,d=this.height,f=this.culledObjects,p=t.length;o=1/o,f.length=0;for(var g=0;gC&&wb&&Es&&(t=s),t},clampY:function(t){var e=this._bounds,i=this.displayHeight,n=e.y+(i-this.height)/2,s=Math.max(n,n+e.height-i);return ts&&(t=s),t},removeBounds:function(){return this.useBounds=!1,this.dirty=!0,this._bounds.setEmpty(),this},setAngle:function(t){return void 0===t&&(t=0),this.rotation=r(t),this},setBackgroundColor:function(t){return void 0===t&&(t="rgba(0,0,0,0)"),this.backgroundColor=u(t),this.transparent=0===this.backgroundColor.alpha,this},setBounds:function(t,e,i,n,s){return void 0===s&&(s=!1),this._bounds.setTo(t,e,i,n),this.dirty=!0,this.useBounds=!0,s?this.centerToBounds():(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},getBounds:function(t){void 0===t&&(t=new h);var e=this._bounds;return t.setTo(e.x,e.y,e.width,e.height),t},setName:function(t){return void 0===t&&(t=""),this.name=t,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setRotation:function(t){return void 0===t&&(t=0),this.rotation=t,this},setRoundPixels:function(t){return this.roundPixels=t,this},setScene:function(t){this.scene&&this._customViewport&&this.sceneManager.customViewports--,this.scene=t;var e=t.sys;this.sceneManager=e.game.scene,this.scaleManager=e.scale,this.cameraManager=e.cameras;var i=this.scaleManager.resolution;return this.resolution=i,this._cx=this._x*i,this._cy=this._y*i,this._cw=this._width*i,this._ch=this._height*i,this.updateSystem(),this},setScroll:function(t,e){return void 0===e&&(e=t),this.scrollX=t,this.scrollY=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},setViewport:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setZoom:function(t){return void 0===t&&(t=1),0===t&&(t=.001),this.zoom=t,this},setMask:function(t,e){return void 0===e&&(e=!0),this.mask=t,this._maskCamera=e?this.cameraManager.default:this,this},clearMask:function(t){return void 0===t&&(t=!1),t&&this.mask&&this.mask.destroy(),this.mask=null,this},toJSON:function(){var t={name:this.name,x:this.x,y:this.y,width:this.width,height:this.height,zoom:this.zoom,rotation:this.rotation,roundPixels:this.roundPixels,scrollX:this.scrollX,scrollY:this.scrollY,backgroundColor:this.backgroundColor.rgba};return this.useBounds&&(t.bounds={x:this._bounds.x,y:this._bounds.y,width:this._bounds.width,height:this._bounds.height}),t},update:function(){},updateSystem:function(){if(this.scaleManager){var t=0!==this._x||0!==this._y||this.scaleManager.width!==this._width||this.scaleManager.height!==this._height,e=this.sceneManager;t&&!this._customViewport?e.customViewports++:!t&&this._customViewport&&e.customViewports--,this.dirty=!0,this._customViewport=t}},destroy:function(){this.emit(a.DESTROY,this),this.removeAllListeners(),this.matrix.destroy(),this.culledObjects=[],this._customViewport&&this.sceneManager.customViewports--,this._bounds=null,this.scene=null,this.scaleManager=null,this.sceneManager=null,this.cameraManager=null},x:{get:function(){return this._x},set:function(t){this._x=t,this._cx=t*this.resolution,this.updateSystem()}},y:{get:function(){return this._y},set:function(t){this._y=t,this._cy=t*this.resolution,this.updateSystem()}},width:{get:function(){return this._width},set:function(t){this._width=t,this._cw=t*this.resolution,this.updateSystem()}},height:{get:function(){return this._height},set:function(t){this._height=t,this._ch=t*this.resolution,this.updateSystem()}},scrollX:{get:function(){return this._scrollX},set:function(t){this._scrollX=t,this.dirty=!0}},scrollY:{get:function(){return this._scrollY},set:function(t){this._scrollY=t,this.dirty=!0}},zoom:{get:function(){return this._zoom},set:function(t){this._zoom=t,this.dirty=!0}},rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this.dirty=!0}},centerX:{get:function(){return this.x+.5*this.width}},centerY:{get:function(){return this.y+.5*this.height}},displayWidth:{get:function(){return this.width/this.zoom}},displayHeight:{get:function(){return this.height/this.zoom}}});t.exports=d},function(t,e,i){t.exports={ENTER_FULLSCREEN:i(695),FULLSCREEN_FAILED:i(696),FULLSCREEN_UNSUPPORTED:i(697),LEAVE_FULLSCREEN:i(698),ORIENTATION_CHANGE:i(699),RESIZE:i(700)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=i(0),s=i(23),r=i(18),o=new n({initialize:function(t,e,i,n,s,r,o){this.texture=t,this.name=e,this.source=t.source[i],this.sourceIndex=i,this.glTexture=this.source.glTexture,this.cutX,this.cutY,this.cutWidth,this.cutHeight,this.x=0,this.y=0,this.width,this.height,this.halfWidth,this.halfHeight,this.centerX,this.centerY,this.pivotX=0,this.pivotY=0,this.customPivot=!1,this.rotated=!1,this.autoRound=-1,this.customData={},this.u0=0,this.v0=0,this.u1=0,this.v1=0,this.data={cut:{x:0,y:0,w:0,h:0,r:0,b:0},trim:!1,sourceSize:{w:0,h:0},spriteSourceSize:{x:0,y:0,w:0,h:0,r:0,b:0},radius:0,drawImage:{x:0,y:0,width:0,height:0}},this.setSize(r,o,n,s)},setSize:function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this.cutX=i,this.cutY=n,this.cutWidth=t,this.cutHeight=e,this.width=t,this.height=e,this.halfWidth=Math.floor(.5*t),this.halfHeight=Math.floor(.5*e),this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2);var s=this.data,r=s.cut;r.x=i,r.y=n,r.w=t,r.h=e,r.r=i+t,r.b=n+e,s.sourceSize.w=t,s.sourceSize.h=e,s.spriteSourceSize.w=t,s.spriteSourceSize.h=e,s.radius=.5*Math.sqrt(t*t+e*e);var o=s.drawImage;return o.x=i,o.y=n,o.width=t,o.height=e,this.updateUVs()},setTrim:function(t,e,i,n,s,r){var o=this.data,a=o.spriteSourceSize;return o.trim=!0,o.sourceSize.w=t,o.sourceSize.h=e,a.x=i,a.y=n,a.w=s,a.h=r,a.r=i+s,a.b=n+r,this.x=i,this.y=n,this.width=s,this.height=r,this.halfWidth=.5*s,this.halfHeight=.5*r,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.updateUVs()},setCropUVs:function(t,e,i,n,r,o,a){var h=this.cutX,l=this.cutY,u=this.cutWidth,c=this.cutHeight,d=this.realWidth,f=this.realHeight,p=h+(e=s(e,0,d)),g=l+(i=s(i,0,f)),v=n=s(n,0,d-e),m=r=s(r,0,f-i),y=this.data;if(y.trim){var x=y.spriteSourceSize,T=e+(n=s(n,0,u-e)),w=i+(r=s(r,0,c-i));if(!(x.rT||x.y>w)){var E=Math.max(x.x,e),_=Math.max(x.y,i),A=Math.min(x.r,T)-E,b=Math.min(x.b,w)-_;v=A,m=b,p=o?h+(u-(E-x.x)-A):h+(E-x.x),g=a?l+(c-(_-x.y)-b):l+(_-x.y),e=E,i=_,n=A,r=b}else p=0,g=0,v=0,m=0}else o&&(p=h+(u-e-n)),a&&(g=l+(c-i-r));var S=this.source.width,C=this.source.height;return t.u0=Math.max(0,p/S),t.v0=Math.max(0,g/C),t.u1=Math.min(1,(p+v)/S),t.v1=Math.min(1,(g+m)/C),t.x=e,t.y=i,t.cx=p,t.cy=g,t.cw=v,t.ch=m,t.width=n,t.height=r,t.flipX=o,t.flipY=a,t},updateCropUVs:function(t,e,i){return this.setCropUVs(t,t.x,t.y,t.width,t.height,e,i)},updateUVs:function(){var t=this.cutX,e=this.cutY,i=this.cutWidth,n=this.cutHeight,s=this.data.drawImage;s.width=i,s.height=n;var r=this.source.width,o=this.source.height;return this.u0=t/r,this.v0=e/o,this.u1=(t+i)/r,this.v1=(e+n)/o,this},updateUVsInverted:function(){var t=this.source.width,e=this.source.height;return this.u0=(this.cutX+this.cutHeight)/t,this.v0=this.cutY/e,this.u1=this.cutX/t,this.v1=(this.cutY+this.cutWidth)/e,this},clone:function(){var t=new o(this.texture,this.name,this.sourceIndex);return t.cutX=this.cutX,t.cutY=this.cutY,t.cutWidth=this.cutWidth,t.cutHeight=this.cutHeight,t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t.halfWidth=this.halfWidth,t.halfHeight=this.halfHeight,t.centerX=this.centerX,t.centerY=this.centerY,t.rotated=this.rotated,t.data=r(!0,t.data,this.data),t.updateUVs(),t},destroy:function(){this.source=null,this.texture=null,this.glTexture=null,this.customData=null,this.data=null},realWidth:{get:function(){return this.data.sourceSize.w}},realHeight:{get:function(){return this.data.sourceSize.h}},radius:{get:function(){return this.data.radius}},trimmed:{get:function(){return this.data.trim}},canvasData:{get:function(){return this.data.drawImage}}});t.exports=o},function(t,e,i){var n=i(0),s=i(94),r=i(391),o=i(392),a=i(46),h=i(151),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=a.ELLIPSE,this.x=t,this.y=e,this.width=i,this.height=n},contains:function(t,e){return s(this,t,e)},getPoint:function(t,e){return r(this,t,e)},getPoints:function(t,e,i){return o(this,t,e,i)},getRandomPoint:function(t){return h(this,t)},setTo:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setEmpty:function(){return this.width=0,this.height=0,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},isEmpty:function(){return this.width<=0||this.height<=0},getMinorRadius:function(){return Math.min(this.width,this.height)/2},getMajorRadius:function(){return Math.max(this.width,this.height)/2},left:{get:function(){return this.x-this.width/2},set:function(t){this.x=t+this.width/2}},right:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},top:{get:function(){return this.y-this.height/2},set:function(t){this.y=t+this.height/2}},bottom:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=l},function(t,e){t.exports=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var n=(e-t.x)/t.width,s=(i-t.y)/t.height;return(n*=n)+(s*=s)<.25}},function(t,e,i){var n=i(236),s=i(0),r=i(88),o=i(2),a=i(6),h=i(7),l=i(385),u=i(127),c=i(73),d=new s({initialize:function(t,e,i){i?e&&!Array.isArray(e)&&(e=[e]):Array.isArray(e)?h(e[0])&&(i=e,e=null):h(e)&&(i=e,e=null),this.scene=t,this.children=new u(e),this.isParent=!0,this.type="Group",this.classType=o(i,"classType",c),this.name=o(i,"name",""),this.active=o(i,"active",!0),this.maxSize=o(i,"maxSize",-1),this.defaultKey=o(i,"defaultKey",null),this.defaultFrame=o(i,"defaultFrame",null),this.runChildUpdate=o(i,"runChildUpdate",!1),this.createCallback=o(i,"createCallback",null),this.removeCallback=o(i,"removeCallback",null),this.createMultipleCallback=o(i,"createMultipleCallback",null),this.internalCreateCallback=o(i,"internalCreateCallback",null),this.internalRemoveCallback=o(i,"internalRemoveCallback",null),i&&this.createMultiple(i)},create:function(t,e,i,n,s,r){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.defaultKey),void 0===n&&(n=this.defaultFrame),void 0===s&&(s=!0),void 0===r&&(r=!0),this.isFull())return null;var o=new this.classType(this.scene,t,e,i,n);return this.scene.sys.displayList.add(o),o.preUpdate&&this.scene.sys.updateList.add(o),o.visible=s,o.setActive(r),this.add(o),o},createMultiple:function(t){if(this.isFull())return[];Array.isArray(t)||(t=[t]);var e=[];if(t[0].key)for(var i=0;i=0;u--)if((l=d[u]).active===i){if(++c===e)break}else l=null;return l?("number"==typeof s&&(l.x=s),"number"==typeof r&&(l.y=r),l):n?this.create(s,r,o,a,h):null},get:function(t,e,i,n,s){return this.getFirst(!1,!0,t,e,i,n,s)},getFirstAlive:function(t,e,i,n,s,r){return this.getFirst(!0,t,e,i,n,s,r)},getFirstDead:function(t,e,i,n,s,r){return this.getFirst(!1,t,e,i,n,s,r)},playAnimation:function(t,e){return n.PlayAnimation(this.children.entries,t,e),this},isFull:function(){return-1!==this.maxSize&&this.children.size>=this.maxSize},countActive:function(t){void 0===t&&(t=!0);for(var e=0,i=0;i=0&&t=0&&e0;e--){var i=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[i],t[i]=n}return t}},function(t,e){t.exports=function(t,e,i){return(e-t)*i+t}},function(t,e,i){(function(e){var i={android:!1,chromeOS:!1,cordova:!1,crosswalk:!1,desktop:!1,ejecta:!1,electron:!1,iOS:!1,iOSVersion:0,iPad:!1,iPhone:!1,kindle:!1,linux:!1,macOS:!1,node:!1,nodeWebkit:!1,pixelRatio:1,webApp:!1,windows:!1,windowsPhone:!1};t.exports=function(){var t=navigator.userAgent;/Windows/.test(t)?i.windows=!0:/Mac OS/.test(t)&&!/like Mac OS/.test(t)?i.macOS=!0:/Android/.test(t)?i.android=!0:/Linux/.test(t)?i.linux=!0:/iP[ao]d|iPhone/i.test(t)?(i.iOS=!0,navigator.appVersion.match(/OS (\d+)/),i.iOSVersion=parseInt(RegExp.$1,10),i.iPhone=-1!==t.toLowerCase().indexOf("iphone"),i.iPad=-1!==t.toLowerCase().indexOf("ipad")):/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?i.kindle=!0:/CrOS/.test(t)&&(i.chromeOS=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(i.android=!1,i.iOS=!1,i.macOS=!1,i.windows=!0,i.windowsPhone=!0);var n=/Silk/.test(t);return(i.windows||i.macOS||i.linux&&!n||i.chromeOS)&&(i.desktop=!0),(i.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(i.desktop=!1),navigator.standalone&&(i.webApp=!0),void 0!==window.cordova&&(i.cordova=!0),void 0!==e&&e.versions&&e.versions.node&&(i.node=!0),i.node&&"object"==typeof e.versions&&(i.nodeWebkit=!!e.versions["node-webkit"],i.electron=!!e.versions.electron),void 0!==window.ejecta&&(i.ejecta=!0),/Crosswalk/.test(t)&&(i.crosswalk=!0),i.pixelRatio=window.devicePixelRatio||1,i}()}).call(this,i(721))},function(t,e,i){var n,s=i(112),r={chrome:!1,chromeVersion:0,edge:!1,firefox:!1,firefoxVersion:0,ie:!1,ieVersion:0,mobileSafari:!1,opera:!1,safari:!1,safariVersion:0,silk:!1,trident:!1,tridentVersion:0};t.exports=(n=navigator.userAgent,/Edge\/\d+/.test(n)?r.edge=!0:/Chrome\/(\d+)/.test(n)&&!s.windowsPhone?(r.chrome=!0,r.chromeVersion=parseInt(RegExp.$1,10)):/Firefox\D+(\d+)/.test(n)?(r.firefox=!0,r.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(n)&&s.iOS?r.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(n)?(r.ie=!0,r.ieVersion=parseInt(RegExp.$1,10)):/Opera/.test(n)?r.opera=!0:/Safari/.test(n)&&!s.windowsPhone?r.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(n)&&(r.ie=!0,r.trident=!0,r.tridentVersion=parseInt(RegExp.$1,10),r.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(n)&&(r.silk=!0),r)},function(t,e){t.exports=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)}},function(t,e,i){t.exports={ADD:i(771),ERROR:i(772),LOAD:i(773),READY:i(774),REMOVE:i(775)}},function(t,e){t.exports=function(t,e){var i;if(e)"string"==typeof e?i=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(i=e);else if(t.parentElement)return t;return i||(i=document.body),i.appendChild(t),t}},function(t,e,i){var n=i(78);t.exports=function(t,e,i,s){var r;if(void 0===s&&(s=t),!Array.isArray(e))return-1!==(r=t.indexOf(e))?(n(t,r),i&&i.call(s,e),e):null;for(var o=e.length-1;o>=0;){var a=e[o];-1!==(r=t.indexOf(a))?(n(t,r),i&&i.call(s,a)):e.pop(),o--}return e}},function(t,e){t.exports={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:42,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,NUMPAD_ZERO:96,NUMPAD_ONE:97,NUMPAD_TWO:98,NUMPAD_THREE:99,NUMPAD_FOUR:100,NUMPAD_FIVE:101,NUMPAD_SIX:102,NUMPAD_SEVEN:103,NUMPAD_EIGHT:104,NUMPAD_NINE:105,NUMPAD_ADD:107,NUMPAD_SUBTRACT:109,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,SEMICOLON:186,PLUS:187,COMMA:188,MINUS:189,PERIOD:190,FORWARD_SLASH:191,BACK_SLASH:220,QUOTES:222,BACKTICK:192,OPEN_BRACKET:219,CLOSED_BRACKET:221,SEMICOLON_FIREFOX:59,COLON:58,COMMA_FIREFOX_WINDOWS:60,COMMA_FIREFOX:62,BRACKET_RIGHT_FIREFOX:174,BRACKET_LEFT_FIREFOX:175}},function(t,e){t.exports={PENDING:0,INIT:1,START:2,LOADING:3,CREATING:4,RUNNING:5,PAUSED:6,SLEEPING:7,SHUTDOWN:8,DESTROYED:9}},function(t,e,i){var n=i(65);t.exports=function(t,e){var i=n(t);for(var s in e)i.hasOwnProperty(s)||(i[s]=e[s]);return i}},function(t,e,i){var n=i(0),s=i(65),r=i(11),o=i(59),a=i(19),h=i(1),l=new n({Extends:r,initialize:function(t){r.call(this),this.game=t,this.jsonCache=t.cache.json,this.sounds=[],this.mute=!1,this.volume=1,this.pauseOnBlur=!0,this._rate=1,this._detune=0,this.locked=this.locked||!1,this.unlocked=!1,t.events.on(a.BLUR,function(){this.pauseOnBlur&&this.onBlur()},this),t.events.on(a.FOCUS,function(){this.pauseOnBlur&&this.onFocus()},this),t.events.on(a.PRE_STEP,this.update,this),t.events.once(a.DESTROY,this.destroy,this)},add:h,addAudioSprite:function(t,e){void 0===e&&(e={});var i=this.add(t,e);for(var n in i.spritemap=this.jsonCache.get(t).spritemap,i.spritemap)if(i.spritemap.hasOwnProperty(n)){var r=s(e),o=i.spritemap[n];r.loop=!!o.hasOwnProperty("loop")&&o.loop,i.addMarker({name:n,start:o.start,duration:o.end-o.start,config:r})}return i},play:function(t,e){var i=this.add(t);return i.once(o.COMPLETE,i.destroy,i),e?e.name?(i.addMarker(e),i.play(e.name)):i.play(e):i.play()},playAudioSprite:function(t,e,i){var n=this.addAudioSprite(t);return n.once(o.COMPLETE,n.destroy,n),n.play(e,i)},remove:function(t){var e=this.sounds.indexOf(t);return-1!==e&&(t.destroy(),this.sounds.splice(e,1),!0)},removeByKey:function(t){for(var e=0,i=this.sounds.length-1;i>=0;i--){var n=this.sounds[i];n.key===t&&(n.destroy(),this.sounds.splice(i,1),e++)}return e},pauseAll:function(){this.forEachActiveSound(function(t){t.pause()}),this.emit(o.PAUSE_ALL,this)},resumeAll:function(){this.forEachActiveSound(function(t){t.resume()}),this.emit(o.RESUME_ALL,this)},stopAll:function(){this.forEachActiveSound(function(t){t.stop()}),this.emit(o.STOP_ALL,this)},unlock:h,onBlur:h,onFocus:h,update:function(t,e){this.unlocked&&(this.unlocked=!1,this.locked=!1,this.emit(o.UNLOCKED,this));for(var i=this.sounds.length-1;i>=0;i--)this.sounds[i].pendingRemove&&this.sounds.splice(i,1);this.sounds.forEach(function(i){i.update(t,e)})},destroy:function(){this.removeAllListeners(),this.forEachActiveSound(function(t){t.destroy()}),this.sounds.length=0,this.sounds=null,this.game=null},forEachActiveSound:function(t,e){var i=this;this.sounds.forEach(function(n,s){n&&!n.pendingRemove&&t.call(e||i,n,s,i.sounds)})},setRate:function(t){return this.rate=t,this},rate:{get:function(){return this._rate},set:function(t){this._rate=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_RATE,this,t)}},setDetune:function(t){return this.detune=t,this},detune:{get:function(){return this._detune},set:function(t){this._detune=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_DETUNE,this,t)}}});t.exports=l},function(t,e,i){var n=i(0),s=i(11),r=i(59),o=i(18),a=i(1),h=new n({Extends:s,initialize:function(t,e,i){s.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=this.duration||0,this.totalDuration=this.totalDuration||0,this.config={mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},this.currentConfig=this.config,this.config=o(this.config,i),this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(console.error("addMarker "+t.name+" already exists in Sound"),!1):(t=o(!0,{name:"",start:0,duration:this.totalDuration-(t.start||0),config:{mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0}},t),this.markers[t.name]=t,!0))},updateMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(this.markers[t.name]=o(!0,this.markers[t.name],t),!0):(console.warn("Audio Marker: "+t.name+" missing in Sound: "+this.key),!1))},removeMarker:function(t){var e=this.markers[t];return e?(this.markers[t]=null,e):null},play:function(t,e){if(void 0===t&&(t=""),"object"==typeof t&&(e=t,t=""),"string"!=typeof t)return!1;if(t){if(!this.markers[t])return console.warn("Marker: "+t+" missing in Sound: "+this.key),!1;this.currentMarker=this.markers[t],this.currentConfig=this.currentMarker.config,this.duration=this.currentMarker.duration}else this.currentMarker=null,this.currentConfig=this.config,this.duration=this.totalDuration;return this.resetConfig(),this.currentConfig=o(this.currentConfig,e),this.isPlaying=!0,this.isPaused=!1,!0},pause:function(){return!(this.isPaused||!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!0,!0)},resume:function(){return!(!this.isPaused||this.isPlaying)&&(this.isPlaying=!0,this.isPaused=!1,!0)},stop:function(){return!(!this.isPaused&&!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!1,this.resetConfig(),!0)},applyConfig:function(){this.mute=this.currentConfig.mute,this.volume=this.currentConfig.volume,this.rate=this.currentConfig.rate,this.detune=this.currentConfig.detune,this.loop=this.currentConfig.loop},resetConfig:function(){this.currentConfig.seek=0,this.currentConfig.delay=0},update:a,calculateRate:function(){var t=this.currentConfig.detune+this.manager.detune,e=Math.pow(1.0005777895065548,t);this.totalRate=this.currentConfig.rate*this.manager.rate*e},destroy:function(){this.pendingRemove||(this.emit(r.DESTROY,this),this.pendingRemove=!0,this.manager=null,this.key="",this.removeAllListeners(),this.isPlaying=!1,this.isPaused=!1,this.config=null,this.currentConfig=null,this.markers=null,this.currentMarker=null)}});t.exports=h},function(t,e,i){var n=i(178),s=i(0),r=i(1),o=i(125),a=new s({initialize:function(t){this.parent=t,this.list=[],this.position=0,this.addCallback=r,this.removeCallback=r,this._sortKey=""},add:function(t,e){return e?n.Add(this.list,t):n.Add(this.list,t,0,this.addCallback,this)},addAt:function(t,e,i){return i?n.AddAt(this.list,t,e):n.AddAt(this.list,t,e,0,this.addCallback,this)},getAt:function(t){return this.list[t]},getIndex:function(t){return this.list.indexOf(t)},sort:function(t,e){return t?(void 0===e&&(e=function(e,i){return e[t]-i[t]}),o.inplace(this.list,e),this):this},getByName:function(t){return n.GetFirst(this.list,"name",t)},getRandom:function(t,e){return n.GetRandom(this.list,t,e)},getFirst:function(t,e,i,s){return n.GetFirst(this.list,t,e,i,s)},getAll:function(t,e,i,s){return n.GetAll(this.list,t,e,i,s)},count:function(t,e){return n.CountAllMatching(this.list,t,e)},swap:function(t,e){n.Swap(this.list,t,e)},moveTo:function(t,e){return n.MoveTo(this.list,t,e)},remove:function(t,e){return e?n.Remove(this.list,t):n.Remove(this.list,t,this.removeCallback,this)},removeAt:function(t,e){return e?n.RemoveAt(this.list,t):n.RemoveAt(this.list,t,this.removeCallback,this)},removeBetween:function(t,e,i){return i?n.RemoveBetween(this.list,t,e):n.RemoveBetween(this.list,t,e,this.removeCallback,this)},removeAll:function(t){for(var e=this.list.length;e--;)this.remove(this.list[e],t);return this},bringToTop:function(t){return n.BringToTop(this.list,t)},sendToBack:function(t){return n.SendToBack(this.list,t)},moveUp:function(t){return n.MoveUp(this.list,t),t},moveDown:function(t){return n.MoveDown(this.list,t),t},reverse:function(){return this.list.reverse(),this},shuffle:function(){return n.Shuffle(this.list),this},replace:function(t,e){return n.Replace(this.list,t,e)},exists:function(t){return this.list.indexOf(t)>-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){for(var i=[null],n=2;n0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}}});t.exports=a},function(t,e,i){var n=i(179),s=i(383);t.exports=function(t,e){if(void 0===e&&(e=90),!n(t))return null;if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)(t=s(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t.reverse(),t=s(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;il&&(r=l),o>l&&(o=l),a=s,h=r;;)if(a-1&&this.entries.splice(e,1),this},dump:function(){console.group("Set");for(var t=0;t-1},union:function(t){var e=new n;return t.entries.forEach(function(t){e.set(t)}),this.entries.forEach(function(t){e.set(t)}),e},intersect:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)&&e.set(i)}),e},difference:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)||e.set(i)}),e},size:{get:function(){return this.entries.length},set:function(t){return t0&&o.length0&&a.lengthe.right||t.y>e.bottom)}},function(t,e,i){var n=i(6),s={},r={register:function(t,e,i,n,r){s[t]={plugin:e,mapping:i,settingsKey:n,configKey:r}},getPlugin:function(t){return s[t]},install:function(t){var e=t.scene.sys,i=e.settings.input,r=e.game.config;for(var o in s){var a=s[o].plugin,h=s[o].mapping,l=s[o].settingsKey,u=s[o].configKey;n(i,l,r[u])&&(t[h]=new a(t))}},remove:function(t){s.hasOwnProperty(t)&&delete s[t]}};t.exports=r},function(t,e,i){t.exports={ANY_KEY_DOWN:i(1207),ANY_KEY_UP:i(1208),COMBO_MATCH:i(1209),DOWN:i(1210),KEY_DOWN:i(1211),KEY_UP:i(1212),UP:i(1213)}},function(t,e){t.exports=function(t,e){return!!t.url&&(t.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t.url:e+t.url)}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===t&&(t=""),void 0===e&&(e=!0),void 0===i&&(i=""),void 0===n&&(n=""),void 0===s&&(s=0),void 0===r&&(r=!1),{responseType:t,async:e,user:i,password:n,timeout:s,header:void 0,headerValue:void 0,requestedWith:!1,overrideMimeType:void 0,withCredentials:r}}},function(t,e,i){var n=i(0),s=i(212),r=i(73),o=new n({Extends:r,Mixins:[s.Acceleration,s.Angular,s.Bounce,s.Debug,s.Drag,s.Enable,s.Friction,s.Gravity,s.Immovable,s.Mass,s.Size,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t,e,i,n,s),this.body=null}});t.exports=o},function(t,e,i){t.exports={CalculateFacesAt:i(215),CalculateFacesWithin:i(51),Copy:i(1303),CreateFromTiles:i(1304),CullTiles:i(1305),Fill:i(1307),FilterTiles:i(1308),FindByIndex:i(1309),FindTile:i(1310),ForEachTile:i(1311),GetTileAt:i(136),GetTileAtWorldXY:i(1312),GetTilesWithin:i(25),GetTilesWithinShape:i(1313),GetTilesWithinWorldXY:i(1314),HasTileAt:i(469),HasTileAtWorldXY:i(1315),IsInLayerBounds:i(99),PutTileAt:i(216),PutTileAtWorldXY:i(1316),PutTilesAt:i(1317),Randomize:i(1318),RemoveTileAt:i(470),RemoveTileAtWorldXY:i(1319),RenderDebug:i(1320),ReplaceByIndex:i(468),SetCollision:i(1321),SetCollisionBetween:i(1322),SetCollisionByExclusion:i(1323),SetCollisionByProperty:i(1324),SetCollisionFromCollisionGroup:i(1325),SetTileIndexCallback:i(1326),SetTileLocationCallback:i(1327),Shuffle:i(1328),SwapByIndex:i(1329),TileToWorldX:i(1330),TileToWorldXY:i(1331),TileToWorldY:i(1332),WeightedRandomize:i(1333),WorldToTileX:i(471),WorldToTileXY:i(1334),WorldToTileY:i(472)}},function(t,e,i){var n=i(99);t.exports=function(t,e,i,s){if(void 0===i&&(i=!1),n(t,e,s)){var r=s.data[e][t]||null;return null===r?null:-1===r.index?i?r:null:r}return null}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o,a){(void 0===i||i<=0)&&(i=32),(void 0===n||n<=0)&&(n=32),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o={}),void 0===a&&(a={}),this.name=t,this.firstgid=e,this.tileWidth=i,this.tileHeight=n,this.tileMargin=s,this.tileSpacing=r,this.tileProperties=o,this.tileData=a,this.image=null,this.glTexture=null,this.rows=0,this.columns=0,this.total=0,this.texCoordinates=[]},getTileProperties:function(t){return this.containsTileIndex(t)?this.tileProperties[t-this.firstgid]:null},getTileData:function(t){return this.containsTileIndex(t)?this.tileData[t-this.firstgid]:null},getTileCollisionGroup:function(t){var e=this.getTileData(t);return e&&e.objectgroup?e.objectgroup:null},containsTileIndex:function(t){return t>=this.firstgid&&t=this.vertexCapacity},resize:function(t,e,i){return this.width=t*i,this.height=e*i,this.resolution=i,this},bind:function(){var t=this.gl,e=this.vertexBuffer,i=this.attributes,n=this.program,s=this.renderer,r=this.vertexSize;s.setProgram(n),s.setVertexBuffer(e);for(var o=0;o=0?(t.enableVertexAttribArray(h),t.vertexAttribPointer(h,a.size,a.type,a.normalized,r,a.offset)):-1!==h&&t.disableVertexAttribArray(h)}return this},onBind:function(){return this},onPreRender:function(){return this},onRender:function(){return this},onPostRender:function(){return this},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t=this.gl,e=this.vertexCount,i=this.topology,n=this.vertexSize;if(0!==e)return t.bufferSubData(t.ARRAY_BUFFER,0,this.bytes.subarray(0,e*n)),t.drawArrays(i,0,e),this.vertexCount=0,this.flushLocked=!1,this;this.flushLocked=!1},destroy:function(){var t=this.gl;return t.deleteProgram(this.program),t.deleteBuffer(this.vertexBuffer),delete this.program,delete this.vertexBuffer,delete this.gl,this},setFloat1:function(t,e){return this.renderer.setFloat1(this.program,t,e),this},setFloat2:function(t,e,i){return this.renderer.setFloat2(this.program,t,e,i),this},setFloat3:function(t,e,i,n){return this.renderer.setFloat3(this.program,t,e,i,n),this},setFloat4:function(t,e,i,n,s){return this.renderer.setFloat4(this.program,t,e,i,n,s),this},setFloat1v:function(t,e){return this.renderer.setFloat1v(this.program,t,e),this},setFloat2v:function(t,e){return this.renderer.setFloat2v(this.program,t,e),this},setFloat3v:function(t,e){return this.renderer.setFloat3v(this.program,t,e),this},setFloat4v:function(t,e){return this.renderer.setFloat4v(this.program,t,e),this},setInt1:function(t,e){return this.renderer.setInt1(this.program,t,e),this},setInt2:function(t,e,i){return this.renderer.setInt2(this.program,t,e,i),this},setInt3:function(t,e,i,n){return this.renderer.setInt3(this.program,t,e,i,n),this},setInt4:function(t,e,i,n,s){return this.renderer.setInt4(this.program,t,e,i,n,s),this},setMatrix2:function(t,e,i){return this.renderer.setMatrix2(this.program,t,e,i),this},setMatrix3:function(t,e,i){return this.renderer.setMatrix3(this.program,t,e,i),this},setMatrix4:function(t,e,i){return this.renderer.setMatrix4(this.program,t,e,i),this}});t.exports=r},,function(t,e,i){var n=i(4);t.exports=function(t,e,i){return void 0===i&&(i=new n),i.x=t.x+t.radius*Math.cos(e),i.y=t.y+t.radius*Math.sin(e),i}},function(t,e,i){var n=i(4);t.exports=function(t,e){void 0===e&&(e=new n);var i=2*Math.PI*Math.random(),s=Math.random()+Math.random(),r=s>1?2-s:s,o=r*Math.cos(i),a=r*Math.sin(i);return e.x=t.x+o*t.radius,e.y=t.y+a*t.radius,e}},function(t,e,i){var n=i(23),s=i(0),r=i(11),o=i(107),a=i(265),h=i(266),l=i(6),u=new s({Extends:r,initialize:function(t,e,i){r.call(this),this.manager=t,this.key=e,this.type="frame",this.frames=this.getFrames(t.textureManager,l(i,"frames",[]),l(i,"defaultTextureKey",null)),this.frameRate=l(i,"frameRate",null),this.duration=l(i,"duration",null),null===this.duration&&null===this.frameRate?(this.frameRate=24,this.duration=this.frameRate/this.frames.length*1e3):this.duration&&null===this.frameRate?this.frameRate=this.frames.length/(this.duration/1e3):this.duration=this.frames.length/this.frameRate*1e3,this.msPerFrame=1e3/this.frameRate,this.skipMissedFrames=l(i,"skipMissedFrames",!0),this.delay=l(i,"delay",0),this.repeat=l(i,"repeat",0),this.repeatDelay=l(i,"repeatDelay",0),this.yoyo=l(i,"yoyo",!1),this.showOnStart=l(i,"showOnStart",!1),this.hideOnComplete=l(i,"hideOnComplete",!1),this.paused=!1,this.manager.on(o.PAUSE_ALL,this.pause,this),this.manager.on(o.RESUME_ALL,this.resume,this)},addFrame:function(t){return this.addFrameAt(this.frames.length,t)},addFrameAt:function(t,e){var i=this.getFrames(this.manager.textureManager,e);if(i.length>0){if(0===t)this.frames=i.concat(this.frames);else if(t===this.frames.length)this.frames=this.frames.concat(i);else{var n=this.frames.slice(0,t),s=this.frames.slice(t);this.frames=n.concat(i,s)}this.updateFrameSequence()}return this},checkFrame:function(t){return t>=0&&t0){s.isLast=!0,s.nextFrame=a[0],a[0].prevFrame=s;var v=1/(a.length-1);for(r=0;r=this.frames.length&&(e=0),t.currentAnim!==this&&(t.currentAnim=this,t.frameRate=this.frameRate,t.duration=this.duration,t.msPerFrame=this.msPerFrame,t.skipMissedFrames=this.skipMissedFrames,t._delay=this.delay,t._repeat=this.repeat,t._repeatDelay=this.repeatDelay,t._yoyo=this.yoyo);var i=this.frames[e];0!==e||t.forward||(i=this.getLastFrame()),t.updateFrame(i)},getFrameByProgress:function(t){return t=n(t,0,1),a(t,this.frames,"progress")},nextFrame:function(t){var e=t.currentFrame;e.isLast?t._yoyo?this.handleYoyoFrame(t,!1):t.repeatCounter>0?t._reverse&&t.forward?t.forward=!1:this.repeatAnimation(t):this.completeAnimation(t):this.updateAndGetNextTick(t,e.nextFrame)},handleYoyoFrame:function(t,e){if(e||(e=!1),t._reverse===!e&&t.repeatCounter>0)return t.forward=e,void this.repeatAnimation(t);if(t._reverse===e||0!==t.repeatCounter){t.forward=e;var i=e?t.currentFrame.nextFrame:t.currentFrame.prevFrame;this.updateAndGetNextTick(t,i)}else this.completeAnimation(t)},getLastFrame:function(){return this.frames[this.frames.length-1]},previousFrame:function(t){var e=t.currentFrame;e.isFirst?t._yoyo?this.handleYoyoFrame(t,!0):t.repeatCounter>0?t._reverse&&!t.forward?(t.currentFrame=this.getLastFrame(),this.repeatAnimation(t)):(t.forward=!0,this.repeatAnimation(t)):this.completeAnimation(t):this.updateAndGetNextTick(t,e.prevFrame)},updateAndGetNextTick:function(t,e){t.updateFrame(e),this.getNextTick(t)},removeFrame:function(t){var e=this.frames.indexOf(t);return-1!==e&&this.removeFrameAt(e),this},removeFrameAt:function(t){return this.frames.splice(t,1),this.updateFrameSequence(),this},repeatAnimation:function(t){if(2===t._pendingStop)return this.completeAnimation(t);if(t._repeatDelay>0&&!1===t.pendingRepeat)t.pendingRepeat=!0,t.accumulator-=t.nextTick,t.nextTick+=t._repeatDelay;else if(t.repeatCounter--,t.updateFrame(t.currentFrame[t.forward?"nextFrame":"prevFrame"]),t.isPlaying){this.getNextTick(t),t.pendingRepeat=!1;var e=t.currentFrame,i=t.parent;this.emit(o.ANIMATION_REPEAT,this,e),i.emit(o.SPRITE_ANIMATION_KEY_REPEAT+this.key,this,e,t.repeatCounter,i),i.emit(o.SPRITE_ANIMATION_REPEAT,this,e,t.repeatCounter,i)}},setFrame:function(t){t.forward?this.nextFrame(t):this.previousFrame(t)},toJSON:function(){var t={key:this.key,type:this.type,frames:[],frameRate:this.frameRate,duration:this.duration,skipMissedFrames:this.skipMissedFrames,delay:this.delay,repeat:this.repeat,repeatDelay:this.repeatDelay,yoyo:this.yoyo,showOnStart:this.showOnStart,hideOnComplete:this.hideOnComplete};return this.frames.forEach(function(e){t.frames.push(e.toJSON())}),t},updateFrameSequence:function(){for(var t,e=this.frames.length,i=1/(e-1),n=0;n1?(t.isLast=!0,t.prevFrame=this.frames[e-2],t.nextFrame=this.frames[0]):e>1&&(t.prevFrame=this.frames[n-1],t.nextFrame=this.frames[n+1]);return this},pause:function(){return this.paused=!0,this},resume:function(){return this.paused=!1,this},destroy:function(){this.removeAllListeners(),this.manager.off(o.PAUSE_ALL,this.pause,this),this.manager.off(o.RESUME_ALL,this.resume,this),this.manager.remove(this.key);for(var t=0;t=1)return i.x=t.x,i.y=t.y,i;var r=n(t)*e;return e>.5?(r-=t.width+t.height)<=t.width?(i.x=t.right-r,i.y=t.bottom):(i.x=t.x,i.y=t.bottom-(r-t.width)):r<=t.width?(i.x=t.x+r,i.y=t.y):(i.x=t.right,i.y=t.y+(r-t.width)),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=n(t)/i);for(var o=t.x1,a=t.y1,h=t.x2,l=t.y2,u=0;u=1&&(a=1-a,h=1-h),e.x=t.x1+(i*a+r*h),e.y=t.y1+(s*a+o*h),e}},function(t,e){t.exports=function(t,e,i,n,s){var r=n+Math.atan2(t.y-i,t.x-e);return t.x=e+s*Math.cos(r),t.y=i+s*Math.sin(r),t}},function(t,e){t.exports=function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)}},function(t,e){t.exports=function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){if(this.entries={},this.size=0,Array.isArray(t))for(var e=0;e=(t=t.toString()).length)switch(n){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((s=e-t.length)/2);t=new Array(s-r+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t}},function(t,e,i){var n=i(289),s=i(292),r=i(294),o=i(295);t.exports=function(t){switch(typeof t){case"string":return"rgb"===t.substr(0,3).toLowerCase()?o(t):n(t);case"number":return s(t);case"object":return r(t)}}},function(t,e){t.exports=function(t,e,i){return t<<16|e<<8|i}},function(t,e,i){var n=i(159);t.exports=function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1);var r=Math.floor(6*t),o=6*t-r,a=Math.floor(i*(1-e)*255),h=Math.floor(i*(1-o*e)*255),l=Math.floor(i*(1-(1-o)*e)*255),u=i=Math.floor(i*=255),c=i,d=i,f=r%6;return 0===f?(c=l,d=a):1===f?(u=h,d=a):2===f?(u=a,d=l):3===f?(u=a,c=h):4===f?(u=l,c=a):5===f&&(c=a,d=h),s?s.setTo?s.setTo(u,c,d,s.alpha,!1):(s.r=u,s.g=c,s.b=d,s.color=n(u,c,d),s):{r:u,g:c,b:d,color:n(u,c,d)}}},function(t,e){var i,n="";t.exports={disable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!1),t},enable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!0),t},getPrefix:i=function(t){for(var e=["i","webkitI","msI","mozI","oI"],i=0;i0&&(n=1/Math.sqrt(n),this.x=t*n,this.y=e*n,this.z=i*n),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},cross:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z;return this.x=i*o-n*r,this.y=n*s-e*o,this.z=e*r-i*s,this},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this},transformMat3:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=e*s[0]+i*s[3]+n*s[6],this.y=e*s[1]+i*s[4]+n*s[7],this.z=e*s[2]+i*s[5]+n*s[8],this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=s[0]*e+s[4]*i+s[8]*n+s[12],this.y=s[1]*e+s[5]*i+s[9]*n+s[13],this.z=s[2]*e+s[6]*i+s[10]*n+s[14],this},transformCoordinates:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=e*s[0]+i*s[4]+n*s[8]+s[12],o=e*s[1]+i*s[5]+n*s[9]+s[13],a=e*s[2]+i*s[6]+n*s[10]+s[14],h=e*s[3]+i*s[7]+n*s[11]+s[15];return this.x=r/h,this.y=o/h,this.z=a/h,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},project:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=s[0],o=s[1],a=s[2],h=s[3],l=s[4],u=s[5],c=s[6],d=s[7],f=s[8],p=s[9],g=s[10],v=s[11],m=s[12],y=s[13],x=s[14],T=1/(e*h+i*d+n*v+s[15]);return this.x=(e*r+i*l+n*f+m)*T,this.y=(e*o+i*u+n*p+y)*T,this.z=(e*a+i*c+n*g+x)*T,this},unproject:function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,o=this.x-i,a=r-this.y-1-n,h=this.z;return this.x=2*o/s-1,this.y=2*a/r-1,this.z=2*h-1,this.project(e)},reset:function(){return this.x=0,this.y=0,this.z=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0,0),n.LEFT=new n(-1,0,0),n.UP=new n(0,-1,0),n.DOWN=new n(0,1,0),n.FORWARD=new n(0,0,1),n.BACK=new n(0,0,-1),n.ONE=new n(1,1,1),t.exports=n},function(t,e,i){t.exports={Global:["game","anims","cache","plugins","registry","scale","sound","textures"],CoreScene:["EventEmitter","CameraManager","GameObjectCreator","GameObjectFactory","ScenePlugin","DisplayList","UpdateList"],DefaultScene:["Clock","DataManagerPlugin","InputPlugin","Loader","TweenManager","LightsPlugin"]}},function(t,e,i){var n=i(13),s=i(16);t.exports=function(t,e){if(void 0===e&&(e=new n),0===t.length)return e;for(var i,r,o,a=Number.MAX_VALUE,h=Number.MAX_VALUE,l=s.MIN_SAFE_INTEGER,u=s.MIN_SAFE_INTEGER,c=0;c0},isTransitionIn:function(){return this.settings.isTransition},isVisible:function(){return this.settings.visible},setVisible:function(t){return this.settings.visible=t,this},setActive:function(t,e){return t?this.resume(e):this.pause(e)},start:function(t){t&&(this.settings.data=t),this.settings.status=s.START,this.settings.active=!0,this.settings.visible=!0,this.events.emit(o.START,this),this.events.emit(o.READY,this,t)},shutdown:function(t){this.events.off(o.TRANSITION_INIT),this.events.off(o.TRANSITION_START),this.events.off(o.TRANSITION_COMPLETE),this.events.off(o.TRANSITION_OUT),this.settings.status=s.SHUTDOWN,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.SHUTDOWN,this,t)},destroy:function(){this.settings.status=s.DESTROYED,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.DESTROY,this),this.events.removeAllListeners();for(var t=["scene","game","anims","cache","plugins","registry","sound","textures","add","camera","displayList","events","make","scenePlugin","updateList"],e=0;e0},getRenderList:function(){return this.dirty&&(this.renderList=this.children.list.filter(this.childCanRender,this),this.dirty=!1),this.renderList},clear:function(){this.children.removeAll(),this.dirty=!0},preDestroy:function(){this.children.destroy(),this.renderList=[]}});t.exports=u},function(t,e,i){var n=i(178),s=i(52),r=i(0),o=i(12),a=i(88),h=i(14),l=i(13),u=i(945),c=i(387),d=i(3),f=new r({Extends:h,Mixins:[o.AlphaSingle,o.BlendMode,o.ComputedSize,o.Depth,o.Mask,o.Transform,o.Visible,u],initialize:function(t,e,i,n){h.call(this,t,"Container"),this.list=[],this.exclusive=!0,this.maxSize=-1,this.position=0,this.localTransform=new o.TransformMatrix,this.tempTransformMatrix=new o.TransformMatrix,this._displayList=t.sys.displayList,this._sortKey="",this._sysEvents=t.sys.events,this.scrollFactorX=1,this.scrollFactorY=1,this.setPosition(e,i),this.clearAlpha(),this.setBlendMode(s.SKIP_CHECK),n&&this.add(n)},originX:{get:function(){return.5}},originY:{get:function(){return.5}},displayOriginX:{get:function(){return.5*this.width}},displayOriginY:{get:function(){return.5*this.height}},setExclusive:function(t){return void 0===t&&(t=!0),this.exclusive=t,this},getBounds:function(t){if(void 0===t&&(t=new l),t.setTo(this.x,this.y,0,0),this.list.length>0)for(var e=this.list,i=new l,n=0;n-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){var i,n=[null],s=this.list.slice(),r=s.length;for(i=2;i0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}},preDestroy:function(){this.removeAll(!!this.exclusive),this.localTransform.destroy(),this.tempTransformMatrix.destroy(),this.list=[],this._displayList=null}});t.exports=f},function(t,e,i){var n=i(126),s=i(0),r=i(950),o=new s({Extends:n,Mixins:[r],initialize:function(t,e,i,s,r,o,a){n.call(this,t,e,i,s,r,o,a),this.type="DynamicBitmapText",this.scrollX=0,this.scrollY=0,this.cropWidth=0,this.cropHeight=0,this.displayCallback,this.callbackData={parent:this,color:0,tint:{topLeft:0,topRight:0,bottomLeft:0,bottomRight:0},index:0,charCode:0,x:0,y:0,scale:0,rotation:0,data:0}},setSize:function(t,e){return this.cropWidth=t,this.cropHeight=e,this},setDisplayCallback:function(t){return this.displayCallback=t,this},setScrollX:function(t){return this.scrollX=t,this},setScrollY:function(t){return this.scrollY=t,this}});t.exports=o},function(t,e,i){var n=i(89),s=i(0),r=i(187),o=i(264),a=i(267),h=i(268),l=i(272),u=i(150),c=i(277),d=i(278),f=i(275),p=i(30),g=i(93),v=i(14),m=i(2),y=i(6),x=i(16),T=i(956),w=new s({Extends:v,Mixins:[o,a,h,l,u,c,d,f,T],initialize:function(t,e){var i=y(e,"x",0),n=y(e,"y",0);v.call(this,t,"Graphics"),this.setPosition(i,n),this.initPipeline(),this.displayOriginX=0,this.displayOriginY=0,this.commandBuffer=[],this.defaultFillColor=-1,this.defaultFillAlpha=1,this.defaultStrokeWidth=1,this.defaultStrokeColor=-1,this.defaultStrokeAlpha=1,this._lineWidth=1,this._tempMatrix1=new p,this._tempMatrix2=new p,this._tempMatrix3=new p,this.setDefaultStyles(e)},setDefaultStyles:function(t){return y(t,"lineStyle",null)&&(this.defaultStrokeWidth=y(t,"lineStyle.width",1),this.defaultStrokeColor=y(t,"lineStyle.color",16777215),this.defaultStrokeAlpha=y(t,"lineStyle.alpha",1),this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha)),y(t,"fillStyle",null)&&(this.defaultFillColor=y(t,"fillStyle.color",16777215),this.defaultFillAlpha=y(t,"fillStyle.alpha",1),this.fillStyle(this.defaultFillColor,this.defaultFillAlpha)),this},lineStyle:function(t,e,i){return void 0===i&&(i=1),this.commandBuffer.push(r.LINE_STYLE,t,e,i),this._lineWidth=t,this},fillStyle:function(t,e){return void 0===e&&(e=1),this.commandBuffer.push(r.FILL_STYLE,t,e),this},fillGradientStyle:function(t,e,i,n,s){return void 0===s&&(s=1),this.commandBuffer.push(r.GRADIENT_FILL_STYLE,s,t,e,i,n),this},lineGradientStyle:function(t,e,i,n,s,o){return void 0===o&&(o=1),this.commandBuffer.push(r.GRADIENT_LINE_STYLE,t,o,e,i,n,s),this},setTexture:function(t,e,i){if(void 0===i&&(i=0),void 0===t)this.commandBuffer.push(r.CLEAR_TEXTURE);else{var n=this.scene.sys.textures.getFrame(t,e);n&&(2===i&&(i=3),this.commandBuffer.push(r.SET_TEXTURE,n,i))}return this},beginPath:function(){return this.commandBuffer.push(r.BEGIN_PATH),this},closePath:function(){return this.commandBuffer.push(r.CLOSE_PATH),this},fillPath:function(){return this.commandBuffer.push(r.FILL_PATH),this},fill:function(){return this.commandBuffer.push(r.FILL_PATH),this},strokePath:function(){return this.commandBuffer.push(r.STROKE_PATH),this},stroke:function(){return this.commandBuffer.push(r.STROKE_PATH),this},fillCircleShape:function(t){return this.fillCircle(t.x,t.y,t.radius)},strokeCircleShape:function(t){return this.strokeCircle(t.x,t.y,t.radius)},fillCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.fillPath(),this},strokeCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.strokePath(),this},fillRectShape:function(t){return this.fillRect(t.x,t.y,t.width,t.height)},strokeRectShape:function(t){return this.strokeRect(t.x,t.y,t.width,t.height)},fillRect:function(t,e,i,n){return this.commandBuffer.push(r.FILL_RECT,t,e,i,n),this},strokeRect:function(t,e,i,n){var s=this._lineWidth/2,r=t-s,o=t+s;return this.beginPath(),this.moveTo(t,e),this.lineTo(t,e+n),this.strokePath(),this.beginPath(),this.moveTo(t+i,e),this.lineTo(t+i,e+n),this.strokePath(),this.beginPath(),this.moveTo(r,e),this.lineTo(o+i,e),this.strokePath(),this.beginPath(),this.moveTo(r,e+n),this.lineTo(o+i,e+n),this.strokePath(),this},fillRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.fillPath(),this},strokeRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.strokePath(),this},fillPointShape:function(t,e){return this.fillPoint(t.x,t.y,e)},fillPoint:function(t,e,i){return!i||i<1?i=1:(t-=i/2,e-=i/2),this.commandBuffer.push(r.FILL_RECT,t,e,i,i),this},fillTriangleShape:function(t){return this.fillTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},strokeTriangleShape:function(t){return this.strokeTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},fillTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.FILL_TRIANGLE,t,e,i,n,s,o),this},strokeTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.STROKE_TRIANGLE,t,e,i,n,s,o),this},strokeLineShape:function(t){return this.lineBetween(t.x1,t.y1,t.x2,t.y2)},lineBetween:function(t,e,i,n){return this.beginPath(),this.moveTo(t,e),this.lineTo(i,n),this.strokePath(),this},lineTo:function(t,e){return this.commandBuffer.push(r.LINE_TO,t,e),this},moveTo:function(t,e){return this.commandBuffer.push(r.MOVE_TO,t,e),this},strokePoints:function(t,e,i,n){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===n&&(n=t.length),this.beginPath(),this.moveTo(t[0].x,t[0].y);for(var s=1;s-1&&this.fillStyle(this.defaultFillColor,this.defaultFillAlpha),this.defaultStrokeColor>-1&&this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha),this},generateTexture:function(t,e,i){var n,s,r=this.scene.sys,o=r.game.renderer;if(void 0===e&&(e=r.scale.width),void 0===i&&(i=r.scale.height),w.TargetCamera.setScene(this.scene),w.TargetCamera.setViewport(0,0,e,i),w.TargetCamera.scrollX=this.x,w.TargetCamera.scrollY=this.y,"string"==typeof t)if(r.textures.exists(t)){var a=(n=r.textures.get(t)).getSourceImage();a instanceof HTMLCanvasElement&&(s=a.getContext("2d"))}else s=(n=r.textures.createCanvas(t,e,i)).getSourceImage().getContext("2d");else t instanceof HTMLCanvasElement&&(s=t.getContext("2d"));return s&&(this.renderCanvas(o,this,0,w.TargetCamera,null,s,!1),n&&n.refresh()),this},preDestroy:function(){this.commandBuffer=[]}});w.TargetCamera=new n,t.exports=w},function(t,e){t.exports={ARC:0,BEGIN_PATH:1,CLOSE_PATH:2,FILL_RECT:3,LINE_TO:4,MOVE_TO:5,LINE_STYLE:6,FILL_STYLE:7,FILL_PATH:8,STROKE_PATH:9,FILL_TRIANGLE:10,STROKE_TRIANGLE:11,SAVE:14,RESTORE:15,TRANSLATE:16,SCALE:17,ROTATE:18,SET_TEXTURE:19,CLEAR_TEXTURE:20,GRADIENT_FILL_STYLE:21,GRADIENT_LINE_STYLE:22}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.width/2,r=t.height/2;return i.x=t.x+s*Math.cos(e),i.y=t.y+r*Math.sin(e),i}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(395),a=i(123),h=i(397),l=i(966),u=new n({Extends:r,Mixins:[s.Depth,s.Mask,s.Pipeline,s.Transform,s.Visible,l],initialize:function(t,e,i,n){if(r.call(this,t,"ParticleEmitterManager"),this.blendMode=-1,this.timeScale=1,this.texture=null,this.frame=null,this.frameNames=[],null===i||"object"!=typeof i&&!Array.isArray(i)||(n=i,i=null),this.setTexture(e,i),this.initPipeline(),this.emitters=new a(this),this.wells=new a(this),n){Array.isArray(n)||(n=[n]);for(var s=0;s0?e.defaultFrame=i[0]:e.defaultFrame=this.defaultFrame,this},addEmitter:function(t){return this.emitters.add(t)},createEmitter:function(t){return this.addEmitter(new h(this,t))},removeEmitter:function(t){return this.emitters.remove(t,!0)},addGravityWell:function(t){return this.wells.add(t)},createGravityWell:function(t){return this.addGravityWell(new o(t))},emitParticle:function(t,e,i){for(var n=this.emitters.list,s=0;ss.width&&(t=s.width-this.frame.cutX),this.frame.cutY+e>s.height&&(e=s.height-this.frame.cutY),this.frame.setSize(t,e,this.frame.cutX,this.frame.cutY)}this.updateDisplayOrigin();var r=this.input;return r&&!r.customHitArea&&(r.hitArea.width=t,r.hitArea.height=e),this},setGlobalTint:function(t){return this.globalTint=t,this},setGlobalAlpha:function(t){return this.globalAlpha=t,this},saveTexture:function(t){return this.textureManager.renameTexture(this.texture.key,t),this._saved=!0,this.texture},fill:function(t,e,i,n,s,r){void 0===e&&(e=1),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.frame.cutWidth),void 0===r&&(r=this.frame.cutHeight);var o=255&(t>>16|0),a=255&(t>>8|0),h=255&(0|t),l=this.gl,u=this.frame;if(this.camera.preRender(1,1),l){var c=this.camera._cx,f=this.camera._cy,p=this.camera._cw,g=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(c,f,p,g,g);var v=this.pipeline;v.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),v.drawFillRect(i,n,s,r,d.getTintFromFloats(o/255,a/255,h/255,1),e),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),v.projOrtho(0,v.width,v.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.context.fillStyle="rgba("+o+","+a+","+h+","+e+")",this.context.fillRect(i+u.cutX,n+u.cutY,s,r),this.renderer.setContext();return this.dirty=!0,this},clear:function(){if(this.dirty){var t=this.gl;if(t){var e=this.renderer;e.setFramebuffer(this.framebuffer,!0),this.frame.cutWidth===this.canvas.width&&this.frame.cutHeight===this.canvas.height||t.scissor(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),e.setFramebuffer(null,!0)}else{var i=this.context;i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),i.restore()}this.dirty=!1}return this},erase:function(t,e,i){this._eraseMode=!0;var s=this.renderer.currentBlendMode;return this.renderer.setBlendMode(n.ERASE),this.draw(t,e,i,1,16777215),this.renderer.setBlendMode(s),this._eraseMode=!1,this},draw:function(t,e,i,n,s){void 0===n&&(n=this.globalAlpha),s=void 0===s?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(s>>16)+(65280&s)+((255&s)<<16),Array.isArray(t)||(t=[t]);var r=this.gl;if(this.camera.preRender(1,1),r){var o=this.camera._cx,a=this.camera._cy,h=this.camera._cw,l=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(o,a,h,l,l);var u=this.pipeline;u.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),this.batchList(t,e,i,n,s),u.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),u.projOrtho(0,u.width,u.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.batchList(t,e,i,n,s),this.renderer.setContext();return this.dirty=!0,this},drawFrame:function(t,e,i,n,s,r){void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.globalAlpha),r=void 0===r?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(r>>16)+(65280&r)+((255&r)<<16);var o=this.gl,a=this.textureManager.getFrame(t,e);if(a){if(this.camera.preRender(1,1),o){var h=this.camera._cx,l=this.camera._cy,u=this.camera._cw,c=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(h,l,u,c,c);var d=this.pipeline;d.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),d.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,r,s,this.camera.matrix,null),d.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),d.projOrtho(0,d.width,d.height,0,-1e3,1e3)}else this.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,s,r);this.dirty=!0}return this},batchList:function(t,e,i,n,s){for(var r=0;rr&&(o=t[r]),s[r]=o,t.length>r+1&&(o=t[r+1]),s[r+1]=o}return this},setColors:function(t){var e=this.points.length;if(e<1)return this;var i,n=this.colors;void 0===t?t=[16777215]:Array.isArray(t)||(t=[t]);var s=0;if(t.length===e)for(i=0;is&&(r=t[s]),n[s]=r,t.length>s+1&&(r=t[s+1]),n[s+1]=r}return this},setPoints:function(t,e,i){if(void 0===t&&(t=2),"number"==typeof t){var n,s,r,o=t;if(o<2&&(o=2),t=[],this.horizontal)for(r=-this.frame.halfWidth,s=this.frame.width/(o-1),n=0;nl){if(0===c){for(var g=f;g.length&&(g=g.slice(0,-1),!((p=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var v=d.substr(g.length);u[c]=v,h+=g}var m=u[c].length?c:c+1,y=u.slice(m).join(" ").replace(/[ \n]*$/gi,"");s[o+1]=y+" "+(s[o+1]||""),r=s.length;break}h+=f,l-=p}n+=h.replace(/[ \n]*$/gi,"")+"\n"}}return n=n.replace(/[\s|\n]*$/gi,"")},basicWordWrap:function(t,e,i){for(var n="",s=t.split(this.splitRegExp),r=s.length-1,o=e.measureText(" ").width,a=0;a<=r;a++){for(var h=i,l=s[a].split(" "),u=l.length-1,c=0;c<=u;c++){var d=l[c],f=e.measureText(d).width,p=f+o;p>h&&c>0&&(n+="\n",h=i),n+=d,c0&&(d+=h.lineSpacing*g),i.rtl)c=f-c;else if("right"===i.align)c+=o-h.lineWidths[g];else if("center"===i.align)c+=(o-h.lineWidths[g])/2;else if("justify"===i.align){if(h.lineWidths[g]/h.width>=.85){var v=h.width-h.lineWidths[g],m=e.measureText(" ").width,y=a[g].trim(),x=y.split(" ");v+=(a[g].length-y.length)*m;for(var T=Math.floor(v/m),w=0;T>0;)x[w]+=" ",w=(w+1)%(x.length-1||1),--T;a[g]=x.join(" ")}}this.autoRound&&(c=Math.round(c),d=Math.round(d)),i.strokeThickness&&(this.style.syncShadow(e,i.shadowStroke),e.strokeText(a[g],c,d)),i.color&&(this.style.syncShadow(e,i.shadowFill),e.fillText(a[g],c,d))}e.restore(),this.renderer.gl&&(this.frame.source.glTexture=this.renderer.canvasToTexture(t,this.frame.source.glTexture,!0),this.frame.glTexture=this.frame.source.glTexture),this.dirty=!0;var E=this.input;return E&&!E.customHitArea&&(E.hitArea.width=this.width,E.hitArea.height=this.height),this},getTextMetrics:function(){return this.style.getTextMetrics()},text:{get:function(){return this._text},set:function(t){this.setText(t)}},toJSON:function(){var t=o.ToJSON(this),e={autoRound:this.autoRound,text:this._text,style:this.style.toJSON(),padding:{left:this.padding.left,right:this.padding.right,top:this.padding.top,bottom:this.padding.bottom}};return t.data=e,t},preDestroy:function(){this.style.rtl&&c(this.canvas),s.remove(this.canvas),this.texture.destroy()}});t.exports=p},function(t,e,i){var n=i(27),s=i(0),r=i(12),o=i(19),a=i(14),h=i(323),l=i(161),u=i(985),c=i(3),d=new s({Extends:a,Mixins:[r.Alpha,r.BlendMode,r.ComputedSize,r.Crop,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Tint,r.Transform,r.Visible,u],initialize:function(t,e,i,s,r,l,u){var d=t.sys.game.renderer;a.call(this,t,"TileSprite");var f=t.sys.textures.get(l),p=f.get(u);s&&r?(s=Math.floor(s),r=Math.floor(r)):(s=p.width,r=p.height),this._tilePosition=new c,this._tileScale=new c(1,1),this.dirty=!1,this.renderer=d,this.canvas=n.create(this,s,r),this.context=this.canvas.getContext("2d"),this.displayTexture=f,this.displayFrame=p,this._crop=this.resetCropObject(),this.texture=t.sys.textures.addCanvas(null,this.canvas,!0),this.frame=this.texture.get(),this.potWidth=h(p.width),this.potHeight=h(p.height),this.fillCanvas=n.create2D(this,this.potWidth,this.potHeight),this.fillContext=this.fillCanvas.getContext("2d"),this.fillPattern=null,this.setPosition(e,i),this.setSize(s,r),this.setFrame(u),this.setOriginFromFrame(),this.initPipeline(),t.sys.game.events.on(o.CONTEXT_RESTORED,function(t){var e=t.gl;this.dirty=!0,this.fillPattern=null,this.fillPattern=t.createTexture2D(0,e.LINEAR,e.LINEAR,e.REPEAT,e.REPEAT,e.RGBA,this.fillCanvas,this.potWidth,this.potHeight)},this)},setTexture:function(t,e){return this.displayTexture=this.scene.sys.textures.get(t),this.setFrame(e)},setFrame:function(t){var e=this.displayTexture.get(t);return this.potWidth=h(e.width),this.potHeight=h(e.height),this.canvas.width=0,e.cutWidth&&e.cutHeight?this.renderFlags|=8:this.renderFlags&=-9,this.displayFrame=e,this.dirty=!0,this.updateTileTexture(),this},setTilePosition:function(t,e){return void 0!==t&&(this.tilePositionX=t),void 0!==e&&(this.tilePositionY=e),this},setTileScale:function(t,e){return void 0===t&&(t=this.tileScaleX),void 0===e&&(e=t),this.tileScaleX=t,this.tileScaleY=e,this},updateTileTexture:function(){if(this.dirty&&this.renderer){var t=this.displayFrame;if(t.source.isRenderTexture||t.source.isGLTexture)return console.warn("TileSprites can only use Image or Canvas based textures"),void(this.dirty=!1);var e=this.fillContext,i=this.fillCanvas,n=this.potWidth,s=this.potHeight;this.renderer.gl||(n=t.cutWidth,s=t.cutHeight),e.clearRect(0,0,n,s),i.width=n,i.height=s,e.drawImage(t.source.image,t.cutX,t.cutY,t.cutWidth,t.cutHeight,0,0,n,s),this.renderer.gl?this.fillPattern=this.renderer.canvasToTexture(i,this.fillPattern):this.fillPattern=e.createPattern(i,"repeat"),this.updateCanvas(),this.dirty=!1}},updateCanvas:function(){var t=this.canvas;if(t.width===this.width&&t.height===this.height||(t.width=this.width,t.height=this.height,this.frame.setSize(this.width,this.height),this.updateDisplayOrigin(),this.dirty=!0),!this.dirty||this.renderer&&this.renderer.gl)this.dirty=!1;else{var e=this.context;this.scene.sys.game.config.antialias||l.disable(e);var i=this._tileScale.x,n=this._tileScale.y,s=this._tilePosition.x,r=this._tilePosition.y;e.clearRect(0,0,this.width,this.height),e.save(),e.scale(i,n),e.translate(-s,-r),e.fillStyle=this.fillPattern,e.fillRect(s,r,this.width/i,this.height/n),e.restore(),this.dirty=!1}},preDestroy:function(){this.renderer&&this.renderer.gl&&this.renderer.deleteTexture(this.fillPattern),n.remove(this.canvas),n.remove(this.fillCanvas),this.fillPattern=null,this.fillContext=null,this.fillCanvas=null,this.displayTexture=null,this.displayFrame=null,this.texture.destroy(),this.renderer=null},tilePositionX:{get:function(){return this._tilePosition.x},set:function(t){this._tilePosition.x=t,this.dirty=!0}},tilePositionY:{get:function(){return this._tilePosition.y},set:function(t){this._tilePosition.y=t,this.dirty=!0}},tileScaleX:{get:function(){return this._tileScale.x},set:function(t){this._tileScale.x=t,this.dirty=!0}},tileScaleY:{get:function(){return this._tileScale.y},set:function(t){this._tileScale.y=t,this.dirty=!0}}});t.exports=d},function(t,e,i){var n=i(0),s=i(23),r=i(12),o=i(88),a=i(19),h=i(14),l=i(59),u=i(191),c=i(988),d=i(16),f=new n({Extends:h,Mixins:[r.Alpha,r.BlendMode,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Size,r.TextureCrop,r.Tint,r.Transform,r.Visible,c],initialize:function(t,e,i,n){h.call(this,t,"Video"),this.video=null,this.videoTexture=null,this.videoTextureSource=null,this.snapshotTexture=null,this.flipY=!1,this._key=u(),this.touchLocked=!0,this.playWhenUnlocked=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._systemMuted=!1,this._codeMuted=!1,this._systemPaused=!1,this._codePaused=!1,this._callbacks={play:this.playHandler.bind(this),error:this.loadErrorHandler.bind(this),end:this.completeHandler.bind(this),time:this.timeUpdateHandler.bind(this),seeking:this.seekingHandler.bind(this),seeked:this.seekedHandler.bind(this)},this._crop=this.resetCropObject(),this.markers={},this._markerIn=-1,this._markerOut=d.MAX_SAFE_INTEGER,this._lastUpdate=0,this._cacheKey="",this._isSeeking=!1,this.removeVideoElementOnDestroy=!1,this.setPosition(e,i),this.initPipeline(),n&&this.changeSource(n,!1);var s=t.sys.game.events;s.on(a.PAUSE,this.globalPause,this),s.on(a.RESUME,this.globalResume,this);var r=t.sys.sound;r&&r.on(l.GLOBAL_MUTE,this.globalMute,this)},play:function(t,e,i){if(this.touchLocked&&this.playWhenUnlocked||this.isPlaying())return this;var n=this.video;if(!n)return console.warn("Video not loaded"),this;void 0===t&&(t=n.loop);var s=this.scene.sys.sound;s&&s.mute&&this.setMute(!0),isNaN(e)||(this._markerIn=e),!isNaN(i)&&i>e&&(this._markerOut=i),n.loop=t;var r=this._callbacks,o=n.play();return void 0!==o?o.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)):(n.addEventListener("playing",r.play,!0),n.readyState<2&&(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval))),n.addEventListener("ended",r.end,!0),n.addEventListener("timeupdate",r.time,!0),n.addEventListener("seeking",r.seeking,!0),n.addEventListener("seeked",r.seeked,!0),this},changeSource:function(t,e,i,n,s){void 0===e&&(e=!0),this.video&&this.stop();var r=this.scene.sys.cache.video.get(t);return r?(this.video=r,this._cacheKey=t,this._codePaused=r.paused,this._codeMuted=r.muted,this.videoTexture?(this.scene.sys.textures.remove(this._key),this.videoTexture=this.scene.sys.textures.create(this._key,r,r.videoWidth,r.videoHeight),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,r.videoWidth,r.videoHeight),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,r.videoWidth,r.videoHeight)):this.updateTexture(),r.currentTime=0,this._lastUpdate=0,e&&this.play(i,n,s)):this.video=null,this},addMarker:function(t,e,i){return!isNaN(e)&&e>=0&&!isNaN(i)&&(this.markers[t]=[e,i]),this},playMarker:function(t,e){var i=this.markers[t];return i&&this.play(e,i[0],i[1]),this},removeMarker:function(t){return delete this.markers[t],this},snapshot:function(t,e){return void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.snapshotArea(0,0,this.width,this.height,t,e)},snapshotArea:function(t,e,i,n,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=this.height),void 0===s&&(s=i),void 0===r&&(r=n);var o=this.video,a=this.snapshotTexture;return a?(a.setSize(s,r),o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)):(a=this.scene.sys.textures.createCanvas(u(),s,r),this.snapshotTexture=a,o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)),a.update()},saveSnapshotTexture:function(t){return this.snapshotTexture?this.scene.sys.textures.renameTexture(this.snapshotTexture.key,t):this.snapshotTexture=this.scene.sys.textures.createCanvas(t,this.width,this.height),this.snapshotTexture},loadURL:function(t,e,i){void 0===e&&(e="loadeddata"),void 0===i&&(i=!1),this.video&&this.stop(),this.videoTexture&&this.scene.sys.textures.remove(this._key);var n=document.createElement("video");return n.controls=!1,i&&(n.muted=!0,n.defaultMuted=!0,n.setAttribute("autoplay","autoplay")),n.setAttribute("playsinline","playsinline"),n.setAttribute("preload","auto"),n.addEventListener("error",this._callbacks.error,!0),n.src=t,n.load(),this.video=n,this},playPromiseSuccessHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn)},playPromiseErrorHandler:function(t){this.scene.sys.input.once("pointerdown",this.unlockHandler,this),this.touchLocked=!0,this.playWhenUnlocked=!0,this.emit(o.VIDEO_ERROR,this,t)},playHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this.video.removeEventListener("playing",this._callbacks.play,!0)},loadErrorHandler:function(t){this.stop(),this.emit(o.VIDEO_ERROR,this,t)},unlockHandler:function(){this.touchLocked=!1,this.playWhenUnlocked=!1,this.emit(o.VIDEO_UNLOCKED,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn),this.video.play(),this.emit(o.VIDEO_PLAY,this)},completeHandler:function(){this.emit(o.VIDEO_COMPLETE,this)},timeUpdateHandler:function(){this.video&&this.video.currentTime=this._markerOut&&(t.loop?(t.currentTime=this._markerIn,this.updateTexture(),this._lastUpdate=e,this.emit(o.VIDEO_LOOP,this)):(this.emit(o.VIDEO_COMPLETE,this),this.stop())))}},checkVideoProgress:function(){this.video.readyState>=2?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):this.emit(o.VIDEO_TIMEOUT,this))},updateTexture:function(){var t=this.video,e=t.videoWidth,i=t.videoHeight;if(this.videoTexture){var n=this.videoTextureSource;n.source!==t&&(n.source=t,n.width=e,n.height=i),n.update()}else this.videoTexture=this.scene.sys.textures.create(this._key,t,e,i),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,e,i),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,e,i)},getVideoKey:function(){return this._cacheKey},seekTo:function(t){var e=this.video;if(e){var i=e.duration;if(i!==1/0&&!isNaN(i)){var n=i*t;this.setCurrentTime(n)}}return this},getCurrentTime:function(){return this.video?this.video.currentTime:0},setCurrentTime:function(t){var e=this.video;if(e){if("string"==typeof t){var i=t[0],n=parseFloat(t.substr(1));"+"===i?t=e.currentTime+n:"-"===i&&(t=e.currentTime-n)}e.currentTime=t,this._lastUpdate=t}return this},isSeeking:function(){return this._isSeeking},seekingHandler:function(){this._isSeeking=!0,this.emit(o.VIDEO_SEEKING,this)},seekedHandler:function(){this._isSeeking=!1,this.emit(o.VIDEO_SEEKED,this),this.video&&this.updateTexture()},getProgress:function(){var t=this.video;if(t){var e=t.currentTime,i=t.duration;if(i!==1/0&&!isNaN(i))return e/i}return 0},getDuration:function(){return this.video?this.video.duration:0},setMute:function(t){void 0===t&&(t=!0),this._codeMuted=t;var e=this.video;return e&&(e.muted=!!this._systemMuted||t),this},isMuted:function(){return this._codeMuted},globalMute:function(t,e){this._systemMuted=e;var i=this.video;i&&(i.muted=!!this._codeMuted||e)},globalPause:function(){this._systemPaused=!0,this.video&&this.video.pause()},globalResume:function(){this._systemPaused=!1,this.video&&!this._codePaused&&this.video.play()},setPaused:function(t){void 0===t&&(t=!0);var e=this.video;return this._codePaused=t,e&&(t?e.paused||e.pause():t||e.paused&&!this._systemPaused&&e.play()),this},getVolume:function(){return this.video?this.video.volume:1},setVolume:function(t){return void 0===t&&(t=1),this.video&&(this.video.volume=s(t,0,1)),this},getPlaybackRate:function(){return this.video?this.video.playbackRate:1},setPlaybackRate:function(t){return this.video&&(this.video.playbackRate=t),this},getLoop:function(){return!!this.video&&this.video.loop},setLoop:function(t){return void 0===t&&(t=!0),this.video&&(this.video.loop=t),this},isPlaying:function(){return!!this.video&&!(this.video.paused||this.video.ended)},isPaused:function(){return this.video&&this.video.paused||this._codePaused||this._systemPaused},saveTexture:function(t,e){return void 0===e&&(e=!1),this.videoTexture&&this.scene.sys.textures.renameTexture(this._key,t),this._key=t,this.flipY=e,this.videoTextureSource&&this.videoTextureSource.setFlipY(e),this.videoTexture},stop:function(){var t=this.video;if(t){var e=this._callbacks;for(var i in e)t.removeEventListener(i,e[i],!0);t.pause()}return this._retryID&&window.clearTimeout(this._retryID),this.emit(o.VIDEO_STOP,this),this},removeVideoElement:function(){var t=this.video;if(t){for(t.parentNode&&t.parentNode.removeChild(t);t.hasChildNodes();)t.removeChild(t.firstChild);t.removeAttribute("autoplay"),t.removeAttribute("src"),this.video=null}},preDestroy:function(){this.stop(),this.removeVideoElementOnDestroy&&this.removeVideoElement();var t=this.scene.sys.game.events;t.off(a.PAUSE,this.globalPause,this),t.off(a.RESUME,this.globalResume,this);var e=this.scene.sys.sound;e&&e.off(l.GLOBAL_MUTE,this.globalMute,this),this._retryID&&window.clearTimeout(this._retryID)}});t.exports=f},function(t,e,i){var n=i(0),s=i(197),r=i(412),o=i(46),a=new n({initialize:function(t){this.type=o.POLYGON,this.area=0,this.points=[],t&&this.setTo(t)},contains:function(t,e){return s(this,t,e)},setTo:function(t){if(this.area=0,this.points=[],"string"==typeof t&&(t=t.split(" ")),!Array.isArray(t))return this;for(var e,i=Number.MAX_VALUE,n=0;no||r>a)return!1;if(s<=i||r<=n)return!0;var h=s-i,l=r-n;return h*h+l*l<=t.radius*t.radius}},function(t,e,i){var n=i(4),s=i(203);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a=t.x1,h=t.y1,l=t.x2,u=t.y2,c=e.x,d=e.y,f=e.radius,p=l-a,g=u-h,v=a-c,m=h-d,y=p*p+g*g,x=2*(p*v+g*m),T=x*x-4*y*(v*v+m*m-f*f);if(0===T){var w=-x/(2*y);r=a+w*p,o=h+w*g,w>=0&&w<=1&&i.push(new n(r,o))}else if(T>0){var E=(-x-Math.sqrt(T))/(2*y);r=a+E*p,o=h+E*g,E>=0&&E<=1&&i.push(new n(r,o));var _=(-x+Math.sqrt(T))/(2*y);r=a+_*p,o=h+_*g,_>=0&&_<=1&&i.push(new n(r,o))}}return i}},function(t,e,i){var n=i(55),s=new(i(4));t.exports=function(t,e,i){if(void 0===i&&(i=s),n(e,t.x1,t.y1))return i.x=t.x1,i.y=t.y1,!0;if(n(e,t.x2,t.y2))return i.x=t.x2,i.y=t.y2,!0;var r=t.x2-t.x1,o=t.y2-t.y1,a=e.x-t.x1,h=e.y-t.y1,l=r*r+o*o,u=r,c=o;if(l>0){var d=(a*r+h*o)/l;u*=d,c*=d}return i.x=t.x1+u,i.y=t.y1+c,u*u+c*c<=l&&u*r+c*o>=0&&n(e,i.x,i.y)}},function(t,e,i){var n=i(4),s=i(82),r=i(425);t.exports=function(t,e,i){if(void 0===i&&(i=[]),r(t,e))for(var o=e.getLineA(),a=e.getLineB(),h=e.getLineC(),l=e.getLineD(),u=[new n,new n,new n,new n],c=[s(o,t,u[0]),s(a,t,u[1]),s(h,t,u[2]),s(l,t,u[3])],d=0;d<4;d++)c[d]&&i.push(u[d]);return i}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=!1),void 0===n&&(n=[]);for(var s,r,o,a,h,l,u=t.x3-t.x1,c=t.y3-t.y1,d=t.x2-t.x1,f=t.y2-t.y1,p=u*u+c*c,g=u*d+c*f,v=d*d+f*f,m=p*v-g*g,y=0===m?0:1/m,x=t.x1,T=t.y1,w=0;w=0&&r>=0&&s+r<1&&(n.push({x:e[w].x,y:e[w].y}),i)));w++);return n}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,t}},function(t,e){t.exports=function(t){return 0===t.height?NaN:t.width/t.height}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,o=t.x3-e,a=t.y3-i,t.x3=o*s-a*r+e,t.y3=o*r+a*s+i,t}},function(t,e,i){t.exports={BUTTON_DOWN:i(1193),BUTTON_UP:i(1194),CONNECTED:i(1195),DISCONNECTED:i(1196),GAMEPAD_BUTTON_DOWN:i(1197),GAMEPAD_BUTTON_UP:i(1198)}},function(t,e,i){var n=i(18),s=i(133);t.exports=function(t,e){var i=void 0===t?s():n({},t);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=i(359),u=new n({Extends:r,initialize:function(t,e,i,n){var s="xml";if(h(e)){var o=e;e=a(o,"key"),i=a(o,"url"),n=a(o,"xhrSettings"),s=a(o,"extension",s)}var l={type:"xml",cache:t.cacheManager.xml,extension:s,responseType:"text",key:e,url:i,xhrSettings:n};r.call(this,t,l)},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=l(this.xhrLoader.responseText),this.data?this.onProcessComplete():(console.warn("Invalid XMLFile: "+this.key),this.onProcessError())}});o.register("xml",function(t,e,i){if(Array.isArray(t))for(var n=0;n0&&(s.totalDuration+=s.t2*s.repeat),s.totalDuration>t&&(t=s.totalDuration),s.delay0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay,this.startDelay=e},init:function(){if(this.paused&&!this.parentIsTimeline)return this.state=h.PENDING_ADD,this._pausedState=h.INIT,!1;for(var t=this.data,e=this.totalTargets,i=0;i0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweenData(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=h.LOOP_DELAY):(this.state=h.ACTIVE,this.dispatchTweenEvent(r.TWEEN_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=h.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=h.PENDING_REMOVE,this.dispatchTweenEvent(r.TWEEN_COMPLETE,this.callbacks.onComplete))},pause:function(){return this.state===h.PAUSED?this:(this.paused=!0,this._pausedState=this.state,this.state=h.PAUSED,this)},play:function(t){void 0===t&&(t=!1);var e=this.state;return e!==h.INIT||this.parentIsTimeline?e===h.ACTIVE||e===h.PENDING_ADD&&this._pausedState===h.PENDING_ADD?this:this.parentIsTimeline||e!==h.PENDING_REMOVE&&e!==h.REMOVED?(this.parentIsTimeline?(this.resetTweenData(t),0===this.calculatedOffset?this.state=h.ACTIVE:(this.countdown=this.calculatedOffset,this.state=h.OFFSET_DELAY)):this.paused?(this.paused=!1,this.makeActive()):(this.resetTweenData(t),this.state=h.ACTIVE,this.makeActive()),this):(this.seek(0),this.parent.makeActive(this),this):(this.resetTweenData(!1),this.state=h.ACTIVE,this)},resetTweenData:function(t){for(var e=this.data,i=this.totalData,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY),r.getActiveValue&&(o[a]=r.getActiveValue(r.target,r.key,r.start))}},resume:function(){return this.state===h.PAUSED?(this.paused=!1,this.state=this._pausedState):this.play(),this},seek:function(t,e){if(void 0===e&&(e=16.6),this.totalDuration>=36e5)return console.warn("Tween.seek duration too long"),this;this.state===h.REMOVED&&this.makeActive(),this.elapsed=0,this.progress=0,this.totalElapsed=0,this.totalProgress=0;for(var i=this.data,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY)}this.calcDuration();var c=!1;this.state===h.PAUSED&&(c=!0,this.state=h.ACTIVE),this.isSeeking=!0;do{this.update(0,e)}while(this.totalProgress0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.start=e.getStartValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},setStateFromStart:function(t,e,i){return e.repeatCounter>0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},updateTweenData:function(t,e,i){var n=e.target;switch(e.state){case h.PLAYING_FORWARD:case h.PLAYING_BACKWARD:if(!n){e.state=h.COMPLETE;break}var s=e.elapsed,o=e.duration,a=0;(s+=i)>o&&(a=s-o,s=o);var l=e.state===h.PLAYING_FORWARD,u=s/o;if(e.elapsed=s,e.progress=u,e.previous=e.current,1===u)l?(e.current=e.end,n[e.key]=e.end,e.hold>0?(e.elapsed=e.hold-a,e.state=h.HOLD_DELAY):e.state=this.setStateFromEnd(t,e,a)):(e.current=e.start,n[e.key]=e.start,e.state=this.setStateFromStart(t,e,a));else{var c=l?e.ease(u):e.ease(1-u);e.current=e.start+(e.end-e.start)*c,n[e.key]=e.current}this.dispatchTweenDataEvent(r.TWEEN_UPDATE,t.callbacks.onUpdate,e);break;case h.DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PENDING_RENDER);break;case h.REPEAT_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PLAYING_FORWARD,this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e));break;case h.HOLD_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.state=this.setStateFromEnd(t,e,Math.abs(e.elapsed)));break;case h.PENDING_RENDER:n?(e.start=e.getStartValue(n,e.key,n[e.key],e.index,t.totalTargets,t),e.end=e.getEndValue(n,e.key,e.start,e.index,t.totalTargets,t),e.current=e.start,n[e.key]=e.start,e.state=h.PLAYING_FORWARD):e.state=h.COMPLETE}return e.state!==h.COMPLETE}});u.TYPES=["onActive","onComplete","onLoop","onRepeat","onStart","onUpdate","onYoyo"],a.register("tween",function(t){return this.scene.sys.tweens.add(t)}),o.register("tween",function(t){return this.scene.sys.tweens.create(t)}),t.exports=u},function(t,e,i){t.exports={TIMELINE_COMPLETE:i(1351),TIMELINE_LOOP:i(1352),TIMELINE_PAUSE:i(1353),TIMELINE_RESUME:i(1354),TIMELINE_START:i(1355),TIMELINE_UPDATE:i(1356),TWEEN_ACTIVE:i(1357),TWEEN_COMPLETE:i(1358),TWEEN_LOOP:i(1359),TWEEN_REPEAT:i(1360),TWEEN_START:i(1361),TWEEN_UPDATE:i(1362),TWEEN_YOYO:i(1363)}},function(t,e){t.exports=function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p){return{target:t,index:e,key:i,getActiveValue:r,getEndValue:n,getStartValue:s,ease:o,duration:0,totalDuration:0,delay:0,yoyo:l,hold:0,repeat:0,repeatDelay:0,flipX:f,flipY:p,progress:0,elapsed:0,repeatCounter:0,start:0,previous:0,current:0,end:0,t1:0,t2:0,gen:{delay:a,duration:h,hold:u,repeat:c,repeatDelay:d},state:0}}},function(t,e){t.exports={DEFAULT:0,LINEAR:0,NEAREST:1}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-Math.PI,Math.PI)}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-180,180)}},function(t,e,i){var n=i(0),s=i(64),r=i(2),o=i(233),a=i(335),h=i(336),l=i(30),u=i(9),c=i(141),d=new n({Extends:c,Mixins:[o],initialize:function(t){var e=t.renderer.config;c.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:r(t,"topology",t.renderer.gl.TRIANGLES),vertShader:r(t,"vertShader",h),fragShader:r(t,"fragShader",a),vertexCapacity:r(t,"vertexCapacity",6*e.batchSize),vertexSize:r(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.tempTriangle=[{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0}],this.tintEffect=2,this.strokeTint={TL:0,TR:0,BL:0,BR:0},this.fillTint={TL:0,TR:0,BL:0,BR:0},this.currentFrame={u0:0,v0:0,u1:1,v1:1},this.firstQuad=[0,0,0,0,0],this.prevQuad=[0,0,0,0,0],this.polygonCache=[],this.mvpInit()},onBind:function(){return c.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return c.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this},batchSprite:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix1,s=this._tempMatrix2,r=this._tempMatrix3,o=t.frame,a=o.glTexture,h=o.u0,l=o.v0,c=o.u1,d=o.v1,f=o.x,p=o.y,g=o.cutWidth,v=o.cutHeight,m=o.customPivot,y=t.displayOriginX,x=t.displayOriginY,T=-y+f,w=-x+p;if(t.isCropped){var E=t._crop;E.flipX===t.flipX&&E.flipY===t.flipY||o.updateCropUVs(E,t.flipX,t.flipY),h=E.u0,l=E.v0,c=E.u1,d=E.v1,g=E.width,v=E.height,T=-y+(f=E.x),w=-x+(p=E.y)}var _=1,A=1;t.flipX&&(m||(T+=-o.realWidth+2*y),_=-1),(t.flipY||o.source.isGLTexture&&!a.flipY)&&(m||(w+=-o.realHeight+2*x),A=-1),s.applyITRS(t.x,t.y,t.rotation,t.scaleX*_,t.scaleY*A),n.copyFrom(e.matrix),i?(n.multiplyWithOffset(i,-e.scrollX*t.scrollFactorX,-e.scrollY*t.scrollFactorY),s.e=t.x,s.f=t.y,n.multiply(s,r)):(s.e-=e.scrollX*t.scrollFactorX,s.f-=e.scrollY*t.scrollFactorY,n.multiply(s,r));var b=T+g,S=w+v,C=r.getX(T,w),M=r.getY(T,w),O=r.getX(T,S),P=r.getY(T,S),R=r.getX(b,S),L=r.getY(b,S),D=r.getX(b,w),F=r.getY(b,w),k=u.getTintAppendFloatAlpha(t._tintTL,e.alpha*t._alphaTL),I=u.getTintAppendFloatAlpha(t._tintTR,e.alpha*t._alphaTR),Y=u.getTintAppendFloatAlpha(t._tintBL,e.alpha*t._alphaBL),B=u.getTintAppendFloatAlpha(t._tintBR,e.alpha*t._alphaBR);e.roundPixels&&(C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P),R=Math.round(R),L=Math.round(L),D=Math.round(D),F=Math.round(F)),this.setTexture2D(a,0);var N=t._isTinted&&t.tintFill;this.batchQuad(C,M,O,P,R,L,D,F,h,l,c,d,k,I,Y,B,N,a,0)},batchQuad:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y){var x=!1;this.vertexCount+6>this.vertexCapacity&&(this.flush(),x=!0,this.setTexture2D(m,y));var T=this.vertexViewF32,w=this.vertexViewU32,E=this.vertexCount*this.vertexComponentCount-1;return T[++E]=t,T[++E]=e,T[++E]=h,T[++E]=l,T[++E]=v,w[++E]=d,T[++E]=i,T[++E]=n,T[++E]=h,T[++E]=c,T[++E]=v,w[++E]=p,T[++E]=s,T[++E]=r,T[++E]=u,T[++E]=c,T[++E]=v,w[++E]=g,T[++E]=t,T[++E]=e,T[++E]=h,T[++E]=l,T[++E]=v,w[++E]=d,T[++E]=s,T[++E]=r,T[++E]=u,T[++E]=c,T[++E]=v,w[++E]=g,T[++E]=o,T[++E]=a,T[++E]=u,T[++E]=l,T[++E]=v,w[++E]=f,this.vertexCount+=6,x},batchTri:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g){var v=!1;this.vertexCount+3>this.vertexCapacity&&(this.flush(),this.setTexture2D(p,g),v=!0);var m=this.vertexViewF32,y=this.vertexViewU32,x=this.vertexCount*this.vertexComponentCount-1;return m[++x]=t,m[++x]=e,m[++x]=o,m[++x]=a,m[++x]=f,y[++x]=u,m[++x]=i,m[++x]=n,m[++x]=o,m[++x]=l,m[++x]=f,y[++x]=c,m[++x]=s,m[++x]=r,m[++x]=h,m[++x]=l,m[++x]=f,y[++x]=d,this.vertexCount+=3,v},batchTexture:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y,x,T,w,E,_,A,b,S,C,M,O,P){this.renderer.setPipeline(this,t);var R=this._tempMatrix1,L=this._tempMatrix2,D=this._tempMatrix3,F=m/i+S,k=y/n+C,I=(m+x)/i+S,Y=(y+T)/n+C,B=o,N=a,X=-g,z=-v;if(t.isCropped){var U=t._crop;B=U.width,N=U.height,o=U.width,a=U.height;var G=m=U.x,W=y=U.y;c&&(G=x-U.x-U.width),d&&!e.isRenderTexture&&(W=T-U.y-U.height),F=G/i+S,k=W/n+C,I=(G+U.width)/i+S,Y=(W+U.height)/n+C,X=-g+m,z=-v+y}d^=!P&&e.isRenderTexture?1:0,c&&(B*=-1,X+=o),d&&(N*=-1,z+=a);var H=X+B,V=z+N;L.applyITRS(s,r,u,h,l),R.copyFrom(M.matrix),O?(R.multiplyWithOffset(O,-M.scrollX*f,-M.scrollY*p),L.e=s,L.f=r,R.multiply(L,D)):(L.e-=M.scrollX*f,L.f-=M.scrollY*p,R.multiply(L,D));var j=D.getX(X,z),K=D.getY(X,z),q=D.getX(X,V),J=D.getY(X,V),Z=D.getX(H,V),Q=D.getY(H,V),$=D.getX(H,z),tt=D.getY(H,z);M.roundPixels&&(j=Math.round(j),K=Math.round(K),q=Math.round(q),J=Math.round(J),Z=Math.round(Z),Q=Math.round(Q),$=Math.round($),tt=Math.round(tt)),this.setTexture2D(e,0),this.batchQuad(j,K,q,J,Z,Q,$,tt,F,k,I,Y,w,E,_,A,b,e,0)},batchTextureFrame:function(t,e,i,n,s,r,o){this.renderer.setPipeline(this);var a=this._tempMatrix1.copyFrom(r),h=this._tempMatrix2,l=e+t.width,c=i+t.height;o?a.multiply(o,h):h=a;var d=h.getX(e,i),f=h.getY(e,i),p=h.getX(e,c),g=h.getY(e,c),v=h.getX(l,c),m=h.getY(l,c),y=h.getX(l,i),x=h.getY(l,i);this.setTexture2D(t.glTexture,0),n=u.getTintAppendFloatAlpha(n,s),this.batchQuad(d,f,p,g,v,m,y,x,t.u0,t.v0,t.u1,t.v1,n,n,n,n,0,t.glTexture,0)},drawFillRect:function(t,e,i,n,s,r){var o=t+i,a=e+n;this.setTexture2D();var h=u.getTintAppendFloatAlphaAndSwap(s,r);this.batchQuad(t,e,t,a,o,a,o,e,0,0,1,1,h,h,h,h,2)},batchFillRect:function(t,e,i,n,s,r){this.renderer.setPipeline(this);var o=this._tempMatrix3;r&&r.multiply(s,o);var a=t+i,h=e+n,l=o.getX(t,e),u=o.getY(t,e),c=o.getX(t,h),d=o.getY(t,h),f=o.getX(a,h),p=o.getY(a,h),g=o.getX(a,e),v=o.getY(a,e),m=this.currentFrame,y=m.u0,x=m.v0,T=m.u1,w=m.v1;this.batchQuad(l,u,c,d,f,p,g,v,y,x,T,w,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.fillTint.BR,this.tintEffect)},batchFillTriangle:function(t,e,i,n,s,r,o,a){this.renderer.setPipeline(this);var h=this._tempMatrix3;a&&a.multiply(o,h);var l=h.getX(t,e),u=h.getY(t,e),c=h.getX(i,n),d=h.getY(i,n),f=h.getX(s,r),p=h.getY(s,r),g=this.currentFrame,v=g.u0,m=g.v0,y=g.u1,x=g.v1;this.batchTri(l,u,c,d,f,p,v,m,y,x,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.tintEffect)},batchStrokeTriangle:function(t,e,i,n,s,r,o,a,h){var l=this.tempTriangle;l[0].x=t,l[0].y=e,l[0].width=o,l[1].x=i,l[1].y=n,l[1].width=o,l[2].x=s,l[2].y=r,l[2].width=o,l[3].x=t,l[3].y=e,l[3].width=o,this.batchStrokePath(l,o,!1,a,h)},batchFillPath:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix3;i&&i.multiply(e,n);for(var r,o,a=t.length,h=this.polygonCache,l=this.fillTint.TL,u=this.fillTint.TR,c=this.fillTint.BL,d=this.tintEffect,f=0;f0&&V[4]?this.batchQuad(D,F,O,P,V[0],V[1],V[2],V[3],U,G,W,H,Y,B,N,X,I):(j[0]=D,j[1]=F,j[2]=O,j[3]=P,j[4]=1),h&&j[4]?this.batchQuad(C,M,R,L,j[0],j[1],j[2],j[3],U,G,W,H,Y,B,N,X,I):(V[0]=C,V[1]=M,V[2]=R,V[3]=L,V[4]=1)}}});t.exports=d},function(t,e){var i={modelMatrixDirty:!1,viewMatrixDirty:!1,projectionMatrixDirty:!1,modelMatrix:null,viewMatrix:null,projectionMatrix:null,mvpInit:function(){return this.modelMatrixDirty=!0,this.viewMatrixDirty=!0,this.projectionMatrixDirty=!0,this.modelMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.viewMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.projectionMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this},mvpUpdate:function(){var t=this.program;return this.modelMatrixDirty&&(this.renderer.setMatrix4(t,"uModelMatrix",!1,this.modelMatrix),this.modelMatrixDirty=!1),this.viewMatrixDirty&&(this.renderer.setMatrix4(t,"uViewMatrix",!1,this.viewMatrix),this.viewMatrixDirty=!1),this.projectionMatrixDirty&&(this.renderer.setMatrix4(t,"uProjectionMatrix",!1,this.projectionMatrix),this.projectionMatrixDirty=!1),this},modelIdentity:function(){var t=this.modelMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.modelMatrixDirty=!0,this},modelScale:function(t,e,i){var n=this.modelMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.modelMatrixDirty=!0,this},modelTranslate:function(t,e,i){var n=this.modelMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.modelMatrixDirty=!0,this},modelRotateX:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.modelMatrixDirty=!0,this},modelRotateY:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.modelMatrixDirty=!0,this},modelRotateZ:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.modelMatrixDirty=!0,this},viewIdentity:function(){var t=this.viewMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.viewMatrixDirty=!0,this},viewScale:function(t,e,i){var n=this.viewMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.viewMatrixDirty=!0,this},viewTranslate:function(t,e,i){var n=this.viewMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.viewMatrixDirty=!0,this},viewRotateX:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.viewMatrixDirty=!0,this},viewRotateY:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.viewMatrixDirty=!0,this},viewRotateZ:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.viewMatrixDirty=!0,this},viewLoad2D:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=0,e[3]=0,e[4]=t[2],e[5]=t[3],e[6]=0,e[7]=0,e[8]=t[4],e[9]=t[5],e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this.viewMatrixDirty=!0,this},viewLoad:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this.viewMatrixDirty=!0,this},projIdentity:function(){var t=this.projectionMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.projectionMatrixDirty=!0,this},projOrtho:function(t,e,i,n,s,r){var o=this.projectionMatrix,a=1/(t-e),h=1/(i-n),l=1/(s-r);return o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this.projectionMatrixDirty=!0,this},projPersp:function(t,e,i,n){var s=this.projectionMatrix,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this.projectionMatrixDirty=!0,this}};t.exports=i},,,function(t,e,i){t.exports={AlignTo:i(522),Angle:i(523),Call:i(524),GetFirst:i(525),GetLast:i(526),GridAlign:i(527),IncAlpha:i(588),IncX:i(589),IncXY:i(590),IncY:i(591),PlaceOnCircle:i(592),PlaceOnEllipse:i(593),PlaceOnLine:i(594),PlaceOnRectangle:i(595),PlaceOnTriangle:i(596),PlayAnimation:i(597),PropertyValueInc:i(34),PropertyValueSet:i(26),RandomCircle:i(598),RandomEllipse:i(599),RandomLine:i(600),RandomRectangle:i(601),RandomTriangle:i(602),Rotate:i(603),RotateAround:i(604),RotateAroundDistance:i(605),ScaleX:i(606),ScaleXY:i(607),ScaleY:i(608),SetAlpha:i(609),SetBlendMode:i(610),SetDepth:i(611),SetHitArea:i(612),SetOrigin:i(613),SetRotation:i(614),SetScale:i(615),SetScaleX:i(616),SetScaleY:i(617),SetScrollFactor:i(618),SetScrollFactorX:i(619),SetScrollFactorY:i(620),SetTint:i(621),SetVisible:i(622),SetX:i(623),SetXY:i(624),SetY:i(625),ShiftPosition:i(626),Shuffle:i(627),SmootherStep:i(628),SmoothStep:i(629),Spread:i(630),ToggleVisible:i(631),WrapInRectangle:i(632)}},function(t,e,i){var n=i(102),s=[];s[n.BOTTOM_CENTER]=i(238),s[n.BOTTOM_LEFT]=i(239),s[n.BOTTOM_RIGHT]=i(240),s[n.LEFT_BOTTOM]=i(241),s[n.LEFT_CENTER]=i(242),s[n.LEFT_TOP]=i(243),s[n.RIGHT_BOTTOM]=i(244),s[n.RIGHT_CENTER]=i(245),s[n.RIGHT_TOP]=i(246),s[n.TOP_CENTER]=i(247),s[n.TOP_LEFT]=i(248),s[n.TOP_RIGHT]=i(249);t.exports=function(t,e,i,n,r){return s[i](t,e,n,r)}},function(t,e,i){var n=i(38),s=i(74),r=i(75),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)+i),o(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(40),r=i(41),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)-i),o(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(42),r=i(43),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)+i),o(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(40),r=i(44),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(76),s=i(40),r=i(77),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(40),s=i(45),r=i(43),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)-i),o(t,s(e)-a),t}},function(t,e,i){var n=i(38),s=i(42),r=i(44),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(76),s=i(42),r=i(77),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(42),s=i(45),r=i(41),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(74),s=i(45),r=i(44),o=i(75);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)+i),r(t,s(e)-a),t}},function(t,e,i){var n=i(40),s=i(45),r=i(44),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)-i),r(t,s(e)-a),t}},function(t,e,i){var n=i(42),s=i(45),r=i(44),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)+i),r(t,s(e)-a),t}},function(t,e,i){var n=i(102),s=[];s[n.BOTTOM_CENTER]=i(251),s[n.BOTTOM_LEFT]=i(252),s[n.BOTTOM_RIGHT]=i(253),s[n.CENTER]=i(254),s[n.LEFT_CENTER]=i(256),s[n.RIGHT_CENTER]=i(257),s[n.TOP_CENTER]=i(258),s[n.TOP_LEFT]=i(259),s[n.TOP_RIGHT]=i(260),s[n.LEFT_BOTTOM]=s[n.BOTTOM_LEFT],s[n.LEFT_TOP]=s[n.TOP_LEFT],s[n.RIGHT_BOTTOM]=s[n.BOTTOM_RIGHT],s[n.RIGHT_TOP]=s[n.TOP_RIGHT];t.exports=function(t,e,i,n,r){return s[i](t,e,n,r)}},function(t,e,i){var n=i(38),s=i(74),r=i(44),o=i(75);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(40),r=i(44),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(42),r=i(44),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(255),s=i(74),r=i(76);t.exports=function(t,e,i,o){return void 0===i&&(i=0),void 0===o&&(o=0),n(t,s(e)+i,r(e)+o),t}},function(t,e,i){var n=i(75),s=i(77);t.exports=function(t,e,i){return n(t,e),s(t,i)}},function(t,e,i){var n=i(76),s=i(40),r=i(77),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(76),s=i(42),r=i(77),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(74),s=i(45),r=i(75),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(40),s=i(45),r=i(41),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)-i),o(t,s(e)-a),t}},function(t,e,i){var n=i(42),s=i(45),r=i(43),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(143),s=i(85),r=i(16),o=i(4);t.exports=function(t,e,i){void 0===i&&(i=new o);var a=s(e,0,r.PI2);return n(t,a,i)}},function(t,e,i){var n=i(263),s=i(143),r=i(85),o=i(16);t.exports=function(t,e,i,a){void 0===a&&(a=[]),e||(e=n(t)/i);for(var h=0;he.length&&(r=e.length),i?(n=e[r-1][i],(s=e[r][i])-t<=t-n?e[r]:e[r-1]):(n=e[r-1],(s=e[r])-t<=t-n?s:n)}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.textureKey=t,this.textureFrame=e,this.index=i,this.frame=n,this.isFirst=!1,this.isLast=!1,this.prevFrame=null,this.nextFrame=null,this.duration=0,this.progress=0},toJSON:function(){return{key:this.textureKey,frame:this.textureFrame,duration:this.duration}},destroy:function(){this.frame=void 0}});t.exports=n},function(t,e,i){var n=i(52),s={_blendMode:n.NORMAL,blendMode:{get:function(){return this._blendMode},set:function(t){"string"==typeof t&&(t=n[t]),(t|=0)>=-1&&(this._blendMode=t)}},setBlendMode:function(t){return this.blendMode=t,this}};t.exports=s},function(t,e){var i={_depth:0,depth:{get:function(){return this._depth},set:function(t){this.scene.sys.queueDepthSort(),this._depth=t}},setDepth:function(t){return void 0===t&&(t=0),this.depth=t,this}};t.exports=i},function(t,e,i){var n=i(146),s=i(108);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=s(t)/i);for(var o=0;o=t.right&&(h=1,a+=o-t.right,o=t.right);break;case 1:(a+=e)>=t.bottom&&(h=2,o-=a-t.bottom,a=t.bottom);break;case 2:(o-=e)<=t.left&&(h=3,a-=t.left-o,o=t.left);break;case 3:(a-=e)<=t.top&&(h=0,a=t.top)}return r}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);for(var i=null,n=0;n-h&&(c-=h,n+=l),fd.right&&(f=u(f,f+(g-d.right),this.lerp.x)),vd.bottom&&(p=u(p,p+(v-d.bottom),this.lerp.y))):(f=u(f,g-h,this.lerp.x),p=u(p,v-l,this.lerp.y))}this.useBounds&&(f=this.clampX(f),p=this.clampY(p)),this.roundPixels&&(h=Math.round(h),l=Math.round(l)),this.scrollX=f,this.scrollY=p;var m=f+n,y=p+s;this.midPoint.set(m,y);var x=e/o,T=i/o;this.worldView.setTo(m-x/2,y-T/2,x,T),a.applyITRS(this.x+h,this.y+l,this.rotation,o,o),a.translate(-h,-l),this.shakeEffect.preRender()},setLerp:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=t),this.lerp.set(t,e),this},setFollowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.followOffset.set(t,e),this},startFollow:function(t,e,i,n,s,r){void 0===e&&(e=!1),void 0===i&&(i=1),void 0===n&&(n=i),void 0===s&&(s=0),void 0===r&&(r=s),this._follow=t,this.roundPixels=e,i=o(i,0,1),n=o(n,0,1),this.lerp.set(i,n),this.followOffset.set(s,r);var a=this.width/2,h=this.height/2,l=t.x-s,u=t.y-r;return this.midPoint.set(l,u),this.scrollX=l-a,this.scrollY=u-h,this.useBounds&&(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},stopFollow:function(){return this._follow=null,this},resetFX:function(){return this.panEffect.reset(),this.shakeEffect.reset(),this.flashEffect.reset(),this.fadeEffect.reset(),this},update:function(t,e){this.visible&&(this.panEffect.update(t,e),this.zoomEffect.update(t,e),this.shakeEffect.update(t,e),this.flashEffect.update(t,e),this.fadeEffect.update(t,e))},destroy:function(){this.clearRenderToTexture(),this.resetFX(),n.prototype.destroy.call(this),this._follow=null,this.deadzone=null}});t.exports=f},function(t,e,i){var n=i(32);t.exports=function(t){var e=new n;t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,n){return e+e+i+i+n+n});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e.setTo(s,r,o)}return e}},function(t,e){t.exports=function(t,e,i,n){return n<<24|t<<16|e<<8|i}},function(t,e){t.exports=function(t,e,i,n){void 0===n&&(n={h:0,s:0,v:0}),t/=255,e/=255,i/=255;var s=Math.min(t,e,i),r=Math.max(t,e,i),o=r-s,a=0,h=0===r?0:o/r,l=r;return r!==s&&(r===t?a=(e-i)/o+(e16777215?{a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{a:255,r:t>>16&255,g:t>>8&255,b:255&t}}},function(t,e,i){var n=i(32);t.exports=function(t){return new n(t.r,t.g,t.b,t.a)}},function(t,e,i){var n=i(32);t.exports=function(t){var e=new n,i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t.toLowerCase());if(i){var s=parseInt(i[1],10),r=parseInt(i[2],10),o=parseInt(i[3],10),a=void 0!==i[4]?parseFloat(i[4]):1;e.setTo(s,r,o,255*a)}return e}},function(t,e,i){t.exports={Fade:i(657),Flash:i(658),Pan:i(659),Shake:i(692),Zoom:i(693)}},function(t,e,i){t.exports={In:i(660),Out:i(661),InOut:i(662)}},function(t,e,i){t.exports={In:i(663),Out:i(664),InOut:i(665)}},function(t,e,i){t.exports={In:i(666),Out:i(667),InOut:i(668)}},function(t,e,i){t.exports={In:i(669),Out:i(670),InOut:i(671)}},function(t,e,i){t.exports={In:i(672),Out:i(673),InOut:i(674)}},function(t,e,i){t.exports={In:i(675),Out:i(676),InOut:i(677)}},function(t,e,i){t.exports=i(678)},function(t,e,i){t.exports={In:i(679),Out:i(680),InOut:i(681)}},function(t,e,i){t.exports={In:i(682),Out:i(683),InOut:i(684)}},function(t,e,i){t.exports={In:i(685),Out:i(686),InOut:i(687)}},function(t,e,i){t.exports={In:i(688),Out:i(689),InOut:i(690)}},function(t,e,i){t.exports=i(691)},function(t,e,i){var n=i(0),s=i(10),r=i(310),o=i(2),a=i(6),h=i(7),l=i(165),u=i(1),c=i(170),d=i(158),f=new n({initialize:function(t){void 0===t&&(t={});this.width=a(t,"width",1024),this.height=a(t,"height",768),this.zoom=a(t,"zoom",1),this.resolution=a(t,"resolution",1),this.parent=a(t,"parent",void 0),this.scaleMode=a(t,"scaleMode",0),this.expandParent=a(t,"expandParent",!0),this.autoRound=a(t,"autoRound",!1),this.autoCenter=a(t,"autoCenter",0),this.resizeInterval=a(t,"resizeInterval",500),this.fullscreenTarget=a(t,"fullscreenTarget",null),this.minWidth=a(t,"minWidth",0),this.maxWidth=a(t,"maxWidth",0),this.minHeight=a(t,"minHeight",0),this.maxHeight=a(t,"maxHeight",0);var e=a(t,"scale",null);e&&(this.width=a(e,"width",this.width),this.height=a(e,"height",this.height),this.zoom=a(e,"zoom",this.zoom),this.resolution=a(e,"resolution",this.resolution),this.parent=a(e,"parent",this.parent),this.scaleMode=a(e,"mode",this.scaleMode),this.expandParent=a(e,"expandParent",this.expandParent),this.autoRound=a(e,"autoRound",this.autoRound),this.autoCenter=a(e,"autoCenter",this.autoCenter),this.resizeInterval=a(e,"resizeInterval",this.resizeInterval),this.fullscreenTarget=a(e,"fullscreenTarget",this.fullscreenTarget),this.minWidth=a(e,"min.width",this.minWidth),this.maxWidth=a(e,"max.width",this.maxWidth),this.minHeight=a(e,"min.height",this.minHeight),this.maxHeight=a(e,"max.height",this.maxHeight)),this.renderType=a(t,"type",s.AUTO),this.canvas=a(t,"canvas",null),this.context=a(t,"context",null),this.canvasStyle=a(t,"canvasStyle",null),this.customEnvironment=a(t,"customEnvironment",!1),this.sceneConfig=a(t,"scene",null),this.seed=a(t,"seed",[(Date.now()*Math.random()).toString()]),l.RND=new l.RandomDataGenerator(this.seed),this.gameTitle=a(t,"title",""),this.gameURL=a(t,"url","https://phaser.io"),this.gameVersion=a(t,"version",""),this.autoFocus=a(t,"autoFocus",!0),this.domCreateContainer=a(t,"dom.createContainer",!1),this.domBehindCanvas=a(t,"dom.behindCanvas",!1),this.inputKeyboard=a(t,"input.keyboard",!0),this.inputKeyboardEventTarget=a(t,"input.keyboard.target",window),this.inputKeyboardCapture=a(t,"input.keyboard.capture",[]),this.inputMouse=a(t,"input.mouse",!0),this.inputMouseEventTarget=a(t,"input.mouse.target",null),this.inputMouseCapture=a(t,"input.mouse.capture",!0),this.inputTouch=a(t,"input.touch",r.input.touch),this.inputTouchEventTarget=a(t,"input.touch.target",null),this.inputTouchCapture=a(t,"input.touch.capture",!0),this.inputActivePointers=a(t,"input.activePointers",1),this.inputSmoothFactor=a(t,"input.smoothFactor",0),this.inputWindowEvents=a(t,"input.windowEvents",!0),this.inputGamepad=a(t,"input.gamepad",!1),this.inputGamepadEventTarget=a(t,"input.gamepad.target",window),this.disableContextMenu=a(t,"disableContextMenu",!1),this.audio=a(t,"audio"),this.hideBanner=!1===a(t,"banner",null),this.hidePhaser=a(t,"banner.hidePhaser",!1),this.bannerTextColor=a(t,"banner.text","#ffffff"),this.bannerBackgroundColor=a(t,"banner.background",["#ff0000","#ffff00","#00ff00","#00ffff","#000000"]),""===this.gameTitle&&this.hidePhaser&&(this.hideBanner=!0),this.fps=a(t,"fps",null);var i=a(t,"render",t);this.antialias=a(i,"antialias",!0),this.antialiasGL=a(i,"antialiasGL",!0),this.mipmapFilter=a(i,"mipmapFilter","LINEAR"),this.desynchronized=a(i,"desynchronized",!1),this.roundPixels=a(i,"roundPixels",!1),this.pixelArt=a(i,"pixelArt",1!==this.zoom),this.pixelArt&&(this.antialias=!1,this.roundPixels=!0),this.transparent=a(i,"transparent",!1),this.clearBeforeRender=a(i,"clearBeforeRender",!0),this.premultipliedAlpha=a(i,"premultipliedAlpha",!0),this.failIfMajorPerformanceCaveat=a(i,"failIfMajorPerformanceCaveat",!1),this.powerPreference=a(i,"powerPreference","default"),this.batchSize=a(i,"batchSize",2e3),this.maxLights=a(i,"maxLights",10);var n=a(t,"backgroundColor",0);this.backgroundColor=d(n),0===n&&this.transparent&&(this.backgroundColor.alpha=0),this.preBoot=a(t,"callbacks.preBoot",u),this.postBoot=a(t,"callbacks.postBoot",u),this.physics=a(t,"physics",{}),this.defaultPhysicsSystem=a(this.physics,"default",!1),this.loaderBaseURL=a(t,"loader.baseURL",""),this.loaderPath=a(t,"loader.path",""),this.loaderMaxParallelDownloads=a(t,"loader.maxParallelDownloads",32),this.loaderCrossOrigin=a(t,"loader.crossOrigin",void 0),this.loaderResponseType=a(t,"loader.responseType",""),this.loaderAsync=a(t,"loader.async",!0),this.loaderUser=a(t,"loader.user",""),this.loaderPassword=a(t,"loader.password",""),this.loaderTimeout=a(t,"loader.timeout",0),this.loaderWithCredentials=a(t,"loader.withCredentials",!1),this.installGlobalPlugins=[],this.installScenePlugins=[];var f=a(t,"plugins",null),p=c.DefaultScene;f&&(Array.isArray(f)?this.defaultPlugins=f:h(f)&&(this.installGlobalPlugins=o(f,"global",[]),this.installScenePlugins=o(f,"scene",[]),Array.isArray(f.default)?p=f.default:Array.isArray(f.defaultMerge)&&(p=p.concat(f.defaultMerge)))),this.defaultPlugins=p;var g="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg";this.defaultImage=a(t,"images.default",g+"AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="),this.missingImage=a(t,"images.missing",g+"CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="),window&&(window.FORCE_WEBGL?this.renderType=s.WEBGL:window.FORCE_CANVAS&&(this.renderType=s.CANVAS))}});t.exports=f},function(t,e,i){t.exports={os:i(112),browser:i(113),features:i(164),input:i(722),audio:i(723),video:i(724),fullscreen:i(725),canvasFeatures:i(311)}},function(t,e,i){var n,s,r,o=i(27),a={supportInverseAlpha:!1,supportNewBlendModes:!1};t.exports=(void 0!==document&&(a.supportNewBlendModes=(n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",s="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",(r=new Image).onload=function(){var t=new Image;t.onload=function(){var e=o.create(t,6,1).getContext("2d");if(e.globalCompositeOperation="multiply",e.drawImage(r,0,0),e.drawImage(t,2,0),!e.getImageData(2,0,1,1))return!1;var i=e.getImageData(2,0,1,1).data;o.remove(t),a.supportNewBlendModes=255===i[0]&&0===i[1]&&0===i[2]},t.src=n+"/wCKxvRF"+s},r.src=n+"AP804Oa6"+s,!1),a.supportInverseAlpha=function(){var t=o.create(this,2,1).getContext("2d");t.fillStyle="rgba(10, 20, 30, 0.5)",t.fillRect(0,0,1,1);var e=t.getImageData(0,0,1,1);if(null===e)return!1;t.putImageData(e,1,0);var i=t.getImageData(1,0,1,1);return i.data[0]===e.data[0]&&i.data[1]===e.data[1]&&i.data[2]===e.data[2]&&i.data[3]===e.data[3]}()),a)},function(t,e){t.exports=function(t,e,i,n){return Math.atan2(n-e,i-t)}},function(t,e){t.exports=function(t){return(t%=2*Math.PI)>=0?t:t+2*Math.PI}},function(t,e){t.exports=function(t,e){var i=t.x-e.x,n=t.y-e.y;return Math.sqrt(i*i+n*n)}},function(t,e){t.exports=function(t,e,i,n){var s=t-i,r=e-n;return s*s+r*r}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t>e-i}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t0?Math.ceil(t):Math.floor(t)}},function(t,e,i){var n=i(3);t.exports=function(t,e,i,s,r,o,a,h){void 0===h&&(h=new n);var l=Math.sin(r),u=Math.cos(r),c=u*o,d=l*o,f=-l*a,p=u*a,g=1/(c*p+f*-d);return h.x=p*g*t+-f*g*e+(s*f-i*p)*g,h.y=c*g*e+-d*g*t+(-s*c+i*d)*g,h}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.x=0,this.y=0,this.z=0,this.w=0,"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},clone:function(){return new n(this.x,this.y,this.z,this.w)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z||0,this.w=t.w||0,this},equals:function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z||0,this.w+=t.w||0,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z||0,this.w-=t.w||0,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z||1,this.w*=t.w||1,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z||1,this.w/=t.w||1,this},distance:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return Math.sqrt(e*e+i*i+n*n+s*s)},distanceSq:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return e*e+i*i+n*n+s*s},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.val;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},reset:function(){return this.x=0,this.y=0,this.z=0,this.w=0,this}});n.prototype.sub=n.prototype.subtract,n.prototype.mul=n.prototype.multiply,n.prototype.div=n.prototype.divide,n.prototype.dist=n.prototype.distance,n.prototype.distSq=n.prototype.distanceSq,n.prototype.len=n.prototype.length,n.prototype.lenSq=n.prototype.lengthSq,t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(9),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this},fromMat4:function(t){var e=t.val,i=this.val;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[5];return t[1]=t[3],t[2]=t[6],t[3]=e,t[5]=t[7],t[6]=i,t[7]=n,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=l*r-o*h,c=-l*s+o*a,d=h*s-r*a,f=e*u+i*c+n*d;return f?(f=1/f,t[0]=u*f,t[1]=(-l*i+n*h)*f,t[2]=(o*i-n*r)*f,t[3]=c*f,t[4]=(l*e-n*a)*f,t[5]=(-o*e+n*s)*f,t[6]=d*f,t[7]=(-h*e+i*a)*f,t[8]=(r*e-i*s)*f,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return t[0]=r*l-o*h,t[1]=n*h-i*l,t[2]=i*o-n*r,t[3]=o*a-s*l,t[4]=e*l-n*a,t[5]=n*s-e*o,t[6]=s*h-r*a,t[7]=i*a-e*h,t[8]=e*r-i*s,this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*(l*r-o*h)+i*(-l*s+o*a)+n*(h*s-r*a)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=t.val,d=c[0],f=c[1],p=c[2],g=c[3],v=c[4],m=c[5],y=c[6],x=c[7],T=c[8];return e[0]=d*i+f*r+p*h,e[1]=d*n+f*o+p*l,e[2]=d*s+f*a+p*u,e[3]=g*i+v*r+m*h,e[4]=g*n+v*o+m*l,e[5]=g*s+v*a+m*u,e[6]=y*i+x*r+T*h,e[7]=y*n+x*o+T*l,e[8]=y*s+x*a+T*u,this},translate:function(t){var e=this.val,i=t.x,n=t.y;return e[6]=i*e[0]+n*e[3]+e[6],e[7]=i*e[1]+n*e[4]+e[7],e[8]=i*e[2]+n*e[5]+e[8],this},rotate:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=Math.sin(t),l=Math.cos(t);return e[0]=l*i+h*r,e[1]=l*n+h*o,e[2]=l*s+h*a,e[3]=l*r-h*i,e[4]=l*o-h*n,e[5]=l*a-h*s,this},scale:function(t){var e=this.val,i=t.x,n=t.y;return e[0]=i*e[0],e[1]=i*e[1],e[2]=i*e[2],e[3]=n*e[3],e[4]=n*e[4],e[5]=n*e[5],this},fromQuat:function(t){var e=t.x,i=t.y,n=t.z,s=t.w,r=e+e,o=i+i,a=n+n,h=e*r,l=e*o,u=e*a,c=i*o,d=i*a,f=n*a,p=s*r,g=s*o,v=s*a,m=this.val;return m[0]=1-(c+f),m[3]=l+v,m[6]=u-g,m[1]=l-v,m[4]=1-(h+f),m[7]=d+p,m[2]=u+g,m[5]=d-p,m[8]=1-(h+c),this},normalFromMat4:function(t){var e=t.val,i=this.val,n=e[0],s=e[1],r=e[2],o=e[3],a=e[4],h=e[5],l=e[6],u=e[7],c=e[8],d=e[9],f=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=n*h-s*a,T=n*l-r*a,w=n*u-o*a,E=s*l-r*h,_=s*u-o*h,A=r*u-o*l,b=c*v-d*g,S=c*m-f*g,C=c*y-p*g,M=d*m-f*v,O=d*y-p*v,P=f*y-p*m,R=x*P-T*O+w*M+E*C-_*S+A*b;return R?(R=1/R,i[0]=(h*P-l*O+u*M)*R,i[1]=(l*C-a*P-u*S)*R,i[2]=(a*O-h*C+u*b)*R,i[3]=(r*O-s*P-o*M)*R,i[4]=(n*P-r*C+o*S)*R,i[5]=(s*C-n*O-o*b)*R,i[6]=(v*A-m*_+y*E)*R,i[7]=(m*w-g*A-y*T)*R,i[8]=(g*_-v*w+y*x)*R,this):null}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(16),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},zero:function(){var t=this.val;return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=0,this},xyz:function(t,e,i){this.identity();var n=this.val;return n[12]=t,n[13]=e,n[14]=i,this},scaling:function(t,e,i){this.zero();var n=this.val;return n[0]=t,n[5]=e,n[10]=i,n[15]=1,this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[3],s=t[6],r=t[7],o=t[11];return t[1]=t[4],t[2]=t[8],t[3]=t[12],t[4]=e,t[6]=t[9],t[7]=t[13],t[8]=i,t[9]=s,t[11]=t[14],t[12]=n,t[13]=r,t[14]=o,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15],m=e*o-i*r,y=e*a-n*r,x=e*h-s*r,T=i*a-n*o,w=i*h-s*o,E=n*h-s*a,_=l*p-u*f,A=l*g-c*f,b=l*v-d*f,S=u*g-c*p,C=u*v-d*p,M=c*v-d*g,O=m*M-y*C+x*S+T*b-w*A+E*_;return O?(O=1/O,t[0]=(o*M-a*C+h*S)*O,t[1]=(n*C-i*M-s*S)*O,t[2]=(p*E-g*w+v*T)*O,t[3]=(c*w-u*E-d*T)*O,t[4]=(a*b-r*M-h*A)*O,t[5]=(e*M-n*b+s*A)*O,t[6]=(g*x-f*E-v*y)*O,t[7]=(l*E-c*x+d*y)*O,t[8]=(r*C-o*b+h*_)*O,t[9]=(i*b-e*C-s*_)*O,t[10]=(f*w-p*x+v*m)*O,t[11]=(u*x-l*w-d*m)*O,t[12]=(o*A-r*S-a*_)*O,t[13]=(e*S-i*A+n*_)*O,t[14]=(p*y-f*T-g*m)*O,t[15]=(l*T-u*y+c*m)*O,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return t[0]=o*(c*v-d*g)-u*(a*v-h*g)+p*(a*d-h*c),t[1]=-(i*(c*v-d*g)-u*(n*v-s*g)+p*(n*d-s*c)),t[2]=i*(a*v-h*g)-o*(n*v-s*g)+p*(n*h-s*a),t[3]=-(i*(a*d-h*c)-o*(n*d-s*c)+u*(n*h-s*a)),t[4]=-(r*(c*v-d*g)-l*(a*v-h*g)+f*(a*d-h*c)),t[5]=e*(c*v-d*g)-l*(n*v-s*g)+f*(n*d-s*c),t[6]=-(e*(a*v-h*g)-r*(n*v-s*g)+f*(n*h-s*a)),t[7]=e*(a*d-h*c)-r*(n*d-s*c)+l*(n*h-s*a),t[8]=r*(u*v-d*p)-l*(o*v-h*p)+f*(o*d-h*u),t[9]=-(e*(u*v-d*p)-l*(i*v-s*p)+f*(i*d-s*u)),t[10]=e*(o*v-h*p)-r*(i*v-s*p)+f*(i*h-s*o),t[11]=-(e*(o*d-h*u)-r*(i*d-s*u)+l*(i*h-s*o)),t[12]=-(r*(u*g-c*p)-l*(o*g-a*p)+f*(o*c-a*u)),t[13]=e*(u*g-c*p)-l*(i*g-n*p)+f*(i*c-n*u),t[14]=-(e*(o*g-a*p)-r*(i*g-n*p)+f*(i*a-n*o)),t[15]=e*(o*c-a*u)-r*(i*c-n*u)+l*(i*a-n*o),this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return(e*o-i*r)*(c*v-d*g)-(e*a-n*r)*(u*v-d*p)+(e*h-s*r)*(u*g-c*p)+(i*a-n*o)*(l*v-d*f)-(i*h-s*o)*(l*g-c*f)+(n*h-s*a)*(l*p-u*f)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=e[9],d=e[10],f=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=t.val,x=y[0],T=y[1],w=y[2],E=y[3];return e[0]=x*i+T*o+w*u+E*p,e[1]=x*n+T*a+w*c+E*g,e[2]=x*s+T*h+w*d+E*v,e[3]=x*r+T*l+w*f+E*m,x=y[4],T=y[5],w=y[6],E=y[7],e[4]=x*i+T*o+w*u+E*p,e[5]=x*n+T*a+w*c+E*g,e[6]=x*s+T*h+w*d+E*v,e[7]=x*r+T*l+w*f+E*m,x=y[8],T=y[9],w=y[10],E=y[11],e[8]=x*i+T*o+w*u+E*p,e[9]=x*n+T*a+w*c+E*g,e[10]=x*s+T*h+w*d+E*v,e[11]=x*r+T*l+w*f+E*m,x=y[12],T=y[13],w=y[14],E=y[15],e[12]=x*i+T*o+w*u+E*p,e[13]=x*n+T*a+w*c+E*g,e[14]=x*s+T*h+w*d+E*v,e[15]=x*r+T*l+w*f+E*m,this},multiplyLocal:function(t){var e=[],i=this.val,n=t.val;return e[0]=i[0]*n[0]+i[1]*n[4]+i[2]*n[8]+i[3]*n[12],e[1]=i[0]*n[1]+i[1]*n[5]+i[2]*n[9]+i[3]*n[13],e[2]=i[0]*n[2]+i[1]*n[6]+i[2]*n[10]+i[3]*n[14],e[3]=i[0]*n[3]+i[1]*n[7]+i[2]*n[11]+i[3]*n[15],e[4]=i[4]*n[0]+i[5]*n[4]+i[6]*n[8]+i[7]*n[12],e[5]=i[4]*n[1]+i[5]*n[5]+i[6]*n[9]+i[7]*n[13],e[6]=i[4]*n[2]+i[5]*n[6]+i[6]*n[10]+i[7]*n[14],e[7]=i[4]*n[3]+i[5]*n[7]+i[6]*n[11]+i[7]*n[15],e[8]=i[8]*n[0]+i[9]*n[4]+i[10]*n[8]+i[11]*n[12],e[9]=i[8]*n[1]+i[9]*n[5]+i[10]*n[9]+i[11]*n[13],e[10]=i[8]*n[2]+i[9]*n[6]+i[10]*n[10]+i[11]*n[14],e[11]=i[8]*n[3]+i[9]*n[7]+i[10]*n[11]+i[11]*n[15],e[12]=i[12]*n[0]+i[13]*n[4]+i[14]*n[8]+i[15]*n[12],e[13]=i[12]*n[1]+i[13]*n[5]+i[14]*n[9]+i[15]*n[13],e[14]=i[12]*n[2]+i[13]*n[6]+i[14]*n[10]+i[15]*n[14],e[15]=i[12]*n[3]+i[13]*n[7]+i[14]*n[11]+i[15]*n[15],this.fromArray(e)},translate:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[12]=s[0]*e+s[4]*i+s[8]*n+s[12],s[13]=s[1]*e+s[5]*i+s[9]*n+s[13],s[14]=s[2]*e+s[6]*i+s[10]*n+s[14],s[15]=s[3]*e+s[7]*i+s[11]*n+s[15],this},translateXYZ:function(t,e,i){var n=this.val;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this},scale:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[0]=s[0]*e,s[1]=s[1]*e,s[2]=s[2]*e,s[3]=s[3]*e,s[4]=s[4]*i,s[5]=s[5]*i,s[6]=s[6]*i,s[7]=s[7]*i,s[8]=s[8]*n,s[9]=s[9]*n,s[10]=s[10]*n,s[11]=s[11]*n,this},scaleXYZ:function(t,e,i){var n=this.val;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this},makeRotationAxis:function(t,e){var i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,o=t.y,a=t.z,h=s*r,l=s*o;return this.fromArray([h*r+i,h*o-n*a,h*a+n*o,0,h*o+n*a,l*o+i,l*a-n*r,0,h*a-n*o,l*a+n*r,s*a*a+i,0,0,0,0,1]),this},rotate:function(t,e){var i=this.val,n=e.x,s=e.y,r=e.z,o=Math.sqrt(n*n+s*s+r*r);if(Math.abs(o)<1e-6)return null;n*=o=1/o,s*=o,r*=o;var a=Math.sin(t),h=Math.cos(t),l=1-h,u=i[0],c=i[1],d=i[2],f=i[3],p=i[4],g=i[5],v=i[6],m=i[7],y=i[8],x=i[9],T=i[10],w=i[11],E=n*n*l+h,_=s*n*l+r*a,A=r*n*l-s*a,b=n*s*l-r*a,S=s*s*l+h,C=r*s*l+n*a,M=n*r*l+s*a,O=s*r*l-n*a,P=r*r*l+h;return i[0]=u*E+p*_+y*A,i[1]=c*E+g*_+x*A,i[2]=d*E+v*_+T*A,i[3]=f*E+m*_+w*A,i[4]=u*b+p*S+y*C,i[5]=c*b+g*S+x*C,i[6]=d*b+v*S+T*C,i[7]=f*b+m*S+w*C,i[8]=u*M+p*O+y*P,i[9]=c*M+g*O+x*P,i[10]=d*M+v*O+T*P,i[11]=f*M+m*O+w*P,this},rotateX:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this},rotateY:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this},rotateZ:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this},fromRotationTranslation:function(t,e){var i=this.val,n=t.x,s=t.y,r=t.z,o=t.w,a=n+n,h=s+s,l=r+r,u=n*a,c=n*h,d=n*l,f=s*h,p=s*l,g=r*l,v=o*a,m=o*h,y=o*l;return i[0]=1-(f+g),i[1]=c+y,i[2]=d-m,i[3]=0,i[4]=c-y,i[5]=1-(u+g),i[6]=p+v,i[7]=0,i[8]=d+m,i[9]=p-v,i[10]=1-(u+f),i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this},fromQuat:function(t){var e=this.val,i=t.x,n=t.y,s=t.z,r=t.w,o=i+i,a=n+n,h=s+s,l=i*o,u=i*a,c=i*h,d=n*a,f=n*h,p=s*h,g=r*o,v=r*a,m=r*h;return e[0]=1-(d+p),e[1]=u+m,e[2]=c-v,e[3]=0,e[4]=u-m,e[5]=1-(l+p),e[6]=f+g,e[7]=0,e[8]=c+v,e[9]=f-g,e[10]=1-(l+d),e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},frustum:function(t,e,i,n,s,r){var o=this.val,a=1/(e-t),h=1/(n-i),l=1/(s-r);return o[0]=2*s*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*s*h,o[6]=0,o[7]=0,o[8]=(e+t)*a,o[9]=(n+i)*h,o[10]=(r+s)*l,o[11]=-1,o[12]=0,o[13]=0,o[14]=r*s*2*l,o[15]=0,this},perspective:function(t,e,i,n){var s=this.val,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this},perspectiveLH:function(t,e,i,n){var s=this.val;return s[0]=2*i/t,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/e,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-n/(i-n),s[11]=1,s[12]=0,s[13]=0,s[14]=i*n/(i-n),s[15]=0,this},ortho:function(t,e,i,n,s,r){var o=this.val,a=t-e,h=i-n,l=s-r;return a=0===a?a:1/a,h=0===h?h:1/h,l=0===l?l:1/l,o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this},lookAt:function(t,e,i){var n=this.val,s=t.x,r=t.y,o=t.z,a=i.x,h=i.y,l=i.z,u=e.x,c=e.y,d=e.z;if(Math.abs(s-u)<1e-6&&Math.abs(r-c)<1e-6&&Math.abs(o-d)<1e-6)return this.identity();var f=s-u,p=r-c,g=o-d,v=1/Math.sqrt(f*f+p*p+g*g),m=h*(g*=v)-l*(p*=v),y=l*(f*=v)-a*g,x=a*p-h*f;(v=Math.sqrt(m*m+y*y+x*x))?(m*=v=1/v,y*=v,x*=v):(m=0,y=0,x=0);var T=p*x-g*y,w=g*m-f*x,E=f*y-p*m;return(v=Math.sqrt(T*T+w*w+E*E))?(T*=v=1/v,w*=v,E*=v):(T=0,w=0,E=0),n[0]=m,n[1]=T,n[2]=f,n[3]=0,n[4]=y,n[5]=w,n[6]=p,n[7]=0,n[8]=x,n[9]=E,n[10]=g,n[11]=0,n[12]=-(m*s+y*r+x*o),n[13]=-(T*s+w*r+E*o),n[14]=-(f*s+p*r+g*o),n[15]=1,this},yawPitchRoll:function(t,e,i){this.zero(),s.zero(),r.zero();var n=this.val,o=s.val,a=r.val,h=Math.sin(i),l=Math.cos(i);return n[10]=1,n[15]=1,n[0]=l,n[1]=h,n[4]=-h,n[5]=l,h=Math.sin(e),l=Math.cos(e),o[0]=1,o[15]=1,o[5]=l,o[10]=l,o[9]=-h,o[6]=h,h=Math.sin(t),l=Math.cos(t),a[5]=1,a[15]=1,a[0]=l,a[2]=-h,a[8]=h,a[10]=l,this.multiplyLocal(s),this.multiplyLocal(r),this},setWorldMatrix:function(t,e,i,n,o){return this.yawPitchRoll(t.y,t.x,t.z),s.scaling(i.x,i.y,i.z),r.xyz(e.x,e.y,e.z),this.multiplyLocal(s),this.multiplyLocal(r),void 0!==n&&this.multiplyLocal(n),void 0!==o&&this.multiplyLocal(o),this}}),s=new n,r=new n;t.exports=n},function(t,e,i){var n=i(0),s=i(169),r=i(330),o=new Int8Array([1,2,0]),a=new Float32Array([0,0,0]),h=new s(1,0,0),l=new s(0,1,0),u=new s,c=new r,d=new n({initialize:function(t,e,i,n){"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},rotationTo:function(t,e){var i=t.x*e.x+t.y*e.y+t.z*e.z;return i<-.999999?(u.copy(h).cross(t).length()<1e-6&&u.copy(l).cross(t),u.normalize(),this.setAxisAngle(u,Math.PI)):i>.999999?(this.x=0,this.y=0,this.z=0,this.w=1,this):(u.copy(t).cross(e),this.x=u.x,this.y=u.y,this.z=u.z,this.w=1+i,this.normalize())},setAxes:function(t,e,i){var n=c.val;return n[0]=e.x,n[3]=e.y,n[6]=e.z,n[1]=i.x,n[4]=i.y,n[7]=i.z,n[2]=-t.x,n[5]=-t.y,n[8]=-t.z,this.fromMat3(c).normalize()},identity:function(){return this.x=0,this.y=0,this.z=0,this.w=1,this},setAxisAngle:function(t,e){e*=.5;var i=Math.sin(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=Math.cos(e),this},multiply:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,o=t.y,a=t.z,h=t.w;return this.x=e*h+s*r+i*a-n*o,this.y=i*h+s*o+n*r-e*a,this.z=n*h+s*a+e*o-i*r,this.w=s*h-e*r-i*o-n*a,this},slerp:function(t,e){var i=this.x,n=this.y,s=this.z,r=this.w,o=t.x,a=t.y,h=t.z,l=t.w,u=i*o+n*a+s*h+r*l;u<0&&(u=-u,o=-o,a=-a,h=-h,l=-l);var c=1-e,d=e;if(1-u>1e-6){var f=Math.acos(u),p=Math.sin(f);c=Math.sin((1-e)*f)/p,d=Math.sin(e*f)/p}return this.x=c*i+d*o,this.y=c*n+d*a,this.z=c*s+d*h,this.w=c*r+d*l,this},invert:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n,r=s?1/s:0;return this.x=-t*r,this.y=-e*r,this.z=-i*r,this.w=n*r,this},conjugate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},rotateX:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+s*r,this.y=i*o+n*r,this.z=n*o-i*r,this.w=s*o-e*r,this},rotateY:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o-n*r,this.y=i*o+s*r,this.z=n*o+e*r,this.w=s*o-i*r,this},rotateZ:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+i*r,this.y=i*o-e*r,this.z=n*o+s*r,this.w=s*o-n*r,this},calculateW:function(){var t=this.x,e=this.y,i=this.z;return this.w=-Math.sqrt(1-t*t-e*e-i*i),this},fromMat3:function(t){var e,i=t.val,n=i[0]+i[4]+i[8];if(n>0)e=Math.sqrt(n+1),this.w=.5*e,e=.5/e,this.x=(i[7]-i[5])*e,this.y=(i[2]-i[6])*e,this.z=(i[3]-i[1])*e;else{var s=0;i[4]>i[0]&&(s=1),i[8]>i[3*s+s]&&(s=2);var r=o[s],h=o[r];e=Math.sqrt(i[3*s+s]-i[3*r+r]-i[3*h+h]+1),a[s]=.5*e,e=.5/e,a[r]=(i[3*r+s]+i[3*s+r])*e,a[h]=(i[3*h+s]+i[3*s+h])*e,this.x=a[0],this.y=a[1],this.z=a[2],this.w=(i[3*h+r]-i[3*r+h])*e}return this}});t.exports=d},function(t,e,i){var n=i(334),s=i(27),r=i(10),o=i(164);t.exports=function(t){var e=t.config;if((e.customEnvironment||e.canvas)&&e.renderType===r.AUTO)throw new Error("Must set explicit renderType in custom environment");if(!e.customEnvironment&&!e.canvas&&e.renderType!==r.HEADLESS)if(e.renderType===r.CANVAS||e.renderType!==r.CANVAS&&!o.webGL){if(!o.canvas)throw new Error("Cannot create Canvas or WebGL context, aborting.");e.renderType=r.CANVAS}else e.renderType=r.WEBGL;e.antialias||s.disableSmoothing();var a,h,l=t.scale.baseSize,u=l.width,c=l.height;e.canvas?(t.canvas=e.canvas,t.canvas.width=u,t.canvas.height=c):t.canvas=s.create(t,u,c,e.renderType),e.canvasStyle&&(t.canvas.style=e.canvasStyle),e.antialias||n.setCrisp(t.canvas),e.renderType!==r.HEADLESS&&(a=i(500),h=i(503),e.renderType===r.WEBGL?t.renderer=new h(t):(t.renderer=new a(t),t.context=t.renderer.gameContext))}},function(t,e){t.exports={setCrisp:function(t){return["optimizeSpeed","-moz-crisp-edges","-o-crisp-edges","-webkit-optimize-contrast","optimize-contrast","crisp-edges","pixelated"].forEach(function(e){t.style["image-rendering"]=e}),t.style.msInterpolationMode="nearest-neighbor",t},setBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}}},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_FS","","precision mediump float;","","uniform sampler2D uMainSampler;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main()","{"," vec4 texture = texture2D(uMainSampler, outTexCoord);"," vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);"," vec4 color = texture;",""," if (outTintEffect == 0.0)"," {"," // Multiply texture tint"," color = texture * texel;"," }"," else if (outTintEffect == 1.0)"," {"," // Solid color + texture alpha"," color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);"," color.a = texture.a * texel.a;"," }"," else if (outTintEffect == 2.0)"," {"," // Solid color, no texture"," color = texel;"," }",""," gl_FragColor = color;","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_VS","","precision mediump float;","","uniform mat4 uProjectionMatrix;","uniform mat4 uViewMatrix;","uniform mat4 uModelMatrix;","","attribute vec2 inPosition;","attribute vec2 inTexCoord;","attribute float inTintEffect;","attribute vec4 inTint;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main ()","{"," gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);",""," outTexCoord = inTexCoord;"," outTint = inTint;"," outTintEffect = inTintEffect;","}","",""].join("\n")},function(t,e,i){var n=i(10);t.exports=function(t){var e=t.config;if(!e.hideBanner){var i="WebGL";e.renderType===n.CANVAS?i="Canvas":e.renderType===n.HEADLESS&&(i="Headless");var s,r=e.audio,o=t.device.audio;if(s=!o.webAudio||r&&r.disableWebAudio?r&&r.noAudio||!o.webAudio&&!o.audioData?"No Audio":"HTML5 Audio":"Web Audio",t.device.browser.ie)window.console&&console.log("Phaser v"+n.VERSION+" / https://phaser.io");else{var a,h="",l=[h];Array.isArray(e.bannerBackgroundColor)?(e.bannerBackgroundColor.forEach(function(t){h=h.concat("%c "),l.push("background: "+t),a=t}),l[l.length-1]="color: "+e.bannerTextColor+"; background: "+a):(h=h.concat("%c "),l.push("color: "+e.bannerTextColor+"; background: "+e.bannerBackgroundColor)),l.push("background: #fff"),e.gameTitle&&(h=h.concat(e.gameTitle),e.gameVersion&&(h=h.concat(" v"+e.gameVersion)),e.hidePhaser||(h=h.concat(" / "))),e.hidePhaser||(h=h.concat("Phaser v"+n.VERSION+" ("+i+" | "+s+")")),h=h.concat(" %c "+e.gameURL),l[0]=h,console.log.apply(console,l)}}}},function(t,e,i){var n=i(0),s=i(6),r=i(1),o=i(339),a=new n({initialize:function(t,e){this.game=t,this.raf=new o,this.started=!1,this.running=!1,this.minFps=s(e,"min",5),this.targetFps=s(e,"target",60),this._min=1e3/this.minFps,this._target=1e3/this.targetFps,this.actualFps=this.targetFps,this.nextFpsUpdate=0,this.framesThisSecond=0,this.callback=r,this.forceSetTimeOut=s(e,"forceSetTimeOut",!1),this.time=0,this.startTime=0,this.lastTime=0,this.frame=0,this.inFocus=!0,this._pauseTime=0,this._coolDown=0,this.delta=0,this.deltaIndex=0,this.deltaHistory=[],this.deltaSmoothingMax=s(e,"deltaHistory",10),this.panicMax=s(e,"panicMax",120),this.rawDelta=0,this.now=0,this.smoothStep=s(e,"smoothStep",!0)},blur:function(){this.inFocus=!1},focus:function(){this.inFocus=!0,this.resetDelta()},pause:function(){this._pauseTime=window.performance.now()},resume:function(){this.resetDelta(),this.startTime+=this.time-this._pauseTime},resetDelta:function(){var t=window.performance.now();this.time=t,this.lastTime=t,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0;for(var e=0;e0||!this.inFocus)&&(this._coolDown--,r=Math.min(r,this._target)),r>this._min&&(r=n[i],r=Math.min(r,this._min)),n[i]=r,this.deltaIndex++,this.deltaIndex>s&&(this.deltaIndex=0),o=0;for(var a=0;athis.nextFpsUpdate&&(this.actualFps=.25*this.framesThisSecond+.75*this.actualFps,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0),this.framesThisSecond++;var h=o/this._target;this.callback(t,o,h),this.lastTime=t,this.frame++},tick:function(){this.step()},sleep:function(){this.running&&(this.raf.stop(),this.running=!1)},wake:function(t){this.running?this.sleep():t&&(this.startTime+=-this.lastTime+(this.lastTime+window.performance.now())),this.raf.start(this.step.bind(this),this.useRAF),this.running=!0,this.step()},getDuration:function(){return Math.round(this.lastTime-this.startTime)/1e3},getDurationMS:function(){return Math.round(this.lastTime-this.startTime)},stop:function(){return this.running=!1,this.started=!1,this.raf.stop(),this},destroy:function(){this.stop(),this.callback=r,this.raf=null,this.game=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(1),r=new n({initialize:function(){this.isRunning=!1,this.callback=s,this.tick=0,this.isSetTimeOut=!1,this.timeOutID=null,this.lastTime=0,this.target=0;var t=this;this.step=function e(){var i=window.performance.now();t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.requestAnimationFrame(e)},this.stepTimeout=function e(){var i=Date.now(),n=Math.min(Math.max(2*t.target+t.tick-i,0),t.target);t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.setTimeout(e,n)}},start:function(t,e,i){this.isRunning||(this.callback=t,this.isSetTimeOut=e,this.target=i,this.isRunning=!0,this.timeOutID=e?window.setTimeout(this.stepTimeout,0):window.requestAnimationFrame(this.step))},stop:function(){this.isRunning=!1,this.isSetTimeOut?clearTimeout(this.timeOutID):window.cancelAnimationFrame(this.timeOutID)},destroy:function(){this.stop(),this.callback=s}});t.exports=r},function(t,e,i){var n=i(19);t.exports=function(t){var e,i=t.events;void 0!==document.hidden?e="visibilitychange":["webkit","moz","ms"].forEach(function(t){void 0!==document[t+"Hidden"]&&(document.hidden=function(){return document[t+"Hidden"]},e=t+"visibilitychange")});e&&document.addEventListener(e,function(t){document.hidden||"pause"===t.type?i.emit(n.HIDDEN):i.emit(n.VISIBLE)},!1),window.onblur=function(){i.emit(n.BLUR)},window.onfocus=function(){i.emit(n.FOCUS)},window.focus&&t.config.autoFocus&&window.focus()}},function(t,e,i){var n=i(342),s=i(27),r=i(6);t.exports=function(t){var e=r(t,"data",[]),i=r(t,"canvas",null),o=r(t,"palette",n),a=r(t,"pixelWidth",1),h=r(t,"pixelHeight",a),l=r(t,"resizeCanvas",!0),u=r(t,"clearCanvas",!0),c=r(t,"preRender",null),d=r(t,"postRender",null),f=Math.floor(Math.abs(e[0].length*a)),p=Math.floor(Math.abs(e.length*h));i||(i=s.create2D(this,f,p),l=!1,u=!1),l&&(i.width=f,i.height=p);var g=i.getContext("2d");u&&g.clearRect(0,0,f,p),c&&c(i,g);for(var v=0;vi;)n-=i;ni.length-2?i.length-1:r+1],c=i[r>i.length-3?i.length-1:r+2];return e.set(n(a,h.x,l.x,u.x,c.x),n(a,h.y,l.y,u.y,c.y))},toJSON:function(){for(var t=[],e=0;e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}},function(t,e,i){var n=i(112);t.exports=function(t){if("complete"!==document.readyState&&"interactive"!==document.readyState){var e=function(){document.removeEventListener("deviceready",e,!0),document.removeEventListener("DOMContentLoaded",e,!0),window.removeEventListener("load",e,!0),t()};document.body?n.cordova?document.addEventListener("deviceready",e,!1):(document.addEventListener("DOMContentLoaded",e,!0),window.addEventListener("load",e,!0)):window.setTimeout(e,20)}else t()}},function(t,e,i){var n=i(172);t.exports=function(t,e){var i=window.screen,s=!!i&&(i.orientation||i.mozOrientation||i.msOrientation);if(s&&"string"==typeof s.type)return s.type;if("string"==typeof s)return s;if(i)return i.height>i.width?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if("number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return n.ORIENTATION.PORTRAIT;if(window.matchMedia("(orientation: landscape)").matches)return n.ORIENTATION.LANDSCAPE}return e>t?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE}},function(t,e){t.exports={NO_CENTER:0,CENTER_BOTH:1,CENTER_HORIZONTALLY:2,CENTER_VERTICALLY:3}},function(t,e){t.exports={LANDSCAPE:"landscape-primary",PORTRAIT:"portrait-primary"}},function(t,e){t.exports={NONE:0,WIDTH_CONTROLS_HEIGHT:1,HEIGHT_CONTROLS_WIDTH:2,FIT:3,ENVELOP:4,RESIZE:5}},function(t,e){t.exports={NO_ZOOM:1,ZOOM_2X:2,ZOOM_4X:4,MAX_ZOOM:-1}},function(t,e){t.exports=function(t){var e;return""!==t&&("string"==typeof t?e=document.getElementById(t):t&&1===t.nodeType&&(e=t)),e||(e=document.body),e}},function(t,e){t.exports=function(t){var e="";try{window.DOMParser?e=(new DOMParser).parseFromString(t,"text/xml"):(e=new ActiveXObject("Microsoft.XMLDOM")).loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null}},function(t,e,i){var n=i(0),s=i(174),r=i(11),o=i(54),a=i(19),h=i(361),l=i(362),u=i(363),c=i(364),d=i(30),f=i(328),p=new n({initialize:function(t,e){this.game=t,this.scaleManager,this.canvas,this.config=e,this.enabled=!0,this.events=new r,this.isOver=!0,this.defaultCursor="",this.keyboard=e.inputKeyboard?new h(this):null,this.mouse=e.inputMouse?new l(this):null,this.touch=e.inputTouch?new c(this):null,this.pointers=[],this.pointersTotal=e.inputActivePointers,e.inputTouch&&1===this.pointersTotal&&(this.pointersTotal=2);for(var i=0;i<=this.pointersTotal;i++){var n=new u(this,i);n.smoothFactor=e.inputSmoothFactor,this.pointers.push(n)}this.mousePointer=e.inputMouse?this.pointers[0]:null,this.activePointer=this.pointers[0],this.globalTopOnly=!0,this.time=0,this._tempPoint={x:0,y:0},this._tempHitTest=[],this._tempMatrix=new d,this._tempMatrix2=new d,this._tempSkip=!1,this.mousePointerContainer=[this.mousePointer],t.events.once(a.BOOT,this.boot,this)},boot:function(){this.canvas=this.game.canvas,this.scaleManager=this.game.scale,this.events.emit(o.MANAGER_BOOT),this.game.events.on(a.PRE_RENDER,this.preRender,this),this.game.events.once(a.DESTROY,this.destroy,this)},setCanvasOver:function(t){this.isOver=!0,this.events.emit(o.GAME_OVER,t)},setCanvasOut:function(t){this.isOver=!1,this.events.emit(o.GAME_OUT,t)},preRender:function(){var t=this.game.loop.now,e=this.game.loop.delta,i=this.game.scene.getScenes(!0,!0);this.time=t,this.events.emit(o.MANAGER_UPDATE);for(var n=0;n10&&(t=10-this.pointersTotal);for(var i=0;i-1&&e.preventDefault()}},this.onKeyUp=function(e){if(!e.defaultPrevented&&t.enabled&&t.manager){t.queue.push(e),t.manager.useQueue||t.manager.events.emit(o.MANAGER_PROCESS);var i=e.altKey||e.ctrlKey||e.shiftKey||e.metaKey;t.preventDefault&&!i&&t.captures.indexOf(e.keyCode)>-1&&e.preventDefault()}};var e=this.target;e&&(e.addEventListener("keydown",this.onKeyDown,!1),e.addEventListener("keyup",this.onKeyUp,!1),this.enabled=!0)},stopListeners:function(){var t=this.target;t.removeEventListener("keydown",this.onKeyDown,!1),t.removeEventListener("keyup",this.onKeyUp,!1),this.enabled=!1},postUpdate:function(){this.queue=[]},addCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},removeCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},clearCaptures:function(){this.captures=[],this.preventDefault=!1},destroy:function(){this.stopListeners(),this.clearCaptures(),this.queue=[],this.manager.game.events.off(r.POST_RENDER,this.postUpdate,this),this.target=null,this.enabled=!1,this.manager=null}});t.exports=l},function(t,e,i){var n=i(0),s=i(164),r=i(54),o=i(0),a=new n({initialize:function(t){this.manager=t,this.capture=!0,this.enabled=!1,this.target,this.locked=!1,this.onMouseMove=o,this.onMouseDown=o,this.onMouseUp=o,this.onMouseDownWindow=o,this.onMouseUpWindow=o,this.onMouseOver=o,this.onMouseOut=o,this.onMouseWheel=o,this.pointerLockChange=o,t.events.once(r.MANAGER_BOOT,this.boot,this)},boot:function(){var t=this.manager.config;this.enabled=t.inputMouse,this.target=t.inputMouseEventTarget,this.capture=t.inputMouseCapture,this.target?"string"==typeof this.target&&(this.target=document.getElementById(this.target)):this.target=this.manager.game.canvas,t.disableContextMenu&&this.disableContextMenu(),this.enabled&&this.target&&this.startListeners()},disableContextMenu:function(){return document.body.addEventListener("contextmenu",function(t){return t.preventDefault(),!1}),this},requestPointerLock:function(){if(s.pointerLock){var t=this.target;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock()}},releasePointerLock:function(){s.pointerLock&&(document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock())},startListeners:function(){var t=this,e=this.manager.canvas,i=window&&window.focus&&this.manager.game.config.autoFocus;this.onMouseMove=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseMove(e),t.capture&&e.preventDefault())},this.onMouseDown=function(n){i&&window.focus(),!n.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseDown(n),t.capture&&n.target===e&&n.preventDefault())},this.onMouseDownWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseDown(i)},this.onMouseUp=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseUp(i),t.capture&&i.target===e&&i.preventDefault())},this.onMouseUpWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseUp(i)},this.onMouseOver=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOver(e)},this.onMouseOut=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOut(e)},this.onMouseWheel=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.onMouseWheel(e)};var n=this.target;if(n){var r={passive:!0},o={passive:!1};n.addEventListener("mousemove",this.onMouseMove,this.capture?o:r),n.addEventListener("mousedown",this.onMouseDown,this.capture?o:r),n.addEventListener("mouseup",this.onMouseUp,this.capture?o:r),n.addEventListener("mouseover",this.onMouseOver,this.capture?o:r),n.addEventListener("mouseout",this.onMouseOut,this.capture?o:r),n.addEventListener("wheel",this.onMouseWheel,this.capture?o:r),window&&this.manager.game.config.inputWindowEvents&&(window.addEventListener("mousedown",this.onMouseDownWindow,o),window.addEventListener("mouseup",this.onMouseUpWindow,o)),s.pointerLock&&(this.pointerLockChange=function(e){var i=t.target;t.locked=document.pointerLockElement===i||document.mozPointerLockElement===i||document.webkitPointerLockElement===i,t.manager.onPointerLockChange(e)},document.addEventListener("pointerlockchange",this.pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this.pointerLockChange,!0)),this.enabled=!0}},stopListeners:function(){var t=this.target;t.removeEventListener("mousemove",this.onMouseMove),t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("mouseup",this.onMouseUp),t.removeEventListener("mouseover",this.onMouseOver),t.removeEventListener("mouseout",this.onMouseOut),window&&(window.removeEventListener("mousedown",this.onMouseDownWindow),window.removeEventListener("mouseup",this.onMouseUpWindow)),s.pointerLock&&(document.removeEventListener("pointerlockchange",this.pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this.pointerLockChange,!0))},destroy:function(){this.stopListeners(),this.target=null,this.enabled=!1,this.manager=null}});t.exports=a},function(t,e,i){var n=i(312),s=i(0),r=i(53),o=i(140),a=i(322),h=i(3),l=new s({initialize:function(t,e){this.manager=t,this.id=e,this.event,this.downElement,this.upElement,this.camera=null,this.button=0,this.buttons=0,this.position=new h,this.prevPosition=new h,this.midPoint=new h(-1,-1),this.velocity=new h,this.angle=0,this.distance=0,this.smoothFactor=0,this.motionFactor=.2,this.worldX=0,this.worldY=0,this.moveTime=0,this.downX=0,this.downY=0,this.downTime=0,this.upX=0,this.upY=0,this.upTime=0,this.primaryDown=!1,this.isDown=!1,this.wasTouch=!1,this.wasCanceled=!1,this.movementX=0,this.movementY=0,this.identifier=0,this.pointerId=null,this.active=0===e,this.locked=!1,this.deltaX=0,this.deltaY=0,this.deltaZ=0},updateWorldPoint:function(t){var e=this.x,i=this.y;1!==t.resolution&&(e+=t._x,i+=t._y);var n=t.getWorldPoint(e,i);return this.worldX=n.x,this.worldY=n.y,this},positionToCamera:function(t,e){return t.getWorldPoint(this.x,this.y,e)},updateMotion:function(){var t=this.position.x,e=this.position.y,i=this.midPoint.x,s=this.midPoint.y;if(t!==i||e!==s){var r=a(this.motionFactor,i,t),h=a(this.motionFactor,s,e);o(r,t,.1)&&(r=t),o(h,e,.1)&&(h=e),this.midPoint.set(r,h);var l=t-r,u=e-h;this.velocity.set(l,u),this.angle=n(r,h,t,e),this.distance=Math.sqrt(l*l+u*u)}},up:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=t.timeStamp),this.isDown=!1,this.wasTouch=!1},down:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=t.timeStamp),this.isDown=!0,this.wasTouch=!1},move:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.locked&&(this.movementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.movementY=t.movementY||t.mozMovementY||t.webkitMovementY||0),this.moveTime=t.timeStamp,this.wasTouch=!1},wheel:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ,this.wasTouch=!1},touchstart:function(t,e){t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.active=!0,this.buttons=1,this.event=e,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=e.timeStamp,this.isDown=!0,this.wasTouch=!0,this.wasCanceled=!1,this.updateMotion()},touchmove:function(t,e){this.event=e,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.moveTime=e.timeStamp,this.wasTouch=!0,this.updateMotion()},touchend:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!1,this.active=!1,this.updateMotion()},touchcancel:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!0,this.active=!1},noButtonDown:function(){return 0===this.buttons},leftButtonDown:function(){return!!(1&this.buttons)},rightButtonDown:function(){return!!(2&this.buttons)},middleButtonDown:function(){return!!(4&this.buttons)},backButtonDown:function(){return!!(8&this.buttons)},forwardButtonDown:function(){return!!(16&this.buttons)},leftButtonReleased:function(){return 0===this.button&&!this.isDown},rightButtonReleased:function(){return 2===this.button&&!this.isDown},middleButtonReleased:function(){return 1===this.button&&!this.isDown},backButtonReleased:function(){return 3===this.button&&!this.isDown},forwardButtonReleased:function(){return 4===this.button&&!this.isDown},getDistance:function(){return this.isDown?r(this.downX,this.downY,this.x,this.y):r(this.downX,this.downY,this.upX,this.upY)},getDistanceX:function(){return this.isDown?Math.abs(this.downX-this.x):Math.abs(this.downX-this.upX)},getDistanceY:function(){return this.isDown?Math.abs(this.downY-this.y):Math.abs(this.downY-this.upY)},getDuration:function(){return this.isDown?this.manager.time-this.downTime:this.upTime-this.downTime},getAngle:function(){return this.isDown?n(this.downX,this.downY,this.x,this.y):n(this.downX,this.downY,this.upX,this.upY)},getInterpolatedPosition:function(t,e){void 0===t&&(t=10),void 0===e&&(e=[]);for(var i=this.prevPosition.x,n=this.prevPosition.y,s=this.position.x,r=this.position.y,o=0;o0&&this.parentSize.height>0&&this.displaySize.setParent(this.parentSize),this.refresh()),t.events.on(a.PRE_STEP,this.step,this),t.events.once(a.DESTROY,this.destroy,this),this.startListeners()},parseConfig:function(t){this.getParent(t),this.getParentBounds();var e=t.width,i=t.height,s=t.scaleMode,r=t.resolution,o=t.zoom,a=t.autoRound;if("string"==typeof e){var h=this.parentSize.width;0===h&&(h=window.innerWidth);var l=parseInt(e,10)/100;e=Math.floor(h*l)}if("string"==typeof i){var c=this.parentSize.height;0===c&&(c=window.innerHeight);var d=parseInt(i,10)/100;i=Math.floor(c*d)}this.resolution=1,this.scaleMode=s,this.autoRound=a,this.autoCenter=t.autoCenter,this.resizeInterval=t.resizeInterval,a&&(e=Math.floor(e),i=Math.floor(i)),this.gameSize.setSize(e,i),o===n.ZOOM.MAX_ZOOM&&(o=this.getMaxZoom()),this.zoom=o,1!==o&&(this._resetZoom=!0),this.baseSize.setSize(e*r,i*r),a&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),t.minWidth>0&&this.displaySize.setMin(t.minWidth*o,t.minHeight*o),t.maxWidth>0&&this.displaySize.setMax(t.maxWidth*o,t.maxHeight*o),this.displaySize.setSize(e,i),this.orientation=u(e,i)},getParent:function(t){var e=t.parent;if(null!==e){if(this.parent=l(e),this.parentIsWindow=this.parent===document.body,t.expandParent&&t.scaleMode!==n.SCALE_MODE.NONE){var i=this.parent.getBoundingClientRect();(this.parentIsWindow||0===i.height)&&(document.documentElement.style.height="100%",document.body.style.height="100%",i=this.parent.getBoundingClientRect(),this.parentIsWindow||0!==i.height||(this.parent.style.overflow="hidden",this.parent.style.width="100%",this.parent.style.height="100%"))}t.fullscreenTarget&&!this.fullscreenTarget&&(this.fullscreenTarget=l(t.fullscreenTarget))}},getParentBounds:function(){if(!this.parent)return!1;var t=this.parentSize,e=this.parent.getBoundingClientRect();this.parentIsWindow&&this.game.device.os.iOS&&(e.height=h(!0));var i=this.resolution,n=e.width*i,s=e.height*i;return(t.width!==n||t.height!==s)&&(t.setSize(n,s),!0)},lockOrientation:function(t){var e=screen.lockOrientation||screen.mozLockOrientation||screen.msLockOrientation;return!!e&&e(t)},setParentSize:function(t,e){return this.parentSize.setSize(t,e),this.refresh()},setGameSize:function(t,e){var i=this.autoRound,n=this.resolution;i&&(t=Math.floor(t),e=Math.floor(e));var s=this.width,r=this.height;return this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),i&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t,e),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height,this.refresh(s,r)},resize:function(t,e){var i=this.zoom,n=this.resolution,s=this.autoRound;s&&(t=Math.floor(t),e=Math.floor(e));var r=this.width,o=this.height;this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),s&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t*i*n,e*i*n),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height;var a=this.canvas.style,h=t*i,l=e*i;return s&&(h=Math.floor(h),l=Math.floor(l)),h===t&&l===e||(a.width=h+"px",a.height=l+"px"),this.refresh(r,o)},setZoom:function(t){return this.zoom=t,this._resetZoom=!0,this.refresh()},setMaxZoom:function(){return this.zoom=this.getMaxZoom(),this._resetZoom=!0,this.refresh()},refresh:function(t,e){void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.updateScale(),this.updateBounds(),this.updateOrientation(),this.displayScale.set(this.baseSize.width/this.canvasBounds.width,this.baseSize.height/this.canvasBounds.height);var i=this.game.domContainer;if(i){this.baseSize.setCSS(i);var n=this.canvas.style,s=i.style;s.transform="scale("+this.displaySize.width/this.baseSize.width+","+this.displaySize.height/this.baseSize.height+")",s.marginLeft=n.marginLeft,s.marginTop=n.marginTop}return this.emit(o.RESIZE,this.gameSize,this.baseSize,this.displaySize,this.resolution,t,e),this},updateOrientation:function(){if(this._checkOrientation){this._checkOrientation=!1;var t=u(this.width,this.height);t!==this.orientation&&(this.orientation=t,this.emit(o.ORIENTATION_CHANGE,t))}},updateScale:function(){var t,e,i=this.canvas.style,s=this.gameSize.width,r=this.gameSize.height,o=this.zoom,a=this.autoRound;this.scaleMode===n.SCALE_MODE.NONE?(this.displaySize.setSize(s*o*1,r*o*1),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this._resetZoom&&(i.width=t+"px",i.height=e+"px",this._resetZoom=!1)):this.scaleMode===n.SCALE_MODE.RESIZE?(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),this.gameSize.setSize(this.displaySize.width,this.displaySize.height),this.baseSize.setSize(1*this.displaySize.width,1*this.displaySize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this.canvas.width=t,this.canvas.height=e):(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),i.width=t+"px",i.height=e+"px"),this.getParentBounds(),this.updateCenter()},getMaxZoom:function(){var t=p(this.parentSize.width,this.gameSize.width,0,!0),e=p(this.parentSize.height,this.gameSize.height,0,!0);return Math.max(Math.min(t,e),1)},updateCenter:function(){var t=this.autoCenter;if(t!==n.CENTER.NO_CENTER){var e=this.canvas,i=e.style,s=e.getBoundingClientRect(),r=s.width,o=s.height,a=Math.floor((this.parentSize.width-r)/2),h=Math.floor((this.parentSize.height-o)/2);t===n.CENTER.CENTER_HORIZONTALLY?h=0:t===n.CENTER.CENTER_VERTICALLY&&(a=0),i.marginLeft=a+"px",i.marginTop=h+"px"}},updateBounds:function(){var t=this.canvasBounds,e=this.canvas.getBoundingClientRect();t.x=e.left+(window.pageXOffset||0)-(document.documentElement.clientLeft||0),t.y=e.top+(window.pageYOffset||0)-(document.documentElement.clientTop||0),t.width=e.width,t.height=e.height},transformX:function(t){return(t-this.canvasBounds.left)*this.displayScale.x},transformY:function(t){return(t-this.canvasBounds.top)*this.displayScale.y},startFullscreen:function(t){void 0===t&&(t={navigationUI:"hide"});var e=this.fullscreen;if(e.available){if(!e.active){var i,n=this.getFullscreenTarget();(i=e.keyboard?n[e.request](Element.ALLOW_KEYBOARD_INPUT):n[e.request](t))?i.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)):e.active?this.fullscreenSuccessHandler():this.fullscreenErrorHandler()}}else this.emit(o.FULLSCREEN_UNSUPPORTED)},fullscreenSuccessHandler:function(){this.getParentBounds(),this.refresh(),this.emit(o.ENTER_FULLSCREEN)},fullscreenErrorHandler:function(t){this.removeFullscreenTarget(),this.emit(o.FULLSCREEN_FAILED,t)},getFullscreenTarget:function(){if(!this.fullscreenTarget){var t=document.createElement("div");t.style.margin="0",t.style.padding="0",t.style.width="100%",t.style.height="100%",this.fullscreenTarget=t,this._createdFullscreenTarget=!0}this._createdFullscreenTarget&&(this.canvas.parentNode.insertBefore(this.fullscreenTarget,this.canvas),this.fullscreenTarget.appendChild(this.canvas));return this.fullscreenTarget},removeFullscreenTarget:function(){if(this._createdFullscreenTarget){var t=this.fullscreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.canvas,t),e.removeChild(t)}}},stopFullscreen:function(){var t=this.fullscreen;if(!t.available)return this.emit(o.FULLSCREEN_UNSUPPORTED),!1;t.active&&document[t.cancel](),this.removeFullscreenTarget(),this.getParentBounds(),this.emit(o.LEAVE_FULLSCREEN),this.refresh()},toggleFullscreen:function(t){this.fullscreen.active?this.stopFullscreen():this.startFullscreen(t)},startListeners:function(){var t=this,e=this.listeners;if(e.orientationChange=function(){t._checkOrientation=!0,t.dirty=!0},e.windowResize=function(){t.dirty=!0},window.addEventListener("orientationchange",e.orientationChange,!1),window.addEventListener("resize",e.windowResize,!1),this.fullscreen.available){e.fullScreenChange=function(e){return t.onFullScreenChange(e)},e.fullScreenError=function(e){return t.onFullScreenError(e)};["webkit","moz",""].forEach(function(t){document.addEventListener(t+"fullscreenchange",e.fullScreenChange,!1),document.addEventListener(t+"fullscreenerror",e.fullScreenError,!1)}),document.addEventListener("MSFullscreenChange",e.fullScreenChange,!1),document.addEventListener("MSFullscreenError",e.fullScreenError,!1)}},onFullScreenChange:function(){document.fullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||this.stopFullscreen()},onFullScreenError:function(){this.removeFullscreenTarget()},step:function(t,e){this.parent&&(this._lastCheck+=e,(this.dirty||this._lastCheck>this.resizeInterval)&&(this.getParentBounds()&&this.refresh(),this.dirty=!1,this._lastCheck=0))},stopListeners:function(){var t=this.listeners;window.removeEventListener("orientationchange",t.orientationChange,!1),window.removeEventListener("resize",t.windowResize,!1);["webkit","moz",""].forEach(function(e){document.removeEventListener(e+"fullscreenchange",t.fullScreenChange,!1),document.removeEventListener(e+"fullscreenerror",t.fullScreenError,!1)}),document.removeEventListener("MSFullscreenChange",t.fullScreenChange,!1),document.removeEventListener("MSFullscreenError",t.fullScreenError,!1)},destroy:function(){this.removeAllListeners(),this.stopListeners(),this.game=null,this.canvas=null,this.canvasBounds=null,this.parent=null,this.fullscreenTarget=null,this.parentSize.destroy(),this.gameSize.destroy(),this.baseSize.destroy(),this.displaySize.destroy()},isFullscreen:{get:function(){return this.fullscreen.active}},width:{get:function(){return this.gameSize.width}},height:{get:function(){return this.gameSize.height}},isPortrait:{get:function(){return this.orientation===n.ORIENTATION.PORTRAIT}},isLandscape:{get:function(){return this.orientation===n.ORIENTATION.LANDSCAPE}},isGamePortrait:{get:function(){return this.height>this.width}},isGameLandscape:{get:function(){return this.width>this.height}}});t.exports=v},function(t,e,i){var n=i(23),s=i(0),r=i(91),o=i(3),a=new s({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=0),void 0===n&&(n=null),this._width=t,this._height=e,this._parent=n,this.aspectMode=i,this.aspectRatio=0===e?1:t/e,this.minWidth=0,this.minHeight=0,this.maxWidth=Number.MAX_VALUE,this.maxHeight=Number.MAX_VALUE,this.snapTo=new o},setAspectMode:function(t){return void 0===t&&(t=0),this.aspectMode=t,this.setSize(this._width,this._height)},setSnap:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.snapTo.set(t,e),this.setSize(this._width,this._height)},setParent:function(t){return this._parent=t,this.setSize(this._width,this._height)},setMin:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.minWidth=n(t,0,this.maxWidth),this.minHeight=n(e,0,this.maxHeight),this.setSize(this._width,this._height)},setMax:function(t,e){return void 0===t&&(t=Number.MAX_VALUE),void 0===e&&(e=t),this.maxWidth=n(t,this.minWidth,Number.MAX_VALUE),this.maxHeight=n(e,this.minHeight,Number.MAX_VALUE),this.setSize(this._width,this._height)},setSize:function(t,e){switch(void 0===t&&(t=0),void 0===e&&(e=t),this.aspectMode){case a.NONE:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height;break;case a.WIDTH_CONTROLS_HEIGHT:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(this._width*(1/this.aspectRatio),!1);break;case a.HEIGHT_CONTROLS_WIDTH:this._height=this.getNewHeight(r(e,this.snapTo.y)),this._width=this.getNewWidth(this._height*this.aspectRatio,!1);break;case a.FIT:this.constrain(t,e,!0);break;case a.ENVELOP:this.constrain(t,e,!1)}return this},setAspectRatio:function(t){return this.aspectRatio=t,this.setSize(this._width,this._height)},resize:function(t,e){return this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height,this},getNewWidth:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minWidth,this.maxWidth),e&&this._parent&&t>this._parent.width&&(t=Math.max(this.minWidth,this._parent.width)),t},getNewHeight:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minHeight,this.maxHeight),e&&this._parent&&t>this._parent.height&&(t=Math.max(this.minHeight,this._parent.height)),t},constrain:function(t,e,i){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=!0),t=this.getNewWidth(t),e=this.getNewHeight(e);var n=this.snapTo,s=0===e?1:t/e;return i&&this.aspectRatio>s||!i&&this.aspectRatio0&&(t=(e=r(e,n.y))*this.aspectRatio)):(i&&this.aspectRatios)&&(t=(e=r(e,n.y))*this.aspectRatio,n.x>0&&(e=(t=r(t,n.x))*(1/this.aspectRatio))),this._width=t,this._height=e,this},fitTo:function(t,e){return this.constrain(t,e,!0)},envelop:function(t,e){return this.constrain(t,e,!1)},setWidth:function(t){return this.setSize(t,this._height)},setHeight:function(t){return this.setSize(this._width,t)},toString:function(){return"[{ Size (width="+this._width+" height="+this._height+" aspectRatio="+this.aspectRatio+" aspectMode="+this.aspectMode+") }]"},setCSS:function(t){t&&t.style&&(t.style.width=this._width+"px",t.style.height=this._height+"px")},copy:function(t){return t.setAspectMode(this.aspectMode),t.aspectRatio=this.aspectRatio,t.setSize(this.width,this.height)},destroy:function(){this._parent=null,this.snapTo=null},width:{get:function(){return this._width},set:function(t){this.setSize(t,this._height)}},height:{get:function(){return this._height},set:function(t){this.setSize(this._width,t)}}});a.NONE=0,a.WIDTH_CONTROLS_HEIGHT=1,a.HEIGHT_CONTROLS_WIDTH=2,a.FIT=3,a.ENVELOP=4,t.exports=a},function(t,e,i){var n=i(0),s=i(119),r=i(22),o=i(19),a=i(6),h=i(80),l=i(1),u=i(369),c=i(175),d=new n({initialize:function(t,e){if(this.game=t,this.keys={},this.scenes=[],this._pending=[],this._start=[],this._queue=[],this._data={},this.isProcessing=!1,this.isBooted=!1,this.customViewports=0,e){Array.isArray(e)||(e=[e]);for(var i=0;i-1&&(delete this.keys[n],this.scenes.splice(i,1),this._start.indexOf(n)>-1&&(i=this._start.indexOf(n),this._start.splice(i,1)),e.sys.destroy())}return this},bootScene:function(t){var e,i=t.sys,n=i.settings;t.init&&(t.init.call(t,n.data),n.status=s.INIT,n.isTransition&&i.events.emit(r.TRANSITION_INIT,n.transitionFrom,n.transitionDuration)),i.load&&(e=i.load).reset(),e&&t.preload?(t.preload.call(t),0===e.list.size?this.create(t):(n.status=s.LOADING,e.once(h.COMPLETE,this.loadComplete,this),e.start())):this.create(t)},loadComplete:function(t){var e=t.scene;this.game.sound&&this.game.sound.onBlurPausedSounds&&this.game.sound.unlock(),this.create(e)},payloadComplete:function(t){this.bootScene(t.scene)},update:function(t,e){this.processQueue(),this.isProcessing=!0;for(var i=this.scenes.length-1;i>=0;i--){var n=this.scenes[i].sys;n.settings.status>s.START&&n.settings.status<=s.RUNNING&&n.step(t,e)}},render:function(t){for(var e=0;e=s.LOADING&&i.settings.status0){var i=this.getScene(t);this.scenes.splice(e,1),this.scenes.unshift(i)}}return this},moveDown:function(t){if(this.isProcessing)this._queue.push({op:"moveDown",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e>0){var i=e-1,n=this.getScene(t),s=this.getAt(i);this.scenes[e]=s,this.scenes[i]=n}}return this},moveUp:function(t){if(this.isProcessing)this._queue.push({op:"moveUp",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e=r.x&&t=r.y&&e=r.x&&t=r.y&&e-1){var o=this.context.getImageData(t,e,1,1);o.data[0]=i,o.data[1]=n,o.data[2]=s,o.data[3]=r,this.context.putImageData(o,t,e)}return this},putData:function(t,e,i,n,s,r,o){return void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=t.width),void 0===o&&(o=t.height),this.context.putImageData(t,e,i,n,s,r,o),this},getData:function(t,e,i,n){return t=s(Math.floor(t),0,this.width-1),e=s(Math.floor(e),0,this.height-1),i=s(i,1,this.width-t),n=s(n,1,this.height-e),this.context.getImageData(t,e,i,n)},getPixel:function(t,e,i){i||(i=new r);var n=this.getIndex(t,e);if(n>-1){var s=this.data,o=s[n+0],a=s[n+1],h=s[n+2],l=s[n+3];i.setTo(o,a,h,l)}return i},getPixels:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=i),t=Math.abs(Math.round(t)),e=Math.abs(Math.round(e));for(var o=s(t,0,this.width),a=s(t+i,0,this.width),h=s(e,0,this.height),l=s(e+n,0,this.height),u=new r,c=[],d=h;d0)&&(!!n.prototype.pause.call(this)&&(this.currentConfig.seek=this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0),this.stopAndReleaseAudioTag(),this.emit(r.PAUSE,this),!0)))},resume:function(){return!this.manager.isLocked(this,"resume")&&(!(this.startTime>0)&&(!!n.prototype.resume.call(this)&&(!!this.pickAndPlayAudioTag()&&(this.emit(r.RESUME,this),!0))))},stop:function(){return!this.manager.isLocked(this,"stop")&&(!!n.prototype.stop.call(this)&&(this.stopAndReleaseAudioTag(),this.emit(r.STOP,this),!0))},pickAndPlayAudioTag:function(){if(!this.pickAudioTag())return this.reset(),!1;var t=this.currentConfig.seek,e=this.currentConfig.delay,i=(this.currentMarker?this.currentMarker.start:0)+t;return this.previousTime=i,this.audio.currentTime=i,this.applyConfig(),0===e?(this.startTime=0,this.audio.paused&&this.playCatchPromise()):(this.startTime=window.performance.now()+1e3*e,this.audio.paused||this.audio.pause()),this.resetConfig(),!0},pickAudioTag:function(){if(this.audio)return!0;for(var t=0;t0)this.startTime=n-this.manager.loopEndOffset?(this.audio.currentTime=i+Math.max(0,s-n),s=this.audio.currentTime):s=n)return this.reset(),this.stopAndReleaseAudioTag(),void this.emit(r.COMPLETE,this);this.previousTime=s}},destroy:function(){n.prototype.destroy.call(this),this.tags=null,this.audio&&this.stopAndReleaseAudioTag()},updateMute:function(){this.audio&&(this.audio.muted=this.currentConfig.mute||this.manager.mute)},updateVolume:function(){this.audio&&(this.audio.volume=this.currentConfig.volume*this.manager.volume)},calculateRate:function(){n.prototype.calculateRate.call(this),this.audio&&(this.audio.playbackRate=this.totalRate)},mute:{get:function(){return this.currentConfig.mute},set:function(t){this.currentConfig.mute=t,this.manager.isLocked(this,"mute",t)||(this.updateMute(),this.emit(r.MUTE,this,t))}},setMute:function(t){return this.mute=t,this},volume:{get:function(){return this.currentConfig.volume},set:function(t){this.currentConfig.volume=t,this.manager.isLocked(this,"volume",t)||(this.updateVolume(),this.emit(r.VOLUME,this,t))}},setVolume:function(t){return this.volume=t,this},rate:{get:function(){return this.currentConfig.rate},set:function(t){this.currentConfig.rate=t,this.manager.isLocked(this,r.RATE,t)||(this.calculateRate(),this.emit(r.RATE,this,t))}},setRate:function(t){return this.rate=t,this},detune:{get:function(){return this.currentConfig.detune},set:function(t){this.currentConfig.detune=t,this.manager.isLocked(this,r.DETUNE,t)||(this.calculateRate(),this.emit(r.DETUNE,this,t))}},setDetune:function(t){return this.detune=t,this},seek:{get:function(){return this.isPlaying?this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0):this.isPaused?this.currentConfig.seek:0},set:function(t){this.manager.isLocked(this,"seek",t)||this.startTime>0||(this.isPlaying||this.isPaused)&&(t=Math.min(Math.max(0,t),this.duration),this.isPlaying?(this.previousTime=t,this.audio.currentTime=t):this.isPaused&&(this.currentConfig.seek=t),this.emit(r.SEEK,this,t))}},setSeek:function(t){return this.seek=t,this},loop:{get:function(){return this.currentConfig.loop},set:function(t){this.currentConfig.loop=t,this.manager.isLocked(this,"loop",t)||(this.audio&&(this.audio.loop=t),this.emit(r.LOOP,this,t))}},setLoop:function(t){return this.loop=t,this}});t.exports=o},function(t,e,i){var n=i(121),s=i(0),r=i(11),o=i(379),a=i(1),h=new s({Extends:r,initialize:function(t){r.call(this),this.game=t,this.sounds=[],this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.pauseOnBlur=!0,this.locked=!1},add:function(t,e){var i=new o(this,t,e);return this.sounds.push(i),i},addAudioSprite:function(t,e){var i=this.add(t,e);return i.spritemap={},i},play:function(t,e){return!1},playAudioSprite:function(t,e,i){return!1},remove:function(t){return n.prototype.remove.call(this,t)},removeByKey:function(t){return n.prototype.removeByKey.call(this,t)},pauseAll:a,resumeAll:a,stopAll:a,update:a,setRate:a,setDetune:a,setMute:a,setVolume:a,forEachActiveSound:function(t,e){n.prototype.forEachActiveSound.call(this,t,e)},destroy:function(){n.prototype.destroy.call(this)}});t.exports=h},function(t,e,i){var n=i(122),s=i(0),r=i(11),o=i(18),a=new s({Extends:r,initialize:function(t,e,i){void 0===i&&(i={}),r.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=0,this.totalDuration=0,this.config=o({mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},i),this.currentConfig=this.config,this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.seek=0,this.loop=!1,this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!1},updateMarker:function(t){return!1},removeMarker:function(t){return null},play:function(t,e){return!1},pause:function(){return!1},resume:function(){return!1},stop:function(){return!1},destroy:function(){this.manager.remove(this),n.prototype.destroy.call(this)}});t.exports=a},function(t,e,i){var n=i(381),s=i(121),r=i(0),o=i(59),a=i(382),h=new r({Extends:s,initialize:function(t){this.context=this.createAudioContext(t),this.masterMuteNode=this.context.createGain(),this.masterVolumeNode=this.context.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(this.context.destination),this.destination=this.masterMuteNode,this.locked="suspended"===this.context.state&&("ontouchstart"in window||"onclick"in window),s.call(this,t),this.locked&&this.unlock()},createAudioContext:function(t){var e=t.config.audio;return e&&e.context?(e.context.resume(),e.context):new AudioContext},setAudioContext:function(t){return this.context&&this.context.close(),this.masterMuteNode&&this.masterMuteNode.disconnect(),this.masterVolumeNode&&this.masterVolumeNode.disconnect(),this.context=t,this.masterMuteNode=t.createGain(),this.masterVolumeNode=t.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(t.destination),this.destination=this.masterMuteNode,this},add:function(t,e){var i=new a(this,t,e);return this.sounds.push(i),i},decodeAudio:function(t,e){var i;i=Array.isArray(t)?t:[{key:t,data:e}];for(var s=this.game.cache.audio,r=i.length,a=0;a>4,u[h++]=(15&i)<<4|s>>2,u[h++]=(3&s)<<6|63&r;return l}},function(t,e,i){var n=i(122),s=i(0),r=i(59),o=new s({Extends:n,initialize:function(t,e,i){if(void 0===i&&(i={}),this.audioBuffer=t.game.cache.audio.get(e),!this.audioBuffer)throw new Error('There is no audio asset with key "'+e+'" in the audio cache');this.source=null,this.loopSource=null,this.muteNode=t.context.createGain(),this.volumeNode=t.context.createGain(),this.playTime=0,this.startTime=0,this.loopTime=0,this.rateUpdates=[],this.hasEnded=!1,this.hasLooped=!1,this.muteNode.connect(this.volumeNode),this.volumeNode.connect(t.destination),this.duration=this.audioBuffer.duration,this.totalDuration=this.audioBuffer.duration,n.call(this,t,e,i)},play:function(t,e){return!!n.prototype.play.call(this,t,e)&&(this.stopAndRemoveBufferSource(),this.createAndStartBufferSource(),this.emit(r.PLAY,this),!0)},pause:function(){return!(this.manager.context.currentTime-1;r--)n[s][r]=t[r][s]}return n}},function(t,e){function i(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function n(t,e){return te?1:0}var s=function(t,e,r,o,a){for(void 0===r&&(r=0),void 0===o&&(o=t.length-1),void 0===a&&(a=n);o>r;){if(o-r>600){var h=o-r+1,l=e-r+1,u=Math.log(h),c=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*c*(h-c)/h)*(l-h/2<0?-1:1),f=Math.max(r,Math.floor(e-l*c/h+d)),p=Math.min(o,Math.floor(e+(h-l)*c/h+d));s(t,e,f,p,a)}var g=t[e],v=r,m=o;for(i(t,r,e),a(t[o],g)>0&&i(t,r,o);v0;)m--}0===a(t[r],g)?i(t,r,m):i(t,++m,o),m<=e&&(r=m+1),e<=m&&(o=m-1)}};t.exports=s},function(t,e,i){var n=i(6),s=i(110),r=function(t,e,i){for(var n=[],s=0;s0?s.delayedPlay(d,r,o):s.load(r)}return t}},function(t,e,i){var n=i(13);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.right,e.right)-s,a=Math.max(t.bottom,e.bottom)-r;return i.setTo(s,r,o,a)}},function(t,e,i){var n=i(0),s=i(12),r=i(948),o=i(14),a=i(7),h=i(173),l=i(22),u=i(329),c=new n({Extends:o,Mixins:[s.AlphaSingle,s.BlendMode,s.Depth,s.Origin,s.ScrollFactor,s.Transform,s.Visible,r],initialize:function(t,e,i,n,s,r){o.call(this,t,"DOMElement"),this.parent=t.sys.game.domContainer,this.cache=t.sys.cache.html,this.node,this.transformOnly=!1,this.skewX=0,this.skewY=0,this.rotate3d=new u,this.rotate3dAngle="deg",this.width=0,this.height=0,this.displayWidth=0,this.displayHeight=0,this.handler=this.dispatchNativeEvent.bind(this),this.setPosition(e,i),"string"==typeof n?"#"===n[0]?this.setElement(n.substr(1),s,r):this.createElement(n,s,r):n&&this.setElement(n,s,r),t.sys.events.on(l.SLEEP,this.handleSceneEvent,this),t.sys.events.on(l.WAKE,this.handleSceneEvent,this)},handleSceneEvent:function(t){var e=this.node,i=e.style;e&&(i.display=t.settings.visible?"block":"none")},setSkew:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.skewX=t,this.skewY=e,this},setPerspective:function(t){return this.parent.style.perspective=t+"px",this},perspective:{get:function(){return parseFloat(this.parent.style.perspective)},set:function(t){this.parent.style.perspective=t+"px"}},addListener:function(t){if(this.node){t=t.split(" ");for(var e=0;e>>16,y=(65280&p)>>>8,x=255&p,c.strokeStyle="rgba("+m+","+y+","+x+","+d+")",c.lineWidth=v,T+=3;break;case n.FILL_STYLE:g=l[T+1],f=l[T+2],m=(16711680&g)>>>16,y=(65280&g)>>>8,x=255&g,c.fillStyle="rgba("+m+","+y+","+x+","+f+")",T+=2;break;case n.BEGIN_PATH:c.beginPath();break;case n.CLOSE_PATH:c.closePath();break;case n.FILL_PATH:h||c.fill();break;case n.STROKE_PATH:h||c.stroke();break;case n.FILL_RECT:h?c.rect(l[T+1],l[T+2],l[T+3],l[T+4]):c.fillRect(l[T+1],l[T+2],l[T+3],l[T+4]),T+=4;break;case n.FILL_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.fill(),T+=6;break;case n.STROKE_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.stroke(),T+=6;break;case n.LINE_TO:c.lineTo(l[T+1],l[T+2]),T+=2;break;case n.MOVE_TO:c.moveTo(l[T+1],l[T+2]),T+=2;break;case n.LINE_FX_TO:c.lineTo(l[T+1],l[T+2]),T+=5;break;case n.MOVE_FX_TO:c.moveTo(l[T+1],l[T+2]),T+=5;break;case n.SAVE:c.save();break;case n.RESTORE:c.restore();break;case n.TRANSLATE:c.translate(l[T+1],l[T+2]),T+=2;break;case n.SCALE:c.scale(l[T+1],l[T+2]),T+=2;break;case n.ROTATE:c.rotate(l[T+1]),T+=1;break;case n.GRADIENT_FILL_STYLE:T+=5;break;case n.GRADIENT_LINE_STYLE:T+=6;break;case n.SET_TEXTURE:T+=2}c.restore()}}},function(t,e,i){var n=i(0),s=i(2),r=new n({initialize:function(t,e,i,n,r){if("object"==typeof t){var o=t;t=s(o,"x",0),e=s(o,"y",0),i=s(o,"power",0),n=s(o,"epsilon",100),r=s(o,"gravity",50)}else void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=100),void 0===r&&(r=50);this.x=t,this.y=e,this.active=!0,this._gravity=r,this._power=0,this._epsilon=0,this.power=i,this.epsilon=n},update:function(t,e){var i=this.x-t.x,n=this.y-t.y,s=i*i+n*n;if(0!==s){var r=Math.sqrt(s);s0},resetPosition:function(){this.x=0,this.y=0},fire:function(t,e){var i=this.emitter;this.frame=i.getFrame(),i.emitZone&&i.emitZone.getPoint(this),void 0===t?(i.follow&&(this.x+=i.follow.x+i.followOffset.x),this.x+=i.x.onEmit(this,"x")):this.x+=t,void 0===e?(i.follow&&(this.y+=i.follow.y+i.followOffset.y),this.y+=i.y.onEmit(this,"y")):this.y+=e,this.life=i.lifespan.onEmit(this,"lifespan"),this.lifeCurrent=this.life,this.lifeT=0;var n=i.speedX.onEmit(this,"speedX"),o=i.speedY?i.speedY.onEmit(this,"speedY"):n;if(i.radial){var a=s(i.angle.onEmit(this,"angle"));this.velocityX=Math.cos(a)*Math.abs(n),this.velocityY=Math.sin(a)*Math.abs(o)}else if(i.moveTo){var h=i.moveToX.onEmit(this,"moveToX"),l=i.moveToY?i.moveToY.onEmit(this,"moveToY"):h,u=Math.atan2(l-this.y,h-this.x),c=r(this.x,this.y,h,l)/(this.life/1e3);this.velocityX=Math.cos(u)*c,this.velocityY=Math.sin(u)*c}else this.velocityX=n,this.velocityY=o;i.acceleration&&(this.accelerationX=i.accelerationX.onEmit(this,"accelerationX"),this.accelerationY=i.accelerationY.onEmit(this,"accelerationY")),this.maxVelocityX=i.maxVelocityX.onEmit(this,"maxVelocityX"),this.maxVelocityY=i.maxVelocityY.onEmit(this,"maxVelocityY"),this.delayCurrent=i.delay.onEmit(this,"delay"),this.scaleX=i.scaleX.onEmit(this,"scaleX"),this.scaleY=i.scaleY?i.scaleY.onEmit(this,"scaleY"):this.scaleX,this.angle=i.rotate.onEmit(this,"rotate"),this.rotation=s(this.angle),this.bounce=i.bounce.onEmit(this,"bounce"),this.alpha=i.alpha.onEmit(this,"alpha"),this.tint=i.tint.onEmit(this,"tint")},computeVelocity:function(t,e,i,n){var s=this.velocityX,r=this.velocityY,o=this.accelerationX,a=this.accelerationY,h=this.maxVelocityX,l=this.maxVelocityY;s+=t.gravityX*i,r+=t.gravityY*i,o&&(s+=o*i),a&&(r+=a*i),s>h?s=h:s<-h&&(s=-h),r>l?r=l:r<-l&&(r=-l),this.velocityX=s,this.velocityY=r;for(var u=0;ue.right&&t.collideRight&&(this.x=e.right,this.velocityX*=i),this.ye.bottom&&t.collideBottom&&(this.y=e.bottom,this.velocityY*=i)},update:function(t,e,i){if(this.delayCurrent>0)return this.delayCurrent-=t,!1;var n=this.emitter,r=1-this.lifeCurrent/this.life;return this.lifeT=r,this.computeVelocity(n,t,e,i),this.x+=this.velocityX*e,this.y+=this.velocityY*e,n.bounds&&this.checkBounds(n),n.deathZone&&n.deathZone.willKill(this)?(this.lifeCurrent=0,!0):(this.scaleX=n.scaleX.onUpdate(this,"scaleX",r,this.scaleX),n.scaleY?this.scaleY=n.scaleY.onUpdate(this,"scaleY",r,this.scaleY):this.scaleY=this.scaleX,this.angle=n.rotate.onUpdate(this,"rotate",r,this.angle),this.rotation=s(this.angle),this.alpha=n.alpha.onUpdate(this,"alpha",r,this.alpha),this.tint=n.tint.onUpdate(this,"tint",r,this.tint),this.lifeCurrent-=t,this.lifeCurrent<=0)}});t.exports=o},function(t,e,i){var n=i(52),s=i(0),r=i(12),o=i(398),a=i(399),h=i(965),l=i(2),u=i(180),c=i(400),d=i(104),f=i(396),p=i(401),g=i(13),v=i(125),m=i(3),y=i(58),x=new s({Mixins:[r.BlendMode,r.Mask,r.ScrollFactor,r.Visible],initialize:function(t,e){this.manager=t,this.texture=t.texture,this.frames=[t.defaultFrame],this.defaultFrame=t.defaultFrame,this.configFastMap=["active","blendMode","collideBottom","collideLeft","collideRight","collideTop","deathCallback","deathCallbackScope","emitCallback","emitCallbackScope","follow","frequency","gravityX","gravityY","maxParticles","name","on","particleBringToTop","particleClass","radial","timeScale","trackVisible","visible"],this.configOpMap=["accelerationX","accelerationY","angle","alpha","bounce","delay","lifespan","maxVelocityX","maxVelocityY","moveToX","moveToY","quantity","rotate","scaleX","scaleY","speedX","speedY","tint","x","y"],this.name="",this.particleClass=f,this.x=new h(e,"x",0,!0),this.y=new h(e,"y",0,!0),this.radial=!0,this.gravityX=0,this.gravityY=0,this.acceleration=!1,this.accelerationX=new h(e,"accelerationX",0,!0),this.accelerationY=new h(e,"accelerationY",0,!0),this.maxVelocityX=new h(e,"maxVelocityX",1e4,!0),this.maxVelocityY=new h(e,"maxVelocityY",1e4,!0),this.speedX=new h(e,"speedX",0,!0),this.speedY=new h(e,"speedY",0,!0),this.moveTo=!1,this.moveToX=new h(e,"moveToX",0,!0),this.moveToY=new h(e,"moveToY",0,!0),this.bounce=new h(e,"bounce",0,!0),this.scaleX=new h(e,"scaleX",1),this.scaleY=new h(e,"scaleY",1),this.tint=new h(e,"tint",4294967295),this.alpha=new h(e,"alpha",1),this.lifespan=new h(e,"lifespan",1e3,!0),this.angle=new h(e,"angle",{min:0,max:360},!0),this.rotate=new h(e,"rotate",0),this.emitCallback=null,this.emitCallbackScope=null,this.deathCallback=null,this.deathCallbackScope=null,this.maxParticles=0,this.quantity=new h(e,"quantity",1,!0),this.delay=new h(e,"delay",0,!0),this.frequency=0,this.on=!0,this.particleBringToTop=!0,this.timeScale=1,this.emitZone=null,this.deathZone=null,this.bounds=null,this.collideLeft=!0,this.collideRight=!0,this.collideTop=!0,this.collideBottom=!0,this.active=!0,this.visible=!0,this.blendMode=n.NORMAL,this.follow=null,this.followOffset=new m,this.trackVisible=!1,this.currentFrame=0,this.randomFrame=!0,this.frameQuantity=1,this.dead=[],this.alive=[],this._counter=0,this._frameCounter=0,e&&this.fromJSON(e)},fromJSON:function(t){if(!t)return this;var e=0,i="";for(e=0;e0&&this.getParticleCount()===this.maxParticles},onParticleEmit:function(t,e){return void 0===t?(this.emitCallback=null,this.emitCallbackScope=null):"function"==typeof t&&(this.emitCallback=t,e&&(this.emitCallbackScope=e)),this},onParticleDeath:function(t,e){return void 0===t?(this.deathCallback=null,this.deathCallbackScope=null):"function"==typeof t&&(this.deathCallback=t,e&&(this.deathCallbackScope=e)),this},killAll:function(){for(var t=this.dead,e=this.alive;e.length>0;)t.push(e.pop());return this},forEachAlive:function(t,e){for(var i=this.alive,n=i.length,s=0;s0){var u=this.deathCallback,c=this.deathCallbackScope;for(o=h-1;o>=0;o--){var d=a[o];s.splice(d.index,1),r.push(d.particle),u&&u.call(c,d.particle),d.particle.resetPosition()}}this.on&&(0===this.frequency?this.emitParticle():this.frequency>0&&(this._counter-=e,this._counter<=0&&(this.emitParticle(),this._counter=this.frequency-Math.abs(this._counter))))},depthSortCallback:function(t,e){return t.y-e.y}});t.exports=x},function(t,e,i){var n=new(i(0))({initialize:function(t,e){this.source=t,this.killOnEnter=e},willKill:function(t){var e=this.source.contains(t.x,t.y);return e&&this.killOnEnter||!e&&!this.killOnEnter}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s){void 0===n&&(n=!1),void 0===s&&(s=!0),this.source=t,this.points=[],this.quantity=e,this.stepRate=i,this.yoyo=n,this.counter=-1,this.seamless=s,this._length=0,this._direction=0,this.updateSource()},updateSource:function(){if(this.points=this.source.getPoints(this.quantity,this.stepRate),this.seamless){var t=this.points[0],e=this.points[this.points.length-1];t.x===e.x&&t.y===e.y&&this.points.pop()}var i=this._length;return this._length=this.points.length,this._lengththis._length&&(this.counter=this._length-1),this},changeSource:function(t){return this.source=t,this.updateSource()},getPoint:function(t){0===this._direction?(this.counter++,this.counter>=this._length&&(this.yoyo?(this._direction=1,this.counter=this._length-1):this.counter=0)):(this.counter--,-1===this.counter&&(this.yoyo?(this._direction=0,this.counter=0):this.counter=this._length-1));var e=this.points[this.counter];e&&(t.x=e.x,t.y=e.y)}});t.exports=n},function(t,e){t.exports=function(t,e){for(var i=0;i0&&(s=-h.PI2+s%h.PI2):s>h.PI2?s=h.PI2:s<0&&(s=h.PI2+s%h.PI2);for(var u,c=[a+Math.cos(n)*i,l+Math.sin(n)*i];e<1;)u=s*e+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),e+=t;return u=s+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),c.push(a+Math.cos(n)*i,l+Math.sin(n)*i),this.pathIndexes=o(c),this.pathData=c,this}});t.exports=u},function(t,e,i){var n=i(0),s=i(994),r=i(64),o=i(13),a=i(31),h=new n({Extends:a,Mixins:[s],initialize:function(t,e,i,n,s,r){void 0===e&&(e=0),void 0===i&&(i=0),a.call(this,t,"Curve",n),this._smoothness=32,this._curveBounds=new o,this.closePath=!1,this.setPosition(e,i),void 0!==s&&this.setFillStyle(s,r),this.updateData()},smoothness:{get:function(){return this._smoothness},set:function(t){this._smoothness=t,this.updateData()}},setSmoothness:function(t){return this._smoothness=t,this.updateData()},updateData:function(){var t=this._curveBounds,e=this._smoothness;this.geom.getBounds(t,e),this.setSize(t.width,t.height),this.updateDisplayOrigin();for(var i=[],n=this.geom.getPoints(e),s=0;sc+v)){var m=g.getPoint((u-c)/v);o.push(m);break}c+=v}return o}},function(t,e,i){var n=i(57),s=i(56);t.exports=function(t){for(var e=t.points,i=0,r=0;r0&&r.push(i([0,0],n[0])),e=0;e1&&r.push(i([0,0],n[n.length-1])),t.setTo(r)}},function(t,e,i){var n=i(0),s=i(13),r=i(31),o=i(1015),a=new n({Extends:r,Mixins:[o],initialize:function(t,e,i,n,o,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=128),void 0===o&&(o=128),r.call(this,t,"Rectangle",new s(0,0,n,o)),this.setPosition(e,i),this.setSize(n,o),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},updateData:function(){var t=[],e=this.geom,i=this._tempLine;return e.getLineA(i),t.push(i.x1,i.y1,i.x2,i.y2),e.getLineB(i),t.push(i.x2,i.y2),e.getLineC(i),t.push(i.x2,i.y2),e.getLineD(i),t.push(i.x2,i.y2),this.pathData=t,this}});t.exports=a},function(t,e,i){var n=i(1018),s=i(0),r=i(64),o=i(31),a=new s({Extends:o,Mixins:[n],initialize:function(t,e,i,n,s,r,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=5),void 0===s&&(s=32),void 0===r&&(r=64),o.call(this,t,"Star",null),this._points=n,this._innerRadius=s,this._outerRadius=r,this.setPosition(e,i),this.setSize(2*r,2*r),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},setPoints:function(t){return this._points=t,this.updateData()},setInnerRadius:function(t){return this._innerRadius=t,this.updateData()},setOuterRadius:function(t){return this._outerRadius=t,this.updateData()},points:{get:function(){return this._points},set:function(t){this._points=t,this.updateData()}},innerRadius:{get:function(){return this._innerRadius},set:function(t){this._innerRadius=t,this.updateData()}},outerRadius:{get:function(){return this._outerRadius},set:function(t){this._outerRadius=t,this.updateData()}},updateData:function(){var t=[],e=this._points,i=this._innerRadius,n=this._outerRadius,s=Math.PI/2*3,o=Math.PI/e,a=n,h=n;t.push(a,h+-n);for(var l=0;l=1)return i.x=r.x1,i.y=r.y1,i;var h=s(r),l=s(o),u=s(a),c=(h+l+u)*e,d=0;return ch+l?(d=(c-=h+l)/u,i.x=a.x1+(a.x2-a.x1)*d,i.y=a.y1+(a.y2-a.y1)*d):(d=(c-=h)/l,i.x=o.x1+(o.x2-o.x1)*d,i.y=o.y1+(o.y2-o.y1)*d),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]);var o=t.getLineA(),a=t.getLineB(),h=t.getLineC(),l=n(o),u=n(a),c=n(h),d=l+u+c;e||(e=d/i);for(var f=0;fl+u?(g=(p-=l+u)/c,v.x=h.x1+(h.x2-h.x1)*g,v.y=h.y1+(h.y2-h.y1)*g):(g=(p-=l)/u,v.x=a.x1+(a.x2-a.x1)*g,v.y=a.y1+(a.y2-a.y1)*g),r.push(v)}return r}},function(t,e){t.exports=function(t,e,i){if(!t||"number"==typeof t)return!1;if(t.hasOwnProperty(e))return t[e]=i,!0;if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=t,o=0;o0?(h=this.lightPool.pop()).set(t,e,i,a[0],a[1],a[2],o):h=new s(t,e,i,a[0],a[1],a[2],o),this.lights.push(h),h},removeLight:function(t){var e=this.lights.indexOf(t);return e>=0&&(this.lightPool.push(t),this.lights.splice(e,1)),this},shutdown:function(){for(;this.lights.length>0;)this.lightPool.push(this.lights.pop());this.ambientColor={r:.1,g:.1,b:.1},this.culledLights.length=0,this.lights.length=0},destroy:function(){this.shutdown()}});t.exports=o},function(t,e,i){var n=i(46),s=i(18),r={Circle:i(1081),Ellipse:i(1091),Intersects:i(424),Line:i(1110),Point:i(1132),Polygon:i(1146),Rectangle:i(437),Triangle:i(1176)};r=s(!1,r,n),t.exports=r},function(t,e,i){t.exports={CircleToCircle:i(200),CircleToRectangle:i(201),GetCircleToCircle:i(1101),GetCircleToRectangle:i(1102),GetLineToCircle:i(202),GetLineToRectangle:i(204),GetRectangleIntersection:i(1103),GetRectangleToRectangle:i(1104),GetRectangleToTriangle:i(1105),GetTriangleToCircle:i(1106),GetTriangleToLine:i(429),GetTriangleToTriangle:i(1107),LineToCircle:i(203),LineToLine:i(82),LineToRectangle:i(425),PointToLine:i(433),PointToLineSegment:i(1108),RectangleToRectangle:i(129),RectangleToTriangle:i(426),RectangleToValues:i(1109),TriangleToCircle:i(428),TriangleToLine:i(430),TriangleToTriangle:i(431)}},function(t,e){t.exports=function(t,e){var i=t.x1,n=t.y1,s=t.x2,r=t.y2,o=e.x,a=e.y,h=e.right,l=e.bottom,u=0;if(i>=o&&i<=h&&n>=a&&n<=l||s>=o&&s<=h&&r>=a&&r<=l)return!0;if(i=o){if((u=n+(r-n)*(o-i)/(s-i))>a&&u<=l)return!0}else if(i>h&&s<=h&&(u=n+(r-n)*(h-i)/(s-i))>=a&&u<=l)return!0;if(n=a){if((u=i+(s-i)*(a-n)/(r-n))>=o&&u<=h)return!0}else if(n>l&&r<=l&&(u=i+(s-i)*(l-n)/(r-n))>=o&&u<=h)return!0;return!1}},function(t,e,i){var n=i(82),s=i(47),r=i(205),o=i(427);t.exports=function(t,e){if(e.left>t.right||e.rightt.bottom||e.bottom0}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x,y:t.y}),e.push({x:t.right,y:t.y}),e.push({x:t.right,y:t.bottom}),e.push({x:t.x,y:t.bottom}),e}},function(t,e,i){var n=i(203),s=i(81);t.exports=function(t,e){return!(t.left>e.right||t.righte.bottom||t.bottome.right||t.righte.bottom||t.bottom0||(c=s(e),(d=n(t,c,!0)).length>0)}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x1,y:t.y1}),e.push({x:t.x2,y:t.y2}),e.push({x:t.x3,y:t.y3}),e}},function(t,e){t.exports=function(t,e,i){void 0===i&&(i=1);var n=e.x1,s=e.y1,r=e.x2,o=e.y2,a=t.x,h=t.y,l=(r-n)*(r-n)+(o-s)*(o-s);if(0===l)return!1;var u=((a-n)*(r-n)+(h-s)*(o-s))/l;if(u<0)return Math.sqrt((n-a)*(n-a)+(s-h)*(s-h))<=i;if(u>=0&&u<=1){var c=((s-h)*(r-n)-(n-a)*(o-s))/l;return Math.abs(c)*Math.sqrt(l)<=i}return Math.sqrt((r-a)*(r-a)+(o-h)*(o-h))<=i}},function(t,e,i){var n=i(16),s=i(58),r=i(83);t.exports=function(t){var e=r(t)-n.TAU;return s(e,-Math.PI,Math.PI)}},function(t,e){t.exports=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)}},function(t,e){t.exports=function(t){return t.x*t.x+t.y*t.y}},function(t,e,i){var n=i(13);n.Area=i(1151),n.Ceil=i(1152),n.CeilAll=i(1153),n.CenterOn=i(162),n.Clone=i(1154),n.Contains=i(47),n.ContainsPoint=i(1155),n.ContainsRect=i(438),n.CopyFrom=i(1156),n.Decompose=i(427),n.Equals=i(1157),n.FitInside=i(1158),n.FitOutside=i(1159),n.Floor=i(1160),n.FloorAll=i(1161),n.FromPoints=i(171),n.GetAspectRatio=i(207),n.GetCenter=i(1162),n.GetPoint=i(146),n.GetPoints=i(269),n.GetSize=i(1163),n.Inflate=i(1164),n.Intersection=i(1165),n.MarchingAnts=i(280),n.MergePoints=i(1166),n.MergeRect=i(1167),n.MergeXY=i(1168),n.Offset=i(1169),n.OffsetPoint=i(1170),n.Overlaps=i(1171),n.Perimeter=i(108),n.PerimeterPoint=i(1172),n.Random=i(149),n.RandomOutside=i(1173),n.SameDimensions=i(1174),n.Scale=i(1175),n.Union=i(387),t.exports=n},function(t,e){t.exports=function(t,e){return!(e.width*e.height>t.width*t.height)&&e.x>t.x&&e.xt.x&&e.rightt.y&&e.yt.y&&e.bottom=this.threshold?this.pressed||(this.pressed=!0,this.events.emit(s.BUTTON_DOWN,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_DOWN,i,t,this)):this.pressed&&(this.pressed=!1,this.events.emit(s.BUTTON_UP,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_UP,i,t,this))},destroy:function(){this.pad=null,this.events=null}});t.exports=r},function(t,e,i){var n=i(443),s=i(444),r=i(0),o=i(11),a=i(3),h=new r({Extends:o,initialize:function(t,e){o.call(this),this.manager=t,this.pad=e,this.id=e.id,this.index=e.index;for(var i=[],r=0;r=2&&(this.leftStick.set(r[0].getValue(),r[1].getValue()),s>=4&&this.rightStick.set(r[2].getValue(),r[3].getValue()))},destroy:function(){var t;for(this.removeAllListeners(),this.manager=null,this.pad=null,t=0;t=r;for(i=0;i=r;)this._elapsed-=r,this.step(s)}},step:function(t){var e,i,n=this.bodies.entries,s=n.length;for(e=0;e0){var l=this.tree,u=this.staticTree;for(n=(i=h.entries).length,t=0;t-1&&p>g&&(t.velocity.normalize().scale(g),p=g),t.speed=p},separate:function(t,e,i,n,s){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(n,t.gameObject,e.gameObject))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,s);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h=o.center;if((h.ya.bottom)&&(h.xa.right))return this.separateCircle(t,e,s)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)r.right&&(s=h(o.x,o.y,r.right,r.y)-o.radius):o.y>r.bottom&&(o.xr.right&&(s=h(o.x,o.y,r.right,r.bottom)-o.radius)),s*=-1}else s=t.halfWidth+e.halfWidth-h(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s&&(t.onOverlap||e.onOverlap)&&this.emit(u.OVERLAP,t.gameObject,e.gameObject,t,e),0!==s;var a=t.center.x-e.center.x,l=t.center.y-e.center.y,c=Math.sqrt(Math.pow(a,2)+Math.pow(l,2)),d=(e.center.x-t.center.x)/c||0,f=(e.center.y-t.center.y)/c||0,v=2*(t.velocity.x*d+t.velocity.y*f-e.velocity.x*d-e.velocity.y*f)/(t.mass+e.mass);t.immovable||(t.velocity.x=t.velocity.x-v*t.mass*d,t.velocity.y=t.velocity.y-v*t.mass*f),e.immovable||(e.velocity.x=e.velocity.x+v*e.mass*d,e.velocity.y=e.velocity.y+v*e.mass*f);var m=e.velocity.x-t.velocity.x,y=e.velocity.y-t.velocity.y,x=Math.atan2(y,m),T=this._frameTime;return t.immovable||e.immovable||(s/=2),t.immovable||(t.x+=t.velocity.x*T-s*Math.cos(x),t.y+=t.velocity.y*T-s*Math.sin(x)),e.immovable||(e.x+=e.velocity.x*T+s*Math.cos(x),e.y+=e.velocity.y*T+s*Math.sin(x)),t.velocity.x*=t.bounce.x,t.velocity.y*=t.bounce.y,e.velocity.x*=e.bounce.x,e.velocity.y*=e.bounce.y,(t.onCollide||e.onCollide)&&this.emit(u.COLLIDE,t.gameObject,e.gameObject,t,e),!0},intersects:function(t,e){return t!==e&&(t.isCircle||e.isCircle?t.isCircle?e.isCircle?h(t.center.x,t.center.y,e.center.x,e.center.y)<=t.halfWidth+e.halfWidth:this.circleBodyIntersects(t,e):this.circleBodyIntersects(e,t):!(t.right<=e.position.x||t.bottom<=e.position.y||t.position.x>=e.right||t.position.y>=e.bottom))},circleBodyIntersects:function(t,e){var i=s(t.center.x,e.left,e.right),n=s(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},overlap:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!0)},collide:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!1)},collideObjects:function(t,e,i,n,s,r){var o,a;t.isParent&&void 0===t.physicsType&&(t=t.children.entries),e&&e.isParent&&void 0===e.physicsType&&(e=e.children.entries);var h=Array.isArray(t),l=Array.isArray(e);if(this._total=0,h||l)if(!h&&l)for(o=0;o0},collideHandler:function(t,e,i,n,s,r){if(void 0===e&&t.isParent)return this.collideGroupVsGroup(t,t,i,n,s,r);if(!t||!e)return!1;if(t.body){if(e.body)return this.collideSpriteVsSprite(t,e,i,n,s,r);if(e.isParent)return this.collideSpriteVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideSpriteVsTilemapLayer(t,e,i,n,s,r)}else if(t.isParent){if(e.body)return this.collideSpriteVsGroup(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideGroupVsTilemapLayer(t,e,i,n,s,r)}else if(t.isTilemap){if(e.body)return this.collideSpriteVsTilemapLayer(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsTilemapLayer(e,t,i,n,s,r)}},collideSpriteVsSprite:function(t,e,i,n,s,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,n,s,r)&&(i&&i.call(s,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,n,s,r){var o,h,l,u=t.body;if(0!==e.length&&u&&u.enable)if(this.useTree){var c=this.treeMinMax;c.minX=u.left,c.minY=u.top,c.maxX=u.right,c.maxY=u.bottom;var d=e.physicsType===a.DYNAMIC_BODY?this.tree.search(c):this.staticTree.search(c);for(h=d.length,o=0;oc.baseTileWidth){var d=(c.tileWidth-c.baseTileWidth)*e.scaleX;a-=d,l+=d}c.tileHeight>c.baseTileHeight&&(u+=(c.tileHeight-c.baseTileHeight)*e.scaleY);var f=e.getTilesWithinWorldXY(a,h,l,u);return 0!==f.length&&this.collideSpriteVsTilesHandler(t,f,i,n,s,r,!0)},collideSpriteVsTilesHandler:function(t,e,i,n,s,r,o){for(var a,h,l=t.body,c={left:0,right:0,top:0,bottom:0},d=!1,f=0;f0&&t>i&&(t=i)),0!==n&&0!==e&&(e<0&&e<-n?e=-n:e>0&&e>n&&(e=n)),this.gameObject.x+=t,this.gameObject.y+=e}t<0?this.facing=s.FACING_LEFT:t>0&&(this.facing=s.FACING_RIGHT),e<0?this.facing=s.FACING_UP:e>0&&(this.facing=s.FACING_DOWN),this.allowRotation&&(this.gameObject.angle+=this.deltaZ()),this._tx=t,this._ty=e},setBoundsRectangle:function(t){return this.customBoundsRectangle=t||this.world.bounds,this},checkWorldBounds:function(){var t=this.position,e=this.customBoundsRectangle,i=this.world.checkCollision,n=this.worldBounce?-this.worldBounce.x:-this.bounce.x,s=this.worldBounce?-this.worldBounce.y:-this.bounce.y,r=!1;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=n,this.blocked.right=!0,r=!0),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=s,this.blocked.down=!0,r=!0),r&&(this.blocked.none=!1),r},setOffset:function(t,e){return void 0===e&&(e=t),this.offset.set(t,e),this.updateCenter(),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter(),i&&n.getCenter){var s=(n.width-t)/2,r=(n.height-e)/2;this.offset.set(s,r)}return this.isCircle=!1,this.radius=0,this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter()):this.isCircle=!1,this},reset:function(t,e){this.stop();var i=this.gameObject;i.setPosition(t,e),i.getTopLeft?i.getTopLeft(this.position):this.position.set(t,e),this.prev.copy(this.position),this.prevFrame.copy(this.position),this.rotation=i.angle,this.preRotation=i.angle,this.updateBounds(),this.updateCenter()},stop:function(){return this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?this.radius>0&&t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom&&(this.center.x-t)*(this.center.x-t)+(this.center.y-e)*(this.center.y-e)<=this.radius*this.radius:h(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this._dx>0?this._dx:-this._dx},deltaAbsY:function(){return this._dy>0?this._dy:-this._dy},deltaX:function(){return this._dx},deltaY:function(){return this._dy},deltaXFinal:function(){return this._tx},deltaYFinal:function(){return this._ty},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.enable=!1,this.world&&this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor),this.isCircle?t.strokeCircle(i,n,this.width/2):(this.checkCollision.up&&t.lineBetween(e.x,e.y,e.x+this.width,e.y),this.checkCollision.right&&t.lineBetween(e.x+this.width,e.y,e.x+this.width,e.y+this.height),this.checkCollision.down&&t.lineBetween(e.x,e.y+this.height,e.x+this.width,e.y+this.height),this.checkCollision.left&&t.lineBetween(e.x,e.y,e.x,e.y+this.height))),this.debugShowVelocity&&(t.lineStyle(t.defaultStrokeWidth,this.world.defaults.velocityDebugColor,1),t.lineBetween(i,n,i+this.velocity.x/2,n+this.velocity.y/2))},willDrawDebug:function(){return this.debugShowBody||this.debugShowVelocity},setCollideWorldBounds:function(t,e,i){void 0===t&&(t=!0),this.collideWorldBounds=t;var n=void 0!==e,s=void 0!==i;return(n||s)&&(this.worldBounce||(this.worldBounce=new l),n&&(this.worldBounce.x=e),s&&(this.worldBounce.y=i)),this},setVelocity:function(t,e){return this.velocity.set(t,e),t=this.velocity.x,e=this.velocity.y,this.speed=Math.sqrt(t*t+e*e),this},setVelocityX:function(t){this.velocity.x=t;var e=t,i=this.velocity.y;return this.speed=Math.sqrt(e*e+i*i),this},setVelocityY:function(t){this.velocity.y=t;var e=this.velocity.x,i=t;return this.speed=Math.sqrt(e*e+i*i),this},setMaxVelocity:function(t,e){return this.maxVelocity.set(t,e),this},setMaxSpeed:function(t){return this.maxSpeed=t,this},setBounce:function(t,e){return this.bounce.set(t,e),this},setBounceX:function(t){return this.bounce.x=t,this},setBounceY:function(t){return this.bounce.y=t,this},setAcceleration:function(t,e){return this.acceleration.set(t,e),this},setAccelerationX:function(t){return this.acceleration.x=t,this},setAccelerationY:function(t){return this.acceleration.y=t,this},setAllowDrag:function(t){return void 0===t&&(t=!0),this.allowDrag=t,this},setAllowGravity:function(t){return void 0===t&&(t=!0),this.allowGravity=t,this},setAllowRotation:function(t){return void 0===t&&(t=!0),this.allowRotation=t,this},setDrag:function(t,e){return this.drag.set(t,e),this},setDragX:function(t){return this.drag.x=t,this},setDragY:function(t){return this.drag.y=t,this},setGravity:function(t,e){return this.gravity.set(t,e),this},setGravityX:function(t){return this.gravity.x=t,this},setGravityY:function(t){return this.gravity.y=t,this},setFriction:function(t,e){return this.friction.set(t,e),this},setFrictionX:function(t){return this.friction.x=t,this},setFrictionY:function(t){return this.friction.y=t,this},setAngularVelocity:function(t){return this.angularVelocity=t,this},setAngularAcceleration:function(t){return this.angularAcceleration=t,this},setAngularDrag:function(t){return this.angularDrag=t,this},setMass:function(t){return this.mass=t,this},setImmovable:function(t){return void 0===t&&(t=!0),this.immovable=t,this},setEnable:function(t){return void 0===t&&(t=!0),this.enable=t,this},x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=u},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o){this.world=t,this.name="",this.active=!0,this.overlapOnly=e,this.object1=i,this.object2=n,this.collideCallback=s,this.processCallback=r,this.callbackContext=o},setName:function(t){return this.name=t,this},update:function(){this.world.collideObjects(this.object1,this.object2,this.collideCallback,this.processCallback,this.callbackContext,this.overlapOnly)},destroy:function(){this.world.removeCollider(this),this.active=!1,this.world=null,this.object1=null,this.object2=null,this.collideCallback=null,this.processCallback=null,this.callbackContext=null}});t.exports=n},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsX()+e.deltaAbsX()+s;return 0===t._dx&&0===e._dx?(t.embedded=!0,e.embedded=!0):t._dx>e._dx?(r=t.right-e.x)>o&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?r=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.right=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.left=!0)):t._dxo&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?r=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.left=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.right=!0))),t.overlapX=r,e.overlapX=r,r}},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsY()+e.deltaAbsY()+s;return 0===t._dy&&0===e._dy?(t.embedded=!0,e.embedded=!0):t._dy>e._dy?(r=t.bottom-e.y)>o&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?r=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.down=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.up=!0)):t._dyo&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?r=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.up=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.down=!0))),t.overlapY=r,e.overlapY=r,r}},function(t,e,i){var n=i(384);function s(t){if(!(this instanceof s))return new s(t,[".left",".top",".right",".bottom"]);this._maxEntries=Math.max(4,t||9),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}function r(t,e,i){if(!i)return e.indexOf(t);for(var n=0;n=t.minX&&e.maxY>=t.minY}function g(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function v(t,e,i,s,r){for(var o,a=[e,i];a.length;)(i=a.pop())-(e=a.pop())<=s||(o=e+Math.ceil((i-e)/s/2)*s,n(t,o,e,i,r),a.push(e,o,o,i))}s.prototype={all:function(){return this._all(this.data,[])},search:function(t){var e=this.data,i=[],n=this.toBBox;if(!p(t,e))return i;for(var s,r,o,a,h=[];e;){for(s=0,r=e.children.length;s=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)},_split:function(t,e){var i=t[e],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);var r=this._chooseSplitIndex(i,s,n),a=g(i.children.splice(r,i.children.length-r));a.height=i.height,a.leaf=i.leaf,o(i,this.toBBox),o(a,this.toBBox),e?t[e-1].children.push(a):this._splitRoot(i,a)},_splitRoot:function(t,e){this.data=g([t,e]),this.data.height=t.height+1,this.data.leaf=!1,o(this.data,this.toBBox)},_chooseSplitIndex:function(t,e,i){var n,s,r,o,h,l,u,d,f,p,g,v,m,y;for(l=u=1/0,n=e;n<=i-e;n++)s=a(t,0,n,this.toBBox),r=a(t,n,i,this.toBBox),f=s,p=r,void 0,void 0,void 0,void 0,g=Math.max(f.minX,p.minX),v=Math.max(f.minY,p.minY),m=Math.min(f.maxX,p.maxX),y=Math.min(f.maxY,p.maxY),o=Math.max(0,m-g)*Math.max(0,y-v),h=c(s)+c(r),o=e;s--)r=t.children[s],h(u,t.leaf?o(r):r),c+=d(u);return c},_adjustParentBBoxes:function(t,e,i){for(var n=i;n>=0;n--)h(e[n],t)},_condense:function(t){for(var e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children).splice(e.indexOf(t[i]),1):this.clear():o(t[i],this.toBBox)},compareMinX:function(t,e){return t.left-e.left},compareMinY:function(t,e){return t.top-e.top},toBBox:function(t){return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}},t.exports=s},function(t,e){t.exports=function(t,e){return!(e.right<=t.left||e.bottom<=t.top||e.position.x>=t.right||e.position.y>=t.bottom)}},function(t,e,i){var n=i(55),s=i(0),r=i(50),o=i(47),a=i(3),h=new s({initialize:function(t,e){var i=e.displayWidth?e.displayWidth:64,n=e.displayHeight?e.displayHeight:64;this.world=t,this.gameObject=e,this.debugShowBody=t.defaults.debugShowStaticBody,this.debugBodyColor=t.defaults.staticBodyDebugColor,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new a,this.position=new a(e.x-e.displayOriginX,e.y-e.displayOriginY),this.width=i,this.height=n,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center=new a(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.velocity=a.ZERO,this.allowGravity=!1,this.gravity=a.ZERO,this.bounce=a.ZERO,this.onWorldBounds=!1,this.onCollide=!1,this.onOverlap=!1,this.mass=1,this.immovable=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.physicsType=r.STATIC_BODY,this._dx=0,this._dy=0},setGameObject:function(t,e){return t&&t!==this.gameObject&&(this.gameObject.body=null,t.body=this,this.gameObject=t),e&&this.updateFromGameObject(),this},updateFromGameObject:function(){this.world.staticTree.remove(this);var t=this.gameObject;return t.getTopLeft(this.position),this.width=t.displayWidth,this.height=t.displayHeight,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.world.staticTree.insert(this),this},setOffset:function(t,e){return void 0===e&&(e=t),this.world.staticTree.remove(this),this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(t,e),this.position.x+=this.offset.x,this.position.y+=this.offset.y,this.updateCenter(),this.world.staticTree.insert(this),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.world.staticTree.remove(this),this.width=t,this.height=e,this.halfWidth=Math.floor(t/2),this.halfHeight=Math.floor(e/2),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(s-this.halfWidth,r-this.halfHeight),this.position.x+=this.offset.x,this.position.y+=this.offset.y}return this.updateCenter(),this.isCircle=!1,this.radius=0,this.world.staticTree.insert(this),this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.world.staticTree.remove(this),this.isCircle=!0,this.radius=t,this.width=2*t,this.height=2*t,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter(),this.world.staticTree.insert(this)):this.isCircle=!1,this},updateCenter:function(){this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(t,e){var i=this.gameObject;void 0===t&&(t=i.x),void 0===e&&(e=i.y),this.world.staticTree.remove(this),i.setPosition(t,e),i.getTopLeft(this.position),this.updateCenter(),this.world.staticTree.insert(this)},stop:function(){return this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?n(this,t,e):o(this,t,e)},postUpdate:function(){},deltaAbsX:function(){return 0},deltaAbsY:function(){return 0},deltaX:function(){return 0},deltaY:function(){return 0},deltaZ:function(){return 0},destroy:function(){this.enable=!1,this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor,1),this.isCircle?t.strokeCircle(i,n,this.width/2):t.strokeRect(e.x,e.y,this.width,this.height))},willDrawDebug:function(){return this.debugShowBody},setMass:function(t){return t<=0&&(t=.1),this.mass=t,this},x:{get:function(){return this.position.x},set:function(t){this.world.staticTree.remove(this),this.position.x=t,this.world.staticTree.insert(this)}},y:{get:function(){return this.position.y},set:function(t){this.world.staticTree.remove(this),this.position.y=t,this.world.staticTree.insert(this)}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=h},,function(t,e,i){var n=new(i(0))({initialize:function(t){this.pluginManager=t,this.game=t.game},init:function(){},start:function(){},stop:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=n},function(t,e,i){var n=i(25);t.exports=function(t,e,i,s,r,o,a){for(var h=n(i,s,r,o,null,a),l=0;l-1}return!1}},function(t,e,i){var n=i(72),s=i(99),r=i(215);t.exports=function(t,e,i,o,a){if(void 0===i&&(i=!1),void 0===o&&(o=!0),!s(t,e,a))return null;var h=a.data[e][t];return h?(a.data[e][t]=i?null:new n(a,-1,t,e,a.tileWidth,a.tileHeight),o&&h&&h.collides&&r(t,e,a),h):null}},function(t,e,i){var n=i(10),s=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileWidth,r=n.tilemapLayer;return r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.x+i.scrollX*(1-r.scrollFactorX),s*=r.scaleX),e?Math.floor(t/s):t/s},r=function(){return console.warn("With the current map type you have to use the WorldToTileXY function."),null};t.exports=function(t){switch(t){case n.ORTHOGONAL:return s;default:return r}}},function(t,e,i){var n=i(10),s=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileHeight,r=n.tilemapLayer;return r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.y+i.scrollY*(1-r.scrollFactorY),s*=r.scaleY),e?Math.floor(t/s):t/s},r=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileHeight,r=n.tilemapLayer;return r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.y+i.scrollY*(1-r.scrollFactorY),s*=r.scaleY),e?Math.floor(t/(s/2)):t/(s/2)},o=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileHeight,r=n.tilemapLayer;r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.y+i.scrollY*(1-r.scrollFactorY),s*=r.scaleY);var o=n.hexSideLength,a=(s-o)/2+o;return e?Math.floor(t/a):t/a},a=function(){return console.warn("With the current map type you have to use the WorldToTileXY function."),null};t.exports=function(t){switch(t){case n.ORTHOGONAL:return s;case n.HEXAGONAL:return o;case n.STAGGERED:return r;default:return a}}},function(t,e,i){var n=i(33),s=i(218),r=i(474),o=i(475),a=i(486);t.exports=function(t,e,i,h,l,u){var c;switch(e){case n.ARRAY_2D:c=s(t,i,h,l,u);break;case n.CSV:c=r(t,i,h,l,u);break;case n.TILED_JSON:c=o(t,i,u);break;case n.WELTMEISTER:c=a(t,i,u);break;default:console.warn("Unrecognized tilemap data format: "+e),c=null}return c}},function(t,e,i){var n=i(33),s=i(218);t.exports=function(t,e,i,r,o){var a=e.trim().split("\n").map(function(t){return t.split(",")}),h=s(t,a,i,r,o);return h.format=n.CSV,h}},function(t,e,i){var n=i(10),s=i(33),r=i(101),o=i(476),a=i(478),h=i(479),l=i(482),u=i(484),c=i(485);t.exports=function(t,e,i){if("isometric"===e.orientation||"staggered"===e.orientation)console.warn("Isometric map types are WIP in this version of Phaser");else if("hexagonal"===e.orientation)console.warn("Hexagonal map types are WIP in this version of Phaser");else if("orthogonal"!==e.orientation)return console.warn("Only orthogonal, hexagonal and isometric map types are supported in this version of Phaser"),null;var d=new r({width:e.width,height:e.height,name:t,tileWidth:e.tilewidth,tileHeight:e.tileheight,orientation:n.fromOrientationString(e.orientation),format:s.TILED_JSON,version:e.version,properties:e.properties,renderOrder:e.renderorder,infinite:e.infinite});d.orientation===n.HEXAGONAL&&(d.hexSideLength=e.hexsidelength),d.layers=o(e,i),d.images=a(e);var f=h(e);return d.tilesets=f.tilesets,d.imageCollections=f.imageCollections,d.objects=l(e),d.tiles=u(d),c(d),d}},function(t,e,i){var n=i(10),s=i(477),r=i(2),o=i(100),a=i(219),h=i(72),l=i(220);t.exports=function(t,e){for(var i=r(t,"infinite",!1),u=[],c=[],d=l(t);d.i0;)if(d.i>=d.layers.length){if(c.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}d=c.pop()}else{var f=d.layers[d.i];if(d.i++,"tilelayer"===f.type)if(f.compression)console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+f.name+"'");else{if(f.encoding&&"base64"===f.encoding){if(f.chunks)for(var p=0;p0?((m=new h(g,v.gid,R,L,t.tilewidth,t.tileheight)).rotation=v.rotation,m.flipX=v.flipped,x[L][R]=m):(y=e?null:new h(g,-1,R,L,t.tilewidth,t.tileheight),x[L][R]=y),++T===b.width&&(M++,T=0)}}else{(g=new o({name:d.name+f.name,x:d.x+r(f,"offsetx",0)+f.x,y:d.y+r(f,"offsety",0)+f.y,width:f.width,height:f.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,alpha:d.opacity*f.opacity,visible:d.visible&&f.visible,properties:r(f,"properties",{}),orientation:n.fromOrientationString(t.orientation)})).orientation===n.HEXAGONAL&&(g.hexSideLength=t.hexsidelength);for(var D=[],F=0,k=f.data.length;F0?((m=new h(g,v.gid,T,x.length,t.tilewidth,t.tileheight)).rotation=v.rotation,m.flipX=v.flipped,D.push(m)):(y=e?null:new h(g,-1,T,x.length,t.tilewidth,t.tileheight),D.push(y)),++T===f.width&&(x.push(D),T=0,D=[])}g.data=x,u.push(g)}else if("group"===f.type){var I=l(t,f,d);c.push(d),d=I}}return u}},function(t,e){t.exports=function(t){for(var e=window.atob(t),i=e.length,n=new Array(i/4),s=0;s>>0;return n}},function(t,e,i){var n=i(2),s=i(220);t.exports=function(t){for(var e=[],i=[],r=s(t);r.i0;)if(r.i>=r.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}r=i.pop()}else{var o=r.layers[r.i];if(r.i++,"imagelayer"===o.type){var a=n(o,"offsetx",0)+n(o,"startx",0),h=n(o,"offsety",0)+n(o,"starty",0);e.push({name:r.name+o.name,image:o.image,x:r.x+a+o.x,y:r.y+h+o.y,alpha:r.opacity*o.opacity,visible:r.visible&&o.visible,properties:n(o,"properties",{})})}else if("group"===o.type){var l=s(t,o,r);i.push(r),r=l}}return e}},function(t,e,i){var n=i(137),s=i(480),r=i(221);t.exports=function(t){for(var e,i=[],o=[],a=null,h=0;h1){if(Array.isArray(l.tiles)){for(var c={},d={},f=0;f=this.firstgid&&t0;)if(a.i>=a.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}a=i.pop()}else{var h=a.layers[a.i];if(a.i++,h.opacity*=a.opacity,h.visible=a.visible&&h.visible,"objectgroup"===h.type){h.name=a.name+h.name;for(var l=a.x+n(h,"startx",0)+n(h,"offsetx",0),u=a.y+n(h,"starty",0)+n(h,"offsety",0),c=[],d=0;da&&(a=e.layer[l].width),e.layer[l].height>h&&(h=e.layer[l].height);var u=new s({width:a,height:h,name:t,tileWidth:e.layer[0].tilesize,tileHeight:e.layer[0].tilesize,format:n.WELTMEISTER});return u.layers=r(e,i),u.tilesets=o(e),u}},function(t,e,i){var n=i(100),s=i(72);t.exports=function(t,e){for(var i=[],r=0;r-1?new s(a,f,c,u,o.tilesize,o.tilesize):e?null:new s(a,-1,c,u,o.tilesize,o.tilesize),h.push(d)}l.push(h),h=[]}a.data=l,i.push(a)}return i}},function(t,e,i){var n=i(137);t.exports=function(t){for(var e=[],i=[],s=0;s-1&&(this.renderOrder=t),this},addTilesetImage:function(t,e,i,n,s,r,o){if(void 0===t)return null;if(void 0!==e&&null!==e||(e=t),!this.scene.sys.textures.exists(e))return console.warn("Invalid Tileset Image: "+e),null;var h=this.scene.sys.textures.get(e),l=this.getTilesetIndex(t);if(null===l&&this.format===a.TILED_JSON)return console.warn("No data found for Tileset: "+t),null;var u=this.tilesets[l];return u?(u.setTileSize(i,n),u.setSpacing(s,r),u.setImage(h),u):(void 0===i&&(i=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o=0),(u=new p(t,o,i,n,s,r)).setImage(h),this.tilesets.push(u),u)},convertLayerToStatic:function(t){if(null===(t=this.getLayer(t)))return null;var e=t.tilemapLayer;if(!(e&&e instanceof r))return null;var i=new c(e.scene,e.tilemap,e.layerIndex,e.tileset,e.x,e.y);return this.scene.sys.displayList.add(i),e.destroy(),i},copy:function(t,e,i,n,s,r,o,a){return a=this.getLayer(a),this._isStaticCall(a,"copy")?this:null!==a?(f.Copy(t,e,i,n,s,r,o,a),this):null},createBlankDynamicLayer:function(t,e,i,n,s,o,a,l){if(void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.width),void 0===o&&(o=this.height),void 0===a&&(a=this.tileWidth),void 0===l&&(l=this.tileHeight),null!==this.getLayerIndex(t))return console.warn("Invalid Tilemap Layer ID: "+t),null;for(var u,c=new h({name:t,tileWidth:a,tileHeight:l,width:s,height:o,orientation:this.orientation}),f=0;f-1&&this.putTileAt(e,r.x,r.y,i,r.tilemapLayer)}return n},removeTileAt:function(t,e,i,n,s){return s=this.getLayer(s),this._isStaticCall(s,"removeTileAt")?null:null===s?null:f.RemoveTileAt(t,e,i,n,s)},removeTileAtWorldXY:function(t,e,i,n,s,r){return r=this.getLayer(r),this._isStaticCall(r,"removeTileAtWorldXY")?null:null===r?null:f.RemoveTileAtWorldXY(t,e,i,n,s,r)},renderDebug:function(t,e,i){return null===(i=this.getLayer(i))?null:(f.RenderDebug(t,e,i),this)},renderDebugFull:function(t,e){for(var i=this.layers,n=0;n=0&&t<4&&(this._renderOrder=t),this},calculateFacesAt:function(t,e){return a.CalculateFacesAt(t,e,this.layer),this},calculateFacesWithin:function(t,e,i,n){return a.CalculateFacesWithin(t,e,i,n,this.layer),this},createFromTiles:function(t,e,i,n,s){return a.CreateFromTiles(t,e,i,n,s,this.layer)},cull:function(t){return this.cullCallback(this.layer,t,this.culledTiles,this._renderOrder)},copy:function(t,e,i,n,s,r,o){return a.Copy(t,e,i,n,s,r,o,this.layer),this},destroy:function(t){void 0===t&&(t=!0),this.tilemap&&(this.layer.tilemapLayer===this&&(this.layer.tilemapLayer=void 0),t&&this.tilemap.removeLayer(this),this.tilemap=void 0,this.layer=void 0,this.culledTiles.length=0,this.cullCallback=null,this.gidMap=[],this.tileset=[],o.prototype.destroy.call(this))},fill:function(t,e,i,n,s,r){return a.Fill(t,e,i,n,s,r,this.layer),this},filterTiles:function(t,e,i,n,s,r,o){return a.FilterTiles(t,e,i,n,s,r,o,this.layer)},findByIndex:function(t,e,i){return a.FindByIndex(t,e,i,this.layer)},findTile:function(t,e,i,n,s,r,o){return a.FindTile(t,e,i,n,s,r,o,this.layer)},forEachTile:function(t,e,i,n,s,r,o){return a.ForEachTile(t,e,i,n,s,r,o,this.layer),this},getTileAt:function(t,e,i){return a.GetTileAt(t,e,i,this.layer)},getTileAtWorldXY:function(t,e,i,n){return a.GetTileAtWorldXY(t,e,i,n,this.layer)},getTilesWithin:function(t,e,i,n,s){return a.GetTilesWithin(t,e,i,n,s,this.layer)},getTilesWithinShape:function(t,e,i){return a.GetTilesWithinShape(t,e,i,this.layer)},getTilesWithinWorldXY:function(t,e,i,n,s,r){return a.GetTilesWithinWorldXY(t,e,i,n,s,r,this.layer)},hasTileAt:function(t,e){return a.HasTileAt(t,e,this.layer)},hasTileAtWorldXY:function(t,e,i){return a.HasTileAtWorldXY(t,e,i,this.layer)},putTileAt:function(t,e,i,n){return a.PutTileAt(t,e,i,n,this.layer)},putTileAtWorldXY:function(t,e,i,n,s){return a.PutTileAtWorldXY(t,e,i,n,s,this.layer)},putTilesAt:function(t,e,i,n){return a.PutTilesAt(t,e,i,n,this.layer),this},randomize:function(t,e,i,n,s){return a.Randomize(t,e,i,n,s,this.layer),this},removeTileAt:function(t,e,i,n){return a.RemoveTileAt(t,e,i,n,this.layer)},removeTileAtWorldXY:function(t,e,i,n,s){return a.RemoveTileAtWorldXY(t,e,i,n,s,this.layer)},renderDebug:function(t,e){return a.RenderDebug(t,e,this.layer),this},replaceByIndex:function(t,e,i,n,s,r){return a.ReplaceByIndex(t,e,i,n,s,r,this.layer),this},setSkipCull:function(t){return void 0===t&&(t=!0),this.skipCull=t,this},setCullPadding:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=1),this.cullPaddingX=t,this.cullPaddingY=e,this},setCollision:function(t,e,i,n){return a.SetCollision(t,e,i,this.layer,n),this},setCollisionBetween:function(t,e,i,n){return a.SetCollisionBetween(t,e,i,n,this.layer),this},setCollisionByProperty:function(t,e,i){return a.SetCollisionByProperty(t,e,i,this.layer),this},setCollisionByExclusion:function(t,e,i){return a.SetCollisionByExclusion(t,e,i,this.layer),this},setCollisionFromCollisionGroup:function(t,e){return a.SetCollisionFromCollisionGroup(t,e,this.layer),this},setTileIndexCallback:function(t,e,i){return a.SetTileIndexCallback(t,e,i,this.layer),this},setTileLocationCallback:function(t,e,i,n,s,r){return a.SetTileLocationCallback(t,e,i,n,s,r,this.layer),this},shuffle:function(t,e,i,n){return a.Shuffle(t,e,i,n,this.layer),this},swapByIndex:function(t,e,i,n,s,r){return a.SwapByIndex(t,e,i,n,s,r,this.layer),this},tileToWorldX:function(t,e){return this.tilemap.TileToWorldX(t,e,this.layer)},tileToWorldY:function(t,e){return this.tilemap.TileToWorldY(t,e,this.layer)},tileToWorldXY:function(t,e,i,n){return this.tilemap.TileToWorldXY(t,e,i,n,this.layer)},weightedRandomize:function(t,e,i,n,s){return a.WeightedRandomize(t,e,i,n,s,this.layer),this},worldToTileX:function(t,e,i){return this.tilemap.WorldToTileX(t,e,i,this.layer)},worldToTileY:function(t,e,i){return this.tilemap.WorldToTileY(t,e,i,this.layer)},worldToTileXY:function(t,e,i,n,s){return this.tilemap.WorldToTileXY(t,e,i,n,s,this.layer)}});t.exports=l},function(t,e,i){var n=i(0),s=i(12),r=i(19),o=i(14),a=i(1341),h=i(135),l=i(30),u=i(9),c=i(3),d=new n({Extends:o,Mixins:[s.Alpha,s.BlendMode,s.ComputedSize,s.Depth,s.Flip,s.GetBounds,s.Origin,s.Pipeline,s.Transform,s.Visible,s.ScrollFactor,a],initialize:function(t,e,i,n,s,a){o.call(this,t,"StaticTilemapLayer"),this.isTilemap=!0,this.tilemap=e,this.layerIndex=i,this.layer=e.layers[i],this.layer.tilemapLayer=this,this.tileset=[],this.culledTiles=[],this.skipCull=!1,this.isoCullDistances=new c(1,1),this.tilesDrawn=0,this.tilesTotal=this.layer.width*this.layer.height,this.cullPaddingX=1,this.cullPaddingY=1,this.cullCallback=h.CullTiles,this.renderer=t.sys.game.renderer,this.vertexBuffer=[],this.bufferData=[],this.vertexViewF32=[],this.vertexViewU32=[],this.dirty=[],this.vertexCount=[],this._renderOrder=0,this._tempMatrix=new l,this.gidMap=[],this.setTilesets(n),this.setAlpha(this.layer.alpha),this.setPosition(s,a),this.setOrigin(),this.setSize(e.tileWidth*this.layer.width,e.tileHeight*this.layer.height),this.updateVBOData(),this.initPipeline("TextureTintPipeline"),t.sys.game.events.on(r.CONTEXT_RESTORED,function(){this.updateVBOData()},this)},setTilesets:function(t){var e=[],i=[],n=this.tilemap;Array.isArray(t)||(t=[t]);for(var s=0;sv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(1===p)for(o=0;o=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(2===p)for(o=u-1;o>=0;o--)for(a=0;av||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(3===p)for(o=u-1;o>=0;o--)for(a=l-1;a>=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));this.dirty[e]=!1,null===m?(m=i.createVertexBuffer(y,n.STATIC_DRAW),this.vertexBuffer[e]=m):(i.setVertexBuffer(m),n.bufferSubData(n.ARRAY_BUFFER,0,y))}return this},batchTile:function(t,e,i,n,s,r,o){var a=i.getTileTextureCoordinates(e.index);if(!a)return t;var h=i.tileWidth,l=i.tileHeight,c=h/2,d=l/2,f=a.x/n,p=a.y/s,g=(a.x+h)/n,v=(a.y+l)/s,m=this._tempMatrix,y=-c,x=-d;e.flipX&&(h*=-1,y+=i.tileWidth),e.flipY&&(l*=-1,x+=i.tileHeight);var T=y+h,w=x+l;m.applyITRS(c+e.pixelX,d+e.pixelY,e.rotation,1,1);var E=u.getTintAppendFloatAlpha(16777215,r.alpha*this.alpha*e.alpha),_=m.getX(y,x),A=m.getY(y,x),b=m.getX(y,w),S=m.getY(y,w),C=m.getX(T,w),M=m.getY(T,w),O=m.getX(T,x),P=m.getY(T,x);r.roundPixels&&(_=Math.round(_),A=Math.round(A),b=Math.round(b),S=Math.round(S),C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P));var R=this.vertexViewF32[o],L=this.vertexViewU32[o];return R[++t]=_,R[++t]=A,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=E,R[++t]=b,R[++t]=S,R[++t]=f,R[++t]=v,R[++t]=0,L[++t]=E,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=E,R[++t]=_,R[++t]=A,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=E,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=E,R[++t]=O,R[++t]=P,R[++t]=g,R[++t]=p,R[++t]=0,L[++t]=E,this.vertexCount[o]+=6,t},setRenderOrder:function(t){if("string"==typeof t&&(t=["right-down","left-down","right-up","left-up"].indexOf(t)),t>=0&&t<4){this._renderOrder=t;for(var e=0;e0){var t=this.delay+this.delay*this.repeat;return(this.elapsed+this.delay*(this.repeat-this.repeatCount))/t}return this.getProgress()},getRepeatCount:function(){return this.repeatCount},getElapsed:function(){return this.elapsed},getElapsedSeconds:function(){return.001*this.elapsed},remove:function(t){void 0===t&&(t=!1),this.elapsed=this.delay,this.hasDispatched=!t,this.repeatCount=0},destroy:function(){this.callback=void 0,this.callbackScope=void 0,this.args=[]}});t.exports=r},function(t,e,i){var n=i(1350);t.exports=function(t){var e,i=[];if(t.hasOwnProperty("props"))for(e in t.props)"_"!==e.substr(0,1)&&i.push({key:e,value:t.props[e]});else for(e in t)-1===n.indexOf(e)&&"_"!==e.substr(0,1)&&i.push({key:e,value:t[e]});return i}},function(t,e,i){var n=i(6);t.exports=function(t){var e=n(t,"tweens",null);return null===e?[]:("function"==typeof e&&(e=e.call()),Array.isArray(e)||(e=[e]),e)}},function(t,e,i){var n=i(225),s=i(15),r=i(86),o=i(67),a=i(138),h=i(6),l=i(224),u=i(226),c=i(228);t.exports=function(t,e,i){void 0===i&&(i=n);var d=h(e,"from",0),f=h(e,"to",1),p=[{value:d}],g=a(e,"delay",i.delay),v=a(e,"duration",i.duration),m=h(e,"easeParams",i.easeParams),y=o(h(e,"ease",i.ease),m),x=a(e,"hold",i.hold),T=a(e,"repeat",i.repeat),w=a(e,"repeatDelay",i.repeatDelay),E=r(e,"yoyo",i.yoyo),_=[],A=l("value",f),b=c(p[0],0,"value",A.getEnd,A.getStart,A.getActive,y,g,v,E,x,T,w,!1,!1);b.start=d,b.current=d,b.to=f,_.push(b);var S=new u(t,_,p);S.offset=s(e,"offset",null),S.completeDelay=s(e,"completeDelay",0),S.loop=Math.round(s(e,"loop",0)),S.loopDelay=Math.round(s(e,"loopDelay",0)),S.paused=r(e,"paused",!1),S.useFrames=r(e,"useFrames",!1);for(var C=h(e,"callbackScope",S),M=[S,null],O=u.TYPES,P=0;PA&&(A=C),_[b][S]=C}}}var M=o?n(o):null;return a?function(t,e,n,s){var r,o=0,a=s%m,h=Math.floor(s/m);if(a>=0&&a=0&&h0?Math.floor(v/p.length):h(e,"duration",g.duration),g.delay=h(e,"delay",g.delay),g.easeParams=c(e,"easeParams",g.easeParams),g.ease=a(c(e,"ease",g.ease),g.easeParams),g.hold=h(e,"hold",g.hold),g.repeat=h(e,"repeat",g.repeat),g.repeatDelay=h(e,"repeatDelay",g.repeatDelay),g.yoyo=o(e,"yoyo",g.yoyo),g.flipX=o(e,"flipX",g.flipX),g.flipY=o(e,"flipY",g.flipY);for(var m=0;m0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay},init:function(){return this.calcDuration(),this.progress=0,this.totalProgress=0,!this.paused||(this.state=a.PAUSED,!1)},resetTweens:function(t){for(var e=0;e0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweens(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=a.LOOP_DELAY):(this.state=a.ACTIVE,this.dispatchTimelineEvent(r.TIMELINE_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=a.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=a.PENDING_REMOVE,this.dispatchTimelineEvent(r.TIMELINE_COMPLETE,this.callbacks.onComplete))},update:function(t,e){if(this.state!==a.PAUSED){switch(this.useFrames&&(e=1*this.manager.timeScale),e*=this.timeScale,this.elapsed+=e,this.progress=Math.min(this.elapsed/this.duration,1),this.totalElapsed+=e,this.totalProgress=Math.min(this.totalElapsed/this.totalDuration,1),this.state){case a.ACTIVE:for(var i=this.totalData,n=0;n=this.nextTick&&this.currentAnim.setFrame(this)}},setCurrentFrame:function(t){var e=this.parent;return this.currentFrame=t,e.texture=t.frame.texture,e.frame=t.frame,e.isCropped&&e.frame.updateCropUVs(e._crop,e.flipX,e.flipY),e.setSizeToFrame(),e._originComponent&&(t.frame.customPivot?e.setOrigin(t.frame.pivotX,t.frame.pivotY):e.updateDisplayOrigin()),e},updateFrame:function(t){var e=this.setCurrentFrame(t);if(this.isPlaying){t.setAlpha&&(e.alpha=t.alpha);var i=this.currentAnim;e.emit(r.SPRITE_ANIMATION_KEY_UPDATE+i.key,i,t,e),e.emit(r.SPRITE_ANIMATION_UPDATE,i,t,e),3===this._pendingStop&&this._pendingStopValue===t&&this.currentAnim.completeAnimation(this)}},nextFrame:function(){return this.currentAnim&&this.currentAnim.nextFrame(this),this.parent},previousFrame:function(){return this.currentAnim&&this.currentAnim.previousFrame(this),this.parent},setYoyo:function(t){return void 0===t&&(t=!1),this._yoyo=t,this.parent},getYoyo:function(){return this._yoyo},destroy:function(){this.animationManager.off(r.REMOVE_ANIMATION,this.remove,this),this.animationManager=null,this.parent=null,this.currentAnim=null,this.currentFrame=null}});t.exports=o},function(t,e,i){var n=i(501),s=i(48),r=i(0),o=i(10),a=i(502),h=i(90),l=i(30),u=new r({initialize:function(t){this.game=t,this.type=o.CANVAS,this.drawCount=0,this.width=0,this.height=0,this.config={clearBeforeRender:t.config.clearBeforeRender,backgroundColor:t.config.backgroundColor,resolution:t.config.resolution,antialias:t.config.antialias,roundPixels:t.config.roundPixels},this.gameCanvas=t.canvas;var e={alpha:t.config.transparent,desynchronized:t.config.desynchronized};this.gameContext=this.game.config.context?this.game.config.context:this.gameCanvas.getContext("2d",e),this.currentContext=this.gameContext,this.antialias=t.config.antialias,this.blendModes=a(),this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92},this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.init()},init:function(){this.game.scale.on(h.RESIZE,this.onResize,this);var t=this.game.scale.baseSize;this.resize(t.width,t.height)},onResize:function(t,e){e.width===this.width&&e.height===this.height||this.resize(e.width,e.height)},resize:function(t,e){this.width=t,this.height=e},resetTransform:function(){this.currentContext.setTransform(1,0,0,1,0,0)},setBlendMode:function(t){return this.currentContext.globalCompositeOperation=t,this},setContext:function(t){return this.currentContext=t||this.gameContext,this},setAlpha:function(t){return this.currentContext.globalAlpha=t,this},preRender:function(){var t=this.gameContext,e=this.config,i=this.width,n=this.height;t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),e.clearBeforeRender&&t.clearRect(0,0,i,n),e.transparent||(t.fillStyle=e.backgroundColor.rgba,t.fillRect(0,0,i,n)),t.save(),this.drawCount=0},render:function(t,e,i,n){var r=e.list,o=r.length,a=n._cx,h=n._cy,l=n._cw,u=n._ch,c=n.renderToTexture?n.context:t.sys.context;c.save(),this.game.scene.customViewports&&(c.beginPath(),c.rect(a,h,l,u),c.clip()),this.currentContext=c;var d=n.mask;d&&d.preRenderCanvas(this,null,n._maskCamera),n.transparent||(c.fillStyle=n.backgroundColor.rgba,c.fillRect(a,h,l,u)),c.globalAlpha=n.alpha,c.globalCompositeOperation="source-over",this.drawCount+=r.length,n.renderToTexture&&n.emit(s.PRE_RENDER,n),n.matrix.copyToContext(c);for(var f=0;f=0?y=-(y+d):y<0&&(y=Math.abs(y)-d)),t.flipY&&(x>=0?x=-(x+f):x<0&&(x=Math.abs(x)-f))}var w=1,E=1;t.flipX&&(p||(y+=-e.realWidth+2*v),w=-1),t.flipY&&(p||(x+=-e.realHeight+2*m),E=-1),a.applyITRS(t.x,t.y,t.rotation,t.scaleX*w,t.scaleY*E),o.copyFrom(i.matrix),n?(o.multiplyWithOffset(n,-i.scrollX*t.scrollFactorX,-i.scrollY*t.scrollFactorY),a.e=t.x,a.f=t.y,o.multiply(a,h)):(a.e-=i.scrollX*t.scrollFactorX,a.f-=i.scrollY*t.scrollFactorY,o.multiply(a,h)),r.save(),h.setToContext(r),r.globalCompositeOperation=this.blendModes[t.blendMode],r.globalAlpha=s,r.imageSmoothingEnabled=!(!this.antialias||e.source.scaleMode),r.drawImage(e.source.image,u,c,d,f,y,x,d/g,f/g),r.restore()}},destroy:function(){this.gameCanvas=null,this.gameContext=null,this.game=null}});t.exports=u},function(t,e,i){var n=i(27),s=i(32),r=i(2);t.exports=function(t,e){var i=r(e,"callback"),o=r(e,"type","image/png"),a=r(e,"encoder",.92),h=Math.abs(Math.round(r(e,"x",0))),l=Math.abs(Math.round(r(e,"y",0))),u=r(e,"width",t.width),c=r(e,"height",t.height);if(r(e,"getPixel",!1)){var d=t.getContext("2d").getImageData(h,l,1,1).data;i.call(null,new s(d[0],d[1],d[2],d[3]/255))}else if(0!==h||0!==l||u!==t.width||c!==t.height){var f=n.createWebGL(this,u,c);f.getContext("2d").drawImage(t,h,l,u,c,0,0,u,c);var p=new Image;p.onerror=function(){i.call(null),n.remove(f)},p.onload=function(){i.call(null,p),n.remove(f)},p.src=f.toDataURL(o,a)}else{var g=new Image;g.onerror=function(){i.call(null)},g.onload=function(){i.call(null,g)},g.src=t.toDataURL(o,a)}}},function(t,e,i){var n=i(52),s=i(311);t.exports=function(){var t=[],e=s.supportNewBlendModes,i="source-over";return t[n.NORMAL]=i,t[n.ADD]="lighter",t[n.MULTIPLY]=e?"multiply":i,t[n.SCREEN]=e?"screen":i,t[n.OVERLAY]=e?"overlay":i,t[n.DARKEN]=e?"darken":i,t[n.LIGHTEN]=e?"lighten":i,t[n.COLOR_DODGE]=e?"color-dodge":i,t[n.COLOR_BURN]=e?"color-burn":i,t[n.HARD_LIGHT]=e?"hard-light":i,t[n.SOFT_LIGHT]=e?"soft-light":i,t[n.DIFFERENCE]=e?"difference":i,t[n.EXCLUSION]=e?"exclusion":i,t[n.HUE]=e?"hue":i,t[n.SATURATION]=e?"saturation":i,t[n.COLOR]=e?"color":i,t[n.LUMINOSITY]=e?"luminosity":i,t[n.ERASE]="destination-out",t[n.SOURCE_IN]="source-in",t[n.SOURCE_OUT]="source-out",t[n.SOURCE_ATOP]="source-atop",t[n.DESTINATION_OVER]="destination-over",t[n.DESTINATION_IN]="destination-in",t[n.DESTINATION_OUT]="destination-out",t[n.DESTINATION_ATOP]="destination-atop",t[n.LIGHTER]="lighter",t[n.COPY]="copy",t[n.XOR]="xor",t}},function(t,e,i){var n=i(89),s=i(48),r=i(0),o=i(10),a=i(19),h=i(114),l=i(1),u=i(90),c=i(78),d=i(115),f=i(30),p=i(9),g=i(504),v=i(505),m=i(506),y=i(232),x=i(507),T=new r({initialize:function(t){var e=t.config,i={alpha:e.transparent,desynchronized:e.desynchronized,depth:!1,antialias:e.antialiasGL,premultipliedAlpha:e.premultipliedAlpha,stencil:!0,failIfMajorPerformanceCaveat:e.failIfMajorPerformanceCaveat,powerPreference:e.powerPreference};this.config={clearBeforeRender:e.clearBeforeRender,antialias:e.antialias,backgroundColor:e.backgroundColor,contextCreation:i,resolution:e.resolution,roundPixels:e.roundPixels,maxTextures:e.maxTextures,maxTextureSize:e.maxTextureSize,batchSize:e.batchSize,maxLights:e.maxLights,mipmapFilter:e.mipmapFilter},this.game=t,this.type=o.WEBGL,this.width=0,this.height=0,this.canvas=t.canvas,this.blendModes=[],this.nativeTextures=[],this.contextLost=!1,this.pipelines=null,this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92,isFramebuffer:!1,bufferWidth:0,bufferHeight:0},this.currentActiveTextureUnit=0,this.currentTextures=new Array(16),this.currentFramebuffer=null,this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.currentBlendMode=1/0,this.currentScissorEnabled=!1,this.currentScissor=null,this.scissorStack=[],this.contextLostHandler=l,this.contextRestoredHandler=l,this.gl=null,this.supportedExtensions=null,this.extensions={},this.glFormats=[],this.compression={ETC1:!1,PVRTC:!1,S3TC:!1},this.drawingBufferHeight=0,this.blankTexture=null,this.defaultCamera=new n(0,0,0,0),this._tempMatrix1=new f,this._tempMatrix2=new f,this._tempMatrix3=new f,this._tempMatrix4=new f,this.maskCount=0,this.maskStack=[],this.currentMask={mask:null,camera:null},this.currentCameraMask={mask:null,camera:null},this.glFuncMap=null,this.currentType="",this.newType=!1,this.nextTypeMatch=!1,this.mipmapFilter=null,this.init(this.config)},init:function(t){var e,i=this.game,n=this.canvas,s=t.backgroundColor;if(!(e=i.config.context?i.config.context:n.getContext("webgl",t.contextCreation)||n.getContext("experimental-webgl",t.contextCreation))||e.isContextLost())throw this.contextLost=!0,new Error("WebGL unsupported");this.gl=e;var r=this;this.contextLostHandler=function(t){r.contextLost=!0,r.game.events.emit(a.CONTEXT_LOST,r),t.preventDefault()},this.contextRestoredHandler=function(){r.contextLost=!1,r.init(r.config),r.game.events.emit(a.CONTEXT_RESTORED,r)},n.addEventListener("webglcontextlost",this.contextLostHandler,!1),n.addEventListener("webglcontextrestored",this.contextRestoredHandler,!1),i.context=e;for(var h=0;h<=27;h++)this.blendModes.push({func:[e.ONE,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_ADD});this.blendModes[1].func=[e.ONE,e.DST_ALPHA],this.blendModes[2].func=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA],this.blendModes[3].func=[e.ONE,e.ONE_MINUS_SRC_COLOR],this.blendModes[17]={func:[e.ZERO,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_REVERSE_SUBTRACT},this.glFormats[0]=e.BYTE,this.glFormats[1]=e.SHORT,this.glFormats[2]=e.UNSIGNED_BYTE,this.glFormats[3]=e.UNSIGNED_SHORT,this.glFormats[4]=e.FLOAT,this.glFuncMap={mat2:{func:e.uniformMatrix2fv,length:1,matrix:!0},mat3:{func:e.uniformMatrix3fv,length:1,matrix:!0},mat4:{func:e.uniformMatrix4fv,length:1,matrix:!0},"1f":{func:e.uniform1f,length:1},"1fv":{func:e.uniform1fv,length:1},"1i":{func:e.uniform1i,length:1},"1iv":{func:e.uniform1iv,length:1},"2f":{func:e.uniform2f,length:2},"2fv":{func:e.uniform2fv,length:1},"2i":{func:e.uniform2i,length:2},"2iv":{func:e.uniform2iv,length:1},"3f":{func:e.uniform3f,length:3},"3fv":{func:e.uniform3fv,length:1},"3i":{func:e.uniform3i,length:3},"3iv":{func:e.uniform3iv,length:1},"4f":{func:e.uniform4f,length:4},"4fv":{func:e.uniform4fv,length:1},"4i":{func:e.uniform4i,length:4},"4iv":{func:e.uniform4iv,length:1}};var l=e.getSupportedExtensions();t.maxTextures||(t.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)),t.maxTextureSize||(t.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE));var u="WEBGL_compressed_texture_",c="WEBKIT_"+u;this.compression.ETC1=e.getExtension(u+"etc1")||e.getExtension(c+"etc1"),this.compression.PVRTC=e.getExtension(u+"pvrtc")||e.getExtension(c+"pvrtc"),this.compression.S3TC=e.getExtension(u+"s3tc")||e.getExtension(c+"s3tc"),this.supportedExtensions=l,e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.clearColor(s.redGL,s.greenGL,s.blueGL,s.alphaGL),this.mipmapFilter=e[t.mipmapFilter];for(var f=0;f0&&n>0;if(o&&a){var h=o[0],l=o[1],u=o[2],c=o[3];a=h!==t||l!==e||u!==i||c!==n}a&&(this.flush(),r.scissor(t,s-e-n,i,n))},popScissor:function(){var t=this.scissorStack;t.pop();var e=t[t.length-1];e&&this.setScissor(e[0],e[1],e[2],e[3]),this.currentScissor=e},setPipeline:function(t,e){return this.currentPipeline===t&&this.currentPipeline.vertexBuffer===this.currentVertexBuffer&&this.currentPipeline.program===this.currentProgram||(this.flush(),this.currentPipeline=t,this.currentPipeline.bind()),this.currentPipeline.onBind(e),this.currentPipeline},hasActiveStencilMask:function(){var t=this.currentMask.mask,e=this.currentCameraMask.mask;return t&&t.isStencil||e&&e.isStencil},rebindPipeline:function(t){var e=this.gl;e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),this.hasActiveStencilMask()?e.clear(e.DEPTH_BUFFER_BIT):(e.disable(e.STENCIL_TEST),e.clear(e.DEPTH_BUFFER_BIT|e.STENCIL_BUFFER_BIT)),e.viewport(0,0,this.width,this.height),this.setBlendMode(0,!0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.blankTexture.glTexture),this.currentActiveTextureUnit=0,this.currentTextures[0]=this.blankTexture.glTexture,this.currentPipeline=t,this.currentPipeline.bind(),this.currentPipeline.onBind()},clearPipeline:function(){this.flush(),this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.setBlendMode(0,!0)},setBlendMode:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.blendModes[t];return!!(e||t!==o.BlendModes.SKIP_CHECK&&this.currentBlendMode!==t)&&(this.flush(),i.enable(i.BLEND),i.blendEquation(n.equation),n.func.length>2?i.blendFuncSeparate(n.func[0],n.func[1],n.func[2],n.func[3]):i.blendFunc(n.func[0],n.func[1]),this.currentBlendMode=t,!0)},addBlendMode:function(t,e){return this.blendModes.push({func:t,equation:e})-1},updateBlendMode:function(t,e,i){return this.blendModes[t]&&(this.blendModes[t].func=e,i&&(this.blendModes[t].equation=i)),this},removeBlendMode:function(t){return t>17&&this.blendModes[t]&&this.blendModes.splice(t,1),this},setBlankTexture:function(t){void 0===t&&(t=!1),!t&&0===this.currentActiveTextureUnit&&this.currentTextures[0]||this.setTexture2D(this.blankTexture.glTexture,0)},setTexture2D:function(t,e,i){void 0===i&&(i=!0);var n=this.gl;return t!==this.currentTextures[e]&&(i&&this.flush(),this.currentActiveTextureUnit!==e&&(n.activeTexture(n.TEXTURE0+e),this.currentActiveTextureUnit=e),n.bindTexture(n.TEXTURE_2D,t),this.currentTextures[e]=t),this},setFramebuffer:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.width,s=this.height;return t!==this.currentFramebuffer&&(t&&t.renderTexture?(n=t.renderTexture.width,s=t.renderTexture.height):this.flush(),i.bindFramebuffer(i.FRAMEBUFFER,t),i.viewport(0,0,n,s),e&&(t?(this.drawingBufferHeight=s,this.pushScissor(0,0,n,s)):(this.drawingBufferHeight=this.height,this.popScissor())),this.currentFramebuffer=t),this},setProgram:function(t){var e=this.gl;return t!==this.currentProgram&&(this.flush(),e.useProgram(t),this.currentProgram=t),this},setVertexBuffer:function(t){var e=this.gl;return t!==this.currentVertexBuffer&&(this.flush(),e.bindBuffer(e.ARRAY_BUFFER,t),this.currentVertexBuffer=t),this},setIndexBuffer:function(t){var e=this.gl;return t!==this.currentIndexBuffer&&(this.flush(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.currentIndexBuffer=t),this},createTextureFromSource:function(t,e,i,n){var s=this.gl,r=s.NEAREST,a=s.NEAREST,l=s.CLAMP_TO_EDGE;e=t?t.width:e,i=t?t.height:i;var u=h(e,i);return u&&(l=s.REPEAT),n===o.ScaleModes.LINEAR&&this.config.antialias&&(r=u?this.mipmapFilter:s.LINEAR,a=s.LINEAR),t||"number"!=typeof e||"number"!=typeof i?this.createTexture2D(0,r,a,l,l,s.RGBA,t):this.createTexture2D(0,r,a,l,l,s.RGBA,null,e,i)},createTexture2D:function(t,e,i,n,s,r,o,a,l,u,c,d){u=void 0===u||null===u||u,void 0===c&&(c=!1),void 0===d&&(d=!1);var f=this.gl,p=f.createTexture();return this.setTexture2D(p,0),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,e),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,i),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,s),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,n),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u),f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,d),null===o||void 0===o?f.texImage2D(f.TEXTURE_2D,t,r,a,l,0,r,f.UNSIGNED_BYTE,null):(c||(a=o.width,l=o.height),f.texImage2D(f.TEXTURE_2D,t,r,r,f.UNSIGNED_BYTE,o)),h(a,l)&&f.generateMipmap(f.TEXTURE_2D),this.setTexture2D(null,0),p.isAlphaPremultiplied=u,p.isRenderTexture=!1,p.width=a,p.height=l,this.nativeTextures.push(p),p},createFramebuffer:function(t,e,i,n){var s,r=this.gl,o=r.createFramebuffer();if(this.setFramebuffer(o),n){var a=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,a),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,a)}if(i.isRenderTexture=!0,i.isAlphaPremultiplied=!1,r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),(s=r.checkFramebufferStatus(r.FRAMEBUFFER))!==r.FRAMEBUFFER_COMPLETE){throw new Error("Framebuffer incomplete. Framebuffer status: "+{36054:"Incomplete Attachment",36055:"Missing Attachment",36057:"Incomplete Dimensions",36061:"Framebuffer Unsupported"}[s])}return o.renderTexture=i,this.setFramebuffer(null),o},createProgram:function(t,e){var i=this.gl,n=i.createProgram(),s=i.createShader(i.VERTEX_SHADER),r=i.createShader(i.FRAGMENT_SHADER);if(i.shaderSource(s,t),i.shaderSource(r,e),i.compileShader(s),i.compileShader(r),!i.getShaderParameter(s,i.COMPILE_STATUS))throw new Error("Failed to compile Vertex Shader:\n"+i.getShaderInfoLog(s));if(!i.getShaderParameter(r,i.COMPILE_STATUS))throw new Error("Failed to compile Fragment Shader:\n"+i.getShaderInfoLog(r));if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw new Error("Failed to link program:\n"+i.getProgramInfoLog(n));return n},createVertexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setVertexBuffer(n),i.bufferData(i.ARRAY_BUFFER,t,e),this.setVertexBuffer(null),n},createIndexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setIndexBuffer(n),i.bufferData(i.ELEMENT_ARRAY_BUFFER,t,e),this.setIndexBuffer(null),n},deleteTexture:function(t){var e=this.nativeTextures.indexOf(t);return-1!==e&&c(this.nativeTextures,e),this.gl.deleteTexture(t),this.currentTextures[0]!==t||this.game.pendingDestroy||this.setBlankTexture(!0),this},deleteFramebuffer:function(t){return this.gl.deleteFramebuffer(t),this},deleteProgram:function(t){return this.gl.deleteProgram(t),this},deleteBuffer:function(t){return this.gl.deleteBuffer(t),this},preRenderCamera:function(t){var e=t._cx,i=t._cy,n=t._cw,r=t._ch,o=this.pipelines.TextureTintPipeline,a=t.backgroundColor;if(t.renderToTexture){this.flush(),this.pushScissor(e,i,n,-r),this.setFramebuffer(t.framebuffer);var h=this.gl;h.clearColor(0,0,0,0),h.clear(h.COLOR_BUFFER_BIT),o.projOrtho(e,n+e,i,r+i,-1e3,1e3),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n+e,r+i,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL),t.emit(s.PRE_RENDER,t)}else this.pushScissor(e,i,n,r),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n,r,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL)},getCurrentStencilMask:function(){var t=null,e=this.maskStack,i=this.currentCameraMask;return e.length>0?t=e[e.length-1]:i.mask&&i.mask.isStencil&&(t=i),t},postRenderCamera:function(t){var e=this.pipelines.TextureTintPipeline;if(t.flashEffect.postRenderWebGL(e,p.getTintFromFloats),t.fadeEffect.postRenderWebGL(e,p.getTintFromFloats),t.dirty=!1,this.popScissor(),t.renderToTexture){if(e.flush(),this.setFramebuffer(null),t.emit(s.POST_RENDER,t),t.renderToGame){e.projOrtho(0,e.width,e.height,0,-1e3,1e3);var i=p.getTintAppendFloatAlpha;(t.pipeline?t.pipeline:e).batchTexture(t,t.glTexture,t.width,t.height,t.x,t.y,t.width,t.height,t.zoom,t.zoom,t.rotation,t.flipX,!t.flipY,1,1,0,0,0,0,t.width,t.height,i(t._tintTL,t._alphaTL),i(t._tintTR,t._alphaTR),i(t._tintBL,t._alphaBL),i(t._tintBR,t._alphaBR),t._isTinted&&t.tintFill,0,0,this.defaultCamera,null)}this.setBlankTexture(!0)}t.mask&&(this.currentCameraMask.mask=null,t.mask.postRenderWebGL(this,t._maskCamera))},preRender:function(){if(!this.contextLost){var t=this.gl,e=this.pipelines;if(t.bindFramebuffer(t.FRAMEBUFFER,null),this.config.clearBeforeRender){var i=this.config.backgroundColor;t.clearColor(i.redGL,i.greenGL,i.blueGL,i.alphaGL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT)}for(var n in t.enable(t.SCISSOR_TEST),e)e[n].onPreRender();this.currentScissor=[0,0,this.width,this.height],this.scissorStack=[this.currentScissor],this.game.scene.customViewports&&t.scissor(0,this.drawingBufferHeight-this.height,this.width,this.height),this.currentMask.mask=null,this.currentCameraMask.mask=null,this.maskStack.length=0,this.setPipeline(this.pipelines.TextureTintPipeline)}},render:function(t,e,i,n){if(!this.contextLost){var s=e.list,r=s.length,a=this.pipelines;for(var h in a)a[h].onRender(t,n);if(this.preRenderCamera(n),0===r)return this.setBlendMode(o.BlendModes.NORMAL),void this.postRenderCamera(n);this.currentType="";for(var l=this.currentMask,u=0;u0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},createVideoTexture:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=this.gl,s=n.NEAREST,r=n.NEAREST,o=t.videoWidth,a=t.videoHeight,l=n.CLAMP_TO_EDGE,u=h(o,a);return!e&&u&&(l=n.REPEAT),this.config.antialias&&(s=u?this.mipmapFilter:n.LINEAR,r=n.LINEAR),this.createTexture2D(0,s,r,l,l,n.RGBA,t,o,a,!0,!0,i)},updateVideoTexture:function(t,e,i){void 0===i&&(i=!1);var n=this.gl,s=t.videoWidth,r=t.videoHeight;return s>0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},setTextureFilter:function(t,e){var i=this.gl,n=[i.LINEAR,i.NEAREST][e];return this.setTexture2D(t,0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,n),this.setTexture2D(null,0),this},setFloat1:function(t,e,i){return this.setProgram(t),this.gl.uniform1f(this.gl.getUniformLocation(t,e),i),this},setFloat2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2f(this.gl.getUniformLocation(t,e),i,n),this},setFloat3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3f(this.gl.getUniformLocation(t,e),i,n,s),this},setFloat4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4f(this.gl.getUniformLocation(t,e),i,n,s,r),this},setFloat1v:function(t,e,i){return this.setProgram(t),this.gl.uniform1fv(this.gl.getUniformLocation(t,e),i),this},setFloat2v:function(t,e,i){return this.setProgram(t),this.gl.uniform2fv(this.gl.getUniformLocation(t,e),i),this},setFloat3v:function(t,e,i){return this.setProgram(t),this.gl.uniform3fv(this.gl.getUniformLocation(t,e),i),this},setFloat4v:function(t,e,i){return this.setProgram(t),this.gl.uniform4fv(this.gl.getUniformLocation(t,e),i),this},setInt1:function(t,e,i){return this.setProgram(t),this.gl.uniform1i(this.gl.getUniformLocation(t,e),i),this},setInt2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2i(this.gl.getUniformLocation(t,e),i,n),this},setInt3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3i(this.gl.getUniformLocation(t,e),i,n,s),this},setInt4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4i(this.gl.getUniformLocation(t,e),i,n,s,r),this},setMatrix2:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix2fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix3:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix3fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix4:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix4fv(this.gl.getUniformLocation(t,e),i,n),this},getMaxTextures:function(){return this.config.maxTextures},getMaxTextureSize:function(){return this.config.maxTextureSize},destroy:function(){for(var t=0;t0&&this.flush();var e=this.inverseRotationMatrix;if(t){var i=-t,n=Math.cos(i),s=Math.sin(i);e[1]=s,e[3]=-s,e[0]=e[4]=n}else e[0]=e[4]=1,e[1]=e[3]=0;this.renderer.setMatrix3(this.program,"uInverseRotationMatrix",!1,e),this.currentNormalMapRotation=t}},batchSprite:function(t,e,i){if(this.active){var n=t.texture.dataSource[t.frame.sourceIndex];n&&(this.renderer.setPipeline(this),this.setTexture2D(n.glTexture,1),this.setNormalMapRotation(t.rotation),r.prototype.batchSprite.call(this,t,e,i))}}});a.LIGHT_COUNT=o,t.exports=a},function(t,e,i){var n=i(0),s=i(2),r=i(233),o=i(335),a=i(336),h=i(30),l=i(141),u=new n({Extends:l,Mixins:[r],initialize:function(t){var e=t.renderer.config;l.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:t.renderer.gl.TRIANGLE_STRIP,vertShader:s(t,"vertShader",a),fragShader:s(t,"fragShader",o),vertexCapacity:s(t,"vertexCapacity",6*e.batchSize),vertexSize:s(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new h,this._tempMatrix2=new h,this._tempMatrix3=new h,this.mvpInit()},onBind:function(){return l.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return l.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this}});t.exports=u},,,,,function(t,e){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(t){"object"==typeof window&&(i=window)}t.exports=i},function(t,e,i){i(514),i(515),i(516),i(517),i(518),i(519),i(520),i(521)},function(t,e){Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var n=arguments.length>=2?arguments[1]:void 0,s=0;s>16)+(65280&t)+((255&t)<<16)},n={_tintTL:16777215,_tintTR:16777215,_tintBL:16777215,_tintBR:16777215,_isTinted:!1,tintFill:!1,clearTint:function(){return this.setTint(16777215),this._isTinted=!1,this},setTint:function(t,e,n,s){return void 0===t&&(t=16777215),void 0===e&&(e=t,n=t,s=t),this._tintTL=i(t),this._tintTR=i(e),this._tintBL=i(n),this._tintBR=i(s),this._isTinted=!0,this.tintFill=!1,this},setTintFill:function(t,e,i,n){return this.setTint(t,e,i,n),this.tintFill=!0,this},tintTopLeft:{get:function(){return this._tintTL},set:function(t){this._tintTL=i(t),this._isTinted=!0}},tintTopRight:{get:function(){return this._tintTR},set:function(t){this._tintTR=i(t),this._isTinted=!0}},tintBottomLeft:{get:function(){return this._tintBL},set:function(t){this._tintBL=i(t),this._isTinted=!0}},tintBottomRight:{get:function(){return this._tintBR},set:function(t){this._tintBR=i(t),this._isTinted=!0}},tint:{set:function(t){this.setTint(t,t,t,t)}},isTinted:{get:function(){return this._isTinted}}};t.exports=n},function(t,e){t.exports="changedata"},function(t,e){t.exports="changedata-"},function(t,e){t.exports="removedata"},function(t,e){t.exports="setdata"},function(t,e){t.exports="destroy"},function(t,e){t.exports="complete"},function(t,e){t.exports="created"},function(t,e){t.exports="error"},function(t,e){t.exports="loop"},function(t,e){t.exports="play"},function(t,e){t.exports="seeked"},function(t,e){t.exports="seeking"},function(t,e){t.exports="stop"},function(t,e){t.exports="timeout"},function(t,e){t.exports="unlocked"},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"alpha",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"x",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r,o,a){return void 0!==i&&null!==i||(i=e),n(t,"x",e,s,o,a),n(t,"y",i,r,o,a)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"y",e,i,s,r)}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=6.28);for(var s=i,r=(n-i)/t.length,o=0;o0?s(o,i):i<0&&r(o,Math.abs(i));for(var a=0;a1)if(0===s){var d=t.length-1;for(o=t[d].x,a=t[d].y,h=d-1;h>=0;h--)l=(c=t[h]).x,u=c.y,c.x=o,c.y=a,o=l,a=u;t[d].x=e,t[d].y=i}else{for(o=t[0].x,a=t[0].y,h=1;h0?(this._speedX-=this.dragX*t,this._speedX<0&&(this._speedX=0)):this._speedX<0&&(this._speedX+=this.dragX*t,this._speedX>0&&(this._speedX=0)),this._speedY>0?(this._speedY-=this.dragY*t,this._speedY<0&&(this._speedY=0)):this._speedY<0&&(this._speedY+=this.dragY*t,this._speedY>0&&(this._speedY=0)),this.up&&this.up.isDown?(this._speedY+=this.accelY,this._speedY>this.maxSpeedY&&(this._speedY=this.maxSpeedY)):this.down&&this.down.isDown&&(this._speedY-=this.accelY,this._speedY<-this.maxSpeedY&&(this._speedY=-this.maxSpeedY)),this.left&&this.left.isDown?(this._speedX+=this.accelX,this._speedX>this.maxSpeedX&&(this._speedX=this.maxSpeedX)):this.right&&this.right.isDown&&(this._speedX-=this.accelX,this._speedX<-this.maxSpeedX&&(this._speedX=-this.maxSpeedX)),this.zoomIn&&this.zoomIn.isDown?this._zoom=-this.zoomSpeed:this.zoomOut&&this.zoomOut.isDown?this._zoom=this.zoomSpeed:this._zoom=0,0!==this._speedX&&(e.scrollX-=this._speedX*t|0),0!==this._speedY&&(e.scrollY-=this._speedY*t|0),0!==this._zoom&&(e.zoom+=this._zoom,e.zoom<.001&&(e.zoom=.001))}},destroy:function(){this.camera=null,this.left=null,this.right=null,this.up=null,this.down=null,this.zoomIn=null,this.zoomOut=null}});t.exports=r},function(t,e,i){t.exports={Camera:i(288),BaseCamera:i(89),CameraManager:i(694),Effects:i(296),Events:i(48)}},function(t,e){t.exports="cameradestroy"},function(t,e){t.exports="camerafadeincomplete"},function(t,e){t.exports="camerafadeinstart"},function(t,e){t.exports="camerafadeoutcomplete"},function(t,e){t.exports="camerafadeoutstart"},function(t,e){t.exports="cameraflashcomplete"},function(t,e){t.exports="cameraflashstart"},function(t,e){t.exports="camerapancomplete"},function(t,e){t.exports="camerapanstart"},function(t,e){t.exports="postrender"},function(t,e){t.exports="prerender"},function(t,e){t.exports="camerashakecomplete"},function(t,e){t.exports="camerashakestart"},function(t,e){t.exports="camerazoomcomplete"},function(t,e){t.exports="camerazoomstart"},function(t,e,i){var n=i(23),s=i(0),r=i(48),o=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.isComplete=!1,this.direction=!0,this.duration=0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this.progress=0,this._elapsed=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s,o,a,h){if(void 0===t&&(t=!0),void 0===e&&(e=1e3),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=0),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===h&&(h=this.camera.scene),!o&&this.isRunning)return this.camera;this.isRunning=!0,this.isComplete=!1,this.duration=e,this.direction=t,this.progress=0,this.red=i,this.green=n,this.blue=s,this.alpha=t?Number.MIN_VALUE:1,this._elapsed=0,this._onUpdate=a,this._onUpdateScope=h;var l=t?r.FADE_OUT_START:r.FADE_IN_START;return this.camera.emit(l,this.camera,this,e,i,n,s),this.camera},update:function(t,e){this.isRunning&&(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed=1?1:1/e*(1+(e*t|0))}},function(t,e,i){var n=i(23),s=i(0),r=i(48),o=i(3),a=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.duration=0,this.intensity=new o,this.progress=0,this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s){return void 0===t&&(t=100),void 0===e&&(e=.05),void 0===i&&(i=!1),void 0===n&&(n=null),void 0===s&&(s=this.camera.scene),!i&&this.isRunning?this.camera:(this.isRunning=!0,this.duration=t,this.progress=0,"number"==typeof e?this.intensity.set(e):this.intensity.set(e.x,e.y),this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate=n,this._onUpdateScope=s,this.camera.emit(r.SHAKE_START,this.camera,this,t,e),this.camera)},preRender:function(){this.isRunning&&this.camera.matrix.translate(this._offsetX,this._offsetY)},update:function(t,e){if(this.isRunning)if(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed0&&(o.preRender(1),t.render(n,e,i,o))}},resetAll:function(){for(var t=0;t1)for(var i=1;i=1)&&(s.touch=!0),(navigator.msPointerEnabled||navigator.pointerEnabled)&&(s.mspointer=!0),navigator.getGamepads&&(s.gamepads=!0),"onwheel"in window||n.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":n.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"),s)},function(t,e,i){var n=i(113),s={audioData:!1,dolby:!1,m4a:!1,mp3:!1,ogg:!1,opus:!1,wav:!1,webAudio:!1,webm:!1};t.exports=function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio"),e=!!t.canPlayType;try{if(e&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(n.edge)s.dolby=!0;else if(n.safari&&n.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var i=parseInt(RegExp.$1,10),r=parseInt(RegExp.$2,10);(10===i&&r>=11||i>10)&&(s.dolby=!0)}}catch(t){}return s}()},function(t,e){var i={h264:!1,hls:!1,mp4:!1,ogg:!1,vp9:!1,webm:!1};t.exports=function(){var t=document.createElement("video"),e=!!t.canPlayType;try{e&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(i.ogg=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.h264=!0,i.mp4=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(i.webm=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(i.vp9=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.hls=!0))}catch(t){}return i}()},function(t,e){var i={available:!1,cancel:"",keyboard:!1,request:""};t.exports=function(){var t,e="Fullscreen",n="FullScreen",s=["request"+e,"request"+n,"webkitRequest"+e,"webkitRequest"+n,"msRequest"+e,"msRequest"+n,"mozRequest"+n,"mozRequest"+e];for(t=0;tMath.PI&&(t-=n.PI2),Math.abs(((t+n.TAU)%n.PI2-n.PI2)%n.PI2)}},function(t,e,i){var n=i(313);t.exports=function(t){return n(t+Math.PI)}},function(t,e,i){var n=i(16);t.exports=function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=i:e1?t[i]-(n(s-i,t[i],t[i],t[i-1],t[i-1])-t[i]):n(s-r,t[r?r-1:0],t[r],t[i1?n(t[i],t[i-1],i-s):n(t[r],t[r+1>i?i:r+1],s-r)}},function(t,e,i){var n=i(154);t.exports=function(t,e,i){return e+(i-e)*n(t,0,1)}},function(t,e,i){t.exports={GetNext:i(323),IsSize:i(114),IsValue:i(749)}},function(t,e){t.exports=function(t){return t>0&&0==(t&t-1)}},function(t,e,i){t.exports={Ceil:i(324),Floor:i(91),To:i(751)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){void 0===t&&(t=[(Date.now()*Math.random()).toString()]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.n=0,this.signs=[-1,1],t&&this.init(t)},rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},hash:function(t){var e,i=this.n;t=t.toString();for(var n=0;n>>0,i=(e*=i)>>>0,i+=4294967296*(e-=i);return this.n=i,2.3283064365386963e-10*(i>>>0)},init:function(t){"string"==typeof t?this.state(t):this.sow(t)},sow:function(t){if(this.n=4022871197,this.s0=this.hash(" "),this.s1=this.hash(" "),this.s2=this.hash(" "),this.c=1,t)for(var e=0;e0;e--){var i=Math.floor(this.frac()*(e+1)),n=t[i];t[i]=t[e],t[e]=n}return t}});t.exports=n},function(t,e){t.exports=function(t){for(var e=0,i=0;i1?void 0!==n?(s=(n-t)/(n-i))<0&&(s=0):s=1:s<0&&(s=0),s}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI;return t.x=Math.cos(i)*e,t.y=Math.sin(i)*e,t}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI,n=2*Math.random()-1,s=Math.sqrt(1-n*n)*e;return t.x=Math.cos(i)*s,t.y=Math.sin(i)*s,t.z=n*e,t}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=1),t.x=(2*Math.random()-1)*e,t.y=(2*Math.random()-1)*e,t.z=(2*Math.random()-1)*e,t.w=(2*Math.random()-1)*e,t}},function(t,e){t.exports=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var n=Math.pow(i,-e);return Math.round(t*n)/n}},function(t,e){t.exports=function(t,e,i,n){void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=1),n*=Math.PI/t;for(var s=[],r=[],o=0;o0&&t<=e*i&&(r=t>e-1?t-(o=Math.floor(t/e))*e:t,s.set(r,o)),s}},function(t,e){t.exports=function(t,e,i){return Math.abs(t-e)<=i}},function(t,e,i){var n=i(169),s=i(331),r=i(332),o=new s,a=new r,h=new n;t.exports=function(t,e,i){return a.setAxisAngle(e,i),o.fromRotationTranslation(a,h.set(0,0,0)),t.transformMat4(o)}},function(t,e){t.exports="addtexture"},function(t,e){t.exports="onerror"},function(t,e){t.exports="onload"},function(t,e){t.exports="ready"},function(t,e){t.exports="removetexture"},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_FS","","precision mediump float;","","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uMaskSampler;","uniform bool uInvertMaskAlpha;","","void main()","{"," vec2 uv = gl_FragCoord.xy / uResolution;"," vec4 mainColor = texture2D(uMainSampler, uv);"," vec4 maskColor = texture2D(uMaskSampler, uv);"," float alpha = mainColor.a;",""," if (!uInvertMaskAlpha)"," {"," alpha *= (maskColor.a);"," }"," else"," {"," alpha *= (1.0 - maskColor.a);"," }",""," gl_FragColor = vec4(mainColor.rgb * alpha, alpha);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_VS","","precision mediump float;","","attribute vec2 inPosition;","","void main()","{"," gl_Position = vec4(inPosition, 0.0, 1.0);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS","","precision mediump float;","","struct Light","{"," vec2 position;"," vec3 color;"," float intensity;"," float radius;","};","","const int kMaxLights = %LIGHT_COUNT%;","","uniform vec4 uCamera; /* x, y, rotation, zoom */","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uNormSampler;","uniform vec3 uAmbientLightColor;","uniform Light uLights[kMaxLights];","uniform mat3 uInverseRotationMatrix;","","varying vec2 outTexCoord;","varying vec4 outTint;","","void main()","{"," vec3 finalColor = vec3(0.0, 0.0, 0.0);"," vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);"," vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;"," vec3 normal = normalize(uInverseRotationMatrix * vec3(normalMap * 2.0 - 1.0));"," vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;",""," for (int index = 0; index < kMaxLights; ++index)"," {"," Light light = uLights[index];"," vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);"," vec3 lightNormal = normalize(lightDir);"," float distToSurf = length(lightDir) * uCamera.w;"," float diffuseFactor = max(dot(normal, lightNormal), 0.0);"," float radius = (light.radius / res.x * uCamera.w) * uCamera.w;"," float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);"," vec3 diffuse = light.color * diffuseFactor;"," finalColor += (attenuation * diffuse) * light.intensity;"," }",""," vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);"," gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);","","}",""].join("\n")},function(t,e,i){t.exports={GenerateTexture:i(341),Palettes:i(780)}},function(t,e,i){t.exports={ARNE16:i(342),C64:i(781),CGA:i(782),JMP:i(783),MSX:i(784)}},function(t,e){t.exports={0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"}},function(t,e){t.exports={0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}},function(t,e,i){t.exports={Path:i(786),CubicBezier:i(343),Curve:i(79),Ellipse:i(344),Line:i(345),QuadraticBezier:i(346),Spline:i(347)}},function(t,e,i){var n=i(0),s=i(343),r=i(344),o=i(5),a=i(345),h=i(787),l=i(346),u=i(13),c=i(347),d=i(3),f=i(16),p=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.name="",this.curves=[],this.cacheLengths=[],this.autoClose=!1,this.startPoint=new d,this._tmpVec2A=new d,this._tmpVec2B=new d,"object"==typeof t?this.fromJSON(t):this.startPoint.set(t,e)},add:function(t){return this.curves.push(t),this},circleTo:function(t,e,i){return void 0===e&&(e=!1),this.ellipseTo(t,t,0,360,e,i)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);return t.equals(e)||this.curves.push(new a(e,t)),this},cubicBezierTo:function(t,e,i,n,r,o){var a,h,l,u=this.getEndPoint();return t instanceof d?(a=t,h=e,l=i):(a=new d(i,n),h=new d(r,o),l=new d(t,e)),this.add(new s(u,a,h,l))},quadraticBezierTo:function(t,e,i,n){var s,r,o=this.getEndPoint();return t instanceof d?(s=t,r=e):(s=new d(i,n),r=new d(t,e)),this.add(new l(o,s,r))},draw:function(t,e){for(var i=0;i0?this.curves[this.curves.length-1].getPoint(1,t):t.copy(this.startPoint),t},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},getPoint:function(t,e){void 0===e&&(e=new d);for(var i=t*this.getLength(),n=this.getCurveLengths(),s=0;s=i){var r=n[s]-i,o=this.curves[s],a=o.getLength(),h=0===a?0:1-r/a;return o.getPointAt(h,e)}s++}return null},getPoints:function(t){void 0===t&&(t=12);for(var e,i=[],n=0;n1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},getRandomPoint:function(t){return void 0===t&&(t=new d),this.getPoint(Math.random(),t)},getSpacedPoints:function(t){void 0===t&&(t=40);for(var e=[],i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e},getStartPoint:function(t){return void 0===t&&(t=new d),t.copy(this.startPoint)},lineTo:function(t,e){t instanceof d?this._tmpVec2B.copy(t):this._tmpVec2B.set(t,e);var i=this.getEndPoint(this._tmpVec2A);return this.add(new a([i.x,i.y,this._tmpVec2B.x,this._tmpVec2B.y]))},splineTo:function(t){return t.unshift(this.getEndPoint()),this.add(new c(t))},moveTo:function(t,e){return t instanceof d?this.add(new h(t.x,t.y)):this.add(new h(t,e))},toJSON:function(){for(var t=[],e=0;e>16&255,g:t>>8&255,b:255&t,a:255};return t>16777215&&(e.a=t>>>24),e}},function(t,e,i){var n=i(32),s=i(351);t.exports=function(t,e,i){var r=i,o=i,a=i;if(0!==e){var h=i<.5?i*(1+e):i+e-i*e,l=2*i-h;r=s(l,h,t+1/3),o=s(l,h,t),a=s(l,h,t-1/3)}return(new n).setGLTo(r,o,a,1)}},function(t,e,i){var n=i(160);t.exports=function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n(s/359,t,e));return i}},function(t,e,i){var n=i(111),s=function(t,e,i,s,r,o,a,h){void 0===a&&(a=100),void 0===h&&(h=0);var l=h/a;return{r:n(t,s,l),g:n(e,r,l),b:n(i,o,l)}};t.exports={RGBWithRGB:s,ColorWithRGB:function(t,e,i,n,r,o){return void 0===r&&(r=100),void 0===o&&(o=0),s(t.r,t.g,t.b,e,i,n,r,o)},ColorWithColor:function(t,e,i,n){return void 0===i&&(i=100),void 0===n&&(n=0),s(t.r,t.g,t.b,e.r,e.g,e.b,i,n)}}},function(t,e,i){var n=i(167),s=i(32);t.exports=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=255),new s(n(t,e),n(t,e),n(t,e))}},function(t,e,i){var n=i(350);t.exports=function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n(s)+n(t)+n(e)+n(i)}},function(t,e,i){t.exports={BitmapMask:i(273),GeometryMask:i(274)}},function(t,e,i){var n={AddToDOM:i(116),DOMContentLoaded:i(352),GetScreenOrientation:i(353),GetTarget:i(358),ParseXML:i(359),RemoveFromDOM:i(173),RequestAnimationFrame:i(339)};t.exports=n},function(t,e,i){t.exports={EventEmitter:i(809)}},function(t,e,i){var n=i(0),s=i(11),r=i(24),o=new n({Extends:s,initialize:function(){s.call(this)},shutdown:function(){this.removeAllListeners()},destroy:function(){this.removeAllListeners()}});r.register("EventEmitter",o,"events"),t.exports=o},function(t,e,i){var n=i(116),s=i(284),r=i(287),o=i(27),a=i(0),h=i(309),l=i(811),u=i(333),c=i(109),d=i(337),f=i(310),p=i(352),g=i(11),v=i(19),m=i(360),y=i(24),x=i(365),T=i(366),w=i(368),E=i(115),_=i(371),A=i(338),b=i(340),S=i(375),C=new a({initialize:function(t){this.config=new h(t),this.renderer=null,this.domContainer=null,this.canvas=null,this.context=null,this.isBooted=!1,this.isRunning=!1,this.events=new g,this.anims=new s(this),this.textures=new _(this),this.cache=new r(this),this.registry=new c(this),this.input=new m(this,this.config),this.scene=new w(this,this.config.sceneConfig),this.device=f,this.scale=new T(this,this.config),this.sound=null,this.sound=S.create(this),this.loop=new A(this,this.config.fps),this.plugins=new x(this,this.config),this.pendingDestroy=!1,this.removeCanvas=!1,this.noReturn=!1,this.hasFocus=!1,p(this.boot.bind(this))},boot:function(){y.hasCore("EventEmitter")?(this.isBooted=!0,this.config.preBoot(this),this.scale.preBoot(),u(this),l(this),d(this),n(this.canvas,this.config.parent),this.textures.once(E.READY,this.texturesReady,this),this.events.emit(v.BOOT)):console.warn("Aborting. Core Plugins missing.")},texturesReady:function(){this.events.emit(v.READY),this.start()},start:function(){this.isRunning=!0,this.config.postBoot(this),this.renderer?this.loop.start(this.step.bind(this)):this.loop.start(this.headlessStep.bind(this)),b(this);var t=this.events;t.on(v.HIDDEN,this.onHidden,this),t.on(v.VISIBLE,this.onVisible,this),t.on(v.BLUR,this.onBlur,this),t.on(v.FOCUS,this.onFocus,this)},step:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e);var n=this.renderer;n.preRender(),i.emit(v.PRE_RENDER,n,t,e),this.scene.render(n),n.postRender(),i.emit(v.POST_RENDER,n,t,e)},headlessStep:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e),i.emit(v.PRE_RENDER),i.emit(v.POST_RENDER)},onHidden:function(){this.loop.pause(),this.events.emit(v.PAUSE)},onVisible:function(){this.loop.resume(),this.events.emit(v.RESUME)},onBlur:function(){this.hasFocus=!1,this.loop.blur()},onFocus:function(){this.hasFocus=!0,this.loop.focus()},getFrame:function(){return this.loop.frame},getTime:function(){return this.loop.now},destroy:function(t,e){void 0===e&&(e=!1),this.pendingDestroy=!0,this.removeCanvas=t,this.noReturn=e},runDestroy:function(){this.scene.destroy(),this.events.emit(v.DESTROY),this.events.removeAllListeners(),this.renderer&&this.renderer.destroy(),this.removeCanvas&&this.canvas&&(o.remove(this.canvas),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)),this.domContainer&&this.domContainer.parentNode.removeChild(this.domContainer),this.loop.destroy(),this.pendingDestroy=!1}});t.exports=C},function(t,e,i){var n=i(116);t.exports=function(t){var e=t.config;if(e.parent&&e.domCreateContainer){var i=document.createElement("div");i.style.cssText=["display: block;","width: "+t.scale.width+"px;","height: "+t.scale.height+"px;","padding: 0; margin: 0;","position: absolute;","overflow: hidden;","pointer-events: none;","transform: scale(1);","transform-origin: left top;"].join(" "),t.domContainer=i,n(i,e.parent)}}},function(t,e){t.exports="boot"},function(t,e){t.exports="destroy"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameout"},function(t,e){t.exports="gameover"},function(t,e){t.exports="gameobjectdown"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameobjectmove"},function(t,e){t.exports="gameobjectout"},function(t,e){t.exports="gameobjectover"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="wheel"},function(t,e){t.exports="gameobjectup"},function(t,e){t.exports="gameobjectwheel"},function(t,e){t.exports="boot"},function(t,e){t.exports="process"},function(t,e){t.exports="update"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointerdownoutside"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="pointerupoutside"},function(t,e){t.exports="wheel"},function(t,e){t.exports="pointerlockchange"},function(t,e){t.exports="preupdate"},function(t,e){t.exports="shutdown"},function(t,e){t.exports="start"},function(t,e){t.exports="update"},function(t,e){t.exports=function(t){if(!t)return window.innerHeight;var e=Math.abs(window.orientation),i={w:0,h:0},n=document.createElement("div");return n.setAttribute("style","position: fixed; height: 100vh; width: 0; top: 0"),document.documentElement.appendChild(n),i.w=90===e?n.offsetHeight:window.innerWidth,i.h=90===e?window.innerWidth:n.offsetHeight,document.documentElement.removeChild(n),n=null,90!==Math.abs(window.orientation)?i.h:i.w}},function(t,e){t.exports="addfile"},function(t,e){t.exports="complete"},function(t,e){t.exports="filecomplete"},function(t,e){t.exports="filecomplete-"},function(t,e){t.exports="loaderror"},function(t,e){t.exports="load"},function(t,e){t.exports="fileprogress"},function(t,e){t.exports="postprocess"},function(t,e){t.exports="progress"},function(t,e){t.exports="start"},function(t,e,i){var n=i(2),s=i(176);t.exports=function(t){var e=t.game.config.defaultPhysicsSystem,i=n(t.settings,"physics",!1);if(e||i){var r=[];if(e&&r.push(s(e+"Physics")),i)for(var o in i)o=s(o.concat("Physics")),-1===r.indexOf(o)&&r.push(o);return r}}},function(t,e,i){var n=i(2);t.exports=function(t){var e=t.plugins.getDefaultScenePlugins(),i=n(t.settings,"plugins",!1);return Array.isArray(i)?i:e||[]}},function(t,e,i){t.exports={game:"game",anims:"anims",cache:"cache",plugins:"plugins",registry:"registry",scale:"scale",sound:"sound",textures:"textures",events:"events",cameras:"cameras",add:"add",make:"make",scenePlugin:"scene",displayList:"children",lights:"lights",data:"data",input:"input",load:"load",time:"time",tweens:"tweens",arcadePhysics:"physics",impactPhysics:"impact",matterPhysics:"matter"}},function(t,e){t.exports=function(t,e,i){if(i.getElementsByTagName("TextureAtlas")){var n=t.source[e];t.add("__BASE",e,0,0,n.width,n.height);for(var s,r=i.getElementsByTagName("SubTexture"),o=0;og||c<-g)&&(c=0),c<0&&(c=g+c),-1!==d&&(g=c+(d+1));for(var v=f,m=f,y=0,x=0,T=0;Tr&&(y=w-r),E>o&&(x=E-o),t.add(T,e,i+v,s+m,h-y,l-x),(v+=h+p)+h>r&&(v=f,m+=l+p)}return t}},function(t,e,i){var n=i(2);t.exports=function(t,e,i){var s=n(i,"frameWidth",null),r=n(i,"frameHeight",s);if(!s)throw new Error("TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.");var o=t.source[0];t.add("__BASE",0,0,0,o.width,o.height);var a,h=n(i,"startFrame",0),l=n(i,"endFrame",-1),u=n(i,"margin",0),c=n(i,"spacing",0),d=e.cutX,f=e.cutY,p=e.cutWidth,g=e.cutHeight,v=e.realWidth,m=e.realHeight,y=Math.floor((v-u+c)/(s+c)),x=Math.floor((m-u+c)/(r+c)),T=y*x,w=e.x,E=s-w,_=s-(v-p-w),A=e.y,b=r-A,S=r-(m-g-A);(h>T||h<-T)&&(h=0),h<0&&(h=T+h),-1!==l&&(T=h+(l+1));for(var C=u,M=u,O=0,P=e.sourceIndex,R=0;R0){var r=i-t.length;if(r<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.push(e),n&&n.call(s,e),e):null;for(var o=e.length-1;o>=0;)-1!==t.indexOf(e[o])&&e.splice(o,1),o--;if(0===(o=e.length))return null;i>0&&o>r&&(e.splice(r),o=r);for(var a=0;a0){var o=n-t.length;if(o<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.splice(i,0,e),s&&s.call(r,e),e):null;for(var a=e.length-1;a>=0;)-1!==t.indexOf(e[a])&&e.pop(),a--;if(0===(a=e.length))return null;n>0&&a>o&&(e.splice(o),a=o);for(var h=a-1;h>=0;h--){var l=e[h];t.splice(i,0,l),s&&s.call(r,l)}return e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);return-1!==i&&i0){var n=t[i-1],s=t.indexOf(n);t[i]=n,t[s]=e}return t}},function(t,e){t.exports=function(t,e,i){var n=t.indexOf(e);if(-1===n||i<0||i>=t.length)throw new Error("Supplied index out of bounds");return n!==i&&(t.splice(n,1),t.splice(i,0,e)),e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);if(-1!==i&&it.length-1)throw new Error("Index out of bounds");var r=n(t,e);return i&&i.call(s,r),r}},function(t,e,i){var n=i(66);t.exports=function(t,e,i,s,r){if(void 0===e&&(e=0),void 0===i&&(i=t.length),void 0===r&&(r=t),n(t,e,i)){var o=i-e,a=t.splice(e,o);if(s)for(var h=0;h0&&(t.splice(i,1),t.unshift(e)),e}},function(t,e,i){var n=i(66);t.exports=function(t,e,i,s,r){if(void 0===s&&(s=0),void 0===r&&(r=t.length),n(t,s,r))for(var o=s;o0){for(n=0;nl||U-B>l?(N.push(X.i-1),X.cr?(N.push(X.i+X.word.length),B=0,Y=null):Y=X):X.cr&&(N.push(X.i+X.word.length),B=0,Y=null)}for(n=N.length-1;n>=0;n--)s=a,r=N[n],o="\n",a=s.substr(0,r)+o+s.substr(r+1);i.wrappedText=a,h=a.length,F=[],k=null}for(n=0;nE&&(c=E),d>_&&(d=_);var W=E+w.xAdvance,H=_+v;fR&&(R=D),DR&&(R=D),D0&&(a=(o=z.wrappedText).length);var U=e._bounds.lines;1===B?X=(U.longest-U.lengths[0])/2:2===B&&(X=U.longest-U.lengths[0]);for(var G=s.roundPixels,W=0;W0&&(a=(o=L.wrappedText).length);var D=e._bounds.lines;1===O?R=(D.longest-D.lengths[0])/2:2===O&&(R=D.longest-D.lengths[0]),h.translate(-e.displayOriginX,-e.displayOriginY);for(var F=s.roundPixels,k=0;k0!=t>0,this._alpha=t}}});t.exports=r},function(t,e,i){var n=i(1),s=i(1);n=i(946),s=i(947),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){var r=e.list;if(0!==r.length){var o=e.localTransform;s?(o.loadIdentity(),o.multiply(s),o.translate(e.x,e.y),o.rotate(e.rotation),o.scale(e.scaleX,e.scaleY)):o.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);var a=-1!==e.blendMode;a||t.setBlendMode(0);for(var h=e.alpha,l=e.scrollFactorX,u=e.scrollFactorY,c=r,d=r.length,f=0;f0||e.cropHeight>0;l&&(h.flush(),t.pushScissor(e.x,e.y,e.cropWidth*e.scaleX,e.cropHeight*e.scaleY));var u=h._tempMatrix1,c=h._tempMatrix2,d=h._tempMatrix3,f=h._tempMatrix4;c.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),u.copyFrom(s.matrix),r?(u.multiplyWithOffset(r,-s.scrollX*e.scrollFactorX,-s.scrollY*e.scrollFactorY),c.e=e.x,c.f=e.y,u.multiply(c,d)):(c.e-=s.scrollX*e.scrollFactorX,c.f-=s.scrollY*e.scrollFactorY,u.multiply(c,d));var p=e.frame,g=p.glTexture,v=p.cutX,m=p.cutY,y=g.width,x=g.height,T=e._isTinted&&e.tintFill,w=n.getTintAppendFloatAlpha(e._tintTL,s.alpha*e._alphaTL),E=n.getTintAppendFloatAlpha(e._tintTR,s.alpha*e._alphaTR),_=n.getTintAppendFloatAlpha(e._tintBL,s.alpha*e._alphaBL),A=n.getTintAppendFloatAlpha(e._tintBR,s.alpha*e._alphaBR);h.setTexture2D(g,0);var b,S,C=0,M=0,O=0,P=0,R=e.letterSpacing,L=0,D=0,F=0,k=0,I=e.scrollX,Y=e.scrollY,B=e.fontData,N=B.chars,X=B.lineHeight,z=e.fontSize/B.size,U=0,G=e._align,W=0,H=0;e.getTextBounds(!1);var V=e._bounds.lines;1===G?H=(V.longest-V.lengths[0])/2:2===G&&(H=V.longest-V.lengths[0]);for(var j=s.roundPixels,K=e.displayCallback,q=e.callbackData,J=0;J0&&e.cropHeight>0&&(h.beginPath(),h.rect(0,0,e.cropWidth,e.cropHeight),h.clip());for(var B=0;B0&&(N=N%E-E):N>E?N=E:N<0&&(N=E+N%E),null===S&&(S=new o(k+Math.cos(B)*Y,I+Math.sin(B)*Y,v),_.push(S),F+=.01);F<1+z;)w=N*F+B,x=k+Math.cos(w)*Y,T=I+Math.sin(w)*Y,S.points.push(new r(x,T,v)),F+=.01;w=N+B,x=k+Math.cos(w)*Y,T=I+Math.sin(w)*Y,S.points.push(new r(x,T,v));break;case n.FILL_RECT:u.setTexture2D(M),u.batchFillRect(p[++O],p[++O],p[++O],p[++O],f,c);break;case n.FILL_TRIANGLE:u.setTexture2D(M),u.batchFillTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],f,c);break;case n.STROKE_TRIANGLE:u.setTexture2D(M),u.batchStrokeTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],v,f,c);break;case n.LINE_TO:null!==S?S.points.push(new r(p[++O],p[++O],v)):(S=new o(p[++O],p[++O],v),_.push(S));break;case n.MOVE_TO:S=new o(p[++O],p[++O],v),_.push(S);break;case n.SAVE:a.push(f.copyToArray());break;case n.RESTORE:f.copyFromArray(a.pop());break;case n.TRANSLATE:k=p[++O],I=p[++O],f.translate(k,I);break;case n.SCALE:k=p[++O],I=p[++O],f.scale(k,I);break;case n.ROTATE:f.rotate(p[++O]);break;case n.SET_TEXTURE:var U=p[++O],G=p[++O];u.currentFrame=U,u.setTexture2D(U.glTexture,0),u.tintEffect=G,M=U.glTexture;break;case n.CLEAR_TEXTURE:u.currentFrame=t.blankTexture,u.tintEffect=2,M=t.blankTexture.glTexture}}}},function(t,e,i){var n=i(1),s=i(1);n=i(959),s=i(960),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(1),s=i(1);n=i(962),s=i(963),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){t.exports={GravityWell:i(395),Particle:i(396),ParticleEmitter:i(397),ParticleEmitterManager:i(189),Zones:i(969)}},function(t,e,i){var n=i(0),s=i(325),r=i(67),o=i(2),a=i(58),h=new n({initialize:function(t,e,i,n){void 0===n&&(n=!1),this.propertyKey=e,this.propertyValue=i,this.defaultValue=i,this.steps=0,this.counter=0,this.start=0,this.end=0,this.ease,this.emitOnly=n,this.onEmit=this.defaultEmit,this.onUpdate=this.defaultUpdate,this.loadConfig(t)},loadConfig:function(t,e){void 0===t&&(t={}),e&&(this.propertyKey=e),this.propertyValue=o(t,this.propertyKey,this.defaultValue),this.setMethods(),this.emitOnly&&(this.onUpdate=this.defaultUpdate)},toJSON:function(){return this.propertyValue},onChange:function(t){return this.propertyValue=t,this.setMethods()},setMethods:function(){var t=this.propertyValue,e=typeof t;if("number"===e)this.onEmit=this.staticValueEmit,this.onUpdate=this.staticValueUpdate;else if(Array.isArray(t))this.onEmit=this.randomStaticValueEmit;else if("function"===e)this.emitOnly?this.onEmit=t:this.onUpdate=t;else if("object"===e&&(this.has(t,"random")||this.hasBoth(t,"start","end")||this.hasBoth(t,"min","max"))){this.start=this.has(t,"start")?t.start:t.min,this.end=this.has(t,"end")?t.end:t.max;var i=this.hasBoth(t,"min","max")||!!t.random;if(i){var n=t.random;Array.isArray(n)&&(this.start=n[0],this.end=n[1]),this.onEmit=this.randomRangedValueEmit}if(this.has(t,"steps"))this.steps=t.steps,this.counter=this.start,this.onEmit=this.steppedEmit;else{var s=this.has(t,"ease")?t.ease:"Linear";this.ease=r(s),i||(this.onEmit=this.easedValueEmit),this.onUpdate=this.easeValueUpdate}}else"object"===e&&this.hasEither(t,"onEmit","onUpdate")&&(this.has(t,"onEmit")&&(this.onEmit=t.onEmit),this.has(t,"onUpdate")&&(this.onUpdate=t.onUpdate));return this},has:function(t,e){return t.hasOwnProperty(e)},hasBoth:function(t,e,i){return t.hasOwnProperty(e)&&t.hasOwnProperty(i)},hasEither:function(t,e,i){return t.hasOwnProperty(e)||t.hasOwnProperty(i)},defaultEmit:function(t,e,i){return i},defaultUpdate:function(t,e,i,n){return n},staticValueEmit:function(){return this.propertyValue},staticValueUpdate:function(){return this.propertyValue},randomStaticValueEmit:function(){var t=Math.floor(Math.random()*this.propertyValue.length);return this.propertyValue[t]},randomRangedValueEmit:function(t,e){var i=s(this.start,this.end);return t&&t.data[e]&&(t.data[e].min=i),i},steppedEmit:function(){var t=this.counter,e=this.counter+(this.end-this.start)/this.steps;return this.counter=a(e,this.start,this.end),t},easedValueEmit:function(t,e){if(t&&t.data[e]){var i=t.data[e];i.min=this.start,i.max=this.end}return this.start},easeValueUpdate:function(t,e,i){var n=t.data[e];return(n.max-n.min)*this.ease(i)+n.min}});t.exports=h},function(t,e,i){var n=i(1),s=i(1);n=i(967),s=i(968),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(9);t.exports=function(t,e,i,s,r){var o=e.emitters.list,a=o.length;if(0!==a){var h=this.pipeline,l=h._tempMatrix1.copyFrom(s.matrix),u=h._tempMatrix2,c=h._tempMatrix3,d=h._tempMatrix4.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);l.multiply(d),t.setPipeline(h);var f=s.roundPixels,p=e.defaultFrame.glTexture,g=n.getTintAppendFloatAlphaAndSwap;h.setTexture2D(p,0);for(var v=0;v?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",TEXT_SET2:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET3:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",TEXT_SET4:"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",TEXT_SET5:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",TEXT_SET6:"ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",TEXT_SET7:"AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",TEXT_SET8:"0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET9:"ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",TEXT_SET10:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET11:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"}},function(t,e,i){var n=i(6);t.exports=function(t,e){var i=e.width,s=e.height,r=Math.floor(i/2),o=Math.floor(s/2),a=n(e,"chars","");if(""!==a){var h=n(e,"image",""),l=n(e,"offset.x",0),u=n(e,"offset.y",0),c=n(e,"spacing.x",0),d=n(e,"spacing.y",0),f=n(e,"lineSpacing",0),p=n(e,"charsPerRow",null);null===p&&(p=t.sys.textures.getFrame(h).width/i)>a.length&&(p=a.length);for(var g=l,v=u,m={retroFont:!0,font:h,size:i,lineHeight:s+f,chars:{}},y=0,x=0;x0&&r.maxLines1&&(d+=f*(h-1)),{width:a,height:d,lines:h,lineWidths:o,lineSpacing:f,lineHeight:c}}},function(t,e,i){var n=i(1),s=i(1);n=i(981),s=i(982),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(9);t.exports=function(t,e,i,s,r){if(0!==e.width&&0!==e.height){var o=e.frame,a=o.width,h=o.height,l=n.getTintAppendFloatAlpha;this.pipeline.batchTexture(e,o.glTexture,a,h,e.x,e.y,a/e.style.resolution,h/e.style.resolution,e.scaleX,e.scaleY,e.rotation,e.flipX,e.flipY,e.scrollFactorX,e.scrollFactorY,e.displayOriginX,e.displayOriginY,0,0,a,h,l(e._tintTL,s.alpha*e._alphaTL),l(e._tintTR,s.alpha*e._alphaTR),l(e._tintBL,s.alpha*e._alphaBL),l(e._tintBR,s.alpha*e._alphaBR),e._isTinted&&e.tintFill,0,0,s,r)}}},function(t,e){t.exports=function(t,e,i,n,s){0!==e.width&&0!==e.height&&t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(0),s=i(15),r=i(6),o=i(984),a={fontFamily:["fontFamily","Courier"],fontSize:["fontSize","16px"],fontStyle:["fontStyle",""],backgroundColor:["backgroundColor",null],color:["color","#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",!1],shadowFill:["shadow.fill",!1],align:["align","left"],maxLines:["maxLines",0],fixedWidth:["fixedWidth",0],fixedHeight:["fixedHeight",0],resolution:["resolution",0],rtl:["rtl",!1],testString:["testString","|MÉqgy"],baselineX:["baselineX",1.2],baselineY:["baselineY",1.4],wordWrapWidth:["wordWrap.width",null],wordWrapCallback:["wordWrap.callback",null],wordWrapCallbackScope:["wordWrap.callbackScope",null],wordWrapUseAdvanced:["wordWrap.useAdvancedWrap",!1]},h=new n({initialize:function(t,e){this.parent=t,this.fontFamily,this.fontSize,this.fontStyle,this.backgroundColor,this.color,this.stroke,this.strokeThickness,this.shadowOffsetX,this.shadowOffsetY,this.shadowColor,this.shadowBlur,this.shadowStroke,this.shadowFill,this.align,this.maxLines,this.fixedWidth,this.fixedHeight,this.resolution,this.rtl,this.testString,this.baselineX,this.baselineY,this._font,this.setStyle(e,!1,!0);var i=r(e,"metrics",!1);this.metrics=i?{ascent:r(i,"ascent",0),descent:r(i,"descent",0),fontSize:r(i,"fontSize",0)}:o(this)},setStyle:function(t,e,i){for(var n in void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px"),a){var o=i?a[n][1]:this[n];this[n]="wordWrapCallback"===n||"wordWrapCallbackScope"===n?r(t,a[n][0],o):s(t,a[n][0],o)}var h=r(t,"font",null);null!==h&&this.setFont(h,!1),this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim();var l=r(t,"fill",null);return null!==l&&(this.color=l),e?this.update(!0):this.parent},syncFont:function(t,e){e.font=this._font},syncStyle:function(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"},syncShadow:function(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)},update:function(t){return t&&(this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim(),this.metrics=o(this)),this.parent.updateText()},setFont:function(t,e){void 0===e&&(e=!0);var i=t,n="",s="";if("string"!=typeof t)i=r(t,"fontFamily","Courier"),n=r(t,"fontSize","16px"),s=r(t,"fontStyle","");else{var o=t.split(" "),a=0;s=o.length>2?o[a++]:"",n=o[a++]||"16px",i=o[a++]||"Courier"}return i===this.fontFamily&&n===this.fontSize&&s===this.fontStyle||(this.fontFamily=i,this.fontSize=n,this.fontStyle=s,e&&this.update(!0)),this.parent},setFontFamily:function(t){return this.fontFamily!==t&&(this.fontFamily=t,this.update(!0)),this.parent},setFontStyle:function(t){return this.fontStyle!==t&&(this.fontStyle=t,this.update(!0)),this.parent},setFontSize:function(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize!==t&&(this.fontSize=t,this.update(!0)),this.parent},setTestString:function(t){return this.testString=t,this.update(!0)},setFixedSize:function(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(!1)},setBackgroundColor:function(t){return this.backgroundColor=t,this.update(!1)},setFill:function(t){return this.color=t,this.update(!1)},setColor:function(t){return this.color=t,this.update(!1)},setResolution:function(t){return this.resolution=t,this.update(!1)},setStroke:function(t,e){return void 0===e&&(e=this.strokeThickness),void 0===t&&0!==this.strokeThickness?(this.strokeThickness=0,this.update(!0)):this.stroke===t&&this.strokeThickness===e||(this.stroke=t,this.strokeThickness=e,this.update(!0)),this.parent},setShadow:function(t,e,i,n,s,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===n&&(n=0),void 0===s&&(s=!1),void 0===r&&(r=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=i,this.shadowBlur=n,this.shadowStroke=s,this.shadowFill=r,this.update(!1)},setShadowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)},setShadowColor:function(t){return void 0===t&&(t="#000"),this.shadowColor=t,this.update(!1)},setShadowBlur:function(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)},setShadowStroke:function(t){return this.shadowStroke=t,this.update(!1)},setShadowFill:function(t){return this.shadowFill=t,this.update(!1)},setWordWrapWidth:function(t,e){return void 0===e&&(e=!1),this.wordWrapWidth=t,this.wordWrapUseAdvanced=e,this.update(!1)},setWordWrapCallback:function(t,e){return void 0===e&&(e=null),this.wordWrapCallback=t,this.wordWrapCallbackScope=e,this.update(!1)},setAlign:function(t){return void 0===t&&(t="left"),this.align=t,this.update(!1)},setMaxLines:function(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)},getTextMetrics:function(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}},toJSON:function(){var t={};for(var e in a)t[e]=this[e];return t.metrics=this.getTextMetrics(),t},destroy:function(){this.parent=void 0}});t.exports=h},function(t,e,i){var n=i(27);t.exports=function(t){var e=n.create(this),i=e.getContext("2d");t.syncFont(e,i);var s=Math.ceil(i.measureText(t.testString).width*t.baselineX),r=s,o=2*r;r=r*t.baselineY|0,e.width=s,e.height=o,i.fillStyle="#f00",i.fillRect(0,0,s,o),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,r);var a={ascent:0,descent:0,fontSize:0};if(!i.getImageData(0,0,s,o))return a.ascent=r,a.descent=r+6,a.fontSize=a.ascent+a.descent,n.remove(e),a;var h,l,u=i.getImageData(0,0,s,o).data,c=u.length,d=4*s,f=0,p=!1;for(h=0;hr;h--){for(l=0;l0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.fillColor,e.fillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.altFillColor,e.altFillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0){var R=o.strokeTint,L=n.getTintAppendFloatAlphaAndSwap(e.outlineFillColor,e.outlineFillAlpha*d);for(R.TL=L,R.TR=L,R.BL=L,R.BR=L,S=1;S0)for(n(h,e),S=0;S0)for(n(h,e,e.altFillColor,e.altFillAlpha*c),S=0;S0){for(s(h,e,e.outlineFillColor,e.outlineFillAlpha*c),b=1;bo.vertexCapacity&&o.flush(),o.setTexture2D(u,0);for(var m=o.vertexViewF32,y=o.vertexViewU32,x=o.vertexCount*o.vertexComponentCount-1,T=0,w=e.tintFill,E=0;E0?Math.PI*t.radius*t.radius:0}},function(t,e,i){var n=i(63);t.exports=function(t){return new n(t.x,t.y,t.radius)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.radius)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.radius===e.radius}},function(t,e,i){var n=i(13);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.diameter,e.height=t.diameter,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(93);n.Area=i(1092),n.Circumference=i(393),n.CircumferencePoint=i(188),n.Clone=i(1093),n.Contains=i(94),n.ContainsPoint=i(1094),n.ContainsRect=i(1095),n.CopyFrom=i(1096),n.Equals=i(1097),n.GetBounds=i(1098),n.GetPoint=i(391),n.GetPoints=i(392),n.Offset=i(1099),n.OffsetPoint=i(1100),n.Random=i(151),t.exports=n},function(t,e){t.exports=function(t){return t.isEmpty()?0:t.getMajorRadius()*t.getMinorRadius()*Math.PI}},function(t,e,i){var n=i(93);t.exports=function(t){return new n(t.x,t.y,t.width,t.height)}},function(t,e,i){var n=i(94);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(94);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.width,t.height)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}},function(t,e,i){var n=i(13);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.width,e.height=t.height,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(4),s=i(200);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a,h,l=t.x,u=t.y,c=t.radius,d=e.x,f=e.y,p=e.radius;if(u===f)0==(a=(o=-2*f)*o-4*(r=1)*(d*d+(h=(p*p-c*c-d*d+l*l)/(2*(l-d)))*h-2*d*h+f*f-p*p))?i.push(new n(h,-o/(2*r))):a>0&&(i.push(new n(h,(-o+Math.sqrt(a))/(2*r))),i.push(new n(h,(-o-Math.sqrt(a))/(2*r))));else{var g=(l-d)/(u-f),v=(p*p-c*c-d*d+l*l-f*f+u*u)/(2*(u-f));0==(a=(o=2*u*g-2*v*g-2*l)*o-4*(r=g*g+1)*(l*l+u*u+v*v-c*c-2*u*v))?(h=-o/(2*r),i.push(new n(h,v-h*g))):a>0&&(h=(-o+Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)),h=(-o-Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)))}}return i}},function(t,e,i){var n=i(202),s=i(201);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC(),h=e.getLineD();n(r,t,i),n(o,t,i),n(a,t,i),n(h,t,i)}return i}},function(t,e,i){var n=i(13),s=i(129);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i}},function(t,e,i){var n=i(204),s=i(129);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC(),h=t.getLineD();n(r,e,i),n(o,e,i),n(a,e,i),n(h,e,i)}return i}},function(t,e,i){var n=i(426),s=i(204);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(r,t,i),s(o,t,i),s(a,t,i)}return i}},function(t,e,i){var n=i(202),s=i(428);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC();n(r,e,i),n(o,e,i),n(a,e,i)}return i}},function(t,e,i){var n=i(431),s=i(429);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(t,r,i),s(t,o,i),s(t,a,i)}return i}},function(t,e,i){var n=i(433);t.exports=function(t,e){if(!n(t,e))return!1;var i=Math.min(e.x1,e.x2),s=Math.max(e.x1,e.x2),r=Math.min(e.y1,e.y2),o=Math.max(e.y1,e.y2);return t.x>=i&&t.x<=s&&t.y>=r&&t.y<=o}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||s0){var m=u[0],y=[m];for(h=1;h=o&&(y.push(x),m=x)}var T=u[u.length-1];return n(m,T)i&&(i=h.x),h.xr&&(r=h.y),h.yn(e)?t.setSize(e.height*i,e.height):t.setSize(e.width,e.width/i),t.setPosition(e.centerX-t.width/2,e.centerY-t.height/2)}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t.width=Math.floor(t.width),t.height=Math.floor(t.height),t}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.centerX,e.y=t.centerY,e}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.width,e.y=t.height,e}},function(t,e,i){var n=i(162);t.exports=function(t,e,i){var s=t.centerX,r=t.centerY;return t.setSize(t.width+2*e,t.height+2*i),n(t,s,r)}},function(t,e,i){var n=i(13),s=i(129);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)?(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y):i.setEmpty(),i}},function(t,e){t.exports=function(t,e){for(var i=t.x,n=t.right,s=t.y,r=t.bottom,o=0;oe.x&&t.ye.y}},function(t,e,i){var n=i(4),s=i(35);t.exports=function(t,e,i){void 0===i&&(i=new n),e=s(e);var r=Math.sin(e),o=Math.cos(e),a=o>0?t.width/2:t.width/-2,h=r>0?t.height/2:t.height/-2;return Math.abs(a*r)-1&&(s.splice(a,1),this.clear(o,!0))}t.length=0,this._pendingRemoval.length=0,this._list=s.concat(e.splice(0))}},isActive:function(){return this.enabled&&this.scene.sys.isActive()},updatePoll:function(t,e){if(!this.isActive())return!1;if(this.pluginEvents.emit(d.UPDATE,t,e),this._updatedThisFrame)return this._updatedThisFrame=!1,!1;var i,n=this.manager,s=n.pointers,r=n.pointersTotal;for(i=0;i0){if(this._pollTimer-=e,!(this._pollTimer<0))return!1;this._pollTimer=this.pollRate}var a=!1;for(i=0;i0&&(a=!0)}return a},update:function(t,e){if(!this.isActive())return!1;for(var i=e.length,n=!1,s=0;s0&&(n=!0)}return this._updatedThisFrame=!0,n},clear:function(t,e){void 0===e&&(e=!1);var i=t.input;if(i){e||this.queueForRemoval(t),i.gameObject=void 0,i.target=void 0,i.hitArea=void 0,i.hitAreaCallback=void 0,i.callbackContext=void 0,this.manager.resetCursor(i),t.input=null;var n=this._draggable.indexOf(t);return n>-1&&this._draggable.splice(n,1),(n=this._drag[0].indexOf(t))>-1&&this._drag[0].splice(n,1),(n=this._over[0].indexOf(t))>-1&&this._over[0].splice(n,1),t}},disable:function(t){t.input.enabled=!1},enable:function(t,e,i,n){return void 0===n&&(n=!1),t.input?t.input.enabled=!0:this.setHitArea(t,e,i),t.input&&n&&!t.input.dropZone&&(t.input.dropZone=n),this},hitTestPointer:function(t){for(var e=this.cameras.getCamerasBelowPointer(t),i=0;i0)return t.camera=n,s}return t.camera=e[0],[]},processDownEvents:function(t){var e=0,i=this._temp,n=this._eventData,s=this._eventContainer;n.cancelled=!1;for(var r=!1,o=0;o0&&l(t.x,t.y,t.downX,t.downY)>=s?i=!0:n>0&&e>=t.downTime+n&&(i=!0),i)return this.setDragState(t,3),this.processDragStartList(t)},processDragStartList:function(t){if(3!==this.getDragState(t))return 0;for(var e=this._drag[t.id],i=0;i1&&(this.sortGameObjects(i),this.topOnly&&i.splice(1)),this._drag[t.id]=i,0===this.dragDistanceThreshold&&0===this.dragTimeThreshold?(this.setDragState(t,3),this.processDragStartList(t)):(this.setDragState(t,2),0))},processDragMoveEvent:function(t){if(2===this.getDragState(t)&&this.processDragThresholdEvent(t,this.manager.game.loop.now),4!==this.getDragState(t))return 0;for(var e=this._tempZones,i=this._drag[t.id],n=0;n0?(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),e[0]?(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):a.target=null)}else!h&&e[0]&&(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h));if(o.parentContainer){var u=t.x-a.dragStartXGlobal,c=t.y-a.dragStartYGlobal,f=o.getParentRotation(),p=u*Math.cos(f)+c*Math.sin(f),g=c*Math.cos(f)-u*Math.sin(f);p*=1/o.parentContainer.scaleX,g*=1/o.parentContainer.scaleY,s=p+a.dragStartX,r=g+a.dragStartY}else s=t.x-a.dragX,r=t.y-a.dragY;o.emit(d.GAMEOBJECT_DRAG,t,s,r),this.emit(d.DRAG,t,o,s,r)}return i.length},processDragUpEvent:function(t){for(var e=this._drag[t.id],i=0;i0){var r=this.manager,o=this._eventData,a=this._eventContainer;o.cancelled=!1;for(var h=!1,l=0;l0){var s=this.manager,r=this._eventData,o=this._eventContainer;r.cancelled=!1;var a=!1;this.sortGameObjects(e);for(var h=0;h0){for(this.sortGameObjects(s),e=0;e0){for(this.sortGameObjects(r),e=0;e-1&&this._draggable.splice(s,1)}return this},makePixelPerfect:function(t){void 0===t&&(t=1);var e=this.systems.textures;return h(e,t)},setHitArea:function(t,e,i){if(void 0===e)return this.setHitAreaFromTexture(t);Array.isArray(t)||(t=[t]);var n=!1,s=!1,r=!1,o=!1,h=!1,l=!0;if(m(e)){var u=e;e=p(u,"hitArea",null),i=p(u,"hitAreaCallback",null),n=p(u,"draggable",!1),s=p(u,"dropZone",!1),r=p(u,"cursor",!1),o=p(u,"useHandCursor",!1),h=p(u,"pixelPerfect",!1);var c=p(u,"alphaTolerance",1);h&&(e={},i=this.makePixelPerfect(c)),e&&i||(this.setHitAreaFromTexture(t),l=!1)}else"function"!=typeof e||i||(i=e,e={});for(var d=0;d=e}}},function(t,e,i){t.exports={Events:i(131),KeyboardManager:i(361),KeyboardPlugin:i(1214),Key:i(446),KeyCodes:i(118),KeyCombo:i(447),JustDown:i(1219),JustUp:i(1220),DownDuration:i(1221),UpDuration:i(1222)}},function(t,e){t.exports="keydown"},function(t,e){t.exports="keyup"},function(t,e){t.exports="keycombomatch"},function(t,e){t.exports="down"},function(t,e){t.exports="keydown-"},function(t,e){t.exports="keyup-"},function(t,e){t.exports="up"},function(t,e,i){var n=i(0),s=i(11),r=i(131),o=i(19),a=i(6),h=i(54),l=i(130),u=i(446),c=i(118),d=i(447),f=i(1218),p=i(91),g=new n({Extends:s,initialize:function(t){s.call(this),this.game=t.systems.game,this.scene=t.scene,this.settings=this.scene.sys.settings,this.sceneInputPlugin=t,this.manager=t.manager.keyboard,this.enabled=!0,this.keys=[],this.combos=[],t.pluginEvents.once(h.BOOT,this.boot,this),t.pluginEvents.on(h.START,this.start,this)},boot:function(){var t=this.settings.input;this.enabled=a(t,"keyboard",!0);var e=a(t,"keyboard.capture",null);e&&this.addCaptures(e),this.sceneInputPlugin.pluginEvents.once(h.DESTROY,this.destroy,this)},start:function(){this.sceneInputPlugin.manager.useQueue?this.sceneInputPlugin.pluginEvents.on(h.UPDATE,this.update,this):this.sceneInputPlugin.manager.events.on(h.MANAGER_PROCESS,this.update,this),this.sceneInputPlugin.pluginEvents.once(h.SHUTDOWN,this.shutdown,this),this.game.events.on(o.BLUR,this.resetKeys,this)},isActive:function(){return this.enabled&&this.scene.sys.isActive()},addCapture:function(t){return this.manager.addCapture(t),this},removeCapture:function(t){return this.manager.removeCapture(t),this},getCaptures:function(){return this.manager.captures},enableGlobalCapture:function(){return this.manager.preventDefault=!0,this},disableGlobalCapture:function(){return this.manager.preventDefault=!1,this},clearCaptures:function(){return this.manager.clearCaptures(),this},createCursorKeys:function(){return this.addKeys({up:c.UP,down:c.DOWN,left:c.LEFT,right:c.RIGHT,space:c.SPACE,shift:c.SHIFT})},addKeys:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1);var n={};if("string"==typeof t){t=t.split(",");for(var s=0;s-1?n[s]=t:n[t.keyCode]=t,e&&this.addCapture(t.keyCode),t.setEmitOnRepeat(i),t}return"string"==typeof t&&(t=c[t.toUpperCase()]),n[t]||(n[t]=new u(this,t),e&&this.addCapture(t),n[t].setEmitOnRepeat(i)),n[t]},removeKey:function(t,e){void 0===e&&(e=!1);var i,n=this.keys;if(t instanceof u){var s=n.indexOf(t);s>-1&&(i=this.keys[s],this.keys[s]=void 0)}else"string"==typeof t&&(t=c[t.toUpperCase()]);return n[t]&&(i=n[t],n[t]=void 0),i&&(i.plugin=null,e&&i.destroy()),this},createCombo:function(t,e){return new d(this,t,e)},checkDown:function(t,e){if(this.enabled&&t.isDown){var i=p(this.time-t.timeDown,e);if(i>t._tick)return t._tick=i,!0}return!1},update:function(){var t=this.manager.queue,e=t.length;if(this.isActive()&&0!==e)for(var i=this.keys,n=0;n0&&e.maxKeyDelay>0){var r=e.timeLastMatched+e.maxKeyDelay;t.timeStamp<=r&&(s=!0,i=n(t,e))}else s=!0,i=n(t,e);return!s&&e.resetOnWrongKey&&(e.index=0,e.current=e.keyCodes[0]),i&&(e.timeLastMatched=t.timeStamp,e.matched=!0,e.timeMatched=t.timeStamp),i}},function(t,e){t.exports=function(t,e){return e.timeLastMatched=t.timeStamp,e.index++,e.index===e.size||(e.current=e.keyCodes[e.index],!1)}},function(t,e){t.exports=function(t){return t.current=t.keyCodes[0],t.index=0,t.timeLastMatched=0,t.matched=!1,t.timeMatched=0,t}},function(t,e,i){var n=i(118),s={};for(var r in n)s[n[r]]=r;t.exports=s},function(t,e){t.exports=function(t){return!!t._justDown&&(t._justDown=!1,!0)}},function(t,e){t.exports=function(t){return!!t._justUp&&(t._justUp=!1,!0)}},function(t,e){t.exports=function(t,e){void 0===e&&(e=50);var i=t.plugin.game.loop.time-t.timeDown;return t.isDown&&i'),i.push(''),i.push(''),i.push(this.xhrLoader.responseText),i.push(""),i.push(""),i.push("");var n=[i.join("\n")],o=this;try{var a=new window.Blob(n,{type:"image/svg+xml;charset=utf-8"})}catch(t){return o.state=s.FILE_ERRORED,void o.onProcessComplete()}this.data=new Image,this.data.crossOrigin=this.crossOrigin,this.data.onload=function(){r.revokeObjectURL(o.data),o.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(o.data),o.onProcessError()},r.createObjectURL(this.data,a,"image/svg+xml")},addToCache:function(){var t=this.cache.addImage(this.key,this.data);this.pendingDestroy(t)}});o.register("htmlTexture",function(t,e,i,n,s){if(Array.isArray(t))for(var r=0;r0},isLoading:function(){return this.state===s.LOADER_LOADING||this.state===s.LOADER_PROCESSING},isReady:function(){return this.state===s.LOADER_IDLE||this.state===s.LOADER_COMPLETE},start:function(){this.isReady()&&(this.progress=0,this.totalFailed=0,this.totalComplete=0,this.totalToLoad=this.list.size,this.emit(a.START,this),0===this.list.size?this.loadComplete():(this.state=s.LOADER_LOADING,this.inflight.clear(),this.queue.clear(),this.updateProgress(),this.checkLoadQueue(),this.systems.events.on(c.UPDATE,this.update,this)))},updateProgress:function(){this.progress=1-(this.list.size+this.inflight.size)/this.totalToLoad,this.emit(a.PROGRESS,this.progress)},update:function(){this.state===s.LOADER_LOADING&&this.list.size>0&&this.inflight.sizei&&(n=l,i=c)}}return n},moveTo:function(t,e,i,n,s){void 0===n&&(n=60),void 0===s&&(s=0);var o=Math.atan2(i-t.y,e-t.x);return s>0&&(n=r(t.x,t.y,e,i)/(s/1e3)),t.body.velocity.setToPolar(o,n),o},moveToObject:function(t,e,i,n){return this.moveTo(t,e.x,e.y,i,n)},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(s(t),e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(t,e)},overlapRect:function(t,e,i,n,s,r){return c(this.world,t,e,i,n,s,r)},overlapCirc:function(t,e,i,n,s){return u(this.world,t,e,i,n,s)},shutdown:function(){if(this.world){var t=this.systems.events;t.off(f.UPDATE,this.world.update,this.world),t.off(f.POST_UPDATE,this.world.postUpdate,this.world),t.off(f.SHUTDOWN,this.shutdown,this),this.add.destroy(),this.world.destroy(),this.add=null,this.world=null}},destroy:function(){this.shutdown(),this.scene.sys.events.off(f.START,this.start,this),this.scene=null,this.systems=null}});d.register("ArcadePhysics",v,"arcadePhysics"),t.exports=v},function(t,e){t.exports={setAcceleration:function(t,e){return this.body.acceleration.set(t,e),this},setAccelerationX:function(t){return this.body.acceleration.x=t,this},setAccelerationY:function(t){return this.body.acceleration.y=t,this}}},function(t,e){t.exports={setAngularVelocity:function(t){return this.body.angularVelocity=t,this},setAngularAcceleration:function(t){return this.body.angularAcceleration=t,this},setAngularDrag:function(t){return this.body.angularDrag=t,this}}},function(t,e){t.exports={setBounce:function(t,e){return this.body.bounce.set(t,e),this},setBounceX:function(t){return this.body.bounce.x=t,this},setBounceY:function(t){return this.body.bounce.y=t,this},setCollideWorldBounds:function(t,e,i){return this.body.setCollideWorldBounds(t,e,i),this}}},function(t,e){t.exports={setDebug:function(t,e,i){return this.debugShowBody=t,this.debugShowVelocity=e,this.debugBodyColor=i,this},setDebugBodyColor:function(t){return this.body.debugBodyColor=t,this},debugShowBody:{get:function(){return this.body.debugShowBody},set:function(t){this.body.debugShowBody=t}},debugShowVelocity:{get:function(){return this.body.debugShowVelocity},set:function(t){this.body.debugShowVelocity=t}},debugBodyColor:{get:function(){return this.body.debugBodyColor},set:function(t){this.body.debugBodyColor=t}}}},function(t,e){t.exports={setDrag:function(t,e){return this.body.drag.set(t,e),this},setDragX:function(t){return this.body.drag.x=t,this},setDragY:function(t){return this.body.drag.y=t,this},setDamping:function(t){return this.body.useDamping=t,this}}},function(t,e){var i={enableBody:function(t,e,i,n,s){return t&&this.body.reset(e,i),n&&(this.body.gameObject.active=!0),s&&(this.body.gameObject.visible=!0),this.body.enable=!0,this},disableBody:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=!1),this.body.stop(),this.body.enable=!1,t&&(this.body.gameObject.active=!1),e&&(this.body.gameObject.visible=!1),this},refreshBody:function(){return this.body.updateFromGameObject(),this}};t.exports=i},function(t,e){t.exports={setFriction:function(t,e){return this.body.friction.set(t,e),this},setFrictionX:function(t){return this.body.friction.x=t,this},setFrictionY:function(t){return this.body.friction.y=t,this}}},function(t,e){t.exports={setGravity:function(t,e){return this.body.gravity.set(t,e),this},setGravityX:function(t){return this.body.gravity.x=t,this},setGravityY:function(t){return this.body.gravity.y=t,this}}},function(t,e){var i={setImmovable:function(t){return void 0===t&&(t=!0),this.body.immovable=t,this}};t.exports=i},function(t,e){t.exports={setMass:function(t){return this.body.mass=t,this}}},function(t,e){t.exports={setOffset:function(t,e){return this.body.setOffset(t,e),this},setSize:function(t,e,i){return this.body.setSize(t,e,i),this},setCircle:function(t,e,i){return this.body.setCircle(t,e,i),this}}},function(t,e){t.exports={setVelocity:function(t,e){return this.body.setVelocity(t,e),this},setVelocityX:function(t){return this.body.setVelocityX(t),this},setVelocityY:function(t){return this.body.setVelocityY(t),this},setMaxVelocity:function(t,e){return this.body.maxVelocity.set(t,e),this}}},function(t,e,i){var n=i(457),s=i(63),r=i(200),o=i(201);t.exports=function(t,e,i,a,h,l){var u=n(t,e-a,i-a,2*a,2*a,h,l);if(0===u.length)return u;for(var c=new s(e,i,a),d=new s,f=[],p=0;pe.deltaAbsY()?y=-1:e.deltaAbsX()0&&u&&t.checkCollision.right&&h&&t.right>i&&(a=t.right-i)>r&&(a=0),0!==a&&(t.customSeparateX?t.overlapX=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.left=!0):e>0&&(t.blocked.none=!1,t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x}},function(t,e,i){var n=i(1279);t.exports=function(t,e,i,s,r,o){var a=0,h=e.faceTop,l=e.faceBottom,u=e.collideUp,c=e.collideDown;return o||(h=!0,l=!0,u=!0,c=!0),t.deltaY()<0&&c&&t.checkCollision.up?l&&t.y0&&u&&t.checkCollision.down&&h&&t.bottom>i&&(a=t.bottom-i)>r&&(a=0),0!==a&&(t.customSeparateY?t.overlapY=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.up=!0):e>0&&(t.blocked.none=!1,t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},function(t,e,i){var n=i(461);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.x,a=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=r,e.velocity.x=o-a*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=r,t.velocity.x=a-o*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{r*=.5,t.x-=r,e.x+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.x=u+h*t.bounce.x,e.velocity.x=u+l*e.bounce.x}return!0}},function(t,e,i){var n=i(462);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.y,a=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=r,e.velocity.y=o-a*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=r,t.velocity.y=a-o*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{r*=.5,t.y-=r,e.y+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.y=u+h*t.bounce.y,e.velocity.y=u+l*e.bounce.y}return!0}},,,,,,,,,,,,,function(t,e,i){t.exports={BasePlugin:i(467),DefaultPlugins:i(170),PluginCache:i(24),PluginManager:i(365),ScenePlugin:i(1295)}},function(t,e,i){var n=i(467),s=i(0),r=i(22),o=new s({Extends:n,initialize:function(t,e){n.call(this,e),this.scene=t,this.systems=t.sys,t.sys.events.once(r.BOOT,this.boot,this)},boot:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=o},function(t,e,i){var n=i(18),s=i(172),r={Center:i(354),Events:i(90),Orientation:i(355),ScaleManager:i(366),ScaleModes:i(356),Zoom:i(357)};r=n(!1,r=n(!1,r=n(!1,r=n(!1,r,s.CENTER),s.ORIENTATION),s.SCALE_MODE),s.ZOOM),t.exports=r},function(t,e,i){var n=i(119),s=i(18),r={Events:i(22),SceneManager:i(368),ScenePlugin:i(1298),Settings:i(370),Systems:i(175)};r=s(!1,r,n),t.exports=r},function(t,e,i){var n=i(23),s=i(0),r=i(22),o=i(2),a=i(24),h=new s({initialize:function(t){this.scene=t,this.systems=t.sys,this.settings=t.sys.settings,this.key=t.sys.settings.key,this.manager=t.sys.game.scene,this.transitionProgress=0,this._elapsed=0,this._target=null,this._duration=0,this._onUpdate,this._onUpdateScope,this._willSleep=!1,this._willRemove=!1,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.pluginStart,this)},boot:function(){this.systems.events.once(r.DESTROY,this.destroy,this)},pluginStart:function(){this._target=null,this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},start:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",this.key),this.manager.queueOp("start",t,e),this},restart:function(t){var e=this.key;return this.manager.queueOp("stop",e),this.manager.queueOp("start",e,t),this},transition:function(t){void 0===t&&(t={});var e=o(t,"target",!1),i=this.manager.getScene(e);if(!e||!this.checkValidTransition(i))return!1;var n=o(t,"duration",1e3);this._elapsed=0,this._target=i,this._duration=n,this._willSleep=o(t,"sleep",!1),this._willRemove=o(t,"remove",!1);var s=o(t,"onUpdate",null);s&&(this._onUpdate=s,this._onUpdateScope=o(t,"onUpdateScope",this.scene));var a=o(t,"allowInput",!1);this.settings.transitionAllowInput=a;var h=i.sys.settings;return h.isTransition=!0,h.transitionFrom=this.scene,h.transitionDuration=n,h.transitionAllowInput=a,o(t,"moveAbove",!1)?this.manager.moveAbove(this.key,e):o(t,"moveBelow",!1)&&this.manager.moveBelow(this.key,e),i.sys.isSleeping()?i.sys.wake():this.manager.start(e,o(t,"data")),this.systems.events.emit(r.TRANSITION_OUT,i,n),this.systems.events.on(r.UPDATE,this.step,this),!0},checkValidTransition:function(t){return!(!t||t.sys.isActive()||t.sys.isTransitioning()||t===this.scene||this.systems.isTransitioning())},step:function(t,e){this._elapsed+=e,this.transitionProgress=n(this._elapsed/this._duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.transitionProgress),this._elapsed>=this._duration&&this.transitionComplete()},transitionComplete:function(){var t=this._target.sys,e=this._target.sys.settings;this.systems.events.off(r.UPDATE,this.step,this),t.events.emit(r.TRANSITION_COMPLETE,this.scene),e.isTransition=!1,e.transitionFrom=null,this._duration=0,this._target=null,this._onUpdate=null,this._onUpdateScope=null,this._willRemove?this.manager.remove(this.key):this._willSleep?this.systems.sleep():this.manager.stop(this.key)},add:function(t,e,i,n){return this.manager.add(t,e,i,n)},launch:function(t,e){return t&&t!==this.key&&this.manager.queueOp("start",t,e),this},run:function(t,e){return t&&t!==this.key&&this.manager.queueOp("run",t,e),this},pause:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("pause",t,e),this},resume:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("resume",t,e),this},sleep:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("sleep",t,e),this},wake:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("wake",t,e),this},switch:function(t){return t!==this.key&&this.manager.queueOp("switch",this.key,t),this},stop:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",t,e),this},setActive:function(t,e,i){void 0===e&&(e=this.key);var n=this.manager.getScene(e);return n&&n.sys.setActive(t,i),this},setVisible:function(t,e){void 0===e&&(e=this.key);var i=this.manager.getScene(e);return i&&i.sys.setVisible(t),this},isSleeping:function(t){return void 0===t&&(t=this.key),this.manager.isSleeping(t)},isActive:function(t){return void 0===t&&(t=this.key),this.manager.isActive(t)},isPaused:function(t){return void 0===t&&(t=this.key),this.manager.isPaused(t)},isVisible:function(t){return void 0===t&&(t=this.key),this.manager.isVisible(t)},swapPosition:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.swapPosition(t,e),this},moveAbove:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveAbove(t,e),this},moveBelow:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveBelow(t,e),this},remove:function(t){return void 0===t&&(t=this.key),this.manager.remove(t),this},moveUp:function(t){return void 0===t&&(t=this.key),this.manager.moveUp(t),this},moveDown:function(t){return void 0===t&&(t=this.key),this.manager.moveDown(t),this},bringToTop:function(t){return void 0===t&&(t=this.key),this.manager.bringToTop(t),this},sendToBack:function(t){return void 0===t&&(t=this.key),this.manager.sendToBack(t),this},get:function(t){return this.manager.getScene(t)},getIndex:function(t){return void 0===t&&(t=this.key),this.manager.getIndex(t)},shutdown:function(){var t=this.systems.events;t.off(r.SHUTDOWN,this.shutdown,this),t.off(r.POST_UPDATE,this.step,this),t.off(r.TRANSITION_OUT)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.settings=null,this.manager=null}});a.register("ScenePlugin",h,"scenePlugin"),t.exports=h},function(t,e,i){t.exports={List:i(123),Map:i(156),ProcessQueue:i(181),RTree:i(463),Set:i(127),Size:i(367)}},function(t,e,i){var n=i(18),s=i(1301),r={CanvasTexture:i(372),Events:i(115),FilterMode:s,Frame:i(92),Parsers:i(374),Texture:i(177),TextureManager:i(371),TextureSource:i(373)};r=n(!1,r,s),t.exports=r},function(t,e){t.exports={LINEAR:0,NEAREST:1}},function(t,e,i){t.exports={Components:i(135),Parsers:i(1335),Formats:i(33),ImageCollection:i(480),ParseToTilemap:i(222),Tile:i(72),Tilemap:i(489),TilemapCreator:i(1344),TilemapFactory:i(1345),Tileset:i(137),LayerData:i(100),MapData:i(101),ObjectLayer:i(483),DynamicTilemapLayer:i(490),StaticTilemapLayer:i(491)}},function(t,e,i){var n=i(25),s=i(51);t.exports=function(t,e,i,r,o,a,h,l){t<0&&(t=0),e<0&&(e=0),void 0===h&&(h=!0);for(var u=n(t,e,i,r,null,l),c=o-t,d=a-e,f=0;f=0&&p=0&&g=y;h--)(u=f[l][h])&&-1!==u.index&&u.visible&&0!==u.alpha&&i.push(u);else if(2===a)for(l=w;l>=T;l--)for(h=y;f[l]&&h=T;l--)for(h=x;f[l]&&h>=y;h--)(u=f[l][h])&&-1!==u.index&&u.visible&&0!==u.alpha&&i.push(u)}else if(t.orientation===n.ISOMETRIC)if(0===a){for(l=T;l=y;h--)if(o(h,l,t,e)){if(!(u=f[l][h])||-1===u.index||!u.visible||0===u.alpha)continue;i.push(u)}}else if(2===a){for(l=w;l>=T;l--)for(h=y;f[l]&&h=T;l--)for(h=x;f[l]&&h>=y;h--)if(o(h,l,t,e)){if(!(u=f[l][h])||-1===u.index||!u.visible||0===u.alpha)continue;i.push(u)}return d.tilesDrawn=i.length,d.tilesTotal=p*g,i}},function(t,e){t.exports=function(t,e,i,n){var s=i.tilemapLayer,r=s.isoCullDistances,o=s.tileToWorldXY(t,e,void 0,n);return o.x>n.worldView.x+s.scaleX*i.tileWidth*(-r.x-.5)&&o.xn.worldView.y+s.scaleY*i.tileHeight*(-r.y-.5)&&o.y=0;r--)for(s=n.width-1;s>=0;s--)if((o=n.data[r][s])&&o.index===t){if(a===e)return o;a+=1}}else for(r=0;re)){for(var l=t;l<=e;l++)r(l,i,a);if(h)for(var u=0;u=t&&d.index<=e&&n(d,i)}o&&s(0,0,a.width,a.height,a)}}},function(t,e,i){var n=i(71),s=i(51),r=i(217);t.exports=function(t,e,i,o){void 0===e&&(e=!0),void 0===i&&(i=!0),Array.isArray(t)||(t=[t]);for(var a=0;a0&&n(a,t)}}e&&s(0,0,i.width,i.height,i)}},function(t,e){t.exports=function(t,e,i,n){if("number"==typeof t)n.callbacks[t]=null!==e?{callback:e,callbackContext:i}:void 0;else for(var s=0,r=t.length;s1||e.scaleY>1)&&(c.imageSmoothingEnabled=!1);for(var p=0;p0&&(t.currentPipeline&&t.currentPipeline.vertexCount>0&&t.flush(),r.vertexBuffer=e.vertexBuffer[a],t.setPipeline(r),t.setTexture2D(s[a].glTexture,0),t.gl.drawArrays(r.topology,0,e.vertexCount[a]));r.vertexBuffer=o,r.viewIdentity(),r.modelIdentity()}},function(t,e){t.exports=function(t,e,i,n,s){e.cull(n);var r=e.culledTiles,o=r.length;if(0!==o){var a=t._tempMatrix1,h=t._tempMatrix2,l=t._tempMatrix3;h.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),a.copyFrom(n.matrix);var u=t.currentContext,c=e.gidMap;u.save(),s?(a.multiplyWithOffset(s,-n.scrollX*e.scrollFactorX,-n.scrollY*e.scrollFactorY),h.e=e.x,h.f=e.y,a.multiply(h,l),l.copyToContext(u)):(h.e-=n.scrollX*e.scrollFactorX,h.f-=n.scrollY*e.scrollFactorY,h.copyToContext(u));var d=n.alpha*e.alpha;(!t.antialias||e.scaleX>1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f-1&&this._active.splice(s,1),n.destroy()}for(i=0;i=n.delay)){var s=n.elapsed-n.delay;n.elapsed=n.delay,!n.hasDispatched&&n.callback&&(n.hasDispatched=!0,n.callback.apply(n.callbackScope,n.args)),n.repeatCount>0?(n.repeatCount--,n.elapsed=s,n.hasDispatched=!1):this._pendingRemoval.push(n)}}}},shutdown:function(){var t;for(t=0;t-1&&(e.state=u.REMOVED,s.splice(r,1)):(e.state=u.REMOVED,n.splice(r,1))}for(i.length=0,i=this._add,t=0;t>2],r+=i[(3&n[o])<<4|n[o+1]>>4],r+=i[(15&n[o+1])<<2|n[o+2]>>6],r+=i[63&n[o+2]];return s%3==2?r=r.substring(0,r.length-1)+"=":s%3==1&&(r=r.substring(0,r.length-2)+"=="),r}},function(t,e,i){t.exports={Clone:i(65),Extend:i(18),GetAdvancedValue:i(15),GetFastValue:i(2),GetMinMaxValue:i(1369),GetValue:i(6),HasAll:i(1370),HasAny:i(400),HasValue:i(104),IsPlainObject:i(7),Merge:i(120),MergeRight:i(1371),Pick:i(481),SetValue:i(420)}},function(t,e,i){var n=i(6),s=i(23);t.exports=function(t,e,i,r,o){void 0===o&&(o=i);var a=n(t,e,o);return s(a,i,r)}},function(t,e){t.exports=function(t,e){for(var i=0;i0&&(i=1/Math.sqrt(i),this.x=t*i,this.y=e*i),this},normalizeRightHand:function(){var t=this.x;return this.x=-1*this.y,this.y=t,this},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this},transformMat3:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this},transformMat4:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[4]*i+n[12],this.y=n[1]*e+n[5]*i+n[13],this},reset:function(){return this.x=0,this.y=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0),n.LEFT=new n(-1,0),n.UP=new n(0,-1),n.DOWN=new n(0,1),n.ONE=new n(1,1),t.exports=n},function(t,e,i){var n=i(0),s=i(46),r=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=t),this.type=s.POINT,this.x=t,this.y=e},setTo:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.x=t,this.y=e,this}});t.exports=r},function(t,e,i){var n=i(0),s=i(23),r=i(19),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},existing:function(t){return(t.renderCanvas||t.renderWebGL)&&this.displayList.add(t),t.preUpdate&&this.updateList.add(t),t},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectFactory",o,"add"),t.exports=o},function(t,e){t.exports=function(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=i,o=0;o>>0},getTintAppendFloatAlpha:function(t,e){return((255&(255*e|0))<<24|t)>>>0},getTintAppendFloatAlphaAndSwap:function(t,e){return((255&(255*e|0))<<24|(255&(0|t))<<16|(255&(t>>8|0))<<8|255&(t>>16|0))>>>0},getFloatsFromUintRGB:function(t){return[(255&(t>>16|0))/255,(255&(t>>8|0))/255,(255&(0|t))/255]},getComponentCount:function(t,e){for(var i=0,n=0;n=this.right?this.width=0:this.width=this.right-t,this.x=t}},right:{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}},top:{get:function(){return this.y},set:function(t){t>=this.bottom?this.height=0:this.height=this.bottom-t,this.y=t}},bottom:{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}},centerX:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},centerY:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=u},function(t,e,i){t.exports={Alpha:i(527),AlphaSingle:i(266),Animation:i(498),BlendMode:i(269),ComputedSize:i(546),Crop:i(547),Depth:i(270),Flip:i(548),GetBounds:i(549),Mask:i(274),Origin:i(566),PathFollower:i(567),Pipeline:i(153),ScrollFactor:i(277),Size:i(568),Texture:i(569),TextureCrop:i(570),Tint:i(571),ToJSON:i(278),Transform:i(279),TransformMatrix:i(32),Visible:i(280)}},function(t,e){var i={PI2:2*Math.PI,TAU:.5*Math.PI,EPSILON:1e-6,DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,RND:null,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER||-9007199254740991,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991};t.exports=i},function(t,e,i){var n=i(0),s=i(278),r=i(113),o=i(9),a=i(90),h=new n({Extends:o,initialize:function(t,e){o.call(this),this.scene=t,this.type=e,this.state=0,this.parentContainer=null,this.name="",this.active=!0,this.tabIndex=-1,this.data=null,this.renderFlags=15,this.cameraFilter=0,this.input=null,this.body=null,this.ignoreDestroy=!1,t.sys.queueDepthSort()},setActive:function(t){return this.active=t,this},setName:function(t){return this.name=t,this},setState:function(t){return this.state=t,this},setDataEnabled:function(){return this.data||(this.data=new r(this)),this},setData:function(t,e){return this.data||(this.data=new r(this)),this.data.set(t,e),this},getData:function(t){return this.data||(this.data=new r(this)),this.data.get(t)},setInteractive:function(t,e,i){return this.scene.sys.input.enable(this,t,e,i),this},disableInteractive:function(){return this.input&&(this.input.enabled=!1),this},removeInteractive:function(){return this.scene.sys.input.clear(this),this.input=void 0,this},update:function(){},toJSON:function(){return s(this)},willRender:function(t){return!(h.RENDER_MASK!==this.renderFlags||0!==this.cameraFilter&&this.cameraFilter&t.id)},getIndexList:function(){for(var t=this,e=this.parentContainer,i=[];e&&(i.unshift(e.getIndex(t)),t=e,e.parentContainer);)e=e.parentContainer;return i.unshift(this.scene.sys.displayList.getIndex(t)),i},destroy:function(t){if(void 0===t&&(t=!1),this.scene&&!this.ignoreDestroy){this.preDestroy&&this.preDestroy.call(this),this.emit(a.DESTROY,this);var e=this.scene.sys;t||(e.displayList.remove(this),e.updateList.remove(this)),this.input&&(e.input.clear(this),this.input=void 0),this.data&&(this.data.destroy(),this.data=void 0),this.body&&(this.body.destroy(),this.body=void 0),t||e.queueDepthSort(),this.active=!1,this.visible=!1,this.scene=void 0,this.parentContainer=void 0,this.removeAllListeners()}}});h.RENDER_MASK=15,t.exports=h},function(t,e,i){var n=i(168),s=i(6);t.exports=function(t,e,i){var r=s(t,e,null);if(null===r)return i;if(Array.isArray(r))return n.RND.pick(r);if("object"==typeof r){if(r.hasOwnProperty("randInt"))return n.RND.integerInRange(r.randInt[0],r.randInt[1]);if(r.hasOwnProperty("randFloat"))return n.RND.realInRange(r.randFloat[0],r.randFloat[1])}else if("function"==typeof r)return r(e);return r}},function(t,e,i){var n=i(0),s=i(23),r=i(19),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectCreator",o,"make"),t.exports=o},function(t,e,i){var n=i(7),s=function(){var t,e,i,r,o,a,h=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof h&&(c=h,h=arguments[1]||{},l=2),u===l&&(h=this,--l);l=400&&t.status<=599&&(n=!1),this.resetXHR(),this.loader.nextFile(this,n)},onError:function(){this.resetXHR(),this.loader.nextFile(this,!1)},onProgress:function(t){t.lengthComputable&&(this.bytesLoaded=t.loaded,this.bytesTotal=t.total,this.percentComplete=Math.min(this.bytesLoaded/this.bytesTotal,1),this.loader.emit(r.FILE_PROGRESS,this,this.percentComplete))},onProcess:function(){this.state=s.FILE_PROCESSING,this.onProcessComplete()},onProcessComplete:function(){this.state=s.FILE_COMPLETE,this.multiFile&&this.multiFile.onFileComplete(this),this.loader.fileProcessComplete(this)},onProcessError:function(){this.state=s.FILE_ERRORED,this.multiFile&&this.multiFile.onFileFailed(this),this.loader.fileProcessComplete(this)},hasCacheConflict:function(){return this.cache&&this.cache.exists(this.key)},addToCache:function(){this.cache&&this.cache.add(this.key,this.data),this.pendingDestroy()},pendingDestroy:function(t){void 0===t&&(t=this.data);var e=this.key,i=this.type;this.loader.emit(r.FILE_COMPLETE,e,i,t),this.loader.emit(r.FILE_KEY_COMPLETE+i+"-"+e,e,i,t),this.loader.flagForRemoval(this)},destroy:function(){this.loader=null,this.cache=null,this.xhrSettings=null,this.multiFile=null,this.linkFile=null,this.data=null}});c.createObjectURL=function(t,e,i){if("function"==typeof URL)t.src=URL.createObjectURL(e);else{var n=new FileReader;n.onload=function(){t.removeAttribute("crossOrigin"),t.src="data:"+(e.type||i)+";base64,"+n.result.split(",")[1]},n.onerror=t.onerror,n.readAsDataURL(e)}},c.revokeObjectURL=function(t){"function"==typeof URL&&URL.revokeObjectURL(t.src)},t.exports=c},function(t,e){t.exports=function(t,e,i){return Math.max(e,Math.min(i,t))}},function(t,e){var i={},n={},s={register:function(t,e,n,s){void 0===s&&(s=!1),i[t]={plugin:e,mapping:n,custom:s}},registerCustom:function(t,e,i,s){n[t]={plugin:e,mapping:i,data:s}},hasCore:function(t){return i.hasOwnProperty(t)},hasCustom:function(t){return n.hasOwnProperty(t)},getCore:function(t){return i[t]},getCustom:function(t){return n[t]},getCustomClass:function(t){return n.hasOwnProperty(t)?n[t].plugin:null},remove:function(t){i.hasOwnProperty(t)&&delete i[t]},removeCustom:function(t){n.hasOwnProperty(t)&&delete n[t]},destroyCorePlugins:function(){for(var t in i)i.hasOwnProperty(t)&&delete i[t]},destroyCustomPlugins:function(){for(var t in n)n.hasOwnProperty(t)&&delete n[t]}};t.exports=s},function(t,e,i){var n=i(2);t.exports=function(t,e,i,s,r,o){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=o.width),void 0===s&&(s=o.height);var a=n(r,"isNotEmpty",!1),h=n(r,"isColliding",!1),l=n(r,"hasInterestingFace",!1);t<0&&(i+=t,t=0),e<0&&(s+=e,e=0),t+i>o.width&&(i=Math.max(o.width-t,0)),e+s>o.height&&(s=Math.max(o.height-e,0));for(var u=[],c=e;c=0;o--)t[o][e]=i+a*n,a++;return t}},function(t,e,i){var n,s,r,o=i(29),a=i(164),h=[],l=!1;t.exports={create2D:function(t,e,i){return n(t,e,i,o.CANVAS)},create:n=function(t,e,i,n,r){var u;void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=o.CANVAS),void 0===r&&(r=!1);var c=s(n);return null===c?(c={parent:t,canvas:document.createElement("canvas"),type:n},n===o.CANVAS&&h.push(c),u=c.canvas):(c.parent=t,u=c.canvas),r&&(c.parent=u),u.width=e,u.height=i,l&&n===o.CANVAS&&a.disable(u.getContext("2d")),u},createWebGL:function(t,e,i){return n(t,e,i,o.WEBGL)},disableSmoothing:function(){l=!0},enableSmoothing:function(){l=!1},first:s=function(t){if(void 0===t&&(t=o.CANVAS),t===o.WEBGL)return null;for(var e=0;e0?Math.acos(e/this.scaleX):-Math.acos(e/this.scaleX):n||r?s.TAU-(r>0?Math.acos(-n/this.scaleY):-Math.acos(n/this.scaleY)):0}},scaleX:{get:function(){return Math.sqrt(this.a*this.a+this.b*this.b)}},scaleY:{get:function(){return Math.sqrt(this.c*this.c+this.d*this.d)}},loadIdentity:function(){var t=this.matrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,this},translate:function(t,e){var i=this.matrix;return i[4]=i[0]*t+i[2]*e+i[4],i[5]=i[1]*t+i[3]*e+i[5],this},scale:function(t,e){var i=this.matrix;return i[0]*=t,i[1]*=t,i[2]*=e,i[3]*=e,this},rotate:function(t){var e=Math.sin(t),i=Math.cos(t),n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3];return n[0]=s*i+o*e,n[1]=r*i+a*e,n[2]=s*-e+o*i,n[3]=r*-e+a*i,this},multiply:function(t,e){var i=this.matrix,n=t.matrix,s=i[0],r=i[1],o=i[2],a=i[3],h=i[4],l=i[5],u=n[0],c=n[1],d=n[2],f=n[3],p=n[4],g=n[5],v=void 0===e?this:e;return v.a=u*s+c*o,v.b=u*r+c*a,v.c=d*s+f*o,v.d=d*r+f*a,v.e=p*s+g*o+h,v.f=p*r+g*a+l,v},multiplyWithOffset:function(t,e,i){var n=this.matrix,s=t.matrix,r=n[0],o=n[1],a=n[2],h=n[3],l=e*r+i*a+n[4],u=e*o+i*h+n[5],c=s[0],d=s[1],f=s[2],p=s[3],g=s[4],v=s[5];return n[0]=c*r+d*a,n[1]=c*o+d*h,n[2]=f*r+p*a,n[3]=f*o+p*h,n[4]=g*r+v*a+l,n[5]=g*o+v*h+u,this},transform:function(t,e,i,n,s,r){var o=this.matrix,a=o[0],h=o[1],l=o[2],u=o[3],c=o[4],d=o[5];return o[0]=t*a+e*l,o[1]=t*h+e*u,o[2]=i*a+n*l,o[3]=i*h+n*u,o[4]=s*a+r*l+c,o[5]=s*h+r*u+d,this},transformPoint:function(t,e,i){void 0===i&&(i={x:0,y:0});var n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5];return i.x=t*s+e*o+h,i.y=t*r+e*a+l,i},invert:function(){var t=this.matrix,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=e*s-i*n;return t[0]=s/a,t[1]=-i/a,t[2]=-n/a,t[3]=e/a,t[4]=(n*o-s*r)/a,t[5]=-(e*o-i*r)/a,this},copyFrom:function(t){var e=this.matrix;return e[0]=t.a,e[1]=t.b,e[2]=t.c,e[3]=t.d,e[4]=t.e,e[5]=t.f,this},copyFromArray:function(t){var e=this.matrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],this},copyToContext:function(t){var e=this.matrix;return t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t},setToContext:function(t){var e=this.matrix;return t.setTransform(e[0],e[1],e[2],e[3],e[4],e[5]),t},copyToArray:function(t){var e=this.matrix;return void 0===t?t=[e[0],e[1],e[2],e[3],e[4],e[5]]:(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]),t},setTransform:function(t,e,i,n,s,r){var o=this.matrix;return o[0]=t,o[1]=e,o[2]=i,o[3]=n,o[4]=s,o[5]=r,this},decomposeMatrix:function(){var t=this.decomposedMatrix,e=this.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(t.translateX=e[4],t.translateY=e[5],i||n){var a=Math.sqrt(i*i+n*n);t.rotation=n>0?Math.acos(i/a):-Math.acos(i/a),t.scaleX=a,t.scaleY=o/a}else if(s||r){var h=Math.sqrt(s*s+r*r);t.rotation=.5*Math.PI-(r>0?Math.acos(-s/h):-Math.acos(s/h)),t.scaleX=o/h,t.scaleY=h}else t.rotation=0,t.scaleX=0,t.scaleY=0;return t},applyITRS:function(t,e,i,n,s){var r=this.matrix,o=Math.sin(i),a=Math.cos(i);return r[4]=t,r[5]=e,r[0]=a*n,r[1]=o*n,r[2]=-o*s,r[3]=a*s,this},applyInverse:function(t,e,i){void 0===i&&(i=new r);var n=this.matrix,s=n[0],o=n[1],a=n[2],h=n[3],l=n[4],u=n[5],c=1/(s*h+a*-o);return i.x=h*c*t+-a*c*e+(u*a-l*h)*c,i.y=s*c*e+-o*c*t+(-u*s+l*o)*c,i},getX:function(t,e){return t*this.a+e*this.c+this.e},getY:function(t,e){return t*this.b+e*this.d+this.f},getCSSMatrix:function(){var t=this.matrix;return"matrix("+t[0]+","+t[1]+","+t[2]+","+t[3]+","+t[4]+","+t[5]+")"},destroy:function(){this.matrix=null,this.decomposedMatrix=null}});t.exports=o},function(t,e,i){var n=i(0),s=i(162),r=i(292),o=i(163),a=i(293),h=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=255),this.r=0,this.g=0,this.b=0,this.a=255,this._h=0,this._s=0,this._v=0,this._locked=!1,this.gl=[0,0,0,1],this._color=0,this._color32=0,this._rgba="",this.setTo(t,e,i,n)},transparent:function(){return this._locked=!0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this._locked=!1,this.update(!0)},setTo:function(t,e,i,n,s){return void 0===n&&(n=255),void 0===s&&(s=!0),this._locked=!0,this.red=t,this.green=e,this.blue=i,this.alpha=n,this._locked=!1,this.update(s)},setGLTo:function(t,e,i,n){return void 0===n&&(n=1),this._locked=!0,this.redGL=t,this.greenGL=e,this.blueGL=i,this.alphaGL=n,this._locked=!1,this.update(!0)},setFromRGB:function(t){return this._locked=!0,this.red=t.r,this.green=t.g,this.blue=t.b,t.hasOwnProperty("a")&&(this.alpha=t.a),this._locked=!1,this.update(!0)},setFromHSV:function(t,e,i){return o(t,e,i,this)},update:function(t){if(void 0===t&&(t=!1),this._locked)return this;var e=this.r,i=this.g,n=this.b,o=this.a;return this._color=s(e,i,n),this._color32=r(e,i,n,o),this._rgba="rgba("+e+","+i+","+n+","+o/255+")",t&&a(e,i,n,this),this},updateHSV:function(){var t=this.r,e=this.g,i=this.b;return a(t,e,i,this),this},clone:function(){return new h(this.r,this.g,this.b,this.a)},gray:function(t){return this.setTo(t,t,t)},random:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t)),n=Math.floor(t+Math.random()*(e-t)),s=Math.floor(t+Math.random()*(e-t));return this.setTo(i,n,s)},randomGray:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t));return this.setTo(i,i,i)},saturate:function(t){return this.s+=t/100,this},desaturate:function(t){return this.s-=t/100,this},lighten:function(t){return this.v+=t/100,this},darken:function(t){return this.v-=t/100,this},brighten:function(t){var e=this.r,i=this.g,n=this.b;return e=Math.max(0,Math.min(255,e-Math.round(-t/100*255))),i=Math.max(0,Math.min(255,i-Math.round(-t/100*255))),n=Math.max(0,Math.min(255,n-Math.round(-t/100*255))),this.setTo(e,i,n)},color:{get:function(){return this._color}},color32:{get:function(){return this._color32}},rgba:{get:function(){return this._rgba}},redGL:{get:function(){return this.gl[0]},set:function(t){this.gl[0]=Math.min(Math.abs(t),1),this.r=Math.floor(255*this.gl[0]),this.update(!0)}},greenGL:{get:function(){return this.gl[1]},set:function(t){this.gl[1]=Math.min(Math.abs(t),1),this.g=Math.floor(255*this.gl[1]),this.update(!0)}},blueGL:{get:function(){return this.gl[2]},set:function(t){this.gl[2]=Math.min(Math.abs(t),1),this.b=Math.floor(255*this.gl[2]),this.update(!0)}},alphaGL:{get:function(){return this.gl[3]},set:function(t){this.gl[3]=Math.min(Math.abs(t),1),this.a=Math.floor(255*this.gl[3]),this.update()}},red:{get:function(){return this.r},set:function(t){t=Math.floor(Math.abs(t)),this.r=Math.min(t,255),this.gl[0]=t/255,this.update(!0)}},green:{get:function(){return this.g},set:function(t){t=Math.floor(Math.abs(t)),this.g=Math.min(t,255),this.gl[1]=t/255,this.update(!0)}},blue:{get:function(){return this.b},set:function(t){t=Math.floor(Math.abs(t)),this.b=Math.min(t,255),this.gl[2]=t/255,this.update(!0)}},alpha:{get:function(){return this.a},set:function(t){t=Math.floor(Math.abs(t)),this.a=Math.min(t,255),this.gl[3]=t/255,this.update()}},h:{get:function(){return this._h},set:function(t){this._h=t,o(t,this._s,this._v,this)}},s:{get:function(){return this._s},set:function(t){this._s=t,o(this._h,t,this._v,this)}},v:{get:function(){return this._v},set:function(t){this._v=t,o(this._h,this._s,t,this)}}});t.exports=h},function(t,e){t.exports=function(t,e,i,n,s,r){var o;void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=1);var a=0,h=t.length;if(1===r)for(o=s;o=0;o--)t[o][e]+=i+a*n,a++;return t}},function(t,e,i){var n=i(13);t.exports=function(t){return t*n.DEG_TO_RAD}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.fillColor,r=n||e.fillAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.fillStyle="rgba("+o+","+a+","+h+","+r+")"}},,function(t,e){t.exports=function(t){return t.y+t.height-t.height*t.originY}},function(t,e){t.exports=function(t,e){return t.y=e+t.height*t.originY,t}},function(t,e){t.exports=function(t){return t.x-t.width*t.originX}},function(t,e){t.exports=function(t,e){return t.x=e+t.width*t.originX,t}},function(t,e){t.exports=function(t){return t.x+t.width-t.width*t.originX}},function(t,e){t.exports=function(t,e){return t.x=e-t.width+t.width*t.originX,t}},function(t,e){t.exports=function(t,e){return t.y=e-t.height+t.height*t.originY,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY}},function(t,e){t.exports={CIRCLE:0,ELLIPSE:1,LINE:2,POINT:3,POLYGON:4,RECTANGLE:5,TRIANGLE:6}},function(t,e){t.exports=function(t,e,i){return!(t.width<=0||t.height<=0)&&t.x<=e&&t.x+t.width>=e&&t.y<=i&&t.y+t.height>=i}},function(t,e,i){t.exports={DESTROY:i(641),FADE_IN_COMPLETE:i(642),FADE_IN_START:i(643),FADE_OUT_COMPLETE:i(644),FADE_OUT_START:i(645),FLASH_COMPLETE:i(646),FLASH_START:i(647),PAN_COMPLETE:i(648),PAN_START:i(649),POST_RENDER:i(650),PRE_RENDER:i(651),SHAKE_COMPLETE:i(652),SHAKE_START:i(653),ZOOM_COMPLETE:i(654),ZOOM_START:i(655)}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.strokeColor,r=n||e.strokeAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.strokeStyle="rgba("+o+","+a+","+h+","+r+")",t.lineWidth=e.lineWidth}},function(t,e){t.exports={DYNAMIC_BODY:0,STATIC_BODY:1,GROUP:2,TILEMAPLAYER:3,FACING_NONE:10,FACING_UP:11,FACING_DOWN:12,FACING_LEFT:13,FACING_RIGHT:14}},function(t,e,i){var n=i(138),s=i(24);t.exports=function(t,e,i,r,o){for(var a=null,h=null,l=null,u=null,c=s(t,e,i,r,null,o),d=0;d0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}},function(t,e,i){var n=i(0),s=i(272),r=i(150),o=i(46),a=i(151),h=i(3),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=o.LINE,this.x1=t,this.y1=e,this.x2=i,this.y2=n},getPoint:function(t,e){return s(this,t,e)},getPoints:function(t,e,i){return r(this,t,e,i)},getRandomPoint:function(t){return a(this,t)},setTo:function(t,e,i,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x1=t,this.y1=e,this.x2=i,this.y2=n,this},getPointA:function(t){return void 0===t&&(t=new h),t.set(this.x1,this.y1),t},getPointB:function(t){return void 0===t&&(t=new h),t.set(this.x2,this.y2),t},left:{get:function(){return Math.min(this.x1,this.x2)},set:function(t){this.x1<=this.x2?this.x1=t:this.x2=t}},right:{get:function(){return Math.max(this.x1,this.x2)},set:function(t){this.x1>this.x2?this.x1=t:this.x2=t}},top:{get:function(){return Math.min(this.y1,this.y2)},set:function(t){this.y1<=this.y2?this.y1=t:this.y2=t}},bottom:{get:function(){return Math.max(this.y1,this.y2)},set:function(t){this.y1>this.y2?this.y1=t:this.y2=t}}});t.exports=l},function(t,e){t.exports=function(t){return Math.sqrt((t.x2-t.x1)*(t.x2-t.x1)+(t.y2-t.y1)*(t.y2-t.y1))}},function(t,e){t.exports=function(t,e,i){var n=i-e;return e+((t-e)%n+n)%n}},function(t,e,i){t.exports={COMPLETE:i(882),DECODED:i(883),DECODED_ALL:i(884),DESTROY:i(885),DETUNE:i(886),GLOBAL_DETUNE:i(887),GLOBAL_MUTE:i(888),GLOBAL_RATE:i(889),GLOBAL_VOLUME:i(890),LOOP:i(891),LOOPED:i(892),MUTE:i(893),PAUSE_ALL:i(894),PAUSE:i(895),PLAY:i(896),RATE:i(897),RESUME_ALL:i(898),RESUME:i(899),SEEK:i(900),STOP_ALL:i(901),STOP:i(902),UNLOCKED:i(903),VOLUME:i(904)}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(6),l=i(7),u=new n({Extends:r,initialize:function(t,e,i,n,o){var u="json";if(l(e)){var c=e;e=a(c,"key"),i=a(c,"url"),n=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"dataKey",o)}var d={type:"json",cache:t.cacheManager.json,extension:u,responseType:"text",key:e,url:i,xhrSettings:n,config:o};r.call(this,t,d),l(i)&&(this.data=o?h(i,o):i,this.state=s.FILE_POPULATED)},onProcess:function(){if(this.state!==s.FILE_POPULATED){this.state=s.FILE_PROCESSING;var t=JSON.parse(this.xhrLoader.responseText),e=this.config;this.data="string"==typeof e?h(t,e,t):t}this.onProcessComplete()}});o.register("json",function(t,e,i,n){if(Array.isArray(t))for(var s=0;s80*i){n=h=t[0],a=l=t[1];for(var T=i;Th&&(h=u),f>l&&(l=f);g=0!==(g=Math.max(h-n,l-a))?1/g:0}return o(y,x,i,n,a,g),x}function s(t,e,i,n,s){var r,o;if(s===A(t,e,i,n)>0)for(r=e;r=e;r-=n)o=E(r,t[r],t[r+1],o);return o&&y(o,o.next)&&(_(o),o=o.next),o}function r(t,e){if(!t)return t;e||(e=t);var i,n=t;do{if(i=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(_(n),(n=e=n.prev)===n.next)break;i=!0}}while(i||n!==e);return e}function o(t,e,i,n,s,c,d){if(t){!d&&c&&function(t,e,i,n){var s=t;do{null===s.z&&(s.z=f(s.x,s.y,e,i,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,n,s,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,n=i,a=0,e=0;e0||h>0&&n;)0!==a&&(0===h||!n||i.z<=n.z)?(s=i,i=i.nextZ,a--):(s=n,n=n.nextZ,h--),r?r.nextZ=s:t=s,s.prevZ=r,r=s;i=n}r.nextZ=null,l*=2}while(o>1)}(s)}(t,n,s,c);for(var p,g,v=t;t.prev!==t.next;)if(p=t.prev,g=t.next,c?h(t,n,s,c):a(t))e.push(p.i/i),e.push(t.i/i),e.push(g.i/i),_(t),t=g.next,v=g.next;else if((t=g)===v){d?1===d?o(t=l(t,e,i),e,i,n,s,c,2):2===d&&u(t,e,i,n,s,c):o(r(t),e,i,n,s,c,1);break}}}function a(t){var e=t.prev,i=t,n=t.next;if(m(e,i,n)>=0)return!1;for(var s=t.next.next;s!==t.prev;){if(g(e.x,e.y,i.x,i.y,n.x,n.y,s.x,s.y)&&m(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function h(t,e,i,n){var s=t.prev,r=t,o=t.next;if(m(s,r,o)>=0)return!1;for(var a=s.xr.x?s.x>o.x?s.x:o.x:r.x>o.x?r.x:o.x,u=s.y>r.y?s.y>o.y?s.y:o.y:r.y>o.y?r.y:o.y,c=f(a,h,e,i,n),d=f(l,u,e,i,n),p=t.prevZ,v=t.nextZ;p&&p.z>=c&&v&&v.z<=d;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;v&&v.z<=d;){if(v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function l(t,e,i){var n=t;do{var s=n.prev,r=n.next.next;!y(s,r)&&x(s,n,n.next,r)&&T(s,r)&&T(r,s)&&(e.push(s.i/i),e.push(n.i/i),e.push(r.i/i),_(n),_(n.next),n=t=r),n=n.next}while(n!==t);return n}function u(t,e,i,n,s,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&v(h,l)){var u=w(h,l);return h=r(h,h.next),u=r(u,u.next),o(h,e,i,n,s,a),void o(u,e,i,n,s,a)}l=l.next}h=h.next}while(h!==t)}function c(t,e){return t.x-e.x}function d(t,e){if(e=function(t,e){var i,n=e,s=t.x,r=t.y,o=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){var a=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=s&&a>o){if(o=a,a===s){if(r===n.y)return n;if(r===n.next.y)return n.next}i=n.x=n.x&&n.x>=u&&s!==n.x&&g(ri.x)&&T(n,t)&&(i=n,d=h),n=n.next;return i}(t,e)){var i=w(e,t);r(i,i.next)}}function f(t,e,i,n,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*s)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*s)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function p(t){var e=t,i=t;do{e.x=0&&(t-o)*(n-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(s-o)*(n-a)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&x(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&T(t,e)&&T(e,t)&&function(t,e){var i=t,n=!1,s=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&i.next.y!==i.y&&s<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,i,n){return!!(y(t,e)&&y(i,n)||y(t,n)&&y(i,e))||m(t,e,i)>0!=m(t,e,n)>0&&m(i,n,t)>0!=m(i,n,e)>0}function T(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function w(t,e){var i=new b(t.i,t.x,t.y),n=new b(e.i,e.x,e.y),s=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,n.next=i,i.prev=n,r.next=n,n.prev=r,n}function E(t,e,i,n){var s=new b(t,e,i);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function _(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function b(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,i,n){for(var s=0,r=e,o=i-n;r0&&(n+=t[s-1].length,i.holes.push(n))}return i}},function(t,e){t.exports=function(t){var e={};for(var i in t)Array.isArray(t[i])?e[i]=t[i].slice(0):e[i]=t[i];return e}},function(t,e){t.exports=function(t,e,i,n){var s=t.length;if(e<0||e>s||e>=i||i>s||e+i>s){if(n)throw new Error("Range Error: Values outside acceptable range");return!1}return!0}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(960),a=new n({Extends:r,Mixins:[s.Alpha,s.BlendMode,s.Depth,s.Flip,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Size,s.TextureCrop,s.Tint,s.Transform,s.Visible,o],initialize:function(t,e,i,n,o){r.call(this,t,"Sprite"),this._crop=this.resetCropObject(),this.anims=new s.Animation(this),this.setTexture(n,o),this.setPosition(e,i),this.setSizeToFrame(),this.setOriginFromFrame(),this.initPipeline()},preUpdate:function(t,e){this.anims.update(t,e)},play:function(t,e,i){return this.anims.play(t,e,i),this},toJSON:function(){return s.ToJSON(this)},preDestroy:function(){this.anims.destroy(),this.anims=void 0}});t.exports=a},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){var o=t.strokeTint,a=n.getTintAppendFloatAlphaAndSwap(e.strokeColor,e.strokeAlpha*i);o.TL=a,o.TR=a,o.BL=a,o.BR=a;var h=e.pathData,l=h.length-1,u=e.lineWidth,c=u/2,d=h[0]-s,f=h[1]-r;e.closePath||(l-=2);for(var p=2;p=this.x2&&this.x1>=this.x3?this.x1-t:this.x2>=this.x1&&this.x2>=this.x3?this.x2-t:this.x3-t,this.x1-=e,this.x2-=e,this.x3-=e}},top:{get:function(){return Math.min(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1<=this.y2&&this.y1<=this.y3?this.y1-t:this.y2<=this.y1&&this.y2<=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}},bottom:{get:function(){return Math.max(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1>=this.y2&&this.y1>=this.y3?this.y1-t:this.y2>=this.y1&&this.y2>=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}}});t.exports=u},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=new n({Extends:r,initialize:function t(e,i,n,s,o){var l,u="png";if(h(i)){var c=i;i=a(c,"key"),n=a(c,"url"),l=a(c,"normalMap"),s=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"frameConfig")}Array.isArray(n)&&(l=n[1],n=n[0]);var d={type:"image",cache:e.textureManager,extension:u,responseType:"blob",key:i,url:n,xhrSettings:s,config:o};if(r.call(this,e,d),l){var f=new t(e,this.key,l,s,o);f.type="normalMap",this.setLink(f),e.addFile(f)}},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=new Image,this.data.crossOrigin=this.crossOrigin;var t=this;this.data.onload=function(){r.revokeObjectURL(t.data),t.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(t.data),t.onProcessError()},r.createObjectURL(this.data,this.xhrLoader.response,"image/png")},addToCache:function(){var t,e=this.linkFile;e&&e.state===s.FILE_COMPLETE?(t="image"===this.type?this.cache.addImage(this.key,this.data,e.data):this.cache.addImage(e.key,e.data,this.data),this.pendingDestroy(t),e.pendingDestroy(t)):e||(t=this.cache.addImage(this.key,this.data),this.pendingDestroy(t))}});o.register("image",function(t,e,i){if(Array.isArray(t))for(var n=0;nthis.right||e>this.bottom)},copy:function(t){return this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.visible=t.visible,this.setFlip(t.flipX,t.flipY),this.tint=t.tint,this.rotation=t.rotation,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext,this},getCollisionGroup:function(){return this.tileset?this.tileset.getTileCollisionGroup(this.index):null},getTileData:function(){return this.tileset?this.tileset.getTileData(this.index):null},getLeft:function(t){var e=this.tilemapLayer;return e?e.tileToWorldX(this.x,t):this.x*this.baseWidth},getRight:function(t){var e=this.tilemapLayer;return e?this.getLeft(t)+this.width*e.scaleX:this.getLeft(t)+this.width},getTop:function(t){var e=this.tilemapLayer;return e?e.tileToWorldY(this.y,t)-(this.height-this.baseHeight)*e.scaleY:this.y*this.baseHeight-(this.height-this.baseHeight)},getBottom:function(t){var e=this.tilemapLayer;return e?this.getTop(t)+this.height*e.scaleY:this.getTop(t)+this.height},getBounds:function(t,e){return void 0===e&&(e=new r),e.x=this.getLeft(),e.y=this.getTop(),e.width=this.getRight()-e.x,e.height=this.getBottom()-e.y,e},getCenterX:function(t){return(this.getLeft(t)+this.getRight(t))/2},getCenterY:function(t){return(this.getTop(t)+this.getBottom(t))/2},destroy:function(){this.collisionCallback=void 0,this.collisionCallbackContext=void 0,this.properties=void 0},intersects:function(t,e,i,n){return!(i<=this.pixelX||n<=this.pixelY||t>=this.right||e>=this.bottom)},isInteresting:function(t,e){return t&&e?this.canCollide||this.hasInterestingFace:t?this.collides:!!e&&this.hasInterestingFace},resetCollision:function(t){(void 0===t&&(t=!0),this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,t)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},resetFaces:function(){return this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this},setCollision:function(t,e,i,n,s){(void 0===e&&(e=t),void 0===i&&(i=t),void 0===n&&(n=t),void 0===s&&(s=!0),this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=n,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=n,s)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},setCollisionCallback:function(t,e){return null===t?(this.collisionCallback=void 0,this.collisionCallbackContext=void 0):(this.collisionCallback=t,this.collisionCallbackContext=e),this},setSize:function(t,e,i,n){return void 0!==t&&(this.width=t),void 0!==e&&(this.height=e),void 0!==i&&(this.baseWidth=i),void 0!==n&&(this.baseHeight=n),this.updatePixelXY(),this},updatePixelXY:function(){return this.pixelX=this.x*this.baseWidth,this.pixelY=this.y*this.baseHeight,this},canCollide:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}},collides:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}},hasInterestingFace:{get:function(){return this.faceTop||this.faceBottom||this.faceLeft||this.faceRight}},tileset:{get:function(){var t=this.layer.tilemapLayer;if(t){var e=t.gidMap[this.index];if(e)return e}return null}},tilemapLayer:{get:function(){return this.layer.tilemapLayer}},tilemap:{get:function(){var t=this.tilemapLayer;return t?t.tilemap:null}}});t.exports=o},function(t,e){t.exports=function(t){return t.x-t.width*t.originX+.5*t.width}},function(t,e){t.exports=function(t,e){var i=t.width*t.originX;return t.x=e+i-.5*t.width,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY+.5*t.height}},function(t,e){t.exports=function(t,e){var i=t.height*t.originY;return t.y=e+i-.5*t.height,t}},function(t,e){t.exports=function(t,e){if(!(e>=t.length)){for(var i=t.length-1,n=t[e],s=e;si&&(e=i/2);var n=Math.max(1,Math.round(i/e));return s(this.getSpacedPoints(n),t)},getDistancePoints:function(t){var e=this.getLength(),i=Math.max(1,e/t);return this.getSpacedPoints(i)},getEndPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(1,t)},getLength:function(){var t=this.getLengths();return t[t.length-1]},getLengths:function(t){if(void 0===t&&(t=this.arcLengthDivisions),this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,i=[],n=this.getPoint(0,this._tmpVec2A),s=0;i.push(0);for(var r=1;r<=t;r++)s+=(e=this.getPoint(r/t,this._tmpVec2B)).distance(n),i.push(s),n.copy(e);return this.cacheArcLengths=i,i},getPointAt:function(t,e){var i=this.getUtoTmapping(t);return this.getPoint(i,e)},getPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++)i.push(this.getPoint(n/t));return i},getRandomPoint:function(t){return void 0===t&&(t=new o),this.getPoint(Math.random(),t)},getSpacedPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++){var s=this.getUtoTmapping(n/t,null,t);i.push(this.getPoint(s))}return i},getStartPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(0,t)},getTangent:function(t,e){void 0===e&&(e=new o);var i=t-1e-4,n=t+1e-4;return i<0&&(i=0),n>1&&(n=1),this.getPoint(i,this._tmpVec2A),this.getPoint(n,e),e.subtract(this._tmpVec2A).normalize()},getTangentAt:function(t,e){var i=this.getUtoTmapping(t);return this.getTangent(i,e)},getTFromDistance:function(t,e){return t<=0?0:this.getUtoTmapping(0,t,e)},getUtoTmapping:function(t,e,i){var n,s=this.getLengths(i),r=0,o=s.length;n=e?Math.min(e,s[o-1]):t*s[o-1];for(var a,h=0,l=o-1;h<=l;)if((a=s[r=Math.floor(h+(l-h)/2)]-n)<0)h=r+1;else{if(!(a>0)){l=r;break}l=r-1}if(s[r=l]===n)return r/(o-1);var u=s[r];return(r+(n-u)/(s[r+1]-u))/(o-1)},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths()}});t.exports=a},function(t,e,i){t.exports={ADD:i(861),COMPLETE:i(862),FILE_COMPLETE:i(863),FILE_KEY_COMPLETE:i(864),FILE_LOAD_ERROR:i(865),FILE_LOAD:i(866),FILE_PROGRESS:i(867),POST_PROCESS:i(868),PROGRESS:i(869),START:i(870)}},function(t,e,i){var n=i(166),s=i(179);t.exports=function(t,e){var i=n.Power0;if("string"==typeof t)if(n.hasOwnProperty(t))i=n[t];else{var r="";t.indexOf(".")&&("in"===(r=t.substr(t.indexOf(".")+1)).toLowerCase()?r="easeIn":"out"===r.toLowerCase()?r="easeOut":"inout"===r.toLowerCase()&&(r="easeInOut")),t=s(t.substr(0,t.indexOf(".")+1)+r),n.hasOwnProperty(t)&&(i=n[t])}else"function"==typeof t?i=t:Array.isArray(t)&&t.length;if(!e)return i;var o=e.slice(0);return o.unshift(0),function(t){return o[0]=t,i.apply(this,o)}}},function(t,e){t.exports=function(t,e,i){var n=t.x3-t.x1,s=t.y3-t.y1,r=t.x2-t.x1,o=t.y2-t.y1,a=e-t.x1,h=i-t.y1,l=n*n+s*s,u=n*r+s*o,c=n*a+s*h,d=r*r+o*o,f=r*a+o*h,p=l*d-u*u,g=0===p?0:1/p,v=(d*c-u*f)*g,m=(l*f-u*c)*g;return v>=0&&m>=0&&v+m<1}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.x1,r=t.y1,o=t.x2,a=t.y2,h=e.x1,l=e.y1,u=e.x2,c=e.y2,d=(u-h)*(r-l)-(c-l)*(s-h),f=(o-s)*(r-l)-(a-r)*(s-h),p=(c-l)*(o-s)-(u-h)*(a-r);if(0===p)return!1;var g=d/p,v=f/p;return g>=0&&g<=1&&v>=0&&v<=1&&(i.x=s+g*(o-s),i.y=r+g*(a-r),!0)}},function(t,e){t.exports=function(t){return Math.atan2(t.y2-t.y1,t.x2-t.x1)}},,function(t,e,i){var n=i(22);t.exports=function(t,e,i){return(i-e)*(t=n(t,0,1))}},function(t,e){t.exports=function(t,e,i){return t&&t.hasOwnProperty(e)?t[e]:i}},function(t,e){t.exports={CREATED:0,INIT:1,DELAY:2,OFFSET_DELAY:3,PENDING_RENDER:4,PLAYING_FORWARD:5,PLAYING_BACKWARD:6,HOLD_DELAY:7,REPEAT_DELAY:8,COMPLETE:9,PENDING_ADD:20,PAUSED:21,LOOP_DELAY:22,ACTIVE:23,COMPLETE_DELAY:24,PENDING_REMOVE:25,REMOVED:26}},function(t,e,i){t.exports={DESTROY:i(576),VIDEO_COMPLETE:i(577),VIDEO_CREATED:i(578),VIDEO_ERROR:i(579),VIDEO_LOOP:i(580),VIDEO_PLAY:i(581),VIDEO_SEEKED:i(582),VIDEO_SEEKING:i(583),VIDEO_STOP:i(584),VIDEO_TIMEOUT:i(585),VIDEO_UNLOCKED:i(586)}},function(t,e,i){var n=i(0),s=i(12),r=i(35),o=i(9),a=i(48),h=i(11),l=i(32),u=i(161),c=i(3),d=new n({Extends:o,Mixins:[s.Alpha,s.Visible],initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),o.call(this),this.scene,this.sceneManager,this.scaleManager,this.cameraManager,this.id=0,this.name="",this.resolution=1,this.roundPixels=!1,this.useBounds=!1,this.worldView=new h,this.dirty=!0,this._x=t,this._y=e,this._cx=0,this._cy=0,this._cw=0,this._ch=0,this._width=i,this._height=n,this._bounds=new h,this._scrollX=0,this._scrollY=0,this._zoom=1,this._rotation=0,this.matrix=new l,this.transparent=!0,this.backgroundColor=u("rgba(0,0,0,0)"),this.disableCull=!1,this.culledObjects=[],this.midPoint=new c(i/2,n/2),this.originX=.5,this.originY=.5,this._customViewport=!1,this.mask=null,this._maskCamera=null},setOrigin:function(t,e){return void 0===t&&(t=.5),void 0===e&&(e=t),this.originX=t,this.originY=e,this},getScroll:function(t,e,i){void 0===i&&(i=new c);var n=.5*this.width,s=.5*this.height;return i.x=t-n,i.y=e-s,this.useBounds&&(i.x=this.clampX(i.x),i.y=this.clampY(i.y)),i},centerOnX:function(t){var e=.5*this.width;return this.midPoint.x=t,this.scrollX=t-e,this.useBounds&&(this.scrollX=this.clampX(this.scrollX)),this},centerOnY:function(t){var e=.5*this.height;return this.midPoint.y=t,this.scrollY=t-e,this.useBounds&&(this.scrollY=this.clampY(this.scrollY)),this},centerOn:function(t,e){return this.centerOnX(t),this.centerOnY(e),this},centerToBounds:function(){if(this.useBounds){var t=this._bounds,e=.5*this.width,i=.5*this.height;this.midPoint.set(t.centerX,t.centerY),this.scrollX=t.centerX-e,this.scrollY=t.centerY-i}return this},centerToSize:function(){return this.scrollX=.5*this.width,this.scrollY=.5*this.height,this},cull:function(t){if(this.disableCull)return t;var e=this.matrix.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(!o)return t;var a=e[4],h=e[5],l=this.scrollX,u=this.scrollY,c=this.width,d=this.height,f=this.culledObjects,p=t.length;o=1/o,f.length=0;for(var g=0;gC&&wA&&Es&&(t=s),t},clampY:function(t){var e=this._bounds,i=this.displayHeight,n=e.y+(i-this.height)/2,s=Math.max(n,n+e.height-i);return ts&&(t=s),t},removeBounds:function(){return this.useBounds=!1,this.dirty=!0,this._bounds.setEmpty(),this},setAngle:function(t){return void 0===t&&(t=0),this.rotation=r(t),this},setBackgroundColor:function(t){return void 0===t&&(t="rgba(0,0,0,0)"),this.backgroundColor=u(t),this.transparent=0===this.backgroundColor.alpha,this},setBounds:function(t,e,i,n,s){return void 0===s&&(s=!1),this._bounds.setTo(t,e,i,n),this.dirty=!0,this.useBounds=!0,s?this.centerToBounds():(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},getBounds:function(t){void 0===t&&(t=new h);var e=this._bounds;return t.setTo(e.x,e.y,e.width,e.height),t},setName:function(t){return void 0===t&&(t=""),this.name=t,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setRotation:function(t){return void 0===t&&(t=0),this.rotation=t,this},setRoundPixels:function(t){return this.roundPixels=t,this},setScene:function(t){this.scene&&this._customViewport&&this.sceneManager.customViewports--,this.scene=t;var e=t.sys;this.sceneManager=e.game.scene,this.scaleManager=e.scale,this.cameraManager=e.cameras;var i=this.scaleManager.resolution;return this.resolution=i,this._cx=this._x*i,this._cy=this._y*i,this._cw=this._width*i,this._ch=this._height*i,this.updateSystem(),this},setScroll:function(t,e){return void 0===e&&(e=t),this.scrollX=t,this.scrollY=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},setViewport:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setZoom:function(t){return void 0===t&&(t=1),0===t&&(t=.001),this.zoom=t,this},setMask:function(t,e){return void 0===e&&(e=!0),this.mask=t,this._maskCamera=e?this.cameraManager.default:this,this},clearMask:function(t){return void 0===t&&(t=!1),t&&this.mask&&this.mask.destroy(),this.mask=null,this},toJSON:function(){var t={name:this.name,x:this.x,y:this.y,width:this.width,height:this.height,zoom:this.zoom,rotation:this.rotation,roundPixels:this.roundPixels,scrollX:this.scrollX,scrollY:this.scrollY,backgroundColor:this.backgroundColor.rgba};return this.useBounds&&(t.bounds={x:this._bounds.x,y:this._bounds.y,width:this._bounds.width,height:this._bounds.height}),t},update:function(){},updateSystem:function(){if(this.scaleManager){var t=0!==this._x||0!==this._y||this.scaleManager.width!==this._width||this.scaleManager.height!==this._height,e=this.sceneManager;t&&!this._customViewport?e.customViewports++:!t&&this._customViewport&&e.customViewports--,this.dirty=!0,this._customViewport=t}},destroy:function(){this.emit(a.DESTROY,this),this.removeAllListeners(),this.matrix.destroy(),this.culledObjects=[],this._customViewport&&this.sceneManager.customViewports--,this._bounds=null,this.scene=null,this.scaleManager=null,this.sceneManager=null,this.cameraManager=null},x:{get:function(){return this._x},set:function(t){this._x=t,this._cx=t*this.resolution,this.updateSystem()}},y:{get:function(){return this._y},set:function(t){this._y=t,this._cy=t*this.resolution,this.updateSystem()}},width:{get:function(){return this._width},set:function(t){this._width=t,this._cw=t*this.resolution,this.updateSystem()}},height:{get:function(){return this._height},set:function(t){this._height=t,this._ch=t*this.resolution,this.updateSystem()}},scrollX:{get:function(){return this._scrollX},set:function(t){this._scrollX=t,this.dirty=!0}},scrollY:{get:function(){return this._scrollY},set:function(t){this._scrollY=t,this.dirty=!0}},zoom:{get:function(){return this._zoom},set:function(t){this._zoom=t,this.dirty=!0}},rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this.dirty=!0}},centerX:{get:function(){return this.x+.5*this.width}},centerY:{get:function(){return this.y+.5*this.height}},displayWidth:{get:function(){return this.width/this.zoom}},displayHeight:{get:function(){return this.height/this.zoom}}});t.exports=d},function(t,e,i){t.exports={ENTER_FULLSCREEN:i(694),FULLSCREEN_FAILED:i(695),FULLSCREEN_UNSUPPORTED:i(696),LEAVE_FULLSCREEN:i(697),ORIENTATION_CHANGE:i(698),RESIZE:i(699)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=i(0),s=i(22),r=i(17),o=new n({initialize:function(t,e,i,n,s,r,o){this.texture=t,this.name=e,this.source=t.source[i],this.sourceIndex=i,this.glTexture=this.source.glTexture,this.cutX,this.cutY,this.cutWidth,this.cutHeight,this.x=0,this.y=0,this.width,this.height,this.halfWidth,this.halfHeight,this.centerX,this.centerY,this.pivotX=0,this.pivotY=0,this.customPivot=!1,this.rotated=!1,this.autoRound=-1,this.customData={},this.u0=0,this.v0=0,this.u1=0,this.v1=0,this.data={cut:{x:0,y:0,w:0,h:0,r:0,b:0},trim:!1,sourceSize:{w:0,h:0},spriteSourceSize:{x:0,y:0,w:0,h:0,r:0,b:0},radius:0,drawImage:{x:0,y:0,width:0,height:0}},this.setSize(r,o,n,s)},setSize:function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this.cutX=i,this.cutY=n,this.cutWidth=t,this.cutHeight=e,this.width=t,this.height=e,this.halfWidth=Math.floor(.5*t),this.halfHeight=Math.floor(.5*e),this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2);var s=this.data,r=s.cut;r.x=i,r.y=n,r.w=t,r.h=e,r.r=i+t,r.b=n+e,s.sourceSize.w=t,s.sourceSize.h=e,s.spriteSourceSize.w=t,s.spriteSourceSize.h=e,s.radius=.5*Math.sqrt(t*t+e*e);var o=s.drawImage;return o.x=i,o.y=n,o.width=t,o.height=e,this.updateUVs()},setTrim:function(t,e,i,n,s,r){var o=this.data,a=o.spriteSourceSize;return o.trim=!0,o.sourceSize.w=t,o.sourceSize.h=e,a.x=i,a.y=n,a.w=s,a.h=r,a.r=i+s,a.b=n+r,this.x=i,this.y=n,this.width=s,this.height=r,this.halfWidth=.5*s,this.halfHeight=.5*r,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.updateUVs()},setCropUVs:function(t,e,i,n,r,o,a){var h=this.cutX,l=this.cutY,u=this.cutWidth,c=this.cutHeight,d=this.realWidth,f=this.realHeight,p=h+(e=s(e,0,d)),g=l+(i=s(i,0,f)),v=n=s(n,0,d-e),m=r=s(r,0,f-i),y=this.data;if(y.trim){var x=y.spriteSourceSize,T=e+(n=s(n,0,u-e)),w=i+(r=s(r,0,c-i));if(!(x.rT||x.y>w)){var E=Math.max(x.x,e),_=Math.max(x.y,i),b=Math.min(x.r,T)-E,A=Math.min(x.b,w)-_;v=b,m=A,p=o?h+(u-(E-x.x)-b):h+(E-x.x),g=a?l+(c-(_-x.y)-A):l+(_-x.y),e=E,i=_,n=b,r=A}else p=0,g=0,v=0,m=0}else o&&(p=h+(u-e-n)),a&&(g=l+(c-i-r));var S=this.source.width,C=this.source.height;return t.u0=Math.max(0,p/S),t.v0=Math.max(0,g/C),t.u1=Math.min(1,(p+v)/S),t.v1=Math.min(1,(g+m)/C),t.x=e,t.y=i,t.cx=p,t.cy=g,t.cw=v,t.ch=m,t.width=n,t.height=r,t.flipX=o,t.flipY=a,t},updateCropUVs:function(t,e,i){return this.setCropUVs(t,t.x,t.y,t.width,t.height,e,i)},updateUVs:function(){var t=this.cutX,e=this.cutY,i=this.cutWidth,n=this.cutHeight,s=this.data.drawImage;s.width=i,s.height=n;var r=this.source.width,o=this.source.height;return this.u0=t/r,this.v0=e/o,this.u1=(t+i)/r,this.v1=(e+n)/o,this},updateUVsInverted:function(){var t=this.source.width,e=this.source.height;return this.u0=(this.cutX+this.cutHeight)/t,this.v0=this.cutY/e,this.u1=this.cutX/t,this.v1=(this.cutY+this.cutWidth)/e,this},clone:function(){var t=new o(this.texture,this.name,this.sourceIndex);return t.cutX=this.cutX,t.cutY=this.cutY,t.cutWidth=this.cutWidth,t.cutHeight=this.cutHeight,t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t.halfWidth=this.halfWidth,t.halfHeight=this.halfHeight,t.centerX=this.centerX,t.centerY=this.centerY,t.rotated=this.rotated,t.data=r(!0,t.data,this.data),t.updateUVs(),t},destroy:function(){this.source=null,this.texture=null,this.glTexture=null,this.customData=null,this.data=null},realWidth:{get:function(){return this.data.sourceSize.w}},realHeight:{get:function(){return this.data.sourceSize.h}},radius:{get:function(){return this.data.radius}},trimmed:{get:function(){return this.data.trim}},canvasData:{get:function(){return this.data.drawImage}}});t.exports=o},function(t,e,i){var n=i(0),s=i(96),r=i(390),o=i(391),a=i(46),h=i(154),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=a.ELLIPSE,this.x=t,this.y=e,this.width=i,this.height=n},contains:function(t,e){return s(this,t,e)},getPoint:function(t,e){return r(this,t,e)},getPoints:function(t,e,i){return o(this,t,e,i)},getRandomPoint:function(t){return h(this,t)},setTo:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setEmpty:function(){return this.width=0,this.height=0,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},isEmpty:function(){return this.width<=0||this.height<=0},getMinorRadius:function(){return Math.min(this.width,this.height)/2},getMajorRadius:function(){return Math.max(this.width,this.height)/2},left:{get:function(){return this.x-this.width/2},set:function(t){this.x=t+this.width/2}},right:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},top:{get:function(){return this.y-this.height/2},set:function(t){this.y=t+this.height/2}},bottom:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=l},function(t,e){t.exports=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var n=(e-t.x)/t.width,s=(i-t.y)/t.height;return(n*=n)+(s*=s)<.25}},function(t,e,i){var n=i(238),s=i(0),r=i(90),o=i(2),a=i(6),h=i(7),l=i(384),u=i(108),c=i(69),d=new s({initialize:function(t,e,i){i?e&&!Array.isArray(e)&&(e=[e]):Array.isArray(e)?h(e[0])&&(i=e,e=null):h(e)&&(i=e,e=null),this.scene=t,this.children=new u(e),this.isParent=!0,this.type="Group",this.classType=o(i,"classType",c),this.name=o(i,"name",""),this.active=o(i,"active",!0),this.maxSize=o(i,"maxSize",-1),this.defaultKey=o(i,"defaultKey",null),this.defaultFrame=o(i,"defaultFrame",null),this.runChildUpdate=o(i,"runChildUpdate",!1),this.createCallback=o(i,"createCallback",null),this.removeCallback=o(i,"removeCallback",null),this.createMultipleCallback=o(i,"createMultipleCallback",null),this.internalCreateCallback=o(i,"internalCreateCallback",null),this.internalRemoveCallback=o(i,"internalRemoveCallback",null),i&&this.createMultiple(i)},create:function(t,e,i,n,s,r){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.defaultKey),void 0===n&&(n=this.defaultFrame),void 0===s&&(s=!0),void 0===r&&(r=!0),this.isFull())return null;var o=new this.classType(this.scene,t,e,i,n);return this.scene.sys.displayList.add(o),o.preUpdate&&this.scene.sys.updateList.add(o),o.visible=s,o.setActive(r),this.add(o),o},createMultiple:function(t){if(this.isFull())return[];Array.isArray(t)||(t=[t]);var e=[];if(t[0].key)for(var i=0;i=0;u--)if((l=d[u]).active===i){if(++c===e)break}else l=null;return l?("number"==typeof s&&(l.x=s),"number"==typeof r&&(l.y=r),l):n?this.create(s,r,o,a,h):null},get:function(t,e,i,n,s){return this.getFirst(!1,!0,t,e,i,n,s)},getFirstAlive:function(t,e,i,n,s,r){return this.getFirst(!0,t,e,i,n,s,r)},getFirstDead:function(t,e,i,n,s,r){return this.getFirst(!1,t,e,i,n,s,r)},playAnimation:function(t,e){return n.PlayAnimation(this.children.entries,t,e),this},isFull:function(){return-1!==this.maxSize&&this.children.size>=this.maxSize},countActive:function(t){void 0===t&&(t=!0);for(var e=0,i=0;i=0&&t=0&&e-1&&this.entries.splice(e,1),this},dump:function(){console.group("Set");for(var t=0;t-1},union:function(t){var e=new n;return t.entries.forEach(function(t){e.set(t)}),this.entries.forEach(function(t){e.set(t)}),e},intersect:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)&&e.set(i)}),e},difference:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)||e.set(i)}),e},size:{get:function(){return this.entries.length},set:function(t){return t0;e--){var i=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[i],t[i]=n}return t}},function(t,e){t.exports=function(t,e,i){return(e-t)*i+t}},function(t,e,i){(function(e){var i={android:!1,chromeOS:!1,cordova:!1,crosswalk:!1,desktop:!1,ejecta:!1,electron:!1,iOS:!1,iOSVersion:0,iPad:!1,iPhone:!1,kindle:!1,linux:!1,macOS:!1,node:!1,nodeWebkit:!1,pixelRatio:1,webApp:!1,windows:!1,windowsPhone:!1};t.exports=function(){var t=navigator.userAgent;/Windows/.test(t)?i.windows=!0:/Mac OS/.test(t)&&!/like Mac OS/.test(t)?i.macOS=!0:/Android/.test(t)?i.android=!0:/Linux/.test(t)?i.linux=!0:/iP[ao]d|iPhone/i.test(t)?(i.iOS=!0,navigator.appVersion.match(/OS (\d+)/),i.iOSVersion=parseInt(RegExp.$1,10),i.iPhone=-1!==t.toLowerCase().indexOf("iphone"),i.iPad=-1!==t.toLowerCase().indexOf("ipad")):/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?i.kindle=!0:/CrOS/.test(t)&&(i.chromeOS=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(i.android=!1,i.iOS=!1,i.macOS=!1,i.windows=!0,i.windowsPhone=!0);var n=/Silk/.test(t);return(i.windows||i.macOS||i.linux&&!n||i.chromeOS)&&(i.desktop=!0),(i.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(i.desktop=!1),navigator.standalone&&(i.webApp=!0),void 0!==window.cordova&&(i.cordova=!0),void 0!==e&&e.versions&&e.versions.node&&(i.node=!0),i.node&&"object"==typeof e.versions&&(i.nodeWebkit=!!e.versions["node-webkit"],i.electron=!!e.versions.electron),void 0!==window.ejecta&&(i.ejecta=!0),/Crosswalk/.test(t)&&(i.crosswalk=!0),i.pixelRatio=window.devicePixelRatio||1,i}()}).call(this,i(720))},function(t,e,i){var n,s=i(116),r={chrome:!1,chromeVersion:0,edge:!1,firefox:!1,firefoxVersion:0,ie:!1,ieVersion:0,mobileSafari:!1,opera:!1,safari:!1,safariVersion:0,silk:!1,trident:!1,tridentVersion:0};t.exports=(n=navigator.userAgent,/Edge\/\d+/.test(n)?r.edge=!0:/Chrome\/(\d+)/.test(n)&&!s.windowsPhone?(r.chrome=!0,r.chromeVersion=parseInt(RegExp.$1,10)):/Firefox\D+(\d+)/.test(n)?(r.firefox=!0,r.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(n)&&s.iOS?r.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(n)?(r.ie=!0,r.ieVersion=parseInt(RegExp.$1,10)):/Opera/.test(n)?r.opera=!0:/Safari/.test(n)&&!s.windowsPhone?r.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(n)&&(r.ie=!0,r.trident=!0,r.tridentVersion=parseInt(RegExp.$1,10),r.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(n)&&(r.silk=!0),r)},function(t,e){t.exports=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)}},function(t,e,i){t.exports={ADD:i(771),ERROR:i(772),LOAD:i(773),READY:i(774),REMOVE:i(775)}},function(t,e){t.exports=function(t,e){var i;if(e)"string"==typeof e?i=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(i=e);else if(t.parentElement)return t;return i||(i=document.body),i.appendChild(t),t}},function(t,e,i){var n=i(79);t.exports=function(t,e,i,s){var r;if(void 0===s&&(s=t),!Array.isArray(e))return-1!==(r=t.indexOf(e))?(n(t,r),i&&i.call(s,e),e):null;for(var o=e.length-1;o>=0;){var a=e[o];-1!==(r=t.indexOf(a))?(n(t,r),i&&i.call(s,a)):e.pop(),o--}return e}},function(t,e){t.exports={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:42,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,NUMPAD_ZERO:96,NUMPAD_ONE:97,NUMPAD_TWO:98,NUMPAD_THREE:99,NUMPAD_FOUR:100,NUMPAD_FIVE:101,NUMPAD_SIX:102,NUMPAD_SEVEN:103,NUMPAD_EIGHT:104,NUMPAD_NINE:105,NUMPAD_ADD:107,NUMPAD_SUBTRACT:109,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,SEMICOLON:186,PLUS:187,COMMA:188,MINUS:189,PERIOD:190,FORWARD_SLASH:191,BACK_SLASH:220,QUOTES:222,BACKTICK:192,OPEN_BRACKET:219,CLOSED_BRACKET:221,SEMICOLON_FIREFOX:59,COLON:58,COMMA_FIREFOX_WINDOWS:60,COMMA_FIREFOX:62,BRACKET_RIGHT_FIREFOX:174,BRACKET_LEFT_FIREFOX:175}},function(t,e){t.exports={PENDING:0,INIT:1,START:2,LOADING:3,CREATING:4,RUNNING:5,PAUSED:6,SLEEPING:7,SHUTDOWN:8,DESTROYED:9}},function(t,e,i){var n=i(0),s=i(67),r=i(9),o=i(59),a=i(18),h=i(1),l=new n({Extends:r,initialize:function(t){r.call(this),this.game=t,this.jsonCache=t.cache.json,this.sounds=[],this.mute=!1,this.volume=1,this.pauseOnBlur=!0,this._rate=1,this._detune=0,this.locked=this.locked||!1,this.unlocked=!1,t.events.on(a.BLUR,function(){this.pauseOnBlur&&this.onBlur()},this),t.events.on(a.FOCUS,function(){this.pauseOnBlur&&this.onFocus()},this),t.events.on(a.PRE_STEP,this.update,this),t.events.once(a.DESTROY,this.destroy,this)},add:h,addAudioSprite:function(t,e){void 0===e&&(e={});var i=this.add(t,e);for(var n in i.spritemap=this.jsonCache.get(t).spritemap,i.spritemap)if(i.spritemap.hasOwnProperty(n)){var r=s(e),o=i.spritemap[n];r.loop=!!o.hasOwnProperty("loop")&&o.loop,i.addMarker({name:n,start:o.start,duration:o.end-o.start,config:r})}return i},play:function(t,e){var i=this.add(t);return i.once(o.COMPLETE,i.destroy,i),e?e.name?(i.addMarker(e),i.play(e.name)):i.play(e):i.play()},playAudioSprite:function(t,e,i){var n=this.addAudioSprite(t);return n.once(o.COMPLETE,n.destroy,n),n.play(e,i)},remove:function(t){var e=this.sounds.indexOf(t);return-1!==e&&(t.destroy(),this.sounds.splice(e,1),!0)},removeByKey:function(t){for(var e=0,i=this.sounds.length-1;i>=0;i--){var n=this.sounds[i];n.key===t&&(n.destroy(),this.sounds.splice(i,1),e++)}return e},pauseAll:function(){this.forEachActiveSound(function(t){t.pause()}),this.emit(o.PAUSE_ALL,this)},resumeAll:function(){this.forEachActiveSound(function(t){t.resume()}),this.emit(o.RESUME_ALL,this)},stopAll:function(){this.forEachActiveSound(function(t){t.stop()}),this.emit(o.STOP_ALL,this)},unlock:h,onBlur:h,onFocus:h,update:function(t,e){this.unlocked&&(this.unlocked=!1,this.locked=!1,this.emit(o.UNLOCKED,this));for(var i=this.sounds.length-1;i>=0;i--)this.sounds[i].pendingRemove&&this.sounds.splice(i,1);this.sounds.forEach(function(i){i.update(t,e)})},destroy:function(){this.removeAllListeners(),this.forEachActiveSound(function(t){t.destroy()}),this.sounds.length=0,this.sounds=null,this.game=null},forEachActiveSound:function(t,e){var i=this;this.sounds.forEach(function(n,s){n&&!n.pendingRemove&&t.call(e||i,n,s,i.sounds)})},setRate:function(t){return this.rate=t,this},rate:{get:function(){return this._rate},set:function(t){this._rate=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_RATE,this,t)}},setDetune:function(t){return this.detune=t,this},detune:{get:function(){return this._detune},set:function(t){this._detune=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_DETUNE,this,t)}}});t.exports=l},function(t,e,i){var n=i(0),s=i(9),r=i(59),o=i(17),a=i(1),h=new n({Extends:s,initialize:function(t,e,i){s.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=this.duration||0,this.totalDuration=this.totalDuration||0,this.config={mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},this.currentConfig=this.config,this.config=o(this.config,i),this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(console.error("addMarker "+t.name+" already exists in Sound"),!1):(t=o(!0,{name:"",start:0,duration:this.totalDuration-(t.start||0),config:{mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0}},t),this.markers[t.name]=t,!0))},updateMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(this.markers[t.name]=o(!0,this.markers[t.name],t),!0):(console.warn("Audio Marker: "+t.name+" missing in Sound: "+this.key),!1))},removeMarker:function(t){var e=this.markers[t];return e?(this.markers[t]=null,e):null},play:function(t,e){if(void 0===t&&(t=""),"object"==typeof t&&(e=t,t=""),"string"!=typeof t)return!1;if(t){if(!this.markers[t])return console.warn("Marker: "+t+" missing in Sound: "+this.key),!1;this.currentMarker=this.markers[t],this.currentConfig=this.currentMarker.config,this.duration=this.currentMarker.duration}else this.currentMarker=null,this.currentConfig=this.config,this.duration=this.totalDuration;return this.resetConfig(),this.currentConfig=o(this.currentConfig,e),this.isPlaying=!0,this.isPaused=!1,!0},pause:function(){return!(this.isPaused||!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!0,!0)},resume:function(){return!(!this.isPaused||this.isPlaying)&&(this.isPlaying=!0,this.isPaused=!1,!0)},stop:function(){return!(!this.isPaused&&!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!1,this.resetConfig(),!0)},applyConfig:function(){this.mute=this.currentConfig.mute,this.volume=this.currentConfig.volume,this.rate=this.currentConfig.rate,this.detune=this.currentConfig.detune,this.loop=this.currentConfig.loop},resetConfig:function(){this.currentConfig.seek=0,this.currentConfig.delay=0},update:a,calculateRate:function(){var t=this.currentConfig.detune+this.manager.detune,e=Math.pow(1.0005777895065548,t);this.totalRate=this.currentConfig.rate*this.manager.rate*e},destroy:function(){this.pendingRemove||(this.emit(r.DESTROY,this),this.pendingRemove=!0,this.manager=null,this.key="",this.removeAllListeners(),this.isPlaying=!1,this.isPaused=!1,this.config=null,this.currentConfig=null,this.markers=null,this.currentMarker=null)}});t.exports=h},function(t,e,i){var n=i(181),s=i(0),r=i(1),o=i(128),a=new s({initialize:function(t){this.parent=t,this.list=[],this.position=0,this.addCallback=r,this.removeCallback=r,this._sortKey=""},add:function(t,e){return e?n.Add(this.list,t):n.Add(this.list,t,0,this.addCallback,this)},addAt:function(t,e,i){return i?n.AddAt(this.list,t,e):n.AddAt(this.list,t,e,0,this.addCallback,this)},getAt:function(t){return this.list[t]},getIndex:function(t){return this.list.indexOf(t)},sort:function(t,e){return t?(void 0===e&&(e=function(e,i){return e[t]-i[t]}),o.inplace(this.list,e),this):this},getByName:function(t){return n.GetFirst(this.list,"name",t)},getRandom:function(t,e){return n.GetRandom(this.list,t,e)},getFirst:function(t,e,i,s){return n.GetFirst(this.list,t,e,i,s)},getAll:function(t,e,i,s){return n.GetAll(this.list,t,e,i,s)},count:function(t,e){return n.CountAllMatching(this.list,t,e)},swap:function(t,e){n.Swap(this.list,t,e)},moveTo:function(t,e){return n.MoveTo(this.list,t,e)},remove:function(t,e){return e?n.Remove(this.list,t):n.Remove(this.list,t,this.removeCallback,this)},removeAt:function(t,e){return e?n.RemoveAt(this.list,t):n.RemoveAt(this.list,t,this.removeCallback,this)},removeBetween:function(t,e,i){return i?n.RemoveBetween(this.list,t,e):n.RemoveBetween(this.list,t,e,this.removeCallback,this)},removeAll:function(t){for(var e=this.list.length;e--;)this.remove(this.list[e],t);return this},bringToTop:function(t){return n.BringToTop(this.list,t)},sendToBack:function(t){return n.SendToBack(this.list,t)},moveUp:function(t){return n.MoveUp(this.list,t),t},moveDown:function(t){return n.MoveDown(this.list,t),t},reverse:function(){return this.list.reverse(),this},shuffle:function(){return n.Shuffle(this.list),this},replace:function(t,e){return n.Replace(this.list,t,e)},exists:function(t){return this.list.indexOf(t)>-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){for(var i=[null],n=2;n0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}}});t.exports=a},function(t,e,i){var n=i(182),s=i(382);t.exports=function(t,e){if(void 0===e&&(e=90),!n(t))return null;if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)(t=s(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t.reverse(),t=s(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;il&&(r=l),o>l&&(o=l),a=s,h=r;;)if(a0&&o.length0&&a.lengthe.right||t.y>e.bottom)}},function(t,e,i){var n=i(6),s={},r={register:function(t,e,i,n,r){s[t]={plugin:e,mapping:i,settingsKey:n,configKey:r}},getPlugin:function(t){return s[t]},install:function(t){var e=t.scene.sys,i=e.settings.input,r=e.game.config;for(var o in s){var a=s[o].plugin,h=s[o].mapping,l=s[o].settingsKey,u=s[o].configKey;n(i,l,r[u])&&(t[h]=new a(t))}},remove:function(t){s.hasOwnProperty(t)&&delete s[t]}};t.exports=r},function(t,e,i){t.exports={ANY_KEY_DOWN:i(1203),ANY_KEY_UP:i(1204),COMBO_MATCH:i(1205),DOWN:i(1206),KEY_DOWN:i(1207),KEY_UP:i(1208),UP:i(1209)}},function(t,e){t.exports=function(t,e){return!!t.url&&(t.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t.url:e+t.url)}},function(t,e){t.exports=function(t,e,i,n,s){return void 0===t&&(t=""),void 0===e&&(e=!0),void 0===i&&(i=""),void 0===n&&(n=""),void 0===s&&(s=0),{responseType:t,async:e,user:i,password:n,timeout:s,header:void 0,headerValue:void 0,requestedWith:!1,overrideMimeType:void 0}}},function(t,e,i){var n=i(0),s=i(214),r=i(69),o=new n({Extends:r,Mixins:[s.Acceleration,s.Angular,s.Bounce,s.Debug,s.Drag,s.Enable,s.Friction,s.Gravity,s.Immovable,s.Mass,s.Size,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t,e,i,n,s),this.body=null}});t.exports=o},function(t,e,i){t.exports={CalculateFacesAt:i(217),CalculateFacesWithin:i(51),Copy:i(1301),CreateFromTiles:i(1302),CullTiles:i(1303),Fill:i(1304),FilterTiles:i(1305),FindByIndex:i(1306),FindTile:i(1307),ForEachTile:i(1308),GetTileAt:i(138),GetTileAtWorldXY:i(1309),GetTilesWithin:i(24),GetTilesWithinShape:i(1310),GetTilesWithinWorldXY:i(1311),HasTileAt:i(470),HasTileAtWorldXY:i(1312),IsInLayerBounds:i(103),PutTileAt:i(218),PutTileAtWorldXY:i(1313),PutTilesAt:i(1314),Randomize:i(1315),RemoveTileAt:i(471),RemoveTileAtWorldXY:i(1316),RenderDebug:i(1317),ReplaceByIndex:i(469),SetCollision:i(1318),SetCollisionBetween:i(1319),SetCollisionByExclusion:i(1320),SetCollisionByProperty:i(1321),SetCollisionFromCollisionGroup:i(1322),SetTileIndexCallback:i(1323),SetTileLocationCallback:i(1324),Shuffle:i(1325),SwapByIndex:i(1326),TileToWorldX:i(139),TileToWorldXY:i(1327),TileToWorldY:i(140),WeightedRandomize:i(1328),WorldToTileX:i(63),WorldToTileXY:i(1329),WorldToTileY:i(64)}},function(t,e,i){var n=i(103);t.exports=function(t,e,i,s){if(void 0===i&&(i=!1),n(t,e,s)){var r=s.data[e][t]||null;return null===r?null:-1===r.index?i?r:null:r}return null}},function(t,e){t.exports=function(t,e,i){var n=i.baseTileWidth,s=i.tilemapLayer,r=0;return s&&(void 0===e&&(e=s.scene.cameras.main),r=s.x+e.scrollX*(1-s.scrollFactorX),n*=s.scaleX),r+t*n}},function(t,e){t.exports=function(t,e,i){var n=i.baseTileHeight,s=i.tilemapLayer,r=0;return s&&(void 0===e&&(e=s.scene.cameras.main),r=s.y+e.scrollY*(1-s.scrollFactorY),n*=s.scaleY),r+t*n}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o,a){(void 0===i||i<=0)&&(i=32),(void 0===n||n<=0)&&(n=32),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o={}),void 0===a&&(a={}),this.name=t,this.firstgid=e,this.tileWidth=i,this.tileHeight=n,this.tileMargin=s,this.tileSpacing=r,this.tileProperties=o,this.tileData=a,this.image=null,this.glTexture=null,this.rows=0,this.columns=0,this.total=0,this.texCoordinates=[]},getTileProperties:function(t){return this.containsTileIndex(t)?this.tileProperties[t-this.firstgid]:null},getTileData:function(t){return this.containsTileIndex(t)?this.tileData[t-this.firstgid]:null},getTileCollisionGroup:function(t){var e=this.getTileData(t);return e&&e.objectgroup?e.objectgroup:null},containsTileIndex:function(t){return t>=this.firstgid&&t1?2-s:s,o=r*Math.cos(i),a=r*Math.sin(i);return e.x=t.x+o*t.radius,e.y=t.y+a*t.radius,e}},function(t,e,i){var n=i(22),s=i(0),r=i(9),o=i(111),a=i(267),h=i(268),l=i(6),u=new s({Extends:r,initialize:function(t,e,i){r.call(this),this.manager=t,this.key=e,this.type="frame",this.frames=this.getFrames(t.textureManager,l(i,"frames",[]),l(i,"defaultTextureKey",null)),this.frameRate=l(i,"frameRate",null),this.duration=l(i,"duration",null),null===this.duration&&null===this.frameRate?(this.frameRate=24,this.duration=this.frameRate/this.frames.length*1e3):this.duration&&null===this.frameRate?this.frameRate=this.frames.length/(this.duration/1e3):this.duration=this.frames.length/this.frameRate*1e3,this.msPerFrame=1e3/this.frameRate,this.skipMissedFrames=l(i,"skipMissedFrames",!0),this.delay=l(i,"delay",0),this.repeat=l(i,"repeat",0),this.repeatDelay=l(i,"repeatDelay",0),this.yoyo=l(i,"yoyo",!1),this.showOnStart=l(i,"showOnStart",!1),this.hideOnComplete=l(i,"hideOnComplete",!1),this.paused=!1,this.manager.on(o.PAUSE_ALL,this.pause,this),this.manager.on(o.RESUME_ALL,this.resume,this)},addFrame:function(t){return this.addFrameAt(this.frames.length,t)},addFrameAt:function(t,e){var i=this.getFrames(this.manager.textureManager,e);if(i.length>0){if(0===t)this.frames=i.concat(this.frames);else if(t===this.frames.length)this.frames=this.frames.concat(i);else{var n=this.frames.slice(0,t),s=this.frames.slice(t);this.frames=n.concat(i,s)}this.updateFrameSequence()}return this},checkFrame:function(t){return t>=0&&t0){s.isLast=!0,s.nextFrame=a[0],a[0].prevFrame=s;var v=1/(a.length-1);for(r=0;r=this.frames.length&&(e=0),t.currentAnim!==this&&(t.currentAnim=this,t.frameRate=this.frameRate,t.duration=this.duration,t.msPerFrame=this.msPerFrame,t.skipMissedFrames=this.skipMissedFrames,t._delay=this.delay,t._repeat=this.repeat,t._repeatDelay=this.repeatDelay,t._yoyo=this.yoyo);var i=this.frames[e];0!==e||t.forward||(i=this.getLastFrame()),t.updateFrame(i)},getFrameByProgress:function(t){return t=n(t,0,1),a(t,this.frames,"progress")},nextFrame:function(t){var e=t.currentFrame;e.isLast?t._yoyo?this.handleYoyoFrame(t,!1):t.repeatCounter>0?t._reverse&&t.forward?t.forward=!1:this.repeatAnimation(t):this.completeAnimation(t):this.updateAndGetNextTick(t,e.nextFrame)},handleYoyoFrame:function(t,e){if(e||(e=!1),t._reverse===!e&&t.repeatCounter>0)return t.forward=e,void this.repeatAnimation(t);if(t._reverse===e||0!==t.repeatCounter){t.forward=e;var i=e?t.currentFrame.nextFrame:t.currentFrame.prevFrame;this.updateAndGetNextTick(t,i)}else this.completeAnimation(t)},getLastFrame:function(){return this.frames[this.frames.length-1]},previousFrame:function(t){var e=t.currentFrame;e.isFirst?t._yoyo?this.handleYoyoFrame(t,!0):t.repeatCounter>0?t._reverse&&!t.forward?(t.currentFrame=this.getLastFrame(),this.repeatAnimation(t)):(t.forward=!0,this.repeatAnimation(t)):this.completeAnimation(t):this.updateAndGetNextTick(t,e.prevFrame)},updateAndGetNextTick:function(t,e){t.updateFrame(e),this.getNextTick(t)},removeFrame:function(t){var e=this.frames.indexOf(t);return-1!==e&&this.removeFrameAt(e),this},removeFrameAt:function(t){return this.frames.splice(t,1),this.updateFrameSequence(),this},repeatAnimation:function(t){if(2===t._pendingStop)return this.completeAnimation(t);if(t._repeatDelay>0&&!1===t.pendingRepeat)t.pendingRepeat=!0,t.accumulator-=t.nextTick,t.nextTick+=t._repeatDelay;else if(t.repeatCounter--,t.updateFrame(t.currentFrame[t.forward?"nextFrame":"prevFrame"]),t.isPlaying){this.getNextTick(t),t.pendingRepeat=!1;var e=t.currentFrame,i=t.parent;this.emit(o.ANIMATION_REPEAT,this,e),i.emit(o.SPRITE_ANIMATION_KEY_REPEAT+this.key,this,e,t.repeatCounter,i),i.emit(o.SPRITE_ANIMATION_REPEAT,this,e,t.repeatCounter,i)}},setFrame:function(t){t.forward?this.nextFrame(t):this.previousFrame(t)},toJSON:function(){var t={key:this.key,type:this.type,frames:[],frameRate:this.frameRate,duration:this.duration,skipMissedFrames:this.skipMissedFrames,delay:this.delay,repeat:this.repeat,repeatDelay:this.repeatDelay,yoyo:this.yoyo,showOnStart:this.showOnStart,hideOnComplete:this.hideOnComplete};return this.frames.forEach(function(e){t.frames.push(e.toJSON())}),t},updateFrameSequence:function(){for(var t,e=this.frames.length,i=1/(e-1),n=0;n1?(t.isLast=!0,t.prevFrame=this.frames[e-2],t.nextFrame=this.frames[0]):e>1&&(t.prevFrame=this.frames[n-1],t.nextFrame=this.frames[n+1]);return this},pause:function(){return this.paused=!0,this},resume:function(){return this.paused=!1,this},destroy:function(){this.removeAllListeners(),this.manager.off(o.PAUSE_ALL,this.pause,this),this.manager.off(o.RESUME_ALL,this.resume,this),this.manager.remove(this.key);for(var t=0;t=1)return i.x=t.x,i.y=t.y,i;var r=n(t)*e;return e>.5?(r-=t.width+t.height)<=t.width?(i.x=t.right-r,i.y=t.bottom):(i.x=t.x,i.y=t.bottom-(r-t.width)):r<=t.width?(i.x=t.x+r,i.y=t.y):(i.x=t.right,i.y=t.y+(r-t.width)),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=n(t)/i);for(var o=t.x1,a=t.y1,h=t.x2,l=t.y2,u=0;u=1&&(a=1-a,h=1-h),e.x=t.x1+(i*a+r*h),e.y=t.y1+(s*a+o*h),e}},function(t,e){t.exports=function(t,e,i,n,s){var r=n+Math.atan2(t.y-i,t.x-e);return t.x=e+s*Math.cos(r),t.y=i+s*Math.sin(r),t}},function(t,e){t.exports=function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)}},function(t,e){t.exports=function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){if(this.entries={},this.size=0,Array.isArray(t))for(var e=0;e=(t=t.toString()).length)switch(n){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((s=e-t.length)/2);t=new Array(s-r+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t}},function(t,e,i){var n=i(291),s=i(294),r=i(296),o=i(297);t.exports=function(t){switch(typeof t){case"string":return"rgb"===t.substr(0,3).toLowerCase()?o(t):n(t);case"number":return s(t);case"object":return r(t)}}},function(t,e){t.exports=function(t,e,i){return t<<16|e<<8|i}},function(t,e,i){var n=i(162);t.exports=function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1);var r=Math.floor(6*t),o=6*t-r,a=Math.floor(i*(1-e)*255),h=Math.floor(i*(1-o*e)*255),l=Math.floor(i*(1-(1-o)*e)*255),u=i=Math.floor(i*=255),c=i,d=i,f=r%6;return 0===f?(c=l,d=a):1===f?(u=h,d=a):2===f?(u=a,d=l):3===f?(u=a,c=h):4===f?(u=l,c=a):5===f&&(c=a,d=h),s?s.setTo?s.setTo(u,c,d,s.alpha,!1):(s.r=u,s.g=c,s.b=d,s.color=n(u,c,d),s):{r:u,g:c,b:d,color:n(u,c,d)}}},function(t,e){var i,n="";t.exports={disable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!1),t},enable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!0),t},getPrefix:i=function(t){for(var e=["i","webkitI","msI","mozI","oI"],i=0;i0&&(n=1/Math.sqrt(n),this.x=t*n,this.y=e*n,this.z=i*n),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},cross:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z;return this.x=i*o-n*r,this.y=n*s-e*o,this.z=e*r-i*s,this},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this},transformMat3:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=e*s[0]+i*s[3]+n*s[6],this.y=e*s[1]+i*s[4]+n*s[7],this.z=e*s[2]+i*s[5]+n*s[8],this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=s[0]*e+s[4]*i+s[8]*n+s[12],this.y=s[1]*e+s[5]*i+s[9]*n+s[13],this.z=s[2]*e+s[6]*i+s[10]*n+s[14],this},transformCoordinates:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=e*s[0]+i*s[4]+n*s[8]+s[12],o=e*s[1]+i*s[5]+n*s[9]+s[13],a=e*s[2]+i*s[6]+n*s[10]+s[14],h=e*s[3]+i*s[7]+n*s[11]+s[15];return this.x=r/h,this.y=o/h,this.z=a/h,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},project:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=s[0],o=s[1],a=s[2],h=s[3],l=s[4],u=s[5],c=s[6],d=s[7],f=s[8],p=s[9],g=s[10],v=s[11],m=s[12],y=s[13],x=s[14],T=1/(e*h+i*d+n*v+s[15]);return this.x=(e*r+i*l+n*f+m)*T,this.y=(e*o+i*u+n*p+y)*T,this.z=(e*a+i*c+n*g+x)*T,this},unproject:function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,o=this.x-i,a=r-this.y-1-n,h=this.z;return this.x=2*o/s-1,this.y=2*a/r-1,this.z=2*h-1,this.project(e)},reset:function(){return this.x=0,this.y=0,this.z=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0,0),n.LEFT=new n(-1,0,0),n.UP=new n(0,-1,0),n.DOWN=new n(0,1,0),n.FORWARD=new n(0,0,1),n.BACK=new n(0,0,-1),n.ONE=new n(1,1,1),t.exports=n},function(t,e,i){t.exports={Global:["game","anims","cache","plugins","registry","scale","sound","textures"],CoreScene:["EventEmitter","CameraManager","GameObjectCreator","GameObjectFactory","ScenePlugin","DisplayList","UpdateList"],DefaultScene:["Clock","DataManagerPlugin","InputPlugin","Loader","TweenManager","LightsPlugin"]}},function(t,e,i){var n=i(11),s=i(13);t.exports=function(t,e){if(void 0===e&&(e=new n),0===t.length)return e;for(var i,r,o,a=Number.MAX_VALUE,h=Number.MAX_VALUE,l=s.MIN_SAFE_INTEGER,u=s.MIN_SAFE_INTEGER,c=0;c0},isTransitionIn:function(){return this.settings.isTransition},isVisible:function(){return this.settings.visible},setVisible:function(t){return this.settings.visible=t,this},setActive:function(t,e){return t?this.resume(e):this.pause(e)},start:function(t){t&&(this.settings.data=t),this.settings.status=s.START,this.settings.active=!0,this.settings.visible=!0,this.events.emit(o.START,this),this.events.emit(o.READY,this,t)},shutdown:function(t){this.events.off(o.TRANSITION_INIT),this.events.off(o.TRANSITION_START),this.events.off(o.TRANSITION_COMPLETE),this.events.off(o.TRANSITION_OUT),this.settings.status=s.SHUTDOWN,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.SHUTDOWN,this,t)},destroy:function(){this.settings.status=s.DESTROYED,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.DESTROY,this),this.events.removeAllListeners();for(var t=["scene","game","anims","cache","plugins","registry","sound","textures","add","camera","displayList","events","make","scenePlugin","updateList"],e=0;e0},getRenderList:function(){return this.dirty&&(this.renderList=this.children.list.filter(this.childCanRender,this),this.dirty=!1),this.renderList},clear:function(){this.children.removeAll(),this.dirty=!0},preDestroy:function(){this.children.destroy(),this.renderList=[]}});t.exports=u},function(t,e,i){var n=i(181),s=i(52),r=i(0),o=i(12),a=i(90),h=i(14),l=i(11),u=i(947),c=i(386),d=i(3),f=new r({Extends:h,Mixins:[o.AlphaSingle,o.BlendMode,o.ComputedSize,o.Depth,o.Mask,o.Transform,o.Visible,u],initialize:function(t,e,i,n){h.call(this,t,"Container"),this.list=[],this.exclusive=!0,this.maxSize=-1,this.position=0,this.localTransform=new o.TransformMatrix,this.tempTransformMatrix=new o.TransformMatrix,this._displayList=t.sys.displayList,this._sortKey="",this._sysEvents=t.sys.events,this.scrollFactorX=1,this.scrollFactorY=1,this.setPosition(e,i),this.clearAlpha(),this.setBlendMode(s.SKIP_CHECK),n&&this.add(n)},originX:{get:function(){return.5}},originY:{get:function(){return.5}},displayOriginX:{get:function(){return.5*this.width}},displayOriginY:{get:function(){return.5*this.height}},setExclusive:function(t){return void 0===t&&(t=!0),this.exclusive=t,this},getBounds:function(t){if(void 0===t&&(t=new l),t.setTo(this.x,this.y,0,0),this.list.length>0)for(var e=this.list,i=new l,n=0;n-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){var i,n=[null],s=this.list.slice(),r=s.length;for(i=2;i0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}},preDestroy:function(){this.removeAll(!!this.exclusive),this.localTransform.destroy(),this.tempTransformMatrix.destroy(),this.list=[],this._displayList=null}});t.exports=f},function(t,e,i){var n=i(129),s=i(0),r=i(952),o=new s({Extends:n,Mixins:[r],initialize:function(t,e,i,s,r,o,a){n.call(this,t,e,i,s,r,o,a),this.type="DynamicBitmapText",this.scrollX=0,this.scrollY=0,this.cropWidth=0,this.cropHeight=0,this.displayCallback,this.callbackData={parent:this,color:0,tint:{topLeft:0,topRight:0,bottomLeft:0,bottomRight:0},index:0,charCode:0,x:0,y:0,scale:0,rotation:0,data:0}},setSize:function(t,e){return this.cropWidth=t,this.cropHeight=e,this},setDisplayCallback:function(t){return this.displayCallback=t,this},setScrollX:function(t){return this.scrollX=t,this},setScrollY:function(t){return this.scrollY=t,this}});t.exports=o},function(t,e,i){var n=i(91),s=i(0),r=i(190),o=i(266),a=i(269),h=i(270),l=i(274),u=i(153),c=i(279),d=i(280),f=i(277),p=i(32),g=i(95),v=i(14),m=i(2),y=i(6),x=i(13),T=i(958),w=new s({Extends:v,Mixins:[o,a,h,l,u,c,d,f,T],initialize:function(t,e){var i=y(e,"x",0),n=y(e,"y",0);v.call(this,t,"Graphics"),this.setPosition(i,n),this.initPipeline(),this.displayOriginX=0,this.displayOriginY=0,this.commandBuffer=[],this.defaultFillColor=-1,this.defaultFillAlpha=1,this.defaultStrokeWidth=1,this.defaultStrokeColor=-1,this.defaultStrokeAlpha=1,this._lineWidth=1,this._tempMatrix1=new p,this._tempMatrix2=new p,this._tempMatrix3=new p,this.setDefaultStyles(e)},setDefaultStyles:function(t){return y(t,"lineStyle",null)&&(this.defaultStrokeWidth=y(t,"lineStyle.width",1),this.defaultStrokeColor=y(t,"lineStyle.color",16777215),this.defaultStrokeAlpha=y(t,"lineStyle.alpha",1),this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha)),y(t,"fillStyle",null)&&(this.defaultFillColor=y(t,"fillStyle.color",16777215),this.defaultFillAlpha=y(t,"fillStyle.alpha",1),this.fillStyle(this.defaultFillColor,this.defaultFillAlpha)),this},lineStyle:function(t,e,i){return void 0===i&&(i=1),this.commandBuffer.push(r.LINE_STYLE,t,e,i),this._lineWidth=t,this},fillStyle:function(t,e){return void 0===e&&(e=1),this.commandBuffer.push(r.FILL_STYLE,t,e),this},fillGradientStyle:function(t,e,i,n,s){return void 0===s&&(s=1),this.commandBuffer.push(r.GRADIENT_FILL_STYLE,s,t,e,i,n),this},lineGradientStyle:function(t,e,i,n,s,o){return void 0===o&&(o=1),this.commandBuffer.push(r.GRADIENT_LINE_STYLE,t,o,e,i,n,s),this},setTexture:function(t,e,i){if(void 0===i&&(i=0),void 0===t)this.commandBuffer.push(r.CLEAR_TEXTURE);else{var n=this.scene.sys.textures.getFrame(t,e);n&&(2===i&&(i=3),this.commandBuffer.push(r.SET_TEXTURE,n,i))}return this},beginPath:function(){return this.commandBuffer.push(r.BEGIN_PATH),this},closePath:function(){return this.commandBuffer.push(r.CLOSE_PATH),this},fillPath:function(){return this.commandBuffer.push(r.FILL_PATH),this},fill:function(){return this.commandBuffer.push(r.FILL_PATH),this},strokePath:function(){return this.commandBuffer.push(r.STROKE_PATH),this},stroke:function(){return this.commandBuffer.push(r.STROKE_PATH),this},fillCircleShape:function(t){return this.fillCircle(t.x,t.y,t.radius)},strokeCircleShape:function(t){return this.strokeCircle(t.x,t.y,t.radius)},fillCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.fillPath(),this},strokeCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.strokePath(),this},fillRectShape:function(t){return this.fillRect(t.x,t.y,t.width,t.height)},strokeRectShape:function(t){return this.strokeRect(t.x,t.y,t.width,t.height)},fillRect:function(t,e,i,n){return this.commandBuffer.push(r.FILL_RECT,t,e,i,n),this},strokeRect:function(t,e,i,n){var s=this._lineWidth/2,r=t-s,o=t+s;return this.beginPath(),this.moveTo(t,e),this.lineTo(t,e+n),this.strokePath(),this.beginPath(),this.moveTo(t+i,e),this.lineTo(t+i,e+n),this.strokePath(),this.beginPath(),this.moveTo(r,e),this.lineTo(o+i,e),this.strokePath(),this.beginPath(),this.moveTo(r,e+n),this.lineTo(o+i,e+n),this.strokePath(),this},fillRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.fillPath(),this},strokeRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.strokePath(),this},fillPointShape:function(t,e){return this.fillPoint(t.x,t.y,e)},fillPoint:function(t,e,i){return!i||i<1?i=1:(t-=i/2,e-=i/2),this.commandBuffer.push(r.FILL_RECT,t,e,i,i),this},fillTriangleShape:function(t){return this.fillTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},strokeTriangleShape:function(t){return this.strokeTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},fillTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.FILL_TRIANGLE,t,e,i,n,s,o),this},strokeTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.STROKE_TRIANGLE,t,e,i,n,s,o),this},strokeLineShape:function(t){return this.lineBetween(t.x1,t.y1,t.x2,t.y2)},lineBetween:function(t,e,i,n){return this.beginPath(),this.moveTo(t,e),this.lineTo(i,n),this.strokePath(),this},lineTo:function(t,e){return this.commandBuffer.push(r.LINE_TO,t,e),this},moveTo:function(t,e){return this.commandBuffer.push(r.MOVE_TO,t,e),this},strokePoints:function(t,e,i,n){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===n&&(n=t.length),this.beginPath(),this.moveTo(t[0].x,t[0].y);for(var s=1;s-1&&this.fillStyle(this.defaultFillColor,this.defaultFillAlpha),this.defaultStrokeColor>-1&&this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha),this},generateTexture:function(t,e,i){var n,s,r=this.scene.sys,o=r.game.renderer;if(void 0===e&&(e=r.scale.width),void 0===i&&(i=r.scale.height),w.TargetCamera.setScene(this.scene),w.TargetCamera.setViewport(0,0,e,i),w.TargetCamera.scrollX=this.x,w.TargetCamera.scrollY=this.y,"string"==typeof t)if(r.textures.exists(t)){var a=(n=r.textures.get(t)).getSourceImage();a instanceof HTMLCanvasElement&&(s=a.getContext("2d"))}else s=(n=r.textures.createCanvas(t,e,i)).getSourceImage().getContext("2d");else t instanceof HTMLCanvasElement&&(s=t.getContext("2d"));return s&&(this.renderCanvas(o,this,0,w.TargetCamera,null,s,!1),n&&n.refresh()),this},preDestroy:function(){this.commandBuffer=[]}});w.TargetCamera=new n,t.exports=w},function(t,e){t.exports={ARC:0,BEGIN_PATH:1,CLOSE_PATH:2,FILL_RECT:3,LINE_TO:4,MOVE_TO:5,LINE_STYLE:6,FILL_STYLE:7,FILL_PATH:8,STROKE_PATH:9,FILL_TRIANGLE:10,STROKE_TRIANGLE:11,SAVE:14,RESTORE:15,TRANSLATE:16,SCALE:17,ROTATE:18,SET_TEXTURE:19,CLEAR_TEXTURE:20,GRADIENT_FILL_STYLE:21,GRADIENT_LINE_STYLE:22}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.width/2,r=t.height/2;return i.x=t.x+s*Math.cos(e),i.y=t.y+r*Math.sin(e),i}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(394),a=i(126),h=i(396),l=i(968),u=new n({Extends:r,Mixins:[s.Depth,s.Mask,s.Pipeline,s.Transform,s.Visible,l],initialize:function(t,e,i,n){if(r.call(this,t,"ParticleEmitterManager"),this.blendMode=-1,this.timeScale=1,this.texture=null,this.frame=null,this.frameNames=[],null===i||"object"!=typeof i&&!Array.isArray(i)||(n=i,i=null),this.setTexture(e,i),this.initPipeline(),this.emitters=new a(this),this.wells=new a(this),n){Array.isArray(n)||(n=[n]);for(var s=0;s0?e.defaultFrame=i[0]:e.defaultFrame=this.defaultFrame,this},addEmitter:function(t){return this.emitters.add(t)},createEmitter:function(t){return this.addEmitter(new h(this,t))},removeEmitter:function(t){return this.emitters.remove(t,!0)},addGravityWell:function(t){return this.wells.add(t)},createGravityWell:function(t){return this.addGravityWell(new o(t))},emitParticle:function(t,e,i){for(var n=this.emitters.list,s=0;ss.width&&(t=s.width-this.frame.cutX),this.frame.cutY+e>s.height&&(e=s.height-this.frame.cutY),this.frame.setSize(t,e,this.frame.cutX,this.frame.cutY)}this.updateDisplayOrigin();var r=this.input;return r&&!r.customHitArea&&(r.hitArea.width=t,r.hitArea.height=e),this},setGlobalTint:function(t){return this.globalTint=t,this},setGlobalAlpha:function(t){return this.globalAlpha=t,this},saveTexture:function(t){return this.textureManager.renameTexture(this.texture.key,t),this._saved=!0,this.texture},fill:function(t,e,i,n,s,r){void 0===e&&(e=1),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.frame.cutWidth),void 0===r&&(r=this.frame.cutHeight);var o=255&(t>>16|0),a=255&(t>>8|0),h=255&(0|t),l=this.gl,u=this.frame;if(this.camera.preRender(1,1),l){var c=this.camera._cx,f=this.camera._cy,p=this.camera._cw,g=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(c,f,p,g,g);var v=this.pipeline;v.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),v.drawFillRect(i,n,s,r,d.getTintFromFloats(o/255,a/255,h/255,1),e),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),v.projOrtho(0,v.width,v.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.context.fillStyle="rgba("+o+","+a+","+h+","+e+")",this.context.fillRect(i+u.cutX,n+u.cutY,s,r),this.renderer.setContext();return this.dirty=!0,this},clear:function(){if(this.dirty){var t=this.gl;if(t){var e=this.renderer;e.setFramebuffer(this.framebuffer,!0),this.frame.cutWidth===this.canvas.width&&this.frame.cutHeight===this.canvas.height||t.scissor(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),e.setFramebuffer(null,!0)}else{var i=this.context;i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),i.restore()}this.dirty=!1}return this},erase:function(t,e,i){this._eraseMode=!0;var s=this.renderer.currentBlendMode;return this.renderer.setBlendMode(n.ERASE),this.draw(t,e,i,1,16777215),this.renderer.setBlendMode(s),this._eraseMode=!1,this},draw:function(t,e,i,n,s){void 0===n&&(n=this.globalAlpha),s=void 0===s?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(s>>16)+(65280&s)+((255&s)<<16),Array.isArray(t)||(t=[t]);var r=this.gl;if(this.camera.preRender(1,1),r){var o=this.camera._cx,a=this.camera._cy,h=this.camera._cw,l=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(o,a,h,l,l);var u=this.pipeline;u.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),this.batchList(t,e,i,n,s),u.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),u.projOrtho(0,u.width,u.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.batchList(t,e,i,n,s),this.renderer.setContext();return this.dirty=!0,this},drawFrame:function(t,e,i,n,s,r){void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.globalAlpha),r=void 0===r?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(r>>16)+(65280&r)+((255&r)<<16);var o=this.gl,a=this.textureManager.getFrame(t,e);if(a){if(this.camera.preRender(1,1),o){var h=this.camera._cx,l=this.camera._cy,u=this.camera._cw,c=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(h,l,u,c,c);var d=this.pipeline;d.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),d.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,r,s,this.camera.matrix,null),d.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),d.projOrtho(0,d.width,d.height,0,-1e3,1e3)}else this.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,s,r);this.dirty=!0}return this},batchList:function(t,e,i,n,s){for(var r=0;rl){if(0===c){for(var g=f;g.length&&(g=g.slice(0,-1),!((p=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var v=d.substr(g.length);u[c]=v,h+=g}var m=u[c].length?c:c+1,y=u.slice(m).join(" ").replace(/[ \n]*$/gi,"");s[o+1]=y+" "+(s[o+1]||""),r=s.length;break}h+=f,l-=p}n+=h.replace(/[ \n]*$/gi,"")+"\n"}}return n=n.replace(/[\s|\n]*$/gi,"")},basicWordWrap:function(t,e,i){for(var n="",s=t.split(this.splitRegExp),r=s.length-1,o=e.measureText(" ").width,a=0;a<=r;a++){for(var h=i,l=s[a].split(" "),u=l.length-1,c=0;c<=u;c++){var d=l[c],f=e.measureText(d).width,p=f+o;p>h&&c>0&&(n+="\n",h=i),n+=d,c0&&(d+=h.lineSpacing*g),i.rtl)c=f-c;else if("right"===i.align)c+=o-h.lineWidths[g];else if("center"===i.align)c+=(o-h.lineWidths[g])/2;else if("justify"===i.align){if(h.lineWidths[g]/h.width>=.85){var v=h.width-h.lineWidths[g],m=e.measureText(" ").width,y=a[g].trim(),x=y.split(" ");v+=(a[g].length-y.length)*m;for(var T=Math.floor(v/m),w=0;T>0;)x[w]+=" ",w=(w+1)%(x.length-1||1),--T;a[g]=x.join(" ")}}this.autoRound&&(c=Math.round(c),d=Math.round(d)),i.strokeThickness&&(this.style.syncShadow(e,i.shadowStroke),e.strokeText(a[g],c,d)),i.color&&(this.style.syncShadow(e,i.shadowFill),e.fillText(a[g],c,d))}e.restore(),this.renderer.gl&&(this.frame.source.glTexture=this.renderer.canvasToTexture(t,this.frame.source.glTexture,!0),this.frame.glTexture=this.frame.source.glTexture),this.dirty=!0;var E=this.input;return E&&!E.customHitArea&&(E.hitArea.width=this.width,E.hitArea.height=this.height),this},getTextMetrics:function(){return this.style.getTextMetrics()},text:{get:function(){return this._text},set:function(t){this.setText(t)}},toJSON:function(){var t=o.ToJSON(this),e={autoRound:this.autoRound,text:this._text,style:this.style.toJSON(),padding:{left:this.padding.left,right:this.padding.right,top:this.padding.top,bottom:this.padding.bottom}};return t.data=e,t},preDestroy:function(){this.style.rtl&&c(this.canvas),s.remove(this.canvas),this.texture.destroy()}});t.exports=p},function(t,e,i){var n=i(26),s=i(0),r=i(12),o=i(18),a=i(14),h=i(324),l=i(164),u=i(984),c=i(3),d=new s({Extends:a,Mixins:[r.Alpha,r.BlendMode,r.ComputedSize,r.Crop,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Tint,r.Transform,r.Visible,u],initialize:function(t,e,i,s,r,l,u){var d=t.sys.game.renderer;a.call(this,t,"TileSprite");var f=t.sys.textures.get(l),p=f.get(u);s&&r?(s=Math.floor(s),r=Math.floor(r)):(s=p.width,r=p.height),this._tilePosition=new c,this._tileScale=new c(1,1),this.dirty=!1,this.renderer=d,this.canvas=n.create(this,s,r),this.context=this.canvas.getContext("2d"),this.displayTexture=f,this.displayFrame=p,this._crop=this.resetCropObject(),this.texture=t.sys.textures.addCanvas(null,this.canvas,!0),this.frame=this.texture.get(),this.potWidth=h(p.width),this.potHeight=h(p.height),this.fillCanvas=n.create2D(this,this.potWidth,this.potHeight),this.fillContext=this.fillCanvas.getContext("2d"),this.fillPattern=null,this.setPosition(e,i),this.setSize(s,r),this.setFrame(u),this.setOriginFromFrame(),this.initPipeline(),t.sys.game.events.on(o.CONTEXT_RESTORED,function(t){var e=t.gl;this.dirty=!0,this.fillPattern=null,this.fillPattern=t.createTexture2D(0,e.LINEAR,e.LINEAR,e.REPEAT,e.REPEAT,e.RGBA,this.fillCanvas,this.potWidth,this.potHeight)},this)},setTexture:function(t,e){return this.displayTexture=this.scene.sys.textures.get(t),this.setFrame(e)},setFrame:function(t){var e=this.displayTexture.get(t);return this.potWidth=h(e.width),this.potHeight=h(e.height),this.canvas.width=0,e.cutWidth&&e.cutHeight?this.renderFlags|=8:this.renderFlags&=-9,this.displayFrame=e,this.dirty=!0,this.updateTileTexture(),this},setTilePosition:function(t,e){return void 0!==t&&(this.tilePositionX=t),void 0!==e&&(this.tilePositionY=e),this},setTileScale:function(t,e){return void 0===t&&(t=this.tileScaleX),void 0===e&&(e=t),this.tileScaleX=t,this.tileScaleY=e,this},updateTileTexture:function(){if(this.dirty&&this.renderer){var t=this.displayFrame;if(t.source.isRenderTexture||t.source.isGLTexture)return console.warn("TileSprites can only use Image or Canvas based textures"),void(this.dirty=!1);var e=this.fillContext,i=this.fillCanvas,n=this.potWidth,s=this.potHeight;this.renderer.gl||(n=t.cutWidth,s=t.cutHeight),e.clearRect(0,0,n,s),i.width=n,i.height=s,e.drawImage(t.source.image,t.cutX,t.cutY,t.cutWidth,t.cutHeight,0,0,n,s),this.renderer.gl?this.fillPattern=this.renderer.canvasToTexture(i,this.fillPattern):this.fillPattern=e.createPattern(i,"repeat"),this.updateCanvas(),this.dirty=!1}},updateCanvas:function(){var t=this.canvas;if(t.width===this.width&&t.height===this.height||(t.width=this.width,t.height=this.height,this.frame.setSize(this.width,this.height),this.updateDisplayOrigin(),this.dirty=!0),!this.dirty||this.renderer&&this.renderer.gl)this.dirty=!1;else{var e=this.context;this.scene.sys.game.config.antialias||l.disable(e);var i=this._tileScale.x,n=this._tileScale.y,s=this._tilePosition.x,r=this._tilePosition.y;e.clearRect(0,0,this.width,this.height),e.save(),e.scale(i,n),e.translate(-s,-r),e.fillStyle=this.fillPattern,e.fillRect(s,r,this.width/i,this.height/n),e.restore(),this.dirty=!1}},preDestroy:function(){this.renderer&&this.renderer.gl&&this.renderer.deleteTexture(this.fillPattern),n.remove(this.canvas),n.remove(this.fillCanvas),this.fillPattern=null,this.fillContext=null,this.fillCanvas=null,this.displayTexture=null,this.displayFrame=null,this.texture.destroy(),this.renderer=null},tilePositionX:{get:function(){return this._tilePosition.x},set:function(t){this._tilePosition.x=t,this.dirty=!0}},tilePositionY:{get:function(){return this._tilePosition.y},set:function(t){this._tilePosition.y=t,this.dirty=!0}},tileScaleX:{get:function(){return this._tileScale.x},set:function(t){this._tileScale.x=t,this.dirty=!0}},tileScaleY:{get:function(){return this._tileScale.y},set:function(t){this._tileScale.y=t,this.dirty=!0}}});t.exports=d},function(t,e,i){var n=i(0),s=i(22),r=i(12),o=i(90),a=i(18),h=i(14),l=i(59),u=i(194),c=i(987),d=i(13),f=new n({Extends:h,Mixins:[r.Alpha,r.BlendMode,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Size,r.TextureCrop,r.Tint,r.Transform,r.Visible,c],initialize:function(t,e,i,n){h.call(this,t,"Video"),this.video=null,this.videoTexture=null,this.videoTextureSource=null,this.snapshotTexture=null,this.flipY=!1,this._key=u(),this.touchLocked=!0,this.playWhenUnlocked=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._systemMuted=!1,this._codeMuted=!1,this._systemPaused=!1,this._codePaused=!1,this._callbacks={play:this.playHandler.bind(this),error:this.loadErrorHandler.bind(this),end:this.completeHandler.bind(this),time:this.timeUpdateHandler.bind(this),seeking:this.seekingHandler.bind(this),seeked:this.seekedHandler.bind(this)},this._crop=this.resetCropObject(),this.markers={},this._markerIn=-1,this._markerOut=d.MAX_SAFE_INTEGER,this._lastUpdate=0,this._cacheKey="",this._isSeeking=!1,this.removeVideoElementOnDestroy=!1,this.setPosition(e,i),this.initPipeline(),n&&this.changeSource(n,!1);var s=t.sys.game.events;s.on(a.PAUSE,this.globalPause,this),s.on(a.RESUME,this.globalResume,this);var r=t.sys.sound;r&&r.on(l.GLOBAL_MUTE,this.globalMute,this)},play:function(t,e,i){if(this.touchLocked&&this.playWhenUnlocked||this.isPlaying())return this;var n=this.video;if(!n)return console.warn("Video not loaded"),this;void 0===t&&(t=n.loop);var s=this.scene.sys.sound;s&&s.mute&&this.setMute(!0),isNaN(e)||(this._markerIn=e),!isNaN(i)&&i>e&&(this._markerOut=i),n.loop=t;var r=this._callbacks,o=n.play();return void 0!==o?o.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)):(n.addEventListener("playing",r.play,!0),n.readyState<2&&(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval))),n.addEventListener("ended",r.end,!0),n.addEventListener("timeupdate",r.time,!0),n.addEventListener("seeking",r.seeking,!0),n.addEventListener("seeked",r.seeked,!0),this},changeSource:function(t,e,i,n,s){void 0===e&&(e=!0),this.video&&this.stop();var r=this.scene.sys.cache.video.get(t);return r?(this.video=r,this._cacheKey=t,this._codePaused=r.paused,this._codeMuted=r.muted,this.videoTexture?(this.scene.sys.textures.remove(this._key),this.videoTexture=this.scene.sys.textures.create(this._key,r,r.videoWidth,r.videoHeight),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,r.videoWidth,r.videoHeight),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,r.videoWidth,r.videoHeight)):this.updateTexture(),r.currentTime=0,this._lastUpdate=0,e&&this.play(i,n,s)):this.video=null,this},addMarker:function(t,e,i){return!isNaN(e)&&e>=0&&!isNaN(i)&&(this.markers[t]=[e,i]),this},playMarker:function(t,e){var i=this.markers[t];return i&&this.play(e,i[0],i[1]),this},removeMarker:function(t){return delete this.markers[t],this},snapshot:function(t,e){return void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.snapshotArea(0,0,this.width,this.height,t,e)},snapshotArea:function(t,e,i,n,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=this.height),void 0===s&&(s=i),void 0===r&&(r=n);var o=this.video,a=this.snapshotTexture;return a?(a.setSize(s,r),o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)):(a=this.scene.sys.textures.createCanvas(u(),s,r),this.snapshotTexture=a,o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)),a.update()},saveSnapshotTexture:function(t){return this.snapshotTexture?this.scene.sys.textures.renameTexture(this.snapshotTexture.key,t):this.snapshotTexture=this.scene.sys.textures.createCanvas(t,this.width,this.height),this.snapshotTexture},loadURL:function(t,e,i){void 0===e&&(e="loadeddata"),void 0===i&&(i=!1),this.video&&this.stop(),this.videoTexture&&this.scene.sys.textures.remove(this._key);var n=document.createElement("video");return n.controls=!1,i&&(n.muted=!0,n.defaultMuted=!0,n.setAttribute("autoplay","autoplay")),n.setAttribute("playsinline","playsinline"),n.setAttribute("preload","auto"),n.addEventListener("error",this._callbacks.error,!0),n.src=t,n.load(),this.video=n,this},playPromiseSuccessHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn)},playPromiseErrorHandler:function(t){this.scene.sys.input.once("pointerdown",this.unlockHandler,this),this.touchLocked=!0,this.playWhenUnlocked=!0,this.emit(o.VIDEO_ERROR,this,t)},playHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this.video.removeEventListener("playing",this._callbacks.play,!0)},loadErrorHandler:function(t){this.stop(),this.emit(o.VIDEO_ERROR,this,t)},unlockHandler:function(){this.touchLocked=!1,this.playWhenUnlocked=!1,this.emit(o.VIDEO_UNLOCKED,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn),this.video.play(),this.emit(o.VIDEO_PLAY,this)},completeHandler:function(){this.emit(o.VIDEO_COMPLETE,this)},timeUpdateHandler:function(){this.video&&this.video.currentTime=this._markerOut&&(t.loop?(t.currentTime=this._markerIn,this.updateTexture(),this._lastUpdate=e,this.emit(o.VIDEO_LOOP,this)):(this.emit(o.VIDEO_COMPLETE,this),this.stop())))}},checkVideoProgress:function(){this.video.readyState>=2?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):this.emit(o.VIDEO_TIMEOUT,this))},updateTexture:function(){var t=this.video,e=t.videoWidth,i=t.videoHeight;if(this.videoTexture){var n=this.videoTextureSource;n.source!==t&&(n.source=t,n.width=e,n.height=i),n.update()}else this.videoTexture=this.scene.sys.textures.create(this._key,t,e,i),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,e,i),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,e,i)},getVideoKey:function(){return this._cacheKey},seekTo:function(t){var e=this.video;if(e){var i=e.duration;if(i!==1/0&&!isNaN(i)){var n=i*t;this.setCurrentTime(n)}}return this},getCurrentTime:function(){return this.video?this.video.currentTime:0},setCurrentTime:function(t){var e=this.video;if(e){if("string"==typeof t){var i=t[0],n=parseFloat(t.substr(1));"+"===i?t=e.currentTime+n:"-"===i&&(t=e.currentTime-n)}e.currentTime=t,this._lastUpdate=t}return this},isSeeking:function(){return this._isSeeking},seekingHandler:function(){this._isSeeking=!0,this.emit(o.VIDEO_SEEKING,this)},seekedHandler:function(){this._isSeeking=!1,this.emit(o.VIDEO_SEEKED,this),this.video&&this.updateTexture()},getProgress:function(){var t=this.video;if(t){var e=t.currentTime,i=t.duration;if(i!==1/0&&!isNaN(i))return e/i}return 0},getDuration:function(){return this.video?this.video.duration:0},setMute:function(t){void 0===t&&(t=!0),this._codeMuted=t;var e=this.video;return e&&(e.muted=!!this._systemMuted||t),this},isMuted:function(){return this._codeMuted},globalMute:function(t,e){this._systemMuted=e;var i=this.video;i&&(i.muted=!!this._codeMuted||e)},globalPause:function(){this._systemPaused=!0,this.video&&this.video.pause()},globalResume:function(){this._systemPaused=!1,this.video&&!this._codePaused&&this.video.play()},setPaused:function(t){void 0===t&&(t=!0);var e=this.video;return this._codePaused=t,e&&(t?e.paused||e.pause():t||e.paused&&!this._systemPaused&&e.play()),this},getVolume:function(){return this.video?this.video.volume:1},setVolume:function(t){return void 0===t&&(t=1),this.video&&(this.video.volume=s(t,0,1)),this},getPlaybackRate:function(){return this.video?this.video.playbackRate:1},setPlaybackRate:function(t){return this.video&&(this.video.playbackRate=t),this},getLoop:function(){return!!this.video&&this.video.loop},setLoop:function(t){return void 0===t&&(t=!0),this.video&&(this.video.loop=t),this},isPlaying:function(){return!!this.video&&!(this.video.paused||this.video.ended)},isPaused:function(){return this.video&&this.video.paused||this._codePaused||this._systemPaused},saveTexture:function(t,e){return void 0===e&&(e=!1),this.videoTexture&&this.scene.sys.textures.renameTexture(this._key,t),this._key=t,this.flipY=e,this.videoTextureSource&&this.videoTextureSource.setFlipY(e),this.videoTexture},stop:function(){var t=this.video;if(t){var e=this._callbacks;for(var i in e)t.removeEventListener(i,e[i],!0);t.pause()}return this._retryID&&window.clearTimeout(this._retryID),this.emit(o.VIDEO_STOP,this),this},removeVideoElement:function(){var t=this.video;if(t){for(t.parentNode&&t.parentNode.removeChild(t);t.hasChildNodes();)t.removeChild(t.firstChild);t.removeAttribute("autoplay"),t.removeAttribute("src"),this.video=null}},preDestroy:function(){this.stop(),this.removeVideoElementOnDestroy&&this.removeVideoElement();var t=this.scene.sys.game.events;t.off(a.PAUSE,this.globalPause,this),t.off(a.RESUME,this.globalResume,this);var e=this.scene.sys.sound;e&&e.off(l.GLOBAL_MUTE,this.globalMute,this),this._retryID&&window.clearTimeout(this._retryID)}});t.exports=f},function(t,e,i){var n=i(0),s=i(199),r=i(411),o=i(46),a=new n({initialize:function(t){this.type=o.POLYGON,this.area=0,this.points=[],t&&this.setTo(t)},contains:function(t,e){return s(this,t,e)},setTo:function(t){if(this.area=0,this.points=[],"string"==typeof t&&(t=t.split(" ")),!Array.isArray(t))return this;for(var e,i=Number.MAX_VALUE,n=0;no||r>a)return!1;if(s<=i||r<=n)return!0;var h=s-i,l=r-n;return h*h+l*l<=t.radius*t.radius}},function(t,e,i){var n=i(4),s=i(205);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a=t.x1,h=t.y1,l=t.x2,u=t.y2,c=e.x,d=e.y,f=e.radius,p=l-a,g=u-h,v=a-c,m=h-d,y=p*p+g*g,x=2*(p*v+g*m),T=x*x-4*y*(v*v+m*m-f*f);if(0===T){var w=-x/(2*y);r=a+w*p,o=h+w*g,w>=0&&w<=1&&i.push(new n(r,o))}else if(T>0){var E=(-x-Math.sqrt(T))/(2*y);r=a+E*p,o=h+E*g,E>=0&&E<=1&&i.push(new n(r,o));var _=(-x+Math.sqrt(T))/(2*y);r=a+_*p,o=h+_*g,_>=0&&_<=1&&i.push(new n(r,o))}}return i}},function(t,e,i){var n=i(55),s=new(i(4));t.exports=function(t,e,i){if(void 0===i&&(i=s),n(e,t.x1,t.y1))return i.x=t.x1,i.y=t.y1,!0;if(n(e,t.x2,t.y2))return i.x=t.x2,i.y=t.y2,!0;var r=t.x2-t.x1,o=t.y2-t.y1,a=e.x-t.x1,h=e.y-t.y1,l=r*r+o*o,u=r,c=o;if(l>0){var d=(a*r+h*o)/l;u*=d,c*=d}return i.x=t.x1+u,i.y=t.y1+c,u*u+c*c<=l&&u*r+c*o>=0&&n(e,i.x,i.y)}},function(t,e,i){var n=i(4),s=i(84),r=i(424);t.exports=function(t,e,i){if(void 0===i&&(i=[]),r(t,e))for(var o=e.getLineA(),a=e.getLineB(),h=e.getLineC(),l=e.getLineD(),u=[new n,new n,new n,new n],c=[s(o,t,u[0]),s(a,t,u[1]),s(h,t,u[2]),s(l,t,u[3])],d=0;d<4;d++)c[d]&&i.push(u[d]);return i}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=!1),void 0===n&&(n=[]);for(var s,r,o,a,h,l,u=t.x3-t.x1,c=t.y3-t.y1,d=t.x2-t.x1,f=t.y2-t.y1,p=u*u+c*c,g=u*d+c*f,v=d*d+f*f,m=p*v-g*g,y=0===m?0:1/m,x=t.x1,T=t.y1,w=0;w=0&&r>=0&&s+r<1&&(n.push({x:e[w].x,y:e[w].y}),i)));w++);return n}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,t}},function(t,e){t.exports=function(t){return 0===t.height?NaN:t.width/t.height}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,o=t.x3-e,a=t.y3-i,t.x3=o*s-a*r+e,t.y3=o*r+a*s+i,t}},function(t,e,i){t.exports={BUTTON_DOWN:i(1189),BUTTON_UP:i(1190),CONNECTED:i(1191),DISCONNECTED:i(1192),GAMEPAD_BUTTON_DOWN:i(1193),GAMEPAD_BUTTON_UP:i(1194)}},function(t,e,i){var n=i(17),s=i(135);t.exports=function(t,e){var i=void 0===t?s():n({},t);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=i(358),u=new n({Extends:r,initialize:function(t,e,i,n){var s="xml";if(h(e)){var o=e;e=a(o,"key"),i=a(o,"url"),n=a(o,"xhrSettings"),s=a(o,"extension",s)}var l={type:"xml",cache:t.cacheManager.xml,extension:s,responseType:"text",key:e,url:i,xhrSettings:n};r.call(this,t,l)},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=l(this.xhrLoader.responseText),this.data?this.onProcessComplete():(console.warn("Invalid XMLFile: "+this.key),this.onProcessError())}});o.register("xml",function(t,e,i){if(Array.isArray(t))for(var n=0;n0&&(s.totalDuration+=s.t2*s.repeat),s.totalDuration>t&&(t=s.totalDuration),s.delay0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay,this.startDelay=e},init:function(){if(this.paused&&!this.parentIsTimeline)return this.state=h.PENDING_ADD,this._pausedState=h.INIT,!1;for(var t=this.data,e=this.totalTargets,i=0;i0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweenData(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=h.LOOP_DELAY):(this.state=h.ACTIVE,this.dispatchTweenEvent(r.TWEEN_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=h.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=h.PENDING_REMOVE,this.dispatchTweenEvent(r.TWEEN_COMPLETE,this.callbacks.onComplete))},pause:function(){return this.state===h.PAUSED?this:(this.paused=!0,this._pausedState=this.state,this.state=h.PAUSED,this)},play:function(t){void 0===t&&(t=!1);var e=this.state;return e!==h.INIT||this.parentIsTimeline?e===h.ACTIVE||e===h.PENDING_ADD&&this._pausedState===h.PENDING_ADD?this:this.parentIsTimeline||e!==h.PENDING_REMOVE&&e!==h.REMOVED?(this.parentIsTimeline?(this.resetTweenData(t),0===this.calculatedOffset?this.state=h.ACTIVE:(this.countdown=this.calculatedOffset,this.state=h.OFFSET_DELAY)):this.paused?(this.paused=!1,this.makeActive()):(this.resetTweenData(t),this.state=h.ACTIVE,this.makeActive()),this):(this.seek(0),this.parent.makeActive(this),this):(this.resetTweenData(!1),this.state=h.ACTIVE,this)},resetTweenData:function(t){for(var e=this.data,i=this.totalData,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY),r.getActiveValue&&(o[a]=r.getActiveValue(r.target,r.key,r.start))}},resume:function(){return this.state===h.PAUSED?(this.paused=!1,this.state=this._pausedState):this.play(),this},seek:function(t,e){if(void 0===e&&(e=16.6),this.totalDuration>=36e5)return console.warn("Tween.seek duration too long"),this;this.state===h.REMOVED&&this.makeActive(),this.elapsed=0,this.progress=0,this.totalElapsed=0,this.totalProgress=0;for(var i=this.data,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY)}this.calcDuration();var c=!1;this.state===h.PAUSED&&(c=!0,this.state=h.ACTIVE),this.isSeeking=!0;do{this.update(0,e)}while(this.totalProgress0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.start=e.getStartValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},setStateFromStart:function(t,e,i){return e.repeatCounter>0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},updateTweenData:function(t,e,i){var n=e.target;switch(e.state){case h.PLAYING_FORWARD:case h.PLAYING_BACKWARD:if(!n){e.state=h.COMPLETE;break}var s=e.elapsed,o=e.duration,a=0;(s+=i)>o&&(a=s-o,s=o);var l=e.state===h.PLAYING_FORWARD,u=s/o;if(e.elapsed=s,e.progress=u,e.previous=e.current,1===u)l?(e.current=e.end,n[e.key]=e.end,e.hold>0?(e.elapsed=e.hold-a,e.state=h.HOLD_DELAY):e.state=this.setStateFromEnd(t,e,a)):(e.current=e.start,n[e.key]=e.start,e.state=this.setStateFromStart(t,e,a));else{var c=l?e.ease(u):e.ease(1-u);e.current=e.start+(e.end-e.start)*c,n[e.key]=e.current}this.dispatchTweenDataEvent(r.TWEEN_UPDATE,t.callbacks.onUpdate,e);break;case h.DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PENDING_RENDER);break;case h.REPEAT_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PLAYING_FORWARD,this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e));break;case h.HOLD_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.state=this.setStateFromEnd(t,e,Math.abs(e.elapsed)));break;case h.PENDING_RENDER:n?(e.start=e.getStartValue(n,e.key,n[e.key],e.index,t.totalTargets,t),e.end=e.getEndValue(n,e.key,e.start,e.index,t.totalTargets,t),e.current=e.start,n[e.key]=e.start,e.state=h.PLAYING_FORWARD):e.state=h.COMPLETE}return e.state!==h.COMPLETE}});u.TYPES=["onActive","onComplete","onLoop","onRepeat","onStart","onUpdate","onYoyo"],a.register("tween",function(t){return this.scene.sys.tweens.add(t)}),o.register("tween",function(t){return this.scene.sys.tweens.create(t)}),t.exports=u},function(t,e,i){t.exports={TIMELINE_COMPLETE:i(1346),TIMELINE_LOOP:i(1347),TIMELINE_PAUSE:i(1348),TIMELINE_RESUME:i(1349),TIMELINE_START:i(1350),TIMELINE_UPDATE:i(1351),TWEEN_ACTIVE:i(1352),TWEEN_COMPLETE:i(1353),TWEEN_LOOP:i(1354),TWEEN_REPEAT:i(1355),TWEEN_START:i(1356),TWEEN_UPDATE:i(1357),TWEEN_YOYO:i(1358)}},function(t,e){t.exports=function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p){return{target:t,index:e,key:i,getActiveValue:r,getEndValue:n,getStartValue:s,ease:o,duration:0,totalDuration:0,delay:0,yoyo:l,hold:0,repeat:0,repeatDelay:0,flipX:f,flipY:p,progress:0,elapsed:0,repeatCounter:0,start:0,previous:0,current:0,end:0,t1:0,t2:0,gen:{delay:a,duration:h,hold:u,repeat:c,repeatDelay:d},state:0}}},function(t,e){t.exports={DEFAULT:0,LINEAR:0,NEAREST:1}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-Math.PI,Math.PI)}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-180,180)}},function(t,e,i){var n=i(0),s=i(10),r=new n({initialize:function(t){this.name="WebGLPipeline",this.game=t.game,this.view=t.game.canvas,this.resolution=1,this.width=0,this.height=0,this.gl=t.gl,this.vertexCount=0,this.vertexCapacity=t.vertexCapacity,this.renderer=t.renderer,this.vertexData=t.vertices?t.vertices:new ArrayBuffer(t.vertexCapacity*t.vertexSize),this.vertexBuffer=this.renderer.createVertexBuffer(t.vertices?t.vertices:this.vertexData.byteLength,this.gl.STREAM_DRAW),this.program=this.renderer.createProgram(t.vertShader,t.fragShader),this.attributes=t.attributes,this.vertexSize=t.vertexSize,this.topology=t.topology,this.bytes=new Uint8Array(this.vertexData),this.vertexComponentCount=s.getComponentCount(t.attributes,this.gl),this.flushLocked=!1,this.active=!1},boot:function(){},addAttribute:function(t,e,i,n,r){return this.attributes.push({name:t,size:e,type:this.renderer.glFormats[i],normalized:n,offset:r}),this.vertexComponentCount=s.getComponentCount(this.attributes,this.gl),this},shouldFlush:function(){return this.vertexCount>=this.vertexCapacity},resize:function(t,e,i){return this.width=t*i,this.height=e*i,this.resolution=i,this},bind:function(){var t=this.gl,e=this.vertexBuffer,i=this.attributes,n=this.program,s=this.renderer,r=this.vertexSize;s.setProgram(n),s.setVertexBuffer(e);for(var o=0;o=0?(t.enableVertexAttribArray(h),t.vertexAttribPointer(h,a.size,a.type,a.normalized,r,a.offset)):-1!==h&&t.disableVertexAttribArray(h)}return this},onBind:function(){return this},onPreRender:function(){return this},onRender:function(){return this},onPostRender:function(){return this},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t=this.gl,e=this.vertexCount,i=this.topology,n=this.vertexSize;if(0!==e)return t.bufferSubData(t.ARRAY_BUFFER,0,this.bytes.subarray(0,e*n)),t.drawArrays(i,0,e),this.vertexCount=0,this.flushLocked=!1,this;this.flushLocked=!1},destroy:function(){var t=this.gl;return t.deleteProgram(this.program),t.deleteBuffer(this.vertexBuffer),delete this.program,delete this.vertexBuffer,delete this.gl,this},setFloat1:function(t,e){return this.renderer.setFloat1(this.program,t,e),this},setFloat2:function(t,e,i){return this.renderer.setFloat2(this.program,t,e,i),this},setFloat3:function(t,e,i,n){return this.renderer.setFloat3(this.program,t,e,i,n),this},setFloat4:function(t,e,i,n,s){return this.renderer.setFloat4(this.program,t,e,i,n,s),this},setFloat1v:function(t,e){return this.renderer.setFloat1v(this.program,t,e),this},setFloat2v:function(t,e){return this.renderer.setFloat2v(this.program,t,e),this},setFloat3v:function(t,e){return this.renderer.setFloat3v(this.program,t,e),this},setFloat4v:function(t,e){return this.renderer.setFloat4v(this.program,t,e),this},setInt1:function(t,e){return this.renderer.setInt1(this.program,t,e),this},setInt2:function(t,e,i){return this.renderer.setInt2(this.program,t,e,i),this},setInt3:function(t,e,i,n){return this.renderer.setInt3(this.program,t,e,i,n),this},setInt4:function(t,e,i,n,s){return this.renderer.setInt4(this.program,t,e,i,n,s),this},setMatrix2:function(t,e,i){return this.renderer.setMatrix2(this.program,t,e,i),this},setMatrix3:function(t,e,i){return this.renderer.setMatrix3(this.program,t,e,i),this},setMatrix4:function(t,e,i){return this.renderer.setMatrix4(this.program,t,e,i),this}});t.exports=r},function(t,e,i){var n=i(0),s=i(66),r=i(2),o=i(506),a=i(779),h=i(780),l=i(32),u=i(10),c=i(234),d=new n({Extends:c,Mixins:[o],initialize:function(t){var e=t.renderer.config;c.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:r(t,"topology",t.renderer.gl.TRIANGLES),vertShader:r(t,"vertShader",h),fragShader:r(t,"fragShader",a),vertexCapacity:r(t,"vertexCapacity",6*e.batchSize),vertexSize:r(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.tempTriangle=[{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0}],this.tintEffect=2,this.strokeTint={TL:0,TR:0,BL:0,BR:0},this.fillTint={TL:0,TR:0,BL:0,BR:0},this.currentFrame={u0:0,v0:0,u1:1,v1:1},this.firstQuad=[0,0,0,0,0],this.prevQuad=[0,0,0,0,0],this.polygonCache=[],this.mvpInit()},onBind:function(){return c.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return c.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this},batchSprite:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix1,s=this._tempMatrix2,r=this._tempMatrix3,o=t.frame,a=o.glTexture,h=o.u0,l=o.v0,c=o.u1,d=o.v1,f=o.x,p=o.y,g=o.cutWidth,v=o.cutHeight,m=o.customPivot,y=t.displayOriginX,x=t.displayOriginY,T=-y+f,w=-x+p;if(t.isCropped){var E=t._crop;E.flipX===t.flipX&&E.flipY===t.flipY||o.updateCropUVs(E,t.flipX,t.flipY),h=E.u0,l=E.v0,c=E.u1,d=E.v1,g=E.width,v=E.height,T=-y+(f=E.x),w=-x+(p=E.y)}var _=1,b=1;t.flipX&&(m||(T+=-o.realWidth+2*y),_=-1),(t.flipY||o.source.isGLTexture&&!a.flipY)&&(m||(w+=-o.realHeight+2*x),b=-1),s.applyITRS(t.x,t.y,t.rotation,t.scaleX*_,t.scaleY*b),n.copyFrom(e.matrix),i?(n.multiplyWithOffset(i,-e.scrollX*t.scrollFactorX,-e.scrollY*t.scrollFactorY),s.e=t.x,s.f=t.y,n.multiply(s,r)):(s.e-=e.scrollX*t.scrollFactorX,s.f-=e.scrollY*t.scrollFactorY,n.multiply(s,r));var A=T+g,S=w+v,C=r.getX(T,w),M=r.getY(T,w),O=r.getX(T,S),P=r.getY(T,S),R=r.getX(A,S),L=r.getY(A,S),D=r.getX(A,w),F=r.getY(A,w),k=u.getTintAppendFloatAlpha(t._tintTL,e.alpha*t._alphaTL),I=u.getTintAppendFloatAlpha(t._tintTR,e.alpha*t._alphaTR),B=u.getTintAppendFloatAlpha(t._tintBL,e.alpha*t._alphaBL),Y=u.getTintAppendFloatAlpha(t._tintBR,e.alpha*t._alphaBR);e.roundPixels&&(C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P),R=Math.round(R),L=Math.round(L),D=Math.round(D),F=Math.round(F)),this.setTexture2D(a,0);var N=t._isTinted&&t.tintFill;this.batchQuad(C,M,O,P,R,L,D,F,h,l,c,d,k,I,B,Y,N,a,0)},batchQuad:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y){var x=!1;this.vertexCount+6>this.vertexCapacity&&(this.flush(),x=!0,this.setTexture2D(m,y));var T=this.vertexViewF32,w=this.vertexViewU32,E=this.vertexCount*this.vertexComponentCount-1;return T[++E]=t,T[++E]=e,T[++E]=h,T[++E]=l,T[++E]=v,w[++E]=d,T[++E]=i,T[++E]=n,T[++E]=h,T[++E]=c,T[++E]=v,w[++E]=p,T[++E]=s,T[++E]=r,T[++E]=u,T[++E]=c,T[++E]=v,w[++E]=g,T[++E]=t,T[++E]=e,T[++E]=h,T[++E]=l,T[++E]=v,w[++E]=d,T[++E]=s,T[++E]=r,T[++E]=u,T[++E]=c,T[++E]=v,w[++E]=g,T[++E]=o,T[++E]=a,T[++E]=u,T[++E]=l,T[++E]=v,w[++E]=f,this.vertexCount+=6,x},batchTri:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g){var v=!1;this.vertexCount+3>this.vertexCapacity&&(this.flush(),this.setTexture2D(p,g),v=!0);var m=this.vertexViewF32,y=this.vertexViewU32,x=this.vertexCount*this.vertexComponentCount-1;return m[++x]=t,m[++x]=e,m[++x]=o,m[++x]=a,m[++x]=f,y[++x]=u,m[++x]=i,m[++x]=n,m[++x]=o,m[++x]=l,m[++x]=f,y[++x]=c,m[++x]=s,m[++x]=r,m[++x]=h,m[++x]=l,m[++x]=f,y[++x]=d,this.vertexCount+=3,v},batchTexture:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y,x,T,w,E,_,b,A,S,C,M,O,P){this.renderer.setPipeline(this,t);var R=this._tempMatrix1,L=this._tempMatrix2,D=this._tempMatrix3,F=m/i+S,k=y/n+C,I=(m+x)/i+S,B=(y+T)/n+C,Y=o,N=a,X=-g,U=-v;if(t.isCropped){var z=t._crop;Y=z.width,N=z.height,o=z.width,a=z.height;var G=m=z.x,W=y=z.y;c&&(G=x-z.x-z.width),d&&!e.isRenderTexture&&(W=T-z.y-z.height),F=G/i+S,k=W/n+C,I=(G+z.width)/i+S,B=(W+z.height)/n+C,X=-g+m,U=-v+y}d^=!P&&e.isRenderTexture?1:0,c&&(Y*=-1,X+=o),d&&(N*=-1,U+=a);var H=X+Y,V=U+N;L.applyITRS(s,r,u,h,l),R.copyFrom(M.matrix),O?(R.multiplyWithOffset(O,-M.scrollX*f,-M.scrollY*p),L.e=s,L.f=r,R.multiply(L,D)):(L.e-=M.scrollX*f,L.f-=M.scrollY*p,R.multiply(L,D));var j=D.getX(X,U),K=D.getY(X,U),q=D.getX(X,V),J=D.getY(X,V),Z=D.getX(H,V),Q=D.getY(H,V),$=D.getX(H,U),tt=D.getY(H,U);M.roundPixels&&(j=Math.round(j),K=Math.round(K),q=Math.round(q),J=Math.round(J),Z=Math.round(Z),Q=Math.round(Q),$=Math.round($),tt=Math.round(tt)),this.setTexture2D(e,0),this.batchQuad(j,K,q,J,Z,Q,$,tt,F,k,I,B,w,E,_,b,A,e,0)},batchTextureFrame:function(t,e,i,n,s,r,o){this.renderer.setPipeline(this);var a=this._tempMatrix1.copyFrom(r),h=this._tempMatrix2,l=e+t.width,c=i+t.height;o?a.multiply(o,h):h=a;var d=h.getX(e,i),f=h.getY(e,i),p=h.getX(e,c),g=h.getY(e,c),v=h.getX(l,c),m=h.getY(l,c),y=h.getX(l,i),x=h.getY(l,i);this.setTexture2D(t.glTexture,0),n=u.getTintAppendFloatAlpha(n,s),this.batchQuad(d,f,p,g,v,m,y,x,t.u0,t.v0,t.u1,t.v1,n,n,n,n,0,t.glTexture,0)},drawFillRect:function(t,e,i,n,s,r){var o=t+i,a=e+n;this.setTexture2D();var h=u.getTintAppendFloatAlphaAndSwap(s,r);this.batchQuad(t,e,t,a,o,a,o,e,0,0,1,1,h,h,h,h,2)},batchFillRect:function(t,e,i,n,s,r){this.renderer.setPipeline(this);var o=this._tempMatrix3;r&&r.multiply(s,o);var a=t+i,h=e+n,l=o.getX(t,e),u=o.getY(t,e),c=o.getX(t,h),d=o.getY(t,h),f=o.getX(a,h),p=o.getY(a,h),g=o.getX(a,e),v=o.getY(a,e),m=this.currentFrame,y=m.u0,x=m.v0,T=m.u1,w=m.v1;this.batchQuad(l,u,c,d,f,p,g,v,y,x,T,w,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.fillTint.BR,this.tintEffect)},batchFillTriangle:function(t,e,i,n,s,r,o,a){this.renderer.setPipeline(this);var h=this._tempMatrix3;a&&a.multiply(o,h);var l=h.getX(t,e),u=h.getY(t,e),c=h.getX(i,n),d=h.getY(i,n),f=h.getX(s,r),p=h.getY(s,r),g=this.currentFrame,v=g.u0,m=g.v0,y=g.u1,x=g.v1;this.batchTri(l,u,c,d,f,p,v,m,y,x,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.tintEffect)},batchStrokeTriangle:function(t,e,i,n,s,r,o,a,h){var l=this.tempTriangle;l[0].x=t,l[0].y=e,l[0].width=o,l[1].x=i,l[1].y=n,l[1].width=o,l[2].x=s,l[2].y=r,l[2].width=o,l[3].x=t,l[3].y=e,l[3].width=o,this.batchStrokePath(l,o,!1,a,h)},batchFillPath:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix3;i&&i.multiply(e,n);for(var r,o,a=t.length,h=this.polygonCache,l=this.fillTint.TL,u=this.fillTint.TR,c=this.fillTint.BL,d=this.tintEffect,f=0;f0&&V[4]?this.batchQuad(D,F,O,P,V[0],V[1],V[2],V[3],z,G,W,H,B,Y,N,X,I):(j[0]=D,j[1]=F,j[2]=O,j[3]=P,j[4]=1),h&&j[4]?this.batchQuad(C,M,R,L,j[0],j[1],j[2],j[3],z,G,W,H,B,Y,N,X,I):(V[0]=C,V[1]=M,V[2]=R,V[3]=L,V[4]=1)}}});t.exports=d},,,function(t,e,i){t.exports={AlignTo:i(521),Angle:i(522),Call:i(523),GetFirst:i(524),GetLast:i(525),GridAlign:i(526),IncAlpha:i(587),IncX:i(588),IncXY:i(589),IncY:i(590),PlaceOnCircle:i(591),PlaceOnEllipse:i(592),PlaceOnLine:i(593),PlaceOnRectangle:i(594),PlaceOnTriangle:i(595),PlayAnimation:i(596),PropertyValueInc:i(34),PropertyValueSet:i(25),RandomCircle:i(597),RandomEllipse:i(598),RandomLine:i(599),RandomRectangle:i(600),RandomTriangle:i(601),Rotate:i(602),RotateAround:i(603),RotateAroundDistance:i(604),ScaleX:i(605),ScaleXY:i(606),ScaleY:i(607),SetAlpha:i(608),SetBlendMode:i(609),SetDepth:i(610),SetHitArea:i(611),SetOrigin:i(612),SetRotation:i(613),SetScale:i(614),SetScaleX:i(615),SetScaleY:i(616),SetScrollFactor:i(617),SetScrollFactorX:i(618),SetScrollFactorY:i(619),SetTint:i(620),SetVisible:i(621),SetX:i(622),SetXY:i(623),SetY:i(624),ShiftPosition:i(625),Shuffle:i(626),SmootherStep:i(627),SmoothStep:i(628),Spread:i(629),ToggleVisible:i(630),WrapInRectangle:i(631)}},function(t,e,i){var n=i(106),s=[];s[n.BOTTOM_CENTER]=i(240),s[n.BOTTOM_LEFT]=i(241),s[n.BOTTOM_RIGHT]=i(242),s[n.LEFT_BOTTOM]=i(243),s[n.LEFT_CENTER]=i(244),s[n.LEFT_TOP]=i(245),s[n.RIGHT_BOTTOM]=i(246),s[n.RIGHT_CENTER]=i(247),s[n.RIGHT_TOP]=i(248),s[n.TOP_CENTER]=i(249),s[n.TOP_LEFT]=i(250),s[n.TOP_RIGHT]=i(251);t.exports=function(t,e,i,n,r){return s[i](t,e,n,r)}},function(t,e,i){var n=i(38),s=i(75),r=i(76),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)+i),o(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(40),r=i(41),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)-i),o(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(42),r=i(43),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)+i),o(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(40),r=i(44),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(77),s=i(40),r=i(78),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(40),s=i(45),r=i(43),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)-i),o(t,s(e)-a),t}},function(t,e,i){var n=i(38),s=i(42),r=i(44),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(77),s=i(42),r=i(78),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(42),s=i(45),r=i(41),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(75),s=i(45),r=i(44),o=i(76);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)+i),r(t,s(e)-a),t}},function(t,e,i){var n=i(40),s=i(45),r=i(44),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)-i),r(t,s(e)-a),t}},function(t,e,i){var n=i(42),s=i(45),r=i(44),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)+i),r(t,s(e)-a),t}},function(t,e,i){var n=i(106),s=[];s[n.BOTTOM_CENTER]=i(253),s[n.BOTTOM_LEFT]=i(254),s[n.BOTTOM_RIGHT]=i(255),s[n.CENTER]=i(256),s[n.LEFT_CENTER]=i(258),s[n.RIGHT_CENTER]=i(259),s[n.TOP_CENTER]=i(260),s[n.TOP_LEFT]=i(261),s[n.TOP_RIGHT]=i(262),s[n.LEFT_BOTTOM]=s[n.BOTTOM_LEFT],s[n.LEFT_TOP]=s[n.TOP_LEFT],s[n.RIGHT_BOTTOM]=s[n.BOTTOM_RIGHT],s[n.RIGHT_TOP]=s[n.TOP_RIGHT];t.exports=function(t,e,i,n,r){return s[i](t,e,n,r)}},function(t,e,i){var n=i(38),s=i(75),r=i(44),o=i(76);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(40),r=i(44),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(38),s=i(42),r=i(44),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(257),s=i(75),r=i(77);t.exports=function(t,e,i,o){return void 0===i&&(i=0),void 0===o&&(o=0),n(t,s(e)+i,r(e)+o),t}},function(t,e,i){var n=i(76),s=i(78);t.exports=function(t,e,i){return n(t,e),s(t,i)}},function(t,e,i){var n=i(77),s=i(40),r=i(78),o=i(41);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(77),s=i(42),r=i(78),o=i(43);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(75),s=i(45),r=i(76),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(40),s=i(45),r=i(41),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)-i),o(t,s(e)-a),t}},function(t,e,i){var n=i(42),s=i(45),r=i(43),o=i(39);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(146),s=i(87),r=i(13),o=i(4);t.exports=function(t,e,i){void 0===i&&(i=new o);var a=s(e,0,r.PI2);return n(t,a,i)}},function(t,e,i){var n=i(265),s=i(146),r=i(87),o=i(13);t.exports=function(t,e,i,a){void 0===a&&(a=[]),e||(e=n(t)/i);for(var h=0;he.length&&(r=e.length),i?(n=e[r-1][i],(s=e[r][i])-t<=t-n?e[r]:e[r-1]):(n=e[r-1],(s=e[r])-t<=t-n?s:n)}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.textureKey=t,this.textureFrame=e,this.index=i,this.frame=n,this.isFirst=!1,this.isLast=!1,this.prevFrame=null,this.nextFrame=null,this.duration=0,this.progress=0},toJSON:function(){return{key:this.textureKey,frame:this.textureFrame,duration:this.duration}},destroy:function(){this.frame=void 0}});t.exports=n},function(t,e,i){var n=i(52),s={_blendMode:n.NORMAL,blendMode:{get:function(){return this._blendMode},set:function(t){"string"==typeof t&&(t=n[t]),(t|=0)>=-1&&(this._blendMode=t)}},setBlendMode:function(t){return this.blendMode=t,this}};t.exports=s},function(t,e){var i={_depth:0,depth:{get:function(){return this._depth},set:function(t){this.scene.sys.queueDepthSort(),this._depth=t}},setDepth:function(t){return void 0===t&&(t=0),this.depth=t,this}};t.exports=i},function(t,e,i){var n=i(149),s=i(112);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=s(t)/i);for(var o=0;o=t.right&&(h=1,a+=o-t.right,o=t.right);break;case 1:(a+=e)>=t.bottom&&(h=2,o-=a-t.bottom,a=t.bottom);break;case 2:(o-=e)<=t.left&&(h=3,a-=t.left-o,o=t.left);break;case 3:(a-=e)<=t.top&&(h=0,a=t.top)}return r}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);for(var i=null,n=0;n-h&&(c-=h,n+=l),fd.right&&(f=u(f,f+(g-d.right),this.lerp.x)),vd.bottom&&(p=u(p,p+(v-d.bottom),this.lerp.y))):(f=u(f,g-h,this.lerp.x),p=u(p,v-l,this.lerp.y))}this.useBounds&&(f=this.clampX(f),p=this.clampY(p)),this.roundPixels&&(h=Math.round(h),l=Math.round(l)),this.scrollX=f,this.scrollY=p;var m=f+n,y=p+s;this.midPoint.set(m,y);var x=e/o,T=i/o;this.worldView.setTo(m-x/2,y-T/2,x,T),a.applyITRS(this.x+h,this.y+l,this.rotation,o,o),a.translate(-h,-l),this.shakeEffect.preRender()},setLerp:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=t),this.lerp.set(t,e),this},setFollowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.followOffset.set(t,e),this},startFollow:function(t,e,i,n,s,r){void 0===e&&(e=!1),void 0===i&&(i=1),void 0===n&&(n=i),void 0===s&&(s=0),void 0===r&&(r=s),this._follow=t,this.roundPixels=e,i=o(i,0,1),n=o(n,0,1),this.lerp.set(i,n),this.followOffset.set(s,r);var a=this.width/2,h=this.height/2,l=t.x-s,u=t.y-r;return this.midPoint.set(l,u),this.scrollX=l-a,this.scrollY=u-h,this.useBounds&&(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},stopFollow:function(){return this._follow=null,this},resetFX:function(){return this.panEffect.reset(),this.shakeEffect.reset(),this.flashEffect.reset(),this.fadeEffect.reset(),this},update:function(t,e){this.visible&&(this.panEffect.update(t,e),this.zoomEffect.update(t,e),this.shakeEffect.update(t,e),this.flashEffect.update(t,e),this.fadeEffect.update(t,e))},destroy:function(){this.clearRenderToTexture(),this.resetFX(),n.prototype.destroy.call(this),this._follow=null,this.deadzone=null}});t.exports=f},function(t,e,i){var n=i(33);t.exports=function(t){var e=new n;t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,n){return e+e+i+i+n+n});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e.setTo(s,r,o)}return e}},function(t,e){t.exports=function(t,e,i,n){return n<<24|t<<16|e<<8|i}},function(t,e){t.exports=function(t,e,i,n){void 0===n&&(n={h:0,s:0,v:0}),t/=255,e/=255,i/=255;var s=Math.min(t,e,i),r=Math.max(t,e,i),o=r-s,a=0,h=0===r?0:o/r,l=r;return r!==s&&(r===t?a=(e-i)/o+(e16777215?{a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{a:255,r:t>>16&255,g:t>>8&255,b:255&t}}},function(t,e,i){var n=i(33);t.exports=function(t){return new n(t.r,t.g,t.b,t.a)}},function(t,e,i){var n=i(33);t.exports=function(t){var e=new n,i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t.toLowerCase());if(i){var s=parseInt(i[1],10),r=parseInt(i[2],10),o=parseInt(i[3],10),a=void 0!==i[4]?parseFloat(i[4]):1;e.setTo(s,r,o,255*a)}return e}},function(t,e,i){t.exports={Fade:i(656),Flash:i(657),Pan:i(658),Shake:i(691),Zoom:i(692)}},function(t,e,i){t.exports={In:i(659),Out:i(660),InOut:i(661)}},function(t,e,i){t.exports={In:i(662),Out:i(663),InOut:i(664)}},function(t,e,i){t.exports={In:i(665),Out:i(666),InOut:i(667)}},function(t,e,i){t.exports={In:i(668),Out:i(669),InOut:i(670)}},function(t,e,i){t.exports={In:i(671),Out:i(672),InOut:i(673)}},function(t,e,i){t.exports={In:i(674),Out:i(675),InOut:i(676)}},function(t,e,i){t.exports=i(677)},function(t,e,i){t.exports={In:i(678),Out:i(679),InOut:i(680)}},function(t,e,i){t.exports={In:i(681),Out:i(682),InOut:i(683)}},function(t,e,i){t.exports={In:i(684),Out:i(685),InOut:i(686)}},function(t,e,i){t.exports={In:i(687),Out:i(688),InOut:i(689)}},function(t,e,i){t.exports=i(690)},function(t,e,i){var n=i(0),s=i(29),r=i(312),o=i(2),a=i(6),h=i(7),l=i(168),u=i(1),c=i(173),d=i(161),f=new n({initialize:function(t){void 0===t&&(t={});this.width=a(t,"width",1024),this.height=a(t,"height",768),this.zoom=a(t,"zoom",1),this.resolution=a(t,"resolution",1),this.parent=a(t,"parent",void 0),this.scaleMode=a(t,"scaleMode",0),this.expandParent=a(t,"expandParent",!0),this.autoRound=a(t,"autoRound",!1),this.autoCenter=a(t,"autoCenter",0),this.resizeInterval=a(t,"resizeInterval",500),this.fullscreenTarget=a(t,"fullscreenTarget",null),this.minWidth=a(t,"minWidth",0),this.maxWidth=a(t,"maxWidth",0),this.minHeight=a(t,"minHeight",0),this.maxHeight=a(t,"maxHeight",0);var e=a(t,"scale",null);e&&(this.width=a(e,"width",this.width),this.height=a(e,"height",this.height),this.zoom=a(e,"zoom",this.zoom),this.resolution=a(e,"resolution",this.resolution),this.parent=a(e,"parent",this.parent),this.scaleMode=a(e,"mode",this.scaleMode),this.expandParent=a(e,"expandParent",this.expandParent),this.autoRound=a(e,"autoRound",this.autoRound),this.autoCenter=a(e,"autoCenter",this.autoCenter),this.resizeInterval=a(e,"resizeInterval",this.resizeInterval),this.fullscreenTarget=a(e,"fullscreenTarget",this.fullscreenTarget),this.minWidth=a(e,"min.width",this.minWidth),this.maxWidth=a(e,"max.width",this.maxWidth),this.minHeight=a(e,"min.height",this.minHeight),this.maxHeight=a(e,"max.height",this.maxHeight)),this.renderType=a(t,"type",s.AUTO),this.canvas=a(t,"canvas",null),this.context=a(t,"context",null),this.canvasStyle=a(t,"canvasStyle",null),this.customEnvironment=a(t,"customEnvironment",!1),this.sceneConfig=a(t,"scene",null),this.seed=a(t,"seed",[(Date.now()*Math.random()).toString()]),l.RND=new l.RandomDataGenerator(this.seed),this.gameTitle=a(t,"title",""),this.gameURL=a(t,"url","https://phaser.io"),this.gameVersion=a(t,"version",""),this.autoFocus=a(t,"autoFocus",!0),this.domCreateContainer=a(t,"dom.createContainer",!1),this.domBehindCanvas=a(t,"dom.behindCanvas",!1),this.inputKeyboard=a(t,"input.keyboard",!0),this.inputKeyboardEventTarget=a(t,"input.keyboard.target",window),this.inputKeyboardCapture=a(t,"input.keyboard.capture",[]),this.inputMouse=a(t,"input.mouse",!0),this.inputMouseEventTarget=a(t,"input.mouse.target",null),this.inputMouseCapture=a(t,"input.mouse.capture",!0),this.inputTouch=a(t,"input.touch",r.input.touch),this.inputTouchEventTarget=a(t,"input.touch.target",null),this.inputTouchCapture=a(t,"input.touch.capture",!0),this.inputActivePointers=a(t,"input.activePointers",1),this.inputSmoothFactor=a(t,"input.smoothFactor",0),this.inputWindowEvents=a(t,"input.windowEvents",!0),this.inputGamepad=a(t,"input.gamepad",!1),this.inputGamepadEventTarget=a(t,"input.gamepad.target",window),this.disableContextMenu=a(t,"disableContextMenu",!1),this.audio=a(t,"audio"),this.hideBanner=!1===a(t,"banner",null),this.hidePhaser=a(t,"banner.hidePhaser",!1),this.bannerTextColor=a(t,"banner.text","#ffffff"),this.bannerBackgroundColor=a(t,"banner.background",["#ff0000","#ffff00","#00ff00","#00ffff","#000000"]),""===this.gameTitle&&this.hidePhaser&&(this.hideBanner=!0),this.fps=a(t,"fps",null);var i=a(t,"render",t);this.antialias=a(i,"antialias",!0),this.antialiasGL=a(i,"antialiasGL",!0),this.mipmapFilter=a(i,"mipmapFilter","LINEAR"),this.desynchronized=a(i,"desynchronized",!1),this.roundPixels=a(i,"roundPixels",!1),this.pixelArt=a(i,"pixelArt",1!==this.zoom),this.pixelArt&&(this.antialias=!1,this.roundPixels=!0),this.transparent=a(i,"transparent",!1),this.clearBeforeRender=a(i,"clearBeforeRender",!0),this.premultipliedAlpha=a(i,"premultipliedAlpha",!0),this.failIfMajorPerformanceCaveat=a(i,"failIfMajorPerformanceCaveat",!1),this.powerPreference=a(i,"powerPreference","default"),this.batchSize=a(i,"batchSize",2e3),this.maxLights=a(i,"maxLights",10);var n=a(t,"backgroundColor",0);this.backgroundColor=d(n),0===n&&this.transparent&&(this.backgroundColor.alpha=0),this.preBoot=a(t,"callbacks.preBoot",u),this.postBoot=a(t,"callbacks.postBoot",u),this.physics=a(t,"physics",{}),this.defaultPhysicsSystem=a(this.physics,"default",!1),this.loaderBaseURL=a(t,"loader.baseURL",""),this.loaderPath=a(t,"loader.path",""),this.loaderMaxParallelDownloads=a(t,"loader.maxParallelDownloads",32),this.loaderCrossOrigin=a(t,"loader.crossOrigin",void 0),this.loaderResponseType=a(t,"loader.responseType",""),this.loaderAsync=a(t,"loader.async",!0),this.loaderUser=a(t,"loader.user",""),this.loaderPassword=a(t,"loader.password",""),this.loaderTimeout=a(t,"loader.timeout",0),this.installGlobalPlugins=[],this.installScenePlugins=[];var f=a(t,"plugins",null),p=c.DefaultScene;f&&(Array.isArray(f)?this.defaultPlugins=f:h(f)&&(this.installGlobalPlugins=o(f,"global",[]),this.installScenePlugins=o(f,"scene",[]),Array.isArray(f.default)?p=f.default:Array.isArray(f.defaultMerge)&&(p=p.concat(f.defaultMerge)))),this.defaultPlugins=p;var g="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg";this.defaultImage=a(t,"images.default",g+"AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="),this.missingImage=a(t,"images.missing",g+"CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="),window&&(window.FORCE_WEBGL?this.renderType=s.WEBGL:window.FORCE_CANVAS&&(this.renderType=s.CANVAS))}});t.exports=f},function(t,e,i){t.exports={os:i(116),browser:i(117),features:i(167),input:i(721),audio:i(722),video:i(723),fullscreen:i(724),canvasFeatures:i(313)}},function(t,e,i){var n,s,r,o=i(26),a={supportInverseAlpha:!1,supportNewBlendModes:!1};t.exports=(void 0!==document&&(a.supportNewBlendModes=(n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",s="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",(r=new Image).onload=function(){var t=new Image;t.onload=function(){var e=o.create(t,6,1).getContext("2d");if(e.globalCompositeOperation="multiply",e.drawImage(r,0,0),e.drawImage(t,2,0),!e.getImageData(2,0,1,1))return!1;var i=e.getImageData(2,0,1,1).data;o.remove(t),a.supportNewBlendModes=255===i[0]&&0===i[1]&&0===i[2]},t.src=n+"/wCKxvRF"+s},r.src=n+"AP804Oa6"+s,!1),a.supportInverseAlpha=function(){var t=o.create(this,2,1).getContext("2d");t.fillStyle="rgba(10, 20, 30, 0.5)",t.fillRect(0,0,1,1);var e=t.getImageData(0,0,1,1);if(null===e)return!1;t.putImageData(e,1,0);var i=t.getImageData(1,0,1,1);return i.data[0]===e.data[0]&&i.data[1]===e.data[1]&&i.data[2]===e.data[2]&&i.data[3]===e.data[3]}()),a)},function(t,e){t.exports=function(t,e,i,n){return Math.atan2(n-e,i-t)}},function(t,e){t.exports=function(t){return(t%=2*Math.PI)>=0?t:t+2*Math.PI}},function(t,e){t.exports=function(t,e,i,n){var s=t-i,r=e-n;return s*s+r*r}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t>e-i}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t0?Math.ceil(t):Math.floor(t)}},function(t,e,i){var n=i(3);t.exports=function(t,e,i,s,r,o,a,h){void 0===h&&(h=new n);var l=Math.sin(r),u=Math.cos(r),c=u*o,d=l*o,f=-l*a,p=u*a,g=1/(c*p+f*-d);return h.x=p*g*t+-f*g*e+(s*f-i*p)*g,h.y=c*g*e+-d*g*t+(-s*c+i*d)*g,h}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.x=0,this.y=0,this.z=0,this.w=0,"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},clone:function(){return new n(this.x,this.y,this.z,this.w)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z||0,this.w=t.w||0,this},equals:function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z||0,this.w+=t.w||0,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z||0,this.w-=t.w||0,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z||1,this.w*=t.w||1,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z||1,this.w/=t.w||1,this},distance:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return Math.sqrt(e*e+i*i+n*n+s*s)},distanceSq:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return e*e+i*i+n*n+s*s},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.val;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},reset:function(){return this.x=0,this.y=0,this.z=0,this.w=0,this}});n.prototype.sub=n.prototype.subtract,n.prototype.mul=n.prototype.multiply,n.prototype.div=n.prototype.divide,n.prototype.dist=n.prototype.distance,n.prototype.distSq=n.prototype.distanceSq,n.prototype.len=n.prototype.length,n.prototype.lenSq=n.prototype.lengthSq,t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(9),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this},fromMat4:function(t){var e=t.val,i=this.val;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[5];return t[1]=t[3],t[2]=t[6],t[3]=e,t[5]=t[7],t[6]=i,t[7]=n,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=l*r-o*h,c=-l*s+o*a,d=h*s-r*a,f=e*u+i*c+n*d;return f?(f=1/f,t[0]=u*f,t[1]=(-l*i+n*h)*f,t[2]=(o*i-n*r)*f,t[3]=c*f,t[4]=(l*e-n*a)*f,t[5]=(-o*e+n*s)*f,t[6]=d*f,t[7]=(-h*e+i*a)*f,t[8]=(r*e-i*s)*f,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return t[0]=r*l-o*h,t[1]=n*h-i*l,t[2]=i*o-n*r,t[3]=o*a-s*l,t[4]=e*l-n*a,t[5]=n*s-e*o,t[6]=s*h-r*a,t[7]=i*a-e*h,t[8]=e*r-i*s,this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*(l*r-o*h)+i*(-l*s+o*a)+n*(h*s-r*a)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=t.val,d=c[0],f=c[1],p=c[2],g=c[3],v=c[4],m=c[5],y=c[6],x=c[7],T=c[8];return e[0]=d*i+f*r+p*h,e[1]=d*n+f*o+p*l,e[2]=d*s+f*a+p*u,e[3]=g*i+v*r+m*h,e[4]=g*n+v*o+m*l,e[5]=g*s+v*a+m*u,e[6]=y*i+x*r+T*h,e[7]=y*n+x*o+T*l,e[8]=y*s+x*a+T*u,this},translate:function(t){var e=this.val,i=t.x,n=t.y;return e[6]=i*e[0]+n*e[3]+e[6],e[7]=i*e[1]+n*e[4]+e[7],e[8]=i*e[2]+n*e[5]+e[8],this},rotate:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=Math.sin(t),l=Math.cos(t);return e[0]=l*i+h*r,e[1]=l*n+h*o,e[2]=l*s+h*a,e[3]=l*r-h*i,e[4]=l*o-h*n,e[5]=l*a-h*s,this},scale:function(t){var e=this.val,i=t.x,n=t.y;return e[0]=i*e[0],e[1]=i*e[1],e[2]=i*e[2],e[3]=n*e[3],e[4]=n*e[4],e[5]=n*e[5],this},fromQuat:function(t){var e=t.x,i=t.y,n=t.z,s=t.w,r=e+e,o=i+i,a=n+n,h=e*r,l=e*o,u=e*a,c=i*o,d=i*a,f=n*a,p=s*r,g=s*o,v=s*a,m=this.val;return m[0]=1-(c+f),m[3]=l+v,m[6]=u-g,m[1]=l-v,m[4]=1-(h+f),m[7]=d+p,m[2]=u+g,m[5]=d-p,m[8]=1-(h+c),this},normalFromMat4:function(t){var e=t.val,i=this.val,n=e[0],s=e[1],r=e[2],o=e[3],a=e[4],h=e[5],l=e[6],u=e[7],c=e[8],d=e[9],f=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=n*h-s*a,T=n*l-r*a,w=n*u-o*a,E=s*l-r*h,_=s*u-o*h,b=r*u-o*l,A=c*v-d*g,S=c*m-f*g,C=c*y-p*g,M=d*m-f*v,O=d*y-p*v,P=f*y-p*m,R=x*P-T*O+w*M+E*C-_*S+b*A;return R?(R=1/R,i[0]=(h*P-l*O+u*M)*R,i[1]=(l*C-a*P-u*S)*R,i[2]=(a*O-h*C+u*A)*R,i[3]=(r*O-s*P-o*M)*R,i[4]=(n*P-r*C+o*S)*R,i[5]=(s*C-n*O-o*A)*R,i[6]=(v*b-m*_+y*E)*R,i[7]=(m*w-g*b-y*T)*R,i[8]=(g*_-v*w+y*x)*R,this):null}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(16),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},zero:function(){var t=this.val;return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=0,this},xyz:function(t,e,i){this.identity();var n=this.val;return n[12]=t,n[13]=e,n[14]=i,this},scaling:function(t,e,i){this.zero();var n=this.val;return n[0]=t,n[5]=e,n[10]=i,n[15]=1,this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[3],s=t[6],r=t[7],o=t[11];return t[1]=t[4],t[2]=t[8],t[3]=t[12],t[4]=e,t[6]=t[9],t[7]=t[13],t[8]=i,t[9]=s,t[11]=t[14],t[12]=n,t[13]=r,t[14]=o,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15],m=e*o-i*r,y=e*a-n*r,x=e*h-s*r,T=i*a-n*o,w=i*h-s*o,E=n*h-s*a,_=l*p-u*f,b=l*g-c*f,A=l*v-d*f,S=u*g-c*p,C=u*v-d*p,M=c*v-d*g,O=m*M-y*C+x*S+T*A-w*b+E*_;return O?(O=1/O,t[0]=(o*M-a*C+h*S)*O,t[1]=(n*C-i*M-s*S)*O,t[2]=(p*E-g*w+v*T)*O,t[3]=(c*w-u*E-d*T)*O,t[4]=(a*A-r*M-h*b)*O,t[5]=(e*M-n*A+s*b)*O,t[6]=(g*x-f*E-v*y)*O,t[7]=(l*E-c*x+d*y)*O,t[8]=(r*C-o*A+h*_)*O,t[9]=(i*A-e*C-s*_)*O,t[10]=(f*w-p*x+v*m)*O,t[11]=(u*x-l*w-d*m)*O,t[12]=(o*b-r*S-a*_)*O,t[13]=(e*S-i*b+n*_)*O,t[14]=(p*y-f*T-g*m)*O,t[15]=(l*T-u*y+c*m)*O,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return t[0]=o*(c*v-d*g)-u*(a*v-h*g)+p*(a*d-h*c),t[1]=-(i*(c*v-d*g)-u*(n*v-s*g)+p*(n*d-s*c)),t[2]=i*(a*v-h*g)-o*(n*v-s*g)+p*(n*h-s*a),t[3]=-(i*(a*d-h*c)-o*(n*d-s*c)+u*(n*h-s*a)),t[4]=-(r*(c*v-d*g)-l*(a*v-h*g)+f*(a*d-h*c)),t[5]=e*(c*v-d*g)-l*(n*v-s*g)+f*(n*d-s*c),t[6]=-(e*(a*v-h*g)-r*(n*v-s*g)+f*(n*h-s*a)),t[7]=e*(a*d-h*c)-r*(n*d-s*c)+l*(n*h-s*a),t[8]=r*(u*v-d*p)-l*(o*v-h*p)+f*(o*d-h*u),t[9]=-(e*(u*v-d*p)-l*(i*v-s*p)+f*(i*d-s*u)),t[10]=e*(o*v-h*p)-r*(i*v-s*p)+f*(i*h-s*o),t[11]=-(e*(o*d-h*u)-r*(i*d-s*u)+l*(i*h-s*o)),t[12]=-(r*(u*g-c*p)-l*(o*g-a*p)+f*(o*c-a*u)),t[13]=e*(u*g-c*p)-l*(i*g-n*p)+f*(i*c-n*u),t[14]=-(e*(o*g-a*p)-r*(i*g-n*p)+f*(i*a-n*o)),t[15]=e*(o*c-a*u)-r*(i*c-n*u)+l*(i*a-n*o),this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return(e*o-i*r)*(c*v-d*g)-(e*a-n*r)*(u*v-d*p)+(e*h-s*r)*(u*g-c*p)+(i*a-n*o)*(l*v-d*f)-(i*h-s*o)*(l*g-c*f)+(n*h-s*a)*(l*p-u*f)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=e[9],d=e[10],f=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=t.val,x=y[0],T=y[1],w=y[2],E=y[3];return e[0]=x*i+T*o+w*u+E*p,e[1]=x*n+T*a+w*c+E*g,e[2]=x*s+T*h+w*d+E*v,e[3]=x*r+T*l+w*f+E*m,x=y[4],T=y[5],w=y[6],E=y[7],e[4]=x*i+T*o+w*u+E*p,e[5]=x*n+T*a+w*c+E*g,e[6]=x*s+T*h+w*d+E*v,e[7]=x*r+T*l+w*f+E*m,x=y[8],T=y[9],w=y[10],E=y[11],e[8]=x*i+T*o+w*u+E*p,e[9]=x*n+T*a+w*c+E*g,e[10]=x*s+T*h+w*d+E*v,e[11]=x*r+T*l+w*f+E*m,x=y[12],T=y[13],w=y[14],E=y[15],e[12]=x*i+T*o+w*u+E*p,e[13]=x*n+T*a+w*c+E*g,e[14]=x*s+T*h+w*d+E*v,e[15]=x*r+T*l+w*f+E*m,this},multiplyLocal:function(t){var e=[],i=this.val,n=t.val;return e[0]=i[0]*n[0]+i[1]*n[4]+i[2]*n[8]+i[3]*n[12],e[1]=i[0]*n[1]+i[1]*n[5]+i[2]*n[9]+i[3]*n[13],e[2]=i[0]*n[2]+i[1]*n[6]+i[2]*n[10]+i[3]*n[14],e[3]=i[0]*n[3]+i[1]*n[7]+i[2]*n[11]+i[3]*n[15],e[4]=i[4]*n[0]+i[5]*n[4]+i[6]*n[8]+i[7]*n[12],e[5]=i[4]*n[1]+i[5]*n[5]+i[6]*n[9]+i[7]*n[13],e[6]=i[4]*n[2]+i[5]*n[6]+i[6]*n[10]+i[7]*n[14],e[7]=i[4]*n[3]+i[5]*n[7]+i[6]*n[11]+i[7]*n[15],e[8]=i[8]*n[0]+i[9]*n[4]+i[10]*n[8]+i[11]*n[12],e[9]=i[8]*n[1]+i[9]*n[5]+i[10]*n[9]+i[11]*n[13],e[10]=i[8]*n[2]+i[9]*n[6]+i[10]*n[10]+i[11]*n[14],e[11]=i[8]*n[3]+i[9]*n[7]+i[10]*n[11]+i[11]*n[15],e[12]=i[12]*n[0]+i[13]*n[4]+i[14]*n[8]+i[15]*n[12],e[13]=i[12]*n[1]+i[13]*n[5]+i[14]*n[9]+i[15]*n[13],e[14]=i[12]*n[2]+i[13]*n[6]+i[14]*n[10]+i[15]*n[14],e[15]=i[12]*n[3]+i[13]*n[7]+i[14]*n[11]+i[15]*n[15],this.fromArray(e)},translate:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[12]=s[0]*e+s[4]*i+s[8]*n+s[12],s[13]=s[1]*e+s[5]*i+s[9]*n+s[13],s[14]=s[2]*e+s[6]*i+s[10]*n+s[14],s[15]=s[3]*e+s[7]*i+s[11]*n+s[15],this},translateXYZ:function(t,e,i){var n=this.val;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this},scale:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[0]=s[0]*e,s[1]=s[1]*e,s[2]=s[2]*e,s[3]=s[3]*e,s[4]=s[4]*i,s[5]=s[5]*i,s[6]=s[6]*i,s[7]=s[7]*i,s[8]=s[8]*n,s[9]=s[9]*n,s[10]=s[10]*n,s[11]=s[11]*n,this},scaleXYZ:function(t,e,i){var n=this.val;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this},makeRotationAxis:function(t,e){var i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,o=t.y,a=t.z,h=s*r,l=s*o;return this.fromArray([h*r+i,h*o-n*a,h*a+n*o,0,h*o+n*a,l*o+i,l*a-n*r,0,h*a-n*o,l*a+n*r,s*a*a+i,0,0,0,0,1]),this},rotate:function(t,e){var i=this.val,n=e.x,s=e.y,r=e.z,o=Math.sqrt(n*n+s*s+r*r);if(Math.abs(o)<1e-6)return null;n*=o=1/o,s*=o,r*=o;var a=Math.sin(t),h=Math.cos(t),l=1-h,u=i[0],c=i[1],d=i[2],f=i[3],p=i[4],g=i[5],v=i[6],m=i[7],y=i[8],x=i[9],T=i[10],w=i[11],E=n*n*l+h,_=s*n*l+r*a,b=r*n*l-s*a,A=n*s*l-r*a,S=s*s*l+h,C=r*s*l+n*a,M=n*r*l+s*a,O=s*r*l-n*a,P=r*r*l+h;return i[0]=u*E+p*_+y*b,i[1]=c*E+g*_+x*b,i[2]=d*E+v*_+T*b,i[3]=f*E+m*_+w*b,i[4]=u*A+p*S+y*C,i[5]=c*A+g*S+x*C,i[6]=d*A+v*S+T*C,i[7]=f*A+m*S+w*C,i[8]=u*M+p*O+y*P,i[9]=c*M+g*O+x*P,i[10]=d*M+v*O+T*P,i[11]=f*M+m*O+w*P,this},rotateX:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this},rotateY:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this},rotateZ:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this},fromRotationTranslation:function(t,e){var i=this.val,n=t.x,s=t.y,r=t.z,o=t.w,a=n+n,h=s+s,l=r+r,u=n*a,c=n*h,d=n*l,f=s*h,p=s*l,g=r*l,v=o*a,m=o*h,y=o*l;return i[0]=1-(f+g),i[1]=c+y,i[2]=d-m,i[3]=0,i[4]=c-y,i[5]=1-(u+g),i[6]=p+v,i[7]=0,i[8]=d+m,i[9]=p-v,i[10]=1-(u+f),i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this},fromQuat:function(t){var e=this.val,i=t.x,n=t.y,s=t.z,r=t.w,o=i+i,a=n+n,h=s+s,l=i*o,u=i*a,c=i*h,d=n*a,f=n*h,p=s*h,g=r*o,v=r*a,m=r*h;return e[0]=1-(d+p),e[1]=u+m,e[2]=c-v,e[3]=0,e[4]=u-m,e[5]=1-(l+p),e[6]=f+g,e[7]=0,e[8]=c+v,e[9]=f-g,e[10]=1-(l+d),e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},frustum:function(t,e,i,n,s,r){var o=this.val,a=1/(e-t),h=1/(n-i),l=1/(s-r);return o[0]=2*s*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*s*h,o[6]=0,o[7]=0,o[8]=(e+t)*a,o[9]=(n+i)*h,o[10]=(r+s)*l,o[11]=-1,o[12]=0,o[13]=0,o[14]=r*s*2*l,o[15]=0,this},perspective:function(t,e,i,n){var s=this.val,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this},perspectiveLH:function(t,e,i,n){var s=this.val;return s[0]=2*i/t,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/e,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-n/(i-n),s[11]=1,s[12]=0,s[13]=0,s[14]=i*n/(i-n),s[15]=0,this},ortho:function(t,e,i,n,s,r){var o=this.val,a=t-e,h=i-n,l=s-r;return a=0===a?a:1/a,h=0===h?h:1/h,l=0===l?l:1/l,o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this},lookAt:function(t,e,i){var n=this.val,s=t.x,r=t.y,o=t.z,a=i.x,h=i.y,l=i.z,u=e.x,c=e.y,d=e.z;if(Math.abs(s-u)<1e-6&&Math.abs(r-c)<1e-6&&Math.abs(o-d)<1e-6)return this.identity();var f=s-u,p=r-c,g=o-d,v=1/Math.sqrt(f*f+p*p+g*g),m=h*(g*=v)-l*(p*=v),y=l*(f*=v)-a*g,x=a*p-h*f;(v=Math.sqrt(m*m+y*y+x*x))?(m*=v=1/v,y*=v,x*=v):(m=0,y=0,x=0);var T=p*x-g*y,w=g*m-f*x,E=f*y-p*m;return(v=Math.sqrt(T*T+w*w+E*E))?(T*=v=1/v,w*=v,E*=v):(T=0,w=0,E=0),n[0]=m,n[1]=T,n[2]=f,n[3]=0,n[4]=y,n[5]=w,n[6]=p,n[7]=0,n[8]=x,n[9]=E,n[10]=g,n[11]=0,n[12]=-(m*s+y*r+x*o),n[13]=-(T*s+w*r+E*o),n[14]=-(f*s+p*r+g*o),n[15]=1,this},yawPitchRoll:function(t,e,i){this.zero(),s.zero(),r.zero();var n=this.val,o=s.val,a=r.val,h=Math.sin(i),l=Math.cos(i);return n[10]=1,n[15]=1,n[0]=l,n[1]=h,n[4]=-h,n[5]=l,h=Math.sin(e),l=Math.cos(e),o[0]=1,o[15]=1,o[5]=l,o[10]=l,o[9]=-h,o[6]=h,h=Math.sin(t),l=Math.cos(t),a[5]=1,a[15]=1,a[0]=l,a[2]=-h,a[8]=h,a[10]=l,this.multiplyLocal(s),this.multiplyLocal(r),this},setWorldMatrix:function(t,e,i,n,o){return this.yawPitchRoll(t.y,t.x,t.z),s.scaling(i.x,i.y,i.z),r.xyz(e.x,e.y,e.z),this.multiplyLocal(s),this.multiplyLocal(r),void 0!==n&&this.multiplyLocal(n),void 0!==o&&this.multiplyLocal(o),this}}),s=new n,r=new n;t.exports=n},function(t,e,i){var n=i(0),s=i(172),r=i(331),o=new Int8Array([1,2,0]),a=new Float32Array([0,0,0]),h=new s(1,0,0),l=new s(0,1,0),u=new s,c=new r,d=new n({initialize:function(t,e,i,n){"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},rotationTo:function(t,e){var i=t.x*e.x+t.y*e.y+t.z*e.z;return i<-.999999?(u.copy(h).cross(t).length()<1e-6&&u.copy(l).cross(t),u.normalize(),this.setAxisAngle(u,Math.PI)):i>.999999?(this.x=0,this.y=0,this.z=0,this.w=1,this):(u.copy(t).cross(e),this.x=u.x,this.y=u.y,this.z=u.z,this.w=1+i,this.normalize())},setAxes:function(t,e,i){var n=c.val;return n[0]=e.x,n[3]=e.y,n[6]=e.z,n[1]=i.x,n[4]=i.y,n[7]=i.z,n[2]=-t.x,n[5]=-t.y,n[8]=-t.z,this.fromMat3(c).normalize()},identity:function(){return this.x=0,this.y=0,this.z=0,this.w=1,this},setAxisAngle:function(t,e){e*=.5;var i=Math.sin(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=Math.cos(e),this},multiply:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,o=t.y,a=t.z,h=t.w;return this.x=e*h+s*r+i*a-n*o,this.y=i*h+s*o+n*r-e*a,this.z=n*h+s*a+e*o-i*r,this.w=s*h-e*r-i*o-n*a,this},slerp:function(t,e){var i=this.x,n=this.y,s=this.z,r=this.w,o=t.x,a=t.y,h=t.z,l=t.w,u=i*o+n*a+s*h+r*l;u<0&&(u=-u,o=-o,a=-a,h=-h,l=-l);var c=1-e,d=e;if(1-u>1e-6){var f=Math.acos(u),p=Math.sin(f);c=Math.sin((1-e)*f)/p,d=Math.sin(e*f)/p}return this.x=c*i+d*o,this.y=c*n+d*a,this.z=c*s+d*h,this.w=c*r+d*l,this},invert:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n,r=s?1/s:0;return this.x=-t*r,this.y=-e*r,this.z=-i*r,this.w=n*r,this},conjugate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},rotateX:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+s*r,this.y=i*o+n*r,this.z=n*o-i*r,this.w=s*o-e*r,this},rotateY:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o-n*r,this.y=i*o+s*r,this.z=n*o+e*r,this.w=s*o-i*r,this},rotateZ:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+i*r,this.y=i*o-e*r,this.z=n*o+s*r,this.w=s*o-n*r,this},calculateW:function(){var t=this.x,e=this.y,i=this.z;return this.w=-Math.sqrt(1-t*t-e*e-i*i),this},fromMat3:function(t){var e,i=t.val,n=i[0]+i[4]+i[8];if(n>0)e=Math.sqrt(n+1),this.w=.5*e,e=.5/e,this.x=(i[7]-i[5])*e,this.y=(i[2]-i[6])*e,this.z=(i[3]-i[1])*e;else{var s=0;i[4]>i[0]&&(s=1),i[8]>i[3*s+s]&&(s=2);var r=o[s],h=o[r];e=Math.sqrt(i[3*s+s]-i[3*r+r]-i[3*h+h]+1),a[s]=.5*e,e=.5/e,a[r]=(i[3*r+s]+i[3*s+r])*e,a[h]=(i[3*h+s]+i[3*s+h])*e,this.x=a[0],this.y=a[1],this.z=a[2],this.w=(i[3*h+r]-i[3*r+h])*e}return this}});t.exports=d},function(t,e,i){var n=i(335),s=i(26),r=i(29),o=i(167);t.exports=function(t){var e=t.config;if((e.customEnvironment||e.canvas)&&e.renderType===r.AUTO)throw new Error("Must set explicit renderType in custom environment");if(!e.customEnvironment&&!e.canvas&&e.renderType!==r.HEADLESS)if(e.renderType===r.CANVAS||e.renderType!==r.CANVAS&&!o.webGL){if(!o.canvas)throw new Error("Cannot create Canvas or WebGL context, aborting.");e.renderType=r.CANVAS}else e.renderType=r.WEBGL;e.antialias||s.disableSmoothing();var a,h,l=t.scale.baseSize,u=l.width,c=l.height;e.canvas?(t.canvas=e.canvas,t.canvas.width=u,t.canvas.height=c):t.canvas=s.create(t,u,c,e.renderType),e.canvasStyle&&(t.canvas.style=e.canvasStyle),e.antialias||n.setCrisp(t.canvas),e.renderType!==r.HEADLESS&&(a=i(499),h=i(502),e.renderType===r.WEBGL?t.renderer=new h(t):(t.renderer=new a(t),t.context=t.renderer.gameContext))}},function(t,e){t.exports={setCrisp:function(t){return["optimizeSpeed","-moz-crisp-edges","-o-crisp-edges","-webkit-optimize-contrast","optimize-contrast","crisp-edges","pixelated"].forEach(function(e){t.style["image-rendering"]=e}),t.style.msInterpolationMode="nearest-neighbor",t},setBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}}},function(t,e,i){var n=i(29);t.exports=function(t){var e=t.config;if(!e.hideBanner){var i="WebGL";e.renderType===n.CANVAS?i="Canvas":e.renderType===n.HEADLESS&&(i="Headless");var s,r=e.audio,o=t.device.audio;if(s=!o.webAudio||r&&r.disableWebAudio?r&&r.noAudio||!o.webAudio&&!o.audioData?"No Audio":"HTML5 Audio":"Web Audio",t.device.browser.ie)window.console&&console.log("Phaser v"+n.VERSION+" / https://phaser.io");else{var a,h="",l=[h];Array.isArray(e.bannerBackgroundColor)?(e.bannerBackgroundColor.forEach(function(t){h=h.concat("%c "),l.push("background: "+t),a=t}),l[l.length-1]="color: "+e.bannerTextColor+"; background: "+a):(h=h.concat("%c "),l.push("color: "+e.bannerTextColor+"; background: "+e.bannerBackgroundColor)),l.push("background: #fff"),e.gameTitle&&(h=h.concat(e.gameTitle),e.gameVersion&&(h=h.concat(" v"+e.gameVersion)),e.hidePhaser||(h=h.concat(" / "))),e.hidePhaser||(h=h.concat("Phaser v"+n.VERSION+" ("+i+" | "+s+")")),h=h.concat(" %c "+e.gameURL),l[0]=h,console.log.apply(console,l)}}}},function(t,e,i){var n=i(0),s=i(6),r=i(1),o=i(338),a=new n({initialize:function(t,e){this.game=t,this.raf=new o,this.started=!1,this.running=!1,this.minFps=s(e,"min",5),this.targetFps=s(e,"target",60),this._min=1e3/this.minFps,this._target=1e3/this.targetFps,this.actualFps=this.targetFps,this.nextFpsUpdate=0,this.framesThisSecond=0,this.callback=r,this.forceSetTimeOut=s(e,"forceSetTimeOut",!1),this.time=0,this.startTime=0,this.lastTime=0,this.frame=0,this.inFocus=!0,this._pauseTime=0,this._coolDown=0,this.delta=0,this.deltaIndex=0,this.deltaHistory=[],this.deltaSmoothingMax=s(e,"deltaHistory",10),this.panicMax=s(e,"panicMax",120),this.rawDelta=0,this.now=0,this.smoothStep=s(e,"smoothStep",!0)},blur:function(){this.inFocus=!1},focus:function(){this.inFocus=!0,this.resetDelta()},pause:function(){this._pauseTime=window.performance.now()},resume:function(){this.resetDelta(),this.startTime+=this.time-this._pauseTime},resetDelta:function(){var t=window.performance.now();this.time=t,this.lastTime=t,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0;for(var e=0;e0||!this.inFocus)&&(this._coolDown--,r=Math.min(r,this._target)),r>this._min&&(r=n[i],r=Math.min(r,this._min)),n[i]=r,this.deltaIndex++,this.deltaIndex>s&&(this.deltaIndex=0),o=0;for(var a=0;athis.nextFpsUpdate&&(this.actualFps=.25*this.framesThisSecond+.75*this.actualFps,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0),this.framesThisSecond++;var h=o/this._target;this.callback(t,o,h),this.lastTime=t,this.frame++},tick:function(){this.step()},sleep:function(){this.running&&(this.raf.stop(),this.running=!1)},wake:function(t){this.running?this.sleep():t&&(this.startTime+=-this.lastTime+(this.lastTime+window.performance.now())),this.raf.start(this.step.bind(this),this.useRAF),this.running=!0,this.step()},getDuration:function(){return Math.round(this.lastTime-this.startTime)/1e3},getDurationMS:function(){return Math.round(this.lastTime-this.startTime)},stop:function(){return this.running=!1,this.started=!1,this.raf.stop(),this},destroy:function(){this.stop(),this.callback=r,this.raf=null,this.game=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(1),r=new n({initialize:function(){this.isRunning=!1,this.callback=s,this.tick=0,this.isSetTimeOut=!1,this.timeOutID=null,this.lastTime=0,this.target=0;var t=this;this.step=function e(){var i=window.performance.now();t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.requestAnimationFrame(e)},this.stepTimeout=function e(){var i=Date.now(),n=Math.min(Math.max(2*t.target+t.tick-i,0),t.target);t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.setTimeout(e,n)}},start:function(t,e,i){this.isRunning||(this.callback=t,this.isSetTimeOut=e,this.target=i,this.isRunning=!0,this.timeOutID=e?window.setTimeout(this.stepTimeout,0):window.requestAnimationFrame(this.step))},stop:function(){this.isRunning=!1,this.isSetTimeOut?clearTimeout(this.timeOutID):window.cancelAnimationFrame(this.timeOutID)},destroy:function(){this.stop(),this.callback=s}});t.exports=r},function(t,e,i){var n=i(18);t.exports=function(t){var e,i=t.events;void 0!==document.hidden?e="visibilitychange":["webkit","moz","ms"].forEach(function(t){void 0!==document[t+"Hidden"]&&(document.hidden=function(){return document[t+"Hidden"]},e=t+"visibilitychange")});e&&document.addEventListener(e,function(t){document.hidden||"pause"===t.type?i.emit(n.HIDDEN):i.emit(n.VISIBLE)},!1),window.onblur=function(){i.emit(n.BLUR)},window.onfocus=function(){i.emit(n.FOCUS)},window.focus&&t.config.autoFocus&&window.focus()}},function(t,e,i){var n=i(341),s=i(26),r=i(6);t.exports=function(t){var e=r(t,"data",[]),i=r(t,"canvas",null),o=r(t,"palette",n),a=r(t,"pixelWidth",1),h=r(t,"pixelHeight",a),l=r(t,"resizeCanvas",!0),u=r(t,"clearCanvas",!0),c=r(t,"preRender",null),d=r(t,"postRender",null),f=Math.floor(Math.abs(e[0].length*a)),p=Math.floor(Math.abs(e.length*h));i||(i=s.create2D(this,f,p),l=!1,u=!1),l&&(i.width=f,i.height=p);var g=i.getContext("2d");u&&g.clearRect(0,0,f,p),c&&c(i,g);for(var v=0;vi;)n-=i;ni.length-2?i.length-1:r+1],c=i[r>i.length-3?i.length-1:r+2];return e.set(n(a,h.x,l.x,u.x,c.x),n(a,h.y,l.y,u.y,c.y))},toJSON:function(){for(var t=[],e=0;e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}},function(t,e,i){var n=i(116);t.exports=function(t){if("complete"!==document.readyState&&"interactive"!==document.readyState){var e=function(){document.removeEventListener("deviceready",e,!0),document.removeEventListener("DOMContentLoaded",e,!0),window.removeEventListener("load",e,!0),t()};document.body?n.cordova?document.addEventListener("deviceready",e,!1):(document.addEventListener("DOMContentLoaded",e,!0),window.addEventListener("load",e,!0)):window.setTimeout(e,20)}else t()}},function(t,e,i){var n=i(175);t.exports=function(t,e){var i=window.screen,s=!!i&&(i.orientation||i.mozOrientation||i.msOrientation);if(s&&"string"==typeof s.type)return s.type;if("string"==typeof s)return s;if(i)return i.height>i.width?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if("number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return n.ORIENTATION.PORTRAIT;if(window.matchMedia("(orientation: landscape)").matches)return n.ORIENTATION.LANDSCAPE}return e>t?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE}},function(t,e){t.exports={NO_CENTER:0,CENTER_BOTH:1,CENTER_HORIZONTALLY:2,CENTER_VERTICALLY:3}},function(t,e){t.exports={LANDSCAPE:"landscape-primary",PORTRAIT:"portrait-primary"}},function(t,e){t.exports={NONE:0,WIDTH_CONTROLS_HEIGHT:1,HEIGHT_CONTROLS_WIDTH:2,FIT:3,ENVELOP:4,RESIZE:5}},function(t,e){t.exports={NO_ZOOM:1,ZOOM_2X:2,ZOOM_4X:4,MAX_ZOOM:-1}},function(t,e){t.exports=function(t){var e;return""!==t&&("string"==typeof t?e=document.getElementById(t):t&&1===t.nodeType&&(e=t)),e||(e=document.body),e}},function(t,e){t.exports=function(t){var e="";try{window.DOMParser?e=(new DOMParser).parseFromString(t,"text/xml"):(e=new ActiveXObject("Microsoft.XMLDOM")).loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null}},function(t,e,i){var n=i(0),s=i(177),r=i(9),o=i(54),a=i(18),h=i(360),l=i(361),u=i(362),c=i(363),d=i(32),f=i(329),p=new n({initialize:function(t,e){this.game=t,this.scaleManager,this.canvas,this.config=e,this.enabled=!0,this.events=new r,this.isOver=!0,this.defaultCursor="",this.keyboard=e.inputKeyboard?new h(this):null,this.mouse=e.inputMouse?new l(this):null,this.touch=e.inputTouch?new c(this):null,this.pointers=[],this.pointersTotal=e.inputActivePointers,e.inputTouch&&1===this.pointersTotal&&(this.pointersTotal=2);for(var i=0;i<=this.pointersTotal;i++){var n=new u(this,i);n.smoothFactor=e.inputSmoothFactor,this.pointers.push(n)}this.mousePointer=e.inputMouse?this.pointers[0]:null,this.activePointer=this.pointers[0],this.globalTopOnly=!0,this.time=0,this._tempPoint={x:0,y:0},this._tempHitTest=[],this._tempMatrix=new d,this._tempMatrix2=new d,this._tempSkip=!1,this.mousePointerContainer=[this.mousePointer],t.events.once(a.BOOT,this.boot,this)},boot:function(){this.canvas=this.game.canvas,this.scaleManager=this.game.scale,this.events.emit(o.MANAGER_BOOT),this.game.events.on(a.PRE_RENDER,this.preRender,this),this.game.events.once(a.DESTROY,this.destroy,this)},setCanvasOver:function(t){this.isOver=!0,this.events.emit(o.GAME_OVER,t)},setCanvasOut:function(t){this.isOver=!1,this.events.emit(o.GAME_OUT,t)},preRender:function(){var t=this.game.loop.now,e=this.game.loop.delta,i=this.game.scene.getScenes(!0,!0);this.time=t,this.events.emit(o.MANAGER_UPDATE);for(var n=0;n10&&(t=10-this.pointersTotal);for(var i=0;i-1&&e.preventDefault()}},this.onKeyUp=function(e){if(!e.defaultPrevented&&t.enabled&&t.manager){t.queue.push(e),t.manager.useQueue||t.manager.events.emit(o.MANAGER_PROCESS);var i=e.altKey||e.ctrlKey||e.shiftKey||e.metaKey;t.preventDefault&&!i&&t.captures.indexOf(e.keyCode)>-1&&e.preventDefault()}};var e=this.target;e&&(e.addEventListener("keydown",this.onKeyDown,!1),e.addEventListener("keyup",this.onKeyUp,!1),this.enabled=!0)},stopListeners:function(){var t=this.target;t.removeEventListener("keydown",this.onKeyDown,!1),t.removeEventListener("keyup",this.onKeyUp,!1),this.enabled=!1},postUpdate:function(){this.queue=[]},addCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},removeCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},clearCaptures:function(){this.captures=[],this.preventDefault=!1},destroy:function(){this.stopListeners(),this.clearCaptures(),this.queue=[],this.manager.game.events.off(r.POST_RENDER,this.postUpdate,this),this.target=null,this.enabled=!1,this.manager=null}});t.exports=l},function(t,e,i){var n=i(0),s=i(167),r=i(54),o=i(0),a=new n({initialize:function(t){this.manager=t,this.capture=!0,this.enabled=!1,this.target,this.locked=!1,this.onMouseMove=o,this.onMouseDown=o,this.onMouseUp=o,this.onMouseDownWindow=o,this.onMouseUpWindow=o,this.onMouseOver=o,this.onMouseOut=o,this.onMouseWheel=o,this.pointerLockChange=o,t.events.once(r.MANAGER_BOOT,this.boot,this)},boot:function(){var t=this.manager.config;this.enabled=t.inputMouse,this.target=t.inputMouseEventTarget,this.capture=t.inputMouseCapture,this.target?"string"==typeof this.target&&(this.target=document.getElementById(this.target)):this.target=this.manager.game.canvas,t.disableContextMenu&&this.disableContextMenu(),this.enabled&&this.target&&this.startListeners()},disableContextMenu:function(){return document.body.addEventListener("contextmenu",function(t){return t.preventDefault(),!1}),this},requestPointerLock:function(){if(s.pointerLock){var t=this.target;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock()}},releasePointerLock:function(){s.pointerLock&&(document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock())},startListeners:function(){var t=this,e=this.manager.canvas,i=window&&window.focus&&this.manager.game.config.autoFocus;this.onMouseMove=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseMove(e),t.capture&&e.preventDefault())},this.onMouseDown=function(n){i&&window.focus(),!n.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseDown(n),t.capture&&n.target===e&&n.preventDefault())},this.onMouseDownWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseDown(i)},this.onMouseUp=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseUp(i),t.capture&&i.target===e&&i.preventDefault())},this.onMouseUpWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseUp(i)},this.onMouseOver=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOver(e)},this.onMouseOut=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOut(e)},this.onMouseWheel=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.onMouseWheel(e)};var n=this.target;if(n){var r={passive:!0},o={passive:!1};n.addEventListener("mousemove",this.onMouseMove,this.capture?o:r),n.addEventListener("mousedown",this.onMouseDown,this.capture?o:r),n.addEventListener("mouseup",this.onMouseUp,this.capture?o:r),n.addEventListener("mouseover",this.onMouseOver,this.capture?o:r),n.addEventListener("mouseout",this.onMouseOut,this.capture?o:r),n.addEventListener("wheel",this.onMouseWheel,this.capture?o:r),window&&this.manager.game.config.inputWindowEvents&&(window.addEventListener("mousedown",this.onMouseDownWindow,o),window.addEventListener("mouseup",this.onMouseUpWindow,o)),s.pointerLock&&(this.pointerLockChange=function(e){var i=t.target;t.locked=document.pointerLockElement===i||document.mozPointerLockElement===i||document.webkitPointerLockElement===i,t.manager.onPointerLockChange(e)},document.addEventListener("pointerlockchange",this.pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this.pointerLockChange,!0)),this.enabled=!0}},stopListeners:function(){var t=this.target;t.removeEventListener("mousemove",this.onMouseMove),t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("mouseup",this.onMouseUp),t.removeEventListener("mouseover",this.onMouseOver),t.removeEventListener("mouseout",this.onMouseOut),window&&(window.removeEventListener("mousedown",this.onMouseDownWindow),window.removeEventListener("mouseup",this.onMouseUpWindow)),s.pointerLock&&(document.removeEventListener("pointerlockchange",this.pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this.pointerLockChange,!0))},destroy:function(){this.stopListeners(),this.target=null,this.enabled=!1,this.manager=null}});t.exports=a},function(t,e,i){var n=i(314),s=i(0),r=i(53),o=i(144),a=i(323),h=i(3),l=new s({initialize:function(t,e){this.manager=t,this.id=e,this.event,this.downElement,this.upElement,this.camera=null,this.button=0,this.buttons=0,this.position=new h,this.prevPosition=new h,this.midPoint=new h(-1,-1),this.velocity=new h,this.angle=0,this.distance=0,this.smoothFactor=0,this.motionFactor=.2,this.worldX=0,this.worldY=0,this.moveTime=0,this.downX=0,this.downY=0,this.downTime=0,this.upX=0,this.upY=0,this.upTime=0,this.primaryDown=!1,this.isDown=!1,this.wasTouch=!1,this.wasCanceled=!1,this.movementX=0,this.movementY=0,this.identifier=0,this.pointerId=null,this.active=0===e,this.locked=!1,this.deltaX=0,this.deltaY=0,this.deltaZ=0},updateWorldPoint:function(t){var e=this.x,i=this.y;1!==t.resolution&&(e+=t._x,i+=t._y);var n=t.getWorldPoint(e,i);return this.worldX=n.x,this.worldY=n.y,this},positionToCamera:function(t,e){return t.getWorldPoint(this.x,this.y,e)},updateMotion:function(){var t=this.position.x,e=this.position.y,i=this.midPoint.x,s=this.midPoint.y;if(t!==i||e!==s){var r=a(this.motionFactor,i,t),h=a(this.motionFactor,s,e);o(r,t,.1)&&(r=t),o(h,e,.1)&&(h=e),this.midPoint.set(r,h);var l=t-r,u=e-h;this.velocity.set(l,u),this.angle=n(r,h,t,e),this.distance=Math.sqrt(l*l+u*u)}},up:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=t.timeStamp),this.isDown=!1,this.wasTouch=!1},down:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=t.timeStamp),this.isDown=!0,this.wasTouch=!1},move:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.locked&&(this.movementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.movementY=t.movementY||t.mozMovementY||t.webkitMovementY||0),this.moveTime=t.timeStamp,this.wasTouch=!1},wheel:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ,this.wasTouch=!1},touchstart:function(t,e){t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.active=!0,this.buttons=1,this.event=e,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=e.timeStamp,this.isDown=!0,this.wasTouch=!0,this.wasCanceled=!1,this.updateMotion()},touchmove:function(t,e){this.event=e,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.moveTime=e.timeStamp,this.wasTouch=!0,this.updateMotion()},touchend:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!1,this.active=!1,this.updateMotion()},touchcancel:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!0,this.active=!1},noButtonDown:function(){return 0===this.buttons},leftButtonDown:function(){return!!(1&this.buttons)},rightButtonDown:function(){return!!(2&this.buttons)},middleButtonDown:function(){return!!(4&this.buttons)},backButtonDown:function(){return!!(8&this.buttons)},forwardButtonDown:function(){return!!(16&this.buttons)},leftButtonReleased:function(){return 0===this.button&&!this.isDown},rightButtonReleased:function(){return 2===this.button&&!this.isDown},middleButtonReleased:function(){return 1===this.button&&!this.isDown},backButtonReleased:function(){return 3===this.button&&!this.isDown},forwardButtonReleased:function(){return 4===this.button&&!this.isDown},getDistance:function(){return this.isDown?r(this.downX,this.downY,this.x,this.y):r(this.downX,this.downY,this.upX,this.upY)},getDistanceX:function(){return this.isDown?Math.abs(this.downX-this.x):Math.abs(this.downX-this.upX)},getDistanceY:function(){return this.isDown?Math.abs(this.downY-this.y):Math.abs(this.downY-this.upY)},getDuration:function(){return this.isDown?this.manager.time-this.downTime:this.upTime-this.downTime},getAngle:function(){return this.isDown?n(this.downX,this.downY,this.x,this.y):n(this.downX,this.downY,this.upX,this.upY)},getInterpolatedPosition:function(t,e){void 0===t&&(t=10),void 0===e&&(e=[]);for(var i=this.prevPosition.x,n=this.prevPosition.y,s=this.position.x,r=this.position.y,o=0;o0&&this.parentSize.height>0&&this.displaySize.setParent(this.parentSize),this.refresh()),t.events.on(a.PRE_STEP,this.step,this),t.events.once(a.DESTROY,this.destroy,this),this.startListeners()},parseConfig:function(t){this.getParent(t),this.getParentBounds();var e=t.width,i=t.height,s=t.scaleMode,r=t.resolution,o=t.zoom,a=t.autoRound;if("string"==typeof e){var h=this.parentSize.width;0===h&&(h=window.innerWidth);var l=parseInt(e,10)/100;e=Math.floor(h*l)}if("string"==typeof i){var c=this.parentSize.height;0===c&&(c=window.innerHeight);var d=parseInt(i,10)/100;i=Math.floor(c*d)}this.resolution=1,this.scaleMode=s,this.autoRound=a,this.autoCenter=t.autoCenter,this.resizeInterval=t.resizeInterval,a&&(e=Math.floor(e),i=Math.floor(i)),this.gameSize.setSize(e,i),o===n.ZOOM.MAX_ZOOM&&(o=this.getMaxZoom()),this.zoom=o,1!==o&&(this._resetZoom=!0),this.baseSize.setSize(e*r,i*r),a&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),t.minWidth>0&&this.displaySize.setMin(t.minWidth*o,t.minHeight*o),t.maxWidth>0&&this.displaySize.setMax(t.maxWidth*o,t.maxHeight*o),this.displaySize.setSize(e,i),this.orientation=u(e,i)},getParent:function(t){var e=t.parent;if(null!==e){if(this.parent=l(e),this.parentIsWindow=this.parent===document.body,t.expandParent&&t.scaleMode!==n.SCALE_MODE.NONE){var i=this.parent.getBoundingClientRect();(this.parentIsWindow||0===i.height)&&(document.documentElement.style.height="100%",document.body.style.height="100%",i=this.parent.getBoundingClientRect(),this.parentIsWindow||0!==i.height||(this.parent.style.overflow="hidden",this.parent.style.width="100%",this.parent.style.height="100%"))}t.fullscreenTarget&&!this.fullscreenTarget&&(this.fullscreenTarget=l(t.fullscreenTarget))}},getParentBounds:function(){if(!this.parent)return!1;var t=this.parentSize,e=this.parent.getBoundingClientRect();this.parentIsWindow&&this.game.device.os.iOS&&(e.height=h(!0));var i=this.resolution,n=e.width*i,s=e.height*i;return(t.width!==n||t.height!==s)&&(t.setSize(n,s),!0)},lockOrientation:function(t){var e=screen.lockOrientation||screen.mozLockOrientation||screen.msLockOrientation;return!!e&&e(t)},setParentSize:function(t,e){return this.parentSize.setSize(t,e),this.refresh()},setGameSize:function(t,e){var i=this.autoRound,n=this.resolution;i&&(t=Math.floor(t),e=Math.floor(e));var s=this.width,r=this.height;return this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),i&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t,e),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height,this.refresh(s,r)},resize:function(t,e){var i=this.zoom,n=this.resolution,s=this.autoRound;s&&(t=Math.floor(t),e=Math.floor(e));var r=this.width,o=this.height;this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),s&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t*i*n,e*i*n),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height;var a=this.canvas.style,h=t*i,l=e*i;return s&&(h=Math.floor(h),l=Math.floor(l)),h===t&&l===e||(a.width=h+"px",a.height=l+"px"),this.refresh(r,o)},setZoom:function(t){return this.zoom=t,this._resetZoom=!0,this.refresh()},setMaxZoom:function(){return this.zoom=this.getMaxZoom(),this._resetZoom=!0,this.refresh()},refresh:function(t,e){void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.updateScale(),this.updateBounds(),this.updateOrientation(),this.displayScale.set(this.baseSize.width/this.canvasBounds.width,this.baseSize.height/this.canvasBounds.height);var i=this.game.domContainer;if(i){this.baseSize.setCSS(i);var n=this.canvas.style,s=i.style;s.transform="scale("+this.displaySize.width/this.baseSize.width+","+this.displaySize.height/this.baseSize.height+")",s.marginLeft=n.marginLeft,s.marginTop=n.marginTop}return this.emit(o.RESIZE,this.gameSize,this.baseSize,this.displaySize,this.resolution,t,e),this},updateOrientation:function(){if(this._checkOrientation){this._checkOrientation=!1;var t=u(this.width,this.height);t!==this.orientation&&(this.orientation=t,this.emit(o.ORIENTATION_CHANGE,t))}},updateScale:function(){var t,e,i=this.canvas.style,s=this.gameSize.width,r=this.gameSize.height,o=this.zoom,a=this.autoRound;this.scaleMode===n.SCALE_MODE.NONE?(this.displaySize.setSize(s*o*1,r*o*1),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this._resetZoom&&(i.width=t+"px",i.height=e+"px",this._resetZoom=!1)):this.scaleMode===n.SCALE_MODE.RESIZE?(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),this.gameSize.setSize(this.displaySize.width,this.displaySize.height),this.baseSize.setSize(1*this.displaySize.width,1*this.displaySize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this.canvas.width=t,this.canvas.height=e):(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),i.width=t+"px",i.height=e+"px"),this.getParentBounds(),this.updateCenter()},getMaxZoom:function(){var t=p(this.parentSize.width,this.gameSize.width,0,!0),e=p(this.parentSize.height,this.gameSize.height,0,!0);return Math.max(Math.min(t,e),1)},updateCenter:function(){var t=this.autoCenter;if(t!==n.CENTER.NO_CENTER){var e=this.canvas,i=e.style,s=e.getBoundingClientRect(),r=s.width,o=s.height,a=Math.floor((this.parentSize.width-r)/2),h=Math.floor((this.parentSize.height-o)/2);t===n.CENTER.CENTER_HORIZONTALLY?h=0:t===n.CENTER.CENTER_VERTICALLY&&(a=0),i.marginLeft=a+"px",i.marginTop=h+"px"}},updateBounds:function(){var t=this.canvasBounds,e=this.canvas.getBoundingClientRect();t.x=e.left+(window.pageXOffset||0)-(document.documentElement.clientLeft||0),t.y=e.top+(window.pageYOffset||0)-(document.documentElement.clientTop||0),t.width=e.width,t.height=e.height},transformX:function(t){return(t-this.canvasBounds.left)*this.displayScale.x},transformY:function(t){return(t-this.canvasBounds.top)*this.displayScale.y},startFullscreen:function(t){void 0===t&&(t={navigationUI:"hide"});var e=this.fullscreen;if(e.available){if(!e.active){var i,n=this.getFullscreenTarget();(i=e.keyboard?n[e.request](Element.ALLOW_KEYBOARD_INPUT):n[e.request](t))?i.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)):e.active?this.fullscreenSuccessHandler():this.fullscreenErrorHandler()}}else this.emit(o.FULLSCREEN_UNSUPPORTED)},fullscreenSuccessHandler:function(){this.getParentBounds(),this.refresh(),this.emit(o.ENTER_FULLSCREEN)},fullscreenErrorHandler:function(t){this.removeFullscreenTarget(),this.emit(o.FULLSCREEN_FAILED,t)},getFullscreenTarget:function(){if(!this.fullscreenTarget){var t=document.createElement("div");t.style.margin="0",t.style.padding="0",t.style.width="100%",t.style.height="100%",this.fullscreenTarget=t,this._createdFullscreenTarget=!0}this._createdFullscreenTarget&&(this.canvas.parentNode.insertBefore(this.fullscreenTarget,this.canvas),this.fullscreenTarget.appendChild(this.canvas));return this.fullscreenTarget},removeFullscreenTarget:function(){if(this._createdFullscreenTarget){var t=this.fullscreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.canvas,t),e.removeChild(t)}}},stopFullscreen:function(){var t=this.fullscreen;if(!t.available)return this.emit(o.FULLSCREEN_UNSUPPORTED),!1;t.active&&document[t.cancel](),this.removeFullscreenTarget(),this.getParentBounds(),this.emit(o.LEAVE_FULLSCREEN),this.refresh()},toggleFullscreen:function(t){this.fullscreen.active?this.stopFullscreen():this.startFullscreen(t)},startListeners:function(){var t=this,e=this.listeners;if(e.orientationChange=function(){t._checkOrientation=!0,t.dirty=!0},e.windowResize=function(){t.dirty=!0},window.addEventListener("orientationchange",e.orientationChange,!1),window.addEventListener("resize",e.windowResize,!1),this.fullscreen.available){e.fullScreenChange=function(e){return t.onFullScreenChange(e)},e.fullScreenError=function(e){return t.onFullScreenError(e)};["webkit","moz",""].forEach(function(t){document.addEventListener(t+"fullscreenchange",e.fullScreenChange,!1),document.addEventListener(t+"fullscreenerror",e.fullScreenError,!1)}),document.addEventListener("MSFullscreenChange",e.fullScreenChange,!1),document.addEventListener("MSFullscreenError",e.fullScreenError,!1)}},onFullScreenChange:function(){document.fullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||this.stopFullscreen()},onFullScreenError:function(){this.removeFullscreenTarget()},step:function(t,e){this.parent&&(this._lastCheck+=e,(this.dirty||this._lastCheck>this.resizeInterval)&&(this.getParentBounds()&&this.refresh(),this.dirty=!1,this._lastCheck=0))},stopListeners:function(){var t=this.listeners;window.removeEventListener("orientationchange",t.orientationChange,!1),window.removeEventListener("resize",t.windowResize,!1);["webkit","moz",""].forEach(function(e){document.removeEventListener(e+"fullscreenchange",t.fullScreenChange,!1),document.removeEventListener(e+"fullscreenerror",t.fullScreenError,!1)}),document.removeEventListener("MSFullscreenChange",t.fullScreenChange,!1),document.removeEventListener("MSFullscreenError",t.fullScreenError,!1)},destroy:function(){this.removeAllListeners(),this.stopListeners(),this.game=null,this.canvas=null,this.canvasBounds=null,this.parent=null,this.fullscreenTarget=null,this.parentSize.destroy(),this.gameSize.destroy(),this.baseSize.destroy(),this.displaySize.destroy()},isFullscreen:{get:function(){return this.fullscreen.active}},width:{get:function(){return this.gameSize.width}},height:{get:function(){return this.gameSize.height}},isPortrait:{get:function(){return this.orientation===n.ORIENTATION.PORTRAIT}},isLandscape:{get:function(){return this.orientation===n.ORIENTATION.LANDSCAPE}},isGamePortrait:{get:function(){return this.height>this.width}},isGameLandscape:{get:function(){return this.width>this.height}}});t.exports=v},function(t,e,i){var n=i(22),s=i(0),r=i(93),o=i(3),a=new s({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=0),void 0===n&&(n=null),this._width=t,this._height=e,this._parent=n,this.aspectMode=i,this.aspectRatio=0===e?1:t/e,this.minWidth=0,this.minHeight=0,this.maxWidth=Number.MAX_VALUE,this.maxHeight=Number.MAX_VALUE,this.snapTo=new o},setAspectMode:function(t){return void 0===t&&(t=0),this.aspectMode=t,this.setSize(this._width,this._height)},setSnap:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.snapTo.set(t,e),this.setSize(this._width,this._height)},setParent:function(t){return this._parent=t,this.setSize(this._width,this._height)},setMin:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.minWidth=n(t,0,this.maxWidth),this.minHeight=n(e,0,this.maxHeight),this.setSize(this._width,this._height)},setMax:function(t,e){return void 0===t&&(t=Number.MAX_VALUE),void 0===e&&(e=t),this.maxWidth=n(t,this.minWidth,Number.MAX_VALUE),this.maxHeight=n(e,this.minHeight,Number.MAX_VALUE),this.setSize(this._width,this._height)},setSize:function(t,e){switch(void 0===t&&(t=0),void 0===e&&(e=t),this.aspectMode){case a.NONE:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height;break;case a.WIDTH_CONTROLS_HEIGHT:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(this._width*(1/this.aspectRatio),!1);break;case a.HEIGHT_CONTROLS_WIDTH:this._height=this.getNewHeight(r(e,this.snapTo.y)),this._width=this.getNewWidth(this._height*this.aspectRatio,!1);break;case a.FIT:this.constrain(t,e,!0);break;case a.ENVELOP:this.constrain(t,e,!1)}return this},setAspectRatio:function(t){return this.aspectRatio=t,this.setSize(this._width,this._height)},resize:function(t,e){return this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height,this},getNewWidth:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minWidth,this.maxWidth),e&&this._parent&&t>this._parent.width&&(t=Math.max(this.minWidth,this._parent.width)),t},getNewHeight:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minHeight,this.maxHeight),e&&this._parent&&t>this._parent.height&&(t=Math.max(this.minHeight,this._parent.height)),t},constrain:function(t,e,i){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=!0),t=this.getNewWidth(t),e=this.getNewHeight(e);var n=this.snapTo,s=0===e?1:t/e;return i&&this.aspectRatio>s||!i&&this.aspectRatio0&&(t=(e=r(e,n.y))*this.aspectRatio)):(i&&this.aspectRatios)&&(t=(e=r(e,n.y))*this.aspectRatio,n.x>0&&(e=(t=r(t,n.x))*(1/this.aspectRatio))),this._width=t,this._height=e,this},fitTo:function(t,e){return this.constrain(t,e,!0)},envelop:function(t,e){return this.constrain(t,e,!1)},setWidth:function(t){return this.setSize(t,this._height)},setHeight:function(t){return this.setSize(this._width,t)},toString:function(){return"[{ Size (width="+this._width+" height="+this._height+" aspectRatio="+this.aspectRatio+" aspectMode="+this.aspectMode+") }]"},setCSS:function(t){t&&t.style&&(t.style.width=this._width+"px",t.style.height=this._height+"px")},copy:function(t){return t.setAspectMode(this.aspectMode),t.aspectRatio=this.aspectRatio,t.setSize(this.width,this.height)},destroy:function(){this._parent=null,this.snapTo=null},width:{get:function(){return this._width},set:function(t){this.setSize(t,this._height)}},height:{get:function(){return this._height},set:function(t){this.setSize(this._width,t)}}});a.NONE=0,a.WIDTH_CONTROLS_HEIGHT=1,a.HEIGHT_CONTROLS_WIDTH=2,a.FIT=3,a.ENVELOP=4,t.exports=a},function(t,e,i){var n=i(0),s=i(123),r=i(19),o=i(18),a=i(6),h=i(81),l=i(1),u=i(368),c=i(178),d=new n({initialize:function(t,e){if(this.game=t,this.keys={},this.scenes=[],this._pending=[],this._start=[],this._queue=[],this._data={},this.isProcessing=!1,this.isBooted=!1,this.customViewports=0,e){Array.isArray(e)||(e=[e]);for(var i=0;i-1&&(delete this.keys[n],this.scenes.splice(i,1),this._start.indexOf(n)>-1&&(i=this._start.indexOf(n),this._start.splice(i,1)),e.sys.destroy())}return this},bootScene:function(t){var e,i=t.sys,n=i.settings;t.init&&(t.init.call(t,n.data),n.status=s.INIT,n.isTransition&&i.events.emit(r.TRANSITION_INIT,n.transitionFrom,n.transitionDuration)),i.load&&(e=i.load).reset(),e&&t.preload?(t.preload.call(t),0===e.list.size?this.create(t):(n.status=s.LOADING,e.once(h.COMPLETE,this.loadComplete,this),e.start())):this.create(t)},loadComplete:function(t){var e=t.scene;this.game.sound&&this.game.sound.onBlurPausedSounds&&this.game.sound.unlock(),this.create(e)},payloadComplete:function(t){this.bootScene(t.scene)},update:function(t,e){this.processQueue(),this.isProcessing=!0;for(var i=this.scenes.length-1;i>=0;i--){var n=this.scenes[i].sys;n.settings.status>s.START&&n.settings.status<=s.RUNNING&&n.step(t,e)}},render:function(t){for(var e=0;e=s.LOADING&&i.settings.status0){var i=this.getScene(t);this.scenes.splice(e,1),this.scenes.unshift(i)}}return this},moveDown:function(t){if(this.isProcessing)this._queue.push({op:"moveDown",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e>0){var i=e-1,n=this.getScene(t),s=this.getAt(i);this.scenes[e]=s,this.scenes[i]=n}}return this},moveUp:function(t){if(this.isProcessing)this._queue.push({op:"moveUp",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e=r.x&&t=r.y&&e=r.x&&t=r.y&&e-1){var o=this.context.getImageData(t,e,1,1);o.data[0]=i,o.data[1]=n,o.data[2]=s,o.data[3]=r,this.context.putImageData(o,t,e)}return this},putData:function(t,e,i,n,s,r,o){return void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=t.width),void 0===o&&(o=t.height),this.context.putImageData(t,e,i,n,s,r,o),this},getData:function(t,e,i,n){return t=s(Math.floor(t),0,this.width-1),e=s(Math.floor(e),0,this.height-1),i=s(i,1,this.width-t),n=s(n,1,this.height-e),this.context.getImageData(t,e,i,n)},getPixel:function(t,e,i){i||(i=new r);var n=this.getIndex(t,e);if(n>-1){var s=this.data,o=s[n+0],a=s[n+1],h=s[n+2],l=s[n+3];i.setTo(o,a,h,l)}return i},getPixels:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=i),t=Math.abs(Math.round(t)),e=Math.abs(Math.round(e));for(var o=s(t,0,this.width),a=s(t+i,0,this.width),h=s(e,0,this.height),l=s(e+n,0,this.height),u=new r,c=[],d=h;d0)&&(!!n.prototype.pause.call(this)&&(this.currentConfig.seek=this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0),this.stopAndReleaseAudioTag(),this.emit(r.PAUSE,this),!0)))},resume:function(){return!this.manager.isLocked(this,"resume")&&(!(this.startTime>0)&&(!!n.prototype.resume.call(this)&&(!!this.pickAndPlayAudioTag()&&(this.emit(r.RESUME,this),!0))))},stop:function(){return!this.manager.isLocked(this,"stop")&&(!!n.prototype.stop.call(this)&&(this.stopAndReleaseAudioTag(),this.emit(r.STOP,this),!0))},pickAndPlayAudioTag:function(){if(!this.pickAudioTag())return this.reset(),!1;var t=this.currentConfig.seek,e=this.currentConfig.delay,i=(this.currentMarker?this.currentMarker.start:0)+t;return this.previousTime=i,this.audio.currentTime=i,this.applyConfig(),0===e?(this.startTime=0,this.audio.paused&&this.playCatchPromise()):(this.startTime=window.performance.now()+1e3*e,this.audio.paused||this.audio.pause()),this.resetConfig(),!0},pickAudioTag:function(){if(this.audio)return!0;for(var t=0;t0)this.startTime=n-this.manager.loopEndOffset?(this.audio.currentTime=i+Math.max(0,s-n),s=this.audio.currentTime):s=n)return this.reset(),this.stopAndReleaseAudioTag(),void this.emit(r.COMPLETE,this);this.previousTime=s}},destroy:function(){n.prototype.destroy.call(this),this.tags=null,this.audio&&this.stopAndReleaseAudioTag()},updateMute:function(){this.audio&&(this.audio.muted=this.currentConfig.mute||this.manager.mute)},updateVolume:function(){this.audio&&(this.audio.volume=this.currentConfig.volume*this.manager.volume)},calculateRate:function(){n.prototype.calculateRate.call(this),this.audio&&(this.audio.playbackRate=this.totalRate)},mute:{get:function(){return this.currentConfig.mute},set:function(t){this.currentConfig.mute=t,this.manager.isLocked(this,"mute",t)||(this.updateMute(),this.emit(r.MUTE,this,t))}},setMute:function(t){return this.mute=t,this},volume:{get:function(){return this.currentConfig.volume},set:function(t){this.currentConfig.volume=t,this.manager.isLocked(this,"volume",t)||(this.updateVolume(),this.emit(r.VOLUME,this,t))}},setVolume:function(t){return this.volume=t,this},rate:{get:function(){return this.currentConfig.rate},set:function(t){this.currentConfig.rate=t,this.manager.isLocked(this,r.RATE,t)||(this.calculateRate(),this.emit(r.RATE,this,t))}},setRate:function(t){return this.rate=t,this},detune:{get:function(){return this.currentConfig.detune},set:function(t){this.currentConfig.detune=t,this.manager.isLocked(this,r.DETUNE,t)||(this.calculateRate(),this.emit(r.DETUNE,this,t))}},setDetune:function(t){return this.detune=t,this},seek:{get:function(){return this.isPlaying?this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0):this.isPaused?this.currentConfig.seek:0},set:function(t){this.manager.isLocked(this,"seek",t)||this.startTime>0||(this.isPlaying||this.isPaused)&&(t=Math.min(Math.max(0,t),this.duration),this.isPlaying?(this.previousTime=t,this.audio.currentTime=t):this.isPaused&&(this.currentConfig.seek=t),this.emit(r.SEEK,this,t))}},setSeek:function(t){return this.seek=t,this},loop:{get:function(){return this.currentConfig.loop},set:function(t){this.currentConfig.loop=t,this.manager.isLocked(this,"loop",t)||(this.audio&&(this.audio.loop=t),this.emit(r.LOOP,this,t))}},setLoop:function(t){return this.loop=t,this}});t.exports=o},function(t,e,i){var n=i(124),s=i(0),r=i(9),o=i(378),a=i(1),h=new s({Extends:r,initialize:function(t){r.call(this),this.game=t,this.sounds=[],this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.pauseOnBlur=!0,this.locked=!1},add:function(t,e){var i=new o(this,t,e);return this.sounds.push(i),i},addAudioSprite:function(t,e){var i=this.add(t,e);return i.spritemap={},i},play:function(t,e){return!1},playAudioSprite:function(t,e,i){return!1},remove:function(t){return n.prototype.remove.call(this,t)},removeByKey:function(t){return n.prototype.removeByKey.call(this,t)},pauseAll:a,resumeAll:a,stopAll:a,update:a,setRate:a,setDetune:a,setMute:a,setVolume:a,forEachActiveSound:function(t,e){n.prototype.forEachActiveSound.call(this,t,e)},destroy:function(){n.prototype.destroy.call(this)}});t.exports=h},function(t,e,i){var n=i(125),s=i(0),r=i(9),o=i(17),a=new s({Extends:r,initialize:function(t,e,i){void 0===i&&(i={}),r.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=0,this.totalDuration=0,this.config=o({mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},i),this.currentConfig=this.config,this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.seek=0,this.loop=!1,this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!1},updateMarker:function(t){return!1},removeMarker:function(t){return null},play:function(t,e){return!1},pause:function(){return!1},resume:function(){return!1},stop:function(){return!1},destroy:function(){this.manager.remove(this),n.prototype.destroy.call(this)}});t.exports=a},function(t,e,i){var n=i(380),s=i(124),r=i(0),o=i(59),a=i(381),h=new r({Extends:s,initialize:function(t){this.context=this.createAudioContext(t),this.masterMuteNode=this.context.createGain(),this.masterVolumeNode=this.context.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(this.context.destination),this.destination=this.masterMuteNode,this.locked="suspended"===this.context.state&&("ontouchstart"in window||"onclick"in window),s.call(this,t),this.locked&&this.unlock()},createAudioContext:function(t){var e=t.config.audio;return e&&e.context?(e.context.resume(),e.context):new AudioContext},setAudioContext:function(t){return this.context&&this.context.close(),this.masterMuteNode&&this.masterMuteNode.disconnect(),this.masterVolumeNode&&this.masterVolumeNode.disconnect(),this.context=t,this.masterMuteNode=t.createGain(),this.masterVolumeNode=t.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(t.destination),this.destination=this.masterMuteNode,this},add:function(t,e){var i=new a(this,t,e);return this.sounds.push(i),i},decodeAudio:function(t,e){var i;i=Array.isArray(t)?t:[{key:t,data:e}];for(var s=this.game.cache.audio,r=i.length,a=0;a>4,u[h++]=(15&i)<<4|s>>2,u[h++]=(3&s)<<6|63&r;return l}},function(t,e,i){var n=i(125),s=i(0),r=i(59),o=new s({Extends:n,initialize:function(t,e,i){if(void 0===i&&(i={}),this.audioBuffer=t.game.cache.audio.get(e),!this.audioBuffer)throw new Error('There is no audio asset with key "'+e+'" in the audio cache');this.source=null,this.loopSource=null,this.muteNode=t.context.createGain(),this.volumeNode=t.context.createGain(),this.playTime=0,this.startTime=0,this.loopTime=0,this.rateUpdates=[],this.hasEnded=!1,this.hasLooped=!1,this.muteNode.connect(this.volumeNode),this.volumeNode.connect(t.destination),this.duration=this.audioBuffer.duration,this.totalDuration=this.audioBuffer.duration,n.call(this,t,e,i)},play:function(t,e){return!!n.prototype.play.call(this,t,e)&&(this.stopAndRemoveBufferSource(),this.createAndStartBufferSource(),this.emit(r.PLAY,this),!0)},pause:function(){return!(this.manager.context.currentTime-1;r--)n[s][r]=t[r][s]}return n}},function(t,e){function i(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function n(t,e){return te?1:0}var s=function(t,e,r,o,a){for(void 0===r&&(r=0),void 0===o&&(o=t.length-1),void 0===a&&(a=n);o>r;){if(o-r>600){var h=o-r+1,l=e-r+1,u=Math.log(h),c=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*c*(h-c)/h)*(l-h/2<0?-1:1),f=Math.max(r,Math.floor(e-l*c/h+d)),p=Math.min(o,Math.floor(e+(h-l)*c/h+d));s(t,e,f,p,a)}var g=t[e],v=r,m=o;for(i(t,r,e),a(t[o],g)>0&&i(t,r,o);v0;)m--}0===a(t[r],g)?i(t,r,m):i(t,++m,o),m<=e&&(r=m+1),e<=m&&(o=m-1)}};t.exports=s},function(t,e,i){var n=i(6),s=i(114),r=function(t,e,i){for(var n=[],s=0;s0?s.delayedPlay(d,r,o):s.load(r)}return t}},function(t,e,i){var n=i(11);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.right,e.right)-s,a=Math.max(t.bottom,e.bottom)-r;return i.setTo(s,r,o,a)}},function(t,e,i){var n=i(0),s=i(12),r=i(950),o=i(14),a=i(7),h=i(176),l=i(19),u=i(330),c=new n({Extends:o,Mixins:[s.AlphaSingle,s.BlendMode,s.Depth,s.Origin,s.ScrollFactor,s.Transform,s.Visible,r],initialize:function(t,e,i,n,s,r){o.call(this,t,"DOMElement"),this.parent=t.sys.game.domContainer,this.cache=t.sys.cache.html,this.node,this.transformOnly=!1,this.skewX=0,this.skewY=0,this.rotate3d=new u,this.rotate3dAngle="deg",this.width=0,this.height=0,this.displayWidth=0,this.displayHeight=0,this.handler=this.dispatchNativeEvent.bind(this),this.setPosition(e,i),"string"==typeof n?"#"===n[0]?this.setElement(n.substr(1),s,r):this.createElement(n,s,r):n&&this.setElement(n,s,r),t.sys.events.on(l.SLEEP,this.handleSceneEvent,this),t.sys.events.on(l.WAKE,this.handleSceneEvent,this)},handleSceneEvent:function(t){var e=this.node,i=e.style;e&&(i.display=t.settings.visible?"block":"none")},setSkew:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.skewX=t,this.skewY=e,this},setPerspective:function(t){return this.parent.style.perspective=t+"px",this},perspective:{get:function(){return parseFloat(this.parent.style.perspective)},set:function(t){this.parent.style.perspective=t+"px"}},addListener:function(t){if(this.node){t=t.split(" ");for(var e=0;e>>16,y=(65280&p)>>>8,x=255&p,c.strokeStyle="rgba("+m+","+y+","+x+","+d+")",c.lineWidth=v,T+=3;break;case n.FILL_STYLE:g=l[T+1],f=l[T+2],m=(16711680&g)>>>16,y=(65280&g)>>>8,x=255&g,c.fillStyle="rgba("+m+","+y+","+x+","+f+")",T+=2;break;case n.BEGIN_PATH:c.beginPath();break;case n.CLOSE_PATH:c.closePath();break;case n.FILL_PATH:h||c.fill();break;case n.STROKE_PATH:h||c.stroke();break;case n.FILL_RECT:h?c.rect(l[T+1],l[T+2],l[T+3],l[T+4]):c.fillRect(l[T+1],l[T+2],l[T+3],l[T+4]),T+=4;break;case n.FILL_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.fill(),T+=6;break;case n.STROKE_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.stroke(),T+=6;break;case n.LINE_TO:c.lineTo(l[T+1],l[T+2]),T+=2;break;case n.MOVE_TO:c.moveTo(l[T+1],l[T+2]),T+=2;break;case n.LINE_FX_TO:c.lineTo(l[T+1],l[T+2]),T+=5;break;case n.MOVE_FX_TO:c.moveTo(l[T+1],l[T+2]),T+=5;break;case n.SAVE:c.save();break;case n.RESTORE:c.restore();break;case n.TRANSLATE:c.translate(l[T+1],l[T+2]),T+=2;break;case n.SCALE:c.scale(l[T+1],l[T+2]),T+=2;break;case n.ROTATE:c.rotate(l[T+1]),T+=1;break;case n.GRADIENT_FILL_STYLE:T+=5;break;case n.GRADIENT_LINE_STYLE:T+=6;break;case n.SET_TEXTURE:T+=2}c.restore()}}},function(t,e,i){var n=i(0),s=i(2),r=new n({initialize:function(t,e,i,n,r){if("object"==typeof t){var o=t;t=s(o,"x",0),e=s(o,"y",0),i=s(o,"power",0),n=s(o,"epsilon",100),r=s(o,"gravity",50)}else void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=100),void 0===r&&(r=50);this.x=t,this.y=e,this.active=!0,this._gravity=r,this._power=0,this._epsilon=0,this.power=i,this.epsilon=n},update:function(t,e){var i=this.x-t.x,n=this.y-t.y,s=i*i+n*n;if(0!==s){var r=Math.sqrt(s);s0},resetPosition:function(){this.x=0,this.y=0},fire:function(t,e){var i=this.emitter;this.frame=i.getFrame(),i.emitZone&&i.emitZone.getPoint(this),void 0===t?(i.follow&&(this.x+=i.follow.x+i.followOffset.x),this.x+=i.x.onEmit(this,"x")):this.x+=t,void 0===e?(i.follow&&(this.y+=i.follow.y+i.followOffset.y),this.y+=i.y.onEmit(this,"y")):this.y+=e,this.life=i.lifespan.onEmit(this,"lifespan"),this.lifeCurrent=this.life,this.lifeT=0;var n=i.speedX.onEmit(this,"speedX"),o=i.speedY?i.speedY.onEmit(this,"speedY"):n;if(i.radial){var a=s(i.angle.onEmit(this,"angle"));this.velocityX=Math.cos(a)*Math.abs(n),this.velocityY=Math.sin(a)*Math.abs(o)}else if(i.moveTo){var h=i.moveToX.onEmit(this,"moveToX"),l=i.moveToY?i.moveToY.onEmit(this,"moveToY"):h,u=Math.atan2(l-this.y,h-this.x),c=r(this.x,this.y,h,l)/(this.life/1e3);this.velocityX=Math.cos(u)*c,this.velocityY=Math.sin(u)*c}else this.velocityX=n,this.velocityY=o;i.acceleration&&(this.accelerationX=i.accelerationX.onEmit(this,"accelerationX"),this.accelerationY=i.accelerationY.onEmit(this,"accelerationY")),this.maxVelocityX=i.maxVelocityX.onEmit(this,"maxVelocityX"),this.maxVelocityY=i.maxVelocityY.onEmit(this,"maxVelocityY"),this.delayCurrent=i.delay.onEmit(this,"delay"),this.scaleX=i.scaleX.onEmit(this,"scaleX"),this.scaleY=i.scaleY?i.scaleY.onEmit(this,"scaleY"):this.scaleX,this.angle=i.rotate.onEmit(this,"rotate"),this.rotation=s(this.angle),this.bounce=i.bounce.onEmit(this,"bounce"),this.alpha=i.alpha.onEmit(this,"alpha"),this.tint=i.tint.onEmit(this,"tint")},computeVelocity:function(t,e,i,n){var s=this.velocityX,r=this.velocityY,o=this.accelerationX,a=this.accelerationY,h=this.maxVelocityX,l=this.maxVelocityY;s+=t.gravityX*i,r+=t.gravityY*i,o&&(s+=o*i),a&&(r+=a*i),s>h?s=h:s<-h&&(s=-h),r>l?r=l:r<-l&&(r=-l),this.velocityX=s,this.velocityY=r;for(var u=0;ue.right&&t.collideRight&&(this.x=e.right,this.velocityX*=i),this.ye.bottom&&t.collideBottom&&(this.y=e.bottom,this.velocityY*=i)},update:function(t,e,i){if(this.delayCurrent>0)return this.delayCurrent-=t,!1;var n=this.emitter,r=1-this.lifeCurrent/this.life;return this.lifeT=r,this.computeVelocity(n,t,e,i),this.x+=this.velocityX*e,this.y+=this.velocityY*e,n.bounds&&this.checkBounds(n),n.deathZone&&n.deathZone.willKill(this)?(this.lifeCurrent=0,!0):(this.scaleX=n.scaleX.onUpdate(this,"scaleX",r,this.scaleX),n.scaleY?this.scaleY=n.scaleY.onUpdate(this,"scaleY",r,this.scaleY):this.scaleY=this.scaleX,this.angle=n.rotate.onUpdate(this,"rotate",r,this.angle),this.rotation=s(this.angle),this.alpha=n.alpha.onUpdate(this,"alpha",r,this.alpha),this.tint=n.tint.onUpdate(this,"tint",r,this.tint),this.lifeCurrent-=t,this.lifeCurrent<=0)}});t.exports=o},function(t,e,i){var n=i(52),s=i(0),r=i(12),o=i(397),a=i(398),h=i(967),l=i(2),u=i(183),c=i(399),d=i(99),f=i(395),p=i(400),g=i(11),v=i(128),m=i(3),y=i(58),x=new s({Mixins:[r.BlendMode,r.Mask,r.ScrollFactor,r.Visible],initialize:function(t,e){this.manager=t,this.texture=t.texture,this.frames=[t.defaultFrame],this.defaultFrame=t.defaultFrame,this.configFastMap=["active","blendMode","collideBottom","collideLeft","collideRight","collideTop","deathCallback","deathCallbackScope","emitCallback","emitCallbackScope","follow","frequency","gravityX","gravityY","maxParticles","name","on","particleBringToTop","particleClass","radial","timeScale","trackVisible","visible"],this.configOpMap=["accelerationX","accelerationY","angle","alpha","bounce","delay","lifespan","maxVelocityX","maxVelocityY","moveToX","moveToY","quantity","rotate","scaleX","scaleY","speedX","speedY","tint","x","y"],this.name="",this.particleClass=f,this.x=new h(e,"x",0,!0),this.y=new h(e,"y",0,!0),this.radial=!0,this.gravityX=0,this.gravityY=0,this.acceleration=!1,this.accelerationX=new h(e,"accelerationX",0,!0),this.accelerationY=new h(e,"accelerationY",0,!0),this.maxVelocityX=new h(e,"maxVelocityX",1e4,!0),this.maxVelocityY=new h(e,"maxVelocityY",1e4,!0),this.speedX=new h(e,"speedX",0,!0),this.speedY=new h(e,"speedY",0,!0),this.moveTo=!1,this.moveToX=new h(e,"moveToX",0,!0),this.moveToY=new h(e,"moveToY",0,!0),this.bounce=new h(e,"bounce",0,!0),this.scaleX=new h(e,"scaleX",1),this.scaleY=new h(e,"scaleY",1),this.tint=new h(e,"tint",4294967295),this.alpha=new h(e,"alpha",1),this.lifespan=new h(e,"lifespan",1e3,!0),this.angle=new h(e,"angle",{min:0,max:360},!0),this.rotate=new h(e,"rotate",0),this.emitCallback=null,this.emitCallbackScope=null,this.deathCallback=null,this.deathCallbackScope=null,this.maxParticles=0,this.quantity=new h(e,"quantity",1,!0),this.delay=new h(e,"delay",0,!0),this.frequency=0,this.on=!0,this.particleBringToTop=!0,this.timeScale=1,this.emitZone=null,this.deathZone=null,this.bounds=null,this.collideLeft=!0,this.collideRight=!0,this.collideTop=!0,this.collideBottom=!0,this.active=!0,this.visible=!0,this.blendMode=n.NORMAL,this.follow=null,this.followOffset=new m,this.trackVisible=!1,this.currentFrame=0,this.randomFrame=!0,this.frameQuantity=1,this.dead=[],this.alive=[],this._counter=0,this._frameCounter=0,e&&this.fromJSON(e)},fromJSON:function(t){if(!t)return this;var e=0,i="";for(e=0;e0&&this.getParticleCount()===this.maxParticles},onParticleEmit:function(t,e){return void 0===t?(this.emitCallback=null,this.emitCallbackScope=null):"function"==typeof t&&(this.emitCallback=t,e&&(this.emitCallbackScope=e)),this},onParticleDeath:function(t,e){return void 0===t?(this.deathCallback=null,this.deathCallbackScope=null):"function"==typeof t&&(this.deathCallback=t,e&&(this.deathCallbackScope=e)),this},killAll:function(){for(var t=this.dead,e=this.alive;e.length>0;)t.push(e.pop());return this},forEachAlive:function(t,e){for(var i=this.alive,n=i.length,s=0;s0){var u=this.deathCallback,c=this.deathCallbackScope;for(o=h-1;o>=0;o--){var d=a[o];s.splice(d.index,1),r.push(d.particle),u&&u.call(c,d.particle),d.particle.resetPosition()}}this.on&&(0===this.frequency?this.emitParticle():this.frequency>0&&(this._counter-=e,this._counter<=0&&(this.emitParticle(),this._counter=this.frequency-Math.abs(this._counter))))},depthSortCallback:function(t,e){return t.y-e.y}});t.exports=x},function(t,e,i){var n=new(i(0))({initialize:function(t,e){this.source=t,this.killOnEnter=e},willKill:function(t){var e=this.source.contains(t.x,t.y);return e&&this.killOnEnter||!e&&!this.killOnEnter}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s){void 0===n&&(n=!1),void 0===s&&(s=!0),this.source=t,this.points=[],this.quantity=e,this.stepRate=i,this.yoyo=n,this.counter=-1,this.seamless=s,this._length=0,this._direction=0,this.updateSource()},updateSource:function(){if(this.points=this.source.getPoints(this.quantity,this.stepRate),this.seamless){var t=this.points[0],e=this.points[this.points.length-1];t.x===e.x&&t.y===e.y&&this.points.pop()}var i=this._length;return this._length=this.points.length,this._lengththis._length&&(this.counter=this._length-1),this},changeSource:function(t){return this.source=t,this.updateSource()},getPoint:function(t){0===this._direction?(this.counter++,this.counter>=this._length&&(this.yoyo?(this._direction=1,this.counter=this._length-1):this.counter=0)):(this.counter--,-1===this.counter&&(this.yoyo?(this._direction=0,this.counter=0):this.counter=this._length-1));var e=this.points[this.counter];e&&(t.x=e.x,t.y=e.y)}});t.exports=n},function(t,e){t.exports=function(t,e){for(var i=0;i0&&(s=-h.PI2+s%h.PI2):s>h.PI2?s=h.PI2:s<0&&(s=h.PI2+s%h.PI2);for(var u,c=[a+Math.cos(n)*i,l+Math.sin(n)*i];e<1;)u=s*e+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),e+=t;return u=s+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),c.push(a+Math.cos(n)*i,l+Math.sin(n)*i),this.pathIndexes=o(c),this.pathData=c,this}});t.exports=u},function(t,e,i){var n=i(0),s=i(993),r=i(66),o=i(11),a=i(30),h=new n({Extends:a,Mixins:[s],initialize:function(t,e,i,n,s,r){void 0===e&&(e=0),void 0===i&&(i=0),a.call(this,t,"Curve",n),this._smoothness=32,this._curveBounds=new o,this.closePath=!1,this.setPosition(e,i),void 0!==s&&this.setFillStyle(s,r),this.updateData()},smoothness:{get:function(){return this._smoothness},set:function(t){this._smoothness=t,this.updateData()}},setSmoothness:function(t){return this._smoothness=t,this.updateData()},updateData:function(){var t=this._curveBounds,e=this._smoothness;this.geom.getBounds(t,e),this.setSize(t.width,t.height),this.updateDisplayOrigin();for(var i=[],n=this.geom.getPoints(e),s=0;sc+v)){var m=g.getPoint((u-c)/v);o.push(m);break}c+=v}return o}},function(t,e,i){var n=i(57),s=i(56);t.exports=function(t){for(var e=t.points,i=0,r=0;r0&&r.push(i([0,0],n[0])),e=0;e1&&r.push(i([0,0],n[n.length-1])),t.setTo(r)}},function(t,e,i){var n=i(0),s=i(11),r=i(30),o=i(1014),a=new n({Extends:r,Mixins:[o],initialize:function(t,e,i,n,o,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=128),void 0===o&&(o=128),r.call(this,t,"Rectangle",new s(0,0,n,o)),this.setPosition(e,i),this.setSize(n,o),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},updateData:function(){var t=[],e=this.geom,i=this._tempLine;return e.getLineA(i),t.push(i.x1,i.y1,i.x2,i.y2),e.getLineB(i),t.push(i.x2,i.y2),e.getLineC(i),t.push(i.x2,i.y2),e.getLineD(i),t.push(i.x2,i.y2),this.pathData=t,this}});t.exports=a},function(t,e,i){var n=i(1017),s=i(0),r=i(66),o=i(30),a=new s({Extends:o,Mixins:[n],initialize:function(t,e,i,n,s,r,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=5),void 0===s&&(s=32),void 0===r&&(r=64),o.call(this,t,"Star",null),this._points=n,this._innerRadius=s,this._outerRadius=r,this.setPosition(e,i),this.setSize(2*r,2*r),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},setPoints:function(t){return this._points=t,this.updateData()},setInnerRadius:function(t){return this._innerRadius=t,this.updateData()},setOuterRadius:function(t){return this._outerRadius=t,this.updateData()},points:{get:function(){return this._points},set:function(t){this._points=t,this.updateData()}},innerRadius:{get:function(){return this._innerRadius},set:function(t){this._innerRadius=t,this.updateData()}},outerRadius:{get:function(){return this._outerRadius},set:function(t){this._outerRadius=t,this.updateData()}},updateData:function(){var t=[],e=this._points,i=this._innerRadius,n=this._outerRadius,s=Math.PI/2*3,o=Math.PI/e,a=n,h=n;t.push(a,h+-n);for(var l=0;l=1)return i.x=r.x1,i.y=r.y1,i;var h=s(r),l=s(o),u=s(a),c=(h+l+u)*e,d=0;return ch+l?(d=(c-=h+l)/u,i.x=a.x1+(a.x2-a.x1)*d,i.y=a.y1+(a.y2-a.y1)*d):(d=(c-=h)/l,i.x=o.x1+(o.x2-o.x1)*d,i.y=o.y1+(o.y2-o.y1)*d),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]);var o=t.getLineA(),a=t.getLineB(),h=t.getLineC(),l=n(o),u=n(a),c=n(h),d=l+u+c;e||(e=d/i);for(var f=0;fl+u?(g=(p-=l+u)/c,v.x=h.x1+(h.x2-h.x1)*g,v.y=h.y1+(h.y2-h.y1)*g):(g=(p-=l)/u,v.x=a.x1+(a.x2-a.x1)*g,v.y=a.y1+(a.y2-a.y1)*g),r.push(v)}return r}},function(t,e){t.exports=function(t,e,i){if(!t||"number"==typeof t)return!1;if(t.hasOwnProperty(e))return t[e]=i,!0;if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=t,o=0;o0?(h=this.lightPool.pop()).set(t,e,i,a[0],a[1],a[2],o):h=new s(t,e,i,a[0],a[1],a[2],o),this.lights.push(h),h},removeLight:function(t){var e=this.lights.indexOf(t);return e>=0&&(this.lightPool.push(t),this.lights.splice(e,1)),this},shutdown:function(){for(;this.lights.length>0;)this.lightPool.push(this.lights.pop());this.ambientColor={r:.1,g:.1,b:.1},this.culledLights.length=0,this.lights.length=0},destroy:function(){this.shutdown()}});t.exports=o},function(t,e,i){var n=i(46),s=i(17),r={Circle:i(1078),Ellipse:i(1088),Intersects:i(423),Line:i(1107),Point:i(1128),Polygon:i(1142),Rectangle:i(436),Triangle:i(1172)};r=s(!1,r,n),t.exports=r},function(t,e,i){t.exports={CircleToCircle:i(202),CircleToRectangle:i(203),GetCircleToCircle:i(1098),GetCircleToRectangle:i(1099),GetLineToCircle:i(204),GetLineToRectangle:i(206),GetRectangleIntersection:i(1100),GetRectangleToRectangle:i(1101),GetRectangleToTriangle:i(1102),GetTriangleToCircle:i(1103),GetTriangleToLine:i(428),GetTriangleToTriangle:i(1104),LineToCircle:i(205),LineToLine:i(84),LineToRectangle:i(424),PointToLine:i(432),PointToLineSegment:i(1105),RectangleToRectangle:i(131),RectangleToTriangle:i(425),RectangleToValues:i(1106),TriangleToCircle:i(427),TriangleToLine:i(429),TriangleToTriangle:i(430)}},function(t,e){t.exports=function(t,e){var i=t.x1,n=t.y1,s=t.x2,r=t.y2,o=e.x,a=e.y,h=e.right,l=e.bottom,u=0;if(i>=o&&i<=h&&n>=a&&n<=l||s>=o&&s<=h&&r>=a&&r<=l)return!0;if(i=o){if((u=n+(r-n)*(o-i)/(s-i))>a&&u<=l)return!0}else if(i>h&&s<=h&&(u=n+(r-n)*(h-i)/(s-i))>=a&&u<=l)return!0;if(n=a){if((u=i+(s-i)*(a-n)/(r-n))>=o&&u<=h)return!0}else if(n>l&&r<=l&&(u=i+(s-i)*(l-n)/(r-n))>=o&&u<=h)return!0;return!1}},function(t,e,i){var n=i(84),s=i(47),r=i(207),o=i(426);t.exports=function(t,e){if(e.left>t.right||e.rightt.bottom||e.bottom0}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x,y:t.y}),e.push({x:t.right,y:t.y}),e.push({x:t.right,y:t.bottom}),e.push({x:t.x,y:t.bottom}),e}},function(t,e,i){var n=i(205),s=i(83);t.exports=function(t,e){return!(t.left>e.right||t.righte.bottom||t.bottome.right||t.righte.bottom||t.bottom0||(c=s(e),(d=n(t,c,!0)).length>0)}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x1,y:t.y1}),e.push({x:t.x2,y:t.y2}),e.push({x:t.x3,y:t.y3}),e}},function(t,e){t.exports=function(t,e,i){void 0===i&&(i=1);var n=e.x1,s=e.y1,r=e.x2,o=e.y2,a=t.x,h=t.y,l=(r-n)*(r-n)+(o-s)*(o-s);if(0===l)return!1;var u=((a-n)*(r-n)+(h-s)*(o-s))/l;if(u<0)return Math.sqrt((n-a)*(n-a)+(s-h)*(s-h))<=i;if(u>=0&&u<=1){var c=((s-h)*(r-n)-(n-a)*(o-s))/l;return Math.abs(c)*Math.sqrt(l)<=i}return Math.sqrt((r-a)*(r-a)+(o-h)*(o-h))<=i}},function(t,e,i){var n=i(13),s=i(58),r=i(85);t.exports=function(t){var e=r(t)-n.TAU;return s(e,-Math.PI,Math.PI)}},function(t,e){t.exports=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)}},function(t,e){t.exports=function(t){return t.x*t.x+t.y*t.y}},function(t,e,i){var n=i(11);n.Area=i(1147),n.Ceil=i(1148),n.CeilAll=i(1149),n.CenterOn=i(165),n.Clone=i(1150),n.Contains=i(47),n.ContainsPoint=i(1151),n.ContainsRect=i(437),n.CopyFrom=i(1152),n.Decompose=i(426),n.Equals=i(1153),n.FitInside=i(1154),n.FitOutside=i(1155),n.Floor=i(1156),n.FloorAll=i(1157),n.FromPoints=i(174),n.GetAspectRatio=i(209),n.GetCenter=i(1158),n.GetPoint=i(149),n.GetPoints=i(271),n.GetSize=i(1159),n.Inflate=i(1160),n.Intersection=i(1161),n.MarchingAnts=i(282),n.MergePoints=i(1162),n.MergeRect=i(1163),n.MergeXY=i(1164),n.Offset=i(1165),n.OffsetPoint=i(1166),n.Overlaps=i(1167),n.Perimeter=i(112),n.PerimeterPoint=i(1168),n.Random=i(152),n.RandomOutside=i(1169),n.SameDimensions=i(1170),n.Scale=i(1171),n.Union=i(386),t.exports=n},function(t,e){t.exports=function(t,e){return!(e.width*e.height>t.width*t.height)&&e.x>t.x&&e.xt.x&&e.rightt.y&&e.yt.y&&e.bottom=this.threshold?this.pressed||(this.pressed=!0,this.events.emit(s.BUTTON_DOWN,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_DOWN,i,t,this)):this.pressed&&(this.pressed=!1,this.events.emit(s.BUTTON_UP,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_UP,i,t,this))},destroy:function(){this.pad=null,this.events=null}});t.exports=r},function(t,e,i){var n=i(442),s=i(443),r=i(0),o=i(9),a=i(3),h=new r({Extends:o,initialize:function(t,e){o.call(this),this.manager=t,this.pad=e,this.id=e.id,this.index=e.index;for(var i=[],r=0;r=2&&(this.leftStick.set(r[0].getValue(),r[1].getValue()),s>=4&&this.rightStick.set(r[2].getValue(),r[3].getValue()))},destroy:function(){var t;for(this.removeAllListeners(),this.manager=null,this.pad=null,t=0;t=r;for(i=0;i=r;)this._elapsed-=r,this.step(s)}},step:function(t){var e,i,n=this.bodies.entries,s=n.length;for(e=0;e0){var l=this.tree,u=this.staticTree;for(n=(i=h.entries).length,t=0;t-1&&p>g&&(t.velocity.normalize().scale(g),p=g),t.speed=p},separate:function(t,e,i,n,s){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(n,t.gameObject,e.gameObject))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,s);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h=o.center;if((h.ya.bottom)&&(h.xa.right))return this.separateCircle(t,e,s)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)r.right&&(s=h(o.x,o.y,r.right,r.y)-o.radius):o.y>r.bottom&&(o.xr.right&&(s=h(o.x,o.y,r.right,r.bottom)-o.radius)),s*=-1}else s=t.halfWidth+e.halfWidth-h(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s&&(t.onOverlap||e.onOverlap)&&this.emit(u.OVERLAP,t.gameObject,e.gameObject,t,e),0!==s;var a=t.center.x-e.center.x,l=t.center.y-e.center.y,c=Math.sqrt(Math.pow(a,2)+Math.pow(l,2)),d=(e.center.x-t.center.x)/c||0,f=(e.center.y-t.center.y)/c||0,v=2*(t.velocity.x*d+t.velocity.y*f-e.velocity.x*d-e.velocity.y*f)/(t.mass+e.mass);t.immovable||(t.velocity.x=t.velocity.x-v*t.mass*d,t.velocity.y=t.velocity.y-v*t.mass*f),e.immovable||(e.velocity.x=e.velocity.x+v*e.mass*d,e.velocity.y=e.velocity.y+v*e.mass*f);var m=e.velocity.x-t.velocity.x,y=e.velocity.y-t.velocity.y,x=Math.atan2(y,m),T=this._frameTime;return t.immovable||e.immovable||(s/=2),t.immovable||(t.x+=t.velocity.x*T-s*Math.cos(x),t.y+=t.velocity.y*T-s*Math.sin(x)),e.immovable||(e.x+=e.velocity.x*T+s*Math.cos(x),e.y+=e.velocity.y*T+s*Math.sin(x)),t.velocity.x*=t.bounce.x,t.velocity.y*=t.bounce.y,e.velocity.x*=e.bounce.x,e.velocity.y*=e.bounce.y,(t.onCollide||e.onCollide)&&this.emit(u.COLLIDE,t.gameObject,e.gameObject,t,e),!0},intersects:function(t,e){return t!==e&&(t.isCircle||e.isCircle?t.isCircle?e.isCircle?h(t.center.x,t.center.y,e.center.x,e.center.y)<=t.halfWidth+e.halfWidth:this.circleBodyIntersects(t,e):this.circleBodyIntersects(e,t):!(t.right<=e.position.x||t.bottom<=e.position.y||t.position.x>=e.right||t.position.y>=e.bottom))},circleBodyIntersects:function(t,e){var i=s(t.center.x,e.left,e.right),n=s(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},overlap:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!0)},collide:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!1)},collideObjects:function(t,e,i,n,s,r){var o,a;t.isParent&&void 0===t.physicsType&&(t=t.children.entries),e&&e.isParent&&void 0===e.physicsType&&(e=e.children.entries);var h=Array.isArray(t),l=Array.isArray(e);if(this._total=0,h||l)if(!h&&l)for(o=0;o0},collideHandler:function(t,e,i,n,s,r){if(void 0===e&&t.isParent)return this.collideGroupVsGroup(t,t,i,n,s,r);if(!t||!e)return!1;if(t.body){if(e.body)return this.collideSpriteVsSprite(t,e,i,n,s,r);if(e.isParent)return this.collideSpriteVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideSpriteVsTilemapLayer(t,e,i,n,s,r)}else if(t.isParent){if(e.body)return this.collideSpriteVsGroup(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideGroupVsTilemapLayer(t,e,i,n,s,r)}else if(t.isTilemap){if(e.body)return this.collideSpriteVsTilemapLayer(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsTilemapLayer(e,t,i,n,s,r)}},collideSpriteVsSprite:function(t,e,i,n,s,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,n,s,r)&&(i&&i.call(s,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,n,s,r){var o,h,l,u=t.body;if(0!==e.length&&u&&u.enable)if(this.useTree){var c=this.treeMinMax;c.minX=u.left,c.minY=u.top,c.maxX=u.right,c.maxY=u.bottom;var d=e.physicsType===a.DYNAMIC_BODY?this.tree.search(c):this.staticTree.search(c);for(h=d.length,o=0;oc.baseTileWidth){var d=(c.tileWidth-c.baseTileWidth)*e.scaleX;a-=d,l+=d}c.tileHeight>c.baseTileHeight&&(u+=(c.tileHeight-c.baseTileHeight)*e.scaleY);var f=e.getTilesWithinWorldXY(a,h,l,u);return 0!==f.length&&this.collideSpriteVsTilesHandler(t,f,i,n,s,r,!0)},collideSpriteVsTilesHandler:function(t,e,i,n,s,r,o){for(var a,h,l=t.body,c={left:0,right:0,top:0,bottom:0},d=!1,f=0;f0&&t>i&&(t=i)),0!==n&&0!==e&&(e<0&&e<-n?e=-n:e>0&&e>n&&(e=n)),this.gameObject.x+=t,this.gameObject.y+=e}t<0?this.facing=s.FACING_LEFT:t>0&&(this.facing=s.FACING_RIGHT),e<0?this.facing=s.FACING_UP:e>0&&(this.facing=s.FACING_DOWN),this.allowRotation&&(this.gameObject.angle+=this.deltaZ()),this._tx=t,this._ty=e},setBoundsRectangle:function(t){return this.customBoundsRectangle=t||this.world.bounds,this},checkWorldBounds:function(){var t=this.position,e=this.customBoundsRectangle,i=this.world.checkCollision,n=this.worldBounce?-this.worldBounce.x:-this.bounce.x,s=this.worldBounce?-this.worldBounce.y:-this.bounce.y,r=!1;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=n,this.blocked.right=!0,r=!0),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=s,this.blocked.down=!0,r=!0),r&&(this.blocked.none=!1),r},setOffset:function(t,e){return void 0===e&&(e=t),this.offset.set(t,e),this.updateCenter(),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter(),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.offset.set(s-this.halfWidth,r-this.halfHeight)}return this.isCircle=!1,this.radius=0,this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter()):this.isCircle=!1,this},reset:function(t,e){this.stop();var i=this.gameObject;i.setPosition(t,e),i.getTopLeft?i.getTopLeft(this.position):this.position.set(t,e),this.prev.copy(this.position),this.prevFrame.copy(this.position),this.rotation=i.angle,this.preRotation=i.angle,this.updateBounds(),this.updateCenter()},stop:function(){return this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?this.radius>0&&t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom&&(this.center.x-t)*(this.center.x-t)+(this.center.y-e)*(this.center.y-e)<=this.radius*this.radius:h(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this._dx>0?this._dx:-this._dx},deltaAbsY:function(){return this._dy>0?this._dy:-this._dy},deltaX:function(){return this._dx},deltaY:function(){return this._dy},deltaXFinal:function(){return this._tx},deltaYFinal:function(){return this._ty},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.enable=!1,this.world&&this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor),this.isCircle?t.strokeCircle(i,n,this.width/2):(this.checkCollision.up&&t.lineBetween(e.x,e.y,e.x+this.width,e.y),this.checkCollision.right&&t.lineBetween(e.x+this.width,e.y,e.x+this.width,e.y+this.height),this.checkCollision.down&&t.lineBetween(e.x,e.y+this.height,e.x+this.width,e.y+this.height),this.checkCollision.left&&t.lineBetween(e.x,e.y,e.x,e.y+this.height))),this.debugShowVelocity&&(t.lineStyle(t.defaultStrokeWidth,this.world.defaults.velocityDebugColor,1),t.lineBetween(i,n,i+this.velocity.x/2,n+this.velocity.y/2))},willDrawDebug:function(){return this.debugShowBody||this.debugShowVelocity},setCollideWorldBounds:function(t,e,i){void 0===t&&(t=!0),this.collideWorldBounds=t;var n=void 0!==e,s=void 0!==i;return(n||s)&&(this.worldBounce||(this.worldBounce=new l),n&&(this.worldBounce.x=e),s&&(this.worldBounce.y=i)),this},setVelocity:function(t,e){return this.velocity.set(t,e),t=this.velocity.x,e=this.velocity.y,this.speed=Math.sqrt(t*t+e*e),this},setVelocityX:function(t){this.velocity.x=t;var e=t,i=this.velocity.y;return this.speed=Math.sqrt(e*e+i*i),this},setVelocityY:function(t){this.velocity.y=t;var e=this.velocity.x,i=t;return this.speed=Math.sqrt(e*e+i*i),this},setMaxVelocity:function(t,e){return this.maxVelocity.set(t,e),this},setMaxSpeed:function(t){return this.maxSpeed=t,this},setBounce:function(t,e){return this.bounce.set(t,e),this},setBounceX:function(t){return this.bounce.x=t,this},setBounceY:function(t){return this.bounce.y=t,this},setAcceleration:function(t,e){return this.acceleration.set(t,e),this},setAccelerationX:function(t){return this.acceleration.x=t,this},setAccelerationY:function(t){return this.acceleration.y=t,this},setAllowDrag:function(t){return void 0===t&&(t=!0),this.allowDrag=t,this},setAllowGravity:function(t){return void 0===t&&(t=!0),this.allowGravity=t,this},setAllowRotation:function(t){return void 0===t&&(t=!0),this.allowRotation=t,this},setDrag:function(t,e){return this.drag.set(t,e),this},setDragX:function(t){return this.drag.x=t,this},setDragY:function(t){return this.drag.y=t,this},setGravity:function(t,e){return this.gravity.set(t,e),this},setGravityX:function(t){return this.gravity.x=t,this},setGravityY:function(t){return this.gravity.y=t,this},setFriction:function(t,e){return this.friction.set(t,e),this},setFrictionX:function(t){return this.friction.x=t,this},setFrictionY:function(t){return this.friction.y=t,this},setAngularVelocity:function(t){return this.angularVelocity=t,this},setAngularAcceleration:function(t){return this.angularAcceleration=t,this},setAngularDrag:function(t){return this.angularDrag=t,this},setMass:function(t){return this.mass=t,this},setImmovable:function(t){return void 0===t&&(t=!0),this.immovable=t,this},setEnable:function(t){return void 0===t&&(t=!0),this.enable=t,this},x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=u},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o){this.world=t,this.name="",this.active=!0,this.overlapOnly=e,this.object1=i,this.object2=n,this.collideCallback=s,this.processCallback=r,this.callbackContext=o},setName:function(t){return this.name=t,this},update:function(){this.world.collideObjects(this.object1,this.object2,this.collideCallback,this.processCallback,this.callbackContext,this.overlapOnly)},destroy:function(){this.world.removeCollider(this),this.active=!1,this.world=null,this.object1=null,this.object2=null,this.collideCallback=null,this.processCallback=null,this.callbackContext=null}});t.exports=n},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsX()+e.deltaAbsX()+s;return 0===t._dx&&0===e._dx?(t.embedded=!0,e.embedded=!0):t._dx>e._dx?(r=t.right-e.x)>o&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?r=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.right=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.left=!0)):t._dxo&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?r=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.left=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.right=!0))),t.overlapX=r,e.overlapX=r,r}},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsY()+e.deltaAbsY()+s;return 0===t._dy&&0===e._dy?(t.embedded=!0,e.embedded=!0):t._dy>e._dy?(r=t.bottom-e.y)>o&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?r=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.down=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.up=!0)):t._dyo&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?r=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.up=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.down=!0))),t.overlapY=r,e.overlapY=r,r}},function(t,e,i){var n=i(383);function s(t){if(!(this instanceof s))return new s(t,[".left",".top",".right",".bottom"]);this._maxEntries=Math.max(4,t||9),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}function r(t,e,i){if(!i)return e.indexOf(t);for(var n=0;n=t.minX&&e.maxY>=t.minY}function g(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function v(t,e,i,s,r){for(var o,a=[e,i];a.length;)(i=a.pop())-(e=a.pop())<=s||(o=e+Math.ceil((i-e)/s/2)*s,n(t,o,e,i,r),a.push(e,o,o,i))}s.prototype={all:function(){return this._all(this.data,[])},search:function(t){var e=this.data,i=[],n=this.toBBox;if(!p(t,e))return i;for(var s,r,o,a,h=[];e;){for(s=0,r=e.children.length;s=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)},_split:function(t,e){var i=t[e],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);var r=this._chooseSplitIndex(i,s,n),a=g(i.children.splice(r,i.children.length-r));a.height=i.height,a.leaf=i.leaf,o(i,this.toBBox),o(a,this.toBBox),e?t[e-1].children.push(a):this._splitRoot(i,a)},_splitRoot:function(t,e){this.data=g([t,e]),this.data.height=t.height+1,this.data.leaf=!1,o(this.data,this.toBBox)},_chooseSplitIndex:function(t,e,i){var n,s,r,o,h,l,u,d,f,p,g,v,m,y;for(l=u=1/0,n=e;n<=i-e;n++)s=a(t,0,n,this.toBBox),r=a(t,n,i,this.toBBox),f=s,p=r,void 0,void 0,void 0,void 0,g=Math.max(f.minX,p.minX),v=Math.max(f.minY,p.minY),m=Math.min(f.maxX,p.maxX),y=Math.min(f.maxY,p.maxY),o=Math.max(0,m-g)*Math.max(0,y-v),h=c(s)+c(r),o=e;s--)r=t.children[s],h(u,t.leaf?o(r):r),c+=d(u);return c},_adjustParentBBoxes:function(t,e,i){for(var n=i;n>=0;n--)h(e[n],t)},_condense:function(t){for(var e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children).splice(e.indexOf(t[i]),1):this.clear():o(t[i],this.toBBox)},compareMinX:function(t,e){return t.left-e.left},compareMinY:function(t,e){return t.top-e.top},toBBox:function(t){return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}},t.exports=s},function(t,e){t.exports=function(t,e){return!(e.right<=t.left||e.bottom<=t.top||e.position.x>=t.right||e.position.y>=t.bottom)}},function(t,e,i){var n=i(55),s=i(0),r=i(50),o=i(47),a=i(3),h=new s({initialize:function(t,e){var i=e.width?e.width:64,n=e.height?e.height:64;this.world=t,this.gameObject=e,this.debugShowBody=t.defaults.debugShowStaticBody,this.debugBodyColor=t.defaults.staticBodyDebugColor,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new a,this.position=new a(e.x-e.displayOriginX,e.y-e.displayOriginY),this.width=i,this.height=n,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center=new a(e.x+this.halfWidth,e.y+this.halfHeight),this.velocity=a.ZERO,this.allowGravity=!1,this.gravity=a.ZERO,this.bounce=a.ZERO,this.onWorldBounds=!1,this.onCollide=!1,this.onOverlap=!1,this.mass=1,this.immovable=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.physicsType=r.STATIC_BODY,this._dx=0,this._dy=0},setGameObject:function(t,e){return t&&t!==this.gameObject&&(this.gameObject.body=null,t.body=this,this.gameObject=t),e&&this.updateFromGameObject(),this},updateFromGameObject:function(){this.world.staticTree.remove(this);var t=this.gameObject;return t.getTopLeft(this.position),this.width=t.displayWidth,this.height=t.displayHeight,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.world.staticTree.insert(this),this},setOffset:function(t,e){return void 0===e&&(e=t),this.world.staticTree.remove(this),this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(t,e),this.position.x+=this.offset.x,this.position.y+=this.offset.y,this.updateCenter(),this.world.staticTree.insert(this),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.world.staticTree.remove(this),this.width=t,this.height=e,this.halfWidth=Math.floor(t/2),this.halfHeight=Math.floor(e/2),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(s-this.halfWidth,r-this.halfHeight),this.position.x+=this.offset.x,this.position.y+=this.offset.y}return this.updateCenter(),this.isCircle=!1,this.radius=0,this.world.staticTree.insert(this),this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.world.staticTree.remove(this),this.isCircle=!0,this.radius=t,this.width=2*t,this.height=2*t,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter(),this.world.staticTree.insert(this)):this.isCircle=!1,this},updateCenter:function(){this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(t,e){var i=this.gameObject;void 0===t&&(t=i.x),void 0===e&&(e=i.y),this.world.staticTree.remove(this),i.setPosition(t,e),i.getTopLeft(this.position),this.updateCenter(),this.world.staticTree.insert(this)},stop:function(){return this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?n(this,t,e):o(this,t,e)},postUpdate:function(){},deltaAbsX:function(){return 0},deltaAbsY:function(){return 0},deltaX:function(){return 0},deltaY:function(){return 0},deltaZ:function(){return 0},destroy:function(){this.enable=!1,this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor,1),this.isCircle?t.strokeCircle(i,n,this.width/2):t.strokeRect(e.x,e.y,this.width,this.height))},willDrawDebug:function(){return this.debugShowBody},setMass:function(t){return t<=0&&(t=.1),this.mass=t,this},x:{get:function(){return this.position.x},set:function(t){this.world.staticTree.remove(this),this.position.x=t,this.world.staticTree.insert(this)}},y:{get:function(){return this.position.y},set:function(t){this.world.staticTree.remove(this),this.position.y=t,this.world.staticTree.insert(this)}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=h},,,,function(t,e,i){var n=new(i(0))({initialize:function(t){this.pluginManager=t,this.game=t.game},init:function(){},start:function(){},stop:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=n},function(t,e,i){var n=i(24);t.exports=function(t,e,i,s,r,o,a){for(var h=n(i,s,r,o,null,a),l=0;l-1}return!1}},function(t,e,i){var n=i(74),s=i(103),r=i(217);t.exports=function(t,e,i,o,a){if(void 0===i&&(i=!1),void 0===o&&(o=!0),!s(t,e,a))return null;var h=a.data[e][t];return h?(a.data[e][t]=i?null:new n(a,-1,t,e,h.width,h.height),o&&h&&h.collides&&r(t,e,a),h):null}},function(t,e,i){var n=i(31),s=i(220),r=i(473),o=i(474),a=i(485);t.exports=function(t,e,i,h,l,u){var c;switch(e){case n.ARRAY_2D:c=s(t,i,h,l,u);break;case n.CSV:c=r(t,i,h,l,u);break;case n.TILED_JSON:c=o(t,i,u);break;case n.WELTMEISTER:c=a(t,i,u);break;default:console.warn("Unrecognized tilemap data format: "+e),c=null}return c}},function(t,e,i){var n=i(31),s=i(220);t.exports=function(t,e,i,r,o){var a=e.trim().split("\n").map(function(t){return t.split(",")}),h=s(t,a,i,r,o);return h.format=n.CSV,h}},function(t,e,i){var n=i(31),s=i(105),r=i(475),o=i(477),a=i(478),h=i(481),l=i(483),u=i(484);t.exports=function(t,e,i){if("orthogonal"!==e.orientation)return console.warn("Only orthogonal map types are supported in this version of Phaser"),null;var c=new s({width:e.width,height:e.height,name:t,tileWidth:e.tilewidth,tileHeight:e.tileheight,orientation:e.orientation,format:n.TILED_JSON,version:e.version,properties:e.properties,renderOrder:e.renderorder,infinite:e.infinite});c.layers=r(e,i),c.images=o(e);var d=a(e);return c.tilesets=d.tilesets,c.imageCollections=d.imageCollections,c.objects=h(e),c.tiles=l(c),u(c),c}},function(t,e,i){var n=i(476),s=i(2),r=i(104),o=i(221),a=i(74),h=i(222);t.exports=function(t,e){for(var i=s(t,"infinite",!1),l=[],u=[],c=h(t);c.i0;)if(c.i>=c.layers.length){if(u.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}c=u.pop()}else{var d=c.layers[c.i];if(c.i++,"tilelayer"===d.type)if(d.compression)console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+d.name+"'");else{if(d.encoding&&"base64"===d.encoding){if(d.chunks)for(var f=0;f0?((v=new a(p,g.gid,P,R,t.tilewidth,t.tileheight)).rotation=g.rotation,v.flipX=g.flipped,y[R][P]=v):(m=e?null:new a(p,-1,P,R,t.tilewidth,t.tileheight),y[R][P]=m),++x===b.width&&(C++,x=0)}}else{p=new r({name:c.name+d.name,x:c.x+s(d,"offsetx",0)+d.x,y:c.y+s(d,"offsety",0)+d.y,width:d.width,height:d.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,alpha:c.opacity*d.opacity,visible:c.visible&&d.visible,properties:s(d,"properties",{})});for(var L=[],D=0,F=d.data.length;D0?((v=new a(p,g.gid,x,y.length,t.tilewidth,t.tileheight)).rotation=g.rotation,v.flipX=g.flipped,L.push(v)):(m=e?null:new a(p,-1,x,y.length,t.tilewidth,t.tileheight),L.push(m)),++x===d.width&&(y.push(L),x=0,L=[])}p.data=y,l.push(p)}else if("group"===d.type){var k=h(t,d,c);u.push(c),c=k}}return l}},function(t,e){t.exports=function(t){for(var e=window.atob(t),i=e.length,n=new Array(i/4),s=0;s>>0;return n}},function(t,e,i){var n=i(2),s=i(222);t.exports=function(t){for(var e=[],i=[],r=s(t);r.i0;)if(r.i>=r.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}r=i.pop()}else{var o=r.layers[r.i];if(r.i++,"imagelayer"===o.type){var a=n(o,"offsetx",0)+n(o,"startx",0),h=n(o,"offsety",0)+n(o,"starty",0);e.push({name:r.name+o.name,image:o.image,x:r.x+a+o.x,y:r.y+h+o.y,alpha:r.opacity*o.opacity,visible:r.visible&&o.visible,properties:n(o,"properties",{})})}else if("group"===o.type){var l=s(t,o,r);i.push(r),r=l}}return e}},function(t,e,i){var n=i(141),s=i(479),r=i(223);t.exports=function(t){for(var e,i=[],o=[],a=null,h=0;h1){if(Array.isArray(l.tiles)){for(var c={},d={},f=0;f=this.firstgid&&t0;)if(a.i>=a.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}a=i.pop()}else{var h=a.layers[a.i];if(a.i++,h.opacity*=a.opacity,h.visible=a.visible&&h.visible,"objectgroup"===h.type){h.name=a.name+h.name;for(var l=a.x+n(h,"startx",0)+n(h,"offsetx",0),u=a.y+n(h,"starty",0)+n(h,"offsety",0),c=[],d=0;da&&(a=e.layer[l].width),e.layer[l].height>h&&(h=e.layer[l].height);var u=new s({width:a,height:h,name:t,tileWidth:e.layer[0].tilesize,tileHeight:e.layer[0].tilesize,format:n.WELTMEISTER});return u.layers=r(e,i),u.tilesets=o(e),u}},function(t,e,i){var n=i(104),s=i(74);t.exports=function(t,e){for(var i=[],r=0;r-1?new s(a,f,c,u,o.tilesize,o.tilesize):e?null:new s(a,-1,c,u,o.tilesize,o.tilesize),h.push(d)}l.push(h),h=[]}a.data=l,i.push(a)}return i}},function(t,e,i){var n=i(141);t.exports=function(t){for(var e=[],i=[],s=0;s-1&&(this.renderOrder=t),this},addTilesetImage:function(t,e,i,n,s,r,o){if(void 0===t)return null;if(void 0!==e&&null!==e||(e=t),!this.scene.sys.textures.exists(e))return console.warn("Invalid Tileset Image: "+e),null;var h=this.scene.sys.textures.get(e),l=this.getTilesetIndex(t);if(null===l&&this.format===a.TILED_JSON)return console.warn("No data found for Tileset: "+t),null;var u=this.tilesets[l];return u?(u.setTileSize(i,n),u.setSpacing(s,r),u.setImage(h),u):(void 0===i&&(i=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o=0),(u=new p(t,o,i,n,s,r)).setImage(h),this.tilesets.push(u),u)},convertLayerToStatic:function(t){if(null===(t=this.getLayer(t)))return null;var e=t.tilemapLayer;if(!(e&&e instanceof r))return null;var i=new c(e.scene,e.tilemap,e.layerIndex,e.tileset,e.x,e.y);return this.scene.sys.displayList.add(i),e.destroy(),i},copy:function(t,e,i,n,s,r,o,a){return a=this.getLayer(a),this._isStaticCall(a,"copy")?this:null!==a?(f.Copy(t,e,i,n,s,r,o,a),this):null},createBlankDynamicLayer:function(t,e,i,n,s,o,a,l){if(void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.width),void 0===o&&(o=this.height),void 0===a&&(a=this.tileWidth),void 0===l&&(l=this.tileHeight),null!==this.getLayerIndex(t))return console.warn("Invalid Tilemap Layer ID: "+t),null;for(var u,c=new h({name:t,tileWidth:a,tileHeight:l,width:s,height:o}),f=0;f-1&&this.putTileAt(e,r.x,r.y,i,r.tilemapLayer)}return n},removeTileAt:function(t,e,i,n,s){return s=this.getLayer(s),this._isStaticCall(s,"removeTileAt")?null:null===s?null:f.RemoveTileAt(t,e,i,n,s)},removeTileAtWorldXY:function(t,e,i,n,s,r){return r=this.getLayer(r),this._isStaticCall(r,"removeTileAtWorldXY")?null:null===r?null:f.RemoveTileAtWorldXY(t,e,i,n,s,r)},renderDebug:function(t,e,i){return null===(i=this.getLayer(i))?null:(f.RenderDebug(t,e,i),this)},renderDebugFull:function(t,e){for(var i=this.layers,n=0;n=0&&t<4&&(this._renderOrder=t),this},calculateFacesAt:function(t,e){return a.CalculateFacesAt(t,e,this.layer),this},calculateFacesWithin:function(t,e,i,n){return a.CalculateFacesWithin(t,e,i,n,this.layer),this},createFromTiles:function(t,e,i,n,s){return a.CreateFromTiles(t,e,i,n,s,this.layer)},cull:function(t){return this.cullCallback(this.layer,t,this.culledTiles,this._renderOrder)},copy:function(t,e,i,n,s,r,o){return a.Copy(t,e,i,n,s,r,o,this.layer),this},destroy:function(t){void 0===t&&(t=!0),this.tilemap&&(this.layer.tilemapLayer===this&&(this.layer.tilemapLayer=void 0),t&&this.tilemap.removeLayer(this),this.tilemap=void 0,this.layer=void 0,this.culledTiles.length=0,this.cullCallback=null,this.gidMap=[],this.tileset=[],o.prototype.destroy.call(this))},fill:function(t,e,i,n,s,r){return a.Fill(t,e,i,n,s,r,this.layer),this},filterTiles:function(t,e,i,n,s,r,o){return a.FilterTiles(t,e,i,n,s,r,o,this.layer)},findByIndex:function(t,e,i){return a.FindByIndex(t,e,i,this.layer)},findTile:function(t,e,i,n,s,r,o){return a.FindTile(t,e,i,n,s,r,o,this.layer)},forEachTile:function(t,e,i,n,s,r,o){return a.ForEachTile(t,e,i,n,s,r,o,this.layer),this},getTileAt:function(t,e,i){return a.GetTileAt(t,e,i,this.layer)},getTileAtWorldXY:function(t,e,i,n){return a.GetTileAtWorldXY(t,e,i,n,this.layer)},getTilesWithin:function(t,e,i,n,s){return a.GetTilesWithin(t,e,i,n,s,this.layer)},getTilesWithinShape:function(t,e,i){return a.GetTilesWithinShape(t,e,i,this.layer)},getTilesWithinWorldXY:function(t,e,i,n,s,r){return a.GetTilesWithinWorldXY(t,e,i,n,s,r,this.layer)},hasTileAt:function(t,e){return a.HasTileAt(t,e,this.layer)},hasTileAtWorldXY:function(t,e,i){return a.HasTileAtWorldXY(t,e,i,this.layer)},putTileAt:function(t,e,i,n){return a.PutTileAt(t,e,i,n,this.layer)},putTileAtWorldXY:function(t,e,i,n,s){return a.PutTileAtWorldXY(t,e,i,n,s,this.layer)},putTilesAt:function(t,e,i,n){return a.PutTilesAt(t,e,i,n,this.layer),this},randomize:function(t,e,i,n,s){return a.Randomize(t,e,i,n,s,this.layer),this},removeTileAt:function(t,e,i,n){return a.RemoveTileAt(t,e,i,n,this.layer)},removeTileAtWorldXY:function(t,e,i,n,s){return a.RemoveTileAtWorldXY(t,e,i,n,s,this.layer)},renderDebug:function(t,e){return a.RenderDebug(t,e,this.layer),this},replaceByIndex:function(t,e,i,n,s,r){return a.ReplaceByIndex(t,e,i,n,s,r,this.layer),this},setSkipCull:function(t){return void 0===t&&(t=!0),this.skipCull=t,this},setCullPadding:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=1),this.cullPaddingX=t,this.cullPaddingY=e,this},setCollision:function(t,e,i,n){return a.SetCollision(t,e,i,this.layer,n),this},setCollisionBetween:function(t,e,i,n){return a.SetCollisionBetween(t,e,i,n,this.layer),this},setCollisionByProperty:function(t,e,i){return a.SetCollisionByProperty(t,e,i,this.layer),this},setCollisionByExclusion:function(t,e,i){return a.SetCollisionByExclusion(t,e,i,this.layer),this},setCollisionFromCollisionGroup:function(t,e){return a.SetCollisionFromCollisionGroup(t,e,this.layer),this},setTileIndexCallback:function(t,e,i){return a.SetTileIndexCallback(t,e,i,this.layer),this},setTileLocationCallback:function(t,e,i,n,s,r){return a.SetTileLocationCallback(t,e,i,n,s,r,this.layer),this},shuffle:function(t,e,i,n){return a.Shuffle(t,e,i,n,this.layer),this},swapByIndex:function(t,e,i,n,s,r){return a.SwapByIndex(t,e,i,n,s,r,this.layer),this},tileToWorldX:function(t,e){return a.TileToWorldX(t,e,this.layer)},tileToWorldY:function(t,e){return a.TileToWorldY(t,e,this.layer)},tileToWorldXY:function(t,e,i,n){return a.TileToWorldXY(t,e,i,n,this.layer)},weightedRandomize:function(t,e,i,n,s){return a.WeightedRandomize(t,e,i,n,s,this.layer),this},worldToTileX:function(t,e,i){return a.WorldToTileX(t,e,i,this.layer)},worldToTileY:function(t,e,i){return a.WorldToTileY(t,e,i,this.layer)},worldToTileXY:function(t,e,i,n,s){return a.WorldToTileXY(t,e,i,n,s,this.layer)}});t.exports=h},function(t,e,i){var n=i(0),s=i(12),r=i(18),o=i(14),a=i(1336),h=i(137),l=i(32),u=i(10),c=new n({Extends:o,Mixins:[s.Alpha,s.BlendMode,s.ComputedSize,s.Depth,s.Flip,s.GetBounds,s.Origin,s.Pipeline,s.Transform,s.Visible,s.ScrollFactor,a],initialize:function(t,e,i,n,s,a){o.call(this,t,"StaticTilemapLayer"),this.isTilemap=!0,this.tilemap=e,this.layerIndex=i,this.layer=e.layers[i],this.layer.tilemapLayer=this,this.tileset=[],this.culledTiles=[],this.skipCull=!1,this.tilesDrawn=0,this.tilesTotal=this.layer.width*this.layer.height,this.cullPaddingX=1,this.cullPaddingY=1,this.cullCallback=h.CullTiles,this.renderer=t.sys.game.renderer,this.vertexBuffer=[],this.bufferData=[],this.vertexViewF32=[],this.vertexViewU32=[],this.dirty=[],this.vertexCount=[],this._renderOrder=0,this._tempMatrix=new l,this.gidMap=[],this.setTilesets(n),this.setAlpha(this.layer.alpha),this.setPosition(s,a),this.setOrigin(),this.setSize(e.tileWidth*this.layer.width,e.tileHeight*this.layer.height),this.updateVBOData(),this.initPipeline("TextureTintPipeline"),t.sys.game.events.on(r.CONTEXT_RESTORED,function(){this.updateVBOData()},this)},setTilesets:function(t){var e=[],i=[],n=this.tilemap;Array.isArray(t)||(t=[t]);for(var s=0;sv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(1===p)for(o=0;o=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(2===p)for(o=u-1;o>=0;o--)for(a=0;av||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(3===p)for(o=u-1;o>=0;o--)for(a=l-1;a>=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));this.dirty[e]=!1,null===m?(m=i.createVertexBuffer(y,n.STATIC_DRAW),this.vertexBuffer[e]=m):(i.setVertexBuffer(m),n.bufferSubData(n.ARRAY_BUFFER,0,y))}return this},batchTile:function(t,e,i,n,s,r,o){var a=i.getTileTextureCoordinates(e.index);if(!a)return t;var h=i.tileWidth,l=i.tileHeight,c=h/2,d=l/2,f=a.x/n,p=a.y/s,g=(a.x+h)/n,v=(a.y+l)/s,m=this._tempMatrix,y=-c,x=-d;e.flipX&&(h*=-1,y+=i.tileWidth),e.flipY&&(l*=-1,x+=i.tileHeight);var T=y+h,w=x+l;m.applyITRS(c+e.pixelX,d+e.pixelY,e.rotation,1,1);var E=u.getTintAppendFloatAlpha(16777215,r.alpha*this.alpha*e.alpha),_=m.getX(y,x),b=m.getY(y,x),A=m.getX(y,w),S=m.getY(y,w),C=m.getX(T,w),M=m.getY(T,w),O=m.getX(T,x),P=m.getY(T,x);r.roundPixels&&(_=Math.round(_),b=Math.round(b),A=Math.round(A),S=Math.round(S),C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P));var R=this.vertexViewF32[o],L=this.vertexViewU32[o];return R[++t]=_,R[++t]=b,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=E,R[++t]=A,R[++t]=S,R[++t]=f,R[++t]=v,R[++t]=0,L[++t]=E,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=E,R[++t]=_,R[++t]=b,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=E,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=E,R[++t]=O,R[++t]=P,R[++t]=g,R[++t]=p,R[++t]=0,L[++t]=E,this.vertexCount[o]+=6,t},setRenderOrder:function(t){if("string"==typeof t&&(t=["right-down","left-down","right-up","left-up"].indexOf(t)),t>=0&&t<4){this._renderOrder=t;for(var e=0;e0){var t=this.delay+this.delay*this.repeat;return(this.elapsed+this.delay*(this.repeat-this.repeatCount))/t}return this.getProgress()},getRepeatCount:function(){return this.repeatCount},getElapsed:function(){return this.elapsed},getElapsedSeconds:function(){return.001*this.elapsed},remove:function(t){void 0===t&&(t=!1),this.elapsed=this.delay,this.hasDispatched=!t,this.repeatCount=0},destroy:function(){this.callback=void 0,this.callbackScope=void 0,this.args=[]}});t.exports=r},function(t,e,i){var n=i(1345);t.exports=function(t){var e,i=[];if(t.hasOwnProperty("props"))for(e in t.props)"_"!==e.substr(0,1)&&i.push({key:e,value:t.props[e]});else for(e in t)-1===n.indexOf(e)&&"_"!==e.substr(0,1)&&i.push({key:e,value:t[e]});return i}},function(t,e,i){var n=i(6);t.exports=function(t){var e=n(t,"tweens",null);return null===e?[]:("function"==typeof e&&(e=e.call()),Array.isArray(e)||(e=[e]),e)}},function(t,e,i){var n=i(227),s=i(15),r=i(88),o=i(82),a=i(142),h=i(6),l=i(226),u=i(228),c=i(230);t.exports=function(t,e,i){void 0===i&&(i=n);var d=h(e,"from",0),f=h(e,"to",1),p=[{value:d}],g=a(e,"delay",i.delay),v=a(e,"duration",i.duration),m=h(e,"easeParams",i.easeParams),y=o(h(e,"ease",i.ease),m),x=a(e,"hold",i.hold),T=a(e,"repeat",i.repeat),w=a(e,"repeatDelay",i.repeatDelay),E=r(e,"yoyo",i.yoyo),_=[],b=l("value",f),A=c(p[0],0,"value",b.getEnd,b.getStart,b.getActive,y,g,v,E,x,T,w,!1,!1);A.start=d,A.current=d,A.to=f,_.push(A);var S=new u(t,_,p);S.offset=s(e,"offset",null),S.completeDelay=s(e,"completeDelay",0),S.loop=Math.round(s(e,"loop",0)),S.loopDelay=Math.round(s(e,"loopDelay",0)),S.paused=r(e,"paused",!1),S.useFrames=r(e,"useFrames",!1);for(var C=h(e,"callbackScope",S),M=[S,null],O=u.TYPES,P=0;Pb&&(b=C),_[A][S]=C}}}var M=o?n(o):null;return a?function(t,e,n,s){var r,o=0,a=s%m,h=Math.floor(s/m);if(a>=0&&a=0&&h0?Math.floor(v/p.length):h(e,"duration",g.duration),g.delay=h(e,"delay",g.delay),g.easeParams=c(e,"easeParams",g.easeParams),g.ease=a(c(e,"ease",g.ease),g.easeParams),g.hold=h(e,"hold",g.hold),g.repeat=h(e,"repeat",g.repeat),g.repeatDelay=h(e,"repeatDelay",g.repeatDelay),g.yoyo=o(e,"yoyo",g.yoyo),g.flipX=o(e,"flipX",g.flipX),g.flipY=o(e,"flipY",g.flipY);for(var m=0;m0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay},init:function(){return this.calcDuration(),this.progress=0,this.totalProgress=0,!this.paused||(this.state=a.PAUSED,!1)},resetTweens:function(t){for(var e=0;e0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweens(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=a.LOOP_DELAY):(this.state=a.ACTIVE,this.dispatchTimelineEvent(r.TIMELINE_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=a.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=a.PENDING_REMOVE,this.dispatchTimelineEvent(r.TIMELINE_COMPLETE,this.callbacks.onComplete))},update:function(t,e){if(this.state!==a.PAUSED){switch(this.useFrames&&(e=1*this.manager.timeScale),e*=this.timeScale,this.elapsed+=e,this.progress=Math.min(this.elapsed/this.duration,1),this.totalElapsed+=e,this.totalProgress=Math.min(this.totalElapsed/this.totalDuration,1),this.state){case a.ACTIVE:for(var i=this.totalData,n=0;n=this.nextTick&&this.currentAnim.setFrame(this)}},setCurrentFrame:function(t){var e=this.parent;return this.currentFrame=t,e.texture=t.frame.texture,e.frame=t.frame,e.isCropped&&e.frame.updateCropUVs(e._crop,e.flipX,e.flipY),e.setSizeToFrame(),t.frame.customPivot?e.setOrigin(t.frame.pivotX,t.frame.pivotY):e.updateDisplayOrigin(),e},updateFrame:function(t){var e=this.setCurrentFrame(t);if(this.isPlaying){t.setAlpha&&(e.alpha=t.alpha);var i=this.currentAnim;e.emit(r.SPRITE_ANIMATION_KEY_UPDATE+i.key,i,t,e),e.emit(r.SPRITE_ANIMATION_UPDATE,i,t,e),3===this._pendingStop&&this._pendingStopValue===t&&this.currentAnim.completeAnimation(this)}},nextFrame:function(){return this.currentAnim&&this.currentAnim.nextFrame(this),this.parent},previousFrame:function(){return this.currentAnim&&this.currentAnim.previousFrame(this),this.parent},setYoyo:function(t){return void 0===t&&(t=!1),this._yoyo=t,this.parent},getYoyo:function(){return this._yoyo},destroy:function(){this.animationManager.off(r.REMOVE_ANIMATION,this.remove,this),this.animationManager=null,this.parent=null,this.currentAnim=null,this.currentFrame=null}});t.exports=o},function(t,e,i){var n=i(500),s=i(48),r=i(0),o=i(29),a=i(501),h=i(92),l=i(32),u=new r({initialize:function(t){this.game=t,this.type=o.CANVAS,this.drawCount=0,this.width=0,this.height=0,this.config={clearBeforeRender:t.config.clearBeforeRender,backgroundColor:t.config.backgroundColor,resolution:t.config.resolution,antialias:t.config.antialias,roundPixels:t.config.roundPixels},this.gameCanvas=t.canvas;var e={alpha:t.config.transparent,desynchronized:t.config.desynchronized};this.gameContext=this.game.config.context?this.game.config.context:this.gameCanvas.getContext("2d",e),this.currentContext=this.gameContext,this.antialias=t.config.antialias,this.blendModes=a(),this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92},this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.init()},init:function(){this.game.scale.on(h.RESIZE,this.onResize,this);var t=this.game.scale.baseSize;this.resize(t.width,t.height)},onResize:function(t,e){e.width===this.width&&e.height===this.height||this.resize(e.width,e.height)},resize:function(t,e){this.width=t,this.height=e},resetTransform:function(){this.currentContext.setTransform(1,0,0,1,0,0)},setBlendMode:function(t){return this.currentContext.globalCompositeOperation=t,this},setContext:function(t){return this.currentContext=t||this.gameContext,this},setAlpha:function(t){return this.currentContext.globalAlpha=t,this},preRender:function(){var t=this.gameContext,e=this.config,i=this.width,n=this.height;t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),e.clearBeforeRender&&t.clearRect(0,0,i,n),e.transparent||(t.fillStyle=e.backgroundColor.rgba,t.fillRect(0,0,i,n)),t.save(),this.drawCount=0},render:function(t,e,i,n){var r=e.list,o=r.length,a=n._cx,h=n._cy,l=n._cw,u=n._ch,c=n.renderToTexture?n.context:t.sys.context;c.save(),this.game.scene.customViewports&&(c.beginPath(),c.rect(a,h,l,u),c.clip()),this.currentContext=c;var d=n.mask;d&&d.preRenderCanvas(this,null,n._maskCamera),n.transparent||(c.fillStyle=n.backgroundColor.rgba,c.fillRect(a,h,l,u)),c.globalAlpha=n.alpha,c.globalCompositeOperation="source-over",this.drawCount+=r.length,n.renderToTexture&&n.emit(s.PRE_RENDER,n),n.matrix.copyToContext(c);for(var f=0;f=0?y=-(y+d):y<0&&(y=Math.abs(y)-d)),t.flipY&&(x>=0?x=-(x+f):x<0&&(x=Math.abs(x)-f))}var w=1,E=1;t.flipX&&(p||(y+=-e.realWidth+2*v),w=-1),t.flipY&&(p||(x+=-e.realHeight+2*m),E=-1),a.applyITRS(t.x,t.y,t.rotation,t.scaleX*w,t.scaleY*E),o.copyFrom(i.matrix),n?(o.multiplyWithOffset(n,-i.scrollX*t.scrollFactorX,-i.scrollY*t.scrollFactorY),a.e=t.x,a.f=t.y,o.multiply(a,h)):(a.e-=i.scrollX*t.scrollFactorX,a.f-=i.scrollY*t.scrollFactorY,o.multiply(a,h)),r.save(),h.setToContext(r),r.globalCompositeOperation=this.blendModes[t.blendMode],r.globalAlpha=s,r.imageSmoothingEnabled=!(!this.antialias||e.source.scaleMode),r.drawImage(e.source.image,u,c,d,f,y,x,d/g,f/g),r.restore()}},destroy:function(){this.gameCanvas=null,this.gameContext=null,this.game=null}});t.exports=u},function(t,e,i){var n=i(26),s=i(33),r=i(2);t.exports=function(t,e){var i=r(e,"callback"),o=r(e,"type","image/png"),a=r(e,"encoder",.92),h=Math.abs(Math.round(r(e,"x",0))),l=Math.abs(Math.round(r(e,"y",0))),u=r(e,"width",t.width),c=r(e,"height",t.height);if(r(e,"getPixel",!1)){var d=t.getContext("2d").getImageData(h,l,1,1).data;i.call(null,new s(d[0],d[1],d[2],d[3]/255))}else if(0!==h||0!==l||u!==t.width||c!==t.height){var f=n.createWebGL(this,u,c);f.getContext("2d").drawImage(t,h,l,u,c,0,0,u,c);var p=new Image;p.onerror=function(){i.call(null),n.remove(f)},p.onload=function(){i.call(null,p),n.remove(f)},p.src=f.toDataURL(o,a)}else{var g=new Image;g.onerror=function(){i.call(null)},g.onload=function(){i.call(null,g)},g.src=t.toDataURL(o,a)}}},function(t,e,i){var n=i(52),s=i(313);t.exports=function(){var t=[],e=s.supportNewBlendModes,i="source-over";return t[n.NORMAL]=i,t[n.ADD]="lighter",t[n.MULTIPLY]=e?"multiply":i,t[n.SCREEN]=e?"screen":i,t[n.OVERLAY]=e?"overlay":i,t[n.DARKEN]=e?"darken":i,t[n.LIGHTEN]=e?"lighten":i,t[n.COLOR_DODGE]=e?"color-dodge":i,t[n.COLOR_BURN]=e?"color-burn":i,t[n.HARD_LIGHT]=e?"hard-light":i,t[n.SOFT_LIGHT]=e?"soft-light":i,t[n.DIFFERENCE]=e?"difference":i,t[n.EXCLUSION]=e?"exclusion":i,t[n.HUE]=e?"hue":i,t[n.SATURATION]=e?"saturation":i,t[n.COLOR]=e?"color":i,t[n.LUMINOSITY]=e?"luminosity":i,t[n.ERASE]="destination-out",t[n.SOURCE_IN]="source-in",t[n.SOURCE_OUT]="source-out",t[n.SOURCE_ATOP]="source-atop",t[n.DESTINATION_OVER]="destination-over",t[n.DESTINATION_IN]="destination-in",t[n.DESTINATION_OUT]="destination-out",t[n.DESTINATION_ATOP]="destination-atop",t[n.LIGHTER]="lighter",t[n.COPY]="copy",t[n.XOR]="xor",t}},function(t,e,i){var n=i(91),s=i(48),r=i(0),o=i(29),a=i(18),h=i(118),l=i(1),u=i(92),c=i(79),d=i(119),f=i(32),p=i(10),g=i(503),v=i(504),m=i(505),y=i(235),x=new r({initialize:function(t){var e=t.config,i={alpha:e.transparent,desynchronized:e.desynchronized,depth:!1,antialias:e.antialiasGL,premultipliedAlpha:e.premultipliedAlpha,stencil:!0,failIfMajorPerformanceCaveat:e.failIfMajorPerformanceCaveat,powerPreference:e.powerPreference};this.config={clearBeforeRender:e.clearBeforeRender,antialias:e.antialias,backgroundColor:e.backgroundColor,contextCreation:i,resolution:e.resolution,roundPixels:e.roundPixels,maxTextures:e.maxTextures,maxTextureSize:e.maxTextureSize,batchSize:e.batchSize,maxLights:e.maxLights,mipmapFilter:e.mipmapFilter},this.game=t,this.type=o.WEBGL,this.width=0,this.height=0,this.canvas=t.canvas,this.blendModes=[],this.nativeTextures=[],this.contextLost=!1,this.pipelines=null,this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92,isFramebuffer:!1,bufferWidth:0,bufferHeight:0},this.currentActiveTextureUnit=0,this.currentTextures=new Array(16),this.currentFramebuffer=null,this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.currentBlendMode=1/0,this.currentScissorEnabled=!1,this.currentScissor=null,this.scissorStack=[],this.contextLostHandler=l,this.contextRestoredHandler=l,this.gl=null,this.supportedExtensions=null,this.extensions={},this.glFormats=[],this.compression={ETC1:!1,PVRTC:!1,S3TC:!1},this.drawingBufferHeight=0,this.blankTexture=null,this.defaultCamera=new n(0,0,0,0),this._tempMatrix1=new f,this._tempMatrix2=new f,this._tempMatrix3=new f,this._tempMatrix4=new f,this.maskCount=0,this.maskStack=[],this.currentMask={mask:null,camera:null},this.currentCameraMask={mask:null,camera:null},this.glFuncMap=null,this.currentType="",this.newType=!1,this.nextTypeMatch=!1,this.mipmapFilter=null,this.init(this.config)},init:function(t){var e,i=this.game,n=this.canvas,s=t.backgroundColor;if(!(e=i.config.context?i.config.context:n.getContext("webgl",t.contextCreation)||n.getContext("experimental-webgl",t.contextCreation))||e.isContextLost())throw this.contextLost=!0,new Error("WebGL unsupported");this.gl=e;var r=this;this.contextLostHandler=function(t){r.contextLost=!0,r.game.events.emit(a.CONTEXT_LOST,r),t.preventDefault()},this.contextRestoredHandler=function(){r.contextLost=!1,r.init(r.config),r.game.events.emit(a.CONTEXT_RESTORED,r)},n.addEventListener("webglcontextlost",this.contextLostHandler,!1),n.addEventListener("webglcontextrestored",this.contextRestoredHandler,!1),i.context=e;for(var h=0;h<=27;h++)this.blendModes.push({func:[e.ONE,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_ADD});this.blendModes[1].func=[e.ONE,e.DST_ALPHA],this.blendModes[2].func=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA],this.blendModes[3].func=[e.ONE,e.ONE_MINUS_SRC_COLOR],this.blendModes[17]={func:[e.ZERO,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_REVERSE_SUBTRACT},this.glFormats[0]=e.BYTE,this.glFormats[1]=e.SHORT,this.glFormats[2]=e.UNSIGNED_BYTE,this.glFormats[3]=e.UNSIGNED_SHORT,this.glFormats[4]=e.FLOAT,this.glFuncMap={mat2:{func:e.uniformMatrix2fv,length:1,matrix:!0},mat3:{func:e.uniformMatrix3fv,length:1,matrix:!0},mat4:{func:e.uniformMatrix4fv,length:1,matrix:!0},"1f":{func:e.uniform1f,length:1},"1fv":{func:e.uniform1fv,length:1},"1i":{func:e.uniform1i,length:1},"1iv":{func:e.uniform1iv,length:1},"2f":{func:e.uniform2f,length:2},"2fv":{func:e.uniform2fv,length:1},"2i":{func:e.uniform2i,length:2},"2iv":{func:e.uniform2iv,length:1},"3f":{func:e.uniform3f,length:3},"3fv":{func:e.uniform3fv,length:1},"3i":{func:e.uniform3i,length:3},"3iv":{func:e.uniform3iv,length:1},"4f":{func:e.uniform4f,length:4},"4fv":{func:e.uniform4fv,length:1},"4i":{func:e.uniform4i,length:4},"4iv":{func:e.uniform4iv,length:1}};var l=e.getSupportedExtensions();t.maxTextures||(t.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)),t.maxTextureSize||(t.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE));var u="WEBGL_compressed_texture_",c="WEBKIT_"+u;this.compression.ETC1=e.getExtension(u+"etc1")||e.getExtension(c+"etc1"),this.compression.PVRTC=e.getExtension(u+"pvrtc")||e.getExtension(c+"pvrtc"),this.compression.S3TC=e.getExtension(u+"s3tc")||e.getExtension(c+"s3tc"),this.supportedExtensions=l,e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.clearColor(s.redGL,s.greenGL,s.blueGL,s.alphaGL),this.mipmapFilter=e[t.mipmapFilter];for(var f=0;f0&&n>0;if(o&&a){var h=o[0],l=o[1],u=o[2],c=o[3];a=h!==t||l!==e||u!==i||c!==n}a&&(this.flush(),r.scissor(t,s-e-n,i,n))},popScissor:function(){var t=this.scissorStack;t.pop();var e=t[t.length-1];e&&this.setScissor(e[0],e[1],e[2],e[3]),this.currentScissor=e},setPipeline:function(t,e){return this.currentPipeline===t&&this.currentPipeline.vertexBuffer===this.currentVertexBuffer&&this.currentPipeline.program===this.currentProgram||(this.flush(),this.currentPipeline=t,this.currentPipeline.bind()),this.currentPipeline.onBind(e),this.currentPipeline},hasActiveStencilMask:function(){var t=this.currentMask.mask,e=this.currentCameraMask.mask;return t&&t.isStencil||e&&e.isStencil},rebindPipeline:function(t){var e=this.gl;e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),this.hasActiveStencilMask()?e.clear(e.DEPTH_BUFFER_BIT):(e.disable(e.STENCIL_TEST),e.clear(e.DEPTH_BUFFER_BIT|e.STENCIL_BUFFER_BIT)),e.viewport(0,0,this.width,this.height),this.setBlendMode(0,!0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.blankTexture.glTexture),this.currentActiveTextureUnit=0,this.currentTextures[0]=this.blankTexture.glTexture,this.currentPipeline=t,this.currentPipeline.bind(),this.currentPipeline.onBind()},clearPipeline:function(){this.flush(),this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.setBlendMode(0,!0)},setBlendMode:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.blendModes[t];return!!(e||t!==o.BlendModes.SKIP_CHECK&&this.currentBlendMode!==t)&&(this.flush(),i.enable(i.BLEND),i.blendEquation(n.equation),n.func.length>2?i.blendFuncSeparate(n.func[0],n.func[1],n.func[2],n.func[3]):i.blendFunc(n.func[0],n.func[1]),this.currentBlendMode=t,!0)},addBlendMode:function(t,e){return this.blendModes.push({func:t,equation:e})-1},updateBlendMode:function(t,e,i){return this.blendModes[t]&&(this.blendModes[t].func=e,i&&(this.blendModes[t].equation=i)),this},removeBlendMode:function(t){return t>17&&this.blendModes[t]&&this.blendModes.splice(t,1),this},setBlankTexture:function(t){void 0===t&&(t=!1),!t&&0===this.currentActiveTextureUnit&&this.currentTextures[0]||this.setTexture2D(this.blankTexture.glTexture,0)},setTexture2D:function(t,e,i){void 0===i&&(i=!0);var n=this.gl;return t!==this.currentTextures[e]&&(i&&this.flush(),this.currentActiveTextureUnit!==e&&(n.activeTexture(n.TEXTURE0+e),this.currentActiveTextureUnit=e),n.bindTexture(n.TEXTURE_2D,t),this.currentTextures[e]=t),this},setFramebuffer:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.width,s=this.height;return t!==this.currentFramebuffer&&(t&&t.renderTexture?(n=t.renderTexture.width,s=t.renderTexture.height):this.flush(),i.bindFramebuffer(i.FRAMEBUFFER,t),i.viewport(0,0,n,s),e&&(t?(this.drawingBufferHeight=s,this.pushScissor(0,0,n,s)):(this.drawingBufferHeight=this.height,this.popScissor())),this.currentFramebuffer=t),this},setProgram:function(t){var e=this.gl;return t!==this.currentProgram&&(this.flush(),e.useProgram(t),this.currentProgram=t),this},setVertexBuffer:function(t){var e=this.gl;return t!==this.currentVertexBuffer&&(this.flush(),e.bindBuffer(e.ARRAY_BUFFER,t),this.currentVertexBuffer=t),this},setIndexBuffer:function(t){var e=this.gl;return t!==this.currentIndexBuffer&&(this.flush(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.currentIndexBuffer=t),this},createTextureFromSource:function(t,e,i,n){var s=this.gl,r=s.NEAREST,a=s.NEAREST,l=s.CLAMP_TO_EDGE;e=t?t.width:e,i=t?t.height:i;var u=h(e,i);return u&&(l=s.REPEAT),n===o.ScaleModes.LINEAR&&this.config.antialias&&(r=u?this.mipmapFilter:s.LINEAR,a=s.LINEAR),t||"number"!=typeof e||"number"!=typeof i?this.createTexture2D(0,r,a,l,l,s.RGBA,t):this.createTexture2D(0,r,a,l,l,s.RGBA,null,e,i)},createTexture2D:function(t,e,i,n,s,r,o,a,l,u,c,d){u=void 0===u||null===u||u,void 0===c&&(c=!1),void 0===d&&(d=!1);var f=this.gl,p=f.createTexture();return this.setTexture2D(p,0),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,e),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,i),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,s),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,n),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u),f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,d),null===o||void 0===o?f.texImage2D(f.TEXTURE_2D,t,r,a,l,0,r,f.UNSIGNED_BYTE,null):(c||(a=o.width,l=o.height),f.texImage2D(f.TEXTURE_2D,t,r,r,f.UNSIGNED_BYTE,o)),h(a,l)&&f.generateMipmap(f.TEXTURE_2D),this.setTexture2D(null,0),p.isAlphaPremultiplied=u,p.isRenderTexture=!1,p.width=a,p.height=l,this.nativeTextures.push(p),p},createFramebuffer:function(t,e,i,n){var s,r=this.gl,o=r.createFramebuffer();if(this.setFramebuffer(o),n){var a=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,a),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,a)}if(i.isRenderTexture=!0,i.isAlphaPremultiplied=!1,r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),(s=r.checkFramebufferStatus(r.FRAMEBUFFER))!==r.FRAMEBUFFER_COMPLETE){throw new Error("Framebuffer incomplete. Framebuffer status: "+{36054:"Incomplete Attachment",36055:"Missing Attachment",36057:"Incomplete Dimensions",36061:"Framebuffer Unsupported"}[s])}return o.renderTexture=i,this.setFramebuffer(null),o},createProgram:function(t,e){var i=this.gl,n=i.createProgram(),s=i.createShader(i.VERTEX_SHADER),r=i.createShader(i.FRAGMENT_SHADER);if(i.shaderSource(s,t),i.shaderSource(r,e),i.compileShader(s),i.compileShader(r),!i.getShaderParameter(s,i.COMPILE_STATUS))throw new Error("Failed to compile Vertex Shader:\n"+i.getShaderInfoLog(s));if(!i.getShaderParameter(r,i.COMPILE_STATUS))throw new Error("Failed to compile Fragment Shader:\n"+i.getShaderInfoLog(r));if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw new Error("Failed to link program:\n"+i.getProgramInfoLog(n));return n},createVertexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setVertexBuffer(n),i.bufferData(i.ARRAY_BUFFER,t,e),this.setVertexBuffer(null),n},createIndexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setIndexBuffer(n),i.bufferData(i.ELEMENT_ARRAY_BUFFER,t,e),this.setIndexBuffer(null),n},deleteTexture:function(t){var e=this.nativeTextures.indexOf(t);return-1!==e&&c(this.nativeTextures,e),this.gl.deleteTexture(t),this.currentTextures[0]!==t||this.game.pendingDestroy||this.setBlankTexture(!0),this},deleteFramebuffer:function(t){return this.gl.deleteFramebuffer(t),this},deleteProgram:function(t){return this.gl.deleteProgram(t),this},deleteBuffer:function(t){return this.gl.deleteBuffer(t),this},preRenderCamera:function(t){var e=t._cx,i=t._cy,n=t._cw,r=t._ch,o=this.pipelines.TextureTintPipeline,a=t.backgroundColor;if(t.renderToTexture){this.flush(),this.pushScissor(e,i,n,-r),this.setFramebuffer(t.framebuffer);var h=this.gl;h.clearColor(0,0,0,0),h.clear(h.COLOR_BUFFER_BIT),o.projOrtho(e,n+e,i,r+i,-1e3,1e3),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n+e,r+i,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL),t.emit(s.PRE_RENDER,t)}else this.pushScissor(e,i,n,r),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n,r,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL)},getCurrentStencilMask:function(){var t=null,e=this.maskStack,i=this.currentCameraMask;return e.length>0?t=e[e.length-1]:i.mask&&i.mask.isStencil&&(t=i),t},postRenderCamera:function(t){var e=this.pipelines.TextureTintPipeline;if(t.flashEffect.postRenderWebGL(e,p.getTintFromFloats),t.fadeEffect.postRenderWebGL(e,p.getTintFromFloats),t.dirty=!1,this.popScissor(),t.renderToTexture){e.flush(),this.setFramebuffer(null),t.emit(s.POST_RENDER,t),e.projOrtho(0,e.width,e.height,0,-1e3,1e3);var i=p.getTintAppendFloatAlpha;(t.pipeline?t.pipeline:e).batchTexture(t,t.glTexture,t.width,t.height,t.x,t.y,t.width,t.height,t.zoom,t.zoom,t.rotation,t.flipX,!t.flipY,1,1,0,0,0,0,t.width,t.height,i(t._tintTL,t._alphaTL),i(t._tintTR,t._alphaTR),i(t._tintBL,t._alphaBL),i(t._tintBR,t._alphaBR),t._isTinted&&t.tintFill,0,0,this.defaultCamera,null),this.setBlankTexture(!0)}t.mask&&(this.currentCameraMask.mask=null,t.mask.postRenderWebGL(this,t._maskCamera))},preRender:function(){if(!this.contextLost){var t=this.gl,e=this.pipelines;if(t.bindFramebuffer(t.FRAMEBUFFER,null),this.config.clearBeforeRender){var i=this.config.backgroundColor;t.clearColor(i.redGL,i.greenGL,i.blueGL,i.alphaGL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT)}for(var n in t.enable(t.SCISSOR_TEST),e)e[n].onPreRender();this.currentScissor=[0,0,this.width,this.height],this.scissorStack=[this.currentScissor],this.game.scene.customViewports&&t.scissor(0,this.drawingBufferHeight-this.height,this.width,this.height),this.currentMask.mask=null,this.currentCameraMask.mask=null,this.maskStack.length=0,this.setPipeline(this.pipelines.TextureTintPipeline)}},render:function(t,e,i,n){if(!this.contextLost){var s=e.list,r=s.length,a=this.pipelines;for(var h in a)a[h].onRender(t,n);if(this.preRenderCamera(n),0===r)return this.setBlendMode(o.BlendModes.NORMAL),void this.postRenderCamera(n);this.currentType="";for(var l=this.currentMask,u=0;u0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},createVideoTexture:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=this.gl,s=n.NEAREST,r=n.NEAREST,o=t.videoWidth,a=t.videoHeight,l=n.CLAMP_TO_EDGE,u=h(o,a);return!e&&u&&(l=n.REPEAT),this.config.antialias&&(s=u?this.mipmapFilter:n.LINEAR,r=n.LINEAR),this.createTexture2D(0,s,r,l,l,n.RGBA,t,o,a,!0,!0,i)},updateVideoTexture:function(t,e,i){void 0===i&&(i=!1);var n=this.gl,s=t.videoWidth,r=t.videoHeight;return s>0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},setTextureFilter:function(t,e){var i=this.gl,n=[i.LINEAR,i.NEAREST][e];return this.setTexture2D(t,0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,n),this.setTexture2D(null,0),this},setFloat1:function(t,e,i){return this.setProgram(t),this.gl.uniform1f(this.gl.getUniformLocation(t,e),i),this},setFloat2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2f(this.gl.getUniformLocation(t,e),i,n),this},setFloat3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3f(this.gl.getUniformLocation(t,e),i,n,s),this},setFloat4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4f(this.gl.getUniformLocation(t,e),i,n,s,r),this},setFloat1v:function(t,e,i){return this.setProgram(t),this.gl.uniform1fv(this.gl.getUniformLocation(t,e),i),this},setFloat2v:function(t,e,i){return this.setProgram(t),this.gl.uniform2fv(this.gl.getUniformLocation(t,e),i),this},setFloat3v:function(t,e,i){return this.setProgram(t),this.gl.uniform3fv(this.gl.getUniformLocation(t,e),i),this},setFloat4v:function(t,e,i){return this.setProgram(t),this.gl.uniform4fv(this.gl.getUniformLocation(t,e),i),this},setInt1:function(t,e,i){return this.setProgram(t),this.gl.uniform1i(this.gl.getUniformLocation(t,e),i),this},setInt2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2i(this.gl.getUniformLocation(t,e),i,n),this},setInt3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3i(this.gl.getUniformLocation(t,e),i,n,s),this},setInt4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4i(this.gl.getUniformLocation(t,e),i,n,s,r),this},setMatrix2:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix2fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix3:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix3fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix4:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix4fv(this.gl.getUniformLocation(t,e),i,n),this},getMaxTextures:function(){return this.config.maxTextures},getMaxTextureSize:function(){return this.config.maxTextureSize},destroy:function(){for(var t=0;t0&&this.flush();var e=this.inverseRotationMatrix;if(t){var i=-t,n=Math.cos(i),s=Math.sin(i);e[1]=s,e[3]=-s,e[0]=e[4]=n}else e[0]=e[4]=1,e[1]=e[3]=0;this.renderer.setMatrix3(this.program,"uInverseRotationMatrix",!1,e),this.currentNormalMapRotation=t}},batchSprite:function(t,e,i){if(this.active){var n=t.texture.dataSource[t.frame.sourceIndex];n&&(this.renderer.setPipeline(this),this.setTexture2D(n.glTexture,1),this.setNormalMapRotation(t.rotation),r.prototype.batchSprite.call(this,t,e,i))}}});a.LIGHT_COUNT=o,t.exports=a},function(t,e){var i={modelMatrixDirty:!1,viewMatrixDirty:!1,projectionMatrixDirty:!1,modelMatrix:null,viewMatrix:null,projectionMatrix:null,mvpInit:function(){return this.modelMatrixDirty=!0,this.viewMatrixDirty=!0,this.projectionMatrixDirty=!0,this.modelMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.viewMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.projectionMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this},mvpUpdate:function(){var t=this.program;return this.modelMatrixDirty&&(this.renderer.setMatrix4(t,"uModelMatrix",!1,this.modelMatrix),this.modelMatrixDirty=!1),this.viewMatrixDirty&&(this.renderer.setMatrix4(t,"uViewMatrix",!1,this.viewMatrix),this.viewMatrixDirty=!1),this.projectionMatrixDirty&&(this.renderer.setMatrix4(t,"uProjectionMatrix",!1,this.projectionMatrix),this.projectionMatrixDirty=!1),this},modelIdentity:function(){var t=this.modelMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.modelMatrixDirty=!0,this},modelScale:function(t,e,i){var n=this.modelMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.modelMatrixDirty=!0,this},modelTranslate:function(t,e,i){var n=this.modelMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.modelMatrixDirty=!0,this},modelRotateX:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.modelMatrixDirty=!0,this},modelRotateY:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.modelMatrixDirty=!0,this},modelRotateZ:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.modelMatrixDirty=!0,this},viewIdentity:function(){var t=this.viewMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.viewMatrixDirty=!0,this},viewScale:function(t,e,i){var n=this.viewMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.viewMatrixDirty=!0,this},viewTranslate:function(t,e,i){var n=this.viewMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.viewMatrixDirty=!0,this},viewRotateX:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.viewMatrixDirty=!0,this},viewRotateY:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.viewMatrixDirty=!0,this},viewRotateZ:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.viewMatrixDirty=!0,this},viewLoad2D:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=0,e[3]=0,e[4]=t[2],e[5]=t[3],e[6]=0,e[7]=0,e[8]=t[4],e[9]=t[5],e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this.viewMatrixDirty=!0,this},viewLoad:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this.viewMatrixDirty=!0,this},projIdentity:function(){var t=this.projectionMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.projectionMatrixDirty=!0,this},projOrtho:function(t,e,i,n,s,r){var o=this.projectionMatrix,a=1/(t-e),h=1/(i-n),l=1/(s-r);return o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this.projectionMatrixDirty=!0,this},projPersp:function(t,e,i,n){var s=this.projectionMatrix,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this.projectionMatrixDirty=!0,this}};t.exports=i},,,,,function(t,e){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(t){"object"==typeof window&&(i=window)}t.exports=i},function(t,e,i){i(513),i(514),i(515),i(516),i(517),i(518),i(519),i(520)},function(t,e){Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var n=arguments.length>=2?arguments[1]:void 0,s=0;s>16)+(65280&t)+((255&t)<<16)},n={_tintTL:16777215,_tintTR:16777215,_tintBL:16777215,_tintBR:16777215,_isTinted:!1,tintFill:!1,clearTint:function(){return this.setTint(16777215),this._isTinted=!1,this},setTint:function(t,e,n,s){return void 0===t&&(t=16777215),void 0===e&&(e=t,n=t,s=t),this._tintTL=i(t),this._tintTR=i(e),this._tintBL=i(n),this._tintBR=i(s),this._isTinted=!0,this.tintFill=!1,this},setTintFill:function(t,e,i,n){return this.setTint(t,e,i,n),this.tintFill=!0,this},tintTopLeft:{get:function(){return this._tintTL},set:function(t){this._tintTL=i(t),this._isTinted=!0}},tintTopRight:{get:function(){return this._tintTR},set:function(t){this._tintTR=i(t),this._isTinted=!0}},tintBottomLeft:{get:function(){return this._tintBL},set:function(t){this._tintBL=i(t),this._isTinted=!0}},tintBottomRight:{get:function(){return this._tintBR},set:function(t){this._tintBR=i(t),this._isTinted=!0}},tint:{set:function(t){this.setTint(t,t,t,t)}},isTinted:{get:function(){return this._isTinted}}};t.exports=n},function(t,e){t.exports="changedata"},function(t,e){t.exports="changedata-"},function(t,e){t.exports="removedata"},function(t,e){t.exports="setdata"},function(t,e){t.exports="destroy"},function(t,e){t.exports="complete"},function(t,e){t.exports="created"},function(t,e){t.exports="error"},function(t,e){t.exports="loop"},function(t,e){t.exports="play"},function(t,e){t.exports="seeked"},function(t,e){t.exports="seeking"},function(t,e){t.exports="stop"},function(t,e){t.exports="timeout"},function(t,e){t.exports="unlocked"},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"alpha",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"x",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r,o,a){return void 0!==i&&null!==i||(i=e),n(t,"x",e,s,o,a),n(t,"y",i,r,o,a)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"y",e,i,s,r)}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=6.28);for(var s=i,r=(n-i)/t.length,o=0;o0?s(o,i):i<0&&r(o,Math.abs(i));for(var a=0;a1)if(0===s){var d=t.length-1;for(o=t[d].x,a=t[d].y,h=d-1;h>=0;h--)l=(c=t[h]).x,u=c.y,c.x=o,c.y=a,o=l,a=u;t[d].x=e,t[d].y=i}else{for(o=t[0].x,a=t[0].y,h=1;h0?(this._speedX-=this.dragX*t,this._speedX<0&&(this._speedX=0)):this._speedX<0&&(this._speedX+=this.dragX*t,this._speedX>0&&(this._speedX=0)),this._speedY>0?(this._speedY-=this.dragY*t,this._speedY<0&&(this._speedY=0)):this._speedY<0&&(this._speedY+=this.dragY*t,this._speedY>0&&(this._speedY=0)),this.up&&this.up.isDown?(this._speedY+=this.accelY,this._speedY>this.maxSpeedY&&(this._speedY=this.maxSpeedY)):this.down&&this.down.isDown&&(this._speedY-=this.accelY,this._speedY<-this.maxSpeedY&&(this._speedY=-this.maxSpeedY)),this.left&&this.left.isDown?(this._speedX+=this.accelX,this._speedX>this.maxSpeedX&&(this._speedX=this.maxSpeedX)):this.right&&this.right.isDown&&(this._speedX-=this.accelX,this._speedX<-this.maxSpeedX&&(this._speedX=-this.maxSpeedX)),this.zoomIn&&this.zoomIn.isDown?this._zoom=-this.zoomSpeed:this.zoomOut&&this.zoomOut.isDown?this._zoom=this.zoomSpeed:this._zoom=0,0!==this._speedX&&(e.scrollX-=this._speedX*t|0),0!==this._speedY&&(e.scrollY-=this._speedY*t|0),0!==this._zoom&&(e.zoom+=this._zoom,e.zoom<.001&&(e.zoom=.001))}},destroy:function(){this.camera=null,this.left=null,this.right=null,this.up=null,this.down=null,this.zoomIn=null,this.zoomOut=null}});t.exports=r},function(t,e,i){t.exports={Camera:i(290),BaseCamera:i(91),CameraManager:i(693),Effects:i(298),Events:i(48)}},function(t,e){t.exports="cameradestroy"},function(t,e){t.exports="camerafadeincomplete"},function(t,e){t.exports="camerafadeinstart"},function(t,e){t.exports="camerafadeoutcomplete"},function(t,e){t.exports="camerafadeoutstart"},function(t,e){t.exports="cameraflashcomplete"},function(t,e){t.exports="cameraflashstart"},function(t,e){t.exports="camerapancomplete"},function(t,e){t.exports="camerapanstart"},function(t,e){t.exports="postrender"},function(t,e){t.exports="prerender"},function(t,e){t.exports="camerashakecomplete"},function(t,e){t.exports="camerashakestart"},function(t,e){t.exports="camerazoomcomplete"},function(t,e){t.exports="camerazoomstart"},function(t,e,i){var n=i(22),s=i(0),r=i(48),o=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.isComplete=!1,this.direction=!0,this.duration=0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this.progress=0,this._elapsed=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s,o,a,h){if(void 0===t&&(t=!0),void 0===e&&(e=1e3),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=0),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===h&&(h=this.camera.scene),!o&&this.isRunning)return this.camera;this.isRunning=!0,this.isComplete=!1,this.duration=e,this.direction=t,this.progress=0,this.red=i,this.green=n,this.blue=s,this.alpha=t?Number.MIN_VALUE:1,this._elapsed=0,this._onUpdate=a,this._onUpdateScope=h;var l=t?r.FADE_OUT_START:r.FADE_IN_START;return this.camera.emit(l,this.camera,this,e,i,n,s),this.camera},update:function(t,e){this.isRunning&&(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed=1?1:1/e*(1+(e*t|0))}},function(t,e,i){var n=i(22),s=i(0),r=i(48),o=i(3),a=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.duration=0,this.intensity=new o,this.progress=0,this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s){return void 0===t&&(t=100),void 0===e&&(e=.05),void 0===i&&(i=!1),void 0===n&&(n=null),void 0===s&&(s=this.camera.scene),!i&&this.isRunning?this.camera:(this.isRunning=!0,this.duration=t,this.progress=0,"number"==typeof e?this.intensity.set(e):this.intensity.set(e.x,e.y),this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate=n,this._onUpdateScope=s,this.camera.emit(r.SHAKE_START,this.camera,this,t,e),this.camera)},preRender:function(){this.isRunning&&this.camera.matrix.translate(this._offsetX,this._offsetY)},update:function(t,e){if(this.isRunning)if(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed0&&(o.preRender(1),t.render(n,e,i,o))}},resetAll:function(){for(var t=0;t1)for(var i=1;i=1)&&(s.touch=!0),(navigator.msPointerEnabled||navigator.pointerEnabled)&&(s.mspointer=!0),navigator.getGamepads&&(s.gamepads=!0),"onwheel"in window||n.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":n.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"),s)},function(t,e,i){var n=i(117),s={audioData:!1,dolby:!1,m4a:!1,mp3:!1,ogg:!1,opus:!1,wav:!1,webAudio:!1,webm:!1};t.exports=function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio"),e=!!t.canPlayType;try{if(e&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(n.edge)s.dolby=!0;else if(n.safari&&n.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var i=parseInt(RegExp.$1,10),r=parseInt(RegExp.$2,10);(10===i&&r>=11||i>10)&&(s.dolby=!0)}}catch(t){}return s}()},function(t,e){var i={h264:!1,hls:!1,mp4:!1,ogg:!1,vp9:!1,webm:!1};t.exports=function(){var t=document.createElement("video"),e=!!t.canPlayType;try{e&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(i.ogg=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.h264=!0,i.mp4=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(i.webm=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(i.vp9=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.hls=!0))}catch(t){}return i}()},function(t,e){var i={available:!1,cancel:"",keyboard:!1,request:""};t.exports=function(){var t,e="Fullscreen",n="FullScreen",s=["request"+e,"request"+n,"webkitRequest"+e,"webkitRequest"+n,"msRequest"+e,"msRequest"+n,"mozRequest"+n,"mozRequest"+e];for(t=0;tMath.PI&&(t-=n.PI2),Math.abs(((t+n.TAU)%n.PI2-n.PI2)%n.PI2)}},function(t,e,i){var n=i(315);t.exports=function(t){return n(t+Math.PI)}},function(t,e,i){var n=i(13);t.exports=function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=i:e1?t[i]-(n(s-i,t[i],t[i],t[i-1],t[i-1])-t[i]):n(s-r,t[r?r-1:0],t[r],t[i1?n(t[i],t[i-1],i-s):n(t[r],t[r+1>i?i:r+1],s-r)}},function(t,e,i){var n=i(157);t.exports=function(t,e,i){return e+(i-e)*n(t,0,1)}},function(t,e,i){t.exports={GetNext:i(324),IsSize:i(118),IsValue:i(749)}},function(t,e){t.exports=function(t){return t>0&&0==(t&t-1)}},function(t,e,i){t.exports={Ceil:i(325),Floor:i(93),To:i(751)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){void 0===t&&(t=[(Date.now()*Math.random()).toString()]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.n=0,this.signs=[-1,1],t&&this.init(t)},rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},hash:function(t){var e,i=this.n;t=t.toString();for(var n=0;n>>0,i=(e*=i)>>>0,i+=4294967296*(e-=i);return this.n=i,2.3283064365386963e-10*(i>>>0)},init:function(t){"string"==typeof t?this.state(t):this.sow(t)},sow:function(t){if(this.n=4022871197,this.s0=this.hash(" "),this.s1=this.hash(" "),this.s2=this.hash(" "),this.c=1,t)for(var e=0;e0;e--){var i=Math.floor(this.frac()*(e+1)),n=t[i];t[i]=t[e],t[e]=n}return t}});t.exports=n},function(t,e){t.exports=function(t){for(var e=0,i=0;i1?void 0!==n?(s=(n-t)/(n-i))<0&&(s=0):s=1:s<0&&(s=0),s}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI;return t.x=Math.cos(i)*e,t.y=Math.sin(i)*e,t}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI,n=2*Math.random()-1,s=Math.sqrt(1-n*n)*e;return t.x=Math.cos(i)*s,t.y=Math.sin(i)*s,t.z=n*e,t}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=1),t.x=(2*Math.random()-1)*e,t.y=(2*Math.random()-1)*e,t.z=(2*Math.random()-1)*e,t.w=(2*Math.random()-1)*e,t}},function(t,e){t.exports=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var n=Math.pow(i,-e);return Math.round(t*n)/n}},function(t,e){t.exports=function(t,e,i,n){void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=1),n*=Math.PI/t;for(var s=[],r=[],o=0;o0&&t<=e*i&&(r=t>e-1?t-(o=Math.floor(t/e))*e:t,s.set(r,o)),s}},function(t,e){t.exports=function(t,e,i){return Math.abs(t-e)<=i}},function(t,e,i){var n=i(172),s=i(332),r=i(333),o=new s,a=new r,h=new n;t.exports=function(t,e,i){return a.setAxisAngle(e,i),o.fromRotationTranslation(a,h.set(0,0,0)),t.transformMat4(o)}},function(t,e){t.exports="addtexture"},function(t,e){t.exports="onerror"},function(t,e){t.exports="onload"},function(t,e){t.exports="ready"},function(t,e){t.exports="removetexture"},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_FS","","precision mediump float;","","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uMaskSampler;","uniform bool uInvertMaskAlpha;","","void main()","{"," vec2 uv = gl_FragCoord.xy / uResolution;"," vec4 mainColor = texture2D(uMainSampler, uv);"," vec4 maskColor = texture2D(uMaskSampler, uv);"," float alpha = mainColor.a;",""," if (!uInvertMaskAlpha)"," {"," alpha *= (maskColor.a);"," }"," else"," {"," alpha *= (1.0 - maskColor.a);"," }",""," gl_FragColor = vec4(mainColor.rgb * alpha, alpha);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_VS","","precision mediump float;","","attribute vec2 inPosition;","","void main()","{"," gl_Position = vec4(inPosition, 0.0, 1.0);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS","","precision mediump float;","","struct Light","{"," vec2 position;"," vec3 color;"," float intensity;"," float radius;","};","","const int kMaxLights = %LIGHT_COUNT%;","","uniform vec4 uCamera; /* x, y, rotation, zoom */","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uNormSampler;","uniform vec3 uAmbientLightColor;","uniform Light uLights[kMaxLights];","uniform mat3 uInverseRotationMatrix;","","varying vec2 outTexCoord;","varying vec4 outTint;","","void main()","{"," vec3 finalColor = vec3(0.0, 0.0, 0.0);"," vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);"," vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;"," vec3 normal = normalize(uInverseRotationMatrix * vec3(normalMap * 2.0 - 1.0));"," vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;",""," for (int index = 0; index < kMaxLights; ++index)"," {"," Light light = uLights[index];"," vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);"," vec3 lightNormal = normalize(lightDir);"," float distToSurf = length(lightDir) * uCamera.w;"," float diffuseFactor = max(dot(normal, lightNormal), 0.0);"," float radius = (light.radius / res.x * uCamera.w) * uCamera.w;"," float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);"," vec3 diffuse = light.color * diffuseFactor;"," finalColor += (attenuation * diffuse) * light.intensity;"," }",""," vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);"," gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);","","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_FS","","precision mediump float;","","uniform sampler2D uMainSampler;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main()","{"," vec4 texture = texture2D(uMainSampler, outTexCoord);"," vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);"," vec4 color = texture;",""," if (outTintEffect == 0.0)"," {"," // Multiply texture tint"," color = texture * texel;"," }"," else if (outTintEffect == 1.0)"," {"," // Solid color + texture alpha"," color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);"," color.a = texture.a * texel.a;"," }"," else if (outTintEffect == 2.0)"," {"," // Solid color, no texture"," color = texel;"," }",""," gl_FragColor = color;","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_VS","","precision mediump float;","","uniform mat4 uProjectionMatrix;","uniform mat4 uViewMatrix;","uniform mat4 uModelMatrix;","","attribute vec2 inPosition;","attribute vec2 inTexCoord;","attribute float inTintEffect;","attribute vec4 inTint;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main ()","{"," gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);",""," outTexCoord = inTexCoord;"," outTint = inTint;"," outTintEffect = inTintEffect;","}","",""].join("\n")},function(t,e,i){t.exports={GenerateTexture:i(340),Palettes:i(782)}},function(t,e,i){t.exports={ARNE16:i(341),C64:i(783),CGA:i(784),JMP:i(785),MSX:i(786)}},function(t,e){t.exports={0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"}},function(t,e){t.exports={0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}},function(t,e,i){t.exports={Path:i(788),CubicBezier:i(342),Curve:i(80),Ellipse:i(343),Line:i(344),QuadraticBezier:i(345),Spline:i(346)}},function(t,e,i){var n=i(0),s=i(342),r=i(343),o=i(5),a=i(344),h=i(789),l=i(345),u=i(11),c=i(346),d=i(3),f=i(13),p=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.name="",this.curves=[],this.cacheLengths=[],this.autoClose=!1,this.startPoint=new d,this._tmpVec2A=new d,this._tmpVec2B=new d,"object"==typeof t?this.fromJSON(t):this.startPoint.set(t,e)},add:function(t){return this.curves.push(t),this},circleTo:function(t,e,i){return void 0===e&&(e=!1),this.ellipseTo(t,t,0,360,e,i)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);return t.equals(e)||this.curves.push(new a(e,t)),this},cubicBezierTo:function(t,e,i,n,r,o){var a,h,l,u=this.getEndPoint();return t instanceof d?(a=t,h=e,l=i):(a=new d(i,n),h=new d(r,o),l=new d(t,e)),this.add(new s(u,a,h,l))},quadraticBezierTo:function(t,e,i,n){var s,r,o=this.getEndPoint();return t instanceof d?(s=t,r=e):(s=new d(i,n),r=new d(t,e)),this.add(new l(o,s,r))},draw:function(t,e){for(var i=0;i0?this.curves[this.curves.length-1].getPoint(1,t):t.copy(this.startPoint),t},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},getPoint:function(t,e){void 0===e&&(e=new d);for(var i=t*this.getLength(),n=this.getCurveLengths(),s=0;s=i){var r=n[s]-i,o=this.curves[s],a=o.getLength(),h=0===a?0:1-r/a;return o.getPointAt(h,e)}s++}return null},getPoints:function(t){void 0===t&&(t=12);for(var e,i=[],n=0;n1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},getRandomPoint:function(t){return void 0===t&&(t=new d),this.getPoint(Math.random(),t)},getSpacedPoints:function(t){void 0===t&&(t=40);for(var e=[],i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e},getStartPoint:function(t){return void 0===t&&(t=new d),t.copy(this.startPoint)},lineTo:function(t,e){t instanceof d?this._tmpVec2B.copy(t):this._tmpVec2B.set(t,e);var i=this.getEndPoint(this._tmpVec2A);return this.add(new a([i.x,i.y,this._tmpVec2B.x,this._tmpVec2B.y]))},splineTo:function(t){return t.unshift(this.getEndPoint()),this.add(new c(t))},moveTo:function(t,e){return t instanceof d?this.add(new h(t.x,t.y)):this.add(new h(t,e))},toJSON:function(){for(var t=[],e=0;e>16&255,g:t>>8&255,b:255&t,a:255};return t>16777215&&(e.a=t>>>24),e}},function(t,e,i){var n=i(33),s=i(350);t.exports=function(t,e,i){var r=i,o=i,a=i;if(0!==e){var h=i<.5?i*(1+e):i+e-i*e,l=2*i-h;r=s(l,h,t+1/3),o=s(l,h,t),a=s(l,h,t-1/3)}return(new n).setGLTo(r,o,a,1)}},function(t,e,i){var n=i(163);t.exports=function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n(s/359,t,e));return i}},function(t,e,i){var n=i(115),s=function(t,e,i,s,r,o,a,h){void 0===a&&(a=100),void 0===h&&(h=0);var l=h/a;return{r:n(t,s,l),g:n(e,r,l),b:n(i,o,l)}};t.exports={RGBWithRGB:s,ColorWithRGB:function(t,e,i,n,r,o){return void 0===r&&(r=100),void 0===o&&(o=0),s(t.r,t.g,t.b,e,i,n,r,o)},ColorWithColor:function(t,e,i,n){return void 0===i&&(i=100),void 0===n&&(n=0),s(t.r,t.g,t.b,e.r,e.g,e.b,i,n)}}},function(t,e,i){var n=i(170),s=i(33);t.exports=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=255),new s(n(t,e),n(t,e),n(t,e))}},function(t,e,i){var n=i(349);t.exports=function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n(s)+n(t)+n(e)+n(i)}},function(t,e,i){t.exports={BitmapMask:i(275),GeometryMask:i(276)}},function(t,e,i){var n={AddToDOM:i(120),DOMContentLoaded:i(351),GetScreenOrientation:i(352),GetTarget:i(357),ParseXML:i(358),RemoveFromDOM:i(176),RequestAnimationFrame:i(338)};t.exports=n},function(t,e,i){t.exports={EventEmitter:i(811)}},function(t,e,i){var n=i(0),s=i(9),r=i(23),o=new n({Extends:s,initialize:function(){s.call(this)},shutdown:function(){this.removeAllListeners()},destroy:function(){this.removeAllListeners()}});r.register("EventEmitter",o,"events"),t.exports=o},function(t,e,i){var n=i(120),s=i(286),r=i(289),o=i(26),a=i(0),h=i(311),l=i(813),u=i(334),c=i(113),d=i(336),f=i(312),p=i(351),g=i(9),v=i(18),m=i(359),y=i(23),x=i(364),T=i(365),w=i(367),E=i(119),_=i(370),b=i(337),A=i(339),S=i(374),C=new a({initialize:function(t){this.config=new h(t),this.renderer=null,this.domContainer=null,this.canvas=null,this.context=null,this.isBooted=!1,this.isRunning=!1,this.events=new g,this.anims=new s(this),this.textures=new _(this),this.cache=new r(this),this.registry=new c(this),this.input=new m(this,this.config),this.scene=new w(this,this.config.sceneConfig),this.device=f,this.scale=new T(this,this.config),this.sound=null,this.sound=S.create(this),this.loop=new b(this,this.config.fps),this.plugins=new x(this,this.config),this.pendingDestroy=!1,this.removeCanvas=!1,this.noReturn=!1,this.hasFocus=!1,p(this.boot.bind(this))},boot:function(){y.hasCore("EventEmitter")?(this.isBooted=!0,this.config.preBoot(this),this.scale.preBoot(),u(this),l(this),d(this),n(this.canvas,this.config.parent),this.textures.once(E.READY,this.texturesReady,this),this.events.emit(v.BOOT)):console.warn("Aborting. Core Plugins missing.")},texturesReady:function(){this.events.emit(v.READY),this.start()},start:function(){this.isRunning=!0,this.config.postBoot(this),this.renderer?this.loop.start(this.step.bind(this)):this.loop.start(this.headlessStep.bind(this)),A(this);var t=this.events;t.on(v.HIDDEN,this.onHidden,this),t.on(v.VISIBLE,this.onVisible,this),t.on(v.BLUR,this.onBlur,this),t.on(v.FOCUS,this.onFocus,this)},step:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e);var n=this.renderer;n.preRender(),i.emit(v.PRE_RENDER,n,t,e),this.scene.render(n),n.postRender(),i.emit(v.POST_RENDER,n,t,e)},headlessStep:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e),i.emit(v.PRE_RENDER),i.emit(v.POST_RENDER)},onHidden:function(){this.loop.pause(),this.events.emit(v.PAUSE)},onVisible:function(){this.loop.resume(),this.events.emit(v.RESUME)},onBlur:function(){this.hasFocus=!1,this.loop.blur()},onFocus:function(){this.hasFocus=!0,this.loop.focus()},getFrame:function(){return this.loop.frame},getTime:function(){return this.loop.now},destroy:function(t,e){void 0===e&&(e=!1),this.pendingDestroy=!0,this.removeCanvas=t,this.noReturn=e},runDestroy:function(){this.scene.destroy(),this.events.emit(v.DESTROY),this.events.removeAllListeners(),this.renderer&&this.renderer.destroy(),this.removeCanvas&&this.canvas&&(o.remove(this.canvas),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)),this.domContainer&&this.domContainer.parentNode.removeChild(this.domContainer),this.loop.destroy(),this.pendingDestroy=!1}});t.exports=C},function(t,e,i){var n=i(120);t.exports=function(t){var e=t.config;if(e.parent&&e.domCreateContainer){var i=document.createElement("div");i.style.cssText=["display: block;","width: "+t.scale.width+"px;","height: "+t.scale.height+"px;","padding: 0; margin: 0;","position: absolute;","overflow: hidden;","pointer-events: none;","transform: scale(1);","transform-origin: left top;"].join(" "),t.domContainer=i,n(i,e.parent)}}},function(t,e){t.exports="boot"},function(t,e){t.exports="destroy"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameout"},function(t,e){t.exports="gameover"},function(t,e){t.exports="gameobjectdown"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameobjectmove"},function(t,e){t.exports="gameobjectout"},function(t,e){t.exports="gameobjectover"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="wheel"},function(t,e){t.exports="gameobjectup"},function(t,e){t.exports="gameobjectwheel"},function(t,e){t.exports="boot"},function(t,e){t.exports="process"},function(t,e){t.exports="update"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointerdownoutside"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="pointerupoutside"},function(t,e){t.exports="wheel"},function(t,e){t.exports="pointerlockchange"},function(t,e){t.exports="preupdate"},function(t,e){t.exports="shutdown"},function(t,e){t.exports="start"},function(t,e){t.exports="update"},function(t,e){t.exports=function(t){if(!t)return window.innerHeight;var e=Math.abs(window.orientation),i={w:0,h:0},n=document.createElement("div");return n.setAttribute("style","position: fixed; height: 100vh; width: 0; top: 0"),document.documentElement.appendChild(n),i.w=90===e?n.offsetHeight:window.innerWidth,i.h=90===e?window.innerWidth:n.offsetHeight,document.documentElement.removeChild(n),n=null,90!==Math.abs(window.orientation)?i.h:i.w}},function(t,e){t.exports="addfile"},function(t,e){t.exports="complete"},function(t,e){t.exports="filecomplete"},function(t,e){t.exports="filecomplete-"},function(t,e){t.exports="loaderror"},function(t,e){t.exports="load"},function(t,e){t.exports="fileprogress"},function(t,e){t.exports="postprocess"},function(t,e){t.exports="progress"},function(t,e){t.exports="start"},function(t,e,i){var n=i(2),s=i(179);t.exports=function(t){var e=t.game.config.defaultPhysicsSystem,i=n(t.settings,"physics",!1);if(e||i){var r=[];if(e&&r.push(s(e+"Physics")),i)for(var o in i)o=s(o.concat("Physics")),-1===r.indexOf(o)&&r.push(o);return r}}},function(t,e,i){var n=i(2);t.exports=function(t){var e=t.plugins.getDefaultScenePlugins(),i=n(t.settings,"plugins",!1);return Array.isArray(i)?i:e||[]}},function(t,e,i){t.exports={game:"game",anims:"anims",cache:"cache",plugins:"plugins",registry:"registry",scale:"scale",sound:"sound",textures:"textures",events:"events",cameras:"cameras",add:"add",make:"make",scenePlugin:"scene",displayList:"children",lights:"lights",data:"data",input:"input",load:"load",time:"time",tweens:"tweens",arcadePhysics:"physics",impactPhysics:"impact",matterPhysics:"matter"}},function(t,e){t.exports=function(t,e,i){if(i.getElementsByTagName("TextureAtlas")){var n=t.source[e];t.add("__BASE",e,0,0,n.width,n.height);for(var s,r=i.getElementsByTagName("SubTexture"),o=0;og||c<-g)&&(c=0),c<0&&(c=g+c),-1!==d&&(g=c+(d+1));for(var v=f,m=f,y=0,x=0,T=0;Tr&&(y=w-r),E>o&&(x=E-o),t.add(T,e,i+v,s+m,h-y,l-x),(v+=h+p)+h>r&&(v=f,m+=l+p)}return t}},function(t,e,i){var n=i(2);t.exports=function(t,e,i){var s=n(i,"frameWidth",null),r=n(i,"frameHeight",s);if(!s)throw new Error("TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.");var o=t.source[0];t.add("__BASE",0,0,0,o.width,o.height);var a,h=n(i,"startFrame",0),l=n(i,"endFrame",-1),u=n(i,"margin",0),c=n(i,"spacing",0),d=e.cutX,f=e.cutY,p=e.cutWidth,g=e.cutHeight,v=e.realWidth,m=e.realHeight,y=Math.floor((v-u+c)/(s+c)),x=Math.floor((m-u+c)/(r+c)),T=y*x,w=e.x,E=s-w,_=s-(v-p-w),b=e.y,A=r-b,S=r-(m-g-b);(h>T||h<-T)&&(h=0),h<0&&(h=T+h),-1!==l&&(T=h+(l+1));for(var C=u,M=u,O=0,P=e.sourceIndex,R=0;R0){var r=i-t.length;if(r<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.push(e),n&&n.call(s,e),e):null;for(var o=e.length-1;o>=0;)-1!==t.indexOf(e[o])&&e.splice(o,1),o--;if(0===(o=e.length))return null;i>0&&o>r&&(e.splice(r),o=r);for(var a=0;a0){var o=n-t.length;if(o<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.splice(i,0,e),s&&s.call(r,e),e):null;for(var a=e.length-1;a>=0;)-1!==t.indexOf(e[a])&&e.pop(),a--;if(0===(a=e.length))return null;n>0&&a>o&&(e.splice(o),a=o);for(var h=a-1;h>=0;h--){var l=e[h];t.splice(i,0,l),s&&s.call(r,l)}return e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);return-1!==i&&i0){var n=t[i-1],s=t.indexOf(n);t[i]=n,t[s]=e}return t}},function(t,e){t.exports=function(t,e,i){var n=t.indexOf(e);if(-1===n||i<0||i>=t.length)throw new Error("Supplied index out of bounds");return n!==i&&(t.splice(n,1),t.splice(i,0,e)),e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);if(-1!==i&&it.length-1)throw new Error("Index out of bounds");var r=n(t,e);return i&&i.call(s,r),r}},function(t,e,i){var n=i(68);t.exports=function(t,e,i,s,r){if(void 0===e&&(e=0),void 0===i&&(i=t.length),void 0===r&&(r=t),n(t,e,i)){var o=i-e,a=t.splice(e,o);if(s)for(var h=0;h0&&(t.splice(i,1),t.unshift(e)),e}},function(t,e,i){var n=i(68);t.exports=function(t,e,i,s,r){if(void 0===s&&(s=0),void 0===r&&(r=t.length),n(t,s,r))for(var o=s;o0){for(n=0;nl||z-Y>l?(N.push(X.i-1),X.cr?(N.push(X.i+X.word.length),Y=0,B=null):B=X):X.cr&&(N.push(X.i+X.word.length),Y=0,B=null)}for(n=N.length-1;n>=0;n--)s=a,r=N[n],o="\n",a=s.substr(0,r)+o+s.substr(r+1);i.wrappedText=a,h=a.length,F=[],k=null}for(n=0;nE&&(c=E),d>_&&(d=_);var W=E+w.xAdvance,H=_+v;fR&&(R=D),DR&&(R=D),D0&&(a=(o=U.wrappedText).length);var z=e._bounds.lines;1===Y?X=(z.longest-z.lengths[0])/2:2===Y&&(X=z.longest-z.lengths[0]);for(var G=s.roundPixels,W=0;W0&&(a=(o=L.wrappedText).length);var D=e._bounds.lines;1===O?R=(D.longest-D.lengths[0])/2:2===O&&(R=D.longest-D.lengths[0]),h.translate(-e.displayOriginX,-e.displayOriginY);for(var F=s.roundPixels,k=0;k0!=t>0,this._alpha=t}}});t.exports=r},function(t,e,i){var n=i(1),s=i(1);n=i(948),s=i(949),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){var r=e.list;if(0!==r.length){var o=e.localTransform;s?(o.loadIdentity(),o.multiply(s),o.translate(e.x,e.y),o.rotate(e.rotation),o.scale(e.scaleX,e.scaleY)):o.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);var a=-1!==e.blendMode;a||t.setBlendMode(0);for(var h=e.alpha,l=e.scrollFactorX,u=e.scrollFactorY,c=r,d=r.length,f=0;f0||e.cropHeight>0;l&&(h.flush(),t.pushScissor(e.x,e.y,e.cropWidth*e.scaleX,e.cropHeight*e.scaleY));var u=h._tempMatrix1,c=h._tempMatrix2,d=h._tempMatrix3,f=h._tempMatrix4;c.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),u.copyFrom(s.matrix),r?(u.multiplyWithOffset(r,-s.scrollX*e.scrollFactorX,-s.scrollY*e.scrollFactorY),c.e=e.x,c.f=e.y,u.multiply(c,d)):(c.e-=s.scrollX*e.scrollFactorX,c.f-=s.scrollY*e.scrollFactorY,u.multiply(c,d));var p=e.frame,g=p.glTexture,v=p.cutX,m=p.cutY,y=g.width,x=g.height,T=e._isTinted&&e.tintFill,w=n.getTintAppendFloatAlpha(e._tintTL,s.alpha*e._alphaTL),E=n.getTintAppendFloatAlpha(e._tintTR,s.alpha*e._alphaTR),_=n.getTintAppendFloatAlpha(e._tintBL,s.alpha*e._alphaBL),b=n.getTintAppendFloatAlpha(e._tintBR,s.alpha*e._alphaBR);h.setTexture2D(g,0);var A,S,C=0,M=0,O=0,P=0,R=e.letterSpacing,L=0,D=0,F=0,k=0,I=e.scrollX,B=e.scrollY,Y=e.fontData,N=Y.chars,X=Y.lineHeight,U=e.fontSize/Y.size,z=0,G=e._align,W=0,H=0;e.getTextBounds(!1);var V=e._bounds.lines;1===G?H=(V.longest-V.lengths[0])/2:2===G&&(H=V.longest-V.lengths[0]);for(var j=s.roundPixels,K=e.displayCallback,q=e.callbackData,J=0;J0&&e.cropHeight>0&&(h.beginPath(),h.rect(0,0,e.cropWidth,e.cropHeight),h.clip());for(var Y=0;Y0&&(N=N%E-E):N>E?N=E:N<0&&(N=E+N%E),null===S&&(S=new o(k+Math.cos(Y)*B,I+Math.sin(Y)*B,v),_.push(S),F+=.01);F<1+U;)w=N*F+Y,x=k+Math.cos(w)*B,T=I+Math.sin(w)*B,S.points.push(new r(x,T,v)),F+=.01;w=N+Y,x=k+Math.cos(w)*B,T=I+Math.sin(w)*B,S.points.push(new r(x,T,v));break;case n.FILL_RECT:u.setTexture2D(M),u.batchFillRect(p[++O],p[++O],p[++O],p[++O],f,c);break;case n.FILL_TRIANGLE:u.setTexture2D(M),u.batchFillTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],f,c);break;case n.STROKE_TRIANGLE:u.setTexture2D(M),u.batchStrokeTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],v,f,c);break;case n.LINE_TO:null!==S?S.points.push(new r(p[++O],p[++O],v)):(S=new o(p[++O],p[++O],v),_.push(S));break;case n.MOVE_TO:S=new o(p[++O],p[++O],v),_.push(S);break;case n.SAVE:a.push(f.copyToArray());break;case n.RESTORE:f.copyFromArray(a.pop());break;case n.TRANSLATE:k=p[++O],I=p[++O],f.translate(k,I);break;case n.SCALE:k=p[++O],I=p[++O],f.scale(k,I);break;case n.ROTATE:f.rotate(p[++O]);break;case n.SET_TEXTURE:var z=p[++O],G=p[++O];u.currentFrame=z,u.setTexture2D(z.glTexture,0),u.tintEffect=G,M=z.glTexture;break;case n.CLEAR_TEXTURE:u.currentFrame=t.blankTexture,u.tintEffect=2,M=t.blankTexture.glTexture}}}},function(t,e,i){var n=i(1),s=i(1);n=i(961),s=i(962),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(1),s=i(1);n=i(964),s=i(965),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){t.exports={GravityWell:i(394),Particle:i(395),ParticleEmitter:i(396),ParticleEmitterManager:i(192),Zones:i(971)}},function(t,e,i){var n=i(0),s=i(326),r=i(82),o=i(2),a=i(58),h=new n({initialize:function(t,e,i,n){void 0===n&&(n=!1),this.propertyKey=e,this.propertyValue=i,this.defaultValue=i,this.steps=0,this.counter=0,this.start=0,this.end=0,this.ease,this.emitOnly=n,this.onEmit=this.defaultEmit,this.onUpdate=this.defaultUpdate,this.loadConfig(t)},loadConfig:function(t,e){void 0===t&&(t={}),e&&(this.propertyKey=e),this.propertyValue=o(t,this.propertyKey,this.defaultValue),this.setMethods(),this.emitOnly&&(this.onUpdate=this.defaultUpdate)},toJSON:function(){return this.propertyValue},onChange:function(t){return this.propertyValue=t,this.setMethods()},setMethods:function(){var t=this.propertyValue,e=typeof t;if("number"===e)this.onEmit=this.staticValueEmit,this.onUpdate=this.staticValueUpdate;else if(Array.isArray(t))this.onEmit=this.randomStaticValueEmit;else if("function"===e)this.emitOnly?this.onEmit=t:this.onUpdate=t;else if("object"===e&&(this.has(t,"random")||this.hasBoth(t,"start","end")||this.hasBoth(t,"min","max"))){this.start=this.has(t,"start")?t.start:t.min,this.end=this.has(t,"end")?t.end:t.max;var i=this.hasBoth(t,"min","max")||!!t.random;if(i){var n=t.random;Array.isArray(n)&&(this.start=n[0],this.end=n[1]),this.onEmit=this.randomRangedValueEmit}if(this.has(t,"steps"))this.steps=t.steps,this.counter=this.start,this.onEmit=this.steppedEmit;else{var s=this.has(t,"ease")?t.ease:"Linear";this.ease=r(s),i||(this.onEmit=this.easedValueEmit),this.onUpdate=this.easeValueUpdate}}else"object"===e&&this.hasEither(t,"onEmit","onUpdate")&&(this.has(t,"onEmit")&&(this.onEmit=t.onEmit),this.has(t,"onUpdate")&&(this.onUpdate=t.onUpdate));return this},has:function(t,e){return t.hasOwnProperty(e)},hasBoth:function(t,e,i){return t.hasOwnProperty(e)&&t.hasOwnProperty(i)},hasEither:function(t,e,i){return t.hasOwnProperty(e)||t.hasOwnProperty(i)},defaultEmit:function(t,e,i){return i},defaultUpdate:function(t,e,i,n){return n},staticValueEmit:function(){return this.propertyValue},staticValueUpdate:function(){return this.propertyValue},randomStaticValueEmit:function(){var t=Math.floor(Math.random()*this.propertyValue.length);return this.propertyValue[t]},randomRangedValueEmit:function(t,e){var i=s(this.start,this.end);return t&&t.data[e]&&(t.data[e].min=i),i},steppedEmit:function(){var t=this.counter,e=this.counter+(this.end-this.start)/this.steps;return this.counter=a(e,this.start,this.end),t},easedValueEmit:function(t,e){if(t&&t.data[e]){var i=t.data[e];i.min=this.start,i.max=this.end}return this.start},easeValueUpdate:function(t,e,i){var n=t.data[e];return(n.max-n.min)*this.ease(i)+n.min}});t.exports=h},function(t,e,i){var n=i(1),s=i(1);n=i(969),s=i(970),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){var o=e.emitters.list,a=o.length;if(0!==a){var h=this.pipeline,l=h._tempMatrix1.copyFrom(s.matrix),u=h._tempMatrix2,c=h._tempMatrix3,d=h._tempMatrix4.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);l.multiply(d),t.setPipeline(h);var f=s.roundPixels,p=e.defaultFrame.glTexture,g=n.getTintAppendFloatAlphaAndSwap;h.setTexture2D(p,0);for(var v=0;v?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",TEXT_SET2:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET3:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",TEXT_SET4:"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",TEXT_SET5:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",TEXT_SET6:"ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",TEXT_SET7:"AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",TEXT_SET8:"0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET9:"ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",TEXT_SET10:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET11:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"}},function(t,e,i){var n=i(6);t.exports=function(t,e){var i=e.width,s=e.height,r=Math.floor(i/2),o=Math.floor(s/2),a=n(e,"chars","");if(""!==a){var h=n(e,"image",""),l=n(e,"offset.x",0),u=n(e,"offset.y",0),c=n(e,"spacing.x",0),d=n(e,"spacing.y",0),f=n(e,"lineSpacing",0),p=n(e,"charsPerRow",null);null===p&&(p=t.sys.textures.getFrame(h).width/i)>a.length&&(p=a.length);for(var g=l,v=u,m={retroFont:!0,font:h,size:i,lineHeight:s+f,chars:{}},y=0,x=0;x0&&r.maxLines1&&(d+=f*(h-1)),{width:a,height:d,lines:h,lineWidths:o,lineSpacing:f,lineHeight:c}}},function(t,e,i){var n=i(1),s=i(1);n=i(980),s=i(981),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){if(0!==e.width&&0!==e.height){var o=e.frame,a=o.width,h=o.height,l=n.getTintAppendFloatAlpha;this.pipeline.batchTexture(e,o.glTexture,a,h,e.x,e.y,a/e.style.resolution,h/e.style.resolution,e.scaleX,e.scaleY,e.rotation,e.flipX,e.flipY,e.scrollFactorX,e.scrollFactorY,e.displayOriginX,e.displayOriginY,0,0,a,h,l(e._tintTL,s.alpha*e._alphaTL),l(e._tintTR,s.alpha*e._alphaTR),l(e._tintBL,s.alpha*e._alphaBL),l(e._tintBR,s.alpha*e._alphaBR),e._isTinted&&e.tintFill,0,0,s,r)}}},function(t,e){t.exports=function(t,e,i,n,s){0!==e.width&&0!==e.height&&t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(0),s=i(15),r=i(6),o=i(983),a={fontFamily:["fontFamily","Courier"],fontSize:["fontSize","16px"],fontStyle:["fontStyle",""],backgroundColor:["backgroundColor",null],color:["color","#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",!1],shadowFill:["shadow.fill",!1],align:["align","left"],maxLines:["maxLines",0],fixedWidth:["fixedWidth",0],fixedHeight:["fixedHeight",0],resolution:["resolution",0],rtl:["rtl",!1],testString:["testString","|MÉqgy"],baselineX:["baselineX",1.2],baselineY:["baselineY",1.4],wordWrapWidth:["wordWrap.width",null],wordWrapCallback:["wordWrap.callback",null],wordWrapCallbackScope:["wordWrap.callbackScope",null],wordWrapUseAdvanced:["wordWrap.useAdvancedWrap",!1]},h=new n({initialize:function(t,e){this.parent=t,this.fontFamily,this.fontSize,this.fontStyle,this.backgroundColor,this.color,this.stroke,this.strokeThickness,this.shadowOffsetX,this.shadowOffsetY,this.shadowColor,this.shadowBlur,this.shadowStroke,this.shadowFill,this.align,this.maxLines,this.fixedWidth,this.fixedHeight,this.resolution,this.rtl,this.testString,this.baselineX,this.baselineY,this._font,this.setStyle(e,!1,!0);var i=r(e,"metrics",!1);this.metrics=i?{ascent:r(i,"ascent",0),descent:r(i,"descent",0),fontSize:r(i,"fontSize",0)}:o(this)},setStyle:function(t,e,i){for(var n in void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px"),a){var o=i?a[n][1]:this[n];this[n]="wordWrapCallback"===n||"wordWrapCallbackScope"===n?r(t,a[n][0],o):s(t,a[n][0],o)}var h=r(t,"font",null);null!==h&&this.setFont(h,!1),this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim();var l=r(t,"fill",null);return null!==l&&(this.color=l),e?this.update(!0):this.parent},syncFont:function(t,e){e.font=this._font},syncStyle:function(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"},syncShadow:function(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)},update:function(t){return t&&(this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim(),this.metrics=o(this)),this.parent.updateText()},setFont:function(t,e){void 0===e&&(e=!0);var i=t,n="",s="";if("string"!=typeof t)i=r(t,"fontFamily","Courier"),n=r(t,"fontSize","16px"),s=r(t,"fontStyle","");else{var o=t.split(" "),a=0;s=o.length>2?o[a++]:"",n=o[a++]||"16px",i=o[a++]||"Courier"}return i===this.fontFamily&&n===this.fontSize&&s===this.fontStyle||(this.fontFamily=i,this.fontSize=n,this.fontStyle=s,e&&this.update(!0)),this.parent},setFontFamily:function(t){return this.fontFamily!==t&&(this.fontFamily=t,this.update(!0)),this.parent},setFontStyle:function(t){return this.fontStyle!==t&&(this.fontStyle=t,this.update(!0)),this.parent},setFontSize:function(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize!==t&&(this.fontSize=t,this.update(!0)),this.parent},setTestString:function(t){return this.testString=t,this.update(!0)},setFixedSize:function(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(!1)},setBackgroundColor:function(t){return this.backgroundColor=t,this.update(!1)},setFill:function(t){return this.color=t,this.update(!1)},setColor:function(t){return this.color=t,this.update(!1)},setResolution:function(t){return this.resolution=t,this.update(!1)},setStroke:function(t,e){return void 0===e&&(e=this.strokeThickness),void 0===t&&0!==this.strokeThickness?(this.strokeThickness=0,this.update(!0)):this.stroke===t&&this.strokeThickness===e||(this.stroke=t,this.strokeThickness=e,this.update(!0)),this.parent},setShadow:function(t,e,i,n,s,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===n&&(n=0),void 0===s&&(s=!1),void 0===r&&(r=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=i,this.shadowBlur=n,this.shadowStroke=s,this.shadowFill=r,this.update(!1)},setShadowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)},setShadowColor:function(t){return void 0===t&&(t="#000"),this.shadowColor=t,this.update(!1)},setShadowBlur:function(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)},setShadowStroke:function(t){return this.shadowStroke=t,this.update(!1)},setShadowFill:function(t){return this.shadowFill=t,this.update(!1)},setWordWrapWidth:function(t,e){return void 0===e&&(e=!1),this.wordWrapWidth=t,this.wordWrapUseAdvanced=e,this.update(!1)},setWordWrapCallback:function(t,e){return void 0===e&&(e=null),this.wordWrapCallback=t,this.wordWrapCallbackScope=e,this.update(!1)},setAlign:function(t){return void 0===t&&(t="left"),this.align=t,this.update(!1)},setMaxLines:function(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)},getTextMetrics:function(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}},toJSON:function(){var t={};for(var e in a)t[e]=this[e];return t.metrics=this.getTextMetrics(),t},destroy:function(){this.parent=void 0}});t.exports=h},function(t,e,i){var n=i(26);t.exports=function(t){var e=n.create(this),i=e.getContext("2d");t.syncFont(e,i);var s=Math.ceil(i.measureText(t.testString).width*t.baselineX),r=s,o=2*r;r=r*t.baselineY|0,e.width=s,e.height=o,i.fillStyle="#f00",i.fillRect(0,0,s,o),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,r);var a={ascent:0,descent:0,fontSize:0};if(!i.getImageData(0,0,s,o))return a.ascent=r,a.descent=r+6,a.fontSize=a.ascent+a.descent,n.remove(e),a;var h,l,u=i.getImageData(0,0,s,o).data,c=u.length,d=4*s,f=0,p=!1;for(h=0;hr;h--){for(l=0;l0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.fillColor,e.fillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.altFillColor,e.altFillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0){var R=o.strokeTint,L=n.getTintAppendFloatAlphaAndSwap(e.outlineFillColor,e.outlineFillAlpha*d);for(R.TL=L,R.TR=L,R.BL=L,R.BR=L,S=1;S0)for(n(h,e),S=0;S0)for(n(h,e,e.altFillColor,e.altFillAlpha*c),S=0;S0){for(s(h,e,e.outlineFillColor,e.outlineFillAlpha*c),A=1;Ao.vertexCapacity&&o.flush(),o.setTexture2D(u,0);for(var m=o.vertexViewF32,y=o.vertexViewU32,x=o.vertexCount*o.vertexComponentCount-1,T=0,w=e.tintFill,E=0;E0?Math.PI*t.radius*t.radius:0}},function(t,e,i){var n=i(65);t.exports=function(t){return new n(t.x,t.y,t.radius)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.radius)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.radius===e.radius}},function(t,e,i){var n=i(11);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.diameter,e.height=t.diameter,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(95);n.Area=i(1089),n.Circumference=i(392),n.CircumferencePoint=i(191),n.Clone=i(1090),n.Contains=i(96),n.ContainsPoint=i(1091),n.ContainsRect=i(1092),n.CopyFrom=i(1093),n.Equals=i(1094),n.GetBounds=i(1095),n.GetPoint=i(390),n.GetPoints=i(391),n.Offset=i(1096),n.OffsetPoint=i(1097),n.Random=i(154),t.exports=n},function(t,e){t.exports=function(t){return t.isEmpty()?0:t.getMajorRadius()*t.getMinorRadius()*Math.PI}},function(t,e,i){var n=i(95);t.exports=function(t){return new n(t.x,t.y,t.width,t.height)}},function(t,e,i){var n=i(96);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(96);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.width,t.height)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}},function(t,e,i){var n=i(11);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.width,e.height=t.height,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(4),s=i(202);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a,h,l=t.x,u=t.y,c=t.radius,d=e.x,f=e.y,p=e.radius;if(u===f)0==(a=(o=-2*f)*o-4*(r=1)*(d*d+(h=(p*p-c*c-d*d+l*l)/(2*(l-d)))*h-2*d*h+f*f-p*p))?i.push(new n(h,-o/(2*r))):a>0&&(i.push(new n(h,(-o+Math.sqrt(a))/(2*r))),i.push(new n(h,(-o-Math.sqrt(a))/(2*r))));else{var g=(l-d)/(u-f),v=(p*p-c*c-d*d+l*l-f*f+u*u)/(2*(u-f));0==(a=(o=2*u*g-2*v*g-2*l)*o-4*(r=g*g+1)*(l*l+u*u+v*v-c*c-2*u*v))?(h=-o/(2*r),i.push(new n(h,v-h*g))):a>0&&(h=(-o+Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)),h=(-o-Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)))}}return i}},function(t,e,i){var n=i(204),s=i(203);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC(),h=e.getLineD();n(r,t,i),n(o,t,i),n(a,t,i),n(h,t,i)}return i}},function(t,e,i){var n=i(11),s=i(131);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i}},function(t,e,i){var n=i(206),s=i(131);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC(),h=t.getLineD();n(r,e,i),n(o,e,i),n(a,e,i),n(h,e,i)}return i}},function(t,e,i){var n=i(425),s=i(206);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(r,t,i),s(o,t,i),s(a,t,i)}return i}},function(t,e,i){var n=i(204),s=i(427);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC();n(r,e,i),n(o,e,i),n(a,e,i)}return i}},function(t,e,i){var n=i(430),s=i(428);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(t,r,i),s(t,o,i),s(t,a,i)}return i}},function(t,e,i){var n=i(432);t.exports=function(t,e){if(!n(t,e))return!1;var i=Math.min(e.x1,e.x2),s=Math.max(e.x1,e.x2),r=Math.min(e.y1,e.y2),o=Math.max(e.y1,e.y2);return t.x>=i&&t.x<=s&&t.y>=r&&t.y<=o}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||si&&(i=h.x),h.xr&&(r=h.y),h.yn(e)?t.setSize(e.height*i,e.height):t.setSize(e.width,e.width/i),t.setPosition(e.centerX-t.width/2,e.centerY-t.height/2)}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t.width=Math.floor(t.width),t.height=Math.floor(t.height),t}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.centerX,e.y=t.centerY,e}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.width,e.y=t.height,e}},function(t,e,i){var n=i(165);t.exports=function(t,e,i){var s=t.centerX,r=t.centerY;return t.setSize(t.width+2*e,t.height+2*i),n(t,s,r)}},function(t,e,i){var n=i(11),s=i(131);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)?(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y):i.setEmpty(),i}},function(t,e){t.exports=function(t,e){for(var i=t.x,n=t.right,s=t.y,r=t.bottom,o=0;oe.x&&t.ye.y}},function(t,e,i){var n=i(4),s=i(35);t.exports=function(t,e,i){void 0===i&&(i=new n),e=s(e);var r=Math.sin(e),o=Math.cos(e),a=o>0?t.width/2:t.width/-2,h=r>0?t.height/2:t.height/-2;return Math.abs(a*r)-1&&(s.splice(a,1),this.clear(o,!0))}t.length=0,this._pendingRemoval.length=0,this._list=s.concat(e.splice(0))}},isActive:function(){return this.enabled&&this.scene.sys.isActive()},updatePoll:function(t,e){if(!this.isActive())return!1;if(this.pluginEvents.emit(d.UPDATE,t,e),this._updatedThisFrame)return this._updatedThisFrame=!1,!1;var i,n=this.manager,s=n.pointers,r=n.pointersTotal;for(i=0;i0){if(this._pollTimer-=e,!(this._pollTimer<0))return!1;this._pollTimer=this.pollRate}var a=!1;for(i=0;i0&&(a=!0)}return a},update:function(t,e){if(!this.isActive())return!1;for(var i=e.length,n=!1,s=0;s0&&(n=!0)}return this._updatedThisFrame=!0,n},clear:function(t,e){void 0===e&&(e=!1);var i=t.input;if(i){e||this.queueForRemoval(t),i.gameObject=void 0,i.target=void 0,i.hitArea=void 0,i.hitAreaCallback=void 0,i.callbackContext=void 0,this.manager.resetCursor(i),t.input=null;var n=this._draggable.indexOf(t);return n>-1&&this._draggable.splice(n,1),(n=this._drag[0].indexOf(t))>-1&&this._drag[0].splice(n,1),(n=this._over[0].indexOf(t))>-1&&this._over[0].splice(n,1),t}},disable:function(t){t.input.enabled=!1},enable:function(t,e,i,n){return void 0===n&&(n=!1),t.input?t.input.enabled=!0:this.setHitArea(t,e,i),t.input&&n&&!t.input.dropZone&&(t.input.dropZone=n),this},hitTestPointer:function(t){for(var e=this.cameras.getCamerasBelowPointer(t),i=0;i0)return t.camera=n,s}return t.camera=e[0],[]},processDownEvents:function(t){var e=0,i=this._temp,n=this._eventData,s=this._eventContainer;n.cancelled=!1;for(var r=!1,o=0;o0&&l(t.x,t.y,t.downX,t.downY)>=s?i=!0:n>0&&e>=t.downTime+n&&(i=!0),i)return this.setDragState(t,3),this.processDragStartList(t)},processDragStartList:function(t){if(3!==this.getDragState(t))return 0;for(var e=this._drag[t.id],i=0;i1&&(this.sortGameObjects(i),this.topOnly&&i.splice(1)),this._drag[t.id]=i,0===this.dragDistanceThreshold&&0===this.dragTimeThreshold?(this.setDragState(t,3),this.processDragStartList(t)):(this.setDragState(t,2),0))},processDragMoveEvent:function(t){if(2===this.getDragState(t)&&this.processDragThresholdEvent(t,this.manager.game.loop.now),4!==this.getDragState(t))return 0;for(var e=this._tempZones,i=this._drag[t.id],n=0;n0?(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),e[0]?(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):a.target=null)}else!h&&e[0]&&(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h));if(o.parentContainer){var u=t.x-a.dragStartXGlobal,c=t.y-a.dragStartYGlobal,f=o.getParentRotation(),p=u*Math.cos(f)+c*Math.sin(f),g=c*Math.cos(f)-u*Math.sin(f);p*=1/o.parentContainer.scaleX,g*=1/o.parentContainer.scaleY,s=p+a.dragStartX,r=g+a.dragStartY}else s=t.x-a.dragX,r=t.y-a.dragY;o.emit(d.GAMEOBJECT_DRAG,t,s,r),this.emit(d.DRAG,t,o,s,r)}return i.length},processDragUpEvent:function(t){for(var e=this._drag[t.id],i=0;i0){var r=this.manager,o=this._eventData,a=this._eventContainer;o.cancelled=!1;for(var h=!1,l=0;l0){var s=this.manager,r=this._eventData,o=this._eventContainer;r.cancelled=!1;var a=!1;this.sortGameObjects(e);for(var h=0;h0){for(this.sortGameObjects(s),e=0;e0){for(this.sortGameObjects(r),e=0;e-1&&this._draggable.splice(s,1)}return this},makePixelPerfect:function(t){void 0===t&&(t=1);var e=this.systems.textures;return h(e,t)},setHitArea:function(t,e,i){if(void 0===e)return this.setHitAreaFromTexture(t);Array.isArray(t)||(t=[t]);var n=!1,s=!1,r=!1,o=!1,h=!1,l=!0;if(m(e)){var u=e;e=p(u,"hitArea",null),i=p(u,"hitAreaCallback",null),n=p(u,"draggable",!1),s=p(u,"dropZone",!1),r=p(u,"cursor",!1),o=p(u,"useHandCursor",!1),h=p(u,"pixelPerfect",!1);var c=p(u,"alphaTolerance",1);h&&(e={},i=this.makePixelPerfect(c)),e&&i||(this.setHitAreaFromTexture(t),l=!1)}else"function"!=typeof e||i||(i=e,e={});for(var d=0;d=e}}},function(t,e,i){t.exports={Events:i(133),KeyboardManager:i(360),KeyboardPlugin:i(1210),Key:i(445),KeyCodes:i(122),KeyCombo:i(446),JustDown:i(1215),JustUp:i(1216),DownDuration:i(1217),UpDuration:i(1218)}},function(t,e){t.exports="keydown"},function(t,e){t.exports="keyup"},function(t,e){t.exports="keycombomatch"},function(t,e){t.exports="down"},function(t,e){t.exports="keydown-"},function(t,e){t.exports="keyup-"},function(t,e){t.exports="up"},function(t,e,i){var n=i(0),s=i(9),r=i(133),o=i(18),a=i(6),h=i(54),l=i(132),u=i(445),c=i(122),d=i(446),f=i(1214),p=i(93),g=new n({Extends:s,initialize:function(t){s.call(this),this.game=t.systems.game,this.scene=t.scene,this.settings=this.scene.sys.settings,this.sceneInputPlugin=t,this.manager=t.manager.keyboard,this.enabled=!0,this.keys=[],this.combos=[],t.pluginEvents.once(h.BOOT,this.boot,this),t.pluginEvents.on(h.START,this.start,this)},boot:function(){var t=this.settings.input;this.enabled=a(t,"keyboard",!0);var e=a(t,"keyboard.capture",null);e&&this.addCaptures(e),this.sceneInputPlugin.pluginEvents.once(h.DESTROY,this.destroy,this)},start:function(){this.sceneInputPlugin.manager.useQueue?this.sceneInputPlugin.pluginEvents.on(h.UPDATE,this.update,this):this.sceneInputPlugin.manager.events.on(h.MANAGER_PROCESS,this.update,this),this.sceneInputPlugin.pluginEvents.once(h.SHUTDOWN,this.shutdown,this),this.game.events.on(o.BLUR,this.resetKeys,this)},isActive:function(){return this.enabled&&this.scene.sys.isActive()},addCapture:function(t){return this.manager.addCapture(t),this},removeCapture:function(t){return this.manager.removeCapture(t),this},getCaptures:function(){return this.manager.captures},enableGlobalCapture:function(){return this.manager.preventDefault=!0,this},disableGlobalCapture:function(){return this.manager.preventDefault=!1,this},clearCaptures:function(){return this.manager.clearCaptures(),this},createCursorKeys:function(){return this.addKeys({up:c.UP,down:c.DOWN,left:c.LEFT,right:c.RIGHT,space:c.SPACE,shift:c.SHIFT})},addKeys:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1);var n={};if("string"==typeof t){t=t.split(",");for(var s=0;s-1?n[s]=t:n[t.keyCode]=t,e&&this.addCapture(t.keyCode),t.setEmitOnRepeat(i),t}return"string"==typeof t&&(t=c[t.toUpperCase()]),n[t]||(n[t]=new u(this,t),e&&this.addCapture(t),n[t].setEmitOnRepeat(i)),n[t]},removeKey:function(t,e){void 0===e&&(e=!1);var i,n=this.keys;if(t instanceof u){var s=n.indexOf(t);s>-1&&(i=this.keys[s],this.keys[s]=void 0)}else"string"==typeof t&&(t=c[t.toUpperCase()]);return n[t]&&(i=n[t],n[t]=void 0),i&&(i.plugin=null,e&&i.destroy()),this},createCombo:function(t,e){return new d(this,t,e)},checkDown:function(t,e){if(this.enabled&&t.isDown){var i=p(this.time-t.timeDown,e);if(i>t._tick)return t._tick=i,!0}return!1},update:function(){var t=this.manager.queue,e=t.length;if(this.isActive()&&0!==e)for(var i=this.keys,n=0;n0&&e.maxKeyDelay>0){var r=e.timeLastMatched+e.maxKeyDelay;t.timeStamp<=r&&(s=!0,i=n(t,e))}else s=!0,i=n(t,e);return!s&&e.resetOnWrongKey&&(e.index=0,e.current=e.keyCodes[0]),i&&(e.timeLastMatched=t.timeStamp,e.matched=!0,e.timeMatched=t.timeStamp),i}},function(t,e){t.exports=function(t,e){return e.timeLastMatched=t.timeStamp,e.index++,e.index===e.size||(e.current=e.keyCodes[e.index],!1)}},function(t,e){t.exports=function(t){return t.current=t.keyCodes[0],t.index=0,t.timeLastMatched=0,t.matched=!1,t.timeMatched=0,t}},function(t,e,i){var n=i(122),s={};for(var r in n)s[n[r]]=r;t.exports=s},function(t,e){t.exports=function(t){return!!t._justDown&&(t._justDown=!1,!0)}},function(t,e){t.exports=function(t){return!!t._justUp&&(t._justUp=!1,!0)}},function(t,e){t.exports=function(t,e){void 0===e&&(e=50);var i=t.plugin.game.loop.time-t.timeDown;return t.isDown&&i'),i.push(''),i.push(''),i.push(this.xhrLoader.responseText),i.push(""),i.push(""),i.push("");var n=[i.join("\n")],o=this;try{var a=new window.Blob(n,{type:"image/svg+xml;charset=utf-8"})}catch(t){return o.state=s.FILE_ERRORED,void o.onProcessComplete()}this.data=new Image,this.data.crossOrigin=this.crossOrigin,this.data.onload=function(){r.revokeObjectURL(o.data),o.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(o.data),o.onProcessError()},r.createObjectURL(this.data,a,"image/svg+xml")},addToCache:function(){var t=this.cache.addImage(this.key,this.data);this.pendingDestroy(t)}});o.register("htmlTexture",function(t,e,i,n,s){if(Array.isArray(t))for(var r=0;r0},isLoading:function(){return this.state===s.LOADER_LOADING||this.state===s.LOADER_PROCESSING},isReady:function(){return this.state===s.LOADER_IDLE||this.state===s.LOADER_COMPLETE},start:function(){this.isReady()&&(this.progress=0,this.totalFailed=0,this.totalComplete=0,this.totalToLoad=this.list.size,this.emit(a.START,this),0===this.list.size?this.loadComplete():(this.state=s.LOADER_LOADING,this.inflight.clear(),this.queue.clear(),this.updateProgress(),this.checkLoadQueue(),this.systems.events.on(c.UPDATE,this.update,this)))},updateProgress:function(){this.progress=1-(this.list.size+this.inflight.size)/this.totalToLoad,this.emit(a.PROGRESS,this.progress)},update:function(){this.state===s.LOADER_LOADING&&this.list.size>0&&this.inflight.sizei&&(n=l,i=c)}}return n},moveTo:function(t,e,i,n,s){void 0===n&&(n=60),void 0===s&&(s=0);var o=Math.atan2(i-t.y,e-t.x);return s>0&&(n=r(t.x,t.y,e,i)/(s/1e3)),t.body.velocity.setToPolar(o,n),o},moveToObject:function(t,e,i,n){return this.moveTo(t,e.x,e.y,i,n)},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(s(t),e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(t,e)},overlapRect:function(t,e,i,n,s,r){return c(this.world,t,e,i,n,s,r)},overlapCirc:function(t,e,i,n,s){return u(this.world,t,e,i,n,s)},shutdown:function(){if(this.world){var t=this.systems.events;t.off(f.UPDATE,this.world.update,this.world),t.off(f.POST_UPDATE,this.world.postUpdate,this.world),t.off(f.SHUTDOWN,this.shutdown,this),this.add.destroy(),this.world.destroy(),this.add=null,this.world=null}},destroy:function(){this.shutdown(),this.scene.sys.events.off(f.START,this.start,this),this.scene=null,this.systems=null}});d.register("ArcadePhysics",v,"arcadePhysics"),t.exports=v},function(t,e){t.exports={setAcceleration:function(t,e){return this.body.acceleration.set(t,e),this},setAccelerationX:function(t){return this.body.acceleration.x=t,this},setAccelerationY:function(t){return this.body.acceleration.y=t,this}}},function(t,e){t.exports={setAngularVelocity:function(t){return this.body.angularVelocity=t,this},setAngularAcceleration:function(t){return this.body.angularAcceleration=t,this},setAngularDrag:function(t){return this.body.angularDrag=t,this}}},function(t,e){t.exports={setBounce:function(t,e){return this.body.bounce.set(t,e),this},setBounceX:function(t){return this.body.bounce.x=t,this},setBounceY:function(t){return this.body.bounce.y=t,this},setCollideWorldBounds:function(t,e,i){return this.body.setCollideWorldBounds(t,e,i),this}}},function(t,e){t.exports={setDebug:function(t,e,i){return this.debugShowBody=t,this.debugShowVelocity=e,this.debugBodyColor=i,this},setDebugBodyColor:function(t){return this.body.debugBodyColor=t,this},debugShowBody:{get:function(){return this.body.debugShowBody},set:function(t){this.body.debugShowBody=t}},debugShowVelocity:{get:function(){return this.body.debugShowVelocity},set:function(t){this.body.debugShowVelocity=t}},debugBodyColor:{get:function(){return this.body.debugBodyColor},set:function(t){this.body.debugBodyColor=t}}}},function(t,e){t.exports={setDrag:function(t,e){return this.body.drag.set(t,e),this},setDragX:function(t){return this.body.drag.x=t,this},setDragY:function(t){return this.body.drag.y=t,this},setDamping:function(t){return this.body.useDamping=t,this}}},function(t,e){var i={enableBody:function(t,e,i,n,s){return t&&this.body.reset(e,i),n&&(this.body.gameObject.active=!0),s&&(this.body.gameObject.visible=!0),this.body.enable=!0,this},disableBody:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=!1),this.body.stop(),this.body.enable=!1,t&&(this.body.gameObject.active=!1),e&&(this.body.gameObject.visible=!1),this},refreshBody:function(){return this.body.updateFromGameObject(),this}};t.exports=i},function(t,e){t.exports={setFriction:function(t,e){return this.body.friction.set(t,e),this},setFrictionX:function(t){return this.body.friction.x=t,this},setFrictionY:function(t){return this.body.friction.y=t,this}}},function(t,e){t.exports={setGravity:function(t,e){return this.body.gravity.set(t,e),this},setGravityX:function(t){return this.body.gravity.x=t,this},setGravityY:function(t){return this.body.gravity.y=t,this}}},function(t,e){var i={setImmovable:function(t){return void 0===t&&(t=!0),this.body.immovable=t,this}};t.exports=i},function(t,e){t.exports={setMass:function(t){return this.body.mass=t,this}}},function(t,e){t.exports={setOffset:function(t,e){return this.body.setOffset(t,e),this},setSize:function(t,e,i){return this.body.setSize(t,e,i),this},setCircle:function(t,e,i){return this.body.setCircle(t,e,i),this}}},function(t,e){t.exports={setVelocity:function(t,e){return this.body.setVelocity(t,e),this},setVelocityX:function(t){return this.body.setVelocityX(t),this},setVelocityY:function(t){return this.body.setVelocityY(t),this},setMaxVelocity:function(t,e){return this.body.maxVelocity.set(t,e),this}}},function(t,e,i){var n=i(456),s=i(65),r=i(202),o=i(203);t.exports=function(t,e,i,a,h,l){var u=n(t,e-a,i-a,2*a,2*a,h,l);if(0===u.length)return u;for(var c=new s(e,i,a),d=new s,f=[],p=0;pe.deltaAbsY()?y=-1:e.deltaAbsX()0&&u&&t.checkCollision.right&&h&&t.right>i&&(a=t.right-i)>r&&(a=0),0!==a&&(t.customSeparateX?t.overlapX=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.left=!0):e>0&&(t.blocked.none=!1,t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x}},function(t,e,i){var n=i(1275);t.exports=function(t,e,i,s,r,o){var a=0,h=e.faceTop,l=e.faceBottom,u=e.collideUp,c=e.collideDown;return o||(h=!0,l=!0,u=!0,c=!0),t.deltaY()<0&&c&&t.checkCollision.up?l&&t.y0&&u&&t.checkCollision.down&&h&&t.bottom>i&&(a=t.bottom-i)>r&&(a=0),0!==a&&(t.customSeparateY?t.overlapY=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.up=!0):e>0&&(t.blocked.none=!1,t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},function(t,e,i){var n=i(460);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.x,a=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=r,e.velocity.x=o-a*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=r,t.velocity.x=a-o*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{r*=.5,t.x-=r,e.x+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.x=u+h*t.bounce.x,e.velocity.x=u+l*e.bounce.x}return!0}},function(t,e,i){var n=i(461);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.y,a=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=r,e.velocity.y=o-a*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=r,t.velocity.y=a-o*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{r*=.5,t.y-=r,e.y+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.y=u+h*t.bounce.y,e.velocity.y=u+l*e.bounce.y}return!0}},,,,,,,,,,,,,,,function(t,e,i){t.exports={BasePlugin:i(468),DefaultPlugins:i(173),PluginCache:i(23),PluginManager:i(364),ScenePlugin:i(1293)}},function(t,e,i){var n=i(468),s=i(0),r=i(19),o=new s({Extends:n,initialize:function(t,e){n.call(this,e),this.scene=t,this.systems=t.sys,t.sys.events.once(r.BOOT,this.boot,this)},boot:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=o},function(t,e,i){var n=i(17),s=i(175),r={Center:i(353),Events:i(92),Orientation:i(354),ScaleManager:i(365),ScaleModes:i(355),Zoom:i(356)};r=n(!1,r=n(!1,r=n(!1,r=n(!1,r,s.CENTER),s.ORIENTATION),s.SCALE_MODE),s.ZOOM),t.exports=r},function(t,e,i){var n=i(123),s=i(17),r={Events:i(19),SceneManager:i(367),ScenePlugin:i(1296),Settings:i(369),Systems:i(178)};r=s(!1,r,n),t.exports=r},function(t,e,i){var n=i(22),s=i(0),r=i(19),o=i(2),a=i(23),h=new s({initialize:function(t){this.scene=t,this.systems=t.sys,this.settings=t.sys.settings,this.key=t.sys.settings.key,this.manager=t.sys.game.scene,this.transitionProgress=0,this._elapsed=0,this._target=null,this._duration=0,this._onUpdate,this._onUpdateScope,this._willSleep=!1,this._willRemove=!1,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.pluginStart,this)},boot:function(){this.systems.events.once(r.DESTROY,this.destroy,this)},pluginStart:function(){this._target=null,this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},start:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",this.key),this.manager.queueOp("start",t,e),this},restart:function(t){var e=this.key;return this.manager.queueOp("stop",e),this.manager.queueOp("start",e,t),this},transition:function(t){void 0===t&&(t={});var e=o(t,"target",!1),i=this.manager.getScene(e);if(!e||!this.checkValidTransition(i))return!1;var n=o(t,"duration",1e3);this._elapsed=0,this._target=i,this._duration=n,this._willSleep=o(t,"sleep",!1),this._willRemove=o(t,"remove",!1);var s=o(t,"onUpdate",null);s&&(this._onUpdate=s,this._onUpdateScope=o(t,"onUpdateScope",this.scene));var a=o(t,"allowInput",!1);this.settings.transitionAllowInput=a;var h=i.sys.settings;return h.isTransition=!0,h.transitionFrom=this.scene,h.transitionDuration=n,h.transitionAllowInput=a,o(t,"moveAbove",!1)?this.manager.moveAbove(this.key,e):o(t,"moveBelow",!1)&&this.manager.moveBelow(this.key,e),i.sys.isSleeping()?i.sys.wake():this.manager.start(e,o(t,"data")),this.systems.events.emit(r.TRANSITION_OUT,i,n),this.systems.events.on(r.UPDATE,this.step,this),!0},checkValidTransition:function(t){return!(!t||t.sys.isActive()||t.sys.isTransitioning()||t===this.scene||this.systems.isTransitioning())},step:function(t,e){this._elapsed+=e,this.transitionProgress=n(this._elapsed/this._duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.transitionProgress),this._elapsed>=this._duration&&this.transitionComplete()},transitionComplete:function(){var t=this._target.sys,e=this._target.sys.settings;this.systems.events.off(r.UPDATE,this.step,this),t.events.emit(r.TRANSITION_COMPLETE,this.scene),e.isTransition=!1,e.transitionFrom=null,this._duration=0,this._target=null,this._onUpdate=null,this._onUpdateScope=null,this._willRemove?this.manager.remove(this.key):this._willSleep?this.systems.sleep():this.manager.stop(this.key)},add:function(t,e,i,n){return this.manager.add(t,e,i,n)},launch:function(t,e){return t&&t!==this.key&&this.manager.queueOp("start",t,e),this},run:function(t,e){return t&&t!==this.key&&this.manager.queueOp("run",t,e),this},pause:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("pause",t,e),this},resume:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("resume",t,e),this},sleep:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("sleep",t,e),this},wake:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("wake",t,e),this},switch:function(t){return t!==this.key&&this.manager.queueOp("switch",this.key,t),this},stop:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",t,e),this},setActive:function(t,e,i){void 0===e&&(e=this.key);var n=this.manager.getScene(e);return n&&n.sys.setActive(t,i),this},setVisible:function(t,e){void 0===e&&(e=this.key);var i=this.manager.getScene(e);return i&&i.sys.setVisible(t),this},isSleeping:function(t){return void 0===t&&(t=this.key),this.manager.isSleeping(t)},isActive:function(t){return void 0===t&&(t=this.key),this.manager.isActive(t)},isPaused:function(t){return void 0===t&&(t=this.key),this.manager.isPaused(t)},isVisible:function(t){return void 0===t&&(t=this.key),this.manager.isVisible(t)},swapPosition:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.swapPosition(t,e),this},moveAbove:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveAbove(t,e),this},moveBelow:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveBelow(t,e),this},remove:function(t){return void 0===t&&(t=this.key),this.manager.remove(t),this},moveUp:function(t){return void 0===t&&(t=this.key),this.manager.moveUp(t),this},moveDown:function(t){return void 0===t&&(t=this.key),this.manager.moveDown(t),this},bringToTop:function(t){return void 0===t&&(t=this.key),this.manager.bringToTop(t),this},sendToBack:function(t){return void 0===t&&(t=this.key),this.manager.sendToBack(t),this},get:function(t){return this.manager.getScene(t)},getIndex:function(t){return void 0===t&&(t=this.key),this.manager.getIndex(t)},shutdown:function(){var t=this.systems.events;t.off(r.SHUTDOWN,this.shutdown,this),t.off(r.POST_UPDATE,this.step,this),t.off(r.TRANSITION_OUT)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.settings=null,this.manager=null}});a.register("ScenePlugin",h,"scenePlugin"),t.exports=h},function(t,e,i){t.exports={List:i(126),Map:i(159),ProcessQueue:i(184),RTree:i(462),Set:i(108),Size:i(366)}},function(t,e,i){var n=i(17),s=i(1299),r={CanvasTexture:i(371),Events:i(119),FilterMode:s,Frame:i(94),Parsers:i(373),Texture:i(180),TextureManager:i(370),TextureSource:i(372)};r=n(!1,r,s),t.exports=r},function(t,e){t.exports={LINEAR:0,NEAREST:1}},function(t,e,i){t.exports={Components:i(137),Parsers:i(1330),Formats:i(31),ImageCollection:i(479),ParseToTilemap:i(224),Tile:i(74),Tilemap:i(488),TilemapCreator:i(1339),TilemapFactory:i(1340),Tileset:i(141),LayerData:i(104),MapData:i(105),ObjectLayer:i(482),DynamicTilemapLayer:i(489),StaticTilemapLayer:i(490)}},function(t,e,i){var n=i(24),s=i(51);t.exports=function(t,e,i,r,o,a,h,l){t<0&&(t=0),e<0&&(e=0),void 0===h&&(h=!0);for(var u=n(t,e,i,r,null,l),c=o-t,d=a-e,f=0;f=0&&p=0&&g=v;o--)(h=c[a][o])&&-1!==h.index&&h.visible&&0!==h.alpha&&i.push(h);else if(2===r)for(a=x;a>=y;a--)for(o=v;c[a]&&o=y;a--)for(o=m;c[a]&&o>=v;o--)(h=c[a][o])&&-1!==h.index&&h.visible&&0!==h.alpha&&i.push(h);return u.tilesDrawn=i.length,u.tilesTotal=d*f,i}},function(t,e,i){var n=i(24),s=i(51),r=i(73);t.exports=function(t,e,i,o,a,h,l){for(var u=-1!==l.collideIndexes.indexOf(t),c=n(e,i,o,a,null,l),d=0;d=0;r--)for(s=n.width-1;s>=0;s--)if((o=n.data[r][s])&&o.index===t){if(a===e)return o;a+=1}}else for(r=0;re)){for(var l=t;l<=e;l++)r(l,i,a);if(h)for(var u=0;u=t&&d.index<=e&&n(d,i)}o&&s(0,0,a.width,a.height,a)}}},function(t,e,i){var n=i(73),s=i(51),r=i(219);t.exports=function(t,e,i,o){void 0===e&&(e=!0),void 0===i&&(i=!0),Array.isArray(t)||(t=[t]);for(var a=0;a0&&n(a,t)}}e&&s(0,0,i.width,i.height,i)}},function(t,e){t.exports=function(t,e,i,n){if("number"==typeof t)n.callbacks[t]=null!==e?{callback:e,callbackContext:i}:void 0;else for(var s=0,r=t.length;s1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f0&&(t.currentPipeline&&t.currentPipeline.vertexCount>0&&t.flush(),r.vertexBuffer=e.vertexBuffer[a],t.setPipeline(r),t.setTexture2D(s[a].glTexture,0),t.gl.drawArrays(r.topology,0,e.vertexCount[a]));r.vertexBuffer=o,r.viewIdentity(),r.modelIdentity()}},function(t,e){t.exports=function(t,e,i,n,s){e.cull(n);var r=e.culledTiles,o=r.length;if(0!==o){var a=t._tempMatrix1,h=t._tempMatrix2,l=t._tempMatrix3;h.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),a.copyFrom(n.matrix);var u=t.currentContext,c=e.gidMap;u.save(),s?(a.multiplyWithOffset(s,-n.scrollX*e.scrollFactorX,-n.scrollY*e.scrollFactorY),h.e=e.x,h.f=e.y,a.multiply(h,l),l.copyToContext(u)):(h.e-=n.scrollX*e.scrollFactorX,h.f-=n.scrollY*e.scrollFactorY,h.copyToContext(u));var d=n.alpha*e.alpha;(!t.antialias||e.scaleX>1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f-1&&this._active.splice(s,1),n.destroy()}for(i=0;i=n.delay)){var s=n.elapsed-n.delay;n.elapsed=n.delay,!n.hasDispatched&&n.callback&&(n.hasDispatched=!0,n.callback.apply(n.callbackScope,n.args)),n.repeatCount>0?(n.repeatCount--,n.elapsed=s,n.hasDispatched=!1):this._pendingRemoval.push(n)}}}},shutdown:function(){var t;for(t=0;t-1&&(e.state=u.REMOVED,s.splice(r,1)):(e.state=u.REMOVED,n.splice(r,1))}for(i.length=0,i=this._add,t=0;t>2],r+=i[(3&n[o])<<4|n[o+1]>>4],r+=i[(15&n[o+1])<<2|n[o+2]>>6],r+=i[63&n[o+2]];return s%3==2?r=r.substring(0,r.length-1)+"=":s%3==1&&(r=r.substring(0,r.length-2)+"=="),r}},function(t,e,i){t.exports={Clone:i(67),Extend:i(17),GetAdvancedValue:i(15),GetFastValue:i(2),GetMinMaxValue:i(1364),GetValue:i(6),HasAll:i(1365),HasAny:i(399),HasValue:i(99),IsPlainObject:i(7),Merge:i(107),MergeRight:i(1366),Pick:i(480),SetValue:i(419)}},function(t,e,i){var n=i(6),s=i(22);t.exports=function(t,e,i,r,o){void 0===o&&(o=i);var a=n(t,e,o);return s(a,i,r)}},function(t,e){t.exports=function(t,e){for(var i=0;i + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Taken from klasse by mattdesl https://github.com/mattdesl/klasse + +function hasGetterOrSetter (def) +{ + return (!!def.get && typeof def.get === 'function') || (!!def.set && typeof def.set === 'function'); +} + +function getProperty (definition, k, isClassDescriptor) +{ + // 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. + var def = (isClassDescriptor) ? definition[k] : Object.getOwnPropertyDescriptor(definition, k); + + if (!isClassDescriptor && def.value && typeof def.value === 'object') + { + def = def.value; + } + + // This might be a regular property, or it may be a getter/setter the user defined in a class. + if (def && hasGetterOrSetter(def)) + { + if (typeof def.enumerable === 'undefined') + { + def.enumerable = true; + } + + if (typeof def.configurable === 'undefined') + { + def.configurable = true; + } + + return def; + } + else + { + return false; + } +} + +function hasNonConfigurable (obj, k) +{ + var prop = Object.getOwnPropertyDescriptor(obj, k); + + if (!prop) + { + return false; + } + + if (prop.value && typeof prop.value === 'object') + { + prop = prop.value; + } + + if (prop.configurable === false) + { + return true; + } + + return false; +} + +/** + * Extends the given `myClass` object's prototype with the properties of `definition`. + * + * @function extend + * @param {Object} ctor The constructor object to mix into. + * @param {Object} definition A dictionary of functions for the class. + * @param {boolean} isClassDescriptor Is the definition a class descriptor? + * @param {Object} [extend] The parent constructor object. + */ +function extend (ctor, definition, isClassDescriptor, extend) +{ + for (var k in definition) + { + if (!definition.hasOwnProperty(k)) + { + continue; + } + + var def = getProperty(definition, k, isClassDescriptor); + + if (def !== false) + { + // If Extends is used, we will check its prototype to see if the final variable exists. + + var parent = extend || ctor; + + if (hasNonConfigurable(parent.prototype, k)) + { + // Just skip the final property + if (Class.ignoreFinals) + { + continue; + } + + // 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. + throw new Error('cannot override final property \'' + k + '\', set Class.ignoreFinals = true to skip'); + } + + Object.defineProperty(ctor.prototype, k, def); + } + else + { + ctor.prototype[k] = definition[k]; + } + } +} + +/** + * Applies the given `mixins` to the prototype of `myClass`. + * + * @function mixin + * @param {Object} myClass The constructor object to mix into. + * @param {Object|Array} mixins The mixins to apply to the constructor. + */ +function mixin (myClass, mixins) +{ + if (!mixins) + { + return; + } + + if (!Array.isArray(mixins)) + { + mixins = [ mixins ]; + } + + for (var i = 0; i < mixins.length; i++) + { + extend(myClass, mixins[i].prototype || mixins[i]); + } +} + +/** + * Creates a new class with the given descriptor. + * The constructor, defined by the name `initialize`, + * is an optional function. If unspecified, an anonymous + * function will be used which calls the parent class (if + * one exists). + * + * You can also use `Extends` and `Mixins` to provide subclassing + * and inheritance. + * + * @class Phaser.Class + * @constructor + * @param {Object} definition a dictionary of functions for the class + * @example + * + * var MyClass = new Phaser.Class({ + * + * initialize: function() { + * this.foo = 2.0; + * }, + * + * bar: function() { + * return this.foo + 5; + * } + * }); + */ +function Class (definition) +{ + if (!definition) + { + definition = {}; + } + + // The variable name here dictates what we see in Chrome debugger + var initialize; + var Extends; + + if (definition.initialize) + { + if (typeof definition.initialize !== 'function') + { + throw new Error('initialize must be a function'); + } + + initialize = definition.initialize; + + // 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). + delete definition.initialize; + } + else if (definition.Extends) + { + var base = definition.Extends; + + initialize = function () + { + base.apply(this, arguments); + }; + } + else + { + initialize = function () {}; + } + + if (definition.Extends) + { + initialize.prototype = Object.create(definition.Extends.prototype); + initialize.prototype.constructor = initialize; + + // For getOwnPropertyDescriptor to work, we need to act directly on the Extends (or Mixin) + + Extends = definition.Extends; + + delete definition.Extends; + } + else + { + initialize.prototype.constructor = initialize; + } + + // Grab the mixins, if they are specified... + var mixins = null; + + if (definition.Mixins) + { + mixins = definition.Mixins; + delete definition.Mixins; + } + + // First, mixin if we can. + mixin(initialize, mixins); + + // Now we grab the actual definition which defines the overrides. + extend(initialize, definition, true, Extends); + + return initialize; +} + +Class.extend = extend; +Class.mixin = mixin; +Class.ignoreFinals = false; + +module.exports = Class; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Finds the key within the top level of the {@link source} object, or returns {@link defaultValue} + * + * @function Phaser.Utils.Objects.GetFastValue + * @since 3.0.0 + * + * @param {object} source - The object to search + * @param {string} key - The key for the property on source. Must exist at the top level of the source object (no periods) + * @param {*} [defaultValue] - The default value to use if the key does not exist. + * + * @return {*} The value if found; otherwise, defaultValue (null if none provided) + */ +var GetFastValue = function (source, key, defaultValue) +{ + var t = typeof(source); + + if (!source || t === 'number' || t === 'string') + { + return defaultValue; + } + else if (source.hasOwnProperty(key) && source[key] !== undefined) + { + return source[key]; + } + else + { + return defaultValue; + } +}; + +module.exports = GetFastValue; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A NOOP (No Operation) callback function. + * + * Used internally by Phaser when it's more expensive to determine if a callback exists + * than it is to just invoke an empty function. + * + * @function Phaser.Utils.NOOP + * @since 3.0.0 + */ +var NOOP = function () +{ + // NOOP +}; + +module.exports = NOOP; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A representation of a vector in 2D space. + * + * A two-component vector. + * + * @class Vector2 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number|Phaser.Types.Math.Vector2Like} [x] - The x component, or an object with `x` and `y` properties. + * @param {number} [y] - The y component. + */ +var Vector2 = new Class({ + + initialize: + + function Vector2 (x, y) + { + /** + * The x component of this Vector. + * + * @name Phaser.Math.Vector2#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y component of this Vector. + * + * @name Phaser.Math.Vector2#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + } + else + { + if (y === undefined) { y = x; } + + this.x = x || 0; + this.y = y || 0; + } + }, + + /** + * Make a clone of this Vector2. + * + * @method Phaser.Math.Vector2#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} A clone of this Vector2. + */ + clone: function () + { + return new Vector2(this.x, this.y); + }, + + /** + * Copy the components of a given Vector into this Vector. + * + * @method Phaser.Math.Vector2#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to copy the components from. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + copy: function (src) + { + this.x = src.x || 0; + this.y = src.y || 0; + + return this; + }, + + /** + * Set the component values of this Vector from a given Vector2Like object. + * + * @method Phaser.Math.Vector2#setFromObject + * @since 3.0.0 + * + * @param {Phaser.Types.Math.Vector2Like} obj - The object containing the component values to set for this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + setFromObject: function (obj) + { + this.x = obj.x || 0; + this.y = obj.y || 0; + + return this; + }, + + /** + * Set the `x` and `y` components of the this Vector to the given `x` and `y` values. + * + * @method Phaser.Math.Vector2#set + * @since 3.0.0 + * + * @param {number} x - The x value to set for this Vector. + * @param {number} [y=x] - The y value to set for this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + set: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * This method is an alias for `Vector2.set`. + * + * @method Phaser.Math.Vector2#setTo + * @since 3.4.0 + * + * @param {number} x - The x value to set for this Vector. + * @param {number} [y=x] - The y value to set for this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + setTo: function (x, y) + { + return this.set(x, y); + }, + + /** + * Sets the `x` and `y` values of this object from a given polar coordinate. + * + * @method Phaser.Math.Vector2#setToPolar + * @since 3.0.0 + * + * @param {number} azimuth - The angular coordinate, in radians. + * @param {number} [radius=1] - The radial coordinate (length). + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + setToPolar: function (azimuth, radius) + { + if (radius == null) { radius = 1; } + + this.x = Math.cos(azimuth) * radius; + this.y = Math.sin(azimuth) * radius; + + return this; + }, + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict equality check against each Vector's components. + * + * @method Phaser.Math.Vector2#equals + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} v - The vector to compare with this Vector. + * + * @return {boolean} Whether the given Vector is equal to this Vector. + */ + equals: function (v) + { + return ((this.x === v.x) && (this.y === v.y)); + }, + + /** + * Calculate the angle between this Vector and the positive x-axis, in radians. + * + * @method Phaser.Math.Vector2#angle + * @since 3.0.0 + * + * @return {number} The angle between this Vector, and the positive x-axis, given in radians. + */ + angle: function () + { + // computes the angle in radians with respect to the positive x-axis + + var angle = Math.atan2(this.y, this.x); + + if (angle < 0) + { + angle += 2 * Math.PI; + } + + return angle; + }, + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * + * @method Phaser.Math.Vector2#add + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to add to this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + add: function (src) + { + this.x += src.x; + this.y += src.y; + + return this; + }, + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * + * @method Phaser.Math.Vector2#subtract + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to subtract from this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + subtract: function (src) + { + this.x -= src.x; + this.y -= src.y; + + return this; + }, + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * + * @method Phaser.Math.Vector2#multiply + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to multiply this Vector by. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + multiply: function (src) + { + this.x *= src.x; + this.y *= src.y; + + return this; + }, + + /** + * Scale this Vector by the given value. + * + * @method Phaser.Math.Vector2#scale + * @since 3.0.0 + * + * @param {number} value - The value to scale this Vector by. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + scale: function (value) + { + if (isFinite(value)) + { + this.x *= value; + this.y *= value; + } + else + { + this.x = 0; + this.y = 0; + } + + return this; + }, + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * + * @method Phaser.Math.Vector2#divide + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to divide this Vector by. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + divide: function (src) + { + this.x /= src.x; + this.y /= src.y; + + return this; + }, + + /** + * Negate the `x` and `y` components of this Vector. + * + * @method Phaser.Math.Vector2#negate + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + negate: function () + { + this.x = -this.x; + this.y = -this.y; + + return this; + }, + + /** + * Calculate the distance between this Vector and the given Vector. + * + * @method Phaser.Math.Vector2#distance + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector. + */ + distance: function (src) + { + var dx = src.x - this.x; + var dy = src.y - this.y; + + return Math.sqrt(dx * dx + dy * dy); + }, + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * + * @method Phaser.Math.Vector2#distanceSq + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector, squared. + */ + distanceSq: function (src) + { + var dx = src.x - this.x; + var dy = src.y - this.y; + + return dx * dx + dy * dy; + }, + + /** + * Calculate the length (or magnitude) of this Vector. + * + * @method Phaser.Math.Vector2#length + * @since 3.0.0 + * + * @return {number} The length of this Vector. + */ + length: function () + { + var x = this.x; + var y = this.y; + + return Math.sqrt(x * x + y * y); + }, + + /** + * Calculate the length of this Vector squared. + * + * @method Phaser.Math.Vector2#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Vector, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + + return x * x + y * y; + }, + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + * + * @method Phaser.Math.Vector2#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var len = x * x + y * y; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + } + + return this; + }, + + /** + * Right-hand normalize (make unit length) this Vector. + * + * @method Phaser.Math.Vector2#normalizeRightHand + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + normalizeRightHand: function () + { + var x = this.x; + + this.x = this.y * -1; + this.y = x; + + return this; + }, + + /** + * Calculate the dot product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector2#dot + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector2 to dot product with this Vector2. + * + * @return {number} The dot product of this Vector and the given Vector. + */ + dot: function (src) + { + return this.x * src.x + this.y * src.y; + }, + + /** + * Calculate the cross product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector2#cross + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector2 to cross with this Vector2. + * + * @return {number} The cross product of this Vector and the given Vector. + */ + cross: function (src) + { + return this.x * src.y - this.y * src.x; + }, + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * + * @method Phaser.Math.Vector2#lerp + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector2 to interpolate towards. + * @param {number} [t=0] - The interpolation percentage, between 0 and 1. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + lerp: function (src, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + + this.x = ax + t * (src.x - ax); + this.y = ay + t * (src.y - ay); + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector2#transformMat3 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} mat - The Matrix3 to transform this Vector2 with. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + transformMat3: function (mat) + { + var x = this.x; + var y = this.y; + var m = mat.val; + + this.x = m[0] * x + m[3] * y + m[6]; + this.y = m[1] * x + m[4] * y + m[7]; + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector2#transformMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector2 with. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + transformMat4: function (mat) + { + var x = this.x; + var y = this.y; + var m = mat.val; + + this.x = m[0] * x + m[4] * y + m[12]; + this.y = m[1] * x + m[5] * y + m[13]; + + return this; + }, + + /** + * Make this Vector the zero vector (0, 0). + * + * @method Phaser.Math.Vector2#reset + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + reset: function () + { + this.x = 0; + this.y = 0; + + return this; + } + +}); + +/** + * A static zero Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.ZERO + * @type {Phaser.Math.Vector2} + * @since 3.1.0 + */ +Vector2.ZERO = new Vector2(); + +/** + * A static right Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.RIGHT + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.RIGHT = new Vector2(1, 0); + +/** + * A static left Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.LEFT + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.LEFT = new Vector2(-1, 0); + +/** + * A static up Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.UP + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.UP = new Vector2(0, -1); + +/** + * A static down Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.DOWN + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.DOWN = new Vector2(0, 1); + +/** + * A static one Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.ONE + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.ONE = new Vector2(1, 1); + +module.exports = Vector2; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GEOM_CONST = __webpack_require__(52); + +/** + * @classdesc + * Defines a Point in 2D space, with an x and y component. + * + * @class Point + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The x coordinate of this Point. + * @param {number} [y=x] - The y coordinate of this Point. + */ +var Point = new Class({ + + initialize: + + function Point (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + /** + * The geometry constant type of this object: `GEOM_CONST.POINT`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Point#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.POINT; + + /** + * The x coordinate of this Point. + * + * @name Phaser.Geom.Point#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The y coordinate of this Point. + * + * @name Phaser.Geom.Point#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + }, + + /** + * Set the x and y coordinates of the point to the given values. + * + * @method Phaser.Geom.Point#setTo + * @since 3.0.0 + * + * @param {number} [x=0] - The x coordinate of this Point. + * @param {number} [y=x] - The y coordinate of this Point. + * + * @return {Phaser.Geom.Point} This Point object. + */ + setTo: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + } + +}); + +module.exports = Point; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Source object +// The key as a string, or an array of keys, i.e. 'banner', or 'banner.hideBanner' +// The default value to use if the key doesn't exist + +/** + * Retrieves a value from an object. + * + * @function Phaser.Utils.Objects.GetValue + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @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. + * + * @return {*} The value of the requested key. + */ +var GetValue = function (source, key, defaultValue) +{ + if (!source || typeof source === 'number') + { + return defaultValue; + } + else if (source.hasOwnProperty(key)) + { + return source[key]; + } + else if (key.indexOf('.') !== -1) + { + var keys = key.split('.'); + var parent = source; + var value = defaultValue; + + // Use for loop here so we can break early + for (var i = 0; i < keys.length; i++) + { + if (parent.hasOwnProperty(keys[i])) + { + // Yes it has a key property, let's carry on down + value = parent[keys[i]]; + + parent = parent[keys[i]]; + } + else + { + // Can't go any further, so reset to default + value = defaultValue; + break; + } + } + + return value; + } + else + { + return defaultValue; + } +}; + +module.exports = GetValue; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * The Game Object Factory is a Scene plugin that allows you to quickly create many common + * types of Game Objects and have them automatically registered with the Scene. + * + * Game Objects directly register themselves with the Factory and inject their own creation + * methods into the class. + * + * @class GameObjectFactory + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object Factory belongs. + */ +var GameObjectFactory = new Class({ + + initialize: + + function GameObjectFactory (scene) + { + /** + * The Scene to which this Game Object Factory belongs. + * + * @name Phaser.GameObjects.GameObjectFactory#scene + * @type {Phaser.Scene} + * @protected + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene.Systems. + * + * @name Phaser.GameObjects.GameObjectFactory#systems + * @type {Phaser.Scenes.Systems} + * @protected + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the Scene Display List. + * + * @name Phaser.GameObjects.GameObjectFactory#displayList + * @type {Phaser.GameObjects.DisplayList} + * @protected + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene Update List. + * + * @name Phaser.GameObjects.GameObjectFactory#updateList + * @type {Phaser.GameObjects.UpdateList} + * @protected + * @since 3.0.0 + */ + this.updateList; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectFactory#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.displayList = this.systems.displayList; + this.updateList = this.systems.updateList; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectFactory#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Adds an existing Game Object to this Scene. + * + * If the Game Object renders, it will be added to the Display List. + * If it has a `preUpdate` method, it will be added to the Update List. + * + * @method Phaser.GameObjects.GameObjectFactory#existing + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.Group)} child - The child to be added to this Scene. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was added. + */ + existing: function (child) + { + if (child.renderCanvas || child.renderWebGL) + { + this.displayList.add(child); + } + + if (child.preUpdate) + { + this.updateList.add(child); + } + + return child; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.GameObjectFactory#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.GameObjectFactory#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + + this.displayList = null; + this.updateList = null; + } + +}); + +/** + * Static method called directly by the Game Object factory functions. + * With this method you can register a custom GameObject factory in the GameObjectFactory, + * providing a name (`factoryType`) and the constructor (`factoryFunction`) in order + * to be called when you call to Phaser.Scene.add[ factoryType ] method. + * + * @method Phaser.GameObjects.GameObjectFactory.register + * @static + * @since 3.0.0 + * + * @param {string} factoryType - The key of the factory that you will use to call to Phaser.Scene.add[ factoryType ] method. + * @param {function} factoryFunction - The constructor function to be called when you invoke to the Phaser.Scene.add method. + */ +GameObjectFactory.register = function (factoryType, factoryFunction) +{ + if (!GameObjectFactory.prototype.hasOwnProperty(factoryType)) + { + GameObjectFactory.prototype[factoryType] = factoryFunction; + } +}; + +/** + * Static method called directly by the Game Object factory functions. + * With this method you can remove a custom GameObject factory registered in the GameObjectFactory, + * providing a its `factoryType`. + * + * @method Phaser.GameObjects.GameObjectFactory.remove + * @static + * @since 3.0.0 + * + * @param {string} factoryType - The key of the factory that you want to remove from the GameObjectFactory. + */ +GameObjectFactory.remove = function (factoryType) +{ + if (GameObjectFactory.prototype.hasOwnProperty(factoryType)) + { + delete GameObjectFactory.prototype[factoryType]; + } +}; + +PluginCache.register('GameObjectFactory', GameObjectFactory, 'add'); + +module.exports = GameObjectFactory; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * + * @function Phaser.Utils.Objects.IsPlainObject + * @since 3.0.0 + * + * @param {object} obj - The object to inspect. + * + * @return {boolean} `true` if the object is plain, otherwise `false`. + */ +var IsPlainObject = function (obj) +{ + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== 'object' || obj.nodeType || obj === obj.window) + { + return false; + } + + // 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 + try + { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) + { + return false; + } + } + catch (e) + { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; +}; + +module.exports = IsPlainObject; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var types = {}; + +/** + * @namespace Phaser.Loader.FileTypesManager + */ + +var FileTypesManager = { + + /** + * Static method called when a LoaderPlugin is created. + * + * Loops through the local types object and injects all of them as + * properties into the LoaderPlugin instance. + * + * @method Phaser.Loader.FileTypesManager.install + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The LoaderPlugin to install the types into. + */ + install: function (loader) + { + for (var key in types) + { + loader[key] = types[key]; + } + }, + + /** + * Static method called directly by the File Types. + * + * The key is a reference to the function used to load the files via the Loader, i.e. `image`. + * + * @method Phaser.Loader.FileTypesManager.register + * @since 3.0.0 + * + * @param {string} key - The key that will be used as the method name in the LoaderPlugin. + * @param {function} factoryFunction - The function that will be called when LoaderPlugin.key is invoked. + */ + register: function (key, factoryFunction) + { + types[key] = factoryFunction; + }, + + /** + * Removed all associated file types. + * + * @method Phaser.Loader.FileTypesManager.destroy + * @since 3.0.0 + */ + destroy: function () + { + types = {}; + } + +}; + +module.exports = FileTypesManager; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} + +// +// 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. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // 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. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; +} + +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; +}; + +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; + +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; +} + + +/***/ }), +/* 10 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.WebGL.Utils + * @since 3.0.0 + */ +module.exports = { + + /** + * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats + * @since 3.0.0 + * + * @param {number} r - Red component in a range from 0.0 to 1.0 + * @param {number} g - Green component in a range from 0.0 to 1.0 + * @param {number} b - Blue component in a range from 0.0 to 1.0 + * @param {number} a - Alpha component in a range from 0.0 to 1.0 + * + * @return {number} [description] + */ + getTintFromFloats: function (r, g, b, a) + { + var ur = ((r * 255.0)|0) & 0xFF; + var ug = ((g * 255.0)|0) & 0xFF; + var ub = ((b * 255.0)|0) & 0xFF; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlpha: function (rgb, a) + { + var ua = ((a * 255.0)|0) & 0xFF; + return ((ua << 24) | rgb) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a + * swizzled Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlphaAndSwap: function (rgb, a) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; + }, + + /** + * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 + * + * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB + * @since 3.0.0 + * + * @param {number} rgb - RGB packed as a Uint24 + * + * @return {array} Array of floats representing each component as a float + */ + getFloatsFromUintRGB: function (rgb) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + + return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; + }, + + /** + * Counts how many attributes of 32 bits a vertex has + * + * @function Phaser.Renderer.WebGL.Utils.getComponentCount + * @since 3.0.0 + * + * @param {array} attributes - Array of attributes + * @param {WebGLRenderingContext} glContext - WebGLContext used for check types + * + * @return {number} Count of 32 bit attributes in vertex + */ + getComponentCount: function (attributes, glContext) + { + var count = 0; + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + + if (element.type === glContext.FLOAT) + { + count += element.size; + } + else + { + count += 1; // We'll force any other type to be 32 bit. for now + } + } + + return count; + } + +}; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Contains = __webpack_require__(53); +var GetPoint = __webpack_require__(161); +var GetPoints = __webpack_require__(293); +var GEOM_CONST = __webpack_require__(52); +var Line = __webpack_require__(61); +var Random = __webpack_require__(164); + +/** + * @classdesc + * Encapsulates a 2D rectangle defined by its corner point in the top-left and its extends in x (width) and y (height) + * + * @class Rectangle + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The X coordinate of the top left corner of the Rectangle. + * @param {number} [y=0] - The Y coordinate of the top left corner of the Rectangle. + * @param {number} [width=0] - The width of the Rectangle. + * @param {number} [height=0] - The height of the Rectangle. + */ +var Rectangle = new Class({ + + initialize: + + function Rectangle (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.RECTANGLE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Rectangle#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.RECTANGLE; + + /** + * The X coordinate of the top left corner of the Rectangle. + * + * @name Phaser.Geom.Rectangle#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The Y coordinate of the top left corner of the Rectangle. + * + * @name Phaser.Geom.Rectangle#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + + /** + * The width of the Rectangle, i.e. the distance between its left side (defined by `x`) and its right side. + * + * @name Phaser.Geom.Rectangle#width + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the Rectangle, i.e. the distance between its top side (defined by `y`) and its bottom side. + * + * @name Phaser.Geom.Rectangle#height + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.height = height; + }, + + /** + * Checks if the given point is inside the Rectangle's bounds. + * + * @method Phaser.Geom.Rectangle#contains + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is within the Rectangle's bounds, otherwise `false`. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. + * + * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. + * + * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. + * + * @method Phaser.Geom.Rectangle#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [output,$return] + * + * @param {number} position - The normalized distance into the Rectangle's perimeter to return. + * @param {(Phaser.Geom.Point|object)} [output] - An object to update with the `x` and `y` coordinates of the point. + * + * @return {(Phaser.Geom.Point|object)} The updated `output` object, or a new Point if no `output` object was given. + */ + getPoint: function (position, output) + { + return GetPoint(this, position, output); + }, + + /** + * 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 {(array|Phaser.Geom.Point[])} [output] - An array to which to append the points. + * + * @return {(array|Phaser.Geom.Point[])} The modified `output` array, or a new array if none was provided. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a random point within the Rectangle's bounds. + * + * @method Phaser.Geom.Rectangle#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} [point] - The object in which to store the `x` and `y` coordinates of the point. + * + * @return {Phaser.Geom.Point} The updated `point`, or a new Point if none was provided. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets the position, width, and height of the Rectangle. + * + * @method Phaser.Geom.Rectangle#setTo + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the top left corner of the Rectangle. + * @param {number} y - The Y coordinate of the top left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setTo: function (x, y, width, height) + { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + }, + + /** + * Resets the position, width, and height of the Rectangle to 0. + * + * @method Phaser.Geom.Rectangle#setEmpty + * @since 3.0.0 + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setEmpty: function () + { + return this.setTo(0, 0, 0, 0); + }, + + /** + * Sets the position of the Rectangle. + * + * @method Phaser.Geom.Rectangle#setPosition + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the top left corner of the Rectangle. + * @param {number} [y=x] - The Y coordinate of the top left corner of the Rectangle. + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Sets the width and height of the Rectangle. + * + * @method Phaser.Geom.Rectangle#setSize + * @since 3.0.0 + * + * @param {number} width - The width to set the Rectangle to. + * @param {number} [height=width] - The height to set the Rectangle to. + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + this.width = width; + this.height = height; + + return this; + }, + + /** + * Determines if the Rectangle is empty. A Rectangle is empty if its width or height is less than or equal to 0. + * + * @method Phaser.Geom.Rectangle#isEmpty + * @since 3.0.0 + * + * @return {boolean} `true` if the Rectangle is empty. A Rectangle object is empty if its width or height is less than or equal to 0. + */ + isEmpty: function () + { + return (this.width <= 0 || this.height <= 0); + }, + + /** + * Returns a Line object that corresponds to the top of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineA + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the top of this Rectangle. + */ + getLineA: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x, this.y, this.right, this.y); + + return line; + }, + + /** + * Returns a Line object that corresponds to the right of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineB + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the right of this Rectangle. + */ + getLineB: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.right, this.y, this.right, this.bottom); + + return line; + }, + + /** + * Returns a Line object that corresponds to the bottom of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineC + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the bottom of this Rectangle. + */ + getLineC: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.right, this.bottom, this.x, this.bottom); + + return line; + }, + + /** + * Returns a Line object that corresponds to the left of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineD + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the left of this Rectangle. + */ + getLineD: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x, this.bottom, this.x, this.y); + + return line; + }, + + /** + * The x coordinate of the left of the Rectangle. + * Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * + * @name Phaser.Geom.Rectangle#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.x; + }, + + set: function (value) + { + if (value >= this.right) + { + this.width = 0; + } + else + { + this.width = this.right - value; + } + + this.x = value; + } + + }, + + /** + * The sum of the x and width properties. + * Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. + * + * @name Phaser.Geom.Rectangle#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.x + this.width; + }, + + set: function (value) + { + if (value <= this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + + }, + + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * + * @name Phaser.Geom.Rectangle#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.y; + }, + + set: function (value) + { + if (value >= this.bottom) + { + this.height = 0; + } + else + { + this.height = (this.bottom - value); + } + + this.y = value; + } + + }, + + /** + * The sum of the y and height properties. + * Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * + * @name Phaser.Geom.Rectangle#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.y + this.height; + }, + + set: function (value) + { + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + + }, + + /** + * The x coordinate of the center of the Rectangle. + * + * @name Phaser.Geom.Rectangle#centerX + * @type {number} + * @since 3.0.0 + */ + centerX: { + + get: function () + { + return this.x + (this.width / 2); + }, + + set: function (value) + { + this.x = value - (this.width / 2); + } + + }, + + /** + * The y coordinate of the center of the Rectangle. + * + * @name Phaser.Geom.Rectangle#centerY + * @type {number} + * @since 3.0.0 + */ + centerY: { + + get: function () + { + return this.y + (this.height / 2); + }, + + set: function (value) + { + this.y = value - (this.height / 2); + } + + } + +}); + +module.exports = Rectangle; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Components + */ + +module.exports = { + + Alpha: __webpack_require__(559), + AlphaSingle: __webpack_require__(287), + Animation: __webpack_require__(288), + BlendMode: __webpack_require__(291), + ComputedSize: __webpack_require__(578), + Crop: __webpack_require__(579), + Depth: __webpack_require__(292), + Flip: __webpack_require__(580), + GetBounds: __webpack_require__(581), + Mask: __webpack_require__(296), + Origin: __webpack_require__(598), + PathFollower: __webpack_require__(599), + Pipeline: __webpack_require__(121), + ScrollFactor: __webpack_require__(299), + Size: __webpack_require__(600), + Texture: __webpack_require__(601), + TextureCrop: __webpack_require__(602), + Tint: __webpack_require__(603), + ToJSON: __webpack_require__(300), + Transform: __webpack_require__(301), + TransformMatrix: __webpack_require__(35), + Visible: __webpack_require__(302) + +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = { + + /** + * The value of PI * 2. + * + * @name Phaser.Math.PI2 + * @type {number} + * @since 3.0.0 + */ + PI2: Math.PI * 2, + + /** + * The value of PI * 0.5. + * + * @name Phaser.Math.TAU + * @type {number} + * @since 3.0.0 + */ + TAU: Math.PI * 0.5, + + /** + * An epsilon value (1.0e-6) + * + * @name Phaser.Math.EPSILON + * @type {number} + * @since 3.0.0 + */ + EPSILON: 1.0e-6, + + /** + * For converting degrees to radians (PI / 180) + * + * @name Phaser.Math.DEG_TO_RAD + * @type {number} + * @since 3.0.0 + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * For converting radians to degrees (180 / PI) + * + * @name Phaser.Math.RAD_TO_DEG + * @type {number} + * @since 3.0.0 + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * An instance of the Random Number Generator. + * This is not set until the Game boots. + * + * @name Phaser.Math.RND + * @type {Phaser.Math.RandomDataGenerator} + * @since 3.0.0 + */ + RND: null, + + /** + * The minimum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MIN_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, + + /** + * The maximum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MAX_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 + +}; + +module.exports = MATH_CONST; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var ComponentsToJSON = __webpack_require__(300); +var DataManager = __webpack_require__(101); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(102); + +/** + * @classdesc + * The base class that all Game Objects extend. + * You don't create GameObjects directly and they cannot be added to the display list. + * Instead, use them as the base for your own custom classes. + * + * @class GameObject + * @memberof Phaser.GameObjects + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. + * @param {string} type - A textual representation of the type of Game Object, i.e. `sprite`. + */ +var GameObject = new Class({ + + Extends: EventEmitter, + + initialize: + + function GameObject (scene, type) + { + EventEmitter.call(this); + + /** + * The Scene to which this Game Object belongs. + * Game Objects can only belong to one Scene. + * + * @name Phaser.GameObjects.GameObject#scene + * @type {Phaser.Scene} + * @protected + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A textual representation of this Game Object, i.e. `sprite`. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.GameObjects.GameObject#type + * @type {string} + * @since 3.0.0 + */ + this.type = type; + + /** + * The current state of this Game Object. + * + * Phaser itself will never modify this value, although plugins may do so. + * + * Use this property to track the state of a Game Object during its lifetime. For example, it could change from + * a state of 'moving', to 'attacking', to 'dead'. The state value should be an integer (ideally mapped to a constant + * in your game code), or a string. These are recommended to keep it light and simple, with fast comparisons. + * If you need to store complex data about your Game Object, look at using the Data Component instead. + * + * @name Phaser.GameObjects.GameObject#state + * @type {(integer|string)} + * @since 3.16.0 + */ + this.state = 0; + + /** + * The parent Container of this Game Object, if it has one. + * + * @name Phaser.GameObjects.GameObject#parentContainer + * @type {Phaser.GameObjects.Container} + * @since 3.4.0 + */ + this.parentContainer = null; + + /** + * The name of this Game Object. + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.GameObjects.GameObject#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * The active state of this Game Object. + * A Game Object with an active state of `true` is processed by the Scenes UpdateList, if added to it. + * An active object is one which is having its logic and internal systems updated. + * + * @name Phaser.GameObjects.GameObject#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * The Tab Index of the Game Object. + * Reserved for future use by plugins and the Input Manager. + * + * @name Phaser.GameObjects.GameObject#tabIndex + * @type {integer} + * @default -1 + * @since 3.0.0 + */ + this.tabIndex = -1; + + /** + * A Data Manager. + * It allows you to store, query and get key/value paired information specific to this Game Object. + * `null` by default. Automatically created if you use `getData` or `setData` or `setDataEnabled`. + * + * @name Phaser.GameObjects.GameObject#data + * @type {Phaser.Data.DataManager} + * @default null + * @since 3.0.0 + */ + this.data = null; + + /** + * The flags that are compared against `RENDER_MASK` to determine if this Game Object will render or not. + * The bits are 0001 | 0010 | 0100 | 1000 set by the components Visible, Alpha, Transform and Texture respectively. + * If those components are not used by your custom class then you can use this bitmask as you wish. + * + * @name Phaser.GameObjects.GameObject#renderFlags + * @type {integer} + * @default 15 + * @since 3.0.0 + */ + this.renderFlags = 15; + + /** + * A bitmask that controls if this Game Object is drawn by a Camera or not. + * Not usually set directly, instead call `Camera.ignore`, however you can + * set this property directly using the Camera.id property: + * + * @example + * this.cameraFilter |= camera.id + * + * @name Phaser.GameObjects.GameObject#cameraFilter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.cameraFilter = 0; + + /** + * If this Game Object is enabled for input then this property will contain an InteractiveObject instance. + * Not usually set directly. Instead call `GameObject.setInteractive()`. + * + * @name Phaser.GameObjects.GameObject#input + * @type {?Phaser.Types.Input.InteractiveObject} + * @default null + * @since 3.0.0 + */ + this.input = null; + + /** + * If this Game Object is enabled for physics then this property will contain a reference to a Physics Body. + * + * @name Phaser.GameObjects.GameObject#body + * @type {?(object|Phaser.Physics.Arcade.Body|Phaser.Physics.Impact.Body)} + * @default null + * @since 3.0.0 + */ + this.body = null; + + /** + * This Game Object will ignore all calls made to its destroy method if this flag is set to `true`. + * This includes calls that may come from a Group, Container or the Scene itself. + * While it allows you to persist a Game Object across Scenes, please understand you are entirely + * responsible for managing references to and from this Game Object. + * + * @name Phaser.GameObjects.GameObject#ignoreDestroy + * @type {boolean} + * @default false + * @since 3.5.0 + */ + this.ignoreDestroy = false; + + // Tell the Scene to re-sort the children + scene.sys.queueDepthSort(); + }, + + /** + * Sets the `active` property of this Game Object and returns this Game Object for further chaining. + * A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. + * + * @method Phaser.GameObjects.GameObject#setActive + * @since 3.0.0 + * + * @param {boolean} value - True if this Game Object should be set as active, false if not. + * + * @return {this} This GameObject. + */ + setActive: function (value) + { + this.active = value; + + return this; + }, + + /** + * Sets the `name` property of this Game Object and returns this Game Object for further chaining. + * The `name` property is not populated by Phaser and is presented for your own use. + * + * @method Phaser.GameObjects.GameObject#setName + * @since 3.0.0 + * + * @param {string} value - The name to be given to this Game Object. + * + * @return {this} This GameObject. + */ + setName: function (value) + { + this.name = value; + + return this; + }, + + /** + * Sets the current state of this Game Object. + * + * Phaser itself will never modify the State of a Game Object, although plugins may do so. + * + * For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. + * The state value should typically be an integer (ideally mapped to a constant + * in your game code), but could also be a string. It is recommended to keep it light and simple. + * If you need to store complex data about your Game Object, look at using the Data Component instead. + * + * @method Phaser.GameObjects.GameObject#setState + * @since 3.16.0 + * + * @param {(integer|string)} value - The state of the Game Object. + * + * @return {this} This GameObject. + */ + setState: function (value) + { + this.state = value; + + return this; + }, + + /** + * Adds a Data Manager component to this Game Object. + * + * @method Phaser.GameObjects.GameObject#setDataEnabled + * @since 3.0.0 + * @see Phaser.Data.DataManager + * + * @return {this} This GameObject. + */ + setDataEnabled: function () + { + if (!this.data) + { + this.data = new DataManager(this); + } + + return this; + }, + + /** + * Allows you to store a key value pair within this Game Objects Data Manager. + * + * If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled + * before setting the value. + * + * If the key doesn't already exist in the Data Manager then it is created. + * + * ```javascript + * sprite.setData('name', 'Red Gem Stone'); + * ``` + * + * You can also pass in an object of key value pairs as the first argument: + * + * ```javascript + * sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); + * ``` + * + * To get a value back again you can call `getData`: + * + * ```javascript + * sprite.getData('gold'); + * ``` + * + * Or you can access the value directly via the `values` property, where it works like any other variable: + * + * ```javascript + * sprite.data.values.gold += 50; + * ``` + * + * When the value is first set, a `setdata` event is emitted from this Game Object. + * + * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. + * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. + * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. + * + * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * + * @method Phaser.GameObjects.GameObject#setData + * @since 3.0.0 + * + * @param {(string|object)} key - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. + * @param {*} [data] - The value to set for the given key. If an object is provided as the key this argument is ignored. + * + * @return {this} This GameObject. + */ + setData: function (key, value) + { + if (!this.data) + { + this.data = new DataManager(this); + } + + this.data.set(key, value); + + return this; + }, + + /** + * Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. + * + * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: + * + * ```javascript + * sprite.getData('gold'); + * ``` + * + * Or access the value directly: + * + * ```javascript + * sprite.data.values.gold; + * ``` + * + * You can also pass in an array of keys, in which case an array of values will be returned: + * + * ```javascript + * sprite.getData([ 'gold', 'armor', 'health' ]); + * ``` + * + * This approach is useful for destructuring arrays in ES6. + * + * @method Phaser.GameObjects.GameObject#getData + * @since 3.0.0 + * + * @param {(string|string[])} key - The key of the value to retrieve, or an array of keys. + * + * @return {*} The value belonging to the given key, or an array of values, the order of which will match the input array. + */ + getData: function (key) + { + if (!this.data) + { + this.data = new DataManager(this); + } + + return this.data.get(key); + }, + + /** + * 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. + * + * @method Phaser.GameObjects.GameObject#setInteractive + * @since 3.0.0 + * + * @param {(Phaser.Types.Input.InputConfiguration|any)} [shape] - 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} [callback] - A callback to be invoked when the Game Object is interacted with. 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. + */ + setInteractive: function (shape, callback, dropZone) + { + this.scene.sys.input.enable(this, shape, callback, dropZone); + + return this; + }, + + /** + * If this Game Object has previously been enabled for input, this will disable it. + * + * An object that is disabled for input stops processing or being considered for + * input events, but can be turned back on again at any time by simply calling + * `setInteractive()` with no arguments provided. + * + * If want to completely remove interaction from this Game Object then use `removeInteractive` instead. + * + * @method Phaser.GameObjects.GameObject#disableInteractive + * @since 3.7.0 + * + * @return {this} This GameObject. + */ + disableInteractive: function () + { + if (this.input) + { + this.input.enabled = false; + } + + return this; + }, + + /** + * If this Game Object has previously been enabled for input, this will queue it + * for removal, causing it to no longer be interactive. The removal happens on + * the next game step, it is not immediate. + * + * The Interactive Object that was assigned to this Game Object will be destroyed, + * removed from the Input Manager and cleared from this Game Object. + * + * If you wish to re-enable this Game Object at a later date you will need to + * re-create its InteractiveObject by calling `setInteractive` again. + * + * If you wish to only temporarily stop an object from receiving input then use + * `disableInteractive` instead, as that toggles the interactive state, where-as + * this erases it completely. + * + * If you wish to resize a hit area, don't remove and then set it as being + * interactive. Instead, access the hitarea object directly and resize the shape + * being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the + * shape is a Rectangle, which it is by default.) + * + * @method Phaser.GameObjects.GameObject#removeInteractive + * @since 3.7.0 + * + * @return {this} This GameObject. + */ + removeInteractive: function () + { + this.scene.sys.input.clear(this); + + this.input = undefined; + + return this; + }, + + /** + * To be overridden by custom GameObjects. Allows base objects to be used in a Pool. + * + * @method Phaser.GameObjects.GameObject#update + * @since 3.0.0 + * + * @param {...*} [args] - args + */ + update: function () + { + }, + + /** + * Returns a JSON representation of the Game Object. + * + * @method Phaser.GameObjects.GameObject#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ + toJSON: function () + { + return ComponentsToJSON(this); + }, + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * Also checks the Game Object against the given Cameras exclusion list. + * + * @method Phaser.GameObjects.GameObject#willRender + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object. + * + * @return {boolean} True if the Game Object should be rendered, otherwise false. + */ + willRender: function (camera) + { + return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id))); + }, + + /** + * Returns an array containing the display list index of either this Game Object, or if it has one, + * its parent Container. It then iterates up through all of the parent containers until it hits the + * root of the display list (which is index 0 in the returned array). + * + * Used internally by the InputPlugin but also useful if you wish to find out the display depth of + * this Game Object and all of its ancestors. + * + * @method Phaser.GameObjects.GameObject#getIndexList + * @since 3.4.0 + * + * @return {integer[]} An array of display list position indexes. + */ + getIndexList: function () + { + // eslint-disable-next-line consistent-this + var child = this; + var parent = this.parentContainer; + + var indexes = []; + + while (parent) + { + // indexes.unshift([parent.getIndex(child), parent.name]); + indexes.unshift(parent.getIndex(child)); + + child = parent; + + if (!parent.parentContainer) + { + break; + } + else + { + parent = parent.parentContainer; + } + } + + // indexes.unshift([this.scene.sys.displayList.getIndex(child), 'root']); + indexes.unshift(this.scene.sys.displayList.getIndex(child)); + + return indexes; + }, + + /** + * Destroys this Game Object removing it from the Display List and Update List and + * severing all ties to parent resources. + * + * Also removes itself from the Input Manager and Physics Manager if previously enabled. + * + * Use this to remove a Game Object from your game if you don't ever plan to use it again. + * As long as no reference to it exists within your own code it should become free for + * garbage collection by the browser. + * + * If you just want to temporarily disable an object then look at using the + * Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. + * + * @method Phaser.GameObjects.GameObject#destroy + * @fires Phaser.GameObjects.Events#DESTROY + * @since 3.0.0 + * + * @param {boolean} [fromScene=false] - Is this Game Object being destroyed as the result of a Scene shutdown? + */ + destroy: function (fromScene) + { + if (fromScene === undefined) { fromScene = false; } + + // This Game Object has already been destroyed + if (!this.scene || this.ignoreDestroy) + { + return; + } + + if (this.preDestroy) + { + this.preDestroy.call(this); + } + + this.emit(Events.DESTROY, this); + + var sys = this.scene.sys; + + if (!fromScene) + { + sys.displayList.remove(this); + sys.updateList.remove(this); + } + + if (this.input) + { + sys.input.clear(this); + this.input = undefined; + } + + if (this.data) + { + this.data.destroy(); + + this.data = undefined; + } + + if (this.body) + { + this.body.destroy(); + this.body = undefined; + } + + // Tell the Scene to re-sort the children + if (!fromScene) + { + sys.queueDepthSort(); + } + + this.active = false; + this.visible = false; + + this.scene = undefined; + + this.parentContainer = undefined; + + this.removeAllListeners(); + } + +}); + +/** + * The bitmask that `GameObject.renderFlags` is compared against to determine if the Game Object will render or not. + * + * @constant {integer} RENDER_MASK + * @memberof Phaser.GameObjects.GameObject + * @default + */ +GameObject.RENDER_MASK = 15; + +module.exports = GameObject; + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH = __webpack_require__(181); +var GetValue = __webpack_require__(5); + +/** + * Retrieves a value from an object. Allows for more advanced selection options, including: + * + * Allowed types: + * + * Implicit + * { + * x: 4 + * } + * + * From function + * { + * x: function () + * } + * + * Randomly pick one element from the array + * { + * x: [a, b, c, d, e, f] + * } + * + * Random integer between min and max: + * { + * x: { randInt: [min, max] } + * } + * + * Random float between min and max: + * { + * x: { randFloat: [min, max] } + * } + * + * + * @function Phaser.Utils.Objects.GetAdvancedValue + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @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. + * + * @return {*} The value of the requested key. + */ +var GetAdvancedValue = function (source, key, defaultValue) +{ + var value = GetValue(source, key, null); + + if (value === null) + { + return defaultValue; + } + else if (Array.isArray(value)) + { + return MATH.RND.pick(value); + } + else if (typeof value === 'object') + { + if (value.hasOwnProperty('randInt')) + { + return MATH.RND.integerInRange(value.randInt[0], value.randInt[1]); + } + else if (value.hasOwnProperty('randFloat')) + { + return MATH.RND.realInRange(value.randFloat[0], value.randFloat[1]); + } + } + else if (typeof value === 'function') + { + return value(key); + } + + return value; +}; + +module.exports = GetAdvancedValue; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * The Game Object Creator is a Scene plugin that allows you to quickly create many common + * types of Game Objects and return them. Unlike the Game Object Factory, they are not automatically + * added to the Scene. + * + * Game Objects directly register themselves with the Creator and inject their own creation + * methods into the class. + * + * @class GameObjectCreator + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object Factory belongs. + */ +var GameObjectCreator = new Class({ + + initialize: + + function GameObjectCreator (scene) + { + /** + * The Scene to which this Game Object Creator belongs. + * + * @name Phaser.GameObjects.GameObjectCreator#scene + * @type {Phaser.Scene} + * @protected + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene.Systems. + * + * @name Phaser.GameObjects.GameObjectCreator#systems + * @type {Phaser.Scenes.Systems} + * @protected + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the Scene Display List. + * + * @name Phaser.GameObjects.GameObjectCreator#displayList + * @type {Phaser.GameObjects.DisplayList} + * @protected + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene Update List. + * + * @name Phaser.GameObjects.GameObjectCreator#updateList + * @type {Phaser.GameObjects.UpdateList} + * @protected + * @since 3.0.0 + */ + this.updateList; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectCreator#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.displayList = this.systems.displayList; + this.updateList = this.systems.updateList; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectCreator#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.GameObjectCreator#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.GameObjectCreator#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + this.displayList = null; + this.updateList = null; + } + +}); + +// Static method called directly by the Game Object creator functions + +GameObjectCreator.register = function (factoryType, factoryFunction) +{ + if (!GameObjectCreator.prototype.hasOwnProperty(factoryType)) + { + GameObjectCreator.prototype[factoryType] = factoryFunction; + } +}; + +GameObjectCreator.remove = function (factoryType) +{ + if (GameObjectCreator.prototype.hasOwnProperty(factoryType)) + { + delete GameObjectCreator.prototype[factoryType]; + } +}; + +PluginCache.register('GameObjectCreator', GameObjectCreator, 'make'); + +module.exports = GameObjectCreator; + + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsPlainObject = __webpack_require__(7); + +// @param {boolean} deep - Perform a deep copy? +// @param {object} target - The target object to copy to. +// @return {object} The extended object. + +/** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @function Phaser.Utils.Objects.Extend + * @since 3.0.0 + * + * @return {object} The extended object. + */ +var Extend = function () +{ + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') + { + deep = target; + target = arguments[1] || {}; + + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (IsPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && IsPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +module.exports = Extend; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Scenes.Events + */ + +module.exports = { + + BOOT: __webpack_require__(732), + CREATE: __webpack_require__(733), + DESTROY: __webpack_require__(734), + PAUSE: __webpack_require__(735), + POST_UPDATE: __webpack_require__(736), + PRE_UPDATE: __webpack_require__(737), + READY: __webpack_require__(738), + RENDER: __webpack_require__(739), + RESUME: __webpack_require__(740), + SHUTDOWN: __webpack_require__(741), + SLEEP: __webpack_require__(742), + START: __webpack_require__(743), + TRANSITION_COMPLETE: __webpack_require__(744), + TRANSITION_INIT: __webpack_require__(745), + TRANSITION_OUT: __webpack_require__(746), + TRANSITION_START: __webpack_require__(747), + TRANSITION_WAKE: __webpack_require__(748), + UPDATE: __webpack_require__(749), + WAKE: __webpack_require__(750) + +}; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + +/** +* The `Matter.Common` module contains utility functions that are common to all modules. +* +* @class Common +*/ + +var Common = {}; + +module.exports = Common; + +(function() { + + Common._nextId = 0; + Common._seed = 0; + Common._nowStartTime = +(new Date()); + + /** + * Extends the object in the first argument using the object in the second argument. + * @method extend + * @param {} obj + * @param {boolean} deep + * @return {} obj extended + */ + Common.extend = function(obj, deep) { + var argsStart, + args, + deepClone; + + if (typeof deep === 'boolean') { + argsStart = 2; + deepClone = deep; + } else { + argsStart = 1; + deepClone = true; + } + + for (var i = argsStart; i < arguments.length; i++) { + var source = arguments[i]; + + if (source) { + for (var prop in source) { + if (deepClone && source[prop] && source[prop].constructor === Object) { + if (!obj[prop] || obj[prop].constructor === Object) { + obj[prop] = obj[prop] || {}; + Common.extend(obj[prop], deepClone, source[prop]); + } else { + obj[prop] = source[prop]; + } + } else { + obj[prop] = source[prop]; + } + } + } + } + + return obj; + }; + + /** + * Creates a new clone of the object, if deep is true references will also be cloned. + * @method clone + * @param {} obj + * @param {bool} deep + * @return {} obj cloned + */ + Common.clone = function(obj, deep) { + return Common.extend({}, deep, obj); + }; + + /** + * Returns the list of keys for the given object. + * @method keys + * @param {} obj + * @return {string[]} keys + */ + Common.keys = function(obj) { + if (Object.keys) + return Object.keys(obj); + + // avoid hasOwnProperty for performance + var keys = []; + for (var key in obj) + keys.push(key); + return keys; + }; + + /** + * Returns the list of values for the given object. + * @method values + * @param {} obj + * @return {array} Array of the objects property values + */ + Common.values = function(obj) { + var values = []; + + if (Object.keys) { + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + } + + // avoid hasOwnProperty for performance + for (var key in obj) + values.push(obj[key]); + return values; + }; + + /** + * Gets a value from `base` relative to the `path` string. + * @method get + * @param {} obj The base object + * @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz' + * @param {number} [begin] Path slice begin + * @param {number} [end] Path slice end + * @return {} The object at the given path + */ + Common.get = function(obj, path, begin, end) { + path = path.split('.').slice(begin, end); + + for (var i = 0; i < path.length; i += 1) { + obj = obj[path[i]]; + } + + return obj; + }; + + /** + * Sets a value on `base` relative to the given `path` string. + * @method set + * @param {} obj The base object + * @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz' + * @param {} val The value to set + * @param {number} [begin] Path slice begin + * @param {number} [end] Path slice end + * @return {} Pass through `val` for chaining + */ + Common.set = function(obj, path, val, begin, end) { + var parts = path.split('.').slice(begin, end); + Common.get(obj, path, 0, -1)[parts[parts.length - 1]] = val; + return val; + }; + + /** + * Shuffles the given array in-place. + * The function uses a seeded random generator. + * @method shuffle + * @param {array} array + * @return {array} array shuffled randomly + */ + Common.shuffle = function(array) { + for (var i = array.length - 1; i > 0; i--) { + var j = Math.floor(Common.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + return array; + }; + + /** + * Randomly chooses a value from a list with equal probability. + * The function uses a seeded random generator. + * @method choose + * @param {array} choices + * @return {object} A random choice object from the array + */ + Common.choose = function(choices) { + return choices[Math.floor(Common.random() * choices.length)]; + }; + + /** + * Returns true if the object is a HTMLElement, otherwise false. + * @method isElement + * @param {object} obj + * @return {boolean} True if the object is a HTMLElement, otherwise false + */ + Common.isElement = function(obj) { + if (typeof HTMLElement !== 'undefined') { + return obj instanceof HTMLElement; + } + + return !!(obj && obj.nodeType && obj.nodeName); + }; + + /** + * Returns true if the object is an array. + * @method isArray + * @param {object} obj + * @return {boolean} True if the object is an array, otherwise false + */ + Common.isArray = function(obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + /** + * Returns true if the object is a function. + * @method isFunction + * @param {object} obj + * @return {boolean} True if the object is a function, otherwise false + */ + Common.isFunction = function(obj) { + return typeof obj === "function"; + }; + + /** + * Returns true if the object is a plain object. + * @method isPlainObject + * @param {object} obj + * @return {boolean} True if the object is a plain object, otherwise false + */ + Common.isPlainObject = function(obj) { + return typeof obj === 'object' && obj.constructor === Object; + }; + + /** + * Returns true if the object is a string. + * @method isString + * @param {object} obj + * @return {boolean} True if the object is a string, otherwise false + */ + Common.isString = function(obj) { + return toString.call(obj) === '[object String]'; + }; + + /** + * Returns the given value clamped between a minimum and maximum value. + * @method clamp + * @param {number} value + * @param {number} min + * @param {number} max + * @return {number} The value clamped between min and max inclusive + */ + Common.clamp = function(value, min, max) { + if (value < min) + return min; + if (value > max) + return max; + return value; + }; + + /** + * Returns the sign of the given value. + * @method sign + * @param {number} value + * @return {number} -1 if negative, +1 if 0 or positive + */ + Common.sign = function(value) { + return value < 0 ? -1 : 1; + }; + + /** + * Returns the current timestamp since the time origin (e.g. from page load). + * The result will be high-resolution including decimal places if available. + * @method now + * @return {number} the current timestamp + */ + Common.now = function() { + if (typeof window !== 'undefined' && window.performance) { + if (window.performance.now) { + return window.performance.now(); + } else if (window.performance.webkitNow) { + return window.performance.webkitNow(); + } + } + + return (new Date()) - Common._nowStartTime; + }; + + /** + * Returns a random value between a minimum and a maximum value inclusive. + * The function uses a seeded random generator. + * @method random + * @param {number} min + * @param {number} max + * @return {number} A random number between min and max inclusive + */ + Common.random = function(min, max) { + min = (typeof min !== "undefined") ? min : 0; + max = (typeof max !== "undefined") ? max : 1; + return min + _seededRandom() * (max - min); + }; + + var _seededRandom = function() { + // https://en.wikipedia.org/wiki/Linear_congruential_generator + Common._seed = (Common._seed * 9301 + 49297) % 233280; + return Common._seed / 233280; + }; + + /** + * Converts a CSS hex colour string into an integer. + * @method colorToNumber + * @param {string} colorString + * @return {number} An integer representing the CSS hex string + */ + Common.colorToNumber = function(colorString) { + colorString = colorString.replace('#',''); + + if (colorString.length == 3) { + colorString = colorString.charAt(0) + colorString.charAt(0) + + colorString.charAt(1) + colorString.charAt(1) + + colorString.charAt(2) + colorString.charAt(2); + } + + return parseInt(colorString, 16); + }; + + /** + * The console logging level to use, where each level includes all levels above and excludes the levels below. + * The default level is 'debug' which shows all console messages. + * + * Possible level values are: + * - 0 = None + * - 1 = Debug + * - 2 = Info + * - 3 = Warn + * - 4 = Error + * @property Common.logLevel + * @type {Number} + * @default 1 + */ + Common.logLevel = 1; + + /** + * Shows a `console.log` message only if the current `Common.logLevel` allows it. + * The message will be prefixed with 'matter-js' to make it easily identifiable. + * @method log + * @param ...objs {} The objects to log. + */ + Common.log = function() { + if (console && Common.logLevel > 0 && Common.logLevel <= 3) { + console.log.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments))); + } + }; + + /** + * Shows a `console.info` message only if the current `Common.logLevel` allows it. + * The message will be prefixed with 'matter-js' to make it easily identifiable. + * @method info + * @param ...objs {} The objects to log. + */ + Common.info = function() { + if (console && Common.logLevel > 0 && Common.logLevel <= 2) { + console.info.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments))); + } + }; + + /** + * Shows a `console.warn` message only if the current `Common.logLevel` allows it. + * The message will be prefixed with 'matter-js' to make it easily identifiable. + * @method warn + * @param ...objs {} The objects to log. + */ + Common.warn = function() { + if (console && Common.logLevel > 0 && Common.logLevel <= 3) { + console.warn.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments))); + } + }; + + /** + * Returns the next unique sequential ID. + * @method nextId + * @return {Number} Unique sequential ID + */ + Common.nextId = function() { + return Common._nextId++; + }; + + /** + * A cross browser compatible indexOf implementation. + * @method indexOf + * @param {array} haystack + * @param {object} needle + * @return {number} The position of needle in haystack, otherwise -1. + */ + Common.indexOf = function(haystack, needle) { + if (haystack.indexOf) + return haystack.indexOf(needle); + + for (var i = 0; i < haystack.length; i++) { + if (haystack[i] === needle) + return i; + } + + return -1; + }; + + /** + * A cross browser compatible array map implementation. + * @method map + * @param {array} list + * @param {function} func + * @return {array} Values from list transformed by func. + */ + Common.map = function(list, func) { + if (list.map) { + return list.map(func); + } + + var mapped = []; + + for (var i = 0; i < list.length; i += 1) { + mapped.push(func(list[i])); + } + + return mapped; + }; + + /** + * Takes a directed graph and returns the partially ordered set of vertices in topological order. + * Circular dependencies are allowed. + * @method topologicalSort + * @param {object} graph + * @return {array} Partially ordered set of vertices in topological order. + */ + Common.topologicalSort = function(graph) { + // https://github.com/mgechev/javascript-algorithms + // Copyright (c) Minko Gechev (MIT license) + // Modifications: tidy formatting and naming + var result = [], + visited = [], + temp = []; + + for (var node in graph) { + if (!visited[node] && !temp[node]) { + Common._topologicalSort(node, visited, temp, graph, result); + } + } + + return result; + }; + + Common._topologicalSort = function(node, visited, temp, graph, result) { + var neighbors = graph[node] || []; + temp[node] = true; + + for (var i = 0; i < neighbors.length; i += 1) { + var neighbor = neighbors[i]; + + if (temp[neighbor]) { + // skip circular dependencies + continue; + } + + if (!visited[neighbor]) { + Common._topologicalSort(neighbor, visited, temp, graph, result); + } + } + + temp[node] = false; + visited[node] = true; + + result.push(node); + }; + + /** + * Takes _n_ functions as arguments and returns a new function that calls them in order. + * The arguments applied when calling the new function will also be applied to every function passed. + * The value of `this` refers to the last value returned in the chain that was not `undefined`. + * Therefore if a passed function does not return a value, the previously returned value is maintained. + * After all passed functions have been called the new function returns the last returned value (if any). + * If any of the passed functions are a chain, then the chain will be flattened. + * @method chain + * @param ...funcs {function} The functions to chain. + * @return {function} A new function that calls the passed functions in order. + */ + Common.chain = function() { + var funcs = []; + + for (var i = 0; i < arguments.length; i += 1) { + var func = arguments[i]; + + if (func._chained) { + // flatten already chained functions + funcs.push.apply(funcs, func._chained); + } else { + funcs.push(func); + } + } + + var chain = function() { + // https://github.com/GoogleChrome/devtools-docs/issues/53#issuecomment-51941358 + var lastResult, + args = new Array(arguments.length); + + for (var i = 0, l = arguments.length; i < l; i++) { + args[i] = arguments[i]; + } + + for (i = 0; i < funcs.length; i += 1) { + var result = funcs[i].apply(lastResult, args); + + if (typeof result !== 'undefined') { + lastResult = result; + } + } + + return lastResult; + }; + + chain._chained = funcs; + + return chain; + }; + + /** + * Chains a function to excute before the original function on the given `path` relative to `base`. + * See also docs for `Common.chain`. + * @method chainPathBefore + * @param {} base The base object + * @param {string} path The path relative to `base` + * @param {function} func The function to chain before the original + * @return {function} The chained function that replaced the original + */ + Common.chainPathBefore = function(base, path, func) { + return Common.set(base, path, Common.chain( + func, + Common.get(base, path) + )); + }; + + /** + * Chains a function to excute after the original function on the given `path` relative to `base`. + * See also docs for `Common.chain`. + * @method chainPathAfter + * @param {} base The base object + * @param {string} path The path relative to `base` + * @param {function} func The function to chain after the original + * @return {function} The chained function that replaced the original + */ + Common.chainPathAfter = function(base, path, func) { + return Common.set(base, path, Common.chain( + Common.get(base, path), + func + )); + }; +})(); + + +/***/ }), +/* 20 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @function Phaser.Math.Clamp + * @since 3.0.0 + * + * @param {number} value - The value to be clamped. + * @param {number} min - The minimum bounds. + * @param {number} max - The maximum bounds. + * + * @return {number} The clamped value. + */ +var Clamp = function (value, min, max) +{ + return Math.max(min, Math.min(max, value)); +}; + +module.exports = Clamp; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Core.Events + */ + +module.exports = { + + BLUR: __webpack_require__(582), + BOOT: __webpack_require__(583), + CONTEXT_LOST: __webpack_require__(584), + CONTEXT_RESTORED: __webpack_require__(585), + DESTROY: __webpack_require__(586), + FOCUS: __webpack_require__(587), + HIDDEN: __webpack_require__(588), + PAUSE: __webpack_require__(589), + POST_RENDER: __webpack_require__(590), + POST_STEP: __webpack_require__(591), + PRE_RENDER: __webpack_require__(592), + PRE_STEP: __webpack_require__(593), + READY: __webpack_require__(594), + RESUME: __webpack_require__(595), + STEP: __webpack_require__(596), + VISIBLE: __webpack_require__(597) + +}; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Contains the plugins that Phaser uses globally and locally. +// These are the source objects, not instantiated. +var corePlugins = {}; + +// Contains the plugins that the dev has loaded into their game +// These are the source objects, not instantiated. +var customPlugins = {}; + +var PluginCache = {}; + +/** + * @namespace Phaser.Plugins.PluginCache + */ + +/** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * + * @method Phaser.Plugins.PluginCache.register + * @since 3.8.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin? + */ +PluginCache.register = function (key, plugin, mapping, custom) +{ + if (custom === undefined) { custom = false; } + + corePlugins[key] = { plugin: plugin, mapping: mapping, custom: custom }; +}; + +/** + * Stores a custom plugin in the global plugin cache. + * The key must be unique, within the scope of the cache. + * + * @method Phaser.Plugins.PluginCache.registerCustom + * @since 3.8.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param {?any} data - A value to be passed to the plugin's `init` method. + */ +PluginCache.registerCustom = function (key, plugin, mapping, data) +{ + customPlugins[key] = { plugin: plugin, mapping: mapping, data: data }; +}; + +/** + * Checks if the given key is already being used in the core plugin cache. + * + * @method Phaser.Plugins.PluginCache.hasCore + * @since 3.8.0 + * + * @param {string} key - The key to check for. + * + * @return {boolean} `true` if the key is already in use in the core cache, otherwise `false`. + */ +PluginCache.hasCore = function (key) +{ + return corePlugins.hasOwnProperty(key); +}; + +/** + * Checks if the given key is already being used in the custom plugin cache. + * + * @method Phaser.Plugins.PluginCache.hasCustom + * @since 3.8.0 + * + * @param {string} key - The key to check for. + * + * @return {boolean} `true` if the key is already in use in the custom cache, otherwise `false`. + */ +PluginCache.hasCustom = function (key) +{ + return customPlugins.hasOwnProperty(key); +}; + +/** + * 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. + */ +PluginCache.getCore = function (key) +{ + return corePlugins[key]; +}; + +/** + * 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. + */ +PluginCache.getCustom = function (key) +{ + return customPlugins[key]; +}; + +/** + * Returns an object from the custom cache based on the given key that can be instantiated. + * + * @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. + */ +PluginCache.getCustomClass = function (key) +{ + return (customPlugins.hasOwnProperty(key)) ? customPlugins[key].plugin : null; +}; + +/** + * 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. + */ +PluginCache.remove = function (key) +{ + if (corePlugins.hasOwnProperty(key)) + { + delete corePlugins[key]; + } +}; + +/** + * 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. + */ +PluginCache.removeCustom = function (key) +{ + if (customPlugins.hasOwnProperty(key)) + { + delete customPlugins[key]; + } +}; + +/** + * Removes all Core Plugins. + * + * This includes all of the internal system plugins that Phaser needs, like the Input Plugin and Loader Plugin. + * So be sure you only call this if you do not wish to run Phaser again. + * + * @method Phaser.Plugins.PluginCache.destroyCorePlugins + * @since 3.12.0 + */ +PluginCache.destroyCorePlugins = function () +{ + for (var key in corePlugins) + { + if (corePlugins.hasOwnProperty(key)) + { + delete corePlugins[key]; + } + } +}; + +/** + * Removes all Custom Plugins. + * + * @method Phaser.Plugins.PluginCache.destroyCustomPlugins + * @since 3.12.0 + */ +PluginCache.destroyCustomPlugins = function () +{ + for (var key in customPlugins) + { + if (customPlugins.hasOwnProperty(key)) + { + delete customPlugins[key]; + } + } +}; + +module.exports = PluginCache; + + +/***/ }), +/* 23 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FILE_CONST = { + + /** + * The Loader is idle. + * + * @name Phaser.Loader.LOADER_IDLE + * @type {integer} + * @since 3.0.0 + */ + LOADER_IDLE: 0, + + /** + * The Loader is actively loading. + * + * @name Phaser.Loader.LOADER_LOADING + * @type {integer} + * @since 3.0.0 + */ + LOADER_LOADING: 1, + + /** + * The Loader is processing files is has loaded. + * + * @name Phaser.Loader.LOADER_PROCESSING + * @type {integer} + * @since 3.0.0 + */ + LOADER_PROCESSING: 2, + + /** + * The Loader has completed loading and processing. + * + * @name Phaser.Loader.LOADER_COMPLETE + * @type {integer} + * @since 3.0.0 + */ + LOADER_COMPLETE: 3, + + /** + * The Loader is shutting down. + * + * @name Phaser.Loader.LOADER_SHUTDOWN + * @type {integer} + * @since 3.0.0 + */ + LOADER_SHUTDOWN: 4, + + /** + * The Loader has been destroyed. + * + * @name Phaser.Loader.LOADER_DESTROYED + * @type {integer} + * @since 3.0.0 + */ + LOADER_DESTROYED: 5, + + /** + * File is in the load queue but not yet started + * + * @name Phaser.Loader.FILE_PENDING + * @type {integer} + * @since 3.0.0 + */ + FILE_PENDING: 10, + + /** + * File has been started to load by the loader (onLoad called) + * + * @name Phaser.Loader.FILE_LOADING + * @type {integer} + * @since 3.0.0 + */ + FILE_LOADING: 11, + + /** + * File has loaded successfully, awaiting processing + * + * @name Phaser.Loader.FILE_LOADED + * @type {integer} + * @since 3.0.0 + */ + FILE_LOADED: 12, + + /** + * File failed to load + * + * @name Phaser.Loader.FILE_FAILED + * @type {integer} + * @since 3.0.0 + */ + FILE_FAILED: 13, + + /** + * File is being processed (onProcess callback) + * + * @name Phaser.Loader.FILE_PROCESSING + * @type {integer} + * @since 3.0.0 + */ + FILE_PROCESSING: 14, + + /** + * The File has errored somehow during processing. + * + * @name Phaser.Loader.FILE_ERRORED + * @type {integer} + * @since 3.0.0 + */ + FILE_ERRORED: 16, + + /** + * File has finished processing. + * + * @name Phaser.Loader.FILE_COMPLETE + * @type {integer} + * @since 3.0.0 + */ + FILE_COMPLETE: 17, + + /** + * File has been destroyed + * + * @name Phaser.Loader.FILE_DESTROYED + * @type {integer} + * @since 3.0.0 + */ + FILE_DESTROYED: 18, + + /** + * File was populated from local data and doesn't need an HTTP request + * + * @name Phaser.Loader.FILE_POPULATED + * @type {integer} + * @since 3.0.0 + */ + FILE_POPULATED: 19 + +}; + +module.exports = FILE_CONST; + + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var Events = __webpack_require__(87); +var GetFastValue = __webpack_require__(1); +var GetURL = __webpack_require__(143); +var MergeXHRSettings = __webpack_require__(227); +var XHRLoader = __webpack_require__(478); +var XHRSettings = __webpack_require__(144); + +/** + * @classdesc + * The base File class used by all File Types that the Loader can support. + * You shouldn't create an instance of a File directly, but should extend it with your own class, setting a custom type and processing methods. + * + * @class File + * @memberof Phaser.Loader + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File. + * @param {Phaser.Types.Loader.FileConfig} fileConfig - The file configuration object, as created by the file type. + */ +var File = new Class({ + + initialize: + + function File (loader, fileConfig) + { + /** + * A reference to the Loader that is going to load this file. + * + * @name Phaser.Loader.File#loader + * @type {Phaser.Loader.LoaderPlugin} + * @since 3.0.0 + */ + this.loader = loader; + + /** + * A reference to the Cache, or Texture Manager, that is going to store this file if it loads. + * + * @name Phaser.Loader.File#cache + * @type {(Phaser.Cache.BaseCache|Phaser.Textures.TextureManager)} + * @since 3.7.0 + */ + this.cache = GetFastValue(fileConfig, 'cache', false); + + /** + * The file type string (image, json, etc) for sorting within the Loader. + * + * @name Phaser.Loader.File#type + * @type {string} + * @since 3.0.0 + */ + this.type = GetFastValue(fileConfig, 'type', false); + + /** + * Unique cache key (unique within its file type) + * + * @name Phaser.Loader.File#key + * @type {string} + * @since 3.0.0 + */ + this.key = GetFastValue(fileConfig, 'key', false); + + var loadKey = this.key; + + if (loader.prefix && loader.prefix !== '') + { + this.key = loader.prefix + loadKey; + } + + if (!this.type || !this.key) + { + throw new Error('Error calling \'Loader.' + this.type + '\' invalid key provided.'); + } + + /** + * The URL of the file, not including baseURL. + * Automatically has Loader.path prepended to it. + * + * @name Phaser.Loader.File#url + * @type {string} + * @since 3.0.0 + */ + this.url = GetFastValue(fileConfig, 'url'); + + if (this.url === undefined) + { + this.url = loader.path + loadKey + '.' + GetFastValue(fileConfig, 'extension', ''); + } + else if (typeof(this.url) !== 'function') + { + this.url = loader.path + this.url; + } + + /** + * The final URL this file will load from, including baseURL and path. + * Set automatically when the Loader calls 'load' on this file. + * + * @name Phaser.Loader.File#src + * @type {string} + * @since 3.0.0 + */ + this.src = ''; + + /** + * The merged XHRSettings for this file. + * + * @name Phaser.Loader.File#xhrSettings + * @type {Phaser.Types.Loader.XHRSettingsObject} + * @since 3.0.0 + */ + this.xhrSettings = XHRSettings(GetFastValue(fileConfig, 'responseType', undefined)); + + if (GetFastValue(fileConfig, 'xhrSettings', false)) + { + this.xhrSettings = MergeXHRSettings(this.xhrSettings, GetFastValue(fileConfig, 'xhrSettings', {})); + } + + /** + * The XMLHttpRequest instance (as created by XHR Loader) that is loading this File. + * + * @name Phaser.Loader.File#xhrLoader + * @type {?XMLHttpRequest} + * @since 3.0.0 + */ + this.xhrLoader = null; + + /** + * The current state of the file. One of the FILE_CONST values. + * + * @name Phaser.Loader.File#state + * @type {integer} + * @since 3.0.0 + */ + this.state = (typeof(this.url) === 'function') ? CONST.FILE_POPULATED : CONST.FILE_PENDING; + + /** + * The total size of this file. + * Set by onProgress and only if loading via XHR. + * + * @name Phaser.Loader.File#bytesTotal + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.bytesTotal = 0; + + /** + * Updated as the file loads. + * Only set if loading via XHR. + * + * @name Phaser.Loader.File#bytesLoaded + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.bytesLoaded = -1; + + /** + * A percentage value between 0 and 1 indicating how much of this file has loaded. + * Only set if loading via XHR. + * + * @name Phaser.Loader.File#percentComplete + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.percentComplete = -1; + + /** + * For CORs based loading. + * If this is undefined then the File will check BaseLoader.crossOrigin and use that (if set) + * + * @name Phaser.Loader.File#crossOrigin + * @type {(string|undefined)} + * @since 3.0.0 + */ + this.crossOrigin = undefined; + + /** + * The processed file data, stored here after the file has loaded. + * + * @name Phaser.Loader.File#data + * @type {*} + * @since 3.0.0 + */ + this.data = undefined; + + /** + * A config object that can be used by file types to store transitional data. + * + * @name Phaser.Loader.File#config + * @type {*} + * @since 3.0.0 + */ + this.config = GetFastValue(fileConfig, 'config', {}); + + /** + * If this is a multipart file, i.e. an atlas and its json together, then this is a reference + * to the parent MultiFile. Set and used internally by the Loader or specific file types. + * + * @name Phaser.Loader.File#multiFile + * @type {?Phaser.Loader.MultiFile} + * @since 3.7.0 + */ + this.multiFile; + + /** + * Does this file have an associated linked file? Such as an image and a normal map. + * Atlases and Bitmap Fonts use the multiFile, because those files need loading together but aren't + * actually bound by data, where-as a linkFile is. + * + * @name Phaser.Loader.File#linkFile + * @type {?Phaser.Loader.File} + * @since 3.7.0 + */ + this.linkFile; + }, + + /** + * Links this File with another, so they depend upon each other for loading and processing. + * + * @method Phaser.Loader.File#setLink + * @since 3.7.0 + * + * @param {Phaser.Loader.File} fileB - The file to link to this one. + */ + setLink: function (fileB) + { + this.linkFile = fileB; + + fileB.linkFile = this; + }, + + /** + * Resets the XHRLoader instance this file is using. + * + * @method Phaser.Loader.File#resetXHR + * @since 3.0.0 + */ + resetXHR: function () + { + if (this.xhrLoader) + { + this.xhrLoader.onload = undefined; + this.xhrLoader.onerror = undefined; + this.xhrLoader.onprogress = undefined; + } + }, + + /** + * 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 + */ + load: function () + { + if (this.state === CONST.FILE_POPULATED) + { + // Can happen for example in a JSONFile if they've provided a JSON object instead of a URL + this.loader.nextFile(this, true); + } + else + { + this.src = GetURL(this, this.loader.baseURL); + + if (this.src.indexOf('data:') === 0) + { + console.warn('Local data URIs are not supported: ' + this.key); + } + else + { + // The creation of this XHRLoader starts the load process going. + // It will automatically call the following, based on the load outcome: + // + // xhr.onload = this.onLoad + // xhr.onerror = this.onError + // xhr.onprogress = this.onProgress + + this.xhrLoader = XHRLoader(this, this.loader.xhr); + } + } + }, + + /** + * Called when the file finishes loading, is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.File#onLoad + * @since 3.0.0 + * + * @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event. + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. + */ + onLoad: function (xhr, event) + { + var localFileOk = ((xhr.responseURL && xhr.responseURL.indexOf('file://') === 0 && event.target.status === 0)); + + var success = !(event.target && event.target.status !== 200) || localFileOk; + + // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) + { + success = false; + } + + this.resetXHR(); + + this.loader.nextFile(this, success); + }, + + /** + * Called if the file errors while loading, is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.File#onError + * @since 3.0.0 + * + * @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event. + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this error. + */ + onError: function () + { + this.resetXHR(); + + this.loader.nextFile(this, false); + }, + + /** + * Called during the file load progress. Is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.File#onProgress + * @fires Phaser.Loader.Events#FILE_PROGRESS + * @since 3.0.0 + * + * @param {ProgressEvent} event - The DOM ProgressEvent. + */ + onProgress: function (event) + { + if (event.lengthComputable) + { + this.bytesLoaded = event.loaded; + this.bytesTotal = event.total; + + this.percentComplete = Math.min((this.bytesLoaded / this.bytesTotal), 1); + + this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete); + } + }, + + /** + * Usually overridden by the FileTypes and is called by Loader.nextFile. + * This method controls what extra work this File does with its loaded data, for example a JSON file will parse itself during this stage. + * + * @method Phaser.Loader.File#onProcess + * @since 3.0.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.onProcessComplete(); + }, + + /** + * Called when the File has completed processing. + * Checks on the state of its multifile, if set. + * + * @method Phaser.Loader.File#onProcessComplete + * @since 3.7.0 + */ + onProcessComplete: function () + { + this.state = CONST.FILE_COMPLETE; + + if (this.multiFile) + { + this.multiFile.onFileComplete(this); + } + + this.loader.fileProcessComplete(this); + }, + + /** + * Called when the File has completed processing but it generated an error. + * Checks on the state of its multifile, if set. + * + * @method Phaser.Loader.File#onProcessError + * @since 3.7.0 + */ + onProcessError: function () + { + this.state = CONST.FILE_ERRORED; + + if (this.multiFile) + { + this.multiFile.onFileFailed(this); + } + + this.loader.fileProcessComplete(this); + }, + + /** + * Checks if a key matching the one used by this file exists in the target Cache or not. + * This is called automatically by the LoaderPlugin to decide if the file can be safely + * loaded or will conflict. + * + * @method Phaser.Loader.File#hasCacheConflict + * @since 3.7.0 + * + * @return {boolean} `true` if adding this file will cause a conflict, otherwise `false`. + */ + hasCacheConflict: function () + { + return (this.cache && this.cache.exists(this.key)); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * This method is often overridden by specific file types. + * + * @method Phaser.Loader.File#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.cache) + { + this.cache.add(this.key, this.data); + } + + this.pendingDestroy(); + }, + + /** + * Called once the file has been added to its cache and is now ready for deletion from the Loader. + * It will emit a `filecomplete` event from the LoaderPlugin. + * + * @method Phaser.Loader.File#pendingDestroy + * @fires Phaser.Loader.Events#FILE_COMPLETE + * @fires Phaser.Loader.Events#FILE_KEY_COMPLETE + * @since 3.7.0 + */ + pendingDestroy: function (data) + { + if (data === undefined) { data = this.data; } + + var key = this.key; + var type = this.type; + + this.loader.emit(Events.FILE_COMPLETE, key, type, data); + this.loader.emit(Events.FILE_KEY_COMPLETE + type + '-' + key, key, type, data); + + this.loader.flagForRemoval(this); + }, + + /** + * Destroy this File and any references it holds. + * + * @method Phaser.Loader.File#destroy + * @since 3.7.0 + */ + destroy: function () + { + this.loader = null; + this.cache = null; + this.xhrSettings = null; + this.multiFile = null; + this.linkFile = null; + this.data = null; + } + +}); + +/** + * Static method for creating object URL using URL API and setting it as image 'src' attribute. + * If URL API is not supported (usually on old browsers) it falls back to creating Base64 encoded url using FileReader. + * + * @method Phaser.Loader.File.createObjectURL + * @static + * @since 3.7.0 + * + * @param {HTMLImageElement} image - Image object which 'src' attribute should be set to object URL. + * @param {Blob} blob - A Blob object to create an object URL for. + * @param {string} defaultType - Default mime type used if blob type is not available. + */ +File.createObjectURL = function (image, blob, defaultType) +{ + if (typeof URL === 'function') + { + image.src = URL.createObjectURL(blob); + } + else + { + var reader = new FileReader(); + + reader.onload = function () + { + image.removeAttribute('crossOrigin'); + image.src = 'data:' + (blob.type || defaultType) + ';base64,' + reader.result.split(',')[1]; + }; + + reader.onerror = image.onerror; + + reader.readAsDataURL(blob); + } +}; + +/** + * Static method for releasing an existing object URL which was previously created + * by calling {@link File#createObjectURL} method. + * + * @method Phaser.Loader.File.revokeObjectURL + * @static + * @since 3.7.0 + * + * @param {HTMLImageElement} image - Image object which 'src' attribute should be revoked. + */ +File.revokeObjectURL = function (image) +{ + if (typeof URL === 'function') + { + URL.revokeObjectURL(image.src); + } +}; + +module.exports = File; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * 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 + */ + +var Body = {}; + +module.exports = Body; + +var Vertices = __webpack_require__(31); +var Vector = __webpack_require__(37); +var Sleeping = __webpack_require__(95); +var Common = __webpack_require__(19); +var Bounds = __webpack_require__(38); +var Axes = __webpack_require__(146); + +(function() { + + Body._inertiaScale = 4; + Body._nextCollidingGroupId = 1; + Body._nextNonCollidingGroupId = -1; + Body._nextCategory = 0x0001; + + /** + * 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 + */ + Body.create = function(options) { + var defaults = { + id: Common.nextId(), + type: 'body', + label: 'Body', + parts: [], + plugin: {}, + angle: 0, + vertices: null, // Phaser change: no point calling fromPath if they pass in vertices anyway + position: { x: 0, y: 0 }, + force: { x: 0, y: 0 }, + torque: 0, + positionImpulse: { x: 0, y: 0 }, + previousPositionImpulse: { x: 0, y: 0 }, + constraintImpulse: { x: 0, y: 0, angle: 0 }, + totalContacts: 0, + speed: 0, + angularSpeed: 0, + velocity: { x: 0, y: 0 }, + angularVelocity: 0, + isSensor: false, + isStatic: false, + isSleeping: false, + motion: 0, + sleepThreshold: 60, + density: 0.001, + restitution: 0, + friction: 0.1, + frictionStatic: 0.5, + frictionAir: 0.01, + collisionFilter: { + category: 0x0001, + mask: 0xFFFFFFFF, + group: 0 + }, + slop: 0.05, + timeScale: 1, + events: null, + bounds: null, + chamfer: null, + circleRadius: 0, + positionPrev: null, + anglePrev: 0, + parent: null, + axes: null, + area: 0, + mass: 0, + inverseMass: 0, + inertia: 0, + inverseInertia: 0, + _original: null, + render: { + visible: true, + opacity: 1, + sprite: { + xOffset: 0, + yOffset: 0 + }, + fillColor: null, // custom Phaser property + fillOpacity: null, // custom Phaser property + lineColor: null, // custom Phaser property + lineOpacity: null, // custom Phaser property + lineThickness: null // custom Phaser property + }, + gameObject: null, // custom Phaser property + scale: { x: 1, y: 1 }, // custom Phaser property + centerOfMass: { x: 0, y: 0 }, // custom Phaser property (float, 0 - 1) + centerOffset: { x: 0, y: 0 }, // custom Phaser property (pixel values) + gravityScale: { x: 1, y: 1 }, // custom Phaser property + ignoreGravity: false, // custom Phaser property + ignorePointer: false, // custom Phaser property + onCollideCallback: null, // custom Phaser property + onCollideEndCallback: null, // custom Phaser property + onCollideActiveCallback: null, // custom Phaser property + onCollideWith: {} // custom Phaser property + }; + + if (!options.hasOwnProperty('position') && options.hasOwnProperty('vertices')) + { + options.position = Vertices.centre(options.vertices); + } + else if (!options.hasOwnProperty('vertices')) + { + defaults.vertices = Vertices.fromPath('L 0 0 L 40 0 L 40 40 L 0 40'); + } + + var body = Common.extend(defaults, options); + + _initProperties(body, options); + + // Helper function + body.setOnCollideWith = function (body, callback) + { + if (callback) + { + this.onCollideWith[body.id] = callback; + } + else + { + delete this.onCollideWith[body.id]; + } + + return this; + } + + return body; + }; + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. + * See `body.collisionFilter` for more information. + * @method nextGroup + * @param {bool} [isNonColliding=false] + * @return {Number} Unique group index + */ + Body.nextGroup = function(isNonColliding) { + if (isNonColliding) + return Body._nextNonCollidingGroupId--; + + return Body._nextCollidingGroupId++; + }; + + /** + * Returns the next unique category bitfield (starting after the initial default category `0x0001`). + * There are 32 available. See `body.collisionFilter` for more information. + * @method nextCategory + * @return {Number} Unique category bitfield + */ + Body.nextCategory = function() { + Body._nextCategory = Body._nextCategory << 1; + return Body._nextCategory; + }; + + /** + * Initialises body properties. + * @method _initProperties + * @private + * @param {body} body + * @param {} [options] + */ + var _initProperties = function(body, options) { + options = options || {}; + + // init required properties (order is important) + Body.set(body, { + bounds: body.bounds || Bounds.create(body.vertices), + positionPrev: body.positionPrev || Vector.clone(body.position), + anglePrev: body.anglePrev || body.angle, + vertices: body.vertices, + parts: body.parts || [body], + isStatic: body.isStatic, + isSleeping: body.isSleeping, + parent: body.parent || body + }); + + var bounds = body.bounds; + + Vertices.rotate(body.vertices, body.angle, body.position); + Axes.rotate(body.axes, body.angle); + Bounds.update(bounds, body.vertices, body.velocity); + + // allow options to override the automatically calculated properties + Body.set(body, { + axes: options.axes || body.axes, + area: options.area || body.area, + mass: options.mass || body.mass, + inertia: options.inertia || body.inertia + }); + + if (body.parts.length === 1) + { + var centerOfMass = body.centerOfMass; + var centerOffset = body.centerOffset; + + var bodyWidth = bounds.max.x - bounds.min.x; + var bodyHeight = bounds.max.y - bounds.min.y; + + centerOfMass.x = -(bounds.min.x - body.position.x) / bodyWidth; + centerOfMass.y = -(bounds.min.y - body.position.y) / bodyHeight; + + centerOffset.x = bodyWidth * centerOfMass.x; + centerOffset.y = bodyHeight * centerOfMass.y; + } + }; + + /** + * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. + * Prefer to use the actual setter functions in performance critical situations. + * @method set + * @param {body} body + * @param {} settings A property name (or map of properties and values) to set on the body. + * @param {} value The value to set if `settings` is a single property name. + */ + Body.set = function(body, settings, value) { + var property; + + if (typeof settings === 'string') { + property = settings; + settings = {}; + settings[property] = value; + } + + for (property in settings) { + if (!Object.prototype.hasOwnProperty.call(settings, property)) + continue; + + value = settings[property]; + switch (property) { + + case 'isStatic': + Body.setStatic(body, value); + break; + case 'isSleeping': + Sleeping.set(body, value); + break; + case 'mass': + Body.setMass(body, value); + break; + case 'density': + Body.setDensity(body, value); + break; + case 'inertia': + Body.setInertia(body, value); + break; + case 'vertices': + Body.setVertices(body, value); + break; + case 'position': + Body.setPosition(body, value); + break; + case 'angle': + Body.setAngle(body, value); + break; + case 'velocity': + Body.setVelocity(body, value); + break; + case 'angularVelocity': + Body.setAngularVelocity(body, value); + break; + case 'parts': + Body.setParts(body, value); + break; + case 'centre': + Body.setCentre(body, value); + break; + default: + body[property] = value; + } + } + }; + + /** + * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. + * @method setStatic + * @param {body} body + * @param {bool} isStatic + */ + Body.setStatic = function(body, isStatic) { + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + part.isStatic = isStatic; + + if (isStatic) { + part._original = { + restitution: part.restitution, + friction: part.friction, + mass: part.mass, + inertia: part.inertia, + density: part.density, + inverseMass: part.inverseMass, + inverseInertia: part.inverseInertia + }; + + part.restitution = 0; + part.friction = 1; + part.mass = part.inertia = part.density = Infinity; + part.inverseMass = part.inverseInertia = 0; + + part.positionPrev.x = part.position.x; + part.positionPrev.y = part.position.y; + part.anglePrev = part.angle; + part.angularVelocity = 0; + part.speed = 0; + part.angularSpeed = 0; + part.motion = 0; + } else if (part._original) { + part.restitution = part._original.restitution; + part.friction = part._original.friction; + part.mass = part._original.mass; + part.inertia = part._original.inertia; + part.density = part._original.density; + part.inverseMass = part._original.inverseMass; + part.inverseInertia = part._original.inverseInertia; + + part._original = null; + } + } + }; + + /** + * Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change. + * @method setMass + * @param {body} body + * @param {number} mass + */ + Body.setMass = function(body, mass) { + var moment = body.inertia / (body.mass / 6); + body.inertia = moment * (mass / 6); + body.inverseInertia = 1 / body.inertia; + + body.mass = mass; + body.inverseMass = 1 / body.mass; + body.density = body.mass / body.area; + }; + + /** + * Sets the density of the body. Mass and inertia are automatically updated to reflect the change. + * @method setDensity + * @param {body} body + * @param {number} density + */ + Body.setDensity = function(body, density) { + Body.setMass(body, density * body.area); + body.density = density; + }; + + /** + * Sets the moment of inertia (i.e. second moment of area) of the body. + * Inverse inertia is automatically updated to reflect the change. Mass is not changed. + * @method setInertia + * @param {body} body + * @param {number} inertia + */ + Body.setInertia = function(body, inertia) { + body.inertia = inertia; + body.inverseInertia = 1 / body.inertia; + }; + + /** + * 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 + */ + Body.setVertices = function(body, vertices) { + // change vertices + if (vertices[0].body === body) { + body.vertices = vertices; + } else { + body.vertices = Vertices.create(vertices, body); + } + + // update properties + body.axes = Axes.fromVertices(body.vertices); + body.area = Vertices.area(body.vertices); + Body.setMass(body, body.density * body.area); + + // orient vertices around the centre of mass at origin (0, 0) + var centre = Vertices.centre(body.vertices); + Vertices.translate(body.vertices, centre, -1); + + // update inertia while vertices are at origin (0, 0) + Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass)); + + // update geometry + Vertices.translate(body.vertices, body.position); + + Bounds.update(body.bounds, body.vertices, body.velocity); + }; + + /** + * Sets the parts of the `body` and updates mass, inertia and centroid. + * Each part will have its parent set to `body`. + * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` + * Note that this method will ensure that the first part in `body.parts` will always be the `body`. + * @method setParts + * @param {body} body + * @param [body] parts + * @param {bool} [autoHull=true] + */ + Body.setParts = function(body, parts, autoHull) { + var i; + + // add all the parts, ensuring that the first part is always the parent body + parts = parts.slice(0); + body.parts.length = 0; + body.parts.push(body); + body.parent = body; + + for (i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part !== body) { + part.parent = body; + body.parts.push(part); + } + } + + if (body.parts.length === 1) + return; + + autoHull = typeof autoHull !== 'undefined' ? autoHull : true; + + // find the convex hull of all parts to set on the parent body + if (autoHull) { + var vertices = []; + for (i = 0; i < parts.length; i++) { + vertices = vertices.concat(parts[i].vertices); + } + + Vertices.clockwiseSort(vertices); + + var hull = Vertices.hull(vertices), + hullCentre = Vertices.centre(hull); + + Body.setVertices(body, hull); + Vertices.translate(body.vertices, hullCentre); + } + + // sum the properties of all compound parts of the parent body + var total = Body._totalProperties(body); + + // Phaser addition + var cx = total.centre.x; + var cy = total.centre.y; + + var bounds = body.bounds; + var centerOfMass = body.centerOfMass; + var centerOffset = body.centerOffset; + + Bounds.update(bounds, body.vertices, body.velocity); + + centerOfMass.x = -(bounds.min.x - cx) / (bounds.max.x - bounds.min.x); + centerOfMass.y = -(bounds.min.y - cy) / (bounds.max.y - bounds.min.y); + + centerOffset.x = cx; + centerOffset.y = cy; + + body.area = total.area; + body.parent = body; + body.position.x = cx; + body.position.y = cy; + body.positionPrev.x = cx; + body.positionPrev.y = cy; + + Body.setMass(body, total.mass); + Body.setInertia(body, total.inertia); + Body.setPosition(body, total.centre); + }; + + /** + * Set the centre of mass of the body. + * The `centre` is a vector in world-space unless `relative` is set, in which case it is a translation. + * The centre of mass is the point the body rotates about and can be used to simulate non-uniform density. + * This is equal to moving `body.position` but not the `body.vertices`. + * Invalid if the `centre` falls outside the body's convex hull. + * @method setCentre + * @param {body} body + * @param {vector} centre + * @param {bool} relative + */ + Body.setCentre = function(body, centre, relative) { + if (!relative) { + body.positionPrev.x = centre.x - (body.position.x - body.positionPrev.x); + body.positionPrev.y = centre.y - (body.position.y - body.positionPrev.y); + body.position.x = centre.x; + body.position.y = centre.y; + } else { + body.positionPrev.x += centre.x; + body.positionPrev.y += centre.y; + body.position.x += centre.x; + body.position.y += centre.y; + } + }; + + /** + * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. + * @method setPosition + * @param {body} body + * @param {vector} position + */ + Body.setPosition = function(body, position) { + var delta = Vector.sub(position, body.position); + body.positionPrev.x += delta.x; + body.positionPrev.y += delta.y; + + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + part.position.x += delta.x; + part.position.y += delta.y; + Vertices.translate(part.vertices, delta); + Bounds.update(part.bounds, part.vertices, body.velocity); + } + }; + + /** + * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. + * @method setAngle + * @param {body} body + * @param {number} angle + */ + Body.setAngle = function(body, angle) { + var delta = angle - body.angle; + body.anglePrev += delta; + + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + part.angle += delta; + Vertices.rotate(part.vertices, delta, body.position); + Axes.rotate(part.axes, delta); + Bounds.update(part.bounds, part.vertices, body.velocity); + if (i > 0) { + Vector.rotateAbout(part.position, delta, body.position, part.position); + } + } + }; + + /** + * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setVelocity + * @param {body} body + * @param {vector} velocity + */ + Body.setVelocity = function(body, velocity) { + body.positionPrev.x = body.position.x - velocity.x; + body.positionPrev.y = body.position.y - velocity.y; + body.velocity.x = velocity.x; + body.velocity.y = velocity.y; + body.speed = Vector.magnitude(body.velocity); + }; + + /** + * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setAngularVelocity + * @param {body} body + * @param {number} velocity + */ + Body.setAngularVelocity = function(body, velocity) { + body.anglePrev = body.angle - velocity; + body.angularVelocity = velocity; + body.angularSpeed = Math.abs(body.angularVelocity); + }; + + /** + * Moves a body by a given vector relative to its current position, without imparting any velocity. + * @method translate + * @param {body} body + * @param {vector} translation + */ + Body.translate = function(body, translation) { + Body.setPosition(body, Vector.add(body.position, translation)); + }; + + /** + * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. + * @method rotate + * @param {body} body + * @param {number} rotation + * @param {vector} [point] + */ + Body.rotate = function(body, rotation, point) { + if (!point) { + Body.setAngle(body, body.angle + rotation); + } else { + var cos = Math.cos(rotation), + sin = Math.sin(rotation), + dx = body.position.x - point.x, + dy = body.position.y - point.y; + + Body.setPosition(body, { + x: point.x + (dx * cos - dy * sin), + y: point.y + (dx * sin + dy * cos) + }); + + Body.setAngle(body, body.angle + rotation); + } + }; + + /** + * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). + * @method scale + * @param {body} body + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} [point] + */ + Body.scale = function(body, scaleX, scaleY, point) { + var totalArea = 0, + totalInertia = 0; + + point = point || body.position; + + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + + part.scale.x = scaleX; + part.scale.y = scaleY; + + // scale vertices + Vertices.scale(part.vertices, scaleX, scaleY, point); + + // update properties + part.axes = Axes.fromVertices(part.vertices); + part.area = Vertices.area(part.vertices); + Body.setMass(part, body.density * part.area); + + // update inertia (requires vertices to be at origin) + Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y }); + Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass)); + Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y }); + + if (i > 0) { + totalArea += part.area; + totalInertia += part.inertia; + } + + // scale position + part.position.x = point.x + (part.position.x - point.x) * scaleX; + part.position.y = point.y + (part.position.y - point.y) * scaleY; + + // update bounds + Bounds.update(part.bounds, part.vertices, body.velocity); + } + + // handle parent body + if (body.parts.length > 1) { + body.area = totalArea; + + if (!body.isStatic) { + Body.setMass(body, body.density * totalArea); + Body.setInertia(body, totalInertia); + } + } + + // handle circles + if (body.circleRadius) { + if (scaleX === scaleY) { + body.circleRadius *= scaleX; + } else { + // body is no longer a circle + body.circleRadius = null; + } + } + }; + + /** + * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. + * @method update + * @param {body} body + * @param {number} deltaTime + * @param {number} timeScale + * @param {number} correction + */ + Body.update = function(body, deltaTime, timeScale, correction) { + var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2); + + // from the previous step + var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale, + velocityPrevX = body.position.x - body.positionPrev.x, + velocityPrevY = body.position.y - body.positionPrev.y; + + // update velocity with Verlet integration + body.velocity.x = (velocityPrevX * frictionAir * correction) + (body.force.x / body.mass) * deltaTimeSquared; + body.velocity.y = (velocityPrevY * frictionAir * correction) + (body.force.y / body.mass) * deltaTimeSquared; + + body.positionPrev.x = body.position.x; + body.positionPrev.y = body.position.y; + body.position.x += body.velocity.x; + body.position.y += body.velocity.y; + + // update angular velocity with Verlet integration + body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared; + body.anglePrev = body.angle; + body.angle += body.angularVelocity; + + // track speed and acceleration + body.speed = Vector.magnitude(body.velocity); + body.angularSpeed = Math.abs(body.angularVelocity); + + // transform the body geometry + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + + Vertices.translate(part.vertices, body.velocity); + + if (i > 0) { + part.position.x += body.velocity.x; + part.position.y += body.velocity.y; + } + + if (body.angularVelocity !== 0) { + Vertices.rotate(part.vertices, body.angularVelocity, body.position); + Axes.rotate(part.axes, body.angularVelocity); + if (i > 0) { + Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position); + } + } + + Bounds.update(part.bounds, part.vertices, body.velocity); + } + }; + + /** + * Applies a force to a body from a given world-space position, including resulting torque. + * @method applyForce + * @param {body} body + * @param {vector} position + * @param {vector} force + */ + Body.applyForce = function(body, position, force) { + body.force.x += force.x; + body.force.y += force.y; + var offset = { x: position.x - body.position.x, y: position.y - body.position.y }; + body.torque += offset.x * force.y - offset.y * force.x; + }; + + /** + * Returns the sums of the properties of all compound parts of the parent body. + * @method _totalProperties + * @private + * @param {body} body + * @return {} + */ + Body._totalProperties = function(body) { + // 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 + + var properties = { + mass: 0, + area: 0, + inertia: 0, + centre: { x: 0, y: 0 } + }; + + // sum the properties of all compound parts of the parent body + for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) { + var part = body.parts[i], + mass = part.mass !== Infinity ? part.mass : 1; + + properties.mass += mass; + properties.area += part.area; + properties.inertia += part.inertia; + properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass)); + } + + properties.centre = Vector.div(properties.centre, properties.mass); + + return properties; + }; + + /* + * + * Events Documentation + * + */ + + /** + * Fired when a body starts sleeping (where `this` is the body). + * + * @event sleepStart + * @this {body} The body that has started sleeping + * @param {} event An event object + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a body ends sleeping (where `this` is the body). + * + * @event sleepEnd + * @this {body} The body that has ended sleeping + * @param {} event An event object + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`. + * + * @property id + * @type number + */ + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "body" + * @readOnly + */ + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Body" + */ + + /** + * An array of bodies that make up this body. + * The first body in the array must always be a self reference to the current body instance. + * All bodies in the `parts` array together form a single rigid compound body. + * Parts are allowed to overlap, have gaps or holes or even form concave bodies. + * Parts themselves should never be added to a `World`, only the parent body should be. + * Use `Body.setParts` when setting parts to ensure correct updates of all properties. + * + * @property parts + * @type body[] + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + + /** + * A self reference if the body is _not_ a part of another body. + * Otherwise this is a reference to the body that this is a part of. + * See `body.parts`. + * + * @property parent + * @type body + */ + + /** + * A `Number` specifying the angle of the body, in radians. + * + * @property angle + * @type number + * @default 0 + */ + + /** + * An array of `Vector` objects that specify the convex hull of the rigid body. + * These should be provided about the origin `(0, 0)`. E.g. + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). + * The `Vector` objects are also augmented with additional properties required for efficient collision detection. + * + * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). + * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. + * + * @property vertices + * @type vector[] + */ + + /** + * A `Vector` that specifies the current world-space position of the body. + * + * @property position + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Vector` that holds the current scale values as set by `Body.setScale`. + * + * @property scale + * @type vector + * @default { x: 1, y: 1 } + */ + + /** + * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. + * + * @property force + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. + * + * @property torque + * @type number + * @default 0 + */ + + /** + * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). + * + * @readOnly + * @property speed + * @type number + * @default 0 + */ + + /** + * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). + * + * @readOnly + * @property angularSpeed + * @type number + * @default 0 + */ + + /** + * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property velocity + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property angularVelocity + * @type number + * @default 0 + */ + + /** + * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. + * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. + * + * @property isStatic + * @type boolean + * @default false + */ + + /** + * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + * + * @property isSensor + * @type boolean + * @default false + */ + + /** + * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. + * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. + * + * @property isSleeping + * @type boolean + * @default false + */ + + /** + * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. + * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. + * + * @readOnly + * @property motion + * @type number + * @default 0 + */ + + /** + * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). + * + * @property sleepThreshold + * @type number + * @default 60 + */ + + /** + * 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 mass of the body, although it may be more appropriate to specify the `density` property instead. + * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). + * + * @property mass + * @type number + */ + + /** + * A `Number` that defines the inverse mass of the body (`1 / mass`). + * If you modify this value, you must also modify the `body.mass` property. + * + * @property inverseMass + * @type number + */ + + /** + * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. + * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. + * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). + * + * @property inertia + * @type number + */ + + /** + * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). + * If you modify this value, you must also modify the `body.inertia` property. + * + * @property inverseInertia + * @type number + */ + + /** + * 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 + */ + + /** + * A `Number` that defines the static friction of the body (in the Coulomb friction model). + * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. + * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. + * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. + * + * @property frictionStatic + * @type number + * @default 0.5 + */ + + /** + * A `Number` that defines the air friction of the body (air resistance). + * A value of `0` means the body will never slow as it moves through space. + * The higher the value, the faster a body slows when moving through space. + * The effects of the value are non-linear. + * + * @property frictionAir + * @type number + * @default 0.01 + */ + + /** + * An `Object` that specifies the collision filtering properties of this body. + * + * Collisions between two bodies will obey the following rules: + * - If the two bodies have the same non-zero value of `collisionFilter.group`, + * they will always collide if the value is positive, and they will never collide + * if the value is negative. + * - If the two bodies have different values of `collisionFilter.group` or if one + * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: + * + * Each body belongs to a collision category, given by `collisionFilter.category`. This + * value is used as a bit field and the category should have only one bit set, meaning that + * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 + * different collision categories available. + * + * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies + * the categories it collides with (the value is the bitwise AND value of all these categories). + * + * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's + * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` + * are both true. + * + * @property collisionFilter + * @type object + */ + + /** + * An Integer `Number`, that specifies the collision group this body belongs to. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter.group + * @type object + * @default 0 + */ + + /** + * A bit field that specifies the collision category this body belongs to. + * The category value should have only one bit set, for example `0x0001`. + * This means there are up to 32 unique collision categories available. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter.category + * @type object + * @default 1 + */ + + /** + * A bit mask that specifies the collision categories this body may collide with. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter.mask + * @type object + * @default -1 + */ + + /** + * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. + * Avoid changing this value unless you understand the purpose of `slop` in physics engines. + * The default should generally suffice, although very large bodies may require larger values for stable stacking. + * + * @property slop + * @type number + * @default 0.05 + */ + + /** + * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + * + * @property timeScale + * @type number + * @default 1 + */ + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + + /** + * A flag that indicates if the body should be rendered. + * + * @property render.visible + * @type boolean + * @default true + */ + + /** + * Sets the opacity to use when rendering. + * + * @property render.opacity + * @type number + * @default 1 + */ + + /** + * An `Object` that defines the sprite properties to use when rendering, if any. + * + * @property render.sprite + * @type object + */ + + /** + * A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width). + * + * @property render.sprite.xOffset + * @type number + * @default 0 + */ + + /** + * A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height). + * + * @property render.sprite.yOffset + * @type number + * @default 0 + */ + + /** + * A hex color value that defines the fill color to use when rendering the body. + * + * @property render.fillColor + * @type number + */ + + /** + * A value that defines the fill opacity to use when rendering the body. + * + * @property render.fillOpacity + * @type number + */ + + /** + * A hex color value that defines the line color to use when rendering the body. + * + * @property render.lineColor + * @type number + */ + + /** + * A value that defines the line opacity to use when rendering the body. + * + * @property render.lineOpacity + * @type number + */ + + /** + * A `Number` that defines the line width to use when rendering the body outline. + * + * @property render.lineThickness + * @type number + */ + + /** + * An array of unique axis vectors (edge normals) used for collision detection. + * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. + * They are constantly updated by `Body.update` during the simulation. + * + * @property axes + * @type vector[] + */ + + /** + * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. + * + * @property area + * @type string + * @default + */ + + /** + * A `Bounds` object that defines the AABB region for the body. + * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. + * + * @property bounds + * @type bounds + */ + + /** + * A reference to the Phaser Game Object this body belongs to, if any. + * + * @property gameObject + * @type Phaser.GameObjects.GameObject + */ + + /** + * The center of mass of the Body. + * + * @property centerOfMass + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * The center of the body in pixel values. + * Used by Phaser for texture aligment. + * + * @property centerOffset + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * Will this Body ignore World gravity during the Engine update? + * + * @property ignoreGravity + * @type boolean + * @default false + */ + + /** + * Scale the influence of World gravity when applied to this body. + * + * @property gravityScale + * @type vector + * @default { x: 1, y: 1 } + */ + + /** + * Will this Body ignore Phaser Pointer input events? + * + * @property ignorePointer + * @type boolean + * @default false + */ + + /** + * A callback that is invoked when this Body starts colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideCallback + * @type function + * @default null + */ + + /** + * A callback that is invoked when this Body stops colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideEndCallback + * @type function + * @default null + */ + + /** + * A callback that is invoked for the duration that this Body is colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideActiveCallback + * @type function + * @default null + */ + + /** + * A collision callback dictionary used by the `Body.setOnCollideWith` function. + * + * @property onCollideWith + * @type object + * @default null + */ + +})(); + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * + * @function Phaser.Tilemaps.Components.GetTilesWithin + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.GetTilesWithinFilteringOptions} GetTilesWithinFilteringOptions - Optional filters to apply when getting the tiles. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. + */ +var GetTilesWithin = function (tileX, tileY, width, height, filteringOptions, layer) +{ + if (tileX === undefined) { tileX = 0; } + if (tileY === undefined) { tileY = 0; } + if (width === undefined) { width = layer.width; } + if (height === undefined) { height = layer.height; } + + var isNotEmpty = GetFastValue(filteringOptions, 'isNotEmpty', false); + var isColliding = GetFastValue(filteringOptions, 'isColliding', false); + var hasInterestingFace = GetFastValue(filteringOptions, 'hasInterestingFace', false); + + // Clip x, y to top left of map, while shrinking width/height to match. + if (tileX < 0) + { + width += tileX; + tileX = 0; + } + if (tileY < 0) + { + height += tileY; + tileY = 0; + } + + // Clip width and height to bottom right of map. + if (tileX + width > layer.width) + { + width = Math.max(layer.width - tileX, 0); + } + if (tileY + height > layer.height) + { + height = Math.max(layer.height - tileY, 0); + } + + var results = []; + + for (var ty = tileY; ty < tileY + height; ty++) + { + for (var tx = tileX; tx < tileX + width; tx++) + { + var tile = layer.data[ty][tx]; + if (tile !== null) + { + if (isNotEmpty && tile.index === -1) { continue; } + if (isColliding && !tile.collides) { continue; } + if (hasInterestingFace && !tile.hasInterestingFace) { continue; } + results.push(tile); + } + } + } + + return results; +}; + +module.exports = GetTilesWithin; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `PropertyValueSet(group.getChildren(), key, value, step)` + * + * @function Phaser.Actions.PropertyValueSet + * @since 3.3.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 {string} key - The property to be updated. + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var PropertyValueSet = function (items, key, value, step, index, direction) +{ + if (step === undefined) { step = 0; } + if (index === undefined) { index = 0; } + if (direction === undefined) { direction = 1; } + + var i; + var t = 0; + var end = items.length; + + if (direction === 1) + { + // Start to End + for (i = index; i < end; i++) + { + items[i][key] = value + (t * step); + t++; + } + } + else + { + // End to Start + for (i = index; i >= 0; i--) + { + items[i][key] = value + (t * step); + t++; + } + } + + return items; +}; + +module.exports = PropertyValueSet; + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(32); +var Smoothing = __webpack_require__(177); + +// The pool into which the canvas elements are placed. +var pool = []; + +// Automatically apply smoothing(false) to created Canvas elements +var _disableContextSmoothing = false; + +/** + * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. + * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, + * which is useless for some of the Phaser pipelines / renderer. + * + * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. + * Which means all instances of Phaser Games on the same page can share the one single pool. + * + * @namespace Phaser.Display.Canvas.CanvasPool + * @since 3.0.0 + */ +var CanvasPool = function () +{ + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @function Phaser.Display.Canvas.CanvasPool.create + * @since 3.0.0 + * + * @param {*} parent - The parent of the Canvas object. + * @param {integer} [width=1] - The width of the Canvas. + * @param {integer} [height=1] - The height of the Canvas. + * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. + * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? + * + * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool + */ + var create = function (parent, width, height, canvasType, selfParent) + { + if (width === undefined) { width = 1; } + if (height === undefined) { height = 1; } + if (canvasType === undefined) { canvasType = CONST.CANVAS; } + if (selfParent === undefined) { selfParent = false; } + + var canvas; + var container = first(canvasType); + + if (container === null) + { + container = { + parent: parent, + canvas: document.createElement('canvas'), + type: canvasType + }; + + if (canvasType === CONST.CANVAS) + { + pool.push(container); + } + + canvas = container.canvas; + } + else + { + container.parent = parent; + + canvas = container.canvas; + } + + if (selfParent) + { + container.parent = canvas; + } + + canvas.width = width; + canvas.height = height; + + if (_disableContextSmoothing && canvasType === CONST.CANVAS) + { + Smoothing.disable(canvas.getContext('2d')); + } + + return canvas; + }; + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @function Phaser.Display.Canvas.CanvasPool.create2D + * @since 3.0.0 + * + * @param {*} parent - The parent of the Canvas object. + * @param {integer} [width=1] - The width of the Canvas. + * @param {integer} [height=1] - The height of the Canvas. + * + * @return {HTMLCanvasElement} The created canvas. + */ + var create2D = function (parent, width, height) + { + return create(parent, width, height, CONST.CANVAS); + }; + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @function Phaser.Display.Canvas.CanvasPool.createWebGL + * @since 3.0.0 + * + * @param {*} parent - The parent of the Canvas object. + * @param {integer} [width=1] - The width of the Canvas. + * @param {integer} [height=1] - The height of the Canvas. + * + * @return {HTMLCanvasElement} The created WebGL canvas. + */ + var createWebGL = function (parent, width, height) + { + return create(parent, width, height, CONST.WEBGL); + }; + + /** + * Gets the first free canvas index from the pool. + * + * @function Phaser.Display.Canvas.CanvasPool.first + * @since 3.0.0 + * + * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. + * + * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. + */ + var first = function (canvasType) + { + if (canvasType === undefined) { canvasType = CONST.CANVAS; } + + if (canvasType === CONST.WEBGL) + { + return null; + } + + for (var i = 0; i < pool.length; i++) + { + var container = pool[i]; + + if (!container.parent && container.type === canvasType) + { + return container; + } + } + + return null; + }; + + /** + * 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. + */ + var remove = function (parent) + { + // Check to see if the parent is a canvas object + var isCanvas = parent instanceof HTMLCanvasElement; + + pool.forEach(function (container) + { + if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) + { + container.parent = null; + container.canvas.width = 1; + container.canvas.height = 1; + } + }); + }; + + /** + * Gets the total number of used canvas elements in the pool. + * + * @function Phaser.Display.Canvas.CanvasPool.total + * @since 3.0.0 + * + * @return {integer} The number of used canvases. + */ + var total = function () + { + var c = 0; + + pool.forEach(function (container) + { + if (container.parent) + { + c++; + } + }); + + return c; + }; + + /** + * Gets the total number of free canvas elements in the pool. + * + * @function Phaser.Display.Canvas.CanvasPool.free + * @since 3.0.0 + * + * @return {integer} The number of free canvases. + */ + var free = function () + { + return pool.length - total(); + }; + + /** + * Disable context smoothing on any new Canvas element created. + * + * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing + * @since 3.0.0 + */ + var disableSmoothing = function () + { + _disableContextSmoothing = true; + }; + + /** + * Enable context smoothing on any new Canvas element created. + * + * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing + * @since 3.0.0 + */ + var enableSmoothing = function () + { + _disableContextSmoothing = false; + }; + + return { + create2D: create2D, + create: create, + createWebGL: createWebGL, + disableSmoothing: disableSmoothing, + enableSmoothing: enableSmoothing, + first: first, + free: free, + pool: pool, + remove: remove, + total: total + }; +}; + +// If we export the called function here, it'll only be invoked once (not every time it's required). +module.exports = CanvasPool(); + + +/***/ }), +/* 29 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. + * + * 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`. + */ +var SetTransform = function (renderer, ctx, src, camera, parentMatrix) +{ + var alpha = camera.alpha * src.alpha; + + if (alpha <= 0) + { + // Nothing to see, so don't waste time calculating stuff + return false; + } + + var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); + var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + var calcMatrix = renderer._tempMatrix3; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + gameObjectMatrix.e = src.x; + gameObjectMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + else + { + gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; + gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + + // Blend Mode + ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + + // Alpha + ctx.globalAlpha = alpha; + + ctx.save(); + + calcMatrix.setToContext(ctx); + + ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); + + return true; +}; + +module.exports = SetTransform; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = __webpack_require__(43); +var GetAdvancedValue = __webpack_require__(15); + +/** + * Builds a Game Object using the provided configuration object. + * + * @function Phaser.GameObjects.BuildGameObject + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene. + * @param {Phaser.GameObjects.GameObject} gameObject - The initial GameObject. + * @param {Phaser.Types.GameObjects.GameObjectConfig} config - The config to build the GameObject with. + * + * @return {Phaser.GameObjects.GameObject} The built Game Object. + */ +var BuildGameObject = function (scene, gameObject, config) +{ + // Position + + gameObject.x = GetAdvancedValue(config, 'x', 0); + gameObject.y = GetAdvancedValue(config, 'y', 0); + gameObject.depth = GetAdvancedValue(config, 'depth', 0); + + // Flip + + gameObject.flipX = GetAdvancedValue(config, 'flipX', false); + gameObject.flipY = GetAdvancedValue(config, 'flipY', false); + + // Scale + // Either: { scale: 2 } or { scale: { x: 2, y: 2 }} + + var scale = GetAdvancedValue(config, 'scale', null); + + if (typeof scale === 'number') + { + gameObject.setScale(scale); + } + else if (scale !== null) + { + gameObject.scaleX = GetAdvancedValue(scale, 'x', 1); + gameObject.scaleY = GetAdvancedValue(scale, 'y', 1); + } + + // ScrollFactor + // Either: { scrollFactor: 2 } or { scrollFactor: { x: 2, y: 2 }} + + var scrollFactor = GetAdvancedValue(config, 'scrollFactor', null); + + if (typeof scrollFactor === 'number') + { + gameObject.setScrollFactor(scrollFactor); + } + else if (scrollFactor !== null) + { + gameObject.scrollFactorX = GetAdvancedValue(scrollFactor, 'x', 1); + gameObject.scrollFactorY = GetAdvancedValue(scrollFactor, 'y', 1); + } + + // Rotation + + gameObject.rotation = GetAdvancedValue(config, 'rotation', 0); + + var angle = GetAdvancedValue(config, 'angle', null); + + if (angle !== null) + { + gameObject.angle = angle; + } + + // Alpha + + gameObject.alpha = GetAdvancedValue(config, 'alpha', 1); + + // Origin + // Either: { origin: 0.5 } or { origin: { x: 0.5, y: 0.5 }} + + var origin = GetAdvancedValue(config, 'origin', null); + + if (typeof origin === 'number') + { + gameObject.setOrigin(origin); + } + else if (origin !== null) + { + var ox = GetAdvancedValue(origin, 'x', 0.5); + var oy = GetAdvancedValue(origin, 'y', 0.5); + + gameObject.setOrigin(ox, oy); + } + + // BlendMode + + gameObject.blendMode = GetAdvancedValue(config, 'blendMode', BlendModes.NORMAL); + + // Visible + + gameObject.visible = GetAdvancedValue(config, 'visible', true); + + // Add to Scene + + var add = GetAdvancedValue(config, 'add', true); + + if (add) + { + scene.sys.displayList.add(gameObject); + } + + if (gameObject.preUpdate) + { + scene.sys.updateList.add(gameObject); + } + + return gameObject; +}; + +module.exports = BuildGameObject; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Vertices = {}; + +module.exports = Vertices; + +var Vector = __webpack_require__(37); +var Common = __webpack_require__(19); + +(function() { + + /** + * Creates a new set of `Matter.Body` compatible vertices. + * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example: + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects, + * but with some additional references required for efficient collision detection routines. + * + * Vertices must be specified in clockwise order. + * + * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided. + * + * @method create + * @param {vector[]} points + * @param {body} body + */ + Vertices.create = function(points, body) { + var vertices = []; + + for (var i = 0; i < points.length; i++) { + var point = points[i], + vertex = { + x: point.x, + y: point.y, + index: i, + body: body, + isInternal: false, + contact: null, + offset: null + }; + + vertex.contact = { + vertex: vertex, + normalImpulse: 0, + tangentImpulse: 0 + }; + + vertices.push(vertex); + } + + return vertices; + }; + + /** + * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), + * into a `Matter.Vertices` object for the given `Matter.Body`. + * For parsing SVG paths, see `Svg.pathToVertices`. + * @method fromPath + * @param {string} path + * @param {body} body + * @return {vertices} vertices + */ + Vertices.fromPath = function(path, body) { + var pathPattern = /L?\s*([-\d.e]+)[\s,]*([-\d.e]+)*/ig, + points = []; + + path.replace(pathPattern, function(match, x, y) { + points.push({ x: parseFloat(x), y: parseFloat(y) }); + }); + + return Vertices.create(points, body); + }; + + /** + * Returns the centre (centroid) of the set of vertices. + * @method centre + * @param {vertices} vertices + * @return {vector} The centre point + */ + Vertices.centre = function(vertices) { + var area = Vertices.area(vertices, true), + centre = { x: 0, y: 0 }, + cross, + temp, + j; + + for (var i = 0; i < vertices.length; i++) { + j = (i + 1) % vertices.length; + cross = Vector.cross(vertices[i], vertices[j]); + temp = Vector.mult(Vector.add(vertices[i], vertices[j]), cross); + centre = Vector.add(centre, temp); + } + + return Vector.div(centre, 6 * area); + }; + + /** + * Returns the average (mean) of the set of vertices. + * @method mean + * @param {vertices} vertices + * @return {vector} The average point + */ + Vertices.mean = function(vertices) { + var average = { x: 0, y: 0 }; + + for (var i = 0; i < vertices.length; i++) { + average.x += vertices[i].x; + average.y += vertices[i].y; + } + + return Vector.div(average, vertices.length); + }; + + /** + * Returns the area of the set of vertices. + * @method area + * @param {vertices} vertices + * @param {bool} signed + * @return {number} The area + */ + Vertices.area = function(vertices, signed) { + var area = 0, + j = vertices.length - 1; + + for (var i = 0; i < vertices.length; i++) { + area += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y); + j = i; + } + + if (signed) + return area / 2; + + return Math.abs(area) / 2; + }; + + /** + * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. + * @method inertia + * @param {vertices} vertices + * @param {number} mass + * @return {number} The polygon's moment of inertia + */ + Vertices.inertia = function(vertices, mass) { + var numerator = 0, + denominator = 0, + v = vertices, + cross, + j; + + // find the polygon's moment of inertia, using second moment of area + // from equations at http://www.physicsforums.com/showthread.php?t=25293 + for (var n = 0; n < v.length; n++) { + j = (n + 1) % v.length; + cross = Math.abs(Vector.cross(v[j], v[n])); + numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n])); + denominator += cross; + } + + return (mass / 6) * (numerator / denominator); + }; + + /** + * Translates the set of vertices in-place. + * @method translate + * @param {vertices} vertices + * @param {vector} vector + * @param {number} scalar + */ + Vertices.translate = function(vertices, vector, scalar) { + var i; + if (scalar) { + for (i = 0; i < vertices.length; i++) { + vertices[i].x += vector.x * scalar; + vertices[i].y += vector.y * scalar; + } + } else { + for (i = 0; i < vertices.length; i++) { + vertices[i].x += vector.x; + vertices[i].y += vector.y; + } + } + + return vertices; + }; + + /** + * Rotates the set of vertices in-place. + * @method rotate + * @param {vertices} vertices + * @param {number} angle + * @param {vector} point + */ + Vertices.rotate = function(vertices, angle, point) { + if (angle === 0) + return; + + var cos = Math.cos(angle), + sin = Math.sin(angle); + + for (var i = 0; i < vertices.length; i++) { + var vertice = vertices[i], + dx = vertice.x - point.x, + dy = vertice.y - point.y; + + vertice.x = point.x + (dx * cos - dy * sin); + vertice.y = point.y + (dx * sin + dy * cos); + } + + return vertices; + }; + + /** + * Returns `true` if the `point` is inside the set of `vertices`. + * @method contains + * @param {vertices} vertices + * @param {vector} point + * @return {boolean} True if the vertices contains point, otherwise false + */ + Vertices.contains = function(vertices, point) { + for (var i = 0; i < vertices.length; i++) { + var vertice = vertices[i], + nextVertice = vertices[(i + 1) % vertices.length]; + if ((point.x - vertice.x) * (nextVertice.y - vertice.y) + (point.y - vertice.y) * (vertice.x - nextVertice.x) > 0) { + return false; + } + } + + return true; + }; + + /** + * Scales the vertices from a point (default is centre) in-place. + * @method scale + * @param {vertices} vertices + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + */ + Vertices.scale = function(vertices, scaleX, scaleY, point) { + if (scaleX === 1 && scaleY === 1) + return vertices; + + point = point || Vertices.centre(vertices); + + var vertex, + delta; + + for (var i = 0; i < vertices.length; i++) { + vertex = vertices[i]; + delta = Vector.sub(vertex, point); + vertices[i].x = point.x + delta.x * scaleX; + vertices[i].y = point.y + delta.y * scaleY; + } + + return vertices; + }; + + /** + * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. + * The radius parameter is a single number or an array to specify the radius for each vertex. + * @method chamfer + * @param {vertices} vertices + * @param {number[]} radius + * @param {number} quality + * @param {number} qualityMin + * @param {number} qualityMax + */ + Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) { + if (typeof radius === 'number') { + radius = [radius]; + } else { + radius = radius || [8]; + } + + // quality defaults to -1, which is auto + quality = (typeof quality !== 'undefined') ? quality : -1; + qualityMin = qualityMin || 2; + qualityMax = qualityMax || 14; + + var newVertices = []; + + for (var i = 0; i < vertices.length; i++) { + var prevVertex = vertices[i - 1 >= 0 ? i - 1 : vertices.length - 1], + vertex = vertices[i], + nextVertex = vertices[(i + 1) % vertices.length], + currentRadius = radius[i < radius.length ? i : radius.length - 1]; + + if (currentRadius === 0) { + newVertices.push(vertex); + continue; + } + + var prevNormal = Vector.normalise({ + x: vertex.y - prevVertex.y, + y: prevVertex.x - vertex.x + }); + + var nextNormal = Vector.normalise({ + x: nextVertex.y - vertex.y, + y: vertex.x - nextVertex.x + }); + + var diagonalRadius = Math.sqrt(2 * Math.pow(currentRadius, 2)), + radiusVector = Vector.mult(Common.clone(prevNormal), currentRadius), + midNormal = Vector.normalise(Vector.mult(Vector.add(prevNormal, nextNormal), 0.5)), + scaledVertex = Vector.sub(vertex, Vector.mult(midNormal, diagonalRadius)); + + var precision = quality; + + if (quality === -1) { + // automatically decide precision + precision = Math.pow(currentRadius, 0.32) * 1.75; + } + + precision = Common.clamp(precision, qualityMin, qualityMax); + + // use an even value for precision, more likely to reduce axes by using symmetry + if (precision % 2 === 1) + precision += 1; + + var alpha = Math.acos(Vector.dot(prevNormal, nextNormal)), + theta = alpha / precision; + + for (var j = 0; j < precision; j++) { + newVertices.push(Vector.add(Vector.rotate(radiusVector, theta * j), scaledVertex)); + } + } + + return newVertices; + }; + + /** + * Sorts the input vertices into clockwise order in place. + * @method clockwiseSort + * @param {vertices} vertices + * @return {vertices} vertices + */ + Vertices.clockwiseSort = function(vertices) { + var centre = Vertices.mean(vertices); + + vertices.sort(function(vertexA, vertexB) { + return Vector.angle(centre, vertexA) - Vector.angle(centre, vertexB); + }); + + return vertices; + }; + + /** + * Returns true if the vertices form a convex shape (vertices must be in clockwise order). + * @method isConvex + * @param {vertices} vertices + * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable). + */ + Vertices.isConvex = function(vertices) { + // http://paulbourke.net/geometry/polygonmesh/ + // Copyright (c) Paul Bourke (use permitted) + + var flag = 0, + n = vertices.length, + i, + j, + k, + z; + + if (n < 3) + return null; + + for (i = 0; i < n; i++) { + j = (i + 1) % n; + k = (i + 2) % n; + z = (vertices[j].x - vertices[i].x) * (vertices[k].y - vertices[j].y); + z -= (vertices[j].y - vertices[i].y) * (vertices[k].x - vertices[j].x); + + if (z < 0) { + flag |= 1; + } else if (z > 0) { + flag |= 2; + } + + if (flag === 3) { + return false; + } + } + + if (flag !== 0){ + return true; + } else { + return null; + } + }; + + /** + * Returns the convex hull of the input vertices as a new array of points. + * @method hull + * @param {vertices} vertices + * @return [vertex] vertices + */ + Vertices.hull = function(vertices) { + // http://geomalgorithms.com/a10-_hull-1.html + + var upper = [], + lower = [], + vertex, + i; + + // sort vertices on x-axis (y-axis for ties) + vertices = vertices.slice(0); + vertices.sort(function(vertexA, vertexB) { + var dx = vertexA.x - vertexB.x; + return dx !== 0 ? dx : vertexA.y - vertexB.y; + }); + + // build lower hull + for (i = 0; i < vertices.length; i += 1) { + vertex = vertices[i]; + + while (lower.length >= 2 + && Vector.cross3(lower[lower.length - 2], lower[lower.length - 1], vertex) <= 0) { + lower.pop(); + } + + lower.push(vertex); + } + + // build upper hull + for (i = vertices.length - 1; i >= 0; i -= 1) { + vertex = vertices[i]; + + while (upper.length >= 2 + && Vector.cross3(upper[upper.length - 2], upper[upper.length - 1], vertex) <= 0) { + upper.pop(); + } + + upper.push(vertex); + } + + // 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 + upper.pop(); + lower.pop(); + + return upper.concat(lower); + }; + +})(); + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Global constants. + * + * @ignore + */ + +var CONST = { + + /** + * Phaser Release Version + * + * @name Phaser.VERSION + * @const + * @type {string} + * @since 3.0.0 + */ + VERSION: '3.22.0', + + BlendModes: __webpack_require__(43), + + ScaleModes: __webpack_require__(157), + + /** + * AUTO Detect Renderer. + * + * @name Phaser.AUTO + * @const + * @type {integer} + * @since 3.0.0 + */ + AUTO: 0, + + /** + * Canvas Renderer. + * + * @name Phaser.CANVAS + * @const + * @type {integer} + * @since 3.0.0 + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * + * @name Phaser.WEBGL + * @const + * @type {integer} + * @since 3.0.0 + */ + WEBGL: 2, + + /** + * Headless Renderer. + * + * @name Phaser.HEADLESS + * @const + * @type {integer} + * @since 3.0.0 + */ + HEADLESS: 3, + + /** + * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead + * to help you remember what the value is doing in your code. + * + * @name Phaser.FOREVER + * @const + * @type {integer} + * @since 3.0.0 + */ + FOREVER: -1, + + /** + * Direction constant. + * + * @name Phaser.NONE + * @const + * @type {integer} + * @since 3.0.0 + */ + NONE: 4, + + /** + * Direction constant. + * + * @name Phaser.UP + * @const + * @type {integer} + * @since 3.0.0 + */ + UP: 5, + + /** + * Direction constant. + * + * @name Phaser.DOWN + * @const + * @type {integer} + * @since 3.0.0 + */ + DOWN: 6, + + /** + * Direction constant. + * + * @name Phaser.LEFT + * @const + * @type {integer} + * @since 3.0.0 + */ + LEFT: 7, + + /** + * Direction constant. + * + * @name Phaser.RIGHT + * @const + * @type {integer} + * @since 3.0.0 + */ + RIGHT: 8 + +}; + +module.exports = CONST; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var Line = __webpack_require__(61); + +/** + * @classdesc + * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. + * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. + * + * @class Shape + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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 {string} [type] - The internal type of the Shape. + * @param {any} [data] - The data of the source shape geometry, if any. + */ +var Shape = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Transform, + Components.Visible + ], + + initialize: + + function Shape (scene, type, data) + { + if (type === undefined) { type = 'Shape'; } + + GameObject.call(this, scene, type); + + /** + * The source Shape data. Typically a geometry object. + * You should not manipulate this directly. + * + * @name Phaser.GameObjects.Shape#data + * @type {any} + * @readonly + * @since 3.13.0 + */ + this.geom = data; + + /** + * Holds the polygon path data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathData + * @type {number[]} + * @readonly + * @since 3.13.0 + */ + this.pathData = []; + + /** + * Holds the earcut polygon path index data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathIndexes + * @type {integer[]} + * @readonly + * @since 3.13.0 + */ + this.pathIndexes = []; + + /** + * The fill color used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillColor + * @type {number} + * @since 3.13.0 + */ + this.fillColor = 0xffffff; + + /** + * The fill alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillAlpha + * @type {number} + * @since 3.13.0 + */ + this.fillAlpha = 1; + + /** + * The stroke color used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeColor + * @type {number} + * @since 3.13.0 + */ + this.strokeColor = 0xffffff; + + /** + * The stroke alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeAlpha + * @type {number} + * @since 3.13.0 + */ + this.strokeAlpha = 1; + + /** + * The stroke line width used by this Shape. + * + * @name Phaser.GameObjects.Shape#lineWidth + * @type {number} + * @since 3.13.0 + */ + this.lineWidth = 1; + + /** + * Controls if this Shape is filled or not. + * Note that some Shapes do not support being filled (such as Line shapes) + * + * @name Phaser.GameObjects.Shape#isFilled + * @type {boolean} + * @since 3.13.0 + */ + this.isFilled = false; + + /** + * Controls if this Shape is stroked or not. + * Note that some Shapes do not support being stroked (such as Iso Box shapes) + * + * @name Phaser.GameObjects.Shape#isStroked + * @type {boolean} + * @since 3.13.0 + */ + this.isStroked = false; + + /** + * Controls if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * @name Phaser.GameObjects.Shape#closePath + * @type {boolean} + * @since 3.13.0 + */ + this.closePath = true; + + /** + * Private internal value. + * A Line used when parsing internal path data to avoid constant object re-creation. + * + * @name Phaser.GameObjects.Curve#_tempLine + * @type {Phaser.Geom.Line} + * @private + * @since 3.13.0 + */ + this._tempLine = new Line(); + + this.initPipeline(); + }, + + /** + * Sets the fill color and alpha for this Shape. + * + * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. + * + * Note that some Shapes do not support fill colors, such as the Line shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setFillStyle + * @since 3.13.0 + * + * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. + * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (color === undefined) + { + this.isFilled = false; + } + else + { + this.fillColor = color; + this.fillAlpha = alpha; + this.isFilled = true; + } + + return this; + }, + + /** + * Sets the stroke color and alpha for this Shape. + * + * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. + * + * Note that some Shapes do not support being stroked, such as the Iso Box shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setStrokeStyle + * @since 3.13.0 + * + * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. + * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. + * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. + * + * @return {this} This Game Object instance. + */ + setStrokeStyle: function (lineWidth, color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (lineWidth === undefined) + { + this.isStroked = false; + } + else + { + this.lineWidth = lineWidth; + this.strokeColor = color; + this.strokeAlpha = alpha; + this.isStroked = true; + } + + return this; + }, + + /** + * Sets if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setClosePath + * @since 3.13.0 + * + * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. + * + * @return {this} This Game Object instance. + */ + setClosePath: function (value) + { + this.closePath = value; + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Shape#preDestroy + * @protected + * @since 3.13.0 + */ + preDestroy: function () + { + this.geom = null; + this._tempLine = null; + this.pathData = []; + this.pathIndexes = []; + } + +}); + +module.exports = Shape; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Formats + */ + +module.exports = { + + /** + * CSV Map Type + * + * @name Phaser.Tilemaps.Formats.CSV + * @type {number} + * @since 3.0.0 + */ + CSV: 0, + + /** + * Tiled JSON Map Type + * + * @name Phaser.Tilemaps.Formats.TILED_JSON + * @type {number} + * @since 3.0.0 + */ + TILED_JSON: 1, + + /** + * 2D Array Map Type + * + * @name Phaser.Tilemaps.Formats.ARRAY_2D + * @type {number} + * @since 3.0.0 + */ + ARRAY_2D: 2, + + /** + * Weltmeister (Impact.js) Map Type + * + * @name Phaser.Tilemaps.Formats.WELTMEISTER + * @type {number} + * @since 3.0.0 + */ + WELTMEISTER: 3 + +}; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var MATH_CONST = __webpack_require__(13); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Matrix used for display transformations for rendering. + * + * It is represented like so: + * + * ``` + * | a | c | tx | + * | b | d | ty | + * | 0 | 0 | 1 | + * ``` + * + * @class TransformMatrix + * @memberof Phaser.GameObjects.Components + * @constructor + * @since 3.0.0 + * + * @param {number} [a=1] - The Scale X value. + * @param {number} [b=0] - The Skew Y value. + * @param {number} [c=0] - The Skew X value. + * @param {number} [d=1] - The Scale Y value. + * @param {number} [tx=0] - The Translate X value. + * @param {number} [ty=0] - The Translate Y value. + */ +var TransformMatrix = new Class({ + + initialize: + + function TransformMatrix (a, b, c, d, tx, ty) + { + if (a === undefined) { a = 1; } + if (b === undefined) { b = 0; } + if (c === undefined) { c = 0; } + if (d === undefined) { d = 1; } + if (tx === undefined) { tx = 0; } + if (ty === undefined) { ty = 0; } + + /** + * The matrix values. + * + * @name Phaser.GameObjects.Components.TransformMatrix#matrix + * @type {Float32Array} + * @since 3.0.0 + */ + this.matrix = new Float32Array([ a, b, c, d, tx, ty, 0, 0, 1 ]); + + /** + * The decomposed matrix. + * + * @name Phaser.GameObjects.Components.TransformMatrix#decomposedMatrix + * @type {object} + * @since 3.0.0 + */ + this.decomposedMatrix = { + translateX: 0, + translateY: 0, + scaleX: 1, + scaleY: 1, + rotation: 0 + }; + }, + + /** + * The Scale X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#a + * @type {number} + * @since 3.4.0 + */ + a: { + + get: function () + { + return this.matrix[0]; + }, + + set: function (value) + { + this.matrix[0] = value; + } + + }, + + /** + * The Skew Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#b + * @type {number} + * @since 3.4.0 + */ + b: { + + get: function () + { + return this.matrix[1]; + }, + + set: function (value) + { + this.matrix[1] = value; + } + + }, + + /** + * The Skew X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#c + * @type {number} + * @since 3.4.0 + */ + c: { + + get: function () + { + return this.matrix[2]; + }, + + set: function (value) + { + this.matrix[2] = value; + } + + }, + + /** + * The Scale Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#d + * @type {number} + * @since 3.4.0 + */ + d: { + + get: function () + { + return this.matrix[3]; + }, + + set: function (value) + { + this.matrix[3] = value; + } + + }, + + /** + * The Translate X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#e + * @type {number} + * @since 3.11.0 + */ + e: { + + get: function () + { + return this.matrix[4]; + }, + + set: function (value) + { + this.matrix[4] = value; + } + + }, + + /** + * The Translate Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#f + * @type {number} + * @since 3.11.0 + */ + f: { + + get: function () + { + return this.matrix[5]; + }, + + set: function (value) + { + this.matrix[5] = value; + } + + }, + + /** + * The Translate X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#tx + * @type {number} + * @since 3.4.0 + */ + tx: { + + get: function () + { + return this.matrix[4]; + }, + + set: function (value) + { + this.matrix[4] = value; + } + + }, + + /** + * The Translate Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#ty + * @type {number} + * @since 3.4.0 + */ + ty: { + + get: function () + { + return this.matrix[5]; + }, + + set: function (value) + { + this.matrix[5] = value; + } + + }, + + /** + * The rotation of the Matrix. Value is in radians. + * + * @name Phaser.GameObjects.Components.TransformMatrix#rotation + * @type {number} + * @readonly + * @since 3.4.0 + */ + rotation: { + + get: function () + { + return Math.acos(this.a / this.scaleX) * ((Math.atan(-this.c / this.a) < 0) ? -1 : 1); + } + + }, + + /** + * The rotation of the Matrix, normalized to be within the Phaser right-handed + * clockwise rotation space. Value is in radians. + * + * @name Phaser.GameObjects.Components.TransformMatrix#rotationNormalized + * @type {number} + * @readonly + * @since 3.19.0 + */ + rotationNormalized: { + + get: function () + { + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + + if (a || b) + { + // var r = Math.sqrt(a * a + b * b); + + return (b > 0) ? Math.acos(a / this.scaleX) : -Math.acos(a / this.scaleX); + } + else if (c || d) + { + // var s = Math.sqrt(c * c + d * d); + + return MATH_CONST.TAU - ((d > 0) ? Math.acos(-c / this.scaleY) : -Math.acos(c / this.scaleY)); + } + else + { + return 0; + } + } + + }, + + /** + * The decomposed horizontal scale of the Matrix. This value is always positive. + * + * @name Phaser.GameObjects.Components.TransformMatrix#scaleX + * @type {number} + * @readonly + * @since 3.4.0 + */ + scaleX: { + + get: function () + { + return Math.sqrt((this.a * this.a) + (this.b * this.b)); + } + + }, + + /** + * The decomposed vertical scale of the Matrix. This value is always positive. + * + * @name Phaser.GameObjects.Components.TransformMatrix#scaleY + * @type {number} + * @readonly + * @since 3.4.0 + */ + scaleY: { + + get: function () + { + return Math.sqrt((this.c * this.c) + (this.d * this.d)); + } + + }, + + /** + * Reset the Matrix to an identity matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#loadIdentity + * @since 3.0.0 + * + * @return {this} This TransformMatrix. + */ + loadIdentity: function () + { + var matrix = this.matrix; + + matrix[0] = 1; + matrix[1] = 0; + matrix[2] = 0; + matrix[3] = 1; + matrix[4] = 0; + matrix[5] = 0; + + return this; + }, + + /** + * Translate the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#translate + * @since 3.0.0 + * + * @param {number} x - The horizontal translation value. + * @param {number} y - The vertical translation value. + * + * @return {this} This TransformMatrix. + */ + translate: function (x, y) + { + var matrix = this.matrix; + + matrix[4] = matrix[0] * x + matrix[2] * y + matrix[4]; + matrix[5] = matrix[1] * x + matrix[3] * y + matrix[5]; + + return this; + }, + + /** + * Scale the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#scale + * @since 3.0.0 + * + * @param {number} x - The horizontal scale value. + * @param {number} y - The vertical scale value. + * + * @return {this} This TransformMatrix. + */ + scale: function (x, y) + { + var matrix = this.matrix; + + matrix[0] *= x; + matrix[1] *= x; + matrix[2] *= y; + matrix[3] *= y; + + return this; + }, + + /** + * Rotate the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#rotate + * @since 3.0.0 + * + * @param {number} angle - The angle of rotation in radians. + * + * @return {this} This TransformMatrix. + */ + rotate: function (angle) + { + var sin = Math.sin(angle); + var cos = Math.cos(angle); + + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + + matrix[0] = a * cos + c * sin; + matrix[1] = b * cos + d * sin; + matrix[2] = a * -sin + c * cos; + matrix[3] = b * -sin + d * cos; + + return this; + }, + + /** + * Multiply this Matrix by the given Matrix. + * + * If an `out` Matrix is given then the results will be stored in it. + * If it is not given, this matrix will be updated in place instead. + * Use an `out` Matrix if you do not wish to mutate this matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#multiply + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} rhs - The Matrix to multiply by. + * @param {Phaser.GameObjects.Components.TransformMatrix} [out] - An optional Matrix to store the results in. + * + * @return {Phaser.GameObjects.Components.TransformMatrix} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. + */ + multiply: function (rhs, out) + { + var matrix = this.matrix; + var source = rhs.matrix; + + var localA = matrix[0]; + var localB = matrix[1]; + var localC = matrix[2]; + var localD = matrix[3]; + var localE = matrix[4]; + var localF = matrix[5]; + + var sourceA = source[0]; + var sourceB = source[1]; + var sourceC = source[2]; + var sourceD = source[3]; + var sourceE = source[4]; + var sourceF = source[5]; + + var destinationMatrix = (out === undefined) ? this : out; + + destinationMatrix.a = (sourceA * localA) + (sourceB * localC); + destinationMatrix.b = (sourceA * localB) + (sourceB * localD); + destinationMatrix.c = (sourceC * localA) + (sourceD * localC); + destinationMatrix.d = (sourceC * localB) + (sourceD * localD); + destinationMatrix.e = (sourceE * localA) + (sourceF * localC) + localE; + destinationMatrix.f = (sourceE * localB) + (sourceF * localD) + localF; + + return destinationMatrix; + }, + + /** + * Multiply this Matrix by the matrix given, including the offset. + * + * The offsetX is added to the tx value: `offsetX * a + offsetY * c + tx`. + * The offsetY is added to the ty value: `offsetY * b + offsetY * d + ty`. + * + * @method Phaser.GameObjects.Components.TransformMatrix#multiplyWithOffset + * @since 3.11.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} src - The source Matrix to copy from. + * @param {number} offsetX - Horizontal offset to factor in to the multiplication. + * @param {number} offsetY - Vertical offset to factor in to the multiplication. + * + * @return {this} This TransformMatrix. + */ + multiplyWithOffset: function (src, offsetX, offsetY) + { + var matrix = this.matrix; + var otherMatrix = src.matrix; + + var a0 = matrix[0]; + var b0 = matrix[1]; + var c0 = matrix[2]; + var d0 = matrix[3]; + var tx0 = matrix[4]; + var ty0 = matrix[5]; + + var pse = offsetX * a0 + offsetY * c0 + tx0; + var psf = offsetX * b0 + offsetY * d0 + ty0; + + var a1 = otherMatrix[0]; + var b1 = otherMatrix[1]; + var c1 = otherMatrix[2]; + var d1 = otherMatrix[3]; + var tx1 = otherMatrix[4]; + var ty1 = otherMatrix[5]; + + matrix[0] = a1 * a0 + b1 * c0; + matrix[1] = a1 * b0 + b1 * d0; + matrix[2] = c1 * a0 + d1 * c0; + matrix[3] = c1 * b0 + d1 * d0; + matrix[4] = tx1 * a0 + ty1 * c0 + pse; + matrix[5] = tx1 * b0 + ty1 * d0 + psf; + + return this; + }, + + /** + * Transform the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#transform + * @since 3.0.0 + * + * @param {number} a - The Scale X value. + * @param {number} b - The Shear Y value. + * @param {number} c - The Shear X value. + * @param {number} d - The Scale Y value. + * @param {number} tx - The Translate X value. + * @param {number} ty - The Translate Y value. + * + * @return {this} This TransformMatrix. + */ + transform: function (a, b, c, d, tx, ty) + { + var matrix = this.matrix; + + var a0 = matrix[0]; + var b0 = matrix[1]; + var c0 = matrix[2]; + var d0 = matrix[3]; + var tx0 = matrix[4]; + var ty0 = matrix[5]; + + matrix[0] = a * a0 + b * c0; + matrix[1] = a * b0 + b * d0; + matrix[2] = c * a0 + d * c0; + matrix[3] = c * b0 + d * d0; + matrix[4] = tx * a0 + ty * c0 + tx0; + matrix[5] = tx * b0 + ty * d0 + ty0; + + return this; + }, + + /** + * Transform a point using this Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#transformPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the point to transform. + * @param {number} y - The y coordinate of the point to transform. + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The Point object to store the transformed coordinates. + * + * @return {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} The Point containing the transformed coordinates. + */ + transformPoint: function (x, y, point) + { + if (point === undefined) { point = { x: 0, y: 0 }; } + + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + var tx = matrix[4]; + var ty = matrix[5]; + + point.x = x * a + y * c + tx; + point.y = x * b + y * d + ty; + + return point; + }, + + /** + * Invert the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#invert + * @since 3.0.0 + * + * @return {this} This TransformMatrix. + */ + invert: function () + { + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + var tx = matrix[4]; + var ty = matrix[5]; + + var n = a * d - b * c; + + matrix[0] = d / n; + matrix[1] = -b / n; + matrix[2] = -c / n; + matrix[3] = a / n; + matrix[4] = (c * ty - d * tx) / n; + matrix[5] = -(a * ty - b * tx) / n; + + return this; + }, + + /** + * Set the values of this Matrix to copy those of the matrix given. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyFrom + * @since 3.11.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} src - The source Matrix to copy from. + * + * @return {this} This TransformMatrix. + */ + copyFrom: function (src) + { + var matrix = this.matrix; + + matrix[0] = src.a; + matrix[1] = src.b; + matrix[2] = src.c; + matrix[3] = src.d; + matrix[4] = src.e; + matrix[5] = src.f; + + return this; + }, + + /** + * Set the values of this Matrix to copy those of the array given. + * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyFromArray + * @since 3.11.0 + * + * @param {array} src - The array of values to set into this matrix. + * + * @return {this} This TransformMatrix. + */ + copyFromArray: function (src) + { + var matrix = this.matrix; + + matrix[0] = src[0]; + matrix[1] = src[1]; + matrix[2] = src[2]; + matrix[3] = src[3]; + matrix[4] = src[4]; + matrix[5] = src[5]; + + return this; + }, + + /** + * Copy the values from this Matrix to the given Canvas Rendering Context. + * This will use the Context.transform method. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyToContext + * @since 3.12.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas Rendering Context to copy the matrix values to. + * + * @return {CanvasRenderingContext2D} The Canvas Rendering Context. + */ + copyToContext: function (ctx) + { + var matrix = this.matrix; + + ctx.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + return ctx; + }, + + /** + * Copy the values from this Matrix to the given Canvas Rendering Context. + * This will use the Context.setTransform method. + * + * @method Phaser.GameObjects.Components.TransformMatrix#setToContext + * @since 3.12.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas Rendering Context to copy the matrix values to. + * + * @return {CanvasRenderingContext2D} The Canvas Rendering Context. + */ + setToContext: function (ctx) + { + var matrix = this.matrix; + + ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + return ctx; + }, + + /** + * Copy the values in this Matrix to the array given. + * + * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyToArray + * @since 3.12.0 + * + * @param {array} [out] - The array to copy the matrix values in to. + * + * @return {array} An array where elements 0 to 5 contain the values from this matrix. + */ + copyToArray: function (out) + { + var matrix = this.matrix; + + if (out === undefined) + { + out = [ matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5] ]; + } + else + { + out[0] = matrix[0]; + out[1] = matrix[1]; + out[2] = matrix[2]; + out[3] = matrix[3]; + out[4] = matrix[4]; + out[5] = matrix[5]; + } + + return out; + }, + + /** + * Set the values of this Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#setTransform + * @since 3.0.0 + * + * @param {number} a - The Scale X value. + * @param {number} b - The Shear Y value. + * @param {number} c - The Shear X value. + * @param {number} d - The Scale Y value. + * @param {number} tx - The Translate X value. + * @param {number} ty - The Translate Y value. + * + * @return {this} This TransformMatrix. + */ + setTransform: function (a, b, c, d, tx, ty) + { + var matrix = this.matrix; + + matrix[0] = a; + matrix[1] = b; + matrix[2] = c; + matrix[3] = d; + matrix[4] = tx; + matrix[5] = ty; + + return this; + }, + + /** + * Decompose this Matrix into its translation, scale and rotation values using QR decomposition. + * + * The result must be applied in the following order to reproduce the current matrix: + * + * translate -> rotate -> scale + * + * @method Phaser.GameObjects.Components.TransformMatrix#decomposeMatrix + * @since 3.0.0 + * + * @return {object} The decomposed Matrix. + */ + decomposeMatrix: function () + { + var decomposedMatrix = this.decomposedMatrix; + + var matrix = this.matrix; + + // a = scale X (1) + // b = shear Y (0) + // c = shear X (0) + // d = scale Y (1) + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + + var determ = a * d - b * c; + + decomposedMatrix.translateX = matrix[4]; + decomposedMatrix.translateY = matrix[5]; + + if (a || b) + { + var r = Math.sqrt(a * a + b * b); + + decomposedMatrix.rotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + decomposedMatrix.scaleX = r; + decomposedMatrix.scaleY = determ / r; + } + else if (c || d) + { + var s = Math.sqrt(c * c + d * d); + + decomposedMatrix.rotation = Math.PI * 0.5 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s)); + decomposedMatrix.scaleX = determ / s; + decomposedMatrix.scaleY = s; + } + else + { + decomposedMatrix.rotation = 0; + decomposedMatrix.scaleX = 0; + decomposedMatrix.scaleY = 0; + } + + return decomposedMatrix; + }, + + /** + * Apply the identity, translate, rotate and scale operations on the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#applyITRS + * @since 3.0.0 + * + * @param {number} x - The horizontal translation. + * @param {number} y - The vertical translation. + * @param {number} rotation - The angle of rotation in radians. + * @param {number} scaleX - The horizontal scale. + * @param {number} scaleY - The vertical scale. + * + * @return {this} This TransformMatrix. + */ + applyITRS: function (x, y, rotation, scaleX, scaleY) + { + var matrix = this.matrix; + + var radianSin = Math.sin(rotation); + var radianCos = Math.cos(rotation); + + // Translate + matrix[4] = x; + matrix[5] = y; + + // Rotate and Scale + matrix[0] = radianCos * scaleX; + matrix[1] = radianSin * scaleX; + matrix[2] = -radianSin * scaleY; + matrix[3] = radianCos * scaleY; + + return this; + }, + + /** + * Takes the `x` and `y` values and returns a new position in the `output` vector that is the inverse of + * the current matrix with its transformation applied. + * + * Can be used to translate points from world to local space. + * + * @method Phaser.GameObjects.Components.TransformMatrix#applyInverse + * @since 3.12.0 + * + * @param {number} x - The x position to translate. + * @param {number} y - The y position to translate. + * @param {Phaser.Math.Vector2} [output] - A Vector2, or point-like object, to store the results in. + * + * @return {Phaser.Math.Vector2} The coordinates, inverse-transformed through this matrix. + */ + applyInverse: function (x, y, output) + { + if (output === undefined) { output = new Vector2(); } + + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + var tx = matrix[4]; + var ty = matrix[5]; + + var id = 1 / ((a * d) + (c * -b)); + + output.x = (d * id * x) + (-c * id * y) + (((ty * c) - (tx * d)) * id); + output.y = (a * id * y) + (-b * id * x) + (((-ty * a) + (tx * b)) * id); + + return output; + }, + + /** + * Returns the X component of this matrix multiplied by the given values. + * This is the same as `x * a + y * c + e`. + * + * @method Phaser.GameObjects.Components.TransformMatrix#getX + * @since 3.12.0 + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * + * @return {number} The calculated x value. + */ + getX: function (x, y) + { + return x * this.a + y * this.c + this.e; + }, + + /** + * Returns the Y component of this matrix multiplied by the given values. + * This is the same as `x * b + y * d + f`. + * + * @method Phaser.GameObjects.Components.TransformMatrix#getY + * @since 3.12.0 + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * + * @return {number} The calculated y value. + */ + getY: function (x, y) + { + return x * this.b + y * this.d + this.f; + }, + + /** + * Returns a string that can be used in a CSS Transform call as a `matrix` property. + * + * @method Phaser.GameObjects.Components.TransformMatrix#getCSSMatrix + * @since 3.12.0 + * + * @return {string} A string containing the CSS Transform matrix values. + */ + getCSSMatrix: function () + { + var m = this.matrix; + + return 'matrix(' + m[0] + ',' + m[1] + ',' + m[2] + ',' + m[3] + ',' + m[4] + ',' + m[5] + ')'; + }, + + /** + * Destroys this Transform Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#destroy + * @since 3.4.0 + */ + destroy: function () + { + this.matrix = null; + this.decomposedMatrix = null; + } + +}); + +module.exports = TransformMatrix; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetColor = __webpack_require__(175); +var GetColor32 = __webpack_require__(314); +var HSVToRGB = __webpack_require__(176); +var RGBToHSV = __webpack_require__(315); + +/** + * @namespace Phaser.Display.Color + */ + +/** + * @classdesc + * The Color class holds a single color value and allows for easy modification and reading of it. + * + * @class Color + * @memberof Phaser.Display + * @constructor + * @since 3.0.0 + * + * @param {integer} [red=0] - The red color value. A number between 0 and 255. + * @param {integer} [green=0] - The green color value. A number between 0 and 255. + * @param {integer} [blue=0] - The blue color value. A number between 0 and 255. + * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. + */ +var Color = new Class({ + + initialize: + + function Color (red, green, blue, alpha) + { + if (red === undefined) { red = 0; } + if (green === undefined) { green = 0; } + if (blue === undefined) { blue = 0; } + if (alpha === undefined) { alpha = 255; } + + /** + * The internal red color value. + * + * @name Phaser.Display.Color#r + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.r = 0; + + /** + * The internal green color value. + * + * @name Phaser.Display.Color#g + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.g = 0; + + /** + * The internal blue color value. + * + * @name Phaser.Display.Color#b + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.b = 0; + + /** + * The internal alpha color value. + * + * @name Phaser.Display.Color#a + * @type {number} + * @private + * @default 255 + * @since 3.0.0 + */ + this.a = 255; + + /** + * The hue color value. A number between 0 and 1. + * This is the base color. + * + * @name Phaser.Display.Color#_h + * @type {number} + * @default 0 + * @private + * @since 3.13.0 + */ + this._h = 0; + + /** + * The saturation color value. A number between 0 and 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. + * + * @name Phaser.Display.Color#_s + * @type {number} + * @default 0 + * @private + * @since 3.13.0 + */ + this._s = 0; + + /** + * The lightness color value. A number between 0 and 1. + * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. + * + * @name Phaser.Display.Color#_v + * @type {number} + * @default 0 + * @private + * @since 3.13.0 + */ + this._v = 0; + + /** + * Is this color update locked? + * + * @name Phaser.Display.Color#_locked + * @type {boolean} + * @private + * @since 3.13.0 + */ + this._locked = false; + + /** + * An array containing the calculated color values for WebGL use. + * + * @name Phaser.Display.Color#gl + * @type {number[]} + * @since 3.0.0 + */ + this.gl = [ 0, 0, 0, 1 ]; + + /** + * Pre-calculated internal color value. + * + * @name Phaser.Display.Color#_color + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._color = 0; + + /** + * Pre-calculated internal color32 value. + * + * @name Phaser.Display.Color#_color32 + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._color32 = 0; + + /** + * Pre-calculated internal color rgb string value. + * + * @name Phaser.Display.Color#_rgba + * @type {string} + * @private + * @default '' + * @since 3.0.0 + */ + this._rgba = ''; + + this.setTo(red, green, blue, alpha); + }, + + /** + * Sets this color to be transparent. Sets all values to zero. + * + * @method Phaser.Display.Color#transparent + * @since 3.0.0 + * + * @return {Phaser.Display.Color} This Color object. + */ + transparent: function () + { + this._locked = true; + + this.red = 0; + this.green = 0; + this.blue = 0; + this.alpha = 0; + + this._locked = false; + + return this.update(true); + }, + + /** + * Sets the color of this Color component. + * + * @method Phaser.Display.Color#setTo + * @since 3.0.0 + * + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. + * @param {boolean} [updateHSV=true] - Update the HSV values after setting the RGB values? + * + * @return {Phaser.Display.Color} This Color object. + */ + setTo: function (red, green, blue, alpha, updateHSV) + { + if (alpha === undefined) { alpha = 255; } + if (updateHSV === undefined) { updateHSV = true; } + + this._locked = true; + + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + + this._locked = false; + + return this.update(updateHSV); + }, + + /** + * Sets the red, green, blue and alpha GL values of this Color component. + * + * @method Phaser.Display.Color#setGLTo + * @since 3.0.0 + * + * @param {number} red - The red color value. A number between 0 and 1. + * @param {number} green - The green color value. A number between 0 and 1. + * @param {number} blue - The blue color value. A number between 0 and 1. + * @param {number} [alpha=1] - The alpha value. A number between 0 and 1. + * + * @return {Phaser.Display.Color} This Color object. + */ + setGLTo: function (red, green, blue, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this._locked = true; + + this.redGL = red; + this.greenGL = green; + this.blueGL = blue; + this.alphaGL = alpha; + + this._locked = false; + + return this.update(true); + }, + + /** + * 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. + */ + setFromRGB: function (color) + { + this._locked = true; + + this.red = color.r; + this.green = color.g; + this.blue = color.b; + + if (color.hasOwnProperty('a')) + { + this.alpha = color.a; + } + + this._locked = false; + + return this.update(true); + }, + + /** + * Sets the color based on the hue, saturation and lightness values 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. + */ + setFromHSV: function (h, s, v) + { + return HSVToRGB(h, s, v, this); + }, + + /** + * Updates the internal cache values. + * + * @method Phaser.Display.Color#update + * @private + * @since 3.0.0 + * + * @return {Phaser.Display.Color} This Color object. + */ + update: function (updateHSV) + { + if (updateHSV === undefined) { updateHSV = false; } + + if (this._locked) + { + return this; + } + + var r = this.r; + var g = this.g; + var b = this.b; + var a = this.a; + + this._color = GetColor(r, g, b); + this._color32 = GetColor32(r, g, b, a); + this._rgba = 'rgba(' + r + ',' + g + ',' + b + ',' + (a / 255) + ')'; + + if (updateHSV) + { + RGBToHSV(r, g, b, this); + } + + return this; + }, + + /** + * Updates the internal hsv cache values. + * + * @method Phaser.Display.Color#updateHSV + * @private + * @since 3.13.0 + * + * @return {Phaser.Display.Color} This Color object. + */ + updateHSV: function () + { + var r = this.r; + var g = this.g; + var b = this.b; + + RGBToHSV(r, g, b, this); + + return this; + }, + + /** + * Returns a new Color component using the values from this one. + * + * @method Phaser.Display.Color#clone + * @since 3.0.0 + * + * @return {Phaser.Display.Color} A new Color object. + */ + clone: function () + { + return new Color(this.r, this.g, this.b, this.a); + }, + + /** + * Sets this Color object to be grayscaled based on the shade value given. + * + * @method Phaser.Display.Color#gray + * @since 3.13.0 + * + * @param {integer} shade - A value between 0 and 255. + * + * @return {Phaser.Display.Color} This Color object. + */ + gray: function (shade) + { + return this.setTo(shade, shade, shade); + }, + + /** + * Sets this Color object to be a random color between the `min` and `max` values given. + * + * @method Phaser.Display.Color#random + * @since 3.13.0 + * + * @param {integer} [min=0] - The minimum random color value. Between 0 and 255. + * @param {integer} [max=255] - The maximum random color value. Between 0 and 255. + * + * @return {Phaser.Display.Color} This Color object. + */ + random: function (min, max) + { + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + + var r = Math.floor(min + Math.random() * (max - min)); + var g = Math.floor(min + Math.random() * (max - min)); + var b = Math.floor(min + Math.random() * (max - min)); + + return this.setTo(r, g, b); + }, + + /** + * Sets this Color object to be a random grayscale color between the `min` and `max` values given. + * + * @method Phaser.Display.Color#randomGray + * @since 3.13.0 + * + * @param {integer} [min=0] - The minimum random color value. Between 0 and 255. + * @param {integer} [max=255] - The maximum random color value. Between 0 and 255. + * + * @return {Phaser.Display.Color} This Color object. + */ + randomGray: function (min, max) + { + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + + var s = Math.floor(min + Math.random() * (max - min)); + + return this.setTo(s, s, s); + }, + + /** + * Increase the saturation of this Color by the percentage amount given. + * The saturation is the amount of the base color in the hue. + * + * @method Phaser.Display.Color#saturate + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + saturate: function (amount) + { + this.s += amount / 100; + + return this; + }, + + /** + * Decrease the saturation of this Color by the percentage amount given. + * The saturation is the amount of the base color in the hue. + * + * @method Phaser.Display.Color#desaturate + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + desaturate: function (amount) + { + this.s -= amount / 100; + + return this; + }, + + /** + * Increase the lightness of this Color by the percentage amount given. + * + * @method Phaser.Display.Color#lighten + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + lighten: function (amount) + { + this.v += amount / 100; + + return this; + }, + + /** + * Decrease the lightness of this Color by the percentage amount given. + * + * @method Phaser.Display.Color#darken + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + darken: function (amount) + { + this.v -= amount / 100; + + return this; + }, + + /** + * Brighten this Color by the percentage amount given. + * + * @method Phaser.Display.Color#brighten + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + brighten: function (amount) + { + var r = this.r; + var g = this.g; + var b = this.b; + + r = Math.max(0, Math.min(255, r - Math.round(255 * - (amount / 100)))); + g = Math.max(0, Math.min(255, g - Math.round(255 * - (amount / 100)))); + b = Math.max(0, Math.min(255, b - Math.round(255 * - (amount / 100)))); + + return this.setTo(r, g, b); + }, + + /** + * The color of this Color component, not including the alpha channel. + * + * @name Phaser.Display.Color#color + * @type {number} + * @readonly + * @since 3.0.0 + */ + color: { + + get: function () + { + return this._color; + } + + }, + + /** + * The color of this Color component, including the alpha channel. + * + * @name Phaser.Display.Color#color32 + * @type {number} + * @readonly + * @since 3.0.0 + */ + color32: { + + get: function () + { + return this._color32; + } + + }, + + /** + * The color of this Color component as a string which can be used in CSS color values. + * + * @name Phaser.Display.Color#rgba + * @type {string} + * @readonly + * @since 3.0.0 + */ + rgba: { + + get: function () + { + return this._rgba; + } + + }, + + /** + * The red color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#redGL + * @type {number} + * @since 3.0.0 + */ + redGL: { + + get: function () + { + return this.gl[0]; + }, + + set: function (value) + { + this.gl[0] = Math.min(Math.abs(value), 1); + + this.r = Math.floor(this.gl[0] * 255); + + this.update(true); + } + + }, + + /** + * The green color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#greenGL + * @type {number} + * @since 3.0.0 + */ + greenGL: { + + get: function () + { + return this.gl[1]; + }, + + set: function (value) + { + this.gl[1] = Math.min(Math.abs(value), 1); + + this.g = Math.floor(this.gl[1] * 255); + + this.update(true); + } + + }, + + /** + * The blue color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#blueGL + * @type {number} + * @since 3.0.0 + */ + blueGL: { + + get: function () + { + return this.gl[2]; + }, + + set: function (value) + { + this.gl[2] = Math.min(Math.abs(value), 1); + + this.b = Math.floor(this.gl[2] * 255); + + this.update(true); + } + + }, + + /** + * The alpha color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#alphaGL + * @type {number} + * @since 3.0.0 + */ + alphaGL: { + + get: function () + { + return this.gl[3]; + }, + + set: function (value) + { + this.gl[3] = Math.min(Math.abs(value), 1); + + this.a = Math.floor(this.gl[3] * 255); + + this.update(); + } + + }, + + /** + * The red color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#red + * @type {number} + * @since 3.0.0 + */ + red: { + + get: function () + { + return this.r; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.r = Math.min(value, 255); + + this.gl[0] = value / 255; + + this.update(true); + } + + }, + + /** + * The green color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#green + * @type {number} + * @since 3.0.0 + */ + green: { + + get: function () + { + return this.g; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.g = Math.min(value, 255); + + this.gl[1] = value / 255; + + this.update(true); + } + + }, + + /** + * The blue color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#blue + * @type {number} + * @since 3.0.0 + */ + blue: { + + get: function () + { + return this.b; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.b = Math.min(value, 255); + + this.gl[2] = value / 255; + + this.update(true); + } + + }, + + /** + * The alpha color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this.a; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.a = Math.min(value, 255); + + this.gl[3] = value / 255; + + this.update(); + } + + }, + + /** + * The hue color value. A number between 0 and 1. + * This is the base color. + * + * @name Phaser.Display.Color#h + * @type {number} + * @since 3.13.0 + */ + h: { + + get: function () + { + return this._h; + }, + + set: function (value) + { + this._h = value; + + HSVToRGB(value, this._s, this._v, this); + } + + }, + + /** + * The saturation color value. A number between 0 and 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. + * + * @name Phaser.Display.Color#s + * @type {number} + * @since 3.13.0 + */ + s: { + + get: function () + { + return this._s; + }, + + set: function (value) + { + this._s = value; + + HSVToRGB(this._h, value, this._v, this); + } + + }, + + /** + * The lightness color value. A number between 0 and 1. + * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. + * + * @name Phaser.Display.Color#v + * @type {number} + * @since 3.13.0 + */ + v: { + + get: function () + { + return this._v; + }, + + set: function (value) + { + this._v = value; + + HSVToRGB(this._h, this._s, value, this); + } + + } + +}); + +module.exports = Color; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports) { + +/** +* 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 +*/ + +// TODO: consider params for reusing vector objects + +var Vector = {}; + +module.exports = Vector; + +(function() { + + /** + * Creates a new vector. + * @method create + * @param {number} x + * @param {number} y + * @return {vector} A new vector + */ + Vector.create = function(x, y) { + return { x: x || 0, y: y || 0 }; + }; + + /** + * Returns a new vector with `x` and `y` copied from the given `vector`. + * @method clone + * @param {vector} vector + * @return {vector} A new cloned vector + */ + Vector.clone = function(vector) { + return { x: vector.x, y: vector.y }; + }; + + /** + * Returns the magnitude (length) of a vector. + * @method magnitude + * @param {vector} vector + * @return {number} The magnitude of the vector + */ + Vector.magnitude = function(vector) { + return Math.sqrt((vector.x * vector.x) + (vector.y * vector.y)); + }; + + /** + * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation). + * @method magnitudeSquared + * @param {vector} vector + * @return {number} The squared magnitude of the vector + */ + Vector.magnitudeSquared = function(vector) { + return (vector.x * vector.x) + (vector.y * vector.y); + }; + + /** + * Rotates the vector about (0, 0) by specified angle. + * @method rotate + * @param {vector} vector + * @param {number} angle + * @param {vector} [output] + * @return {vector} The vector rotated about (0, 0) + */ + Vector.rotate = function(vector, angle, output) { + var cos = Math.cos(angle), sin = Math.sin(angle); + if (!output) output = {}; + var x = vector.x * cos - vector.y * sin; + output.y = vector.x * sin + vector.y * cos; + output.x = x; + return output; + }; + + /** + * Rotates the vector about a specified point by specified angle. + * @method rotateAbout + * @param {vector} vector + * @param {number} angle + * @param {vector} point + * @param {vector} [output] + * @return {vector} A new vector rotated about the point + */ + Vector.rotateAbout = function(vector, angle, point, output) { + var cos = Math.cos(angle), sin = Math.sin(angle); + if (!output) output = {}; + var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin); + output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos); + output.x = x; + return output; + }; + + /** + * Normalises a vector (such that its magnitude is `1`). + * @method normalise + * @param {vector} vector + * @return {vector} A new vector normalised + */ + Vector.normalise = function(vector) { + var magnitude = Vector.magnitude(vector); + if (magnitude === 0) + return { x: 0, y: 0 }; + return { x: vector.x / magnitude, y: vector.y / magnitude }; + }; + + /** + * Returns the dot-product of two vectors. + * @method dot + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The dot product of the two vectors + */ + Vector.dot = function(vectorA, vectorB) { + return (vectorA.x * vectorB.x) + (vectorA.y * vectorB.y); + }; + + /** + * Returns the cross-product of two vectors. + * @method cross + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The cross product of the two vectors + */ + Vector.cross = function(vectorA, vectorB) { + return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x); + }; + + /** + * Returns the cross-product of three vectors. + * @method cross3 + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} vectorC + * @return {number} The cross product of the three vectors + */ + Vector.cross3 = function(vectorA, vectorB, vectorC) { + return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x); + }; + + /** + * Adds the two vectors. + * @method add + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} [output] + * @return {vector} A new vector of vectorA and vectorB added + */ + Vector.add = function(vectorA, vectorB, output) { + if (!output) output = {}; + output.x = vectorA.x + vectorB.x; + output.y = vectorA.y + vectorB.y; + return output; + }; + + /** + * Subtracts the two vectors. + * @method sub + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} [output] + * @return {vector} A new vector of vectorA and vectorB subtracted + */ + Vector.sub = function(vectorA, vectorB, output) { + if (!output) output = {}; + output.x = vectorA.x - vectorB.x; + output.y = vectorA.y - vectorB.y; + return output; + }; + + /** + * Multiplies a vector and a scalar. + * @method mult + * @param {vector} vector + * @param {number} scalar + * @return {vector} A new vector multiplied by scalar + */ + Vector.mult = function(vector, scalar) { + return { x: vector.x * scalar, y: vector.y * scalar }; + }; + + /** + * Divides a vector and a scalar. + * @method div + * @param {vector} vector + * @param {number} scalar + * @return {vector} A new vector divided by scalar + */ + Vector.div = function(vector, scalar) { + return { x: vector.x / scalar, y: vector.y / scalar }; + }; + + /** + * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction. + * @method perp + * @param {vector} vector + * @param {bool} [negate=false] + * @return {vector} The perpendicular vector + */ + Vector.perp = function(vector, negate) { + negate = negate === true ? -1 : 1; + return { x: negate * -vector.y, y: negate * vector.x }; + }; + + /** + * Negates both components of a vector such that it points in the opposite direction. + * @method neg + * @param {vector} vector + * @return {vector} The negated vector + */ + Vector.neg = function(vector) { + return { x: -vector.x, y: -vector.y }; + }; + + /** + * Returns the angle between the vector `vectorB - vectorA` and the x-axis in radians. + * @method angle + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The angle in radians + */ + Vector.angle = function(vectorA, vectorB) { + return Math.atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x); + }; + + /** + * Temporary vector pool (not thread-safe). + * @property _temp + * @type {vector[]} + * @private + */ + Vector._temp = [ + Vector.create(), Vector.create(), + Vector.create(), Vector.create(), + Vector.create(), Vector.create() + ]; + +})(); + +/***/ }), +/* 38 */ +/***/ (function(module, exports) { + +/** +* The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). +* +* @class Bounds +*/ + +var Bounds = {}; + +module.exports = Bounds; + +(function() { + + /** + * Creates a new axis-aligned bounding box (AABB) for the given vertices. + * @method create + * @param {vertices} vertices + * @return {bounds} A new bounds object + */ + Bounds.create = function(vertices) { + var bounds = { + min: { x: 0, y: 0 }, + max: { x: 0, y: 0 } + }; + + if (vertices) + Bounds.update(bounds, vertices); + + return bounds; + }; + + /** + * Updates bounds using the given vertices and extends the bounds given a velocity. + * @method update + * @param {bounds} bounds + * @param {vertices} vertices + * @param {vector} velocity + */ + Bounds.update = function(bounds, vertices, velocity) { + bounds.min.x = Infinity; + bounds.max.x = -Infinity; + bounds.min.y = Infinity; + bounds.max.y = -Infinity; + + for (var i = 0; i < vertices.length; i++) { + var vertex = vertices[i]; + if (vertex.x > bounds.max.x) bounds.max.x = vertex.x; + if (vertex.x < bounds.min.x) bounds.min.x = vertex.x; + if (vertex.y > bounds.max.y) bounds.max.y = vertex.y; + if (vertex.y < bounds.min.y) bounds.min.y = vertex.y; + } + + if (velocity) { + if (velocity.x > 0) { + bounds.max.x += velocity.x; + } else { + bounds.min.x += velocity.x; + } + + if (velocity.y > 0) { + bounds.max.y += velocity.y; + } else { + bounds.min.y += velocity.y; + } + } + }; + + /** + * Returns true if the bounds contains the given point. + * @method contains + * @param {bounds} bounds + * @param {vector} point + * @return {boolean} True if the bounds contain the point, otherwise false + */ + Bounds.contains = function(bounds, point) { + return point.x >= bounds.min.x && point.x <= bounds.max.x + && point.y >= bounds.min.y && point.y <= bounds.max.y; + }; + + /** + * Returns true if the two bounds intersect. + * @method overlaps + * @param {bounds} boundsA + * @param {bounds} boundsB + * @return {boolean} True if the bounds overlap, otherwise false + */ + Bounds.overlaps = function(boundsA, boundsB) { + return (boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x + && boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y); + }; + + /** + * Translates the bounds by the given vector. + * @method translate + * @param {bounds} bounds + * @param {vector} vector + */ + Bounds.translate = function(bounds, vector) { + bounds.min.x += vector.x; + bounds.max.x += vector.x; + bounds.min.y += vector.y; + bounds.max.y += vector.y; + }; + + /** + * Shifts the bounds to the given position. + * @method shift + * @param {bounds} bounds + * @param {vector} position + */ + Bounds.shift = function(bounds, position) { + var deltaX = bounds.max.x - bounds.min.x, + deltaY = bounds.max.y - bounds.min.y; + + bounds.min.x = position.x; + bounds.max.x = position.x + deltaX; + bounds.min.y = position.y; + bounds.max.y = position.y + deltaY; + }; + +})(); + + +/***/ }), +/* 39 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, + * and then adds the given value to it. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `PropertyValueInc(group.getChildren(), key, value, step)` + * + * @function Phaser.Actions.PropertyValueInc + * @since 3.3.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 {string} key - The property to be updated. + * @param {number} value - The amount to be added to the property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var PropertyValueInc = function (items, key, value, step, index, direction) +{ + if (step === undefined) { step = 0; } + if (index === undefined) { index = 0; } + if (direction === undefined) { direction = 1; } + + var i; + var t = 0; + var end = items.length; + + if (direction === 1) + { + // Start to End + for (i = index; i < end; i++) + { + items[i][key] += value + (t * step); + t++; + } + } + else + { + // End to Start + for (i = index; i >= 0; i--) + { + items[i][key] += value + (t * step); + t++; + } + } + + return items; +}; + +module.exports = PropertyValueInc; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(13); + +/** + * Convert the given angle from degrees, to the equivalent angle in radians. + * + * @function Phaser.Math.DegToRad + * @since 3.0.0 + * + * @param {integer} degrees - The angle (in degrees) to convert to radians. + * + * @return {number} The given angle converted to radians. + */ +var DegToRad = function (degrees) +{ + return degrees * CONST.DEG_TO_RAD; +}; + +module.exports = DegToRad; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var FillStyleCanvas = function (ctx, src, altColor, altAlpha) +{ + var fillColor = (altColor) ? altColor : src.fillColor; + var fillAlpha = (altAlpha) ? altAlpha : src.fillAlpha; + + var red = ((fillColor & 0xFF0000) >>> 16); + var green = ((fillColor & 0xFF00) >>> 8); + var blue = (fillColor & 0xFF); + + ctx.fillStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + fillAlpha + ')'; +}; + +module.exports = FillStyleCanvas; + + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +// TODO: true circle bodies + +var Bodies = {}; + +module.exports = Bodies; + +var Vertices = __webpack_require__(31); +var Common = __webpack_require__(19); +var Body = __webpack_require__(25); +var Bounds = __webpack_require__(38); +var Vector = __webpack_require__(37); +var decomp = __webpack_require__(505); + +(function() { + + /** + * Creates a new rigid body model with a rectangle hull. + * The options parameter is an object that specifies any 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 rectangle + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {object} [options] + * @return {body} A new rectangle body + */ + Bodies.rectangle = function(x, y, width, height, options) { + options = options || {}; + + var rectangle = { + label: 'Rectangle Body', + position: { x: x, y: y }, + vertices: Vertices.fromPath('L 0 0 L ' + width + ' 0 L ' + width + ' ' + height + ' L 0 ' + height) + }; + + if (options.chamfer) { + var chamfer = options.chamfer; + rectangle.vertices = Vertices.chamfer(rectangle.vertices, chamfer.radius, + chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); + delete options.chamfer; + } + + return Body.create(Common.extend({}, rectangle, options)); + }; + + /** + * Creates a new rigid body model with a trapezoid hull. + * The options parameter is an object that specifies any 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 trapezoid + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {number} slope + * @param {object} [options] + * @return {body} A new trapezoid body + */ + Bodies.trapezoid = function(x, y, width, height, slope, options) { + options = options || {}; + + slope *= 0.5; + var roof = (1 - (slope * 2)) * width; + + var x1 = width * slope, + x2 = x1 + roof, + x3 = x2 + x1, + verticesPath; + + if (slope < 0.5) { + verticesPath = 'L 0 0 L ' + x1 + ' ' + (-height) + ' L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0'; + } else { + verticesPath = 'L 0 0 L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0'; + } + + var trapezoid = { + label: 'Trapezoid Body', + position: { x: x, y: y }, + vertices: Vertices.fromPath(verticesPath) + }; + + if (options.chamfer) { + var chamfer = options.chamfer; + trapezoid.vertices = Vertices.chamfer(trapezoid.vertices, chamfer.radius, + chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); + delete options.chamfer; + } + + return Body.create(Common.extend({}, trapezoid, options)); + }; + + /** + * Creates a new rigid body model with a circle hull. + * The options parameter is an object that specifies any 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 circle + * @param {number} x + * @param {number} y + * @param {number} radius + * @param {object} [options] + * @param {number} [maxSides] + * @return {body} A new circle body + */ + Bodies.circle = function(x, y, radius, options, maxSides) { + options = options || {}; + + var circle = { + label: 'Circle Body', + circleRadius: radius + }; + + // approximate circles with polygons until true circles implemented in SAT + maxSides = maxSides || 25; + var sides = Math.ceil(Math.max(10, Math.min(maxSides, radius))); + + // optimisation: always use even number of sides (half the number of unique axes) + if (sides % 2 === 1) + sides += 1; + + return Bodies.polygon(x, y, sides, radius, Common.extend({}, circle, options)); + }; + + /** + * Creates a new rigid body model with a regular polygon hull with the given number of sides. + * The options parameter is an object that specifies any 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 polygon + * @param {number} x + * @param {number} y + * @param {number} sides + * @param {number} radius + * @param {object} [options] + * @return {body} A new regular polygon body + */ + Bodies.polygon = function(x, y, sides, radius, options) { + options = options || {}; + + if (sides < 3) + return Bodies.circle(x, y, radius, options); + + var theta = 2 * Math.PI / sides, + path = '', + offset = theta * 0.5; + + for (var i = 0; i < sides; i += 1) { + var angle = offset + (i * theta), + xx = Math.cos(angle) * radius, + yy = Math.sin(angle) * radius; + + path += 'L ' + xx.toFixed(3) + ' ' + yy.toFixed(3) + ' '; + } + + var polygon = { + label: 'Polygon Body', + position: { x: x, y: y }, + vertices: Vertices.fromPath(path) + }; + + if (options.chamfer) { + var chamfer = options.chamfer; + polygon.vertices = Vertices.chamfer(polygon.vertices, chamfer.radius, + chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); + delete options.chamfer; + } + + return Body.create(Common.extend({}, polygon, options)); + }; + + /** + * Creates a body using the supplied vertices (or an array containing multiple sets of vertices). + * If the vertices are convex, they will pass through as supplied. + * Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available. + * Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail). + * By default the decomposition will discard collinear edges (to improve performance). + * It can also optionally discard any parts that have an area less than `minimumArea`. + * If the vertices can not be decomposed, the result will fall back to using the convex hull. + * The options parameter is an object that 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 [[vector]] vertexSets + * @param {object} [options] + * @param {bool} [flagInternal=false] + * @param {number} [removeCollinear=0.01] + * @param {number} [minimumArea=10] + * @return {body} + */ + Bodies.fromVertices = function(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) { + var body, + parts, + isConvex, + vertices, + i, + j, + k, + v, + z; + + options = options || {}; + parts = []; + + flagInternal = typeof flagInternal !== 'undefined' ? flagInternal : false; + removeCollinear = typeof removeCollinear !== 'undefined' ? removeCollinear : 0.01; + minimumArea = typeof minimumArea !== 'undefined' ? minimumArea : 10; + + if (!decomp) { + Common.warn('Bodies.fromVertices: poly-decomp.js required. Could not decompose vertices. Fallback to convex hull.'); + } + + // ensure vertexSets is an array of arrays + if (!Common.isArray(vertexSets[0])) { + vertexSets = [vertexSets]; + } + + for (v = 0; v < vertexSets.length; v += 1) { + vertices = vertexSets[v]; + isConvex = Vertices.isConvex(vertices); + + if (isConvex || !decomp) { + if (isConvex) { + vertices = Vertices.clockwiseSort(vertices); + } else { + // fallback to convex hull when decomposition is not possible + vertices = Vertices.hull(vertices); + } + + parts.push({ + position: { x: x, y: y }, + vertices: vertices + }); + } else { + // initialise a decomposition + var concave = vertices.map(function(vertex) { + return [vertex.x, vertex.y]; + }); + + // vertices are concave and simple, we can decompose into parts + decomp.makeCCW(concave); + if (removeCollinear !== false) + decomp.removeCollinearPoints(concave, removeCollinear); + + // use the quick decomposition algorithm (Bayazit) + var decomposed = decomp.quickDecomp(concave); + + // for each decomposed chunk + for (i = 0; i < decomposed.length; i++) { + var chunk = decomposed[i]; + + // convert vertices into the correct structure + var chunkVertices = chunk.map(function(vertices) { + return { + x: vertices[0], + y: vertices[1] + }; + }); + + // skip small chunks + if (minimumArea > 0 && Vertices.area(chunkVertices) < minimumArea) + continue; + + // create a compound part + parts.push({ + position: Vertices.centre(chunkVertices), + vertices: chunkVertices + }); + } + } + } + + // create body parts + for (i = 0; i < parts.length; i++) { + parts[i] = Body.create(Common.extend(parts[i], options)); + } + + if (flagInternal) + { + Bodies.flagCoincidentParts(parts, 5); + } + + if (parts.length > 1) { + // create the parent body to be returned, that contains generated compound parts + body = Body.create(Common.extend({ parts: parts.slice(0) }, options)); + Body.setPosition(body, { x: x, y: y }); + + return body; + } else { + return parts[0]; + } + }; + + /** + * 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. + */ + Bodies.flagCoincidentParts = function (parts, maxDistance) + { + if (maxDistance === undefined) { maxDistance = 5; } + + for (var i = 0; i < parts.length; i++) + { + var partA = parts[i]; + + for (var j = i + 1; j < parts.length; j++) + { + var partB = parts[j]; + + if (Bounds.overlaps(partA.bounds, partB.bounds)) + { + var pav = partA.vertices; + var pbv = partB.vertices; + + // iterate vertices of both parts + for (var k = 0; k < partA.vertices.length; k++) + { + for (var z = 0; z < partB.vertices.length; z++) + { + // find distances between the vertices + var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])); + var db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length])); + + // if both vertices are very close, consider the edge concident (internal) + if (da < maxDistance && db < maxDistance) + { + pav[k].isInternal = true; + pbv[z].isInternal = true; + } + } + } + } + } + } + + return parts; + }; + +})(); + + +/***/ }), +/* 43 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Blend Modes. + * + * @namespace Phaser.BlendModes + * @since 3.0.0 + */ + +module.exports = { + + /** + * Skips the Blend Mode check in the renderer. + * + * @name Phaser.BlendModes.SKIP_CHECK + * @type {integer} + * @const + * @since 3.0.0 + */ + SKIP_CHECK: -1, + + /** + * Normal blend mode. For Canvas and WebGL. + * This is the default setting and draws new shapes on top of the existing canvas content. + * + * @name Phaser.BlendModes.NORMAL + * @type {integer} + * @const + * @since 3.0.0 + */ + NORMAL: 0, + + /** + * Add blend mode. For Canvas and WebGL. + * Where both shapes overlap the color is determined by adding color values. + * + * @name Phaser.BlendModes.ADD + * @type {integer} + * @const + * @since 3.0.0 + */ + ADD: 1, + + /** + * Multiply blend mode. For Canvas and WebGL. + * The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result. + * + * @name Phaser.BlendModes.MULTIPLY + * @type {integer} + * @const + * @since 3.0.0 + */ + MULTIPLY: 2, + + /** + * Screen blend mode. For Canvas and WebGL. + * The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply) + * + * @name Phaser.BlendModes.SCREEN + * @type {integer} + * @const + * @since 3.0.0 + */ + SCREEN: 3, + + /** + * Overlay blend mode. For Canvas only. + * A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter. + * + * @name Phaser.BlendModes.OVERLAY + * @type {integer} + * @const + * @since 3.0.0 + */ + OVERLAY: 4, + + /** + * Darken blend mode. For Canvas only. + * Retains the darkest pixels of both layers. + * + * @name Phaser.BlendModes.DARKEN + * @type {integer} + * @const + * @since 3.0.0 + */ + DARKEN: 5, + + /** + * Lighten blend mode. For Canvas only. + * Retains the lightest pixels of both layers. + * + * @name Phaser.BlendModes.LIGHTEN + * @type {integer} + * @const + * @since 3.0.0 + */ + LIGHTEN: 6, + + /** + * Color Dodge blend mode. For Canvas only. + * Divides the bottom layer by the inverted top layer. + * + * @name Phaser.BlendModes.COLOR_DODGE + * @type {integer} + * @const + * @since 3.0.0 + */ + COLOR_DODGE: 7, + + /** + * Color Burn blend mode. For Canvas only. + * Divides the inverted bottom layer by the top layer, and then inverts the result. + * + * @name Phaser.BlendModes.COLOR_BURN + * @type {integer} + * @const + * @since 3.0.0 + */ + COLOR_BURN: 8, + + /** + * Hard Light blend mode. For Canvas only. + * A combination of multiply and screen like overlay, but with top and bottom layer swapped. + * + * @name Phaser.BlendModes.HARD_LIGHT + * @type {integer} + * @const + * @since 3.0.0 + */ + HARD_LIGHT: 9, + + /** + * Soft Light blend mode. For Canvas only. + * A softer version of hard-light. Pure black or white does not result in pure black or white. + * + * @name Phaser.BlendModes.SOFT_LIGHT + * @type {integer} + * @const + * @since 3.0.0 + */ + SOFT_LIGHT: 10, + + /** + * Difference blend mode. For Canvas only. + * Subtracts the bottom layer from the top layer or the other way round to always get a positive value. + * + * @name Phaser.BlendModes.DIFFERENCE + * @type {integer} + * @const + * @since 3.0.0 + */ + DIFFERENCE: 11, + + /** + * Exclusion blend mode. For Canvas only. + * Like difference, but with lower contrast. + * + * @name Phaser.BlendModes.EXCLUSION + * @type {integer} + * @const + * @since 3.0.0 + */ + EXCLUSION: 12, + + /** + * Hue blend mode. For Canvas only. + * Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer. + * + * @name Phaser.BlendModes.HUE + * @type {integer} + * @const + * @since 3.0.0 + */ + HUE: 13, + + /** + * Saturation blend mode. For Canvas only. + * Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer. + * + * @name Phaser.BlendModes.SATURATION + * @type {integer} + * @const + * @since 3.0.0 + */ + SATURATION: 14, + + /** + * Color blend mode. For Canvas only. + * Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer. + * + * @name Phaser.BlendModes.COLOR + * @type {integer} + * @const + * @since 3.0.0 + */ + COLOR: 15, + + /** + * Luminosity blend mode. For Canvas only. + * Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer. + * + * @name Phaser.BlendModes.LUMINOSITY + * @type {integer} + * @const + * @since 3.0.0 + */ + LUMINOSITY: 16, + + /** + * Alpha erase blend mode. For Canvas and WebGL. + * + * @name Phaser.BlendModes.ERASE + * @type {integer} + * @const + * @since 3.0.0 + */ + ERASE: 17, + + /** + * Source-in blend mode. For Canvas only. + * The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent. + * + * @name Phaser.BlendModes.SOURCE_IN + * @type {integer} + * @const + * @since 3.0.0 + */ + SOURCE_IN: 18, + + /** + * Source-out blend mode. For Canvas only. + * The new shape is drawn where it doesn't overlap the existing canvas content. + * + * @name Phaser.BlendModes.SOURCE_OUT + * @type {integer} + * @const + * @since 3.0.0 + */ + SOURCE_OUT: 19, + + /** + * Source-out blend mode. For Canvas only. + * The new shape is only drawn where it overlaps the existing canvas content. + * + * @name Phaser.BlendModes.SOURCE_ATOP + * @type {integer} + * @const + * @since 3.0.0 + */ + SOURCE_ATOP: 20, + + /** + * Destination-over blend mode. For Canvas only. + * New shapes are drawn behind the existing canvas content. + * + * @name Phaser.BlendModes.DESTINATION_OVER + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_OVER: 21, + + /** + * Destination-in blend mode. For Canvas only. + * The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent. + * + * @name Phaser.BlendModes.DESTINATION_IN + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_IN: 22, + + /** + * Destination-out blend mode. For Canvas only. + * The existing content is kept where it doesn't overlap the new shape. + * + * @name Phaser.BlendModes.DESTINATION_OUT + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_OUT: 23, + + /** + * Destination-out blend mode. For Canvas only. + * The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content. + * + * @name Phaser.BlendModes.DESTINATION_ATOP + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_ATOP: 24, + + /** + * Lighten blend mode. For Canvas only. + * Where both shapes overlap the color is determined by adding color values. + * + * @name Phaser.BlendModes.LIGHTER + * @type {integer} + * @const + * @since 3.0.0 + */ + LIGHTER: 25, + + /** + * Copy blend mode. For Canvas only. + * Only the new shape is shown. + * + * @name Phaser.BlendModes.COPY + * @type {integer} + * @const + * @since 3.0.0 + */ + COPY: 26, + + /** + * Xor blend mode. For Canvas only. + * Shapes are made transparent where both overlap and drawn normal everywhere else. + * + * @name Phaser.BlendModes.XOR + * @type {integer} + * @const + * @since 3.0.0 + */ + XOR: 27 + +}; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the bottom coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetBottom + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The bottom coordinate of the bounds of the Game Object. + */ +var GetBottom = function (gameObject) +{ + return (gameObject.y + gameObject.height) - (gameObject.height * gameObject.originY); +}; + +module.exports = GetBottom; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the top of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetTop + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetTop = function (gameObject, value) +{ + gameObject.y = value + (gameObject.height * gameObject.originY); + + return gameObject; +}; + +module.exports = SetTop; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the left coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetLeft + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The left coordinate of the bounds of the Game Object. + */ +var GetLeft = function (gameObject) +{ + return gameObject.x - (gameObject.width * gameObject.originX); +}; + +module.exports = GetLeft; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the left of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetLeft = function (gameObject, value) +{ + gameObject.x = value + (gameObject.width * gameObject.originX); + + return gameObject; +}; + +module.exports = SetLeft; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the right coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetRight + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The right coordinate of the bounds of the Game Object. + */ +var GetRight = function (gameObject) +{ + return (gameObject.x + gameObject.width) - (gameObject.width * gameObject.originX); +}; + +module.exports = GetRight; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the left of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetRight = function (gameObject, value) +{ + gameObject.x = (value - gameObject.width) + (gameObject.width * gameObject.originX); + + return gameObject; +}; + +module.exports = SetRight; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the bottom of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetBottom + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetBottom = function (gameObject, value) +{ + gameObject.y = (value - gameObject.height) + (gameObject.height * gameObject.originY); + + return gameObject; +}; + +module.exports = SetBottom; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the top coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetTop + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The top coordinate of the bounds of the Game Object. + */ +var GetTop = function (gameObject) +{ + return gameObject.y - (gameObject.height * gameObject.originY); +}; + +module.exports = GetTop; + + +/***/ }), +/* 52 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GEOM_CONST = { + + /** + * A Circle Geometry object type. + * + * @name Phaser.Geom.CIRCLE + * @type {integer} + * @since 3.19.0 + */ + CIRCLE: 0, + + /** + * An Ellipse Geometry object type. + * + * @name Phaser.Geom.ELLIPSE + * @type {integer} + * @since 3.19.0 + */ + ELLIPSE: 1, + + /** + * A Line Geometry object type. + * + * @name Phaser.Geom.LINE + * @type {integer} + * @since 3.19.0 + */ + LINE: 2, + + /** + * A Point Geometry object type. + * + * @name Phaser.Geom.POINT + * @type {integer} + * @since 3.19.0 + */ + POINT: 3, + + /** + * A Polygon Geometry object type. + * + * @name Phaser.Geom.POLYGON + * @type {integer} + * @since 3.19.0 + */ + POLYGON: 4, + + /** + * A Rectangle Geometry object type. + * + * @name Phaser.Geom.RECTANGLE + * @type {integer} + * @since 3.19.0 + */ + RECTANGLE: 5, + + /** + * A Triangle Geometry object type. + * + * @name Phaser.Geom.TRIANGLE + * @type {integer} + * @since 3.19.0 + */ + TRIANGLE: 6 + +}; + +module.exports = GEOM_CONST; + + +/***/ }), +/* 53 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if a given point is inside a Rectangle's bounds. + * + * @function Phaser.Geom.Rectangle.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to check. + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is within the Rectangle's bounds, otherwise `false`. + */ +var Contains = function (rect, x, y) +{ + if (rect.width <= 0 || rect.height <= 0) + { + return false; + } + + return (rect.x <= x && rect.x + rect.width >= x && rect.y <= y && rect.y + rect.height >= y); +}; + +module.exports = Contains; + + +/***/ }), +/* 54 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two sets of coordinates (points). + * + * @function Phaser.Math.Distance.Between + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point. + */ +var DistanceBetween = function (x1, y1, x2, y2) +{ + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); +}; + +module.exports = DistanceBetween; + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Scene2D.Events + */ + +module.exports = { + + DESTROY: __webpack_require__(673), + FADE_IN_COMPLETE: __webpack_require__(674), + FADE_IN_START: __webpack_require__(675), + FADE_OUT_COMPLETE: __webpack_require__(676), + FADE_OUT_START: __webpack_require__(677), + FLASH_COMPLETE: __webpack_require__(678), + FLASH_START: __webpack_require__(679), + PAN_COMPLETE: __webpack_require__(680), + PAN_START: __webpack_require__(681), + POST_RENDER: __webpack_require__(682), + PRE_RENDER: __webpack_require__(683), + SHAKE_COMPLETE: __webpack_require__(684), + SHAKE_START: __webpack_require__(685), + ZOOM_COMPLETE: __webpack_require__(686), + ZOOM_START: __webpack_require__(687) + +}; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Events + */ + +module.exports = { + + BOOT: __webpack_require__(846), + DESTROY: __webpack_require__(847), + DRAG_END: __webpack_require__(848), + DRAG_ENTER: __webpack_require__(849), + DRAG: __webpack_require__(850), + DRAG_LEAVE: __webpack_require__(851), + DRAG_OVER: __webpack_require__(852), + DRAG_START: __webpack_require__(853), + DROP: __webpack_require__(854), + GAME_OUT: __webpack_require__(855), + GAME_OVER: __webpack_require__(856), + GAMEOBJECT_DOWN: __webpack_require__(857), + GAMEOBJECT_DRAG_END: __webpack_require__(858), + GAMEOBJECT_DRAG_ENTER: __webpack_require__(859), + GAMEOBJECT_DRAG: __webpack_require__(860), + GAMEOBJECT_DRAG_LEAVE: __webpack_require__(861), + GAMEOBJECT_DRAG_OVER: __webpack_require__(862), + GAMEOBJECT_DRAG_START: __webpack_require__(863), + GAMEOBJECT_DROP: __webpack_require__(864), + GAMEOBJECT_MOVE: __webpack_require__(865), + GAMEOBJECT_OUT: __webpack_require__(866), + GAMEOBJECT_OVER: __webpack_require__(867), + GAMEOBJECT_POINTER_DOWN: __webpack_require__(868), + GAMEOBJECT_POINTER_MOVE: __webpack_require__(869), + GAMEOBJECT_POINTER_OUT: __webpack_require__(870), + GAMEOBJECT_POINTER_OVER: __webpack_require__(871), + GAMEOBJECT_POINTER_UP: __webpack_require__(872), + GAMEOBJECT_POINTER_WHEEL: __webpack_require__(873), + GAMEOBJECT_UP: __webpack_require__(874), + GAMEOBJECT_WHEEL: __webpack_require__(875), + MANAGER_BOOT: __webpack_require__(876), + MANAGER_PROCESS: __webpack_require__(877), + MANAGER_UPDATE: __webpack_require__(878), + POINTER_DOWN: __webpack_require__(879), + POINTER_DOWN_OUTSIDE: __webpack_require__(880), + POINTER_MOVE: __webpack_require__(881), + POINTER_OUT: __webpack_require__(882), + POINTER_OVER: __webpack_require__(883), + POINTER_UP: __webpack_require__(884), + POINTER_UP_OUTSIDE: __webpack_require__(885), + POINTER_WHEEL: __webpack_require__(886), + POINTERLOCK_CHANGE: __webpack_require__(887), + PRE_UPDATE: __webpack_require__(888), + SHUTDOWN: __webpack_require__(889), + START: __webpack_require__(890), + UPDATE: __webpack_require__(891) + +}; + + +/***/ }), +/* 57 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var LineStyleCanvas = function (ctx, src, altColor, altAlpha) +{ + var strokeColor = (altColor) ? altColor : src.strokeColor; + var strokeAlpha = (altAlpha) ? altAlpha : src.strokeAlpha; + + var red = ((strokeColor & 0xFF0000) >>> 16); + var green = ((strokeColor & 0xFF00) >>> 8); + var blue = (strokeColor & 0xFF); + + ctx.strokeStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + strokeAlpha + ')'; + ctx.lineWidth = src.lineWidth; +}; + +module.exports = LineStyleCanvas; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Arcade Physics consts. + * + * @ignore + */ + +var CONST = { + + /** + * Dynamic Body. + * + * @name Phaser.Physics.Arcade.DYNAMIC_BODY + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#physicsType + * @see Phaser.Physics.Arcade.Group#physicsType + */ + DYNAMIC_BODY: 0, + + /** + * Static Body. + * + * @name Phaser.Physics.Arcade.STATIC_BODY + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#physicsType + * @see Phaser.Physics.Arcade.StaticBody#physicsType + */ + STATIC_BODY: 1, + + /** + * Arcade Physics Group containing Dynamic Bodies. + * + * @name Phaser.Physics.Arcade.GROUP + * @readonly + * @type {number} + * @since 3.0.0 + */ + GROUP: 2, + + /** + * A Tilemap Layer. + * + * @name Phaser.Physics.Arcade.TILEMAPLAYER + * @readonly + * @type {number} + * @since 3.0.0 + */ + TILEMAPLAYER: 3, + + /** + * Facing no direction (initial value). + * + * @name Phaser.Physics.Arcade.FACING_NONE + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_NONE: 10, + + /** + * Facing up. + * + * @name Phaser.Physics.Arcade.FACING_UP + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_UP: 11, + + /** + * Facing down. + * + * @name Phaser.Physics.Arcade.FACING_DOWN + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_DOWN: 12, + + /** + * Facing left. + * + * @name Phaser.Physics.Arcade.FACING_LEFT + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_LEFT: 13, + + /** + * Facing right. + * + * @name Phaser.Physics.Arcade.FACING_RIGHT + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_RIGHT: 14 + +}; + +module.exports = CONST; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTileAt = __webpack_require__(151); +var GetTilesWithin = __webpack_require__(26); + +/** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * @function Phaser.Tilemaps.Components.CalculateFacesWithin + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var CalculateFacesWithin = function (tileX, tileY, width, height, layer) +{ + var above = null; + var below = null; + var left = null; + var right = null; + + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + if (tile) + { + if (tile.collides) + { + above = GetTileAt(tile.x, tile.y - 1, true, layer); + below = GetTileAt(tile.x, tile.y + 1, true, layer); + left = GetTileAt(tile.x - 1, tile.y, true, layer); + right = GetTileAt(tile.x + 1, tile.y, true, layer); + + tile.faceTop = (above && above.collides) ? false : true; + tile.faceBottom = (below && below.collides) ? false : true; + tile.faceLeft = (left && left.collides) ? false : true; + tile.faceRight = (right && right.collides) ? false : true; + } + else + { + tile.resetFaces(); + } + } + } +}; + +module.exports = CalculateFacesWithin; + + +/***/ }), +/* 60 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check to see if the Circle contains the given x / y coordinates. + * + * @function Phaser.Geom.Circle.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to check. + * @param {number} x - The x coordinate to check within the circle. + * @param {number} y - The y coordinate to check within the circle. + * + * @return {boolean} True if the coordinates are within the circle, otherwise false. + */ +var Contains = function (circle, x, y) +{ + // Check if x/y are within the bounds first + if (circle.radius > 0 && x >= circle.left && x <= circle.right && y >= circle.top && y <= circle.bottom) + { + var dx = (circle.x - x) * (circle.x - x); + var dy = (circle.y - y) * (circle.y - y); + + return (dx + dy) <= (circle.radius * circle.radius); + } + else + { + return false; + } +}; + +module.exports = Contains; + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetPoint = __webpack_require__(294); +var GetPoints = __webpack_require__(162); +var GEOM_CONST = __webpack_require__(52); +var Random = __webpack_require__(163); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * Defines a Line segment, a part of a line between two endpoints. + * + * @class Line + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x1=0] - The x coordinate of the lines starting point. + * @param {number} [y1=0] - The y coordinate of the lines starting point. + * @param {number} [x2=0] - The x coordinate of the lines ending point. + * @param {number} [y2=0] - The y coordinate of the lines ending point. + */ +var Line = new Class({ + + initialize: + + function Line (x1, y1, x2, y2) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.LINE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Line#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.LINE; + + /** + * The x coordinate of the lines starting point. + * + * @name Phaser.Geom.Line#x1 + * @type {number} + * @since 3.0.0 + */ + this.x1 = x1; + + /** + * The y coordinate of the lines starting point. + * + * @name Phaser.Geom.Line#y1 + * @type {number} + * @since 3.0.0 + */ + this.y1 = y1; + + /** + * The x coordinate of the lines ending point. + * + * @name Phaser.Geom.Line#x2 + * @type {number} + * @since 3.0.0 + */ + this.x2 = x2; + + /** + * The y coordinate of the lines ending point. + * + * @name Phaser.Geom.Line#y2 + * @type {number} + * @since 3.0.0 + */ + this.y2 = y2; + }, + + /** + * Get a point on a line that's a given percentage along its length. + * + * @method Phaser.Geom.Line#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [output,$return] + * + * @param {number} position - A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. + * @param {(Phaser.Geom.Point|object)} [output] - An optional point, or point-like object, to store the coordinates of the point on the line. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point on the line. + */ + getPoint: function (position, output) + { + return GetPoint(this, position, output); + }, + + /** + * Get a number of points along a line's length. + * + * Provide a `quantity` to get an exact number of points along the line. + * + * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when + * providing a `stepRate`. + * + * @method Phaser.Geom.Line#getPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [output,$return] + * + * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. + * @param {integer} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. + * @param {(array|Phaser.Geom.Point[])} [output] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. + * + * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Get a random Point on the Line. + * + * @method Phaser.Geom.Line#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {(Phaser.Geom.Point|object)} [point] - An instance of a Point to be modified. + * + * @return {Phaser.Geom.Point} A random Point on the Line. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Set new coordinates for the line endpoints. + * + * @method Phaser.Geom.Line#setTo + * @since 3.0.0 + * + * @param {number} [x1=0] - The x coordinate of the lines starting point. + * @param {number} [y1=0] - The y coordinate of the lines starting point. + * @param {number} [x2=0] - The x coordinate of the lines ending point. + * @param {number} [y2=0] - The y coordinate of the lines ending point. + * + * @return {Phaser.Geom.Line} This Line object. + */ + setTo: function (x1, y1, x2, y2) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + + this.x1 = x1; + this.y1 = y1; + + this.x2 = x2; + this.y2 = y2; + + return this; + }, + + /** + * Returns a Vector2 object that corresponds to the start of this Line. + * + * @method Phaser.Geom.Line#getPointA + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [vec2,$return] + * + * @param {Phaser.Math.Vector2} [vec2] - A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. + * + * @return {Phaser.Math.Vector2} A Vector2 object that corresponds to the start of this Line. + */ + getPointA: function (vec2) + { + if (vec2 === undefined) { vec2 = new Vector2(); } + + vec2.set(this.x1, this.y1); + + return vec2; + }, + + /** + * Returns a Vector2 object that corresponds to the end of this Line. + * + * @method Phaser.Geom.Line#getPointB + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [vec2,$return] + * + * @param {Phaser.Math.Vector2} [vec2] - A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. + * + * @return {Phaser.Math.Vector2} A Vector2 object that corresponds to the end of this Line. + */ + getPointB: function (vec2) + { + if (vec2 === undefined) { vec2 = new Vector2(); } + + vec2.set(this.x2, this.y2); + + return vec2; + }, + + /** + * The left position of the Line. + * + * @name Phaser.Geom.Line#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return Math.min(this.x1, this.x2); + }, + + set: function (value) + { + if (this.x1 <= this.x2) + { + this.x1 = value; + } + else + { + this.x2 = value; + } + } + + }, + + /** + * The right position of the Line. + * + * @name Phaser.Geom.Line#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return Math.max(this.x1, this.x2); + }, + + set: function (value) + { + if (this.x1 > this.x2) + { + this.x1 = value; + } + else + { + this.x2 = value; + } + } + + }, + + /** + * The top position of the Line. + * + * @name Phaser.Geom.Line#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return Math.min(this.y1, this.y2); + }, + + set: function (value) + { + if (this.y1 <= this.y2) + { + this.y1 = value; + } + else + { + this.y2 = value; + } + } + + }, + + /** + * The bottom position of the Line. + * + * @name Phaser.Geom.Line#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return Math.max(this.y1, this.y2); + }, + + set: function (value) + { + if (this.y1 > this.y2) + { + this.y1 = value; + } + else + { + this.y2 = value; + } + } + + } + +}); + +module.exports = Line; + + +/***/ }), +/* 62 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the length of the given line. + * + * @function Phaser.Geom.Line.Length + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the length of. + * + * @return {number} The length of the line. + */ +var Length = function (line) +{ + return Math.sqrt((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1)); +}; + +module.exports = Length; + + +/***/ }), +/* 63 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Wrap the given `value` between `min` and `max. + * + * @function Phaser.Math.Wrap + * @since 3.0.0 + * + * @param {number} value - The value to wrap. + * @param {number} min - The minimum value. + * @param {number} max - The maximum value. + * + * @return {number} The wrapped value. + */ +var Wrap = function (value, min, max) +{ + var range = max - min; + + return (min + ((((value - min) % range) + range) % range)); +}; + +module.exports = Wrap; + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Sound.Events + */ + +module.exports = { + + COMPLETE: __webpack_require__(914), + DECODED: __webpack_require__(915), + DECODED_ALL: __webpack_require__(916), + DESTROY: __webpack_require__(917), + DETUNE: __webpack_require__(918), + GLOBAL_DETUNE: __webpack_require__(919), + GLOBAL_MUTE: __webpack_require__(920), + GLOBAL_RATE: __webpack_require__(921), + GLOBAL_VOLUME: __webpack_require__(922), + LOOP: __webpack_require__(923), + LOOPED: __webpack_require__(924), + MUTE: __webpack_require__(925), + PAUSE_ALL: __webpack_require__(926), + PAUSE: __webpack_require__(927), + PLAY: __webpack_require__(928), + RATE: __webpack_require__(929), + RESUME_ALL: __webpack_require__(930), + RESUME: __webpack_require__(931), + SEEK: __webpack_require__(932), + STOP_ALL: __webpack_require__(933), + STOP: __webpack_require__(934), + UNLOCKED: __webpack_require__(935), + VOLUME: __webpack_require__(936) + +}; + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var SpriteRender = __webpack_require__(997); + +/** + * @classdesc + * A Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class Sprite + * @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.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Sprite = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + SpriteRender + ], + + initialize: + + function Sprite (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Sprite'); + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Sprite#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); + + /** + * The Animation Controller of this Sprite. + * + * @name Phaser.GameObjects.Sprite#anims + * @type {Phaser.GameObjects.Components.Animation} + * @since 3.0.0 + */ + this.anims = new Components.Animation(this); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + }, + + /** + * Update this Sprite's animations. + * + * @method Phaser.GameObjects.Sprite#preUpdate + * @protected + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + preUpdate: function (time, delta) + { + this.anims.update(time, delta); + }, + + /** + * Start playing the given animation. + * + * @method Phaser.GameObjects.Sprite#play + * @since 3.0.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.Sprite} This Game Object. + */ + play: function (key, ignoreIfPlaying, startFrame) + { + this.anims.play(key, ignoreIfPlaying, startFrame); + + return this; + }, + + /** + * Build a JSON representation of this Sprite. + * + * @method Phaser.GameObjects.Sprite#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ + toJSON: function () + { + var data = Components.ToJSON(this); + + // Extra Sprite data is added here + + return data; + }, + + /** + * Handles the pre-destroy step for the Sprite, which removes the Animation component. + * + * @method Phaser.GameObjects.Sprite#preDestroy + * @private + * @since 3.14.0 + */ + preDestroy: function () + { + this.anims.destroy(); + + this.anims = undefined; + } + +}); + +module.exports = Sprite; + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var GetValue = __webpack_require__(5); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#json method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#json. + * + * @class JSONFile + * @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.JSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. + */ +var JSONFile = new Class({ + + Extends: File, + + initialize: + + // 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 + + function JSONFile (loader, key, url, xhrSettings, dataKey) + { + var extension = 'json'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + dataKey = GetFastValue(config, 'dataKey', dataKey); + } + + var fileConfig = { + type: 'json', + cache: loader.cacheManager.json, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: dataKey + }; + + File.call(this, loader, fileConfig); + + if (IsPlainObject(url)) + { + // Object provided instead of a URL, so no need to actually load it (populate data with value) + if (dataKey) + { + this.data = GetValue(url, dataKey); + } + else + { + this.data = url; + } + + this.state = CONST.FILE_POPULATED; + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.JSONFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + if (this.state !== CONST.FILE_POPULATED) + { + this.state = CONST.FILE_PROCESSING; + + var json = JSON.parse(this.xhrLoader.responseText); + + var key = this.config; + + if (typeof key === 'string') + { + this.data = GetValue(json, key, json); + } + else + { + this.data = json; + } + } + + this.onProcessComplete(); + } + +}); + +/** + * Adds a JSON file, or array of JSON 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.json('wavedata', 'files/AlienWaveData.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. + * + * 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.json({ + * key: 'wavedata', + * url: 'files/AlienWaveData.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.json('wavedata', 'files/AlienWaveData.json'); + * // and later in your game ... + * var data = this.cache.json.get('wavedata'); + * ``` + * + * 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 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#json + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.JSONFileConfig|Phaser.Types.Loader.FileTypes.JSONFileConfig[])} 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 `.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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('json', function (key, url, dataKey, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new JSONFile(this, key[i])); + } + } + else + { + this.addFile(new JSONFile(this, key, url, xhrSettings, dataKey)); + } + + return this; +}); + +module.exports = JSONFile; + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A MultiFile is a special kind of parent that contains two, or more, Files as children and looks after + * the loading and processing of them all. It is commonly extended and used as a base class for file types such as AtlasJSON or BitmapFont. + * + * You shouldn't create an instance of a MultiFile directly, but should extend it with your own class, setting a custom type and processing methods. + * + * @class MultiFile + * @memberof Phaser.Loader + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File. + * @param {string} type - The file type string for sorting within the Loader. + * @param {string} key - The key of the file within the loader. + * @param {Phaser.Loader.File[]} files - An array of Files that make-up this MultiFile. + */ +var MultiFile = new Class({ + + initialize: + + function MultiFile (loader, type, key, files) + { + /** + * A reference to the Loader that is going to load this file. + * + * @name Phaser.Loader.MultiFile#loader + * @type {Phaser.Loader.LoaderPlugin} + * @since 3.7.0 + */ + this.loader = loader; + + /** + * The file type string for sorting within the Loader. + * + * @name Phaser.Loader.MultiFile#type + * @type {string} + * @since 3.7.0 + */ + this.type = type; + + /** + * Unique cache key (unique within its file type) + * + * @name Phaser.Loader.MultiFile#key + * @type {string} + * @since 3.7.0 + */ + this.key = key; + + /** + * The current index being used by multi-file loaders to avoid key clashes. + * + * @name Phaser.Loader.MultiFile#multiKeyIndex + * @type {integer} + * @private + * @since 3.20.0 + */ + this.multiKeyIndex = loader.multiKeyIndex++; + + /** + * Array of files that make up this MultiFile. + * + * @name Phaser.Loader.MultiFile#files + * @type {Phaser.Loader.File[]} + * @since 3.7.0 + */ + this.files = files; + + /** + * The completion status of this MultiFile. + * + * @name Phaser.Loader.MultiFile#complete + * @type {boolean} + * @default false + * @since 3.7.0 + */ + this.complete = false; + + /** + * The number of files to load. + * + * @name Phaser.Loader.MultiFile#pending + * @type {integer} + * @since 3.7.0 + */ + + this.pending = files.length; + + /** + * The number of files that failed to load. + * + * @name Phaser.Loader.MultiFile#failed + * @type {integer} + * @default 0 + * @since 3.7.0 + */ + this.failed = 0; + + /** + * A storage container for transient data that the loading files need. + * + * @name Phaser.Loader.MultiFile#config + * @type {any} + * @since 3.7.0 + */ + this.config = {}; + + /** + * A reference to the Loaders baseURL at the time this MultiFile was created. + * Used to populate child-files. + * + * @name Phaser.Loader.MultiFile#baseURL + * @type {string} + * @since 3.20.0 + */ + this.baseURL = loader.baseURL; + + /** + * A reference to the Loaders path at the time this MultiFile was created. + * Used to populate child-files. + * + * @name Phaser.Loader.MultiFile#path + * @type {string} + * @since 3.20.0 + */ + this.path = loader.path; + + /** + * A reference to the Loaders prefix at the time this MultiFile was created. + * Used to populate child-files. + * + * @name Phaser.Loader.MultiFile#prefix + * @type {string} + * @since 3.20.0 + */ + this.prefix = loader.prefix; + + // Link the files + for (var i = 0; i < files.length; i++) + { + files[i].multiFile = this; + } + }, + + /** + * Checks if this MultiFile is ready to process its children or not. + * + * @method Phaser.Loader.MultiFile#isReadyToProcess + * @since 3.7.0 + * + * @return {boolean} `true` if all children of this MultiFile have loaded, otherwise `false`. + */ + isReadyToProcess: function () + { + return (this.pending === 0 && this.failed === 0 && !this.complete); + }, + + /** + * Adds another child to this MultiFile, increases the pending count and resets the completion status. + * + * @method Phaser.Loader.MultiFile#addToMultiFile + * @since 3.7.0 + * + * @param {Phaser.Loader.File} files - The File to add to this MultiFile. + * + * @return {Phaser.Loader.MultiFile} This MultiFile instance. + */ + addToMultiFile: function (file) + { + this.files.push(file); + + file.multiFile = this; + + this.pending++; + + this.complete = false; + + return this; + }, + + /** + * Called by each File when it finishes loading. + * + * @method Phaser.Loader.MultiFile#onFileComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has completed processing. + */ + onFileComplete: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.pending--; + } + }, + + /** + * Called by each File that fails to load. + * + * @method Phaser.Loader.MultiFile#onFileFailed + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has failed to load. + */ + onFileFailed: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.failed++; + } + } + +}); + +module.exports = MultiFile; + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Composite = {}; + +module.exports = Composite; + +var Events = __webpack_require__(96); +var Common = __webpack_require__(19); +var Bounds = __webpack_require__(38); +var Body = __webpack_require__(25); + +(function() { + + /** + * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. + * See the properites section below for detailed information on what you can pass via the `options` object. + * @method create + * @param {} [options] + * @return {composite} A new composite + */ + Composite.create = function(options) { + return Common.extend({ + id: Common.nextId(), + type: 'composite', + parent: null, + isModified: false, + bodies: [], + constraints: [], + composites: [], + label: 'Composite', + plugin: {} + }, options); + }; + + /** + * Sets the composite's `isModified` flag. + * If `updateParents` is true, all parents will be set (default: false). + * If `updateChildren` is true, all children will be set (default: false). + * @method setModified + * @param {composite} composite + * @param {boolean} isModified + * @param {boolean} [updateParents=false] + * @param {boolean} [updateChildren=false] + */ + Composite.setModified = function(composite, isModified, updateParents, updateChildren) { + + Events.trigger(composite, 'compositeModified', composite); + + composite.isModified = isModified; + + if (updateParents && composite.parent) { + Composite.setModified(composite.parent, isModified, updateParents, updateChildren); + } + + if (updateChildren) { + for(var i = 0; i < composite.composites.length; i++) { + var childComposite = composite.composites[i]; + Composite.setModified(childComposite, isModified, updateParents, updateChildren); + } + } + }; + + /** + * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. + * Triggers `beforeAdd` and `afterAdd` events on the `composite`. + * @method add + * @param {composite} composite + * @param {} object + * @return {composite} The original composite with the objects added + */ + Composite.add = function(composite, object) { + var objects = [].concat(object); + + Events.trigger(composite, 'beforeAdd', { object: object }); + + for (var i = 0; i < objects.length; i++) { + var obj = objects[i]; + + switch (obj.type) { + + case 'body': + // skip adding compound parts + if (obj.parent !== obj) { + Common.warn('Composite.add: skipped adding a compound body part (you must add its parent instead)'); + break; + } + + Composite.addBody(composite, obj); + break; + case 'constraint': + Composite.addConstraint(composite, obj); + break; + case 'composite': + Composite.addComposite(composite, obj); + break; + case 'mouseConstraint': + Composite.addConstraint(composite, obj.constraint); + break; + + } + } + + Events.trigger(composite, 'afterAdd', { object: object }); + + return composite; + }; + + /** + * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. + * Optionally searching its children recursively. + * Triggers `beforeRemove` and `afterRemove` events on the `composite`. + * @method remove + * @param {composite} composite + * @param {} object + * @param {boolean} [deep=false] + * @return {composite} The original composite with the objects removed + */ + Composite.remove = function(composite, object, deep) { + var objects = [].concat(object); + + Events.trigger(composite, 'beforeRemove', { object: object }); + + for (var i = 0; i < objects.length; i++) { + var obj = objects[i]; + + switch (obj.type) { + + case 'body': + Composite.removeBody(composite, obj, deep); + break; + case 'constraint': + Composite.removeConstraint(composite, obj, deep); + break; + case 'composite': + Composite.removeComposite(composite, obj, deep); + break; + case 'mouseConstraint': + Composite.removeConstraint(composite, obj.constraint); + break; + + } + } + + Events.trigger(composite, 'afterRemove', { object: object }); + + return composite; + }; + + /** + * Adds a composite to the given composite. + * @private + * @method addComposite + * @param {composite} compositeA + * @param {composite} compositeB + * @return {composite} The original compositeA with the objects from compositeB added + */ + Composite.addComposite = function(compositeA, compositeB) { + compositeA.composites.push(compositeB); + compositeB.parent = compositeA; + Composite.setModified(compositeA, true, true, false); + return compositeA; + }; + + /** + * Removes a composite from the given composite, and optionally searching its children recursively. + * @private + * @method removeComposite + * @param {composite} compositeA + * @param {composite} compositeB + * @param {boolean} [deep=false] + * @return {composite} The original compositeA with the composite removed + */ + Composite.removeComposite = function(compositeA, compositeB, deep) { + var position = compositeA.composites.indexOf(compositeB); + if (position !== -1) { + Composite.removeCompositeAt(compositeA, position); + Composite.setModified(compositeA, true, true, false); + } + + if (deep) { + for (var i = 0; i < compositeA.composites.length; i++){ + Composite.removeComposite(compositeA.composites[i], compositeB, true); + } + } + + return compositeA; + }; + + /** + * Removes a composite from the given composite. + * @private + * @method removeCompositeAt + * @param {composite} composite + * @param {number} position + * @return {composite} The original composite with the composite removed + */ + Composite.removeCompositeAt = function(composite, position) { + composite.composites.splice(position, 1); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Adds a body to the given composite. + * @private + * @method addBody + * @param {composite} composite + * @param {body} body + * @return {composite} The original composite with the body added + */ + Composite.addBody = function(composite, body) { + composite.bodies.push(body); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Removes a body from the given composite, and optionally searching its children recursively. + * @private + * @method removeBody + * @param {composite} composite + * @param {body} body + * @param {boolean} [deep=false] + * @return {composite} The original composite with the body removed + */ + Composite.removeBody = function(composite, body, deep) { + var position = composite.bodies.indexOf(body); + if (position !== -1) { + Composite.removeBodyAt(composite, position); + Composite.setModified(composite, true, true, false); + } + + if (deep) { + for (var i = 0; i < composite.composites.length; i++){ + Composite.removeBody(composite.composites[i], body, true); + } + } + + return composite; + }; + + /** + * Removes a body from the given composite. + * @private + * @method removeBodyAt + * @param {composite} composite + * @param {number} position + * @return {composite} The original composite with the body removed + */ + Composite.removeBodyAt = function(composite, position) { + composite.bodies.splice(position, 1); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Adds a constraint to the given composite. + * @private + * @method addConstraint + * @param {composite} composite + * @param {constraint} constraint + * @return {composite} The original composite with the constraint added + */ + Composite.addConstraint = function(composite, constraint) { + composite.constraints.push(constraint); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Removes a constraint from the given composite, and optionally searching its children recursively. + * @private + * @method removeConstraint + * @param {composite} composite + * @param {constraint} constraint + * @param {boolean} [deep=false] + * @return {composite} The original composite with the constraint removed + */ + Composite.removeConstraint = function(composite, constraint, deep) { + var position = composite.constraints.indexOf(constraint); + if (position !== -1) { + Composite.removeConstraintAt(composite, position); + } + + if (deep) { + for (var i = 0; i < composite.composites.length; i++){ + Composite.removeConstraint(composite.composites[i], constraint, true); + } + } + + return composite; + }; + + /** + * Removes a body from the given composite. + * @private + * @method removeConstraintAt + * @param {composite} composite + * @param {number} position + * @return {composite} The original composite with the constraint removed + */ + Composite.removeConstraintAt = function(composite, position) { + composite.constraints.splice(position, 1); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Removes all bodies, constraints and composites from the given composite. + * Optionally clearing its children recursively. + * @method clear + * @param {composite} composite + * @param {boolean} keepStatic + * @param {boolean} [deep=false] + */ + Composite.clear = function(composite, keepStatic, deep) { + if (deep) { + for (var i = 0; i < composite.composites.length; i++){ + Composite.clear(composite.composites[i], keepStatic, true); + } + } + + if (keepStatic) { + composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; }); + } else { + composite.bodies.length = 0; + } + + composite.constraints.length = 0; + composite.composites.length = 0; + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Returns all bodies in the given composite, including all bodies in its children, recursively. + * @method allBodies + * @param {composite} composite + * @return {body[]} All the bodies + */ + Composite.allBodies = function(composite) { + var bodies = [].concat(composite.bodies); + + for (var i = 0; i < composite.composites.length; i++) + bodies = bodies.concat(Composite.allBodies(composite.composites[i])); + + return bodies; + }; + + /** + * Returns all constraints in the given composite, including all constraints in its children, recursively. + * @method allConstraints + * @param {composite} composite + * @return {constraint[]} All the constraints + */ + Composite.allConstraints = function(composite) { + var constraints = [].concat(composite.constraints); + + for (var i = 0; i < composite.composites.length; i++) + constraints = constraints.concat(Composite.allConstraints(composite.composites[i])); + + return constraints; + }; + + /** + * Returns all composites in the given composite, including all composites in its children, recursively. + * @method allComposites + * @param {composite} composite + * @return {composite[]} All the composites + */ + Composite.allComposites = function(composite) { + var composites = [].concat(composite.composites); + + for (var i = 0; i < composite.composites.length; i++) + composites = composites.concat(Composite.allComposites(composite.composites[i])); + + return composites; + }; + + /** + * Searches the composite recursively for an object matching the type and id supplied, null if not found. + * @method get + * @param {composite} composite + * @param {number} id + * @param {string} type + * @return {object} The requested object, if found + */ + Composite.get = function(composite, id, type) { + var objects, + object; + + switch (type) { + case 'body': + objects = Composite.allBodies(composite); + break; + case 'constraint': + objects = Composite.allConstraints(composite); + break; + case 'composite': + objects = Composite.allComposites(composite).concat(composite); + break; + } + + if (!objects) + return null; + + object = objects.filter(function(object) { + return object.id.toString() === id.toString(); + }); + + return object.length === 0 ? null : object[0]; + }; + + /** + * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). + * @method move + * @param {compositeA} compositeA + * @param {object[]} objects + * @param {compositeB} compositeB + * @return {composite} Returns compositeA + */ + Composite.move = function(compositeA, objects, compositeB) { + Composite.remove(compositeA, objects); + Composite.add(compositeB, objects); + return compositeA; + }; + + /** + * Assigns new ids for all objects in the composite, recursively. + * @method rebase + * @param {composite} composite + * @return {composite} Returns composite + */ + Composite.rebase = function(composite) { + var objects = Composite.allBodies(composite) + .concat(Composite.allConstraints(composite)) + .concat(Composite.allComposites(composite)); + + for (var i = 0; i < objects.length; i++) { + objects[i].id = Common.nextId(); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Translates all children in the composite by a given vector relative to their current positions, + * without imparting any velocity. + * @method translate + * @param {composite} composite + * @param {vector} translation + * @param {bool} [recursive=true] + */ + Composite.translate = function(composite, translation, recursive) { + var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; + + for (var i = 0; i < bodies.length; i++) { + Body.translate(bodies[i], translation); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. + * @method rotate + * @param {composite} composite + * @param {number} rotation + * @param {vector} point + * @param {bool} [recursive=true] + */ + Composite.rotate = function(composite, rotation, point, recursive) { + var cos = Math.cos(rotation), + sin = Math.sin(rotation), + bodies = recursive ? Composite.allBodies(composite) : composite.bodies; + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + dx = body.position.x - point.x, + dy = body.position.y - point.y; + + Body.setPosition(body, { + x: point.x + (dx * cos - dy * sin), + y: point.y + (dx * sin + dy * cos) + }); + + Body.rotate(body, rotation); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. + * @method scale + * @param {composite} composite + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + * @param {bool} [recursive=true] + */ + Composite.scale = function(composite, scaleX, scaleY, point, recursive) { + var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + dx = body.position.x - point.x, + dy = body.position.y - point.y; + + Body.setPosition(body, { + x: point.x + dx * scaleX, + y: point.y + dy * scaleY + }); + + Body.scale(body, scaleX, scaleY); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Returns the union of the bounds of all of the composite's bodies. + * @method bounds + * @param {composite} composite The composite. + * @returns {bounds} The composite bounds. + */ + Composite.bounds = function(composite) { + var bodies = Composite.allBodies(composite), + vertices = []; + + for (var i = 0; i < bodies.length; i += 1) { + var body = bodies[i]; + vertices.push(body.bounds.min, body.bounds.max); + } + + return Bounds.create(vertices); + }; + + /* + * + * Events Documentation + * + */ + + /** + * Fired when a call to `Composite.add` is made, before objects have been added. + * + * @event beforeAdd + * @param {} event An event object + * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a call to `Composite.add` is made, after objects have been added. + * + * @event afterAdd + * @param {} event An event object + * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a call to `Composite.remove` is made, before objects have been removed. + * + * @event beforeRemove + * @param {} event An event object + * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a call to `Composite.remove` is made, after objects have been removed. + * + * @event afterRemove + * @param {} event An event object + * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "composite" + * @readOnly + */ + + /** + * An arbitrary `String` name to help the user identify and manage composites. + * + * @property label + * @type string + * @default "Composite" + */ + + /** + * A flag that specifies whether the composite has been modified during the current step. + * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. + * If you need to change it manually, you should use the `Composite.setModified` method. + * + * @property isModified + * @type boolean + * @default false + */ + + /** + * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. + * + * @property parent + * @type composite + * @default null + */ + + /** + * An array of `Body` that are _direct_ children of this composite. + * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. + * + * @property bodies + * @type body[] + * @default [] + */ + + /** + * An array of `Constraint` that are _direct_ children of this composite. + * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. + * + * @property constraints + * @type constraint[] + * @default [] + */ + + /** + * An array of `Composite` that are _direct_ children of this composite. + * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. + * + * @property composites + * @type composite[] + * @default [] + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + +})(); + + +/***/ }), +/* 69 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileX + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The X location in tile units. + */ +var WorldToTileX = function (worldX, snapToFloor, camera, layer) +{ + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + } + + return snapToFloor + ? Math.floor(worldX / tileWidth) + : worldX / tileWidth; +}; + +module.exports = WorldToTileX; + + +/***/ }), +/* 70 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileY + * @private + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The Y location in tile units. + */ +var WorldToTileY = function (worldY, snapToFloor, camera, layer) +{ + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + return snapToFloor + ? Math.floor(worldY / tileHeight) + : worldY / tileHeight; +}; + +module.exports = WorldToTileY; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Contains = __webpack_require__(60); +var GetPoint = __webpack_require__(284); +var GetPoints = __webpack_require__(285); +var GEOM_CONST = __webpack_require__(52); +var Random = __webpack_require__(159); + +/** + * @classdesc + * A Circle object. + * + * This is a geometry object, containing numerical values and related methods to inspect and modify them. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render a Circle you should look at the capabilities of the Graphics class. + * + * @class Circle + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the circle. + * @param {number} [y=0] - The y position of the center of the circle. + * @param {number} [radius=0] - The radius of the circle. + */ +var Circle = new Class({ + + initialize: + + function Circle (x, y, radius) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (radius === undefined) { radius = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.CIRCLE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Circle#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.CIRCLE; + + /** + * The x position of the center of the circle. + * + * @name Phaser.Geom.Circle#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The y position of the center of the circle. + * + * @name Phaser.Geom.Circle#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + + /** + * The internal radius of the circle. + * + * @name Phaser.Geom.Circle#_radius + * @type {number} + * @private + * @since 3.0.0 + */ + this._radius = radius; + + /** + * The internal diameter of the circle. + * + * @name Phaser.Geom.Circle#_diameter + * @type {number} + * @private + * @since 3.0.0 + */ + this._diameter = radius * 2; + }, + + /** + * Check to see if the Circle contains the given x / y coordinates. + * + * @method Phaser.Geom.Circle#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check within the circle. + * @param {number} y - The y coordinate to check within the circle. + * + * @return {boolean} True if the coordinates are within the circle, otherwise false. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * 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.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle. + */ + getPoint: function (position, point) + { + return GetPoint(this, position, point); + }, + + /** + * 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 circle and dividing it by the stepRate. + * @param {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the circle. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a uniformly distributed random point from anywhere within the Circle. + * + * @method Phaser.Geom.Circle#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {(Phaser.Geom.Point|object)} [point] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets the x, y and radius of this circle. + * + * @method Phaser.Geom.Circle#setTo + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the circle. + * @param {number} [y=0] - The y position of the center of the circle. + * @param {number} [radius=0] - The radius of the circle. + * + * @return {Phaser.Geom.Circle} This Circle object. + */ + setTo: function (x, y, radius) + { + this.x = x; + this.y = y; + this._radius = radius; + this._diameter = radius * 2; + + return this; + }, + + /** + * Sets this Circle to be empty with a radius of zero. + * Does not change its position. + * + * @method Phaser.Geom.Circle#setEmpty + * @since 3.0.0 + * + * @return {Phaser.Geom.Circle} This Circle object. + */ + setEmpty: function () + { + this._radius = 0; + this._diameter = 0; + + return this; + }, + + /** + * Sets the position of this Circle. + * + * @method Phaser.Geom.Circle#setPosition + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the circle. + * @param {number} [y=0] - The y position of the center of the circle. + * + * @return {Phaser.Geom.Circle} This Circle object. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Checks to see if the Circle is empty: has a radius of zero. + * + * @method Phaser.Geom.Circle#isEmpty + * @since 3.0.0 + * + * @return {boolean} True if the Circle is empty, otherwise false. + */ + isEmpty: function () + { + return (this._radius <= 0); + }, + + /** + * The radius of the Circle. + * + * @name Phaser.Geom.Circle#radius + * @type {number} + * @since 3.0.0 + */ + radius: { + + get: function () + { + return this._radius; + }, + + set: function (value) + { + this._radius = value; + this._diameter = value * 2; + } + + }, + + /** + * The diameter of the Circle. + * + * @name Phaser.Geom.Circle#diameter + * @type {number} + * @since 3.0.0 + */ + diameter: { + + get: function () + { + return this._diameter; + }, + + set: function (value) + { + this._diameter = value; + this._radius = value * 0.5; + } + + }, + + /** + * The left position of the Circle. + * + * @name Phaser.Geom.Circle#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.x - this._radius; + }, + + set: function (value) + { + this.x = value + this._radius; + } + + }, + + /** + * The right position of the Circle. + * + * @name Phaser.Geom.Circle#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.x + this._radius; + }, + + set: function (value) + { + this.x = value - this._radius; + } + + }, + + /** + * The top position of the Circle. + * + * @name Phaser.Geom.Circle#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.y - this._radius; + }, + + set: function (value) + { + this.y = value + this._radius; + } + + }, + + /** + * The bottom position of the Circle. + * + * @name Phaser.Geom.Circle#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.y + this._radius; + }, + + set: function (value) + { + this.y = value - this._radius; + } + + } + +}); + +module.exports = Circle; + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Earcut 2.1.4 (December 4th 2018) + +/* + * 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. + */ + + + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate collinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter collinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // 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 + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // 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 + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// 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 +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + + +/***/ }), +/* 73 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Shallow Object Clone. Will not clone nested objects. + * + * @function Phaser.Utils.Objects.Clone + * @since 3.0.0 + * + * @param {object} obj - the object from which to clone + * + * @return {object} a new object with the same properties as the input obj + */ +var Clone = function (obj) +{ + var clone = {}; + + for (var key in obj) + { + if (Array.isArray(obj[key])) + { + clone[key] = obj[key].slice(0); + } + else + { + clone[key] = obj[key]; + } + } + + return clone; +}; + +module.exports = Clone; + + +/***/ }), +/* 74 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tests if the start and end indexes are a safe range for the given array. + * + * @function Phaser.Utils.Array.SafeRange + * @since 3.4.0 + * + * @param {array} array - The array to check. + * @param {integer} startIndex - The start index. + * @param {integer} endIndex - The end index. + * @param {boolean} [throwError=true] - Throw an error if the range is out of bounds. + * + * @return {boolean} True if the range is safe, otherwise false. + */ +var SafeRange = function (array, startIndex, endIndex, throwError) +{ + var len = array.length; + + if (startIndex < 0 || + startIndex > len || + startIndex >= endIndex || + endIndex > len || + startIndex + endIndex > len) + { + if (throwError) + { + throw new Error('Range Error: Values outside acceptable range'); + } + + return false; + } + else + { + return true; + } +}; + +module.exports = SafeRange; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders a stroke outline around the given Shape. + * + * @method Phaser.GameObjects.Shape#StrokePathWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipeline - The WebGL Pipeline used to render this Shape. + * @param {Phaser.GameObjects.Shape} src - The Game Object shape being rendered in this call. + * @param {number} alpha - The base alpha value. + * @param {number} dx - The source displayOriginX. + * @param {number} dy - The source displayOriginY. + */ +var StrokePathWebGL = function (pipeline, src, alpha, dx, dy) +{ + var strokeTint = pipeline.strokeTint; + var strokeTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); + + strokeTint.TL = strokeTintColor; + strokeTint.TR = strokeTintColor; + strokeTint.BL = strokeTintColor; + strokeTint.BR = strokeTintColor; + + var path = src.pathData; + var pathLength = path.length - 1; + var lineWidth = src.lineWidth; + var halfLineWidth = lineWidth / 2; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + pipeline.setTexture2D(); + + pipeline.batchLine( + px1, + py1, + px2, + py2, + halfLineWidth, + halfLineWidth, + lineWidth, + i - 2, + (src.closePath) ? (i === pathLength - 1) : false + ); + + px1 = px2; + py1 = py2; + } +}; + +module.exports = StrokePathWebGL; + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Contains = __webpack_require__(92); +var GetPoint = __webpack_require__(448); +var GetPoints = __webpack_require__(449); +var GEOM_CONST = __webpack_require__(52); +var Line = __webpack_require__(61); +var Random = __webpack_require__(168); + +/** + * @classdesc + * A triangle is a plane created by connecting three points. + * The first two arguments specify the first point, the middle two arguments + * specify the second point, and the last two arguments specify the third point. + * + * @class Triangle + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x1=0] - `x` coordinate of the first point. + * @param {number} [y1=0] - `y` coordinate of the first point. + * @param {number} [x2=0] - `x` coordinate of the second point. + * @param {number} [y2=0] - `y` coordinate of the second point. + * @param {number} [x3=0] - `x` coordinate of the third point. + * @param {number} [y3=0] - `y` coordinate of the third point. + */ +var Triangle = new Class({ + + initialize: + + function Triangle (x1, y1, x2, y2, x3, y3) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + if (x3 === undefined) { x3 = 0; } + if (y3 === undefined) { y3 = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.TRIANGLE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Triangle#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.TRIANGLE; + + /** + * `x` coordinate of the first point. + * + * @name Phaser.Geom.Triangle#x1 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x1 = x1; + + /** + * `y` coordinate of the first point. + * + * @name Phaser.Geom.Triangle#y1 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y1 = y1; + + /** + * `x` coordinate of the second point. + * + * @name Phaser.Geom.Triangle#x2 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x2 = x2; + + /** + * `y` coordinate of the second point. + * + * @name Phaser.Geom.Triangle#y2 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y2 = y2; + + /** + * `x` coordinate of the third point. + * + * @name Phaser.Geom.Triangle#x3 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x3 = x3; + + /** + * `y` coordinate of the third point. + * + * @name Phaser.Geom.Triangle#y3 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y3 = y3; + }, + + /** + * Checks whether a given points lies within the triangle. + * + * @method Phaser.Geom.Triangle#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the point to check. + * @param {number} y - The y coordinate of the point to check. + * + * @return {boolean} `true` if the coordinate pair is within the triangle, otherwise `false`. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Returns a specific point on the triangle. + * + * @method Phaser.Geom.Triangle#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [output,$return] + * + * @param {number} position - Position as float within `0` and `1`. `0` equals the first point. + * @param {(Phaser.Geom.Point|object)} [output] - Optional Point, or point-like object, that the calculated point will be written to. + * + * @return {(Phaser.Geom.Point|object)} Calculated `Point` that represents the requested position. It is the same as `output` when this parameter has been given. + */ + getPoint: function (position, output) + { + return GetPoint(this, position, output); + }, + + /** + * Calculates a list of evenly distributed points on the triangle. It is either possible to pass an amount of points to be generated (`quantity`) or the distance between two points (`stepRate`). + * + * @method Phaser.Geom.Triangle#getPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [output,$return] + * + * @param {integer} quantity - Number of points to be generated. Can be falsey when `stepRate` should be used. All points have the same distance along the triangle. + * @param {number} [stepRate] - Distance between two points. Will only be used when `quantity` is falsey. + * @param {(array|Phaser.Geom.Point[])} [output] - Optional Array for writing the calculated points into. Otherwise a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} Returns a list of calculated `Point` instances or the filled array passed as parameter `output`. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a random point along the triangle. + * + * @method Phaser.Geom.Triangle#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} [point] - Optional `Point` that should be modified. Otherwise a new one will be created. + * + * @return {Phaser.Geom.Point} Random `Point`. When parameter `point` has been provided it will be returned. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets all three points of the triangle. Leaving out any coordinate sets it to be `0`. + * + * @method Phaser.Geom.Triangle#setTo + * @since 3.0.0 + * + * @param {number} [x1=0] - `x` coordinate of the first point. + * @param {number} [y1=0] - `y` coordinate of the first point. + * @param {number} [x2=0] - `x` coordinate of the second point. + * @param {number} [y2=0] - `y` coordinate of the second point. + * @param {number} [x3=0] - `x` coordinate of the third point. + * @param {number} [y3=0] - `y` coordinate of the third point. + * + * @return {Phaser.Geom.Triangle} This Triangle object. + */ + setTo: function (x1, y1, x2, y2, x3, y3) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + if (x3 === undefined) { x3 = 0; } + if (y3 === undefined) { y3 = 0; } + + this.x1 = x1; + this.y1 = y1; + + this.x2 = x2; + this.y2 = y2; + + this.x3 = x3; + this.y3 = y3; + + return this; + }, + + /** + * Returns a Line object that corresponds to Line A of this Triangle. + * + * @method Phaser.Geom.Triangle#getLineA + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to line A of this Triangle. + */ + getLineA: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x1, this.y1, this.x2, this.y2); + + return line; + }, + + /** + * Returns a Line object that corresponds to Line B of this Triangle. + * + * @method Phaser.Geom.Triangle#getLineB + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to line B of this Triangle. + */ + getLineB: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x2, this.y2, this.x3, this.y3); + + return line; + }, + + /** + * Returns a Line object that corresponds to Line C of this Triangle. + * + * @method Phaser.Geom.Triangle#getLineC + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to line C of this Triangle. + */ + getLineC: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x3, this.y3, this.x1, this.y1); + + return line; + }, + + /** + * Left most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. + * + * @name Phaser.Geom.Triangle#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return Math.min(this.x1, this.x2, this.x3); + }, + + set: function (value) + { + var diff = 0; + + if (this.x1 <= this.x2 && this.x1 <= this.x3) + { + diff = this.x1 - value; + } + else if (this.x2 <= this.x1 && this.x2 <= this.x3) + { + diff = this.x2 - value; + } + else + { + diff = this.x3 - value; + } + + this.x1 -= diff; + this.x2 -= diff; + this.x3 -= diff; + } + + }, + + /** + * Right most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. + * + * @name Phaser.Geom.Triangle#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return Math.max(this.x1, this.x2, this.x3); + }, + + set: function (value) + { + var diff = 0; + + if (this.x1 >= this.x2 && this.x1 >= this.x3) + { + diff = this.x1 - value; + } + else if (this.x2 >= this.x1 && this.x2 >= this.x3) + { + diff = this.x2 - value; + } + else + { + diff = this.x3 - value; + } + + this.x1 -= diff; + this.x2 -= diff; + this.x3 -= diff; + } + + }, + + /** + * Top most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. + * + * @name Phaser.Geom.Triangle#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return Math.min(this.y1, this.y2, this.y3); + }, + + set: function (value) + { + var diff = 0; + + if (this.y1 <= this.y2 && this.y1 <= this.y3) + { + diff = this.y1 - value; + } + else if (this.y2 <= this.y1 && this.y2 <= this.y3) + { + diff = this.y2 - value; + } + else + { + diff = this.y3 - value; + } + + this.y1 -= diff; + this.y2 -= diff; + this.y3 -= diff; + } + + }, + + /** + * Bottom most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. + * + * @name Phaser.Geom.Triangle#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return Math.max(this.y1, this.y2, this.y3); + }, + + set: function (value) + { + var diff = 0; + + if (this.y1 >= this.y2 && this.y1 >= this.y3) + { + diff = this.y1 - value; + } + else if (this.y2 >= this.y1 && this.y2 >= this.y3) + { + diff = this.y2 - value; + } + else + { + diff = this.y3 - value; + } + + this.y1 -= diff; + this.y2 -= diff; + this.y3 -= diff; + } + + } + +}); + +module.exports = Triangle; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Image File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#image method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#image. + * + * @class ImageFile + * @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.ImageFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. Only provided for, and used by, Sprite Sheets. + */ +var ImageFile = new Class({ + + Extends: File, + + initialize: + + function ImageFile (loader, key, url, xhrSettings, frameConfig) + { + var extension = 'png'; + var normalMapURL; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + normalMapURL = GetFastValue(config, 'normalMap'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + frameConfig = GetFastValue(config, 'frameConfig'); + } + + if (Array.isArray(url)) + { + normalMapURL = url[1]; + url = url[0]; + } + + var fileConfig = { + type: 'image', + cache: loader.textureManager, + extension: extension, + responseType: 'blob', + key: key, + url: url, + xhrSettings: xhrSettings, + config: frameConfig + }; + + File.call(this, loader, fileConfig); + + // Do we have a normal map to load as well? + if (normalMapURL) + { + var normalMap = new ImageFile(loader, this.key, normalMapURL, xhrSettings, frameConfig); + + normalMap.type = 'normalMap'; + + this.setLink(normalMap); + + loader.addFile(normalMap); + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.ImageFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = new Image(); + + this.data.crossOrigin = this.crossOrigin; + + var _this = this; + + this.data.onload = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessError(); + }; + + File.createObjectURL(this.data, this.xhrLoader.response, 'image/png'); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.ImageFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture; + var linkFile = this.linkFile; + + if (linkFile && linkFile.state === CONST.FILE_COMPLETE) + { + if (this.type === 'image') + { + texture = this.cache.addImage(this.key, this.data, linkFile.data); + } + else + { + texture = this.cache.addImage(linkFile.key, linkFile.data, this.data); + } + + this.pendingDestroy(texture); + + linkFile.pendingDestroy(texture); + } + else if (!linkFile) + { + texture = this.cache.addImage(this.key, this.data); + + this.pendingDestroy(texture); + } + } + +}); + +/** + * Adds an Image, or array of Images, 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.image('logo', 'images/phaserLogo.png'); + * } + * ``` + * + * 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. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback + * of animated gifs to Canvas elements. + * + * 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.image({ + * key: 'logo', + * url: 'images/AtariLogo.png' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ImageFileConfig` 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.image('logo', 'images/AtariLogo.png'); + * // and later in your game ... + * this.add.image(x, y, 'logo'); + * ``` + * + * 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.image('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ]); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.image({ + * key: 'logo', + * url: 'images/AtariLogo.png', + * normalMap: 'images/AtariLogo-n.png' + * }); + * ``` + * + * 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 Image 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#image + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.ImageFileConfig|Phaser.Types.Loader.FileTypes.ImageFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('image', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new ImageFile(this, key[i])); + } + } + else + { + this.addFile(new ImageFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = ImageFile; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Constraint = {}; + +module.exports = Constraint; + +var Vertices = __webpack_require__(31); +var Vector = __webpack_require__(37); +var Sleeping = __webpack_require__(95); +var Bounds = __webpack_require__(38); +var Axes = __webpack_require__(146); +var Common = __webpack_require__(19); + +(function() { + + Constraint._warming = 0.4; + Constraint._torqueDampen = 1; + Constraint._minLength = 0.000001; + + /** + * 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 + */ + Constraint.create = function(options) { + var constraint = options; + + // if bodies defined but no points, use body centre + if (constraint.bodyA && !constraint.pointA) + constraint.pointA = { x: 0, y: 0 }; + if (constraint.bodyB && !constraint.pointB) + constraint.pointB = { x: 0, y: 0 }; + + // calculate static length using initial world space points + var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA, + initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB, + length = Vector.magnitude(Vector.sub(initialPointA, initialPointB)); + + constraint.length = typeof constraint.length !== 'undefined' ? constraint.length : length; + + // option defaults + constraint.id = constraint.id || Common.nextId(); + constraint.label = constraint.label || 'Constraint'; + constraint.type = 'constraint'; + constraint.stiffness = constraint.stiffness || (constraint.length > 0 ? 1 : 0.7); + constraint.damping = constraint.damping || 0; + constraint.angularStiffness = constraint.angularStiffness || 0; + constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA; + constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB; + constraint.plugin = {}; + + // render + var render = { + visible: true, + type: 'line', + anchors: true, + lineColor: null, // custom Phaser property + lineOpacity: null, // custom Phaser property + lineThickness: null, // custom Phaser property + pinSize: null, // custom Phaser property + anchorColor: null, // custom Phaser property + anchorSize: null // custom Phaser property + }; + + if (constraint.length === 0 && constraint.stiffness > 0.1) { + render.type = 'pin'; + render.anchors = false; + } else if (constraint.stiffness < 0.9) { + render.type = 'spring'; + } + + constraint.render = Common.extend(render, constraint.render); + + return constraint; + }; + + /** + * Prepares for solving by constraint warming. + * @private + * @method preSolveAll + * @param {body[]} bodies + */ + Constraint.preSolveAll = function(bodies) { + for (var i = 0; i < bodies.length; i += 1) { + var body = bodies[i], + impulse = body.constraintImpulse; + + if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) { + continue; + } + + body.position.x += impulse.x; + body.position.y += impulse.y; + body.angle += impulse.angle; + } + }; + + /** + * Solves all constraints in a list of collisions. + * @private + * @method solveAll + * @param {constraint[]} constraints + * @param {number} timeScale + */ + Constraint.solveAll = function(constraints, timeScale) { + // Solve fixed constraints first. + for (var i = 0; i < constraints.length; i += 1) { + var constraint = constraints[i], + fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic), + fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic); + + if (fixedA || fixedB) { + Constraint.solve(constraints[i], timeScale); + } + } + + // Solve free constraints last. + for (i = 0; i < constraints.length; i += 1) { + constraint = constraints[i]; + fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic); + fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic); + + if (!fixedA && !fixedB) { + Constraint.solve(constraints[i], timeScale); + } + } + }; + + /** + * Solves a distance constraint with Gauss-Siedel method. + * @private + * @method solve + * @param {constraint} constraint + * @param {number} timeScale + */ + Constraint.solve = function(constraint, timeScale) { + var bodyA = constraint.bodyA, + bodyB = constraint.bodyB, + pointA = constraint.pointA, + pointB = constraint.pointB; + + if (!bodyA && !bodyB) + return; + + // update reference angle + if (bodyA && !bodyA.isStatic) { + Vector.rotate(pointA, bodyA.angle - constraint.angleA, pointA); + constraint.angleA = bodyA.angle; + } + + // update reference angle + if (bodyB && !bodyB.isStatic) { + Vector.rotate(pointB, bodyB.angle - constraint.angleB, pointB); + constraint.angleB = bodyB.angle; + } + + var pointAWorld = pointA, + pointBWorld = pointB; + + if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA); + if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB); + + if (!pointAWorld || !pointBWorld) + return; + + var delta = Vector.sub(pointAWorld, pointBWorld), + currentLength = Vector.magnitude(delta); + + // prevent singularity + if (currentLength < Constraint._minLength) { + currentLength = Constraint._minLength; + } + + // solve distance constraint with Gauss-Siedel method + var difference = (currentLength - constraint.length) / currentLength, + stiffness = constraint.stiffness < 1 ? constraint.stiffness * timeScale : constraint.stiffness, + force = Vector.mult(delta, difference * stiffness), + massTotal = (bodyA ? bodyA.inverseMass : 0) + (bodyB ? bodyB.inverseMass : 0), + inertiaTotal = (bodyA ? bodyA.inverseInertia : 0) + (bodyB ? bodyB.inverseInertia : 0), + resistanceTotal = massTotal + inertiaTotal, + torque, + share, + normal, + normalVelocity, + relativeVelocity; + + if (constraint.damping) { + var zero = Vector.create(); + normal = Vector.div(delta, currentLength); + + relativeVelocity = Vector.sub( + bodyB && Vector.sub(bodyB.position, bodyB.positionPrev) || zero, + bodyA && Vector.sub(bodyA.position, bodyA.positionPrev) || zero + ); + + normalVelocity = Vector.dot(normal, relativeVelocity); + } + + if (bodyA && !bodyA.isStatic) { + share = bodyA.inverseMass / massTotal; + + // keep track of applied impulses for post solving + bodyA.constraintImpulse.x -= force.x * share; + bodyA.constraintImpulse.y -= force.y * share; + + // apply forces + bodyA.position.x -= force.x * share; + bodyA.position.y -= force.y * share; + + // apply damping + if (constraint.damping) { + bodyA.positionPrev.x -= constraint.damping * normal.x * normalVelocity * share; + bodyA.positionPrev.y -= constraint.damping * normal.y * normalVelocity * share; + } + + // apply torque + torque = (Vector.cross(pointA, force) / resistanceTotal) * Constraint._torqueDampen * bodyA.inverseInertia * (1 - constraint.angularStiffness); + bodyA.constraintImpulse.angle -= torque; + bodyA.angle -= torque; + } + + if (bodyB && !bodyB.isStatic) { + share = bodyB.inverseMass / massTotal; + + // keep track of applied impulses for post solving + bodyB.constraintImpulse.x += force.x * share; + bodyB.constraintImpulse.y += force.y * share; + + // apply forces + bodyB.position.x += force.x * share; + bodyB.position.y += force.y * share; + + // apply damping + if (constraint.damping) { + bodyB.positionPrev.x += constraint.damping * normal.x * normalVelocity * share; + bodyB.positionPrev.y += constraint.damping * normal.y * normalVelocity * share; + } + + // apply torque + torque = (Vector.cross(pointB, force) / resistanceTotal) * Constraint._torqueDampen * bodyB.inverseInertia * (1 - constraint.angularStiffness); + bodyB.constraintImpulse.angle += torque; + bodyB.angle += torque; + } + + }; + + /** + * Performs body updates required after solving constraints. + * @private + * @method postSolveAll + * @param {body[]} bodies + */ + Constraint.postSolveAll = function(bodies) { + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + impulse = body.constraintImpulse; + + if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) { + continue; + } + + Sleeping.set(body, false); + + // update geometry and reset + for (var j = 0; j < body.parts.length; j++) { + var part = body.parts[j]; + + Vertices.translate(part.vertices, impulse); + + if (j > 0) { + part.position.x += impulse.x; + part.position.y += impulse.y; + } + + if (impulse.angle !== 0) { + Vertices.rotate(part.vertices, impulse.angle, body.position); + Axes.rotate(part.axes, impulse.angle); + if (j > 0) { + Vector.rotateAbout(part.position, impulse.angle, body.position, part.position); + } + } + + Bounds.update(part.bounds, part.vertices, body.velocity); + } + + // dampen the cached impulse for warming next step + impulse.angle *= Constraint._warming; + impulse.x *= Constraint._warming; + impulse.y *= Constraint._warming; + } + }; + + /** + * Returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`. + * @method pointAWorld + * @param {constraint} constraint + * @returns {vector} the world-space position + */ + Constraint.pointAWorld = function(constraint) { + return { + x: (constraint.bodyA ? constraint.bodyA.position.x : 0) + constraint.pointA.x, + y: (constraint.bodyA ? constraint.bodyA.position.y : 0) + constraint.pointA.y + }; + }; + + /** + * Returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`. + * @method pointBWorld + * @param {constraint} constraint + * @returns {vector} the world-space position + */ + Constraint.pointBWorld = function(constraint) { + return { + x: (constraint.bodyB ? constraint.bodyB.position.x : 0) + constraint.pointB.x, + y: (constraint.bodyB ? constraint.bodyB.position.y : 0) + constraint.pointB.y + }; + }; + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "constraint" + * @readOnly + */ + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Constraint" + */ + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + + /** + * A flag that indicates if the constraint should be rendered. + * + * @property render.visible + * @type boolean + * @default true + */ + + /** + * A `Number` that defines the line width to use when rendering the constraint outline. + * A value of `0` means no outline will be rendered. + * + * @property render.lineWidth + * @type number + * @default 2 + */ + + /** + * A `String` that defines the stroke style to use when rendering the constraint outline. + * It is the same as when using a canvas, so it accepts CSS style property values. + * + * @property render.strokeStyle + * @type string + * @default a random colour + */ + + /** + * A `String` that defines the constraint rendering type. + * The possible values are 'line', 'pin', 'spring'. + * An appropriate render type will be automatically chosen unless one is given in options. + * + * @property render.type + * @type string + * @default 'line' + */ + + /** + * A `Boolean` that defines if the constraint's anchor points should be rendered. + * + * @property render.anchors + * @type boolean + * @default true + */ + + /** + * The first possible `Body` that this constraint is attached to. + * + * @property bodyA + * @type body + * @default null + */ + + /** + * The second possible `Body` that this constraint is attached to. + * + * @property bodyB + * @type body + * @default null + */ + + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. + * + * @property pointA + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. + * + * @property pointB + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. + * A value of `1` means the constraint should be very stiff. + * A value of `0.2` means the constraint acts like a soft spring. + * + * @property stiffness + * @type number + * @default 1 + */ + + /** + * 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 + */ + + /** + * A `Number` that specifies the target resting length of the constraint. + * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * + * @property length + * @type number + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + +})(); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internally used method to set the colliding state of a tile. This does not recalculate + * interesting faces. + * + * @function Phaser.Tilemaps.Components.SetTileCollision + * @private + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The Tile to set the collision on. + * @param {boolean} [collides=true] - Should the tile index collide or not? + */ +var SetTileCollision = function (tile, collides) +{ + if (collides) + { + tile.setCollision(true, true, true, true, false); + } + else + { + tile.resetCollision(false); + } +}; + +module.exports = SetTileCollision; + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var Rectangle = __webpack_require__(467); + +/** + * @classdesc + * A Tile is a representation of a single tile within the Tilemap. This is a lightweight data + * representation, so its position information is stored without factoring in scroll, layer + * scale or layer position. + * + * @class Tile + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Tilemaps.LayerData} layer - The LayerData object in the Tilemap that this tile belongs to. + * @param {integer} index - The unique index of this tile within the map. + * @param {integer} x - The x coordinate of this tile in tile coordinates. + * @param {integer} y - The y coordinate of this tile in tile coordinates. + * @param {integer} width - Width of the tile in pixels. + * @param {integer} height - Height of the tile in pixels. + * @param {integer} baseWidth - The base width a tile in the map (in pixels). Tiled maps support + * multiple tileset sizes within one map, but they are still placed at intervals of the base + * tile width. + * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). Tiled maps + * support multiple tileset sizes within one map, but they are still placed at intervals of the + * base tile height. + */ +var Tile = new Class({ + + Mixins: [ + Components.Alpha, + Components.Flip, + Components.Visible + ], + + initialize: + + function Tile (layer, index, x, y, width, height, baseWidth, baseHeight) + { + /** + * The LayerData in the Tilemap data that this tile belongs to. + * + * @name Phaser.Tilemaps.Tile#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + this.layer = layer; + + /** + * The index of this tile within the map data corresponding to the tileset, or -1 if this + * represents a blank tile. + * + * @name Phaser.Tilemaps.Tile#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * The x map coordinate of this tile in tile units. + * + * @name Phaser.Tilemaps.Tile#x + * @type {integer} + * @since 3.0.0 + */ + this.x = x; + + /** + * The y map coordinate of this tile in tile units. + * + * @name Phaser.Tilemaps.Tile#y + * @type {integer} + * @since 3.0.0 + */ + this.y = y; + + /** + * The width of the tile in pixels. + * + * @name Phaser.Tilemaps.Tile#width + * @type {integer} + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the tile in pixels. + * + * @name Phaser.Tilemaps.Tile#height + * @type {integer} + * @since 3.0.0 + */ + this.height = height; + + /** + * The map's base width of a tile in pixels. Tiled maps support multiple tileset sizes + * within one map, but they are still placed at intervals of the base tile size. + * + * @name Phaser.Tilemaps.Tile#baseWidth + * @type {integer} + * @since 3.0.0 + */ + this.baseWidth = (baseWidth !== undefined) ? baseWidth : width; + + /** + * The map's base height of a tile in pixels. Tiled maps support multiple tileset sizes + * within one map, but they are still placed at intervals of the base tile size. + * + * @name Phaser.Tilemaps.Tile#baseHeight + * @type {integer} + * @since 3.0.0 + */ + this.baseHeight = (baseHeight !== undefined) ? baseHeight : height; + + /** + * The x coordinate of the top left of this tile in pixels. This is relative to the top left + * of the layer this tile is being rendered within. This property does NOT factor in camera + * scroll, layer scale or layer position. + * + * @name Phaser.Tilemaps.Tile#pixelX + * @type {number} + * @since 3.0.0 + */ + this.pixelX = 0; + + /** + * The y coordinate of the top left of this tile in pixels. This is relative to the top left + * of the layer this tile is being rendered within. This property does NOT factor in camera + * scroll, layer scale or layer position. + * + * @name Phaser.Tilemaps.Tile#pixelY + * @type {number} + * @since 3.0.0 + */ + this.pixelY = 0; + + this.updatePixelXY(); + + /** + * Tile specific properties. These usually come from Tiled. + * + * @name Phaser.Tilemaps.Tile#properties + * @type {any} + * @since 3.0.0 + */ + this.properties = {}; + + /** + * The rotation angle of this tile. + * + * @name Phaser.Tilemaps.Tile#rotation + * @type {number} + * @since 3.0.0 + */ + this.rotation = 0; + + /** + * Whether the tile should collide with any object on the left side. + * + * @name Phaser.Tilemaps.Tile#collideLeft + * @type {boolean} + * @since 3.0.0 + */ + this.collideLeft = false; + + /** + * Whether the tile should collide with any object on the right side. + * + * @name Phaser.Tilemaps.Tile#collideRight + * @type {boolean} + * @since 3.0.0 + */ + this.collideRight = false; + + /** + * Whether the tile should collide with any object on the top side. + * + * @name Phaser.Tilemaps.Tile#collideUp + * @type {boolean} + * @since 3.0.0 + */ + this.collideUp = false; + + /** + * Whether the tile should collide with any object on the bottom side. + * + * @name Phaser.Tilemaps.Tile#collideDown + * @type {boolean} + * @since 3.0.0 + */ + this.collideDown = false; + + /** + * Whether the tile's left edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceLeft + * @type {boolean} + * @since 3.0.0 + */ + this.faceLeft = false; + + /** + * Whether the tile's right edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceRight + * @type {boolean} + * @since 3.0.0 + */ + this.faceRight = false; + + /** + * Whether the tile's top edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceTop + * @type {boolean} + * @since 3.0.0 + */ + this.faceTop = false; + + /** + * Whether the tile's bottom edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceBottom + * @type {boolean} + * @since 3.0.0 + */ + this.faceBottom = false; + + /** + * Tile collision callback. + * + * @name Phaser.Tilemaps.Tile#collisionCallback + * @type {function} + * @since 3.0.0 + */ + this.collisionCallback = null; + + /** + * The context in which the collision callback will be called. + * + * @name Phaser.Tilemaps.Tile#collisionCallbackContext + * @type {object} + * @since 3.0.0 + */ + this.collisionCallbackContext = this; + + /** + * The tint to apply to this tile. Note: tint is currently a single color value instead of + * the 4 corner tint component on other GameObjects. + * + * @name Phaser.Tilemaps.Tile#tint + * @type {number} + * @default + * @since 3.0.0 + */ + this.tint = 0xffffff; + + /** + * An empty object where physics-engine specific information (e.g. bodies) may be stored. + * + * @name Phaser.Tilemaps.Tile#physics + * @type {object} + * @since 3.0.0 + */ + this.physics = {}; + }, + + /** + * Check if the given x and y world coordinates are within this Tile. This does not factor in + * camera scroll, layer scale or layer position. + * + * @method Phaser.Tilemaps.Tile#containsPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) + { + return !(x < this.pixelX || y < this.pixelY || x > this.right || y > this.bottom); + }, + + /** + * Copies the tile data & properties from the given tile to this tile. This copies everything + * except for position and interesting faces. + * + * @method Phaser.Tilemaps.Tile#copy + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The tile to copy from. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + copy: function (tile) + { + this.index = tile.index; + this.alpha = tile.alpha; + this.properties = tile.properties; + this.visible = tile.visible; + this.setFlip(tile.flipX, tile.flipY); + this.tint = tile.tint; + this.rotation = tile.rotation; + this.collideUp = tile.collideUp; + this.collideDown = tile.collideDown; + this.collideLeft = tile.collideLeft; + this.collideRight = tile.collideRight; + this.collisionCallback = tile.collisionCallback; + this.collisionCallbackContext = tile.collisionCallbackContext; + + return this; + }, + + /** + * The collision group for this Tile, defined within the Tileset. This returns a reference to + * the collision group stored within the Tileset, so any modification of the returned object + * will impact all tiles that have the same index as this tile. + * + * @method Phaser.Tilemaps.Tile#getCollisionGroup + * @since 3.0.0 + * + * @return {?object} tileset + */ + getCollisionGroup: function () + { + return this.tileset ? this.tileset.getTileCollisionGroup(this.index) : null; + }, + + /** + * The tile data for this Tile, defined within the Tileset. This typically contains Tiled + * collision data, tile animations and terrain information. This returns a reference to the tile + * data stored within the Tileset, so any modification of the returned object will impact all + * tiles that have the same index as this tile. + * + * @method Phaser.Tilemaps.Tile#getTileData + * @since 3.0.0 + * + * @return {?object} tileset + */ + getTileData: function () + { + return this.tileset ? this.tileset.getTileData(this.index) : null; + }, + + /** + * Gets the world X position of the left side of the tile, factoring in the layers position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getLeft + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getLeft: function (camera) + { + var tilemapLayer = this.tilemapLayer; + + return (tilemapLayer) ? tilemapLayer.tileToWorldX(this.x, camera) : this.x * this.baseWidth; + }, + + /** + * Gets the world X position of the right side of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getRight + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getRight: function (camera) + { + var tilemapLayer = this.tilemapLayer; + + return (tilemapLayer) ? this.getLeft(camera) + this.width * tilemapLayer.scaleX : this.getLeft(camera) + this.width; + }, + + /** + * Gets the world Y position of the top side of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getTop + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getTop: function (camera) + { + var tilemapLayer = this.tilemapLayer; + + // 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. + return tilemapLayer + ? tilemapLayer.tileToWorldY(this.y, camera) - (this.height - this.baseHeight) * tilemapLayer.scaleY + : this.y * this.baseHeight - (this.height - this.baseHeight); + }, + + /** + * Gets the world Y position of the bottom side of the tile, factoring in the layer's position, + * scale and scroll. + + * @method Phaser.Tilemaps.Tile#getBottom + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getBottom: function (camera) + { + var tilemapLayer = this.tilemapLayer; + return tilemapLayer + ? this.getTop(camera) + this.height * tilemapLayer.scaleY + : this.getTop(camera) + this.height; + }, + + + /** + * Gets the world rectangle bounding box for the tile, factoring in the layers position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getBounds + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * @param {object} [output] - [description] + * + * @return {(Phaser.Geom.Rectangle|object)} + */ + getBounds: function (camera, output) + { + if (output === undefined) { output = new Rectangle(); } + + output.x = this.getLeft(); + output.y = this.getTop(); + output.width = this.getRight() - output.x; + output.height = this.getBottom() - output.y; + + return output; + }, + + /** + * Gets the world X position of the center of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getCenterX + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getCenterX: function (camera) + { + return (this.getLeft(camera) + this.getRight(camera)) / 2; + }, + + /** + * Gets the world Y position of the center of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getCenterY + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getCenterY: function (camera) + { + return (this.getTop(camera) + this.getBottom(camera)) / 2; + }, + + /** + * Clean up memory. + * + * @method Phaser.Tilemaps.Tile#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.collisionCallback = undefined; + this.collisionCallbackContext = undefined; + this.properties = undefined; + }, + + /** + * Check for intersection with this tile. This does not factor in camera scroll, layer scale or + * layer position. + * + * @method Phaser.Tilemaps.Tile#intersects + * @since 3.0.0 + * + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + * + * @return {boolean} + */ + intersects: function (x, y, right, bottom) + { + return !( + right <= this.pixelX || bottom <= this.pixelY || + x >= this.right || y >= this.bottom + ); + }, + + /** + * Checks if the tile is interesting. + * + * @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. + */ + isInteresting: function (collides, faces) + { + if (collides && faces) { return (this.canCollide || this.hasInterestingFace); } + else if (collides) { return this.collides; } + else if (faces) { return this.hasInterestingFace; } + return false; + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tilemaps.Tile#resetCollision + * @since 3.0.0 + * + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate interesting faces for this tile and its neighbors. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + resetCollision: function (recalculateFaces) + { + if (recalculateFaces === undefined) { recalculateFaces = true; } + + this.collideLeft = false; + this.collideRight = false; + this.collideUp = false; + this.collideDown = false; + + this.faceTop = false; + this.faceBottom = false; + this.faceLeft = false; + this.faceRight = false; + + if (recalculateFaces) + { + var tilemapLayer = this.tilemapLayer; + + if (tilemapLayer) + { + this.tilemapLayer.calculateFacesAt(this.x, this.y); + } + } + + return this; + }, + + /** + * Reset faces. + * + * @method Phaser.Tilemaps.Tile#resetFaces + * @since 3.0.0 + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + resetFaces: function () + { + this.faceTop = false; + this.faceBottom = false; + this.faceLeft = false; + this.faceRight = false; + + return this; + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tilemaps.Tile#setCollision + * @since 3.0.0 + * + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} [right] - Indicating collide with any object on the right. + * @param {boolean} [up] - Indicating collide with any object on the top. + * @param {boolean} [down] - Indicating collide with any object on the bottom. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate interesting faces + * for this tile and its neighbors. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + setCollision: function (left, right, up, down, recalculateFaces) + { + if (right === undefined) { right = left; } + if (up === undefined) { up = left; } + if (down === undefined) { down = left; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + if (recalculateFaces) + { + var tilemapLayer = this.tilemapLayer; + + if (tilemapLayer) + { + this.tilemapLayer.calculateFacesAt(this.x, this.y); + } + } + + return this; + }, + + /** + * Set a callback to be called when this tile is hit by an object. The callback must true for + * collision processing to take place. + * + * @method Phaser.Tilemaps.Tile#setCollisionCallback + * @since 3.0.0 + * + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + setCollisionCallback: function (callback, context) + { + if (callback === null) + { + this.collisionCallback = undefined; + this.collisionCallbackContext = undefined; + } + else + { + this.collisionCallback = callback; + this.collisionCallbackContext = context; + } + + return this; + }, + + /** + * Sets the size of the tile and updates its pixelX and pixelY. + * + * @method Phaser.Tilemaps.Tile#setSize + * @since 3.0.0 + * + * @param {integer} tileWidth - The width of the tile in pixels. + * @param {integer} tileHeight - The height of the tile in pixels. + * @param {integer} baseWidth - The base width a tile in the map (in pixels). + * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + setSize: function (tileWidth, tileHeight, baseWidth, baseHeight) + { + if (tileWidth !== undefined) { this.width = tileWidth; } + if (tileHeight !== undefined) { this.height = tileHeight; } + if (baseWidth !== undefined) { this.baseWidth = baseWidth; } + if (baseHeight !== undefined) { this.baseHeight = baseHeight; } + + this.updatePixelXY(); + + return this; + }, + + /** + * 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 {Phaser.Tilemaps.Tile} This Tile object. + */ + updatePixelXY: function () + { + // 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. + this.pixelX = this.x * this.baseWidth; + this.pixelY = this.y * this.baseHeight; + + // this.pixelY = this.y * this.baseHeight - (this.height - this.baseHeight); + + return this; + }, + + /** + * True if this tile can collide on any of its faces or has a collision callback set. + * + * @name Phaser.Tilemaps.Tile#canCollide + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + canCollide: { + get: function () + { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + }, + + /** + * True if this tile can collide on any of its faces. + * + * @name Phaser.Tilemaps.Tile#collides + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + collides: { + get: function () + { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + }, + + /** + * True if this tile has any interesting faces. + * + * @name Phaser.Tilemaps.Tile#hasInterestingFace + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + hasInterestingFace: { + get: function () + { + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + }, + + /** + * The tileset that contains this Tile. This is null if accessed from a LayerData instance + * before the tile is placed in a StaticTilemapLayer or DynamicTilemapLayer, or if the tile has + * an index that doesn't correspond to any of the map's tilesets. + * + * @name Phaser.Tilemaps.Tile#tileset + * @type {?Phaser.Tilemaps.Tileset} + * @readonly + * @since 3.0.0 + */ + tileset: { + + get: function () + { + var tilemapLayer = this.layer.tilemapLayer; + + if (tilemapLayer) + { + var tileset = tilemapLayer.gidMap[this.index]; + + if (tileset) + { + return tileset; + } + } + + return null; + } + + }, + + /** + * The tilemap layer that contains this Tile. This will only return null if accessed from a + * LayerData instance before the tile is placed within a StaticTilemapLayer or + * DynamicTilemapLayer. + * + * @name Phaser.Tilemaps.Tile#tilemapLayer + * @type {?Phaser.Tilemaps.StaticTilemapLayer|Phaser.Tilemaps.DynamicTilemapLayer} + * @readonly + * @since 3.0.0 + */ + tilemapLayer: { + get: function () + { + return this.layer.tilemapLayer; + } + }, + + /** + * The tilemap that contains this Tile. This will only return null if accessed from a LayerData + * instance before the tile is placed within a StaticTilemapLayer or DynamicTilemapLayer. + * + * @name Phaser.Tilemaps.Tile#tilemap + * @type {?Phaser.Tilemaps.Tilemap} + * @readonly + * @since 3.0.0 + */ + tilemap: { + get: function () + { + var tilemapLayer = this.tilemapLayer; + return tilemapLayer ? tilemapLayer.tilemap : null; + } + } + +}); + +module.exports = Tile; + + +/***/ }), +/* 81 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the center x coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetCenterX + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The center x coordinate of the bounds of the Game Object. + */ +var GetCenterX = function (gameObject) +{ + return gameObject.x - (gameObject.width * gameObject.originX) + (gameObject.width * 0.5); +}; + +module.exports = GetCenterX; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetCenterX + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} x - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetCenterX = function (gameObject, x) +{ + var offsetX = gameObject.width * gameObject.originX; + + gameObject.x = (x + offsetX) - (gameObject.width * 0.5); + + return gameObject; +}; + +module.exports = SetCenterX; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the center y coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetCenterY + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The center y coordinate of the bounds of the Game Object. + */ +var GetCenterY = function (gameObject) +{ + return gameObject.y - (gameObject.height * gameObject.originY) + (gameObject.height * 0.5); +}; + +module.exports = GetCenterY; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetCenterY + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} y - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetCenterY = function (gameObject, y) +{ + var offsetY = gameObject.height * gameObject.originY; + + gameObject.y = (y + offsetY) - (gameObject.height * 0.5); + + return gameObject; +}; + +module.exports = SetCenterY; + + +/***/ }), +/* 85 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} index - The index of the item which should be spliced. + * + * @return {*} The item which was spliced (removed). + */ +var SpliceOne = function (array, index) +{ + if (index >= array.length) + { + return; + } + + var len = array.length - 1; + + var item = array[index]; + + for (var i = index; i < len; i++) + { + array[i] = array[i + 1]; + } + + array.length = len; + + return item; +}; + +module.exports = SpliceOne; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FromPoints = __webpack_require__(189); +var Rectangle = __webpack_require__(11); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Base Curve class, which all other curve types extend. + * + * 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. + */ +var Curve = new Class({ + + initialize: + + function Curve (type) + { + /** + * String based identifier for the type of curve. + * + * @name Phaser.Curves.Curve#type + * @type {string} + * @since 3.0.0 + */ + this.type = type; + + /** + * The default number of divisions within the curve. + * + * @name Phaser.Curves.Curve#defaultDivisions + * @type {integer} + * @default 5 + * @since 3.0.0 + */ + this.defaultDivisions = 5; + + /** + * The quantity of arc length divisions within the curve. + * + * @name Phaser.Curves.Curve#arcLengthDivisions + * @type {integer} + * @default 100 + * @since 3.0.0 + */ + this.arcLengthDivisions = 100; + + /** + * An array of cached arc length values. + * + * @name Phaser.Curves.Curve#cacheArcLengths + * @type {number[]} + * @default [] + * @since 3.0.0 + */ + this.cacheArcLengths = []; + + /** + * Does the data of this curve need updating? + * + * @name Phaser.Curves.Curve#needsUpdate + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.needsUpdate = true; + + /** + * For a curve on a Path, `false` means the Path will ignore this curve. + * + * @name Phaser.Curves.Curve#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * A temporary calculation Vector. + * + * @name Phaser.Curves.Curve#_tmpVec2A + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2A = new Vector2(); + + /** + * A temporary calculation Vector. + * + * @name Phaser.Curves.Curve#_tmpVec2B + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2B = new Vector2(); + }, + + /** + * Draws this curve on the given Graphics object. + * + * The curve is drawn using `Graphics.strokePoints` so will be drawn at whatever the present Graphics stroke color is. + * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. + * + * @method Phaser.Curves.Curve#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn. + * @param {integer} [pointsTotal=32] - The resolution of the curve. The higher the value the smoother it will render, at the cost of rendering performance. + * + * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn. + */ + draw: function (graphics, pointsTotal) + { + if (pointsTotal === undefined) { pointsTotal = 32; } + + // So you can chain graphics calls + return graphics.strokePoints(this.getPoints(pointsTotal)); + }, + + /** + * Returns a Rectangle where the position and dimensions match the bounds of this Curve. + * + * You can control the accuracy of the bounds. The value given is used to work out how many points + * to plot across the curve. Higher values are more accurate at the cost of calculation speed. + * + * @method Phaser.Curves.Curve#getBounds + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the bounds in. If falsey a new object will be created. + * @param {integer} [accuracy=16] - The accuracy of the bounds calculations. + * + * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object. + */ + getBounds: function (out, accuracy) + { + if (!out) { out = new Rectangle(); } + if (accuracy === undefined) { accuracy = 16; } + + var len = this.getLength(); + + if (accuracy > len) + { + accuracy = len / 2; + } + + // The length of the curve in pixels + // So we'll have 1 spaced point per 'accuracy' pixels + + var spaced = Math.max(1, Math.round(len / accuracy)); + + return FromPoints(this.getSpacedPoints(spaced), out); + }, + + /** + * Returns an array of points, spaced out X distance pixels apart. + * The smaller the distance, the larger the array will be. + * + * @method Phaser.Curves.Curve#getDistancePoints + * @since 3.0.0 + * + * @param {integer} distance - The distance, in pixels, between each point along the curve. + * + * @return {Phaser.Geom.Point[]} An Array of Point objects. + */ + getDistancePoints: function (distance) + { + var len = this.getLength(); + + var spaced = Math.max(1, len / distance); + + return this.getSpacedPoints(spaced); + }, + + /** + * Get a point at the end of the curve. + * + * @method Phaser.Curves.Curve#getEndPoint + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} [out] - Optional Vector object to store the result in. + * + * @return {Phaser.Math.Vector2} Vector2 containing the coordinates of the curves end point. + */ + getEndPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPointAt(1, out); + }, + + /** + * Get total curve arc length + * + * @method Phaser.Curves.Curve#getLength + * @since 3.0.0 + * + * @return {number} The total length of the curve. + */ + getLength: function () + { + var lengths = this.getLengths(); + + return lengths[lengths.length - 1]; + }, + + + /** + * Get a list of cumulative segment lengths. + * + * These lengths are + * + * - [0] 0 + * - [1] The first segment + * - [2] The first and second segment + * - ... + * - [divisions] All segments + * + * @method Phaser.Curves.Curve#getLengths + * @since 3.0.0 + * + * @param {integer} [divisions] - The number of divisions or segments. + * + * @return {number[]} An array of cumulative lengths. + */ + getLengths: function (divisions) + { + if (divisions === undefined) { divisions = this.arcLengthDivisions; } + + if ((this.cacheArcLengths.length === divisions + 1) && !this.needsUpdate) + { + return this.cacheArcLengths; + } + + this.needsUpdate = false; + + var cache = []; + var current; + var last = this.getPoint(0, this._tmpVec2A); + var sum = 0; + + cache.push(0); + + for (var p = 1; p <= divisions; p++) + { + current = this.getPoint(p / divisions, this._tmpVec2B); + + sum += current.distance(last); + + cache.push(sum); + + last.copy(current); + } + + this.cacheArcLengths = cache; + + return cache; // { sums: cache, sum:sum }; Sum is in the last element. + }, + + // Get point at relative position in curve according to arc length + + // - u [0 .. 1] + + /** + * Get a point at a relative position on the curve, by arc length. + * + * @method Phaser.Curves.Curve#getPointAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The relative position, [0..1]. + * @param {Phaser.Math.Vector2} [out] - A point to store the result in. + * + * @return {Phaser.Math.Vector2} The point. + */ + getPointAt: function (u, out) + { + var t = this.getUtoTmapping(u); + + return this.getPoint(t, out); + }, + + // Get sequence of points using getPoint( t ) + + /** + * Get a sequence of evenly spaced points from the curve. + * + * You can pass `divisions`, `stepRate`, or neither. + * + * The number of divisions will be + * + * 1. `divisions`, if `divisions` > 0; or + * 2. `this.getLength / stepRate`, if `stepRate` > 0; or + * 3. `this.defaultDivisions` + * + * `1 + divisions` points will be returned. + * + * @method Phaser.Curves.Curve#getPoints + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2[]} O - [out,$return] + * + * @param {integer} [divisions] - The number of divisions to make. + * @param {number} [stepRate] - The curve distance between points, implying `divisions`. + * @param {(array|Phaser.Math.Vector2[])} [out] - An optional array to store the points in. + * + * @return {(array|Phaser.Math.Vector2[])} An array of Points from the curve. + */ + getPoints: function (divisions, stepRate, out) + { + if (out === undefined) { out = []; } + + // If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!divisions) + { + if (!stepRate) + { + divisions = this.defaultDivisions; + } + else + { + divisions = this.getLength() / stepRate; + } + } + + for (var d = 0; d <= divisions; d++) + { + out.push(this.getPoint(d / divisions)); + } + + return out; + }, + + /** + * Get a random point from the curve. + * + * @method Phaser.Curves.Curve#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A point object to store the result in. + * + * @return {Phaser.Math.Vector2} The point. + */ + getRandomPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPoint(Math.random(), out); + }, + + // Get sequence of points using getPointAt( u ) + + /** + * Get a sequence of equally spaced points (by arc distance) from the curve. + * + * `1 + divisions` points will be returned. + * + * @method Phaser.Curves.Curve#getSpacedPoints + * @since 3.0.0 + * + * @param {integer} [divisions=this.defaultDivisions] - The number of divisions to make. + * @param {number} [stepRate] - Step between points. Used to calculate the number of points to return when divisions is falsy. Ignored if divisions is positive. + * @param {(array|Phaser.Math.Vector2[])} [out] - An optional array to store the points in. + * + * @return {Phaser.Math.Vector2[]} An array of points. + */ + getSpacedPoints: function (divisions, stepRate, out) + { + if (out === undefined) { out = []; } + + // If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!divisions) + { + if (!stepRate) + { + divisions = this.defaultDivisions; + } + else + { + divisions = this.getLength() / stepRate; + } + } + + for (var d = 0; d <= divisions; d++) + { + var t = this.getUtoTmapping(d / divisions, null, divisions); + + out.push(this.getPoint(t)); + } + + return out; + }, + + /** + * Get a point at the start of the curve. + * + * @method Phaser.Curves.Curve#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A point to store the result in. + * + * @return {Phaser.Math.Vector2} The point. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPointAt(0, out); + }, + + /** + * Get a unit vector tangent at a relative position on the curve. + * In case any sub curve does not implement its tangent derivation, + * 2 points a small delta apart will be used to find its gradient + * which seems to give a reasonable approximation + * + * @method Phaser.Curves.Curve#getTangent + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The relative position on the curve, [0..1]. + * @param {Phaser.Math.Vector2} [out] - A vector to store the result in. + * + * @return {Phaser.Math.Vector2} Vector approximating the tangent line at the point t (delta +/- 0.0001) + */ + getTangent: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; + + // Capping in case of danger + + if (t1 < 0) + { + t1 = 0; + } + + if (t2 > 1) + { + t2 = 1; + } + + this.getPoint(t1, this._tmpVec2A); + this.getPoint(t2, out); + + return out.subtract(this._tmpVec2A).normalize(); + }, + + /** + * Get a unit vector tangent at a relative position on the curve, by arc length. + * + * @method Phaser.Curves.Curve#getTangentAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The relative position on the curve, [0..1]. + * @param {Phaser.Math.Vector2} [out] - A vector to store the result in. + * + * @return {Phaser.Math.Vector2} The tangent vector. + */ + getTangentAt: function (u, out) + { + var t = this.getUtoTmapping(u); + + return this.getTangent(t, out); + }, + + // Given a distance in pixels, get a t to find p. + /** + * [description] + * + * @method Phaser.Curves.Curve#getTFromDistance + * @since 3.0.0 + * + * @param {integer} distance - [description] + * @param {integer} [divisions] - [description] + * + * @return {number} [description] + */ + getTFromDistance: function (distance, divisions) + { + if (distance <= 0) + { + return 0; + } + + return this.getUtoTmapping(0, distance, divisions); + }, + + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + + /** + * [description] + * + * @method Phaser.Curves.Curve#getUtoTmapping + * @since 3.0.0 + * + * @param {number} u - [description] + * @param {integer} distance - [description] + * @param {integer} [divisions] - [description] + * + * @return {number} [description] + */ + getUtoTmapping: function (u, distance, divisions) + { + var arcLengths = this.getLengths(divisions); + + var i = 0; + var il = arcLengths.length; + + var targetArcLength; // The targeted u distance value to get + + if (distance) + { + // Cannot overshoot the curve + targetArcLength = Math.min(distance, arcLengths[il - 1]); + } + else + { + targetArcLength = u * arcLengths[il - 1]; + } + + // binary search for the index with largest value smaller than target u distance + + var low = 0; + var high = il - 1; + var comparison; + + while (low <= high) + { + i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + + comparison = arcLengths[i] - targetArcLength; + + if (comparison < 0) + { + low = i + 1; + } + else if (comparison > 0) + { + high = i - 1; + } + else + { + high = i; + break; + } + } + + i = high; + + if (arcLengths[i] === targetArcLength) + { + return i / (il - 1); + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + var lengthBefore = arcLengths[i]; + var lengthAfter = arcLengths[i + 1]; + + var segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + + // add that fractional amount to t + + return (i + segmentFraction) / (il - 1); + }, + + /** + * Calculate and cache the arc lengths. + * + * @method Phaser.Curves.Curve#updateArcLengths + * @since 3.0.0 + * + * @see Phaser.Curves.Curve#getLengths() + */ + updateArcLengths: function () + { + this.needsUpdate = true; + + this.getLengths(); + } + +}); + +module.exports = Curve; + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Loader.Events + */ + +module.exports = { + + ADD: __webpack_require__(893), + COMPLETE: __webpack_require__(894), + FILE_COMPLETE: __webpack_require__(895), + FILE_KEY_COMPLETE: __webpack_require__(896), + FILE_LOAD_ERROR: __webpack_require__(897), + FILE_LOAD: __webpack_require__(898), + FILE_PROGRESS: __webpack_require__(899), + POST_PROCESS: __webpack_require__(900), + PROGRESS: __webpack_require__(901), + START: __webpack_require__(902) + +}; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(73); + +/** + * Creates a new Object using all values from obj1 and obj2. + * If a value exists in both obj1 and obj2, the value in obj1 is used. + * + * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this + * function on shallow objects. + * + * @function Phaser.Utils.Objects.Merge + * @since 3.0.0 + * + * @param {object} obj1 - The first object. + * @param {object} obj2 - The second object. + * + * @return {object} A new object containing the union of obj1's and obj2's properties. + */ +var Merge = function (obj1, obj2) +{ + var clone = Clone(obj1); + + for (var key in obj2) + { + if (!clone.hasOwnProperty(key)) + { + clone[key] = obj2[key]; + } + } + + return clone; +}; + +module.exports = Merge; + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var ImageRender = __webpack_require__(1000); + +/** + * @classdesc + * An Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class Image + * @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.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Image = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + ImageRender + ], + + initialize: + + function Image (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Image'); + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Image#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + } + +}); + +module.exports = Image; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var EaseMap = __webpack_require__(179); +var UppercaseFirst = __webpack_require__(194); + +/** + * This internal function is used to return the correct ease function for a Tween. + * + * It can take a variety of input, including an EaseMap based string, or a custom function. + * + * @function Phaser.Tweens.Builders.GetEaseFunction + * @since 3.0.0 + * + * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. + * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * + * @return {function} The ease function. + */ +var GetEaseFunction = function (ease, easeParams) +{ + // Default ease function + var easeFunction = EaseMap.Power0; + + // Prepare ease function + if (typeof ease === 'string') + { + // String based look-up + + // 1) They specified it correctly + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + else + { + // Do some string manipulation to try and find it + var direction = ''; + + if (ease.indexOf('.')) + { + // quad.in = Quad.easeIn + // quad.out = Quad.easeOut + // quad.inout =Quad.easeInOut + + direction = ease.substr(ease.indexOf('.') + 1); + + if (direction.toLowerCase() === 'in') + { + direction = 'easeIn'; + } + else if (direction.toLowerCase() === 'out') + { + direction = 'easeOut'; + } + else if (direction.toLowerCase() === 'inout') + { + direction = 'easeInOut'; + } + } + + ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); + + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + } + } + else if (typeof ease === 'function') + { + // Custom function + easeFunction = ease; + } + else if (Array.isArray(ease) && ease.length === 4) + { + // Bezier function (TODO) + } + + // No custom ease parameters? + if (!easeParams) + { + // Return ease function + return easeFunction; + } + + var cloneParams = easeParams.slice(0); + + cloneParams.unshift(0); + + // Return ease function with custom ease parameters + return function (v) + { + cloneParams[0] = v; + + return easeFunction.apply(this, cloneParams); + }; +}; + +module.exports = GetEaseFunction; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determine whether the source object has a property with the specified key. + * + * @function Phaser.Utils.Objects.HasValue + * @since 3.0.0 + * + * @param {object} source - The source object to be checked. + * @param {string} key - The property to check for within the object + * + * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. + */ +var HasValue = function (source, key) +{ + return (source.hasOwnProperty(key)); +}; + +module.exports = HasValue; + + +/***/ }), +/* 92 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// http://www.blackpawn.com/texts/pointinpoly/ + +/** + * Checks if a point (as a pair of coordinates) is inside a Triangle's bounds. + * + * @function Phaser.Geom.Triangle.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check. + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is inside the Triangle, otherwise `false`. + */ +var Contains = function (triangle, x, y) +{ + var v0x = triangle.x3 - triangle.x1; + var v0y = triangle.y3 - triangle.y1; + + var v1x = triangle.x2 - triangle.x1; + var v1y = triangle.y2 - triangle.y1; + + var v2x = x - triangle.x1; + var v2y = y - triangle.y1; + + var dot00 = (v0x * v0x) + (v0y * v0y); + var dot01 = (v0x * v1x) + (v0y * v1y); + var dot02 = (v0x * v2x) + (v0y * v2y); + var dot11 = (v1x * v1x) + (v1y * v1y); + var dot12 = (v1x * v2x) + (v1y * v2y); + + // Compute barycentric coordinates + var b = ((dot00 * dot11) - (dot01 * dot01)); + var inv = (b === 0) ? 0 : (1 / b); + var u = ((dot11 * dot02) - (dot01 * dot12)) * inv; + var v = ((dot00 * dot12) - (dot01 * dot02)) * inv; + + return (u >= 0 && v >= 0 && (u + v < 1)); +}; + +module.exports = Contains; + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +// This is based off an explanation and expanded math presented by Paul Bourke: +// See http:'local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ + +/** + * Checks if two Lines intersect. If the Lines are identical, they will be treated as parallel and thus non-intersecting. + * + * @function Phaser.Geom.Intersects.LineToLine + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line1 - The first Line to check. + * @param {Phaser.Geom.Line} line2 - The second Line to check. + * @param {Phaser.Geom.Point} [out] - A Point in which to optionally store the point of intersection. + * + * @return {boolean} `true` if the two Lines intersect, and the `out` object will be populated, if given. Otherwise, `false`. + */ +var LineToLine = function (line1, line2, out) +{ + if (out === undefined) { out = new Point(); } + + var x1 = line1.x1; + var y1 = line1.y1; + var x2 = line1.x2; + var y2 = line1.y2; + + var x3 = line2.x1; + var y3 = line2.y1; + var x4 = line2.x2; + var y4 = line2.y2; + + var numA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); + var numB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); + var deNom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + + // 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). + + if (deNom === 0) + { + return false; + } + + // Calculate the intermediate fractional point that the lines potentially intersect. + + var uA = numA / deNom; + var uB = numB / deNom; + + // 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 (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) + { + out.x = x1 + (uA * (x2 - x1)); + out.y = y1 + (uA * (y2 - y1)); + + return true; + } + + return false; +}; + +module.exports = LineToLine; + + +/***/ }), +/* 94 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the angle of the line in radians. + * + * @function Phaser.Geom.Line.Angle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the angle of. + * + * @return {number} The angle of the line, in radians. + */ +var Angle = function (line) +{ + return Math.atan2(line.y2 - line.y1, line.x2 - line.x1); +}; + +module.exports = Angle; + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies. +* +* @class Sleeping +*/ + +var Sleeping = {}; + +module.exports = Sleeping; + +var Events = __webpack_require__(96); + +(function() { + + Sleeping._motionWakeThreshold = 0.18; + Sleeping._motionSleepThreshold = 0.08; + Sleeping._minBias = 0.9; + + /** + * Puts bodies to sleep or wakes them up depending on their motion. + * @method update + * @param {body[]} bodies + * @param {number} timeScale + */ + Sleeping.update = function(bodies, timeScale) { + var timeFactor = timeScale * timeScale * timeScale; + + // update bodies sleeping status + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + motion = body.speed * body.speed + body.angularSpeed * body.angularSpeed; + + // wake up bodies if they have a force applied + if (body.force.x !== 0 || body.force.y !== 0) { + Sleeping.set(body, false); + continue; + } + + var minMotion = Math.min(body.motion, motion), + maxMotion = Math.max(body.motion, motion); + + // biased average motion estimation between frames + body.motion = Sleeping._minBias * minMotion + (1 - Sleeping._minBias) * maxMotion; + + if (body.sleepThreshold > 0 && body.motion < Sleeping._motionSleepThreshold * timeFactor) { + body.sleepCounter += 1; + + if (body.sleepCounter >= body.sleepThreshold) + Sleeping.set(body, true); + } else if (body.sleepCounter > 0) { + body.sleepCounter -= 1; + } + } + }; + + /** + * Given a set of colliding pairs, wakes the sleeping bodies involved. + * @method afterCollisions + * @param {pair[]} pairs + * @param {number} timeScale + */ + Sleeping.afterCollisions = function(pairs, timeScale) { + var timeFactor = timeScale * timeScale * timeScale; + + // wake up bodies involved in collisions + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + + // don't wake inactive pairs + if (!pair.isActive) + continue; + + var collision = pair.collision, + bodyA = collision.bodyA.parent, + bodyB = collision.bodyB.parent; + + // don't wake if at least one body is static + if ((bodyA.isSleeping && bodyB.isSleeping) || bodyA.isStatic || bodyB.isStatic) + continue; + + if (bodyA.isSleeping || bodyB.isSleeping) { + var sleepingBody = (bodyA.isSleeping && !bodyA.isStatic) ? bodyA : bodyB, + movingBody = sleepingBody === bodyA ? bodyB : bodyA; + + if (!sleepingBody.isStatic && movingBody.motion > Sleeping._motionWakeThreshold * timeFactor) { + Sleeping.set(sleepingBody, false); + } + } + } + }; + + /** + * Set a body as sleeping or awake. + * @method set + * @param {body} body + * @param {boolean} isSleeping + */ + Sleeping.set = function(body, isSleeping) { + var wasSleeping = body.isSleeping; + + if (isSleeping) { + body.isSleeping = true; + body.sleepCounter = body.sleepThreshold; + + body.positionImpulse.x = 0; + body.positionImpulse.y = 0; + + body.positionPrev.x = body.position.x; + body.positionPrev.y = body.position.y; + + body.anglePrev = body.angle; + body.speed = 0; + body.angularSpeed = 0; + body.motion = 0; + + if (!wasSleeping) { + Events.trigger(body, 'sleepStart'); + } + } else { + body.isSleeping = false; + body.sleepCounter = 0; + + if (wasSleeping) { + Events.trigger(body, 'sleepEnd'); + } + } + }; + +})(); + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Events = {}; + +module.exports = Events; + +var Common = __webpack_require__(19); + +(function() { + + /** + * Subscribes a callback function to the given object's `eventName`. + * @method on + * @param {} object + * @param {string} eventNames + * @param {function} callback + */ + Events.on = function(object, eventNames, callback) { + var names = eventNames.split(' '), + name; + + for (var i = 0; i < names.length; i++) { + name = names[i]; + object.events = object.events || {}; + object.events[name] = object.events[name] || []; + object.events[name].push(callback); + } + + return callback; + }; + + /** + * Removes the given event callback. If no callback, clears all callbacks in `eventNames`. If no `eventNames`, clears all events. + * @method off + * @param {} object + * @param {string} eventNames + * @param {function} callback + */ + Events.off = function(object, eventNames, callback) { + if (!eventNames) { + object.events = {}; + return; + } + + // handle Events.off(object, callback) + if (typeof eventNames === 'function') { + callback = eventNames; + eventNames = Common.keys(object.events).join(' '); + } + + var names = eventNames.split(' '); + + for (var i = 0; i < names.length; i++) { + var callbacks = object.events[names[i]], + newCallbacks = []; + + if (callback && callbacks) { + for (var j = 0; j < callbacks.length; j++) { + if (callbacks[j] !== callback) + newCallbacks.push(callbacks[j]); + } + } + + object.events[names[i]] = newCallbacks; + } + }; + + /** + * Fires all the callbacks subscribed to the given object's `eventName`, in the order they subscribed, if any. + * @method trigger + * @param {} object + * @param {string} eventNames + * @param {} event + */ + Events.trigger = function(object, eventNames, event) { + var names, + name, + callbacks, + eventClone; + + var events = object.events; + + if (events && Common.keys(events).length > 0) { + if (!event) + event = {}; + + names = eventNames.split(' '); + + for (var i = 0; i < names.length; i++) { + name = names[i]; + callbacks = events[name]; + + if (callbacks) { + eventClone = Common.clone(event, false); + eventClone.name = name; + eventClone.source = object; + + for (var j = 0; j < callbacks.length; j++) { + callbacks[j].apply(object, [eventClone]); + } + } + } + } + }; + +})(); + + +/***/ }), +/* 97 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = { + + /** + * A constant representing a top-left alignment or position. + * @constant + * @name Phaser.Display.Align.TOP_LEFT + * @since 3.0.0 + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant + * @name Phaser.Display.Align.TOP_CENTER + * @since 3.0.0 + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant + * @name Phaser.Display.Align.TOP_RIGHT + * @since 3.0.0 + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant + * @name Phaser.Display.Align.LEFT_TOP + * @since 3.0.0 + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant + * @name Phaser.Display.Align.LEFT_CENTER + * @since 3.0.0 + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant + * @name Phaser.Display.Align.LEFT_BOTTOM + * @since 3.0.0 + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant + * @name Phaser.Display.Align.CENTER + * @since 3.0.0 + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant + * @name Phaser.Display.Align.RIGHT_TOP + * @since 3.0.0 + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant + * @name Phaser.Display.Align.RIGHT_CENTER + * @since 3.0.0 + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant + * @name Phaser.Display.Align.RIGHT_BOTTOM + * @since 3.0.0 + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant + * @name Phaser.Display.Align.BOTTOM_LEFT + * @since 3.0.0 + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant + * @name Phaser.Display.Align.BOTTOM_CENTER + * @since 3.0.0 + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant + * @name Phaser.Display.Align.BOTTOM_RIGHT + * @since 3.0.0 + * @type {integer} + */ + BOTTOM_RIGHT: 12 + +}; + +module.exports = ALIGN_CONST; + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); + +/** + * Return 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 between 0 and 1 representing the percentage. + * @param {number} min - The minimum value. + * @param {number} [max] - The maximum value. + * + * @return {number} The value that is `percent` percent between `min` and `max`. + */ +var FromPercent = function (percent, min, max) +{ + percent = Clamp(percent, 0, 1); + + return (max - min) * percent; +}; + +module.exports = FromPercent; + + +/***/ }), +/* 99 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Retrieves the value of the given key from an object. + * + * @function Phaser.Tweens.Builders.GetBoolean + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @param {string} key - The key to look for in the `source` object. + * @param {*} defaultValue - The default value to return if the `key` doesn't exist or if no `source` object is provided. + * + * @return {*} The retrieved value. + */ +var GetBoolean = function (source, key, defaultValue) +{ + if (!source) + { + return defaultValue; + } + else if (source.hasOwnProperty(key)) + { + return source[key]; + } + else + { + return defaultValue; + } +}; + +module.exports = GetBoolean; + + +/***/ }), +/* 100 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TWEEN_CONST = { + + /** + * TweenData state. + * + * @name Phaser.Tweens.CREATED + * @type {integer} + * @since 3.0.0 + */ + CREATED: 0, + + /** + * TweenData state. + * + * @name Phaser.Tweens.INIT + * @type {integer} + * @since 3.0.0 + */ + INIT: 1, + + /** + * TweenData state. + * + * @name Phaser.Tweens.DELAY + * @type {integer} + * @since 3.0.0 + */ + DELAY: 2, + + /** + * TweenData state. + * + * @name Phaser.Tweens.OFFSET_DELAY + * @type {integer} + * @since 3.0.0 + */ + OFFSET_DELAY: 3, + + /** + * TweenData state. + * + * @name Phaser.Tweens.PENDING_RENDER + * @type {integer} + * @since 3.0.0 + */ + PENDING_RENDER: 4, + + /** + * TweenData state. + * + * @name Phaser.Tweens.PLAYING_FORWARD + * @type {integer} + * @since 3.0.0 + */ + PLAYING_FORWARD: 5, + + /** + * TweenData state. + * + * @name Phaser.Tweens.PLAYING_BACKWARD + * @type {integer} + * @since 3.0.0 + */ + PLAYING_BACKWARD: 6, + + /** + * TweenData state. + * + * @name Phaser.Tweens.HOLD_DELAY + * @type {integer} + * @since 3.0.0 + */ + HOLD_DELAY: 7, + + /** + * TweenData state. + * + * @name Phaser.Tweens.REPEAT_DELAY + * @type {integer} + * @since 3.0.0 + */ + REPEAT_DELAY: 8, + + /** + * TweenData state. + * + * @name Phaser.Tweens.COMPLETE + * @type {integer} + * @since 3.0.0 + */ + COMPLETE: 9, + + // Tween specific (starts from 20 to cleanly allow extra TweenData consts in the future) + + /** + * Tween state. + * + * @name Phaser.Tweens.PENDING_ADD + * @type {integer} + * @since 3.0.0 + */ + PENDING_ADD: 20, + + /** + * Tween state. + * + * @name Phaser.Tweens.PAUSED + * @type {integer} + * @since 3.0.0 + */ + PAUSED: 21, + + /** + * Tween state. + * + * @name Phaser.Tweens.LOOP_DELAY + * @type {integer} + * @since 3.0.0 + */ + LOOP_DELAY: 22, + + /** + * Tween state. + * + * @name Phaser.Tweens.ACTIVE + * @type {integer} + * @since 3.0.0 + */ + ACTIVE: 23, + + /** + * Tween state. + * + * @name Phaser.Tweens.COMPLETE_DELAY + * @type {integer} + * @since 3.0.0 + */ + COMPLETE_DELAY: 24, + + /** + * Tween state. + * + * @name Phaser.Tweens.PENDING_REMOVE + * @type {integer} + * @since 3.0.0 + */ + PENDING_REMOVE: 25, + + /** + * Tween state. + * + * @name Phaser.Tweens.REMOVED + * @type {integer} + * @since 3.0.0 + */ + REMOVED: 26 + +}; + +module.exports = TWEEN_CONST; + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Events = __webpack_require__(303); + +/** + * @callback DataEachCallback + * + * @param {*} parent - The parent object of the DataManager. + * @param {string} key - The key of the value. + * @param {*} value - The value. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the game object, key, and data. + */ + +/** + * @classdesc + * The Data Manager Component features a means to store pieces of data specific to a Game Object, System or Plugin. + * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, + * or have a property called `events` that is an instance of it. + * + * @class DataManager + * @memberof Phaser.Data + * @constructor + * @since 3.0.0 + * + * @param {object} parent - The object that this DataManager belongs to. + * @param {Phaser.Events.EventEmitter} eventEmitter - The DataManager's event emitter. + */ +var DataManager = new Class({ + + initialize: + + function DataManager (parent, eventEmitter) + { + /** + * The object that this DataManager belongs to. + * + * @name Phaser.Data.DataManager#parent + * @type {*} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * The DataManager's event emitter. + * + * @name Phaser.Data.DataManager#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = eventEmitter; + + if (!eventEmitter) + { + this.events = (parent.events) ? parent.events : parent; + } + + /** + * The data list. + * + * @name Phaser.Data.DataManager#list + * @type {Object.} + * @default {} + * @since 3.0.0 + */ + this.list = {}; + + /** + * The public values list. You can use this to access anything you have stored + * in this Data Manager. For example, if you set a value called `gold` you can + * access it via: + * + * ```javascript + * this.data.values.gold; + * ``` + * + * You can also modify it directly: + * + * ```javascript + * this.data.values.gold += 1000; + * ``` + * + * Doing so will emit a `setdata` event from the parent of this Data Manager. + * + * Do not modify this object directly. Adding properties directly to this object will not + * emit any events. Always use `DataManager.set` to create new items the first time around. + * + * @name Phaser.Data.DataManager#values + * @type {Object.} + * @default {} + * @since 3.10.0 + */ + this.values = {}; + + /** + * Whether setting data is frozen for this DataManager. + * + * @name Phaser.Data.DataManager#_frozen + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._frozen = false; + + if (!parent.hasOwnProperty('sys') && this.events) + { + this.events.once('destroy', this.destroy, this); + } + }, + + /** + * Retrieves the value for the given key, or undefined if it doesn't exist. + * + * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: + * + * ```javascript + * this.data.get('gold'); + * ``` + * + * Or access the value directly: + * + * ```javascript + * this.data.values.gold; + * ``` + * + * You can also pass in an array of keys, in which case an array of values will be returned: + * + * ```javascript + * this.data.get([ 'gold', 'armor', 'health' ]); + * ``` + * + * This approach is useful for destructuring arrays in ES6. + * + * @method Phaser.Data.DataManager#get + * @since 3.0.0 + * + * @param {(string|string[])} key - The key of the value to retrieve, or an array of keys. + * + * @return {*} The value belonging to the given key, or an array of values, the order of which will match the input array. + */ + get: function (key) + { + var list = this.list; + + if (Array.isArray(key)) + { + var output = []; + + for (var i = 0; i < key.length; i++) + { + output.push(list[key[i]]); + } + + return output; + } + else + { + return list[key]; + } + }, + + /** + * Retrieves all data values in a new object. + * + * @method Phaser.Data.DataManager#getAll + * @since 3.0.0 + * + * @return {Object.} All data values. + */ + getAll: function () + { + var results = {}; + + for (var key in this.list) + { + if (this.list.hasOwnProperty(key)) + { + results[key] = this.list[key]; + } + } + + return results; + }, + + /** + * Queries the DataManager for the values of keys matching the given regular expression. + * + * @method Phaser.Data.DataManager#query + * @since 3.0.0 + * + * @param {RegExp} search - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). + * + * @return {Object.} The values of the keys matching the search string. + */ + query: function (search) + { + var results = {}; + + for (var key in this.list) + { + if (this.list.hasOwnProperty(key) && key.match(search)) + { + results[key] = this.list[key]; + } + } + + return results; + }, + + /** + * Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created. + * + * ```javascript + * data.set('name', 'Red Gem Stone'); + * ``` + * + * You can also pass in an object of key value pairs as the first argument: + * + * ```javascript + * data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); + * ``` + * + * To get a value back again you can call `get`: + * + * ```javascript + * data.get('gold'); + * ``` + * + * Or you can access the value directly via the `values` property, where it works like any other variable: + * + * ```javascript + * data.values.gold += 50; + * ``` + * + * When the value is first set, a `setdata` event is emitted. + * + * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. + * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. + * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. + * + * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * + * @method Phaser.Data.DataManager#set + * @fires Phaser.Data.Events#SET_DATA + * @fires Phaser.Data.Events#CHANGE_DATA + * @fires Phaser.Data.Events#CHANGE_DATA_KEY + * @since 3.0.0 + * + * @param {(string|object)} key - The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored. + * @param {*} data - The value to set for the given key. If an object is provided as the key this argument is ignored. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + set: function (key, data) + { + if (this._frozen) + { + return this; + } + + if (typeof key === 'string') + { + return this.setValue(key, data); + } + else + { + for (var entry in key) + { + this.setValue(entry, key[entry]); + } + } + + return this; + }, + + /** + * Internal value setter, called automatically by the `set` method. + * + * @method Phaser.Data.DataManager#setValue + * @fires Phaser.Data.Events#SET_DATA + * @fires Phaser.Data.Events#CHANGE_DATA + * @fires Phaser.Data.Events#CHANGE_DATA_KEY + * @private + * @since 3.10.0 + * + * @param {string} key - The key to set the value for. + * @param {*} data - The value to set. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + setValue: function (key, data) + { + if (this._frozen) + { + return this; + } + + if (this.has(key)) + { + // Hit the key getter, which will in turn emit the events. + this.values[key] = data; + } + else + { + var _this = this; + var list = this.list; + var events = this.events; + var parent = this.parent; + + Object.defineProperty(this.values, key, { + + enumerable: true, + + configurable: true, + + get: function () + { + return list[key]; + }, + + set: function (value) + { + if (!_this._frozen) + { + var previousValue = list[key]; + list[key] = value; + + events.emit(Events.CHANGE_DATA, parent, key, value, previousValue); + events.emit(Events.CHANGE_DATA_KEY + key, parent, value, previousValue); + } + } + + }); + + list[key] = data; + + events.emit(Events.SET_DATA, parent, key, data); + } + + return this; + }, + + /** + * Passes all data entries to the given callback. + * + * @method Phaser.Data.DataManager#each + * @since 3.0.0 + * + * @param {DataEachCallback} callback - The function to call. + * @param {*} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the game object, key, and data. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + each: function (callback, context) + { + var args = [ this.parent, null, undefined ]; + + for (var i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var key in this.list) + { + args[1] = key; + args[2] = this.list[key]; + + callback.apply(context, args); + } + + return this; + }, + + /** + * Merge the given object of key value pairs into this DataManager. + * + * Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument) + * will emit a `changedata` event. + * + * @method Phaser.Data.DataManager#merge + * @fires Phaser.Data.Events#SET_DATA + * @fires Phaser.Data.Events#CHANGE_DATA + * @fires Phaser.Data.Events#CHANGE_DATA_KEY + * @since 3.0.0 + * + * @param {Object.} data - The data to merge. + * @param {boolean} [overwrite=true] - Whether to overwrite existing data. Defaults to true. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + merge: function (data, overwrite) + { + if (overwrite === undefined) { overwrite = true; } + + // Merge data from another component into this one + for (var key in data) + { + if (data.hasOwnProperty(key) && (overwrite || (!overwrite && !this.has(key)))) + { + this.setValue(key, data[key]); + } + } + + return this; + }, + + /** + * Remove the value for the given key. + * + * If the key is found in this Data Manager it is removed from the internal lists and a + * `removedata` event is emitted. + * + * You can also pass in an array of keys, in which case all keys in the array will be removed: + * + * ```javascript + * this.data.remove([ 'gold', 'armor', 'health' ]); + * ``` + * + * @method Phaser.Data.DataManager#remove + * @fires Phaser.Data.Events#REMOVE_DATA + * @since 3.0.0 + * + * @param {(string|string[])} key - The key to remove, or an array of keys to remove. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + remove: function (key) + { + if (this._frozen) + { + return this; + } + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + this.removeValue(key[i]); + } + } + else + { + return this.removeValue(key); + } + + return this; + }, + + /** + * Internal value remover, called automatically by the `remove` method. + * + * @method Phaser.Data.DataManager#removeValue + * @private + * @fires Phaser.Data.Events#REMOVE_DATA + * @since 3.10.0 + * + * @param {string} key - The key to set the value for. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + removeValue: function (key) + { + if (this.has(key)) + { + var data = this.list[key]; + + delete this.list[key]; + delete this.values[key]; + + this.events.emit(Events.REMOVE_DATA, this.parent, key, data); + } + + return this; + }, + + /** + * Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it. + * + * @method Phaser.Data.DataManager#pop + * @fires Phaser.Data.Events#REMOVE_DATA + * @since 3.0.0 + * + * @param {string} key - The key of the value to retrieve and delete. + * + * @return {*} The value of the given key. + */ + pop: function (key) + { + var data = undefined; + + if (!this._frozen && this.has(key)) + { + data = this.list[key]; + + delete this.list[key]; + delete this.values[key]; + + this.events.emit(Events.REMOVE_DATA, this.parent, key, data); + } + + return data; + }, + + /** + * Determines whether the given key is set in this Data Manager. + * + * Please note that the keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * + * @method Phaser.Data.DataManager#has + * @since 3.0.0 + * + * @param {string} key - The key to check. + * + * @return {boolean} Returns `true` if the key exists, otherwise `false`. + */ + has: function (key) + { + return this.list.hasOwnProperty(key); + }, + + /** + * Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts + * to create new values or update existing ones. + * + * @method Phaser.Data.DataManager#setFreeze + * @since 3.0.0 + * + * @param {boolean} value - Whether to freeze or unfreeze the Data Manager. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + setFreeze: function (value) + { + this._frozen = value; + + return this; + }, + + /** + * Delete all data in this Data Manager and unfreeze it. + * + * @method Phaser.Data.DataManager#reset + * @since 3.0.0 + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + reset: function () + { + for (var key in this.list) + { + delete this.list[key]; + delete this.values[key]; + } + + this._frozen = false; + + return this; + }, + + /** + * Destroy this data manager. + * + * @method Phaser.Data.DataManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.reset(); + + this.events.off(Events.CHANGE_DATA); + this.events.off(Events.SET_DATA); + this.events.off(Events.REMOVE_DATA); + + this.parent = null; + }, + + /** + * Gets or sets the frozen state of this Data Manager. + * A frozen Data Manager will block all attempts to create new values or update existing ones. + * + * @name Phaser.Data.DataManager#freeze + * @type {boolean} + * @since 3.0.0 + */ + freeze: { + + get: function () + { + return this._frozen; + }, + + set: function (value) + { + this._frozen = (value) ? true : false; + } + + }, + + /** + * Return the total number of entries in this Data Manager. + * + * @name Phaser.Data.DataManager#count + * @type {integer} + * @since 3.0.0 + */ + count: { + + get: function () + { + var i = 0; + + for (var key in this.list) + { + if (this.list[key] !== undefined) + { + i++; + } + } + + return i; + } + + } + +}); + +module.exports = DataManager; + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Events + */ + +module.exports = { + + DESTROY: __webpack_require__(608), + VIDEO_COMPLETE: __webpack_require__(609), + VIDEO_CREATED: __webpack_require__(610), + VIDEO_ERROR: __webpack_require__(611), + VIDEO_LOOP: __webpack_require__(612), + VIDEO_PLAY: __webpack_require__(613), + VIDEO_SEEKED: __webpack_require__(614), + VIDEO_SEEKING: __webpack_require__(615), + VIDEO_STOP: __webpack_require__(616), + VIDEO_TIMEOUT: __webpack_require__(617), + VIDEO_UNLOCKED: __webpack_require__(618) + +}; + + +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var DegToRad = __webpack_require__(40); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(55); +var Rectangle = __webpack_require__(11); +var TransformMatrix = __webpack_require__(35); +var ValueToColor = __webpack_require__(174); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Base Camera class. + * + * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, + * and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. + * + * The Base Camera is extended by the Camera class, which adds in special effects including Fade, + * Flash and Camera Shake, as well as the ability to follow Game Objects. + * + * The Base Camera was introduced in Phaser 3.12. It was split off from the Camera class, to allow + * you to isolate special effects as needed. Therefore the 'since' values for properties of this class relate + * to when they were added to the Camera class. + * + * @class BaseCamera + * @memberof Phaser.Cameras.Scene2D + * @constructor + * @since 3.12.0 + * + * @extends Phaser.Events.EventEmitter + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.Visible + * + * @param {number} x - The x position of the Camera, relative to the top-left of the game canvas. + * @param {number} y - The y position of the Camera, relative to the top-left of the game canvas. + * @param {number} width - The width of the Camera, in pixels. + * @param {number} height - The height of the Camera, in pixels. + */ +var BaseCamera = new Class({ + + Extends: EventEmitter, + + Mixins: [ + Components.Alpha, + Components.Visible + ], + + initialize: + + function BaseCamera (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + + EventEmitter.call(this); + + /** + * A reference to the Scene this camera belongs to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene; + + /** + * A reference to the Game Scene Manager. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#sceneManager + * @type {Phaser.Scenes.SceneManager} + * @since 3.12.0 + */ + this.sceneManager; + + /** + * A reference to the Game Scale Manager. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scaleManager + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.0 + */ + this.scaleManager; + + /** + * A reference to the Scene's Camera Manager to which this Camera belongs. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#cameraManager + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.17.0 + */ + this.cameraManager; + + /** + * The Camera ID. Assigned by the Camera Manager and used to handle camera exclusion. + * This value is a bitmask. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#id + * @type {integer} + * @readonly + * @since 3.11.0 + */ + this.id = 0; + + /** + * The name of the Camera. This is left empty for your own use. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * This property is un-used in v3.16. + * + * The resolution of the Game, used in most Camera calculations. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#resolution + * @type {number} + * @readonly + * @deprecated + * @since 3.12.0 + */ + this.resolution = 1; + + /** + * Should this camera round its pixel values to integers? + * + * @name Phaser.Cameras.Scene2D.BaseCamera#roundPixels + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.roundPixels = false; + + /** + * Is this Camera visible or not? + * + * A visible camera will render and perform input tests. + * An invisible camera will not render anything and will skip input tests. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#visible + * @type {boolean} + * @default true + * @since 3.10.0 + */ + + /** + * Is this Camera using a bounds to restrict scrolling movement? + * + * Set this property along with the bounds via `Camera.setBounds`. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#useBounds + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.useBounds = false; + + /** + * The World View is a Rectangle that defines the area of the 'world' the Camera is currently looking at. + * This factors in the Camera viewport size, zoom and scroll position and is updated in the Camera preRender step. + * If you have enabled Camera bounds the worldview will be clamped to those bounds accordingly. + * You can use it for culling or intersection checks. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#worldView + * @type {Phaser.Geom.Rectangle} + * @readonly + * @since 3.11.0 + */ + this.worldView = new Rectangle(); + + /** + * Is this Camera dirty? + * + * A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. + * + * This flag is cleared during the `postRenderCamera` method of the renderer. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#dirty + * @type {boolean} + * @default true + * @since 3.11.0 + */ + this.dirty = true; + + /** + * The x position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollX` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#x + * @type {number} + * @private + * @since 3.0.0 + */ + this._x = x; + + /** + * The y position of the Camera, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollY` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#y + * @type {number} + * @private + * @since 3.0.0 + */ + this._y = y; + + /** + * Internal Camera X value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_cx + * @type {number} + * @private + * @since 3.12.0 + */ + this._cx = 0; + + /** + * Internal Camera Y value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_cy + * @type {number} + * @private + * @since 3.12.0 + */ + this._cy = 0; + + /** + * Internal Camera Width value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_cw + * @type {number} + * @private + * @since 3.12.0 + */ + this._cw = 0; + + /** + * Internal Camera Height value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_ch + * @type {number} + * @private + * @since 3.12.0 + */ + this._ch = 0; + + /** + * The width of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_width + * @type {number} + * @private + * @since 3.11.0 + */ + this._width = width; + + /** + * The height of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_height + * @type {number} + * @private + * @since 3.11.0 + */ + this._height = height; + + /** + * The bounds the camera is restrained to during scrolling. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_bounds + * @type {Phaser.Geom.Rectangle} + * @private + * @since 3.0.0 + */ + this._bounds = new Rectangle(); + + /** + * The horizontal scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_scrollX + * @type {number} + * @private + * @default 0 + * @since 3.11.0 + */ + this._scrollX = 0; + + /** + * The vertical scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_scrollY + * @type {number} + * @private + * @default 0 + * @since 3.11.0 + */ + this._scrollY = 0; + + /** + * The Camera zoom value. Change this value to zoom in, or out of, a Scene. + * + * A value of 0.5 would zoom the Camera out, so you can now see twice as much + * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel + * now takes up 2 pixels when rendered. + * + * Set to 1 to return to the default zoom level. + * + * Be careful to never set this value to zero. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_zoom + * @type {number} + * @private + * @default 1 + * @since 3.11.0 + */ + this._zoom = 1; + + /** + * 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 + */ + this._rotation = 0; + + /** + * A local transform matrix used for internal calculations. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#matrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.0.0 + */ + this.matrix = new TransformMatrix(); + + /** + * Does this Camera have a transparent background? + * + * @name Phaser.Cameras.Scene2D.BaseCamera#transparent + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.transparent = true; + + /** + * The background color of this Camera. Only used if `transparent` is `false`. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#backgroundColor + * @type {Phaser.Display.Color} + * @since 3.0.0 + */ + this.backgroundColor = ValueToColor('rgba(0,0,0,0)'); + + /** + * The Camera alpha value. Setting this property impacts every single object that this Camera + * renders. You can either set the property directly, i.e. via a Tween, to fade a Camera in or out, + * or via the chainable `setAlpha` method instead. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#alpha + * @type {number} + * @default 1 + * @since 3.11.0 + */ + + /** + * Should the camera cull Game Objects before checking them for input hit tests? + * In some special cases it may be beneficial to disable this. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#disableCull + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.disableCull = false; + + /** + * A temporary array of culled objects. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#culledObjects + * @type {Phaser.GameObjects.GameObject[]} + * @default [] + * @private + * @since 3.0.0 + */ + this.culledObjects = []; + + /** + * The mid-point of the Camera in 'world' coordinates. + * + * Use it to obtain exactly where in the world the center of the camera is currently looking. + * + * This value is updated in the preRender method, after the scroll values and follower + * have been processed. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#midPoint + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.11.0 + */ + this.midPoint = new Vector2(width / 2, height / 2); + + /** + * The horizontal origin of rotation for this Camera. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * See `setOrigin` to set both origins in a single, chainable call. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#originX + * @type {number} + * @default 0.5 + * @since 3.11.0 + */ + this.originX = 0.5; + + /** + * The vertical origin of rotation for this Camera. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * See `setOrigin` to set both origins in a single, chainable call. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#originY + * @type {number} + * @default 0.5 + * @since 3.11.0 + */ + this.originY = 0.5; + + /** + * Does this Camera have a custom viewport? + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_customViewport + * @type {boolean} + * @private + * @default false + * @since 3.12.0 + */ + this._customViewport = false; + + /** + * The Mask this Camera is using during render. + * Set the mask using the `setMask` method. Remove the mask using the `clearMask` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#mask + * @type {?(Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask)} + * @since 3.17.0 + */ + this.mask = null; + + /** + * The Camera that this Camera uses for translation during masking. + * + * If the mask is fixed in position this will be a reference to + * the CameraManager.default instance. Otherwise, it'll be a reference + * to itself. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_maskCamera + * @type {?Phaser.Cameras.Scene2D.BaseCamera} + * @private + * @since 3.17.0 + */ + this._maskCamera = null; + }, + + /** + * Set the Alpha level of this Camera. The alpha controls the opacity of the Camera as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setAlpha + * @since 3.11.0 + * + * @param {number} [value=1] - The Camera alpha value. + * + * @return {this} This Camera instance. + */ + + /** + * Sets the rotation origin of this Camera. + * + * The values are given in the range 0 to 1 and are only used when calculating Camera rotation. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setOrigin + * @since 3.11.0 + * + * @param {number} [x=0.5] - The horizontal origin value. + * @param {number} [y=x] - The vertical origin value. If not defined it will be set to the value of `x`. + * + * @return {this} This Camera instance. + */ + setOrigin: function (x, y) + { + if (x === undefined) { x = 0.5; } + if (y === undefined) { y = x; } + + this.originX = x; + this.originY = y; + + return this; + }, + + /** + * 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. + */ + getScroll: function (x, y, out) + { + if (out === undefined) { out = new Vector2(); } + + var originX = this.width * 0.5; + var originY = this.height * 0.5; + + out.x = x - originX; + out.y = y - originY; + + if (this.useBounds) + { + out.x = this.clampX(out.x); + out.y = this.clampY(out.y); + } + + return out; + }, + + /** + * Moves the Camera horizontally so that it is centered on the given x coordinate, bounds allowing. + * Calling this does not change the scrollY value. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerOnX + * @since 3.16.0 + * + * @param {number} x - The horizontal coordinate to center on. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerOnX: function (x) + { + var originX = this.width * 0.5; + + this.midPoint.x = x; + + this.scrollX = x - originX; + + if (this.useBounds) + { + this.scrollX = this.clampX(this.scrollX); + } + + return this; + }, + + /** + * Moves the Camera vertically so that it is centered on the given y coordinate, bounds allowing. + * Calling this does not change the scrollX value. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerOnY + * @since 3.16.0 + * + * @param {number} y - The vertical coordinate to center on. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerOnY: function (y) + { + var originY = this.height * 0.5; + + this.midPoint.y = y; + + this.scrollY = y - originY; + + if (this.useBounds) + { + this.scrollY = this.clampY(this.scrollY); + } + + return this; + }, + + /** + * Moves the Camera so that it is centered on the given coordinates, bounds allowing. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerOn + * @since 3.11.0 + * + * @param {number} x - The horizontal coordinate to center on. + * @param {number} y - The vertical coordinate to center on. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerOn: function (x, y) + { + this.centerOnX(x); + this.centerOnY(y); + + return this; + }, + + /** + * Moves the Camera so that it is looking at the center of the Camera Bounds, if enabled. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerToBounds + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerToBounds: function () + { + if (this.useBounds) + { + var bounds = this._bounds; + var originX = this.width * 0.5; + var originY = this.height * 0.5; + + this.midPoint.set(bounds.centerX, bounds.centerY); + + this.scrollX = bounds.centerX - originX; + this.scrollY = bounds.centerY - originY; + } + + return this; + }, + + /** + * 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 {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerToSize: function () + { + this.scrollX = this.width * 0.5; + this.scrollY = this.height * 0.5; + + return this; + }, + + /** + * Takes an array of Game Objects and returns a new array featuring only those objects + * visible by this camera. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#cull + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [renderableObjects,$return] + * + * @param {Phaser.GameObjects.GameObject[]} renderableObjects - An array of Game Objects to cull. + * + * @return {Phaser.GameObjects.GameObject[]} An array of Game Objects visible to this Camera. + */ + cull: function (renderableObjects) + { + if (this.disableCull) + { + return renderableObjects; + } + + var cameraMatrix = this.matrix.matrix; + + var mva = cameraMatrix[0]; + var mvb = cameraMatrix[1]; + var mvc = cameraMatrix[2]; + var mvd = cameraMatrix[3]; + + /* First Invert Matrix */ + var determinant = (mva * mvd) - (mvb * mvc); + + if (!determinant) + { + return renderableObjects; + } + + var mve = cameraMatrix[4]; + var mvf = cameraMatrix[5]; + + var scrollX = this.scrollX; + var scrollY = this.scrollY; + var cameraW = this.width; + var cameraH = this.height; + var culledObjects = this.culledObjects; + var length = renderableObjects.length; + + determinant = 1 / determinant; + + culledObjects.length = 0; + + for (var index = 0; index < length; ++index) + { + var object = renderableObjects[index]; + + if (!object.hasOwnProperty('width') || object.parentContainer) + { + culledObjects.push(object); + continue; + } + + var objectW = object.width; + var objectH = object.height; + var objectX = (object.x - (scrollX * object.scrollFactorX)) - (objectW * object.originX); + var objectY = (object.y - (scrollY * object.scrollFactorY)) - (objectH * object.originY); + var tx = (objectX * mva + objectY * mvc + mve); + var ty = (objectX * mvb + objectY * mvd + mvf); + var tw = ((objectX + objectW) * mva + (objectY + objectH) * mvc + mve); + var th = ((objectX + objectW) * mvb + (objectY + objectH) * mvd + mvf); + var cullTop = this.y; + var cullBottom = cullTop + cameraH; + var cullLeft = this.x; + var cullRight = cullLeft + cameraW; + + if ((tw > cullLeft && tx < cullRight) && (th > cullTop && ty < cullBottom)) + { + culledObjects.push(object); + } + } + + return culledObjects; + }, + + /** + * 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. + */ + getWorldPoint: function (x, y, output) + { + if (output === undefined) { output = new Vector2(); } + + var cameraMatrix = this.matrix.matrix; + + var mva = cameraMatrix[0]; + var mvb = cameraMatrix[1]; + var mvc = cameraMatrix[2]; + var mvd = cameraMatrix[3]; + var mve = cameraMatrix[4]; + var mvf = cameraMatrix[5]; + + // Invert Matrix + var determinant = (mva * mvd) - (mvb * mvc); + + if (!determinant) + { + output.x = x; + output.y = y; + + return output; + } + + determinant = 1 / determinant; + + var ima = mvd * determinant; + var imb = -mvb * determinant; + var imc = -mvc * determinant; + var imd = mva * determinant; + var ime = (mvc * mvf - mvd * mve) * determinant; + var imf = (mvb * mve - mva * mvf) * determinant; + + var c = Math.cos(this.rotation); + var s = Math.sin(this.rotation); + + var zoom = this.zoom; + var res = this.resolution; + + var scrollX = this.scrollX; + var scrollY = this.scrollY; + + // Works for zoom of 1 with any resolution, but resolution > 1 and zoom !== 1 breaks + var sx = x + ((scrollX * c - scrollY * s) * zoom); + var sy = y + ((scrollX * s + scrollY * c) * zoom); + + // Apply transform to point + output.x = (sx * ima + sy * imc) * res + ime; + output.y = (sx * imb + sy * imd) * res + imf; + + return output; + }, + + /** + * Given a Game Object, or an array of Game Objects, it will update all of their camera filter settings + * so that they are ignored by this Camera. This means they will not be rendered by this Camera. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#ignore + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group)} entries - The Game Object, or array of Game Objects, to be ignored by this Camera. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + ignore: function (entries) + { + var id = this.id; + + if (!Array.isArray(entries)) + { + entries = [ entries ]; + } + + for (var i = 0; i < entries.length; i++) + { + var entry = entries[i]; + + if (Array.isArray(entry)) + { + this.ignore(entry); + } + else if (entry.isParent) + { + this.ignore(entry.getChildren()); + } + else + { + entry.cameraFilter |= id; + } + } + + return this; + }, + + /** + * Internal preRender step. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#preRender + * @protected + * @since 3.0.0 + * + * @param {number} resolution - The game resolution, as set in the Scale Manager. + */ + preRender: function (resolution) + { + var width = this.width; + var height = this.height; + + var halfWidth = width * 0.5; + var halfHeight = height * 0.5; + + var zoom = this.zoom * resolution; + var matrix = this.matrix; + + var originX = width * this.originX; + var originY = height * this.originY; + + var sx = this.scrollX; + var sy = this.scrollY; + + if (this.useBounds) + { + sx = this.clampX(sx); + sy = this.clampY(sy); + } + + if (this.roundPixels) + { + originX = Math.round(originX); + originY = Math.round(originY); + } + + // Values are in pixels and not impacted by zooming the Camera + this.scrollX = sx; + this.scrollY = sy; + + var midX = sx + halfWidth; + var midY = sy + halfHeight; + + // 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 + this.midPoint.set(midX, midY); + + var displayWidth = width / zoom; + var displayHeight = height / zoom; + + this.worldView.setTo( + midX - (displayWidth / 2), + midY - (displayHeight / 2), + displayWidth, + displayHeight + ); + + matrix.applyITRS(this.x + originX, this.y + originY, this.rotation, zoom, zoom); + matrix.translate(-originX, -originY); + }, + + /** + * Takes an x value and checks it's within the range of the Camera bounds, adjusting if required. + * Do not call this method if you are not using camera bounds. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#clampX + * @since 3.11.0 + * + * @param {number} x - The value to horizontally scroll clamp. + * + * @return {number} The adjusted value to use as scrollX. + */ + clampX: function (x) + { + var bounds = this._bounds; + + var dw = this.displayWidth; + + var bx = bounds.x + ((dw - this.width) / 2); + var bw = Math.max(bx, bx + bounds.width - dw); + + if (x < bx) + { + x = bx; + } + else if (x > bw) + { + x = bw; + } + + return x; + }, + + /** + * Takes a y value and checks it's within the range of the Camera bounds, adjusting if required. + * Do not call this method if you are not using camera bounds. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#clampY + * @since 3.11.0 + * + * @param {number} y - The value to vertically scroll clamp. + * + * @return {number} The adjusted value to use as scrollY. + */ + clampY: function (y) + { + var bounds = this._bounds; + + var dh = this.displayHeight; + + var by = bounds.y + ((dh - this.height) / 2); + var bh = Math.max(by, by + bounds.height - dh); + + if (y < by) + { + y = by; + } + else if (y > bh) + { + y = bh; + } + + return y; + }, + + /* + var gap = this._zoomInversed; + return gap * Math.round((src.x - this.scrollX * src.scrollFactorX) / gap); + */ + + /** + * If this Camera has previously had movement bounds set on it, this will remove them. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#removeBounds + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + removeBounds: function () + { + this.useBounds = false; + + this.dirty = true; + + this._bounds.setEmpty(); + + return this; + }, + + /** + * Set the rotation of this Camera. This causes everything it renders to appear rotated. + * + * Rotating a camera does not rotate the viewport itself, it is applied during rendering. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setAngle + * @since 3.0.0 + * + * @param {number} [value=0] - The cameras angle of rotation, given in degrees. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setAngle: function (value) + { + if (value === undefined) { value = 0; } + + this.rotation = DegToRad(value); + + return this; + }, + + /** + * Sets the background color for this Camera. + * + * By default a Camera has a transparent background but it can be given a solid color, with any level + * of transparency, via this method. + * + * The color value can be specified using CSS color notation, hex or numbers. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setBackgroundColor + * @since 3.0.0 + * + * @param {(string|number|Phaser.Types.Display.InputColorObject)} [color='rgba(0,0,0,0)'] - The color value. In CSS, hex or numeric color notation. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setBackgroundColor: function (color) + { + if (color === undefined) { color = 'rgba(0,0,0,0)'; } + + this.backgroundColor = ValueToColor(color); + + this.transparent = (this.backgroundColor.alpha === 0); + + return this; + }, + + /** + * Set the bounds of the Camera. The bounds are an axis-aligned rectangle. + * + * The Camera bounds controls where the Camera can scroll to, stopping it from scrolling off the + * edges and into blank space. It does not limit the placement of Game Objects, or where + * the Camera viewport can be positioned. + * + * Temporarily disable the bounds by changing the boolean `Camera.useBounds`. + * + * Clear the bounds entirely by calling `Camera.removeBounds`. + * + * If you set bounds that are smaller than the viewport it will stop the Camera from being + * able to scroll. The bounds can be positioned where-ever you wish. By default they are from + * 0x0 to the canvas width x height. This means that the coordinate 0x0 is the top left of + * the Camera bounds. However, you can position them anywhere. So if you wanted a game world + * that was 2048x2048 in size, with 0x0 being the center of it, you can set the bounds x/y + * to be -1024, -1024, with a width and height of 2048. Depending on your game you may find + * it easier for 0x0 to be the top-left of the bounds, or you may wish 0x0 to be the middle. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setBounds + * @since 3.0.0 + * + * @param {integer} x - The top-left x coordinate of the bounds. + * @param {integer} y - The top-left y coordinate of the bounds. + * @param {integer} width - The width of the bounds, in pixels. + * @param {integer} height - The height of the bounds, in pixels. + * @param {boolean} [centerOn=false] - If `true` the Camera will automatically be centered on the new bounds. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setBounds: function (x, y, width, height, centerOn) + { + if (centerOn === undefined) { centerOn = false; } + + this._bounds.setTo(x, y, width, height); + + this.dirty = true; + this.useBounds = true; + + if (centerOn) + { + this.centerToBounds(); + } + else + { + this.scrollX = this.clampX(this.scrollX); + this.scrollY = this.clampY(this.scrollY); + } + + return this; + }, + + /** + * Returns a rectangle containing the bounds of the Camera. + * + * If the Camera does not have any bounds the rectangle will be empty. + * + * The rectangle is a copy of the bounds, so is safe to modify. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#getBounds + * @since 3.16.0 + * + * @param {Phaser.Geom.Rectangle} [out] - An optional Rectangle to store the bounds in. If not given, a new Rectangle will be created. + * + * @return {Phaser.Geom.Rectangle} A rectangle containing the bounds of this Camera. + */ + getBounds: function (out) + { + if (out === undefined) { out = new Rectangle(); } + + var source = this._bounds; + + out.setTo(source.x, source.y, source.width, source.height); + + return out; + }, + + /** + * Sets the name of this Camera. + * This value is for your own use and isn't used internally. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setName + * @since 3.0.0 + * + * @param {string} [value=''] - The name of the Camera. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setName: function (value) + { + if (value === undefined) { value = ''; } + + this.name = value; + + return this; + }, + + /** + * Set the position of the Camera viewport within the game. + * + * This does not change where the camera is 'looking'. See `setScroll` to control that. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setPosition + * @since 3.0.0 + * + * @param {number} x - The top-left x coordinate of the Camera viewport. + * @param {number} [y=x] - The top-left y coordinate of the Camera viewport. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Set the rotation of this Camera. This causes everything it renders to appear rotated. + * + * Rotating a camera does not rotate the viewport itself, it is applied during rendering. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setRotation + * @since 3.0.0 + * + * @param {number} [value=0] - The rotation of the Camera, in radians. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setRotation: function (value) + { + if (value === undefined) { value = 0; } + + this.rotation = value; + + return this; + }, + + /** + * Should the Camera round pixel values to whole integers when rendering Game Objects? + * + * In some types of game, especially with pixel art, this is required to prevent sub-pixel aliasing. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setRoundPixels + * @since 3.0.0 + * + * @param {boolean} value - `true` to round Camera pixels, `false` to not. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setRoundPixels: function (value) + { + this.roundPixels = value; + + return this; + }, + + /** + * Sets the Scene the Camera is bound to. + * + * Also populates the `resolution` property and updates the internal size values. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setScene + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene the camera is bound to. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setScene: function (scene) + { + if (this.scene && this._customViewport) + { + this.sceneManager.customViewports--; + } + + this.scene = scene; + + var sys = scene.sys; + + this.sceneManager = sys.game.scene; + this.scaleManager = sys.scale; + this.cameraManager = sys.cameras; + + var res = this.scaleManager.resolution; + + this.resolution = res; + + this._cx = this._x * res; + this._cy = this._y * res; + this._cw = this._width * res; + this._ch = this._height * res; + + this.updateSystem(); + + return this; + }, + + /** + * Set the position of where the Camera is looking within the game. + * You can also modify the properties `Camera.scrollX` and `Camera.scrollY` directly. + * Use this method, or the scroll properties, to move your camera around the game world. + * + * This does not change where the camera viewport is placed. See `setPosition` to control that. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setScroll + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the Camera in the game world. + * @param {number} [y=x] - The y coordinate of the Camera in the game world. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setScroll: function (x, y) + { + if (y === undefined) { y = x; } + + this.scrollX = x; + this.scrollY = y; + + return this; + }, + + /** + * Set the size of the Camera viewport. + * + * By default a Camera is the same size as the game, but can be made smaller via this method, + * allowing you to create mini-cam style effects by creating and positioning a smaller Camera + * viewport within your game. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setSize + * @since 3.0.0 + * + * @param {integer} width - The width of the Camera viewport. + * @param {integer} [height=width] - The height of the Camera viewport. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + this.width = width; + this.height = height; + + return this; + }, + + /** + * This method sets the position and size of the Camera viewport in a single call. + * + * If you're trying to change where the Camera is looking at in your game, then see + * the method `Camera.setScroll` instead. This method is for changing the viewport + * itself, not what the camera can see. + * + * By default a Camera is the same size as the game, but can be made smaller via this method, + * allowing you to create mini-cam style effects by creating and positioning a smaller Camera + * viewport within your game. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setViewport + * @since 3.0.0 + * + * @param {number} x - The top-left x coordinate of the Camera viewport. + * @param {number} y - The top-left y coordinate of the Camera viewport. + * @param {integer} width - The width of the Camera viewport. + * @param {integer} [height=width] - The height of the Camera viewport. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setViewport: function (x, y, width, height) + { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + }, + + /** + * Set the zoom value of the Camera. + * + * Changing to a smaller value, such as 0.5, will cause the camera to 'zoom out'. + * Changing to a larger value, such as 2, will cause the camera to 'zoom in'. + * + * A value of 1 means 'no zoom' and is the default. + * + * Changing the zoom does not impact the Camera viewport in any way, it is only applied during rendering. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setZoom + * @since 3.0.0 + * + * @param {number} [value=1] - The zoom value of the Camera. The minimum it can be is 0.001. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setZoom: function (value) + { + if (value === undefined) { value = 1; } + + if (value === 0) + { + value = 0.001; + } + + this.zoom = value; + + return this; + }, + + /** + * Sets the mask to be applied to this Camera during rendering. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * + * Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Camera it will be immediately replaced. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * + * Note: You cannot mask a Camera that has `renderToTexture` set. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setMask + * @since 3.17.0 + * + * @param {(Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask)} mask - The mask this Camera will use when rendering. + * @param {boolean} [fixedPosition=true] - Should the mask translate along with the Camera, or be fixed in place and not impacted by the Cameras transform? + * + * @return {this} This Camera instance. + */ + setMask: function (mask, fixedPosition) + { + if (fixedPosition === undefined) { fixedPosition = true; } + + this.mask = mask; + + this._maskCamera = (fixedPosition) ? this.cameraManager.default : this; + + return this; + }, + + /** + * Clears the mask that this Camera was using. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#clearMask + * @since 3.17.0 + * + * @param {boolean} [destroyMask=false] - Destroy the mask before clearing it? + * + * @return {this} This Camera instance. + */ + clearMask: function (destroyMask) + { + if (destroyMask === undefined) { destroyMask = false; } + + if (destroyMask && this.mask) + { + this.mask.destroy(); + } + + this.mask = null; + + return this; + }, + + /** + * Sets the visibility of this Camera. + * + * An invisible Camera will skip rendering and input tests of everything it can see. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setVisible + * @since 3.10.0 + * + * @param {boolean} value - The visible state of the Camera. + * + * @return {this} This Camera instance. + */ + + /** + * Returns an Object suitable for JSON storage containing all of the Camera viewport and rendering properties. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Cameras.Scene2D.JSONCamera} A well-formed object suitable for conversion to JSON. + */ + toJSON: function () + { + var output = { + name: this.name, + x: this.x, + y: this.y, + width: this.width, + height: this.height, + zoom: this.zoom, + rotation: this.rotation, + roundPixels: this.roundPixels, + scrollX: this.scrollX, + scrollY: this.scrollY, + backgroundColor: this.backgroundColor.rgba + }; + + if (this.useBounds) + { + output['bounds'] = { + x: this._bounds.x, + y: this._bounds.y, + width: this._bounds.width, + height: this._bounds.height + }; + } + + return output; + }, + + /** + * Internal method called automatically by the Camera Manager. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#update + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + update: function () + { + // NOOP + }, + + /** + * Internal method called automatically when the viewport changes. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#updateSystem + * @private + * @since 3.12.0 + */ + updateSystem: function () + { + if (!this.scaleManager) + { + return; + } + + var custom = (this._x !== 0 || this._y !== 0 || this.scaleManager.width !== this._width || this.scaleManager.height !== this._height); + + var sceneManager = this.sceneManager; + + if (custom && !this._customViewport) + { + // We need a custom viewport for this Camera + sceneManager.customViewports++; + } + else if (!custom && this._customViewport) + { + // We're turning off a custom viewport for this Camera + sceneManager.customViewports--; + } + + this.dirty = true; + this._customViewport = custom; + }, + + /** + * Destroys this Camera instance and its internal properties and references. + * Once destroyed you cannot use this Camera again, even if re-added to a Camera Manager. + * + * This method is called automatically by `CameraManager.remove` if that methods `runDestroy` argument is `true`, which is the default. + * + * Unless you have a specific reason otherwise, always use `CameraManager.remove` and allow it to handle the camera destruction, + * rather than calling this method directly. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#destroy + * @fires Phaser.Cameras.Scene2D.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + this.emit(Events.DESTROY, this); + + this.removeAllListeners(); + + this.matrix.destroy(); + + this.culledObjects = []; + + if (this._customViewport) + { + // We're turning off a custom viewport for this Camera + this.sceneManager.customViewports--; + } + + this._bounds = null; + + this.scene = null; + this.scaleManager = null; + this.sceneManager = null; + this.cameraManager = null; + }, + + /** + * The x position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollX` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this._x; + }, + + set: function (value) + { + this._x = value; + this._cx = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The y position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollY` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this._y; + }, + + set: function (value) + { + this._y = value; + this._cy = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The width of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#width + * @type {number} + * @since 3.0.0 + */ + width: { + + get: function () + { + return this._width; + }, + + set: function (value) + { + this._width = value; + this._cw = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The height of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#height + * @type {number} + * @since 3.0.0 + */ + height: { + + get: function () + { + return this._height; + }, + + set: function (value) + { + this._height = value; + this._ch = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The horizontal scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scrollX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + scrollX: { + + get: function () + { + return this._scrollX; + }, + + set: function (value) + { + this._scrollX = value; + this.dirty = true; + } + + }, + + /** + * The vertical scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scrollY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + scrollY: { + + get: function () + { + return this._scrollY; + }, + + set: function (value) + { + this._scrollY = value; + this.dirty = true; + } + + }, + + /** + * The Camera zoom value. Change this value to zoom in, or out of, a Scene. + * + * A value of 0.5 would zoom the Camera out, so you can now see twice as much + * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel + * now takes up 2 pixels when rendered. + * + * Set to 1 to return to the default zoom level. + * + * Be careful to never set this value to zero. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#zoom + * @type {number} + * @default 1 + * @since 3.0.0 + */ + zoom: { + + get: function () + { + return this._zoom; + }, + + set: function (value) + { + this._zoom = value; + this.dirty = true; + } + + }, + + /** + * 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 + */ + rotation: { + + get: function () + { + return this._rotation; + }, + + set: function (value) + { + this._rotation = value; + this.dirty = true; + } + + }, + + /** + * The horizontal position of the center of the Camera's viewport, relative to the left of the game canvas. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#centerX + * @type {number} + * @readonly + * @since 3.10.0 + */ + centerX: { + + get: function () + { + return this.x + (0.5 * this.width); + } + + }, + + /** + * The vertical position of the center of the Camera's viewport, relative to the top of the game canvas. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#centerY + * @type {number} + * @readonly + * @since 3.10.0 + */ + centerY: { + + get: function () + { + return this.y + (0.5 * this.height); + } + + }, + + /** + * The displayed width of the camera viewport, factoring in the camera zoom level. + * + * If a camera has a viewport width of 800 and a zoom of 0.5 then its display width + * would be 1600, as it's displaying twice as many pixels as zoom level 1. + * + * Equally, a camera with a width of 800 and zoom of 2 would have a display width + * of 400 pixels. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#displayWidth + * @type {number} + * @readonly + * @since 3.11.0 + */ + displayWidth: { + + get: function () + { + return this.width / this.zoom; + } + + }, + + /** + * The displayed height of the camera viewport, factoring in the camera zoom level. + * + * If a camera has a viewport height of 600 and a zoom of 0.5 then its display height + * would be 1200, as it's displaying twice as many pixels as zoom level 1. + * + * Equally, a camera with a height of 600 and zoom of 2 would have a display height + * of 300 pixels. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#displayHeight + * @type {number} + * @readonly + * @since 3.11.0 + */ + displayHeight: { + + get: function () + { + return this.height / this.zoom; + } + + } + +}); + +module.exports = BaseCamera; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Scale.Events + */ + +module.exports = { + + ENTER_FULLSCREEN: __webpack_require__(726), + FULLSCREEN_FAILED: __webpack_require__(727), + FULLSCREEN_UNSUPPORTED: __webpack_require__(728), + LEAVE_FULLSCREEN: __webpack_require__(729), + ORIENTATION_CHANGE: __webpack_require__(730), + RESIZE: __webpack_require__(731) + +}; + + +/***/ }), +/* 105 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10`. + * As will `14` snap to `10`... but `16` will snap to `15`. + * + * @function Phaser.Math.Snap.Floor + * @since 3.0.0 + * + * @param {number} value - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. + * + * @return {number} The snapped value. + */ +var SnapFloor = function (value, gap, start, divide) +{ + if (start === undefined) { start = 0; } + + if (gap === 0) + { + return value; + } + + value -= start; + value = gap * Math.floor(value / gap); + + return (divide) ? (start + value) / gap : start + value; +}; + +module.exports = SnapFloor; + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Clamp = __webpack_require__(20); +var Extend = __webpack_require__(17); + +/** + * @classdesc + * A Frame is a section of a Texture. + * + * @class Frame + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture this Frame is a part of. + * @param {(integer|string)} name - The name of this Frame. The name is unique within the Texture. + * @param {integer} sourceIndex - The index of the TextureSource that this Frame is a part of. + * @param {number} x - The x coordinate of the top-left of this Frame. + * @param {number} y - The y coordinate of the top-left of this Frame. + * @param {number} width - The width of this Frame. + * @param {number} height - The height of this Frame. + */ +var Frame = new Class({ + + initialize: + + function Frame (texture, name, sourceIndex, x, y, width, height) + { + /** + * The Texture this Frame is a part of. + * + * @name Phaser.Textures.Frame#texture + * @type {Phaser.Textures.Texture} + * @since 3.0.0 + */ + this.texture = texture; + + /** + * The name of this Frame. + * The name is unique within the Texture. + * + * @name Phaser.Textures.Frame#name + * @type {string} + * @since 3.0.0 + */ + this.name = name; + + /** + * The TextureSource this Frame is part of. + * + * @name Phaser.Textures.Frame#source + * @type {Phaser.Textures.TextureSource} + * @since 3.0.0 + */ + this.source = texture.source[sourceIndex]; + + /** + * The index of the TextureSource in the Texture sources array. + * + * @name Phaser.Textures.Frame#sourceIndex + * @type {integer} + * @since 3.0.0 + */ + this.sourceIndex = sourceIndex; + + /** + * A reference to the Texture Source WebGL Texture that this Frame is using. + * + * @name Phaser.Textures.Frame#glTexture + * @type {?WebGLTexture} + * @default null + * @since 3.11.0 + */ + this.glTexture = this.source.glTexture; + + /** + * X position within the source image to cut from. + * + * @name Phaser.Textures.Frame#cutX + * @type {integer} + * @since 3.0.0 + */ + this.cutX; + + /** + * Y position within the source image to cut from. + * + * @name Phaser.Textures.Frame#cutY + * @type {integer} + * @since 3.0.0 + */ + this.cutY; + + /** + * The width of the area in the source image to cut. + * + * @name Phaser.Textures.Frame#cutWidth + * @type {integer} + * @since 3.0.0 + */ + this.cutWidth; + + /** + * The height of the area in the source image to cut. + * + * @name Phaser.Textures.Frame#cutHeight + * @type {integer} + * @since 3.0.0 + */ + this.cutHeight; + + /** + * The X rendering offset of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#x + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The Y rendering offset of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#y + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The rendering width of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#width + * @type {integer} + * @since 3.0.0 + */ + this.width; + + /** + * The rendering height of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#height + * @type {integer} + * @since 3.0.0 + */ + this.height; + + /** + * Half the width, floored. + * Precalculated for the renderer. + * + * @name Phaser.Textures.Frame#halfWidth + * @type {integer} + * @since 3.0.0 + */ + this.halfWidth; + + /** + * Half the height, floored. + * Precalculated for the renderer. + * + * @name Phaser.Textures.Frame#halfHeight + * @type {integer} + * @since 3.0.0 + */ + this.halfHeight; + + /** + * The x center of this frame, floored. + * + * @name Phaser.Textures.Frame#centerX + * @type {integer} + * @since 3.0.0 + */ + this.centerX; + + /** + * The y center of this frame, floored. + * + * @name Phaser.Textures.Frame#centerY + * @type {integer} + * @since 3.0.0 + */ + this.centerY; + + /** + * The horizontal pivot point of this Frame. + * + * @name Phaser.Textures.Frame#pivotX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.pivotX = 0; + + /** + * The vertical pivot point of this Frame. + * + * @name Phaser.Textures.Frame#pivotY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.pivotY = 0; + + /** + * Does this Frame have a custom pivot point? + * + * @name Phaser.Textures.Frame#customPivot + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customPivot = false; + + /** + * **CURRENTLY UNSUPPORTED** + * + * Is this frame is rotated or not in the Texture? + * Rotation allows you to use rotated frames in texture atlas packing. + * It has nothing to do with Sprite rotation. + * + * @name Phaser.Textures.Frame#rotated + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.rotated = false; + + /** + * Over-rides the Renderer setting. + * -1 = use Renderer Setting + * 0 = No rounding + * 1 = Round + * + * @name Phaser.Textures.Frame#autoRound + * @type {integer} + * @default -1 + * @since 3.0.0 + */ + this.autoRound = -1; + + /** + * Any Frame specific custom data can be stored here. + * + * @name Phaser.Textures.Frame#customData + * @type {object} + * @since 3.0.0 + */ + this.customData = {}; + + /** + * WebGL UV u0 value. + * + * @name Phaser.Textures.Frame#u0 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.u0 = 0; + + /** + * WebGL UV v0 value. + * + * @name Phaser.Textures.Frame#v0 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.v0 = 0; + + /** + * WebGL UV u1 value. + * + * @name Phaser.Textures.Frame#u1 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.u1 = 0; + + /** + * WebGL UV v1 value. + * + * @name Phaser.Textures.Frame#v1 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.v1 = 0; + + /** + * The un-modified source frame, trim and UV data. + * + * @name Phaser.Textures.Frame#data + * @type {object} + * @private + * @since 3.0.0 + */ + this.data = { + cut: { + x: 0, + y: 0, + w: 0, + h: 0, + r: 0, + b: 0 + }, + trim: false, + sourceSize: { + w: 0, + h: 0 + }, + spriteSourceSize: { + x: 0, + y: 0, + w: 0, + h: 0, + r: 0, + b: 0 + }, + radius: 0, + drawImage: { + x: 0, + y: 0, + width: 0, + height: 0 + } + }; + + this.setSize(width, height, x, y); + }, + + /** + * Sets the width, height, x and y of this Frame. + * + * This is called automatically by the constructor + * and should rarely be changed on-the-fly. + * + * @method Phaser.Textures.Frame#setSize + * @since 3.7.0 + * + * @param {integer} width - The width of the frame before being trimmed. + * @param {integer} height - The height of the frame before being trimmed. + * @param {integer} [x=0] - The x coordinate of the top-left of this Frame. + * @param {integer} [y=0] - The y coordinate of the top-left of this Frame. + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + setSize: function (width, height, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + this.cutX = x; + this.cutY = y; + this.cutWidth = width; + this.cutHeight = height; + + this.width = width; + this.height = height; + + this.halfWidth = Math.floor(width * 0.5); + this.halfHeight = Math.floor(height * 0.5); + + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + + var data = this.data; + var cut = data.cut; + + cut.x = x; + cut.y = y; + cut.w = width; + cut.h = height; + cut.r = x + width; + cut.b = y + height; + + data.sourceSize.w = width; + data.sourceSize.h = height; + + data.spriteSourceSize.w = width; + data.spriteSourceSize.h = height; + + data.radius = 0.5 * Math.sqrt(width * width + height * height); + + var drawImage = data.drawImage; + + drawImage.x = x; + drawImage.y = y; + drawImage.width = width; + drawImage.height = height; + + return this.updateUVs(); + }, + + /** + * If the frame was trimmed when added to the Texture Atlas, this records the trim and source data. + * + * @method Phaser.Textures.Frame#setTrim + * @since 3.0.0 + * + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + setTrim: function (actualWidth, actualHeight, destX, destY, destWidth, destHeight) + { + var data = this.data; + var ss = data.spriteSourceSize; + + // Store actual values + + data.trim = true; + + data.sourceSize.w = actualWidth; + data.sourceSize.h = actualHeight; + + ss.x = destX; + ss.y = destY; + ss.w = destWidth; + ss.h = destHeight; + ss.r = destX + destWidth; + ss.b = destY + destHeight; + + // Adjust properties + this.x = destX; + this.y = destY; + + this.width = destWidth; + this.height = destHeight; + + this.halfWidth = destWidth * 0.5; + this.halfHeight = destHeight * 0.5; + + this.centerX = Math.floor(destWidth / 2); + this.centerY = Math.floor(destHeight / 2); + + return this.updateUVs(); + }, + + /** + * 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. + * + * 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. + */ + setCropUVs: function (crop, x, y, width, height, flipX, flipY) + { + // Clamp the input values + + var cx = this.cutX; + var cy = this.cutY; + var cw = this.cutWidth; + var ch = this.cutHeight; + var rw = this.realWidth; + var rh = this.realHeight; + + x = Clamp(x, 0, rw); + y = Clamp(y, 0, rh); + + width = Clamp(width, 0, rw - x); + height = Clamp(height, 0, rh - y); + + var ox = cx + x; + var oy = cy + y; + var ow = width; + var oh = height; + + var data = this.data; + + if (data.trim) + { + var ss = data.spriteSourceSize; + + // 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 + + width = Clamp(width, 0, cw - x); + height = Clamp(height, 0, ch - y); + + var cropRight = x + width; + var cropBottom = y + height; + + var intersects = !(ss.r < x || ss.b < y || ss.x > cropRight || ss.y > cropBottom); + + if (intersects) + { + var ix = Math.max(ss.x, x); + var iy = Math.max(ss.y, y); + var iw = Math.min(ss.r, cropRight) - ix; + var ih = Math.min(ss.b, cropBottom) - iy; + + ow = iw; + oh = ih; + + if (flipX) + { + ox = cx + (cw - (ix - ss.x) - iw); + } + else + { + ox = cx + (ix - ss.x); + } + + if (flipY) + { + oy = cy + (ch - (iy - ss.y) - ih); + } + else + { + oy = cy + (iy - ss.y); + } + + x = ix; + y = iy; + + width = iw; + height = ih; + } + else + { + ox = 0; + oy = 0; + ow = 0; + oh = 0; + } + } + else + { + if (flipX) + { + ox = cx + (cw - x - width); + } + + if (flipY) + { + oy = cy + (ch - y - height); + } + } + + var tw = this.source.width; + var th = this.source.height; + + // Map the given coordinates into UV space, clamping to the 0-1 range. + + crop.u0 = Math.max(0, ox / tw); + crop.v0 = Math.max(0, oy / th); + crop.u1 = Math.min(1, (ox + ow) / tw); + crop.v1 = Math.min(1, (oy + oh) / th); + + crop.x = x; + crop.y = y; + + crop.cx = ox; + crop.cy = oy; + crop.cw = ow; + crop.ch = oh; + + crop.width = width; + crop.height = height; + + crop.flipX = flipX; + crop.flipY = flipY; + + return crop; + }, + + /** + * 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. + */ + updateCropUVs: function (crop, flipX, flipY) + { + return this.setCropUVs(crop, crop.x, crop.y, crop.width, crop.height, flipX, flipY); + }, + + /** + * Updates the internal WebGL UV cache and the drawImage cache. + * + * @method Phaser.Textures.Frame#updateUVs + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + updateUVs: function () + { + var cx = this.cutX; + var cy = this.cutY; + var cw = this.cutWidth; + var ch = this.cutHeight; + + // Canvas data + + var cd = this.data.drawImage; + + cd.width = cw; + cd.height = ch; + + // WebGL data + + var tw = this.source.width; + var th = this.source.height; + + this.u0 = cx / tw; + this.v0 = cy / th; + + this.u1 = (cx + cw) / tw; + this.v1 = (cy + ch) / th; + + return this; + }, + + /** + * Updates the internal WebGL UV cache. + * + * @method Phaser.Textures.Frame#updateUVsInverted + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + updateUVsInverted: function () + { + var tw = this.source.width; + var th = this.source.height; + + this.u0 = (this.cutX + this.cutHeight) / tw; + this.v0 = this.cutY / th; + + this.u1 = this.cutX / tw; + this.v1 = (this.cutY + this.cutWidth) / th; + + return this; + }, + + /** + * Clones this Frame into a new Frame object. + * + * @method Phaser.Textures.Frame#clone + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} A clone of this Frame. + */ + clone: function () + { + var clone = new Frame(this.texture, this.name, this.sourceIndex); + + clone.cutX = this.cutX; + clone.cutY = this.cutY; + clone.cutWidth = this.cutWidth; + clone.cutHeight = this.cutHeight; + + clone.x = this.x; + clone.y = this.y; + + clone.width = this.width; + clone.height = this.height; + + clone.halfWidth = this.halfWidth; + clone.halfHeight = this.halfHeight; + + clone.centerX = this.centerX; + clone.centerY = this.centerY; + + clone.rotated = this.rotated; + + clone.data = Extend(true, clone.data, this.data); + + clone.updateUVs(); + + return clone; + }, + + /** + * Destroys this Frame by nulling its reference to the parent Texture and and data objects. + * + * @method Phaser.Textures.Frame#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.source = null; + this.texture = null; + this.glTexture = null; + this.customData = null; + this.data = null; + }, + + /** + * The width of the Frame in its un-trimmed, un-padded state, as prepared in the art package, + * before being packed. + * + * @name Phaser.Textures.Frame#realWidth + * @type {number} + * @readonly + * @since 3.0.0 + */ + realWidth: { + + get: function () + { + return this.data.sourceSize.w; + } + + }, + + /** + * The height of the Frame in its un-trimmed, un-padded state, as prepared in the art package, + * before being packed. + * + * @name Phaser.Textures.Frame#realHeight + * @type {number} + * @readonly + * @since 3.0.0 + */ + realHeight: { + + get: function () + { + return this.data.sourceSize.h; + } + + }, + + /** + * The radius of the Frame (derived from sqrt(w * w + h * h) / 2) + * + * @name Phaser.Textures.Frame#radius + * @type {number} + * @readonly + * @since 3.0.0 + */ + radius: { + + get: function () + { + return this.data.radius; + } + + }, + + /** + * Is the Frame trimmed or not? + * + * @name Phaser.Textures.Frame#trimmed + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + trimmed: { + + get: function () + { + return this.data.trim; + } + + }, + + /** + * The Canvas drawImage data object. + * + * @name Phaser.Textures.Frame#canvasData + * @type {object} + * @readonly + * @since 3.0.0 + */ + canvasData: { + + get: function () + { + return this.data.drawImage; + } + + } + +}); + +module.exports = Frame; + + +/***/ }), +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Contains = __webpack_require__(108); +var GetPoint = __webpack_require__(421); +var GetPoints = __webpack_require__(422); +var GEOM_CONST = __webpack_require__(52); +var Random = __webpack_require__(167); + +/** + * @classdesc + * An Ellipse object. + * + * This is a geometry object, containing numerical values and related methods to inspect and modify them. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render an Ellipse you should look at the capabilities of the Graphics class. + * + * @class Ellipse + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the ellipse. + * @param {number} [y=0] - The y position of the center of the ellipse. + * @param {number} [width=0] - The width of the ellipse. + * @param {number} [height=0] - The height of the ellipse. + */ +var Ellipse = new Class({ + + initialize: + + function Ellipse (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.ELLIPSE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Ellipse#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.ELLIPSE; + + /** + * The x position of the center of the ellipse. + * + * @name Phaser.Geom.Ellipse#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The y position of the center of the ellipse. + * + * @name Phaser.Geom.Ellipse#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + + /** + * The width of the ellipse. + * + * @name Phaser.Geom.Ellipse#width + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the ellipse. + * + * @name Phaser.Geom.Ellipse#height + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.height = height; + }, + + /** + * Check to see if the Ellipse contains the given x / y coordinates. + * + * @method Phaser.Geom.Ellipse#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check within the ellipse. + * @param {number} y - The y coordinate to check within the ellipse. + * + * @return {boolean} True if the coordinates are within the ellipse, otherwise false. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Returns a Point 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 circle. + * + * @method Phaser.Geom.Ellipse#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the ellipse. + */ + getPoint: function (position, point) + { + return GetPoint(this, position, point); + }, + + /** + * Returns an array of Point 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the ellipse. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a uniformly distributed random point from anywhere within the given Ellipse. + * + * @method Phaser.Geom.Ellipse#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {(Phaser.Geom.Point|object)} [point] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets the x, y, width and height of this ellipse. + * + * @method Phaser.Geom.Ellipse#setTo + * @since 3.0.0 + * + * @param {number} x - The x position of the center of the ellipse. + * @param {number} y - The y position of the center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) + { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + }, + + /** + * Sets this Ellipse to be empty with a width and height of zero. + * Does not change its position. + * + * @method Phaser.Geom.Ellipse#setEmpty + * @since 3.0.0 + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setEmpty: function () + { + this.width = 0; + this.height = 0; + + return this; + }, + + /** + * Sets the position of this Ellipse. + * + * @method Phaser.Geom.Ellipse#setPosition + * @since 3.0.0 + * + * @param {number} x - The x position of the center of the ellipse. + * @param {number} y - The y position of the center of the ellipse. + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Sets the size of this Ellipse. + * Does not change its position. + * + * @method Phaser.Geom.Ellipse#setSize + * @since 3.0.0 + * + * @param {number} width - The width of the ellipse. + * @param {number} [height=width] - The height of the ellipse. + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + this.width = width; + this.height = height; + + return this; + }, + + /** + * Checks to see if the Ellipse is empty: has a width or height equal to zero. + * + * @method Phaser.Geom.Ellipse#isEmpty + * @since 3.0.0 + * + * @return {boolean} True if the Ellipse is empty, otherwise false. + */ + isEmpty: function () + { + return (this.width <= 0 || this.height <= 0); + }, + + /** + * Returns the minor radius of the ellipse. Also known as the Semi Minor Axis. + * + * @method Phaser.Geom.Ellipse#getMinorRadius + * @since 3.0.0 + * + * @return {number} The minor radius. + */ + getMinorRadius: function () + { + return Math.min(this.width, this.height) / 2; + }, + + /** + * Returns the major radius of the ellipse. Also known as the Semi Major Axis. + * + * @method Phaser.Geom.Ellipse#getMajorRadius + * @since 3.0.0 + * + * @return {number} The major radius. + */ + getMajorRadius: function () + { + return Math.max(this.width, this.height) / 2; + }, + + /** + * The left position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.x - (this.width / 2); + }, + + set: function (value) + { + this.x = value + (this.width / 2); + } + + }, + + /** + * The right position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.x + (this.width / 2); + }, + + set: function (value) + { + this.x = value - (this.width / 2); + } + + }, + + /** + * The top position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.y - (this.height / 2); + }, + + set: function (value) + { + this.y = value + (this.height / 2); + } + + }, + + /** + * The bottom position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.y + (this.height / 2); + }, + + set: function (value) + { + this.y = value - (this.height / 2); + } + + } + +}); + +module.exports = Ellipse; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check to see if the Ellipse contains the given x / y coordinates. + * + * @function Phaser.Geom.Ellipse.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. + * @param {number} x - The x coordinate to check within the ellipse. + * @param {number} y - The y coordinate to check within the ellipse. + * + * @return {boolean} True if the coordinates are within the ellipse, otherwise false. + */ +var Contains = function (ellipse, x, y) +{ + if (ellipse.width <= 0 || ellipse.height <= 0) + { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - ellipse.x) / ellipse.width); + var normy = ((y - ellipse.y) / ellipse.height); + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); +}; + +module.exports = Contains; + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Actions = __webpack_require__(259); +var Class = __webpack_require__(0); +var Events = __webpack_require__(102); +var GetFastValue = __webpack_require__(1); +var GetValue = __webpack_require__(5); +var IsPlainObject = __webpack_require__(7); +var Range = __webpack_require__(415); +var Set = __webpack_require__(110); +var Sprite = __webpack_require__(65); + +/** + * @classdesc + * A Group is a way for you to create, manipulate, or recycle similar Game Objects. + * + * Group membership is non-exclusive. A Game Object can belong to several groups, one group, or none. + * + * Groups themselves aren't displayable, and can't be positioned, rotated, scaled, or hidden. + * + * @class Group + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * @param {Phaser.Scene} scene - The scene this group belongs to. + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. If `key` is set, Phaser.GameObjects.Group#createMultiple is also called with these settings. + * + * @see Phaser.Physics.Arcade.Group + * @see Phaser.Physics.Arcade.StaticGroup + */ +var Group = new Class({ + + initialize: + + function Group (scene, children, config) + { + // 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 + + if (config) + { + // config has been set, are the children an array? + + if (children && !Array.isArray(children)) + { + children = [ children ]; + } + } + else if (Array.isArray(children)) + { + // No config, so let's check the children argument + + if (IsPlainObject(children[0])) + { + // It's an array of plain config objects + config = children; + children = null; + } + } + else if (IsPlainObject(children)) + { + // Children isn't an array. Is it a config object though? + config = children; + children = null; + } + + /** + * This scene this group belongs to. + * + * @name Phaser.GameObjects.Group#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * Members of this group. + * + * @name Phaser.GameObjects.Group#children + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.children = new Set(children); + + /** + * A flag identifying this object as a group. + * + * @name Phaser.GameObjects.Group#isParent + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.isParent = true; + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.GameObjects.Group#type + * @type {string} + * @default 'Group' + * @since 3.21.0 + */ + this.type = 'Group'; + + /** + * The class to create new group members from. + * + * @name Phaser.GameObjects.Group#classType + * @type {Function} + * @since 3.0.0 + * @default Phaser.GameObjects.Sprite + */ + this.classType = GetFastValue(config, 'classType', Sprite); + + /** + * The name of this group. + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.GameObjects.Group#name + * @type {string} + * @default '' + * @since 3.18.0 + */ + this.name = GetFastValue(config, 'name', ''); + + /** + * Whether this group runs its {@link Phaser.GameObjects.Group#preUpdate} method + * (which may update any members). + * + * @name Phaser.GameObjects.Group#active + * @type {boolean} + * @since 3.0.0 + */ + this.active = GetFastValue(config, 'active', true); + + /** + * The maximum size of this group, if used as a pool. -1 is no limit. + * + * @name Phaser.GameObjects.Group#maxSize + * @type {integer} + * @since 3.0.0 + * @default -1 + */ + this.maxSize = GetFastValue(config, 'maxSize', -1); + + /** + * A default texture key to use when creating new group members. + * + * This is used in {@link Phaser.GameObjects.Group#create} + * but not in {@link Phaser.GameObjects.Group#createMultiple}. + * + * @name Phaser.GameObjects.Group#defaultKey + * @type {string} + * @since 3.0.0 + */ + this.defaultKey = GetFastValue(config, 'defaultKey', null); + + /** + * A default texture frame to use when creating new group members. + * + * @name Phaser.GameObjects.Group#defaultFrame + * @type {(string|integer)} + * @since 3.0.0 + */ + this.defaultFrame = GetFastValue(config, 'defaultFrame', null); + + /** + * Whether to call the update method of any members. + * + * @name Phaser.GameObjects.Group#runChildUpdate + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.GameObjects.Group#preUpdate + */ + this.runChildUpdate = GetFastValue(config, 'runChildUpdate', false); + + /** + * A function to be called when adding or creating group members. + * + * @name Phaser.GameObjects.Group#createCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @since 3.0.0 + */ + this.createCallback = GetFastValue(config, 'createCallback', null); + + /** + * A function to be called when removing group members. + * + * @name Phaser.GameObjects.Group#removeCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @since 3.0.0 + */ + this.removeCallback = GetFastValue(config, 'removeCallback', null); + + /** + * A function to be called when creating several group members at once. + * + * @name Phaser.GameObjects.Group#createMultipleCallback + * @type {?Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback} + * @since 3.0.0 + */ + this.createMultipleCallback = GetFastValue(config, 'createMultipleCallback', null); + + /** + * A function to be called when adding or creating group members. + * For internal use only by a Group, or any class that extends it. + * + * @name Phaser.GameObjects.Group#internalCreateCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @private + * @since 3.22.0 + */ + this.internalCreateCallback = GetFastValue(config, 'internalCreateCallback', null); + + /** + * A function to be called when removing group members. + * For internal use only by a Group, or any class that extends it. + * + * @name Phaser.GameObjects.Group#internalRemoveCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @private + * @since 3.22.0 + */ + this.internalRemoveCallback = GetFastValue(config, 'internalRemoveCallback', null); + + if (config) + { + this.createMultiple(config); + } + }, + + /** + * Creates a new Game Object and adds it to this group, unless the group {@link Phaser.GameObjects.Group#isFull is full}. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#create + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal position of the new Game Object in the world. + * @param {number} [y=0] - The vertical position of the new Game Object in the world. + * @param {string} [key=defaultKey] - The texture key of the new Game Object. + * @param {(string|integer)} [frame=defaultFrame] - The texture frame of the new Game Object. + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of the new Game Object. + * @param {boolean} [active=true] - The {@link Phaser.GameObjects.GameObject#active} state of the new Game Object. + * + * @return {any} The new Game Object (usually a Sprite, etc.). + */ + create: function (x, y, key, frame, visible, active) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (key === undefined) { key = this.defaultKey; } + if (frame === undefined) { frame = this.defaultFrame; } + if (visible === undefined) { visible = true; } + if (active === undefined) { active = true; } + + // Pool? + if (this.isFull()) + { + return null; + } + + var child = new this.classType(this.scene, x, y, key, frame); + + this.scene.sys.displayList.add(child); + + if (child.preUpdate) + { + this.scene.sys.updateList.add(child); + } + + child.visible = visible; + child.setActive(active); + + this.add(child); + + return child; + }, + + /** + * Creates several Game Objects and adds them to this group. + * + * If the group becomes {@link Phaser.GameObjects.Group#isFull}, no further Game Objects are created. + * + * Calls {@link Phaser.GameObjects.Group#createMultipleCallback} and {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#createMultiple + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Group.GroupCreateConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig[]} config - Creation settings. This can be a single configuration object or an array of such objects, which will be applied in turn. + * + * @return {any[]} The newly created Game Objects. + */ + createMultiple: function (config) + { + if (this.isFull()) + { + return []; + } + + if (!Array.isArray(config)) + { + config = [ config ]; + } + + var output = []; + + if (config[0].key) + { + for (var i = 0; i < config.length; i++) + { + var entries = this.createFromConfig(config[i]); + + output = output.concat(entries); + } + } + + return output; + }, + + /** + * A helper for {@link Phaser.GameObjects.Group#createMultiple}. + * + * @method Phaser.GameObjects.Group#createFromConfig + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Group.GroupCreateConfig} options - Creation settings. + * + * @return {any[]} The newly created Game Objects. + */ + createFromConfig: function (options) + { + if (this.isFull()) + { + return []; + } + + this.classType = GetFastValue(options, 'classType', this.classType); + + var key = GetFastValue(options, 'key', undefined); + var frame = GetFastValue(options, 'frame', null); + var visible = GetFastValue(options, 'visible', true); + var active = GetFastValue(options, 'active', true); + + var entries = []; + + // Can't do anything without at least a key + if (key === undefined) + { + return entries; + } + else + { + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + } + + // Build an array of key frame pairs to loop through + + var repeat = GetFastValue(options, 'repeat', 0); + var randomKey = GetFastValue(options, 'randomKey', false); + var randomFrame = GetFastValue(options, 'randomFrame', false); + var yoyo = GetFastValue(options, 'yoyo', false); + var quantity = GetFastValue(options, 'quantity', false); + var frameQuantity = GetFastValue(options, 'frameQuantity', 1); + var max = GetFastValue(options, 'max', 0); + + // If a quantity value is set we use that to override the frameQuantity + + var range = Range(key, frame, { + max: max, + qty: (quantity) ? quantity : frameQuantity, + random: randomKey, + randomB: randomFrame, + repeat: repeat, + yoyo: yoyo + }); + + if (options.createCallback) + { + this.createCallback = options.createCallback; + } + + if (options.removeCallback) + { + this.removeCallback = options.removeCallback; + } + + for (var c = 0; c < range.length; c++) + { + var created = this.create(0, 0, range[c].a, range[c].b, visible, active); + + if (!created) + { + break; + } + + entries.push(created); + } + + // Post-creation options (applied only to those items created in this call): + + var x = GetValue(options, 'setXY.x', 0); + var y = GetValue(options, 'setXY.y', 0); + var stepX = GetValue(options, 'setXY.stepX', 0); + var stepY = GetValue(options, 'setXY.stepY', 0); + + Actions.SetXY(entries, x, y, stepX, stepY); + + var rotation = GetValue(options, 'setRotation.value', 0); + var stepRotation = GetValue(options, 'setRotation.step', 0); + + Actions.SetRotation(entries, rotation, stepRotation); + + var scaleX = GetValue(options, 'setScale.x', 1); + var scaleY = GetValue(options, 'setScale.y', scaleX); + var stepScaleX = GetValue(options, 'setScale.stepX', 0); + var stepScaleY = GetValue(options, 'setScale.stepY', 0); + + Actions.SetScale(entries, scaleX, scaleY, stepScaleX, stepScaleY); + + var alpha = GetValue(options, 'setAlpha.value', 1); + var stepAlpha = GetValue(options, 'setAlpha.step', 0); + + Actions.SetAlpha(entries, alpha, stepAlpha); + + var depth = GetValue(options, 'setDepth.value', 0); + var stepDepth = GetValue(options, 'setDepth.step', 0); + + Actions.SetDepth(entries, depth, stepDepth); + + var scrollFactorX = GetValue(options, 'setScrollFactor.x', 1); + var scrollFactorY = GetValue(options, 'setScrollFactor.y', scrollFactorX); + var stepScrollFactorX = GetValue(options, 'setScrollFactor.stepX', 0); + var stepScrollFactorY = GetValue(options, 'setScrollFactor.stepY', 0); + + Actions.SetScrollFactor(entries, scrollFactorX, scrollFactorY, stepScrollFactorX, stepScrollFactorY); + + var hitArea = GetFastValue(options, 'hitArea', null); + var hitAreaCallback = GetFastValue(options, 'hitAreaCallback', null); + + if (hitArea) + { + Actions.SetHitArea(entries, hitArea, hitAreaCallback); + } + + var grid = GetFastValue(options, 'gridAlign', false); + + if (grid) + { + Actions.GridAlign(entries, grid); + } + + if (this.createMultipleCallback) + { + this.createMultipleCallback.call(this, entries); + } + + return entries; + }, + + /** + * Updates any group members, if {@link Phaser.GameObjects.Group#runChildUpdate} is enabled. + * + * @method Phaser.GameObjects.Group#preUpdate + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time elapsed since the last frame. + */ + preUpdate: function (time, delta) + { + if (!this.runChildUpdate || this.children.size === 0) + { + return; + } + + // Because a Group child may mess with the length of the Group during its update + var temp = this.children.entries.slice(); + + for (var i = 0; i < temp.length; i++) + { + var item = temp[i]; + + if (item.active) + { + item.update(time, delta); + } + } + }, + + /** + * Adds a Game Object to this group. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#add + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. + * @param {boolean} [addToScene=false] - Also add the Game Object to the scene. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + add: function (child, addToScene) + { + if (addToScene === undefined) { addToScene = false; } + + if (this.isFull()) + { + return this; + } + + this.children.set(child); + + if (this.internalCreateCallback) + { + this.internalCreateCallback.call(this, child); + } + + if (this.createCallback) + { + this.createCallback.call(this, child); + } + + if (addToScene) + { + this.scene.sys.displayList.add(child); + + if (child.preUpdate) + { + this.scene.sys.updateList.add(child); + } + } + + child.on(Events.DESTROY, this.remove, this); + + return this; + }, + + /** + * Adds several Game Objects to this group. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#addMultiple + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject[]} children - The Game Objects to add. + * @param {boolean} [addToScene=false] - Also add the Game Objects to the scene. + * + * @return {Phaser.GameObjects.Group} This group. + */ + addMultiple: function (children, addToScene) + { + if (addToScene === undefined) { addToScene = false; } + + if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], addToScene); + } + } + + return this; + }, + + /** + * Removes a member of this Group and optionally removes it from the Scene and / or destroys it. + * + * Calls {@link Phaser.GameObjects.Group#removeCallback}. + * + * @method Phaser.GameObjects.Group#remove + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to remove. + * @param {boolean} [removeFromScene=false] - Optionally remove the Group member from the Scene it belongs to. + * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group member. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + remove: function (child, removeFromScene, destroyChild) + { + if (removeFromScene === undefined) { removeFromScene = false; } + if (destroyChild === undefined) { destroyChild = false; } + + if (!this.children.contains(child)) + { + return this; + } + + this.children.delete(child); + + if (this.internalRemoveCallback) + { + this.internalRemoveCallback.call(this, child); + } + + if (this.removeCallback) + { + this.removeCallback.call(this, child); + } + + child.off(Events.DESTROY, this.remove, this); + + if (destroyChild) + { + child.destroy(); + } + else if (removeFromScene) + { + child.scene.sys.displayList.remove(child); + + if (child.preUpdate) + { + child.scene.sys.updateList.remove(child); + } + } + + return this; + }, + + /** + * Removes all members of this Group and optionally removes them from the Scene and / or destroys them. + * + * Does not call {@link Phaser.GameObjects.Group#removeCallback}. + * + * @method Phaser.GameObjects.Group#clear + * @since 3.0.0 + * + * @param {boolean} [removeFromScene=false] - Optionally remove each Group member from the Scene. + * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group members. + * + * @return {Phaser.GameObjects.Group} This group. + */ + clear: function (removeFromScene, destroyChild) + { + if (removeFromScene === undefined) { removeFromScene = false; } + if (destroyChild === undefined) { destroyChild = false; } + + var children = this.children; + + for (var i = 0; i < children.size; i++) + { + var gameObject = children.entries[i]; + + gameObject.off(Events.DESTROY, this.remove, this); + + if (destroyChild) + { + gameObject.destroy(); + } + else if (removeFromScene) + { + gameObject.scene.sys.displayList.remove(gameObject); + + if (gameObject.preUpdate) + { + gameObject.scene.sys.updateList.remove(gameObject); + } + } + } + + this.children.clear(); + + return this; + }, + + /** + * Tests if a Game Object is a member of this group. + * + * @method Phaser.GameObjects.Group#contains + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - A Game Object. + * + * @return {boolean} True if the Game Object is a member of this group. + */ + contains: function (child) + { + return this.children.contains(child); + }, + + /** + * All members of the group. + * + * @method Phaser.GameObjects.Group#getChildren + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject[]} The group members. + */ + getChildren: function () + { + return this.children.entries; + }, + + /** + * The number of members of the group. + * + * @method Phaser.GameObjects.Group#getLength + * @since 3.0.0 + * + * @return {integer} + */ + getLength: function () + { + return this.children.size; + }, + + /** + * Scans the Group, from top to bottom, for the first member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirst + * @since 3.0.0 + * + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getFirst: function (state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(true, 1, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the Group, from top to bottom, for the nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirstNth + * @since 3.6.0 + * + * @param {integer} nth - The nth matching Group member to search for. + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getFirstNth: function (nth, state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(true, nth, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the Group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getLast + * @since 3.6.0 + * + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getLast: function (state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(false, 1, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the Group for the last nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getLastNth + * @since 3.6.0 + * + * @param {integer} nth - The nth matching Group member to search for. + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getLastNth: function (nth, state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(false, nth, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getHandler + * @private + * @since 3.6.0 + * + * @param {boolean} forwards - Search front to back or back to front? + * @param {integer} nth - Stop matching after nth successful matches. + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getHandler: function (forwards, nth, state, createIfNull, x, y, key, frame, visible) + { + if (state === undefined) { state = false; } + if (createIfNull === undefined) { createIfNull = false; } + + var gameObject; + + var i; + var total = 0; + var children = this.children.entries; + + if (forwards) + { + for (i = 0; i < children.length; i++) + { + gameObject = children[i]; + + if (gameObject.active === state) + { + total++; + + if (total === nth) + { + break; + } + } + else + { + gameObject = null; + } + } + } + else + { + for (i = children.length - 1; i >= 0; i--) + { + gameObject = children[i]; + + if (gameObject.active === state) + { + total++; + + if (total === nth) + { + break; + } + } + else + { + gameObject = null; + } + } + } + + if (gameObject) + { + if (typeof(x) === 'number') + { + gameObject.x = x; + } + + if (typeof(y) === 'number') + { + gameObject.y = y; + } + + return gameObject; + } + + // Got this far? We need to create or bail + if (createIfNull) + { + return this.create(x, y, key, frame, visible); + } + else + { + return null; + } + }, + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, + * assigns `x` and `y`, and returns the member. + * + * If no inactive member is found and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * The new Game Object will have its active state set to `true`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#get + * @since 3.0.0 + * + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first inactive group member, or a newly created member, or null. + */ + get: function (x, y, key, frame, visible) + { + return this.getFirst(false, true, x, y, key, frame, visible); + }, + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `true`, + * assigns `x` and `y`, and returns the member. + * + * If no active member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirstAlive + * @since 3.0.0 + * + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {any} The first active group member, or a newly created member, or null. + */ + getFirstAlive: function (createIfNull, x, y, key, frame, visible) + { + return this.getFirst(true, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, + * assigns `x` and `y`, and returns the member. + * + * If no inactive member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. + * The new Game Object will have an active state set to `true`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirstDead + * @since 3.0.0 + * + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {any} The first inactive group member, or a newly created member, or null. + */ + getFirstDead: function (createIfNull, x, y, key, frame, visible) + { + return this.getFirst(false, createIfNull, x, y, key, frame, visible); + }, + + /** + * {@link Phaser.GameObjects.Components.Animation#play Plays} an animation for all members of this group. + * + * @method Phaser.GameObjects.Group#playAnimation + * @since 3.0.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {string} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + playAnimation: function (key, startFrame) + { + Actions.PlayAnimation(this.children.entries, key, startFrame); + + return this; + }, + + /** + * Whether this group's size at its {@link Phaser.GameObjects.Group#maxSize maximum}. + * + * @method Phaser.GameObjects.Group#isFull + * @since 3.0.0 + * + * @return {boolean} True if the number of members equals {@link Phaser.GameObjects.Group#maxSize}. + */ + isFull: function () + { + if (this.maxSize === -1) + { + return false; + } + else + { + return (this.children.size >= this.maxSize); + } + }, + + /** + * Counts the number of active (or inactive) group members. + * + * @method Phaser.GameObjects.Group#countActive + * @since 3.0.0 + * + * @param {boolean} [value=true] - Count active (true) or inactive (false) group members. + * + * @return {integer} The number of group members with an active state matching the `active` argument. + */ + countActive: function (value) + { + if (value === undefined) { value = true; } + + var total = 0; + + for (var i = 0; i < this.children.size; i++) + { + if (this.children.entries[i].active === value) + { + total++; + } + } + + return total; + }, + + /** + * Counts the number of in-use (active) group members. + * + * @method Phaser.GameObjects.Group#getTotalUsed + * @since 3.0.0 + * + * @return {integer} The number of group members with an active state of true. + */ + getTotalUsed: function () + { + return this.countActive(); + }, + + /** + * The difference of {@link Phaser.GameObjects.Group#maxSize} and the number of active group members. + * + * This represents the number of group members that could be created or reactivated before reaching the size limit. + * + * @method Phaser.GameObjects.Group#getTotalFree + * @since 3.0.0 + * + * @return {integer} maxSize minus the number of active group numbers; or a large number (if maxSize is -1). + */ + getTotalFree: function () + { + var used = this.getTotalUsed(); + var capacity = (this.maxSize === -1) ? 999999999999 : this.maxSize; + + return (capacity - used); + }, + + /** + * Sets the property as defined in `key` of each group member to the given value. + * + * @method Phaser.GameObjects.Group#propertyValueSet + * @since 3.21.0 + * + * @param {string} key - The property to be updated. + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + propertyValueSet: function (key, value, step, index, direction) + { + Actions.PropertyValueSet(this.children.entries, key, value, step, index, direction); + + return this; + }, + + /** + * Adds the given value to the property as defined in `key` of each group member. + * + * @method Phaser.GameObjects.Group#propertyValueInc + * @since 3.21.0 + * + * @param {string} key - The property to be updated. + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + propertyValueInc: function (key, value, step, index, direction) + { + Actions.PropertyValueInc(this.children.entries, key, value, step, index, direction); + + return this; + }, + + /** + * Sets the x of each group member. + * + * @method Phaser.GameObjects.Group#setX + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setX: function (value, step) + { + Actions.SetX(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the y of each group member. + * + * @method Phaser.GameObjects.Group#setY + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setY: function (value, step) + { + Actions.SetY(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the x, y of each group member. + * + * @method Phaser.GameObjects.Group#setXY + * @since 3.21.0 + * + * @param {number} x - The amount to set the `x` property to. + * @param {number} [y=x] - The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setXY: function (x, y, stepX, stepY) + { + Actions.SetXY(this.children.entries, x, y, stepX, stepY); + + return this; + }, + + /** + * Adds the given value to the x of each group member. + * + * @method Phaser.GameObjects.Group#incX + * @since 3.21.0 + * + * @param {number} value - The amount to be added to the `x` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + incX: function (value, step) + { + Actions.IncX(this.children.entries, value, step); + + return this; + }, + + /** + * Adds the given value to the y of each group member. + * + * @method Phaser.GameObjects.Group#incY + * @since 3.21.0 + * + * @param {number} value - The amount to be added to the `y` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + incY: function (value, step) + { + Actions.IncY(this.children.entries, value, step); + + return this; + }, + + /** + * Adds the given value to the x, y of each group member. + * + * @method Phaser.GameObjects.Group#incXY + * @since 3.21.0 + * + * @param {number} x - The amount to be added to the `x` property. + * @param {number} [y=x] - The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + incXY: function (x, y, stepX, stepY) + { + Actions.IncXY(this.children.entries, x, y, stepX, stepY); + + return this; + }, + + /** + * Iterate through the group members changing the position of each element to be that of the element that came before + * it in the array (or after it if direction = 1) + * + * The first group member position is set to x/y. + * + * @method Phaser.GameObjects.Group#shiftPosition + * @since 3.21.0 + * + * @param {number} x - The x coordinate to place the first item in the array at. + * @param {number} y - The y coordinate to place the first item in the array at. + * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + shiftPosition: function (x, y, direction) + { + Actions.ShiftPosition(this.children.entries, x, y, direction); + + return this; + }, + + /** + * Sets the angle of each group member. + * + * @method Phaser.GameObjects.Group#angle + * @since 3.21.0 + * + * @param {number} value - The amount to set the angle to, in degrees. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + angle: function (value, step) + { + Actions.Angle(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the rotation of each group member. + * + * @method Phaser.GameObjects.Group#rotate + * @since 3.21.0 + * + * @param {number} value - The amount to set the rotation to, in radians. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + rotate: function (value, step) + { + Actions.Rotate(this.children.entries, value, step); + + return this; + }, + + /** + * Rotates each group member around the given point by the given angle. + * + * @method Phaser.GameObjects.Group#rotateAround + * @since 3.21.0 + * + * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + rotateAround: function (point, angle) + { + Actions.RotateAround(this.children.entries, point, angle); + + return this; + }, + + /** + * Rotates each group member around the given point by the given angle and distance. + * + * @method Phaser.GameObjects.Group#rotateAroundDistance + * @since 3.21.0 + * + * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * @param {number} distance - The distance from the point of rotation in pixels. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + rotateAroundDistance: function (point, angle, distance) + { + Actions.RotateAroundDistance(this.children.entries, point, angle, distance); + + return this; + }, + + /** + * Sets the alpha of each group member. + * + * @method Phaser.GameObjects.Group#setAlpha + * @since 3.21.0 + * + * @param {number} value - The amount to set the alpha to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setAlpha: function (value, step) + { + Actions.SetAlpha(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the tint of each group member. + * + * @method Phaser.GameObjects.Group#setTint + * @since 3.21.0 + * + * @param {number} topLeft - The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. + * @param {number} [topRight] - The tint to be applied to top-right corner of item. + * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. + * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setTint: function (topLeft, topRight, bottomLeft, bottomRight) + { + Actions.SetTint(this.children.entries, topLeft, topRight, bottomLeft, bottomRight); + + return this; + }, + + /** + * Sets the originX, originY of each group member. + * + * @method Phaser.GameObjects.Group#setOrigin + * @since 3.21.0 + * + * @param {number} originX - The amount to set the `originX` property to. + * @param {number} [originY] - The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. + * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setOrigin: function (originX, originY, stepX, stepY) + { + Actions.SetOrigin(this.children.entries, originX, originY, stepX, stepY); + + return this; + }, + + /** + * Sets the scaleX of each group member. + * + * @method Phaser.GameObjects.Group#scaleX + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + scaleX: function (value, step) + { + Actions.ScaleX(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the scaleY of each group member. + * + * @method Phaser.GameObjects.Group#scaleY + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + scaleY: function (value, step) + { + Actions.ScaleY(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the scaleX, scaleY of each group member. + * + * @method Phaser.GameObjects.Group#scaleXY + * @since 3.21.0 + * + * @param {number} scaleX - The amount to be added to the `scaleX` property. + * @param {number} [scaleY] - The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. + * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + scaleXY: function (scaleX, scaleY, stepX, stepY) + { + Actions.ScaleXY(this.children.entries, scaleX, scaleY, stepX, stepY); + + return this; + }, + + /** + * Sets the depth of each group member. + * + * @method Phaser.GameObjects.Group#setDepth + * @since 3.0.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setDepth: function (value, step) + { + Actions.SetDepth(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the blendMode of each group member. + * + * @method Phaser.GameObjects.Group#setBlendMode + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setBlendMode: function (value) + { + Actions.SetBlendMode(this.children.entries, value); + + return this; + }, + + /** + * Passes all group members to the Input Manager to enable them for input with identical areas and callbacks. + * + * @method Phaser.GameObjects.Group#setHitArea + * @since 3.21.0 + * + * @param {*} 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 - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setHitArea: function (hitArea, hitAreaCallback) + { + Actions.SetHitArea(this.children.entries, hitArea, hitAreaCallback); + + return this; + }, + + /** + * Shuffles the group members in place. + * + * @method Phaser.GameObjects.Group#shuffle + * @since 3.21.0 + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + shuffle: function () + { + Actions.Shuffle(this.children.entries); + + return this; + }, + + /** + * Deactivates a member of this group. + * + * @method Phaser.GameObjects.Group#kill + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - A member of this group. + */ + kill: function (gameObject) + { + if (this.children.contains(gameObject)) + { + gameObject.setActive(false); + } + }, + + /** + * Deactivates and hides a member of this group. + * + * @method Phaser.GameObjects.Group#killAndHide + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - A member of this group. + */ + killAndHide: function (gameObject) + { + if (this.children.contains(gameObject)) + { + gameObject.setActive(false); + gameObject.setVisible(false); + } + }, + + /** + * Sets the visible of each group member. + * + * @method Phaser.GameObjects.Group#setVisible + * @since 3.21.0 + * + * @param {boolean} value - The value to set the property to. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + setVisible: function (value, index, direction) + { + Actions.SetVisible(this.children.entries, value, index, direction); + + return this; + }, + + /** + * Toggles (flips) the visible state of each member of this group. + * + * @method Phaser.GameObjects.Group#toggleVisible + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Group} This Group object. + */ + toggleVisible: function () + { + Actions.ToggleVisible(this.children.entries); + + return this; + }, + + /** + * Empties this group and removes it from the Scene. + * + * Does not call {@link Phaser.GameObjects.Group#removeCallback}. + * + * @method Phaser.GameObjects.Group#destroy + * @since 3.0.0 + * + * @param {boolean} [destroyChildren=false] - Also {@link Phaser.GameObjects.GameObject#destroy} each group member. + */ + destroy: function (destroyChildren) + { + if (destroyChildren === undefined) { destroyChildren = false; } + + // This Game Object had already been destroyed + if (!this.scene || this.ignoreDestroy) + { + return; + } + + this.clear(false, destroyChildren); + + this.scene = undefined; + this.children = undefined; + } + +}); + +module.exports = Group; + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @callback EachSetCallback + * + * @param {E} entry - The Set entry. + * @param {number} index - The index of the entry within the Set. + * + * @return {?boolean} The callback result. + */ + +/** + * @classdesc + * A Set is a collection of unique elements. + * + * @class Set + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [elements] + * + * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. + */ +var Set = new Class({ + + initialize: + + function Set (elements) + { + /** + * The entries of this Set. Stored internally as an array. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.Set#entries + * @type {Array.<*>} + * @default [] + * @since 3.0.0 + */ + this.entries = []; + + if (Array.isArray(elements)) + { + for (var i = 0; i < elements.length; i++) + { + this.set(elements[i]); + } + } + }, + + /** + * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. + * + * @method Phaser.Structs.Set#set + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to insert into this Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + set: function (value) + { + if (this.entries.indexOf(value) === -1) + { + this.entries.push(value); + } + + return this; + }, + + /** + * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. + * If no elements of this Set satisfy the condition then this method will return `null`. + * + * @method Phaser.Structs.Set#get + * @since 3.0.0 + * + * @genericUse {T} - [value,$return] + * + * @param {string} property - The property name to check on the elements of this Set. + * @param {*} value - The value to check for. + * + * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. + */ + get: function (property, value) + { + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + + if (entry[property] === value) + { + return entry; + } + } + }, + + /** + * Returns an array containing all the values in this Set. + * + * @method Phaser.Structs.Set#getArray + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} An array containing all the values in this Set. + */ + getArray: function () + { + return this.entries.slice(0); + }, + + /** + * Removes the given value from this Set if this Set contains that value. + * + * @method Phaser.Structs.Set#delete + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to remove from the Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + delete: function (value) + { + var index = this.entries.indexOf(value); + + if (index > -1) + { + this.entries.splice(index, 1); + } + + return this; + }, + + /** + * Dumps the contents of this Set to the console via `console.group`. + * + * @method Phaser.Structs.Set#dump + * @since 3.0.0 + */ + dump: function () + { + // eslint-disable-next-line no-console + console.group('Set'); + + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + console.log(entry); + } + + // eslint-disable-next-line no-console + console.groupEnd(); + }, + + /** + * Passes each value in this Set to the given callback. + * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. + * + * @method Phaser.Structs.Set#each + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + each: function (callback, callbackScope) + { + var i; + var temp = this.entries.slice(); + var len = temp.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, temp[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(temp[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Passes each value in this Set to the given callback. + * For when you absolutely know this Set won't be modified during the iteration. + * + * @method Phaser.Structs.Set#iterate + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterate: function (callback, callbackScope) + { + var i; + var len = this.entries.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, this.entries[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(this.entries[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. + * + * @method Phaser.Structs.Set#iterateLocal + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {string} callbackKey - The key of the function to be invoked on each Set entry. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterateLocal: function (callbackKey) + { + var i; + var args = []; + + for (i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + var len = this.entries.length; + + for (i = 0; i < len; i++) + { + var entry = this.entries[i]; + + entry[callbackKey].apply(entry, args); + } + + return this; + }, + + /** + * Clears this Set so that it no longer contains any values. + * + * @method Phaser.Structs.Set#clear + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @return {Phaser.Structs.Set} This Set object. + */ + clear: function () + { + this.entries.length = 0; + + return this; + }, + + /** + * Returns `true` if this Set contains the given value, otherwise returns `false`. + * + * @method Phaser.Structs.Set#contains + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {*} value - The value to check for in this Set. + * + * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. + */ + contains: function (value) + { + return (this.entries.indexOf(value) > -1); + }, + + /** + * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. + * + * @method Phaser.Structs.Set#union + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the union with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. + */ + union: function (set) + { + var newSet = new Set(); + + set.entries.forEach(function (value) + { + newSet.set(value); + }); + + this.entries.forEach(function (value) + { + newSet.set(value); + }); + + return newSet; + }, + + /** + * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. + * + * @method Phaser.Structs.Set#intersect + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to intersect this set with. + * + * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. + */ + intersect: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * Returns a new Set containing all the values in this Set which are *not* also in the given Set. + * + * @method Phaser.Structs.Set#difference + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the difference with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. + */ + difference: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (!set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * The size of this Set. This is the number of entries within it. + * Changing the size will truncate the Set if the given value is smaller than the current size. + * Increasing the size larger than the current size has no effect. + * + * @name Phaser.Structs.Set#size + * @type {integer} + * @since 3.0.0 + */ + size: { + + get: function () + { + return this.entries.length; + }, + + set: function (value) + { + if (value < this.entries.length) + { + return this.entries.length = value; + } + else + { + return this.entries.length; + } + } + + } + +}); + +module.exports = Set; + + +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders a filled path for the given Shape. + * + * @method Phaser.GameObjects.Shape#FillPathWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipeline - The WebGL Pipeline used to render this Shape. + * @param {Phaser.GameObjects.Components.TransformMatrix} calcMatrix - The transform matrix used to get the position values. + * @param {Phaser.GameObjects.Shape} src - The Game Object shape being rendered in this call. + * @param {number} alpha - The base alpha value. + * @param {number} dx - The source displayOriginX. + * @param {number} dy - The source displayOriginY. + */ +var FillPathWebGL = function (pipeline, calcMatrix, src, alpha, dx, dy) +{ + var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + var path = src.pathData; + var pathIndexes = src.pathIndexes; + + for (var i = 0; i < pathIndexes.length; i += 3) + { + var p0 = pathIndexes[i] * 2; + var p1 = pathIndexes[i + 1] * 2; + var p2 = pathIndexes[i + 2] * 2; + + var x0 = path[p0 + 0] - dx; + var y0 = path[p0 + 1] - dy; + var x1 = path[p1 + 0] - dx; + var y1 = path[p1 + 1] - dy; + var x2 = path[p2 + 0] - dx; + var y2 = path[p2 + 1] - dy; + + var tx0 = calcMatrix.getX(x0, y0); + var ty0 = calcMatrix.getY(x0, y0); + + var tx1 = calcMatrix.getX(x1, y1); + var ty1 = calcMatrix.getY(x1, y1); + + var tx2 = calcMatrix.getX(x2, y2); + var ty2 = calcMatrix.getY(x2, y2); + + pipeline.setTexture2D(); + + pipeline.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, 0, 0, 1, 1, fillTintColor, fillTintColor, fillTintColor, pipeline.tintEffect); + } +}; + +module.exports = FillPathWebGL; + + +/***/ }), +/* 112 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + * + * @namespace Phaser.Physics.Impact.COLLIDES + * @memberof Phaser.Physics.Impact + * @since 3.0.0 + */ + +module.exports = { + + /** + * Never collides. + * + * @name Phaser.Physics.Impact.COLLIDES.NEVER + * @type {integer} + * @const + * @since 3.0.0 + */ + NEVER: 0, + + /** + * Lite collision. + * + * @name Phaser.Physics.Impact.COLLIDES.LITE + * @type {integer} + * @const + * @since 3.0.0 + */ + LITE: 1, + + /** + * Passive collision. + * + * @name Phaser.Physics.Impact.COLLIDES.PASSIVE + * @type {integer} + * @const + * @since 3.0.0 + */ + PASSIVE: 2, + + /** + * Active collision. + * + * @name Phaser.Physics.Impact.COLLIDES.ACTIVE + * @type {integer} + * @const + * @since 3.0.0 + */ + ACTIVE: 4, + + /** + * Fixed collision. + * + * @name Phaser.Physics.Impact.COLLIDES.FIXED + * @type {integer} + * @const + * @since 3.0.0 + */ + FIXED: 8 + +}; + + +/***/ }), +/* 113 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + * + * @namespace Phaser.Physics.Impact.TYPE + * @memberof Phaser.Physics.Impact + * @since 3.0.0 + */ +module.exports = { + + /** + * Collides with nothing. + * + * @name Phaser.Physics.Impact.TYPE.NONE + * @type {integer} + * @const + * @since 3.0.0 + */ + NONE: 0, + + /** + * Type A. Collides with Type B. + * + * @name Phaser.Physics.Impact.TYPE.A + * @type {integer} + * @const + * @since 3.0.0 + */ + A: 1, + + /** + * Type B. Collides with Type A. + * + * @name Phaser.Physics.Impact.TYPE.B + * @type {integer} + * @const + * @since 3.0.0 + */ + B: 2, + + /** + * Collides with both types A and B. + * + * @name Phaser.Physics.Impact.TYPE.BOTH + * @type {integer} + * @const + * @since 3.0.0 + */ + BOTH: 3 + +}; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports) { + +/** +* The `Matter.Pair` module contains methods for creating and manipulating collision pairs. +* +* @class Pair +*/ + +var Pair = {}; + +module.exports = Pair; + +(function() { + + /** + * Creates a pair. + * @method create + * @param {collision} collision + * @param {number} timestamp + * @return {pair} A new pair + */ + Pair.create = function(collision, timestamp) { + var bodyA = collision.bodyA, + bodyB = collision.bodyB; + + var pair = { + id: Pair.id(bodyA, bodyB), + bodyA: bodyA, + bodyB: bodyB, + activeContacts: [], + separation: 0, + isActive: true, + confirmedActive: true, + isSensor: bodyA.isSensor || bodyB.isSensor, + timeCreated: timestamp, + timeUpdated: timestamp, + collision: null, + inverseMass: 0, + friction: 0, + frictionStatic: 0, + restitution: 0, + slop: 0 + }; + + Pair.update(pair, collision, timestamp); + + return pair; + }; + + /** + * Updates a pair given a collision. + * @method update + * @param {pair} pair + * @param {collision} collision + * @param {number} timestamp + */ + Pair.update = function(pair, collision, timestamp) { + pair.collision = collision; + + if (collision.collided) { + var supports = collision.supports, + activeContacts = pair.activeContacts, + parentA = collision.parentA, + parentB = collision.parentB; + + pair.inverseMass = parentA.inverseMass + parentB.inverseMass; + pair.friction = Math.min(parentA.friction, parentB.friction); + pair.frictionStatic = Math.max(parentA.frictionStatic, parentB.frictionStatic); + pair.restitution = Math.max(parentA.restitution, parentB.restitution); + pair.slop = Math.max(parentA.slop, parentB.slop); + + for (var i = 0; i < supports.length; i++) { + activeContacts[i] = supports[i].contact; + } + + // optimise array size + var supportCount = supports.length; + if (supportCount < activeContacts.length) { + activeContacts.length = supportCount; + } + + pair.separation = collision.depth; + Pair.setActive(pair, true, timestamp); + } else { + if (pair.isActive === true) + Pair.setActive(pair, false, timestamp); + } + }; + + /** + * Set a pair as active or inactive. + * @method setActive + * @param {pair} pair + * @param {bool} isActive + * @param {number} timestamp + */ + Pair.setActive = function(pair, isActive, timestamp) { + if (isActive) { + pair.isActive = true; + pair.timeUpdated = timestamp; + } else { + pair.isActive = false; + pair.activeContacts.length = 0; + } + }; + + /** + * Get the id for the given pair. + * @method id + * @param {body} bodyA + * @param {body} bodyB + * @return {string} Unique pairId + */ + Pair.id = function(bodyA, bodyB) { + if (bodyA.id < bodyB.id) { + return 'A' + bodyA.id + 'B' + bodyB.id; + } else { + return 'A' + bodyB.id + 'B' + bodyA.id; + } + }; + +})(); + + +/***/ }), +/* 115 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the given tile coordinates are within the bounds of the layer. + * + * @function Phaser.Tilemaps.Components.IsInLayerBounds + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {boolean} `true` if the tile coordinates are within the bounds of the layer, otherwise `false`. + */ +var IsInLayerBounds = function (tileX, tileY, layer) +{ + return (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height); +}; + +module.exports = IsInLayerBounds; + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetFastValue = __webpack_require__(1); + +/** + * @classdesc + * A class for representing data about about a layer in a map. Maps are parsed from CSV, Tiled, + * etc. into this format. Tilemap, StaticTilemapLayer and DynamicTilemapLayer have a reference + * to this data and use it to look up and perform operations on tiles. + * + * @class LayerData + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {object} [config] - [description] + */ +var LayerData = new Class({ + + initialize: + + function LayerData (config) + { + if (config === undefined) { config = {}; } + + /** + * The name of the layer, if specified in Tiled. + * + * @name Phaser.Tilemaps.LayerData#name + * @type {string} + * @since 3.0.0 + */ + this.name = GetFastValue(config, 'name', 'layer'); + + /** + * The x offset of where to draw from the top left + * + * @name Phaser.Tilemaps.LayerData#x + * @type {number} + * @since 3.0.0 + */ + this.x = GetFastValue(config, 'x', 0); + + /** + * The y offset of where to draw from the top left + * + * @name Phaser.Tilemaps.LayerData#y + * @type {number} + * @since 3.0.0 + */ + this.y = GetFastValue(config, 'y', 0); + + /** + * The width in tile of the layer. + * + * @name Phaser.Tilemaps.LayerData#width + * @type {number} + * @since 3.0.0 + */ + this.width = GetFastValue(config, 'width', 0); + + /** + * The height in tiles of the layer. + * + * @name Phaser.Tilemaps.LayerData#height + * @type {number} + * @since 3.0.0 + */ + this.height = GetFastValue(config, 'height', 0); + + /** + * The pixel width of the tiles. + * + * @name Phaser.Tilemaps.LayerData#tileWidth + * @type {number} + * @since 3.0.0 + */ + this.tileWidth = GetFastValue(config, 'tileWidth', 0); + + /** + * The pixel height of the tiles. + * + * @name Phaser.Tilemaps.LayerData#tileHeight + * @type {number} + * @since 3.0.0 + */ + this.tileHeight = GetFastValue(config, 'tileHeight', 0); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#baseTileWidth + * @type {number} + * @since 3.0.0 + */ + this.baseTileWidth = GetFastValue(config, 'baseTileWidth', this.tileWidth); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#baseTileHeight + * @type {number} + * @since 3.0.0 + */ + this.baseTileHeight = GetFastValue(config, 'baseTileHeight', this.tileHeight); + + /** + * The width in pixels of the entire layer. + * + * @name Phaser.Tilemaps.LayerData#widthInPixels + * @type {number} + * @since 3.0.0 + */ + this.widthInPixels = GetFastValue(config, 'widthInPixels', this.width * this.baseTileWidth); + + /** + * The height in pixels of the entire layer. + * + * @name Phaser.Tilemaps.LayerData#heightInPixels + * @type {number} + * @since 3.0.0 + */ + this.heightInPixels = GetFastValue(config, 'heightInPixels', this.height * this.baseTileHeight); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#alpha + * @type {number} + * @since 3.0.0 + */ + this.alpha = GetFastValue(config, 'alpha', 1); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#visible + * @type {boolean} + * @since 3.0.0 + */ + this.visible = GetFastValue(config, 'visible', true); + + /** + * Layer specific properties (can be specified in Tiled) + * + * @name Phaser.Tilemaps.LayerData#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = GetFastValue(config, 'properties', {}); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#indexes + * @type {array} + * @since 3.0.0 + */ + this.indexes = GetFastValue(config, 'indexes', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#collideIndexes + * @type {array} + * @since 3.0.0 + */ + this.collideIndexes = GetFastValue(config, 'collideIndexes', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#callbacks + * @type {array} + * @since 3.0.0 + */ + this.callbacks = GetFastValue(config, 'callbacks', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#bodies + * @type {array} + * @since 3.0.0 + */ + this.bodies = GetFastValue(config, 'bodies', []); + + /** + * An array of the tile indexes + * + * @name Phaser.Tilemaps.LayerData#data + * @type {Phaser.Tilemaps.Tile[][]} + * @since 3.0.0 + */ + this.data = GetFastValue(config, 'data', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#tilemapLayer + * @type {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} + * @since 3.0.0 + */ + this.tilemapLayer = GetFastValue(config, 'tilemapLayer', null); + } + +}); + +module.exports = LayerData; + + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetFastValue = __webpack_require__(1); + +/** + * @classdesc + * A class for representing data about a map. Maps are parsed from CSV, Tiled, etc. into this + * format. A Tilemap object get a copy of this data and then unpacks the needed properties into + * itself. + * + * @class MapData + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Tilemaps.MapDataConfig} [config] - The Map configuration object. + */ +var MapData = new Class({ + + initialize: + + function MapData (config) + { + if (config === undefined) { config = {}; } + + /** + * The key in the Phaser cache that corresponds to the loaded tilemap data. + * + * @name Phaser.Tilemaps.MapData#name + * @type {string} + * @since 3.0.0 + */ + this.name = GetFastValue(config, 'name', 'map'); + + /** + * The width of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#width + * @type {number} + * @since 3.0.0 + */ + this.width = GetFastValue(config, 'width', 0); + + /** + * The height of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#height + * @type {number} + * @since 3.0.0 + */ + this.height = GetFastValue(config, 'height', 0); + + /** + * If the map is infinite or not. + * + * @name Phaser.Tilemaps.MapData#infinite + * @type {boolean} + * @since 3.17.0 + */ + this.infinite = GetFastValue(config, 'infinite', false); + + /** + * The width of the tiles. + * + * @name Phaser.Tilemaps.MapData#tileWidth + * @type {number} + * @since 3.0.0 + */ + this.tileWidth = GetFastValue(config, 'tileWidth', 0); + + /** + * The height of the tiles. + * + * @name Phaser.Tilemaps.MapData#tileHeight + * @type {number} + * @since 3.0.0 + */ + this.tileHeight = GetFastValue(config, 'tileHeight', 0); + + /** + * The width in pixels of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#widthInPixels + * @type {number} + * @since 3.0.0 + */ + this.widthInPixels = GetFastValue(config, 'widthInPixels', this.width * this.tileWidth); + + /** + * The height in pixels of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#heightInPixels + * @type {number} + * @since 3.0.0 + */ + this.heightInPixels = GetFastValue(config, 'heightInPixels', this.height * this.tileHeight); + + /** + * [description] + * + * @name Phaser.Tilemaps.MapData#format + * @type {integer} + * @since 3.0.0 + */ + this.format = GetFastValue(config, 'format', null); + + /** + * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. + * + * @name Phaser.Tilemaps.MapData#orientation + * @type {string} + * @since 3.0.0 + */ + this.orientation = GetFastValue(config, 'orientation', 'orthogonal'); + + /** + * Determines the draw order of tilemap. Default is right-down + * + * 0, or 'right-down' + * 1, or 'left-down' + * 2, or 'right-up' + * 3, or 'left-up' + * + * @name Phaser.Tilemaps.MapData#renderOrder + * @type {string} + * @since 3.12.0 + */ + this.renderOrder = GetFastValue(config, 'renderOrder', 'right-down'); + + /** + * The version of the map data (as specified in Tiled). + * + * @name Phaser.Tilemaps.MapData#version + * @type {string} + * @since 3.0.0 + */ + this.version = GetFastValue(config, 'version', '1'); + + /** + * Map specific properties (can be specified in Tiled) + * + * @name Phaser.Tilemaps.MapData#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = GetFastValue(config, 'properties', {}); + + /** + * An array with all the layers configured to the MapData. + * + * @name Phaser.Tilemaps.MapData#layers + * @type {(Phaser.Tilemaps.LayerData[]|Phaser.Tilemaps.ObjectLayer)} + * @since 3.0.0 + */ + this.layers = GetFastValue(config, 'layers', []); + + /** + * An array of Tiled Image Layers. + * + * @name Phaser.Tilemaps.MapData#images + * @type {array} + * @since 3.0.0 + */ + this.images = GetFastValue(config, 'images', []); + + /** + * An object of Tiled Object Layers. + * + * @name Phaser.Tilemaps.MapData#objects + * @type {object} + * @since 3.0.0 + */ + this.objects = GetFastValue(config, 'objects', {}); + + /** + * An object of collision data. Must be created as physics object or will return undefined. + * + * @name Phaser.Tilemaps.MapData#collision + * @type {object} + * @since 3.0.0 + */ + this.collision = GetFastValue(config, 'collision', {}); + + /** + * An array of Tilesets. + * + * @name Phaser.Tilemaps.MapData#tilesets + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tilesets = GetFastValue(config, 'tilesets', []); + + /** + * The collection of images the map uses(specified in Tiled) + * + * @name Phaser.Tilemaps.MapData#imageCollections + * @type {array} + * @since 3.0.0 + */ + this.imageCollections = GetFastValue(config, 'imageCollections', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.MapData#tiles + * @type {array} + * @since 3.0.0 + */ + this.tiles = GetFastValue(config, 'tiles', []); + } + +}); + +module.exports = MapData; + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = __webpack_require__(43); +var Circle = __webpack_require__(71); +var CircleContains = __webpack_require__(60); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var Rectangle = __webpack_require__(11); +var RectangleContains = __webpack_require__(53); + +/** + * @classdesc + * A Zone Game Object. + * + * A Zone is a non-rendering rectangular Game Object that has a position and size. + * It has no texture and never displays, but does live on the display list and + * can be moved, scaled and rotated like any other Game Object. + * + * Its primary use is for creating Drop Zones and Input Hit Areas and it has a couple of helper methods + * specifically for this. It is also useful for object overlap checks, or as a base for your own + * non-displaying Game Objects. + + * The default origin is 0.5, the center of the Zone, the same as with Game Objects. + * + * @class Zone + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Visible + * + * @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 {number} [width=1] - The width of the Game Object. + * @param {number} [height=1] - The height of the Game Object. + */ +var Zone = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Depth, + Components.GetBounds, + Components.Origin, + Components.Transform, + Components.ScrollFactor, + Components.Visible + ], + + initialize: + + function Zone (scene, x, y, width, height) + { + if (width === undefined) { width = 1; } + if (height === undefined) { height = width; } + + GameObject.call(this, scene, 'Zone'); + + this.setPosition(x, y); + + /** + * The native (un-scaled) width of this Game Object. + * + * @name Phaser.GameObjects.Zone#width + * @type {number} + * @since 3.0.0 + */ + this.width = width; + + /** + * The native (un-scaled) height of this Game Object. + * + * @name Phaser.GameObjects.Zone#height + * @type {number} + * @since 3.0.0 + */ + this.height = height; + + /** + * The Blend Mode of the Game Object. + * Although a Zone never renders, it still has a blend mode to allow it to fit seamlessly into + * display lists without causing a batch flush. + * + * @name Phaser.GameObjects.Zone#blendMode + * @type {integer} + * @since 3.0.0 + */ + this.blendMode = BlendModes.NORMAL; + + this.updateDisplayOrigin(); + }, + + /** + * The displayed width of this Game Object. + * This value takes into account the scale factor. + * + * @name Phaser.GameObjects.Zone#displayWidth + * @type {number} + * @since 3.0.0 + */ + displayWidth: { + + get: function () + { + return this.scaleX * this.width; + }, + + set: function (value) + { + this.scaleX = value / this.width; + } + + }, + + /** + * The displayed height of this Game Object. + * This value takes into account the scale factor. + * + * @name Phaser.GameObjects.Zone#displayHeight + * @type {number} + * @since 3.0.0 + */ + displayHeight: { + + get: function () + { + return this.scaleY * this.height; + }, + + set: function (value) + { + this.scaleY = value / this.height; + } + + }, + + /** + * Sets the size of this Game Object. + * + * @method Phaser.GameObjects.Zone#setSize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * @param {boolean} [resizeInput=true] - If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. + * + * @return {Phaser.GameObjects.Zone} This Game Object. + */ + setSize: function (width, height, resizeInput) + { + if (resizeInput === undefined) { resizeInput = true; } + + this.width = width; + this.height = height; + + this.updateDisplayOrigin(); + + var input = this.input; + + if (resizeInput && input && !input.customHitArea) + { + input.hitArea.width = width; + input.hitArea.height = height; + } + + return this; + }, + + /** + * Sets the display size of this Game Object. + * Calling this will adjust the scale. + * + * @method Phaser.GameObjects.Zone#setDisplaySize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {Phaser.GameObjects.Zone} This Game Object. + */ + setDisplaySize: function (width, height) + { + this.displayWidth = width; + this.displayHeight = height; + + return this; + }, + + /** + * Sets this Zone to be a Circular Drop Zone. + * The circle is centered on this Zones `x` and `y` coordinates. + * + * @method Phaser.GameObjects.Zone#setCircleDropZone + * @since 3.0.0 + * + * @param {number} radius - The radius of the Circle that will form the Drop Zone. + * + * @return {Phaser.GameObjects.Zone} This Game Object. + */ + setCircleDropZone: function (radius) + { + return this.setDropZone(new Circle(0, 0, radius), CircleContains); + }, + + /** + * Sets this Zone to be a Rectangle Drop Zone. + * The rectangle is centered on this Zones `x` and `y` coordinates. + * + * @method Phaser.GameObjects.Zone#setRectangleDropZone + * @since 3.0.0 + * + * @param {number} width - The width of the rectangle drop zone. + * @param {number} height - The height of the rectangle drop zone. + * + * @return {Phaser.GameObjects.Zone} This Game Object. + */ + setRectangleDropZone: function (width, height) + { + return this.setDropZone(new Rectangle(0, 0, width, height), RectangleContains); + }, + + /** + * Allows you to define your own Geometry shape to be used as a Drop Zone. + * + * @method Phaser.GameObjects.Zone#setDropZone + * @since 3.0.0 + * + * @param {object} shape - A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. + * @param {Phaser.Types.Input.HitAreaCallback} callback - A function that will return `true` if the given x/y coords it is sent are within the shape. + * + * @return {Phaser.GameObjects.Zone} This Game Object. + */ + setDropZone: function (shape, callback) + { + if (shape === undefined) + { + this.setRectangleDropZone(this.width, this.height); + } + else if (!this.input) + { + this.setInteractive(shape, callback, true); + } + + return this; + }, + + /** + * A NOOP method so you can pass a Zone to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Zone#setAlpha + * @private + * @since 3.11.0 + */ + setAlpha: function () + { + }, + + /** + * A NOOP method so you can pass a Zone to a Container in Canvas. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Zone#setBlendMode + * @private + * @since 3.16.2 + */ + setBlendMode: function () + { + }, + + /** + * A Zone does not render. + * + * @method Phaser.GameObjects.Zone#renderCanvas + * @private + * @since 3.0.0 + */ + renderCanvas: function () + { + }, + + /** + * A Zone does not render. + * + * @method Phaser.GameObjects.Zone#renderWebGL + * @private + * @since 3.0.0 + */ + renderWebGL: function () + { + } + +}); + +module.exports = Zone; + + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Animations.Events + */ + +module.exports = { + + ADD_ANIMATION: __webpack_require__(560), + ANIMATION_COMPLETE: __webpack_require__(561), + ANIMATION_REPEAT: __webpack_require__(562), + ANIMATION_RESTART: __webpack_require__(563), + ANIMATION_START: __webpack_require__(564), + PAUSE_ALL: __webpack_require__(565), + REMOVE_ANIMATION: __webpack_require__(566), + RESUME_ALL: __webpack_require__(567), + SPRITE_ANIMATION_COMPLETE: __webpack_require__(568), + SPRITE_ANIMATION_KEY_COMPLETE: __webpack_require__(569), + SPRITE_ANIMATION_KEY_REPEAT: __webpack_require__(570), + SPRITE_ANIMATION_KEY_RESTART: __webpack_require__(571), + SPRITE_ANIMATION_KEY_START: __webpack_require__(572), + SPRITE_ANIMATION_KEY_UPDATE: __webpack_require__(573), + SPRITE_ANIMATION_REPEAT: __webpack_require__(574), + SPRITE_ANIMATION_RESTART: __webpack_require__(575), + SPRITE_ANIMATION_START: __webpack_require__(576), + SPRITE_ANIMATION_UPDATE: __webpack_require__(577) + +}; + + +/***/ }), +/* 120 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the perimeter of a Rectangle. + * + * @function Phaser.Geom.Rectangle.Perimeter + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to use. + * + * @return {number} The perimeter of the Rectangle, equal to `(width * 2) + (height * 2)`. + */ +var Perimeter = function (rect) +{ + return 2 * (rect.width + rect.height); +}; + +module.exports = Perimeter; + + +/***/ }), +/* 121 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the WebGL rendering pipeline of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Pipeline + * @webglOnly + * @since 3.0.0 + */ + +var Pipeline = { + + /** + * The initial WebGL pipeline of this Game Object. + * + * @name Phaser.GameObjects.Components.Pipeline#defaultPipeline + * @type {Phaser.Renderer.WebGL.WebGLPipeline} + * @default null + * @webglOnly + * @since 3.0.0 + */ + defaultPipeline: null, + + /** + * The current WebGL pipeline of this Game Object. + * + * @name Phaser.GameObjects.Components.Pipeline#pipeline + * @type {Phaser.Renderer.WebGL.WebGLPipeline} + * @default null + * @webglOnly + * @since 3.0.0 + */ + pipeline: null, + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * + * @method Phaser.GameObjects.Components.Pipeline#initPipeline + * @webglOnly + * @since 3.0.0 + * + * @param {string} [pipelineName=TextureTintPipeline] - The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. + * + * @return {boolean} `true` if the pipeline was set successfully, otherwise `false`. + */ + initPipeline: function (pipelineName) + { + if (pipelineName === undefined) { pipelineName = 'TextureTintPipeline'; } + + var renderer = this.scene.sys.game.renderer; + + if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) + { + this.defaultPipeline = renderer.getPipeline(pipelineName); + this.pipeline = this.defaultPipeline; + + return true; + } + + return false; + }, + + /** + * Sets the active WebGL Pipeline of this Game Object. + * + * @method Phaser.GameObjects.Components.Pipeline#setPipeline + * @webglOnly + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline to set on this Game Object. + * + * @return {this} This Game Object instance. + */ + setPipeline: function (pipelineName) + { + var renderer = this.scene.sys.game.renderer; + + if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) + { + this.pipeline = renderer.getPipeline(pipelineName); + } + + return this; + }, + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + * + * @method Phaser.GameObjects.Components.Pipeline#resetPipeline + * @webglOnly + * @since 3.0.0 + * + * @return {boolean} `true` if the pipeline was set successfully, otherwise `false`. + */ + resetPipeline: function () + { + this.pipeline = this.defaultPipeline; + + return (this.pipeline !== null); + }, + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + * + * @method Phaser.GameObjects.Components.Pipeline#getPipelineName + * @webglOnly + * @since 3.0.0 + * + * @return {string} The string-based name of the pipeline being used by this Game Object. + */ + getPipelineName: function () + { + return this.pipeline.name; + } + +}; + +module.exports = Pipeline; + + +/***/ }), +/* 122 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Shuffles the contents of the given array using the Fisher-Yates implementation. + * + * The original array is modified directly and returned. + * + * @function Phaser.Utils.Array.Shuffle + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [array,$return] + * + * @param {T[]} array - The array to shuffle. This array is modified in place. + * + * @return {T[]} The shuffled array. + */ +var Shuffle = function (array) +{ + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; +}; + +module.exports = Shuffle; + + +/***/ }), +/* 123 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates a linear (interpolation) value over t. + * + * @function Phaser.Math.Linear + * @since 3.0.0 + * + * @param {number} p0 - The first point. + * @param {number} p1 - The second point. + * @param {number} t - The percentage between p0 and p1 to return, represented as a number between 0 and 1. + * + * @return {number} The step t% of the way between p0 and p1. + */ +var Linear = function (p0, p1, t) +{ + return (p1 - p0) * t + p0; +}; + +module.exports = Linear; + + +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process) {/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines the operating system of the device 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.os` from within any Scene. + * + * @typedef {object} Phaser.Device.OS + * @since 3.0.0 + * + * @property {boolean} android - Is running on android? + * @property {boolean} chromeOS - Is running on chromeOS? + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @property {boolean} desktop - Is running on a desktop? + * @property {boolean} ejecta - Is the game running under Ejecta? + * @property {boolean} electron - Is the game running under GitHub Electron? + * @property {boolean} iOS - Is running on iOS? + * @property {boolean} iPad - Is running on iPad? + * @property {boolean} iPhone - Is running on iPhone? + * @property {boolean} kindle - Is running on an Amazon Kindle? + * @property {boolean} linux - Is running on linux? + * @property {boolean} macOS - Is running on macOS? + * @property {boolean} node - Is the game running under Node.js? + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @property {boolean} windows - Is running on windows? + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @property {number} pixelRatio - PixelRatio of the host device? + */ +var OS = { + + android: false, + chromeOS: false, + cordova: false, + crosswalk: false, + desktop: false, + ejecta: false, + electron: false, + iOS: false, + iOSVersion: 0, + iPad: false, + iPhone: false, + kindle: false, + linux: false, + macOS: false, + node: false, + nodeWebkit: false, + pixelRatio: 1, + webApp: false, + windows: false, + windowsPhone: false + +}; + +function init () +{ + var ua = navigator.userAgent; + + if (/Windows/.test(ua)) + { + OS.windows = true; + } + else if (/Mac OS/.test(ua) && !(/like Mac OS/.test(ua))) + { + OS.macOS = true; + } + else if (/Android/.test(ua)) + { + OS.android = true; + } + else if (/Linux/.test(ua)) + { + OS.linux = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + OS.iOS = true; + + (navigator.appVersion).match(/OS (\d+)/); + + OS.iOSVersion = parseInt(RegExp.$1, 10); + + OS.iPhone = ua.toLowerCase().indexOf('iphone') !== -1; + OS.iPad = ua.toLowerCase().indexOf('ipad') !== -1; + } + else if (/Kindle/.test(ua) || (/\bKF[A-Z][A-Z]+/).test(ua) || (/Silk.*Mobile Safari/).test(ua)) + { + OS.kindle = true; + + // 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" + } + else if (/CrOS/.test(ua)) + { + OS.chromeOS = true; + } + + if (/Windows Phone/i.test(ua) || (/IEMobile/i).test(ua)) + { + OS.android = false; + OS.iOS = false; + OS.macOS = false; + OS.windows = true; + OS.windowsPhone = true; + } + + var silk = (/Silk/).test(ua); + + if (OS.windows || OS.macOS || (OS.linux && !silk) || OS.chromeOS) + { + OS.desktop = true; + } + + // Windows Phone / Table reset + if (OS.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + OS.desktop = false; + } + + // WebApp mode in iOS + if (navigator.standalone) + { + OS.webApp = true; + } + + if (window.cordova !== undefined) + { + OS.cordova = true; + } + + if (typeof process !== 'undefined' && process.versions && process.versions.node) + { + OS.node = true; + } + + if (OS.node && typeof process.versions === 'object') + { + OS.nodeWebkit = !!process.versions['node-webkit']; + + OS.electron = !!process.versions.electron; + } + + if (window.ejecta !== undefined) + { + OS.ejecta = true; + } + + if ((/Crosswalk/).test(ua)) + { + OS.crosswalk = true; + } + + OS.pixelRatio = window['devicePixelRatio'] || 1; + + return OS; +} + +module.exports = init(); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(752))) + +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var OS = __webpack_require__(124); + +/** + * 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+) + * @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} + */ +var Browser = { + + chrome: false, + chromeVersion: 0, + edge: false, + firefox: false, + firefoxVersion: 0, + ie: false, + ieVersion: 0, + mobileSafari: false, + opera: false, + safari: false, + safariVersion: 0, + silk: false, + trident: false, + tridentVersion: 0 + +}; + +function init () +{ + var ua = navigator.userAgent; + + if (/Edge\/\d+/.test(ua)) + { + Browser.edge = true; + } + else if ((/Chrome\/(\d+)/).test(ua) && !OS.windowsPhone) + { + Browser.chrome = true; + Browser.chromeVersion = parseInt(RegExp.$1, 10); + } + else if ((/Firefox\D+(\d+)/).test(ua)) + { + Browser.firefox = true; + Browser.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if ((/AppleWebKit/).test(ua) && OS.iOS) + { + Browser.mobileSafari = true; + } + else if ((/MSIE (\d+\.\d+);/).test(ua)) + { + Browser.ie = true; + Browser.ieVersion = parseInt(RegExp.$1, 10); + } + else if ((/Opera/).test(ua)) + { + Browser.opera = true; + } + else if ((/Safari/).test(ua) && !OS.windowsPhone) + { + Browser.safari = true; + } + else if ((/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/).test(ua)) + { + Browser.ie = true; + Browser.trident = true; + Browser.tridentVersion = parseInt(RegExp.$1, 10); + Browser.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if ((/Silk/).test(ua)) + { + Browser.silk = true; + } + + return Browser; +} + +module.exports = init(); + + +/***/ }), +/* 126 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check whether the given values are fuzzily equal. + * + * Two numbers are fuzzily equal if their difference is less than `epsilon`. + * + * @function Phaser.Math.Fuzzy.Equal + * @since 3.0.0 + * + * @param {number} a - The first value. + * @param {number} b - The second value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {boolean} `true` if the values are fuzzily equal, otherwise `false`. + */ +var Equal = function (a, b, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.abs(a - b) < epsilon; +}; + +module.exports = Equal; + + +/***/ }), +/* 127 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the given `width` and `height` are a power of two. + * Useful for checking texture dimensions. + * + * @function Phaser.Math.Pow2.IsSize + * @since 3.0.0 + * + * @param {number} width - The width. + * @param {number} height - The height. + * + * @return {boolean} `true` if `width` and `height` are a power of two, otherwise `false`. + */ +var IsSizePowerOfTwo = function (width, height) +{ + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); +}; + +module.exports = IsSizePowerOfTwo; + + +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Textures.Events + */ + +module.exports = { + + ADD: __webpack_require__(803), + ERROR: __webpack_require__(804), + LOAD: __webpack_require__(805), + READY: __webpack_require__(806), + REMOVE: __webpack_require__(807) + +}; + + +/***/ }), +/* 129 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds the given element to the DOM. If a parent is provided the element is added as a child of the parent, providing it was able to access it. + * If no parent was given it falls back to using `document.body`. + * + * @function Phaser.DOM.AddToDOM + * @since 3.0.0 + * + * @param {HTMLElement} element - The element to be added to the DOM. Usually a Canvas object. + * @param {(string|HTMLElement)} [parent] - The parent in which to add the element. Can be a string which is passed to `getElementById` or an actual DOM object. + * + * @return {HTMLElement} The element that was added to the DOM. + */ +var AddToDOM = function (element, parent) +{ + var target; + + if (parent) + { + if (typeof parent === 'string') + { + // Hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // Quick test for a HTMLElement + target = parent; + } + } + else if (element.parentElement) + { + return element; + } + + // Fallback, covers an invalid ID and a non HTMLElement object + if (!target) + { + target = document.body; + } + + target.appendChild(element); + + return element; +}; + +module.exports = AddToDOM; + + +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SpliceOne = __webpack_require__(85); + +/** + * Removes the given item, or array of items, from the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for each item successfully removed from the array. + * + * @function Phaser.Utils.Array.Remove + * @since 3.4.0 + * + * @param {array} array - The array to be modified. + * @param {*|Array.<*>} item - The item, or array of items, to be removed from the array. + * @param {function} [callback] - A callback to be invoked for each item successfully removed from the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {*|Array.<*>} The item, or array of items, that were successfully removed from the array. + */ +var Remove = function (array, item, callback, context) +{ + if (context === undefined) { context = array; } + + var index; + + // Fast path to avoid array mutation and iteration + if (!Array.isArray(item)) + { + index = array.indexOf(item); + + if (index !== -1) + { + SpliceOne(array, index); + + if (callback) + { + callback.call(context, item); + } + + return item; + } + else + { + return null; + } + } + + // If we got this far, we have an array of items to remove + + var itemLength = item.length - 1; + + while (itemLength >= 0) + { + var entry = item[itemLength]; + + index = array.indexOf(entry); + + if (index !== -1) + { + SpliceOne(array, index); + + if (callback) + { + callback.call(context, entry); + } + } + else + { + // Item wasn't found in the array, so remove it from our return results + item.pop(); + } + + itemLength--; + } + + return item; +}; + +module.exports = Remove; + + +/***/ }), +/* 131 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Keyboard Codes. + * + * @namespace Phaser.Input.Keyboard.KeyCodes + * @memberof Phaser.Input.Keyboard + * @since 3.0.0 + */ + +var KeyCodes = { + + /** + * The BACKSPACE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BACKSPACE + * @type {integer} + * @since 3.0.0 + */ + BACKSPACE: 8, + + /** + * The TAB key. + * + * @name Phaser.Input.Keyboard.KeyCodes.TAB + * @type {integer} + * @since 3.0.0 + */ + TAB: 9, + + /** + * The ENTER key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ENTER + * @type {integer} + * @since 3.0.0 + */ + ENTER: 13, + + /** + * The SHIFT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SHIFT + * @type {integer} + * @since 3.0.0 + */ + SHIFT: 16, + + /** + * The CTRL key. + * + * @name Phaser.Input.Keyboard.KeyCodes.CTRL + * @type {integer} + * @since 3.0.0 + */ + CTRL: 17, + + /** + * The ALT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ALT + * @type {integer} + * @since 3.0.0 + */ + ALT: 18, + + /** + * The PAUSE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PAUSE + * @type {integer} + * @since 3.0.0 + */ + PAUSE: 19, + + /** + * The CAPS_LOCK key. + * + * @name Phaser.Input.Keyboard.KeyCodes.CAPS_LOCK + * @type {integer} + * @since 3.0.0 + */ + CAPS_LOCK: 20, + + /** + * The ESC key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ESC + * @type {integer} + * @since 3.0.0 + */ + ESC: 27, + + /** + * The SPACE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SPACE + * @type {integer} + * @since 3.0.0 + */ + SPACE: 32, + + /** + * The PAGE_UP key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PAGE_UP + * @type {integer} + * @since 3.0.0 + */ + PAGE_UP: 33, + + /** + * The PAGE_DOWN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PAGE_DOWN + * @type {integer} + * @since 3.0.0 + */ + PAGE_DOWN: 34, + + /** + * The END key. + * + * @name Phaser.Input.Keyboard.KeyCodes.END + * @type {integer} + * @since 3.0.0 + */ + END: 35, + + /** + * The HOME key. + * + * @name Phaser.Input.Keyboard.KeyCodes.HOME + * @type {integer} + * @since 3.0.0 + */ + HOME: 36, + + /** + * The LEFT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.LEFT + * @type {integer} + * @since 3.0.0 + */ + LEFT: 37, + + /** + * The UP key. + * + * @name Phaser.Input.Keyboard.KeyCodes.UP + * @type {integer} + * @since 3.0.0 + */ + UP: 38, + + /** + * The RIGHT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.RIGHT + * @type {integer} + * @since 3.0.0 + */ + RIGHT: 39, + + /** + * The DOWN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.DOWN + * @type {integer} + * @since 3.0.0 + */ + DOWN: 40, + + /** + * The PRINT_SCREEN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PRINT_SCREEN + * @type {integer} + * @since 3.0.0 + */ + PRINT_SCREEN: 42, + + /** + * The INSERT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.INSERT + * @type {integer} + * @since 3.0.0 + */ + INSERT: 45, + + /** + * The DELETE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.DELETE + * @type {integer} + * @since 3.0.0 + */ + DELETE: 46, + + /** + * The ZERO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ZERO + * @type {integer} + * @since 3.0.0 + */ + ZERO: 48, + + /** + * The ONE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ONE + * @type {integer} + * @since 3.0.0 + */ + ONE: 49, + + /** + * The TWO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.TWO + * @type {integer} + * @since 3.0.0 + */ + TWO: 50, + + /** + * The THREE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.THREE + * @type {integer} + * @since 3.0.0 + */ + THREE: 51, + + /** + * The FOUR key. + * + * @name Phaser.Input.Keyboard.KeyCodes.FOUR + * @type {integer} + * @since 3.0.0 + */ + FOUR: 52, + + /** + * The FIVE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.FIVE + * @type {integer} + * @since 3.0.0 + */ + FIVE: 53, + + /** + * The SIX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SIX + * @type {integer} + * @since 3.0.0 + */ + SIX: 54, + + /** + * The SEVEN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SEVEN + * @type {integer} + * @since 3.0.0 + */ + SEVEN: 55, + + /** + * The EIGHT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.EIGHT + * @type {integer} + * @since 3.0.0 + */ + EIGHT: 56, + + /** + * The NINE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NINE + * @type {integer} + * @since 3.0.0 + */ + NINE: 57, + + /** + * The NUMPAD_ZERO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ZERO + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_ZERO: 96, + + /** + * The NUMPAD_ONE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ONE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_ONE: 97, + + /** + * The NUMPAD_TWO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_TWO + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_TWO: 98, + + /** + * The NUMPAD_THREE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_THREE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_THREE: 99, + + /** + * The NUMPAD_FOUR key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_FOUR + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_FOUR: 100, + + /** + * The NUMPAD_FIVE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_FIVE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_FIVE: 101, + + /** + * The NUMPAD_SIX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SIX + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_SIX: 102, + + /** + * The NUMPAD_SEVEN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SEVEN + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_SEVEN: 103, + + /** + * The NUMPAD_EIGHT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_EIGHT + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_EIGHT: 104, + + /** + * The NUMPAD_NINE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_NINE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_NINE: 105, + + /** + * The Numpad Addition (+) key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ADD + * @type {integer} + * @since 3.21.0 + */ + NUMPAD_ADD: 107, + + /** + * The Numpad Subtraction (-) key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SUBTRACT + * @type {integer} + * @since 3.21.0 + */ + NUMPAD_SUBTRACT: 109, + + /** + * The A key. + * + * @name Phaser.Input.Keyboard.KeyCodes.A + * @type {integer} + * @since 3.0.0 + */ + A: 65, + + /** + * The B key. + * + * @name Phaser.Input.Keyboard.KeyCodes.B + * @type {integer} + * @since 3.0.0 + */ + B: 66, + + /** + * The C key. + * + * @name Phaser.Input.Keyboard.KeyCodes.C + * @type {integer} + * @since 3.0.0 + */ + C: 67, + + /** + * The D key. + * + * @name Phaser.Input.Keyboard.KeyCodes.D + * @type {integer} + * @since 3.0.0 + */ + D: 68, + + /** + * The E key. + * + * @name Phaser.Input.Keyboard.KeyCodes.E + * @type {integer} + * @since 3.0.0 + */ + E: 69, + + /** + * The F key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F + * @type {integer} + * @since 3.0.0 + */ + F: 70, + + /** + * The G key. + * + * @name Phaser.Input.Keyboard.KeyCodes.G + * @type {integer} + * @since 3.0.0 + */ + G: 71, + + /** + * The H key. + * + * @name Phaser.Input.Keyboard.KeyCodes.H + * @type {integer} + * @since 3.0.0 + */ + H: 72, + + /** + * The I key. + * + * @name Phaser.Input.Keyboard.KeyCodes.I + * @type {integer} + * @since 3.0.0 + */ + I: 73, + + /** + * The J key. + * + * @name Phaser.Input.Keyboard.KeyCodes.J + * @type {integer} + * @since 3.0.0 + */ + J: 74, + + /** + * The K key. + * + * @name Phaser.Input.Keyboard.KeyCodes.K + * @type {integer} + * @since 3.0.0 + */ + K: 75, + + /** + * The L key. + * + * @name Phaser.Input.Keyboard.KeyCodes.L + * @type {integer} + * @since 3.0.0 + */ + L: 76, + + /** + * The M key. + * + * @name Phaser.Input.Keyboard.KeyCodes.M + * @type {integer} + * @since 3.0.0 + */ + M: 77, + + /** + * The N key. + * + * @name Phaser.Input.Keyboard.KeyCodes.N + * @type {integer} + * @since 3.0.0 + */ + N: 78, + + /** + * The O key. + * + * @name Phaser.Input.Keyboard.KeyCodes.O + * @type {integer} + * @since 3.0.0 + */ + O: 79, + + /** + * The P key. + * + * @name Phaser.Input.Keyboard.KeyCodes.P + * @type {integer} + * @since 3.0.0 + */ + P: 80, + + /** + * The Q key. + * + * @name Phaser.Input.Keyboard.KeyCodes.Q + * @type {integer} + * @since 3.0.0 + */ + Q: 81, + + /** + * The R key. + * + * @name Phaser.Input.Keyboard.KeyCodes.R + * @type {integer} + * @since 3.0.0 + */ + R: 82, + + /** + * The S key. + * + * @name Phaser.Input.Keyboard.KeyCodes.S + * @type {integer} + * @since 3.0.0 + */ + S: 83, + + /** + * The T key. + * + * @name Phaser.Input.Keyboard.KeyCodes.T + * @type {integer} + * @since 3.0.0 + */ + T: 84, + + /** + * The U key. + * + * @name Phaser.Input.Keyboard.KeyCodes.U + * @type {integer} + * @since 3.0.0 + */ + U: 85, + + /** + * The V key. + * + * @name Phaser.Input.Keyboard.KeyCodes.V + * @type {integer} + * @since 3.0.0 + */ + V: 86, + + /** + * The W key. + * + * @name Phaser.Input.Keyboard.KeyCodes.W + * @type {integer} + * @since 3.0.0 + */ + W: 87, + + /** + * The X key. + * + * @name Phaser.Input.Keyboard.KeyCodes.X + * @type {integer} + * @since 3.0.0 + */ + X: 88, + + /** + * The Y key. + * + * @name Phaser.Input.Keyboard.KeyCodes.Y + * @type {integer} + * @since 3.0.0 + */ + Y: 89, + + /** + * The Z key. + * + * @name Phaser.Input.Keyboard.KeyCodes.Z + * @type {integer} + * @since 3.0.0 + */ + Z: 90, + + /** + * The F1 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F1 + * @type {integer} + * @since 3.0.0 + */ + F1: 112, + + /** + * The F2 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F2 + * @type {integer} + * @since 3.0.0 + */ + F2: 113, + + /** + * The F3 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F3 + * @type {integer} + * @since 3.0.0 + */ + F3: 114, + + /** + * The F4 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F4 + * @type {integer} + * @since 3.0.0 + */ + F4: 115, + + /** + * The F5 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F5 + * @type {integer} + * @since 3.0.0 + */ + F5: 116, + + /** + * The F6 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F6 + * @type {integer} + * @since 3.0.0 + */ + F6: 117, + + /** + * The F7 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F7 + * @type {integer} + * @since 3.0.0 + */ + F7: 118, + + /** + * The F8 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F8 + * @type {integer} + * @since 3.0.0 + */ + F8: 119, + + /** + * The F9 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F9 + * @type {integer} + * @since 3.0.0 + */ + F9: 120, + + /** + * The F10 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F10 + * @type {integer} + * @since 3.0.0 + */ + F10: 121, + + /** + * The F11 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F11 + * @type {integer} + * @since 3.0.0 + */ + F11: 122, + + /** + * The F12 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F12 + * @type {integer} + * @since 3.0.0 + */ + F12: 123, + + /** + * The SEMICOLON key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SEMICOLON + * @type {integer} + * @since 3.0.0 + */ + SEMICOLON: 186, + + /** + * The PLUS key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PLUS + * @type {integer} + * @since 3.0.0 + */ + PLUS: 187, + + /** + * The COMMA key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COMMA + * @type {integer} + * @since 3.0.0 + */ + COMMA: 188, + + /** + * The MINUS key. + * + * @name Phaser.Input.Keyboard.KeyCodes.MINUS + * @type {integer} + * @since 3.0.0 + */ + MINUS: 189, + + /** + * The PERIOD key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PERIOD + * @type {integer} + * @since 3.0.0 + */ + PERIOD: 190, + + /** + * The FORWARD_SLASH key. + * + * @name Phaser.Input.Keyboard.KeyCodes.FORWARD_SLASH + * @type {integer} + * @since 3.0.0 + */ + FORWARD_SLASH: 191, + + /** + * The BACK_SLASH key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BACK_SLASH + * @type {integer} + * @since 3.0.0 + */ + BACK_SLASH: 220, + + /** + * The QUOTES key. + * + * @name Phaser.Input.Keyboard.KeyCodes.QUOTES + * @type {integer} + * @since 3.0.0 + */ + QUOTES: 222, + + /** + * The BACKTICK key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BACKTICK + * @type {integer} + * @since 3.0.0 + */ + BACKTICK: 192, + + /** + * The OPEN_BRACKET key. + * + * @name Phaser.Input.Keyboard.KeyCodes.OPEN_BRACKET + * @type {integer} + * @since 3.0.0 + */ + OPEN_BRACKET: 219, + + /** + * The CLOSED_BRACKET key. + * + * @name Phaser.Input.Keyboard.KeyCodes.CLOSED_BRACKET + * @type {integer} + * @since 3.0.0 + */ + CLOSED_BRACKET: 221, + + /** + * The SEMICOLON_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SEMICOLON_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + SEMICOLON_FIREFOX: 59, + + /** + * The COLON key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COLON + * @type {integer} + * @since 3.0.0 + */ + COLON: 58, + + /** + * The COMMA_FIREFOX_WINDOWS key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COMMA_FIREFOX_WINDOWS + * @type {integer} + * @since 3.0.0 + */ + COMMA_FIREFOX_WINDOWS: 60, + + /** + * The COMMA_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COMMA_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + COMMA_FIREFOX: 62, + + /** + * The BRACKET_RIGHT_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BRACKET_RIGHT_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + BRACKET_RIGHT_FIREFOX: 174, + + /** + * The BRACKET_LEFT_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BRACKET_LEFT_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + BRACKET_LEFT_FIREFOX: 175 +}; + +module.exports = KeyCodes; + + +/***/ }), +/* 132 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Scene consts. + * + * @ignore + */ + +var CONST = { + + /** + * Scene state. + * + * @name Phaser.Scenes.PENDING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + PENDING: 0, + + /** + * Scene state. + * + * @name Phaser.Scenes.INIT + * @readonly + * @type {integer} + * @since 3.0.0 + */ + INIT: 1, + + /** + * Scene state. + * + * @name Phaser.Scenes.START + * @readonly + * @type {integer} + * @since 3.0.0 + */ + START: 2, + + /** + * Scene state. + * + * @name Phaser.Scenes.LOADING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + LOADING: 3, + + /** + * Scene state. + * + * @name Phaser.Scenes.CREATING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + CREATING: 4, + + /** + * Scene state. + * + * @name Phaser.Scenes.RUNNING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + RUNNING: 5, + + /** + * Scene state. + * + * @name Phaser.Scenes.PAUSED + * @readonly + * @type {integer} + * @since 3.0.0 + */ + PAUSED: 6, + + /** + * Scene state. + * + * @name Phaser.Scenes.SLEEPING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + SLEEPING: 7, + + /** + * Scene state. + * + * @name Phaser.Scenes.SHUTDOWN + * @readonly + * @type {integer} + * @since 3.0.0 + */ + SHUTDOWN: 8, + + /** + * Scene state. + * + * @name Phaser.Scenes.DESTROYED + * @readonly + * @type {integer} + * @since 3.0.0 + */ + DESTROYED: 9 + +}; + +module.exports = CONST; + + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Clone = __webpack_require__(73); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(64); +var GameEvents = __webpack_require__(21); +var NOOP = __webpack_require__(2); + +/** + * @classdesc + * The sound manager is responsible for playing back audio via Web Audio API or HTML Audio tag as fallback. + * The audio file type and the encoding of those files are extremely important. + * + * Not all browsers can play all audio formats. + * + * There is a good guide to what's supported [here](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support). + * + * @class BaseSoundManager + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var BaseSoundManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function BaseSoundManager (game) + { + EventEmitter.call(this); + + /** + * Local reference to game. + * + * @name Phaser.Sound.BaseSoundManager#game + * @type {Phaser.Game} + * @readonly + * @since 3.0.0 + */ + this.game = game; + + /** + * Local reference to the JSON Cache, as used by Audio Sprites. + * + * @name Phaser.Sound.BaseSoundManager#jsonCache + * @type {Phaser.Cache.BaseCache} + * @readonly + * @since 3.7.0 + */ + this.jsonCache = game.cache.json; + + /** + * An array containing all added sounds. + * + * @name Phaser.Sound.BaseSoundManager#sounds + * @type {Phaser.Sound.BaseSound[]} + * @default [] + * @private + * @since 3.0.0 + */ + this.sounds = []; + + /** + * Global mute setting. + * + * @name Phaser.Sound.BaseSoundManager#mute + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.mute = false; + + /** + * Global volume setting. + * + * @name Phaser.Sound.BaseSoundManager#volume + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.volume = 1; + + /** + * Flag indicating if sounds should be paused when game looses focus, + * for instance when user switches to another tab/program/app. + * + * @name Phaser.Sound.BaseSoundManager#pauseOnBlur + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.pauseOnBlur = true; + + /** + * Property that actually holds the value of global playback rate. + * + * @name Phaser.Sound.BaseSoundManager#_rate + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + this._rate = 1; + + /** + * Property that actually holds the value of global detune. + * + * @name Phaser.Sound.BaseSoundManager#_detune + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._detune = 0; + + /** + * Mobile devices require sounds to be triggered from an explicit user action, + * such as a tap, before any sound can be loaded/played on a web page. + * Set to true if the audio system is currently locked awaiting user interaction. + * + * @name Phaser.Sound.BaseSoundManager#locked + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.locked = this.locked || false; + + /** + * Flag used internally for handling when the audio system + * has been unlocked, if there ever was a need for it. + * + * @name Phaser.Sound.BaseSoundManager#unlocked + * @type {boolean} + * @default false + * @private + * @since 3.0.0 + */ + this.unlocked = false; + + game.events.on(GameEvents.BLUR, function () + { + if (this.pauseOnBlur) + { + this.onBlur(); + } + }, this); + + game.events.on(GameEvents.FOCUS, function () + { + if (this.pauseOnBlur) + { + this.onFocus(); + } + }, this); + + game.events.on(GameEvents.PRE_STEP, this.update, this); + game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Adds a new sound into the sound manager. + * + * @method Phaser.Sound.BaseSoundManager#add + * @override + * @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.BaseSound} The new sound instance. + */ + add: NOOP, + + /** + * 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.HTML5AudioSound|Phaser.Sound.WebAudioSound)} The new audio sprite sound instance. + */ + addAudioSprite: function (key, config) + { + if (config === undefined) { config = {}; } + + var sound = this.add(key, config); + + sound.spritemap = this.jsonCache.get(key).spritemap; + + for (var markerName in sound.spritemap) + { + if (!sound.spritemap.hasOwnProperty(markerName)) + { + continue; + } + + var markerConfig = Clone(config); + + var marker = sound.spritemap[markerName]; + + markerConfig.loop = (marker.hasOwnProperty('loop')) ? marker.loop : false; + + sound.addMarker({ + name: markerName, + start: marker.start, + duration: marker.end - marker.start, + config: markerConfig + }); + } + + return sound; + }, + + /** + * Adds a new sound to the sound manager and plays it. + * The sound will be automatically removed (destroyed) once playback ends. + * This lets you play a new sound on the fly without the need to keep a reference to it. + * + * @method Phaser.Sound.BaseSoundManager#play + * @listens Phaser.Sound.Events#COMPLETE + * @since 3.0.0 + * + * @param {string} key - Asset key for the sound. + * @param {(Phaser.Types.Sound.SoundConfig|Phaser.Types.Sound.SoundMarker)} [extra] - An optional additional object containing settings to be applied to the sound. It could be either config or marker object. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (key, extra) + { + var sound = this.add(key); + + sound.once(Events.COMPLETE, sound.destroy, sound); + + if (extra) + { + if (extra.name) + { + sound.addMarker(extra); + + return sound.play(extra.name); + } + else + { + return sound.play(extra); + } + } + else + { + return sound.play(); + } + }, + + /** + * Enables playing audio sprite sound on the fly without the need to keep a reference to it. + * Sound will auto destroy once its playback ends. + * + * @method Phaser.Sound.BaseSoundManager#playAudioSprite + * @listens Phaser.Sound.Events#COMPLETE + * @since 3.0.0 + * + * @param {string} key - Asset key for the sound. + * @param {string} spriteName - The name of the sound sprite to play. + * @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings. + * + * @return {boolean} Whether the audio sprite sound started playing successfully. + */ + playAudioSprite: function (key, spriteName, config) + { + var sound = this.addAudioSprite(key); + + sound.once(Events.COMPLETE, sound.destroy, sound); + + return sound.play(spriteName, config); + }, + + /** + * Removes a sound from the sound manager. + * The removed sound is destroyed before removal. + * + * @method Phaser.Sound.BaseSoundManager#remove + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSound} sound - The sound object to remove. + * + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) + { + var index = this.sounds.indexOf(sound); + + if (index !== -1) + { + sound.destroy(); + + this.sounds.splice(index, 1); + + return true; + } + + return false; + }, + + /** + * Removes all sounds from the sound manager that have an asset key matching the given value. + * The removed sounds are destroyed before removal. + * + * @method Phaser.Sound.BaseSoundManager#removeByKey + * @since 3.0.0 + * + * @param {string} key - The key to match when removing sound objects. + * + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) + { + var removed = 0; + + for (var i = this.sounds.length - 1; i >= 0; i--) + { + var sound = this.sounds[i]; + + if (sound.key === key) + { + sound.destroy(); + + this.sounds.splice(i, 1); + + removed++; + } + } + + return removed; + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.Sound.BaseSoundManager#pauseAll + * @fires Phaser.Sound.Events#PAUSE_ALL + * @since 3.0.0 + */ + pauseAll: function () + { + this.forEachActiveSound(function (sound) + { + sound.pause(); + }); + + this.emit(Events.PAUSE_ALL, this); + }, + + /** + * Resumes all the sounds in the game. + * + * @method Phaser.Sound.BaseSoundManager#resumeAll + * @fires Phaser.Sound.Events#RESUME_ALL + * @since 3.0.0 + */ + resumeAll: function () + { + this.forEachActiveSound(function (sound) + { + sound.resume(); + }); + + this.emit(Events.RESUME_ALL, this); + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.Sound.BaseSoundManager#stopAll + * @fires Phaser.Sound.Events#STOP_ALL + * @since 3.0.0 + */ + stopAll: function () + { + this.forEachActiveSound(function (sound) + { + sound.stop(); + }); + + this.emit(Events.STOP_ALL, this); + }, + + /** + * 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 + */ + unlock: NOOP, + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.BaseSoundManager#onBlur + * @override + * @protected + * @since 3.0.0 + */ + onBlur: NOOP, + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.BaseSoundManager#onFocus + * @override + * @protected + * @since 3.0.0 + */ + onFocus: NOOP, + + /** + * Update method called on every game step. + * Removes destroyed sounds and updates every active sound in the game. + * + * @method Phaser.Sound.BaseSoundManager#update + * @protected + * @fires Phaser.Sound.Events#UNLOCKED + * @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 elapsed since the last frame. + */ + update: function (time, delta) + { + if (this.unlocked) + { + this.unlocked = false; + this.locked = false; + + this.emit(Events.UNLOCKED, this); + } + + for (var i = this.sounds.length - 1; i >= 0; i--) + { + if (this.sounds[i].pendingRemove) + { + this.sounds.splice(i, 1); + } + } + + this.sounds.forEach(function (sound) + { + sound.update(time, delta); + }); + }, + + /** + * Destroys all the sounds in the game and all associated events. + * + * @method Phaser.Sound.BaseSoundManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.forEachActiveSound(function (sound) + { + sound.destroy(); + }); + + this.sounds.length = 0; + this.sounds = null; + + this.game = null; + }, + + /** + * Method used internally for iterating only over active sounds and skipping sounds that are marked for removal. + * + * @method Phaser.Sound.BaseSoundManager#forEachActiveSound + * @private + * @since 3.0.0 + * + * @param {Phaser.Types.Sound.EachActiveSoundCallback} callback - Callback function. (manager: Phaser.Sound.BaseSoundManager, sound: Phaser.Sound.BaseSound, index: number, sounds: Phaser.Manager.BaseSound[]) => void + * @param {*} [scope] - Callback context. + */ + forEachActiveSound: function (callback, scope) + { + var _this = this; + + this.sounds.forEach(function (sound, index) + { + if (sound && !sound.pendingRemove) + { + callback.call(scope || _this, sound, index, _this.sounds); + } + }); + }, + + /** + * Sets the global playback rate at which all the sounds will be played. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @method Phaser.Sound.BaseSoundManager#setRate + * @fires Phaser.Sound.Events#GLOBAL_RATE + * @since 3.3.0 + * + * @param {number} value - Global playback rate at which all the sounds will be played. + * + * @return {Phaser.Sound.BaseSoundManager} This Sound Manager. + */ + setRate: function (value) + { + this.rate = value; + + return this; + }, + + /** + * Global playback rate at which all the sounds will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audio's playback speed. + * + * @name Phaser.Sound.BaseSoundManager#rate + * @type {number} + * @default 1 + * @since 3.0.0 + */ + rate: { + + get: function () + { + return this._rate; + }, + + set: function (value) + { + this._rate = value; + + this.forEachActiveSound(function (sound) + { + sound.calculateRate(); + }); + + this.emit(Events.GLOBAL_RATE, this, value); + } + + }, + + /** + * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + * + * @method Phaser.Sound.BaseSoundManager#setDetune + * @fires Phaser.Sound.Events#GLOBAL_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 {Phaser.Sound.BaseSoundManager} This Sound Manager. + */ + setDetune: function (value) + { + this.detune = value; + + return this; + }, + + /** + * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + * + * @name Phaser.Sound.BaseSoundManager#detune + * @type {number} + * @default 0 + * @since 3.0.0 + */ + detune: { + + get: function () + { + return this._detune; + }, + + set: function (value) + { + this._detune = value; + + this.forEachActiveSound(function (sound) + { + sound.calculateRate(); + }); + + this.emit(Events.GLOBAL_DETUNE, this, value); + } + + } + +}); + +module.exports = BaseSoundManager; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(64); +var Extend = __webpack_require__(17); +var NOOP = __webpack_require__(2); + +/** + * @classdesc + * Class containing all the shared state and behavior of a sound object, independent of the implementation. + * + * @class BaseSound + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} 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. + */ +var BaseSound = new Class({ + + Extends: EventEmitter, + + initialize: + + function BaseSound (manager, key, config) + { + EventEmitter.call(this); + + /** + * Local reference to the sound manager. + * + * @name Phaser.Sound.BaseSound#manager + * @type {Phaser.Sound.BaseSoundManager} + * @private + * @since 3.0.0 + */ + this.manager = manager; + + /** + * Asset key for the sound. + * + * @name Phaser.Sound.BaseSound#key + * @type {string} + * @readonly + * @since 3.0.0 + */ + this.key = key; + + /** + * Flag indicating if sound is currently playing. + * + * @name Phaser.Sound.BaseSound#isPlaying + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isPlaying = false; + + /** + * Flag indicating if sound is currently paused. + * + * @name Phaser.Sound.BaseSound#isPaused + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isPaused = false; + + /** + * A property that holds the value of sound's actual playback rate, + * after its rate and detune values has been combined with global + * rate and detune values. + * + * @name Phaser.Sound.BaseSound#totalRate + * @type {number} + * @default 1 + * @readonly + * @since 3.0.0 + */ + this.totalRate = 1; + + /** + * A value representing the duration, in seconds. + * It could be total sound duration or a marker duration. + * + * @name Phaser.Sound.BaseSound#duration + * @type {number} + * @readonly + * @since 3.0.0 + */ + this.duration = this.duration || 0; + + /** + * The total duration of the sound in seconds. + * + * @name Phaser.Sound.BaseSound#totalDuration + * @type {number} + * @readonly + * @since 3.0.0 + */ + this.totalDuration = this.totalDuration || 0; + + /** + * A config object used to store default sound settings' values. + * Default values will be set by properties' setters. + * + * @name Phaser.Sound.BaseSound#config + * @type {Phaser.Types.Sound.SoundConfig} + * @private + * @since 3.0.0 + */ + this.config = { + + mute: false, + volume: 1, + rate: 1, + detune: 0, + seek: 0, + loop: false, + delay: 0 + + }; + + /** + * Reference to the currently used config. + * It could be default config or marker config. + * + * @name Phaser.Sound.BaseSound#currentConfig + * @type {Phaser.Types.Sound.SoundConfig} + * @private + * @since 3.0.0 + */ + this.currentConfig = this.config; + + this.config = Extend(this.config, config); + + /** + * Object containing markers definitions. + * + * @name Phaser.Sound.BaseSound#markers + * @type {Object.} + * @default {} + * @readonly + * @since 3.0.0 + */ + this.markers = {}; + + /** + * Currently playing marker. + * 'null' if whole sound is playing. + * + * @name Phaser.Sound.BaseSound#currentMarker + * @type {Phaser.Types.Sound.SoundMarker} + * @default null + * @readonly + * @since 3.0.0 + */ + this.currentMarker = null; + + /** + * Flag indicating if destroy method was called on this sound. + * + * @name Phaser.Sound.BaseSound#pendingRemove + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this.pendingRemove = false; + }, + + /** + * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound.BaseSound#addMarker + * @since 3.0.0 + * + * @param {Phaser.Types.Sound.SoundMarker} marker - Marker object. + * + * @return {boolean} Whether the marker was added successfully. + */ + addMarker: function (marker) + { + if (!marker || !marker.name || typeof marker.name !== 'string') + { + return false; + } + + if (this.markers[marker.name]) + { + // eslint-disable-next-line no-console + console.error('addMarker ' + marker.name + ' already exists in Sound'); + + return false; + } + + marker = Extend(true, { + name: '', + start: 0, + duration: this.totalDuration - (marker.start || 0), + config: { + mute: false, + volume: 1, + rate: 1, + detune: 0, + seek: 0, + loop: false, + delay: 0 + } + }, marker); + + this.markers[marker.name] = marker; + + return true; + }, + + /** + * Updates previously added marker. + * + * @method Phaser.Sound.BaseSound#updateMarker + * @since 3.0.0 + * + * @param {Phaser.Types.Sound.SoundMarker} marker - Marker object with updated values. + * + * @return {boolean} Whether the marker was updated successfully. + */ + updateMarker: function (marker) + { + if (!marker || !marker.name || typeof marker.name !== 'string') + { + return false; + } + + if (!this.markers[marker.name]) + { + // eslint-disable-next-line no-console + console.warn('Audio Marker: ' + marker.name + ' missing in Sound: ' + this.key); + + return false; + } + + this.markers[marker.name] = Extend(true, this.markers[marker.name], marker); + + return true; + }, + + /** + * Removes a marker from the sound. + * + * @method Phaser.Sound.BaseSound#removeMarker + * @since 3.0.0 + * + * @param {string} markerName - The name of the marker to remove. + * + * @return {?Phaser.Types.Sound.SoundMarker} Removed marker object or 'null' if there was no marker with provided name. + */ + removeMarker: function (markerName) + { + var marker = this.markers[markerName]; + + if (!marker) + { + return null; + } + + this.markers[markerName] = null; + + return marker; + }, + + /** + * Play this sound, or a marked section of it. + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * + * @method Phaser.Sound.BaseSound#play + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. + * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (markerName, config) + { + if (markerName === undefined) { markerName = ''; } + + if (typeof markerName === 'object') + { + config = markerName; + markerName = ''; + } + + if (typeof markerName !== 'string') + { + return false; + } + + if (!markerName) + { + this.currentMarker = null; + this.currentConfig = this.config; + this.duration = this.totalDuration; + } + else + { + if (!this.markers[markerName]) + { + // eslint-disable-next-line no-console + console.warn('Marker: ' + markerName + ' missing in Sound: ' + this.key); + + return false; + } + + this.currentMarker = this.markers[markerName]; + this.currentConfig = this.currentMarker.config; + this.duration = this.currentMarker.duration; + } + + this.resetConfig(); + + this.currentConfig = Extend(this.currentConfig, config); + + this.isPlaying = true; + this.isPaused = false; + + return true; + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound.BaseSound#pause + * @since 3.0.0 + * + * @return {boolean} Whether the sound was paused successfully. + */ + pause: function () + { + if (this.isPaused || !this.isPlaying) + { + return false; + } + + this.isPlaying = false; + this.isPaused = true; + + return true; + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound.BaseSound#resume + * @since 3.0.0 + * + * @return {boolean} Whether the sound was resumed successfully. + */ + resume: function () + { + if (!this.isPaused || this.isPlaying) + { + return false; + } + + this.isPlaying = true; + this.isPaused = false; + + return true; + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound.BaseSound#stop + * @since 3.0.0 + * + * @return {boolean} Whether the sound was stopped successfully. + */ + stop: function () + { + if (!this.isPaused && !this.isPlaying) + { + return false; + } + + this.isPlaying = false; + this.isPaused = false; + + this.resetConfig(); + + return true; + }, + + /** + * Method used internally for applying config values to some of the sound properties. + * + * @method Phaser.Sound.BaseSound#applyConfig + * @protected + * @since 3.0.0 + */ + applyConfig: function () + { + this.mute = this.currentConfig.mute; + this.volume = this.currentConfig.volume; + this.rate = this.currentConfig.rate; + this.detune = this.currentConfig.detune; + this.loop = this.currentConfig.loop; + }, + + /** + * Method used internally for resetting values of some of the config properties. + * + * @method Phaser.Sound.BaseSound#resetConfig + * @protected + * @since 3.0.0 + */ + resetConfig: function () + { + this.currentConfig.seek = 0; + this.currentConfig.delay = 0; + }, + + /** + * Update method called automatically by sound manager on every game step. + * + * @method Phaser.Sound.BaseSound#update + * @override + * @protected + * @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 elapsed since the last frame. + */ + update: NOOP, + + /** + * Method used internally to calculate total playback rate of the sound. + * + * @method Phaser.Sound.BaseSound#calculateRate + * @protected + * @since 3.0.0 + */ + calculateRate: function () + { + var cent = 1.0005777895065548; // Math.pow(2, 1/1200); + var totalDetune = this.currentConfig.detune + this.manager.detune; + var detuneRate = Math.pow(cent, totalDetune); + + this.totalRate = this.currentConfig.rate * this.manager.rate * detuneRate; + }, + + /** + * Destroys this sound and all associated events and marks it for removal from the sound manager. + * + * @method Phaser.Sound.BaseSound#destroy + * @fires Phaser.Sound.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + if (this.pendingRemove) + { + return; + } + + this.emit(Events.DESTROY, this); + this.pendingRemove = true; + this.manager = null; + this.key = ''; + this.removeAllListeners(); + this.isPlaying = false; + this.isPaused = false; + this.config = null; + this.currentConfig = null; + this.markers = null; + this.currentMarker = null; + } + +}); + +module.exports = BaseSound; + + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayUtils = __webpack_require__(196); +var Class = __webpack_require__(0); +var NOOP = __webpack_require__(2); +var StableSort = __webpack_require__(137); + +/** + * @callback EachListCallback + * + * @param {I} item - The item which is currently being processed. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + +/** + * @classdesc + * List is a generic implementation of an ordered list which contains utility methods for retrieving, manipulating, and iterating items. + * + * @class List + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic T + * + * @param {*} parent - The parent of this list. + */ +var List = new Class({ + + initialize: + + function List (parent) + { + /** + * The parent of this list. + * + * @name Phaser.Structs.List#parent + * @type {*} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * The objects that belong to this collection. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.List#list + * @type {Array.<*>} + * @default [] + * @since 3.0.0 + */ + this.list = []; + + /** + * The index of the current element. + * + * This is used internally when iterating through the list with the {@link #first}, {@link #last}, {@link #get}, and {@link #previous} properties. + * + * @name Phaser.Structs.List#position + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.position = 0; + + /** + * A callback that is invoked every time a child is added to this list. + * + * @name Phaser.Structs.List#addCallback + * @type {function} + * @since 3.4.0 + */ + this.addCallback = NOOP; + + /** + * A callback that is invoked every time a child is removed from this list. + * + * @name Phaser.Structs.List#removeCallback + * @type {function} + * @since 3.4.0 + */ + this.removeCallback = NOOP; + + /** + * The property key to sort by. + * + * @name Phaser.Structs.List#_sortKey + * @type {string} + * @since 3.4.0 + */ + this._sortKey = ''; + }, + + /** + * Adds the given item to the end of the list. Each item must be unique. + * + * @method Phaser.Structs.List#add + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*|Array.<*>} child - The item, or array of items, to add to the list. + * @param {boolean} [skipCallback=false] - Skip calling the List.addCallback if this child is added successfully. + * + * @return {*} The list's underlying array. + */ + add: function (child, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.Add(this.list, child); + } + else + { + return ArrayUtils.Add(this.list, child, 0, this.addCallback, this); + } + }, + + /** + * Adds an item to list, starting at a specified index. Each item must be unique within the list. + * + * @method Phaser.Structs.List#addAt + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item, or array of items, to add to the list. + * @param {integer} [index=0] - The index in the list at which the element(s) will be inserted. + * @param {boolean} [skipCallback=false] - Skip calling the List.addCallback if this child is added successfully. + * + * @return {*} The List's underlying array. + */ + addAt: function (child, index, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.AddAt(this.list, child, index); + } + else + { + return ArrayUtils.AddAt(this.list, child, index, 0, this.addCallback, this); + } + }, + + /** + * Retrieves the item at a given position inside the List. + * + * @method Phaser.Structs.List#getAt + * @since 3.0.0 + * + * @genericUse {T} - [$return] + * + * @param {integer} index - The index of the item. + * + * @return {*} The retrieved item, or `undefined` if it's outside the List's bounds. + */ + getAt: function (index) + { + return this.list[index]; + }, + + /** + * Locates an item within the List and returns its index. + * + * @method Phaser.Structs.List#getIndex + * @since 3.0.0 + * + * @genericUse {T} - [child] + * + * @param {*} child - The item to locate. + * + * @return {integer} The index of the item within the List, or -1 if it's not in the List. + */ + getIndex: function (child) + { + // Return -1 if given child isn't a child of this display list + return this.list.indexOf(child); + }, + + /** + * 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 boolean. + * + * @return {Phaser.Structs.List} This List object. + */ + sort: function (property, handler) + { + if (!property) + { + return this; + } + + if (handler === undefined) + { + handler = function (childA, childB) + { + return childA[property] - childB[property]; + }; + } + + StableSort.inplace(this.list, handler); + + return this; + }, + + /** + * Searches for the first instance of a child with its `name` + * property matching the given argument. Should more than one child have + * the same name only the first is returned. + * + * @method Phaser.Structs.List#getByName + * @since 3.0.0 + * + * @genericUse {T | null} - [$return] + * + * @param {string} name - The name to search for. + * + * @return {?*} The first child with a matching name, or null if none were found. + */ + getByName: function (name) + { + return ArrayUtils.GetFirst(this.list, 'name', name); + }, + + /** + * Returns a random child from the group. + * + * @method Phaser.Structs.List#getRandom + * @since 3.0.0 + * + * @genericUse {T | null} - [$return] + * + * @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). + * @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. + * + * @return {?*} A random child of this Group. + */ + getRandom: function (startIndex, length) + { + return ArrayUtils.GetRandom(this.list, startIndex, length); + }, + + /** + * Returns the first element in a given part of the List which matches a specific criterion. + * + * @method Phaser.Structs.List#getFirst + * @since 3.0.0 + * + * @genericUse {T | null} - [$return] + * + * @param {string} property - The name of the property to test or a falsey value to have no criterion. + * @param {*} value - The value to test the `property` against, or `undefined` to allow any value and only check for existence. + * @param {number} [startIndex=0] - The position in the List to start the search at. + * @param {number} [endIndex] - The position in the List to optionally stop the search at. It won't be checked. + * + * @return {?*} The first item which matches the given criterion, or `null` if no such item exists. + */ + getFirst: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetFirst(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns all children in this List. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('parent')` would return only children that have a property called `parent`. + * + * You can also specify a value to compare the property to: + * + * `getAll('visible', true)` would return only children that have their visible property set to `true`. + * + * Optionally you can specify a start and end index. For example if this List had 100 children, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 children in the List. + * + * @method Phaser.Structs.List#getAll + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {T[]} - [$return] + * + * @param {string} [property] - An optional property to test against the value argument. + * @param {*} [value] - If property is set then Child.property must strictly equal this value to be included in the results. + * @param {integer} [startIndex] - The first child index to start the search from. + * @param {integer} [endIndex] - The last child index to search up until. + * + * @return {Array.<*>} All items of the List which match the given criterion, if any. + */ + getAll: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns the total number of items in the List which have a property matching the given value. + * + * @method Phaser.Structs.List#count + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {string} property - The property to test on each item. + * @param {*} value - The value to test the property against. + * + * @return {integer} The total number of matching elements. + */ + count: function (property, value) + { + return ArrayUtils.CountAllMatching(this.list, property, value); + }, + + /** + * Swaps the positions of two items in the list. + * + * @method Phaser.Structs.List#swap + * @since 3.0.0 + * + * @genericUse {T} - [child1,child2] + * + * @param {*} child1 - The first item to swap. + * @param {*} child2 - The second item to swap. + */ + swap: function (child1, child2) + { + ArrayUtils.Swap(this.list, child1, child2); + }, + + /** + * Moves an item in the List to a new position. + * + * @method Phaser.Structs.List#moveTo + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to move. + * @param {integer} index - Moves an item in the List to a new position. + * + * @return {*} The item that was moved. + */ + moveTo: function (child, index) + { + return ArrayUtils.MoveTo(this.list, child, index); + }, + + /** + * Removes one or many items from the List. + * + * @method Phaser.Structs.List#remove + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item, or array of items, to remove. + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {*} The item, or array of items, which were successfully removed from the List. + */ + remove: function (child, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.Remove(this.list, child); + } + else + { + return ArrayUtils.Remove(this.list, child, this.removeCallback, this); + } + }, + + /** + * Removes the item at the given position in the List. + * + * @method Phaser.Structs.List#removeAt + * @since 3.0.0 + * + * @genericUse {T} - [$return] + * + * @param {integer} index - The position to remove the item from. + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {*} The item that was removed. + */ + removeAt: function (index, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.RemoveAt(this.list, index); + } + else + { + return ArrayUtils.RemoveAt(this.list, index, this.removeCallback, this); + } + }, + + /** + * Removes the items within the given range in the List. + * + * @method Phaser.Structs.List#removeBetween + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @param {integer} [startIndex=0] - The index to start removing from. + * @param {integer} [endIndex] - The position to stop removing at. The item at this position won't be removed. + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {Array.<*>} An array of the items which were removed. + */ + removeBetween: function (startIndex, endIndex, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex); + } + else + { + return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeCallback, this); + } + }, + + /** + * Removes all the items. + * + * @method Phaser.Structs.List#removeAll + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.List.} - [$return] + * + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {Phaser.Structs.List} This List object. + */ + removeAll: function (skipCallback) + { + var i = this.list.length; + + while (i--) + { + this.remove(this.list[i], skipCallback); + } + + return this; + }, + + /** + * Brings the given child to the top of this List. + * + * @method Phaser.Structs.List#bringToTop + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to bring to the top of the List. + * + * @return {*} The item which was moved. + */ + bringToTop: function (child) + { + return ArrayUtils.BringToTop(this.list, child); + }, + + /** + * Sends the given child to the bottom of this List. + * + * @method Phaser.Structs.List#sendToBack + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to send to the back of the list. + * + * @return {*} The item which was moved. + */ + sendToBack: function (child) + { + return ArrayUtils.SendToBack(this.list, child); + }, + + /** + * Moves the given child up one place in this group unless it's already at the top. + * + * @method Phaser.Structs.List#moveUp + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to move up. + * + * @return {*} The item which was moved. + */ + moveUp: function (child) + { + ArrayUtils.MoveUp(this.list, child); + + return child; + }, + + /** + * Moves the given child down one place in this group unless it's already at the bottom. + * + * @method Phaser.Structs.List#moveDown + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to move down. + * + * @return {*} The item which was moved. + */ + moveDown: function (child) + { + ArrayUtils.MoveDown(this.list, child); + + return child; + }, + + /** + * Reverses the order of all children in this List. + * + * @method Phaser.Structs.List#reverse + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.List.} - [$return] + * + * @return {Phaser.Structs.List} This List object. + */ + reverse: function () + { + this.list.reverse(); + + return this; + }, + + /** + * Shuffles the items in the list. + * + * @method Phaser.Structs.List#shuffle + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.List.} - [$return] + * + * @return {Phaser.Structs.List} This List object. + */ + shuffle: function () + { + ArrayUtils.Shuffle(this.list); + + return this; + }, + + /** + * Replaces a child of this List with the given newChild. The newChild cannot be a member of this List. + * + * @method Phaser.Structs.List#replace + * @since 3.0.0 + * + * @genericUse {T} - [oldChild,newChild,$return] + * + * @param {*} oldChild - The child in this List that will be replaced. + * @param {*} newChild - The child to be inserted into this List. + * + * @return {*} Returns the oldChild that was replaced within this group. + */ + replace: function (oldChild, newChild) + { + return ArrayUtils.Replace(this.list, oldChild, newChild); + }, + + /** + * Checks if an item exists within the List. + * + * @method Phaser.Structs.List#exists + * @since 3.0.0 + * + * @genericUse {T} - [child] + * + * @param {*} child - The item to check for the existence of. + * + * @return {boolean} `true` if the item is found in the list, otherwise `false`. + */ + exists: function (child) + { + return (this.list.indexOf(child) > -1); + }, + + /** + * Sets the property `key` to the given value on all members of this List. + * + * @method Phaser.Structs.List#setAll + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {string} property - The name of the property to set. + * @param {*} value - The value to set the property to. + * @param {integer} [startIndex] - The first child index to start the search from. + * @param {integer} [endIndex] - The last child index to search up until. + */ + setAll: function (property, value, startIndex, endIndex) + { + ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); + + return this; + }, + + /** + * Passes all children to the given callback. + * + * @method Phaser.Structs.List#each + * @since 3.0.0 + * + * @genericUse {EachListCallback.} - [callback] + * + * @param {EachListCallback} callback - The function to call. + * @param {*} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + each: function (callback, context) + { + var args = [ null ]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < this.list.length; i++) + { + args[0] = this.list[i]; + + callback.apply(context, args); + } + }, + + /** + * Clears the List and recreates its internal array. + * + * @method Phaser.Structs.List#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAll(); + + this.list = []; + }, + + /** + * Destroys this List. + * + * @method Phaser.Structs.List#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAll(); + + this.parent = null; + this.addCallback = null; + this.removeCallback = null; + }, + + /** + * The number of items inside the List. + * + * @name Phaser.Structs.List#length + * @type {integer} + * @readonly + * @since 3.0.0 + */ + length: { + + get: function () + { + return this.list.length; + } + + }, + + /** + * The first item in the List or `null` for an empty List. + * + * @name Phaser.Structs.List#first + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + first: { + + get: function () + { + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + } + + }, + + /** + * The last item in the List, or `null` for an empty List. + * + * @name Phaser.Structs.List#last + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + last: { + + get: function () + { + if (this.list.length > 0) + { + this.position = this.list.length - 1; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * The next item in the List, or `null` if the entire List has been traversed. + * + * This property can be read successively after reading {@link #first} or manually setting the {@link #position} to iterate the List. + * + * @name Phaser.Structs.List#next + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + next: { + + get: function () + { + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * The previous item in the List, or `null` if the entire List has been traversed. + * + * This property can be read successively after reading {@link #last} or manually setting the {@link #position} to iterate the List backwards. + * + * @name Phaser.Structs.List#previous + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + previous: { + + get: function () + { + if (this.position > 0) + { + this.position--; + + return this.list[this.position]; + } + else + { + return null; + } + } + + } + +}); + +module.exports = List; + + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CheckMatrix = __webpack_require__(197); +var TransposeMatrix = __webpack_require__(413); + +/** + * Rotates the array matrix based on the given rotation value. + * + * The value can be given in degrees: 90, -90, 270, -270 or 180, + * or a string command: `rotateLeft`, `rotateRight` or `rotate180`. + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @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. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var RotateMatrix = function (matrix, direction) +{ + if (direction === undefined) { direction = 90; } + + if (!CheckMatrix(matrix)) + { + return null; + } + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = TransposeMatrix(matrix); + matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix.reverse(); + matrix = TransposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix.reverse(); + } + + return matrix; +}; + +module.exports = RotateMatrix; + + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +//! stable.js 0.1.6, https://github.com/Two-Screen/stable +//! © 2017 Angry Bytes and contributors. MIT licensed. + +/** + * @namespace Phaser.Utils.Array.StableSortFunctions + */ + +(function() { + + /** + * A stable array sort, because `Array#sort()` is not guaranteed stable. + * This is an implementation of merge sort, without recursion. + * + * @function Phaser.Utils.Array.StableSort + * @since 3.0.0 + * + * @param {array} arr - The input array to be sorted. + * @param {function} comp - The comparison handler. + * + * @return {array} The sorted result. + */ +var stable = function(arr, comp) { + return exec(arr.slice(), comp); +}; + + /** + * Sort the input array and simply copy it back if the result isn't in the original array, which happens on an odd number of passes. + * + * @function Phaser.Utils.Array.StableSortFunctions.inplace + * @memberof Phaser.Utils.Array.StableSortFunctions + * @since 3.0.0 + * + * @param {array} arr - The input array. + * @param {function} comp - The comparison handler. + * + * @return {array} The sorted array. + */ +stable.inplace = function(arr, comp) { + var result = exec(arr, comp); + + // This simply copies back if the result isn't in the original array, + // which happens on an odd number of passes. + if (result !== arr) { + pass(result, null, arr.length, arr); + } + + return arr; +}; + +// Execute the sort using the input array and a second buffer as work space. +// Returns one of those two, containing the final result. +function exec(arr, comp) { + if (typeof(comp) !== 'function') { + comp = function(a, b) { + return String(a).localeCompare(b); + }; + } + + // Short-circuit when there's nothing to sort. + var len = arr.length; + if (len <= 1) { + return arr; + } + + // 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. + var buffer = new Array(len); + for (var chk = 1; chk < len; chk *= 2) { + pass(arr, comp, chk, buffer); + + var tmp = arr; + arr = buffer; + buffer = tmp; + } + + return arr; +} + +// Run a single pass with the given chunk size. +var pass = function(arr, comp, chk, result) { + var len = arr.length; + var i = 0; + // Step size / double chunk size. + var dbl = chk * 2; + // Bounds of the left and right chunks. + var l, r, e; + // Iterators over the left and right chunk. + var li, ri; + + // Iterate over pairs of chunks. + for (l = 0; l < len; l += dbl) { + r = l + chk; + e = r + chk; + if (r > len) r = len; + if (e > len) e = len; + + // Iterate both chunks in parallel. + li = l; + ri = r; + while (true) { + // Compare the chunks. + if (li < r && ri < e) { + // This works for a regular `sort()` compatible comparator, + // but also for a simple comparator like: `a > b` + if (comp(arr[li], arr[ri]) <= 0) { + result[i++] = arr[li++]; + } + else { + result[i++] = arr[ri++]; + } + } + // Nothing to compare, just flush what's left. + else if (li < r) { + result[i++] = arr[li++]; + } + else if (ri < e) { + result[i++] = arr[ri++]; + } + // Both iterators are at the chunk ends. + else { + break; + } + } + } +}; + +// Export using CommonJS or to the window. +if (true) { + module.exports = stable; +} +else {} + +})(); + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var GetBitmapTextSize = __webpack_require__(975); +var ParseFromAtlas = __webpack_require__(976); +var ParseXMLBitmapFont = __webpack_require__(200); +var Render = __webpack_require__(977); + +/** + * @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} + * Littera (Web-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.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. + */ +var BitmapText = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Texture, + Components.Tint, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + function BitmapText (scene, x, y, font, text, size, align) + { + if (text === undefined) { text = ''; } + if (align === undefined) { align = 0; } + + GameObject.call(this, scene, 'BitmapText'); + + /** + * The key of the Bitmap Font used by this Bitmap Text. + * To change the font after creation please use `setFont`. + * + * @name Phaser.GameObjects.BitmapText#font + * @type {string} + * @readonly + * @since 3.0.0 + */ + this.font = font; + + var entry = this.scene.sys.cache.bitmapFont.get(font); + + /** + * The data of the Bitmap Font used by this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#fontData + * @type {Phaser.Types.GameObjects.BitmapText.BitmapFontData} + * @readonly + * @since 3.0.0 + */ + this.fontData = entry.data; + + /** + * The text that this Bitmap Text object displays. + * + * @name Phaser.GameObjects.BitmapText#_text + * @type {string} + * @private + * @since 3.0.0 + */ + this._text = ''; + + /** + * The font size of this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#_fontSize + * @type {number} + * @private + * @since 3.0.0 + */ + this._fontSize = size || this.fontData.size; + + /** + * Adds / Removes spacing between characters. + * + * Can be a negative or positive number. + * + * @name Phaser.GameObjects.BitmapText#_letterSpacing + * @type {number} + * @private + * @since 3.4.0 + */ + this._letterSpacing = 0; + + /** + * 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 {integer} + * @private + * @since 3.11.0 + */ + this._align = align; + + /** + * An object that describes the size of this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#_bounds + * @type {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} + * @private + * @since 3.0.0 + */ + this._bounds = GetBitmapTextSize(); + + /** + * An internal dirty flag for bounds calculation. + * + * @name Phaser.GameObjects.BitmapText#_dirty + * @type {boolean} + * @private + * @since 3.11.0 + */ + this._dirty = true; + + /** + * Internal cache var holding the maxWidth. + * + * @name Phaser.GameObjects.BitmapText#_maxWidth + * @type {number} + * @private + * @since 3.21.0 + */ + this._maxWidth = 0; + + /** + * The character code used to detect for word wrapping. + * Defaults to 32 (a space character). + * + * @name Phaser.GameObjects.BitmapText#wordWrapCharCode + * @type {number} + * @since 3.21.0 + */ + this.wordWrapCharCode = 32; + + this.setTexture(entry.texture, entry.frame); + this.setPosition(x, y); + this.setOrigin(0, 0); + this.initPipeline(); + + this.setText(text); + }, + + /** + * Set the lines of text in this BitmapText to be left-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + * + * @method Phaser.GameObjects.BitmapText#setLeftAlign + * @since 3.11.0 + * + * @return {this} This BitmapText Object. + */ + setLeftAlign: function () + { + this._align = BitmapText.ALIGN_LEFT; + + this._dirty = true; + + return this; + }, + + /** + * Set the lines of text in this BitmapText to be center-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + * + * @method Phaser.GameObjects.BitmapText#setCenterAlign + * @since 3.11.0 + * + * @return {this} This BitmapText Object. + */ + setCenterAlign: function () + { + this._align = BitmapText.ALIGN_CENTER; + + this._dirty = true; + + return this; + }, + + /** + * Set the lines of text in this BitmapText to be right-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + * + * @method Phaser.GameObjects.BitmapText#setRightAlign + * @since 3.11.0 + * + * @return {this} This BitmapText Object. + */ + setRightAlign: function () + { + this._align = BitmapText.ALIGN_RIGHT; + + this._dirty = true; + + return this; + }, + + /** + * Set the font size of this Bitmap Text. + * + * @method Phaser.GameObjects.BitmapText#setFontSize + * @since 3.0.0 + * + * @param {number} size - The font size to set. + * + * @return {this} This BitmapText Object. + */ + setFontSize: function (size) + { + this._fontSize = size; + + this._dirty = true; + + return this; + }, + + /** + * Sets the letter spacing between each character of this Bitmap Text. + * Can be a positive value to increase the space, or negative to reduce it. + * Spacing is applied after the kerning values have been set. + * + * @method Phaser.GameObjects.BitmapText#setLetterSpacing + * @since 3.4.0 + * + * @param {number} [spacing=0] - The amount of horizontal space to add between each character. + * + * @return {this} This BitmapText Object. + */ + setLetterSpacing: function (spacing) + { + if (spacing === undefined) { spacing = 0; } + + this._letterSpacing = spacing; + + this._dirty = true; + + return this; + }, + + /** + * Set the textual content of this BitmapText. + * + * An array of strings will be converted into multi-line text. Use the align methods to change multi-line alignment. + * + * @method Phaser.GameObjects.BitmapText#setText + * @since 3.0.0 + * + * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this BitmapText. + * + * @return {this} This BitmapText Object. + */ + setText: function (value) + { + if (!value && value !== 0) + { + value = ''; + } + + if (Array.isArray(value)) + { + value = value.join('\n'); + } + + if (value !== this.text) + { + this._text = value.toString(); + + this._dirty = true; + + this.updateDisplayOrigin(); + } + + return this; + }, + + /** + * 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] - Whether to round the results to the nearest integer. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} An object that describes the size of this Bitmap Text. + */ + getTextBounds: function (round) + { + // local = The BitmapText based on fontSize and 0x0 coords + // global = The BitmapText, taking into account scale and world position + // lines = The BitmapText line data + + var bounds = this._bounds; + + if (this._dirty || this.scaleX !== bounds.scaleX || this.scaleY !== bounds.scaleY) + { + GetBitmapTextSize(this, round, bounds); + + this._dirty = false; + + this.updateDisplayOrigin(); + } + + return bounds; + }, + + /** + * Changes the font this BitmapText is using to render. + * + * The new texture is loaded and applied to the BitmapText. The existing test, size and alignment are preserved, + * unless overridden via the arguments. + * + * @method Phaser.GameObjects.BitmapText#setFont + * @since 3.11.0 + * + * @param {string} font - The key of the font to use from the Bitmap Font cache. + * @param {number} [size] - The font size of this Bitmap Text. If not specified the current size will be used. + * @param {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. If not specified the current alignment will be used. + * + * @return {this} This BitmapText Object. + */ + setFont: function (key, size, align) + { + if (size === undefined) { size = this._fontSize; } + if (align === undefined) { align = this._align; } + + if (key !== this.font) + { + var entry = this.scene.sys.cache.bitmapFont.get(key); + + if (entry) + { + this.font = key; + this.fontData = entry.data; + this._fontSize = size; + this._align = align; + + this.setTexture(entry.texture, entry.frame); + + GetBitmapTextSize(this, false, this._bounds); + } + } + + return this; + }, + + /** + * 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. + */ + setMaxWidth: function (value, wordWrapCharCode) + { + this._maxWidth = value; + + this._dirty = true; + + if (wordWrapCharCode !== undefined) + { + this.wordWrapCharCode = wordWrapCharCode; + } + + return this; + }, + + /** + * 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 {integer} + * @since 3.11.0 + */ + align: { + + set: function (value) + { + this._align = value; + this._dirty = true; + }, + + get: function () + { + return this._align; + } + + }, + + /** + * The text that this Bitmap Text object displays. + * + * You can also use the method `setText` if you want a chainable way to change the text content. + * + * @name Phaser.GameObjects.BitmapText#text + * @type {string} + * @since 3.0.0 + */ + text: { + + set: function (value) + { + this.setText(value); + }, + + get: function () + { + return this._text; + } + + }, + + /** + * The font size of this Bitmap Text. + * + * You can also use the method `setFontSize` if you want a chainable way to change the font size. + * + * @name Phaser.GameObjects.BitmapText#fontSize + * @type {number} + * @since 3.0.0 + */ + fontSize: { + + set: function (value) + { + this._fontSize = value; + this._dirty = true; + }, + + get: function () + { + return this._fontSize; + } + + }, + + /** + * Adds / Removes spacing between characters. + * + * Can be a negative or positive number. + * + * You can also use the method `setLetterSpacing` if you want a chainable way to change the letter spacing. + * + * @name Phaser.GameObjects.BitmapText#letterSpacing + * @type {number} + * @since 3.0.0 + */ + letterSpacing: { + + set: function (value) + { + this._letterSpacing = value; + this._dirty = true; + }, + + get: function () + { + return this._letterSpacing; + } + + }, + + /** + * 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 + */ + maxWidth: { + + set: function (value) + { + this._maxWidth = value; + this._dirty = true; + }, + + get: function () + { + return this._maxWidth; + } + + }, + + /** + * The width of this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#width + * @type {number} + * @readonly + * @since 3.0.0 + */ + width: { + + get: function () + { + this.getTextBounds(false); + + return this._bounds.global.width; + } + + }, + + /** + * The height of this bitmap text. + * + * @name Phaser.GameObjects.BitmapText#height + * @type {number} + * @readonly + * @since 3.0.0 + */ + height: { + + get: function () + { + this.getTextBounds(false); + + return this._bounds.global.height; + } + + }, + + /** + * Build a JSON representation of this Bitmap Text. + * + * @method Phaser.GameObjects.BitmapText#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.BitmapText.JSONBitmapText} A JSON representation of this Bitmap Text. + */ + toJSON: function () + { + var out = Components.ToJSON(this); + + // Extra data is added here + + var data = { + font: this.font, + text: this.text, + fontSize: this.fontSize, + letterSpacing: this.letterSpacing, + align: this.align + }; + + out.data = data; + + return out; + } + +}); + +/** + * Left align the text characters in a multi-line BitmapText object. + * + * @name Phaser.GameObjects.BitmapText.ALIGN_LEFT + * @type {integer} + * @since 3.11.0 + */ +BitmapText.ALIGN_LEFT = 0; + +/** + * Center align the text characters in a multi-line BitmapText object. + * + * @name Phaser.GameObjects.BitmapText.ALIGN_CENTER + * @type {integer} + * @since 3.11.0 + */ +BitmapText.ALIGN_CENTER = 1; + +/** + * Right align the text characters in a multi-line BitmapText object. + * + * @name Phaser.GameObjects.BitmapText.ALIGN_RIGHT + * @type {integer} + * @since 3.11.0 + */ +BitmapText.ALIGN_RIGHT = 2; + +/** + * Parse an XML Bitmap Font from an Atlas. + * + * Adds the parsed Bitmap Font data to the cache with the `fontName` key. + * + * @method Phaser.GameObjects.BitmapText.ParseFromAtlas + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to parse the Bitmap Font for. + * @param {string} fontName - The key of the font to add to the Bitmap Font cache. + * @param {string} textureKey - The key of the BitmapFont's texture. + * @param {string} frameKey - The key of the BitmapFont texture's frame. + * @param {string} xmlKey - The key of the XML data of the font to parse. + * @param {integer} [xSpacing] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing] - The y-axis spacing to add to the line height. + * + * @return {boolean} Whether the parsing was successful or not. + */ +BitmapText.ParseFromAtlas = ParseFromAtlas; + +/** + * Parse an XML font to Bitmap Font data for the Bitmap Font cache. + * + * @method Phaser.GameObjects.BitmapText.ParseXMLBitmapFont + * @since 3.17.0 + * + * @param {XMLDocument} xml - The XML Document to parse the font from. + * @param {integer} [xSpacing=0] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing=0] - The y-axis spacing to add to the line height. + * @param {Phaser.Textures.Frame} [frame] - The texture frame to take into account while parsing. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapFontData} The parsed Bitmap Font data. + */ +BitmapText.ParseXMLBitmapFont = ParseXMLBitmapFont; + +module.exports = BitmapText; + + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var MeshRender = __webpack_require__(1102); +var NOOP = __webpack_require__(2); + +/** + * @classdesc + * A Mesh Game Object. + * + * @class Mesh + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * @extends Phaser.GameObjects.Components.ScrollFactor + * + * @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 {number[]} vertices - An array containing the vertices data for this Mesh. + * @param {number[]} uv - An array containing the uv data for this Mesh. + * @param {number[]} colors - An array containing the color data for this Mesh. + * @param {number[]} alphas - An array containing the alpha data for this Mesh. + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Mesh = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.BlendMode, + Components.Depth, + Components.Mask, + Components.Pipeline, + Components.Size, + Components.Texture, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + MeshRender + ], + + initialize: + + function Mesh (scene, x, y, vertices, uv, colors, alphas, texture, frame) + { + GameObject.call(this, scene, 'Mesh'); + + if (vertices.length !== uv.length) + { + throw new Error('Mesh Vertex count must match UV count'); + } + + var verticesUB = (vertices.length / 2) | 0; + + if (colors.length > 0 && colors.length < verticesUB) + { + throw new Error('Mesh Color count must match Vertex count'); + } + + if (alphas.length > 0 && alphas.length < verticesUB) + { + throw new Error('Mesh Alpha count must match Vertex count'); + } + + var i; + + if (colors.length === 0) + { + for (i = 0; i < verticesUB; ++i) + { + colors[i] = 0xFFFFFF; + } + } + + if (alphas.length === 0) + { + for (i = 0; i < verticesUB; ++i) + { + alphas[i] = 1.0; + } + } + + /** + * An array containing the vertices data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#vertices + * @type {Float32Array} + * @since 3.0.0 + */ + this.vertices = new Float32Array(vertices); + + /** + * An array containing the uv data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#uv + * @type {Float32Array} + * @since 3.0.0 + */ + this.uv = new Float32Array(uv); + + /** + * An array containing the color data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#colors + * @type {Uint32Array} + * @since 3.0.0 + */ + this.colors = new Uint32Array(colors); + + /** + * An array containing the alpha data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#alphas + * @type {Float32Array} + * @since 3.0.0 + */ + this.alphas = new Float32Array(alphas); + + /** + * Fill or additive mode used when blending the color values? + * + * @name Phaser.GameObjects.Mesh#tintFill + * @type {boolean} + * @default false + * @since 3.11.0 + */ + this.tintFill = false; + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.initPipeline(); + }, + + /** + * This method is left intentionally empty and does not do anything. + * It is retained to allow a Mesh or Quad to be added to a Container. + * + * @method Phaser.GameObjects.Mesh#setAlpha + * @since 3.17.0 + */ + setAlpha: NOOP + +}); + +module.exports = Mesh; + + +/***/ }), +/* 140 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if two Rectangles intersect. + * + * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. + * As such, the two Rectangles are considered "solid". + * A Rectangle with no width or no height will never intersect another Rectangle. + * + * @function Phaser.Geom.Intersects.RectangleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. + * + * @return {boolean} `true` if the two Rectangles intersect, otherwise `false`. + */ +var RectangleToRectangle = function (rectA, rectB) +{ + if (rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) + { + return false; + } + + return !(rectA.right < rectB.x || rectA.bottom < rectB.y || rectA.x > rectB.right || rectA.y > rectB.bottom); +}; + +module.exports = RectangleToRectangle; + + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = __webpack_require__(5); + +// Contains the plugins that Phaser uses globally and locally. +// These are the source objects, not instantiated. +var inputPlugins = {}; + +/** + * @namespace Phaser.Input.InputPluginCache + */ + +var InputPluginCache = {}; + +/** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * + * @function Phaser.Input.InputPluginCache.register + * @static + * @since 3.10.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Input Plugin, this is the property key used. + * @param {string} settingsKey - The key in the Scene Settings to check to see if this plugin should install or not. + * @param {string} configKey - The key in the Game Config to check to see if this plugin should install or not. + */ +InputPluginCache.register = function (key, plugin, mapping, settingsKey, configKey) +{ + inputPlugins[key] = { plugin: plugin, mapping: mapping, settingsKey: settingsKey, configKey: configKey }; +}; + +/** + * Returns the input plugin object from the cache based on the given key. + * + * @function Phaser.Input.InputPluginCache.getCore + * @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. + */ +InputPluginCache.getPlugin = function (key) +{ + return inputPlugins[key]; +}; + +/** + * Installs all of the registered Input Plugins into the given target. + * + * @function Phaser.Input.InputPluginCache.install + * @static + * @since 3.10.0 + * + * @param {Phaser.Input.InputPlugin} target - The target InputPlugin to install the plugins into. + */ +InputPluginCache.install = function (target) +{ + var sys = target.scene.sys; + var settings = sys.settings.input; + var config = sys.game.config; + + for (var key in inputPlugins) + { + var source = inputPlugins[key].plugin; + var mapping = inputPlugins[key].mapping; + var settingsKey = inputPlugins[key].settingsKey; + var configKey = inputPlugins[key].configKey; + + if (GetValue(settings, settingsKey, config[configKey])) + { + target[mapping] = new source(target); + } + } +}; + +/** + * 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. + */ +InputPluginCache.remove = function (key) +{ + if (inputPlugins.hasOwnProperty(key)) + { + delete inputPlugins[key]; + } +}; + +module.exports = InputPluginCache; + + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Keyboard.Events + */ + +module.exports = { + + ANY_KEY_DOWN: __webpack_require__(1240), + ANY_KEY_UP: __webpack_require__(1241), + COMBO_MATCH: __webpack_require__(1242), + DOWN: __webpack_require__(1243), + KEY_DOWN: __webpack_require__(1244), + KEY_UP: __webpack_require__(1245), + UP: __webpack_require__(1246) + +}; + + +/***/ }), +/* 143 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Given a File and a baseURL value this returns the URL the File will use to download from. + * + * @function Phaser.Loader.GetURL + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - The File object. + * @param {string} baseURL - A default base URL. + * + * @return {string} The URL the File will use. + */ +var GetURL = function (file, baseURL) +{ + if (!file.url) + { + return false; + } + + if (file.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return file.url; + } + else + { + return baseURL + file.url; + } +}; + +module.exports = GetURL; + + +/***/ }), +/* 144 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates an XHRSettings Object with default values. + * + * @function Phaser.Loader.XHRSettings + * @since 3.0.0 + * + * @param {XMLHttpRequestResponseType} [responseType=''] - The responseType, such as 'text'. + * @param {boolean} [async=true] - Should the XHR request use async or not? + * @param {string} [user=''] - Optional username for the XHR request. + * @param {string} [password=''] - Optional password for the XHR request. + * @param {integer} [timeout=0] - Optional XHR timeout value. + * + * @return {Phaser.Types.Loader.XHRSettingsObject} The XHRSettings object as used by the Loader. + */ +var XHRSettings = function (responseType, async, user, password, timeout) +{ + if (responseType === undefined) { responseType = ''; } + if (async === undefined) { async = true; } + if (user === undefined) { user = ''; } + if (password === undefined) { password = ''; } + if (timeout === undefined) { timeout = 0; } + + // 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". + + return { + + // Ignored by the Loader, only used by File. + responseType: responseType, + + async: async, + + // credentials + user: user, + password: password, + + // timeout in ms (0 = no timeout) + timeout: timeout, + + // setRequestHeader + header: undefined, + headerValue: undefined, + requestedWith: false, + + // overrideMimeType + overrideMimeType: undefined + + }; +}; + +module.exports = XHRSettings; + + +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(229); +var Sprite = __webpack_require__(65); + +/** + * @classdesc + * An Arcade Physics Sprite is a Sprite with an Arcade Physics body and related components. + * The body can be dynamic or static. + * + * The main difference between an Arcade Sprite and an Arcade Image is that you cannot animate an Arcade Image. + * If you do not require animation then you can safely use Arcade Images instead of Arcade Sprites. + * + * @class Sprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Arcade.Components.Acceleration + * @extends Phaser.Physics.Arcade.Components.Angular + * @extends Phaser.Physics.Arcade.Components.Bounce + * @extends Phaser.Physics.Arcade.Components.Debug + * @extends Phaser.Physics.Arcade.Components.Drag + * @extends Phaser.Physics.Arcade.Components.Enable + * @extends Phaser.Physics.Arcade.Components.Friction + * @extends Phaser.Physics.Arcade.Components.Gravity + * @extends Phaser.Physics.Arcade.Components.Immovable + * @extends Phaser.Physics.Arcade.Components.Mass + * @extends Phaser.Physics.Arcade.Components.Size + * @extends Phaser.Physics.Arcade.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ArcadeSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Acceleration, + Components.Angular, + Components.Bounce, + Components.Debug, + Components.Drag, + Components.Enable, + Components.Friction, + Components.Gravity, + Components.Immovable, + Components.Mass, + Components.Size, + Components.Velocity + ], + + initialize: + + function ArcadeSprite (scene, x, y, texture, frame) + { + Sprite.call(this, scene, x, y, texture, frame); + + /** + * This Game Object's Physics Body. + * + * @name Phaser.Physics.Arcade.Sprite#body + * @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} + * @default null + * @since 3.0.0 + */ + this.body = null; + } + +}); + +module.exports = ArcadeSprite; + + +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Axes` module contains methods for creating and manipulating sets of axes. +* +* @class Axes +*/ + +var Axes = {}; + +module.exports = Axes; + +var Vector = __webpack_require__(37); +var Common = __webpack_require__(19); + +(function() { + + /** + * Creates a new set of axes from the given vertices. + * @method fromVertices + * @param {vertices} vertices + * @return {axes} A new axes from the given vertices + */ + Axes.fromVertices = function(vertices) { + var axes = {}; + + // find the unique axes, using edge normal gradients + for (var i = 0; i < vertices.length; i++) { + var j = (i + 1) % vertices.length, + normal = Vector.normalise({ + x: vertices[j].y - vertices[i].y, + y: vertices[i].x - vertices[j].x + }), + gradient = (normal.y === 0) ? Infinity : (normal.x / normal.y); + + // limit precision + gradient = gradient.toFixed(3).toString(); + axes[gradient] = normal; + } + + return Common.values(axes); + }; + + /** + * Rotates a set of axes by the given angle. + * @method rotate + * @param {axes} axes + * @param {number} angle + */ + Axes.rotate = function(axes, angle) { + if (angle === 0) + return; + + var cos = Math.cos(angle), + sin = Math.sin(angle); + + for (var i = 0; i < axes.length; i++) { + var axis = axes[i], + xx; + xx = axis.x * cos - axis.y * sin; + axis.y = axis.x * sin + axis.y * cos; + axis.x = xx; + } + }; + +})(); + + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter.Components + */ + +module.exports = { + + Bounce: __webpack_require__(1341), + Collision: __webpack_require__(1342), + Force: __webpack_require__(1343), + Friction: __webpack_require__(1344), + Gravity: __webpack_require__(1345), + Mass: __webpack_require__(1346), + Static: __webpack_require__(1347), + Sensor: __webpack_require__(1348), + SetBody: __webpack_require__(1349), + Sleep: __webpack_require__(1350), + Transform: __webpack_require__(1367), + Velocity: __webpack_require__(1368) + +}; + + +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. +* +* @class Detector +*/ + +// TODO: speculative contacts + +var Detector = {}; + +module.exports = Detector; + +var SAT = __webpack_require__(149); +var Pair = __webpack_require__(114); +var Bounds = __webpack_require__(38); + +(function() { + + /** + * Finds all collisions given a list of pairs. + * @method collisions + * @param {pair[]} broadphasePairs + * @param {engine} engine + * @return {array} collisions + */ + Detector.collisions = function(broadphasePairs, engine) { + var collisions = [], + pairsTable = engine.pairs.table; + + // @if DEBUG + var metrics = engine.metrics; + // @endif + + for (var i = 0; i < broadphasePairs.length; i++) { + var bodyA = broadphasePairs[i][0], + bodyB = broadphasePairs[i][1]; + + if ((bodyA.isStatic || bodyA.isSleeping) && (bodyB.isStatic || bodyB.isSleeping)) + continue; + + if (!Detector.canCollide(bodyA.collisionFilter, bodyB.collisionFilter)) + continue; + + // @if DEBUG + metrics.midphaseTests += 1; + // @endif + + // mid phase + if (Bounds.overlaps(bodyA.bounds, bodyB.bounds)) { + for (var j = bodyA.parts.length > 1 ? 1 : 0; j < bodyA.parts.length; j++) { + var partA = bodyA.parts[j]; + + for (var k = bodyB.parts.length > 1 ? 1 : 0; k < bodyB.parts.length; k++) { + var partB = bodyB.parts[k]; + + if ((partA === bodyA && partB === bodyB) || Bounds.overlaps(partA.bounds, partB.bounds)) { + // find a previous collision we could reuse + var pairId = Pair.id(partA, partB), + pair = pairsTable[pairId], + previousCollision; + + if (pair && pair.isActive) { + previousCollision = pair.collision; + } else { + previousCollision = null; + } + + // narrow phase + var collision = SAT.collides(partA, partB, previousCollision); + + // @if DEBUG + metrics.narrowphaseTests += 1; + if (collision.reused) + metrics.narrowReuseCount += 1; + // @endif + + if (collision.collided) { + collisions.push(collision); + // @if DEBUG + metrics.narrowDetections += 1; + // @endif + } + } + } + } + } + } + + return collisions; + }; + + /** + * Returns `true` if both supplied collision filters will allow a collision to occur. + * See `body.collisionFilter` for more information. + * @method canCollide + * @param {} filterA + * @param {} filterB + * @return {bool} `true` if collision can occur + */ + Detector.canCollide = function(filterA, filterB) { + if (filterA.group === filterB.group && filterA.group !== 0) + return filterA.group > 0; + + return (filterA.mask & filterB.category) !== 0 && (filterB.mask & filterA.category) !== 0; + }; + +})(); + + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. +* +* @class SAT +*/ + +// TODO: true circles and curves + +var SAT = {}; + +module.exports = SAT; + +var Vertices = __webpack_require__(31); +var Vector = __webpack_require__(37); + +(function() { + + /** + * Detect collision between two bodies using the Separating Axis Theorem. + * @method collides + * @param {body} bodyA + * @param {body} bodyB + * @param {collision} previousCollision + * @return {collision} collision + */ + SAT.collides = function(bodyA, bodyB, previousCollision) { + var overlapAB, + overlapBA, + minOverlap, + collision, + canReusePrevCol = false; + + if (previousCollision) { + // estimate total motion + var parentA = bodyA.parent, + parentB = bodyB.parent, + motion = parentA.speed * parentA.speed + parentA.angularSpeed * parentA.angularSpeed + + parentB.speed * parentB.speed + parentB.angularSpeed * parentB.angularSpeed; + + // we may be able to (partially) reuse collision result + // but only safe if collision was resting + canReusePrevCol = previousCollision && previousCollision.collided && motion < 0.2; + + // reuse collision object + collision = previousCollision; + } else { + collision = { collided: false, bodyA: bodyA, bodyB: bodyB }; + } + + if (previousCollision && canReusePrevCol) { + // if we can reuse the collision result + // we only need to test the previously found axis + var axisBodyA = collision.axisBody, + axisBodyB = axisBodyA === bodyA ? bodyB : bodyA, + axes = [axisBodyA.axes[previousCollision.axisNumber]]; + + minOverlap = SAT._overlapAxes(axisBodyA.vertices, axisBodyB.vertices, axes); + collision.reused = true; + + if (minOverlap.overlap <= 0) { + collision.collided = false; + return collision; + } + } else { + // if we can't reuse a result, perform a full SAT test + + overlapAB = SAT._overlapAxes(bodyA.vertices, bodyB.vertices, bodyA.axes); + + if (overlapAB.overlap <= 0) { + collision.collided = false; + return collision; + } + + overlapBA = SAT._overlapAxes(bodyB.vertices, bodyA.vertices, bodyB.axes); + + if (overlapBA.overlap <= 0) { + collision.collided = false; + return collision; + } + + if (overlapAB.overlap < overlapBA.overlap) { + minOverlap = overlapAB; + collision.axisBody = bodyA; + } else { + minOverlap = overlapBA; + collision.axisBody = bodyB; + } + + // important for reuse later + collision.axisNumber = minOverlap.axisNumber; + } + + collision.bodyA = bodyA.id < bodyB.id ? bodyA : bodyB; + collision.bodyB = bodyA.id < bodyB.id ? bodyB : bodyA; + collision.collided = true; + collision.depth = minOverlap.overlap; + collision.parentA = collision.bodyA.parent; + collision.parentB = collision.bodyB.parent; + + bodyA = collision.bodyA; + bodyB = collision.bodyB; + + // ensure normal is facing away from bodyA + if (Vector.dot(minOverlap.axis, Vector.sub(bodyB.position, bodyA.position)) < 0) { + collision.normal = { + x: minOverlap.axis.x, + y: minOverlap.axis.y + }; + } else { + collision.normal = { + x: -minOverlap.axis.x, + y: -minOverlap.axis.y + }; + } + + collision.tangent = Vector.perp(collision.normal); + + collision.penetration = collision.penetration || {}; + collision.penetration.x = collision.normal.x * collision.depth; + collision.penetration.y = collision.normal.y * collision.depth; + + // find support points, there is always either exactly one or two + var verticesB = SAT._findSupports(bodyA, bodyB, collision.normal), + supports = []; + + // find the supports from bodyB that are inside bodyA + if (Vertices.contains(bodyA.vertices, verticesB[0])) + supports.push(verticesB[0]); + + if (Vertices.contains(bodyA.vertices, verticesB[1])) + supports.push(verticesB[1]); + + // find the supports from bodyA that are inside bodyB + if (supports.length < 2) { + var verticesA = SAT._findSupports(bodyB, bodyA, Vector.neg(collision.normal)); + + if (Vertices.contains(bodyB.vertices, verticesA[0])) + supports.push(verticesA[0]); + + if (supports.length < 2 && Vertices.contains(bodyB.vertices, verticesA[1])) + supports.push(verticesA[1]); + } + + // account for the edge case of overlapping but no vertex containment + if (supports.length < 1) + supports = [verticesB[0]]; + + collision.supports = supports; + + return collision; + }; + + /** + * Find the overlap between two sets of vertices. + * @method _overlapAxes + * @private + * @param {} verticesA + * @param {} verticesB + * @param {} axes + * @return result + */ + SAT._overlapAxes = function(verticesA, verticesB, axes) { + var projectionA = Vector._temp[0], + projectionB = Vector._temp[1], + result = { overlap: Number.MAX_VALUE }, + overlap, + axis; + + for (var i = 0; i < axes.length; i++) { + axis = axes[i]; + + SAT._projectToAxis(projectionA, verticesA, axis); + SAT._projectToAxis(projectionB, verticesB, axis); + + overlap = Math.min(projectionA.max - projectionB.min, projectionB.max - projectionA.min); + + if (overlap <= 0) { + result.overlap = overlap; + return result; + } + + if (overlap < result.overlap) { + result.overlap = overlap; + result.axis = axis; + result.axisNumber = i; + } + } + + return result; + }; + + /** + * Projects vertices on an axis and returns an interval. + * @method _projectToAxis + * @private + * @param {} projection + * @param {} vertices + * @param {} axis + */ + SAT._projectToAxis = function(projection, vertices, axis) { + var min = Vector.dot(vertices[0], axis), + max = min; + + for (var i = 1; i < vertices.length; i += 1) { + var dot = Vector.dot(vertices[i], axis); + + if (dot > max) { + max = dot; + } else if (dot < min) { + min = dot; + } + } + + projection.min = min; + projection.max = max; + }; + + /** + * Finds supporting vertices given two bodies along a given direction using hill-climbing. + * @method _findSupports + * @private + * @param {} bodyA + * @param {} bodyB + * @param {} normal + * @return [vector] + */ + SAT._findSupports = function(bodyA, bodyB, normal) { + var nearestDistance = Number.MAX_VALUE, + vertexToBody = Vector._temp[0], + vertices = bodyB.vertices, + bodyAPosition = bodyA.position, + distance, + vertex, + vertexA, + vertexB; + + // find closest vertex on bodyB + for (var i = 0; i < vertices.length; i++) { + vertex = vertices[i]; + vertexToBody.x = vertex.x - bodyAPosition.x; + vertexToBody.y = vertex.y - bodyAPosition.y; + distance = -Vector.dot(normal, vertexToBody); + + if (distance < nearestDistance) { + nearestDistance = distance; + vertexA = vertex; + } + } + + // find next closest vertex using the two connected to it + var prevIndex = vertexA.index - 1 >= 0 ? vertexA.index - 1 : vertices.length - 1; + vertex = vertices[prevIndex]; + vertexToBody.x = vertex.x - bodyAPosition.x; + vertexToBody.y = vertex.y - bodyAPosition.y; + nearestDistance = -Vector.dot(normal, vertexToBody); + vertexB = vertex; + + var nextIndex = (vertexA.index + 1) % vertices.length; + vertex = vertices[nextIndex]; + vertexToBody.x = vertex.x - bodyAPosition.x; + vertexToBody.y = vertex.y - bodyAPosition.y; + distance = -Vector.dot(normal, vertexToBody); + if (distance < nearestDistance) { + vertexB = vertex; + } + + return [vertexA, vertexB]; + }; + +})(); + + +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Components + */ + +module.exports = { + + CalculateFacesAt: __webpack_require__(245), + CalculateFacesWithin: __webpack_require__(59), + Copy: __webpack_require__(1389), + CreateFromTiles: __webpack_require__(1390), + CullTiles: __webpack_require__(1391), + Fill: __webpack_require__(1392), + FilterTiles: __webpack_require__(1393), + FindByIndex: __webpack_require__(1394), + FindTile: __webpack_require__(1395), + ForEachTile: __webpack_require__(1396), + GetTileAt: __webpack_require__(151), + GetTileAtWorldXY: __webpack_require__(1397), + GetTilesWithin: __webpack_require__(26), + GetTilesWithinShape: __webpack_require__(1398), + GetTilesWithinWorldXY: __webpack_require__(1399), + HasTileAt: __webpack_require__(514), + HasTileAtWorldXY: __webpack_require__(1400), + IsInLayerBounds: __webpack_require__(115), + PutTileAt: __webpack_require__(246), + PutTileAtWorldXY: __webpack_require__(1401), + PutTilesAt: __webpack_require__(1402), + Randomize: __webpack_require__(1403), + RemoveTileAt: __webpack_require__(515), + RemoveTileAtWorldXY: __webpack_require__(1404), + RenderDebug: __webpack_require__(1405), + ReplaceByIndex: __webpack_require__(513), + SetCollision: __webpack_require__(1406), + SetCollisionBetween: __webpack_require__(1407), + SetCollisionByExclusion: __webpack_require__(1408), + SetCollisionByProperty: __webpack_require__(1409), + SetCollisionFromCollisionGroup: __webpack_require__(1410), + SetTileIndexCallback: __webpack_require__(1411), + SetTileLocationCallback: __webpack_require__(1412), + Shuffle: __webpack_require__(1413), + SwapByIndex: __webpack_require__(1414), + TileToWorldX: __webpack_require__(152), + TileToWorldXY: __webpack_require__(1415), + TileToWorldY: __webpack_require__(153), + WeightedRandomize: __webpack_require__(1416), + WorldToTileX: __webpack_require__(69), + WorldToTileXY: __webpack_require__(1417), + WorldToTileY: __webpack_require__(70) + +}; + + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsInLayerBounds = __webpack_require__(115); + +/** + * Gets a tile at the given tile coordinates from the given layer. + * + * @function Phaser.Tilemaps.Components.GetTileAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ +var GetTileAt = function (tileX, tileY, nonNull, layer) +{ + if (nonNull === undefined) { nonNull = false; } + + if (IsInLayerBounds(tileX, tileY, layer)) + { + var tile = layer.data[tileY][tileX] || null; + if (tile === null) + { + return null; + } + else if (tile.index === -1) + { + return nonNull ? tile : null; + } + else + { + return tile; + } + } + else + { + return null; + } +}; + +module.exports = GetTileAt; + + +/***/ }), +/* 152 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldX + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var TileToWorldX = function (tileX, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + var layerWorldX = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + + tileWidth *= tilemapLayer.scaleX; + } + + return layerWorldX + tileX * tileWidth; +}; + +module.exports = TileToWorldX; + + +/***/ }), +/* 153 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldY + * @private + * @since 3.0.0 + * + * @param {integer} tileY - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var TileToWorldY = function (tileY, camera, layer) +{ + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + return layerWorldY + tileY * tileHeight; +}; + +module.exports = TileToWorldY; + + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A Tileset is a combination of an image containing the tiles and a container for data about + * each tile. + * + * @class Tileset + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {string} name - The name of the tileset in the map data. + * @param {integer} firstgid - The first tile index this tileset contains. + * @param {integer} [tileWidth=32] - Width of each tile (in pixels). + * @param {integer} [tileHeight=32] - Height of each tile (in pixels). + * @param {integer} [tileMargin=0] - The margin around all tiles in the sheet (in pixels). + * @param {integer} [tileSpacing=0] - The spacing between each tile in the sheet (in pixels). + * @param {object} [tileProperties={}] - Custom properties defined per tile in the Tileset. + * These typically are custom properties created in Tiled when editing a tileset. + * @param {object} [tileData={}] - Data stored per tile. These typically are created in Tiled + * when editing a tileset, e.g. from Tiled's tile collision editor or terrain editor. + */ +var Tileset = new Class({ + + initialize: + + function Tileset (name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, tileProperties, tileData) + { + if (tileWidth === undefined || tileWidth <= 0) { tileWidth = 32; } + if (tileHeight === undefined || tileHeight <= 0) { tileHeight = 32; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (tileProperties === undefined) { tileProperties = {}; } + if (tileData === undefined) { tileData = {}; } + + /** + * The name of the Tileset. + * + * @name Phaser.Tilemaps.Tileset#name + * @type {string} + * @since 3.0.0 + */ + this.name = name; + + /** + * The starting index of the first tile index this Tileset contains. + * + * @name Phaser.Tilemaps.Tileset#firstgid + * @type {integer} + * @since 3.0.0 + */ + this.firstgid = firstgid; + + /** + * The width of each tile (in pixels). Use setTileSize to change. + * + * @name Phaser.Tilemaps.Tileset#tileWidth + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileWidth = tileWidth; + + /** + * The height of each tile (in pixels). Use setTileSize to change. + * + * @name Phaser.Tilemaps.Tileset#tileHeight + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileHeight = tileHeight; + + /** + * The margin around the tiles in the sheet (in pixels). Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.Tileset#tileMargin + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileMargin = tileMargin; + + /** + * The spacing between each the tile in the sheet (in pixels). Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.Tileset#tileSpacing + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileSpacing = tileSpacing; + + /** + * Tileset-specific properties per tile that are typically defined in the Tiled editor in the + * Tileset editor. + * + * @name Phaser.Tilemaps.Tileset#tileProperties + * @type {object} + * @since 3.0.0 + */ + this.tileProperties = tileProperties; + + /** + * Tileset-specific data per tile that are typically defined in the Tiled editor, e.g. within + * the Tileset collision editor. This is where collision objects and terrain are stored. + * + * @name Phaser.Tilemaps.Tileset#tileData + * @type {object} + * @since 3.0.0 + */ + this.tileData = tileData; + + /** + * The cached image that contains the individual tiles. Use setImage to set. + * + * @name Phaser.Tilemaps.Tileset#image + * @type {?Phaser.Textures.Texture} + * @readonly + * @since 3.0.0 + */ + this.image = null; + + /** + * The gl texture used by the WebGL renderer. + * + * @name Phaser.Tilemaps.Tileset#glTexture + * @type {?WebGLTexture} + * @readonly + * @since 3.11.0 + */ + this.glTexture = null; + + /** + * The number of tile rows in the the tileset. + * + * @name Phaser.Tilemaps.Tileset#rows + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * + * @name Phaser.Tilemaps.Tileset#columns + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * + * @name Phaser.Tilemaps.Tileset#total + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.total = 0; + + /** + * The look-up table to specific tile image texture coordinates (UV in pixels). Each element + * contains the coordinates for a tile in an object of the form {x, y}. + * + * @name Phaser.Tilemaps.Tileset#texCoordinates + * @type {object[]} + * @readonly + * @since 3.0.0 + */ + this.texCoordinates = []; + }, + + /** + * Get a tiles properties that are stored in the Tileset. Returns null if tile index is not + * contained in this Tileset. This is typically defined in Tiled under the Tileset editor. + * + * @method Phaser.Tilemaps.Tileset#getTileProperties + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?(object|undefined)} + */ + getTileProperties: function (tileIndex) + { + if (!this.containsTileIndex(tileIndex)) { return null; } + + return this.tileProperties[tileIndex - this.firstgid]; + }, + + /** + * Get a tile's data that is stored in the Tileset. Returns null if tile index is not contained + * in this Tileset. This is typically defined in Tiled and will contain both Tileset collision + * info and terrain mapping. + * + * @method Phaser.Tilemaps.Tileset#getTileData + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?object|undefined} + */ + getTileData: function (tileIndex) + { + if (!this.containsTileIndex(tileIndex)) { return null; } + + return this.tileData[tileIndex - this.firstgid]; + }, + + /** + * Get a tile's collision group that is stored in the Tileset. Returns null if tile index is not + * contained in this Tileset. This is typically defined within Tiled's tileset collision editor. + * + * @method Phaser.Tilemaps.Tileset#getTileCollisionGroup + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?object} + */ + getTileCollisionGroup: function (tileIndex) + { + var data = this.getTileData(tileIndex); + + return (data && data.objectgroup) ? data.objectgroup : null; + }, + + /** + * Returns true if and only if this Tileset contains the given tile index. + * + * @method Phaser.Tilemaps.Tileset#containsTileIndex + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {boolean} + */ + containsTileIndex: function (tileIndex) + { + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + }, + + /** + * Returns the texture coordinates (UV in pixels) in the Tileset image for the given tile index. + * Returns null if tile index is not contained in this Tileset. + * + * @method Phaser.Tilemaps.Tileset#getTileTextureCoordinates + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?object} Object in the form { x, y } representing the top-left UV coordinate + * within the Tileset image. + */ + getTileTextureCoordinates: function (tileIndex) + { + if (!this.containsTileIndex(tileIndex)) { return null; } + + return this.texCoordinates[tileIndex - this.firstgid]; + }, + + /** + * Sets the image associated with this Tileset and updates the tile data (rows, columns, etc.). + * + * @method Phaser.Tilemaps.Tileset#setImage + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The image that contains the tiles. + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + setImage: function (texture) + { + this.image = texture; + + this.glTexture = texture.get().source.glTexture; + + this.updateTileData(this.image.source[0].width, this.image.source[0].height); + + return this; + }, + + /** + * Sets the tile width & height and updates the tile data (rows, columns, etc.). + * + * @method Phaser.Tilemaps.Tileset#setTileSize + * @since 3.0.0 + * + * @param {integer} [tileWidth] - The width of a tile in pixels. + * @param {integer} [tileHeight] - The height of a tile in pixels. + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + setTileSize: function (tileWidth, tileHeight) + { + if (tileWidth !== undefined) { this.tileWidth = tileWidth; } + if (tileHeight !== undefined) { this.tileHeight = tileHeight; } + + if (this.image) + { + this.updateTileData(this.image.source[0].width, this.image.source[0].height); + } + + return this; + }, + + /** + * Sets the tile margin & spacing and updates the tile data (rows, columns, etc.). + * + * @method Phaser.Tilemaps.Tileset#setSpacing + * @since 3.0.0 + * + * @param {integer} [margin] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing] - The spacing between the tiles in the sheet (in pixels). + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + setSpacing: function (margin, spacing) + { + if (margin !== undefined) { this.tileMargin = margin; } + if (spacing !== undefined) { this.tileSpacing = spacing; } + + if (this.image) + { + this.updateTileData(this.image.source[0].width, this.image.source[0].height); + } + + return this; + }, + + /** + * Updates tile texture coordinates and tileset data. + * + * @method Phaser.Tilemaps.Tileset#updateTileData + * @since 3.0.0 + * + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + updateTileData: function (imageWidth, imageHeight) + { + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn('Image tile area not tile size multiple in: ' + this.name); + } + + // 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. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + this.rows = rowCount; + this.columns = colCount; + + // In Tiled, "empty" spaces in a tileset count as tiles and hence count towards the gid + this.total = rowCount * colCount; + + this.texCoordinates.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.texCoordinates.push({ x: tx, y: ty }); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + return this; + } + +}); + +module.exports = Tileset; + + +/***/ }), +/* 155 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internal function used by the Tween Builder to create a function that will return + * the given value from the source. + * + * @function Phaser.Tweens.Builders.GetNewValue + * @since 3.0.0 + * + * @param {any} source - The source object to get the value from. + * @param {string} key - The property to get from the source. + * @param {any} defaultValue - A default value to return should the source not have the property set. + * + * @return {function} A function which when called will return the property value from the source. + */ +var GetNewValue = function (source, key, defaultValue) +{ + var valueCallback; + + if (source.hasOwnProperty(key)) + { + var t = typeof(source[key]); + + if (t === 'function') + { + valueCallback = function (target, targetKey, value, targetIndex, totalTargets, tween) + { + return source[key](target, targetKey, value, targetIndex, totalTargets, tween); + }; + } + else + { + valueCallback = function () + { + return source[key]; + }; + } + } + else if (typeof defaultValue === 'function') + { + valueCallback = defaultValue; + } + else + { + valueCallback = function () + { + return defaultValue; + }; + } + + return valueCallback; +}; + +module.exports = GetNewValue; + + +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Defaults = __webpack_require__(255); +var GetAdvancedValue = __webpack_require__(15); +var GetBoolean = __webpack_require__(99); +var GetEaseFunction = __webpack_require__(90); +var GetNewValue = __webpack_require__(155); +var GetProps = __webpack_require__(536); +var GetTargets = __webpack_require__(253); +var GetValue = __webpack_require__(5); +var GetValueOp = __webpack_require__(254); +var Tween = __webpack_require__(256); +var TweenData = __webpack_require__(258); + +/** + * Creates a new Tween. + * + * @function Phaser.Tweens.Builders.TweenBuilder + * @since 3.0.0 + * + * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - The owner of the new Tween. + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - Configuration for the new Tween. + * @param {Phaser.Types.Tweens.TweenConfigDefaults} defaults - Tween configuration defaults. + * + * @return {Phaser.Tweens.Tween} The new tween. + */ +var TweenBuilder = function (parent, config, defaults) +{ + if (defaults === undefined) + { + defaults = Defaults; + } + + // Create arrays of the Targets and the Properties + var targets = (defaults.targets) ? defaults.targets : GetTargets(config); + + // var props = (defaults.props) ? defaults.props : GetProps(config); + var props = GetProps(config); + + // Default Tween values + var delay = GetNewValue(config, 'delay', defaults.delay); + var duration = GetNewValue(config, 'duration', defaults.duration); + var easeParams = GetValue(config, 'easeParams', defaults.easeParams); + var ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), easeParams); + var hold = GetNewValue(config, 'hold', defaults.hold); + var repeat = GetNewValue(config, 'repeat', defaults.repeat); + var repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); + var yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); + var flipX = GetBoolean(config, 'flipX', defaults.flipX); + var flipY = GetBoolean(config, 'flipY', defaults.flipY); + + var data = []; + + // Loop through every property defined in the Tween, i.e.: props { x, y, alpha } + for (var p = 0; p < props.length; p++) + { + var key = props[p].key; + var value = props[p].value; + + // Create 1 TweenData per target, per property + for (var t = 0; t < targets.length; t++) + { + var ops = GetValueOp(key, value); + + var tweenData = TweenData( + targets[t], + t, + key, + ops.getEnd, + ops.getStart, + ops.getActive, + GetEaseFunction(GetValue(value, 'ease', ease), easeParams), + GetNewValue(value, 'delay', delay), + GetNewValue(value, 'duration', duration), + GetBoolean(value, 'yoyo', yoyo), + GetNewValue(value, 'hold', hold), + GetNewValue(value, 'repeat', repeat), + GetNewValue(value, 'repeatDelay', repeatDelay), + GetBoolean(value, 'flipX', flipX), + GetBoolean(value, 'flipY', flipY) + ); + + data.push(tweenData); + } + } + + var tween = new Tween(parent, data, targets); + + tween.offset = GetAdvancedValue(config, 'offset', null); + tween.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); + tween.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); + tween.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); + tween.paused = GetBoolean(config, 'paused', false); + tween.useFrames = GetBoolean(config, 'useFrames', false); + + // Set the Callbacks + var scope = GetValue(config, 'callbackScope', tween); + + // Callback parameters: 0 = a reference to the Tween itself, 1 = the target/s of the Tween, ... your own params + var tweenArray = [ tween, null ]; + + var callbacks = Tween.TYPES; + + for (var i = 0; i < callbacks.length; i++) + { + var type = callbacks[i]; + + var callback = GetValue(config, type, false); + + if (callback) + { + var callbackScope = GetValue(config, type + 'Scope', scope); + var callbackParams = GetValue(config, type + 'Params', []); + + // The null is reset to be the Tween target + tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope); + } + } + + return tween; +}; + +module.exports = TweenBuilder; + + +/***/ }), +/* 157 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Modes. + * + * @namespace Phaser.ScaleModes + * @since 3.0.0 + */ + +var ScaleModes = { + + /** + * Default Scale Mode (Linear). + * + * @name Phaser.ScaleModes.DEFAULT + * @type {integer} + * @readonly + * @since 3.0.0 + */ + DEFAULT: 0, + + /** + * Linear Scale Mode. + * + * @name Phaser.ScaleModes.LINEAR + * @type {integer} + * @readonly + * @since 3.0.0 + */ + LINEAR: 0, + + /** + * Nearest Scale Mode. + * + * @name Phaser.ScaleModes.NEAREST + * @type {integer} + * @readonly + * @since 3.0.0 + */ + NEAREST: 1 + +}; + +module.exports = ScaleModes; + + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns a Point 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.Geom.Point} 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.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference. + */ +var CircumferencePoint = function (circle, angle, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = circle.x + (circle.radius * Math.cos(angle)); + out.y = circle.y + (circle.radius * Math.sin(angle)); + + return out; +}; + +module.exports = CircumferencePoint; + + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns a uniformly distributed random point from anywhere within the given Circle. + * + * @function Phaser.Geom.Circle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to get a random point from. + * @param {(Phaser.Geom.Point|object)} [out] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ +var Random = function (circle, out) +{ + if (out === undefined) { out = new Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = circle.x + (x * circle.radius); + out.y = circle.y + (y * circle.radius); + + return out; +}; + +module.exports = Random; + + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(119); +var FindClosestInSorted = __webpack_require__(289); +var Frame = __webpack_require__(290); +var GetValue = __webpack_require__(5); + +/** + * @classdesc + * A Frame based Animation. + * + * This consists of a key, some default values (like the frame rate) and a bunch of Frame objects. + * + * The Animation Manager creates these. Game Objects don't own an instance of these directly. + * Game Objects have the Animation Component, which are like playheads to global Animations (these objects) + * So multiple Game Objects can have playheads all pointing to this one Animation instance. + * + * @class Animation + * @memberof Phaser.Animations + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationManager} manager - A reference to the global Animation Manager + * @param {string} key - The unique identifying string for this animation. + * @param {Phaser.Types.Animations.Animation} config - The Animation configuration. + */ +var Animation = new Class({ + + Extends: EventEmitter, + + initialize: + + function Animation (manager, key, config) + { + EventEmitter.call(this); + + /** + * A reference to the global Animation Manager. + * + * @name Phaser.Animations.Animation#manager + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The unique identifying string for this animation. + * + * @name Phaser.Animations.Animation#key + * @type {string} + * @since 3.0.0 + */ + this.key = key; + + /** + * A frame based animation (as opposed to a bone based animation) + * + * @name Phaser.Animations.Animation#type + * @type {string} + * @default frame + * @since 3.0.0 + */ + this.type = 'frame'; + + /** + * Extract all the frame data into the frames array. + * + * @name Phaser.Animations.Animation#frames + * @type {Phaser.Animations.AnimationFrame[]} + * @since 3.0.0 + */ + this.frames = this.getFrames( + manager.textureManager, + GetValue(config, 'frames', []), + GetValue(config, 'defaultTextureKey', null) + ); + + /** + * The frame rate of playback in frames per second (default 24 if duration is null) + * + * @name Phaser.Animations.Animation#frameRate + * @type {integer} + * @default 24 + * @since 3.0.0 + */ + this.frameRate = GetValue(config, 'frameRate', null); + + /** + * How long the animation should play for, in milliseconds. + * If the `frameRate` property has been set then it overrides this value, + * otherwise the `frameRate` is derived from `duration`. + * + * @name Phaser.Animations.Animation#duration + * @type {integer} + * @since 3.0.0 + */ + this.duration = GetValue(config, 'duration', null); + + if (this.duration === null && this.frameRate === null) + { + // No duration or frameRate given, use default frameRate of 24fps + this.frameRate = 24; + this.duration = (this.frameRate / this.frames.length) * 1000; + } + else if (this.duration && this.frameRate === null) + { + // 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 + this.frameRate = this.frames.length / (this.duration / 1000); + } + else + { + // 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) + this.duration = (this.frames.length / this.frameRate) * 1000; + } + + /** + * How many ms per frame, not including frame specific modifiers. + * + * @name Phaser.Animations.Animation#msPerFrame + * @type {integer} + * @since 3.0.0 + */ + this.msPerFrame = 1000 / this.frameRate; + + /** + * Skip frames if the time lags, or always advanced anyway? + * + * @name Phaser.Animations.Animation#skipMissedFrames + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.skipMissedFrames = GetValue(config, 'skipMissedFrames', true); + + /** + * The delay in ms before the playback will begin. + * + * @name Phaser.Animations.Animation#delay + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.delay = GetValue(config, 'delay', 0); + + /** + * Number of times to repeat the animation. Set to -1 to repeat forever. + * + * @name Phaser.Animations.Animation#repeat + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.repeat = GetValue(config, 'repeat', 0); + + /** + * The delay in ms before the a repeat play starts. + * + * @name Phaser.Animations.Animation#repeatDelay + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.repeatDelay = GetValue(config, 'repeatDelay', 0); + + /** + * Should the animation yoyo (reverse back down to the start) before repeating? + * + * @name Phaser.Animations.Animation#yoyo + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.yoyo = GetValue(config, 'yoyo', false); + + /** + * Should the GameObject's `visible` property be set to `true` when the animation starts to play? + * + * @name Phaser.Animations.Animation#showOnStart + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.showOnStart = GetValue(config, 'showOnStart', false); + + /** + * Should the GameObject's `visible` property be set to `false` when the animation finishes? + * + * @name Phaser.Animations.Animation#hideOnComplete + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.hideOnComplete = GetValue(config, 'hideOnComplete', false); + + /** + * Global pause. All Game Objects using this Animation instance are impacted by this property. + * + * @name Phaser.Animations.Animation#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + this.manager.on(Events.PAUSE_ALL, this.pause, this); + this.manager.on(Events.RESUME_ALL, this.resume, this); + }, + + /** + * Add frames to the end of the animation. + * + * @method Phaser.Animations.Animation#addFrame + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - [description] + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + addFrame: function (config) + { + return this.addFrameAt(this.frames.length, config); + }, + + /** + * Add frame/s into the animation. + * + * @method Phaser.Animations.Animation#addFrameAt + * @since 3.0.0 + * + * @param {integer} index - The index to insert the frame at within the animation. + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - [description] + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + addFrameAt: function (index, config) + { + var newFrames = this.getFrames(this.manager.textureManager, config); + + if (newFrames.length > 0) + { + if (index === 0) + { + this.frames = newFrames.concat(this.frames); + } + else if (index === this.frames.length) + { + this.frames = this.frames.concat(newFrames); + } + else + { + var pre = this.frames.slice(0, index); + var post = this.frames.slice(index); + + this.frames = pre.concat(newFrames, post); + } + + this.updateFrameSequence(); + } + + return this; + }, + + /** + * Check if the given frame index is valid. + * + * @method Phaser.Animations.Animation#checkFrame + * @since 3.0.0 + * + * @param {integer} index - The index to be checked. + * + * @return {boolean} `true` if the index is valid, otherwise `false`. + */ + checkFrame: function (index) + { + return (index >= 0 && index < this.frames.length); + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#completeAnimation + * @protected + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - [description] + */ + completeAnimation: function (component) + { + if (this.hideOnComplete) + { + component.parent.visible = false; + } + + component.stop(); + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#getFirstTick + * @protected + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - [description] + * @param {boolean} [includeDelay=true] - [description] + */ + getFirstTick: function (component, includeDelay) + { + if (includeDelay === undefined) { includeDelay = true; } + + // When is the first update due? + component.accumulator = 0; + component.nextTick = component.msPerFrame + component.currentFrame.duration; + + if (includeDelay) + { + component.nextTick += component._delay; + } + }, + + /** + * Returns the AnimationFrame at the provided index + * + * @method Phaser.Animations.Animation#getFrameAt + * @protected + * @since 3.0.0 + * + * @param {integer} index - The index in the AnimationFrame array + * + * @return {Phaser.Animations.AnimationFrame} The frame at the index provided from the animation sequence + */ + getFrameAt: function (index) + { + return this.frames[index]; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#getFrames + * @since 3.0.0 + * + * @param {Phaser.Textures.TextureManager} textureManager - [description] + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} frames - [description] + * @param {string} [defaultTextureKey] - [description] + * + * @return {Phaser.Animations.AnimationFrame[]} [description] + */ + getFrames: function (textureManager, frames, defaultTextureKey) + { + var out = []; + var prev; + var animationFrame; + var index = 1; + var i; + var textureKey; + + // if frames is a string, we'll get all the frames from the texture manager as if it's a sprite sheet + if (typeof frames === 'string') + { + textureKey = frames; + + var texture = textureManager.get(textureKey); + var frameKeys = texture.getFrameNames(); + + frames = []; + + frameKeys.forEach(function (idx, value) + { + frames.push({ key: textureKey, frame: value }); + }); + } + + if (!Array.isArray(frames) || frames.length === 0) + { + return out; + } + + for (i = 0; i < frames.length; i++) + { + var item = frames[i]; + + var key = GetValue(item, 'key', defaultTextureKey); + + if (!key) + { + continue; + } + + // Could be an integer or a string + var frame = GetValue(item, 'frame', 0); + + // The actual texture frame + var textureFrame = textureManager.getFrame(key, frame); + + animationFrame = new Frame(key, frame, index, textureFrame); + + animationFrame.duration = GetValue(item, 'duration', 0); + + animationFrame.isFirst = (!prev); + + // The previously created animationFrame + if (prev) + { + prev.nextFrame = animationFrame; + + animationFrame.prevFrame = prev; + } + + out.push(animationFrame); + + prev = animationFrame; + + index++; + } + + if (out.length > 0) + { + animationFrame.isLast = true; + + // Link them end-to-end, so they loop + animationFrame.nextFrame = out[0]; + + out[0].prevFrame = animationFrame; + + // Generate the progress data + + var slice = 1 / (out.length - 1); + + for (i = 0; i < out.length; i++) + { + out[i].progress = i * slice; + } + } + + return out; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#getNextTick + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - [description] + */ + getNextTick: function (component) + { + // accumulator += delta * _timeScale + // after a large delta surge (perf issue for example) we need to adjust for it here + + // When is the next update due? + component.accumulator -= component.nextTick; + + component.nextTick = component.msPerFrame + component.currentFrame.duration; + }, + + /** + * Loads the Animation values into the Animation Component. + * + * @method Phaser.Animations.Animation#load + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to load values into. + * @param {integer} startFrame - The start frame of the animation to load. + */ + load: function (component, startFrame) + { + if (startFrame >= this.frames.length) + { + startFrame = 0; + } + + if (component.currentAnim !== this) + { + component.currentAnim = this; + + component.frameRate = this.frameRate; + component.duration = this.duration; + component.msPerFrame = this.msPerFrame; + component.skipMissedFrames = this.skipMissedFrames; + + component._delay = this.delay; + component._repeat = this.repeat; + component._repeatDelay = this.repeatDelay; + component._yoyo = this.yoyo; + } + + var frame = this.frames[startFrame]; + + if (startFrame === 0 && !component.forward) + { + frame = this.getLastFrame(); + } + + component.updateFrame(frame); + }, + + /** + * Returns the frame closest to the given progress value between 0 and 1. + * + * @method Phaser.Animations.Animation#getFrameByProgress + * @since 3.4.0 + * + * @param {number} value - A value between 0 and 1. + * + * @return {Phaser.Animations.AnimationFrame} The frame closest to the given progress value. + */ + getFrameByProgress: function (value) + { + value = Clamp(value, 0, 1); + + return FindClosestInSorted(value, this.frames, 'progress'); + }, + + /** + * Advance the animation frame. + * + * @method Phaser.Animations.Animation#nextFrame + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to advance. + */ + nextFrame: function (component) + { + var frame = component.currentFrame; + + // TODO: Add frame skip support + + if (frame.isLast) + { + // We're at the end of the animation + + // Yoyo? (happens before repeat) + if (component._yoyo) + { + this.handleYoyoFrame(component, false); + } + else if (component.repeatCounter > 0) + { + // Repeat (happens before complete) + + if (component._reverse && component.forward) + { + component.forward = false; + } + else + { + this.repeatAnimation(component); + } + } + else + { + this.completeAnimation(component); + } + } + else + { + this.updateAndGetNextTick(component, frame.nextFrame); + } + }, + + /** + * Handle the yoyo functionality in nextFrame and previousFrame methods. + * + * @method Phaser.Animations.Animation#handleYoyoFrame + * @private + * @since 3.12.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to advance. + * @param {boolean} isReverse - Is animation in reverse mode? (Default: false) + */ + handleYoyoFrame: function (component, isReverse) + { + if (!isReverse) { isReverse = false; } + + if (component._reverse === !isReverse && component.repeatCounter > 0) + { + component.forward = isReverse; + + this.repeatAnimation(component); + + return; + } + + if (component._reverse !== isReverse && component.repeatCounter === 0) + { + this.completeAnimation(component); + + return; + } + + component.forward = isReverse; + + var frame = (isReverse) ? component.currentFrame.nextFrame : component.currentFrame.prevFrame; + + this.updateAndGetNextTick(component, frame); + }, + + /** + * Returns the animation last frame. + * + * @method Phaser.Animations.Animation#getLastFrame + * @since 3.12.0 + * + * @return {Phaser.Animations.AnimationFrame} component - The Animation Last Frame. + */ + getLastFrame: function () + { + return this.frames[this.frames.length - 1]; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#previousFrame + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - [description] + */ + previousFrame: function (component) + { + var frame = component.currentFrame; + + // TODO: Add frame skip support + + if (frame.isFirst) + { + // We're at the start of the animation + + if (component._yoyo) + { + this.handleYoyoFrame(component, true); + } + else if (component.repeatCounter > 0) + { + if (component._reverse && !component.forward) + { + component.currentFrame = this.getLastFrame(); + this.repeatAnimation(component); + } + else + { + // Repeat (happens before complete) + component.forward = true; + this.repeatAnimation(component); + } + } + else + { + this.completeAnimation(component); + } + } + else + { + this.updateAndGetNextTick(component, frame.prevFrame); + } + }, + + /** + * Update Frame and Wait next tick. + * + * @method Phaser.Animations.Animation#updateAndGetNextTick + * @private + * @since 3.12.0 + * + * @param {Phaser.Animations.AnimationFrame} frame - An Animation frame. + */ + updateAndGetNextTick: function (component, frame) + { + component.updateFrame(frame); + + this.getNextTick(component); + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#removeFrame + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} frame - [description] + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + removeFrame: function (frame) + { + var index = this.frames.indexOf(frame); + + if (index !== -1) + { + this.removeFrameAt(index); + } + + return this; + }, + + /** + * Removes a frame from the AnimationFrame array at the provided index + * and updates the animation accordingly. + * + * @method Phaser.Animations.Animation#removeFrameAt + * @since 3.0.0 + * + * @param {integer} index - The index in the AnimationFrame array + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + removeFrameAt: function (index) + { + this.frames.splice(index, 1); + + this.updateFrameSequence(); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#repeatAnimation + * @fires Phaser.Animations.Events#ANIMATION_REPEAT + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_REPEAT + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - [description] + */ + repeatAnimation: function (component) + { + if (component._pendingStop === 2) + { + return this.completeAnimation(component); + } + + if (component._repeatDelay > 0 && component.pendingRepeat === false) + { + component.pendingRepeat = true; + component.accumulator -= component.nextTick; + component.nextTick += component._repeatDelay; + } + else + { + component.repeatCounter--; + + component.updateFrame(component.currentFrame[(component.forward) ? 'nextFrame' : 'prevFrame']); + + if (component.isPlaying) + { + this.getNextTick(component); + + component.pendingRepeat = false; + + var frame = component.currentFrame; + var parent = component.parent; + + this.emit(Events.ANIMATION_REPEAT, this, frame); + + parent.emit(Events.SPRITE_ANIMATION_KEY_REPEAT + this.key, this, frame, component.repeatCounter, parent); + + parent.emit(Events.SPRITE_ANIMATION_REPEAT, this, frame, component.repeatCounter, parent); + } + } + }, + + /** + * Sets the texture frame the animation uses for rendering. + * + * @method Phaser.Animations.Animation#setFrame + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - [description] + */ + setFrame: function (component) + { + // Work out which frame should be set next on the child, and set it + if (component.forward) + { + this.nextFrame(component); + } + else + { + this.previousFrame(component); + } + }, + + /** + * Converts the animation data to JSON. + * + * @method Phaser.Animations.Animation#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Animations.JSONAnimation} [description] + */ + toJSON: function () + { + var output = { + key: this.key, + type: this.type, + frames: [], + frameRate: this.frameRate, + duration: this.duration, + skipMissedFrames: this.skipMissedFrames, + delay: this.delay, + repeat: this.repeat, + repeatDelay: this.repeatDelay, + yoyo: this.yoyo, + showOnStart: this.showOnStart, + hideOnComplete: this.hideOnComplete + }; + + this.frames.forEach(function (frame) + { + output.frames.push(frame.toJSON()); + }); + + return output; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#updateFrameSequence + * @since 3.0.0 + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + updateFrameSequence: function () + { + var len = this.frames.length; + var slice = 1 / (len - 1); + + var frame; + + for (var i = 0; i < len; i++) + { + frame = this.frames[i]; + + frame.index = i + 1; + frame.isFirst = false; + frame.isLast = false; + frame.progress = i * slice; + + if (i === 0) + { + frame.isFirst = true; + + if (len === 1) + { + frame.isLast = true; + frame.nextFrame = frame; + frame.prevFrame = frame; + } + else + { + frame.isLast = false; + frame.prevFrame = this.frames[len - 1]; + frame.nextFrame = this.frames[i + 1]; + } + } + else if (i === len - 1 && len > 1) + { + frame.isLast = true; + frame.prevFrame = this.frames[len - 2]; + frame.nextFrame = this.frames[0]; + } + else if (len > 1) + { + frame.prevFrame = this.frames[i - 1]; + frame.nextFrame = this.frames[i + 1]; + } + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#pause + * @since 3.0.0 + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + pause: function () + { + this.paused = true; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#resume + * @since 3.0.0 + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + resume: function () + { + this.paused = false; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Animations.Animation#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.manager.off(Events.PAUSE_ALL, this.pause, this); + this.manager.off(Events.RESUME_ALL, this.resume, this); + + this.manager.remove(this.key); + + for (var i = 0; i < this.frames.length; i++) + { + this.frames[i].destroy(); + } + + this.frames = []; + + this.manager = null; + } + +}); + +module.exports = Animation; + + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Perimeter = __webpack_require__(120); +var Point = __webpack_require__(4); + +/** + * Position is a value between 0 and 1 where 0 = the top-left of the rectangle and 0.5 = the bottom right. + * + * @function Phaser.Geom.Rectangle.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectangle - [description] + * @param {number} position - [description] + * @param {(Phaser.Geom.Point|object)} [out] - [description] + * + * @return {Phaser.Geom.Point} [description] + */ +var GetPoint = function (rectangle, position, out) +{ + if (out === undefined) { out = new Point(); } + + if (position <= 0 || position >= 1) + { + out.x = rectangle.x; + out.y = rectangle.y; + + return out; + } + + var p = Perimeter(rectangle) * position; + + if (position > 0.5) + { + p -= (rectangle.width + rectangle.height); + + if (p <= rectangle.width) + { + // Face 3 + out.x = rectangle.right - p; + out.y = rectangle.bottom; + } + else + { + // Face 4 + out.x = rectangle.x; + out.y = rectangle.bottom - (p - rectangle.width); + } + } + else if (p <= rectangle.width) + { + // Face 1 + out.x = rectangle.x + p; + out.y = rectangle.y; + } + else + { + // Face 2 + out.x = rectangle.right; + out.y = rectangle.y + (p - rectangle.width); + } + + return out; +}; + +module.exports = GetPoint; + + +/***/ }), +/* 162 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = __webpack_require__(62); +var Point = __webpack_require__(4); + +/** + * Get a number of points along a line's length. + * + * Provide a `quantity` to get an exact number of points along the line. + * + * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when + * providing a `stepRate`. + * + * @function Phaser.Geom.Line.GetPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line. + * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. + * @param {number} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. + * @param {(array|Phaser.Geom.Point[])} [out] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. + * + * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. + */ +var GetPoints = function (line, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Length(line) / stepRate; + } + + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + for (var i = 0; i < quantity; i++) + { + var position = i / quantity; + + var x = x1 + (x2 - x1) * position; + var y = y1 + (y2 - y1) * position; + + out.push(new Point(x, y)); + } + + return out; +}; + +module.exports = GetPoints; + + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns a random point on a given Line. + * + * @function Phaser.Geom.Line.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The Line to calculate the random Point on. + * @param {(Phaser.Geom.Point|object)} [out] - An instance of a Point to be modified. + * + * @return {(Phaser.Geom.Point|object)} A random Point on the Line. + */ +var Random = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + var t = Math.random(); + + out.x = line.x1 + t * (line.x2 - line.x1); + out.y = line.y1 + t * (line.y2 - line.y1); + + return out; +}; + +module.exports = Random; + + +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns a random point within a Rectangle. + * + * @function Phaser.Geom.Rectangle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to return a point from. + * @param {Phaser.Geom.Point} out - The object to update with the point's coordinates. + * + * @return {Phaser.Geom.Point} The modified `out` object, or a new Point if none was provided. + */ +var Random = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.x + (Math.random() * rect.width); + out.y = rect.y + (Math.random() * rect.height); + + return out; +}; + +module.exports = Random; + + +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathWrap = __webpack_require__(63); + +/** + * Wrap an angle. + * + * Wraps the angle to a value in the range of -PI to PI. + * + * @function Phaser.Math.Angle.Wrap + * @since 3.0.0 + * + * @param {number} angle - The angle to wrap, in radians. + * + * @return {number} The wrapped angle, in radians. + */ +var Wrap = function (angle) +{ + return MathWrap(angle, -Math.PI, Math.PI); +}; + +module.exports = Wrap; + + +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Wrap = __webpack_require__(63); + +/** + * Wrap an angle in degrees. + * + * Wraps the angle to a value in the range of -180 to 180. + * + * @function Phaser.Math.Angle.WrapDegrees + * @since 3.0.0 + * + * @param {number} angle - The angle to wrap, in degrees. + * + * @return {number} The wrapped angle, in degrees. + */ +var WrapDegrees = function (angle) +{ + return Wrap(angle, -180, 180); +}; + +module.exports = WrapDegrees; + + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns a uniformly distributed random point from anywhere within the given Ellipse. + * + * @function Phaser.Geom.Ellipse.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get a random point from. + * @param {(Phaser.Geom.Point|object)} [out] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ +var Random = function (ellipse, out) +{ + if (out === undefined) { out = new Point(); } + + var p = Math.random() * Math.PI * 2; + var s = Math.sqrt(Math.random()); + + out.x = ellipse.x + ((s * Math.cos(p)) * ellipse.width / 2); + out.y = ellipse.y + ((s * Math.sin(p)) * ellipse.height / 2); + + return out; +}; + +module.exports = Random; + + +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * [description] + * + * @function Phaser.Geom.Triangle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - [description] + * @param {Phaser.Geom.Point} [out] - [description] + * + * @return {Phaser.Geom.Point} [description] + */ +var Random = function (triangle, out) +{ + if (out === undefined) { out = new Point(); } + + // Basis vectors + var ux = triangle.x2 - triangle.x1; + var uy = triangle.y2 - triangle.y1; + + var vx = triangle.x3 - triangle.x1; + var vy = triangle.y3 - triangle.y1; + + // Random point within the unit square + var r = Math.random(); + var s = Math.random(); + + // Point outside the triangle? Remap it. + if (r + s >= 1) + { + r = 1 - r; + s = 1 - s; + } + + out.x = triangle.x1 + ((ux * r) + (vx * s)); + out.y = triangle.y1 + ((uy * r) + (vy * s)); + + return out; +}; + +module.exports = Random; + + +/***/ }), +/* 169 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a `point` around `x` and `y` by the given `angle` and `distance`. + * + * @function Phaser.Math.RotateAroundDistance + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. + * @param {number} x - The horizontal coordinate to rotate around. + * @param {number} y - The vertical coordinate to rotate around. + * @param {number} angle - The angle of rotation in radians. + * @param {number} distance - The distance from (x, y) to place the point at. + * + * @return {Phaser.Geom.Point} The given point. + */ +var RotateAroundDistance = function (point, x, y, angle, distance) +{ + var t = angle + Math.atan2(point.y - y, point.x - x); + + point.x = x + (distance * Math.cos(t)); + point.y = y + (distance * Math.sin(t)); + + return point; +}; + +module.exports = RotateAroundDistance; + + +/***/ }), +/* 170 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var SmootherStep = function (x, min, max) +{ + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); +}; + +module.exports = SmootherStep; + + +/***/ }), +/* 171 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var SmoothStep = function (x, min, max) +{ + if (x <= min) + { + return 0; + } + + if (x >= max) + { + return 1; + } + + x = (x - min) / (max - min); + + return x * x * (3 - 2 * x); +}; + +module.exports = SmoothStep; + + +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @callback EachMapCallback + * + * @param {string} key - The key of the Map entry. + * @param {E} entry - The value of the Map entry. + * + * @return {?boolean} The callback result. + */ + +/** + * @classdesc + * The keys of a Map can be arbitrary values. + * + * ```javascript + * var map = new Map([ + * [ 1, 'one' ], + * [ 2, 'two' ], + * [ 3, 'three' ] + * ]); + * ``` + * + * @class Map + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic K + * @generic V + * @genericUse {V[]} - [elements] + * + * @param {Array.<*>} elements - An optional array of key-value pairs to populate this Map with. + */ +var Map = new Class({ + + initialize: + + function Map (elements) + { + /** + * The entries in this Map. + * + * @genericUse {Object.} - [$type] + * + * @name Phaser.Structs.Map#entries + * @type {Object.} + * @default {} + * @since 3.0.0 + */ + this.entries = {}; + + /** + * The number of key / value pairs in this Map. + * + * @name Phaser.Structs.Map#size + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.size = 0; + + if (Array.isArray(elements)) + { + for (var i = 0; i < elements.length; i++) + { + this.set(elements[i][0], elements[i][1]); + } + } + }, + + /** + * Adds an element with a specified `key` and `value` to this Map. + * If the `key` already exists, the value will be replaced. + * + * @method Phaser.Structs.Map#set + * @since 3.0.0 + * + * @genericUse {K} - [key] + * @genericUse {V} - [value] + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @param {string} key - The key of the element to be added to this Map. + * @param {*} value - The value of the element to be added to this Map. + * + * @return {Phaser.Structs.Map} This Map object. + */ + set: function (key, value) + { + if (!this.has(key)) + { + this.size++; + } + + this.entries[key] = value; + + return this; + }, + + /** + * Returns the value associated to the `key`, or `undefined` if there is none. + * + * @method Phaser.Structs.Map#get + * @since 3.0.0 + * + * @genericUse {K} - [key] + * @genericUse {V} - [$return] + * + * @param {string} key - The key of the element to return from the `Map` object. + * + * @return {*} The element associated with the specified key or `undefined` if the key can't be found in this Map object. + */ + get: function (key) + { + if (this.has(key)) + { + return this.entries[key]; + } + }, + + /** + * Returns an `Array` of all the values stored in this Map. + * + * @method Phaser.Structs.Map#getArray + * @since 3.0.0 + * + * @genericUse {V[]} - [$return] + * + * @return {Array.<*>} An array of the values stored in this Map. + */ + getArray: function () + { + var output = []; + var entries = this.entries; + + for (var key in entries) + { + output.push(entries[key]); + } + + return output; + }, + + /** + * Returns a boolean indicating whether an element with the specified key exists or not. + * + * @method Phaser.Structs.Map#has + * @since 3.0.0 + * + * @genericUse {K} - [key] + * + * @param {string} key - The key of the element to test for presence of in this Map. + * + * @return {boolean} Returns `true` if an element with the specified key exists in this Map, otherwise `false`. + */ + has: function (key) + { + return (this.entries.hasOwnProperty(key)); + }, + + /** + * Delete the specified element from this Map. + * + * @method Phaser.Structs.Map#delete + * @since 3.0.0 + * + * @genericUse {K} - [key] + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @param {string} key - The key of the element to delete from this Map. + * + * @return {Phaser.Structs.Map} This Map object. + */ + delete: function (key) + { + if (this.has(key)) + { + delete this.entries[key]; + this.size--; + } + + return this; + }, + + /** + * Delete all entries from this Map. + * + * @method Phaser.Structs.Map#clear + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @return {Phaser.Structs.Map} This Map object. + */ + clear: function () + { + Object.keys(this.entries).forEach(function (prop) + { + delete this.entries[prop]; + + }, this); + + this.size = 0; + + return this; + }, + + /** + * Returns all entries keys in this Map. + * + * @method Phaser.Structs.Map#keys + * @since 3.0.0 + * + * @genericUse {K[]} - [$return] + * + * @return {string[]} Array containing entries' keys. + */ + keys: function () + { + return Object.keys(this.entries); + }, + + /** + * Returns an `Array` of all entries. + * + * @method Phaser.Structs.Map#values + * @since 3.0.0 + * + * @genericUse {V[]} - [$return] + * + * @return {Array.<*>} An `Array` of entries. + */ + values: function () + { + var output = []; + var entries = this.entries; + + for (var key in entries) + { + output.push(entries[key]); + } + + return output; + }, + + /** + * Dumps the contents of this Map to the console via `console.group`. + * + * @method Phaser.Structs.Map#dump + * @since 3.0.0 + */ + dump: function () + { + var entries = this.entries; + + // eslint-disable-next-line no-console + console.group('Map'); + + for (var key in entries) + { + console.log(key, entries[key]); + } + + // eslint-disable-next-line no-console + console.groupEnd(); + }, + + /** + * Passes all entries in this Map to the given callback. + * + * @method Phaser.Structs.Map#each + * @since 3.0.0 + * + * @genericUse {EachMapCallback.} - [callback] + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @param {EachMapCallback} callback - The callback which will receive the keys and entries held in this Map. + * + * @return {Phaser.Structs.Map} This Map object. + */ + each: function (callback) + { + var entries = this.entries; + + for (var key in entries) + { + if (callback(key, entries[key]) === false) + { + break; + } + } + + return this; + }, + + /** + * Returns `true` if the value exists within this Map. Otherwise, returns `false`. + * + * @method Phaser.Structs.Map#contains + * @since 3.0.0 + * + * @genericUse {V} - [value] + * + * @param {*} value - The value to search for. + * + * @return {boolean} `true` if the value is found, otherwise `false`. + */ + contains: function (value) + { + var entries = this.entries; + + for (var key in entries) + { + if (entries[key] === value) + { + return true; + } + } + + return false; + }, + + /** + * Merges all new keys from the given Map into this one. + * If it encounters a key that already exists it will be skipped unless override is set to `true`. + * + * @method Phaser.Structs.Map#merge + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Map.} - [map,$return] + * + * @param {Phaser.Structs.Map} map - The Map to merge in to this Map. + * @param {boolean} [override=false] - Set to `true` to replace values in this Map with those from the source map, or `false` to skip them. + * + * @return {Phaser.Structs.Map} This Map object. + */ + merge: function (map, override) + { + if (override === undefined) { override = false; } + + var local = this.entries; + var source = map.entries; + + for (var key in source) + { + if (local.hasOwnProperty(key) && override) + { + local[key] = source[key]; + } + else + { + this.set(key, source[key]); + } + } + + return this; + } + +}); + +module.exports = Map; + + +/***/ }), +/* 173 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @function Phaser.Utils.String.Pad + * @since 3.0.0 + * + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * + * @return {string} The padded string. + */ +var Pad = function (str, len, pad, dir) +{ + if (len === undefined) { len = 0; } + if (pad === undefined) { pad = ' '; } + if (dir === undefined) { dir = 3; } + + str = str.toString(); + + var padlen = 0; + + if (len + 1 >= str.length) + { + switch (dir) + { + case 1: + str = new Array(len + 1 - str.length).join(pad) + str; + break; + + case 3: + var right = Math.ceil((padlen = len - str.length) / 2); + var left = padlen - right; + str = new Array(left + 1).join(pad) + str + new Array(right + 1).join(pad); + break; + + default: + str = str + new Array(len + 1 - str.length).join(pad); + break; + } + } + + return str; +}; + +module.exports = Pad; + + +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HexStringToColor = __webpack_require__(313); +var IntegerToColor = __webpack_require__(316); +var ObjectToColor = __webpack_require__(318); +var RGBStringToColor = __webpack_require__(319); + +/** + * Converts the given source color value into an instance of a Color class. + * The value can be either a string, prefixed with `rgb` or a hex string, a number or an Object. + * + * @function Phaser.Display.Color.ValueToColor + * @since 3.0.0 + * + * @param {(string|number|Phaser.Types.Display.InputColorObject)} input - The source color value to convert. + * + * @return {Phaser.Display.Color} A Color object. + */ +var ValueToColor = function (input) +{ + var t = typeof input; + + switch (t) + { + case 'string': + + if (input.substr(0, 3).toLowerCase() === 'rgb') + { + return RGBStringToColor(input); + } + else + { + return HexStringToColor(input); + } + + case 'number': + + return IntegerToColor(input); + + case 'object': + + return ObjectToColor(input); + } +}; + +module.exports = ValueToColor; + + +/***/ }), +/* 175 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Given 3 separate color values this will return an integer representation of it. + * + * @function Phaser.Display.Color.GetColor + * @since 3.0.0 + * + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * + * @return {number} The combined color value. + */ +var GetColor = function (red, green, blue) +{ + return red << 16 | green << 8 | blue; +}; + +module.exports = GetColor; + + +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetColor = __webpack_require__(175); + +/** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion formula from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @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 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. + * @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. + */ +var HSVToRGB = function (h, s, v, out) +{ + if (s === undefined) { s = 1; } + if (v === undefined) { v = 1; } + + var i = Math.floor(h * 6); + var f = h * 6 - i; + + var p = Math.floor((v * (1 - s)) * 255); + var q = Math.floor((v * (1 - f * s)) * 255); + var t = Math.floor((v * (1 - (1 - f) * s)) * 255); + + v = Math.floor(v *= 255); + + var r = v; + var g = v; + var b = v; + + var c = i % 6; + + if (c === 0) + { + g = t; + b = p; + } + else if (c === 1) + { + r = q; + b = p; + } + else if (c === 2) + { + r = p; + b = t; + } + else if (c === 3) + { + r = p; + g = q; + } + else if (c === 4) + { + r = t; + g = p; + } + else if (c === 5) + { + g = p; + b = q; + } + + if (!out) + { + return { r: r, g: g, b: b, color: GetColor(r, g, b) }; + } + else if (out.setTo) + { + return out.setTo(r, g, b, out.alpha, false); + } + else + { + out.r = r; + out.g = g; + out.b = b; + out.color = GetColor(r, g, b); + + return out; + } +}; + +module.exports = HSVToRGB; + + +/***/ }), +/* 177 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Browser specific prefix, so not going to change between contexts, only between browsers +var prefix = ''; + +/** + * @namespace Phaser.Display.Canvas.Smoothing + * @since 3.0.0 + */ +var Smoothing = function () +{ + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @function Phaser.Display.Canvas.Smoothing.getPrefix + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The canvas context to check. + * + * @return {string} The name of the property on the context which controls image smoothing (either `imageSmoothingEnabled` or a vendor-prefixed version thereof), or `null` if not supported. + */ + var getPrefix = function (context) + { + var vendors = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var i = 0; i < vendors.length; i++) + { + var s = vendors[i] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + }; + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @function Phaser.Display.Canvas.Smoothing.enable + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context on which to enable smoothing. + * + * @return {(CanvasRenderingContext2D|WebGLRenderingContext)} The provided context. + */ + var enable = function (context) + { + if (prefix === '') + { + prefix = getPrefix(context); + } + + if (prefix) + { + context[prefix] = true; + } + + return context; + }; + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @function Phaser.Display.Canvas.Smoothing.disable + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context on which to disable smoothing. + * + * @return {(CanvasRenderingContext2D|WebGLRenderingContext)} The provided context. + */ + var disable = function (context) + { + if (prefix === '') + { + prefix = getPrefix(context); + } + + if (prefix) + { + context[prefix] = false; + } + + return context; + }; + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * Returns null if no smoothing prefix is available. + * + * @function Phaser.Display.Canvas.Smoothing.isEnabled + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context to check. + * + * @return {?boolean} `true` if smoothing is enabled on the context, otherwise `false`. `null` if not supported. + */ + var isEnabled = function (context) + { + return (prefix !== null) ? context[prefix] : null; + }; + + return { + disable: disable, + enable: enable, + getPrefix: getPrefix, + isEnabled: isEnabled + }; + +}; + +module.exports = Smoothing(); + + +/***/ }), +/* 178 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Centers this Rectangle so that the center coordinates match the given x and y values. + +/** + * Moves the top-left corner of a Rectangle so that its center is at the given coordinates. + * + * @function Phaser.Geom.Rectangle.CenterOn + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to be centered. + * @param {number} x - The X coordinate of the Rectangle's center. + * @param {number} y - The Y coordinate of the Rectangle's center. + * + * @return {Phaser.Geom.Rectangle} The centered rectangle. + */ +var CenterOn = function (rect, x, y) +{ + rect.x = x - (rect.width / 2); + rect.y = y - (rect.height / 2); + + return rect; +}; + +module.exports = CenterOn; + + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Back = __webpack_require__(321); +var Bounce = __webpack_require__(322); +var Circular = __webpack_require__(323); +var Cubic = __webpack_require__(324); +var Elastic = __webpack_require__(325); +var Expo = __webpack_require__(326); +var Linear = __webpack_require__(327); +var Quadratic = __webpack_require__(328); +var Quartic = __webpack_require__(329); +var Quintic = __webpack_require__(330); +var Sine = __webpack_require__(331); +var Stepped = __webpack_require__(332); + +// EaseMap +module.exports = { + + Power0: Linear, + Power1: Quadratic.Out, + Power2: Cubic.Out, + Power3: Quartic.Out, + Power4: Quintic.Out, + + Linear: Linear, + Quad: Quadratic.Out, + Cubic: Cubic.Out, + Quart: Quartic.Out, + Quint: Quintic.Out, + Sine: Sine.Out, + Expo: Expo.Out, + Circ: Circular.Out, + Elastic: Elastic.Out, + Back: Back.Out, + Bounce: Bounce.Out, + Stepped: Stepped, + + 'Quad.easeIn': Quadratic.In, + 'Cubic.easeIn': Cubic.In, + 'Quart.easeIn': Quartic.In, + 'Quint.easeIn': Quintic.In, + 'Sine.easeIn': Sine.In, + 'Expo.easeIn': Expo.In, + 'Circ.easeIn': Circular.In, + 'Elastic.easeIn': Elastic.In, + 'Back.easeIn': Back.In, + 'Bounce.easeIn': Bounce.In, + + 'Quad.easeOut': Quadratic.Out, + 'Cubic.easeOut': Cubic.Out, + 'Quart.easeOut': Quartic.Out, + 'Quint.easeOut': Quintic.Out, + 'Sine.easeOut': Sine.Out, + 'Expo.easeOut': Expo.Out, + 'Circ.easeOut': Circular.Out, + 'Elastic.easeOut': Elastic.Out, + 'Back.easeOut': Back.Out, + 'Bounce.easeOut': Bounce.Out, + + 'Quad.easeInOut': Quadratic.InOut, + 'Cubic.easeInOut': Cubic.InOut, + 'Quart.easeInOut': Quartic.InOut, + 'Quint.easeInOut': Quintic.InOut, + 'Sine.easeInOut': Sine.InOut, + 'Expo.easeInOut': Expo.InOut, + 'Circ.easeInOut': Circular.InOut, + 'Elastic.easeInOut': Elastic.InOut, + 'Back.easeInOut': Back.InOut, + 'Bounce.easeInOut': Bounce.InOut + +}; + + +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var OS = __webpack_require__(124); +var Browser = __webpack_require__(125); +var CanvasPool = __webpack_require__(28); + +/** + * Determines the features of the browser 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.features` from within any Scene. + * + * @typedef {object} Phaser.Device.Features + * @since 3.0.0 + * + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @property {boolean} canvas - Is canvas available? + * @property {boolean} file - Is file available? + * @property {boolean} fileSystem - Is fileSystem available? + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @property {boolean} localStorage - Is localStorage available? + * @property {boolean} pointerLock - Is Pointer Lock available? + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @property {boolean} vibration - Does the device support the Vibration API? + * @property {boolean} webGL - Is webGL available? + * @property {boolean} worker - Is worker available? + */ +var Features = { + + canvas: false, + canvasBitBltShift: null, + file: false, + fileSystem: false, + getUserMedia: true, + littleEndian: false, + localStorage: false, + pointerLock: false, + support32bit: false, + vibration: false, + webGL: false, + worker: false + +}; + +// Check Little or Big Endian system. +// @author Matt DesLauriers (@mattdesl) +function checkIsLittleEndian () +{ + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } +} + +function init () +{ + Features.canvas = !!window['CanvasRenderingContext2D']; + + try + { + Features.localStorage = !!localStorage.getItem; + } + catch (error) + { + Features.localStorage = false; + } + + Features.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + Features.fileSystem = !!window['requestFileSystem']; + + var isUint8 = false; + + var testWebGL = function () + { + if (window['WebGLRenderingContext']) + { + try + { + var canvas = CanvasPool.createWebGL(this); + + var ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'); + + var canvas2D = CanvasPool.create2D(this); + + var ctx2D = canvas2D.getContext('2d'); + + // Can't be done on a webgl context + var image = ctx2D.createImageData(1, 1); + + // Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + // @author Matt DesLauriers (@mattdesl) + isUint8 = image.data instanceof Uint8ClampedArray; + + CanvasPool.remove(canvas); + CanvasPool.remove(canvas2D); + + return !!ctx; + } + catch (e) + { + return false; + } + } + + return false; + }; + + Features.webGL = testWebGL(); + + Features.worker = !!window['Worker']; + + Features.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + Features.getUserMedia = Features.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (Browser.firefox && Browser.firefoxVersion < 21) + { + Features.getUserMedia = false; + } + + // 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. + if (!OS.iOS && (Browser.ie || Browser.firefox || Browser.chrome)) + { + Features.canvasBitBltShift = true; + } + + // Known not to work + if (Browser.safari || Browser.mobileSafari) + { + Features.canvasBitBltShift = false; + } + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + Features.vibration = true; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + Features.littleEndian = checkIsLittleEndian(); + } + + Features.support32bit = ( + typeof ArrayBuffer !== 'undefined' && + typeof Uint8ClampedArray !== 'undefined' && + typeof Int32Array !== 'undefined' && + Features.littleEndian !== null && + isUint8 + ); + + return Features; +} + +module.exports = init(); + + +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(13); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Math + */ + +var PhaserMath = { + + // Collections of functions + Angle: __webpack_require__(757), + Distance: __webpack_require__(765), + Easing: __webpack_require__(771), + Fuzzy: __webpack_require__(772), + Interpolation: __webpack_require__(775), + Pow2: __webpack_require__(780), + Snap: __webpack_require__(782), + + // Expose the RNG Class + RandomDataGenerator: __webpack_require__(784), + + // Single functions + Average: __webpack_require__(785), + Bernstein: __webpack_require__(341), + Between: __webpack_require__(183), + CatmullRom: __webpack_require__(182), + CeilTo: __webpack_require__(786), + Clamp: __webpack_require__(20), + DegToRad: __webpack_require__(40), + Difference: __webpack_require__(787), + Factorial: __webpack_require__(342), + FloatBetween: __webpack_require__(348), + FloorTo: __webpack_require__(788), + FromPercent: __webpack_require__(98), + GetSpeed: __webpack_require__(789), + IsEven: __webpack_require__(790), + IsEvenStrict: __webpack_require__(791), + Linear: __webpack_require__(123), + MaxAdd: __webpack_require__(792), + MinSub: __webpack_require__(793), + Percent: __webpack_require__(794), + RadToDeg: __webpack_require__(184), + RandomXY: __webpack_require__(795), + RandomXYZ: __webpack_require__(796), + RandomXYZW: __webpack_require__(797), + Rotate: __webpack_require__(349), + RotateAround: __webpack_require__(295), + RotateAroundDistance: __webpack_require__(169), + RoundAwayFromZero: __webpack_require__(350), + RoundTo: __webpack_require__(798), + SinCosTableGenerator: __webpack_require__(799), + SmootherStep: __webpack_require__(170), + SmoothStep: __webpack_require__(171), + ToXY: __webpack_require__(800), + TransformXY: __webpack_require__(351), + Within: __webpack_require__(801), + Wrap: __webpack_require__(63), + + // Vector classes + Vector2: __webpack_require__(3), + Vector3: __webpack_require__(185), + Vector4: __webpack_require__(352), + Matrix3: __webpack_require__(353), + Matrix4: __webpack_require__(354), + Quaternion: __webpack_require__(355), + RotateVec3: __webpack_require__(802) + +}; + +// Merge in the consts + +PhaserMath = Extend(false, PhaserMath, CONST); + +// Export it + +module.exports = PhaserMath; + + +/***/ }), +/* 182 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates a Catmull-Rom value. + * + * @function Phaser.Math.CatmullRom + * @since 3.0.0 + * + * @param {number} t - [description] + * @param {number} p0 - [description] + * @param {number} p1 - [description] + * @param {number} p2 - [description] + * @param {number} p3 - [description] + * + * @return {number} The Catmull-Rom value. + */ +var CatmullRom = function (t, p0, p1, p2, p3) +{ + var v0 = (p2 - p0) * 0.5; + var v1 = (p3 - p1) * 0.5; + var t2 = t * t; + var t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; +}; + +module.exports = CatmullRom; + + +/***/ }), +/* 183 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random integer between the `min` and `max` values, inclusive. + * + * @function Phaser.Math.Between + * @since 3.0.0 + * + * @param {integer} min - The minimum value. + * @param {integer} max - The maximum value. + * + * @return {integer} The random integer. + */ +var Between = function (min, max) +{ + return Math.floor(Math.random() * (max - min + 1) + min); +}; + +module.exports = Between; + + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(13); + +/** + * Convert the given angle in radians, to the equivalent angle in degrees. + * + * @function Phaser.Math.RadToDeg + * @since 3.0.0 + * + * @param {number} radians - The angle in radians to convert ot degrees. + * + * @return {integer} The given angle converted to degrees. + */ +var RadToDeg = function (radians) +{ + return radians * CONST.RAD_TO_DEG; +}; + +module.exports = RadToDeg; + + +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A representation of a vector in 3D space. + * + * A three-component vector. + * + * @class Vector3 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - The x component. + * @param {number} [y] - The y component. + * @param {number} [z] - The z component. + */ +var Vector3 = new Class({ + + initialize: + + function Vector3 (x, y, z) + { + /** + * The x component of this Vector. + * + * @name Phaser.Math.Vector3#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y component of this Vector. + * + * @name Phaser.Math.Vector3#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The z component of this Vector. + * + * @name Phaser.Math.Vector3#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.z = 0; + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + } + }, + + /** + * Set this Vector to point up. + * + * Sets the y component of the vector to 1, and the others to 0. + * + * @method Phaser.Math.Vector3#up + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + up: function () + { + this.x = 0; + this.y = 1; + this.z = 0; + + return this; + }, + + /** + * Make a clone of this Vector3. + * + * @method Phaser.Math.Vector3#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} A new Vector3 object containing this Vectors values. + */ + clone: function () + { + return new Vector3(this.x, this.y, this.z); + }, + + /** + * Calculate the cross (vector) product of two given Vectors. + * + * @method Phaser.Math.Vector3#crossVectors + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} a - The first Vector to multiply. + * @param {Phaser.Math.Vector3} b - The second Vector to multiply. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + crossVectors: function (a, b) + { + var ax = a.x; + var ay = a.y; + var az = a.z; + var bx = b.x; + var by = b.y; + var bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + }, + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict equality check against each Vector's components. + * + * @method Phaser.Math.Vector3#equals + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector3 to compare against. + * + * @return {boolean} True if the two vectors strictly match, otherwise false. + */ + equals: function (v) + { + return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z)); + }, + + /** + * Copy the components of a given Vector into this Vector. + * + * @method Phaser.Math.Vector3#copy + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} src - The Vector to copy the components from. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + copy: function (src) + { + this.x = src.x; + this.y = src.y; + this.z = src.z || 0; + + return this; + }, + + /** + * Set the `x`, `y`, and `z` components of this Vector to the given `x`, `y`, and `z` values. + * + * @method Phaser.Math.Vector3#set + * @since 3.0.0 + * + * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y and z components. + * @param {number} [y] - The y value to set for this Vector. + * @param {number} [z] - The z value to set for this Vector. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + set: function (x, y, z) + { + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + } + + return this; + }, + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * + * @method Phaser.Math.Vector3#add + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to add to this Vector. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + add: function (v) + { + this.x += v.x; + this.y += v.y; + this.z += v.z || 0; + + return this; + }, + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * + * @method Phaser.Math.Vector3#subtract + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to subtract from this Vector. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + subtract: function (v) + { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z || 0; + + return this; + }, + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * + * @method Phaser.Math.Vector3#multiply + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to multiply this Vector by. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + multiply: function (v) + { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z || 1; + + return this; + }, + + /** + * Scale this Vector by the given value. + * + * @method Phaser.Math.Vector3#scale + * @since 3.0.0 + * + * @param {number} scale - The value to scale this Vector by. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + scale: function (scale) + { + if (isFinite(scale)) + { + this.x *= scale; + this.y *= scale; + this.z *= scale; + } + else + { + this.x = 0; + this.y = 0; + this.z = 0; + } + + return this; + }, + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * + * @method Phaser.Math.Vector3#divide + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to divide this Vector by. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + divide: function (v) + { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z || 1; + + return this; + }, + + /** + * Negate the `x`, `y` and `z` components of this Vector. + * + * @method Phaser.Math.Vector3#negate + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + negate: function () + { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + + return this; + }, + + /** + * Calculate the distance between this Vector and the given Vector. + * + * @method Phaser.Math.Vector3#distance + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector. + */ + distance: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + + return Math.sqrt(dx * dx + dy * dy + dz * dz); + }, + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * + * @method Phaser.Math.Vector3#distanceSq + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector, squared. + */ + distanceSq: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + + return dx * dx + dy * dy + dz * dz; + }, + + /** + * Calculate the length (or magnitude) of this Vector. + * + * @method Phaser.Math.Vector3#length + * @since 3.0.0 + * + * @return {number} The length of this Vector. + */ + length: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + + return Math.sqrt(x * x + y * y + z * z); + }, + + /** + * Calculate the length of this Vector squared. + * + * @method Phaser.Math.Vector3#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Vector, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + + return x * x + y * y + z * z; + }, + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + * + * @method Phaser.Math.Vector3#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var len = x * x + y * y + z * z; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + this.z = z * len; + } + + return this; + }, + + /** + * Calculate the dot product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector3#dot + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector3 to dot product with this Vector3. + * + * @return {number} The dot product of this Vector and `v`. + */ + dot: function (v) + { + return this.x * v.x + this.y * v.y + this.z * v.z; + }, + + /** + * Calculate the cross (vector) product of this Vector (which will be modified) and the given Vector. + * + * @method Phaser.Math.Vector3#cross + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector to cross product with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + cross: function (v) + { + var ax = this.x; + var ay = this.y; + var az = this.z; + var bx = v.x; + var by = v.y; + var bz = v.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + }, + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * + * @method Phaser.Math.Vector3#lerp + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector3 to interpolate towards. + * @param {number} [t=0] - The interpolation percentage, between 0 and 1. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + lerp: function (v, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + var az = this.z; + + this.x = ax + t * (v.x - ax); + this.y = ay + t * (v.y - ay); + this.z = az + t * (v.z - az); + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector3#transformMat3 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} mat - The Matrix3 to transform this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformMat3: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + this.x = x * m[0] + y * m[3] + z * m[6]; + this.y = x * m[1] + y * m[4] + z * m[7]; + this.z = x * m[2] + y * m[5] + z * m[8]; + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector3#transformMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformMat4: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + this.x = m[0] * x + m[4] * y + m[8] * z + m[12]; + this.y = m[1] * x + m[5] * y + m[9] * z + m[13]; + this.z = m[2] * x + m[6] * y + m[10] * z + m[14]; + + return this; + }, + + /** + * Transforms the coordinates of this Vector3 with the given Matrix4. + * + * @method Phaser.Math.Vector3#transformCoordinates + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformCoordinates: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + var tx = (x * m[0]) + (y * m[4]) + (z * m[8]) + m[12]; + var ty = (x * m[1]) + (y * m[5]) + (z * m[9]) + m[13]; + var tz = (x * m[2]) + (y * m[6]) + (z * m[10]) + m[14]; + var tw = (x * m[3]) + (y * m[7]) + (z * m[11]) + m[15]; + + this.x = tx / tw; + this.y = ty / tw; + this.z = tz / tw; + + return this; + }, + + /** + * Transform this Vector with the given Quaternion. + * + * @method Phaser.Math.Vector3#transformQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformQuat: function (q) + { + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + var x = this.x; + var y = this.y; + var z = this.z; + var qx = q.x; + var qy = q.y; + var qz = q.z; + var qw = q.w; + + // calculate quat * vec + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + + return this; + }, + + /** + * Multiplies this Vector3 by the specified matrix, applying a W divide. This is useful for projection, + * e.g. unprojecting a 2D point into 3D space. + * + * @method Phaser.Math.Vector3#project + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to multiply this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + project: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + var a00 = m[0]; + var a01 = m[1]; + var a02 = m[2]; + var a03 = m[3]; + var a10 = m[4]; + var a11 = m[5]; + var a12 = m[6]; + var a13 = m[7]; + var a20 = m[8]; + var a21 = m[9]; + var a22 = m[10]; + var a23 = m[11]; + var a30 = m[12]; + var a31 = m[13]; + var a32 = m[14]; + var a33 = m[15]; + + var lw = 1 / (x * a03 + y * a13 + z * a23 + a33); + + this.x = (x * a00 + y * a10 + z * a20 + a30) * lw; + this.y = (x * a01 + y * a11 + z * a21 + a31) * lw; + this.z = (x * a02 + y * a12 + z * a22 + a32) * lw; + + return this; + }, + + /** + * Unproject this point from 2D space to 3D space. + * The point should have its x and y properties set to + * 2D screen space, and the z either at 0 (near plane) + * or 1 (far plane). The provided matrix is assumed to already + * be combined, i.e. projection * view * model. + * + * After this operation, this vector's (x, y, z) components will + * represent the unprojected 3D coordinate. + * + * @method Phaser.Math.Vector3#unproject + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} viewport - Screen x, y, width and height in pixels. + * @param {Phaser.Math.Matrix4} invProjectionView - Combined projection and view matrix. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + unproject: function (viewport, invProjectionView) + { + var viewX = viewport.x; + var viewY = viewport.y; + var viewWidth = viewport.z; + var viewHeight = viewport.w; + + var x = this.x - viewX; + var y = (viewHeight - this.y - 1) - viewY; + var z = this.z; + + this.x = (2 * x) / viewWidth - 1; + this.y = (2 * y) / viewHeight - 1; + this.z = 2 * z - 1; + + return this.project(invProjectionView); + }, + + /** + * Make this Vector the zero vector (0, 0, 0). + * + * @method Phaser.Math.Vector3#reset + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + reset: function () + { + this.x = 0; + this.y = 0; + this.z = 0; + + return this; + } + +}); + +/** + * A static zero Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.ZERO + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.ZERO = new Vector3(); + +/** + * A static right Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.RIGHT + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.RIGHT = new Vector3(1, 0, 0); + +/** + * A static left Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.LEFT + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.LEFT = new Vector3(-1, 0, 0); + +/** + * A static up Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.UP + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.UP = new Vector3(0, -1, 0); + +/** + * A static down Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.DOWN + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.DOWN = new Vector3(0, 1, 0); + +/** + * A static forward Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.FORWARD + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.FORWARD = new Vector3(0, 0, 1); + +/** + * A static back Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.BACK + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.BACK = new Vector3(0, 0, -1); + +/** + * A static one Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.ONE + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.ONE = new Vector3(1, 1, 1); + +module.exports = Vector3; + + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Plugins.DefaultPlugins + * + * @property {array} Global - These are the Global Managers that are created by the Phaser.Game instance. + * @property {array} CoreScene - These are the core plugins that are installed into every Scene.Systems instance, no matter what. + * @property {array} DefaultScene - These plugins are created in Scene.Systems in addition to the CoreScenePlugins. + */ + +var DefaultPlugins = { + + /** + * These are the Global Managers that are created by the Phaser.Game instance. + * They are referenced from Scene.Systems so that plugins can use them. + * + * @name Phaser.Plugins.Global + * @type {array} + * @since 3.0.0 + */ + Global: [ + + 'game', + 'anims', + 'cache', + 'plugins', + 'registry', + 'scale', + 'sound', + 'textures' + + ], + + /** + * These are the core plugins that are installed into every Scene.Systems instance, no matter what. + * They are optionally exposed in the Scene as well (see the InjectionMap for details) + * + * They are created in the order in which they appear in this array and EventEmitter is always first. + * + * @name Phaser.Plugins.CoreScene + * @type {array} + * @since 3.0.0 + */ + CoreScene: [ + + 'EventEmitter', + + 'CameraManager', + 'GameObjectCreator', + 'GameObjectFactory', + 'ScenePlugin', + 'DisplayList', + 'UpdateList' + + ], + + /** + * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. + * + * You can elect not to have these plugins by either creating a DefaultPlugins object as part + * of the Game Config, by creating a Plugins object as part of a Scene Config, or by modifying this array + * and building your own bundle. + * + * They are optionally exposed in the Scene as well (see the InjectionMap for details) + * + * They are always created in the order in which they appear in the array. + * + * @name Phaser.Plugins.DefaultScene + * @type {array} + * @since 3.0.0 + */ + DefaultScene: [ + + 'Clock', + 'DataManagerPlugin', + 'InputPlugin', + 'Loader', + 'TweenManager', + 'LightsPlugin' + + ] + +}; + +if (false) +{} + +if (true) +{ + DefaultPlugins.Global.push('facebook'); +} + +module.exports = DefaultPlugins; + + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Utils = __webpack_require__(10); + +/** + * @classdesc + * WebGLPipeline is a class that describes the way elements will be renderered + * in WebGL, specially focused on batching vertices (batching is not provided). + * Pipelines are mostly used for describing 2D rendering passes but it's + * flexible enough to be used for any type of rendering including 3D. + * Internally WebGLPipeline will handle things like compiling shaders, + * creating vertex buffers, assigning primitive topology and binding + * vertex attributes. + * + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - gl: Current WebGL context. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * - vertices: An optional buffer of vertices + * - attributes: An array describing the vertex attributes + * + * The vertex attributes properties are: + * - name : String - Name of the attribute in the vertex shader + * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 + * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) + * - normalized : boolean - Is the attribute normalized + * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C + * Here you can find more information of how to describe an attribute: + * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer + * + * @class WebGLPipeline + * @memberof Phaser.Renderer.WebGL + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration object for this WebGL Pipeline, as described above. + */ +var WebGLPipeline = new Class({ + + initialize: + + function WebGLPipeline (config) + { + /** + * Name of the Pipeline. Used for identifying + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'WebGLPipeline'; + + /** + * The Game which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = config.game; + + /** + * The canvas which this WebGL Pipeline renders to. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#view + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.view = config.game.canvas; + + /** + * Used to store the current game resolution + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution + * @type {number} + * @since 3.0.0 + */ + this.resolution = 1; + + /** + * Width of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#width + * @type {number} + * @since 3.0.0 + */ + this.width = 0; + + /** + * Height of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#height + * @type {number} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The WebGL context this WebGL Pipeline uses. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#gl + * @type {WebGLRenderingContext} + * @since 3.0.0 + */ + this.gl = config.gl; + + /** + * How many vertices have been fed to the current pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.vertexCount = 0; + + /** + * The limit of vertices that the pipeline can hold + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity + * @type {integer} + * @since 3.0.0 + */ + this.vertexCapacity = config.vertexCapacity; + + /** + * The WebGL Renderer which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer + * @type {Phaser.Renderer.WebGL.WebGLRenderer} + * @since 3.0.0 + */ + this.renderer = config.renderer; + + /** + * Raw byte buffer of vertices. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData + * @type {ArrayBuffer} + * @since 3.0.0 + */ + this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); + + /** + * The handle to a WebGL vertex buffer object. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer + * @type {WebGLBuffer} + * @since 3.0.0 + */ + this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); + + /** + * The handle to a WebGL program + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#program + * @type {WebGLProgram} + * @since 3.0.0 + */ + this.program = this.renderer.createProgram(config.vertShader, config.fragShader); + + /** + * Array of objects that describe the vertex attributes + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes + * @type {object} + * @since 3.0.0 + */ + this.attributes = config.attributes; + + /** + * The size in bytes of the vertex + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize + * @type {integer} + * @since 3.0.0 + */ + this.vertexSize = config.vertexSize; + + /** + * The primitive topology which the pipeline will use to submit draw calls + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#topology + * @type {integer} + * @since 3.0.0 + */ + this.topology = config.topology; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources + * to the GPU. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes + * @type {Uint8Array} + * @since 3.0.0 + */ + this.bytes = new Uint8Array(this.vertexData); + + /** + * This will store the amount of components of 32 bit length + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount + * @type {integer} + * @since 3.0.0 + */ + this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); + + /** + * Indicates if the current pipeline is flushing the contents to the GPU. + * When the variable is set the flush function will be locked. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked + * @type {boolean} + * @since 3.1.0 + */ + this.flushLocked = false; + + /** + * Indicates if the current pipeline is active or not for this frame only. + * Reset in the onRender method. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#active + * @type {boolean} + * @since 3.10.0 + */ + this.active = false; + }, + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#boot + * @since 3.11.0 + */ + boot: function () + { + }, + + /** + * Adds a description of vertex attribute to the pipeline + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute + * @since 3.2.0 + * + * @param {string} name - Name of the vertex attribute + * @param {integer} size - Vertex component size + * @param {integer} type - Type of the attribute + * @param {boolean} normalized - Is the value normalized to a range + * @param {integer} offset - Byte offset to the beginning of the first element in the vertex + * + * @return {this} This WebGLPipeline instance. + */ + addAttribute: function (name, size, type, normalized, offset) + { + this.attributes.push({ + name: name, + size: size, + type: this.renderer.glFormats[type], + normalized: normalized, + offset: offset + }); + + this.vertexComponentCount = Utils.getComponentCount( + this.attributes, + this.gl + ); + return this; + }, + + /** + * Check if the current batch of vertices is full. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush + * @since 3.0.0 + * + * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. + */ + shouldFlush: function () + { + return (this.vertexCount >= this.vertexCapacity); + }, + + /** + * Resizes the properties used to describe the viewport + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width of this WebGL Pipeline. + * @param {number} height - The new height of this WebGL Pipeline. + * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + this.width = width * resolution; + this.height = height * resolution; + this.resolution = resolution; + + return this; + }, + + /** + * Binds the pipeline resources, including programs, vertex buffers and binds attributes + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#bind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + bind: function () + { + var gl = this.gl; + var vertexBuffer = this.vertexBuffer; + var attributes = this.attributes; + var program = this.program; + var renderer = this.renderer; + var vertexSize = this.vertexSize; + + renderer.setProgram(program); + renderer.setVertexBuffer(vertexBuffer); + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + var location = gl.getAttribLocation(program, element.name); + + if (location >= 0) + { + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); + } + else if (location !== -1) + { + gl.disableVertexAttribArray(location); + } + } + + return this; + }, + + /** + * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. + * + * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + // This is for updating uniform data it's called on each bind attempt. + return this; + }, + + /** + * Called before each frame is rendered, but after the canvas has been cleared. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPreRender: function () + { + // called once every frame + return this; + }, + + /** + * Called before a Scene's Camera is rendered. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. + * + * @return {this} This WebGLPipeline instance. + */ + onRender: function () + { + // called for each camera + return this; + }, + + /** + * Called after each frame has been completely rendered and snapshots have been taken. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPostRender: function () + { + // called once every frame + return this; + }, + + /** + * Uploads the vertex data and emits a draw call + * for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#flush + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) { return this; } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + + if (vertexCount === 0) + { + this.flushLocked = false; + return; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + gl.drawArrays(topology, 0, vertexCount); + + this.vertexCount = 0; + this.flushLocked = false; + + return this; + }, + + /** + * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + destroy: function () + { + var gl = this.gl; + + gl.deleteProgram(this.program); + gl.deleteBuffer(this.vertexBuffer); + + delete this.program; + delete this.vertexBuffer; + delete this.gl; + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new value of the `float` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1: function (name, x) + { + this.renderer.setFloat1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec2` uniform. + * @param {number} y - The new Y component of the `vec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2: function (name, x, y) + { + this.renderer.setFloat2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec3` uniform. + * @param {number} y - The new Y component of the `vec3` uniform. + * @param {number} z - The new Z component of the `vec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3: function (name, x, y, z) + { + this.renderer.setFloat3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - X component of the uniform + * @param {number} y - Y component of the uniform + * @param {number} z - Z component of the uniform + * @param {number} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4: function (name, x, y, z, w) + { + this.renderer.setFloat4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1v: function (name, arr) + { + this.renderer.setFloat1v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2v: function (name, arr) + { + this.renderer.setFloat2v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3v: function (name, arr) + { + this.renderer.setFloat3v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4v: function (name, arr) + { + this.renderer.setFloat4v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new value of the `int` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt1: function (name, x) + { + this.renderer.setInt1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec2` uniform. + * @param {integer} y - The new Y component of the `ivec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt2: function (name, x, y) + { + this.renderer.setInt2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec3` uniform. + * @param {integer} y - The new Y component of the `ivec3` uniform. + * @param {integer} z - The new Z component of the `ivec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt3: function (name, x, y, z) + { + this.renderer.setInt3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - X component of the uniform + * @param {integer} y - Y component of the uniform + * @param {integer} z - Z component of the uniform + * @param {integer} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setInt4: function (name, x, y, z, w) + { + this.renderer.setInt4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix2: function (name, transpose, matrix) + { + this.renderer.setMatrix2(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix3: function (name, transpose, matrix) + { + this.renderer.setMatrix3(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Should the matrix be transpose + * @param {Float32Array} matrix - Matrix data + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix4: function (name, transpose, matrix) + { + this.renderer.setMatrix4(this.program, name, transpose, matrix); + + return this; + } + +}); + +module.exports = WebGLPipeline; + + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Earcut = __webpack_require__(72); +var GetFastValue = __webpack_require__(1); +var ModelViewProjection = __webpack_require__(365); +var ShaderSourceFS = __webpack_require__(811); +var ShaderSourceVS = __webpack_require__(812); +var TransformMatrix = __webpack_require__(35); +var Utils = __webpack_require__(10); +var WebGLPipeline = __webpack_require__(187); + +/** + * @classdesc + * TextureTintPipeline implements the rendering infrastructure + * for displaying textured objects + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * + * @class TextureTintPipeline + * @extends Phaser.Renderer.WebGL.WebGLPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. + */ +var TextureTintPipeline = new Class({ + + Extends: WebGLPipeline, + + Mixins: [ + ModelViewProjection + ], + + initialize: + + function TextureTintPipeline (config) + { + var rendererConfig = config.renderer.config; + + // Vertex Size = attribute size added together (2 + 2 + 1 + 4) + + WebGLPipeline.call(this, { + game: config.game, + renderer: config.renderer, + gl: config.renderer.gl, + topology: GetFastValue(config, 'topology', config.renderer.gl.TRIANGLES), + vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), + fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), + vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), + vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), + attributes: [ + { + name: 'inPosition', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: 0 + }, + { + name: 'inTexCoord', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: Float32Array.BYTES_PER_ELEMENT * 2 + }, + { + name: 'inTintEffect', + size: 1, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: Float32Array.BYTES_PER_ELEMENT * 4 + }, + { + name: 'inTint', + size: 4, + type: config.renderer.gl.UNSIGNED_BYTE, + normalized: true, + offset: Float32Array.BYTES_PER_ELEMENT * 5 + } + ] + }); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#vertexViewF32 + * @type {Float32Array} + * @since 3.0.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * Uint32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#vertexViewU32 + * @type {Uint32Array} + * @since 3.0.0 + */ + this.vertexViewU32 = new Uint32Array(this.vertexData); + + /** + * Size of the batch. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#maxQuads + * @type {integer} + * @since 3.0.0 + */ + this.maxQuads = rendererConfig.batchSize; + + /** + * Collection of batch information + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batches + * @type {array} + * @since 3.1.0 + */ + this.batches = []; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix4 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix4 = new TransformMatrix(); + + /** + * Used internally to draw stroked triangles. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#tempTriangle + * @type {array} + * @private + * @since 3.12.0 + */ + this.tempTriangle = [ + { x: 0, y: 0, width: 0 }, + { x: 0, y: 0, width: 0 }, + { x: 0, y: 0, width: 0 }, + { x: 0, y: 0, width: 0 } + ]; + + /** + * The tint effect to be applied by the shader in the next geometry draw: + * + * 0 = texture multiplied by color + * 1 = solid color + texture alpha + * 2 = solid color, no texture + * 3 = solid texture, no color + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#tintEffect + * @type {number} + * @private + * @since 3.12.0 + */ + this.tintEffect = 2; + + /** + * Cached stroke tint. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#strokeTint + * @type {object} + * @private + * @since 3.12.0 + */ + this.strokeTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; + + /** + * Cached fill tint. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#fillTint + * @type {object} + * @private + * @since 3.12.0 + */ + this.fillTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; + + /** + * Internal texture frame reference. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#currentFrame + * @type {Phaser.Textures.Frame} + * @private + * @since 3.12.0 + */ + this.currentFrame = { u0: 0, v0: 0, u1: 1, v1: 1 }; + + /** + * Internal path quad cache. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#firstQuad + * @type {array} + * @private + * @since 3.12.0 + */ + this.firstQuad = [ 0, 0, 0, 0, 0 ]; + + /** + * Internal path quad cache. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#prevQuad + * @type {array} + * @private + * @since 3.12.0 + */ + this.prevQuad = [ 0, 0, 0, 0, 0 ]; + + /** + * Used internally for triangulating a polygon. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#polygonCache + * @type {array} + * @private + * @since 3.12.0 + */ + this.polygonCache = []; + + this.mvpInit(); + }, + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + WebGLPipeline.prototype.onBind.call(this); + + this.mvpUpdate(); + + return this; + }, + + /** + * Resizes this pipeline and updates the projection. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width. + * @param {number} height - The new height. + * @param {number} resolution - The resolution. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + WebGLPipeline.prototype.resize.call(this, width, height, resolution); + + this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); + + return this; + }, + + /** + * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#setTexture2D + * @since 3.1.0 + * + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} This pipeline instance. + */ + setTexture2D: function (texture, unit) + { + if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } + if (unit === undefined) { unit = 0; } + + if (this.requireTextureBatch(texture, unit)) + { + this.pushBatch(texture, unit); + } + + return this; + }, + + /** + * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#requireTextureBatch + * @since 3.16.0 + * + * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param {integer} unit - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. + */ + requireTextureBatch: function (texture, unit) + { + var batches = this.batches; + var batchLength = batches.length; + + if (batchLength > 0) + { + // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property + var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; + + return !(currentTexture === texture); + } + + return true; + }, + + /** + * Creates a new batch object and pushes it to a batch array. + * The batch object contains information relevant to the current + * vertex batch like the offset in the vertex buffer, vertex count and + * the textures used by that batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#pushBatch + * @since 3.1.0 + * + * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. + * @param {integer} unit - Texture unit to which the texture needs to be bound. + */ + pushBatch: function (texture, unit) + { + if (unit === 0) + { + this.batches.push({ + first: this.vertexCount, + texture: texture, + textures: [] + }); + } + else + { + var textures = []; + + textures[unit - 1] = texture; + + this.batches.push({ + first: this.vertexCount, + texture: null, + textures: textures + }); + } + }, + + /** + * Uploads the vertex data and emits a draw call for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#flush + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) + { + return this; + } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + var renderer = this.renderer; + + var batches = this.batches; + var batchCount = batches.length; + var batchVertexCount = 0; + var batch = null; + var batchNext; + var textureIndex; + var nTexture; + + if (batchCount === 0 || vertexCount === 0) + { + this.flushLocked = false; + + return this; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + + // Process the TEXTURE BATCHES + + for (var index = 0; index < batchCount - 1; index++) + { + batch = batches[index]; + batchNext = batches[index + 1]; + + // Multi-texture check (for non-zero texture units) + if (batch.textures.length > 0) + { + for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) + { + nTexture = batch.textures[textureIndex]; + + if (nTexture) + { + renderer.setTexture2D(nTexture, 1 + textureIndex, false); + } + } + + gl.activeTexture(gl.TEXTURE0); + } + + batchVertexCount = batchNext.first - batch.first; + + // Bail out if texture property is null (i.e. if a texture unit > 0) + if (batch.texture === null || batchVertexCount <= 0) + { + continue; + } + + renderer.setTexture2D(batch.texture, 0, false); + + gl.drawArrays(topology, batch.first, batchVertexCount); + } + + // Left over data + batch = batches[batchCount - 1]; + + // Multi-texture check (for non-zero texture units) + + if (batch.textures.length > 0) + { + for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) + { + nTexture = batch.textures[textureIndex]; + + if (nTexture) + { + renderer.setTexture2D(nTexture, 1 + textureIndex, false); + } + } + + gl.activeTexture(gl.TEXTURE0); + } + + batchVertexCount = vertexCount - batch.first; + + if (batch.texture && batchVertexCount > 0) + { + renderer.setTexture2D(batch.texture, 0, false); + + gl.drawArrays(topology, batch.first, batchVertexCount); + } + + this.vertexCount = 0; + + batches.length = 0; + + this.flushLocked = false; + + return this; + }, + + /** + * Takes a Sprite Game Object, or any object that extends it, and adds it to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchSprite + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.Image|Phaser.GameObjects.Sprite)} sprite - The texture based Game Object to add to the batch. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - The transform matrix of the parent container, if set. + */ + batchSprite: function (sprite, camera, parentTransformMatrix) + { + // Will cause a flush if there are batchSize entries already + this.renderer.setPipeline(this); + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var frame = sprite.frame; + var texture = frame.glTexture; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + var frameX = frame.x; + var frameY = frame.y; + var frameWidth = frame.cutWidth; + var frameHeight = frame.cutHeight; + var customPivot = frame.customPivot; + + var displayOriginX = sprite.displayOriginX; + var displayOriginY = sprite.displayOriginY; + + var x = -displayOriginX + frameX; + var y = -displayOriginY + frameY; + + if (sprite.isCropped) + { + var crop = sprite._crop; + + if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) + { + frame.updateCropUVs(crop, sprite.flipX, sprite.flipY); + } + + u0 = crop.u0; + v0 = crop.v0; + u1 = crop.u1; + v1 = crop.v1; + + frameWidth = crop.width; + frameHeight = crop.height; + + frameX = crop.x; + frameY = crop.y; + + x = -displayOriginX + frameX; + y = -displayOriginY + frameY; + } + + var flipX = 1; + var flipY = 1; + + if (sprite.flipX) + { + if (!customPivot) + { + x += (-frame.realWidth + (displayOriginX * 2)); + } + + flipX = -1; + } + + // Auto-invert the flipY if this is coming from a GLTexture + if (sprite.flipY || (frame.source.isGLTexture && !texture.flipY)) + { + if (!customPivot) + { + y += (-frame.realHeight + (displayOriginY * 2)); + } + + flipY = -1; + } + + spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX * flipX, sprite.scaleY * flipY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = sprite.x; + spriteMatrix.f = sprite.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; + spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var xw = x + frameWidth; + var yh = y + frameHeight; + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + var tintTL = Utils.getTintAppendFloatAlpha(sprite._tintTL, camera.alpha * sprite._alphaTL); + var tintTR = Utils.getTintAppendFloatAlpha(sprite._tintTR, camera.alpha * sprite._alphaTR); + var tintBL = Utils.getTintAppendFloatAlpha(sprite._tintBL, camera.alpha * sprite._alphaBL); + var tintBR = Utils.getTintAppendFloatAlpha(sprite._tintBR, camera.alpha * sprite._alphaBR); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + this.setTexture2D(texture, 0); + + var tintEffect = (sprite._isTinted && sprite.tintFill); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + }, + + /** + * Adds the vertices data into the batch and flushes if full. + * + * Assumes 6 vertices in the following arrangement: + * + * ``` + * 0----3 + * |\ B| + * | \ | + * | \ | + * | A \| + * | \ + * 1----2 + * ``` + * + * Where tx0/ty0 = 0, tx1/ty1 = 1, tx2/ty2 = 2 and tx3/ty3 = 3 + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchQuad + * @since 3.12.0 + * + * @param {number} x0 - The top-left x position. + * @param {number} y0 - The top-left y position. + * @param {number} x1 - The bottom-left x position. + * @param {number} y1 - The bottom-left y position. + * @param {number} x2 - The bottom-right x position. + * @param {number} y2 - The bottom-right y position. + * @param {number} x3 - The top-right x position. + * @param {number} y3 - The top-right y position. + * @param {number} u0 - UV u0 value. + * @param {number} v0 - UV v0 value. + * @param {number} u1 - UV u1 value. + * @param {number} v1 - UV v1 value. + * @param {number} tintTL - The top-left tint color value. + * @param {number} tintTR - The top-right tint color value. + * @param {number} tintBL - The bottom-left tint color value. + * @param {number} tintBR - The bottom-right tint color value. + * @param {(number|boolean)} tintEffect - The tint effect for the shader to use. + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch if a flush occurs. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if this method caused the batch to flush, otherwise `false`. + */ + batchQuad: function (x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, unit) + { + var hasFlushed = false; + + if (this.vertexCount + 6 > this.vertexCapacity) + { + this.flush(); + + hasFlushed = true; + + this.setTexture2D(texture, unit); + } + + var vertexViewF32 = this.vertexViewF32; + var vertexViewU32 = this.vertexViewU32; + + var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; + + vertexViewF32[++vertexOffset] = x0; + vertexViewF32[++vertexOffset] = y0; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTL; + + vertexViewF32[++vertexOffset] = x1; + vertexViewF32[++vertexOffset] = y1; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBL; + + vertexViewF32[++vertexOffset] = x2; + vertexViewF32[++vertexOffset] = y2; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBR; + + vertexViewF32[++vertexOffset] = x0; + vertexViewF32[++vertexOffset] = y0; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTL; + + vertexViewF32[++vertexOffset] = x2; + vertexViewF32[++vertexOffset] = y2; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBR; + + vertexViewF32[++vertexOffset] = x3; + vertexViewF32[++vertexOffset] = y3; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTR; + + this.vertexCount += 6; + + return hasFlushed; + }, + + /** + * Adds the vertices data into the batch and flushes if full. + * + * Assumes 3 vertices in the following arrangement: + * + * ``` + * 0 + * |\ + * | \ + * | \ + * | \ + * | \ + * 1-----2 + * ``` + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTri + * @since 3.12.0 + * + * @param {number} x1 - The bottom-left x position. + * @param {number} y1 - The bottom-left y position. + * @param {number} x2 - The bottom-right x position. + * @param {number} y2 - The bottom-right y position. + * @param {number} x3 - The top-right x position. + * @param {number} y3 - The top-right y position. + * @param {number} u0 - UV u0 value. + * @param {number} v0 - UV v0 value. + * @param {number} u1 - UV u1 value. + * @param {number} v1 - UV v1 value. + * @param {number} tintTL - The top-left tint color value. + * @param {number} tintTR - The top-right tint color value. + * @param {number} tintBL - The bottom-left tint color value. + * @param {(number|boolean)} tintEffect - The tint effect for the shader to use. + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch if a flush occurs. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if this method caused the batch to flush, otherwise `false`. + */ + batchTri: function (x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect, texture, unit) + { + var hasFlushed = false; + + if (this.vertexCount + 3 > this.vertexCapacity) + { + this.flush(); + + this.setTexture2D(texture, unit); + + hasFlushed = true; + } + + var vertexViewF32 = this.vertexViewF32; + var vertexViewU32 = this.vertexViewU32; + + var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; + + vertexViewF32[++vertexOffset] = x1; + vertexViewF32[++vertexOffset] = y1; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTL; + + vertexViewF32[++vertexOffset] = x2; + vertexViewF32[++vertexOffset] = y2; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTR; + + vertexViewF32[++vertexOffset] = x3; + vertexViewF32[++vertexOffset] = y3; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBL; + + this.vertexCount += 3; + + return hasFlushed; + }, + + /** + * Generic function for batching a textured quad using argument values instead of a Game Object. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTexture + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Source GameObject. + * @param {WebGLTexture} texture - Raw WebGLTexture associated with the quad. + * @param {integer} textureWidth - Real texture width. + * @param {integer} textureHeight - Real texture height. + * @param {number} srcX - X coordinate of the quad. + * @param {number} srcY - Y coordinate of the quad. + * @param {number} srcWidth - Width of the quad. + * @param {number} srcHeight - Height of the quad. + * @param {number} scaleX - X component of scale. + * @param {number} scaleY - Y component of scale. + * @param {number} rotation - Rotation of the quad. + * @param {boolean} flipX - Indicates if the quad is horizontally flipped. + * @param {boolean} flipY - Indicates if the quad is vertically flipped. + * @param {number} scrollFactorX - By which factor is the quad affected by the camera horizontal scroll. + * @param {number} scrollFactorY - By which factor is the quad effected by the camera vertical scroll. + * @param {number} displayOriginX - Horizontal origin in pixels. + * @param {number} displayOriginY - Vertical origin in pixels. + * @param {number} frameX - X coordinate of the texture frame. + * @param {number} frameY - Y coordinate of the texture frame. + * @param {number} frameWidth - Width of the texture frame. + * @param {number} frameHeight - Height of the texture frame. + * @param {integer} tintTL - Tint for top left. + * @param {integer} tintTR - Tint for top right. + * @param {integer} tintBL - Tint for bottom left. + * @param {integer} tintBR - Tint for bottom right. + * @param {number} tintEffect - The tint effect. + * @param {number} uOffset - Horizontal offset on texture coordinate. + * @param {number} vOffset - Vertical offset on texture coordinate. + * @param {Phaser.Cameras.Scene2D.Camera} camera - Current used camera. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - Parent container. + * @param {boolean} [skipFlip=false] - Skip the renderTexture check. + */ + batchTexture: function ( + gameObject, + texture, + textureWidth, textureHeight, + srcX, srcY, + srcWidth, srcHeight, + scaleX, scaleY, + rotation, + flipX, flipY, + scrollFactorX, scrollFactorY, + displayOriginX, displayOriginY, + frameX, frameY, frameWidth, frameHeight, + tintTL, tintTR, tintBL, tintBR, tintEffect, + uOffset, vOffset, + camera, + parentTransformMatrix, + skipFlip) + { + this.renderer.setPipeline(this, gameObject); + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var u0 = (frameX / textureWidth) + uOffset; + var v0 = (frameY / textureHeight) + vOffset; + var u1 = (frameX + frameWidth) / textureWidth + uOffset; + var v1 = (frameY + frameHeight) / textureHeight + vOffset; + + var width = srcWidth; + var height = srcHeight; + + var x = -displayOriginX; + var y = -displayOriginY; + + if (gameObject.isCropped) + { + var crop = gameObject._crop; + + width = crop.width; + height = crop.height; + + srcWidth = crop.width; + srcHeight = crop.height; + + frameX = crop.x; + frameY = crop.y; + + var ox = frameX; + var oy = frameY; + + if (flipX) + { + ox = (frameWidth - crop.x - crop.width); + } + + if (flipY && !texture.isRenderTexture) + { + oy = (frameHeight - crop.y - crop.height); + } + + u0 = (ox / textureWidth) + uOffset; + v0 = (oy / textureHeight) + vOffset; + u1 = (ox + crop.width) / textureWidth + uOffset; + v1 = (oy + crop.height) / textureHeight + vOffset; + + x = -displayOriginX + frameX; + y = -displayOriginY + frameY; + } + + // Invert the flipY if this is a RenderTexture + flipY = flipY ^ (!skipFlip && texture.isRenderTexture ? 1 : 0); + + if (flipX) + { + width *= -1; + x += srcWidth; + } + + if (flipY) + { + height *= -1; + y += srcHeight; + } + + var xw = x + width; + var yh = y + height; + + spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = srcX; + spriteMatrix.f = srcY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * scrollFactorX; + spriteMatrix.f -= camera.scrollY * scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + this.setTexture2D(texture, 0); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + }, + + /** + * Adds a Texture Frame into the batch for rendering. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTextureFrame + * @since 3.12.0 + * + * @param {Phaser.Textures.Frame} frame - The Texture Frame to be rendered. + * @param {number} x - The horizontal position to render the texture at. + * @param {number} y - The vertical position to render the texture at. + * @param {number} tint - The tint color. + * @param {number} alpha - The alpha value. + * @param {Phaser.GameObjects.Components.TransformMatrix} transformMatrix - The Transform Matrix to use for the texture. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - A parent Transform Matrix. + */ + batchTextureFrame: function ( + frame, + x, y, + tint, alpha, + transformMatrix, + parentTransformMatrix + ) + { + this.renderer.setPipeline(this); + + var spriteMatrix = this._tempMatrix1.copyFrom(transformMatrix); + var calcMatrix = this._tempMatrix2; + + var xw = x + frame.width; + var yh = y + frame.height; + + if (parentTransformMatrix) + { + spriteMatrix.multiply(parentTransformMatrix, calcMatrix); + } + else + { + calcMatrix = spriteMatrix; + } + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + this.setTexture2D(frame.glTexture, 0); + + tint = Utils.getTintAppendFloatAlpha(tint, alpha); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, 0, frame.glTexture, 0); + }, + + /** + * Pushes a filled rectangle into the vertex batch. + * Rectangle has no transform values and isn't transformed into the local space. + * Used for directly batching untransformed rectangles, such as Camera background colors. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#drawFillRect + * @since 3.12.0 + * + * @param {number} x - Horizontal top left coordinate of the rectangle. + * @param {number} y - Vertical top left coordinate of the rectangle. + * @param {number} width - Width of the rectangle. + * @param {number} height - Height of the rectangle. + * @param {number} color - Color of the rectangle to draw. + * @param {number} alpha - Alpha value of the rectangle to draw. + */ + drawFillRect: function (x, y, width, height, color, alpha) + { + var xw = x + width; + var yh = y + height; + + this.setTexture2D(); + + var tint = Utils.getTintAppendFloatAlphaAndSwap(color, alpha); + + this.batchQuad(x, y, x, yh, xw, yh, xw, y, 0, 0, 1, 1, tint, tint, tint, tint, 2); + }, + + /** + * Pushes a filled rectangle into the vertex batch. + * Rectangle factors in the given transform matrices before adding to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillRect + * @since 3.12.0 + * + * @param {number} x - Horizontal top left coordinate of the rectangle. + * @param {number} y - Vertical top left coordinate of the rectangle. + * @param {number} width - Width of the rectangle. + * @param {number} height - Height of the rectangle. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchFillRect: function (x, y, width, height, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var xw = x + width; + var yh = y + height; + + var x0 = calcMatrix.getX(x, y); + var y0 = calcMatrix.getY(x, y); + + var x1 = calcMatrix.getX(x, yh); + var y1 = calcMatrix.getY(x, yh); + + var x2 = calcMatrix.getX(xw, yh); + var y2 = calcMatrix.getY(xw, yh); + + var x3 = calcMatrix.getX(xw, y); + var y3 = calcMatrix.getY(xw, y); + + var frame = this.currentFrame; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + this.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.fillTint.BR, this.tintEffect); + }, + + /** + * Pushes a filled triangle into the vertex batch. + * Triangle factors in the given transform matrices before adding to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillTriangle + * @since 3.12.0 + * + * @param {number} x0 - Point 0 x coordinate. + * @param {number} y0 - Point 0 y coordinate. + * @param {number} x1 - Point 1 x coordinate. + * @param {number} y1 - Point 1 y coordinate. + * @param {number} x2 - Point 2 x coordinate. + * @param {number} y2 - Point 2 y coordinate. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchFillTriangle: function (x0, y0, x1, y1, x2, y2, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var tx0 = calcMatrix.getX(x0, y0); + var ty0 = calcMatrix.getY(x0, y0); + + var tx1 = calcMatrix.getX(x1, y1); + var ty1 = calcMatrix.getY(x1, y1); + + var tx2 = calcMatrix.getX(x2, y2); + var ty2 = calcMatrix.getY(x2, y2); + + var frame = this.currentFrame; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.tintEffect); + }, + + /** + * Pushes a stroked triangle into the vertex batch. + * Triangle factors in the given transform matrices before adding to the batch. + * The triangle is created from 3 lines and drawn using the `batchStrokePath` method. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchStrokeTriangle + * @since 3.12.0 + * + * @param {number} x0 - Point 0 x coordinate. + * @param {number} y0 - Point 0 y coordinate. + * @param {number} x1 - Point 1 x coordinate. + * @param {number} y1 - Point 1 y coordinate. + * @param {number} x2 - Point 2 x coordinate. + * @param {number} y2 - Point 2 y coordinate. + * @param {number} lineWidth - The width of the line in pixels. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchStrokeTriangle: function (x0, y0, x1, y1, x2, y2, lineWidth, currentMatrix, parentMatrix) + { + var tempTriangle = this.tempTriangle; + + tempTriangle[0].x = x0; + tempTriangle[0].y = y0; + tempTriangle[0].width = lineWidth; + + tempTriangle[1].x = x1; + tempTriangle[1].y = y1; + tempTriangle[1].width = lineWidth; + + tempTriangle[2].x = x2; + tempTriangle[2].y = y2; + tempTriangle[2].width = lineWidth; + + tempTriangle[3].x = x0; + tempTriangle[3].y = y0; + tempTriangle[3].width = lineWidth; + + this.batchStrokePath(tempTriangle, lineWidth, false, currentMatrix, parentMatrix); + }, + + /** + * Adds the given path to the vertex batch for rendering. + * + * It works by taking the array of path data and then passing it through Earcut, which + * creates a list of polygons. Each polygon is then added to the batch. + * + * The path is always automatically closed because it's filled. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillPath + * @since 3.12.0 + * + * @param {array} path - Collection of points that represent the path. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchFillPath: function (path, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var length = path.length; + var polygonCache = this.polygonCache; + var polygonIndexArray; + var point; + + var tintTL = this.fillTint.TL; + var tintTR = this.fillTint.TR; + var tintBL = this.fillTint.BL; + var tintEffect = this.tintEffect; + + for (var pathIndex = 0; pathIndex < length; ++pathIndex) + { + point = path[pathIndex]; + polygonCache.push(point.x, point.y); + } + + polygonIndexArray = Earcut(polygonCache); + length = polygonIndexArray.length; + + var frame = this.currentFrame; + + for (var index = 0; index < length; index += 3) + { + var p0 = polygonIndexArray[index + 0] * 2; + var p1 = polygonIndexArray[index + 1] * 2; + var p2 = polygonIndexArray[index + 2] * 2; + + var x0 = polygonCache[p0 + 0]; + var y0 = polygonCache[p0 + 1]; + var x1 = polygonCache[p1 + 0]; + var y1 = polygonCache[p1 + 1]; + var x2 = polygonCache[p2 + 0]; + var y2 = polygonCache[p2 + 1]; + + var tx0 = calcMatrix.getX(x0, y0); + var ty0 = calcMatrix.getY(x0, y0); + + var tx1 = calcMatrix.getX(x1, y1); + var ty1 = calcMatrix.getY(x1, y1); + + var tx2 = calcMatrix.getX(x2, y2); + var ty2 = calcMatrix.getY(x2, y2); + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect); + } + + polygonCache.length = 0; + }, + + /** + * Adds the given path to the vertex batch for rendering. + * + * It works by taking the array of path data and calling `batchLine` for each section + * of the path. + * + * The path is optionally closed at the end. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchStrokePath + * @since 3.12.0 + * + * @param {array} path - Collection of points that represent the path. + * @param {number} lineWidth - The width of the line segments in pixels. + * @param {boolean} pathOpen - Indicates if the path should be closed or left open. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchStrokePath: function (path, lineWidth, pathOpen, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + // Reset the closePath booleans + this.prevQuad[4] = 0; + this.firstQuad[4] = 0; + + var pathLength = path.length - 1; + + for (var pathIndex = 0; pathIndex < pathLength; pathIndex++) + { + var point0 = path[pathIndex]; + var point1 = path[pathIndex + 1]; + + this.batchLine( + point0.x, + point0.y, + point1.x, + point1.y, + point0.width / 2, + point1.width / 2, + lineWidth, + pathIndex, + !pathOpen && (pathIndex === pathLength - 1), + currentMatrix, + parentMatrix + ); + } + }, + + /** + * Creates a quad and adds it to the vertex batch based on the given line values. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchLine + * @since 3.12.0 + * + * @param {number} ax - X coordinate to the start of the line + * @param {number} ay - Y coordinate to the start of the line + * @param {number} bx - X coordinate to the end of the line + * @param {number} by - Y coordinate to the end of the line + * @param {number} aLineWidth - Width of the start of the line + * @param {number} bLineWidth - Width of the end of the line + * @param {Float32Array} currentMatrix - Parent matrix, generally used by containers + */ + batchLine: function (ax, ay, bx, by, aLineWidth, bLineWidth, lineWidth, index, closePath, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var dx = bx - ax; + var dy = by - ay; + + var len = Math.sqrt(dx * dx + dy * dy); + var al0 = aLineWidth * (by - ay) / len; + var al1 = aLineWidth * (ax - bx) / len; + var bl0 = bLineWidth * (by - ay) / len; + var bl1 = bLineWidth * (ax - bx) / len; + + var lx0 = bx - bl0; + var ly0 = by - bl1; + var lx1 = ax - al0; + var ly1 = ay - al1; + var lx2 = bx + bl0; + var ly2 = by + bl1; + var lx3 = ax + al0; + var ly3 = ay + al1; + + // tx0 = bottom right + var brX = calcMatrix.getX(lx0, ly0); + var brY = calcMatrix.getY(lx0, ly0); + + // tx1 = bottom left + var blX = calcMatrix.getX(lx1, ly1); + var blY = calcMatrix.getY(lx1, ly1); + + // tx2 = top right + var trX = calcMatrix.getX(lx2, ly2); + var trY = calcMatrix.getY(lx2, ly2); + + // tx3 = top left + var tlX = calcMatrix.getX(lx3, ly3); + var tlY = calcMatrix.getY(lx3, ly3); + + var tint = this.strokeTint; + var tintEffect = this.tintEffect; + + var tintTL = tint.TL; + var tintTR = tint.TR; + var tintBL = tint.BL; + var tintBR = tint.BR; + + var frame = this.currentFrame; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + // TL, BL, BR, TR + this.batchQuad(tlX, tlY, blX, blY, brX, brY, trX, trY, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); + + if (lineWidth <= 2) + { + // No point doing a linejoin if the line isn't thick enough + return; + } + + var prev = this.prevQuad; + var first = this.firstQuad; + + if (index > 0 && prev[4]) + { + this.batchQuad(tlX, tlY, blX, blY, prev[0], prev[1], prev[2], prev[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); + } + else + { + first[0] = tlX; + first[1] = tlY; + first[2] = blX; + first[3] = blY; + first[4] = 1; + } + + if (closePath && first[4]) + { + // Add a join for the final path segment + this.batchQuad(brX, brY, trX, trY, first[0], first[1], first[2], first[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); + } + else + { + // Store it + + prev[0] = brX; + prev[1] = brY; + prev[2] = trX; + prev[3] = trY; + prev[4] = 1; + } + } + +}); + +module.exports = TextureTintPipeline; + + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); +var MATH_CONST = __webpack_require__(13); + +// points is an array of Point-like objects, +// either 2 dimensional arrays, or objects with public x/y properties: +// var points = [ +// [100, 200], +// [200, 400], +// { x: 30, y: 60 } +// ] + +/** + * Constructs new Rectangle or repositions and resizes an existing Rectangle so that all of the given points are on or within its bounds. + * + * @function Phaser.Geom.Rectangle.FromPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {array} points - An array of points (either arrays with two elements corresponding to the X and Y coordinate or an object with public `x` and `y` properties) which should be surrounded by the Rectangle. + * @param {Phaser.Geom.Rectangle} [out] - Optional Rectangle to adjust. + * + * @return {Phaser.Geom.Rectangle} The adjusted `out` Rectangle, or a new Rectangle if none was provided. + */ +var FromPoints = function (points, out) +{ + if (out === undefined) { out = new Rectangle(); } + + if (points.length === 0) + { + return out; + } + + var minX = Number.MAX_VALUE; + var minY = Number.MAX_VALUE; + + var maxX = MATH_CONST.MIN_SAFE_INTEGER; + var maxY = MATH_CONST.MIN_SAFE_INTEGER; + + var p; + var px; + var py; + + for (var i = 0; i < points.length; i++) + { + p = points[i]; + + if (Array.isArray(p)) + { + px = p[0]; + py = p[1]; + } + else + { + px = p.x; + py = p.y; + } + + minX = Math.min(minX, px); + minY = Math.min(minY, py); + + maxX = Math.max(maxX, px); + maxY = Math.max(maxY, py); + } + + out.x = minX; + out.y = minY; + out.width = maxX - minX; + out.height = maxY - minY; + + return out; +}; + +module.exports = FromPoints; + + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = { + + CENTER: __webpack_require__(383), + ORIENTATION: __webpack_require__(384), + SCALE_MODE: __webpack_require__(385), + ZOOM: __webpack_require__(386) + +}; + +module.exports = CONST; + + +/***/ }), +/* 191 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Attempts to remove the element from its parentNode in the DOM. + * + * @function Phaser.DOM.RemoveFromDOM + * @since 3.0.0 + * + * @param {HTMLElement} element - The DOM element to remove from its parent node. + */ +var RemoveFromDOM = function (element) +{ + if (element.parentNode) + { + element.parentNode.removeChild(element); + } +}; + +module.exports = RemoveFromDOM; + + +/***/ }), +/* 192 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var INPUT_CONST = { + + /** + * The mouse pointer is being held down. + * + * @name Phaser.Input.MOUSE_DOWN + * @type {integer} + * @since 3.10.0 + */ + MOUSE_DOWN: 0, + + /** + * The mouse pointer is being moved. + * + * @name Phaser.Input.MOUSE_MOVE + * @type {integer} + * @since 3.10.0 + */ + MOUSE_MOVE: 1, + + /** + * The mouse pointer is released. + * + * @name Phaser.Input.MOUSE_UP + * @type {integer} + * @since 3.10.0 + */ + MOUSE_UP: 2, + + /** + * A touch pointer has been started. + * + * @name Phaser.Input.TOUCH_START + * @type {integer} + * @since 3.10.0 + */ + TOUCH_START: 3, + + /** + * A touch pointer has been started. + * + * @name Phaser.Input.TOUCH_MOVE + * @type {integer} + * @since 3.10.0 + */ + TOUCH_MOVE: 4, + + /** + * A touch pointer has been started. + * + * @name Phaser.Input.TOUCH_END + * @type {integer} + * @since 3.10.0 + */ + TOUCH_END: 5, + + /** + * The pointer lock has changed. + * + * @name Phaser.Input.POINTER_LOCK_CHANGE + * @type {integer} + * @since 3.10.0 + */ + POINTER_LOCK_CHANGE: 6, + + /** + * A touch pointer has been been cancelled by the browser. + * + * @name Phaser.Input.TOUCH_CANCEL + * @type {integer} + * @since 3.15.0 + */ + TOUCH_CANCEL: 7, + + /** + * The mouse wheel changes. + * + * @name Phaser.Input.MOUSE_WHEEL + * @type {integer} + * @since 3.18.0 + */ + MOUSE_WHEEL: 8 + +}; + +module.exports = INPUT_CONST; + + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(132); +var DefaultPlugins = __webpack_require__(186); +var Events = __webpack_require__(18); +var GetPhysicsPlugins = __webpack_require__(903); +var GetScenePlugins = __webpack_require__(904); +var NOOP = __webpack_require__(2); +var Settings = __webpack_require__(399); + +/** + * @classdesc + * The Scene Systems class. + * + * This class is available from within a Scene under the property `sys`. + * It is responsible for managing all of the plugins a Scene has running, including the display list, and + * handling the update step and renderer. It also contains references to global systems belonging to Game. + * + * @class Systems + * @memberof Phaser.Scenes + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that owns this Systems instance. + * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - Scene specific configuration settings. + */ +var Systems = new Class({ + + initialize: + + function Systems (scene, config) + { + /** + * A reference to the Scene that these Systems belong to. + * + * @name Phaser.Scenes.Systems#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Phaser Game instance. + * + * @name Phaser.Scenes.Systems#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game; + + /** + * A reference to either the Canvas or WebGL Renderer that this Game is using. + * + * @name Phaser.Scenes.Systems#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.17.0 + */ + this.renderer; + + if (true) + { + /** + * The Facebook Instant Games Plugin. + * + * @name Phaser.Scenes.Systems#facebook + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.12.0 + */ + this.facebook; + } + + /** + * The Scene Configuration object, as passed in when creating the Scene. + * + * @name Phaser.Scenes.Systems#config + * @type {(string|Phaser.Types.Scenes.SettingsConfig)} + * @since 3.0.0 + */ + this.config = config; + + /** + * 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 + */ + this.settings = Settings.create(config); + + /** + * A handy reference to the Scene canvas / context. + * + * @name Phaser.Scenes.Systems#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas; + + /** + * A reference to the Canvas Rendering Context being used by the renderer. + * + * @name Phaser.Scenes.Systems#context + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.context; + + // Global Systems - these are single-instance global managers that belong to Game + + /** + * A reference to the global Animations Manager. + * + * In the default set-up you can access this from within a Scene via the `this.anims` property. + * + * @name Phaser.Scenes.Systems#anims + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.anims; + + /** + * A reference to the global Cache. The Cache stores all files bought in to Phaser via + * the Loader, with the exception of images. Images are stored in the Texture Manager. + * + * In the default set-up you can access this from within a Scene via the `this.cache` property. + * + * @name Phaser.Scenes.Systems#cache + * @type {Phaser.Cache.CacheManager} + * @since 3.0.0 + */ + this.cache; + + /** + * A reference to the global Plugins Manager. + * + * In the default set-up you can access this from within a Scene via the `this.plugins` property. + * + * @name Phaser.Scenes.Systems#plugins + * @type {Phaser.Plugins.PluginManager} + * @since 3.0.0 + */ + this.plugins; + + /** + * A reference to the global registry. This is a game-wide instance of the Data Manager, allowing + * you to exchange data between Scenes via a universal and shared point. + * + * In the default set-up you can access this from within a Scene via the `this.registry` property. + * + * @name Phaser.Scenes.Systems#registry + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.registry; + + /** + * A reference to the global Scale Manager. + * + * In the default set-up you can access this from within a Scene via the `this.scale` property. + * + * @name Phaser.Scenes.Systems#scale + * @type {Phaser.Scale.ScaleManager} + * @since 3.15.0 + */ + this.scale; + + /** + * A reference to the global Sound Manager. + * + * In the default set-up you can access this from within a Scene via the `this.sound` property. + * + * @name Phaser.Scenes.Systems#sound + * @type {(Phaser.Sound.NoAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager)} + * @since 3.0.0 + */ + this.sound; + + /** + * A reference to the global Texture Manager. + * + * In the default set-up you can access this from within a Scene via the `this.textures` property. + * + * @name Phaser.Scenes.Systems#textures + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.textures; + + // Core Plugins - these are non-optional Scene plugins, needed by lots of the other systems + + /** + * A reference to the Scene's Game Object Factory. + * + * Use this to quickly and easily create new Game Object's. + * + * In the default set-up you can access this from within a Scene via the `this.add` property. + * + * @name Phaser.Scenes.Systems#add + * @type {Phaser.GameObjects.GameObjectFactory} + * @since 3.0.0 + */ + this.add; + + /** + * A reference to the Scene's Camera Manager. + * + * Use this to manipulate and create Cameras for this specific Scene. + * + * In the default set-up you can access this from within a Scene via the `this.cameras` property. + * + * @name Phaser.Scenes.Systems#cameras + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.0.0 + */ + this.cameras; + + /** + * A reference to the Scene's Display List. + * + * Use this to organize the children contained in the display list. + * + * In the default set-up you can access this from within a Scene via the `this.children` property. + * + * @name Phaser.Scenes.Systems#displayList + * @type {Phaser.GameObjects.DisplayList} + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene's Event Manager. + * + * Use this to listen for Scene specific events, such as `pause` and `shutdown`. + * + * In the default set-up you can access this from within a Scene via the `this.events` property. + * + * @name Phaser.Scenes.Systems#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events; + + /** + * A reference to the Scene's Game Object Creator. + * + * Use this to quickly and easily create new Game Object's. The difference between this and the + * Game Object Factory, is that the Creator just creates and returns Game Object instances, it + * doesn't then add them to the Display List or Update List. + * + * In the default set-up you can access this from within a Scene via the `this.make` property. + * + * @name Phaser.Scenes.Systems#make + * @type {Phaser.GameObjects.GameObjectCreator} + * @since 3.0.0 + */ + this.make; + + /** + * A reference to the Scene Manager Plugin. + * + * Use this to manipulate both this and other Scene's in your game, for example to launch a parallel Scene, + * or pause or resume a Scene, or switch from this Scene to another. + * + * In the default set-up you can access this from within a Scene via the `this.scene` property. + * + * @name Phaser.Scenes.Systems#scenePlugin + * @type {Phaser.Scenes.ScenePlugin} + * @since 3.0.0 + */ + this.scenePlugin; + + /** + * A reference to the Scene's Update List. + * + * Use this to organize the children contained in the update list. + * + * The Update List is responsible for managing children that need their `preUpdate` methods called, + * in order to process so internal components, such as Sprites with Animations. + * + * In the default set-up there is no reference to this from within the Scene itself. + * + * @name Phaser.Scenes.Systems#updateList + * @type {Phaser.GameObjects.UpdateList} + * @since 3.0.0 + */ + this.updateList; + + /** + * The Scene Update function. + * + * This starts out as NOOP during init, preload and create, and at the end of create + * it swaps to be whatever the Scene.update function is. + * + * @name Phaser.Scenes.Systems#sceneUpdate + * @type {function} + * @private + * @since 3.10.0 + */ + this.sceneUpdate = NOOP; + }, + + /** + * This method is called only once by the Scene Manager when the Scene is instantiated. + * It is responsible for setting up all of the Scene plugins and references. + * It should never be called directly. + * + * @method Phaser.Scenes.Systems#init + * @protected + * @fires Phaser.Scenes.Events#BOOT + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser Game instance. + */ + init: function (game) + { + this.settings.status = CONST.INIT; + + // This will get replaced by the SceneManager with the actual update function, if it exists, once create is over. + this.sceneUpdate = NOOP; + + this.game = game; + this.renderer = game.renderer; + + this.canvas = game.canvas; + this.context = game.context; + + var pluginManager = game.plugins; + + this.plugins = pluginManager; + + pluginManager.addToScene(this, DefaultPlugins.Global, [ DefaultPlugins.CoreScene, GetScenePlugins(this), GetPhysicsPlugins(this) ]); + + this.events.emit(Events.BOOT, this); + + this.settings.isBooted = true; + }, + + /** + * Called by a plugin, it tells the System to install the plugin locally. + * + * @method Phaser.Scenes.Systems#install + * @private + * @since 3.0.0 + * + * @param {array} plugin - An array of plugins to install into this Scene. + */ + install: function (plugin) + { + if (!Array.isArray(plugin)) + { + plugin = [ plugin ]; + } + + this.plugins.installLocal(this, plugin); + }, + + /** + * A single game step. Called automatically by the Scene Manager as a result of a Request Animation + * Frame or Set Timeout call to the main Game instance. + * + * @method Phaser.Scenes.Systems#step + * @fires Phaser.Scenes.Events#PRE_UPDATE + * @fires Phaser.Scenes.Events#_UPDATE + * @fires Phaser.Scenes.Events#POST_UPDATE + * @since 3.0.0 + * + * @param {number} time - The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). + * @param {number} delta - The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. + */ + step: function (time, delta) + { + this.events.emit(Events.PRE_UPDATE, time, delta); + + this.events.emit(Events.UPDATE, time, delta); + + this.sceneUpdate.call(this.scene, time, delta); + + this.events.emit(Events.POST_UPDATE, time, delta); + }, + + /** + * Called automatically by the Scene Manager. + * Instructs the Scene to render itself via its Camera Manager to the renderer given. + * + * @method Phaser.Scenes.Systems#render + * @fires Phaser.Scenes.Events#RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer that invoked the render call. + */ + render: function (renderer) + { + var displayList = this.displayList; + + displayList.depthSort(); + + this.cameras.render(renderer, displayList); + + this.events.emit(Events.RENDER, renderer); + }, + + /** + * Force a sort of the display list on the next render. + * + * @method Phaser.Scenes.Systems#queueDepthSort + * @since 3.0.0 + */ + queueDepthSort: function () + { + this.displayList.queueDepthSort(); + }, + + /** + * Immediately sorts the display list if the flag is set. + * + * @method Phaser.Scenes.Systems#depthSort + * @since 3.0.0 + */ + depthSort: function () + { + this.displayList.depthSort(); + }, + + /** + * Pause this Scene. + * A paused Scene still renders, it just doesn't run ANY of its update handlers or systems. + * + * @method Phaser.Scenes.Systems#pause + * @fires Phaser.Scenes.Events#PAUSE + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'pause' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + pause: function (data) + { + if (this.settings.active) + { + this.settings.status = CONST.PAUSED; + + this.settings.active = false; + + this.events.emit(Events.PAUSE, this, data); + } + + return this; + }, + + /** + * Resume this Scene from a paused state. + * + * @method Phaser.Scenes.Systems#resume + * @fires Phaser.Scenes.Events#RESUME + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'resume' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + resume: function (data) + { + if (!this.settings.active) + { + this.settings.status = CONST.RUNNING; + + this.settings.active = true; + + this.events.emit(Events.RESUME, this, data); + } + + return this; + }, + + /** + * Send this Scene to sleep. + * + * A sleeping Scene doesn't run its update step or render anything, but it also isn't shut down + * or has any of its systems or children removed, meaning it can be re-activated at any point and + * will carry on from where it left off. It also keeps everything in memory and events and callbacks + * from other Scenes may still invoke changes within it, so be careful what is left active. + * + * @method Phaser.Scenes.Systems#sleep + * @fires Phaser.Scenes.Events#SLEEP + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'sleep' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + sleep: function (data) + { + this.settings.status = CONST.SLEEPING; + + this.settings.active = false; + this.settings.visible = false; + + this.events.emit(Events.SLEEP, this, data); + + return this; + }, + + /** + * Wake-up this Scene if it was previously asleep. + * + * @method Phaser.Scenes.Systems#wake + * @fires Phaser.Scenes.Events#WAKE + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'wake' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + wake: function (data) + { + var settings = this.settings; + + settings.status = CONST.RUNNING; + + settings.active = true; + settings.visible = true; + + this.events.emit(Events.WAKE, this, data); + + if (settings.isTransition) + { + this.events.emit(Events.TRANSITION_WAKE, settings.transitionFrom, settings.transitionDuration); + } + + return this; + }, + + /** + * Returns any data that was sent to this Scene by another Scene. + * + * The data is also passed to `Scene.init` and in various Scene events, but + * you can access it at any point via this method. + * + * @method Phaser.Scenes.Systems#getData + * @since 3.22.0 + * + * @return {any} + */ + getData: function () + { + return this.settings.data; + }, + + /** + * Is this Scene sleeping? + * + * @method Phaser.Scenes.Systems#isSleeping + * @since 3.0.0 + * + * @return {boolean} `true` if this Scene is asleep, otherwise `false`. + */ + isSleeping: function () + { + return (this.settings.status === CONST.SLEEPING); + }, + + /** + * Is this Scene running? + * + * @method Phaser.Scenes.Systems#isActive + * @since 3.0.0 + * + * @return {boolean} `true` if this Scene is running, otherwise `false`. + */ + isActive: function () + { + return (this.settings.status === CONST.RUNNING); + }, + + /** + * Is this Scene paused? + * + * @method Phaser.Scenes.Systems#isPaused + * @since 3.13.0 + * + * @return {boolean} `true` if this Scene is paused, otherwise `false`. + */ + isPaused: function () + { + return (this.settings.status === CONST.PAUSED); + }, + + /** + * Is this Scene currently transitioning out to, or in from another Scene? + * + * @method Phaser.Scenes.Systems#isTransitioning + * @since 3.5.0 + * + * @return {boolean} `true` if this Scene is currently transitioning, otherwise `false`. + */ + isTransitioning: function () + { + return (this.settings.isTransition || this.scenePlugin._target !== null); + }, + + /** + * Is this Scene currently transitioning out from itself to another Scene? + * + * @method Phaser.Scenes.Systems#isTransitionOut + * @since 3.5.0 + * + * @return {boolean} `true` if this Scene is in transition to another Scene, otherwise `false`. + */ + isTransitionOut: function () + { + return (this.scenePlugin._target !== null && this.scenePlugin._duration > 0); + }, + + /** + * Is this Scene currently transitioning in from another Scene? + * + * @method Phaser.Scenes.Systems#isTransitionIn + * @since 3.5.0 + * + * @return {boolean} `true` if this Scene is transitioning in from another Scene, otherwise `false`. + */ + isTransitionIn: function () + { + return (this.settings.isTransition); + }, + + /** + * Is this Scene visible and rendering? + * + * @method Phaser.Scenes.Systems#isVisible + * @since 3.0.0 + * + * @return {boolean} `true` if this Scene is visible, otherwise `false`. + */ + isVisible: function () + { + return this.settings.visible; + }, + + /** + * Sets the visible state of this Scene. + * An invisible Scene will not render, but will still process updates. + * + * @method Phaser.Scenes.Systems#setVisible + * @since 3.0.0 + * + * @param {boolean} value - `true` to render this Scene, otherwise `false`. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + setVisible: function (value) + { + this.settings.visible = value; + + return this; + }, + + /** + * Set the active state of this Scene. + * + * An active Scene will run its core update loop. + * + * @method Phaser.Scenes.Systems#setActive + * @since 3.0.0 + * + * @param {boolean} value - If `true` the Scene will be resumed, if previously paused. If `false` it will be paused. + * @param {object} [data] - A data object that will be passed in the 'resume' or 'pause' events. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + setActive: function (value, data) + { + if (value) + { + return this.resume(data); + } + else + { + return this.pause(data); + } + }, + + /** + * Start this Scene running and rendering. + * Called automatically by the SceneManager. + * + * @method Phaser.Scenes.Systems#start + * @fires Phaser.Scenes.Events#START + * @fires Phaser.Scenes.Events#READY + * @since 3.0.0 + * + * @param {object} data - Optional data object that may have been passed to this Scene from another. + */ + start: function (data) + { + if (data) + { + this.settings.data = data; + } + + this.settings.status = CONST.START; + + this.settings.active = true; + this.settings.visible = true; + + // For plugins to listen out for + this.events.emit(Events.START, this); + + // For user-land code to listen out for + this.events.emit(Events.READY, this, data); + }, + + /** + * Shutdown this Scene and send a shutdown event to all of its systems. + * A Scene that has been shutdown will not run its update loop or render, but it does + * not destroy any of its plugins or references. It is put into hibernation for later use. + * If you don't ever plan to use this Scene again, then it should be destroyed instead + * to free-up resources. + * + * @method Phaser.Scenes.Systems#shutdown + * @fires Phaser.Scenes.Events#SHUTDOWN + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'shutdown' event. + */ + shutdown: function (data) + { + this.events.off(Events.TRANSITION_INIT); + this.events.off(Events.TRANSITION_START); + this.events.off(Events.TRANSITION_COMPLETE); + this.events.off(Events.TRANSITION_OUT); + + this.settings.status = CONST.SHUTDOWN; + + this.settings.active = false; + this.settings.visible = false; + + this.events.emit(Events.SHUTDOWN, this, data); + }, + + /** + * Destroy this Scene and send a destroy event all of its systems. + * A destroyed Scene cannot be restarted. + * You should not call this directly, instead use `SceneManager.remove`. + * + * @method Phaser.Scenes.Systems#destroy + * @private + * @fires Phaser.Scenes.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + this.settings.status = CONST.DESTROYED; + + this.settings.active = false; + this.settings.visible = false; + + this.events.emit(Events.DESTROY, this); + + this.events.removeAllListeners(); + + var props = [ 'scene', 'game', 'anims', 'cache', 'plugins', 'registry', 'sound', 'textures', 'add', 'camera', 'displayList', 'events', 'make', 'scenePlugin', 'updateList' ]; + + for (var i = 0; i < props.length; i++) + { + this[props[i]] = null; + } + } + +}); + +module.exports = Systems; + + +/***/ }), +/* 194 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Capitalizes the first letter of a string if there is one. + * @example + * UppercaseFirst('abc'); + * // returns 'Abc' + * @example + * UppercaseFirst('the happy family'); + * // returns 'The happy family' + * @example + * UppercaseFirst(''); + * // returns '' + * + * @function Phaser.Utils.String.UppercaseFirst + * @since 3.0.0 + * + * @param {string} str - The string to capitalize. + * + * @return {string} A new string, same as the first, but with the first letter capitalized. + */ +var UppercaseFirst = function (str) +{ + return str && str[0].toUpperCase() + str.slice(1); +}; + +module.exports = UppercaseFirst; + + +/***/ }), +/* 195 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Frame = __webpack_require__(106); +var TextureSource = __webpack_require__(402); + +var TEXTURE_MISSING_ERROR = 'Texture.frame missing: '; + +/** + * @classdesc + * A Texture consists of a source, usually an Image from the Cache, and a collection of Frames. + * The Frames represent the different areas of the Texture. For example a texture atlas + * may have many Frames, one for each element within the atlas. Where-as a single image would have + * just one frame, that encompasses the whole image. + * + * Every Texture, no matter where it comes from, always has at least 1 frame called the `__BASE` frame. + * This frame represents the entirety of the source image. + * + * Textures are managed by the global TextureManager. This is a singleton class that is + * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. + * + * Sprites and other Game Objects get the texture data they need from the TextureManager. + * + * @class Texture + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Textures.TextureManager} manager - A reference to the Texture Manager this Texture belongs to. + * @param {string} key - The unique string-based key of this Texture. + * @param {(HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[])} source - An array of sources that are used to create the texture. Usually Images, but can also be a Canvas. + * @param {number} [width] - The width of the Texture. This is optional and automatically derived from the source images. + * @param {number} [height] - The height of the Texture. This is optional and automatically derived from the source images. + */ +var Texture = new Class({ + + initialize: + + function Texture (manager, key, source, width, height) + { + if (!Array.isArray(source)) + { + source = [ source ]; + } + + /** + * A reference to the Texture Manager this Texture belongs to. + * + * @name Phaser.Textures.Texture#manager + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The unique string-based key of this Texture. + * + * @name Phaser.Textures.Texture#key + * @type {string} + * @since 3.0.0 + */ + this.key = key; + + /** + * An array of TextureSource instances. + * These are unique to this Texture and contain the actual Image (or Canvas) data. + * + * @name Phaser.Textures.Texture#source + * @type {Phaser.Textures.TextureSource[]} + * @since 3.0.0 + */ + this.source = []; + + /** + * An array of TextureSource data instances. + * Used to store additional data images, such as normal maps or specular maps. + * + * @name Phaser.Textures.Texture#dataSource + * @type {array} + * @since 3.0.0 + */ + this.dataSource = []; + + /** + * A key-value object pair associating the unique Frame keys with the Frames objects. + * + * @name Phaser.Textures.Texture#frames + * @type {object} + * @since 3.0.0 + */ + this.frames = {}; + + /** + * Any additional data that was set in the source JSON (if any), + * or any extra data you'd like to store relating to this texture + * + * @name Phaser.Textures.Texture#customData + * @type {object} + * @since 3.0.0 + */ + this.customData = {}; + + /** + * The name of the first frame of the Texture. + * + * @name Phaser.Textures.Texture#firstFrame + * @type {string} + * @since 3.0.0 + */ + this.firstFrame = '__BASE'; + + /** + * The total number of Frames in this Texture, including the `__BASE` frame. + * + * A Texture will always contain at least 1 frame because every Texture contains a `__BASE` frame by default, + * in addition to any extra frames that have been added to it, such as when parsing a Sprite Sheet or Texture Atlas. + * + * @name Phaser.Textures.Texture#frameTotal + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.frameTotal = 0; + + // Load the Sources + for (var i = 0; i < source.length; i++) + { + this.source.push(new TextureSource(this, source[i], width, height)); + } + }, + + /** + * Adds a new Frame to this Texture. + * + * A Frame is a rectangular region of a TextureSource with a unique index or string-based key. + * + * The name given must be unique within this Texture. If it already exists, this method will return `null`. + * + * @method Phaser.Textures.Texture#add + * @since 3.0.0 + * + * @param {(integer|string)} name - The name of this Frame. The name is unique within the Texture. + * @param {integer} sourceIndex - The index of the TextureSource that this Frame is a part of. + * @param {number} x - The x coordinate of the top-left of this Frame. + * @param {number} y - The y coordinate of the top-left of this Frame. + * @param {number} width - The width of this Frame. + * @param {number} height - The height of this Frame. + * + * @return {?Phaser.Textures.Frame} The Frame that was added to this Texture, or `null` if the given name already exists. + */ + add: function (name, sourceIndex, x, y, width, height) + { + if (this.has(name)) + { + return null; + } + + var frame = new Frame(this, name, sourceIndex, x, y, width, height); + + this.frames[name] = frame; + + // 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 + if (this.firstFrame === '__BASE') + { + this.firstFrame = name; + } + + this.frameTotal++; + + return frame; + }, + + /** + * Removes the given Frame from this Texture. The Frame is destroyed immediately. + * + * Any Game Objects using this Frame should stop using it _before_ you remove it, + * as it does not happen automatically. + * + * @method Phaser.Textures.Texture#remove + * @since 3.19.0 + * + * @param {string} name - The key of the Frame to remove. + * + * @return {boolean} True if a Frame with the matching key was removed from this Texture. + */ + remove: function (name) + { + if (this.has(name)) + { + var frame = this.get(name); + + frame.destroy(); + + delete this.frames[name]; + + return true; + } + + return false; + }, + + /** + * Checks to see if a Frame matching the given key exists within this Texture. + * + * @method Phaser.Textures.Texture#has + * @since 3.0.0 + * + * @param {string} name - The key of the Frame to check for. + * + * @return {boolean} True if a Frame with the matching key exists in this Texture. + */ + has: function (name) + { + return (this.frames[name]); + }, + + /** + * 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|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. + * + * @return {Phaser.Textures.Frame} The Texture Frame. + */ + get: function (name) + { + // null, undefined, empty string, zero + if (!name) + { + name = this.firstFrame; + } + + var frame = this.frames[name]; + + if (!frame) + { + console.warn(TEXTURE_MISSING_ERROR + name); + + frame = this.frames[this.firstFrame]; + } + + return frame; + }, + + /** + * Takes the given TextureSource and returns the index of it within this Texture. + * If it's not in this Texture, it returns -1. + * Unless this Texture has multiple TextureSources, such as with a multi-atlas, this + * method will always return zero or -1. + * + * @method Phaser.Textures.Texture#getTextureSourceIndex + * @since 3.0.0 + * + * @param {Phaser.Textures.TextureSource} source - The TextureSource to check. + * + * @return {integer} The index of the TextureSource within this Texture, or -1 if not in this Texture. + */ + getTextureSourceIndex: function (source) + { + for (var i = 0; i < this.source.length; i++) + { + if (this.source[i] === source) + { + return i; + } + } + + return -1; + }, + + /** + * Returns an array of all the Frames in the given TextureSource. + * + * @method Phaser.Textures.Texture#getFramesFromTextureSource + * @since 3.0.0 + * + * @param {integer} sourceIndex - The index of the TextureSource to get the Frames from. + * @param {boolean} [includeBase=false] - Include the `__BASE` Frame in the output array? + * + * @return {Phaser.Textures.Frame[]} An array of Texture Frames. + */ + getFramesFromTextureSource: function (sourceIndex, includeBase) + { + if (includeBase === undefined) { includeBase = false; } + + var out = []; + + for (var frameName in this.frames) + { + if (frameName === '__BASE' && !includeBase) + { + continue; + } + + var frame = this.frames[frameName]; + + if (frame.sourceIndex === sourceIndex) + { + out.push(frame); + } + } + + return out; + }, + + /** + * Returns an array with all of the names of the Frames in this Texture. + * + * Useful if you want to randomly assign a Frame to a Game Object, as you can + * pick a random element from the returned array. + * + * @method Phaser.Textures.Texture#getFrameNames + * @since 3.0.0 + * + * @param {boolean} [includeBase=false] - Include the `__BASE` Frame in the output array? + * + * @return {string[]} An array of all Frame names in this Texture. + */ + getFrameNames: function (includeBase) + { + if (includeBase === undefined) { includeBase = false; } + + var out = Object.keys(this.frames); + + if (!includeBase) + { + var idx = out.indexOf('__BASE'); + + if (idx !== -1) + { + out.splice(idx, 1); + } + } + + return out; + }, + + /** + * Given a Frame name, return the source image it uses to render with. + * + * This will return the actual DOM Image or Canvas element. + * + * @method Phaser.Textures.Texture#getSourceImage + * @since 3.0.0 + * + * @param {(string|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. + * + * @return {(HTMLImageElement|HTMLCanvasElement|Phaser.GameObjects.RenderTexture)} The DOM Image, Canvas Element or Render Texture. + */ + getSourceImage: function (name) + { + if (name === undefined || name === null || this.frameTotal === 1) + { + name = '__BASE'; + } + + var frame = this.frames[name]; + + if (frame) + { + return frame.source.image; + } + else + { + console.warn(TEXTURE_MISSING_ERROR + name); + + return this.frames['__BASE'].source.image; + } + }, + + /** + * Given a Frame name, return the data source image it uses to render with. + * You can use this to get the normal map for an image for example. + * + * This will return the actual DOM Image. + * + * @method Phaser.Textures.Texture#getDataSourceImage + * @since 3.7.0 + * + * @param {(string|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. + * + * @return {(HTMLImageElement|HTMLCanvasElement)} The DOM Image or Canvas Element. + */ + getDataSourceImage: function (name) + { + if (name === undefined || name === null || this.frameTotal === 1) + { + name = '__BASE'; + } + + var frame = this.frames[name]; + var idx; + + if (!frame) + { + console.warn(TEXTURE_MISSING_ERROR + name); + + idx = this.frames['__BASE'].sourceIndex; + } + else + { + idx = frame.sourceIndex; + } + + return this.dataSource[idx].image; + }, + + /** + * Adds a data source image to this Texture. + * + * An example of a data source image would be a normal map, where all of the Frames for this Texture + * equally apply to the normal map. + * + * @method Phaser.Textures.Texture#setDataSource + * @since 3.0.0 + * + * @param {(HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[])} data - The source image. + */ + setDataSource: function (data) + { + if (!Array.isArray(data)) + { + data = [ data ]; + } + + for (var i = 0; i < data.length; i++) + { + var source = this.source[i]; + + this.dataSource.push(new TextureSource(this, data[i], source.width, source.height)); + } + }, + + /** + * Sets the Filter Mode for this Texture. + * + * The mode can be either Linear, the default, or Nearest. + * + * For pixel-art you should use Nearest. + * + * The mode applies to the entire Texture, not just a specific Frame of it. + * + * @method Phaser.Textures.Texture#setFilter + * @since 3.0.0 + * + * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode. + */ + setFilter: function (filterMode) + { + var i; + + for (i = 0; i < this.source.length; i++) + { + this.source[i].setFilter(filterMode); + } + + for (i = 0; i < this.dataSource.length; i++) + { + this.dataSource[i].setFilter(filterMode); + } + }, + + /** + * Destroys this Texture and releases references to its sources and frames. + * + * @method Phaser.Textures.Texture#destroy + * @since 3.0.0 + */ + destroy: function () + { + var i; + + for (i = 0; i < this.source.length; i++) + { + this.source[i].destroy(); + } + + for (i = 0; i < this.dataSource.length; i++) + { + this.dataSource[i].destroy(); + } + + for (var frameName in this.frames) + { + var frame = this.frames[frameName]; + + frame.destroy(); + } + + this.source = []; + this.dataSource = []; + this.frames = {}; + + this.manager.removeKey(this.key); + + this.manager = null; + } + +}); + +module.exports = Texture; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Array + */ + +module.exports = { + + Matrix: __webpack_require__(944), + + Add: __webpack_require__(951), + AddAt: __webpack_require__(952), + BringToTop: __webpack_require__(953), + CountAllMatching: __webpack_require__(954), + Each: __webpack_require__(955), + EachInRange: __webpack_require__(956), + FindClosestInSorted: __webpack_require__(289), + GetAll: __webpack_require__(957), + GetFirst: __webpack_require__(958), + GetRandom: __webpack_require__(198), + MoveDown: __webpack_require__(959), + MoveTo: __webpack_require__(960), + MoveUp: __webpack_require__(961), + NumberArray: __webpack_require__(962), + NumberArrayStep: __webpack_require__(963), + QuickSelect: __webpack_require__(414), + Range: __webpack_require__(415), + Remove: __webpack_require__(130), + RemoveAt: __webpack_require__(964), + RemoveBetween: __webpack_require__(965), + RemoveRandomElement: __webpack_require__(966), + Replace: __webpack_require__(967), + RotateLeft: __webpack_require__(305), + RotateRight: __webpack_require__(306), + SafeRange: __webpack_require__(74), + SendToBack: __webpack_require__(968), + SetAll: __webpack_require__(969), + Shuffle: __webpack_require__(122), + SpliceOne: __webpack_require__(85), + StableSort: __webpack_require__(137), + Swap: __webpack_require__(970) + +}; + + +/***/ }), +/* 197 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if an array can be used as a matrix. + * + * 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: + * + * ``` + * [ + * [ 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.CheckMatrix + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix] + * + * @param {T[][]} [matrix] - The array to check. + * + * @return {boolean} `true` if the given `matrix` array is a valid matrix. + */ +var CheckMatrix = function (matrix) +{ + if (!Array.isArray(matrix) || matrix.length < 2 || !Array.isArray(matrix[0])) + { + return false; + } + + // How long is the first row? + var size = matrix[0].length; + + // Validate the rest of the rows are the same length + for (var i = 1; i < matrix.length; i++) + { + if (matrix[i].length !== size) + { + return false; + } + } + + return true; +}; + +module.exports = CheckMatrix; + + +/***/ }), +/* 198 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns a Random element from the array. + * + * @function Phaser.Utils.Array.GetRandom + * @since 3.0.0 + * + * @param {array} array - The array to select the random entry from. + * @param {integer} [startIndex=0] - An optional start index. + * @param {integer} [length=array.length] - An optional length, the total number of elements (from the startIndex) to choose from. + * + * @return {*} A random element from the array, or `null` if no element could be found in the range given. + */ +var GetRandom = function (array, startIndex, length) +{ + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = array.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return (array[randomIndex] === undefined) ? null : array[randomIndex]; +}; + +module.exports = GetRandom; + + +/***/ }), +/* 199 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(972); + +/** + * @classdesc + * A Process Queue maintains three internal lists. + * + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * The `active` list is a selection of items which are considered active and should be updated. + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * When new items are added to a Process Queue they are put in the pending list, rather than being added + * immediately the active list. Equally, items that are removed are put into the destroy list, rather than + * being destroyed immediately. This allows the Process Queue to carefully process each item at a specific, fixed + * time, rather than at the time of the request from the API. + * + * @class ProcessQueue + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic T + */ +var ProcessQueue = new Class({ + + Extends: EventEmitter, + + initialize: + + function ProcessQueue () + { + EventEmitter.call(this); + + /** + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.ProcessQueue#_pending + * @type {Array.<*>} + * @private + * @default [] + * @since 3.0.0 + */ + this._pending = []; + + /** + * The `active` list is a selection of items which are considered active and should be updated. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.ProcessQueue#_active + * @type {Array.<*>} + * @private + * @default [] + * @since 3.0.0 + */ + this._active = []; + + /** + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.ProcessQueue#_destroy + * @type {Array.<*>} + * @private + * @default [] + * @since 3.0.0 + */ + this._destroy = []; + + /** + * The total number of items awaiting processing. + * + * @name Phaser.Structs.ProcessQueue#_toProcess + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._toProcess = 0; + }, + + /** + * Adds a new item to the Process Queue. + * + * The item is added to the pending list and made active in the next update. + * + * @method Phaser.Structs.ProcessQueue#add + * @since 3.0.0 + * + * @genericUse {T} - [item] + * @genericUse {Phaser.Structs.ProcessQueue.} - [$return] + * + * @param {*} item - The item to add to the queue. + * + * @return {*} The item that was added. + */ + add: function (item) + { + this._pending.push(item); + + this._toProcess++; + + return item; + }, + + /** + * Removes an item from the Process Queue. + * + * The item is added to the pending destroy and fully removed in the next update. + * + * @method Phaser.Structs.ProcessQueue#remove + * @since 3.0.0 + * + * @genericUse {T} - [item] + * @genericUse {Phaser.Structs.ProcessQueue.} - [$return] + * + * @param {*} item - The item to be removed from the queue. + * + * @return {*} The item that was removed. + */ + remove: function (item) + { + this._destroy.push(item); + + this._toProcess++; + + return item; + }, + + /** + * Removes all active items from this Process Queue. + * + * All the items are marked as 'pending destroy' and fully removed in the next update. + * + * @method Phaser.Structs.ProcessQueue#removeAll + * @since 3.20.0 + * + * @return {this} This Process Queue object. + */ + removeAll: function () + { + var list = this._active; + var destroy = this._destroy; + var i = list.length; + + while (i--) + { + destroy.push(list[i]); + + this._toProcess++; + } + + return this; + }, + + /** + * Update this queue. First it will process any items awaiting destruction, and remove them. + * + * Then it will check to see if there are any items pending insertion, and move them to an + * active state. Finally, it will return a list of active items for further processing. + * + * @method Phaser.Structs.ProcessQueue#update + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} A list of active items. + */ + update: function () + { + if (this._toProcess === 0) + { + // Quick bail + return this._active; + } + + var list = this._destroy; + var active = this._active; + var i; + var item; + + // Clear the 'destroy' list + for (i = 0; i < list.length; i++) + { + item = list[i]; + + // Remove from the 'active' array + var idx = active.indexOf(item); + + if (idx !== -1) + { + active.splice(idx, 1); + + this.emit(Events.REMOVE, item); + } + } + + list.length = 0; + + // Process the pending addition list + // This stops callbacks and out of sync events from populating the active array mid-way during an update + + list = this._pending; + + for (i = 0; i < list.length; i++) + { + item = list[i]; + + this._active.push(item); + + this.emit(Events.ADD, item); + } + + list.length = 0; + + this._toProcess = 0; + + // The owner of this queue can now safely do whatever it needs to with the active list + return this._active; + }, + + /** + * Returns the current list of active items. + * + * This method returns a reference to the active list array, not a copy of it. + * Therefore, be careful to not modify this array outside of the ProcessQueue. + * + * @method Phaser.Structs.ProcessQueue#getActive + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} A list of active items. + */ + getActive: function () + { + return this._active; + }, + + /** + * The number of entries in the active list. + * + * @name Phaser.Structs.ProcessQueue#length + * @type {integer} + * @readonly + * @since 3.20.0 + */ + length: { + + get: function () + { + return this._active.length; + } + + }, + + /** + * Immediately destroys this process queue, clearing all of its internal arrays and resetting the process totals. + * + * @method Phaser.Structs.ProcessQueue#destroy + * @since 3.0.0 + */ + destroy: function () + { + this._toProcess = 0; + + this._pending = []; + this._active = []; + this._destroy = []; + } + +}); + +module.exports = ProcessQueue; + + +/***/ }), +/* 200 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Read an integer value from an XML Node. + * + * @function getValue + * @since 3.0.0 + * @private + * + * @param {Node} node - The XML Node. + * @param {string} attribute - The attribute to read. + * + * @return {integer} The parsed value. + */ +function getValue (node, attribute) +{ + return parseInt(node.getAttribute(attribute), 10); +} + +/** + * Parse an XML font to Bitmap Font data for the Bitmap Font cache. + * + * @function ParseXMLBitmapFont + * @since 3.0.0 + * @private + * + * @param {XMLDocument} xml - The XML Document to parse the font from. + * @param {integer} [xSpacing=0] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing=0] - The y-axis spacing to add to the line height. + * @param {Phaser.Textures.Frame} [frame] - The texture frame to take into account while parsing. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapFontData} The parsed Bitmap Font data. + */ +var ParseXMLBitmapFont = function (xml, xSpacing, ySpacing, frame) +{ + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = getValue(info, 'size'); + data.lineHeight = getValue(common, 'lineHeight') + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var adjustForTrim = (frame !== undefined && frame.trimmed); + + if (adjustForTrim) + { + var top = frame.height; + var left = frame.width; + } + + for (var i = 0; i < letters.length; i++) + { + var node = letters[i]; + + var charCode = getValue(node, 'id'); + var gx = getValue(node, 'x'); + var gy = getValue(node, 'y'); + var gw = getValue(node, 'width'); + var gh = getValue(node, 'height'); + + // Handle frame trim issues + + if (adjustForTrim) + { + if (gx < left) + { + left = gx; + } + + if (gy < top) + { + top = gy; + } + } + + data.chars[charCode] = + { + x: gx, + y: gy, + width: gw, + height: gh, + centerX: Math.floor(gw / 2), + centerY: Math.floor(gh / 2), + xOffset: getValue(node, 'xoffset'), + yOffset: getValue(node, 'yoffset'), + xAdvance: getValue(node, 'xadvance') + xSpacing, + data: {}, + kerning: {} + }; + } + + if (adjustForTrim && top !== 0 && left !== 0) + { + // Now we know the top and left coordinates of the glyphs in the original data + // so we can work out how much to adjust the glyphs by + + for (var code in data.chars) + { + var glyph = data.chars[code]; + + glyph.x -= frame.x; + glyph.y -= frame.y; + } + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var kern = kernings[i]; + + var first = getValue(kern, 'first'); + var second = getValue(kern, 'second'); + var amount = getValue(kern, 'amount'); + + data.chars[second].kerning[first] = amount; + } + + return data; +}; + +module.exports = ParseXMLBitmapFont; + + +/***/ }), +/* 201 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlitterRender = __webpack_require__(980); +var Bob = __webpack_require__(983); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var Frame = __webpack_require__(106); +var GameObject = __webpack_require__(14); +var List = __webpack_require__(135); + +/** + * @callback CreateCallback + * + * @param {Phaser.GameObjects.Bob} bob - The Bob that was created by the Blitter. + * @param {integer} index - The position of the Bob within the Blitter display list. + */ + +/** + * @classdesc + * A Blitter Game Object. + * + * The Blitter Game Object is a special kind of container that creates, updates and manages Bob objects. + * Bobs are designed for rendering speed rather than flexibility. They consist of a texture, or frame from a texture, + * a position and an alpha value. You cannot scale or rotate them. They use a batched drawing method for speed + * during rendering. + * + * A Blitter Game Object has one texture bound to it. Bobs created by the Blitter can use any Frame from this + * Texture to render with, but they cannot use any other Texture. It is this single texture-bind that allows + * them their speed. + * + * If you have a need to blast a large volume of frames around the screen then Blitter objects are well worth + * investigating. They are especially useful for using as a base for your own special effects systems. + * + * @class Blitter + * @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.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. It can only belong to one Scene at any given time. + * @param {number} [x=0] - The x coordinate of this Game Object in world space. + * @param {number} [y=0] - The y coordinate of this Game Object in world space. + * @param {string} [texture='__DEFAULT'] - The key of the texture this Game Object will use for rendering. The Texture must already exist in the Texture Manager. + * @param {(string|integer)} [frame=0] - The Frame of the Texture that this Game Object will use. Only set if the Texture has multiple frames, such as a Texture Atlas or Sprite Sheet. + */ +var Blitter = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Mask, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.Texture, + Components.Transform, + Components.Visible, + BlitterRender + ], + + initialize: + + function Blitter (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Blitter'); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.initPipeline(); + + /** + * The children of this Blitter. + * This List contains all of the Bob objects created by the Blitter. + * + * @name Phaser.GameObjects.Blitter#children + * @type {Phaser.Structs.List.} + * @since 3.0.0 + */ + this.children = new List(); + + /** + * A transient array that holds all of the Bobs that will be rendered this frame. + * The array is re-populated whenever the dirty flag is set. + * + * @name Phaser.GameObjects.Blitter#renderList + * @type {Phaser.GameObjects.Bob[]} + * @default [] + * @private + * @since 3.0.0 + */ + this.renderList = []; + + /** + * Is the Blitter considered dirty? + * A 'dirty' Blitter has had its child count changed since the last frame. + * + * @name Phaser.GameObjects.Blitter#dirty + * @type {boolean} + * @since 3.0.0 + */ + this.dirty = false; + }, + + /** + * Creates a new Bob in this Blitter. + * + * The Bob is created at the given coordinates, relative to the Blitter and uses the given frame. + * A Bob can use any frame belonging to the texture bound to the Blitter. + * + * @method Phaser.GameObjects.Blitter#create + * @since 3.0.0 + * + * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. + * @param {boolean} [visible=true] - Should the created Bob render or not? + * @param {integer} [index] - The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list. + * + * @return {Phaser.GameObjects.Bob} The newly created Bob object. + */ + create: function (x, y, frame, visible, index) + { + if (visible === undefined) { visible = true; } + if (index === undefined) { index = this.children.length; } + + if (frame === undefined) + { + frame = this.frame; + } + else if (!(frame instanceof Frame)) + { + frame = this.texture.get(frame); + } + + var bob = new Bob(this, x, y, frame, visible); + + this.children.addAt(bob, index, false); + + this.dirty = true; + + return bob; + }, + + /** + * Creates multiple Bob objects within this Blitter and then passes each of them to the specified callback. + * + * @method Phaser.GameObjects.Blitter#createFromCallback + * @since 3.0.0 + * + * @param {CreateCallback} callback - The callback to invoke after creating a bob. It will be sent two arguments: The Bob and the index of the Bob. + * @param {integer} quantity - The quantity of Bob objects to create. + * @param {(string|integer|Phaser.Textures.Frame|string[]|integer[]|Phaser.Textures.Frame[])} [frame] - The Frame the Bobs will use. It must be part of the Blitter Texture. + * @param {boolean} [visible=true] - Should the created Bob render or not? + * + * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that were created. + */ + createFromCallback: function (callback, quantity, frame, visible) + { + var bobs = this.createMultiple(quantity, frame, visible); + + for (var i = 0; i < bobs.length; i++) + { + var bob = bobs[i]; + + callback.call(this, bob, i); + } + + return bobs; + }, + + /** + * Creates multiple Bobs in one call. + * + * The amount created is controlled by a combination of the `quantity` argument and the number of frames provided. + * + * If the quantity is set to 10 and you provide 2 frames, then 20 Bobs will be created. 10 with the first + * frame and 10 with the second. + * + * @method Phaser.GameObjects.Blitter#createMultiple + * @since 3.0.0 + * + * @param {integer} quantity - The quantity of Bob objects to create. + * @param {(string|integer|Phaser.Textures.Frame|string[]|integer[]|Phaser.Textures.Frame[])} [frame] - The Frame the Bobs will use. It must be part of the Blitter Texture. + * @param {boolean} [visible=true] - Should the created Bob render or not? + * + * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that were created. + */ + createMultiple: function (quantity, frame, visible) + { + if (frame === undefined) { frame = this.frame.name; } + if (visible === undefined) { visible = true; } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var bobs = []; + var _this = this; + + frame.forEach(function (singleFrame) + { + for (var i = 0; i < quantity; i++) + { + bobs.push(_this.create(0, 0, singleFrame, visible)); + } + }); + + return bobs; + }, + + /** + * Checks if the given child can render or not, by checking its `visible` and `alpha` values. + * + * @method Phaser.GameObjects.Blitter#childCanRender + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Bob} child - The Bob to check for rendering. + * + * @return {boolean} Returns `true` if the given child can render, otherwise `false`. + */ + childCanRender: function (child) + { + return (child.visible && child.alpha > 0); + }, + + /** + * Returns an array of Bobs to be rendered. + * If the Blitter is dirty then a new list is generated and stored in `renderList`. + * + * @method Phaser.GameObjects.Blitter#getRenderList + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that will be rendered this frame. + */ + getRenderList: function () + { + if (this.dirty) + { + this.renderList = this.children.list.filter(this.childCanRender, this); + this.dirty = false; + } + + return this.renderList; + }, + + /** + * Removes all Bobs from the children List and clears the dirty flag. + * + * @method Phaser.GameObjects.Blitter#clear + * @since 3.0.0 + */ + clear: function () + { + this.children.removeAll(); + this.dirty = true; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Blitter#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + this.children.destroy(); + + this.renderList = []; + } + +}); + +module.exports = Blitter; + + +/***/ }), +/* 202 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayUtils = __webpack_require__(196); +var BlendModes = __webpack_require__(43); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var Events = __webpack_require__(102); +var GameObject = __webpack_require__(14); +var Rectangle = __webpack_require__(11); +var Render = __webpack_require__(984); +var Union = __webpack_require__(417); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Container Game Object. + * + * A Container, as the name implies, can 'contain' other types of Game Object. + * When a Game Object is added to a Container, the Container becomes responsible for the rendering of it. + * By default it will be removed from the Display List and instead added to the Containers own internal list. + * + * The position of the Game Object automatically becomes relative to the position of the Container. + * + * When the Container is rendered, all of its children are rendered as well, in the order in which they exist + * within the Container. Container children can be repositioned using methods such as `MoveUp`, `MoveDown` and `SendToBack`. + * + * If you modify a transform property of the Container, such as `Container.x` or `Container.rotation` then it will + * automatically influence all children as well. + * + * Containers can include other Containers for deeply nested transforms. + * + * Containers can have masks set on them and can be used as a mask too. However, Container children cannot be masked. + * The masks do not 'stack up'. Only a Container on the root of the display list will use its mask. + * + * Containers can be enabled for input. Because they do not have a texture you need to provide a shape for them + * to use as their hit area. Container children can also be enabled for input, independent of the Container. + * + * Containers can be given a physics body for either Arcade Physics, Impact Physics or Matter Physics. However, + * if Container _children_ are enabled for physics you may get unexpected results, such as offset bodies, + * if the Container itself, or any of its ancestors, is positioned anywhere other than at 0 x 0. Container children + * with physics do not factor in the Container due to the excessive extra calculations needed. Please structure + * your game to work around this. + * + * It's important to understand the impact of using Containers. They add additional processing overhead into + * every one of their children. The deeper you nest them, the more the cost escalates. This is especially true + * for input events. You also loose the ability to set the display depth of Container children in the same + * flexible manner as those not within them. In short, don't use them for the sake of it. You pay a small cost + * every time you create one, try to structure your game around avoiding that where possible. + * + * @class Container + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.4.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Mask + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to this Container. + */ +var Container = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.Mask, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + function Container (scene, x, y, children) + { + GameObject.call(this, scene, 'Container'); + + /** + * An array holding the children of this Container. + * + * @name Phaser.GameObjects.Container#list + * @type {Phaser.GameObjects.GameObject[]} + * @since 3.4.0 + */ + this.list = []; + + /** + * Does this Container exclusively manage its children? + * + * The default is `true` which means a child added to this Container cannot + * belong in another Container, which includes the Scene display list. + * + * If you disable this then this Container will no longer exclusively manage its children. + * This allows you to create all kinds of interesting graphical effects, such as replicating + * Game Objects without reparenting them all over the Scene. + * However, doing so will prevent children from receiving any kind of input event or have + * their physics bodies work by default, as they're no longer a single entity on the + * display list, but are being replicated where-ever this Container is. + * + * @name Phaser.GameObjects.Container#exclusive + * @type {boolean} + * @default true + * @since 3.4.0 + */ + this.exclusive = true; + + /** + * Containers can have an optional maximum size. If set to anything above 0 it + * will constrict the addition of new Game Objects into the Container, capping off + * the maximum limit the Container can grow in size to. + * + * @name Phaser.GameObjects.Container#maxSize + * @type {integer} + * @default -1 + * @since 3.4.0 + */ + this.maxSize = -1; + + /** + * The cursor position. + * + * @name Phaser.GameObjects.Container#position + * @type {integer} + * @since 3.4.0 + */ + this.position = 0; + + /** + * Internal Transform Matrix used for local space conversion. + * + * @name Phaser.GameObjects.Container#localTransform + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.4.0 + */ + this.localTransform = new Components.TransformMatrix(); + + /** + * Internal temporary Transform Matrix used to avoid object creation. + * + * @name Phaser.GameObjects.Container#tempTransformMatrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.4.0 + */ + this.tempTransformMatrix = new Components.TransformMatrix(); + + /** + * A reference to the Scene Display List. + * + * @name Phaser.GameObjects.Container#_displayList + * @type {Phaser.GameObjects.DisplayList} + * @private + * @since 3.4.0 + */ + this._displayList = scene.sys.displayList; + + /** + * The property key to sort by. + * + * @name Phaser.GameObjects.Container#_sortKey + * @type {string} + * @private + * @since 3.4.0 + */ + this._sortKey = ''; + + /** + * A reference to the Scene Systems Event Emitter. + * + * @name Phaser.GameObjects.Container#_sysEvents + * @type {Phaser.Events.EventEmitter} + * @private + * @since 3.9.0 + */ + this._sysEvents = scene.sys.events; + + /** + * 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.0.0 + */ + this.scrollFactorX = 1; + + /** + * 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.0.0 + */ + this.scrollFactorY = 1; + + this.setPosition(x, y); + + this.clearAlpha(); + + this.setBlendMode(BlendModes.SKIP_CHECK); + + if (children) + { + this.add(children); + } + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#originX + * @type {number} + * @readonly + * @since 3.4.0 + */ + originX: { + + get: function () + { + return 0.5; + } + + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#originY + * @type {number} + * @readonly + * @since 3.4.0 + */ + originY: { + + get: function () + { + return 0.5; + } + + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#displayOriginX + * @type {number} + * @readonly + * @since 3.4.0 + */ + displayOriginX: { + + get: function () + { + return this.width * 0.5; + } + + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#displayOriginY + * @type {number} + * @readonly + * @since 3.4.0 + */ + displayOriginY: { + + get: function () + { + return this.height * 0.5; + } + + }, + + /** + * Does this Container exclusively manage its children? + * + * The default is `true` which means a child added to this Container cannot + * belong in another Container, which includes the Scene display list. + * + * If you disable this then this Container will no longer exclusively manage its children. + * This allows you to create all kinds of interesting graphical effects, such as replicating + * Game Objects without reparenting them all over the Scene. + * However, doing so will prevent children from receiving any kind of input event or have + * their physics bodies work by default, as they're no longer a single entity on the + * display list, but are being replicated where-ever this Container is. + * + * @method Phaser.GameObjects.Container#setExclusive + * @since 3.4.0 + * + * @param {boolean} [value=true] - The exclusive state of this Container. + * + * @return {Phaser.GameObjects.Container} This Container. + */ + setExclusive: function (value) + { + if (value === undefined) { value = true; } + + this.exclusive = value; + + return this; + }, + + /** + * Gets the bounds of this Container. It works by iterating all children of the Container, + * getting their respective bounds, and then working out a min-max rectangle from that. + * It does not factor in if the children render or not, all are included. + * + * Some children are unable to return their bounds, such as Graphics objects, in which case + * they are skipped. + * + * Depending on the quantity of children in this Container it could be a really expensive call, + * so cache it and only poll it as needed. + * + * The values are stored and returned in a Rectangle object. + * + * @method Phaser.GameObjects.Container#getBounds + * @since 3.4.0 + * + * @param {Phaser.Geom.Rectangle} [output] - A Geom.Rectangle object to store the values in. If not provided a new Rectangle will be created. + * + * @return {Phaser.Geom.Rectangle} The values stored in the output object. + */ + getBounds: function (output) + { + if (output === undefined) { output = new Rectangle(); } + + output.setTo(this.x, this.y, 0, 0); + + if (this.list.length > 0) + { + var children = this.list; + var tempRect = new Rectangle(); + + for (var i = 0; i < children.length; i++) + { + var entry = children[i]; + + if (entry.getBounds) + { + entry.getBounds(tempRect); + + Union(tempRect, output, output); + } + } + } + + return output; + }, + + /** + * Internal add handler. + * + * @method Phaser.GameObjects.Container#addHandler + * @private + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that was just added to this Container. + */ + addHandler: function (gameObject) + { + gameObject.once(Events.DESTROY, this.remove, this); + + if (this.exclusive) + { + this._displayList.remove(gameObject); + + if (gameObject.parentContainer) + { + gameObject.parentContainer.remove(gameObject); + } + + gameObject.parentContainer = this; + } + }, + + /** + * Internal remove handler. + * + * @method Phaser.GameObjects.Container#removeHandler + * @private + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that was just removed from this Container. + */ + removeHandler: function (gameObject) + { + gameObject.off(Events.DESTROY, this.remove); + + if (this.exclusive) + { + gameObject.parentContainer = null; + } + }, + + /** + * Takes a Point-like object, such as a Vector2, Geom.Point or object with public x and y properties, + * and transforms it into the space of this Container, then returns it in the output object. + * + * @method Phaser.GameObjects.Container#pointToContainer + * @since 3.4.0 + * + * @param {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} source - The Source Point to be transformed. + * @param {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} [output] - A destination object to store the transformed point in. If none given a Vector2 will be created and returned. + * + * @return {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} The transformed point. + */ + pointToContainer: function (source, output) + { + if (output === undefined) { output = new Vector2(); } + + if (this.parentContainer) + { + return this.parentContainer.pointToContainer(source, output); + } + + var tempMatrix = this.tempTransformMatrix; + + // No need to loadIdentity because applyITRS overwrites every value anyway + tempMatrix.applyITRS(this.x, this.y, this.rotation, this.scaleX, this.scaleY); + + tempMatrix.invert(); + + tempMatrix.transformPoint(source.x, source.y, output); + + return output; + }, + + /** + * Returns the world transform matrix as used for Bounds checks. + * + * The returned matrix is temporal and shouldn't be stored. + * + * @method Phaser.GameObjects.Container#getBoundsTransformMatrix + * @since 3.4.0 + * + * @return {Phaser.GameObjects.Components.TransformMatrix} The world transform matrix. + */ + getBoundsTransformMatrix: function () + { + return this.getWorldTransformMatrix(this.tempTransformMatrix, this.localTransform); + }, + + /** + * Adds the given Game Object, or array of Game Objects, to this Container. + * + * Each Game Object must be unique within the Container. + * + * @method Phaser.GameObjects.Container#add + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + add: function (child) + { + ArrayUtils.Add(this.list, child, this.maxSize, this.addHandler, this); + + return this; + }, + + /** + * Adds the given Game Object, or array of Game Objects, to this Container at the specified position. + * + * Existing Game Objects in the Container are shifted up. + * + * Each Game Object must be unique within the Container. + * + * @method Phaser.GameObjects.Container#addAt + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. + * @param {integer} [index=0] - The position to insert the Game Object/s at. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + addAt: function (child, index) + { + ArrayUtils.AddAt(this.list, child, index, this.maxSize, this.addHandler, this); + + return this; + }, + + /** + * Returns the Game Object at the given position in this Container. + * + * @method Phaser.GameObjects.Container#getAt + * @since 3.4.0 + * + * @param {integer} index - The position to get the Game Object from. + * + * @return {?Phaser.GameObjects.GameObject} The Game Object at the specified index, or `null` if none found. + */ + getAt: function (index) + { + return this.list[index]; + }, + + /** + * Returns the index of the given Game Object in this Container. + * + * @method Phaser.GameObjects.Container#getIndex + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to search for in this Container. + * + * @return {integer} The index of the Game Object in this Container, or -1 if not found. + */ + getIndex: function (child) + { + return this.list.indexOf(child); + }, + + /** + * 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 boolean. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + sort: function (property, handler) + { + if (!property) + { + return this; + } + + if (handler === undefined) + { + handler = function (childA, childB) + { + return childA[property] - childB[property]; + }; + } + + ArrayUtils.StableSort.inplace(this.list, handler); + + return this; + }, + + /** + * Searches for the first instance of a child with its `name` property matching the given argument. + * Should more than one child have the same name only the first is returned. + * + * @method Phaser.GameObjects.Container#getByName + * @since 3.4.0 + * + * @param {string} name - The name to search for. + * + * @return {?Phaser.GameObjects.GameObject} The first child with a matching name, or `null` if none were found. + */ + getByName: function (name) + { + return ArrayUtils.GetFirst(this.list, 'name', name); + }, + + /** + * Returns a random Game Object from this Container. + * + * @method Phaser.GameObjects.Container#getRandom + * @since 3.4.0 + * + * @param {integer} [startIndex=0] - An optional start index. + * @param {integer} [length] - An optional length, the total number of elements (from the startIndex) to choose from. + * + * @return {?Phaser.GameObjects.GameObject} A random child from the Container, or `null` if the Container is empty. + */ + getRandom: function (startIndex, length) + { + return ArrayUtils.GetRandom(this.list, startIndex, length); + }, + + /** + * Gets the first Game Object in this Container. + * + * You can also specify a property and value to search for, in which case it will return the first + * Game Object in this Container with a matching property and / or value. + * + * For example: `getFirst('visible', true)` would return the first Game Object that had its `visible` property set. + * + * You can limit the search to the `startIndex` - `endIndex` range. + * + * @method Phaser.GameObjects.Container#getFirst + * @since 3.4.0 + * + * @param {string} property - The property to test on each Game Object in the Container. + * @param {*} value - The value to test the property against. Must pass a strict (`===`) comparison check. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {?Phaser.GameObjects.GameObject} The first matching Game Object, or `null` if none was found. + */ + getFirst: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetFirst(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns all Game Objects in this Container. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('body')` would return only Game Objects that have a body property. + * + * You can also specify a value to compare the property to: + * + * `getAll('visible', true)` would return only Game Objects that have their visible property set to `true`. + * + * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 Game Objects. + * + * @method Phaser.GameObjects.Container#getAll + * @since 3.4.0 + * + * @param {string} [property] - The property to test on each Game Object in the Container. + * @param {any} [value] - If property is set then the `property` must strictly equal this value to be included in the results. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {Phaser.GameObjects.GameObject[]} An array of matching Game Objects from this Container. + */ + getAll: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns the total number of Game Objects in this Container that have a property + * matching the given value. + * + * For example: `count('visible', true)` would count all the elements that have their visible property set. + * + * You can optionally limit the operation to the `startIndex` - `endIndex` range. + * + * @method Phaser.GameObjects.Container#count + * @since 3.4.0 + * + * @param {string} property - The property to check. + * @param {any} value - The value to check. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {integer} The total number of Game Objects in this Container with a property matching the given value. + */ + count: function (property, value, startIndex, endIndex) + { + return ArrayUtils.CountAllMatching(this.list, property, value, startIndex, endIndex); + }, + + /** + * Swaps the position of two Game Objects in this Container. + * Both Game Objects must belong to this Container. + * + * @method Phaser.GameObjects.Container#swap + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child1 - The first Game Object to swap. + * @param {Phaser.GameObjects.GameObject} child2 - The second Game Object to swap. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + swap: function (child1, child2) + { + ArrayUtils.Swap(this.list, child1, child2); + + return this; + }, + + /** + * Moves a Game Object to a new position within this Container. + * + * The Game Object must already be a child of this Container. + * + * The Game Object is removed from its old position and inserted into the new one. + * Therefore the Container size does not change. Other children will change position accordingly. + * + * @method Phaser.GameObjects.Container#moveTo + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to move. + * @param {integer} index - The new position of the Game Object in this Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + moveTo: function (child, index) + { + ArrayUtils.MoveTo(this.list, child, index); + + return this; + }, + + /** + * Removes the given Game Object, or array of Game Objects, from this Container. + * + * The Game Objects must already be children of this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * + * @method Phaser.GameObjects.Container#remove + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to be removed from the Container. + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each child successfully removed from this Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + remove: function (child, destroyChild) + { + var removed = ArrayUtils.Remove(this.list, child, this.removeHandler, this); + + if (destroyChild && removed) + { + if (!Array.isArray(removed)) + { + removed = [ removed ]; + } + + for (var i = 0; i < removed.length; i++) + { + removed[i].destroy(); + } + } + + return this; + }, + + /** + * Removes the Game Object at the given position in this Container. + * + * You can also optionally call `destroy` on the Game Object, if one is found. + * + * @method Phaser.GameObjects.Container#removeAt + * @since 3.4.0 + * + * @param {integer} index - The index of the Game Object to be removed. + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + removeAt: function (index, destroyChild) + { + var removed = ArrayUtils.RemoveAt(this.list, index, this.removeHandler, this); + + if (destroyChild && removed) + { + removed.destroy(); + } + + return this; + }, + + /** + * Removes the Game Objects between the given positions in this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * + * @method Phaser.GameObjects.Container#removeBetween + * @since 3.4.0 + * + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + removeBetween: function (startIndex, endIndex, destroyChild) + { + var removed = ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeHandler, this); + + if (destroyChild) + { + for (var i = 0; i < removed.length; i++) + { + removed[i].destroy(); + } + } + + return this; + }, + + /** + * Removes all Game Objects from this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * + * @method Phaser.GameObjects.Container#removeAll + * @since 3.4.0 + * + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + removeAll: function (destroyChild) + { + var removed = ArrayUtils.RemoveBetween(this.list, 0, this.list.length, this.removeHandler, this); + + if (destroyChild) + { + for (var i = 0; i < removed.length; i++) + { + removed[i].destroy(); + } + } + + return this; + }, + + /** + * Brings the given Game Object to the top of this Container. + * This will cause it to render on-top of any other objects in the Container. + * + * @method Phaser.GameObjects.Container#bringToTop + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to bring to the top of the Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + bringToTop: function (child) + { + ArrayUtils.BringToTop(this.list, child); + + return this; + }, + + /** + * Sends the given Game Object to the bottom of this Container. + * This will cause it to render below any other objects in the Container. + * + * @method Phaser.GameObjects.Container#sendToBack + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to send to the bottom of the Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + sendToBack: function (child) + { + ArrayUtils.SendToBack(this.list, child); + + return this; + }, + + /** + * Moves the given Game Object up one place in this Container, unless it's already at the top. + * + * @method Phaser.GameObjects.Container#moveUp + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + moveUp: function (child) + { + ArrayUtils.MoveUp(this.list, child); + + return this; + }, + + /** + * Moves the given Game Object down one place in this Container, unless it's already at the bottom. + * + * @method Phaser.GameObjects.Container#moveDown + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + moveDown: function (child) + { + ArrayUtils.MoveDown(this.list, child); + + return this; + }, + + /** + * Reverses the order of all Game Objects in this Container. + * + * @method Phaser.GameObjects.Container#reverse + * @since 3.4.0 + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + reverse: function () + { + this.list.reverse(); + + return this; + }, + + /** + * Shuffles the all Game Objects in this Container using the Fisher-Yates implementation. + * + * @method Phaser.GameObjects.Container#shuffle + * @since 3.4.0 + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + shuffle: function () + { + ArrayUtils.Shuffle(this.list); + + return this; + }, + + /** + * Replaces a Game Object in this Container with the new Game Object. + * The new Game Object cannot already be a child of this Container. + * + * @method Phaser.GameObjects.Container#replace + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} oldChild - The Game Object in this Container that will be replaced. + * @param {Phaser.GameObjects.GameObject} newChild - The Game Object to be added to this Container. + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + replace: function (oldChild, newChild, destroyChild) + { + var moved = ArrayUtils.Replace(this.list, oldChild, newChild); + + if (moved) + { + this.addHandler(newChild); + this.removeHandler(oldChild); + + if (destroyChild) + { + oldChild.destroy(); + } + } + + return this; + }, + + /** + * Returns `true` if the given Game Object is a direct child of this Container. + * + * This check does not scan nested Containers. + * + * @method Phaser.GameObjects.Container#exists + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to check for within this Container. + * + * @return {boolean} True if the Game Object is an immediate child of this Container, otherwise false. + */ + exists: function (child) + { + return (this.list.indexOf(child) > -1); + }, + + /** + * Sets the property to the given value on all Game Objects in this Container. + * + * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 Game Objects. + * + * @method Phaser.GameObjects.Container#setAll + * @since 3.4.0 + * + * @param {string} property - The property that must exist on the Game Object. + * @param {any} value - The value to get the property to. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + setAll: function (property, value, startIndex, endIndex) + { + ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); + + return this; + }, + + /** + * @callback EachContainerCallback + * @generic I - [item] + * + * @param {*} item - The child Game Object of the Container. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + + /** + * Passes all Game Objects in this Container to the given callback. + * + * A copy of the Container is made before passing each entry to your callback. + * This protects against the callback itself modifying the Container. + * + * If you know for sure that the callback will not change the size of this Container + * then you can use the more performant `Container.iterate` method instead. + * + * @method Phaser.GameObjects.Container#each + * @since 3.4.0 + * + * @param {function} callback - The function to call. + * @param {object} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + each: function (callback, context) + { + var args = [ null ]; + var i; + var temp = this.list.slice(); + var len = temp.length; + + for (i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < len; i++) + { + args[0] = temp[i]; + + callback.apply(context, args); + } + + return this; + }, + + /** + * Passes all Game Objects in this Container to the given callback. + * + * Only use this method when you absolutely know that the Container will not be modified during + * the iteration, i.e. by removing or adding to its contents. + * + * @method Phaser.GameObjects.Container#iterate + * @since 3.4.0 + * + * @param {function} callback - The function to call. + * @param {object} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {Phaser.GameObjects.Container} This Container instance. + */ + iterate: function (callback, context) + { + var args = [ null ]; + var i; + + for (i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < this.list.length; i++) + { + args[0] = this.list[i]; + + callback.apply(context, args); + } + + return this; + }, + + /** + * 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.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. + * @param {boolean} [updateChildren=false] - Apply this scrollFactor to all Container children as well? + * + * @return {this} This Game Object instance. + */ + setScrollFactor: function (x, y, updateChildren) + { + if (y === undefined) { y = x; } + if (updateChildren === undefined) { updateChildren = false; } + + this.scrollFactorX = x; + this.scrollFactorY = y; + + if (updateChildren) + { + ArrayUtils.SetAll(this.list, 'scrollFactorX', x); + ArrayUtils.SetAll(this.list, 'scrollFactorY', y); + } + + return this; + }, + + /** + * The number of Game Objects inside this Container. + * + * @name Phaser.GameObjects.Container#length + * @type {integer} + * @readonly + * @since 3.4.0 + */ + length: { + + get: function () + { + return this.list.length; + } + + }, + + /** + * Returns the first Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#first + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + first: { + + get: function () + { + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + } + + }, + + /** + * Returns the last Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#last + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + last: { + + get: function () + { + if (this.list.length > 0) + { + this.position = this.list.length - 1; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * Returns the next Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#next + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + next: { + + get: function () + { + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * Returns the previous Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#previous + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + previous: { + + get: function () + { + if (this.position > 0) + { + this.position--; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Container#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + this.removeAll(!!this.exclusive); + + this.localTransform.destroy(); + this.tempTransformMatrix.destroy(); + + this.list = []; + this._displayList = null; + } + +}); + +module.exports = Container; + + +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = __webpack_require__(138); +var Class = __webpack_require__(0); +var Render = __webpack_require__(989); + +/** + * @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. + * + * 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): 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 + * + * @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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. + */ +var DynamicBitmapText = new Class({ + + Extends: BitmapText, + + Mixins: [ + Render + ], + + initialize: + + function DynamicBitmapText (scene, x, y, font, text, size, align) + { + BitmapText.call(this, scene, x, y, font, text, size, align); + + this.type = 'DynamicBitmapText'; + + /** + * The horizontal scroll position of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#scrollX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.scrollX = 0; + + /** + * The vertical scroll position of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#scrollY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.scrollY = 0; + + /** + * The crop width of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#cropWidth + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.cropWidth = 0; + + /** + * The crop height of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#cropHeight + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.cropHeight = 0; + + /** + * A callback that alters how each character of the Bitmap Text is rendered. + * + * @name Phaser.GameObjects.DynamicBitmapText#displayCallback + * @type {Phaser.Types.GameObjects.BitmapText.DisplayCallback} + * @since 3.0.0 + */ + this.displayCallback; + + /** + * The data object that is populated during rendering, then passed to the displayCallback. + * You should modify this object then return it back from the callback. It's updated values + * will be used to render the specific glyph. + * + * Please note that if you need a reference to this object locally in your game code then you + * should shallow copy it, as it's updated and re-used for every glyph in the text. + * + * @name Phaser.GameObjects.DynamicBitmapText#callbackData + * @type {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} + * @since 3.11.0 + */ + this.callbackData = { + parent: this, + color: 0, + tint: { + topLeft: 0, + topRight: 0, + bottomLeft: 0, + bottomRight: 0 + }, + index: 0, + charCode: 0, + x: 0, + y: 0, + scale: 0, + rotation: 0, + data: 0 + }; + }, + + /** + * Set the crop size of this Bitmap Text. + * + * @method Phaser.GameObjects.DynamicBitmapText#setSize + * @since 3.0.0 + * + * @param {number} width - The width of the crop. + * @param {number} height - The height of the crop. + * + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. + */ + setSize: function (width, height) + { + this.cropWidth = width; + this.cropHeight = height; + + return this; + }, + + /** + * Set a callback that alters how each character of the Bitmap Text is rendered. + * + * The callback receives a {@link Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} object that contains information about the character that's + * about to be rendered. + * + * It should return an object with `x`, `y`, `scale` and `rotation` properties that will be used instead of the + * usual values when rendering. + * + * @method Phaser.GameObjects.DynamicBitmapText#setDisplayCallback + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallback} callback - The display callback to set. + * + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. + */ + setDisplayCallback: function (callback) + { + this.displayCallback = callback; + + return this; + }, + + /** + * Set the horizontal scroll position of this Bitmap Text. + * + * @method Phaser.GameObjects.DynamicBitmapText#setScrollX + * @since 3.0.0 + * + * @param {number} value - The horizontal scroll position to set. + * + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. + */ + setScrollX: function (value) + { + this.scrollX = value; + + return this; + }, + + /** + * Set the vertical scroll position of this Bitmap Text. + * + * @method Phaser.GameObjects.DynamicBitmapText#setScrollY + * @since 3.0.0 + * + * @param {number} value - The vertical scroll position to set. + * + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. + */ + setScrollY: function (value) + { + this.scrollY = value; + + return this; + } + +}); + +module.exports = DynamicBitmapText; + + +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCamera = __webpack_require__(103); +var Class = __webpack_require__(0); +var Commands = __webpack_require__(205); +var ComponentsAlpha = __webpack_require__(287); +var ComponentsBlendMode = __webpack_require__(291); +var ComponentsDepth = __webpack_require__(292); +var ComponentsMask = __webpack_require__(296); +var ComponentsPipeline = __webpack_require__(121); +var ComponentsTransform = __webpack_require__(301); +var ComponentsVisible = __webpack_require__(302); +var ComponentsScrollFactor = __webpack_require__(299); + +var TransformMatrix = __webpack_require__(35); + +var Ellipse = __webpack_require__(107); +var GameObject = __webpack_require__(14); +var GetFastValue = __webpack_require__(1); +var GetValue = __webpack_require__(5); +var MATH_CONST = __webpack_require__(13); +var Render = __webpack_require__(995); + +/** + * @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. + * + * 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.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @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. + */ +var Graphics = new Class({ + + Extends: GameObject, + + Mixins: [ + ComponentsAlpha, + ComponentsBlendMode, + ComponentsDepth, + ComponentsMask, + ComponentsPipeline, + ComponentsTransform, + ComponentsVisible, + ComponentsScrollFactor, + Render + ], + + initialize: + + function Graphics (scene, options) + { + var x = GetValue(options, 'x', 0); + var y = GetValue(options, 'y', 0); + + GameObject.call(this, scene, 'Graphics'); + + this.setPosition(x, y); + this.initPipeline(); + + /** + * The horizontal display origin of the Graphics. + * + * @name Phaser.GameObjects.Graphics#displayOriginX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.displayOriginX = 0; + + /** + * The vertical display origin of the Graphics. + * + * @name Phaser.GameObjects.Graphics#displayOriginY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.displayOriginY = 0; + + /** + * The array of commands used to render the Graphics. + * + * @name Phaser.GameObjects.Graphics#commandBuffer + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.commandBuffer = []; + + /** + * The default fill color for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultFillColor + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.defaultFillColor = -1; + + /** + * The default fill alpha for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultFillAlpha + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.defaultFillAlpha = 1; + + /** + * The default stroke width for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultStrokeWidth + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.defaultStrokeWidth = 1; + + /** + * The default stroke color for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultStrokeColor + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.defaultStrokeColor = -1; + + /** + * The default stroke alpha for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultStrokeAlpha + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.defaultStrokeAlpha = 1; + + /** + * Internal property that keeps track of the line width style setting. + * + * @name Phaser.GameObjects.Graphics#_lineWidth + * @type {number} + * @private + * @since 3.0.0 + */ + this._lineWidth = 1.0; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Graphics#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Graphics#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Graphics#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + this.setDefaultStyles(options); + }, + + /** + * Set the default style settings for this Graphics object. + * + * @method Phaser.GameObjects.Graphics#setDefaultStyles + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Graphics.Styles} options - The styles to set as defaults. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + setDefaultStyles: function (options) + { + if (GetValue(options, 'lineStyle', null)) + { + this.defaultStrokeWidth = GetValue(options, 'lineStyle.width', 1); + this.defaultStrokeColor = GetValue(options, 'lineStyle.color', 0xffffff); + this.defaultStrokeAlpha = GetValue(options, 'lineStyle.alpha', 1); + + this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha); + } + + if (GetValue(options, 'fillStyle', null)) + { + this.defaultFillColor = GetValue(options, 'fillStyle.color', 0xffffff); + this.defaultFillAlpha = GetValue(options, 'fillStyle.alpha', 1); + + this.fillStyle(this.defaultFillColor, this.defaultFillAlpha); + } + + return this; + }, + + /** + * Set the current line style. + * + * @method Phaser.GameObjects.Graphics#lineStyle + * @since 3.0.0 + * + * @param {number} lineWidth - The stroke width. + * @param {number} color - The stroke color. + * @param {number} [alpha=1] - The stroke alpha. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + lineStyle: function (lineWidth, color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.LINE_STYLE, + lineWidth, color, alpha + ); + + this._lineWidth = lineWidth; + + return this; + }, + + /** + * Set the current fill style. + * + * @method Phaser.GameObjects.Graphics#fillStyle + * @since 3.0.0 + * + * @param {number} color - The fill color. + * @param {number} [alpha=1] - The fill alpha. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillStyle: function (color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.FILL_STYLE, + color, alpha + ); + + return this; + }, + + /** + * Sets a gradient fill style. This is a WebGL only feature. + * + * The gradient color values represent the 4 corners of an untransformed rectangle. + * The gradient is used to color all filled shapes and paths drawn after calling this method. + * If you wish to turn a gradient off, call `fillStyle` and provide a new single fill color. + * + * When filling a triangle only the first 3 color values provided are used for the 3 points of a triangle. + * + * This feature is best used only on rectangles and triangles. All other shapes will give strange results. + * + * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used + * will be filled with a gradient on its own. There is no ability to gradient fill a shape or path as a single + * entity at this time. + * + * @method Phaser.GameObjects.Graphics#fillGradientStyle + * @webglOnly + * @since 3.12.0 + * + * @param {integer} topLeft - The tint being applied to the top-left of the Game Object. + * @param {integer} topRight - The tint being applied to the top-right of the Game Object. + * @param {integer} bottomLeft - The tint being applied to the bottom-left of the Game Object. + * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. + * @param {number} [alpha=1] - The fill alpha. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillGradientStyle: function (topLeft, topRight, bottomLeft, bottomRight, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.GRADIENT_FILL_STYLE, + alpha, topLeft, topRight, bottomLeft, bottomRight + ); + + return this; + }, + + /** + * Sets a gradient line style. This is a WebGL only feature. + * + * The gradient color values represent the 4 corners of an untransformed rectangle. + * The gradient is used to color all stroked shapes and paths drawn after calling this method. + * If you wish to turn a gradient off, call `lineStyle` and provide a new single line color. + * + * This feature is best used only on single lines. All other shapes will give strange results. + * + * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used + * will be filled with a gradient on its own. There is no ability to gradient stroke a shape or path as a single + * entity at this time. + * + * @method Phaser.GameObjects.Graphics#lineGradientStyle + * @webglOnly + * @since 3.12.0 + * + * @param {number} lineWidth - The stroke width. + * @param {integer} topLeft - The tint being applied to the top-left of the Game Object. + * @param {integer} topRight - The tint being applied to the top-right of the Game Object. + * @param {integer} bottomLeft - The tint being applied to the bottom-left of the Game Object. + * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. + * @param {number} [alpha=1] - The fill alpha. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + lineGradientStyle: function (lineWidth, topLeft, topRight, bottomLeft, bottomRight, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.GRADIENT_LINE_STYLE, + lineWidth, alpha, topLeft, topRight, bottomLeft, bottomRight + ); + + return this; + }, + + /** + * Sets the texture frame this Graphics Object will use when drawing all shapes defined after calling this. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * Once set, all shapes will use this texture. Call this method with no arguments to clear it. + * + * The textures are not tiled. They are stretched to the dimensions of the shapes being rendered. For this reason, + * it works best with seamless / tileable textures. + * + * The mode argument controls how the textures are combined with the fill colors. The default value (0) will + * multiply the texture by the fill color. A value of 1 will use just the fill color, but the alpha data from the texture, + * and a value of 2 will use just the texture and no fill color at all. + * + * @method Phaser.GameObjects.Graphics#setTexture + * @since 3.12.0 + * @webglOnly + * + * @param {string} [key] - The key of the texture to be used, as stored in the Texture Manager. Leave blank to clear a previously set texture. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * @param {number} [mode=0] - The texture tint mode. 0 is multiply, 1 is alpha only and 2 is texture only. + * + * @return {this} This Game Object. + */ + setTexture: function (key, frame, mode) + { + if (mode === undefined) { mode = 0; } + + if (key === undefined) + { + this.commandBuffer.push( + Commands.CLEAR_TEXTURE + ); + } + else + { + var textureFrame = this.scene.sys.textures.getFrame(key, frame); + + if (textureFrame) + { + if (mode === 2) + { + mode = 3; + } + + this.commandBuffer.push( + Commands.SET_TEXTURE, + textureFrame, + mode + ); + } + } + + return this; + }, + + /** + * Start a new shape path. + * + * @method Phaser.GameObjects.Graphics#beginPath + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + beginPath: function () + { + this.commandBuffer.push( + Commands.BEGIN_PATH + ); + + return this; + }, + + /** + * Close the current path. + * + * @method Phaser.GameObjects.Graphics#closePath + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + closePath: function () + { + this.commandBuffer.push( + Commands.CLOSE_PATH + ); + + return this; + }, + + /** + * Fill the current path. + * + * @method Phaser.GameObjects.Graphics#fillPath + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillPath: function () + { + this.commandBuffer.push( + Commands.FILL_PATH + ); + + return this; + }, + + /** + * Fill the current path. + * + * This is an alias for `Graphics.fillPath` and does the same thing. + * It was added to match the CanvasRenderingContext 2D API. + * + * @method Phaser.GameObjects.Graphics#fill + * @since 3.16.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fill: function () + { + this.commandBuffer.push( + Commands.FILL_PATH + ); + + return this; + }, + + /** + * Stroke the current path. + * + * @method Phaser.GameObjects.Graphics#strokePath + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokePath: function () + { + this.commandBuffer.push( + Commands.STROKE_PATH + ); + + return this; + }, + + /** + * Stroke the current path. + * + * This is an alias for `Graphics.strokePath` and does the same thing. + * It was added to match the CanvasRenderingContext 2D API. + * + * @method Phaser.GameObjects.Graphics#stroke + * @since 3.16.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + stroke: function () + { + this.commandBuffer.push( + Commands.STROKE_PATH + ); + + return this; + }, + + /** + * Fill the given circle. + * + * @method Phaser.GameObjects.Graphics#fillCircleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to fill. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillCircleShape: function (circle) + { + return this.fillCircle(circle.x, circle.y, circle.radius); + }, + + /** + * Stroke the given circle. + * + * @method Phaser.GameObjects.Graphics#strokeCircleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to stroke. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeCircleShape: function (circle) + { + return this.strokeCircle(circle.x, circle.y, circle.radius); + }, + + /** + * Fill a circle with the given position and radius. + * + * @method Phaser.GameObjects.Graphics#fillCircle + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} radius - The radius of the circle. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillCircle: function (x, y, radius) + { + this.beginPath(); + this.arc(x, y, radius, 0, MATH_CONST.PI2); + this.fillPath(); + + return this; + }, + + /** + * Stroke a circle with the given position and radius. + * + * @method Phaser.GameObjects.Graphics#strokeCircle + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} radius - The radius of the circle. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeCircle: function (x, y, radius) + { + this.beginPath(); + this.arc(x, y, radius, 0, MATH_CONST.PI2); + this.strokePath(); + + return this; + }, + + /** + * Fill the given rectangle. + * + * @method Phaser.GameObjects.Graphics#fillRectShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to fill. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillRectShape: function (rect) + { + return this.fillRect(rect.x, rect.y, rect.width, rect.height); + }, + + /** + * Stroke the given rectangle. + * + * @method Phaser.GameObjects.Graphics#strokeRectShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to stroke. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeRectShape: function (rect) + { + return this.strokeRect(rect.x, rect.y, rect.width, rect.height); + }, + + /** + * Fill a rectangle with the given position and size. + * + * @method Phaser.GameObjects.Graphics#fillRect + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillRect: function (x, y, width, height) + { + this.commandBuffer.push( + Commands.FILL_RECT, + x, y, width, height + ); + + return this; + }, + + /** + * Stroke a rectangle with the given position and size. + * + * @method Phaser.GameObjects.Graphics#strokeRect + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeRect: function (x, y, width, height) + { + var lineWidthHalf = this._lineWidth / 2; + var minx = x - lineWidthHalf; + var maxx = x + lineWidthHalf; + + this.beginPath(); + this.moveTo(x, y); + this.lineTo(x, y + height); + this.strokePath(); + + this.beginPath(); + this.moveTo(x + width, y); + this.lineTo(x + width, y + height); + this.strokePath(); + + this.beginPath(); + this.moveTo(minx, y); + this.lineTo(maxx + width, y); + this.strokePath(); + + this.beginPath(); + this.moveTo(minx, y + height); + this.lineTo(maxx + width, y + height); + this.strokePath(); + + return this; + }, + + /** + * Fill a rounded rectangle with the given position, size and radius. + * + * @method Phaser.GameObjects.Graphics#fillRoundedRect + * @since 3.11.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillRoundedRect: function (x, y, width, height, radius) + { + if (radius === undefined) { radius = 20; } + + var tl = radius; + var tr = radius; + var bl = radius; + var br = radius; + + if (typeof radius !== 'number') + { + tl = GetFastValue(radius, 'tl', 20); + tr = GetFastValue(radius, 'tr', 20); + bl = GetFastValue(radius, 'bl', 20); + br = GetFastValue(radius, 'br', 20); + } + + this.beginPath(); + this.moveTo(x + tl, y); + this.lineTo(x + width - tr, y); + this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); + this.lineTo(x + width, y + height - br); + this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); + this.lineTo(x + bl, y + height); + this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); + this.lineTo(x, y + tl); + this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); + this.fillPath(); + + return this; + }, + + /** + * Stroke a rounded rectangle with the given position, size and radius. + * + * @method Phaser.GameObjects.Graphics#strokeRoundedRect + * @since 3.11.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeRoundedRect: function (x, y, width, height, radius) + { + if (radius === undefined) { radius = 20; } + + var tl = radius; + var tr = radius; + var bl = radius; + var br = radius; + + if (typeof radius !== 'number') + { + tl = GetFastValue(radius, 'tl', 20); + tr = GetFastValue(radius, 'tr', 20); + bl = GetFastValue(radius, 'bl', 20); + br = GetFastValue(radius, 'br', 20); + } + + this.beginPath(); + this.moveTo(x + tl, y); + this.lineTo(x + width - tr, y); + this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); + this.lineTo(x + width, y + height - br); + this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); + this.lineTo(x + bl, y + height); + this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); + this.lineTo(x, y + tl); + this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); + this.strokePath(); + + return this; + }, + + /** + * Fill the given point. + * + * Draws a square at the given position, 1 pixel in size by default. + * + * @method Phaser.GameObjects.Graphics#fillPointShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The point to fill. + * @param {number} [size=1] - The size of the square to draw. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillPointShape: function (point, size) + { + return this.fillPoint(point.x, point.y, size); + }, + + /** + * Fill a point at the given position. + * + * Draws a square at the given position, 1 pixel in size by default. + * + * @method Phaser.GameObjects.Graphics#fillPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the point. + * @param {number} y - The y coordinate of the point. + * @param {number} [size=1] - The size of the square to draw. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillPoint: function (x, y, size) + { + if (!size || size < 1) + { + size = 1; + } + else + { + x -= (size / 2); + y -= (size / 2); + } + + this.commandBuffer.push( + Commands.FILL_RECT, + x, y, size, size + ); + + return this; + }, + + /** + * Fill the given triangle. + * + * @method Phaser.GameObjects.Graphics#fillTriangleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle to fill. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillTriangleShape: function (triangle) + { + return this.fillTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3); + }, + + /** + * Stroke the given triangle. + * + * @method Phaser.GameObjects.Graphics#strokeTriangleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle to stroke. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeTriangleShape: function (triangle) + { + return this.strokeTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3); + }, + + /** + * Fill a triangle with the given points. + * + * @method Phaser.GameObjects.Graphics#fillTriangle + * @since 3.0.0 + * + * @param {number} x0 - The x coordinate of the first point. + * @param {number} y0 - The y coordinate of the first point. + * @param {number} x1 - The x coordinate of the second point. + * @param {number} y1 - The y coordinate of the second point. + * @param {number} x2 - The x coordinate of the third point. + * @param {number} y2 - The y coordinate of the third point. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillTriangle: function (x0, y0, x1, y1, x2, y2) + { + this.commandBuffer.push( + Commands.FILL_TRIANGLE, + x0, y0, x1, y1, x2, y2 + ); + + return this; + }, + + /** + * Stroke a triangle with the given points. + * + * @method Phaser.GameObjects.Graphics#strokeTriangle + * @since 3.0.0 + * + * @param {number} x0 - The x coordinate of the first point. + * @param {number} y0 - The y coordinate of the first point. + * @param {number} x1 - The x coordinate of the second point. + * @param {number} y1 - The y coordinate of the second point. + * @param {number} x2 - The x coordinate of the third point. + * @param {number} y2 - The y coordinate of the third point. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeTriangle: function (x0, y0, x1, y1, x2, y2) + { + this.commandBuffer.push( + Commands.STROKE_TRIANGLE, + x0, y0, x1, y1, x2, y2 + ); + + return this; + }, + + /** + * Draw the given line. + * + * @method Phaser.GameObjects.Graphics#strokeLineShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to stroke. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeLineShape: function (line) + { + return this.lineBetween(line.x1, line.y1, line.x2, line.y2); + }, + + /** + * Draw a line between the given points. + * + * @method Phaser.GameObjects.Graphics#lineBetween + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the start point of the line. + * @param {number} y1 - The y coordinate of the start point of the line. + * @param {number} x2 - The x coordinate of the end point of the line. + * @param {number} y2 - The y coordinate of the end point of the line. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + lineBetween: function (x1, y1, x2, y2) + { + this.beginPath(); + this.moveTo(x1, y1); + this.lineTo(x2, y2); + this.strokePath(); + + return this; + }, + + /** + * Draw a line from the current drawing position to the given position. + * + * Moves the current drawing position to the given position. + * + * @method Phaser.GameObjects.Graphics#lineTo + * @since 3.0.0 + * + * @param {number} x - The x coordinate to draw the line to. + * @param {number} y - The y coordinate to draw the line to. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + lineTo: function (x, y) + { + this.commandBuffer.push( + Commands.LINE_TO, + x, y + ); + + return this; + }, + + /** + * Move the current drawing position to the given position. + * + * @method Phaser.GameObjects.Graphics#moveTo + * @since 3.0.0 + * + * @param {number} x - The x coordinate to move to. + * @param {number} y - The y coordinate to move to. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + moveTo: function (x, y) + { + this.commandBuffer.push( + Commands.MOVE_TO, + x, y + ); + + return this; + }, + + /** + * Stroke the shape represented by the given array of points. + * + * Pass `closeShape` to automatically close the shape by joining the last to the first point. + * + * Pass `closePath` to automatically close the path before it is stroked. + * + * @method Phaser.GameObjects.Graphics#strokePoints + * @since 3.0.0 + * + * @param {(array|Phaser.Geom.Point[])} points - The points to stroke. + * @param {boolean} [closeShape=false] - When `true`, the shape is closed by joining the last point to the first point. + * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. + * @param {integer} [endIndex] - The index of `points` to stop drawing at. Defaults to `points.length`. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokePoints: function (points, closeShape, closePath, endIndex) + { + if (closeShape === undefined) { closeShape = false; } + if (closePath === undefined) { closePath = false; } + if (endIndex === undefined) { endIndex = points.length; } + + this.beginPath(); + + this.moveTo(points[0].x, points[0].y); + + for (var i = 1; i < endIndex; i++) + { + this.lineTo(points[i].x, points[i].y); + } + + if (closeShape) + { + this.lineTo(points[0].x, points[0].y); + } + + if (closePath) + { + this.closePath(); + } + + this.strokePath(); + + return this; + }, + + /** + * Fill the shape represented by the given array of points. + * + * Pass `closeShape` to automatically close the shape by joining the last to the first point. + * + * Pass `closePath` to automatically close the path before it is filled. + * + * @method Phaser.GameObjects.Graphics#fillPoints + * @since 3.0.0 + * + * @param {(array|Phaser.Geom.Point[])} points - The points to fill. + * @param {boolean} [closeShape=false] - When `true`, the shape is closed by joining the last point to the first point. + * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. + * @param {integer} [endIndex] - The index of `points` to stop at. Defaults to `points.length`. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillPoints: function (points, closeShape, closePath, endIndex) + { + if (closeShape === undefined) { closeShape = false; } + if (closePath === undefined) { closePath = false; } + if (endIndex === undefined) { endIndex = points.length; } + + this.beginPath(); + + this.moveTo(points[0].x, points[0].y); + + for (var i = 1; i < endIndex; i++) + { + this.lineTo(points[i].x, points[i].y); + } + + if (closeShape) + { + this.lineTo(points[0].x, points[0].y); + } + + if (closePath) + { + this.closePath(); + } + + this.fillPath(); + + return this; + }, + + /** + * Stroke the given ellipse. + * + * @method Phaser.GameObjects.Graphics#strokeEllipseShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to stroke. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeEllipseShape: function (ellipse, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var points = ellipse.getPoints(smoothness); + + return this.strokePoints(points, true); + }, + + /** + * Stroke an ellipse with the given position and size. + * + * @method Phaser.GameObjects.Graphics#strokeEllipse + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the ellipse. + * @param {number} y - The y coordinate of the center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + strokeEllipse: function (x, y, width, height, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var ellipse = new Ellipse(x, y, width, height); + + var points = ellipse.getPoints(smoothness); + + return this.strokePoints(points, true); + }, + + /** + * Fill the given ellipse. + * + * @method Phaser.GameObjects.Graphics#fillEllipseShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to fill. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillEllipseShape: function (ellipse, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var points = ellipse.getPoints(smoothness); + + return this.fillPoints(points, true); + }, + + /** + * Fill an ellipse with the given position and size. + * + * @method Phaser.GameObjects.Graphics#fillEllipse + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the ellipse. + * @param {number} y - The y coordinate of the center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + fillEllipse: function (x, y, width, height, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var ellipse = new Ellipse(x, y, width, height); + + var points = ellipse.getPoints(smoothness); + + return this.fillPoints(points, true); + }, + + /** + * Draw an arc. + * + * This method can be used to create circles, or parts of circles. + * + * Make sure you call `beginPath` before starting the arc unless you wish for the arc to automatically + * close when filled or stroked. + * + * Use the optional `overshoot` argument increase the number of iterations that take place when + * the arc is rendered in WebGL. This is useful if you're drawing an arc with an especially thick line, + * as it will allow the arc to fully join-up. Try small values at first, i.e. 0.01. + * + * Call {@link Phaser.GameObjects.Graphics#fillPath} or {@link Phaser.GameObjects.Graphics#strokePath} after calling + * this method to draw the arc. + * + * @method Phaser.GameObjects.Graphics#arc + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} radius - The radius of the circle. + * @param {number} startAngle - The starting angle, in radians. + * @param {number} endAngle - The ending angle, in radians. + * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. + * @param {number} [overshoot=0] - This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + arc: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) + { + if (anticlockwise === undefined) { anticlockwise = false; } + if (overshoot === undefined) { overshoot = 0; } + + this.commandBuffer.push( + Commands.ARC, + x, y, radius, startAngle, endAngle, anticlockwise, overshoot + ); + + return this; + }, + + /** + * Creates a pie-chart slice shape centered at `x`, `y` with the given radius. + * You must define the start and end angle of the slice. + * + * Setting the `anticlockwise` argument to `true` creates a shape similar to Pacman. + * Setting it to `false` creates a shape like a slice of pie. + * + * This method will begin a new path and close the path at the end of it. + * To display the actual slice you need to call either `strokePath` or `fillPath` after it. + * + * @method Phaser.GameObjects.Graphics#slice + * @since 3.4.0 + * + * @param {number} x - The horizontal center of the slice. + * @param {number} y - The vertical center of the slice. + * @param {number} radius - The radius of the slice. + * @param {number} startAngle - The start angle of the slice, given in radians. + * @param {number} endAngle - The end angle of the slice, given in radians. + * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. + * @param {number} [overshoot=0] - This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + slice: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) + { + if (anticlockwise === undefined) { anticlockwise = false; } + if (overshoot === undefined) { overshoot = 0; } + + this.commandBuffer.push(Commands.BEGIN_PATH); + + this.commandBuffer.push(Commands.MOVE_TO, x, y); + + this.commandBuffer.push(Commands.ARC, x, y, radius, startAngle, endAngle, anticlockwise, overshoot); + + this.commandBuffer.push(Commands.CLOSE_PATH); + + return this; + }, + + /** + * Saves the state of the Graphics by pushing the current state onto a stack. + * + * The most recently saved state can then be restored with {@link Phaser.GameObjects.Graphics#restore}. + * + * @method Phaser.GameObjects.Graphics#save + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + save: function () + { + this.commandBuffer.push( + Commands.SAVE + ); + + return this; + }, + + /** + * Restores the most recently saved state of the Graphics by popping from the state stack. + * + * Use {@link Phaser.GameObjects.Graphics#save} to save the current state, and call this afterwards to restore that state. + * + * If there is no saved state, this command does nothing. + * + * @method Phaser.GameObjects.Graphics#restore + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + restore: function () + { + this.commandBuffer.push( + Commands.RESTORE + ); + + return this; + }, + + /** + * Inserts a translation command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be translated + * by the given amount. + * + * This does not change the position of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * + * @method Phaser.GameObjects.Graphics#translateCanvas + * @since 3.0.0 + * + * @param {number} x - The horizontal translation to apply. + * @param {number} y - The vertical translation to apply. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + translateCanvas: function (x, y) + { + this.commandBuffer.push( + Commands.TRANSLATE, + x, y + ); + + return this; + }, + + /** + * Inserts a scale command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be scaled + * by the given amount. + * + * This does not change the scale of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * + * @method Phaser.GameObjects.Graphics#scaleCanvas + * @since 3.0.0 + * + * @param {number} x - The horizontal scale to apply. + * @param {number} y - The vertical scale to apply. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + scaleCanvas: function (x, y) + { + this.commandBuffer.push( + Commands.SCALE, + x, y + ); + + return this; + }, + + /** + * Inserts a rotation command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be rotated + * by the given amount. + * + * This does not change the rotation of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * + * @method Phaser.GameObjects.Graphics#rotateCanvas + * @since 3.0.0 + * + * @param {number} radians - The rotation angle, in radians. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + rotateCanvas: function (radians) + { + this.commandBuffer.push( + Commands.ROTATE, + radians + ); + + return this; + }, + + /** + * Clear the command buffer and reset the fill style and line style to their defaults. + * + * @method Phaser.GameObjects.Graphics#clear + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + clear: function () + { + this.commandBuffer.length = 0; + + if (this.defaultFillColor > -1) + { + this.fillStyle(this.defaultFillColor, this.defaultFillAlpha); + } + + if (this.defaultStrokeColor > -1) + { + this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha); + } + + return this; + }, + + /** + * Generate a texture from this Graphics object. + * + * If `key` is a string it'll generate a new texture using it and add it into the + * Texture Manager (assuming no key conflict happens). + * + * If `key` is a Canvas it will draw the texture to that canvas context. Note that it will NOT + * automatically upload it to the GPU in WebGL mode. + * + * @method Phaser.GameObjects.Graphics#generateTexture + * @since 3.0.0 + * + * @param {(string|HTMLCanvasElement)} key - The key to store the texture with in the Texture Manager, or a Canvas to draw to. + * @param {integer} [width] - The width of the graphics to generate. + * @param {integer} [height] - The height of the graphics to generate. + * + * @return {Phaser.GameObjects.Graphics} This Game Object. + */ + generateTexture: function (key, width, height) + { + var sys = this.scene.sys; + var renderer = sys.game.renderer; + + if (width === undefined) { width = sys.scale.width; } + if (height === undefined) { height = sys.scale.height; } + + Graphics.TargetCamera.setScene(this.scene); + Graphics.TargetCamera.setViewport(0, 0, width, height); + Graphics.TargetCamera.scrollX = this.x; + Graphics.TargetCamera.scrollY = this.y; + + var texture; + var ctx; + + if (typeof key === 'string') + { + if (sys.textures.exists(key)) + { + // Key is a string, it DOES exist in the Texture Manager AND is a canvas, so draw to it + + texture = sys.textures.get(key); + + var src = texture.getSourceImage(); + + if (src instanceof HTMLCanvasElement) + { + ctx = src.getContext('2d'); + } + } + else + { + // Key is a string and doesn't exist in the Texture Manager, so generate and save it + + texture = sys.textures.createCanvas(key, width, height); + + ctx = texture.getSourceImage().getContext('2d'); + } + } + else if (key instanceof HTMLCanvasElement) + { + // Key is a Canvas, so draw to it + + ctx = key.getContext('2d'); + } + + if (ctx) + { + // var GraphicsCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) + this.renderCanvas(renderer, this, 0, Graphics.TargetCamera, null, ctx, false); + + if (texture) + { + texture.refresh(); + } + } + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Graphics#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + this.commandBuffer = []; + } + +}); + +/** + * A Camera used specifically by the Graphics system for rendering to textures. + * + * @name Phaser.GameObjects.Graphics.TargetCamera + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.1.0 + */ +Graphics.TargetCamera = new BaseCamera(); + +module.exports = Graphics; + + +/***/ }), +/* 205 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +module.exports = { + + ARC: 0, + BEGIN_PATH: 1, + CLOSE_PATH: 2, + FILL_RECT: 3, + LINE_TO: 4, + MOVE_TO: 5, + LINE_STYLE: 6, + FILL_STYLE: 7, + FILL_PATH: 8, + STROKE_PATH: 9, + FILL_TRIANGLE: 10, + STROKE_TRIANGLE: 11, + SAVE: 14, + RESTORE: 15, + TRANSLATE: 16, + SCALE: 17, + ROTATE: 18, + SET_TEXTURE: 19, + CLEAR_TEXTURE: 20, + GRADIENT_FILL_STYLE: 21, + GRADIENT_LINE_STYLE: 22 + +}; + + +/***/ }), +/* 206 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns a Point object 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.Geom.Point} 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.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference. + */ +var CircumferencePoint = function (ellipse, angle, out) +{ + if (out === undefined) { out = new Point(); } + + var halfWidth = ellipse.width / 2; + var halfHeight = ellipse.height / 2; + + out.x = ellipse.x + halfWidth * Math.cos(angle); + out.y = ellipse.y + halfHeight * Math.sin(angle); + + return out; +}; + +module.exports = CircumferencePoint; + + +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var GravityWell = __webpack_require__(425); +var List = __webpack_require__(135); +var ParticleEmitter = __webpack_require__(427); +var Render = __webpack_require__(1005); + +/** + * @classdesc + * A Particle Emitter Manager creates and controls {@link Phaser.GameObjects.Particles.ParticleEmitter Particle Emitters} and {@link Phaser.GameObjects.Particles.GravityWell Gravity Wells}. + * + * @class ParticleEmitterManager + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Scene} scene - The Scene to which this Emitter Manager belongs. + * @param {string} texture - The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Emitter Manager will use to render particles. + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create. + */ +var ParticleEmitterManager = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Depth, + Components.Mask, + Components.Pipeline, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + // frame is optional and can contain the emitters array or object if skipped + function ParticleEmitterManager (scene, texture, frame, emitters) + { + GameObject.call(this, scene, 'ParticleEmitterManager'); + + /** + * The blend mode applied to all emitters and particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#blendMode + * @type {integer} + * @default -1 + * @private + * @since 3.0.0 + */ + this.blendMode = -1; + + /** + * The time scale applied to all emitters and particles, affecting flow rate, lifespan, and movement. + * Values larger than 1 are faster than normal. + * This is multiplied with any timeScale set on each individual emitter. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * The texture used to render this Emitter Manager's particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#texture + * @type {Phaser.Textures.Texture} + * @default null + * @since 3.0.0 + */ + this.texture = null; + + /** + * The texture frame used to render this Emitter Manager's particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#frame + * @type {Phaser.Textures.Frame} + * @default null + * @since 3.0.0 + */ + this.frame = null; + + /** + * Names of this Emitter Manager's texture frames. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#frameNames + * @type {string[]} + * @since 3.0.0 + */ + this.frameNames = []; + + // frame is optional and can contain the emitters array or object if skipped + if (frame !== null && (typeof frame === 'object' || Array.isArray(frame))) + { + emitters = frame; + frame = null; + } + + this.setTexture(texture, frame); + + this.initPipeline(); + + /** + * A list of Emitters being managed by this Emitter Manager. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#emitters + * @type {Phaser.Structs.List.} + * @since 3.0.0 + */ + this.emitters = new List(this); + + /** + * A list of Gravity Wells being managed by this Emitter Manager. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#wells + * @type {Phaser.Structs.List.} + * @since 3.0.0 + */ + this.wells = new List(this); + + if (emitters) + { + // An array of emitter configs? + if (!Array.isArray(emitters)) + { + emitters = [ emitters ]; + } + + for (var i = 0; i < emitters.length; i++) + { + this.createEmitter(emitters[i]); + } + } + }, + + /** + * Sets the texture and frame this Emitter Manager will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setTexture + * @since 3.0.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + setTexture: function (key, frame) + { + this.texture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Emitter Manager will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + setFrame: function (frame) + { + this.frame = this.texture.get(frame); + + var frames = this.texture.getFramesFromTextureSource(this.frame.sourceIndex); + + var names = []; + + frames.forEach(function (sourceFrame) + { + names.push(sourceFrame.name); + }); + + this.frameNames = names; + + this.defaultFrame = this.frame; + + return this; + }, + + /** + * Assigns texture frames to an emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setEmitterFrames + * @since 3.0.0 + * + * @param {(Phaser.Textures.Frame|Phaser.Textures.Frame[])} frames - The texture frames. + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The particle emitter to modify. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + setEmitterFrames: function (frames, emitter) + { + if (!Array.isArray(frames)) + { + frames = [ frames ]; + } + + var out = emitter.frames; + + out.length = 0; + + for (var i = 0; i < frames.length; i++) + { + var frame = frames[i]; + + if (this.frameNames.indexOf(frame) !== -1) + { + out.push(this.texture.get(frame)); + } + } + + if (out.length > 0) + { + emitter.defaultFrame = out[0]; + } + else + { + emitter.defaultFrame = this.defaultFrame; + } + + return this; + }, + + /** + * Adds an existing Particle Emitter to this Emitter Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#addEmitter + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Particle Emitter to add to this Emitter Manager. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter that was added to this Emitter Manager. + */ + addEmitter: function (emitter) + { + return this.emitters.add(emitter); + }, + + /** + * Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#createEmitter + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Configuration settings for the Particle Emitter to create. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter that was created. + */ + createEmitter: function (config) + { + return this.addEmitter(new ParticleEmitter(this, config)); + }, + + /** + * Removes a Particle Emitter from this Emitter Manager, if the Emitter belongs to this Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#removeEmitter + * @since 3.22.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter + * + * @return {?Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter if it was removed or null if it was not. + */ + removeEmitter: function (emitter) + { + return this.emitters.remove(emitter, true); + }, + + /** + * Adds an existing Gravity Well object to this Emitter Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#addGravityWell + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.GravityWell} well - The Gravity Well to add to this Emitter Manager. + * + * @return {Phaser.GameObjects.Particles.GravityWell} The Gravity Well that was added to this Emitter Manager. + */ + addGravityWell: function (well) + { + return this.wells.add(well); + }, + + /** + * Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#createGravityWell + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.GravityWellConfig} config - Configuration settings for the Gravity Well to create. + * + * @return {Phaser.GameObjects.Particles.GravityWell} The Gravity Well that was created. + */ + createGravityWell: function (config) + { + return this.addGravityWell(new GravityWell(config)); + }, + + /** + * Emits particles from each active emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#emitParticle + * @since 3.0.0 + * + * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. + * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + emitParticle: function (count, x, y) + { + var emitters = this.emitters.list; + + for (var i = 0; i < emitters.length; i++) + { + var emitter = emitters[i]; + + if (emitter.active) + { + emitter.emitParticle(count, x, y); + } + } + + return this; + }, + + /** + * Emits particles from each active emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#emitParticleAt + * @since 3.0.0 + * + * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. + * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. + * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + emitParticleAt: function (x, y, count) + { + return this.emitParticle(count, x, y); + }, + + /** + * Pauses this Emitter Manager. + * + * This has the effect of pausing all emitters, and all particles of those emitters, currently under its control. + * + * The particles will still render, but they will not have any of their logic updated. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#pause + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + pause: function () + { + this.active = false; + + return this; + }, + + /** + * Resumes this Emitter Manager, should it have been previously paused. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#resume + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. + */ + resume: function () + { + this.active = true; + + return this; + }, + + /** + * Gets all active particle processors (gravity wells). + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#getProcessors + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.GravityWell[]} - The active gravity wells. + */ + getProcessors: function () + { + return this.wells.getAll('active', true); + }, + + /** + * Updates all active emitters. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#preUpdate + * @since 3.0.0 + * + * @param {integer} 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. + */ + preUpdate: function (time, delta) + { + // Scale the delta + delta *= this.timeScale; + + var emitters = this.emitters.list; + + for (var i = 0; i < emitters.length; i++) + { + var emitter = emitters[i]; + + if (emitter.active) + { + emitter.preUpdate(time, delta); + } + } + }, + + /** + * A NOOP method so you can pass an EmitterManager to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setAlpha + * @private + * @since 3.10.0 + */ + setAlpha: function () + { + }, + + /** + * A NOOP method so you can pass an EmitterManager to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setScrollFactor + * @private + * @since 3.10.0 + */ + setScrollFactor: function () + { + }, + + /** + * A NOOP method so you can pass an EmitterManager to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setBlendMode + * @private + * @since 3.15.0 + */ + setBlendMode: function () + { + } + +}); + +module.exports = ParticleEmitterManager; + + +/***/ }), +/* 208 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = __webpack_require__(43); +var Camera = __webpack_require__(103); +var CanvasPool = __webpack_require__(28); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var CONST = __webpack_require__(32); +var Frame = __webpack_require__(106); +var GameObject = __webpack_require__(14); +var Render = __webpack_require__(1009); +var Utils = __webpack_require__(10); +var UUID = __webpack_require__(209); + +/** + * @classdesc + * A Render Texture. + * + * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and + * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic + * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. + * + * Note that under WebGL a FrameBuffer, which is what the Render Texture uses internally, cannot be anti-aliased. This means + * that when drawing objects such as Shapes to a Render Texture they will appear to be drawn with no aliasing, however this + * is a technical limitation of WebGL. To get around it, create your shape as a texture in an art package, then draw that + * to the Render Texture. + * + * @class RenderTexture + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.2.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.Pipeline + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {integer} [width=32] - The width of the Render Texture. + * @param {integer} [height=32] - The height of the Render Texture. + * @property {string} [key] - The texture key to make the RenderTexture from. + * @property {string} [frame] - the frame to make the RenderTexture from. + */ +var RenderTexture = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Crop, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Tint, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + function RenderTexture (scene, x, y, width, height, key, frame) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 32; } + if (height === undefined) { height = 32; } + + GameObject.call(this, scene, 'RenderTexture'); + + /** + * A reference to either the Canvas or WebGL Renderer that the Game instance is using. + * + * @name Phaser.GameObjects.RenderTexture#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.2.0 + */ + this.renderer = scene.sys.game.renderer; + + /** + * A reference to the Texture Manager. + * + * @name Phaser.GameObjects.RenderTexture#textureManager + * @type {Phaser.Textures.TextureManager} + * @since 3.12.0 + */ + this.textureManager = scene.sys.textures; + + /** + * The tint of the Render Texture when rendered. + * + * @name Phaser.GameObjects.RenderTexture#globalTint + * @type {number} + * @default 0xffffff + * @since 3.2.0 + */ + this.globalTint = 0xffffff; + + /** + * The alpha of the Render Texture when rendered. + * + * @name Phaser.GameObjects.RenderTexture#globalAlpha + * @type {number} + * @default 1 + * @since 3.2.0 + */ + this.globalAlpha = 1; + + /** + * The HTML Canvas Element that the Render Texture is drawing to when using the Canvas Renderer. + * + * @name Phaser.GameObjects.RenderTexture#canvas + * @type {HTMLCanvasElement} + * @since 3.2.0 + */ + this.canvas = null; + + /** + * A reference to the GL Frame Buffer this Render Texture is drawing to. + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.GameObjects.RenderTexture#framebuffer + * @type {?WebGLFramebuffer} + * @since 3.2.0 + */ + this.framebuffer = null; + + /** + * Is this Render Texture dirty or not? If not it won't spend time clearing or filling itself. + * + * @name Phaser.GameObjects.RenderTexture#dirty + * @type {boolean} + * @since 3.12.0 + */ + this.dirty = false; + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.RenderTexture#_crop + * @type {object} + * @private + * @since 3.12.0 + */ + this._crop = this.resetCropObject(); + + /** + * The Texture corresponding to this Render Texture. + * + * @name Phaser.GameObjects.RenderTexture#texture + * @type {Phaser.Textures.Texture} + * @since 3.12.0 + */ + this.texture = null; + + /** + * The Frame corresponding to this Render Texture. + * + * @name Phaser.GameObjects.RenderTexture#frame + * @type {Phaser.Textures.Frame} + * @since 3.12.0 + */ + this.frame = null; + + /** + * Internal saved texture flag. + * + * @name Phaser.GameObjects.RenderTexture#_saved + * @type {boolean} + * @private + * @since 3.12.0 + */ + this._saved = false; + + if (key === undefined) + { + this.canvas = CanvasPool.create2D(this, width, height); + + // Create a new Texture for this Text object + this.texture = scene.sys.textures.addCanvas(UUID(), this.canvas); + + // Get the frame + this.frame = this.texture.get(); + } + else + { + this.texture = scene.sys.textures.get(key); + + // Get the frame + this.frame = this.texture.get(frame); + + this.canvas = this.frame.source.image; + this._saved = true; + + this.dirty = true; + + this.width = this.frame.cutWidth; + this.height = this.frame.cutHeight; + } + + /** + * A reference to the Rendering Context belonging to the Canvas Element this Render Texture is drawing to. + * + * @name Phaser.GameObjects.RenderTexture#context + * @type {CanvasRenderingContext2D} + * @since 3.2.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * Internal erase mode flag. + * + * @name Phaser.GameObjects.RenderTexture#_eraseMode + * @type {boolean} + * @private + * @since 3.16.0 + */ + this._eraseMode = false; + + /** + * An internal Camera that can be used to move around the Render Texture. + * Control it just like you would any Scene Camera. The difference is that it only impacts the placement of what + * is drawn to the Render Texture. You can scroll, zoom and rotate this Camera. + * + * @name Phaser.GameObjects.RenderTexture#camera + * @type {Phaser.Cameras.Scene2D.BaseCamera} + * @since 3.12.0 + */ + this.camera = new Camera(0, 0, width, height); + + /** + * A reference to the WebGL Rendering Context. + * + * @name Phaser.GameObjects.RenderTexture#gl + * @type {WebGLRenderingContext} + * @default null + * @since 3.0.0 + */ + this.gl = null; + + /** + * A reference to the WebGLTexture that is being rendered to in a WebGL Context. + * + * @name Phaser.GameObjects.RenderTexture#glTexture + * @type {WebGLTexture} + * @default null + * @readonly + * @since 3.19.0 + */ + this.glTexture = null; + + var renderer = this.renderer; + + if (renderer.type === CONST.WEBGL) + { + var gl = renderer.gl; + + this.gl = gl; + this.glTexture = this.frame.source.glTexture; + this.drawGameObject = this.batchGameObjectWebGL; + this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false); + } + else if (renderer.type === CONST.CANVAS) + { + this.drawGameObject = this.batchGameObjectCanvas; + } + + this.camera.setScene(scene); + + this.setPosition(x, y); + + if (key === undefined) + { + this.setSize(width, height); + } + + this.setOrigin(0, 0); + this.initPipeline(); + }, + + /** + * Sets the size of this Game Object. + * + * @method Phaser.GameObjects.RenderTexture#setSize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + return this.resize(width, height); + }, + + /** + * Resizes the Render Texture to the new dimensions given. + * + * If Render Texture was created from specific frame, only the size of the frame will be changed. The size of the source + * texture will not change. + * + * If Render Texture was not created from specific frame, the following will happen: + * In WebGL it will destroy and then re-create the frame buffer being used by the Render Texture. + * In Canvas it will resize the underlying canvas element. + * Both approaches will erase everything currently drawn to the Render Texture. + * + * If the dimensions given are the same as those already being used, calling this method will do nothing. + * + * @method Phaser.GameObjects.RenderTexture#resize + * @since 3.10.0 + * + * @param {number} width - The new width of the Render Texture. + * @param {number} [height=width] - The new height of the Render Texture. If not specified, will be set the same as the `width`. + * + * @return {this} This Render Texture. + */ + resize: function (width, height) + { + if (height === undefined) { height = width; } + + if (width !== this.width || height !== this.height) + { + if (this.frame.name === '__BASE') + { + // Resize the texture + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.width = width; + this.texture.height = height; + + if (this.gl) + { + var gl = this.gl; + + this.renderer.deleteTexture(this.frame.source.glTexture); + this.renderer.deleteFramebuffer(this.framebuffer); + + var glTexture = this.renderer.createTexture2D(0, gl.NEAREST, gl.NEAREST, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, gl.RGBA, null, width, height, false); + + this.framebuffer = this.renderer.createFramebuffer(width, height, glTexture, false); + + this.frame.source.isRenderTexture = true; + + this.frame.glTexture = glTexture; + this.glTexture = glTexture; + } + + this.frame.source.width = width; + this.frame.source.height = height; + + this.camera.setSize(width, height); + + this.frame.setSize(width, height); + + this.width = width; + this.height = height; + } + } + else + { + // Resize the frame + + var baseFrame = this.texture.getSourceImage(); + + if (this.frame.cutX + width > baseFrame.width) + { + width = baseFrame.width - this.frame.cutX; + } + + if (this.frame.cutY + height > baseFrame.height) + { + height = baseFrame.height - this.frame.cutY; + } + + this.frame.setSize(width, height, this.frame.cutX, this.frame.cutY); + } + + this.updateDisplayOrigin(); + + var input = this.input; + + if (input && !input.customHitArea) + { + input.hitArea.width = width; + input.hitArea.height = height; + } + + return this; + }, + + /** + * Set the tint to use when rendering this Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#setGlobalTint + * @since 3.2.0 + * + * @param {integer} tint - The tint value. + * + * @return {this} This Render Texture. + */ + setGlobalTint: function (tint) + { + this.globalTint = tint; + + return this; + }, + + /** + * Set the alpha to use when rendering this Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#setGlobalAlpha + * @since 3.2.0 + * + * @param {number} alpha - The alpha value. + * + * @return {this} This Render Texture. + */ + setGlobalAlpha: function (alpha) + { + this.globalAlpha = alpha; + + return this; + }, + + /** + * Stores a copy of this Render Texture in the Texture Manager using the given key. + * + * After doing this, any texture based Game Object, such as a Sprite, can use the contents of this + * Render Texture by using the texture key: + * + * ```javascript + * var rt = this.add.renderTexture(0, 0, 128, 128); + * + * // Draw something to the Render Texture + * + * rt.saveTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Updating the contents of this Render Texture will automatically update _any_ Game Object + * that is using it as a texture. Calling `saveTexture` again will not save another copy + * of the same texture, it will just rename the key of the existing copy. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame from a Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#saveTexture + * @since 3.12.0 + * + * @param {string} key - The unique key to store the texture as within the global Texture Manager. + * + * @return {Phaser.Textures.Texture} The Texture that was saved. + */ + saveTexture: function (key) + { + this.textureManager.renameTexture(this.texture.key, key); + + this._saved = true; + + return this.texture; + }, + + /** + * Fills the Render Texture with the given color. + * + * @method Phaser.GameObjects.RenderTexture#fill + * @since 3.2.0 + * + * @param {number} rgb - The color to fill the Render Texture with. + * @param {number} [alpha=1] - The alpha value used by the fill. + * @param {number} [x=0] - The left coordinate of the fill rectangle. + * @param {number} [y=0] - The top coordinate of the fill rectangle. + * @param {number} [width=this.frame.cutWidth] - The width of the fill rectangle. + * @param {number} [height=this.frame.cutHeight] - The height of the fill rectangle. + * + * @return {this} This Render Texture instance. + */ + fill: function (rgb, alpha, x, y, width, height) + { + if (alpha === undefined) { alpha = 1; } + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.frame.cutWidth; } + if (height === undefined) { height = this.frame.cutHeight; } + + var r = ((rgb >> 16) | 0) & 0xff; + var g = ((rgb >> 8) | 0) & 0xff; + var b = (rgb | 0) & 0xff; + + var gl = this.gl; + var frame = this.frame; + + this.camera.preRender(1, 1); + + if (gl) + { + var cx = this.camera._cx; + var cy = this.camera._cy; + var cw = this.camera._cw; + var ch = this.camera._ch; + + this.renderer.setFramebuffer(this.framebuffer, false); + + this.renderer.pushScissor(cx, cy, cw, ch, ch); + + var pipeline = this.pipeline; + + pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); + + pipeline.drawFillRect( + x, y, width, height, + Utils.getTintFromFloats(r / 255, g / 255, b / 255, 1), + alpha + ); + + this.renderer.setFramebuffer(null, false); + + this.renderer.popScissor(); + + pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); + } + else + { + this.renderer.setContext(this.context); + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'; + this.context.fillRect(x + frame.cutX, y + frame.cutY, width, height); + + this.renderer.setContext(); + } + + this.dirty = true; + + return this; + }, + + /** + * Clears the Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#clear + * @since 3.2.0 + * + * @return {this} This Render Texture instance. + */ + clear: function () + { + if (this.dirty) + { + var gl = this.gl; + + if (gl) + { + var renderer = this.renderer; + + renderer.setFramebuffer(this.framebuffer, true); + + if (this.frame.cutWidth !== this.canvas.width || this.frame.cutHeight !== this.canvas.height) + { + gl.scissor(this.frame.cutX, this.frame.cutY, this.frame.cutWidth, this.frame.cutHeight); + } + + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + + renderer.setFramebuffer(null, true); + } + else + { + var ctx = this.context; + + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(this.frame.cutX, this.frame.cutY, this.frame.cutWidth, this.frame.cutHeight); + ctx.restore(); + } + + this.dirty = false; + } + + return this; + }, + + /** + * Draws the given object, or an array of objects, to this Render Texture using a blend mode of ERASE. + * This has the effect of erasing any filled pixels in the objects from this Render Texture. + * + * It can accept any of the following: + * + * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. + * * Another Render Texture. + * * A Texture Frame instance. + * * A string. This is used to look-up a texture from the Texture Manager. + * + * Note: You cannot erase a Render Texture from itself. + * + * 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. + * + * 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. + * + * Calling this method causes the WebGL batch to flush, so it can write the texture + * data to the framebuffer being used internally. The batch is flushed at the end, + * after the entries have been iterated. So if you've a bunch of objects to draw, + * try and pass them in an array in one single call, rather than making lots of + * separate calls. + * + * @method Phaser.GameObjects.RenderTexture#erase + * @since 3.16.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] - The x position to draw the Frame at, or the offset applied to the object. + * @param {number} [y] - The y position to draw the Frame at, or the offset applied to the object. + * + * @return {this} This Render Texture instance. + */ + erase: function (entries, x, y) + { + this._eraseMode = true; + + var blendMode = this.renderer.currentBlendMode; + + this.renderer.setBlendMode(BlendModes.ERASE); + + this.draw(entries, x, y, 1, 16777215); + + this.renderer.setBlendMode(blendMode); + + this._eraseMode = false; + + return this; + }, + + /** + * Draws the given object, or an array of objects, to this Render Texture. + * + * It can accept any of the following: + * + * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. + * * Another Render Texture. + * * A Texture Frame instance. + * * A string. This is used to look-up a texture from the Texture Manager. + * + * Note: You cannot draw a Render Texture to itself. + * + * 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. + * + * The `alpha` and `tint` values are only used by Texture Frames. + * Game Objects use their own alpha and tint values when being drawn. + * + * Calling this method causes the WebGL batch to flush, so it can write the texture + * data to the framebuffer being used internally. The batch is flushed at the end, + * after the entries have been iterated. So if you've a bunch of objects to draw, + * try and pass them in an array in one single call, rather than making lots of + * separate calls. + * + * @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] - The x position to draw the Frame at, or the offset applied to the object. + * @param {number} [y] - The y position to draw the Frame at, or the offset applied to the object. + * @param {number} [alpha] - The alpha value. Only used for Texture Frames and if not specified defaults to the `globalAlpha` property. Game Objects use their own current alpha value. + * @param {number} [tint] - WebGL only. The tint color value. Only used for Texture Frames and if not specified defaults to the `globalTint` property. Game Objects use their own current tint value. + * + * @return {this} This Render Texture instance. + */ + draw: function (entries, x, y, alpha, tint) + { + if (alpha === undefined) { alpha = this.globalAlpha; } + + if (tint === undefined) + { + tint = (this.globalTint >> 16) + (this.globalTint & 0xff00) + ((this.globalTint & 0xff) << 16); + } + else + { + tint = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16); + } + + if (!Array.isArray(entries)) + { + entries = [ entries ]; + } + + var gl = this.gl; + + this.camera.preRender(1, 1); + + if (gl) + { + var cx = this.camera._cx; + var cy = this.camera._cy; + var cw = this.camera._cw; + var ch = this.camera._ch; + + this.renderer.setFramebuffer(this.framebuffer, false); + + this.renderer.pushScissor(cx, cy, cw, ch, ch); + + var pipeline = this.pipeline; + + pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); + + this.batchList(entries, x, y, alpha, tint); + + pipeline.flush(); + + this.renderer.setFramebuffer(null, false); + + this.renderer.popScissor(); + + pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); + } + else + { + this.renderer.setContext(this.context); + + this.batchList(entries, x, y, alpha, tint); + + this.renderer.setContext(); + } + + this.dirty = true; + + return this; + }, + + /** + * Draws the Texture Frame to the Render Texture at the given position. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * ```javascript + * var rt = this.add.renderTexture(0, 0, 800, 600); + * rt.drawFrame(key, frame); + * ``` + * + * You can optionally provide a position, alpha and tint value to apply to the frame + * before it is drawn. + * + * Calling this method will cause a batch flush, so if you've got a stack of things to draw + * in a tight loop, try using the `draw` method instead. + * + * If you need to draw a Sprite to this Render Texture, use the `draw` method instead. + * + * @method Phaser.GameObjects.RenderTexture#drawFrame + * @since 3.12.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * @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 {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. + * @param {number} [tint] - WebGL only. The tint color to use. If not specified it uses the `globalTint` property. + * + * @return {this} This Render Texture instance. + */ + drawFrame: function (key, frame, x, y, alpha, tint) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (alpha === undefined) { alpha = this.globalAlpha; } + + if (tint === undefined) + { + tint = (this.globalTint >> 16) + (this.globalTint & 0xff00) + ((this.globalTint & 0xff) << 16); + } + else + { + tint = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16); + } + + var gl = this.gl; + var textureFrame = this.textureManager.getFrame(key, frame); + + if (textureFrame) + { + this.camera.preRender(1, 1); + + if (gl) + { + var cx = this.camera._cx; + var cy = this.camera._cy; + var cw = this.camera._cw; + var ch = this.camera._ch; + + this.renderer.setFramebuffer(this.framebuffer, false); + + this.renderer.pushScissor(cx, cy, cw, ch, ch); + + var pipeline = this.pipeline; + + pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); + + pipeline.batchTextureFrame(textureFrame, x + this.frame.cutX, y + this.frame.cutY, tint, alpha, this.camera.matrix, null); + + pipeline.flush(); + + this.renderer.setFramebuffer(null, false); + + this.renderer.popScissor(); + + pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); + } + else + { + this.batchTextureFrame(textureFrame, x + this.frame.cutX, y + this.frame.cutY, alpha, tint); + } + + this.dirty = true; + } + + return this; + }, + + /** + * Internal method that handles the drawing of an array of children. + * + * @method Phaser.GameObjects.RenderTexture#batchList + * @private + * @since 3.12.0 + * + * @param {array} children - The array of Game Objects to draw. + * @param {number} [x] - The x position to offset the Game Object by. + * @param {number} [y] - The y position to offset the Game Object by. + * @param {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. + * @param {number} [tint] - The tint color to use. If not specified it uses the `globalTint` property. + */ + batchList: function (children, x, y, alpha, tint) + { + for (var i = 0; i < children.length; i++) + { + var entry = children[i]; + + if (!entry || entry === this) + { + continue; + } + + if (entry.renderWebGL || entry.renderCanvas) + { + // Game Objects + this.drawGameObject(entry, x, y); + } + else if (entry.isParent || entry.list) + { + // Groups / Display Lists + this.batchGroup(entry.getChildren(), x, y); + } + else if (typeof entry === 'string') + { + // Texture key + this.batchTextureFrameKey(entry, null, x, y, alpha, tint); + } + else if (entry instanceof Frame) + { + // Texture Frame instance + this.batchTextureFrame(entry, x, y, alpha, tint); + } + else if (Array.isArray(entry)) + { + // Another Array + this.batchList(entry, x, y, alpha, tint); + } + } + }, + + /** + * Internal method that handles the drawing a Phaser Group contents. + * + * @method Phaser.GameObjects.RenderTexture#batchGroup + * @private + * @since 3.12.0 + * + * @param {array} children - The array of Game Objects to draw. + * @param {number} [x=0] - The x position to offset the Game Object by. + * @param {number} [y=0] - The y position to offset the Game Object by. + */ + batchGroup: function (children, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + x += this.frame.cutX; + y += this.frame.cutY; + + for (var i = 0; i < children.length; i++) + { + var entry = children[i]; + + if (entry.willRender()) + { + var tx = entry.x + x; + var ty = entry.y + y; + + this.drawGameObject(entry, tx, ty); + } + } + }, + + /** + * Internal method that handles drawing a single Phaser Game Object to this Render Texture using WebGL. + * + * @method Phaser.GameObjects.RenderTexture#batchGameObjectWebGL + * @private + * @since 3.12.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to draw. + * @param {number} [x] - The x position to draw the Game Object at. + * @param {number} [y] - The y position to draw the Game Object at. + */ + batchGameObjectWebGL: function (gameObject, x, y) + { + if (x === undefined) { x = gameObject.x; } + if (y === undefined) { y = gameObject.y; } + + var prevX = gameObject.x; + var prevY = gameObject.y; + + if (!this._eraseMode) + { + this.renderer.setBlendMode(gameObject.blendMode); + } + + gameObject.setPosition(x + this.frame.cutX, y + this.frame.cutY); + + gameObject.renderWebGL(this.renderer, gameObject, 0, this.camera, null); + + gameObject.setPosition(prevX, prevY); + }, + + /** + * Internal method that handles drawing a single Phaser Game Object to this Render Texture using Canvas. + * + * @method Phaser.GameObjects.RenderTexture#batchGameObjectCanvas + * @private + * @since 3.12.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to draw. + * @param {number} [x] - The x position to draw the Game Object at. + * @param {number} [y] - The y position to draw the Game Object at. + */ + batchGameObjectCanvas: function (gameObject, x, y) + { + if (x === undefined) { x = gameObject.x; } + if (y === undefined) { y = gameObject.y; } + + var prevX = gameObject.x; + var prevY = gameObject.y; + + if (this._eraseMode) + { + var blendMode = gameObject.blendMode; + + gameObject.blendMode = BlendModes.ERASE; + } + + gameObject.setPosition(x + this.frame.cutX, y + this.frame.cutY); + + gameObject.renderCanvas(this.renderer, gameObject, 0, this.camera, null); + + gameObject.setPosition(prevX, prevY); + + if (this._eraseMode) + { + gameObject.blendMode = blendMode; + } + }, + + /** + * Internal method that handles the drawing of an array of children. + * + * @method Phaser.GameObjects.RenderTexture#batchTextureFrameKey + * @private + * @since 3.12.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * @param {number} [x=0] - The x position to offset the Game Object by. + * @param {number} [y=0] - The y position to offset the Game Object by. + * @param {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. + * @param {number} [tint] - The tint color to use. If not specified it uses the `globalTint` property. + */ + batchTextureFrameKey: function (key, frame, x, y, alpha, tint) + { + var textureFrame = this.textureManager.getFrame(key, frame); + + if (textureFrame) + { + this.batchTextureFrame(textureFrame, x, y, alpha, tint); + } + }, + + /** + * Internal method that handles the drawing of a Texture Frame to this Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#batchTextureFrame + * @private + * @since 3.12.0 + * + * @param {Phaser.Textures.Frame} textureFrame - The Texture Frame to draw. + * @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 {number} [tint] - A tint color to be applied to the frame drawn to the Render Texture. + */ + batchTextureFrame: function (textureFrame, x, y, alpha, tint) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + x += this.frame.cutX; + y += this.frame.cutY; + + if (this.gl) + { + this.pipeline.batchTextureFrame(textureFrame, x, y, tint, alpha, this.camera.matrix, null); + } + else + { + var ctx = this.context; + var cd = textureFrame.canvasData; + var source = textureFrame.source.image; + + var matrix = this.camera.matrix; + + ctx.globalAlpha = this.globalAlpha; + + ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + ctx.drawImage(source, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); + } + }, + + /** + * Takes a snapshot of the given area of this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture the whole Render Texture see the `snapshot` method. To capture a specific pixel, see `snapshotPixel`. + * + * 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.GameObjects.RenderTexture#snapshotArea + * @since 3.19.0 + * + * @param {integer} x - The x coordinate to grab from. + * @param {integer} y - The y coordinate to grab from. + * @param {integer} width - The width of the area to grab. + * @param {integer} 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 Render Texture instance. + */ + snapshotArea: function (x, y, width, height, callback, type, encoderOptions) + { + if (this.gl) + { + this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, false, x, y, width, height, type, encoderOptions); + } + else + { + this.renderer.snapshotCanvas(this.canvas, callback, false, x, y, width, height, type, encoderOptions); + } + + return this; + }, + + /** + * Takes a snapshot of the whole of this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture just a portion of the Render Texture see the `snapshotArea` method. To capture a specific pixel, see `snapshotPixel`. + * + * 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.GameObjects.RenderTexture#snapshot + * @since 3.19.0 + * + * @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 Render Texture instance. + */ + snapshot: function (callback, type, encoderOptions) + { + if (this.gl) + { + this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, false, 0, 0, this.width, this.height, type, encoderOptions); + } + else + { + this.renderer.snapshotCanvas(this.canvas, callback, false, 0, 0, this.width, this.height, type, encoderOptions); + } + + return this; + }, + + /** + * Takes a snapshot of the given pixel from this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture the whole Render Texture see the `snapshot` method. To capture a specific portion, see `snapshotArea`. + * + * Unlike the other two snapshot methods, this one will send your callback 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, than the other snapshot methods. + * + * @method Phaser.GameObjects.RenderTexture#snapshotPixel + * @since 3.19.0 + * + * @param {integer} x - The x coordinate of the pixel to get. + * @param {integer} y - The y coordinate of the pixel to get. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. + * + * @return {this} This Render Texture instance. + */ + snapshotPixel: function (x, y, callback) + { + if (this.gl) + { + this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, true, x, y); + } + else + { + this.renderer.snapshotCanvas(this.canvas, callback, true, x, y); + } + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.RenderTexture#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + if (!this._saved) + { + CanvasPool.remove(this.canvas); + + if (this.gl) + { + this.renderer.deleteFramebuffer(this.framebuffer); + } + + this.texture.destroy(); + this.camera.destroy(); + + this.canvas = null; + this.context = null; + this.framebuffer = null; + this.texture = null; + this.glTexture = null; + } + } + +}); + +module.exports = RenderTexture; + + +/***/ }), +/* 209 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates and returns an RFC4122 version 4 compliant UUID. + * + * The string is in the form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` where each `x` is replaced with a random + * hexadecimal digit from 0 to f, and `y` is replaced with a random hexadecimal digit from 8 to b. + * + * @function Phaser.Utils.String.UUID + * @since 3.12.0 + * + * @return {string} The UUID string. + */ +var UUID = function () +{ + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) + { + var r = Math.random() * 16 | 0; + var v = (c === 'x') ? r : (r & 0x3 | 0x8); + + return v.toString(16); + }); +}; + +module.exports = UUID; + + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AddToDOM = __webpack_require__(129); +var CanvasPool = __webpack_require__(28); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameEvents = __webpack_require__(21); +var GameObject = __webpack_require__(14); +var GetTextSize = __webpack_require__(1015); +var GetValue = __webpack_require__(5); +var RemoveFromDOM = __webpack_require__(191); +var TextRender = __webpack_require__(1016); +var TextStyle = __webpack_require__(1019); + +/** + * @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:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes, either + * when creating the Text object, or when setting the font via `setFont` or `setFontFamily`. I.e.: + * + * ```javascript + * this.add.text(0, 0, 'Hello World', { fontFamily: '"Roboto Condensed"' }); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * this.add.text(0, 0, 'Hello World', { fontFamily: 'Verdana, "Times New Roman", Tahoma, serif' }); + * ``` + * + * You can only display fonts that are currently loaded and available to the browser: therefore fonts must + * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, + * or have the fonts ready 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.Pipeline + * @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. + */ +var Text = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Crop, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Tint, + Components.Transform, + Components.Visible, + TextRender + ], + + initialize: + + function Text (scene, x, y, text, style) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + GameObject.call(this, scene, 'Text'); + + /** + * The renderer in use by this Text object. + * + * @name Phaser.GameObjects.Text#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.12.0 + */ + this.renderer = scene.sys.game.renderer; + + this.setPosition(x, y); + this.setOrigin(0, 0); + this.initPipeline(); + + /** + * The canvas element that the text is rendered to. + * + * @name Phaser.GameObjects.Text#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas = CanvasPool.create(this); + + /** + * The context of the canvas element that the text is rendered to. + * + * @name Phaser.GameObjects.Text#context + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * The Text Style object. + * + * Manages the style of this Text object. + * + * @name Phaser.GameObjects.Text#style + * @type {Phaser.GameObjects.TextStyle} + * @since 3.0.0 + */ + this.style = new TextStyle(this, style); + + /** + * Whether to automatically round line positions. + * + * @name Phaser.GameObjects.Text#autoRound + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.autoRound = true; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * + * @name Phaser.GameObjects.Text#splitRegExp + * @type {object} + * @since 3.0.0 + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + /** + * The text to display. + * + * @name Phaser.GameObjects.Text#_text + * @type {string} + * @private + * @since 3.12.0 + */ + this._text = undefined; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * Allows you to add extra spacing if the browser is unable to accurately determine the true font dimensions. + * + * @name Phaser.GameObjects.Text#padding + * @type {{left:number,right:number,top:number,bottom:number}} + * @since 3.0.0 + */ + this.padding = { left: 0, right: 0, top: 0, bottom: 0 }; + + /** + * The width of this Text object. + * + * @name Phaser.GameObjects.Text#width + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.width = 1; + + /** + * The height of this Text object. + * + * @name Phaser.GameObjects.Text#height + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.height = 1; + + /** + * The line spacing value. + * This value is added to the font height to calculate the overall line height. + * Only has an effect if this Text object contains multiple lines of text. + * + * If you update this property directly, instead of using the `setLineSpacing` method, then + * be sure to call `updateText` after, or you won't see the change reflected in the Text object. + * + * @name Phaser.GameObjects.Text#lineSpacing + * @type {number} + * @since 3.13.0 + */ + this.lineSpacing = 0; + + /** + * Whether the text or its settings have changed and need updating. + * + * @name Phaser.GameObjects.Text#dirty + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.dirty = false; + + // If resolution wasn't set, then we get it from the game config + if (this.style.resolution === 0) + { + this.style.resolution = scene.sys.game.config.resolution; + } + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Text#_crop + * @type {object} + * @private + * @since 3.12.0 + */ + this._crop = this.resetCropObject(); + + // Create a Texture for this Text object + this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); + + // Get the frame + this.frame = this.texture.get(); + + // Set the resolution + this.frame.source.resolution = this.style.resolution; + + if (this.renderer && this.renderer.gl) + { + // Clear the default 1x1 glTexture, as we override it later + this.renderer.deleteTexture(this.frame.source.glTexture); + + this.frame.source.glTexture = null; + } + + this.initRTL(); + + this.setText(text); + + if (style && style.padding) + { + this.setPadding(style.padding); + } + + if (style && style.lineSpacing) + { + this.setLineSpacing(style.lineSpacing); + } + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function () + { + this.dirty = true; + }, this); + }, + + /** + * Initialize right to left text. + * + * @method Phaser.GameObjects.Text#initRTL + * @since 3.0.0 + */ + initRTL: function () + { + if (!this.style.rtl) + { + return; + } + + // 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. + + this.canvas.dir = 'rtl'; + + // Experimental atm, but one day ... + this.context.direction = 'rtl'; + + // Add it to the DOM, but hidden within the parent canvas. + this.canvas.style.display = 'none'; + + AddToDOM(this.canvas, this.scene.sys.canvas); + + // And finally we set the x origin + this.originX = 1; + }, + + /** + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. + * + * @method Phaser.GameObjects.Text#runWordWrap + * @since 3.0.0 + * + * @param {string} text - The text to perform word wrap detection against. + * + * @return {string} The text after wrapping has been applied. + */ + runWordWrap: function (text) + { + var style = this.style; + + if (style.wordWrapCallback) + { + var wrappedLines = style.wordWrapCallback.call(style.wordWrapCallbackScope, text, this); + + if (Array.isArray(wrappedLines)) + { + wrappedLines = wrappedLines.join('\n'); + } + + return wrappedLines; + } + else if (style.wordWrapWidth) + { + if (style.wordWrapUseAdvanced) + { + return this.advancedWordWrap(text, this.context, this.style.wordWrapWidth); + } + else + { + return this.basicWordWrap(text, this.context, this.style.wordWrapWidth); + } + } + else + { + return text; + } + }, + + /** + * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. Consecutive spaces will be collapsed and replaced with a single space. Lines will be + * trimmed of white space before processing. Throws an error if wordWrapWidth is less than a + * single character. + * + * @method Phaser.GameObjects.Text#advancedWordWrap + * @since 3.0.0 + * + * @param {string} text - The text to perform word wrap detection against. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + * @param {number} wordWrapWidth - The word wrap width. + * + * @return {string} The wrapped text. + */ + advancedWordWrap: function (text, context, wordWrapWidth) + { + var output = ''; + + // Condense consecutive spaces and split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(this.splitRegExp); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // Trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // If entire line is less than wordWrapWidth append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // Otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // Split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // Break word + if (j === 0) + { + // Shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // If wordWrapWidth is too small for even a single letter, shame user + // failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // Replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // Append first piece to output + out += newWord; + } + + // If existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // Collapse rest of sentence and remove any trailing white space + var remainder = words.slice(offset).join(' ') + .replace(/[ \n]*$/gi, ''); + + // Prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // Processing on this line + + // Append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // Append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // Trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + }, + + /** + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. Spaces are not collapsed and whitespace is not trimmed. + * + * @method Phaser.GameObjects.Text#basicWordWrap + * @since 3.0.0 + * + * @param {string} text - The text to perform word wrap detection against. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + * @param {number} wordWrapWidth - The word wrap width. + * + * @return {string} The wrapped text. + */ + basicWordWrap: function (text, context, wordWrapWidth) + { + var result = ''; + var lines = text.split(this.splitRegExp); + var lastLineIndex = lines.length - 1; + var whiteSpaceWidth = context.measureText(' ').width; + + for (var i = 0; i <= lastLineIndex; i++) + { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + var lastWordIndex = words.length - 1; + + for (var j = 0; j <= lastWordIndex; j++) + { + var word = words[j]; + var wordWidth = context.measureText(word).width; + var wordWidthWithSpace = wordWidth + whiteSpaceWidth; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater + // than the word wrap width. + if (j > 0) + { + result += '\n'; + spaceLeft = wordWrapWidth; + } + } + + result += word; + + if (j < lastWordIndex) + { + result += ' '; + spaceLeft -= wordWidthWithSpace; + } + else + { + spaceLeft -= wordWidth; + } + } + + if (i < lastLineIndex) + { + result += '\n'; + } + } + + return result; + }, + + /** + * Runs the given text through this Text objects word wrapping and returns the results as an + * array, where each element of the array corresponds to a wrapped line of text. + * + * @method Phaser.GameObjects.Text#getWrappedText + * @since 3.0.0 + * + * @param {string} text - The text for which the wrapping will be calculated. If unspecified, the Text objects current text will be used. + * + * @return {string[]} An array of strings with the pieces of wrapped text. + */ + getWrappedText: function (text) + { + if (text === undefined) { text = this._text; } + + this.style.syncFont(this.canvas, this.context); + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(this.splitRegExp); + }, + + /** + * Set the text to display. + * + * An array of strings will be joined with `\n` line breaks. + * + * @method Phaser.GameObjects.Text#setText + * @since 3.0.0 + * + * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this Text object. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setText: function (value) + { + if (!value && value !== 0) + { + value = ''; + } + + if (Array.isArray(value)) + { + value = value.join('\n'); + } + + if (value !== this._text) + { + this._text = value.toString(); + + this.updateText(); + } + + return this; + }, + + /** + * Set the text style. + * + * @example + * text.setStyle({ + * fontSize: '64px', + * fontFamily: 'Arial', + * color: '#ffffff', + * align: 'center', + * backgroundColor: '#ff00ff' + * }); + * + * @method Phaser.GameObjects.Text#setStyle + * @since 3.0.0 + * + * @param {object} style - The style settings to set. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setStyle: function (style) + { + return this.style.setStyle(style); + }, + + /** + * 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:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: + * + * ```javascript + * Text.setFont('"Roboto Condensed"'); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); + * ``` + * + * @method Phaser.GameObjects.Text#setFont + * @since 3.0.0 + * + * @param {string} font - The font family or font settings to set. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setFont: function (font) + { + return this.style.setFont(font); + }, + + /** + * Set the font family. + * + * **Important:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: + * + * ```javascript + * Text.setFont('"Roboto Condensed"'); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); + * ``` + * + * @method Phaser.GameObjects.Text#setFontFamily + * @since 3.0.0 + * + * @param {string} family - The font family. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setFontFamily: function (family) + { + return this.style.setFontFamily(family); + }, + + /** + * Set the font size. + * + * @method Phaser.GameObjects.Text#setFontSize + * @since 3.0.0 + * + * @param {number} size - The font size. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setFontSize: function (size) + { + return this.style.setFontSize(size); + }, + + /** + * Set the font style. + * + * @method Phaser.GameObjects.Text#setFontStyle + * @since 3.0.0 + * + * @param {string} style - The font style. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setFontStyle: function (style) + { + return this.style.setFontStyle(style); + }, + + /** + * Set a fixed width and height for the text. + * + * Pass in `0` for either of these parameters to disable fixed width or height respectively. + * + * @method Phaser.GameObjects.Text#setFixedSize + * @since 3.0.0 + * + * @param {number} width - The fixed width to set. `0` disables fixed width. + * @param {number} height - The fixed height to set. `0` disables fixed height. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setFixedSize: function (width, height) + { + return this.style.setFixedSize(width, height); + }, + + /** + * Set the background color. + * + * @method Phaser.GameObjects.Text#setBackgroundColor + * @since 3.0.0 + * + * @param {string} color - The background color. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setBackgroundColor: function (color) + { + return this.style.setBackgroundColor(color); + }, + + /** + * 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|any)} color - The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setFill: function (fillStyle) + { + return this.style.setFill(fillStyle); + }, + + /** + * Set the text fill color. + * + * @method Phaser.GameObjects.Text#setColor + * @since 3.0.0 + * + * @param {string} color - The text fill color. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setColor: function (color) + { + return this.style.setColor(color); + }, + + /** + * Set the stroke settings. + * + * @method Phaser.GameObjects.Text#setStroke + * @since 3.0.0 + * + * @param {string} color - The stroke color. + * @param {number} thickness - The stroke thickness. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setStroke: function (color, thickness) + { + return this.style.setStroke(color, thickness); + }, + + /** + * Set the shadow settings. + * + * @method Phaser.GameObjects.Text#setShadow + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal shadow offset. + * @param {number} [y=0] - The vertical shadow offset. + * @param {string} [color='#000'] - The shadow color. + * @param {number} [blur=0] - The shadow blur radius. + * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. + * @param {boolean} [shadowFill=true] - Whether to fill the shadow. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setShadow: function (x, y, color, blur, shadowStroke, shadowFill) + { + return this.style.setShadow(x, y, color, blur, shadowStroke, shadowFill); + }, + + /** + * Set the shadow offset. + * + * @method Phaser.GameObjects.Text#setShadowOffset + * @since 3.0.0 + * + * @param {number} x - The horizontal shadow offset. + * @param {number} y - The vertical shadow offset. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setShadowOffset: function (x, y) + { + return this.style.setShadowOffset(x, y); + }, + + /** + * Set the shadow color. + * + * @method Phaser.GameObjects.Text#setShadowColor + * @since 3.0.0 + * + * @param {string} color - The shadow color. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setShadowColor: function (color) + { + return this.style.setShadowColor(color); + }, + + /** + * Set the shadow blur radius. + * + * @method Phaser.GameObjects.Text#setShadowBlur + * @since 3.0.0 + * + * @param {number} blur - The shadow blur radius. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setShadowBlur: function (blur) + { + return this.style.setShadowBlur(blur); + }, + + /** + * Enable or disable shadow stroke. + * + * @method Phaser.GameObjects.Text#setShadowStroke + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow stroke is enabled or not. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setShadowStroke: function (enabled) + { + return this.style.setShadowStroke(enabled); + }, + + /** + * Enable or disable shadow fill. + * + * @method Phaser.GameObjects.Text#setShadowFill + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow fill is enabled or not. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setShadowFill: function (enabled) + { + return this.style.setShadowFill(enabled); + }, + + /** + * Set the width (in pixels) to use for wrapping lines. Pass in null to remove wrapping by width. + * + * @method Phaser.GameObjects.Text#setWordWrapWidth + * @since 3.0.0 + * + * @param {?number} width - The maximum width of a line in pixels. Set to null to remove wrapping. + * @param {boolean} [useAdvancedWrap=false] - Whether or not to use the advanced wrapping + * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, + * spaces and whitespace are left as is. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setWordWrapWidth: function (width, useAdvancedWrap) + { + return this.style.setWordWrapWidth(width, useAdvancedWrap); + }, + + /** + * Set a custom callback for wrapping lines. Pass in null to remove wrapping by callback. + * + * @method Phaser.GameObjects.Text#setWordWrapCallback + * @since 3.0.0 + * + * @param {TextStyleWordWrapCallback} callback - A custom function that will be responsible for wrapping the + * text. It will receive two arguments: text (the string to wrap), textObject (this Text + * instance). It should return the wrapped lines either as an array of lines or as a string with + * newline characters in place to indicate where breaks should happen. + * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setWordWrapCallback: function (callback, scope) + { + return this.style.setWordWrapCallback(callback, scope); + }, + + /** + * Set the alignment of the text in this Text object. + * + * The argument can be one of: `left`, `right`, `center` or `justify`. + * + * Alignment only works if the Text object has more than one line of text. + * + * @method Phaser.GameObjects.Text#setAlign + * @since 3.0.0 + * + * @param {string} [align='left'] - The text alignment for multi-line text. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setAlign: function (align) + { + return this.style.setAlign(align); + }, + + /** + * Set the resolution used by this Text object. + * + * By default it will be set to match the resolution set in the Game Config, + * but you can override it via this method, or by specifying it in the Text style configuration object. + * + * It allows for much clearer text on High DPI devices, at the cost of memory because it uses larger + * internal Canvas textures for the Text. + * + * Therefore, please use with caution, as the more high res Text you have, the more memory it uses. + * + * @method Phaser.GameObjects.Text#setResolution + * @since 3.12.0 + * + * @param {number} value - The resolution for this Text object to use. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setResolution: function (value) + { + return this.style.setResolution(value); + }, + + /** + * Sets the line spacing value. + * + * This value is _added_ to the height of the font when calculating the overall line height. + * This only has an effect if this Text object consists of multiple lines of text. + * + * @method Phaser.GameObjects.Text#setLineSpacing + * @since 3.13.0 + * + * @param {number} value - The amount to add to the font height to achieve the overall line height. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setLineSpacing: function (value) + { + this.lineSpacing = value; + + return this.updateText(); + }, + + /** + * Set the text padding. + * + * 'left' can be an object. + * + * If only 'left' and 'top' are given they are treated as 'x' and 'y'. + * + * @method Phaser.GameObjects.Text#setPadding + * @since 3.0.0 + * + * @param {(number|Phaser.Types.GameObjects.Text.TextPadding)} left - The left padding value, or a padding config object. + * @param {number} top - The top padding value. + * @param {number} right - The right padding value. + * @param {number} bottom - The bottom padding value. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setPadding: function (left, top, right, bottom) + { + if (typeof left === 'object') + { + var config = left; + + // If they specify x and/or y this applies to all + var x = GetValue(config, 'x', null); + + if (x !== null) + { + left = x; + right = x; + } + else + { + left = GetValue(config, 'left', 0); + right = GetValue(config, 'right', left); + } + + var y = GetValue(config, 'y', null); + + if (y !== null) + { + top = y; + bottom = y; + } + else + { + top = GetValue(config, 'top', 0); + bottom = GetValue(config, 'bottom', top); + } + } + else + { + if (left === undefined) { left = 0; } + if (top === undefined) { top = left; } + if (right === undefined) { right = left; } + if (bottom === undefined) { bottom = top; } + } + + this.padding.left = left; + this.padding.top = top; + this.padding.right = right; + this.padding.bottom = bottom; + + return this.updateText(); + }, + + /** + * Set the maximum number of lines to draw. + * + * @method Phaser.GameObjects.Text#setMaxLines + * @since 3.0.0 + * + * @param {integer} [max=0] - The maximum number of lines to draw. + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + setMaxLines: function (max) + { + return this.style.setMaxLines(max); + }, + + /** + * Update the displayed text. + * + * @method Phaser.GameObjects.Text#updateText + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Text} This Text object. + */ + updateText: function () + { + var canvas = this.canvas; + var context = this.context; + var style = this.style; + var resolution = style.resolution; + var size = style.metrics; + + style.syncFont(canvas, context); + + var outputText = this._text; + + if (style.wordWrapWidth || style.wordWrapCallback) + { + outputText = this.runWordWrap(this._text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + var textSize = GetTextSize(this, size, lines); + + var padding = this.padding; + + var textWidth; + + if (style.fixedWidth === 0) + { + this.width = textSize.width + padding.left + padding.right; + + textWidth = textSize.width; + } + else + { + this.width = style.fixedWidth; + + textWidth = this.width - padding.left - padding.right; + + if (textWidth < textSize.width) + { + textWidth = textSize.width; + } + } + + if (style.fixedHeight === 0) + { + this.height = textSize.height + padding.top + padding.bottom; + } + else + { + this.height = style.fixedHeight; + } + + var w = this.width; + var h = this.height; + + this.updateDisplayOrigin(); + + w *= resolution; + h *= resolution; + + w = Math.max(w, 1); + h = Math.max(h, 1); + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + + this.frame.setSize(w, h); + + // Because resizing the canvas resets the context + style.syncFont(canvas, context); + } + else + { + context.clearRect(0, 0, w, h); + } + + context.save(); + + context.scale(resolution, resolution); + + if (style.backgroundColor) + { + context.fillStyle = style.backgroundColor; + context.fillRect(0, 0, w, h); + } + + style.syncStyle(canvas, context); + + context.textBaseline = 'alphabetic'; + + // Apply padding + context.translate(padding.left, padding.top); + + var linePositionX; + var linePositionY; + + // Draw text line by line + for (var i = 0; i < textSize.lines; i++) + { + linePositionX = style.strokeThickness / 2; + linePositionY = (style.strokeThickness / 2 + i * textSize.lineHeight) + size.ascent; + + if (i > 0) + { + linePositionY += (textSize.lineSpacing * i); + } + + if (style.rtl) + { + linePositionX = w - linePositionX; + } + else if (style.align === 'right') + { + linePositionX += textWidth - textSize.lineWidths[i]; + } + else if (style.align === 'center') + { + linePositionX += (textWidth - textSize.lineWidths[i]) / 2; + } + else if (style.align === 'justify') + { + // To justify text line its width must be no less than 85% of defined width + var minimumLengthToApplyJustification = 0.85; + + if (textSize.lineWidths[i] / textSize.width >= minimumLengthToApplyJustification) + { + var extraSpace = textSize.width - textSize.lineWidths[i]; + var spaceSize = context.measureText(' ').width; + var trimmedLine = lines[i].trim(); + var array = trimmedLine.split(' '); + + extraSpace += (lines[i].length - trimmedLine.length) * spaceSize; + + var extraSpaceCharacters = Math.floor(extraSpace / spaceSize); + var idx = 0; + + while (extraSpaceCharacters > 0) + { + array[idx] += ' '; + idx = (idx + 1) % (array.length - 1 || 1); + --extraSpaceCharacters; + } + + lines[i] = array.join(' '); + } + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (style.strokeThickness) + { + this.style.syncShadow(context, style.shadowStroke); + + context.strokeText(lines[i], linePositionX, linePositionY); + } + + if (style.color) + { + this.style.syncShadow(context, style.shadowFill); + + context.fillText(lines[i], linePositionX, linePositionY); + } + } + + context.restore(); + + if (this.renderer.gl) + { + this.frame.source.glTexture = this.renderer.canvasToTexture(canvas, this.frame.source.glTexture, true); + + this.frame.glTexture = this.frame.source.glTexture; + } + + this.dirty = true; + + var input = this.input; + + if (input && !input.customHitArea) + { + input.hitArea.width = this.width; + input.hitArea.height = this.height; + } + + return this; + }, + + /** + * Get the current text metrics. + * + * @method Phaser.GameObjects.Text#getTextMetrics + * @since 3.0.0 + * + * @return {object} The text metrics. + */ + getTextMetrics: function () + { + return this.style.getTextMetrics(); + }, + + /** + * The text string being rendered by this Text Game Object. + * + * @name Phaser.GameObjects.Text#text + * @type {string} + * @since 3.0.0 + */ + text: { + + get: function () + { + return this._text; + }, + + set: function (value) + { + this.setText(value); + } + + }, + + /** + * Build a JSON representation of the Text object. + * + * @method Phaser.GameObjects.Text#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Text object. + */ + toJSON: function () + { + var out = Components.ToJSON(this); + + // Extra Text data is added here + + var data = { + autoRound: this.autoRound, + text: this._text, + style: this.style.toJSON(), + padding: { + left: this.padding.left, + right: this.padding.right, + top: this.padding.top, + bottom: this.padding.bottom + } + }; + + out.data = data; + + return out; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Text#preDestroy + * @protected + * @since 3.0.0 + */ + preDestroy: function () + { + if (this.style.rtl) + { + RemoveFromDOM(this.canvas); + } + + CanvasPool.remove(this.canvas); + + this.texture.destroy(); + } + + /** + * 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 + */ + +}); + +module.exports = Text; + + +/***/ }), +/* 211 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameEvents = __webpack_require__(21); +var GameObject = __webpack_require__(14); +var GetPowerOfTwo = __webpack_require__(346); +var Smoothing = __webpack_require__(177); +var TileSpriteRender = __webpack_require__(1021); +var Vector2 = __webpack_require__(3); + +// bitmask flag for GameObject.renderMask +var _FLAG = 8; // 1000 + +/** + * @classdesc + * A TileSprite is a Sprite that has a repeating texture. + * + * The texture can be scrolled and scaled independently of the TileSprite itself. Textures will automatically wrap and + * are designed so that you can create game backdrops using seamless textures as a source. + * + * You shouldn't ever create a TileSprite any larger than your actual canvas size. If you want to create a large repeating background + * that scrolls across the whole map of your game, then you create a TileSprite that fits the canvas size and then use the `tilePosition` + * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will + * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to + * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. + * + * An important note about Tile Sprites and NPOT textures: Internally, TileSprite textures use GL_REPEAT to provide + * seamless repeating of the textures. This, combined with the way in which the textures are handled in WebGL, means + * they need to be POT (power-of-two) sizes in order to wrap. If you provide a NPOT (non power-of-two) texture to a + * TileSprite it will generate a POT sized canvas and draw your texture to it, scaled up to the POT size. It's then + * scaled back down again during rendering to the original dimensions. While this works, in that it allows you to use + * any size texture for a Tile Sprite, it does mean that NPOT textures are going to appear anti-aliased when rendered, + * due to the interpolation that took place when it was resized into a POT texture. This is especially visible in + * pixel art graphics. If you notice it and it becomes an issue, the only way to avoid it is to ensure that you + * provide POT textures for Tile Sprites. + * + * @class TileSprite + * @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.Pipeline + * @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 {integer} width - The width of the Game Object. If zero it will use the size of the texture frame. + * @param {integer} height - The height of the Game Object. If zero it will use the size of the texture frame. + * @param {string} textureKey - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frameKey] - An optional frame from the Texture this Game Object is rendering with. + */ +var TileSprite = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Crop, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Tint, + Components.Transform, + Components.Visible, + TileSpriteRender + ], + + initialize: + + function TileSprite (scene, x, y, width, height, textureKey, frameKey) + { + var renderer = scene.sys.game.renderer; + + GameObject.call(this, scene, 'TileSprite'); + + var displayTexture = scene.sys.textures.get(textureKey); + var displayFrame = displayTexture.get(frameKey); + + if (!width || !height) + { + width = displayFrame.width; + height = displayFrame.height; + } + else + { + width = Math.floor(width); + height = Math.floor(height); + } + + /** + * Internal tile position vector. + * + * @name Phaser.GameObjects.TileSprite#_tilePosition + * @type {Phaser.Math.Vector2} + * @private + * @since 3.12.0 + */ + this._tilePosition = new Vector2(); + + /** + * Internal tile scale vector. + * + * @name Phaser.GameObjects.TileSprite#_tileScale + * @type {Phaser.Math.Vector2} + * @private + * @since 3.12.0 + */ + this._tileScale = new Vector2(1, 1); + + /** + * Whether the Tile Sprite has changed in some way, requiring an re-render of its tile texture. + * + * Such changes include the texture frame and scroll position of the Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#dirty + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.dirty = false; + + /** + * The renderer in use by this Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.0.0 + */ + this.renderer = renderer; + + /** + * The Canvas element that the TileSprite renders its fill pattern in to. + * Only used in Canvas mode. + * + * @name Phaser.GameObjects.TileSprite#canvas + * @type {?HTMLCanvasElement} + * @since 3.12.0 + */ + this.canvas = CanvasPool.create(this, width, height); + + /** + * The Context of the Canvas element that the TileSprite renders its fill pattern in to. + * Only used in Canvas mode. + * + * @name Phaser.GameObjects.TileSprite#context + * @type {CanvasRenderingContext2D} + * @since 3.12.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * The Texture the TileSprite is using as its fill pattern. + * + * @name Phaser.GameObjects.TileSprite#displayTexture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @private + * @since 3.12.0 + */ + this.displayTexture = displayTexture; + + /** + * The Frame the TileSprite is using as its fill pattern. + * + * @name Phaser.GameObjects.TileSprite#displayFrame + * @type {Phaser.Textures.Frame} + * @private + * @since 3.12.0 + */ + this.displayFrame = displayFrame; + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.TileSprite#_crop + * @type {object} + * @private + * @since 3.12.0 + */ + this._crop = this.resetCropObject(); + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.TileSprite#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.TileSprite#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + this.frame = this.texture.get(); + + /** + * The next power of two value from the width of the Fill Pattern frame. + * + * @name Phaser.GameObjects.TileSprite#potWidth + * @type {integer} + * @since 3.0.0 + */ + this.potWidth = GetPowerOfTwo(displayFrame.width); + + /** + * The next power of two value from the height of the Fill Pattern frame. + * + * @name Phaser.GameObjects.TileSprite#potHeight + * @type {integer} + * @since 3.0.0 + */ + this.potHeight = GetPowerOfTwo(displayFrame.height); + + /** + * The Canvas that the TileSprites texture is rendered to. + * This is used to create a WebGL texture from. + * + * @name Phaser.GameObjects.TileSprite#fillCanvas + * @type {HTMLCanvasElement} + * @since 3.12.0 + */ + this.fillCanvas = CanvasPool.create2D(this, this.potWidth, this.potHeight); + + /** + * The Canvas Context used to render the TileSprites texture. + * + * @name Phaser.GameObjects.TileSprite#fillContext + * @type {CanvasRenderingContext2D} + * @since 3.12.0 + */ + this.fillContext = this.fillCanvas.getContext('2d'); + + /** + * The texture that the Tile Sprite is rendered to, which is then rendered to a Scene. + * In WebGL this is a WebGLTexture. In Canvas it's a Canvas Fill Pattern. + * + * @name Phaser.GameObjects.TileSprite#fillPattern + * @type {?(WebGLTexture|CanvasPattern)} + * @since 3.12.0 + */ + this.fillPattern = null; + + this.setPosition(x, y); + this.setSize(width, height); + this.setFrame(frameKey); + this.setOriginFromFrame(); + this.initPipeline(); + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer) + { + var gl = renderer.gl; + + this.dirty = true; + this.fillPattern = null; + this.fillPattern = renderer.createTexture2D(0, gl.LINEAR, gl.LINEAR, gl.REPEAT, gl.REPEAT, gl.RGBA, this.fillCanvas, this.potWidth, this.potHeight); + + }, this); + }, + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.TileSprite#setTexture + * @since 3.0.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setTexture: function (key, frame) + { + this.displayTexture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * @method Phaser.GameObjects.TileSprite#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame) + { + var newFrame = this.displayTexture.get(frame); + + this.potWidth = GetPowerOfTwo(newFrame.width); + this.potHeight = GetPowerOfTwo(newFrame.height); + + // So updateCanvas is triggered + this.canvas.width = 0; + + if (!newFrame.cutWidth || !newFrame.cutHeight) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + this.displayFrame = newFrame; + + this.dirty = true; + + this.updateTileTexture(); + + return this; + }, + + /** + * Sets {@link Phaser.GameObjects.TileSprite#tilePositionX} and {@link Phaser.GameObjects.TileSprite#tilePositionY}. + * + * @method Phaser.GameObjects.TileSprite#setTilePosition + * @since 3.3.0 + * + * @param {number} [x] - The x position of this sprite's tiling texture. + * @param {number} [y] - The y position of this sprite's tiling texture. + * + * @return {this} This Tile Sprite instance. + */ + setTilePosition: function (x, y) + { + if (x !== undefined) + { + this.tilePositionX = x; + } + + if (y !== undefined) + { + this.tilePositionY = y; + } + + return this; + }, + + /** + * Sets {@link Phaser.GameObjects.TileSprite#tileScaleX} and {@link Phaser.GameObjects.TileSprite#tileScaleY}. + * + * @method Phaser.GameObjects.TileSprite#setTileScale + * @since 3.12.0 + * + * @param {number} [x] - The horizontal scale of the tiling texture. If not given it will use the current `tileScaleX` value. + * @param {number} [y=x] - The vertical scale of the tiling texture. If not given it will use the `x` value. + * + * @return {this} This Tile Sprite instance. + */ + setTileScale: function (x, y) + { + if (x === undefined) { x = this.tileScaleX; } + if (y === undefined) { y = x; } + + this.tileScaleX = x; + this.tileScaleY = y; + + return this; + }, + + /** + * Render the tile texture if it is dirty, or if the frame has changed. + * + * @method Phaser.GameObjects.TileSprite#updateTileTexture + * @private + * @since 3.0.0 + */ + updateTileTexture: function () + { + if (!this.dirty || !this.renderer) + { + return; + } + + // Draw the displayTexture to our fillCanvas + + var frame = this.displayFrame; + + if (frame.source.isRenderTexture || frame.source.isGLTexture) + { + console.warn('TileSprites can only use Image or Canvas based textures'); + + this.dirty = false; + + return; + } + + var ctx = this.fillContext; + var canvas = this.fillCanvas; + + var fw = this.potWidth; + var fh = this.potHeight; + + if (!this.renderer.gl) + { + fw = frame.cutWidth; + fh = frame.cutHeight; + } + + ctx.clearRect(0, 0, fw, fh); + + canvas.width = fw; + canvas.height = fh; + + ctx.drawImage( + frame.source.image, + frame.cutX, frame.cutY, + frame.cutWidth, frame.cutHeight, + 0, 0, + fw, fh + ); + + if (this.renderer.gl) + { + this.fillPattern = this.renderer.canvasToTexture(canvas, this.fillPattern); + } + else + { + this.fillPattern = ctx.createPattern(canvas, 'repeat'); + } + + this.updateCanvas(); + + this.dirty = false; + }, + + /** + * Draw the fill pattern to the internal canvas. + * + * @method Phaser.GameObjects.TileSprite#updateCanvas + * @private + * @since 3.12.0 + */ + updateCanvas: function () + { + var canvas = this.canvas; + + if (canvas.width !== this.width || canvas.height !== this.height) + { + canvas.width = this.width; + canvas.height = this.height; + + this.frame.setSize(this.width, this.height); + this.updateDisplayOrigin(); + + this.dirty = true; + } + + if (!this.dirty || this.renderer && this.renderer.gl) + { + this.dirty = false; + return; + } + + var ctx = this.context; + + if (!this.scene.sys.game.config.antialias) + { + Smoothing.disable(ctx); + } + + var scaleX = this._tileScale.x; + var scaleY = this._tileScale.y; + + var positionX = this._tilePosition.x; + var positionY = this._tilePosition.y; + + ctx.clearRect(0, 0, this.width, this.height); + + ctx.save(); + + ctx.scale(scaleX, scaleY); + + ctx.translate(-positionX, -positionY); + + ctx.fillStyle = this.fillPattern; + + ctx.fillRect(positionX, positionY, this.width / scaleX, this.height / scaleY); + + ctx.restore(); + + this.dirty = false; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.TileSprite#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + if (this.renderer && this.renderer.gl) + { + this.renderer.deleteTexture(this.fillPattern); + } + + CanvasPool.remove(this.canvas); + CanvasPool.remove(this.fillCanvas); + + this.fillPattern = null; + this.fillContext = null; + this.fillCanvas = null; + + this.displayTexture = null; + this.displayFrame = null; + + this.texture.destroy(); + + this.renderer = null; + }, + + /** + * The horizontal scroll position of the Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#tilePositionX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + tilePositionX: { + + get: function () + { + return this._tilePosition.x; + }, + + set: function (value) + { + this._tilePosition.x = value; + this.dirty = true; + } + + }, + + /** + * The vertical scroll position of the Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#tilePositionY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + tilePositionY: { + + get: function () + { + return this._tilePosition.y; + }, + + set: function (value) + { + this._tilePosition.y = value; + this.dirty = true; + } + + }, + + /** + * The horizontal scale of the Tile Sprite texture. + * + * @name Phaser.GameObjects.TileSprite#tileScaleX + * @type {number} + * @default 1 + * @since 3.11.0 + */ + tileScaleX: { + + get: function () + { + return this._tileScale.x; + }, + + set: function (value) + { + this._tileScale.x = value; + this.dirty = true; + } + + }, + + /** + * The vertical scale of the Tile Sprite texture. + * + * @name Phaser.GameObjects.TileSprite#tileScaleY + * @type {number} + * @default 1 + * @since 3.11.0 + */ + tileScaleY: { + + get: function () + { + return this._tileScale.y; + }, + + set: function (value) + { + this._tileScale.y = value; + this.dirty = true; + } + + } + +}); + +module.exports = TileSprite; + + +/***/ }), +/* 212 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Clamp = __webpack_require__(20); +var Components = __webpack_require__(12); +var Events = __webpack_require__(102); +var GameEvents = __webpack_require__(21); +var GameObject = __webpack_require__(14); +var SoundEvents = __webpack_require__(64); +var UUID = __webpack_require__(209); +var VideoRender = __webpack_require__(1024); +var MATH_CONST = __webpack_require__(13); + +/** + * @classdesc + * A Video Game Object. + * + * This Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, + * or playing a video based on a given URL. Videos can be either local, or streamed. + * + * ```javascript + * preload () { + * this.load.video('pixar', 'nemo.mp4'); + * } + * + * create () { + * this.add.video(400, 300, 'pixar'); + * } + * ``` + * + * 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. + * + * ### 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, ahd 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', 'loadeddata', false, true); + * } + * ``` + * + * The 5th 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. + * + * Note that due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. + * + * 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.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.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. + */ +var Video = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + VideoRender + ], + + initialize: + + function Video (scene, x, y, key) + { + GameObject.call(this, scene, 'Video'); + + /** + * A reference to the HTML Video Element this Video Game Object is playing. + * Will be `null` until a video is loaded for playback. + * + * @name Phaser.GameObjects.Video#video + * @type {?HTMLVideoElement} + * @since 3.20.0 + */ + this.video = null; + + /** + * The Phaser Texture this Game Object is using to render the video to. + * Will be `null` until a video is loaded for playback. + * + * @name Phaser.GameObjects.Video#videoTexture + * @type {?Phaser.Textures.Texture} + * @since 3.20.0 + */ + this.videoTexture = null; + + /** + * A reference to the TextureSource belong to the `videoTexture` Texture object. + * Will be `null` until a video is loaded for playback. + * + * @name Phaser.GameObjects.Video#videoTextureSource + * @type {?Phaser.Textures.TextureSource} + * @since 3.20.0 + */ + this.videoTextureSource = null; + + /** + * A Phaser CanvasTexture instance that holds the most recent snapshot taken from the video. + * This will only be set if `snapshot` or `snapshotArea` have been called, and will be `null` until that point. + * + * @name Phaser.GameObjects.Video#snapshotTexture + * @type {?Phaser.Textures.CanvasTexture} + * @since 3.20.0 + */ + this.snapshotTexture = null; + + /** + * If you have saved this video to a texture via the `saveTexture` method, this controls if the video + * is rendered with `flipY` in WebGL or not. You often need to set this if you wish to use the video texture + * as the input source for a shader. If you find your video is appearing upside down within a shader or + * custom pipeline, flip this property. + * + * @name Phaser.GameObjects.Video#flipY + * @type {boolean} + * @since 3.20.0 + */ + this.flipY = false; + + /** + * The key used by the texture as stored in the Texture Manager. + * + * @name Phaser.GameObjects.Video#_key + * @type {string} + * @private + * @since 3.20.0 + */ + this._key = UUID(); + + /** + * An internal flag holding the current state of the video lock, should document interaction be required + * before playback can begin. + * + * @name Phaser.GameObjects.Video#touchLocked + * @type {boolean} + * @since 3.20.0 + */ + this.touchLocked = true; + + /** + * Should the video auto play when document interaction is required and happens? + * + * @name Phaser.GameObjects.Video#playWhenUnlocked + * @type {boolean} + * @since 3.20.0 + */ + this.playWhenUnlocked = false; + + /** + * When starting playback of a video Phaser will monitor its `readyState` using a `setTimeout` call. + * The `setTimeout` happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * + * @name Phaser.GameObjects.Video#retryLimit + * @type {integer} + * @since 3.20.0 + */ + this.retryLimit = 20; + + /** + * The current retry attempt. + * + * @name Phaser.GameObjects.Video#retry + * @type {integer} + * @since 3.20.0 + */ + this.retry = 0; + + /** + * The number of ms between each retry while monitoring the ready state of a downloading video. + * + * @name Phaser.GameObjects.Video#retryInterval + * @type {integer} + * @since 3.20.0 + */ + this.retryInterval = 500; + + /** + * The setTimeout callback ID. + * + * @name Phaser.GameObjects.Video#_retryID + * @type {integer} + * @private + * @since 3.20.0 + */ + this._retryID = null; + + /** + * The video was muted due to a system event, such as the game losing focus. + * + * @name Phaser.GameObjects.Video#_systemMuted + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._systemMuted = false; + + /** + * The video was muted due to game code, not a system event. + * + * @name Phaser.GameObjects.Video#_codeMuted + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._codeMuted = false; + + /** + * The video was paused due to a system event, such as the game losing focus. + * + * @name Phaser.GameObjects.Video#_systemPaused + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._systemPaused = false; + + /** + * The video was paused due to game code, not a system event. + * + * @name Phaser.GameObjects.Video#_codePaused + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._codePaused = false; + + /** + * The locally bound event callback handlers. + * + * @name Phaser.GameObjects.Video#_callbacks + * @type {any} + * @private + * @since 3.20.0 + */ + this._callbacks = { + play: this.playHandler.bind(this), + error: this.loadErrorHandler.bind(this), + end: this.completeHandler.bind(this), + time: this.timeUpdateHandler.bind(this), + seeking: this.seekingHandler.bind(this), + seeked: this.seekedHandler.bind(this) + }; + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Video#_crop + * @type {object} + * @private + * @since 3.20.0 + */ + this._crop = this.resetCropObject(); + + /** + * An object containing in and out markers for sequence playback. + * + * @name Phaser.GameObjects.Video#markers + * @type {any} + * @since 3.20.0 + */ + this.markers = {}; + + /** + * The in marker. + * + * @name Phaser.GameObjects.Video#_markerIn + * @type {integer} + * @private + * @since 3.20.0 + */ + this._markerIn = -1; + + /** + * The out marker. + * + * @name Phaser.GameObjects.Video#_markerOut + * @type {integer} + * @private + * @since 3.20.0 + */ + this._markerOut = MATH_CONST.MAX_SAFE_INTEGER; + + /** + * The last time the TextureSource was updated. + * + * @name Phaser.GameObjects.Video#_lastUpdate + * @type {integer} + * @private + * @since 3.20.0 + */ + this._lastUpdate = 0; + + /** + * The key of the video being played from the Video cache, if any. + * + * @name Phaser.GameObjects.Video#_cacheKey + * @type {string} + * @private + * @since 3.20.0 + */ + this._cacheKey = ''; + + /** + * Is the video currently seeking? + * + * @name Phaser.GameObjects.Video#_isSeeking + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._isSeeking = false; + + /** + * Should the Video element that this Video is using, be removed from the DOM + * when this Video is destroyed? + * + * @name Phaser.GameObjects.Video#removeVideoElementOnDestroy + * @type {boolean} + * @since 3.21.0 + */ + this.removeVideoElementOnDestroy = false; + + this.setPosition(x, y); + this.initPipeline(); + + if (key) + { + this.changeSource(key, false); + } + + var game = scene.sys.game.events; + + game.on(GameEvents.PAUSE, this.globalPause, this); + game.on(GameEvents.RESUME, this.globalResume, this); + + var sound = scene.sys.sound; + + if (sound) + { + sound.on(SoundEvents.GLOBAL_MUTE, this.globalMute, this); + } + }, + + /** + * 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', 'loadeddata', false, true); + * } + * ``` + * + * The 5th 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 {integer} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video. + * @param {integer} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video. + * + * @return {this} This Video Game Object for method chaining. + */ + play: function (loop, markerIn, markerOut) + { + if ((this.touchLocked && this.playWhenUnlocked) || this.isPlaying()) + { + return this; + } + + var video = this.video; + + if (!video) + { + console.warn('Video not loaded'); + + return this; + } + + if (loop === undefined) { loop = video.loop; } + + var sound = this.scene.sys.sound; + + if (sound && sound.mute) + { + // Mute will be set based on the global mute state of the Sound Manager (if there is one) + this.setMute(true); + } + + if (!isNaN(markerIn)) + { + this._markerIn = markerIn; + } + + if (!isNaN(markerOut) && markerOut > markerIn) + { + this._markerOut = markerOut; + } + + video.loop = loop; + + var callbacks = this._callbacks; + + var playPromise = video.play(); + + if (playPromise !== undefined) + { + playPromise.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)); + } + else + { + // Old-school browsers with no Promises + video.addEventListener('playing', callbacks.play, true); + + // If video hasn't downloaded properly yet ... + if (video.readyState < 2) + { + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + } + + // Set these _after_ calling `play` or they don't fire (useful, thanks browsers) + video.addEventListener('ended', callbacks.end, true); + video.addEventListener('timeupdate', callbacks.time, true); + video.addEventListener('seeking', callbacks.seeking, true); + video.addEventListener('seeked', callbacks.seeked, true); + + return this; + }, + + /** + * This method allows you to change the source of the current video element. It works by first stopping the + * current video, if playing. Then deleting the video texture, if one has been created. Finally, it makes a + * new video texture and starts playback of the new source through the existing video element. + * + * The reason you may wish to do this is because videos that require interaction to unlock, remain in an unlocked + * state, even if you change the source of the video. By changing the source to a new video you avoid having to + * go through the unlock process again. + * + * @method Phaser.GameObjects.Video#changeSource + * @since 3.20.0 + * + * @param {string} key - The key of the Video this Game Object will swap to playing, as stored in the Video Cache. + * @param {boolean} [autoplay=true] - Should the video start playing immediately, once the swap is complete? + * @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 {integer} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video. + * @param {integer} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video. + * + * @return {this} This Video Game Object for method chaining. + */ + changeSource: function (key, autoplay, loop, markerIn, markerOut) + { + if (autoplay === undefined) { autoplay = true; } + + var currentVideo = this.video; + + if (currentVideo) + { + this.stop(); + } + + var newVideo = this.scene.sys.cache.video.get(key); + + if (newVideo) + { + this.video = newVideo; + + this._cacheKey = key; + + this._codePaused = newVideo.paused; + this._codeMuted = newVideo.muted; + + if (this.videoTexture) + { + this.scene.sys.textures.remove(this._key); + + this.videoTexture = this.scene.sys.textures.create(this._key, newVideo, newVideo.videoWidth, newVideo.videoHeight); + this.videoTextureSource = this.videoTexture.source[0]; + this.videoTexture.add('__BASE', 0, 0, 0, newVideo.videoWidth, newVideo.videoHeight); + + this.setTexture(this.videoTexture); + this.setSizeToFrame(); + this.updateDisplayOrigin(); + + this.emit(Events.VIDEO_CREATED, this, newVideo.videoWidth, newVideo.videoHeight); + } + else + { + this.updateTexture(); + } + + newVideo.currentTime = 0; + + this._lastUpdate = 0; + + if (autoplay) + { + this.play(loop, markerIn, markerOut); + } + } + else + { + this.video = null; + } + + return this; + }, + + /** + * 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 {integer} markerIn - The time, in seconds, representing the start of this marker. + * @param {integer} markerOut - The time, in seconds, representing the end of this marker. + * + * @return {this} This Video Game Object for method chaining. + */ + addMarker: function (key, markerIn, markerOut) + { + if (!isNaN(markerIn) && markerIn >= 0 && !isNaN(markerOut)) + { + this.markers[key] = [ markerIn, markerOut ]; + } + + return this; + }, + + /** + * 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. + */ + playMarker: function (key, loop) + { + var marker = this.markers[key]; + + if (marker) + { + this.play(loop, marker[0], marker[1]); + } + + return this; + }, + + /** + * Removes a previously set marker from this video. + * + * If the marker is currently playing it will _not_ stop playback. + * + * @method Phaser.GameObjects.Video#removeMarker + * @since 3.20.0 + * + * @param {string} key - The name of the marker to remove. + * + * @return {this} This Video Game Object for method chaining. + */ + removeMarker: function (key) + { + delete this.markers[key]; + + return this; + }, + + /** + * Takes a snapshot of the current frame of the video and renders it to a CanvasTexture object, + * which is then returned. You can optionally resize the grab by passing a width and height. + * + * This method returns a reference to the `Video.snapshotTexture` object. Calling this method + * multiple times will overwrite the previous snapshot with the most recent one. + * + * @method Phaser.GameObjects.Video#snapshot + * @since 3.20.0 + * + * @param {integer} [width] - The width of the resulting CanvasTexture. + * @param {integer} [height] - The height of the resulting CanvasTexture. + * + * @return {Phaser.Textures.CanvasTexture} + */ + snapshot: function (width, height) + { + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + return this.snapshotArea(0, 0, this.width, this.height, width, height); + }, + + /** + * Takes a snapshot of the specified area of the current frame of the video and renders it to a CanvasTexture object, + * which is then returned. You can optionally resize the grab by passing a different `destWidth` and `destHeight`. + * + * This method returns a reference to the `Video.snapshotTexture` object. Calling this method + * multiple times will overwrite the previous snapshot with the most recent one. + * + * @method Phaser.GameObjects.Video#snapshotArea + * @since 3.20.0 + * + * @param {integer} [x=0] - The horizontal location of the top-left of the area to grab from. + * @param {integer} [y=0] - The vertical location of the top-left of the area to grab from. + * @param {integer} [srcWidth] - The width of area to grab from the video. If not given it will grab the full video dimensions. + * @param {integer} [srcHeight] - The height of area to grab from the video. If not given it will grab the full video dimensions. + * @param {integer} [destWidth] - The destination width of the grab, allowing you to resize it. + * @param {integer} [destHeight] - The destination height of the grab, allowing you to resize it. + * + * @return {Phaser.Textures.CanvasTexture} + */ + snapshotArea: function (x, y, srcWidth, srcHeight, destWidth, destHeight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (srcWidth === undefined) { srcWidth = this.width; } + if (srcHeight === undefined) { srcHeight = this.height; } + if (destWidth === undefined) { destWidth = srcWidth; } + if (destHeight === undefined) { destHeight = srcHeight; } + + var video = this.video; + var snap = this.snapshotTexture; + + if (!snap) + { + snap = this.scene.sys.textures.createCanvas(UUID(), destWidth, destHeight); + + this.snapshotTexture = snap; + + if (video) + { + snap.context.drawImage(video, x, y, srcWidth, srcHeight, 0, 0, destWidth, destHeight); + } + } + else + { + snap.setSize(destWidth, destHeight); + + if (video) + { + snap.context.drawImage(video, x, y, srcWidth, srcHeight, 0, 0, destWidth, destHeight); + } + } + + return snap.update(); + }, + + /** + * Stores a copy of this Videos `snapshotTexture` in the Texture Manager using the given key. + * + * This texture is created when the `snapshot` or `snapshotArea` methods are called. + * + * After doing this, any texture based Game Object, such as a Sprite, can use the contents of the + * snapshot by using the texture key: + * + * ```javascript + * var vid = this.add.video(0, 0, 'intro'); + * + * vid.snapshot(); + * + * vid.saveSnapshotTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Updating the contents of the `snapshotTexture`, for example by calling `snapshot` again, + * will automatically update _any_ Game Object that is using it as a texture. + * Calling `saveSnapshotTexture` again will not save another copy of the same texture, + * it will just rename the existing one. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame. + * + * @method Phaser.GameObjects.Video#saveSnapshotTexture + * @since 3.20.0 + * + * @param {string} key - The unique key to store the texture as within the global Texture Manager. + * + * @return {Phaser.Textures.CanvasTexture} The Texture that was saved. + */ + saveSnapshotTexture: function (key) + { + if (this.snapshotTexture) + { + this.scene.sys.textures.renameTexture(this.snapshotTexture.key, key); + } + else + { + this.snapshotTexture = this.scene.sys.textures.createCanvas(key, this.width, this.height); + } + + return this.snapshotTexture; + }, + + /** + * Loads a Video from the given URL, ready for playback with the `Video.play` method. + * + * You can control at what point the browser determines the video as being ready for playback via + * the `loadEvent` parameter. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement + * for more details. + * + * @method Phaser.GameObjects.Video#loadURL + * @since 3.20.0 + * + * @param {string} url - The URL of the video to load or be streamed. + * @param {string} [loadEvent='loadeddata'] - The load event to listen for. Either `loadeddata`, `canplay` or `canplaythrough`. + * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. + * + * @return {this} This Video Game Object for method chaining. + */ + loadURL: function (url, loadEvent, noAudio) + { + if (loadEvent === undefined) { loadEvent = 'loadeddata'; } + if (noAudio === undefined) { noAudio = false; } + + if (this.video) + { + this.stop(); + } + + if (this.videoTexture) + { + this.scene.sys.textures.remove(this._key); + } + + var video = document.createElement('video'); + + video.controls = false; + + if (noAudio) + { + video.muted = true; + video.defaultMuted = true; + + video.setAttribute('autoplay', 'autoplay'); + } + + video.setAttribute('playsinline', 'playsinline'); + video.setAttribute('preload', 'auto'); + + video.addEventListener('error', this._callbacks.error, true); + + video.src = url; + + video.load(); + + this.video = video; + + return this; + }, + + /** + * This internal method is called automatically if the playback Promise resolves successfully. + * + * @method Phaser.GameObjects.Video#playPromiseSuccessHandler + * @fires Phaser.GameObjects.Events#VIDEO_PLAY + * @private + * @since 3.20.0 + */ + playPromiseSuccessHandler: function () + { + this.touchLocked = false; + + this.emit(Events.VIDEO_PLAY, this); + + if (this._markerIn > -1) + { + this.video.currentTime = this._markerIn; + } + }, + + /** + * This internal method is called automatically if the playback Promise fails to resolve. + * + * @method Phaser.GameObjects.Video#playPromiseErrorHandler + * @fires Phaser.GameObjects.Events#VIDEO_ERROR + * @private + * @since 3.20.0 + * + * @param {any} error - The Promise resolution error. + */ + playPromiseErrorHandler: function (error) + { + this.scene.sys.input.once('pointerdown', this.unlockHandler, this); + + this.touchLocked = true; + this.playWhenUnlocked = true; + + this.emit(Events.VIDEO_ERROR, this, error); + }, + + /** + * Called when the video emits a `playing` event during load. + * + * This is only listened for if the browser doesn't support Promises. + * + * @method Phaser.GameObjects.Video#playHandler + * @fires Phaser.GameObjects.Events#VIDEO_PLAY + * @since 3.20.0 + */ + playHandler: function () + { + this.touchLocked = false; + + this.emit(Events.VIDEO_PLAY, this); + + this.video.removeEventListener('playing', this._callbacks.play, true); + }, + + /** + * This internal method is called automatically if the video fails to load. + * + * @method Phaser.GameObjects.Video#loadErrorHandler + * @fires Phaser.GameObjects.Events#VIDEO_ERROR + * @private + * @since 3.20.0 + * + * @param {Event} event - The error Event. + */ + loadErrorHandler: function (event) + { + this.stop(); + + this.emit(Events.VIDEO_ERROR, this, event); + }, + + /** + * This internal method is called if the video couldn't be played because it was interaction locked + * by the browser, but an input event has since been received. + * + * @method Phaser.GameObjects.Video#unlockHandler + * @fires Phaser.GameObjects.Events#VIDEO_UNLOCKED + * @fires Phaser.GameObjects.Events#VIDEO_PLAY + * @private + * @since 3.20.0 + * + * @param {any} error - The Promise resolution error. + */ + unlockHandler: function () + { + this.touchLocked = false; + this.playWhenUnlocked = false; + + this.emit(Events.VIDEO_UNLOCKED, this); + + if (this._markerIn > -1) + { + this.video.currentTime = this._markerIn; + } + + this.video.play(); + + this.emit(Events.VIDEO_PLAY, this); + }, + + /** + * Called when the video completes playback, i.e. reaches an `ended` state. + * + * This will never happen if the video is coming from a live stream, where the duration is `Infinity`. + * + * @method Phaser.GameObjects.Video#completeHandler + * @fires Phaser.GameObjects.Events#VIDEO_COMPLETE + * @since 3.20.0 + */ + completeHandler: function () + { + this.emit(Events.VIDEO_COMPLETE, this); + }, + + /** + * Called when the video emits a `timeUpdate` event during playback. + * + * This event is too slow and irregular to be used for actual video timing or texture updating, + * but we can use it to determine if a video has looped. + * + * @method Phaser.GameObjects.Video#timeUpdateHandler + * @fires Phaser.GameObjects.Events#VIDEO_LOOP + * @since 3.20.0 + */ + timeUpdateHandler: function () + { + if (this.video && this.video.currentTime < this._lastUpdate) + { + this.emit(Events.VIDEO_LOOP, this); + + this._lastUpdate = 0; + } + }, + + /** + * The internal update step. + * + * @method Phaser.GameObjects.Video#preUpdate + * @private + * @since 3.20.0 + */ + preUpdate: function () + { + var video = this.video; + + if (video) + { + var currentTime = video.currentTime; + + // Don't render a new frame unless the video has actually changed time + if (currentTime !== this._lastUpdate) + { + this._lastUpdate = currentTime; + + this.updateTexture(); + + if (currentTime >= this._markerOut) + { + if (video.loop) + { + video.currentTime = this._markerIn; + + this.updateTexture(); + + this._lastUpdate = currentTime; + + this.emit(Events.VIDEO_LOOP, this); + } + else + { + this.emit(Events.VIDEO_COMPLETE, this); + + this.stop(); + } + } + } + } + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.GameObjects.Video#checkVideoProgress + * @fires Phaser.GameObjects.Events#VIDEO_TIMEOUT + * @private + * @since 3.20.0 + */ + checkVideoProgress: function () + { + if (this.video.readyState >= 2) + { + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this.emit(Events.VIDEO_TIMEOUT, this); + } + } + }, + + /** + * Internal method that is called when enough video data has been received in order to create a texture + * from it. The texture is assigned to the `Video.videoTexture` property and given a base frame that + * encompases the whole video size. + * + * @method Phaser.GameObjects.Video#updateTexture + * @since 3.20.0 + */ + updateTexture: function () + { + var video = this.video; + + var width = video.videoWidth; + var height = video.videoHeight; + + if (!this.videoTexture) + { + this.videoTexture = this.scene.sys.textures.create(this._key, video, width, height); + this.videoTextureSource = this.videoTexture.source[0]; + this.videoTexture.add('__BASE', 0, 0, 0, width, height); + + this.setTexture(this.videoTexture); + this.setSizeToFrame(); + this.updateDisplayOrigin(); + + this.emit(Events.VIDEO_CREATED, this, width, height); + } + else + { + var textureSource = this.videoTextureSource; + + if (textureSource.source !== video) + { + textureSource.source = video; + textureSource.width = width; + textureSource.height = height; + } + + textureSource.update(); + } + }, + + /** + * Returns the key of the currently played video, as stored in the Video Cache. + * If the video did not come from the cache this will return an empty string. + * + * @method Phaser.GameObjects.Video#getVideoKey + * @since 3.20.0 + * + * @return {string} The key of the video being played from the Video Cache, if any. + */ + getVideoKey: function () + { + return this._cacheKey; + }, + + /** + * 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. + * + * @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. + */ + seekTo: function (value) + { + var video = this.video; + + if (video) + { + var duration = video.duration; + + if (duration !== Infinity && !isNaN(duration)) + { + var seekTime = duration * value; + + this.setCurrentTime(seekTime); + } + } + + return this; + }, + + /** + * A double-precision floating-point value indicating the current playback time in seconds. + * If the media has not started to play and has not been seeked, this value is the media's initial playback time. + * + * @method Phaser.GameObjects.Video#getCurrentTime + * @since 3.20.0 + * + * @return {number} A double-precision floating-point value indicating the current playback time in seconds. + */ + getCurrentTime: function () + { + return (this.video) ? this.video.currentTime : 0; + }, + + /** + * 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. + */ + setCurrentTime: function (value) + { + var video = this.video; + + if (video) + { + if (typeof value === 'string') + { + var op = value[0]; + var num = parseFloat(value.substr(1)); + + if (op === '+') + { + value = video.currentTime + num; + } + else if (op === '-') + { + value = video.currentTime - num; + } + } + + video.currentTime = value; + + this._lastUpdate = value; + } + + return this; + }, + + /** + * Returns a boolean indicating if this Video is currently seeking, or not. + * + * @method Phaser.GameObjects.Video#isSeeking + * @since 3.20.0 + * + * @return {boolean} A boolean indicating if this Video is currently seeking, or not. + */ + isSeeking: function () + { + return this._isSeeking; + }, + + /** + * Internal seeking handler. + * + * @method Phaser.GameObjects.Video#seekingHandler + * @fires Phaser.GameObjects.Events#VIDEO_SEEKING + * @private + * @since 3.20.0 + */ + seekingHandler: function () + { + this._isSeeking = true; + + this.emit(Events.VIDEO_SEEKING, this); + }, + + /** + * Internal seeked handler. + * + * @method Phaser.GameObjects.Video#seekedHandler + * @fires Phaser.GameObjects.Events#VIDEO_SEEKED + * @private + * @since 3.20.0 + */ + seekedHandler: function () + { + this._isSeeking = false; + + this.emit(Events.VIDEO_SEEKED, this); + + var video = this.video; + + if (video) + { + this.updateTexture(); + } + }, + + /** + * Returns the current progress of the video. Progress is defined as a value between 0 (the start) + * and 1 (the end). + * + * Progress can only be returned if the video has a duration, otherwise it will always return zero. + * + * @method Phaser.GameObjects.Video#getProgress + * @since 3.20.0 + * + * @return {number} The current progress of playback. If the video has no duration, will always return zero. + */ + getProgress: function () + { + var video = this.video; + + if (video) + { + var now = video.currentTime; + var duration = video.duration; + + if (duration !== Infinity && !isNaN(duration)) + { + return now / duration; + } + } + + return 0; + }, + + /** + * A double-precision floating-point value which indicates the duration (total length) of the media in seconds, + * on the media's timeline. If no media is present on the element, or the media is not valid, the returned value is NaN. + * + * If the media has no known end (such as for live streams of unknown duration, web radio, media incoming from WebRTC, + * and so forth), this value is +Infinity. + * + * @method Phaser.GameObjects.Video#getDuration + * @since 3.20.0 + * + * @return {number} A double-precision floating-point value indicating the duration of the media in seconds. + */ + getDuration: function () + { + return (this.video) ? this.video.duration : 0; + }, + + /** + * Sets the muted state of the currently playing video, if one is loaded. + * + * @method Phaser.GameObjects.Video#setMute + * @since 3.20.0 + * + * @param {boolean} [value=true] - The mute value. `true` if the video should be muted, otherwise `false`. + * + * @return {this} This Video Game Object for method chaining. + */ + setMute: function (value) + { + if (value === undefined) { value = true; } + + this._codeMuted = value; + + var video = this.video; + + if (video) + { + video.muted = (this._systemMuted) ? true : value; + } + + return this; + }, + + /** + * Returns a boolean indicating if this Video is currently muted. + * + * @method Phaser.GameObjects.Video#isMuted + * @since 3.20.0 + * + * @return {boolean} A boolean indicating if this Video is currently muted, or not. + */ + isMuted: function () + { + return this._codeMuted; + }, + + /** + * Internal global mute handler. Will mute the video, if playing, if the global sound system mutes. + * + * @method Phaser.GameObjects.Video#globalMute + * @private + * @since 3.20.0 + * + * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the Sound Manager that emitted the event. + * @param {boolean} mute - The mute value. `true` if the Sound Manager is now muted, otherwise `false`. + */ + globalMute: function (soundManager, value) + { + this._systemMuted = value; + + var video = this.video; + + if (video) + { + video.muted = (this._codeMuted) ? true : value; + } + }, + + /** + * Internal global pause handler. Will pause the video if the Game itself pauses. + * + * @method Phaser.GameObjects.Video#globalPause + * @private + * @since 3.20.0 + */ + globalPause: function () + { + this._systemPaused = true; + + if (this.video) + { + this.video.pause(); + } + }, + + /** + * Internal global resume handler. Will resume a paused video if the Game itself resumes. + * + * @method Phaser.GameObjects.Video#globalResume + * @private + * @since 3.20.0 + */ + globalResume: function () + { + this._systemPaused = false; + + if (this.video && !this._codePaused) + { + this.video.play(); + } + }, + + /** + * Sets the paused state of the currently loaded video. + * + * If the video is playing, calling this method with `true` will pause playback. + * If the video is paused, calling this method with `false` will resume playback. + * + * If no video is loaded, this method does nothing. + * + * @method Phaser.GameObjects.Video#setPaused + * @since 3.20.0 + * + * @param {boolean} [value=true] - The paused value. `true` if the video should be paused, `false` to resume it. + * + * @return {this} This Video Game Object for method chaining. + */ + setPaused: function (value) + { + if (value === undefined) { value = true; } + + var video = this.video; + + this._codePaused = value; + + if (video) + { + if (value) + { + if (!video.paused) + { + video.pause(); + } + } + else if (!value) + { + if (video.paused && !this._systemPaused) + { + video.play(); + } + } + } + + return this; + }, + + /** + * Returns a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * + * @method Phaser.GameObjects.Video#getVolume + * @since 3.20.0 + * + * @return {number} A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + */ + getVolume: function () + { + return (this.video) ? this.video.volume : 1; + }, + + /** + * Sets the volume of the currently playing video. + * + * The value given is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * + * @method Phaser.GameObjects.Video#setVolume + * @since 3.20.0 + * + * @param {number} [value=1] - A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * + * @return {this} This Video Game Object for method chaining. + */ + setVolume: function (value) + { + if (value === undefined) { value = 1; } + + if (this.video) + { + this.video.volume = Clamp(value, 0, 1); + } + + return this; + }, + + /** + * Returns a double that indicates the rate at which the media is being played back. + * + * @method Phaser.GameObjects.Video#getPlaybackRate + * @since 3.20.0 + * + * @return {number} A double that indicates the rate at which the media is being played back. + */ + getPlaybackRate: function () + { + return (this.video) ? this.video.playbackRate : 1; + }, + + /** + * Sets the playback rate of the current video. + * + * The value given is a double that indicates the rate at which the media is being played back. + * + * @method Phaser.GameObjects.Video#setPlaybackRate + * @since 3.20.0 + * + * @param {number} [rate] - A double that indicates the rate at which the media is being played back. + * + * @return {this} This Video Game Object for method chaining. + */ + setPlaybackRate: function (rate) + { + if (this.video) + { + this.video.playbackRate = rate; + } + + return this; + }, + + /** + * Returns a boolean which indicates whether the media element should start over when it reaches the end. + * + * @method Phaser.GameObjects.Video#getLoop + * @since 3.20.0 + * + * @return {boolean} A boolean which indicates whether the media element will start over when it reaches the end. + */ + getLoop: function () + { + return (this.video) ? this.video.loop : false; + }, + + /** + * Sets the loop state of the current video. + * + * The value given is a boolean which indicates whether the media element will start over when it reaches the end. + * + * Not all videos can loop, for example live streams. + * + * Please note that not all browsers support _seamless_ video looping for all encoding formats. + * + * @method Phaser.GameObjects.Video#setLoop + * @since 3.20.0 + * + * @param {boolean} [value=true] - A boolean which indicates whether the media element will start over when it reaches the end. + * + * @return {this} This Video Game Object for method chaining. + */ + setLoop: function (value) + { + if (value === undefined) { value = true; } + + if (this.video) + { + this.video.loop = value; + } + + return this; + }, + + /** + * Returns a boolean which indicates whether the video is currently playing. + * + * @method Phaser.GameObjects.Video#isPlaying + * @since 3.20.0 + * + * @return {boolean} A boolean which indicates whether the video is playing, or not. + */ + isPlaying: function () + { + return (this.video) ? !(this.video.paused || this.video.ended) : false; + }, + + /** + * Returns a boolean which indicates whether the video is currently paused. + * + * @method Phaser.GameObjects.Video#isPaused + * @since 3.20.0 + * + * @return {boolean} A boolean which indicates whether the video is paused, or not. + */ + isPaused: function () + { + return ((this.video && this.video.paused) || this._codePaused || this._systemPaused); + }, + + /** + * Stores this Video in the Texture Manager using the given key as a dynamic texture, + * which any texture-based Game Object, such as a Sprite, can use as its texture: + * + * ```javascript + * var vid = this.add.video(0, 0, 'intro'); + * + * vid.play(); + * + * vid.saveTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * The saved texture is automatically updated as the video plays. If you pause this video, + * or change its source, then the saved texture updates instantly. + * + * Calling `saveTexture` again will not save another copy of the same texture, it will just rename the existing one. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame. + * + * If you intend to save the texture so you can use it as the input for a Shader, you may need to set the + * `flipY` parameter to `true` if you find the video renders upside down in your shader. + * + * @method Phaser.GameObjects.Video#saveTexture + * @since 3.20.0 + * + * @param {string} key - The unique key to store the texture as within the global Texture Manager. + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y` during upload? + * + * @return {Phaser.Textures.Texture} The Texture that was saved. + */ + saveTexture: function (key, flipY) + { + if (flipY === undefined) { flipY = false; } + + if (this.videoTexture) + { + this.scene.sys.textures.renameTexture(this._key, key); + } + + this._key = key; + + this.flipY = flipY; + + if (this.videoTextureSource) + { + this.videoTextureSource.setFlipY(flipY); + } + + return this.videoTexture; + }, + + /** + * Stops the video playing and clears all internal event listeners. + * + * If you only wish to pause playback of the video, and resume it a later time, use the `Video.pause` method instead. + * + * If the video hasn't finished downloading, calling this method will not abort the download. To do that you need to + * call `destroy` instead. + * + * @method Phaser.GameObjects.Video#stop + * @fires Phaser.GameObjects.Events#VIDEO_STOP + * @since 3.20.0 + * + * @return {this} This Video Game Object for method chaining. + */ + stop: function () + { + var video = this.video; + + if (video) + { + var callbacks = this._callbacks; + + for (var callback in callbacks) + { + video.removeEventListener(callback, callbacks[callback], true); + } + + video.pause(); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + this.emit(Events.VIDEO_STOP, this); + + return this; + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * + * Also removes the autoplay and src attributes and nulls the Video reference. + * + * You should not call this method if you were playing a video from the Video Cache that + * you wish to play again in your game, or if another Video object is also using the same + * video. + * + * If you loaded an external video via `Video.loadURL` then you should call this function + * to clear up once you are done with the instance. + * + * @method Phaser.GameObjects.Video#removeVideoElement + * @since 3.20.0 + */ + removeVideoElement: function () + { + var video = this.video; + + if (!video) + { + return; + } + + if (video.parentNode) + { + video.parentNode.removeChild(video); + } + + while (video.hasChildNodes()) + { + video.removeChild(video.firstChild); + } + + video.removeAttribute('autoplay'); + video.removeAttribute('src'); + + this.video = null; + }, + + /** + * Handles the pre-destroy step for the Video object. + * + * This calls `Video.stop` and optionally `Video.removeVideoElement`. + * + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.GameObjects.Video#preDestroy + * @private + * @since 3.21.0 + */ + preDestroy: function () + { + this.stop(); + + if (this.removeVideoElementOnDestroy) + { + this.removeVideoElement(); + } + + var game = this.scene.sys.game.events; + + game.off(GameEvents.PAUSE, this.globalPause, this); + game.off(GameEvents.RESUME, this.globalResume, this); + + var sound = this.scene.sys.sound; + + if (sound) + { + sound.off(SoundEvents.GLOBAL_MUTE, this.globalMute, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + } + +}); + +module.exports = Video; + + +/***/ }), +/* 213 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Contains = __webpack_require__(214); +var GetPoints = __webpack_require__(442); +var GEOM_CONST = __webpack_require__(52); + +/** + * @classdesc + * A Polygon object + * + * The polygon is a closed shape consists of a series of connected straight lines defined by list of ordered points. + * Several formats are supported to define the list of points, check the setTo method for details. + * This is a geometry object allowing you to define and inspect the shape. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render a Polygon you should look at the capabilities of the Graphics class. + * + * @class Polygon + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Geom.Point[]} [points] - List of points defining the perimeter of this Polygon. Several formats are supported: + * - A string containing paired x y values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + */ +var Polygon = new Class({ + + initialize: + + function Polygon (points) + { + /** + * The geometry constant type of this object: `GEOM_CONST.POLYGON`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Polygon#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.POLYGON; + + /** + * The area of this Polygon. + * + * @name Phaser.Geom.Polygon#area + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.area = 0; + + /** + * An array of number pair objects that make up this polygon. I.e. [ {x,y}, {x,y}, {x,y} ] + * + * @name Phaser.Geom.Polygon#points + * @type {Phaser.Geom.Point[]} + * @since 3.0.0 + */ + this.points = []; + + if (points) + { + this.setTo(points); + } + }, + + /** + * Check to see if the Polygon contains the given x / y coordinates. + * + * @method Phaser.Geom.Polygon#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check within the polygon. + * @param {number} y - The y coordinate to check within the polygon. + * + * @return {boolean} `true` if the coordinates are within the polygon, otherwise `false`. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Geom.Polygon#setTo + * @since 3.0.0 + * + * @param {array} points - Points defining the perimeter of this polygon. Please check function description above for the different supported formats. + * + * @return {Phaser.Geom.Polygon} This Polygon object. + */ + setTo: function (points) + { + this.area = 0; + this.points = []; + + if (typeof points === 'string') + { + points = points.split(' '); + } + + if (!Array.isArray(points)) + { + return this; + } + + var p; + var y0 = Number.MAX_VALUE; + + // The points argument is an array, so iterate through it + for (var i = 0; i < points.length; i++) + { + p = { x: 0, y: 0 }; + + if (typeof points[i] === 'number' || typeof points[i] === 'string') + { + p.x = parseFloat(points[i]); + p.y = parseFloat(points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + // An array of arrays? + p.x = points[i][0]; + p.y = points[i][1]; + } + else + { + p.x = points[i].x; + p.y = points[i].y; + } + + this.points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + + return this; + }, + + /** + * Calculates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Geom.Polygon#calculateArea + * @since 3.0.0 + * + * @return {number} The area of the polygon. + */ + calculateArea: function () + { + if (this.points.length < 3) + { + this.area = 0; + + return this.area; + } + + var sum = 0; + var p1; + var p2; + + for (var i = 0; i < this.points.length - 1; i++) + { + p1 = this.points[i]; + p2 = this.points[i + 1]; + + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + + p1 = this.points[0]; + p2 = this.points[this.points.length - 1]; + + sum += (p1.x - p2.x) * (p2.y + p1.y); + + this.area = -sum * 0.5; + + return this.area; + }, + + /** + * Returns an array of Point 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 perimeter of the Polygon and dividing it by the stepRate. + * @param {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the perimeter of the Polygon. + */ + getPoints: function (quantity, step, output) + { + return GetPoints(this, quantity, step, output); + } + +}); + +module.exports = Polygon; + + +/***/ }), +/* 214 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// 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 + +/** + * Checks if a point is within the bounds of a Polygon. + * + * @function Phaser.Geom.Polygon.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to check against. + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is within the bounds of the Polygon, otherwise `false`. + */ +var Contains = function (polygon, x, y) +{ + var inside = false; + + for (var i = -1, j = polygon.points.length - 1; ++i < polygon.points.length; j = i) + { + var ix = polygon.points[i].x; + var iy = polygon.points[i].y; + + var jx = polygon.points[j].x; + var jy = polygon.points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + return inside; +}; + +module.exports = Contains; + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Mesh = __webpack_require__(139); + +/** + * @classdesc + * A Quad Game Object. + * + * A Quad is a Mesh Game Object pre-configured with two triangles arranged into a rectangle, with a single + * texture spread across them. + * + * You can manipulate the corner points of the quad via the getters and setters such as `topLeftX`, and also + * change their alpha and color values. The quad itself can be moved by adjusting the `x` and `y` properties. + * + * @class Quad + * @extends Phaser.GameObjects.Mesh + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Quad 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 {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Quad = new Class({ + + Extends: Mesh, + + initialize: + + function Quad (scene, x, y, texture, frame) + { + // 0----3 + // |\ B| + // | \ | + // | \ | + // | A \| + // | \ + // 1----2 + + var vertices = [ + 0, 0, // tl + 0, 0, // bl + 0, 0, // br + 0, 0, // tl + 0, 0, // br + 0, 0 // tr + ]; + + var uv = [ + 0, 0, // tl + 0, 1, // bl + 1, 1, // br + 0, 0, // tl + 1, 1, // br + 1, 0 // tr + ]; + + var colors = [ + 0xffffff, // tl + 0xffffff, // bl + 0xffffff, // br + 0xffffff, // tl + 0xffffff, // br + 0xffffff // tr + ]; + + var alphas = [ + 1, // tl + 1, // bl + 1, // br + 1, // tl + 1, // br + 1 // tr + ]; + + Mesh.call(this, scene, x, y, vertices, uv, colors, alphas, texture, frame); + + this.resetPosition(); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * + * @method Phaser.GameObjects.Quad#setFrame + * @since 3.11.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame) + { + this.frame = this.texture.get(frame); + + if (!this.frame.cutWidth || !this.frame.cutHeight) + { + this.renderFlags &= ~8; + } + else + { + this.renderFlags |= 8; + } + + frame = this.frame; + + // TL + this.uv[0] = frame.u0; + this.uv[1] = frame.v0; + + // BL + this.uv[2] = frame.u0; + this.uv[3] = frame.v1; + + // BR + this.uv[4] = frame.u1; + this.uv[5] = frame.v1; + + // TL + this.uv[6] = frame.u0; + this.uv[7] = frame.v0; + + // BR + this.uv[8] = frame.u1; + this.uv[9] = frame.v1; + + // TR + this.uv[10] = frame.u1; + this.uv[11] = frame.v0; + + return this; + }, + + /** + * The top-left x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftX + * @type {number} + * @since 3.0.0 + */ + topLeftX: { + + get: function () + { + return this.x + this.vertices[0]; + }, + + set: function (value) + { + this.vertices[0] = value - this.x; + this.vertices[6] = value - this.x; + } + + }, + + /** + * The top-left y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftY + * @type {number} + * @since 3.0.0 + */ + topLeftY: { + + get: function () + { + return this.y + this.vertices[1]; + }, + + set: function (value) + { + this.vertices[1] = value - this.y; + this.vertices[7] = value - this.y; + } + + }, + + /** + * The top-right x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightX + * @type {number} + * @since 3.0.0 + */ + topRightX: { + + get: function () + { + return this.x + this.vertices[10]; + }, + + set: function (value) + { + this.vertices[10] = value - this.x; + } + + }, + + /** + * The top-right y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightY + * @type {number} + * @since 3.0.0 + */ + topRightY: { + + get: function () + { + return this.y + this.vertices[11]; + }, + + set: function (value) + { + this.vertices[11] = value - this.y; + } + + }, + + /** + * The bottom-left x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftX + * @type {number} + * @since 3.0.0 + */ + bottomLeftX: { + + get: function () + { + return this.x + this.vertices[2]; + }, + + set: function (value) + { + this.vertices[2] = value - this.x; + } + + }, + + /** + * The bottom-left y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftY + * @type {number} + * @since 3.0.0 + */ + bottomLeftY: { + + get: function () + { + return this.y + this.vertices[3]; + }, + + set: function (value) + { + this.vertices[3] = value - this.y; + } + + }, + + /** + * The bottom-right x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightX + * @type {number} + * @since 3.0.0 + */ + bottomRightX: { + + get: function () + { + return this.x + this.vertices[4]; + }, + + set: function (value) + { + this.vertices[4] = value - this.x; + this.vertices[8] = value - this.x; + } + + }, + + /** + * The bottom-right y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightY + * @type {number} + * @since 3.0.0 + */ + bottomRightY: { + + get: function () + { + return this.y + this.vertices[5]; + }, + + set: function (value) + { + this.vertices[5] = value - this.y; + this.vertices[9] = value - this.y; + } + + }, + + /** + * The top-left alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftAlpha + * @type {number} + * @since 3.0.0 + */ + topLeftAlpha: { + + get: function () + { + return this.alphas[0]; + }, + + set: function (value) + { + this.alphas[0] = value; + this.alphas[3] = value; + } + + }, + + /** + * The top-right alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightAlpha + * @type {number} + * @since 3.0.0 + */ + topRightAlpha: { + + get: function () + { + return this.alphas[5]; + }, + + set: function (value) + { + this.alphas[5] = value; + } + + }, + + /** + * The bottom-left alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftAlpha + * @type {number} + * @since 3.0.0 + */ + bottomLeftAlpha: { + + get: function () + { + return this.alphas[1]; + }, + + set: function (value) + { + this.alphas[1] = value; + } + + }, + + /** + * The bottom-right alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightAlpha + * @type {number} + * @since 3.0.0 + */ + bottomRightAlpha: { + + get: function () + { + return this.alphas[2]; + }, + + set: function (value) + { + this.alphas[2] = value; + this.alphas[4] = value; + } + + }, + + /** + * The top-left color value of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftColor + * @type {number} + * @since 3.0.0 + */ + topLeftColor: { + + get: function () + { + return this.colors[0]; + }, + + set: function (value) + { + this.colors[0] = value; + this.colors[3] = value; + } + + }, + + /** + * The top-right color value of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightColor + * @type {number} + * @since 3.0.0 + */ + topRightColor: { + + get: function () + { + return this.colors[5]; + }, + + set: function (value) + { + this.colors[5] = value; + } + + }, + + /** + * The bottom-left color value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftColor + * @type {number} + * @since 3.0.0 + */ + bottomLeftColor: { + + get: function () + { + return this.colors[1]; + }, + + set: function (value) + { + this.colors[1] = value; + } + + }, + + /** + * The bottom-right color value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightColor + * @type {number} + * @since 3.0.0 + */ + bottomRightColor: { + + get: function () + { + return this.colors[2]; + }, + + set: function (value) + { + this.colors[2] = value; + this.colors[4] = value; + } + + }, + + /** + * Sets the top-left vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setTopLeft + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + setTopLeft: function (x, y) + { + this.topLeftX = x; + this.topLeftY = y; + + return this; + }, + + /** + * Sets the top-right vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setTopRight + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + setTopRight: function (x, y) + { + this.topRightX = x; + this.topRightY = y; + + return this; + }, + + /** + * Sets the bottom-left vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setBottomLeft + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + setBottomLeft: function (x, y) + { + this.bottomLeftX = x; + this.bottomLeftY = y; + + return this; + }, + + /** + * Sets the bottom-right vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setBottomRight + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + setBottomRight: function (x, y) + { + this.bottomRightX = x; + this.bottomRightY = y; + + return this; + }, + + /** + * Resets the positions of the four corner vertices of this Quad. + * + * @method Phaser.GameObjects.Quad#resetPosition + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + resetPosition: function () + { + var x = this.x; + var y = this.y; + var halfWidth = Math.floor(this.width / 2); + var halfHeight = Math.floor(this.height / 2); + + this.setTopLeft(x - halfWidth, y - halfHeight); + this.setTopRight(x + halfWidth, y - halfHeight); + this.setBottomLeft(x - halfWidth, y + halfHeight); + this.setBottomRight(x + halfWidth, y + halfHeight); + + return this; + }, + + /** + * Resets the alpha values used by this Quad back to 1. + * + * @method Phaser.GameObjects.Quad#resetAlpha + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + resetAlpha: function () + { + var alphas = this.alphas; + + alphas[0] = 1; + alphas[1] = 1; + alphas[2] = 1; + alphas[3] = 1; + alphas[4] = 1; + alphas[5] = 1; + + return this; + }, + + /** + * Resets the color values used by this Quad back to 0xffffff. + * + * @method Phaser.GameObjects.Quad#resetColors + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + resetColors: function () + { + var colors = this.colors; + + colors[0] = 0xffffff; + colors[1] = 0xffffff; + colors[2] = 0xffffff; + colors[3] = 0xffffff; + colors[4] = 0xffffff; + colors[5] = 0xffffff; + + return this; + }, + + /** + * Resets the position, alpha and color values used by this Quad. + * + * @method Phaser.GameObjects.Quad#reset + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Quad} This Game Object. + */ + reset: function () + { + this.resetPosition(); + + this.resetAlpha(); + + return this.resetColors(); + } + +}); + +module.exports = Quad; + + +/***/ }), +/* 216 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var GetFastValue = __webpack_require__(1); +var Extend = __webpack_require__(17); +var SetValue = __webpack_require__(450); +var ShaderRender = __webpack_require__(1105); +var TransformMatrix = __webpack_require__(35); + +/** + * @classdesc + * A Shader Game Object. + * + * This Game Object allows you to easily add a quad with its own shader into the display list, and manipulate it + * as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders + * can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other + * Game Object. They can also be made interactive and used for input events. + * + * It works by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can + * be created dynamically at runtime, or loaded in via the GLSL File Loader: + * + * ```javascript + * function preload () + * { + * this.load.glsl('fire', 'shaders/fire.glsl.js'); + * } + * + * function create () + * { + * this.add.shader('fire', 400, 300, 512, 512); + * } + * ``` + * + * Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. + * + * Due to the way in which they work, you cannot directly change the alpha or blend mode of a Shader. This should + * be handled via exposed uniforms in the shader code itself. + * + * By default a Shader will be created with a standard set of uniforms. These were added to match those + * found on sites such as ShaderToy or GLSLSandbox, and provide common functionality a shader may need, + * such as the timestamp, resolution or pointer position. You can replace them by specifying your own uniforms + * in the Base Shader. + * + * These Shaders work by halting the current pipeline during rendering, creating a viewport matched to the + * size of this Game Object and then renders a quad using the bound shader. At the end, the pipeline is restored. + * + * Because it blocks the pipeline it means it will interrupt any batching that is currently going on, so you should + * use these Game Objects sparingly. If you need to have a fully batched custom shader, then please look at using + * a custom pipeline instead. However, for background or special masking effects, they are extremely effective. + * + * @class Shader + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.17.0 + * + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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 {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the Game Object. + * @param {number} [height=128] - The height of the Game Object. + * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param {any} [textureData] - Additional texture data if you want to create shader with none NPOT textures. + */ +var Shader = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.ComputedSize, + Components.Depth, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.ScrollFactor, + Components.Transform, + Components.Visible, + ShaderRender + ], + + initialize: + + function Shader (scene, key, x, y, width, height, textures, textureData) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + + GameObject.call(this, scene, 'Shader'); + + /** + * This Game Object cannot have a blend mode, so skip all checks. + * + * @name Phaser.GameObjects.Shader#blendMode + * @type {integer} + * @private + * @since 3.17.0 + */ + this.blendMode = -1; + + /** + * The underlying shader object being used. + * Empty by default and set during a call to the `setShader` method. + * + * @name Phaser.GameObjects.Shader#shader + * @type {Phaser.Display.BaseShader} + * @since 3.17.0 + */ + this.shader; + + var renderer = scene.sys.renderer; + + /** + * A reference to the current renderer. + * Shaders only work with the WebGL Renderer. + * + * @name Phaser.GameObjects.Shader#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.17.0 + */ + this.renderer = renderer; + + /** + * The WebGL context belonging to the renderer. + * + * @name Phaser.GameObjects.Shader#gl + * @type {WebGLRenderingContext} + * @since 3.17.0 + */ + this.gl = renderer.gl; + + /** + * Raw byte buffer of vertices this Shader uses. + * + * @name Phaser.GameObjects.Shader#vertexData + * @type {ArrayBuffer} + * @since 3.17.0 + */ + this.vertexData = new ArrayBuffer(6 * (Float32Array.BYTES_PER_ELEMENT * 2)); + + /** + * The WebGL vertex buffer object this shader uses. + * + * @name Phaser.GameObjects.Shader#vertexBuffer + * @type {WebGLBuffer} + * @since 3.17.0 + */ + this.vertexBuffer = renderer.createVertexBuffer(this.vertexData.byteLength, this.gl.STREAM_DRAW); + + /** + * The WebGL shader program this shader uses. + * + * @name Phaser.GameObjects.Shader#program + * @type {WebGLProgram} + * @since 3.17.0 + */ + this.program = null; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources to the GPU. + * + * @name Phaser.GameObjects.Shader#bytes + * @type {Uint8Array} + * @since 3.17.0 + */ + this.bytes = new Uint8Array(this.vertexData); + + /** + * Float32 view of the array buffer containing the shaders vertices. + * + * @name Phaser.GameObjects.Shader#vertexViewF32 + * @type {Float32Array} + * @since 3.17.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Shader#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Shader#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Shader#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * The view matrix the shader uses during rendering. + * + * @name Phaser.GameObjects.Shader#viewMatrix + * @type {Float32Array} + * @readonly + * @since 3.17.0 + */ + this.viewMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); + + /** + * The projection matrix the shader uses during rendering. + * + * @name Phaser.GameObjects.Shader#projectionMatrix + * @type {Float32Array} + * @readonly + * @since 3.17.0 + */ + this.projectionMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); + + /** + * The default uniform mappings. These can be added to (or replaced) by specifying your own uniforms when + * creating this shader game object. The uniforms are updated automatically during the render step. + * + * The defaults are: + * + * `resolution` (2f) - Set to the size of this shader. + * `time` (1f) - The elapsed game time, in seconds. + * `mouse` (2f) - If a pointer has been bound (with `setPointer`), this uniform contains its position each frame. + * `date` (4fv) - A vec4 containing the year, month, day and time in seconds. + * `sampleRate` (1f) - Sound sample rate. 44100 by default. + * `iChannel0...3` (sampler2D) - Input channels 0 to 3. `null` by default. + * + * @name Phaser.GameObjects.Shader#uniforms + * @type {any} + * @since 3.17.0 + */ + this.uniforms = {}; + + /** + * The pointer bound to this shader, if any. + * Set via the chainable `setPointer` method, or by modifying this property directly. + * + * @name Phaser.GameObjects.Shader#pointer + * @type {Phaser.Input.Pointer} + * @since 3.17.0 + */ + this.pointer = null; + + /** + * The cached width of the renderer. + * + * @name Phaser.GameObjects.Shader#_rendererWidth + * @type {number} + * @private + * @since 3.17.0 + */ + this._rendererWidth = renderer.width; + + /** + * The cached height of the renderer. + * + * @name Phaser.GameObjects.Shader#_rendererHeight + * @type {number} + * @private + * @since 3.17.0 + */ + this._rendererHeight = renderer.height; + + /** + * Internal texture count tracker. + * + * @name Phaser.GameObjects.Shader#_textureCount + * @type {number} + * @private + * @since 3.17.0 + */ + this._textureCount = 0; + + /** + * A reference to the GL Frame Buffer this Shader is drawing to. + * This property is only set if you have called `Shader.setRenderToTexture`. + * + * @name Phaser.GameObjects.Shader#framebuffer + * @type {?WebGLFramebuffer} + * @since 3.19.0 + */ + this.framebuffer = null; + + /** + * A reference to the WebGLTexture this Shader is rendering to. + * This property is only set if you have called `Shader.setRenderToTexture`. + * + * @name Phaser.GameObjects.Shader#glTexture + * @type {?WebGLTexture} + * @since 3.19.0 + */ + this.glTexture = null; + + /** + * A flag that indicates if this Shader has been set to render to a texture instead of the display list. + * + * This property is `true` if you have called `Shader.setRenderToTexture`, otherwise it's `false`. + * + * A Shader that is rendering to a texture _does not_ appear on the display list. + * + * @name Phaser.GameObjects.Shader#renderToTexture + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this.renderToTexture = false; + + /** + * A reference to the Phaser.Textures.Texture that has been stored in the Texture Manager for this Shader. + * + * This property is only set if you have called `Shader.setRenderToTexture`, otherwise it is `null`. + * + * @name Phaser.GameObjects.Shader#texture + * @type {Phaser.Textures.Texture} + * @since 3.19.0 + */ + this.texture = null; + + this.setPosition(x, y); + this.setSize(width, height); + this.setOrigin(0.5, 0.5); + this.setShader(key, textures, textureData); + }, + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * Also checks the Game Object against the given Cameras exclusion list. + * + * @method Phaser.GameObjects.Shader#willRender + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object. + * + * @return {boolean} True if the Game Object should be rendered, otherwise false. + */ + willRender: function (camera) + { + if (this.renderToTexture) + { + return true; + } + else + { + return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id))); + } + }, + + /** + * Changes this Shader so instead of rendering to the display list it renders to a + * WebGL Framebuffer and WebGL Texture instead. This allows you to use the output + * of this shader as an input for another shader, by mapping a sampler2D uniform + * to it. + * + * After calling this method the `Shader.framebuffer` and `Shader.glTexture` properties + * are populated. + * + * Additionally, you can provide a key to this method. Doing so will create a Phaser Texture + * from this Shader and save it into the Texture Manager, allowing you to then use it for + * any texture-based Game Object, such as a Sprite or Image: + * + * ```javascript + * var shader = this.add.shader('myShader', x, y, width, height); + * + * shader.setRenderToTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Note that it stores an active reference to this Shader. That means as this shader updates, + * so does the texture and any object using it to render with. Also, if you destroy this + * shader, be sure to clear any objects that may have been using it as a texture too. + * + * You can access the Phaser Texture that is created via the `Shader.texture` property. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame from a Render Texture. + * + * @method Phaser.GameObjects.Shader#setRenderToTexture + * @since 3.19.0 + * + * @param {string} [key] - The unique key to store the texture as within the global Texture Manager. + * @param {boolean} [flipY=false] - Does this texture need vertically flipping before rendering? This should usually be set to `true` if being fed from a buffer. + * + * @return {this} This Shader instance. + */ + setRenderToTexture: function (key, flipY) + { + if (flipY === undefined) { flipY = false; } + + if (!this.renderToTexture) + { + var width = this.width; + var height = this.height; + var renderer = this.renderer; + + this.glTexture = renderer.createTextureFromSource(null, width, height, 0); + + this.glTexture.flipY = flipY; + + this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false); + + this._rendererWidth = width; + this._rendererHeight = height; + + this.renderToTexture = true; + + this.projOrtho(0, this.width, this.height, 0); + + if (key) + { + this.texture = this.scene.sys.textures.addGLTexture(key, this.glTexture, width, height); + } + } + + // And now render at least once, so our texture isn't blank on the first update + + if (this.shader) + { + var pipeline = renderer.currentPipeline; + + renderer.clearPipeline(); + + this.load(); + this.flush(); + + renderer.rebindPipeline(pipeline); + } + + return this; + }, + + /** + * Sets the fragment and, optionally, the vertex shader source code that this Shader will use. + * This will immediately delete the active shader program, if set, and then create a new one + * with the given source. Finally, the shader uniforms are initialized. + * + * @method Phaser.GameObjects.Shader#setShader + * @since 3.17.0 + * + * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. + * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setShader: function (key, textures, textureData) + { + if (textures === undefined) { textures = []; } + + if (typeof key === 'string') + { + var cache = this.scene.sys.cache.shader; + + if (!cache.has(key)) + { + console.warn('Shader missing: ' + key); + return this; + } + + this.shader = cache.get(key); + } + else + { + this.shader = key; + } + + var gl = this.gl; + var renderer = this.renderer; + + if (this.program) + { + gl.deleteProgram(this.program); + } + + var program = renderer.createProgram(this.shader.vertexSrc, this.shader.fragmentSrc); + + // The default uniforms available within the vertex shader + renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); + renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + renderer.setFloat2(program, 'uResolution', this.width, this.height); + + this.program = program; + + var d = new Date(); + + // The default uniforms available within the fragment shader + var defaultUniforms = { + resolution: { type: '2f', value: { x: this.width, y: this.height } }, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: this.width / 2, y: this.height / 2 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() * 60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + }; + + if (this.shader.uniforms) + { + this.uniforms = Extend(true, {}, this.shader.uniforms, defaultUniforms); + } + else + { + this.uniforms = defaultUniforms; + } + + for (var i = 0; i < 4; i++) + { + if (textures[i]) + { + this.setSampler2D('iChannel' + i, textures[i], i, textureData); + } + } + + this.initUniforms(); + + this.projOrtho(0, this._rendererWidth, this._rendererHeight, 0); + + return this; + }, + + /** + * Binds a Phaser Pointer object to this Shader. + * + * The screen position of the pointer will be set in to the shaders `mouse` uniform + * automatically every frame. Call this method with no arguments to unbind the pointer. + * + * @method Phaser.GameObjects.Shader#setPointer + * @since 3.17.0 + * + * @param {Phaser.Input.Pointer} [pointer] - The Pointer to bind to this shader. + * + * @return {this} This Shader instance. + */ + setPointer: function (pointer) + { + this.pointer = pointer; + + return this; + }, + + /** + * Sets this shader to use an orthographic projection matrix. + * This matrix is stored locally in the `projectionMatrix` property, + * as well as being bound to the `uProjectionMatrix` uniform. + * + * @method Phaser.GameObjects.Shader#projOrtho + * @since 3.17.0 + * + * @param {number} left - The left value. + * @param {number} right - The right value. + * @param {number} bottom - The bottom value. + * @param {number} top - The top value. + */ + projOrtho: function (left, right, bottom, top) + { + var near = -1000; + var far = 1000; + + var leftRight = 1 / (left - right); + var bottomTop = 1 / (bottom - top); + var nearFar = 1 / (near - far); + + var pm = this.projectionMatrix; + + pm[0] = -2 * leftRight; + pm[5] = -2 * bottomTop; + pm[10] = 2 * nearFar; + pm[12] = (left + right) * leftRight; + pm[13] = (top + bottom) * bottomTop; + pm[14] = (far + near) * nearFar; + + var program = this.program; + + this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + + this._rendererWidth = right; + this._rendererHeight = bottom; + }, + + // Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ + // http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf + + /** + * Initializes all of the uniforms this shader uses. + * + * @method Phaser.GameObjects.Shader#initUniforms + * @private + * @since 3.17.0 + */ + initUniforms: function () + { + var gl = this.gl; + var map = this.renderer.glFuncMap; + var program = this.program; + + this._textureCount = 0; + + for (var key in this.uniforms) + { + var uniform = this.uniforms[key]; + + var type = uniform.type; + var data = map[type]; + + uniform.uniformLocation = gl.getUniformLocation(program, key); + + if (type !== 'sampler2D') + { + uniform.glMatrix = data.matrix; + uniform.glValueLength = data.length; + uniform.glFunc = data.func; + } + } + }, + + /** + * Sets a sampler2D uniform on this shader where the source texture is a WebGLTexture. + * + * This allows you to feed the output from one Shader into another: + * + * ```javascript + * let shader1 = this.add.shader(baseShader1, 0, 0, 512, 512).setRenderToTexture(); + * let shader2 = this.add.shader(baseShader2, 0, 0, 512, 512).setRenderToTexture('output'); + * + * shader1.setSampler2DBuffer('iChannel0', shader2.glTexture, 512, 512); + * shader2.setSampler2DBuffer('iChannel0', shader1.glTexture, 512, 512); + * ``` + * + * In the above code, the result of baseShader1 is fed into Shader2 as the `iChannel0` sampler2D uniform. + * The result of baseShader2 is then fed back into shader1 again, creating a feedback loop. + * + * If you wish to use an image from the Texture Manager as a sampler2D input for this shader, + * see the `Shader.setSampler2D` method. + * + * @method Phaser.GameObjects.Shader#setSampler2DBuffer + * @since 3.19.0 + * + * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`. + * @param {WebGLTexture} texture - A WebGLTexture reference. + * @param {integer} width - The width of the texture. + * @param {integer} height - The height of the texture. + * @param {integer} [textureIndex=0] - The texture index. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setSampler2DBuffer: function (uniformKey, texture, width, height, textureIndex, textureData) + { + if (textureIndex === undefined) { textureIndex = 0; } + if (textureData === undefined) { textureData = {}; } + + var uniform = this.uniforms[uniformKey]; + + uniform.value = texture; + + textureData.width = width; + textureData.height = height; + + uniform.textureData = textureData; + + this._textureCount = textureIndex; + + this.initSampler2D(uniform); + + return this; + }, + + /** + * Sets a sampler2D uniform on this shader. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * If you wish to use another Shader as a sampler2D input for this shader, see the `Shader.setSampler2DBuffer` method. + * + * @method Phaser.GameObjects.Shader#setSampler2D + * @since 3.17.0 + * + * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`. + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {integer} [textureIndex=0] - The texture index. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setSampler2D: function (uniformKey, textureKey, textureIndex, textureData) + { + if (textureIndex === undefined) { textureIndex = 0; } + + var textureManager = this.scene.sys.textures; + + if (textureManager.exists(textureKey)) + { + var frame = textureManager.getFrame(textureKey); + var uniform = this.uniforms[uniformKey]; + var source = frame.source; + + uniform.textureKey = textureKey; + uniform.source = source.image; + uniform.value = frame.glTexture; + + if (source.isGLTexture) + { + if (!textureData) + { + textureData = {}; + } + + textureData.width = source.width; + textureData.height = source.height; + } + + if (textureData) + { + uniform.textureData = textureData; + } + + this._textureCount = textureIndex; + + this.initSampler2D(uniform); + } + + return this; + }, + + /** + * Sets a property of a uniform already present on this shader. + * + * To modify the value of a uniform such as a 1f or 1i use the `value` property directly: + * + * ```javascript + * shader.setUniform('size.value', 16); + * ``` + * + * You can use dot notation to access deeper values, for example: + * + * ```javascript + * shader.setUniform('resolution.value.x', 512); + * ``` + * + * The change to the uniform will take effect the next time the shader is rendered. + * + * @method Phaser.GameObjects.Shader#setUniform + * @since 3.17.0 + * + * @param {string} key - The key of the uniform to modify. Use dots for deep properties, i.e. `resolution.value.x`. + * @param {any} value - The value to set into the uniform. + * + * @return {this} This Shader instance. + */ + setUniform: function (key, value) + { + SetValue(this.uniforms, key, value); + + return this; + }, + + /** + * Returns the uniform object for the given key, or `null` if the uniform couldn't be found. + * + * @method Phaser.GameObjects.Shader#getUniform + * @since 3.17.0 + * + * @param {string} key - The key of the uniform to return the value for. + * + * @return {any} A reference to the uniform object. This is not a copy, so modifying it will update the original object also. + */ + getUniform: function (key) + { + return GetFastValue(this.uniforms, key, null); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel0` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel0 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel0: function (textureKey, textureData) + { + return this.setSampler2D('iChannel0', textureKey, 0, textureData); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel1` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel1 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel1: function (textureKey, textureData) + { + return this.setSampler2D('iChannel1', textureKey, 1, textureData); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel2` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel2 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel2: function (textureKey, textureData) + { + return this.setSampler2D('iChannel2', textureKey, 2, textureData); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel3` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel3 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel3: function (textureKey, textureData) + { + return this.setSampler2D('iChannel3', textureKey, 3, textureData); + }, + + /** + * Internal method that takes a sampler2D uniform and prepares it for use by setting the + * gl texture parameters. + * + * @method Phaser.GameObjects.Shader#initSampler2D + * @private + * @since 3.17.0 + * + * @param {any} uniform - The sampler2D uniform to process. + */ + initSampler2D: function (uniform) + { + if (!uniform.value) + { + return; + } + + var gl = this.gl; + + gl.activeTexture(gl.TEXTURE0 + this._textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value); + + // Extended texture data + + var data = uniform.textureData; + + if (data) + { + // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D + + // mag / minFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + // format can be: gl.LUMINANCE or gl.RGBA + + var magFilter = gl[GetFastValue(data, 'magFilter', 'linear').toUpperCase()]; + var minFilter = gl[GetFastValue(data, 'minFilter', 'linear').toUpperCase()]; + var wrapS = gl[GetFastValue(data, 'wrapS', 'repeat').toUpperCase()]; + var wrapT = gl[GetFastValue(data, 'wrapT', 'repeat').toUpperCase()]; + var format = gl[GetFastValue(data, 'format', 'rgba').toUpperCase()]; + + if (data.repeat) + { + wrapS = gl.REPEAT; + wrapT = gl.REPEAT; + } + + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); + + if (data.width) + { + var width = GetFastValue(data, 'width', 512); + var height = GetFastValue(data, 'height', 2); + var border = GetFastValue(data, 'border', 0); + + // texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels) + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels) + gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.source); + } + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); + } + + this.renderer.setProgram(this.program); + + gl.uniform1i(uniform.uniformLocation, this._textureCount); + + this._textureCount++; + }, + + /** + * Synchronizes all of the uniforms this shader uses. + * Each uniforms gl function is called in turn. + * + * @method Phaser.GameObjects.Shader#syncUniforms + * @private + * @since 3.17.0 + */ + syncUniforms: function () + { + var gl = this.gl; + + var uniforms = this.uniforms; + var uniform; + var length; + var glFunc; + var location; + var value; + var textureCount = 0; + + for (var key in uniforms) + { + uniform = uniforms[key]; + + glFunc = uniform.glFunc; + length = uniform.glValueLength; + location = uniform.uniformLocation; + value = uniform.value; + + if (value === null) + { + continue; + } + + if (length === 1) + { + if (uniform.glMatrix) + { + glFunc.call(gl, location, uniform.transpose, value); + } + else + { + glFunc.call(gl, location, value); + } + } + else if (length === 2) + { + glFunc.call(gl, location, value.x, value.y); + } + else if (length === 3) + { + glFunc.call(gl, location, value.x, value.y, value.z); + } + else if (length === 4) + { + glFunc.call(gl, location, value.x, value.y, value.z, value.w); + } + else if (uniform.type === 'sampler2D') + { + gl.activeTexture(gl['TEXTURE' + textureCount]); + + gl.bindTexture(gl.TEXTURE_2D, value); + + gl.uniform1i(location, textureCount); + + textureCount++; + } + } + }, + + /** + * Called automatically during render. + * + * This method performs matrix ITRS and then stores the resulting value in the `uViewMatrix` uniform. + * It then sets up the vertex buffer and shader, updates and syncs the uniforms ready + * for flush to be called. + * + * @method Phaser.GameObjects.Shader#load + * @since 3.17.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} [matrix2D] - The transform matrix to use during rendering. + */ + load: function (matrix2D) + { + // ITRS + + var gl = this.gl; + var width = this.width; + var height = this.height; + var renderer = this.renderer; + var program = this.program; + var vm = this.viewMatrix; + + if (!this.renderToTexture) + { + var x = -this._displayOriginX; + var y = -this._displayOriginY; + + vm[0] = matrix2D[0]; + vm[1] = matrix2D[1]; + vm[4] = matrix2D[2]; + vm[5] = matrix2D[3]; + vm[8] = matrix2D[4]; + vm[9] = matrix2D[5]; + vm[12] = vm[0] * x + vm[4] * y; + vm[13] = vm[1] * x + vm[5] * y; + } + + // Update vertex shader uniforms + + gl.useProgram(program); + + gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uViewMatrix'), false, vm); + gl.uniform2f(gl.getUniformLocation(program, 'uResolution'), this.width, this.height); + + // Update fragment shader uniforms + + var uniforms = this.uniforms; + var res = uniforms.resolution; + + res.value.x = width; + res.value.y = height; + + uniforms.time.value = renderer.game.loop.getDuration(); + + var pointer = this.pointer; + + if (pointer) + { + var mouse = uniforms.mouse; + + var px = pointer.x / width; + var py = 1 - pointer.y / height; + + mouse.value.x = px.toFixed(2); + mouse.value.y = py.toFixed(2); + } + + this.syncUniforms(); + }, + + /** + * Called automatically during render. + * + * Sets the active shader, loads the vertex buffer and then draws. + * + * @method Phaser.GameObjects.Shader#flush + * @since 3.17.0 + */ + flush: function () + { + // Bind + + var width = this.width; + var height = this.height; + var program = this.program; + + var gl = this.gl; + var vertexBuffer = this.vertexBuffer; + var renderer = this.renderer; + var vertexSize = Float32Array.BYTES_PER_ELEMENT * 2; + + if (this.renderToTexture) + { + renderer.setFramebuffer(this.framebuffer); + + gl.clearColor(0, 0, 0, 0); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); + + var location = gl.getAttribLocation(program, 'inPosition'); + + if (location !== -1) + { + gl.enableVertexAttribArray(location); + + gl.vertexAttribPointer(location, 2, gl.FLOAT, false, vertexSize, 0); + } + + // Draw + + var vf = this.vertexViewF32; + + vf[3] = height; + vf[4] = width; + vf[5] = height; + vf[8] = width; + vf[9] = height; + vf[10] = width; + + // Flush + + var vertexCount = 6; + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + + gl.drawArrays(gl.TRIANGLES, 0, vertexCount); + + if (this.renderToTexture) + { + renderer.setFramebuffer(null, false); + } + }, + + /** + * A NOOP method so you can pass a Shader to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Shader#setAlpha + * @private + * @since 3.17.0 + */ + setAlpha: function () + { + }, + + /** + * A NOOP method so you can pass a Shader to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Shader#setBlendMode + * @private + * @since 3.17.0 + */ + setBlendMode: function () + { + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Shader#preDestroy + * @protected + * @since 3.17.0 + */ + preDestroy: function () + { + var gl = this.gl; + + gl.deleteProgram(this.program); + gl.deleteBuffer(this.vertexBuffer); + + if (this.renderToTexture) + { + this.renderer.deleteFramebuffer(this.framebuffer); + + this.texture.destroy(); + + this.framebuffer = null; + this.glTexture = null; + this.texture = null; + } + } + +}); + +module.exports = Shader; + + +/***/ }), +/* 217 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DistanceBetween = __webpack_require__(54); + +/** + * Checks if two Circles intersect. + * + * @function Phaser.Geom.Intersects.CircleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circleA - The first Circle to check for intersection. + * @param {Phaser.Geom.Circle} circleB - The second Circle to check for intersection. + * + * @return {boolean} `true` if the two Circles intersect, otherwise `false`. + */ +var CircleToCircle = function (circleA, circleB) +{ + return (DistanceBetween(circleA.x, circleA.y, circleB.x, circleB.y) <= (circleA.radius + circleB.radius)); +}; + +module.exports = CircleToCircle; + + +/***/ }), +/* 218 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks for intersection between a circle and a rectangle. + * + * @function Phaser.Geom.Intersects.CircleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to be checked. + * @param {Phaser.Geom.Rectangle} rect - The rectangle to be checked. + * + * @return {boolean} `true` if the two objects intersect, otherwise `false`. + */ +var CircleToRectangle = function (circle, rect) +{ + var halfWidth = rect.width / 2; + var halfHeight = rect.height / 2; + + var cx = Math.abs(circle.x - rect.x - halfWidth); + var cy = Math.abs(circle.y - rect.y - halfHeight); + var xDist = halfWidth + circle.radius; + var yDist = halfHeight + circle.radius; + + if (cx > xDist || cy > yDist) + { + return false; + } + else if (cx <= halfWidth || cy <= halfHeight) + { + return true; + } + else + { + var xCornerDist = cx - halfWidth; + var yCornerDist = cy - halfHeight; + var xCornerDistSq = xCornerDist * xCornerDist; + var yCornerDistSq = yCornerDist * yCornerDist; + var maxCornerDistSq = circle.radius * circle.radius; + + return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq); + } +}; + +module.exports = CircleToRectangle; + + +/***/ }), +/* 219 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var LineToCircle = __webpack_require__(220); + +/** + * Checks for intersection between the line segment and circle, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetLineToCircle + * @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 {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetLineToCircle = function (line, circle, out) +{ + if (out === undefined) { out = []; } + + if (LineToCircle(line, circle)) + { + var lx1 = line.x1; + var ly1 = line.y1; + + var lx2 = line.x2; + var ly2 = line.y2; + + var cx = circle.x; + var cy = circle.y; + var cr = circle.radius; + + var lDirX = lx2 - lx1; + var lDirY = ly2 - ly1; + var oDirX = lx1 - cx; + var oDirY = ly1 - cy; + + var coefficientA = lDirX * lDirX + lDirY * lDirY; + var coefficientB = 2 * (lDirX * oDirX + lDirY * oDirY); + var coefficientC = oDirX * oDirX + oDirY * oDirY - cr * cr; + + var lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); + + var x, y; + + if (lambda === 0) + { + var root = -coefficientB / (2 * coefficientA); + x = lx1 + root * lDirX; + y = ly1 + root * lDirY; + if (root >= 0 && root <= 1) + { + out.push(new Point(x, y)); + } + } + else if (lambda > 0) + { + var root1 = (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA); + x = lx1 + root1 * lDirX; + y = ly1 + root1 * lDirY; + if (root1 >= 0 && root1 <= 1) + { + out.push(new Point(x, y)); + } + + var root2 = (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA); + x = lx1 + root2 * lDirX; + y = ly1 + root2 * lDirY; + if (root2 >= 0 && root2 <= 1) + { + out.push(new Point(x, y)); + } + } + } + + return out; +}; + +module.exports = GetLineToCircle; + + +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(60); +var Point = __webpack_require__(4); + +var tmp = new Point(); + +/** + * 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.Geom.Point|any)} [nearest] - An optional Point-like 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`. + */ +var LineToCircle = function (line, circle, nearest) +{ + if (nearest === undefined) { nearest = tmp; } + + if (Contains(circle, line.x1, line.y1)) + { + nearest.x = line.x1; + nearest.y = line.y1; + + return true; + } + + if (Contains(circle, line.x2, line.y2)) + { + nearest.x = line.x2; + nearest.y = line.y2; + + return true; + } + + var dx = line.x2 - line.x1; + var dy = line.y2 - line.y1; + + var lcx = circle.x - line.x1; + var lcy = circle.y - line.y1; + + // project lc onto d, resulting in vector p + var dLen2 = (dx * dx) + (dy * dy); + var px = dx; + var py = dy; + + if (dLen2 > 0) + { + var dp = ((lcx * dx) + (lcy * dy)) / dLen2; + + px *= dp; + py *= dp; + } + + nearest.x = line.x1 + px; + nearest.y = line.y1 + py; + + // len2 of p + var pLen2 = (px * px) + (py * py); + + return ( + pLen2 <= dLen2 && + ((px * dx) + (py * dy)) >= 0 && + Contains(circle, nearest.x, nearest.y) + ); +}; + +module.exports = LineToCircle; + + +/***/ }), +/* 221 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var LineToLine = __webpack_require__(93); +var LineToRectangle = __webpack_require__(455); + +/** + * Checks for intersection between the Line and a Rectangle shape, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetLineToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The Line to check for intersection. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetLineToRectangle = function (line, rect, out) +{ + if (out === undefined) { out = []; } + + if (LineToRectangle(line, rect)) + { + var lineA = rect.getLineA(); + var lineB = rect.getLineB(); + var lineC = rect.getLineC(); + var lineD = rect.getLineD(); + + var output = [ new Point(), new Point(), new Point(), new Point() ]; + + var result = [ + LineToLine(lineA, line, output[0]), + LineToLine(lineB, line, output[1]), + LineToLine(lineC, line, output[2]), + LineToLine(lineD, line, output[3]) + ]; + + for (var i = 0; i < 4; i++) + { + if (result[i]) { out.push(output[i]); } + } + } + + return out; +}; + +module.exports = GetLineToRectangle; + + +/***/ }), +/* 222 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// http://www.blackpawn.com/texts/pointinpoly/ + +// points is an array of Point-like objects with public x/y properties +// returns an array containing all points that are within the triangle, or an empty array if none +// if 'returnFirst' is true it will return after the first point within the triangle is found + +/** + * Filters an array of point-like objects to only those contained within a triangle. + * If `returnFirst` is true, will return an array containing only the first point in the provided array that is within the triangle (or an empty array if there are no such points). + * + * @function Phaser.Geom.Triangle.ContainsArray + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle that the points are being checked in. + * @param {Phaser.Geom.Point[]} points - An array of point-like objects (objects that have an `x` and `y` property) + * @param {boolean} [returnFirst=false] - If `true`, return an array containing only the first point found that is within the triangle. + * @param {array} [out] - If provided, the points that are within the triangle will be appended to this array instead of being added to a new array. If `returnFirst` is true, only the first point found within the triangle will be appended. This array will also be returned by this function. + * + * @return {Phaser.Geom.Point[]} An array containing all the points from `points` that are within the triangle, if an array was provided as `out`, points will be appended to that array and it will also be returned here. + */ +var ContainsArray = function (triangle, points, returnFirst, out) +{ + if (returnFirst === undefined) { returnFirst = false; } + if (out === undefined) { out = []; } + + var v0x = triangle.x3 - triangle.x1; + var v0y = triangle.y3 - triangle.y1; + + var v1x = triangle.x2 - triangle.x1; + var v1y = triangle.y2 - triangle.y1; + + var dot00 = (v0x * v0x) + (v0y * v0y); + var dot01 = (v0x * v1x) + (v0y * v1y); + var dot11 = (v1x * v1x) + (v1y * v1y); + + // Compute barycentric coordinates + var b = ((dot00 * dot11) - (dot01 * dot01)); + var inv = (b === 0) ? 0 : (1 / b); + + var u; + var v; + var v2x; + var v2y; + var dot02; + var dot12; + + var x1 = triangle.x1; + var y1 = triangle.y1; + + for (var i = 0; i < points.length; i++) + { + v2x = points[i].x - x1; + v2y = points[i].y - y1; + + dot02 = (v0x * v2x) + (v0y * v2y); + dot12 = (v1x * v2x) + (v1y * v2y); + + u = ((dot11 * dot02) - (dot01 * dot12)) * inv; + v = ((dot00 * dot12) - (dot01 * dot02)) * inv; + + if (u >= 0 && v >= 0 && (u + v < 1)) + { + out.push({ x: points[i].x, y: points[i].y }); + + if (returnFirst) + { + break; + } + } + } + + return out; +}; + +module.exports = ContainsArray; + + +/***/ }), +/* 223 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a line around the given coordinates by the given angle in radians. + * + * @function Phaser.Geom.Line.RotateAroundXY + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to rotate. + * @param {number} x - The horizontal coordinate to rotate the line around. + * @param {number} y - The vertical coordinate to rotate the line around. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Line} The rotated line. + */ +var RotateAroundXY = function (line, x, y, angle) +{ + var c = Math.cos(angle); + var s = Math.sin(angle); + + var tx = line.x1 - x; + var ty = line.y1 - y; + + line.x1 = tx * c - ty * s + x; + line.y1 = tx * s + ty * c + y; + + tx = line.x2 - x; + ty = line.y2 - y; + + line.x2 = tx * c - ty * s + x; + line.y2 = tx * s + ty * c + y; + + return line; +}; + +module.exports = RotateAroundXY; + + +/***/ }), +/* 224 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the width/height ratio of a rectangle. + * + * @function Phaser.Geom.Rectangle.GetAspectRatio + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle. + * + * @return {number} The width/height ratio of the rectangle. + */ +var GetAspectRatio = function (rect) +{ + return (rect.height === 0) ? NaN : rect.width / rect.height; +}; + +module.exports = GetAspectRatio; + + +/***/ }), +/* 225 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotates an entire Triangle at a given angle about a specific point. + * + * @function Phaser.Geom.Triangle.RotateAroundXY + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. + * @param {number} x - The X coordinate of the point to rotate the Triangle about. + * @param {number} y - The Y coordinate of the point to rotate the Triangle about. + * @param {number} angle - The angle by which to rotate the Triangle, in radians. + * + * @return {Phaser.Geom.Triangle} The rotated Triangle. + */ +var RotateAroundXY = function (triangle, x, y, angle) +{ + var c = Math.cos(angle); + var s = Math.sin(angle); + + var tx = triangle.x1 - x; + var ty = triangle.y1 - y; + + triangle.x1 = tx * c - ty * s + x; + triangle.y1 = tx * s + ty * c + y; + + tx = triangle.x2 - x; + ty = triangle.y2 - y; + + triangle.x2 = tx * c - ty * s + x; + triangle.y2 = tx * s + ty * c + y; + + tx = triangle.x3 - x; + ty = triangle.y3 - y; + + triangle.x3 = tx * c - ty * s + x; + triangle.y3 = tx * s + ty * c + y; + + return triangle; +}; + +module.exports = RotateAroundXY; + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Gamepad.Events + */ + +module.exports = { + + BUTTON_DOWN: __webpack_require__(1226), + BUTTON_UP: __webpack_require__(1227), + CONNECTED: __webpack_require__(1228), + DISCONNECTED: __webpack_require__(1229), + GAMEPAD_BUTTON_DOWN: __webpack_require__(1230), + GAMEPAD_BUTTON_UP: __webpack_require__(1231) + +}; + + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = __webpack_require__(17); +var XHRSettings = __webpack_require__(144); + +/** + * Takes two XHRSettings Objects and creates a new XHRSettings object from them. + * + * The new object is seeded by the values given in the global settings, but any setting in + * the local object overrides the global ones. + * + * @function Phaser.Loader.MergeXHRSettings + * @since 3.0.0 + * + * @param {Phaser.Types.Loader.XHRSettingsObject} global - The global XHRSettings object. + * @param {Phaser.Types.Loader.XHRSettingsObject} local - The local XHRSettings object. + * + * @return {Phaser.Types.Loader.XHRSettingsObject} A newly formed XHRSettings object. + */ +var MergeXHRSettings = function (global, local) +{ + var output = (global === undefined) ? XHRSettings() : Extend({}, global); + + if (local) + { + for (var setting in local) + { + if (local[setting] !== undefined) + { + output[setting] = local[setting]; + } + } + } + + return output; +}; + +module.exports = MergeXHRSettings; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); +var ParseXML = __webpack_require__(388); + +/** + * @classdesc + * A single XML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#xml method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#xml. + * + * @class XMLFile + * @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.XMLFileConfig)} 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 `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var XMLFile = new Class({ + + Extends: File, + + initialize: + + function XMLFile (loader, key, url, xhrSettings) + { + var extension = 'xml'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'xml', + cache: loader.cacheManager.xml, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.XMLFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = ParseXML(this.xhrLoader.responseText); + + if (this.data) + { + this.onProcessComplete(); + } + else + { + console.warn('Invalid XMLFile: ' + this.key); + + this.onProcessError(); + } + } + +}); + +/** + * Adds an XML file, or array of XML 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.xml('wavedata', 'files/AlienWaveData.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. + * + * The key must be a unique String. It is used to add the file to the global XML Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the XML 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 XML Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.xml({ + * key: 'wavedata', + * url: 'files/AlienWaveData.xml' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.XMLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.xml('wavedata', 'files/AlienWaveData.xml'); + * // and later in your game ... + * var data = this.cache.xml.get('wavedata'); + * ``` + * + * 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 XML 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.xml". It will always add `.xml` 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 XML 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#xml + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.XMLFileConfig|Phaser.Types.Loader.FileTypes.XMLFileConfig[])} 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 `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('xml', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new XMLFile(this, key[i])); + } + } + else + { + this.addFile(new XMLFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = XMLFile; + + +/***/ }), +/* 229 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Arcade.Components + */ + +module.exports = { + + Acceleration: __webpack_require__(1287), + Angular: __webpack_require__(1288), + Bounce: __webpack_require__(1289), + Debug: __webpack_require__(1290), + Drag: __webpack_require__(1291), + Enable: __webpack_require__(1292), + Friction: __webpack_require__(1293), + Gravity: __webpack_require__(1294), + Immovable: __webpack_require__(1295), + Mass: __webpack_require__(1296), + Size: __webpack_require__(1297), + Velocity: __webpack_require__(1298) + +}; + + +/***/ }), +/* 230 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Arcade.Events + */ + +module.exports = { + + COLLIDE: __webpack_require__(1300), + OVERLAP: __webpack_require__(1301), + PAUSE: __webpack_require__(1302), + RESUME: __webpack_require__(1303), + TILE_COLLIDE: __webpack_require__(1304), + TILE_OVERLAP: __webpack_require__(1305), + WORLD_BOUNDS: __webpack_require__(1306), + WORLD_STEP: __webpack_require__(1307) + +}; + + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Impact.Events + */ + +module.exports = { + + COLLIDE: __webpack_require__(1319), + PAUSE: __webpack_require__(1320), + RESUME: __webpack_require__(1321) + +}; + + +/***/ }), +/* 232 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Impact.Components + */ + +module.exports = { + + Acceleration: __webpack_require__(1323), + BodyScale: __webpack_require__(1324), + BodyType: __webpack_require__(1325), + Bounce: __webpack_require__(1326), + CheckAgainst: __webpack_require__(1327), + Collides: __webpack_require__(1328), + Debug: __webpack_require__(1329), + Friction: __webpack_require__(1330), + Gravity: __webpack_require__(1331), + Offset: __webpack_require__(1332), + SetGameObject: __webpack_require__(1333), + Velocity: __webpack_require__(1334) + +}; + + +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Composites = {}; + +module.exports = Composites; + +var Composite = __webpack_require__(68); +var Constraint = __webpack_require__(78); +var Common = __webpack_require__(19); +var Body = __webpack_require__(25); +var Bodies = __webpack_require__(42); + +(function() { + + /** + * Create a new composite containing bodies created in the callback in a grid arrangement. + * This function uses the body's bounds to prevent overlaps. + * @method stack + * @param {number} xx + * @param {number} yy + * @param {number} columns + * @param {number} rows + * @param {number} columnGap + * @param {number} rowGap + * @param {function} callback + * @return {composite} A new composite containing objects created in the callback + */ + Composites.stack = function(xx, yy, columns, rows, columnGap, rowGap, callback) { + var stack = Composite.create({ label: 'Stack' }), + x = xx, + y = yy, + lastBody, + i = 0; + + for (var row = 0; row < rows; row++) { + var maxHeight = 0; + + for (var column = 0; column < columns; column++) { + var body = callback(x, y, column, row, lastBody, i); + + if (body) { + var bodyHeight = body.bounds.max.y - body.bounds.min.y, + bodyWidth = body.bounds.max.x - body.bounds.min.x; + + if (bodyHeight > maxHeight) + maxHeight = bodyHeight; + + Body.translate(body, { x: bodyWidth * 0.5, y: bodyHeight * 0.5 }); + + x = body.bounds.max.x + columnGap; + + Composite.addBody(stack, body); + + lastBody = body; + i += 1; + } else { + x += columnGap; + } + } + + y += maxHeight + rowGap; + x = xx; + } + + return stack; + }; + + /** + * Chains all bodies in the given composite together using constraints. + * @method chain + * @param {composite} composite + * @param {number} xOffsetA + * @param {number} yOffsetA + * @param {number} xOffsetB + * @param {number} yOffsetB + * @param {object} options + * @return {composite} A new composite containing objects chained together with constraints + */ + Composites.chain = function(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) { + var bodies = composite.bodies; + + for (var i = 1; i < bodies.length; i++) { + var bodyA = bodies[i - 1], + bodyB = bodies[i], + bodyAHeight = bodyA.bounds.max.y - bodyA.bounds.min.y, + bodyAWidth = bodyA.bounds.max.x - bodyA.bounds.min.x, + bodyBHeight = bodyB.bounds.max.y - bodyB.bounds.min.y, + bodyBWidth = bodyB.bounds.max.x - bodyB.bounds.min.x; + + var defaults = { + bodyA: bodyA, + pointA: { x: bodyAWidth * xOffsetA, y: bodyAHeight * yOffsetA }, + bodyB: bodyB, + pointB: { x: bodyBWidth * xOffsetB, y: bodyBHeight * yOffsetB } + }; + + var constraint = Common.extend(defaults, options); + + Composite.addConstraint(composite, Constraint.create(constraint)); + } + + composite.label += ' Chain'; + + return composite; + }; + + /** + * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. + * @method mesh + * @param {composite} composite + * @param {number} columns + * @param {number} rows + * @param {boolean} crossBrace + * @param {object} options + * @return {composite} The composite containing objects meshed together with constraints + */ + Composites.mesh = function(composite, columns, rows, crossBrace, options) { + var bodies = composite.bodies, + row, + col, + bodyA, + bodyB, + bodyC; + + for (row = 0; row < rows; row++) { + for (col = 1; col < columns; col++) { + bodyA = bodies[(col - 1) + (row * columns)]; + bodyB = bodies[col + (row * columns)]; + Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options))); + } + + if (row > 0) { + for (col = 0; col < columns; col++) { + bodyA = bodies[col + ((row - 1) * columns)]; + bodyB = bodies[col + (row * columns)]; + Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options))); + + if (crossBrace && col > 0) { + bodyC = bodies[(col - 1) + ((row - 1) * columns)]; + Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options))); + } + + if (crossBrace && col < columns - 1) { + bodyC = bodies[(col + 1) + ((row - 1) * columns)]; + Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options))); + } + } + } + } + + composite.label += ' Mesh'; + + return composite; + }; + + /** + * Create a new composite containing bodies created in the callback in a pyramid arrangement. + * This function uses the body's bounds to prevent overlaps. + * @method pyramid + * @param {number} xx + * @param {number} yy + * @param {number} columns + * @param {number} rows + * @param {number} columnGap + * @param {number} rowGap + * @param {function} callback + * @return {composite} A new composite containing objects created in the callback + */ + Composites.pyramid = function(xx, yy, columns, rows, columnGap, rowGap, callback) { + return Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y, column, row, lastBody, i) { + var actualRows = Math.min(rows, Math.ceil(columns / 2)), + lastBodyWidth = lastBody ? lastBody.bounds.max.x - lastBody.bounds.min.x : 0; + + if (row > actualRows) + return; + + // reverse row order + row = actualRows - row; + + var start = row, + end = columns - 1 - row; + + if (column < start || column > end) + return; + + // retroactively fix the first body's position, since width was unknown + if (i === 1) { + Body.translate(lastBody, { x: (column + (columns % 2 === 1 ? 1 : -1)) * lastBodyWidth, y: 0 }); + } + + var xOffset = lastBody ? column * lastBodyWidth : 0; + + return callback(xx + xOffset + column * columnGap, y, column, row, lastBody, i); + }); + }; + + /** + * Creates a composite with a Newton's Cradle setup of bodies and constraints. + * @method newtonsCradle + * @param {number} xx + * @param {number} yy + * @param {number} number + * @param {number} size + * @param {number} length + * @return {composite} A new composite newtonsCradle body + */ + Composites.newtonsCradle = function(xx, yy, number, size, length) { + var newtonsCradle = Composite.create({ label: 'Newtons Cradle' }); + + for (var i = 0; i < number; i++) { + var separation = 1.9, + circle = Bodies.circle(xx + i * (size * separation), yy + length, size, + { inertia: Infinity, restitution: 1, friction: 0, frictionAir: 0.0001, slop: 1 }), + constraint = Constraint.create({ pointA: { x: xx + i * (size * separation), y: yy }, bodyB: circle }); + + Composite.addBody(newtonsCradle, circle); + Composite.addConstraint(newtonsCradle, constraint); + } + + return newtonsCradle; + }; + + /** + * Creates a composite with simple car setup of bodies and constraints. + * @method car + * @param {number} xx + * @param {number} yy + * @param {number} width + * @param {number} height + * @param {number} wheelSize + * @return {composite} A new composite car body + */ + Composites.car = function(xx, yy, width, height, wheelSize) { + var group = Body.nextGroup(true), + wheelBase = 20, + wheelAOffset = -width * 0.5 + wheelBase, + wheelBOffset = width * 0.5 - wheelBase, + wheelYOffset = 0; + + var car = Composite.create({ label: 'Car' }), + body = Bodies.rectangle(xx, yy, width, height, { + collisionFilter: { + group: group + }, + chamfer: { + radius: height * 0.5 + }, + density: 0.0002 + }); + + var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, { + collisionFilter: { + group: group + }, + friction: 0.8 + }); + + var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, { + collisionFilter: { + group: group + }, + friction: 0.8 + }); + + var axelA = Constraint.create({ + bodyB: body, + pointB: { x: wheelAOffset, y: wheelYOffset }, + bodyA: wheelA, + stiffness: 1, + length: 0 + }); + + var axelB = Constraint.create({ + bodyB: body, + pointB: { x: wheelBOffset, y: wheelYOffset }, + bodyA: wheelB, + stiffness: 1, + length: 0 + }); + + Composite.addBody(car, body); + Composite.addBody(car, wheelA); + Composite.addBody(car, wheelB); + Composite.addConstraint(car, axelA); + Composite.addConstraint(car, axelB); + + return car; + }; + + /** + * Creates a simple soft body like object. + * @method softBody + * @param {number} xx + * @param {number} yy + * @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 + */ + Composites.softBody = function(xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) { + particleOptions = Common.extend({ inertia: Infinity }, particleOptions); + constraintOptions = Common.extend({ stiffness: 0.2, render: { type: 'line', anchors: false } }, constraintOptions); + + var softBody = Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y) { + return Bodies.circle(x, y, particleRadius, particleOptions); + }); + + Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions); + + softBody.label = 'Soft Body'; + + return softBody; + }; + +})(); + + +/***/ }), +/* 234 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Svg = {}; + +module.exports = Svg; + +var Bounds = __webpack_require__(38); +var Common = __webpack_require__(19); + +(function() { + + /** + * Converts an SVG path into an array of vector points. + * If the input path forms a concave shape, you must decompose the result into convex parts before use. + * See `Bodies.fromVertices` which provides support for this. + * Note that this function is not guaranteed to support complex paths (such as those with holes). + * You must load the `pathseg.js` polyfill on newer browsers. + * @method pathToVertices + * @param {SVGPathElement} path + * @param {Number} [sampleLength=15] + * @return {Vector[]} points + */ + Svg.pathToVertices = function(path, sampleLength) { + if (typeof window !== 'undefined' && !('SVGPathSeg' in window)) { + Common.warn('Svg.pathToVertices: SVGPathSeg not defined, a polyfill is required.'); + } + + // https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js + var i, il, total, point, segment, segments, + segmentsQueue, lastSegment, + lastPoint, segmentIndex, points = [], + lx, ly, length = 0, x = 0, y = 0; + + sampleLength = sampleLength || 15; + + var addPoint = function(px, py, pathSegType) { + // all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1) + var isRelative = pathSegType % 2 === 1 && pathSegType > 1; + + // when the last point doesn't equal the current point add the current point + if (!lastPoint || px != lastPoint.x || py != lastPoint.y) { + if (lastPoint && isRelative) { + lx = lastPoint.x; + ly = lastPoint.y; + } else { + lx = 0; + ly = 0; + } + + var point = { + x: lx + px, + y: ly + py + }; + + // set last point + if (isRelative || !lastPoint) { + lastPoint = point; + } + + points.push(point); + + x = lx + px; + y = ly + py; + } + }; + + var addSegmentPoint = function(segment) { + var segType = segment.pathSegTypeAsLetter.toUpperCase(); + + // skip path ends + if (segType === 'Z') + return; + + // map segment to x and y + switch (segType) { + + case 'M': + case 'L': + case 'T': + case 'C': + case 'S': + case 'Q': + x = segment.x; + y = segment.y; + break; + case 'H': + x = segment.x; + break; + case 'V': + y = segment.y; + break; + } + + addPoint(x, y, segment.pathSegType); + }; + + // ensure path is absolute + Svg._svgPathToAbsolute(path); + + // get total length + total = path.getTotalLength(); + + // queue segments + segments = []; + for (i = 0; i < path.pathSegList.numberOfItems; i += 1) + segments.push(path.pathSegList.getItem(i)); + + segmentsQueue = segments.concat(); + + // sample through path + while (length < total) { + // get segment at position + segmentIndex = path.getPathSegAtLength(length); + segment = segments[segmentIndex]; + + // new segment + if (segment != lastSegment) { + while (segmentsQueue.length && segmentsQueue[0] != segment) + addSegmentPoint(segmentsQueue.shift()); + + lastSegment = segment; + } + + // add points in between when curving + // TODO: adaptive sampling + switch (segment.pathSegTypeAsLetter.toUpperCase()) { + + case 'C': + case 'T': + case 'S': + case 'Q': + case 'A': + point = path.getPointAtLength(length); + addPoint(point.x, point.y, 0); + break; + + } + + // increment by sample value + length += sampleLength; + } + + // add remaining segments not passed by sampling + for (i = 0, il = segmentsQueue.length; i < il; ++i) + addSegmentPoint(segmentsQueue[i]); + + return points; + }; + + Svg._svgPathToAbsolute = function(path) { + // http://phrogz.net/convert-svg-path-to-all-absolute-commands + // Copyright (c) Gavin Kistner + // http://phrogz.net/js/_ReuseLicense.txt + // Modifications: tidy formatting and naming + var x0, y0, x1, y1, x2, y2, segs = path.pathSegList, + x = 0, y = 0, len = segs.numberOfItems; + + for (var i = 0; i < len; ++i) { + var seg = segs.getItem(i), + segType = seg.pathSegTypeAsLetter; + + if (/[MLHVCSQTA]/.test(segType)) { + if ('x' in seg) x = seg.x; + if ('y' in seg) y = seg.y; + } else { + if ('x1' in seg) x1 = x + seg.x1; + if ('x2' in seg) x2 = x + seg.x2; + if ('y1' in seg) y1 = y + seg.y1; + if ('y2' in seg) y2 = y + seg.y2; + if ('x' in seg) x += seg.x; + if ('y' in seg) y += seg.y; + + switch (segType) { + + case 'm': + segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i); + break; + case 'l': + segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i); + break; + case 'h': + segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i); + break; + case 'v': + segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i); + break; + case 'c': + segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i); + break; + case 's': + segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i); + break; + case 'q': + segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i); + break; + case 't': + segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i); + break; + case 'a': + segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i); + break; + case 'z': + case 'Z': + x = x0; + y = y0; + break; + + } + } + + if (segType == 'M' || segType == 'm') { + x0 = x; + y0 = y; + } + } + }; + +})(); + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Joachim Grill + * @author Richard Davey + * @copyright 2018 CodeAndWeb GmbH + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = __webpack_require__(42); +var Body = __webpack_require__(25); +var Common = __webpack_require__(19); +var GetFastValue = __webpack_require__(1); +var Vertices = __webpack_require__(31); + +/** + * Use PhysicsEditorParser.parseBody() to build a Matter body object, based on a physics data file + * created and exported with PhysicsEditor (https://www.codeandweb.com/physicseditor). + * + * @namespace Phaser.Physics.Matter.PhysicsEditorParser + * @since 3.10.0 + */ +var PhysicsEditorParser = { + + /** + * Parses a body element exported by PhysicsEditor. + * + * @function Phaser.Physics.Matter.PhysicsEditorParser.parseBody + * @since 3.10.0 + * + * @param {number} x - The horizontal world location of the body. + * @param {number} y - The vertical world location of the body. + * @param {object} config - The body configuration and fixture (child body) definitions, as exported by PhysicsEditor. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A compound Matter JS Body. + */ + parseBody: function (x, y, config, options) + { + if (options === undefined) { options = {}; } + + var fixtureConfigs = GetFastValue(config, 'fixtures', []); + var fixtures = []; + + for (var fc = 0; fc < fixtureConfigs.length; fc++) + { + var fixtureParts = this.parseFixture(fixtureConfigs[fc]); + + for (var i = 0; i < fixtureParts.length; i++) + { + fixtures.push(fixtureParts[i]); + } + } + + var matterConfig = Common.clone(config, true); + + Common.extend(matterConfig, options, true); + + delete matterConfig.fixtures; + delete matterConfig.type; + + var body = Body.create(matterConfig); + + Body.setParts(body, fixtures); + + Body.setPosition(body, { x: x, y: y }); + + return body; + }, + + /** + * Parses an element of the "fixtures" list exported by PhysicsEditor + * + * @function Phaser.Physics.Matter.PhysicsEditorParser.parseFixture + * @since 3.10.0 + * + * @param {object} fixtureConfig - The fixture object to parse. + * + * @return {MatterJS.BodyType[]} - An array of Matter JS Bodies. + */ + parseFixture: function (fixtureConfig) + { + var matterConfig = Common.extend({}, false, fixtureConfig); + + delete matterConfig.circle; + delete matterConfig.vertices; + + var fixtures; + + if (fixtureConfig.circle) + { + var x = GetFastValue(fixtureConfig.circle, 'x'); + var y = GetFastValue(fixtureConfig.circle, 'y'); + var r = GetFastValue(fixtureConfig.circle, 'radius'); + fixtures = [ Bodies.circle(x, y, r, matterConfig) ]; + } + else if (fixtureConfig.vertices) + { + fixtures = this.parseVertices(fixtureConfig.vertices, matterConfig); + } + + return fixtures; + }, + + /** + * Parses the "vertices" lists exported by PhysicsEditor. + * + * @function Phaser.Physics.Matter.PhysicsEditorParser.parseVertices + * @since 3.10.0 + * + * @param {array} vertexSets - The vertex lists to parse. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType[]} - An array of Matter JS Bodies. + */ + parseVertices: function (vertexSets, options) + { + if (options === undefined) { options = {}; } + + var parts = []; + + for (var v = 0; v < vertexSets.length; v++) + { + Vertices.clockwiseSort(vertexSets[v]); + + parts.push(Body.create(Common.extend({ + position: Vertices.centre(vertexSets[v]), + vertices: vertexSets[v] + }, options))); + } + + // flag coincident part edges + return Bodies.flagCoincidentParts(parts); + } +}; + +module.exports = PhysicsEditorParser; + + +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = __webpack_require__(42); +var Body = __webpack_require__(25); + +/** + * Creates a body using the supplied physics data, as provided by a JSON file. + * + * The data file should be loaded as JSON: + * + * ```javascript + * preload () + * { + * this.load.json('ninjas', 'assets/ninjas.json); + * } + * + * create () + * { + * const ninjaShapes = this.cache.json.get('ninjas'); + * + * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); + * } + * ``` + * + * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. + * + * If you pas in an `options` object, any settings in there will override those in the config object. + * + * The structure of the JSON file is as follows: + * + * ```text + * { + * 'generator_info': // The name of the application that created the JSON data + * 'shapeName': { + * 'type': // The type of body + * 'label': // Optional body label + * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs + * } + * } + * ``` + * + * At the time of writing, only the Phaser Physics Tracer App exports in this format. + * + * @namespace Phaser.Physics.Matter.PhysicsJSONParser + * @since 3.22.0 + */ +var PhysicsJSONParser = { + + /** + * Parses a body element from the given JSON data. + * + * @function Phaser.Physics.Matter.PhysicsJSONParser.parseBody + * @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 {object} config - The body configuration data. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + parseBody: function (x, y, config, options) + { + if (options === undefined) { options = {}; } + + var body; + var vertexSets = config.vertices; + + if (vertexSets.length === 1) + { + // Just a single Body + options.vertices = vertexSets[0]; + + body = Body.create(options); + + Bodies.flagCoincidentParts(body.parts); + } + else + { + var parts = []; + + for (var i = 0; i < vertexSets.length; i++) + { + var part = Body.create({ + vertices: vertexSets[i] + }); + + parts.push(part); + } + + Bodies.flagCoincidentParts(parts); + + options.parts = parts; + + body = Body.create(options); + } + + body.label = config.label; + + Body.setPosition(body, { x: x, y: y }); + + return body; + } + +}; + +module.exports = PhysicsJSONParser; + + +/***/ }), +/* 237 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter.Events + */ + +module.exports = { + + AFTER_ADD: __webpack_require__(1351), + AFTER_REMOVE: __webpack_require__(1352), + AFTER_UPDATE: __webpack_require__(1353), + BEFORE_ADD: __webpack_require__(1354), + BEFORE_REMOVE: __webpack_require__(1355), + BEFORE_UPDATE: __webpack_require__(1356), + COLLISION_ACTIVE: __webpack_require__(1357), + COLLISION_END: __webpack_require__(1358), + COLLISION_START: __webpack_require__(1359), + DRAG_END: __webpack_require__(1360), + DRAG: __webpack_require__(1361), + DRAG_START: __webpack_require__(1362), + PAUSE: __webpack_require__(1363), + RESUME: __webpack_require__(1364), + SLEEP_END: __webpack_require__(1365), + SLEEP_START: __webpack_require__(1366) + +}; + + +/***/ }), +/* 238 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = __webpack_require__(42); +var Body = __webpack_require__(25); +var Class = __webpack_require__(0); +var Components = __webpack_require__(147); +var GetFastValue = __webpack_require__(1); +var HasValue = __webpack_require__(91); +var Vertices = __webpack_require__(31); + +/** + * @classdesc + * A wrapper around a Tile that provides access to a corresponding Matter body. A tile can only + * have one Matter body associated with it. You can either pass in an existing Matter body for + * the tile or allow the constructor to create the corresponding body for you. If the Tile has a + * collision group (defined in Tiled), those shapes will be used to create the body. If not, the + * tile's rectangle bounding box will be used. + * + * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. + * + * Note: not all Tiled collision shapes are supported. See + * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. + * + * @class TileBody + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Matter.Components.Bounce + * @extends Phaser.Physics.Matter.Components.Collision + * @extends Phaser.Physics.Matter.Components.Friction + * @extends Phaser.Physics.Matter.Components.Gravity + * @extends Phaser.Physics.Matter.Components.Mass + * @extends Phaser.Physics.Matter.Components.Sensor + * @extends Phaser.Physics.Matter.Components.Sleep + * @extends Phaser.Physics.Matter.Components.Static + * + * @param {Phaser.Physics.Matter.World} world - The Matter world instance this body belongs to. + * @param {Phaser.Tilemaps.Tile} tile - The target tile that should have a Matter body. + * @param {Phaser.Types.Physics.Matter.MatterTileOptions} [options] - Options to be used when creating the Matter body. + */ +var MatterTileBody = new Class({ + + Mixins: [ + Components.Bounce, + Components.Collision, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.Sleep, + Components.Static + ], + + initialize: + + function MatterTileBody (world, tile, options) + { + /** + * The tile object the body is associated with. + * + * @name Phaser.Physics.Matter.TileBody#tile + * @type {Phaser.Tilemaps.Tile} + * @since 3.0.0 + */ + this.tile = tile; + + /** + * The Matter world the body exists within. + * + * @name Phaser.Physics.Matter.TileBody#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + // Install a reference to 'this' on the tile and ensure there can only be one matter body + // associated with the tile + if (tile.physics.matterBody) + { + tile.physics.matterBody.destroy(); + } + + tile.physics.matterBody = this; + + // 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. + var body = GetFastValue(options, 'body', null); + + var addToWorld = GetFastValue(options, 'addToWorld', true); + + if (!body) + { + var collisionGroup = tile.getCollisionGroup(); + var collisionObjects = GetFastValue(collisionGroup, 'objects', []); + + if (collisionObjects.length > 0) + { + this.setFromTileCollision(options); + } + else + { + this.setFromTileRectangle(options); + } + } + else + { + this.setBody(body, addToWorld); + } + }, + + /** + * Sets the current body to a rectangle that matches the bounds of the tile. + * + * @method Phaser.Physics.Matter.TileBody#setFromTileRectangle + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBodyTileOptions} [options] - Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + setFromTileRectangle: function (options) + { + if (options === undefined) { options = {}; } + if (!HasValue(options, 'isStatic')) { options.isStatic = true; } + if (!HasValue(options, 'addToWorld')) { options.addToWorld = true; } + + var bounds = this.tile.getBounds(); + var cx = bounds.x + (bounds.width / 2); + var cy = bounds.y + (bounds.height / 2); + var body = Bodies.rectangle(cx, cy, bounds.width, bounds.height, options); + + this.setBody(body, options.addToWorld); + + return this; + }, + + /** + * Sets the current body from the collision group associated with the Tile. This is typically + * set up in Tiled's collision editor. + * + * Note: Matter doesn't support all shapes from Tiled. Rectangles and polygons are directly + * supported. Ellipses are converted into circle bodies. Polylines are treated as if they are + * closed polygons. If a tile has multiple shapes, a multi-part body will be created. Concave + * shapes are supported if poly-decomp library is included. Decomposition is not guaranteed to + * work for complex shapes (e.g. holes), so it's often best to manually decompose a concave + * polygon into multiple convex polygons yourself. + * + * @method Phaser.Physics.Matter.TileBody#setFromTileCollision + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBodyTileOptions} [options] - Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + setFromTileCollision: function (options) + { + if (options === undefined) { options = {}; } + if (!HasValue(options, 'isStatic')) { options.isStatic = true; } + if (!HasValue(options, 'addToWorld')) { options.addToWorld = true; } + + var sx = this.tile.tilemapLayer.scaleX; + var sy = this.tile.tilemapLayer.scaleY; + var tileX = this.tile.getLeft(); + var tileY = this.tile.getTop(); + var collisionGroup = this.tile.getCollisionGroup(); + var collisionObjects = GetFastValue(collisionGroup, 'objects', []); + + var parts = []; + + for (var i = 0; i < collisionObjects.length; i++) + { + var object = collisionObjects[i]; + var ox = tileX + (object.x * sx); + var oy = tileY + (object.y * sy); + var ow = object.width * sx; + var oh = object.height * sy; + var body = null; + + if (object.rectangle) + { + body = Bodies.rectangle(ox + ow / 2, oy + oh / 2, ow, oh, options); + } + else if (object.ellipse) + { + body = Bodies.circle(ox + ow / 2, oy + oh / 2, ow / 2, options); + } + else if (object.polygon || object.polyline) + { + // Polygons and polylines are both treated as closed polygons + var originalPoints = object.polygon ? object.polygon : object.polyline; + + var points = originalPoints.map(function (p) + { + return { x: p.x * sx, y: p.y * sy }; + }); + + var vertices = Vertices.create(points); + + // 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. + + var center = Vertices.centre(vertices); + + ox += center.x; + oy += center.y; + + body = Bodies.fromVertices(ox, oy, vertices, options); + } + + if (body) + { + parts.push(body); + } + } + + if (parts.length === 1) + { + this.setBody(parts[0], options.addToWorld); + } + else if (parts.length > 1) + { + options.parts = parts; + this.setBody(Body.create(options), options.addToWorld); + } + + return this; + }, + + /** + * Sets the current body to the given body. This will remove the previous body, if one already + * exists. + * + * @method Phaser.Physics.Matter.TileBody#setBody + * @since 3.0.0 + * + * @param {MatterJS.BodyType} body - The new Matter body to use. + * @param {boolean} [addToWorld=true] - Whether or not to add the body to the Matter world. + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + setBody: function (body, addToWorld) + { + if (addToWorld === undefined) { addToWorld = true; } + + if (this.body) + { + this.removeBody(); + } + + this.body = body; + this.body.gameObject = this; + + if (addToWorld) + { + this.world.add(this.body); + } + + return this; + }, + + /** + * Removes the current body from the TileBody and from the Matter world + * + * @method Phaser.Physics.Matter.TileBody#removeBody + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + removeBody: function () + { + if (this.body) + { + this.world.remove(this.body); + this.body.gameObject = undefined; + this.body = undefined; + } + + return this; + }, + + /** + * Removes the current body from the tile and the world. + * + * @method Phaser.Physics.Matter.TileBody#destroy + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + destroy: function () + { + this.removeBody(); + this.tile.physics.matterBody = undefined; + } + +}); + +module.exports = MatterTileBody; + + +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter.Matter + */ + +var Matter = __webpack_require__(508); + +Matter.Body = __webpack_require__(25); +Matter.Composite = __webpack_require__(68); +Matter.World = __webpack_require__(241); + +Matter.Detector = __webpack_require__(148); +Matter.Grid = __webpack_require__(242); +Matter.Pairs = __webpack_require__(243); +Matter.Pair = __webpack_require__(114); +Matter.Query = __webpack_require__(509); +Matter.Resolver = __webpack_require__(244); +Matter.SAT = __webpack_require__(149); + +Matter.Constraint = __webpack_require__(78); + +Matter.Common = __webpack_require__(19); +Matter.Engine = __webpack_require__(510); +Matter.Events = __webpack_require__(96); +Matter.Sleeping = __webpack_require__(95); +Matter.Plugin = __webpack_require__(240); + +Matter.Bodies = __webpack_require__(42); +Matter.Composites = __webpack_require__(233); + +Matter.Axes = __webpack_require__(146); +Matter.Bounds = __webpack_require__(38); +Matter.Svg = __webpack_require__(234); +Matter.Vector = __webpack_require__(37); +Matter.Vertices = __webpack_require__(31); + +// aliases + +Matter.World.add = Matter.Composite.add; +Matter.World.remove = Matter.Composite.remove; +Matter.World.addComposite = Matter.Composite.addComposite; +Matter.World.addBody = Matter.Composite.addBody; +Matter.World.addConstraint = Matter.Composite.addConstraint; +Matter.World.clear = Matter.Composite.clear; + +module.exports = Matter; + + +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Plugin` module contains functions for registering and installing plugins on modules. +* +* @class Plugin +*/ + +var Plugin = {}; + +module.exports = Plugin; + +var Common = __webpack_require__(19); + +(function() { + + Plugin._registry = {}; + + /** + * Registers a plugin object so it can be resolved later by name. + * @method register + * @param plugin {} The plugin to register. + * @return {object} The plugin. + */ + Plugin.register = function(plugin) { + if (!Plugin.isPlugin(plugin)) { + Common.warn('Plugin.register:', Plugin.toString(plugin), 'does not implement all required fields.'); + } + + if (plugin.name in Plugin._registry) { + var registered = Plugin._registry[plugin.name], + pluginVersion = Plugin.versionParse(plugin.version).number, + registeredVersion = Plugin.versionParse(registered.version).number; + + if (pluginVersion > registeredVersion) { + Common.warn('Plugin.register:', Plugin.toString(registered), 'was upgraded to', Plugin.toString(plugin)); + Plugin._registry[plugin.name] = plugin; + } else if (pluginVersion < registeredVersion) { + Common.warn('Plugin.register:', Plugin.toString(registered), 'can not be downgraded to', Plugin.toString(plugin)); + } else if (plugin !== registered) { + Common.warn('Plugin.register:', Plugin.toString(plugin), 'is already registered to different plugin object'); + } + } else { + Plugin._registry[plugin.name] = plugin; + } + + return plugin; + }; + + /** + * Resolves a dependency to a plugin object from the registry if it exists. + * The `dependency` may contain a version, but only the name matters when resolving. + * @method resolve + * @param dependency {string} The dependency. + * @return {object} The plugin if resolved, otherwise `undefined`. + */ + Plugin.resolve = function(dependency) { + return Plugin._registry[Plugin.dependencyParse(dependency).name]; + }; + + /** + * Returns a pretty printed plugin name and version. + * @method toString + * @param plugin {} The plugin. + * @return {string} Pretty printed plugin name and version. + */ + Plugin.toString = function(plugin) { + return typeof plugin === 'string' ? plugin : (plugin.name || 'anonymous') + '@' + (plugin.version || plugin.range || '0.0.0'); + }; + + /** + * Returns `true` if the object meets the minimum standard to be considered a plugin. + * This means it must define the following properties: + * - `name` + * - `version` + * - `install` + * @method isPlugin + * @param obj {} The obj to test. + * @return {boolean} `true` if the object can be considered a plugin otherwise `false`. + */ + Plugin.isPlugin = function(obj) { + return obj && obj.name && obj.version && obj.install; + }; + + /** + * Returns `true` if a plugin with the given `name` been installed on `module`. + * @method isUsed + * @param module {} The module. + * @param name {string} The plugin name. + * @return {boolean} `true` if a plugin with the given `name` been installed on `module`, otherwise `false`. + */ + Plugin.isUsed = function(module, name) { + return module.used.indexOf(name) > -1; + }; + + /** + * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`. + * If `plugin.for` is not specified then it is assumed to be applicable. + * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`. + * @method isFor + * @param plugin {} The plugin. + * @param module {} The module. + * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`. + */ + Plugin.isFor = function(plugin, module) { + var parsed = plugin.for && Plugin.dependencyParse(plugin.for); + return !plugin.for || (module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range)); + }; + + /** + * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`. + * For installing plugins on `Matter` see the convenience function `Matter.use`. + * Plugins may be specified either by their name or a reference to the plugin object. + * Plugins themselves may specify further dependencies, but each plugin is installed only once. + * Order is important, a topological sort is performed to find the best resulting order of installation. + * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases. + * This function logs the resulting status of each dependency in the console, along with any warnings. + * - A green tick ✅ indicates a dependency was resolved and installed. + * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies. + * - A red cross ❌ indicates a dependency could not be resolved. + * Avoid calling this function multiple times on the same module unless you intend to manually control installation order. + * @method use + * @param module {} The module install plugins on. + * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`). + */ + Plugin.use = function(module, plugins) { + module.uses = (module.uses || []).concat(plugins || []); + + if (module.uses.length === 0) { + Common.warn('Plugin.use:', Plugin.toString(module), 'does not specify any dependencies to install.'); + return; + } + + var dependencies = Plugin.dependencies(module), + sortedDependencies = Common.topologicalSort(dependencies), + status = []; + + for (var i = 0; i < sortedDependencies.length; i += 1) { + if (sortedDependencies[i] === module.name) { + continue; + } + + var plugin = Plugin.resolve(sortedDependencies[i]); + + if (!plugin) { + status.push('❌ ' + sortedDependencies[i]); + continue; + } + + if (Plugin.isUsed(module, plugin.name)) { + continue; + } + + if (!Plugin.isFor(plugin, module)) { + Common.warn('Plugin.use:', Plugin.toString(plugin), 'is for', plugin.for, 'but installed on', Plugin.toString(module) + '.'); + plugin._warned = true; + } + + if (plugin.install) { + plugin.install(module); + } else { + Common.warn('Plugin.use:', Plugin.toString(plugin), 'does not specify an install function.'); + plugin._warned = true; + } + + if (plugin._warned) { + status.push('🔶 ' + Plugin.toString(plugin)); + delete plugin._warned; + } else { + status.push('✅ ' + Plugin.toString(plugin)); + } + + module.used.push(plugin.name); + } + + if (status.length > 0 && !plugin.silent) { + Common.info(status.join(' ')); + } + }; + + /** + * Recursively finds all of a module's dependencies and returns a flat dependency graph. + * @method dependencies + * @param module {} The module. + * @return {object} A dependency graph. + */ + Plugin.dependencies = function(module, tracked) { + var parsedBase = Plugin.dependencyParse(module), + name = parsedBase.name; + + tracked = tracked || {}; + + if (name in tracked) { + return; + } + + module = Plugin.resolve(module) || module; + + tracked[name] = Common.map(module.uses || [], function(dependency) { + if (Plugin.isPlugin(dependency)) { + Plugin.register(dependency); + } + + var parsed = Plugin.dependencyParse(dependency), + resolved = Plugin.resolve(dependency); + + if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) { + Common.warn( + 'Plugin.dependencies:', Plugin.toString(resolved), 'does not satisfy', + Plugin.toString(parsed), 'used by', Plugin.toString(parsedBase) + '.' + ); + + resolved._warned = true; + module._warned = true; + } else if (!resolved) { + Common.warn( + 'Plugin.dependencies:', Plugin.toString(dependency), 'used by', + Plugin.toString(parsedBase), 'could not be resolved.' + ); + + module._warned = true; + } + + return parsed.name; + }); + + for (var i = 0; i < tracked[name].length; i += 1) { + Plugin.dependencies(tracked[name][i], tracked); + } + + return tracked; + }; + + /** + * Parses a dependency string into its components. + * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`. + * See documentation for `Plugin.versionParse` for a description of the format. + * This function can also handle dependencies that are already resolved (e.g. a module object). + * @method dependencyParse + * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`. + * @return {object} The dependency parsed into its components. + */ + Plugin.dependencyParse = function(dependency) { + if (Common.isString(dependency)) { + var pattern = /^[\w-]+(@(\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?))?$/; + + if (!pattern.test(dependency)) { + Common.warn('Plugin.dependencyParse:', dependency, 'is not a valid dependency string.'); + } + + return { + name: dependency.split('@')[0], + range: dependency.split('@')[1] || '*' + }; + } + + return { + name: dependency.name, + range: dependency.range || dependency.version + }; + }; + + /** + * 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` + * - 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. + */ + Plugin.versionParse = function(range) { + var pattern = /^\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?$/; + + if (!pattern.test(range)) { + Common.warn('Plugin.versionParse:', range, 'is not a valid version or range.'); + } + + var identifiers = range.split('-'); + range = identifiers[0]; + + var isRange = isNaN(Number(range[0])), + version = isRange ? range.substr(1) : range, + parts = Common.map(version.split('.'), function(part) { + return Number(part); + }); + + return { + isRange: isRange, + version: version, + range: range, + operator: isRange ? range[0] : '', + parts: parts, + prerelease: identifiers[1], + number: parts[0] * 1e8 + parts[1] * 1e4 + parts[2] + }; + }; + + /** + * Returns `true` if `version` satisfies the given `range`. + * See documentation for `Plugin.versionParse` for a description of the format. + * If a version or range is not specified, then any version (`*`) is assumed to satisfy. + * @method versionSatisfies + * @param version {string} The version string. + * @param range {string} The range string. + * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`. + */ + Plugin.versionSatisfies = function(version, range) { + range = range || '*'; + + var rangeParsed = Plugin.versionParse(range), + rangeParts = rangeParsed.parts, + versionParsed = Plugin.versionParse(version), + versionParts = versionParsed.parts; + + if (rangeParsed.isRange) { + if (rangeParsed.operator === '*' || version === '*') { + return true; + } + + if (rangeParsed.operator === '~') { + return versionParts[0] === rangeParts[0] && versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2]; + } + + if (rangeParsed.operator === '^') { + if (rangeParts[0] > 0) { + return versionParts[0] === rangeParts[0] && versionParsed.number >= rangeParsed.number; + } + + if (rangeParts[1] > 0) { + return versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2]; + } + + return versionParts[2] === rangeParts[2]; + } + } + + return version === range || version === '*'; + }; + +})(); + + +/***/ }), +/* 241 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.World` module contains methods for creating and manipulating the world composite. +* A `Matter.World` is a `Matter.Composite` body, which is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`. +* A `Matter.World` has a few additional properties including `gravity` and `bounds`. +* It is important to use the functions in the `Matter.Composite` module to modify the world composite, rather than directly modifying its properties. +* There are also a few methods here that alias those in `Matter.Composite` for easier readability. +* +* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). +* +* @class World +* @extends Composite +*/ + +var World = {}; + +module.exports = World; + +var Composite = __webpack_require__(68); +var Constraint = __webpack_require__(78); +var Common = __webpack_require__(19); + +(function() { + + /** + * Creates a new world composite. The options parameter is an object that specifies any properties you wish to override the defaults. + * See the properties section below for detailed information on what you can pass via the `options` object. + * @method create + * @constructor + * @param {} options + * @return {world} A new world + */ + World.create = function(options) { + var composite = Composite.create(); + + var defaults = { + label: 'World', + gravity: { + x: 0, + y: 1, + scale: 0.001 + }, + bounds: { + min: { x: -Infinity, y: -Infinity }, + max: { x: Infinity, y: Infinity } + } + }; + + return Common.extend(composite, defaults, options); + }; + + /* + * + * Properties Documentation + * + */ + + /** + * The gravity to apply on the world. + * + * @property gravity + * @type object + */ + + /** + * The gravity x component. + * + * @property gravity.x + * @type object + * @default 0 + */ + + /** + * The gravity y component. + * + * @property gravity.y + * @type object + * @default 1 + */ + + /** + * The gravity scale factor. + * + * @property gravity.scale + * @type object + * @default 0.001 + */ + + /** + * A `Bounds` object that defines the world bounds for collision detection. + * + * @property bounds + * @type bounds + * @default { min: { x: -Infinity, y: -Infinity }, max: { x: Infinity, y: Infinity } } + */ + + // World is a Composite body + // see src/module/Outro.js for these aliases: + + /** + * An alias for Composite.add + * @method add + * @param {world} world + * @param {} object + * @return {composite} The original world with the objects added + */ + + /** + * An alias for Composite.remove + * @method remove + * @param {world} world + * @param {} object + * @param {boolean} [deep=false] + * @return {composite} The original world with the objects removed + */ + + /** + * An alias for Composite.clear + * @method clear + * @param {world} world + * @param {boolean} keepStatic + */ + + /** + * An alias for Composite.addComposite + * @method addComposite + * @param {world} world + * @param {composite} composite + * @return {world} The original world with the objects from composite added + */ + + /** + * An alias for Composite.addBody + * @method addBody + * @param {world} world + * @param {body} body + * @return {world} The original world with the body added + */ + + /** + * An alias for Composite.addConstraint + * @method addConstraint + * @param {world} world + * @param {constraint} constraint + * @return {world} The original world with the constraint added + */ + +})(); + + +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. +* +* @class Grid +*/ + +var Grid = {}; + +module.exports = Grid; + +var Pair = __webpack_require__(114); +var Detector = __webpack_require__(148); +var Common = __webpack_require__(19); + +(function() { + + /** + * Creates a new grid. + * @method create + * @param {} options + * @return {grid} A new grid + */ + Grid.create = function(options) { + var defaults = { + controller: Grid, + detector: Detector.collisions, + buckets: {}, + pairs: {}, + pairsList: [], + bucketWidth: 48, + bucketHeight: 48 + }; + + return Common.extend(defaults, options); + }; + + /** + * The width of a single grid bucket. + * + * @property bucketWidth + * @type number + * @default 48 + */ + + /** + * The height of a single grid bucket. + * + * @property bucketHeight + * @type number + * @default 48 + */ + + /** + * Updates the grid. + * @method update + * @param {grid} grid + * @param {body[]} bodies + * @param {engine} engine + * @param {boolean} forceUpdate + */ + Grid.update = function(grid, bodies, engine, forceUpdate) { + var i, col, row, + world = engine.world, + buckets = grid.buckets, + bucket, + bucketId, + gridChanged = false; + + // @if DEBUG + var metrics = engine.metrics; + metrics.broadphaseTests = 0; + // @endif + + for (i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + if (body.isSleeping && !forceUpdate) + continue; + + // don't update out of world bodies + if (body.bounds.max.x < world.bounds.min.x || body.bounds.min.x > world.bounds.max.x + || body.bounds.max.y < world.bounds.min.y || body.bounds.min.y > world.bounds.max.y) + continue; + + var newRegion = Grid._getRegion(grid, body); + + // if the body has changed grid region + if (!body.region || newRegion.id !== body.region.id || forceUpdate) { + + // @if DEBUG + metrics.broadphaseTests += 1; + // @endif + + if (!body.region || forceUpdate) + body.region = newRegion; + + var union = Grid._regionUnion(newRegion, body.region); + + // update grid buckets affected by region change + // iterate over the union of both regions + for (col = union.startCol; col <= union.endCol; col++) { + for (row = union.startRow; row <= union.endRow; row++) { + bucketId = Grid._getBucketId(col, row); + bucket = buckets[bucketId]; + + var isInsideNewRegion = (col >= newRegion.startCol && col <= newRegion.endCol + && row >= newRegion.startRow && row <= newRegion.endRow); + + var isInsideOldRegion = (col >= body.region.startCol && col <= body.region.endCol + && row >= body.region.startRow && row <= body.region.endRow); + + // remove from old region buckets + if (!isInsideNewRegion && isInsideOldRegion) { + if (isInsideOldRegion) { + if (bucket) + Grid._bucketRemoveBody(grid, bucket, body); + } + } + + // add to new region buckets + if (body.region === newRegion || (isInsideNewRegion && !isInsideOldRegion) || forceUpdate) { + if (!bucket) + bucket = Grid._createBucket(buckets, bucketId); + Grid._bucketAddBody(grid, bucket, body); + } + } + } + + // set the new region + body.region = newRegion; + + // flag changes so we can update pairs + gridChanged = true; + } + } + + // update pairs list only if pairs changed (i.e. a body changed region) + if (gridChanged) + grid.pairsList = Grid._createActivePairsList(grid); + }; + + /** + * Clears the grid. + * @method clear + * @param {grid} grid + */ + Grid.clear = function(grid) { + grid.buckets = {}; + grid.pairs = {}; + grid.pairsList = []; + }; + + /** + * Finds the union of two regions. + * @method _regionUnion + * @private + * @param {} regionA + * @param {} regionB + * @return {} region + */ + Grid._regionUnion = function(regionA, regionB) { + var startCol = Math.min(regionA.startCol, regionB.startCol), + endCol = Math.max(regionA.endCol, regionB.endCol), + startRow = Math.min(regionA.startRow, regionB.startRow), + endRow = Math.max(regionA.endRow, regionB.endRow); + + return Grid._createRegion(startCol, endCol, startRow, endRow); + }; + + /** + * Gets the region a given body falls in for a given grid. + * @method _getRegion + * @private + * @param {} grid + * @param {} body + * @return {} region + */ + Grid._getRegion = function(grid, body) { + var bounds = body.bounds, + startCol = Math.floor(bounds.min.x / grid.bucketWidth), + endCol = Math.floor(bounds.max.x / grid.bucketWidth), + startRow = Math.floor(bounds.min.y / grid.bucketHeight), + endRow = Math.floor(bounds.max.y / grid.bucketHeight); + + return Grid._createRegion(startCol, endCol, startRow, endRow); + }; + + /** + * Creates a region. + * @method _createRegion + * @private + * @param {} startCol + * @param {} endCol + * @param {} startRow + * @param {} endRow + * @return {} region + */ + Grid._createRegion = function(startCol, endCol, startRow, endRow) { + return { + id: startCol + ',' + endCol + ',' + startRow + ',' + endRow, + startCol: startCol, + endCol: endCol, + startRow: startRow, + endRow: endRow + }; + }; + + /** + * Gets the bucket id at the given position. + * @method _getBucketId + * @private + * @param {} column + * @param {} row + * @return {string} bucket id + */ + Grid._getBucketId = function(column, row) { + return 'C' + column + 'R' + row; + }; + + /** + * Creates a bucket. + * @method _createBucket + * @private + * @param {} buckets + * @param {} bucketId + * @return {} bucket + */ + Grid._createBucket = function(buckets, bucketId) { + var bucket = buckets[bucketId] = []; + return bucket; + }; + + /** + * Adds a body to a bucket. + * @method _bucketAddBody + * @private + * @param {} grid + * @param {} bucket + * @param {} body + */ + Grid._bucketAddBody = function(grid, bucket, body) { + // add new pairs + for (var i = 0; i < bucket.length; i++) { + var bodyB = bucket[i]; + + if (body.id === bodyB.id || (body.isStatic && bodyB.isStatic)) + continue; + + // keep track of the number of buckets the pair exists in + // important for Grid.update to work + var pairId = Pair.id(body, bodyB), + pair = grid.pairs[pairId]; + + if (pair) { + pair[2] += 1; + } else { + grid.pairs[pairId] = [body, bodyB, 1]; + } + } + + // add to bodies (after pairs, otherwise pairs with self) + bucket.push(body); + }; + + /** + * Removes a body from a bucket. + * @method _bucketRemoveBody + * @private + * @param {} grid + * @param {} bucket + * @param {} body + */ + Grid._bucketRemoveBody = function(grid, bucket, body) { + // remove from bucket + bucket.splice(bucket.indexOf(body), 1); + + // update pair counts + for (var i = 0; i < bucket.length; i++) { + // keep track of the number of buckets the pair exists in + // important for _createActivePairsList to work + var bodyB = bucket[i], + pairId = Pair.id(body, bodyB), + pair = grid.pairs[pairId]; + + if (pair) + pair[2] -= 1; + } + }; + + /** + * Generates a list of the active pairs in the grid. + * @method _createActivePairsList + * @private + * @param {} grid + * @return [] pairs + */ + Grid._createActivePairsList = function(grid) { + var pairKeys, + pair, + pairs = []; + + // grid.pairs is used as a hashmap + pairKeys = Common.keys(grid.pairs); + + // iterate over grid.pairs + for (var k = 0; k < pairKeys.length; k++) { + pair = grid.pairs[pairKeys[k]]; + + // if pair exists in at least one bucket + // it is a pair that needs further collision testing so push it + if (pair[2] > 0) { + pairs.push(pair); + } else { + delete grid.pairs[pairKeys[k]]; + } + } + + return pairs; + }; + +})(); + + +/***/ }), +/* 243 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. +* +* @class Pairs +*/ + +var Pairs = {}; + +module.exports = Pairs; + +var Pair = __webpack_require__(114); +var Common = __webpack_require__(19); + +(function() { + + Pairs._pairMaxIdleLife = 1000; + + /** + * Creates a new pairs structure. + * @method create + * @param {object} options + * @return {pairs} A new pairs structure + */ + Pairs.create = function(options) { + return Common.extend({ + table: {}, + list: [], + collisionStart: [], + collisionActive: [], + collisionEnd: [] + }, options); + }; + + /** + * Updates pairs given a list of collisions. + * @method update + * @param {object} pairs + * @param {collision[]} collisions + * @param {number} timestamp + */ + Pairs.update = function(pairs, collisions, timestamp) { + var pairsList = pairs.list, + pairsTable = pairs.table, + collisionStart = pairs.collisionStart, + collisionEnd = pairs.collisionEnd, + collisionActive = pairs.collisionActive, + collision, + pairId, + pair, + i; + + // clear collision state arrays, but maintain old reference + collisionStart.length = 0; + collisionEnd.length = 0; + collisionActive.length = 0; + + for (i = 0; i < pairsList.length; i++) { + pairsList[i].confirmedActive = false; + } + + for (i = 0; i < collisions.length; i++) { + collision = collisions[i]; + + if (collision.collided) { + pairId = Pair.id(collision.bodyA, collision.bodyB); + + pair = pairsTable[pairId]; + + if (pair) { + // pair already exists (but may or may not be active) + if (pair.isActive) { + // pair exists and is active + collisionActive.push(pair); + } else { + // pair exists but was inactive, so a collision has just started again + collisionStart.push(pair); + } + + // update the pair + Pair.update(pair, collision, timestamp); + pair.confirmedActive = true; + } else { + // pair did not exist, create a new pair + pair = Pair.create(collision, timestamp); + pairsTable[pairId] = pair; + + // push the new pair + collisionStart.push(pair); + pairsList.push(pair); + } + } + } + + // deactivate previously active pairs that are now inactive + for (i = 0; i < pairsList.length; i++) { + pair = pairsList[i]; + if (pair.isActive && !pair.confirmedActive) { + Pair.setActive(pair, false, timestamp); + collisionEnd.push(pair); + } + } + }; + + /** + * Finds and removes pairs that have been inactive for a set amount of time. + * @method removeOld + * @param {object} pairs + * @param {number} timestamp + */ + Pairs.removeOld = function(pairs, timestamp) { + var pairsList = pairs.list, + pairsTable = pairs.table, + indexesToRemove = [], + pair, + collision, + pairIndex, + i; + + for (i = 0; i < pairsList.length; i++) { + pair = pairsList[i]; + collision = pair.collision; + + // never remove sleeping pairs + if (collision.bodyA.isSleeping || collision.bodyB.isSleeping) { + pair.timeUpdated = timestamp; + continue; + } + + // if pair is inactive for too long, mark it to be removed + if (timestamp - pair.timeUpdated > Pairs._pairMaxIdleLife) { + indexesToRemove.push(i); + } + } + + // remove marked pairs + for (i = 0; i < indexesToRemove.length; i++) { + pairIndex = indexesToRemove[i] - i; + pair = pairsList[pairIndex]; + delete pairsTable[pair.id]; + pairsList.splice(pairIndex, 1); + } + }; + + /** + * Clears the given pairs structure. + * @method clear + * @param {pairs} pairs + * @return {pairs} pairs + */ + Pairs.clear = function(pairs) { + pairs.table = {}; + pairs.list.length = 0; + pairs.collisionStart.length = 0; + pairs.collisionActive.length = 0; + pairs.collisionEnd.length = 0; + return pairs; + }; + +})(); + + +/***/ }), +/* 244 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter.Resolver` module contains methods for resolving collision pairs. +* +* @class Resolver +*/ + +var Resolver = {}; + +module.exports = Resolver; + +var Vertices = __webpack_require__(31); +var Vector = __webpack_require__(37); +var Common = __webpack_require__(19); +var Bounds = __webpack_require__(38); + +(function() { + + Resolver._restingThresh = 4; + Resolver._restingThreshTangent = 6; + Resolver._positionDampen = 0.9; + Resolver._positionWarming = 0.8; + Resolver._frictionNormalMultiplier = 5; + + /** + * Prepare pairs for position solving. + * @method preSolvePosition + * @param {pair[]} pairs + */ + Resolver.preSolvePosition = function(pairs) { + var i, + pair, + activeCount; + + // find total contacts on each body + for (i = 0; i < pairs.length; i++) { + pair = pairs[i]; + + if (!pair.isActive) + continue; + + activeCount = pair.activeContacts.length; + pair.collision.parentA.totalContacts += activeCount; + pair.collision.parentB.totalContacts += activeCount; + } + }; + + /** + * Find a solution for pair positions. + * @method solvePosition + * @param {pair[]} pairs + * @param {body[]} bodies + * @param {number} timeScale + */ + Resolver.solvePosition = function(pairs, bodies, timeScale) { + var i, + normalX, + normalY, + pair, + collision, + bodyA, + bodyB, + normal, + separation, + penetration, + positionImpulseA, + positionImpulseB, + contactShare, + bodyBtoAX, + bodyBtoAY, + positionImpulse, + impulseCoefficient = timeScale * Resolver._positionDampen; + + for (i = 0; i < bodies.length; i++) { + var body = bodies[i]; + body.previousPositionImpulse.x = body.positionImpulse.x; + body.previousPositionImpulse.y = body.positionImpulse.y; + } + + // find impulses required to resolve penetration + for (i = 0; i < pairs.length; i++) { + pair = pairs[i]; + + if (!pair.isActive || pair.isSensor) + continue; + + collision = pair.collision; + bodyA = collision.parentA; + bodyB = collision.parentB; + normal = collision.normal; + + positionImpulseA = bodyA.previousPositionImpulse; + positionImpulseB = bodyB.previousPositionImpulse; + + penetration = collision.penetration; + + bodyBtoAX = positionImpulseB.x - positionImpulseA.x + penetration.x; + bodyBtoAY = positionImpulseB.y - positionImpulseA.y + penetration.y; + + normalX = normal.x; + normalY = normal.y; + + separation = normalX * bodyBtoAX + normalY * bodyBtoAY; + pair.separation = separation; + + positionImpulse = (separation - pair.slop) * impulseCoefficient; + + if (bodyA.isStatic || bodyB.isStatic) + positionImpulse *= 2; + + if (!(bodyA.isStatic || bodyA.isSleeping)) { + contactShare = positionImpulse / bodyA.totalContacts; + bodyA.positionImpulse.x += normalX * contactShare; + bodyA.positionImpulse.y += normalY * contactShare; + } + + if (!(bodyB.isStatic || bodyB.isSleeping)) { + contactShare = positionImpulse / bodyB.totalContacts; + bodyB.positionImpulse.x -= normalX * contactShare; + bodyB.positionImpulse.y -= normalY * contactShare; + } + } + }; + + /** + * Apply position resolution. + * @method postSolvePosition + * @param {body[]} bodies + */ + Resolver.postSolvePosition = function(bodies) { + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + // reset contact count + body.totalContacts = 0; + + if (body.positionImpulse.x !== 0 || body.positionImpulse.y !== 0) { + // update body geometry + for (var j = 0; j < body.parts.length; j++) { + var part = body.parts[j]; + Vertices.translate(part.vertices, body.positionImpulse); + Bounds.update(part.bounds, part.vertices, body.velocity); + part.position.x += body.positionImpulse.x; + part.position.y += body.positionImpulse.y; + } + + // move the body without changing velocity + body.positionPrev.x += body.positionImpulse.x; + body.positionPrev.y += body.positionImpulse.y; + + if (Vector.dot(body.positionImpulse, body.velocity) < 0) { + // reset cached impulse if the body has velocity along it + body.positionImpulse.x = 0; + body.positionImpulse.y = 0; + } else { + // warm the next iteration + body.positionImpulse.x *= Resolver._positionWarming; + body.positionImpulse.y *= Resolver._positionWarming; + } + } + } + }; + + /** + * Prepare pairs for velocity solving. + * @method preSolveVelocity + * @param {pair[]} pairs + */ + Resolver.preSolveVelocity = function(pairs) { + var i, + j, + pair, + contacts, + collision, + bodyA, + bodyB, + normal, + tangent, + contact, + contactVertex, + normalImpulse, + tangentImpulse, + offset, + impulse = Vector._temp[0], + tempA = Vector._temp[1]; + + for (i = 0; i < pairs.length; i++) { + pair = pairs[i]; + + if (!pair.isActive || pair.isSensor) + continue; + + contacts = pair.activeContacts; + collision = pair.collision; + bodyA = collision.parentA; + bodyB = collision.parentB; + normal = collision.normal; + tangent = collision.tangent; + + // resolve each contact + for (j = 0; j < contacts.length; j++) { + contact = contacts[j]; + contactVertex = contact.vertex; + normalImpulse = contact.normalImpulse; + tangentImpulse = contact.tangentImpulse; + + if (normalImpulse !== 0 || tangentImpulse !== 0) { + // total impulse from contact + impulse.x = (normal.x * normalImpulse) + (tangent.x * tangentImpulse); + impulse.y = (normal.y * normalImpulse) + (tangent.y * tangentImpulse); + + // apply impulse from contact + if (!(bodyA.isStatic || bodyA.isSleeping)) { + offset = Vector.sub(contactVertex, bodyA.position, tempA); + bodyA.positionPrev.x += impulse.x * bodyA.inverseMass; + bodyA.positionPrev.y += impulse.y * bodyA.inverseMass; + bodyA.anglePrev += Vector.cross(offset, impulse) * bodyA.inverseInertia; + } + + if (!(bodyB.isStatic || bodyB.isSleeping)) { + offset = Vector.sub(contactVertex, bodyB.position, tempA); + bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass; + bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass; + bodyB.anglePrev -= Vector.cross(offset, impulse) * bodyB.inverseInertia; + } + } + } + } + }; + + /** + * Find a solution for pair velocities. + * @method solveVelocity + * @param {pair[]} pairs + * @param {number} timeScale + */ + Resolver.solveVelocity = function(pairs, timeScale) { + var timeScaleSquared = timeScale * timeScale, + impulse = Vector._temp[0], + tempA = Vector._temp[1], + tempB = Vector._temp[2], + tempC = Vector._temp[3], + tempD = Vector._temp[4], + tempE = Vector._temp[5]; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + + if (!pair.isActive || pair.isSensor) + continue; + + var collision = pair.collision, + bodyA = collision.parentA, + bodyB = collision.parentB, + normal = collision.normal, + tangent = collision.tangent, + contacts = pair.activeContacts, + contactShare = 1 / contacts.length; + + // update body velocities + bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x; + bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y; + bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x; + bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y; + bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev; + bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev; + + // resolve each contact + for (var j = 0; j < contacts.length; j++) { + var contact = contacts[j], + contactVertex = contact.vertex, + offsetA = Vector.sub(contactVertex, bodyA.position, tempA), + offsetB = Vector.sub(contactVertex, bodyB.position, tempB), + velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity), tempC), + velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity), tempD), + relativeVelocity = Vector.sub(velocityPointA, velocityPointB, tempE), + normalVelocity = Vector.dot(normal, relativeVelocity); + + var tangentVelocity = Vector.dot(tangent, relativeVelocity), + tangentSpeed = Math.abs(tangentVelocity), + tangentVelocityDirection = Common.sign(tangentVelocity); + + // raw impulses + var normalImpulse = (1 + pair.restitution) * normalVelocity, + normalForce = Common.clamp(pair.separation + normalVelocity, 0, 1) * Resolver._frictionNormalMultiplier; + + // coulomb friction + var tangentImpulse = tangentVelocity, + maxFriction = Infinity; + + if (tangentSpeed > pair.friction * pair.frictionStatic * normalForce * timeScaleSquared) { + maxFriction = tangentSpeed; + tangentImpulse = Common.clamp( + pair.friction * tangentVelocityDirection * timeScaleSquared, + -maxFriction, maxFriction + ); + } + + // modify impulses accounting for mass, inertia and offset + var oAcN = Vector.cross(offsetA, normal), + oBcN = Vector.cross(offsetB, normal), + share = contactShare / (bodyA.inverseMass + bodyB.inverseMass + bodyA.inverseInertia * oAcN * oAcN + bodyB.inverseInertia * oBcN * oBcN); + + normalImpulse *= share; + tangentImpulse *= share; + + // handle high velocity and resting collisions separately + if (normalVelocity < 0 && normalVelocity * normalVelocity > Resolver._restingThresh * timeScaleSquared) { + // high normal velocity so clear cached contact normal impulse + contact.normalImpulse = 0; + } else { + // solve resting collision constraints using Erin Catto's method (GDC08) + // impulse constraint tends to 0 + var contactNormalImpulse = contact.normalImpulse; + contact.normalImpulse = Math.min(contact.normalImpulse + normalImpulse, 0); + normalImpulse = contact.normalImpulse - contactNormalImpulse; + } + + // handle high velocity and resting collisions separately + if (tangentVelocity * tangentVelocity > Resolver._restingThreshTangent * timeScaleSquared) { + // high tangent velocity so clear cached contact tangent impulse + contact.tangentImpulse = 0; + } else { + // solve resting collision constraints using Erin Catto's method (GDC08) + // tangent impulse tends to -tangentSpeed or +tangentSpeed + var contactTangentImpulse = contact.tangentImpulse; + contact.tangentImpulse = Common.clamp(contact.tangentImpulse + tangentImpulse, -maxFriction, maxFriction); + tangentImpulse = contact.tangentImpulse - contactTangentImpulse; + } + + // total impulse from contact + impulse.x = (normal.x * normalImpulse) + (tangent.x * tangentImpulse); + impulse.y = (normal.y * normalImpulse) + (tangent.y * tangentImpulse); + + // apply impulse from contact + if (!(bodyA.isStatic || bodyA.isSleeping)) { + bodyA.positionPrev.x += impulse.x * bodyA.inverseMass; + bodyA.positionPrev.y += impulse.y * bodyA.inverseMass; + bodyA.anglePrev += Vector.cross(offsetA, impulse) * bodyA.inverseInertia; + } + + if (!(bodyB.isStatic || bodyB.isSleeping)) { + bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass; + bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass; + bodyB.anglePrev -= Vector.cross(offsetB, impulse) * bodyB.inverseInertia; + } + } + } + }; + +})(); + + +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTileAt = __webpack_require__(151); + +/** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * @function Phaser.Tilemaps.Components.CalculateFacesAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var CalculateFacesAt = function (tileX, tileY, layer) +{ + var tile = GetTileAt(tileX, tileY, true, layer); + var above = GetTileAt(tileX, tileY - 1, true, layer); + var below = GetTileAt(tileX, tileY + 1, true, layer); + var left = GetTileAt(tileX - 1, tileY, true, layer); + var right = GetTileAt(tileX + 1, tileY, true, layer); + var tileCollides = tile && tile.collides; + + // Assume the changed tile has all interesting edges + if (tileCollides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + // Reset edges that are shared between tile and its neighbors + if (above && above.collides) + { + if (tileCollides) { tile.faceTop = false; } + above.faceBottom = !tileCollides; + } + + if (below && below.collides) + { + if (tileCollides) { tile.faceBottom = false; } + below.faceTop = !tileCollides; + } + + if (left && left.collides) + { + if (tileCollides) { tile.faceLeft = false; } + left.faceRight = !tileCollides; + } + + if (right && right.collides) + { + if (tileCollides) { tile.faceRight = false; } + right.faceLeft = !tileCollides; + } + + if (tile && !tile.collides) { tile.resetFaces(); } + + return tile; +}; + +module.exports = CalculateFacesAt; + + +/***/ }), +/* 246 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tile = __webpack_require__(80); +var IsInLayerBounds = __webpack_require__(115); +var CalculateFacesAt = __webpack_require__(245); +var SetTileCollision = __webpack_require__(79); + +/** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * @function Phaser.Tilemaps.Components.PutTileAt + * @private + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. + */ +var PutTileAt = function (tile, tileX, tileY, recalculateFaces, layer) +{ + if (!IsInLayerBounds(tileX, tileY, layer)) { return null; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + var oldTile = layer.data[tileY][tileX]; + var oldTileCollides = oldTile && oldTile.collides; + + if (tile instanceof Tile) + { + if (layer.data[tileY][tileX] === null) + { + layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, tile.width, tile.height); + } + layer.data[tileY][tileX].copy(tile); + } + else + { + var index = tile; + if (layer.data[tileY][tileX] === null) + { + layer.data[tileY][tileX] = new Tile(layer, index, tileX, tileY, layer.tileWidth, layer.tileHeight); + } + else + { + layer.data[tileY][tileX].index = index; + } + } + + // Updating colliding flag on the new tile + var newTile = layer.data[tileY][tileX]; + var collides = layer.collideIndexes.indexOf(newTile.index) !== -1; + SetTileCollision(newTile, collides); + + // Recalculate faces only if the colliding flag at (tileX, tileY) has changed + if (recalculateFaces && (oldTileCollides !== newTile.collides)) + { + CalculateFacesAt(tileX, tileY, layer); + } + + return newTile; +}; + +module.exports = PutTileAt; + + + +/***/ }), +/* 247 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internally used method to keep track of the tile indexes that collide within a layer. This + * updates LayerData.collideIndexes to either contain or not contain the given `tileIndex`. + * + * @function Phaser.Tilemaps.Components.SetLayerCollisionIndex + * @private + * @since 3.0.0 + * + * @param {integer} tileIndex - The tile index to set the collision boolean for. + * @param {boolean} [collides=true] - Should the tile index collide or not? + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetLayerCollisionIndex = function (tileIndex, collides, layer) +{ + var loc = layer.collideIndexes.indexOf(tileIndex); + + if (collides && loc === -1) + { + layer.collideIndexes.push(tileIndex); + } + else if (!collides && loc !== -1) + { + layer.collideIndexes.splice(loc, 1); + } +}; + +module.exports = SetLayerCollisionIndex; + + +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = __webpack_require__(34); +var LayerData = __webpack_require__(116); +var MapData = __webpack_require__(117); +var Tile = __webpack_require__(80); + +/** + * Parses a 2D array of tile indexes into a new MapData object with a single layer. + * + * @function Phaser.Tilemaps.Parsers.Parse2DArray + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {integer[][]} data - 2D array, CSV string or Tiled JSON object. + * @param {integer} tileWidth - The width of a tile in pixels. + * @param {integer} tileHeight - The height of a tile in pixels. + * @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've 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} [description] + */ +var Parse2DArray = function (name, data, tileWidth, tileHeight, insertNull) +{ + var layerData = new LayerData({ + tileWidth: tileWidth, + tileHeight: tileHeight + }); + + var mapData = new MapData({ + name: name, + tileWidth: tileWidth, + tileHeight: tileHeight, + format: Formats.ARRAY_2D, + layers: [ layerData ] + }); + + var tiles = []; + var height = data.length; + var width = 0; + + for (var y = 0; y < data.length; y++) + { + tiles[y] = []; + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var tileIndex = parseInt(row[x], 10); + + if (isNaN(tileIndex) || tileIndex === -1) + { + tiles[y][x] = insertNull + ? null + : new Tile(layerData, -1, x, y, tileWidth, tileHeight); + } + else + { + tiles[y][x] = new Tile(layerData, tileIndex, x, y, tileWidth, tileHeight); + } + } + + if (width === 0) + { + width = row.length; + } + } + + mapData.width = layerData.width = width; + mapData.height = layerData.height = height; + mapData.widthInPixels = layerData.widthInPixels = width * tileWidth; + mapData.heightInPixels = layerData.heightInPixels = height * tileHeight; + layerData.data = tiles; + + return mapData; +}; + +module.exports = Parse2DArray; + + +/***/ }), +/* 249 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FLIPPED_HORIZONTAL = 0x80000000; +var FLIPPED_VERTICAL = 0x40000000; +var FLIPPED_ANTI_DIAGONAL = 0x20000000; // Top-right is swapped with bottom-left corners + +/** + * See Tiled documentation on tile flipping: + * http://docs.mapeditor.org/en/latest/reference/tmx-map-format/ + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseGID + * @since 3.0.0 + * + * @param {number} gid - [description] + * + * @return {object} [description] + */ +var ParseGID = function (gid) +{ + var flippedHorizontal = Boolean(gid & FLIPPED_HORIZONTAL); + var flippedVertical = Boolean(gid & FLIPPED_VERTICAL); + var flippedAntiDiagonal = Boolean(gid & FLIPPED_ANTI_DIAGONAL); + gid = gid & ~(FLIPPED_HORIZONTAL | FLIPPED_VERTICAL | FLIPPED_ANTI_DIAGONAL); + + // Parse the flip flags into something Phaser can use + var rotation = 0; + var flipped = false; + + if (flippedHorizontal && flippedVertical && flippedAntiDiagonal) + { + rotation = Math.PI / 2; + flipped = true; + } + else if (flippedHorizontal && flippedVertical && !flippedAntiDiagonal) + { + rotation = Math.PI; + flipped = false; + } + else if (flippedHorizontal && !flippedVertical && flippedAntiDiagonal) + { + rotation = Math.PI / 2; + flipped = false; + } + else if (flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) + { + rotation = 0; + flipped = true; + } + else if (!flippedHorizontal && flippedVertical && flippedAntiDiagonal) + { + rotation = 3 * Math.PI / 2; + flipped = false; + } + else if (!flippedHorizontal && flippedVertical && !flippedAntiDiagonal) + { + rotation = Math.PI; + flipped = true; + } + else if (!flippedHorizontal && !flippedVertical && flippedAntiDiagonal) + { + rotation = 3 * Math.PI / 2; + flipped = true; + } + else if (!flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) + { + rotation = 0; + flipped = false; + } + + return { + gid: gid, + flippedHorizontal: flippedHorizontal, + flippedVertical: flippedVertical, + flippedAntiDiagonal: flippedAntiDiagonal, + rotation: rotation, + flipped: flipped + }; +}; + +module.exports = ParseGID; + + +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Seth Berrier + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * Parse a Tiled group layer and create a state object for inheriting. + * + * @function Phaser.Tilemaps.Parsers.Tiled.CreateGroupLayer + * @since 3.21.0 + * + * @param {object} json - The Tiled JSON object. + * @param {object} [currentl] - The current group layer from the Tiled JSON file. + * @param {object} [parentstate] - The state of the parent group (if any). + * + * @return {object} A group state object with proper values for updating children layers. + */ +var CreateGroupLayer = function (json, groupl, parentstate) +{ + if (!groupl) + { + // Return a default group state object + return { + i: 0, // Current layer array iterator + layers: json.layers, // Current array of layers + + // Values inherited from parent group + name: '', + opacity: 1, + visible: true, + x: 0, + y: 0 + }; + } + + // Compute group layer x, y + var layerX = groupl.x + GetFastValue(groupl, 'startx', 0) * json.tilewidth + GetFastValue(groupl, 'offsetx', 0); + var layerY = groupl.y + GetFastValue(groupl, 'starty', 0) * json.tileheight + GetFastValue(groupl, 'offsety', 0); + + // Compute next state inherited from group + return { + i: 0, + layers: groupl.layers, + name: parentstate.name + groupl.name + '/', + opacity: parentstate.opacity * groupl.opacity, + visible: parentstate.visible && groupl.visible, + x: parentstate.x + layerX, + y: parentstate.y + layerY + }; +}; + +module.exports = CreateGroupLayer; + + +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Pick = __webpack_require__(524); +var ParseGID = __webpack_require__(249); + +var copyPoints = function (p) { return { x: p.x, y: p.y }; }; + +var commonObjectProps = [ 'id', 'name', 'type', 'rotation', 'properties', 'visible', 'x', 'y', 'width', 'height' ]; + +/** + * Convert a Tiled object to an internal parsed object normalising and copying properties over, while applying optional x and y offsets. The parsed object will always have the properties `id`, `name`, `type`, `rotation`, `properties`, `visible`, `x`, `y`, `width` and `height`. Other properties will be added according to the object type (such as text, polyline, gid etc.) + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseObject + * @since 3.0.0 + * + * @param {object} tiledObject - Tiled object to convert to an internal parsed object normalising and copying properties over. + * @param {number} [offsetX=0] - Optional additional offset to apply to the object's x property. Defaults to 0. + * @param {number} [offsetY=0] - Optional additional offset to apply to the object's y property. Defaults to 0. + * + * @return {object} The parsed object containing properties read from the Tiled object according to it's type with x and y values updated according to the given offsets. + */ +var ParseObject = function (tiledObject, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + var parsedObject = Pick(tiledObject, commonObjectProps); + + parsedObject.x += offsetX; + parsedObject.y += offsetY; + + if (tiledObject.gid) + { + // Object tiles + var gidInfo = ParseGID(tiledObject.gid); + parsedObject.gid = gidInfo.gid; + parsedObject.flippedHorizontal = gidInfo.flippedHorizontal; + parsedObject.flippedVertical = gidInfo.flippedVertical; + parsedObject.flippedAntiDiagonal = gidInfo.flippedAntiDiagonal; + } + else if (tiledObject.polyline) + { + parsedObject.polyline = tiledObject.polyline.map(copyPoints); + } + else if (tiledObject.polygon) + { + parsedObject.polygon = tiledObject.polygon.map(copyPoints); + } + else if (tiledObject.ellipse) + { + parsedObject.ellipse = tiledObject.ellipse; + parsedObject.width = tiledObject.width; + parsedObject.height = tiledObject.height; + } + else if (tiledObject.text) + { + parsedObject.width = tiledObject.width; + parsedObject.height = tiledObject.height; + parsedObject.text = tiledObject.text; + } + else + { + // Otherwise, assume it is a rectangle + parsedObject.rectangle = true; + parsedObject.width = tiledObject.width; + parsedObject.height = tiledObject.height; + } + + return parsedObject; +}; + +module.exports = ParseObject; + + +/***/ }), +/* 252 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = __webpack_require__(34); +var MapData = __webpack_require__(117); +var Parse = __webpack_require__(516); +var Tilemap = __webpack_require__(532); + +/** + * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When + * loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing from + * a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map data. For + * an empty map, you should specify tileWidth, tileHeight, width & height. + * + * @function Phaser.Tilemaps.ParseToTilemap + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Tilemap belongs. + * @param {string} [key] - The key in the Phaser cache that corresponds to the loaded tilemap data. + * @param {integer} [tileWidth=32] - The width of a tile in pixels. + * @param {integer} [tileHeight=32] - The height of a tile in pixels. + * @param {integer} [width=10] - The width of the map in tiles. + * @param {integer} [height=10] - The height of the map in tiles. + * @param {integer[][]} [data] - Instead of loading from the cache, you can also load directly from + * a 2D array of tile indexes. + * @param {boolean} [insertNull=false] - 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've 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.Tilemap} + */ +var ParseToTilemap = function (scene, key, tileWidth, tileHeight, width, height, data, insertNull) +{ + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + if (insertNull === undefined) { insertNull = false; } + + var mapData = null; + + if (Array.isArray(data)) + { + var name = key !== undefined ? key : 'map'; + mapData = Parse(name, Formats.ARRAY_2D, data, tileWidth, tileHeight, insertNull); + } + else if (key !== undefined) + { + var tilemapData = scene.cache.tilemap.get(key); + + if (!tilemapData) + { + console.warn('No map data found for key ' + key); + } + else + { + mapData = Parse(key, tilemapData.format, tilemapData.data, tileWidth, tileHeight, insertNull); + } + } + + if (mapData === null) + { + mapData = new MapData({ + tileWidth: tileWidth, + tileHeight: tileHeight, + width: width, + height: height + }); + } + + return new Tilemap(scene, mapData); +}; + +module.exports = ParseToTilemap; + + +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = __webpack_require__(5); + +/** + * Extracts an array of targets from a Tween configuration object. + * + * The targets will be looked for in a `targets` property. If it's a function, its return value will be used as the result. + * + * @function Phaser.Tweens.Builders.GetTargets + * @since 3.0.0 + * + * @param {object} config - The configuration object to use. + * + * @return {array} An array of targets (may contain only one element), or `null` if no targets were specified. + */ +var GetTargets = function (config) +{ + var targets = GetValue(config, 'targets', null); + + if (targets === null) + { + return targets; + } + + if (typeof targets === 'function') + { + targets = targets.call(); + } + + if (!Array.isArray(targets)) + { + targets = [ targets ]; + } + + return targets; +}; + +module.exports = GetTargets; + + +/***/ }), +/* 254 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function hasGetActive (def) +{ + return (!!def.getActive && typeof def.getActive === 'function'); +} + +/** + * @ignore + */ +function hasGetStart (def) +{ + return (!!def.getStart && typeof def.getStart === 'function'); +} + +/** + * @ignore + */ +function hasGetEnd (def) +{ + return (!!def.getEnd && typeof def.getEnd === 'function'); +} + +/** + * @ignore + */ +function hasGetters (def) +{ + return hasGetStart(def) || hasGetEnd(def) || hasGetActive(def); +} + +/** + * 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. + * + * 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 array of functions, `getActive`, `getStart` and `getEnd`, which return the starting and the ending value of the property based on the provided value. + */ +var GetValueOp = function (key, propertyValue) +{ + var callbacks; + + // The returned value sets what the property will be at the END of the Tween (usually called at the start of the Tween) + var getEnd = function (target, key, value) { return value; }; + + // The returned value sets what the property will be at the START of the Tween (usually called at the end of the Tween) + var getStart = function (target, key, value) { return value; }; + + // What to set the property to the moment the TweenData is invoked + var getActive = null; + + var t = typeof(propertyValue); + + if (t === 'number') + { + // props: { + // x: 400, + // y: 300 + // } + + getEnd = function () + { + return propertyValue; + }; + } + else if (t === 'string') + { + // props: { + // x: '+=400', + // y: '-=300', + // z: '*=2', + // w: '/=2' + // } + + var op = propertyValue[0]; + var num = parseFloat(propertyValue.substr(2)); + + switch (op) + { + case '+': + getEnd = function (target, key, value) + { + return value + num; + }; + break; + + case '-': + getEnd = function (target, key, value) + { + return value - num; + }; + break; + + case '*': + getEnd = function (target, key, value) + { + return value * num; + }; + break; + + case '/': + getEnd = function (target, key, value) + { + return value / num; + }; + break; + + default: + getEnd = function () + { + return parseFloat(propertyValue); + }; + } + } + else if (t === 'function') + { + // The same as setting just the getEnd function and no getStart + + // props: { + // x: function (target, key, value, targetIndex, totalTargets, tween) { return value + 50); }, + // } + + getEnd = propertyValue; + } + else if (t === 'object') + { + if (hasGetters(propertyValue)) + { + /* + x: { + // Called the moment Tween is active. The returned value sets the property on the target immediately. + getActive: function (target, key, value, targetIndex, totalTargets, tween) + { + return value; + }, + + // Called at the start of the Tween. The returned value sets what the property will be at the END of the Tween. + getEnd: function (target, key, value, targetIndex, totalTargets, tween) + { + return value; + }, + + // Called at the end of the Tween. The returned value sets what the property will be at the START of the Tween. + getStart: function (target, key, value, targetIndex, totalTargets, tween) + { + return value; + } + } + */ + + if (hasGetActive(propertyValue)) + { + getActive = propertyValue.getActive; + } + + if (hasGetEnd(propertyValue)) + { + getEnd = propertyValue.getEnd; + } + + if (hasGetStart(propertyValue)) + { + getStart = propertyValue.getStart; + } + } + else if (propertyValue.hasOwnProperty('value')) + { + // 'value' may still be a string, function or a number + // props: { + // x: { value: 400, ... }, + // y: { value: 300, ... } + // } + + callbacks = GetValueOp(key, propertyValue.value); + } + else + { + // 'from' and 'to' may still be a string, function or a number + // props: { + // x: { from: 400, to: 600 }, + // y: { from: 300, to: 500 } + // } + + // Same as above, but the 'start' value is set immediately on the target + // props: { + // x: { start: 400, to: 600 }, + // y: { start: 300, to: 500 } + // } + + // 'start' value is set immediately, then it goes 'from' to 'to' during the tween + // props: { + // x: { start: 200, from: 400, to: 600 }, + // y: { start: 300, from: 300, to: 500 } + // } + + var hasTo = propertyValue.hasOwnProperty('to'); + var hasFrom = propertyValue.hasOwnProperty('from'); + var hasStart = propertyValue.hasOwnProperty('start'); + + if (hasTo && (hasFrom || hasStart)) + { + callbacks = GetValueOp(key, propertyValue.to); + + if (hasStart) + { + var startCallbacks = GetValueOp(key, propertyValue.start); + + callbacks.getActive = startCallbacks.getEnd; + } + + if (hasFrom) + { + var fromCallbacks = GetValueOp(key, propertyValue.from); + + callbacks.getStart = fromCallbacks.getEnd; + } + } + } + } + + // If callback not set by the else if block above then set it here and return it + if (!callbacks) + { + callbacks = { + getActive: getActive, + getEnd: getEnd, + getStart: getStart + }; + } + + return callbacks; +}; + +module.exports = GetValueOp; + + +/***/ }), +/* 255 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Types.Tweens.TweenConfigDefaults + * @since 3.0.0 + * + * @property {(object|object[])} targets - The object, or an array of objects, to run the tween on. + * @property {number} [delay=0] - The number of milliseconds to delay before the tween will start. + * @property {number} [duration=1000] - The duration of the tween in milliseconds. + * @property {string} [ease='Power0'] - The easing equation to use for the tween. + * @property {array} [easeParams] - Optional easing parameters. + * @property {number} [hold=0] - The number of milliseconds to hold the tween for before yoyo'ing. + * @property {number} [repeat=0] - The number of times to repeat the tween. + * @property {number} [repeatDelay=0] - The number of milliseconds to pause before a tween will repeat. + * @property {boolean} [yoyo=false] - Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. + * @property {boolean} [flipX=false] - Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. + * @property {boolean} [flipY=false] - Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. + */ + +var TWEEN_DEFAULTS = { + targets: null, + delay: 0, + duration: 1000, + ease: 'Power0', + easeParams: null, + hold: 0, + repeat: 0, + repeatDelay: 0, + yoyo: false, + flipX: false, + flipY: false +}; + +module.exports = TWEEN_DEFAULTS; + + +/***/ }), +/* 256 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(257); +var GameObjectCreator = __webpack_require__(16); +var GameObjectFactory = __webpack_require__(6); +var TWEEN_CONST = __webpack_require__(100); +var MATH_CONST = __webpack_require__(13); + +/** + * @classdesc + * A Tween is able to manipulate the properties of one or more objects to any given value, based + * on a duration and type of ease. They are rarely instantiated directly and instead should be + * created via the TweenManager. + * + * @class Tween + * @memberof Phaser.Tweens + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - A reference to the parent of this Tween. Either the Tween Manager or a Tween Timeline instance. + * @param {Phaser.Types.Tweens.TweenDataConfig[]} data - An array of TweenData objects, each containing a unique property to be tweened. + * @param {array} targets - An array of targets to be tweened. + */ +var Tween = new Class({ + + Extends: EventEmitter, + + initialize: + + function Tween (parent, data, targets) + { + EventEmitter.call(this); + + /** + * A reference to the parent of this Tween. + * Either the Tween Manager or a Tween Timeline instance. + * + * @name Phaser.Tweens.Tween#parent + * @type {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * Is the parent of this Tween a Timeline? + * + * @name Phaser.Tweens.Tween#parentIsTimeline + * @type {boolean} + * @since 3.0.0 + */ + this.parentIsTimeline = parent.hasOwnProperty('isTimeline'); + + /** + * An array of TweenData objects, each containing a unique property and target being tweened. + * + * @name Phaser.Tweens.Tween#data + * @type {Phaser.Types.Tweens.TweenDataConfig[]} + * @since 3.0.0 + */ + this.data = data; + + /** + * The cached length of the data array. + * + * @name Phaser.Tweens.Tween#totalData + * @type {integer} + * @since 3.0.0 + */ + this.totalData = data.length; + + /** + * An array of references to the target/s this Tween is operating on. + * + * @name Phaser.Tweens.Tween#targets + * @type {object[]} + * @since 3.0.0 + */ + this.targets = targets; + + /** + * Cached target total (not necessarily the same as the data total) + * + * @name Phaser.Tweens.Tween#totalTargets + * @type {integer} + * @since 3.0.0 + */ + this.totalTargets = targets.length; + + /** + * If `true` then duration, delay, etc values are all frame totals. + * + * @name Phaser.Tweens.Tween#useFrames + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.useFrames = false; + + /** + * Scales the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * Value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. + * + * @name Phaser.Tweens.Tween#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Loop this tween? Can be -1 for an infinite loop, or an integer. + * When enabled it will play through ALL TweenDatas again. Use TweenData.repeat to loop a single element. + * + * @name Phaser.Tweens.Tween#loop + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loop = 0; + + /** + * Time in ms/frames before the tween loops. + * + * @name Phaser.Tweens.Tween#loopDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopDelay = 0; + + /** + * How many loops are left to run? + * + * @name Phaser.Tweens.Tween#loopCounter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopCounter = 0; + + /** + * Time in ms/frames before the 'onStart' event fires. + * This is the shortest `delay` value across all of the TweenDatas of this Tween. + * + * @name Phaser.Tweens.Tween#startDelay + * @type {number} + * @default 0 + * @since 3.19.0 + */ + this.startDelay = 0; + + /** + * Has this Tween started playback yet? + * This boolean is toggled when the Tween leaves the 'delayed' state and starts running. + * + * @name Phaser.Tweens.Tween#hasStarted + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this.hasStarted = false; + + /** + * Is this Tween currently seeking? + * This boolean is toggled in the `Tween.seek` method. + * When a tween is seeking it will not dispatch any events or callbacks. + * + * @name Phaser.Tweens.Tween#isSeeking + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this.isSeeking = false; + + /** + * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = -1 (as it never completes) + * + * @name Phaser.Tweens.Tween#completeDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.completeDelay = 0; + + /** + * Countdown timer (used by timeline offset, loopDelay and completeDelay) + * + * @name Phaser.Tweens.Tween#countdown + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.countdown = 0; + + /** + * Set only if this Tween is part of a Timeline. + * + * @name Phaser.Tweens.Tween#offset + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.offset = 0; + + /** + * Set only if this Tween is part of a Timeline. The calculated offset amount. + * + * @name Phaser.Tweens.Tween#calculatedOffset + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.calculatedOffset = 0; + + /** + * The current state of the tween + * + * @name Phaser.Tweens.Tween#state + * @type {integer} + * @since 3.0.0 + */ + this.state = TWEEN_CONST.PENDING_ADD; + + /** + * The state of the tween when it was paused (used by Resume) + * + * @name Phaser.Tweens.Tween#_pausedState + * @type {integer} + * @private + * @since 3.0.0 + */ + this._pausedState = TWEEN_CONST.INIT; + + /** + * Does the Tween start off paused? (if so it needs to be started with Tween.play) + * + * @name Phaser.Tweens.Tween#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * Elapsed time in ms/frames of this run through the Tween. + * + * @name Phaser.Tweens.Tween#elapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.elapsed = 0; + + /** + * Total elapsed time in ms/frames of the entire Tween, including looping. + * + * @name Phaser.Tweens.Tween#totalElapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalElapsed = 0; + + /** + * Time in ms/frames for the whole Tween to play through once, excluding loop amounts and loop delays. + * + * @name Phaser.Tweens.Tween#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * Value between 0 and 1. The amount through the Tween, excluding loops. + * + * @name Phaser.Tweens.Tween#progress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.progress = 0; + + /** + * Time in ms/frames for the Tween to complete (including looping) + * + * @name Phaser.Tweens.Tween#totalDuration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalDuration = 0; + + /** + * Value between 0 and 1. The amount through the entire Tween, including looping. + * + * @name Phaser.Tweens.Tween#totalProgress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalProgress = 0; + + /** + * An object containing the different Tween callback functions. + * + * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. + * + * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. + * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. + * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. + * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. + * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. + * `onUpdate` When a TweenData updates a property on a source target during playback. + * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. + * + * @name Phaser.Tweens.Tween#callbacks + * @type {object} + * @since 3.0.0 + */ + this.callbacks = { + onActive: null, + onComplete: null, + onLoop: null, + onRepeat: null, + onStart: null, + onUpdate: null, + onYoyo: null + }; + + /** + * The context in which all callbacks are invoked. + * + * @name Phaser.Tweens.Tween#callbackScope + * @type {any} + * @since 3.0.0 + */ + this.callbackScope; + }, + + /** + * Returns the current value of the specified Tween Data. + * + * @method Phaser.Tweens.Tween#getValue + * @since 3.0.0 + * + * @param {integer} [index=0] - The Tween Data to return the value from. + * + * @return {number} The value of the requested Tween Data. + */ + getValue: function (index) + { + if (index === undefined) { index = 0; } + + return this.data[index].current; + }, + + /** + * Set the scale the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * + * @method Phaser.Tweens.Tween#setTimeScale + * @since 3.0.0 + * + * @param {number} value - The scale factor for timescale. + * + * @return {this} - This Tween instance. + */ + setTimeScale: function (value) + { + this.timeScale = value; + + return this; + }, + + /** + * Returns the scale of the time applied to this Tween. + * + * @method Phaser.Tweens.Tween#getTimeScale + * @since 3.0.0 + * + * @return {number} The timescale of this tween (between 0 and 1) + */ + getTimeScale: function () + { + return this.timeScale; + }, + + /** + * Checks if the Tween is currently active. + * + * @method Phaser.Tweens.Tween#isPlaying + * @since 3.0.0 + * + * @return {boolean} `true` if the Tween is active, otherwise `false`. + */ + isPlaying: function () + { + return (this.state === TWEEN_CONST.ACTIVE); + }, + + /** + * Checks if the Tween is currently paused. + * + * @method Phaser.Tweens.Tween#isPaused + * @since 3.0.0 + * + * @return {boolean} `true` if the Tween is paused, otherwise `false`. + */ + isPaused: function () + { + return (this.state === TWEEN_CONST.PAUSED); + }, + + /** + * See if this Tween is currently acting upon the given target. + * + * @method Phaser.Tweens.Tween#hasTarget + * @since 3.0.0 + * + * @param {object} target - The target to check against this Tween. + * + * @return {boolean} `true` if the given target is a target of this Tween, otherwise `false`. + */ + hasTarget: function (target) + { + return (this.targets.indexOf(target) !== -1); + }, + + /** + * Updates the 'end' value of the given property across all matching targets. + * + * Calling this does not adjust the duration of the tween, or the current progress. + * + * You can optionally tell it to set the 'start' value to be the current value (before the change). + * + * @method Phaser.Tweens.Tween#updateTo + * @since 3.0.0 + * + * @param {string} key - The property to set the new value for. + * @param {*} value - The new value of the property. + * @param {boolean} [startToCurrent=false] - Should this change set the start value to be the current value? + * + * @return {this} - This Tween instance. + */ + updateTo: function (key, value, startToCurrent) + { + if (startToCurrent === undefined) { startToCurrent = false; } + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = this.data[i]; + + if (tweenData.key === key) + { + tweenData.end = value; + + if (startToCurrent) + { + tweenData.start = tweenData.current; + } + } + } + + return this; + }, + + /** + * Restarts the tween from the beginning. + * + * @method Phaser.Tweens.Tween#restart + * @since 3.0.0 + * + * @return {this} This Tween instance. + */ + restart: function () + { + // Reset these so they're ready for the next update + this.elapsed = 0; + this.progress = 0; + this.totalElapsed = 0; + this.totalProgress = 0; + + if (this.state === TWEEN_CONST.ACTIVE) + { + return this.seek(0); + } + else if (this.state === TWEEN_CONST.REMOVED) + { + this.seek(0); + this.parent.makeActive(this); + + return this; + } + else if (this.state === TWEEN_CONST.PENDING_ADD) + { + return this; + } + else + { + return this.play(); + } + }, + + /** + * Internal method that calculates the overall duration of the Tween. + * + * @method Phaser.Tweens.Tween#calcDuration + * @since 3.0.0 + */ + calcDuration: function () + { + var maxDuration = 0; + var minDelay = MATH_CONST.MAX_SAFE_INTEGER; + + var data = this.data; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = data[i]; + + // Set t1 (duration + hold + yoyo) + tweenData.t1 = tweenData.duration + tweenData.hold; + + if (tweenData.yoyo) + { + tweenData.t1 += tweenData.duration; + } + + // Set t2 (repeatDelay + duration + hold + yoyo) + tweenData.t2 = tweenData.t1 + tweenData.repeatDelay; + + // Total Duration + tweenData.totalDuration = tweenData.delay + tweenData.t1; + + if (tweenData.repeat === -1) + { + tweenData.totalDuration += (tweenData.t2 * 999999999999); + } + else if (tweenData.repeat > 0) + { + tweenData.totalDuration += (tweenData.t2 * tweenData.repeat); + } + + if (tweenData.totalDuration > maxDuration) + { + // Get the longest TweenData from the Tween, used to calculate the Tween TD + maxDuration = tweenData.totalDuration; + } + + if (tweenData.delay < minDelay) + { + minDelay = tweenData.delay; + } + } + + // Excludes loop values + + // If duration has been set to 0 then we give it a super-low value so that it always + // renders at least 1 frame, but no more, without causing divided by zero errors elsewhere. + this.duration = Math.max(maxDuration, 0.001); + + this.loopCounter = (this.loop === -1) ? 999999999999 : this.loop; + + if (this.loopCounter > 0) + { + this.totalDuration = this.duration + this.completeDelay + ((this.duration + this.loopDelay) * this.loopCounter); + } + else + { + this.totalDuration = this.duration + this.completeDelay; + } + + // How long before this Tween starts playback? + this.startDelay = minDelay; + }, + + /** + * Called by TweenManager.preUpdate as part of its loop to check pending and active tweens. + * Should not be called directly. + * + * @method Phaser.Tweens.Tween#init + * @since 3.0.0 + * + * @return {boolean} Returns `true` if this Tween should be moved from the pending list to the active list by the Tween Manager. + */ + init: function () + { + // You can't have a paused Tween if it's part of a Timeline + if (this.paused && !this.parentIsTimeline) + { + this.state = TWEEN_CONST.PENDING_ADD; + this._pausedState = TWEEN_CONST.INIT; + + return false; + } + + var data = this.data; + var totalTargets = this.totalTargets; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = data[i]; + var target = tweenData.target; + var gen = tweenData.gen; + var key = tweenData.key; + var targetIndex = tweenData.index; + + // Old function signature: i, totalTargets, target + // New function signature: target, key, value, index, total, tween + + tweenData.delay = gen.delay(target, key, 0, targetIndex, totalTargets, this); + tweenData.duration = Math.max(gen.duration(target, key, 0, targetIndex, totalTargets, this), 0.001); + tweenData.hold = gen.hold(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeat = gen.repeat(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeatDelay = gen.repeatDelay(target, key, 0, targetIndex, totalTargets, this); + } + + this.calcDuration(); + + this.progress = 0; + this.totalProgress = 0; + this.elapsed = 0; + this.totalElapsed = 0; + + this.state = TWEEN_CONST.INIT; + + return true; + }, + + /** + * Internal method that makes this Tween active within the TweenManager + * and emits the onActive event and callback. + * + * @method Phaser.Tweens.Tween#makeActive + * @fires Phaser.Tweens.Events#TWEEN_ACTIVE + * @since 3.19.0 + */ + makeActive: function () + { + this.parent.makeActive(this); + + this.dispatchTweenEvent(Events.TWEEN_ACTIVE, this.callbacks.onActive); + }, + + /** + * Internal method that advances to the next state of the Tween during playback. + * + * @method Phaser.Tweens.Tween#nextState + * @fires Phaser.Tweens.Events#TWEEN_COMPLETE + * @fires Phaser.Tweens.Events#TWEEN_LOOP + * @since 3.0.0 + */ + nextState: function () + { + if (this.loopCounter > 0) + { + this.elapsed = 0; + this.progress = 0; + this.loopCounter--; + + this.resetTweenData(true); + + if (this.loopDelay > 0) + { + this.countdown = this.loopDelay; + this.state = TWEEN_CONST.LOOP_DELAY; + } + else + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTweenEvent(Events.TWEEN_LOOP, this.callbacks.onLoop); + } + } + else if (this.completeDelay > 0) + { + this.state = TWEEN_CONST.COMPLETE_DELAY; + + this.countdown = this.completeDelay; + } + else + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); + } + }, + + /** + * Pauses the Tween immediately. Use `resume` to continue playback. + * + * @method Phaser.Tweens.Tween#pause + * @since 3.0.0 + * + * @return {this} - This Tween instance. + */ + pause: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + return this; + } + + this.paused = true; + + this._pausedState = this.state; + + this.state = TWEEN_CONST.PAUSED; + + return this; + }, + + /** + * Starts a Tween playing. + * + * You only need to call this method if you have configured the tween to be paused on creation. + * + * If the Tween is already playing, calling this method again will have no effect. If you wish to + * restart the Tween, use `Tween.restart` instead. + * + * Calling this method after the Tween has completed will start the Tween playing again from the start. + * This is the same as calling `Tween.seek(0)` and then `Tween.play()`. + * + * @method Phaser.Tweens.Tween#play + * @since 3.0.0 + * + * @param {boolean} [resetFromTimeline=false] - Is this Tween being played as part of a Timeline? + * + * @return {this} This Tween instance. + */ + play: function (resetFromTimeline) + { + if (resetFromTimeline === undefined) { resetFromTimeline = false; } + + var state = this.state; + + if (state === TWEEN_CONST.INIT && !this.parentIsTimeline) + { + this.resetTweenData(false); + + this.state = TWEEN_CONST.ACTIVE; + + return this; + } + else if (state === TWEEN_CONST.ACTIVE || (state === TWEEN_CONST.PENDING_ADD && this._pausedState === TWEEN_CONST.PENDING_ADD)) + { + return this; + } + else if (!this.parentIsTimeline && (state === TWEEN_CONST.PENDING_REMOVE || state === TWEEN_CONST.REMOVED)) + { + this.seek(0); + this.parent.makeActive(this); + + return this; + } + + if (this.parentIsTimeline) + { + this.resetTweenData(resetFromTimeline); + + if (this.calculatedOffset === 0) + { + this.state = TWEEN_CONST.ACTIVE; + } + else + { + this.countdown = this.calculatedOffset; + + this.state = TWEEN_CONST.OFFSET_DELAY; + } + } + else if (this.paused) + { + this.paused = false; + + this.makeActive(); + } + else + { + this.resetTweenData(resetFromTimeline); + + this.state = TWEEN_CONST.ACTIVE; + + this.makeActive(); + } + + return this; + }, + + /** + * Internal method that resets all of the Tween Data, including the progress and elapsed values. + * + * @method Phaser.Tweens.Tween#resetTweenData + * @since 3.0.0 + * + * @param {boolean} resetFromLoop - Has this method been called as part of a loop? + */ + resetTweenData: function (resetFromLoop) + { + var data = this.data; + var total = this.totalData; + var totalTargets = this.totalTargets; + + for (var i = 0; i < total; i++) + { + var tweenData = data[i]; + + var target = tweenData.target; + var key = tweenData.key; + var targetIndex = tweenData.index; + + tweenData.progress = 0; + tweenData.elapsed = 0; + + tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; + + if (resetFromLoop) + { + tweenData.start = tweenData.getStartValue(target, key, tweenData.start, targetIndex, totalTargets, this); + + tweenData.end = tweenData.getEndValue(target, key, tweenData.end, targetIndex, totalTargets, this); + + tweenData.current = tweenData.start; + + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + } + else + { + tweenData.state = TWEEN_CONST.PENDING_RENDER; + } + + if (tweenData.delay > 0) + { + tweenData.elapsed = tweenData.delay; + + tweenData.state = TWEEN_CONST.DELAY; + } + + if (tweenData.getActiveValue) + { + target[key] = tweenData.getActiveValue(tweenData.target, tweenData.key, tweenData.start); + } + } + }, + + /** + * Resumes the playback of a previously paused Tween. + * + * @method Phaser.Tweens.Tween#resume + * @since 3.0.0 + * + * @return {this} - This Tween instance. + */ + resume: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + this.paused = false; + + this.state = this._pausedState; + } + else + { + this.play(); + } + + return this; + }, + + /** + * Seeks to a specific point in the Tween. + * + * **Note:** You cannot seek a Tween that repeats or loops forever, or that has an unusually long total duration. + * + * The given position is a value between 0 and 1 which represents how far through the Tween to seek to. + * A value of 0.5 would seek to half-way through the Tween, where-as a value of zero would seek to the start. + * + * Note that the seek 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 0.5 would seek to 3 seconds into the Tween, as that's half-way through its _entire_ duration. + * + * 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. + * + * @method Phaser.Tweens.Tween#seek + * @since 3.0.0 + * + * @param {number} toPosition - A value between 0 and 1 which represents the progress point to seek to. + * @param {number} [delta=16.6] - The size of each step when seeking through the Tween. A higher value completes faster but at a cost of less precision. + * + * @return {this} This Tween instance. + */ + seek: function (toPosition, delta) + { + if (delta === undefined) { delta = 16.6; } + + if (this.totalDuration >= 3600000) + { + console.warn('Tween.seek duration too long'); + + return this; + } + + if (this.state === TWEEN_CONST.REMOVED) + { + this.makeActive(); + } + + this.elapsed = 0; + this.progress = 0; + this.totalElapsed = 0; + this.totalProgress = 0; + + var data = this.data; + var totalTargets = this.totalTargets; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = data[i]; + var target = tweenData.target; + var gen = tweenData.gen; + var key = tweenData.key; + var targetIndex = tweenData.index; + + tweenData.progress = 0; + tweenData.elapsed = 0; + + tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; + + // Old function signature: i, totalTargets, target + // New function signature: target, key, value, index, total, tween + + tweenData.delay = gen.delay(target, key, 0, targetIndex, totalTargets, this); + tweenData.duration = Math.max(gen.duration(target, key, 0, targetIndex, totalTargets, this), 0.001); + tweenData.hold = gen.hold(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeat = gen.repeat(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeatDelay = gen.repeatDelay(target, key, 0, targetIndex, totalTargets, this); + + tweenData.current = tweenData.start; + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + + this.updateTweenData(this, tweenData, 0, targetIndex, totalTargets); + + if (tweenData.delay > 0) + { + tweenData.elapsed = tweenData.delay; + tweenData.state = TWEEN_CONST.DELAY; + } + } + + this.calcDuration(); + + var wasPaused = false; + + if (this.state === TWEEN_CONST.PAUSED) + { + wasPaused = true; + + this.state = TWEEN_CONST.ACTIVE; + } + + this.isSeeking = true; + + do + { + this.update(0, delta); + + } while (this.totalProgress < toPosition); + + this.isSeeking = false; + + if (wasPaused) + { + this.state = TWEEN_CONST.PAUSED; + } + + return this; + }, + + /** + * Sets an event based callback to be invoked during playback. + * + * Calling this method will replace a previously set callback for the given type, if any exists. + * + * The types available are: + * + * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. + * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. + * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. + * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. + * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. + * `onUpdate` When a TweenData updates a property on a source target during playback. + * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. + * + * @method Phaser.Tweens.Tween#setCallback + * @since 3.0.0 + * + * @param {string} type - Type of the callback to set. + * @param {function} callback - The function to invoke when this callback happens. + * @param {array} [params] - An array of parameters for specified callbacks types. + * @param {any} [scope] - The context the callback will be invoked in. + * + * @return {this} This Tween instance. + */ + setCallback: function (type, callback, params, scope) + { + this.callbacks[type] = { func: callback, scope: scope, params: params }; + + return this; + }, + + /** + * Flags the Tween as being complete, whatever stage of progress it is at. + * + * If an onComplete callback has been defined it will automatically invoke it, unless a `delay` + * argument is provided, in which case the Tween will delay for that period of time before calling the callback. + * + * If you don't need a delay, or have an onComplete callback, then call `Tween.stop` instead. + * + * @method Phaser.Tweens.Tween#complete + * @fires Phaser.Tweens.Events#TWEEN_COMPLETE + * @since 3.2.0 + * + * @param {number} [delay=0] - The time to wait before invoking the complete callback. If zero it will fire immediately. + * + * @return {this} This Tween instance. + */ + complete: function (delay) + { + if (delay === undefined) { delay = 0; } + + if (delay) + { + this.state = TWEEN_CONST.COMPLETE_DELAY; + + this.countdown = delay; + } + else + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); + } + + return this; + }, + + /** + * Immediately removes this Tween from the TweenManager and all of its internal arrays, + * no matter what stage it as it. Then sets the tween state to `REMOVED`. + * + * You should dispose of your reference to this tween after calling this method, to + * free it from memory. + * + * @method Phaser.Tweens.Tween#remove + * @since 3.17.0 + * + * @return {this} This Tween instance. + */ + remove: function () + { + this.parent.remove(this); + + return this; + }, + + /** + * Stops the Tween immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. + * + * @method Phaser.Tweens.Tween#stop + * @since 3.0.0 + * + * @param {number} [resetTo] - If you want to seek the tween, provide a value between 0 and 1. + * + * @return {this} This Tween instance. + */ + stop: function (resetTo) + { + if (this.state === TWEEN_CONST.ACTIVE) + { + if (resetTo !== undefined) + { + this.seek(resetTo); + } + } + + if (this.state !== TWEEN_CONST.REMOVED) + { + if (this.state === TWEEN_CONST.PAUSED || this.state === TWEEN_CONST.PENDING_ADD) + { + if (this.parentIsTimeline) + { + this.parent.manager._destroy.push(this); + this.parent.manager._toProcess++; + } + else + { + this.parent._destroy.push(this); + this.parent._toProcess++; + } + } + + this.removeAllListeners(); + + this.state = TWEEN_CONST.PENDING_REMOVE; + } + + return this; + }, + + /** + * 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} timestamp - 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} Returns `true` if this Tween has finished and should be removed from the Tween Manager, otherwise returns `false`. + */ + update: function (timestamp, delta) + { + if (this.state === TWEEN_CONST.PAUSED) + { + return false; + } + + if (this.useFrames) + { + delta = 1 * this.parent.timeScale; + } + + delta *= this.timeScale; + + this.elapsed += delta; + this.progress = Math.min(this.elapsed / this.duration, 1); + + this.totalElapsed += delta; + this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); + + switch (this.state) + { + case TWEEN_CONST.ACTIVE: + + if (!this.hasStarted && !this.isSeeking) + { + this.startDelay -= delta; + + if (this.startDelay <= 0) + { + this.hasStarted = true; + + this.dispatchTweenEvent(Events.TWEEN_START, this.callbacks.onStart); + } + } + + var stillRunning = false; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = this.data[i]; + + if (this.updateTweenData(this, tweenData, delta)) + { + stillRunning = true; + } + } + + // Anything still running? If not, we're done + if (!stillRunning) + { + this.nextState(); + } + + break; + + case TWEEN_CONST.LOOP_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTweenEvent(Events.TWEEN_LOOP, this.callbacks.onLoop); + } + + break; + + case TWEEN_CONST.OFFSET_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.ACTIVE; + } + + break; + + case TWEEN_CONST.COMPLETE_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); + } + + break; + } + + return (this.state === TWEEN_CONST.PENDING_REMOVE); + }, + + /** + * Internal method that will emit a TweenData based Event and invoke the given callback. + * + * @method Phaser.Tweens.Tween#dispatchTweenDataEvent + * @since 3.19.0 + * + * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. + * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData object that caused this event. + */ + dispatchTweenDataEvent: function (event, callback, tweenData) + { + if (!this.isSeeking) + { + this.emit(event, this, tweenData.key, tweenData.target, tweenData.current, tweenData.previous); + + if (callback) + { + callback.params[1] = tweenData.target; + + callback.func.apply(callback.scope, callback.params); + } + } + }, + + /** + * Internal method that will emit a Tween based Event and invoke the given callback. + * + * @method Phaser.Tweens.Tween#dispatchTweenEvent + * @since 3.19.0 + * + * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. + * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. + */ + dispatchTweenEvent: function (event, callback) + { + if (!this.isSeeking) + { + this.emit(event, this, this.targets); + + if (callback) + { + callback.params[1] = this.targets; + + callback.func.apply(callback.scope, callback.params); + } + } + }, + + /** + * Internal method used as part of the playback process that sets a tween to play in reverse. + * + * @method Phaser.Tweens.Tween#setStateFromEnd + * @fires Phaser.Tweens.Events#TWEEN_REPEAT + * @fires Phaser.Tweens.Events#TWEEN_YOYO + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to update. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. + * @param {number} diff - Any extra time that needs to be accounted for in the elapsed and progress values. + * + * @return {integer} The state of this Tween. + */ + setStateFromEnd: function (tween, tweenData, diff) + { + if (tweenData.yoyo) + { + // We've hit the end of a Playing Forward TweenData and we have a yoyo + + // Account for any extra time we got from the previous frame + tweenData.elapsed = diff; + tweenData.progress = diff / tweenData.duration; + + if (tweenData.flipX) + { + tweenData.target.toggleFlipX(); + } + + if (tweenData.flipY) + { + tweenData.target.toggleFlipY(); + } + + this.dispatchTweenDataEvent(Events.TWEEN_YOYO, tween.callbacks.onYoyo, tweenData); + + tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + return TWEEN_CONST.PLAYING_BACKWARD; + } + else if (tweenData.repeatCounter > 0) + { + // We've hit the end of a Playing Forward TweenData and we have a Repeat. + // So we're going to go right back to the start to repeat it again. + + tweenData.repeatCounter--; + + // Account for any extra time we got from the previous frame + tweenData.elapsed = diff; + tweenData.progress = diff / tweenData.duration; + + if (tweenData.flipX) + { + tweenData.target.toggleFlipX(); + } + + if (tweenData.flipY) + { + tweenData.target.toggleFlipY(); + } + + tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + // Delay? + if (tweenData.repeatDelay > 0) + { + tweenData.elapsed = tweenData.repeatDelay - diff; + + tweenData.current = tweenData.start; + + tweenData.target[tweenData.key] = tweenData.current; + + return TWEEN_CONST.REPEAT_DELAY; + } + else + { + this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); + + return TWEEN_CONST.PLAYING_FORWARD; + } + } + + return TWEEN_CONST.COMPLETE; + }, + + /** + * Internal method used as part of the playback process that sets a tween to play from the start. + * + * @method Phaser.Tweens.Tween#setStateFromStart + * @fires Phaser.Tweens.Events#TWEEN_REPEAT + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to update. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. + * @param {number} diff - Any extra time that needs to be accounted for in the elapsed and progress values. + * + * @return {integer} The state of this Tween. + */ + setStateFromStart: function (tween, tweenData, diff) + { + if (tweenData.repeatCounter > 0) + { + tweenData.repeatCounter--; + + // Account for any extra time we got from the previous frame + tweenData.elapsed = diff; + tweenData.progress = diff / tweenData.duration; + + if (tweenData.flipX) + { + tweenData.target.toggleFlipX(); + } + + if (tweenData.flipY) + { + tweenData.target.toggleFlipY(); + } + + tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + // Delay? + if (tweenData.repeatDelay > 0) + { + tweenData.elapsed = tweenData.repeatDelay - diff; + + tweenData.current = tweenData.start; + + tweenData.target[tweenData.key] = tweenData.current; + + return TWEEN_CONST.REPEAT_DELAY; + } + else + { + this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); + + return TWEEN_CONST.PLAYING_FORWARD; + } + } + + return TWEEN_CONST.COMPLETE; + }, + + /** + * Internal method that advances the TweenData based on the time value given. + * + * @method Phaser.Tweens.Tween#updateTweenData + * @fires Phaser.Tweens.Events#TWEEN_UPDATE + * @fires Phaser.Tweens.Events#TWEEN_REPEAT + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to update. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. + * @param {number} delta - Either a value in ms, or 1 if Tween.useFrames is true. + * + * @return {boolean} True if the tween is not complete (e.g., playing), or false if the tween is complete. + */ + updateTweenData: function (tween, tweenData, delta) + { + var target = tweenData.target; + + switch (tweenData.state) + { + case TWEEN_CONST.PLAYING_FORWARD: + case TWEEN_CONST.PLAYING_BACKWARD: + + if (!target) + { + tweenData.state = TWEEN_CONST.COMPLETE; + break; + } + + var elapsed = tweenData.elapsed; + var duration = tweenData.duration; + var diff = 0; + + elapsed += delta; + + if (elapsed > duration) + { + diff = elapsed - duration; + elapsed = duration; + } + + var forward = (tweenData.state === TWEEN_CONST.PLAYING_FORWARD); + var progress = elapsed / duration; + + tweenData.elapsed = elapsed; + tweenData.progress = progress; + tweenData.previous = tweenData.current; + + if (progress === 1) + { + if (forward) + { + tweenData.current = tweenData.end; + target[tweenData.key] = tweenData.end; + + if (tweenData.hold > 0) + { + tweenData.elapsed = tweenData.hold - diff; + + tweenData.state = TWEEN_CONST.HOLD_DELAY; + } + else + { + tweenData.state = this.setStateFromEnd(tween, tweenData, diff); + } + } + else + { + tweenData.current = tweenData.start; + target[tweenData.key] = tweenData.start; + + tweenData.state = this.setStateFromStart(tween, tweenData, diff); + } + } + else + { + var v = (forward) ? tweenData.ease(progress) : tweenData.ease(1 - progress); + + tweenData.current = tweenData.start + ((tweenData.end - tweenData.start) * v); + + target[tweenData.key] = tweenData.current; + } + + this.dispatchTweenDataEvent(Events.TWEEN_UPDATE, tween.callbacks.onUpdate, tweenData); + + break; + + case TWEEN_CONST.DELAY: + + tweenData.elapsed -= delta; + + if (tweenData.elapsed <= 0) + { + tweenData.elapsed = Math.abs(tweenData.elapsed); + + tweenData.state = TWEEN_CONST.PENDING_RENDER; + } + + break; + + case TWEEN_CONST.REPEAT_DELAY: + + tweenData.elapsed -= delta; + + if (tweenData.elapsed <= 0) + { + tweenData.elapsed = Math.abs(tweenData.elapsed); + + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + + this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); + } + + break; + + case TWEEN_CONST.HOLD_DELAY: + + tweenData.elapsed -= delta; + + if (tweenData.elapsed <= 0) + { + tweenData.state = this.setStateFromEnd(tween, tweenData, Math.abs(tweenData.elapsed)); + } + + break; + + case TWEEN_CONST.PENDING_RENDER: + + if (target) + { + tweenData.start = tweenData.getStartValue(target, tweenData.key, target[tweenData.key], tweenData.index, tween.totalTargets, tween); + + tweenData.end = tweenData.getEndValue(target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + tweenData.current = tweenData.start; + + target[tweenData.key] = tweenData.start; + + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + } + else + { + tweenData.state = TWEEN_CONST.COMPLETE; + } + + break; + } + + // Return TRUE if this TweenData still playing, otherwise return FALSE + return (tweenData.state !== TWEEN_CONST.COMPLETE); + } + +}); + +// onActive = 'active' event = When the Tween is moved from the pending to the active list in the manager, even if playback delayed +// onStart = 'start' event = When the Tween starts playing from a delayed state (will happen same time as onActive if no delay) +// onYoyo = 'yoyo' event = When the Tween starts a yoyo +// onRepeat = 'repeat' event = When a TweenData repeats playback (if any) +// onComplete = 'complete' event = When the Tween finishes all playback (can sometimes never happen if repeat -1), also when 'stop' called +// onUpdate = 'update' event = When the Tween updates a TweenData during playback (expensive!) +// onLoop = 'loop' event = Used to loop ALL TweenDatas in a Tween + +Tween.TYPES = [ + 'onActive', + 'onComplete', + 'onLoop', + 'onRepeat', + 'onStart', + 'onUpdate', + 'onYoyo' +]; + +/** + * Creates a new Tween object. + * + * Note: This method will only be available if Tweens have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#tween + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The Tween configuration. + * + * @return {Phaser.Tweens.Tween} The Tween that was created. + */ +GameObjectFactory.register('tween', function (config) +{ + return this.scene.sys.tweens.add(config); +}); + +// 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 + +/** + * Creates a new Tween object and returns it. + * + * Note: This method will only be available if Tweens have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#tween + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The Tween configuration. + * + * @return {Phaser.Tweens.Tween} The Tween that was created. + */ +GameObjectCreator.register('tween', function (config) +{ + return this.scene.sys.tweens.create(config); +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + +module.exports = Tween; + + +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tweens.Events + */ + +module.exports = { + + TIMELINE_COMPLETE: __webpack_require__(1434), + TIMELINE_LOOP: __webpack_require__(1435), + TIMELINE_PAUSE: __webpack_require__(1436), + TIMELINE_RESUME: __webpack_require__(1437), + TIMELINE_START: __webpack_require__(1438), + TIMELINE_UPDATE: __webpack_require__(1439), + TWEEN_ACTIVE: __webpack_require__(1440), + TWEEN_COMPLETE: __webpack_require__(1441), + TWEEN_LOOP: __webpack_require__(1442), + TWEEN_REPEAT: __webpack_require__(1443), + TWEEN_START: __webpack_require__(1444), + TWEEN_UPDATE: __webpack_require__(1445), + TWEEN_YOYO: __webpack_require__(1446) + +}; + + +/***/ }), +/* 258 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns a TweenDataConfig object that describes the tween data for a unique property of a unique target. + * A single Tween consists of multiple TweenDatas, depending on how many properties are being changed by the Tween. + * + * This is an internal function used by the TweenBuilder and should not be accessed directly, instead, + * Tweens should be created using the GameObjectFactory or GameObjectCreator. + * + * @function Phaser.Tweens.TweenData + * @since 3.0.0 + * + * @param {any} target - The target to tween. + * @param {integer} index - The target index within the Tween targets array. + * @param {string} key - The property of the target to tween. + * @param {function} getEnd - What the property will be at the END of the Tween. + * @param {function} getStart - What the property will be at the START of the Tween. + * @param {?function} getActive - If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. + * @param {function} ease - The ease function this tween uses. + * @param {number} delay - Time in ms/frames before tween will start. + * @param {number} duration - Duration of the tween in ms/frames. + * @param {boolean} yoyo - Determines whether the tween should return back to its start value after hold has expired. + * @param {number} hold - Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. + * @param {number} repeat - Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + * @param {number} repeatDelay - Time in ms/frames before the repeat will start. + * @param {boolean} flipX - Should toggleFlipX be called when yoyo or repeat happens? + * @param {boolean} flipY - Should toggleFlipY be called when yoyo or repeat happens? + * + * @return {Phaser.Types.Tweens.TweenDataConfig} The config object describing this TweenData. + */ +var TweenData = function (target, index, key, getEnd, getStart, getActive, ease, delay, duration, yoyo, hold, repeat, repeatDelay, flipX, flipY) +{ + return { + + // The target to tween + target: target, + + // The index of the target within the tween targets array + index: index, + + // The property of the target to tween + key: key, + + // What to set the property to the moment the TweenData is invoked. + getActiveValue: getActive, + + // The returned value sets what the property will be at the END of the Tween. + getEndValue: getEnd, + + // The returned value sets what the property will be at the START of the Tween. + getStartValue: getStart, + + // The ease function this tween uses. + ease: ease, + + // Duration of the tween in ms/frames, excludes time for yoyo or repeats. + duration: 0, + + // The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) + totalDuration: 0, + + // Time in ms/frames before tween will start. + delay: 0, + + // Cause the tween to return back to its start value after hold has expired. + yoyo: yoyo, + + // Time in ms/frames the tween will pause before running the yoyo or starting a repeat. + hold: 0, + + // Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + repeat: 0, + + // Time in ms/frames before the repeat will start. + repeatDelay: 0, + + // Automatically call toggleFlipX when the TweenData yoyos or repeats + flipX: flipX, + + // Automatically call toggleFlipY when the TweenData yoyos or repeats + flipY: flipY, + + // Between 0 and 1 showing completion of this TweenData. + progress: 0, + + // Delta counter. + elapsed: 0, + + // How many repeats are left to run? + repeatCounter: 0, + + // Ease Value Data: + + start: 0, + previous: 0, + current: 0, + end: 0, + + // Time Durations + t1: 0, + t2: 0, + + // LoadValue generation functions + gen: { + delay: delay, + duration: duration, + hold: hold, + repeat: repeat, + repeatDelay: repeatDelay + }, + + // TWEEN_CONST.CREATED + state: 0 + }; +}; + +module.exports = TweenData; + + +/***/ }), +/* 259 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Actions + */ + +module.exports = { + + AlignTo: __webpack_require__(553), + Angle: __webpack_require__(554), + Call: __webpack_require__(555), + GetFirst: __webpack_require__(556), + GetLast: __webpack_require__(557), + GridAlign: __webpack_require__(558), + IncAlpha: __webpack_require__(619), + IncX: __webpack_require__(620), + IncXY: __webpack_require__(621), + IncY: __webpack_require__(622), + PlaceOnCircle: __webpack_require__(623), + PlaceOnEllipse: __webpack_require__(624), + PlaceOnLine: __webpack_require__(625), + PlaceOnRectangle: __webpack_require__(626), + PlaceOnTriangle: __webpack_require__(627), + PlayAnimation: __webpack_require__(628), + PropertyValueInc: __webpack_require__(39), + PropertyValueSet: __webpack_require__(27), + RandomCircle: __webpack_require__(629), + RandomEllipse: __webpack_require__(630), + RandomLine: __webpack_require__(631), + RandomRectangle: __webpack_require__(632), + RandomTriangle: __webpack_require__(633), + Rotate: __webpack_require__(634), + RotateAround: __webpack_require__(635), + RotateAroundDistance: __webpack_require__(636), + ScaleX: __webpack_require__(637), + ScaleXY: __webpack_require__(638), + ScaleY: __webpack_require__(639), + SetAlpha: __webpack_require__(640), + SetBlendMode: __webpack_require__(641), + SetDepth: __webpack_require__(642), + SetHitArea: __webpack_require__(643), + SetOrigin: __webpack_require__(644), + SetRotation: __webpack_require__(645), + SetScale: __webpack_require__(646), + SetScaleX: __webpack_require__(647), + SetScaleY: __webpack_require__(648), + SetScrollFactor: __webpack_require__(649), + SetScrollFactorX: __webpack_require__(650), + SetScrollFactorY: __webpack_require__(651), + SetTint: __webpack_require__(652), + SetVisible: __webpack_require__(653), + SetX: __webpack_require__(654), + SetXY: __webpack_require__(655), + SetY: __webpack_require__(656), + ShiftPosition: __webpack_require__(657), + Shuffle: __webpack_require__(658), + SmootherStep: __webpack_require__(659), + SmoothStep: __webpack_require__(660), + Spread: __webpack_require__(661), + ToggleVisible: __webpack_require__(662), + WrapInRectangle: __webpack_require__(663) + +}; + + +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = __webpack_require__(97); + +var AlignToMap = []; + +AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(261); +AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(262); +AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(263); +AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = __webpack_require__(264); +AlignToMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(265); +AlignToMap[ALIGN_CONST.LEFT_TOP] = __webpack_require__(266); +AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = __webpack_require__(267); +AlignToMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(268); +AlignToMap[ALIGN_CONST.RIGHT_TOP] = __webpack_require__(269); +AlignToMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(270); +AlignToMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(271); +AlignToMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(272); + +/** + * 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 {integer} 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. + * @param {number} [offsetY=0] - Optional vertical offset from the position. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was aligned. + */ +var QuickSet = function (child, alignTo, position, offsetX, offsetY) +{ + return AlignToMap[position](child, alignTo, offsetX, offsetY); +}; + +module.exports = QuickSet; + + +/***/ }), +/* 261 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetCenterX = __webpack_require__(81); +var SetCenterX = __webpack_require__(82); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the bottom center position of the other. + * + * @function Phaser.Display.Align.To.BottomCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var BottomCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); + SetTop(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = BottomCenter; + + +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetLeft = __webpack_require__(46); +var SetLeft = __webpack_require__(47); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the bottom left position of the other. + * + * @function Phaser.Display.Align.To.BottomLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var BottomLeft = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignTo) - offsetX); + SetTop(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = BottomLeft; + + +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetRight = __webpack_require__(48); +var SetRight = __webpack_require__(49); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the bottom right position of the other. + * + * @function Phaser.Display.Align.To.BottomRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var BottomRight = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignTo) + offsetX); + SetTop(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = BottomRight; + + +/***/ }), +/* 264 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetLeft = __webpack_require__(46); +var SetBottom = __webpack_require__(50); +var SetRight = __webpack_require__(49); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the left bottom position of the other. + * + * @function Phaser.Display.Align.To.LeftBottom + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var LeftBottom = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetLeft(alignTo) - offsetX); + SetBottom(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = LeftBottom; + + +/***/ }), +/* 265 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = __webpack_require__(83); +var GetLeft = __webpack_require__(46); +var SetCenterY = __webpack_require__(84); +var SetRight = __webpack_require__(49); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the left center position of the other. + * + * @function Phaser.Display.Align.To.LeftCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var LeftCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetLeft(alignTo) - offsetX); + SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = LeftCenter; + + +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLeft = __webpack_require__(46); +var GetTop = __webpack_require__(51); +var SetRight = __webpack_require__(49); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the left top position of the other. + * + * @function Phaser.Display.Align.To.LeftTop + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var LeftTop = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetLeft(alignTo) - offsetX); + SetTop(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = LeftTop; + + +/***/ }), +/* 267 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetRight = __webpack_require__(48); +var SetBottom = __webpack_require__(50); +var SetLeft = __webpack_require__(47); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the right bottom position of the other. + * + * @function Phaser.Display.Align.To.RightBottom + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var RightBottom = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetRight(alignTo) + offsetX); + SetBottom(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = RightBottom; + + +/***/ }), +/* 268 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = __webpack_require__(83); +var GetRight = __webpack_require__(48); +var SetCenterY = __webpack_require__(84); +var SetLeft = __webpack_require__(47); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the right center position of the other. + * + * @function Phaser.Display.Align.To.RightCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var RightCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetRight(alignTo) + offsetX); + SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = RightCenter; + + +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetRight = __webpack_require__(48); +var GetTop = __webpack_require__(51); +var SetLeft = __webpack_require__(47); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the right top position of the other. + * + * @function Phaser.Display.Align.To.RightTop + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var RightTop = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetRight(alignTo) + offsetX); + SetTop(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = RightTop; + + +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterX = __webpack_require__(81); +var GetTop = __webpack_require__(51); +var SetBottom = __webpack_require__(50); +var SetCenterX = __webpack_require__(82); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. + * + * @function Phaser.Display.Align.To.TopCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var TopCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); + SetBottom(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = TopCenter; + + +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLeft = __webpack_require__(46); +var GetTop = __webpack_require__(51); +var SetBottom = __webpack_require__(50); +var SetLeft = __webpack_require__(47); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the top left position of the other. + * + * @function Phaser.Display.Align.To.TopLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var TopLeft = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignTo) - offsetX); + SetBottom(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = TopLeft; + + +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetRight = __webpack_require__(48); +var GetTop = __webpack_require__(51); +var SetBottom = __webpack_require__(50); +var SetRight = __webpack_require__(49); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the top right position of the other. + * + * @function Phaser.Display.Align.To.TopRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var TopRight = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignTo) + offsetX); + SetBottom(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = TopRight; + + +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = __webpack_require__(97); + +var AlignInMap = []; + +AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(274); +AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(275); +AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(276); +AlignInMap[ALIGN_CONST.CENTER] = __webpack_require__(277); +AlignInMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(279); +AlignInMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(280); +AlignInMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(281); +AlignInMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(282); +AlignInMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(283); +AlignInMap[ALIGN_CONST.LEFT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_LEFT]; +AlignInMap[ALIGN_CONST.LEFT_TOP] = AlignInMap[ALIGN_CONST.TOP_LEFT]; +AlignInMap[ALIGN_CONST.RIGHT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_RIGHT]; +AlignInMap[ALIGN_CONST.RIGHT_TOP] = AlignInMap[ALIGN_CONST.TOP_RIGHT]; + +/** + * Takes given Game Object and aligns it so that it is positioned relative to the other. + * 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 {integer} 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. + */ +var QuickSet = function (child, alignIn, position, offsetX, offsetY) +{ + return AlignInMap[position](child, alignIn, offsetX, offsetY); +}; + +module.exports = QuickSet; + + +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetCenterX = __webpack_require__(81); +var SetBottom = __webpack_require__(50); +var SetCenterX = __webpack_require__(82); + +/** + * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. + * + * @function Phaser.Display.Align.In.BottomCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var BottomCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); + SetBottom(gameObject, GetBottom(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = BottomCenter; + + +/***/ }), +/* 275 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetLeft = __webpack_require__(46); +var SetBottom = __webpack_require__(50); +var SetLeft = __webpack_require__(47); + +/** + * Takes given Game Object and aligns it so that it is positioned in the bottom left of the other. + * + * @function Phaser.Display.Align.In.BottomLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var BottomLeft = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignIn) - offsetX); + SetBottom(gameObject, GetBottom(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = BottomLeft; + + +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = __webpack_require__(44); +var GetRight = __webpack_require__(48); +var SetBottom = __webpack_require__(50); +var SetRight = __webpack_require__(49); + +/** + * Takes given Game Object and aligns it so that it is positioned in the bottom right of the other. + * + * @function Phaser.Display.Align.In.BottomRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var BottomRight = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignIn) + offsetX); + SetBottom(gameObject, GetBottom(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = BottomRight; + + +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CenterOn = __webpack_require__(278); +var GetCenterX = __webpack_require__(81); +var GetCenterY = __webpack_require__(83); + +/** + * Takes given Game Object and aligns it so that it is positioned in the center of the other. + * + * @function Phaser.Display.Align.In.Center + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var Center = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + CenterOn(gameObject, GetCenterX(alignIn) + offsetX, GetCenterY(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = Center; + + +/***/ }), +/* 278 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetCenterX = __webpack_require__(82); +var SetCenterY = __webpack_require__(84); + +/** + * Positions the Game Object so that it is centered on the given coordinates. + * + * @function Phaser.Display.Bounds.CenterOn + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} x - The horizontal coordinate to position the Game Object on. + * @param {number} y - The vertical coordinate to position the Game Object on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var CenterOn = function (gameObject, x, y) +{ + SetCenterX(gameObject, x); + + return SetCenterY(gameObject, y); +}; + +module.exports = CenterOn; + + +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = __webpack_require__(83); +var GetLeft = __webpack_require__(46); +var SetCenterY = __webpack_require__(84); +var SetLeft = __webpack_require__(47); + +/** + * Takes given Game Object and aligns it so that it is positioned in the left center of the other. + * + * @function Phaser.Display.Align.In.LeftCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var LeftCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignIn) - offsetX); + SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = LeftCenter; + + +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = __webpack_require__(83); +var GetRight = __webpack_require__(48); +var SetCenterY = __webpack_require__(84); +var SetRight = __webpack_require__(49); + +/** + * Takes given Game Object and aligns it so that it is positioned in the right center of the other. + * + * @function Phaser.Display.Align.In.RightCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var RightCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignIn) + offsetX); + SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = RightCenter; + + +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterX = __webpack_require__(81); +var GetTop = __webpack_require__(51); +var SetCenterX = __webpack_require__(82); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned in the top center of the other. + * + * @function Phaser.Display.Align.In.TopCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var TopCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); + SetTop(gameObject, GetTop(alignIn) - offsetY); + + return gameObject; +}; + +module.exports = TopCenter; + + +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLeft = __webpack_require__(46); +var GetTop = __webpack_require__(51); +var SetLeft = __webpack_require__(47); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned in the top left of the other. + * + * @function Phaser.Display.Align.In.TopLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var TopLeft = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignIn) - offsetX); + SetTop(gameObject, GetTop(alignIn) - offsetY); + + return gameObject; +}; + +module.exports = TopLeft; + + +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetRight = __webpack_require__(48); +var GetTop = __webpack_require__(51); +var SetRight = __webpack_require__(49); +var SetTop = __webpack_require__(45); + +/** + * Takes given Game Object and aligns it so that it is positioned in the top right of the other. + * + * @function Phaser.Display.Align.In.TopRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var TopRight = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignIn) + offsetX); + SetTop(gameObject, GetTop(alignIn) - offsetY); + + return gameObject; +}; + +module.exports = TopRight; + + +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CircumferencePoint = __webpack_require__(158); +var FromPercent = __webpack_require__(98); +var MATH_CONST = __webpack_require__(13); +var Point = __webpack_require__(4); + +/** + * 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. + * + * @function Phaser.Geom.Circle.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle. + */ +var GetPoint = function (circle, position, out) +{ + if (out === undefined) { out = new Point(); } + + var angle = FromPercent(position, 0, MATH_CONST.PI2); + + return CircumferencePoint(circle, angle, out); +}; + +module.exports = GetPoint; + + +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circumference = __webpack_require__(286); +var CircumferencePoint = __webpack_require__(158); +var FromPercent = __webpack_require__(98); +var MATH_CONST = __webpack_require__(13); + +/** + * 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. + * + * @function Phaser.Geom.Circle.GetPoints + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the points from. + * @param {integer} 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 circle 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.Geom.Point[]} An array of Point objects pertaining to the points around the circumference of the circle. + */ +var GetPoints = function (circle, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Circumference(circle) / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); + + out.push(CircumferencePoint(circle, angle)); + } + + return out; +}; + +module.exports = GetPoints; + + +/***/ }), +/* 286 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the circumference of the given Circle. + * + * @function Phaser.Geom.Circle.Circumference + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the circumference of. + * + * @return {number} The circumference of the Circle. + */ +var Circumference = function (circle) +{ + return 2 * (Math.PI * circle.radius); +}; + +module.exports = Circumference; + + +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); + +// bitmask flag for GameObject.renderMask +var _FLAG = 2; // 0010 + +/** + * Provides methods used for setting the alpha property of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.AlphaSingle + * @since 3.22.0 + */ + +var AlphaSingle = { + + /** + * Private internal value. Holds the global alpha value. + * + * @name Phaser.GameObjects.Components.AlphaSingle#_alpha + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alpha: 1, + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + * + * @method Phaser.GameObjects.Components.AlphaSingle#clearAlpha + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + clearAlpha: function () + { + return this.setAlpha(1); + }, + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * @method Phaser.GameObjects.Components.AlphaSingle#setAlpha + * @since 3.0.0 + * + * @param {number} [value=1] - The alpha value applied across the whole Game Object. + * + * @return {this} This Game Object instance. + */ + setAlpha: function (value) + { + if (value === undefined) { value = 1; } + + this.alpha = value; + + return this; + }, + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + * + * @name Phaser.GameObjects.Components.AlphaSingle#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this._alpha; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alpha = v; + + if (v === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + } + +}; + +module.exports = AlphaSingle; + + +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseAnimation = __webpack_require__(160); +var Class = __webpack_require__(0); +var Events = __webpack_require__(119); + +/** + * @classdesc + * A Game Object Animation Controller. + * + * This controller lives as an instance within a Game Object, accessible as `sprite.anims`. + * + * @class Animation + * @memberof Phaser.GameObjects.Components + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} parent - The Game Object to which this animation controller belongs. + */ +var Animation = new Class({ + + initialize: + + function Animation (parent) + { + /** + * The Game Object to which this animation controller belongs. + * + * @name Phaser.GameObjects.Components.Animation#parent + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * A reference to the global Animation Manager. + * + * @name Phaser.GameObjects.Components.Animation#animationManager + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.animationManager = parent.scene.sys.anims; + + this.animationManager.once(Events.REMOVE_ANIMATION, this.remove, this); + + /** + * Is an animation currently playing or not? + * + * @name Phaser.GameObjects.Components.Animation#isPlaying + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isPlaying = false; + + /** + * The current Animation loaded into this Animation Controller. + * + * @name Phaser.GameObjects.Components.Animation#currentAnim + * @type {?Phaser.Animations.Animation} + * @default null + * @since 3.0.0 + */ + this.currentAnim = null; + + /** + * The current AnimationFrame being displayed by this Animation Controller. + * + * @name Phaser.GameObjects.Components.Animation#currentFrame + * @type {?Phaser.Animations.AnimationFrame} + * @default null + * @since 3.0.0 + */ + this.currentFrame = null; + + /** + * The key of the next Animation to be loaded into this Animation Controller when the current animation completes. + * + * @name Phaser.GameObjects.Components.Animation#nextAnim + * @type {?string} + * @default null + * @since 3.16.0 + */ + this.nextAnim = null; + + /** + * Time scale factor. + * + * @name Phaser.GameObjects.Components.Animation#_timeScale + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + this._timeScale = 1; + + /** + * The frame rate of playback in frames per second. + * The default is 24 if the `duration` property is `null`. + * + * @name Phaser.GameObjects.Components.Animation#frameRate + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.frameRate = 0; + + /** + * How long the animation should play for, in milliseconds. + * If the `frameRate` property has been set then it overrides this value, + * otherwise the `frameRate` is derived from `duration`. + * + * @name Phaser.GameObjects.Components.Animation#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * ms per frame, not including frame specific modifiers that may be present in the Animation data. + * + * @name Phaser.GameObjects.Components.Animation#msPerFrame + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.msPerFrame = 0; + + /** + * Skip frames if the time lags, or always advanced anyway? + * + * @name Phaser.GameObjects.Components.Animation#skipMissedFrames + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.skipMissedFrames = true; + + /** + * A delay before starting playback, in milliseconds. + * + * @name Phaser.GameObjects.Components.Animation#_delay + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._delay = 0; + + /** + * Number of times to repeat the animation (-1 for infinity) + * + * @name Phaser.GameObjects.Components.Animation#_repeat + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._repeat = 0; + + /** + * Delay before the repeat starts, in milliseconds. + * + * @name Phaser.GameObjects.Components.Animation#_repeatDelay + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._repeatDelay = 0; + + /** + * Should the animation yoyo? (reverse back down to the start) before repeating? + * + * @name Phaser.GameObjects.Components.Animation#_yoyo + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._yoyo = false; + + /** + * Will the playhead move forwards (`true`) or in reverse (`false`). + * + * @name Phaser.GameObjects.Components.Animation#forward + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.forward = true; + + /** + * An Internal trigger that's play the animation in reverse mode ('true') or not ('false'), + * needed because forward can be changed by yoyo feature. + * + * @name Phaser.GameObjects.Components.Animation#_reverse + * @type {boolean} + * @default false + * @private + * @since 3.12.0 + */ + this._reverse = false; + + /** + * Internal time overflow accumulator. + * + * @name Phaser.GameObjects.Components.Animation#accumulator + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accumulator = 0; + + /** + * The time point at which the next animation frame will change. + * + * @name Phaser.GameObjects.Components.Animation#nextTick + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.nextTick = 0; + + /** + * An internal counter keeping track of how many repeats are left to play. + * + * @name Phaser.GameObjects.Components.Animation#repeatCounter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.repeatCounter = 0; + + /** + * An internal flag keeping track of pending repeats. + * + * @name Phaser.GameObjects.Components.Animation#pendingRepeat + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.pendingRepeat = false; + + /** + * Is the Animation paused? + * + * @name Phaser.GameObjects.Components.Animation#_paused + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._paused = false; + + /** + * Was the animation previously playing before being paused? + * + * @name Phaser.GameObjects.Components.Animation#_wasPlaying + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._wasPlaying = false; + + /** + * Internal property tracking if this Animation is waiting to stop. + * + * 0 = No + * 1 = Waiting for ms to pass + * 2 = Waiting for repeat + * 3 = Waiting for specific frame + * + * @name Phaser.GameObjects.Components.Animation#_pendingStop + * @type {integer} + * @private + * @since 3.4.0 + */ + this._pendingStop = 0; + + /** + * Internal property used by _pendingStop. + * + * @name Phaser.GameObjects.Components.Animation#_pendingStopValue + * @type {any} + * @private + * @since 3.4.0 + */ + this._pendingStopValue; + }, + + /** + * Sets an animation to be played immediately after the current one completes. + * + * The current animation must enter a 'completed' state for this to happen, i.e. finish all of its repeats, delays, etc, or have the `stop` method called directly on it. + * + * An animation set to repeat forever will never enter a completed state. + * + * You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). + * Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. + * + * Call this method with no arguments to reset the chained animation. + * + * @method Phaser.GameObjects.Components.Animation#chain + * @since 3.16.0 + * + * @param {(string|Phaser.Animations.Animation)} [key] - The string-based key of the animation to play next, as defined previously in the Animation Manager. Or an Animation instance. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + chain: function (key) + { + if (key instanceof BaseAnimation) + { + key = key.key; + } + + this.nextAnim = key; + + return this.parent; + }, + + /** + * Sets the amount of time, in milliseconds, that the animation will be delayed before starting playback. + * + * @method Phaser.GameObjects.Components.Animation#setDelay + * @since 3.4.0 + * + * @param {integer} [value=0] - The amount of time, in milliseconds, to wait before starting playback. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setDelay: function (value) + { + if (value === undefined) { value = 0; } + + this._delay = value; + + return this.parent; + }, + + /** + * Gets the amount of time, in milliseconds that the animation will be delayed before starting playback. + * + * @method Phaser.GameObjects.Components.Animation#getDelay + * @since 3.4.0 + * + * @return {integer} The amount of time, in milliseconds, the Animation will wait before starting playback. + */ + getDelay: function () + { + return this._delay; + }, + + /** + * Waits for the specified delay, in milliseconds, then starts playback of the requested animation. + * + * @method Phaser.GameObjects.Components.Animation#delayedPlay + * @since 3.0.0 + * + * @param {integer} delay - The delay, in milliseconds, to wait before starting the animation playing. + * @param {string} key - The key of the animation to play. + * @param {integer} [startFrame=0] - The frame of the animation to start from. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + delayedPlay: function (delay, key, startFrame) + { + this.play(key, true, startFrame); + + this.nextTick += delay; + + return this.parent; + }, + + /** + * Returns the key of the animation currently loaded into this component. + * + * @method Phaser.GameObjects.Components.Animation#getCurrentKey + * @since 3.0.0 + * + * @return {string} The key of the Animation loaded into this component. + */ + getCurrentKey: function () + { + if (this.currentAnim) + { + return this.currentAnim.key; + } + }, + + /** + * Internal method used to load an animation into this component. + * + * @method Phaser.GameObjects.Components.Animation#load + * @protected + * @since 3.0.0 + * + * @param {string} key - The key of the animation to load. + * @param {integer} [startFrame=0] - The start frame of the animation to load. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + load: function (key, startFrame) + { + if (startFrame === undefined) { startFrame = 0; } + + if (this.isPlaying) + { + this.stop(); + } + + // Load the new animation in + this.animationManager.load(this, key, startFrame); + + return this.parent; + }, + + /** + * Pause the current animation and set the `isPlaying` property to `false`. + * You can optionally pause it at a specific frame. + * + * @method Phaser.GameObjects.Components.Animation#pause + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} [atFrame] - An optional frame to set after pausing the animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + pause: function (atFrame) + { + if (!this._paused) + { + this._paused = true; + this._wasPlaying = this.isPlaying; + this.isPlaying = false; + } + + if (atFrame !== undefined) + { + this.updateFrame(atFrame); + } + + return this.parent; + }, + + /** + * Resumes playback of a paused animation and sets the `isPlaying` property to `true`. + * You can optionally tell it to start playback from a specific frame. + * + * @method Phaser.GameObjects.Components.Animation#resume + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} [fromFrame] - An optional frame to set before restarting playback. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + resume: function (fromFrame) + { + if (this._paused) + { + this._paused = false; + this.isPlaying = this._wasPlaying; + } + + if (fromFrame !== undefined) + { + this.updateFrame(fromFrame); + } + + return this.parent; + }, + + /** + * `true` if the current animation is paused, otherwise `false`. + * + * @name Phaser.GameObjects.Components.Animation#isPaused + * @readonly + * @type {boolean} + * @since 3.4.0 + */ + isPaused: { + + get: function () + { + return this._paused; + } + + }, + + /** + * Plays an Animation on a Game Object that has the Animation component, such as a Sprite. + * + * Animations are stored in the global Animation Manager and are referenced by a unique string-based key. + * + * @method Phaser.GameObjects.Components.Animation#play + * @fires Phaser.GameObjects.Components.Animation#onStartEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Animations.Animation)} key - The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. + * @param {boolean} [ignoreIfPlaying=false] - If this animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + play: function (key, ignoreIfPlaying, startFrame) + { + if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false; } + if (startFrame === undefined) { startFrame = 0; } + + if (key instanceof BaseAnimation) + { + key = key.key; + } + + if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) + { + return this.parent; + } + + this.forward = true; + this._reverse = false; + this._paused = false; + this._wasPlaying = true; + + return this._startAnimation(key, startFrame); + }, + + /** + * Plays an Animation (in reverse mode) on the Game Object that owns this Animation Component. + * + * @method Phaser.GameObjects.Components.Animation#playReverse + * @fires Phaser.GameObjects.Components.Animation#onStartEvent + * @since 3.12.0 + * + * @param {(string|Phaser.Animations.Animation)} key - The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + playReverse: function (key, ignoreIfPlaying, startFrame) + { + if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false; } + if (startFrame === undefined) { startFrame = 0; } + + if (key instanceof BaseAnimation) + { + key = key.key; + } + + if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) + { + return this.parent; + } + + this.forward = false; + this._reverse = true; + + return this._startAnimation(key, startFrame); + }, + + /** + * Load an Animation and fires 'onStartEvent' event, extracted from 'play' method. + * + * @method Phaser.GameObjects.Components.Animation#_startAnimation + * @fires Phaser.Animations.Events#START_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_START_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_START_KEY_ANIMATION_EVENT + * @since 3.12.0 + * + * @param {string} key - The string-based key of the animation to play, as defined previously in the Animation Manager. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + _startAnimation: function (key, startFrame) + { + this.load(key, startFrame); + + var anim = this.currentAnim; + var gameObject = this.parent; + + if (!anim) + { + return gameObject; + } + + // Should give us 9,007,199,254,740,991 safe repeats + this.repeatCounter = (this._repeat === -1) ? Number.MAX_VALUE : this._repeat; + + anim.getFirstTick(this); + + this.isPlaying = true; + this.pendingRepeat = false; + + if (anim.showOnStart) + { + gameObject.visible = true; + } + + var frame = this.currentFrame; + + anim.emit(Events.ANIMATION_START, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_START + key, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_START, anim, frame, gameObject); + + return gameObject; + }, + + /** + * Reverse the Animation that is already playing on the Game Object. + * + * @method Phaser.GameObjects.Components.Animation#reverse + * @since 3.12.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + reverse: function () + { + if (this.isPlaying) + { + this._reverse = !this._reverse; + + this.forward = !this.forward; + } + + return this.parent; + }, + + /** + * Returns a value between 0 and 1 indicating how far this animation is through, ignoring repeats and yoyos. + * If the animation has a non-zero repeat defined, `getProgress` and `getTotalProgress` will be different + * because `getProgress` doesn't include any repeats or repeat delays, whereas `getTotalProgress` does. + * + * @method Phaser.GameObjects.Components.Animation#getProgress + * @since 3.4.0 + * + * @return {number} The progress of the current animation, between 0 and 1. + */ + getProgress: function () + { + var p = this.currentFrame.progress; + + if (!this.forward) + { + p = 1 - p; + } + + return p; + }, + + /** + * 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. + * + * @method Phaser.GameObjects.Components.Animation#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. + */ + setProgress: function (value) + { + if (!this.forward) + { + value = 1 - value; + } + + this.setCurrentFrame(this.currentAnim.getFrameByProgress(value)); + + return this.parent; + }, + + /** + * Handle the removal of an animation from the Animation Manager. + * + * @method Phaser.GameObjects.Components.Animation#remove + * @since 3.0.0 + * + * @param {string} [key] - The key of the removed Animation. + * @param {Phaser.Animations.Animation} [animation] - The removed Animation. + */ + remove: function (key, animation) + { + if (animation === undefined) { animation = this.currentAnim; } + + if (this.isPlaying && animation.key === this.currentAnim.key) + { + this.stop(); + + this.setCurrentFrame(this.currentAnim.frames[0]); + } + }, + + /** + * Gets the number of times that the animation will repeat + * after its first iteration. For example, if returns 1, the animation will + * play a total of twice (the initial play plus 1 repeat). + * A value of -1 means the animation will repeat indefinitely. + * + * @method Phaser.GameObjects.Components.Animation#getRepeat + * @since 3.4.0 + * + * @return {integer} The number of times that the animation will repeat. + */ + getRepeat: function () + { + return this._repeat; + }, + + /** + * Sets the number of times that the animation should repeat + * after its first iteration. For example, if repeat is 1, the animation will + * play a total of twice (the initial play plus 1 repeat). + * To repeat indefinitely, use -1. repeat should always be an integer. + * + * @method Phaser.GameObjects.Components.Animation#setRepeat + * @since 3.4.0 + * + * @param {integer} value - The number of times that the animation should repeat. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setRepeat: function (value) + { + this._repeat = value; + + this.repeatCounter = (value === -1) ? Number.MAX_VALUE : value; + + return this.parent; + }, + + /** + * Gets the amount of delay between repeats, if any. + * + * @method Phaser.GameObjects.Components.Animation#getRepeatDelay + * @since 3.4.0 + * + * @return {number} The delay between repeats. + */ + getRepeatDelay: function () + { + return this._repeatDelay; + }, + + /** + * Sets the amount of time in seconds between repeats. + * For example, if `repeat` is 2 and `repeatDelay` is 10, the animation will play initially, + * then wait for 10 seconds before repeating, then play again, then wait another 10 seconds + * before doing its final repeat. + * + * @method Phaser.GameObjects.Components.Animation#setRepeatDelay + * @since 3.4.0 + * + * @param {number} value - The delay to wait between repeats, in seconds. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setRepeatDelay: function (value) + { + this._repeatDelay = value; + + return this.parent; + }, + + /** + * Restarts the current animation from its beginning, optionally including its delay value. + * + * @method Phaser.GameObjects.Components.Animation#restart + * @fires Phaser.Animations.Events#RESTART_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_RESTART_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_RESTART_KEY_ANIMATION_EVENT + * @since 3.0.0 + * + * @param {boolean} [includeDelay=false] - Whether to include the delay value of the animation when restarting. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + restart: function (includeDelay) + { + if (includeDelay === undefined) { includeDelay = false; } + + var anim = this.currentAnim; + + anim.getFirstTick(this, includeDelay); + + this.forward = true; + this.isPlaying = true; + this.pendingRepeat = false; + this._paused = false; + + // Set frame + this.updateFrame(anim.frames[0]); + + var gameObject = this.parent; + var frame = this.currentFrame; + + anim.emit(Events.ANIMATION_RESTART, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_RESTART + anim.key, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_RESTART, anim, frame, gameObject); + + return this.parent; + }, + + /** + * Immediately stops the current animation from playing and dispatches the `animationcomplete` event. + * + * If no animation is set, no event will be dispatched. + * + * If there is another animation queued (via the `chain` method) then it will start playing immediately. + * + * @method Phaser.GameObjects.Components.Animation#stop + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stop: function () + { + this._pendingStop = 0; + + this.isPlaying = false; + + var gameObject = this.parent; + var anim = this.currentAnim; + var frame = this.currentFrame; + + if (anim) + { + anim.emit(Events.ANIMATION_COMPLETE, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_COMPLETE + anim.key, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_COMPLETE, anim, frame, gameObject); + } + + if (this.nextAnim) + { + var key = this.nextAnim; + + this.nextAnim = null; + + this.play(key); + } + + return gameObject; + }, + + /** + * Stops the current animation from playing after the specified time delay, given in milliseconds. + * + * @method Phaser.GameObjects.Components.Animation#stopAfterDelay + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.4.0 + * + * @param {integer} delay - The number of milliseconds to wait before stopping this animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stopAfterDelay: function (delay) + { + this._pendingStop = 1; + this._pendingStopValue = delay; + + return this.parent; + }, + + /** + * Stops the current animation from playing when it next repeats. + * + * @method Phaser.GameObjects.Components.Animation#stopOnRepeat + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.4.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stopOnRepeat: function () + { + this._pendingStop = 2; + + return this.parent; + }, + + /** + * Stops the current animation from playing when it next sets the given frame. + * If this frame doesn't exist within the animation it will not stop it from playing. + * + * @method Phaser.GameObjects.Components.Animation#stopOnFrame + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.4.0 + * + * @param {Phaser.Animations.AnimationFrame} frame - The frame to check before stopping this animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stopOnFrame: function (frame) + { + this._pendingStop = 3; + this._pendingStopValue = frame; + + return this.parent; + }, + + /** + * Sets the Time Scale factor, allowing you to make the animation go go faster or slower than default. + * Where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. + * + * @method Phaser.GameObjects.Components.Animation#setTimeScale + * @since 3.4.0 + * + * @param {number} [value=1] - The time scale factor, where 1 is no change, 0.5 is half speed, etc. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setTimeScale: function (value) + { + if (value === undefined) { value = 1; } + + this._timeScale = value; + + return this.parent; + }, + + /** + * Gets the Time Scale factor. + * + * @method Phaser.GameObjects.Components.Animation#getTimeScale + * @since 3.4.0 + * + * @return {number} The Time Scale value. + */ + getTimeScale: function () + { + return this._timeScale; + }, + + /** + * Returns the total number of frames in this animation. + * + * @method Phaser.GameObjects.Components.Animation#getTotalFrames + * @since 3.4.0 + * + * @return {integer} The total number of frames in this animation. + */ + getTotalFrames: function () + { + return this.currentAnim.frames.length; + }, + + /** + * The internal update loop for the Animation Component. + * + * @method Phaser.GameObjects.Components.Animation#update + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + update: function (time, delta) + { + if (!this.currentAnim || !this.isPlaying || this.currentAnim.paused) + { + return; + } + + this.accumulator += delta * this._timeScale; + + if (this._pendingStop === 1) + { + this._pendingStopValue -= delta; + + if (this._pendingStopValue <= 0) + { + return this.currentAnim.completeAnimation(this); + } + } + + if (this.accumulator >= this.nextTick) + { + this.currentAnim.setFrame(this); + } + }, + + /** + * Sets the given Animation Frame as being the current frame + * and applies it to the parent Game Object, adjusting its size and origin as needed. + * + * @method Phaser.GameObjects.Components.Animation#setCurrentFrame + * @since 3.4.0 + * + * @param {Phaser.Animations.AnimationFrame} animationFrame - The Animation Frame to set as being current. + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + setCurrentFrame: function (animationFrame) + { + var gameObject = this.parent; + + this.currentFrame = animationFrame; + + gameObject.texture = animationFrame.frame.texture; + gameObject.frame = animationFrame.frame; + + if (gameObject.isCropped) + { + gameObject.frame.updateCropUVs(gameObject._crop, gameObject.flipX, gameObject.flipY); + } + + gameObject.setSizeToFrame(); + + if (animationFrame.frame.customPivot) + { + gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); + } + else + { + gameObject.updateDisplayOrigin(); + } + + return gameObject; + }, + + /** + * Internal frame change handler. + * + * @method Phaser.GameObjects.Components.Animation#updateFrame + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_UPDATE_EVENT + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_UPDATE_EVENT + * @private + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} animationFrame - The animation frame to change to. + */ + updateFrame: function (animationFrame) + { + var gameObject = this.setCurrentFrame(animationFrame); + + if (this.isPlaying) + { + if (animationFrame.setAlpha) + { + gameObject.alpha = animationFrame.alpha; + } + + var anim = this.currentAnim; + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_UPDATE + anim.key, anim, animationFrame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_UPDATE, anim, animationFrame, gameObject); + + if (this._pendingStop === 3 && this._pendingStopValue === animationFrame) + { + this.currentAnim.completeAnimation(this); + } + } + }, + + /** + * Advances the animation to the next frame, regardless of the time or animation state. + * If the animation is set to repeat, or yoyo, this will still take effect. + * + * Calling this does not change the direction of the animation. I.e. if it was currently + * playing in reverse, calling this method doesn't then change the direction to forwards. + * + * @method Phaser.GameObjects.Components.Animation#nextFrame + * @since 3.16.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + nextFrame: function () + { + if (this.currentAnim) + { + this.currentAnim.nextFrame(this); + } + + return this.parent; + }, + + /** + * Advances the animation to the previous frame, regardless of the time or animation state. + * If the animation is set to repeat, or yoyo, this will still take effect. + * + * Calling this does not change the direction of the animation. I.e. if it was currently + * playing in forwards, calling this method doesn't then change the direction to backwards. + * + * @method Phaser.GameObjects.Components.Animation#previousFrame + * @since 3.16.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + previousFrame: function () + { + if (this.currentAnim) + { + this.currentAnim.previousFrame(this); + } + + return this.parent; + }, + + /** + * Sets if the current Animation will yoyo when it reaches the end. + * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. + * + * @method Phaser.GameObjects.Components.Animation#setYoyo + * @since 3.4.0 + * + * @param {boolean} [value=false] - `true` if the animation should yoyo, `false` to not. + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + setYoyo: function (value) + { + if (value === undefined) { value = false; } + + this._yoyo = value; + + return this.parent; + }, + + /** + * Gets if the current Animation will yoyo when it reaches the end. + * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. + * + * @method Phaser.GameObjects.Components.Animation#getYoyo + * @since 3.4.0 + * + * @return {boolean} `true` if the animation is set to yoyo, `false` if not. + */ + getYoyo: function () + { + return this._yoyo; + }, + + /** + * Destroy this Animation component. + * + * Unregisters event listeners and cleans up its references. + * + * @method Phaser.GameObjects.Components.Animation#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.animationManager.off(Events.REMOVE_ANIMATION, this.remove, this); + + this.animationManager = null; + this.parent = null; + + this.currentAnim = null; + this.currentFrame = null; + } + +}); + +module.exports = Animation; + + +/***/ }), +/* 289 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Searches a pre-sorted array for the closet value to the given number. + * + * If the `key` argument is given it will assume the array contains objects that all have the required `key` property name, + * and will check for the closest value of those to the given number. + * + * @function Phaser.Utils.Array.FindClosestInSorted + * @since 3.0.0 + * + * @param {number} value - The value to search for in the array. + * @param {array} array - The array to search, which must be sorted. + * @param {string} [key] - An optional property key. If specified the array elements property will be checked against value. + * + * @return {(number|any)} The nearest value found in the array, or if a `key` was given, the nearest object with the matching property value. + */ +var FindClosestInSorted = function (value, array, key) +{ + if (!array.length) + { + return NaN; + } + else if (array.length === 1) + { + return array[0]; + } + + var i = 1; + var low; + var high; + + if (key) + { + if (value < array[0][key]) + { + return array[0]; + } + + while (array[i][key] < value) + { + i++; + } + } + else + { + while (array[i] < value) + { + i++; + } + } + + if (i > array.length) + { + i = array.length; + } + + if (key) + { + low = array[i - 1][key]; + high = array[i][key]; + + return ((high - value) <= (value - low)) ? array[i] : array[i - 1]; + } + else + { + low = array[i - 1]; + high = array[i]; + + return ((high - value) <= (value - low)) ? high : low; + } +}; + +module.exports = FindClosestInSorted; + + +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A single frame in an Animation sequence. + * + * An AnimationFrame consists of a reference to the Texture it uses for rendering, references to other + * frames in the animation, and index data. It also has the ability to modify the animation timing. + * + * AnimationFrames are generated automatically by the Animation class. + * + * @class AnimationFrame + * @memberof Phaser.Animations + * @constructor + * @since 3.0.0 + * + * @param {string} textureKey - The key of the Texture this AnimationFrame uses. + * @param {(string|integer)} textureFrame - The key of the Frame within the Texture that this AnimationFrame uses. + * @param {integer} index - The index of this AnimationFrame within the Animation sequence. + * @param {Phaser.Textures.Frame} frame - A reference to the Texture Frame this AnimationFrame uses for rendering. + */ +var AnimationFrame = new Class({ + + initialize: + + function AnimationFrame (textureKey, textureFrame, index, frame) + { + /** + * The key of the Texture this AnimationFrame uses. + * + * @name Phaser.Animations.AnimationFrame#textureKey + * @type {string} + * @since 3.0.0 + */ + this.textureKey = textureKey; + + /** + * The key of the Frame within the Texture that this AnimationFrame uses. + * + * @name Phaser.Animations.AnimationFrame#textureFrame + * @type {(string|integer)} + * @since 3.0.0 + */ + this.textureFrame = textureFrame; + + /** + * The index of this AnimationFrame within the Animation sequence. + * + * @name Phaser.Animations.AnimationFrame#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * A reference to the Texture Frame this AnimationFrame uses for rendering. + * + * @name Phaser.Animations.AnimationFrame#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + this.frame = frame; + + /** + * Is this the first frame in an animation sequence? + * + * @name Phaser.Animations.AnimationFrame#isFirst + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isFirst = false; + + /** + * Is this the last frame in an animation sequence? + * + * @name Phaser.Animations.AnimationFrame#isLast + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isLast = false; + + /** + * A reference to the AnimationFrame that comes before this one in the animation, if any. + * + * @name Phaser.Animations.AnimationFrame#prevFrame + * @type {?Phaser.Animations.AnimationFrame} + * @default null + * @readonly + * @since 3.0.0 + */ + this.prevFrame = null; + + /** + * A reference to the AnimationFrame that comes after this one in the animation, if any. + * + * @name Phaser.Animations.AnimationFrame#nextFrame + * @type {?Phaser.Animations.AnimationFrame} + * @default null + * @readonly + * @since 3.0.0 + */ + this.nextFrame = null; + + /** + * Additional time (in ms) that this frame should appear for during playback. + * The value is added onto the msPerFrame set by the animation. + * + * @name Phaser.Animations.AnimationFrame#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * What % through the animation does this frame come? + * This value is generated when the animation is created and cached here. + * + * @name Phaser.Animations.AnimationFrame#progress + * @type {number} + * @default 0 + * @readonly + * @since 3.0.0 + */ + this.progress = 0; + }, + + /** + * Generates a JavaScript object suitable for converting to JSON. + * + * @method Phaser.Animations.AnimationFrame#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Animations.JSONAnimationFrame} The AnimationFrame data. + */ + toJSON: function () + { + return { + key: this.textureKey, + frame: this.textureFrame, + duration: this.duration + }; + }, + + /** + * Destroys this object by removing references to external resources and callbacks. + * + * @method Phaser.Animations.AnimationFrame#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.frame = undefined; + } + +}); + +module.exports = AnimationFrame; + + +/***/ }), +/* 291 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = __webpack_require__(43); + +/** + * Provides methods used for setting the blend mode of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.BlendMode + * @since 3.0.0 + */ + +var BlendMode = { + + /** + * Private internal value. Holds the current blend mode. + * + * @name Phaser.GameObjects.Components.BlendMode#_blendMode + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + _blendMode: BlendModes.NORMAL, + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + * + * @name Phaser.GameObjects.Components.BlendMode#blendMode + * @type {(Phaser.BlendModes|string)} + * @since 3.0.0 + */ + blendMode: { + + get: function () + { + return this._blendMode; + }, + + set: function (value) + { + if (typeof value === 'string') + { + value = BlendModes[value]; + } + + value |= 0; + + if (value >= -1) + { + this._blendMode = value; + } + } + + }, + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * + * @method Phaser.GameObjects.Components.BlendMode#setBlendMode + * @since 3.0.0 + * + * @param {(string|Phaser.BlendModes)} value - The BlendMode value. Either a string or a CONST. + * + * @return {this} This Game Object instance. + */ + setBlendMode: function (value) + { + this.blendMode = value; + + return this; + } + +}; + +module.exports = BlendMode; + + +/***/ }), +/* 292 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the depth of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Depth + * @since 3.0.0 + */ + +var Depth = { + + /** + * Private internal value. Holds the depth of the Game Object. + * + * @name Phaser.GameObjects.Components.Depth#_depth + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + _depth: 0, + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * + * @name Phaser.GameObjects.Components.Depth#depth + * @type {number} + * @since 3.0.0 + */ + depth: { + + get: function () + { + return this._depth; + }, + + set: function (value) + { + this.scene.sys.queueDepthSort(); + this._depth = value; + } + + }, + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * + * @method Phaser.GameObjects.Components.Depth#setDepth + * @since 3.0.0 + * + * @param {integer} value - The depth of this Game Object. + * + * @return {this} This Game Object instance. + */ + setDepth: function (value) + { + if (value === undefined) { value = 0; } + + this.depth = value; + + return this; + } + +}; + +module.exports = Depth; + + +/***/ }), +/* 293 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetPoint = __webpack_require__(161); +var Perimeter = __webpack_require__(120); + +// Return an array of points from the perimeter of the rectangle +// each spaced out based on the quantity or step required + +/** + * Return an array of 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.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle object to get the points from. + * @param {number} step - Step between points. Used to calculate the number of points to return when quantity is falsey. Ignored if quantity is positive. + * @param {integer} quantity - The number of evenly spaced points from the rectangles perimeter to return. If falsey, step param will be used to calculate the number of points. + * @param {(array|Phaser.Geom.Point[])} [out] - An optional array to store the points in. + * + * @return {(array|Phaser.Geom.Point[])} An array of Points from the perimeter of the rectangle. + */ +var GetPoints = function (rectangle, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Perimeter(rectangle) / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var position = i / quantity; + + out.push(GetPoint(rectangle, position)); + } + + return out; +}; + +module.exports = GetPoints; + + +/***/ }), +/* 294 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Get a point on a line that's a given percentage along its length. + * + * @function Phaser.Geom.Line.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line. + * @param {number} position - A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the point on the line. + * + * @return {(Phaser.Geom.Point|object)} The point on the line. + */ +var GetPoint = function (line, position, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = line.x1 + (line.x2 - line.x1) * position; + out.y = line.y1 + (line.y2 - line.y1) * position; + + return out; +}; + +module.exports = GetPoint; + + +/***/ }), +/* 295 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a `point` around `x` and `y` by the given `angle`. + * + * @function Phaser.Math.RotateAround + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. + * @param {number} x - The horizontal coordinate to rotate around. + * @param {number} y - The vertical coordinate to rotate around. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Point} The given point, rotated by the given angle around the given coordinates. + */ +var RotateAround = function (point, x, y, angle) +{ + var c = Math.cos(angle); + var s = Math.sin(angle); + + var tx = point.x - x; + var ty = point.y - y; + + point.x = tx * c - ty * s + x; + point.y = tx * s + ty * c + y; + + return point; +}; + +module.exports = RotateAround; + + +/***/ }), +/* 296 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapMask = __webpack_require__(297); +var GeometryMask = __webpack_require__(298); + +/** + * Provides methods used for getting and setting the mask of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Mask + * @since 3.0.0 + */ + +var Mask = { + + /** + * The Mask this Game Object is using during render. + * + * @name Phaser.GameObjects.Components.Mask#mask + * @type {Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask} + * @since 3.0.0 + */ + mask: null, + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * + * @method Phaser.GameObjects.Components.Mask#setMask + * @since 3.6.2 + * + * @param {Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask} mask - The mask this Game Object will use when rendering. + * + * @return {this} This Game Object instance. + */ + setMask: function (mask) + { + this.mask = mask; + + return this; + }, + + /** + * Clears the mask that this Game Object was using. + * + * @method Phaser.GameObjects.Components.Mask#clearMask + * @since 3.6.2 + * + * @param {boolean} [destroyMask=false] - Destroy the mask before clearing it? + * + * @return {this} This Game Object instance. + */ + clearMask: function (destroyMask) + { + if (destroyMask === undefined) { destroyMask = false; } + + if (destroyMask && this.mask) + { + this.mask.destroy(); + } + + this.mask = null; + + return this; + }, + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * + * @method Phaser.GameObjects.Components.Mask#createBitmapMask + * @since 3.6.2 + * + * @param {Phaser.GameObjects.GameObject} [renderable] - A renderable Game Object that uses a texture, such as a Sprite. + * + * @return {Phaser.Display.Masks.BitmapMask} This Bitmap Mask that was created. + */ + createBitmapMask: function (renderable) + { + if (renderable === undefined && (this.texture || this.shader)) + { + // eslint-disable-next-line consistent-this + renderable = this; + } + + return new BitmapMask(this.scene, renderable); + }, + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * + * @method Phaser.GameObjects.Components.Mask#createGeometryMask + * @since 3.6.2 + * + * @param {Phaser.GameObjects.Graphics} [graphics] - A Graphics Game Object. The geometry within it will be used as the mask. + * + * @return {Phaser.Display.Masks.GeometryMask} This Geometry Mask that was created. + */ + createGeometryMask: function (graphics) + { + if (graphics === undefined && this.type === 'Graphics') + { + // eslint-disable-next-line consistent-this + graphics = this; + } + + return new GeometryMask(this.scene, graphics); + } + +}; + +module.exports = Mask; + + +/***/ }), +/* 297 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GameEvents = __webpack_require__(21); + +/** + * @classdesc + * A Bitmap Mask combines the alpha (opacity) of a masked pixel with the alpha of another pixel. + * Unlike the Geometry Mask, which is a clipping path, a Bitmap Mask behaves like an alpha mask, + * not a clipping path. It is only available when using the WebGL Renderer. + * + * A Bitmap Mask can use any Game Object to determine the alpha of each pixel of the masked Game Object(s). + * For any given point of a masked Game Object's texture, the pixel's alpha will be multiplied by the alpha + * of the pixel at the same position in the Bitmap Mask's Game Object. The color of the pixel from the + * Bitmap Mask doesn't matter. + * + * For example, if a pure blue pixel with an alpha of 0.95 is masked with a pure red pixel with an + * alpha of 0.5, the resulting pixel will be pure blue with an alpha of 0.475. Naturally, this means + * that a pixel in the mask with an alpha of 0 will hide the corresponding pixel in all masked Game Objects + * A pixel with an alpha of 1 in the masked Game Object will receive the same alpha as the + * corresponding pixel in the mask. + * + * The Bitmap Mask's location matches the location of its Game Object, not the location of the + * masked objects. Moving or transforming the underlying Game Object will change the mask + * (and affect the visibility of any masked objects), whereas moving or transforming a masked object + * will not affect the mask. + * + * The Bitmap Mask will not render its Game Object by itself. If the Game Object is not in a + * Scene's display list, it will only be used for the mask and its full texture will not be directly + * visible. Adding the underlying Game Object to a Scene will not cause any problems - it will + * render as a normal Game Object and will also serve as a mask. + * + * @class BitmapMask + * @memberof Phaser.Display.Masks + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which this Bitmap Mask will be used in. + * @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite. + */ +var BitmapMask = new Class({ + + initialize: + + function BitmapMask (scene, renderable) + { + var renderer = scene.sys.game.renderer; + + /** + * A reference to either the Canvas or WebGL Renderer that this Mask is using. + * + * @name Phaser.Display.Masks.BitmapMask#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.11.0 + */ + this.renderer = renderer; + + /** + * A renderable Game Object that uses a texture, such as a Sprite. + * + * @name Phaser.Display.Masks.BitmapMask#bitmapMask + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.bitmapMask = renderable; + + /** + * The texture used for the mask's framebuffer. + * + * @name Phaser.Display.Masks.BitmapMask#maskTexture + * @type {WebGLTexture} + * @default null + * @since 3.0.0 + */ + this.maskTexture = null; + + /** + * The texture used for the main framebuffer. + * + * @name Phaser.Display.Masks.BitmapMask#mainTexture + * @type {WebGLTexture} + * @default null + * @since 3.0.0 + */ + this.mainTexture = null; + + /** + * Whether the Bitmap Mask is dirty and needs to be updated. + * + * @name Phaser.Display.Masks.BitmapMask#dirty + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.dirty = true; + + /** + * The framebuffer to which a masked Game Object is rendered. + * + * @name Phaser.Display.Masks.BitmapMask#mainFramebuffer + * @type {WebGLFramebuffer} + * @since 3.0.0 + */ + this.mainFramebuffer = null; + + /** + * The framebuffer to which the Bitmap Mask's masking Game Object is rendered. + * + * @name Phaser.Display.Masks.BitmapMask#maskFramebuffer + * @type {WebGLFramebuffer} + * @since 3.0.0 + */ + this.maskFramebuffer = null; + + /** + * The previous framebuffer set in the renderer before this one was enabled. + * + * @name Phaser.Display.Masks.BitmapMask#prevFramebuffer + * @type {WebGLFramebuffer} + * @since 3.17.0 + */ + this.prevFramebuffer = null; + + /** + * Whether to invert the masks alpha. + * + * If `true`, the alpha of the masking pixel will be inverted before it's multiplied with the masked pixel. Essentially, this means that a masked area will be visible only if the corresponding area in the mask is invisible. + * + * @name Phaser.Display.Masks.BitmapMask#invertAlpha + * @type {boolean} + * @since 3.1.2 + */ + this.invertAlpha = false; + + /** + * Is this mask a stencil mask? + * + * @name Phaser.Display.Masks.BitmapMask#isStencil + * @type {boolean} + * @readonly + * @since 3.17.0 + */ + this.isStencil = false; + + if (renderer && renderer.gl) + { + var width = renderer.width; + var height = renderer.height; + var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0); + var gl = renderer.gl; + var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; + var filter = gl.LINEAR; + + this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true); + this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true); + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer) + { + var width = renderer.width; + var height = renderer.height; + var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0); + var gl = renderer.gl; + var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; + var filter = gl.LINEAR; + + this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true); + this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true); + + }, this); + } + }, + + /** + * Sets a new masking Game Object for the Bitmap Mask. + * + * @method Phaser.Display.Masks.BitmapMask#setBitmap + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite. + */ + setBitmap: function (renderable) + { + this.bitmapMask = renderable; + }, + + /** + * Prepares the WebGL Renderer to render a Game Object with this mask applied. + * + * This renders the masking Game Object to the mask framebuffer and switches to the main framebuffer so that the masked Game Object will be rendered to it instead of being rendered directly to the frame. + * + * @method Phaser.Display.Masks.BitmapMask#preRenderWebGL + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to prepare. + * @param {Phaser.GameObjects.GameObject} maskedObject - The masked Game Object which will be drawn. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to. + */ + preRenderWebGL: function (renderer, maskedObject, camera) + { + renderer.pipelines.BitmapMaskPipeline.beginMask(this, maskedObject, camera); + }, + + /** + * Finalizes rendering of a masked Game Object. + * + * This resets the previously bound framebuffer and switches the WebGL Renderer to the Bitmap Mask Pipeline, which uses a special fragment shader to apply the masking effect. + * + * @method Phaser.Display.Masks.BitmapMask#postRenderWebGL + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to clean up. + */ + postRenderWebGL: function (renderer, camera) + { + renderer.pipelines.BitmapMaskPipeline.endMask(this, camera); + }, + + /** + * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. + * + * @method Phaser.Display.Masks.BitmapMask#preRenderCanvas + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to. + * @param {Phaser.GameObjects.GameObject} mask - The masked Game Object which would be rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to. + */ + preRenderCanvas: function () + { + // NOOP + }, + + /** + * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. + * + * @method Phaser.Display.Masks.BitmapMask#postRenderCanvas + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to. + */ + postRenderCanvas: function () + { + // NOOP + }, + + /** + * Destroys this BitmapMask and nulls any references it holds. + * + * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, + * so be sure to call `clearMask` on any Game Object using it, before destroying it. + * + * @method Phaser.Display.Masks.BitmapMask#destroy + * @since 3.7.0 + */ + destroy: function () + { + this.bitmapMask = null; + + var renderer = this.renderer; + + if (renderer && renderer.gl) + { + renderer.deleteTexture(this.mainTexture); + renderer.deleteTexture(this.maskTexture); + renderer.deleteFramebuffer(this.mainFramebuffer); + renderer.deleteFramebuffer(this.maskFramebuffer); + } + + this.mainTexture = null; + this.maskTexture = null; + this.mainFramebuffer = null; + this.maskFramebuffer = null; + this.prevFramebuffer = null; + this.renderer = null; + } + +}); + +module.exports = BitmapMask; + + +/***/ }), +/* 298 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A Geometry Mask can be applied to a Game Object to hide any pixels of it which don't intersect + * a visible pixel from the geometry mask. The mask is essentially a clipping path which can only + * make a masked pixel fully visible or fully invisible without changing its alpha (opacity). + * + * A Geometry Mask uses a Graphics Game Object to determine which pixels of the masked Game Object(s) + * should be clipped. For any given point of a masked Game Object's texture, the pixel will only be displayed + * if the Graphics Game Object of the Geometry Mask has a visible pixel at the same position. The color and + * alpha of the pixel from the Geometry Mask do not matter. + * + * The Geometry Mask's location matches the location of its Graphics object, not the location of the masked objects. + * Moving or transforming the underlying Graphics object will change the mask (and affect the visibility + * of any masked objects), whereas moving or transforming a masked object will not affect the mask. + * You can think of the Geometry Mask (or rather, of its Graphics object) as an invisible curtain placed + * in front of all masked objects which has its own visual properties and, naturally, respects the camera's + * visual properties, but isn't affected by and doesn't follow the masked objects by itself. + * + * @class GeometryMask + * @memberof Phaser.Display.Masks + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - This parameter is not used. + * @param {Phaser.GameObjects.Graphics} graphicsGeometry - The Graphics Game Object to use for the Geometry Mask. Doesn't have to be in the Display List. + */ +var GeometryMask = new Class({ + + initialize: + + function GeometryMask (scene, graphicsGeometry) + { + /** + * The Graphics object which describes the Geometry Mask. + * + * @name Phaser.Display.Masks.GeometryMask#geometryMask + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.geometryMask = graphicsGeometry; + + /** + * Similar to the BitmapMasks invertAlpha setting this to true will then hide all pixels + * drawn to the Geometry Mask. + * + * @name Phaser.Display.Masks.GeometryMask#invertAlpha + * @type {boolean} + * @since 3.16.0 + */ + this.invertAlpha = false; + + /** + * Is this mask a stencil mask? + * + * @name Phaser.Display.Masks.GeometryMask#isStencil + * @type {boolean} + * @readonly + * @since 3.17.0 + */ + this.isStencil = true; + + /** + * The current stencil level. + * + * @name Phaser.Display.Masks.GeometryMask#level + * @type {boolean} + * @private + * @since 3.17.0 + */ + this.level = 0; + }, + + /** + * Sets a new Graphics object for the Geometry Mask. + * + * @method Phaser.Display.Masks.GeometryMask#setShape + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphicsGeometry - The Graphics object which will be used for the Geometry Mask. + * + * @return {this} This Geometry Mask + */ + setShape: function (graphicsGeometry) + { + this.geometryMask = graphicsGeometry; + + return this; + }, + + /** + * Sets the `invertAlpha` property of this Geometry Mask. + * Inverting the alpha essentially flips the way the mask works. + * + * @method Phaser.Display.Masks.GeometryMask#setInvertAlpha + * @since 3.17.0 + * + * @param {boolean} [value=true] - Invert the alpha of this mask? + * + * @return {this} This Geometry Mask + */ + setInvertAlpha: function (value) + { + if (value === undefined) { value = true; } + + this.invertAlpha = value; + + return this; + }, + + /** + * Renders the Geometry Mask's underlying Graphics object to the OpenGL stencil buffer and enables the stencil test, which clips rendered pixels according to the mask. + * + * @method Phaser.Display.Masks.GeometryMask#preRenderWebGL + * @since 3.0.0 + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw to. + * @param {Phaser.GameObjects.GameObject} child - The Game Object being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. + */ + preRenderWebGL: function (renderer, child, camera) + { + var gl = renderer.gl; + + // Force flushing before drawing to stencil buffer + renderer.flush(); + + if (renderer.maskStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + + renderer.maskCount = 0; + } + + if (renderer.currentCameraMask.mask !== this) + { + renderer.currentMask.mask = this; + } + + renderer.maskStack.push({ mask: this, camera: camera }); + + this.applyStencil(renderer, camera, true); + + renderer.maskCount++; + }, + + /** + * Applies the current stencil mask to the renderer. + * + * @method Phaser.Display.Masks.GeometryMask#applyStencil + * @since 3.17.0 + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw to. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. + * @param {boolean} inc - Is this an INCR stencil or a DECR stencil? + */ + applyStencil: function (renderer, camera, inc) + { + var gl = renderer.gl; + var geometryMask = this.geometryMask; + var level = renderer.maskCount; + + gl.colorMask(false, false, false, false); + + if (inc) + { + gl.stencilFunc(gl.EQUAL, level, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL, level + 1, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + } + + // Write stencil buffer + geometryMask.renderWebGL(renderer, geometryMask, 0, camera); + + renderer.flush(); + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + + if (inc) + { + if (this.invertAlpha) + { + gl.stencilFunc(gl.NOTEQUAL, level + 1, 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL, level + 1, 0xFF); + } + } + else if (this.invertAlpha) + { + gl.stencilFunc(gl.NOTEQUAL, level, 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL, level, 0xFF); + } + }, + + /** + * Flushes all rendered pixels and disables the stencil test of a WebGL context, thus disabling the mask for it. + * + * @method Phaser.Display.Masks.GeometryMask#postRenderWebGL + * @since 3.0.0 + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw flush. + */ + postRenderWebGL: function (renderer) + { + var gl = renderer.gl; + + renderer.maskStack.pop(); + + renderer.maskCount--; + + if (renderer.maskStack.length === 0) + { + // If this is the only mask in the stack, flush and disable + renderer.flush(); + + renderer.currentMask.mask = null; + + gl.disable(gl.STENCIL_TEST); + } + else + { + // Force flush before disabling stencil test + renderer.flush(); + + var prev = renderer.maskStack[renderer.maskStack.length - 1]; + + prev.mask.applyStencil(renderer, prev.camera, false); + + if (renderer.currentCameraMask.mask !== prev.mask) + { + renderer.currentMask.mask = prev.mask; + renderer.currentMask.camera = prev.camera; + } + else + { + renderer.currentMask.mask = null; + } + } + }, + + /** + * Sets the clipping path of a 2D canvas context to the Geometry Mask's underlying Graphics object. + * + * @method Phaser.Display.Masks.GeometryMask#preRenderCanvas + * @since 3.0.0 + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - The Canvas Renderer instance to set the clipping path on. + * @param {Phaser.GameObjects.GameObject} mask - The Game Object being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. + */ + preRenderCanvas: function (renderer, mask, camera) + { + var geometryMask = this.geometryMask; + + renderer.currentContext.save(); + + geometryMask.renderCanvas(renderer, geometryMask, 0, camera, null, null, true); + + renderer.currentContext.clip(); + }, + + /** + * Restore the canvas context's previous clipping path, thus turning off the mask for it. + * + * @method Phaser.Display.Masks.GeometryMask#postRenderCanvas + * @since 3.0.0 + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - The Canvas Renderer instance being restored. + */ + postRenderCanvas: function (renderer) + { + renderer.currentContext.restore(); + }, + + /** + * Destroys this GeometryMask and nulls any references it holds. + * + * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, + * so be sure to call `clearMask` on any Game Object using it, before destroying it. + * + * @method Phaser.Display.Masks.GeometryMask#destroy + * @since 3.7.0 + */ + destroy: function () + { + this.geometryMask = null; + } + +}); + +module.exports = GeometryMask; + + +/***/ }), +/* 299 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the Scroll Factor of a Game Object. + * + * @namespace Phaser.GameObjects.Components.ScrollFactor + * @since 3.0.0 + */ + +var ScrollFactor = { + + /** + * 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 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.Components.ScrollFactor#scrollFactorX + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scrollFactorX: 1, + + /** + * 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 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.Components.ScrollFactor#scrollFactorY + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scrollFactorY: 1, + + /** + * Sets the 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 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.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. + */ + setScrollFactor: function (x, y) + { + if (y === undefined) { y = x; } + + this.scrollFactorX = x; + this.scrollFactorY = y; + + return this; + } + +}; + +module.exports = ScrollFactor; + + +/***/ }), +/* 300 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Build a JSON representation of the given Game Object. + * + * This is typically extended further by Game Object specific implementations. + * + * @method Phaser.GameObjects.Components.ToJSON + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to export as JSON. + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ +var ToJSON = function (gameObject) +{ + var out = { + name: gameObject.name, + type: gameObject.type, + x: gameObject.x, + y: gameObject.y, + depth: gameObject.depth, + scale: { + x: gameObject.scaleX, + y: gameObject.scaleY + }, + origin: { + x: gameObject.originX, + y: gameObject.originY + }, + flipX: gameObject.flipX, + flipY: gameObject.flipY, + rotation: gameObject.rotation, + alpha: gameObject.alpha, + visible: gameObject.visible, + blendMode: gameObject.blendMode, + textureKey: '', + frameKey: '', + data: {} + }; + + if (gameObject.texture) + { + out.textureKey = gameObject.texture.key; + out.frameKey = gameObject.frame.name; + } + + return out; +}; + +module.exports = ToJSON; + + +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = __webpack_require__(13); +var TransformMatrix = __webpack_require__(35); +var WrapAngle = __webpack_require__(165); +var WrapAngleDegrees = __webpack_require__(166); + +// global bitmask flag for GameObject.renderMask (used by Scale) +var _FLAG = 4; // 0100 + +/** + * Provides methods used for getting and setting the position, scale and rotation of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Transform + * @since 3.0.0 + */ + +var Transform = { + + /** + * Private internal value. Holds the horizontal scale value. + * + * @name Phaser.GameObjects.Components.Transform#_scaleX + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _scaleX: 1, + + /** + * Private internal value. Holds the vertical scale value. + * + * @name Phaser.GameObjects.Components.Transform#_scaleY + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _scaleY: 1, + + /** + * Private internal value. Holds the rotation value in radians. + * + * @name Phaser.GameObjects.Components.Transform#_rotation + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + _rotation: 0, + + /** + * The x position of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + x: 0, + + /** + * The y position of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + y: 0, + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + * + * @name Phaser.GameObjects.Components.Transform#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + z: 0, + + /** + * The w position of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#w + * @type {number} + * @default 0 + * @since 3.0.0 + */ + w: 0, + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + * + * @name Phaser.GameObjects.Components.Transform#scale + * @type {number} + * @default 1 + * @since 3.18.0 + */ + scale: { + + get: function () + { + return (this._scaleX + this._scaleY) / 2; + }, + + set: function (value) + { + this._scaleX = value; + this._scaleY = value; + + if (value === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The horizontal scale of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#scaleX + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scaleX: { + + get: function () + { + return this._scaleX; + }, + + set: function (value) + { + this._scaleX = value; + + if (value === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The vertical scale of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#scaleY + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scaleY: { + + get: function () + { + return this._scaleY; + }, + + set: function (value) + { + this._scaleY = value; + + if (value === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + * + * @name Phaser.GameObjects.Components.Transform#angle + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + angle: { + + get: function () + { + return WrapAngleDegrees(this._rotation * MATH_CONST.RAD_TO_DEG); + }, + + set: function (value) + { + // value is in degrees + this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD; + } + }, + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + * + * @name Phaser.GameObjects.Components.Transform#rotation + * @type {number} + * @default 1 + * @since 3.0.0 + */ + rotation: { + + get: function () + { + return this._rotation; + }, + + set: function (value) + { + // value is in radians + this._rotation = WrapAngle(value); + } + }, + + /** + * Sets the position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setPosition + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of this Game Object. + * @param {number} [y=x] - The y position of this Game Object. If not set it will use the `x` value. + * @param {number} [z=0] - The z position of this Game Object. + * @param {number} [w=0] - The w position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setPosition: function (x, y, z, w) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + if (z === undefined) { z = 0; } + if (w === undefined) { w = 0; } + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + return this; + }, + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * + * @method Phaser.GameObjects.Components.Transform#setRandomPosition + * @since 3.8.0 + * + * @param {number} [x=0] - The x position of the top-left of the random area. + * @param {number} [y=0] - The y position of the top-left of the random area. + * @param {number} [width] - The width of the random area. + * @param {number} [height] - The height of the random area. + * + * @return {this} This Game Object instance. + */ + setRandomPosition: function (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + + this.x = x + (Math.random() * width); + this.y = y + (Math.random() * height); + + return this; + }, + + /** + * Sets the rotation of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setRotation + * @since 3.0.0 + * + * @param {number} [radians=0] - The rotation of this Game Object, in radians. + * + * @return {this} This Game Object instance. + */ + setRotation: function (radians) + { + if (radians === undefined) { radians = 0; } + + this.rotation = radians; + + return this; + }, + + /** + * Sets the angle of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setAngle + * @since 3.0.0 + * + * @param {number} [degrees=0] - The rotation of this Game Object, in degrees. + * + * @return {this} This Game Object instance. + */ + setAngle: function (degrees) + { + if (degrees === undefined) { degrees = 0; } + + this.angle = degrees; + + return this; + }, + + /** + * Sets the scale of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setScale + * @since 3.0.0 + * + * @param {number} x - The horizontal scale of this Game Object. + * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the `x` value. + * + * @return {this} This Game Object instance. + */ + setScale: function (x, y) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + this.scaleX = x; + this.scaleY = y; + + return this; + }, + + /** + * Sets the x position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setX + * @since 3.0.0 + * + * @param {number} [value=0] - The x position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setX: function (value) + { + if (value === undefined) { value = 0; } + + this.x = value; + + return this; + }, + + /** + * Sets the y position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setY + * @since 3.0.0 + * + * @param {number} [value=0] - The y position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setY: function (value) + { + if (value === undefined) { value = 0; } + + this.y = value; + + return this; + }, + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * + * @method Phaser.GameObjects.Components.Transform#setZ + * @since 3.0.0 + * + * @param {number} [value=0] - The z position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setZ: function (value) + { + if (value === undefined) { value = 0; } + + this.z = value; + + return this; + }, + + /** + * Sets the w position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setW + * @since 3.0.0 + * + * @param {number} [value=0] - The w position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setW: function (value) + { + if (value === undefined) { value = 0; } + + this.w = value; + + return this; + }, + + /** + * Gets the local transform matrix for this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#getLocalTransformMatrix + * @since 3.4.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} [tempMatrix] - The matrix to populate with the values from this Game Object. + * + * @return {Phaser.GameObjects.Components.TransformMatrix} The populated Transform Matrix. + */ + getLocalTransformMatrix: function (tempMatrix) + { + if (tempMatrix === undefined) { tempMatrix = new TransformMatrix(); } + + return tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); + }, + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * + * @method Phaser.GameObjects.Components.Transform#getWorldTransformMatrix + * @since 3.4.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} [tempMatrix] - The matrix to populate with the values from this Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentMatrix] - A temporary matrix to hold parent values during the calculations. + * + * @return {Phaser.GameObjects.Components.TransformMatrix} The populated Transform Matrix. + */ + getWorldTransformMatrix: function (tempMatrix, parentMatrix) + { + if (tempMatrix === undefined) { tempMatrix = new TransformMatrix(); } + if (parentMatrix === undefined) { parentMatrix = new TransformMatrix(); } + + var parent = this.parentContainer; + + if (!parent) + { + return this.getLocalTransformMatrix(tempMatrix); + } + + tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); + + while (parent) + { + parentMatrix.applyITRS(parent.x, parent.y, parent._rotation, parent._scaleX, parent._scaleY); + + parentMatrix.multiply(tempMatrix, tempMatrix); + + parent = parent.parentContainer; + } + + return tempMatrix; + }, + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + * + * @method Phaser.GameObjects.Components.Transform#getParentRotation + * @since 3.18.0 + * + * @return {number} The sum total rotation, in radians, of all parent containers of this Game Object. + */ + getParentRotation: function () + { + var rotation = 0; + + var parent = this.parentContainer; + + while (parent) + { + rotation += parent.rotation; + + parent = parent.parentContainer; + } + + return rotation; + } + +}; + +module.exports = Transform; + + +/***/ }), +/* 302 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// bitmask flag for GameObject.renderMask +var _FLAG = 1; // 0001 + +/** + * Provides methods used for setting the visibility of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Visible + * @since 3.0.0 + */ + +var Visible = { + + /** + * Private internal value. Holds the visible value. + * + * @name Phaser.GameObjects.Components.Visible#_visible + * @type {boolean} + * @private + * @default true + * @since 3.0.0 + */ + _visible: true, + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * + * @name Phaser.GameObjects.Components.Visible#visible + * @type {boolean} + * @since 3.0.0 + */ + visible: { + + get: function () + { + return this._visible; + }, + + set: function (value) + { + if (value) + { + this._visible = true; + this.renderFlags |= _FLAG; + } + else + { + this._visible = false; + this.renderFlags &= ~_FLAG; + } + } + + }, + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * + * @method Phaser.GameObjects.Components.Visible#setVisible + * @since 3.0.0 + * + * @param {boolean} value - The visible state of the Game Object. + * + * @return {this} This Game Object instance. + */ + setVisible: function (value) + { + this.visible = value; + + return this; + } +}; + +module.exports = Visible; + + +/***/ }), +/* 303 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Data.Events + */ + +module.exports = { + + CHANGE_DATA: __webpack_require__(604), + CHANGE_DATA_KEY: __webpack_require__(605), + REMOVE_DATA: __webpack_require__(606), + SET_DATA: __webpack_require__(607) + +}; + + +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Perimeter = __webpack_require__(120); +var Point = __webpack_require__(4); + + +/** + * Return an array of points from the perimeter of the rectangle + * each spaced out based on the quantity or step required + * + * @function Phaser.Geom.Rectangle.MarchingAnts + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - [description] + * @param {number} step - [description] + * @param {integer} quantity - [description] + * @param {(array|Phaser.Geom.Point[])} [out] - [description] + * + * @return {(array|Phaser.Geom.Point[])} [description] + */ +var MarchingAnts = function (rect, step, quantity, out) +{ + if (out === undefined) { out = []; } + + if (!step && !quantity) + { + // Bail out + return 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 + if (!step) + { + step = Perimeter(rect) / quantity; + } + else + { + quantity = Math.round(Perimeter(rect) / step); + } + + var x = rect.x; + var y = rect.y; + var face = 0; + + // Loop across each face of the rectangle + + for (var i = 0; i < quantity; i++) + { + out.push(new Point(x, y)); + + switch (face) + { + + // Top face + case 0: + x += step; + + if (x >= rect.right) + { + face = 1; + y += (x - rect.right); + x = rect.right; + } + break; + + // Right face + case 1: + y += step; + + if (y >= rect.bottom) + { + face = 2; + x -= (y - rect.bottom); + y = rect.bottom; + } + break; + + // Bottom face + case 2: + x -= step; + + if (x <= rect.left) + { + face = 3; + y -= (rect.left - x); + x = rect.left; + } + break; + + // Left face + case 3: + y -= step; + + if (y <= rect.top) + { + face = 0; + y = rect.top; + } + break; + } + } + + return out; +}; + +module.exports = MarchingAnts; + + +/***/ }), +/* 305 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the element at the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * @function Phaser.Utils.Array.RotateLeft + * @since 3.0.0 + * + * @param {array} array - The array to shift to the left. This array is modified in place. + * @param {integer} [total=1] - The number of times to shift the array. + * + * @return {*} The most recently shifted element. + */ +var RotateLeft = function (array, total) +{ + if (total === undefined) { total = 1; } + + var element = null; + + for (var i = 0; i < total; i++) + { + element = array.shift(); + array.push(element); + } + + return element; +}; + +module.exports = RotateLeft; + + +/***/ }), +/* 306 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the element at the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * @function Phaser.Utils.Array.RotateRight + * @since 3.0.0 + * + * @param {array} array - The array to shift to the right. This array is modified in place. + * @param {integer} [total=1] - The number of times to shift the array. + * + * @return {*} The most recently shifted element. + */ +var RotateRight = function (array, total) +{ + if (total === undefined) { total = 1; } + + var element = null; + + for (var i = 0; i < total; i++) + { + element = array.pop(); + array.unshift(element); + } + + return element; +}; + +module.exports = RotateRight; + + +/***/ }), +/* 307 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * + * The `start` and `end` points are rounded before this runs as the algorithm works on integers. + * + * @function Phaser.Geom.Line.BresenhamPoints + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line. + * @param {integer} [stepRate=1] - The optional step rate for the points on the line. + * @param {Phaser.Types.Math.Vector2Like[]} [results] - An optional array to push the resulting coordinates into. + * + * @return {Phaser.Types.Math.Vector2Like[]} The array of coordinates on the line. + */ +var BresenhamPoints = function (line, stepRate, results) +{ + if (stepRate === undefined) { stepRate = 1; } + if (results === undefined) { results = []; } + + var x1 = Math.round(line.x1); + var y1 = Math.round(line.y1); + var x2 = Math.round(line.x2); + var y2 = Math.round(line.y2); + + var dx = Math.abs(x2 - x1); + var dy = Math.abs(y2 - y1); + var sx = (x1 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push({ x: x1, y: y1 }); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push({ x: x1, y: y1 }); + } + + i++; + } + + return results; +}; + +module.exports = BresenhamPoints; + + +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Animation = __webpack_require__(160); +var Class = __webpack_require__(0); +var CustomMap = __webpack_require__(172); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(119); +var GameEvents = __webpack_require__(21); +var GetValue = __webpack_require__(5); +var Pad = __webpack_require__(173); + +/** + * @classdesc + * The Animation Manager. + * + * Animations are managed by the global Animation Manager. This is a singleton class that is + * responsible for creating and delivering animations and their corresponding data to all Game Objects. + * Unlike plugins it is owned by the Game instance, not the Scene. + * + * Sprites and other Game Objects get the data they need from the AnimationManager. + * + * @class AnimationManager + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Animations + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser.Game instance. + */ +var AnimationManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function AnimationManager (game) + { + EventEmitter.call(this); + + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.Animations.AnimationManager#game + * @type {Phaser.Game} + * @protected + * @since 3.0.0 + */ + this.game = game; + + /** + * A reference to the Texture Manager. + * + * @name Phaser.Animations.AnimationManager#textureManager + * @type {Phaser.Textures.TextureManager} + * @protected + * @since 3.0.0 + */ + this.textureManager = null; + + /** + * The global time scale of the Animation Manager. + * + * This scales the time delta between two frames, thus influencing the speed of time for the Animation Manager. + * + * @name Phaser.Animations.AnimationManager#globalTimeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.globalTimeScale = 1; + + /** + * The Animations registered in the Animation Manager. + * + * This map should be modified with the {@link #add} and {@link #create} methods of the Animation Manager. + * + * @name Phaser.Animations.AnimationManager#anims + * @type {Phaser.Structs.Map.} + * @protected + * @since 3.0.0 + */ + this.anims = new CustomMap(); + + /** + * Whether the Animation Manager is paused along with all of its Animations. + * + * @name Phaser.Animations.AnimationManager#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * The name of this Animation Manager. + * + * @name Phaser.Animations.AnimationManager#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'AnimationManager'; + + game.events.once(GameEvents.BOOT, this.boot, this); + }, + + /** + * Registers event listeners after the Game boots. + * + * @method Phaser.Animations.AnimationManager#boot + * @listens Phaser.Core.Events#DESTROY + * @since 3.0.0 + */ + boot: function () + { + this.textureManager = this.game.textures; + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Adds an existing Animation to the Animation Manager. + * + * @method Phaser.Animations.AnimationManager#add + * @fires Phaser.Animations.Events#ADD_ANIMATION + * @since 3.0.0 + * + * @param {string} key - The key under which the Animation should be added. The Animation will be updated with it. Must be unique. + * @param {Phaser.Animations.Animation} animation - The Animation which should be added to the Animation Manager. + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + add: function (key, animation) + { + if (this.anims.has(key)) + { + console.warn('Animation key exists: ' + key); + + return; + } + + animation.key = key; + + this.anims.set(key, animation); + + this.emit(Events.ADD_ANIMATION, key, animation); + + return this; + }, + + /** + * Checks to see if the given key is already in use within the Animation Manager or not. + * + * Animations are global. Keys created in one scene can be used from any other Scene in your game. They are not Scene specific. + * + * @method Phaser.Animations.AnimationManager#exists + * @since 3.16.0 + * + * @param {string} key - The key of the Animation to check. + * + * @return {boolean} `true` if the Animation already exists in the Animation Manager, or `false` if the key is available. + */ + exists: function (key) + { + return this.anims.has(key); + }, + + /** + * Creates a new Animation and adds it to the Animation Manager. + * + * Animations are global. Once created, you can use them in any Scene in your game. They are not Scene specific. + * + * If an invalid key is given this method will return `false`. + * + * If you pass the key of an animation that already exists in the Animation Manager, that animation will be returned. + * + * A brand new animation is only created if the key is valid and not already in use. + * + * If you wish to re-use an existing key, call `AnimationManager.remove` first, then this method. + * + * @method Phaser.Animations.AnimationManager#create + * @fires Phaser.Animations.Events#ADD_ANIMATION + * @since 3.0.0 + * + * @param {Phaser.Types.Animations.Animation} config - The configuration settings for the Animation. + * + * @return {(Phaser.Animations.Animation|false)} The Animation that was created, or `false` is the key is already in use. + */ + create: function (config) + { + var key = config.key; + + var anim = false; + + if (key) + { + anim = this.get(key); + + if (!anim) + { + anim = new Animation(this, key, config); + + this.anims.set(key, anim); + + this.emit(Events.ADD_ANIMATION, key, anim); + } + } + + return anim; + }, + + /** + * Loads this Animation Manager's Animations and settings from a JSON object. + * + * @method Phaser.Animations.AnimationManager#fromJSON + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Animations.JSONAnimations|Phaser.Types.Animations.JSONAnimation)} data - The JSON object to parse. + * @param {boolean} [clearCurrentAnimations=false] - If set to `true`, the current animations will be removed (`anims.clear()`). If set to `false` (default), the animations in `data` will be added. + * + * @return {Phaser.Animations.Animation[]} An array containing all of the Animation objects that were created as a result of this call. + */ + fromJSON: function (data, clearCurrentAnimations) + { + if (clearCurrentAnimations === undefined) { clearCurrentAnimations = false; } + + if (clearCurrentAnimations) + { + this.anims.clear(); + } + + // Do we have a String (i.e. from JSON, or an Object?) + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + var output = []; + + // Array of animations, or a single animation? + if (data.hasOwnProperty('anims') && Array.isArray(data.anims)) + { + for (var i = 0; i < data.anims.length; i++) + { + output.push(this.create(data.anims[i])); + } + + if (data.hasOwnProperty('globalTimeScale')) + { + this.globalTimeScale = data.globalTimeScale; + } + } + else if (data.hasOwnProperty('key') && data.type === 'frame') + { + output.push(this.create(data)); + } + + return output; + }, + + /** + * [description] + * + * @method Phaser.Animations.AnimationManager#generateFrameNames + * @since 3.0.0 + * + * @param {string} key - The key for the texture containing the animation frames. + * @param {Phaser.Types.Animations.GenerateFrameNames} [config] - The configuration object for the animation frame names. + * + * @return {Phaser.Types.Animations.AnimationFrame[]} The array of {@link Phaser.Types.Animations.AnimationFrame} objects. + */ + generateFrameNames: function (key, config) + { + var prefix = GetValue(config, 'prefix', ''); + var start = GetValue(config, 'start', 0); + var end = GetValue(config, 'end', 0); + var suffix = GetValue(config, 'suffix', ''); + var zeroPad = GetValue(config, 'zeroPad', 0); + var out = GetValue(config, 'outputArray', []); + var frames = GetValue(config, 'frames', false); + + var texture = this.textureManager.get(key); + + if (!texture) + { + return out; + } + + var diff = (start < end) ? 1 : -1; + + // Adjust because we use i !== end in the for loop + end += diff; + + var i; + var frame; + + if (!config) + { + // Use every frame in the atlas? + frames = texture.getFrameNames(); + + for (i = 0; i < frames.length; i++) + { + out.push({ key: key, frame: frames[i] }); + } + } + else if (Array.isArray(frames)) + { + // Have they provided their own custom frame sequence array? + for (i = 0; i < frames.length; i++) + { + frame = prefix + Pad(frames[i], zeroPad, '0', 1) + suffix; + + if (texture.has(frame)) + { + out.push({ key: key, frame: frame }); + } + } + } + else + { + for (i = start; i !== end; i += diff) + { + frame = prefix + Pad(i, zeroPad, '0', 1) + suffix; + + if (texture.has(frame)) + { + out.push({ key: key, frame: frame }); + } + } + } + + return out; + }, + + /** + * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. + * + * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. + * + * @method Phaser.Animations.AnimationManager#generateFrameNumbers + * @since 3.0.0 + * + * @param {string} key - The key for the texture containing the animation frames. + * @param {Phaser.Types.Animations.GenerateFrameNumbers} config - The configuration object for the animation frames. + * + * @return {Phaser.Types.Animations.AnimationFrame[]} The array of {@link Phaser.Types.Animations.AnimationFrame} objects. + */ + generateFrameNumbers: function (key, config) + { + var startFrame = GetValue(config, 'start', 0); + var endFrame = GetValue(config, 'end', -1); + var firstFrame = GetValue(config, 'first', false); + var out = GetValue(config, 'outputArray', []); + var frames = GetValue(config, 'frames', false); + + var texture = this.textureManager.get(key); + + if (!texture) + { + return out; + } + + if (firstFrame && texture.has(firstFrame)) + { + out.push({ key: key, frame: firstFrame }); + } + + var i; + + // Have they provided their own custom frame sequence array? + if (Array.isArray(frames)) + { + for (i = 0; i < frames.length; i++) + { + if (texture.has(frames[i])) + { + out.push({ key: key, frame: frames[i] }); + } + } + } + else + { + // No endFrame then see if we can get it + if (endFrame === -1) + { + endFrame = texture.frameTotal; + } + + var diff = (startFrame < endFrame) ? 1 : -1; + + // Adjust because we use i !== end in the for loop + endFrame += diff; + + for (i = startFrame; i !== endFrame; i += diff) + { + if (texture.has(i)) + { + out.push({ key: key, frame: i }); + } + } + } + + return out; + }, + + /** + * Get an Animation. + * + * @method Phaser.Animations.AnimationManager#get + * @since 3.0.0 + * + * @param {string} key - The key of the Animation to retrieve. + * + * @return {Phaser.Animations.Animation} The Animation. + */ + get: function (key) + { + return this.anims.get(key); + }, + + /** + * Load an Animation into a Game Object's Animation Component. + * + * @method Phaser.Animations.AnimationManager#load + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to load the animation into. + * @param {string} key - The key of the animation to load. + * @param {(string|integer)} [startFrame] - The name of a start frame to set on the loaded animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object with the animation loaded into it. + */ + load: function (child, key, startFrame) + { + var anim = this.get(key); + + if (anim) + { + anim.load(child, startFrame); + } + else + { + console.warn('Missing animation: ' + key); + } + + return child; + }, + + /** + * Pause all animations. + * + * @method Phaser.Animations.AnimationManager#pauseAll + * @fires Phaser.Animations.Events#PAUSE_ALL + * @since 3.0.0 + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + pauseAll: function () + { + if (!this.paused) + { + this.paused = true; + + this.emit(Events.PAUSE_ALL); + } + + return this; + }, + + /** + * Play an animation on the given Game Objects that have an Animation Component. + * + * @method Phaser.Animations.AnimationManager#play + * @since 3.0.0 + * + * @param {string} key - The key of the animation to play on the Game Object. + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Objects to play the animation on. + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + play: function (key, child) + { + if (!Array.isArray(child)) + { + child = [ child ]; + } + + var anim = this.get(key); + + if (!anim) + { + return; + } + + for (var i = 0; i < child.length; i++) + { + child[i].anims.play(key); + } + + return this; + }, + + /** + * Remove an animation. + * + * @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} [description] + */ + remove: function (key) + { + var anim = this.get(key); + + if (anim) + { + this.emit(Events.REMOVE_ANIMATION, key, anim); + + this.anims.delete(key); + } + + return anim; + }, + + /** + * Resume all paused animations. + * + * @method Phaser.Animations.AnimationManager#resumeAll + * @fires Phaser.Animations.Events#RESUME_ALL + * @since 3.0.0 + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + resumeAll: function () + { + if (this.paused) + { + this.paused = false; + + this.emit(Events.RESUME_ALL); + } + + return this; + }, + + /** + * Takes an array of Game Objects that have an Animation Component and then + * starts the given animation playing on them, each one offset by the + * `stagger` amount given to this method. + * + * @method Phaser.Animations.AnimationManager#staggerPlay + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items,$return] + * + * @param {string} key - The key of the animation to play on the Game Objects. + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} children - An array of Game Objects to play the animation on. They must have an Animation Component. + * @param {number} [stagger=0] - The amount of time, in milliseconds, to offset each play time by. + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + staggerPlay: function (key, children, stagger) + { + if (stagger === undefined) { stagger = 0; } + + if (!Array.isArray(children)) + { + children = [ children ]; + } + + var anim = this.get(key); + + if (!anim) + { + return; + } + + for (var i = 0; i < children.length; i++) + { + children[i].anims.delayedPlay(stagger * i, key); + } + + return this; + }, + + /** + * Get the animation data as javascript object by giving key, or get the data of all animations as array of objects, if key wasn't provided. + * + * @method Phaser.Animations.AnimationManager#toJSON + * @since 3.0.0 + * + * @param {string} key - [description] + * + * @return {Phaser.Types.Animations.JSONAnimations} [description] + */ + toJSON: function (key) + { + if (key !== undefined && key !== '') + { + return this.anims.get(key).toJSON(); + } + else + { + var output = { + anims: [], + globalTimeScale: this.globalTimeScale + }; + + this.anims.each(function (animationKey, animation) + { + output.anims.push(animation.toJSON()); + }); + + return output; + } + }, + + /** + * Destroy this Animation Manager and clean up animation definitions and references to other objects. + * This method should not be called directly. It will be called automatically as a response to a `destroy` event from the Phaser.Game instance. + * + * @method Phaser.Animations.AnimationManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.anims.clear(); + + this.textureManager = null; + + this.game = null; + } + +}); + +module.exports = AnimationManager; + + +/***/ }), +/* 309 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CustomMap = __webpack_require__(172); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(310); + +/** + * @classdesc + * The BaseCache is a base Cache class that can be used for storing references to any kind of data. + * + * Data can be added, retrieved and removed based on the given keys. + * + * Keys are string-based. + * + * @class BaseCache + * @memberof Phaser.Cache + * @constructor + * @since 3.0.0 + */ +var BaseCache = new Class({ + + initialize: + + function BaseCache () + { + /** + * The Map in which the cache objects are stored. + * + * You can query the Map directly or use the BaseCache methods. + * + * @name Phaser.Cache.BaseCache#entries + * @type {Phaser.Structs.Map.} + * @since 3.0.0 + */ + this.entries = new CustomMap(); + + /** + * An instance of EventEmitter used by the cache to emit related events. + * + * @name Phaser.Cache.BaseCache#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = new EventEmitter(); + }, + + /** + * Adds an item to this cache. The item is referenced by a unique string, which you are responsible + * for setting and keeping track of. The item can only be retrieved by using this string. + * + * @method Phaser.Cache.BaseCache#add + * @fires Phaser.Cache.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique key by which the data added to the cache will be referenced. + * @param {*} data - The data to be stored in the cache. + * + * @return {Phaser.Cache.BaseCache} This BaseCache object. + */ + add: function (key, data) + { + this.entries.set(key, data); + + this.events.emit(Events.ADD, this, key, data); + + return this; + }, + + /** + * Checks if this cache contains an item matching the given key. + * This performs the same action as `BaseCache.exists`. + * + * @method Phaser.Cache.BaseCache#has + * @since 3.0.0 + * + * @param {string} key - The unique key of the item to be checked in this cache. + * + * @return {boolean} Returns `true` if the cache contains an item matching the given key, otherwise `false`. + */ + has: function (key) + { + return this.entries.has(key); + }, + + /** + * Checks if this cache contains an item matching the given key. + * This performs the same action as `BaseCache.has` and is called directly by the Loader. + * + * @method Phaser.Cache.BaseCache#exists + * @since 3.7.0 + * + * @param {string} key - The unique key of the item to be checked in this cache. + * + * @return {boolean} Returns `true` if the cache contains an item matching the given key, otherwise `false`. + */ + exists: function (key) + { + return this.entries.has(key); + }, + + /** + * 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. + */ + get: function (key) + { + return this.entries.get(key); + }, + + /** + * Removes and 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 {Phaser.Cache.BaseCache} This BaseCache object. + */ + remove: function (key) + { + var entry = this.get(key); + + if (entry) + { + this.entries.delete(key); + + this.events.emit(Events.REMOVE, this, key, entry.data); + } + + return this; + }, + + /** + * Returns all keys in use in this cache. + * + * @method Phaser.Cache.BaseCache#getKeys + * @since 3.17.0 + * + * @return {string[]} Array containing all the keys. + */ + getKeys: function () + { + return this.entries.keys(); + }, + + /** + * Destroys this cache and all items within it. + * + * @method Phaser.Cache.BaseCache#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.entries.clear(); + this.events.removeAllListeners(); + + this.entries = null; + this.events = null; + } + +}); + +module.exports = BaseCache; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cache.Events + */ + +module.exports = { + + ADD: __webpack_require__(666), + REMOVE: __webpack_require__(667) + +}; + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCache = __webpack_require__(309); +var Class = __webpack_require__(0); +var GameEvents = __webpack_require__(21); + +/** + * @classdesc + * The Cache Manager is the global cache owned and maintained by the Game instance. + * + * Various systems, such as the file Loader, rely on this cache in order to store the files + * it has loaded. The manager itself doesn't store any files, but instead owns multiple BaseCache + * instances, one per type of file. You can also add your own custom caches. + * + * @class CacheManager + * @memberof Phaser.Cache + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser.Game instance that owns this CacheManager. + */ +var CacheManager = new Class({ + + initialize: + + function CacheManager (game) + { + /** + * A reference to the Phaser.Game instance that owns this CacheManager. + * + * @name Phaser.Cache.CacheManager#game + * @type {Phaser.Game} + * @protected + * @since 3.0.0 + */ + this.game = game; + + /** + * A Cache storing all binary files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#binary + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.binary = new BaseCache(); + + /** + * A Cache storing all bitmap font data files, typically added via the Loader. + * Only the font data is stored in this cache, the textures are part of the Texture Manager. + * + * @name Phaser.Cache.CacheManager#bitmapFont + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.bitmapFont = new BaseCache(); + + /** + * A Cache storing all JSON data files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#json + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.json = new BaseCache(); + + /** + * A Cache storing all physics data files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#physics + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.physics = new BaseCache(); + + /** + * A Cache storing all shader source files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#shader + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.shader = new BaseCache(); + + /** + * A Cache storing all non-streaming audio files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#audio + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.audio = new BaseCache(); + + /** + * A Cache storing all non-streaming video files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#video + * @type {Phaser.Cache.BaseCache} + * @since 3.20.0 + */ + this.video = new BaseCache(); + + /** + * A Cache storing all text files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#text + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.text = new BaseCache(); + + /** + * A Cache storing all html files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#html + * @type {Phaser.Cache.BaseCache} + * @since 3.12.0 + */ + this.html = new BaseCache(); + + /** + * A Cache storing all WaveFront OBJ files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#obj + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.obj = new BaseCache(); + + /** + * A Cache storing all tilemap data files, typically added via the Loader. + * Only the data is stored in this cache, the textures are part of the Texture Manager. + * + * @name Phaser.Cache.CacheManager#tilemap + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.tilemap = new BaseCache(); + + /** + * A Cache storing all xml data files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#xml + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.xml = new BaseCache(); + + /** + * An object that contains your own custom BaseCache entries. + * Add to this via the `addCustom` method. + * + * @name Phaser.Cache.CacheManager#custom + * @type {Object.} + * @since 3.0.0 + */ + this.custom = {}; + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Add your own custom Cache for storing your own files. + * The cache will be available under `Cache.custom.key`. + * The cache will only be created if the key is not already in use. + * + * @method Phaser.Cache.CacheManager#addCustom + * @since 3.0.0 + * + * @param {string} key - The unique key of your custom cache. + * + * @return {Phaser.Cache.BaseCache} A reference to the BaseCache that was created. If the key was already in use, a reference to the existing cache is returned instead. + */ + addCustom: function (key) + { + if (!this.custom.hasOwnProperty(key)) + { + this.custom[key] = new BaseCache(); + } + + return this.custom[key]; + }, + + /** + * Removes all entries from all BaseCaches and destroys all custom caches. + * + * @method Phaser.Cache.CacheManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + var keys = [ + 'binary', + 'bitmapFont', + 'json', + 'physics', + 'shader', + 'audio', + 'video', + 'text', + 'html', + 'obj', + 'tilemap', + 'xml' + ]; + + for (var i = 0; i < keys.length; i++) + { + this[keys[i]].destroy(); + this[keys[i]] = null; + } + + for (var key in this.custom) + { + this.custom[key].destroy(); + } + + this.custom = null; + + this.game = null; + } + +}); + +module.exports = CacheManager; + + +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCamera = __webpack_require__(103); +var CanvasPool = __webpack_require__(28); +var CenterOn = __webpack_require__(178); +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var Effects = __webpack_require__(320); +var Linear = __webpack_require__(123); +var Rectangle = __webpack_require__(11); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Camera. + * + * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, + * and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. + * + * A Camera also has built-in special effects including Fade, Flash and Camera Shake. + * + * @class Camera + * @memberof Phaser.Cameras.Scene2D + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Cameras.Scene2D.BaseCamera + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Tint + * + * @param {number} x - The x position of the Camera, relative to the top-left of the game canvas. + * @param {number} y - The y position of the Camera, relative to the top-left of the game canvas. + * @param {number} width - The width of the Camera, in pixels. + * @param {number} height - The height of the Camera, in pixels. + */ +var Camera = new Class({ + + Extends: BaseCamera, + + Mixins: [ + Components.Flip, + Components.Tint + ], + + initialize: + + function Camera (x, y, width, height) + { + BaseCamera.call(this, x, y, width, height); + + /** + * Does this Camera allow the Game Objects it renders to receive input events? + * + * @name Phaser.Cameras.Scene2D.Camera#inputEnabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.inputEnabled = true; + + /** + * The Camera Fade effect handler. + * To fade this camera see the `Camera.fade` methods. + * + * @name Phaser.Cameras.Scene2D.Camera#fadeEffect + * @type {Phaser.Cameras.Scene2D.Effects.Fade} + * @since 3.5.0 + */ + this.fadeEffect = new Effects.Fade(this); + + /** + * The Camera Flash effect handler. + * To flash this camera see the `Camera.flash` method. + * + * @name Phaser.Cameras.Scene2D.Camera#flashEffect + * @type {Phaser.Cameras.Scene2D.Effects.Flash} + * @since 3.5.0 + */ + this.flashEffect = new Effects.Flash(this); + + /** + * The Camera Shake effect handler. + * To shake this camera see the `Camera.shake` method. + * + * @name Phaser.Cameras.Scene2D.Camera#shakeEffect + * @type {Phaser.Cameras.Scene2D.Effects.Shake} + * @since 3.5.0 + */ + this.shakeEffect = new Effects.Shake(this); + + /** + * The Camera Pan effect handler. + * To pan this camera see the `Camera.pan` method. + * + * @name Phaser.Cameras.Scene2D.Camera#panEffect + * @type {Phaser.Cameras.Scene2D.Effects.Pan} + * @since 3.11.0 + */ + this.panEffect = new Effects.Pan(this); + + /** + * The Camera Zoom effect handler. + * To zoom this camera see the `Camera.zoom` method. + * + * @name Phaser.Cameras.Scene2D.Camera#zoomEffect + * @type {Phaser.Cameras.Scene2D.Effects.Zoom} + * @since 3.11.0 + */ + this.zoomEffect = new Effects.Zoom(this); + + /** + * The linear interpolation value to use when following a target. + * + * Can also be set via `setLerp` or as part of the `startFollow` call. + * + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * + * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. + * + * @name Phaser.Cameras.Scene2D.Camera#lerp + * @type {Phaser.Math.Vector2} + * @since 3.9.0 + */ + this.lerp = new Vector2(1, 1); + + /** + * The values stored in this property are subtracted from the Camera targets position, allowing you to + * offset the camera from the actual target x/y coordinates by this amount. + * Can also be set via `setFollowOffset` or as part of the `startFollow` call. + * + * @name Phaser.Cameras.Scene2D.Camera#followOffset + * @type {Phaser.Math.Vector2} + * @since 3.9.0 + */ + this.followOffset = new Vector2(); + + /** + * The Camera dead zone. + * + * The deadzone is only used when the camera is following a target. + * + * It defines a rectangular region within which if the target is present, the camera will not scroll. + * If the target moves outside of this area, the camera will begin scrolling in order to follow it. + * + * The `lerp` values that you can set for a follower target also apply when using a deadzone. + * + * You can directly set this property to be an instance of a Rectangle. Or, you can use the + * `setDeadzone` method for a chainable approach. + * + * The rectangle you provide can have its dimensions adjusted dynamically, however, please + * note that its position is updated every frame, as it is constantly re-centered on the cameras mid point. + * + * Calling `setDeadzone` with no arguments will reset an active deadzone, as will setting this property + * to `null`. + * + * @name Phaser.Cameras.Scene2D.Camera#deadzone + * @type {?Phaser.Geom.Rectangle} + * @since 3.11.0 + */ + this.deadzone = null; + + /** + * Internal follow target reference. + * + * @name Phaser.Cameras.Scene2D.Camera#_follow + * @type {?any} + * @private + * @default null + * @since 3.0.0 + */ + this._follow = null; + + /** + * Is this Camera rendering directly to the canvas or to a texture? + * + * Enable rendering to texture with the method `setRenderToTexture` (just enabling this boolean won't be enough) + * + * Once enabled you can toggle it by switching this property. + * + * To properly remove a render texture you should call the `clearRenderToTexture()` method. + * + * @name Phaser.Cameras.Scene2D.Camera#renderToTexture + * @type {boolean} + * @default false + * @since 3.13.0 + */ + this.renderToTexture = false; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the HTML Canvas Element that the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only populated if Phaser is running with the Canvas Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#canvas + * @type {HTMLCanvasElement} + * @since 3.13.0 + */ + this.canvas = null; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the Rendering Context belonging to the Canvas element the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only populated if Phaser is running with the Canvas Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#context + * @type {CanvasRenderingContext2D} + * @since 3.13.0 + */ + this.context = null; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the GL Texture belonging the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#glTexture + * @type {?WebGLTexture} + * @since 3.13.0 + */ + this.glTexture = null; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the GL Frame Buffer belonging the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#framebuffer + * @type {?WebGLFramebuffer} + * @since 3.13.0 + */ + this.framebuffer = null; + + /** + * If this Camera has been set to render to a texture and to use a custom pipeline, + * then this holds a reference to the pipeline the Camera is drawing with. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#pipeline + * @type {any} + * @since 3.13.0 + */ + this.pipeline = null; + }, + + /** + * Sets the Camera to render to a texture instead of to the main canvas. + * + * The Camera will redirect all Game Objects it's asked to render to this texture. + * + * During the render sequence, the texture itself will then be rendered to the main canvas. + * + * Doing this gives you the ability to modify the texture before this happens, + * allowing for special effects such as Camera specific shaders, or post-processing + * on the texture. + * + * If running under Canvas the Camera will render to its `canvas` property. + * + * If running under WebGL the Camera will create a frame buffer, which is stored in its `framebuffer` and `glTexture` properties. + * + * If you set a camera to render to a texture then it will emit 2 events during the render loop: + * + * First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. + * + * Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the + * Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before + * it appears in-game. + * + * You should not enable this unless you plan on actually using the texture it creates + * somehow, otherwise you're just doubling the work required to render your game. + * + * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. + * + * If you no longer require the Camera to render to a texture, call the `clearRenderToTexture` method, + * which will delete the respective textures and free-up resources. + * + * @method Phaser.Cameras.Scene2D.Camera#setRenderToTexture + * @since 3.13.0 + * + * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + setRenderToTexture: function (pipeline) + { + var renderer = this.scene.sys.game.renderer; + + if (renderer.gl) + { + this.glTexture = renderer.createTextureFromSource(null, this.width, this.height, 0); + this.framebuffer = renderer.createFramebuffer(this.width, this.height, this.glTexture, false); + } + else + { + this.canvas = CanvasPool.create2D(this, this.width, this.height); + this.context = this.canvas.getContext('2d'); + } + + this.renderToTexture = true; + + if (pipeline) + { + this.setPipeline(pipeline); + } + + return this; + }, + + /** + * Sets the WebGL pipeline this Camera is using when rendering to a texture. + * + * You can pass either the string-based name of the pipeline, or a reference to the pipeline itself. + * + * Call this method with no arguments to clear any previously set pipeline. + * + * @method Phaser.Cameras.Scene2D.Camera#setPipeline + * @since 3.13.0 + * + * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - The WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. Or if left empty it will clear the pipeline. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + setPipeline: function (pipeline) + { + if (typeof pipeline === 'string') + { + var renderer = this.scene.sys.game.renderer; + + if (renderer.gl && renderer.hasPipeline(pipeline)) + { + this.pipeline = renderer.getPipeline(pipeline); + } + } + else + { + this.pipeline = pipeline; + } + + return this; + }, + + /** + * If this Camera was set to render to a texture, this will clear the resources it was using and + * redirect it to render back to the primary Canvas again. + * + * If you only wish to temporarily disable rendering to a texture then you can toggle the + * property `renderToTexture` instead. + * + * @method Phaser.Cameras.Scene2D.Camera#clearRenderToTexture + * @since 3.13.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + clearRenderToTexture: function () + { + if (!this.scene) + { + return; + } + + var renderer = this.scene.sys.game.renderer; + + if (!renderer) + { + return; + } + + if (renderer.gl) + { + if (this.framebuffer) + { + renderer.deleteFramebuffer(this.framebuffer); + } + + if (this.glTexture) + { + renderer.deleteTexture(this.glTexture); + } + + this.framebuffer = null; + this.glTexture = null; + this.pipeline = null; + } + else + { + CanvasPool.remove(this); + + this.canvas = null; + this.context = null; + } + + this.renderToTexture = false; + + return this; + }, + + /** + * Sets the Camera dead zone. + * + * The deadzone is only used when the camera is following a target. + * + * It defines a rectangular region within which if the target is present, the camera will not scroll. + * If the target moves outside of this area, the camera will begin scrolling in order to follow it. + * + * The deadzone rectangle is re-positioned every frame so that it is centered on the mid-point + * of the camera. This allows you to use the object for additional game related checks, such as + * testing if an object is within it or not via a Rectangle.contains call. + * + * The `lerp` values that you can set for a follower target also apply when using a deadzone. + * + * Calling this method with no arguments will reset an active deadzone. + * + * @method Phaser.Cameras.Scene2D.Camera#setDeadzone + * @since 3.11.0 + * + * @param {number} [width] - The width of the deadzone rectangle in pixels. If not specified the deadzone is removed. + * @param {number} [height] - The height of the deadzone rectangle in pixels. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + setDeadzone: function (width, height) + { + if (width === undefined) + { + this.deadzone = null; + } + else + { + if (this.deadzone) + { + this.deadzone.width = width; + this.deadzone.height = height; + } + else + { + this.deadzone = new Rectangle(0, 0, width, height); + } + + if (this._follow) + { + var originX = this.width / 2; + var originY = this.height / 2; + + var fx = this._follow.x - this.followOffset.x; + var fy = this._follow.y - this.followOffset.y; + + this.midPoint.set(fx, fy); + + this.scrollX = fx - originX; + this.scrollY = fy - originY; + } + + CenterOn(this.deadzone, this.midPoint.x, this.midPoint.y); + } + + return this; + }, + + /** + * Fades the Camera in from the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#fadeIn + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @since 3.3.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fadeIn: function (duration, red, green, blue, callback, context) + { + return this.fadeEffect.start(false, duration, red, green, blue, true, callback, context); + }, + + /** + * Fades the Camera out to the given color over the duration specified. + * This is an alias for Camera.fade that forces the fade to start, regardless of existing fades. + * + * @method Phaser.Cameras.Scene2D.Camera#fadeOut + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.3.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fadeOut: function (duration, red, green, blue, callback, context) + { + return this.fadeEffect.start(true, duration, red, green, blue, true, callback, context); + }, + + /** + * Fades the Camera from the given color to transparent over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#fadeFrom + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @since 3.5.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fadeFrom: function (duration, red, green, blue, force, callback, context) + { + return this.fadeEffect.start(false, duration, red, green, blue, force, callback, context); + }, + + /** + * Fades the Camera from transparent to the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#fade + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.0.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fade: function (duration, red, green, blue, force, callback, context) + { + return this.fadeEffect.start(true, duration, red, green, blue, force, callback, context); + }, + + /** + * Flashes the Camera by setting it to the given color immediately and then fading it away again quickly over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#flash + * @fires Phaser.Cameras.Scene2D.Events#FLASH_START + * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.0.0 + * + * @param {integer} [duration=250] - The duration of the effect in milliseconds. + * @param {integer} [red=255] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=255] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=255] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + flash: function (duration, red, green, blue, force, callback, context) + { + return this.flashEffect.start(duration, red, green, blue, force, callback, context); + }, + + /** + * Shakes the Camera by the given intensity over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#shake + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_START + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.0.0 + * + * @param {integer} [duration=100] - The duration of the effect in milliseconds. + * @param {(number|Phaser.Math.Vector2)} [intensity=0.05] - The intensity of the shake. + * @param {boolean} [force=false] - Force the shake effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + shake: function (duration, intensity, force, callback, context) + { + return this.shakeEffect.start(duration, intensity, force, callback, context); + }, + + /** + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Camera#pan + * @fires Phaser.Cameras.Scene2D.Events#PAN_START + * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.11.0 + * + * @param {number} x - The destination x coordinate to scroll the center of the Camera viewport to. + * @param {number} y - The destination y coordinate to scroll the center of the Camera viewport to. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + pan: function (x, y, duration, ease, force, callback, context) + { + return this.panEffect.start(x, y, duration, ease, force, callback, context); + }, + + /** + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Camera#zoomTo + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_START + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.11.0 + * + * @param {number} zoom - The target Camera zoom value. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + zoomTo: function (zoom, duration, ease, force, callback, context) + { + return this.zoomEffect.start(zoom, duration, ease, force, callback, context); + }, + + /** + * Internal preRender step. + * + * @method Phaser.Cameras.Scene2D.Camera#preRender + * @protected + * @since 3.0.0 + * + * @param {number} resolution - The game resolution, as set in the Scale Manager. + */ + preRender: function (resolution) + { + var width = this.width; + var height = this.height; + + var halfWidth = width * 0.5; + var halfHeight = height * 0.5; + + var zoom = this.zoom * resolution; + var matrix = this.matrix; + + var originX = width * this.originX; + var originY = height * this.originY; + + var follow = this._follow; + var deadzone = this.deadzone; + + var sx = this.scrollX; + var sy = this.scrollY; + + if (deadzone) + { + CenterOn(deadzone, this.midPoint.x, this.midPoint.y); + } + + if (follow && !this.panEffect.isRunning) + { + var fx = (follow.x - this.followOffset.x); + var fy = (follow.y - this.followOffset.y); + + if (deadzone) + { + if (fx < deadzone.x) + { + sx = Linear(sx, sx - (deadzone.x - fx), this.lerp.x); + } + else if (fx > deadzone.right) + { + sx = Linear(sx, sx + (fx - deadzone.right), this.lerp.x); + } + + if (fy < deadzone.y) + { + sy = Linear(sy, sy - (deadzone.y - fy), this.lerp.y); + } + else if (fy > deadzone.bottom) + { + sy = Linear(sy, sy + (fy - deadzone.bottom), this.lerp.y); + } + } + else + { + sx = Linear(sx, fx - originX, this.lerp.x); + sy = Linear(sy, fy - originY, this.lerp.y); + } + } + + if (this.useBounds) + { + sx = this.clampX(sx); + sy = this.clampY(sy); + } + + if (this.roundPixels) + { + originX = Math.round(originX); + originY = Math.round(originY); + } + + // Values are in pixels and not impacted by zooming the Camera + this.scrollX = sx; + this.scrollY = sy; + + var midX = sx + halfWidth; + var midY = sy + halfHeight; + + // 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 + this.midPoint.set(midX, midY); + + var displayWidth = width / zoom; + var displayHeight = height / zoom; + + this.worldView.setTo( + midX - (displayWidth / 2), + midY - (displayHeight / 2), + displayWidth, + displayHeight + ); + + matrix.applyITRS(this.x + originX, this.y + originY, this.rotation, zoom, zoom); + matrix.translate(-originX, -originY); + + this.shakeEffect.preRender(); + }, + + /** + * Sets the linear interpolation value to use when following a target. + * + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * + * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. + * + * @method Phaser.Cameras.Scene2D.Camera#setLerp + * @since 3.9.0 + * + * @param {number} [x=1] - The amount added to the horizontal linear interpolation of the follow target. + * @param {number} [y=1] - The amount added to the vertical linear interpolation of the follow target. + * + * @return {this} This Camera instance. + */ + setLerp: function (x, y) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + this.lerp.set(x, y); + + return this; + }, + + /** + * Sets the horizontal and vertical offset of the camera from its follow target. + * The values are subtracted from the targets position during the Cameras update step. + * + * @method Phaser.Cameras.Scene2D.Camera#setFollowOffset + * @since 3.9.0 + * + * @param {number} [x=0] - The horizontal offset from the camera follow target.x position. + * @param {number} [y=0] - The vertical offset from the camera follow target.y position. + * + * @return {this} This Camera instance. + */ + setFollowOffset: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + this.followOffset.set(x, y); + + return this; + }, + + /** + * Sets the Camera to follow a Game Object. + * + * When enabled the Camera will automatically adjust its scroll position to keep the target Game Object + * in its center. + * + * You can set the linear interpolation value used in the follow code. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following an object it's probably to do with sub-pixel + * rendering of the targets position. This can be rounded by setting the `roundPixels` argument to `true` to + * force full pixel rounding rendering. Note that this can still be broken if you have specified a non-integer zoom + * value on the camera. So be sure to keep the camera zoom to integers. + * + * @method Phaser.Cameras.Scene2D.Camera#startFollow + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|object)} target - The target for the Camera to follow. + * @param {boolean} [roundPixels=false] - Round the camera position to whole integers to avoid sub-pixel rendering? + * @param {number} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {number} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + * @param {number} [offsetX=0] - The horizontal offset from the camera follow target.x position. + * @param {number} [offsetY=0] - The vertical offset from the camera follow target.y position. + * + * @return {this} This Camera instance. + */ + startFollow: function (target, roundPixels, lerpX, lerpY, offsetX, offsetY) + { + if (roundPixels === undefined) { roundPixels = false; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = lerpX; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = offsetX; } + + this._follow = target; + + this.roundPixels = roundPixels; + + lerpX = Clamp(lerpX, 0, 1); + lerpY = Clamp(lerpY, 0, 1); + + this.lerp.set(lerpX, lerpY); + + this.followOffset.set(offsetX, offsetY); + + var originX = this.width / 2; + var originY = this.height / 2; + + var fx = target.x - offsetX; + var fy = target.y - offsetY; + + this.midPoint.set(fx, fy); + + this.scrollX = fx - originX; + this.scrollY = fy - originY; + + if (this.useBounds) + { + this.scrollX = this.clampX(this.scrollX); + this.scrollY = this.clampY(this.scrollY); + } + + return this; + }, + + /** + * Stops a Camera from following a Game Object, if previously set via `Camera.startFollow`. + * + * @method Phaser.Cameras.Scene2D.Camera#stopFollow + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + stopFollow: function () + { + this._follow = null; + + return this; + }, + + /** + * Resets any active FX, such as a fade, flash or shake. Useful to call after a fade in order to + * remove the fade. + * + * @method Phaser.Cameras.Scene2D.Camera#resetFX + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + resetFX: function () + { + this.panEffect.reset(); + this.shakeEffect.reset(); + this.flashEffect.reset(); + this.fadeEffect.reset(); + + return this; + }, + + /** + * Internal method called automatically by the Camera Manager. + * + * @method Phaser.Cameras.Scene2D.Camera#update + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (this.visible) + { + this.panEffect.update(time, delta); + this.zoomEffect.update(time, delta); + this.shakeEffect.update(time, delta); + this.flashEffect.update(time, delta); + this.fadeEffect.update(time, delta); + } + }, + + /** + * Destroys this Camera instance. You rarely need to call this directly. + * + * Called by the Camera Manager. If you wish to destroy a Camera please use `CameraManager.remove` as + * cameras are stored in a pool, ready for recycling later, and calling this directly will prevent that. + * + * @method Phaser.Cameras.Scene2D.Camera#destroy + * @fires Phaser.Cameras.Scene2D.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + this.clearRenderToTexture(); + + this.resetFX(); + + BaseCamera.prototype.destroy.call(this); + + this._follow = null; + + this.deadzone = null; + } + +}); + +module.exports = Camera; + + +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = __webpack_require__(36); + +/** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @function Phaser.Display.Color.HexStringToColor + * @since 3.0.0 + * + * @param {string} hex - The hex color value to convert, such as `#0033ff` or the short-hand format: `#03f`. + * + * @return {Phaser.Display.Color} A Color object populated by the values of the given string. + */ +var HexStringToColor = function (hex) +{ + var color = new Color(); + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function (m, r, g, b) + { + return r + r + g + g + b + b; + }); + + var result = (/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i).exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + color.setTo(r, g, b); + } + + return color; +}; + +module.exports = HexStringToColor; + + +/***/ }), +/* 314 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @function Phaser.Display.Color.GetColor32 + * @since 3.0.0 + * + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * @param {integer} alpha - The alpha color value. A number between 0 and 255. + * + * @return {number} The combined color value. + */ +var GetColor32 = function (red, green, blue, alpha) +{ + return alpha << 24 | red << 16 | green << 8 | blue; +}; + +module.exports = GetColor32; + + +/***/ }), +/* 315 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} r - The red color value. A number between 0 and 255. + * @param {integer} g - The green color value. A number between 0 and 255. + * @param {integer} 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. + */ +var RGBToHSV = function (r, g, b, out) +{ + if (out === undefined) { out = { h: 0, s: 0, v: 0 }; } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + var h = 0; + var s = (max === 0) ? 0 : d / max; + var v = max; + + if (max !== min) + { + if (max === r) + { + h = (g - b) / d + ((g < b) ? 6 : 0); + } + else if (max === g) + { + h = (b - r) / d + 2; + } + else if (max === b) + { + h = (r - g) / d + 4; + } + + h /= 6; + } + + if (out.hasOwnProperty('_h')) + { + out._h = h; + out._s = s; + out._v = v; + } + else + { + out.h = h; + out.s = s; + out.v = v; + } + + return out; +}; + +module.exports = RGBToHSV; + + +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = __webpack_require__(36); +var IntegerToRGB = __webpack_require__(317); + +/** + * Converts the given color value into an instance of a Color object. + * + * @function Phaser.Display.Color.IntegerToColor + * @since 3.0.0 + * + * @param {integer} input - The color value to convert into a Color object. + * + * @return {Phaser.Display.Color} A Color object. + */ +var IntegerToColor = function (input) +{ + var rgb = IntegerToRGB(input); + + return new Color(rgb.r, rgb.g, rgb.b, rgb.a); +}; + +module.exports = IntegerToColor; + + +/***/ }), +/* 317 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exists in the given color (0xAARRGGBB) + * + * @function Phaser.Display.Color.IntegerToRGB + * @since 3.0.0 + * + * @param {integer} input - The color value to convert into a Color object. + * + * @return {Phaser.Types.Display.ColorObject} An object with the red, green and blue values set in the r, g and b properties. + */ +var IntegerToRGB = function (color) +{ + if (color > 16777215) + { + // The color value has an alpha component + return { + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } +}; + +module.exports = IntegerToRGB; + + +/***/ }), +/* 318 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = __webpack_require__(36); + +/** + * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. + * + * @function Phaser.Display.Color.ObjectToColor + * @since 3.0.0 + * + * @param {Phaser.Types.Display.InputColorObject} input - An object containing `r`, `g`, `b` and `a` properties in the range 0 to 255. + * + * @return {Phaser.Display.Color} A Color object. + */ +var ObjectToColor = function (input) +{ + return new Color(input.r, input.g, input.b, input.a); +}; + +module.exports = ObjectToColor; + + +/***/ }), +/* 319 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = __webpack_require__(36); + +/** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @function Phaser.Display.Color.RGBStringToColor + * @since 3.0.0 + * + * @param {string} rgb - The CSS format color string, using the `rgb` or `rgba` format. + * + * @return {Phaser.Display.Color} A Color object. + */ +var RGBStringToColor = function (rgb) +{ + var color = new Color(); + + var result = (/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/).exec(rgb.toLowerCase()); + + if (result) + { + var r = parseInt(result[1], 10); + var g = parseInt(result[2], 10); + var b = parseInt(result[3], 10); + var a = (result[4] !== undefined) ? parseFloat(result[4]) : 1; + + color.setTo(r, g, b, a * 255); + } + + return color; +}; + +module.exports = RGBStringToColor; + + +/***/ }), +/* 320 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Scene2D.Effects + */ + +module.exports = { + + Fade: __webpack_require__(688), + Flash: __webpack_require__(689), + Pan: __webpack_require__(690), + Shake: __webpack_require__(723), + Zoom: __webpack_require__(724) + +}; + + +/***/ }), +/* 321 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Back + */ + +module.exports = { + + In: __webpack_require__(691), + Out: __webpack_require__(692), + InOut: __webpack_require__(693) + +}; + + +/***/ }), +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Bounce + */ + +module.exports = { + + In: __webpack_require__(694), + Out: __webpack_require__(695), + InOut: __webpack_require__(696) + +}; + + +/***/ }), +/* 323 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Circular + */ + +module.exports = { + + In: __webpack_require__(697), + Out: __webpack_require__(698), + InOut: __webpack_require__(699) + +}; + + +/***/ }), +/* 324 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Cubic + */ + +module.exports = { + + In: __webpack_require__(700), + Out: __webpack_require__(701), + InOut: __webpack_require__(702) + +}; + + +/***/ }), +/* 325 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Elastic + */ + +module.exports = { + + In: __webpack_require__(703), + Out: __webpack_require__(704), + InOut: __webpack_require__(705) + +}; + + +/***/ }), +/* 326 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Expo + */ + +module.exports = { + + In: __webpack_require__(706), + Out: __webpack_require__(707), + InOut: __webpack_require__(708) + +}; + + +/***/ }), +/* 327 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Linear + */ + +module.exports = __webpack_require__(709); + + +/***/ }), +/* 328 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Quadratic + */ + +module.exports = { + + In: __webpack_require__(710), + Out: __webpack_require__(711), + InOut: __webpack_require__(712) + +}; + + +/***/ }), +/* 329 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Quartic + */ + +module.exports = { + + In: __webpack_require__(713), + Out: __webpack_require__(714), + InOut: __webpack_require__(715) + +}; + + +/***/ }), +/* 330 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Quintic + */ + +module.exports = { + + In: __webpack_require__(716), + Out: __webpack_require__(717), + InOut: __webpack_require__(718) + +}; + + +/***/ }), +/* 331 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Sine + */ + +module.exports = { + + In: __webpack_require__(719), + Out: __webpack_require__(720), + InOut: __webpack_require__(721) + +}; + + +/***/ }), +/* 332 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Stepped + */ + +module.exports = __webpack_require__(722); + + +/***/ }), +/* 333 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(32); +var Device = __webpack_require__(334); +var GetFastValue = __webpack_require__(1); +var GetValue = __webpack_require__(5); +var IsPlainObject = __webpack_require__(7); +var PhaserMath = __webpack_require__(181); +var NOOP = __webpack_require__(2); +var DefaultPlugins = __webpack_require__(186); +var ValueToColor = __webpack_require__(174); + +/** + * @classdesc + * The active game configuration settings, parsed from a {@link Phaser.Types.Core.GameConfig} object. + * + * @class Config + * @memberof Phaser.Core + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Core.GameConfig} [GameConfig] - The configuration object for your Phaser Game instance. + * + * @see Phaser.Game#config + */ +var Config = new Class({ + + initialize: + + function Config (config) + { + if (config === undefined) { config = {}; } + + var defaultBannerColor = [ + '#ff0000', + '#ffff00', + '#00ff00', + '#00ffff', + '#000000' + ]; + + var defaultBannerTextColor = '#ffffff'; + + /** + * @const {(integer|string)} Phaser.Core.Config#width - The width of the underlying canvas, in pixels. + */ + this.width = GetValue(config, 'width', 1024); + + /** + * @const {(integer|string)} Phaser.Core.Config#height - The height of the underlying canvas, in pixels. + */ + this.height = GetValue(config, 'height', 768); + + /** + * @const {(Phaser.Scale.ZoomType|integer)} Phaser.Core.Config#zoom - The zoom factor, as used by the Scale Manager. + */ + this.zoom = GetValue(config, 'zoom', 1); + + /** + * @const {number} Phaser.Core.Config#resolution - The canvas device pixel resolution. Currently un-used. + */ + this.resolution = GetValue(config, 'resolution', 1); + + /** + * @const {?*} Phaser.Core.Config#parent - A parent DOM element into which the canvas created by the renderer will be injected. + */ + this.parent = GetValue(config, 'parent', undefined); + + /** + * @const {Phaser.Scale.ScaleModeType} Phaser.Core.Config#scaleMode - The scale mode as used by the Scale Manager. The default is zero, which is no scaling. + */ + this.scaleMode = GetValue(config, 'scaleMode', 0); + + /** + * @const {boolean} Phaser.Core.Config#expandParent - Is the Scale Manager allowed to adjust the CSS height property of the parent to be 100%? + */ + this.expandParent = GetValue(config, 'expandParent', true); + + /** + * @const {integer} Phaser.Core.Config#autoRound - Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. + */ + this.autoRound = GetValue(config, 'autoRound', false); + + /** + * @const {Phaser.Scale.CenterType} Phaser.Core.Config#autoCenter - Automatically center the canvas within the parent? + */ + this.autoCenter = GetValue(config, 'autoCenter', 0); + + /** + * @const {integer} Phaser.Core.Config#resizeInterval - How many ms should elapse before checking if the browser size has changed? + */ + this.resizeInterval = GetValue(config, 'resizeInterval', 500); + + /** + * @const {?(HTMLElement|string)} Phaser.Core.Config#fullscreenTarget - The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. + */ + this.fullscreenTarget = GetValue(config, 'fullscreenTarget', null); + + /** + * @const {integer} Phaser.Core.Config#minWidth - The minimum width, in pixels, the canvas will scale down to. A value of zero means no minimum. + */ + this.minWidth = GetValue(config, 'minWidth', 0); + + /** + * @const {integer} Phaser.Core.Config#maxWidth - The maximum width, in pixels, the canvas will scale up to. A value of zero means no maximum. + */ + this.maxWidth = GetValue(config, 'maxWidth', 0); + + /** + * @const {integer} Phaser.Core.Config#minHeight - The minimum height, in pixels, the canvas will scale down to. A value of zero means no minimum. + */ + this.minHeight = GetValue(config, 'minHeight', 0); + + /** + * @const {integer} Phaser.Core.Config#maxHeight - The maximum height, in pixels, the canvas will scale up to. A value of zero means no maximum. + */ + this.maxHeight = GetValue(config, 'maxHeight', 0); + + // Scale Manager - Anything set in here over-rides anything set above + + var scaleConfig = GetValue(config, 'scale', null); + + if (scaleConfig) + { + this.width = GetValue(scaleConfig, 'width', this.width); + this.height = GetValue(scaleConfig, 'height', this.height); + this.zoom = GetValue(scaleConfig, 'zoom', this.zoom); + this.resolution = GetValue(scaleConfig, 'resolution', this.resolution); + this.parent = GetValue(scaleConfig, 'parent', this.parent); + this.scaleMode = GetValue(scaleConfig, 'mode', this.scaleMode); + this.expandParent = GetValue(scaleConfig, 'expandParent', this.expandParent); + this.autoRound = GetValue(scaleConfig, 'autoRound', this.autoRound); + this.autoCenter = GetValue(scaleConfig, 'autoCenter', this.autoCenter); + this.resizeInterval = GetValue(scaleConfig, 'resizeInterval', this.resizeInterval); + this.fullscreenTarget = GetValue(scaleConfig, 'fullscreenTarget', this.fullscreenTarget); + this.minWidth = GetValue(scaleConfig, 'min.width', this.minWidth); + this.maxWidth = GetValue(scaleConfig, 'max.width', this.maxWidth); + this.minHeight = GetValue(scaleConfig, 'min.height', this.minHeight); + this.maxHeight = GetValue(scaleConfig, 'max.height', this.maxHeight); + } + + /** + * @const {number} Phaser.Core.Config#renderType - Force Phaser to use a specific renderer. Can be `CONST.CANVAS`, `CONST.WEBGL`, `CONST.HEADLESS` or `CONST.AUTO` (default) + */ + this.renderType = GetValue(config, 'type', CONST.AUTO); + + /** + * @const {?HTMLCanvasElement} Phaser.Core.Config#canvas - Force Phaser to use your own Canvas element instead of creating one. + */ + this.canvas = GetValue(config, 'canvas', null); + + /** + * @const {?(CanvasRenderingContext2D|WebGLRenderingContext)} Phaser.Core.Config#context - Force Phaser to use your own Canvas context instead of creating one. + */ + this.context = GetValue(config, 'context', null); + + /** + * @const {?string} Phaser.Core.Config#canvasStyle - Optional CSS attributes to be set on the canvas object created by the renderer. + */ + this.canvasStyle = GetValue(config, 'canvasStyle', null); + + /** + * @const {boolean} Phaser.Core.Config#customEnvironment - Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. + */ + this.customEnvironment = GetValue(config, 'customEnvironment', false); + + /** + * @const {?object} Phaser.Core.Config#sceneConfig - The default Scene configuration object. + */ + this.sceneConfig = GetValue(config, 'scene', null); + + /** + * @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. + */ + this.seed = GetValue(config, 'seed', [ (Date.now() * Math.random()).toString() ]); + + PhaserMath.RND = new PhaserMath.RandomDataGenerator(this.seed); + + /** + * @const {string} Phaser.Core.Config#gameTitle - The title of the game. + */ + this.gameTitle = GetValue(config, 'title', ''); + + /** + * @const {string} Phaser.Core.Config#gameURL - The URL of the game. + */ + this.gameURL = GetValue(config, 'url', 'https://phaser.io'); + + /** + * @const {string} Phaser.Core.Config#gameVersion - The version of the game. + */ + this.gameVersion = GetValue(config, 'version', ''); + + /** + * @const {boolean} Phaser.Core.Config#autoFocus - If `true` the window will automatically be given focus immediately and on any future mousedown event. + */ + this.autoFocus = GetValue(config, 'autoFocus', true); + + // DOM Element Container + + /** + * @const {?boolean} Phaser.Core.Config#domCreateContainer - Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. + */ + this.domCreateContainer = GetValue(config, 'dom.createContainer', false); + + /** + * @const {?boolean} Phaser.Core.Config#domBehindCanvas - Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? + */ + this.domBehindCanvas = GetValue(config, 'dom.behindCanvas', false); + + // Input + + /** + * @const {boolean} Phaser.Core.Config#inputKeyboard - Enable the Keyboard Plugin. This can be disabled in games that don't need keyboard input. + */ + this.inputKeyboard = GetValue(config, 'input.keyboard', true); + + /** + * @const {*} Phaser.Core.Config#inputKeyboardEventTarget - The DOM Target to listen for keyboard events on. Defaults to `window` if not specified. + */ + this.inputKeyboardEventTarget = GetValue(config, 'input.keyboard.target', window); + + /** + * @const {?integer[]} Phaser.Core.Config#inputKeyboardCapture - `preventDefault` will be called on every non-modified key which has a key code in this array. By default, it is empty. + */ + this.inputKeyboardCapture = GetValue(config, 'input.keyboard.capture', []); + + /** + * @const {(boolean|object)} Phaser.Core.Config#inputMouse - Enable the Mouse Plugin. This can be disabled in games that don't need mouse input. + */ + this.inputMouse = GetValue(config, 'input.mouse', true); + + /** + * @const {?*} Phaser.Core.Config#inputMouseEventTarget - The DOM Target to listen for mouse events on. Defaults to the game canvas if not specified. + */ + this.inputMouseEventTarget = GetValue(config, 'input.mouse.target', null); + + /** + * @const {boolean} Phaser.Core.Config#inputMouseCapture - Should mouse events be captured? I.e. have prevent default called on them. + */ + this.inputMouseCapture = GetValue(config, 'input.mouse.capture', true); + + /** + * @const {boolean} Phaser.Core.Config#inputTouch - Enable the Touch Plugin. This can be disabled in games that don't need touch input. + */ + this.inputTouch = GetValue(config, 'input.touch', Device.input.touch); + + /** + * @const {?*} Phaser.Core.Config#inputTouchEventTarget - The DOM Target to listen for touch events on. Defaults to the game canvas if not specified. + */ + this.inputTouchEventTarget = GetValue(config, 'input.touch.target', null); + + /** + * @const {boolean} Phaser.Core.Config#inputTouchCapture - Should touch events be captured? I.e. have prevent default called on them. + */ + this.inputTouchCapture = GetValue(config, 'input.touch.capture', true); + + /** + * @const {integer} Phaser.Core.Config#inputActivePointers - The number of Pointer objects created by default. In a mouse-only, or non-multi touch game, you can leave this as 1. + */ + this.inputActivePointers = GetValue(config, 'input.activePointers', 1); + + /** + * @const {integer} Phaser.Core.Config#inputSmoothFactor - The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. + */ + this.inputSmoothFactor = GetValue(config, 'input.smoothFactor', 0); + + /** + * @const {boolean} Phaser.Core.Config#inputWindowEvents - Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. + */ + this.inputWindowEvents = GetValue(config, 'input.windowEvents', true); + + /** + * @const {boolean} Phaser.Core.Config#inputGamepad - Enable the Gamepad Plugin. This can be disabled in games that don't need gamepad input. + */ + this.inputGamepad = GetValue(config, 'input.gamepad', false); + + /** + * @const {*} Phaser.Core.Config#inputGamepadEventTarget - The DOM Target to listen for gamepad events on. Defaults to `window` if not specified. + */ + this.inputGamepadEventTarget = GetValue(config, 'input.gamepad.target', window); + + /** + * @const {boolean} Phaser.Core.Config#disableContextMenu - Set to `true` to disable the right-click context menu. + */ + this.disableContextMenu = GetValue(config, 'disableContextMenu', false); + + /** + * @const {Phaser.Types.Core.AudioConfig} Phaser.Core.Config#audio - The Audio Configuration object. + */ + this.audio = GetValue(config, 'audio'); + + // If you do: { banner: false } it won't display any banner at all + + /** + * @const {boolean} Phaser.Core.Config#hideBanner - Don't write the banner line to the console.log. + */ + this.hideBanner = (GetValue(config, 'banner', null) === false); + + /** + * @const {boolean} Phaser.Core.Config#hidePhaser - Omit Phaser's name and version from the banner. + */ + this.hidePhaser = GetValue(config, 'banner.hidePhaser', false); + + /** + * @const {string} Phaser.Core.Config#bannerTextColor - The color of the banner text. + */ + this.bannerTextColor = GetValue(config, 'banner.text', defaultBannerTextColor); + + /** + * @const {string[]} Phaser.Core.Config#bannerBackgroundColor - The background colors of the banner. + */ + this.bannerBackgroundColor = GetValue(config, 'banner.background', defaultBannerColor); + + if (this.gameTitle === '' && this.hidePhaser) + { + this.hideBanner = true; + } + + /** + * @const {?Phaser.Types.Core.FPSConfig} Phaser.Core.Config#fps - The Frame Rate Configuration object, as parsed by the Timestep class. + */ + this.fps = GetValue(config, 'fps', null); + + // Renderer Settings + // These can either be in a `render` object within the Config, or specified on their own + + var renderConfig = GetValue(config, 'render', config); + + /** + * @const {boolean} Phaser.Core.Config#antialias - When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. + */ + this.antialias = GetValue(renderConfig, 'antialias', true); + + /** + * @const {boolean} Phaser.Core.Config#antialiasGL - Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. + */ + this.antialiasGL = GetValue(renderConfig, 'antialiasGL', true); + + /** + * @const {string} Phaser.Core.Config#mipmapFilter - Sets the `mipmapFilter` property when the WebGL renderer is created. + */ + this.mipmapFilter = GetValue(renderConfig, 'mipmapFilter', 'LINEAR'); + + /** + * @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. + */ + this.desynchronized = GetValue(renderConfig, 'desynchronized', false); + + /** + * @const {boolean} Phaser.Core.Config#roundPixels - Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. + */ + this.roundPixels = GetValue(renderConfig, 'roundPixels', false); + + /** + * @const {boolean} Phaser.Core.Config#pixelArt - Prevent pixel art from becoming blurred when scaled. It will remain crisp (tells the WebGL renderer to automatically create textures using a linear filter mode). + */ + this.pixelArt = GetValue(renderConfig, 'pixelArt', this.zoom !== 1); + + if (this.pixelArt) + { + this.antialias = false; + this.roundPixels = true; + } + + /** + * @const {boolean} Phaser.Core.Config#transparent - Whether the game canvas will have a transparent background. + */ + this.transparent = GetValue(renderConfig, 'transparent', false); + + /** + * @const {boolean} Phaser.Core.Config#clearBeforeRender - Whether the game canvas will be cleared between each rendering frame. You can disable this if you have a full-screen background image or game object. + */ + this.clearBeforeRender = GetValue(renderConfig, 'clearBeforeRender', true); + + /** + * @const {boolean} Phaser.Core.Config#premultipliedAlpha - In WebGL mode, sets the drawing buffer to contain colors with pre-multiplied alpha. + */ + this.premultipliedAlpha = GetValue(renderConfig, 'premultipliedAlpha', true); + + /** + * @const {boolean} Phaser.Core.Config#failIfMajorPerformanceCaveat - Let the browser abort creating a WebGL context if it judges performance would be unacceptable. + */ + this.failIfMajorPerformanceCaveat = GetValue(renderConfig, 'failIfMajorPerformanceCaveat', false); + + /** + * @const {string} Phaser.Core.Config#powerPreference - "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. + */ + this.powerPreference = GetValue(renderConfig, 'powerPreference', 'default'); + + /** + * @const {integer} Phaser.Core.Config#batchSize - The default WebGL Batch size. + */ + this.batchSize = GetValue(renderConfig, 'batchSize', 2000); + + /** + * @const {integer} Phaser.Core.Config#maxLights - The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. + */ + this.maxLights = GetValue(renderConfig, 'maxLights', 10); + + var bgc = GetValue(config, 'backgroundColor', 0); + + /** + * @const {Phaser.Display.Color} Phaser.Core.Config#backgroundColor - The background color of the game canvas. The default is black. This value is ignored if `transparent` is set to `true`. + */ + this.backgroundColor = ValueToColor(bgc); + + if (bgc === 0 && this.transparent) + { + this.backgroundColor.alpha = 0; + } + + /** + * @const {Phaser.Types.Core.BootCallback} Phaser.Core.Config#preBoot - Called before Phaser boots. Useful for initializing anything not related to Phaser that Phaser may require while booting. + */ + this.preBoot = GetValue(config, 'callbacks.preBoot', NOOP); + + /** + * @const {Phaser.Types.Core.BootCallback} Phaser.Core.Config#postBoot - A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. + */ + this.postBoot = GetValue(config, 'callbacks.postBoot', NOOP); + + /** + * @const {Phaser.Types.Core.PhysicsConfig} Phaser.Core.Config#physics - The Physics Configuration object. + */ + this.physics = GetValue(config, 'physics', {}); + + /** + * @const {(boolean|string)} Phaser.Core.Config#defaultPhysicsSystem - The default physics system. It will be started for each scene. Either 'arcade', 'impact' or 'matter'. + */ + this.defaultPhysicsSystem = GetValue(this.physics, 'default', false); + + /** + * @const {string} Phaser.Core.Config#loaderBaseURL - A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. + */ + this.loaderBaseURL = GetValue(config, 'loader.baseURL', ''); + + /** + * @const {string} Phaser.Core.Config#loaderPath - A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. + */ + this.loaderPath = GetValue(config, 'loader.path', ''); + + /** + * @const {integer} Phaser.Core.Config#loaderMaxParallelDownloads - Maximum parallel downloads allowed for resources (Default to 32). + */ + this.loaderMaxParallelDownloads = GetValue(config, 'loader.maxParallelDownloads', 32); + + /** + * @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}. + */ + this.loaderCrossOrigin = GetValue(config, 'loader.crossOrigin', undefined); + + /** + * @const {string} Phaser.Core.Config#loaderResponseType - The response type of the XHR request, e.g. `blob`, `text`, etc. + */ + this.loaderResponseType = GetValue(config, 'loader.responseType', ''); + + /** + * @const {boolean} Phaser.Core.Config#loaderAsync - Should the XHR request use async or not? + */ + this.loaderAsync = GetValue(config, 'loader.async', true); + + /** + * @const {string} Phaser.Core.Config#loaderUser - Optional username for all XHR requests. + */ + this.loaderUser = GetValue(config, 'loader.user', ''); + + /** + * @const {string} Phaser.Core.Config#loaderPassword - Optional password for all XHR requests. + */ + this.loaderPassword = GetValue(config, 'loader.password', ''); + + /** + * @const {integer} Phaser.Core.Config#loaderTimeout - Optional XHR timeout value, in ms. + */ + this.loaderTimeout = GetValue(config, 'loader.timeout', 0); + + /* + * Allows `plugins` property to either be an array, in which case it just replaces + * the default plugins like previously, or a config object. + * + * plugins: { + * global: [ + * { key: 'TestPlugin', plugin: TestPlugin, start: true, data: { msg: 'The plugin is alive' } }, + * ], + * scene: [ + * { key: 'WireFramePlugin', plugin: WireFramePlugin, systemKey: 'wireFramePlugin', sceneKey: 'wireframe' } + * ], + * default: [], OR + * defaultMerge: [ + * 'ModPlayer' + * ] + * } + */ + + /** + * @const {any} Phaser.Core.Config#installGlobalPlugins - An array of global plugins to be installed. + */ + this.installGlobalPlugins = []; + + /** + * @const {any} Phaser.Core.Config#installScenePlugins - An array of Scene level plugins to be installed. + */ + this.installScenePlugins = []; + + var plugins = GetValue(config, 'plugins', null); + var defaultPlugins = DefaultPlugins.DefaultScene; + + if (plugins) + { + // Old 3.7 array format? + if (Array.isArray(plugins)) + { + this.defaultPlugins = plugins; + } + else if (IsPlainObject(plugins)) + { + this.installGlobalPlugins = GetFastValue(plugins, 'global', []); + this.installScenePlugins = GetFastValue(plugins, 'scene', []); + + if (Array.isArray(plugins.default)) + { + defaultPlugins = plugins.default; + } + else if (Array.isArray(plugins.defaultMerge)) + { + defaultPlugins = defaultPlugins.concat(plugins.defaultMerge); + } + } + } + + /** + * @const {any} Phaser.Core.Config#defaultPlugins - The plugins installed into every Scene (in addition to CoreScene and Global). + */ + this.defaultPlugins = defaultPlugins; + + // Default / Missing Images + var pngPrefix = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg'; + + /** + * @const {string} Phaser.Core.Config#defaultImage - A base64 encoded PNG that will be used as the default blank texture. + */ + this.defaultImage = GetValue(config, 'images.default', pngPrefix + 'AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='); + + /** + * @const {string} Phaser.Core.Config#missingImage - A base64 encoded PNG that will be used as the default texture when a texture is assigned that is missing or not loaded. + */ + this.missingImage = GetValue(config, 'images.missing', pngPrefix + 'CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='); + + if (window) + { + if (window.FORCE_WEBGL) + { + this.renderType = CONST.WEBGL; + } + else if (window.FORCE_CANVAS) + { + this.renderType = CONST.CANVAS; + } + } + } + +}); + +module.exports = Config; + + +/***/ }), +/* 334 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// This singleton is instantiated as soon as Phaser loads, +// before a Phaser.Game instance has even been created. +// Which means all instances of Phaser Games can share it, +// without having to re-poll the device all over again + +/** + * @namespace Phaser.Device + * @since 3.0.0 + */ + +/** + * @typedef {object} Phaser.DeviceConf + * + * @property {Phaser.Device.OS} os - The OS Device functions. + * @property {Phaser.Device.Browser} browser - The Browser Device functions. + * @property {Phaser.Device.Features} features - The Features Device functions. + * @property {Phaser.Device.Input} input - The Input Device functions. + * @property {Phaser.Device.Audio} audio - The Audio Device functions. + * @property {Phaser.Device.Video} video - The Video Device functions. + * @property {Phaser.Device.Fullscreen} fullscreen - The Fullscreen Device functions. + * @property {Phaser.Device.CanvasFeatures} canvasFeatures - The Canvas Device functions. + */ + +module.exports = { + + os: __webpack_require__(124), + browser: __webpack_require__(125), + features: __webpack_require__(180), + input: __webpack_require__(753), + audio: __webpack_require__(754), + video: __webpack_require__(755), + fullscreen: __webpack_require__(756), + canvasFeatures: __webpack_require__(335) + +}; + + +/***/ }), +/* 335 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); + +/** + * Determines the canvas features of the browser 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.canvasFeatures` from within any Scene. + * + * @typedef {object} Phaser.Device.CanvasFeatures + * @since 3.0.0 + * + * @property {boolean} supportInverseAlpha - Set to true if the browser supports inversed alpha. + * @property {boolean} supportNewBlendModes - Set to true if the browser supports new canvas blend modes. + */ +var CanvasFeatures = { + + supportInverseAlpha: false, + supportNewBlendModes: false + +}; + +function checkBlendMode () +{ + var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/'; + var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg=='; + + var magenta = new Image(); + + magenta.onload = function () + { + var yellow = new Image(); + + yellow.onload = function () + { + var canvas = CanvasPool.create(yellow, 6, 1); + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + if (!context.getImageData(2, 0, 1, 1)) + { + return false; + } + + var data = context.getImageData(2, 0, 1, 1).data; + + CanvasPool.remove(yellow); + + CanvasFeatures.supportNewBlendModes = (data[0] === 255 && data[1] === 0 && data[2] === 0); + }; + + yellow.src = pngHead + '/wCKxvRF' + pngEnd; + }; + + magenta.src = pngHead + 'AP804Oa6' + pngEnd; + + return false; +} + +function checkInverseAlpha () +{ + var canvas = CanvasPool.create(this, 2, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1 === null) + { + return false; + } + + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and return + return (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]); +} + +function init () +{ + if (document !== undefined) + { + CanvasFeatures.supportNewBlendModes = checkBlendMode(); + CanvasFeatures.supportInverseAlpha = checkInverseAlpha(); + } + + return CanvasFeatures; +} + +module.exports = init(); + + +/***/ }), +/* 336 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @function Phaser.Math.Angle.Between + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The angle in radians. + */ +var Between = function (x1, y1, x2, y2) +{ + return Math.atan2(y2 - y1, x2 - x1); +}; + +module.exports = Between; + + +/***/ }), +/* 337 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Normalize an angle to the [0, 2pi] range. + * + * @function Phaser.Math.Angle.Normalize + * @since 3.0.0 + * + * @param {number} angle - The angle to normalize, in radians. + * + * @return {number} The normalized angle, in radians. + */ +var Normalize = function (angle) +{ + angle = angle % (2 * Math.PI); + + if (angle >= 0) + { + return angle; + } + else + { + return angle + 2 * Math.PI; + } +}; + +module.exports = Normalize; + + +/***/ }), +/* 338 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two sets of coordinates (points), squared. + * + * @function Phaser.Math.Distance.Squared + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point, squared. + */ +var DistanceSquared = function (x1, y1, x2, y2) +{ + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; +}; + +module.exports = DistanceSquared; + + +/***/ }), +/* 339 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check whether `a` is fuzzily greater than `b`. + * + * `a` is fuzzily greater than `b` if it is more than `b - epsilon`. + * + * @function Phaser.Math.Fuzzy.GreaterThan + * @since 3.0.0 + * + * @param {number} a - The first value. + * @param {number} b - The second value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {boolean} `true` if `a` is fuzzily greater than than `b`, otherwise `false`. + */ +var GreaterThan = function (a, b, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; +}; + +module.exports = GreaterThan; + + +/***/ }), +/* 340 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check whether `a` is fuzzily less than `b`. + * + * `a` is fuzzily less than `b` if it is less than `b + epsilon`. + * + * @function Phaser.Math.Fuzzy.LessThan + * @since 3.0.0 + * + * @param {number} a - The first value. + * @param {number} b - The second value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {boolean} `true` if `a` is fuzzily less than `b`, otherwise `false`. + */ +var LessThan = function (a, b, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return a < b + epsilon; +}; + +module.exports = LessThan; + + +/***/ }), +/* 341 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Factorial = __webpack_require__(342); + +/** + * [description] + * + * @function Phaser.Math.Bernstein + * @since 3.0.0 + * + * @param {number} n - [description] + * @param {number} i - [description] + * + * @return {number} [description] + */ +var Bernstein = function (n, i) +{ + return Factorial(n) / Factorial(i) / Factorial(n - i); +}; + +module.exports = Bernstein; + + +/***/ }), +/* 342 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the factorial of a given number for integer values greater than 0. + * + * @function Phaser.Math.Factorial + * @since 3.0.0 + * + * @param {number} value - A positive integer to calculate the factorial of. + * + * @return {number} The factorial of the given number. + */ +var Factorial = function (value) +{ + if (value === 0) + { + return 1; + } + + var res = value; + + while (--value) + { + res *= value; + } + + return res; +}; + +module.exports = Factorial; + + +/***/ }), +/* 343 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function P0 (t, p) +{ + var k = 1 - t; + + return k * k * k * p; +} + +/** + * @ignore + */ +function P1 (t, p) +{ + var k = 1 - t; + + return 3 * k * k * t * p; +} + +/** + * @ignore + */ +function P2 (t, p) +{ + return 3 * (1 - t) * t * t * p; +} + +/** + * @ignore + */ +function P3 (t, p) +{ + return t * t * t * p; +} + +/** + * A cubic bezier interpolation method. + * + * 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. + */ +var CubicBezierInterpolation = function (t, p0, p1, p2, p3) +{ + return P0(t, p0) + P1(t, p1) + P2(t, p2) + P3(t, p3); +}; + +module.exports = CubicBezierInterpolation; + + +/***/ }), +/* 344 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function P0 (t, p) +{ + var k = 1 - t; + + return k * k * p; +} + +/** + * @ignore + */ +function P1 (t, p) +{ + return 2 * (1 - t) * t * p; +} + +/** + * @ignore + */ +function P2 (t, p) +{ + return t * t * p; +} + +// https://github.com/mrdoob/three.js/blob/master/src/extras/core/Interpolations.js + +/** + * A quadratic bezier interpolation method. + * + * @function Phaser.Math.Interpolation.QuadraticBezier + * @since 3.2.0 + * + * @param {number} t - The percentage of interpolation, between 0 and 1. + * @param {number} p0 - The start point. + * @param {number} p1 - The control point. + * @param {number} p2 - The end point. + * + * @return {number} The interpolated value. + */ +var QuadraticBezierInterpolation = function (t, p0, p1, p2) +{ + return P0(t, p0) + P1(t, p1) + P2(t, p2); +}; + +module.exports = QuadraticBezierInterpolation; + + +/***/ }), +/* 345 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SmoothStep = __webpack_require__(171); + +/** + * A Smooth Step interpolation method. + * + * @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. + */ +var SmoothStepInterpolation = function (t, min, max) +{ + return min + (max - min) * SmoothStep(t, 0, 1); +}; + +module.exports = SmoothStepInterpolation; + + +/***/ }), +/* 346 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the nearest power of 2 to the given `value`. + * + * @function Phaser.Math.Pow2.GetNext + * @since 3.0.0 + * + * @param {number} value - The value. + * + * @return {integer} The nearest power of 2 to `value`. + */ +var GetPowerOfTwo = function (value) +{ + var index = Math.log(value) / 0.6931471805599453; + + return (1 << Math.ceil(index)); +}; + +module.exports = GetPowerOfTwo; + + +/***/ }), +/* 347 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `15`. + * As will `14` snap to `15`... but `16` will snap to `20`. + * + * @function Phaser.Math.Snap.Ceil + * @since 3.0.0 + * + * @param {number} value - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. + * + * @return {number} The snapped value. + */ +var SnapCeil = function (value, gap, start, divide) +{ + if (start === undefined) { start = 0; } + + if (gap === 0) + { + return value; + } + + value -= start; + value = gap * Math.ceil(value / gap); + + return (divide) ? (start + value) / gap : start + value; +}; + +module.exports = SnapCeil; + + +/***/ }), +/* 348 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Generate a random floating point number between the two given bounds, minimum inclusive, maximum exclusive. + * + * @function Phaser.Math.FloatBetween + * @since 3.0.0 + * + * @param {number} min - The lower bound for the float, inclusive. + * @param {number} max - The upper bound for the float exclusive. + * + * @return {number} A random float within the given range. + */ +var FloatBetween = function (min, max) +{ + return Math.random() * (max - min) + min; +}; + +module.exports = FloatBetween; + + +/***/ }), +/* 349 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a given point by a given angle around the origin (0, 0), in an anti-clockwise direction. + * + * @function Phaser.Math.Rotate + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. + * @param {number} angle - The angle to be rotated by in an anticlockwise direction. + * + * @return {Phaser.Geom.Point} The given point, rotated by the given angle in an anticlockwise direction. + */ +var Rotate = function (point, angle) +{ + var x = point.x; + var y = point.y; + + point.x = (x * Math.cos(angle)) - (y * Math.sin(angle)); + point.y = (x * Math.sin(angle)) + (y * Math.cos(angle)); + + return point; +}; + +module.exports = Rotate; + + +/***/ }), +/* 350 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Round a given number so it is further away from zero. That is, positive numbers are rounded up, and negative numbers are rounded down. + * + * @function Phaser.Math.RoundAwayFromZero + * @since 3.0.0 + * + * @param {number} value - The number to round. + * + * @return {number} The rounded number, rounded away from zero. + */ +var RoundAwayFromZero = function (value) +{ + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); +}; + +module.exports = RoundAwayFromZero; + + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = __webpack_require__(3); + +/** + * Takes the `x` and `y` coordinates and transforms them into the same space as + * defined by the position, rotation and scale values. + * + * @function Phaser.Math.TransformXY + * @since 3.0.0 + * + * @param {number} x - The x coordinate to be transformed. + * @param {number} y - The y coordinate to be transformed. + * @param {number} positionX - Horizontal position of the transform point. + * @param {number} positionY - Vertical position of the transform point. + * @param {number} rotation - Rotation of the transform point, in radians. + * @param {number} scaleX - Horizontal scale of the transform point. + * @param {number} scaleY - Vertical scale of the transform point. + * @param {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} [output] - The output vector, point or object for the translated coordinates. + * + * @return {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} The translated point. + */ +var TransformXY = function (x, y, positionX, positionY, rotation, scaleX, scaleY, output) +{ + if (output === undefined) { output = new Vector2(); } + + var radianSin = Math.sin(rotation); + var radianCos = Math.cos(rotation); + + // Rotate and Scale + var a = radianCos * scaleX; + var b = radianSin * scaleX; + var c = -radianSin * scaleY; + var d = radianCos * scaleY; + + // Invert + var id = 1 / ((a * d) + (c * -b)); + + output.x = (d * id * x) + (-c * id * y) + (((positionY * c) - (positionX * d)) * id); + output.y = (a * id * y) + (-b * id * x) + (((-positionY * a) + (positionX * b)) * id); + + return output; +}; + +module.exports = TransformXY; + + +/***/ }), +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A representation of a vector in 4D space. + * + * A four-component vector. + * + * @class Vector4 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - The x component. + * @param {number} [y] - The y component. + * @param {number} [z] - The z component. + * @param {number} [w] - The w component. + */ +var Vector4 = new Class({ + + initialize: + + function Vector4 (x, y, z, w) + { + /** + * The x component of this Vector. + * + * @name Phaser.Math.Vector4#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y component of this Vector. + * + * @name Phaser.Math.Vector4#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The z component of this Vector. + * + * @name Phaser.Math.Vector4#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.z = 0; + + /** + * The w component of this Vector. + * + * @name Phaser.Math.Vector4#w + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.w = 0; + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + }, + + /** + * Make a clone of this Vector4. + * + * @method Phaser.Math.Vector4#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} A clone of this Vector4. + */ + clone: function () + { + return new Vector4(this.x, this.y, this.z, this.w); + }, + + /** + * Copy the components of a given Vector into this Vector. + * + * @method Phaser.Math.Vector4#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} src - The Vector to copy the components from. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + copy: function (src) + { + this.x = src.x; + this.y = src.y; + this.z = src.z || 0; + this.w = src.w || 0; + + return this; + }, + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict quality check against each Vector's components. + * + * @method Phaser.Math.Vector4#equals + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} v - The vector to check equality with. + * + * @return {boolean} A boolean indicating whether the two Vectors are equal or not. + */ + equals: function (v) + { + return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z) && (this.w === v.w)); + }, + + /** + * Set the `x`, `y`, `z` and `w` components of the this Vector to the given `x`, `y`, `z` and `w` values. + * + * @method Phaser.Math.Vector4#set + * @since 3.0.0 + * + * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y, z and w components. + * @param {number} y - The y value to set for this Vector. + * @param {number} z - The z value to set for this Vector. + * @param {number} w - The z value to set for this Vector. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + set: function (x, y, z, w) + { + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + + return this; + }, + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * + * @method Phaser.Math.Vector4#add + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to add to this Vector. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + add: function (v) + { + this.x += v.x; + this.y += v.y; + this.z += v.z || 0; + this.w += v.w || 0; + + return this; + }, + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * + * @method Phaser.Math.Vector4#subtract + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to subtract from this Vector. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + subtract: function (v) + { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z || 0; + this.w -= v.w || 0; + + return this; + }, + + /** + * Scale this Vector by the given value. + * + * @method Phaser.Math.Vector4#scale + * @since 3.0.0 + * + * @param {number} scale - The value to scale this Vector by. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + scale: function (scale) + { + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + + return this; + }, + + /** + * Calculate the length (or magnitude) of this Vector. + * + * @method Phaser.Math.Vector4#length + * @since 3.0.0 + * + * @return {number} The length of this Vector. + */ + length: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return Math.sqrt(x * x + y * y + z * z + w * w); + }, + + /** + * Calculate the length of this Vector squared. + * + * @method Phaser.Math.Vector4#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Vector, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return x * x + y * y + z * z + w * w; + }, + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + * + * @method Phaser.Math.Vector4#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + this.z = z * len; + this.w = w * len; + } + + return this; + }, + + /** + * Calculate the dot product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector4#dot + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} v - The Vector4 to dot product with this Vector4. + * + * @return {number} The dot product of this Vector and the given Vector. + */ + dot: function (v) + { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + }, + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * + * @method Phaser.Math.Vector4#lerp + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} v - The Vector4 to interpolate towards. + * @param {number} [t=0] - The interpolation percentage, between 0 and 1. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + lerp: function (v, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + this.x = ax + t * (v.x - ax); + this.y = ay + t * (v.y - ay); + this.z = az + t * (v.z - az); + this.w = aw + t * (v.w - aw); + + return this; + }, + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * + * @method Phaser.Math.Vector4#multiply + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to multiply this Vector by. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + multiply: function (v) + { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z || 1; + this.w *= v.w || 1; + + return this; + }, + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * + * @method Phaser.Math.Vector4#divide + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to divide this Vector by. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + divide: function (v) + { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z || 1; + this.w /= v.w || 1; + + return this; + }, + + /** + * Calculate the distance between this Vector and the given Vector. + * + * @method Phaser.Math.Vector4#distance + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector. + */ + distance: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + var dw = v.w - this.w || 0; + + return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); + }, + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * + * @method Phaser.Math.Vector4#distanceSq + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector, squared. + */ + distanceSq: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + var dw = v.w - this.w || 0; + + return dx * dx + dy * dy + dz * dz + dw * dw; + }, + + /** + * Negate the `x`, `y`, `z` and `w` components of this Vector. + * + * @method Phaser.Math.Vector4#negate + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + negate: function () + { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector4#transformMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector4 with. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + transformMat4: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + var m = mat.val; + + this.x = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + this.y = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + this.z = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + this.w = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + + return this; + }, + + /** + * Transform this Vector with the given Quaternion. + * + * @method Phaser.Math.Vector4#transformQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + transformQuat: function (q) + { + // TODO: is this really the same as Vector3? + // Also, what about this: http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + var x = this.x; + var y = this.y; + var z = this.z; + var qx = q.x; + var qy = q.y; + var qz = q.z; + var qw = q.w; + + // calculate quat * vec + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + + return this; + }, + + /** + * Make this Vector the zero vector (0, 0, 0, 0). + * + * @method Phaser.Math.Vector4#reset + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + reset: function () + { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + + return this; + } + +}); + +// TODO: Check if these are required internally, if not, remove. +Vector4.prototype.sub = Vector4.prototype.subtract; +Vector4.prototype.mul = Vector4.prototype.multiply; +Vector4.prototype.div = Vector4.prototype.divide; +Vector4.prototype.dist = Vector4.prototype.distance; +Vector4.prototype.distSq = Vector4.prototype.distanceSq; +Vector4.prototype.len = Vector4.prototype.length; +Vector4.prototype.lenSq = Vector4.prototype.lengthSq; + +module.exports = Vector4; + + +/***/ }), +/* 353 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A three-dimensional matrix. + * + * Defaults to the identity matrix when instantiated. + * + * @class Matrix3 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} [m] - Optional Matrix3 to copy values from. + */ +var Matrix3 = new Class({ + + initialize: + + function Matrix3 (m) + { + /** + * The matrix values. + * + * @name Phaser.Math.Matrix3#val + * @type {Float32Array} + * @since 3.0.0 + */ + this.val = new Float32Array(9); + + if (m) + { + // Assume Matrix3 with val: + this.copy(m); + } + else + { + // Default to identity + this.identity(); + } + }, + + /** + * Make a clone of this Matrix3. + * + * @method Phaser.Math.Matrix3#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} A clone of this Matrix3. + */ + clone: function () + { + return new Matrix3(this); + }, + + /** + * This method is an alias for `Matrix3.copy`. + * + * @method Phaser.Math.Matrix3#set + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} src - The Matrix to set the values of this Matrix's from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + set: function (src) + { + return this.copy(src); + }, + + /** + * Copy the values of a given Matrix into this Matrix. + * + * @method Phaser.Math.Matrix3#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} src - The Matrix to copy the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + copy: function (src) + { + var out = this.val; + var a = src.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + + return this; + }, + + /** + * Copy the values of a given Matrix4 into this Matrix3. + * + * @method Phaser.Math.Matrix3#fromMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} m - The Matrix4 to copy the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + fromMat4: function (m) + { + var a = m.val; + var out = this.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + + return this; + }, + + /** + * Set the values of this Matrix from the given array. + * + * @method Phaser.Math.Matrix3#fromArray + * @since 3.0.0 + * + * @param {array} a - The array to copy the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + fromArray: function (a) + { + var out = this.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + + return this; + }, + + /** + * Reset this Matrix to an identity (default) matrix. + * + * @method Phaser.Math.Matrix3#identity + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + identity: function () + { + var out = this.val; + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + + return this; + }, + + /** + * Transpose this Matrix. + * + * @method Phaser.Math.Matrix3#transpose + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + transpose: function () + { + var a = this.val; + var a01 = a[1]; + var a02 = a[2]; + var a12 = a[5]; + + a[1] = a[3]; + a[2] = a[6]; + a[3] = a01; + a[5] = a[7]; + a[6] = a02; + a[7] = a12; + + return this; + }, + + /** + * Invert this Matrix. + * + * @method Phaser.Math.Matrix3#invert + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + invert: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + var b01 = a22 * a11 - a12 * a21; + var b11 = -a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; + + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) + { + return null; + } + + det = 1 / det; + + a[0] = b01 * det; + a[1] = (-a22 * a01 + a02 * a21) * det; + a[2] = (a12 * a01 - a02 * a11) * det; + a[3] = b11 * det; + a[4] = (a22 * a00 - a02 * a20) * det; + a[5] = (-a12 * a00 + a02 * a10) * det; + a[6] = b21 * det; + a[7] = (-a21 * a00 + a01 * a20) * det; + a[8] = (a11 * a00 - a01 * a10) * det; + + return this; + }, + + /** + * Calculate the adjoint, or adjugate, of this Matrix. + * + * @method Phaser.Math.Matrix3#adjoint + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + adjoint: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + a[0] = (a11 * a22 - a12 * a21); + a[1] = (a02 * a21 - a01 * a22); + a[2] = (a01 * a12 - a02 * a11); + a[3] = (a12 * a20 - a10 * a22); + a[4] = (a00 * a22 - a02 * a20); + a[5] = (a02 * a10 - a00 * a12); + a[6] = (a10 * a21 - a11 * a20); + a[7] = (a01 * a20 - a00 * a21); + a[8] = (a00 * a11 - a01 * a10); + + return this; + }, + + /** + * Calculate the determinant of this Matrix. + * + * @method Phaser.Math.Matrix3#determinant + * @since 3.0.0 + * + * @return {number} The determinant of this Matrix. + */ + determinant: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); + }, + + /** + * Multiply this Matrix by the given Matrix. + * + * @method Phaser.Math.Matrix3#multiply + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} src - The Matrix to multiply this Matrix by. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + multiply: function (src) + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + var b = src.val; + + var b00 = b[0]; + var b01 = b[1]; + var b02 = b[2]; + var b10 = b[3]; + var b11 = b[4]; + var b12 = b[5]; + var b20 = b[6]; + var b21 = b[7]; + var b22 = b[8]; + + a[0] = b00 * a00 + b01 * a10 + b02 * a20; + a[1] = b00 * a01 + b01 * a11 + b02 * a21; + a[2] = b00 * a02 + b01 * a12 + b02 * a22; + + a[3] = b10 * a00 + b11 * a10 + b12 * a20; + a[4] = b10 * a01 + b11 * a11 + b12 * a21; + a[5] = b10 * a02 + b11 * a12 + b12 * a22; + + a[6] = b20 * a00 + b21 * a10 + b22 * a20; + a[7] = b20 * a01 + b21 * a11 + b22 * a21; + a[8] = b20 * a02 + b21 * a12 + b22 * a22; + + return this; + }, + + /** + * Translate this Matrix using the given Vector. + * + * @method Phaser.Math.Matrix3#translate + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to translate this Matrix with. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + translate: function (v) + { + var a = this.val; + var x = v.x; + var y = v.y; + + a[6] = x * a[0] + y * a[3] + a[6]; + a[7] = x * a[1] + y * a[4] + a[7]; + a[8] = x * a[2] + y * a[5] + a[8]; + + return this; + }, + + /** + * Apply a rotation transformation to this Matrix. + * + * @method Phaser.Math.Matrix3#rotate + * @since 3.0.0 + * + * @param {number} rad - The angle in radians to rotate by. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + rotate: function (rad) + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + + var s = Math.sin(rad); + var c = Math.cos(rad); + + a[0] = c * a00 + s * a10; + a[1] = c * a01 + s * a11; + a[2] = c * a02 + s * a12; + + a[3] = c * a10 - s * a00; + a[4] = c * a11 - s * a01; + a[5] = c * a12 - s * a02; + + return this; + }, + + /** + * Apply a scale transformation to this Matrix. + * + * Uses the `x` and `y` components of the given Vector to scale the Matrix. + * + * @method Phaser.Math.Matrix3#scale + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to scale this Matrix with. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + scale: function (v) + { + var a = this.val; + var x = v.x; + var y = v.y; + + a[0] = x * a[0]; + a[1] = x * a[1]; + a[2] = x * a[2]; + + a[3] = y * a[3]; + a[4] = y * a[4]; + a[5] = y * a[5]; + + return this; + }, + + /** + * Set the values of this Matrix from the given Quaternion. + * + * @method Phaser.Math.Matrix3#fromQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to set the values of this Matrix from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + fromQuat: function (q) + { + var x = q.x; + var y = q.y; + var z = q.z; + var w = q.w; + + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + var out = this.val; + + out[0] = 1 - (yy + zz); + out[3] = xy + wz; + out[6] = xz - wy; + + out[1] = xy - wz; + out[4] = 1 - (xx + zz); + out[7] = yz + wx; + + out[2] = xz + wy; + out[5] = yz - wx; + out[8] = 1 - (xx + yy); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Math.Matrix3#normalFromMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} m - [description] + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + normalFromMat4: function (m) + { + var a = m.val; + var out = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) + { + return null; + } + + det = 1 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + + return this; + } + +}); + +module.exports = Matrix3; + + +/***/ }), +/* 354 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = __webpack_require__(0); + +var EPSILON = 0.000001; + +/** + * @classdesc + * A four-dimensional matrix. + * + * @class Matrix4 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} [m] - Optional Matrix4 to copy values from. + */ +var Matrix4 = new Class({ + + initialize: + + function Matrix4 (m) + { + /** + * The matrix values. + * + * @name Phaser.Math.Matrix4#val + * @type {Float32Array} + * @since 3.0.0 + */ + this.val = new Float32Array(16); + + if (m) + { + // Assume Matrix4 with val: + this.copy(m); + } + else + { + // Default to identity + this.identity(); + } + }, + + /** + * Make a clone of this Matrix4. + * + * @method Phaser.Math.Matrix4#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} A clone of this Matrix4. + */ + clone: function () + { + return new Matrix4(this); + }, + + // TODO - Should work with basic values + + /** + * This method is an alias for `Matrix4.copy`. + * + * @method Phaser.Math.Matrix4#set + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The Matrix to set the values of this Matrix's from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + set: function (src) + { + return this.copy(src); + }, + + /** + * Copy the values of a given Matrix into this Matrix. + * + * @method Phaser.Math.Matrix4#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The Matrix to copy the values from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + copy: function (src) + { + var out = this.val; + var a = src.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + + return this; + }, + + /** + * Set the values of this Matrix from the given array. + * + * @method Phaser.Math.Matrix4#fromArray + * @since 3.0.0 + * + * @param {array} a - The array to copy the values from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + fromArray: function (a) + { + var out = this.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + + return this; + }, + + /** + * Reset this Matrix. + * + * Sets all values to `0`. + * + * @method Phaser.Math.Matrix4#zero + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + zero: function () + { + var out = this.val; + + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 0; + + return this; + }, + + /** + * Set the `x`, `y` and `z` values of this Matrix. + * + * @method Phaser.Math.Matrix4#xyz + * @since 3.0.0 + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * @param {number} z - The z value. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + xyz: function (x, y, z) + { + this.identity(); + + var out = this.val; + + out[12] = x; + out[13] = y; + out[14] = z; + + return this; + }, + + /** + * Set the scaling values of this Matrix. + * + * @method Phaser.Math.Matrix4#scaling + * @since 3.0.0 + * + * @param {number} x - The x scaling value. + * @param {number} y - The y scaling value. + * @param {number} z - The z scaling value. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + scaling: function (x, y, z) + { + this.zero(); + + var out = this.val; + + out[0] = x; + out[5] = y; + out[10] = z; + out[15] = 1; + + return this; + }, + + /** + * Reset this Matrix to an identity (default) matrix. + * + * @method Phaser.Math.Matrix4#identity + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + identity: function () + { + var out = this.val; + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + + return this; + }, + + /** + * Transpose this Matrix. + * + * @method Phaser.Math.Matrix4#transpose + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + transpose: function () + { + var a = this.val; + + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a12 = a[6]; + var a13 = a[7]; + var a23 = a[11]; + + a[1] = a[4]; + a[2] = a[8]; + a[3] = a[12]; + a[4] = a01; + a[6] = a[9]; + a[7] = a[13]; + a[8] = a02; + a[9] = a12; + a[11] = a[14]; + a[12] = a03; + a[13] = a13; + a[14] = a23; + + return this; + }, + + /** + * Invert this Matrix. + * + * @method Phaser.Math.Matrix4#invert + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + invert: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) + { + return null; + } + + det = 1 / det; + + a[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + a[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + a[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + a[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + a[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + a[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + a[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + a[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + a[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + a[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + a[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + a[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + a[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + a[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + a[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + a[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return this; + }, + + /** + * Calculate the adjoint, or adjugate, of this Matrix. + * + * @method Phaser.Math.Matrix4#adjoint + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + adjoint: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + a[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); + a[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + a[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); + a[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + a[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + a[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); + a[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + a[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); + a[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); + a[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + a[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); + a[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + a[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + a[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); + a[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + a[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); + + return this; + }, + + /** + * Calculate the determinant of this Matrix. + * + * @method Phaser.Math.Matrix4#determinant + * @since 3.0.0 + * + * @return {number} The determinant of this Matrix. + */ + determinant: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + }, + + /** + * Multiply this Matrix by the given Matrix. + * + * @method Phaser.Math.Matrix4#multiply + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The Matrix to multiply this Matrix by. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + multiply: function (src) + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b = src.val; + + // Cache only the current line of the second matrix + var b0 = b[0]; + var b1 = b[1]; + var b2 = b[2]; + var b3 = b[3]; + + a[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + + a[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + + a[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + + a[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Math.Matrix4#multiplyLocal + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - [description] + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + multiplyLocal: function (src) + { + var a = []; + var m1 = this.val; + var m2 = src.val; + + a[0] = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12]; + a[1] = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13]; + a[2] = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14]; + a[3] = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15]; + + a[4] = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12]; + a[5] = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13]; + a[6] = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14]; + a[7] = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15]; + + a[8] = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12]; + a[9] = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13]; + a[10] = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14]; + a[11] = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15]; + + a[12] = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12]; + a[13] = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13]; + a[14] = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14]; + a[15] = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15]; + + return this.fromArray(a); + }, + + /** + * Translate this Matrix using the given Vector. + * + * @method Phaser.Math.Matrix4#translate + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to translate this Matrix with. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + translate: function (v) + { + var x = v.x; + var y = v.y; + var z = v.z; + var a = this.val; + + a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + + return this; + }, + + /** + * Translate this Matrix using the given values. + * + * @method Phaser.Math.Matrix4#translateXYZ + * @since 3.16.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + translateXYZ: function (x, y, z) + { + var a = this.val; + + a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + + return this; + }, + + /** + * Apply a scale transformation to this Matrix. + * + * Uses the `x`, `y` and `z` components of the given Vector to scale the Matrix. + * + * @method Phaser.Math.Matrix4#scale + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to scale this Matrix with. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + scale: function (v) + { + var x = v.x; + var y = v.y; + var z = v.z; + var a = this.val; + + a[0] = a[0] * x; + a[1] = a[1] * x; + a[2] = a[2] * x; + a[3] = a[3] * x; + + a[4] = a[4] * y; + a[5] = a[5] * y; + a[6] = a[6] * y; + a[7] = a[7] * y; + + a[8] = a[8] * z; + a[9] = a[9] * z; + a[10] = a[10] * z; + a[11] = a[11] * z; + + return this; + }, + + /** + * Apply a scale transformation to this Matrix. + * + * @method Phaser.Math.Matrix4#scaleXYZ + * @since 3.16.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + scaleXYZ: function (x, y, z) + { + var a = this.val; + + a[0] = a[0] * x; + a[1] = a[1] * x; + a[2] = a[2] * x; + a[3] = a[3] * x; + + a[4] = a[4] * y; + a[5] = a[5] * y; + a[6] = a[6] * y; + a[7] = a[7] * y; + + a[8] = a[8] * z; + a[9] = a[9] * z; + a[10] = a[10] * z; + a[11] = a[11] * z; + + return this; + }, + + /** + * Derive a rotation matrix around the given axis. + * + * @method Phaser.Math.Matrix4#makeRotationAxis + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} axis - The rotation axis. + * @param {number} angle - The rotation angle in radians. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + makeRotationAxis: function (axis, angle) + { + // Based on http://www.gamedev.net/reference/articles/article1199.asp + + var c = Math.cos(angle); + var s = Math.sin(angle); + var t = 1 - c; + var x = axis.x; + var y = axis.y; + var z = axis.z; + var tx = t * x; + var ty = t * y; + + this.fromArray([ + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 + ]); + + return this; + }, + + /** + * Apply a rotation transformation to this Matrix. + * + * @method Phaser.Math.Matrix4#rotate + * @since 3.0.0 + * + * @param {number} rad - The angle in radians to rotate by. + * @param {Phaser.Math.Vector3} axis - The axis to rotate upon. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotate: function (rad, axis) + { + var a = this.val; + var x = axis.x; + var y = axis.y; + var z = axis.z; + var len = Math.sqrt(x * x + y * y + z * z); + + if (Math.abs(len) < EPSILON) + { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + + var s = Math.sin(rad); + var c = Math.cos(rad); + var t = 1 - c; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + // Construct the elements of the rotation matrix + var b00 = x * x * t + c; + var b01 = y * x * t + z * s; + var b02 = z * x * t - y * s; + + var b10 = x * y * t - z * s; + var b11 = y * y * t + c; + var b12 = z * y * t + x * s; + + var b20 = x * z * t + y * s; + var b21 = y * z * t - x * s; + var b22 = z * z * t + c; + + // Perform rotation-specific matrix multiplication + a[0] = a00 * b00 + a10 * b01 + a20 * b02; + a[1] = a01 * b00 + a11 * b01 + a21 * b02; + a[2] = a02 * b00 + a12 * b01 + a22 * b02; + a[3] = a03 * b00 + a13 * b01 + a23 * b02; + a[4] = a00 * b10 + a10 * b11 + a20 * b12; + a[5] = a01 * b10 + a11 * b11 + a21 * b12; + a[6] = a02 * b10 + a12 * b11 + a22 * b12; + a[7] = a03 * b10 + a13 * b11 + a23 * b12; + a[8] = a00 * b20 + a10 * b21 + a20 * b22; + a[9] = a01 * b20 + a11 * b21 + a21 * b22; + a[10] = a02 * b20 + a12 * b21 + a22 * b22; + a[11] = a03 * b20 + a13 * b21 + a23 * b22; + + return this; + }, + + /** + * Rotate this matrix on its X axis. + * + * @method Phaser.Math.Matrix4#rotateX + * @since 3.0.0 + * + * @param {number} rad - The angle in radians to rotate by. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotateX: function (rad) + { + var a = this.val; + var s = Math.sin(rad); + var c = Math.cos(rad); + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + // Perform axis-specific matrix multiplication + a[4] = a10 * c + a20 * s; + a[5] = a11 * c + a21 * s; + a[6] = a12 * c + a22 * s; + a[7] = a13 * c + a23 * s; + a[8] = a20 * c - a10 * s; + a[9] = a21 * c - a11 * s; + a[10] = a22 * c - a12 * s; + a[11] = a23 * c - a13 * s; + + return this; + }, + + /** + * Rotate this matrix on its Y axis. + * + * @method Phaser.Math.Matrix4#rotateY + * @since 3.0.0 + * + * @param {number} rad - The angle to rotate by, in radians. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotateY: function (rad) + { + var a = this.val; + var s = Math.sin(rad); + var c = Math.cos(rad); + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + // Perform axis-specific matrix multiplication + a[0] = a00 * c - a20 * s; + a[1] = a01 * c - a21 * s; + a[2] = a02 * c - a22 * s; + a[3] = a03 * c - a23 * s; + a[8] = a00 * s + a20 * c; + a[9] = a01 * s + a21 * c; + a[10] = a02 * s + a22 * c; + a[11] = a03 * s + a23 * c; + + return this; + }, + + /** + * Rotate this matrix on its Z axis. + * + * @method Phaser.Math.Matrix4#rotateZ + * @since 3.0.0 + * + * @param {number} rad - The angle to rotate by, in radians. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotateZ: function (rad) + { + var a = this.val; + var s = Math.sin(rad); + var c = Math.cos(rad); + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + // Perform axis-specific matrix multiplication + a[0] = a00 * c + a10 * s; + a[1] = a01 * c + a11 * s; + a[2] = a02 * c + a12 * s; + a[3] = a03 * c + a13 * s; + a[4] = a10 * c - a00 * s; + a[5] = a11 * c - a01 * s; + a[6] = a12 * c - a02 * s; + a[7] = a13 * c - a03 * s; + + return this; + }, + + /** + * Set the values of this Matrix from the given rotation Quaternion and translation Vector. + * + * @method Phaser.Math.Matrix4#fromRotationTranslation + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to set rotation from. + * @param {Phaser.Math.Vector3} v - The Vector to set translation from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + fromRotationTranslation: function (q, v) + { + // Quaternion math + var out = this.val; + + var x = q.x; + var y = q.y; + var z = q.z; + var w = q.w; + + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + + out[12] = v.x; + out[13] = v.y; + out[14] = v.z; + out[15] = 1; + + return this; + }, + + /** + * Set the values of this Matrix from the given Quaternion. + * + * @method Phaser.Math.Matrix4#fromQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to set the values of this Matrix from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + fromQuat: function (q) + { + var out = this.val; + + var x = q.x; + var y = q.y; + var z = q.z; + var w = q.w; + + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + + return this; + }, + + /** + * Generate a frustum matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#frustum + * @since 3.0.0 + * + * @param {number} left - The left bound of the frustum. + * @param {number} right - The right bound of the frustum. + * @param {number} bottom - The bottom bound of the frustum. + * @param {number} top - The top bound of the frustum. + * @param {number} near - The near bound of the frustum. + * @param {number} far - The far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + frustum: function (left, right, bottom, top, near, far) + { + var out = this.val; + + var rl = 1 / (right - left); + var tb = 1 / (top - bottom); + var nf = 1 / (near - far); + + out[0] = (near * 2) * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = (near * 2) * tb; + out[6] = 0; + out[7] = 0; + + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + + out[12] = 0; + out[13] = 0; + out[14] = (far * near * 2) * nf; + out[15] = 0; + + return this; + }, + + /** + * Generate a perspective projection matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#perspective + * @since 3.0.0 + * + * @param {number} fovy - Vertical field of view in radians + * @param {number} aspect - Aspect ratio. Typically viewport width /height. + * @param {number} near - Near bound of the frustum. + * @param {number} far - Far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + perspective: function (fovy, aspect, near, far) + { + var out = this.val; + var f = 1.0 / Math.tan(fovy / 2); + var nf = 1 / (near - far); + + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + + out[12] = 0; + out[13] = 0; + out[14] = (2 * far * near) * nf; + out[15] = 0; + + return this; + }, + + /** + * Generate a perspective projection matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#perspectiveLH + * @since 3.0.0 + * + * @param {number} width - The width of the frustum. + * @param {number} height - The height of the frustum. + * @param {number} near - Near bound of the frustum. + * @param {number} far - Far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + perspectiveLH: function (width, height, near, far) + { + var out = this.val; + + out[0] = (2 * near) / width; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = (2 * near) / height; + out[6] = 0; + out[7] = 0; + + out[8] = 0; + out[9] = 0; + out[10] = -far / (near - far); + out[11] = 1; + + out[12] = 0; + out[13] = 0; + out[14] = (near * far) / (near - far); + out[15] = 0; + + return this; + }, + + /** + * Generate an orthogonal projection matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#ortho + * @since 3.0.0 + * + * @param {number} left - The left bound of the frustum. + * @param {number} right - The right bound of the frustum. + * @param {number} bottom - The bottom bound of the frustum. + * @param {number} top - The top bound of the frustum. + * @param {number} near - The near bound of the frustum. + * @param {number} far - The far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + ortho: function (left, right, bottom, top, near, far) + { + var out = this.val; + var lr = left - right; + var bt = bottom - top; + var nf = near - far; + + // Avoid division by zero + lr = (lr === 0) ? lr : 1 / lr; + bt = (bt === 0) ? bt : 1 / bt; + nf = (nf === 0) ? nf : 1 / nf; + + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + + return this; + }, + + /** + * Generate a look-at matrix with the given eye position, focal point, and up axis. + * + * @method Phaser.Math.Matrix4#lookAt + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} eye - Position of the viewer + * @param {Phaser.Math.Vector3} center - Point the viewer is looking at + * @param {Phaser.Math.Vector3} up - vec3 pointing up. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + lookAt: function (eye, center, up) + { + var out = this.val; + + var eyex = eye.x; + var eyey = eye.y; + var eyez = eye.z; + + var upx = up.x; + var upy = up.y; + var upz = up.z; + + var centerx = center.x; + var centery = center.y; + var centerz = center.z; + + if (Math.abs(eyex - centerx) < EPSILON && + Math.abs(eyey - centery) < EPSILON && + Math.abs(eyez - centerz) < EPSILON) + { + return this.identity(); + } + + var z0 = eyex - centerx; + var z1 = eyey - centery; + var z2 = eyez - centerz; + + var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + + z0 *= len; + z1 *= len; + z2 *= len; + + var x0 = upy * z2 - upz * z1; + var x1 = upz * z0 - upx * z2; + var x2 = upx * z1 - upy * z0; + + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + + if (!len) + { + x0 = 0; + x1 = 0; + x2 = 0; + } + else + { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + var y0 = z1 * x2 - z2 * x1; + var y1 = z2 * x0 - z0 * x2; + var y2 = z0 * x1 - z1 * x0; + + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + + if (!len) + { + y0 = 0; + y1 = 0; + y2 = 0; + } + else + { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + + return this; + }, + + /** + * Set the values of this matrix from the given `yaw`, `pitch` and `roll` values. + * + * @method Phaser.Math.Matrix4#yawPitchRoll + * @since 3.0.0 + * + * @param {number} yaw - [description] + * @param {number} pitch - [description] + * @param {number} roll - [description] + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + yawPitchRoll: function (yaw, pitch, roll) + { + this.zero(); + _tempMat1.zero(); + _tempMat2.zero(); + + var m0 = this.val; + var m1 = _tempMat1.val; + var m2 = _tempMat2.val; + + // Rotate Z + var s = Math.sin(roll); + var c = Math.cos(roll); + + m0[10] = 1; + m0[15] = 1; + m0[0] = c; + m0[1] = s; + m0[4] = -s; + m0[5] = c; + + // Rotate X + s = Math.sin(pitch); + c = Math.cos(pitch); + + m1[0] = 1; + m1[15] = 1; + m1[5] = c; + m1[10] = c; + m1[9] = -s; + m1[6] = s; + + // Rotate Y + s = Math.sin(yaw); + c = Math.cos(yaw); + + m2[5] = 1; + m2[15] = 1; + m2[0] = c; + m2[2] = -s; + m2[8] = s; + m2[10] = c; + + this.multiplyLocal(_tempMat1); + this.multiplyLocal(_tempMat2); + + return this; + }, + + /** + * Generate a world matrix from the given rotation, position, scale, view matrix and projection matrix. + * + * @method Phaser.Math.Matrix4#setWorldMatrix + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} rotation - The rotation of the world matrix. + * @param {Phaser.Math.Vector3} position - The position of the world matrix. + * @param {Phaser.Math.Vector3} scale - The scale of the world matrix. + * @param {Phaser.Math.Matrix4} [viewMatrix] - The view matrix. + * @param {Phaser.Math.Matrix4} [projectionMatrix] - The projection matrix. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + setWorldMatrix: function (rotation, position, scale, viewMatrix, projectionMatrix) + { + this.yawPitchRoll(rotation.y, rotation.x, rotation.z); + + _tempMat1.scaling(scale.x, scale.y, scale.z); + _tempMat2.xyz(position.x, position.y, position.z); + + this.multiplyLocal(_tempMat1); + this.multiplyLocal(_tempMat2); + + if (viewMatrix !== undefined) + { + this.multiplyLocal(viewMatrix); + } + + if (projectionMatrix !== undefined) + { + this.multiplyLocal(projectionMatrix); + } + + return this; + } + +}); + +var _tempMat1 = new Matrix4(); +var _tempMat2 = new Matrix4(); + +module.exports = Matrix4; + + +/***/ }), +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = __webpack_require__(0); +var Vector3 = __webpack_require__(185); +var Matrix3 = __webpack_require__(353); + +var EPSILON = 0.000001; + +// Some shared 'private' arrays +var siNext = new Int8Array([ 1, 2, 0 ]); +var tmp = new Float32Array([ 0, 0, 0 ]); + +var xUnitVec3 = new Vector3(1, 0, 0); +var yUnitVec3 = new Vector3(0, 1, 0); + +var tmpvec = new Vector3(); +var tmpMat3 = new Matrix3(); + +/** + * @classdesc + * A quaternion. + * + * @class Quaternion + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - The x component. + * @param {number} [y] - The y component. + * @param {number} [z] - The z component. + * @param {number} [w] - The w component. + */ +var Quaternion = new Class({ + + initialize: + + function Quaternion (x, y, z, w) + { + /** + * The x component of this Quaternion. + * + * @name Phaser.Math.Quaternion#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + /** + * The y component of this Quaternion. + * + * @name Phaser.Math.Quaternion#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + /** + * The z component of this Quaternion. + * + * @name Phaser.Math.Quaternion#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + /** + * The w component of this Quaternion. + * + * @name Phaser.Math.Quaternion#w + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + }, + + /** + * Copy the components of a given Quaternion or Vector into this Quaternion. + * + * @method Phaser.Math.Quaternion#copy + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} src - The Quaternion or Vector to copy the components from. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + copy: function (src) + { + this.x = src.x; + this.y = src.y; + this.z = src.z; + this.w = src.w; + + return this; + }, + + /** + * Set the components of this Quaternion. + * + * @method Phaser.Math.Quaternion#set + * @since 3.0.0 + * + * @param {(number|object)} [x=0] - The x component, or an object containing x, y, z, and w components. + * @param {number} [y=0] - The y component. + * @param {number} [z=0] - The z component. + * @param {number} [w=0] - The w component. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + set: function (x, y, z, w) + { + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + + return this; + }, + + /** + * Add a given Quaternion or Vector to this Quaternion. Addition is component-wise. + * + * @method Phaser.Math.Quaternion#add + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to add to this Quaternion. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + add: function (v) + { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + + return this; + }, + + /** + * Subtract a given Quaternion or Vector from this Quaternion. Subtraction is component-wise. + * + * @method Phaser.Math.Quaternion#subtract + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to subtract from this Quaternion. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + subtract: function (v) + { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + + return this; + }, + + /** + * Scale this Quaternion by the given value. + * + * @method Phaser.Math.Quaternion#scale + * @since 3.0.0 + * + * @param {number} scale - The value to scale this Quaternion by. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + scale: function (scale) + { + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + + return this; + }, + + /** + * Calculate the length of this Quaternion. + * + * @method Phaser.Math.Quaternion#length + * @since 3.0.0 + * + * @return {number} The length of this Quaternion. + */ + length: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return Math.sqrt(x * x + y * y + z * z + w * w); + }, + + /** + * Calculate the length of this Quaternion squared. + * + * @method Phaser.Math.Quaternion#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Quaternion, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return x * x + y * y + z * z + w * w; + }, + + /** + * Normalize this Quaternion. + * + * @method Phaser.Math.Quaternion#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + this.z = z * len; + this.w = w * len; + } + + return this; + }, + + /** + * Calculate the dot product of this Quaternion and the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#dot + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to dot product with this Quaternion. + * + * @return {number} The dot product of this Quaternion and the given Quaternion or Vector. + */ + dot: function (v) + { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + }, + + /** + * Linearly interpolate this Quaternion towards the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#lerp + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to interpolate towards. + * @param {number} [t=0] - The percentage of interpolation. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + lerp: function (v, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + this.x = ax + t * (v.x - ax); + this.y = ay + t * (v.y - ay); + this.z = az + t * (v.z - az); + this.w = aw + t * (v.w - aw); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Math.Quaternion#rotationTo + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} a - [description] + * @param {Phaser.Math.Vector3} b - [description] + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotationTo: function (a, b) + { + var dot = a.x * b.x + a.y * b.y + a.z * b.z; + + if (dot < -0.999999) + { + if (tmpvec.copy(xUnitVec3).cross(a).length() < EPSILON) + { + tmpvec.copy(yUnitVec3).cross(a); + } + + tmpvec.normalize(); + + return this.setAxisAngle(tmpvec, Math.PI); + + } + else if (dot > 0.999999) + { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 1; + + return this; + } + else + { + tmpvec.copy(a).cross(b); + + this.x = tmpvec.x; + this.y = tmpvec.y; + this.z = tmpvec.z; + this.w = 1 + dot; + + return this.normalize(); + } + }, + + /** + * Set the axes of this Quaternion. + * + * @method Phaser.Math.Quaternion#setAxes + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} view - The view axis. + * @param {Phaser.Math.Vector3} right - The right axis. + * @param {Phaser.Math.Vector3} up - The upwards axis. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + setAxes: function (view, right, up) + { + var m = tmpMat3.val; + + m[0] = right.x; + m[3] = right.y; + m[6] = right.z; + + m[1] = up.x; + m[4] = up.y; + m[7] = up.z; + + m[2] = -view.x; + m[5] = -view.y; + m[8] = -view.z; + + return this.fromMat3(tmpMat3).normalize(); + }, + + /** + * Reset this Matrix to an identity (default) Quaternion. + * + * @method Phaser.Math.Quaternion#identity + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + identity: function () + { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 1; + + return this; + }, + + /** + * Set the axis angle of this Quaternion. + * + * @method Phaser.Math.Quaternion#setAxisAngle + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} axis - The axis. + * @param {number} rad - The angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + setAxisAngle: function (axis, rad) + { + rad = rad * 0.5; + + var s = Math.sin(rad); + + this.x = s * axis.x; + this.y = s * axis.y; + this.z = s * axis.z; + this.w = Math.cos(rad); + + return this; + }, + + /** + * Multiply this Quaternion by the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#multiply + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} b - The Quaternion or Vector to multiply this Quaternion by. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + multiply: function (b) + { + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bx = b.x; + var by = b.y; + var bz = b.z; + var bw = b.w; + + this.x = ax * bw + aw * bx + ay * bz - az * by; + this.y = ay * bw + aw * by + az * bx - ax * bz; + this.z = az * bw + aw * bz + ax * by - ay * bx; + this.w = aw * bw - ax * bx - ay * by - az * bz; + + return this; + }, + + /** + * Smoothly linearly interpolate this Quaternion towards the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#slerp + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} b - The Quaternion or Vector to interpolate towards. + * @param {number} t - The percentage of interpolation. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + slerp: function (b, t) + { + // benchmarks: http://jsperf.com/quaternion-slerp-implementations + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bx = b.x; + var by = b.y; + var bz = b.z; + var bw = b.w; + + // calc cosine + var cosom = ax * bx + ay * by + az * bz + aw * bw; + + // adjust signs (if necessary) + if (cosom < 0) + { + cosom = -cosom; + bx = - bx; + by = - by; + bz = - bz; + bw = - bw; + } + + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + var scale0 = 1 - t; + var scale1 = t; + + // calculate coefficients + if ((1 - cosom) > EPSILON) + { + // standard case (slerp) + var omega = Math.acos(cosom); + var sinom = Math.sin(omega); + + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } + + // calculate final values + this.x = scale0 * ax + scale1 * bx; + this.y = scale0 * ay + scale1 * by; + this.z = scale0 * az + scale1 * bz; + this.w = scale0 * aw + scale1 * bw; + + return this; + }, + + /** + * Invert this Quaternion. + * + * @method Phaser.Math.Quaternion#invert + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + invert: function () + { + var a0 = this.x; + var a1 = this.y; + var a2 = this.z; + var a3 = this.w; + + var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; + var invDot = (dot) ? 1 / dot : 0; + + // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + this.x = -a0 * invDot; + this.y = -a1 * invDot; + this.z = -a2 * invDot; + this.w = a3 * invDot; + + return this; + }, + + /** + * Convert this Quaternion into its conjugate. + * + * Sets the x, y and z components. + * + * @method Phaser.Math.Quaternion#conjugate + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + conjugate: function () + { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + + return this; + }, + + /** + * Rotate this Quaternion on the X axis. + * + * @method Phaser.Math.Quaternion#rotateX + * @since 3.0.0 + * + * @param {number} rad - The rotation angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotateX: function (rad) + { + rad *= 0.5; + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bx = Math.sin(rad); + var bw = Math.cos(rad); + + this.x = ax * bw + aw * bx; + this.y = ay * bw + az * bx; + this.z = az * bw - ay * bx; + this.w = aw * bw - ax * bx; + + return this; + }, + + /** + * Rotate this Quaternion on the Y axis. + * + * @method Phaser.Math.Quaternion#rotateY + * @since 3.0.0 + * + * @param {number} rad - The rotation angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotateY: function (rad) + { + rad *= 0.5; + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var by = Math.sin(rad); + var bw = Math.cos(rad); + + this.x = ax * bw - az * by; + this.y = ay * bw + aw * by; + this.z = az * bw + ax * by; + this.w = aw * bw - ay * by; + + return this; + }, + + /** + * Rotate this Quaternion on the Z axis. + * + * @method Phaser.Math.Quaternion#rotateZ + * @since 3.0.0 + * + * @param {number} rad - The rotation angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotateZ: function (rad) + { + rad *= 0.5; + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bz = Math.sin(rad); + var bw = Math.cos(rad); + + this.x = ax * bw + ay * bz; + this.y = ay * bw - ax * bz; + this.z = az * bw + aw * bz; + this.w = aw * bw - az * bz; + + return this; + }, + + /** + * Create a unit (or rotation) Quaternion from its x, y, and z components. + * + * Sets the w component. + * + * @method Phaser.Math.Quaternion#calculateW + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + calculateW: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + + this.w = -Math.sqrt(1.0 - x * x - y * y - z * z); + + return this; + }, + + /** + * Convert the given Matrix into this Quaternion. + * + * @method Phaser.Math.Quaternion#fromMat3 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} mat - The Matrix to convert from. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + fromMat3: function (mat) + { + // 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". + var m = mat.val; + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if (fTrace > 0) + { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + + this.w = 0.5 * fRoot; + + fRoot = 0.5 / fRoot; // 1/(4w) + + this.x = (m[7] - m[5]) * fRoot; + this.y = (m[2] - m[6]) * fRoot; + this.z = (m[3] - m[1]) * fRoot; + } + else + { + // |w| <= 1/2 + var i = 0; + + if (m[4] > m[0]) + { + i = 1; + } + + if (m[8] > m[i * 3 + i]) + { + i = 2; + } + + var j = siNext[i]; + var k = siNext[j]; + + // This isn't quite as clean without array access + fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1); + tmp[i] = 0.5 * fRoot; + + fRoot = 0.5 / fRoot; + + tmp[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; + tmp[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; + + this.x = tmp[0]; + this.y = tmp[1]; + this.z = tmp[2]; + this.w = (m[k * 3 + j] - m[j * 3 + k]) * fRoot; + } + + return this; + } + +}); + +module.exports = Quaternion; + + +/***/ }), +/* 356 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasInterpolation = __webpack_require__(357); +var CanvasPool = __webpack_require__(28); +var CONST = __webpack_require__(32); +var Features = __webpack_require__(180); + +/** + * Called automatically by Phaser.Game and responsible for creating the renderer it will use. + * + * Relies upon two webpack global flags to be defined: `WEBGL_RENDERER` and `CANVAS_RENDERER` during build time, but not at run-time. + * + * @function Phaser.Core.CreateRenderer + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance on which the renderer will be set. + */ +var CreateRenderer = function (game) +{ + var config = game.config; + + if ((config.customEnvironment || config.canvas) && config.renderType === CONST.AUTO) + { + throw new Error('Must set explicit renderType in custom environment'); + } + + // Not a custom environment, didn't provide their own canvas and not headless, so determine the renderer: + if (!config.customEnvironment && !config.canvas && config.renderType !== CONST.HEADLESS) + { + if (config.renderType === CONST.CANVAS || (config.renderType !== CONST.CANVAS && !Features.webGL)) + { + if (Features.canvas) + { + // They requested Canvas and their browser supports it + config.renderType = CONST.CANVAS; + } + else + { + throw new Error('Cannot create Canvas or WebGL context, aborting.'); + } + } + else + { + // Game requested WebGL and browser says it supports it + config.renderType = CONST.WEBGL; + } + } + + // Pixel Art mode? + if (!config.antialias) + { + CanvasPool.disableSmoothing(); + } + + var baseSize = game.scale.baseSize; + + var width = baseSize.width; + var height = baseSize.height; + + // Does the game config provide its own canvas element to use? + if (config.canvas) + { + game.canvas = config.canvas; + + game.canvas.width = width; + game.canvas.height = height; + } + else + { + game.canvas = CanvasPool.create(game, width, height, config.renderType); + } + + // Does the game config provide some canvas css styles to use? + if (config.canvasStyle) + { + game.canvas.style = config.canvasStyle; + } + + // Pixel Art mode? + if (!config.antialias) + { + CanvasInterpolation.setCrisp(game.canvas); + } + + if (config.renderType === CONST.HEADLESS) + { + // Nothing more to do here + return; + } + + var CanvasRenderer; + var WebGLRenderer; + + if (true) + { + CanvasRenderer = __webpack_require__(358); + WebGLRenderer = __webpack_require__(361); + + // Let the config pick the renderer type, as both are included + if (config.renderType === CONST.WEBGL) + { + game.renderer = new WebGLRenderer(game); + } + else + { + game.renderer = new CanvasRenderer(game); + game.context = game.renderer.gameContext; + } + } + + if (false) + {} + + if (false) + {} +}; + +module.exports = CreateRenderer; + + +/***/ }), +/* 357 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Canvas.CanvasInterpolation + * @since 3.0.0 + */ +var CanvasInterpolation = { + + /** + * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit). + * + * @function Phaser.Display.Canvas.CanvasInterpolation.setCrisp + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas object to have the style set on. + * + * @return {HTMLCanvasElement} The canvas. + */ + setCrisp: function (canvas) + { + var types = [ 'optimizeSpeed', '-moz-crisp-edges', '-o-crisp-edges', '-webkit-optimize-contrast', 'optimize-contrast', 'crisp-edges', 'pixelated' ]; + + types.forEach(function (type) + { + canvas.style['image-rendering'] = type; + }); + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * + * @function Phaser.Display.Canvas.CanvasInterpolation.setBicubic + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas object to have the style set on. + * + * @return {HTMLCanvasElement} The canvas. + */ + setBicubic: function (canvas) + { + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + } + +}; + +module.exports = CanvasInterpolation; + + +/***/ }), +/* 358 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasSnapshot = __webpack_require__(359); +var CameraEvents = __webpack_require__(55); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(32); +var GetBlendModes = __webpack_require__(360); +var ScaleEvents = __webpack_require__(104); +var TransformMatrix = __webpack_require__(35); + +/** + * @classdesc + * The Canvas Renderer is responsible for managing 2D canvas rendering contexts, including the one used by the Game's canvas. It tracks the internal state of a given context and can renderer textured Game Objects to it, taking into account alpha, blending, and scaling. + * + * @class CanvasRenderer + * @memberof Phaser.Renderer.Canvas + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser Game instance that owns this renderer. + */ +var CanvasRenderer = new Class({ + + initialize: + + function CanvasRenderer (game) + { + /** + * The Phaser Game instance that owns this renderer. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * A constant which allows the renderer to be easily identified as a Canvas Renderer. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#type + * @type {integer} + * @since 3.0.0 + */ + this.type = CONST.CANVAS; + + /** + * The total number of Game Objects which were rendered in a frame. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#drawCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.drawCount = 0; + + /** + * The width of the canvas being rendered to. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#width + * @type {integer} + * @since 3.0.0 + */ + this.width = 0; + + /** + * The height of the canvas being rendered to. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#height + * @type {integer} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The local configuration settings of the CanvasRenderer. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#config + * @type {object} + * @since 3.0.0 + */ + this.config = { + clearBeforeRender: game.config.clearBeforeRender, + backgroundColor: game.config.backgroundColor, + resolution: game.config.resolution, + antialias: game.config.antialias, + roundPixels: game.config.roundPixels + }; + + /** + * The canvas element which the Game uses. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#gameCanvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.gameCanvas = game.canvas; + + var contextOptions = { + alpha: game.config.transparent, + desynchronized: game.config.desynchronized + }; + + /** + * The canvas context used to render all Cameras in all Scenes during the game loop. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#gameContext + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.gameContext = (this.game.config.context) ? this.game.config.context : this.gameCanvas.getContext('2d', contextOptions); + + /** + * The canvas context currently used by the CanvasRenderer for all rendering operations. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#currentContext + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.currentContext = this.gameContext; + + /** + * Should the Canvas use Image Smoothing or not when drawing Sprites? + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#antialias + * @type {boolean} + * @since 3.20.0 + */ + this.antialias = game.config.antialias; + + /** + * The blend modes supported by the Canvas Renderer. + * + * This object maps the {@link Phaser.BlendModes} to canvas compositing operations. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#blendModes + * @type {array} + * @since 3.0.0 + */ + this.blendModes = GetBlendModes(); + + /** + * Details about the currently scheduled snapshot. + * + * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#snapshotState + * @type {Phaser.Types.Renderer.Snapshot.SnapshotState} + * @since 3.16.0 + */ + this.snapshotState = { + x: 0, + y: 0, + width: 1, + height: 1, + getPixel: false, + callback: null, + type: 'image/png', + encoder: 0.92 + }; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix4 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix4 = new TransformMatrix(); + + this.init(); + }, + + /** + * Prepares the game canvas for rendering. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#init + * @since 3.0.0 + */ + init: function () + { + this.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); + + var baseSize = this.game.scale.baseSize; + + this.resize(baseSize.width, baseSize.height); + }, + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#onResize + * @since 3.16.0 + * + * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. + * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + * @param {Phaser.Structs.Size} displaySize - The display Size object. The size of the canvas style width / height attributes. + * @param {number} [resolution] - The Scale Manager resolution setting. + */ + onResize: function (gameSize, baseSize) + { + // Has the underlying canvas size changed? + if (baseSize.width !== this.width || baseSize.height !== this.height) + { + this.resize(baseSize.width, baseSize.height); + } + }, + + /** + * Resize the main game canvas. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#resize + * @since 3.0.0 + * + * @param {number} [width] - The new width of the renderer. + * @param {number} [height] - The new height of the renderer. + */ + resize: function (width, height) + { + this.width = width; + this.height = height; + }, + + /** + * Resets the transformation matrix of the current context to the identity matrix, thus resetting any transformation. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#resetTransform + * @since 3.0.0 + */ + resetTransform: function () + { + this.currentContext.setTransform(1, 0, 0, 1, 0, 0); + }, + + /** + * Sets the blend mode (compositing operation) of the current context. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#setBlendMode + * @since 3.0.0 + * + * @param {string} blendMode - The new blend mode which should be used. + * + * @return {this} This CanvasRenderer object. + */ + setBlendMode: function (blendMode) + { + this.currentContext.globalCompositeOperation = blendMode; + + return this; + }, + + /** + * Changes the Canvas Rendering Context that all draw operations are performed against. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#setContext + * @since 3.12.0 + * + * @param {?CanvasRenderingContext2D} [ctx] - The new Canvas Rendering Context to draw everything to. Leave empty to reset to the Game Canvas. + * + * @return {this} The Canvas Renderer instance. + */ + setContext: function (ctx) + { + this.currentContext = (ctx) ? ctx : this.gameContext; + + return this; + }, + + /** + * Sets the global alpha of the current context. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#setAlpha + * @since 3.0.0 + * + * @param {number} alpha - The new alpha to use, where 0 is fully transparent and 1 is fully opaque. + * + * @return {this} This CanvasRenderer object. + */ + setAlpha: function (alpha) + { + this.currentContext.globalAlpha = alpha; + + return this; + }, + + /** + * Called at the start of the render loop. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#preRender + * @since 3.0.0 + */ + preRender: function () + { + var ctx = this.gameContext; + var config = this.config; + + var width = this.width; + var height = this.height; + + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = 'source-over'; + ctx.setTransform(1, 0, 0, 1, 0, 0); + + if (config.clearBeforeRender) + { + ctx.clearRect(0, 0, width, height); + } + + if (!config.transparent) + { + ctx.fillStyle = config.backgroundColor.rgba; + ctx.fillRect(0, 0, width, height); + } + + ctx.save(); + + this.drawCount = 0; + }, + + /** + * Renders the Scene to the given Camera. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#render + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to render. + * @param {Phaser.GameObjects.DisplayList} children - The Game Objects within the Scene to be rendered. + * @param {number} interpolationPercentage - The interpolation percentage to apply. Currently unused. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera to render with. + */ + render: function (scene, children, interpolationPercentage, camera) + { + var list = children.list; + var childCount = list.length; + + var cx = camera._cx; + var cy = camera._cy; + var cw = camera._cw; + var ch = camera._ch; + + var ctx = (camera.renderToTexture) ? camera.context : scene.sys.context; + + // Save context pre-clip + ctx.save(); + + if (this.game.scene.customViewports) + { + ctx.beginPath(); + ctx.rect(cx, cy, cw, ch); + ctx.clip(); + } + + this.currentContext = ctx; + + var mask = camera.mask; + + if (mask) + { + mask.preRenderCanvas(this, null, camera._maskCamera); + } + + if (!camera.transparent) + { + ctx.fillStyle = camera.backgroundColor.rgba; + ctx.fillRect(cx, cy, cw, ch); + } + + ctx.globalAlpha = camera.alpha; + + ctx.globalCompositeOperation = 'source-over'; + + this.drawCount += list.length; + + if (camera.renderToTexture) + { + camera.emit(CameraEvents.PRE_RENDER, camera); + } + + camera.matrix.copyToContext(ctx); + + for (var i = 0; i < childCount; i++) + { + var child = list[i]; + + if (!child.willRender(camera)) + { + continue; + } + + if (child.mask) + { + child.mask.preRenderCanvas(this, child, camera); + } + + child.renderCanvas(this, child, interpolationPercentage, camera); + + if (child.mask) + { + child.mask.postRenderCanvas(this, child, camera); + } + } + + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalCompositeOperation = 'source-over'; + ctx.globalAlpha = 1; + + camera.flashEffect.postRenderCanvas(ctx); + camera.fadeEffect.postRenderCanvas(ctx); + + camera.dirty = false; + + if (mask) + { + mask.postRenderCanvas(this); + } + + // Restore pre-clip context + ctx.restore(); + + if (camera.renderToTexture) + { + camera.emit(CameraEvents.POST_RENDER, camera); + + scene.sys.context.drawImage(camera.canvas, cx, cy); + } + }, + + /** + * Restores the game context's global settings and takes a snapshot if one is scheduled. + * + * The post-render step happens after all Cameras in all Scenes have been rendered. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#postRender + * @since 3.0.0 + */ + postRender: function () + { + var ctx = this.gameContext; + + ctx.restore(); + + var state = this.snapshotState; + + if (state.callback) + { + CanvasSnapshot(this.gameCanvas, state); + + state.callback = null; + } + }, + + /** + * Takes a snapshot of the given area of the given canvas. + * + * Unlike the other snapshot methods, this one is processed immediately and doesn't wait for the next render. + * + * Snapshots work by creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshotCanvas + * @since 3.19.0 + * + * @param {HTMLCanvasElement} canvas - The canvas to grab from. + * @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 {integer} [x=0] - The x coordinate to grab from. + * @param {integer} [y=0] - The y coordinate to grab from. + * @param {integer} [width=canvas.width] - The width of the area to grab. + * @param {integer} [height=canvas.height] - 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 Canvas Renderer. + */ + snapshotCanvas: function (canvas, callback, getPixel, x, y, width, height, type, encoderOptions) + { + if (getPixel === undefined) { getPixel = false; } + + this.snapshotArea(x, y, width, height, callback, type, encoderOptions); + + var state = this.snapshotState; + + state.getPixel = getPixel; + + CanvasSnapshot(this.canvas, state); + + state.callback = null; + + return this; + }, + + /** + * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. + * + * To capture a specific area see the `snapshotArea` 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 creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshot + * @since 3.0.0 + * + * @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. + */ + snapshot: function (callback, type, encoderOptions) + { + return this.snapshotArea(0, 0, this.gameCanvas.width, this.gameCanvas.height, callback, type, encoderOptions); + }, + + /** + * 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 creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshotArea + * @since 3.16.0 + * + * @param {integer} x - The x coordinate to grab from. + * @param {integer} y - The y coordinate to grab from. + * @param {integer} width - The width of the area to grab. + * @param {integer} 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. + */ + snapshotArea: function (x, y, width, height, callback, type, encoderOptions) + { + var state = this.snapshotState; + + state.callback = callback; + state.type = type; + state.encoder = encoderOptions; + state.getPixel = false; + state.x = x; + state.y = y; + state.width = Math.min(width, this.gameCanvas.width); + state.height = Math.min(height, this.gameCanvas.height); + + return this; + }, + + /** + * 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.Canvas.CanvasRenderer#snapshotPixel + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the pixel to get. + * @param {integer} y - The y coordinate of the pixel to get. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. + * + * @return {this} This WebGL Renderer. + */ + snapshotPixel: function (x, y, callback) + { + this.snapshotArea(x, y, 1, 1, callback); + + this.snapshotState.getPixel = true; + + return this; + }, + + /** + * Takes a Sprite Game Object, or any object that extends it, and draws it to the current context. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#batchSprite + * @since 3.12.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The texture based Game Object to draw. + * @param {Phaser.Textures.Frame} frame - The frame to draw, doesn't have to be that owned by the Game Object. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - The transform matrix of the parent container, if set. + */ + batchSprite: function (sprite, frame, camera, parentTransformMatrix) + { + var alpha = camera.alpha * sprite.alpha; + + if (alpha === 0) + { + // Nothing to see, so abort early + return; + } + + var ctx = this.currentContext; + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var cd = frame.canvasData; + + var frameX = cd.x; + var frameY = cd.y; + var frameWidth = frame.cutWidth; + var frameHeight = frame.cutHeight; + var customPivot = frame.customPivot; + + var res = frame.source.resolution; + + var displayOriginX = sprite.displayOriginX; + var displayOriginY = sprite.displayOriginY; + + var x = -displayOriginX + frame.x; + var y = -displayOriginY + frame.y; + + if (sprite.isCropped) + { + var crop = sprite._crop; + + if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) + { + frame.updateCropUVs(crop, sprite.flipX, sprite.flipY); + } + + frameWidth = crop.cw; + frameHeight = crop.ch; + + frameX = crop.cx; + frameY = crop.cy; + + x = -displayOriginX + crop.x; + y = -displayOriginY + crop.y; + + if (sprite.flipX) + { + if (x >= 0) + { + x = -(x + frameWidth); + } + else if (x < 0) + { + x = (Math.abs(x) - frameWidth); + } + } + + if (sprite.flipY) + { + if (y >= 0) + { + y = -(y + frameHeight); + } + else if (y < 0) + { + y = (Math.abs(y) - frameHeight); + } + } + } + + var flipX = 1; + var flipY = 1; + + if (sprite.flipX) + { + if (!customPivot) + { + x += (-frame.realWidth + (displayOriginX * 2)); + } + + flipX = -1; + } + + // Auto-invert the flipY if this is coming from a GLTexture + if (sprite.flipY) + { + if (!customPivot) + { + y += (-frame.realHeight + (displayOriginY * 2)); + } + + flipY = -1; + } + + spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX * flipX, sprite.scaleY * flipY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = sprite.x; + spriteMatrix.f = sprite.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; + spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + ctx.save(); + + calcMatrix.setToContext(ctx); + + ctx.globalCompositeOperation = this.blendModes[sprite.blendMode]; + + ctx.globalAlpha = alpha; + + ctx.imageSmoothingEnabled = !(!this.antialias || frame.source.scaleMode); + + ctx.drawImage(frame.source.image, frameX, frameY, frameWidth, frameHeight, x, y, frameWidth / res, frameHeight / res); + + ctx.restore(); + }, + + /** + * Destroys all object references in the Canvas Renderer. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.gameCanvas = null; + this.gameContext = null; + + this.game = null; + } + +}); + +module.exports = CanvasRenderer; + + +/***/ }), +/* 359 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); +var Color = __webpack_require__(36); +var GetFastValue = __webpack_require__(1); + +/** + * Takes a snapshot of an area from the current frame displayed by a canvas. + * + * This is then copied to an Image object. When this loads, the results are sent + * to the callback provided in the Snapshot Configuration object. + * + * @function Phaser.Renderer.Snapshot.Canvas + * @since 3.0.0 + * + * @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotState} config - The snapshot configuration object. + */ +var CanvasSnapshot = function (canvas, config) +{ + var callback = GetFastValue(config, 'callback'); + var type = GetFastValue(config, 'type', 'image/png'); + var encoderOptions = GetFastValue(config, 'encoder', 0.92); + var x = Math.abs(Math.round(GetFastValue(config, 'x', 0))); + var y = Math.abs(Math.round(GetFastValue(config, 'y', 0))); + var width = GetFastValue(config, 'width', canvas.width); + var height = GetFastValue(config, 'height', canvas.height); + var getPixel = GetFastValue(config, 'getPixel', false); + + if (getPixel) + { + var context = canvas.getContext('2d'); + var imageData = context.getImageData(x, y, 1, 1); + var data = imageData.data; + + callback.call(null, new Color(data[0], data[1], data[2], data[3] / 255)); + } + else if (x !== 0 || y !== 0 || width !== canvas.width || height !== canvas.height) + { + // Area Grab + var copyCanvas = CanvasPool.createWebGL(this, width, height); + var ctx = copyCanvas.getContext('2d'); + + ctx.drawImage(canvas, x, y, width, height, 0, 0, width, height); + + var image1 = new Image(); + + image1.onerror = function () + { + callback.call(null); + + CanvasPool.remove(copyCanvas); + }; + + image1.onload = function () + { + callback.call(null, image1); + + CanvasPool.remove(copyCanvas); + }; + + image1.src = copyCanvas.toDataURL(type, encoderOptions); + } + else + { + // Full Grab + var image2 = new Image(); + + image2.onerror = function () + { + callback.call(null); + }; + + image2.onload = function () + { + callback.call(null, image2); + }; + + image2.src = canvas.toDataURL(type, encoderOptions); + } +}; + +module.exports = CanvasSnapshot; + + +/***/ }), +/* 360 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var modes = __webpack_require__(43); +var CanvasFeatures = __webpack_require__(335); + +/** + * Returns an array which maps the default blend modes to supported Canvas blend modes. + * + * If the browser doesn't support a blend mode, it will default to the normal `source-over` blend mode. + * + * @function Phaser.Renderer.Canvas.GetBlendModes + * @since 3.0.0 + * + * @return {array} Which Canvas blend mode corresponds to which default Phaser blend mode. + */ +var GetBlendModes = function () +{ + var output = []; + var useNew = CanvasFeatures.supportNewBlendModes; + var so = 'source-over'; + + output[modes.NORMAL] = so; + output[modes.ADD] = 'lighter'; + output[modes.MULTIPLY] = (useNew) ? 'multiply' : so; + output[modes.SCREEN] = (useNew) ? 'screen' : so; + output[modes.OVERLAY] = (useNew) ? 'overlay' : so; + output[modes.DARKEN] = (useNew) ? 'darken' : so; + output[modes.LIGHTEN] = (useNew) ? 'lighten' : so; + output[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : so; + output[modes.COLOR_BURN] = (useNew) ? 'color-burn' : so; + output[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : so; + output[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : so; + output[modes.DIFFERENCE] = (useNew) ? 'difference' : so; + output[modes.EXCLUSION] = (useNew) ? 'exclusion' : so; + output[modes.HUE] = (useNew) ? 'hue' : so; + output[modes.SATURATION] = (useNew) ? 'saturation' : so; + output[modes.COLOR] = (useNew) ? 'color' : so; + output[modes.LUMINOSITY] = (useNew) ? 'luminosity' : so; + output[modes.ERASE] = 'destination-out'; + output[modes.SOURCE_IN] = 'source-in'; + output[modes.SOURCE_OUT] = 'source-out'; + output[modes.SOURCE_ATOP] = 'source-atop'; + output[modes.DESTINATION_OVER] = 'destination-over'; + output[modes.DESTINATION_IN] = 'destination-in'; + output[modes.DESTINATION_OUT] = 'destination-out'; + output[modes.DESTINATION_ATOP] = 'destination-atop'; + output[modes.LIGHTER] = 'lighter'; + output[modes.COPY] = 'copy'; + output[modes.XOR] = 'xor'; + + return output; +}; + +module.exports = GetBlendModes; + + +/***/ }), +/* 361 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCamera = __webpack_require__(103); +var CameraEvents = __webpack_require__(55); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(32); +var GameEvents = __webpack_require__(21); +var IsSizePowerOfTwo = __webpack_require__(127); +var NOOP = __webpack_require__(2); +var ScaleEvents = __webpack_require__(104); +var SpliceOne = __webpack_require__(85); +var TextureEvents = __webpack_require__(128); +var TransformMatrix = __webpack_require__(35); +var Utils = __webpack_require__(10); +var WebGLSnapshot = __webpack_require__(362); + +// Default Pipelines +var BitmapMaskPipeline = __webpack_require__(363); +var ForwardDiffuseLightPipeline = __webpack_require__(364); +var TextureTintPipeline = __webpack_require__(188); + +/** + * @callback WebGLContextCallback + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer which owns the context. + */ + +/** + * @classdesc + * WebGLRenderer is a class that contains the needed functionality to keep the + * WebGLRenderingContext state clean. The main idea of the WebGLRenderer is to keep track of + * any context change that happens for WebGL rendering inside of Phaser. This means + * if raw webgl functions are called outside the WebGLRenderer of the Phaser WebGL + * rendering ecosystem they might pollute the current WebGLRenderingContext state producing + * unexpected behavior. It's recommended that WebGL interaction is done through + * WebGLRenderer and/or WebGLPipeline. + * + * @class WebGLRenderer + * @memberof Phaser.Renderer.WebGL + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Game instance which owns this WebGL Renderer. + */ +var WebGLRenderer = new Class({ + + initialize: + + function WebGLRenderer (game) + { + var gameConfig = game.config; + + var contextCreationConfig = { + alpha: gameConfig.transparent, + desynchronized: gameConfig.desynchronized, + depth: false, + antialias: gameConfig.antialiasGL, + premultipliedAlpha: gameConfig.premultipliedAlpha, + stencil: true, + failIfMajorPerformanceCaveat: gameConfig.failIfMajorPerformanceCaveat, + powerPreference: gameConfig.powerPreference + }; + + /** + * The local configuration settings of this WebGL Renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#config + * @type {object} + * @since 3.0.0 + */ + this.config = { + clearBeforeRender: gameConfig.clearBeforeRender, + antialias: gameConfig.antialias, + backgroundColor: gameConfig.backgroundColor, + contextCreation: contextCreationConfig, + resolution: gameConfig.resolution, + roundPixels: gameConfig.roundPixels, + maxTextures: gameConfig.maxTextures, + maxTextureSize: gameConfig.maxTextureSize, + batchSize: gameConfig.batchSize, + maxLights: gameConfig.maxLights, + mipmapFilter: gameConfig.mipmapFilter + }; + + /** + * The Game instance which owns this WebGL Renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * A constant which allows the renderer to be easily identified as a WebGL Renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#type + * @type {integer} + * @since 3.0.0 + */ + this.type = CONST.WEBGL; + + /** + * The width of the canvas being rendered to. + * This is populated in the onResize event handler. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#width + * @type {integer} + * @since 3.0.0 + */ + this.width = 0; + + /** + * The height of the canvas being rendered to. + * This is populated in the onResize event handler. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#height + * @type {integer} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The canvas which this WebGL Renderer draws to. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas = game.canvas; + + /** + * An array of blend modes supported by the WebGL Renderer. + * + * This array includes the default blend modes as well as any custom blend modes added through {@link #addBlendMode}. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#blendModes + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.blendModes = []; + + /** + * Keeps track of any WebGLTexture created with the current WebGLRenderingContext + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#nativeTextures + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.nativeTextures = []; + + /** + * This property is set to `true` if the WebGL context of the renderer is lost. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#contextLost + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.contextLost = false; + + /** + * This object will store all pipelines created through addPipeline + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#pipelines + * @type {object} + * @default null + * @since 3.0.0 + */ + this.pipelines = null; + + /** + * Details about the currently scheduled snapshot. + * + * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#snapshotState + * @type {Phaser.Types.Renderer.Snapshot.SnapshotState} + * @since 3.0.0 + */ + this.snapshotState = { + x: 0, + y: 0, + width: 1, + height: 1, + getPixel: false, + callback: null, + type: 'image/png', + encoder: 0.92, + isFramebuffer: false, + bufferWidth: 0, + bufferHeight: 0 + }; + + // Internal Renderer State (Textures, Framebuffers, Pipelines, Buffers, etc) + + /** + * Cached value for the last texture unit that was used + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentActiveTextureUnit + * @type {integer} + * @since 3.1.0 + */ + this.currentActiveTextureUnit = 0; + + /** + * An array of the last texture handles that were bound to the WebGLRenderingContext + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentTextures + * @type {array} + * @since 3.0.0 + */ + this.currentTextures = new Array(16); + + /** + * Current framebuffer in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentFramebuffer + * @type {WebGLFramebuffer} + * @default null + * @since 3.0.0 + */ + this.currentFramebuffer = null; + + /** + * Current WebGLPipeline in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentPipeline + * @type {Phaser.Renderer.WebGL.WebGLPipeline} + * @default null + * @since 3.0.0 + */ + this.currentPipeline = null; + + /** + * Current WebGLProgram in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentProgram + * @type {WebGLProgram} + * @default null + * @since 3.0.0 + */ + this.currentProgram = null; + + /** + * Current WebGLBuffer (Vertex buffer) in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentVertexBuffer + * @type {WebGLBuffer} + * @default null + * @since 3.0.0 + */ + this.currentVertexBuffer = null; + + /** + * Current WebGLBuffer (Index buffer) in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentIndexBuffer + * @type {WebGLBuffer} + * @default null + * @since 3.0.0 + */ + this.currentIndexBuffer = null; + + /** + * Current blend mode in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentBlendMode + * @type {integer} + * @since 3.0.0 + */ + this.currentBlendMode = Infinity; + + /** + * Indicates if the the scissor state is enabled in WebGLRenderingContext + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentScissorEnabled + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.currentScissorEnabled = false; + + /** + * Stores the current scissor data + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentScissor + * @type {Uint32Array} + * @since 3.0.0 + */ + this.currentScissor = null; + + /** + * Stack of scissor data + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#scissorStack + * @type {Uint32Array} + * @since 3.0.0 + */ + this.scissorStack = []; + + /** + * The handler to invoke when the context is lost. + * This should not be changed and is set in the boot method. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#contextLostHandler + * @type {function} + * @since 3.19.0 + */ + this.contextLostHandler = NOOP; + + /** + * The handler to invoke when the context is restored. + * This should not be changed and is set in the boot method. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#contextRestoredHandler + * @type {function} + * @since 3.19.0 + */ + this.contextRestoredHandler = NOOP; + + /** + * The underlying WebGL context of the renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#gl + * @type {WebGLRenderingContext} + * @default null + * @since 3.0.0 + */ + this.gl = null; + + /** + * Array of strings that indicate which WebGL extensions are supported by the browser + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#supportedExtensions + * @type {object} + * @default null + * @since 3.0.0 + */ + this.supportedExtensions = null; + + /** + * Extensions loaded into the current context + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#extensions + * @type {object} + * @default {} + * @since 3.0.0 + */ + this.extensions = {}; + + /** + * Stores the current WebGL component formats for further use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#glFormats + * @type {array} + * @default [] + * @since 3.2.0 + */ + this.glFormats = []; + + /** + * Stores the supported WebGL texture compression formats. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#compression + * @type {array} + * @since 3.8.0 + */ + this.compression = { + ETC1: false, + PVRTC: false, + S3TC: false + }; + + /** + * Cached drawing buffer height to reduce gl calls. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#drawingBufferHeight + * @type {number} + * @readonly + * @since 3.11.0 + */ + this.drawingBufferHeight = 0; + + /** + * A blank 32x32 transparent texture, as used by the Graphics system where needed. + * This is set in the `boot` method. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#blankTexture + * @type {WebGLTexture} + * @readonly + * @since 3.12.0 + */ + this.blankTexture = null; + + /** + * A default Camera used in calls when no other camera has been provided. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#defaultCamera + * @type {Phaser.Cameras.Scene2D.BaseCamera} + * @since 3.12.0 + */ + this.defaultCamera = new BaseCamera(0, 0, 0, 0); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix4 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix4 = new TransformMatrix(); + + /** + * The total number of masks currently stacked. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#maskCount + * @type {integer} + * @since 3.17.0 + */ + this.maskCount = 0; + + /** + * The mask stack. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#maskStack + * @type {Phaser.Display.Masks.GeometryMask[]} + * @since 3.17.0 + */ + this.maskStack = []; + + /** + * Internal property that tracks the currently set mask. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentMask + * @type {any} + * @since 3.17.0 + */ + this.currentMask = { mask: null, camera: null }; + + /** + * Internal property that tracks the currently set camera mask. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentCameraMask + * @type {any} + * @since 3.17.0 + */ + this.currentCameraMask = { mask: null, camera: null }; + + /** + * Internal gl function mapping for uniform look-up. + * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#glFuncMap + * @type {any} + * @since 3.17.0 + */ + this.glFuncMap = null; + + /** + * The `type` of the Game Object being currently rendered. + * This can be used by advanced render functions for batching look-ahead. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentType + * @type {string} + * @since 3.19.0 + */ + this.currentType = ''; + + /** + * Is the `type` of the Game Object being currently rendered different than the + * type of the object before it in the display list? I.e. it's a 'new' type. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#newType + * @type {boolean} + * @since 3.19.0 + */ + this.newType = false; + + /** + * Does the `type` of the next Game Object in the display list match that + * of the object being currently rendered? + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#nextTypeMatch + * @type {boolean} + * @since 3.19.0 + */ + this.nextTypeMatch = false; + + /** + * The mipmap magFilter to be used when creating textures. + * + * You can specify this as a string in the game config, i.e.: + * + * `renderer: { 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 + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#mipmapFilter + * @type {GLenum} + * @since 3.21.0 + */ + this.mipmapFilter = null; + + this.init(this.config); + }, + + /** + * Creates a new WebGLRenderingContext and initializes all internal state. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#init + * @since 3.0.0 + * + * @param {object} config - The configuration object for the renderer. + * + * @return {this} This WebGLRenderer instance. + */ + init: function (config) + { + var gl; + var game = this.game; + var canvas = this.canvas; + var clearColor = config.backgroundColor; + + // Did they provide their own context? + if (game.config.context) + { + gl = game.config.context; + } + else + { + gl = canvas.getContext('webgl', config.contextCreation) || canvas.getContext('experimental-webgl', config.contextCreation); + } + + if (!gl || gl.isContextLost()) + { + this.contextLost = true; + + throw new Error('WebGL unsupported'); + } + + this.gl = gl; + + var _this = this; + + this.contextLostHandler = function (event) + { + _this.contextLost = true; + + _this.game.events.emit(GameEvents.CONTEXT_LOST, _this); + + event.preventDefault(); + }; + + this.contextRestoredHandler = function () + { + _this.contextLost = false; + + _this.init(_this.config); + + _this.game.events.emit(GameEvents.CONTEXT_RESTORED, _this); + }; + + canvas.addEventListener('webglcontextlost', this.contextLostHandler, false); + canvas.addEventListener('webglcontextrestored', this.contextRestoredHandler, false); + + // Set it back into the Game, so developers can access it from there too + game.context = gl; + + for (var i = 0; i <= 27; i++) + { + this.blendModes.push({ func: [ gl.ONE, gl.ONE_MINUS_SRC_ALPHA ], equation: gl.FUNC_ADD }); + } + + // ADD + this.blendModes[1].func = [ gl.ONE, gl.DST_ALPHA ]; + + // MULTIPLY + this.blendModes[2].func = [ gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA ]; + + // SCREEN + this.blendModes[3].func = [ gl.ONE, gl.ONE_MINUS_SRC_COLOR ]; + + // ERASE + this.blendModes[17] = { func: [ gl.ZERO, gl.ONE_MINUS_SRC_ALPHA ], equation: gl.FUNC_REVERSE_SUBTRACT }; + + this.glFormats[0] = gl.BYTE; + this.glFormats[1] = gl.SHORT; + this.glFormats[2] = gl.UNSIGNED_BYTE; + this.glFormats[3] = gl.UNSIGNED_SHORT; + this.glFormats[4] = gl.FLOAT; + + // Set the gl function map + this.glFuncMap = { + + mat2: { func: gl.uniformMatrix2fv, length: 1, matrix: true }, + mat3: { func: gl.uniformMatrix3fv, length: 1, matrix: true }, + mat4: { func: gl.uniformMatrix4fv, length: 1, matrix: true }, + + '1f': { func: gl.uniform1f, length: 1 }, + '1fv': { func: gl.uniform1fv, length: 1 }, + '1i': { func: gl.uniform1i, length: 1 }, + '1iv': { func: gl.uniform1iv, length: 1 }, + + '2f': { func: gl.uniform2f, length: 2 }, + '2fv': { func: gl.uniform2fv, length: 1 }, + '2i': { func: gl.uniform2i, length: 2 }, + '2iv': { func: gl.uniform2iv, length: 1 }, + + '3f': { func: gl.uniform3f, length: 3 }, + '3fv': { func: gl.uniform3fv, length: 1 }, + '3i': { func: gl.uniform3i, length: 3 }, + '3iv': { func: gl.uniform3iv, length: 1 }, + + '4f': { func: gl.uniform4f, length: 4 }, + '4fv': { func: gl.uniform4fv, length: 1 }, + '4i': { func: gl.uniform4i, length: 4 }, + '4iv': { func: gl.uniform4iv, length: 1 } + + }; + + // Load supported extensions + var exts = gl.getSupportedExtensions(); + + if (!config.maxTextures) + { + config.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + } + + if (!config.maxTextureSize) + { + config.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + } + + var extString = 'WEBGL_compressed_texture_'; + var wkExtString = 'WEBKIT_' + extString; + + this.compression.ETC1 = gl.getExtension(extString + 'etc1') || gl.getExtension(wkExtString + 'etc1'); + this.compression.PVRTC = gl.getExtension(extString + 'pvrtc') || gl.getExtension(wkExtString + 'pvrtc'); + this.compression.S3TC = gl.getExtension(extString + 's3tc') || gl.getExtension(wkExtString + 's3tc'); + + this.supportedExtensions = exts; + + // Setup initial WebGL state + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + + gl.enable(gl.BLEND); + + gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, clearColor.alphaGL); + + // Mipmaps + this.mipmapFilter = gl[config.mipmapFilter]; + + // Initialize all textures to null + for (var index = 0; index < this.currentTextures.length; ++index) + { + this.currentTextures[index] = null; + } + + // Clear previous pipelines and reload default ones + this.pipelines = {}; + + this.addPipeline('TextureTintPipeline', new TextureTintPipeline({ game: game, renderer: this })); + this.addPipeline('BitmapMaskPipeline', new BitmapMaskPipeline({ game: game, renderer: this })); + this.addPipeline('Light2D', new ForwardDiffuseLightPipeline({ game: game, renderer: this, maxLights: config.maxLights })); + + this.setBlendMode(CONST.BlendModes.NORMAL); + + game.textures.once(TextureEvents.READY, this.boot, this); + + return this; + }, + + /** + * Internal boot handler. Calls 'boot' on each pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#boot + * @private + * @since 3.11.0 + */ + boot: function () + { + for (var pipelineName in this.pipelines) + { + this.pipelines[pipelineName].boot(); + } + + var blank = this.game.textures.getFrame('__DEFAULT'); + + this.pipelines.TextureTintPipeline.currentFrame = blank; + + this.blankTexture = blank; + + var gl = this.gl; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + gl.enable(gl.SCISSOR_TEST); + + this.setPipeline(this.pipelines.TextureTintPipeline); + + this.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); + + var baseSize = this.game.scale.baseSize; + + this.resize(baseSize.width, baseSize.height, this.game.scale.resolution); + }, + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#onResize + * @since 3.16.0 + * + * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. + * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + * @param {Phaser.Structs.Size} displaySize - The display Size object. The size of the canvas style width / height attributes. + * @param {number} [resolution] - The Scale Manager resolution setting. + */ + onResize: function (gameSize, baseSize, displaySize, resolution) + { + // Has the underlying canvas size changed? + if (baseSize.width !== this.width || baseSize.height !== this.height || resolution !== this.resolution) + { + this.resize(baseSize.width, baseSize.height, resolution); + } + }, + + /** + * Resizes the drawing buffer to match that required by the Scale Manager. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#resize + * @since 3.0.0 + * + * @param {number} [width] - The new width of the renderer. + * @param {number} [height] - The new height of the renderer. + * @param {number} [resolution] - The new resolution of the renderer. + * + * @return {this} This WebGLRenderer instance. + */ + resize: function (width, height, resolution) + { + var gl = this.gl; + var pipelines = this.pipelines; + + this.width = width; + this.height = height; + this.resolution = resolution; + + gl.viewport(0, 0, width, height); + + // Update all registered pipelines + for (var pipelineName in pipelines) + { + pipelines[pipelineName].resize(width, height, resolution); + } + + this.drawingBufferHeight = gl.drawingBufferHeight; + + gl.scissor(0, (gl.drawingBufferHeight - height), width, height); + + this.defaultCamera.setSize(width, height); + + return this; + }, + + /** + * Checks if a WebGL extension is supported + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#hasExtension + * @since 3.0.0 + * + * @param {string} extensionName - Name of the WebGL extension + * + * @return {boolean} `true` if the extension is supported, otherwise `false`. + */ + hasExtension: function (extensionName) + { + return this.supportedExtensions ? this.supportedExtensions.indexOf(extensionName) : false; + }, + + /** + * Loads a WebGL extension + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getExtension + * @since 3.0.0 + * + * @param {string} extensionName - The name of the extension to load. + * + * @return {object} WebGL extension if the extension is supported + */ + getExtension: function (extensionName) + { + if (!this.hasExtension(extensionName)) { return null; } + + if (!(extensionName in this.extensions)) + { + this.extensions[extensionName] = this.gl.getExtension(extensionName); + } + + return this.extensions[extensionName]; + }, + + /** + * Flushes the current pipeline if the pipeline is bound + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#flush + * @since 3.0.0 + */ + flush: function () + { + if (this.currentPipeline) + { + this.currentPipeline.flush(); + } + }, + + /** + * Checks if a pipeline is present in the current WebGLRenderer + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#hasPipeline + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline. + * + * @return {boolean} `true` if the given pipeline is loaded, otherwise `false`. + */ + hasPipeline: function (pipelineName) + { + return (pipelineName in this.pipelines); + }, + + /** + * Returns the pipeline by name if the pipeline exists + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getPipeline + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline. + * + * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline instance, or `null` if not found. + */ + getPipeline: function (pipelineName) + { + return (this.hasPipeline(pipelineName)) ? this.pipelines[pipelineName] : null; + }, + + /** + * Removes a pipeline by name. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#removePipeline + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline to be removed. + * + * @return {this} This WebGLRenderer instance. + */ + removePipeline: function (pipelineName) + { + delete this.pipelines[pipelineName]; + + return this; + }, + + /** + * Adds a pipeline instance into the collection of pipelines + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#addPipeline + * @since 3.0.0 + * + * @param {string} pipelineName - A unique string-based key for the pipeline. + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - A pipeline instance which must extend WebGLPipeline. + * + * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline instance that was passed. + */ + addPipeline: function (pipelineName, pipelineInstance) + { + if (!this.hasPipeline(pipelineName)) + { + this.pipelines[pipelineName] = pipelineInstance; + } + else + { + console.warn('Pipeline exists: ' + pipelineName); + } + + pipelineInstance.name = pipelineName; + + this.pipelines[pipelineName].resize(this.width, this.height, this.config.resolution); + + return pipelineInstance; + }, + + /** + * Pushes a new scissor state. This is used to set nested scissor states. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#pushScissor + * @since 3.0.0 + * + * @param {integer} x - The x position of the scissor. + * @param {integer} y - The y position of the scissor. + * @param {integer} width - The width of the scissor. + * @param {integer} height - The height of the scissor. + * @param {integer} [drawingBufferHeight] - Optional drawingBufferHeight override value. + * + * @return {integer[]} An array containing the scissor values. + */ + pushScissor: function (x, y, width, height, drawingBufferHeight) + { + if (drawingBufferHeight === undefined) { drawingBufferHeight = this.drawingBufferHeight; } + + var scissorStack = this.scissorStack; + + var scissor = [ x, y, width, height ]; + + scissorStack.push(scissor); + + this.setScissor(x, y, width, height, drawingBufferHeight); + + this.currentScissor = scissor; + + return scissor; + }, + + /** + * Sets the current scissor state. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setScissor + * @since 3.0.0 + * + * @param {integer} x - The x position of the scissor. + * @param {integer} y - The y position of the scissor. + * @param {integer} width - The width of the scissor. + * @param {integer} height - The height of the scissor. + * @param {integer} [drawingBufferHeight] - Optional drawingBufferHeight override value. + */ + setScissor: function (x, y, width, height, drawingBufferHeight) + { + if (drawingBufferHeight === undefined) { drawingBufferHeight = this.drawingBufferHeight; } + + var gl = this.gl; + + var current = this.currentScissor; + + var setScissor = (width > 0 && height > 0); + + if (current && setScissor) + { + var cx = current[0]; + var cy = current[1]; + var cw = current[2]; + var ch = current[3]; + + setScissor = (cx !== x || cy !== y || cw !== width || ch !== height); + } + + if (setScissor) + { + this.flush(); + + // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/scissor + gl.scissor(x, (drawingBufferHeight - y - height), width, height); + } + }, + + /** + * Pops the last scissor state and sets it. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#popScissor + * @since 3.0.0 + */ + popScissor: function () + { + var scissorStack = this.scissorStack; + + // Remove the current scissor + scissorStack.pop(); + + // Reset the previous scissor + var scissor = scissorStack[scissorStack.length - 1]; + + if (scissor) + { + this.setScissor(scissor[0], scissor[1], scissor[2], scissor[3]); + } + + this.currentScissor = scissor; + }, + + /** + * Binds a WebGLPipeline and sets it as the current pipeline to be used. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setPipeline + * @since 3.0.0 + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - The pipeline instance to be activated. + * @param {Phaser.GameObjects.GameObject} [gameObject] - The Game Object that invoked this pipeline, if any. + * + * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline that was activated. + */ + setPipeline: function (pipelineInstance, gameObject) + { + if (this.currentPipeline !== pipelineInstance || + this.currentPipeline.vertexBuffer !== this.currentVertexBuffer || + this.currentPipeline.program !== this.currentProgram) + { + this.flush(); + this.currentPipeline = pipelineInstance; + this.currentPipeline.bind(); + } + + this.currentPipeline.onBind(gameObject); + + return this.currentPipeline; + }, + + /** + * Is there an active stencil mask? + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#hasActiveStencilMask + * @since 3.17.0 + * + * @return {boolean} `true` if there is an active stencil mask, otherwise `false`. + */ + hasActiveStencilMask: function () + { + var mask = this.currentMask.mask; + var camMask = this.currentCameraMask.mask; + + return ((mask && mask.isStencil) || (camMask && camMask.isStencil)); + }, + + /** + * Use this to reset the gl context to the state that Phaser requires to continue rendering. + * Calling this will: + * + * * Disable `DEPTH_TEST`, `CULL_FACE` and `STENCIL_TEST`. + * * Clear the depth buffer and stencil buffers. + * * Reset the viewport size. + * * Reset the blend mode. + * * Bind a blank texture as the active texture on texture unit zero. + * * Rebinds the given pipeline instance. + * + * You should call this having previously called `clearPipeline` and then wishing to return + * control to Phaser again. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#rebindPipeline + * @since 3.16.0 + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - The pipeline instance to be activated. + */ + rebindPipeline: function (pipelineInstance) + { + var gl = this.gl; + + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + + if (this.hasActiveStencilMask()) + { + gl.clear(gl.DEPTH_BUFFER_BIT); + } + else + { + // If there wasn't a stencil mask set before this call, we can disable it safely + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + } + + gl.viewport(0, 0, this.width, this.height); + + this.setBlendMode(0, true); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, this.blankTexture.glTexture); + + this.currentActiveTextureUnit = 0; + this.currentTextures[0] = this.blankTexture.glTexture; + + this.currentPipeline = pipelineInstance; + this.currentPipeline.bind(); + this.currentPipeline.onBind(); + }, + + /** + * Flushes the current WebGLPipeline being used and then clears it, along with the + * the current shader program and vertex buffer. Then resets the blend mode to NORMAL. + * Call this before jumping to your own gl context handler, and then call `rebindPipeline` when + * you wish to return control to Phaser again. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#clearPipeline + * @since 3.16.0 + */ + clearPipeline: function () + { + this.flush(); + + this.currentPipeline = null; + this.currentProgram = null; + this.currentVertexBuffer = null; + this.currentIndexBuffer = null; + + this.setBlendMode(0, true); + }, + + /** + * Sets the blend mode to the value given. + * + * If the current blend mode is different from the one given, the pipeline is flushed and the new + * blend mode is enabled. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setBlendMode + * @since 3.0.0 + * + * @param {integer} blendModeId - The blend mode to be set. Can be a `BlendModes` const or an integer value. + * @param {boolean} [force=false] - Force the blend mode to be set, regardless of the currently set blend mode. + * + * @return {boolean} `true` if the blend mode was changed as a result of this call, forcing a flush, otherwise `false`. + */ + setBlendMode: function (blendModeId, force) + { + if (force === undefined) { force = false; } + + var gl = this.gl; + var blendMode = this.blendModes[blendModeId]; + + if (force || (blendModeId !== CONST.BlendModes.SKIP_CHECK && this.currentBlendMode !== blendModeId)) + { + this.flush(); + + gl.enable(gl.BLEND); + gl.blendEquation(blendMode.equation); + + if (blendMode.func.length > 2) + { + gl.blendFuncSeparate(blendMode.func[0], blendMode.func[1], blendMode.func[2], blendMode.func[3]); + } + else + { + gl.blendFunc(blendMode.func[0], blendMode.func[1]); + } + + this.currentBlendMode = blendModeId; + + return true; + } + + return false; + }, + + /** + * 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 {integer} The index of the new blend mode, used for referencing it in the future. + */ + addBlendMode: function (func, equation) + { + var index = this.blendModes.push({ func: func, equation: equation }); + + return index - 1; + }, + + /** + * Updates the function bound to a given custom blend mode. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#updateBlendMode + * @since 3.0.0 + * + * @param {integer} index - The index of the custom blend mode. + * @param {function} func - The function to use for the blend mode. + * @param {function} equation - The equation to use for the blend mode. + * + * @return {this} This WebGLRenderer instance. + */ + updateBlendMode: function (index, func, equation) + { + if (this.blendModes[index]) + { + this.blendModes[index].func = func; + + if (equation) + { + this.blendModes[index].equation = equation; + } + } + + return this; + }, + + /** + * Removes a custom blend mode from the renderer. + * Any Game Objects still using this blend mode will error, so be sure to clear them first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#removeBlendMode + * @since 3.0.0 + * + * @param {integer} index - The index of the custom blend mode to be removed. + * + * @return {this} This WebGLRenderer instance. + */ + removeBlendMode: function (index) + { + if (index > 17 && this.blendModes[index]) + { + this.blendModes.splice(index, 1); + } + + return this; + }, + + /** + * Sets the current active texture for texture unit zero to be a blank texture. + * This only happens if there isn't a texture already in use by texture unit zero. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setBlankTexture + * @private + * @since 3.12.0 + * + * @param {boolean} [force=false] - Force a blank texture set, regardless of what's already bound? + */ + setBlankTexture: function (force) + { + if (force === undefined) { force = false; } + + if (force || this.currentActiveTextureUnit !== 0 || !this.currentTextures[0]) + { + this.setTexture2D(this.blankTexture.glTexture, 0); + } + }, + + /** + * Binds a texture at a texture unit. If a texture is already + * bound to that unit it will force a flush on the current pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setTexture2D + * @since 3.0.0 + * + * @param {WebGLTexture} texture - The WebGL texture that needs to be bound. + * @param {integer} textureUnit - The texture unit to which the texture will be bound. + * @param {boolean} [flush=true] - Will the current pipeline be flushed if this is a new texture, or not? + * + * @return {this} This WebGLRenderer instance. + */ + setTexture2D: function (texture, textureUnit, flush) + { + if (flush === undefined) { flush = true; } + + var gl = this.gl; + + if (texture !== this.currentTextures[textureUnit]) + { + if (flush) + { + this.flush(); + } + + if (this.currentActiveTextureUnit !== textureUnit) + { + gl.activeTexture(gl.TEXTURE0 + textureUnit); + + this.currentActiveTextureUnit = textureUnit; + } + + gl.bindTexture(gl.TEXTURE_2D, texture); + + this.currentTextures[textureUnit] = texture; + } + + return this; + }, + + /** + * Binds a framebuffer. If there was another framebuffer already bound it will force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFramebuffer + * @since 3.0.0 + * + * @param {WebGLFramebuffer} framebuffer - The framebuffer that needs to be bound. + * @param {boolean} [updateScissor=false] - If a framebuffer is given, set the gl scissor to match the frame buffer size? Or, if `null` given, pop the scissor from the stack. + * + * @return {this} This WebGLRenderer instance. + */ + setFramebuffer: function (framebuffer, updateScissor) + { + if (updateScissor === undefined) { updateScissor = false; } + + var gl = this.gl; + + var width = this.width; + var height = this.height; + + if (framebuffer !== this.currentFramebuffer) + { + if (framebuffer && framebuffer.renderTexture) + { + width = framebuffer.renderTexture.width; + height = framebuffer.renderTexture.height; + } + else + { + this.flush(); + } + + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + + gl.viewport(0, 0, width, height); + + if (updateScissor) + { + if (framebuffer) + { + this.drawingBufferHeight = height; + + this.pushScissor(0, 0, width, height); + } + else + { + this.drawingBufferHeight = this.height; + + this.popScissor(); + } + } + + this.currentFramebuffer = framebuffer; + } + + return this; + }, + + /** + * Binds a program. If there was another program already bound it will force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setProgram + * @since 3.0.0 + * + * @param {WebGLProgram} program - The program that needs to be bound. + * + * @return {this} This WebGLRenderer instance. + */ + setProgram: function (program) + { + var gl = this.gl; + + if (program !== this.currentProgram) + { + this.flush(); + + gl.useProgram(program); + + this.currentProgram = program; + } + + return this; + }, + + /** + * Bounds a vertex buffer. If there is a vertex buffer already bound it'll force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setVertexBuffer + * @since 3.0.0 + * + * @param {WebGLBuffer} vertexBuffer - The buffer that needs to be bound. + * + * @return {this} This WebGLRenderer instance. + */ + setVertexBuffer: function (vertexBuffer) + { + var gl = this.gl; + + if (vertexBuffer !== this.currentVertexBuffer) + { + this.flush(); + + gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); + + this.currentVertexBuffer = vertexBuffer; + } + + return this; + }, + + /** + * Bounds a index buffer. If there is a index buffer already bound it'll force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setIndexBuffer + * @since 3.0.0 + * + * @param {WebGLBuffer} indexBuffer - The buffer the needs to be bound. + * + * @return {this} This WebGLRenderer instance. + */ + setIndexBuffer: function (indexBuffer) + { + var gl = this.gl; + + if (indexBuffer !== this.currentIndexBuffer) + { + this.flush(); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); + + this.currentIndexBuffer = indexBuffer; + } + + return this; + }, + + /** + * Creates a texture from an image source. If the source is not valid it creates an empty texture. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createTextureFromSource + * @since 3.0.0 + * + * @param {object} source - The source of the texture. + * @param {integer} width - The width of the texture. + * @param {integer} height - The height of the texture. + * @param {integer} scaleMode - The scale mode to be used by the texture. + * + * @return {?WebGLTexture} The WebGL Texture that was created, or `null` if it couldn't be created. + */ + createTextureFromSource: function (source, width, height, scaleMode) + { + var gl = this.gl; + var minFilter = gl.NEAREST; + var magFilter = gl.NEAREST; + var wrap = gl.CLAMP_TO_EDGE; + var texture = null; + + width = source ? source.width : width; + height = source ? source.height : height; + + var pow = IsSizePowerOfTwo(width, height); + + if (pow) + { + wrap = gl.REPEAT; + } + + if (scaleMode === CONST.ScaleModes.LINEAR && this.config.antialias) + { + minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; + magFilter = gl.LINEAR; + } + + if (!source && typeof width === 'number' && typeof height === 'number') + { + texture = this.createTexture2D(0, minFilter, magFilter, wrap, wrap, gl.RGBA, null, width, height); + } + else + { + texture = this.createTexture2D(0, minFilter, magFilter, wrap, wrap, gl.RGBA, source); + } + + return texture; + }, + + /** + * A wrapper for creating a WebGLTexture. If no pixel data is passed it will create an empty texture. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createTexture2D + * @since 3.0.0 + * + * @param {integer} mipLevel - Mip level of the texture. + * @param {integer} minFilter - Filtering of the texture. + * @param {integer} magFilter - Filtering of the texture. + * @param {integer} wrapT - Wrapping mode of the texture. + * @param {integer} wrapS - Wrapping mode of the texture. + * @param {integer} format - Which format does the texture use. + * @param {?object} pixels - pixel data. + * @param {integer} width - Width of the texture in pixels. + * @param {integer} height - Height of the texture in pixels. + * @param {boolean} [pma=true] - Does the texture have premultiplied alpha? + * @param {boolean} [forceSize=false] - If `true` it will use the width and height passed to this method, regardless of the pixels dimension. + * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + * + * @return {WebGLTexture} The WebGLTexture that was created. + */ + createTexture2D: function (mipLevel, minFilter, magFilter, wrapT, wrapS, format, pixels, width, height, pma, forceSize, flipY) + { + pma = (pma === undefined || pma === null) ? true : pma; + if (forceSize === undefined) { forceSize = false; } + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + var texture = gl.createTexture(); + + this.setTexture2D(texture, 0); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, pma); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + + if (pixels === null || pixels === undefined) + { + gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, width, height, 0, format, gl.UNSIGNED_BYTE, null); + } + else + { + if (!forceSize) + { + width = pixels.width; + height = pixels.height; + } + + gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, format, gl.UNSIGNED_BYTE, pixels); + } + + if (IsSizePowerOfTwo(width, height)) + { + gl.generateMipmap(gl.TEXTURE_2D); + } + + this.setTexture2D(null, 0); + + texture.isAlphaPremultiplied = pma; + texture.isRenderTexture = false; + texture.width = width; + texture.height = height; + + this.nativeTextures.push(texture); + + return texture; + }, + + /** + * Wrapper for creating WebGLFramebuffer. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createFramebuffer + * @since 3.0.0 + * + * @param {integer} width - Width in pixels of the framebuffer + * @param {integer} height - Height in pixels of the framebuffer + * @param {WebGLTexture} renderTexture - The color texture to where the color pixels are written + * @param {boolean} addDepthStencilBuffer - Indicates if the current framebuffer support depth and stencil buffers + * + * @return {WebGLFramebuffer} Raw WebGLFramebuffer + */ + createFramebuffer: function (width, height, renderTexture, addDepthStencilBuffer) + { + var gl = this.gl; + var framebuffer = gl.createFramebuffer(); + var complete = 0; + + this.setFramebuffer(framebuffer); + + if (addDepthStencilBuffer) + { + var depthStencilBuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); + } + + renderTexture.isRenderTexture = true; + renderTexture.isAlphaPremultiplied = false; + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, renderTexture, 0); + + complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + + if (complete !== gl.FRAMEBUFFER_COMPLETE) + { + var errors = { + 36054: 'Incomplete Attachment', + 36055: 'Missing Attachment', + 36057: 'Incomplete Dimensions', + 36061: 'Framebuffer Unsupported' + }; + + throw new Error('Framebuffer incomplete. Framebuffer status: ' + errors[complete]); + } + + framebuffer.renderTexture = renderTexture; + + this.setFramebuffer(null); + + return framebuffer; + }, + + /** + * Wrapper for creating a WebGLProgram + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createProgram + * @since 3.0.0 + * + * @param {string} vertexShader - Source to the vertex shader + * @param {string} fragmentShader - Source to the fragment shader + * + * @return {WebGLProgram} Raw WebGLProgram + */ + createProgram: function (vertexShader, fragmentShader) + { + var gl = this.gl; + var program = gl.createProgram(); + var vs = gl.createShader(gl.VERTEX_SHADER); + var fs = gl.createShader(gl.FRAGMENT_SHADER); + + gl.shaderSource(vs, vertexShader); + gl.shaderSource(fs, fragmentShader); + gl.compileShader(vs); + gl.compileShader(fs); + + if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) + { + throw new Error('Failed to compile Vertex Shader:\n' + gl.getShaderInfoLog(vs)); + } + if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) + { + throw new Error('Failed to compile Fragment Shader:\n' + gl.getShaderInfoLog(fs)); + } + + gl.attachShader(program, vs); + gl.attachShader(program, fs); + gl.linkProgram(program); + + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + throw new Error('Failed to link program:\n' + gl.getProgramInfoLog(program)); + } + + return program; + }, + + /** + * Wrapper for creating a vertex buffer. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createVertexBuffer + * @since 3.0.0 + * + * @param {ArrayBuffer} initialDataOrSize - It's either ArrayBuffer or an integer indicating the size of the vbo + * @param {integer} bufferUsage - How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW + * + * @return {WebGLBuffer} Raw vertex buffer + */ + createVertexBuffer: function (initialDataOrSize, bufferUsage) + { + var gl = this.gl; + var vertexBuffer = gl.createBuffer(); + + this.setVertexBuffer(vertexBuffer); + + gl.bufferData(gl.ARRAY_BUFFER, initialDataOrSize, bufferUsage); + + this.setVertexBuffer(null); + + return vertexBuffer; + }, + + /** + * Wrapper for creating a vertex buffer. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createIndexBuffer + * @since 3.0.0 + * + * @param {ArrayBuffer} initialDataOrSize - Either ArrayBuffer or an integer indicating the size of the vbo. + * @param {integer} bufferUsage - How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW. + * + * @return {WebGLBuffer} Raw index buffer + */ + createIndexBuffer: function (initialDataOrSize, bufferUsage) + { + var gl = this.gl; + var indexBuffer = gl.createBuffer(); + + this.setIndexBuffer(indexBuffer); + + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, initialDataOrSize, bufferUsage); + + this.setIndexBuffer(null); + + return indexBuffer; + }, + + /** + * Removes the given texture from the nativeTextures array and then deletes it from the GPU. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteTexture + * @since 3.0.0 + * + * @param {WebGLTexture} texture - The WebGL Texture to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteTexture: function (texture) + { + var index = this.nativeTextures.indexOf(texture); + + if (index !== -1) + { + SpliceOne(this.nativeTextures, index); + } + + this.gl.deleteTexture(texture); + + if (this.currentTextures[0] === texture && !this.game.pendingDestroy) + { + // texture we just deleted is in use, so bind a blank texture + this.setBlankTexture(true); + } + + return this; + }, + + /** + * Deletes a WebGLFramebuffer from the GL instance. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteFramebuffer + * @since 3.0.0 + * + * @param {WebGLFramebuffer} framebuffer - The Framebuffer to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteFramebuffer: function (framebuffer) + { + this.gl.deleteFramebuffer(framebuffer); + + return this; + }, + + /** + * Deletes a WebGLProgram from the GL instance. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteProgram + * @since 3.0.0 + * + * @param {WebGLProgram} program - The shader program to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteProgram: function (program) + { + this.gl.deleteProgram(program); + + return this; + }, + + /** + * Deletes a WebGLBuffer from the GL instance. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteBuffer + * @since 3.0.0 + * + * @param {WebGLBuffer} vertexBuffer - The WebGLBuffer to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteBuffer: function (buffer) + { + this.gl.deleteBuffer(buffer); + + return this; + }, + + /** + * Controls the pre-render operations for the given camera. + * Handles any clipping needed by the camera and renders the background color if a color is visible. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#preRenderCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to pre-render. + */ + preRenderCamera: function (camera) + { + var cx = camera._cx; + var cy = camera._cy; + var cw = camera._cw; + var ch = camera._ch; + + var TextureTintPipeline = this.pipelines.TextureTintPipeline; + + var color = camera.backgroundColor; + + if (camera.renderToTexture) + { + this.flush(); + + this.pushScissor(cx, cy, cw, -ch); + + this.setFramebuffer(camera.framebuffer); + + var gl = this.gl; + + gl.clearColor(0, 0, 0, 0); + + gl.clear(gl.COLOR_BUFFER_BIT); + + TextureTintPipeline.projOrtho(cx, cw + cx, cy, ch + cy, -1000, 1000); + + if (camera.mask) + { + this.currentCameraMask.mask = camera.mask; + this.currentCameraMask.camera = camera._maskCamera; + + camera.mask.preRenderWebGL(this, camera, camera._maskCamera); + } + + if (color.alphaGL > 0) + { + TextureTintPipeline.drawFillRect( + cx, cy, cw + cx, ch + cy, + Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), + color.alphaGL + ); + } + + camera.emit(CameraEvents.PRE_RENDER, camera); + } + else + { + this.pushScissor(cx, cy, cw, ch); + + if (camera.mask) + { + this.currentCameraMask.mask = camera.mask; + this.currentCameraMask.camera = camera._maskCamera; + + camera.mask.preRenderWebGL(this, camera, camera._maskCamera); + } + + if (color.alphaGL > 0) + { + TextureTintPipeline.drawFillRect( + cx, cy, cw , ch, + Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), + color.alphaGL + ); + } + } + }, + + getCurrentStencilMask: function () + { + var prev = null; + var stack = this.maskStack; + var cameraMask = this.currentCameraMask; + + if (stack.length > 0) + { + prev = stack[stack.length - 1]; + } + else if (cameraMask.mask && cameraMask.mask.isStencil) + { + prev = cameraMask; + } + + return prev; + }, + + /** + * Controls the post-render operations for the given camera. + * Renders the foreground camera effects like flash and fading. It resets the current scissor state. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#postRenderCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to post-render. + */ + postRenderCamera: function (camera) + { + var TextureTintPipeline = this.pipelines.TextureTintPipeline; + + camera.flashEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); + camera.fadeEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); + + camera.dirty = false; + + this.popScissor(); + + if (camera.renderToTexture) + { + TextureTintPipeline.flush(); + + this.setFramebuffer(null); + + camera.emit(CameraEvents.POST_RENDER, camera); + + TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); + + var getTint = Utils.getTintAppendFloatAlpha; + + var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; + + pipeline.batchTexture( + camera, + camera.glTexture, + camera.width, camera.height, + camera.x, camera.y, + camera.width, camera.height, + camera.zoom, camera.zoom, + camera.rotation, + camera.flipX, !camera.flipY, + 1, 1, + 0, 0, + 0, 0, camera.width, camera.height, + getTint(camera._tintTL, camera._alphaTL), + getTint(camera._tintTR, camera._alphaTR), + getTint(camera._tintBL, camera._alphaBL), + getTint(camera._tintBR, camera._alphaBR), + (camera._isTinted && camera.tintFill), + 0, 0, + this.defaultCamera, + null + ); + + // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it + this.setBlankTexture(true); + } + + if (camera.mask) + { + this.currentCameraMask.mask = null; + + camera.mask.postRenderWebGL(this, camera._maskCamera); + } + }, + + /** + * Clears the current vertex buffer and updates pipelines. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#preRender + * @since 3.0.0 + */ + preRender: function () + { + if (this.contextLost) { return; } + + var gl = this.gl; + var pipelines = this.pipelines; + + // Make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.config.clearBeforeRender) + { + var clearColor = this.config.backgroundColor; + + gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, clearColor.alphaGL); + + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + } + + gl.enable(gl.SCISSOR_TEST); + + for (var key in pipelines) + { + pipelines[key].onPreRender(); + } + + // TODO - Find a way to stop needing to create these arrays every frame + // and equally not need a huge array buffer created to hold them + + this.currentScissor = [ 0, 0, this.width, this.height ]; + this.scissorStack = [ this.currentScissor ]; + + if (this.game.scene.customViewports) + { + gl.scissor(0, (this.drawingBufferHeight - this.height), this.width, this.height); + } + + this.currentMask.mask = null; + this.currentCameraMask.mask = null; + this.maskStack.length = 0; + + this.setPipeline(this.pipelines.TextureTintPipeline); + }, + + /** + * The core render step for a Scene Camera. + * + * Iterates through the given Game Object's array and renders them with the given Camera. + * + * This is called by the `CameraManager.render` method. The Camera Manager instance belongs to a Scene, and is invoked + * by the Scene Systems.render method. + * + * This method is not called if `Camera.visible` is `false`, or `Camera.alpha` is zero. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#render + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to render. + * @param {Phaser.GameObjects.GameObject} children - The Game Object's within the Scene to be rendered. + * @param {number} interpolationPercentage - The interpolation percentage to apply. Currently un-used. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera to render with. + */ + render: function (scene, children, interpolationPercentage, camera) + { + if (this.contextLost) { return; } + + var list = children.list; + var childCount = list.length; + var pipelines = this.pipelines; + + for (var key in pipelines) + { + pipelines[key].onRender(scene, camera); + } + + // Apply scissor for cam region + render background color, if not transparent + this.preRenderCamera(camera); + + // Nothing to render, so bail out + if (childCount === 0) + { + this.setBlendMode(CONST.BlendModes.NORMAL); + + // Applies camera effects and pops the scissor, if set + this.postRenderCamera(camera); + + return; + } + + // Reset the current type + this.currentType = ''; + + var current = this.currentMask; + + for (var i = 0; i < childCount; i++) + { + var child = list[i]; + + if (!child.willRender(camera)) + { + continue; + } + + if (child.blendMode !== this.currentBlendMode) + { + this.setBlendMode(child.blendMode); + } + + var mask = child.mask; + + current = this.currentMask; + + if (current.mask && current.mask !== mask) + { + // Render out the previously set mask + current.mask.postRenderWebGL(this, current.camera); + } + + if (mask && current.mask !== mask) + { + mask.preRenderWebGL(this, child, camera); + } + + var type = child.type; + + if (type !== this.currentType) + { + this.newType = true; + this.currentType = type; + } + + this.nextTypeMatch = (i < childCount - 1) ? (list[i + 1].type === this.currentType) : false; + + child.renderWebGL(this, child, interpolationPercentage, camera); + + this.newType = false; + } + + current = this.currentMask; + + if (current.mask) + { + // Render out the previously set mask, if it was the last item in the display list + current.mask.postRenderWebGL(this, current.camera); + } + + this.setBlendMode(CONST.BlendModes.NORMAL); + + // Applies camera effects and pops the scissor, if set + this.postRenderCamera(camera); + }, + + /** + * The post-render step happens after all Cameras in all Scenes have been rendered. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#postRender + * @since 3.0.0 + */ + postRender: function () + { + if (this.contextLost) { return; } + + this.flush(); + + // Unbind custom framebuffer here + + var state = this.snapshotState; + + if (state.callback) + { + WebGLSnapshot(this.canvas, state); + + state.callback = null; + } + + var pipelines = this.pipelines; + + for (var key in pipelines) + { + pipelines[key].onPostRender(); + } + }, + + /** + * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. + * + * To capture a specific area see the `snapshotArea` 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#snapshot + * @since 3.0.0 + * + * @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. + */ + snapshot: function (callback, type, encoderOptions) + { + return this.snapshotArea(0, 0, this.gl.drawingBufferWidth, this.gl.drawingBufferHeight, callback, type, encoderOptions); + }, + + /** + * 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 {integer} x - The x coordinate to grab from. + * @param {integer} y - The y coordinate to grab from. + * @param {integer} width - The width of the area to grab. + * @param {integer} 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. + */ + snapshotArea: function (x, y, width, height, callback, type, encoderOptions) + { + var state = this.snapshotState; + + state.callback = callback; + state.type = type; + state.encoder = encoderOptions; + state.getPixel = false; + state.x = x; + state.y = y; + state.width = Math.min(width, this.gl.drawingBufferWidth); + state.height = Math.min(height, this.gl.drawingBufferHeight); + + return this; + }, + + /** + * 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 {integer} x - The x coordinate of the pixel to get. + * @param {integer} y - The y coordinate of the pixel to get. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. + * + * @return {this} This WebGL Renderer. + */ + snapshotPixel: function (x, y, callback) + { + this.snapshotArea(x, y, 1, 1, callback); + + this.snapshotState.getPixel = true; + + return this; + }, + + /** + * 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 {WebGLFramebuffer} framebuffer - The framebuffer to grab from. + * @param {integer} bufferWidth - The width of the framebuffer. + * @param {integer} 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 {integer} [x=0] - The x coordinate to grab from. + * @param {integer} [y=0] - The y coordinate to grab from. + * @param {integer} [width=bufferWidth] - The width of the area to grab. + * @param {integer} [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. + */ + snapshotFramebuffer: function (framebuffer, bufferWidth, bufferHeight, callback, getPixel, x, y, width, height, type, encoderOptions) + { + if (getPixel === undefined) { getPixel = false; } + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = bufferWidth; } + if (height === undefined) { height = bufferHeight; } + + var currentFramebuffer = this.currentFramebuffer; + + this.snapshotArea(x, y, width, height, callback, type, encoderOptions); + + var state = this.snapshotState; + + state.getPixel = getPixel; + + state.isFramebuffer = true; + state.bufferWidth = bufferWidth; + state.bufferHeight = bufferHeight; + + this.setFramebuffer(framebuffer); + + WebGLSnapshot(this.canvas, state); + + this.setFramebuffer(currentFramebuffer); + + state.callback = null; + state.isFramebuffer = false; + + return this; + }, + + /** + * 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 {WebGLTexture} [dstTexture] - The destination WebGL Texture to set. + * @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT` (such as for Text objects?) + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The newly created, or updated, WebGL Texture. + */ + canvasToTexture: function (srcCanvas, dstTexture, noRepeat, flipY) + { + if (noRepeat === undefined) { noRepeat = false; } + if (flipY === undefined) { flipY = false; } + + if (!dstTexture) + { + return this.createCanvasTexture(srcCanvas, noRepeat, flipY); + } + else + { + return this.updateCanvasTexture(srcCanvas, dstTexture, flipY); + } + }, + + /** + * 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=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The newly created WebGL Texture. + */ + createCanvasTexture: function (srcCanvas, noRepeat, flipY) + { + if (noRepeat === undefined) { noRepeat = false; } + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + var minFilter = gl.NEAREST; + var magFilter = gl.NEAREST; + + var width = srcCanvas.width; + var height = srcCanvas.height; + + var wrapping = gl.CLAMP_TO_EDGE; + + var pow = IsSizePowerOfTwo(width, height); + + if (!noRepeat && pow) + { + wrapping = gl.REPEAT; + } + + if (this.config.antialias) + { + minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; + magFilter = gl.LINEAR; + } + + return this.createTexture2D(0, minFilter, magFilter, wrapping, wrapping, gl.RGBA, srcCanvas, width, height, true, false, flipY); + }, + + /** + * 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 {WebGLTexture} dstTexture - The destination WebGL Texture to update. + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The updated WebGL Texture. + */ + updateCanvasTexture: function (srcCanvas, dstTexture, flipY) + { + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + + var width = srcCanvas.width; + var height = srcCanvas.height; + + if (width > 0 && height > 0) + { + this.setTexture2D(dstTexture, 0); + + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcCanvas); + + dstTexture.width = width; + dstTexture.height = height; + + this.setTexture2D(null, 0); + } + + return dstTexture; + }, + + /** + * 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=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The newly created WebGL Texture. + */ + createVideoTexture: function (srcVideo, noRepeat, flipY) + { + if (noRepeat === undefined) { noRepeat = false; } + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + var minFilter = gl.NEAREST; + var magFilter = gl.NEAREST; + + var width = srcVideo.videoWidth; + var height = srcVideo.videoHeight; + + var wrapping = gl.CLAMP_TO_EDGE; + + var pow = IsSizePowerOfTwo(width, height); + + if (!noRepeat && pow) + { + wrapping = gl.REPEAT; + } + + if (this.config.antialias) + { + minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; + magFilter = gl.LINEAR; + } + + return this.createTexture2D(0, minFilter, magFilter, wrapping, wrapping, gl.RGBA, srcVideo, width, height, true, true, flipY); + }, + + /** + * 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 {WebGLTexture} dstTexture - The destination WebGL Texture to update. + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The updated WebGL Texture. + */ + updateVideoTexture: function (srcVideo, dstTexture, flipY) + { + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + + var width = srcVideo.videoWidth; + var height = srcVideo.videoHeight; + + if (width > 0 && height > 0) + { + this.setTexture2D(dstTexture, 0); + + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcVideo); + + dstTexture.width = width; + dstTexture.height = height; + + this.setTexture2D(null, 0); + } + + return dstTexture; + }, + + /** + * Sets the minification and magnification filter for a texture. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setTextureFilter + * @since 3.0.0 + * + * @param {integer} texture - The texture to set the filter for. + * @param {integer} filter - The filter to set. 0 for linear filtering, 1 for nearest neighbor (blocky) filtering. + * + * @return {this} This WebGL Renderer instance. + */ + setTextureFilter: function (texture, filter) + { + var gl = this.gl; + var glFilter = [ gl.LINEAR, gl.NEAREST ][filter]; + + this.setTexture2D(texture, 0); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter); + + this.setTexture2D(null, 0); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - [description] + * + * @return {this} This WebGL Renderer instance. + */ + setFloat1: function (program, name, x) + { + this.setProgram(program); + + this.gl.uniform1f(this.gl.getUniformLocation(program, name), x); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - [description] + * @param {number} y - [description] + * + * @return {this} This WebGL Renderer instance. + */ + setFloat2: function (program, name, x, y) + { + this.setProgram(program); + + this.gl.uniform2f(this.gl.getUniformLocation(program, name), x, y); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} z - [description] + * + * @return {this} This WebGL Renderer instance. + */ + setFloat3: function (program, name, x, y, z) + { + this.setProgram(program); + + this.gl.uniform3f(this.gl.getUniformLocation(program, name), x, y, z); + + return this; + }, + + /** + * Sets uniform of a WebGLProgram + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - X component + * @param {number} y - Y component + * @param {number} z - Z component + * @param {number} w - W component + * + * @return {this} This WebGL Renderer instance. + */ + setFloat4: function (program, name, x, y, z, w) + { + this.setProgram(program); + + this.gl.uniform4f(this.gl.getUniformLocation(program, name), x, y, z, w); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat1v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform1fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat2v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform2fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat3v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform3fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + + setFloat4v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform4fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt1 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - [description] + * + * @return {this} This WebGL Renderer instance. + */ + setInt1: function (program, name, x) + { + this.setProgram(program); + + this.gl.uniform1i(this.gl.getUniformLocation(program, name), x); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt2 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component + * @param {integer} y - The new Y component + * + * @return {this} This WebGL Renderer instance. + */ + setInt2: function (program, name, x, y) + { + this.setProgram(program); + + this.gl.uniform2i(this.gl.getUniformLocation(program, name), x, y); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt3 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component + * @param {integer} y - The new Y component + * @param {integer} z - The new Z component + * + * @return {this} This WebGL Renderer instance. + */ + setInt3: function (program, name, x, y, z) + { + this.setProgram(program); + + this.gl.uniform3i(this.gl.getUniformLocation(program, name), x, y, z); + + return this; + }, + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt4 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - X component + * @param {integer} y - Y component + * @param {integer} z - Z component + * @param {integer} w - W component + * + * @return {this} This WebGL Renderer instance. + */ + setInt4: function (program, name, x, y, z, w) + { + this.setProgram(program); + + this.gl.uniform4i(this.gl.getUniformLocation(program, name), x, y, z, w); + + return this; + }, + + /** + * Sets the value of a 2x2 matrix uniform variable in the given WebGLProgram. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix2 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. + * @param {Float32Array} matrix - The new matrix value. + * + * @return {this} This WebGL Renderer instance. + */ + setMatrix2: function (program, name, transpose, matrix) + { + this.setProgram(program); + + this.gl.uniformMatrix2fv(this.gl.getUniformLocation(program, name), transpose, matrix); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix3 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - [description] + * @param {Float32Array} matrix - [description] + * + * @return {this} This WebGL Renderer instance. + */ + setMatrix3: function (program, name, transpose, matrix) + { + this.setProgram(program); + + this.gl.uniformMatrix3fv(this.gl.getUniformLocation(program, name), transpose, matrix); + + return this; + }, + + /** + * Sets uniform of a WebGLProgram + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix4 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Is the matrix transposed + * @param {Float32Array} matrix - Matrix data + * + * @return {this} This WebGL Renderer instance. + */ + setMatrix4: function (program, name, transpose, matrix) + { + this.setProgram(program); + + this.gl.uniformMatrix4fv(this.gl.getUniformLocation(program, name), transpose, matrix); + + return this; + }, + + /** + * Returns the maximum number of texture units that can be used in a fragment shader. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getMaxTextures + * @since 3.8.0 + * + * @return {integer} The maximum number of textures WebGL supports. + */ + getMaxTextures: function () + { + return this.config.maxTextures; + }, + + /** + * Returns the largest texture size (either width or height) that can be created. + * Note that VRAM may not allow a texture of any given size, it just expresses + * hardware / driver support for a given size. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getMaxTextureSize + * @since 3.8.0 + * + * @return {integer} The maximum supported texture size. + */ + getMaxTextureSize: function () + { + return this.config.maxTextureSize; + }, + + /** + * Destroy this WebGLRenderer, cleaning up all related resources such as pipelines, native textures, etc. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#destroy + * @since 3.0.0 + */ + destroy: function () + { + // Clear-up anything that should be cleared :) + + for (var i = 0; i < this.nativeTextures.length; i++) + { + this.gl.deleteTexture(this.nativeTextures[i]); + } + + this.nativeTextures = []; + + for (var key in this.pipelines) + { + this.pipelines[key].destroy(); + + delete this.pipelines[key]; + } + + this.defaultCamera.destroy(); + + this.currentMask = null; + this.currentCameraMask = null; + + this.canvas.removeEventListener('webglcontextlost', this.contextLostHandler, false); + this.canvas.removeEventListener('webglcontextrestored', this.contextRestoredHandler, false); + + this.game = null; + this.gl = null; + this.canvas = null; + + this.maskStack = []; + + this.contextLost = true; + + this.extensions = {}; + } + +}); + +module.exports = WebGLRenderer; + + +/***/ }), +/* 362 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); +var Color = __webpack_require__(36); +var GetFastValue = __webpack_require__(1); + +/** + * Takes a snapshot of an area from the current frame displayed by a WebGL canvas. + * + * This is then copied to an Image object. When this loads, the results are sent + * to the callback provided in the Snapshot Configuration object. + * + * @function Phaser.Renderer.Snapshot.WebGL + * @since 3.0.0 + * + * @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotState} config - The snapshot configuration object. + */ +var WebGLSnapshot = function (sourceCanvas, config) +{ + var gl = sourceCanvas.getContext('experimental-webgl'); + + var callback = GetFastValue(config, 'callback'); + var type = GetFastValue(config, 'type', 'image/png'); + var encoderOptions = GetFastValue(config, 'encoder', 0.92); + var x = GetFastValue(config, 'x', 0); + var y = GetFastValue(config, 'y', 0); + + var getPixel = GetFastValue(config, 'getPixel', false); + + var isFramebuffer = GetFastValue(config, 'isFramebuffer', false); + + var bufferWidth = (isFramebuffer) ? GetFastValue(config, 'bufferWidth', 1) : gl.drawingBufferWidth; + var bufferHeight = (isFramebuffer) ? GetFastValue(config, 'bufferHeight', 1) : gl.drawingBufferHeight; + + if (getPixel) + { + var pixel = new Uint8Array(4); + + var destY = (isFramebuffer) ? y : bufferHeight - y; + + gl.readPixels(x, destY, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); + + callback.call(null, new Color(pixel[0], pixel[1], pixel[2], pixel[3] / 255)); + } + else + { + var width = GetFastValue(config, 'width', bufferWidth); + var height = GetFastValue(config, 'height', bufferHeight); + + var total = width * height * 4; + + var pixels = new Uint8Array(total); + + gl.readPixels(x, bufferHeight - y - height, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + + var canvas = CanvasPool.createWebGL(this, width, height); + var ctx = canvas.getContext('2d'); + + var imageData = ctx.getImageData(0, 0, width, height); + + var data = imageData.data; + + for (var py = 0; py < height; py++) + { + for (var px = 0; px < width; px++) + { + var sourceIndex = ((height - py) * width + px) * 4; + var destIndex = (isFramebuffer) ? total - ((py * width + (width - px)) * 4) : (py * width + px) * 4; + + data[destIndex + 0] = pixels[sourceIndex + 0]; + data[destIndex + 1] = pixels[sourceIndex + 1]; + data[destIndex + 2] = pixels[sourceIndex + 2]; + data[destIndex + 3] = pixels[sourceIndex + 3]; + } + } + + ctx.putImageData(imageData, 0, 0); + + var image = new Image(); + + image.onerror = function () + { + callback.call(null); + + CanvasPool.remove(canvas); + }; + + image.onload = function () + { + callback.call(null, image); + + CanvasPool.remove(canvas); + }; + + image.src = canvas.toDataURL(type, encoderOptions); + } +}; + +module.exports = WebGLSnapshot; + + +/***/ }), +/* 363 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var ShaderSourceFS = __webpack_require__(808); +var ShaderSourceVS = __webpack_require__(809); +var WebGLPipeline = __webpack_require__(187); + +/** + * @classdesc + * BitmapMaskPipeline handles all bitmap masking rendering in WebGL. It works by using + * sampling two texture on the fragment shader and using the fragment's alpha to clip the region. + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * + * @class BitmapMaskPipeline + * @extends Phaser.Renderer.WebGL.WebGLPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.0.0 + * + * @param {object} config - Used for overriding shader an pipeline properties if extending this pipeline. + */ +var BitmapMaskPipeline = new Class({ + + Extends: WebGLPipeline, + + initialize: + + function BitmapMaskPipeline (config) + { + WebGLPipeline.call(this, { + game: config.game, + renderer: config.renderer, + gl: config.renderer.gl, + topology: (config.topology ? config.topology : config.renderer.gl.TRIANGLES), + vertShader: (config.vertShader ? config.vertShader : ShaderSourceVS), + fragShader: (config.fragShader ? config.fragShader : ShaderSourceFS), + vertexCapacity: (config.vertexCapacity ? config.vertexCapacity : 3), + + vertexSize: (config.vertexSize ? config.vertexSize : + Float32Array.BYTES_PER_ELEMENT * 2), + + vertices: new Float32Array([ + -1, +1, -1, -7, +7, +1 + ]).buffer, + + attributes: [ + { + name: 'inPosition', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: 0 + } + ] + }); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#vertexViewF32 + * @type {Float32Array} + * @since 3.0.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * Size of the batch. + * + * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#maxQuads + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.maxQuads = 1; + + /** + * Dirty flag to check if resolution properties need to be updated on the + * masking shader. + * + * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resolutionDirty + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.resolutionDirty = true; + }, + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + WebGLPipeline.prototype.onBind.call(this); + + var renderer = this.renderer; + var program = this.program; + + if (this.resolutionDirty) + { + renderer.setFloat2(program, 'uResolution', this.width, this.height); + renderer.setInt1(program, 'uMainSampler', 0); + renderer.setInt1(program, 'uMaskSampler', 1); + this.resolutionDirty = false; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resize + * @since 3.0.0 + * + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} resolution - [description] + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + WebGLPipeline.prototype.resize.call(this, width, height, resolution); + this.resolutionDirty = true; + return this; + }, + + /** + * Binds necessary resources and renders the mask to a separated framebuffer. + * The framebuffer for the masked object is also bound for further use. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#beginMask + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} mask - GameObject used as mask. + * @param {Phaser.GameObjects.GameObject} maskedObject - GameObject masked by the mask GameObject. + * @param {Phaser.Cameras.Scene2D.Camera} camera - [description] + */ + beginMask: function (mask, maskedObject, camera) + { + var renderer = this.renderer; + var gl = this.gl; + + // The renderable Game Object that is being used for the bitmap mask + var bitmapMask = mask.bitmapMask; + + if (bitmapMask && gl) + { + renderer.flush(); + + mask.prevFramebuffer = renderer.currentFramebuffer; + + renderer.setFramebuffer(mask.mainFramebuffer); + + gl.disable(gl.STENCIL_TEST); + + gl.clearColor(0, 0, 0, 0); + + gl.clear(gl.COLOR_BUFFER_BIT); + + if (renderer.currentCameraMask.mask !== mask) + { + renderer.currentMask.mask = mask; + renderer.currentMask.camera = camera; + } + } + }, + + /** + * The masked game objects framebuffer is unbound and its texture + * is bound together with the mask texture and the mask shader and + * a draw call with a single quad is processed. Here is where the + * masking effect is applied. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#endMask + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} mask - GameObject used as a mask. + */ + endMask: function (mask, camera) + { + var gl = this.gl; + var renderer = this.renderer; + + // The renderable Game Object that is being used for the bitmap mask + var bitmapMask = mask.bitmapMask; + + if (bitmapMask && gl) + { + renderer.flush(); + + // First we draw the mask to the mask fb + renderer.setFramebuffer(mask.maskFramebuffer); + + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + + renderer.setBlendMode(0, true); + + bitmapMask.renderWebGL(renderer, bitmapMask, 0, camera); + + renderer.flush(); + + renderer.setFramebuffer(mask.prevFramebuffer); + + // Is there a stencil further up the stack? + var prev = renderer.getCurrentStencilMask(); + + if (prev) + { + gl.enable(gl.STENCIL_TEST); + + prev.mask.applyStencil(renderer, prev.camera, true); + } + else + { + renderer.currentMask.mask = null; + } + + // Bind bitmap mask pipeline and draw + renderer.setPipeline(this); + + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, mask.maskTexture); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, mask.mainTexture); + + gl.uniform1i(gl.getUniformLocation(this.program, 'uInvertMaskAlpha'), mask.invertAlpha); + + // Finally, draw a triangle filling the whole screen + gl.drawArrays(this.topology, 0, 3); + } + } + +}); + +module.exports = BitmapMaskPipeline; + + +/***/ }), +/* 364 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var ShaderSourceFS = __webpack_require__(810); +var TextureTintPipeline = __webpack_require__(188); + +var LIGHT_COUNT = 10; + +/** + * @classdesc + * ForwardDiffuseLightPipeline implements a forward rendering approach for 2D lights. + * This pipeline extends TextureTintPipeline so it implements all it's rendering functions + * and batching system. + * + * @class ForwardDiffuseLightPipeline + * @extends Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration of the pipeline, same as the {@link Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline}. The fragment shader will be replaced with the lighting shader. + */ +var ForwardDiffuseLightPipeline = new Class({ + + Extends: TextureTintPipeline, + + initialize: + + function ForwardDiffuseLightPipeline (config) + { + LIGHT_COUNT = config.maxLights; + + config.fragShader = ShaderSourceFS.replace('%LIGHT_COUNT%', LIGHT_COUNT.toString()); + + TextureTintPipeline.call(this, config); + + /** + * Default normal map texture to use. + * + * @name Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#defaultNormalMap + * @type {Phaser.Texture.Frame} + * @private + * @since 3.11.0 + */ + this.defaultNormalMap; + + /** + * Inverse rotation matrix for normal map rotations. + * + * @name Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#inverseRotationMatrix + * @type {Float32Array} + * @private + * @since 3.16.0 + */ + this.inverseRotationMatrix = new Float32Array([ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]); + }, + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#boot + * @override + * @since 3.11.0 + */ + boot: function () + { + this.defaultNormalMap = this.game.textures.getFrame('__DEFAULT'); + }, + + /** + * This function binds its base class resources and this lights 2D resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#onBind + * @override + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} [gameObject] - The Game Object that invoked this pipeline, if any. + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function (gameObject) + { + TextureTintPipeline.prototype.onBind.call(this); + + var renderer = this.renderer; + var program = this.program; + + this.mvpUpdate(); + + renderer.setInt1(program, 'uNormSampler', 1); + renderer.setFloat2(program, 'uResolution', this.width, this.height); + + if (gameObject) + { + this.setNormalMap(gameObject); + } + + return this; + }, + + /** + * This function sets all the needed resources for each camera pass. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#onRender + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. + * + * @return {this} This WebGLPipeline instance. + */ + onRender: function (scene, camera) + { + this.active = false; + + var lightManager = scene.sys.lights; + + if (!lightManager || lightManager.lights.length <= 0 || !lightManager.active) + { + // Passthru + return this; + } + + var lights = lightManager.cull(camera); + var lightCount = Math.min(lights.length, LIGHT_COUNT); + + if (lightCount === 0) + { + return this; + } + + this.active = true; + + var renderer = this.renderer; + var program = this.program; + var cameraMatrix = camera.matrix; + var point = {x: 0, y: 0}; + var height = renderer.height; + var index; + + for (index = 0; index < LIGHT_COUNT; ++index) + { + // Reset lights + renderer.setFloat1(program, 'uLights[' + index + '].radius', 0); + } + + renderer.setFloat4(program, 'uCamera', camera.x, camera.y, camera.rotation, camera.zoom); + renderer.setFloat3(program, 'uAmbientLightColor', lightManager.ambientColor.r, lightManager.ambientColor.g, lightManager.ambientColor.b); + + for (index = 0; index < lightCount; ++index) + { + var light = lights[index]; + var lightName = 'uLights[' + index + '].'; + + cameraMatrix.transformPoint(light.x, light.y, point); + + renderer.setFloat2(program, lightName + 'position', point.x - (camera.scrollX * light.scrollFactorX * camera.zoom), height - (point.y - (camera.scrollY * light.scrollFactorY) * camera.zoom)); + renderer.setFloat3(program, lightName + 'color', light.r, light.g, light.b); + renderer.setFloat1(program, lightName + 'intensity', light.intensity); + renderer.setFloat1(program, lightName + 'radius', light.radius); + } + + this.currentNormalMapRotation = null; + + return this; + }, + + /** + * Generic function for batching a textured quad + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#batchTexture + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Source GameObject + * @param {WebGLTexture} texture - Raw WebGLTexture associated with the quad + * @param {integer} textureWidth - Real texture width + * @param {integer} textureHeight - Real texture height + * @param {number} srcX - X coordinate of the quad + * @param {number} srcY - Y coordinate of the quad + * @param {number} srcWidth - Width of the quad + * @param {number} srcHeight - Height of the quad + * @param {number} scaleX - X component of scale + * @param {number} scaleY - Y component of scale + * @param {number} rotation - Rotation of the quad + * @param {boolean} flipX - Indicates if the quad is horizontally flipped + * @param {boolean} flipY - Indicates if the quad is vertically flipped + * @param {number} scrollFactorX - By which factor is the quad affected by the camera horizontal scroll + * @param {number} scrollFactorY - By which factor is the quad effected by the camera vertical scroll + * @param {number} displayOriginX - Horizontal origin in pixels + * @param {number} displayOriginY - Vertical origin in pixels + * @param {number} frameX - X coordinate of the texture frame + * @param {number} frameY - Y coordinate of the texture frame + * @param {number} frameWidth - Width of the texture frame + * @param {number} frameHeight - Height of the texture frame + * @param {integer} tintTL - Tint for top left + * @param {integer} tintTR - Tint for top right + * @param {integer} tintBL - Tint for bottom left + * @param {integer} tintBR - Tint for bottom right + * @param {number} tintEffect - The tint effect (0 for additive, 1 for replacement) + * @param {number} uOffset - Horizontal offset on texture coordinate + * @param {number} vOffset - Vertical offset on texture coordinate + * @param {Phaser.Cameras.Scene2D.Camera} camera - Current used camera + * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - Parent container + */ + batchTexture: function ( + gameObject, + texture, + textureWidth, textureHeight, + srcX, srcY, + srcWidth, srcHeight, + scaleX, scaleY, + rotation, + flipX, flipY, + scrollFactorX, scrollFactorY, + displayOriginX, displayOriginY, + frameX, frameY, frameWidth, frameHeight, + tintTL, tintTR, tintBL, tintBR, tintEffect, + uOffset, vOffset, + camera, + parentTransformMatrix) + { + if (!this.active) + { + return; + } + + this.renderer.setPipeline(this); + + var normalTexture; + + if (gameObject.displayTexture) + { + normalTexture = gameObject.displayTexture.dataSource[gameObject.displayFrame.sourceIndex]; + } + else if (gameObject.texture) + { + normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex]; + } + else if (gameObject.tileset) + { + if (Array.isArray(gameObject.tileset)) + { + normalTexture = gameObject.tileset[0].image.dataSource[0]; + } + else + { + normalTexture = gameObject.tileset.image.dataSource[0]; + } + } + + if (!normalTexture) + { + console.warn('Normal map missing or invalid'); + return; + } + + this.setTexture2D(normalTexture.glTexture, 1); + this.setNormalMapRotation(rotation); + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var u0 = (frameX / textureWidth) + uOffset; + var v0 = (frameY / textureHeight) + vOffset; + var u1 = (frameX + frameWidth) / textureWidth + uOffset; + var v1 = (frameY + frameHeight) / textureHeight + vOffset; + + var width = srcWidth; + var height = srcHeight; + + // var x = -displayOriginX + frameX; + // var y = -displayOriginY + frameY; + + var x = -displayOriginX; + var y = -displayOriginY; + + if (gameObject.isCropped) + { + var crop = gameObject._crop; + + width = crop.width; + height = crop.height; + + srcWidth = crop.width; + srcHeight = crop.height; + + frameX = crop.x; + frameY = crop.y; + + var ox = frameX; + var oy = frameY; + + if (flipX) + { + ox = (frameWidth - crop.x - crop.width); + } + + if (flipY && !texture.isRenderTexture) + { + oy = (frameHeight - crop.y - crop.height); + } + + u0 = (ox / textureWidth) + uOffset; + v0 = (oy / textureHeight) + vOffset; + u1 = (ox + crop.width) / textureWidth + uOffset; + v1 = (oy + crop.height) / textureHeight + vOffset; + + x = -displayOriginX + frameX; + y = -displayOriginY + frameY; + } + + // Invert the flipY if this is a RenderTexture + flipY = flipY ^ (texture.isRenderTexture ? 1 : 0); + + if (flipX) + { + width *= -1; + x += srcWidth; + } + + if (flipY) + { + height *= -1; + y += srcHeight; + } + + // Do we need this? (doubt it) + // if (camera.roundPixels) + // { + // x |= 0; + // y |= 0; + // } + + var xw = x + width; + var yh = y + height; + + spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = srcX; + spriteMatrix.f = srcY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * scrollFactorX; + spriteMatrix.f -= camera.scrollY * scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + this.setTexture2D(texture, 0); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + }, + + /** + * Sets the Game Objects normal map as the active texture. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#setNormalMap + * @since 3.11.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to update. + */ + setNormalMap: function (gameObject) + { + if (!this.active || !gameObject) + { + return; + } + + var normalTexture; + + if (gameObject.texture) + { + normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex]; + } + + if (!normalTexture) + { + normalTexture = this.defaultNormalMap; + } + + this.setTexture2D(normalTexture.glTexture, 1); + + this.renderer.setPipeline(gameObject.defaultPipeline); + }, + + /** + * Rotates the normal map vectors inversely by the given angle. + * Only works in 2D space. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#setNormalMapRotation + * @since 3.16.0 + * + * @param {number} rotation - The angle of rotation in radians. + */ + setNormalMapRotation: function (rotation) + { + if (rotation !== this.currentNormalMapRotation || this.batches.length === 0) + { + if (this.batches.length > 0) + { + this.flush(); + } + + var inverseRotationMatrix = this.inverseRotationMatrix; + + if (rotation) + { + var rot = -rotation; + var c = Math.cos(rot); + var s = Math.sin(rot); + + inverseRotationMatrix[1] = s; + inverseRotationMatrix[3] = -s; + inverseRotationMatrix[0] = inverseRotationMatrix[4] = c; + } + else + { + inverseRotationMatrix[0] = inverseRotationMatrix[4] = 1; + inverseRotationMatrix[1] = inverseRotationMatrix[3] = 0; + } + + this.renderer.setMatrix3(this.program, 'uInverseRotationMatrix', false, inverseRotationMatrix); + + this.currentNormalMapRotation = rotation; + } + }, + + /** + * Takes a Sprite Game Object, or any object that extends it, which has a normal texture and adds it to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#batchSprite + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Sprite} sprite - The texture-based Game Object to add to the batch. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - The transform matrix of the parent container, if set. + */ + batchSprite: function (sprite, camera, parentTransformMatrix) + { + if (!this.active) + { + return; + } + + var normalTexture = sprite.texture.dataSource[sprite.frame.sourceIndex]; + + if (normalTexture) + { + this.renderer.setPipeline(this); + + this.setTexture2D(normalTexture.glTexture, 1); + this.setNormalMapRotation(sprite.rotation); + + TextureTintPipeline.prototype.batchSprite.call(this, sprite, camera, parentTransformMatrix); + } + } + +}); + +ForwardDiffuseLightPipeline.LIGHT_COUNT = LIGHT_COUNT; + +module.exports = ForwardDiffuseLightPipeline; + + +/***/ }), +/* 365 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Implements a model view projection matrices. + * Pipelines can implement this for doing 2D and 3D rendering. + * + * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection + * @since 3.0.0 + */ +var ModelViewProjection = { + + /** + * Dirty flag for checking if model matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + modelMatrixDirty: false, + + /** + * Dirty flag for checking if view matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + viewMatrixDirty: false, + + /** + * Dirty flag for checking if projection matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + projectionMatrixDirty: false, + + /** + * Model matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + modelMatrix: null, + + /** + * View matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + viewMatrix: null, + + /** + * Projection matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + projectionMatrix: null, + + /** + * Initializes MVP matrices with an identity matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit + * @since 3.0.0 + */ + mvpInit: function () + { + this.modelMatrixDirty = true; + this.viewMatrixDirty = true; + this.projectionMatrixDirty = true; + + this.modelMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.viewMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.projectionMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + return this; + }, + + /** + * If dirty flags are set then the matrices are uploaded to the GPU. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate + * @since 3.0.0 + */ + mvpUpdate: function () + { + var program = this.program; + + if (this.modelMatrixDirty) + { + this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); + this.modelMatrixDirty = false; + } + + if (this.viewMatrixDirty) + { + this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); + this.viewMatrixDirty = false; + } + + if (this.projectionMatrixDirty) + { + this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + this.projectionMatrixDirty = false; + } + + return this; + }, + + /** + * Loads an identity matrix to the model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity + * @since 3.0.0 + */ + modelIdentity: function () + { + var modelMatrix = this.modelMatrix; + + modelMatrix[0] = 1; + modelMatrix[1] = 0; + modelMatrix[2] = 0; + modelMatrix[3] = 0; + modelMatrix[4] = 0; + modelMatrix[5] = 1; + modelMatrix[6] = 0; + modelMatrix[7] = 0; + modelMatrix[8] = 0; + modelMatrix[9] = 0; + modelMatrix[10] = 1; + modelMatrix[11] = 0; + modelMatrix[12] = 0; + modelMatrix[13] = 0; + modelMatrix[14] = 0; + modelMatrix[15] = 1; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Scale model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelScale: function (x, y, z) + { + var modelMatrix = this.modelMatrix; + + modelMatrix[0] = modelMatrix[0] * x; + modelMatrix[1] = modelMatrix[1] * x; + modelMatrix[2] = modelMatrix[2] * x; + modelMatrix[3] = modelMatrix[3] * x; + modelMatrix[4] = modelMatrix[4] * y; + modelMatrix[5] = modelMatrix[5] * y; + modelMatrix[6] = modelMatrix[6] * y; + modelMatrix[7] = modelMatrix[7] * y; + modelMatrix[8] = modelMatrix[8] * z; + modelMatrix[9] = modelMatrix[9] * z; + modelMatrix[10] = modelMatrix[10] * z; + modelMatrix[11] = modelMatrix[11] * z; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Translate model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelTranslate: function (x, y, z) + { + var modelMatrix = this.modelMatrix; + + modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; + modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; + modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; + modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateX: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; + + modelMatrix[4] = a10 * c + a20 * s; + modelMatrix[5] = a11 * c + a21 * s; + modelMatrix[6] = a12 * c + a22 * s; + modelMatrix[7] = a13 * c + a23 * s; + modelMatrix[8] = a20 * c - a10 * s; + modelMatrix[9] = a21 * c - a11 * s; + modelMatrix[10] = a22 * c - a12 * s; + modelMatrix[11] = a23 * c - a13 * s; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateY: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; + + modelMatrix[0] = a00 * c - a20 * s; + modelMatrix[1] = a01 * c - a21 * s; + modelMatrix[2] = a02 * c - a22 * s; + modelMatrix[3] = a03 * c - a23 * s; + modelMatrix[8] = a00 * s + a20 * c; + modelMatrix[9] = a01 * s + a21 * c; + modelMatrix[10] = a02 * s + a22 * c; + modelMatrix[11] = a03 * s + a23 * c; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateZ: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; + + modelMatrix[0] = a00 * c + a10 * s; + modelMatrix[1] = a01 * c + a11 * s; + modelMatrix[2] = a02 * c + a12 * s; + modelMatrix[3] = a03 * c + a13 * s; + modelMatrix[4] = a10 * c - a00 * s; + modelMatrix[5] = a11 * c - a01 * s; + modelMatrix[6] = a12 * c - a02 * s; + modelMatrix[7] = a13 * c - a03 * s; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Loads identity matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + viewIdentity: function () + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = 1; + viewMatrix[1] = 0; + viewMatrix[2] = 0; + viewMatrix[3] = 0; + viewMatrix[4] = 0; + viewMatrix[5] = 1; + viewMatrix[6] = 0; + viewMatrix[7] = 0; + viewMatrix[8] = 0; + viewMatrix[9] = 0; + viewMatrix[10] = 1; + viewMatrix[11] = 0; + viewMatrix[12] = 0; + viewMatrix[13] = 0; + viewMatrix[14] = 0; + viewMatrix[15] = 1; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Scales view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewScale: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = viewMatrix[0] * x; + viewMatrix[1] = viewMatrix[1] * x; + viewMatrix[2] = viewMatrix[2] * x; + viewMatrix[3] = viewMatrix[3] * x; + viewMatrix[4] = viewMatrix[4] * y; + viewMatrix[5] = viewMatrix[5] * y; + viewMatrix[6] = viewMatrix[6] * y; + viewMatrix[7] = viewMatrix[7] * y; + viewMatrix[8] = viewMatrix[8] * z; + viewMatrix[9] = viewMatrix[9] * z; + viewMatrix[10] = viewMatrix[10] * z; + viewMatrix[11] = viewMatrix[11] * z; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Translates view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewTranslate: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; + viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; + viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; + viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateX: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[4] = a10 * c + a20 * s; + viewMatrix[5] = a11 * c + a21 * s; + viewMatrix[6] = a12 * c + a22 * s; + viewMatrix[7] = a13 * c + a23 * s; + viewMatrix[8] = a20 * c - a10 * s; + viewMatrix[9] = a21 * c - a11 * s; + viewMatrix[10] = a22 * c - a12 * s; + viewMatrix[11] = a23 * c - a13 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateY: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[0] = a00 * c - a20 * s; + viewMatrix[1] = a01 * c - a21 * s; + viewMatrix[2] = a02 * c - a22 * s; + viewMatrix[3] = a03 * c - a23 * s; + viewMatrix[8] = a00 * s + a20 * c; + viewMatrix[9] = a01 * s + a21 * c; + viewMatrix[10] = a02 * s + a22 * c; + viewMatrix[11] = a03 * s + a23 * c; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateZ: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + + viewMatrix[0] = a00 * c + a10 * s; + viewMatrix[1] = a01 * c + a11 * s; + viewMatrix[2] = a02 * c + a12 * s; + viewMatrix[3] = a03 * c + a13 * s; + viewMatrix[4] = a10 * c - a00 * s; + viewMatrix[5] = a11 * c - a01 * s; + viewMatrix[6] = a12 * c - a02 * s; + viewMatrix[7] = a13 * c - a03 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D + * @since 3.0.0 + * + * @param {Float32Array} matrix2D - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad2D: function (matrix2D) + { + var vm = this.viewMatrix; + + vm[0] = matrix2D[0]; + vm[1] = matrix2D[1]; + vm[2] = 0.0; + vm[3] = 0.0; + vm[4] = matrix2D[2]; + vm[5] = matrix2D[3]; + vm[6] = 0.0; + vm[7] = 0.0; + vm[8] = matrix2D[4]; + vm[9] = matrix2D[5]; + vm[10] = 1.0; + vm[11] = 0.0; + vm[12] = 0.0; + vm[13] = 0.0; + vm[14] = 0.0; + vm[15] = 1.0; + + this.viewMatrixDirty = true; + + return this; + }, + + + /** + * Copies a 4x4 matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad + * @since 3.0.0 + * + * @param {Float32Array} matrix - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad: function (matrix) + { + var vm = this.viewMatrix; + + vm[0] = matrix[0]; + vm[1] = matrix[1]; + vm[2] = matrix[2]; + vm[3] = matrix[3]; + vm[4] = matrix[4]; + vm[5] = matrix[5]; + vm[6] = matrix[6]; + vm[7] = matrix[7]; + vm[8] = matrix[8]; + vm[9] = matrix[9]; + vm[10] = matrix[10]; + vm[11] = matrix[11]; + vm[12] = matrix[12]; + vm[13] = matrix[13]; + vm[14] = matrix[14]; + vm[15] = matrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads identity matrix into the projection matrix. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + projIdentity: function () + { + var projectionMatrix = this.projectionMatrix; + + projectionMatrix[0] = 1; + projectionMatrix[1] = 0; + projectionMatrix[2] = 0; + projectionMatrix[3] = 0; + projectionMatrix[4] = 0; + projectionMatrix[5] = 1; + projectionMatrix[6] = 0; + projectionMatrix[7] = 0; + projectionMatrix[8] = 0; + projectionMatrix[9] = 0; + projectionMatrix[10] = 1; + projectionMatrix[11] = 0; + projectionMatrix[12] = 0; + projectionMatrix[13] = 0; + projectionMatrix[14] = 0; + projectionMatrix[15] = 1; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up an orthographic projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho + * @since 3.0.0 + * + * @param {number} left - The left value. + * @param {number} right - The right value. + * @param {number} bottom - The bottom value. + * @param {number} top - The top value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projOrtho: function (left, right, bottom, top, near, far) + { + var projectionMatrix = this.projectionMatrix; + var leftRight = 1.0 / (left - right); + var bottomTop = 1.0 / (bottom - top); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = -2.0 * leftRight; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = -2.0 * bottomTop; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = 2.0 * nearFar; + projectionMatrix[11] = 0.0; + projectionMatrix[12] = (left + right) * leftRight; + projectionMatrix[13] = (top + bottom) * bottomTop; + projectionMatrix[14] = (far + near) * nearFar; + projectionMatrix[15] = 1.0; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up a perspective projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp + * @since 3.0.0 + * + * @param {number} fovY - The fov value. + * @param {number} aspectRatio - The aspectRatio value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projPersp: function (fovY, aspectRatio, near, far) + { + var projectionMatrix = this.projectionMatrix; + var fov = 1.0 / Math.tan(fovY / 2.0); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = fov / aspectRatio; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = fov; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = (far + near) * nearFar; + projectionMatrix[11] = -1.0; + projectionMatrix[12] = 0.0; + projectionMatrix[13] = 0.0; + projectionMatrix[14] = (2.0 * far * near) * nearFar; + projectionMatrix[15] = 0.0; + + this.projectionMatrixDirty = true; + + return this; + } +}; + +module.exports = ModelViewProjection; + + +/***/ }), +/* 366 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(32); + +/** + * Called automatically by Phaser.Game and responsible for creating the console.log debug header. + * + * You can customize or disable the header via the Game Config object. + * + * @function Phaser.Core.DebugHeader + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance which will output this debug header. + */ +var DebugHeader = function (game) +{ + var config = game.config; + + if (config.hideBanner) + { + return; + } + + var renderType = 'WebGL'; + + if (config.renderType === CONST.CANVAS) + { + renderType = 'Canvas'; + } + else if (config.renderType === CONST.HEADLESS) + { + renderType = 'Headless'; + } + + var audioConfig = config.audio; + var deviceAudio = game.device.audio; + + var audioType; + + if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) + { + audioType = 'Web Audio'; + } + else if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + audioType = 'No Audio'; + } + else + { + audioType = 'HTML5 Audio'; + } + + if (!game.device.browser.ie) + { + var c = ''; + var args = [ c ]; + + if (Array.isArray(config.bannerBackgroundColor)) + { + var lastColor; + + config.bannerBackgroundColor.forEach(function (color) + { + c = c.concat('%c '); + + args.push('background: ' + color); + + lastColor = color; + + }); + + // inject the text color + args[args.length - 1] = 'color: ' + config.bannerTextColor + '; background: ' + lastColor; + } + else + { + c = c.concat('%c '); + + args.push('color: ' + config.bannerTextColor + '; background: ' + config.bannerBackgroundColor); + } + + // URL link background color (always white) + args.push('background: #fff'); + + if (config.gameTitle) + { + c = c.concat(config.gameTitle); + + if (config.gameVersion) + { + c = c.concat(' v' + config.gameVersion); + } + + if (!config.hidePhaser) + { + c = c.concat(' / '); + } + } + + var fb = ( true) ? '-FB' : undefined; + + if (!config.hidePhaser) + { + c = c.concat('Phaser v' + CONST.VERSION + fb + ' (' + renderType + ' | ' + audioType + ')'); + } + + c = c.concat(' %c ' + config.gameURL); + + // Inject the new string back into the args array + args[0] = c; + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + CONST.VERSION + ' / https://phaser.io'); + } +}; + +module.exports = DebugHeader; + + +/***/ }), +/* 367 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetValue = __webpack_require__(5); +var NOOP = __webpack_require__(2); +var RequestAnimationFrame = __webpack_require__(368); + +// http://www.testufo.com/#test=animation-time-graph + +/** + * @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 + */ +var TimeStep = new Class({ + + initialize: + + function TimeStep (game, config) + { + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.Core.TimeStep#game + * @type {Phaser.Game} + * @readonly + * @since 3.0.0 + */ + this.game = game; + + /** + * The Request Animation Frame DOM Event handler. + * + * @name Phaser.Core.TimeStep#raf + * @type {Phaser.DOM.RequestAnimationFrame} + * @readonly + * @since 3.0.0 + */ + this.raf = new RequestAnimationFrame(); + + /** + * A flag that is set once the TimeStep has started running and toggled when it stops. + * + * @name Phaser.Core.TimeStep#started + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.started = false; + + /** + * A flag that is set once the TimeStep has started running and toggled when it stops. + * The difference between this value and `started` is that `running` is toggled when + * the TimeStep is sent to sleep, where-as `started` remains `true`, only changing if + * the TimeStep is actually stopped, not just paused. + * + * @name Phaser.Core.TimeStep#running + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.running = false; + + /** + * The minimum fps rate you want the Time Step to run at. + * + * @name Phaser.Core.TimeStep#minFps + * @type {integer} + * @default 5 + * @since 3.0.0 + */ + this.minFps = GetValue(config, 'min', 5); + + /** + * The target fps rate for the Time Step to run at. + * + * Setting this value will not actually change the speed at which the browser runs, that is beyond + * the control of Phaser. Instead, it allows you to determine performance issues and if the Time Step + * is spiraling out of control. + * + * @name Phaser.Core.TimeStep#targetFps + * @type {integer} + * @default 60 + * @since 3.0.0 + */ + this.targetFps = GetValue(config, 'target', 60); + + /** + * The minFps value in ms. + * Defaults to 200ms between frames (i.e. super slow!) + * + * @name Phaser.Core.TimeStep#_min + * @type {number} + * @private + * @since 3.0.0 + */ + this._min = 1000 / this.minFps; + + /** + * The targetFps value in ms. + * Defaults to 16.66ms between frames (i.e. normal) + * + * @name Phaser.Core.TimeStep#_target + * @type {number} + * @private + * @since 3.0.0 + */ + this._target = 1000 / this.targetFps; + + /** + * An exponential moving average of the frames per second. + * + * @name Phaser.Core.TimeStep#actualFps + * @type {integer} + * @readonly + * @default 60 + * @since 3.0.0 + */ + this.actualFps = this.targetFps; + + /** + * The time at which the next fps rate update will take place. + * When an fps update happens, the `framesThisSecond` value is reset. + * + * @name Phaser.Core.TimeStep#nextFpsUpdate + * @type {integer} + * @readonly + * @default 0 + * @since 3.0.0 + */ + this.nextFpsUpdate = 0; + + /** + * The number of frames processed this second. + * + * @name Phaser.Core.TimeStep#framesThisSecond + * @type {integer} + * @readonly + * @default 0 + * @since 3.0.0 + */ + this.framesThisSecond = 0; + + /** + * A callback to be invoked each time the Time Step steps. + * + * @name Phaser.Core.TimeStep#callback + * @type {Phaser.Types.Core.TimeStepCallback} + * @default NOOP + * @since 3.0.0 + */ + this.callback = NOOP; + + /** + * You can force the Time Step to use Set Timeout instead of Request Animation Frame by setting + * the `forceSetTimeOut` property to `true` in the Game Configuration object. It cannot be changed at run-time. + * + * @name Phaser.Core.TimeStep#forceSetTimeOut + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.forceSetTimeOut = GetValue(config, 'forceSetTimeOut', false); + + /** + * The time, calculated at the start of the current step, as smoothed by the delta value. + * + * @name Phaser.Core.TimeStep#time + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.time = 0; + + /** + * The time at which the game started running. This value is adjusted if the game is then + * paused and resumes. + * + * @name Phaser.Core.TimeStep#startTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.startTime = 0; + + /** + * The time, as returned by `performance.now` of the previous step. + * + * @name Phaser.Core.TimeStep#lastTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.lastTime = 0; + + /** + * The current frame the game is on. This counter is incremented once every game step, regardless of how much + * time has passed and is unaffected by delta smoothing. + * + * @name Phaser.Core.TimeStep#frame + * @type {integer} + * @readonly + * @default 0 + * @since 3.0.0 + */ + this.frame = 0; + + /** + * Is the browser currently considered in focus by the Page Visibility API? + * This value is set in the `blur` method, which is called automatically by the Game instance. + * + * @name Phaser.Core.TimeStep#inFocus + * @type {boolean} + * @readonly + * @default true + * @since 3.0.0 + */ + this.inFocus = true; + + /** + * The timestamp at which the game became paused, as determined by the Page Visibility API. + * + * @name Phaser.Core.TimeStep#_pauseTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._pauseTime = 0; + + /** + * An internal counter to allow for the browser 'cooling down' after coming back into focus. + * + * @name Phaser.Core.TimeStep#_coolDown + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._coolDown = 0; + + /** + * The delta time, in ms, since the last game step. This is a clamped and smoothed average value. + * + * @name Phaser.Core.TimeStep#delta + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.delta = 0; + + /** + * Internal index of the delta history position. + * + * @name Phaser.Core.TimeStep#deltaIndex + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.deltaIndex = 0; + + /** + * Internal array holding the previous delta values, used for delta smoothing. + * + * @name Phaser.Core.TimeStep#deltaHistory + * @type {integer[]} + * @since 3.0.0 + */ + this.deltaHistory = []; + + /** + * The maximum number of delta values that are retained in order to calculate a smoothed moving average. + * + * This can be changed in the Game Config via the `fps.deltaHistory` property. The default is 10. + * + * @name Phaser.Core.TimeStep#deltaSmoothingMax + * @type {integer} + * @default 10 + * @since 3.0.0 + */ + this.deltaSmoothingMax = GetValue(config, 'deltaHistory', 10); + + /** + * The number of frames that the cooldown is set to after the browser panics over the FPS rate, usually + * as a result of switching tabs and regaining focus. + * + * This can be changed in the Game Config via the `fps.panicMax` property. The default is 120. + * + * @name Phaser.Core.TimeStep#panicMax + * @type {integer} + * @default 120 + * @since 3.0.0 + */ + this.panicMax = GetValue(config, 'panicMax', 120); + + /** + * The actual elapsed time in ms between one update and the next. + * + * Unlike with `delta`, no smoothing, capping, or averaging is applied to this value. + * So please be careful when using this value in math calculations. + * + * @name Phaser.Core.TimeStep#rawDelta + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.rawDelta = 0; + + /** + * The time, as returned by `performance.now` at the very start of the current step. + * 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 + */ + this.now = 0; + + /** + * Apply smoothing to the delta value used within Phasers internal calculations? + * + * This can be changed in the Game Config via the `fps.smoothStep` property. The default is `true`. + * + * Smoothing helps settle down the delta values after browser tab switches, or other situations + * which could cause significant delta spikes or dips. By default it has been enabled in Phaser 3 + * since the first version, but is now exposed under this property (and the corresponding game config + * `smoothStep` value), to allow you to easily disable it, should you require. + * + * @name Phaser.Core.TimeStep#smoothStep + * @type {boolean} + * @since 3.22.0 + */ + this.smoothStep = GetValue(config, 'smoothStep', true); + }, + + /** + * Called by the Game instance when the DOM window.onBlur event triggers. + * + * @method Phaser.Core.TimeStep#blur + * @since 3.0.0 + */ + blur: function () + { + this.inFocus = false; + }, + + /** + * Called by the Game instance when the DOM window.onFocus event triggers. + * + * @method Phaser.Core.TimeStep#focus + * @since 3.0.0 + */ + focus: function () + { + this.inFocus = true; + + this.resetDelta(); + }, + + /** + * Called when the visibility API says the game is 'hidden' (tab switch out of view, etc) + * + * @method Phaser.Core.TimeStep#pause + * @since 3.0.0 + */ + pause: function () + { + this._pauseTime = window.performance.now(); + }, + + /** + * Called when the visibility API says the game is 'visible' again (tab switch back into view, etc) + * + * @method Phaser.Core.TimeStep#resume + * @since 3.0.0 + */ + resume: function () + { + this.resetDelta(); + + this.startTime += this.time - this._pauseTime; + }, + + /** + * Resets the time, lastTime, fps averages and delta history. + * Called automatically when a browser sleeps them resumes. + * + * @method Phaser.Core.TimeStep#resetDelta + * @since 3.0.0 + */ + resetDelta: function () + { + var now = window.performance.now(); + + this.time = now; + this.lastTime = now; + this.nextFpsUpdate = now + 1000; + this.framesThisSecond = 0; + + // Pre-populate smoothing array + + for (var i = 0; i < this.deltaSmoothingMax; i++) + { + this.deltaHistory[i] = Math.min(this._target, this.deltaHistory[i]); + } + + this.delta = 0; + this.deltaIndex = 0; + + this._coolDown = this.panicMax; + }, + + /** + * Starts the Time Step running, if it is not already doing so. + * Called automatically by the Game Boot process. + * + * @method Phaser.Core.TimeStep#start + * @since 3.0.0 + * + * @param {Phaser.Types.Core.TimeStepCallback} callback - The callback to be invoked each time the Time Step steps. + */ + start: function (callback) + { + if (this.started) + { + return this; + } + + this.started = true; + this.running = true; + + for (var i = 0; i < this.deltaSmoothingMax; i++) + { + this.deltaHistory[i] = this._target; + } + + this.resetDelta(); + + this.startTime = window.performance.now(); + + this.callback = callback; + + this.raf.start(this.step.bind(this), this.forceSetTimeOut, this._target); + }, + + /** + * The main step method. This is called each time the browser updates, either by Request Animation Frame, + * or by Set Timeout. It is responsible for calculating the delta values, frame totals, cool down history and more. + * You generally should never call this method directly. + * + * @method Phaser.Core.TimeStep#step + * @since 3.0.0 + */ + step: function () + { + // Because the timestamp passed in from raf represents the beginning of the main thread frame that we’re currently in, + // not the actual time now, and as we want to compare this time value against Event timeStamps and the like, we need a + // more accurate one: + + var time = window.performance.now(); + + this.now = time; + + var before = time - this.lastTime; + + if (before < 0) + { + // Because, Chrome. + before = 0; + } + + this.rawDelta = before; + + var idx = this.deltaIndex; + var history = this.deltaHistory; + var max = this.deltaSmoothingMax; + + // delta time (time is in ms) + var dt = before; + + // Delta Average + var avg = before; + + // When a browser switches tab, then comes back again, it takes around 10 frames before + // the delta time settles down so we employ a 'cooling down' period before we start + // trusting the delta values again, to avoid spikes flooding through our delta average + + if (this.smoothStep) + { + if (this._coolDown > 0 || !this.inFocus) + { + this._coolDown--; + + dt = Math.min(dt, this._target); + } + + if (dt > this._min) + { + // Probably super bad start time or browser tab context loss, + // so use the last 'sane' dt value + + dt = history[idx]; + + // Clamp delta to min (in case history has become corrupted somehow) + dt = Math.min(dt, this._min); + } + + // Smooth out the delta over the previous X frames + + // add the delta to the smoothing array + history[idx] = dt; + + // adjusts the delta history array index based on the smoothing count + // this stops the array growing beyond the size of deltaSmoothingMax + this.deltaIndex++; + + if (this.deltaIndex > max) + { + this.deltaIndex = 0; + } + + // Loop the history array, adding the delta values together + avg = 0; + + for (var i = 0; i < max; i++) + { + avg += history[i]; + } + + // Then divide by the array length to get the average delta + avg /= max; + } + + // Set as the world delta value + this.delta = avg; + + // Real-world timer advance + this.time += this.rawDelta; + + // Update the estimate of the frame rate, `fps`. Every second, the number + // of frames that occurred in that second are included in an exponential + // moving average of all frames per second, with an alpha of 0.25. This + // means that more recent seconds affect the estimated frame rate more than + // older seconds. + // + // When a browser window is NOT minimized, but is covered up (i.e. you're using + // another app which has spawned a window over the top of the browser), then it + // will start to throttle the raf callback time. It waits for a while, and then + // starts to drop the frame rate at 1 frame per second until it's down to just over 1fps. + // So if the game was running at 60fps, and the player opens a new window, then + // after 60 seconds (+ the 'buffer time') it'll be down to 1fps, so rafin'g at 1Hz. + // + // When they make the game visible again, the frame rate is increased at a rate of + // approx. 8fps, back up to 60fps (or the max it can obtain) + // + // There is no easy way to determine if this drop in frame rate is because the + // browser is throttling raf, or because the game is struggling with performance + // because you're asking it to do too much on the device. + + if (time > this.nextFpsUpdate) + { + // Compute the new exponential moving average with an alpha of 0.25. + this.actualFps = 0.25 * this.framesThisSecond + 0.75 * this.actualFps; + this.nextFpsUpdate = time + 1000; + this.framesThisSecond = 0; + } + + this.framesThisSecond++; + + // Interpolation - how far between what is expected and where we are? + var interpolation = avg / this._target; + + this.callback(time, avg, interpolation); + + // Shift time value over + this.lastTime = time; + + this.frame++; + }, + + /** + * Manually calls `TimeStep.step`. + * + * @method Phaser.Core.TimeStep#tick + * @since 3.0.0 + */ + tick: function () + { + this.step(); + }, + + /** + * Sends the TimeStep to sleep, stopping Request Animation Frame (or SetTimeout) and toggling the `running` flag to false. + * + * @method Phaser.Core.TimeStep#sleep + * @since 3.0.0 + */ + sleep: function () + { + if (this.running) + { + this.raf.stop(); + + this.running = false; + } + }, + + /** + * 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. + */ + wake: function (seamless) + { + if (this.running) + { + this.sleep(); + } + else if (seamless) + { + this.startTime += -this.lastTime + (this.lastTime + window.performance.now()); + } + + this.raf.start(this.step.bind(this), this.useRAF); + + this.running = true; + + this.step(); + }, + + /** + * Gets the duration which the game has been running, in seconds. + * + * @method Phaser.Core.TimeStep#getDuration + * @since 3.17.0 + * + * @return {number} The duration in seconds. + */ + getDuration: function () + { + return Math.round(this.lastTime - this.startTime) / 1000; + }, + + /** + * Gets the duration which the game has been running, in ms. + * + * @method Phaser.Core.TimeStep#getDurationMS + * @since 3.17.0 + * + * @return {number} The duration in ms. + */ + getDurationMS: function () + { + return Math.round(this.lastTime - this.startTime); + }, + + /** + * Stops the TimeStep running. + * + * @method Phaser.Core.TimeStep#stop + * @since 3.0.0 + * + * @return {this} The TimeStep object. + */ + stop: function () + { + this.running = false; + this.started = false; + + this.raf.stop(); + + return this; + }, + + /** + * Destroys the TimeStep. This will stop Request Animation Frame, stop the step, clear the callbacks and null + * any objects. + * + * @method Phaser.Core.TimeStep#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stop(); + + this.callback = NOOP; + + this.raf = null; + this.game = null; + } + +}); + +module.exports = TimeStep; + + +/***/ }), +/* 368 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var NOOP = __webpack_require__(2); + +/** + * @classdesc + * Abstracts away the use of RAF or setTimeOut for the core game update loop. + * This is invoked automatically by the Phaser.Game instance. + * + * @class RequestAnimationFrame + * @memberof Phaser.DOM + * @constructor + * @since 3.0.0 + */ +var RequestAnimationFrame = new Class({ + + initialize: + + function RequestAnimationFrame () + { + /** + * True if RequestAnimationFrame is running, otherwise false. + * + * @name Phaser.DOM.RequestAnimationFrame#isRunning + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isRunning = false; + + /** + * The callback to be invoked each step. + * + * @name Phaser.DOM.RequestAnimationFrame#callback + * @type {FrameRequestCallback} + * @since 3.0.0 + */ + this.callback = NOOP; + + /** + * The most recent timestamp. Either a DOMHighResTimeStamp under RAF or `Date.now` under SetTimeout. + * + * @name Phaser.DOM.RequestAnimationFrame#tick + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.tick = 0; + + /** + * True if the step is using setTimeout instead of RAF. + * + * @name Phaser.DOM.RequestAnimationFrame#isSetTimeOut + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isSetTimeOut = false; + + /** + * The setTimeout or RAF callback ID used when canceling them. + * + * @name Phaser.DOM.RequestAnimationFrame#timeOutID + * @type {?number} + * @default null + * @since 3.0.0 + */ + this.timeOutID = null; + + /** + * The previous time the step was called. + * + * @name Phaser.DOM.RequestAnimationFrame#lastTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.lastTime = 0; + + /** + * The target FPS rate in ms. + * Only used when setTimeout is used instead of RAF. + * + * @name Phaser.DOM.RequestAnimationFrame#target + * @type {number} + * @default 0 + * @since 3.21.0 + */ + this.target = 0; + + var _this = this; + + /** + * The RAF step function. + * Updates the local tick value, invokes the callback and schedules another call to requestAnimationFrame. + * + * @name Phaser.DOM.RequestAnimationFrame#step + * @type {FrameRequestCallback} + * @since 3.0.0 + */ + this.step = function step () + { + // Because we cannot trust the time passed to this callback from the browser and need it kept in sync with event times + var timestamp = window.performance.now(); + + // DOMHighResTimeStamp + _this.lastTime = _this.tick; + + _this.tick = timestamp; + + _this.callback(timestamp); + + _this.timeOutID = window.requestAnimationFrame(step); + }; + + /** + * The SetTimeout step function. + * Updates the local tick value, invokes the callback and schedules another call to setTimeout. + * + * @name Phaser.DOM.RequestAnimationFrame#stepTimeout + * @type {function} + * @since 3.0.0 + */ + this.stepTimeout = function stepTimeout () + { + var d = Date.now(); + + var delay = Math.min(Math.max(_this.target * 2 + _this.tick - d, 0), _this.target); + + _this.lastTime = _this.tick; + + _this.tick = d; + + _this.callback(d); + + _this.timeOutID = window.setTimeout(stepTimeout, delay); + }; + }, + + /** + * Starts the requestAnimationFrame or setTimeout process running. + * + * @method Phaser.DOM.RequestAnimationFrame#start + * @since 3.0.0 + * + * @param {FrameRequestCallback} callback - The callback to invoke each step. + * @param {boolean} forceSetTimeOut - Should it use SetTimeout, even if RAF is available? + * @param {number} targetFPS - The target fps rate (in ms). Only used when setTimeout is used. + */ + start: function (callback, forceSetTimeOut, targetFPS) + { + if (this.isRunning) + { + return; + } + + this.callback = callback; + + this.isSetTimeOut = forceSetTimeOut; + + this.target = targetFPS; + + this.isRunning = true; + + this.timeOutID = (forceSetTimeOut) ? window.setTimeout(this.stepTimeout, 0) : window.requestAnimationFrame(this.step); + }, + + /** + * Stops the requestAnimationFrame or setTimeout from running. + * + * @method Phaser.DOM.RequestAnimationFrame#stop + * @since 3.0.0 + */ + stop: function () + { + this.isRunning = false; + + if (this.isSetTimeOut) + { + clearTimeout(this.timeOutID); + } + else + { + window.cancelAnimationFrame(this.timeOutID); + } + }, + + /** + * Stops the step from running and clears the callback reference. + * + * @method Phaser.DOM.RequestAnimationFrame#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stop(); + + this.callback = NOOP; + } + +}); + +module.exports = RequestAnimationFrame; + + +/***/ }), +/* 369 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Events = __webpack_require__(21); + +/** + * The Visibility Handler is responsible for listening out for document level visibility change events. + * This includes `visibilitychange` if the browser supports it, and blur and focus events. It then uses + * the provided Event Emitter and fires the related events. + * + * @function Phaser.Core.VisibilityHandler + * @fires Phaser.Core.Events#BLUR + * @fires Phaser.Core.Events#FOCUS + * @fires Phaser.Core.Events#HIDDEN + * @fires Phaser.Core.Events#VISIBLE + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Game instance this Visibility Handler is working on. + */ +var VisibilityHandler = function (game) +{ + var hiddenVar; + var eventEmitter = game.events; + + if (document.hidden !== undefined) + { + hiddenVar = 'visibilitychange'; + } + else + { + var vendors = [ 'webkit', 'moz', 'ms' ]; + + vendors.forEach(function (prefix) + { + if (document[prefix + 'Hidden'] !== undefined) + { + document.hidden = function () + { + return document[prefix + 'Hidden']; + }; + + hiddenVar = prefix + 'visibilitychange'; + } + + }); + } + + var onChange = function (event) + { + if (document.hidden || event.type === 'pause') + { + eventEmitter.emit(Events.HIDDEN); + } + else + { + eventEmitter.emit(Events.VISIBLE); + } + }; + + if (hiddenVar) + { + document.addEventListener(hiddenVar, onChange, false); + } + + window.onblur = function () + { + eventEmitter.emit(Events.BLUR); + }; + + window.onfocus = function () + { + eventEmitter.emit(Events.FOCUS); + }; + + // Automatically give the window focus unless config says otherwise + if (window.focus && game.config.autoFocus) + { + window.focus(); + } +}; + +module.exports = VisibilityHandler; + + +/***/ }), +/* 370 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Arne16 = __webpack_require__(371); +var CanvasPool = __webpack_require__(28); +var GetValue = __webpack_require__(5); + +/** + * [description] + * + * @function Phaser.Create.GenerateTexture + * @since 3.0.0 + * + * @param {Phaser.Types.Create.GenerateTextureConfig} config - [description] + * + * @return {HTMLCanvasElement} [description] + */ +var GenerateTexture = function (config) +{ + var data = GetValue(config, 'data', []); + var canvas = GetValue(config, 'canvas', null); + var palette = GetValue(config, 'palette', Arne16); + var pixelWidth = GetValue(config, 'pixelWidth', 1); + var pixelHeight = GetValue(config, 'pixelHeight', pixelWidth); + var resizeCanvas = GetValue(config, 'resizeCanvas', true); + var clearCanvas = GetValue(config, 'clearCanvas', true); + var preRender = GetValue(config, 'preRender', null); + var postRender = GetValue(config, 'postRender', null); + + var width = Math.floor(Math.abs(data[0].length * pixelWidth)); + var height = Math.floor(Math.abs(data.length * pixelHeight)); + + if (!canvas) + { + canvas = CanvasPool.create2D(this, width, height); + resizeCanvas = false; + clearCanvas = false; + } + + if (resizeCanvas) + { + canvas.width = width; + canvas.height = height; + } + + var ctx = canvas.getContext('2d'); + + if (clearCanvas) + { + ctx.clearRect(0, 0, width, height); + } + + // preRender Callback? + if (preRender) + { + preRender(canvas, ctx); + } + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + ctx.fillStyle = palette[d]; + ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + // postRender Callback? + if (postRender) + { + postRender(canvas, ctx); + } + + return canvas; +}; + +module.exports = GenerateTexture; + + +/***/ }), +/* 371 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) + * + * @name Phaser.Create.Palettes.ARNE16 + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#9D9D9D', + 2: '#FFF', + 3: '#BE2633', + 4: '#E06F8B', + 5: '#493C2B', + 6: '#A46422', + 7: '#EB8931', + 8: '#F7E26B', + 9: '#2F484E', + A: '#44891A', + B: '#A3CE27', + C: '#1B2632', + D: '#005784', + E: '#31A2F2', + F: '#B2DCEF' +}; + + +/***/ }), +/* 372 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = __webpack_require__(0); +var CubicBezier = __webpack_require__(343); +var Curve = __webpack_require__(86); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A higher-order Bézier curve constructed of four points. + * + * @class CubicBezier + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector2[])} p0 - Start point, or an array of point pairs. + * @param {Phaser.Math.Vector2} p1 - Control Point 1. + * @param {Phaser.Math.Vector2} p2 - Control Point 2. + * @param {Phaser.Math.Vector2} p3 - End Point. + */ +var CubicBezierCurve = new Class({ + + Extends: Curve, + + initialize: + + function CubicBezierCurve (p0, p1, p2, p3) + { + Curve.call(this, 'CubicBezierCurve'); + + if (Array.isArray(p0)) + { + p3 = new Vector2(p0[6], p0[7]); + p2 = new Vector2(p0[4], p0[5]); + p1 = new Vector2(p0[2], p0[3]); + p0 = new Vector2(p0[0], p0[1]); + } + + /** + * The start point of this curve. + * + * @name Phaser.Curves.CubicBezier#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = p0; + + /** + * The first control point of this curve. + * + * @name Phaser.Curves.CubicBezier#p1 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p1 = p1; + + /** + * The second control point of this curve. + * + * @name Phaser.Curves.CubicBezier#p2 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p2 = p2; + + /** + * The end point of this curve. + * + * @name Phaser.Curves.CubicBezier#p3 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p3 = p3; + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.CubicBezier#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * Returns the resolution of this curve. + * + * @method Phaser.Curves.CubicBezier#getResolution + * @since 3.0.0 + * + * @param {number} divisions - The amount of divisions used by this curve. + * + * @return {number} The resolution of the curve. + */ + getResolution: function (divisions) + { + return divisions; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.CubicBezier#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var p0 = this.p0; + var p1 = this.p1; + var p2 = this.p2; + var p3 = this.p3; + + return out.set(CubicBezier(t, p0.x, p1.x, p2.x, p3.x), CubicBezier(t, p0.y, p1.y, p2.y, p3.y)); + }, + + /** + * Draws this curve to the specified graphics object. + * + * @method Phaser.Curves.CubicBezier#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The graphics object this curve should be drawn to. + * @param {integer} [pointsTotal=32] - The number of intermediary points that make up this curve. A higher number of points will result in a smoother curve. + * + * @return {Phaser.GameObjects.Graphics} The graphics object this curve was drawn to. Useful for method chaining. + */ + draw: function (graphics, pointsTotal) + { + if (pointsTotal === undefined) { pointsTotal = 32; } + + var points = this.getPoints(pointsTotal); + + graphics.beginPath(); + graphics.moveTo(this.p0.x, this.p0.y); + + for (var i = 1; i < points.length; i++) + { + graphics.lineTo(points[i].x, points[i].y); + } + + graphics.strokePath(); + + // So you can chain graphics calls + return graphics; + }, + + /** + * Returns a JSON object that describes this curve. + * + * @method Phaser.Curves.CubicBezier#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + points: [ + this.p0.x, this.p0.y, + this.p1.x, this.p1.y, + this.p2.x, this.p2.y, + this.p3.x, this.p3.y + ] + }; + } + +}); + +/** + * Generates a curve from a JSON object. + * + * @function Phaser.Curves.CubicBezier.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.CubicBezier} The curve generated from the JSON object. + */ +CubicBezierCurve.fromJSON = function (data) +{ + var points = data.points; + + var p0 = new Vector2(points[0], points[1]); + var p1 = new Vector2(points[2], points[3]); + var p2 = new Vector2(points[4], points[5]); + var p3 = new Vector2(points[6], points[7]); + + return new CubicBezierCurve(p0, p1, p2, p3); +}; + +module.exports = CubicBezierCurve; + + +/***/ }), +/* 373 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = __webpack_require__(0); +var Curve = __webpack_require__(86); +var DegToRad = __webpack_require__(40); +var GetValue = __webpack_require__(5); +var RadToDeg = __webpack_require__(184); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * An Elliptical Curve derived from the Base Curve class. + * + * See https://en.wikipedia.org/wiki/Elliptic_curve 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 {integer} [startAngle=0] - The start angle of the ellipse, in degrees. + * @param {integer} [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 {integer} [rotation=0] - The rotation of the ellipse, in degrees. + */ +var EllipseCurve = new Class({ + + Extends: Curve, + + initialize: + + function EllipseCurve (x, y, xRadius, yRadius, startAngle, endAngle, clockwise, rotation) + { + if (typeof x === 'object') + { + var config = x; + + x = GetValue(config, 'x', 0); + y = GetValue(config, 'y', 0); + xRadius = GetValue(config, 'xRadius', 0); + yRadius = GetValue(config, 'yRadius', xRadius); + startAngle = GetValue(config, 'startAngle', 0); + endAngle = GetValue(config, 'endAngle', 360); + clockwise = GetValue(config, 'clockwise', false); + rotation = GetValue(config, 'rotation', 0); + } + else + { + if (yRadius === undefined) { yRadius = xRadius; } + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 360; } + if (clockwise === undefined) { clockwise = false; } + if (rotation === undefined) { rotation = 0; } + } + + Curve.call(this, 'EllipseCurve'); + + // Center point + + /** + * The center point of the ellipse. Used for calculating rotation. + * + * @name Phaser.Curves.Ellipse#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = new Vector2(x, y); + + /** + * The horizontal radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#_xRadius + * @type {number} + * @private + * @since 3.0.0 + */ + this._xRadius = xRadius; + + /** + * The vertical radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#_yRadius + * @type {number} + * @private + * @since 3.0.0 + */ + this._yRadius = yRadius; + + // Radians + + /** + * The starting angle of the ellipse in radians. + * + * @name Phaser.Curves.Ellipse#_startAngle + * @type {number} + * @private + * @since 3.0.0 + */ + this._startAngle = DegToRad(startAngle); + + /** + * The end angle of the ellipse in radians. + * + * @name Phaser.Curves.Ellipse#_endAngle + * @type {number} + * @private + * @since 3.0.0 + */ + this._endAngle = DegToRad(endAngle); + + /** + * Anti-clockwise direction. + * + * @name Phaser.Curves.Ellipse#_clockwise + * @type {boolean} + * @private + * @since 3.0.0 + */ + this._clockwise = clockwise; + + /** + * The rotation of the arc. + * + * @name Phaser.Curves.Ellipse#_rotation + * @type {number} + * @private + * @since 3.0.0 + */ + this._rotation = DegToRad(rotation); + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.Ellipse#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPoint(0, out); + }, + + /** + * [description] + * + * @method Phaser.Curves.Ellipse#getResolution + * @since 3.0.0 + * + * @param {number} divisions - [description] + * + * @return {number} [description] + */ + getResolution: function (divisions) + { + return divisions * 2; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.Ellipse#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var twoPi = Math.PI * 2; + var deltaAngle = this._endAngle - this._startAngle; + var samePoints = Math.abs(deltaAngle) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while (deltaAngle < 0) + { + deltaAngle += twoPi; + } + + while (deltaAngle > twoPi) + { + deltaAngle -= twoPi; + } + + if (deltaAngle < Number.EPSILON) + { + if (samePoints) + { + deltaAngle = 0; + } + else + { + deltaAngle = twoPi; + } + } + + if (this._clockwise && !samePoints) + { + if (deltaAngle === twoPi) + { + deltaAngle = - twoPi; + } + else + { + deltaAngle = deltaAngle - twoPi; + } + } + + var angle = this._startAngle + t * deltaAngle; + var x = this.p0.x + this._xRadius * Math.cos(angle); + var y = this.p0.y + this._yRadius * Math.sin(angle); + + if (this._rotation !== 0) + { + var cos = Math.cos(this._rotation); + var sin = Math.sin(this._rotation); + + var tx = x - this.p0.x; + var ty = y - this.p0.y; + + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.p0.x; + y = tx * sin + ty * cos + this.p0.y; + } + + return out.set(x, y); + }, + + /** + * Sets the horizontal radius of this curve. + * + * @method Phaser.Curves.Ellipse#setXRadius + * @since 3.0.0 + * + * @param {number} value - The horizontal radius of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setXRadius: function (value) + { + this.xRadius = value; + + return this; + }, + + /** + * Sets the vertical radius of this curve. + * + * @method Phaser.Curves.Ellipse#setYRadius + * @since 3.0.0 + * + * @param {number} value - The vertical radius of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setYRadius: function (value) + { + this.yRadius = value; + + return this; + }, + + /** + * Sets the width of this curve. + * + * @method Phaser.Curves.Ellipse#setWidth + * @since 3.0.0 + * + * @param {number} value - The width of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setWidth: function (value) + { + this.xRadius = value * 2; + + return this; + }, + + /** + * Sets the height of this curve. + * + * @method Phaser.Curves.Ellipse#setHeight + * @since 3.0.0 + * + * @param {number} value - The height of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setHeight: function (value) + { + this.yRadius = value * 2; + + return this; + }, + + /** + * Sets the start angle of this curve. + * + * @method Phaser.Curves.Ellipse#setStartAngle + * @since 3.0.0 + * + * @param {number} value - The start angle of this curve, in radians. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setStartAngle: function (value) + { + this.startAngle = value; + + return this; + }, + + /** + * Sets the end angle of this curve. + * + * @method Phaser.Curves.Ellipse#setEndAngle + * @since 3.0.0 + * + * @param {number} value - The end angle of this curve, in radians. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setEndAngle: function (value) + { + this.endAngle = value; + + return this; + }, + + /** + * Sets if this curve extends clockwise or anti-clockwise. + * + * @method Phaser.Curves.Ellipse#setClockwise + * @since 3.0.0 + * + * @param {boolean} value - The clockwise state of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setClockwise: function (value) + { + this.clockwise = value; + + return this; + }, + + /** + * Sets the rotation of this curve. + * + * @method Phaser.Curves.Ellipse#setRotation + * @since 3.0.0 + * + * @param {number} value - The rotation of this curve, in radians. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setRotation: function (value) + { + this.rotation = value; + + return this; + }, + + /** + * The x coordinate of the center of the ellipse. + * + * @name Phaser.Curves.Ellipse#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.p0.x; + }, + + set: function (value) + { + this.p0.x = value; + } + + }, + + /** + * The y coordinate of the center of the ellipse. + * + * @name Phaser.Curves.Ellipse#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.p0.y; + }, + + set: function (value) + { + this.p0.y = value; + } + + }, + + /** + * The horizontal radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#xRadius + * @type {number} + * @since 3.0.0 + */ + xRadius: { + + get: function () + { + return this._xRadius; + }, + + set: function (value) + { + this._xRadius = value; + } + + }, + + /** + * The vertical radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#yRadius + * @type {number} + * @since 3.0.0 + */ + yRadius: { + + get: function () + { + return this._yRadius; + }, + + set: function (value) + { + this._yRadius = value; + } + + }, + + /** + * The start angle of the ellipse in degrees. + * + * @name Phaser.Curves.Ellipse#startAngle + * @type {number} + * @since 3.0.0 + */ + startAngle: { + + get: function () + { + return RadToDeg(this._startAngle); + }, + + set: function (value) + { + this._startAngle = DegToRad(value); + } + + }, + + /** + * The end angle of the ellipse in degrees. + * + * @name Phaser.Curves.Ellipse#endAngle + * @type {number} + * @since 3.0.0 + */ + endAngle: { + + get: function () + { + return RadToDeg(this._endAngle); + }, + + set: function (value) + { + this._endAngle = DegToRad(value); + } + + }, + + /** + * `true` if the ellipse rotation is clockwise or `false` if anti-clockwise. + * + * @name Phaser.Curves.Ellipse#clockwise + * @type {boolean} + * @since 3.0.0 + */ + clockwise: { + + get: function () + { + return this._clockwise; + }, + + set: function (value) + { + this._clockwise = value; + } + + }, + + /** + * The rotation of the ellipse, relative to the center, in degrees. + * + * @name Phaser.Curves.Ellipse#angle + * @type {number} + * @since 3.14.0 + */ + angle: { + + get: function () + { + return RadToDeg(this._rotation); + }, + + set: function (value) + { + this._rotation = DegToRad(value); + } + + }, + + /** + * The rotation of the ellipse, relative to the center, in radians. + * + * @name Phaser.Curves.Ellipse#rotation + * @type {number} + * @since 3.0.0 + */ + rotation: { + + get: function () + { + return this._rotation; + }, + + set: function (value) + { + this._rotation = value; + } + + }, + + /** + * JSON serialization of the curve. + * + * @method Phaser.Curves.Ellipse#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONEllipseCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + x: this.p0.x, + y: this.p0.y, + xRadius: this._xRadius, + yRadius: this._yRadius, + startAngle: RadToDeg(this._startAngle), + endAngle: RadToDeg(this._endAngle), + clockwise: this._clockwise, + rotation: RadToDeg(this._rotation) + }; + } + +}); + +/** + * Creates a curve from the provided Ellipse Curve Configuration object. + * + * @function Phaser.Curves.Ellipse.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONEllipseCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.Ellipse} The ellipse curve constructed from the configuration object. + */ +EllipseCurve.fromJSON = function (data) +{ + return new EllipseCurve(data); +}; + +module.exports = EllipseCurve; + + +/***/ }), +/* 374 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = __webpack_require__(0); +var Curve = __webpack_require__(86); +var FromPoints = __webpack_require__(189); +var Rectangle = __webpack_require__(11); +var Vector2 = __webpack_require__(3); + +var tmpVec2 = new Vector2(); + +/** + * @classdesc + * A LineCurve is a "curve" comprising exactly two points (a line segment). + * + * @class Line + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|number[])} p0 - The first endpoint. + * @param {Phaser.Math.Vector2} [p1] - The second endpoint. + */ +var LineCurve = new Class({ + + Extends: Curve, + + initialize: + + // vec2s or array + function LineCurve (p0, p1) + { + Curve.call(this, 'LineCurve'); + + if (Array.isArray(p0)) + { + p1 = new Vector2(p0[2], p0[3]); + p0 = new Vector2(p0[0], p0[1]); + } + + /** + * The first endpoint. + * + * @name Phaser.Curves.Line#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = p0; + + /** + * The second endpoint. + * + * @name Phaser.Curves.Line#p1 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p1 = p1; + + // Override default Curve.arcLengthDivisions + + /** + * The quantity of arc length divisions within the curve. + * + * @name Phaser.Curves.Line#arcLengthDivisions + * @type {integer} + * @default 1 + * @since 3.0.0 + */ + this.arcLengthDivisions = 1; + }, + + /** + * Returns a Rectangle where the position and dimensions match the bounds of this Curve. + * + * @method Phaser.Curves.Line#getBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the bounds in. If not given a new Rectangle will be created. + * + * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object. + */ + getBounds: function (out) + { + if (out === undefined) { out = new Rectangle(); } + + return FromPoints([ this.p0, this.p1 ], out); + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.Line#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * Gets the resolution of the line. + * + * @method Phaser.Curves.Line#getResolution + * @since 3.0.0 + * + * @param {number} [divisions=1] - The number of divisions to consider. + * + * @return {number} The resolution. Equal to the number of divisions. + */ + getResolution: function (divisions) + { + if (divisions === undefined) { divisions = 1; } + + return divisions; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.Line#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + if (t === 1) + { + return out.copy(this.p1); + } + + out.copy(this.p1).subtract(this.p0).scale(t).add(this.p0); + + return out; + }, + + // Line curve is linear, so we can overwrite default getPointAt + + /** + * Gets a point at a given position on the line. + * + * @method Phaser.Curves.Line#getPointAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPointAt: function (u, out) + { + return this.getPoint(u, out); + }, + + /** + * Gets the slope of the line as a unit vector. + * + * @method Phaser.Curves.Line#getTangent + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @return {Phaser.Math.Vector2} The tangent vector. + */ + getTangent: function () + { + var tangent = tmpVec2.copy(this.p1).subtract(this.p0); + + return tangent.normalize(); + }, + + // Override default Curve.getUtoTmapping + + /** + * [description] + * + * @method Phaser.Curves.Line#getUtoTmapping + * @since 3.0.0 + * + * @param {number} u - [description] + * @param {integer} distance - [description] + * @param {integer} [divisions] - [description] + * + * @return {number} [description] + */ + getUtoTmapping: function (u, distance, divisions) + { + var t; + + if (distance) + { + var arcLengths = this.getLengths(divisions); + var lineLength = arcLengths[arcLengths.length - 1]; + + // Cannot overshoot the curve + var targetLineLength = Math.min(distance, lineLength); + + t = targetLineLength / lineLength; + } + else + { + t = u; + } + + return t; + }, + + // Override default Curve.draw because this is better than calling getPoints on a line! + + /** + * Draws this curve on the given Graphics object. + * + * The curve is drawn using `Graphics.lineBetween` so will be drawn at whatever the present Graphics line color is. + * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. + * + * @method Phaser.Curves.Line#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn. + * + * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn. + */ + draw: function (graphics) + { + graphics.lineBetween(this.p0.x, this.p0.y, this.p1.x, this.p1.y); + + // So you can chain graphics calls + return graphics; + }, + + /** + * Gets a JSON representation of the line. + * + * @method Phaser.Curves.Line#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + points: [ + this.p0.x, this.p0.y, + this.p1.x, this.p1.y + ] + }; + } + +}); + +/** + * Configures this line from a JSON representation. + * + * @function Phaser.Curves.Line.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.Line} A new LineCurve object. + */ +LineCurve.fromJSON = function (data) +{ + var points = data.points; + + var p0 = new Vector2(points[0], points[1]); + var p1 = new Vector2(points[2], points[3]); + + return new LineCurve(p0, p1); +}; + +module.exports = LineCurve; + + +/***/ }), +/* 375 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Curve = __webpack_require__(86); +var QuadraticBezierInterpolation = __webpack_require__(344); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * [description] + * + * @class QuadraticBezier + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.2.0 + * + * @param {(Phaser.Math.Vector2|number[])} p0 - Start point, or an array of point pairs. + * @param {Phaser.Math.Vector2} p1 - Control Point 1. + * @param {Phaser.Math.Vector2} p2 - Control Point 2. + */ +var QuadraticBezier = new Class({ + + Extends: Curve, + + initialize: + + function QuadraticBezier (p0, p1, p2) + { + Curve.call(this, 'QuadraticBezier'); + + if (Array.isArray(p0)) + { + p2 = new Vector2(p0[4], p0[5]); + p1 = new Vector2(p0[2], p0[3]); + p0 = new Vector2(p0[0], p0[1]); + } + + /** + * [description] + * + * @name Phaser.Curves.QuadraticBezier#p0 + * @type {Phaser.Math.Vector2} + * @since 3.2.0 + */ + this.p0 = p0; + + /** + * [description] + * + * @name Phaser.Curves.QuadraticBezier#p1 + * @type {Phaser.Math.Vector2} + * @since 3.2.0 + */ + this.p1 = p1; + + /** + * [description] + * + * @name Phaser.Curves.QuadraticBezier#p2 + * @type {Phaser.Math.Vector2} + * @since 3.2.0 + */ + this.p2 = p2; + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.QuadraticBezier#getStartPoint + * @since 3.2.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * [description] + * + * @method Phaser.Curves.QuadraticBezier#getResolution + * @since 3.2.0 + * + * @param {number} divisions - [description] + * + * @return {number} [description] + */ + getResolution: function (divisions) + { + return divisions; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.QuadraticBezier#getPoint + * @since 3.2.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var p0 = this.p0; + var p1 = this.p1; + var p2 = this.p2; + + return out.set( + QuadraticBezierInterpolation(t, p0.x, p1.x, p2.x), + QuadraticBezierInterpolation(t, p0.y, p1.y, p2.y) + ); + }, + + /** + * [description] + * + * @method Phaser.Curves.QuadraticBezier#draw + * @since 3.2.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - `Graphics` object to draw onto. + * @param {integer} [pointsTotal=32] - Number of points to be used for drawing the curve. Higher numbers result in smoother curve but require more processing. + * + * @return {Phaser.GameObjects.Graphics} `Graphics` object that was drawn to. + */ + draw: function (graphics, pointsTotal) + { + if (pointsTotal === undefined) { pointsTotal = 32; } + + var points = this.getPoints(pointsTotal); + + graphics.beginPath(); + graphics.moveTo(this.p0.x, this.p0.y); + + for (var i = 1; i < points.length; i++) + { + graphics.lineTo(points[i].x, points[i].y); + } + + graphics.strokePath(); + + // So you can chain graphics calls + return graphics; + }, + + /** + * Converts the curve into a JSON compatible object. + * + * @method Phaser.Curves.QuadraticBezier#toJSON + * @since 3.2.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + points: [ + this.p0.x, this.p0.y, + this.p1.x, this.p1.y, + this.p2.x, this.p2.y + ] + }; + } + +}); + +/** + * Creates a curve from a JSON object, e. g. created by `toJSON`. + * + * @function Phaser.Curves.QuadraticBezier.fromJSON + * @since 3.2.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.QuadraticBezier} The created curve instance. + */ +QuadraticBezier.fromJSON = function (data) +{ + var points = data.points; + + var p0 = new Vector2(points[0], points[1]); + var p1 = new Vector2(points[2], points[3]); + var p2 = new Vector2(points[4], points[5]); + + return new QuadraticBezier(p0, p1, p2); +}; + +module.exports = QuadraticBezier; + + +/***/ }), +/* 376 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var CatmullRom = __webpack_require__(182); +var Class = __webpack_require__(0); +var Curve = __webpack_require__(86); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * Create a smooth 2d spline curve from a series of points. + * + * @class Spline + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2[]|number[]|number[][])} [points] - The points that configure the curve. + */ +var SplineCurve = new Class({ + + Extends: Curve, + + initialize: + + function SplineCurve (points) + { + if (points === undefined) { points = []; } + + Curve.call(this, 'SplineCurve'); + + /** + * The Vector2 points that configure the curve. + * + * @name Phaser.Curves.Spline#points + * @type {Phaser.Math.Vector2[]} + * @default [] + * @since 3.0.0 + */ + this.points = []; + + this.addPoints(points); + }, + + /** + * Add a list of points to the current list of Vector2 points of the curve. + * + * @method Phaser.Curves.Spline#addPoints + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2[]|number[]|number[][])} points - The points that configure the curve. + * + * @return {Phaser.Curves.Spline} This curve object. + */ + addPoints: function (points) + { + for (var i = 0; i < points.length; i++) + { + var p = new Vector2(); + + if (typeof points[i] === 'number') + { + p.x = points[i]; + p.y = points[i + 1]; + i++; + } + else if (Array.isArray(points[i])) + { + // An array of arrays? + p.x = points[i][0]; + p.y = points[i][1]; + } + else + { + p.x = points[i].x; + p.y = points[i].y; + } + + this.points.push(p); + } + + return this; + }, + + /** + * Add a point to the current list of Vector2 points of the curve. + * + * @method Phaser.Curves.Spline#addPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate of this curve + * @param {number} y - The y coordinate of this curve + * + * @return {Phaser.Math.Vector2} The new Vector2 added to the curve + */ + addPoint: function (x, y) + { + var vec = new Vector2(x, y); + + this.points.push(vec); + + return vec; + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.Spline#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.points[0]); + }, + + /** + * [description] + * + * @method Phaser.Curves.Spline#getResolution + * @since 3.0.0 + * + * @param {number} divisions - [description] + * + * @return {number} [description] + */ + getResolution: function (divisions) + { + return divisions * this.points.length; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.Spline#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var points = this.points; + + var point = (points.length - 1) * t; + + var intPoint = Math.floor(point); + + var weight = point - intPoint; + + var p0 = points[(intPoint === 0) ? intPoint : intPoint - 1]; + var p1 = points[intPoint]; + var p2 = points[(intPoint > points.length - 2) ? points.length - 1 : intPoint + 1]; + var p3 = points[(intPoint > points.length - 3) ? points.length - 1 : intPoint + 2]; + + return out.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); + }, + + /** + * Exports a JSON object containing this curve data. + * + * @method Phaser.Curves.Spline#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + var points = []; + + for (var i = 0; i < this.points.length; i++) + { + points.push(this.points[i].x); + points.push(this.points[i].y); + } + + return { + type: this.type, + points: points + }; + } + +}); + +/** + * Imports a JSON object containing this curve data. + * + * @function Phaser.Curves.Spline.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.Spline} The spline curve created. + */ +SplineCurve.fromJSON = function (data) +{ + return new SplineCurve(data.points); +}; + +module.exports = SplineCurve; + + +/***/ }), +/* 377 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A BaseShader is a small resource class that contains the data required for a WebGL Shader to be created. + * + * It contains the raw source code to the fragment and vertex shader, as well as an object that defines + * the uniforms the shader requires, if any. + * + * BaseShaders are stored in the Shader Cache, available in a Scene via `this.cache.shaders` and are referenced + * by a unique key-based string. Retrieve them via `this.cache.shaders.get(key)`. + * + * BaseShaders are created automatically by the GLSL File Loader when loading an external shader resource. + * They can also be created at runtime, allowing you to use dynamically generated shader source code. + * + * Default fragment and vertex source is used if not provided in the constructor, setting-up a basic shader, + * suitable for debug rendering. + * + * @class BaseShader + * @memberof Phaser.Display + * @constructor + * @since 3.17.0 + * + * @param {string} key - The key of this shader. Must be unique within the shader cache. + * @param {string} [fragmentSrc] - The fragment source for the shader. + * @param {string} [vertexSrc] - The vertex source for the shader. + * @param {any} [uniforms] - Optional object defining the uniforms the shader uses. + */ +var BaseShader = new Class({ + + initialize: + + function BaseShader (key, fragmentSrc, vertexSrc, uniforms) + { + if (!fragmentSrc || fragmentSrc === '') + { + fragmentSrc = [ + 'precision mediump float;', + + 'uniform vec2 resolution;', + + 'varying vec2 fragCoord;', + + 'void main () {', + ' vec2 uv = fragCoord / resolution.xy;', + ' gl_FragColor = vec4(uv.xyx, 1.0);', + '}' + ].join('\n'); + } + + if (!vertexSrc || vertexSrc === '') + { + vertexSrc = [ + 'precision mediump float;', + + 'uniform mat4 uProjectionMatrix;', + 'uniform mat4 uViewMatrix;', + 'uniform vec2 uResolution;', + + 'attribute vec2 inPosition;', + + 'varying vec2 fragCoord;', + + 'void main () {', + 'gl_Position = uProjectionMatrix * uViewMatrix * vec4(inPosition, 1.0, 1.0);', + 'fragCoord = vec2(inPosition.x, uResolution.y - inPosition.y);', + '}' + ].join('\n'); + } + + if (uniforms === undefined) { uniforms = null; } + + /** + * The key of this shader, unique within the shader cache of this Phaser game instance. + * + * @name Phaser.Display.BaseShader#key + * @type {string} + * @since 3.17.0 + */ + this.key = key; + + /** + * The source code, as a string, of the fragment shader being used. + * + * @name Phaser.Display.BaseShader#fragmentSrc + * @type {string} + * @since 3.17.0 + */ + this.fragmentSrc = fragmentSrc; + + /** + * The source code, as a string, of the vertex shader being used. + * + * @name Phaser.Display.BaseShader#vertexSrc + * @type {string} + * @since 3.17.0 + */ + this.vertexSrc = vertexSrc; + + /** + * The default uniforms for this shader. + * + * @name Phaser.Display.BaseShader#uniforms + * @type {?any} + * @since 3.17.0 + */ + this.uniforms = uniforms; + } + +}); + +module.exports = BaseShader; + + +/***/ }), +/* 378 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = __webpack_require__(36); + +Color.ColorToRGBA = __webpack_require__(834); +Color.ComponentToHex = __webpack_require__(379); +Color.GetColor = __webpack_require__(175); +Color.GetColor32 = __webpack_require__(314); +Color.HexStringToColor = __webpack_require__(313); +Color.HSLToColor = __webpack_require__(835); +Color.HSVColorWheel = __webpack_require__(836); +Color.HSVToRGB = __webpack_require__(176); +Color.HueToComponent = __webpack_require__(380); +Color.IntegerToColor = __webpack_require__(316); +Color.IntegerToRGB = __webpack_require__(317); +Color.Interpolate = __webpack_require__(837); +Color.ObjectToColor = __webpack_require__(318); +Color.RandomRGB = __webpack_require__(838); +Color.RGBStringToColor = __webpack_require__(319); +Color.RGBToHSV = __webpack_require__(315); +Color.RGBToString = __webpack_require__(839); +Color.ValueToColor = __webpack_require__(174); + +module.exports = Color; + + +/***/ }), +/* 379 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns a string containing a hex representation of the given color component. + * + * @function Phaser.Display.Color.ComponentToHex + * @since 3.0.0 + * + * @param {integer} color - The color channel to get the hex value for, must be a value between 0 and 255. + * + * @return {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ +var ComponentToHex = function (color) +{ + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; +}; + +module.exports = ComponentToHex; + + +/***/ }), +/* 380 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @function Phaser.Display.Color.HueToComponent + * @since 3.0.0 + * + * @param {number} p + * @param {number} q + * @param {number} t + * + * @return {number} The combined color value. + */ +var HueToComponent = function (p, q, t) +{ + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; +}; + +module.exports = HueToComponent; + + +/***/ }), +/* 381 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var OS = __webpack_require__(124); + +/** + * @callback ContentLoadedCallback + */ + +/** + * Inspects the readyState of the document. If the document is already complete then it invokes the given callback. + * If not complete it sets up several event listeners such as `deviceready`, and once those fire, it invokes the callback. + * Called automatically by the Phaser.Game instance. Should not usually be accessed directly. + * + * @function Phaser.DOM.DOMContentLoaded + * @since 3.0.0 + * + * @param {ContentLoadedCallback} callback - The callback to be invoked when the device is ready and the DOM content is loaded. + */ +var DOMContentLoaded = function (callback) +{ + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + callback(); + + return; + } + + var check = function () + { + document.removeEventListener('deviceready', check, true); + document.removeEventListener('DOMContentLoaded', check, true); + window.removeEventListener('load', check, true); + + callback(); + }; + + if (!document.body) + { + window.setTimeout(check, 20); + } + else if (OS.cordova) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + document.addEventListener('deviceready', check, false); + } + else + { + document.addEventListener('DOMContentLoaded', check, true); + window.addEventListener('load', check, true); + } +}; + +module.exports = DOMContentLoaded; + + +/***/ }), +/* 382 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(190); + +/** + * Attempts to determine the screen orientation using the Orientation API. + * + * @function Phaser.DOM.GetScreenOrientation + * @since 3.16.0 + * + * @param {number} width - The width of the viewport. + * @param {number} height - The height of the viewport. + * + * @return {string} The orientation. + */ +var GetScreenOrientation = function (width, height) +{ + var screen = window.screen; + var orientation = (screen) ? screen.orientation || screen.mozOrientation || screen.msOrientation : false; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz / ms-orientation are strings + return orientation; + } + + if (screen) + { + return (screen.height > screen.width) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; + } + else if (typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia('(orientation: portrait)').matches) + { + return CONST.ORIENTATION.PORTRAIT; + } + else if (window.matchMedia('(orientation: landscape)').matches) + { + return CONST.ORIENTATION.LANDSCAPE; + } + } + + return (height > width) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; +}; + +module.exports = GetScreenOrientation; + + +/***/ }), +/* 383 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for centering the game canvas. + * + * @namespace Phaser.Scale.Center + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for centering the game canvas. + * + * To find out what each mode does please see [Phaser.Scale.Center]{@link Phaser.Scale.Center}. + * + * @typedef {Phaser.Scale.Center} Phaser.Scale.CenterType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * The game canvas is not centered within the parent by Phaser. + * You can still center it yourself via CSS. + * + * @name Phaser.Scale.Center.NO_CENTER + * @type {integer} + * @const + * @since 3.16.0 + */ + NO_CENTER: 0, + + /** + * The game canvas is centered both horizontally and vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + * + * @name Phaser.Scale.Center.CENTER_BOTH + * @type {integer} + * @const + * @since 3.16.0 + */ + CENTER_BOTH: 1, + + /** + * The game canvas is centered horizontally within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + * + * @name Phaser.Scale.Center.CENTER_HORIZONTALLY + * @type {integer} + * @const + * @since 3.16.0 + */ + CENTER_HORIZONTALLY: 2, + + /** + * The game canvas is centered both vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + * + * @name Phaser.Scale.Center.CENTER_VERTICALLY + * @type {integer} + * @const + * @since 3.16.0 + */ + CENTER_VERTICALLY: 3 + +}; + + +/***/ }), +/* 384 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for orientation. + * + * @namespace Phaser.Scale.Orientation + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for orientation. + * + * To find out what each mode does please see [Phaser.Scale.Orientation]{@link Phaser.Scale.Orientation}. + * + * @typedef {Phaser.Scale.Orientation} Phaser.Scale.OrientationType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * A landscape orientation. + * + * @name Phaser.Scale.Orientation.LANDSCAPE + * @type {string} + * @const + * @since 3.16.0 + */ + LANDSCAPE: 'landscape-primary', + + /** + * A portrait orientation. + * + * @name Phaser.Scale.Orientation.PORTRAIT + * @type {string} + * @const + * @since 3.16.0 + */ + PORTRAIT: 'portrait-primary' + +}; + + +/***/ }), +/* 385 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for the different scale modes available. + * + * @namespace Phaser.Scale.ScaleModes + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for the different scale modes available. + * + * To find out what each mode does please see [Phaser.Scale.ScaleModes]{@link Phaser.Scale.ScaleModes}. + * + * @typedef {Phaser.Scale.ScaleModes} Phaser.Scale.ScaleModeType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it + * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need + * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. + * + * @name Phaser.Scale.ScaleModes.NONE + * @type {integer} + * @const + * @since 3.16.0 + */ + NONE: 0, + + /** + * The height is automatically adjusted based on the width. + * + * @name Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT + * @type {integer} + * @const + * @since 3.16.0 + */ + WIDTH_CONTROLS_HEIGHT: 1, + + /** + * The width is automatically adjusted based on the height. + * + * @name Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH + * @type {integer} + * @const + * @since 3.16.0 + */ + HEIGHT_CONTROLS_WIDTH: 2, + + /** + * 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. + * + * @name Phaser.Scale.ScaleModes.FIT + * @type {integer} + * @const + * @since 3.16.0 + */ + FIT: 3, + + /** + * 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. + * + * @name Phaser.Scale.ScaleModes.ENVELOP + * @type {integer} + * @const + * @since 3.16.0 + */ + ENVELOP: 4, + + /** + * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. + * + * @name Phaser.Scale.ScaleModes.RESIZE + * @type {integer} + * @const + * @since 3.16.0 + */ + RESIZE: 5 + +}; + + +/***/ }), +/* 386 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for zoom modes. + * + * @namespace Phaser.Scale.Zoom + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for zoom modes. + * + * To find out what each mode does please see [Phaser.Scale.Zoom]{@link Phaser.Scale.Zoom}. + * + * @typedef {Phaser.Scale.Zoom} Phaser.Scale.ZoomType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * The game canvas will not be zoomed by Phaser. + * + * @name Phaser.Scale.Zoom.NO_ZOOM + * @type {integer} + * @const + * @since 3.16.0 + */ + NO_ZOOM: 1, + + /** + * The game canvas will be 2x zoomed by Phaser. + * + * @name Phaser.Scale.Zoom.ZOOM_2X + * @type {integer} + * @const + * @since 3.16.0 + */ + ZOOM_2X: 2, + + /** + * The game canvas will be 4x zoomed by Phaser. + * + * @name Phaser.Scale.Zoom.ZOOM_4X + * @type {integer} + * @const + * @since 3.16.0 + */ + ZOOM_4X: 4, + + /** + * 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 {integer} + * @const + * @since 3.16.0 + */ + MAX_ZOOM: -1 + +}; + + +/***/ }), +/* 387 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var GetTarget = function (element) +{ + var target; + + if (element !== '') + { + if (typeof element === 'string') + { + // Hopefully an element ID + target = document.getElementById(element); + } + else if (element && element.nodeType === 1) + { + // Quick test for a HTMLElement + target = element; + } + } + + // Fallback to the document body. Covers an invalid ID and a non HTMLElement object. + if (!target) + { + // Use the full window + target = document.body; + } + + return target; +}; + +module.exports = GetTarget; + + +/***/ }), +/* 388 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes the given data string and parses it as XML. + * First tries to use the window.DOMParser and reverts to the Microsoft.XMLDOM if that fails. + * The parsed XML object is returned, or `null` if there was an error while parsing the data. + * + * @function Phaser.DOM.ParseXML + * @since 3.0.0 + * + * @param {string} data - The XML source stored in a string. + * + * @return {?(DOMParser|ActiveXObject)} The parsed XML data, or `null` if the data could not be parsed. + */ +var ParseXML = function (data) +{ + var xml = ''; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, 'text/xml'); + } + else + { + xml = new ActiveXObject('Microsoft.XMLDOM'); + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName('parsererror').length) + { + return null; + } + else + { + return xml; + } +}; + +module.exports = ParseXML; + + +/***/ }), +/* 389 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(192); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(56); +var GameEvents = __webpack_require__(21); +var Keyboard = __webpack_require__(390); +var Mouse = __webpack_require__(391); +var Pointer = __webpack_require__(392); +var Touch = __webpack_require__(393); +var TransformMatrix = __webpack_require__(35); +var TransformXY = __webpack_require__(351); + +/** + * @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. + */ +var InputManager = new Class({ + + initialize: + + function InputManager (game, config) + { + /** + * The Game instance that owns the Input Manager. + * A Game only maintains on instance of the Input Manager at any time. + * + * @name Phaser.Input.InputManager#game + * @type {Phaser.Game} + * @readonly + * @since 3.0.0 + */ + this.game = game; + + /** + * A reference to the global Game Scale Manager. + * Used for all bounds checks and pointer scaling. + * + * @name Phaser.Input.InputManager#scaleManager + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.0 + */ + this.scaleManager; + + /** + * The Canvas that is used for all DOM event input listeners. + * + * @name Phaser.Input.InputManager#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas; + + /** + * The Game Configuration object, as set during the game boot. + * + * @name Phaser.Input.InputManager#config + * @type {Phaser.Core.Config} + * @since 3.0.0 + */ + this.config = config; + + /** + * If set, the Input Manager will run its update loop every frame. + * + * @name Phaser.Input.InputManager#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The Event Emitter instance that the Input Manager uses to emit events from. + * + * @name Phaser.Input.InputManager#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = new EventEmitter(); + + /** + * Are any mouse or touch pointers currently over the game canvas? + * This is updated automatically by the canvas over and out handlers. + * + * @name Phaser.Input.InputManager#isOver + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + this.isOver = true; + + /** + * The default CSS cursor to be used when interacting with your game. + * + * See the `setDefaultCursor` method for more details. + * + * @name Phaser.Input.InputManager#defaultCursor + * @type {string} + * @since 3.10.0 + */ + this.defaultCursor = ''; + + /** + * A reference to the Keyboard Manager class, if enabled via the `input.keyboard` Game Config property. + * + * @name Phaser.Input.InputManager#keyboard + * @type {?Phaser.Input.Keyboard.KeyboardManager} + * @since 3.16.0 + */ + this.keyboard = (config.inputKeyboard) ? new Keyboard(this) : null; + + /** + * A reference to the Mouse Manager class, if enabled via the `input.mouse` Game Config property. + * + * @name Phaser.Input.InputManager#mouse + * @type {?Phaser.Input.Mouse.MouseManager} + * @since 3.0.0 + */ + this.mouse = (config.inputMouse) ? new Mouse(this) : null; + + /** + * A reference to the Touch Manager class, if enabled via the `input.touch` Game Config property. + * + * @name Phaser.Input.InputManager#touch + * @type {Phaser.Input.Touch.TouchManager} + * @since 3.0.0 + */ + this.touch = (config.inputTouch) ? new Touch(this) : null; + + /** + * An array of Pointers that have been added to the game. + * The first entry is reserved for the Mouse Pointer, the rest are Touch Pointers. + * + * By default there is 1 touch pointer enabled. If you need more use the `addPointer` method to start them, + * or set the `input.activePointers` property in the Game Config. + * + * @name Phaser.Input.InputManager#pointers + * @type {Phaser.Input.Pointer[]} + * @since 3.10.0 + */ + this.pointers = []; + + /** + * The number of touch objects activated and being processed each update. + * + * You can change this by either calling `addPointer` at run-time, or by + * setting the `input.activePointers` property in the Game Config. + * + * @name Phaser.Input.InputManager#pointersTotal + * @type {integer} + * @readonly + * @since 3.10.0 + */ + this.pointersTotal = config.inputActivePointers; + + if (config.inputTouch && this.pointersTotal === 1) + { + this.pointersTotal = 2; + } + + for (var i = 0; i <= this.pointersTotal; i++) + { + var pointer = new Pointer(this, i); + + pointer.smoothFactor = config.inputSmoothFactor; + + this.pointers.push(pointer); + } + + /** + * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. + * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` + * which will always map to the most recently interacted pointer. + * + * @name Phaser.Input.InputManager#mousePointer + * @type {?Phaser.Input.Pointer} + * @since 3.10.0 + */ + this.mousePointer = (config.inputMouse) ? this.pointers[0] : null; + + /** + * 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 + */ + this.activePointer = this.pointers[0]; + + /** + * If the top-most Scene in the Scene List receives an input it will stop input from + * propagating any lower down the scene list, i.e. if you have a UI Scene at the top + * and click something on it, that click will not then be passed down to any other + * Scene below. Disable this to have input events passed through all Scenes, all the time. + * + * @name Phaser.Input.InputManager#globalTopOnly + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.globalTopOnly = true; + + /** + * The time this Input Manager was last updated. + * This value is populated by the Game Step each frame. + * + * @name Phaser.Input.InputManager#time + * @type {number} + * @readonly + * @since 3.16.2 + */ + this.time = 0; + + /** + * A re-cycled point-like object to store hit test values in. + * + * @name Phaser.Input.InputManager#_tempPoint + * @type {{x:number, y:number}} + * @private + * @since 3.0.0 + */ + this._tempPoint = { x: 0, y: 0 }; + + /** + * A re-cycled array to store hit results in. + * + * @name Phaser.Input.InputManager#_tempHitTest + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this._tempHitTest = []; + + /** + * A re-cycled matrix used in hit test calculations. + * + * @name Phaser.Input.InputManager#_tempMatrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.4.0 + */ + this._tempMatrix = new TransformMatrix(); + + /** + * A re-cycled matrix used in hit test calculations. + * + * @name Phaser.Input.InputManager#_tempMatrix2 + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * An internal private var that records Scenes aborting event processing. + * + * @name Phaser.Input.InputManager#_tempSkip + * @type {boolean} + * @private + * @since 3.18.0 + */ + this._tempSkip = false; + + /** + * An internal private array that avoids needing to create a new array on every DOM mouse event. + * + * @name Phaser.Input.InputManager#mousePointerContainer + * @type {Phaser.Input.Pointer[]} + * @private + * @since 3.18.0 + */ + this.mousePointerContainer = [ this.mousePointer ]; + + game.events.once(GameEvents.BOOT, this.boot, this); + }, + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * The renderer is available by now. + * + * @method Phaser.Input.InputManager#boot + * @protected + * @fires Phaser.Input.Events#MANAGER_BOOT + * @since 3.0.0 + */ + boot: function () + { + this.canvas = this.game.canvas; + + this.scaleManager = this.game.scale; + + this.events.emit(Events.MANAGER_BOOT); + + this.game.events.on(GameEvents.PRE_RENDER, this.preRender, this); + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Internal canvas state change, called automatically by the Mouse Manager. + * + * @method Phaser.Input.InputManager#setCanvasOver + * @fires Phaser.Input.Events#GAME_OVER + * @private + * @since 3.16.0 + * + * @param {(MouseEvent|TouchEvent)} event - The DOM Event. + */ + setCanvasOver: function (event) + { + this.isOver = true; + + this.events.emit(Events.GAME_OVER, event); + }, + + /** + * Internal canvas state change, called automatically by the Mouse Manager. + * + * @method Phaser.Input.InputManager#setCanvasOut + * @fires Phaser.Input.Events#GAME_OUT + * @private + * @since 3.16.0 + * + * @param {(MouseEvent|TouchEvent)} event - The DOM Event. + */ + setCanvasOut: function (event) + { + this.isOver = false; + + this.events.emit(Events.GAME_OUT, event); + }, + + /** + * Internal update, called automatically by the Game Step right at the start. + * + * @method Phaser.Input.InputManager#preRender + * @private + * @since 3.18.0 + */ + preRender: function () + { + var time = this.game.loop.now; + var delta = this.game.loop.delta; + var scenes = this.game.scene.getScenes(true, true); + + this.time = time; + + this.events.emit(Events.MANAGER_UPDATE); + + for (var i = 0; i < scenes.length; i++) + { + var scene = scenes[i]; + + if (scene.sys.input && scene.sys.input.updatePoll(time, delta) && this.globalTopOnly) + { + // If the Scene returns true, it means it captured some input that no other Scene should get, so we bail out + return; + } + } + }, + + /** + * 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. + */ + setDefaultCursor: function (cursor) + { + this.defaultCursor = cursor; + + if (this.canvas.style.cursor !== cursor) + { + this.canvas.style.cursor = 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. + */ + setCursor: function (interactiveObject) + { + if (interactiveObject.cursor) + { + this.canvas.style.cursor = interactiveObject.cursor; + } + }, + + /** + * Called by the InputPlugin when processing over and out events. + * + * Tells the Input Manager to clear the hand cursor, if set, during its postUpdate step. + * + * @method Phaser.Input.InputManager#resetCursor + * @private + * @since 3.10.0 + * + * @param {Phaser.Types.Input.InteractiveObject} interactiveObject - The Interactive Object that called this method. + */ + resetCursor: function (interactiveObject) + { + if (interactiveObject.cursor && this.canvas) + { + this.canvas.style.cursor = this.defaultCursor; + } + }, + + /** + * Adds new Pointer objects to the Input Manager. + * + * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. + * + * You can create more either by calling this method, or by setting the `input.activePointers` property + * in the Game Config, up to a maximum of 10 pointers. + * + * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added + * via this method. + * + * @method Phaser.Input.InputManager#addPointer + * @since 3.10.0 + * + * @param {integer} [quantity=1] The number of new Pointers to create. A maximum of 10 is allowed in total. + * + * @return {Phaser.Input.Pointer[]} An array containing all of the new Pointer objects that were created. + */ + addPointer: function (quantity) + { + if (quantity === undefined) { quantity = 1; } + + var output = []; + + if (this.pointersTotal + quantity > 10) + { + quantity = 10 - this.pointersTotal; + } + + for (var i = 0; i < quantity; i++) + { + var id = this.pointers.length; + + var pointer = new Pointer(this, id); + + pointer.smoothFactor = this.config.inputSmoothFactor; + + this.pointers.push(pointer); + + this.pointersTotal++; + + output.push(pointer); + } + + return output; + }, + + /** + * Internal method that gets a list of all the active Input Plugins in the game + * and updates each of them in turn, in reverse order (top to bottom), to allow + * for DOM top-level event handling simulation. + * + * @method Phaser.Input.InputManager#updateInputPlugins + * @since 3.16.0 + * + * @param {integer} type - The type of event to process. + * @param {Phaser.Input.Pointer[]} pointers - An array of Pointers on which the event occurred. + */ + updateInputPlugins: function (type, pointers) + { + var scenes = this.game.scene.getScenes(true, true); + + this._tempSkip = false; + + for (var i = 0; i < scenes.length; i++) + { + var scene = scenes[i]; + + if (scene.sys.input) + { + var capture = scene.sys.input.update(type, pointers); + + if ((capture && this.globalTopOnly) || this._tempSkip) + { + // If the Scene returns true, or called stopPropagation, it means it captured some input that no other Scene should get, so we bail out + return; + } + } + } + }, + + // 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 + + /** + * Processes a touch start event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchStart + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchStart: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (!pointer.active) + { + pointer.touchstart(changedTouch, event); + + this.activePointer = pointer; + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_START, changed); + }, + + /** + * Processes a touch move event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchMove + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchMove: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (pointer.active && pointer.identifier === changedTouch.identifier) + { + pointer.touchmove(changedTouch, event); + + this.activePointer = pointer; + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_MOVE, changed); + }, + + // 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 + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + + /** + * Processes a touch end event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchEnd + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchEnd: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (pointer.active && pointer.identifier === changedTouch.identifier) + { + pointer.touchend(changedTouch, event); + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_END, changed); + }, + + /** + * Processes a touch cancel event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchCancel + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchCancel: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (pointer.active && pointer.identifier === changedTouch.identifier) + { + pointer.touchcancel(changedTouch, event); + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_CANCEL, changed); + }, + + /** + * Processes a mouse down event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseDown + * @private + * @since 3.18.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onMouseDown: function (event) + { + this.mousePointer.down(event); + + this.mousePointer.updateMotion(); + + this.updateInputPlugins(CONST.MOUSE_DOWN, this.mousePointerContainer); + }, + + /** + * Processes a mouse move event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseMove + * @private + * @since 3.18.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onMouseMove: function (event) + { + this.mousePointer.move(event); + + this.mousePointer.updateMotion(); + + this.updateInputPlugins(CONST.MOUSE_MOVE, this.mousePointerContainer); + }, + + /** + * Processes a mouse up event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseUp + * @private + * @since 3.18.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onMouseUp: function (event) + { + this.mousePointer.up(event); + + this.mousePointer.updateMotion(); + + this.updateInputPlugins(CONST.MOUSE_UP, this.mousePointerContainer); + }, + + /** + * Processes a mouse wheel event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseWheel + * @private + * @since 3.18.0 + * + * @param {WheelEvent} event - The native DOM Wheel event. + */ + onMouseWheel: function (event) + { + this.mousePointer.wheel(event); + + this.updateInputPlugins(CONST.MOUSE_WHEEL, this.mousePointerContainer); + }, + + /** + * Processes a pointer lock change event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onPointerLockChange + * @fires Phaser.Input.Events#POINTERLOCK_CHANGE + * @private + * @since 3.19.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onPointerLockChange: function (event) + { + var isLocked = this.mouse.locked; + + this.mousePointer.locked = isLocked; + + this.events.emit(Events.POINTERLOCK_CHANGE, event, isLocked); + }, + + /** + * Checks if the given Game Object should be considered as a candidate for input or not. + * + * Checks if the Game Object has an input component that is enabled, that it will render, + * and finally, if it has a parent, that the parent parent, or any ancestor, is visible or not. + * + * @method Phaser.Input.InputManager#inputCandidate + * @private + * @since 3.10.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to test. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. + * + * @return {boolean} `true` if the Game Object should be considered for input, otherwise `false`. + */ + inputCandidate: function (gameObject, camera) + { + var input = gameObject.input; + + if (!input || !input.enabled || (!input.alwaysEnabled && !gameObject.willRender(camera))) + { + return false; + } + + var visible = true; + var parent = gameObject.parentContainer; + + if (parent) + { + do + { + if (!parent.willRender(camera)) + { + visible = false; + break; + } + + parent = parent.parentContainer; + + } while (parent); + } + + return visible; + }, + + /** + * Performs a hit test using the given Pointer and camera, against an array of interactive Game Objects. + * + * The Game Objects are culled against the camera, and then the coordinates are translated into the local camera space + * and used to determine if they fall within the remaining Game Objects hit areas or not. + * + * If nothing is matched an empty array is returned. + * + * This method is called automatically by InputPlugin.hitTestPointer and doesn't usually need to be invoked directly. + * + * @method Phaser.Input.InputManager#hitTest + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to test against. + * @param {array} gameObjects - An array of interactive Game Objects to check. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. + * @param {array} [output] - An array to store the results in. If not given, a new empty array is created. + * + * @return {array} An array of the Game Objects that were hit during this hit test. + */ + hitTest: function (pointer, gameObjects, camera, output) + { + if (output === undefined) { output = this._tempHitTest; } + + var tempPoint = this._tempPoint; + + var csx = camera.scrollX; + var csy = camera.scrollY; + + output.length = 0; + + var x = pointer.x; + var y = pointer.y; + + if (camera.resolution !== 1) + { + x += camera._x; + y += camera._y; + } + + // Stores the world point inside of tempPoint + camera.getWorldPoint(x, y, tempPoint); + + pointer.worldX = tempPoint.x; + pointer.worldY = tempPoint.y; + + var point = { x: 0, y: 0 }; + + var matrix = this._tempMatrix; + var parentMatrix = this._tempMatrix2; + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + // 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 + if (!this.inputCandidate(gameObject, camera)) + { + continue; + } + + var px = tempPoint.x + (csx * gameObject.scrollFactorX) - csx; + var py = tempPoint.y + (csy * gameObject.scrollFactorY) - csy; + + if (gameObject.parentContainer) + { + gameObject.getWorldTransformMatrix(matrix, parentMatrix); + + matrix.applyInverse(px, py, point); + } + else + { + TransformXY(px, py, gameObject.x, gameObject.y, gameObject.rotation, gameObject.scaleX, gameObject.scaleY, point); + } + + if (this.pointWithinHitArea(gameObject, point.x, point.y)) + { + output.push(gameObject); + } + } + + return output; + }, + + /** + * Checks if the given x and y coordinate are within the hit area of the Game Object. + * + * This method assumes that the coordinate values have already been translated into the space of the Game Object. + * + * If the coordinates are within the hit area they are set into the Game Objects Input `localX` and `localY` properties. + * + * @method Phaser.Input.InputManager#pointWithinHitArea + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object to check against. + * @param {number} x - The translated x coordinate for the hit test. + * @param {number} y - The translated y coordinate for the hit test. + * + * @return {boolean} `true` if the coordinates were inside the Game Objects hit area, otherwise `false`. + */ + pointWithinHitArea: function (gameObject, x, y) + { + // Normalize the origin + x += gameObject.displayOriginX; + y += gameObject.displayOriginY; + + var input = gameObject.input; + + if (input && input.hitAreaCallback(input.hitArea, x, y, gameObject)) + { + input.localX = x; + input.localY = y; + + return true; + } + else + { + return false; + } + }, + + /** + * Checks if the given x and y coordinate are within the hit area of the Interactive Object. + * + * This method assumes that the coordinate values have already been translated into the space of the Interactive Object. + * + * If the coordinates are within the hit area they are set into the Interactive Objects Input `localX` and `localY` properties. + * + * @method Phaser.Input.InputManager#pointWithinInteractiveObject + * @since 3.0.0 + * + * @param {Phaser.Types.Input.InteractiveObject} object - The Interactive Object to check against. + * @param {number} x - The translated x coordinate for the hit test. + * @param {number} y - The translated y coordinate for the hit test. + * + * @return {boolean} `true` if the coordinates were inside the Game Objects hit area, otherwise `false`. + */ + pointWithinInteractiveObject: function (object, x, y) + { + if (!object.hitArea) + { + return false; + } + + // Normalize the origin + x += object.gameObject.displayOriginX; + y += object.gameObject.displayOriginY; + + object.localX = x; + object.localY = y; + + return object.hitAreaCallback(object.hitArea, x, y, object); + }, + + /** + * Transforms the pageX and pageY values of a Pointer into the scaled coordinate space of the Input Manager. + * + * @method Phaser.Input.InputManager#transformPointer + * @since 3.10.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to transform the values for. + * @param {number} pageX - The Page X value. + * @param {number} pageY - The Page Y value. + * @param {boolean} wasMove - Are we transforming the Pointer from a move event, or an up / down event? + */ + transformPointer: function (pointer, pageX, pageY, wasMove) + { + var p0 = pointer.position; + var p1 = pointer.prevPosition; + + // Store previous position + p1.x = p0.x; + p1.y = p0.y; + + // Translate coordinates + var x = this.scaleManager.transformX(pageX); + var y = this.scaleManager.transformY(pageY); + + var a = pointer.smoothFactor; + + if (!wasMove || a === 0) + { + // Set immediately + p0.x = x; + p0.y = y; + } + else + { + // Apply smoothing + p0.x = x * a + p1.x * (1 - a); + p0.y = y * a + p1.y * (1 - a); + } + }, + + /** + * Destroys the Input Manager and all of its systems. + * + * There is no way to recover from doing this. + * + * @method Phaser.Input.InputManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.events.removeAllListeners(); + + this.game.events.off(GameEvents.PRE_RENDER); + + if (this.keyboard) + { + this.keyboard.destroy(); + } + + if (this.mouse) + { + this.mouse.destroy(); + } + + if (this.touch) + { + this.touch.destroy(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].destroy(); + } + + this.pointers = []; + this._tempHitTest = []; + this._tempMatrix.destroy(); + this.canvas = null; + this.game = null; + } + +}); + +module.exports = InputManager; + + +/***/ }), +/* 390 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayRemove = __webpack_require__(130); +var Class = __webpack_require__(0); +var GameEvents = __webpack_require__(21); +var InputEvents = __webpack_require__(56); +var KeyCodes = __webpack_require__(131); +var NOOP = __webpack_require__(0); + +/** + * @classdesc + * The Keyboard Manager is a helper class that belongs to the global Input Manager. + * + * Its role is to listen for native DOM Keyboard Events and then store them for further processing by the Keyboard Plugin. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically if keyboard + * input has been enabled in the Game Config. + * + * @class KeyboardManager + * @memberof Phaser.Input.Keyboard + * @constructor + * @since 3.16.0 + * + * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. + */ +var KeyboardManager = new Class({ + + initialize: + + function KeyboardManager (inputManager) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Keyboard.KeyboardManager#manager + * @type {Phaser.Input.InputManager} + * @since 3.16.0 + */ + this.manager = inputManager; + + /** + * An internal event queue. + * + * @name Phaser.Input.Keyboard.KeyboardManager#queue + * @type {KeyboardEvent[]} + * @private + * @since 3.16.0 + */ + this.queue = []; + + /** + * A flag that controls if the non-modified keys, matching those stored in the `captures` array, + * have `preventDefault` called on them or not. + * + * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are + * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). + * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. + * However, if the user presses just the r key on its own, it will have its event prevented. + * + * If you wish to stop capturing the keys, for example switching out to a DOM based element, then + * you can toggle this property at run-time. + * + * @name Phaser.Input.Keyboard.KeyboardManager#preventDefault + * @type {boolean} + * @since 3.16.0 + */ + this.preventDefault = true; + + /** + * An array of Key Code values that will automatically have `preventDefault` called on them, + * as long as the `KeyboardManager.preventDefault` boolean is set to `true`. + * + * By default the array is empty. + * + * The key must be non-modified when pressed in order to be captured. + * + * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are + * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). + * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. + * However, if the user presses just the r key on its own, it will have its event prevented. + * + * If you wish to stop capturing the keys, for example switching out to a DOM based element, then + * you can toggle the `KeyboardManager.preventDefault` boolean at run-time. + * + * If you need more specific control, you can create Key objects and set the flag on each of those instead. + * + * This array can be populated via the Game Config by setting the `input.keyboard.capture` array, or you + * can call the `addCapture` method. See also `removeCapture` and `clearCaptures`. + * + * @name Phaser.Input.Keyboard.KeyboardManager#captures + * @type {integer[]} + * @since 3.16.0 + */ + this.captures = []; + + /** + * A boolean that controls if the Keyboard Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Keyboard.KeyboardManager#enabled + * @type {boolean} + * @default false + * @since 3.16.0 + */ + this.enabled = false; + + /** + * The Keyboard Event target, as defined in the Game Config. + * Typically the window in which the game is rendering, but can be any interactive DOM element. + * + * @name Phaser.Input.Keyboard.KeyboardManager#target + * @type {any} + * @since 3.16.0 + */ + this.target; + + /** + * The Key Down Event handler. + * This function is sent the native DOM KeyEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Keyboard.KeyboardManager#onKeyDown + * @type {function} + * @since 3.16.00 + */ + this.onKeyDown = NOOP; + + /** + * The Key Up Event handler. + * This function is sent the native DOM KeyEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Keyboard.KeyboardManager#onKeyUp + * @type {function} + * @since 3.16.00 + */ + this.onKeyUp = NOOP; + + inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); + }, + + /** + * The Keyboard Manager boot process. + * + * @method Phaser.Input.Keyboard.KeyboardManager#boot + * @private + * @since 3.16.0 + */ + boot: function () + { + var config = this.manager.config; + + this.enabled = config.inputKeyboard; + this.target = config.inputKeyboardEventTarget; + + this.addCapture(config.inputKeyboardCapture); + + if (!this.target && window) + { + this.target = window; + } + + if (this.enabled && this.target) + { + this.startListeners(); + } + + this.manager.game.events.on(GameEvents.POST_STEP, this.postUpdate, this); + }, + + /** + * Starts the Keyboard Event listeners running. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Keyboard.KeyboardManager#startListeners + * @since 3.16.0 + */ + startListeners: function () + { + var _this = this; + + this.onKeyDown = function (event) + { + if (event.defaultPrevented || !_this.enabled || !_this.manager) + { + // Do nothing if event already handled + return; + } + + _this.queue.push(event); + + if (!_this.manager.useQueue) + { + _this.manager.events.emit(InputEvents.MANAGER_PROCESS); + } + + var modified = (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey); + + if (_this.preventDefault && !modified && _this.captures.indexOf(event.keyCode) > -1) + { + event.preventDefault(); + } + }; + + this.onKeyUp = function (event) + { + if (event.defaultPrevented || !_this.enabled || !_this.manager) + { + // Do nothing if event already handled + return; + } + + _this.queue.push(event); + + if (!_this.manager.useQueue) + { + _this.manager.events.emit(InputEvents.MANAGER_PROCESS); + } + + var modified = (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey); + + if (_this.preventDefault && !modified && _this.captures.indexOf(event.keyCode) > -1) + { + event.preventDefault(); + } + }; + + var target = this.target; + + if (target) + { + target.addEventListener('keydown', this.onKeyDown, false); + target.addEventListener('keyup', this.onKeyUp, false); + + this.enabled = true; + } + }, + + /** + * Stops the Key Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Keyboard.KeyboardManager#stopListeners + * @since 3.16.0 + */ + stopListeners: function () + { + var target = this.target; + + target.removeEventListener('keydown', this.onKeyDown, false); + target.removeEventListener('keyup', this.onKeyUp, false); + + this.enabled = false; + }, + + /** + * Clears the event queue. + * Called automatically by the Input Manager. + * + * @method Phaser.Input.Keyboard.KeyboardManager#postUpdate + * @private + * @since 3.16.0 + */ + postUpdate: function () + { + this.queue = []; + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * This `addCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent + * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. + * + * You can pass in a single key code value, or an array of key codes, or a string: + * + * ```javascript + * this.input.keyboard.addCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.addCapture([ 62, 63, 64 ]); + * ``` + * + * Or a string: + * + * ```javascript + * this.input.keyboard.addCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * If there are active captures after calling this method, the `preventDefault` property is set to `true`. + * + * @method Phaser.Input.Keyboard.KeyboardManager#addCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to enable capture for, preventing them reaching the browser. + */ + addCapture: function (keycode) + { + if (typeof keycode === 'string') + { + keycode = keycode.split(','); + } + + if (!Array.isArray(keycode)) + { + keycode = [ keycode ]; + } + + var captures = this.captures; + + for (var i = 0; i < keycode.length; i++) + { + var code = keycode[i]; + + if (typeof code === 'string') + { + code = KeyCodes[code.trim().toUpperCase()]; + } + + if (captures.indexOf(code) === -1) + { + captures.push(code); + } + } + + this.preventDefault = captures.length > 0; + }, + + /** + * Removes an existing key capture. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove + * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. + * + * You can pass in a single key code value, or an array of key codes, or a string: + * + * ```javascript + * this.input.keyboard.removeCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.removeCapture([ 62, 63, 64 ]); + * ``` + * + * Or a string: + * + * ```javascript + * this.input.keyboard.removeCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * If there are no captures left after calling this method, the `preventDefault` property is set to `false`. + * + * @method Phaser.Input.Keyboard.KeyboardManager#removeCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to disable capture for, allowing them reaching the browser again. + */ + removeCapture: function (keycode) + { + if (typeof keycode === 'string') + { + keycode = keycode.split(','); + } + + if (!Array.isArray(keycode)) + { + keycode = [ keycode ]; + } + + var captures = this.captures; + + for (var i = 0; i < keycode.length; i++) + { + var code = keycode[i]; + + if (typeof code === 'string') + { + code = KeyCodes[code.toUpperCase()]; + } + + ArrayRemove(captures, code); + } + + this.preventDefault = captures.length > 0; + }, + + /** + * Removes all keyboard captures and sets the `preventDefault` property to `false`. + * + * @method Phaser.Input.Keyboard.KeyboardManager#clearCaptures + * @since 3.16.0 + */ + clearCaptures: function () + { + this.captures = []; + + this.preventDefault = false; + }, + + /** + * Destroys this Keyboard Manager instance. + * + * @method Phaser.Input.Keyboard.KeyboardManager#destroy + * @since 3.16.0 + */ + destroy: function () + { + this.stopListeners(); + + this.clearCaptures(); + + this.queue = []; + + this.manager.game.events.off(GameEvents.POST_RENDER, this.postUpdate, this); + + this.target = null; + this.enabled = false; + this.manager = null; + } + +}); + +module.exports = KeyboardManager; + + +/***/ }), +/* 391 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Features = __webpack_require__(180); +var InputEvents = __webpack_require__(56); +var NOOP = __webpack_require__(0); + +// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent +// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md + +/** + * @classdesc + * The Mouse Manager is a helper class that belongs to the Input Manager. + * + * Its role is to listen for native DOM Mouse Events and then pass them onto the Input Manager for further processing. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically. + * + * @class MouseManager + * @memberof Phaser.Input.Mouse + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. + */ +var MouseManager = new Class({ + + initialize: + + function MouseManager (inputManager) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Mouse.MouseManager#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = inputManager; + + /** + * If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + * + * @name Phaser.Input.Mouse.MouseManager#capture + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.capture = true; + + /** + * A boolean that controls if the Mouse Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Mouse.MouseManager#enabled + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.enabled = false; + + /** + * The Mouse target, as defined in the Game Config. + * Typically the canvas to which the game is rendering, but can be any interactive DOM element. + * + * @name Phaser.Input.Mouse.MouseManager#target + * @type {any} + * @since 3.0.0 + */ + this.target; + + /** + * If the mouse has been pointer locked successfully this will be set to true. + * + * @name Phaser.Input.Mouse.MouseManager#locked + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.locked = false; + + /** + * The Mouse Move Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseMove + * @type {function} + * @since 3.10.0 + */ + this.onMouseMove = NOOP; + + /** + * The Mouse Down Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseDown + * @type {function} + * @since 3.10.0 + */ + this.onMouseDown = NOOP; + + /** + * The Mouse Up Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseUp + * @type {function} + * @since 3.10.0 + */ + this.onMouseUp = NOOP; + + /** + * The Mouse Down Event handler specifically for events on the Window. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseDownWindow + * @type {function} + * @since 3.17.0 + */ + this.onMouseDownWindow = NOOP; + + /** + * The Mouse Up Event handler specifically for events on the Window. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseUpWindow + * @type {function} + * @since 3.17.0 + */ + this.onMouseUpWindow = NOOP; + + /** + * The Mouse Over Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseOver + * @type {function} + * @since 3.16.0 + */ + this.onMouseOver = NOOP; + + /** + * The Mouse Out Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseOut + * @type {function} + * @since 3.16.0 + */ + this.onMouseOut = NOOP; + + /** + * The Mouse Wheel Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseWheel + * @type {function} + * @since 3.18.0 + */ + this.onMouseWheel = NOOP; + + /** + * Internal pointerLockChange handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#pointerLockChange + * @type {function} + * @since 3.0.0 + */ + this.pointerLockChange = NOOP; + + inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); + }, + + /** + * The Touch Manager boot process. + * + * @method Phaser.Input.Mouse.MouseManager#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + var config = this.manager.config; + + this.enabled = config.inputMouse; + this.target = config.inputMouseEventTarget; + this.capture = config.inputMouseCapture; + + if (!this.target) + { + this.target = this.manager.game.canvas; + } + else if (typeof this.target === 'string') + { + this.target = document.getElementById(this.target); + } + + if (config.disableContextMenu) + { + this.disableContextMenu(); + } + + if (this.enabled && this.target) + { + this.startListeners(); + } + }, + + /** + * Attempts to disable the context menu from appearing if you right-click on the browser. + * + * Works by listening for the `contextmenu` event and prevent defaulting it. + * + * Use this if you need to enable right-button mouse support in your game, and the browser + * menu keeps getting in the way. + * + * @method Phaser.Input.Mouse.MouseManager#disableContextMenu + * @since 3.0.0 + * + * @return {Phaser.Input.Mouse.MouseManager} This Mouse Manager instance. + */ + disableContextMenu: function () + { + document.body.addEventListener('contextmenu', function (event) + { + event.preventDefault(); + return false; + }); + + return this; + }, + + /** + * 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. + * + * @method Phaser.Input.Mouse.MouseManager#requestPointerLock + * @since 3.0.0 + */ + requestPointerLock: function () + { + if (Features.pointerLock) + { + var element = this.target; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + } + }, + + /** + * If the browser supports pointer lock, this will request that the pointer lock is released. If + * the browser successfully enters a locked state, a 'POINTER_LOCK_CHANGE_EVENT' will be + * dispatched - from the game's input manager - with an `isPointerLocked` property. + * + * @method Phaser.Input.Mouse.MouseManager#releasePointerLock + * @since 3.0.0 + */ + releasePointerLock: function () + { + if (Features.pointerLock) + { + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + document.exitPointerLock(); + } + }, + + /** + * Starts the Mouse Event listeners running. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Mouse.MouseManager#startListeners + * @since 3.0.0 + */ + startListeners: function () + { + var _this = this; + var canvas = this.manager.canvas; + var autoFocus = (window && window.focus && this.manager.game.config.autoFocus); + + this.onMouseMove = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseMove(event); + + if (_this.capture) + { + event.preventDefault(); + } + } + }; + + this.onMouseDown = function (event) + { + if (autoFocus) + { + window.focus(); + } + + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseDown(event); + + if (_this.capture && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onMouseDownWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onMouseDown(event); + } + }; + + this.onMouseUp = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseUp(event); + + if (_this.capture && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onMouseUpWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onMouseUp(event); + } + }; + + this.onMouseOver = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOver(event); + } + }; + + this.onMouseOut = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOut(event); + } + }; + + this.onMouseWheel = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseWheel(event); + } + }; + + var target = this.target; + + if (!target) + { + return; + } + + var passive = { passive: true }; + var nonPassive = { passive: false }; + + target.addEventListener('mousemove', this.onMouseMove, (this.capture) ? nonPassive : passive); + target.addEventListener('mousedown', this.onMouseDown, (this.capture) ? nonPassive : passive); + target.addEventListener('mouseup', this.onMouseUp, (this.capture) ? nonPassive : passive); + target.addEventListener('mouseover', this.onMouseOver, (this.capture) ? nonPassive : passive); + target.addEventListener('mouseout', this.onMouseOut, (this.capture) ? nonPassive : passive); + target.addEventListener('wheel', this.onMouseWheel, (this.capture) ? nonPassive : passive); + + if (window && this.manager.game.config.inputWindowEvents) + { + window.addEventListener('mousedown', this.onMouseDownWindow, nonPassive); + window.addEventListener('mouseup', this.onMouseUpWindow, nonPassive); + } + + if (Features.pointerLock) + { + this.pointerLockChange = function (event) + { + var element = _this.target; + + _this.locked = (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) ? true : false; + + _this.manager.onPointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this.pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this.pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this.pointerLockChange, true); + } + + this.enabled = true; + }, + + /** + * Stops the Mouse Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Mouse.MouseManager#stopListeners + * @since 3.0.0 + */ + stopListeners: function () + { + var target = this.target; + + target.removeEventListener('mousemove', this.onMouseMove); + target.removeEventListener('mousedown', this.onMouseDown); + target.removeEventListener('mouseup', this.onMouseUp); + target.removeEventListener('mouseover', this.onMouseOver); + target.removeEventListener('mouseout', this.onMouseOut); + + if (window) + { + window.removeEventListener('mousedown', this.onMouseDownWindow); + window.removeEventListener('mouseup', this.onMouseUpWindow); + } + + if (Features.pointerLock) + { + document.removeEventListener('pointerlockchange', this.pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this.pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this.pointerLockChange, true); + } + }, + + /** + * Destroys this Mouse Manager instance. + * + * @method Phaser.Input.Mouse.MouseManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stopListeners(); + + this.target = null; + this.enabled = false; + this.manager = null; + } + +}); + +module.exports = MouseManager; + + +/***/ }), +/* 392 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Angle = __webpack_require__(336); +var Class = __webpack_require__(0); +var Distance = __webpack_require__(54); +var FuzzyEqual = __webpack_require__(126); +var SmoothStepInterpolation = __webpack_require__(345); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Pointer object encapsulates both mouse and touch input within Phaser. + * + * By default, Phaser will create 2 pointers for your game to use. If you require more, i.e. for a multi-touch + * game, then use the `InputPlugin.addPointer` method to do so, rather than instantiating this class directly, + * otherwise it won't be managed by the input system. + * + * You can reference the current active pointer via `InputPlugin.activePointer`. You can also use the properties + * `InputPlugin.pointer1` through to `pointer10`, for each pointer you have enabled in your game. + * + * The properties of this object are set by the Input Plugin during processing. This object is then sent in all + * input related events that the Input Plugin emits, so you can reference properties from it directly in your + * callbacks. + * + * @class Pointer + * @memberof Phaser.Input + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.InputManager} manager - A reference to the Input Manager. + * @param {integer} id - The internal ID of this Pointer. + */ +var Pointer = new Class({ + + initialize: + + function Pointer (manager, id) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Pointer#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The internal ID of this Pointer. + * + * @name Phaser.Input.Pointer#id + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.id = id; + + /** + * The most recent native DOM Event this Pointer has processed. + * + * @name Phaser.Input.Pointer#event + * @type {(TouchEvent|MouseEvent)} + * @since 3.0.0 + */ + this.event; + + /** + * 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 + */ + this.downElement; + + /** + * 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 + */ + this.upElement; + + /** + * The camera the Pointer interacted with during its last update. + * + * A Pointer can only ever interact with one camera at once, which will be the top-most camera + * in the list should multiple cameras be positioned on-top of each other. + * + * @name Phaser.Input.Pointer#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @default null + * @since 3.0.0 + */ + this.camera = null; + + /** + * A read-only property that indicates which button was pressed, or released, on the pointer + * during the most recent event. It is only set during `up` and `down` events. + * + * On Touch devices the value is always 0. + * + * Users may change the configuration of buttons on their pointing device so that if an event's button property + * is zero, it may not have been caused by the button that is physically left–most on the pointing device; + * however, it should behave as if the left button was clicked in the standard button layout. + * + * @name Phaser.Input.Pointer#button + * @type {integer} + * @readonly + * @default 0 + * @since 3.18.0 + */ + this.button = 0; + + /** + * 0: No button or un-initialized + * 1: Left button + * 2: Right button + * 4: Wheel button or middle button + * 8: 4th button (typically the "Browser Back" button) + * 16: 5th button (typically the "Browser Forward" button) + * + * For a mouse configured for left-handed use, the button actions are reversed. + * In this case, the values are read from right to left. + * + * @name Phaser.Input.Pointer#buttons + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.buttons = 0; + + /** + * The position of the Pointer in screen space. + * + * @name Phaser.Input.Pointer#position + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.position = new Vector2(); + + /** + * The previous position of the Pointer in screen space. + * + * The old x and y values are stored in here during the InputManager.transformPointer call. + * + * Use the properties `velocity`, `angle` and `distance` to create your own gesture recognition. + * + * @name Phaser.Input.Pointer#prevPosition + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.11.0 + */ + this.prevPosition = new Vector2(); + + /** + * An internal vector used for calculations of the pointer speed and angle. + * + * @name Phaser.Input.Pointer#midPoint + * @type {Phaser.Math.Vector2} + * @private + * @since 3.16.0 + */ + this.midPoint = new Vector2(-1, -1); + + /** + * 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 + */ + this.velocity = new Vector2(); + + /** + * 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 + */ + this.angle = 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 buttons was pressed down, + * then use the `Pointer.getDistance` method. + * + * @name Phaser.Input.Pointer#distance + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.distance = 0; + + /** + * The smoothing factor to apply to the Pointer position. + * + * Due to their nature, pointer positions are inherently noisy. While this is fine for lots of games, if you need cleaner positions + * then you can set this value to apply an automatic smoothing to the positions as they are recorded. + * + * The default value of zero means 'no smoothing'. + * Set to a small value, such as 0.2, to apply an average level of smoothing between positions. You can do this by changing this + * value directly, or by setting the `input.smoothFactor` property in the Game Config. + * + * Positions are only smoothed when the pointer moves. If the primary button on this Pointer enters an Up or Down state, then the position + * is always precise, and not smoothed. + * + * @name Phaser.Input.Pointer#smoothFactor + * @type {number} + * @default 0 + * @since 3.16.0 + */ + this.smoothFactor = 0; + + /** + * The factor applied to the motion smoothing each frame. + * + * This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, + * angle and distance of the Pointer. It's applied every frame, until the midPoint reaches the current + * position of the Pointer. 0.2 provides a good average but can be increased if you need a + * quicker update and are working in a high performance environment. Never set this value to + * zero. + * + * @name Phaser.Input.Pointer#motionFactor + * @type {number} + * @default 0.2 + * @since 3.16.0 + */ + this.motionFactor = 0.2; + + /** + * The x position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. + * + * If you wish to use this value _outside_ of an input event handler then you should update it first by calling + * the `Pointer.updateWorldPoint` method. + * + * @name Phaser.Input.Pointer#worldX + * @type {number} + * @default 0 + * @since 3.10.0 + */ + this.worldX = 0; + + /** + * The y position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. + * + * If you wish to use this value _outside_ of an input event handler then you should update it first by calling + * the `Pointer.updateWorldPoint` method. + * + * @name Phaser.Input.Pointer#worldY + * @type {number} + * @default 0 + * @since 3.10.0 + */ + this.worldY = 0; + + /** + * Time when this Pointer was most recently moved (regardless of the state of its buttons, if any) + * + * @name Phaser.Input.Pointer#moveTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.moveTime = 0; + + /** + * X coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. + * + * @name Phaser.Input.Pointer#downX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.downX = 0; + + /** + * Y coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. + * + * @name Phaser.Input.Pointer#downY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.downY = 0; + + /** + * Time when Button 1 (left button), or Touch, was pressed, used for dragging objects. + * + * @name Phaser.Input.Pointer#downTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.downTime = 0; + + /** + * X coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. + * + * @name Phaser.Input.Pointer#upX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.upX = 0; + + /** + * Y coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. + * + * @name Phaser.Input.Pointer#upY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.upY = 0; + + /** + * Time when Button 1 (left button), or Touch, was released, used for dragging objects. + * + * @name Phaser.Input.Pointer#upTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.upTime = 0; + + /** + * Is the primary button down? (usually button 0, the left mouse button) + * + * @name Phaser.Input.Pointer#primaryDown + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.primaryDown = false; + + /** + * Is _any_ button on this pointer considered as being down? + * + * @name Phaser.Input.Pointer#isDown + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isDown = false; + + /** + * Did the previous input event come from a Touch input (true) or Mouse? (false) + * + * @name Phaser.Input.Pointer#wasTouch + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.wasTouch = false; + + /** + * Did this Pointer get canceled by a touchcancel event? + * + * Note: "canceled" is the American-English spelling of "cancelled". Please don't submit PRs correcting it! + * + * @name Phaser.Input.Pointer#wasCanceled + * @type {boolean} + * @default false + * @since 3.15.0 + */ + this.wasCanceled = false; + + /** + * If the mouse is locked, the horizontal relative movement of the Pointer in pixels since last frame. + * + * @name Phaser.Input.Pointer#movementX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.movementX = 0; + + /** + * If the mouse is locked, the vertical relative movement of the Pointer in pixels since last frame. + * + * @name Phaser.Input.Pointer#movementY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.movementY = 0; + + /** + * The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * + * @name Phaser.Input.Pointer#identifier + * @type {number} + * @since 3.10.0 + */ + this.identifier = 0; + + /** + * The pointerId property of the Pointer as set by the DOM event when this Pointer is started. + * The browser can and will recycle this value. + * + * @name Phaser.Input.Pointer#pointerId + * @type {number} + * @since 3.10.0 + */ + this.pointerId = null; + + /** + * An active Pointer is one that is currently pressed down on the display. + * A Mouse is always considered as active. + * + * @name Phaser.Input.Pointer#active + * @type {boolean} + * @since 3.10.0 + */ + this.active = (id === 0) ? true : false; + + /** + * Is this pointer Pointer Locked? + * + * Only a mouse pointer can be locked and it only becomes locked when requested via + * the browsers Pointer Lock API. + * + * You can request this by calling the `this.input.mouse.requestPointerLock()` method from + * a `pointerdown` or `pointerup` event handler. + * + * @name Phaser.Input.Pointer#locked + * @readonly + * @type {boolean} + * @since 3.19.0 + */ + this.locked = false; + + /** + * The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * + * @name Phaser.Input.Pointer#deltaX + * @type {number} + * @default 0 + * @since 3.18.0 + */ + this.deltaX = 0; + + /** + * The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * + * @name Phaser.Input.Pointer#deltaY + * @type {number} + * @default 0 + * @since 3.18.0 + */ + this.deltaY = 0; + + /** + * The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * + * @name Phaser.Input.Pointer#deltaZ + * @type {number} + * @default 0 + * @since 3.18.0 + */ + this.deltaZ = 0; + }, + + /** + * Takes a Camera and updates this Pointer's `worldX` and `worldY` values so they are + * the result of a translation through the given Camera. + * + * Note that the values will be automatically replaced the moment the Pointer is + * updated by an input event, such as a mouse move, so should be used immediately. + * + * @method Phaser.Input.Pointer#updateWorldPoint + * @since 3.19.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. + * + * @return {this} This Pointer object. + */ + updateWorldPoint: function (camera) + { + var x = this.x; + var y = this.y; + + if (camera.resolution !== 1) + { + x += camera._x; + y += camera._y; + } + + // Stores the world point inside of tempPoint + var temp = camera.getWorldPoint(x, y); + + this.worldX = temp.x; + this.worldY = temp.y; + + return this; + }, + + /** + * 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. + */ + positionToCamera: function (camera, output) + { + return camera.getWorldPoint(this.x, this.y, output); + }, + + /** + * Calculates the motion of this Pointer, including its velocity and angle of movement. + * This method is called automatically each frame by the Input Manager. + * + * @method Phaser.Input.Pointer#updateMotion + * @private + * @since 3.16.0 + */ + updateMotion: function () + { + var cx = this.position.x; + var cy = this.position.y; + + var mx = this.midPoint.x; + var my = this.midPoint.y; + + if (cx === mx && cy === my) + { + // Nothing to do here + return; + } + + // Moving towards our goal ... + var vx = SmoothStepInterpolation(this.motionFactor, mx, cx); + var vy = SmoothStepInterpolation(this.motionFactor, my, cy); + + if (FuzzyEqual(vx, cx, 0.1)) + { + vx = cx; + } + + if (FuzzyEqual(vy, cy, 0.1)) + { + vy = cy; + } + + this.midPoint.set(vx, vy); + + var dx = cx - vx; + var dy = cy - vy; + + this.velocity.set(dx, dy); + + this.angle = Angle(vx, vy, cx, cy); + + this.distance = Math.sqrt(dx * dx + dy * dy); + }, + + /** + * Internal method to handle a Mouse Up Event. + * + * @method Phaser.Input.Pointer#up + * @private + * @since 3.0.0 + * + * @param {MouseEvent} event - The Mouse Event to process. + */ + up: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + this.button = event.button; + + this.upElement = event.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, false); + + // 0: Main button pressed, usually the left button or the un-initialized state + if (event.button === 0) + { + this.primaryDown = false; + this.upX = this.x; + this.upY = this.y; + this.upTime = event.timeStamp; + } + + this.isDown = false; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Mouse Down Event. + * + * @method Phaser.Input.Pointer#down + * @private + * @since 3.0.0 + * + * @param {MouseEvent} event - The Mouse Event to process. + */ + down: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + this.button = event.button; + + this.downElement = event.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, false); + + // 0: Main button pressed, usually the left button or the un-initialized state + if (event.button === 0) + { + this.primaryDown = true; + this.downX = this.x; + this.downY = this.y; + this.downTime = event.timeStamp; + } + + this.isDown = true; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Mouse Move Event. + * + * @method Phaser.Input.Pointer#move + * @private + * @since 3.0.0 + * + * @param {MouseEvent} event - The Mouse Event to process. + */ + move: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, true); + + if (this.locked) + { + // Multiple DOM events may occur within one frame, but only one Phaser event will fire + this.movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; + this.movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; + } + + this.moveTime = event.timeStamp; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Mouse Wheel Event. + * + * @method Phaser.Input.Pointer#wheel + * @private + * @since 3.18.0 + * + * @param {WheelEvent} event - The Wheel Event to process. + */ + wheel: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, false); + + this.deltaX = event.deltaX; + this.deltaY = event.deltaY; + this.deltaZ = event.deltaZ; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Touch Start Event. + * + * @method Phaser.Input.Pointer#touchstart + * @private + * @since 3.0.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchstart: function (touch, event) + { + if (touch['pointerId']) + { + this.pointerId = touch.pointerId; + } + + this.identifier = touch.identifier; + this.target = touch.target; + this.active = true; + + this.buttons = 1; + + this.event = event; + + this.downElement = touch.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, false); + + this.primaryDown = true; + this.downX = this.x; + this.downY = this.y; + this.downTime = event.timeStamp; + + this.isDown = true; + + this.wasTouch = true; + this.wasCanceled = false; + + this.updateMotion(); + }, + + /** + * Internal method to handle a Touch Move Event. + * + * @method Phaser.Input.Pointer#touchmove + * @private + * @since 3.0.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchmove: function (touch, event) + { + this.event = event; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, true); + + this.moveTime = event.timeStamp; + + this.wasTouch = true; + + this.updateMotion(); + }, + + /** + * Internal method to handle a Touch End Event. + * + * @method Phaser.Input.Pointer#touchend + * @private + * @since 3.0.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchend: function (touch, event) + { + this.buttons = 0; + + this.event = event; + + this.upElement = touch.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, false); + + this.primaryDown = false; + this.upX = this.x; + this.upY = this.y; + this.upTime = event.timeStamp; + + this.isDown = false; + + this.wasTouch = true; + this.wasCanceled = false; + + this.active = false; + + this.updateMotion(); + }, + + /** + * Internal method to handle a Touch Cancel Event. + * + * @method Phaser.Input.Pointer#touchcancel + * @private + * @since 3.15.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchcancel: function (touch, event) + { + this.buttons = 0; + + this.event = event; + + this.upElement = touch.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, false); + + this.primaryDown = false; + this.upX = this.x; + this.upY = this.y; + this.upTime = event.timeStamp; + + this.isDown = false; + + this.wasTouch = true; + this.wasCanceled = true; + + this.active = false; + }, + + /** + * Checks to see if any buttons are being held down on this Pointer. + * + * @method Phaser.Input.Pointer#noButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if no buttons are being held down. + */ + noButtonDown: function () + { + return (this.buttons === 0); + }, + + /** + * Checks to see if the left button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#leftButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the left button is being held down. + */ + leftButtonDown: function () + { + return (this.buttons & 1) ? true : false; + }, + + /** + * Checks to see if the right button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#rightButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the right button is being held down. + */ + rightButtonDown: function () + { + return (this.buttons & 2) ? true : false; + }, + + /** + * Checks to see if the middle button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#middleButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the middle button is being held down. + */ + middleButtonDown: function () + { + return (this.buttons & 4) ? true : false; + }, + + /** + * Checks to see if the back button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#backButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the back button is being held down. + */ + backButtonDown: function () + { + return (this.buttons & 8) ? true : false; + }, + + /** + * Checks to see if the forward button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#forwardButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the forward button is being held down. + */ + forwardButtonDown: function () + { + return (this.buttons & 16) ? true : false; + }, + + /** + * Checks to see if the left button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#leftButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the left button was just released. + */ + leftButtonReleased: function () + { + return (this.button === 0 && !this.isDown); + }, + + /** + * Checks to see if the right button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#rightButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the right button was just released. + */ + rightButtonReleased: function () + { + return (this.button === 2 && !this.isDown); + }, + + /** + * Checks to see if the middle button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#middleButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the middle button was just released. + */ + middleButtonReleased: function () + { + return (this.button === 1 && !this.isDown); + }, + + /** + * Checks to see if the back button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#backButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the back button was just released. + */ + backButtonReleased: function () + { + return (this.button === 3 && !this.isDown); + }, + + /** + * Checks to see if the forward button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#forwardButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the forward button was just released. + */ + forwardButtonReleased: function () + { + return (this.button === 4 && !this.isDown); + }, + + /** + * 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. + */ + getDistance: function () + { + if (this.isDown) + { + return Distance(this.downX, this.downY, this.x, this.y); + } + else + { + return Distance(this.downX, this.downY, this.upX, this.upY); + } + }, + + /** + * 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` and `downY` values and the current 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. + */ + getDistanceX: function () + { + if (this.isDown) + { + return Math.abs(this.downX - this.x); + } + else + { + return Math.abs(this.downX - this.upX); + } + }, + + /** + * 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 `downX` and `downY` values and the current 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. + */ + getDistanceY: function () + { + if (this.isDown) + { + return Math.abs(this.downY - this.y); + } + else + { + return Math.abs(this.downY - this.upY); + } + }, + + /** + * 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 Pointer button was released. + * + * @method Phaser.Input.Pointer#getDuration + * @since 3.16.0 + * + * @return {number} The duration the Pointer was held down for in milliseconds. + */ + getDuration: function () + { + if (this.isDown) + { + return (this.manager.time - this.downTime); + } + else + { + return (this.upTime - this.downTime); + } + }, + + /** + * 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. + */ + getAngle: function () + { + if (this.isDown) + { + return Angle(this.downX, this.downY, this.x, this.y); + } + else + { + return Angle(this.downX, this.downY, this.upX, this.upY); + } + }, + + /** + * Takes the previous and current Pointer positions and then generates an array of interpolated values between + * the two. The array will be populated up to the size of the `steps` argument. + * + * ```javaScript + * var points = pointer.getInterpolatedPosition(4); + * + * // points[0] = { x: 0, y: 0 } + * // points[1] = { x: 2, y: 1 } + * // points[2] = { x: 3, y: 2 } + * // points[3] = { x: 6, y: 3 } + * ``` + * + * Use this if you need to get smoothed values between the previous and current pointer positions. DOM pointer + * events can often fire faster than the main browser loop, and this will help you avoid janky movement + * especially if you have an object following a Pointer. + * + * Note that if you provide an output array it will only be populated up to the number of steps provided. + * It will not clear any previous data that may have existed beyond the range of the steps count. + * + * Internally it uses the Smooth Step interpolation calculation. + * + * @method Phaser.Input.Pointer#getInterpolatedPosition + * @since 3.11.0 + * + * @param {integer} [steps=10] - The number of interpolation steps to use. + * @param {array} [out] - An array to store the results in. If not provided a new one will be created. + * + * @return {array} An array of interpolated values. + */ + getInterpolatedPosition: function (steps, out) + { + if (steps === undefined) { steps = 10; } + if (out === undefined) { out = []; } + + var prevX = this.prevPosition.x; + var prevY = this.prevPosition.y; + + var curX = this.position.x; + var curY = this.position.y; + + for (var i = 0; i < steps; i++) + { + var t = (1 / steps) * i; + + out[i] = { x: SmoothStepInterpolation(t, prevX, curX), y: SmoothStepInterpolation(t, prevY, curY) }; + } + + return out; + }, + + /** + * Destroys this Pointer instance and resets its external references. + * + * @method Phaser.Input.Pointer#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.camera = null; + this.manager = null; + this.position = null; + }, + + /** + * The x position of this Pointer. + * The value is in screen space. + * See `worldX` to get a camera converted position. + * + * @name Phaser.Input.Pointer#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.position.x; + }, + + set: function (value) + { + this.position.x = value; + } + + }, + + /** + * The y position of this Pointer. + * The value is in screen space. + * See `worldY` to get a camera converted position. + * + * @name Phaser.Input.Pointer#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.position.y; + }, + + set: function (value) + { + this.position.y = value; + } + + }, + + /** + * Time when this Pointer was most recently updated by a DOM Event. + * This comes directly from the `event.timeStamp` property. + * If no event has yet taken place, it will return zero. + * + * @name Phaser.Input.Pointer#time + * @type {number} + * @readonly + * @since 3.16.0 + */ + time: { + + get: function () + { + return (this.event) ? this.event.timeStamp : 0; + } + + } + +}); + +module.exports = Pointer; + + +/***/ }), +/* 393 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var InputEvents = __webpack_require__(56); +var NOOP = __webpack_require__(2); + +// 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/ + +/** + * @classdesc + * The Touch Manager is a helper class that belongs to the Input Manager. + * + * Its role is to listen for native DOM Touch Events and then pass them onto the Input Manager for further processing. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically. + * + * @class TouchManager + * @memberof Phaser.Input.Touch + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. + */ +var TouchManager = new Class({ + + initialize: + + function TouchManager (inputManager) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Touch.TouchManager#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = inputManager; + + /** + * If true the DOM events will have event.preventDefault applied to them, if false they will propagate fully. + * + * @name Phaser.Input.Touch.TouchManager#capture + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.capture = true; + + /** + * A boolean that controls if the Touch Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Touch.TouchManager#enabled + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.enabled = false; + + /** + * The Touch Event target, as defined in the Game Config. + * Typically the canvas to which the game is rendering, but can be any interactive DOM element. + * + * @name Phaser.Input.Touch.TouchManager#target + * @type {any} + * @since 3.0.0 + */ + this.target; + + /** + * The Touch Start event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchStart + * @type {function} + * @since 3.0.0 + */ + this.onTouchStart = NOOP; + + /** + * The Touch Start event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchStartWindow + * @type {function} + * @since 3.17.0 + */ + this.onTouchStartWindow = NOOP; + + /** + * The Touch Move event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchMove + * @type {function} + * @since 3.0.0 + */ + this.onTouchMove = NOOP; + + /** + * The Touch End event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchEnd + * @type {function} + * @since 3.0.0 + */ + this.onTouchEnd = NOOP; + + /** + * The Touch End event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchEndWindow + * @type {function} + * @since 3.17.0 + */ + this.onTouchEndWindow = NOOP; + + /** + * The Touch Cancel event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchCancel + * @type {function} + * @since 3.15.0 + */ + this.onTouchCancel = NOOP; + + /** + * The Touch Cancel event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchCancelWindow + * @type {function} + * @since 3.18.0 + */ + this.onTouchCancelWindow = NOOP; + + /** + * The Touch Over event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchOver + * @type {function} + * @since 3.16.0 + */ + this.onTouchOver = NOOP; + + /** + * The Touch Out event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchOut + * @type {function} + * @since 3.16.0 + */ + this.onTouchOut = NOOP; + + inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); + }, + + /** + * The Touch Manager boot process. + * + * @method Phaser.Input.Touch.TouchManager#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + var config = this.manager.config; + + this.enabled = config.inputTouch; + this.target = config.inputTouchEventTarget; + this.capture = config.inputTouchCapture; + + if (!this.target) + { + this.target = this.manager.game.canvas; + } + + if (config.disableContextMenu) + { + this.disableContextMenu(); + } + + if (this.enabled && this.target) + { + this.startListeners(); + } + }, + + /** + * Attempts to disable the context menu from appearing if you touch-hold on the browser. + * + * Works by listening for the `contextmenu` event and prevent defaulting it. + * + * Use this if you need to disable the OS context menu on mobile. + * + * @method Phaser.Input.Touch.TouchManager#disableContextMenu + * @since 3.20.0 + * + * @return {Phaser.Input.Touch.TouchManager} This Touch Manager instance. + */ + disableContextMenu: function () + { + document.body.addEventListener('contextmenu', function (event) + { + event.preventDefault(); + return false; + }); + + return this; + }, + + /** + * Starts the Touch Event listeners running as long as an input target is set. + * + * This method is called automatically if Touch Input is enabled in the game config, + * which it is by default. However, you can call it manually should you need to + * delay input capturing until later in the game. + * + * @method Phaser.Input.Touch.TouchManager#startListeners + * @since 3.0.0 + */ + startListeners: function () + { + var _this = this; + var canvas = this.manager.canvas; + var autoFocus = (window && window.focus && this.manager.game.config.autoFocus); + + this.onTouchStart = function (event) + { + if (autoFocus) + { + window.focus(); + } + + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchStart(event); + + if (_this.capture && event.cancelable && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onTouchStartWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onTouchStart(event); + } + }; + + this.onTouchMove = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchMove(event); + + if (_this.capture && event.cancelable) + { + event.preventDefault(); + } + } + }; + + this.onTouchEnd = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchEnd(event); + + if (_this.capture && event.cancelable && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onTouchEndWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onTouchEnd(event); + } + }; + + this.onTouchCancel = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchCancel(event); + + if (_this.capture) + { + event.preventDefault(); + } + } + }; + + this.onTouchCancelWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchCancel(event); + } + }; + + this.onTouchOver = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOver(event); + } + }; + + this.onTouchOut = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOut(event); + } + }; + + var target = this.target; + + if (!target) + { + return; + } + + var passive = { passive: true }; + var nonPassive = { passive: false }; + + target.addEventListener('touchstart', this.onTouchStart, (this.capture) ? nonPassive : passive); + target.addEventListener('touchmove', this.onTouchMove, (this.capture) ? nonPassive : passive); + target.addEventListener('touchend', this.onTouchEnd, (this.capture) ? nonPassive : passive); + target.addEventListener('touchcancel', this.onTouchCancel, (this.capture) ? nonPassive : passive); + target.addEventListener('touchover', this.onTouchOver, (this.capture) ? nonPassive : passive); + target.addEventListener('touchout', this.onTouchOut, (this.capture) ? nonPassive : passive); + + if (window && this.manager.game.config.inputWindowEvents) + { + window.addEventListener('touchstart', this.onTouchStartWindow, nonPassive); + window.addEventListener('touchend', this.onTouchEndWindow, nonPassive); + window.addEventListener('touchcancel', this.onTouchCancelWindow, nonPassive); + } + + this.enabled = true; + }, + + /** + * Stops the Touch Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Touch.TouchManager#stopListeners + * @since 3.0.0 + */ + stopListeners: function () + { + var target = this.target; + + target.removeEventListener('touchstart', this.onTouchStart); + target.removeEventListener('touchmove', this.onTouchMove); + target.removeEventListener('touchend', this.onTouchEnd); + target.removeEventListener('touchcancel', this.onTouchCancel); + target.removeEventListener('touchover', this.onTouchOver); + target.removeEventListener('touchout', this.onTouchOut); + + if (window) + { + window.removeEventListener('touchstart', this.onTouchStartWindow); + window.removeEventListener('touchend', this.onTouchEndWindow); + } + }, + + /** + * Destroys this Touch Manager instance. + * + * @method Phaser.Input.Touch.TouchManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stopListeners(); + + this.target = null; + this.enabled = false; + this.manager = null; + } + +}); + +module.exports = TouchManager; + + +/***/ }), +/* 394 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GameEvents = __webpack_require__(21); +var EventEmitter = __webpack_require__(9); +var FileTypesManager = __webpack_require__(8); +var GameObjectCreator = __webpack_require__(16); +var GameObjectFactory = __webpack_require__(6); +var GetFastValue = __webpack_require__(1); +var PluginCache = __webpack_require__(22); +var Remove = __webpack_require__(130); + +/** + * @classdesc + * The PluginManager is responsible for installing and adding plugins to Phaser. + * + * It is a global system and therefore belongs to the Game instance, not a specific Scene. + * + * It works in conjunction with the PluginCache. Core internal plugins automatically register themselves + * with the Cache, but it's the Plugin Manager that is responsible for injecting them into the Scenes. + * + * There are two types of plugin: + * + * 1. A Global Plugin + * 2. A Scene Plugin + * + * A Global Plugin is a plugin that lives within the Plugin Manager rather than a Scene. You can get + * access to it by calling `PluginManager.get` and providing a key. Any Scene that requests a plugin in + * this way will all get access to the same plugin instance, allowing you to use a single plugin across + * multiple Scenes. + * + * A Scene Plugin is a plugin dedicated to running within a Scene. These are different to Global Plugins + * in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. + * And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene + * Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. + * + * You can add a plugin to Phaser in three different ways: + * + * 1. Preload it + * 2. Include it in your source code and install it via the Game Config + * 3. Include it in your source code and install it within a Scene + * + * For examples of all of these approaches please see the Phaser 3 Examples Repo `plugins` folder. + * + * For information on creating your own plugin please see the Phaser 3 Plugin Template. + * + * @class PluginManager + * @memberof Phaser.Plugins + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The game instance that owns this Plugin Manager. + */ +var PluginManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function PluginManager (game) + { + EventEmitter.call(this); + + /** + * The game instance that owns this Plugin Manager. + * + * @name Phaser.Plugins.PluginManager#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * The global plugins currently running and managed by this Plugin Manager. + * A plugin must have been started at least once in order to appear in this list. + * + * @name Phaser.Plugins.PluginManager#plugins + * @type {Phaser.Types.Plugins.GlobalPlugin[]} + * @since 3.8.0 + */ + this.plugins = []; + + /** + * A list of plugin keys that should be installed into Scenes as well as the Core Plugins. + * + * @name Phaser.Plugins.PluginManager#scenePlugins + * @type {string[]} + * @since 3.8.0 + */ + this.scenePlugins = []; + + /** + * A temporary list of plugins to install when the game has booted. + * + * @name Phaser.Plugins.PluginManager#_pendingGlobal + * @private + * @type {array} + * @since 3.8.0 + */ + this._pendingGlobal = []; + + /** + * A temporary list of scene plugins to install when the game has booted. + * + * @name Phaser.Plugins.PluginManager#_pendingScene + * @private + * @type {array} + * @since 3.8.0 + */ + this._pendingScene = []; + + if (game.isBooted) + { + this.boot(); + } + else + { + game.events.once(GameEvents.BOOT, this.boot, this); + } + }, + + /** + * Run once the game has booted and installs all of the plugins configured in the Game Config. + * + * @method Phaser.Plugins.PluginManager#boot + * @protected + * @since 3.0.0 + */ + boot: function () + { + var i; + var entry; + var key; + var plugin; + var start; + var mapping; + var data; + var config = this.game.config; + + // Any plugins to install? + var list = config.installGlobalPlugins; + + // Any plugins added outside of the game config, but before the game booted? + list = list.concat(this._pendingGlobal); + + for (i = 0; i < list.length; i++) + { + entry = list[i]; + + // { key: 'TestPlugin', plugin: TestPlugin, start: true, mapping: 'test', data: { msg: 'The plugin is alive' } } + + key = GetFastValue(entry, 'key', null); + plugin = GetFastValue(entry, 'plugin', null); + start = GetFastValue(entry, 'start', false); + mapping = GetFastValue(entry, 'mapping', null); + data = GetFastValue(entry, 'data', null); + + if (key) + { + if (plugin) + { + this.install(key, plugin, start, mapping, data); + } + else + { + console.warn('Missing `plugin` for key: ' + key); + } + + } + } + + // Any scene plugins to install? + list = config.installScenePlugins; + + // Any plugins added outside of the game config, but before the game booted? + list = list.concat(this._pendingScene); + + for (i = 0; i < list.length; i++) + { + entry = list[i]; + + // { key: 'moveSpritePlugin', plugin: MoveSpritePlugin, , mapping: 'move' } + + key = GetFastValue(entry, 'key', null); + plugin = GetFastValue(entry, 'plugin', null); + mapping = GetFastValue(entry, 'mapping', null); + + if (key) + { + if (plugin) + { + this.installScenePlugin(key, plugin, mapping); + } + else + { + console.warn('Missing `plugin` for key: ' + key); + } + } + } + + this._pendingGlobal = []; + this._pendingScene = []; + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Called by the Scene Systems class. Tells the plugin manager to install all Scene plugins into it. + * + * First it will install global references, i.e. references from the Game systems into the Scene Systems (and Scene if mapped.) + * Then it will install Core Scene Plugins followed by Scene Plugins registered with the PluginManager. + * Finally it will install any references to Global Plugins that have a Scene mapping property into the Scene itself. + * + * @method Phaser.Plugins.PluginManager#addToScene + * @protected + * @since 3.8.0 + * + * @param {Phaser.Scenes.Systems} sys - The Scene Systems class to install all the plugins in to. + * @param {array} globalPlugins - An array of global plugins to install. + * @param {array} scenePlugins - An array of scene plugins to install. + */ + addToScene: function (sys, globalPlugins, scenePlugins) + { + var i; + var pluginKey; + var pluginList; + var game = this.game; + var scene = sys.scene; + var map = sys.settings.map; + var isBooted = sys.settings.isBooted; + + // Reference the GlobalPlugins from Game into Scene.Systems + for (i = 0; i < globalPlugins.length; i++) + { + pluginKey = globalPlugins[i]; + + if (game[pluginKey]) + { + sys[pluginKey] = game[pluginKey]; + + // Scene level injection + if (map.hasOwnProperty(pluginKey)) + { + scene[map[pluginKey]] = sys[pluginKey]; + } + } + else if (pluginKey === 'game' && map.hasOwnProperty(pluginKey)) + { + scene[map[pluginKey]] = game; + } + } + + for (var s = 0; s < scenePlugins.length; s++) + { + pluginList = scenePlugins[s]; + + for (i = 0; i < pluginList.length; i++) + { + pluginKey = pluginList[i]; + + if (!PluginCache.hasCore(pluginKey)) + { + continue; + } + + var source = PluginCache.getCore(pluginKey); + + var plugin = new source.plugin(scene, this); + + sys[source.mapping] = plugin; + + // Scene level injection + if (source.custom) + { + scene[source.mapping] = plugin; + } + else if (map.hasOwnProperty(source.mapping)) + { + scene[map[source.mapping]] = plugin; + } + + // Scene is already booted, usually because this method is being called at run-time, so boot the plugin + if (isBooted) + { + plugin.boot(); + } + } + } + + // And finally, inject any 'global scene plugins' + pluginList = this.plugins; + + for (i = 0; i < pluginList.length; i++) + { + var entry = pluginList[i]; + + if (entry.mapping) + { + scene[entry.mapping] = entry.plugin; + } + } + }, + + /** + * Called by the Scene Systems class. Returns a list of plugins to be installed. + * + * @method Phaser.Plugins.PluginManager#getDefaultScenePlugins + * @protected + * @since 3.8.0 + * + * @return {string[]} A list keys of all the Scene Plugins to install. + */ + getDefaultScenePlugins: function () + { + var list = this.game.config.defaultPlugins; + + // Merge in custom Scene plugins + list = list.concat(this.scenePlugins); + + return list; + }, + + /** + * Installs a new Scene Plugin into the Plugin Manager and optionally adds it + * to the given Scene as well. A Scene Plugin added to the manager in this way + * will be automatically installed into all new Scenes using the key and mapping given. + * + * The `key` property is what the plugin is injected into Scene.Systems as. + * The `mapping` property is optional, and if specified is what the plugin is installed into + * the Scene as. For example: + * + * ```javascript + * this.plugins.installScenePlugin('powerupsPlugin', pluginCode, 'powerups'); + * + * // and from within the scene: + * this.sys.powerupsPlugin; // key value + * this.powerups; // mapping value + * ``` + * + * This method is called automatically by Phaser if you install your plugins using either the + * Game Configuration object, or by preloading them via the Loader. + * + * @method Phaser.Plugins.PluginManager#installScenePlugin + * @since 3.8.0 + * + * @param {string} key - The property key that will be used to add this plugin to Scene.Systems. + * @param {function} plugin - The plugin code. This should be the non-instantiated version. + * @param {string} [mapping] - If this plugin is injected into the Phaser.Scene class, this is the property key to use. + * @param {Phaser.Scene} [addToScene] - Optionally automatically add this plugin to the given Scene. + * @param {boolean} [fromLoader=false] - Is this being called by the Loader? + */ + installScenePlugin: function (key, plugin, mapping, addToScene, fromLoader) + { + if (fromLoader === undefined) { fromLoader = false; } + + if (typeof plugin !== 'function') + { + console.warn('Invalid Scene Plugin: ' + key); + return; + } + + if (!PluginCache.hasCore(key)) + { + // Plugin is freshly loaded + PluginCache.register(key, plugin, mapping, true); + + this.scenePlugins.push(key); + } + else if (!fromLoader && PluginCache.hasCore(key)) + { + // Plugin wasn't from the loader but already exists + console.warn('Scene Plugin key in use: ' + key); + return; + } + + if (addToScene) + { + var instance = new plugin(addToScene, this); + + addToScene.sys[key] = instance; + + if (mapping && mapping !== '') + { + addToScene[mapping] = instance; + } + + instance.boot(); + } + }, + + /** + * Installs a new Global Plugin into the Plugin Manager and optionally starts it running. + * A global plugin belongs to the Plugin Manager, rather than a specific Scene, and can be accessed + * and used by all Scenes in your game. + * + * The `key` property is what you use to access this plugin from the Plugin Manager. + * + * ```javascript + * this.plugins.install('powerupsPlugin', pluginCode); + * + * // and from within the scene: + * this.plugins.get('powerupsPlugin'); + * ``` + * + * This method is called automatically by Phaser if you install your plugins using either the + * Game Configuration object, or by preloading them via the Loader. + * + * The same plugin can be installed multiple times into the Plugin Manager by simply giving each + * instance its own unique key. + * + * @method Phaser.Plugins.PluginManager#install + * @since 3.8.0 + * + * @param {string} key - The unique handle given to this plugin within the Plugin Manager. + * @param {function} plugin - The plugin code. This should be the non-instantiated version. + * @param {boolean} [start=false] - Automatically start the plugin running? This is always `true` if you provide a mapping value. + * @param {string} [mapping] - If this plugin is injected into the Phaser.Scene class, this is the property key to use. + * @param {any} [data] - A value passed to the plugin's `init` method. + * + * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if `start` was false, or game isn't yet booted. + */ + install: function (key, plugin, start, mapping, data) + { + if (start === undefined) { start = false; } + if (mapping === undefined) { mapping = null; } + if (data === undefined) { data = null; } + + if (typeof plugin !== 'function') + { + console.warn('Invalid Plugin: ' + key); + return null; + } + + if (PluginCache.hasCustom(key)) + { + console.warn('Plugin key in use: ' + key); + return null; + } + + if (mapping !== null) + { + start = true; + } + + if (!this.game.isBooted) + { + this._pendingGlobal.push({ key: key, plugin: plugin, start: start, mapping: mapping, data: data }); + } + else + { + // Add it to the plugin store + PluginCache.registerCustom(key, plugin, mapping, data); + + if (start) + { + return this.start(key); + } + } + + return null; + }, + + /** + * 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 {integer} The index of the plugin within the plugins array. + */ + getIndex: function (key) + { + var list = this.plugins; + + for (var i = 0; i < list.length; i++) + { + var entry = list[i]; + + if (entry.key === key) + { + return i; + } + } + + return -1; + }, + + /** + * 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. + */ + getEntry: function (key) + { + var idx = this.getIndex(key); + + if (idx !== -1) + { + return this.plugins[idx]; + } + }, + + /** + * 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`. + */ + isActive: function (key) + { + var entry = this.getEntry(key); + + return (entry && entry.active); + }, + + /** + * Starts a global plugin running. + * + * If the plugin was previously active then calling `start` will reset it to an active state and then + * call its `start` method. + * + * If the plugin has never been run before a new instance of it will be created within the Plugin Manager, + * its active state set and then both of its `init` and `start` methods called, in that order. + * + * If the plugin is already running under the given key then nothing happens. + * + * @method Phaser.Plugins.PluginManager#start + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to start. + * @param {string} [runAs] - Run the plugin under a new key. This allows you to run one plugin multiple times. + * + * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if invalid key given or plugin is already stopped. + */ + start: function (key, runAs) + { + if (runAs === undefined) { runAs = key; } + + var entry = this.getEntry(runAs); + + // Plugin already running under this key? + if (entry && !entry.active) + { + // It exists, we just need to start it up again + entry.active = true; + entry.plugin.start(); + } + else if (!entry) + { + entry = this.createEntry(key, runAs); + } + + return (entry) ? entry.plugin : null; + }, + + /** + * Creates a new instance of a global plugin, adds an entry into the plugins array and returns it. + * + * @method Phaser.Plugins.PluginManager#createEntry + * @private + * @since 3.9.0 + * + * @param {string} key - The key of the plugin to create an instance of. + * @param {string} [runAs] - Run the plugin under a new key. This allows you to run one plugin multiple times. + * + * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if invalid key given. + */ + createEntry: function (key, runAs) + { + var entry = PluginCache.getCustom(key); + + if (entry) + { + var instance = new entry.plugin(this); + + entry = { + key: runAs, + plugin: instance, + active: true, + mapping: entry.mapping, + data: entry.data + }; + + this.plugins.push(entry); + + instance.init(entry.data); + instance.start(); + } + + return entry; + }, + + /** + * Stops a global plugin from running. + * + * If the plugin is active then its active state will be set to false and the plugins `stop` method + * will be called. + * + * If the plugin is not already running, nothing will happen. + * + * @method Phaser.Plugins.PluginManager#stop + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to stop. + * + * @return {Phaser.Plugins.PluginManager} The Plugin Manager. + */ + stop: function (key) + { + var entry = this.getEntry(key); + + if (entry && entry.active) + { + entry.active = false; + entry.plugin.stop(); + } + + return this; + }, + + /** + * 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. + */ + get: function (key, autoStart) + { + if (autoStart === undefined) { autoStart = true; } + + var entry = this.getEntry(key); + + if (entry) + { + return entry.plugin; + } + else + { + var plugin = this.getClass(key); + + if (plugin && autoStart) + { + entry = this.createEntry(key, key); + + return (entry) ? entry.plugin : null; + } + else if (plugin) + { + return plugin; + } + } + + return null; + }, + + /** + * Returns the plugin class from the cache. + * Used internally by the Plugin Manager. + * + * @method Phaser.Plugins.PluginManager#getClass + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to get. + * + * @return {Phaser.Plugins.BasePlugin} A Plugin object + */ + getClass: function (key) + { + return PluginCache.getCustomClass(key); + }, + + /** + * Removes a global plugin from the Plugin Manager and Plugin Cache. + * + * It is up to you to remove all references to this plugin that you may hold within your game code. + * + * @method Phaser.Plugins.PluginManager#removeGlobalPlugin + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to remove. + */ + removeGlobalPlugin: function (key) + { + var entry = this.getEntry(key); + + if (entry) + { + Remove(this.plugins, entry); + } + + PluginCache.removeCustom(key); + }, + + /** + * Removes a scene plugin from the Plugin Manager and Plugin Cache. + * + * This will not remove the plugin from any active Scenes that are already using it. + * + * It is up to you to remove all references to this plugin that you may hold within your game code. + * + * @method Phaser.Plugins.PluginManager#removeScenePlugin + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to remove. + */ + removeScenePlugin: function (key) + { + Remove(this.scenePlugins, key); + + PluginCache.remove(key); + }, + + /** + * Registers a new type of Game Object with the global Game Object Factory and / or Creator. + * This is usually called from within your Plugin code and is a helpful short-cut for creating + * new Game Objects. + * + * The key is the property that will be injected into the factories and used to create the + * Game Object. For example: + * + * ```javascript + * this.plugins.registerGameObject('clown', clownFactoryCallback, clownCreatorCallback); + * // later in your game code: + * this.add.clown(); + * this.make.clown(); + * ``` + * + * The callbacks are what are called when the factories try to create a Game Object + * matching the given key. It's important to understand that the callbacks are invoked within + * the context of the GameObjectFactory. In this 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. + * + * See the GameObjectFactory and GameObjectCreator classes for more details. + * Any public property or method listed is available from your callbacks under `this`. + * + * @method Phaser.Plugins.PluginManager#registerGameObject + * @since 3.8.0 + * + * @param {string} key - The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. + * @param {function} [factoryCallback] - The callback to invoke when the Game Object Factory is called. + * @param {function} [creatorCallback] - The callback to invoke when the Game Object Creator is called. + */ + registerGameObject: function (key, factoryCallback, creatorCallback) + { + if (factoryCallback) + { + GameObjectFactory.register(key, factoryCallback); + } + + if (creatorCallback) + { + GameObjectCreator.register(key, creatorCallback); + } + + return this; + }, + + /** + * Removes a previously registered Game Object from the global Game Object Factory and / or Creator. + * This is usually called from within your Plugin destruction code to help clean-up after your plugin has been removed. + * + * @method Phaser.Plugins.PluginManager#removeGameObject + * @since 3.19.0 + * + * @param {string} key - The key of the Game Object to be removed from the factories. + * @param {boolean} [removeFromFactory=true] - Should the Game Object be removed from the Game Object Factory? + * @param {boolean} [removeFromCreator=true] - Should the Game Object be removed from the Game Object Creator? + */ + removeGameObject: function (key, removeFromFactory, removeFromCreator) + { + if (removeFromFactory === undefined) { removeFromFactory = true; } + if (removeFromCreator === undefined) { removeFromCreator = true; } + + if (removeFromFactory) + { + GameObjectFactory.remove(key); + } + + if (removeFromCreator) + { + GameObjectCreator.remove(key); + } + + return this; + }, + + /** + * Registers a new file type with the global File Types Manager, making it available to all Loader + * Plugins created after this. + * + * This is usually called from within your Plugin code and is a helpful short-cut for creating + * new loader file types. + * + * The key is the property that will be injected into the Loader Plugin and used to load the + * files. For example: + * + * ```javascript + * this.plugins.registerFileType('wad', doomWadLoaderCallback); + * // later in your preload code: + * this.load.wad(); + * ``` + * + * The callback is what is called when the loader tries to load a file matching the given key. + * It's important to understand that the callback is invoked within + * the context of the LoaderPlugin. In this context there are several properties / methods available + * to use: + * + * this.addFile - A method to add the new file to the load queue. + * this.scene - The Scene that owns the Loader Plugin instance. + * + * See the LoaderPlugin class for more details. Any public property or method listed is available from + * your callback under `this`. + * + * @method Phaser.Plugins.PluginManager#registerFileType + * @since 3.8.0 + * + * @param {string} key - The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. + * @param {function} callback - The callback to invoke when the Game Object Factory is called. + * @param {Phaser.Scene} [addToScene] - Optionally add this file type into the Loader Plugin owned by the given Scene. + */ + registerFileType: function (key, callback, addToScene) + { + FileTypesManager.register(key, callback); + + if (addToScene && addToScene.sys.load) + { + addToScene.sys.load[key] = callback; + } + }, + + /** + * Destroys this Plugin Manager and all associated plugins. + * It will iterate all plugins found and call their `destroy` methods. + * + * The PluginCache will remove all custom plugins. + * + * @method Phaser.Plugins.PluginManager#destroy + * @since 3.8.0 + */ + destroy: function () + { + for (var i = 0; i < this.plugins.length; i++) + { + this.plugins[i].plugin.destroy(); + } + + PluginCache.destroyCustomPlugins(); + + if (this.game.noReturn) + { + PluginCache.destroyCorePlugins(); + } + + this.game = null; + this.plugins = []; + this.scenePlugins = []; + } + +}); + +/* + * "Sometimes, the elegant implementation is just a function. + * Not a method. Not a class. Not a framework. Just a function." + * -- John Carmack + */ + +module.exports = PluginManager; + + +/***/ }), +/* 395 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(190); +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(104); +var GameEvents = __webpack_require__(21); +var GetInnerHeight = __webpack_require__(892); +var GetTarget = __webpack_require__(387); +var GetScreenOrientation = __webpack_require__(382); +var NOOP = __webpack_require__(2); +var Rectangle = __webpack_require__(11); +var Size = __webpack_require__(396); +var SnapFloor = __webpack_require__(105); +var Vector2 = __webpack_require__(3); + +/** + * @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. + */ +var ScaleManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function ScaleManager (game) + { + EventEmitter.call(this); + + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.Scale.ScaleManager#game + * @type {Phaser.Game} + * @readonly + * @since 3.15.0 + */ + this.game = game; + + /** + * A reference to the HTML Canvas Element that Phaser uses to render the game. + * + * @name Phaser.Scale.ScaleManager#canvas + * @type {HTMLCanvasElement} + * @since 3.16.0 + */ + this.canvas; + + /** + * The DOM bounds of the canvas element. + * + * @name Phaser.Scale.ScaleManager#canvasBounds + * @type {Phaser.Geom.Rectangle} + * @since 3.16.0 + */ + this.canvasBounds = new Rectangle(); + + /** + * The parent object of the Canvas. Often a div, or the browser window, or nothing in non-browser environments. + * + * This is set in the Game Config as the `parent` property. If undefined (or just not present), it will default + * to use the document body. If specifically set to `null` Phaser will ignore all parent operations. + * + * @name Phaser.Scale.ScaleManager#parent + * @type {?any} + * @since 3.16.0 + */ + this.parent = null; + + /** + * Is the parent element the browser window? + * + * @name Phaser.Scale.ScaleManager#parentIsWindow + * @type {boolean} + * @since 3.16.0 + */ + this.parentIsWindow = false; + + /** + * The Parent Size component. + * + * @name Phaser.Scale.ScaleManager#parentSize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.parentSize = new Size(); + + /** + * The Game Size component. + * + * The un-modified game size, as requested in the game config (the raw width / height), + * as used for world bounds, cameras, etc + * + * @name Phaser.Scale.ScaleManager#gameSize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.gameSize = new Size(); + + /** + * The Base Size component. + * + * The modified game size, which is the gameSize * resolution, used to set the canvas width and height + * (but not the CSS style) + * + * @name Phaser.Scale.ScaleManager#baseSize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.baseSize = new Size(); + + /** + * The Display Size component. + * + * The size used for the canvas style, factoring in the scale mode, parent and other values. + * + * @name Phaser.Scale.ScaleManager#displaySize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.displaySize = new Size(); + + /** + * The game scale mode. + * + * @name Phaser.Scale.ScaleManager#scaleMode + * @type {Phaser.Scale.ScaleModeType} + * @since 3.16.0 + */ + this.scaleMode = CONST.SCALE_MODE.NONE; + + /** + * The canvas resolution. + * + * This is hard-coded to a value of 1 in the 3.16 release of Phaser and will be enabled at a later date. + * + * @name Phaser.Scale.ScaleManager#resolution + * @type {number} + * @since 3.16.0 + */ + this.resolution = 1; + + /** + * The game zoom factor. + * + * This value allows you to multiply your games base size by the given zoom factor. + * This is then used when calculating the display size, even in `NONE` situations. + * If you don't want Phaser to touch the canvas style at all, this value should be 1. + * + * Can also be set to `MAX_ZOOM` in which case the zoom value will be derived based + * on the game size and available space within the parent. + * + * @name Phaser.Scale.ScaleManager#zoom + * @type {number} + * @since 3.16.0 + */ + this.zoom = 1; + + /** + * Internal flag set when the game zoom factor is modified. + * + * @name Phaser.Scale.ScaleManager#_resetZoom + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this._resetZoom = false; + + /** + * The scale factor between the baseSize and the canvasBounds. + * + * @name Phaser.Scale.ScaleManager#displayScale + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ + this.displayScale = new Vector2(1, 1); + + /** + * If set, the canvas sizes will be automatically passed through Math.floor. + * This results in rounded pixel display values, which is important for performance on legacy + * and low powered devices, but at the cost of not achieving a 'perfect' fit in some browser windows. + * + * @name Phaser.Scale.ScaleManager#autoRound + * @type {boolean} + * @since 3.16.0 + */ + this.autoRound = false; + + /** + * Automatically center the canvas within the parent? The different centering modes are: + * + * 1. No centering. + * 2. Center both horizontally and vertically. + * 3. Center horizontally. + * 4. Center vertically. + * + * Please be aware that in order to center the game canvas, you must have specified a parent + * that has a size set, or the canvas parent is the document.body. + * + * @name Phaser.Scale.ScaleManager#autoCenter + * @type {Phaser.Scale.CenterType} + * @since 3.16.0 + */ + this.autoCenter = CONST.CENTER.NO_CENTER; + + /** + * The current device orientation. + * + * Orientation events are dispatched via the Device Orientation API, typically only on mobile browsers. + * + * @name Phaser.Scale.ScaleManager#orientation + * @type {Phaser.Scale.OrientationType} + * @since 3.16.0 + */ + this.orientation = CONST.ORIENTATION.LANDSCAPE; + + /** + * A reference to the Device.Fullscreen object. + * + * @name Phaser.Scale.ScaleManager#fullscreen + * @type {Phaser.Device.Fullscreen} + * @since 3.16.0 + */ + this.fullscreen; + + /** + * The DOM Element which is sent into fullscreen mode. + * + * @name Phaser.Scale.ScaleManager#fullscreenTarget + * @type {?any} + * @since 3.16.0 + */ + this.fullscreenTarget = null; + + /** + * Did Phaser create the fullscreen target div, or was it provided in the game config? + * + * @name Phaser.Scale.ScaleManager#_createdFullscreenTarget + * @type {boolean} + * @private + * @since 3.16.0 + */ + this._createdFullscreenTarget = false; + + /** + * The dirty state of the Scale Manager. + * Set if there is a change between the parent size and the current size. + * + * @name Phaser.Scale.ScaleManager#dirty + * @type {boolean} + * @since 3.16.0 + */ + this.dirty = false; + + /** + * 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 {integer} + * @since 3.16.0 + */ + this.resizeInterval = 500; + + /** + * Internal size interval tracker. + * + * @name Phaser.Scale.ScaleManager#_lastCheck + * @type {integer} + * @private + * @since 3.16.0 + */ + this._lastCheck = 0; + + /** + * Internal flag to check orientation state. + * + * @name Phaser.Scale.ScaleManager#_checkOrientation + * @type {boolean} + * @private + * @since 3.16.0 + */ + this._checkOrientation = false; + + /** + * Internal object containing our defined event listeners. + * + * @name Phaser.Scale.ScaleManager#listeners + * @type {object} + * @private + * @since 3.16.0 + */ + this.listeners = { + + orientationChange: NOOP, + windowResize: NOOP, + fullScreenChange: NOOP, + fullScreenError: NOOP + + }; + }, + + /** + * Called _before_ the canvas object is created and added to the DOM. + * + * @method Phaser.Scale.ScaleManager#preBoot + * @protected + * @listens Phaser.Core.Events#BOOT + * @since 3.16.0 + */ + preBoot: function () + { + // Parse the config to get the scaling values we need + this.parseConfig(this.game.config); + + this.game.events.once('boot', this.boot, this); + }, + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * The renderer is available by now and the canvas has been added to the DOM. + * + * @method Phaser.Scale.ScaleManager#boot + * @protected + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + */ + boot: function () + { + var game = this.game; + + this.canvas = game.canvas; + + this.fullscreen = game.device.fullscreen; + + if (this.scaleMode !== CONST.SCALE_MODE.RESIZE) + { + this.displaySize.setAspectMode(this.scaleMode); + } + + if (this.scaleMode === CONST.SCALE_MODE.NONE) + { + this.resize(this.width, this.height); + } + else + { + this.getParentBounds(); + + // Only set the parent bounds if the parent has an actual size + if (this.parentSize.width > 0 && this.parentSize.height > 0) + { + this.displaySize.setParent(this.parentSize); + } + + this.refresh(); + } + + game.events.on(GameEvents.PRE_STEP, this.step, this); + game.events.once(GameEvents.DESTROY, this.destroy, this); + + this.startListeners(); + }, + + /** + * Parses the game configuration to set-up the scale defaults. + * + * @method Phaser.Scale.ScaleManager#parseConfig + * @protected + * @since 3.16.0 + * + * @param {Phaser.Types.Core.GameConfig} config - The Game configuration object. + */ + parseConfig: function (config) + { + // Get the parent element, if any + this.getParent(config); + + // Get the size of the parent element + // This can often set a height of zero (especially for un-styled divs) + this.getParentBounds(); + + var width = config.width; + var height = config.height; + var scaleMode = config.scaleMode; + var resolution = config.resolution; + var zoom = config.zoom; + var autoRound = config.autoRound; + + // If width = '100%', or similar value + if (typeof width === 'string') + { + // If we have a parent with a height, we'll work it out from that + var parentWidth = this.parentSize.width; + + if (parentWidth === 0) + { + parentWidth = window.innerWidth; + } + + var parentScaleX = parseInt(width, 10) / 100; + + width = Math.floor(parentWidth * parentScaleX); + } + + // If height = '100%', or similar value + if (typeof height === 'string') + { + // If we have a parent with a height, we'll work it out from that + var parentHeight = this.parentSize.height; + + if (parentHeight === 0) + { + parentHeight = window.innerHeight; + } + + var parentScaleY = parseInt(height, 10) / 100; + + height = Math.floor(parentHeight * parentScaleY); + } + + // This is fixed at 1 on purpose. + // Changing it will break all user input. + // Wait for another release to solve this issue. + this.resolution = 1; + + this.scaleMode = scaleMode; + + this.autoRound = autoRound; + + this.autoCenter = config.autoCenter; + + this.resizeInterval = config.resizeInterval; + + if (autoRound) + { + width = Math.floor(width); + height = Math.floor(height); + } + + // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc + this.gameSize.setSize(width, height); + + if (zoom === CONST.ZOOM.MAX_ZOOM) + { + zoom = this.getMaxZoom(); + } + + this.zoom = zoom; + + if (zoom !== 1) + { + this._resetZoom = true; + } + + // The modified game size, which is the w/h * resolution + this.baseSize.setSize(width * resolution, height * resolution); + + if (autoRound) + { + this.baseSize.width = Math.floor(this.baseSize.width); + this.baseSize.height = Math.floor(this.baseSize.height); + } + + if (config.minWidth > 0) + { + this.displaySize.setMin(config.minWidth * zoom, config.minHeight * zoom); + } + + if (config.maxWidth > 0) + { + this.displaySize.setMax(config.maxWidth * zoom, config.maxHeight * zoom); + } + + // 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) + this.displaySize.setSize(width, height); + + this.orientation = GetScreenOrientation(width, height); + }, + + /** + * 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. + */ + getParent: function (config) + { + var parent = config.parent; + + if (parent === null) + { + // User is responsible for managing the parent + return; + } + + this.parent = GetTarget(parent); + this.parentIsWindow = (this.parent === document.body); + + if (config.expandParent && config.scaleMode !== CONST.SCALE_MODE.NONE) + { + var DOMRect = this.parent.getBoundingClientRect(); + + if (this.parentIsWindow || DOMRect.height === 0) + { + document.documentElement.style.height = '100%'; + document.body.style.height = '100%'; + + DOMRect = this.parent.getBoundingClientRect(); + + // The parent STILL has no height, clearly no CSS + // has been set on it even though we fixed the body :( + if (!this.parentIsWindow && DOMRect.height === 0) + { + this.parent.style.overflow = 'hidden'; + this.parent.style.width = '100%'; + this.parent.style.height = '100%'; + } + } + } + + // And now get the fullscreenTarget + if (config.fullscreenTarget && !this.fullscreenTarget) + { + this.fullscreenTarget = GetTarget(config.fullscreenTarget); + } + }, + + /** + * Calculates the size of the parent bounds and updates the `parentSize` component, if the canvas has a dom parent. + * + * @method Phaser.Scale.ScaleManager#getParentBounds + * @since 3.16.0 + * + * @return {boolean} `true` if the parent bounds have changed size, otherwise `false`. + */ + getParentBounds: function () + { + if (!this.parent) + { + return false; + } + + var parentSize = this.parentSize; + + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + + var DOMRect = this.parent.getBoundingClientRect(); + + if (this.parentIsWindow && this.game.device.os.iOS) + { + DOMRect.height = GetInnerHeight(true); + } + + var resolution = this.resolution; + var newWidth = DOMRect.width * resolution; + var newHeight = DOMRect.height * resolution; + + if (parentSize.width !== newWidth || parentSize.height !== newHeight) + { + parentSize.setSize(newWidth, newHeight); + + return true; + } + else + { + return false; + } + }, + + /** + * 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`. + */ + lockOrientation: function (orientation) + { + var lock = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; + + if (lock) + { + return lock(orientation); + } + + return false; + }, + + /** + * This method will set the size of the Parent Size component, which is used in scaling + * and centering calculations. You only need to call this method if you have explicitly + * disabled the use of a parent in your game config, but still wish to take advantage of + * other Scale Manager features. + * + * @method Phaser.Scale.ScaleManager#setParentSize + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + * + * @param {number} width - The new width of the parent. + * @param {number} height - The new height of the parent. + * + * @return {this} The Scale Manager instance. + */ + setParentSize: function (width, height) + { + this.parentSize.setSize(width, height); + + return this.refresh(); + }, + + /** + * This method will set a new size for your game. + * + * It should only be used if you're looking to change the base size of your game and are using + * one of the Scale Manager scaling modes, i.e. `FIT`. If you're using `NONE` and wish to + * change the game and canvas size directly, then please use the `resize` method instead. + * + * @method Phaser.Scale.ScaleManager#setGameSize + * @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. + */ + setGameSize: function (width, height) + { + var autoRound = this.autoRound; + var resolution = this.resolution; + + if (autoRound) + { + width = Math.floor(width); + height = Math.floor(height); + } + + var previousWidth = this.width; + var previousHeight = this.height; + + // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc + this.gameSize.resize(width, height); + + // The modified game size, which is the w/h * resolution + this.baseSize.resize(width * resolution, height * resolution); + + if (autoRound) + { + this.baseSize.width = Math.floor(this.baseSize.width); + this.baseSize.height = Math.floor(this.baseSize.height); + } + + // 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) + this.displaySize.setSize(width, height); + + this.canvas.width = this.baseSize.width; + this.canvas.height = this.baseSize.height; + + return this.refresh(previousWidth, previousHeight); + }, + + /** + * 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. + */ + resize: function (width, height) + { + var zoom = this.zoom; + var resolution = this.resolution; + var autoRound = this.autoRound; + + if (autoRound) + { + width = Math.floor(width); + height = Math.floor(height); + } + + var previousWidth = this.width; + var previousHeight = this.height; + + // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc + this.gameSize.resize(width, height); + + // The modified game size, which is the w/h * resolution + this.baseSize.resize(width * resolution, height * resolution); + + if (autoRound) + { + this.baseSize.width = Math.floor(this.baseSize.width); + this.baseSize.height = Math.floor(this.baseSize.height); + } + + // 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) + this.displaySize.setSize((width * zoom) * resolution, (height * zoom) * resolution); + + this.canvas.width = this.baseSize.width; + this.canvas.height = this.baseSize.height; + + var style = this.canvas.style; + + var styleWidth = width * zoom; + var styleHeight = height * zoom; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + if (styleWidth !== width || styleHeight !== height) + { + style.width = styleWidth + 'px'; + style.height = styleHeight + 'px'; + } + + return this.refresh(previousWidth, previousHeight); + }, + + /** + * Sets the zoom value of the Scale Manager. + * + * @method Phaser.Scale.ScaleManager#setZoom + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + * + * @param {integer} value - The new zoom value of the game. + * + * @return {this} The Scale Manager instance. + */ + setZoom: function (value) + { + this.zoom = value; + this._resetZoom = true; + + return this.refresh(); + }, + + /** + * 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. + */ + setMaxZoom: function () + { + this.zoom = this.getMaxZoom(); + this._resetZoom = true; + + return this.refresh(); + }, + + /** + * Refreshes the internal scale values, bounds sizes and orientation checks. + * + * Once finished, dispatches the resize event. + * + * This is called automatically by the Scale Manager when the browser window size changes, + * as long as it is using a Scale Mode other than 'NONE'. + * + * @method Phaser.Scale.ScaleManager#refresh + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + * + * @param {number} [previousWidth] - The previous width of the game. Only set if the gameSize has changed. + * @param {number} [previousHeight] - The previous height of the game. Only set if the gameSize has changed. + * + * @return {this} The Scale Manager instance. + */ + refresh: function (previousWidth, previousHeight) + { + if (previousWidth === undefined) { previousWidth = this.width; } + if (previousHeight === undefined) { previousHeight = this.height; } + + this.updateScale(); + this.updateBounds(); + this.updateOrientation(); + + this.displayScale.set(this.baseSize.width / this.canvasBounds.width, this.baseSize.height / this.canvasBounds.height); + + var domContainer = this.game.domContainer; + + if (domContainer) + { + this.baseSize.setCSS(domContainer); + + var canvasStyle = this.canvas.style; + var domStyle = domContainer.style; + + domStyle.transform = 'scale(' + this.displaySize.width / this.baseSize.width + ',' + this.displaySize.height / this.baseSize.height + ')'; + + domStyle.marginLeft = canvasStyle.marginLeft; + domStyle.marginTop = canvasStyle.marginTop; + } + + this.emit(Events.RESIZE, this.gameSize, this.baseSize, this.displaySize, this.resolution, previousWidth, previousHeight); + + return this; + }, + + /** + * Internal method that checks the current screen orientation, only if the internal check flag is set. + * + * If the orientation has changed it updates the orientation property and then dispatches the orientation change event. + * + * @method Phaser.Scale.ScaleManager#updateOrientation + * @fires Phaser.Scale.Events#ORIENTATION_CHANGE + * @since 3.16.0 + */ + updateOrientation: function () + { + if (this._checkOrientation) + { + this._checkOrientation = false; + + var newOrientation = GetScreenOrientation(this.width, this.height); + + if (newOrientation !== this.orientation) + { + this.orientation = newOrientation; + + this.emit(Events.ORIENTATION_CHANGE, newOrientation); + } + } + }, + + /** + * Internal method that manages updating the size components based on the scale mode. + * + * @method Phaser.Scale.ScaleManager#updateScale + * @since 3.16.0 + */ + updateScale: function () + { + var style = this.canvas.style; + + var width = this.gameSize.width; + var height = this.gameSize.height; + + var styleWidth; + var styleHeight; + + var zoom = this.zoom; + var autoRound = this.autoRound; + var resolution = 1; + + if (this.scaleMode === CONST.SCALE_MODE.NONE) + { + // No scale + this.displaySize.setSize((width * zoom) * resolution, (height * zoom) * resolution); + + styleWidth = this.displaySize.width / resolution; + styleHeight = this.displaySize.height / resolution; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + if (this._resetZoom) + { + style.width = styleWidth + 'px'; + style.height = styleHeight + 'px'; + + this._resetZoom = false; + } + } + else if (this.scaleMode === CONST.SCALE_MODE.RESIZE) + { + // Resize to match parent + + // This will constrain using min/max + this.displaySize.setSize(this.parentSize.width, this.parentSize.height); + + this.gameSize.setSize(this.displaySize.width, this.displaySize.height); + + this.baseSize.setSize(this.displaySize.width * resolution, this.displaySize.height * resolution); + + styleWidth = this.displaySize.width / resolution; + styleHeight = this.displaySize.height / resolution; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + this.canvas.width = styleWidth; + this.canvas.height = styleHeight; + } + else + { + // All other scale modes + this.displaySize.setSize(this.parentSize.width, this.parentSize.height); + + styleWidth = this.displaySize.width / resolution; + styleHeight = this.displaySize.height / resolution; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + style.width = styleWidth + 'px'; + style.height = styleHeight + 'px'; + } + + // Update the parentSize in case the canvas / style change modified it + this.getParentBounds(); + + // Finally, update the centering + this.updateCenter(); + }, + + /** + * 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 {integer} The maximum possible zoom factor. At a minimum this value is always at least 1. + */ + getMaxZoom: function () + { + var zoomH = SnapFloor(this.parentSize.width, this.gameSize.width, 0, true); + var zoomV = SnapFloor(this.parentSize.height, this.gameSize.height, 0, true); + + return Math.max(Math.min(zoomH, zoomV), 1); + }, + + /** + * Calculates and updates the canvas CSS style in order to center it within the + * bounds of its parent. If you have explicitly set parent to be `null` in your + * game config then this method will likely give incorrect results unless you have called the + * `setParentSize` method first. + * + * It works by modifying the canvas CSS `marginLeft` and `marginTop` properties. + * + * If they have already been set by your own style sheet, or code, this will overwrite them. + * + * To prevent the Scale Manager from centering the canvas, either do not set the + * `autoCenter` property in your game config, or make sure it is set to `NO_CENTER`. + * + * @method Phaser.Scale.ScaleManager#updateCenter + * @since 3.16.0 + */ + updateCenter: function () + { + var autoCenter = this.autoCenter; + + if (autoCenter === CONST.CENTER.NO_CENTER) + { + return; + } + + var canvas = this.canvas; + + var style = canvas.style; + + var bounds = canvas.getBoundingClientRect(); + + // var width = parseInt(canvas.style.width, 10) || canvas.width; + // var height = parseInt(canvas.style.height, 10) || canvas.height; + + var width = bounds.width; + var height = bounds.height; + + var offsetX = Math.floor((this.parentSize.width - width) / 2); + var offsetY = Math.floor((this.parentSize.height - height) / 2); + + if (autoCenter === CONST.CENTER.CENTER_HORIZONTALLY) + { + offsetY = 0; + } + else if (autoCenter === CONST.CENTER.CENTER_VERTICALLY) + { + offsetX = 0; + } + + style.marginLeft = offsetX + 'px'; + style.marginTop = offsetY + 'px'; + }, + + /** + * Updates the `canvasBounds` rectangle to match the bounding client rectangle of the + * canvas element being used to track input events. + * + * @method Phaser.Scale.ScaleManager#updateBounds + * @since 3.16.0 + */ + updateBounds: function () + { + var bounds = this.canvasBounds; + var clientRect = this.canvas.getBoundingClientRect(); + + bounds.x = clientRect.left + (window.pageXOffset || 0) - (document.documentElement.clientLeft || 0); + bounds.y = clientRect.top + (window.pageYOffset || 0) - (document.documentElement.clientTop || 0); + bounds.width = clientRect.width; + bounds.height = clientRect.height; + }, + + /** + * Transforms the pageX value into the scaled coordinate space of the Scale Manager. + * + * @method Phaser.Scale.ScaleManager#transformX + * @since 3.16.0 + * + * @param {number} pageX - The DOM pageX value. + * + * @return {number} The translated value. + */ + transformX: function (pageX) + { + return (pageX - this.canvasBounds.left) * this.displayScale.x; + }, + + /** + * Transforms the pageY value into the scaled coordinate space of the Scale Manager. + * + * @method Phaser.Scale.ScaleManager#transformY + * @since 3.16.0 + * + * @param {number} pageY - The DOM pageY value. + * + * @return {number} The translated value. + */ + transformY: function (pageY) + { + return (pageY - this.canvasBounds.top) * this.displayScale.y; + }, + + /** + * 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 user-input gesture, such as `pointerup`. 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 `
` 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. + */ + startFullscreen: function (fullscreenOptions) + { + if (fullscreenOptions === undefined) { fullscreenOptions = { navigationUI: 'hide' }; } + + var fullscreen = this.fullscreen; + + if (!fullscreen.available) + { + this.emit(Events.FULLSCREEN_UNSUPPORTED); + + return; + } + + if (!fullscreen.active) + { + var fsTarget = this.getFullscreenTarget(); + + var fsPromise; + + if (fullscreen.keyboard) + { + fsPromise = fsTarget[fullscreen.request](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsPromise = fsTarget[fullscreen.request](fullscreenOptions); + } + + if (fsPromise) + { + fsPromise.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)); + } + else if (fullscreen.active) + { + this.fullscreenSuccessHandler(); + } + else + { + this.fullscreenErrorHandler(); + } + } + }, + + /** + * The browser has successfully entered fullscreen mode. + * + * @method Phaser.Scale.ScaleManager#fullscreenSuccessHandler + * @private + * @fires Phaser.Scale.Events#ENTER_FULLSCREEN + * @fires Phaser.Scale.Events#RESIZE + * @since 3.17.0 + */ + fullscreenSuccessHandler: function () + { + this.getParentBounds(); + + this.refresh(); + + this.emit(Events.ENTER_FULLSCREEN); + }, + + /** + * The browser failed to enter fullscreen mode. + * + * @method Phaser.Scale.ScaleManager#fullscreenErrorHandler + * @private + * @fires Phaser.Scale.Events#FULLSCREEN_FAILED + * @fires Phaser.Scale.Events#RESIZE + * @since 3.17.0 + * + * @param {any} error - The DOM error event. + */ + fullscreenErrorHandler: function (error) + { + this.removeFullscreenTarget(); + + this.emit(Events.FULLSCREEN_FAILED, error); + }, + + /** + * An internal method that gets the target element that is used when entering fullscreen mode. + * + * @method Phaser.Scale.ScaleManager#getFullscreenTarget + * @since 3.16.0 + * + * @return {object} The fullscreen target element. + */ + getFullscreenTarget: function () + { + if (!this.fullscreenTarget) + { + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + + this.fullscreenTarget = fsTarget; + + this._createdFullscreenTarget = true; + } + + if (this._createdFullscreenTarget) + { + var canvasParent = this.canvas.parentNode; + + canvasParent.insertBefore(this.fullscreenTarget, this.canvas); + + this.fullscreenTarget.appendChild(this.canvas); + } + + return this.fullscreenTarget; + }, + + /** + * Removes the fullscreen target that was added to the DOM. + * + * @method Phaser.Scale.ScaleManager#removeFullscreenTarget + * @since 3.17.0 + */ + removeFullscreenTarget: function () + { + if (this._createdFullscreenTarget) + { + var fsTarget = this.fullscreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + var parent = fsTarget.parentNode; + + parent.insertBefore(this.canvas, fsTarget); + + parent.removeChild(fsTarget); + } + } + }, + + /** + * Calling this method will cancel fullscreen mode, if the browser has entered it. + * + * @method Phaser.Scale.ScaleManager#stopFullscreen + * @fires Phaser.Scale.Events#LEAVE_FULLSCREEN + * @fires Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED + * @since 3.16.0 + */ + stopFullscreen: function () + { + var fullscreen = this.fullscreen; + + if (!fullscreen.available) + { + this.emit(Events.FULLSCREEN_UNSUPPORTED); + + return false; + } + + if (fullscreen.active) + { + document[fullscreen.cancel](); + } + + this.removeFullscreenTarget(); + + // Get the parent size again as it will have changed + this.getParentBounds(); + + this.emit(Events.LEAVE_FULLSCREEN); + + this.refresh(); + }, + + /** + * Toggles the fullscreen mode. If already in fullscreen, calling this will cancel it. + * If not in fullscreen, this will request the browser to enter fullscreen mode. + * + * If the browser does not support this, a `FULLSCREEN_UNSUPPORTED` event will be emitted. + * + * This method _must_ be called from a user-input gesture, such as `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. + * + * @method Phaser.Scale.ScaleManager#toggleFullscreen + * @fires Phaser.Scale.Events#ENTER_FULLSCREEN + * @fires Phaser.Scale.Events#LEAVE_FULLSCREEN + * @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. + */ + toggleFullscreen: function (fullscreenOptions) + { + if (this.fullscreen.active) + { + this.stopFullscreen(); + } + else + { + this.startFullscreen(fullscreenOptions); + } + }, + + /** + * An internal method that starts the different DOM event listeners running. + * + * @method Phaser.Scale.ScaleManager#startListeners + * @since 3.16.0 + */ + startListeners: function () + { + var _this = this; + var listeners = this.listeners; + + listeners.orientationChange = function () + { + _this._checkOrientation = true; + _this.dirty = true; + }; + + listeners.windowResize = function () + { + _this.dirty = true; + }; + + // Only dispatched on mobile devices + window.addEventListener('orientationchange', listeners.orientationChange, false); + + window.addEventListener('resize', listeners.windowResize, false); + + if (this.fullscreen.available) + { + listeners.fullScreenChange = function (event) + { + return _this.onFullScreenChange(event); + }; + + listeners.fullScreenError = function (event) + { + return _this.onFullScreenError(event); + }; + + var vendors = [ 'webkit', 'moz', '' ]; + + vendors.forEach(function (prefix) + { + document.addEventListener(prefix + 'fullscreenchange', listeners.fullScreenChange, false); + document.addEventListener(prefix + 'fullscreenerror', listeners.fullScreenError, false); + }); + + // MS Specific + document.addEventListener('MSFullscreenChange', listeners.fullScreenChange, false); + document.addEventListener('MSFullscreenError', listeners.fullScreenError, false); + } + }, + + /** + * Triggered when a fullscreenchange event is dispatched by the DOM. + * + * @method Phaser.Scale.ScaleManager#onFullScreenChange + * @since 3.16.0 + */ + onFullScreenChange: function () + { + // They pressed ESC while in fullscreen mode + if (!(document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement || document.mozFullScreenElement)) + { + this.stopFullscreen(); + } + }, + + /** + * Triggered when a fullscreenerror event is dispatched by the DOM. + * + * @method Phaser.Scale.ScaleManager#onFullScreenError + * @since 3.16.0 + */ + onFullScreenError: function () + { + this.removeFullscreenTarget(); + }, + + /** + * Internal method, called automatically by the game step. + * Monitors the elapsed time and resize interval to see if a parent bounds check needs to take place. + * + * @method Phaser.Scale.ScaleManager#step + * @since 3.16.0 + * + * @param {number} time - The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). + * @param {number} delta - The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. + */ + step: function (time, delta) + { + if (!this.parent) + { + return; + } + + this._lastCheck += delta; + + if (this.dirty || this._lastCheck > this.resizeInterval) + { + // Returns true if the parent bounds have changed size + if (this.getParentBounds()) + { + this.refresh(); + } + + this.dirty = false; + this._lastCheck = 0; + } + }, + + /** + * Stops all DOM event listeners. + * + * @method Phaser.Scale.ScaleManager#stopListeners + * @since 3.16.0 + */ + stopListeners: function () + { + var listeners = this.listeners; + + window.removeEventListener('orientationchange', listeners.orientationChange, false); + window.removeEventListener('resize', listeners.windowResize, false); + + var vendors = [ 'webkit', 'moz', '' ]; + + vendors.forEach(function (prefix) + { + document.removeEventListener(prefix + 'fullscreenchange', listeners.fullScreenChange, false); + document.removeEventListener(prefix + 'fullscreenerror', listeners.fullScreenError, false); + }); + + // MS Specific + document.removeEventListener('MSFullscreenChange', listeners.fullScreenChange, false); + document.removeEventListener('MSFullscreenError', listeners.fullScreenError, false); + }, + + /** + * Destroys this Scale Manager, releasing all references to external resources. + * Once destroyed, the Scale Manager cannot be used again. + * + * @method Phaser.Scale.ScaleManager#destroy + * @since 3.16.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.stopListeners(); + + this.game = null; + this.canvas = null; + this.canvasBounds = null; + this.parent = null; + this.fullscreenTarget = null; + + this.parentSize.destroy(); + this.gameSize.destroy(); + this.baseSize.destroy(); + this.displaySize.destroy(); + }, + + /** + * Is the browser currently in fullscreen mode or not? + * + * @name Phaser.Scale.ScaleManager#isFullscreen + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isFullscreen: { + + get: function () + { + return this.fullscreen.active; + } + + }, + + /** + * The game width. + * + * This is typically the size given in the game configuration. + * + * @name Phaser.Scale.ScaleManager#width + * @type {number} + * @readonly + * @since 3.16.0 + */ + width: { + + get: function () + { + return this.gameSize.width; + } + + }, + + /** + * The game height. + * + * This is typically the size given in the game configuration. + * + * @name Phaser.Scale.ScaleManager#height + * @type {number} + * @readonly + * @since 3.16.0 + */ + height: { + + get: function () + { + return this.gameSize.height; + } + + }, + + /** + * Is the device in a portrait orientation as reported by the Orientation API? + * This value is usually only available on mobile devices. + * + * @name Phaser.Scale.ScaleManager#isPortrait + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isPortrait: { + + get: function () + { + return (this.orientation === CONST.ORIENTATION.PORTRAIT); + } + + }, + + /** + * Is the device in a landscape orientation as reported by the Orientation API? + * This value is usually only available on mobile devices. + * + * @name Phaser.Scale.ScaleManager#isLandscape + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isLandscape: { + + get: function () + { + return (this.orientation === CONST.ORIENTATION.LANDSCAPE); + } + + }, + + /** + * Are the game dimensions portrait? (i.e. taller than they are wide) + * + * This is different to the device itself being in a portrait orientation. + * + * @name Phaser.Scale.ScaleManager#isGamePortrait + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isGamePortrait: { + + get: function () + { + return (this.height > this.width); + } + + }, + + /** + * Are the game dimensions landscape? (i.e. wider than they are tall) + * + * This is different to the device itself being in a landscape orientation. + * + * @name Phaser.Scale.ScaleManager#isGameLandscape + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isGameLandscape: { + + get: function () + { + return (this.width > this.height); + } + + } + +}); + +module.exports = ScaleManager; + + +/***/ }), +/* 396 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var SnapFloor = __webpack_require__(105); +var Vector2 = __webpack_require__(3); + +/** + * @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 {integer} [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. + */ +var Size = new Class({ + + initialize: + + function Size (width, height, aspectMode, parent) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + if (aspectMode === undefined) { aspectMode = 0; } + if (parent === undefined) { parent = null; } + + /** + * Internal width value. + * + * @name Phaser.Structs.Size#_width + * @type {number} + * @private + * @since 3.16.0 + */ + this._width = width; + + /** + * Internal height value. + * + * @name Phaser.Structs.Size#_height + * @type {number} + * @private + * @since 3.16.0 + */ + this._height = height; + + /** + * Internal parent reference. + * + * @name Phaser.Structs.Size#_parent + * @type {any} + * @private + * @since 3.16.0 + */ + this._parent = parent; + + /** + * The aspect mode this Size component will use when calculating its dimensions. + * This property is read-only. To change it use the `setAspectMode` method. + * + * @name Phaser.Structs.Size#aspectMode + * @type {integer} + * @readonly + * @since 3.16.0 + */ + this.aspectMode = aspectMode; + + /** + * The proportional relationship between the width and height. + * + * This property is read-only and is updated automatically when either the `width` or `height` properties are changed, + * depending on the aspect mode. + * + * @name Phaser.Structs.Size#aspectRatio + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.aspectRatio = (height === 0) ? 1 : width / height; + + /** + * The minimum allowed width. + * Cannot be less than zero. + * This value is read-only. To change it see the `setMin` method. + * + * @name Phaser.Structs.Size#minWidth + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.minWidth = 0; + + /** + * The minimum allowed height. + * Cannot be less than zero. + * This value is read-only. To change it see the `setMin` method. + * + * @name Phaser.Structs.Size#minHeight + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.minHeight = 0; + + /** + * The maximum allowed width. + * This value is read-only. To change it see the `setMax` method. + * + * @name Phaser.Structs.Size#maxWidth + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.maxWidth = Number.MAX_VALUE; + + /** + * The maximum allowed height. + * This value is read-only. To change it see the `setMax` method. + * + * @name Phaser.Structs.Size#maxHeight + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.maxHeight = Number.MAX_VALUE; + + /** + * A Vector2 containing the horizontal and vertical snap values, which the width and height are snapped to during resizing. + * + * By default this is disabled. + * + * This property is read-only. To change it see the `setSnap` method. + * + * @name Phaser.Structs.Size#snapTo + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.16.0 + */ + this.snapTo = new Vector2(); + }, + + /** + * 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 {integer} [value=0] - The aspect mode value. + * + * @return {this} This Size component instance. + */ + setAspectMode: function (value) + { + if (value === undefined) { value = 0; } + + this.aspectMode = value; + + return this.setSize(this._width, this._height); + }, + + /** + * By setting a Snap To value when this Size component is modified its dimensions will automatically + * by snapped to the nearest grid slice, using floor. For example, if you have snap value of 16, + * and the width changes to 68, then it will snap down to 64 (the closest multiple of 16 when floored) + * + * Note that snapping takes place before adjustments by the parent, or the min / max settings. If these + * values are not multiples of the given snap values, then this can result in un-snapped dimensions. + * + * Call this method with no arguments to reset the snap values. + * + * Calling this method automatically recalculates the `width` and the `height`, if required. + * + * @method Phaser.Structs.Size#setSnap + * @since 3.16.0 + * + * @param {number} [snapWidth=0] - The amount to snap the width to. If you don't want to snap the width, pass a value of zero. + * @param {number} [snapHeight=snapWidth] - The amount to snap the height to. If not provided it will use the `snapWidth` value. If you don't want to snap the height, pass a value of zero. + * + * @return {this} This Size component instance. + */ + setSnap: function (snapWidth, snapHeight) + { + if (snapWidth === undefined) { snapWidth = 0; } + if (snapHeight === undefined) { snapHeight = snapWidth; } + + this.snapTo.set(snapWidth, snapHeight); + + return this.setSize(this._width, this._height); + }, + + /** + * 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. + */ + setParent: function (parent) + { + this._parent = parent; + + return this.setSize(this._width, this._height); + }, + + /** + * 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 exceed 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. + */ + setMin: function (width, height) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + + this.minWidth = Clamp(width, 0, this.maxWidth); + this.minHeight = Clamp(height, 0, this.maxHeight); + + return this.setSize(this._width, this._height); + }, + + /** + * 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 exceed 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. + */ + setMax: function (width, height) + { + if (width === undefined) { width = Number.MAX_VALUE; } + if (height === undefined) { height = width; } + + this.maxWidth = Clamp(width, this.minWidth, Number.MAX_VALUE); + this.maxHeight = Clamp(height, this.minHeight, Number.MAX_VALUE); + + return this.setSize(this._width, this._height); + }, + + /** + * 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. + */ + setSize: function (width, height) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + + switch (this.aspectMode) + { + case Size.NONE: + this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); + this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); + this.aspectRatio = (this._height === 0) ? 1 : this._width / this._height; + break; + + case Size.WIDTH_CONTROLS_HEIGHT: + this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); + this._height = this.getNewHeight(this._width * (1 / this.aspectRatio), false); + break; + + case Size.HEIGHT_CONTROLS_WIDTH: + this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); + this._width = this.getNewWidth(this._height * this.aspectRatio, false); + break; + + case Size.FIT: + this.constrain(width, height, true); + break; + + case Size.ENVELOP: + this.constrain(width, height, false); + break; + } + + return this; + }, + + /** + * Sets a new aspect ratio, overriding what was there previously. + * + * It then calls `setSize` immediately using the current dimensions. + * + * @method Phaser.Structs.Size#setAspectRatio + * @since 3.16.0 + * + * @param {number} ratio - The new aspect ratio. + * + * @return {this} This Size component instance. + */ + setAspectRatio: function (ratio) + { + this.aspectRatio = ratio; + + return this.setSize(this._width, this._height); + }, + + /** + * 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. + */ + resize: function (width, height) + { + this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); + this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); + this.aspectRatio = (this._height === 0) ? 1 : this._width / this._height; + + return this; + }, + + /** + * Takes a new width and passes it through the min/max clamp and then checks it doesn't exceed the parent width. + * + * @method Phaser.Structs.Size#getNewWidth + * @since 3.16.0 + * + * @param {number} value - The value to clamp and check. + * @param {boolean} [checkParent=true] - Check the given value against the parent, if set. + * + * @return {number} The modified width value. + */ + getNewWidth: function (value, checkParent) + { + if (checkParent === undefined) { checkParent = true; } + + value = Clamp(value, this.minWidth, this.maxWidth); + + if (checkParent && this._parent && value > this._parent.width) + { + value = Math.max(this.minWidth, this._parent.width); + } + + return value; + }, + + /** + * Takes a new height and passes it through the min/max clamp and then checks it doesn't exceed the parent height. + * + * @method Phaser.Structs.Size#getNewHeight + * @since 3.16.0 + * + * @param {number} value - The value to clamp and check. + * @param {boolean} [checkParent=true] - Check the given value against the parent, if set. + * + * @return {number} The modified height value. + */ + getNewHeight: function (value, checkParent) + { + if (checkParent === undefined) { checkParent = true; } + + value = Clamp(value, this.minHeight, this.maxHeight); + + if (checkParent && this._parent && value > this._parent.height) + { + value = Math.max(this.minHeight, this._parent.height); + } + + return value; + }, + + /** + * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. + * + * If `fit` is true there may be some space inside the target area which is not covered if its aspect ratio differs. + * If `fit` is false the size may extend further out than the target area if the aspect ratios differ. + * + * If this Size component has a parent set, then the width and height passed to this method will be clamped so + * it cannot exceed that of the parent. + * + * @method Phaser.Structs.Size#constrain + * @since 3.16.0 + * + * @param {number} [width=0] - The new width of the Size component. + * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. + * @param {boolean} [fit=true] - Perform a `fit` (true) constraint, or an `envelop` (false) constraint. + * + * @return {this} This Size component instance. + */ + constrain: function (width, height, fit) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + if (fit === undefined) { fit = true; } + + width = this.getNewWidth(width); + height = this.getNewHeight(height); + + var snap = this.snapTo; + var newRatio = (height === 0) ? 1 : width / height; + + if ((fit && this.aspectRatio > newRatio) || (!fit && this.aspectRatio < newRatio)) + { + // We need to change the height to fit the width + + width = SnapFloor(width, snap.x); + + height = width / this.aspectRatio; + + if (snap.y > 0) + { + height = SnapFloor(height, snap.y); + + // Reduce the width accordingly + width = height * this.aspectRatio; + } + } + else if ((fit && this.aspectRatio < newRatio) || (!fit && this.aspectRatio > newRatio)) + { + // We need to change the width to fit the height + + height = SnapFloor(height, snap.y); + + width = height * this.aspectRatio; + + if (snap.x > 0) + { + width = SnapFloor(width, snap.x); + + // Reduce the height accordingly + height = width * (1 / this.aspectRatio); + } + } + + this._width = width; + this._height = height; + + return this; + }, + + /** + * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. + * + * There may be some space inside the target area which is not covered if its aspect ratio differs. + * + * If this Size component has a parent set, then the width and height passed to this method will be clamped so + * it cannot exceed that of the parent. + * + * @method Phaser.Structs.Size#fitTo + * @since 3.16.0 + * + * @param {number} [width=0] - The new width of the Size component. + * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. + * + * @return {this} This Size component instance. + */ + fitTo: function (width, height) + { + return this.constrain(width, height, true); + }, + + /** + * The current `width` and `height` are adjusted so that they fully envelope the given dimensions, while keeping the aspect ratio. + * + * The size may extend further out than the target area if the aspect ratios differ. + * + * If this Size component has a parent set, then the values are clamped so that it never exceeds the parent + * on the longest axis. + * + * @method Phaser.Structs.Size#envelop + * @since 3.16.0 + * + * @param {number} [width=0] - The new width of the Size component. + * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. + * + * @return {this} This Size component instance. + */ + envelop: function (width, height) + { + return this.constrain(width, height, false); + }, + + /** + * Sets the width of this Size component. + * + * Depending on the aspect mode, changing the width may also update the height and aspect ratio. + * + * @method Phaser.Structs.Size#setWidth + * @since 3.16.0 + * + * @param {number} width - The new width of the Size component. + * + * @return {this} This Size component instance. + */ + setWidth: function (value) + { + return this.setSize(value, this._height); + }, + + /** + * Sets the height of this Size component. + * + * Depending on the aspect mode, changing the height may also update the width and aspect ratio. + * + * @method Phaser.Structs.Size#setHeight + * @since 3.16.0 + * + * @param {number} height - The new height of the Size component. + * + * @return {this} This Size component instance. + */ + setHeight: function (value) + { + return this.setSize(this._width, value); + }, + + /** + * Returns a string representation of this Size component. + * + * @method Phaser.Structs.Size#toString + * @since 3.16.0 + * + * @return {string} A string representation of this Size component. + */ + toString: function () + { + return '[{ Size (width=' + this._width + ' height=' + this._height + ' aspectRatio=' + this.aspectRatio + ' aspectMode=' + this.aspectMode + ') }]'; + }, + + /** + * Sets the values of this Size component to the `element.style.width` and `height` + * properties of the given DOM Element. The properties are set as `px` values. + * + * @method Phaser.Structs.Size#setCSS + * @since 3.17.0 + * + * @param {HTMLElement} element - The DOM Element to set the CSS style on. + */ + setCSS: function (element) + { + if (element && element.style) + { + element.style.width = this._width + 'px'; + element.style.height = this._height + 'px'; + } + }, + + /** + * Copies the aspect mode, aspect ratio, width and height from this Size component + * to the given Size component. Note that the parent, if set, is not copied across. + * + * @method Phaser.Structs.Size#copy + * @since 3.16.0 + * + * @param {Phaser.Structs.Size} destination - The Size component to copy the values to. + * + * @return {Phaser.Structs.Size} The updated destination Size component. + */ + copy: function (destination) + { + destination.setAspectMode(this.aspectMode); + + destination.aspectRatio = this.aspectRatio; + + return destination.setSize(this.width, this.height); + }, + + /** + * Destroys this Size component. + * + * This clears the local properties and any parent object, if set. + * + * A destroyed Size component cannot be re-used. + * + * @method Phaser.Structs.Size#destroy + * @since 3.16.0 + */ + destroy: function () + { + this._parent = null; + this.snapTo = null; + }, + + /** + * The width of this Size component. + * + * This value is clamped to the range specified by `minWidth` and `maxWidth`, if enabled. + * + * A width can never be less than zero. + * + * Changing this value will automatically update the `height` if the aspect ratio lock is enabled. + * You can also use the `setWidth` and `getWidth` methods. + * + * @name Phaser.Structs.Size#width + * @type {number} + * @since 3.16.0 + */ + width: { + + get: function () + { + return this._width; + }, + + set: function (value) + { + this.setSize(value, this._height); + } + + }, + + /** + * The height of this Size component. + * + * This value is clamped to the range specified by `minHeight` and `maxHeight`, if enabled. + * + * A height can never be less than zero. + * + * Changing this value will automatically update the `width` if the aspect ratio lock is enabled. + * You can also use the `setHeight` and `getHeight` methods. + * + * @name Phaser.Structs.Size#height + * @type {number} + * @since 3.16.0 + */ + height: { + + get: function () + { + return this._height; + }, + + set: function (value) + { + this.setSize(this._width, value); + } + + } + +}); + +/** + * Do not make the size fit the aspect ratio. Change the ratio when the size changes. + * + * @name Phaser.Structs.Size.NONE + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.NONE = 0; + +/** + * The height is automatically adjusted based on the width. + * + * @name Phaser.Structs.Size.WIDTH_CONTROLS_HEIGHT + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.WIDTH_CONTROLS_HEIGHT = 1; + +/** + * The width is automatically adjusted based on the height. + * + * @name Phaser.Structs.Size.HEIGHT_CONTROLS_WIDTH + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.HEIGHT_CONTROLS_WIDTH = 2; + +/** + * 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. + * + * @name Phaser.Structs.Size.FIT + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.FIT = 3; + +/** + * 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. + * + * @name Phaser.Structs.Size.ENVELOP + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.ENVELOP = 4; + +module.exports = Size; + + +/***/ }), +/* 397 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(132); +var Events = __webpack_require__(18); +var GameEvents = __webpack_require__(21); +var GetValue = __webpack_require__(5); +var LoaderEvents = __webpack_require__(87); +var NOOP = __webpack_require__(2); +var Scene = __webpack_require__(398); +var Systems = __webpack_require__(193); + +/** + * @classdesc + * The Scene Manager. + * + * The Scene Manager is a Game level system, responsible for creating, processing and updating all of the + * Scenes in a Game instance. + * + * + * @class SceneManager + * @memberof Phaser.Scenes + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance this Scene Manager belongs to. + * @param {object} sceneConfig - Scene specific configuration settings. + */ +var SceneManager = new Class({ + + initialize: + + function SceneManager (game, sceneConfig) + { + /** + * The Game that this SceneManager belongs to. + * + * @name Phaser.Scenes.SceneManager#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * An object that maps the keys to the scene so we can quickly get a scene from a key without iteration. + * + * @name Phaser.Scenes.SceneManager#keys + * @type {object} + * @since 3.0.0 + */ + this.keys = {}; + + /** + * The array in which all of the scenes are kept. + * + * @name Phaser.Scenes.SceneManager#scenes + * @type {array} + * @since 3.0.0 + */ + this.scenes = []; + + /** + * Scenes pending to be added are stored in here until the manager has time to add it. + * + * @name Phaser.Scenes.SceneManager#_pending + * @type {array} + * @private + * @since 3.0.0 + */ + this._pending = []; + + /** + * An array of scenes waiting to be started once the game has booted. + * + * @name Phaser.Scenes.SceneManager#_start + * @type {array} + * @private + * @since 3.0.0 + */ + this._start = []; + + /** + * An operations queue, because we don't manipulate the scenes array during processing. + * + * @name Phaser.Scenes.SceneManager#_queue + * @type {array} + * @private + * @since 3.0.0 + */ + this._queue = []; + + /** + * Boot time data to merge. + * + * @name Phaser.Scenes.SceneManager#_data + * @type {object} + * @private + * @since 3.4.0 + */ + this._data = {}; + + /** + * Is the Scene Manager actively processing the Scenes list? + * + * @name Phaser.Scenes.SceneManager#isProcessing + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isProcessing = false; + + /** + * Has the Scene Manager properly started? + * + * @name Phaser.Scenes.SceneManager#isBooted + * @type {boolean} + * @default false + * @readonly + * @since 3.4.0 + */ + this.isBooted = false; + + /** + * Do any of the Cameras in any of the Scenes require a custom viewport? + * If not we can skip scissor tests. + * + * @name Phaser.Scenes.SceneManager#customViewports + * @type {number} + * @default 0 + * @since 3.12.0 + */ + this.customViewports = 0; + + if (sceneConfig) + { + if (!Array.isArray(sceneConfig)) + { + sceneConfig = [ sceneConfig ]; + } + + for (var i = 0; i < sceneConfig.length; i++) + { + // The i === 0 part just autostarts the first Scene given (unless it says otherwise in its config) + this._pending.push({ + key: 'default', + scene: sceneConfig[i], + autoStart: (i === 0), + data: {} + }); + } + } + + game.events.once(GameEvents.READY, this.bootQueue, this); + }, + + /** + * Internal first-time Scene boot handler. + * + * @method Phaser.Scenes.SceneManager#bootQueue + * @private + * @since 3.2.0 + */ + bootQueue: function () + { + if (this.isBooted) + { + return; + } + + var i; + var entry; + var key; + var sceneConfig; + + for (i = 0; i < this._pending.length; i++) + { + entry = this._pending[i]; + + key = entry.key; + sceneConfig = entry.scene; + + var newScene; + + if (sceneConfig instanceof Scene) + { + newScene = this.createSceneFromInstance(key, sceneConfig); + } + else if (typeof sceneConfig === 'object') + { + newScene = this.createSceneFromObject(key, sceneConfig); + } + else if (typeof sceneConfig === 'function') + { + newScene = this.createSceneFromFunction(key, sceneConfig); + } + + // Replace key in case the scene changed it + key = newScene.sys.settings.key; + + this.keys[key] = newScene; + + this.scenes.push(newScene); + + // Any data to inject? + if (this._data[key]) + { + newScene.sys.settings.data = this._data[key].data; + + if (this._data[key].autoStart) + { + entry.autoStart = true; + } + } + + if (entry.autoStart || newScene.sys.settings.active) + { + this._start.push(key); + } + } + + // Clear the pending lists + this._pending.length = 0; + + this._data = {}; + + this.isBooted = true; + + // _start might have been populated by the above + for (i = 0; i < this._start.length; i++) + { + entry = this._start[i]; + + this.start(entry); + } + + this._start.length = 0; + }, + + /** + * Process the Scene operations queue. + * + * @method Phaser.Scenes.SceneManager#processQueue + * @since 3.0.0 + */ + processQueue: function () + { + var pendingLength = this._pending.length; + var queueLength = this._queue.length; + + if (pendingLength === 0 && queueLength === 0) + { + return; + } + + var i; + var entry; + + if (pendingLength) + { + for (i = 0; i < pendingLength; i++) + { + entry = this._pending[i]; + + this.add(entry.key, entry.scene, entry.autoStart, entry.data); + } + + // _start might have been populated by this.add + for (i = 0; i < this._start.length; i++) + { + entry = this._start[i]; + + this.start(entry); + } + + // Clear the pending lists + this._start.length = 0; + this._pending.length = 0; + + return; + } + + for (i = 0; i < this._queue.length; i++) + { + entry = this._queue[i]; + + this[entry.op](entry.keyA, entry.keyB); + } + + this._queue.length = 0; + }, + + /** + * Adds a new Scene into the SceneManager. + * You must give each Scene a unique key by which you'll identify it. + * + * The `sceneConfig` can be: + * + * * A `Phaser.Scene` object, or an object that extends it. + * * A plain JavaScript object + * * A JavaScript ES6 Class that extends `Phaser.Scene` + * * A JavaScript ES5 prototype based Class + * * A JavaScript function + * + * If a function is given then a new Scene will be created by calling it. + * + * @method Phaser.Scenes.SceneManager#add + * @since 3.0.0 + * + * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. + * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene + * @param {boolean} [autoStart=false] - If `true` the Scene will be started immediately after being added. + * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. + * + * @return {?Phaser.Scene} The added Scene, if it was added immediately, otherwise `null`. + */ + add: function (key, sceneConfig, autoStart, data) + { + if (autoStart === undefined) { autoStart = false; } + if (data === undefined) { data = {}; } + + // If processing or not booted then put scene into a holding pattern + if (this.isProcessing || !this.isBooted) + { + this._pending.push({ + key: key, + scene: sceneConfig, + autoStart: autoStart, + data: data + }); + + if (!this.isBooted) + { + this._data[key] = { data: data }; + } + + return null; + } + + key = this.getKey(key, sceneConfig); + + var newScene; + + if (sceneConfig instanceof Scene) + { + newScene = this.createSceneFromInstance(key, sceneConfig); + } + else if (typeof sceneConfig === 'object') + { + sceneConfig.key = key; + + newScene = this.createSceneFromObject(key, sceneConfig); + } + else if (typeof sceneConfig === 'function') + { + newScene = this.createSceneFromFunction(key, sceneConfig); + } + + // Any data to inject? + newScene.sys.settings.data = data; + + // Replace key in case the scene changed it + key = newScene.sys.settings.key; + + this.keys[key] = newScene; + + this.scenes.push(newScene); + + if (autoStart || newScene.sys.settings.active) + { + if (this._pending.length) + { + this._start.push(key); + } + else + { + this.start(key); + } + } + + return newScene; + }, + + /** + * Removes a Scene from the SceneManager. + * + * The Scene is removed from the local scenes array, it's key is cleared from the keys + * cache and Scene.Systems.destroy is then called on it. + * + * If the SceneManager is processing the Scenes when this method is called it will + * queue the operation for the next update sequence. + * + * @method Phaser.Scenes.SceneManager#remove + * @since 3.2.0 + * + * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + remove: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'remove', keyA: key, keyB: null }); + } + else + { + var sceneToRemove = this.getScene(key); + + if (!sceneToRemove || sceneToRemove.sys.isTransitioning()) + { + return this; + } + + var index = this.scenes.indexOf(sceneToRemove); + var sceneKey = sceneToRemove.sys.settings.key; + + if (index > -1) + { + delete this.keys[sceneKey]; + this.scenes.splice(index, 1); + + if (this._start.indexOf(sceneKey) > -1) + { + index = this._start.indexOf(sceneKey); + this._start.splice(index, 1); + } + + sceneToRemove.sys.destroy(); + } + } + + return this; + }, + + /** + * Boot the given Scene. + * + * @method Phaser.Scenes.SceneManager#bootScene + * @private + * @fires Phaser.Scenes.Events#TRANSITION_INIT + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to boot. + */ + bootScene: function (scene) + { + var sys = scene.sys; + var settings = sys.settings; + + if (scene.init) + { + scene.init.call(scene, settings.data); + + settings.status = CONST.INIT; + + if (settings.isTransition) + { + sys.events.emit(Events.TRANSITION_INIT, settings.transitionFrom, settings.transitionDuration); + } + } + + var loader; + + if (sys.load) + { + loader = sys.load; + + loader.reset(); + } + + if (loader && scene.preload) + { + scene.preload.call(scene); + + // Is the loader empty? + if (loader.list.size === 0) + { + this.create(scene); + } + else + { + settings.status = CONST.LOADING; + + // Start the loader going as we have something in the queue + loader.once(LoaderEvents.COMPLETE, this.loadComplete, this); + + loader.start(); + } + } + else + { + // No preload? Then there was nothing to load either + this.create(scene); + } + }, + + /** + * Handles load completion for a Scene's Loader. + * + * Starts the Scene that the Loader belongs to. + * + * @method Phaser.Scenes.SceneManager#loadComplete + * @private + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading. + */ + loadComplete: function (loader) + { + var scene = loader.scene; + + // TODO - Remove. This should *not* be handled here + // Try to unlock HTML5 sounds every time any loader completes + if (this.game.sound && this.game.sound.onBlurPausedSounds) + { + this.game.sound.unlock(); + } + + this.create(scene); + }, + + /** + * Handle payload completion for a Scene. + * + * @method Phaser.Scenes.SceneManager#payloadComplete + * @private + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading its Scene's payload. + */ + payloadComplete: function (loader) + { + this.bootScene(loader.scene); + }, + + /** + * Updates the Scenes. + * + * @method Phaser.Scenes.SceneManager#update + * @since 3.0.0 + * + * @param {number} time - Time elapsed. + * @param {number} delta - Delta time from the last update. + */ + update: function (time, delta) + { + this.processQueue(); + + this.isProcessing = true; + + // Loop through the active scenes in reverse order + for (var i = this.scenes.length - 1; i >= 0; i--) + { + var sys = this.scenes[i].sys; + + if (sys.settings.status > CONST.START && sys.settings.status <= CONST.RUNNING) + { + sys.step(time, delta); + } + } + }, + + /** + * Renders the Scenes. + * + * @method Phaser.Scenes.SceneManager#render + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer to use. + */ + render: function (renderer) + { + // Loop through the scenes in forward order + for (var i = 0; i < this.scenes.length; i++) + { + var sys = this.scenes[i].sys; + + if (sys.settings.visible && sys.settings.status >= CONST.LOADING && sys.settings.status < CONST.SLEEPING) + { + sys.render(renderer); + } + } + + this.isProcessing = false; + }, + + /** + * Calls the given Scene's {@link Phaser.Scene#create} method and updates its status. + * + * @method Phaser.Scenes.SceneManager#create + * @private + * @fires Phaser.Scenes.Events#CREATE + * @fires Phaser.Scenes.Events#TRANSITION_INIT + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to create. + */ + create: function (scene) + { + var sys = scene.sys; + var settings = sys.settings; + + if (scene.create) + { + settings.status = CONST.CREATING; + + scene.create.call(scene, settings.data); + + if (settings.status === CONST.DESTROYED) + { + return; + } + } + + if (settings.isTransition) + { + sys.events.emit(Events.TRANSITION_START, settings.transitionFrom, settings.transitionDuration); + } + + // If the Scene has an update function we'll set it now, otherwise it'll remain as NOOP + if (scene.update) + { + sys.sceneUpdate = scene.update; + } + + settings.status = CONST.RUNNING; + + sys.events.emit(Events.CREATE, scene); + }, + + /** + * Creates and initializes a Scene from a function. + * + * @method Phaser.Scenes.SceneManager#createSceneFromFunction + * @private + * @since 3.0.0 + * + * @param {string} key - The key of the Scene. + * @param {function} scene - The function to create the Scene from. + * + * @return {Phaser.Scene} The created Scene. + */ + createSceneFromFunction: function (key, scene) + { + var newScene = new scene(); + + if (newScene instanceof Scene) + { + var configKey = newScene.sys.settings.key; + + if (configKey !== '') + { + key = configKey; + } + + if (this.keys.hasOwnProperty(key)) + { + throw new Error('Cannot add a Scene with duplicate key: ' + key); + } + + return this.createSceneFromInstance(key, newScene); + } + else + { + newScene.sys = new Systems(newScene); + + newScene.sys.settings.key = key; + + newScene.sys.init(this.game); + + return newScene; + } + }, + + /** + * Creates and initializes a Scene instance. + * + * @method Phaser.Scenes.SceneManager#createSceneFromInstance + * @private + * @since 3.0.0 + * + * @param {string} key - The key of the Scene. + * @param {Phaser.Scene} newScene - The Scene instance. + * + * @return {Phaser.Scene} The created Scene. + */ + createSceneFromInstance: function (key, newScene) + { + var configKey = newScene.sys.settings.key; + + if (configKey !== '') + { + key = configKey; + } + else + { + newScene.sys.settings.key = key; + } + + newScene.sys.init(this.game); + + return newScene; + }, + + /** + * Creates and initializes a Scene from an Object definition. + * + * @method Phaser.Scenes.SceneManager#createSceneFromObject + * @private + * @since 3.0.0 + * + * @param {string} key - The key of the Scene. + * @param {(string|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig)} sceneConfig - The Scene config. + * + * @return {Phaser.Scene} The created Scene. + */ + createSceneFromObject: function (key, sceneConfig) + { + var newScene = new Scene(sceneConfig); + + var configKey = newScene.sys.settings.key; + + if (configKey !== '') + { + key = configKey; + } + else + { + newScene.sys.settings.key = key; + } + + newScene.sys.init(this.game); + + // Extract callbacks + + var defaults = [ 'init', 'preload', 'create', 'update', 'render' ]; + + for (var i = 0; i < defaults.length; i++) + { + var sceneCallback = GetValue(sceneConfig, defaults[i], null); + + if (sceneCallback) + { + newScene[defaults[i]] = sceneCallback; + } + } + + // Now let's move across any other functions or properties that may exist in the extend object: + + /* + scene: { + preload: preload, + create: create, + extend: { + hello: 1, + test: 'atari', + addImage: addImage + } + } + */ + + if (sceneConfig.hasOwnProperty('extend')) + { + for (var propertyKey in sceneConfig.extend) + { + if (!sceneConfig.extend.hasOwnProperty(propertyKey)) + { + continue; + } + + var value = sceneConfig.extend[propertyKey]; + + if (propertyKey === 'data' && newScene.hasOwnProperty('data') && typeof value === 'object') + { + // Populate the DataManager + newScene.data.merge(value); + } + else if (propertyKey !== 'sys') + { + newScene[propertyKey] = value; + } + } + } + + return newScene; + }, + + /** + * Retrieves the key of a Scene from a Scene config. + * + * @method Phaser.Scenes.SceneManager#getKey + * @private + * @since 3.0.0 + * + * @param {string} key - The key to check in the Scene config. + * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|function)} sceneConfig - The Scene config. + * + * @return {string} The Scene key. + */ + getKey: function (key, sceneConfig) + { + if (!key) { key = 'default'; } + + if (typeof sceneConfig === 'function') + { + return key; + } + else if (sceneConfig instanceof Scene) + { + key = sceneConfig.sys.settings.key; + } + else if (typeof sceneConfig === 'object' && sceneConfig.hasOwnProperty('key')) + { + key = sceneConfig.key; + } + + // By this point it's either 'default' or extracted from the Scene + + if (this.keys.hasOwnProperty(key)) + { + throw new Error('Cannot add a Scene with duplicate key: ' + key); + } + else + { + return key; + } + }, + + /** + * Returns an array of all the current Scenes being managed by this Scene Manager. + * + * You can filter the output by the active state of the Scene and choose to have + * the array returned in normal or reversed order. + * + * @method Phaser.Scenes.SceneManager#getScenes + * @since 3.16.0 + * + * @param {boolean} [isActive=true] - Only include Scene's that are currently active? + * @param {boolean} [inReverse=false] - Return the array of Scenes in reverse? + * + * @return {Phaser.Scene[]} An array containing all of the Scenes in the Scene Manager. + */ + getScenes: function (isActive, inReverse) + { + if (isActive === undefined) { isActive = true; } + if (inReverse === undefined) { inReverse = false; } + + var out = []; + var scenes = this.scenes; + + for (var i = 0; i < scenes.length; i++) + { + var scene = scenes[i]; + + if (scene && (!isActive || (isActive && scene.sys.isActive()))) + { + out.push(scene); + } + } + + return (inReverse) ? out.reverse() : out; + }, + + /** + * Retrieves a Scene. + * + * @method Phaser.Scenes.SceneManager#getScene + * @since 3.0.0 + * + * @param {string|Phaser.Scene} key - The Scene to retrieve. + * + * @return {?Phaser.Scene} The Scene. + */ + getScene: function (key) + { + if (typeof key === 'string') + { + if (this.keys[key]) + { + return this.keys[key]; + } + } + else + { + for (var i = 0; i < this.scenes.length; i++) + { + if (key === this.scenes[i]) + { + return key; + } + } + } + + return null; + }, + + /** + * Determines whether a Scene is running. + * + * @method Phaser.Scenes.SceneManager#isActive + * @since 3.0.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is running. + */ + isActive: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isActive(); + } + + return null; + }, + + /** + * Determines whether a Scene is paused. + * + * @method Phaser.Scenes.SceneManager#isPaused + * @since 3.17.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is paused. + */ + isPaused: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isPaused(); + } + + return null; + }, + + /** + * Determines whether a Scene is visible. + * + * @method Phaser.Scenes.SceneManager#isVisible + * @since 3.0.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is visible. + */ + isVisible: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isVisible(); + } + + return null; + }, + + /** + * Determines whether a Scene is sleeping. + * + * @method Phaser.Scenes.SceneManager#isSleeping + * @since 3.0.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is sleeping. + */ + isSleeping: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isSleeping(); + } + + return null; + }, + + /** + * Pauses the given Scene. + * + * @method Phaser.Scenes.SceneManager#pause + * @since 3.0.0 + * + * @param {string} key - The Scene to pause. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its pause event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + pause: function (key, data) + { + var scene = this.getScene(key); + + if (scene) + { + scene.sys.pause(data); + } + + return this; + }, + + /** + * Resumes the given Scene. + * + * @method Phaser.Scenes.SceneManager#resume + * @since 3.0.0 + * + * @param {string} key - The Scene to resume. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its resume event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + resume: function (key, data) + { + var scene = this.getScene(key); + + if (scene) + { + scene.sys.resume(data); + } + + return this; + }, + + /** + * Puts the given Scene to sleep. + * + * @method Phaser.Scenes.SceneManager#sleep + * @since 3.0.0 + * + * @param {string} key - The Scene to put to sleep. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its sleep event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + sleep: function (key, data) + { + var scene = this.getScene(key); + + if (scene && !scene.sys.isTransitioning()) + { + scene.sys.sleep(data); + } + + return this; + }, + + /** + * Awakens the given Scene. + * + * @method Phaser.Scenes.SceneManager#wake + * @since 3.0.0 + * + * @param {string} key - The Scene to wake up. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its wake event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + wake: function (key, data) + { + var scene = this.getScene(key); + + if (scene) + { + scene.sys.wake(data); + } + + return this; + }, + + /** + * Runs the given Scene. + * + * If the given Scene is paused, it will resume it. If sleeping, it will wake it. + * If not running at all, it will be started. + * + * Use this if you wish to open a modal Scene by calling `pause` on the current + * Scene, then `run` on the modal Scene. + * + * @method Phaser.Scenes.SceneManager#run + * @since 3.10.0 + * + * @param {string} key - The Scene to run. + * @param {object} [data] - A data object that will be passed to the Scene on start, wake, or resume. + * + * @return {Phaser.Scenes.SceneManager} This Scene Manager. + */ + run: function (key, data) + { + var scene = this.getScene(key); + + if (!scene) + { + for (var i = 0; i < this._pending.length; i++) + { + if (this._pending[i].key === key) + { + this.queueOp('start', key, data); + break; + } + } + return this; + } + + if (scene.sys.isSleeping()) + { + // Sleeping? + scene.sys.wake(data); + } + else if (scene.sys.isPaused()) + { + // Paused? + scene.sys.resume(data); + } + else + { + // Not actually running? + this.start(key, data); + } + }, + + /** + * Starts the given Scene. + * + * @method Phaser.Scenes.SceneManager#start + * @since 3.0.0 + * + * @param {string} key - The Scene to start. + * @param {object} [data] - Optional data object to pass to Scene.Settings and Scene.init. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + start: function (key, data) + { + // If the Scene Manager is not running, then put the Scene into a holding pattern + if (!this.isBooted) + { + this._data[key] = { + autoStart: true, + data: data + }; + + return this; + } + + var scene = this.getScene(key); + + if (scene) + { + // If the Scene is already running (perhaps they called start from a launched sub-Scene?) + // then we close it down before starting it again. + if (scene.sys.isActive() || scene.sys.isPaused()) + { + scene.sys.shutdown(); + + scene.sys.start(data); + } + else + { + scene.sys.start(data); + + var loader; + + if (scene.sys.load) + { + loader = scene.sys.load; + } + + // Files payload? + if (loader && scene.sys.settings.hasOwnProperty('pack')) + { + loader.reset(); + + if (loader.addPack({ payload: scene.sys.settings.pack })) + { + scene.sys.settings.status = CONST.LOADING; + + loader.once(LoaderEvents.COMPLETE, this.payloadComplete, this); + + loader.start(); + + return this; + } + } + } + + this.bootScene(scene); + } + + return this; + }, + + /** + * Stops the given Scene. + * + * @method Phaser.Scenes.SceneManager#stop + * @since 3.0.0 + * + * @param {string} key - The Scene to stop. + * @param {object} [data] - Optional data object to pass to Scene.shutdown. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + stop: function (key, data) + { + var scene = this.getScene(key); + + if (scene && !scene.sys.isTransitioning()) + { + scene.sys.shutdown(data); + } + + return this; + }, + + /** + * Sleeps one one Scene and starts the other. + * + * @method Phaser.Scenes.SceneManager#switch + * @since 3.0.0 + * + * @param {string} from - The Scene to sleep. + * @param {string} to - The Scene to start. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + switch: function (from, to) + { + var sceneA = this.getScene(from); + var sceneB = this.getScene(to); + + if (sceneA && sceneB && sceneA !== sceneB) + { + this.sleep(from); + + if (this.isSleeping(to)) + { + this.wake(to); + } + else + { + this.start(to); + } + } + + return this; + }, + + /** + * Retrieves a Scene by numeric index. + * + * @method Phaser.Scenes.SceneManager#getAt + * @since 3.0.0 + * + * @param {integer} index - The index of the Scene to retrieve. + * + * @return {(Phaser.Scene|undefined)} The Scene. + */ + getAt: function (index) + { + return this.scenes[index]; + }, + + /** + * Retrieves the numeric index of a Scene. + * + * @method Phaser.Scenes.SceneManager#getIndex + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The key of the Scene. + * + * @return {integer} The index of the Scene. + */ + getIndex: function (key) + { + var scene = this.getScene(key); + + return this.scenes.indexOf(scene); + }, + + /** + * Brings a Scene to the top of the Scenes list. + * + * This means it will render above all other Scenes. + * + * @method Phaser.Scenes.SceneManager#bringToTop + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + bringToTop: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'bringToTop', keyA: key, keyB: null }); + } + else + { + var index = this.getIndex(key); + + if (index !== -1 && index < this.scenes.length) + { + var scene = this.getScene(key); + + this.scenes.splice(index, 1); + this.scenes.push(scene); + } + } + + return this; + }, + + /** + * Sends a Scene to the back of the Scenes list. + * + * This means it will render below all other Scenes. + * + * @method Phaser.Scenes.SceneManager#sendToBack + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + sendToBack: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'sendToBack', keyA: key, keyB: null }); + } + else + { + var index = this.getIndex(key); + + if (index !== -1 && index > 0) + { + var scene = this.getScene(key); + + this.scenes.splice(index, 1); + this.scenes.unshift(scene); + } + } + + return this; + }, + + /** + * Moves a Scene down one position in the Scenes list. + * + * @method Phaser.Scenes.SceneManager#moveDown + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveDown: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'moveDown', keyA: key, keyB: null }); + } + else + { + var indexA = this.getIndex(key); + + if (indexA > 0) + { + var indexB = indexA - 1; + var sceneA = this.getScene(key); + var sceneB = this.getAt(indexB); + + this.scenes[indexA] = sceneB; + this.scenes[indexB] = sceneA; + } + } + + return this; + }, + + /** + * Moves a Scene up one position in the Scenes list. + * + * @method Phaser.Scenes.SceneManager#moveUp + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveUp: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'moveUp', keyA: key, keyB: null }); + } + else + { + var indexA = this.getIndex(key); + + if (indexA < this.scenes.length - 1) + { + var indexB = indexA + 1; + var sceneA = this.getScene(key); + var sceneB = this.getAt(indexB); + + this.scenes[indexA] = sceneB; + this.scenes[indexB] = sceneA; + } + } + + return this; + }, + + /** + * Moves a Scene so it is immediately above another Scene in the Scenes list. + * + * This means it will render over the top of the other Scene. + * + * @method Phaser.Scenes.SceneManager#moveAbove + * @since 3.2.0 + * + * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. + * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveAbove: function (keyA, keyB) + { + if (keyA === keyB) + { + return this; + } + + if (this.isProcessing) + { + this._queue.push({ op: 'moveAbove', keyA: keyA, keyB: keyB }); + } + else + { + var indexA = this.getIndex(keyA); + var indexB = this.getIndex(keyB); + + if (indexA !== -1 && indexB !== -1) + { + var tempScene = this.getAt(indexB); + + // Remove + this.scenes.splice(indexB, 1); + + // Add in new location + this.scenes.splice(indexA + 1, 0, tempScene); + } + } + + return this; + }, + + /** + * Moves a Scene so it is immediately below another Scene in the Scenes list. + * + * This means it will render behind the other Scene. + * + * @method Phaser.Scenes.SceneManager#moveBelow + * @since 3.2.0 + * + * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. + * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveBelow: function (keyA, keyB) + { + if (keyA === keyB) + { + return this; + } + + if (this.isProcessing) + { + this._queue.push({ op: 'moveBelow', keyA: keyA, keyB: keyB }); + } + else + { + var indexA = this.getIndex(keyA); + var indexB = this.getIndex(keyB); + + if (indexA !== -1 && indexB !== -1) + { + var tempScene = this.getAt(indexB); + + // Remove + this.scenes.splice(indexB, 1); + + if (indexA === 0) + { + this.scenes.unshift(tempScene); + } + else + { + // Add in new location + this.scenes.splice(indexA, 0, tempScene); + } + } + } + + return this; + }, + + /** + * Queue a Scene operation for the next update. + * + * @method Phaser.Scenes.SceneManager#queueOp + * @private + * @since 3.0.0 + * + * @param {string} op - The operation to perform. + * @param {(string|Phaser.Scene)} keyA - Scene A. + * @param {(any|string|Phaser.Scene)} [keyB] - Scene B, or a data object. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + queueOp: function (op, keyA, keyB) + { + this._queue.push({ op: op, keyA: keyA, keyB: keyB }); + + return this; + }, + + /** + * Swaps the positions of two Scenes in the Scenes list. + * + * @method Phaser.Scenes.SceneManager#swapPosition + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} keyA - The first Scene to swap. + * @param {(string|Phaser.Scene)} keyB - The second Scene to swap. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + swapPosition: function (keyA, keyB) + { + if (keyA === keyB) + { + return this; + } + + if (this.isProcessing) + { + this._queue.push({ op: 'swapPosition', keyA: keyA, keyB: keyB }); + } + else + { + var indexA = this.getIndex(keyA); + var indexB = this.getIndex(keyB); + + if (indexA !== indexB && indexA !== -1 && indexB !== -1) + { + var tempScene = this.getAt(indexA); + + this.scenes[indexA] = this.scenes[indexB]; + this.scenes[indexB] = tempScene; + } + } + + return this; + }, + + /** + * Dumps debug information about each Scene to the developer console. + * + * @method Phaser.Scenes.SceneManager#dump + * @since 3.2.0 + */ + dump: function () + { + var out = []; + var map = [ 'pending', 'init', 'start', 'loading', 'creating', 'running', 'paused', 'sleeping', 'shutdown', 'destroyed' ]; + + for (var i = 0; i < this.scenes.length; i++) + { + var sys = this.scenes[i].sys; + + var key = (sys.settings.visible && (sys.settings.status === CONST.RUNNING || sys.settings.status === CONST.PAUSED)) ? '[*] ' : '[-] '; + key += sys.settings.key + ' (' + map[sys.settings.status] + ')'; + + out.push(key); + } + + console.log(out.join('\n')); + }, + + /** + * Destroy the SceneManager and all of its Scene's systems. + * + * @method Phaser.Scenes.SceneManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + for (var i = 0; i < this.scenes.length; i++) + { + var sys = this.scenes[i].sys; + + sys.destroy(); + } + + this.update = NOOP; + + this.scenes = []; + + this._pending = []; + this._start = []; + this._queue = []; + + this.game = null; + } + +}); + +module.exports = SceneManager; + + +/***/ }), +/* 398 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Systems = __webpack_require__(193); + +/** + * @classdesc + * A base Phaser.Scene class which can be extended for your own use. + * + * You can also define the optional methods {@link Phaser.Types.Scenes.SceneInitCallback init()}, {@link Phaser.Types.Scenes.ScenePreloadCallback preload()}, and {@link Phaser.Types.Scenes.SceneCreateCallback create()}. + * + * @class Scene + * @memberof Phaser + * @constructor + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - Scene specific configuration settings. + */ +var Scene = new Class({ + + initialize: + + function Scene (config) + { + /** + * The Scene Systems. You must never overwrite this property, or all hell will break lose. + * + * @name Phaser.Scene#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = new Systems(this, config); + + /** + * A reference to the Phaser.Game instance. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game; + + /** + * A reference to the global Animation Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#anims + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.anims; + + /** + * A reference to the global Cache. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#cache + * @type {Phaser.Cache.CacheManager} + * @since 3.0.0 + */ + this.cache; + + /** + * A reference to the game level Data Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#registry + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.registry; + + /** + * A reference to the Sound Manager. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#sound + * @type {Phaser.Sound.BaseSoundManager} + * @since 3.0.0 + */ + this.sound; + + /** + * A reference to the Texture Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#textures + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.textures; + + /** + * A scene level Event Emitter. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events; + + /** + * A scene level Camera System. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#cameras + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.0.0 + */ + this.cameras; + + /** + * A scene level Game Object Factory. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#add + * @type {Phaser.GameObjects.GameObjectFactory} + * @since 3.0.0 + */ + this.add; + + /** + * A scene level Game Object Creator. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#make + * @type {Phaser.GameObjects.GameObjectCreator} + * @since 3.0.0 + */ + this.make; + + /** + * A reference to the Scene Manager Plugin. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#scene + * @type {Phaser.Scenes.ScenePlugin} + * @since 3.0.0 + */ + this.scene; + + /** + * A scene level Game Object Display List. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#children + * @type {Phaser.GameObjects.DisplayList} + * @since 3.0.0 + */ + this.children; + + /** + * A scene level Lights Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#lights + * @type {Phaser.GameObjects.LightsManager} + * @since 3.0.0 + */ + this.lights; + + /** + * A scene level Data Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#data + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.data; + + /** + * A scene level Input Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#input + * @type {Phaser.Input.InputPlugin} + * @since 3.0.0 + */ + this.input; + + /** + * A scene level Loader Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#load + * @type {Phaser.Loader.LoaderPlugin} + * @since 3.0.0 + */ + this.load; + + /** + * A scene level Time and Clock Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#time + * @type {Phaser.Time.Clock} + * @since 3.0.0 + */ + this.time; + + /** + * A scene level Tween Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#tweens + * @type {Phaser.Tweens.TweenManager} + * @since 3.0.0 + */ + this.tweens; + + /** + * A scene level Arcade Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#physics + * @type {Phaser.Physics.Arcade.ArcadePhysics} + * @since 3.0.0 + */ + this.physics; + + /** + * A scene level Impact Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#impact + * @type {Phaser.Physics.Impact.ImpactPhysics} + * @since 3.0.0 + */ + this.impact; + + /** + * A scene level Matter Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#matter + * @type {Phaser.Physics.Matter.MatterPhysics} + * @since 3.0.0 + */ + this.matter; + + if (true) + { + /** + * A scene level Facebook Instant Games Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#facebook + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.12.0 + */ + this.facebook; + } + + /** + * A reference to the global Scale Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#scale + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.2 + */ + this.scale; + + /** + * A reference to the Plugin Manager. + * + * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install + * those plugins into Scenes as required. + * + * @name Phaser.Scene#plugins + * @type {Phaser.Plugins.PluginManager} + * @since 3.0.0 + */ + this.plugins; + }, + + /** + * Should be overridden by your own Scenes. + * This method is called once per game step while the scene is running. + * + * @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. + */ + update: function () + { + } + +}); + +module.exports = Scene; + + +/***/ }), +/* 399 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(132); +var GetValue = __webpack_require__(5); +var Merge = __webpack_require__(88); +var InjectionMap = __webpack_require__(905); + +/** + * @namespace Phaser.Scenes.Settings + */ + +var Settings = { + + /** + * Takes a Scene configuration object and returns a fully formed System Settings object. + * + * @function Phaser.Scenes.Settings.create + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - The Scene configuration object used to create this Scene Settings. + * + * @return {Phaser.Types.Scenes.SettingsObject} The Scene Settings object created as a result of the config and default settings. + */ + create: function (config) + { + if (typeof config === 'string') + { + config = { key: config }; + } + else if (config === undefined) + { + // Pass the 'hasOwnProperty' checks + config = {}; + } + + return { + + status: CONST.PENDING, + + key: GetValue(config, 'key', ''), + active: GetValue(config, 'active', false), + visible: GetValue(config, 'visible', true), + + isBooted: false, + + isTransition: false, + transitionFrom: null, + transitionDuration: 0, + transitionAllowInput: true, + + // Loader payload array + + data: {}, + + pack: GetValue(config, 'pack', false), + + // Cameras + + cameras: GetValue(config, 'cameras', null), + + // Scene Property Injection Map + + map: GetValue(config, 'map', Merge(InjectionMap, GetValue(config, 'mapAdd', {}))), + + // Physics + + physics: GetValue(config, 'physics', {}), + + // Loader + + loader: GetValue(config, 'loader', {}), + + // Plugins + + plugins: GetValue(config, 'plugins', false), + + // Input + + input: GetValue(config, 'input', {}) + + }; + } + +}; + +module.exports = Settings; + + +/***/ }), +/* 400 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); +var CanvasTexture = __webpack_require__(401); +var Class = __webpack_require__(0); +var Color = __webpack_require__(36); +var CONST = __webpack_require__(32); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(128); +var GameEvents = __webpack_require__(21); +var GenerateTexture = __webpack_require__(370); +var GetValue = __webpack_require__(5); +var Parser = __webpack_require__(403); +var Texture = __webpack_require__(195); + +/** + * @callback EachTextureCallback + * + * @param {Phaser.Textures.Texture} texture - Each texture in Texture Manager. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + +/** + * @classdesc + * Textures are managed by the global TextureManager. This is a singleton class that is + * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. + * + * Sprites and other Game Objects get the texture data they need from the TextureManager. + * + * Access it via `scene.textures`. + * + * @class TextureManager + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance this Texture Manager belongs to. + */ +var TextureManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function TextureManager (game) + { + EventEmitter.call(this); + + /** + * The Game that this TextureManager belongs to. + * + * @name Phaser.Textures.TextureManager#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * The name of this manager. + * + * @name Phaser.Textures.TextureManager#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'TextureManager'; + + /** + * An object that has all of textures that Texture Manager creates. + * Textures are assigned to keys so we can access to any texture that this object has directly by key value without iteration. + * + * @name Phaser.Textures.TextureManager#list + * @type {object} + * @default {} + * @since 3.0.0 + */ + this.list = {}; + + /** + * The temporary canvas element to save an pixel data of an arbitrary texture in getPixel() and getPixelAlpha() method. + * + * @name Phaser.Textures.TextureManager#_tempCanvas + * @type {HTMLCanvasElement} + * @private + * @since 3.0.0 + */ + this._tempCanvas = CanvasPool.create2D(this, 1, 1); + + /** + * The context of the temporary canvas element made to save an pixel data in getPixel() and getPixelAlpha() method. + * + * @name Phaser.Textures.TextureManager#_tempContext + * @type {CanvasRenderingContext2D} + * @private + * @since 3.0.0 + */ + this._tempContext = this._tempCanvas.getContext('2d'); + + /** + * An counting value used for emitting 'ready' event after all of managers in game is loaded. + * + * @name Phaser.Textures.TextureManager#_pending + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._pending = 0; + + game.events.once(GameEvents.BOOT, this.boot, this); + }, + + /** + * The Boot Handler called by Phaser.Game when it first starts up. + * + * @method Phaser.Textures.TextureManager#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + this._pending = 2; + + this.on(Events.LOAD, this.updatePending, this); + this.on(Events.ERROR, this.updatePending, this); + + this.addBase64('__DEFAULT', this.game.config.defaultImage); + this.addBase64('__MISSING', this.game.config.missingImage); + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * After 'onload' or 'onerror' invoked twice, emit 'ready' event. + * + * @method Phaser.Textures.TextureManager#updatePending + * @private + * @since 3.0.0 + */ + updatePending: function () + { + this._pending--; + + if (this._pending === 0) + { + this.off(Events.LOAD); + this.off(Events.ERROR); + + this.emit(Events.READY); + } + }, + + /** + * Checks the given texture key and throws a console.warn if the key is already in use, then returns false. + * If you wish to avoid the console.warn then use `TextureManager.exists` instead. + * + * @method Phaser.Textures.TextureManager#checkKey + * @since 3.7.0 + * + * @param {string} key - The texture key to check. + * + * @return {boolean} `true` if it's safe to use the texture key, otherwise `false`. + */ + checkKey: function (key) + { + if (this.exists(key)) + { + // eslint-disable-next-line no-console + console.error('Texture key already in use: ' + key); + + return false; + } + + return true; + }, + + /** + * Removes a Texture from the Texture Manager and destroys it. This will immediately + * clear all references to it from the Texture Manager, and if it has one, destroy its + * WebGLTexture. This will emit a `removetexture` event. + * + * Note: If you have any Game Objects still using this texture they will start throwing + * errors the next time they try to render. Make sure that removing the texture is the final + * step when clearing down to avoid this. + * + * @method Phaser.Textures.TextureManager#remove + * @fires Phaser.Textures.Events#REMOVE + * @since 3.7.0 + * + * @param {(string|Phaser.Textures.Texture)} key - The key of the Texture to remove, or a reference to it. + * + * @return {Phaser.Textures.TextureManager} The Texture Manager. + */ + remove: function (key) + { + if (typeof key === 'string') + { + if (this.exists(key)) + { + key = this.get(key); + } + else + { + console.warn('No texture found matching key: ' + key); + return this; + } + } + + // By this point key should be a Texture, if not, the following fails anyway + if (this.list.hasOwnProperty(key.key)) + { + key.destroy(); + + this.emit(Events.REMOVE, key.key); + } + + return this; + }, + + /** + * Removes a key from the Texture Manager but does not destroy the Texture that was using the key. + * + * @method Phaser.Textures.TextureManager#removeKey + * @since 3.17.0 + * + * @param {string} key - The key to remove from the texture list. + * + * @return {Phaser.Textures.TextureManager} The Texture Manager. + */ + removeKey: function (key) + { + if (this.list.hasOwnProperty(key)) + { + delete this.list[key]; + } + + return this; + }, + + /** + * Adds a new Texture to the Texture Manager created from the given Base64 encoded data. + * + * @method Phaser.Textures.TextureManager#addBase64 + * @fires Phaser.Textures.Events#ADD + * @fires Phaser.Textures.Events#ERROR + * @fires Phaser.Textures.Events#LOAD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {*} data - The Base64 encoded data. + * + * @return {this} This Texture Manager instance. + */ + addBase64: function (key, data) + { + if (this.checkKey(key)) + { + var _this = this; + + var image = new Image(); + + image.onerror = function () + { + _this.emit(Events.ERROR, key); + }; + + image.onload = function () + { + var texture = _this.create(key, image); + + Parser.Image(texture, 0); + + _this.emit(Events.ADD, key, texture); + + _this.emit(Events.LOAD, key, texture); + }; + + image.src = data; + } + + return this; + }, + + /** + * Gets an existing texture frame and converts it into a base64 encoded image and returns the base64 data. + * + * You can also provide the image type and encoder options. + * + * This will only work with bitmap based texture frames, such as those created from Texture Atlases. + * It will not work with GL Texture objects, such as Shaders, or Render Textures. For those please + * see the WebGL Snapshot function instead. + * + * @method Phaser.Textures.TextureManager#getBase64 + * @since 3.12.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. + * @param {string} [type='image/png'] - [description] + * @param {number} [encoderOptions=0.92] - [description] + * + * @return {string} The base64 encoded data, or an empty string if the texture frame could not be found. + */ + getBase64: function (key, frame, type, encoderOptions) + { + if (type === undefined) { type = 'image/png'; } + if (encoderOptions === undefined) { encoderOptions = 0.92; } + + var data = ''; + + var textureFrame = this.getFrame(key, frame); + + if (textureFrame && (textureFrame.source.isRenderTexture || textureFrame.source.isGLTexture)) + { + console.warn('Cannot getBase64 from WebGL Texture'); + } + else if (textureFrame) + { + var cd = textureFrame.canvasData; + + var canvas = CanvasPool.create2D(this, cd.width, cd.height); + var ctx = canvas.getContext('2d'); + + ctx.drawImage( + textureFrame.source.image, + cd.x, + cd.y, + cd.width, + cd.height, + 0, + 0, + cd.width, + cd.height + ); + + data = canvas.toDataURL(type, encoderOptions); + + CanvasPool.remove(canvas); + } + + return data; + }, + + /** + * Adds a new Texture to the Texture Manager created from the given Image element. + * + * @method Phaser.Textures.TextureManager#addImage + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {HTMLImageElement|HTMLCanvasElement} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addImage: function (key, source, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + Parser.Image(texture, 0); + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Takes a WebGL Texture and creates a Phaser Texture from it, which is added to the Texture Manager using the given key. + * + * This allows you to then use the Texture as a normal texture for texture based Game Objects like Sprites. + * + * This is a WebGL only feature. + * + * @method Phaser.Textures.TextureManager#addGLTexture + * @fires Phaser.Textures.Events#ADD + * @since 3.19.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {WebGLTexture} glTexture - The source Render Texture. + * @param {number} width - The new width of the Texture. + * @param {number} height - The new height of the Texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addGLTexture: function (key, glTexture, width, height) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, glTexture, width, height); + + texture.add('__BASE', 0, 0, 0, width, height); + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Render Texture to the Texture Manager using the given key. + * This allows you to then use the Render Texture as a normal texture for texture based Game Objects like Sprites. + * + * @method Phaser.Textures.TextureManager#addRenderTexture + * @fires Phaser.Textures.Events#ADD + * @since 3.12.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {Phaser.GameObjects.RenderTexture} renderTexture - The source Render Texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addRenderTexture: function (key, renderTexture) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, renderTexture); + + texture.add('__BASE', 0, 0, 0, renderTexture.width, renderTexture.height); + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Creates a new Texture using the given config values. + * Generated textures consist of a Canvas element to which the texture data is drawn. + * See the Phaser.Create function for the more direct way to create textures. + * + * @method Phaser.Textures.TextureManager#generate + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {object} config - The configuration object needed to generate the texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + generate: function (key, config) + { + if (this.checkKey(key)) + { + var canvas = CanvasPool.create(this, 1, 1); + + config.canvas = canvas; + + GenerateTexture(config); + + return this.addCanvas(key, canvas); + } + else + { + return null; + } + }, + + /** + * Creates a new Texture using a blank Canvas element of the size given. + * + * Canvas elements are automatically pooled and calling this method will + * extract a free canvas from the CanvasPool, or create one if none are available. + * + * @method Phaser.Textures.TextureManager#createCanvas + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {integer} [width=256] - The width of the Canvas element. + * @param {integer} [height=256] - The height of the Canvas element. + * + * @return {?Phaser.Textures.CanvasTexture} The Canvas Texture that was created, or `null` if the key is already in use. + */ + createCanvas: function (key, width, height) + { + if (width === undefined) { width = 256; } + if (height === undefined) { height = 256; } + + if (this.checkKey(key)) + { + var canvas = CanvasPool.create(this, width, height, CONST.CANVAS, true); + + return this.addCanvas(key, canvas); + } + + return null; + }, + + /** + * Creates a new Canvas Texture object from an existing Canvas element + * and adds it to this Texture Manager, unless `skipCache` is true. + * + * @method Phaser.Textures.TextureManager#addCanvas + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLCanvasElement} source - The Canvas element to form the base of the new Texture. + * @param {boolean} [skipCache=false] - Skip adding this Texture into the Cache? + * + * @return {?Phaser.Textures.CanvasTexture} The Canvas Texture that was created, or `null` if the key is already in use. + */ + addCanvas: function (key, source, skipCache) + { + if (skipCache === undefined) { skipCache = false; } + + var texture = null; + + if (skipCache) + { + texture = new CanvasTexture(this, key, source, source.width, source.height); + } + else if (this.checkKey(key)) + { + texture = new CanvasTexture(this, key, source, source.width, source.height); + + this.list[key] = texture; + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a new Texture Atlas to this Texture Manager. + * It can accept either JSON Array or JSON Hash formats, as exported by Texture Packer and similar software. + * + * @method Phaser.Textures.TextureManager#addAtlas + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlas: function (key, source, data, dataSource) + { + // New Texture Packer format? + if (Array.isArray(data.textures) || Array.isArray(data.frames)) + { + return this.addAtlasJSONArray(key, source, data, dataSource); + } + else + { + return this.addAtlasJSONHash(key, source, data, dataSource); + } + }, + + /** + * Adds a Texture Atlas to this Texture Manager. + * The frame data of the atlas must be stored in an Array within the JSON. + * This is known as a JSON Array in software such as Texture Packer. + * + * @method Phaser.Textures.TextureManager#addAtlasJSONArray + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(HTMLImageElement|HTMLImageElement[])} source - The source Image element/s. + * @param {(object|object[])} data - The Texture Atlas data/s. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlasJSONArray: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + // Multi-Atlas? + if (Array.isArray(data)) + { + var singleAtlasFile = (data.length === 1); // multi-pack with one atlas file for all images + + // !! Assumes the textures are in the same order in the source array as in the json data !! + for (var i = 0; i < texture.source.length; i++) + { + var atlasData = singleAtlasFile ? data[0] : data[i]; + + Parser.JSONArray(texture, i, atlasData); + } + } + else + { + Parser.JSONArray(texture, 0, data); + } + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Texture Atlas to this Texture Manager. + * The frame data of the atlas must be stored in an Object within the JSON. + * This is known as a JSON Hash in software such as Texture Packer. + * + * @method Phaser.Textures.TextureManager#addAtlasJSONHash + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlasJSONHash: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + if (Array.isArray(data)) + { + for (var i = 0; i < data.length; i++) + { + Parser.JSONHash(texture, i, data[i]); + } + } + else + { + Parser.JSONHash(texture, 0, data); + } + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Texture Atlas to this Texture Manager, where the atlas data is given + * in the XML format. + * + * @method Phaser.Textures.TextureManager#addAtlasXML + * @fires Phaser.Textures.Events#ADD + * @since 3.7.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas XML data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlasXML: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + Parser.AtlasXML(texture, 0, data); + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Unity Texture Atlas to this Texture Manager. + * The data must be in the form of a Unity YAML file. + * + * @method Phaser.Textures.TextureManager#addUnityAtlas + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addUnityAtlas: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + Parser.UnityYAML(texture, 0, data); + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Sprite Sheet to this Texture Manager. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @method Phaser.Textures.TextureManager#addSpriteSheet + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {Phaser.Types.Textures.SpriteSheetConfig} config - The configuration object for this Sprite Sheet. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addSpriteSheet: function (key, source, config) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + var width = texture.source[0].width; + var height = texture.source[0].height; + + Parser.SpriteSheet(texture, 0, 0, 0, width, height, config); + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Sprite Sheet to this Texture Manager, where the Sprite Sheet exists as a Frame within a Texture Atlas. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @method Phaser.Textures.TextureManager#addSpriteSheetFromAtlas + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {Phaser.Types.Textures.SpriteSheetFromAtlasConfig} config - The configuration object for this Sprite Sheet. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addSpriteSheetFromAtlas: function (key, config) + { + if (!this.checkKey(key)) + { + return null; + } + + var atlasKey = GetValue(config, 'atlas', null); + var atlasFrame = GetValue(config, 'frame', null); + + if (!atlasKey || !atlasFrame) + { + return; + } + + var atlas = this.get(atlasKey); + var sheet = atlas.get(atlasFrame); + + if (sheet) + { + var texture = this.create(key, sheet.source.image); + + if (sheet.trimmed) + { + // If trimmed we need to help the parser adjust + Parser.SpriteSheetFromAtlas(texture, sheet, config); + } + else + { + Parser.SpriteSheet(texture, 0, sheet.cutX, sheet.cutY, sheet.cutWidth, sheet.cutHeight, config); + } + + this.emit(Events.ADD, key, texture); + + return texture; + } + }, + + /** + * Creates a new Texture using the given source and dimensions. + * + * @method Phaser.Textures.TextureManager#create + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {integer} width - The width of the Texture. + * @param {integer} height - The height of the Texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + create: function (key, source, width, height) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = new Texture(this, key, source, width, height); + + this.list[key] = texture; + } + + return texture; + }, + + /** + * Checks the given key to see if a Texture using it exists within this Texture Manager. + * + * @method Phaser.Textures.TextureManager#exists + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * + * @return {boolean} Returns `true` if a Texture matching the given key exists in this Texture Manager. + */ + exists: function (key) + { + return (this.list.hasOwnProperty(key)); + }, + + /** + * Returns a Texture from the Texture Manager that matches the given key. + * + * If the key is `undefined` it will return the `__DEFAULT` Texture. + * + * If the key is an instance of a Texture, it will return the key directly. + * + * Finally. if the key is given, but not found and not a Texture instance, it will return the `__MISSING` Texture. + * + * @method Phaser.Textures.TextureManager#get + * @since 3.0.0 + * + * @param {(string|Phaser.Textures.Texture)} key - The unique string-based key of the Texture, or a Texture instance. + * + * @return {Phaser.Textures.Texture} The Texture that was created. + */ + get: function (key) + { + if (key === undefined) { key = '__DEFAULT'; } + + if (this.list[key]) + { + return this.list[key]; + } + else if (key instanceof Texture) + { + return key; + } + else + { + return this.list['__MISSING']; + } + }, + + /** + * Takes a Texture key and Frame name and returns a clone of that Frame if found. + * + * @method Phaser.Textures.TextureManager#cloneFrame + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} frame - The string or index of the Frame to be cloned. + * + * @return {Phaser.Textures.Frame} A Clone of the given Frame. + */ + cloneFrame: function (key, frame) + { + if (this.list[key]) + { + return this.list[key].get(frame).clone(); + } + }, + + /** + * Takes a Texture key and Frame name and returns a reference to that Frame, if found. + * + * @method Phaser.Textures.TextureManager#getFrame + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. + * + * @return {Phaser.Textures.Frame} A Texture Frame object. + */ + getFrame: function (key, frame) + { + if (this.list[key]) + { + return this.list[key].get(frame); + } + }, + + /** + * Returns an array with all of the keys of all Textures in this Texture Manager. + * The output array will exclude the `__DEFAULT` and `__MISSING` keys. + * + * @method Phaser.Textures.TextureManager#getTextureKeys + * @since 3.0.0 + * + * @return {string[]} An array containing all of the Texture keys stored in this Texture Manager. + */ + getTextureKeys: function () + { + var output = []; + + for (var key in this.list) + { + if (key !== '__DEFAULT' && key !== '__MISSING') + { + output.push(key); + } + } + + return output; + }, + + /** + * Given a Texture and an `x` and `y` coordinate this method will return a new + * Color object that has been populated with the color and alpha values of the pixel + * at that location in the Texture. + * + * @method Phaser.Textures.TextureManager#getPixel + * @since 3.0.0 + * + * @param {integer} x - The x coordinate of the pixel within the Texture. + * @param {integer} y - The y coordinate of the pixel within the Texture. + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string or index of the Frame. + * + * @return {?Phaser.Display.Color} A Color object populated with the color values of the requested pixel, + * or `null` if the coordinates were out of bounds. + */ + getPixel: function (x, y, key, frame) + { + var textureFrame = this.getFrame(key, frame); + + if (textureFrame) + { + // Adjust for trim (if not trimmed x and y are just zero) + x -= textureFrame.x; + y -= textureFrame.y; + + var data = textureFrame.data.cut; + + x += data.x; + y += data.y; + + if (x >= data.x && x < data.r && y >= data.y && y < data.b) + { + var ctx = this._tempContext; + + ctx.clearRect(0, 0, 1, 1); + ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = ctx.getImageData(0, 0, 1, 1); + + return new Color(rgb.data[0], rgb.data[1], rgb.data[2], rgb.data[3]); + } + } + + return null; + }, + + /** + * Given a Texture and an `x` and `y` coordinate this method will return a value between 0 and 255 + * corresponding to the alpha value of the pixel at that location in the Texture. If the coordinate + * is out of bounds it will return null. + * + * @method Phaser.Textures.TextureManager#getPixelAlpha + * @since 3.10.0 + * + * @param {integer} x - The x coordinate of the pixel within the Texture. + * @param {integer} y - The y coordinate of the pixel within the Texture. + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string or index of the Frame. + * + * @return {integer} A value between 0 and 255, or `null` if the coordinates were out of bounds. + */ + getPixelAlpha: function (x, y, key, frame) + { + var textureFrame = this.getFrame(key, frame); + + if (textureFrame) + { + // Adjust for trim (if not trimmed x and y are just zero) + x -= textureFrame.x; + y -= textureFrame.y; + + var data = textureFrame.data.cut; + + x += data.x; + y += data.y; + + if (x >= data.x && x < data.r && y >= data.y && y < data.b) + { + var ctx = this._tempContext; + + ctx.clearRect(0, 0, 1, 1); + ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = ctx.getImageData(0, 0, 1, 1); + + return rgb.data[3]; + } + } + + return null; + }, + + /** + * Sets the given Game Objects `texture` and `frame` properties so that it uses + * the Texture and Frame specified in the `key` and `frame` arguments to this method. + * + * @method Phaser.Textures.TextureManager#setTexture + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the texture would be set on. + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string or index of the Frame. + * + * @return {Phaser.GameObjects.GameObject} The Game Object the texture was set on. + */ + setTexture: function (gameObject, key, frame) + { + if (this.list[key]) + { + gameObject.texture = this.list[key]; + gameObject.frame = gameObject.texture.get(frame); + } + + return gameObject; + }, + + /** + * Changes the key being used by a Texture to the new key provided. + * + * The old key is removed, allowing it to be re-used. + * + * Game Objects are linked to Textures by a reference to the Texture object, so + * all existing references will be retained. + * + * @method Phaser.Textures.TextureManager#renameTexture + * @since 3.12.0 + * + * @param {string} currentKey - The current string-based key of the Texture you wish to rename. + * @param {string} newKey - The new unique string-based key to use for the Texture. + * + * @return {boolean} `true` if the Texture key was successfully renamed, otherwise `false`. + */ + renameTexture: function (currentKey, newKey) + { + var texture = this.get(currentKey); + + if (texture && currentKey !== newKey) + { + texture.key = newKey; + + this.list[newKey] = texture; + + delete this.list[currentKey]; + + return true; + } + + return false; + }, + + /** + * Passes all Textures to the given callback. + * + * @method Phaser.Textures.TextureManager#each + * @since 3.0.0 + * + * @param {EachTextureCallback} callback - The callback function to be sent the Textures. + * @param {object} scope - The value to use as `this` when executing the callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + each: function (callback, scope) + { + var args = [ null ]; + + for (var i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var texture in this.list) + { + args[0] = this.list[texture]; + + callback.apply(scope, args); + } + }, + + /** + * Destroys the Texture Manager and all Textures stored within it. + * + * @method Phaser.Textures.TextureManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + for (var texture in this.list) + { + this.list[texture].destroy(); + } + + this.list = {}; + + this.game = null; + + CanvasPool.remove(this._tempCanvas); + } + +}); + +module.exports = TextureManager; + + +/***/ }), +/* 401 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Clamp = __webpack_require__(20); +var Color = __webpack_require__(36); +var CONST = __webpack_require__(32); +var IsSizePowerOfTwo = __webpack_require__(127); +var Texture = __webpack_require__(195); + +/** + * @classdesc + * A Canvas Texture is a special kind of Texture that is backed by an HTML Canvas Element as its source. + * + * You can use the properties of this texture to draw to the canvas element directly, using all of the standard + * canvas operations available in the browser. Any Game Object can be given this texture and will render with it. + * + * Note: When running under WebGL the Canvas Texture needs to re-generate its base WebGLTexture and reupload it to + * the GPU every time you modify it, otherwise the changes you make to this texture will not be visible. To do this + * you should call `CanvasTexture.refresh()` once you are finished with your changes to the canvas. Try and keep + * this to a minimum, especially on large canvas sizes, or you may inadvertently thrash the GPU by constantly uploading + * texture data to it. This restriction does not apply if using the Canvas Renderer. + * + * It starts with only one frame that covers the whole of the canvas. You can add further frames, that specify + * sections of the canvas using the `add` method. + * + * Should you need to resize the canvas use the `setSize` method so that it accurately updates all of the underlying + * texture data as well. Forgetting to do this (i.e. by changing the canvas size directly from your code) could cause + * graphical errors. + * + * @class CanvasTexture + * @extends Phaser.Textures.Texture + * @memberof Phaser.Textures + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Textures.TextureManager} manager - A reference to the Texture Manager this Texture belongs to. + * @param {string} key - The unique string-based key of this Texture. + * @param {HTMLCanvasElement} source - The canvas element that is used as the base of this texture. + * @param {integer} width - The width of the canvas. + * @param {integer} height - The height of the canvas. + */ +var CanvasTexture = new Class({ + + Extends: Texture, + + initialize: + + function CanvasTexture (manager, key, source, width, height) + { + Texture.call(this, manager, key, source, width, height); + + this.add('__BASE', 0, 0, 0, width, height); + + /** + * A reference to the Texture Source of this Canvas. + * + * @name Phaser.Textures.CanvasTexture#_source + * @type {Phaser.Textures.TextureSource} + * @private + * @since 3.7.0 + */ + this._source = this.frames['__BASE'].source; + + /** + * The source Canvas Element. + * + * @name Phaser.Textures.CanvasTexture#canvas + * @readonly + * @type {HTMLCanvasElement} + * @since 3.7.0 + */ + this.canvas = this._source.image; + + /** + * The 2D Canvas Rendering Context. + * + * @name Phaser.Textures.CanvasTexture#context + * @readonly + * @type {CanvasRenderingContext2D} + * @since 3.7.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * The width of the Canvas. + * This property is read-only, if you wish to change it use the `setSize` method. + * + * @name Phaser.Textures.CanvasTexture#width + * @readonly + * @type {integer} + * @since 3.7.0 + */ + this.width = width; + + /** + * The height of the Canvas. + * This property is read-only, if you wish to change it use the `setSize` method. + * + * @name Phaser.Textures.CanvasTexture#height + * @readonly + * @type {integer} + * @since 3.7.0 + */ + this.height = height; + + /** + * The context image data. + * Use the `update` method to populate this when the canvas changes. + * + * @name Phaser.Textures.CanvasTexture#imageData + * @type {ImageData} + * @since 3.13.0 + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into the `buffer`. + * Use the `update` method to populate this when the canvas changes. + * Note that this is unavailable in some browsers, such as Epic Browser, due to their security restrictions. + * + * @name Phaser.Textures.CanvasTexture#data + * @type {Uint8ClampedArray} + * @since 3.13.0 + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * An Uint32Array view into the `buffer`. + * + * @name Phaser.Textures.CanvasTexture#pixels + * @type {Uint32Array} + * @since 3.13.0 + */ + this.pixels = null; + + /** + * An ArrayBuffer the same size as the context ImageData. + * + * @name Phaser.Textures.CanvasTexture#buffer + * @type {ArrayBuffer} + * @since 3.13.0 + */ + this.buffer; + + if (this.data) + { + if (this.imageData.data.buffer) + { + this.buffer = this.imageData.data.buffer; + this.pixels = new Uint32Array(this.buffer); + } + else if (window.ArrayBuffer) + { + this.buffer = new ArrayBuffer(this.imageData.data.length); + this.pixels = new Uint32Array(this.buffer); + } + else + { + this.pixels = this.imageData.data; + } + } + }, + + /** + * This re-creates the `imageData` from the current context. + * It then re-builds the ArrayBuffer, the `data` Uint8ClampedArray reference and the `pixels` Int32Array. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.Textures.CanvasTexture#update + * @since 3.13.0 + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + update: function () + { + this.imageData = this.context.getImageData(0, 0, this.width, this.height); + + this.data = this.imageData.data; + + if (this.imageData.data.buffer) + { + this.buffer = this.imageData.data.buffer; + this.pixels = new Uint32Array(this.buffer); + } + else if (window.ArrayBuffer) + { + this.buffer = new ArrayBuffer(this.imageData.data.length); + this.pixels = new Uint32Array(this.buffer); + } + else + { + this.pixels = this.imageData.data; + } + + if (this.manager.game.config.renderType === CONST.WEBGL) + { + this.refresh(); + } + + return this; + }, + + /** + * Draws the given Image or Canvas element to this CanvasTexture, then updates the internal + * ImageData buffer and arrays. + * + * @method Phaser.Textures.CanvasTexture#draw + * @since 3.13.0 + * + * @param {integer} x - The x coordinate to draw the source at. + * @param {integer} y - The y coordinate to draw the source at. + * @param {(HTMLImageElement|HTMLCanvasElement)} source - The element to draw to this canvas. + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + draw: function (x, y, source) + { + this.context.drawImage(source, x, y); + + return this.update(); + }, + + /** + * Draws the given texture frame to this CanvasTexture, then updates the internal + * ImageData buffer and arrays. + * + * @method Phaser.Textures.CanvasTexture#drawFrame + * @since 3.16.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. + * @param {integer} [x=0] - The x coordinate to draw the source at. + * @param {integer} [y=0] - The y coordinate to draw the source at. + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + drawFrame: function (key, frame, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + var textureFrame = this.manager.getFrame(key, frame); + + if (textureFrame) + { + var cd = textureFrame.canvasData; + + var width = textureFrame.cutWidth; + var height = textureFrame.cutHeight; + var res = textureFrame.source.resolution; + + this.context.drawImage( + textureFrame.source.image, + cd.x, cd.y, + width, + height, + x, y, + width / res, + height / res + ); + + return this.update(); + } + else + { + return this; + } + }, + + /** + * Sets a pixel in the CanvasTexture to the given color and alpha values. + * + * This is an expensive operation to run in large quantities, so use sparingly. + * + * @method Phaser.Textures.CanvasTexture#setPixel + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. + * + * @return {this} This CanvasTexture. + */ + setPixel: function (x, y, red, green, blue, alpha) + { + if (alpha === undefined) { alpha = 255; } + + x = Math.abs(Math.floor(x)); + y = Math.abs(Math.floor(y)); + + var index = this.getIndex(x, y); + + if (index > -1) + { + var imageData = this.context.getImageData(x, y, 1, 1); + + imageData.data[0] = red; + imageData.data[1] = green; + imageData.data[2] = blue; + imageData.data[3] = alpha; + + this.context.putImageData(imageData, x, y); + } + + return this; + }, + + /** + * Puts the ImageData into the context of this CanvasTexture at the given coordinates. + * + * @method Phaser.Textures.CanvasTexture#putData + * @since 3.16.0 + * + * @param {ImageData} imageData - The ImageData to put at the given location. + * @param {integer} x - The x coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} [dirtyX=0] - Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. + * @param {integer} [dirtyY=0] - Vertical position (x coordinate) of the top-left corner from which the image data will be extracted. + * @param {integer} [dirtyWidth] - Width of the rectangle to be painted. Defaults to the width of the image data. + * @param {integer} [dirtyHeight] - Height of the rectangle to be painted. Defaults to the height of the image data. + * + * @return {this} This CanvasTexture. + */ + putData: function (imageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight) + { + if (dirtyX === undefined) { dirtyX = 0; } + if (dirtyY === undefined) { dirtyY = 0; } + if (dirtyWidth === undefined) { dirtyWidth = imageData.width; } + if (dirtyHeight === undefined) { dirtyHeight = imageData.height; } + + this.context.putImageData(imageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight); + + return this; + }, + + /** + * Gets an ImageData region from this CanvasTexture from the position and size specified. + * You can write this back using `CanvasTexture.putData`, or manipulate it. + * + * @method Phaser.Textures.CanvasTexture#getData + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} width - The width of the rectangle from which the ImageData will be extracted. Positive values are to the right, and negative to the left. + * @param {integer} height - The height of the rectangle from which the ImageData will be extracted. Positive values are down, and negative are up. + * + * @return {ImageData} The ImageData extracted from this CanvasTexture. + */ + getData: function (x, y, width, height) + { + x = Clamp(Math.floor(x), 0, this.width - 1); + y = Clamp(Math.floor(y), 0, this.height - 1); + width = Clamp(width, 1, this.width - x); + height = Clamp(height, 1, this.height - y); + + var imageData = this.context.getImageData(x, y, width, height); + + return imageData; + }, + + /** + * Get the color of a specific pixel from this texture and store it in a Color object. + * + * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.Textures.CanvasTexture#getPixel + * @since 3.13.0 + * + * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {Phaser.Display.Color} [out] - A Color object to store the pixel values in. If not provided a new Color object will be created. + * + * @return {Phaser.Display.Color} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) + { + if (!out) + { + out = new Color(); + } + + var index = this.getIndex(x, y); + + if (index > -1) + { + var data = this.data; + + var r = data[index + 0]; + var g = data[index + 1]; + var b = data[index + 2]; + var a = data[index + 3]; + + out.setTo(r, g, b, a); + } + + return out; + }, + + /** + * Returns an array containing all of the pixels in the given region. + * + * If the requested region extends outside the bounds of this CanvasTexture, + * the region is truncated to fit. + * + * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.Textures.CanvasTexture#getPixels + * @since 3.16.0 + * + * @param {integer} [x=0] - The x coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} [y=0] - The y coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} [width] - The width of the region to get. Must be an integer. Defaults to the canvas width if not given. + * @param {integer} [height] - The height of the region to get. Must be an integer. If not given will be set to the `width`. + * + * @return {Phaser.Types.Textures.PixelConfig[]} An array of Pixel objects. + */ + getPixels: function (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = width; } + + x = Math.abs(Math.round(x)); + y = Math.abs(Math.round(y)); + + var left = Clamp(x, 0, this.width); + var right = Clamp(x + width, 0, this.width); + var top = Clamp(y, 0, this.height); + var bottom = Clamp(y + height, 0, this.height); + + var pixel = new Color(); + + var out = []; + + for (var py = top; py < bottom; py++) + { + var row = []; + + for (var px = left; px < right; px++) + { + pixel = this.getPixel(px, py, pixel); + + row.push({ x: px, y: py, color: pixel.color, alpha: pixel.alphaGL }); + } + + out.push(row); + } + + return out; + }, + + /** + * Returns the Image Data index for the given pixel in this CanvasTexture. + * + * The index can be used to read directly from the `this.data` array. + * + * The index points to the red value in the array. The subsequent 3 indexes + * point to green, blue and alpha respectively. + * + * @method Phaser.Textures.CanvasTexture#getIndex + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * + * @return {integer} + */ + getIndex: function (x, y) + { + x = Math.abs(Math.round(x)); + y = Math.abs(Math.round(y)); + + if (x < this.width && y < this.height) + { + return (x + y * this.width) * 4; + } + else + { + return -1; + } + }, + + /** + * This should be called manually if you are running under WebGL. + * It will refresh the WebGLTexture from the Canvas source. Only call this if you know that the + * canvas has changed, as there is a significant GPU texture allocation cost involved in doing so. + * + * @method Phaser.Textures.CanvasTexture#refresh + * @since 3.7.0 + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + refresh: function () + { + this._source.update(); + + return this; + }, + + /** + * Gets the Canvas Element. + * + * @method Phaser.Textures.CanvasTexture#getCanvas + * @since 3.7.0 + * + * @return {HTMLCanvasElement} The Canvas DOM element this texture is using. + */ + getCanvas: function () + { + return this.canvas; + }, + + /** + * Gets the 2D Canvas Rendering Context. + * + * @method Phaser.Textures.CanvasTexture#getContext + * @since 3.7.0 + * + * @return {CanvasRenderingContext2D} The Canvas Rendering Context this texture is using. + */ + getContext: function () + { + return this.context; + }, + + /** + * Clears the given region of this Canvas Texture, resetting it back to transparent. + * If no region is given, the whole Canvas Texture is cleared. + * + * @method Phaser.Textures.CanvasTexture#clear + * @since 3.7.0 + * + * @param {integer} [x=0] - The x coordinate of the top-left of the region to clear. + * @param {integer} [y=0] - The y coordinate of the top-left of the region to clear. + * @param {integer} [width] - The width of the region. + * @param {integer} [height] - The height of the region. + * + * @return {Phaser.Textures.CanvasTexture} The Canvas Texture. + */ + clear: function (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + return this.update(); + }, + + /** + * Changes the size of this Canvas Texture. + * + * @method Phaser.Textures.CanvasTexture#setSize + * @since 3.7.0 + * + * @param {integer} width - The new width of the Canvas. + * @param {integer} [height] - The new height of the Canvas. If not given it will use the width as the height. + * + * @return {Phaser.Textures.CanvasTexture} The Canvas Texture. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + if (width !== this.width || height !== this.height) + { + // Update the Canvas + this.canvas.width = width; + this.canvas.height = height; + + // Update the Texture Source + this._source.width = width; + this._source.height = height; + this._source.isPowerOf2 = IsSizePowerOfTwo(width, height); + + // Update the Frame + this.frames['__BASE'].setSize(width, height, 0, 0); + + this.refresh(); + } + + return this; + }, + + /** + * Destroys this Texture and releases references to its sources and frames. + * + * @method Phaser.Textures.CanvasTexture#destroy + * @since 3.16.0 + */ + destroy: function () + { + Texture.prototype.destroy.call(this); + + this._source = null; + this.canvas = null; + this.context = null; + this.imageData = null; + this.data = null; + this.pixels = null; + this.buffer = null; + } + +}); + +module.exports = CanvasTexture; + + +/***/ }), +/* 402 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); +var Class = __webpack_require__(0); +var IsSizePowerOfTwo = __webpack_require__(127); +var ScaleModes = __webpack_require__(157); + +/** + * @classdesc + * A Texture Source is the encapsulation of the actual source data for a Texture. + * + * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element. + * + * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded. + * + * @class TextureSource + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture this TextureSource belongs to. + * @param {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture)} source - The source image data. + * @param {integer} [width] - Optional width of the source image. If not given it's derived from the source itself. + * @param {integer} [height] - Optional height of the source image. If not given it's derived from the source itself. + * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + */ +var TextureSource = new Class({ + + initialize: + + function TextureSource (texture, source, width, height, flipY) + { + if (flipY === undefined) { flipY = false; } + + var game = texture.manager.game; + + /** + * The Texture this TextureSource belongs to. + * + * @name Phaser.Textures.TextureSource#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.7.0 + */ + this.renderer = game.renderer; + + /** + * The Texture this TextureSource belongs to. + * + * @name Phaser.Textures.TextureSource#texture + * @type {Phaser.Textures.Texture} + * @since 3.0.0 + */ + this.texture = texture; + + /** + * The source of the image data. + * + * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture. + * + * @name Phaser.Textures.TextureSource#source + * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture)} + * @since 3.12.0 + */ + this.source = source; + + /** + * The image data. + * + * This is either an Image element, Canvas element or a Video Element. + * + * @name Phaser.Textures.TextureSource#image + * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement)} + * @since 3.0.0 + */ + this.image = source; + + /** + * Currently un-used. + * + * @name Phaser.Textures.TextureSource#compressionAlgorithm + * @type {integer} + * @default null + * @since 3.0.0 + */ + this.compressionAlgorithm = null; + + /** + * The resolution of the source image. + * + * @name Phaser.Textures.TextureSource#resolution + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.resolution = 1; + + /** + * The width of the source image. If not specified in the constructor it will check + * the `naturalWidth` and then `width` properties of the source image. + * + * @name Phaser.Textures.TextureSource#width + * @type {integer} + * @since 3.0.0 + */ + this.width = width || source.naturalWidth || source.videoWidth || source.width || 0; + + /** + * The height of the source image. If not specified in the constructor it will check + * the `naturalHeight` and then `height` properties of the source image. + * + * @name Phaser.Textures.TextureSource#height + * @type {integer} + * @since 3.0.0 + */ + this.height = height || source.naturalHeight || source.videoHeight || source.height || 0; + + /** + * The Scale Mode the image will use when rendering. + * Either Linear or Nearest. + * + * @name Phaser.Textures.TextureSource#scaleMode + * @type {number} + * @since 3.0.0 + */ + this.scaleMode = ScaleModes.DEFAULT; + + /** + * Is the source image a Canvas Element? + * + * @name Phaser.Textures.TextureSource#isCanvas + * @type {boolean} + * @since 3.0.0 + */ + this.isCanvas = (source instanceof HTMLCanvasElement); + + /** + * Is the source image a Video Element? + * + * @name Phaser.Textures.TextureSource#isVideo + * @type {boolean} + * @since 3.20.0 + */ + this.isVideo = (window.hasOwnProperty('HTMLVideoElement') && source instanceof HTMLVideoElement); + + /** + * Is the source image a Render Texture? + * + * @name Phaser.Textures.TextureSource#isRenderTexture + * @type {boolean} + * @since 3.12.0 + */ + this.isRenderTexture = (source.type === 'RenderTexture'); + + /** + * Is the source image a WebGLTexture? + * + * @name Phaser.Textures.TextureSource#isGLTexture + * @type {boolean} + * @since 3.19.0 + */ + this.isGLTexture = (window.hasOwnProperty('WebGLTexture') && source instanceof WebGLTexture); + + /** + * Are the source image dimensions a power of two? + * + * @name Phaser.Textures.TextureSource#isPowerOf2 + * @type {boolean} + * @since 3.0.0 + */ + this.isPowerOf2 = IsSizePowerOfTwo(this.width, this.height); + + /** + * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture + * already, then this is a reference to that WebGLTexture. + * + * @name Phaser.Textures.TextureSource#glTexture + * @type {?WebGLTexture} + * @default null + * @since 3.0.0 + */ + this.glTexture = null; + + /** + * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + * + * @name Phaser.Textures.TextureSource#flipY + * @type {boolean} + * @since 3.20.0 + */ + this.flipY = flipY; + + this.init(game); + }, + + /** + * Creates a WebGL Texture, if required, and sets the Texture filter mode. + * + * @method Phaser.Textures.TextureSource#init + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser Game instance. + */ + init: function (game) + { + if (this.renderer) + { + if (this.renderer.gl) + { + if (this.isCanvas) + { + this.glTexture = this.renderer.createCanvasTexture(this.image, false, this.flipY); + } + else if (this.isVideo) + { + this.glTexture = this.renderer.createVideoTexture(this.image, false, this.flipY); + } + else if (this.isRenderTexture) + { + this.image = this.source.canvas; + + this.glTexture = this.renderer.createTextureFromSource(null, this.width, this.height, this.scaleMode); + } + else if (this.isGLTexture) + { + this.glTexture = this.source; + } + else + { + this.glTexture = this.renderer.createTextureFromSource(this.image, this.width, this.height, this.scaleMode); + } + } + else if (this.isRenderTexture) + { + this.image = this.source.canvas; + } + } + + if (!game.config.antialias) + { + this.setFilter(1); + } + }, + + /** + * Sets the Filter Mode for this Texture. + * + * The mode can be either Linear, the default, or Nearest. + * + * For pixel-art you should use Nearest. + * + * @method Phaser.Textures.TextureSource#setFilter + * @since 3.0.0 + * + * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode. + */ + setFilter: function (filterMode) + { + if (this.renderer.gl) + { + this.renderer.setTextureFilter(this.glTexture, filterMode); + } + + this.scaleMode = filterMode; + }, + + /** + * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload. + * + * @method Phaser.Textures.TextureSource#setFlipY + * @since 3.20.0 + * + * @param {boolean} [value=true] - Should the WebGL Texture be flipped on the Y axis on texture upload or not? + */ + setFlipY: function (value) + { + if (value === undefined) { value = true; } + + this.flipY = value; + + return this; + }, + + /** + * If this TextureSource is backed by a Canvas and is running under WebGL, + * it updates the WebGLTexture using the canvas data. + * + * @method Phaser.Textures.TextureSource#update + * @since 3.7.0 + */ + update: function () + { + var gl = this.renderer.gl; + + if (gl && this.isCanvas) + { + this.glTexture = this.renderer.updateCanvasTexture(this.image, this.glTexture, this.flipY); + } + else if (gl && this.isVideo) + { + this.glTexture = this.renderer.updateVideoTexture(this.image, this.glTexture, this.flipY); + } + }, + + /** + * Destroys this Texture Source and nulls the references. + * + * @method Phaser.Textures.TextureSource#destroy + * @since 3.0.0 + */ + destroy: function () + { + if (this.glTexture) + { + this.renderer.deleteTexture(this.glTexture); + } + + if (this.isCanvas) + { + CanvasPool.remove(this.image); + } + + this.renderer = null; + this.texture = null; + this.source = null; + this.image = null; + this.glTexture = null; + } + +}); + +module.exports = TextureSource; + + +/***/ }), +/* 403 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Textures.Parsers + */ + +module.exports = { + + AtlasXML: __webpack_require__(906), + Canvas: __webpack_require__(907), + Image: __webpack_require__(908), + JSONArray: __webpack_require__(909), + JSONHash: __webpack_require__(910), + SpriteSheet: __webpack_require__(911), + SpriteSheetFromAtlas: __webpack_require__(912), + UnityYAML: __webpack_require__(913) + +}; + + +/***/ }), +/* 404 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HTML5AudioSoundManager = __webpack_require__(405); +var NoAudioSoundManager = __webpack_require__(407); +var WebAudioSoundManager = __webpack_require__(409); + +/** + * 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 + * + * @function Phaser.Sound.SoundManagerCreator + * @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. + */ +var SoundManagerCreator = { + + create: function (game) + { + var audioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + return new NoAudioSoundManager(game); + } + + if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) + { + return new WebAudioSoundManager(game); + } + + return new HTML5AudioSoundManager(game); + } + +}; + +module.exports = SoundManagerCreator; + + +/***/ }), +/* 405 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSoundManager = __webpack_require__(133); +var Class = __webpack_require__(0); +var Events = __webpack_require__(64); +var HTML5AudioSound = __webpack_require__(406); + +/** + * HTML5 Audio implementation of the Sound Manager. + * + * Note: 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 + * }); + * ``` + * + * @class HTML5AudioSoundManager + * @extends Phaser.Sound.BaseSoundManager + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var HTML5AudioSoundManager = new Class({ + + Extends: BaseSoundManager, + + initialize: + + function HTML5AudioSoundManager (game) + { + /** + * Flag indicating whether if there are no idle instances of HTML5 Audio tag, + * for any particular sound, if one of the used tags should be hijacked and used + * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play + * call should be ignored. + * + * @name Phaser.Sound.HTML5AudioSoundManager#override + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.override = true; + + /** + * Value representing time difference, in seconds, between calling + * play method on an audio tag and when it actually starts playing. + * It is used to achieve more accurate delayed sound playback. + * + * You might need to tweak this value to get the desired results + * since audio play delay varies depending on the browser/platform. + * + * @name Phaser.Sound.HTML5AudioSoundManager#audioPlayDelay + * @type {number} + * @default 0.1 + * @since 3.0.0 + */ + this.audioPlayDelay = 0.1; + + /** + * A value by which we should offset the loop end marker of the + * looping sound to compensate for lag, caused by changing audio + * tag playback position, in order to achieve gapless looping. + * + * You might need to tweak this value to get the desired results + * since loop lag varies depending on the browser/platform. + * + * @name Phaser.Sound.HTML5AudioSoundManager#loopEndOffset + * @type {number} + * @default 0.05 + * @since 3.0.0 + */ + this.loopEndOffset = 0.05; + + /** + * An array for keeping track of all the sounds + * that were paused when game lost focus. + * + * @name Phaser.Sound.HTML5AudioSoundManager#onBlurPausedSounds + * @type {Phaser.Sound.HTML5AudioSound[]} + * @private + * @default [] + * @since 3.0.0 + */ + this.onBlurPausedSounds = []; + + this.locked = 'ontouchstart' in window; + + /** + * A queue of all actions performed on sound objects while audio was locked. + * Once the audio gets unlocked, after an explicit user interaction, + * all actions will be performed in chronological order. + * Array of object types: { sound: Phaser.Sound.HTML5AudioSound, name: string, value?: * } + * + * @name Phaser.Sound.HTML5AudioSoundManager#lockedActionsQueue + * @type {array} + * @private + * @since 3.0.0 + */ + this.lockedActionsQueue = this.locked ? [] : null; + + /** + * Property that actually holds the value of global mute + * for HTML5 Audio sound manager implementation. + * + * @name Phaser.Sound.HTML5AudioSoundManager#_mute + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._mute = false; + + /** + * Property that actually holds the value of global volume + * for HTML5 Audio sound manager implementation. + * + * @name Phaser.Sound.HTML5AudioSoundManager#_volume + * @type {boolean} + * @private + * @default 1 + * @since 3.0.0 + */ + this._volume = 1; + + BaseSoundManager.call(this, game); + }, + + /** + * Adds a new sound into the sound manager. + * + * @method Phaser.Sound.HTML5AudioSoundManager#add + * @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.HTML5AudioSound} The new sound instance. + */ + add: function (key, config) + { + var sound = new HTML5AudioSound(this, key, config); + + this.sounds.push(sound); + + return sound; + }, + + /** + * Unlocks HTML5 Audio loading and playback on mobile + * devices on the initial explicit user interaction. + * + * @method Phaser.Sound.HTML5AudioSoundManager#unlock + * @since 3.0.0 + */ + unlock: function () + { + this.locked = false; + + var _this = this; + + this.game.cache.audio.entries.each(function (key, tags) + { + for (var i = 0; i < tags.length; i++) + { + if (tags[i].dataset.locked === 'true') + { + _this.locked = true; + + return false; + } + } + + return true; + }); + + if (!this.locked) + { + return; + } + + var moved = false; + + var detectMove = function () + { + moved = true; + }; + + var unlock = function () + { + if (moved) + { + moved = false; + return; + } + + document.body.removeEventListener('touchmove', detectMove); + document.body.removeEventListener('touchend', unlock); + + var lockedTags = []; + + _this.game.cache.audio.entries.each(function (key, tags) + { + for (var i = 0; i < tags.length; i++) + { + var tag = tags[i]; + + if (tag.dataset.locked === 'true') + { + lockedTags.push(tag); + } + } + + return true; + }); + + if (lockedTags.length === 0) + { + return; + } + + var lastTag = lockedTags[lockedTags.length - 1]; + + lastTag.oncanplaythrough = function () + { + lastTag.oncanplaythrough = null; + + lockedTags.forEach(function (tag) + { + tag.dataset.locked = 'false'; + }); + + _this.unlocked = true; + }; + + lockedTags.forEach(function (tag) + { + tag.load(); + }); + }; + + this.once(Events.UNLOCKED, function () + { + this.forEachActiveSound(function (sound) + { + if (sound.currentMarker === null && sound.duration === 0) + { + sound.duration = sound.tags[0].duration; + } + + sound.totalDuration = sound.tags[0].duration; + }); + + while (this.lockedActionsQueue.length) + { + var lockedAction = this.lockedActionsQueue.shift(); + + if (lockedAction.sound[lockedAction.prop].apply) + { + lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []); + } + else + { + lockedAction.sound[lockedAction.prop] = lockedAction.value; + } + } + + }, this); + + document.body.addEventListener('touchmove', detectMove, false); + document.body.addEventListener('touchend', unlock, false); + }, + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSoundManager#onBlur + * @protected + * @since 3.0.0 + */ + onBlur: function () + { + this.forEachActiveSound(function (sound) + { + if (sound.isPlaying) + { + this.onBlurPausedSounds.push(sound); + sound.onBlur(); + } + }); + }, + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSoundManager#onFocus + * @protected + * @since 3.0.0 + */ + onFocus: function () + { + this.onBlurPausedSounds.forEach(function (sound) + { + sound.onFocus(); + }); + + this.onBlurPausedSounds.length = 0; + }, + + /** + * Calls Phaser.Sound.BaseSoundManager#destroy method + * and cleans up all HTML5 Audio related stuff. + * + * @method Phaser.Sound.HTML5AudioSoundManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + BaseSoundManager.prototype.destroy.call(this); + + this.onBlurPausedSounds.length = 0; + this.onBlurPausedSounds = null; + }, + + /** + * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters + * to check if sound manager is locked and then either perform action immediately or queue it + * to be performed once the sound manager gets unlocked. + * + * @method Phaser.Sound.HTML5AudioSoundManager#isLocked + * @protected + * @since 3.0.0 + * + * @param {Phaser.Sound.HTML5AudioSound} sound - Sound object on which to perform queued action. + * @param {string} prop - Name of the method to be called or property to be assigned a value to. + * @param {*} [value] - An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property. + * + * @return {boolean} Whether the sound manager is locked. + */ + isLocked: function (sound, prop, value) + { + if (sound.tags[0].dataset.locked === 'true') + { + this.lockedActionsQueue.push({ + sound: sound, + prop: prop, + value: value + }); + + return true; + } + + return false; + }, + + /** + * Sets the muted state of all this Sound Manager. + * + * @method Phaser.Sound.HTML5AudioSoundManager#setMute + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.3.0 + * + * @param {boolean} value - `true` to mute all sounds, `false` to unmute them. + * + * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * @name Phaser.Sound.HTML5AudioSoundManager#mute + * @type {boolean} + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return this._mute; + }, + + set: function (value) + { + this._mute = value; + + this.forEachActiveSound(function (sound) + { + sound.updateMute(); + }); + + this.emit(Events.GLOBAL_MUTE, this, value); + } + + }, + + /** + * Sets the volume of this Sound Manager. + * + * @method Phaser.Sound.HTML5AudioSoundManager#setVolume + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.3.0 + * + * @param {number} value - The global volume of this Sound Manager. + * + * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * @name Phaser.Sound.HTML5AudioSoundManager#volume + * @type {number} + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this._volume; + }, + + set: function (value) + { + this._volume = value; + + this.forEachActiveSound(function (sound) + { + sound.updateVolume(); + }); + + this.emit(Events.GLOBAL_VOLUME, this, value); + } + + } + +}); + +module.exports = HTML5AudioSoundManager; + + +/***/ }), +/* 406 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSound = __webpack_require__(134); +var Class = __webpack_require__(0); +var Events = __webpack_require__(64); + +/** + * @classdesc + * HTML5 Audio implementation of the sound. + * + * @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. + */ +var HTML5AudioSound = new Class({ + + Extends: BaseSound, + + initialize: + + function HTML5AudioSound (manager, key, config) + { + if (config === undefined) { config = {}; } + + /** + * An array containing all HTML5 Audio tags that could be used for individual + * sound's playback. Number of instances depends on the config value passed + * to the Loader#audio method call, default is 1. + * + * @name Phaser.Sound.HTML5AudioSound#tags + * @type {HTMLAudioElement[]} + * @private + * @since 3.0.0 + */ + this.tags = manager.game.cache.audio.get(key); + + if (!this.tags) + { + throw new Error('There is no audio asset with key "' + key + '" in the audio cache'); + } + + /** + * Reference to an HTML5 Audio tag used for playing sound. + * + * @name Phaser.Sound.HTML5AudioSound#audio + * @type {HTMLAudioElement} + * @private + * @default null + * @since 3.0.0 + */ + this.audio = null; + + /** + * Timestamp as generated by the Request Animation Frame or SetTimeout + * representing the time at which the delayed sound playback should start. + * Set to 0 if sound playback is not delayed. + * + * @name Phaser.Sound.HTML5AudioSound#startTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.startTime = 0; + + /** + * Audio tag's playback position recorded on previous + * update method call. Set to 0 if sound is not playing. + * + * @name Phaser.Sound.HTML5AudioSound#previousTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.previousTime = 0; + + this.duration = this.tags[0].duration; + + this.totalDuration = this.tags[0].duration; + + BaseSound.call(this, manager, key, config); + }, + + /** + * Play this sound, or a marked section of it. + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * + * @method Phaser.Sound.HTML5AudioSound#play + * @fires Phaser.Sound.Events#PLAY + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. + * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (markerName, config) + { + if (this.manager.isLocked(this, 'play', [ markerName, config ])) + { + return false; + } + + if (!BaseSound.prototype.play.call(this, markerName, config)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + if (!this.pickAndPlayAudioTag()) + { + return false; + } + + this.emit(Events.PLAY, this); + + return true; + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound.HTML5AudioSound#pause + * @fires Phaser.Sound.Events#PAUSE + * @since 3.0.0 + * + * @return {boolean} Whether the sound was paused successfully. + */ + pause: function () + { + if (this.manager.isLocked(this, 'pause')) + { + return false; + } + + if (this.startTime > 0) + { + return false; + } + + if (!BaseSound.prototype.pause.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = true \/\/\/ + this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); + + this.stopAndReleaseAudioTag(); + + this.emit(Events.PAUSE, this); + + return true; + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound.HTML5AudioSound#resume + * @fires Phaser.Sound.Events#RESUME + * @since 3.0.0 + * + * @return {boolean} Whether the sound was resumed successfully. + */ + resume: function () + { + if (this.manager.isLocked(this, 'resume')) + { + return false; + } + + if (this.startTime > 0) + { + return false; + } + + if (!BaseSound.prototype.resume.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + if (!this.pickAndPlayAudioTag()) + { + return false; + } + + this.emit(Events.RESUME, this); + + return true; + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound.HTML5AudioSound#stop + * @fires Phaser.Sound.Events#STOP + * @since 3.0.0 + * + * @return {boolean} Whether the sound was stopped successfully. + */ + stop: function () + { + if (this.manager.isLocked(this, 'stop')) + { + return false; + } + + if (!BaseSound.prototype.stop.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = false \/\/\/ + this.stopAndReleaseAudioTag(); + + this.emit(Events.STOP, this); + + return true; + }, + + /** + * Used internally to do what the name says. + * + * @method Phaser.Sound.HTML5AudioSound#pickAndPlayAudioTag + * @private + * @since 3.0.0 + * + * @return {boolean} Whether the sound was assigned an audio tag successfully. + */ + pickAndPlayAudioTag: function () + { + if (!this.pickAudioTag()) + { + this.reset(); + return false; + } + + var seek = this.currentConfig.seek; + var delay = this.currentConfig.delay; + var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; + + this.previousTime = offset; + this.audio.currentTime = offset; + this.applyConfig(); + + if (delay === 0) + { + this.startTime = 0; + + if (this.audio.paused) + { + this.playCatchPromise(); + } + } + else + { + this.startTime = window.performance.now() + delay * 1000; + + if (!this.audio.paused) + { + this.audio.pause(); + } + } + + this.resetConfig(); + + return true; + }, + + /** + * 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 + * @private + * @since 3.0.0 + * + * @return {boolean} Whether the sound was assigned an audio tag successfully. + */ + pickAudioTag: function () + { + if (this.audio) + { + return true; + } + + for (var i = 0; i < this.tags.length; i++) + { + var audio = this.tags[i]; + + if (audio.dataset.used === 'false') + { + audio.dataset.used = 'true'; + this.audio = audio; + return true; + } + } + + if (!this.manager.override) + { + return false; + } + + var otherSounds = []; + + this.manager.forEachActiveSound(function (sound) + { + if (sound.key === this.key && sound.audio) + { + otherSounds.push(sound); + } + }, this); + + otherSounds.sort(function (a1, a2) + { + if (a1.loop === a2.loop) + { + // sort by progress + return (a2.seek / a2.duration) - (a1.seek / a1.duration); + } + return a1.loop ? 1 : -1; + }); + + var selectedSound = otherSounds[0]; + + this.audio = selectedSound.audio; + + selectedSound.reset(); + selectedSound.audio = null; + selectedSound.startTime = 0; + selectedSound.previousTime = 0; + + return true; + }, + + /** + * Method used for playing audio tag and catching possible exceptions + * thrown from rejected Promise returned from play method call. + * + * @method Phaser.Sound.HTML5AudioSound#playCatchPromise + * @private + * @since 3.0.0 + */ + playCatchPromise: function () + { + var playPromise = this.audio.play(); + + if (playPromise) + { + // eslint-disable-next-line no-unused-vars + playPromise.catch(function (reason) + { + console.warn(reason); + }); + } + }, + + /** + * Used internally to do what the name says. + * + * @method Phaser.Sound.HTML5AudioSound#stopAndReleaseAudioTag + * @private + * @since 3.0.0 + */ + stopAndReleaseAudioTag: function () + { + this.audio.pause(); + this.audio.dataset.used = 'false'; + this.audio = null; + this.startTime = 0; + this.previousTime = 0; + }, + + /** + * Method used internally to reset sound state, usually when stopping sound + * or when hijacking audio tag from another sound. + * + * @method Phaser.Sound.HTML5AudioSound#reset + * @private + * @since 3.0.0 + */ + reset: function () + { + BaseSound.prototype.stop.call(this); + }, + + /** + * Method used internally by sound manager for pausing sound if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSoundManager#onBlur + * @private + * @since 3.0.0 + */ + onBlur: function () + { + this.isPlaying = false; + this.isPaused = true; + + this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); + + this.currentConfig.delay = Math.max(0, (this.startTime - window.performance.now()) / 1000); + + this.stopAndReleaseAudioTag(); + }, + + /** + * Method used internally by sound manager for resuming sound if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSound#onFocus + * @private + * @since 3.0.0 + */ + onFocus: function () + { + this.isPlaying = true; + this.isPaused = false; + this.pickAndPlayAudioTag(); + }, + + /** + * Update method called automatically by sound manager on every game step. + * + * @method Phaser.Sound.HTML5AudioSound#update + * @fires Phaser.Sound.Events#COMPLETE + * @fires Phaser.Sound.Events#LOOPED + * @protected + * @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 elapsed since the last frame. + */ + // eslint-disable-next-line no-unused-vars + update: function (time, delta) + { + if (!this.isPlaying) + { + return; + } + + // handling delayed playback + if (this.startTime > 0) + { + if (this.startTime < time - this.manager.audioPlayDelay) + { + this.audio.currentTime += Math.max(0, time - this.startTime) / 1000; + this.startTime = 0; + this.previousTime = this.audio.currentTime; + this.playCatchPromise(); + } + + return; + } + + // handle looping and ending + var startTime = this.currentMarker ? this.currentMarker.start : 0; + var endTime = startTime + this.duration; + var currentTime = this.audio.currentTime; + + if (this.currentConfig.loop) + { + if (currentTime >= endTime - this.manager.loopEndOffset) + { + this.audio.currentTime = startTime + Math.max(0, currentTime - endTime); + currentTime = this.audio.currentTime; + } + else if (currentTime < startTime) + { + this.audio.currentTime += startTime; + currentTime = this.audio.currentTime; + } + + if (currentTime < this.previousTime) + { + this.emit(Events.LOOPED, this); + } + } + else if (currentTime >= endTime) + { + this.reset(); + + this.stopAndReleaseAudioTag(); + + this.emit(Events.COMPLETE, this); + + return; + } + + this.previousTime = currentTime; + }, + + /** + * Calls Phaser.Sound.BaseSound#destroy method + * and cleans up all HTML5 Audio related stuff. + * + * @method Phaser.Sound.HTML5AudioSound#destroy + * @since 3.0.0 + */ + destroy: function () + { + BaseSound.prototype.destroy.call(this); + + this.tags = null; + + if (this.audio) + { + this.stopAndReleaseAudioTag(); + } + }, + + /** + * Method used internally to determine mute setting of the sound. + * + * @method Phaser.Sound.HTML5AudioSound#updateMute + * @private + * @since 3.0.0 + */ + updateMute: function () + { + if (this.audio) + { + this.audio.muted = this.currentConfig.mute || this.manager.mute; + } + }, + + /** + * Method used internally to calculate total volume of the sound. + * + * @method Phaser.Sound.HTML5AudioSound#updateVolume + * @private + * @since 3.0.0 + */ + updateVolume: function () + { + if (this.audio) + { + this.audio.volume = this.currentConfig.volume * this.manager.volume; + } + }, + + /** + * Method used internally to calculate total playback rate of the sound. + * + * @method Phaser.Sound.HTML5AudioSound#calculateRate + * @protected + * @since 3.0.0 + */ + calculateRate: function () + { + BaseSound.prototype.calculateRate.call(this); + + if (this.audio) + { + this.audio.playbackRate = this.totalRate; + } + }, + + /** + * Boolean indicating whether the sound is muted or not. + * Gets or sets the muted state of this sound. + * + * @name Phaser.Sound.HTML5AudioSound#mute + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return this.currentConfig.mute; + }, + + set: function (value) + { + this.currentConfig.mute = value; + + if (this.manager.isLocked(this, 'mute', value)) + { + return; + } + + this.updateMute(); + + this.emit(Events.MUTE, this, value); + } + }, + + /** + * Sets the muted state of this Sound. + * + * @method Phaser.Sound.HTML5AudioSound#setMute + * @fires Phaser.Sound.Events#MUTE + * @since 3.4.0 + * + * @param {boolean} value - `true` to mute this sound, `false` to unmute it. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). + * + * @name Phaser.Sound.HTML5AudioSound#volume + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this.currentConfig.volume; + }, + + set: function (value) + { + this.currentConfig.volume = value; + + if (this.manager.isLocked(this, 'volume', value)) + { + return; + } + + this.updateVolume(); + + this.emit(Events.VOLUME, this, value); + } + }, + + /** + * Sets the volume of this Sound. + * + * @method Phaser.Sound.HTML5AudioSound#setVolume + * @fires Phaser.Sound.Events#VOLUME + * @since 3.4.0 + * + * @param {number} value - The volume of the sound. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * Rate at which this Sound will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @name Phaser.Sound.HTML5AudioSound#rate + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#RATE + * @since 3.0.0 + */ + rate: { + + get: function () + { + return this.currentConfig.rate; + }, + + set: function (value) + { + this.currentConfig.rate = value; + + if (this.manager.isLocked(this, Events.RATE, value)) + { + return; + } + else + { + this.calculateRate(); + + this.emit(Events.RATE, this, value); + } + } + + }, + + /** + * Sets the playback rate of this Sound. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @method Phaser.Sound.HTML5AudioSound#setRate + * @fires Phaser.Sound.Events#RATE + * @since 3.3.0 + * + * @param {number} value - The playback rate at of this Sound. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound. + */ + setRate: function (value) + { + this.rate = value; + + return this; + }, + + /** + * 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 + */ + detune: { + + get: function () + { + return this.currentConfig.detune; + }, + + set: function (value) + { + this.currentConfig.detune = value; + + if (this.manager.isLocked(this, Events.DETUNE, value)) + { + return; + } + else + { + this.calculateRate(); + + this.emit(Events.DETUNE, this, value); + } + } + + }, + + /** + * 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 {Phaser.Sound.HTML5AudioSound} This Sound. + */ + setDetune: function (value) + { + this.detune = value; + + return this; + }, + + /** + * Property representing the position of playback for this sound, in seconds. + * Setting it to a specific value moves current playback to that position. + * The value given is clamped to the range 0 to current marker duration. + * Setting seek of a stopped sound has no effect. + * + * @name Phaser.Sound.HTML5AudioSound#seek + * @type {number} + * @fires Phaser.Sound.Events#SEEK + * @since 3.0.0 + */ + seek: { + + get: function () + { + if (this.isPlaying) + { + return this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); + } + else if (this.isPaused) + { + return this.currentConfig.seek; + } + else + { + return 0; + } + }, + + set: function (value) + { + if (this.manager.isLocked(this, 'seek', value)) + { + return; + } + + if (this.startTime > 0) + { + return; + } + + if (this.isPlaying || this.isPaused) + { + value = Math.min(Math.max(0, value), this.duration); + + if (this.isPlaying) + { + this.previousTime = value; + this.audio.currentTime = value; + } + else if (this.isPaused) + { + this.currentConfig.seek = value; + } + + this.emit(Events.SEEK, this, value); + } + } + }, + + /** + * Seeks to a specific point in this sound. + * + * @method Phaser.Sound.HTML5AudioSound#setSeek + * @fires Phaser.Sound.Events#SEEK + * @since 3.4.0 + * + * @param {number} value - The point in the sound to seek to. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setSeek: function (value) + { + this.seek = value; + + return this; + }, + + /** + * Flag indicating whether or not the sound or current sound marker will loop. + * + * @name Phaser.Sound.HTML5AudioSound#loop + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#LOOP + * @since 3.0.0 + */ + loop: { + + get: function () + { + return this.currentConfig.loop; + }, + + set: function (value) + { + this.currentConfig.loop = value; + + if (this.manager.isLocked(this, 'loop', value)) + { + return; + } + + if (this.audio) + { + this.audio.loop = value; + } + + this.emit(Events.LOOP, this, value); + } + + }, + + /** + * Sets the loop state of this Sound. + * + * @method Phaser.Sound.HTML5AudioSound#setLoop + * @fires Phaser.Sound.Events#LOOP + * @since 3.4.0 + * + * @param {boolean} value - `true` to loop this sound, `false` to not loop it. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setLoop: function (value) + { + this.loop = value; + + return this; + } + +}); + +module.exports = HTML5AudioSound; + + +/***/ }), +/* 407 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSoundManager = __webpack_require__(133); +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var NoAudioSound = __webpack_require__(408); +var NOOP = __webpack_require__(2); + +/** + * @classdesc + * No audio implementation of the sound manager. It is used if audio has been + * disabled in the game config or the device doesn't support any audio. + * + * It represents a graceful degradation of sound manager logic that provides + * minimal functionality and prevents Phaser projects that use audio from + * breaking on devices that don't support any audio playback technologies. + * + * @class NoAudioSoundManager + * @extends Phaser.Sound.BaseSoundManager + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var NoAudioSoundManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function NoAudioSoundManager (game) + { + EventEmitter.call(this); + + this.game = game; + this.sounds = []; + this.mute = false; + this.volume = 1; + this.rate = 1; + this.detune = 0; + this.pauseOnBlur = true; + this.locked = false; + }, + + add: function (key, config) + { + var sound = new NoAudioSound(this, key, config); + + this.sounds.push(sound); + + return sound; + }, + + addAudioSprite: function (key, config) + { + var sound = this.add(key, config); + + sound.spritemap = {}; + + return sound; + }, + + // eslint-disable-next-line no-unused-vars + play: function (key, extra) + { + return false; + }, + + // eslint-disable-next-line no-unused-vars + playAudioSprite: function (key, spriteName, config) + { + return false; + }, + + remove: function (sound) + { + return BaseSoundManager.prototype.remove.call(this, sound); + }, + + removeByKey: function (key) + { + return BaseSoundManager.prototype.removeByKey.call(this, key); + }, + + pauseAll: NOOP, + resumeAll: NOOP, + stopAll: NOOP, + update: NOOP, + setRate: NOOP, + setDetune: NOOP, + setMute: NOOP, + setVolume: NOOP, + + forEachActiveSound: function (callbackfn, scope) + { + BaseSoundManager.prototype.forEachActiveSound.call(this, callbackfn, scope); + }, + + destroy: function () + { + BaseSoundManager.prototype.destroy.call(this); + } + +}); + +module.exports = NoAudioSoundManager; + + +/***/ }), +/* 408 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSound = __webpack_require__(134); +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Extend = __webpack_require__(17); + +/** + * @classdesc + * No audio implementation of the sound. It is used if audio has been + * disabled in the game config or the device doesn't support any audio. + * + * It represents a graceful degradation of sound logic that provides + * minimal functionality and prevents Phaser projects that use audio from + * breaking on devices that don't support any audio playback technologies. + * + * @class NoAudioSound + * @extends Phaser.Sound.BaseSound + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Sound.NoAudioSoundManager} 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. + */ +var NoAudioSound = new Class({ + + Extends: EventEmitter, + + initialize: + + function NoAudioSound (manager, key, config) + { + if (config === void 0) { config = {}; } + + EventEmitter.call(this); + + this.manager = manager; + this.key = key; + this.isPlaying = false; + this.isPaused = false; + this.totalRate = 1; + this.duration = 0; + this.totalDuration = 0; + + this.config = Extend({ + mute: false, + volume: 1, + rate: 1, + detune: 0, + seek: 0, + loop: false, + delay: 0 + }, config); + + this.currentConfig = this.config; + this.mute = false; + this.volume = 1; + this.rate = 1; + this.detune = 0; + this.seek = 0; + this.loop = false; + this.markers = {}; + this.currentMarker = null; + this.pendingRemove = false; + }, + + // eslint-disable-next-line no-unused-vars + addMarker: function (marker) + { + return false; + }, + + // eslint-disable-next-line no-unused-vars + updateMarker: function (marker) + { + return false; + }, + + // eslint-disable-next-line no-unused-vars + removeMarker: function (markerName) + { + return null; + }, + + // eslint-disable-next-line no-unused-vars + play: function (markerName, config) + { + return false; + }, + + pause: function () + { + return false; + }, + + resume: function () + { + return false; + }, + + stop: function () + { + return false; + }, + + destroy: function () + { + this.manager.remove(this); + + BaseSound.prototype.destroy.call(this); + } +}); + +module.exports = NoAudioSound; + + +/***/ }), +/* 409 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Base64ToArrayBuffer = __webpack_require__(410); +var BaseSoundManager = __webpack_require__(133); +var Class = __webpack_require__(0); +var Events = __webpack_require__(64); +var WebAudioSound = __webpack_require__(411); + +/** + * @classdesc + * Web Audio API implementation of the sound manager. + * + * @class WebAudioSoundManager + * @extends Phaser.Sound.BaseSoundManager + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var WebAudioSoundManager = new Class({ + + Extends: BaseSoundManager, + + initialize: + + function WebAudioSoundManager (game) + { + /** + * The AudioContext being used for playback. + * + * @name Phaser.Sound.WebAudioSoundManager#context + * @type {AudioContext} + * @private + * @since 3.0.0 + */ + this.context = this.createAudioContext(game); + + /** + * Gain node responsible for controlling global muting. + * + * @name Phaser.Sound.WebAudioSoundManager#masterMuteNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.masterMuteNode = this.context.createGain(); + + /** + * Gain node responsible for controlling global volume. + * + * @name Phaser.Sound.WebAudioSoundManager#masterVolumeNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.masterVolumeNode = this.context.createGain(); + + this.masterMuteNode.connect(this.masterVolumeNode); + + this.masterVolumeNode.connect(this.context.destination); + + /** + * Destination node for connecting individual sounds to. + * + * @name Phaser.Sound.WebAudioSoundManager#destination + * @type {AudioNode} + * @private + * @since 3.0.0 + */ + this.destination = this.masterMuteNode; + + this.locked = this.context.state === 'suspended' && ('ontouchstart' in window || 'onclick' in window); + + BaseSoundManager.call(this, game); + + if (this.locked) + { + this.unlock(); + } + }, + + /** + * Method responsible for instantiating and returning AudioContext instance. + * If an instance of an AudioContext class was provided through the game config, + * that instance will be returned instead. This can come in handy if you are reloading + * a Phaser game on a page that never properly refreshes (such as in an SPA project) + * and you want to reuse already instantiated AudioContext. + * + * @method Phaser.Sound.WebAudioSoundManager#createAudioContext + * @private + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + * + * @return {AudioContext} The AudioContext instance to be used for playback. + */ + createAudioContext: function (game) + { + var audioConfig = game.config.audio; + + if (audioConfig && audioConfig.context) + { + audioConfig.context.resume(); + + return audioConfig.context; + } + + return new AudioContext(); + }, + + /** + * This method takes a new AudioContext reference and then sets + * this Sound Manager to use that context for all playback. + * + * As part of this call it also disconnects the master mute and volume + * nodes and then re-creates them on the new given context. + * + * @method Phaser.Sound.WebAudioSoundManager#setAudioContext + * @since 3.21.0 + * + * @param {AudioContext} context - Reference to an already created AudioContext instance. + * + * @return {this} The WebAudioSoundManager instance. + */ + setAudioContext: function (context) + { + if (this.context) + { + this.context.close(); + } + + if (this.masterMuteNode) + { + this.masterMuteNode.disconnect(); + } + + if (this.masterVolumeNode) + { + this.masterVolumeNode.disconnect(); + } + + this.context = context; + + this.masterMuteNode = context.createGain(); + this.masterVolumeNode = context.createGain(); + + this.masterMuteNode.connect(this.masterVolumeNode); + this.masterVolumeNode.connect(context.destination); + + this.destination = this.masterMuteNode; + + return this; + }, + + /** + * Adds a new sound into the sound manager. + * + * @method Phaser.Sound.WebAudioSoundManager#add + * @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.WebAudioSound} The new sound instance. + */ + add: function (key, config) + { + var sound = new WebAudioSound(this, key, config); + + this.sounds.push(sound); + + return sound; + }, + + /** + * Decode audio data into a format ready for playback via Web Audio. + * + * The audio data can be a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + * + * The `audioKey` is the key that will be used to save the decoded audio to the audio cache. + * + * Instead of passing a single entry you can instead pass an array of `Phaser.Types.Sound.DecodeAudioConfig` + * objects as the first and only argument. + * + * Decoding is an async process, so be sure to listen for the events to know when decoding has completed. + * + * Once the audio has decoded it can be added to the Sound Manager or played via its key. + * + * @method Phaser.Sound.WebAudioSoundManager#decodeAudio + * @fires Phaser.Sound.Events#DECODED + * @fires Phaser.Sound.Events#DECODED_ALL + * @since 3.18.0 + * + * @param {(Phaser.Types.Sound.DecodeAudioConfig[]|string)} [audioKey] - The string-based key to be used to reference the decoded audio in the audio cache, or an array of audio config objects. + * @param {(ArrayBuffer|string)} [audioData] - The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + */ + decodeAudio: function (audioKey, audioData) + { + var audioFiles; + + if (!Array.isArray(audioKey)) + { + audioFiles = [ { key: audioKey, data: audioData } ]; + } + else + { + audioFiles = audioKey; + } + + var cache = this.game.cache.audio; + var remaining = audioFiles.length; + + for (var i = 0; i < audioFiles.length; i++) + { + var entry = audioFiles[i]; + + var key = entry.key; + var data = entry.data; + + if (typeof data === 'string') + { + data = Base64ToArrayBuffer(data); + } + + var success = function (key, audioBuffer) + { + cache.add(key, audioBuffer); + + this.emit(Events.DECODED, key); + + remaining--; + + if (remaining === 0) + { + this.emit(Events.DECODED_ALL); + } + }.bind(this, key); + + var failure = function (key, error) + { + // eslint-disable-next-line no-console + console.error('Error decoding audio: ' + key + ' - ', error ? error.message : ''); + + remaining--; + + if (remaining === 0) + { + this.emit(Events.DECODED_ALL); + } + }.bind(this, key); + + this.context.decodeAudioData(data, success, failure); + } + }, + + /** + * 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 + */ + unlock: function () + { + var _this = this; + + var body = document.body; + + var unlockHandler = function unlockHandler () + { + if (_this.context) + { + _this.context.resume().then(function () + { + body.removeEventListener('touchstart', unlockHandler); + body.removeEventListener('touchend', unlockHandler); + body.removeEventListener('click', unlockHandler); + body.removeEventListener('keydown', unlockHandler); + + _this.unlocked = true; + }, function () + { + body.removeEventListener('touchstart', unlockHandler); + body.removeEventListener('touchend', unlockHandler); + body.removeEventListener('click', unlockHandler); + body.removeEventListener('keydown', unlockHandler); + }); + } + }; + + if (body) + { + body.addEventListener('touchstart', unlockHandler, false); + body.addEventListener('touchend', unlockHandler, false); + body.addEventListener('click', unlockHandler, false); + body.addEventListener('keydown', unlockHandler, false); + } + }, + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.WebAudioSoundManager#onBlur + * @protected + * @since 3.0.0 + */ + onBlur: function () + { + if (!this.locked) + { + this.context.suspend(); + } + }, + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.WebAudioSoundManager#onFocus + * @protected + * @since 3.0.0 + */ + onFocus: function () + { + if (!this.locked) + { + this.context.resume(); + } + }, + + /** + * Calls Phaser.Sound.BaseSoundManager#destroy method + * and cleans up all Web Audio API related stuff. + * + * @method Phaser.Sound.WebAudioSoundManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.destination = null; + this.masterVolumeNode.disconnect(); + this.masterVolumeNode = null; + this.masterMuteNode.disconnect(); + this.masterMuteNode = null; + + if (this.game.config.audio && this.game.config.audio.context) + { + this.context.suspend(); + } + else + { + var _this = this; + + this.context.close().then(function () + { + _this.context = null; + }); + } + + BaseSoundManager.prototype.destroy.call(this); + }, + + /** + * Sets the muted state of all this Sound Manager. + * + * @method Phaser.Sound.WebAudioSoundManager#setMute + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.3.0 + * + * @param {boolean} value - `true` to mute all sounds, `false` to unmute them. + * + * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * @name Phaser.Sound.WebAudioSoundManager#mute + * @type {boolean} + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return (this.masterMuteNode.gain.value === 0); + }, + + set: function (value) + { + this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0); + + this.emit(Events.GLOBAL_MUTE, this, value); + } + + }, + + /** + * Sets the volume of this Sound Manager. + * + * @method Phaser.Sound.WebAudioSoundManager#setVolume + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.3.0 + * + * @param {number} value - The global volume of this Sound Manager. + * + * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * @name Phaser.Sound.WebAudioSoundManager#volume + * @type {number} + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this.masterVolumeNode.gain.value; + }, + + set: function (value) + { + this.masterVolumeNode.gain.setValueAtTime(value, 0); + + this.emit(Events.GLOBAL_VOLUME, this, value); + } + + } + +}); + +module.exports = WebAudioSoundManager; + + +/***/ }), +/* 410 */ +/***/ (function(module, exports) { + +/** + * @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer) + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +// Use a lookup table to find the index. +var lookup = new Uint8Array(256); + +for (var i = 0; i < chars.length; i++) +{ + lookup[chars.charCodeAt(i)] = i; +} + +/** + * Converts a base64 string, either with or without a data uri, into an Array Buffer. + * + * @function Phaser.Utils.Base64.Base64ToArrayBuffer + * @since 3.18.0 + * + * @param {string} base64 - The base64 string to be decoded. Can optionally contain a data URI header, which will be stripped out prior to decoding. + * + * @return {ArrayBuffer} An ArrayBuffer decoded from the base64 data. + */ +var Base64ToArrayBuffer = function (base64) +{ + // Is it a data uri? if so, strip the header away + base64 = base64.substr(base64.indexOf(',') + 1); + + var len = base64.length; + var bufferLength = len * 0.75; + var p = 0; + var encoded1; + var encoded2; + var encoded3; + var encoded4; + + if (base64[len - 1] === '=') + { + bufferLength--; + + if (base64[len - 2] === '=') + { + bufferLength--; + } + } + + var arrayBuffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(arrayBuffer); + + for (var i = 0; i < len; i += 4) + { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return arrayBuffer; +}; + +module.exports = Base64ToArrayBuffer; + + +/***/ }), +/* 411 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSound = __webpack_require__(134); +var Class = __webpack_require__(0); +var Events = __webpack_require__(64); + +/** + * @classdesc + * Web Audio API implementation of the sound. + * + * @class WebAudioSound + * @extends Phaser.Sound.BaseSound + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Sound.WebAudioSoundManager} 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. + */ +var WebAudioSound = new Class({ + + Extends: BaseSound, + + initialize: + + function WebAudioSound (manager, key, config) + { + if (config === undefined) { config = {}; } + + /** + * Audio buffer containing decoded data of the audio asset to be played. + * + * @name Phaser.Sound.WebAudioSound#audioBuffer + * @type {AudioBuffer} + * @private + * @since 3.0.0 + */ + this.audioBuffer = manager.game.cache.audio.get(key); + + if (!this.audioBuffer) + { + throw new Error('There is no audio asset with key "' + key + '" in the audio cache'); + } + + /** + * A reference to an audio source node used for playing back audio from + * audio data stored in Phaser.Sound.WebAudioSound#audioBuffer. + * + * @name Phaser.Sound.WebAudioSound#source + * @type {AudioBufferSourceNode} + * @private + * @default null + * @since 3.0.0 + */ + this.source = null; + + /** + * A reference to a second audio source used for gapless looped playback. + * + * @name Phaser.Sound.WebAudioSound#loopSource + * @type {AudioBufferSourceNode} + * @private + * @default null + * @since 3.0.0 + */ + this.loopSource = null; + + /** + * Gain node responsible for controlling this sound's muting. + * + * @name Phaser.Sound.WebAudioSound#muteNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.muteNode = manager.context.createGain(); + + /** + * Gain node responsible for controlling this sound's volume. + * + * @name Phaser.Sound.WebAudioSound#volumeNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.volumeNode = manager.context.createGain(); + + /** + * The time at which the sound should have started playback from the beginning. + * Based on BaseAudioContext.currentTime value. + * + * @name Phaser.Sound.WebAudioSound#playTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.playTime = 0; + + /** + * The time at which the sound source should have actually started playback. + * Based on BaseAudioContext.currentTime value. + * + * @name Phaser.Sound.WebAudioSound#startTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.startTime = 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} + * @private + * @default 0 + * @since 3.0.0 + */ + this.loopTime = 0; + + /** + * An array where we keep track of all rate updates during playback. + * Array of object types: { time: number, rate: number } + * + * @name Phaser.Sound.WebAudioSound#rateUpdates + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this.rateUpdates = []; + + /** + * Used for keeping track when sound source playback has ended + * so its state can be updated accordingly. + * + * @name Phaser.Sound.WebAudioSound#hasEnded + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this.hasEnded = false; + + /** + * Used for keeping track when sound source has looped + * so its state can be updated accordingly. + * + * @name Phaser.Sound.WebAudioSound#hasLooped + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this.hasLooped = false; + + this.muteNode.connect(this.volumeNode); + + this.volumeNode.connect(manager.destination); + + this.duration = this.audioBuffer.duration; + + this.totalDuration = this.audioBuffer.duration; + + BaseSound.call(this, manager, key, config); + }, + + /** + * Play this sound, or a marked section of it. + * + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * + * @method Phaser.Sound.WebAudioSound#play + * @fires Phaser.Sound.Events#PLAY + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. + * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (markerName, config) + { + if (!BaseSound.prototype.play.call(this, markerName, config)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + this.stopAndRemoveBufferSource(); + this.createAndStartBufferSource(); + + this.emit(Events.PLAY, this); + + return true; + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound.WebAudioSound#pause + * @fires Phaser.Sound.Events#PAUSE + * @since 3.0.0 + * + * @return {boolean} Whether the sound was paused successfully. + */ + pause: function () + { + if (this.manager.context.currentTime < this.startTime) + { + return false; + } + + if (!BaseSound.prototype.pause.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = true \/\/\/ + this.currentConfig.seek = this.getCurrentTime(); // Equivalent to setting paused time + this.stopAndRemoveBufferSource(); + + this.emit(Events.PAUSE, this); + + return true; + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound.WebAudioSound#resume + * @fires Phaser.Sound.Events#RESUME + * @since 3.0.0 + * + * @return {boolean} Whether the sound was resumed successfully. + */ + resume: function () + { + if (this.manager.context.currentTime < this.startTime) + { + return false; + } + + if (!BaseSound.prototype.resume.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + this.createAndStartBufferSource(); + + this.emit(Events.RESUME, this); + + return true; + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound.WebAudioSound#stop + * @fires Phaser.Sound.Events#STOP + * @since 3.0.0 + * + * @return {boolean} Whether the sound was stopped successfully. + */ + stop: function () + { + if (!BaseSound.prototype.stop.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = false \/\/\/ + this.stopAndRemoveBufferSource(); + + this.emit(Events.STOP, this); + + return true; + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#createAndStartBufferSource + * @private + * @since 3.0.0 + */ + createAndStartBufferSource: function () + { + var seek = this.currentConfig.seek; + var delay = this.currentConfig.delay; + var when = this.manager.context.currentTime + delay; + var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; + var duration = this.duration - seek; + + this.playTime = when - seek; + this.startTime = when; + this.source = this.createBufferSource(); + + this.applyConfig(); + + this.source.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); + + this.resetConfig(); + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#createAndStartLoopBufferSource + * @private + * @since 3.0.0 + */ + createAndStartLoopBufferSource: function () + { + var when = this.getLoopTime(); + var offset = this.currentMarker ? this.currentMarker.start : 0; + var duration = this.duration; + + this.loopTime = when; + this.loopSource = this.createBufferSource(); + this.loopSource.playbackRate.setValueAtTime(this.totalRate, 0); + this.loopSource.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#createBufferSource + * @private + * @since 3.0.0 + * + * @return {AudioBufferSourceNode} + */ + createBufferSource: function () + { + var _this = this; + var source = this.manager.context.createBufferSource(); + + source.buffer = this.audioBuffer; + + source.connect(this.muteNode); + + source.onended = function (ev) + { + if (ev.target === _this.source) + { + // sound ended + if (_this.currentConfig.loop) + { + _this.hasLooped = true; + } + else + { + _this.hasEnded = true; + } + } + + // else was stopped + }; + + return source; + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#stopAndRemoveBufferSource + * @private + * @since 3.0.0 + */ + stopAndRemoveBufferSource: function () + { + if (this.source) + { + this.source.stop(); + this.source.disconnect(); + this.source = null; + } + + this.playTime = 0; + this.startTime = 0; + + this.stopAndRemoveLoopBufferSource(); + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#stopAndRemoveLoopBufferSource + * @private + * @since 3.0.0 + */ + stopAndRemoveLoopBufferSource: function () + { + if (this.loopSource) + { + this.loopSource.stop(); + this.loopSource.disconnect(); + this.loopSource = null; + } + + this.loopTime = 0; + }, + + /** + * Method used internally for applying config values to some of the sound properties. + * + * @method Phaser.Sound.WebAudioSound#applyConfig + * @protected + * @since 3.0.0 + */ + applyConfig: function () + { + this.rateUpdates.length = 0; + + this.rateUpdates.push({ + time: 0, + rate: 1 + }); + + BaseSound.prototype.applyConfig.call(this); + }, + + /** + * Update method called automatically by sound manager on every game step. + * + * @method Phaser.Sound.WebAudioSound#update + * @fires Phaser.Sound.Events#COMPLETE + * @fires Phaser.Sound.Events#LOOPED + * @protected + * @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 elapsed since the last frame. + */ + // eslint-disable-next-line no-unused-vars + update: function (time, delta) + { + if (this.hasEnded) + { + this.hasEnded = false; + + BaseSound.prototype.stop.call(this); + + this.stopAndRemoveBufferSource(); + + this.emit(Events.COMPLETE, this); + } + else if (this.hasLooped) + { + this.hasLooped = false; + this.source = this.loopSource; + this.loopSource = null; + this.playTime = this.startTime = this.loopTime; + this.rateUpdates.length = 0; + + this.rateUpdates.push({ + time: 0, + rate: this.totalRate + }); + + this.createAndStartLoopBufferSource(); + + this.emit(Events.LOOPED, this); + } + }, + + /** + * Calls Phaser.Sound.BaseSound#destroy method + * and cleans up all Web Audio API related stuff. + * + * @method Phaser.Sound.WebAudioSound#destroy + * @since 3.0.0 + */ + destroy: function () + { + BaseSound.prototype.destroy.call(this); + + this.audioBuffer = null; + this.stopAndRemoveBufferSource(); + this.muteNode.disconnect(); + this.muteNode = null; + this.volumeNode.disconnect(); + this.volumeNode = null; + this.rateUpdates.length = 0; + this.rateUpdates = null; + }, + + /** + * Method used internally to calculate total playback rate of the sound. + * + * @method Phaser.Sound.WebAudioSound#calculateRate + * @protected + * @since 3.0.0 + */ + calculateRate: function () + { + BaseSound.prototype.calculateRate.call(this); + + var now = this.manager.context.currentTime; + + if (this.source && typeof this.totalRate === 'number') + { + this.source.playbackRate.setValueAtTime(this.totalRate, now); + } + + if (this.isPlaying) + { + this.rateUpdates.push({ + time: Math.max(this.startTime, now) - this.playTime, + rate: this.totalRate + }); + + if (this.loopSource) + { + this.stopAndRemoveLoopBufferSource(); + this.createAndStartLoopBufferSource(); + } + } + }, + + /** + * Method used internally for calculating current playback time of a playing sound. + * + * @method Phaser.Sound.WebAudioSound#getCurrentTime + * @private + * @since 3.0.0 + */ + getCurrentTime: function () + { + var currentTime = 0; + + for (var i = 0; i < this.rateUpdates.length; i++) + { + var nextTime = 0; + + if (i < this.rateUpdates.length - 1) + { + nextTime = this.rateUpdates[i + 1].time; + } + else + { + nextTime = this.manager.context.currentTime - this.playTime; + } + + currentTime += (nextTime - this.rateUpdates[i].time) * this.rateUpdates[i].rate; + } + + return currentTime; + }, + + /** + * Method used internally for calculating the time + * at witch the loop source should start playing. + * + * @method Phaser.Sound.WebAudioSound#getLoopTime + * @private + * @since 3.0.0 + */ + getLoopTime: function () + { + var lastRateUpdateCurrentTime = 0; + + for (var i = 0; i < this.rateUpdates.length - 1; i++) + { + lastRateUpdateCurrentTime += (this.rateUpdates[i + 1].time - this.rateUpdates[i].time) * this.rateUpdates[i].rate; + } + + var lastRateUpdate = this.rateUpdates[this.rateUpdates.length - 1]; + + return this.playTime + lastRateUpdate.time + (this.duration - lastRateUpdateCurrentTime) / lastRateUpdate.rate; + }, + + /** + * Rate at which this Sound will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @name Phaser.Sound.WebAudioSound#rate + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#RATE + * @since 3.0.0 + */ + rate: { + + get: function () + { + return this.currentConfig.rate; + }, + + set: function (value) + { + this.currentConfig.rate = value; + + this.calculateRate(); + + this.emit(Events.RATE, this, value); + } + + }, + + /** + * Sets the playback rate of this Sound. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @method Phaser.Sound.WebAudioSound#setRate + * @fires Phaser.Sound.Events#RATE + * @since 3.3.0 + * + * @param {number} value - The playback rate at of this Sound. + * + * @return {Phaser.Sound.WebAudioSound} This Sound. + */ + setRate: function (value) + { + this.rate = value; + + return this; + }, + + /** + * 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 + */ + detune: { + + get: function () + { + return this.currentConfig.detune; + }, + + set: function (value) + { + this.currentConfig.detune = value; + + this.calculateRate(); + + this.emit(Events.DETUNE, this, value); + } + + }, + + /** + * 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 {Phaser.Sound.WebAudioSound} This Sound. + */ + setDetune: function (value) + { + this.detune = value; + + return this; + }, + + /** + * Boolean indicating whether the sound is muted or not. + * Gets or sets the muted state of this sound. + * + * @name Phaser.Sound.WebAudioSound#mute + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return (this.muteNode.gain.value === 0); + }, + + set: function (value) + { + this.currentConfig.mute = value; + this.muteNode.gain.setValueAtTime(value ? 0 : 1, 0); + + this.emit(Events.MUTE, this, value); + } + + }, + + /** + * Sets the muted state of this Sound. + * + * @method Phaser.Sound.WebAudioSound#setMute + * @fires Phaser.Sound.Events#MUTE + * @since 3.4.0 + * + * @param {boolean} value - `true` to mute this sound, `false` to unmute it. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). + * + * @name Phaser.Sound.WebAudioSound#volume + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this.volumeNode.gain.value; + }, + + set: function (value) + { + this.currentConfig.volume = value; + this.volumeNode.gain.setValueAtTime(value, 0); + + this.emit(Events.VOLUME, this, value); + } + }, + + /** + * Sets the volume of this Sound. + * + * @method Phaser.Sound.WebAudioSound#setVolume + * @fires Phaser.Sound.Events#VOLUME + * @since 3.4.0 + * + * @param {number} value - The volume of the sound. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * Property representing the position of playback for this sound, in seconds. + * Setting it to a specific value moves current playback to that position. + * The value given is clamped to the range 0 to current marker duration. + * Setting seek of a stopped sound has no effect. + * + * @name Phaser.Sound.WebAudioSound#seek + * @type {number} + * @fires Phaser.Sound.Events#SEEK + * @since 3.0.0 + */ + seek: { + + get: function () + { + if (this.isPlaying) + { + if (this.manager.context.currentTime < this.startTime) + { + return this.startTime - this.playTime; + } + + return this.getCurrentTime(); + } + else if (this.isPaused) + { + return this.currentConfig.seek; + } + else + { + return 0; + } + }, + + set: function (value) + { + if (this.manager.context.currentTime < this.startTime) + { + return; + } + + if (this.isPlaying || this.isPaused) + { + value = Math.min(Math.max(0, value), this.duration); + + this.currentConfig.seek = value; + + if (this.isPlaying) + { + this.stopAndRemoveBufferSource(); + this.createAndStartBufferSource(); + } + + this.emit(Events.SEEK, this, value); + } + } + }, + + /** + * Seeks to a specific point in this sound. + * + * @method Phaser.Sound.WebAudioSound#setSeek + * @fires Phaser.Sound.Events#SEEK + * @since 3.4.0 + * + * @param {number} value - The point in the sound to seek to. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setSeek: function (value) + { + this.seek = value; + + return this; + }, + + /** + * Flag indicating whether or not the sound or current sound marker will loop. + * + * @name Phaser.Sound.WebAudioSound#loop + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#LOOP + * @since 3.0.0 + */ + loop: { + + get: function () + { + return this.currentConfig.loop; + }, + + set: function (value) + { + this.currentConfig.loop = value; + + if (this.isPlaying) + { + this.stopAndRemoveLoopBufferSource(); + + if (value) + { + this.createAndStartLoopBufferSource(); + } + } + + this.emit(Events.LOOP, this, value); + } + }, + + /** + * Sets the loop state of this Sound. + * + * @method Phaser.Sound.WebAudioSound#setLoop + * @fires Phaser.Sound.Events#LOOP + * @since 3.4.0 + * + * @param {boolean} value - `true` to loop this sound, `false` to not loop it. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setLoop: function (value) + { + this.loop = value; + + return this; + } + +}); + +module.exports = WebAudioSound; + + +/***/ }), +/* 412 */ +/***/ (function(module, exports, __webpack_require__) { + +/* eslint no-console: 0 */ + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var AdInstance = __webpack_require__(937); +var Class = __webpack_require__(0); +var DataManager = __webpack_require__(101); +var EventEmitter = __webpack_require__(9); +var Leaderboard = __webpack_require__(938); +var Product = __webpack_require__(940); +var Purchase = __webpack_require__(941); + +/** + * @classdesc + * The Facebook Instant Games Plugin for Phaser 3 provides a seamless bridge between Phaser + * and the Facebook Instant Games API version 6.2. + * + * You can access this plugin via the `facebook` property in a Scene, i.e: + * + * ```javascript + * this.facebook.getPlatform(); + * ``` + * + * If this is unavailable please check to make sure you're using a build of Phaser that has + * this plugin within it. You can quickly check this by looking at the dev tools console + * header - the Phaser version number will have `-FB` after it if this plugin is loaded. + * + * If you are building your own version of Phaser then use this Webpack DefinePlugin flag: + * + * `"typeof PLUGIN_FBINSTANT": JSON.stringify(true)` + * + * You will find that every Instant Games API method has a mapping in this plugin. + * For a full list please consult either the plugin documentation, or the 6.2 SDK documentation + * at https://developers.facebook.com/docs/games/instant-games/sdk/fbinstant6.2 + * + * Internally this plugin uses its own Data Manager to handle seamless user data updates and provides + * handy functions for advertisement displaying, opening share dialogs, logging, leaderboards, purchase API requests, + * loader integration and more. + * + * To get started with Facebook Instant Games you will need to register on Facebook and create a new Instant + * Game app that has its own unique app ID. Facebook have also provided a dashboard interface for setting up + * various features for your game, including leaderboards, ad requests and the payments API. There are lots + * of guides on the Facebook Developers portal to assist with setting these + * various systems up: https://developers.facebook.com/docs/games/instant-games/guides + * + * For more details follow the Quick Start guide here: https://developers.facebook.com/docs/games/instant-games + * + * @class FacebookInstantGamesPlugin + * @memberOf Phaser + * @constructor + * @extends Phaser.Events.EventEmitter + * @since 3.13.0 + * + * @param {Phaser.Game} game - A reference to the Phaser.Game instance. + */ +var FacebookInstantGamesPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function FacebookInstantGamesPlugin (game) + { + EventEmitter.call(this); + + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.FacebookInstantGamesPlugin#game + * @type {Phaser.Game} + * @readOnly + * @since 3.13.0 + */ + this.game = game; + + /** + * A Data Manager instance. + * It allows you to store, query and retrieve any key/value data you may need to store. + * It's also used internally by the plugin to store FBIG API data. + * + * @name Phaser.FacebookInstantGamesPlugin#data + * @type {Phaser.Data.DataManager} + * @since 3.13.0 + */ + this.data = new DataManager(this); + + this.on('setdata', this.setDataHandler, this); + this.on('changedata', this.changeDataHandler, this); + + /** + * Has the Facebook Instant Games API loaded yet? + * This is set automatically during the boot process. + * + * @name Phaser.FacebookInstantGamesPlugin#hasLoaded + * @type {boolean} + * @since 3.13.0 + */ + this.hasLoaded = false; + + /** + * Is the Data Manager currently locked? + * + * @name Phaser.FacebookInstantGamesPlugin#dataLocked + * @type {boolean} + * @since 3.13.0 + */ + this.dataLocked = false; + + /** + * A list of the Facebook Instant Games APIs that are available, + * based on the given platform, context and user privacy settings. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#supportedAPIs + * @type {string[]} + * @since 3.13.0 + */ + this.supportedAPIs = []; + + /** + * Holds the entry point that the game was launched from. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#entryPoint + * @type {string} + * @since 3.13.0 + */ + this.entryPoint = ''; + + /** + * An object that contains any data associated with the entry point that the game was launched from. + * The contents of the object are developer-defined, and can occur from entry points on different platforms. + * This will return null for older mobile clients, as well as when there is no data associated with the particular entry point. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#entryPointData + * @type {any} + * @since 3.13.0 + */ + this.entryPointData = null; + + /** + * A unique identifier for the current game context. This represents a specific context + * that the game is being played in (for example, a particular messenger conversation or facebook post). + * The identifier will be null if game is being played in a solo context. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#contextID + * @type {string} + * @since 3.13.0 + */ + this.contextID = null; + + /** + * The current context in which your game is running. This can be either `null` or + * one of: + * + * `POST` - The game is running inside of a Facebook post. + * `THREAD` - The game is running inside a Facebook Messenger thread. + * `GROUP` - The game is running inside a Facebook Group. + * `SOLO` - This is the default context, the player is the only participant. + * + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#contextType + * @type {?string} + * @since 3.13.0 + */ + this.contextType = null; + + /** + * The current locale. + * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. + * Use this to determine what languages the current game should be localized with. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#locale + * @type {?string} + * @since 3.13.0 + */ + this.locale = null; + + /** + * The platform on which the game is currently running, i.e. `IOS`. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#platform + * @type {?string} + * @since 3.13.0 + */ + this.platform = null; + + /** + * The string representation of the Facebook Instant Games SDK version being used. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#version + * @type {?string} + * @since 3.13.0 + */ + this.version = null; + + /** + * Holds the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. + * This value is populated automatically during boot if the API is supported. + * + * @name Phaser.FacebookInstantGamesPlugin#playerID + * @type {?string} + * @since 3.13.0 + */ + this.playerID = null; + + /** + * The player's localized display name. + * This value is populated automatically during boot if the API is supported. + * + * @name Phaser.FacebookInstantGamesPlugin#playerName + * @type {?string} + * @since 3.13.0 + */ + this.playerName = null; + + /** + * A url to the player's public profile photo. The photo will always be a square, and with dimensions + * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. + * It's recommended to always scale the image to a desired size before rendering. + * This value is populated automatically during boot if the API is supported. + * + * @name Phaser.FacebookInstantGamesPlugin#playerPhotoURL + * @type {?string} + * @since 3.13.0 + */ + this.playerPhotoURL = null; + + /** + * Whether a player can subscribe to the game bot or not. + * + * @name Phaser.FacebookInstantGamesPlugin#playerCanSubscribeBot + * @type {boolean} + * @since 3.13.0 + */ + this.playerCanSubscribeBot = false; + + /** + * Does the current platform and context allow for use of the payments API? + * Currently this is only available on Facebook.com and Android 6+. + * + * @name Phaser.FacebookInstantGamesPlugin#paymentsReady + * @type {boolean} + * @since 3.13.0 + */ + this.paymentsReady = false; + + /** + * The set of products that are registered to the game. + * + * @name Phaser.FacebookInstantGamesPlugin#catalog + * @type {Product[]} + * @since 3.13.0 + */ + this.catalog = []; + + /** + * Contains all of the player's unconsumed purchases. + * The game must fetch the current player's purchases as soon as the client indicates that it is ready to perform payments-related operations, + * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. + * + * @name Phaser.FacebookInstantGamesPlugin#purchases + * @type {Purchase[]} + * @since 3.13.0 + */ + this.purchases = []; + + /** + * Contains all of the leaderboard data, as populated by the `getLeaderboard()` method. + * + * @name Phaser.FacebookInstantGamesPlugin#leaderboards + * @type {Phaser.FacebookInstantGamesLeaderboard[]} + * @since 3.13.0 + */ + this.leaderboards = {}; + + /** + * Contains AdInstance objects, as created by the `preloadAds()` method. + * + * @name Phaser.FacebookInstantGamesPlugin#ads + * @type {AdInstance[]} + * @since 3.13.0 + */ + this.ads = []; + }, + + /** + * Internal set data handler. + * + * @method Phaser.FacebookInstantGamesPlugin#setDataHandler + * @private + * @since 3.13.0 + * + * @param {Phaser.Data.DataManager} parent - The parent Data Manager instance. + * @param {string} key - The key of the data. + * @param {any} value - The value of the data. + */ + setDataHandler: function (parent, key, value) + { + if (this.dataLocked) + { + return; + } + + var data = {}; + + data[key] = value; + + var _this = this; + + FBInstant.player.setDataAsync(data).then(function () + { + _this.emit('savedata', data); + }); + }, + + /** + * Internal change data handler. + * + * @method Phaser.FacebookInstantGamesPlugin#changeDataHandler + * @private + * @since 3.13.0 + * + * @param {Phaser.Data.DataManager} parent - The parent Data Manager instance. + * @param {string} key - The key of the data. + * @param {any} value - The value of the data. + */ + changeDataHandler: function (parent, key, value) + { + if (this.dataLocked) + { + return; + } + + var data = {}; + + data[key] = value; + + var _this = this; + + FBInstant.player.setDataAsync(data).then(function () + { + _this.emit('savedata', data); + }); + }, + + /** + * Call this method from your `Scene.preload` in order to sync the load progress + * of the Phaser Loader with the Facebook Instant Games loader display, i.e.: + * + * ```javascript + * this.facebook.showLoadProgress(this); + * this.facebook.once('startgame', this.startGame, this); + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#showLoadProgress + * @since 3.13.0 + * + * @param {Phaser.Scene} scene - The Scene for which you want to show loader progress for. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + showLoadProgress: function (scene) + { + scene.load.on('progress', function (value) + { + if (!this.hasLoaded) + { + FBInstant.setLoadingProgress(value * 100); + } + + }, this); + + scene.load.on('complete', function () + { + if (!this.hasLoaded) + { + this.hasLoaded = true; + + FBInstant.startGameAsync().then(this.gameStartedHandler.bind(this)); + } + + }, this); + + return this; + }, + + /** + * This method is called automatically when the game has finished loading, + * if you used the `showLoadProgress` method. If your game doesn't need to + * load any assets, or you're managing the load yourself, then call this + * method directly to start the API running. + * + * When the API has finished starting this plugin will emit a `startgame` event + * which you should listen for. + * + * @method Phaser.FacebookInstantGamesPlugin#gameStarted + * @since 3.13.0 + */ + gameStarted: function () + { + if (!this.hasLoaded) + { + this.hasLoaded = true; + + FBInstant.startGameAsync().then(this.gameStartedHandler.bind(this)); + } + else + { + this.gameStartedHandler(); + } + }, + + /** + * The internal gameStarted handler. + * + * @method Phaser.FacebookInstantGamesPlugin#gameStartedHandler + * @private + * @since 3.20.0 + */ + gameStartedHandler: function () + { + var APIs = FBInstant.getSupportedAPIs(); + + var supported = {}; + + var dotToUpper = function (match) + { + return match[1].toUpperCase(); + }; + + APIs.forEach(function (api) + { + api = api.replace(/\../g, dotToUpper); + + supported[api] = true; + }); + + this.supportedAPIs = supported; + + this.getID(); + this.getType(); + this.getLocale(); + this.getPlatform(); + this.getSDKVersion(); + + this.getPlayerID(); + this.getPlayerName(); + this.getPlayerPhotoURL(); + + var _this = this; + + FBInstant.onPause(function () + { + _this.emit('pause'); + }); + + FBInstant.getEntryPointAsync().then(function (entrypoint) + { + _this.entryPoint = entrypoint; + _this.entryPointData = FBInstant.getEntryPointData(); + + _this.emit('startgame'); + + }).catch(function (e) + { + console.warn(e); + }); + + // Facebook.com and Android 6 only + if (this.supportedAPIs.paymentsPurchaseAsync) + { + FBInstant.payments.onReady(function () + { + _this.paymentsReady = true; + + }).catch(function (e) + { + console.warn(e); + }); + } + }, + + /** + * Checks to see if a given Facebook Instant Games API is available or not. + * + * @method Phaser.FacebookInstantGamesPlugin#checkAPI + * @since 3.13.0 + * + * @param {string} api - The API to check for, i.e. `player.getID`. + * + * @return {boolean} `true` if the API is supported, otherwise `false`. + */ + checkAPI: function (api) + { + if (!this.supportedAPIs[api]) + { + return false; + } + else + { + return true; + } + }, + + /** + * Returns the unique identifier for the current game context. This represents a specific context + * that the game is being played in (for example, a particular messenger conversation or facebook post). + * The identifier will be null if game is being played in a solo context. + * + * It is only populated if `contextGetID` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getID + * @since 3.13.0 + * + * @return {string} The context ID. + */ + getID: function () + { + if (!this.contextID && this.supportedAPIs.contextGetID) + { + this.contextID = FBInstant.context.getID(); + } + + return this.contextID; + }, + + /** + * Returns the current context in which your game is running. This can be either `null` or one of: + * + * `POST` - The game is running inside of a Facebook post. + * `THREAD` - The game is running inside a Facebook Messenger thread. + * `GROUP` - The game is running inside a Facebook Group. + * `SOLO` - This is the default context, the player is the only participant. + * + * It is only populated if `contextGetType` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getType + * @since 3.13.0 + * + * @return {?string} The context type. + */ + getType: function () + { + if (!this.contextType && this.supportedAPIs.contextGetType) + { + this.contextType = FBInstant.context.getType(); + } + + return this.contextType; + }, + + /** + * Returns the current locale. + * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. + * Use this to determine what languages the current game should be localized with. + * It is only populated if `getLocale` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getLocale + * @since 3.13.0 + * + * @return {?string} The current locale. + */ + getLocale: function () + { + if (!this.locale && this.supportedAPIs.getLocale) + { + this.locale = FBInstant.getLocale(); + } + + return this.locale; + }, + + /** + * Returns the platform on which the game is currently running, i.e. `IOS`. + * It is only populated if `getPlatform` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlatform + * @since 3.13.0 + * + * @return {?string} The current platform. + */ + getPlatform: function () + { + if (!this.platform && this.supportedAPIs.getPlatform) + { + this.platform = FBInstant.getPlatform(); + } + + return this.platform; + }, + + /** + * Returns the string representation of the Facebook Instant Games SDK version being used. + * It is only populated if `getSDKVersion` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getSDKVersion + * @since 3.13.0 + * + * @return {?string} The sdk version. + */ + getSDKVersion: function () + { + if (!this.version && this.supportedAPIs.getSDKVersion) + { + this.version = FBInstant.getSDKVersion(); + } + + return this.version; + }, + + /** + * Returns the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. + * It is only populated if `playerGetID` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayerID + * @since 3.13.0 + * + * @return {?string} The player ID. + */ + getPlayerID: function () + { + if (!this.playerID && this.supportedAPIs.playerGetID) + { + this.playerID = FBInstant.player.getID(); + } + + return this.playerID; + }, + + /** + * Returns the player's localized display name. + * It is only populated if `playerGetName` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayerName + * @since 3.13.0 + * + * @return {?string} The player's localized display name. + */ + getPlayerName: function () + { + if (!this.playerName && this.supportedAPIs.playerGetName) + { + this.playerName = FBInstant.player.getName(); + } + + return this.playerName; + }, + + /** + * Returns the url to the player's public profile photo. The photo will always be a square, and with dimensions + * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. + * It's recommended to always scale the image to a desired size before rendering. + * It is only populated if `playerGetPhoto` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayerPhotoURL + * @since 3.13.0 + * + * @return {?string} The player's photo url. + */ + getPlayerPhotoURL: function () + { + if (!this.playerPhotoURL && this.supportedAPIs.playerGetPhoto) + { + this.playerPhotoURL = FBInstant.player.getPhoto(); + } + + return this.playerPhotoURL; + }, + + /** + * Load the player's photo and store it in the Texture Manager, ready for use in-game. + * + * This method works by using a Scene Loader instance and then asking the Loader to + * retrieve the image. + * + * When complete the plugin will emit a `photocomplete` event, along with the key of the photo. + * + * ```javascript + * this.facebook.loadPlayerPhoto(this, 'player').once('photocomplete', function (key) { + * this.add.image(x, y, 'player'); + * }, this); + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#loadPlayerPhoto + * @since 3.13.0 + * + * @param {Phaser.Scene} scene - The Scene that will be responsible for loading this photo. + * @param {string} key - The key to use when storing the photo in the Texture Manager. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + loadPlayerPhoto: function (scene, key) + { + if (this.playerPhotoURL) + { + scene.load.setCORS('anonymous'); + + scene.load.image(key, this.playerPhotoURL); + + scene.load.once('filecomplete-image-' + key, function () + { + this.emit('photocomplete', key); + + }, this); + + scene.load.start(); + } + + return this; + }, + + /** + * Checks if the current player can subscribe to the game bot. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they can subscribe, the `playerCanSubscribeBot` property is set to `true` + * and this plugin will emit the `cansubscribebot` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `cansubscribebotfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#canSubscribeBot + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + canSubscribeBot: function () + { + if (this.supportedAPIs.playerCanSubscribeBotAsync) + { + var _this = this; + + FBInstant.player.canSubscribeBotAsync().then(function () + { + _this.playerCanSubscribeBot = true; + + _this.emit('cansubscribebot'); + + }).catch(function (e) + { + _this.emit('cansubscribebotfail', e); + }); + } + else + { + this.emit('cansubscribebotfail'); + } + + return this; + }, + + /** + * Subscribes the current player to the game bot. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `subscribebot` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `subscribebotfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#subscribeBot + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + subscribeBot: function () + { + if (this.playerCanSubscribeBot) + { + var _this = this; + + FBInstant.player.subscribeBotAsync().then(function () + { + _this.emit('subscribebot'); + + }).catch(function (e) + { + _this.emit('subscribebotfail', e); + }); + } + else + { + this.emit('subscribebotfail'); + } + + return this; + }, + + /** + * Gets the associated data from the player based on the given key, or array of keys. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the data is set into this plugins Data Manager and the + * `getdata` event will be emitted. + * + * @method Phaser.FacebookInstantGamesPlugin#getData + * @since 3.13.0 + * + * @param {(string|string[])} keys - The key/s of the data to retrieve. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getData: function (keys) + { + if (!this.checkAPI('playerGetDataAsync')) + { + return this; + } + + if (!Array.isArray(keys)) + { + keys = [ keys ]; + } + + var _this = this; + + FBInstant.player.getDataAsync(keys).then(function (data) + { + _this.dataLocked = true; + + for (var key in data) + { + _this.data.set(key, data[key]); + } + + _this.dataLocked = false; + + _this.emit('getdata', data); + }); + + return this; + }, + + /** + * Set data to be saved to the designated cloud storage of the current player. The game can store up to 1MB of data for each unique player. + * + * The data save is requested in an async call, so the result isn't available immediately. + * + * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this + * method directly if you need to replace the data object directly. + * + * When the APIs `setDataAsync` call resolves it will emit the `savedata` event from this plugin. If the call fails for some + * reason it will emit `savedatafail` instead. + * + * The call resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was valid and + * has been scheduled to be saved. It also guarantees that all values that were set are now available in `getData`. + * + * @method Phaser.FacebookInstantGamesPlugin#saveData + * @since 3.13.0 + * + * @param {object} data - An object containing a set of key-value pairs that should be persisted to cloud storage. + * The object must contain only serializable values - any non-serializable values will cause the entire modification to be rejected. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + saveData: function (data) + { + if (!this.checkAPI('playerSetDataAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.setDataAsync(data).then(function () + { + _this.emit('savedata', data); + + }).catch(function (e) + { + _this.emit('savedatafail', e); + }); + + return this; + }, + + /** + * Immediately flushes any changes to the player data to the designated cloud storage. + * This function is expensive, and should primarily be used for critical changes where persistence needs to be immediate + * and known by the game. Non-critical changes should rely on the platform to persist them in the background. + * NOTE: Calls to player.setDataAsync will be rejected while this function's result is pending. + * + * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this + * method directly if you need to flush the data directly. + * + * When the APIs `flushDataAsync` call resolves it will emit the `flushdata` event from this plugin. If the call fails for some + * reason it will emit `flushdatafail` instead. + * + * @method Phaser.FacebookInstantGamesPlugin#flushData + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + flushData: function () + { + if (!this.checkAPI('playerFlushDataAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.flushDataAsync().then(function () + { + _this.emit('flushdata'); + + }).catch(function (e) + { + _this.emit('flushdatafail', e); + }); + + return this; + }, + + /** + * Retrieve stats from the designated cloud storage of the current player. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `getstats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `getstatsfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getStats + * @since 3.13.0 + * + * @param {string[]} [keys] - An optional array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getStats: function (keys) + { + if (!this.checkAPI('playerGetStatsAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.getStatsAsync(keys).then(function (data) + { + _this.emit('getstats', data); + + }).catch(function (e) + { + _this.emit('getstatsfail', e); + }); + + return this; + }, + + /** + * Save the stats of the current player to the designated cloud storage. + * + * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, + * all other data types will be ignored. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `savestats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `savestatsfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#saveStats + * @since 3.13.0 + * + * @param {object} data - An object containing a set of key-value pairs that should be persisted to cloud storage as stats. Note that only numerical values are stored. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + saveStats: function (data) + { + if (!this.checkAPI('playerSetStatsAsync')) + { + return this; + } + + var output = {}; + + for (var key in data) + { + if (typeof data[key] === 'number') + { + output[key] = data[key]; + } + } + + var _this = this; + + FBInstant.player.setStatsAsync(output).then(function () + { + _this.emit('savestats', output); + + }).catch(function (e) + { + _this.emit('savestatsfail', e); + }); + + return this; + }, + + /** + * Increment the stats of the current player and save them to the designated cloud storage. + * + * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, + * all other data types will be ignored. + * + * The data object provided for this call should contain offsets for how much to modify the stats by: + * + * ```javascript + * this.facebook.incStats({ + * level: 1, + * zombiesSlain: 17, + * rank: -1 + * }); + * ``` + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `incstats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `incstatsfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#incStats + * @since 3.13.0 + * + * @param {object} data - An object containing a set of key-value pairs indicating how much to increment each stat in cloud storage. Note that only numerical values are processed. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + incStats: function (data) + { + if (!this.checkAPI('playerIncrementStatsAsync')) + { + return this; + } + + var output = {}; + + for (var key in data) + { + if (typeof data[key] === 'number') + { + output[key] = data[key]; + } + } + + var _this = this; + + FBInstant.player.incrementStatsAsync(output).then(function (stats) + { + _this.emit('incstats', stats); + + }).catch(function (e) + { + _this.emit('incstatsfail', e); + }); + + return this; + }, + + /** + * Sets the data associated with the individual gameplay session for the current context. + * + * This function should be called whenever the game would like to update the current session data. + * + * This session data may be used to populate a variety of payloads, such as game play webhooks. + * + * @method Phaser.FacebookInstantGamesPlugin#saveSession + * @since 3.13.0 + * + * @param {object} data - An arbitrary data object, which must be less than or equal to 1000 characters when stringified. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + saveSession: function (data) + { + if (!this.checkAPI('setSessionData')) + { + return this; + } + + var test = JSON.stringify(data); + + if (test.length <= 1000) + { + FBInstant.setSessionData(data); + } + else + { + console.warn('Session data too long. Max 1000 chars.'); + } + + return this; + }, + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openShare + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openShare: function (text, key, frame, sessionData) + { + return this._share('SHARE', text, key, frame, sessionData); + }, + + /** + * This invokes a dialog to let the user invite a friend to play this game, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openInvite + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openInvite: function (text, key, frame, sessionData) + { + return this._share('INVITE', text, key, frame, sessionData); + }, + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openRequest + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openRequest: function (text, key, frame, sessionData) + { + return this._share('REQUEST', text, key, frame, sessionData); + }, + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openChallenge + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openChallenge: function (text, key, frame, sessionData) + { + return this._share('CHALLENGE', text, key, frame, sessionData); + }, + + /** + * Internal share handler. + * + * @method Phaser.FacebookInstantGamesPlugin#_share + * @private + * @since 3.13.0 + * + * @param {string} intent - ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share. + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + _share: function (intent, text, key, frame, sessionData) + { + if (!this.checkAPI('shareAsync')) + { + return this; + } + + if (sessionData === undefined) { sessionData = {}; } + + if (key) + { + var imageData = this.game.textures.getBase64(key, frame); + } + + // intent ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share. + // image string A base64 encoded image to be shared. + // text string A text message to be shared. + // data Object? A blob of data to attach to the share. All game sessions launched from the share will be able to access this blob through FBInstant.getEntryPointData(). + + var payload = { + intent: intent, + image: imageData, + text: text, + data: sessionData + }; + + var _this = this; + + FBInstant.shareAsync(payload).then(function () + { + _this.emit('resume'); + }); + + return this; + }, + + /** + * This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. + * If one of the bounds is null only the other bound will be checked against. + * It will always return the original result for the first call made in a context in a given game play session. + * Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset. + * + * @method Phaser.FacebookInstantGamesPlugin#isSizeBetween + * @since 3.13.0 + * + * @param {integer} [min] - The minimum bound of the context size query. + * @param {integer} [max] - The maximum bound of the context size query. + * + * @return {object} The Context Size Response object in the format: `{answer: boolean, minSize: number?, maxSize: number?}`. + */ + isSizeBetween: function (min, max) + { + if (!this.checkAPI('contextIsSizeBetween')) + { + return this; + } + + return FBInstant.context.isSizeBetween(min, max); + }, + + /** + * Request a switch into a specific context. If the player does not have permission to enter that context, + * or if the player does not provide permission for the game to enter that context, this will emit a `switchfail` event. + * + * Otherwise, the plugin will emit the `switch` event when the game has switched into the specified context. + * + * @method Phaser.FacebookInstantGamesPlugin#switchContext + * @since 3.13.0 + * + * @param {string} contextID - The ID of the desired context. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + switchContext: function (contextID) + { + if (!this.checkAPI('contextSwitchAsync')) + { + return this; + } + + if (contextID !== this.contextID) + { + var _this = this; + + FBInstant.context.switchAsync(contextID).then(function () + { + _this.contextID = FBInstant.context.getID(); + + _this.emit('switch', _this.contextID); + + }).catch(function (e) + { + _this.emit('switchfail', e); + }); + } + + return this; + }, + + /** + * A filter that may be applied to a Context Choose operation. + * + * 'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been played in before. + * 'INCLUDE_EXISTING_CHALLENGES' - Include the "Existing Challenges" section, which surfaces actively played-in contexts that the player is a part of. + * 'NEW_PLAYERS_ONLY' - In sections containing individuals, prefer people who have not played the game. + * + * @typedef {string} ContextFilter + */ + + /** + * A configuration object that may be applied to a Context Choose operation. + * + * @typedef {object} ChooseContextConfig + * @property {ContextFilter[]} [filters] - The set of filters to apply to the context suggestions: 'NEW_CONTEXT_ONLY', 'INCLUDE_EXISTING_CHALLENGES' or 'NEW_PLAYERS_ONLY'. + * @property {number} [maxSize] - The maximum number of participants that a suggested context should ideally have. + * @property {number} [minSize] - The minimum number of participants that a suggested context should ideally have. + */ + + /** + * Opens a context selection dialog for the player. If the player selects an available context, + * the client will attempt to switch into that context, and emit the `choose` event if successful. + * Otherwise, if the player exits the menu or the client fails to switch into the new context, the `choosefail` event will be emitted. + * + * @method Phaser.FacebookInstantGamesPlugin#chooseContext + * @since 3.13.0 + * + * @param {ChooseContextConfig} [options] - An object specifying conditions on the contexts that should be offered. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + chooseContext: function (options) + { + if (!this.checkAPI('contextChooseAsync')) + { + return this; + } + + var _this = this; + + FBInstant.context.chooseAsync(options).then(function () + { + _this.contextID = FBInstant.context.getID(); + _this.emit('choose', _this.contextID); + + }).catch(function (e) + { + _this.emit('choosefail', e); + }); + + return this; + }, + + /** + * Attempts to create or switch into a context between a specified player and the current player. + * This plugin will emit the `create` event once the context switch is completed. + * If the API call fails, such as if the player listed is not a Connected Player of the current player or if the + * player does not provide permission to enter the new context, then the plugin will emit a 'createfail' event. + * + * @method Phaser.FacebookInstantGamesPlugin#createContext + * @since 3.13.0 + * + * @param {string} playerID - ID of the player. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + createContext: function (playerID) + { + if (!this.checkAPI('contextCreateAsync')) + { + return this; + } + + var _this = this; + + FBInstant.context.createAsync(playerID).then(function () + { + _this.contextID = FBInstant.context.getID(); + _this.emit('create', _this.contextID); + + }).catch(function (e) + { + _this.emit('createfail', e); + }); + + return this; + }, + + /** + * Fetches an array of ConnectedPlayer objects containing information about active players + * (people who played the game in the last 90 days) that are connected to the current player. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `players` event along + * with the player data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `playersfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayers + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getPlayers: function () + { + if (!this.checkAPI('playerGetConnectedPlayersAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.getConnectedPlayersAsync().then(function (players) + { + _this.emit('players', players); + + }).catch(function (e) + { + _this.emit('playersfail', e); + }); + + return this; + }, + + /** + * Fetches the game's product catalog. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `getcatalog` event along + * with the catalog data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `getcatalogfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getCatalog + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getCatalog: function () + { + if (!this.paymentsReady) + { + return this; + } + + var _this = this; + var catalog = this.catalog; + + FBInstant.payments.getCatalogAsync().then(function (data) + { + catalog = []; + + data.forEach(function (item) + { + catalog.push(Product(item)); + }); + + _this.emit('getcatalog', catalog); + + }).catch(function (e) + { + _this.emit('getcatalogfail', e); + }); + + return this; + }, + + /** + * Fetches a single Product from the game's product catalog. + * + * The product catalog must have been populated using `getCatalog` prior to calling this method. + * + * Use this to look-up product details based on a purchase list. + * + * @method Phaser.FacebookInstantGamesPlugin#getProduct + * @since 3.17.0 + * + * @param {string} productID - The Product ID of the item to get from the catalog. + * + * @return {?Product} The Product from the catalog, or `null` if it couldn't be found or the catalog isn't populated. + */ + getProduct: function (productID) + { + for (var i = 0; i < this.catalog.length; i++) + { + if (this.catalog[i].productID === productID) + { + return this.catalog[i]; + } + } + + return null; + }, + + /** + * Begins the purchase flow for a specific product. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `purchase` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `purchasefail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#purchase + * @since 3.13.0 + * + * @param {string} productID - The identifier of the product to purchase. + * @param {string} [developerPayload] - An optional developer-specified payload, to be included in the returned purchase's signed request. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + purchase: function (productID, developerPayload) + { + if (!this.paymentsReady) + { + return this; + } + + var config = {productID: productID}; + + if (developerPayload) + { + config.developerPayload = developerPayload; + } + + var _this = this; + + FBInstant.payments.purchaseAsync(config).then(function (data) + { + var purchase = Purchase(data); + + _this.emit('purchase', purchase); + + }).catch(function (e) + { + _this.emit('purchasefail', e); + }); + + return this; + }, + + /** + * Fetches all of the player's unconsumed purchases. The game must fetch the current player's purchases + * as soon as the client indicates that it is ready to perform payments-related operations, + * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `getpurchases` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `getpurchasesfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getPurchases + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getPurchases: function () + { + if (!this.paymentsReady) + { + return this; + } + + var _this = this; + var purchases = this.purchases; + + FBInstant.payments.getPurchasesAsync().then(function (data) + { + purchases = []; + + data.forEach(function (item) + { + purchases.push(Purchase(item)); + }); + + _this.emit('getpurchases', purchases); + + }).catch(function (e) + { + _this.emit('getpurchasesfail', e); + }); + + return this; + }, + + /** + * Consumes a specific purchase belonging to the current player. Before provisioning a product's effects to the player, + * the game should request the consumption of the purchased product. Once the purchase is successfully consumed, + * the game should immediately provide the player with the effects of their purchase. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `consumepurchase` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `consumepurchasefail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#consumePurchase + * @since 3.17.0 + * + * @param {string} purchaseToken - The purchase token of the purchase that should be consumed. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + consumePurchase: function (purchaseToken) + { + if (!this.paymentsReady) + { + return this; + } + + var _this = this; + + FBInstant.payments.consumePurchaseAsync(purchaseToken).then(function () + { + _this.emit('consumepurchase', purchaseToken); + + }).catch(function (e) + { + _this.emit('consumepurchasefail', e); + }); + + return this; + }, + + /** + * Informs Facebook of a custom update that occurred in the game. + * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. + * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * The `text` parameter is an update payload with the following structure: + * + * ``` + * text: { + * default: 'X just invaded Y\'s village!', + * localizations: { + * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + + * '\u0642\u0631\u064A\u0629 Y!', + * en_US: 'X just invaded Y\'s village!', + * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', + * } + * } + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#update + * @since 3.13.0 + * + * @param {string} cta - The call to action text. + * @param {object} text - The text object. + * @param {string} key - The key of the texture to use as the share image. + * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {string} template - The update template key. + * @param {object} updateData - The update data object payload. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + update: function (cta, text, key, frame, template, updateData) + { + return this._update('CUSTOM', cta, text, key, frame, template, updateData); + }, + + /** + * Informs Facebook of a leaderboard update that occurred in the game. + * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. + * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * The `text` parameter is an update payload with the following structure: + * + * ``` + * text: { + * default: 'X just invaded Y\'s village!', + * localizations: { + * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + + * '\u0642\u0631\u064A\u0629 Y!', + * en_US: 'X just invaded Y\'s village!', + * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', + * } + * } + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#updateLeaderboard + * @since 3.13.0 + * + * @param {string} cta - The call to action text. + * @param {object} text - The text object. + * @param {string} key - The key of the texture to use as the share image. + * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {string} template - The update template key. + * @param {object} updateData - The update data object payload. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + updateLeaderboard: function (cta, text, key, frame, template, updateData) + { + return this._update('LEADERBOARD', cta, text, key, frame, template, updateData); + }, + + /** + * Internal update handler. + * + * @method Phaser.FacebookInstantGamesPlugin#_update + * @private + * @since 3.13.0 + * + * @param {string} action - The update action. + * @param {string} cta - The call to action text. + * @param {object} text - The text object. + * @param {string} key - The key of the texture to use as the share image. + * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {string} template - The update template key. + * @param {object} updateData - The update data object payload. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + _update: function (action, cta, text, key, frame, template, updateData) + { + if (!this.checkAPI('shareAsync')) + { + return this; + } + + if (cta === undefined) { cta = ''; } + + if (typeof text === 'string') + { + text = {default: text}; + } + + if (updateData === undefined) { updateData = {}; } + + if (key) + { + var imageData = this.game.textures.getBase64(key, frame); + } + + var payload = { + action: action, + cta: cta, + image: imageData, + text: text, + template: template, + data: updateData, + strategy: 'IMMEDIATE', + notification: 'NO_PUSH' + }; + + var _this = this; + + FBInstant.updateAsync(payload).then(function () + { + _this.emit('update'); + + }).catch(function (e) + { + _this.emit('updatefail', e); + }); + + return this; + }, + + /** + * Request that the client switch to a different Instant Game. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If the game switches successfully this plugin will emit the `switchgame` event and the client will load the new game. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `switchgamefail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#switchGame + * @since 3.13.0 + * + * @param {string} appID - The Application ID of the Instant Game to switch to. The application must be an Instant Game, and must belong to the same business as the current game. + * @param {object} [data] - An optional data payload. This will be set as the entrypoint data for the game being switched to. Must be less than or equal to 1000 characters when stringified. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + switchGame: function (appID, data) + { + if (!this.checkAPI('switchGameAsync')) + { + return this; + } + + if (data) + { + var test = JSON.stringify(data); + + if (test.length > 1000) + { + console.warn('Switch Game data too long. Max 1000 chars.'); + return this; + } + } + + var _this = this; + + FBInstant.switchGameAsync(appID, data).then(function () + { + _this.emit('switchgame', appID); + + }).catch(function (e) + { + _this.emit('switchgamefail', e); + }); + + return this; + }, + + /** + * Prompts the user to create a shortcut to the game if they are eligible to. + * Can only be called once per session. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If the user choose to create a shortcut this plugin will emit the `shortcutcreated` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `shortcutcreatedfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#createShortcut + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + createShortcut: function () + { + var _this = this; + + FBInstant.canCreateShortcutAsync().then(function (canCreateShortcut) + { + if (canCreateShortcut) + { + FBInstant.createShortcutAsync().then(function () + { + _this.emit('shortcutcreated'); + + }).catch(function (e) + { + _this.emit('shortcutfailed', e); + }); + } + }); + + return this; + }, + + /** + * Quits the game. + * + * @method Phaser.FacebookInstantGamesPlugin#quit + * @since 3.13.0 + */ + quit: function () + { + FBInstant.quit(); + }, + + /** + * Log an app event with FB Analytics. + * + * See https://developers.facebook.com/docs/javascript/reference/v2.8#app_events for more details about FB Analytics. + * + * @method Phaser.FacebookInstantGamesPlugin#log + * @since 3.13.0 + * + * @param {string} name - Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. + * @param {number} [value] - An optional numeric value that FB Analytics can calculate a sum with. + * @param {object} [params] - An optional object that can contain up to 25 key-value pairs to be logged with the event. Keys must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. Values must be less than 100 characters in length. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + log: function (name, value, params) + { + if (!this.checkAPI('logEvent')) + { + return this; + } + + if (params === undefined) { params = {}; } + + if (name.length >= 2 && name.length <= 40) + { + FBInstant.logEvent(name, parseFloat(value), params); + } + + return this; + }, + + /** + * Attempt to create an instance of an interstitial ad. + * + * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showAd()`. + * + * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. + * + * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. + * + * @method Phaser.FacebookInstantGamesPlugin#preloadAds + * @since 3.13.0 + * + * @param {(string|string[])} placementID - The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + preloadAds: function (placementID) + { + if (!this.checkAPI('getInterstitialAdAsync')) + { + return this; + } + + if (!Array.isArray(placementID)) + { + placementID = [ placementID ]; + } + + var i; + var _this = this; + + var total = 0; + + for (i = 0; i < this.ads.length; i++) + { + if (!this.ads[i].shown) + { + total++; + } + } + + if (total + placementID.length >= 3) + { + console.warn('Too many AdInstances. Show an ad before loading more'); + return this; + } + + for (i = 0; i < placementID.length; i++) + { + var id = placementID[i]; + var data; + + FBInstant.getInterstitialAdAsync(id).then(function (interstitial) + { + data = interstitial; + + return interstitial.loadAsync(); + + }).then(function () + { + var ad = AdInstance(id, data, false); + + _this.ads.push(ad); + + _this.emit('adloaded', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NO_FILL') + { + _this.emit('adsnofill', id); + } + else if (e.code === 'ADS_FREQUENT_LOAD') + { + _this.emit('adsfrequentload', id); + } + else + { + console.warn(e); + } + }); + } + + return this; + }, + + /** + * Attempt to create an instance of an rewarded video ad. + * + * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showVideo()`. + * + * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. + * + * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. + * + * @method Phaser.FacebookInstantGamesPlugin#preloadVideoAds + * @since 3.13.0 + * + * @param {(string|string[])} placementID - The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + preloadVideoAds: function (placementID) + { + if (!this.checkAPI('getRewardedVideoAsync')) + { + return this; + } + + if (!Array.isArray(placementID)) + { + placementID = [ placementID ]; + } + + var i; + var _this = this; + + var total = 0; + + for (i = 0; i < this.ads.length; i++) + { + if (!this.ads[i].shown) + { + total++; + } + } + + if (total + placementID.length >= 3) + { + console.warn('Too many AdInstances. Show an ad before loading more'); + return this; + } + + for (i = 0; i < placementID.length; i++) + { + var id = placementID[i]; + var data; + + FBInstant.getRewardedVideoAsync(id).then(function (reward) + { + data = reward; + + return reward.loadAsync(); + + }).then(function () + { + var ad = AdInstance(id, data, true); + + _this.ads.push(ad); + + _this.emit('adloaded', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NO_FILL') + { + _this.emit('adsnofill', id); + } + else if (e.code === 'ADS_FREQUENT_LOAD') + { + _this.emit('adsfrequentload', id); + } + else + { + console.warn(e); + } + }); + } + + return this; + }, + + /** + * Displays a previously loaded interstitial ad. + * + * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. + * + * If the ad cannot be displayed, it will emit the `adsnotloaded` event. + * + * @method Phaser.FacebookInstantGamesPlugin#showAd + * @since 3.13.0 + * + * @param {string} placementID - The ad placement ID to display. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + showAd: function (placementID) + { + var _this = this; + + for (var i = 0; i < this.ads.length; i++) + { + var ad = this.ads[i]; + + if (ad.placementID === placementID && !ad.shown) + { + ad.instance.showAsync().then(function () + { + ad.shown = true; + + _this.emit('adfinished', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NOT_LOADED') + { + _this.emit('adsnotloaded', ad); + } + else if (e.code === 'RATE_LIMITED') + { + _this.emit('adratelimited', ad); + } + + _this.emit('adshowerror', e, ad); + }); + + break; + } + } + + return this; + }, + + /** + * Displays a previously loaded interstitial video ad. + * + * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. + * + * If the ad cannot be displayed, it will emit the `adsnotloaded` event. + * + * @method Phaser.FacebookInstantGamesPlugin#showVideo + * @since 3.13.0 + * + * @param {string} placementID - The ad placement ID to display. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + showVideo: function (placementID) + { + var _this = this; + + for (var i = 0; i < this.ads.length; i++) + { + var ad = this.ads[i]; + + if (ad.placementID === placementID && ad.video && !ad.shown) + { + ad.instance.showAsync().then(function () + { + ad.shown = true; + + _this.emit('adfinished', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NOT_LOADED') + { + _this.emit('adsnotloaded', ad); + } + else if (e.code === 'RATE_LIMITED') + { + _this.emit('adratelimited', ad); + } + + _this.emit('adshowerror', e, ad); + }); + + break; + } + } + + return this; + }, + + /** + * Attempts to match the current player with other users looking for people to play with. + * If successful, a new Messenger group thread will be created containing the matched players and the player will + * be context switched to that thread. This plugin will also dispatch the `matchplayer` event, containing the new context ID and Type. + * + * The default minimum and maximum number of players in one matched thread are 2 and 20 respectively, + * depending on how many players are trying to get matched around the same time. + * + * The values can be changed in `fbapp-config.json`. See the Bundle Config documentation for documentation about `fbapp-config.json`. + * + * @method Phaser.FacebookInstantGamesPlugin#matchPlayer + * @since 3.13.0 + * + * @param {string} [matchTag] - Optional extra information about the player used to group them with similar players. Players will only be grouped with other players with exactly the same tag. The tag must only include letters, numbers, and underscores and be 100 characters or less in length. + * @param {boolean} [switchImmediately=false] - Optional extra parameter that specifies whether the player should be immediately switched to the new context when a match is found. By default this will be false which will mean the player needs explicitly press play after being matched to switch to the new context. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + matchPlayer: function (matchTag, switchImmediately) + { + if (matchTag === undefined) { matchTag = null; } + if (switchImmediately === undefined) { switchImmediately = false; } + + if (!this.checkAPI('matchPlayerAsync')) + { + return this; + } + + var _this = this; + + FBInstant.matchPlayerAsync(matchTag, switchImmediately).then(function () + { + _this.getID(); + _this.getType(); + + _this.emit('matchplayer', _this.contextID, _this.contextType); + }); + + return this; + }, + + /** + * Fetch a specific leaderboard belonging to this Instant Game. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `getleaderboard` event will be emitted along with a Leaderboard object instance. + * + * @method Phaser.FacebookInstantGamesPlugin#getLeaderboard + * @since 3.13.0 + * + * @param {string} name - The name of the leaderboard. Each leaderboard for an Instant Game must have its own distinct name. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getLeaderboard: function (name) + { + if (!this.checkAPI('getLeaderboardAsync')) + { + return this; + } + + var _this = this; + + FBInstant.getLeaderboardAsync(name).then(function (data) + { + var leaderboard = new Leaderboard(_this, data); + + _this.leaderboards[name] = leaderboard; + + _this.emit('getleaderboard', leaderboard); + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + }, + + /** + * Quits the Facebook API and then destroys this plugin. + * + * @method Phaser.FacebookInstantGamesPlugin#destroy + * @since 3.13.0 + */ + destroy: function () + { + FBInstant.quit(); + + this.data.destroy(); + + this.removeAllListeners(); + + this.catalog = []; + this.purchases = []; + this.leaderboards = []; + this.ads = []; + + this.game = null; + } + +}); + +module.exports = FacebookInstantGamesPlugin; + + +/***/ }), +/* 413 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Transposes the elements of the given matrix (array of arrays). + * + * The transpose of a matrix is a new matrix whose rows are the columns of the original. + * + * @function Phaser.Utils.Array.Matrix.TransposeMatrix + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [array,$return] + * + * @param {T[][]} [array] - The array matrix to transpose. + * + * @return {T[][]} A new array matrix which is a transposed version of the given array. + */ +var TransposeMatrix = function (array) +{ + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; +}; + +module.exports = TransposeMatrix; + + +/***/ }), +/* 414 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function swap (arr, i, j) +{ + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +/** + * @ignore + */ +function defaultCompare (a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * 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 sort. + * @param {integer} k - The k-th element index. + * @param {integer} [left=0] - The index of the left part of the range. + * @param {integer} [right] - The index of the right part of the range. + * @param {function} [compare] - An optional comparison function. Is passed two elements and should return 0, 1 or -1. + */ +var QuickSelect = function (arr, k, left, right, compare) +{ + if (left === undefined) { left = 0; } + if (right === undefined) { right = arr.length - 1; } + if (compare === undefined) { compare = defaultCompare; } + + while (right > left) + { + if (right - left > 600) + { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + + QuickSelect(arr, k, newLeft, newRight, compare); + } + + var t = arr[k]; + var i = left; + var j = right; + + swap(arr, left, k); + + if (compare(arr[right], t) > 0) + { + swap(arr, left, right); + } + + while (i < j) + { + swap(arr, i, j); + + i++; + j--; + + while (compare(arr[i], t) < 0) + { + i++; + } + + while (compare(arr[j], t) > 0) + { + j--; + } + } + + if (compare(arr[left], t) === 0) + { + swap(arr, left, j); + } + else + { + j++; + swap(arr, j, right); + } + + if (j <= k) + { + left = j + 1; + } + + if (k <= j) + { + right = j - 1; + } + } +}; + +module.exports = QuickSelect; + + +/***/ }), +/* 415 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = __webpack_require__(5); +var Shuffle = __webpack_require__(122); + +var BuildChunk = function (a, b, qty) +{ + var out = []; + + for (var aIndex = 0; aIndex < a.length; aIndex++) + { + for (var bIndex = 0; bIndex < b.length; bIndex++) + { + for (var i = 0; i < qty; i++) + { + out.push({ a: a[aIndex], b: b[bIndex] }); + } + } + } + + return out; +}; + +/** + * 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) = + * Maybe if max is set then repeat goes to -1 automatically? + * 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. Can contain: repeat, random, randomB, yoyo, max, qty. + * + * @return {array} An array of arranged elements. + */ +var Range = function (a, b, options) +{ + var max = GetValue(options, 'max', 0); + var qty = GetValue(options, 'qty', 1); + var random = GetValue(options, 'random', false); + var randomB = GetValue(options, 'randomB', false); + var repeat = GetValue(options, 'repeat', 0); + var yoyo = GetValue(options, 'yoyo', false); + + var out = []; + + if (randomB) + { + Shuffle(b); + } + + // Endless repeat, so limit by max + if (repeat === -1) + { + if (max === 0) + { + repeat = 0; + } + else + { + // Work out how many repeats we need + var total = (a.length * b.length) * qty; + + if (yoyo) + { + total *= 2; + } + + repeat = Math.ceil(max / total); + } + } + + for (var i = 0; i <= repeat; i++) + { + var chunk = BuildChunk(a, b, qty); + + if (random) + { + Shuffle(chunk); + } + + out = out.concat(chunk); + + if (yoyo) + { + chunk.reverse(); + + out = out.concat(chunk); + } + } + + if (max) + { + out.splice(max); + } + + return out; +}; + +module.exports = Range; + + +/***/ }), +/* 416 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetAdvancedValue = __webpack_require__(15); + +/** + * Adds an Animation component to a Sprite and populates it based on the given config. + * + * @function Phaser.GameObjects.BuildGameObjectAnimation + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Sprite} sprite - The sprite to add an Animation component to. + * @param {object} config - The animation config. + * + * @return {Phaser.GameObjects.Sprite} The updated Sprite. + */ +var BuildGameObjectAnimation = function (sprite, config) +{ + var animConfig = GetAdvancedValue(config, 'anims', null); + + if (animConfig === null) + { + return sprite; + } + + if (typeof animConfig === 'string') + { + // { anims: 'key' } + sprite.anims.play(animConfig); + } + else if (typeof animConfig === 'object') + { + // { anims: { + // key: string + // startFrame: [string|integer] + // delay: [float] + // repeat: [integer] + // repeatDelay: [float] + // yoyo: [boolean] + // play: [boolean] + // delayedPlay: [boolean] + // } + // } + + var anims = sprite.anims; + + var key = GetAdvancedValue(animConfig, 'key', undefined); + var startFrame = GetAdvancedValue(animConfig, 'startFrame', undefined); + + var delay = GetAdvancedValue(animConfig, 'delay', 0); + var repeat = GetAdvancedValue(animConfig, 'repeat', 0); + var repeatDelay = GetAdvancedValue(animConfig, 'repeatDelay', 0); + var yoyo = GetAdvancedValue(animConfig, 'yoyo', false); + + var play = GetAdvancedValue(animConfig, 'play', false); + var delayedPlay = GetAdvancedValue(animConfig, 'delayedPlay', 0); + + anims.setDelay(delay); + anims.setRepeat(repeat); + anims.setRepeatDelay(repeatDelay); + anims.setYoyo(yoyo); + + if (play) + { + anims.play(key, startFrame); + } + else if (delayedPlay > 0) + { + anims.delayedPlay(delayedPlay, key, startFrame); + } + else + { + anims.load(key); + } + } + + return sprite; +}; + +module.exports = BuildGameObjectAnimation; + + +/***/ }), +/* 417 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +/** + * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. + * + * @function Phaser.Geom.Rectangle.Union + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to use. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to use. + * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the union in. + * + * @return {Phaser.Geom.Rectangle} The modified `out` Rectangle, or a new Rectangle if none was provided. + */ +var Union = function (rectA, rectB, out) +{ + if (out === undefined) { out = new Rectangle(); } + + // Cache vars so we can use one of the input rects as the output rect + var x = Math.min(rectA.x, rectB.x); + var y = Math.min(rectA.y, rectB.y); + var w = Math.max(rectA.right, rectB.right) - x; + var h = Math.max(rectA.bottom, rectB.bottom) - y; + + return out.setTo(x, y, w, h); +}; + +module.exports = Union; + + +/***/ }), +/* 418 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var DOMElementRender = __webpack_require__(987); +var GameObject = __webpack_require__(14); +var IsPlainObject = __webpack_require__(7); +var RemoveFromDOM = __webpack_require__(191); +var SCENE_EVENTS = __webpack_require__(18); +var Vector4 = __webpack_require__(352); + +/** + * @classdesc + * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. + * + * In order for DOM Elements to display you have to enable them by adding the following to your game + * configuration object: + * + * ```javascript + * dom { + * createContainer: true + * } + * ``` + * + * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top + * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of + * settings within the Scale Manager, the dom container is resized accordingly. + * + * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing + * Element that you wish to be placed under the control of Phaser. For example: + * + * ```javascript + * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); + * ``` + * + * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in + * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, + * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + * + * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control + * alignment and positioning of the elements next to regular game content. + * + * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the + * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other + * methods available in this class to help construct your elements. + * + * Once the element has been created you can then control it like you would any other Game Object. You can set its + * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped + * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that + * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have + * a DOM Element, then a Sprite, then another DOM Element behind it. + * + * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event + * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas + * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you + * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. + * + * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. + * + * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert + * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. + * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and + * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top + * of your game, and should treat it accordingly. + * + * @class DOMElement + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.17.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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=0] - The horizontal position of this DOM Element in the world. + * @param {number} [y=0] - The vertical position of this DOM Element in the world. + * @param {(Element|string)} [element] - An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. + * @param {(string|any)} [style] - If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. + * @param {string} [innerText] - If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. + */ +var DOMElement = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.Depth, + Components.Origin, + Components.ScrollFactor, + Components.Transform, + Components.Visible, + DOMElementRender + ], + + initialize: + + function DOMElement (scene, x, y, element, style, innerText) + { + GameObject.call(this, scene, 'DOMElement'); + + /** + * A reference to the parent DOM Container that the Game instance created when it started. + * + * @name Phaser.GameObjects.DOMElement#parent + * @type {Element} + * @since 3.17.0 + */ + this.parent = scene.sys.game.domContainer; + + /** + * A reference to the HTML Cache. + * + * @name Phaser.GameObjects.DOMElement#cache + * @type {Phaser.Cache.BaseCache} + * @since 3.17.0 + */ + this.cache = scene.sys.cache.html; + + /** + * The actual DOM Element that this Game Object is bound to. For example, if you've created a `
` + * then this property is a direct reference to that element within the dom. + * + * @name Phaser.GameObjects.DOMElement#node + * @type {Element} + * @since 3.17.0 + */ + this.node; + + /** + * By default a DOM Element will have its transform, display, opacity, zIndex and blend mode properties + * updated when its rendered. If, for some reason, you don't want any of these changed other than the + * CSS transform, then set this flag to `true`. When `true` only the CSS Transform is applied and it's + * up to you to keep track of and set the other properties as required. + * + * This can be handy if, for example, you've a nested DOM Element and you don't want the opacity to be + * picked-up by any of its children. + * + * @name Phaser.GameObjects.DOMElement#transformOnly + * @type {boolean} + * @since 3.17.0 + */ + this.transformOnly = false; + + /** + * 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 + */ + this.skewX = 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 + */ + this.skewY = 0; + + /** + * A Vector4 that contains the 3D rotation of this DOM Element around a fixed axis in 3D space. + * + * All values in the Vector4 are treated as degrees, unless the `rotate3dAngle` property is changed. + * + * 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 + */ + this.rotate3d = new Vector4(); + + /** + * 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 + */ + this.rotate3dAngle = 'deg'; + + /** + * The native (un-scaled) width of this Game Object. + * + * For a DOM Element this property is read-only. + * + * The property `displayWidth` holds the computed bounds of this DOM Element, factoring in scaling. + * + * @name Phaser.GameObjects.DOMElement#width + * @type {number} + * @readonly + * @since 3.17.0 + */ + this.width = 0; + + /** + * The native (un-scaled) height of this Game Object. + * + * For a DOM Element this property is read-only. + * + * The property `displayHeight` holds the computed bounds of this DOM Element, factoring in scaling. + * + * @name Phaser.GameObjects.DOMElement#height + * @type {number} + * @readonly + * @since 3.17.0 + */ + this.height = 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 + */ + this.displayWidth = 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 + */ + this.displayHeight = 0; + + /** + * Internal native event handler. + * + * @name Phaser.GameObjects.DOMElement#handler + * @type {number} + * @private + * @since 3.17.0 + */ + this.handler = this.dispatchNativeEvent.bind(this); + + this.setPosition(x, y); + + if (typeof element === 'string') + { + // hash? + if (element[0] === '#') + { + this.setElement(element.substr(1), style, innerText); + } + else + { + this.createElement(element, style, innerText); + } + } + else if (element) + { + this.setElement(element, style, innerText); + } + + scene.sys.events.on(SCENE_EVENTS.SLEEP, this.handleSceneEvent, this); + scene.sys.events.on(SCENE_EVENTS.WAKE, this.handleSceneEvent, this); + }, + + /** + * Handles a Scene Sleep and Wake event. + * + * @method Phaser.GameObjects.DOMElement#handleSceneEvent + * @private + * @since 3.22.0 + * + * @param {Phaser.Scenes.Systems} sys - The Scene Systems. + */ + handleSceneEvent: function (sys) + { + var node = this.node; + var style = node.style; + + if (node) + { + style.display = (sys.settings.visible) ? 'block' : 'none'; + } + }, + + /** + * 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. + */ + setSkew: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.skewX = x; + this.skewY = y; + + return this; + }, + + /** + * 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. + */ + setPerspective: function (value) + { + this.parent.style.perspective = value + 'px'; + + return this; + }, + + /** + * 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 + */ + perspective: { + + get: function () + { + return parseFloat(this.parent.style.perspective); + }, + + set: function (value) + { + this.parent.style.perspective = value + 'px'; + } + + }, + + /** + * Adds one or more native DOM event listeners onto the underlying Element of this Game Object. + * The event is then dispatched via this Game Objects standard event emitter. + * + * For example: + * + * ```javascript + * var div = this.add.dom(x, y, element); + * + * div.addListener('click'); + * + * div.on('click', handler); + * ``` + * + * @method Phaser.GameObjects.DOMElement#addListener + * @since 3.17.0 + * + * @param {string} events - The DOM event/s to listen for. You can specify multiple events by separating them with spaces. + * + * @return {this} This DOM Element instance. + */ + addListener: function (events) + { + if (this.node) + { + events = events.split(' '); + + for (var i = 0; i < events.length; i++) + { + this.node.addEventListener(events[i], this.handler, false); + } + } + + return this; + }, + + /** + * Removes one or more native DOM event listeners from the underlying Element of this Game Object. + * + * @method Phaser.GameObjects.DOMElement#removeListener + * @since 3.17.0 + * + * @param {string} events - The DOM event/s to stop listening for. You can specify multiple events by separating them with spaces. + * + * @return {this} This DOM Element instance. + */ + removeListener: function (events) + { + if (this.node) + { + events = events.split(' '); + + for (var i = 0; i < events.length; i++) + { + this.node.removeEventListener(events[i], this.handler); + } + } + + return this; + }, + + /** + * Internal event proxy to dispatch native DOM Events via this Game Object. + * + * @method Phaser.GameObjects.DOMElement#dispatchNativeEvent + * @private + * @since 3.17.0 + * + * @param {any} event - The native DOM event. + */ + dispatchNativeEvent: function (event) + { + this.emit(event.type, event); + }, + + /** + * 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 ready 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. + */ + createElement: function (tagName, style, innerText) + { + return this.setElement(document.createElement(tagName), style, innerText); + }, + + /** + * Binds a new DOM Element to this Game Object. 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 on the new element. + * + * The `element` argument you pass to this method can be either a string tagName: + * + * ```javascript + *

Phaser

+ * + * this.add.dom().setElement('heading'); + * ``` + * + * Or a reference to an Element instance: + * + * ```javascript + *

Phaser

+ * + * var h1 = document.getElementById('heading'); + * + * this.add.dom().setElement(h1); + * ``` + * + * 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().setElement(h1, '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().setElement(h1, style, 'Phaser'); + * ``` + * + * @method Phaser.GameObjects.DOMElement#setElement + * @since 3.17.0 + * + * @param {(string|Element)} element - If a string it is passed to `getElementById()`, or it should be a reference to an existing Element. + * @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 ready 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. + */ + setElement: function (element, style, innerText) + { + // Already got an element? Remove it first + this.removeElement(); + + var target; + + if (typeof element === 'string') + { + // hash? + if (element[0] === '#') + { + element = element.substr(1); + } + + target = document.getElementById(element); + } + else if (typeof element === 'object' && element.nodeType === 1) + { + target = element; + } + + if (!target) + { + return this; + } + + this.node = target; + + // style can be empty, a string or a plain object + if (style && IsPlainObject(style)) + { + for (var key in style) + { + target.style[key] = style[key]; + } + } + else if (typeof style === 'string') + { + target.style = style; + } + + // Add / Override the values we need + + target.style.zIndex = '0'; + target.style.display = 'inline'; + target.style.position = 'absolute'; + + // Node handler + + target.phaser = this; + + if (this.parent) + { + this.parent.appendChild(target); + } + + // InnerText + + if (innerText) + { + target.innerText = innerText; + } + + return this.updateSize(); + }, + + /** + * Takes a block of html from the HTML Cache, that has previously been preloaded into the game, and then + * creates a DOM Element from it. The loaded HTML is set as the `innerHTML` property of the created + * element. + * + * Assume the following html is stored in a file called `loginform.html`: + * + * ```html + * + * + * ``` + * + * Which is loaded into your game using the cache key 'login': + * + * ```javascript + * this.load.html('login', 'assets/loginform.html'); + * ``` + * + * You can create a DOM Element from it using the cache key: + * + * ```javascript + * this.add.dom().createFromCache('login'); + * ``` + * + * The optional `elementType` argument controls the container that is created, into which the loaded html is inserted. + * The default is a plain `div` object, but any valid tagName can be given. + * + * 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#createFromCache + * @since 3.17.0 + * + * @param {string} The key of the html cache entry to use for this DOM Element. + * @param {string} [tagName='div'] - The tag name of the element into which all of the loaded html will be inserted. Defaults to a plain div tag. + * + * @return {this} This DOM Element instance. + */ + createFromCache: function (key, tagName) + { + var html = this.cache.get(key); + + if (html) + { + this.createFromHTML(html, tagName); + } + + return this; + }, + + /** + * Takes a string of html and then creates a DOM Element from it. The HTML is set as the `innerHTML` + * property of the created element. + * + * ```javascript + * let form = ` + * + * + * `; + * ``` + * + * You can create a DOM Element from it using the string: + * + * ```javascript + * this.add.dom().createFromHTML(form); + * ``` + * + * The optional `elementType` argument controls the type of container that is created, into which the html is inserted. + * The default is a plain `div` object, but any valid tagName can be given. + * + * 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#createFromHTML + * @since 3.17.0 + * + * @param {string} A string of html to be set as the `innerHTML` property of the created element. + * @param {string} [tagName='div'] - The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag. + * + * @return {this} This DOM Element instance. + */ + createFromHTML: function (html, tagName) + { + if (tagName === undefined) { tagName = 'div'; } + + // Already got an element? Remove it first + this.removeElement(); + + var element = document.createElement(tagName); + + this.node = element; + + element.style.zIndex = '0'; + element.style.display = 'inline'; + element.style.position = 'absolute'; + + // Node handler + + element.phaser = this; + + if (this.parent) + { + this.parent.appendChild(element); + } + + element.innerHTML = html; + + return this.updateSize(); + }, + + /** + * Removes the current DOM Element bound to this Game Object from the DOM entirely and resets the + * `node` property of this Game Object to be `null`. + * + * @method Phaser.GameObjects.DOMElement#removeElement + * @since 3.17.0 + * + * @return {this} This DOM Element instance. + */ + removeElement: function () + { + if (this.node) + { + RemoveFromDOM(this.node); + + this.node = null; + } + + return this; + }, + + /** + * Internal method that calls `getBoundingClientRect` on the `node` and then sets the bounds width + * and height into the `displayWidth` and `displayHeight` properties, and the `clientWidth` and `clientHeight` + * values into the `width` and `height` properties respectively. + * + * This is called automatically whenever a new element is created or set. + * + * @method Phaser.GameObjects.DOMElement#updateSize + * @since 3.17.0 + * + * @return {this} This DOM Element instance. + */ + updateSize: function () + { + var node = this.node; + + var nodeBounds = node.getBoundingClientRect(); + + this.width = node.clientWidth; + this.height = node.clientHeight; + + this.displayWidth = nodeBounds.width || 0; + this.displayHeight = nodeBounds.height || 0; + + return this; + }, + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a property matching the given key and value. It then returns this child + * if found, or `null` if not. + * + * @method Phaser.GameObjects.DOMElement#getChildByProperty + * @since 3.17.0 + * + * @param {string} property - The property to search the children for. + * @param {string} value - The value the property must strictly equal. + * + * @return {?Element} The first matching child DOM Element, or `null` if not found. + */ + getChildByProperty: function (property, value) + { + if (this.node) + { + var children = this.node.querySelectorAll('*'); + + for (var i = 0; i < children.length; i++) + { + if (children[i][property] === value) + { + return children[i]; + } + } + } + + return null; + }, + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a matching id. It then returns this child if found, or `null` if not. + * + * Be aware that class and id names are case-sensitive. + * + * @method Phaser.GameObjects.DOMElement#getChildByID + * @since 3.17.0 + * + * @param {string} id - The id to search the children for. + * + * @return {?Element} The first matching child DOM Element, or `null` if not found. + */ + getChildByID: function (id) + { + return this.getChildByProperty('id', id); + }, + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a matching name. It then returns this child if found, or `null` if not. + * + * Be aware that class and id names are case-sensitive. + * + * @method Phaser.GameObjects.DOMElement#getChildByName + * @since 3.17.0 + * + * @param {string} name - The name to search the children for. + * + * @return {?Element} The first matching child DOM Element, or `null` if not found. + */ + getChildByName: function (name) + { + return this.getChildByProperty('name', name); + }, + + /** + * Sets the `className` property of the DOM Element node and updates the internal sizes. + * + * @method Phaser.GameObjects.DOMElement#setClassName + * @since 3.17.0 + * + * @param {string} className - A string representing the class or space-separated classes of the element. + * + * @return {this} This DOM Element instance. + */ + setClassName: function (className) + { + if (this.node) + { + this.node.className = className; + + this.updateSize(); + } + + return this; + }, + + /** + * Sets the `innerText` property of the DOM Element node and updates the internal sizes. + * + * Note that only certain types of Elements can have `innerText` set on them. + * + * @method Phaser.GameObjects.DOMElement#setText + * @since 3.17.0 + * + * @param {string} text - A DOMString representing the rendered text content of the element. + * + * @return {this} This DOM Element instance. + */ + setText: function (text) + { + if (this.node) + { + this.node.innerText = text; + + this.updateSize(); + } + + return this; + }, + + /** + * Sets the `innerHTML` property of the DOM Element node and updates the internal sizes. + * + * @method Phaser.GameObjects.DOMElement#setHTML + * @since 3.17.0 + * + * @param {string} html - A DOMString of html to be set as the `innerHTML` property of the element. + * + * @return {this} This DOM Element instance. + */ + setHTML: function (html) + { + if (this.node) + { + this.node.innerHTML = html; + + this.updateSize(); + } + + return this; + }, + + /** + * Runs internal update tasks. + * + * @method Phaser.GameObjects.DOMElement#preUpdate + * @private + * @since 3.17.0 + */ + preUpdate: function () + { + var parent = this.parentContainer; + var node = this.node; + + if (node && parent && !parent.willRender()) + { + node.style.display = 'none'; + } + }, + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * + * DOMElements always return `true` as they need to still set values during the render pass, even if not visible. + * + * @method Phaser.GameObjects.DOMElement#willRender + * @since 3.17.0 + * + * @return {boolean} `true` if the Game Object should be rendered, otherwise `false`. + */ + willRender: function () + { + return true; + }, + + /** + * Handles the pre-destroy step for the DOM Element, which removes the underlying node from the DOM. + * + * @method Phaser.GameObjects.DOMElement#preDestroy + * @private + * @since 3.17.0 + */ + preDestroy: function () + { + this.removeElement(); + + this.scene.sys.events.off(SCENE_EVENTS.SLEEP, this.handleSceneEvent, this); + this.scene.sys.events.off(SCENE_EVENTS.WAKE, this.handleSceneEvent, this); + } + +}); + +module.exports = DOMElement; + + +/***/ }), +/* 419 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CSSBlendModes = __webpack_require__(988); +var GameObject = __webpack_require__(14); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.DOMElement#renderWebGL + * @since 3.17.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active renderer. + * @param {Phaser.GameObjects.DOMElement} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DOMElementCSSRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var node = src.node; + var style = node.style; + var settings = src.scene.sys.settings; + + if (!node || !style || !settings.visible || GameObject.RENDER_MASK !== src.renderFlags || (src.cameraFilter !== 0 && (src.cameraFilter & camera.id)) || (src.parentContainer && !src.parentContainer.willRender())) + { + if (node) + { + style.display = 'none'; + } + + return; + } + + var parent = src.parentContainer; + var alpha = camera.alpha * src.alpha; + + if (parent) + { + alpha *= parent.alpha; + } + + var camMatrix = renderer._tempMatrix1; + var srcMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + var dx = 0; + var dy = 0; + + var tx = '0%'; + var ty = '0%'; + + if (parentMatrix) + { + dx = (src.width * src.scaleX) * src.originX; + dy = (src.height * src.scaleY) * src.originY; + + srcMatrix.applyITRS(src.x - dx, src.y - dy, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + srcMatrix.e = src.x - dx; + srcMatrix.f = src.y - dy; + + // Multiply by the src matrix, store result in calcMatrix + camMatrix.multiply(srcMatrix, calcMatrix); + } + else + { + dx = (src.width) * src.originX; + dy = (src.height) * src.originY; + + srcMatrix.applyITRS(src.x - dx, src.y - dy, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + tx = (100 * src.originX) + '%'; + ty = (100 * src.originY) + '%'; + + srcMatrix.e -= camera.scrollX * src.scrollFactorX; + srcMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the src matrix, store result in calcMatrix + camMatrix.multiply(srcMatrix, calcMatrix); + } + + if (!src.transformOnly) + { + style.display = 'block'; + style.opacity = alpha; + style.zIndex = src._depth; + style.pointerEvents = 'auto'; + style.mixBlendMode = CSSBlendModes[src._blendMode]; + } + + // https://developer.mozilla.org/en-US/docs/Web/CSS/transform + + style.transform = + calcMatrix.getCSSMatrix() + + ' skew(' + src.skewX + 'rad, ' + src.skewY + 'rad)' + + ' rotate3d(' + src.rotate3d.x + ',' + src.rotate3d.y + ',' + src.rotate3d.z + ',' + src.rotate3d.w + src.rotate3dAngle + ')'; + + style.transformOrigin = tx + ' ' + ty; +}; + +module.exports = DOMElementCSSRenderer; + + +/***/ }), +/* 420 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var ExternRender = __webpack_require__(992); + +/** + * @classdesc + * An Extern Game Object is a special type of Game Object that allows you to pass + * rendering off to a 3rd party. + * + * When you create an Extern and place it in the display list of a Scene, the renderer will + * process the list as usual. When it finds an Extern it will flush the current batch, + * clear down the pipeline and prepare a transform matrix which your render function can + * take advantage of, if required. + * + * The WebGL context is then left is a 'clean' state, ready for you to bind your own shaders, + * or draw to it, whatever you wish to do. Once you've finished, you should free-up any + * of your resources. The Extern will then rebind the Phaser pipeline and carry on + * rendering the display list. + * + * Although this object has lots of properties such as Alpha, Blend Mode and Tint, none of + * them are used during rendering unless you take advantage of them in your own render code. + * + * @class Extern + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.16.0 + * + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. A Game Object can only belong to one Scene at a time. + */ +var Extern = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.Origin, + Components.ScrollFactor, + Components.Size, + Components.Texture, + Components.Tint, + Components.Transform, + Components.Visible, + ExternRender + ], + + initialize: + + function Extern (scene) + { + GameObject.call(this, scene, 'Extern'); + }, + + preUpdate: function () + { + // override this! + // Arguments: time, delta + }, + + render: function () + { + // override this! + // Arguments: renderer, camera, calcMatrix + } + +}); + +module.exports = Extern; + + +/***/ }), +/* 421 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CircumferencePoint = __webpack_require__(206); +var FromPercent = __webpack_require__(98); +var MATH_CONST = __webpack_require__(13); +var Point = __webpack_require__(4); + +/** + * Returns a Point 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 circle. + * + * @function Phaser.Geom.Ellipse.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} 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 around the ellipse. + * @param {(Phaser.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the ellipse. + */ +var GetPoint = function (ellipse, position, out) +{ + if (out === undefined) { out = new Point(); } + + var angle = FromPercent(position, 0, MATH_CONST.PI2); + + return CircumferencePoint(ellipse, angle, out); +}; + +module.exports = GetPoint; + + +/***/ }), +/* 422 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circumference = __webpack_require__(423); +var CircumferencePoint = __webpack_require__(206); +var FromPercent = __webpack_require__(98); +var MATH_CONST = __webpack_require__(13); + +/** + * Returns an array of Point 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.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the points from. + * @param {integer} 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 {(array|Phaser.Geom.Point[])} [out] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the ellipse. + */ +var GetPoints = function (ellipse, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Circumference(ellipse) / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); + + out.push(CircumferencePoint(ellipse, angle)); + } + + return out; +}; + +module.exports = GetPoints; + + +/***/ }), +/* 423 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the circumference of the given Ellipse. + * + * @function Phaser.Geom.Ellipse.Circumference + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the circumference of. + * + * @return {number} The circumference of th Ellipse. + */ +var Circumference = function (ellipse) +{ + var rx = ellipse.width / 2; + var ry = ellipse.height / 2; + var h = Math.pow((rx - ry), 2) / Math.pow((rx + ry), 2); + + return (Math.PI * (rx + ry)) * (1 + ((3 * h) / (10 + Math.sqrt(4 - (3 * h))))); +}; + +module.exports = Circumference; + + +/***/ }), +/* 424 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Commands = __webpack_require__(205); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Graphics#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Graphics} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + * @param {CanvasRenderingContext2D} [renderTargetCtx] - The target rendering context. + * @param {boolean} allowClip - If `true` then path operations will be used instead of fill operations. + */ +var GraphicsCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) +{ + var commandBuffer = src.commandBuffer; + var commandBufferLength = commandBuffer.length; + + var ctx = renderTargetCtx || renderer.currentContext; + + if (commandBufferLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + return; + } + + var lineAlpha = 1; + var fillAlpha = 1; + var lineColor = 0; + var fillColor = 0; + var lineWidth = 1; + var red = 0; + var green = 0; + var blue = 0; + + // Reset any currently active paths + ctx.beginPath(); + + for (var index = 0; index < commandBufferLength; ++index) + { + var commandID = commandBuffer[index]; + + switch (commandID) + { + case Commands.ARC: + ctx.arc( + commandBuffer[index + 1], + commandBuffer[index + 2], + commandBuffer[index + 3], + commandBuffer[index + 4], + commandBuffer[index + 5], + commandBuffer[index + 6] + ); + + // +7 because overshoot is the 7th value, not used in Canvas + index += 7; + break; + + case Commands.LINE_STYLE: + lineWidth = commandBuffer[index + 1]; + lineColor = commandBuffer[index + 2]; + lineAlpha = commandBuffer[index + 3]; + red = ((lineColor & 0xFF0000) >>> 16); + green = ((lineColor & 0xFF00) >>> 8); + blue = (lineColor & 0xFF); + ctx.strokeStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + lineAlpha + ')'; + ctx.lineWidth = lineWidth; + index += 3; + break; + + case Commands.FILL_STYLE: + fillColor = commandBuffer[index + 1]; + fillAlpha = commandBuffer[index + 2]; + red = ((fillColor & 0xFF0000) >>> 16); + green = ((fillColor & 0xFF00) >>> 8); + blue = (fillColor & 0xFF); + ctx.fillStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + fillAlpha + ')'; + index += 2; + break; + + case Commands.BEGIN_PATH: + ctx.beginPath(); + break; + + case Commands.CLOSE_PATH: + ctx.closePath(); + break; + + case Commands.FILL_PATH: + if (!allowClip) + { + ctx.fill(); + } + break; + + case Commands.STROKE_PATH: + if (!allowClip) + { + ctx.stroke(); + } + break; + + case Commands.FILL_RECT: + if (!allowClip) + { + ctx.fillRect( + commandBuffer[index + 1], + commandBuffer[index + 2], + commandBuffer[index + 3], + commandBuffer[index + 4] + ); + } + else + { + ctx.rect( + commandBuffer[index + 1], + commandBuffer[index + 2], + commandBuffer[index + 3], + commandBuffer[index + 4] + ); + } + index += 4; + break; + + case Commands.FILL_TRIANGLE: + ctx.beginPath(); + ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); + ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); + ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); + ctx.closePath(); + if (!allowClip) + { + ctx.fill(); + } + index += 6; + break; + + case Commands.STROKE_TRIANGLE: + ctx.beginPath(); + ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); + ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); + ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); + ctx.closePath(); + if (!allowClip) + { + ctx.stroke(); + } + index += 6; + break; + + case Commands.LINE_TO: + ctx.lineTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.MOVE_TO: + ctx.moveTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.LINE_FX_TO: + ctx.lineTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 5; + break; + + case Commands.MOVE_FX_TO: + ctx.moveTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 5; + break; + + case Commands.SAVE: + ctx.save(); + break; + + case Commands.RESTORE: + ctx.restore(); + break; + + case Commands.TRANSLATE: + ctx.translate( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.SCALE: + ctx.scale( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.ROTATE: + ctx.rotate( + commandBuffer[index + 1] + ); + index += 1; + break; + + case Commands.GRADIENT_FILL_STYLE: + index += 5; + break; + + case Commands.GRADIENT_LINE_STYLE: + index += 6; + break; + + case Commands.SET_TEXTURE: + index += 2; + break; + } + } + + // Restore the context saved in SetTransform + ctx.restore(); +}; + +module.exports = GraphicsCanvasRenderer; + + +/***/ }), +/* 425 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetFastValue = __webpack_require__(1); + +/** + * @classdesc + * The GravityWell action applies a force on the particle to draw it towards, or repel it from, a single point. + * + * The force applied is inversely proportional to the square of the distance from the particle to the point, in accordance with Newton's law of gravity. + * + * This simulates the effect of gravity over large distances (as between planets, for example). + * + * @class GravityWell + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @param {(number|Phaser.Types.GameObjects.Particles.GravityWellConfig)} [x=0] - The x coordinate of the Gravity Well, in world space. + * @param {number} [y=0] - The y coordinate of the Gravity Well, in world space. + * @param {number} [power=0] - The strength of the gravity force - larger numbers produce a stronger force. + * @param {number} [epsilon=100] - The minimum distance for which the gravity force is calculated. + * @param {number} [gravity=50] - The gravitational force of this Gravity Well. + */ +var GravityWell = new Class({ + + initialize: + + function GravityWell (x, y, power, epsilon, gravity) + { + if (typeof x === 'object') + { + var config = x; + + x = GetFastValue(config, 'x', 0); + y = GetFastValue(config, 'y', 0); + power = GetFastValue(config, 'power', 0); + epsilon = GetFastValue(config, 'epsilon', 100); + gravity = GetFastValue(config, 'gravity', 50); + } + else + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (power === undefined) { power = 0; } + if (epsilon === undefined) { epsilon = 100; } + if (gravity === undefined) { gravity = 50; } + } + + /** + * The x coordinate of the Gravity Well, in world space. + * + * @name Phaser.GameObjects.Particles.GravityWell#x + * @type {number} + * @since 3.0.0 + */ + this.x = x; + + /** + * The y coordinate of the Gravity Well, in world space. + * + * @name Phaser.GameObjects.Particles.GravityWell#y + * @type {number} + * @since 3.0.0 + */ + this.y = y; + + /** + * The active state of the Gravity Well. An inactive Gravity Well will not influence any particles. + * + * @name Phaser.GameObjects.Particles.GravityWell#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * Internal gravity value. + * + * @name Phaser.GameObjects.Particles.GravityWell#_gravity + * @type {number} + * @private + * @since 3.0.0 + */ + this._gravity = gravity; + + /** + * Internal power value. + * + * @name Phaser.GameObjects.Particles.GravityWell#_power + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._power = 0; + + /** + * Internal epsilon value. + * + * @name Phaser.GameObjects.Particles.GravityWell#_epsilon + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._epsilon = 0; + + /** + * The strength of the gravity force - larger numbers produce a stronger force. + * + * @name Phaser.GameObjects.Particles.GravityWell#power + * @type {number} + * @since 3.0.0 + */ + this.power = power; + + /** + * The minimum distance for which the gravity force is calculated. + * + * @name Phaser.GameObjects.Particles.GravityWell#epsilon + * @type {number} + * @since 3.0.0 + */ + this.epsilon = epsilon; + }, + + /** + * Takes a Particle and updates it based on the properties of this Gravity Well. + * + * @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. + */ + update: function (particle, delta) + { + var x = this.x - particle.x; + var y = this.y - particle.y; + var dSq = x * x + y * y; + + if (dSq === 0) + { + return; + } + + var d = Math.sqrt(dSq); + + if (dSq < this._epsilon) + { + dSq = this._epsilon; + } + + var factor = ((this._power * delta) / (dSq * d)) * 100; + + particle.velocityX += x * factor; + particle.velocityY += y * factor; + }, + + epsilon: { + + get: function () + { + return Math.sqrt(this._epsilon); + }, + + set: function (value) + { + this._epsilon = value * value; + } + + }, + + power: { + + get: function () + { + return this._power / this._gravity; + }, + + set: function (value) + { + this._power = value * this._gravity; + } + + }, + + gravity: { + + get: function () + { + return this._gravity; + }, + + set: function (value) + { + var pwr = this.power; + this._gravity = value; + this.power = pwr; + } + + } + +}); + +module.exports = GravityWell; + + +/***/ }), +/* 426 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var DegToRad = __webpack_require__(40); +var DistanceBetween = __webpack_require__(54); + +/** + * @classdesc + * A Particle is a simple Game Object controlled by a Particle Emitter and Manager, and rendered by the Manager. + * It uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. + * + * @class Particle + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter to which this Particle belongs. + */ +var Particle = new Class({ + + initialize: + + function Particle (emitter) + { + /** + * The Emitter to which this Particle belongs. + * + * A Particle can only belong to a single Emitter and is created, updated and destroyed via it. + * + * @name Phaser.GameObjects.Particles.Particle#emitter + * @type {Phaser.GameObjects.Particles.ParticleEmitter} + * @since 3.0.0 + */ + this.emitter = emitter; + + /** + * The texture frame used to render this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#frame + * @type {Phaser.Textures.Frame} + * @default null + * @since 3.0.0 + */ + this.frame = null; + + /** + * The x coordinate of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y coordinate of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The x velocity of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#velocityX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.velocityX = 0; + + /** + * The y velocity of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#velocityY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.velocityY = 0; + + /** + * The x acceleration of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#accelerationX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelerationX = 0; + + /** + * The y acceleration of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#accelerationY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelerationY = 0; + + /** + * The maximum horizontal velocity this Particle can travel at. + * + * @name Phaser.GameObjects.Particles.Particle#maxVelocityX + * @type {number} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityX = 10000; + + /** + * The maximum vertical velocity this Particle can travel at. + * + * @name Phaser.GameObjects.Particles.Particle#maxVelocityY + * @type {number} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityY = 10000; + + /** + * The bounciness, or restitution, of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#bounce + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.bounce = 0; + + /** + * The horizontal scale of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#scaleX + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.scaleX = 1; + + /** + * The vertical scale of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#scaleY + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.scaleY = 1; + + /** + * The alpha value of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#alpha + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.alpha = 1; + + /** + * The angle of this Particle in degrees. + * + * @name Phaser.GameObjects.Particles.Particle#angle + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angle = 0; + + /** + * The angle of this Particle in radians. + * + * @name Phaser.GameObjects.Particles.Particle#rotation + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.rotation = 0; + + /** + * The tint applied to this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#tint + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + this.tint = 0xffffff; + + /** + * The lifespan of this Particle in ms. + * + * @name Phaser.GameObjects.Particles.Particle#life + * @type {number} + * @default 1000 + * @since 3.0.0 + */ + this.life = 1000; + + /** + * The current life of this Particle in ms. + * + * @name Phaser.GameObjects.Particles.Particle#lifeCurrent + * @type {number} + * @default 1000 + * @since 3.0.0 + */ + this.lifeCurrent = 1000; + + /** + * The delay applied to this Particle upon emission, in ms. + * + * @name Phaser.GameObjects.Particles.Particle#delayCurrent + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.delayCurrent = 0; + + /** + * The normalized lifespan T value, where 0 is the start and 1 is the end. + * + * @name Phaser.GameObjects.Particles.Particle#lifeT + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.lifeT = 0; + + /** + * The data used by the ease equation. + * + * @name Phaser.GameObjects.Particles.Particle#data + * @type {object} + * @since 3.0.0 + */ + this.data = { + tint: { min: 0xffffff, max: 0xffffff, current: 0xffffff }, + alpha: { min: 1, max: 1 }, + rotate: { min: 0, max: 0 }, + scaleX: { min: 1, max: 1 }, + scaleY: { min: 1, max: 1 } + }; + }, + + /** + * Checks to see if this Particle is alive and updating. + * + * @method Phaser.GameObjects.Particles.Particle#isAlive + * @since 3.0.0 + * + * @return {boolean} `true` if this Particle is alive and updating, otherwise `false`. + */ + isAlive: function () + { + return (this.lifeCurrent > 0); + }, + + /** + * Resets the position of this particle back to zero. + * + * @method Phaser.GameObjects.Particles.Particle#resetPosition + * @since 3.16.0 + */ + resetPosition: function () + { + this.x = 0; + this.y = 0; + }, + + /** + * Starts this Particle from the given coordinates. + * + * @method Phaser.GameObjects.Particles.Particle#fire + * @since 3.0.0 + * + * @param {number} x - The x coordinate to launch this Particle from. + * @param {number} y - The y coordinate to launch this Particle from. + */ + fire: function (x, y) + { + var emitter = this.emitter; + + this.frame = emitter.getFrame(); + + if (emitter.emitZone) + { + // Updates particle.x and particle.y during this call + emitter.emitZone.getPoint(this); + } + + if (x === undefined) + { + if (emitter.follow) + { + this.x += emitter.follow.x + emitter.followOffset.x; + } + + this.x += emitter.x.onEmit(this, 'x'); + } + else + { + this.x += x; + } + + if (y === undefined) + { + if (emitter.follow) + { + this.y += emitter.follow.y + emitter.followOffset.y; + } + + this.y += emitter.y.onEmit(this, 'y'); + } + else + { + this.y += y; + } + + this.life = emitter.lifespan.onEmit(this, 'lifespan'); + this.lifeCurrent = this.life; + this.lifeT = 0; + + var sx = emitter.speedX.onEmit(this, 'speedX'); + var sy = (emitter.speedY) ? emitter.speedY.onEmit(this, 'speedY') : sx; + + if (emitter.radial) + { + var rad = DegToRad(emitter.angle.onEmit(this, 'angle')); + + this.velocityX = Math.cos(rad) * Math.abs(sx); + this.velocityY = Math.sin(rad) * Math.abs(sy); + } + else if (emitter.moveTo) + { + var mx = emitter.moveToX.onEmit(this, 'moveToX'); + var my = (emitter.moveToY) ? emitter.moveToY.onEmit(this, 'moveToY') : mx; + + var angle = Math.atan2(my - this.y, mx - this.x); + + var speed = DistanceBetween(this.x, this.y, mx, my) / (this.life / 1000); + + // We know how many pixels we need to move, but how fast? + // var speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + + this.velocityX = Math.cos(angle) * speed; + this.velocityY = Math.sin(angle) * speed; + } + else + { + this.velocityX = sx; + this.velocityY = sy; + } + + if (emitter.acceleration) + { + this.accelerationX = emitter.accelerationX.onEmit(this, 'accelerationX'); + this.accelerationY = emitter.accelerationY.onEmit(this, 'accelerationY'); + } + + this.maxVelocityX = emitter.maxVelocityX.onEmit(this, 'maxVelocityX'); + this.maxVelocityY = emitter.maxVelocityY.onEmit(this, 'maxVelocityY'); + + this.delayCurrent = emitter.delay.onEmit(this, 'delay'); + + this.scaleX = emitter.scaleX.onEmit(this, 'scaleX'); + this.scaleY = (emitter.scaleY) ? emitter.scaleY.onEmit(this, 'scaleY') : this.scaleX; + + this.angle = emitter.rotate.onEmit(this, 'rotate'); + this.rotation = DegToRad(this.angle); + + this.bounce = emitter.bounce.onEmit(this, 'bounce'); + + this.alpha = emitter.alpha.onEmit(this, 'alpha'); + + this.tint = emitter.tint.onEmit(this, 'tint'); + }, + + /** + * An internal method that calculates the velocity of the Particle. + * + * @method Phaser.GameObjects.Particles.Particle#computeVelocity + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter that is updating this Particle. + * @param {number} delta - The delta time in ms. + * @param {number} step - The delta value divided by 1000. + * @param {array} processors - Particle processors (gravity wells). + */ + computeVelocity: function (emitter, delta, step, processors) + { + var vx = this.velocityX; + var vy = this.velocityY; + + var ax = this.accelerationX; + var ay = this.accelerationY; + + var mx = this.maxVelocityX; + var my = this.maxVelocityY; + + vx += (emitter.gravityX * step); + vy += (emitter.gravityY * step); + + if (ax) + { + vx += (ax * step); + } + + if (ay) + { + vy += (ay * step); + } + + if (vx > mx) + { + vx = mx; + } + else if (vx < -mx) + { + vx = -mx; + } + + if (vy > my) + { + vy = my; + } + else if (vy < -my) + { + vy = -my; + } + + this.velocityX = vx; + this.velocityY = vy; + + // Apply any additional processors + for (var i = 0; i < processors.length; i++) + { + processors[i].update(this, delta, step); + } + }, + + /** + * Checks if this Particle is still within the bounds defined by the given Emitter. + * + * If not, and depending on the Emitter collision flags, the Particle may either stop or rebound. + * + * @method Phaser.GameObjects.Particles.Particle#checkBounds + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter to check the bounds against. + */ + checkBounds: function (emitter) + { + var bounds = emitter.bounds; + var bounce = -this.bounce; + + if (this.x < bounds.x && emitter.collideLeft) + { + this.x = bounds.x; + this.velocityX *= bounce; + } + else if (this.x > bounds.right && emitter.collideRight) + { + this.x = bounds.right; + this.velocityX *= bounce; + } + + if (this.y < bounds.y && emitter.collideTop) + { + this.y = bounds.y; + this.velocityY *= bounce; + } + else if (this.y > bounds.bottom && emitter.collideBottom) + { + this.y = bounds.bottom; + this.velocityY *= bounce; + } + }, + + /** + * The main update method for this Particle. + * + * Updates its life values, computes the velocity and repositions the Particle. + * + * @method Phaser.GameObjects.Particles.Particle#update + * @since 3.0.0 + * + * @param {number} delta - The delta time in ms. + * @param {number} step - The delta value divided by 1000. + * @param {array} processors - An optional array of update processors. + * + * @return {boolean} Returns `true` if this Particle has now expired and should be removed, otherwise `false` if still active. + */ + update: function (delta, step, processors) + { + if (this.delayCurrent > 0) + { + this.delayCurrent -= delta; + + return false; + } + + var emitter = this.emitter; + + // How far along in life is this particle? (t = 0 to 1) + var t = 1 - (this.lifeCurrent / this.life); + + this.lifeT = t; + + this.computeVelocity(emitter, delta, step, processors); + + this.x += this.velocityX * step; + this.y += this.velocityY * step; + + if (emitter.bounds) + { + this.checkBounds(emitter); + } + + if (emitter.deathZone && emitter.deathZone.willKill(this)) + { + this.lifeCurrent = 0; + + // No need to go any further, particle has been killed + return true; + } + + this.scaleX = emitter.scaleX.onUpdate(this, 'scaleX', t, this.scaleX); + + if (emitter.scaleY) + { + this.scaleY = emitter.scaleY.onUpdate(this, 'scaleY', t, this.scaleY); + } + else + { + this.scaleY = this.scaleX; + } + + this.angle = emitter.rotate.onUpdate(this, 'rotate', t, this.angle); + this.rotation = DegToRad(this.angle); + + this.alpha = emitter.alpha.onUpdate(this, 'alpha', t, this.alpha); + + this.tint = emitter.tint.onUpdate(this, 'tint', t, this.tint); + + this.lifeCurrent -= delta; + + return (this.lifeCurrent <= 0); + } + +}); + +module.exports = Particle; + + +/***/ }), +/* 427 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = __webpack_require__(43); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var DeathZone = __webpack_require__(428); +var EdgeZone = __webpack_require__(429); +var EmitterOp = __webpack_require__(1004); +var GetFastValue = __webpack_require__(1); +var GetRandom = __webpack_require__(198); +var HasAny = __webpack_require__(430); +var HasValue = __webpack_require__(91); +var Particle = __webpack_require__(426); +var RandomZone = __webpack_require__(431); +var Rectangle = __webpack_require__(11); +var StableSort = __webpack_require__(137); +var Vector2 = __webpack_require__(3); +var Wrap = __webpack_require__(63); + +/** + * @classdesc + * A particle emitter represents a single particle stream. + * It controls a pool of {@link Phaser.GameObjects.Particles.Particle Particles} and is controlled by a {@link Phaser.GameObjects.Particles.ParticleEmitterManager Particle Emitter Manager}. + * + * @class ParticleEmitter + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} manager - The Emitter Manager this Emitter belongs to. + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. + */ +var ParticleEmitter = new Class({ + + Mixins: [ + Components.BlendMode, + Components.Mask, + Components.ScrollFactor, + Components.Visible + ], + + initialize: + + function ParticleEmitter (manager, config) + { + /** + * The Emitter Manager this Emitter belongs to. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#manager + * @type {Phaser.GameObjects.Particles.ParticleEmitterManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The texture assigned to particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#texture + * @type {Phaser.Textures.Texture} + * @since 3.0.0 + */ + this.texture = manager.texture; + + /** + * The texture frames assigned to particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#frames + * @type {Phaser.Textures.Frame[]} + * @since 3.0.0 + */ + this.frames = [ manager.defaultFrame ]; + + /** + * The default texture frame assigned to particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#defaultFrame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + this.defaultFrame = manager.defaultFrame; + + /** + * Names of simple configuration properties. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#configFastMap + * @type {object} + * @since 3.0.0 + */ + this.configFastMap = [ + 'active', + 'blendMode', + 'collideBottom', + 'collideLeft', + 'collideRight', + 'collideTop', + 'deathCallback', + 'deathCallbackScope', + 'emitCallback', + 'emitCallbackScope', + 'follow', + 'frequency', + 'gravityX', + 'gravityY', + 'maxParticles', + 'name', + 'on', + 'particleBringToTop', + 'particleClass', + 'radial', + 'timeScale', + 'trackVisible', + 'visible' + ]; + + /** + * Names of complex configuration properties. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#configOpMap + * @type {object} + * @since 3.0.0 + */ + this.configOpMap = [ + 'accelerationX', + 'accelerationY', + 'angle', + 'alpha', + 'bounce', + 'delay', + 'lifespan', + 'maxVelocityX', + 'maxVelocityY', + 'moveToX', + 'moveToY', + 'quantity', + 'rotate', + 'scaleX', + 'scaleY', + 'speedX', + 'speedY', + 'tint', + 'x', + 'y' + ]; + + /** + * The name of this Particle Emitter. + * + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * The Particle Class which will be emitted by this Emitter. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#particleClass + * @type {Phaser.GameObjects.Particles.Particle} + * @default Phaser.GameObjects.Particles.Particle + * @since 3.0.0 + */ + this.particleClass = Particle; + + /** + * The x-coordinate of the particle origin (where particles will be emitted). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#x + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition + */ + this.x = new EmitterOp(config, 'x', 0, true); + + /** + * The y-coordinate of the particle origin (where particles will be emitted). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#y + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition + */ + this.y = new EmitterOp(config, 'y', 0, true); + + /** + * A radial emitter will emit particles in all directions between angle min and max, + * using {@link Phaser.GameObjects.Particles.ParticleEmitter#speed} as the value. If set to false then this acts as a point Emitter. + * A point emitter will emit particles only in the direction derived from the speedX and speedY values. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#radial + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setRadial + */ + this.radial = true; + + /** + * Horizontal acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#gravityX + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity + */ + this.gravityX = 0; + + /** + * Vertical acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#gravityY + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity + */ + this.gravityY = 0; + + /** + * Whether accelerationX and accelerationY are non-zero. Set automatically during configuration. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#acceleration + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.acceleration = false; + + /** + * Horizontal acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.accelerationX = new EmitterOp(config, 'accelerationX', 0, true); + + /** + * Vertical acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.accelerationY = new EmitterOp(config, 'accelerationY', 0, true); + + /** + * The maximum horizontal velocity of emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityX = new EmitterOp(config, 'maxVelocityX', 10000, true); + + /** + * The maximum vertical velocity of emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityY = new EmitterOp(config, 'maxVelocityY', 10000, true); + + /** + * The initial horizontal speed of emitted particles, in pixels per second. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#speedX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX + */ + this.speedX = new EmitterOp(config, 'speedX', 0, true); + + /** + * The initial vertical speed of emitted particles, in pixels per second. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#speedY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY + */ + this.speedY = new EmitterOp(config, 'speedY', 0, true); + + /** + * Whether moveToX and moveToY are nonzero. Set automatically during configuration. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#moveTo + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.moveTo = false; + + /** + * The x-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#moveToX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.moveToX = new EmitterOp(config, 'moveToX', 0, true); + + /** + * The y-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#moveToY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.moveToY = new EmitterOp(config, 'moveToY', 0, true); + + /** + * Whether particles will rebound when they meet the emitter bounds. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#bounce + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.bounce = new EmitterOp(config, 'bounce', 0, true); + + /** + * The horizontal scale of emitted particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#scaleX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScale + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleX + */ + this.scaleX = new EmitterOp(config, 'scaleX', 1); + + /** + * The vertical scale of emitted particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#scaleY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScale + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleY + */ + this.scaleY = new EmitterOp(config, 'scaleY', 1); + + /** + * Color tint applied to emitted particles. Any alpha component (0xAA000000) is ignored. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#tint + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0xffffffff + * @since 3.0.0 + */ + this.tint = new EmitterOp(config, 'tint', 0xffffffff); + + /** + * The alpha (transparency) of emitted particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#alpha + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setAlpha + */ + this.alpha = new EmitterOp(config, 'alpha', 1); + + /** + * The lifespan of emitted particles, in ms. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#lifespan + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1000 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setLifespan + */ + this.lifespan = new EmitterOp(config, 'lifespan', 1000, true); + + /** + * The angle of the initial velocity of emitted particles, in degrees. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#angle + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default { min: 0, max: 360 } + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setAngle + */ + this.angle = new EmitterOp(config, 'angle', { min: 0, max: 360 }, true); + + /** + * The rotation of emitted particles, in degrees. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#rotate + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.rotate = new EmitterOp(config, 'rotate', 0); + + /** + * A function to call when a particle is emitted. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallback + * @type {?Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} + * @default null + * @since 3.0.0 + */ + this.emitCallback = null; + + /** + * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope + * @type {?*} + * @default null + * @since 3.0.0 + */ + this.emitCallbackScope = null; + + /** + * A function to call when a particle dies. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallback + * @type {?Phaser.Types.GameObjects.Particles.ParticleDeathCallback} + * @default null + * @since 3.0.0 + */ + this.deathCallback = null; + + /** + * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope + * @type {?*} + * @default null + * @since 3.0.0 + */ + this.deathCallbackScope = null; + + /** + * Set to hard limit the amount of particle objects this emitter is allowed to create. + * 0 means unlimited. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#maxParticles + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.maxParticles = 0; + + /** + * How many particles are emitted each time particles are emitted (one explosion or one flow cycle). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#quantity + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency + * @see Phaser.GameObjects.Particles.ParticleEmitter#setQuantity + */ + this.quantity = new EmitterOp(config, 'quantity', 1, true); + + /** + * How many ms to wait after emission before the particles start updating. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#delay + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.delay = new EmitterOp(config, 'delay', 0, true); + + /** + * For a flow emitter, the time interval (>= 0) between particle flow cycles in ms. + * A value of 0 means there is one particle flow cycle for each logic update (the maximum flow frequency). This is the default setting. + * For an exploding emitter, this value will be -1. + * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} also puts the emitter in flow mode (frequency >= 0). + * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} also puts the emitter in explode mode (frequency = -1). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#frequency + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency + */ + this.frequency = 0; + + /** + * Controls if the emitter is currently emitting a particle flow (when frequency >= 0). + * Already alive particles will continue to update until they expire. + * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#start} and {@link Phaser.GameObjects.Particles.ParticleEmitter#stop}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#on + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.on = true; + + /** + * Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. + * Set to false to send them to the back. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#particleBringToTop + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.particleBringToTop = true; + + /** + * The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * An object describing a shape to emit particles from. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#emitZone + * @type {?Phaser.GameObjects.Particles.Zones.EdgeZone|Phaser.GameObjects.Particles.Zones.RandomZone} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone + */ + this.emitZone = null; + + /** + * An object describing a shape that deactivates particles when they interact with it. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#deathZone + * @type {?Phaser.GameObjects.Particles.Zones.DeathZone} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone + */ + this.deathZone = null; + + /** + * A rectangular boundary constraining particle movement. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#bounds + * @type {?Phaser.Geom.Rectangle} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setBounds + */ + this.bounds = null; + + /** + * Whether particles interact with the left edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideLeft + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideLeft = true; + + /** + * Whether particles interact with the right edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideRight + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideRight = true; + + /** + * Whether particles interact with the top edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideTop + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideTop = true; + + /** + * Whether particles interact with the bottom edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideBottom + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideBottom = true; + + /** + * Whether this emitter updates itself and its particles. + * + * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#pause} + * and {@link Phaser.GameObjects.Particles.ParticleEmitter#resume}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * Set this to false to hide any active particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#visible + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setVisible + */ + this.visible = true; + + /** + * The blend mode of this emitter's particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#blendMode + * @type {integer} + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setBlendMode + */ + this.blendMode = BlendModes.NORMAL; + + /** + * A Game Object whose position is used as the particle origin. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#follow + * @type {?Phaser.GameObjects.GameObject} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow + * @see Phaser.GameObjects.Particles.ParticleEmitter#stopFollow + */ + this.follow = null; + + /** + * The offset of the particle origin from the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#followOffset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow + */ + this.followOffset = new Vector2(); + + /** + * Whether the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#visible} state will track + * the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target's visibility state. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#trackVisible + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow + */ + this.trackVisible = false; + + /** + * The current texture frame, as an index of {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#currentFrame + * @type {integer} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame + */ + this.currentFrame = 0; + + /** + * Whether texture {@link Phaser.GameObjects.Particles.ParticleEmitter#frames} are selected at random. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#randomFrame + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame + */ + this.randomFrame = true; + + /** + * The number of consecutive particles that receive a single texture frame (per frame cycle). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity + * @type {integer} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame + */ + this.frameQuantity = 1; + + /** + * Inactive particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#dead + * @type {Phaser.GameObjects.Particles.Particle[]} + * @private + * @since 3.0.0 + */ + this.dead = []; + + /** + * Active particles + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#alive + * @type {Phaser.GameObjects.Particles.Particle[]} + * @private + * @since 3.0.0 + */ + this.alive = []; + + /** + * The time until the next flow cycle. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#_counter + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._counter = 0; + + /** + * Counts up to {@link Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#_frameCounter + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._frameCounter = 0; + + if (config) + { + this.fromJSON(config); + } + }, + + /** + * Merges configuration settings into the emitter's current settings. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + fromJSON: function (config) + { + if (!config) + { + return this; + } + + // Only update properties from their current state if they exist in the given config + + var i = 0; + var key = ''; + + for (i = 0; i < this.configFastMap.length; i++) + { + key = this.configFastMap[i]; + + if (HasValue(config, key)) + { + this[key] = GetFastValue(config, key); + } + } + + for (i = 0; i < this.configOpMap.length; i++) + { + key = this.configOpMap[i]; + + if (HasValue(config, key)) + { + this[key].loadConfig(config); + } + } + + this.acceleration = (this.accelerationX.propertyValue !== 0 || this.accelerationY.propertyValue !== 0); + + this.moveTo = (this.moveToX.propertyValue !== 0 || this.moveToY.propertyValue !== 0); + + // Special 'speed' override + + if (HasValue(config, 'speed')) + { + this.speedX.loadConfig(config, 'speed'); + this.speedY = null; + } + + // If you specify speedX, speedY or moveTo then it changes the emitter from radial to a point emitter + if (HasAny(config, [ 'speedX', 'speedY' ]) || this.moveTo) + { + this.radial = false; + } + + // Special 'scale' override + + if (HasValue(config, 'scale')) + { + this.scaleX.loadConfig(config, 'scale'); + this.scaleY = null; + } + + if (HasValue(config, 'callbackScope')) + { + var callbackScope = GetFastValue(config, 'callbackScope', null); + + this.emitCallbackScope = callbackScope; + this.deathCallbackScope = callbackScope; + } + + if (HasValue(config, 'emitZone')) + { + this.setEmitZone(config.emitZone); + } + + if (HasValue(config, 'deathZone')) + { + this.setDeathZone(config.deathZone); + } + + if (HasValue(config, 'bounds')) + { + this.setBounds(config.bounds); + } + + if (HasValue(config, 'followOffset')) + { + this.followOffset.setFromObject(GetFastValue(config, 'followOffset', 0)); + } + + if (HasValue(config, 'frame')) + { + this.setFrame(config.frame); + } + + return this; + }, + + /** + * Creates a description of this emitter suitable for JSON serialization. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#toJSON + * @since 3.0.0 + * + * @param {object} [output] - An object to copy output into. + * + * @return {object} - The output object. + */ + toJSON: function (output) + { + if (output === undefined) { output = {}; } + + var i = 0; + var key = ''; + + for (i = 0; i < this.configFastMap.length; i++) + { + key = this.configFastMap[i]; + + output[key] = this[key]; + } + + for (i = 0; i < this.configOpMap.length; i++) + { + key = this.configOpMap[i]; + + if (this[key]) + { + output[key] = this[key].toJSON(); + } + } + + // special handlers + if (!this.speedY) + { + delete output.speedX; + output.speed = this.speedX.toJSON(); + } + + if (!this.scaleY) + { + delete output.scaleX; + output.scale = this.scaleX.toJSON(); + } + + return output; + }, + + /** + * Continuously moves the particle origin to follow a Game Object's position. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#startFollow + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} target - The Game Object to follow. + * @param {number} [offsetX=0] - Horizontal offset of the particle origin from the Game Object. + * @param {number} [offsetY=0] - Vertical offset of the particle origin from the Game Object. + * @param {boolean} [trackVisible=false] - Whether the emitter's visible state will track the target's visible state. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + startFollow: function (target, offsetX, offsetY, trackVisible) + { + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackVisible === undefined) { trackVisible = false; } + + this.follow = target; + this.followOffset.set(offsetX, offsetY); + this.trackVisible = trackVisible; + + return this; + }, + + /** + * Stops following a Game Object. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#stopFollow + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + stopFollow: function () + { + this.follow = null; + this.followOffset.set(0, 0); + this.trackVisible = false; + + return this; + }, + + /** + * Chooses a texture frame from {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getFrame + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} The texture frame. + */ + getFrame: function () + { + if (this.frames.length === 1) + { + return this.defaultFrame; + } + else if (this.randomFrame) + { + return GetRandom(this.frames); + } + else + { + var frame = this.frames[this.currentFrame]; + + this._frameCounter++; + + if (this._frameCounter === this.frameQuantity) + { + this._frameCounter = 0; + this.currentFrame = Wrap(this.currentFrame + 1, 0, this._frameLength); + } + + return frame; + } + }, + + // frame: 0 + // frame: 'red' + // frame: [ 0, 1, 2, 3 ] + // frame: [ 'red', 'green', 'blue', 'pink', 'white' ] + // frame: { frames: [ 'red', 'green', 'blue', 'pink', 'white' ], [cycle: bool], [quantity: int] } + + /** + * Sets a pattern for assigning texture frames to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setFrame + * @since 3.0.0 + * + * @param {(array|string|integer|Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig)} frames - One or more texture frames, or a configuration object. + * @param {boolean} [pickRandom=true] - Whether frames should be assigned at random from `frames`. + * @param {integer} [quantity=1] - The number of consecutive particles that will receive each frame. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setFrame: function (frames, pickRandom, quantity) + { + if (pickRandom === undefined) { pickRandom = true; } + if (quantity === undefined) { quantity = 1; } + + this.randomFrame = pickRandom; + this.frameQuantity = quantity; + this.currentFrame = 0; + this._frameCounter = 0; + + var t = typeof (frames); + + if (Array.isArray(frames) || t === 'string' || t === 'number') + { + this.manager.setEmitterFrames(frames, this); + } + else if (t === 'object') + { + var frameConfig = frames; + + frames = GetFastValue(frameConfig, 'frames', null); + + if (frames) + { + this.manager.setEmitterFrames(frames, this); + } + + var isCycle = GetFastValue(frameConfig, 'cycle', false); + + this.randomFrame = (isCycle) ? false : true; + + this.frameQuantity = GetFastValue(frameConfig, 'quantity', quantity); + } + + this._frameLength = this.frames.length; + + if (this._frameLength === 1) + { + this.frameQuantity = 1; + this.randomFrame = false; + } + + return this; + }, + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle movement on or off. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setRadial + * @since 3.0.0 + * + * @param {boolean} [value=true] - Radial mode (true) or point mode (true). + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setRadial: function (value) + { + if (value === undefined) { value = true; } + + this.radial = value; + + return this; + }, + + /** + * Sets the position of the emitter's particle origin. + * New particles will be emitted here. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setPosition + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} x - The x-coordinate of the particle origin. + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} y - The y-coordinate of the particle origin. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setPosition: function (x, y) + { + this.x.onChange(x); + this.y.onChange(y); + + return this; + }, + + /** + * Sets or modifies a rectangular boundary constraining the particles. + * + * To remove the boundary, set {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds} to null. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setBounds + * @since 3.0.0 + * + * @param {(number|Phaser.Types.GameObjects.Particles.ParticleEmitterBounds|Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt)} x - The x-coordinate of the left edge of the boundary, or an object representing a rectangle. + * @param {number} y - The y-coordinate of the top edge of the boundary. + * @param {number} width - The width of the boundary. + * @param {number} height - The height of the boundary. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setBounds: function (x, y, width, height) + { + if (typeof x === 'object') + { + var obj = x; + + x = obj.x; + y = obj.y; + width = (HasValue(obj, 'w')) ? obj.w : obj.width; + height = (HasValue(obj, 'h')) ? obj.h : obj.height; + } + + if (this.bounds) + { + this.bounds.setTo(x, y, width, height); + } + else + { + this.bounds = new Rectangle(x, y, width, height); + } + + return this; + }, + + /** + * Sets the initial horizontal speed of emitted particles. + * Changes the emitter to point mode. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setSpeedX: function (value) + { + this.speedX.onChange(value); + + // If you specify speedX and Y then it changes the emitter from radial to a point emitter + this.radial = false; + + return this; + }, + + /** + * Sets the initial vertical speed of emitted particles. + * Changes the emitter to point mode. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setSpeedY: function (value) + { + if (this.speedY) + { + this.speedY.onChange(value); + + // If you specify speedX and Y then it changes the emitter from radial to a point emitter + this.radial = false; + } + + return this; + }, + + /** + * Sets the initial radial speed of emitted particles. + * Changes the emitter to radial mode. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeed + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setSpeed: function (value) + { + this.speedX.onChange(value); + this.speedY = null; + + // If you specify speedX and Y then it changes the emitter from radial to a point emitter + this.radial = true; + + return this; + }, + + /** + * Sets the horizontal scale of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleX + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setScaleX: function (value) + { + this.scaleX.onChange(value); + + return this; + }, + + /** + * Sets the vertical scale of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleY + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setScaleY: function (value) + { + this.scaleY.onChange(value); + + return this; + }, + + /** + * Sets the scale of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setScale + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setScale: function (value) + { + this.scaleX.onChange(value); + this.scaleY = null; + + return this; + }, + + /** + * Sets the horizontal gravity applied to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityX + * @since 3.0.0 + * + * @param {number} value - Acceleration due to gravity, in pixels per second squared. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setGravityX: function (value) + { + this.gravityX = value; + + return this; + }, + + /** + * Sets the vertical gravity applied to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityY + * @since 3.0.0 + * + * @param {number} value - Acceleration due to gravity, in pixels per second squared. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setGravityY: function (value) + { + this.gravityY = value; + + return this; + }, + + /** + * Sets the gravity applied to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravity + * @since 3.0.0 + * + * @param {number} x - Horizontal acceleration due to gravity, in pixels per second squared. + * @param {number} y - Vertical acceleration due to gravity, in pixels per second squared. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setGravity: function (x, y) + { + this.gravityX = x; + this.gravityY = y; + + return this; + }, + + /** + * Sets the opacity of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setAlpha + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 (transparent) and 1 (opaque). + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setAlpha: function (value) + { + this.alpha.onChange(value); + + return this; + }, + + /** + * Sets the color tint of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setTint + * @since 3.22.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 and 0xffffff. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setTint: function (value) + { + this.tint.onChange(value); + + return this; + }, + + /** + * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitterAngle + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setEmitterAngle: function (value) + { + this.angle.onChange(value); + + return this; + }, + + /** + * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setAngle + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setAngle: function (value) + { + this.angle.onChange(value); + + return this; + }, + + /** + * Sets the lifespan of newly emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setLifespan + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The particle lifespan, in ms. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setLifespan: function (value) + { + this.lifespan.onChange(value); + + return this; + }, + + /** + * Sets the number of particles released at each flow cycle or explosion. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setQuantity + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} quantity - The number of particles to release at each flow cycle or explosion. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setQuantity: function (quantity) + { + this.quantity.onChange(quantity); + + return this; + }, + + /** + * Sets the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency} + * and {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setFrequency + * @since 3.0.0 + * + * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [quantity] - The number of particles to release at each flow cycle or explosion. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setFrequency: function (frequency, quantity) + { + this.frequency = frequency; + + this._counter = 0; + + if (quantity) + { + this.quantity.onChange(quantity); + } + + return this; + }, + + /** + * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#emitZone}. + * + * An {@link Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig EdgeZone} places particles on its edges. Its {@link Phaser.Types.GameObjects.Particles.EdgeZoneSource source} can be a Curve, Path, Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback getPoints} method. + * + * A {@link Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig RandomZone} places randomly within its interior. Its {@link RandomZoneSource source} can be a Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback getRandomPoint} method. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current emit zone. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setEmitZone: function (zoneConfig) + { + if (zoneConfig === undefined) + { + this.emitZone = null; + } + else + { + // 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] } + + var type = GetFastValue(zoneConfig, 'type', 'random'); + var source = GetFastValue(zoneConfig, 'source', null); + + switch (type) + { + case 'random': + + this.emitZone = new RandomZone(source); + + break; + + case 'edge': + + var quantity = GetFastValue(zoneConfig, 'quantity', 1); + var stepRate = GetFastValue(zoneConfig, 'stepRate', 0); + var yoyo = GetFastValue(zoneConfig, 'yoyo', false); + var seamless = GetFastValue(zoneConfig, 'seamless', true); + + this.emitZone = new EdgeZone(source, quantity, stepRate, yoyo, seamless); + + break; + } + } + + return this; + }, + + /** + * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#deathZone}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current death zone. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + setDeathZone: function (zoneConfig) + { + if (zoneConfig === undefined) + { + this.deathZone = null; + } + else + { + // Where source = Geom like Circle or Rect that supports a 'contains' function + // deathZone: { type: 'onEnter', source: X } + // deathZone: { type: 'onLeave', source: X } + + var type = GetFastValue(zoneConfig, 'type', 'onEnter'); + var source = GetFastValue(zoneConfig, 'source', null); + + if (source && typeof source.contains === 'function') + { + var killOnEnter = (type === 'onEnter') ? true : false; + + this.deathZone = new DeathZone(source, killOnEnter); + } + } + + return this; + }, + + /** + * Creates inactive particles and adds them to this emitter's pool. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#reserve + * @since 3.0.0 + * + * @param {integer} particleCount - The number of particles to create. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + reserve: function (particleCount) + { + var dead = this.dead; + + for (var i = 0; i < particleCount; i++) + { + dead.push(new this.particleClass(this)); + } + + return this; + }, + + /** + * Gets the number of active (in-use) particles in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getAliveParticleCount + * @since 3.0.0 + * + * @return {integer} The number of particles with `active=true`. + */ + getAliveParticleCount: function () + { + return this.alive.length; + }, + + /** + * Gets the number of inactive (available) particles in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getDeadParticleCount + * @since 3.0.0 + * + * @return {integer} The number of particles with `active=false`. + */ + getDeadParticleCount: function () + { + return this.dead.length; + }, + + /** + * Gets the total number of particles in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getParticleCount + * @since 3.0.0 + * + * @return {integer} The number of particles, including both alive and dead. + */ + getParticleCount: function () + { + return this.getAliveParticleCount() + this.getDeadParticleCount(); + }, + + /** + * Whether this emitter is at its limit (if set). + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#atLimit + * @since 3.0.0 + * + * @return {boolean} Returns `true` if this Emitter is at its limit, or `false` if no limit, or below the `maxParticles` level. + */ + atLimit: function () + { + return (this.maxParticles > 0 && this.getParticleCount() === this.maxParticles); + }, + + /** + * Sets a function to call for each newly emitted particle. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleEmit + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. + * @param {*} [context] - The calling context. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + onParticleEmit: function (callback, context) + { + if (callback === undefined) + { + // Clear any previously set callback + this.emitCallback = null; + this.emitCallbackScope = null; + } + else if (typeof callback === 'function') + { + this.emitCallback = callback; + + if (context) + { + this.emitCallbackScope = context; + } + } + + return this; + }, + + /** + * Sets a function to call for each particle death. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleDeath + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleDeathCallback} callback - The function. + * @param {*} [context] - The function's calling context. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + onParticleDeath: function (callback, context) + { + if (callback === undefined) + { + // Clear any previously set callback + this.deathCallback = null; + this.deathCallbackScope = null; + } + else if (typeof callback === 'function') + { + this.deathCallback = callback; + + if (context) + { + this.deathCallbackScope = context; + } + } + + return this; + }, + + /** + * Deactivates every particle in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#killAll + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + killAll: function () + { + var dead = this.dead; + var alive = this.alive; + + while (alive.length > 0) + { + dead.push(alive.pop()); + } + + return this; + }, + + /** + * Calls a function for each active particle in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#forEachAlive + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. + * @param {*} context - The function's calling context. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + forEachAlive: function (callback, context) + { + var alive = this.alive; + var length = alive.length; + + for (var index = 0; index < length; ++index) + { + // Sends the Particle and the Emitter + callback.call(context, alive[index], this); + } + + return this; + }, + + /** + * Calls a function for each inactive particle in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#forEachDead + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. + * @param {*} context - The function's calling context. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + forEachDead: function (callback, context) + { + var dead = this.dead; + var length = dead.length; + + for (var index = 0; index < length; ++index) + { + // Sends the Particle and the Emitter + callback.call(context, dead[index], this); + } + + return this; + }, + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on} the emitter and resets the flow counter. + * + * If this emitter is in flow mode (frequency >= 0; the default), the particle flow will start (or restart). + * + * If this emitter is in explode mode (frequency = -1), nothing will happen. + * Use {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} or {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} instead. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#start + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + start: function () + { + this.on = true; + + this._counter = 0; + + return this; + }, + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on off} the emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#stop + * @since 3.11.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + stop: function () + { + this.on = false; + + return this; + }, + + /** + * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Deactivates} the emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#pause + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + pause: function () + { + this.active = false; + + return this; + }, + + /** + * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Activates} the emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#resume + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + resume: function () + { + this.active = true; + + return this; + }, + + /** + * Removes the emitter from its manager and the scene. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#remove + * @since 3.22.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + remove: function () + { + this.manager.removeEmitter(this); + + return this; + }, + + /** + * Sorts active particles with {@link Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSort + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + depthSort: function () + { + StableSort.inplace(this.alive, this.depthSortCallback); + + return this; + }, + + /** + * Puts the emitter in flow mode (frequency >= 0) and starts (or restarts) a particle flow. + * + * To resume a flow at the current frequency and quantity, use {@link Phaser.GameObjects.Particles.ParticleEmitter#start} instead. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#flow + * @since 3.0.0 + * + * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms. + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [count=1] - The number of particles to emit at each flow cycle. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. + */ + flow: function (frequency, count) + { + if (count === undefined) { count = 1; } + + this.frequency = frequency; + + this.quantity.onChange(count); + + return this.start(); + }, + + /** + * Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#explode + * @since 3.0.0 + * + * @param {integer} count - The amount of Particles to emit. + * @param {number} x - The x coordinate to emit the Particles from. + * @param {number} y - The y coordinate to emit the Particles from. + * + * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. + */ + explode: function (count, x, y) + { + this.frequency = -1; + + return this.emitParticle(count, x, y); + }, + + /** + * Emits particles at a given position (or the emitter's current position). + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticleAt + * @since 3.0.0 + * + * @param {number} [x=this.x] - The x coordinate to emit the Particles from. + * @param {number} [y=this.x] - The y coordinate to emit the Particles from. + * @param {integer} [count=this.quantity] - The number of Particles to emit. + * + * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. + */ + emitParticleAt: function (x, y, count) + { + return this.emitParticle(count, x, y); + }, + + /** + * Emits particles at a given position (or the emitter's current position). + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticle + * @since 3.0.0 + * + * @param {integer} [count=this.quantity] - The number of Particles to emit. + * @param {number} [x=this.x] - The x coordinate to emit the Particles from. + * @param {number} [y=this.x] - The y coordinate to emit the Particles from. + * + * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. + * + * @see Phaser.GameObjects.Particles.Particle#fire + */ + emitParticle: function (count, x, y) + { + if (this.atLimit()) + { + return; + } + + if (count === undefined) + { + count = this.quantity.onEmit(); + } + + var dead = this.dead; + + for (var i = 0; i < count; i++) + { + var particle = dead.pop(); + + if (!particle) + { + particle = new this.particleClass(this); + } + + particle.fire(x, y); + + if (this.particleBringToTop) + { + this.alive.push(particle); + } + else + { + this.alive.unshift(particle); + } + + if (this.emitCallback) + { + this.emitCallback.call(this.emitCallbackScope, particle, this); + } + + if (this.atLimit()) + { + break; + } + } + + return particle; + }, + + /** + * Updates this emitter and its particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#preUpdate + * @since 3.0.0 + * + * @param {integer} 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. + */ + preUpdate: function (time, delta) + { + // Scale the delta + delta *= this.timeScale; + + var step = (delta / 1000); + + if (this.trackVisible) + { + this.visible = this.follow.visible; + } + + // Any particle processors? + var processors = this.manager.getProcessors(); + + var particles = this.alive; + var dead = this.dead; + + var i = 0; + var rip = []; + var length = particles.length; + + for (i = 0; i < length; i++) + { + var particle = particles[i]; + + // update returns `true` if the particle is now dead (lifeCurrent <= 0) + if (particle.update(delta, step, processors)) + { + rip.push({ index: i, particle: particle }); + } + } + + // Move dead particles to the dead array + length = rip.length; + + if (length > 0) + { + var deathCallback = this.deathCallback; + var deathCallbackScope = this.deathCallbackScope; + + for (i = length - 1; i >= 0; i--) + { + var entry = rip[i]; + + // Remove from particles array + particles.splice(entry.index, 1); + + // Add to dead array + dead.push(entry.particle); + + // Callback + if (deathCallback) + { + deathCallback.call(deathCallbackScope, entry.particle); + } + + entry.particle.resetPosition(); + } + } + + if (!this.on) + { + return; + } + + if (this.frequency === 0) + { + this.emitParticle(); + } + else if (this.frequency > 0) + { + this._counter -= delta; + + if (this._counter <= 0) + { + this.emitParticle(); + + // counter = frequency - remained from previous delta + this._counter = (this.frequency - Math.abs(this._counter)); + } + } + }, + + /** + * Calculates the difference of two particles, for sorting them by depth. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback + * @since 3.0.0 + * + * @param {object} a - The first particle. + * @param {object} b - The second particle. + * + * @return {integer} The difference of a and b's y coordinates. + */ + depthSortCallback: function (a, b) + { + return a.y - b.y; + } + +}); + +module.exports = ParticleEmitter; + + +/***/ }), +/* 428 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A Death Zone. + * + * A Death Zone is a special type of zone that will kill a Particle as soon as it either enters, or leaves, the zone. + * + * The zone consists of a `source` which could be a Geometric shape, such as a Rectangle or Ellipse, or your own + * object as long as it includes a `contains` method for which the Particles can be tested against. + * + * @class DeathZone + * @memberof Phaser.GameObjects.Particles.Zones + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.DeathZoneSource} source - An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. + * @param {boolean} killOnEnter - Should the Particle be killed when it enters the zone? `true` or leaves it? `false` + */ +var DeathZone = new Class({ + + initialize: + + function DeathZone (source, killOnEnter) + { + /** + * An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. + * This could be a Geometry shape, such as `Phaser.Geom.Circle`, or your own custom object. + * + * @name Phaser.GameObjects.Particles.Zones.DeathZone#source + * @type {Phaser.Types.GameObjects.Particles.DeathZoneSource} + * @since 3.0.0 + */ + this.source = source; + + /** + * Set to `true` if the Particle should be killed if it enters this zone. + * Set to `false` to kill the Particle if it leaves this zone. + * + * @name Phaser.GameObjects.Particles.Zones.DeathZone#killOnEnter + * @type {boolean} + * @since 3.0.0 + */ + this.killOnEnter = killOnEnter; + }, + + /** + * Checks if the given Particle will be killed or not by this zone. + * + * @method Phaser.GameObjects.Particles.Zones.DeathZone#willKill + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle to be checked against this zone. + * + * @return {boolean} Return `true` if the Particle is to be killed, otherwise return `false`. + */ + willKill: function (particle) + { + var withinZone = this.source.contains(particle.x, particle.y); + + return (withinZone && this.killOnEnter || !withinZone && !this.killOnEnter); + } + +}); + +module.exports = DeathZone; + + +/***/ }), +/* 429 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A zone that places particles on a shape's edges. + * + * @class EdgeZone + * @memberof Phaser.GameObjects.Particles.Zones + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * @param {integer} quantity - The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + * @param {number} stepRate - The distance between each particle. When set, `quantity` is implied and should be set to 0. + * @param {boolean} [yoyo=false] - Whether particles are placed from start to end and then end to start. + * @param {boolean} [seamless=true] - Whether one endpoint will be removed if it's identical to the other. + */ +var EdgeZone = new Class({ + + initialize: + + function EdgeZone (source, quantity, stepRate, yoyo, seamless) + { + if (yoyo === undefined) { yoyo = false; } + if (seamless === undefined) { seamless = true; } + + /** + * An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#source + * @type {Phaser.Types.GameObjects.Particles.EdgeZoneSource|Phaser.Types.GameObjects.Particles.RandomZoneSource} + * @since 3.0.0 + */ + this.source = source; + + /** + * The points placed on the source edge. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#points + * @type {Phaser.Geom.Point[]} + * @default [] + * @since 3.0.0 + */ + this.points = []; + + /** + * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#quantity + * @type {integer} + * @since 3.0.0 + */ + this.quantity = quantity; + + /** + * The distance between each particle. When set, `quantity` is implied and should be set to 0. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#stepRate + * @type {number} + * @since 3.0.0 + */ + this.stepRate = stepRate; + + /** + * Whether particles are placed from start to end and then end to start. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#yoyo + * @type {boolean} + * @since 3.0.0 + */ + this.yoyo = yoyo; + + /** + * The counter used for iterating the EdgeZone's points. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#counter + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.counter = -1; + + /** + * Whether one endpoint will be removed if it's identical to the other. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#seamless + * @type {boolean} + * @since 3.0.0 + */ + this.seamless = seamless; + + /** + * An internal count of the points belonging to this EdgeZone. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#_length + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._length = 0; + + /** + * An internal value used to keep track of the current iteration direction for the EdgeZone's points. + * + * 0 = forwards, 1 = backwards + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#_direction + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._direction = 0; + + this.updateSource(); + }, + + /** + * Update the {@link Phaser.GameObjects.Particles.Zones.EdgeZone#points} from the EdgeZone's + * {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. + * + * Also updates internal properties. + * + * @method Phaser.GameObjects.Particles.Zones.EdgeZone#updateSource + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.Zones.EdgeZone} This Edge Zone. + */ + updateSource: function () + { + this.points = this.source.getPoints(this.quantity, this.stepRate); + + // Remove ends? + if (this.seamless) + { + var a = this.points[0]; + var b = this.points[this.points.length - 1]; + + if (a.x === b.x && a.y === b.y) + { + this.points.pop(); + } + } + + var oldLength = this._length; + + this._length = this.points.length; + + // Adjust counter if we now have less points than before + if (this._length < oldLength && this.counter > this._length) + { + this.counter = this._length - 1; + } + + return this; + }, + + /** + * Change the source of the EdgeZone. + * + * @method Phaser.GameObjects.Particles.Zones.EdgeZone#changeSource + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * + * @return {Phaser.GameObjects.Particles.Zones.EdgeZone} This Edge Zone. + */ + changeSource: function (source) + { + this.source = source; + + return this.updateSource(); + }, + + /** + * Get the next point in the Zone and set its coordinates on the given Particle. + * + * @method Phaser.GameObjects.Particles.Zones.EdgeZone#getPoint + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle. + */ + getPoint: function (particle) + { + if (this._direction === 0) + { + this.counter++; + + if (this.counter >= this._length) + { + if (this.yoyo) + { + this._direction = 1; + this.counter = this._length - 1; + } + else + { + this.counter = 0; + } + } + } + else + { + this.counter--; + + if (this.counter === -1) + { + if (this.yoyo) + { + this._direction = 0; + this.counter = 0; + } + else + { + this.counter = this._length - 1; + } + } + } + + var point = this.points[this.counter]; + + if (point) + { + particle.x = point.x; + particle.y = point.y; + } + } + +}); + +module.exports = EdgeZone; + + +/***/ }), +/* 430 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Verifies that an object contains at least one of the requested keys + * + * @function Phaser.Utils.Objects.HasAny + * @since 3.0.0 + * + * @param {object} source - an object on which to check for key existence + * @param {string[]} keys - an array of keys to search the object for + * + * @return {boolean} true if the source object contains at least one of the keys, false otherwise + */ +var HasAny = function (source, keys) +{ + for (var i = 0; i < keys.length; i++) + { + if (source.hasOwnProperty(keys[i])) + { + return true; + } + } + + return false; +}; + +module.exports = HasAny; + + +/***/ }), +/* 431 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A zone that places particles randomly within a shape's area. + * + * @class RandomZone + * @memberof Phaser.GameObjects.Particles.Zones + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.RandomZoneSource} source - An object instance with a `getRandomPoint(point)` method. + */ +var RandomZone = new Class({ + + initialize: + + function RandomZone (source) + { + /** + * An object instance with a `getRandomPoint(point)` method. + * + * @name Phaser.GameObjects.Particles.Zones.RandomZone#source + * @type {Phaser.Types.GameObjects.Particles.RandomZoneSource} + * @since 3.0.0 + */ + this.source = source; + + /** + * Internal calculation vector. + * + * @name Phaser.GameObjects.Particles.Zones.RandomZone#_tempVec + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tempVec = new Vector2(); + }, + + /** + * Get the next point in the Zone and set its coordinates on the given Particle. + * + * @method Phaser.GameObjects.Particles.Zones.RandomZone#getPoint + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle. + */ + getPoint: function (particle) + { + var vec = this._tempVec; + + this.source.getRandomPoint(vec); + + particle.x = vec.x; + particle.y = vec.y; + } + +}); + +module.exports = RandomZone; + + +/***/ }), +/* 432 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var Sprite = __webpack_require__(65); + +/** + * @classdesc + * A PathFollower Game Object. + * + * A PathFollower is a Sprite Game Object with some extra helpers to allow it to follow a Path automatically. + * + * Anything you can do with a standard Sprite can be done with this PathFollower, such as animate it, tint it, + * scale it and so on. + * + * PathFollowers are bound to a single Path at any one time and can traverse the length of the Path, from start + * to finish, forwards or backwards, or from any given point on the Path to its end. They can optionally rotate + * to face the direction of the path, be offset from the path coordinates or rotate independently of the Path. + * + * @class PathFollower + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.PathFollower + * + * @param {Phaser.Scene} scene - The Scene to which this PathFollower belongs. + * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var PathFollower = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.PathFollower + ], + + initialize: + + function PathFollower (scene, path, x, y, texture, frame) + { + Sprite.call(this, scene, x, y, texture, frame); + + this.path = path; + }, + + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + * + * @method Phaser.GameObjects.PathFollower#preUpdate + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + preUpdate: function (time, delta) + { + this.anims.update(time, delta); + this.pathUpdate(time); + } + +}); + +module.exports = PathFollower; + + +/***/ }), +/* 433 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcRender = __webpack_require__(1027); +var Class = __webpack_require__(0); +var DegToRad = __webpack_require__(40); +var Earcut = __webpack_require__(72); +var GeomCircle = __webpack_require__(71); +var MATH_CONST = __webpack_require__(13); +var Shape = __webpack_require__(33); + +/** + * @classdesc + * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an arc shape. You can control the start and end angles of the arc, + * as well as if the angles are winding clockwise or anti-clockwise. With the default settings + * it renders as a complete circle. By changing the angles you can create other arc shapes, + * such as half-circles. + * + * Arcs also have an `iterations` property and corresponding `setIterations` method. This allows + * you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. + * + * @class Arc + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [radius=128] - The radius of the arc. + * @param {integer} [startAngle=0] - The start angle of the arc, in degrees. + * @param {integer} [endAngle=360] - The end angle of the arc, in degrees. + * @param {boolean} [anticlockwise=false] - The winding order of the start and end angles. + * @param {number} [fillColor] - The color the arc will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Arc = new Class({ + + Extends: Shape, + + Mixins: [ + ArcRender + ], + + initialize: + + function Arc (scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (radius === undefined) { radius = 128; } + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 360; } + if (anticlockwise === undefined) { anticlockwise = false; } + + Shape.call(this, scene, 'Arc', new GeomCircle(0, 0, radius)); + + /** + * Private internal value. Holds the start angle in degrees. + * + * @name Phaser.GameObjects.Arc#_startAngle + * @type {integer} + * @private + * @since 3.13.0 + */ + this._startAngle = startAngle; + + /** + * Private internal value. Holds the end angle in degrees. + * + * @name Phaser.GameObjects.Arc#_endAngle + * @type {integer} + * @private + * @since 3.13.0 + */ + this._endAngle = endAngle; + + /** + * Private internal value. Holds the winding order of the start and end angles. + * + * @name Phaser.GameObjects.Arc#_anticlockwise + * @type {boolean} + * @private + * @since 3.13.0 + */ + this._anticlockwise = anticlockwise; + + /** + * Private internal value. Holds the number of iterations used when drawing the arc. + * + * @name Phaser.GameObjects.Arc#_iterations + * @type {number} + * @default 0.01 + * @private + * @since 3.13.0 + */ + this._iterations = 0.01; + + this.setPosition(x, y); + + var diameter = this.geom.radius * 2; + this.setSize(diameter, diameter); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * The number of iterations used when drawing the arc. + * Increase this value for smoother arcs, at the cost of more polygons being rendered. + * Modify this value by small amounts, such as 0.01. + * + * @name Phaser.GameObjects.Arc#iterations + * @type {number} + * @default 0.01 + * @since 3.13.0 + */ + iterations: { + + get: function () + { + return this._iterations; + }, + + set: function (value) + { + this._iterations = value; + + this.updateData(); + } + + }, + + /** + * The radius of the arc. + * + * @name Phaser.GameObjects.Arc#radius + * @type {number} + * @since 3.13.0 + */ + radius: { + + get: function () + { + return this.geom.radius; + }, + + set: function (value) + { + this.geom.radius = value; + + var diameter = value * 2; + this.setSize(diameter, diameter); + this.updateDisplayOrigin(); + this.updateData(); + } + + }, + + /** + * The start angle of the arc, in degrees. + * + * @name Phaser.GameObjects.Arc#startAngle + * @type {integer} + * @since 3.13.0 + */ + startAngle: { + + get: function () + { + return this._startAngle; + }, + + set: function (value) + { + this._startAngle = value; + + this.updateData(); + } + + }, + + /** + * The end angle of the arc, in degrees. + * + * @name Phaser.GameObjects.Arc#endAngle + * @type {integer} + * @since 3.13.0 + */ + endAngle: { + + get: function () + { + return this._endAngle; + }, + + set: function (value) + { + this._endAngle = value; + + this.updateData(); + } + + }, + + /** + * The winding order of the start and end angles. + * + * @name Phaser.GameObjects.Arc#anticlockwise + * @type {boolean} + * @since 3.13.0 + */ + anticlockwise: { + + get: function () + { + return this._anticlockwise; + }, + + set: function (value) + { + this._anticlockwise = value; + + this.updateData(); + } + + }, + + /** + * Sets the radius of the arc. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setRadius + * @since 3.13.0 + * + * @param {number} value - The value to set the radius to. + * + * @return {this} This Game Object instance. + */ + setRadius: function (value) + { + this.radius = value; + + return this; + }, + + /** + * Sets the number of iterations used when drawing the arc. + * Increase this value for smoother arcs, at the cost of more polygons being rendered. + * Modify this value by small amounts, such as 0.01. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setIterations + * @since 3.13.0 + * + * @param {number} value - The value to set the iterations to. + * + * @return {this} This Game Object instance. + */ + setIterations: function (value) + { + if (value === undefined) { value = 0.01; } + + this.iterations = value; + + return this; + }, + + /** + * Sets the starting angle of the arc, in degrees. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setStartAngle + * @since 3.13.0 + * + * @param {integer} value - The value to set the starting angle to. + * + * @return {this} This Game Object instance. + */ + setStartAngle: function (angle, anticlockwise) + { + this._startAngle = angle; + + if (anticlockwise !== undefined) + { + this._anticlockwise = anticlockwise; + } + + return this.updateData(); + }, + + /** + * Sets the ending angle of the arc, in degrees. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setEndAngle + * @since 3.13.0 + * + * @param {integer} value - The value to set the ending angle to. + * + * @return {this} This Game Object instance. + */ + setEndAngle: function (angle, anticlockwise) + { + this._endAngle = angle; + + if (anticlockwise !== undefined) + { + this._anticlockwise = anticlockwise; + } + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Arc#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var step = this._iterations; + var iteration = step; + + var radius = this.geom.radius; + var startAngle = DegToRad(this._startAngle); + var endAngle = DegToRad(this._endAngle); + var anticlockwise = this._anticlockwise; + + var x = radius; + var y = radius; + + endAngle -= startAngle; + + if (anticlockwise) + { + if (endAngle < -MATH_CONST.PI2) + { + endAngle = -MATH_CONST.PI2; + } + else if (endAngle > 0) + { + endAngle = -MATH_CONST.PI2 + endAngle % MATH_CONST.PI2; + } + } + else if (endAngle > MATH_CONST.PI2) + { + endAngle = MATH_CONST.PI2; + } + else if (endAngle < 0) + { + endAngle = MATH_CONST.PI2 + endAngle % MATH_CONST.PI2; + } + + var path = [ x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius ]; + + var ta; + + while (iteration < 1) + { + ta = endAngle * iteration + startAngle; + + path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); + + iteration += step; + } + + ta = endAngle + startAngle; + + path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); + + path.push(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Arc; + + +/***/ }), +/* 434 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CurveRender = __webpack_require__(1030); +var Earcut = __webpack_require__(72); +var Rectangle = __webpack_require__(11); +var Shape = __webpack_require__(33); + +/** + * @classdesc + * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to + * the Curve Shape in the constructor. + * + * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @class Curve + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {Phaser.Curves.Curve} [curve] - The Curve object to use to create the Shape. + * @param {number} [fillColor] - The color the curve will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Curve = new Class({ + + Extends: Shape, + + Mixins: [ + CurveRender + ], + + initialize: + + function Curve (scene, x, y, curve, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + Shape.call(this, scene, 'Curve', curve); + + /** + * Private internal value. + * The number of points used to draw the curve. Higher values create smoother renders at the cost of more triangles being drawn. + * + * @name Phaser.GameObjects.Curve#_smoothness + * @type {integer} + * @private + * @since 3.13.0 + */ + this._smoothness = 32; + + /** + * Private internal value. + * The Curve bounds rectangle. + * + * @name Phaser.GameObjects.Curve#_curveBounds + * @type {Phaser.Geom.Rectangle} + * @private + * @since 3.13.0 + */ + this._curveBounds = new Rectangle(); + + this.closePath = false; + + this.setPosition(x, y); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateData(); + }, + + /** + * The smoothness of the curve. The number of points used when rendering it. + * Increase this value for smoother curves, at the cost of more polygons being rendered. + * + * @name Phaser.GameObjects.Curve#smoothness + * @type {integer} + * @default 32 + * @since 3.13.0 + */ + smoothness: { + + get: function () + { + return this._smoothness; + }, + + set: function (value) + { + this._smoothness = value; + + this.updateData(); + } + + }, + + /** + * Sets the smoothness of the curve. The number of points used when rendering it. + * Increase this value for smoother curves, at the cost of more polygons being rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.Curve#setSmoothness + * @since 3.13.0 + * + * @param {integer} value - The value to set the smoothness to. + * + * @return {this} This Game Object instance. + */ + setSmoothness: function (value) + { + this._smoothness = value; + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Curve#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var bounds = this._curveBounds; + var smoothness = this._smoothness; + + // Update the bounds in case the underlying data has changed + this.geom.getBounds(bounds, smoothness); + + this.setSize(bounds.width, bounds.height); + this.updateDisplayOrigin(); + + var path = []; + var points = this.geom.getPoints(smoothness); + + for (var i = 0; i < points.length; i++) + { + path.push(points[i].x, points[i].y); + } + + path.push(points[0].x, points[0].y); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Curve; + + +/***/ }), +/* 435 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Earcut = __webpack_require__(72); +var EllipseRender = __webpack_require__(1033); +var GeomEllipse = __webpack_require__(107); +var Shape = __webpack_require__(33); + +/** + * @classdesc + * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. + * If the width and height match it will render as a circle. If the width is less than the height, + * it will look more like an egg shape. + * + * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @class Ellipse + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [height=128] - The height of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [fillColor] - The color the ellipse will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Ellipse = new Class({ + + Extends: Shape, + + Mixins: [ + EllipseRender + ], + + initialize: + + function Ellipse (scene, x, y, width, height, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + + Shape.call(this, scene, 'Ellipse', new GeomEllipse(width / 2, height / 2, width, height)); + + /** + * Private internal value. + * The number of points used to draw the curve. Higher values create smoother renders at the cost of more triangles being drawn. + * + * @name Phaser.GameObjects.Ellipse#_smoothness + * @type {integer} + * @private + * @since 3.13.0 + */ + this._smoothness = 64; + + this.setPosition(x, y); + + this.width = width; + this.height = height; + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * The smoothness of the ellipse. The number of points used when rendering it. + * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. + * + * @name Phaser.GameObjects.Ellipse#smoothness + * @type {integer} + * @default 64 + * @since 3.13.0 + */ + smoothness: { + + get: function () + { + return this._smoothness; + }, + + set: function (value) + { + this._smoothness = value; + + this.updateData(); + } + + }, + + /** + * Sets the size of the ellipse by changing the underlying geometry data, rather than scaling the object. + * This call can be chained. + * + * @method Phaser.GameObjects.Ellipse#setSize + * @since 3.13.0 + * + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + this.geom.setSize(width, height); + + return this.updateData(); + }, + + /** + * Sets the smoothness of the ellipse. The number of points used when rendering it. + * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.Ellipse#setSmoothness + * @since 3.13.0 + * + * @param {integer} value - The value to set the smoothness to. + * + * @return {this} This Game Object instance. + */ + setSmoothness: function (value) + { + this._smoothness = value; + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Ellipse#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var points = this.geom.getPoints(this._smoothness); + + for (var i = 0; i < points.length; i++) + { + path.push(points[i].x, points[i].y); + } + + path.push(points[0].x, points[0].y); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Ellipse; + + +/***/ }), +/* 436 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Shape = __webpack_require__(33); +var GridRender = __webpack_require__(1036); + +/** + * @classdesc + * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * A Grid Shape allows you to display a grid in your game, where you can control the size of the + * grid as well as the width and height of the grid cells. You can set a fill color for each grid + * cell as well as an alternate fill color. When the alternate fill color is set then the grid + * cells will alternate the fill colors as they render, creating a chess-board effect. You can + * also optionally have an outline fill color. If set, this draws lines between the grid cells + * in the given color. If you specify an outline color with an alpha of zero, then it will draw + * the cells spaced out, but without the lines between them. + * + * @class Grid + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the grid. + * @param {number} [height=128] - The height of the grid. + * @param {number} [cellWidth=32] - The width of one cell in the grid. + * @param {number} [cellHeight=32] - The height of one cell in the grid. + * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * @param {number} [outlineFillColor] - The color of the lines between the grid cells. See the `setOutline` method. + * @param {number} [outlineFillAlpha] - The alpha of the lines between the grid cells. + */ +var Grid = new Class({ + + Extends: Shape, + + Mixins: [ + GridRender + ], + + initialize: + + function Grid (scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + if (cellWidth === undefined) { cellWidth = 32; } + if (cellHeight === undefined) { cellHeight = 32; } + + Shape.call(this, scene, 'Grid', null); + + /** + * The width of each grid cell. + * Must be a positive value. + * + * @name Phaser.GameObjects.Grid#cellWidth + * @type {number} + * @since 3.13.0 + */ + this.cellWidth = cellWidth; + + /** + * The height of each grid cell. + * Must be a positive value. + * + * @name Phaser.GameObjects.Grid#cellHeight + * @type {number} + * @since 3.13.0 + */ + this.cellHeight = cellHeight; + + /** + * Will the grid render its cells in the `fillColor`? + * + * @name Phaser.GameObjects.Grid#showCells + * @type {boolean} + * @since 3.13.0 + */ + this.showCells = true; + + /** + * The color of the lines between each grid cell. + * + * @name Phaser.GameObjects.Grid#outlineFillColor + * @type {number} + * @since 3.13.0 + */ + this.outlineFillColor = 0; + + /** + * The alpha value for the color of the lines between each grid cell. + * + * @name Phaser.GameObjects.Grid#outlineFillAlpha + * @type {number} + * @since 3.13.0 + */ + this.outlineFillAlpha = 0; + + /** + * Will the grid display the lines between each cell when it renders? + * + * @name Phaser.GameObjects.Grid#showOutline + * @type {boolean} + * @since 3.13.0 + */ + this.showOutline = true; + + /** + * Will the grid render the alternating cells in the `altFillColor`? + * + * @name Phaser.GameObjects.Grid#showAltCells + * @type {boolean} + * @since 3.13.0 + */ + this.showAltCells = false; + + /** + * The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. + * + * @name Phaser.GameObjects.Grid#altFillColor + * @type {number} + * @since 3.13.0 + */ + this.altFillColor; + + /** + * The alpha the alternating grid cells will be filled with. + * You can also set the alpha of the overall Shape using its `alpha` property. + * + * @name Phaser.GameObjects.Grid#altFillAlpha + * @type {number} + * @since 3.13.0 + */ + this.altFillAlpha; + + this.setPosition(x, y); + this.setSize(width, height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + if (outlineFillColor !== undefined) + { + this.setOutlineStyle(outlineFillColor, outlineFillAlpha); + } + + this.updateDisplayOrigin(); + }, + + /** + * Sets the fill color and alpha level the grid cells will use when rendering. + * + * If this method is called with no values then the grid cells will not be rendered, + * however the grid lines and alternating cells may still be. + * + * Also see the `setOutlineStyle` and `setAltFillStyle` methods. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Grid#setFillStyle + * @since 3.13.0 + * + * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha=1] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (fillColor, fillAlpha) + { + if (fillAlpha === undefined) { fillAlpha = 1; } + + if (fillColor === undefined) + { + this.showCells = false; + } + else + { + this.fillColor = fillColor; + this.fillAlpha = fillAlpha; + this.showCells = true; + } + + return this; + }, + + /** + * Sets the fill color and alpha level that the alternating grid cells will use. + * + * If this method is called with no values then alternating grid cells will not be rendered in a different color. + * + * Also see the `setOutlineStyle` and `setFillStyle` methods. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Grid#setAltFillStyle + * @since 3.13.0 + * + * @param {number} [fillColor] - The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha=1] - The alpha the alternating grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {this} This Game Object instance. + */ + setAltFillStyle: function (fillColor, fillAlpha) + { + if (fillAlpha === undefined) { fillAlpha = 1; } + + if (fillColor === undefined) + { + this.showAltCells = false; + } + else + { + this.altFillColor = fillColor; + this.altFillAlpha = fillAlpha; + this.showAltCells = true; + } + + return this; + }, + + /** + * Sets the fill color and alpha level that the lines between each grid cell will use. + * + * If this method is called with no values then the grid lines will not be rendered at all, however + * the cells themselves may still be if they have colors set. + * + * Also see the `setFillStyle` and `setAltFillStyle` methods. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Grid#setOutlineStyle + * @since 3.13.0 + * + * @param {number} [fillColor] - The color the lines between the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha=1] - The alpha the lines between the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {this} This Game Object instance. + */ + setOutlineStyle: function (fillColor, fillAlpha) + { + if (fillAlpha === undefined) { fillAlpha = 1; } + + if (fillColor === undefined) + { + this.showOutline = false; + } + else + { + this.outlineFillColor = fillColor; + this.outlineFillAlpha = fillAlpha; + this.showOutline = true; + } + + return this; + } + +}); + +module.exports = Grid; + + +/***/ }), +/* 437 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsoBoxRender = __webpack_require__(1039); +var Class = __webpack_require__(0); +var Shape = __webpack_require__(33); + +/** + * @classdesc + * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set + * the color of the top, left and right faces of the rectangle respectively. You can also choose + * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting + * the `projection` property. + * + * @class IsoBox + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso box in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso box. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso box. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso box. + */ +var IsoBox = new Class({ + + Extends: Shape, + + Mixins: [ + IsoBoxRender + ], + + initialize: + + function IsoBox (scene, x, y, size, height, fillTop, fillLeft, fillRight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (size === undefined) { size = 48; } + if (height === undefined) { height = 32; } + if (fillTop === undefined) { fillTop = 0xeeeeee; } + if (fillLeft === undefined) { fillLeft = 0x999999; } + if (fillRight === undefined) { fillRight = 0xcccccc; } + + Shape.call(this, scene, 'IsoBox', null); + + /** + * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * + * @name Phaser.GameObjects.IsoBox#projection + * @type {integer} + * @default 4 + * @since 3.13.0 + */ + this.projection = 4; + + /** + * The color used to fill in the top of the iso box. + * + * @name Phaser.GameObjects.IsoBox#fillTop + * @type {number} + * @since 3.13.0 + */ + this.fillTop = fillTop; + + /** + * The color used to fill in the left-facing side of the iso box. + * + * @name Phaser.GameObjects.IsoBox#fillLeft + * @type {number} + * @since 3.13.0 + */ + this.fillLeft = fillLeft; + + /** + * The color used to fill in the right-facing side of the iso box. + * + * @name Phaser.GameObjects.IsoBox#fillRight + * @type {number} + * @since 3.13.0 + */ + this.fillRight = fillRight; + + /** + * Controls if the top-face of the iso box be rendered. + * + * @name Phaser.GameObjects.IsoBox#showTop + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showTop = true; + + /** + * Controls if the left-face of the iso box be rendered. + * + * @name Phaser.GameObjects.IsoBox#showLeft + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showLeft = true; + + /** + * Controls if the right-face of the iso box be rendered. + * + * @name Phaser.GameObjects.IsoBox#showRight + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showRight = true; + + this.isFilled = true; + + this.setPosition(x, y); + this.setSize(size, height); + + this.updateDisplayOrigin(); + }, + + /** + * Sets the projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoBox#setProjection + * @since 3.13.0 + * + * @param {integer} value - The value to set the projection to. + * + * @return {this} This Game Object instance. + */ + setProjection: function (value) + { + this.projection = value; + + return this; + }, + + /** + * Sets which faces of the iso box will be rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoBox#setFaces + * @since 3.13.0 + * + * @param {boolean} [showTop=true] - Show the top-face of the iso box. + * @param {boolean} [showLeft=true] - Show the left-face of the iso box. + * @param {boolean} [showRight=true] - Show the right-face of the iso box. + * + * @return {this} This Game Object instance. + */ + setFaces: function (showTop, showLeft, showRight) + { + if (showTop === undefined) { showTop = true; } + if (showLeft === undefined) { showLeft = true; } + if (showRight === undefined) { showRight = true; } + + this.showTop = showTop; + this.showLeft = showLeft; + this.showRight = showRight; + + return this; + }, + + /** + * Sets the fill colors for each face of the iso box. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoBox#setFillStyle + * @since 3.13.0 + * + * @param {number} [fillTop] - The color used to fill the top of the iso box. + * @param {number} [fillLeft] - The color used to fill in the left-facing side of the iso box. + * @param {number} [fillRight] - The color used to fill in the right-facing side of the iso box. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (fillTop, fillLeft, fillRight) + { + this.fillTop = fillTop; + this.fillLeft = fillLeft; + this.fillRight = fillRight; + + this.isFilled = true; + + return this; + } + +}); + +module.exports = IsoBox; + + +/***/ }), +/* 438 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var IsoTriangleRender = __webpack_require__(1042); +var Shape = __webpack_require__(33); + +/** + * @classdesc + * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different + * fill color. You can set the color of the top, left and right faces of the triangle respectively + * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting + * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside + * down or not. + * + * @class IsoTriangle + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. + * @param {boolean} [reversed=false] - Is the iso triangle upside down? + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle. + */ +var IsoTriangle = new Class({ + + Extends: Shape, + + Mixins: [ + IsoTriangleRender + ], + + initialize: + + function IsoTriangle (scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (size === undefined) { size = 48; } + if (height === undefined) { height = 32; } + if (reversed === undefined) { reversed = false; } + if (fillTop === undefined) { fillTop = 0xeeeeee; } + if (fillLeft === undefined) { fillLeft = 0x999999; } + if (fillRight === undefined) { fillRight = 0xcccccc; } + + Shape.call(this, scene, 'IsoTriangle', null); + + /** + * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * + * @name Phaser.GameObjects.IsoTriangle#projection + * @type {integer} + * @default 4 + * @since 3.13.0 + */ + this.projection = 4; + + /** + * The color used to fill in the top of the iso triangle. This is only used if the triangle is reversed. + * + * @name Phaser.GameObjects.IsoTriangle#fillTop + * @type {number} + * @since 3.13.0 + */ + this.fillTop = fillTop; + + /** + * The color used to fill in the left-facing side of the iso triangle. + * + * @name Phaser.GameObjects.IsoTriangle#fillLeft + * @type {number} + * @since 3.13.0 + */ + this.fillLeft = fillLeft; + + /** + * The color used to fill in the right-facing side of the iso triangle. + * + * @name Phaser.GameObjects.IsoTriangle#fillRight + * @type {number} + * @since 3.13.0 + */ + this.fillRight = fillRight; + + /** + * Controls if the top-face of the iso triangle be rendered. + * + * @name Phaser.GameObjects.IsoTriangle#showTop + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showTop = true; + + /** + * Controls if the left-face of the iso triangle be rendered. + * + * @name Phaser.GameObjects.IsoTriangle#showLeft + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showLeft = true; + + /** + * Controls if the right-face of the iso triangle be rendered. + * + * @name Phaser.GameObjects.IsoTriangle#showRight + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showRight = true; + + /** + * Sets if the iso triangle will be rendered upside down or not. + * + * @name Phaser.GameObjects.IsoTriangle#isReversed + * @type {boolean} + * @default false + * @since 3.13.0 + */ + this.isReversed = reversed; + + this.isFilled = true; + + this.setPosition(x, y); + this.setSize(size, height); + + this.updateDisplayOrigin(); + }, + + /** + * Sets the projection level of the iso triangle. Change this to change the 'angle' at which you are looking at the pyramid. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setProjection + * @since 3.13.0 + * + * @param {integer} value - The value to set the projection to. + * + * @return {this} This Game Object instance. + */ + setProjection: function (value) + { + this.projection = value; + + return this; + }, + + /** + * Sets if the iso triangle will be rendered upside down or not. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setReversed + * @since 3.13.0 + * + * @param {boolean} reversed - Sets if the iso triangle will be rendered upside down or not. + * + * @return {this} This Game Object instance. + */ + setReversed: function (reversed) + { + this.isReversed = reversed; + + return this; + }, + + /** + * Sets which faces of the iso triangle will be rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setFaces + * @since 3.13.0 + * + * @param {boolean} [showTop=true] - Show the top-face of the iso triangle (only if `reversed` is true) + * @param {boolean} [showLeft=true] - Show the left-face of the iso triangle. + * @param {boolean} [showRight=true] - Show the right-face of the iso triangle. + * + * @return {this} This Game Object instance. + */ + setFaces: function (showTop, showLeft, showRight) + { + if (showTop === undefined) { showTop = true; } + if (showLeft === undefined) { showLeft = true; } + if (showRight === undefined) { showRight = true; } + + this.showTop = showTop; + this.showLeft = showLeft; + this.showRight = showRight; + + return this; + }, + + /** + * Sets the fill colors for each face of the iso triangle. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setFillStyle + * @since 3.13.0 + * + * @param {number} [fillTop] - The color used to fill the top of the iso triangle. + * @param {number} [fillLeft] - The color used to fill in the left-facing side of the iso triangle. + * @param {number} [fillRight] - The color used to fill in the right-facing side of the iso triangle. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (fillTop, fillLeft, fillRight) + { + this.fillTop = fillTop; + this.fillLeft = fillLeft; + this.fillRight = fillRight; + + this.isFilled = true; + + return this; + } + +}); + +module.exports = IsoTriangle; + + +/***/ }), +/* 439 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Shape = __webpack_require__(33); +var GeomLine = __webpack_require__(61); +var LineRender = __webpack_require__(1045); + +/** + * @classdesc + * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only stroke colors and cannot be filled. + * + * A Line Shape allows you to draw a line between two points in your game. You can control the + * stroke color and thickness of the line. In WebGL only you can also specify a different + * thickness for the start and end of the line, allowing you to render lines that taper-off. + * + * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. + * + * Be aware that as with all Game Objects the default origin is 0.5. If you need to draw a Line + * between two points and want the x1/y1 values to match the x/y values, then set the origin to 0. + * + * @class Line + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the start of the line. + * @param {number} [y1=0] - The vertical position of the start of the line. + * @param {number} [x2=128] - The horizontal position of the end of the line. + * @param {number} [y2=0] - The vertical position of the end of the line. + * @param {number} [strokeColor] - The color the line will be drawn in, i.e. 0xff0000 for red. + * @param {number} [strokeAlpha] - The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Line = new Class({ + + Extends: Shape, + + Mixins: [ + LineRender + ], + + initialize: + + function Line (scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 128; } + if (y2 === undefined) { y2 = 0; } + + Shape.call(this, scene, 'Line', new GeomLine(x1, y1, x2, y2)); + + var width = this.geom.right - this.geom.left; + var height = this.geom.bottom - this.geom.top; + + /** + * The width (or thickness) of the line. + * See the setLineWidth method for extra details on changing this on WebGL. + * + * @name Phaser.GameObjects.Line#lineWidth + * @type {number} + * @since 3.13.0 + */ + this.lineWidth = 1; + + /** + * Private internal value. Holds the start width of the line. + * + * @name Phaser.GameObjects.Line#_startWidth + * @type {number} + * @private + * @since 3.13.0 + */ + this._startWidth = 1; + + /** + * Private internal value. Holds the end width of the line. + * + * @name Phaser.GameObjects.Line#_endWidth + * @type {number} + * @private + * @since 3.13.0 + */ + this._endWidth = 1; + + this.setPosition(x, y); + this.setSize(width, height); + + if (strokeColor !== undefined) + { + this.setStrokeStyle(1, strokeColor, strokeAlpha); + } + + this.updateDisplayOrigin(); + }, + + /** + * Sets the width of the line. + * + * When using the WebGL renderer you can have different start and end widths. + * When using the Canvas renderer only the `startWidth` value is used. The `endWidth` is ignored. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Line#setLineWidth + * @since 3.13.0 + * + * @param {number} startWidth - The start width of the line. + * @param {number} [endWidth] - The end width of the line. Only used in WebGL. + * + * @return {this} This Game Object instance. + */ + setLineWidth: function (startWidth, endWidth) + { + if (endWidth === undefined) { endWidth = startWidth; } + + this._startWidth = startWidth; + this._endWidth = endWidth; + + this.lineWidth = startWidth; + + return this; + }, + + /** + * Sets the start and end coordinates of this Line. + * + * @method Phaser.GameObjects.Line#setTo + * @since 3.13.0 + * + * @param {number} [x1=0] - The horizontal position of the start of the line. + * @param {number} [y1=0] - The vertical position of the start of the line. + * @param {number} [x2=0] - The horizontal position of the end of the line. + * @param {number} [y2=0] - The vertical position of the end of the line. + * + * @return {this} This Line object. + */ + setTo: function (x1, y1, x2, y2) + { + this.geom.setTo(x1, y1, x2, y2); + + return this; + } + +}); + +module.exports = Line; + + +/***/ }), +/* 440 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PolygonRender = __webpack_require__(1048); +var Class = __webpack_require__(0); +var Earcut = __webpack_require__(72); +var GetAABB = __webpack_require__(441); +var GeomPolygon = __webpack_require__(213); +var Shape = __webpack_require__(33); +var Smooth = __webpack_require__(444); + +/** + * @classdesc + * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Polygon Shape is created by providing a list of points, which are then used to create an + * internal Polygon geometry object. The points can be set from a variety of formats: + * + * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending + * on the coordinates of the points provided, the final shape may be rendered offset from its origin. + * + * @class Polygon + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {any} [points] - The points that make up the polygon. + * @param {number} [fillColor] - The color the polygon will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Polygon = new Class({ + + Extends: Shape, + + Mixins: [ + PolygonRender + ], + + initialize: + + function Polygon (scene, x, y, points, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + Shape.call(this, scene, 'Polygon', new GeomPolygon(points)); + + var bounds = GetAABB(this.geom); + + this.setPosition(x, y); + this.setSize(bounds.width, bounds.height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Smooths the polygon over the number of iterations specified. + * The base polygon data will be updated and replaced with the smoothed values. + * This call can be chained. + * + * @method Phaser.GameObjects.Polygon#smooth + * @since 3.13.0 + * + * @param {integer} [iterations=1] - The number of times to apply the polygon smoothing. + * + * @return {this} This Game Object instance. + */ + smooth: function (iterations) + { + if (iterations === undefined) { iterations = 1; } + + for (var i = 0; i < iterations; i++) + { + Smooth(this.geom); + } + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Polygon#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var points = this.geom.points; + + for (var i = 0; i < points.length; i++) + { + path.push(points[i].x, points[i].y); + } + + path.push(points[0].x, points[0].y); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Polygon; + + +/***/ }), +/* 441 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +/** + * Calculates the bounding AABB rectangle of a polygon. + * + * @function Phaser.Geom.Polygon.GetAABB + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The polygon that should be calculated. + * @param {(Phaser.Geom.Rectangle|object)} [out] - The rectangle or object that has x, y, width, and height properties to store the result. Optional. + * + * @return {(Phaser.Geom.Rectangle|object)} The resulting rectangle or object that is passed in with position and dimensions of the polygon's AABB. + */ +var GetAABB = function (polygon, out) +{ + if (out === undefined) { out = new Rectangle(); } + + var minX = Infinity; + var minY = Infinity; + var maxX = -minX; + var maxY = -minY; + var p; + + for (var i = 0; i < polygon.points.length; i++) + { + p = polygon.points[i]; + + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + + out.x = minX; + out.y = minY; + out.width = maxX - minX; + out.height = maxY - minY; + + return out; +}; + +module.exports = GetAABB; + + +/***/ }), +/* 442 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = __webpack_require__(62); +var Line = __webpack_require__(61); +var Perimeter = __webpack_require__(443); + +/** + * Returns an array of Point 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 {integer} 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 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.Geom.Point[]} An array of Point objects pertaining to the points around the perimeter of the Polygon. + */ +var GetPoints = function (polygon, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + var points = polygon.points; + var perimeter = Perimeter(polygon); + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = perimeter / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var position = perimeter * (i / quantity); + var accumulatedPerimeter = 0; + + for (var j = 0; j < points.length; j++) + { + var pointA = points[j]; + var pointB = points[(j + 1) % points.length]; + var line = new Line( + pointA.x, + pointA.y, + pointB.x, + pointB.y + ); + var length = Length(line); + + if (position < accumulatedPerimeter || position > accumulatedPerimeter + length) + { + accumulatedPerimeter += length; + continue; + } + + var point = line.getPoint((position - accumulatedPerimeter) / length); + out.push(point); + + break; + } + } + + return out; +}; + +module.exports = GetPoints; + + +/***/ }), +/* 443 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = __webpack_require__(62); +var Line = __webpack_require__(61); + +/** + * Returns the perimeter of the given Polygon. + * + * @function Phaser.Geom.Polygon.Perimeter + * @since 3.12.0 + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to get the perimeter of. + * + * @return {number} The perimeter of the Polygon. + */ +var Perimeter = function (polygon) +{ + var points = polygon.points; + var perimeter = 0; + + for (var i = 0; i < points.length; i++) + { + var pointA = points[i]; + var pointB = points[(i + 1) % points.length]; + var line = new Line( + pointA.x, + pointA.y, + pointB.x, + pointB.y + ); + + perimeter += Length(line); + } + + return perimeter; +}; + +module.exports = Perimeter; + + +/***/ }), +/* 444 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @author Igor Ognichenko + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +var copy = function (out, a) +{ + out[0] = a[0]; + out[1] = a[1]; + + return out; +}; + +/** + * Takes a Polygon object and applies Chaikin's smoothing algorithm on its points. + * + * @function Phaser.Geom.Polygon.Smooth + * @since 3.13.0 + * + * @generic {Phaser.Geom.Polygon} O - [polygon,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The polygon to be smoothed. The polygon will be modified in-place and returned. + * + * @return {Phaser.Geom.Polygon} The input polygon. + */ +var Smooth = function (polygon) +{ + var i; + var points = []; + var data = polygon.points; + + for (i = 0; i < data.length; i++) + { + points.push([ data[i].x, data[i].y ]); + } + + var output = []; + + if (points.length > 0) + { + output.push(copy([ 0, 0 ], points[0])); + } + + for (i = 0; i < points.length - 1; i++) + { + var p0 = points[i]; + var p1 = points[i + 1]; + var p0x = p0[0]; + var p0y = p0[1]; + var p1x = p1[0]; + var p1y = p1[1]; + + output.push([ 0.85 * p0x + 0.15 * p1x, 0.85 * p0y + 0.15 * p1y ]); + output.push([ 0.15 * p0x + 0.85 * p1x, 0.15 * p0y + 0.85 * p1y ]); + } + + if (points.length > 1) + { + output.push(copy([ 0, 0 ], points[points.length - 1])); + } + + return polygon.setTo(output); +}; + +module.exports = Smooth; + + +/***/ }), +/* 445 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GeomRectangle = __webpack_require__(11); +var Shape = __webpack_require__(33); +var RectangleRender = __webpack_require__(1051); + +/** + * @classdesc + * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * You can change the size of the rectangle by changing the `width` and `height` properties. + * + * @class Rectangle + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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 {number} [width=128] - The width of the rectangle. + * @param {number} [height=128] - The height of the rectangle. + * @param {number} [fillColor] - The color the rectangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Rectangle = new Class({ + + Extends: Shape, + + Mixins: [ + RectangleRender + ], + + initialize: + + function Rectangle (scene, x, y, width, height, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + + Shape.call(this, scene, 'Rectangle', new GeomRectangle(0, 0, width, height)); + + this.setPosition(x, y); + this.setSize(width, height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Rectangle#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var rect = this.geom; + var line = this._tempLine; + + rect.getLineA(line); + + path.push(line.x1, line.y1, line.x2, line.y2); + + rect.getLineB(line); + + path.push(line.x2, line.y2); + + rect.getLineC(line); + + path.push(line.x2, line.y2); + + rect.getLineD(line); + + path.push(line.x2, line.y2); + + this.pathData = path; + + return this; + } + +}); + +module.exports = Rectangle; + + +/***/ }), +/* 446 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var StarRender = __webpack_require__(1054); +var Class = __webpack_require__(0); +var Earcut = __webpack_require__(72); +var Shape = __webpack_require__(33); + +/** + * @classdesc + * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * As the name implies, the Star shape will display a star in your game. You can control several + * aspects of it including the number of points that constitute the star. The default is 5. If + * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky + * star shape. + * + * You can also control the inner and outer radius, which is how 'long' each point of the star is. + * Modify these values to create more interesting shapes. + * + * @class Star + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [points=5] - The number of points on the star. + * @param {number} [innerRadius=32] - The inner radius of the star. + * @param {number} [outerRadius=64] - The outer radius of the star. + * @param {number} [fillColor] - The color the star will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Star = new Class({ + + Extends: Shape, + + Mixins: [ + StarRender + ], + + initialize: + + function Star (scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (points === undefined) { points = 5; } + if (innerRadius === undefined) { innerRadius = 32; } + if (outerRadius === undefined) { outerRadius = 64; } + + Shape.call(this, scene, 'Star', null); + + /** + * Private internal value. + * The number of points in the star. + * + * @name Phaser.GameObjects.Star#_points + * @type {integer} + * @private + * @since 3.13.0 + */ + this._points = points; + + /** + * Private internal value. + * The inner radius of the star. + * + * @name Phaser.GameObjects.Star#_innerRadius + * @type {number} + * @private + * @since 3.13.0 + */ + this._innerRadius = innerRadius; + + /** + * Private internal value. + * The outer radius of the star. + * + * @name Phaser.GameObjects.Star#_outerRadius + * @type {number} + * @private + * @since 3.13.0 + */ + this._outerRadius = outerRadius; + + this.setPosition(x, y); + this.setSize(outerRadius * 2, outerRadius * 2); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Sets the number of points that make up the Star shape. + * This call can be chained. + * + * @method Phaser.GameObjects.Star#setPoints + * @since 3.13.0 + * + * @param {integer} value - The amount of points the Star will have. + * + * @return {this} This Game Object instance. + */ + setPoints: function (value) + { + this._points = value; + + return this.updateData(); + }, + + /** + * Sets the inner radius of the Star shape. + * This call can be chained. + * + * @method Phaser.GameObjects.Star#setInnerRadius + * @since 3.13.0 + * + * @param {number} value - The amount to set the inner radius to. + * + * @return {this} This Game Object instance. + */ + setInnerRadius: function (value) + { + this._innerRadius = value; + + return this.updateData(); + }, + + /** + * Sets the outer radius of the Star shape. + * This call can be chained. + * + * @method Phaser.GameObjects.Star#setOuterRadius + * @since 3.13.0 + * + * @param {number} value - The amount to set the outer radius to. + * + * @return {this} This Game Object instance. + */ + setOuterRadius: function (value) + { + this._outerRadius = value; + + return this.updateData(); + }, + + /** + * The number of points that make up the Star shape. + * + * @name Phaser.GameObjects.Star#points + * @type {integer} + * @default 5 + * @since 3.13.0 + */ + points: { + + get: function () + { + return this._points; + }, + + set: function (value) + { + this._points = value; + + this.updateData(); + } + + }, + + /** + * The inner radius of the Star shape. + * + * @name Phaser.GameObjects.Star#innerRadius + * @type {number} + * @default 32 + * @since 3.13.0 + */ + innerRadius: { + + get: function () + { + return this._innerRadius; + }, + + set: function (value) + { + this._innerRadius = value; + + this.updateData(); + } + + }, + + /** + * The outer radius of the Star shape. + * + * @name Phaser.GameObjects.Star#outerRadius + * @type {number} + * @default 64 + * @since 3.13.0 + */ + outerRadius: { + + get: function () + { + return this._outerRadius; + }, + + set: function (value) + { + this._outerRadius = value; + + this.updateData(); + } + + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Star#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + + var points = this._points; + var innerRadius = this._innerRadius; + var outerRadius = this._outerRadius; + + var rot = Math.PI / 2 * 3; + var step = Math.PI / points; + + // So origin 0.5 = the center of the star + var x = outerRadius; + var y = outerRadius; + + path.push(x, y + -outerRadius); + + for (var i = 0; i < points; i++) + { + path.push(x + Math.cos(rot) * outerRadius, y + Math.sin(rot) * outerRadius); + + rot += step; + + path.push(x + Math.cos(rot) * innerRadius, y + Math.sin(rot) * innerRadius); + + rot += step; + } + + path.push(x, y + -outerRadius); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Star; + + +/***/ }), +/* 447 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Shape = __webpack_require__(33); +var GeomTriangle = __webpack_require__(76); +var TriangleRender = __webpack_require__(1057); + +/** + * @classdesc + * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the + * position of each point of these lines. The triangle is always closed and cannot have an open + * face. If you require that, consider using a Polygon instead. + * + * @class Triangle + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the first point in the triangle. + * @param {number} [y1=128] - The vertical position of the first point in the triangle. + * @param {number} [x2=64] - The horizontal position of the second point in the triangle. + * @param {number} [y2=0] - The vertical position of the second point in the triangle. + * @param {number} [x3=128] - The horizontal position of the third point in the triangle. + * @param {number} [y3=128] - The vertical position of the third point in the triangle. + * @param {number} [fillColor] - The color the triangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Triangle = new Class({ + + Extends: Shape, + + Mixins: [ + TriangleRender + ], + + initialize: + + function Triangle (scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 128; } + if (x2 === undefined) { x2 = 64; } + if (y2 === undefined) { y2 = 0; } + if (x3 === undefined) { x3 = 128; } + if (y3 === undefined) { y3 = 128; } + + Shape.call(this, scene, 'Triangle', new GeomTriangle(x1, y1, x2, y2, x3, y3)); + + var width = this.geom.right - this.geom.left; + var height = this.geom.bottom - this.geom.top; + + this.setPosition(x, y); + this.setSize(width, height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Sets the data for the lines that make up this Triangle shape. + * + * @method Phaser.GameObjects.Triangle#setTo + * @since 3.13.0 + * + * @param {number} [x1=0] - The horizontal position of the first point in the triangle. + * @param {number} [y1=0] - The vertical position of the first point in the triangle. + * @param {number} [x2=0] - The horizontal position of the second point in the triangle. + * @param {number} [y2=0] - The vertical position of the second point in the triangle. + * @param {number} [x3=0] - The horizontal position of the third point in the triangle. + * @param {number} [y3=0] - The vertical position of the third point in the triangle. + * + * @return {this} This Game Object instance. + */ + setTo: function (x1, y1, x2, y2, x3, y3) + { + this.geom.setTo(x1, y1, x2, y2, x3, y3); + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Triangle#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var tri = this.geom; + var line = this._tempLine; + + tri.getLineA(line); + + path.push(line.x1, line.y1, line.x2, line.y2); + + tri.getLineB(line); + + path.push(line.x2, line.y2); + + tri.getLineC(line); + + path.push(line.x2, line.y2); + + this.pathData = path; + + return this; + } + +}); + +module.exports = Triangle; + + +/***/ }), +/* 448 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var Length = __webpack_require__(62); + +/** + * Returns a Point from around the perimeter of a Triangle. + * + * @function Phaser.Geom.Triangle.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the point on its perimeter from. + * @param {number} position - The position along the perimeter of the triangle. A value between 0 and 1. + * @param {(Phaser.Geom.Point|object)} [out] - An option Point, or Point-like object to store the value in. If not given a new Point will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point object containing the given position from the perimeter of the triangle. + */ +var GetPoint = function (triangle, position, out) +{ + if (out === undefined) { out = new Point(); } + + var line1 = triangle.getLineA(); + var line2 = triangle.getLineB(); + var line3 = triangle.getLineC(); + + if (position <= 0 || position >= 1) + { + out.x = line1.x1; + out.y = line1.y1; + + return out; + } + + var length1 = Length(line1); + var length2 = Length(line2); + var length3 = Length(line3); + + var perimeter = length1 + length2 + length3; + + var p = perimeter * position; + var localPosition = 0; + + // Which line is it on? + + if (p < length1) + { + // Line 1 + localPosition = p / length1; + + out.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; + out.y = line1.y1 + (line1.y2 - line1.y1) * localPosition; + } + else if (p > length1 + length2) + { + // Line 3 + p -= length1 + length2; + localPosition = p / length3; + + out.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; + out.y = line3.y1 + (line3.y2 - line3.y1) * localPosition; + } + else + { + // Line 2 + p -= length1; + localPosition = p / length2; + + out.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; + out.y = line2.y1 + (line2.y2 - line2.y1) * localPosition; + } + + return out; +}; + +module.exports = GetPoint; + + +/***/ }), +/* 449 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = __webpack_require__(62); +var Point = __webpack_require__(4); + +/** + * Returns an array of evenly spaced points on the perimeter of a Triangle. + * + * @function Phaser.Geom.Triangle.GetPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the points from. + * @param {integer} 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 between each returned point. + * @param {(array|Phaser.Geom.Point[])} [out] - An array to which the points should be appended. + * + * @return {(array|Phaser.Geom.Point[])} The modified `out` array, or a new array if none was provided. + */ +var GetPoints = function (triangle, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + var line1 = triangle.getLineA(); + var line2 = triangle.getLineB(); + var line3 = triangle.getLineC(); + + var length1 = Length(line1); + var length2 = Length(line2); + var length3 = Length(line3); + + var perimeter = length1 + length2 + length3; + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = perimeter / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var p = perimeter * (i / quantity); + var localPosition = 0; + + var point = new Point(); + + // Which line is it on? + + if (p < length1) + { + // Line 1 + localPosition = p / length1; + + point.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; + point.y = line1.y1 + (line1.y2 - line1.y1) * localPosition; + } + else if (p > length1 + length2) + { + // Line 3 + p -= length1 + length2; + localPosition = p / length3; + + point.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; + point.y = line3.y1 + (line3.y2 - line3.y1) * localPosition; + } + else + { + // Line 2 + p -= length1; + localPosition = p / length2; + + point.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; + point.y = line2.y1 + (line2.y2 - line2.y1) * localPosition; + } + + out.push(point); + } + + return out; +}; + +module.exports = GetPoints; + + +/***/ }), +/* 450 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets a value in an object, allowing for dot notation to control the depth of the property. + * + * For example: + * + * ```javascript + * var data = { + * world: { + * position: { + * x: 200, + * y: 100 + * } + * } + * }; + * + * SetValue(data, 'world.position.y', 300); + * + * console.log(data.world.position.y); // 300 + * ``` + * + * @function Phaser.Utils.Objects.SetValue + * @since 3.17.0 + * + * @param {object} source - The object to set the value in. + * @param {string} key - The name of the property in the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) + * @param {any} value - The value to set into the property, if found in the source object. + * + * @return {boolean} `true` if the property key was valid and the value was set, otherwise `false`. + */ +var SetValue = function (source, key, value) +{ + if (!source || typeof source === 'number') + { + return false; + } + else if (source.hasOwnProperty(key)) + { + source[key] = value; + + return true; + } + else if (key.indexOf('.') !== -1) + { + var keys = key.split('.'); + var parent = source; + var prev = source; + + // Use for loop here so we can break early + for (var i = 0; i < keys.length; i++) + { + if (parent.hasOwnProperty(keys[i])) + { + // Yes it has a key property, let's carry on down + prev = parent; + parent = parent[keys[i]]; + } + else + { + return false; + } + } + + prev[keys[keys.length - 1]] = value; + + return true; + } + + return false; +}; + +module.exports = SetValue; + + +/***/ }), +/* 451 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Utils = __webpack_require__(10); + +/** + * @classdesc + * A 2D point light. + * + * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`. + * + * Any Game Objects using the Light2D pipeline will then be affected by these Lights. + * + * They can also simply be used to represent a point light for your own purposes. + * + * @class Light + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the light. + * @param {number} y - The vertical position of the light. + * @param {number} radius - The radius of the light. + * @param {number} r - The red color of the light. A value between 0 and 1. + * @param {number} g - The green color of the light. A value between 0 and 1. + * @param {number} b - The blue color of the light. A value between 0 and 1. + * @param {number} intensity - The intensity of the light. + */ +var Light = new Class({ + + initialize: + + function Light (x, y, radius, r, g, b, intensity) + { + /** + * The horizontal position of the light. + * + * @name Phaser.GameObjects.Light#x + * @type {number} + * @since 3.0.0 + */ + this.x = x; + + /** + * The vertical position of the light. + * + * @name Phaser.GameObjects.Light#y + * @type {number} + * @since 3.0.0 + */ + this.y = y; + + /** + * The radius of the light. + * + * @name Phaser.GameObjects.Light#radius + * @type {number} + * @since 3.0.0 + */ + this.radius = radius; + + /** + * The red color of the light. A value between 0 and 1. + * + * @name Phaser.GameObjects.Light#r + * @type {number} + * @since 3.0.0 + */ + this.r = r; + + /** + * The green color of the light. A value between 0 and 1. + * + * @name Phaser.GameObjects.Light#g + * @type {number} + * @since 3.0.0 + */ + this.g = g; + + /** + * The blue color of the light. A value between 0 and 1. + * + * @name Phaser.GameObjects.Light#b + * @type {number} + * @since 3.0.0 + */ + this.b = b; + + /** + * The intensity of the light. + * + * @name Phaser.GameObjects.Light#intensity + * @type {number} + * @since 3.0.0 + */ + this.intensity = intensity; + + /** + * The horizontal scroll factor of the light. + * + * @name Phaser.GameObjects.Light#scrollFactorX + * @type {number} + * @since 3.0.0 + */ + this.scrollFactorX = 1.0; + + /** + * The vertical scroll factor of the light. + * + * @name Phaser.GameObjects.Light#scrollFactorY + * @type {number} + * @since 3.0.0 + */ + this.scrollFactorY = 1.0; + }, + + /** + * Set the properties of the light. + * + * Sets both horizontal and vertical scroll factor to 1. Use {@link Phaser.GameObjects.Light#setScrollFactor} to set + * the scroll factor. + * + * @method Phaser.GameObjects.Light#set + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the light. + * @param {number} y - The vertical position of the light. + * @param {number} radius - The radius of the light. + * @param {number} r - The red color. A value between 0 and 1. + * @param {number} g - The green color. A value between 0 and 1. + * @param {number} b - The blue color. A value between 0 and 1. + * @param {number} intensity - The intensity of the light. + * + * @return {Phaser.GameObjects.Light} This Light object. + */ + set: function (x, y, radius, r, g, b, intensity) + { + this.x = x; + this.y = y; + + this.radius = radius; + + this.r = r; + this.g = g; + this.b = b; + + this.intensity = intensity; + + this.scrollFactorX = 1; + this.scrollFactorY = 1; + + return this; + }, + + /** + * Set the scroll factor of the light. + * + * @method Phaser.GameObjects.Light#setScrollFactor + * @since 3.0.0 + * + * @param {number} x - The horizontal scroll factor of the light. + * @param {number} y - The vertical scroll factor of the light. + * + * @return {Phaser.GameObjects.Light} This Light object. + */ + setScrollFactor: function (x, y) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + this.scrollFactorX = x; + this.scrollFactorY = y; + + return this; + }, + + /** + * Set the color of the light from a single integer RGB value. + * + * @method Phaser.GameObjects.Light#setColor + * @since 3.0.0 + * + * @param {number} rgb - The integer RGB color of the light. + * + * @return {Phaser.GameObjects.Light} This Light object. + */ + setColor: function (rgb) + { + var color = Utils.getFloatsFromUintRGB(rgb); + + this.r = color[0]; + this.g = color[1]; + this.b = color[2]; + + return this; + }, + + /** + * Set the intensity of the light. + * + * @method Phaser.GameObjects.Light#setIntensity + * @since 3.0.0 + * + * @param {number} intensity - The intensity of the light. + * + * @return {Phaser.GameObjects.Light} This Light object. + */ + setIntensity: function (intensity) + { + this.intensity = intensity; + + return this; + }, + + /** + * Set the position of the light. + * + * @method Phaser.GameObjects.Light#setPosition + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the light. + * @param {number} y - The vertical position of the light. + * + * @return {Phaser.GameObjects.Light} This Light object. + */ + setPosition: function (x, y) + { + this.x = x; + this.y = y; + + return this; + }, + + /** + * Set the radius of the light. + * + * @method Phaser.GameObjects.Light#setRadius + * @since 3.0.0 + * + * @param {number} radius - The radius of the light. + * + * @return {Phaser.GameObjects.Light} This Light object. + */ + setRadius: function (radius) + { + this.radius = radius; + + return this; + } + +}); + +module.exports = Light; + + +/***/ }), +/* 452 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Light = __webpack_require__(451); +var Utils = __webpack_require__(10); + +/** + * @callback LightForEach + * + * @param {Phaser.GameObjects.Light} light - The Light. + */ + +/** + * @classdesc + * Manages Lights for a Scene. + * + * Affects the rendering of Game Objects using the `Light2D` pipeline. + * + * @class LightsManager + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + */ +var LightsManager = new Class({ + + initialize: + + function LightsManager () + { + /** + * The pool of Lights. + * + * Used to recycle removed Lights for a more efficient use of memory. + * + * @name Phaser.GameObjects.LightsManager#lightPool + * @type {Phaser.GameObjects.Light[]} + * @default [] + * @since 3.0.0 + */ + this.lightPool = []; + + /** + * The Lights in the Scene. + * + * @name Phaser.GameObjects.LightsManager#lights + * @type {Phaser.GameObjects.Light[]} + * @default [] + * @since 3.0.0 + */ + this.lights = []; + + /** + * Lights that have been culled from a Camera's viewport. + * + * Lights in this list will not be rendered. + * + * @name Phaser.GameObjects.LightsManager#culledLights + * @type {Phaser.GameObjects.Light[]} + * @default [] + * @since 3.0.0 + */ + this.culledLights = []; + + /** + * The ambient color. + * + * @name Phaser.GameObjects.LightsManager#ambientColor + * @type {{ r: number, g: number, b: number }} + * @since 3.0.0 + */ + this.ambientColor = { r: 0.1, g: 0.1, b: 0.1 }; + + /** + * Whether the Lights Manager is enabled. + * + * @name Phaser.GameObjects.LightsManager#active + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.active = false; + + /** + * The maximum number of lights that a single Camera and the lights shader can process. + * Change this via the `maxLights` property in your game config, as it cannot be changed at runtime. + * + * @name Phaser.GameObjects.LightsManager#maxLights + * @type {integer} + * @readonly + * @since 3.15.0 + */ + this.maxLights = -1; + }, + + /** + * Enable the Lights Manager. + * + * @method Phaser.GameObjects.LightsManager#enable + * @since 3.0.0 + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + enable: function () + { + if (this.maxLights === -1) + { + this.maxLights = this.scene.sys.game.renderer.config.maxLights; + } + + this.active = true; + + return this; + }, + + /** + * Disable the Lights Manager. + * + * @method Phaser.GameObjects.LightsManager#disable + * @since 3.0.0 + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + disable: function () + { + this.active = false; + + return this; + }, + + /** + * Cull any Lights that aren't visible to the given Camera. + * + * Culling Lights improves performance by ensuring that only Lights within a Camera's viewport are rendered. + * + * @method Phaser.GameObjects.LightsManager#cull + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to cull Lights for. + * + * @return {Phaser.GameObjects.Light[]} The culled Lights. + */ + cull: function (camera) + { + var lights = this.lights; + var culledLights = this.culledLights; + var length = lights.length; + var cameraCenterX = camera.x + camera.width / 2.0; + var cameraCenterY = camera.y + camera.height / 2.0; + var cameraRadius = (camera.width + camera.height) / 2.0; + var point = { x: 0, y: 0 }; + var cameraMatrix = camera.matrix; + var viewportHeight = this.systems.game.config.height; + + culledLights.length = 0; + + for (var index = 0; index < length && culledLights.length < this.maxLights; index++) + { + var light = lights[index]; + + cameraMatrix.transformPoint(light.x, light.y, point); + + // We'll just use bounding spheres to test if lights should be rendered + var dx = cameraCenterX - (point.x - (camera.scrollX * light.scrollFactorX * camera.zoom)); + var dy = cameraCenterY - (viewportHeight - (point.y - (camera.scrollY * light.scrollFactorY) * camera.zoom)); + var distance = Math.sqrt(dx * dx + dy * dy); + + if (distance < light.radius + cameraRadius) + { + culledLights.push(lights[index]); + } + } + + return culledLights; + }, + + /** + * Iterate over each Light with a callback. + * + * @method Phaser.GameObjects.LightsManager#forEachLight + * @since 3.0.0 + * + * @param {LightForEach} callback - The callback that is called with each Light. + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + forEachLight: function (callback) + { + if (!callback) + { + return; + } + + var lights = this.lights; + var length = lights.length; + + for (var index = 0; index < length; ++index) + { + callback(lights[index]); + } + + return this; + }, + + /** + * Set the ambient light color. + * + * @method Phaser.GameObjects.LightsManager#setAmbientColor + * @since 3.0.0 + * + * @param {number} rgb - The integer RGB color of the ambient light. + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + setAmbientColor: function (rgb) + { + var color = Utils.getFloatsFromUintRGB(rgb); + + this.ambientColor.r = color[0]; + this.ambientColor.g = color[1]; + this.ambientColor.b = color[2]; + + return this; + }, + + /** + * Returns the maximum number of Lights allowed to appear at once. + * + * @method Phaser.GameObjects.LightsManager#getMaxVisibleLights + * @since 3.0.0 + * + * @return {integer} The maximum number of Lights allowed to appear at once. + */ + getMaxVisibleLights: function () + { + return 10; + }, + + /** + * Get the number of Lights managed by this Lights Manager. + * + * @method Phaser.GameObjects.LightsManager#getLightCount + * @since 3.0.0 + * + * @return {integer} The number of Lights managed by this Lights Manager. + */ + getLightCount: function () + { + return this.lights.length; + }, + + /** + * Add a Light. + * + * @method Phaser.GameObjects.LightsManager#addLight + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal position of the Light. + * @param {number} [y=0] - The vertical position of the Light. + * @param {number} [radius=100] - The radius of the Light. + * @param {number} [rgb=0xffffff] - The integer RGB color of the light. + * @param {number} [intensity=1] - The intensity of the Light. + * + * @return {Phaser.GameObjects.Light} The Light that was added. + */ + addLight: function (x, y, radius, rgb, intensity) + { + var color = null; + var light = null; + + x = (x === undefined) ? 0.0 : x; + y = (y === undefined) ? 0.0 : y; + rgb = (rgb === undefined) ? 0xffffff : rgb; + radius = (radius === undefined) ? 100.0 : radius; + intensity = (intensity === undefined) ? 1.0 : intensity; + + color = Utils.getFloatsFromUintRGB(rgb); + light = null; + + if (this.lightPool.length > 0) + { + light = this.lightPool.pop(); + light.set(x, y, radius, color[0], color[1], color[2], intensity); + } + else + { + light = new Light(x, y, radius, color[0], color[1], color[2], intensity); + } + + this.lights.push(light); + + return light; + }, + + /** + * Remove a Light. + * + * @method Phaser.GameObjects.LightsManager#removeLight + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Light} light - The Light to remove. + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + removeLight: function (light) + { + var index = this.lights.indexOf(light); + + if (index >= 0) + { + this.lightPool.push(light); + this.lights.splice(index, 1); + } + + return this; + }, + + /** + * Shut down the Lights Manager. + * + * Recycles all active Lights into the Light pool, resets ambient light color and clears the lists of Lights and + * culled Lights. + * + * @method Phaser.GameObjects.LightsManager#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + while (this.lights.length > 0) + { + this.lightPool.push(this.lights.pop()); + } + + this.ambientColor = { r: 0.1, g: 0.1, b: 0.1 }; + this.culledLights.length = 0; + this.lights.length = 0; + }, + + /** + * Destroy the Lights Manager. + * + * Cleans up all references by calling {@link Phaser.GameObjects.LightsManager#shutdown}. + * + * @method Phaser.GameObjects.LightsManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + } + +}); + +module.exports = LightsManager; + + +/***/ }), +/* 453 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(52); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Geom + */ + +var Geom = { + + Circle: __webpack_require__(1115), + Ellipse: __webpack_require__(1125), + Intersects: __webpack_require__(454), + Line: __webpack_require__(1144), + Point: __webpack_require__(1165), + Polygon: __webpack_require__(1179), + Rectangle: __webpack_require__(467), + Triangle: __webpack_require__(1209) + +}; + +// Merge in the consts +Geom = Extend(false, Geom, CONST); + +module.exports = Geom; + + +/***/ }), +/* 454 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Geom.Intersects + */ + +module.exports = { + + CircleToCircle: __webpack_require__(217), + CircleToRectangle: __webpack_require__(218), + GetCircleToCircle: __webpack_require__(1135), + GetCircleToRectangle: __webpack_require__(1136), + GetLineToCircle: __webpack_require__(219), + GetLineToRectangle: __webpack_require__(221), + GetRectangleIntersection: __webpack_require__(1137), + GetRectangleToRectangle: __webpack_require__(1138), + GetRectangleToTriangle: __webpack_require__(1139), + GetTriangleToCircle: __webpack_require__(1140), + GetTriangleToLine: __webpack_require__(459), + GetTriangleToTriangle: __webpack_require__(1141), + LineToCircle: __webpack_require__(220), + LineToLine: __webpack_require__(93), + LineToRectangle: __webpack_require__(455), + PointToLine: __webpack_require__(463), + PointToLineSegment: __webpack_require__(1142), + RectangleToRectangle: __webpack_require__(140), + RectangleToTriangle: __webpack_require__(456), + RectangleToValues: __webpack_require__(1143), + TriangleToCircle: __webpack_require__(458), + TriangleToLine: __webpack_require__(460), + TriangleToTriangle: __webpack_require__(461) + +}; + + +/***/ }), +/* 455 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like + * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. + * + * An intersection is considered valid if: + * + * The line starts within, or ends within, the Rectangle. + * The line segment intersects one of the 4 rectangle edges. + * + * The for the purposes of this function rectangles are considered 'solid'. + * + * @function Phaser.Geom.Intersects.LineToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The Line to check for intersection. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle to check for intersection. + * + * @return {boolean} `true` if the Line and the Rectangle intersect, `false` otherwise. + */ +var LineToRectangle = function (line, rect) +{ + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; +}; + +module.exports = LineToRectangle; + + +/***/ }), +/* 456 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LineToLine = __webpack_require__(93); +var Contains = __webpack_require__(53); +var ContainsArray = __webpack_require__(222); +var Decompose = __webpack_require__(457); + +/** + * Checks for intersection between Rectangle shape and Triangle shape. + * + * @function Phaser.Geom.Intersects.RectangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - Rectangle object to test. + * @param {Phaser.Geom.Triangle} triangle - Triangle object to test. + * + * @return {boolean} A value of `true` if objects intersect; otherwise `false`. + */ +var RectangleToTriangle = function (rect, triangle) +{ + // First the cheapest ones: + + if ( + triangle.left > rect.right || + triangle.right < rect.left || + triangle.top > rect.bottom || + triangle.bottom < rect.top) + { + return false; + } + + var triA = triangle.getLineA(); + var triB = triangle.getLineB(); + var triC = triangle.getLineC(); + + // Are any of the triangle points within the rectangle? + + if (Contains(rect, triA.x1, triA.y1) || Contains(rect, triA.x2, triA.y2)) + { + return true; + } + + if (Contains(rect, triB.x1, triB.y1) || Contains(rect, triB.x2, triB.y2)) + { + return true; + } + + if (Contains(rect, triC.x1, triC.y1) || Contains(rect, triC.x2, triC.y2)) + { + return true; + } + + // Cheap tests over, now to see if any of the lines intersect ... + + var rectA = rect.getLineA(); + var rectB = rect.getLineB(); + var rectC = rect.getLineC(); + var rectD = rect.getLineD(); + + if (LineToLine(triA, rectA) || LineToLine(triA, rectB) || LineToLine(triA, rectC) || LineToLine(triA, rectD)) + { + return true; + } + + if (LineToLine(triB, rectA) || LineToLine(triB, rectB) || LineToLine(triB, rectC) || LineToLine(triB, rectD)) + { + return true; + } + + if (LineToLine(triC, rectA) || LineToLine(triC, rectB) || LineToLine(triC, rectC) || LineToLine(triC, rectD)) + { + return true; + } + + // None of the lines intersect, so are any rectangle points within the triangle? + + var points = Decompose(rect); + var within = ContainsArray(triangle, points, true); + + return (within.length > 0); +}; + +module.exports = RectangleToTriangle; + + +/***/ }), +/* 457 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Create an array of points for each corner of a Rectangle + * If an array is specified, each point object will be added to the end of the array, otherwise a new array will be created. + * + * @function Phaser.Geom.Rectangle.Decompose + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle object to be decomposed. + * @param {array} [out] - If provided, each point will be added to this array. + * + * @return {array} Will return the array you specified or a new array containing the points of the Rectangle. + */ +var Decompose = function (rect, out) +{ + if (out === undefined) { out = []; } + + out.push({ x: rect.x, y: rect.y }); + out.push({ x: rect.right, y: rect.y }); + out.push({ x: rect.right, y: rect.bottom }); + out.push({ x: rect.x, y: rect.bottom }); + + return out; +}; + +module.exports = Decompose; + + +/***/ }), +/* 458 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LineToCircle = __webpack_require__(220); +var Contains = __webpack_require__(92); + +/** + * Checks if a Triangle and a Circle intersect. + * + * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. + * + * @function Phaser.Geom.Intersects.TriangleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check for intersection. + * @param {Phaser.Geom.Circle} circle - The Circle to check for intersection. + * + * @return {boolean} `true` if the Triangle and the `Circle` intersect, otherwise `false`. + */ +var TriangleToCircle = function (triangle, circle) +{ + // First the cheapest ones: + + if ( + triangle.left > circle.right || + triangle.right < circle.left || + triangle.top > circle.bottom || + triangle.bottom < circle.top) + { + return false; + } + + if (Contains(triangle, circle.x, circle.y)) + { + return true; + } + + if (LineToCircle(triangle.getLineA(), circle)) + { + return true; + } + + if (LineToCircle(triangle.getLineB(), circle)) + { + return true; + } + + if (LineToCircle(triangle.getLineC(), circle)) + { + return true; + } + + return false; +}; + +module.exports = TriangleToCircle; + + +/***/ }), +/* 459 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var TriangleToLine = __webpack_require__(460); +var LineToLine = __webpack_require__(93); + +/** + * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. + * + * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". + * + * @function Phaser.Geom.Intersects.GetTriangleToLine + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check with. + * @param {Phaser.Geom.Line} line - The Line to check with. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetTriangleToLine = function (triangle, line, out) +{ + if (out === undefined) { out = []; } + + if (TriangleToLine(triangle, line)) + { + var lineA = triangle.getLineA(); + var lineB = triangle.getLineB(); + var lineC = triangle.getLineC(); + + var output = [ new Point(), new Point(), new Point() ]; + + var result = [ + LineToLine(lineA, line, output[0]), + LineToLine(lineB, line, output[1]), + LineToLine(lineC, line, output[2]) + ]; + + for (var i = 0; i < 3; i++) + { + if (result[i]) { out.push(output[i]); } + } + } + + return out; +}; + +module.exports = GetTriangleToLine; + + +/***/ }), +/* 460 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(92); +var LineToLine = __webpack_require__(93); + +/** + * Checks if a Triangle and a Line intersect. + * + * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". + * + * @function Phaser.Geom.Intersects.TriangleToLine + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check with. + * @param {Phaser.Geom.Line} line - The Line to check with. + * + * @return {boolean} `true` if the Triangle and the Line intersect, otherwise `false`. + */ +var TriangleToLine = function (triangle, line) +{ + // If the Triangle contains either the start or end point of the line, it intersects + if (Contains(triangle, line.getPointA()) || Contains(triangle, line.getPointB())) + { + return true; + } + + // Now check the line against each line of the Triangle + if (LineToLine(triangle.getLineA(), line)) + { + return true; + } + + if (LineToLine(triangle.getLineB(), line)) + { + return true; + } + + if (LineToLine(triangle.getLineC(), line)) + { + return true; + } + + return false; +}; + +module.exports = TriangleToLine; + + +/***/ }), +/* 461 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ContainsArray = __webpack_require__(222); +var Decompose = __webpack_require__(462); +var LineToLine = __webpack_require__(93); + +/** + * Checks if two Triangles intersect. + * + * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". + * + * @function Phaser.Geom.Intersects.TriangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangleA - The first Triangle to check for intersection. + * @param {Phaser.Geom.Triangle} triangleB - The second Triangle to check for intersection. + * + * @return {boolean} `true` if the Triangles intersect, otherwise `false`. + */ +var TriangleToTriangle = function (triangleA, triangleB) +{ + // First the cheapest ones: + + if ( + triangleA.left > triangleB.right || + triangleA.right < triangleB.left || + triangleA.top > triangleB.bottom || + triangleA.bottom < triangleB.top) + { + return false; + } + + var lineAA = triangleA.getLineA(); + var lineAB = triangleA.getLineB(); + var lineAC = triangleA.getLineC(); + + var lineBA = triangleB.getLineA(); + var lineBB = triangleB.getLineB(); + var lineBC = triangleB.getLineC(); + + // Now check the lines against each line of TriangleB + if (LineToLine(lineAA, lineBA) || LineToLine(lineAA, lineBB) || LineToLine(lineAA, lineBC)) + { + return true; + } + + if (LineToLine(lineAB, lineBA) || LineToLine(lineAB, lineBB) || LineToLine(lineAB, lineBC)) + { + return true; + } + + if (LineToLine(lineAC, lineBA) || LineToLine(lineAC, lineBB) || LineToLine(lineAC, lineBC)) + { + return true; + } + + // Nope, so check to see if any of the points of triangleA are within triangleB + + var points = Decompose(triangleA); + var within = ContainsArray(triangleB, points, true); + + if (within.length > 0) + { + return true; + } + + // Finally check to see if any of the points of triangleB are within triangleA + + points = Decompose(triangleB); + within = ContainsArray(triangleA, points, true); + + if (within.length > 0) + { + return true; + } + + return false; +}; + +module.exports = TriangleToTriangle; + + +/***/ }), +/* 462 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Decomposes a Triangle into an array of its points. + * + * @function Phaser.Geom.Triangle.Decompose + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to decompose. + * @param {array} [out] - An array to store the points into. + * + * @return {array} The provided `out` array, or a new array if none was provided, with three objects with `x` and `y` properties representing each point of the Triangle appended to it. + */ +var Decompose = function (triangle, out) +{ + if (out === undefined) { out = []; } + + out.push({ x: triangle.x1, y: triangle.y1 }); + out.push({ x: triangle.x2, y: triangle.y2 }); + out.push({ x: triangle.x3, y: triangle.y3 }); + + return out; +}; + +module.exports = Decompose; + + +/***/ }), +/* 463 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @author Florian Mertens + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the 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.Geom.Point|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`. + */ +var PointToLine = function (point, line, lineThickness) +{ + if (lineThickness === undefined) { lineThickness = 1; } + + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var px = point.x; + var py = point.y; + + var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); + + if (L2 === 0) + { + return false; + } + + var r = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))) / L2; + + // Assume line thickness is circular + if (r < 0) + { + // Outside line1 + return (Math.sqrt(((x1 - px) * (x1 - px)) + ((y1 - py) * (y1 - py))) <= lineThickness); + } + else if ((r >= 0) && (r <= 1)) + { + // On the line segment + var s = (((y1 - py) * (x2 - x1)) - ((x1 - px) * (y2 - y1))) / L2; + + return (Math.abs(s) * Math.sqrt(L2) <= lineThickness); + } + else + { + // Outside line2 + return (Math.sqrt(((x2 - px) * (x2 - px)) + ((y2 - py) * (y2 - py))) <= lineThickness); + } +}; + +module.exports = PointToLine; + + +/***/ }), +/* 464 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = __webpack_require__(13); +var Wrap = __webpack_require__(63); +var Angle = __webpack_require__(94); + +/** + * Get the angle of the normal of the given line in radians. + * + * @function Phaser.Geom.Line.NormalAngle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the angle of the normal of. + * + * @return {number} The angle of the normal of the line in radians. + */ +var NormalAngle = function (line) +{ + var angle = Angle(line) - MATH_CONST.TAU; + + return Wrap(angle, -Math.PI, Math.PI); +}; + +module.exports = NormalAngle; + + +/***/ }), +/* 465 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the magnitude of the point, which equivalent to the length of the line from the origin to this point. + * + * @function Phaser.Geom.Point.GetMagnitude + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - The point to calculate the magnitude for + * + * @return {number} The resulting magnitude + */ +var GetMagnitude = function (point) +{ + return Math.sqrt((point.x * point.x) + (point.y * point.y)); +}; + +module.exports = GetMagnitude; + + +/***/ }), +/* 466 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the square of magnitude of given point.(Can be used for fast magnitude calculation of point) + * + * @function Phaser.Geom.Point.GetMagnitudeSq + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - Returns square of the magnitude/length of given point. + * + * @return {number} Returns square of the magnitude of given point. + */ +var GetMagnitudeSq = function (point) +{ + return (point.x * point.x) + (point.y * point.y); +}; + +module.exports = GetMagnitudeSq; + + +/***/ }), +/* 467 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +Rectangle.Area = __webpack_require__(1184); +Rectangle.Ceil = __webpack_require__(1185); +Rectangle.CeilAll = __webpack_require__(1186); +Rectangle.CenterOn = __webpack_require__(178); +Rectangle.Clone = __webpack_require__(1187); +Rectangle.Contains = __webpack_require__(53); +Rectangle.ContainsPoint = __webpack_require__(1188); +Rectangle.ContainsRect = __webpack_require__(468); +Rectangle.CopyFrom = __webpack_require__(1189); +Rectangle.Decompose = __webpack_require__(457); +Rectangle.Equals = __webpack_require__(1190); +Rectangle.FitInside = __webpack_require__(1191); +Rectangle.FitOutside = __webpack_require__(1192); +Rectangle.Floor = __webpack_require__(1193); +Rectangle.FloorAll = __webpack_require__(1194); +Rectangle.FromPoints = __webpack_require__(189); +Rectangle.GetAspectRatio = __webpack_require__(224); +Rectangle.GetCenter = __webpack_require__(1195); +Rectangle.GetPoint = __webpack_require__(161); +Rectangle.GetPoints = __webpack_require__(293); +Rectangle.GetSize = __webpack_require__(1196); +Rectangle.Inflate = __webpack_require__(1197); +Rectangle.Intersection = __webpack_require__(1198); +Rectangle.MarchingAnts = __webpack_require__(304); +Rectangle.MergePoints = __webpack_require__(1199); +Rectangle.MergeRect = __webpack_require__(1200); +Rectangle.MergeXY = __webpack_require__(1201); +Rectangle.Offset = __webpack_require__(1202); +Rectangle.OffsetPoint = __webpack_require__(1203); +Rectangle.Overlaps = __webpack_require__(1204); +Rectangle.Perimeter = __webpack_require__(120); +Rectangle.PerimeterPoint = __webpack_require__(1205); +Rectangle.Random = __webpack_require__(164); +Rectangle.RandomOutside = __webpack_require__(1206); +Rectangle.SameDimensions = __webpack_require__(1207); +Rectangle.Scale = __webpack_require__(1208); +Rectangle.Union = __webpack_require__(417); + +module.exports = Rectangle; + + +/***/ }), +/* 468 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tests if one rectangle fully contains another. + * + * @function Phaser.Geom.Rectangle.ContainsRect + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first rectangle. + * @param {Phaser.Geom.Rectangle} rectB - The second rectangle. + * + * @return {boolean} True only if rectA fully contains rectB. + */ +var ContainsRect = function (rectA, rectB) +{ + // Volume check (if rectB volume > rectA then rectA cannot contain it) + if ((rectB.width * rectB.height) > (rectA.width * rectA.height)) + { + return false; + } + + return ( + (rectB.x > rectA.x && rectB.x < rectA.right) && + (rectB.right > rectA.x && rectB.right < rectA.right) && + (rectB.y > rectA.y && rectB.y < rectA.bottom) && + (rectB.bottom > rectA.y && rectB.bottom < rectA.bottom) + ); +}; + +module.exports = ContainsRect; + + +/***/ }), +/* 469 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +// The three medians (the lines drawn from the vertices to the bisectors of the opposite sides) +// meet in the centroid or center of mass (center of gravity). +// The centroid divides each median in a ratio of 2:1 + +/** + * Calculates the position of a Triangle's centroid, which is also its center of mass (center of gravity). + * + * The centroid is the point in a Triangle at which its three medians (the lines drawn from the vertices to the bisectors of the opposite sides) meet. It divides each one in a 2:1 ratio. + * + * @function Phaser.Geom.Triangle.Centroid + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to use. + * @param {(Phaser.Geom.Point|object)} [out] - An object to store the coordinates in. + * + * @return {(Phaser.Geom.Point|object)} The `out` object with modified `x` and `y` properties, or a new Point if none was provided. + */ +var Centroid = function (triangle, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = (triangle.x1 + triangle.x2 + triangle.x3) / 3; + out.y = (triangle.y1 + triangle.y2 + triangle.y3) / 3; + + return out; +}; + +module.exports = Centroid; + + +/***/ }), +/* 470 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves each point (vertex) of a Triangle by a given offset, thus moving the entire Triangle by that offset. + * + * @function Phaser.Geom.Triangle.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to move. + * @param {number} x - The horizontal offset (distance) by which to move each point. Can be positive or negative. + * @param {number} y - The vertical offset (distance) by which to move each point. Can be positive or negative. + * + * @return {Phaser.Geom.Triangle} The modified Triangle. + */ +var Offset = function (triangle, x, y) +{ + triangle.x1 += x; + triangle.y1 += y; + + triangle.x2 += x; + triangle.y2 += y; + + triangle.x3 += x; + triangle.y3 += y; + + return triangle; +}; + +module.exports = Offset; + + +/***/ }), +/* 471 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +// 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. + +function getLength (x1, y1, x2, y2) +{ + var x = x1 - x2; + var y = y1 - y2; + var magnitude = (x * x) + (y * y); + + return Math.sqrt(magnitude); +} + +/** + * Calculates the position of the incenter of a Triangle object. This is the point where its three angle bisectors meet and it's also the center of the incircle, which is the circle inscribed in the triangle. + * + * @function Phaser.Geom.Triangle.InCenter + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to find the incenter of. + * @param {Phaser.Geom.Point} [out] - An optional Point in which to store the coordinates. + * + * @return {Phaser.Geom.Point} Point (x, y) of the center pixel of the triangle. + */ +var InCenter = function (triangle, out) +{ + if (out === undefined) { out = new Point(); } + + var x1 = triangle.x1; + var y1 = triangle.y1; + + var x2 = triangle.x2; + var y2 = triangle.y2; + + var x3 = triangle.x3; + var y3 = triangle.y3; + + var d1 = getLength(x3, y3, x2, y2); + var d2 = getLength(x1, y1, x3, y3); + var d3 = getLength(x2, y2, x1, y1); + + var p = d1 + d2 + d3; + + out.x = (x1 * d1 + x2 * d2 + x3 * d3) / p; + out.y = (y1 * d1 + y2 * d2 + y3 * d3) / p; + + return out; +}; + +module.exports = InCenter; + + +/***/ }), +/* 472 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates a new Interactive Object. + * + * This is called automatically by the Input Manager when you enable a Game Object for input. + * + * The resulting Interactive Object is mapped to the Game Object's `input` property. + * + * @function Phaser.Input.CreateInteractiveObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to which this Interactive Object is bound. + * @param {any} hitArea - The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. + * @param {Phaser.Types.Input.HitAreaCallback} hitAreaCallback - The 'contains' check callback that the hit area shape will use for all hit tests. + * + * @return {Phaser.Types.Input.InteractiveObject} The new Interactive Object. + */ +var CreateInteractiveObject = function (gameObject, hitArea, hitAreaCallback) +{ + return { + + gameObject: gameObject, + + enabled: true, + alwaysEnabled: false, + draggable: false, + dropZone: false, + cursor: false, + + target: null, + + camera: null, + + hitArea: hitArea, + hitAreaCallback: hitAreaCallback, + hitAreaDebug: null, + + // Has the dev specified their own shape, or is this bound to the texture size? + customHitArea: false, + + localX: 0, + localY: 0, + + // 0 = Not being dragged + // 1 = Being checked for dragging + // 2 = Being dragged + dragState: 0, + + dragStartX: 0, + dragStartY: 0, + dragStartXGlobal: 0, + dragStartYGlobal: 0, + + dragX: 0, + dragY: 0 + + }; +}; + +module.exports = CreateInteractiveObject; + + +/***/ }), +/* 473 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * Contains information about a specific Gamepad Axis. + * Axis objects are created automatically by the Gamepad as they are needed. + * + * @class Axis + * @memberof Phaser.Input.Gamepad + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Axis belongs to. + * @param {integer} index - The index of this Axis. + */ +var Axis = new Class({ + + initialize: + + function Axis (pad, index) + { + /** + * A reference to the Gamepad that this Axis belongs to. + * + * @name Phaser.Input.Gamepad.Axis#pad + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.0.0 + */ + this.pad = pad; + + /** + * An event emitter to use to emit the axis events. + * + * @name Phaser.Input.Gamepad.Axis#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = pad.events; + + /** + * The index of this Axis. + * + * @name Phaser.Input.Gamepad.Axis#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * The raw axis value, between -1 and 1 with 0 being dead center. + * Use the method `getValue` to get a normalized value with the threshold applied. + * + * @name Phaser.Input.Gamepad.Axis#value + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.value = 0; + + /** + * Movement tolerance threshold below which axis values are ignored in `getValue`. + * + * @name Phaser.Input.Gamepad.Axis#threshold + * @type {number} + * @default 0.1 + * @since 3.0.0 + */ + this.threshold = 0.1; + }, + + /** + * Internal update handler for this Axis. + * Called automatically by the Gamepad as part of its update. + * + * @method Phaser.Input.Gamepad.Axis#update + * @private + * @since 3.0.0 + * + * @param {number} value - The value of the axis movement. + */ + update: function (value) + { + this.value = value; + }, + + /** + * Applies the `threshold` value to the axis and returns it. + * + * @method Phaser.Input.Gamepad.Axis#getValue + * @since 3.0.0 + * + * @return {number} The axis value, adjusted for the movement threshold. + */ + getValue: function () + { + return (Math.abs(this.value) < this.threshold) ? 0 : this.value; + }, + + /** + * Destroys this Axis instance and releases external references it holds. + * + * @method Phaser.Input.Gamepad.Axis#destroy + * @since 3.10.0 + */ + destroy: function () + { + this.pad = null; + this.events = null; + } + +}); + +module.exports = Axis; + + +/***/ }), +/* 474 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Events = __webpack_require__(226); + +/** + * @classdesc + * Contains information about a specific button on a Gamepad. + * Button objects are created automatically by the Gamepad as they are needed. + * + * @class Button + * @memberof Phaser.Input.Gamepad + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Button belongs to. + * @param {integer} index - The index of this Button. + */ +var Button = new Class({ + + initialize: + + function Button (pad, index) + { + /** + * A reference to the Gamepad that this Button belongs to. + * + * @name Phaser.Input.Gamepad.Button#pad + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.0.0 + */ + this.pad = pad; + + /** + * An event emitter to use to emit the button events. + * + * @name Phaser.Input.Gamepad.Button#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = pad.manager; + + /** + * The index of this Button. + * + * @name Phaser.Input.Gamepad.Button#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * Between 0 and 1. + * + * @name Phaser.Input.Gamepad.Button#value + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.value = 0; + + /** + * Can be set for analogue buttons to enable a 'pressure' threshold, + * before a button is considered as being 'pressed'. + * + * @name Phaser.Input.Gamepad.Button#threshold + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.threshold = 1; + + /** + * Is the Button being pressed down or not? + * + * @name Phaser.Input.Gamepad.Button#pressed + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.pressed = false; + }, + + /** + * Internal update handler for this Button. + * Called automatically by the Gamepad as part of its update. + * + * @method Phaser.Input.Gamepad.Button#update + * @fires Phaser.Input.Gamepad.Events#BUTTON_DOWN + * @fires Phaser.Input.Gamepad.Events#BUTTON_UP + * @fires Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_DOWN + * @fires Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_UP + * @private + * @since 3.0.0 + * + * @param {number} value - The value of the button. Between 0 and 1. + */ + update: function (value) + { + this.value = value; + + var pad = this.pad; + var index = this.index; + + if (value >= this.threshold) + { + if (!this.pressed) + { + this.pressed = true; + this.events.emit(Events.BUTTON_DOWN, pad, this, value); + this.pad.emit(Events.GAMEPAD_BUTTON_DOWN, index, value, this); + } + } + else if (this.pressed) + { + this.pressed = false; + this.events.emit(Events.BUTTON_UP, pad, this, value); + this.pad.emit(Events.GAMEPAD_BUTTON_UP, index, value, this); + } + }, + + /** + * Destroys this Button instance and releases external references it holds. + * + * @method Phaser.Input.Gamepad.Button#destroy + * @since 3.10.0 + */ + destroy: function () + { + this.pad = null; + this.events = null; + } + +}); + +module.exports = Button; + + +/***/ }), +/* 475 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Axis = __webpack_require__(473); +var Button = __webpack_require__(474); +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A single Gamepad. + * + * These are created, updated and managed by the Gamepad Plugin. + * + * @class Gamepad + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Input.Gamepad + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad.GamepadPlugin} manager - A reference to the Gamepad Plugin. + * @param {Phaser.Types.Input.Gamepad.Pad} pad - The Gamepad object, as extracted from GamepadEvent. + */ +var Gamepad = new Class({ + + Extends: EventEmitter, + + initialize: + + function Gamepad (manager, pad) + { + EventEmitter.call(this); + + /** + * A reference to the Gamepad Plugin. + * + * @name Phaser.Input.Gamepad.Gamepad#manager + * @type {Phaser.Input.Gamepad.GamepadPlugin} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * A reference to the native Gamepad object that is connected to the browser. + * + * @name Phaser.Input.Gamepad.Gamepad#pad + * @type {any} + * @since 3.10.0 + */ + this.pad = pad; + + /** + * A string containing some information about the controller. + * + * This is not strictly specified, but in Firefox it will contain three pieces of information + * separated by dashes (-): two 4-digit hexadecimal strings containing the USB vendor and + * product id of the controller, and the name of the controller as provided by the driver. + * In Chrome it will contain the name of the controller as provided by the driver, + * followed by vendor and product 4-digit hexadecimal strings. + * + * @name Phaser.Input.Gamepad.Gamepad#id + * @type {string} + * @since 3.0.0 + */ + this.id = pad.id; + + /** + * An integer that is unique for each Gamepad currently connected to the system. + * This can be used to distinguish multiple controllers. + * Note that disconnecting a device and then connecting a new device may reuse the previous index. + * + * @name Phaser.Input.Gamepad.Gamepad#index + * @type {number} + * @since 3.0.0 + */ + this.index = pad.index; + + var buttons = []; + + for (var i = 0; i < pad.buttons.length; i++) + { + buttons.push(new Button(this, i)); + } + + /** + * An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad. + * + * @name Phaser.Input.Gamepad.Gamepad#buttons + * @type {Phaser.Input.Gamepad.Button[]} + * @since 3.0.0 + */ + this.buttons = buttons; + + var axes = []; + + for (i = 0; i < pad.axes.length; i++) + { + axes.push(new Axis(this, i)); + } + + /** + * An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any. + * + * @name Phaser.Input.Gamepad.Gamepad#axes + * @type {Phaser.Input.Gamepad.Axis[]} + * @since 3.0.0 + */ + this.axes = axes; + + /** + * The Gamepad's Haptic Actuator (Vibration / Rumble support). + * This is highly experimental and only set if both present on the device, + * and exposed by both the hardware and browser. + * + * @name Phaser.Input.Gamepad.Gamepad#vibration + * @type {GamepadHapticActuator} + * @since 3.10.0 + */ + this.vibration = pad.vibrationActuator; + + // https://w3c.github.io/gamepad/#remapping + + var _noButton = { value: 0, pressed: false }; + + /** + * A reference to the Left Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCLeft = (buttons[14]) ? buttons[14] : _noButton; + + /** + * A reference to the Right Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCRight = (buttons[15]) ? buttons[15] : _noButton; + + /** + * A reference to the Top Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCTop = (buttons[12]) ? buttons[12] : _noButton; + + /** + * A reference to the Bottom Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCBottom = (buttons[13]) ? buttons[13] : _noButton; + + /** + * A reference to the Left Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCLeft = (buttons[2]) ? buttons[2] : _noButton; + + /** + * A reference to the Right Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCRight = (buttons[1]) ? buttons[1] : _noButton; + + /** + * A reference to the Top Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCTop = (buttons[3]) ? buttons[3] : _noButton; + + /** + * A reference to the Bottom Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCBottom = (buttons[0]) ? buttons[0] : _noButton; + + /** + * A reference to the Top Left Front Button (L1 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBLeftTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBLeftTop = (buttons[4]) ? buttons[4] : _noButton; + + /** + * A reference to the Bottom Left Front Button (L2 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBLeftBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBLeftBottom = (buttons[6]) ? buttons[6] : _noButton; + + /** + * A reference to the Top Right Front Button (R1 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBRightTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBRightTop = (buttons[5]) ? buttons[5] : _noButton; + + /** + * A reference to the Bottom Right Front Button (R2 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBRightBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBRightBottom = (buttons[7]) ? buttons[7] : _noButton; + + var _noAxis = { value: 0 }; + + /** + * A reference to the Horizontal Axis for the Left Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_HAxisLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._HAxisLeft = (axes[0]) ? axes[0] : _noAxis; + + /** + * A reference to the Vertical Axis for the Left Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_VAxisLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._VAxisLeft = (axes[1]) ? axes[1] : _noAxis; + + /** + * A reference to the Horizontal Axis for the Right Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_HAxisRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._HAxisRight = (axes[2]) ? axes[2] : _noAxis; + + /** + * A reference to the Vertical Axis for the Right Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_VAxisRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._VAxisRight = (axes[3]) ? axes[3] : _noAxis; + + /** + * 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 + */ + this.leftStick = new Vector2(); + + /** + * 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 + */ + this.rightStick = new Vector2(); + }, + + /** + * Gets the total number of axis this Gamepad claims to support. + * + * @method Phaser.Input.Gamepad.Gamepad#getAxisTotal + * @since 3.10.0 + * + * @return {integer} The total number of axes this Gamepad claims to support. + */ + getAxisTotal: function () + { + return this.axes.length; + }, + + /** + * 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 0 and 1. + * + * @method Phaser.Input.Gamepad.Gamepad#getAxisValue + * @since 3.10.0 + * + * @param {integer} index - The index of the axes to get the value for. + * + * @return {number} The value of the axis, between 0 and 1. + */ + getAxisValue: function (index) + { + return this.axes[index].getValue(); + }, + + /** + * Sets the threshold value of all axis on this Gamepad. + * The value is a float between 0 and 1 and is the amount below which the axis is considered as not having been moved. + * + * @method Phaser.Input.Gamepad.Gamepad#setAxisThreshold + * @since 3.10.0 + * + * @param {number} value - A value between 0 and 1. + */ + setAxisThreshold: function (value) + { + for (var i = 0; i < this.axes.length; i++) + { + this.axes[i].threshold = value; + } + }, + + /** + * Gets the total number of buttons this Gamepad claims to have. + * + * @method Phaser.Input.Gamepad.Gamepad#getButtonTotal + * @since 3.10.0 + * + * @return {integer} The total number of buttons this Gamepad claims to have. + */ + getButtonTotal: function () + { + return this.buttons.length; + }, + + /** + * 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 an analogue button, or a float between 0 and 1 + * for a pressure-sensitive digital button, such as the shoulder buttons on a Dual Shock. + * + * @method Phaser.Input.Gamepad.Gamepad#getButtonValue + * @since 3.10.0 + * + * @param {integer} index - The index of the button to get the value for. + * + * @return {number} The value of the button, between 0 and 1. + */ + getButtonValue: function (index) + { + return this.buttons[index].value; + }, + + /** + * Returns if the button is pressed down or not. + * The index must be valid within the range of buttons supported by this Gamepad. + * + * @method Phaser.Input.Gamepad.Gamepad#isButtonDown + * @since 3.10.0 + * + * @param {integer} index - The index of the button to get the value for. + * + * @return {boolean} `true` if the button is considered as being pressed down, otherwise `false`. + */ + isButtonDown: function (index) + { + return this.buttons[index].pressed; + }, + + /** + * Internal update handler for this Gamepad. + * Called automatically by the Gamepad Manager as part of its update. + * + * @method Phaser.Input.Gamepad.Gamepad#update + * @private + * @since 3.0.0 + */ + update: function (pad) + { + var i; + + // Sync the button values + + var localButtons = this.buttons; + var gamepadButtons = pad.buttons; + + var len = localButtons.length; + + for (i = 0; i < len; i++) + { + localButtons[i].update(gamepadButtons[i].value); + } + + // Sync the axis values + + var localAxes = this.axes; + var gamepadAxes = pad.axes; + + len = localAxes.length; + + for (i = 0; i < len; i++) + { + localAxes[i].update(gamepadAxes[i]); + } + + if (len >= 2) + { + this.leftStick.set(localAxes[0].getValue(), localAxes[1].getValue()); + + if (len >= 4) + { + this.rightStick.set(localAxes[2].getValue(), localAxes[3].getValue()); + } + } + }, + + /** + * Destroys this Gamepad instance, its buttons and axes, and releases external references it holds. + * + * @method Phaser.Input.Gamepad.Gamepad#destroy + * @since 3.10.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.manager = null; + this.pad = null; + + var i; + + for (i = 0; i < this.buttons.length; i++) + { + this.buttons[i].destroy(); + } + + for (i = 0; i < this.axes.length; i++) + { + this.axes[i].destroy(); + } + + this.buttons = []; + this.axes = []; + }, + + /** + * Is this Gamepad currently connected or not? + * + * @name Phaser.Input.Gamepad.Gamepad#connected + * @type {boolean} + * @default true + * @since 3.0.0 + */ + connected: { + + get: function () + { + return this.pad.connected; + } + + }, + + /** + * A timestamp containing the most recent time this Gamepad was updated. + * + * @name Phaser.Input.Gamepad.Gamepad#timestamp + * @type {number} + * @since 3.0.0 + */ + timestamp: { + + get: function () + { + return this.pad.timestamp; + } + + }, + + /** + * Is the Gamepad's Left button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad left button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#left + * @type {boolean} + * @since 3.10.0 + */ + left: { + + get: function () + { + return this._LCLeft.pressed; + } + + }, + + /** + * Is the Gamepad's Right button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad right button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#right + * @type {boolean} + * @since 3.10.0 + */ + right: { + + get: function () + { + return this._LCRight.pressed; + } + + }, + + /** + * Is the Gamepad's Up button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad up button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#up + * @type {boolean} + * @since 3.10.0 + */ + up: { + + get: function () + { + return this._LCTop.pressed; + } + + }, + + /** + * Is the Gamepad's Down button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad down button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#down + * @type {boolean} + * @since 3.10.0 + */ + down: { + + get: function () + { + return this._LCBottom.pressed; + } + + }, + + /** + * Is the Gamepad's bottom button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the X button. + * On an XBox controller it's the A button. + * + * @name Phaser.Input.Gamepad.Gamepad#A + * @type {boolean} + * @since 3.10.0 + */ + A: { + + get: function () + { + return this._RCBottom.pressed; + } + + }, + + /** + * Is the Gamepad's top button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Triangle button. + * On an XBox controller it's the Y button. + * + * @name Phaser.Input.Gamepad.Gamepad#Y + * @type {boolean} + * @since 3.10.0 + */ + Y: { + + get: function () + { + return this._RCTop.pressed; + } + + }, + + /** + * Is the Gamepad's left button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Square button. + * On an XBox controller it's the X button. + * + * @name Phaser.Input.Gamepad.Gamepad#X + * @type {boolean} + * @since 3.10.0 + */ + X: { + + get: function () + { + return this._RCLeft.pressed; + } + + }, + + /** + * Is the Gamepad's right button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Circle button. + * On an XBox controller it's the B button. + * + * @name Phaser.Input.Gamepad.Gamepad#B + * @type {boolean} + * @since 3.10.0 + */ + B: { + + get: function () + { + return this._RCRight.pressed; + } + + }, + + /** + * Returns the value of the Gamepad's top left shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the L1 button. + * On an XBox controller it's the LB button. + * + * @name Phaser.Input.Gamepad.Gamepad#L1 + * @type {number} + * @since 3.10.0 + */ + L1: { + + get: function () + { + return this._FBLeftTop.value; + } + + }, + + /** + * Returns the value of the Gamepad's bottom left shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the L2 button. + * On an XBox controller it's the LT button. + * + * @name Phaser.Input.Gamepad.Gamepad#L2 + * @type {number} + * @since 3.10.0 + */ + L2: { + + get: function () + { + return this._FBLeftBottom.value; + } + + }, + + /** + * Returns the value of the Gamepad's top right shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the R1 button. + * On an XBox controller it's the RB button. + * + * @name Phaser.Input.Gamepad.Gamepad#R1 + * @type {number} + * @since 3.10.0 + */ + R1: { + + get: function () + { + return this._FBRightTop.value; + } + + }, + + /** + * Returns the value of the Gamepad's bottom right shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the R2 button. + * On an XBox controller it's the RT button. + * + * @name Phaser.Input.Gamepad.Gamepad#R2 + * @type {number} + * @since 3.10.0 + */ + R2: { + + get: function () + { + return this._FBRightBottom.value; + } + + } + +}); + +module.exports = Gamepad; + + +/***/ }), +/* 476 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(142); + +/** + * @classdesc + * A generic Key object which can be passed to the Process functions (and so on) + * keycode must be an integer + * + * @class Key + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Input.Keyboard + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyboardPlugin} plugin - The Keyboard Plugin instance that owns this Key object. + * @param {integer} keyCode - The keycode of this key. + */ +var Key = new Class({ + + Extends: EventEmitter, + + initialize: + + function Key (plugin, keyCode) + { + EventEmitter.call(this); + + /** + * The Keyboard Plugin instance that owns this Key object. + * + * @name Phaser.Input.Keyboard.Key#plugin + * @type {Phaser.Input.Keyboard.KeyboardPlugin} + * @since 3.17.0 + */ + this.plugin = plugin; + + /** + * The keycode of this key. + * + * @name Phaser.Input.Keyboard.Key#keyCode + * @type {integer} + * @since 3.0.0 + */ + this.keyCode = keyCode; + + /** + * The original DOM event. + * + * @name Phaser.Input.Keyboard.Key#originalEvent + * @type {KeyboardEvent} + * @since 3.0.0 + */ + this.originalEvent = undefined; + + /** + * Can this Key be processed? + * + * @name Phaser.Input.Keyboard.Key#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * + * @name Phaser.Input.Keyboard.Key#isDown + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isDown = false; + + /** + * The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * + * @name Phaser.Input.Keyboard.Key#isUp + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.isUp = true; + + /** + * The down state of the ALT key, if pressed at the same time as this key. + * + * @name Phaser.Input.Keyboard.Key#altKey + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.altKey = false; + + /** + * The down state of the CTRL key, if pressed at the same time as this key. + * + * @name Phaser.Input.Keyboard.Key#ctrlKey + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.ctrlKey = false; + + /** + * The down state of the SHIFT key, if pressed at the same time as this key. + * + * @name Phaser.Input.Keyboard.Key#shiftKey + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.shiftKey = false; + + /** + * The down state of the Meta key, if pressed at the same time as this key. + * On a Mac the Meta Key is the Command key. On Windows keyboards, it's the Windows key. + * + * @name Phaser.Input.Keyboard.Key#metaKey + * @type {boolean} + * @default false + * @since 3.16.0 + */ + this.metaKey = false; + + /** + * The location of the modifier key. 0 for standard (or unknown), 1 for left, 2 for right, 3 for numpad. + * + * @name Phaser.Input.Keyboard.Key#location + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.location = 0; + + /** + * The timestamp when the key was last pressed down. + * + * @name Phaser.Input.Keyboard.Key#timeDown + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeDown = 0; + + /** + * The number of milliseconds this key was held down for in the previous down - up sequence. + * This value isn't updated every game step, only when the Key changes state. + * To get the current duration use the `getDuration` method. + * + * @name Phaser.Input.Keyboard.Key#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * The timestamp when the key was last released. + * + * @name Phaser.Input.Keyboard.Key#timeUp + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeUp = 0; + + /** + * When a key is held down should it continuously fire the `down` event each time it repeats? + * + * By default it will emit the `down` event just once, but if you wish to receive the event + * for each repeat as well, enable this property. + * + * @name Phaser.Input.Keyboard.Key#emitOnRepeat + * @type {boolean} + * @default false + * @since 3.16.0 + */ + this.emitOnRepeat = false; + + /** + * If a key is held down this holds down the number of times the key has 'repeated'. + * + * @name Phaser.Input.Keyboard.Key#repeats + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.repeats = 0; + + /** + * True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * + * @name Phaser.Input.Keyboard.Key#_justDown + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._justDown = false; + + /** + * True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * + * @name Phaser.Input.Keyboard.Key#_justUp + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._justUp = false; + + /** + * Internal tick counter. + * + * @name Phaser.Input.Keyboard.Key#_tick + * @type {number} + * @private + * @since 3.11.0 + */ + this._tick = -1; + }, + + /** + * Controls if this Key will continuously emit a `down` event while being held down (true), + * or emit the event just once, on first press, and then skip future events (false). + * + * @method Phaser.Input.Keyboard.Key#setEmitOnRepeat + * @since 3.16.0 + * + * @param {boolean} value - Emit `down` events on repeated key down actions, or just once? + * + * @return {Phaser.Input.Keyboard.Key} This Key instance. + */ + setEmitOnRepeat: function (value) + { + this.emitOnRepeat = value; + + return this; + }, + + /** + * Processes the Key Down action for this Key. + * Called automatically by the Keyboard Plugin. + * + * @method Phaser.Input.Keyboard.Key#onDown + * @fires Phaser.Input.Keyboard.Events#DOWN + * @since 3.16.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard event. + */ + onDown: function (event) + { + this.originalEvent = event; + + if (!this.enabled) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + this.metaKey = event.metaKey; + this.location = event.location; + + this.repeats++; + + if (!this.isDown) + { + this.isDown = true; + this.isUp = false; + this.timeDown = event.timeStamp; + this.duration = 0; + this._justDown = true; + this._justUp = false; + + this.emit(Events.DOWN, this, event); + } + else if (this.emitOnRepeat) + { + this.emit(Events.DOWN, this, event); + } + }, + + /** + * Processes the Key Up action for this Key. + * Called automatically by the Keyboard Plugin. + * + * @method Phaser.Input.Keyboard.Key#onUp + * @fires Phaser.Input.Keyboard.Events#UP + * @since 3.16.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard event. + */ + onUp: function (event) + { + this.originalEvent = event; + + if (!this.enabled) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = event.timeStamp; + this.duration = this.timeUp - this.timeDown; + this.repeats = 0; + + this._justDown = false; + this._justUp = true; + this._tick = -1; + + this.emit(Events.UP, this, event); + }, + + /** + * Resets this Key object back to its default un-pressed state. + * + * @method Phaser.Input.Keyboard.Key#reset + * @since 3.6.0 + * + * @return {Phaser.Input.Keyboard.Key} This Key instance. + */ + reset: function () + { + this.preventDefault = true; + this.enabled = true; + this.isDown = false; + this.isUp = true; + this.altKey = false; + this.ctrlKey = false; + this.shiftKey = false; + this.metaKey = false; + this.timeDown = 0; + this.duration = 0; + this.timeUp = 0; + this.repeats = 0; + this._justDown = false; + this._justUp = false; + this._tick = -1; + + return this; + }, + + /** + * Returns the duration, in ms, that the Key has been held down for. + * + * If the key is not currently down it will return zero. + * + * The get the duration the Key was held down for in the previous up-down cycle, + * use the `Key.duration` property value instead. + * + * @method Phaser.Input.Keyboard.Key#getDuration + * @since 3.17.0 + * + * @return {number} The duration, in ms, that the Key has been held down for if currently down. + */ + getDuration: function () + { + if (this.isDown) + { + return (this.plugin.game.loop.time - this.timeDown); + } + else + { + return 0; + } + }, + + /** + * Removes any bound event handlers and removes local references. + * + * @method Phaser.Input.Keyboard.Key#destroy + * @since 3.16.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.originalEvent = null; + + this.plugin = null; + } + +}); + +module.exports = Key; + + +/***/ }), +/* 477 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Events = __webpack_require__(142); +var GetFastValue = __webpack_require__(1); +var ProcessKeyCombo = __webpack_require__(1248); +var ResetKeyCombo = __webpack_require__(1250); + +/** + * @classdesc + * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them + * it will emit a `keycombomatch` event from the Keyboard Manager. + * + * The keys to be listened for can be defined as: + * + * A string (i.e. 'ATARI') + * An array of either integers (key codes) or strings, or a mixture of both + * An array of objects (such as Key objects) with a public 'keyCode' property + * + * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) + * you could pass the following array of key codes: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * Or, to listen for the user entering the word PHASER: + * + * ```javascript + * this.input.keyboard.createCombo('PHASER'); + * ``` + * + * @class KeyCombo + * @memberof Phaser.Input.Keyboard + * @constructor + * @listens Phaser.Input.Keyboard.Events#ANY_KEY_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyboardPlugin} keyboardPlugin - A reference to the Keyboard Plugin. + * @param {(string|integer[]|object[])} keys - The keys that comprise this combo. + * @param {Phaser.Types.Input.Keyboard.KeyComboConfig} [config] - A Key Combo configuration object. + */ +var KeyCombo = new Class({ + + initialize: + + function KeyCombo (keyboardPlugin, keys, config) + { + if (config === undefined) { config = {}; } + + // Can't have a zero or single length combo (string or array based) + if (keys.length < 2) + { + return false; + } + + /** + * A reference to the Keyboard Manager + * + * @name Phaser.Input.Keyboard.KeyCombo#manager + * @type {Phaser.Input.Keyboard.KeyboardPlugin} + * @since 3.0.0 + */ + this.manager = keyboardPlugin; + + /** + * A flag that controls if this Key Combo is actively processing keys or not. + * + * @name Phaser.Input.Keyboard.KeyCombo#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * An array of the keycodes that comprise this combo. + * + * @name Phaser.Input.Keyboard.KeyCombo#keyCodes + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.keyCodes = []; + + // if 'keys' is a string we need to get the keycode of each character in it + + for (var i = 0; i < keys.length; i++) + { + var char = keys[i]; + + if (typeof char === 'string') + { + this.keyCodes.push(char.toUpperCase().charCodeAt(0)); + } + else if (typeof char === 'number') + { + this.keyCodes.push(char); + } + else if (char.hasOwnProperty('keyCode')) + { + this.keyCodes.push(char.keyCode); + } + } + + /** + * The current keyCode the combo is waiting for. + * + * @name Phaser.Input.Keyboard.KeyCombo#current + * @type {integer} + * @since 3.0.0 + */ + this.current = this.keyCodes[0]; + + /** + * The current index of the key being waited for in the 'keys' string. + * + * @name Phaser.Input.Keyboard.KeyCombo#index + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.index = 0; + + /** + * The length of this combo (in keycodes) + * + * @name Phaser.Input.Keyboard.KeyCombo#size + * @type {number} + * @since 3.0.0 + */ + this.size = this.keyCodes.length; + + /** + * The time the previous key in the combo was matched. + * + * @name Phaser.Input.Keyboard.KeyCombo#timeLastMatched + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeLastMatched = 0; + + /** + * Has this Key Combo been matched yet? + * + * @name Phaser.Input.Keyboard.KeyCombo#matched + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.matched = false; + + /** + * The time the entire combo was matched. + * + * @name Phaser.Input.Keyboard.KeyCombo#timeMatched + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeMatched = 0; + + /** + * If they press the wrong key do we reset the combo? + * + * @name Phaser.Input.Keyboard.KeyCombo#resetOnWrongKey + * @type {boolean} + * @default 0 + * @since 3.0.0 + */ + this.resetOnWrongKey = GetFastValue(config, 'resetOnWrongKey', true); + + /** + * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. + * + * @name Phaser.Input.Keyboard.KeyCombo#maxKeyDelay + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.maxKeyDelay = GetFastValue(config, 'maxKeyDelay', 0); + + /** + * If previously matched and they press the first key of the combo again, will it reset? + * + * @name Phaser.Input.Keyboard.KeyCombo#resetOnMatch + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.resetOnMatch = GetFastValue(config, 'resetOnMatch', false); + + /** + * If the combo matches, will it delete itself? + * + * @name Phaser.Input.Keyboard.KeyCombo#deleteOnMatch + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.deleteOnMatch = GetFastValue(config, 'deleteOnMatch', false); + + var _this = this; + + var onKeyDownHandler = function (event) + { + if (_this.matched || !_this.enabled) + { + return; + } + + var matched = ProcessKeyCombo(event, _this); + + if (matched) + { + _this.manager.emit(Events.COMBO_MATCH, _this, event); + + if (_this.resetOnMatch) + { + ResetKeyCombo(_this); + } + else if (_this.deleteOnMatch) + { + _this.destroy(); + } + } + }; + + /** + * The internal Key Down handler. + * + * @name Phaser.Input.Keyboard.KeyCombo#onKeyDown + * @private + * @type {KeyboardKeydownCallback} + * @fires Phaser.Input.Keyboard.Events#COMBO_MATCH + * @since 3.0.0 + */ + this.onKeyDown = onKeyDownHandler; + + this.manager.on(Events.ANY_KEY_DOWN, this.onKeyDown); + }, + + /** + * How far complete is this combo? A value between 0 and 1. + * + * @name Phaser.Input.Keyboard.KeyCombo#progress + * @type {number} + * @readonly + * @since 3.0.0 + */ + progress: { + + get: function () + { + return this.index / this.size; + } + + }, + + /** + * Destroys this Key Combo and all of its references. + * + * @method Phaser.Input.Keyboard.KeyCombo#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.enabled = false; + this.keyCodes = []; + + this.manager.off(Events.ANY_KEY_DOWN, this.onKeyDown); + + this.manager = null; + } + +}); + +module.exports = KeyCombo; + + +/***/ }), +/* 478 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MergeXHRSettings = __webpack_require__(227); + +/** + * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings + * and starts the download of it. It uses the Files 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. + */ +var XHRLoader = function (file, globalXHRSettings) +{ + var config = MergeXHRSettings(globalXHRSettings, file.xhrSettings); + + var xhr = new XMLHttpRequest(); + + xhr.open('GET', file.src, config.async, config.user, config.password); + + xhr.responseType = file.xhrSettings.responseType; + xhr.timeout = config.timeout; + + if (config.header && config.headerValue) + { + xhr.setRequestHeader(config.header, config.headerValue); + } + + if (config.requestedWith) + { + xhr.setRequestHeader('X-Requested-With', config.requestedWith); + } + + if (config.overrideMimeType) + { + xhr.overrideMimeType(config.overrideMimeType); + } + + // 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.) + + xhr.onload = file.onLoad.bind(file, xhr); + xhr.onerror = file.onError.bind(file, xhr); + xhr.onprogress = file.onProgress.bind(file); + + // This is the only standard method, the ones above are browser additions (maybe not universal?) + // xhr.onreadystatechange + + xhr.send(); + + return xhr; +}; + +module.exports = XHRLoader; + + +/***/ }), +/* 479 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(32); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var HTML5AudioFile = __webpack_require__(480); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Audio File suitable for loading by the Loader. + * + * 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 {any} [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. + */ +var AudioFile = new Class({ + + Extends: File, + + initialize: + + // URL is an object created by AudioFile.findAudioURL + function AudioFile (loader, key, urlConfig, xhrSettings, audioContext) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + audioContext = GetFastValue(config, 'context', audioContext); + } + + var fileConfig = { + type: 'audio', + cache: loader.cacheManager.audio, + extension: urlConfig.type, + responseType: 'arraybuffer', + key: key, + url: urlConfig.url, + xhrSettings: xhrSettings, + config: { context: audioContext } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.AudioFile#onProcess + * @since 3.0.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var _this = this; + + // interesting read https://github.com/WebAudio/web-audio-api/issues/1305 + this.config.context.decodeAudioData(this.xhrLoader.response, + function (audioBuffer) + { + _this.data = audioBuffer; + + _this.onProcessComplete(); + }, + function (e) + { + // eslint-disable-next-line no-console + console.error('Error decoding audio: ' + this.key + ' - ', e ? e.message : null); + + _this.onProcessError(); + } + ); + + this.config.context = null; + } + +}); + +AudioFile.create = function (loader, key, urls, config, xhrSettings) +{ + var game = loader.systems.game; + var audioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + // url may be inside key, which may be an object + if (IsPlainObject(key)) + { + urls = GetFastValue(key, 'url', []); + config = GetFastValue(key, 'config', {}); + } + + var urlConfig = AudioFile.getAudioURL(game, urls); + + if (!urlConfig) + { + return null; + } + + // https://developers.google.com/web/updates/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs + // var stream = GetFastValue(config, 'stream', false); + + if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) + { + return new AudioFile(loader, key, urlConfig, xhrSettings, game.sound.context); + } + else + { + return new HTML5AudioFile(loader, key, urlConfig, config); + } +}; + +AudioFile.getAudioURL = function (game, urls) +{ + if (!Array.isArray(urls)) + { + urls = [ urls ]; + } + + for (var i = 0; i < urls.length; i++) + { + var url = GetFastValue(urls[i], 'url', urls[i]); + + if (url.indexOf('blob:') === 0 || url.indexOf('data:') === 0) + { + return url; + } + + var audioType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); + + audioType = GetFastValue(urls[i], 'type', (audioType) ? audioType[1] : '').toLowerCase(); + + if (game.device.audio[audioType]) + { + return { + url: url, + type: audioType + }; + } + } + + return null; +}; + +/** + * 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.LoaderPlugin#addFileEvent + * @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[])} [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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('audio', function (key, urls, config, xhrSettings) +{ + var game = this.systems.game; + var audioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + // Sounds are disabled, so skip loading audio + return this; + } + + var audioFile; + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + audioFile = AudioFile.create(this, key[i]); + + if (audioFile) + { + this.addFile(audioFile); + } + } + } + else + { + audioFile = AudioFile.create(this, key, urls, config, xhrSettings); + + if (audioFile) + { + this.addFile(audioFile); + } + } + + return this; +}); + +module.exports = AudioFile; + + +/***/ }), +/* 480 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Events = __webpack_require__(87); +var File = __webpack_require__(24); +var GetFastValue = __webpack_require__(1); +var GetURL = __webpack_require__(143); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Audio File suitable for loading by the Loader. + * + * 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 HTML5AudioFile + * @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 {string} [urlConfig] - The absolute or relative URL to load this file from. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var HTML5AudioFile = new Class({ + + Extends: File, + + initialize: + + function HTML5AudioFile (loader, key, urlConfig, audioConfig) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + audioConfig = GetFastValue(config, 'config', audioConfig); + } + + var fileConfig = { + type: 'audio', + cache: loader.cacheManager.audio, + extension: urlConfig.type, + key: key, + url: urlConfig.url, + config: audioConfig + }; + + File.call(this, loader, fileConfig); + + // New properties specific to this class + this.locked = 'ontouchstart' in window; + this.loaded = false; + this.filesLoaded = 0; + this.filesTotal = 0; + }, + + /** + * Called when the file finishes loading. + * + * @method Phaser.Loader.FileTypes.HTML5AudioFile#onLoad + * @since 3.0.0 + */ + onLoad: function () + { + if (this.loaded) + { + return; + } + + this.loaded = true; + + this.loader.nextFile(this, true); + }, + + /** + * Called if the file errors while loading. + * + * @method Phaser.Loader.FileTypes.HTML5AudioFile#onError + * @since 3.0.0 + */ + onError: function () + { + for (var i = 0; i < this.data.length; i++) + { + var audio = this.data[i]; + + audio.oncanplaythrough = null; + audio.onerror = null; + } + + this.loader.nextFile(this, false); + }, + + /** + * Called during the file load progress. Is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.FileTypes.HTML5AudioFile#onProgress + * @fires Phaser.Loader.Events#FILE_PROGRESS + * @since 3.0.0 + */ + onProgress: function (event) + { + var audio = event.target; + + audio.oncanplaythrough = null; + audio.onerror = null; + + this.filesLoaded++; + + this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1); + + this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete); + + if (this.filesLoaded === this.filesTotal) + { + this.onLoad(); + } + }, + + /** + * 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.FileTypes.HTML5AudioFile#load + * @since 3.0.0 + */ + load: function () + { + this.data = []; + + var instances = (this.config && this.config.instances) || 1; + + this.filesTotal = instances; + this.filesLoaded = 0; + this.percentComplete = 0; + + for (var i = 0; i < instances; i++) + { + var audio = new Audio(); + audio.dataset = {}; + audio.dataset.name = this.key + ('0' + i).slice(-2); + audio.dataset.used = 'false'; + + if (this.locked) + { + audio.dataset.locked = 'true'; + } + else + { + audio.dataset.locked = 'false'; + + audio.preload = 'auto'; + audio.oncanplaythrough = this.onProgress.bind(this); + audio.onerror = this.onError.bind(this); + } + + this.data.push(audio); + } + + for (i = 0; i < this.data.length; i++) + { + audio = this.data[i]; + audio.src = GetURL(this, this.loader.baseURL); + + if (!this.locked) + { + audio.load(); + } + } + + if (this.locked) + { + // This is super-dangerous but works. Race condition potential high. + // Is there another way? + setTimeout(this.onLoad.bind(this)); + } + } + +}); + +module.exports = HTML5AudioFile; + + +/***/ }), +/* 481 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#script method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#script. + * + * @class ScriptFile + * @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.ScriptFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var ScriptFile = new Class({ + + Extends: File, + + initialize: + + function ScriptFile (loader, key, url, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'script', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.ScriptFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('script'); + this.data.language = 'javascript'; + this.data.type = 'text/javascript'; + this.data.defer = false; + this.data.text = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Script file, or array of Script 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.script('aliens', 'lib/aliens.js'); + * } + * ``` + * + * 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.script({ + * key: 'aliens', + * url: 'lib/aliens.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ScriptFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. + * + * 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.js". It will always add `.js` 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 Script 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#script + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.ScriptFileConfig|Phaser.Types.Loader.FileTypes.ScriptFileConfig[])} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('script', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new ScriptFile(this, key[i])); + } + } + else + { + this.addFile(new ScriptFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = ScriptFile; + + +/***/ }), +/* 482 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Text File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#text method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#text. + * + * @class TextFile + * @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.TextFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TextFile = new Class({ + + Extends: File, + + initialize: + + function TextFile (loader, key, url, xhrSettings) + { + var extension = 'txt'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'text', + cache: loader.cacheManager.text, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.TextFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Text file, or array of Text 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.text('story', 'files/IntroStory.txt'); + * } + * ``` + * + * 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 Text Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Text 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.text({ + * key: 'story', + * url: 'files/IntroStory.txt' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TextFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.text('story', 'files/IntroStory.txt'); + * // and later in your game ... + * var data = this.cache.text.get('story'); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Text 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 "story" + * and no URL is given then the Loader will set the URL to be "story.txt". It will always add `.txt` 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 Text 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#text + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TextFileConfig|Phaser.Types.Loader.FileTypes.TextFileConfig[])} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('text', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TextFile(this, key[i])); + } + } + else + { + this.addFile(new TextFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TextFile; + + +/***/ }), +/* 483 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcadeImage = __webpack_require__(484); +var ArcadeSprite = __webpack_require__(145); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(58); +var PhysicsGroup = __webpack_require__(485); +var StaticPhysicsGroup = __webpack_require__(486); + +/** + * @classdesc + * The Arcade Physics Factory allows you to easily create Arcade Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + * + * @class Factory + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics World instance. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * A reference to the Arcade Physics World. + * + * @name Phaser.Physics.Arcade.Factory#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * A reference to the Scene this Arcade Physics instance belongs to. + * + * @name Phaser.Physics.Arcade.Factory#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = world.scene; + + /** + * A reference to the Scene.Systems this Arcade Physics instance belongs to. + * + * @name Phaser.Physics.Arcade.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new Arcade Physics Collider object. + * + * @method Phaser.Physics.Arcade.Factory#collider + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object1 - The first object to check for collision. + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + collider: function (object1, object2, collideCallback, processCallback, callbackContext) + { + return this.world.addCollider(object1, object2, collideCallback, processCallback, callbackContext); + }, + + /** + * Creates a new Arcade Physics Collider Overlap object. + * + * @method Phaser.Physics.Arcade.Factory#overlap + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object1 - The first object to check for overlap. + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object2 - The second object to check for overlap. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + overlap: function (object1, object2, collideCallback, processCallback, callbackContext) + { + return this.world.addOverlap(object1, object2, collideCallback, processCallback, callbackContext); + }, + + /** + * Adds an Arcade Physics Body to the given Game Object. + * + * @method Phaser.Physics.Arcade.Factory#existing + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - A Game Object. + * @param {boolean} [isStatic=false] - Create a Static body (true) or Dynamic body (false). + * + * @return {Phaser.GameObjects.GameObject} The Game Object. + */ + existing: function (gameObject, isStatic) + { + var type = (isStatic) ? CONST.STATIC_BODY : CONST.DYNAMIC_BODY; + + this.world.enableBody(gameObject, type); + + return gameObject; + }, + + /** + * Creates a new Arcade Image object with a Static body. + * + * @method Phaser.Physics.Arcade.Factory#staticImage + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Image} The Image object that was created. + */ + staticImage: function (x, y, key, frame) + { + var image = new ArcadeImage(this.scene, x, y, key, frame); + + this.sys.displayList.add(image); + + this.world.enableBody(image, CONST.STATIC_BODY); + + return image; + }, + + /** + * Creates a new Arcade Image object with a Dynamic body. + * + * @method Phaser.Physics.Arcade.Factory#image + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Image} The Image object that was created. + */ + image: function (x, y, key, frame) + { + var image = new ArcadeImage(this.scene, x, y, key, frame); + + this.sys.displayList.add(image); + + this.world.enableBody(image, CONST.DYNAMIC_BODY); + + return image; + }, + + /** + * Creates a new Arcade Sprite object with a Static body. + * + * @method Phaser.Physics.Arcade.Factory#staticSprite + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Sprite} The Sprite object that was created. + */ + staticSprite: function (x, y, key, frame) + { + var sprite = new ArcadeSprite(this.scene, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + this.world.enableBody(sprite, CONST.STATIC_BODY); + + return sprite; + }, + + /** + * Creates a new Arcade Sprite object with a Dynamic body. + * + * @method Phaser.Physics.Arcade.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Sprite} The Sprite object that was created. + */ + sprite: function (x, y, key, frame) + { + var sprite = new ArcadeSprite(this.scene, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + this.world.enableBody(sprite, CONST.DYNAMIC_BODY); + + return sprite; + }, + + /** + * Creates a Static Physics Group object. + * All Game Objects created by this Group will automatically be static Arcade Physics objects. + * + * @method Phaser.Physics.Arcade.Factory#staticGroup + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + * + * @return {Phaser.Physics.Arcade.StaticGroup} The Static Group object that was created. + */ + staticGroup: function (children, config) + { + return this.sys.updateList.add(new StaticPhysicsGroup(this.world, this.world.scene, children, config)); + }, + + /** + * Creates a Physics Group object. + * All Game Objects created by this Group will automatically be dynamic Arcade Physics objects. + * + * @method Phaser.Physics.Arcade.Factory#group + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + * + * @return {Phaser.Physics.Arcade.Group} The Group object that was created. + */ + group: function (children, config) + { + return this.sys.updateList.add(new PhysicsGroup(this.world, this.world.scene, children, config)); + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Arcade.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.scene = null; + this.sys = null; + } + +}); + +module.exports = Factory; + + +/***/ }), +/* 484 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(229); +var Image = __webpack_require__(89); + +/** + * @classdesc + * An Arcade Physics Image is an Image with an Arcade Physics body and related components. + * The body can be dynamic or static. + * + * The main difference between an Arcade Image and an Arcade Sprite is that you cannot animate an Arcade Image. + * + * @class Image + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Arcade.Components.Acceleration + * @extends Phaser.Physics.Arcade.Components.Angular + * @extends Phaser.Physics.Arcade.Components.Bounce + * @extends Phaser.Physics.Arcade.Components.Debug + * @extends Phaser.Physics.Arcade.Components.Drag + * @extends Phaser.Physics.Arcade.Components.Enable + * @extends Phaser.Physics.Arcade.Components.Friction + * @extends Phaser.Physics.Arcade.Components.Gravity + * @extends Phaser.Physics.Arcade.Components.Immovable + * @extends Phaser.Physics.Arcade.Components.Mass + * @extends Phaser.Physics.Arcade.Components.Size + * @extends Phaser.Physics.Arcade.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ArcadeImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Acceleration, + Components.Angular, + Components.Bounce, + Components.Debug, + Components.Drag, + Components.Enable, + Components.Friction, + Components.Gravity, + Components.Immovable, + Components.Mass, + Components.Size, + Components.Velocity + ], + + initialize: + + function ArcadeImage (scene, x, y, texture, frame) + { + Image.call(this, scene, x, y, texture, frame); + + /** + * This Game Object's Physics Body. + * + * @name Phaser.Physics.Arcade.Image#body + * @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} + * @default null + * @since 3.0.0 + */ + this.body = null; + } + +}); + +module.exports = ArcadeImage; + + +/***/ }), +/* 485 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcadeSprite = __webpack_require__(145); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(58); +var GetFastValue = __webpack_require__(1); +var Group = __webpack_require__(109); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * An Arcade Physics Group object. + * + * All Game Objects created by this Group will automatically be given dynamic Arcade Physics bodies. + * + * Its static counterpart is {@link Phaser.Physics.Arcade.StaticGroup}. + * + * @class Group + * @extends Phaser.GameObjects.Group + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The physics simulation. + * @param {Phaser.Scene} scene - The scene this group belongs to. + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + */ +var PhysicsGroup = new Class({ + + Extends: Group, + + initialize: + + function PhysicsGroup (world, scene, children, config) + { + if (!children && !config) + { + config = { + internalCreateCallback: this.createCallbackHandler, + internalRemoveCallback: this.removeCallbackHandler + }; + } + else if (IsPlainObject(children)) + { + // children is a plain object, so swizzle them: + config = children; + children = null; + + config.internalCreateCallback = this.createCallbackHandler; + config.internalRemoveCallback = this.removeCallbackHandler; + } + else if (Array.isArray(children) && IsPlainObject(children[0])) + { + // children is an array of plain objects + config = children[0]; + + var _this = this; + + children.forEach(function (singleConfig) + { + singleConfig.internalCreateCallback = _this.createCallbackHandler; + singleConfig.internalRemoveCallback = _this.removeCallbackHandler; + }); + } + else + { + // config is not defined and children is not a plain object nor an array of plain objects + config = { + internalCreateCallback: this.createCallbackHandler, + internalRemoveCallback: this.removeCallbackHandler + }; + } + + /** + * The physics simulation. + * + * @name Phaser.Physics.Arcade.Group#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The class to create new Group members from. + * + * This should be either `Phaser.Physics.Arcade.Image`, `Phaser.Physics.Arcade.Sprite`, or a class extending one of those. + * + * @name Phaser.Physics.Arcade.Group#classType + * @type {Function} + * @default ArcadeSprite + * @since 3.0.0 + */ + config.classType = GetFastValue(config, 'classType', ArcadeSprite); + + /** + * The physics type of the Group's members. + * + * @name Phaser.Physics.Arcade.Group#physicsType + * @type {integer} + * @default Phaser.Physics.Arcade.DYNAMIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.DYNAMIC_BODY; + + /** + * Default physics properties applied to Game Objects added to the Group or created by the Group. Derived from the `config` argument. + * + * @name Phaser.Physics.Arcade.Group#defaults + * @type {Phaser.Types.Physics.Arcade.PhysicsGroupDefaults} + * @since 3.0.0 + */ + this.defaults = { + setCollideWorldBounds: GetFastValue(config, 'collideWorldBounds', false), + setBoundsRectangle: GetFastValue(config, 'customBoundsRectangle', null), + setAccelerationX: GetFastValue(config, 'accelerationX', 0), + setAccelerationY: GetFastValue(config, 'accelerationY', 0), + setAllowDrag: GetFastValue(config, 'allowDrag', true), + setAllowGravity: GetFastValue(config, 'allowGravity', true), + setAllowRotation: GetFastValue(config, 'allowRotation', true), + setBounceX: GetFastValue(config, 'bounceX', 0), + setBounceY: GetFastValue(config, 'bounceY', 0), + setDragX: GetFastValue(config, 'dragX', 0), + setDragY: GetFastValue(config, 'dragY', 0), + setEnable: GetFastValue(config, 'enable', true), + setGravityX: GetFastValue(config, 'gravityX', 0), + setGravityY: GetFastValue(config, 'gravityY', 0), + setFrictionX: GetFastValue(config, 'frictionX', 0), + setFrictionY: GetFastValue(config, 'frictionY', 0), + setVelocityX: GetFastValue(config, 'velocityX', 0), + setVelocityY: GetFastValue(config, 'velocityY', 0), + setAngularVelocity: GetFastValue(config, 'angularVelocity', 0), + setAngularAcceleration: GetFastValue(config, 'angularAcceleration', 0), + setAngularDrag: GetFastValue(config, 'angularDrag', 0), + setMass: GetFastValue(config, 'mass', 1), + setImmovable: GetFastValue(config, 'immovable', false) + }; + + if (Array.isArray(children)) + { + config = null; + } + + Group.call(this, scene, children, config); + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.Physics.Arcade.Group#type + * @type {string} + * @default 'PhysicsGroup' + * @since 3.21.0 + */ + this.type = 'PhysicsGroup'; + }, + + /** + * Enables a Game Object's Body and assigns `defaults`. Called when a Group member is added or created. + * + * @method Phaser.Physics.Arcade.Group#createCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object being added. + */ + createCallbackHandler: function (child) + { + if (!child.body) + { + this.world.enableBody(child, CONST.DYNAMIC_BODY); + } + + var body = child.body; + + for (var key in this.defaults) + { + body[key](this.defaults[key]); + } + }, + + /** + * Disables a Game Object's Body. Called when a Group member is removed. + * + * @method Phaser.Physics.Arcade.Group#removeCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object being removed. + */ + removeCallbackHandler: function (child) + { + if (child.body) + { + this.world.disableBody(child); + } + }, + + /** + * Sets the velocity of each Group member. + * + * @method Phaser.Physics.Arcade.Group#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity. + * @param {number} y - The vertical velocity. + * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (x, y), the second (x + step, y + step), and so on. + * + * @return {Phaser.Physics.Arcade.Group} This Physics Group object. + */ + setVelocity: function (x, y, step) + { + if (step === undefined) { step = 0; } + + var items = this.getChildren(); + + for (var i = 0; i < items.length; i++) + { + items[i].body.velocity.set(x + (i * step), y + (i * step)); + } + + return this; + }, + + /** + * Sets the horizontal velocity of each Group member. + * + * @method Phaser.Physics.Arcade.Group#setVelocityX + * @since 3.0.0 + * + * @param {number} value - The velocity value. + * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (x), the second (x + step), and so on. + * + * @return {Phaser.Physics.Arcade.Group} This Physics Group object. + */ + setVelocityX: function (value, step) + { + if (step === undefined) { step = 0; } + + var items = this.getChildren(); + + for (var i = 0; i < items.length; i++) + { + items[i].body.velocity.x = value + (i * step); + } + + return this; + }, + + /** + * Sets the vertical velocity of each Group member. + * + * @method Phaser.Physics.Arcade.Group#setVelocityY + * @since 3.0.0 + * + * @param {number} value - The velocity value. + * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (y), the second (y + step), and so on. + * + * @return {Phaser.Physics.Arcade.Group} This Physics Group object. + */ + setVelocityY: function (value, step) + { + if (step === undefined) { step = 0; } + + var items = this.getChildren(); + + for (var i = 0; i < items.length; i++) + { + items[i].body.velocity.y = value + (i * step); + } + + return this; + } + +}); + +module.exports = PhysicsGroup; + + +/***/ }), +/* 486 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcadeSprite = __webpack_require__(145); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(58); +var GetFastValue = __webpack_require__(1); +var Group = __webpack_require__(109); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * An Arcade Physics Static Group object. + * + * All Game Objects created by this Group will automatically be given static Arcade Physics bodies. + * + * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Group}. + * + * @class StaticGroup + * @extends Phaser.GameObjects.Group + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The physics simulation. + * @param {Phaser.Scene} scene - The scene this group belongs to. + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + */ +var StaticPhysicsGroup = new Class({ + + Extends: Group, + + initialize: + + function StaticPhysicsGroup (world, scene, children, config) + { + if (!children && !config) + { + config = { + internalCreateCallback: this.createCallbackHandler, + internalRemoveCallback: this.removeCallbackHandler, + createMultipleCallback: this.createMultipleCallbackHandler, + classType: ArcadeSprite + }; + } + else if (IsPlainObject(children)) + { + // children is a plain object, so swizzle them: + config = children; + children = null; + + config.internalCreateCallback = this.createCallbackHandler; + config.internalRemoveCallback = this.removeCallbackHandler; + config.createMultipleCallback = this.createMultipleCallbackHandler; + config.classType = GetFastValue(config, 'classType', ArcadeSprite); + } + else if (Array.isArray(children) && IsPlainObject(children[0])) + { + // children is an array of plain objects + config = children; + children = null; + + config.forEach(function (singleConfig) + { + singleConfig.internalCreateCallback = this.createCallbackHandler; + singleConfig.internalRemoveCallback = this.removeCallbackHandler; + singleConfig.createMultipleCallback = this.createMultipleCallbackHandler; + singleConfig.classType = GetFastValue(singleConfig, 'classType', ArcadeSprite); + }); + } + + /** + * The physics simulation. + * + * @name Phaser.Physics.Arcade.StaticGroup#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The scene this group belongs to. + * + * @name Phaser.Physics.Arcade.StaticGroup#physicsType + * @type {integer} + * @default Phaser.Physics.Arcade.STATIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.STATIC_BODY; + + Group.call(this, scene, children, config); + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.Physics.Arcade.StaticGroup#type + * @type {string} + * @default 'StaticPhysicsGroup' + * @since 3.21.0 + */ + this.type = 'StaticPhysicsGroup'; + }, + + /** + * Adds a static physics body to the new group member (if it lacks one) and adds it to the simulation. + * + * @method Phaser.Physics.Arcade.StaticGroup#createCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The new group member. + * + * @see Phaser.Physics.Arcade.World#enableBody + */ + createCallbackHandler: function (child) + { + if (!child.body) + { + this.world.enableBody(child, CONST.STATIC_BODY); + } + }, + + /** + * Disables the group member's physics body, removing it from the simulation. + * + * @method Phaser.Physics.Arcade.StaticGroup#removeCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The group member being removed. + * + * @see Phaser.Physics.Arcade.World#disableBody + */ + removeCallbackHandler: function (child) + { + if (child.body) + { + this.world.disableBody(child); + } + }, + + /** + * Refreshes the group. + * + * @method Phaser.Physics.Arcade.StaticGroup#createMultipleCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject[]} entries - The newly created group members. + * + * @see Phaser.Physics.Arcade.StaticGroup#refresh + */ + createMultipleCallbackHandler: function () + { + this.refresh(); + }, + + /** + * Resets each Body to the position of its parent Game Object. + * Body sizes aren't changed (use {@link Phaser.Physics.Arcade.Components.Enable#refreshBody} for that). + * + * @method Phaser.Physics.Arcade.StaticGroup#refresh + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.StaticGroup} This group. + * + * @see Phaser.Physics.Arcade.StaticBody#reset + */ + refresh: function () + { + var children = this.children.entries; + + for (var i = 0; i < children.length; i++) + { + children[i].body.reset(); + } + + return this; + } + +}); + +module.exports = StaticPhysicsGroup; + + +/***/ }), +/* 487 */ +/***/ (function(module, exports) { + +/** + * This method will search the given rectangular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, + * otherwise the search is O(N) for Dynamic Bodies. + * + * @function Phaser.Physics.Arcade.Components.OverlapRect + * @since 3.17.0 + * + * @param {number} x - The top-left x coordinate of the area to search within. + * @param {number} y - The top-left y coordinate of the area to search within. + * @param {number} width - The width of the area to search within. + * @param {number} height - The height of the area to search within. + * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? + * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? + * + * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. + */ +var OverlapRect = function (world, x, y, width, height, includeDynamic, includeStatic) +{ + if (includeDynamic === undefined) { includeDynamic = true; } + if (includeStatic === undefined) { includeStatic = false; } + + var dynamicBodies = []; + var staticBodies = []; + + var minMax = world.treeMinMax; + + minMax.minX = x; + minMax.minY = y; + minMax.maxX = x + width; + minMax.maxY = y + height; + + if (includeStatic) + { + staticBodies = world.staticTree.search(minMax); + } + + if (includeDynamic && world.useTree) + { + dynamicBodies = world.tree.search(minMax); + } + else if (includeDynamic) + { + var bodies = world.bodies; + + var fakeBody = + { + position: { + x: x, + y: y + }, + left: x, + top: y, + right: x + width, + bottom: y + height, + isCircle: false + }; + + var intersects = world.intersects; + + bodies.iterate(function (target) + { + if (intersects(target, fakeBody)) + { + dynamicBodies.push(target); + } + + }); + } + + return staticBodies.concat(dynamicBodies); +}; + +module.exports = OverlapRect; + + +/***/ }), +/* 488 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(489); +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var Collider = __webpack_require__(490); +var CONST = __webpack_require__(58); +var DistanceBetween = __webpack_require__(54); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(230); +var FuzzyEqual = __webpack_require__(126); +var FuzzyGreaterThan = __webpack_require__(339); +var FuzzyLessThan = __webpack_require__(340); +var GetOverlapX = __webpack_require__(491); +var GetOverlapY = __webpack_require__(492); +var GetValue = __webpack_require__(5); +var ProcessQueue = __webpack_require__(199); +var ProcessTileCallbacks = __webpack_require__(1308); +var Rectangle = __webpack_require__(11); +var RTree = __webpack_require__(493); +var SeparateTile = __webpack_require__(1309); +var SeparateX = __webpack_require__(1314); +var SeparateY = __webpack_require__(1315); +var Set = __webpack_require__(110); +var StaticBody = __webpack_require__(495); +var TileIntersectsBody = __webpack_require__(494); +var TransformMatrix = __webpack_require__(35); +var Vector2 = __webpack_require__(3); +var Wrap = __webpack_require__(63); + +/** + * @classdesc + * The Arcade Physics World. + * + * The World is responsible for creating, managing, colliding and updating all of the bodies within it. + * + * An instance of the World belongs to a Phaser.Scene and is accessed via the property `physics.world`. + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this World instance belongs. + * @param {Phaser.Types.Physics.Arcade.ArcadeWorldConfig} config - An Arcade Physics Configuration object. + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * The Scene this simulation belongs to. + * + * @name Phaser.Physics.Arcade.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * Dynamic Bodies in this simulation. + * + * @name Phaser.Physics.Arcade.World#bodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.bodies = new Set(); + + /** + * Static Bodies in this simulation. + * + * @name Phaser.Physics.Arcade.World#staticBodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.staticBodies = new Set(); + + /** + * Static Bodies marked for deletion. + * + * @name Phaser.Physics.Arcade.World#pendingDestroy + * @type {Phaser.Structs.Set.<(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)>} + * @since 3.1.0 + */ + this.pendingDestroy = new Set(); + + /** + * This simulation's collision processors. + * + * @name Phaser.Physics.Arcade.World#colliders + * @type {Phaser.Structs.ProcessQueue.} + * @since 3.0.0 + */ + this.colliders = new ProcessQueue(); + + /** + * Acceleration of Bodies due to gravity, in pixels per second. + * + * @name Phaser.Physics.Arcade.World#gravity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.gravity = new Vector2(GetValue(config, 'gravity.x', 0), GetValue(config, 'gravity.y', 0)); + + /** + * A boundary constraining Bodies. + * + * @name Phaser.Physics.Arcade.World#bounds + * @type {Phaser.Geom.Rectangle} + * @since 3.0.0 + */ + this.bounds = new Rectangle( + GetValue(config, 'x', 0), + GetValue(config, 'y', 0), + GetValue(config, 'width', scene.sys.scale.width), + GetValue(config, 'height', scene.sys.scale.height) + ); + + /** + * The boundary edges that Bodies can collide with. + * + * @name Phaser.Physics.Arcade.World#checkCollision + * @type {Phaser.Types.Physics.Arcade.CheckCollisionObject} + * @since 3.0.0 + */ + this.checkCollision = { + up: GetValue(config, 'checkCollision.up', true), + down: GetValue(config, 'checkCollision.down', true), + left: GetValue(config, 'checkCollision.left', true), + right: GetValue(config, 'checkCollision.right', true) + }; + + /** + * The number of physics steps to be taken per second. + * + * This property is read-only. Use the `setFPS` method to modify it at run-time. + * + * @name Phaser.Physics.Arcade.World#fps + * @readonly + * @type {number} + * @default 60 + * @since 3.10.0 + */ + this.fps = GetValue(config, 'fps', 60); + + /** + * The amount of elapsed ms since the last frame. + * + * @name Phaser.Physics.Arcade.World#_elapsed + * @private + * @type {number} + * @since 3.10.0 + */ + this._elapsed = 0; + + /** + * Internal frame time value. + * + * @name Phaser.Physics.Arcade.World#_frameTime + * @private + * @type {number} + * @since 3.10.0 + */ + this._frameTime = 1 / this.fps; + + /** + * Internal frame time ms value. + * + * @name Phaser.Physics.Arcade.World#_frameTimeMS + * @private + * @type {number} + * @since 3.10.0 + */ + this._frameTimeMS = 1000 * this._frameTime; + + /** + * The number of steps that took place in the last frame. + * + * @name Phaser.Physics.Arcade.World#stepsLastFrame + * @readonly + * @type {number} + * @since 3.10.0 + */ + this.stepsLastFrame = 0; + + /** + * Scaling factor applied to the frame rate. + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * @name Phaser.Physics.Arcade.World#timeScale + * @type {number} + * @default 1 + * @since 3.10.0 + */ + this.timeScale = GetValue(config, 'timeScale', 1); + + /** + * The maximum absolute difference of a Body's per-step velocity and its overlap with another Body that will result in separation on *each axis*. + * Larger values favor separation. + * Smaller values favor no separation. + * + * @name Phaser.Physics.Arcade.World#OVERLAP_BIAS + * @type {number} + * @default 4 + * @since 3.0.0 + */ + this.OVERLAP_BIAS = GetValue(config, 'overlapBias', 4); + + /** + * The maximum absolute value of a Body's overlap with a tile that will result in separation on *each axis*. + * Larger values favor separation. + * Smaller values favor no separation. + * The optimum value may be similar to the tile size. + * + * @name Phaser.Physics.Arcade.World#TILE_BIAS + * @type {number} + * @default 16 + * @since 3.0.0 + */ + this.TILE_BIAS = GetValue(config, 'tileBias', 16); + + /** + * Always separate overlapping Bodies horizontally before vertically. + * False (the default) means Bodies are first separated on the axis of greater gravity, or the vertical axis if neither is greater. + * + * @name Phaser.Physics.Arcade.World#forceX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.forceX = GetValue(config, 'forceX', false); + + /** + * Whether the simulation advances with the game loop. + * + * @name Phaser.Physics.Arcade.World#isPaused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isPaused = GetValue(config, 'isPaused', false); + + /** + * Temporary total of colliding Bodies. + * + * @name Phaser.Physics.Arcade.World#_total + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._total = 0; + + /** + * Enables the debug display. + * + * @name Phaser.Physics.Arcade.World#drawDebug + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.drawDebug = GetValue(config, 'debug', false); + + /** + * The graphics object drawing the debug display. + * + * @name Phaser.Physics.Arcade.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + /** + * Default debug display settings for new Bodies. + * + * @name Phaser.Physics.Arcade.World#defaults + * @type {Phaser.Types.Physics.Arcade.ArcadeWorldDefaults} + * @since 3.0.0 + */ + this.defaults = { + debugShowBody: GetValue(config, 'debugShowBody', true), + debugShowStaticBody: GetValue(config, 'debugShowStaticBody', true), + debugShowVelocity: GetValue(config, 'debugShowVelocity', true), + bodyDebugColor: GetValue(config, 'debugBodyColor', 0xff00ff), + staticBodyDebugColor: GetValue(config, 'debugStaticBodyColor', 0x0000ff), + velocityDebugColor: GetValue(config, 'debugVelocityColor', 0x00ff00) + }; + + /** + * The maximum number of items per node on the RTree. + * + * This is ignored if `useTree` is `false`. If you have a large number of bodies in + * your world then you may find search performance improves by increasing this value, + * to allow more items per node and less node division. + * + * @name Phaser.Physics.Arcade.World#maxEntries + * @type {integer} + * @default 16 + * @since 3.0.0 + */ + this.maxEntries = GetValue(config, 'maxEntries', 16); + + /** + * Should this Arcade Physics World use an RTree for Dynamic and Static Physics bodies? + * + * An RTree is a fast way of spatially sorting of all the bodies in the world. + * However, at certain limits, the cost of clearing and inserting the bodies into the + * tree every frame becomes more expensive than the search speed gains it provides. + * + * If you have a large number of dynamic bodies in your world then it may be best to + * disable the use of the RTree by setting this property to `false` in the physics config. + * + * The number it can cope with depends on browser and device, but a conservative estimate + * of around 5,000 bodies should be considered the max before disabling it. + * + * This only applies to dynamic bodies. Static bodies are always kept in an RTree, + * because they don't have to be cleared every frame, so you benefit from the + * massive search speeds all the time. + * + * @name Phaser.Physics.Arcade.World#useTree + * @type {boolean} + * @default true + * @since 3.10.0 + */ + this.useTree = GetValue(config, 'useTree', true); + + /** + * The spatial index of Dynamic Bodies. + * + * @name Phaser.Physics.Arcade.World#tree + * @type {Phaser.Structs.RTree} + * @since 3.0.0 + */ + this.tree = new RTree(this.maxEntries); + + /** + * The spatial index of Static Bodies. + * + * @name Phaser.Physics.Arcade.World#staticTree + * @type {Phaser.Structs.RTree} + * @since 3.0.0 + */ + this.staticTree = new RTree(this.maxEntries); + + /** + * Recycled input for tree searches. + * + * @name Phaser.Physics.Arcade.World#treeMinMax + * @type {Phaser.Types.Physics.Arcade.ArcadeWorldTreeMinMax} + * @since 3.0.0 + */ + this.treeMinMax = { minX: 0, minY: 0, maxX: 0, maxY: 0 }; + + /** + * A temporary Transform Matrix used by bodies for calculations without them needing their own local copy. + * + * @name Phaser.Physics.Arcade.World#_tempMatrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.12.0 + */ + this._tempMatrix = new TransformMatrix(); + + /** + * A temporary Transform Matrix used by bodies for calculations without them needing their own local copy. + * + * @name Phaser.Physics.Arcade.World#_tempMatrix2 + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + }, + + /** + * Adds an Arcade Physics Body to a Game Object, an array of Game Objects, or the children of a Group. + * + * The difference between this and the `enableBody` method is that you can pass arrays or Groups + * to this method. + * + * You can specify if the bodies are to be Dynamic or Static. A dynamic body can move via velocity and + * acceleration. A static body remains fixed in place and as such is able to use an optimized search + * tree, making it ideal for static elements such as level objects. You can still collide and overlap + * with static bodies. + * + * Normally, rather than calling this method directly, you'd use the helper methods available in the + * Arcade Physics Factory, such as: + * + * ```javascript + * this.physics.add.image(x, y, textureKey); + * this.physics.add.sprite(x, y, textureKey); + * ``` + * + * Calling factory methods encapsulates the creation of a Game Object and the creation of its + * body at the same time. If you are creating custom classes then you can pass them to this + * method to have their bodies created. + * + * @method Phaser.Physics.Arcade.World#enable + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object - The object, or objects, on which to create the bodies. + * @param {integer} [bodyType] - The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. + */ + enable: function (object, bodyType) + { + if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY; } + + if (!Array.isArray(object)) + { + object = [ object ]; + } + + for (var i = 0; i < object.length; i++) + { + var entry = object[i]; + + if (entry.isParent) + { + var children = entry.getChildren(); + + for (var c = 0; c < children.length; c++) + { + var child = children[c]; + + if (child.isParent) + { + // Handle Groups nested inside of Groups + this.enable(child, bodyType); + } + else + { + this.enableBody(child, bodyType); + } + } + } + else + { + this.enableBody(entry, bodyType); + } + } + }, + + /** + * Creates an Arcade Physics Body on a single Game Object. + * + * If the Game Object already has a body, this method will simply add it back into the simulation. + * + * You can specify if the body is Dynamic or Static. A dynamic body can move via velocity and + * acceleration. A static body remains fixed in place and as such is able to use an optimized search + * tree, making it ideal for static elements such as level objects. You can still collide and overlap + * with static bodies. + * + * Normally, rather than calling this method directly, you'd use the helper methods available in the + * Arcade Physics Factory, such as: + * + * ```javascript + * this.physics.add.image(x, y, textureKey); + * this.physics.add.sprite(x, y, textureKey); + * ``` + * + * Calling factory methods encapsulates the creation of a Game Object and the creation of its + * body at the same time. If you are creating custom classes then you can pass them to this + * method to have their bodies created. + * + * @method Phaser.Physics.Arcade.World#enableBody + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} object - The Game Object on which to create the body. + * @param {integer} [bodyType] - The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. + * + * @return {Phaser.GameObjects.GameObject} The Game Object on which the body was created. + */ + enableBody: function (object, bodyType) + { + if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY; } + + if (!object.body) + { + if (bodyType === CONST.DYNAMIC_BODY) + { + object.body = new Body(this, object); + } + else if (bodyType === CONST.STATIC_BODY) + { + object.body = new StaticBody(this, object); + } + } + + this.add(object.body); + + return object; + }, + + /** + * Adds an existing Arcade Physics Body or StaticBody to the simulation. + * + * The body is enabled and added to the local search trees. + * + * @method Phaser.Physics.Arcade.World#add + * @since 3.10.0 + * + * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The Body to be added to the simulation. + * + * @return {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} The Body that was added to the simulation. + */ + add: function (body) + { + if (body.physicsType === CONST.DYNAMIC_BODY) + { + this.bodies.set(body); + } + else if (body.physicsType === CONST.STATIC_BODY) + { + this.staticBodies.set(body); + + this.staticTree.insert(body); + } + + body.enable = true; + + return body; + }, + + /** + * Disables the Arcade Physics Body of a Game Object, an array of Game Objects, or the children of a Group. + * + * The difference between this and the `disableBody` method is that you can pass arrays or Groups + * to this method. + * + * The body itself is not deleted, it just has its `enable` property set to false, which + * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. + * + * @method Phaser.Physics.Arcade.World#disable + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object - The object, or objects, on which to disable the bodies. + */ + disable: function (object) + { + if (!Array.isArray(object)) + { + object = [ object ]; + } + + for (var i = 0; i < object.length; i++) + { + var entry = object[i]; + + if (entry.isParent) + { + var children = entry.getChildren(); + + for (var c = 0; c < children.length; c++) + { + var child = children[c]; + + if (child.isParent) + { + // Handle Groups nested inside of Groups + this.disable(child); + } + else + { + this.disableBody(child.body); + } + } + } + else + { + this.disableBody(entry.body); + } + } + }, + + /** + * Disables an existing Arcade Physics Body or StaticBody and removes it from the simulation. + * + * The body is disabled and removed from the local search trees. + * + * The body itself is not deleted, it just has its `enable` property set to false, which + * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. + * + * @method Phaser.Physics.Arcade.World#disableBody + * @since 3.0.0 + * + * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The Body to be disabled. + */ + disableBody: function (body) + { + this.remove(body); + + body.enable = false; + }, + + /** + * Removes an existing Arcade Physics Body or StaticBody from the simulation. + * + * The body is disabled and removed from the local search trees. + * + * The body itself is not deleted, it just has its `enabled` property set to false, which + * means you can re-enable it again at any point by passing it to enable `enable` or `add`. + * + * @method Phaser.Physics.Arcade.World#remove + * @since 3.0.0 + * + * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The body to be removed from the simulation. + */ + remove: function (body) + { + if (body.physicsType === CONST.DYNAMIC_BODY) + { + this.tree.remove(body); + this.bodies.delete(body); + } + else if (body.physicsType === CONST.STATIC_BODY) + { + this.staticBodies.delete(body); + this.staticTree.remove(body); + } + }, + + /** + * Creates a Graphics Game Object that the world will use to render the debug display to. + * + * This is called automatically when the World is instantiated if the `debug` config property + * was set to `true`. However, you can call it at any point should you need to display the + * debug Graphic from a fixed point. + * + * You can control which objects are drawn to the Graphics object, and the colors they use, + * by setting the debug properties in the physics config. + * + * You should not typically use this in a production game. Use it to aid during debugging. + * + * @method Phaser.Physics.Arcade.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The Graphics object that was created for use by the World. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * Sets the position, size and properties of the World boundary. + * + * The World boundary is an invisible rectangle that defines the edges of the World. + * If a Body is set to collide with the world bounds then it will automatically stop + * when it reaches any of the edges. You can optionally set which edges of the boundary + * should be checked against. + * + * @method Phaser.Physics.Arcade.World#setBounds + * @since 3.0.0 + * + * @param {number} x - The top-left x coordinate of the boundary. + * @param {number} y - The top-left y coordinate of the boundary. + * @param {number} width - The width of the boundary. + * @param {number} height - The height of the boundary. + * @param {boolean} [checkLeft] - Should bodies check against the left edge of the boundary? + * @param {boolean} [checkRight] - Should bodies check against the right edge of the boundary? + * @param {boolean} [checkUp] - Should bodies check against the top edge of the boundary? + * @param {boolean} [checkDown] - Should bodies check against the bottom edge of the boundary? + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + setBounds: function (x, y, width, height, checkLeft, checkRight, checkUp, checkDown) + { + this.bounds.setTo(x, y, width, height); + + if (checkLeft !== undefined) + { + this.setBoundsCollision(checkLeft, checkRight, checkUp, checkDown); + } + + return this; + }, + + /** + * Enables or disables collisions on each edge of the World boundary. + * + * @method Phaser.Physics.Arcade.World#setBoundsCollision + * @since 3.0.0 + * + * @param {boolean} [left=true] - Should bodies check against the left edge of the boundary? + * @param {boolean} [right=true] - Should bodies check against the right edge of the boundary? + * @param {boolean} [up=true] - Should bodies check against the top edge of the boundary? + * @param {boolean} [down=true] - Should bodies check against the bottom edge of the boundary? + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + setBoundsCollision: function (left, right, up, down) + { + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (up === undefined) { up = true; } + if (down === undefined) { down = true; } + + this.checkCollision.left = left; + this.checkCollision.right = right; + this.checkCollision.up = up; + this.checkCollision.down = down; + + return this; + }, + + /** + * Pauses the simulation. + * + * A paused simulation does not update any existing bodies, or run any Colliders. + * + * However, you can still enable and disable bodies within it, or manually run collide or overlap + * checks. + * + * @method Phaser.Physics.Arcade.World#pause + * @fires Phaser.Physics.Arcade.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + pause: function () + { + this.isPaused = true; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * Resumes the simulation, if paused. + * + * @method Phaser.Physics.Arcade.World#resume + * @fires Phaser.Physics.Arcade.Events#RESUME + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + resume: function () + { + this.isPaused = false; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * Creates a new Collider object and adds it to the simulation. + * + * A Collider is a way to automatically perform collision checks between two objects, + * calling the collide and process callbacks if they occur. + * + * Colliders are run as part of the World update, after all of the Bodies have updated. + * + * By creating a Collider you don't need then call `World.collide` in your `update` loop, + * as it will be handled for you automatically. + * + * @method Phaser.Physics.Arcade.World#addCollider + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#collide + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + addCollider: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + var collider = new Collider(this, false, object1, object2, collideCallback, processCallback, callbackContext); + + this.colliders.add(collider); + + return collider; + }, + + /** + * Creates a new Overlap Collider object and adds it to the simulation. + * + * A Collider is a way to automatically perform overlap checks between two objects, + * calling the collide and process callbacks if they occur. + * + * Colliders are run as part of the World update, after all of the Bodies have updated. + * + * By creating a Collider you don't need then call `World.overlap` in your `update` loop, + * as it will be handled for you automatically. + * + * @method Phaser.Physics.Arcade.World#addOverlap + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for overlap. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for overlap. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects overlap. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + addOverlap: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + var collider = new Collider(this, true, object1, object2, collideCallback, processCallback, callbackContext); + + this.colliders.add(collider); + + return collider; + }, + + /** + * Removes a Collider from the simulation so it is no longer processed. + * + * This method does not destroy the Collider. If you wish to add it back at a later stage you can call + * `World.colliders.add(Collider)`. + * + * If you no longer need the Collider you can call the `Collider.destroy` method instead, which will + * automatically clear all of its references and then remove it from the World. If you call destroy on + * a Collider you _don't_ need to pass it to this method too. + * + * @method Phaser.Physics.Arcade.World#removeCollider + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Collider} collider - The Collider to remove from the simulation. + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + removeCollider: function (collider) + { + this.colliders.remove(collider); + + return this; + }, + + /** + * Sets the frame rate to run the simulation at. + * + * The frame rate value is used to simulate a fixed update time step. This fixed + * time step allows for a straightforward implementation of a deterministic game state. + * + * This frame rate is independent of the frequency at which the game is rendering. The + * higher you set the fps, the more physics simulation steps will occur per game step. + * Conversely, the lower you set it, the less will take place. + * + * You can optionally advance the simulation directly yourself by calling the `step` method. + * + * @method Phaser.Physics.Arcade.World#setFPS + * @since 3.10.0 + * + * @param {integer} framerate - The frame rate to advance the simulation at. + * + * @return {this} This World object. + */ + setFPS: function (framerate) + { + this.fps = framerate; + this._frameTime = 1 / this.fps; + this._frameTimeMS = 1000 * this._frameTime; + + return this; + }, + + /** + * 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 + * @protected + * @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. + */ + update: function (time, delta) + { + if (this.isPaused || this.bodies.size === 0) + { + return; + } + + var i; + var fixedDelta = this._frameTime; + var msPerFrame = this._frameTimeMS * this.timeScale; + + this._elapsed += delta; + + // Update all active bodies + var body; + var bodies = this.bodies.entries; + + // Will a step happen this frame? + var willStep = (this._elapsed >= msPerFrame); + + for (i = 0; i < bodies.length; i++) + { + body = bodies[i]; + + if (body.enable) + { + body.preUpdate(willStep, fixedDelta); + } + } + + // We know that a step will happen this frame, so let's bundle it all together to save branching and iteration costs + if (willStep) + { + this._elapsed -= msPerFrame; + this.stepsLastFrame = 1; + + // Optionally populate our dynamic collision tree + if (this.useTree) + { + this.tree.clear(); + this.tree.load(bodies); + } + + // Process any colliders + var colliders = this.colliders.update(); + + for (i = 0; i < colliders.length; i++) + { + var collider = colliders[i]; + + if (collider.active) + { + collider.update(); + } + } + + this.emit(Events.WORLD_STEP); + } + + // Process any additional steps this frame + while (this._elapsed >= msPerFrame) + { + this._elapsed -= msPerFrame; + + this.step(fixedDelta); + } + }, + + /** + * Advances the simulation by a time increment. + * + * @method Phaser.Physics.Arcade.World#step + * @fires Phaser.Physics.Arcade.Events#WORLD_STEP + * @since 3.10.0 + * + * @param {number} delta - The delta time amount, in seconds, by which to advance the simulation. + */ + step: function (delta) + { + // Update all active bodies + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enable) + { + body.update(delta); + } + } + + // Optionally populate our dynamic collision tree + if (this.useTree) + { + this.tree.clear(); + this.tree.load(bodies); + } + + // Process any colliders + var colliders = this.colliders.update(); + + for (i = 0; i < colliders.length; i++) + { + var collider = colliders[i]; + + if (collider.active) + { + collider.update(); + } + } + + this.emit(Events.WORLD_STEP); + + this.stepsLastFrame++; + }, + + /** + * Updates bodies, draws the debug display, and handles pending queue operations. + * + * @method Phaser.Physics.Arcade.World#postUpdate + * @since 3.0.0 + */ + postUpdate: function () + { + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + + var dynamic = this.bodies; + var staticBodies = this.staticBodies; + + // We don't need to postUpdate if there wasn't a step this frame + if (this.stepsLastFrame) + { + this.stepsLastFrame = 0; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enable) + { + body.postUpdate(); + } + } + } + + if (this.drawDebug) + { + var graphics = this.debugGraphic; + + graphics.clear(); + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + + bodies = staticBodies.entries; + len = bodies.length; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + } + + var pending = this.pendingDestroy; + + if (pending.size > 0) + { + var dynamicTree = this.tree; + var staticTree = this.staticTree; + + bodies = pending.entries; + len = bodies.length; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.physicsType === CONST.DYNAMIC_BODY) + { + dynamicTree.remove(body); + dynamic.delete(body); + } + else if (body.physicsType === CONST.STATIC_BODY) + { + staticTree.remove(body); + staticBodies.delete(body); + } + + body.world = undefined; + body.gameObject = undefined; + } + + pending.clear(); + } + }, + + /** + * Calculates a Body's velocity and updates its position. + * + * @method Phaser.Physics.Arcade.World#updateMotion + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body to be updated. + * @param {number} delta - The delta value to be used in the motion calculations, in seconds. + */ + updateMotion: function (body, delta) + { + if (body.allowRotation) + { + this.computeAngularVelocity(body, delta); + } + + this.computeVelocity(body, delta); + }, + + /** + * Calculates a Body's angular velocity. + * + * @method Phaser.Physics.Arcade.World#computeAngularVelocity + * @since 3.10.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body to compute the velocity for. + * @param {number} delta - The delta value to be used in the calculation, in seconds. + */ + computeAngularVelocity: function (body, delta) + { + var velocity = body.angularVelocity; + var acceleration = body.angularAcceleration; + var drag = body.angularDrag; + var max = body.maxAngular; + + if (acceleration) + { + velocity += acceleration * delta; + } + else if (body.allowDrag && drag) + { + drag *= delta; + + if (FuzzyGreaterThan(velocity - drag, 0, 0.1)) + { + velocity -= drag; + } + else if (FuzzyLessThan(velocity + drag, 0, 0.1)) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + velocity = Clamp(velocity, -max, max); + + var velocityDelta = velocity - body.angularVelocity; + + body.angularVelocity += velocityDelta; + body.rotation += (body.angularVelocity * delta); + }, + + /** + * Calculates a Body's per-axis velocity. + * + * @method Phaser.Physics.Arcade.World#computeVelocity + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body to compute the velocity for. + * @param {number} delta - The delta value to be used in the calculation, in seconds. + */ + computeVelocity: function (body, delta) + { + var velocityX = body.velocity.x; + var accelerationX = body.acceleration.x; + var dragX = body.drag.x; + var maxX = body.maxVelocity.x; + + var velocityY = body.velocity.y; + var accelerationY = body.acceleration.y; + var dragY = body.drag.y; + var maxY = body.maxVelocity.y; + + var speed = body.speed; + var maxSpeed = body.maxSpeed; + var allowDrag = body.allowDrag; + var useDamping = body.useDamping; + + if (body.allowGravity) + { + velocityX += (this.gravity.x + body.gravity.x) * delta; + velocityY += (this.gravity.y + body.gravity.y) * delta; + } + + if (accelerationX) + { + velocityX += accelerationX * delta; + } + else if (allowDrag && dragX) + { + if (useDamping) + { + // Damping based deceleration + + velocityX *= dragX; + + speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY); + + if (FuzzyEqual(speed, 0, 0.001)) + { + velocityX = 0; + } + } + else + { + // Linear deceleration + dragX *= delta; + + if (FuzzyGreaterThan(velocityX - dragX, 0, 0.01)) + { + velocityX -= dragX; + } + else if (FuzzyLessThan(velocityX + dragX, 0, 0.01)) + { + velocityX += dragX; + } + else + { + velocityX = 0; + } + } + } + + if (accelerationY) + { + velocityY += accelerationY * delta; + } + else if (allowDrag && dragY) + { + if (useDamping) + { + // Damping based deceleration + velocityY *= dragY; + + speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY); + + if (FuzzyEqual(speed, 0, 0.001)) + { + velocityY = 0; + } + } + else + { + // Linear deceleration + dragY *= delta; + + if (FuzzyGreaterThan(velocityY - dragY, 0, 0.01)) + { + velocityY -= dragY; + } + else if (FuzzyLessThan(velocityY + dragY, 0, 0.01)) + { + velocityY += dragY; + } + else + { + velocityY = 0; + } + } + } + + velocityX = Clamp(velocityX, -maxX, maxX); + velocityY = Clamp(velocityY, -maxY, maxY); + + body.velocity.set(velocityX, velocityY); + + if (maxSpeed > -1 && speed > maxSpeed) + { + body.velocity.normalize().scale(maxSpeed); + speed = maxSpeed; + } + + body.speed = speed; + }, + + /** + * Separates two Bodies. + * + * @method Phaser.Physics.Arcade.World#separate + * @fires Phaser.Physics.Arcade.Events#COLLIDE + * @fires Phaser.Physics.Arcade.Events#OVERLAP + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to be separated. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to be separated. + * @param {ArcadePhysicsCallback} [processCallback] - The process callback. + * @param {*} [callbackContext] - The context in which to invoke the callback. + * @param {boolean} [overlapOnly] - If this a collide or overlap check? + * + * @return {boolean} True if separation occurred, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) + { + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.gameObject, body2.gameObject) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); + } + } + else + { + resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap || body2.onOverlap) + { + this.emit(Events.OVERLAP, body1.gameObject, body2.gameObject, body1, body2); + } + } + else if (body1.onCollide || body2.onCollide) + { + this.emit(Events.COLLIDE, body1.gameObject, body2.gameObject, body1, body2); + } + } + + return result; + }, + + /** + * Separates two Bodies, when both are circular. + * + * @method Phaser.Physics.Arcade.World#separateCircle + * @fires Phaser.Physics.Arcade.Events#COLLIDE + * @fires Phaser.Physics.Arcade.Events#OVERLAP + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to be separated. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to be separated. + * @param {boolean} [overlapOnly] - If this a collide or overlap check? + * @param {number} [bias] - A small value added to the calculations. + * + * @return {boolean} True if separation occurred, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly, bias) + { + // Set the bounding box overlap values into the bodies themselves (hence we don't use the return values here) + GetOverlapX(body1, body2, false, bias); + GetOverlapY(body1, body2, false, bias); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0 && (body1.onOverlap || body2.onOverlap)) + { + this.emit(Events.OVERLAP, body1.gameObject, body2.gameObject, body1, body2); + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + var dx = body1.center.x - body2.center.x; + var dy = body1.center.y - body2.center.y; + var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); + var nx = ((body2.center.x - body1.center.x) / d) || 0; + var ny = ((body2.center.y - body1.center.y) / d) || 0; + var p = 2 * (body1.velocity.x * nx + body1.velocity.y * ny - body2.velocity.x * nx - body2.velocity.y * ny) / (body1.mass + body2.mass); + + if (!body1.immovable) + { + body1.velocity.x = (body1.velocity.x - p * body1.mass * nx); + body1.velocity.y = (body1.velocity.y - p * body1.mass * ny); + } + + if (!body2.immovable) + { + body2.velocity.x = (body2.velocity.x + p * body2.mass * nx); + body2.velocity.y = (body2.velocity.y + p * body2.mass * ny); + } + + var dvx = body2.velocity.x - body1.velocity.x; + var dvy = body2.velocity.y - body1.velocity.y; + var angleCollision = Math.atan2(dvy, dvx); + + var delta = this._frameTime; + + if (!body1.immovable && !body2.immovable) + { + overlap /= 2; + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * delta) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * delta) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * delta) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * delta) + overlap * Math.sin(angleCollision); + } + + body1.velocity.x *= body1.bounce.x; + body1.velocity.y *= body1.bounce.y; + body2.velocity.x *= body2.bounce.x; + body2.velocity.y *= body2.bounce.y; + + if (body1.onCollide || body2.onCollide) + { + this.emit(Events.COLLIDE, body1.gameObject, body2.gameObject, body1, body2); + } + + return true; + }, + + /** + * Checks to see if two Bodies intersect at all. + * + * @method Phaser.Physics.Arcade.World#intersects + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body1 - The first body to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second body to check. + * + * @return {boolean} True if the two bodies intersect, otherwise false. + */ + intersects: function (body1, body2) + { + if (body1 === body2) + { + return false; + } + + if (!body1.isCircle && !body2.isCircle) + { + // Rect vs. Rect + return !( + body1.right <= body2.position.x || + body1.bottom <= body2.position.y || + body1.position.x >= body2.right || + body1.position.y >= body2.bottom + ); + } + else if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + }, + + /** + * Tests if a circular Body intersects with another Body. + * + * @method Phaser.Physics.Arcade.World#circleBodyIntersects + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} circle - The circular body to test. + * @param {Phaser.Physics.Arcade.Body} body - The rectangular body to test. + * + * @return {boolean} True if the two bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) + { + var x = Clamp(circle.center.x, body.left, body.right); + var y = Clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + }, + + /** + * Tests if Game Objects overlap. + * + * @method Phaser.Physics.Arcade.World#overlap + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {*} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if at least one Game Object overlaps another. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) + { + if (overlapCallback === undefined) { overlapCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = overlapCallback; } + + return this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + }, + + /** + * Performs a collision check and separation between the two physics enabled objects given, which can be single + * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. + * + * If you don't require separation then use {@link #overlap} instead. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. + * + * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding + * objects are passed to it. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * + * @method Phaser.Physics.Arcade.World#collide + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} `true` if any overlapping Game Objects were separated, otherwise `false`. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + return this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + }, + + /** + * Internal helper function. Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideObjects + * @private + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object to check for collision. + * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. + * @param {any} callbackContext - The scope in which to call the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) + { + var i; + var j; + + if (object1.isParent && object1.physicsType === undefined) + { + object1 = object1.children.entries; + } + + if (object2 && object2.isParent && object2.physicsType === undefined) + { + object2 = object2.children.entries; + } + + var object1isArray = Array.isArray(object1); + var object2isArray = Array.isArray(object2); + + this._total = 0; + + if (!object1isArray && !object2isArray) + { + // Neither of them are arrays - do this first as it's the most common use-case + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (!object1isArray && object2isArray) + { + // Object 2 is an Array + for (i = 0; i < object2.length; i++) + { + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (object1isArray && !object2isArray) + { + // Object 1 is an Array + if (!object2) + { + // Special case for array vs. self + for (i = 0; i < object1.length; i++) + { + var child = object1[i]; + + for (j = i + 1; j < object1.length; j++) + { + if (i === j) + { + continue; + } + + this.collideHandler(child, object1[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + for (i = 0; i < object1.length; i++) + { + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + // They're both arrays + for (i = 0; i < object1.length; i++) + { + for (j = 0; j < object2.length; j++) + { + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + return (this._total > 0); + }, + + /** + * Internal helper function. Please use Phaser.Physics.Arcade.World#collide and Phaser.Physics.Arcade.World#overlap instead. + * + * @method Phaser.Physics.Arcade.World#collideHandler + * @private + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} collideCallback - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} processCallback - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) + { + // Collide Group with Self + // Only collide valid objects + if (object2 === undefined && object1.isParent) + { + return this.collideGroupVsGroup(object1, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + + // If neither of the objects are set then bail out + if (!object1 || !object2) + { + return false; + } + + // A Body + if (object1.body) + { + if (object2.body) + { + return this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isParent) + { + return this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isTilemap) + { + return this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + // GROUPS + else if (object1.isParent) + { + if (object2.body) + { + return this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isParent) + { + return this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isTilemap) + { + return this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + // TILEMAP LAYERS + else if (object1.isTilemap) + { + if (object2.body) + { + return this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isParent) + { + return this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + }, + + /** + * Internal handler for Sprite vs. Sprite collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsSprite + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} sprite1 - The first object to check for collision. + * @param {Phaser.GameObjects.GameObject} sprite2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) + { + if (!sprite1.body || !sprite2.body) + { + return false; + } + + if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite1, sprite2); + } + + this._total++; + } + + return true; + }, + + /** + * Internal handler for Sprite vs. Group collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsGroup + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.GameObjects.Group} group - The second object to check for collision. + * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. + * @param {any} callbackContext - The scope in which to call the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} `true` if the Sprite collided with the given Group, otherwise `false`. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) + { + var bodyA = sprite.body; + + if (group.length === 0 || !bodyA || !bodyA.enable) + { + return; + } + + // Does sprite collide with anything? + + var i; + var len; + var bodyB; + + if (this.useTree) + { + var minMax = this.treeMinMax; + + minMax.minX = bodyA.left; + minMax.minY = bodyA.top; + minMax.maxX = bodyA.right; + minMax.maxY = bodyA.bottom; + + var results = (group.physicsType === CONST.DYNAMIC_BODY) ? this.tree.search(minMax) : this.staticTree.search(minMax); + + len = results.length; + + for (i = 0; i < len; i++) + { + bodyB = results[i]; + + if (bodyA === bodyB || !bodyB.enable || !group.contains(bodyB.gameObject)) + { + // Skip if comparing against itself, or if bodyB isn't actually part of the Group + continue; + } + + if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject); + } + + this._total++; + } + } + } + else + { + var children = group.getChildren(); + var skipIndex = group.children.entries.indexOf(sprite); + + len = children.length; + + for (i = 0; i < len; i++) + { + bodyB = children[i].body; + + if (!bodyB || i === skipIndex || !bodyB.enable) + { + continue; + } + + if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject); + } + + this._total++; + } + } + } + }, + + /** + * Internal handler for Group vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideGroupVsTilemapLayer + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Group} group - The first object to check for collision. + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) + { + var children = group.getChildren(); + + if (children.length === 0) + { + return false; + } + + var didCollide = false; + + for (var i = 0; i < children.length; i++) + { + if (children[i].body) + { + if (this.collideSpriteVsTilemapLayer(children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly)) + { + didCollide = true; + } + } + } + + return didCollide; + }, + + /** + * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. + * + * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for collision with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions + * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have + * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the + * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on + * dynamic maps, this method can prove very useful. + * + * @method Phaser.Physics.Arcade.World#collideTiles + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + if (!sprite.body.enable || tiles.length === 0) + { + return false; + } + else + { + return this.collideSpriteVsTilesHandler(sprite, tiles, collideCallback, processCallback, callbackContext, false, false); + } + }, + + /** + * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. + * + * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap + * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * @method Phaser.Physics.Arcade.World#overlapTiles + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + overlapTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + if (!sprite.body.enable || tiles.length === 0) + { + return false; + } + else + { + return this.collideSpriteVsTilesHandler(sprite, tiles, collideCallback, processCallback, callbackContext, true, false); + } + }, + + /** + * Internal handler for Sprite vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsTilemapLayer + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} [overlapOnly] - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) + { + var body = sprite.body; + + if (!body.enable) + { + return false; + } + + var x = body.position.x; + var y = body.position.y; + var w = body.width; + var h = body.height; + + // TODO: this logic should be encapsulated within the Tilemap API at some point. + // If the maps base tile size differs from the layer's tile size, we need to adjust the + // selection area by the difference between the two. + var layerData = tilemapLayer.layer; + + if (layerData.tileWidth > layerData.baseTileWidth) + { + // The x origin of a tile is the left side, so x and width need to be adjusted. + var xDiff = (layerData.tileWidth - layerData.baseTileWidth) * tilemapLayer.scaleX; + x -= xDiff; + w += xDiff; + } + + if (layerData.tileHeight > layerData.baseTileHeight) + { + // The y origin of a tile is the bottom side, so just the height needs to be adjusted. + var yDiff = (layerData.tileHeight - layerData.baseTileHeight) * tilemapLayer.scaleY; + h += yDiff; + } + + var mapData = tilemapLayer.getTilesWithinWorldXY(x, y, w, h); + + if (mapData.length === 0) + { + return false; + } + else + { + return this.collideSpriteVsTilesHandler(sprite, mapData, collideCallback, processCallback, callbackContext, overlapOnly, true); + } + }, + + /** + * Internal handler for Sprite vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsTilesHandler + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @private + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} [overlapOnly] - Whether this is a collision or overlap check. + * @param {boolean} [isLayer] - Is this check coming from a TilemapLayer or an array of tiles? + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideSpriteVsTilesHandler: function (sprite, tiles, collideCallback, processCallback, callbackContext, overlapOnly, isLayer) + { + var body = sprite.body; + + var tile; + var tileWorldRect = { left: 0, right: 0, top: 0, bottom: 0 }; + var tilemapLayer; + var collision = false; + + for (var i = 0; i < tiles.length; i++) + { + tile = tiles[i]; + + tilemapLayer = tile.tilemapLayer; + + tileWorldRect.left = tilemapLayer.tileToWorldX(tile.x); + tileWorldRect.top = tilemapLayer.tileToWorldY(tile.y); + + // If the map's base tile size differs from the layer's tile size, only the top of the rect + // needs to be adjusted since its origin is (0, 1). + if (tile.baseHeight !== tile.height) + { + tileWorldRect.top -= (tile.height - tile.baseHeight) * tilemapLayer.scaleY; + } + + tileWorldRect.right = tileWorldRect.left + tile.width * tilemapLayer.scaleX; + tileWorldRect.bottom = tileWorldRect.top + tile.height * tilemapLayer.scaleY; + + if (TileIntersectsBody(tileWorldRect, body) + && (!processCallback || processCallback.call(callbackContext, sprite, tile)) + && ProcessTileCallbacks(tile, sprite) + && (overlapOnly || SeparateTile(i, body, tile, tileWorldRect, tilemapLayer, this.TILE_BIAS, isLayer))) + { + this._total++; + + collision = true; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, tile); + } + + if (overlapOnly && body.onOverlap) + { + this.emit(Events.TILE_OVERLAP, sprite, tile, body); + } + else if (body.onCollide) + { + this.emit(Events.TILE_COLLIDE, sprite, tile, body); + } + } + } + + return collision; + }, + + /** + * Internal helper for Group vs. Group collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideGroupVsGroup + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Group} group1 - The first object to check for collision. + * @param {Phaser.GameObjects.Group} group2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) + { + if (group1.length === 0 || group2.length === 0) + { + return; + } + + var children = group1.getChildren(); + + for (var i = 0; i < children.length; i++) + { + this.collideSpriteVsGroup(children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + }, + + /** + * Wrap an object's coordinates (or several objects' coordinates) within {@link Phaser.Physics.Arcade.World#bounds}. + * + * If the object is outside any boundary edge (left, top, right, bottom), it will be moved to the same offset from the opposite edge (the interior). + * + * @method Phaser.Physics.Arcade.World#wrap + * @since 3.3.0 + * + * @param {*} object - A Game Object, a Group, an object with `x` and `y` coordinates, or an array of such objects. + * @param {number} [padding=0] - An amount added to each boundary edge during the operation. + */ + wrap: function (object, padding) + { + if (object.body) + { + this.wrapObject(object, padding); + } + else if (object.getChildren) + { + this.wrapArray(object.getChildren(), padding); + } + else if (Array.isArray(object)) + { + this.wrapArray(object, padding); + } + else + { + this.wrapObject(object, padding); + } + }, + + /** + * Wrap each object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. + * + * @method Phaser.Physics.Arcade.World#wrapArray + * @since 3.3.0 + * + * @param {Array.<*>} objects - An array of objects to be wrapped. + * @param {number} [padding=0] - An amount added to the boundary. + */ + wrapArray: function (objects, padding) + { + for (var i = 0; i < objects.length; i++) + { + this.wrapObject(objects[i], padding); + } + }, + + /** + * Wrap an object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. + * + * @method Phaser.Physics.Arcade.World#wrapObject + * @since 3.3.0 + * + * @param {*} object - A Game Object, a Physics Body, or any object with `x` and `y` coordinates + * @param {number} [padding=0] - An amount added to the boundary. + */ + wrapObject: function (object, padding) + { + if (padding === undefined) { padding = 0; } + + object.x = Wrap(object.x, this.bounds.left - padding, this.bounds.right + padding); + object.y = Wrap(object.y, this.bounds.top - padding, this.bounds.bottom + padding); + }, + + /** + * Shuts down the simulation, clearing physics data and removing listeners. + * + * @method Phaser.Physics.Arcade.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.tree.clear(); + this.staticTree.clear(); + this.bodies.clear(); + this.staticBodies.clear(); + this.colliders.destroy(); + + this.removeAllListeners(); + }, + + /** + * Shuts down the simulation and disconnects it from the current scene. + * + * @method Phaser.Physics.Arcade.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene = null; + } + +}); + +module.exports = World; + + +/***/ }), +/* 489 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Benjamin D. Richards + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(58); +var Events = __webpack_require__(230); +var RadToDeg = __webpack_require__(184); +var Rectangle = __webpack_require__(11); +var RectangleContains = __webpack_require__(53); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Dynamic Arcade Body. + * + * Its static counterpart is {@link Phaser.Physics.Arcade.StaticBody}. + * + * @class Body + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics simulation this Body belongs to. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object this Body belongs to. + */ +var Body = new Class({ + + initialize: + + function Body (world, gameObject) + { + var width = (gameObject.width) ? gameObject.width : 64; + var height = (gameObject.height) ? gameObject.height : 64; + + /** + * The Arcade Physics simulation this Body belongs to. + * + * @name Phaser.Physics.Arcade.Body#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Game Object this Body belongs to. + * + * @name Phaser.Physics.Arcade.Body#gameObject + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.gameObject = gameObject; + + /** + * Transformations applied to this Body. + * + * @name Phaser.Physics.Arcade.Body#transform + * @type {object} + * @since 3.4.0 + */ + this.transform = { + x: gameObject.x, + y: gameObject.y, + rotation: gameObject.angle, + scaleX: gameObject.scaleX, + scaleY: gameObject.scaleY, + displayOriginX: gameObject.displayOriginX, + displayOriginY: gameObject.displayOriginY + }; + + /** + * Whether the Body's boundary is drawn to the debug display. + * + * @name Phaser.Physics.Arcade.Body#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowBody; + + /** + * Whether the Body's velocity is drawn to the debug display. + * + * @name Phaser.Physics.Arcade.Body#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowVelocity = world.defaults.debugShowVelocity; + + /** + * The color of this Body on the debug display. + * + * @name Phaser.Physics.Arcade.Body#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.bodyDebugColor; + + /** + * Whether this Body is updated by the physics simulation. + * + * @name Phaser.Physics.Arcade.Body#enable + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enable = true; + + /** + * Whether this Body's boundary is circular (true) or rectangular (false). + * + * @name Phaser.Physics.Arcade.Body#isCircle + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setCircle + */ + this.isCircle = false; + + /** + * If this Body is circular, this is the unscaled radius of the Body's boundary, as set by setCircle(), in source pixels. + * The true radius is equal to `halfWidth`. + * + * @name Phaser.Physics.Arcade.Body#radius + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setCircle + */ + this.radius = 0; + + /** + * The offset of this Body's position from its Game Object's position, in source pixels. + * + * @name Phaser.Physics.Arcade.Body#offset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setOffset + */ + this.offset = new Vector2(); + + /** + * The position of this Body within the simulation. + * + * @name Phaser.Physics.Arcade.Body#position + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.position = new Vector2(gameObject.x, gameObject.y); + + /** + * The position of this Body during the previous step. + * + * @name Phaser.Physics.Arcade.Body#prev + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.prev = new Vector2(gameObject.x, gameObject.y); + + /** + * The position of this Body during the previous frame. + * + * @name Phaser.Physics.Arcade.Body#prevFrame + * @type {Phaser.Math.Vector2} + * @since 3.20.0 + */ + this.prevFrame = new Vector2(gameObject.x, gameObject.y); + + /** + * Whether this Body's `rotation` is affected by its angular acceleration and angular velocity. + * + * @name Phaser.Physics.Arcade.Body#allowRotation + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.allowRotation = true; + + /** + * 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 boundary, which is always an axis-aligned rectangle or a circle. + * + * @name Phaser.Physics.Arcade.Body#rotation + * @type {number} + * @since 3.0.0 + */ + this.rotation = gameObject.angle; + + /** + * The Body rotation, in degrees, during the previous step. + * + * @name Phaser.Physics.Arcade.Body#preRotation + * @type {number} + * @since 3.0.0 + */ + this.preRotation = gameObject.angle; + + /** + * The width of the Body boundary, in pixels. + * If the Body is circular, this is also the diameter. + * If you wish to change the width use the `Body.setSize` method. + * + * @name Phaser.Physics.Arcade.Body#width + * @type {number} + * @readonly + * @default 64 + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the Body boundary, in pixels. + * If the Body is circular, this is also the diameter. + * If you wish to change the height use the `Body.setSize` method. + * + * @name Phaser.Physics.Arcade.Body#height + * @type {number} + * @readonly + * @default 64 + * @since 3.0.0 + */ + this.height = height; + + /** + * The unscaled width of the Body, in source pixels, as set by setSize(). + * The default is the width of the Body's Game Object's texture frame. + * + * @name Phaser.Physics.Arcade.Body#sourceWidth + * @type {number} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setSize + */ + this.sourceWidth = width; + + /** + * The unscaled height of the Body, in source pixels, as set by setSize(). + * The default is the height of the Body's Game Object's texture frame. + * + * @name Phaser.Physics.Arcade.Body#sourceHeight + * @type {number} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setSize + */ + this.sourceHeight = height; + + if (gameObject.frame) + { + this.sourceWidth = gameObject.frame.realWidth; + this.sourceHeight = gameObject.frame.realHeight; + } + + /** + * Half the Body's width, in pixels. + * + * @name Phaser.Physics.Arcade.Body#halfWidth + * @type {number} + * @since 3.0.0 + */ + this.halfWidth = Math.abs(width / 2); + + /** + * Half the Body's height, in pixels. + * + * @name Phaser.Physics.Arcade.Body#halfHeight + * @type {number} + * @since 3.0.0 + */ + this.halfHeight = Math.abs(height / 2); + + /** + * The center of the Body's boundary. + * The midpoint of its `position` (top-left corner) and its bottom-right corner. + * + * @name Phaser.Physics.Arcade.Body#center + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); + + /** + * The Body's velocity, in pixels per second. + * + * @name Phaser.Physics.Arcade.Body#velocity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.velocity = new Vector2(); + + /** + * The Body's change in position (due to velocity) at the last step, in pixels. + * + * The size of this value depends on the simulation's step rate. + * + * @name Phaser.Physics.Arcade.Body#newVelocity + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.newVelocity = new Vector2(); + + /** + * The Body's absolute maximum change in position, in pixels per step. + * + * @name Phaser.Physics.Arcade.Body#deltaMax + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.deltaMax = new Vector2(); + + /** + * The Body's change in velocity, in pixels per second squared. + * + * @name Phaser.Physics.Arcade.Body#acceleration + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.acceleration = new Vector2(); + + /** + * Whether this Body's velocity is affected by its `drag`. + * + * @name Phaser.Physics.Arcade.Body#allowDrag + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.allowDrag = true; + + /** + * Absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @name Phaser.Physics.Arcade.Body#drag + * @type {(Phaser.Math.Vector2|number)} + * @since 3.0.0 + */ + this.drag = new Vector2(); + + /** + * Whether this Body's position is affected by gravity (local or world). + * + * @name Phaser.Physics.Arcade.Body#allowGravity + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#gravity + * @see Phaser.Physics.Arcade.World#gravity + */ + this.allowGravity = true; + + /** + * Acceleration due to gravity (specific to this Body), in pixels per second squared. + * Total gravity is the sum of this vector and the simulation's `gravity`. + * + * @name Phaser.Physics.Arcade.Body#gravity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#gravity + */ + this.gravity = new Vector2(); + + /** + * Rebound following a collision, relative to 1. + * + * @name Phaser.Physics.Arcade.Body#bounce + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.bounce = new Vector2(); + + /** + * Rebound following a collision with the world boundary, relative to 1. + * If null, `bounce` is used instead. + * + * @name Phaser.Physics.Arcade.Body#worldBounce + * @type {?Phaser.Math.Vector2} + * @default null + * @since 3.0.0 + */ + this.worldBounce = null; + + /** + * The rectangle used for world boundary collisions. + * + * By default it is set to the world boundary rectangle. Or, if this Body was + * created by a Physics Group, then whatever rectangle that Group defined. + * + * You can also change it by using the `Body.setBoundsRectangle` method. + * + * @name Phaser.Physics.Arcade.Body#customBoundsRectangle + * @type {?Phaser.Geom.Rectangle} + * @since 3.20 + */ + this.customBoundsRectangle = world.bounds; + + // If true this Body will dispatch events + + /** + * Whether the simulation emits a `worldbounds` event when this Body collides with the world boundary (and `collideWorldBounds` is also true). + * + * @name Phaser.Physics.Arcade.Body#onWorldBounds + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#worldboundsEvent + */ + this.onWorldBounds = false; + + /** + * Whether the simulation emits a `collide` event when this Body collides with another. + * + * @name Phaser.Physics.Arcade.Body#onCollide + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#collideEvent + */ + this.onCollide = false; + + /** + * Whether the simulation emits an `overlap` event when this Body overlaps with another. + * + * @name Phaser.Physics.Arcade.Body#onOverlap + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#overlapEvent + */ + this.onOverlap = false; + + /** + * The Body's absolute maximum velocity, in pixels per second. + * The horizontal and vertical components are applied separately. + * + * @name Phaser.Physics.Arcade.Body#maxVelocity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.maxVelocity = new Vector2(10000, 10000); + + /** + * The maximum speed this Body is allowed to reach, in pixels per second. + * + * If not negative it limits the scalar value of speed. + * + * Any negative value means no maximum is being applied (the default). + * + * @name Phaser.Physics.Arcade.Body#maxSpeed + * @type {number} + * @default -1 + * @since 3.16.0 + */ + this.maxSpeed = -1; + + /** + * If this Body is `immovable` and in motion, `friction` is the proportion of this Body's motion received by the riding Body on each axis, relative to 1. + * The horizontal component (x) is applied only when two colliding Bodies are separated vertically. + * The vertical component (y) is applied only when two colliding Bodies are separated horizontally. + * The default value (1, 0) moves the riding Body horizontally in equal proportion to this Body and vertically not at all. + * + * @name Phaser.Physics.Arcade.Body#friction + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.friction = new Vector2(1, 0); + + /** + * If this Body is using `drag` for deceleration this property controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * + * @name Phaser.Physics.Arcade.Body#useDamping + * @type {boolean} + * @default false + * @since 3.10.0 + */ + this.useDamping = false; + + /** + * The rate of change of this Body's `rotation`, in degrees per second. + * + * @name Phaser.Physics.Arcade.Body#angularVelocity + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angularVelocity = 0; + + /** + * The Body's angular acceleration (change in angular velocity), in degrees per second squared. + * + * @name Phaser.Physics.Arcade.Body#angularAcceleration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angularAcceleration = 0; + + /** + * Loss of angular velocity due to angular movement, in degrees per second. + * + * Angular drag is applied only when angular acceleration is zero. + * + * @name Phaser.Physics.Arcade.Body#angularDrag + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angularDrag = 0; + + /** + * The Body's maximum angular velocity, in degrees per second. + * + * @name Phaser.Physics.Arcade.Body#maxAngular + * @type {number} + * @default 1000 + * @since 3.0.0 + */ + this.maxAngular = 1000; + + /** + * The Body's inertia, relative to a default unit (1). + * With `bounce`, this affects the exchange of momentum (velocities) during collisions. + * + * @name Phaser.Physics.Arcade.Body#mass + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.mass = 1; + + /** + * The calculated angle of this Body's velocity vector, in radians, during the last step. + * + * @name Phaser.Physics.Arcade.Body#angle + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angle = 0; + + /** + * The calculated magnitude of the Body's velocity, in pixels per second, during the last step. + * + * @name Phaser.Physics.Arcade.Body#speed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.speed = 0; + + /** + * The direction of the Body's velocity, as calculated during the last step. + * If the Body is moving on both axes (diagonally), this describes motion on the vertical axis only. + * + * @name Phaser.Physics.Arcade.Body#facing + * @type {integer} + * @since 3.0.0 + */ + this.facing = CONST.FACING_NONE; + + /** + * Whether this Body can be moved by collisions with another Body. + * + * @name Phaser.Physics.Arcade.Body#immovable + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.immovable = false; + + /** + * Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity. + * + * @name Phaser.Physics.Arcade.Body#moves + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.moves = true; + + /** + * A flag disabling the default horizontal separation of colliding bodies. + * Pass your own `collideCallback` to the collider. + * + * @name Phaser.Physics.Arcade.Body#customSeparateX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateX = false; + + /** + * A flag disabling the default vertical separation of colliding bodies. + * Pass your own `collideCallback` to the collider. + * + * @name Phaser.Physics.Arcade.Body#customSeparateY + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateY = false; + + /** + * The amount of horizontal overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.Body#overlapX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapX = 0; + + /** + * The amount of vertical overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.Body#overlapY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapY = 0; + + /** + * The amount of overlap (before separation), if this Body is circular and colliding with another circular body. + * + * @name Phaser.Physics.Arcade.Body#overlapR + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapR = 0; + + /** + * Whether this Body is overlapped with another and both are not moving, on at least one axis. + * + * @name Phaser.Physics.Arcade.Body#embedded + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.embedded = false; + + /** + * Whether this Body interacts with the world boundary. + * + * @name Phaser.Physics.Arcade.Body#collideWorldBounds + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.collideWorldBounds = false; + + /** + * Whether this Body is checked for collisions and for which directions. + * You can set `checkCollision.none = true` to disable collision checks. + * + * @name Phaser.Physics.Arcade.Body#checkCollision + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * Whether this Body is colliding with a Body or Static Body and in which direction. + * In a collision where both bodies have zero velocity, `embedded` will be set instead. + * + * @name Phaser.Physics.Arcade.Body#touching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#blocked + * @see Phaser.Physics.Arcade.Body#embedded + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This Body's `touching` value during the previous step. + * + * @name Phaser.Physics.Arcade.Body#wasTouching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#touching + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether this Body is colliding with a Static Body, a tile, or the world boundary. + * In a collision with a Static Body, if this Body has zero velocity then `embedded` will be set instead. + * + * @name Phaser.Physics.Arcade.Body#blocked + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#embedded + * @see Phaser.Physics.Arcade.Body#touching + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether to automatically synchronize this Body's dimensions to the dimensions of its Game Object's visual bounds. + * + * @name Phaser.Physics.Arcade.Body#syncBounds + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.GameObjects.Components.GetBounds#getBounds + */ + this.syncBounds = false; + + /** + * The Body's physics type (dynamic or static). + * + * @name Phaser.Physics.Arcade.Body#physicsType + * @type {integer} + * @readonly + * @default Phaser.Physics.Arcade.DYNAMIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.DYNAMIC_BODY; + + /** + * Cached horizontal scale of the Body's Game Object. + * + * @name Phaser.Physics.Arcade.Body#_sx + * @type {number} + * @private + * @since 3.0.0 + */ + this._sx = gameObject.scaleX; + + /** + * Cached vertical scale of the Body's Game Object. + * + * @name Phaser.Physics.Arcade.Body#_sy + * @type {number} + * @private + * @since 3.0.0 + */ + this._sy = gameObject.scaleY; + + /** + * The calculated change in the Body's horizontal position during the last step. + * + * @name Phaser.Physics.Arcade.Body#_dx + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._dx = 0; + + /** + * The calculated change in the Body's vertical position during the last step. + * + * @name Phaser.Physics.Arcade.Body#_dy + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._dy = 0; + + /** + * The final calculated change in the Body's horizontal position as of `postUpdate`. + * + * @name Phaser.Physics.Arcade.Body#_tx + * @type {number} + * @private + * @default 0 + * @since 3.22.0 + */ + this._tx = 0; + + /** + * The final calculated change in the Body's vertical position as of `postUpdate`. + * + * @name Phaser.Physics.Arcade.Body#_ty + * @type {number} + * @private + * @default 0 + * @since 3.22.0 + */ + this._ty = 0; + + /** + * Stores the Game Object's bounds. + * + * @name Phaser.Physics.Arcade.Body#_bounds + * @type {Phaser.Geom.Rectangle} + * @private + * @since 3.0.0 + */ + this._bounds = new Rectangle(); + }, + + /** + * Updates the Body's `transform`, `width`, `height`, and `center` from its Game Object. + * The Body's `position` isn't changed. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @since 3.0.0 + */ + updateBounds: function () + { + var sprite = this.gameObject; + + // Container? + + var transform = this.transform; + + if (sprite.parentContainer) + { + var matrix = sprite.getWorldTransformMatrix(this.world._tempMatrix, this.world._tempMatrix2); + + transform.x = matrix.tx; + transform.y = matrix.ty; + transform.rotation = RadToDeg(matrix.rotation); + transform.scaleX = matrix.scaleX; + transform.scaleY = matrix.scaleY; + transform.displayOriginX = sprite.displayOriginX; + transform.displayOriginY = sprite.displayOriginY; + } + else + { + transform.x = sprite.x; + transform.y = sprite.y; + transform.rotation = sprite.angle; + transform.scaleX = sprite.scaleX; + transform.scaleY = sprite.scaleY; + transform.displayOriginX = sprite.displayOriginX; + transform.displayOriginY = sprite.displayOriginY; + } + + var recalc = false; + + if (this.syncBounds) + { + var b = sprite.getBounds(this._bounds); + + this.width = b.width; + this.height = b.height; + recalc = true; + } + else + { + var asx = Math.abs(transform.scaleX); + var asy = Math.abs(transform.scaleY); + + if (this._sx !== asx || this._sy !== asy) + { + this.width = this.sourceWidth * asx; + this.height = this.sourceHeight * asy; + this._sx = asx; + this._sy = asy; + recalc = true; + } + } + + if (recalc) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + }, + + /** + * Updates the Body's `center` from its `position`, `width`, and `height`. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @since 3.0.0 + */ + updateCenter: function () + { + this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + }, + + /** + * Prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. + * + * This method is only called if the physics world is going to run a step this frame. + * + * @method Phaser.Physics.Arcade.Body#resetFlags + * @since 3.18.0 + */ + resetFlags: function () + { + // Store and reset collision flags + this.wasTouching.none = this.touching.none; + this.wasTouching.up = this.touching.up; + this.wasTouching.down = this.touching.down; + this.wasTouching.left = this.touching.left; + this.wasTouching.right = this.touching.right; + + this.touching.none = true; + this.touching.up = false; + this.touching.down = false; + this.touching.left = false; + this.touching.right = false; + + this.blocked.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + }, + + /** + * Syncs the position body position with the parent Game Object. + * + * This method is called every game frame, regardless if the world steps or not. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @since 3.17.0 + * + * @param {boolean} willStep - Will this Body run an update as well? + * @param {number} delta - The delta time, in seconds, elapsed since the last frame. + */ + preUpdate: function (willStep, delta) + { + if (willStep) + { + this.resetFlags(); + } + + this.updateBounds(); + + var sprite = this.transform; + + this.position.x = sprite.x + sprite.scaleX * (this.offset.x - sprite.displayOriginX); + this.position.y = sprite.y + sprite.scaleY * (this.offset.y - sprite.displayOriginY); + + this.updateCenter(); + + this.rotation = sprite.rotation; + + this.preRotation = this.rotation; + + if (this.moves) + { + this.prev.x = this.position.x; + this.prev.y = this.position.y; + this.prevFrame.x = this.position.x; + this.prevFrame.y = this.position.y; + } + + if (willStep) + { + this.update(delta); + } + }, + + /** + * Performs a single physics step and updates the body velocity, angle, speed and other properties. + * + * This method can be called multiple times per game frame, depending on the physics step rate. + * + * The results are synced back to the Game Object in `postUpdate`. + * + * @method Phaser.Physics.Arcade.Body#update + * @fires Phaser.Physics.Arcade.Events#WORLD_BOUNDS + * @since 3.0.0 + * + * @param {number} delta - The delta time, in seconds, elapsed since the last frame. + */ + update: function (delta) + { + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + if (this.moves) + { + this.world.updateMotion(this, delta); + + var vx = this.velocity.x; + var vy = this.velocity.y; + + this.newVelocity.set(vx * delta, vy * delta); + + this.position.add(this.newVelocity); + + this.updateCenter(); + + this.angle = Math.atan2(vy, vx); + this.speed = Math.sqrt(vx * vx + vy * vy); + + // Now the update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds && this.checkWorldBounds() && this.onWorldBounds) + { + this.world.emit(Events.WORLD_BOUNDS, this, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + + this._dx = this.position.x - this.prev.x; + this._dy = this.position.y - this.prev.y; + }, + + /** + * Feeds the Body results back into the parent Game Object. + * + * This method is called every game frame, regardless if the world steps or not. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @since 3.0.0 + */ + postUpdate: function () + { + var dx = this.position.x - this.prevFrame.x; + var dy = this.position.y - this.prevFrame.y; + + if (this.moves) + { + var mx = this.deltaMax.x; + var my = this.deltaMax.y; + + if (mx !== 0 && dx !== 0) + { + if (dx < 0 && dx < -mx) + { + dx = -mx; + } + else if (dx > 0 && dx > mx) + { + dx = mx; + } + } + + if (my !== 0 && dy !== 0) + { + if (dy < 0 && dy < -my) + { + dy = -my; + } + else if (dy > 0 && dy > my) + { + dy = my; + } + } + + this.gameObject.x += dx; + this.gameObject.y += dy; + } + + if (dx < 0) + { + this.facing = CONST.FACING_LEFT; + } + else if (dx > 0) + { + this.facing = CONST.FACING_RIGHT; + } + + if (dy < 0) + { + this.facing = CONST.FACING_UP; + } + else if (dy > 0) + { + this.facing = CONST.FACING_DOWN; + } + + if (this.allowRotation) + { + this.gameObject.angle += this.deltaZ(); + } + + this._tx = dx; + this._ty = dy; + }, + + /** + * Sets a custom collision boundary rectangle. Use if you want to have a custom + * boundary instead of the world boundaries. + * + * @method Phaser.Physics.Arcade.Body#setBoundsRectangle + * @since 3.20 + * + * @param {?Phaser.Geom.Rectangle} [bounds] - The new boundary rectangle. Pass `null` to use the World bounds. + * + * @return {this} This Body object. + */ + setBoundsRectangle: function (bounds) + { + this.customBoundsRectangle = (!bounds) ? this.world.bounds : bounds; + + return this; + }, + + /** + * Checks for collisions between this Body and the world boundary and separates them. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @since 3.0.0 + * + * @return {boolean} True if this Body is colliding with the world boundary. + */ + checkWorldBounds: function () + { + var pos = this.position; + var bounds = this.customBoundsRectangle; + var check = this.world.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + var wasSet = false; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + wasSet = true; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + wasSet = true; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + wasSet = true; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + wasSet = true; + } + + if (wasSet) + { + this.blocked.none = false; + } + + return wasSet; + }, + + /** + * Sets the offset of the Body's position from its Game Object's position. + * + * @method Phaser.Physics.Arcade.Body#setOffset + * @since 3.0.0 + * + * @param {number} x - The horizontal offset, in source pixels. + * @param {number} [y=x] - The vertical offset, in source pixels. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setOffset: function (x, y) + { + if (y === undefined) { y = x; } + + this.offset.set(x, y); + this.updateCenter(); + + return this; + }, + + /** + * Sizes and positions this Body's boundary, as a rectangle. + * Modifies the Body `offset` if `center` is true (the default). + * Resets the width and height to match current frame, if no width and height provided and a frame is found. + * + * @method Phaser.Physics.Arcade.Body#setSize + * @since 3.0.0 + * + * @param {integer} [width] - The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param {integer} [height] - The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param {boolean} [center=true] - Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setSize: function (width, height, center) + { + if (center === undefined) { center = true; } + + var gameObject = this.gameObject; + + if (!width && gameObject.frame) + { + width = gameObject.frame.realWidth; + } + + if (!height && gameObject.frame) + { + height = gameObject.frame.realHeight; + } + + this.sourceWidth = width; + this.sourceHeight = height; + + this.width = this.sourceWidth * this._sx; + this.height = this.sourceHeight * this._sy; + + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + + this.updateCenter(); + + if (center && gameObject.getCenter) + { + var ox = gameObject.displayWidth / 2; + var oy = gameObject.displayHeight / 2; + + this.offset.set(ox - this.halfWidth, oy - this.halfHeight); + } + + this.isCircle = false; + this.radius = 0; + + return this; + }, + + /** + * Sizes and positions this Body's boundary, as a circle. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the Body, in source pixels. + * @param {number} [offsetX] - The horizontal offset of the Body from its Game Object, in source pixels. + * @param {number} [offsetY] - The vertical offset of the Body from its Game Object, in source pixels. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setCircle: function (radius, offsetX, offsetY) + { + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + this.width = this.sourceWidth * this._sx; + this.height = this.sourceHeight * this._sy; + + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + + this.offset.set(offsetX, offsetY); + + this.updateCenter(); + } + else + { + this.isCircle = false; + } + + return this; + }, + + /** + * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. + * If the Body had any velocity or acceleration it is lost as a result of calling this. + * + * @method Phaser.Physics.Arcade.Body#reset + * @since 3.0.0 + * + * @param {number} x - The horizontal position to place the Game Object and Body. + * @param {number} y - The vertical position to place the Game Object and Body. + */ + reset: function (x, y) + { + this.stop(); + + var gameObject = this.gameObject; + + gameObject.setPosition(x, y); + + if (gameObject.getTopLeft) + { + gameObject.getTopLeft(this.position); + } + else + { + this.position.set(x, y); + } + + this.prev.copy(this.position); + this.prevFrame.copy(this.position); + + this.rotation = gameObject.angle; + this.preRotation = gameObject.angle; + + this.updateBounds(); + this.updateCenter(); + }, + + /** + * Sets acceleration, velocity, and speed to zero. + * + * @method Phaser.Physics.Arcade.Body#stop + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + stop: function () + { + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + return this; + }, + + /** + * Copies the coordinates of this Body's edges into an object. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} obj - An object to copy the values into. + * + * @return {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} - An object with {x, y, right, bottom}. + */ + getBounds: function (obj) + { + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + }, + + /** + * Tests if the coordinates are within this Body's boundary. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate. + * @param {number} y - The vertical coordinate. + * + * @return {boolean} True if (x, y) is within this Body. + */ + hitTest: function (x, y) + { + if (!this.isCircle) + { + return RectangleContains(this, x, y); + } + + // Check if x/y are within the bounds first + if (this.radius > 0 && x >= this.left && x <= this.right && y >= this.top && y <= this.bottom) + { + var dx = (this.center.x - x) * (this.center.x - x); + var dy = (this.center.y - y) * (this.center.y - y); + + return (dx + dy) <= (this.radius * this.radius); + } + + return false; + }, + + /** + * Whether this Body is touching a tile or the world boundary while moving down. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#blocked + * + * @return {boolean} True if touching. + */ + onFloor: function () + { + return this.blocked.down; + }, + + /** + * Whether this Body is touching a tile or the world boundary while moving up. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#blocked + * + * @return {boolean} True if touching. + */ + onCeiling: function () + { + return this.blocked.up; + }, + + /** + * Whether this Body is touching a tile or the world boundary while moving left or right. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#blocked + * + * @return {boolean} True if touching. + */ + onWall: function () + { + return (this.blocked.left || this.blocked.right); + }, + + /** + * The absolute (non-negative) change in this Body's horizontal position from the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaAbsX: function () + { + return (this._dx > 0) ? this._dx : -this._dx; + }, + + /** + * The absolute (non-negative) change in this Body's vertical position from the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaAbsY: function () + { + return (this._dy > 0) ? this._dy : -this._dy; + }, + + /** + * The change in this Body's horizontal position from the previous step. + * This value is set during the Body's update phase. + * + * As a Body can update multiple times per step this may not hold the final + * delta value for the Body. In this case, please see the `deltaXFinal` method. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaX: function () + { + return this._dx; + }, + + /** + * The change in this Body's vertical position from the previous step. + * This value is set during the Body's update phase. + * + * As a Body can update multiple times per step this may not hold the final + * delta value for the Body. In this case, please see the `deltaYFinal` method. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaY: function () + { + return this._dy; + }, + + /** + * The change in this Body's horizontal position from the previous game update. + * + * This value is set during the `postUpdate` phase and takes into account the + * `deltaMax` and final position of the Body. + * + * Because this value is not calculated until `postUpdate`, you must listen for it + * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will + * not be calculated by that point. If you _do_ use these values in `update` they + * will represent the delta from the _previous_ game frame. + * + * @method Phaser.Physics.Arcade.Body#deltaXFinal + * @since 3.22.0 + * + * @return {number} The final delta x value. + */ + deltaXFinal: function () + { + return this._tx; + }, + + /** + * The change in this Body's vertical position from the previous game update. + * + * This value is set during the `postUpdate` phase and takes into account the + * `deltaMax` and final position of the Body. + * + * Because this value is not calculated until `postUpdate`, you must listen for it + * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will + * not be calculated by that point. If you _do_ use these values in `update` they + * will represent the delta from the _previous_ game frame. + * + * @method Phaser.Physics.Arcade.Body#deltaYFinal + * @since 3.22.0 + * + * @return {number} The final delta y value. + */ + deltaYFinal: function () + { + return this._ty; + }, + + /** + * The change in this Body's rotation from the previous step, in degrees. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaZ: function () + { + return this.rotation - this.preRotation; + }, + + /** + * Disables this Body and marks it for deletion by the simulation. + * + * @method Phaser.Physics.Arcade.Body#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.enable = false; + + if (this.world) + { + this.world.pendingDestroy.set(this); + } + }, + + /** + * Draws this Body's boundary and velocity, if enabled. + * + * @method Phaser.Physics.Arcade.Body#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - The Graphics object to draw on. + */ + drawDebug: function (graphic) + { + var pos = this.position; + + var x = pos.x + this.halfWidth; + var y = pos.y + this.halfHeight; + + if (this.debugShowBody) + { + graphic.lineStyle(graphic.defaultStrokeWidth, this.debugBodyColor); + + if (this.isCircle) + { + graphic.strokeCircle(x, y, this.width / 2); + } + else + { + // Only draw the sides where checkCollision is true, similar to debugger in layer + if (this.checkCollision.up) + { + graphic.lineBetween(pos.x, pos.y, pos.x + this.width, pos.y); + } + + if (this.checkCollision.right) + { + graphic.lineBetween(pos.x + this.width, pos.y, pos.x + this.width, pos.y + this.height); + } + + if (this.checkCollision.down) + { + graphic.lineBetween(pos.x, pos.y + this.height, pos.x + this.width, pos.y + this.height); + } + + if (this.checkCollision.left) + { + graphic.lineBetween(pos.x, pos.y, pos.x, pos.y + this.height); + } + } + } + + if (this.debugShowVelocity) + { + graphic.lineStyle(graphic.defaultStrokeWidth, this.world.defaults.velocityDebugColor, 1); + graphic.lineBetween(x, y, x + this.velocity.x / 2, y + this.velocity.y / 2); + } + }, + + /** + * Whether this Body will be drawn to the debug display. + * + * @method Phaser.Physics.Arcade.Body#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} True if either `debugShowBody` or `debugShowVelocity` are enabled. + */ + willDrawDebug: function () + { + return (this.debugShowBody || this.debugShowVelocity); + }, + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * + * @method Phaser.Physics.Arcade.Body#setCollideWorldBounds + * @since 3.0.0 + * + * @param {boolean} [value=true] - `true` if this body should collide with the world bounds, otherwise `false`. + * @param {number} [bounceX] - If given this will be replace the `worldBounce.x` value. + * @param {number} [bounceY] - If given this will be replace the `worldBounce.y` value. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setCollideWorldBounds: function (value, bounceX, bounceY) + { + if (value === undefined) { value = true; } + + this.collideWorldBounds = value; + + var setBounceX = (bounceX !== undefined); + var setBounceY = (bounceY !== undefined); + + if (setBounceX || setBounceY) + { + if (!this.worldBounce) + { + this.worldBounce = new Vector2(); + } + + if (setBounceX) + { + this.worldBounce.x = bounceX; + } + + if (setBounceY) + { + this.worldBounce.y = bounceY; + } + } + + return this; + }, + + /** + * Sets the Body's velocity. + * + * @method Phaser.Physics.Arcade.Body#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity, in pixels per second. + * @param {number} [y=x] - The vertical velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setVelocity: function (x, y) + { + this.velocity.set(x, y); + + x = this.velocity.x; + y = this.velocity.y; + + this.speed = Math.sqrt(x * x + y * y); + + return this; + }, + + /** + * Sets the Body's horizontal velocity. + * + * @method Phaser.Physics.Arcade.Body#setVelocityX + * @since 3.0.0 + * + * @param {number} value - The velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setVelocityX: function (value) + { + this.velocity.x = value; + + var x = value; + var y = this.velocity.y; + + this.speed = Math.sqrt(x * x + y * y); + + return this; + }, + + /** + * Sets the Body's vertical velocity. + * + * @method Phaser.Physics.Arcade.Body#setVelocityY + * @since 3.0.0 + * + * @param {number} value - The velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setVelocityY: function (value) + { + this.velocity.y = value; + + var x = this.velocity.x; + var y = value; + + this.speed = Math.sqrt(x * x + y * y); + + return this; + }, + + /** + * Sets the Body's maximum velocity. + * + * @method Phaser.Physics.Arcade.Body#setMaxVelocity + * @since 3.10.0 + * + * @param {number} x - The horizontal velocity, in pixels per second. + * @param {number} [y=x] - The vertical velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setMaxVelocity: function (x, y) + { + this.maxVelocity.set(x, y); + + return this; + }, + + /** + * Sets the maximum speed the Body can move. + * + * @method Phaser.Physics.Arcade.Body#setMaxSpeed + * @since 3.16.0 + * + * @param {number} value - The maximum speed value, in pixels per second. Set to a negative value to disable. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setMaxSpeed: function (value) + { + this.maxSpeed = value; + + return this; + }, + + /** + * Sets the Body's bounce. + * + * @method Phaser.Physics.Arcade.Body#setBounce + * @since 3.0.0 + * + * @param {number} x - The horizontal bounce, relative to 1. + * @param {number} y - The vertical bounce, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setBounce: function (x, y) + { + this.bounce.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal bounce. + * + * @method Phaser.Physics.Arcade.Body#setBounceX + * @since 3.0.0 + * + * @param {number} value - The bounce, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setBounceX: function (value) + { + this.bounce.x = value; + + return this; + }, + + /** + * Sets the Body's vertical bounce. + * + * @method Phaser.Physics.Arcade.Body#setBounceY + * @since 3.0.0 + * + * @param {number} value - The bounce, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setBounceY: function (value) + { + this.bounce.y = value; + + return this; + }, + + /** + * Sets the Body's acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The horizontal component, in pixels per second squared. + * @param {number} y - The vertical component, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAcceleration: function (x, y) + { + this.acceleration.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAccelerationX + * @since 3.0.0 + * + * @param {number} value - The acceleration, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAccelerationX: function (value) + { + this.acceleration.x = value; + + return this; + }, + + /** + * Sets the Body's vertical acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAccelerationY + * @since 3.0.0 + * + * @param {number} value - The acceleration, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAccelerationY: function (value) + { + this.acceleration.y = value; + + return this; + }, + + /** + * Enables or disables drag. + * + * @method Phaser.Physics.Arcade.Body#setAllowDrag + * @since 3.9.0 + * @see Phaser.Physics.Arcade.Body#allowDrag + * + * @param {boolean} [value=true] - `true` to allow drag on this body, or `false` to disable it. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAllowDrag: function (value) + { + if (value === undefined) { value = true; } + + this.allowDrag = value; + + return this; + }, + + /** + * Enables or disables gravity's effect on this Body. + * + * @method Phaser.Physics.Arcade.Body#setAllowGravity + * @since 3.9.0 + * @see Phaser.Physics.Arcade.Body#allowGravity + * + * @param {boolean} [value=true] - `true` to allow gravity on this body, or `false` to disable it. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAllowGravity: function (value) + { + if (value === undefined) { value = true; } + + this.allowGravity = value; + + return this; + }, + + /** + * Enables or disables rotation. + * + * @method Phaser.Physics.Arcade.Body#setAllowRotation + * @since 3.9.0 + * @see Phaser.Physics.Arcade.Body#allowRotation + * + * @param {boolean} [value=true] - `true` to allow rotation on this body, or `false` to disable it. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAllowRotation: function (value) + { + if (value === undefined) { value = true; } + + this.allowRotation = value; + + return this; + }, + + /** + * Sets the Body's drag. + * + * @method Phaser.Physics.Arcade.Body#setDrag + * @since 3.0.0 + * + * @param {number} x - The horizontal component, in pixels per second squared. + * @param {number} y - The vertical component, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setDrag: function (x, y) + { + this.drag.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal drag. + * + * @method Phaser.Physics.Arcade.Body#setDragX + * @since 3.0.0 + * + * @param {number} value - The drag, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setDragX: function (value) + { + this.drag.x = value; + + return this; + }, + + /** + * Sets the Body's vertical drag. + * + * @method Phaser.Physics.Arcade.Body#setDragY + * @since 3.0.0 + * + * @param {number} value - The drag, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setDragY: function (value) + { + this.drag.y = value; + + return this; + }, + + /** + * Sets the Body's gravity. + * + * @method Phaser.Physics.Arcade.Body#setGravity + * @since 3.0.0 + * + * @param {number} x - The horizontal component, in pixels per second squared. + * @param {number} y - The vertical component, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setGravity: function (x, y) + { + this.gravity.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal gravity. + * + * @method Phaser.Physics.Arcade.Body#setGravityX + * @since 3.0.0 + * + * @param {number} value - The gravity, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setGravityX: function (value) + { + this.gravity.x = value; + + return this; + }, + + /** + * Sets the Body's vertical gravity. + * + * @method Phaser.Physics.Arcade.Body#setGravityY + * @since 3.0.0 + * + * @param {number} value - The gravity, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setGravityY: function (value) + { + this.gravity.y = value; + + return this; + }, + + /** + * Sets the Body's friction. + * + * @method Phaser.Physics.Arcade.Body#setFriction + * @since 3.0.0 + * + * @param {number} x - The horizontal component, relative to 1. + * @param {number} y - The vertical component, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setFriction: function (x, y) + { + this.friction.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal friction. + * + * @method Phaser.Physics.Arcade.Body#setFrictionX + * @since 3.0.0 + * + * @param {number} value - The friction value, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setFrictionX: function (value) + { + this.friction.x = value; + + return this; + }, + + /** + * Sets the Body's vertical friction. + * + * @method Phaser.Physics.Arcade.Body#setFrictionY + * @since 3.0.0 + * + * @param {number} value - The friction value, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setFrictionY: function (value) + { + this.friction.y = value; + + return this; + }, + + /** + * Sets the Body's angular velocity. + * + * @method Phaser.Physics.Arcade.Body#setAngularVelocity + * @since 3.0.0 + * + * @param {number} value - The velocity, in degrees per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAngularVelocity: function (value) + { + this.angularVelocity = value; + + return this; + }, + + /** + * Sets the Body's angular acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAngularAcceleration + * @since 3.0.0 + * + * @param {number} value - The acceleration, in degrees per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAngularAcceleration: function (value) + { + this.angularAcceleration = value; + + return this; + }, + + /** + * Sets the Body's angular drag. + * + * @method Phaser.Physics.Arcade.Body#setAngularDrag + * @since 3.0.0 + * + * @param {number} value - The drag, in degrees per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAngularDrag: function (value) + { + this.angularDrag = value; + + return this; + }, + + /** + * Sets the Body's mass. + * + * @method Phaser.Physics.Arcade.Body#setMass + * @since 3.0.0 + * + * @param {number} value - The mass value, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setMass: function (value) + { + this.mass = value; + + return this; + }, + + /** + * Sets the Body's `immovable` property. + * + * @method Phaser.Physics.Arcade.Body#setImmovable + * @since 3.0.0 + * + * @param {boolean} [value=true] - The value to assign to `immovable`. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setImmovable: function (value) + { + if (value === undefined) { value = true; } + + this.immovable = value; + + return this; + }, + + /** + * Sets the Body's `enable` property. + * + * @method Phaser.Physics.Arcade.Body#setEnable + * @since 3.15.0 + * + * @param {boolean} [value=true] - The value to assign to `enable`. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setEnable: function (value) + { + if (value === undefined) { value = true; } + + this.enable = value; + + return this; + }, + + /** + * The Body's horizontal position (left edge). + * + * @name Phaser.Physics.Arcade.Body#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.position.x; + }, + + set: function (value) + { + this.position.x = value; + } + + }, + + /** + * The Body's vertical position (top edge). + * + * @name Phaser.Physics.Arcade.Body#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.position.y; + }, + + set: function (value) + { + this.position.y = value; + } + + }, + + /** + * The left edge of the Body's boundary. Identical to x. + * + * @name Phaser.Physics.Arcade.Body#left + * @type {number} + * @readonly + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.position.x; + } + + }, + + /** + * The right edge of the Body's boundary. + * + * @name Phaser.Physics.Arcade.Body#right + * @type {number} + * @readonly + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.position.x + this.width; + } + + }, + + /** + * The top edge of the Body's boundary. Identical to y. + * + * @name Phaser.Physics.Arcade.Body#top + * @type {number} + * @readonly + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.position.y; + } + + }, + + /** + * The bottom edge of this Body's boundary. + * + * @name Phaser.Physics.Arcade.Body#bottom + * @type {number} + * @readonly + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.position.y + this.height; + } + + } + +}); + +module.exports = Body; + + +/***/ }), +/* 490 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * An Arcade Physics Collider will automatically check for collision, or overlaps, between two objects + * every step. If a collision, or overlap, occurs it will invoke the given callbacks. + * + * @class Collider + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade physics World that will manage the collisions. + * @param {boolean} overlapOnly - Whether to check for collisions or overlap. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. + * @param {any} callbackContext - The scope in which to call the callbacks. + */ +var Collider = new Class({ + + initialize: + + function Collider (world, overlapOnly, object1, object2, collideCallback, processCallback, callbackContext) + { + /** + * The world in which the bodies will collide. + * + * @name Phaser.Physics.Arcade.Collider#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The name of the collider (unused by Phaser). + * + * @name Phaser.Physics.Arcade.Collider#name + * @type {string} + * @since 3.1.0 + */ + this.name = ''; + + /** + * Whether the collider is active. + * + * @name Phaser.Physics.Arcade.Collider#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * Whether to check for collisions or overlaps. + * + * @name Phaser.Physics.Arcade.Collider#overlapOnly + * @type {boolean} + * @since 3.0.0 + */ + this.overlapOnly = overlapOnly; + + /** + * The first object to check for collision. + * + * @name Phaser.Physics.Arcade.Collider#object1 + * @type {Phaser.Types.Physics.Arcade.ArcadeColliderType} + * @since 3.0.0 + */ + this.object1 = object1; + + /** + * The second object to check for collision. + * + * @name Phaser.Physics.Arcade.Collider#object2 + * @type {Phaser.Types.Physics.Arcade.ArcadeColliderType} + * @since 3.0.0 + */ + this.object2 = object2; + + /** + * The callback to invoke when the two objects collide. + * + * @name Phaser.Physics.Arcade.Collider#collideCallback + * @type {ArcadePhysicsCallback} + * @since 3.0.0 + */ + this.collideCallback = collideCallback; + + /** + * If a processCallback exists it must return true or collision checking will be skipped. + * + * @name Phaser.Physics.Arcade.Collider#processCallback + * @type {ArcadePhysicsCallback} + * @since 3.0.0 + */ + this.processCallback = processCallback; + + /** + * The context the collideCallback and processCallback will run in. + * + * @name Phaser.Physics.Arcade.Collider#callbackContext + * @type {object} + * @since 3.0.0 + */ + this.callbackContext = callbackContext; + }, + + /** + * A name for the Collider. + * + * Phaser does not use this value, it's for your own reference. + * + * @method Phaser.Physics.Arcade.Collider#setName + * @since 3.1.0 + * + * @param {string} name - The name to assign to the Collider. + * + * @return {Phaser.Physics.Arcade.Collider} This Collider instance. + */ + setName: function (name) + { + this.name = name; + + return this; + }, + + /** + * Called by World as part of its step processing, initial operation of collision checking. + * + * @method Phaser.Physics.Arcade.Collider#update + * @since 3.0.0 + */ + update: function () + { + this.world.collideObjects( + this.object1, + this.object2, + this.collideCallback, + this.processCallback, + this.callbackContext, + this.overlapOnly + ); + }, + + /** + * Removes Collider from World and disposes of its resources. + * + * @method Phaser.Physics.Arcade.Collider#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.removeCollider(this); + + this.active = false; + + this.world = null; + + this.object1 = null; + this.object2 = null; + + this.collideCallback = null; + this.processCallback = null; + this.callbackContext = null; + } + +}); + +module.exports = Collider; + + +/***/ }), +/* 491 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(58); + +/** + * Calculates and returns the horizontal overlap between two arcade physics bodies and sets their properties + * accordingly, including: `touching.left`, `touching.right`, `touching.none` and `overlapX'. + * + * @function Phaser.Physics.Arcade.GetOverlapX + * @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 - Is this an overlap only check, or part of separation? + * @param {number} bias - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). + * + * @return {number} The amount of overlap. + */ +var GetOverlapX = function (body1, body2, overlapOnly, bias) +{ + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + bias; + + if (body1._dx === 0 && body2._dx === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1._dx > body2._dx) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + + body2.touching.none = false; + body2.touching.left = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.right = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.left = true; + } + } + } + else if (body1._dx < body2._dx) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + + body2.touching.none = false; + body2.touching.right = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.left = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.right = true; + } + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; +}; + +module.exports = GetOverlapX; + + +/***/ }), +/* 492 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(58); + +/** + * Calculates and returns the vertical overlap between two arcade physics bodies and sets their properties + * accordingly, including: `touching.up`, `touching.down`, `touching.none` and `overlapY'. + * + * @function Phaser.Physics.Arcade.GetOverlapY + * @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 - Is this an overlap only check, or part of separation? + * @param {number} bias - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). + * + * @return {number} The amount of overlap. + */ +var GetOverlapY = function (body1, body2, overlapOnly, bias) +{ + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + bias; + + if (body1._dy === 0 && body2._dy === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1._dy > body2._dy) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + + body2.touching.none = false; + body2.touching.up = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.down = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.up = true; + } + } + } + else if (body1._dy < body2._dy) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + + body2.touching.none = false; + body2.touching.down = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.up = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.down = true; + } + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; +}; + +module.exports = GetOverlapY; + + +/***/ }), +/* 493 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Vladimir Agafonkin + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var quickselect = __webpack_require__(414); + +/** + * @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 + */ + +function rbush (maxEntries) +{ + var format = [ '.left', '.top', '.right', '.bottom' ]; + + if (!(this instanceof rbush)) return new rbush(maxEntries, format); + + // max entries in a node is 9 by default; min node fill is 40% for best performance + this._maxEntries = Math.max(4, maxEntries || 9); + this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)); + + this.clear(); +} + +rbush.prototype = { + + all: function () + { + return this._all(this.data, []); + }, + + search: function (bbox) + { + var node = this.data, + result = [], + toBBox = this.toBBox; + + if (!intersects(bbox, node)) return result; + + var nodesToSearch = [], + i, len, child, childBBox; + + while (node) { + for (i = 0, len = node.children.length; i < len; i++) { + + child = node.children[i]; + childBBox = node.leaf ? toBBox(child) : child; + + if (intersects(bbox, childBBox)) { + if (node.leaf) result.push(child); + else if (contains(bbox, childBBox)) this._all(child, result); + else nodesToSearch.push(child); + } + } + node = nodesToSearch.pop(); + } + + return result; + }, + + collides: function (bbox) + { + var node = this.data, + toBBox = this.toBBox; + + if (!intersects(bbox, node)) return false; + + var nodesToSearch = [], + i, len, child, childBBox; + + while (node) { + for (i = 0, len = node.children.length; i < len; i++) { + + child = node.children[i]; + childBBox = node.leaf ? toBBox(child) : child; + + if (intersects(bbox, childBBox)) { + if (node.leaf || contains(bbox, childBBox)) return true; + nodesToSearch.push(child); + } + } + node = nodesToSearch.pop(); + } + + return false; + }, + + load: function (data) + { + if (!(data && data.length)) return this; + + if (data.length < this._minEntries) { + for (var i = 0, len = data.length; i < len; i++) { + this.insert(data[i]); + } + return this; + } + + // recursively build the tree with the given data from scratch using OMT algorithm + var node = this._build(data.slice(), 0, data.length - 1, 0); + + if (!this.data.children.length) { + // save as is if tree is empty + this.data = node; + + } else if (this.data.height === node.height) { + // split root if trees have the same height + this._splitRoot(this.data, node); + + } else { + if (this.data.height < node.height) { + // swap trees if inserted one is bigger + var tmpNode = this.data; + this.data = node; + node = tmpNode; + } + + // insert the small tree into the large tree at appropriate level + this._insert(node, this.data.height - node.height - 1, true); + } + + return this; + }, + + insert: function (item) + { + if (item) this._insert(item, this.data.height - 1); + return this; + }, + + clear: function () + { + this.data = createNode([]); + return this; + }, + + remove: function (item, equalsFn) + { + if (!item) return this; + + var node = this.data, + bbox = this.toBBox(item), + path = [], + indexes = [], + i, parent, index, goingUp; + + // depth-first iterative tree traversal + while (node || path.length) { + + if (!node) { // go up + node = path.pop(); + parent = path[path.length - 1]; + i = indexes.pop(); + goingUp = true; + } + + if (node.leaf) { // check current node + index = findItem(item, node.children, equalsFn); + + if (index !== -1) { + // item found, remove the item and condense tree upwards + node.children.splice(index, 1); + path.push(node); + this._condense(path); + return this; + } + } + + if (!goingUp && !node.leaf && contains(node, bbox)) { // go down + path.push(node); + indexes.push(i); + i = 0; + parent = node; + node = node.children[0]; + + } else if (parent) { // go right + i++; + node = parent.children[i]; + goingUp = false; + + } else node = null; // nothing found + } + + return this; + }, + + toBBox: function (item) { return item; }, + + compareMinX: compareNodeMinX, + compareMinY: compareNodeMinY, + + toJSON: function () { return this.data; }, + + fromJSON: function (data) + { + this.data = data; + return this; + }, + + _all: function (node, result) + { + var nodesToSearch = []; + while (node) { + if (node.leaf) result.push.apply(result, node.children); + else nodesToSearch.push.apply(nodesToSearch, node.children); + + node = nodesToSearch.pop(); + } + return result; + }, + + _build: function (items, left, right, height) + { + var N = right - left + 1, + M = this._maxEntries, + node; + + if (N <= M) { + // reached leaf level; return leaf + node = createNode(items.slice(left, right + 1)); + calcBBox(node, this.toBBox); + return node; + } + + if (!height) { + // target height of the bulk-loaded tree + height = Math.ceil(Math.log(N) / Math.log(M)); + + // target number of root entries to maximize storage utilization + M = Math.ceil(N / Math.pow(M, height - 1)); + } + + node = createNode([]); + node.leaf = false; + node.height = height; + + // split the items into M mostly square tiles + + var N2 = Math.ceil(N / M), + N1 = N2 * Math.ceil(Math.sqrt(M)), + i, j, right2, right3; + + multiSelect(items, left, right, N1, this.compareMinX); + + for (i = left; i <= right; i += N1) { + + right2 = Math.min(i + N1 - 1, right); + + multiSelect(items, i, right2, N2, this.compareMinY); + + for (j = i; j <= right2; j += N2) { + + right3 = Math.min(j + N2 - 1, right2); + + // pack each entry recursively + node.children.push(this._build(items, j, right3, height - 1)); + } + } + + calcBBox(node, this.toBBox); + + return node; + }, + + _chooseSubtree: function (bbox, node, level, path) + { + var i, len, child, targetNode, area, enlargement, minArea, minEnlargement; + + while (true) { + path.push(node); + + if (node.leaf || path.length - 1 === level) break; + + minArea = minEnlargement = Infinity; + + for (i = 0, len = node.children.length; i < len; i++) { + child = node.children[i]; + area = bboxArea(child); + enlargement = enlargedArea(bbox, child) - area; + + // choose entry with the least area enlargement + if (enlargement < minEnlargement) { + minEnlargement = enlargement; + minArea = area < minArea ? area : minArea; + targetNode = child; + + } else if (enlargement === minEnlargement) { + // otherwise choose one with the smallest area + if (area < minArea) { + minArea = area; + targetNode = child; + } + } + } + + node = targetNode || node.children[0]; + } + + return node; + }, + + _insert: function (item, level, isNode) + { + var toBBox = this.toBBox, + bbox = isNode ? item : toBBox(item), + insertPath = []; + + // find the best node for accommodating the item, saving all nodes along the path too + var node = this._chooseSubtree(bbox, this.data, level, insertPath); + + // put the item into the node + node.children.push(item); + extend(node, bbox); + + // split on node overflow; propagate upwards if necessary + while (level >= 0) { + if (insertPath[level].children.length > this._maxEntries) { + this._split(insertPath, level); + level--; + } else break; + } + + // adjust bboxes along the insertion path + this._adjustParentBBoxes(bbox, insertPath, level); + }, + + // split overflowed node into two + _split: function (insertPath, level) + { + var node = insertPath[level], + M = node.children.length, + m = this._minEntries; + + this._chooseSplitAxis(node, m, M); + + var splitIndex = this._chooseSplitIndex(node, m, M); + + var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); + newNode.height = node.height; + newNode.leaf = node.leaf; + + calcBBox(node, this.toBBox); + calcBBox(newNode, this.toBBox); + + if (level) insertPath[level - 1].children.push(newNode); + else this._splitRoot(node, newNode); + }, + + _splitRoot: function (node, newNode) + { + // split root node + this.data = createNode([node, newNode]); + this.data.height = node.height + 1; + this.data.leaf = false; + calcBBox(this.data, this.toBBox); + }, + + _chooseSplitIndex: function (node, m, M) + { + var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index; + + minOverlap = minArea = Infinity; + + for (i = m; i <= M - m; i++) { + bbox1 = distBBox(node, 0, i, this.toBBox); + bbox2 = distBBox(node, i, M, this.toBBox); + + overlap = intersectionArea(bbox1, bbox2); + area = bboxArea(bbox1) + bboxArea(bbox2); + + // choose distribution with minimum overlap + if (overlap < minOverlap) { + minOverlap = overlap; + index = i; + + minArea = area < minArea ? area : minArea; + + } else if (overlap === minOverlap) { + // otherwise choose distribution with minimum area + if (area < minArea) { + minArea = area; + index = i; + } + } + } + + return index; + }, + + // sorts node children by the best axis for split + _chooseSplitAxis: function (node, m, M) + { + var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX, + compareMinY = node.leaf ? this.compareMinY : compareNodeMinY, + xMargin = this._allDistMargin(node, m, M, compareMinX), + yMargin = this._allDistMargin(node, m, M, compareMinY); + + // if total distributions margin value is minimal for x, sort by minX, + // otherwise it's already sorted by minY + if (xMargin < yMargin) node.children.sort(compareMinX); + }, + + // total margin of all possible split distributions where each node is at least m full + _allDistMargin: function (node, m, M, compare) + { + node.children.sort(compare); + + var toBBox = this.toBBox, + leftBBox = distBBox(node, 0, m, toBBox), + rightBBox = distBBox(node, M - m, M, toBBox), + margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), + i, child; + + for (i = m; i < M - m; i++) { + child = node.children[i]; + extend(leftBBox, node.leaf ? toBBox(child) : child); + margin += bboxMargin(leftBBox); + } + + for (i = M - m - 1; i >= m; i--) { + child = node.children[i]; + extend(rightBBox, node.leaf ? toBBox(child) : child); + margin += bboxMargin(rightBBox); + } + + return margin; + }, + + _adjustParentBBoxes: function (bbox, path, level) + { + // adjust bboxes along the given tree path + for (var i = level; i >= 0; i--) { + extend(path[i], bbox); + } + }, + + _condense: function (path) + { + // go through the path, removing empty nodes and updating bboxes + for (var i = path.length - 1, siblings; i >= 0; i--) { + if (path[i].children.length === 0) { + if (i > 0) { + siblings = path[i - 1].children; + siblings.splice(siblings.indexOf(path[i]), 1); + + } else this.clear(); + + } else calcBBox(path[i], this.toBBox); + } + }, + + compareMinX: function (a, b) + { + return a.left - b.left; + }, + + compareMinY: function (a, b) + { + return a.top - b.top; + }, + + toBBox: function (a) + { + return { + minX: a.left, + minY: a.top, + maxX: a.right, + maxY: a.bottom + }; + } +}; + +function findItem (item, items, equalsFn) +{ + if (!equalsFn) return items.indexOf(item); + + for (var i = 0; i < items.length; i++) { + if (equalsFn(item, items[i])) return i; + } + return -1; +} + +// calculate node's bbox from bboxes of its children +function calcBBox (node, toBBox) +{ + distBBox(node, 0, node.children.length, toBBox, node); +} + +// min bounding rectangle of node children from k to p-1 +function distBBox (node, k, p, toBBox, destNode) +{ + if (!destNode) destNode = createNode(null); + destNode.minX = Infinity; + destNode.minY = Infinity; + destNode.maxX = -Infinity; + destNode.maxY = -Infinity; + + for (var i = k, child; i < p; i++) { + child = node.children[i]; + extend(destNode, node.leaf ? toBBox(child) : child); + } + + return destNode; +} + +function extend (a, b) +{ + a.minX = Math.min(a.minX, b.minX); + a.minY = Math.min(a.minY, b.minY); + a.maxX = Math.max(a.maxX, b.maxX); + a.maxY = Math.max(a.maxY, b.maxY); + return a; +} + +function compareNodeMinX (a, b) { return a.minX - b.minX; } +function compareNodeMinY (a, b) { return a.minY - b.minY; } + +function bboxArea (a) { return (a.maxX - a.minX) * (a.maxY - a.minY); } +function bboxMargin (a) { return (a.maxX - a.minX) + (a.maxY - a.minY); } + +function enlargedArea (a, b) +{ + return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * + (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)); +} + +function intersectionArea (a, b) +{ + var minX = Math.max(a.minX, b.minX), + minY = Math.max(a.minY, b.minY), + maxX = Math.min(a.maxX, b.maxX), + maxY = Math.min(a.maxY, b.maxY); + + return Math.max(0, maxX - minX) * + Math.max(0, maxY - minY); +} + +function contains (a, b) +{ + return a.minX <= b.minX && + a.minY <= b.minY && + b.maxX <= a.maxX && + b.maxY <= a.maxY; +} + +function intersects (a, b) +{ + return b.minX <= a.maxX && + b.minY <= a.maxY && + b.maxX >= a.minX && + b.maxY >= a.minY; +} + +function createNode (children) +{ + return { + children: children, + height: 1, + leaf: true, + minX: Infinity, + minY: Infinity, + maxX: -Infinity, + maxY: -Infinity + }; +} + +// 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 + +function multiSelect (arr, left, right, n, compare) +{ + var stack = [left, right], + mid; + + while (stack.length) + { + right = stack.pop(); + left = stack.pop(); + + if (right - left <= n) continue; + + mid = left + Math.ceil((right - left) / n / 2) * n; + quickselect(arr, mid, left, right, compare); + + stack.push(left, mid, mid, right); + } +} + +module.exports = rbush; + +/***/ }), +/* 494 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks for intersection between the given tile rectangle-like object and an Arcade Physics body. + * + * @function Phaser.Physics.Arcade.Tilemap.TileIntersectsBody + * @since 3.0.0 + * + * @param {{ left: number, right: number, top: number, bottom: number }} tileWorldRect - A rectangle object that defines the tile placement in the world. + * @param {Phaser.Physics.Arcade.Body} body - The body to check for intersection against. + * + * @return {boolean} Returns `true` of the tile intersects with the body, otherwise `false`. + */ +var TileIntersectsBody = function (tileWorldRect, body) +{ + // Currently, all bodies are treated as rectangles when colliding with a Tile. + + return !( + body.right <= tileWorldRect.left || + body.bottom <= tileWorldRect.top || + body.position.x >= tileWorldRect.right || + body.position.y >= tileWorldRect.bottom + ); +}; + +module.exports = TileIntersectsBody; + + +/***/ }), +/* 495 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CircleContains = __webpack_require__(60); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(58); +var RectangleContains = __webpack_require__(53); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Static Arcade Physics Body. + * + * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. + * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Body manually. + * + * A Static Body can collide with other Bodies, but is never moved by collisions. + * + * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Body}. + * + * @class StaticBody + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics simulation this Static Body belongs to. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object this Static Body belongs to. + */ +var StaticBody = new Class({ + + initialize: + + function StaticBody (world, gameObject) + { + var width = (gameObject.width) ? gameObject.width : 64; + var height = (gameObject.height) ? gameObject.height : 64; + + /** + * The Arcade Physics simulation this Static Body belongs to. + * + * @name Phaser.Physics.Arcade.StaticBody#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Game Object this Static Body belongs to. + * + * @name Phaser.Physics.Arcade.StaticBody#gameObject + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.gameObject = gameObject; + + /** + * Whether the Static Body's boundary is drawn to the debug display. + * + * @name Phaser.Physics.Arcade.StaticBody#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowStaticBody; + + /** + * The color of this Static Body on the debug display. + * + * @name Phaser.Physics.Arcade.StaticBody#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.staticBodyDebugColor; + + /** + * Whether this Static Body is updated by the physics simulation. + * + * @name Phaser.Physics.Arcade.StaticBody#enable + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enable = true; + + /** + * Whether this Static Body's boundary is circular (`true`) or rectangular (`false`). + * + * @name Phaser.Physics.Arcade.StaticBody#isCircle + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isCircle = false; + + /** + * If this Static Body is circular, this is the unscaled radius of the Static Body's boundary, as set by {@link #setCircle}, in source pixels. + * The true radius is equal to `halfWidth`. + * + * @name Phaser.Physics.Arcade.StaticBody#radius + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.radius = 0; + + /** + * The offset of this Static Body's actual position from any updated position. + * + * Unlike a dynamic Body, a Static Body does not follow its Game Object. As such, this offset is only applied when resizing the Static Body. + * + * @name Phaser.Physics.Arcade.StaticBody#offset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.offset = new Vector2(); + + /** + * The position of this Static Body within the simulation. + * + * @name Phaser.Physics.Arcade.StaticBody#position + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.position = new Vector2(gameObject.x - gameObject.displayOriginX, gameObject.y - gameObject.displayOriginY); + + /** + * The width of the Static Body's boundary, in pixels. + * If the Static Body is circular, this is also the Static Body's diameter. + * + * @name Phaser.Physics.Arcade.StaticBody#width + * @type {number} + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the Static Body's boundary, in pixels. + * If the Static Body is circular, this is also the Static Body's diameter. + * + * @name Phaser.Physics.Arcade.StaticBody#height + * @type {number} + * @since 3.0.0 + */ + this.height = height; + + /** + * Half the Static Body's width, in pixels. + * If the Static Body is circular, this is also the Static Body's radius. + * + * @name Phaser.Physics.Arcade.StaticBody#halfWidth + * @type {number} + * @since 3.0.0 + */ + this.halfWidth = Math.abs(this.width / 2); + + /** + * Half the Static Body's height, in pixels. + * If the Static Body is circular, this is also the Static Body's radius. + * + * @name Phaser.Physics.Arcade.StaticBody#halfHeight + * @type {number} + * @since 3.0.0 + */ + this.halfHeight = Math.abs(this.height / 2); + + /** + * The center of the Static Body's boundary. + * This is the midpoint of its `position` (top-left corner) and its bottom-right corner. + * + * @name Phaser.Physics.Arcade.StaticBody#center + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); + + /** + * A constant zero velocity used by the Arcade Physics simulation for calculations. + * + * @name Phaser.Physics.Arcade.StaticBody#velocity + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.velocity = Vector2.ZERO; + + /** + * A constant `false` value expected by the Arcade Physics simulation. + * + * @name Phaser.Physics.Arcade.StaticBody#allowGravity + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.allowGravity = false; + + /** + * Gravitational force applied specifically to this Body. Values are in pixels per second squared. Always zero for a Static Body. + * + * @name Phaser.Physics.Arcade.StaticBody#gravity + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.gravity = Vector2.ZERO; + + /** + * Rebound, or restitution, following a collision, relative to 1. Always zero for a Static Body. + * + * @name Phaser.Physics.Arcade.StaticBody#bounce + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.bounce = Vector2.ZERO; + + // If true this Body will dispatch events + + /** + * Whether the simulation emits a `worldbounds` event when this StaticBody collides with the world boundary. + * Always false for a Static Body. (Static Bodies never collide with the world boundary and never trigger a `worldbounds` event.) + * + * @name Phaser.Physics.Arcade.StaticBody#onWorldBounds + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.onWorldBounds = false; + + /** + * Whether the simulation emits a `collide` event when this StaticBody collides with another. + * + * @name Phaser.Physics.Arcade.StaticBody#onCollide + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.onCollide = false; + + /** + * Whether the simulation emits an `overlap` event when this StaticBody overlaps with another. + * + * @name Phaser.Physics.Arcade.StaticBody#onOverlap + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.onOverlap = false; + + /** + * The StaticBody's inertia, relative to a default unit (1). With `bounce`, this affects the exchange of momentum (velocities) during collisions. + * + * @name Phaser.Physics.Arcade.StaticBody#mass + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.mass = 1; + + /** + * Whether this object can be moved by collisions with another body. + * + * @name Phaser.Physics.Arcade.StaticBody#immovable + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.immovable = true; + + /** + * A flag disabling the default horizontal separation of colliding bodies. Pass your own `collideHandler` to the collider. + * + * @name Phaser.Physics.Arcade.StaticBody#customSeparateX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateX = false; + + /** + * A flag disabling the default vertical separation of colliding bodies. Pass your own `collideHandler` to the collider. + * + * @name Phaser.Physics.Arcade.StaticBody#customSeparateY + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateY = false; + + /** + * The amount of horizontal overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.StaticBody#overlapX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapX = 0; + + /** + * The amount of vertical overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.StaticBody#overlapY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapY = 0; + + /** + * The amount of overlap (before separation), if this StaticBody is circular and colliding with another circular body. + * + * @name Phaser.Physics.Arcade.StaticBody#overlapR + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapR = 0; + + /** + * Whether this StaticBody has ever overlapped with another while both were not moving. + * + * @name Phaser.Physics.Arcade.StaticBody#embedded + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.embedded = false; + + /** + * Whether this StaticBody interacts with the world boundary. + * Always false for a Static Body. (Static Bodies never collide with the world boundary.) + * + * @name Phaser.Physics.Arcade.StaticBody#collideWorldBounds + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.collideWorldBounds = false; + + /** + * Whether this StaticBody is checked for collisions and for which directions. You can set `checkCollision.none = false` to disable collision checks. + * + * @name Phaser.Physics.Arcade.StaticBody#checkCollision + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * Whether this StaticBody has ever collided with another body and in which direction. + * + * @name Phaser.Physics.Arcade.StaticBody#touching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether this StaticBody was colliding with another body during the last step or any previous step, and in which direction. + * + * @name Phaser.Physics.Arcade.StaticBody#wasTouching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether this StaticBody has ever collided with a tile or the world boundary. + * + * @name Phaser.Physics.Arcade.StaticBody#blocked + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * The StaticBody's physics type (static by default). + * + * @name Phaser.Physics.Arcade.StaticBody#physicsType + * @type {integer} + * @default Phaser.Physics.Arcade.STATIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.STATIC_BODY; + + /** + * The calculated change in the Body's horizontal position during the current step. + * For a static body this is always zero. + * + * @name Phaser.Physics.Arcade.StaticBody#_dx + * @type {number} + * @private + * @default 0 + * @since 3.10.0 + */ + this._dx = 0; + + /** + * The calculated change in the Body's vertical position during the current step. + * For a static body this is always zero. + * + * @name Phaser.Physics.Arcade.StaticBody#_dy + * @type {number} + * @private + * @default 0 + * @since 3.10.0 + */ + this._dy = 0; + }, + + /** + * Changes the Game Object this Body is bound to. + * First it removes its reference from the old Game Object, then sets the new one. + * You can optionally update the position and dimensions of this Body to reflect that of the new Game Object. + * + * @method Phaser.Physics.Arcade.StaticBody#setGameObject + * @since 3.1.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The new Game Object that will own this Body. + * @param {boolean} [update=true] - Reposition and resize this Body to match the new Game Object? + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + * + * @see Phaser.Physics.Arcade.StaticBody#updateFromGameObject + */ + setGameObject: function (gameObject, update) + { + if (gameObject && gameObject !== this.gameObject) + { + // Remove this body from the old game object + this.gameObject.body = null; + + gameObject.body = this; + + // Update our reference + this.gameObject = gameObject; + } + + if (update) + { + this.updateFromGameObject(); + } + + return this; + }, + + /** + * Syncs the Body's position and size with its parent Game Object. + * + * @method Phaser.Physics.Arcade.StaticBody#updateFromGameObject + * @since 3.1.0 + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + updateFromGameObject: function () + { + this.world.staticTree.remove(this); + + var gameObject = this.gameObject; + + gameObject.getTopLeft(this.position); + + this.width = gameObject.displayWidth; + this.height = gameObject.displayHeight; + + this.halfWidth = Math.abs(this.width / 2); + this.halfHeight = Math.abs(this.height / 2); + + this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + this.world.staticTree.insert(this); + + return this; + }, + + /** + * Sets the offset of the body. + * + * @method Phaser.Physics.Arcade.StaticBody#setOffset + * @since 3.4.0 + * + * @param {number} x - The horizontal offset of the Body from the Game Object's center. + * @param {number} y - The vertical offset of the Body from the Game Object's center. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setOffset: function (x, y) + { + if (y === undefined) { y = x; } + + this.world.staticTree.remove(this); + + this.position.x -= this.offset.x; + this.position.y -= this.offset.y; + + this.offset.set(x, y); + + this.position.x += this.offset.x; + this.position.y += this.offset.y; + + this.updateCenter(); + + this.world.staticTree.insert(this); + + return this; + }, + + /** + * Sets the size of the body. + * Resets the width and height to match current frame, if no width and height provided and a frame is found. + * + * @method Phaser.Physics.Arcade.StaticBody#setSize + * @since 3.0.0 + * + * @param {integer} [width] - The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param {integer} [height] - The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param {boolean} [center=true] - Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setSize: function (width, height, center) + { + if (center === undefined) { center = true; } + + var gameObject = this.gameObject; + + if (!width && gameObject.frame) + { + width = gameObject.frame.realWidth; + } + + if (!height && gameObject.frame) + { + height = gameObject.frame.realHeight; + } + + this.world.staticTree.remove(this); + + this.width = width; + this.height = height; + + this.halfWidth = Math.floor(width / 2); + this.halfHeight = Math.floor(height / 2); + + if (center && gameObject.getCenter) + { + var ox = gameObject.displayWidth / 2; + var oy = gameObject.displayHeight / 2; + + this.position.x -= this.offset.x; + this.position.y -= this.offset.y; + + this.offset.set(ox - this.halfWidth, oy - this.halfHeight); + + this.position.x += this.offset.x; + this.position.y += this.offset.y; + } + + this.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + this.world.staticTree.insert(this); + + return this; + }, + + /** + * Sets this Static Body to have a circular body and sets its sizes and position. + * + * @method Phaser.Physics.Arcade.StaticBody#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the StaticBody, in pixels. + * @param {number} [offsetX] - The horizontal offset of the StaticBody from its Game Object, in pixels. + * @param {number} [offsetY] - The vertical offset of the StaticBody from its Game Object, in pixels. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setCircle: function (radius, offsetX, offsetY) + { + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.world.staticTree.remove(this); + + this.isCircle = true; + + this.radius = radius; + + this.width = radius * 2; + this.height = radius * 2; + + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + + this.offset.set(offsetX, offsetY); + + this.updateCenter(); + + this.world.staticTree.insert(this); + } + else + { + this.isCircle = false; + } + + return this; + }, + + /** + * Updates the StaticBody's `center` from its `position` and dimensions. + * + * @method Phaser.Physics.Arcade.StaticBody#updateCenter + * @since 3.0.0 + */ + updateCenter: function () + { + this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + }, + + /** + * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. + * + * @method Phaser.Physics.Arcade.StaticBody#reset + * @since 3.0.0 + * + * @param {number} [x] - The x coordinate to reset the body to. If not given will use the parent Game Object's coordinate. + * @param {number} [y] - The y coordinate to reset the body to. If not given will use the parent Game Object's coordinate. + */ + reset: function (x, y) + { + var gameObject = this.gameObject; + + if (x === undefined) { x = gameObject.x; } + if (y === undefined) { y = gameObject.y; } + + this.world.staticTree.remove(this); + + gameObject.setPosition(x, y); + + gameObject.getTopLeft(this.position); + + this.updateCenter(); + + this.world.staticTree.insert(this); + }, + + /** + * NOOP function. A Static Body cannot be stopped. + * + * @method Phaser.Physics.Arcade.StaticBody#stop + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + stop: function () + { + return this; + }, + + /** + * Returns the x and y coordinates of the top left and bottom right points of the StaticBody. + * + * @method Phaser.Physics.Arcade.StaticBody#getBounds + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} obj - The object which will hold the coordinates of the bounds. + * + * @return {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} The same object that was passed with `x`, `y`, `right` and `bottom` values matching the respective values of the StaticBody. + */ + getBounds: function (obj) + { + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + }, + + /** + * Checks to see if a given x,y coordinate is colliding with this Static Body. + * + * @method Phaser.Physics.Arcade.StaticBody#hitTest + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check against this body. + * @param {number} y - The y coordinate to check against this body. + * + * @return {boolean} `true` if the given coordinate lies within this body, otherwise `false`. + */ + hitTest: function (x, y) + { + return (this.isCircle) ? CircleContains(this, x, y) : RectangleContains(this, x, y); + }, + + /** + * NOOP + * + * @method Phaser.Physics.Arcade.StaticBody#postUpdate + * @since 3.12.0 + */ + postUpdate: function () + { + }, + + /** + * The absolute (non-negative) change in this StaticBody's horizontal position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaAbsX + * @since 3.0.0 + * + * @return {number} Always zero for a Static Body. + */ + deltaAbsX: function () + { + return 0; + }, + + /** + * The absolute (non-negative) change in this StaticBody's vertical position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaAbsY + * @since 3.0.0 + * + * @return {number} Always zero for a Static Body. + */ + deltaAbsY: function () + { + return 0; + }, + + /** + * The change in this StaticBody's horizontal position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaX + * @since 3.0.0 + * + * @return {number} The change in this StaticBody's velocity from the previous step. Always zero. + */ + deltaX: function () + { + return 0; + }, + + /** + * The change in this StaticBody's vertical position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaY + * @since 3.0.0 + * + * @return {number} The change in this StaticBody's velocity from the previous step. Always zero. + */ + deltaY: function () + { + return 0; + }, + + /** + * The change in this StaticBody's rotation from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaZ + * @since 3.0.0 + * + * @return {number} The change in this StaticBody's rotation from the previous step. Always zero. + */ + deltaZ: function () + { + return 0; + }, + + /** + * Disables this Body and marks it for destruction during the next step. + * + * @method Phaser.Physics.Arcade.StaticBody#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.enable = false; + + this.world.pendingDestroy.set(this); + }, + + /** + * Draws a graphical representation of the StaticBody for visual debugging purposes. + * + * @method Phaser.Physics.Arcade.StaticBody#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - The Graphics object to use for the debug drawing of the StaticBody. + */ + drawDebug: function (graphic) + { + var pos = this.position; + + var x = pos.x + this.halfWidth; + var y = pos.y + this.halfHeight; + + if (this.debugShowBody) + { + graphic.lineStyle(graphic.defaultStrokeWidth, this.debugBodyColor, 1); + + if (this.isCircle) + { + graphic.strokeCircle(x, y, this.width / 2); + } + else + { + graphic.strokeRect(pos.x, pos.y, this.width, this.height); + } + + } + }, + + /** + * Indicates whether the StaticBody is going to be showing a debug visualization during postUpdate. + * + * @method Phaser.Physics.Arcade.StaticBody#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} Whether or not the StaticBody is going to show the debug visualization during postUpdate. + */ + willDrawDebug: function () + { + return this.debugShowBody; + }, + + /** + * Sets the Mass of the StaticBody. Will set the Mass to 0.1 if the value passed is less than or equal to zero. + * + * @method Phaser.Physics.Arcade.StaticBody#setMass + * @since 3.0.0 + * + * @param {number} value - The value to set the Mass to. Values of zero or less are changed to 0.1. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setMass: function (value) + { + if (value <= 0) + { + // Causes havoc otherwise + value = 0.1; + } + + this.mass = value; + + return this; + }, + + /** + * The x coordinate of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.position.x; + }, + + set: function (value) + { + this.world.staticTree.remove(this); + + this.position.x = value; + + this.world.staticTree.insert(this); + } + + }, + + /** + * The y coordinate of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.position.y; + }, + + set: function (value) + { + this.world.staticTree.remove(this); + + this.position.y = value; + + this.world.staticTree.insert(this); + } + + }, + + /** + * Returns the left-most x coordinate of the area of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#left + * @type {number} + * @readonly + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.position.x; + } + + }, + + /** + * The right-most x coordinate of the area of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#right + * @type {number} + * @readonly + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.position.x + this.width; + } + + }, + + /** + * The highest y coordinate of the area of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#top + * @type {number} + * @readonly + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.position.y; + } + + }, + + /** + * The lowest y coordinate of the area of the StaticBody. (y + height) + * + * @name Phaser.Physics.Arcade.StaticBody#bottom + * @type {number} + * @readonly + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.position.y + this.height; + } + + } + +}); + +module.exports = StaticBody; + + +/***/ }), +/* 496 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var COLLIDES = __webpack_require__(112); +var GetVelocity = __webpack_require__(1317); +var TYPE = __webpack_require__(113); +var UpdateMotion = __webpack_require__(1318); + +/** + * @callback Phaser.Types.Physics.Impact.BodyUpdateCallback + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + */ + +/** + * @classdesc + * An Impact.js compatible physics body. + * This re-creates the properties you'd get on an Entity and the math needed to update them. + * + * @class Body + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} [sx=16] - [description] + * @param {number} [sy=16] - [description] + */ +var Body = new Class({ + + initialize: + + function Body (world, x, y, sx, sy) + { + if (sx === undefined) { sx = 16; } + if (sy === undefined) { sy = sx; } + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#gameObject + * @type {Phaser.GameObjects.GameObject} + * @default null + * @since 3.0.0 + */ + this.gameObject = null; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The ImpactBody, ImpactSprite or ImpactImage object that owns this Body, if any. + * + * @name Phaser.Physics.Impact.Body#parent + * @type {?(Phaser.Physics.Impact.ImpactBody|Phaser.Physics.Impact.ImpactImage|Phaser.Physics.Impact.ImpactSprite)} + * @since 3.0.0 + */ + this.parent; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#id + * @type {integer} + * @since 3.0.0 + */ + this.id = world.getNextID(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#size + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.size = { x: sx, y: sy }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#offset + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.offset = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#pos + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.pos = { x: x, y: y }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#last + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.last = { x: x, y: y }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#vel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.vel = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.accel = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#friction + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.friction = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#maxVel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.maxVel = { x: world.defaults.maxVelocityX, y: world.defaults.maxVelocityY }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#standing + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.standing = false; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#gravityFactor + * @type {number} + * @since 3.0.0 + */ + this.gravityFactor = world.defaults.gravityFactor; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#bounciness + * @type {number} + * @since 3.0.0 + */ + this.bounciness = world.defaults.bounciness; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#minBounceVelocity + * @type {number} + * @since 3.0.0 + */ + this.minBounceVelocity = world.defaults.minBounceVelocity; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accelGround + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelGround = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accelAir + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelAir = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#jumpSpeed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.jumpSpeed = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#type + * @type {Phaser.Physics.Impact.TYPE} + * @since 3.0.0 + */ + this.type = TYPE.NONE; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#checkAgainst + * @type {Phaser.Physics.Impact.TYPE} + * @since 3.0.0 + */ + this.checkAgainst = TYPE.NONE; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#collides + * @type {Phaser.Physics.Impact.COLLIDES} + * @since 3.0.0 + */ + this.collides = COLLIDES.NEVER; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowBody; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowVelocity = world.defaults.debugShowVelocity; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.bodyDebugColor; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#updateCallback + * @type {?Phaser.Types.Physics.Impact.BodyUpdateCallback} + * @since 3.0.0 + */ + this.updateCallback; + + /** + * min 44 deg, max 136 deg + * + * @name Phaser.Physics.Impact.Body#slopeStanding + * @type {{ min: number, max: number }} + * @since 3.0.0 + */ + this.slopeStanding = { min: 0.767944870877505, max: 2.3736477827122884 }; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#reset + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + */ + reset: function (x, y) + { + this.pos = { x: x, y: y }; + this.last = { x: x, y: y }; + this.vel = { x: 0, y: 0 }; + this.accel = { x: 0, y: 0 }; + this.friction = { x: 0, y: 0 }; + this.maxVel = { x: 100, y: 100 }; + + this.standing = false; + + this.gravityFactor = 1; + this.bounciness = 0; + this.minBounceVelocity = 40; + + this.accelGround = 0; + this.accelAir = 0; + this.jumpSpeed = 0; + + this.type = TYPE.NONE; + this.checkAgainst = TYPE.NONE; + this.collides = COLLIDES.NEVER; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#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. + */ + update: function (delta) + { + var pos = this.pos; + + this.last.x = pos.x; + this.last.y = pos.y; + + this.vel.y += this.world.gravity * delta * this.gravityFactor; + + this.vel.x = GetVelocity(delta, this.vel.x, this.accel.x, this.friction.x, this.maxVel.x); + this.vel.y = GetVelocity(delta, this.vel.y, this.accel.y, this.friction.y, this.maxVel.y); + + var mx = this.vel.x * delta; + var my = this.vel.y * delta; + + var res = this.world.collisionMap.trace(pos.x, pos.y, mx, my, this.size.x, this.size.y); + + if (this.handleMovementTrace(res)) + { + UpdateMotion(this, res); + } + + var go = this.gameObject; + + if (go) + { + go.x = (pos.x - this.offset.x) + go.displayOriginX * go.scaleX; + go.y = (pos.y - this.offset.y) + go.displayOriginY * go.scaleY; + } + + if (this.updateCallback) + { + this.updateCallback(this); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - [description] + */ + drawDebug: function (graphic) + { + var pos = this.pos; + + if (this.debugShowBody) + { + graphic.lineStyle(1, this.debugBodyColor, 1); + graphic.strokeRect(pos.x, pos.y, this.size.x, this.size.y); + } + + if (this.debugShowVelocity) + { + var x = pos.x + this.size.x / 2; + var y = pos.y + this.size.y / 2; + + graphic.lineStyle(1, this.world.defaults.velocityDebugColor, 1); + graphic.lineBetween(x, y, x + this.vel.x, y + this.vel.y); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} [description] + */ + willDrawDebug: function () + { + return (this.debugShowBody || this.debugShowVelocity); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#skipHash + * @since 3.0.0 + * + * @return {boolean} [description] + */ + skipHash: function () + { + return (!this.enabled || (this.type === 0 && this.checkAgainst === 0 && this.collides === 0)); + }, + + /** + * Determines whether the body collides with the `other` one or not. + * + * @method Phaser.Physics.Impact.Body#touches + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + * + * @return {boolean} [description] + */ + touches: function (other) + { + return !( + this.pos.x >= other.pos.x + other.size.x || + this.pos.x + this.size.x <= other.pos.x || + this.pos.y >= other.pos.y + other.size.y || + this.pos.y + this.size.y <= other.pos.y + ); + }, + + /** + * Reset the size and position of the physics body. + * + * @method Phaser.Physics.Impact.Body#resetSize + * @since 3.0.0 + * + * @param {number} x - The x coordinate to position the body. + * @param {number} y - The y coordinate to position the body. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * + * @return {Phaser.Physics.Impact.Body} This Body object. + */ + resetSize: function (x, y, width, height) + { + this.pos.x = x; + this.pos.y = y; + this.size.x = width; + this.size.y = height; + + return this; + }, + + /** + * Export this body object to JSON. + * + * @method Phaser.Physics.Impact.Body#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Physics.Impact.JSONImpactBody} JSON representation of this body object. + */ + toJSON: function () + { + var output = { + name: this.name, + size: { x: this.size.x, y: this.size.y }, + pos: { x: this.pos.x, y: this.pos.y }, + vel: { x: this.vel.x, y: this.vel.y }, + accel: { x: this.accel.x, y: this.accel.y }, + friction: { x: this.friction.x, y: this.friction.y }, + maxVel: { x: this.maxVel.x, y: this.maxVel.y }, + gravityFactor: this.gravityFactor, + bounciness: this.bounciness, + minBounceVelocity: this.minBounceVelocity, + type: this.type, + checkAgainst: this.checkAgainst, + collides: this.collides + }; + + return output; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#fromJSON + * @todo Code it! + * @since 3.0.0 + * + * @param {object} config - [description] + */ + fromJSON: function () + { + }, + + /** + * Can be overridden by user code + * + * @method Phaser.Physics.Impact.Body#check + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + */ + check: function () + { + }, + + /** + * Can be overridden by user code + * + * @method Phaser.Physics.Impact.Body#collideWith + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + * @param {string} axis - [description] + */ + collideWith: function (other, axis) + { + if (this.parent && this.parent._collideCallback) + { + this.parent._collideCallback.call(this.parent._callbackScope, this, other, axis); + } + }, + + /** + * Can be overridden by user code but must return a boolean. + * + * @method Phaser.Physics.Impact.Body#handleMovementTrace + * @since 3.0.0 + * + * @param {number} res - [description] + * + * @return {boolean} [description] + */ + handleMovementTrace: function () + { + return true; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.remove(this); + + this.enabled = false; + + this.world = null; + + this.gameObject = null; + + this.parent = null; + } + +}); + +module.exports = Body; + + +/***/ }), +/* 497 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var DefaultDefs = __webpack_require__(1322); + +/** + * @classdesc + * [description] + * + * @class CollisionMap + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {integer} [tilesize=32] - [description] + * @param {array} [data] - [description] + */ +var CollisionMap = new Class({ + + initialize: + + function CollisionMap (tilesize, data) + { + if (tilesize === undefined) { tilesize = 32; } + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#tilesize + * @type {integer} + * @default 32 + * @since 3.0.0 + */ + this.tilesize = tilesize; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#data + * @type {array} + * @since 3.0.0 + */ + this.data = (Array.isArray(data)) ? data : []; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#width + * @type {number} + * @since 3.0.0 + */ + this.width = (Array.isArray(data)) ? data[0].length : 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#height + * @type {number} + * @since 3.0.0 + */ + this.height = (Array.isArray(data)) ? data.length : 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#lastSlope + * @type {integer} + * @default 55 + * @since 3.0.0 + */ + this.lastSlope = 55; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#tiledef + * @type {object} + * @since 3.0.0 + */ + this.tiledef = DefaultDefs; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#trace + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} objectWidth - [description] + * @param {number} objectHeight - [description] + * + * @return {boolean} [description] + */ + trace: function (x, y, vx, vy, objectWidth, objectHeight) + { + // Set up the trace-result + var res = { + collision: { x: false, y: false, slope: false }, + pos: { x: x + vx, y: y + vy }, + tile: { x: 0, y: 0 } + }; + + if (!this.data) + { + return res; + } + + var steps = Math.ceil(Math.max(Math.abs(vx), Math.abs(vy)) / this.tilesize); + + if (steps > 1) + { + var sx = vx / steps; + var sy = vy / steps; + + for (var i = 0; i < steps && (sx || sy); i++) + { + this.step(res, x, y, sx, sy, objectWidth, objectHeight, vx, vy, i); + + x = res.pos.x; + y = res.pos.y; + + if (res.collision.x) + { + sx = 0; + vx = 0; + } + + if (res.collision.y) + { + sy = 0; + vy = 0; + } + + if (res.collision.slope) + { + break; + } + } + } + else + { + this.step(res, x, y, vx, vy, objectWidth, objectHeight, vx, vy, 0); + } + + return res; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#step + * @since 3.0.0 + * + * @param {object} res - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} rvx - [description] + * @param {number} rvy - [description] + * @param {number} step - [description] + */ + step: function (res, x, y, vx, vy, width, height, rvx, rvy, step) + { + var t = 0; + var tileX; + var tileY; + var tilesize = this.tilesize; + var mapWidth = this.width; + var mapHeight = this.height; + + // Horizontal + if (vx) + { + var pxOffsetX = (vx > 0 ? width : 0); + var tileOffsetX = (vx < 0 ? tilesize : 0); + + var firstTileY = Math.max(Math.floor(y / tilesize), 0); + var lastTileY = Math.min(Math.ceil((y + height) / tilesize), mapHeight); + + tileX = Math.floor((res.pos.x + pxOffsetX) / tilesize); + + var prevTileX = Math.floor((x + pxOffsetX) / tilesize); + + if (step > 0 || tileX === prevTileX || prevTileX < 0 || prevTileX >= mapWidth) + { + prevTileX = -1; + } + + if (tileX >= 0 && tileX < mapWidth) + { + for (tileY = firstTileY; tileY < lastTileY; tileY++) + { + if (prevTileX !== -1) + { + t = this.data[tileY][prevTileX]; + + if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, prevTileX, tileY)) + { + break; + } + } + + t = this.data[tileY][tileX]; + + if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) + { + if (t > 1 && t <= this.lastSlope && res.collision.slope) + { + break; + } + + res.collision.x = true; + res.tile.x = t; + res.pos.x = (tileX * tilesize) - pxOffsetX + tileOffsetX; + x = res.pos.x; + rvx = 0; + + break; + } + } + } + } + + // Vertical + if (vy) + { + var pxOffsetY = (vy > 0 ? height : 0); + var tileOffsetY = (vy < 0 ? tilesize : 0); + + var firstTileX = Math.max(Math.floor(res.pos.x / tilesize), 0); + var lastTileX = Math.min(Math.ceil((res.pos.x + width) / tilesize), mapWidth); + + tileY = Math.floor((res.pos.y + pxOffsetY) / tilesize); + + var prevTileY = Math.floor((y + pxOffsetY) / tilesize); + + if (step > 0 || tileY === prevTileY || prevTileY < 0 || prevTileY >= mapHeight) + { + prevTileY = -1; + } + + if (tileY >= 0 && tileY < mapHeight) + { + for (tileX = firstTileX; tileX < lastTileX; tileX++) + { + if (prevTileY !== -1) + { + t = this.data[prevTileY][tileX]; + + if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, prevTileY)) + { + break; + } + } + + t = this.data[tileY][tileX]; + + if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) + { + if (t > 1 && t <= this.lastSlope && res.collision.slope) + { + break; + } + + res.collision.y = true; + res.tile.y = t; + res.pos.y = tileY * tilesize - pxOffsetY + tileOffsetY; + + break; + } + } + } + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#checkDef + * @since 3.0.0 + * + * @param {object} res - [description] + * @param {number} t - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} tileX - [description] + * @param {number} tileY - [description] + * + * @return {boolean} [description] + */ + checkDef: function (res, t, x, y, vx, vy, width, height, tileX, tileY) + { + var def = this.tiledef[t]; + + if (!def) + { + return false; + } + + var tilesize = this.tilesize; + + var lx = (tileX + def[0]) * tilesize; + var ly = (tileY + def[1]) * tilesize; + var lvx = (def[2] - def[0]) * tilesize; + var lvy = (def[3] - def[1]) * tilesize; + var solid = def[4]; + + var tx = x + vx + (lvy < 0 ? width : 0) - lx; + var ty = y + vy + (lvx > 0 ? height : 0) - ly; + + if (lvx * ty - lvy * tx > 0) + { + if (vx * -lvy + vy * lvx < 0) + { + return solid; + } + + var length = Math.sqrt(lvx * lvx + lvy * lvy); + var nx = lvy / length; + var ny = -lvx / length; + + var proj = tx * nx + ty * ny; + var px = nx * proj; + var py = ny * proj; + + if (px * px + py * py >= vx * vx + vy * vy) + { + return solid || (lvx * (ty - vy) - lvy * (tx - vx) < 0.5); + } + + res.pos.x = x + vx - px; + res.pos.y = y + vy - py; + res.collision.slope = { x: lvx, y: lvy, nx: nx, ny: ny }; + + return true; + } + + return false; + } + +}); + +module.exports = CollisionMap; + + +/***/ }), +/* 498 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var ImpactBody = __webpack_require__(499); +var ImpactImage = __webpack_require__(500); +var ImpactSprite = __webpack_require__(501); + +/** + * @classdesc + * The Impact Physics Factory allows you to easily create Impact Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + * + * @class Factory + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - A reference to the Impact Physics world. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * A reference to the Impact Physics world. + * + * @name Phaser.Physics.Impact.Factory#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * A reference to the Scene.Systems this Impact Physics instance belongs to. + * + * @name Phaser.Physics.Impact.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new ImpactBody object and adds it to the physics simulation. + * + * @method Phaser.Physics.Impact.Factory#body + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the body in the physics world. + * @param {number} y - The vertical position of the body in the physics world. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * + * @return {Phaser.Physics.Impact.ImpactBody} The ImpactBody object that was created. + */ + body: function (x, y, width, height) + { + return new ImpactBody(this.world, x, y, width, height); + }, + + /** + * Adds an Impact Physics Body to the given Game Object. + * + * @method Phaser.Physics.Impact.Factory#existing + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to receive the physics body. + * + * @return {Phaser.GameObjects.GameObject} The Game Object. + */ + existing: function (gameObject) + { + var x = gameObject.x - gameObject.frame.centerX; + var y = gameObject.y - gameObject.frame.centerY; + var w = gameObject.width; + var h = gameObject.height; + + gameObject.body = this.world.create(x, y, w, h); + + gameObject.body.parent = gameObject; + gameObject.body.gameObject = gameObject; + + return gameObject; + }, + + /** + * Creates a new ImpactImage object and adds it to the physics world. + * + * @method Phaser.Physics.Impact.Factory#image + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Impact.ImpactImage} The ImpactImage object that was created. + */ + image: function (x, y, key, frame) + { + var image = new ImpactImage(this.world, x, y, key, frame); + + this.sys.displayList.add(image); + + return image; + }, + + /** + * Creates a new ImpactSprite object and adds it to the physics world. + * + * @method Phaser.Physics.Impact.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Impact.ImpactSprite} The ImpactSprite object that was created. + */ + sprite: function (x, y, key, frame) + { + var sprite = new ImpactSprite(this.world, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + return sprite; + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Impact.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.sys = null; + } + +}); + +module.exports = Factory; + + +/***/ }), +/* 499 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(232); + +/** + * @classdesc + * [description] + * + * @class ImpactBody + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {number} x - x - The horizontal position of this physics body in the world. + * @param {number} y - y - The vertical position of this physics body in the world. + * @param {number} width - The width of the physics body in the world. + * @param {number} height - [description] + */ +var ImpactBody = new Class({ + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactBody (world, x, y, width, height) + { + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x, y, width, height); + + this.body.parent = this; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactBody; + + +/***/ }), +/* 500 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(232); +var Image = __webpack_require__(89); + +/** + * @classdesc + * An Impact Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class ImpactImage + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Impact.World} world - The physics world of the Impact physics system. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ImpactImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactImage (world, x, y, texture, frame) + { + Image.call(this, world.scene, x, y, texture, frame); + + /** + * The Physics Body linked to an ImpactImage. + * + * @name Phaser.Physics.Impact.ImpactImage#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); + + this.body.parent = this; + this.body.gameObject = this; + + /** + * The size of the physics Body. + * + * @name Phaser.Physics.Impact.ImpactImage#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * The X and Y offset of the Body from the left and top of the Image. + * + * @name Phaser.Physics.Impact.ImpactImage#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * The velocity, or rate of change the Body's position. Measured in pixels per second. + * + * @name Phaser.Physics.Impact.ImpactImage#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + * + * @name Phaser.Physics.Impact.ImpactImage#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * Friction between colliding bodies. + * + * @name Phaser.Physics.Impact.ImpactImage#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * The maximum velocity of the body. + * + * @name Phaser.Physics.Impact.ImpactImage#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactImage; + + +/***/ }), +/* 501 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(232); +var Sprite = __webpack_require__(65); + +/** + * @classdesc + * An Impact Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class ImpactSprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ImpactSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactSprite (world, x, y, texture, frame) + { + Sprite.call(this, world.scene, x, y, texture, frame); + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); + + this.body.parent = this; + this.body.gameObject = this; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactSprite; + + +/***/ }), +/* 502 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(496); +var Class = __webpack_require__(0); +var COLLIDES = __webpack_require__(112); +var CollisionMap = __webpack_require__(497); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(231); +var GetFastValue = __webpack_require__(1); +var HasValue = __webpack_require__(91); +var Set = __webpack_require__(110); +var Solver = __webpack_require__(1336); +var TILEMAP_FORMATS = __webpack_require__(34); +var TYPE = __webpack_require__(113); + +/** + * @classdesc + * [description] + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Impact World instance belongs. + * @param {Phaser.Types.Physics.Impact.WorldConfig} config - [description] + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#bodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.bodies = new Set(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#gravity + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.gravity = GetFastValue(config, 'gravity', 0); + + /** + * Spatial hash cell dimensions + * + * @name Phaser.Physics.Impact.World#cellSize + * @type {integer} + * @default 64 + * @since 3.0.0 + */ + this.cellSize = GetFastValue(config, 'cellSize', 64); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#collisionMap + * @type {Phaser.Physics.Impact.CollisionMap} + * @since 3.0.0 + */ + this.collisionMap = new CollisionMap(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = GetFastValue(config, 'timeScale', 1); + + /** + * Impacts maximum time step is 20 fps. + * + * @name Phaser.Physics.Impact.World#maxStep + * @type {number} + * @default 0.05 + * @since 3.0.0 + */ + this.maxStep = GetFastValue(config, 'maxStep', 0.05); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#drawDebug + * @type {boolean} + * @since 3.0.0 + */ + this.drawDebug = GetFastValue(config, 'debug', false); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + var _maxVelocity = GetFastValue(config, 'maxVelocity', 100); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#defaults + * @type {Phaser.Types.Physics.Impact.WorldDefaults} + * @since 3.0.0 + */ + this.defaults = { + debugShowBody: GetFastValue(config, 'debugShowBody', true), + debugShowVelocity: GetFastValue(config, 'debugShowVelocity', true), + bodyDebugColor: GetFastValue(config, 'debugBodyColor', 0xff00ff), + velocityDebugColor: GetFastValue(config, 'debugVelocityColor', 0x00ff00), + maxVelocityX: GetFastValue(config, 'maxVelocityX', _maxVelocity), + maxVelocityY: GetFastValue(config, 'maxVelocityY', _maxVelocity), + minBounceVelocity: GetFastValue(config, 'minBounceVelocity', 40), + gravityFactor: GetFastValue(config, 'gravityFactor', 1), + bounciness: GetFastValue(config, 'bounciness', 0) + }; + + /** + * An object containing the 4 wall bodies that bound the physics world. + * + * @name Phaser.Physics.Impact.World#walls + * @type {Phaser.Types.Physics.Impact.WorldWalls} + * @since 3.0.0 + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#delta + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.delta = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#_lastId + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._lastId = 0; + + if (GetFastValue(config, 'setBounds', false)) + { + var boundsConfig = config['setBounds']; + + if (typeof boundsConfig === 'boolean') + { + this.setBounds(); + } + else + { + var x = GetFastValue(boundsConfig, 'x', 0); + var y = GetFastValue(boundsConfig, 'y', 0); + var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); + var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); + var thickness = GetFastValue(boundsConfig, 'thickness', 64); + var left = GetFastValue(boundsConfig, 'left', true); + var right = GetFastValue(boundsConfig, 'right', true); + var top = GetFastValue(boundsConfig, 'top', true); + var bottom = GetFastValue(boundsConfig, 'bottom', true); + + this.setBounds(x, y, width, height, thickness, left, right, top, bottom); + } + } + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + }, + + /** + * Sets the collision map for the world either from a Weltmeister JSON level in the cache or from + * a 2D array. If loading from a Weltmeister level, the map must have a layer called "collision". + * + * @method Phaser.Physics.Impact.World#setCollisionMap + * @since 3.0.0 + * + * @param {(string|integer[][])} key - Either a string key that corresponds to a Weltmeister level + * in the cache, or a 2D array of collision IDs. + * @param {integer} tileSize - The size of a tile. This is optional if loading from a Weltmeister + * level in the cache. + * + * @return {?Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap, or null if the method failed to + * create the CollisionMap. + */ + setCollisionMap: function (key, tileSize) + { + if (typeof key === 'string') + { + var tilemapData = this.scene.cache.tilemap.get(key); + + if (!tilemapData || tilemapData.format !== TILEMAP_FORMATS.WELTMEISTER) + { + console.warn('The specified key does not correspond to a Weltmeister tilemap: ' + key); + return null; + } + + var layers = tilemapData.data.layer; + var collisionLayer; + for (var i = 0; i < layers.length; i++) + { + if (layers[i].name === 'collision') + { + collisionLayer = layers[i]; + break; + } + } + + if (tileSize === undefined) { tileSize = collisionLayer.tilesize; } + + this.collisionMap = new CollisionMap(tileSize, collisionLayer.data); + } + else if (Array.isArray(key)) + { + this.collisionMap = new CollisionMap(tileSize, key); + } + else + { + console.warn('Invalid Weltmeister collision map data: ' + key); + } + + return this.collisionMap; + }, + + /** + * Sets the collision map for the world from a tilemap layer. Only tiles that are marked as + * colliding will be used. You can specify the mapping from tiles to slope IDs in a couple of + * ways. The easiest is to use Tiled and the slopeTileProperty option. Alternatively, you can + * manually create a slopeMap that stores the mapping between tile indices and slope IDs. + * + * @method Phaser.Physics.Impact.World#setCollisionMapFromTilemapLayer + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemap layer to use. + * @param {Phaser.Types.Physics.Impact.CollisionOptions} [options] - Options for controlling the mapping from tiles to slope IDs. + * + * @return {Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap. + */ + setCollisionMapFromTilemapLayer: function (tilemapLayer, options) + { + if (options === undefined) { options = {}; } + var slopeProperty = GetFastValue(options, 'slopeProperty', null); + var slopeMap = GetFastValue(options, 'slopeMap', null); + var collidingSlope = GetFastValue(options, 'defaultCollidingSlope', null); + var nonCollidingSlope = GetFastValue(options, 'defaultNonCollidingSlope', 0); + + var layerData = tilemapLayer.layer; + var tileSize = layerData.baseTileWidth; + var collisionData = []; + + for (var ty = 0; ty < layerData.height; ty++) + { + collisionData[ty] = []; + + for (var tx = 0; tx < layerData.width; tx++) + { + var tile = layerData.data[ty][tx]; + + if (tile && tile.collides) + { + if (slopeProperty !== null && HasValue(tile.properties, slopeProperty)) + { + collisionData[ty][tx] = parseInt(tile.properties[slopeProperty], 10); + } + else if (slopeMap !== null && HasValue(slopeMap, tile.index)) + { + collisionData[ty][tx] = slopeMap[tile.index]; + } + else if (collidingSlope !== null) + { + collisionData[ty][tx] = collidingSlope; + } + else + { + collisionData[ty][tx] = tile.index; + } + } + else + { + collisionData[ty][tx] = nonCollidingSlope; + } + } + } + + this.collisionMap = new CollisionMap(tileSize, collisionData); + + return this.collisionMap; + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.Impact.World#setBounds + * @since 3.0.0 + * + * @param {number} [x] - The x coordinate of the top-left corner of the bounds. + * @param {number} [y] - The y coordinate of the top-left corner of the bounds. + * @param {number} [width] - The width of the bounds. + * @param {number} [height] - The height of the bounds. + * @param {number} [thickness=64] - [description] + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setBounds: function (x, y, width, height, thickness, left, right, top, bottom) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (thickness === undefined) { thickness = 64; } + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (bottom === undefined) { bottom = true; } + + this.updateWall(left, 'left', x - thickness, y, thickness, height); + this.updateWall(right, 'right', x + width, y, thickness, height); + this.updateWall(top, 'top', x, y - thickness, width, thickness); + this.updateWall(bottom, 'bottom', x, y + height, width, thickness); + + return this; + }, + + /** + * position = 'left', 'right', 'top' or 'bottom' + * + * @method Phaser.Physics.Impact.World#updateWall + * @since 3.0.0 + * + * @param {boolean} add - [description] + * @param {string} position - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} width - [description] + * @param {number} height - [description] + */ + updateWall: function (add, position, x, y, width, height) + { + var wall = this.walls[position]; + + if (add) + { + if (wall) + { + wall.resetSize(x, y, width, height); + } + else + { + this.walls[position] = this.create(x, y, width, height); + this.walls[position].name = position; + this.walls[position].gravityFactor = 0; + this.walls[position].collides = COLLIDES.FIXED; + } + } + else + { + if (wall) + { + this.bodies.remove(wall); + } + + this.walls[position] = null; + } + }, + + /** + * Creates a Graphics Game Object used for debug display and enables the world for debug drawing. + * + * @method Phaser.Physics.Impact.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The Graphics object created that will have the debug visuals drawn to it. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#getNextID + * @since 3.0.0 + * + * @return {integer} [description] + */ + getNextID: function () + { + return this._lastId++; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#create + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} sizeX - [description] + * @param {number} sizeY - [description] + * + * @return {Phaser.Physics.Impact.Body} The Body that was added to this World. + */ + create: function (x, y, sizeX, sizeY) + { + var body = new Body(this, x, y, sizeX, sizeY); + + this.bodies.set(body); + + return body; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#remove + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} object - The Body to remove from this World. + */ + remove: function (object) + { + this.bodies.delete(object); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#pause + * @fires Phaser.Physics.Impact.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + pause: function () + { + this.enabled = false; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#resume + * @fires Phaser.Physics.Impact.Events#RESUME + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + resume: function () + { + this.enabled = true; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.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. + */ + update: function (time, delta) + { + if (!this.enabled || this.bodies.size === 0) + { + return; + } + + // Impact uses a divided delta value that is clamped to the maxStep (20fps) maximum + + var clampedDelta = Math.min(delta / 1000, this.maxStep) * this.timeScale; + + this.delta = clampedDelta; + + // Update all active bodies + + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + var hash = {}; + var size = this.cellSize; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enabled) + { + body.update(clampedDelta); + } + } + + // Run collision against them all now they're in the new positions from the update + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body && !body.skipHash()) + { + this.checkHash(body, hash, size); + } + } + + if (this.drawDebug) + { + var graphics = this.debugGraphic; + + graphics.clear(); + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body && body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + } + }, + + /** + * Check the body against the spatial hash. + * + * @method Phaser.Physics.Impact.World#checkHash + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {object} hash - [description] + * @param {number} size - [description] + */ + checkHash: function (body, hash, size) + { + var checked = {}; + + var xmin = Math.floor(body.pos.x / size); + var ymin = Math.floor(body.pos.y / size); + var xmax = Math.floor((body.pos.x + body.size.x) / size) + 1; + var ymax = Math.floor((body.pos.y + body.size.y) / size) + 1; + + for (var x = xmin; x < xmax; x++) + { + for (var y = ymin; y < ymax; y++) + { + if (!hash[x]) + { + hash[x] = {}; + hash[x][y] = [ body ]; + } + else if (!hash[x][y]) + { + hash[x][y] = [ body ]; + } + else + { + var cell = hash[x][y]; + + for (var c = 0; c < cell.length; c++) + { + if (body.touches(cell[c]) && !checked[cell[c].id]) + { + checked[cell[c].id] = true; + + this.checkBodies(body, cell[c]); + } + } + + cell.push(body); + } + } + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#checkBodies + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} bodyA - [description] + * @param {Phaser.Physics.Impact.Body} bodyB - [description] + */ + checkBodies: function (bodyA, bodyB) + { + // 2 fixed bodies won't do anything + if (bodyA.collides === COLLIDES.FIXED && bodyB.collides === COLLIDES.FIXED) + { + return; + } + + // bitwise checks + if (bodyA.checkAgainst & bodyB.type) + { + bodyA.check(bodyB); + } + + if (bodyB.checkAgainst & bodyA.type) + { + bodyB.check(bodyA); + } + + if (bodyA.collides && bodyB.collides && bodyA.collides + bodyB.collides > COLLIDES.ACTIVE) + { + Solver(this, bodyA, bodyB); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCollidesNever + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCollidesNever: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.NEVER; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setLite + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setLite: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.LITE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setPassive + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setPassive: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.PASSIVE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setActive + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setActive: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.ACTIVE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setFixed + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setFixed: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.FIXED; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeNone + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeNone: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.NONE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setAvsB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setAvsB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.A; + bodies[i].checkAgainst = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setBvsA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setBvsA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.B; + bodies[i].checkAgainst = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstNone + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstNone: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.NONE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAllListeners(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.scene = null; + + this.bodies.clear(); + + this.bodies = null; + + this.collisionMap = null; + } + +}); + +module.exports = World; + + +/***/ }), +/* 503 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Vector2 = __webpack_require__(3); + +/** + * @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 + */ +var BodyBounds = new Class({ + + initialize: + + function BodyBounds () + { + /** + * A Vector2 that stores the temporary bounds center value during calculations by methods in this class. + * + * @name Phaser.Physics.Matter.BodyBounds#boundsCenter + * @type {Phaser.Math.Vector2} + * @since 3.22.0 + */ + this.boundsCenter = new Vector2(); + + /** + * A Vector2 that stores the temporary center diff values during calculations by methods in this class. + * + * @name Phaser.Physics.Matter.BodyBounds#centerDiff + * @type {Phaser.Math.Vector2} + * @since 3.22.0 + */ + this.centerDiff = new Vector2(); + }, + + /** + * Parses the given body to get the bounds diff values from it. + * + * They're stored in this class in the temporary properties `boundsCenter` and `centerDiff`. + * + * This method is called automatically by all other methods in this class. + * + * @method Phaser.Physics.Matter.BodyBounds#parseBody + * @since 3.22.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the bounds position from. + * + * @return {boolean} `true` if it was able to get the bounds, otherwise `false`. + */ + parseBody: function (body) + { + body = (body.hasOwnProperty('body')) ? body.body : body; + + if (!body.hasOwnProperty('bounds') || !body.hasOwnProperty('centerOfMass')) + { + return false; + } + + var boundsCenter = this.boundsCenter; + var centerDiff = this.centerDiff; + + var boundsWidth = body.bounds.max.x - body.bounds.min.x; + var boundsHeight = body.bounds.max.y - body.bounds.min.y; + + var bodyCenterX = boundsWidth * body.centerOfMass.x; + var bodyCenterY = boundsHeight * body.centerOfMass.y; + + boundsCenter.set(boundsWidth / 2, boundsHeight / 2); + centerDiff.set(bodyCenterX - boundsCenter.x, bodyCenterY - boundsCenter.y); + + return true; + }, + + /** + * 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 bodies _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. + */ + getTopLeft: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + center.x + diff.x, + y + center.y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getTopCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + diff.x, + y + center.y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getTopRight: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x - (center.x - diff.x), + y + center.y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getLeftCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + center.x + diff.x, + y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var diff = this.centerDiff; + + return new Vector2( + x + diff.x, + y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getRightCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x - (center.x - diff.x), + y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getBottomLeft: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + center.x + diff.x, + y - (center.y - diff.y) + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getBottomCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + diff.x, + y - (center.y - diff.y) + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getBottomRight: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x - (center.x - diff.x), + y - (center.y - diff.y) + ); + } + + return false; + } + +}); + +module.exports = BodyBounds; + + +/***/ }), +/* 504 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = __webpack_require__(42); +var Class = __webpack_require__(0); +var Composites = __webpack_require__(233); +var Constraint = __webpack_require__(78); +var Svg = __webpack_require__(234); +var MatterGameObject = __webpack_require__(1340); +var MatterImage = __webpack_require__(506); +var MatterSprite = __webpack_require__(507); +var MatterTileBody = __webpack_require__(238); +var PhysicsEditorParser = __webpack_require__(235); +var PhysicsJSONParser = __webpack_require__(236); +var PointerConstraint = __webpack_require__(1369); +var Vertices = __webpack_require__(31); + +/** + * @classdesc + * The Matter Factory is responsible for quickly creating a variety of different types of + * bodies, constraints and Game Objects and adding them into the physics world. + * + * You access the factory from within a Scene using `add`: + * + * ```javascript + * this.matter.add.rectangle(x, y, width, height); + * ``` + * + * Use of the Factory is optional. All of the objects it creates can also be created + * directly via your own code or constructors. It is provided as a means to keep your + * code concise. + * + * @class Factory + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.World} world - The Matter World which this Factory adds to. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * The Matter World which this Factory adds to. + * + * @name Phaser.Physics.Matter.Factory#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Scene which this Factory's Matter World belongs to. + * + * @name Phaser.Physics.Matter.Factory#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = world.scene; + + /** + * A reference to the Scene.Systems this Matter Physics instance belongs to. + * + * @name Phaser.Physics.Matter.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new rigid rectangular Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#rectangle + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} width - The width of the Body. + * @param {number} height - The height of the Body. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + rectangle: function (x, y, width, height, options) + { + var body = Bodies.rectangle(x, y, width, height, options); + + this.world.add(body); + + return body; + }, + + /** + * Creates a new rigid trapezoidal Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#trapezoid + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} width - The width of the trapezoid Body. + * @param {number} height - The height of the trapezoid Body. + * @param {number} slope - The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + trapezoid: function (x, y, width, height, slope, options) + { + var body = Bodies.trapezoid(x, y, width, height, slope, options); + + this.world.add(body); + + return body; + }, + + /** + * Creates a new rigid circular Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#circle + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} radius - The radius of the circle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * @param {number} [maxSides] - The maximum amount of sides to use for the polygon which will approximate this circle. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + circle: function (x, y, radius, options, maxSides) + { + var body = Bodies.circle(x, y, radius, options, maxSides); + + this.world.add(body); + + return body; + }, + + /** + * Creates a new rigid polygonal Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#polygon + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} sides - The number of sides the polygon will have. + * @param {number} radius - The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + polygon: function (x, y, sides, radius, options) + { + var body = Bodies.polygon(x, y, sides, radius, options); + + this.world.add(body); + + return body; + }, + + /** + * Creates a body using the supplied vertices (or an array containing multiple sets of vertices) and adds it to the World. + * If the vertices are convex, they will pass through as supplied. Otherwise, if the vertices are concave, they will be decomposed. Note that this process is not guaranteed to support complex sets of vertices, e.g. ones with holes. + * + * @method Phaser.Physics.Matter.Factory#fromVertices + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {(string|array)} vertexSets - The vertices data. Either a path string or an array of vertices. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * @param {boolean} [flagInternal=false] - Flag internal edges (coincident part edges) + * @param {number} [removeCollinear=0.01] - Whether Matter.js will discard collinear edges (to improve performance). + * @param {number} [minimumArea=10] - During decomposition discard parts that have an area less than this. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + fromVertices: function (x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) + { + if (typeof vertexSets === 'string') + { + vertexSets = Vertices.fromPath(vertexSets); + } + + var body = Bodies.fromVertices(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea); + + this.world.add(body); + + return 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 pas 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. + */ + fromPhysicsEditor: function (x, y, config, options, addToWorld) + { + if (addToWorld === undefined) { addToWorld = true; } + + var body = PhysicsEditorParser.parseBody(x, y, config, options); + + if (addToWorld && !this.world.has(body)) + { + this.world.add(body); + } + + return 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. + */ + fromSVG: function (x, y, xml, scale, options, addToWorld) + { + if (scale === undefined) { scale = 1; } + if (options === undefined) { options = {}; } + if (addToWorld === undefined) { addToWorld = true; } + + var path = xml.getElementsByTagName('path'); + var vertexSets = []; + + for (var i = 0; i < path.length; i++) + { + var points = Svg.pathToVertices(path[i], 30); + + if (scale !== 1) + { + Vertices.scale(points, scale, scale); + } + + vertexSets.push(points); + } + + var body = Bodies.fromVertices(x, y, vertexSets, options); + + if (addToWorld) + { + this.world.add(body); + } + + return body; + }, + + /** + * Creates a body using the supplied physics data, as provided by a JSON file. + * + * The data file should be loaded as JSON: + * + * ```javascript + * preload () + * { + * this.load.json('ninjas', 'assets/ninjas.json); + * } + * + * create () + * { + * const ninjaShapes = this.cache.json.get('ninjas'); + * + * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); + * } + * ``` + * + * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. + * + * If you pas in an `options` object, any settings in there will override those in the config object. + * + * The structure of the JSON file is as follows: + * + * ```text + * { + * 'generator_info': // The name of the application that created the JSON data + * 'shapeName': { + * 'type': // The type of body + * 'label': // Optional body label + * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs + * } + * } + * ``` + * + * At the time of writing, only the Phaser Physics Tracer App exports in this format. + * + * @method Phaser.Physics.Matter.Factory#fromJSON + * @since 3.22.0 + * + * @param {number} x - The X coordinate of the body. + * @param {number} y - The Y coordinate of the body. + * @param {any} config - The JSON physics data. + * @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. + */ + fromJSON: function (x, y, config, options, addToWorld) + { + if (options === undefined) { options = {}; } + if (addToWorld === undefined) { addToWorld = true; } + + var body = PhysicsJSONParser.parseBody(x, y, config, options); + + if (body && addToWorld) + { + this.world.add(body); + } + + return body; + }, + + /** + * Create a new composite containing Matter Image objects created in a grid arrangement. + * This function uses the body bounds to prevent overlaps. + * + * @method Phaser.Physics.Matter.Factory#imageStack + * @since 3.0.0 + * + * @param {string} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} frame - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the grid. + * @param {number} rows - The number of rows in the grid. + * @param {number} [columnGap=0] - The distance between each column. + * @param {number} [rowGap=0] - The distance between each row. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.CompositeType} A Matter JS Composite Stack. + */ + imageStack: function (key, frame, x, y, columns, rows, columnGap, rowGap, options) + { + if (columnGap === undefined) { columnGap = 0; } + if (rowGap === undefined) { rowGap = 0; } + if (options === undefined) { options = {}; } + + var world = this.world; + var displayList = this.sys.displayList; + + options.addToWorld = false; + + var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, function (x, y) + { + var image = new MatterImage(world, x, y, key, frame, options); + + displayList.add(image); + + return image.body; + }); + + world.add(stack); + + return stack; + }, + + /** + * Create a new composite containing bodies created in the callback in a grid arrangement. + * + * This function uses the body bounds to prevent overlaps. + * + * @method Phaser.Physics.Matter.Factory#stack + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the grid. + * @param {number} rows - The number of rows in the grid. + * @param {number} columnGap - The distance between each column. + * @param {number} rowGap - The distance between each row. + * @param {function} callback - The callback that creates the stack. + * + * @return {MatterJS.CompositeType} A new composite containing objects created in the callback. + */ + stack: function (x, y, columns, rows, columnGap, rowGap, callback) + { + var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, callback); + + this.world.add(stack); + + return stack; + }, + + /** + * Create a new composite containing bodies created in the callback in a pyramid arrangement. + * This function uses the body bounds to prevent overlaps. + * + * @method Phaser.Physics.Matter.Factory#pyramid + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the pyramid. + * @param {number} rows - The number of rows in the pyramid. + * @param {number} columnGap - The distance between each column. + * @param {number} rowGap - The distance between each row. + * @param {function} callback - The callback function to be invoked. + * + * @return {MatterJS.CompositeType} A Matter JS Composite pyramid. + */ + pyramid: function (x, y, columns, rows, columnGap, rowGap, callback) + { + var stack = Composites.pyramid(x, y, columns, rows, columnGap, rowGap, callback); + + this.world.add(stack); + + return stack; + }, + + /** + * 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. + */ + chain: function (composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) + { + return Composites.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options); + }, + + /** + * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. + * + * @method Phaser.Physics.Matter.Factory#mesh + * @since 3.0.0 + * + * @param {MatterJS.CompositeType} composite - The composite in which all bodies will be chained together. + * @param {number} columns - The number of columns in the mesh. + * @param {number} rows - The number of rows in the mesh. + * @param {boolean} crossBrace - Create cross braces for the mesh as well? + * @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. + */ + mesh: function (composite, columns, rows, crossBrace, options) + { + return Composites.mesh(composite, columns, rows, crossBrace, options); + }, + + /** + * Creates a composite with a Newton's Cradle setup of bodies and constraints. + * + * @method Phaser.Physics.Matter.Factory#newtonsCradle + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the start of the cradle. + * @param {number} y - The vertical position of the start of the cradle. + * @param {number} number - The number of balls in the cradle. + * @param {number} size - The radius of each ball in the cradle. + * @param {number} length - The length of the 'string' the balls hang from. + * + * @return {MatterJS.CompositeType} A Newton's cradle composite. + */ + newtonsCradle: function (x, y, number, size, length) + { + var composite = Composites.newtonsCradle(x, y, number, size, length); + + this.world.add(composite); + + return composite; + }, + + /** + * Creates a composite with simple car setup of bodies and constraints. + * + * @method Phaser.Physics.Matter.Factory#car + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the car in the world. + * @param {number} y - The vertical position of the car in the world. + * @param {number} width - The width of the car chasis. + * @param {number} height - The height of the car chasis. + * @param {number} wheelSize - The radius of the car wheels. + * + * @return {MatterJS.CompositeType} A new composite car body. + */ + car: function (x, y, width, height, wheelSize) + { + var composite = Composites.car(x, y, width, height, wheelSize); + + this.world.add(composite); + + return composite; + }, + + /** + * Creates a simple soft body like object. + * + * @method Phaser.Physics.Matter.Factory#softBody + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the Composite. + * @param {number} rows - The number of rows in the Composite. + * @param {number} columnGap - The distance between each column. + * @param {number} rowGap - The distance between each row. + * @param {boolean} crossBrace - `true` to create cross braces between the bodies, or `false` to create just straight braces. + * @param {number} particleRadius - The radius of this circlular composite. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [particleOptions] - An optional Body configuration object that is used to set initial Body properties on creation. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [constraintOptions] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.CompositeType} A new composite simple soft body. + */ + softBody: function (x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) + { + var composite = Composites.softBody(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions); + + this.world.add(composite); + + return composite; + }, + + /** + * This method is an alias for `Factory.constraint`. + * + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#joint + * @since 3.0.0 + * + * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. + * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. + * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + joint: function (bodyA, bodyB, length, stiffness, options) + { + return this.constraint(bodyA, bodyB, length, stiffness, options); + }, + + /** + * This method is an alias for `Factory.constraint`. + * + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#spring + * @since 3.0.0 + * + * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. + * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. + * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + spring: function (bodyA, bodyB, length, stiffness, options) + { + return this.constraint(bodyA, bodyB, length, stiffness, options); + }, + + /** + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#constraint + * @since 3.0.0 + * + * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. + * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. + * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + constraint: function (bodyA, bodyB, length, stiffness, options) + { + if (stiffness === undefined) { stiffness = 1; } + if (options === undefined) { options = {}; } + + options.bodyA = (bodyA.type === 'body') ? bodyA : bodyA.body; + options.bodyB = (bodyB.type === 'body') ? bodyB : bodyB.body; + + if (!isNaN(length)) + { + options.length = length; + } + + options.stiffness = stiffness; + + var constraint = Constraint.create(options); + + this.world.add(constraint); + + return constraint; + }, + + /** + * Constraints (or joints) are used for specifying that a fixed distance must be maintained + * between two bodies, or a body and a fixed world-space position. + * + * A world constraint has only one body, you should specify a `pointA` position in + * the constraint options parameter to attach the constraint to the world. + * + * The stiffness of constraints can be modified to create springs or elastic. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#worldConstraint + * @since 3.0.0 + * + * @param {MatterJS.BodyType} body - The Matter `Body` that this constraint is attached to. + * @param {number} [length] - A number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + worldConstraint: function (body, length, stiffness, options) + { + if (stiffness === undefined) { stiffness = 1; } + if (options === undefined) { options = {}; } + + options.bodyB = (body.type === 'body') ? body : body.body; + + if (!isNaN(length)) + { + options.length = length; + } + + options.stiffness = stiffness; + + var constraint = Constraint.create(options); + + this.world.add(constraint); + + return constraint; + }, + + /** + * This method is an alias for `Factory.pointerConstraint`. + * + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * + * @method Phaser.Physics.Matter.Factory#mouseSpring + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + mouseSpring: function (options) + { + return this.pointerConstraint(options); + }, + + /** + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * + * @method Phaser.Physics.Matter.Factory#pointerConstraint + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + pointerConstraint: function (options) + { + if (options === undefined) { options = {}; } + + if (!options.hasOwnProperty('render')) + { + options.render = { visible: false }; + } + + var pointerConstraint = new PointerConstraint(this.scene, this.world, options); + + this.world.add(pointerConstraint.constraint); + + return pointerConstraint; + }, + + /** + * Creates a Matter Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @method Phaser.Physics.Matter.Factory#image + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.Physics.Matter.Image} The Matter Image Game Object. + */ + image: function (x, y, key, frame, options) + { + var image = new MatterImage(this.world, x, y, key, frame, options); + + this.sys.displayList.add(image); + + return image; + }, + + /** + * Creates a wrapper around a Tile that provides access to a corresponding Matter body. A tile can only + * have one Matter body associated with it. You can either pass in an existing Matter body for + * the tile or allow the constructor to create the corresponding body for you. If the Tile has a + * collision group (defined in Tiled), those shapes will be used to create the body. If not, the + * tile's rectangle bounding box will be used. + * + * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. + * + * Note: not all Tiled collision shapes are supported. See + * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. + * + * @method Phaser.Physics.Matter.Factory#tileBody + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The target tile that should have a Matter body. + * @param {Phaser.Types.Physics.Matter.MatterTileOptions} [options] - Options to be used when creating the Matter body. + * + * @return {Phaser.Physics.Matter.TileBody} The Matter Tile Body Game Object. + */ + tileBody: function (tile, options) + { + return new MatterTileBody(this.world, tile, options); + }, + + /** + * Creates a Matter Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @method Phaser.Physics.Matter.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.Physics.Matter.Sprite} The Matter Sprite Game Object. + */ + sprite: function (x, y, key, frame, options) + { + var sprite = new MatterSprite(this.world, x, y, key, frame, options); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + return sprite; + }, + + /** + * Takes an existing Game Object and injects all of the Matter Components into it. + * + * This enables you to use component methods such as `setVelocity` or `isSensor` directly from + * this Game Object. + * + * You can also pass in either a Matter Body Configuration object, or a Matter Body instance + * to link with this Game Object. + * + * @method Phaser.Physics.Matter.Factory#gameObject + * @since 3.3.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to inject the Matter Components in to. + * @param {(Phaser.Types.Physics.Matter.MatterBodyConfig|MatterJS.Body)} [options] - A Matter Body configuration object, or an instance of a Matter Body. + * @param {boolean} [addToWorld=true] - Add this Matter Body to the World? + * + * @return {Phaser.GameObjects.GameObject} The Game Object that had the Matter Components injected into it. + */ + gameObject: function (gameObject, options, addToWorld) + { + return MatterGameObject(this.world, gameObject, options, addToWorld); + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Matter.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.scene = null; + this.sys = null; + } + +}); + +module.exports = Factory; + + +/***/ }), +/* 505 */ +/***/ (function(module, exports) { + +/** + * @author Stefan Hedman (http://steffe.se) + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// v0.3.0 + +module.exports = { + decomp: polygonDecomp, + quickDecomp: polygonQuickDecomp, + isSimple: polygonIsSimple, + removeCollinearPoints: polygonRemoveCollinearPoints, + removeDuplicatePoints: polygonRemoveDuplicatePoints, + makeCCW: polygonMakeCCW +}; + +/** + * Compute the intersection between two lines. + * @static + * @method lineInt + * @param {Array} l1 Line vector 1 + * @param {Array} l2 Line vector 2 + * @param {Number} precision Precision to use when checking if the lines are parallel + * @return {Array} The intersection point. + */ +function lineInt(l1,l2,precision){ + precision = precision || 0; + var i = [0,0]; // point + var a1, b1, c1, a2, b2, c2, det; // scalars + a1 = l1[1][1] - l1[0][1]; + b1 = l1[0][0] - l1[1][0]; + c1 = a1 * l1[0][0] + b1 * l1[0][1]; + a2 = l2[1][1] - l2[0][1]; + b2 = l2[0][0] - l2[1][0]; + c2 = a2 * l2[0][0] + b2 * l2[0][1]; + det = a1 * b2 - a2*b1; + if (!scalar_eq(det, 0, precision)) { // lines are not parallel + i[0] = (b2 * c1 - b1 * c2) / det; + i[1] = (a1 * c2 - a2 * c1) / det; + } + return i; +} + +/** + * Checks if two line segments intersects. + * @method segmentsIntersect + * @param {Array} p1 The start vertex of the first line segment. + * @param {Array} p2 The end vertex of the first line segment. + * @param {Array} q1 The start vertex of the second line segment. + * @param {Array} q2 The end vertex of the second line segment. + * @return {Boolean} True if the two line segments intersect + */ +function lineSegmentsIntersect(p1, p2, q1, q2){ + var dx = p2[0] - p1[0]; + var dy = p2[1] - p1[1]; + var da = q2[0] - q1[0]; + var db = q2[1] - q1[1]; + + // segments are parallel + if((da*dy - db*dx) === 0){ + return false; + } + + var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx); + var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy); + + return (s>=0 && s<=1 && t>=0 && t<=1); +} + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +function triangleArea(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))); +} + +function isLeft(a,b,c){ + return triangleArea(a,b,c) > 0; +} + +function isLeftOn(a,b,c) { + return triangleArea(a, b, c) >= 0; +} + +function isRight(a,b,c) { + return triangleArea(a, b, c) < 0; +} + +function isRightOn(a,b,c) { + return triangleArea(a, b, c) <= 0; +} + +var tmpPoint1 = [], + tmpPoint2 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +function collinear(a,b,c,thresholdAngle) { + if(!thresholdAngle){ + return triangleArea(a, b, c) === 0; + } else { + var ab = tmpPoint1, + bc = tmpPoint2; + + ab[0] = b[0]-a[0]; + ab[1] = b[1]-a[1]; + bc[0] = c[0]-b[0]; + bc[1] = c[1]-b[1]; + + var dot = ab[0]*bc[0] + ab[1]*bc[1], + magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]), + magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]), + angle = Math.acos(dot/(magA*magB)); + return angle < thresholdAngle; + } +} + +function sqdist(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +function polygonAt(polygon, i){ + var s = polygon.length; + return polygon[i < 0 ? i % s + s : i % s]; +} + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +function polygonClear(polygon){ + polygon.length = 0; +} + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +function polygonAppend(polygon, poly, from, to){ + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!isLeft(polygonAt(polygon, br - 1), polygonAt(polygon, br), polygonAt(polygon, br + 1))) { + polygonReverse(polygon); + return true; + } else { + return false; + } +} + +/** + * Reverse the vertices in the polygon + * @method reverse + */ +function polygonReverse(polygon){ + var tmp = []; + var N = polygon.length; + for(var i=0; i!==N; i++){ + tmp.push(polygon.pop()); + } + for(var i=0; i!==N; i++){ + polygon[i] = tmp[i]; + } +} + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +function polygonIsReflex(polygon, i){ + return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1)); +} + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +function polygonCanSee(polygon, a,b) { + var p, dist, l1=tmpLine1, l2=tmpLine2; + + if (isLeftOn(polygonAt(polygon, a + 1), polygonAt(polygon, a), polygonAt(polygon, b)) && isRightOn(polygonAt(polygon, a - 1), polygonAt(polygon, a), polygonAt(polygon, b))) { + return false; + } + dist = sqdist(polygonAt(polygon, a), polygonAt(polygon, b)); + for (var i = 0; i !== polygon.length; ++i) { // for each edge + if ((i + 1) % polygon.length === a || i === a){ // ignore incident edges + continue; + } + if (isLeftOn(polygonAt(polygon, a), polygonAt(polygon, b), polygonAt(polygon, i + 1)) && isRightOn(polygonAt(polygon, a), polygonAt(polygon, b), polygonAt(polygon, i))) { // if diag intersects an edge + l1[0] = polygonAt(polygon, a); + l1[1] = polygonAt(polygon, b); + l2[0] = polygonAt(polygon, i); + l2[1] = polygonAt(polygon, i + 1); + p = lineInt(l1,l2); + if (sqdist(polygonAt(polygon, a), p) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +} + +/** + * Check if two vertices in the polygon can see each other + * @method canSee2 + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +function polygonCanSee2(polygon, a,b) { + // for each edge + for (var i = 0; i !== polygon.length; ++i) { + // ignore incident edges + if (i === a || i === b || (i + 1) % polygon.length === a || (i + 1) % polygon.length === b){ + continue; + } + if( lineSegmentsIntersect(polygonAt(polygon, a), polygonAt(polygon, b), polygonAt(polygon, i), polygonAt(polygon, i+1)) ){ + return false; + } + } + return true; +} + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +function polygonCopy(polygon, i,j,targetPoly){ + var p = targetPoly || []; + polygonClear(p); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++){ + p.push(polygon[k]); + } + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++){ + p.push(polygon[k]); + } + + // Insert vertices i to end + for(var k=i; k 0){ + return polygonSlice(polygon, edges); + } else { + return [polygon]; + } +} + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +function polygonSlice(polygon, cutEdges){ + if(cutEdges.length === 0){ + return [polygon]; + } + if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length===2 && cutEdges[0][0] instanceof Array){ + + var polys = [polygon]; + + for(var i=0; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < polygon.length; ++i) { + if (polygonIsReflex(poly, i)) { + reflexVertices.push(poly[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < polygon.length; ++j) { + if (isLeft(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j)) && isRightOn(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j), polygonAt(poly, j - 1)); // find the point of intersection + if (isRight(polygonAt(poly, i + 1), polygonAt(poly, i), p)) { // make sure it's inside the poly + d = sqdist(poly[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (isLeft(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j + 1)) && isRightOn(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j))) { + p = getIntersectionPoint(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j), polygonAt(poly, j + 1)); + if (isLeft(polygonAt(poly, i - 1), polygonAt(poly, i), p)) { + d = sqdist(poly[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex === (upperIndex + 1) % polygon.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+polygon.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + polygonAppend(lowerPoly, poly, i, upperIndex+1); + lowerPoly.push(p); + upperPoly.push(p); + if (lowerIndex !== 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + polygonAppend(upperPoly, poly,lowerIndex,poly.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + polygonAppend(upperPoly, poly,0,i+1); + } else { + if (i !== 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + polygonAppend(lowerPoly, poly,i,poly.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + polygonAppend(lowerPoly, poly,0,upperIndex+1); + lowerPoly.push(p); + upperPoly.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + polygonAppend(upperPoly, poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+polygon.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += polygon.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if ( + isLeftOn(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j)) && + isRightOn(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j)) + ) { + d = sqdist(polygonAt(poly, i), polygonAt(poly, j)); + if (d < closestDist && polygonCanSee2(poly, i, j)) { + closestDist = d; + closestIndex = j % polygon.length; + } + } + } + + if (i < closestIndex) { + polygonAppend(lowerPoly, poly,i,closestIndex+1); + if (closestIndex !== 0){ + polygonAppend(upperPoly, poly,closestIndex,v.length); + } + polygonAppend(upperPoly, poly,0,i+1); + } else { + if (i !== 0){ + polygonAppend(lowerPoly, poly,i,v.length); + } + polygonAppend(lowerPoly, poly,0,closestIndex+1); + polygonAppend(upperPoly, poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.length < upperPoly.length) { + polygonQuickDecomp(lowerPoly,result,reflexVertices,steinerPoints,delta,maxlevel,level); + polygonQuickDecomp(upperPoly,result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + polygonQuickDecomp(upperPoly,result,reflexVertices,steinerPoints,delta,maxlevel,level); + polygonQuickDecomp(lowerPoly,result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(polygon); + + return result; +} + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +function polygonRemoveCollinearPoints(polygon, precision){ + var num = 0; + for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){ + if(collinear(polygonAt(polygon, i-1),polygonAt(polygon, i),polygonAt(polygon, i+1),precision)){ + // Remove the middle point + polygon.splice(i%polygon.length,1); + num++; + } + } + return num; +} + +/** + * Remove duplicate points in the polygon. + * @method removeDuplicatePoints + * @param {Number} [precision] The threshold to use when determining whether two points are the same. Use zero for best precision. + */ +function polygonRemoveDuplicatePoints(polygon, precision){ + for(var i=polygon.length-1; i>=1; --i){ + var pi = polygon[i]; + for(var j=i-1; j>=0; --j){ + if(points_eq(pi, polygon[j], precision)){ + polygon.splice(i,1); + continue; + } + } + } +} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +function scalar_eq(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) <= precision; +} + +/** + * Check if two points are equal + * @static + * @method points_eq + * @param {Array} a + * @param {Array} b + * @param {Number} [precision] + * @return {Boolean} + */ +function points_eq(a,b,precision){ + return scalar_eq(a[0],b[0],precision) && scalar_eq(a[1],b[1],precision); +} + + +/***/ }), +/* 506 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(147); +var GameObject = __webpack_require__(14); +var GetFastValue = __webpack_require__(1); +var Image = __webpack_require__(89); +var Pipeline = __webpack_require__(121); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Matter Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class Image + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Matter.Components.Bounce + * @extends Phaser.Physics.Matter.Components.Collision + * @extends Phaser.Physics.Matter.Components.Force + * @extends Phaser.Physics.Matter.Components.Friction + * @extends Phaser.Physics.Matter.Components.Gravity + * @extends Phaser.Physics.Matter.Components.Mass + * @extends Phaser.Physics.Matter.Components.Sensor + * @extends Phaser.Physics.Matter.Components.SetBody + * @extends Phaser.Physics.Matter.Components.Sleep + * @extends Phaser.Physics.Matter.Components.Static + * @extends Phaser.Physics.Matter.Components.Transform + * @extends Phaser.Physics.Matter.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Matter.World} world - A reference to the Matter.World instance that this body belongs to. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + */ +var MatterImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Bounce, + Components.Collision, + Components.Force, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.SetBody, + Components.Sleep, + Components.Static, + Components.Transform, + Components.Velocity, + Pipeline + ], + + initialize: + + function MatterImage (world, x, y, texture, frame, options) + { + GameObject.call(this, world.scene, 'Image'); + + this.setTexture(texture, frame); + this.setSizeToFrame(); + this.setOrigin(); + + /** + * A reference to the Matter.World instance that this body belongs to. + * + * @name Phaser.Physics.Matter.Image#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * An internal temp vector used for velocity and force calculations. + * + * @name Phaser.Physics.Matter.Image#_tempVec2 + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tempVec2 = new Vector2(x, y); + + var shape = GetFastValue(options, 'shape', null); + + if (shape) + { + this.setBody(shape, options); + } + else + { + this.setRectangle(this.width, this.height, options); + } + + this.setPosition(x, y); + + this.initPipeline('TextureTintPipeline'); + } + +}); + +module.exports = MatterImage; + + +/***/ }), +/* 507 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AnimationComponent = __webpack_require__(288); +var Class = __webpack_require__(0); +var Components = __webpack_require__(147); +var GameObject = __webpack_require__(14); +var GetFastValue = __webpack_require__(1); +var Pipeline = __webpack_require__(121); +var Sprite = __webpack_require__(65); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Matter Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class Sprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Matter.Components.Bounce + * @extends Phaser.Physics.Matter.Components.Collision + * @extends Phaser.Physics.Matter.Components.Force + * @extends Phaser.Physics.Matter.Components.Friction + * @extends Phaser.Physics.Matter.Components.Gravity + * @extends Phaser.Physics.Matter.Components.Mass + * @extends Phaser.Physics.Matter.Components.Sensor + * @extends Phaser.Physics.Matter.Components.SetBody + * @extends Phaser.Physics.Matter.Components.Sleep + * @extends Phaser.Physics.Matter.Components.Static + * @extends Phaser.Physics.Matter.Components.Transform + * @extends Phaser.Physics.Matter.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Matter.World} world - A reference to the Matter.World instance that this body belongs to. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + */ +var MatterSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Bounce, + Components.Collision, + Components.Force, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.SetBody, + Components.Sleep, + Components.Static, + Components.Transform, + Components.Velocity, + Pipeline + ], + + initialize: + + function MatterSprite (world, x, y, texture, frame, options) + { + GameObject.call(this, world.scene, 'Sprite'); + + this.anims = new AnimationComponent(this); + + this.setTexture(texture, frame); + this.setSizeToFrame(); + this.setOrigin(); + + /** + * A reference to the Matter.World instance that this body belongs to. + * + * @name Phaser.Physics.Matter.Sprite#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * An internal temp vector used for velocity and force calculations. + * + * @name Phaser.Physics.Matter.Sprite#_tempVec2 + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tempVec2 = new Vector2(x, y); + + var shape = GetFastValue(options, 'shape', null); + + if (shape) + { + this.setBody(shape, options); + } + else + { + this.setRectangle(this.width, this.height, options); + } + + this.setPosition(x, y); + + this.initPipeline('TextureTintPipeline'); + } + +}); + +module.exports = MatterSprite; + + +/***/ }), +/* 508 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* The `Matter` module is the top level namespace. It also includes a function for installing plugins on top of the library. +* +* @class Matter +*/ + +var Matter = {}; + +module.exports = Matter; + +var Plugin = __webpack_require__(240); +var Common = __webpack_require__(19); + +(function() { + + /** + * The library name. + * @property name + * @readOnly + * @type {String} + */ + Matter.name = 'matter-js'; + + /** + * The library version. + * @property version + * @readOnly + * @type {String} + */ + Matter.version = '0.14.2'; + + /** + * A list of plugin dependencies to be installed. These are normally set and installed through `Matter.use`. + * Alternatively you may set `Matter.uses` manually and install them by calling `Plugin.use(Matter)`. + * @property uses + * @type {Array} + */ + Matter.uses = []; + + /** + * The plugins that have been installed through `Matter.Plugin.install`. Read only. + * @property used + * @readOnly + * @type {Array} + */ + Matter.used = []; + + /** + * Installs the given plugins on the `Matter` namespace. + * This is a short-hand for `Plugin.use`, see it for more information. + * Call this function once at the start of your code, with all of the plugins you wish to install as arguments. + * Avoid calling this function multiple times unless you intend to manually control installation order. + * @method use + * @param ...plugin {Function} The plugin(s) to install on `base` (multi-argument). + */ + Matter.use = function() { + Plugin.use(Matter, Array.prototype.slice.call(arguments)); + }; + + /** + * Chains a function to excute before the original function on the given `path` relative to `Matter`. + * See also docs for `Common.chain`. + * @method before + * @param {string} path The path relative to `Matter` + * @param {function} func The function to chain before the original + * @return {function} The chained function that replaced the original + */ + Matter.before = function(path, func) { + path = path.replace(/^Matter./, ''); + return Common.chainPathBefore(Matter, path, func); + }; + + /** + * Chains a function to excute after the original function on the given `path` relative to `Matter`. + * See also docs for `Common.chain`. + * @method after + * @param {string} path The path relative to `Matter` + * @param {function} func The function to chain after the original + * @return {function} The chained function that replaced the original + */ + Matter.after = function(path, func) { + path = path.replace(/^Matter./, ''); + return Common.chainPathAfter(Matter, path, func); + }; + +})(); + + +/***/ }), +/* 509 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Query = {}; + +module.exports = Query; + +var Vector = __webpack_require__(37); +var SAT = __webpack_require__(149); +var Bounds = __webpack_require__(38); +var Bodies = __webpack_require__(42); +var Vertices = __webpack_require__(31); + +(function() { + + /** + * Returns a list of collisions between `body` and `bodies`. + * @method collides + * @param {body} body + * @param {body[]} bodies + * @return {object[]} Collisions + */ + Query.collides = function(body, bodies) { + var collisions = []; + + for (var i = 0; i < bodies.length; i++) { + var bodyA = bodies[i]; + + // Phaser addition - skip same body checks + if (body === bodyA) + { + continue; + } + + if (Bounds.overlaps(bodyA.bounds, body.bounds)) { + for (var j = bodyA.parts.length === 1 ? 0 : 1; j < bodyA.parts.length; j++) { + var part = bodyA.parts[j]; + + if (Bounds.overlaps(part.bounds, body.bounds)) { + var collision = SAT.collides(part, body); + + if (collision.collided) { + collisions.push(collision); + break; + } + } + } + } + } + + return collisions; + }; + + /** + * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. + * @method ray + * @param {body[]} bodies + * @param {vector} startPoint + * @param {vector} endPoint + * @param {number} [rayWidth] + * @return {object[]} Collisions + */ + Query.ray = function(bodies, startPoint, endPoint, rayWidth) { + rayWidth = rayWidth || 1e-100; + + var rayAngle = Vector.angle(startPoint, endPoint), + rayLength = Vector.magnitude(Vector.sub(startPoint, endPoint)), + rayX = (endPoint.x + startPoint.x) * 0.5, + rayY = (endPoint.y + startPoint.y) * 0.5, + ray = Bodies.rectangle(rayX, rayY, rayLength, rayWidth, { angle: rayAngle }), + collisions = Query.collides(ray, bodies); + + for (var i = 0; i < collisions.length; i += 1) { + var collision = collisions[i]; + collision.body = collision.bodyB = collision.bodyA; + } + + return collisions; + }; + + /** + * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. + * @method region + * @param {body[]} bodies + * @param {bounds} bounds + * @param {bool} [outside=false] + * @return {body[]} The bodies matching the query + */ + Query.region = function(bodies, bounds, outside) { + var result = []; + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + overlaps = Bounds.overlaps(body.bounds, bounds); + if ((overlaps && !outside) || (!overlaps && outside)) + result.push(body); + } + + return result; + }; + + /** + * Returns all bodies whose vertices contain the given point, from the given set of bodies. + * @method point + * @param {body[]} bodies + * @param {vector} point + * @return {body[]} The bodies matching the query + */ + Query.point = function(bodies, point) { + var result = []; + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + if (Bounds.contains(body.bounds, point)) { + for (var j = body.parts.length === 1 ? 0 : 1; j < body.parts.length; j++) { + var part = body.parts[j]; + + if (Bounds.contains(part.bounds, point) + && Vertices.contains(part.vertices, point)) { + result.push(body); + break; + } + } + } + } + + return result; + }; + +})(); + + +/***/ }), +/* 510 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* 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 +*/ + +var Engine = {}; + +module.exports = Engine; + +var World = __webpack_require__(241); +var Sleeping = __webpack_require__(95); +var Resolver = __webpack_require__(244); +var Pairs = __webpack_require__(243); +var Metrics = __webpack_require__(1370); +var Grid = __webpack_require__(242); +var Events = __webpack_require__(96); +var Composite = __webpack_require__(68); +var Constraint = __webpack_require__(78); +var Common = __webpack_require__(19); +var Body = __webpack_require__(25); + +(function() { + + /** + * 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 + */ + Engine.create = function(element, options) { + // options may be passed as the first (and only) argument + options = Common.isElement(element) ? options : element; + element = Common.isElement(element) ? element : null; + options = options || {}; + + if (element || options.render) { + Common.warn('Engine.create: engine.render is deprecated (see docs)'); + } + + var defaults = { + positionIterations: 6, + velocityIterations: 4, + constraintIterations: 2, + enableSleeping: false, + events: [], + plugin: {}, + timing: { + timestamp: 0, + timeScale: 1 + }, + broadphase: { + controller: Grid + } + }; + + var engine = Common.extend(defaults, options); + + engine.world = options.world || World.create(engine.world); + engine.pairs = Pairs.create(); + engine.broadphase = engine.broadphase.controller.create(engine.broadphase); + engine.metrics = engine.metrics || { extended: false }; + + // @if DEBUG + engine.metrics = Metrics.create(engine.metrics); + // @endif + + return engine; + }; + + /** + * Moves the simulation forward in time by `delta` ms. + * The `correction` argument is 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` 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. + * @method update + * @param {engine} engine + * @param {number} [delta=16.666] + * @param {number} [correction=1] + */ + Engine.update = function(engine, delta, correction) { + delta = delta || 1000 / 60; + correction = correction || 1; + + var world = engine.world, + timing = engine.timing, + broadphase = engine.broadphase, + broadphasePairs = [], + i; + + // increment timestamp + timing.timestamp += delta * timing.timeScale; + + // create an event object + var event = { + timestamp: timing.timestamp + }; + + Events.trigger(engine, 'beforeUpdate', event); + + // get lists of all bodies and constraints, no matter what composites they are in + var allBodies = Composite.allBodies(world), + allConstraints = Composite.allConstraints(world); + + // @if DEBUG + // reset metrics logging + Metrics.reset(engine.metrics); + // @endif + + // if sleeping enabled, call the sleeping controller + if (engine.enableSleeping) + Sleeping.update(allBodies, timing.timeScale); + + // applies gravity to all bodies + Engine._bodiesApplyGravity(allBodies, world.gravity); + + // update all body position and rotation by integration + Engine._bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds); + + // update all constraints (first pass) + Constraint.preSolveAll(allBodies); + for (i = 0; i < engine.constraintIterations; i++) { + Constraint.solveAll(allConstraints, timing.timeScale); + } + Constraint.postSolveAll(allBodies); + + // broadphase pass: find potential collision pairs + if (broadphase.controller) { + // if world is dirty, we must flush the whole grid + if (world.isModified) + broadphase.controller.clear(broadphase); + + // update the grid buckets based on current bodies + broadphase.controller.update(broadphase, allBodies, engine, world.isModified); + broadphasePairs = broadphase.pairsList; + } else { + // if no broadphase set, we just pass all bodies + broadphasePairs = allBodies; + } + + // clear all composite modified flags + if (world.isModified) { + Composite.setModified(world, false, false, true); + } + + // narrowphase pass: find actual collisions, then create or update collision pairs + var collisions = broadphase.detector(broadphasePairs, engine); + + // update collision pairs + var pairs = engine.pairs, + timestamp = timing.timestamp; + Pairs.update(pairs, collisions, timestamp); + Pairs.removeOld(pairs, timestamp); + + // wake up bodies involved in collisions + if (engine.enableSleeping) + Sleeping.afterCollisions(pairs.list, timing.timeScale); + + // trigger collision events + if (pairs.collisionStart.length > 0) + Events.trigger(engine, 'collisionStart', { pairs: pairs.collisionStart }); + + // iteratively resolve position between collisions + Resolver.preSolvePosition(pairs.list); + for (i = 0; i < engine.positionIterations; i++) { + Resolver.solvePosition(pairs.list, allBodies, timing.timeScale); + } + Resolver.postSolvePosition(allBodies); + + // update all constraints (second pass) + Constraint.preSolveAll(allBodies); + for (i = 0; i < engine.constraintIterations; i++) { + Constraint.solveAll(allConstraints, timing.timeScale); + } + Constraint.postSolveAll(allBodies); + + // iteratively resolve velocity between collisions + Resolver.preSolveVelocity(pairs.list); + for (i = 0; i < engine.velocityIterations; i++) { + Resolver.solveVelocity(pairs.list, timing.timeScale); + } + + // trigger collision events + if (pairs.collisionActive.length > 0) + Events.trigger(engine, 'collisionActive', { pairs: pairs.collisionActive }); + + if (pairs.collisionEnd.length > 0) + Events.trigger(engine, 'collisionEnd', { pairs: pairs.collisionEnd }); + + // @if DEBUG + // update metrics log + Metrics.update(engine.metrics, engine); + // @endif + + // clear force buffers + Engine._bodiesClearForces(allBodies); + + Events.trigger(engine, 'afterUpdate', event); + + return engine; + }; + + /** + * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. + * @method merge + * @param {engine} engineA + * @param {engine} engineB + */ + Engine.merge = function(engineA, engineB) { + Common.extend(engineA, engineB); + + if (engineB.world) { + engineA.world = engineB.world; + + Engine.clear(engineA); + + var bodies = Composite.allBodies(engineA.world); + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + Sleeping.set(body, false); + body.id = Common.nextId(); + } + } + }; + + /** + * Clears the engine including the world, pairs and broadphase. + * @method clear + * @param {engine} engine + */ + Engine.clear = function(engine) { + var world = engine.world; + + Pairs.clear(engine.pairs); + + var broadphase = engine.broadphase; + if (broadphase.controller) { + var bodies = Composite.allBodies(world); + broadphase.controller.clear(broadphase); + broadphase.controller.update(broadphase, bodies, engine, true); + } + }; + + /** + * Zeroes the `body.force` and `body.torque` force buffers. + * @method _bodiesClearForces + * @private + * @param {body[]} bodies + */ + Engine._bodiesClearForces = function(bodies) { + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + // reset force buffers + body.force.x = 0; + body.force.y = 0; + body.torque = 0; + } + }; + + /** + * Applys a mass dependant force to all given bodies. + * @method _bodiesApplyGravity + * @private + * @param {body[]} bodies + * @param {vector} gravity + */ + Engine._bodiesApplyGravity = function(bodies, gravity) { + var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001; + + if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) { + return; + } + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + if (body.ignoreGravity || body.isStatic || body.isSleeping) + continue; + + // apply gravity + body.force.x += (body.mass * gravity.x * gravityScale) * body.gravityScale.x; + body.force.y += (body.mass * gravity.y * gravityScale) * body.gravityScale.y; + } + }; + + /** + * Applys `Body.update` to all given `bodies`. + * @method _bodiesUpdate + * @private + * @param {body[]} bodies + * @param {number} deltaTime + * The amount of time elapsed between updates + * @param {number} timeScale + * @param {number} correction + * The Verlet correction factor (deltaTime / lastDeltaTime) + * @param {bounds} worldBounds + */ + Engine._bodiesUpdate = function(bodies, deltaTime, timeScale, correction, worldBounds) { + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + if (body.isStatic || body.isSleeping) + continue; + + Body.update(body, deltaTime, timeScale, correction); + } + }; + + /** + * An alias for `Runner.run`, see `Matter.Runner` for more information. + * @method run + * @param {engine} engine + */ + + /** + * Fired just before an update + * + * @event beforeUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update and all collision events + * + * @event afterUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) + * + * @event collisionStart + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) + * + * @event collisionActive + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) + * + * @event collisionEnd + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` that specifies the number of position iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property positionIterations + * @type number + * @default 6 + */ + + /** + * An integer `Number` that specifies the number of velocity iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property velocityIterations + * @type number + * @default 4 + */ + + /** + * An integer `Number` that specifies the number of constraint iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * The default value of `2` is usually very adequate. + * + * @property constraintIterations + * @type number + * @default 2 + */ + + /** + * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. + * Sleeping can improve stability and performance, but often at the expense of accuracy. + * + * @property enableSleeping + * @type boolean + * @default false + */ + + /** + * An `Object` containing properties regarding the timing systems of the engine. + * + * @property timing + * @type object + */ + + /** + * A `Number` that specifies the global scaling factor of time for all bodies. + * A value of `0` freezes the simulation. + * A value of `0.1` gives a slow-motion effect. + * A value of `1.2` gives a speed-up effect. + * + * @property timing.timeScale + * @type number + * @default 1 + */ + + /** + * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. + * It is incremented on every `Engine.update` by the given `delta` argument. + * + * @property timing.timestamp + * @type number + * @default 0 + */ + + /** + * An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`. + * One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`. + * + * A minimal custom renderer object must define at least three functions: `create`, `clear` and `world` (see `Matter.Render`). + * It is also possible to instead pass the _module_ reference via `options.render.controller` and `Engine.create` will instantiate one for you. + * + * @property render + * @type render + * @deprecated see Demo.js for an example of creating a renderer + * @default a Matter.Render instance + */ + + /** + * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. + * + * @property broadphase + * @type grid + * @default a Matter.Grid instance + */ + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + * + * @property world + * @type world + * @default a Matter.World instance + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + +})(); + + +/***/ }), +/* 511 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = __webpack_require__(42); +var Body = __webpack_require__(25); +var Class = __webpack_require__(0); +var Common = __webpack_require__(19); +var Composite = __webpack_require__(68); +var Engine = __webpack_require__(510); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(237); +var GetFastValue = __webpack_require__(1); +var GetValue = __webpack_require__(5); +var MatterBody = __webpack_require__(25); +var MatterEvents = __webpack_require__(96); +var MatterTileBody = __webpack_require__(238); +var MatterWorld = __webpack_require__(241); +var Vector = __webpack_require__(37); + +/** + * @classdesc + * The Matter World class is responsible for managing one single instance of a Matter Physics World for Phaser. + * + * Access this via `this.matter.world` from within a Scene. + * + * This class creates a Matter JS World Composite along with the Matter JS Engine during instantiation. It also + * handles delta timing, bounds, body and constraint creation and debug drawing. + * + * If you wish to access the Matter JS World object directly, see the `localWorld` property. + * If you wish to access the Matter Engine directly, see the `engine` property. + * + * This class is an Event Emitter and will proxy _all_ Matter JS events, as they are received. + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Matter World instance belongs. + * @param {Phaser.Types.Physics.Matter.MatterWorldConfig} config - The Matter World configuration object. + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * The Scene to which this Matter World instance belongs. + * + * @name Phaser.Physics.Matter.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * An instance of the MatterJS Engine. + * + * @name Phaser.Physics.Matter.World#engine + * @type {MatterJS.Engine} + * @since 3.0.0 + */ + this.engine = Engine.create(config); + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + * + * @name Phaser.Physics.Matter.World#localWorld + * @type {MatterJS.World} + * @since 3.0.0 + */ + this.localWorld = this.engine.world; + + var gravity = GetValue(config, 'gravity', null); + + if (gravity) + { + this.setGravity(gravity.x, gravity.y, gravity.scale); + } + else if (gravity === false) + { + this.setGravity(0, 0, 0); + } + + /** + * An object containing the 4 wall bodies that bound the physics world. + * + * @name Phaser.Physics.Matter.World#walls + * @type {object} + * @since 3.0.0 + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * A flag that toggles if the world is enabled or not. + * + * @name Phaser.Physics.Matter.World#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = GetValue(config, 'enabled', true); + + /** + * The correction argument is 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. + * + * @name Phaser.Physics.Matter.World#correction + * @type {number} + * @default 1 + * @since 3.4.0 + */ + this.correction = GetValue(config, 'correction', 1); + + /** + * This function is called every time the core game loop steps, which is bound to the + * Request Animation Frame frequency unless otherwise modified. + * + * The function is passed two values: `time` and `delta`, both of which come from the game step values. + * + * It must return a number. This number is used as the delta value passed to Matter.Engine.update. + * + * You can override this function with your own to define your own timestep. + * + * If you need to update the Engine multiple times in a single game step then call + * `World.update` as many times as required. Each call will trigger the `getDelta` function. + * If you wish to have full control over when the Engine updates then see the property `autoUpdate`. + * + * You can also adjust the number of iterations that Engine.update performs. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * + * @name Phaser.Physics.Matter.World#getDelta + * @type {function} + * @since 3.4.0 + */ + this.getDelta = GetValue(config, 'getDelta', this.update60Hz); + + var runnerConfig = GetFastValue(config, 'runner', {}); + + var hasFPS = GetFastValue(runnerConfig, 'fps', false); + + var fps = GetFastValue(runnerConfig, 'fps', 60); + + var delta = GetFastValue(runnerConfig, 'delta', 1000 / fps); + var deltaMin = GetFastValue(runnerConfig, 'deltaMin', 1000 / fps); + var deltaMax = GetFastValue(runnerConfig, 'deltaMax', 1000 / (fps * 0.5)); + + if (!hasFPS) + { + fps = 1000 / delta; + } + + /** + * The Matter JS Runner Configuration object. + * + * This object is populated via the Matter Configuration object's `runner` property and is + * updated constantly during the game step. + * + * @name Phaser.Physics.Matter.World#runner + * @type {Phaser.Types.Physics.Matter.MatterRunnerConfig} + * @since 3.22.0 + */ + this.runner = { + fps: fps, + correction: GetFastValue(runnerConfig, 'correction', 1), + deltaSampleSize: GetFastValue(runnerConfig, 'deltaSampleSize', 60), + counterTimestamp: 0, + frameCounter: 0, + deltaHistory: [], + timePrev: null, + timeScalePrev: 1, + frameRequestId: null, + isFixed: GetFastValue(runnerConfig, 'isFixed', false), + delta: delta, + deltaMin: deltaMin, + deltaMax: deltaMax + }; + + /** + * Automatically call Engine.update every time the game steps. + * If you disable this then you are responsible for calling `World.step` directly from your game. + * If you call `set60Hz` or `set30Hz` then `autoUpdate` is reset to `true`. + * + * @name Phaser.Physics.Matter.World#autoUpdate + * @type {boolean} + * @default true + * @since 3.4.0 + */ + this.autoUpdate = GetValue(config, 'autoUpdate', true); + + var debugConfig = GetValue(config, 'debug', false); + + /** + * A flag that controls if the debug graphics will be drawn to or not. + * + * @name Phaser.Physics.Matter.World#drawDebug + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.drawDebug = (typeof(debugConfig) === 'object') ? true : debugConfig; + + /** + * An instance of the Graphics object the debug bodies are drawn to, if enabled. + * + * @name Phaser.Physics.Matter.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + /** + * The debug configuration object. + * + * The values stored in this object are read from the Matter World Config `debug` property. + * + * When a new Body or Constraint is _added to the World_, they are given the values stored in this object, + * unless they have their own `render` object set that will override them. + * + * Note that while you can modify the values of properties in this object at run-time, it will not change + * any of the Matter objects _already added_. It will only impact objects newly added to the world, or one + * that is removed and then re-added at a later time. + * + * @name Phaser.Physics.Matter.World#debugConfig + * @type {Phaser.Types.Physics.Matter.MatterDebugConfig} + * @since 3.22.0 + */ + this.debugConfig = { + showAxes: GetFastValue(debugConfig, 'showAxes', false), + showAngleIndicator: GetFastValue(debugConfig, 'showAngleIndicator', false), + angleColor: GetFastValue(debugConfig, 'angleColor', 0xe81153), + + showBroadphase: GetFastValue(debugConfig, 'showBroadphase', false), + broadphaseColor: GetFastValue(debugConfig, 'broadphaseColor', 0xffb400), + + showBounds: GetFastValue(debugConfig, 'showBounds', false), + boundsColor: GetFastValue(debugConfig, 'boundsColor', 0xffffff), + + showVelocity: GetFastValue(debugConfig, 'showVelocity', false), + velocityColor: GetFastValue(debugConfig, 'velocityColor', 0x00aeef), + + showCollisions: GetFastValue(debugConfig, 'showCollisions', false), + collisionColor: GetFastValue(debugConfig, 'collisionColor', 0xf5950c), + + showSeparations: GetFastValue(debugConfig, 'showSeparations', false), + separationColor: GetFastValue(debugConfig, 'separationColor', 0xffa500), + + showBody: GetFastValue(debugConfig, 'showBody', true), + showStaticBody: GetFastValue(debugConfig, 'showStaticBody', true), + showInternalEdges: GetFastValue(debugConfig, 'showInternalEdges', false), + + renderFill: GetFastValue(debugConfig, 'renderFill', false), + renderLine: GetFastValue(debugConfig, 'renderLine', true), + + fillColor: GetFastValue(debugConfig, 'fillColor', 0x106909), + fillOpacity: GetFastValue(debugConfig, 'fillOpacity', 1), + lineColor: GetFastValue(debugConfig, 'lineColor', 0x28de19), + lineOpacity: GetFastValue(debugConfig, 'lineOpacity', 1), + lineThickness: GetFastValue(debugConfig, 'lineThickness', 1), + + staticFillColor: GetFastValue(debugConfig, 'staticFillColor', 0x0d177b), + staticLineColor: GetFastValue(debugConfig, 'staticLineColor', 0x1327e4), + + showSleeping: GetFastValue(debugConfig, 'showSleeping', false), + staticBodySleepOpacity: GetFastValue(debugConfig, 'staticBodySleepOpacity', 0.7), + sleepFillColor: GetFastValue(debugConfig, 'sleepFillColor', 0x464646), + sleepLineColor: GetFastValue(debugConfig, 'sleepLineColor', 0x999a99), + + showSensors: GetFastValue(debugConfig, 'showSensors', true), + sensorFillColor: GetFastValue(debugConfig, 'sensorFillColor', 0x0d177b), + sensorLineColor: GetFastValue(debugConfig, 'sensorLineColor', 0x1327e4), + + showPositions: GetFastValue(debugConfig, 'showPositions', true), + positionSize: GetFastValue(debugConfig, 'positionSize', 4), + positionColor: GetFastValue(debugConfig, 'positionColor', 0xe042da), + + showJoint: GetFastValue(debugConfig, 'showJoint', true), + jointColor: GetFastValue(debugConfig, 'jointColor', 0xe0e042), + jointLineOpacity: GetFastValue(debugConfig, 'jointLineOpacity', 1), + jointLineThickness: GetFastValue(debugConfig, 'jointLineThickness', 2), + + pinSize: GetFastValue(debugConfig, 'pinSize', 4), + pinColor: GetFastValue(debugConfig, 'pinColor', 0x42e0e0), + + springColor: GetFastValue(debugConfig, 'springColor', 0xe042e0), + + anchorColor: GetFastValue(debugConfig, 'anchorColor', 0xefefef), + anchorSize: GetFastValue(debugConfig, 'anchorSize', 4), + + showConvexHulls: GetFastValue(debugConfig, 'showConvexHulls', false), + hullColor: GetFastValue(debugConfig, 'hullColor', 0xd703d0) + }; + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + + this.setEventsProxy(); + + // Create the walls + + if (GetFastValue(config, 'setBounds', false)) + { + var boundsConfig = config['setBounds']; + + if (typeof boundsConfig === 'boolean') + { + this.setBounds(); + } + else + { + var x = GetFastValue(boundsConfig, 'x', 0); + var y = GetFastValue(boundsConfig, 'y', 0); + var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); + var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); + var thickness = GetFastValue(boundsConfig, 'thickness', 64); + var left = GetFastValue(boundsConfig, 'left', true); + var right = GetFastValue(boundsConfig, 'right', true); + var top = GetFastValue(boundsConfig, 'top', true); + var bottom = GetFastValue(boundsConfig, 'bottom', true); + + this.setBounds(x, y, width, height, thickness, left, right, top, bottom); + } + } + }, + + /** + * Sets the debug render style for the children of the given Matter Composite. + * + * Composites themselves do not render, but they can contain bodies, constraints and other composites that may do. + * So the children of this composite are passed to the `setBodyRenderStyle`, `setCompositeRenderStyle` and + * `setConstraintRenderStyle` methods accordingly. + * + * @method Phaser.Physics.Matter.World#setCompositeRenderStyle + * @since 3.22.0 + * + * @param {MatterJS.CompositeType} composite - The Matter Composite to set the render style on. + * + * @return {this} This Matter World instance for method chaining. + */ + setCompositeRenderStyle: function (composite) + { + var bodies = composite.bodies; + var constraints = composite.constraints; + var composites = composite.composites; + + var i; + var obj; + var render; + + for (i = 0; i < bodies.length; i++) + { + obj = bodies[i]; + render = obj.render; + + this.setBodyRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.fillColor, render.fillOpacity); + } + + for (i = 0; i < constraints.length; i++) + { + obj = constraints[i]; + render = obj.render; + + this.setConstraintRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.pinSize, render.anchorColor, render.anchorSize); + } + + for (i = 0; i < composites.length; i++) + { + obj = composites[i]; + + this.setCompositeRenderStyle(obj); + } + + return this; + }, + + /** + * Sets the debug render style for the given Matter Body. + * + * If you are using this on a Phaser Game Object, such as a Matter Sprite, then pass in the body property + * to this method, not the Game Object itself. + * + * If you wish to skip a parameter, so it retains its current value, pass `false` for it. + * + * If you wish to reset the Body render colors to the defaults found in the World Debug Config, then call + * this method with just the `body` parameter provided and no others. + * + * @method Phaser.Physics.Matter.World#setBodyRenderStyle + * @since 3.22.0 + * + * @param {MatterJS.BodyType} body - The Matter Body to set the render style on. + * @param {number} [lineColor] - The line color. If `null` it will use the World Debug Config value. + * @param {number} [lineOpacity] - The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * @param {number} [lineThickness] - The line thickness. If `null` it will use the World Debug Config value. + * @param {number} [fillColor] - The fill color. If `null` it will use the World Debug Config value. + * @param {number} [fillOpacity] - The fill opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * + * @return {this} This Matter World instance for method chaining. + */ + setBodyRenderStyle: function (body, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) + { + var render = body.render; + var config = this.debugConfig; + + if (!render) + { + return this; + } + + if (lineColor === undefined || lineColor === null) + { + lineColor = (body.isStatic) ? config.staticLineColor : config.lineColor; + } + + if (lineOpacity === undefined || lineOpacity === null) + { + lineOpacity = config.lineOpacity; + } + + if (lineThickness === undefined || lineThickness === null) + { + lineThickness = config.lineThickness; + } + + if (fillColor === undefined || fillColor === null) + { + fillColor = (body.isStatic) ? config.staticFillColor : config.fillColor; + } + + if (fillOpacity === undefined || fillOpacity === null) + { + fillOpacity = config.fillOpacity; + } + + if (lineColor !== false) + { + render.lineColor = lineColor; + } + + if (lineOpacity !== false) + { + render.lineOpacity = lineOpacity; + } + + if (lineThickness !== false) + { + render.lineThickness = lineThickness; + } + + if (fillColor !== false) + { + render.fillColor = fillColor; + } + + if (fillOpacity !== false) + { + render.fillOpacity = fillOpacity; + } + + return this; + }, + + /** + * Sets the debug render style for the given Matter Constraint. + * + * If you are using this on a Phaser Game Object, then pass in the body property + * to this method, not the Game Object itself. + * + * If you wish to skip a parameter, so it retains its current value, pass `false` for it. + * + * If you wish to reset the Constraint render colors to the defaults found in the World Debug Config, then call + * this method with just the `constraint` parameter provided and no others. + * + * @method Phaser.Physics.Matter.World#setConstraintRenderStyle + * @since 3.22.0 + * + * @param {MatterJS.ConstraintType} constraint - The Matter Constraint to set the render style on. + * @param {number} [lineColor] - The line color. If `null` it will use the World Debug Config value. + * @param {number} [lineOpacity] - The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * @param {number} [lineThickness] - The line thickness. If `null` it will use the World Debug Config value. + * @param {number} [pinSize] - If this constraint is a pin, this sets the size of the pin circle. If `null` it will use the World Debug Config value. + * @param {number} [anchorColor] - The color used when rendering this constraints anchors. If `null` it will use the World Debug Config value. + * @param {number} [anchorSize] - The size of the anchor circle, if this constraint has anchors. If `null` it will use the World Debug Config value. + * + * @return {this} This Matter World instance for method chaining. + */ + setConstraintRenderStyle: function (constraint, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize) + { + var render = constraint.render; + var config = this.debugConfig; + + if (!render) + { + return this; + } + + // Reset them + if (lineColor === undefined || lineColor === null) + { + var type = render.type; + + if (type === 'line') + { + lineColor = config.jointColor; + } + else if (type === 'pin') + { + lineColor = config.pinColor; + } + else if (type === 'spring') + { + lineColor = config.springColor; + } + } + + if (lineOpacity === undefined || lineOpacity === null) + { + lineOpacity = config.jointLineOpacity; + } + + if (lineThickness === undefined || lineThickness === null) + { + lineThickness = config.jointLineThickness; + } + + if (pinSize === undefined || pinSize === null) + { + pinSize = config.pinSize; + } + + if (anchorColor === undefined || anchorColor === null) + { + anchorColor = config.anchorColor; + } + + if (anchorSize === undefined || anchorSize === null) + { + anchorSize = config.anchorSize; + } + + if (lineColor !== false) + { + render.lineColor = lineColor; + } + + if (lineOpacity !== false) + { + render.lineOpacity = lineOpacity; + } + + if (lineThickness !== false) + { + render.lineThickness = lineThickness; + } + + if (pinSize !== false) + { + render.pinSize = pinSize; + } + + if (anchorColor !== false) + { + render.anchorColor = anchorColor; + } + + if (anchorSize !== false) + { + render.anchorSize = anchorSize; + } + + return this; + }, + + /** + * This internal method acts as a proxy between all of the Matter JS events and then re-emits them + * via this class. + * + * @method Phaser.Physics.Matter.World#setEventsProxy + * @since 3.0.0 + */ + setEventsProxy: function () + { + var _this = this; + var engine = this.engine; + var world = this.localWorld; + + // Inject debug styles + + if (this.drawDebug) + { + MatterEvents.on(world, 'compositeModified', function (composite) + { + _this.setCompositeRenderStyle(composite); + }); + + MatterEvents.on(world, 'beforeAdd', function (event) + { + var objects = [].concat(event.object); + + for (var i = 0; i < objects.length; i++) + { + var obj = objects[i]; + var render = obj.render; + + if (obj.type === 'body') + { + _this.setBodyRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.fillColor, render.fillOpacity); + } + else if (obj.type === 'composite') + { + _this.setCompositeRenderStyle(obj); + } + else if (obj.type === 'constraint') + { + _this.setConstraintRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.pinSize, render.anchorColor, render.anchorSize); + } + } + }); + } + + MatterEvents.on(world, 'beforeAdd', function (event) + { + _this.emit(Events.BEFORE_ADD, event); + }); + + MatterEvents.on(world, 'afterAdd', function (event) + { + _this.emit(Events.AFTER_ADD, event); + }); + + MatterEvents.on(world, 'beforeRemove', function (event) + { + _this.emit(Events.BEFORE_REMOVE, event); + }); + + MatterEvents.on(world, 'afterRemove', function (event) + { + _this.emit(Events.AFTER_REMOVE, event); + }); + + MatterEvents.on(engine, 'beforeUpdate', function (event) + { + _this.emit(Events.BEFORE_UPDATE, event); + }); + + MatterEvents.on(engine, 'afterUpdate', function (event) + { + _this.emit(Events.AFTER_UPDATE, event); + }); + + MatterEvents.on(engine, 'collisionStart', function (event) + { + var pairs = event.pairs; + var bodyA; + var bodyB; + + if (pairs.length > 0) + { + bodyA = pairs[0].bodyA; + bodyB = pairs[0].bodyB; + } + + _this.emit(Events.COLLISION_START, event, bodyA, bodyB); + }); + + MatterEvents.on(engine, 'collisionActive', function (event) + { + var pairs = event.pairs; + var bodyA; + var bodyB; + + if (pairs.length > 0) + { + bodyA = pairs[0].bodyA; + bodyB = pairs[0].bodyB; + } + + _this.emit(Events.COLLISION_ACTIVE, event, bodyA, bodyB); + }); + + MatterEvents.on(engine, 'collisionEnd', function (event) + { + var pairs = event.pairs; + var bodyA; + var bodyB; + + if (pairs.length > 0) + { + bodyA = pairs[0].bodyA; + bodyB = pairs[0].bodyB; + } + + _this.emit(Events.COLLISION_END, event, bodyA, bodyB); + }); + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.Matter.World#setBounds + * @since 3.0.0 + * + * @param {number} [x=0] - The x coordinate of the top-left corner of the bounds. + * @param {number} [y=0] - The y coordinate of the top-left corner of the bounds. + * @param {number} [width] - The width of the bounds. + * @param {number} [height] - The height of the bounds. + * @param {number} [thickness=64] - The thickness of each wall, in pixels. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * + * @return {Phaser.Physics.Matter.World} This Matter World object. + */ + setBounds: function (x, y, width, height, thickness, left, right, top, bottom) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (thickness === undefined) { thickness = 64; } + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (bottom === undefined) { bottom = true; } + + this.updateWall(left, 'left', x - thickness, y - thickness, thickness, height + (thickness * 2)); + this.updateWall(right, 'right', x + width, y - thickness, thickness, height + (thickness * 2)); + this.updateWall(top, 'top', x, y - thickness, width, thickness); + this.updateWall(bottom, 'bottom', x, y + height, width, thickness); + + return this; + }, + + /** + * Updates the 4 rectangle bodies that were created, if `setBounds` was set in the Matter config, to use + * the new positions and sizes. This method is usually only called internally via the `setBounds` method. + * + * @method Phaser.Physics.Matter.World#updateWall + * @since 3.0.0 + * + * @param {boolean} add - `true` if the walls are being added or updated, `false` to remove them from the world. + * @param {string} [position] - Either `left`, `right`, `top` or `bottom`. Only optional if `add` is `false`. + * @param {number} [x] - The horizontal position to place the walls at. Only optional if `add` is `false`. + * @param {number} [y] - The vertical position to place the walls at. Only optional if `add` is `false`. + * @param {number} [width] - The width of the walls, in pixels. Only optional if `add` is `false`. + * @param {number} [height] - The height of the walls, in pixels. Only optional if `add` is `false`. + */ + updateWall: function (add, position, x, y, width, height) + { + var wall = this.walls[position]; + + if (add) + { + if (wall) + { + MatterWorld.remove(this.localWorld, wall); + } + + // adjust center + x += (width / 2); + y += (height / 2); + + this.walls[position] = this.create(x, y, width, height, { isStatic: true, friction: 0, frictionStatic: 0 }); + } + else + { + if (wall) + { + MatterWorld.remove(this.localWorld, wall); + } + + this.walls[position] = null; + } + }, + + /** + * Creates a Phaser.GameObjects.Graphics object that is used to render all of the debug bodies and joints to. + * + * This method is called automatically by the constructor, if debugging has been enabled. + * + * The created Graphics object is automatically added to the Scene at 0x0 and given a depth of `Number.MAX_VALUE`, + * so it renders above all else in the Scene. + * + * The Graphics object is assigned to the `debugGraphic` property of this class and `drawDebug` is enabled. + * + * @method Phaser.Physics.Matter.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The newly created Graphics object. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * Sets the world gravity and gravity scale to 0. + * + * @method Phaser.Physics.Matter.World#disableGravity + * @since 3.0.0 + * + * @return {this} This Matter World object. + */ + disableGravity: function () + { + this.localWorld.gravity.x = 0; + this.localWorld.gravity.y = 0; + this.localWorld.gravity.scale = 0; + + return this; + }, + + /** + * Sets the worlds gravity to the values given. + * + * Gravity effects all bodies in the world, unless they have the `ignoreGravity` flag set. + * + * @method Phaser.Physics.Matter.World#setGravity + * @since 3.0.0 + * + * @param {number} [x=0] - The world gravity x component. + * @param {number} [y=1] - The world gravity y component. + * @param {number} [scale=0.001] - The gravity scale factor. + * + * @return {this} This Matter World object. + */ + setGravity: function (x, y, scale) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 1; } + + this.localWorld.gravity.x = x; + this.localWorld.gravity.y = y; + + if (scale !== undefined) + { + this.localWorld.gravity.scale = scale; + } + + return this; + }, + + /** + * Creates a rectangle Matter body and adds it to the world. + * + * @method Phaser.Physics.Matter.World#create + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the body in the world. + * @param {number} y - The vertical position of the body in the world. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * @param {object} options - Optional Matter configuration object. + * + * @return {MatterJS.BodyType} The Matter.js body that was created. + */ + create: function (x, y, width, height, options) + { + var body = Bodies.rectangle(x, y, width, height, options); + + MatterWorld.add(this.localWorld, body); + + return body; + }, + + /** + * Adds a Matter JS object, or array of objects, to the world. + * + * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. + * + * Triggers `beforeAdd` and `afterAdd` events. + * + * @method Phaser.Physics.Matter.World#add + * @since 3.0.0 + * + * @param {(object|object[])} object - Can be single object, or an array, and can be a body, composite or constraint. + * + * @return {this} This Matter World object. + */ + add: function (object) + { + MatterWorld.add(this.localWorld, object); + + return this; + }, + + /** + * Removes a Matter JS object, or array of objects, from the world. + * + * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. + * + * Triggers `beforeRemove` and `afterRemove` events. + * + * @method Phaser.Physics.Matter.World#remove + * @since 3.0.0 + * + * @param {(object|object[])} object - Can be single object, or an array, and can be a body, composite or constraint. + * @param {boolean} [deep=false] - Optionally search the objects children and recursively remove those as well. + * + * @return {this} This Matter World object. + */ + remove: function (object, deep) + { + if (!Array.isArray(object)) + { + object = [ object ]; + } + + for (var i = 0; i < object.length; i++) + { + var entity = object[i]; + + var body = (entity.body) ? entity.body : entity; + + Composite.remove(this.localWorld, body, deep); + } + + return this; + }, + + /** + * Removes a Matter JS constraint, or array of constraints, from the world. + * + * Triggers `beforeRemove` and `afterRemove` events. + * + * @method Phaser.Physics.Matter.World#removeConstraint + * @since 3.0.0 + * + * @param {(MatterJS.ConstraintType|MatterJS.ConstraintType[])} constraint - A Matter JS Constraint, or an array of constraints, to be removed. + * @param {boolean} [deep=false] - Optionally search the objects children and recursively remove those as well. + * + * @return {this} This Matter World object. + */ + removeConstraint: function (constraint, deep) + { + Composite.remove(this.localWorld, constraint, deep); + + return this; + }, + + /** + * Adds `MatterTileBody` instances for all the colliding tiles within the given tilemap layer. + * + * Set the appropriate tiles in your layer to collide before calling this method! + * + * @method Phaser.Physics.Matter.World#convertTilemapLayer + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - + * An array of tiles. + * @param {object} [options] - Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} + * + * @return {this} This Matter World object. + */ + convertTilemapLayer: function (tilemapLayer, options) + { + var layerData = tilemapLayer.layer; + var tiles = tilemapLayer.getTilesWithin(0, 0, layerData.width, layerData.height, { isColliding: true }); + + this.convertTiles(tiles, options); + + return this; + }, + + /** + * Adds `MatterTileBody` instances for the given tiles. This adds bodies regardless of whether the + * tiles are set to collide or not. + * + * @method Phaser.Physics.Matter.World#convertTiles + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of tiles. + * @param {object} [options] - Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} + * + * @return {this} This Matter World object. + */ + convertTiles: function (tiles, options) + { + if (tiles.length === 0) + { + return this; + } + + for (var i = 0; i < tiles.length; i++) + { + new MatterTileBody(this, tiles[i], options); + } + + return this; + }, + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will not collide. + * + * @method Phaser.Physics.Matter.World#nextGroup + * @since 3.0.0 + * + * @param {boolean} [isNonColliding=false] - If `true`, returns the next unique group index for which bodies will _not_ collide. + * + * @return {number} Unique category bitfield + */ + nextGroup: function (isNonColliding) + { + return MatterBody.nextGroup(isNonColliding); + }, + + /** + * Returns the next unique category bitfield (starting after the initial default category 0x0001). + * There are 32 available. + * + * @method Phaser.Physics.Matter.World#nextCategory + * @since 3.0.0 + * + * @return {number} Unique category bitfield + */ + nextCategory: function () + { + return MatterBody.nextCategory(); + }, + + /** + * Pauses this Matter World instance and sets `enabled` to `false`. + * + * A paused world will not run any simulations for the duration it is paused. + * + * @method Phaser.Physics.Matter.World#pause + * @fires Phaser.Physics.Matter.Events#PAUSE + * @since 3.0.0 + * + * @return {this} This Matter World object. + */ + pause: function () + { + this.enabled = false; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. + * + * @method Phaser.Physics.Matter.World#resume + * @fires Phaser.Physics.Matter.Events#RESUME + * @since 3.0.0 + * + * @return {this} This Matter World object. + */ + resume: function () + { + this.enabled = true; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * 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. + */ + update: function (time, delta) + { + if (!this.enabled || !this.autoUpdate) + { + return; + } + + var engine = this.engine; + var runner = this.runner; + + var timing = engine.timing; + var correction = this.correction; + + if (runner.isFixed) + { + // fixed timestep + delta = this.getDelta(time, delta); + } + else + { + // dynamic timestep based on wall clock between calls + delta = (time - runner.timePrev) || runner.delta; + runner.timePrev = time; + + // optimistically filter delta over a few frames, to improve stability + runner.deltaHistory.push(delta); + runner.deltaHistory = runner.deltaHistory.slice(-runner.deltaSampleSize); + delta = Math.min.apply(null, runner.deltaHistory); + + // limit delta + delta = delta < runner.deltaMin ? runner.deltaMin : delta; + delta = delta > runner.deltaMax ? runner.deltaMax : delta; + + // correction for delta + correction = delta / runner.delta; + + // update engine timing object + runner.delta = delta; + } + + // time correction for time scaling + if (runner.timeScalePrev !== 0) + { + correction *= timing.timeScale / runner.timeScalePrev; + } + + if (timing.timeScale === 0) + { + correction = 0; + } + + runner.timeScalePrev = timing.timeScale; + runner.correction = correction; + + // fps counter + runner.frameCounter += 1; + + if (time - runner.counterTimestamp >= 1000) + { + runner.fps = runner.frameCounter * ((time - runner.counterTimestamp) / 1000); + runner.counterTimestamp = time; + runner.frameCounter = 0; + } + + Engine.update(engine, delta, correction); + }, + + /** + * Manually advances the physics simulation by one iteration. + * + * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. + * If undefined they use the Matter defaults of 60Hz and no correction. + * + * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. + * + * It also ignores any custom `getDelta` functions, as you should be passing the delta + * value in to this call. + * + * You can adjust the number of iterations that Engine.update performs internally. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * + * @method Phaser.Physics.Matter.World#step + * @since 3.4.0 + * + * @param {number} [delta=16.666] - The delta value. + * @param {number} [correction=1] - Optional delta correction value. + */ + step: function (delta, correction) + { + Engine.update(this.engine, delta, correction); + }, + + /** + * Runs the Matter Engine.update at a fixed timestep of 60Hz. + * + * @method Phaser.Physics.Matter.World#update60Hz + * @since 3.4.0 + * + * @return {number} The delta value to be passed to Engine.update. + */ + update60Hz: function () + { + return 1000 / 60; + }, + + /** + * Runs the Matter Engine.update at a fixed timestep of 30Hz. + * + * @method Phaser.Physics.Matter.World#update30Hz + * @since 3.4.0 + * + * @return {number} The delta value to be passed to Engine.update. + */ + update30Hz: function () + { + return 1000 / 30; + }, + + /** + * Returns `true` if the given body can be found within the World. + * + * @method Phaser.Physics.Matter.World#has + * @since 3.22.0 + * + * @param {(MatterJS.Body|Phaser.GameObjects.GameObject)} body - The Matter Body, or Game Object, to search for within the world. + * + * @return {MatterJS.BodyType[]} An array of all the Matter JS Bodies in this World. + */ + has: function (body) + { + var src = (body.hasOwnProperty('body')) ? body.body : body; + + return (Composite.get(this.localWorld, src.id, src.type) !== null); + }, + + /** + * Returns all the bodies in the Matter World, including all bodies in children, recursively. + * + * @method Phaser.Physics.Matter.World#getAllBodies + * @since 3.22.0 + * + * @return {MatterJS.BodyType[]} An array of all the Matter JS Bodies in this World. + */ + getAllBodies: function () + { + return Composite.allBodies(this.localWorld); + }, + + /** + * Returns all the constraints in the Matter World, including all constraints in children, recursively. + * + * @method Phaser.Physics.Matter.World#getAllConstraints + * @since 3.22.0 + * + * @return {MatterJS.ConstraintType[]} An array of all the Matter JS Constraints in this World. + */ + getAllConstraints: function () + { + return Composite.allConstraints(this.localWorld); + }, + + /** + * Returns all the composites in the Matter World, including all composites in children, recursively. + * + * @method Phaser.Physics.Matter.World#getAllComposites + * @since 3.22.0 + * + * @return {MatterJS.CompositeType[]} An array of all the Matter JS Composites in this World. + */ + getAllComposites: function () + { + return Composite.allComposites(this.localWorld); + }, + + /** + * Handles the rendering of bodies and debug information to the debug Graphics object, if enabled. + * + * This method is called automatically by the Scene after all processing has taken place. + * + * @method Phaser.Physics.Matter.World#postUpdate + * @private + * @since 3.0.0 + */ + postUpdate: function () + { + if (!this.drawDebug) + { + return; + } + + var config = this.debugConfig; + var engine = this.engine; + var graphics = this.debugGraphic; + + var bodies = Composite.allBodies(this.localWorld); + + this.debugGraphic.clear(); + + if (config.showBroadphase && engine.broadphase.controller) + { + this.renderGrid(engine.broadphase, graphics, config.broadphaseColor, 0.5); + } + + if (config.showBounds) + { + this.renderBodyBounds(bodies, graphics, config.boundsColor, 0.5); + } + + if (config.showBody || config.showStaticBody) + { + this.renderBodies(bodies); + } + + if (config.showJoint) + { + this.renderJoints(); + } + + if (config.showAxes || config.showAngleIndicator) + { + this.renderBodyAxes(bodies, graphics, config.showAxes, config.angleColor, 0.5); + } + + if (config.showVelocity) + { + this.renderBodyVelocity(bodies, graphics, config.velocityColor, 1, 2); + } + + if (config.showSeparations) + { + this.renderSeparations(engine.pairs.list, graphics, config.separationColor); + } + + if (config.showCollisions) + { + this.renderCollisions(engine.pairs.list, graphics, config.collisionColor); + } + }, + + /** + * Renders the Engine Broadphase Controller Grid to the given Graphics instance. + * + * The debug renderer calls this method if the `showBroadphase` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderGrid + * @since 3.22.0 + * + * @param {MatterJS.Grid} grid - The Matter Grid to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + * + * @return {this} This Matter World instance for method chaining. + */ + renderGrid: function (grid, graphics, lineColor, lineOpacity) + { + graphics.lineStyle(1, lineColor, lineOpacity); + + var bucketKeys = Common.keys(grid.buckets); + + for (var i = 0; i < bucketKeys.length; i++) + { + var bucketId = bucketKeys[i]; + + if (grid.buckets[bucketId].length < 2) + { + continue; + } + + var region = bucketId.split(/C|R/); + + graphics.strokeRect( + parseInt(region[1], 10) * grid.bucketWidth, + parseInt(region[2], 10) * grid.bucketHeight, + grid.bucketWidth, + grid.bucketHeight + ); + } + + return this; + }, + + /** + * Renders the list of Pair separations to the given Graphics instance. + * + * The debug renderer calls this method if the `showSeparations` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderSeparations + * @since 3.22.0 + * + * @param {MatterJS.Pair[]} pairs - An array of Matter Pairs to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * + * @return {this} This Matter World instance for method chaining. + */ + renderSeparations: function (pairs, graphics, lineColor) + { + graphics.lineStyle(1, lineColor, 1); + + for (var i = 0; i < pairs.length; i++) + { + var pair = pairs[i]; + + if (!pair.isActive) + { + continue; + } + + var collision = pair.collision; + var bodyA = collision.bodyA; + var bodyB = collision.bodyB; + var posA = bodyA.position; + var posB = bodyB.position; + var penetration = collision.penetration; + + var k = (!bodyA.isStatic && !bodyB.isStatic) ? 4 : 1; + + if (bodyB.isStatic) + { + k = 0; + } + + graphics.lineBetween( + posB.x, + posB.y, + posB.x - (penetration.x * k), + posB.y - (penetration.y * k) + ); + + k = (!bodyA.isStatic && !bodyB.isStatic) ? 4 : 1; + + if (bodyA.isStatic) + { + k = 0; + } + + graphics.lineBetween( + posA.x, + posA.y, + posA.x - (penetration.x * k), + posA.y - (penetration.y * k) + ); + } + + return this; + }, + + /** + * Renders the list of collision points and normals to the given Graphics instance. + * + * The debug renderer calls this method if the `showCollisions` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderCollisions + * @since 3.22.0 + * + * @param {MatterJS.Pair[]} pairs - An array of Matter Pairs to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * + * @return {this} This Matter World instance for method chaining. + */ + renderCollisions: function (pairs, graphics, lineColor) + { + graphics.lineStyle(1, lineColor, 0.5); + graphics.fillStyle(lineColor, 1); + + var i; + var pair; + + // Collision Positions + + for (i = 0; i < pairs.length; i++) + { + pair = pairs[i]; + + if (!pair.isActive) + { + continue; + } + + for (var j = 0; j < pair.activeContacts.length; j++) + { + var contact = pair.activeContacts[j]; + var vertex = contact.vertex; + + graphics.fillRect(vertex.x - 2, vertex.y - 2, 5, 5); + } + } + + // Collision Normals + + for (i = 0; i < pairs.length; i++) + { + pair = pairs[i]; + + if (!pair.isActive) + { + continue; + } + + var collision = pair.collision; + var contacts = pair.activeContacts; + + if (contacts.length > 0) + { + var normalPosX = contacts[0].vertex.x; + var normalPosY = contacts[0].vertex.y; + + if (contacts.length === 2) + { + normalPosX = (contacts[0].vertex.x + contacts[1].vertex.x) / 2; + normalPosY = (contacts[0].vertex.y + contacts[1].vertex.y) / 2; + } + + if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic) + { + graphics.lineBetween( + normalPosX - collision.normal.x * 8, + normalPosY - collision.normal.y * 8, + normalPosX, + normalPosY + ); + } + else + { + graphics.lineBetween( + normalPosX + collision.normal.x * 8, + normalPosY + collision.normal.y * 8, + normalPosX, + normalPosY + ); + } + } + } + + return this; + }, + + /** + * Renders the bounds of an array of Bodies to the given Graphics instance. + * + * If the body is a compound body, it will render the bounds for the parent compound. + * + * The debug renderer calls this method if the `showBounds` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderBodyBounds + * @since 3.22.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + */ + renderBodyBounds: function (bodies, graphics, lineColor, lineOpacity) + { + graphics.lineStyle(1, lineColor, lineOpacity); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + var bounds = body.bounds; + + if (bounds) + { + graphics.strokeRect( + bounds.min.x, + bounds.min.y, + bounds.max.x - bounds.min.x, + bounds.max.y - bounds.min.y + ); + } + else + { + var parts = body.parts; + + for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) + { + var part = parts[j]; + + graphics.strokeRect( + part.bounds.min.x, + part.bounds.min.y, + part.bounds.max.x - part.bounds.min.x, + part.bounds.max.y - part.bounds.min.y + ); + } + } + } + + return this; + }, + + /** + * Renders either all axes, or a single axis indicator, for an array of Bodies, to the given Graphics instance. + * + * The debug renderer calls this method if the `showAxes` or `showAngleIndicator` config values are set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderBodyAxes + * @since 3.22.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {boolean} showAxes - If `true` it will render all body axes. If `false` it will render a single axis indicator. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + */ + renderBodyAxes: function (bodies, graphics, showAxes, lineColor, lineOpacity) + { + graphics.lineStyle(1, lineColor, lineOpacity); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + var parts = body.parts; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + var part; + var j; + var k; + + if (showAxes) + { + for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) + { + part = parts[j]; + + for (k = 0; k < part.axes.length; k++) + { + var axis = part.axes[k]; + + graphics.lineBetween( + part.position.x, + part.position.y, + part.position.x + axis.x * 20, + part.position.y + axis.y * 20 + ); + } + } + } + else + { + for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) + { + part = parts[j]; + + for (k = 0; k < part.axes.length; k++) + { + graphics.lineBetween( + part.position.x, + part.position.y, + (part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2, + (part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2 + ); + } + } + } + } + + return this; + }, + + /** + * Renders a velocity indicator for an array of Bodies, to the given Graphics instance. + * + * The debug renderer calls this method if the `showVelocity` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderBodyVelocity + * @since 3.22.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + * @param {number} lineThickness - The line thickness. + */ + renderBodyVelocity: function (bodies, graphics, lineColor, lineOpacity, lineThickness) + { + graphics.lineStyle(lineThickness, lineColor, lineOpacity); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + graphics.lineBetween( + body.position.x, + body.position.y, + body.position.x + (body.position.x - body.positionPrev.x) * 2, + body.position.y + (body.position.y - body.positionPrev.y) * 2 + ); + } + + return this; + }, + + /** + * Renders the given array of Bodies to the debug graphics instance. + * + * Called automatically by the `postUpdate` method. + * + * @method Phaser.Physics.Matter.World#renderBodies + * @private + * @since 3.14.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + */ + renderBodies: function (bodies) + { + var graphics = this.debugGraphic; + + var config = this.debugConfig; + + var showBody = config.showBody; + var showStaticBody = config.showStaticBody; + var showSleeping = config.showSleeping; + var showInternalEdges = config.showInternalEdges; + var showConvexHulls = config.showConvexHulls; + + var renderFill = config.renderFill; + var renderLine = config.renderLine; + + var staticBodySleepOpacity = config.staticBodySleepOpacity; + var sleepFillColor = config.sleepFillColor; + var sleepLineColor = config.sleepLineColor; + + var hullColor = config.hullColor; + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + // 2) Don't show static bodies, OR + // 3) Don't show dynamic bodies + if ((!showStaticBody && body.isStatic) || (!showBody && !body.isStatic)) + { + continue; + } + + var lineColor = body.render.lineColor; + var lineOpacity = body.render.lineOpacity; + var lineThickness = body.render.lineThickness; + var fillColor = body.render.fillColor; + var fillOpacity = body.render.fillOpacity; + + if (showSleeping && body.isSleeping) + { + if (body.isStatic) + { + lineOpacity *= staticBodySleepOpacity; + fillOpacity *= staticBodySleepOpacity; + } + else + { + lineColor = sleepLineColor; + fillColor = sleepFillColor; + } + } + + if (!renderFill) + { + fillColor = null; + } + + if (!renderLine) + { + lineColor = null; + } + + this.renderBody(body, graphics, showInternalEdges, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity); + + var partsLength = body.parts.length; + + if (showConvexHulls && partsLength > 1) + { + this.renderConvexHull(body, graphics, hullColor, lineThickness); + } + } + }, + + /** + * Renders a single Matter Body to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Body to your own Graphics instance. + * + * If you don't wish to render a line around the body, set the `lineColor` parameter to `null`. + * Equally, if you don't wish to render a fill, set the `fillColor` parameter to `null`. + * + * @method Phaser.Physics.Matter.World#renderBody + * @since 3.22.0 + * + * @param {MatterJS.BodyType} body - The Matter Body to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {boolean} showInternalEdges - Render internal edges of the polygon? + * @param {number} [lineColor] - The line color. + * @param {number} [lineOpacity] - The line opacity, between 0 and 1. + * @param {number} [lineThickness=1] - The line thickness. + * @param {number} [fillColor] - The fill color. + * @param {number} [fillOpacity] - The fill opacity, between 0 and 1. + * + * @return {this} This Matter World instance for method chaining. + */ + renderBody: function (body, graphics, showInternalEdges, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) + { + if (lineColor === undefined) { lineColor = null; } + if (lineOpacity === undefined) { lineOpacity = null; } + if (lineThickness === undefined) { lineThickness = 1; } + if (fillColor === undefined) { fillColor = null; } + if (fillOpacity === undefined) { fillOpacity = null; } + + var config = this.debugConfig; + + var sensorFillColor = config.sensorFillColor; + var sensorLineColor = config.sensorLineColor; + + // Handle compound parts + var parts = body.parts; + var partsLength = parts.length; + + for (var k = (partsLength > 1) ? 1 : 0; k < partsLength; k++) + { + var part = parts[k]; + var render = part.render; + var opacity = render.opacity; + + if (!render.visible || opacity === 0 || (part.isSensor && !config.showSensors)) + { + continue; + } + + // Part polygon + var circleRadius = part.circleRadius; + + graphics.beginPath(); + + if (part.isSensor) + { + if (fillColor !== null) + { + graphics.fillStyle(sensorFillColor, fillOpacity * opacity); + } + + if (lineColor !== null) + { + graphics.lineStyle(lineThickness, sensorLineColor, lineOpacity * opacity); + } + } + else + { + if (fillColor !== null) + { + graphics.fillStyle(fillColor, fillOpacity * opacity); + } + + if (lineColor !== null) + { + graphics.lineStyle(lineThickness, lineColor, lineOpacity * opacity); + } + } + + if (circleRadius) + { + graphics.arc(part.position.x, part.position.y, circleRadius, 0, 2 * Math.PI); + } + else + { + var vertices = part.vertices; + var vertLength = vertices.length; + + graphics.moveTo(vertices[0].x, vertices[0].y); + + for (var j = 1; j < vertLength; j++) + { + var vert = vertices[j]; + + if (!vertices[j - 1].isInternal || showInternalEdges) + { + graphics.lineTo(vert.x, vert.y); + } + else + { + graphics.moveTo(vert.x, vert.y); + } + + if (j < vertLength && vert.isInternal && !showInternalEdges) + { + var nextIndex = (j + 1) % vertLength; + + graphics.moveTo(vertices[nextIndex].x, vertices[nextIndex].y); + } + } + + graphics.closePath(); + } + + if (fillColor !== null) + { + graphics.fillPath(); + } + + if (lineColor !== null) + { + graphics.strokePath(); + } + } + + if (config.showPositions && !body.isStatic) + { + var px = body.position.x; + var py = body.position.y; + var hs = Math.ceil(config.positionSize / 2); + + graphics.fillStyle(config.positionColor, 1); + graphics.fillRect(px - hs, py - hs, config.positionSize, config.positionSize); + } + + return this; + }, + + /** + * Renders the Convex Hull for a single Matter Body to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Body hull to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderConvexHull + * @since 3.22.0 + * + * @param {MatterJS.BodyType} body - The Matter Body to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} hullColor - The color used to render the hull. + * @param {number} [lineThickness=1] - The hull line thickness. + * + * @return {this} This Matter World instance for method chaining. + */ + renderConvexHull: function (body, graphics, hullColor, lineThickness) + { + if (lineThickness === undefined) { lineThickness = 1; } + + var parts = body.parts; + var partsLength = parts.length; + + // Render Convex Hulls + if (partsLength > 1) + { + var verts = body.vertices; + + graphics.lineStyle(lineThickness, hullColor); + + graphics.beginPath(); + + graphics.moveTo(verts[0].x, verts[0].y); + + for (var v = 1; v < verts.length; v++) + { + graphics.lineTo(verts[v].x, verts[v].y); + } + + graphics.lineTo(verts[0].x, verts[0].y); + + graphics.strokePath(); + } + + return this; + }, + + /** + * Renders all of the constraints in the world (unless they are specifically set to invisible). + * + * Called automatically by the `postUpdate` method. + * + * @method Phaser.Physics.Matter.World#renderJoints + * @private + * @since 3.14.0 + */ + renderJoints: function () + { + var graphics = this.debugGraphic; + + // Render constraints + var constraints = Composite.allConstraints(this.localWorld); + + for (var i = 0; i < constraints.length; i++) + { + var config = constraints[i].render; + + var lineColor = config.lineColor; + var lineOpacity = config.lineOpacity; + var lineThickness = config.lineThickness; + var pinSize = config.pinSize; + var anchorColor = config.anchorColor; + var anchorSize = config.anchorSize; + + this.renderConstraint(constraints[i], graphics, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize); + } + }, + + /** + * Renders a single Matter Constraint, such as a Pin or a Spring, to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Constraint to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderConstraint + * @since 3.22.0 + * + * @param {MatterJS.ConstraintType} constraint - The Matter Constraint to render. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + * @param {number} lineThickness - The line thickness. + * @param {number} pinSize - If this constraint is a pin, this sets the size of the pin circle. + * @param {number} anchorColor - The color used when rendering this constraints anchors. Set to `null` to not render anchors. + * @param {number} anchorSize - The size of the anchor circle, if this constraint has anchors and is rendering them. + * + * @return {this} This Matter World instance for method chaining. + */ + renderConstraint: function (constraint, graphics, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize) + { + var render = constraint.render; + + if (!render.visible || !constraint.pointA || !constraint.pointB) + { + return this; + } + + graphics.lineStyle(lineThickness, lineColor, lineOpacity); + + var bodyA = constraint.bodyA; + var bodyB = constraint.bodyB; + var start; + var end; + + if (bodyA) + { + start = Vector.add(bodyA.position, constraint.pointA); + } + else + { + start = constraint.pointA; + } + + if (render.type === 'pin') + { + graphics.strokeCircle(start.x, start.y, pinSize); + } + else + { + if (bodyB) + { + end = Vector.add(bodyB.position, constraint.pointB); + } + else + { + end = constraint.pointB; + } + + graphics.beginPath(); + graphics.moveTo(start.x, start.y); + + if (render.type === 'spring') + { + var delta = Vector.sub(end, start); + var normal = Vector.perp(Vector.normalise(delta)); + var coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)); + var offset; + + for (var j = 1; j < coils; j += 1) + { + offset = (j % 2 === 0) ? 1 : -1; + + graphics.lineTo( + start.x + delta.x * (j / coils) + normal.x * offset * 4, + start.y + delta.y * (j / coils) + normal.y * offset * 4 + ); + } + } + + graphics.lineTo(end.x, end.y); + } + + graphics.strokePath(); + + if (render.anchors && anchorSize > 0) + { + graphics.fillStyle(anchorColor); + graphics.fillCircle(start.x, start.y, anchorSize); + graphics.fillCircle(end.x, end.y, anchorSize); + } + + return this; + }, + + /** + * Resets the internal collision IDs that Matter.JS uses for Body collision groups. + * + * You should call this before destroying your game if you need to restart the game + * again on the same page, without first reloading the page. Or, if you wish to + * consistently destroy a Scene that contains Matter.js and then run it again + * later in the same game. + * + * @method Phaser.Physics.Matter.World#resetCollisionIDs + * @since 3.17.0 + */ + resetCollisionIDs: function () + { + Body._nextCollidingGroupId = 1; + Body._nextNonCollidingGroupId = -1; + Body._nextCategory = 0x0001; + + return this; + }, + + /** + * Will remove all Matter physics event listeners and clear the matter physics world, + * engine and any debug graphics, if any. + * + * @method Phaser.Physics.Matter.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + MatterEvents.off(this.engine); + + this.removeAllListeners(); + + MatterWorld.clear(this.localWorld, false); + + Engine.clear(this.engine); + + if (this.drawDebug) + { + this.debugGraphic.destroy(); + } + }, + + /** + * Will remove all Matter physics event listeners and clear the matter physics world, + * engine and any debug graphics, if any. + * + * After destroying the world it cannot be re-used again. + * + * @method Phaser.Physics.Matter.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + } + +}); + +module.exports = World; + + +/***/ }), +/* 512 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* @author Richard Davey +* @copyright 2020 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} +*/ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * A Global Plugin is installed just once into the Game owned Plugin Manager. + * It can listen for Game events and respond to them. + * + * @class BasePlugin + * @memberof Phaser.Plugins + * @constructor + * @since 3.8.0 + * + * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Plugin Manager. + */ +var BasePlugin = new Class({ + + initialize: + + function BasePlugin (pluginManager) + { + /** + * A handy reference to the Plugin Manager that is responsible for this plugin. + * Can be used as a route to gain access to game systems and events. + * + * @name Phaser.Plugins.BasePlugin#pluginManager + * @type {Phaser.Plugins.PluginManager} + * @protected + * @since 3.8.0 + */ + this.pluginManager = pluginManager; + + /** + * A reference to the Game instance this plugin is running under. + * + * @name Phaser.Plugins.BasePlugin#game + * @type {Phaser.Game} + * @protected + * @since 3.8.0 + */ + this.game = pluginManager.game; + }, + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is first instantiated. + * It will never be called again on this instance. + * In here you can set-up whatever you need for this plugin to run. + * If a plugin is set to automatically start then `BasePlugin.start` will be called immediately after this. + * On a Scene Plugin, this method is never called. Use {@link Phaser.Plugins.ScenePlugin#boot} instead. + * + * @method Phaser.Plugins.BasePlugin#init + * @since 3.8.0 + * + * @param {?any} [data] - A value specified by the user, if any, from the `data` property of the plugin's configuration object (if started at game boot) or passed in the PluginManager's `install` method (if started manually). + */ + init: function () + { + }, + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is started. + * If a plugin is stopped, and then started again, this will get called again. + * Typically called immediately after `BasePlugin.init`. + * On a Scene Plugin, this method is never called. + * + * @method Phaser.Plugins.BasePlugin#start + * @since 3.8.0 + */ + start: function () + { + // 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); + }, + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is stopped. + * The game code has requested that your plugin stop doing whatever it does. + * It is now considered as 'inactive' by the PluginManager. + * Handle that process here (i.e. stop listening for events, etc) + * If the plugin is started again then `BasePlugin.start` will be called again. + * On a Scene Plugin, this method is never called. + * + * @method Phaser.Plugins.BasePlugin#stop + * @since 3.8.0 + */ + stop: function () + { + }, + + /** + * Game instance has been destroyed. + * You must release everything in here, all references, all objects, free it all up. + * + * @method Phaser.Plugins.BasePlugin#destroy + * @since 3.8.0 + */ + destroy: function () + { + this.pluginManager = null; + this.game = null; + this.scene = null; + this.systems = null; + } + +}); + +module.exports = BasePlugin; + + +/***/ }), +/* 513 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * @function Phaser.Tilemaps.Components.ReplaceByIndex + * @private + * @since 3.0.0 + * + * @param {integer} findIndex - The index of the tile to search for. + * @param {integer} newIndex - The index of the tile to replace it with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var ReplaceByIndex = function (findIndex, newIndex, tileX, tileY, width, height, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + if (tiles[i] && tiles[i].index === findIndex) + { + tiles[i].index = newIndex; + } + } +}; + +module.exports = ReplaceByIndex; + + +/***/ }), +/* 514 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsInLayerBounds = __webpack_require__(115); + +/** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @function Phaser.Tilemaps.Components.HasTileAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ +var HasTileAt = function (tileX, tileY, layer) +{ + if (IsInLayerBounds(tileX, tileY, layer)) + { + var tile = layer.data[tileY][tileX]; + return (tile !== null && tile.index > -1); + } + else + { + return false; + } + +}; + +module.exports = HasTileAt; + + +/***/ }), +/* 515 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tile = __webpack_require__(80); +var IsInLayerBounds = __webpack_require__(115); +var CalculateFacesAt = __webpack_require__(245); + +/** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * @function Phaser.Tilemaps.Components.RemoveTileAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. + */ +var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, layer) +{ + if (replaceWithNull === undefined) { replaceWithNull = false; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + if (!IsInLayerBounds(tileX, tileY, layer)) + { + return null; + } + + var tile = layer.data[tileY][tileX]; + + if (!tile) + { + return null; + } + else + { + layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, tile.width, tile.height); + } + + // Recalculate faces only if the removed tile was a colliding tile + if (recalculateFaces && tile && tile.collides) + { + CalculateFacesAt(tileX, tileY, layer); + } + + return tile; +}; + +module.exports = RemoveTileAt; + + +/***/ }), +/* 516 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = __webpack_require__(34); +var Parse2DArray = __webpack_require__(248); +var ParseCSV = __webpack_require__(517); +var ParseJSONTiled = __webpack_require__(518); +var ParseWeltmeister = __webpack_require__(529); + +/** + * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format + * is found, returns `null`. When loading from CSV or a 2D array, you should specify the tileWidth & + * tileHeight. When parsing from a map from Tiled, the tileWidth & tileHeight will be pulled from + * the map data. + * + * @function Phaser.Tilemaps.Parsers.Parse + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {integer} mapFormat - See ../Formats.js. + * @param {(integer[][]|string|object)} data - 2D array, CSV string or Tiled JSON object. + * @param {integer} tileWidth - The width of a tile in pixels. Required for 2D array and CSV, but + * ignored for Tiled JSON. + * @param {integer} tileHeight - The height of a tile in pixels. Required for 2D array and CSV, but + * ignored for Tiled JSON. + * @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've 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. + */ +var Parse = function (name, mapFormat, data, tileWidth, tileHeight, insertNull) +{ + var newMap; + + switch (mapFormat) + { + case (Formats.ARRAY_2D): + newMap = Parse2DArray(name, data, tileWidth, tileHeight, insertNull); + break; + case (Formats.CSV): + newMap = ParseCSV(name, data, tileWidth, tileHeight, insertNull); + break; + case (Formats.TILED_JSON): + newMap = ParseJSONTiled(name, data, insertNull); + break; + case (Formats.WELTMEISTER): + newMap = ParseWeltmeister(name, data, insertNull); + break; + default: + console.warn('Unrecognized tilemap data format: ' + mapFormat); + newMap = null; + } + + return newMap; +}; + +module.exports = Parse; + + +/***/ }), +/* 517 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = __webpack_require__(34); +var Parse2DArray = __webpack_require__(248); + +/** + * Parses a CSV string of tile indexes into a new MapData object with a single layer. + * + * @function Phaser.Tilemaps.Parsers.ParseCSV + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {string} data - CSV string of tile indexes. + * @param {integer} tileWidth - The width of a tile in pixels. + * @param {integer} tileHeight - The height of a tile in pixels. + * @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've 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 resulting MapData object. + */ +var ParseCSV = function (name, data, tileWidth, tileHeight, insertNull) +{ + var array2D = data + .trim() + .split('\n') + .map(function (row) { return row.split(','); }); + + var map = Parse2DArray(name, array2D, tileWidth, tileHeight, insertNull); + map.format = Formats.CSV; + + return map; +}; + +module.exports = ParseCSV; + + +/***/ }), +/* 518 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = __webpack_require__(34); +var MapData = __webpack_require__(117); +var ParseTileLayers = __webpack_require__(519); +var ParseImageLayers = __webpack_require__(521); +var ParseTilesets = __webpack_require__(522); +var ParseObjectLayers = __webpack_require__(525); +var BuildTilesetIndex = __webpack_require__(527); +var AssignTileProperties = __webpack_require__(528); + +/** + * Parses a Tiled JSON object into a new MapData object. + * + * @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} json - The Tiled JSON object. + * @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've 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. + */ +var ParseJSONTiled = function (name, json, insertNull) +{ + if (json.orientation !== 'orthogonal') + { + console.warn('Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var mapData = new MapData({ + width: json.width, + height: json.height, + name: name, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Formats.TILED_JSON, + version: json.version, + properties: json.properties, + renderOrder: json.renderorder, + infinite: json.infinite + }); + + mapData.layers = ParseTileLayers(json, insertNull); + mapData.images = ParseImageLayers(json); + + var sets = ParseTilesets(json); + mapData.tilesets = sets.tilesets; + mapData.imageCollections = sets.imageCollections; + + mapData.objects = ParseObjectLayers(json); + + mapData.tiles = BuildTilesetIndex(mapData); + + AssignTileProperties(mapData); + + return mapData; +}; + +module.exports = ParseJSONTiled; + + +/***/ }), +/* 519 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Base64Decode = __webpack_require__(520); +var GetFastValue = __webpack_require__(1); +var LayerData = __webpack_require__(116); +var ParseGID = __webpack_require__(249); +var Tile = __webpack_require__(80); +var CreateGroupLayer = __webpack_require__(250); + +/** + * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseTileLayers + * @since 3.0.0 + * + * @param {object} json - The Tiled JSON object. + * @param {boolean} insertNull - Controls how empty tiles, tiles with an index of -1, in the map + * data are handled (see {@link Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled}). + * + * @return {Phaser.Tilemaps.LayerData[]} - An array of LayerData objects, one for each entry in + * json.layers with the type 'tilelayer'. + */ +var ParseTileLayers = function (json, insertNull) +{ + var infiniteMap = GetFastValue(json, 'infinite', false); + var tileLayers = []; + + // State inherited from a parent group + var groupStack = []; + var curGroupState = CreateGroupLayer(json); + + while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) + { + if (curGroupState.i >= curGroupState.layers.length) + { + // Ensure recursion stack is not empty first + if (groupStack.length < 1) + { + console.warn( + 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' + ); + break; + } + + // Return to previous recursive state + curGroupState = groupStack.pop(); + continue; + } + + var curl = curGroupState.layers[curGroupState.i]; + curGroupState.i++; + + if (curl.type !== 'tilelayer') + { + if (curl.type === 'group') + { + // Compute next state inherited from group + var nextGroupState = CreateGroupLayer(json, curl, curGroupState); + + // Preserve current state before recursing + groupStack.push(curGroupState); + curGroupState = nextGroupState; + } + + // Skip this layer OR 'recurse' (iterative style) into the group + continue; + } + + // Base64 decode data if necessary. NOTE: uncompressed base64 only. + if (curl.compression) + { + console.warn( + 'TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + + curl.name + '\'' + ); + continue; + } + else if (curl.encoding && curl.encoding === 'base64') + { + // Chunks for an infinite map + if (curl.chunks) + { + for (var i = 0; i < curl.chunks.length; i++) + { + curl.chunks[i].data = Base64Decode(curl.chunks[i].data); + } + } + + // Non-infinite map data + if (curl.data) + { + curl.data = Base64Decode(curl.data); + } + + delete curl.encoding; // Allow the same map to be parsed multiple times + } + + // 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. + + var layerData; + var gidInfo; + var tile; + var blankTile; + + var output = []; + var x = 0; + + if (infiniteMap) + { + var layerOffsetX = (GetFastValue(curl, 'startx', 0) + curl.x); + var layerOffsetY = (GetFastValue(curl, 'starty', 0) + curl.y); + layerData = new LayerData({ + name: (curGroupState.name + curl.name), + x: (curGroupState.x + GetFastValue(curl, 'offsetx', 0) + layerOffsetX * json.tilewidth), + y: (curGroupState.y + GetFastValue(curl, 'offsety', 0) + layerOffsetY * json.tileheight), + width: curl.width, + height: curl.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + alpha: (curGroupState.opacity * curl.opacity), + visible: (curGroupState.visible && curl.visible), + properties: GetFastValue(curl, 'properties', {}) + }); + + for (var c = 0; c < curl.height; c++) + { + output.push([ null ]); + + for (var j = 0; j < curl.width; j++) + { + output[c][j] = null; + } + } + + for (c = 0, len = curl.chunks.length; c < len; c++) + { + var chunk = curl.chunks[c]; + + var offsetX = (chunk.x - layerOffsetX); + var offsetY = (chunk.y - layerOffsetY); + + var y = 0; + + for (var t = 0, len2 = chunk.data.length; t < len2; t++) + { + var newOffsetX = x + offsetX; + var newOffsetY = y + offsetY; + + gidInfo = ParseGID(chunk.data[t]); + + // index, x, y, width, height + if (gidInfo.gid > 0) + { + tile = new Tile(layerData, gidInfo.gid, newOffsetX, newOffsetY, json.tilewidth, + json.tileheight); + + // Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal + // propeties into flipX, flipY and rotation + tile.rotation = gidInfo.rotation; + tile.flipX = gidInfo.flipped; + + output[newOffsetY][newOffsetX] = tile; + } + else + { + blankTile = insertNull + ? null + : new Tile(layerData, -1, newOffsetX, newOffsetY, json.tilewidth, json.tileheight); + + output[newOffsetY][newOffsetX] = blankTile; + } + + x++; + + if (x === chunk.width) + { + y++; + x = 0; + } + } + } + } + else + { + layerData = new LayerData({ + name: (curGroupState.name + curl.name), + x: (curGroupState.x + GetFastValue(curl, 'offsetx', 0) + curl.x), + y: (curGroupState.y + GetFastValue(curl, 'offsety', 0) + curl.y), + width: curl.width, + height: curl.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + alpha: (curGroupState.opacity * curl.opacity), + visible: (curGroupState.visible && curl.visible), + properties: GetFastValue(curl, 'properties', {}) + }); + + var row = []; + + // Loop through the data field in the JSON. + for (var k = 0, len = curl.data.length; k < len; k++) + { + gidInfo = ParseGID(curl.data[k]); + + // index, x, y, width, height + if (gidInfo.gid > 0) + { + tile = new Tile(layerData, gidInfo.gid, x, output.length, json.tilewidth, + json.tileheight); + + // Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal + // propeties into flipX, flipY and rotation + tile.rotation = gidInfo.rotation; + tile.flipX = gidInfo.flipped; + + row.push(tile); + } + else + { + blankTile = insertNull + ? null + : new Tile(layerData, -1, x, output.length, json.tilewidth, json.tileheight); + row.push(blankTile); + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + } + + layerData.data = output; + tileLayers.push(layerData); + } + + return tileLayers; +}; + +module.exports = ParseTileLayers; + + +/***/ }), +/* 520 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Decode base-64 encoded data, for example as exported by Tiled. + * + * @function Phaser.Tilemaps.Parsers.Tiled.Base64Decode + * @since 3.0.0 + * + * @param {object} data - Base-64 encoded data to decode. + * + * @return {array} Array containing the decoded bytes. + */ +var Base64Decode = function (data) +{ + var binaryString = window.atob(data); + var len = binaryString.length; + var bytes = new Array(len / 4); + + // Interpret binaryString as an array of bytes representing little-endian encoded uint32 values. + for (var i = 0; i < len; i += 4) + { + bytes[i / 4] = ( + binaryString.charCodeAt(i) | + binaryString.charCodeAt(i + 1) << 8 | + binaryString.charCodeAt(i + 2) << 16 | + binaryString.charCodeAt(i + 3) << 24 + ) >>> 0; + } + + return bytes; +}; + +module.exports = Base64Decode; + + +/***/ }), +/* 521 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); +var CreateGroupLayer = __webpack_require__(250); + +/** + * Parses a Tiled JSON object into an array of objects with details about the image layers. + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseImageLayers + * @since 3.0.0 + * + * @param {object} json - The Tiled JSON object. + * + * @return {array} Array of objects that include critical info about the map's image layers + */ +var ParseImageLayers = function (json) +{ + var images = []; + + // State inherited from a parent group + var groupStack = []; + var curGroupState = CreateGroupLayer(json); + + while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) + { + if (curGroupState.i >= curGroupState.layers.length) + { + // Ensure recursion stack is not empty first + if (groupStack.length < 1) + { + console.warn( + 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' + ); + break; + } + + // Return to previous recursive state + curGroupState = groupStack.pop(); + continue; + } + + // Get current layer and advance iterator + var curi = curGroupState.layers[curGroupState.i]; + curGroupState.i++; + + if (curi.type !== 'imagelayer') + { + if (curi.type === 'group') + { + // Compute next state inherited from group + var nextGroupState = CreateGroupLayer(json, curi, curGroupState); + + // Preserve current state before recursing + groupStack.push(curGroupState); + curGroupState = nextGroupState; + } + + // Skip this layer OR 'recurse' (iterative style) into the group + continue; + } + + var layerOffsetX = GetFastValue(curi, 'offsetx', 0) + GetFastValue(curi, 'startx', 0); + var layerOffsetY = GetFastValue(curi, 'offsety', 0) + GetFastValue(curi, 'starty', 0); + images.push({ + name: (curGroupState.name + curi.name), + image: curi.image, + x: (curGroupState.x + layerOffsetX + curi.x), + y: (curGroupState.y + layerOffsetY + curi.y), + alpha: (curGroupState.opacity * curi.opacity), + visible: (curGroupState.visible && curi.visible), + properties: GetFastValue(curi, 'properties', {}) + }); + } + + return images; +}; + +module.exports = ParseImageLayers; + + +/***/ }), +/* 522 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tileset = __webpack_require__(154); +var ImageCollection = __webpack_require__(523); +var ParseObject = __webpack_require__(251); + +/** + * Tilesets and Image Collections + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseTilesets + * @since 3.0.0 + * + * @param {object} json - [description] + * + * @return {object} [description] + */ +var ParseTilesets = function (json) +{ + var tilesets = []; + var imageCollections = []; + var lastSet = null; + var stringID; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser can\'t load external tilesets. Use the Embed Tileset button and then export the map again.'); + } + else if (set.image) + { + var newSet = new Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing); + + if (json.version > 1) + { + // Tiled 1.2+ + + if (Array.isArray(set.tiles)) + { + var tiles = {}; + var props = {}; + + for (var t = 0; t < set.tiles.length; t++) + { + var tile = set.tiles[t]; + + // Convert tileproperties + if (tile.properties) + { + var newPropData = {}; + + tile.properties.forEach(function (propData) + { + newPropData[propData['name']] = propData['value']; + }); + + props[tile.id] = newPropData; + } + + // Convert objectgroup + if (tile.objectgroup) + { + tiles[tile.id] = { objectgroup: tile.objectgroup }; + + if (tile.objectgroup.objects) + { + var parsedObjects2 = tile.objectgroup.objects.map( + function (obj) { return ParseObject(obj); } + ); + + tiles[tile.id].objectgroup.objects = parsedObjects2; + } + } + + // Copy animation data + if (tile.animation) + { + if (tiles.hasOwnProperty(tile.id)) + { + tiles[tile.id].animation = tile.animation; + } + else + { + tiles[tile.id] = { animation: tile.animation }; + } + } + } + + newSet.tileData = tiles; + newSet.tileProperties = props; + } + } + else + { + // Tiled 1 + + // Properties stored per-tile in object with string indexes starting at "0" + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // Object & terrain shapes stored per-tile in object with string indexes starting at "0" + if (set.tiles) + { + newSet.tileData = set.tiles; + + // Parse the objects into Phaser format to match handling of other Tiled objects + for (stringID in newSet.tileData) + { + var objectGroup = newSet.tileData[stringID].objectgroup; + if (objectGroup && objectGroup.objects) + { + var parsedObjects1 = objectGroup.objects.map( + function (obj) { return ParseObject(obj); } + ); + newSet.tileData[stringID].objectgroup.objects = parsedObjects1; + } + } + } + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else + { + var newCollection = new ImageCollection(set.name, set.firstgid, set.tilewidth, + set.tileheight, set.margin, set.spacing, set.properties); + + for (stringID in set.tiles) + { + var image = set.tiles[stringID].image; + var gid = set.firstgid + parseInt(stringID, 10); + newCollection.addImage(gid, image); + } + + imageCollections.push(newCollection); + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + return { tilesets: tilesets, imageCollections: imageCollections }; +}; + +module.exports = ParseTilesets; + + +/***/ }), +/* 523 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @classdesc + * An Image Collection is a special Tile Set containing multiple images, with no slicing into each image. + * + * Image Collections are normally created automatically when Tiled data is loaded. + * + * @class ImageCollection + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {string} name - The name of the image collection in the map data. + * @param {integer} firstgid - The first image index this image collection contains. + * @param {integer} [width=32] - Width of widest image (in pixels). + * @param {integer} [height=32] - Height of tallest image (in pixels). + * @param {integer} [margin=0] - The margin around all images in the collection (in pixels). + * @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). + * @param {object} [properties={}] - Custom Image Collection properties. + */ +var ImageCollection = new Class({ + + initialize: + + function ImageCollection (name, firstgid, width, height, margin, spacing, properties) + { + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * + * @name Phaser.Tilemaps.ImageCollection#name + * @type {string} + * @since 3.0.0 + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * + * @name Phaser.Tilemaps.ImageCollection#firstgid + * @type {integer} + * @since 3.0.0 + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * + * @name Phaser.Tilemaps.ImageCollection#imageWidth + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * + * @name Phaser.Tilemaps.ImageCollection#imageHeight + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.ImageCollection#imageMarge + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.ImageCollection#imageSpacing + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * + * @name Phaser.Tilemaps.ImageCollection#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * + * @name Phaser.Tilemaps.ImageCollection#images + * @type {array} + * @readonly + * @since 3.0.0 + */ + this.images = []; + + /** + * The total number of images in the image collection. + * + * @name Phaser.Tilemaps.ImageCollection#total + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.total = 0; + }, + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.Tilemaps.ImageCollection#containsImageIndex + * @since 3.0.0 + * + * @param {integer} imageIndex - The image index to search for. + * + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) + { + return (imageIndex >= this.firstgid && imageIndex < (this.firstgid + this.total)); + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.Tilemaps.ImageCollection#addImage + * @since 3.0.0 + * + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + * + * @return {Phaser.Tilemaps.ImageCollection} This ImageCollection object. + */ + addImage: function (gid, image) + { + this.images.push({ gid: gid, image: image }); + this.total++; + + return this; + } + +}); + +module.exports = ImageCollection; + + +/***/ }), +/* 524 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HasValue = __webpack_require__(91); + +/** + * Returns a new object that only contains the `keys` that were found on the object provided. + * If no `keys` are found, an empty object is returned. + * + * @function Phaser.Utils.Objects.Pick + * @since 3.18.0 + * + * @param {object} object - The object to pick the provided keys from. + * @param {array} keys - An array of properties to retrieve from the provided object. + * + * @return {object} A new object that only contains the `keys` that were found on the provided object. If no `keys` were found, an empty object will be returned. + */ +var Pick = function (object, keys) +{ + var obj = {}; + + for (var i = 0; i < keys.length; i++) + { + var key = keys[i]; + + if (HasValue(object, key)) + { + obj[key] = object[key]; + } + } + + return obj; +}; + +module.exports = Pick; + + +/***/ }), +/* 525 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); +var ParseObject = __webpack_require__(251); +var ObjectLayer = __webpack_require__(526); +var CreateGroupLayer = __webpack_require__(250); + +/** + * Parses a Tiled JSON object into an array of ObjectLayer objects. + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseObjectLayers + * @since 3.0.0 + * + * @param {object} json - The Tiled JSON object. + * + * @return {array} An array of all object layers in the tilemap as `ObjectLayer`s. + */ +var ParseObjectLayers = function (json) +{ + var objectLayers = []; + + // State inherited from a parent group + var groupStack = []; + var curGroupState = CreateGroupLayer(json); + + while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) + { + if (curGroupState.i >= curGroupState.layers.length) + { + // Ensure recursion stack is not empty first + if (groupStack.length < 1) + { + console.warn( + 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' + ); + break; + } + + // Return to previous recursive state + curGroupState = groupStack.pop(); + continue; + } + + // Get current layer and advance iterator + var curo = curGroupState.layers[curGroupState.i]; + curGroupState.i++; + + // Modify inherited properties + curo.opacity *= curGroupState.opacity; + curo.visible = curGroupState.visible && curo.visible; + + if (curo.type !== 'objectgroup') + { + if (curo.type === 'group') + { + // Compute next state inherited from group + var nextGroupState = CreateGroupLayer(json, curo, curGroupState); + + // Preserve current state before recursing + groupStack.push(curGroupState); + curGroupState = nextGroupState; + } + + // Skip this layer OR 'recurse' (iterative style) into the group + continue; + } + + curo.name = curGroupState.name + curo.name; + var offsetX = curGroupState.x + GetFastValue(curo, 'startx', 0) + GetFastValue(curo, 'offsetx', 0); + var offsetY = curGroupState.y + GetFastValue(curo, 'starty', 0) + GetFastValue(curo, 'offsety', 0); + + var objects = []; + for (var j = 0; j < curo.objects.length; j++) + { + var parsedObject = ParseObject(curo.objects[j], offsetX, offsetY); + + objects.push(parsedObject); + } + + var objectLayer = new ObjectLayer(curo); + objectLayer.objects = objects; + + objectLayers.push(objectLayer); + } + + return objectLayers; +}; + +module.exports = ParseObjectLayers; + + +/***/ }), +/* 526 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetFastValue = __webpack_require__(1); + +/** + * @classdesc + * A class for representing a Tiled object layer in a map. This mirrors the structure of a Tiled + * object layer, except: + * - "x" & "y" properties are ignored since these cannot be changed in Tiled. + * - "offsetx" & "offsety" are applied to the individual object coordinates directly, so they + * are ignored as well. + * - "draworder" is ignored. + * + * @class ObjectLayer + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Tilemaps.ObjectLayerConfig} [config] - The data for the layer from the Tiled JSON object. + */ +var ObjectLayer = new Class({ + + initialize: + + function ObjectLayer (config) + { + if (config === undefined) { config = {}; } + + /** + * The name of the Object Layer. + * + * @name Phaser.Tilemaps.ObjectLayer#name + * @type {string} + * @since 3.0.0 + */ + this.name = GetFastValue(config, 'name', 'object layer'); + + /** + * The opacity of the layer, between 0 and 1. + * + * @name Phaser.Tilemaps.ObjectLayer#opacity + * @type {number} + * @since 3.0.0 + */ + this.opacity = GetFastValue(config, 'opacity', 1); + + /** + * The custom properties defined on the Object Layer, keyed by their name. + * + * @name Phaser.Tilemaps.ObjectLayer#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = GetFastValue(config, 'properties', {}); + + /** + * The type of each custom property defined on the Object Layer, keyed by its name. + * + * @name Phaser.Tilemaps.ObjectLayer#propertyTypes + * @type {object} + * @since 3.0.0 + */ + this.propertyTypes = GetFastValue(config, 'propertytypes', {}); + + /** + * The type of the layer, which should be `objectgroup`. + * + * @name Phaser.Tilemaps.ObjectLayer#type + * @type {string} + * @since 3.0.0 + */ + this.type = GetFastValue(config, 'type', 'objectgroup'); + + /** + * Whether the layer is shown (`true`) or hidden (`false`). + * + * @name Phaser.Tilemaps.ObjectLayer#visible + * @type {boolean} + * @since 3.0.0 + */ + this.visible = GetFastValue(config, 'visible', true); + + /** + * 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 + */ + this.objects = GetFastValue(config, 'objects', []); + } + +}); + +module.exports = ObjectLayer; + + +/***/ }), +/* 527 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Master list of tiles -> x, y, index in tileset. + * + * @function Phaser.Tilemaps.Parsers.Tiled.BuildTilesetIndex + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.MapData} mapData - [description] + * + * @return {array} [description] + */ +var BuildTilesetIndex = function (mapData) +{ + var tiles = []; + + for (var i = 0; i < mapData.tilesets.length; i++) + { + var set = mapData.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + tiles[t] = [ x, y, i ]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + } + + return tiles; +}; + +module.exports = BuildTilesetIndex; + + +/***/ }), +/* 528 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = __webpack_require__(17); + +/** + * Copy properties from tileset to tiles. + * + * @function Phaser.Tilemaps.Parsers.Tiled.AssignTileProperties + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.MapData} mapData - [description] + */ +var AssignTileProperties = function (mapData) +{ + var layerData; + var tile; + var sid; + var set; + var row; + + // go through each of the map data layers + for (var i = 0; i < mapData.layers.length; i++) + { + layerData = mapData.layers[i]; + + set = null; + + // rows of tiles + for (var j = 0; j < layerData.data.length; j++) + { + row = layerData.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + sid = mapData.tiles[tile.index][2]; + set = mapData.tilesets[sid]; + + // Ensure that a tile's size matches its tileset + tile.width = set.tileWidth; + tile.height = set.tileHeight; + + // if that tile type has any properties, add them to the tile object + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Extend( + tile.properties, set.tileProperties[tile.index - set.firstgid] + ); + } + } + } + } +}; + +module.exports = AssignTileProperties; + + +/***/ }), +/* 529 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = __webpack_require__(34); +var MapData = __webpack_require__(117); +var ParseTileLayers = __webpack_require__(530); +var ParseTilesets = __webpack_require__(531); + +/** + * Parses a Weltmeister JSON object into a new MapData object. + * + * @function Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {object} json - The Weltmeister JSON object. + * @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've 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 {?object} [description] + */ +var ParseWeltmeister = function (name, json, insertNull) +{ + if (json.layer.length === 0) + { + console.warn('No layers found in the Weltmeister map: ' + name); + return null; + } + + var width = 0; + var height = 0; + + for (var i = 0; i < json.layer.length; i++) + { + if (json.layer[i].width > width) { width = json.layer[i].width; } + if (json.layer[i].height > height) { height = json.layer[i].height; } + } + + var mapData = new MapData({ + width: width, + height: height, + name: name, + tileWidth: json.layer[0].tilesize, + tileHeight: json.layer[0].tilesize, + format: Formats.WELTMEISTER + }); + + mapData.layers = ParseTileLayers(json, insertNull); + mapData.tilesets = ParseTilesets(json); + + return mapData; +}; + +module.exports = ParseWeltmeister; + + +/***/ }), +/* 530 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LayerData = __webpack_require__(116); +var Tile = __webpack_require__(80); + +/** + * [description] + * + * @function Phaser.Tilemaps.Parsers.Impact.ParseTileLayers + * @since 3.0.0 + * + * @param {object} json - [description] + * @param {boolean} insertNull - [description] + * + * @return {array} [description] + */ +var ParseTileLayers = function (json, insertNull) +{ + var tileLayers = []; + + for (var i = 0; i < json.layer.length; i++) + { + var layer = json.layer[i]; + + var layerData = new LayerData({ + name: layer.name, + width: layer.width, + height: layer.height, + tileWidth: layer.tilesize, + tileHeight: layer.tilesize, + visible: layer.visible === 1 + }); + + var row = []; + var tileGrid = []; + + // 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. + for (var y = 0; y < layer.data.length; y++) + { + for (var x = 0; x < layer.data[y].length; x++) + { + // In Weltmeister, 0 = no tile, but the Tilemap API expects -1 = no tile. + var index = layer.data[y][x] - 1; + + var tile; + + if (index > -1) + { + tile = new Tile(layerData, index, x, y, layer.tilesize, layer.tilesize); + } + else + { + tile = insertNull + ? null + : new Tile(layerData, -1, x, y, layer.tilesize, layer.tilesize); + } + + row.push(tile); + } + + tileGrid.push(row); + row = []; + } + + layerData.data = tileGrid; + + tileLayers.push(layerData); + } + + return tileLayers; +}; + +module.exports = ParseTileLayers; + + +/***/ }), +/* 531 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tileset = __webpack_require__(154); + +/** + * [description] + * + * @function Phaser.Tilemaps.Parsers.Impact.ParseTilesets + * @since 3.0.0 + * + * @param {object} json - [description] + * + * @return {array} [description] + */ +var ParseTilesets = function (json) +{ + var tilesets = []; + var tilesetsNames = []; + + for (var i = 0; i < json.layer.length; i++) + { + var layer = json.layer[i]; + + // A relative filepath to the source image (within Weltmeister) is used for the name + var tilesetName = layer.tilesetName; + + // Only add unique tilesets that have a valid name. Collision layers will have a blank name. + if (tilesetName !== '' && tilesetsNames.indexOf(tilesetName) === -1) + { + tilesetsNames.push(tilesetName); + + // 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. + tilesets.push(new Tileset(tilesetName, 0, layer.tilesize, layer.tilesize, 0, 0)); + } + } + + return tilesets; +}; + +module.exports = ParseTilesets; + + +/***/ }), +/* 532 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var DegToRad = __webpack_require__(40); +var DynamicTilemapLayer = __webpack_require__(533); +var Extend = __webpack_require__(17); +var Formats = __webpack_require__(34); +var LayerData = __webpack_require__(116); +var Rotate = __webpack_require__(349); +var SpliceOne = __webpack_require__(85); +var StaticTilemapLayer = __webpack_require__(534); +var Tile = __webpack_require__(80); +var TilemapComponents = __webpack_require__(150); +var Tileset = __webpack_require__(154); + +/** + * @callback TilemapFilterCallback + * + * @param {Phaser.GameObjects.GameObject} value - An object found in the filtered area. + * @param {number} index - The index of the object within the array. + * @param {Phaser.GameObjects.GameObject[]} array - An array of all the objects found. + * + * @return {Phaser.GameObjects.GameObject} The object. + */ + +/** + * @callback TilemapFindCallback + * + * @param {Phaser.GameObjects.GameObject} value - An object found. + * @param {number} index - The index of the object within the array. + * @param {Phaser.GameObjects.GameObject[]} array - An array of all the objects found. + * + * @return {boolean} `true` if the callback should be invoked, otherwise `false`. + */ + +/** + * @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 (StaticTilemapLayer or DynamicTilemapLayer), which are the display + * objects that actually render tiles. + * + * The Tilemap data 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 + * + * A Tilemap has handy methods for getting & manipulating the tiles within a layer. You can only + * use the methods that change tiles (e.g. removeTileAt) on a DynamicTilemapLayer. + * + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a + * StaticTilemapLayer or DynamicTilemapLayer may have its own unique tile size that overrides + * it. + * + * As of Phaser 3.21.0, if your tilemap includes layer groups (a feature of Tiled 1.2.0+) these + * will be traversed and the following properties will affect 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'. + * + * @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. + */ +var Tilemap = new Class({ + + initialize: + + function Tilemap (scene, mapData) + { + /** + * @name Phaser.Tilemaps.Tilemap#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The base width of a tile in pixels. Note that individual layers may have a different tile + * width. + * + * @name Phaser.Tilemaps.Tilemap#tileWidth + * @type {integer} + * @since 3.0.0 + */ + this.tileWidth = mapData.tileWidth; + + /** + * The base height of a tile in pixels. Note that individual layers may have a different + * tile height. + * + * @name Phaser.Tilemaps.Tilemap#tileHeight + * @type {integer} + * @since 3.0.0 + */ + this.tileHeight = mapData.tileHeight; + + /** + * The width of the map (in tiles). + * + * @name Phaser.Tilemaps.Tilemap#width + * @type {number} + * @since 3.0.0 + */ + this.width = mapData.width; + + /** + * The height of the map (in tiles). + * + * @name Phaser.Tilemaps.Tilemap#height + * @type {number} + * @since 3.0.0 + */ + this.height = mapData.height; + + /** + * The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + * + * @name Phaser.Tilemaps.Tilemap#orientation + * @type {string} + * @since 3.0.0 + */ + this.orientation = mapData.orientation; + + /** + * The render (draw) order of the map data (as specified in Tiled), usually 'right-down'. + * + * The draw orders are: + * + * right-down + * left-down + * right-up + * left-up + * + * This can be changed via the `setRenderOrder` method. + * + * @name Phaser.Tilemaps.Tilemap#renderOrder + * @type {string} + * @since 3.12.0 + */ + this.renderOrder = mapData.renderOrder; + + /** + * The format of the map data. + * + * @name Phaser.Tilemaps.Tilemap#format + * @type {number} + * @since 3.0.0 + */ + this.format = mapData.format; + + /** + * The version of the map data (as specified in Tiled, usually 1). + * + * @name Phaser.Tilemaps.Tilemap#version + * @type {number} + * @since 3.0.0 + */ + this.version = mapData.version; + + /** + * Map specific properties as specified in Tiled. + * + * @name Phaser.Tilemaps.Tilemap#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = mapData.properties; + + /** + * The width of the map in pixels based on width * tileWidth. + * + * @name Phaser.Tilemaps.Tilemap#widthInPixels + * @type {number} + * @since 3.0.0 + */ + this.widthInPixels = mapData.widthInPixels; + + /** + * The height of the map in pixels based on height * tileHeight. + * + * @name Phaser.Tilemaps.Tilemap#heightInPixels + * @type {number} + * @since 3.0.0 + */ + this.heightInPixels = mapData.heightInPixels; + + /** + * + * @name Phaser.Tilemaps.Tilemap#imageCollections + * @type {Phaser.Tilemaps.ImageCollection[]} + * @since 3.0.0 + */ + this.imageCollections = mapData.imageCollections; + + /** + * An array of Tiled Image Layers. + * + * @name Phaser.Tilemaps.Tilemap#images + * @type {array} + * @since 3.0.0 + */ + this.images = mapData.images; + + /** + * An array of Tilemap layer data. + * + * @name Phaser.Tilemaps.Tilemap#layers + * @type {Phaser.Tilemaps.LayerData[]} + * @since 3.0.0 + */ + this.layers = mapData.layers; + + /** + * An array of Tilesets used in the map. + * + * @name Phaser.Tilemaps.Tilemap#tilesets + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tilesets = mapData.tilesets; + + /** + * An array of ObjectLayer instances parsed from Tiled object layers. + * + * @name Phaser.Tilemaps.Tilemap#objects + * @type {Phaser.Tilemaps.ObjectLayer[]} + * @since 3.0.0 + */ + this.objects = mapData.objects; + + /** + * The index of the currently selected LayerData object. + * + * @name Phaser.Tilemaps.Tilemap#currentLayerIndex + * @type {integer} + * @since 3.0.0 + */ + this.currentLayerIndex = 0; + }, + + /** + * Sets the rendering (draw) order of the tiles in this map. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * Calling this method _after_ creating Static or Dynamic Tilemap Layers will **not** automatically + * update them to use the new render order. If you call this method after creating layers, use their + * own `setRenderOrder` methods to change them as needed. + * + * @method Phaser.Tilemaps.Tilemap#setRenderOrder + * @since 3.12.0 + * + * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + * + * @return {this} This Tilemap object. + */ + setRenderOrder: function (renderOrder) + { + var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; + + if (typeof renderOrder === 'number') + { + renderOrder = orders[renderOrder]; + } + + if (orders.indexOf(renderOrder) > -1) + { + this.renderOrder = renderOrder; + } + + return this; + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled + * editor. + * + * @method Phaser.Tilemaps.Tilemap#addTilesetImage + * @since 3.0.0 + * + * @param {string} tilesetName - The name of the tileset as specified in the map data. + * @param {string} [key] - The key of the Phaser.Cache image used for this tileset. If + * `undefined` or `null` it will look for an image with a key matching the tilesetName parameter. + * @param {integer} [tileWidth] - The width of the tile (in pixels) in the Tileset Image. If not + * given it will default to the map's tileWidth value, or the tileWidth specified in the Tiled + * JSON file. + * @param {integer} [tileHeight] - The height of the tiles (in pixels) in the Tileset Image. If + * not given it will default to the map's tileHeight value, or the tileHeight specified in the + * Tiled JSON file. + * @param {integer} [tileMargin] - The margin around the tiles in the sheet (in pixels). If not + * specified, it will default to 0 or the value specified in the Tiled JSON file. + * @param {integer} [tileSpacing] - The spacing between each the tile in the sheet (in pixels). + * If not specified, it will default to 0 or the value specified in the Tiled JSON file. + * @param {integer} [gid=0] - If adding multiple tilesets to a blank map, specify the starting + * GID this set will use here. + * + * @return {?Phaser.Tilemaps.Tileset} Returns the Tileset object that was created or updated, or null if it + * failed. + */ + addTilesetImage: function (tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) + { + if (tilesetName === undefined) { return null; } + if (key === undefined || key === null) { key = tilesetName; } + + if (!this.scene.sys.textures.exists(key)) + { + console.warn('Invalid Tileset Image: ' + key); + return null; + } + + var texture = this.scene.sys.textures.get(key); + + var index = this.getTilesetIndex(tilesetName); + + if (index === null && this.format === Formats.TILED_JSON) + { + console.warn('No data found for Tileset: ' + tilesetName); + return null; + } + + var tileset = this.tilesets[index]; + + if (tileset) + { + tileset.setTileSize(tileWidth, tileHeight); + tileset.setSpacing(tileMargin, tileSpacing); + tileset.setImage(texture); + + return tileset; + } + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + tileset = new Tileset(tilesetName, gid, tileWidth, tileHeight, tileMargin, tileSpacing); + + tileset.setImage(texture); + + this.tilesets.push(tileset); + + return tileset; + }, + + /** + * Turns the DynamicTilemapLayer associated with the given layer into a StaticTilemapLayer. If + * no layer specified, the map's current layer is used. This is useful if you want to manipulate + * a map at the start of a scene, but then make it non-manipulable and optimize it for speed. + * Note: the DynamicTilemapLayer passed in is destroyed, so make sure to store the value + * returned from this method if you want to manipulate the new StaticTilemapLayer. + * + * @method Phaser.Tilemaps.Tilemap#convertLayerToStatic + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer)} [layer] - The name of the layer from Tiled, the + * index of the layer in the map, or a DynamicTilemapLayer. + * + * @return {?Phaser.Tilemaps.StaticTilemapLayer} Returns the new layer that was created, or null if it + * failed. + */ + convertLayerToStatic: function (layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + var dynamicLayer = layer.tilemapLayer; + + if (!dynamicLayer || !(dynamicLayer instanceof DynamicTilemapLayer)) + { + return null; + } + + var staticLayer = new StaticTilemapLayer( + dynamicLayer.scene, + dynamicLayer.tilemap, + dynamicLayer.layerIndex, + dynamicLayer.tileset, + dynamicLayer.x, + dynamicLayer.y + ); + + this.scene.sys.displayList.add(staticLayer); + + dynamicLayer.destroy(); + + return staticLayer; + }, + + /** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * If no layer specified, the map's current layer is used. This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#copy + * @since 3.0.0 + * + * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} width - The width of the area to copy, in tiles, not pixels. + * @param {integer} height - The height of the area to copy, in tiles, not pixels. + * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. + * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + copy: function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'copy')) { return this; } + + if (layer !== null) + { + TilemapComponents.Copy( + srcTileX, srcTileY, + width, height, + destTileX, destTileY, + recalculateFaces, layer + ); + + return this; + } + else + { + return null; + } + }, + + /** + * Creates a new and empty DynamicTilemapLayer. The currently selected layer in the map is set to this new layer. + * + * @method Phaser.Tilemaps.Tilemap#createBlankDynamicLayer + * @since 3.0.0 + * + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The world x position where the top left of this layer will be placed. + * @param {number} [y=0] - The world y position where the top left of this layer will be placed. + * @param {integer} [width] - The width of the layer in tiles. If not specified, it will default to the map's width. + * @param {integer} [height] - The height of the layer in tiles. If not specified, it will default to the map's height. + * @param {integer} [tileWidth] - The width of the tiles the layer uses for calculations. If not specified, it will default to the map's tileWidth. + * @param {integer} [tileHeight] - The height of the tiles the layer uses for calculations. If not specified, it will default to the map's tileHeight. + * + * @return {?Phaser.Tilemaps.DynamicTilemapLayer} Returns the new layer that was created, or `null` if it failed. + */ + createBlankDynamicLayer: function (name, tileset, x, y, width, height, tileWidth, tileHeight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + var index = this.getLayerIndex(name); + + if (index !== null) + { + console.warn('Invalid Tilemap Layer ID: ' + name); + return null; + } + + var layerData = new LayerData({ + name: name, + tileWidth: tileWidth, + tileHeight: tileHeight, + width: width, + height: height + }); + + var row; + + for (var tileY = 0; tileY < height; tileY++) + { + row = []; + + for (var tileX = 0; tileX < width; tileX++) + { + row.push(new Tile(layerData, -1, tileX, tileY, tileWidth, tileHeight, this.tileWidth, this.tileHeight)); + } + + layerData.data.push(row); + } + + this.layers.push(layerData); + + this.currentLayerIndex = this.layers.length - 1; + + var dynamicLayer = new DynamicTilemapLayer(this.scene, this, this.currentLayerIndex, tileset, x, y); + + dynamicLayer.setRenderOrder(this.renderOrder); + + this.scene.sys.displayList.add(dynamicLayer); + + return dynamicLayer; + }, + + /** + * Creates a new DynamicTilemapLayer that renders the LayerData associated with the given + * `layerID`. The currently selected layer in the map is set to this new layer. + * + * The `layerID` is important. If you've created your map in Tiled then you can get this by + * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and + * look at the layers[].name value. Either way it must match. + * + * Unlike a static layer, a dynamic layer can be modified. See DynamicTilemapLayer for more + * information. + * + * @method Phaser.Tilemaps.Tilemap#createDynamicLayer + * @since 3.0.0 + * + * @param {(integer|string)} layerID - The layer array index value, or if a string is given, the layer name from Tiled. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * @param {number} [y=0] - The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * + * @return {?Phaser.Tilemaps.DynamicTilemapLayer} Returns the new layer was created, or null if it failed. + */ + createDynamicLayer: function (layerID, tileset, x, y) + { + var index = this.getLayerIndex(layerID); + + if (index === null) + { + console.warn('Invalid Tilemap Layer ID: ' + layerID); + + if (typeof layerID === 'string') + { + console.warn('Valid tilelayer names:\n\t' + this.getTileLayerNames().join(',\n\t')); + } + + return null; + } + + var layerData = this.layers[index]; + + // Check for an associated static or dynamic tilemap layer + if (layerData.tilemapLayer) + { + console.warn('Tilemap Layer ID already exists:' + layerID); + return null; + } + + this.currentLayerIndex = index; + + // Default the x/y position to match Tiled layer offset, if it exists. + + if (x === undefined) + { + x = layerData.x; + } + + if (y === undefined) + { + y = layerData.y; + } + + var layer = new DynamicTilemapLayer(this.scene, this, index, tileset, x, y); + + layer.setRenderOrder(this.renderOrder); + + this.scene.sys.displayList.add(layer); + + return layer; + }, + + /** + * Creates a Sprite for every object matching the given gid in the map data. All properties from + * the map data objectgroup are copied into the `spriteConfig`, so you can use this as an easy + * way to configure Sprite properties from within the map editor. For example giving an object a + * property of alpha: 0.5 in the map editor will duplicate that when the Sprite is created. + * + * Custom object properties not sharing names with the Sprite's own properties are copied to the + * Sprite's {@link Phaser.GameObjects.Sprite#data data store}. + * + * @method Phaser.Tilemaps.Tilemap#createFromObjects + * @since 3.0.0 + * + * @param {string} name - The name of the object layer (from Tiled) to create Sprites from. + * @param {(integer|string)} id - Either the id (object), gid (tile object) or name (object or + * tile object) from Tiled. Ids are unique in Tiled, but a gid is shared by all tile objects + * with the same graphic. The same name can be used on multiple objects. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param {Phaser.Scene} [scene=the scene the map is within] - The Scene to create the Sprites within. + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ + createFromObjects: function (name, id, spriteConfig, scene) + { + if (spriteConfig === undefined) { spriteConfig = {}; } + if (scene === undefined) { scene = this.scene; } + + var objectLayer = this.getObjectLayer(name); + + if (!objectLayer) + { + console.warn('Cannot create from object. Invalid objectgroup name given: ' + name); + + if (typeof layerID === 'string') + { + console.warn('Valid objectgroup names:\n\t' + this.getObjectLayerNames().join(',\n\t')); + } + + return null; + } + + var objects = objectLayer.objects; + var sprites = []; + + for (var i = 0; i < objects.length; i++) + { + var found = false; + var obj = objects[i]; + + if (obj.gid !== undefined && typeof id === 'number' && obj.gid === id || + obj.id !== undefined && typeof id === 'number' && obj.id === id || + obj.name !== undefined && typeof id === 'string' && obj.name === id) + { + found = true; + } + + if (found) + { + var config = Extend({}, spriteConfig, obj.properties); + + config.x = obj.x; + config.y = obj.y; + + var sprite = scene.make.sprite(config); + + sprite.name = obj.name; + + if (obj.width) { sprite.displayWidth = obj.width; } + if (obj.height) { sprite.displayHeight = obj.height; } + + // Origin is (0, 1) in Tiled, so find the offset that matches the Sprite's origin. + var offset = { + x: sprite.originX * sprite.displayWidth, + y: (sprite.originY - 1) * sprite.displayHeight + }; + + // If the object is rotated, then the origin offset also needs to be rotated. + if (obj.rotation) + { + var angle = DegToRad(obj.rotation); + Rotate(offset, angle); + sprite.rotation = angle; + } + + sprite.x += offset.x; + sprite.y += offset.y; + + if (obj.flippedHorizontal !== undefined || obj.flippedVertical !== undefined) + { + sprite.setFlip(obj.flippedHorizontal, obj.flippedVertical); + } + + if (!obj.visible) { sprite.visible = false; } + + for (var key in obj.properties) + { + if (sprite.hasOwnProperty(key)) + { + continue; + } + + sprite.setData(key, obj.properties[key]); + } + + sprites.push(sprite); + } + } + + return sprites; + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemaps.Tilemap#createFromTiles + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.GameObjects.Sprite[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + createFromTiles: function (indexes, replacements, spriteConfig, scene, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, layer); + }, + + /** + * Creates a new StaticTilemapLayer that renders the LayerData associated with the given + * `layerID`. The currently selected layer in the map is set to this new layer. + * + * The `layerID` is important. If you've created your map in Tiled then you can get this by + * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and + * look at the layers[].name value. Either way it must match. + * + * It's important to remember that a static layer cannot be modified. See StaticTilemapLayer for + * more information. + * + * @method Phaser.Tilemaps.Tilemap#createStaticLayer + * @since 3.0.0 + * + * @param {(integer|string)} layerID - The layer array index value, or if a string is given, the layer name from Tiled. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * @param {number} [y=0] - The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * + * @return {?Phaser.Tilemaps.StaticTilemapLayer} Returns the new layer was created, or null if it failed. + */ + createStaticLayer: function (layerID, tileset, x, y) + { + var index = this.getLayerIndex(layerID); + + if (index === null) + { + console.warn('Invalid Tilemap Layer ID: ' + layerID); + if (typeof layerID === 'string') + { + console.warn('Valid tilelayer names:\n\t' + this.getTileLayerNames().join(',\n\t')); + } + return null; + } + + var layerData = this.layers[index]; + + // Check for an associated static or dynamic tilemap layer + if (layerData.tilemapLayer) + { + console.warn('Tilemap Layer ID already exists:' + layerID); + return null; + } + + this.currentLayerIndex = index; + + // Default the x/y position to match Tiled layer offset, if it exists. + if (x === undefined && this.layers[index].x) { x = this.layers[index].x; } + if (y === undefined && this.layers[index].y) { y = this.layers[index].y; } + + var layer = new StaticTilemapLayer(this.scene, this, index, tileset, x, y); + + layer.setRenderOrder(this.renderOrder); + + this.scene.sys.displayList.add(layer); + + return layer; + }, + + /** + * Removes all layer data from this Tilemap and nulls the scene reference. This will destroy any + * StaticTilemapLayers or DynamicTilemapLayers that have been linked to LayerData. + * + * @method Phaser.Tilemaps.Tilemap#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllLayers(); + this.tilesets.length = 0; + this.objects.length = 0; + this.scene = undefined; + }, + + /** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * If no layer specified, the map's current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#fill + * @since 3.0.0 + * + * @param {integer} index - The tile index to fill the area with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + fill: function (index, tileX, tileY, width, height, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + if (this._isStaticCall(layer, 'fill')) { return this; } + + TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, layer); + + return this; + }, + + /** + * For each object in the given object layer, run the given filter callback function. Any + * objects that pass the filter test (i.e. where the callback returns true) will returned as a + * new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @method Phaser.Tilemaps.Tilemap#filterObjects + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.ObjectLayer|string)} objectLayer - The name of an object layer (from Tiled) or an ObjectLayer instance. + * @param {TilemapFilterCallback} callback - The callback. Each object in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * + * @return {?Phaser.GameObjects.GameObject[]} An array of object that match the search, or null if the objectLayer given was invalid. + */ + filterObjects: function (objectLayer, callback, context) + { + if (typeof objectLayer === 'string') + { + var name = objectLayer; + + objectLayer = this.getObjectLayer(objectLayer); + + if (!objectLayer) + { + console.warn('No object layer found with the name: ' + name); + return null; + } + } + + return objectLayer.objects.filter(callback, context); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#filterTiles + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, layer); + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#findByIndex + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tiles, or null if the layer given was invalid. + */ + findByIndex: function (findIndex, skip, reverse, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.FindByIndex(findIndex, skip, reverse, layer); + }, + + /** + * Find the first object in the given object layer that satisfies the provided testing function. + * I.e. finds the first object for which `callback` returns true. Similar to + * Array.prototype.find in vanilla JS. + * + * @method Phaser.Tilemaps.Tilemap#findObject + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.ObjectLayer|string)} objectLayer - The name of an object layer (from Tiled) or an ObjectLayer instance. + * @param {TilemapFindCallback} callback - The callback. Each object in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * + * @return {?Phaser.GameObjects.GameObject} An object that matches the search, or null if no object found. + */ + findObject: function (objectLayer, callback, context) + { + if (typeof objectLayer === 'string') + { + var name = objectLayer; + + objectLayer = this.getObjectLayer(objectLayer); + + if (!objectLayer) + { + console.warn('No object layer found with the name: ' + name); + return null; + } + } + + return objectLayer.objects.find(callback, context) || null; + }, + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#findTile + * @since 3.0.0 + * + * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The Tile layer to run the search on. If not provided will use the current layer. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tiles, or null if the layer given was invalid. + */ + findTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#forEachTile + * @since 3.0.0 + * + * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The Tile layer to run the search on. If not provided will use the current layer. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, layer); + + return this; + }, + + /** + * 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 {integer} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) + { + return this.getIndex(this.images, name); + }, + + /** + * Return a list of all valid imagelayer names loaded in this Tilemap. + * + * @method Phaser.Tilemaps.Tilemap#getImageLayerNames + * @since 3.21.0 + * + * @return {string[]} Array of valid imagelayer names / IDs loaded into this Tilemap. + */ + getImageLayerNames: function () + { + if (!this.images || !Array.isArray(this.images)) + { + return []; + } + + return this.images.map(function (image) + { + return image.name; + }); + }, + + /** + * Internally used. Returns the index of the object in one of the Tilemaps arrays whose name + * property matches the given `name`. + * + * @method Phaser.Tilemaps.Tilemap#getIndex + * @since 3.0.0 + * + * @param {array} location - The Tilemap array to search. + * @param {string} name - The name of the array element to get. + * + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) + { + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + }, + + /** + * Gets the LayerData from this.layers that is associated with `layer`, or null if an invalid + * `layer` is given. + * + * @method Phaser.Tilemaps.Tilemap#getLayer + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the maps current layer index. + * + * @return {Phaser.Tilemaps.LayerData} The corresponding LayerData within this.layers. + */ + getLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + return (index !== null) ? this.layers[index] : null; + }, + + /** + * Gets the ObjectLayer from this.objects that has the given `name`, or null if no ObjectLayer + * is found with that name. + * + * @method Phaser.Tilemaps.Tilemap#getObjectLayer + * @since 3.0.0 + * + * @param {string} [name] - The name of the object layer from Tiled. + * + * @return {?Phaser.Tilemaps.ObjectLayer} The corresponding ObjectLayer within this.objects or null. + */ + getObjectLayer: function (name) + { + var index = this.getIndex(this.objects, name); + + return (index !== null) ? this.objects[index] : null; + }, + + /** + * Return a list of all valid objectgroup names loaded in this Tilemap. + * + * @method Phaser.Tilemaps.Tilemap#getObjectLayerNames + * @since 3.21.0 + * + * @return {string[]} Array of valid objectgroup names / IDs loaded into this Tilemap. + */ + getObjectLayerNames: function () + { + if (!this.objects || !Array.isArray(this.objects)) + { + return []; + } + + return this.objects.map(function (object) + { + return object.name; + }); + }, + + /** + * Gets the LayerData index of the given `layer` within this.layers, or null if an invalid + * `layer` is given. + * + * @method Phaser.Tilemaps.Tilemap#getLayerIndex + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + * + * @return {integer} The LayerData index within this.layers. + */ + getLayerIndex: function (layer) + { + if (layer === undefined) + { + return this.currentLayerIndex; + } + else if (typeof layer === 'string') + { + return this.getLayerIndexByName(layer); + } + else if (typeof layer === 'number' && layer < this.layers.length) + { + return layer; + } + else if (layer instanceof StaticTilemapLayer || layer instanceof DynamicTilemapLayer) + { + return layer.layerIndex; + } + else + { + return null; + } + }, + + /** + * Gets the index of the LayerData within this.layers that has the given `name`, or null if an + * invalid `name` is given. + * + * @method Phaser.Tilemaps.Tilemap#getLayerIndexByName + * @since 3.0.0 + * + * @param {string} name - The name of the layer to get. + * + * @return {integer} The LayerData index within this.layers. + */ + getLayerIndexByName: function (name) + { + return this.getIndex(this.layers, name); + }, + + /** + * Gets a tile at the given tile coordinates from the given layer. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + getTileAt: function (tileX, tileY, nonNull, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTileAt(tileX, tileY, nonNull, layer); + }, + + /** + * Gets a tile at the given world coordinates from the given layer. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + getTileAtWorldXY: function (worldX, worldY, nonNull, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, layer); + }, + + /** + * Return a list of all valid tilelayer names loaded in this Tilemap. + * + * @method Phaser.Tilemaps.Tilemap#getTileLayerNames + * @since 3.21.0 + * + * @return {string[]} Array of valid tilelayer names / IDs loaded into this Tilemap. + */ + getTileLayerNames: function () + { + if (!this.layers || !Array.isArray(this.layers)) + { + return []; + } + + return this.layers.map(function (layer) + { + return layer.name; + }); + }, + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTilesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + getTilesWithin: function (tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + }, + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTilesWithinShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + getTilesWithinShape: function (shape, filteringOptions, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, layer); + }, + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTilesWithinWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The world x coordinate for the top-left of the area. + * @param {number} worldY - The world y coordinate for the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, layer); + }, + + /** + * Gets the Tileset that has the given `name`, or null if an invalid `name` is given. + * + * @method Phaser.Tilemaps.Tilemap#getTileset + * @since 3.14.0 + * + * @param {string} name - The name of the Tileset to get. + * + * @return {?Phaser.Tilemaps.Tileset} The Tileset, or `null` if no matching named tileset was found. + */ + getTileset: function (name) + { + var index = this.getIndex(this.tilesets, name); + + return (index !== null) ? this.tilesets[index] : null; + }, + + /** + * Gets the index of the Tileset within this.tilesets that has the given `name`, or null if an + * invalid `name` is given. + * + * @method Phaser.Tilemaps.Tilemap#getTilesetIndex + * @since 3.0.0 + * + * @param {string} name - The name of the Tileset to get. + * + * @return {integer} The Tileset index within this.tilesets. + */ + getTilesetIndex: function (name) + { + return this.getIndex(this.tilesets, name); + }, + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#hasTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ + hasTileAt: function (tileX, tileY, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.HasTileAt(tileX, tileY, layer); + }, + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#hasTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ + hasTileAtWorldXY: function (worldX, worldY, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, layer); + }, + + /** + * The LayerData object that is currently selected in the map. You can set this property using + * any type supported by setLayer. + * + * @name Phaser.Tilemaps.Tilemap#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + layer: { + get: function () + { + return this.layers[this.currentLayerIndex]; + }, + + set: function (layer) + { + this.setLayer(layer); + } + }, + + /** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * If no layer specified, the maps current layer is used. + * + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#putTileAt + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid or the coordinates were out of bounds. + */ + putTileAt: function (tile, tileX, tileY, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'putTileAt')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, layer); + }, + + /** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * If no layer specified, the maps current layer is used. This + * cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#putTileAtWorldXY + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + putTileAtWorldXY: function (tile, worldX, worldY, recalculateFaces, camera, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'putTileAtWorldXY')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, layer); + }, + + /** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#putTilesAt + * @since 3.0.0 + * + * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + putTilesAt: function (tilesArray, tileX, tileY, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'putTilesAt')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, layer); + + return this; + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#randomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + randomize: function (tileX, tileY, width, height, indexes, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'randomize')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.Randomize(tileX, tileY, width, height, indexes, layer); + + return this; + }, + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#calculateFacesAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + calculateFacesAt: function (tileX, tileY, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.CalculateFacesAt(tileX, tileY, layer); + + return this; + }, + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#calculateFacesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + calculateFacesWithin: function (tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Removes the given TilemapLayer from this Tilemap without destroying it. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#removeLayer + * @since 3.17.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to be removed. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + removeLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + if (index !== null) + { + SpliceOne(this.layers, index); + for (var i = index; i < this.layers.length; i++) + { + if (this.layers[i].tilemapLayer) + { + this.layers[i].tilemapLayer.layerIndex--; + } + } + + if (this.currentLayerIndex === index) + { + this.currentLayerIndex = 0; + } + + return this; + } + else + { + return null; + } + }, + + /** + * Destroys the given TilemapLayer and removes it from this Tilemap. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#destroyLayer + * @since 3.17.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to be destroyed. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + destroyLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + if (index !== null) + { + layer = this.layers[index]; + + layer.destroy(); + + SpliceOne(this.layers, index); + + if (this.currentLayerIndex === index) + { + this.currentLayerIndex = 0; + } + + return this; + } + else + { + return null; + } + }, + + /** + * Removes all layers from this Tilemap and destroys any associated StaticTilemapLayers or + * DynamicTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#removeAllLayers + * @since 3.0.0 + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + removeAllLayers: function () + { + var layers = this.layers; + + // Destroy any StaticTilemapLayers or DynamicTilemapLayers that are stored in LayerData + for (var i = 0; i < layers.length; i++) + { + if (layers[i].tilemapLayer) + { + layers[i].tilemapLayer.destroy(false); + } + } + + layers.length = 0; + + this.currentLayerIndex = 0; + + return this; + }, + + /** + * Removes the given Tile, or an array of Tiles, from the layer to which they belong, + * and optionally recalculates the collision information. + * + * This cannot be applied to Tiles that belong to Static Tilemap Layers. + * + * @method Phaser.Tilemaps.Tilemap#removeTile + * @since 3.17.0 + * + * @param {(Phaser.Tilemaps.Tile|Phaser.Tilemaps.Tile[])} tiles - The Tile to remove, or an array of Tiles. + * @param {integer} [replaceIndex=-1] - After removing the Tile, insert a brand new Tile into its location with the given index. Leave as -1 to just remove the tile. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.Tile[]} Returns an array of Tiles that were removed. + */ + removeTile: function (tiles, replaceIndex, recalculateFaces) + { + if (replaceIndex === undefined) { replaceIndex = -1; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + var removed = []; + + if (!Array.isArray(tiles)) + { + tiles = [ tiles ]; + } + + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + removed.push(this.removeTileAt(tile.x, tile.y, true, recalculateFaces, tile.tilemapLayer)); + + if (replaceIndex > -1) + { + this.putTileAt(replaceIndex, tile.x, tile.y, recalculateFaces, tile.tilemapLayer); + } + } + + return removed; + }, + + /** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#removeTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns the Tile that was removed, or null if the layer given was invalid. + */ + removeTileAt: function (tileX, tileY, replaceWithNull, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'removeTileAt')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); + }, + + /** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#removeTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + removeTileAtWorldXY: function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'removeTileAtWorldXY')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, layer); + }, + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#renderDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + renderDebug: function (graphics, styleConfig, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.RenderDebug(graphics, styleConfig, layer); + + return this; + }, + + /** + * Draws a debug representation of all layers within this Tilemap to the given Graphics object. + * + * This is helpful when you want to get a quick idea of which of your tiles are colliding and which + * have interesting faces. The tiles are drawn starting at (0, 0) in the Graphics, allowing you to + * place the debug representation wherever you want on the screen. + * + * @method Phaser.Tilemaps.Tilemap#renderDebugFull + * @since 3.17.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + renderDebugFull: function (graphics, styleConfig) + { + var layers = this.layers; + + // Destroy any StaticTilemapLayers or DynamicTilemapLayers that are stored in LayerData + for (var i = 0; i < layers.length; i++) + { + TilemapComponents.RenderDebug(graphics, styleConfig, layers[i]); + } + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#replaceByIndex + * @since 3.0.0 + * + * @param {integer} findIndex - The index of the tile to search for. + * @param {integer} newIndex - The index of the tile to replace it with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + replaceByIndex: function (findIndex, newIndex, tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'replaceByIndex')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollision + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to false if no tiles have been placed for significant performance boost. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollision: function (indexes, collides, recalculateFaces, layer, updateLayer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollision(indexes, collides, recalculateFaces, layer, updateLayer); + + return this; + }, + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionBetween + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionBetween: function (start, stop, collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionByProperty + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionByProperty: function (properties, collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionByExclusion + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionByExclusion: function (indexes, collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking each tile's collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tile's collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionFromCollisionGroup + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionFromCollisionGroup: function (collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setTileIndexCallback + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, layer); + + return this; + }, + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setTileLocationCallback + * @since 3.0.0 + * + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} [callbackContext] - The context under which the callback is called. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, layer); + + return this; + }, + + /** + * Sets the current layer to the LayerData associated with `layer`. + * + * @method Phaser.Tilemaps.Tilemap#setLayer + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + setLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + if (index !== null) + { + this.currentLayerIndex = index; + } + + return this; + }, + + /** + * Sets the base tile size for the map. Note: this does not necessarily match the tileWidth and + * tileHeight for all layers. This also updates the base size on all tiles across all layers. + * + * @method Phaser.Tilemaps.Tilemap#setBaseTileSize + * @since 3.0.0 + * + * @param {integer} tileWidth - The width of the tiles the map uses for calculations. + * @param {integer} tileHeight - The height of the tiles the map uses for calculations. + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + setBaseTileSize: function (tileWidth, tileHeight) + { + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + // Update the base tile size on all layers & tiles + for (var i = 0; i < this.layers.length; i++) + { + this.layers[i].baseTileWidth = tileWidth; + this.layers[i].baseTileHeight = tileHeight; + + var mapData = this.layers[i].data; + var mapWidth = this.layers[i].width; + var mapHeight = this.layers[i].height; + + for (var row = 0; row < mapHeight; row++) + { + for (var col = 0; col < mapWidth; col++) + { + var tile = mapData[row][col]; + + if (tile !== null) + { + tile.setSize(undefined, undefined, tileWidth, tileHeight); + } + } + } + } + + return this; + }, + + /** + * Sets the tile size for a specific `layer`. Note: this does not necessarily match the map's + * tileWidth and tileHeight for all layers. This will set the tile size for the layer and any + * tiles the layer has. + * + * @method Phaser.Tilemaps.Tilemap#setLayerTileSize + * @since 3.0.0 + * + * @param {integer} tileWidth - The width of the tiles (in pixels) in the layer. + * @param {integer} tileHeight - The height of the tiles (in pixels) in the layer. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + setLayerTileSize: function (tileWidth, tileHeight, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return this; } + + layer.tileWidth = tileWidth; + layer.tileHeight = tileHeight; + + var mapData = layer.data; + var mapWidth = layer.width; + var mapHeight = layer.height; + + for (var row = 0; row < mapHeight; row++) + { + for (var col = 0; col < mapWidth; col++) + { + var tile = mapData[row][col]; + + if (tile !== null) + { + tile.setSize(tileWidth, tileHeight); + } + } + } + + return this; + }, + + /** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#shuffle + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + shuffle: function (tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'shuffle')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.Shuffle(tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#swapByIndex + * @since 3.0.0 + * + * @param {integer} tileA - First tile index. + * @param {integer} tileB - Second tile index. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + swapByIndex: function (indexA, indexB, tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'swapByIndex')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#tileToWorldX + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + tileToWorldX: function (tileX, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.TileToWorldX(tileX, camera, layer); + }, + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#tileToWorldY + * @since 3.0.0 + * + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer + * to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + tileToWorldY: function (tileX, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.TileToWorldY(tileX, camera, layer); + }, + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#tileToWorldXY + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. + */ + tileToWorldXY: function (tileX, tileY, point, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, layer); + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * If no layer specified, the map's current layer is used. This + * cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#weightedRandomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + weightedRandomize: function (tileX, tileY, width, height, weightedIndexes, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'weightedRandomize')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, layer); + + return this; + }, + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#worldToTileX + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer + * to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + worldToTileX: function (worldX, snapToFloor, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, layer); + }, + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#worldToTileY + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + worldToTileY: function (worldY, snapToFloor, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, layer); + }, + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#worldToTileXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. + */ + worldToTileXY: function (worldX, worldY, snapToFloor, point, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); + }, + + /** + * Used internally to check if a layer is static and prints out a warning. + * + * @method Phaser.Tilemaps.Tilemap#_isStaticCall + * @private + * @since 3.0.0 + * + * @return {boolean} + */ + _isStaticCall: function (layer, functionName) + { + if (layer.tilemapLayer instanceof StaticTilemapLayer) + { + console.warn(functionName + ': You cannot change the tiles in a static tilemap layer'); + return true; + } + else + { + return false; + } + } + +}); + +module.exports = Tilemap; + + +/***/ }), +/* 533 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var DynamicTilemapLayerRender = __webpack_require__(1421); +var GameObject = __webpack_require__(14); +var TilemapComponents = __webpack_require__(150); + +/** + * @classdesc + * A Dynamic Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination + * with one, or more, Tilesets. + * + * A Dynamic Tilemap Layer trades some speed for being able to apply powerful effects. Unlike a + * Static Tilemap Layer, you can apply per-tile effects like tint or alpha, and you can change the + * tiles in a DynamicTilemapLayer. + * + * Use this over a Static Tilemap Layer when you need those features. + * + * @class DynamicTilemapLayer + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.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.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. + * @param {Phaser.Tilemaps.Tilemap} tilemap - The Tilemap this layer is a part of. + * @param {integer} layerIndex - The index of the LayerData associated with this layer. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The world x position where the top left of this layer will be placed. + * @param {number} [y=0] - The world y position where the top left of this layer will be placed. + */ +var DynamicTilemapLayer = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Origin, + Components.Pipeline, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + DynamicTilemapLayerRender + ], + + initialize: + + function DynamicTilemapLayer (scene, tilemap, layerIndex, tileset, x, y) + { + GameObject.call(this, scene, 'DynamicTilemapLayer'); + + /** + * Used internally by physics system to perform fast type checks. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#isTilemap + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isTilemap = true; + + /** + * The Tilemap that this layer is a part of. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tilemap + * @type {Phaser.Tilemaps.Tilemap} + * @since 3.0.0 + */ + this.tilemap = tilemap; + + /** + * The index of the LayerData associated with this layer. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#layerIndex + * @type {integer} + * @since 3.0.0 + */ + this.layerIndex = layerIndex; + + /** + * The LayerData associated with this layer. LayerData can only be associated with one + * tilemap layer. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + this.layer = tilemap.layers[layerIndex]; + + // Link the LayerData with this static tilemap layer + this.layer.tilemapLayer = this; + + /** + * The Tileset/s associated with this layer. + * + * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tileset + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tileset = []; + + /** + * Used internally with the canvas render. This holds the tiles that are visible within the + * camera. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#culledTiles + * @type {array} + * @since 3.0.0 + */ + this.culledTiles = []; + + /** + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this, and toggling this flag allows + * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#skipCull + * @type {boolean} + * @since 3.11.0 + */ + this.skipCull = false; + + /** + * The total number of tiles drawn by the renderer in the last frame. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tilesDrawn + * @type {integer} + * @readonly + * @since 3.11.0 + */ + this.tilesDrawn = 0; + + /** + * The total number of tiles in this layer. Updated every frame. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tilesTotal + * @type {integer} + * @readonly + * @since 3.11.0 + */ + this.tilesTotal = this.layer.width * this.layer.height; + + /** + * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#cullPaddingX + * @type {integer} + * @default 1 + * @since 3.11.0 + */ + this.cullPaddingX = 1; + + /** + * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#cullPaddingY + * @type {integer} + * @default 1 + * @since 3.11.0 + */ + this.cullPaddingY = 1; + + /** + * The callback that is invoked when the tiles are culled. + * + * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. + * + * It will be sent 3 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. + * + * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#cullCallback + * @type {function} + * @since 3.11.0 + */ + this.cullCallback = TilemapComponents.CullTiles; + + /** + * The rendering (draw) order of the tiles in this layer. + * + * The default is 0 which is 'right-down', meaning it will draw the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * This can be changed via the `setRenderOrder` method. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#_renderOrder + * @type {integer} + * @default 0 + * @private + * @since 3.12.0 + */ + this._renderOrder = 0; + + /** + * An array holding the mapping between the tile indexes and the tileset they belong to. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#gidMap + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.14.0 + */ + this.gidMap = []; + + this.setTilesets(tileset); + this.setAlpha(this.layer.alpha); + this.setPosition(x, y); + this.setOrigin(); + this.setSize(tilemap.tileWidth * this.layer.width, tilemap.tileHeight * this.layer.height); + + this.initPipeline('TextureTintPipeline'); + }, + + /** + * Populates the internal `tileset` array with the Tileset references this Layer requires for rendering. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setTilesets + * @private + * @since 3.14.0 + * + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + */ + setTilesets: function (tilesets) + { + var gidMap = []; + var setList = []; + var map = this.tilemap; + + if (!Array.isArray(tilesets)) + { + tilesets = [ tilesets ]; + } + + for (var i = 0; i < tilesets.length; i++) + { + var tileset = tilesets[i]; + + if (typeof tileset === 'string') + { + tileset = map.getTileset(tileset); + } + + if (tileset) + { + setList.push(tileset); + + var s = tileset.firstgid; + + for (var t = 0; t < tileset.total; t++) + { + gidMap[s + t] = tileset; + } + } + } + + this.gidMap = gidMap; + this.tileset = setList; + }, + + /** + * Sets the rendering (draw) order of the tiles in this layer. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setRenderOrder + * @since 3.12.0 + * + * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + * + * @return {this} This Tilemap Layer object. + */ + setRenderOrder: function (renderOrder) + { + var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; + + if (typeof renderOrder === 'string') + { + renderOrder = orders.indexOf(renderOrder); + } + + if (renderOrder >= 0 && renderOrder < 4) + { + this._renderOrder = renderOrder; + } + + return this; + }, + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#calculateFacesAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + calculateFacesAt: function (tileX, tileY) + { + TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); + + return this; + }, + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#calculateFacesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + calculateFacesWithin: function (tileX, tileY, width, height) + { + TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#createFromTiles + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ + createFromTiles: function (indexes, replacements, spriteConfig, scene, camera) + { + return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer); + }, + + /** + * Returns the tiles in the given layer that are within the cameras viewport. + * This is used internally. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#cull + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + cull: function (camera) + { + return this.cullCallback(this.layer, camera, this.culledTiles, this._renderOrder); + }, + + /** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#copy + * @since 3.0.0 + * + * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} width - The width of the area to copy, in tiles, not pixels. + * @param {integer} height - The height of the area to copy, in tiles, not pixels. + * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. + * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + copy: function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces) + { + TilemapComponents.Copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, this.layer); + + return this; + }, + + /** + * Destroys this DynamicTilemapLayer and removes its link to the associated LayerData. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#destroy + * @since 3.0.0 + * + * @param {boolean} [removeFromTilemap=true] - Remove this layer from the parent Tilemap? + */ + destroy: function (removeFromTilemap) + { + if (removeFromTilemap === undefined) { removeFromTilemap = true; } + + if (!this.tilemap) + { + // Abort, we've already been destroyed + return; + } + + // Uninstall this layer only if it is still installed on the LayerData object + if (this.layer.tilemapLayer === this) + { + this.layer.tilemapLayer = undefined; + } + + if (removeFromTilemap) + { + this.tilemap.removeLayer(this); + } + + this.tilemap = undefined; + this.layer = undefined; + this.culledTiles.length = 0; + this.cullCallback = null; + + this.gidMap = []; + this.tileset = []; + + GameObject.prototype.destroy.call(this); + }, + + /** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#fill + * @since 3.0.0 + * + * @param {integer} index - The tile index to fill the area with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + fill: function (index, tileX, tileY, width, height, recalculateFaces) + { + TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, this.layer); + + return this; + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#filterTiles + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#findByIndex + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + findByIndex: function (findIndex, skip, reverse) + { + return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer); + }, + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#findTile + * @since 3.0.0 + * + * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {?Phaser.Tilemaps.Tile} + */ + findTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#forEachTile + * @since 3.0.0 + * + * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + + return this; + }, + + /** + * Gets a tile at the given tile coordinates from the given layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTileAt: function (tileX, tileY, nonNull) + { + return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer); + }, + + /** + * Gets a tile at the given world coordinates from the given layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ + getTileAtWorldXY: function (worldX, worldY, nonNull, camera) + { + return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithin: function (tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithinShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinShape: function (shape, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithinWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The world x coordinate for the top-left of the area. + * @param {number} worldY - The world y coordinate for the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#hasTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * + * @return {boolean} `true` if a tile was found at the given location, otherwise `false`. + */ + hasTileAt: function (tileX, tileY) + { + return TilemapComponents.HasTileAt(tileX, tileY, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#hasTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {boolean} `true` if a tile was found at the given location, otherwise `false`. + */ + hasTileAtWorldXY: function (worldX, worldY, camera) + { + return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer); + }, + + /** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#putTileAt + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + putTileAt: function (tile, tileX, tileY, recalculateFaces) + { + return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, this.layer); + }, + + /** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#putTileAtWorldXY + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + putTileAtWorldXY: function (tile, worldX, worldY, recalculateFaces, camera) + { + return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, this.layer); + }, + + /** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#putTilesAt + * @since 3.0.0 + * + * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + putTilesAt: function (tilesArray, tileX, tileY, recalculateFaces) + { + TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, this.layer); + + return this; + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#randomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + randomize: function (tileX, tileY, width, height, indexes) + { + TilemapComponents.Randomize(tileX, tileY, width, height, indexes, this.layer); + + return this; + }, + + /** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#removeTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + removeTileAt: function (tileX, tileY, replaceWithNull, recalculateFaces) + { + return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, this.layer); + }, + + /** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#removeTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + removeTileAtWorldXY: function (worldX, worldY, replaceWithNull, recalculateFaces, camera) + { + return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, this.layer); + }, + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#renderDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + renderDebug: function (graphics, styleConfig) + { + TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#replaceByIndex + * @since 3.0.0 + * + * @param {integer} findIndex - The index of the tile to search for. + * @param {integer} newIndex - The index of the tile to replace it with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + replaceByIndex: function (findIndex, newIndex, tileX, tileY, width, height) + { + TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setSkipCull + * @since 3.11.0 + * + * @param {boolean} [value=true] - Set to `true` to stop culling tiles. Set to `false` to enable culling again. + * + * @return {this} This Tilemap Layer object. + */ + setSkipCull: function (value) + { + if (value === undefined) { value = true; } + + this.skipCull = value; + + return this; + }, + + /** + * When a Camera culls the tiles in this layer it does so using its view into the world, building up a + * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size + * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so + * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px + * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCullPadding + * @since 3.11.0 + * + * @param {integer} [paddingX=1] - The amount of extra horizontal tiles to add to the cull check padding. + * @param {integer} [paddingY=1] - The amount of extra vertical tiles to add to the cull check padding. + * + * @return {this} This Tilemap Layer object. + */ + setCullPadding: function (paddingX, paddingY) + { + if (paddingX === undefined) { paddingX = 1; } + if (paddingY === undefined) { paddingY = 1; } + + this.cullPaddingX = paddingX; + this.cullPaddingY = paddingY; + + return this; + }, + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollision + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollision: function (indexes, collides, recalculateFaces, updateLayer) + { + TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer, updateLayer); + + return this; + }, + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionBetween + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionBetween: function (start, stop, collides, recalculateFaces) + { + TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionByProperty + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionByProperty: function (properties, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionByExclusion + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionByExclusion: function (indexes, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking each tiles collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tiles collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionFromCollisionGroup + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionFromCollisionGroup: function (collides, recalculateFaces) + { + TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setTileIndexCallback + * @since 3.0.0 + * + * @param {(integer|integer[])} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setTileIndexCallback: function (indexes, callback, callbackContext) + { + TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setTileLocationCallback + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {function} [callback] - The callback that will be invoked when the tile is collided with. + * @param {object} [callbackContext] - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext) + { + TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#shuffle + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + shuffle: function (tileX, tileY, width, height) + { + TilemapComponents.Shuffle(tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#swapByIndex + * @since 3.0.0 + * + * @param {integer} tileA - First tile index. + * @param {integer} tileB - Second tile index. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + swapByIndex: function (indexA, indexB, tileX, tileY, width, height) + { + TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldX + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + tileToWorldX: function (tileX, camera) + { + return TilemapComponents.TileToWorldX(tileX, camera, this.layer); + }, + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldY + * @since 3.0.0 + * + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + tileToWorldY: function (tileY, camera) + { + return TilemapComponents.TileToWorldY(tileY, camera, this.layer); + }, + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldXY + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Math.Vector2} + */ + tileToWorldXY: function (tileX, tileY, point, camera) + { + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer); + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#weightedRandomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + weightedRandomize: function (tileX, tileY, width, height, weightedIndexes) + { + TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, this.layer); + + return this; + }, + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileX + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + worldToTileX: function (worldX, snapToFloor, camera) + { + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileY + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + worldToTileY: function (worldY, snapToFloor, camera) + { + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Math.Vector2} + */ + worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) + { + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + } + +}); + +module.exports = DynamicTilemapLayer; + + +/***/ }), +/* 534 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameEvents = __webpack_require__(21); +var GameObject = __webpack_require__(14); +var StaticTilemapLayerRender = __webpack_require__(1424); +var TilemapComponents = __webpack_require__(150); +var TransformMatrix = __webpack_require__(35); +var Utils = __webpack_require__(10); + +/** + * @classdesc + * A Static Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination + * with one, or more, Tilesets. + * + * A Static Tilemap Layer is optimized for rendering speed over flexibility. You cannot apply per-tile + * effects like tint or alpha, or change the tiles or tilesets the layer uses. + * + * Use a Static Tilemap Layer instead of a Dynamic Tilemap Layer when you don't need tile manipulation features. + * + * @class StaticTilemapLayer + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.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.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * @extends Phaser.GameObjects.Components.ScrollFactor + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. + * @param {Phaser.Tilemaps.Tilemap} tilemap - The Tilemap this layer is a part of. + * @param {integer} layerIndex - The index of the LayerData associated with this layer. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The world x position where the top left of this layer will be placed. + * @param {number} [y=0] - The world y position where the top left of this layer will be placed. + */ +var StaticTilemapLayer = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Origin, + Components.Pipeline, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + StaticTilemapLayerRender + ], + + initialize: + + function StaticTilemapLayer (scene, tilemap, layerIndex, tileset, x, y) + { + GameObject.call(this, scene, 'StaticTilemapLayer'); + + /** + * Used internally by physics system to perform fast type checks. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#isTilemap + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isTilemap = true; + + /** + * The Tilemap that this layer is a part of. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tilemap + * @type {Phaser.Tilemaps.Tilemap} + * @since 3.0.0 + */ + this.tilemap = tilemap; + + /** + * The index of the LayerData associated with this layer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#layerIndex + * @type {integer} + * @since 3.0.0 + */ + this.layerIndex = layerIndex; + + /** + * The LayerData associated with this layer. LayerData can only be associated with one + * tilemap layer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + this.layer = tilemap.layers[layerIndex]; + + // Link the LayerData with this static tilemap layer + this.layer.tilemapLayer = this; + + /** + * The Tileset/s associated with this layer. + * + * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tileset + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tileset = []; + + /** + * Used internally by the Canvas renderer. + * This holds the tiles that are visible within the camera in the last frame. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#culledTiles + * @type {array} + * @since 3.0.0 + */ + this.culledTiles = []; + + /** + * Canvas only. + * + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this, and toggling this flag allows + * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#skipCull + * @type {boolean} + * @since 3.12.0 + */ + this.skipCull = false; + + /** + * Canvas only. + * + * The total number of tiles drawn by the renderer in the last frame. + * + * This only works when rending with Canvas. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tilesDrawn + * @type {integer} + * @readonly + * @since 3.12.0 + */ + this.tilesDrawn = 0; + + /** + * Canvas only. + * + * The total number of tiles in this layer. Updated every frame. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tilesTotal + * @type {integer} + * @readonly + * @since 3.12.0 + */ + this.tilesTotal = this.layer.width * this.layer.height; + + /** + * Canvas only. + * + * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#cullPaddingX + * @type {integer} + * @default 1 + * @since 3.12.0 + */ + this.cullPaddingX = 1; + + /** + * Canvas only. + * + * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#cullPaddingY + * @type {integer} + * @default 1 + * @since 3.12.0 + */ + this.cullPaddingY = 1; + + /** + * Canvas only. + * + * The callback that is invoked when the tiles are culled. + * + * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. + * + * It will be sent 3 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. + * + * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#cullCallback + * @type {function} + * @since 3.12.0 + */ + this.cullCallback = TilemapComponents.CullTiles; + + /** + * A reference to the renderer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @private + * @since 3.0.0 + */ + this.renderer = scene.sys.game.renderer; + + /** + * An array of vertex buffer objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexBuffer + * @type {WebGLBuffer[]} + * @private + * @since 3.0.0 + */ + this.vertexBuffer = []; + + /** + * An array of ArrayBuffer objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#bufferData + * @type {ArrayBuffer[]} + * @private + * @since 3.0.0 + */ + this.bufferData = []; + + /** + * An array of Float32 Array objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexViewF32 + * @type {Float32Array[]} + * @private + * @since 3.0.0 + */ + this.vertexViewF32 = []; + + /** + * An array of Uint32 Array objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexViewU32 + * @type {Uint32Array[]} + * @private + * @since 3.0.0 + */ + this.vertexViewU32 = []; + + /** + * An array of booleans, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single boolean. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#dirty + * @type {boolean[]} + * @private + * @since 3.0.0 + */ + this.dirty = []; + + /** + * An array of integers, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single integer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexCount + * @type {integer[]} + * @private + * @since 3.0.0 + */ + this.vertexCount = []; + + /** + * The rendering (draw) order of the tiles in this layer. + * + * The default is 0 which is 'right-down', meaning it will draw the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * This can be changed via the `setRenderOrder` method. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#_renderOrder + * @type {integer} + * @default 0 + * @private + * @since 3.12.0 + */ + this._renderOrder = 0; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#_tempMatrix + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.14.0 + */ + this._tempMatrix = new TransformMatrix(); + + /** + * An array holding the mapping between the tile indexes and the tileset they belong to. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#gidMap + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.14.0 + */ + this.gidMap = []; + + this.setTilesets(tileset); + this.setAlpha(this.layer.alpha); + this.setPosition(x, y); + this.setOrigin(); + this.setSize(tilemap.tileWidth * this.layer.width, tilemap.tileHeight * this.layer.height); + + this.updateVBOData(); + + this.initPipeline('TextureTintPipeline'); + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function () + { + this.updateVBOData(); + }, this); + }, + + /** + * Populates the internal `tileset` array with the Tileset references this Layer requires for rendering. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setTilesets + * @private + * @since 3.14.0 + * + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + */ + setTilesets: function (tilesets) + { + var gidMap = []; + var setList = []; + var map = this.tilemap; + + if (!Array.isArray(tilesets)) + { + tilesets = [ tilesets ]; + } + + for (var i = 0; i < tilesets.length; i++) + { + var tileset = tilesets[i]; + + if (typeof tileset === 'string') + { + tileset = map.getTileset(tileset); + } + + if (tileset) + { + setList.push(tileset); + + var s = tileset.firstgid; + + for (var t = 0; t < tileset.total; t++) + { + gidMap[s + t] = tileset; + } + } + } + + this.gidMap = gidMap; + this.tileset = setList; + }, + + /** + * Prepares the VBO data arrays for population by the `upload` method. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#updateVBOData + * @private + * @since 3.14.0 + * + * @return {this} This Tilemap Layer object. + */ + updateVBOData: function () + { + for (var i = 0; i < this.tileset.length; i++) + { + this.dirty[i] = true; + this.vertexCount[i] = 0; + this.vertexBuffer[i] = null; + this.bufferData[i] = null; + this.vertexViewF32[i] = null; + this.vertexViewU32[i] = null; + } + + return this; + }, + + /** + * Upload the tile data to a VBO. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#upload + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to render to. + * @param {integer} tilesetIndex - The tileset index. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + upload: function (camera, tilesetIndex) + { + var renderer = this.renderer; + var gl = renderer.gl; + + var pipeline = renderer.pipelines.TextureTintPipeline; + + if (this.dirty[tilesetIndex]) + { + var tileset = this.tileset[tilesetIndex]; + var mapWidth = this.layer.width; + var mapHeight = this.layer.height; + var width = tileset.image.source[0].width; + var height = tileset.image.source[0].height; + var mapData = this.layer.data; + var tile; + var row; + var col; + var renderOrder = this._renderOrder; + var minTileIndex = tileset.firstgid; + var maxTileIndex = tileset.firstgid + tileset.total; + + var vertexBuffer = this.vertexBuffer[tilesetIndex]; + var bufferData = this.bufferData[tilesetIndex]; + var vOffset = -1; + var bufferSize = (mapWidth * mapHeight) * pipeline.vertexSize * 6; + + this.vertexCount[tilesetIndex] = 0; + + if (bufferData === null) + { + bufferData = new ArrayBuffer(bufferSize); + + this.bufferData[tilesetIndex] = bufferData; + + this.vertexViewF32[tilesetIndex] = new Float32Array(bufferData); + this.vertexViewU32[tilesetIndex] = new Uint32Array(bufferData); + } + + if (renderOrder === 0) + { + // right-down + + for (row = 0; row < mapHeight; row++) + { + for (col = 0; col < mapWidth; col++) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + else if (renderOrder === 1) + { + // left-down + + for (row = 0; row < mapHeight; row++) + { + for (col = mapWidth - 1; col >= 0; col--) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + else if (renderOrder === 2) + { + // right-up + + for (row = mapHeight - 1; row >= 0; row--) + { + for (col = 0; col < mapWidth; col++) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (row = mapHeight - 1; row >= 0; row--) + { + for (col = mapWidth - 1; col >= 0; col--) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + + this.dirty[tilesetIndex] = false; + + if (vertexBuffer === null) + { + vertexBuffer = renderer.createVertexBuffer(bufferData, gl.STATIC_DRAW); + + this.vertexBuffer[tilesetIndex] = vertexBuffer; + } + else + { + renderer.setVertexBuffer(vertexBuffer); + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, bufferData); + } + } + + return this; + }, + + /** + * Add a single tile into the batch. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#batchTile + * @private + * @since 3.12.0 + * + * @param {integer} vOffset - The vertex offset. + * @param {any} tile - The tile being rendered. + * @param {any} tileset - The tileset being used for rendering. + * @param {integer} width - The width of the tileset image in pixels. + * @param {integer} height - The height of the tileset image in pixels. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the layer is being rendered with. + * @param {integer} tilesetIndex - The tileset index. + * + * @return {integer} The new vOffset value. + */ + batchTile: function (vOffset, tile, tileset, width, height, camera, tilesetIndex) + { + var texCoords = tileset.getTileTextureCoordinates(tile.index); + + if (!texCoords) + { + return vOffset; + } + + var tileWidth = tileset.tileWidth; + var tileHeight = tileset.tileHeight; + + var halfTileWidth = tileWidth / 2; + var halfTileHeight = tileHeight / 2; + + var u0 = texCoords.x / width; + var v0 = texCoords.y / height; + var u1 = (texCoords.x + tileWidth) / width; + var v1 = (texCoords.y + tileHeight) / height; + + var matrix = this._tempMatrix; + + var x = -halfTileWidth; + var y = -halfTileHeight; + + if (tile.flipX) + { + tileWidth *= -1; + x += tileset.tileWidth; + } + + if (tile.flipY) + { + tileHeight *= -1; + y += tileset.tileHeight; + } + + var xw = x + tileWidth; + var yh = y + tileHeight; + + matrix.applyITRS(halfTileWidth + tile.pixelX, halfTileHeight + tile.pixelY, tile.rotation, 1, 1); + + var tint = Utils.getTintAppendFloatAlpha(0xffffff, camera.alpha * this.alpha * tile.alpha); + + var tx0 = matrix.getX(x, y); + var ty0 = matrix.getY(x, y); + + var tx1 = matrix.getX(x, yh); + var ty1 = matrix.getY(x, yh); + + var tx2 = matrix.getX(xw, yh); + var ty2 = matrix.getY(xw, yh); + + var tx3 = matrix.getX(xw, y); + var ty3 = matrix.getY(xw, y); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + var vertexViewF32 = this.vertexViewF32[tilesetIndex]; + var vertexViewU32 = this.vertexViewU32[tilesetIndex]; + + vertexViewF32[++vOffset] = tx0; + vertexViewF32[++vOffset] = ty0; + vertexViewF32[++vOffset] = u0; + vertexViewF32[++vOffset] = v0; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx1; + vertexViewF32[++vOffset] = ty1; + vertexViewF32[++vOffset] = u0; + vertexViewF32[++vOffset] = v1; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx2; + vertexViewF32[++vOffset] = ty2; + vertexViewF32[++vOffset] = u1; + vertexViewF32[++vOffset] = v1; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx0; + vertexViewF32[++vOffset] = ty0; + vertexViewF32[++vOffset] = u0; + vertexViewF32[++vOffset] = v0; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx2; + vertexViewF32[++vOffset] = ty2; + vertexViewF32[++vOffset] = u1; + vertexViewF32[++vOffset] = v1; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx3; + vertexViewF32[++vOffset] = ty3; + vertexViewF32[++vOffset] = u1; + vertexViewF32[++vOffset] = v0; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + this.vertexCount[tilesetIndex] += 6; + + return vOffset; + }, + + /** + * Sets the rendering (draw) order of the tiles in this layer. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setRenderOrder + * @since 3.12.0 + * + * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + * + * @return {this} This Tilemap Layer object. + */ + setRenderOrder: function (renderOrder) + { + var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; + + if (typeof renderOrder === 'string') + { + renderOrder = orders.indexOf(renderOrder); + } + + if (renderOrder >= 0 && renderOrder < 4) + { + this._renderOrder = renderOrder; + + for (var i = 0; i < this.tileset.length; i++) + { + this.dirty[i] = true; + } + } + + return this; + }, + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#calculateFacesAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + calculateFacesAt: function (tileX, tileY) + { + TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); + + return this; + }, + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#calculateFacesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + calculateFacesWithin: function (tileX, tileY, width, height) + { + TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#createFromTiles + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ + createFromTiles: function (indexes, replacements, spriteConfig, scene, camera) + { + return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer); + }, + + /** + * Returns the tiles in the given layer that are within the cameras viewport. + * This is used internally. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#cull + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + cull: function (camera) + { + return this.cullCallback(this.layer, camera, this.culledTiles); + }, + + /** + * Canvas only. + * + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setSkipCull + * @since 3.12.0 + * + * @param {boolean} [value=true] - Set to `true` to stop culling tiles. Set to `false` to enable culling again. + * + * @return {this} This Tilemap Layer object. + */ + setSkipCull: function (value) + { + if (value === undefined) { value = true; } + + this.skipCull = value; + + return this; + }, + + /** + * Canvas only. + * + * When a Camera culls the tiles in this layer it does so using its view into the world, building up a + * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size + * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so + * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px + * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCullPadding + * @since 3.12.0 + * + * @param {integer} [paddingX=1] - The amount of extra horizontal tiles to add to the cull check padding. + * @param {integer} [paddingY=1] - The amount of extra vertical tiles to add to the cull check padding. + * + * @return {this} This Tilemap Layer object. + */ + setCullPadding: function (paddingX, paddingY) + { + if (paddingX === undefined) { paddingX = 1; } + if (paddingY === undefined) { paddingY = 1; } + + this.cullPaddingX = paddingX; + this.cullPaddingY = paddingY; + + return this; + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#findByIndex + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + findByIndex: function (findIndex, skip, reverse) + { + return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer); + }, + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#findTile + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {?Phaser.Tilemaps.Tile} + */ + findTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#filterTiles + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#forEachTile + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + + return this; + }, + + /** + * Gets a tile at the given tile coordinates from the given layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile + * object with an index of -1. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTileAt: function (tileX, tileY, nonNull) + { + return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer); + }, + + /** + * Gets a tile at the given world coordinates from the given layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile + * object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ + getTileAtWorldXY: function (worldX, worldY, nonNull, camera) + { + return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithin: function (tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithinWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {number} worldY - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {number} width - How many tiles wide from the `tileX` index the area will be. + * @param {number} height - How many tiles high from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer); + }, + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithinShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinShape: function (shape, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#hasTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from in tile coordinates. + * @param {integer} tileY - Y position to get the tile from in tile coordinates. + * + * @return {boolean} + */ + hasTileAt: function (tileX, tileY) + { + return TilemapComponents.HasTileAt(tileX, tileY, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#hasTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate of the world position. + * @param {number} worldY - The Y coordinate of the world position. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {boolean} + */ + hasTileAtWorldXY: function (worldX, worldY, camera) + { + return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer); + }, + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#renderDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + renderDebug: function (graphics, styleConfig) + { + TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); + + return this; + }, + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollision + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollision: function (indexes, collides, recalculateFaces, updateLayer) + { + TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer, updateLayer); + + return this; + }, + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionBetween + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionBetween: function (start, stop, collides, recalculateFaces) + { + TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionByProperty + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should + * be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionByProperty: function (properties, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionByExclusion + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionByExclusion: function (indexes, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setTileIndexCallback + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a + * collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setTileIndexCallback: function (indexes, callback, callbackContext) + { + TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking each tiles collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tiles collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionFromCollisionGroup + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionFromCollisionGroup: function (collides, recalculateFaces) + { + TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setTileLocationCallback + * @since 3.0.0 + * + * @param {integer} tileX - The leftmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The topmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} [callbackContext] - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext) + { + TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldX + * @since 3.0.0 + * + * @param {integer} tileX - The X coordinate, in tile coordinates. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. + * + * @return {number} + */ + tileToWorldX: function (tileX, camera) + { + return TilemapComponents.TileToWorldX(tileX, camera, this.layer); + }, + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldY + * @since 3.0.0 + * + * @param {integer} tileY - The Y coordinate, in tile coordinates. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. + * + * @return {number} + */ + tileToWorldY: function (tileY, camera) + { + return TilemapComponents.TileToWorldY(tileY, camera, this.layer); + }, + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldXY + * @since 3.0.0 + * + * @param {integer} tileX - The X coordinate, in tile coordinates. + * @param {integer} tileY - The Y coordinate, in tile coordinates. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given, a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. + * + * @return {Phaser.Math.Vector2} + */ + tileToWorldXY: function (tileX, tileY, point, camera) + { + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer); + }, + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileX + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate, in world pixels. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the + * nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values.] + * + * @return {number} + */ + worldToTileX: function (worldX, snapToFloor, camera) + { + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileY + * @since 3.0.0 + * + * @param {number} worldY - The Y coordinate, in world pixels. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the + * nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + worldToTileY: function (worldY, snapToFloor, camera) + { + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileXY + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate, in world pixels. + * @param {number} worldY - The Y coordinate, in world pixels. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the + * nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given, a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Math.Vector2} + */ + worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) + { + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + }, + + /** + * Destroys this StaticTilemapLayer and removes its link to the associated LayerData. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#destroy + * @since 3.0.0 + * + * @param {boolean} [removeFromTilemap=true] - Remove this layer from the parent Tilemap? + */ + destroy: function (removeFromTilemap) + { + if (removeFromTilemap === undefined) { removeFromTilemap = true; } + + if (!this.tilemap) + { + // Abort, we've already been destroyed + return; + } + + // Uninstall this layer only if it is still installed on the LayerData object + if (this.layer.tilemapLayer === this) + { + this.layer.tilemapLayer = undefined; + } + + if (removeFromTilemap) + { + this.tilemap.removeLayer(this); + } + + this.tilemap = undefined; + this.layer = undefined; + this.culledTiles.length = 0; + this.cullCallback = null; + + for (var i = 0; i < this.tileset.length; i++) + { + this.dirty[i] = true; + this.vertexCount[i] = 0; + this.vertexBuffer[i] = null; + this.bufferData[i] = null; + this.vertexViewF32[i] = null; + this.vertexViewU32[i] = null; + } + + this.gidMap = []; + this.tileset = []; + + GameObject.prototype.destroy.call(this); + } + +}); + +module.exports = StaticTilemapLayer; + + +/***/ }), +/* 535 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetFastValue = __webpack_require__(1); + +/** + * @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. + */ +var TimerEvent = new Class({ + + initialize: + + function TimerEvent (config) + { + /** + * The delay in ms at which this TimerEvent fires. + * + * @name Phaser.Time.TimerEvent#delay + * @type {number} + * @default 0 + * @readonly + * @since 3.0.0 + */ + this.delay = 0; + + /** + * The total number of times this TimerEvent will repeat before finishing. + * + * @name Phaser.Time.TimerEvent#repeat + * @type {number} + * @default 0 + * @readonly + * @since 3.0.0 + */ + this.repeat = 0; + + /** + * If repeating this contains the current repeat count. + * + * @name Phaser.Time.TimerEvent#repeatCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.repeatCount = 0; + + /** + * True if this TimerEvent loops, otherwise false. + * + * @name Phaser.Time.TimerEvent#loop + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.loop = false; + + /** + * The callback that will be called when the TimerEvent occurs. + * + * @name Phaser.Time.TimerEvent#callback + * @type {function} + * @since 3.0.0 + */ + this.callback; + + /** + * The scope in which the callback will be called. + * + * @name Phaser.Time.TimerEvent#callbackScope + * @type {object} + * @since 3.0.0 + */ + this.callbackScope; + + /** + * Additional arguments to be passed to the callback. + * + * @name Phaser.Time.TimerEvent#args + * @type {array} + * @since 3.0.0 + */ + this.args; + + /** + * Scale the time causing this TimerEvent to update. + * + * @name Phaser.Time.TimerEvent#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Start this many MS into the elapsed (useful if you want a long duration with repeat, but for the first loop to fire quickly) + * + * @name Phaser.Time.TimerEvent#startAt + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.startAt = 0; + + /** + * The time in milliseconds which has elapsed since the Timer Event's creation. + * + * This value is local for the Timer Event and is relative to its Clock. As such, it's influenced by the Clock's time scale and paused state, the Timer Event's initial {@link #startAt} property, and the Timer Event's {@link #timeScale} and {@link #paused} state. + * + * @name Phaser.Time.TimerEvent#elapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.elapsed = 0; + + /** + * Whether or not this timer is paused. + * + * @name Phaser.Time.TimerEvent#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * Whether the Timer Event's function has been called. + * + * When the Timer Event fires, this property will be set to `true` before the callback function is invoked and will be reset immediately afterward if the Timer Event should repeat. The value of this property does not directly influence whether the Timer Event will be removed from its Clock, but can prevent it from firing. + * + * @name Phaser.Time.TimerEvent#hasDispatched + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.hasDispatched = false; + + this.reset(config); + }, + + /** + * Completely reinitializes the Timer Event, regardless of its current state, according to a configuration object. + * + * @method Phaser.Time.TimerEvent#reset + * @since 3.0.0 + * + * @param {Phaser.Types.Time.TimerEventConfig} config - The new state for the Timer Event. + * + * @return {Phaser.Time.TimerEvent} This TimerEvent object. + */ + reset: function (config) + { + this.delay = GetFastValue(config, 'delay', 0); + + // Can also be set to -1 for an infinite loop (same as setting loop: true) + this.repeat = GetFastValue(config, 'repeat', 0); + + this.loop = GetFastValue(config, 'loop', false); + + this.callback = GetFastValue(config, 'callback', undefined); + + this.callbackScope = GetFastValue(config, 'callbackScope', this.callback); + + this.args = GetFastValue(config, 'args', []); + + this.timeScale = GetFastValue(config, 'timeScale', 1); + + this.startAt = GetFastValue(config, 'startAt', 0); + + this.paused = GetFastValue(config, 'paused', false); + + this.elapsed = this.startAt; + this.hasDispatched = false; + this.repeatCount = (this.repeat === -1 || this.loop) ? 999999999999 : this.repeat; + + return this; + }, + + /** + * Gets the progress of the current iteration, not factoring in repeats. + * + * @method Phaser.Time.TimerEvent#getProgress + * @since 3.0.0 + * + * @return {number} A number between 0 and 1 representing the current progress. + */ + getProgress: function () + { + return (this.elapsed / this.delay); + }, + + /** + * Gets the progress of the timer overall, factoring in repeats. + * + * @method Phaser.Time.TimerEvent#getOverallProgress + * @since 3.0.0 + * + * @return {number} The overall progress of the Timer Event, between 0 and 1. + */ + getOverallProgress: function () + { + if (this.repeat > 0) + { + var totalDuration = this.delay + (this.delay * this.repeat); + var totalElapsed = this.elapsed + (this.delay * (this.repeat - this.repeatCount)); + + return (totalElapsed / totalDuration); + } + else + { + return this.getProgress(); + } + }, + + /** + * Returns the number of times this Timer Event will repeat before finishing. + * + * This should not be confused with the number of times the Timer Event will fire before finishing. A return value of 0 doesn't indicate that the Timer Event has finished running - it indicates that it will not repeat after the next time it fires. + * + * @method Phaser.Time.TimerEvent#getRepeatCount + * @since 3.0.0 + * + * @return {number} How many times the Timer Event will repeat. + */ + getRepeatCount: function () + { + return this.repeatCount; + }, + + /** + * Returns the local elapsed time for the current iteration of the Timer Event. + * + * @method Phaser.Time.TimerEvent#getElapsed + * @since 3.0.0 + * + * @return {number} The local elapsed time in milliseconds. + */ + getElapsed: function () + { + return this.elapsed; + }, + + /** + * Returns the local elapsed time for the current iteration of the Timer Event in seconds. + * + * @method Phaser.Time.TimerEvent#getElapsedSeconds + * @since 3.0.0 + * + * @return {number} The local elapsed time in seconds. + */ + getElapsedSeconds: function () + { + return this.elapsed * 0.001; + }, + + /** + * Forces the Timer Event to immediately expire, thus scheduling its removal in the next frame. + * + * @method Phaser.Time.TimerEvent#remove + * @since 3.0.0 + * + * @param {boolean} [dispatchCallback=false] - If `true`, the function of the Timer Event will be called before its removal. + */ + remove: function (dispatchCallback) + { + if (dispatchCallback === undefined) { dispatchCallback = false; } + + this.elapsed = this.delay; + + this.hasDispatched = !dispatchCallback; + + this.repeatCount = 0; + }, + + /** + * Destroys all object references in the Timer Event, i.e. its callback, scope, and arguments. + * + * Normally, this method is only called by the Clock when it shuts down. As such, it doesn't stop the Timer Event. If called manually, the Timer Event will still be updated by the Clock, but it won't do anything when it fires. + * + * @method Phaser.Time.TimerEvent#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.callback = undefined; + this.callbackScope = undefined; + this.args = []; + } + +}); + +module.exports = TimerEvent; + + +/***/ }), +/* 536 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RESERVED = __webpack_require__(1433); + +/** + * Internal function used by the Tween Builder to return an array of properties + * that the Tween will be operating on. It takes a tween configuration object + * and then checks that none of the `props` entries start with an underscore, or that + * none of the direct properties are on the Reserved list. + * + * @function Phaser.Tweens.Builders.GetProps + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig} config - The configuration object of the Tween to get the properties from. + * + * @return {string[]} An array of all the properties the tween will operate on. + */ +var GetProps = function (config) +{ + var key; + var keys = []; + + // First see if we have a props object + + if (config.hasOwnProperty('props')) + { + for (key in config.props) + { + // Skip any property that starts with an underscore + if (key.substr(0, 1) !== '_') + { + keys.push({ key: key, value: config.props[key] }); + } + } + } + else + { + for (key in config) + { + // Skip any property that is in the ReservedProps list or that starts with an underscore + if (RESERVED.indexOf(key) === -1 && key.substr(0, 1) !== '_') + { + keys.push({ key: key, value: config[key] }); + } + } + } + + return keys; +}; + +module.exports = GetProps; + + +/***/ }), +/* 537 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = __webpack_require__(5); + +/** + * Internal function used by the Timeline Builder. + * + * It returns an array of all tweens in the given timeline config. + * + * @function Phaser.Tweens.Builders.GetTweens + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} config - The configuration object for the Timeline. + * + * @return {Phaser.Tweens.Tween[]} An array of Tween instances that the Timeline will manage. + */ +var GetTweens = function (config) +{ + var tweens = GetValue(config, 'tweens', null); + + if (tweens === null) + { + return []; + } + else if (typeof tweens === 'function') + { + tweens = tweens.call(); + } + + if (!Array.isArray(tweens)) + { + tweens = [ tweens ]; + } + + return tweens; +}; + +module.exports = GetTweens; + + +/***/ }), +/* 538 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Defaults = __webpack_require__(255); +var GetAdvancedValue = __webpack_require__(15); +var GetBoolean = __webpack_require__(99); +var GetEaseFunction = __webpack_require__(90); +var GetNewValue = __webpack_require__(155); +var GetValue = __webpack_require__(5); +var GetValueOp = __webpack_require__(254); +var Tween = __webpack_require__(256); +var TweenData = __webpack_require__(258); + +/** + * Creates a new Number Tween. + * + * @function Phaser.Tweens.Builders.NumberTweenBuilder + * @since 3.0.0 + * + * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - The owner of the new Tween. + * @param {Phaser.Types.Tweens.NumberTweenBuilderConfig} config - Configuration for the new Tween. + * @param {Phaser.Types.Tweens.TweenConfigDefaults} defaults - Tween configuration defaults. + * + * @return {Phaser.Tweens.Tween} The new tween. + */ +var NumberTweenBuilder = function (parent, config, defaults) +{ + if (defaults === undefined) + { + defaults = Defaults; + } + + // var tween = this.tweens.addCounter({ + // from: 100, + // to: 200, + // ... (normal tween properties) + // }) + // + // Then use it in your game via: + // + // tween.getValue() + + var from = GetValue(config, 'from', 0); + var to = GetValue(config, 'to', 1); + + var targets = [ { value: from } ]; + + var delay = GetNewValue(config, 'delay', defaults.delay); + var duration = GetNewValue(config, 'duration', defaults.duration); + var easeParams = GetValue(config, 'easeParams', defaults.easeParams); + var ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), easeParams); + var hold = GetNewValue(config, 'hold', defaults.hold); + var repeat = GetNewValue(config, 'repeat', defaults.repeat); + var repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); + var yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); + + var data = []; + + var ops = GetValueOp('value', to); + + var tweenData = TweenData( + targets[0], + 0, + 'value', + ops.getEnd, + ops.getStart, + ops.getActive, + ease, + delay, + duration, + yoyo, + hold, + repeat, + repeatDelay, + false, + false + ); + + tweenData.start = from; + tweenData.current = from; + tweenData.to = to; + + data.push(tweenData); + + var tween = new Tween(parent, data, targets); + + tween.offset = GetAdvancedValue(config, 'offset', null); + tween.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); + tween.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); + tween.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); + tween.paused = GetBoolean(config, 'paused', false); + tween.useFrames = GetBoolean(config, 'useFrames', false); + + // Set the Callbacks + var scope = GetValue(config, 'callbackScope', tween); + + // Callback parameters: 0 = a reference to the Tween itself, 1 = the target/s of the Tween, ... your own params + var tweenArray = [ tween, null ]; + + var callbacks = Tween.TYPES; + + for (var i = 0; i < callbacks.length; i++) + { + var type = callbacks[i]; + + var callback = GetValue(config, type, false); + + if (callback) + { + var callbackScope = GetValue(config, type + 'Scope', scope); + var callbackParams = GetValue(config, type + 'Params', []); + + // The null is reset to be the Tween target + tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope); + } + } + + return tween; +}; + +module.exports = NumberTweenBuilder; + + +/***/ }), +/* 539 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetEaseFunction = __webpack_require__(90); +var GetValue = __webpack_require__(5); +var MATH_CONST = __webpack_require__(13); + +/** + * 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} [config] - A Stagger Configuration object. + * + * @return {function} The stagger function. + */ +var StaggerBuilder = function (value, options) +{ + if (options === undefined) { options = {}; } + + var result; + + var start = GetValue(options, 'start', 0); + var ease = GetValue(options, 'ease', null); + var grid = GetValue(options, 'grid', null); + + var from = GetValue(options, 'from', 0); + + var fromFirst = (from === 'first'); + var fromCenter = (from === 'center'); + var fromLast = (from === 'last'); + var fromValue = (typeof(from) === 'number'); + + var isRange = (Array.isArray(value)); + var value1 = (isRange) ? parseFloat(value[0]) : parseFloat(value); + var value2 = (isRange) ? parseFloat(value[1]) : 0; + var maxValue = Math.max(value1, value2); + + if (isRange) + { + start += value1; + } + + if (grid) + { + // Pre-calc the grid to save doing it for ever tweendata update + var gridWidth = grid[0]; + var gridHeight = grid[1]; + + var fromX = 0; + var fromY = 0; + + var distanceX = 0; + var distanceY = 0; + + var gridValues = []; + + if (fromLast) + { + fromX = gridWidth - 1; + fromY = gridHeight - 1; + } + else if (fromValue) + { + fromX = from % gridWidth; + fromY = Math.floor(from / gridWidth); + } + else if (fromCenter) + { + fromX = (gridWidth - 1) / 2; + fromY = (gridHeight - 1) / 2; + } + + var gridMax = MATH_CONST.MIN_SAFE_INTEGER; + + for (var toY = 0; toY < gridHeight; toY++) + { + gridValues[toY] = []; + + for (var toX = 0; toX < gridWidth; toX++) + { + distanceX = fromX - toX; + distanceY = fromY - toY; + + var dist = Math.sqrt(distanceX * distanceX + distanceY * distanceY); + + if (dist > gridMax) + { + gridMax = dist; + } + + gridValues[toY][toX] = dist; + } + } + } + + var easeFunction = (ease) ? GetEaseFunction(ease) : null; + + if (grid) + { + result = function (target, key, value, index) + { + var gridSpace = 0; + var toX = index % gridWidth; + var toY = Math.floor(index / gridWidth); + + if (toX >= 0 && toX < gridWidth && toY >= 0 && toY < gridHeight) + { + gridSpace = gridValues[toY][toX]; + } + + var output; + + if (isRange) + { + var diff = (value2 - value1); + + if (easeFunction) + { + output = ((gridSpace / gridMax) * diff) * easeFunction(gridSpace / gridMax); + } + else + { + output = (gridSpace / gridMax) * diff; + } + } + else if (easeFunction) + { + output = (gridSpace * value1) * easeFunction(gridSpace / gridMax); + } + else + { + output = gridSpace * value1; + } + + return output + start; + }; + } + else + { + result = function (target, key, value, index, total) + { + // zero offset + total--; + + var fromIndex; + + if (fromFirst) + { + fromIndex = index; + } + else if (fromCenter) + { + fromIndex = Math.abs((total / 2) - index); + } + else if (fromLast) + { + fromIndex = total - index; + } + else if (fromValue) + { + fromIndex = Math.abs(from - index); + } + + var output; + + if (isRange) + { + var spacing; + + if (fromCenter) + { + spacing = ((value2 - value1) / total) * (fromIndex * 2); + } + else + { + spacing = ((value2 - value1) / total) * fromIndex; + } + + if (easeFunction) + { + output = spacing * easeFunction(fromIndex / total); + } + else + { + output = spacing; + } + } + else if (easeFunction) + { + output = (total * maxValue) * easeFunction(fromIndex / total); + } + else + { + output = fromIndex * value1; + } + + return output + start; + }; + } + + return result; +}; + +module.exports = StaggerBuilder; + + +/***/ }), +/* 540 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(73); +var Defaults = __webpack_require__(255); +var GetAdvancedValue = __webpack_require__(15); +var GetBoolean = __webpack_require__(99); +var GetEaseFunction = __webpack_require__(90); +var GetNewValue = __webpack_require__(155); +var GetTargets = __webpack_require__(253); +var GetTweens = __webpack_require__(537); +var GetValue = __webpack_require__(5); +var Timeline = __webpack_require__(541); +var TweenBuilder = __webpack_require__(156); + +/** + * Builds a Timeline of Tweens based on a configuration object. + * + * @function Phaser.Tweens.Builders.TimelineBuilder + * @since 3.0.0 + * + * @param {Phaser.Tweens.TweenManager} manager - The Tween Manager to which the Timeline will belong. + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} config - The configuration object for the Timeline. + * + * @return {Phaser.Tweens.Timeline} The created Timeline. + */ +var TimelineBuilder = function (manager, config) +{ + var timeline = new Timeline(manager); + + var tweens = GetTweens(config); + + if (tweens.length === 0) + { + timeline.paused = true; + + return timeline; + } + + var defaults = Clone(Defaults); + + defaults.targets = GetTargets(config); + + // totalDuration: If specified each tween in the Timeline is given an equal portion of the totalDuration + + var totalDuration = GetAdvancedValue(config, 'totalDuration', 0); + + if (totalDuration > 0) + { + defaults.duration = Math.floor(totalDuration / tweens.length); + } + else + { + defaults.duration = GetNewValue(config, 'duration', defaults.duration); + } + + defaults.delay = GetNewValue(config, 'delay', defaults.delay); + defaults.easeParams = GetValue(config, 'easeParams', defaults.easeParams); + defaults.ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), defaults.easeParams); + defaults.hold = GetNewValue(config, 'hold', defaults.hold); + defaults.repeat = GetNewValue(config, 'repeat', defaults.repeat); + defaults.repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); + defaults.yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); + defaults.flipX = GetBoolean(config, 'flipX', defaults.flipX); + defaults.flipY = GetBoolean(config, 'flipY', defaults.flipY); + + // Create the Tweens + for (var i = 0; i < tweens.length; i++) + { + timeline.queue(TweenBuilder(timeline, tweens[i], defaults)); + } + + timeline.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); + timeline.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); + timeline.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); + timeline.paused = GetBoolean(config, 'paused', false); + timeline.useFrames = GetBoolean(config, 'useFrames', false); + + // Callbacks + + var scope = GetValue(config, 'callbackScope', timeline); + + var timelineArray = [ timeline ]; + + var onStart = GetValue(config, 'onStart', false); + + // The Start of the Timeline + if (onStart) + { + var onStartScope = GetValue(config, 'onStartScope', scope); + var onStartParams = GetValue(config, 'onStartParams', []); + + timeline.setCallback('onStart', onStart, timelineArray.concat(onStartParams), onStartScope); + } + + var onUpdate = GetValue(config, 'onUpdate', false); + + // Every time the Timeline updates (regardless which Tweens are running) + if (onUpdate) + { + var onUpdateScope = GetValue(config, 'onUpdateScope', scope); + var onUpdateParams = GetValue(config, 'onUpdateParams', []); + + timeline.setCallback('onUpdate', onUpdate, timelineArray.concat(onUpdateParams), onUpdateScope); + } + + var onLoop = GetValue(config, 'onLoop', false); + + // Called when the whole Timeline loops + if (onLoop) + { + var onLoopScope = GetValue(config, 'onLoopScope', scope); + var onLoopParams = GetValue(config, 'onLoopParams', []); + + timeline.setCallback('onLoop', onLoop, timelineArray.concat(onLoopParams), onLoopScope); + } + + var onYoyo = GetValue(config, 'onYoyo', false); + + // Called when a Timeline yoyos + if (onYoyo) + { + var onYoyoScope = GetValue(config, 'onYoyoScope', scope); + var onYoyoParams = GetValue(config, 'onYoyoParams', []); + + timeline.setCallback('onYoyo', onYoyo, timelineArray.concat(null, onYoyoParams), onYoyoScope); + } + + var onComplete = GetValue(config, 'onComplete', false); + + // Called when the Timeline completes, after the completeDelay, etc. + if (onComplete) + { + var onCompleteScope = GetValue(config, 'onCompleteScope', scope); + var onCompleteParams = GetValue(config, 'onCompleteParams', []); + + timeline.setCallback('onComplete', onComplete, timelineArray.concat(onCompleteParams), onCompleteScope); + } + + return timeline; +}; + +module.exports = TimelineBuilder; + + +/***/ }), +/* 541 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(257); +var TweenBuilder = __webpack_require__(156); +var TWEEN_CONST = __webpack_require__(100); + +/** + * @classdesc + * A Timeline combines multiple Tweens into one. Its overall behavior is otherwise similar to a single Tween. + * + * The Timeline updates all of its Tweens simultaneously. Its methods allow you to easily build a sequence + * of Tweens (each one starting after the previous one) or run multiple Tweens at once during given parts of the Timeline. + * + * @class Timeline + * @memberof Phaser.Tweens + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Tweens.TweenManager} manager - The Tween Manager which owns this Timeline. + */ +var Timeline = new Class({ + + Extends: EventEmitter, + + initialize: + + function Timeline (manager) + { + EventEmitter.call(this); + + /** + * The Tween Manager which owns this Timeline. + * + * @name Phaser.Tweens.Timeline#manager + * @type {Phaser.Tweens.TweenManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * A constant value which allows this Timeline to be easily identified as one. + * + * @name Phaser.Tweens.Timeline#isTimeline + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.isTimeline = true; + + /** + * An array of Tween objects, each containing a unique property and target being tweened. + * + * @name Phaser.Tweens.Timeline#data + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.data = []; + + /** + * The cached size of the data array. + * + * @name Phaser.Tweens.Timeline#totalData + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalData = 0; + + /** + * If true then duration, delay, etc values are all frame totals, rather than ms. + * + * @name Phaser.Tweens.Timeline#useFrames + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.useFrames = false; + + /** + * Scales the time applied to this Timeline. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * Value isn't used when calculating total duration of the Timeline, it's a run-time delta adjustment only. + * + * @name Phaser.Tweens.Timeline#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Loop this Timeline? Can be -1 for an infinite loop, or an integer. + * When enabled it will play through ALL Tweens again (use Tween.repeat to loop a single tween) + * + * @name Phaser.Tweens.Timeline#loop + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loop = 0; + + /** + * Time in ms/frames before this Timeline loops. + * + * @name Phaser.Tweens.Timeline#loopDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopDelay = 0; + + /** + * How many loops are left to run? + * + * @name Phaser.Tweens.Timeline#loopCounter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopCounter = 0; + + /** + * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = true (as it never completes) + * + * @name Phaser.Tweens.Timeline#completeDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.completeDelay = 0; + + /** + * Countdown timer value, as used by `loopDelay` and `completeDelay`. + * + * @name Phaser.Tweens.Timeline#countdown + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.countdown = 0; + + /** + * The current state of the Timeline. + * + * @name Phaser.Tweens.Timeline#state + * @type {integer} + * @since 3.0.0 + */ + this.state = TWEEN_CONST.PENDING_ADD; + + /** + * The state of the Timeline when it was paused (used by Resume) + * + * @name Phaser.Tweens.Timeline#_pausedState + * @type {integer} + * @private + * @since 3.0.0 + */ + this._pausedState = TWEEN_CONST.PENDING_ADD; + + /** + * Does the Timeline start off paused? (if so it needs to be started with Timeline.play) + * + * @name Phaser.Tweens.Timeline#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * Elapsed time in ms/frames of this run through of the Timeline. + * + * @name Phaser.Tweens.Timeline#elapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.elapsed = 0; + + /** + * Total elapsed time in ms/frames of the entire Timeline, including looping. + * + * @name Phaser.Tweens.Timeline#totalElapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalElapsed = 0; + + /** + * Time in ms/frames for the whole Timeline to play through once, excluding loop amounts and loop delays. + * + * @name Phaser.Tweens.Timeline#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * Value between 0 and 1. The amount of progress through the Timeline, _excluding loops_. + * + * @name Phaser.Tweens.Timeline#progress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.progress = 0; + + /** + * Time in ms/frames for all Tweens in this Timeline to complete (including looping) + * + * @name Phaser.Tweens.Timeline#totalDuration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalDuration = 0; + + /** + * Value between 0 and 1. The amount through the entire Timeline, including looping. + * + * @name Phaser.Tweens.Timeline#totalProgress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalProgress = 0; + + /** + * An object containing the different Tween callback functions. + * + * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. + * + * `onComplete` When the Timeline finishes playback fully or `Timeline.stop` is called. Never invoked if timeline is set to repeat infinitely. + * `onLoop` When a Timeline loops. + * `onStart` When the Timeline starts playing. + * `onUpdate` When a Timeline updates a child Tween. + * `onYoyo` When a Timeline starts a yoyo. + * + * @name Phaser.Tweens.Timeline#callbacks + * @type {object} + * @since 3.0.0 + */ + this.callbacks = { + onComplete: null, + onLoop: null, + onStart: null, + onUpdate: null, + onYoyo: null + }; + + /** + * The context in which all callbacks are invoked. + * + * @name Phaser.Tweens.Timeline#callbackScope + * @type {any} + * @since 3.0.0 + */ + this.callbackScope; + }, + + /** + * Internal method that will emit a Timeline based Event and invoke the given callback. + * + * @method Phaser.Tweens.Timeline#dispatchTimelineEvent + * @since 3.19.0 + * + * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. + * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. + */ + dispatchTimelineEvent: function (event, callback) + { + this.emit(event, this); + + if (callback) + { + callback.func.apply(callback.scope, callback.params); + } + }, + + /** + * Sets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. + * A value of 0.5 runs 50% slower, and so on. + * + * The value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. + * + * @method Phaser.Tweens.Timeline#setTimeScale + * @since 3.0.0 + * + * @param {number} value - The time scale value to set. + * + * @return {this} This Timeline object. + */ + setTimeScale: function (value) + { + this.timeScale = value; + + return this; + }, + + /** + * Gets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. + * A value of 0.5 runs 50% slower, and so on. + * + * @method Phaser.Tweens.Timeline#getTimeScale + * @since 3.0.0 + * + * @return {number} The value of the time scale applied to this Timeline. + */ + getTimeScale: function () + { + return this.timeScale; + }, + + /** + * Check whether or not the Timeline is playing. + * + * @method Phaser.Tweens.Timeline#isPlaying + * @since 3.0.0 + * + * @return {boolean} `true` if this Timeline is active, otherwise `false`. + */ + isPlaying: function () + { + return (this.state === TWEEN_CONST.ACTIVE); + }, + + /** + * Creates a new Tween, based on the given Tween Config, and adds it to this Timeline. + * + * @method Phaser.Tweens.Timeline#add + * @since 3.0.0 + * + * @param {(Phaser.Types.Tweens.TweenBuilderConfig|object)} config - The configuration object for the Tween. + * + * @return {this} This Timeline object. + */ + add: function (config) + { + return this.queue(TweenBuilder(this, config)); + }, + + /** + * Adds an existing Tween to this Timeline. + * + * @method Phaser.Tweens.Timeline#queue + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to be added to this Timeline. + * + * @return {this} This Timeline object. + */ + queue: function (tween) + { + if (!this.isPlaying()) + { + tween.parent = this; + tween.parentIsTimeline = true; + + this.data.push(tween); + + this.totalData = this.data.length; + } + + return this; + }, + + /** + * Checks whether a Tween has an offset value. + * + * @method Phaser.Tweens.Timeline#hasOffset + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to check. + * + * @return {boolean} `true` if the tween has a non-null offset. + */ + hasOffset: function (tween) + { + return (tween.offset !== null); + }, + + /** + * Checks whether the offset value is a number or a directive that is relative to previous tweens. + * + * @method Phaser.Tweens.Timeline#isOffsetAbsolute + * @since 3.0.0 + * + * @param {number} value - The offset value to be evaluated. + * + * @return {boolean} `true` if the result is a number, `false` if it is a directive like " -= 1000". + */ + isOffsetAbsolute: function (value) + { + return (typeof(value) === 'number'); + }, + + /** + * Checks if the offset is a relative value rather than an absolute one. + * If the value is just a number, this returns false. + * + * @method Phaser.Tweens.Timeline#isOffsetRelative + * @since 3.0.0 + * + * @param {string} value - The offset value to be evaluated. + * + * @return {boolean} `true` if the value is relative, i.e " -= 1000". If `false`, the offset is absolute. + */ + isOffsetRelative: function (value) + { + var t = typeof(value); + + if (t === 'string') + { + var op = value[0]; + + if (op === '-' || op === '+') + { + return true; + } + } + + return false; + }, + + /** + * Parses the relative offset value, returning a positive or negative number. + * + * @method Phaser.Tweens.Timeline#getRelativeOffset + * @since 3.0.0 + * + * @param {string} value - The relative offset, in the format of '-=500', for example. The first character determines whether it will be a positive or negative number. Spacing matters here. + * @param {number} base - The value to use as the offset. + * + * @return {number} The parsed offset value. + */ + getRelativeOffset: function (value, base) + { + var op = value[0]; + var num = parseFloat(value.substr(2)); + var result = base; + + switch (op) + { + case '+': + result += num; + break; + + case '-': + result -= num; + break; + } + + // Cannot ever be < 0 + return Math.max(0, result); + }, + + /** + * Calculates the total duration of the timeline. + * + * Computes all tween durations and returns the full duration of the timeline. + * + * The resulting number is stored in the timeline, not as a return value. + * + * @method Phaser.Tweens.Timeline#calcDuration + * @since 3.0.0 + */ + calcDuration: function () + { + var prevEnd = 0; + var totalDuration = 0; + var offsetDuration = 0; + + for (var i = 0; i < this.totalData; i++) + { + var tween = this.data[i]; + + tween.init(); + + if (this.hasOffset(tween)) + { + if (this.isOffsetAbsolute(tween.offset)) + { + // An actual number, so it defines the start point from the beginning of the timeline + tween.calculatedOffset = tween.offset; + + if (tween.offset === 0) + { + offsetDuration = 0; + } + } + else if (this.isOffsetRelative(tween.offset)) + { + // A relative offset (i.e. '-=1000', so starts at 'offset' ms relative to the PREVIOUS Tweens ending time) + tween.calculatedOffset = this.getRelativeOffset(tween.offset, prevEnd); + } + } + else + { + // Sequential + tween.calculatedOffset = offsetDuration; + } + + prevEnd = tween.totalDuration + tween.calculatedOffset; + + totalDuration += tween.totalDuration; + offsetDuration += tween.totalDuration; + } + + // Excludes loop values + this.duration = totalDuration; + + this.loopCounter = (this.loop === -1) ? 999999999999 : this.loop; + + if (this.loopCounter > 0) + { + this.totalDuration = this.duration + this.completeDelay + ((this.duration + this.loopDelay) * this.loopCounter); + } + else + { + this.totalDuration = this.duration + this.completeDelay; + } + }, + + /** + * Initializes the timeline, which means all Tweens get their init() called, and the total duration will be computed. + * Returns a boolean indicating whether the timeline is auto-started or not. + * + * @method Phaser.Tweens.Timeline#init + * @since 3.0.0 + * + * @return {boolean} `true` if the Timeline is started. `false` if it is paused. + */ + init: function () + { + this.calcDuration(); + + this.progress = 0; + this.totalProgress = 0; + + if (this.paused) + { + this.state = TWEEN_CONST.PAUSED; + + return false; + } + else + { + return true; + } + }, + + /** + * Resets all of the timeline's tweens back to their initial states. + * The boolean parameter indicates whether tweens that are looping should reset as well, or not. + * + * @method Phaser.Tweens.Timeline#resetTweens + * @since 3.0.0 + * + * @param {boolean} resetFromLoop - If `true`, resets all looping tweens to their initial values. + */ + resetTweens: function (resetFromLoop) + { + for (var i = 0; i < this.totalData; i++) + { + var tween = this.data[i]; + + tween.play(resetFromLoop); + } + }, + + /** + * Sets a callback for the Timeline. + * + * @method Phaser.Tweens.Timeline#setCallback + * @since 3.0.0 + * + * @param {string} type - The internal type of callback to set. + * @param {function} callback - Timeline allows multiple tweens to be linked together to create a streaming sequence. + * @param {array} [params] - The parameters to pass to the callback. + * @param {object} [scope] - The context scope of the callback. + * + * @return {this} This Timeline object. + */ + setCallback: function (type, callback, params, scope) + { + if (Timeline.TYPES.indexOf(type) !== -1) + { + this.callbacks[type] = { func: callback, scope: scope, params: params }; + } + + return this; + }, + + /** + * Passed a Tween to the Tween Manager and requests it be made active. + * + * @method Phaser.Tweens.Timeline#makeActive + * @since 3.3.0 + * + * @param {Phaser.Tweens.Tween} tween - The tween object to make active. + * + * @return {Phaser.Tweens.TweenManager} The Timeline's Tween Manager reference. + */ + makeActive: function (tween) + { + return this.manager.makeActive(tween); + }, + + /** + * Starts playing the Timeline. + * + * @method Phaser.Tweens.Timeline#play + * @fires Phaser.Tweens.Events#TIMELINE_START + * @since 3.0.0 + */ + play: function () + { + if (this.state === TWEEN_CONST.ACTIVE) + { + return; + } + + if (this.paused) + { + this.paused = false; + + this.manager.makeActive(this); + + return; + } + else + { + this.resetTweens(false); + + this.state = TWEEN_CONST.ACTIVE; + } + + this.dispatchTimelineEvent(Events.TIMELINE_START, this.callbacks.onStart); + }, + + /** + * Updates the Timeline's `state` and fires callbacks and events. + * + * @method Phaser.Tweens.Timeline#nextState + * @fires Phaser.Tweens.Events#TIMELINE_COMPLETE + * @fires Phaser.Tweens.Events#TIMELINE_LOOP + * @since 3.0.0 + * + * @see Phaser.Tweens.Timeline#update + */ + nextState: function () + { + if (this.loopCounter > 0) + { + // Reset the elapsed time + this.elapsed = 0; + this.progress = 0; + + this.loopCounter--; + + this.resetTweens(true); + + if (this.loopDelay > 0) + { + this.countdown = this.loopDelay; + + this.state = TWEEN_CONST.LOOP_DELAY; + } + else + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTimelineEvent(Events.TIMELINE_LOOP, this.callbacks.onLoop); + } + } + else if (this.completeDelay > 0) + { + this.state = TWEEN_CONST.COMPLETE_DELAY; + + this.countdown = this.completeDelay; + } + else + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTimelineEvent(Events.TIMELINE_COMPLETE, this.callbacks.onComplete); + } + }, + + /** + * Returns 'true' if this Timeline has finished and should be removed from the Tween Manager. + * Otherwise, returns false. + * + * @method Phaser.Tweens.Timeline#update + * @fires Phaser.Tweens.Events#TIMELINE_COMPLETE + * @fires Phaser.Tweens.Events#TIMELINE_UPDATE + * @since 3.0.0 + * + * @param {number} timestamp - 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} Returns `true` if this Timeline has finished and should be removed from the Tween Manager. + */ + update: function (timestamp, delta) + { + if (this.state === TWEEN_CONST.PAUSED) + { + return; + } + + if (this.useFrames) + { + delta = 1 * this.manager.timeScale; + } + + delta *= this.timeScale; + + this.elapsed += delta; + this.progress = Math.min(this.elapsed / this.duration, 1); + + this.totalElapsed += delta; + this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); + + switch (this.state) + { + case TWEEN_CONST.ACTIVE: + + var stillRunning = this.totalData; + + for (var i = 0; i < this.totalData; i++) + { + var tween = this.data[i]; + + if (tween.update(timestamp, delta)) + { + stillRunning--; + } + } + + this.dispatchTimelineEvent(Events.TIMELINE_UPDATE, this.callbacks.onUpdate); + + // Anything still running? If not, we're done + if (stillRunning === 0) + { + this.nextState(); + } + + break; + + case TWEEN_CONST.LOOP_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTimelineEvent(Events.TIMELINE_LOOP, this.callbacks.onLoop); + } + + break; + + case TWEEN_CONST.COMPLETE_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTimelineEvent(Events.TIMELINE_COMPLETE, this.callbacks.onComplete); + } + + break; + } + + return (this.state === TWEEN_CONST.PENDING_REMOVE); + }, + + /** + * Stops the Timeline immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. + * + * @method Phaser.Tweens.Timeline#stop + * @since 3.0.0 + */ + stop: function () + { + this.state = TWEEN_CONST.PENDING_REMOVE; + }, + + /** + * Pauses the Timeline, retaining its internal state. + * + * Calling this on a Timeline that is already paused has no effect and fires no event. + * + * @method Phaser.Tweens.Timeline#pause + * @fires Phaser.Tweens.Events#TIMELINE_PAUSE + * @since 3.0.0 + * + * @return {this} This Timeline object. + */ + pause: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + return; + } + + this.paused = true; + + this._pausedState = this.state; + + this.state = TWEEN_CONST.PAUSED; + + this.emit(Events.TIMELINE_PAUSE, this); + + return this; + }, + + /** + * Resumes a paused Timeline from where it was when it was paused. + * + * Calling this on a Timeline that isn't paused has no effect and fires no event. + * + * @method Phaser.Tweens.Timeline#resume + * @fires Phaser.Tweens.Events#TIMELINE_RESUME + * @since 3.0.0 + * + * @return {this} This Timeline object. + */ + resume: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + this.paused = false; + + this.state = this._pausedState; + + this.emit(Events.TIMELINE_RESUME, this); + } + + return this; + }, + + /** + * Checks if any of the Tweens in this Timeline as operating on the target object. + * + * Returns `false` if no Tweens operate on the target object. + * + * @method Phaser.Tweens.Timeline#hasTarget + * @since 3.0.0 + * + * @param {object} target - The target to check all Tweens against. + * + * @return {boolean} `true` if there is at least a single Tween that operates on the target object, otherwise `false`. + */ + hasTarget: function (target) + { + for (var i = 0; i < this.data.length; i++) + { + if (this.data[i].hasTarget(target)) + { + return true; + } + } + + return false; + }, + + /** + * Stops all the Tweens in the Timeline immediately, whatever stage of progress they are at and flags + * them for removal by the TweenManager. + * + * @method Phaser.Tweens.Timeline#destroy + * @since 3.0.0 + */ + destroy: function () + { + for (var i = 0; i < this.data.length; i++) + { + this.data[i].stop(); + } + } + +}); + +Timeline.TYPES = [ 'onStart', 'onUpdate', 'onLoop', 'onComplete', 'onYoyo' ]; + +module.exports = Timeline; + + +/***/ }), +/* 542 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +__webpack_require__(544); + +var CONST = __webpack_require__(32); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser + */ + +var Phaser = { + + Actions: __webpack_require__(259), + Animations: __webpack_require__(664), + BlendModes: __webpack_require__(43), + Cache: __webpack_require__(665), + Cameras: __webpack_require__(668), + Core: __webpack_require__(751), + Class: __webpack_require__(0), + Create: __webpack_require__(813), + Curves: __webpack_require__(819), + Data: __webpack_require__(822), + Display: __webpack_require__(824), + DOM: __webpack_require__(841), + Events: __webpack_require__(842), + Game: __webpack_require__(844), + GameObjects: __webpack_require__(942), + Geom: __webpack_require__(453), + Input: __webpack_require__(1224), + Loader: __webpack_require__(1258), + Math: __webpack_require__(181), + Physics: __webpack_require__(1284), + Plugins: __webpack_require__(1375), + Renderer: __webpack_require__(1377), + Scale: __webpack_require__(1382), + ScaleModes: __webpack_require__(157), + Scene: __webpack_require__(398), + Scenes: __webpack_require__(1383), + Structs: __webpack_require__(1385), + Textures: __webpack_require__(1386), + Tilemaps: __webpack_require__(1388), + Time: __webpack_require__(1429), + Tweens: __webpack_require__(1431), + Utils: __webpack_require__(1448) + +}; + +// Merge in the optional plugins + +if (true) +{ + Phaser.Sound = __webpack_require__(1458); +} + +if (false) +{} + +if (true) +{ + Phaser.FacebookInstantGamesPlugin = __webpack_require__(412); +} + +// Merge in the consts + +Phaser = Extend(false, Phaser, CONST); + +/** + * The root types namespace. + * + * @namespace Phaser.Types + * @since 3.17.0 + */ + +// Export it + +module.exports = Phaser; + +global.Phaser = Phaser; + +/* + * "Documentation is like pizza: when it is good, it is very, very good; + * and when it is bad, it is better than nothing." + * -- Dick Brandon + */ + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(543))) + +/***/ }), +/* 543 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 544 */ +/***/ (function(module, exports, __webpack_require__) { + +__webpack_require__(545); +__webpack_require__(546); +__webpack_require__(547); +__webpack_require__(548); +__webpack_require__(549); +__webpack_require__(550); +__webpack_require__(551); +__webpack_require__(552); + + +/***/ }), +/* 545 */ +/***/ (function(module, exports) { + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function (fun /*, thisArg */) + { + 'use strict'; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== 'function') + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + + +/***/ }), +/* 546 */ +/***/ (function(module, exports) { + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + + +/***/ }), +/* 547 */ +/***/ (function(module, exports) { + +/* Copyright 2013 Chris Wilson + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +/* + +This monkeypatch library is intended to be included in projects that are +written to the proper AudioContext spec (instead of webkitAudioContext), +and that use the new naming and proper bits of the Web Audio API (e.g. +using BufferSourceNode.start() instead of BufferSourceNode.noteOn()), but may +have to run on systems that only support the deprecated bits. + +This library should be harmless to include if the browser supports +unprefixed "AudioContext", and/or if it supports the new names. + +The patches this library handles: +if window.AudioContext is unsupported, it will be aliased to webkitAudioContext(). +if AudioBufferSourceNode.start() is unimplemented, it will be routed to noteOn() or +noteGrainOn(), depending on parameters. + +The following aliases only take effect if the new names are not already in place: + +AudioBufferSourceNode.stop() is aliased to noteOff() +AudioContext.createGain() is aliased to createGainNode() +AudioContext.createDelay() is aliased to createDelayNode() +AudioContext.createScriptProcessor() is aliased to createJavaScriptNode() +AudioContext.createPeriodicWave() is aliased to createWaveTable() +OscillatorNode.start() is aliased to noteOn() +OscillatorNode.stop() is aliased to noteOff() +OscillatorNode.setPeriodicWave() is aliased to setWaveTable() +AudioParam.setTargetAtTime() is aliased to setTargetValueAtTime() + +This library does NOT patch the enumerated type changes, as it is +recommended in the specification that implementations support both integer +and string types for AudioPannerNode.panningModel, AudioPannerNode.distanceModel +BiquadFilterNode.type and OscillatorNode.type. + +*/ + +(function () { + + function fixSetTarget(param) { + if (!param) // if NYI, just return + return; + if (!param.setTargetAtTime) + param.setTargetAtTime = param.setTargetValueAtTime; + } + + if (window.hasOwnProperty('webkitAudioContext') && + !window.hasOwnProperty('AudioContext')) { + window.AudioContext = webkitAudioContext; + + if (!AudioContext.prototype.hasOwnProperty('createGain')) + AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; + if (!AudioContext.prototype.hasOwnProperty('createDelay')) + AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; + if (!AudioContext.prototype.hasOwnProperty('createScriptProcessor')) + AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode; + if (!AudioContext.prototype.hasOwnProperty('createPeriodicWave')) + AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; + + + AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain; + AudioContext.prototype.createGain = function() { + var node = this.internal_createGain(); + fixSetTarget(node.gain); + return node; + }; + + AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay; + AudioContext.prototype.createDelay = function(maxDelayTime) { + var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay(); + fixSetTarget(node.delayTime); + return node; + }; + + AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource; + AudioContext.prototype.createBufferSource = function() { + var node = this.internal_createBufferSource(); + if (!node.start) { + node.start = function ( when, offset, duration ) { + if ( offset || duration ) + this.noteGrainOn( when || 0, offset, duration ); + else + this.noteOn( when || 0 ); + }; + } else { + node.internal_start = node.start; + node.start = function( when, offset, duration ) { + if( typeof duration !== 'undefined' ) + node.internal_start( when || 0, offset, duration ); + else + node.internal_start( when || 0, offset || 0 ); + }; + } + if (!node.stop) { + node.stop = function ( when ) { + this.noteOff( when || 0 ); + }; + } else { + node.internal_stop = node.stop; + node.stop = function( when ) { + node.internal_stop( when || 0 ); + }; + } + fixSetTarget(node.playbackRate); + return node; + }; + + AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor; + AudioContext.prototype.createDynamicsCompressor = function() { + var node = this.internal_createDynamicsCompressor(); + fixSetTarget(node.threshold); + fixSetTarget(node.knee); + fixSetTarget(node.ratio); + fixSetTarget(node.reduction); + fixSetTarget(node.attack); + fixSetTarget(node.release); + return node; + }; + + AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter; + AudioContext.prototype.createBiquadFilter = function() { + var node = this.internal_createBiquadFilter(); + fixSetTarget(node.frequency); + fixSetTarget(node.detune); + fixSetTarget(node.Q); + fixSetTarget(node.gain); + return node; + }; + + if (AudioContext.prototype.hasOwnProperty( 'createOscillator' )) { + AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator; + AudioContext.prototype.createOscillator = function() { + var node = this.internal_createOscillator(); + if (!node.start) { + node.start = function ( when ) { + this.noteOn( when || 0 ); + }; + } else { + node.internal_start = node.start; + node.start = function ( when ) { + node.internal_start( when || 0); + }; + } + if (!node.stop) { + node.stop = function ( when ) { + this.noteOff( when || 0 ); + }; + } else { + node.internal_stop = node.stop; + node.stop = function( when ) { + node.internal_stop( when || 0 ); + }; + } + if (!node.setPeriodicWave) + node.setPeriodicWave = node.setWaveTable; + fixSetTarget(node.frequency); + fixSetTarget(node.detune); + return node; + }; + } + } + + if (window.hasOwnProperty('webkitOfflineAudioContext') && + !window.hasOwnProperty('OfflineAudioContext')) { + window.OfflineAudioContext = webkitOfflineAudioContext; + } + +})(); + + +/***/ }), +/* 548 */ +/***/ (function(module, exports) { + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + + +/***/ }), +/* 549 */ +/***/ (function(module, exports) { + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + + +/***/ }), +/* 550 */ +/***/ (function(module, exports) { + +/** + * performance.now + */ +(function () { + + if ('performance' in window === false) + { + window.performance = {}; + } + + // Thanks IE8 + Date.now = (Date.now || function () { + return new Date().getTime(); + }); + + if ('now' in window.performance === false) + { + var nowOffset = Date.now(); + + if (performance.timing && performance.timing.navigationStart) + { + nowOffset = performance.timing.navigationStart; + } + + window.performance.now = function now () + { + return Date.now() - nowOffset; + } + } + +})(); + + +/***/ }), +/* 551 */ +/***/ (function(module, exports) { + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// requestAnimationFrame +var lastTime = Date.now(); + +var vendors = [ 'ms', 'moz', 'webkit', 'o' ]; + +for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) +{ + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; +} + +if (!window.requestAnimationFrame) +{ + window.requestAnimationFrame = function (callback) + { + if (typeof callback !== 'function') + { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = 16 + lastTime - currentTime; + + if (delay < 0) + { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!window.cancelAnimationFrame) +{ + window.cancelAnimationFrame = function(id) + { + clearTimeout(id); + }; +} + + +/***/ }), +/* 552 */ +/***/ (function(module, exports) { + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'object') +{ + var CheapArray = function (fakeType) + { + var proto = new Array(); // jshint ignore:line + + window[fakeType] = function(arg) { + + if (typeof(arg) === 'number') + { + Array.call(this, arg); + + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[fakeType].prototype = proto; + window[fakeType].constructor = window[fakeType]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + + +/***/ }), +/* 553 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var QuickSet = __webpack_require__(260); + +/** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. + * + * The first item isn't moved. The second item is aligned next to the first, then the third next to the second, and so on. + * + * @function Phaser.Actions.AlignTo + * @since 3.22.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 {integer} position - The position to align the items with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. + * @param {number} [offsetX=0] - Optional horizontal offset from the position. + * @param {number} [offsetY=0] - Optional vertical offset from the position. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var AlignTo = function (items, position, offsetX, offsetY) +{ + var target = items[0]; + + for (var i = 1; i < items.length; i++) + { + var item = items[i]; + + QuickSet(item, target, position, offsetX, offsetY); + + target = item; + } + + return items; +}; + +module.exports = AlignTo; + + +/***/ }), +/* 554 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `angle` property, + * and then adds the given value to each of their `angle` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `Angle(group.getChildren(), value, step)` + * + * @function Phaser.Actions.Angle + * @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 {number} value - The amount to be added to the `angle` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var Angle = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'angle', value, step, index, direction); +}; + +module.exports = Angle; + + +/***/ }), +/* 555 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of objects and passes each of them to the given callback. + * + * @function Phaser.Actions.Call + * @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.CallCallback} callback - The callback to be invoked. It will be passed just one argument: the item from the array. + * @param {*} context - The scope in which the callback will be invoked. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that was passed to this Action. + */ +var Call = function (items, callback, context) +{ + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + + callback.call(context, item); + } + + return items; +}; + +module.exports = Call; + + +/***/ }), +/* 556 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of objects and returns the first element in the array that has properties which match + * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` + * then it would return the first item which had the property `scaleX` set to 0.5 and `alpha` set to 1. + * + * To use this with a Group: `GetFirst(group.getChildren(), compare, index)` + * + * @function Phaser.Actions.GetFirst + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items] + * + * @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be searched by this action. + * @param {object} compare - The comparison object. Each property in this object will be checked against the items of the array. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * + * @return {?(object|Phaser.GameObjects.GameObject)} The first object in the array that matches the comparison object, or `null` if no match was found. + */ +var GetFirst = function (items, compare, index) +{ + if (index === undefined) { index = 0; } + + for (var i = index; i < items.length; i++) + { + var item = items[i]; + + var match = true; + + for (var property in compare) + { + if (item[property] !== compare[property]) + { + match = false; + } + } + + if (match) + { + return item; + } + } + + return null; +}; + +module.exports = GetFirst; + + +/***/ }), +/* 557 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of objects and returns the last element in the array that has properties which match + * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` + * then it would return the last item which had the property `scaleX` set to 0.5 and `alpha` set to 1. + * + * To use this with a Group: `GetLast(group.getChildren(), compare, index)` + * + * @function Phaser.Actions.GetLast + * @since 3.3.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items] + * + * @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be searched by this action. + * @param {object} compare - The comparison object. Each property in this object will be checked against the items of the array. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * + * @return {?(object|Phaser.GameObjects.GameObject)} The last object in the array that matches the comparison object, or `null` if no match was found. + */ +var GetLast = function (items, compare, index) +{ + if (index === undefined) { index = 0; } + + for (var i = index; i < items.length; i++) + { + var item = items[i]; + + var match = true; + + for (var property in compare) + { + if (item[property] !== compare[property]) + { + match = false; + } + } + + if (match) + { + return item; + } + } + + return null; +}; + +module.exports = GetLast; + + +/***/ }), +/* 558 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AlignIn = __webpack_require__(273); +var CONST = __webpack_require__(97); +var GetFastValue = __webpack_require__(1); +var NOOP = __webpack_require__(2); +var Zone = __webpack_require__(118); + +var tempZone = new Zone({ sys: { queueDepthSort: NOOP, events: { once: NOOP } } }, 0, 0, 1, 1); + +/** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, + * and then aligns them based on the grid configuration given to this action. + * + * @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. + */ +var GridAlign = function (items, options) +{ + if (options === undefined) { options = {}; } + + var widthSet = options.hasOwnProperty('width'); + var heightSet = options.hasOwnProperty('height'); + + var width = GetFastValue(options, 'width', -1); + var height = GetFastValue(options, 'height', -1); + + var cellWidth = GetFastValue(options, 'cellWidth', 1); + var cellHeight = GetFastValue(options, 'cellHeight', cellWidth); + + var position = GetFastValue(options, 'position', CONST.TOP_LEFT); + var x = GetFastValue(options, 'x', 0); + var y = GetFastValue(options, 'y', 0); + + var cx = 0; + var cy = 0; + var w = (width * cellWidth); + var h = (height * cellHeight); + + tempZone.setPosition(x, y); + tempZone.setSize(cellWidth, cellHeight); + + for (var i = 0; i < items.length; i++) + { + AlignIn(items[i], tempZone, position); + + if (widthSet && width === -1) + { + // We keep laying them out horizontally until we've done them all + tempZone.x += cellWidth; + } + else if (heightSet && height === -1) + { + // We keep laying them out vertically until we've done them all + tempZone.y += cellHeight; + } + else + { + // We keep laying them out until we hit the column limit + cx += cellWidth; + tempZone.x += cellWidth; + + if (cx === w) + { + cx = 0; + cy += cellHeight; + tempZone.x = x; + tempZone.y += cellHeight; + + if (cy === h) + { + // We've hit the column limit, so return, even if there are items left + break; + } + } + } + } + + return items; +}; + +module.exports = GridAlign; + + +/***/ }), +/* 559 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); + +// bitmask flag for GameObject.renderMask +var _FLAG = 2; // 0010 + +/** + * Provides methods used for setting the alpha properties of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Alpha + * @since 3.0.0 + */ + +var Alpha = { + + /** + * Private internal value. Holds the global alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alpha + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alpha: 1, + + /** + * Private internal value. Holds the top-left alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaTL + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaTL: 1, + + /** + * Private internal value. Holds the top-right alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaTR + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaTR: 1, + + /** + * Private internal value. Holds the bottom-left alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaBL + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaBL: 1, + + /** + * Private internal value. Holds the bottom-right alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaBR + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaBR: 1, + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + * + * @method Phaser.GameObjects.Components.Alpha#clearAlpha + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + clearAlpha: function () + { + return this.setAlpha(1); + }, + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * + * @method Phaser.GameObjects.Components.Alpha#setAlpha + * @since 3.0.0 + * + * @param {number} [topLeft=1] - The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. + * @param {number} [topRight] - The alpha value used for the top-right of the Game Object. WebGL only. + * @param {number} [bottomLeft] - The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param {number} [bottomRight] - The alpha value used for the bottom-right of the Game Object. WebGL only. + * + * @return {this} This Game Object instance. + */ + setAlpha: function (topLeft, topRight, bottomLeft, bottomRight) + { + if (topLeft === undefined) { topLeft = 1; } + + // Treat as if there is only one alpha value for the whole Game Object + if (topRight === undefined) + { + this.alpha = topLeft; + } + else + { + this._alphaTL = Clamp(topLeft, 0, 1); + this._alphaTR = Clamp(topRight, 0, 1); + this._alphaBL = Clamp(bottomLeft, 0, 1); + this._alphaBR = Clamp(bottomRight, 0, 1); + } + + return this; + }, + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + * + * @name Phaser.GameObjects.Components.Alpha#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this._alpha; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alpha = v; + this._alphaTL = v; + this._alphaTR = v; + this._alphaBL = v; + this._alphaBR = v; + + if (v === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaTopLeft + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaTopLeft: { + + get: function () + { + return this._alphaTL; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaTL = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaTopRight + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaTopRight: { + + get: function () + { + return this._alphaTR; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaTR = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaBottomLeft + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaBottomLeft: { + + get: function () + { + return this._alphaBL; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaBL = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaBottomRight + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaBottomRight: { + + get: function () + { + return this._alphaBR; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaBR = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + } + +}; + +module.exports = Alpha; + + +/***/ }), +/* 560 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Add Animation Event. + * + * This event is dispatched when a new animation is added to the global Animation Manager. + * + * This can happen either as a result of an animation instance being added to the Animation Manager, + * or the Animation Manager creating a new animation directly. + * + * @event Phaser.Animations.Events#ADD_ANIMATION + * @since 3.0.0 + * + * @param {string} key - The key of the Animation that was added to the global Animation Manager. + * @param {Phaser.Animations.Animation} animation - An instance of the newly created Animation. + */ +module.exports = 'add'; + + +/***/ }), +/* 561 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Complete Event. + * + * This event is dispatched by an Animation instance when it completes, i.e. finishes playing or is manually stopped. + * + * Be careful with the volume of events this could generate. If a group of Sprites all complete the same + * animation at the same time, this event will invoke its handler for each one of them. + * + * @event Phaser.Animations.Events#ANIMATION_COMPLETE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. + */ +module.exports = 'complete'; + + +/***/ }), +/* 562 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Repeat Event. + * + * This event is dispatched when a currently playing animation repeats. + * + * The event is dispatched directly from the Animation object itself. Which means that listeners + * bound to this event will be invoked every time the Animation repeats, for every Game Object that may have it. + * + * @event Phaser.Animations.Events#ANIMATION_REPEAT + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that repeated. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation was on when it repeated. + */ +module.exports = 'repeat'; + + +/***/ }), +/* 563 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Restart Event. + * + * This event is dispatched by an Animation instance when it restarts. + * + * Be careful with the volume of events this could generate. If a group of Sprites all restart the same + * animation at the same time, this event will invoke its handler for each one of them. + * + * @event Phaser.Animations.Events#ANIMATION_RESTART + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that restarted playing. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. + */ +module.exports = 'restart'; + + +/***/ }), +/* 564 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Start Event. + * + * This event is dispatched by an Animation instance when it starts playing. + * + * Be careful with the volume of events this could generate. If a group of Sprites all play the same + * animation at the same time, this event will invoke its handler for each one of them. + * + * @event Phaser.Animations.Events#ANIMATION_START + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that started playing. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. + */ +module.exports = 'start'; + + +/***/ }), +/* 565 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pause All Animations Event. + * + * This event is dispatched when the global Animation Manager is told to pause. + * + * When this happens all current animations will stop updating, although it doesn't necessarily mean + * that the game has paused as well. + * + * @event Phaser.Animations.Events#PAUSE_ALL + * @since 3.0.0 + */ +module.exports = 'pauseall'; + + +/***/ }), +/* 566 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Remove Animation Event. + * + * This event is dispatched when an animation is removed from the global Animation Manager. + * + * @event Phaser.Animations.Events#REMOVE_ANIMATION + * @since 3.0.0 + * + * @param {string} key - The key of the Animation that was removed from the global Animation Manager. + * @param {Phaser.Animations.Animation} animation - An instance of the removed Animation. + */ +module.exports = 'remove'; + + +/***/ }), +/* 567 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Resume All Animations Event. + * + * This event is dispatched when the global Animation Manager resumes, having been previously paused. + * + * When this happens all current animations will continue updating again. + * + * @event Phaser.Animations.Events#RESUME_ALL + * @since 3.0.0 + */ +module.exports = 'resumeall'; + + +/***/ }), +/* 568 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Complete Event. + * + * This event is dispatched by a Sprite when an animation finishes playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationcomplete', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_COMPLETE` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_COMPLETE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. + */ +module.exports = 'animationcomplete'; + + +/***/ }), +/* 569 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Complete Event. + * + * This event is dispatched by a Sprite when a specific animation finishes playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationcomplete-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationcomplete-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_COMPLETE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. + */ +module.exports = 'animationcomplete-'; + + +/***/ }), +/* 570 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Repeat Event. + * + * This event is dispatched by a Sprite when a specific animation repeats playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrepeat-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrepeat-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that is repeating on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {integer} repeatCount - The number of times the Animation has repeated so far. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation repeated playing. + */ +module.exports = 'animationrepeat-'; + + +/***/ }), +/* 571 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Restart Event. + * + * This event is dispatched by a Sprite when a specific animation restarts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrestart-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrestart-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_RESTART + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was restarted on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. + */ +module.exports = 'animationrestart-'; + + +/***/ }), +/* 572 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Start Event. + * + * This event is dispatched by a Sprite when a specific animation starts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationstart-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationstart-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_START + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was started on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. + */ +module.exports = 'animationstart-'; + + +/***/ }), +/* 573 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Update Event. + * + * This event is dispatched by a Sprite when a specific animation playing on it updates. This happens when the animation changes frame, + * based on the animation frame rate and other factors like `timeScale` and `delay`. + * + * Listen for it on the Sprite using `sprite.on('animationupdate-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationupdate-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_UPDATE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated on the Sprite. + * @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. + */ +module.exports = 'animationupdate-'; + + +/***/ }), +/* 574 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Repeat Event. + * + * This event is dispatched by a Sprite when an animation repeats playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrepeat', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_REPEAT` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_REPEAT + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that is repeating on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {integer} repeatCount - The number of times the Animation has repeated so far. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation repeated playing. + */ +module.exports = 'animationrepeat'; + + +/***/ }), +/* 575 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Restart Event. + * + * This event is dispatched by a Sprite when an animation restarts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrestart', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_RESTART` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_RESTART + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was restarted on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. + */ +module.exports = 'animationrestart'; + + +/***/ }), +/* 576 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Start Event. + * + * This event is dispatched by a Sprite when an animation starts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationstart', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_START` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_START + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was started on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. + */ +module.exports = 'animationstart'; + + +/***/ }), +/* 577 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Update Event. + * + * This event is dispatched by a Sprite when an animation playing on it updates. This happens when the animation changes frame, + * based on the animation frame rate and other factors like `timeScale` and `delay`. + * + * Listen for it on the Sprite using `sprite.on('animationupdate', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_UPDATE` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_UPDATE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated on the Sprite. + * @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. + */ +module.exports = 'animationupdate'; + + +/***/ }), +/* 578 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for calculating and setting the size of a non-Frame based Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.ComputedSize + * @since 3.0.0 + */ + +var ComputedSize = { + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + * + * @name Phaser.GameObjects.Components.ComputedSize#width + * @type {number} + * @since 3.0.0 + */ + width: 0, + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + * + * @name Phaser.GameObjects.Components.ComputedSize#height + * @type {number} + * @since 3.0.0 + */ + height: 0, + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.ComputedSize#displayWidth + * @type {number} + * @since 3.0.0 + */ + displayWidth: { + + get: function () + { + return this.scaleX * this.width; + }, + + set: function (value) + { + this.scaleX = value / this.width; + } + + }, + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.ComputedSize#displayHeight + * @type {number} + * @since 3.0.0 + */ + displayHeight: { + + get: function () + { + return this.scaleY * this.height; + }, + + set: function (value) + { + this.scaleY = value / this.height; + } + + }, + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * + * @method Phaser.GameObjects.Components.ComputedSize#setSize + * @since 3.4.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + this.width = width; + this.height = height; + + return this; + }, + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * + * @method Phaser.GameObjects.Components.ComputedSize#setDisplaySize + * @since 3.4.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setDisplaySize: function (width, height) + { + this.displayWidth = width; + this.displayHeight = height; + + return this; + } + +}; + +module.exports = ComputedSize; + + +/***/ }), +/* 579 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the texture of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Crop + * @since 3.12.0 + */ + +var Crop = { + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Crop#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + texture: null, + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Crop#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + frame: null, + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + * + * @name Phaser.GameObjects.Components.Crop#isCropped + * @type {boolean} + * @since 3.11.0 + */ + isCropped: false, + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * + * @method Phaser.GameObjects.Components.Crop#setCrop + * @since 3.11.0 + * + * @param {(number|Phaser.Geom.Rectangle)} [x] - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param {number} [y] - The y coordinate to start the crop from. + * @param {number} [width] - The width of the crop rectangle in pixels. + * @param {number} [height] - The height of the crop rectangle in pixels. + * + * @return {this} This Game Object instance. + */ + setCrop: function (x, y, width, height) + { + if (x === undefined) + { + this.isCropped = false; + } + else if (this.frame) + { + if (typeof x === 'number') + { + this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY); + } + else + { + var rect = x; + + this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY); + } + + this.isCropped = true; + } + + return this; + }, + + /** + * Internal method that returns a blank, well-formed crop object for use by a Game Object. + * + * @method Phaser.GameObjects.Components.Crop#resetCropObject + * @private + * @since 3.12.0 + * + * @return {object} The crop object. + */ + resetCropObject: function () + { + return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 }; + } + +}; + +module.exports = Crop; + + +/***/ }), +/* 580 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for visually flipping a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Flip + * @since 3.0.0 + */ + +var Flip = { + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Components.Flip#flipX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + flipX: false, + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Components.Flip#flipY + * @type {boolean} + * @default false + * @since 3.0.0 + */ + flipY: false, + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @method Phaser.GameObjects.Components.Flip#toggleFlipX + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + toggleFlipX: function () + { + this.flipX = !this.flipX; + + return this; + }, + + /** + * Toggles the vertical flipped state of this Game Object. + * + * @method Phaser.GameObjects.Components.Flip#toggleFlipY + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + toggleFlipY: function () + { + this.flipY = !this.flipY; + + return this; + }, + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @method Phaser.GameObjects.Components.Flip#setFlipX + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Game Object instance. + */ + setFlipX: function (value) + { + this.flipX = value; + + return this; + }, + + /** + * Sets the vertical flipped state of this Game Object. + * + * @method Phaser.GameObjects.Components.Flip#setFlipY + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Game Object instance. + */ + setFlipY: function (value) + { + this.flipY = value; + + return this; + }, + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @method Phaser.GameObjects.Components.Flip#setFlip + * @since 3.0.0 + * + * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Game Object instance. + */ + setFlip: function (x, y) + { + this.flipX = x; + this.flipY = y; + + return this; + }, + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + * + * @method Phaser.GameObjects.Components.Flip#resetFlip + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + resetFlip: function () + { + this.flipX = false; + this.flipY = false; + + return this; + } + +}; + +module.exports = Flip; + + +/***/ }), +/* 581 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); +var RotateAround = __webpack_require__(295); +var Vector2 = __webpack_require__(3); + +/** + * Provides methods used for obtaining the bounds of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.GetBounds + * @since 3.0.0 + */ + +var GetBounds = { + + /** + * Processes the bounds output vector before returning it. + * + * @method Phaser.GameObjects.Components.GetBounds#prepareBoundsOutput + * @private + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} output - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + prepareBoundsOutput: function (output, includeParent) + { + if (includeParent === undefined) { includeParent = false; } + + if (this.rotation !== 0) + { + RotateAround(output, this.x, this.y, this.rotation); + } + + if (includeParent && this.parentContainer) + { + var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); + + parentMatrix.transformPoint(output.x, output.y, output); + } + + return output; + }, + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getCenter + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getCenter: function (output) + { + if (output === undefined) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX) + (this.displayWidth / 2); + output.y = this.y - (this.displayHeight * this.originY) + (this.displayHeight / 2); + + return output; + }, + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getTopLeft + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getTopLeft: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX); + output.y = this.y - (this.displayHeight * this.originY); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getTopCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getTopCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + (this.displayWidth / 2); + output.y = this.y - (this.displayHeight * this.originY); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getTopRight + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getTopRight: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; + output.y = this.y - (this.displayHeight * this.originY); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getLeftCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getLeftCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX); + output.y = (this.y - (this.displayHeight * this.originY)) + (this.displayHeight / 2); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getRightCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getRightCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; + output.y = (this.y - (this.displayHeight * this.originY)) + (this.displayHeight / 2); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getBottomLeft + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getBottomLeft: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX); + output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getBottomCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getBottomCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + (this.displayWidth / 2); + output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getBottomRight + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getBottomRight: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; + output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * + * @method Phaser.GameObjects.Components.GetBounds#getBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [output,$return] + * + * @param {(Phaser.Geom.Rectangle|object)} [output] - An object to store the values in. If not provided a new Rectangle will be created. + * + * @return {(Phaser.Geom.Rectangle|object)} The values stored in the output object. + */ + getBounds: function (output) + { + if (output === undefined) { output = new Rectangle(); } + + // We can use the output object to temporarily store the x/y coords in: + + var TLx, TLy, TRx, TRy, BLx, BLy, BRx, BRy; + + // Instead of doing a check if parent container is + // defined per corner we only do it once. + if (this.parentContainer) + { + var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); + + this.getTopLeft(output); + parentMatrix.transformPoint(output.x, output.y, output); + + TLx = output.x; + TLy = output.y; + + this.getTopRight(output); + parentMatrix.transformPoint(output.x, output.y, output); + + TRx = output.x; + TRy = output.y; + + this.getBottomLeft(output); + parentMatrix.transformPoint(output.x, output.y, output); + + BLx = output.x; + BLy = output.y; + + this.getBottomRight(output); + parentMatrix.transformPoint(output.x, output.y, output); + + BRx = output.x; + BRy = output.y; + } + else + { + this.getTopLeft(output); + + TLx = output.x; + TLy = output.y; + + this.getTopRight(output); + + TRx = output.x; + TRy = output.y; + + this.getBottomLeft(output); + + BLx = output.x; + BLy = output.y; + + this.getBottomRight(output); + + BRx = output.x; + BRy = output.y; + } + + output.x = Math.min(TLx, TRx, BLx, BRx); + output.y = Math.min(TLy, TRy, BLy, BRy); + output.width = Math.max(TLx, TRx, BLx, BRx) - output.x; + output.height = Math.max(TLy, TRy, BLy, BRy) - output.y; + + return output; + } + +}; + +module.exports = GetBounds; + + +/***/ }), +/* 582 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Blur Event. + * + * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded + * enters a blurred state. The blur event is raised when the window loses focus. This can happen if a user swaps + * tab, or if they simply remove focus from the browser to another app. + * + * @event Phaser.Core.Events#BLUR + * @since 3.0.0 + */ +module.exports = 'blur'; + + +/***/ }), +/* 583 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Boot Event. + * + * This event is dispatched when the Phaser Game instance has finished booting, but before it is ready to start running. + * The global systems use this event to know when to set themselves up, dispatching their own `ready` events as required. + * + * @event Phaser.Core.Events#BOOT + * @since 3.0.0 + */ +module.exports = 'boot'; + + +/***/ }), +/* 584 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Context Lost Event. + * + * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Lost event from the browser. + * + * The partner event is `CONTEXT_RESTORED`. + * + * @event Phaser.Core.Events#CONTEXT_LOST + * @since 3.19.0 + */ +module.exports = 'contextlost'; + + +/***/ }), +/* 585 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Context Restored Event. + * + * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Restored event from the browser. + * + * The partner event is `CONTEXT_LOST`. + * + * @event Phaser.Core.Events#CONTEXT_RESTORED + * @since 3.19.0 + */ +module.exports = 'contextrestored'; + + +/***/ }), +/* 586 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Destroy Event. + * + * This event is dispatched when the game instance has been told to destroy itself. + * Lots of internal systems listen to this event in order to clear themselves out. + * Custom plugins and game code should also do the same. + * + * @event Phaser.Core.Events#DESTROY + * @since 3.0.0 + */ +module.exports = 'destroy'; + + +/***/ }), +/* 587 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Focus Event. + * + * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded + * enters a focused state. The focus event is raised when the window re-gains focus, having previously lost it. + * + * @event Phaser.Core.Events#FOCUS + * @since 3.0.0 + */ +module.exports = 'focus'; + + +/***/ }), +/* 588 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Hidden Event. + * + * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded + * enters a hidden state. Only browsers that support the Visibility API will cause this event to be emitted. + * + * In most modern browsers, when the document enters a hidden state, the Request Animation Frame and setTimeout, which + * control the main game loop, will automatically pause. There is no way to stop this from happening. It is something + * your game should account for in its own code, should the pause be an issue (i.e. for multiplayer games) + * + * @event Phaser.Core.Events#HIDDEN + * @since 3.0.0 + */ +module.exports = 'hidden'; + + +/***/ }), +/* 589 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Pause Event. + * + * This event is dispatched when the Game loop enters a paused state, usually as a result of the Visibility Handler. + * + * @event Phaser.Core.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; + + +/***/ }), +/* 590 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Post-Render Event. + * + * This event is dispatched right at the end of the render process. + * + * Every Scene will have rendered and been drawn to the canvas by the time this event is fired. + * Use it for any last minute post-processing before the next game step begins. + * + * @event Phaser.Core.Events#POST_RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - A reference to the current renderer being used by the Game instance. + */ +module.exports = 'postrender'; + + +/***/ }), +/* 591 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'poststep'; + + +/***/ }), +/* 592 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Pre-Render Event. + * + * This event is dispatched immediately before any of the Scenes have started to render. + * + * The renderer will already have been initialized this frame, clearing itself and preparing to receive the Scenes for rendering, but it won't have actually drawn anything yet. + * + * @event Phaser.Core.Events#PRE_RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - A reference to the current renderer being used by the Game instance. + */ +module.exports = 'prerender'; + + +/***/ }), +/* 593 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'prestep'; + + +/***/ }), +/* 594 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Ready Event. + * + * This event is dispatched when the Phaser Game instance has finished booting, the Texture Manager is fully ready, + * and all local systems are now able to start. + * + * @event Phaser.Core.Events#READY + * @since 3.0.0 + */ +module.exports = 'ready'; + + +/***/ }), +/* 595 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Resume Event. + * + * This event is dispatched when the game loop leaves a paused state and resumes running. + * + * @event Phaser.Core.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; + + +/***/ }), +/* 596 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'step'; + + +/***/ }), +/* 597 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Visible Event. + * + * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded + * enters a visible state, previously having been hidden. + * + * Only browsers that support the Visibility API will cause this event to be emitted. + * + * @event Phaser.Core.Events#VISIBLE + * @since 3.0.0 + */ +module.exports = 'visible'; + + +/***/ }), +/* 598 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the origin of a Game Object. + * Values are normalized, given in the range 0 to 1. + * Display values contain the calculated pixel values. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Origin + * @since 3.0.0 + */ + +var Origin = { + + /** + * A property indicating that a Game Object has this component. + * + * @name Phaser.GameObjects.Components.Origin#_originComponent + * @type {boolean} + * @private + * @default true + * @since 3.2.0 + */ + _originComponent: true, + + /** + * 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.Components.Origin#originX + * @type {number} + * @default 0.5 + * @since 3.0.0 + */ + originX: 0.5, + + /** + * 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.Components.Origin#originY + * @type {number} + * @default 0.5 + * @since 3.0.0 + */ + originY: 0.5, + + // private + read only + _displayOriginX: 0, + _displayOriginY: 0, + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + * + * @name Phaser.GameObjects.Components.Origin#displayOriginX + * @type {number} + * @since 3.0.0 + */ + displayOriginX: { + + get: function () + { + return this._displayOriginX; + }, + + set: function (value) + { + this._displayOriginX = value; + this.originX = value / this.width; + } + + }, + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + * + * @name Phaser.GameObjects.Components.Origin#displayOriginY + * @type {number} + * @since 3.0.0 + */ + displayOriginY: { + + get: function () + { + return this._displayOriginY; + }, + + set: function (value) + { + this._displayOriginY = value; + this.originY = value / this.height; + } + + }, + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * + * @method Phaser.GameObjects.Components.Origin#setOrigin + * @since 3.0.0 + * + * @param {number} [x=0.5] - The horizontal origin value. + * @param {number} [y=x] - The vertical origin value. If not defined it will be set to the value of `x`. + * + * @return {this} This Game Object instance. + */ + setOrigin: function (x, y) + { + if (x === undefined) { x = 0.5; } + if (y === undefined) { y = x; } + + this.originX = x; + this.originY = y; + + return this.updateDisplayOrigin(); + }, + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + * + * @method Phaser.GameObjects.Components.Origin#setOriginFromFrame + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + setOriginFromFrame: function () + { + if (!this.frame || !this.frame.customPivot) + { + return this.setOrigin(); + } + else + { + this.originX = this.frame.pivotX; + this.originY = this.frame.pivotY; + } + + return this.updateDisplayOrigin(); + }, + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * + * @method Phaser.GameObjects.Components.Origin#setDisplayOrigin + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal display origin value. + * @param {number} [y=x] - The vertical display origin value. If not defined it will be set to the value of `x`. + * + * @return {this} This Game Object instance. + */ + setDisplayOrigin: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.displayOriginX = x; + this.displayOriginY = y; + + return this; + }, + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + * + * @method Phaser.GameObjects.Components.Origin#updateDisplayOrigin + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + updateDisplayOrigin: function () + { + this._displayOriginX = this.originX * this.width; + this._displayOriginY = this.originY * this.height; + + return this; + } + +}; + +module.exports = Origin; + + +/***/ }), +/* 599 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DegToRad = __webpack_require__(40); +var GetBoolean = __webpack_require__(99); +var GetValue = __webpack_require__(5); +var TWEEN_CONST = __webpack_require__(100); +var Vector2 = __webpack_require__(3); + +/** + * Provides methods used for managing a Game Object following a Path. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.PathFollower + * @since 3.17.0 + */ + +var PathFollower = { + + /** + * The Path this PathFollower is following. It can only follow one Path at a time. + * + * @name Phaser.GameObjects.Components.PathFollower#path + * @type {Phaser.Curves.Path} + * @since 3.0.0 + */ + path: null, + + /** + * Should the PathFollower automatically rotate to point in the direction of the Path? + * + * @name Phaser.GameObjects.Components.PathFollower#rotateToPath + * @type {boolean} + * @default false + * @since 3.0.0 + */ + rotateToPath: false, + + /** + * If the PathFollower is rotating to match the Path (@see Phaser.GameObjects.PathFollower#rotateToPath) + * this value is added to the rotation value. This allows you to rotate objects to a path but control + * the angle of the rotation as well. + * + * @name Phaser.GameObjects.PathFollower#pathRotationOffset + * @type {number} + * @default 0 + * @since 3.0.0 + */ + pathRotationOffset: 0, + + /** + * An additional vector to add to the PathFollowers position, allowing you to offset it from the + * Path coordinates. + * + * @name Phaser.GameObjects.PathFollower#pathOffset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + pathOffset: null, + + /** + * A Vector2 that stores the current point of the path the follower is on. + * + * @name Phaser.GameObjects.PathFollower#pathVector + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + pathVector: null, + + /** + * The Tween used for following the Path. + * + * @name Phaser.GameObjects.PathFollower#pathTween + * @type {Phaser.Tweens.Tween} + * @since 3.0.0 + */ + pathTween: null, + + /** + * Settings for the PathFollower. + * + * @name Phaser.GameObjects.PathFollower#pathConfig + * @type {?Phaser.Types.GameObjects.PathFollower.PathConfig} + * @default null + * @since 3.0.0 + */ + pathConfig: null, + + /** + * Records the direction of the follower so it can change direction. + * + * @name Phaser.GameObjects.PathFollower#_prevDirection + * @type {integer} + * @private + * @since 3.0.0 + */ + _prevDirection: TWEEN_CONST.PLAYING_FORWARD, + + /** + * Set the Path that this PathFollower should follow. + * + * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. + * + * @method Phaser.GameObjects.Components.PathFollower#setPath + * @since 3.0.0 + * + * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path at a time. + * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config] - Settings for the PathFollower. + * + * @return {Phaser.GameObjects.PathFollower} This Game Object. + */ + setPath: function (path, config) + { + if (config === undefined) { config = this.pathConfig; } + + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.stop(); + } + + this.path = path; + + if (config) + { + this.startFollow(config); + } + + return this; + }, + + /** + * Set whether the PathFollower should automatically rotate to point in the direction of the Path. + * + * @method Phaser.GameObjects.Components.PathFollower#setRotateToPath + * @since 3.0.0 + * + * @param {boolean} value - Whether the PathFollower should automatically rotate to point in the direction of the Path. + * @param {number} [offset=0] - Rotation offset in degrees. + * + * @return {Phaser.GameObjects.PathFollower} This Game Object. + */ + setRotateToPath: function (value, offset) + { + if (offset === undefined) { offset = 0; } + + this.rotateToPath = value; + + this.pathRotationOffset = offset; + + return this; + }, + + /** + * Is this PathFollower actively following a Path or not? + * + * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. + * + * @method Phaser.GameObjects.Components.PathFollower#isFollowing + * @since 3.0.0 + * + * @return {boolean} `true` is this PathFollower is actively following a Path, otherwise `false`. + */ + isFollowing: function () + { + var tween = this.pathTween; + + return (tween && tween.isPlaying()); + }, + + /** + * Starts this PathFollower following its given Path. + * + * @method Phaser.GameObjects.Components.PathFollower#startFollow + * @since 3.3.0 + * + * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config={}] - The duration of the follow, or a PathFollower config object. + * @param {number} [startAt=0] - Optional start position of the follow, between 0 and 1. + * + * @return {Phaser.GameObjects.PathFollower} This Game Object. + */ + startFollow: function (config, startAt) + { + if (config === undefined) { config = {}; } + if (startAt === undefined) { startAt = 0; } + + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.stop(); + } + + if (typeof config === 'number') + { + config = { duration: config }; + } + + // Override in case they've been specified in the config + config.from = GetValue(config, 'from', 0); + config.to = GetValue(config, 'to', 1); + + var positionOnPath = GetBoolean(config, 'positionOnPath', false); + + this.rotateToPath = GetBoolean(config, 'rotateToPath', false); + this.pathRotationOffset = GetValue(config, 'rotationOffset', 0); + + // This works, but it's not an ideal way of doing it as the follower jumps position + var seek = GetValue(config, 'startAt', startAt); + + if (seek) + { + config.onStart = function (tween) + { + var tweenData = tween.data[0]; + tweenData.progress = seek; + tweenData.elapsed = tweenData.duration * seek; + var v = tweenData.ease(tweenData.progress); + tweenData.current = tweenData.start + ((tweenData.end - tweenData.start) * v); + tweenData.target[tweenData.key] = tweenData.current; + }; + } + + if (!this.pathOffset) + { + this.pathOffset = new Vector2(this.x, this.y); + } + + if (!this.pathVector) + { + this.pathVector = new Vector2(); + } + + this.pathTween = this.scene.sys.tweens.addCounter(config); + + // The starting point of the path, relative to this follower + this.path.getStartPoint(this.pathOffset); + + if (positionOnPath) + { + this.x = this.pathOffset.x; + this.y = this.pathOffset.y; + } + + this.pathOffset.x = this.x - this.pathOffset.x; + this.pathOffset.y = this.y - this.pathOffset.y; + + this._prevDirection = TWEEN_CONST.PLAYING_FORWARD; + + if (this.rotateToPath) + { + // Set the rotation now (in case the tween has a delay on it, etc) + var nextPoint = this.path.getPoint(0.1); + + this.rotation = Math.atan2(nextPoint.y - this.y, nextPoint.x - this.x) + DegToRad(this.pathRotationOffset); + } + + this.pathConfig = config; + + return this; + }, + + /** + * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the + * point on the Path at which you paused it. + * + * @method Phaser.GameObjects.Components.PathFollower#pauseFollow + * @since 3.3.0 + * + * @return {Phaser.GameObjects.PathFollower} This Game Object. + */ + pauseFollow: function () + { + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.pause(); + } + + return this; + }, + + /** + * Resumes a previously paused PathFollower. + * + * If the PathFollower was not paused this has no effect. + * + * @method Phaser.GameObjects.Components.PathFollower#resumeFollow + * @since 3.3.0 + * + * @return {Phaser.GameObjects.PathFollower} This Game Object. + */ + resumeFollow: function () + { + var tween = this.pathTween; + + if (tween && tween.isPaused()) + { + tween.resume(); + } + + return this; + }, + + /** + * Stops this PathFollower from following the path any longer. + * + * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. + * + * @method Phaser.GameObjects.Components.PathFollower#stopFollow + * @since 3.3.0 + * + * @return {Phaser.GameObjects.PathFollower} This Game Object. + */ + stopFollow: function () + { + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.stop(); + } + + return this; + }, + + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + * + * @method Phaser.GameObjects.Components.PathFollower#pathUpdate + * @since 3.17.0 + */ + pathUpdate: function () + { + var tween = this.pathTween; + + if (tween) + { + var tweenData = tween.data[0]; + var pathVector = this.pathVector; + + if (tweenData.state !== TWEEN_CONST.COMPLETE) + { + this.path.getPoint(1, pathVector); + + pathVector.add(this.pathOffset); + + this.setPosition(pathVector.x, pathVector.y); + + return; + } + else if (tweenData.state !== TWEEN_CONST.PLAYING_FORWARD && tweenData.state !== TWEEN_CONST.PLAYING_BACKWARD) + { + // If delayed, etc then bail out + return; + } + + this.path.getPoint(tween.getValue(), pathVector); + + pathVector.add(this.pathOffset); + + var oldX = this.x; + var oldY = this.y; + + this.setPosition(pathVector.x, pathVector.y); + + var speedX = this.x - oldX; + var speedY = this.y - oldY; + + if (speedX === 0 && speedY === 0) + { + // Bail out early + return; + } + + if (tweenData.state !== this._prevDirection) + { + // We've changed direction, so don't do a rotate this frame + this._prevDirection = tweenData.state; + + return; + } + + if (this.rotateToPath) + { + this.rotation = Math.atan2(speedY, speedX) + DegToRad(this.pathRotationOffset); + } + } + } + +}; + +module.exports = PathFollower; + + +/***/ }), +/* 600 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the size of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Size + * @since 3.0.0 + */ + +var Size = { + + /** + * A property indicating that a Game Object has this component. + * + * @name Phaser.GameObjects.Components.Size#_sizeComponent + * @type {boolean} + * @private + * @default true + * @since 3.2.0 + */ + _sizeComponent: true, + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + * + * @name Phaser.GameObjects.Components.Size#width + * @type {number} + * @since 3.0.0 + */ + width: 0, + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + * + * @name Phaser.GameObjects.Components.Size#height + * @type {number} + * @since 3.0.0 + */ + height: 0, + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.Size#displayWidth + * @type {number} + * @since 3.0.0 + */ + displayWidth: { + + get: function () + { + return Math.abs(this.scaleX * this.frame.realWidth); + }, + + set: function (value) + { + this.scaleX = value / this.frame.realWidth; + } + + }, + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.Size#displayHeight + * @type {number} + * @since 3.0.0 + */ + displayHeight: { + + get: function () + { + return Math.abs(this.scaleY * this.frame.realHeight); + }, + + set: function (value) + { + this.scaleY = value / this.frame.realHeight; + } + + }, + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * + * @method Phaser.GameObjects.Components.Size#setSizeToFrame + * @since 3.0.0 + * + * @param {Phaser.Textures.Frame} frame - The frame to base the size of this Game Object on. + * + * @return {this} This Game Object instance. + */ + setSizeToFrame: function (frame) + { + if (frame === undefined) { frame = this.frame; } + + this.width = frame.realWidth; + this.height = frame.realHeight; + + return this; + }, + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * + * @method Phaser.GameObjects.Components.Size#setSize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + this.width = width; + this.height = height; + + return this; + }, + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * + * @method Phaser.GameObjects.Components.Size#setDisplaySize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setDisplaySize: function (width, height) + { + this.displayWidth = width; + this.displayHeight = height; + + return this; + } + +}; + +module.exports = Size; + + +/***/ }), +/* 601 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// bitmask flag for GameObject.renderMask +var _FLAG = 8; // 1000 + +/** + * Provides methods used for getting and setting the texture of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Texture + * @since 3.0.0 + */ + +var Texture = { + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Texture#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + texture: null, + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Texture#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + frame: null, + + /** + * Internal flag. Not to be set by this Game Object. + * + * @name Phaser.GameObjects.Components.Texture#isCropped + * @type {boolean} + * @private + * @since 3.11.0 + */ + isCropped: false, + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.Components.Texture#setTexture + * @since 3.0.0 + * + * @param {(string|Phaser.Textures.Texture)} key - The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setTexture: function (key, frame) + { + this.texture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * + * @method Phaser.GameObjects.Components.Texture#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * @param {boolean} [updateSize=true] - Should this call adjust the size of the Game Object? + * @param {boolean} [updateOrigin=true] - Should this call adjust the origin of the Game Object? + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame, updateSize, updateOrigin) + { + if (updateSize === undefined) { updateSize = true; } + if (updateOrigin === undefined) { updateOrigin = true; } + + this.frame = this.texture.get(frame); + + if (!this.frame.cutWidth || !this.frame.cutHeight) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + if (this._sizeComponent && updateSize) + { + this.setSizeToFrame(); + } + + if (this._originComponent && updateOrigin) + { + if (this.frame.customPivot) + { + this.setOrigin(this.frame.pivotX, this.frame.pivotY); + } + else + { + this.updateDisplayOrigin(); + } + } + + return this; + } + +}; + +module.exports = Texture; + + +/***/ }), +/* 602 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// bitmask flag for GameObject.renderMask +var _FLAG = 8; // 1000 + +/** + * Provides methods used for getting and setting the texture of a Game Object. + * + * @namespace Phaser.GameObjects.Components.TextureCrop + * @since 3.0.0 + */ + +var TextureCrop = { + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.TextureCrop#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + texture: null, + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.TextureCrop#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + frame: null, + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + * + * @name Phaser.GameObjects.Components.TextureCrop#isCropped + * @type {boolean} + * @since 3.11.0 + */ + isCropped: false, + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * + * @method Phaser.GameObjects.Components.TextureCrop#setCrop + * @since 3.11.0 + * + * @param {(number|Phaser.Geom.Rectangle)} [x] - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param {number} [y] - The y coordinate to start the crop from. + * @param {number} [width] - The width of the crop rectangle in pixels. + * @param {number} [height] - The height of the crop rectangle in pixels. + * + * @return {this} This Game Object instance. + */ + setCrop: function (x, y, width, height) + { + if (x === undefined) + { + this.isCropped = false; + } + else if (this.frame) + { + if (typeof x === 'number') + { + this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY); + } + else + { + var rect = x; + + this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY); + } + + this.isCropped = true; + } + + return this; + }, + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.Components.TextureCrop#setTexture + * @since 3.0.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setTexture: function (key, frame) + { + this.texture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * + * @method Phaser.GameObjects.Components.TextureCrop#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * @param {boolean} [updateSize=true] - Should this call adjust the size of the Game Object? + * @param {boolean} [updateOrigin=true] - Should this call adjust the origin of the Game Object? + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame, updateSize, updateOrigin) + { + if (updateSize === undefined) { updateSize = true; } + if (updateOrigin === undefined) { updateOrigin = true; } + + this.frame = this.texture.get(frame); + + if (!this.frame.cutWidth || !this.frame.cutHeight) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + if (this._sizeComponent && updateSize) + { + this.setSizeToFrame(); + } + + if (this._originComponent && updateOrigin) + { + if (this.frame.customPivot) + { + this.setOrigin(this.frame.pivotX, this.frame.pivotY); + } + else + { + this.updateDisplayOrigin(); + } + } + + if (this.isCropped) + { + this.frame.updateCropUVs(this._crop, this.flipX, this.flipY); + } + + return this; + }, + + /** + * Internal method that returns a blank, well-formed crop object for use by a Game Object. + * + * @method Phaser.GameObjects.Components.TextureCrop#resetCropObject + * @private + * @since 3.12.0 + * + * @return {object} The crop object. + */ + resetCropObject: function () + { + return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 }; + } + +}; + +module.exports = TextureCrop; + + +/***/ }), +/* 603 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @function GetColor + * @since 3.0.0 + * @private + */ +var GetColor = function (value) +{ + return (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); +}; + +/** + * Provides methods used for setting the tint of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Tint + * @webglOnly + * @since 3.0.0 + */ + +var Tint = { + + /** + * Private internal value. Holds the top-left tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintTL + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintTL: 16777215, + + /** + * Private internal value. Holds the top-right tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintTR + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintTR: 16777215, + + /** + * Private internal value. Holds the bottom-left tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintBL + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintBL: 16777215, + + /** + * Private internal value. Holds the bottom-right tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintBR + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintBR: 16777215, + + /** + * Private internal value. Holds if the Game Object is tinted or not. + * + * @name Phaser.GameObjects.Components.Tint#_isTinted + * @type {boolean} + * @private + * @default false + * @since 3.11.0 + */ + _isTinted: false, + + /** + * Fill or additive? + * + * @name Phaser.GameObjects.Components.Tint#tintFill + * @type {boolean} + * @default false + * @since 3.11.0 + */ + tintFill: false, + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + * + * @method Phaser.GameObjects.Components.Tint#clearTint + * @webglOnly + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + clearTint: function () + { + this.setTint(0xffffff); + + this._isTinted = false; + + return this; + }, + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * + * @method Phaser.GameObjects.Components.Tint#setTint + * @webglOnly + * @since 3.0.0 + * + * @param {integer} [topLeft=0xffffff] - The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. + * @param {integer} [topRight] - The tint being applied to the top-right of the Game Object. + * @param {integer} [bottomLeft] - The tint being applied to the bottom-left of the Game Object. + * @param {integer} [bottomRight] - The tint being applied to the bottom-right of the Game Object. + * + * @return {this} This Game Object instance. + */ + setTint: function (topLeft, topRight, bottomLeft, bottomRight) + { + if (topLeft === undefined) { topLeft = 0xffffff; } + + if (topRight === undefined) + { + topRight = topLeft; + bottomLeft = topLeft; + bottomRight = topLeft; + } + + this._tintTL = GetColor(topLeft); + this._tintTR = GetColor(topRight); + this._tintBL = GetColor(bottomLeft); + this._tintBR = GetColor(bottomRight); + + this._isTinted = true; + + this.tintFill = false; + + return this; + }, + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * + * @method Phaser.GameObjects.Components.Tint#setTintFill + * @webglOnly + * @since 3.11.0 + * + * @param {integer} [topLeft=0xffffff] - The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. + * @param {integer} [topRight] - The tint being applied to the top-right of the Game Object. + * @param {integer} [bottomLeft] - The tint being applied to the bottom-left of the Game Object. + * @param {integer} [bottomRight] - The tint being applied to the bottom-right of the Game Object. + * + * @return {this} This Game Object instance. + */ + setTintFill: function (topLeft, topRight, bottomLeft, bottomRight) + { + this.setTint(topLeft, topRight, bottomLeft, bottomRight); + + this.tintFill = true; + + return this; + }, + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintTopLeft + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintTopLeft: { + + get: function () + { + return this._tintTL; + }, + + set: function (value) + { + this._tintTL = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintTopRight + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintTopRight: { + + get: function () + { + return this._tintTR; + }, + + set: function (value) + { + this._tintTR = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintBottomLeft + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintBottomLeft: { + + get: function () + { + return this._tintBL; + }, + + set: function (value) + { + this._tintBL = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintBottomRight + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintBottomRight: { + + get: function () + { + return this._tintBR; + }, + + set: function (value) + { + this._tintBR = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + * + * @name Phaser.GameObjects.Components.Tint#tint + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tint: { + + set: function (value) + { + this.setTint(value, value, value, value); + } + }, + + /** + * Does this Game Object have a tint applied to it or not? + * + * @name Phaser.GameObjects.Components.Tint#isTinted + * @type {boolean} + * @webglOnly + * @readonly + * @since 3.11.0 + */ + isTinted: { + + get: function () + { + return this._isTinted; + } + + } + +}; + +module.exports = Tint; + + +/***/ }), +/* 604 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Change Data Event. + * + * This event is dispatched by a Data Manager when an item in the data store is changed. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * a change data event from a Game Object you would use: `sprite.data.on('changedata', listener)`. + * + * This event is dispatched for all items that change in the Data Manager. + * To listen for the change of a specific item, use the `CHANGE_DATA_KEY_EVENT` event. + * + * @event Phaser.Data.Events#CHANGE_DATA + * @since 3.0.0 + * + * @param {any} parent - A reference to the object that the Data Manager responsible for this event belongs to. + * @param {string} key - The unique key of the data item within the Data Manager. + * @param {any} value - The new value of the item in the Data Manager. + * @param {any} previousValue - The previous value of the item in the Data Manager. + */ +module.exports = 'changedata'; + + +/***/ }), +/* 605 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Change Data Key Event. + * + * This event is dispatched by a Data Manager when an item in the data store is changed. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the change of a specific data item from a Game Object you would use: `sprite.data.on('changedata-key', listener)`, + * where `key` is the unique string key of the data item. For example, if you have a data item stored called `gold` + * then you can listen for `sprite.data.on('changedata-gold')`. + * + * @event Phaser.Data.Events#CHANGE_DATA_KEY + * @since 3.16.1 + * + * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. + * @param {any} value - The item that was updated in the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + * @param {any} previousValue - The previous item that was updated in the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + */ +module.exports = 'changedata-'; + + +/***/ }), +/* 606 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Remove Data Event. + * + * This event is dispatched by a Data Manager when an item is removed from it. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the removal of a data item on a Game Object you would use: `sprite.data.on('removedata', listener)`. + * + * @event Phaser.Data.Events#REMOVE_DATA + * @since 3.0.0 + * + * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. + * @param {string} key - The unique key of the data item within the Data Manager. + * @param {any} data - The item that was removed from the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + */ +module.exports = 'removedata'; + + +/***/ }), +/* 607 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Set Data Event. + * + * This event is dispatched by a Data Manager when a new item is added to the data store. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the addition of a new data item on a Game Object you would use: `sprite.data.on('setdata', listener)`. + * + * @event Phaser.Data.Events#SET_DATA + * @since 3.0.0 + * + * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. + * @param {string} key - The unique key of the data item within the Data Manager. + * @param {any} data - The item that was added to the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + */ +module.exports = 'setdata'; + + +/***/ }), +/* 608 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Destroy Event. + * + * This event is dispatched when a Game Object instance is being destroyed. + * + * Listen for it on a Game Object instance using `GameObject.on('destroy', listener)`. + * + * @event Phaser.GameObjects.Events#DESTROY + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object which is being destroyed. + */ +module.exports = 'destroy'; + + +/***/ }), +/* 609 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Complete Event. + * + * This event is dispatched when a Video finishes playback by reaching the end of its duration. It + * is also dispatched if a video marker sequence is being played and reaches the end. + * + * Note that not all videos can fire this event. Live streams, for example, have no fixed duration, + * so never technically 'complete'. + * + * If a video is stopped from playback, via the `Video.stop` method, it will emit the + * `VIDEO_STOP` event instead of this one. + * + * Listen for it from a Video Game Object instance using `Video.on('complete', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_COMPLETE + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which completed playback. + */ +module.exports = 'complete'; + + +/***/ }), +/* 610 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Created Event. + * + * This event is dispatched when the texture for a Video has been created. This happens + * when enough of the video source has been loaded that the browser is able to render a + * frame from it. + * + * Listen for it from a Video Game Object instance using `Video.on('created', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_CREATED + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which raised the event. + * @param {integer} width - The width of the video. + * @param {integer} height - The height of the video. + */ +module.exports = 'created'; + + +/***/ }), +/* 611 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Error Event. + * + * This event is dispatched when a Video tries to play a source that does not exist, or is the wrong file type. + * + * Listen for it from a Video Game Object instance using `Video.on('error', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_ERROR + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which threw the error. + * @param {Event} event - The native DOM event the browser raised during playback. + */ +module.exports = 'error'; + + +/***/ }), +/* 612 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which has looped. + */ +module.exports = 'loop'; + + +/***/ }), +/* 613 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Play Event. + * + * This event is dispatched when a Video begins playback. For videos that do not require + * interaction unlocking, this is usually as soon as the `Video.play` method is called. + * However, for videos that require unlocking, it is fired once playback begins after + * they've been unlocked. + * + * Listen for it from a Video Game Object instance using `Video.on('play', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_PLAY + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which started playback. + */ +module.exports = 'play'; + + +/***/ }), +/* 614 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Seeked Event. + * + * This event is dispatched when a Video completes seeking to a new point in its timeline. + * + * Listen for it from a Video Game Object instance using `Video.on('seeked', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_SEEKED + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which completed seeking. + */ +module.exports = 'seeked'; + + +/***/ }), +/* 615 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Seeking Event. + * + * This event is dispatched when a Video _begins_ seeking to a new point in its timeline. + * When the seek is complete, it will dispatch the `VIDEO_SEEKED` event to conclude. + * + * Listen for it from a Video Game Object instance using `Video.on('seeking', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_SEEKING + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which started seeking. + */ +module.exports = 'seeking'; + + +/***/ }), +/* 616 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Stopped Event. + * + * This event is dispatched when a Video is stopped from playback via a call to the `Video.stop` method, + * either directly via game code, or indirectly as the result of changing a video source or destroying it. + * + * Listen for it from a Video Game Object instance using `Video.on('stop', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_STOP + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which stopped playback. + */ +module.exports = 'stop'; + + +/***/ }), +/* 617 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Timeout Event. + * + * This event is dispatched when a Video has exhausted its allocated time while trying to connect to a video + * source to start playback. + * + * Listen for it from a Video Game Object instance using `Video.on('timeout', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_TIMEOUT + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which timed out. + */ +module.exports = 'timeout'; + + +/***/ }), +/* 618 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Unlocked Event. + * + * This event is dispatched when a Video that was prevented from playback due to the browsers + * Media Engagement Interaction policy, is unlocked by a user gesture. + * + * Listen for it from a Video Game Object instance using `Video.on('unlocked', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_UNLOCKED + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which raised the event. + */ +module.exports = 'unlocked'; + + +/***/ }), +/* 619 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `alpha` property, + * and then adds the given value to each of their `alpha` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncAlpha(group.getChildren(), value, step)` + * + * @function Phaser.Actions.IncAlpha + * @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 {number} value - The amount to be added to the `alpha` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncAlpha = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'alpha', value, step, index, direction); +}; + +module.exports = IncAlpha; + + +/***/ }), +/* 620 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `x` property, + * and then adds the given value to each of their `x` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.IncX + * @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 {number} value - The amount to be added to the `x` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncX = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'x', value, step, index, direction); +}; + +module.exports = IncX; + + +/***/ }), +/* 621 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, + * and then adds the given value to each of them. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncXY(group.getChildren(), x, y, stepX, stepY)` + * + * @function Phaser.Actions.IncXY + * @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 {number} x - The amount to be added to the `x` property. + * @param {number} [y=x] - The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncXY = function (items, x, y, stepX, stepY, index, direction) +{ + if (y === undefined || y === null) { y = x; } + + PropertyValueInc(items, 'x', x, stepX, index, direction); + + return PropertyValueInc(items, 'y', y, stepY, index, direction); +}; + +module.exports = IncXY; + + +/***/ }), +/* 622 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `y` property, + * and then adds the given value to each of their `y` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.IncY + * @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 {number} value - The amount to be added to the `y` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncY = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'y', value, step, index, direction); +}; + +module.exports = IncY; + + +/***/ }), +/* 623 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Circle. + * + * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.PlaceOnCircle + * @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.Geom.Circle} circle - The Circle to position the Game Objects on. + * @param {number} [startAngle=0] - Optional angle to start position from, in radians. + * @param {number} [endAngle=6.28] - Optional angle to stop position at, in radians. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnCircle = function (items, circle, startAngle, endAngle) +{ + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 6.28; } + + var angle = startAngle; + var angleStep = (endAngle - startAngle) / items.length; + + for (var i = 0; i < items.length; i++) + { + items[i].x = circle.x + (circle.radius * Math.cos(angle)); + items[i].y = circle.y + (circle.radius * Math.sin(angle)); + + angle += angleStep; + } + + return items; +}; + +module.exports = PlaceOnCircle; + + +/***/ }), +/* 624 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of an Ellipse. + * + * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.PlaceOnEllipse + * @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.Geom.Ellipse} ellipse - The Ellipse to position the Game Objects on. + * @param {number} [startAngle=0] - Optional angle to start position from, in radians. + * @param {number} [endAngle=6.28] - Optional angle to stop position at, in radians. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnEllipse = function (items, ellipse, startAngle, endAngle) +{ + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 6.28; } + + var angle = startAngle; + var angleStep = (endAngle - startAngle) / items.length; + + var a = ellipse.width / 2; + var b = ellipse.height / 2; + + for (var i = 0; i < items.length; i++) + { + items[i].x = ellipse.x + a * Math.cos(angle); + items[i].y = ellipse.y + b * Math.sin(angle); + + angle += angleStep; + } + + return items; +}; + +module.exports = PlaceOnEllipse; + + +/***/ }), +/* 625 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetPoints = __webpack_require__(162); + +/** + * Positions an array of Game Objects on evenly spaced points of a Line. + * + * @function Phaser.Actions.PlaceOnLine + * @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.Geom.Line} line - The Line to position the Game Objects on. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnLine = function (items, line) +{ + var points = GetPoints(line, items.length); + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + var point = points[i]; + + item.x = point.x; + item.y = point.y; + } + + return items; +}; + +module.exports = PlaceOnLine; + + +/***/ }), +/* 626 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MarchingAnts = __webpack_require__(304); +var RotateLeft = __webpack_require__(305); +var RotateRight = __webpack_require__(306); + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. + * + * Placement starts from the top-left of the rectangle, and proceeds in a clockwise direction. + * If the `shift` parameter is given you can offset where placement begins. + * + * @function Phaser.Actions.PlaceOnRectangle + * @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.Geom.Rectangle} rect - The Rectangle to position the Game Objects on. + * @param {integer} [shift=1] - An optional positional offset. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnRectangle = function (items, rect, shift) +{ + if (shift === undefined) { shift = 0; } + + var points = MarchingAnts(rect, false, items.length); + + if (shift > 0) + { + RotateLeft(points, shift); + } + else if (shift < 0) + { + RotateRight(points, Math.abs(shift)); + } + + for (var i = 0; i < items.length; i++) + { + items[i].x = points[i].x; + items[i].y = points[i].y; + } + + return items; +}; + +module.exports = PlaceOnRectangle; + + +/***/ }), +/* 627 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BresenhamPoints = __webpack_require__(307); + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. + * + * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.PlaceOnTriangle + * @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.Geom.Triangle} triangle - The Triangle to position the Game Objects on. + * @param {number} [stepRate=1] - An optional step rate, to increase or decrease the packing of the Game Objects on the lines. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnTriangle = function (items, triangle, stepRate) +{ + var p1 = BresenhamPoints({ x1: triangle.x1, y1: triangle.y1, x2: triangle.x2, y2: triangle.y2 }, stepRate); + var p2 = BresenhamPoints({ x1: triangle.x2, y1: triangle.y2, x2: triangle.x3, y2: triangle.y3 }, stepRate); + var p3 = BresenhamPoints({ x1: triangle.x3, y1: triangle.y3, x2: triangle.x1, y2: triangle.y1 }, stepRate); + + // Remove overlaps + p1.pop(); + p2.pop(); + p3.pop(); + + p1 = p1.concat(p2, p3); + + var step = p1.length / items.length; + var p = 0; + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + var point = p1[Math.floor(p)]; + + item.x = point.x; + item.y = point.y; + + p += step; + } + + return items; +}; + +module.exports = PlaceOnTriangle; + + +/***/ }), +/* 628 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Play an animation with the given key, starting at the given startFrame on all Game Objects in items. + * + * @function Phaser.Actions.PlayAnimation + * @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} key - The name of the animation to play. + * @param {(string|integer)} [startFrame] - The starting frame of the animation with the given key. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlayAnimation = function (items, key, startFrame) +{ + for (var i = 0; i < items.length; i++) + { + items[i].anims.play(key, startFrame); + } + + return items; +}; + +module.exports = PlayAnimation; + + +/***/ }), +/* 629 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = __webpack_require__(159); + +/** + * Takes an array of Game Objects and positions them at random locations within the Circle. + * + * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomCircle + * @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.Geom.Circle} circle - The Circle to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomCircle = function (items, circle) +{ + for (var i = 0; i < items.length; i++) + { + Random(circle, items[i]); + } + + return items; +}; + +module.exports = RandomCircle; + + +/***/ }), +/* 630 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = __webpack_require__(167); + +/** + * Takes an array of Game Objects and positions them at random locations within the Ellipse. + * + * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomEllipse + * @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.Geom.Ellipse} ellipse - The Ellipse to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomEllipse = function (items, ellipse) +{ + for (var i = 0; i < items.length; i++) + { + Random(ellipse, items[i]); + } + + return items; +}; + +module.exports = RandomEllipse; + + +/***/ }), +/* 631 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = __webpack_require__(163); + +/** + * Takes an array of Game Objects and positions them at random locations on the Line. + * + * If you wish to pass a `Phaser.GameObjects.Line` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomLine + * @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.Geom.Line} line - The Line to position the Game Objects randomly on. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomLine = function (items, line) +{ + for (var i = 0; i < items.length; i++) + { + Random(line, items[i]); + } + + return items; +}; + +module.exports = RandomLine; + + +/***/ }), +/* 632 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = __webpack_require__(164); + +/** + * Takes an array of Game Objects and positions them at random locations within the Rectangle. + * + * @function Phaser.Actions.RandomRectangle + * @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.Geom.Rectangle} rect - The Rectangle to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomRectangle = function (items, rect) +{ + for (var i = 0; i < items.length; i++) + { + Random(rect, items[i]); + } + + return items; +}; + +module.exports = RandomRectangle; + + +/***/ }), +/* 633 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = __webpack_require__(168); + +/** + * Takes an array of Game Objects and positions them at random locations within the Triangle. + * + * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomTriangle + * @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.Geom.Triangle} triangle - The Triangle to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomTriangle = function (items, triangle) +{ + for (var i = 0; i < items.length; i++) + { + Random(triangle, items[i]); + } + + return items; +}; + +module.exports = RandomTriangle; + + +/***/ }), +/* 634 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `rotation` property, + * and then adds the given value to each of their `rotation` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `Rotate(group.getChildren(), value, step)` + * + * @function Phaser.Actions.Rotate + * @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 {number} value - The amount to be added to the `rotation` property (in radians). + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var Rotate = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'rotation', value, step, index, direction); +}; + +module.exports = Rotate; + + +/***/ }), +/* 635 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundDistance = __webpack_require__(169); +var DistanceBetween = __webpack_require__(54); + +/** + * Rotates each item around the given point by the given angle. + * + * @function Phaser.Actions.RotateAround + * @since 3.0.0 + * @see Phaser.Math.RotateAroundDistance + * + * @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 {object} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RotateAround = function (items, point, angle) +{ + var x = point.x; + var y = point.y; + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + + RotateAroundDistance(item, x, y, angle, Math.max(1, DistanceBetween(item.x, item.y, x, y))); + } + + return items; +}; + +module.exports = RotateAround; + + +/***/ }), +/* 636 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathRotateAroundDistance = __webpack_require__(169); + +/** + * Rotates an array of Game Objects around a point by the given angle and distance. + * + * @function Phaser.Actions.RotateAroundDistance + * @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 {object} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * @param {number} distance - The distance from the point of rotation in pixels. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RotateAroundDistance = function (items, point, angle, distance) +{ + var x = point.x; + var y = point.y; + + // There's nothing to do + if (distance === 0) + { + return items; + } + + for (var i = 0; i < items.length; i++) + { + MathRotateAroundDistance(items[i], x, y, angle, distance); + } + + return items; +}; + +module.exports = RotateAroundDistance; + + +/***/ }), +/* 637 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `scaleX` property, + * and then adds the given value to each of their `scaleX` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.ScaleX + * @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 {number} value - The amount to be added to the `scaleX` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var ScaleX = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'scaleX', value, step, index, direction); +}; + +module.exports = ScaleX; + + +/***/ }), +/* 638 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have public `scaleX` and `scaleY` properties, + * and then adds the given value to each of them. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleXY(group.getChildren(), scaleX, scaleY, stepX, stepY)` + * + * @function Phaser.Actions.ScaleXY + * @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 {number} scaleX - The amount to be added to the `scaleX` property. + * @param {number} [scaleY] - The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. + * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var ScaleXY = function (items, scaleX, scaleY, stepX, stepY, index, direction) +{ + if (scaleY === undefined || scaleY === null) { scaleY = scaleX; } + + PropertyValueInc(items, 'scaleX', scaleX, stepX, index, direction); + + return PropertyValueInc(items, 'scaleY', scaleY, stepY, index, direction); +}; + +module.exports = ScaleXY; + + +/***/ }), +/* 639 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = __webpack_require__(39); + +/** + * Takes an array of Game Objects, or any objects that have a public `scaleY` property, + * and then adds the given value to each of their `scaleY` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.ScaleY + * @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 {number} value - The amount to be added to the `scaleY` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var ScaleY = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'scaleY', value, step, index, direction); +}; + +module.exports = ScaleY; + + +/***/ }), +/* 640 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `alpha` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetAlpha(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetAlpha + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetAlpha = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'alpha', value, step, index, direction); +}; + +module.exports = SetAlpha; + + +/***/ }), +/* 641 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `blendMode` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetBlendMode(group.getChildren(), value)` + * + * @function Phaser.Actions.SetBlendMode + * @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 {number} value - The amount to set the property to. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetBlendMode = function (items, value, index, direction) +{ + return PropertyValueSet(items, 'blendMode', value, 0, index, direction); +}; + +module.exports = SetBlendMode; + + +/***/ }), +/* 642 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `depth` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetDepth(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetDepth + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetDepth = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'depth', value, step, index, direction); +}; + +module.exports = SetDepth; + + +/***/ }), +/* 643 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Passes all provided Game Objects to the Input Manager to enable them for input with identical areas and callbacks. + * + * @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 {*} 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 - A callback to be invoked when the Game Object is interacted with. 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. + */ +var SetHitArea = function (items, hitArea, hitAreaCallback) +{ + for (var i = 0; i < items.length; i++) + { + items[i].setInteractive(hitArea, hitAreaCallback); + } + + return items; +}; + +module.exports = SetHitArea; + + +/***/ }), +/* 644 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetOrigin(group.getChildren(), originX, originY, stepX, stepY)` + * + * @function Phaser.Actions.SetOrigin + * @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 {number} originX - The amount to set the `originX` property to. + * @param {number} [originY] - The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. + * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetOrigin = function (items, originX, originY, stepX, stepY, index, direction) +{ + if (originY === undefined || originY === null) { originY = originX; } + + PropertyValueSet(items, 'originX', originX, stepX, index, direction); + + return PropertyValueSet(items, 'originY', originY, stepY, index, direction); +}; + +module.exports = SetOrigin; + + +/***/ }), +/* 645 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `rotation` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetRotation(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetRotation + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetRotation = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'rotation', value, step, index, direction); +}; + +module.exports = SetRotation; + + +/***/ }), +/* 646 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScale(group.getChildren(), scaleX, scaleY, stepX, stepY)` + * + * @function Phaser.Actions.SetScale + * @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 {number} scaleX - The amount to set the `scaleX` property to. + * @param {number} [scaleY] - The amount to set the `scaleY` property to. If `undefined` or `null` it uses the `scaleX` value. + * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScale = function (items, scaleX, scaleY, stepX, stepY, index, direction) +{ + if (scaleY === undefined || scaleY === null) { scaleY = scaleX; } + + PropertyValueSet(items, 'scaleX', scaleX, stepX, index, direction); + + return PropertyValueSet(items, 'scaleY', scaleY, stepY, index, direction); +}; + +module.exports = SetScale; + + +/***/ }), +/* 647 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scaleX` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScaleX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScaleX + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScaleX = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scaleX', value, step, index, direction); +}; + +module.exports = SetScaleX; + + +/***/ }), +/* 648 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scaleY` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScaleY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScaleY + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScaleY = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scaleY', value, step, index, direction); +}; + +module.exports = SetScaleY; + + +/***/ }), +/* 649 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactor(group.getChildren(), scrollFactorX, scrollFactorY, stepX, stepY)` + * + * @function Phaser.Actions.SetScrollFactor + * @since 3.21.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 {number} scrollFactorX - The amount to set the `scrollFactorX` property to. + * @param {number} [scrollFactorY] - The amount to set the `scrollFactorY` property to. If `undefined` or `null` it uses the `scrollFactorX` value. + * @param {number} [stepX=0] - This is added to the `scrollFactorX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scrollFactorY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScrollFactor = function (items, scrollFactorX, scrollFactorY, stepX, stepY, index, direction) +{ + if (scrollFactorY === undefined || scrollFactorY === null) { scrollFactorY = scrollFactorX; } + + PropertyValueSet(items, 'scrollFactorX', scrollFactorX, stepX, index, direction); + + return PropertyValueSet(items, 'scrollFactorY', scrollFactorY, stepY, index, direction); +}; + +module.exports = SetScrollFactor; + + +/***/ }), +/* 650 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactorX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScrollFactorX + * @since 3.21.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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScrollFactorX = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scrollFactorX', value, step, index, direction); +}; + +module.exports = SetScrollFactorX; + + +/***/ }), +/* 651 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactorY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScrollFactorY + * @since 3.21.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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScrollFactorY = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scrollFactorY', value, step, index, direction); +}; + +module.exports = SetScrollFactorY; + + +/***/ }), +/* 652 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects, or any objects that have the public method setTint() and then updates it to the given value(s). You can specify tint color per corner or provide only one color value for `topLeft` parameter, in which case whole item will be tinted with that color. + * + * @function Phaser.Actions.SetTint + * @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 {number} topLeft - The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. + * @param {number} [topRight] - The tint to be applied to top-right corner of item. + * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. + * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var SetTint = function (items, topLeft, topRight, bottomLeft, bottomRight) +{ + for (var i = 0; i < items.length; i++) + { + items[i].setTint(topLeft, topRight, bottomLeft, bottomRight); + } + + return items; +}; + +module.exports = SetTint; + + +/***/ }), +/* 653 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `visible` + * and then sets it to the given value. + * + * To use this with a Group: `SetVisible(group.getChildren(), value)` + * + * @function Phaser.Actions.SetVisible + * @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 {boolean} value - The value to set the property to. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetVisible = function (items, value, index, direction) +{ + return PropertyValueSet(items, 'visible', value, 0, index, direction); +}; + +module.exports = SetVisible; + + +/***/ }), +/* 654 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `x` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetX + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetX = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'x', value, step, index, direction); +}; + +module.exports = SetX; + + +/***/ }), +/* 655 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetXY(group.getChildren(), x, y, stepX, stepY)` + * + * @function Phaser.Actions.SetXY + * @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 {number} x - The amount to set the `x` property to. + * @param {number} [y=x] - The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetXY = function (items, x, y, stepX, stepY, index, direction) +{ + if (y === undefined || y === null) { y = x; } + + PropertyValueSet(items, 'x', x, stepX, index, direction); + + return PropertyValueSet(items, 'y', y, stepY, index, direction); +}; + +module.exports = SetXY; + + +/***/ }), +/* 656 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = __webpack_require__(27); + +/** + * Takes an array of Game Objects, or any objects that have the public property `y` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetY + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetY = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'y', value, step, index, direction); +}; + +module.exports = SetY; + + +/***/ }), +/* 657 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = __webpack_require__(3); + +/** + * Iterate through the items array changing the position of each element to be that of the element that came before + * it in the array (or after it if direction = 1) + * + * The first items position is set to x/y. + * + * The final x/y coords are returned + * + * @function Phaser.Actions.ShiftPosition + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items] + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action. + * @param {number} x - The x coordinate to place the first item in the array at. + * @param {number} y - The y coordinate to place the first item in the array at. + * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. + * @param {(Phaser.Math.Vector2|object)} [output] - An optional objec to store the final objects position in. + * + * @return {Phaser.Math.Vector2} The output vector. + */ +var ShiftPosition = function (items, x, y, direction, output) +{ + if (direction === undefined) { direction = 0; } + if (output === undefined) { output = new Vector2(); } + + var px; + var py; + + if (items.length > 1) + { + var i; + var cx; + var cy; + var cur; + + if (direction === 0) + { + // Bottom to Top + + var len = items.length - 1; + + px = items[len].x; + py = items[len].y; + + for (i = len - 1; i >= 0; i--) + { + // Current item + cur = items[i]; + + // Get current item x/y, to be passed to the next item in the list + cx = cur.x; + cy = cur.y; + + // Set current item to the previous items x/y + cur.x = px; + cur.y = py; + + // Set current as previous + px = cx; + py = cy; + } + + // Update the head item to the new x/y coordinates + items[len].x = x; + items[len].y = y; + } + else + { + // Top to Bottom + + px = items[0].x; + py = items[0].y; + + for (i = 1; i < items.length; i++) + { + // Current item + cur = items[i]; + + // Get current item x/y, to be passed to the next item in the list + cx = cur.x; + cy = cur.y; + + // Set current item to the previous items x/y + cur.x = px; + cur.y = py; + + // Set current as previous + px = cx; + py = cy; + } + + // Update the head item to the new x/y coordinates + items[0].x = x; + items[0].y = y; + } + } + else + { + px = items[0].x; + py = items[0].y; + + items[0].x = x; + items[0].y = y; + } + + // Return the final set of coordinates as they're effectively lost from the shift and may be needed + + output.x = px; + output.y = py; + + return output; +}; + +module.exports = ShiftPosition; + + +/***/ }), +/* 658 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayShuffle = __webpack_require__(122); + +/** + * Shuffles the array in place. The shuffled array is both modified and returned. + * + * @function Phaser.Actions.Shuffle + * @since 3.0.0 + * @see Phaser.Utils.Array.Shuffle + * + * @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. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var Shuffle = function (items) +{ + return ArrayShuffle(items); +}; + +module.exports = Shuffle; + + +/***/ }), +/* 659 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathSmootherStep = __webpack_require__(170); + +/** + * 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 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.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] - Should the values be incremented? `true` or set (`false`) + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var SmootherStep = function (items, property, min, max, inc) +{ + if (inc === undefined) { inc = false; } + + var step = Math.abs(max - min) / items.length; + var i; + + if (inc) + { + for (i = 0; i < items.length; i++) + { + items[i][property] += MathSmootherStep(i * step, min, max); + } + } + else + { + for (i = 0; i < items.length; i++) + { + items[i][property] = MathSmootherStep(i * step, min, max); + } + } + + return items; +}; + +module.exports = SmootherStep; + + +/***/ }), +/* 660 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathSmoothStep = __webpack_require__(171); + +/** + * 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 minimum interpolation value. + * @param {number} max - The maximum interpolation value. + * @param {boolean} [inc=false] - Should the values be incremented? `true` or set (`false`) + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var SmoothStep = function (items, property, min, max, inc) +{ + if (inc === undefined) { inc = false; } + + var step = Math.abs(max - min) / items.length; + var i; + + if (inc) + { + for (i = 0; i < items.length; i++) + { + items[i][property] += MathSmoothStep(i * step, min, max); + } + } + else + { + for (i = 0; i < items.length; i++) + { + items[i][property] = MathSmoothStep(i * step, min, max); + } + } + + return items; +}; + +module.exports = SmoothStep; + + +/***/ }), +/* 661 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and then modifies their `property` so the value equals, or is incremented, by the + * calculated spread value. + * + * The spread value is derived from the given `min` and `max` values and the total number of items in the array. + * + * For example, to cause an array of Sprites to change in alpha from 0 to 1 you could call: + * + * ```javascript + * Phaser.Actions.Spread(itemsArray, 'alpha', 0, 1); + * ``` + * + * @function Phaser.Actions.Spread + * @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 spread. + * @param {number} min - The minimum value. + * @param {number} max - The maximum value. + * @param {boolean} [inc=false] - Should the values be incremented? `true` or set (`false`) + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that were passed to this Action. + */ +var Spread = function (items, property, min, max, inc) +{ + if (inc === undefined) { inc = false; } + + var step = Math.abs(max - min) / items.length; + var i; + + if (inc) + { + for (i = 0; i < items.length; i++) + { + items[i][property] += i * step + min; + } + } + else + { + for (i = 0; i < items.length; i++) + { + items[i][property] = i * step + min; + } + } + + return items; +}; + +module.exports = Spread; + + +/***/ }), +/* 662 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and toggles the visibility of each one. + * Those previously `visible = false` will become `visible = true`, and vice versa. + * + * @function Phaser.Actions.ToggleVisible + * @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. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var ToggleVisible = function (items) +{ + for (var i = 0; i < items.length; i++) + { + items[i].visible = !items[i].visible; + } + + return items; +}; + +module.exports = ToggleVisible; + + +/***/ }), +/* 663 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Wrap = __webpack_require__(63); + +/** + * Wrap each item's coordinates within a rectangle's area. + * + * @function Phaser.Actions.WrapInRectangle + * @since 3.0.0 + * @see Phaser.Math.Wrap + * + * @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.Geom.Rectangle} rect - The rectangle. + * @param {number} [padding=0] - An amount added to each side of the rectangle during the operation. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var WrapInRectangle = function (items, rect, padding) +{ + if (padding === undefined) + { + padding = 0; + } + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + + item.x = Wrap(item.x, rect.left - padding, rect.right + padding); + item.y = Wrap(item.y, rect.top - padding, rect.bottom + padding); + } + + return items; +}; + +module.exports = WrapInRectangle; + + +/***/ }), +/* 664 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Animations + */ + +module.exports = { + + Animation: __webpack_require__(160), + AnimationFrame: __webpack_require__(290), + AnimationManager: __webpack_require__(308), + Events: __webpack_require__(119) + +}; + + +/***/ }), +/* 665 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cache + */ + +module.exports = { + + BaseCache: __webpack_require__(309), + CacheManager: __webpack_require__(311), + Events: __webpack_require__(310) + +}; + + +/***/ }), +/* 666 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Cache Add Event. + * + * This event is dispatched by any Cache that extends the BaseCache each time a new object is added to it. + * + * @event Phaser.Cache.Events#ADD + * @since 3.0.0 + * + * @param {Phaser.Cache.BaseCache} cache - The cache to which the object was added. + * @param {string} key - The key of the object added to the cache. + * @param {*} object - A reference to the object that was added to the cache. + */ +module.exports = 'add'; + + +/***/ }), +/* 667 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Cache Remove Event. + * + * This event is dispatched by any Cache that extends the BaseCache each time an object is removed from it. + * + * @event Phaser.Cache.Events#REMOVE + * @since 3.0.0 + * + * @param {Phaser.Cache.BaseCache} cache - The cache from which the object was removed. + * @param {string} key - The key of the object removed from the cache. + * @param {*} object - A reference to the object that was removed from the cache. + */ +module.exports = 'remove'; + + +/***/ }), +/* 668 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras + */ + +/** + * @namespace Phaser.Types.Cameras + */ + +module.exports = { + + Controls: __webpack_require__(669), + Scene2D: __webpack_require__(672) + +}; + + +/***/ }), +/* 669 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Controls + */ + +module.exports = { + + FixedKeyControl: __webpack_require__(670), + SmoothedKeyControl: __webpack_require__(671) + +}; + + +/***/ }), +/* 670 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetValue = __webpack_require__(5); + +/** + * @classdesc + * A Fixed Key Camera Control. + * + * This allows you to control the movement and zoom of a camera using the defined keys. + * + * ```javascript + * var camControl = new FixedKeyControl({ + * camera: this.cameras.main, + * left: cursors.left, + * right: cursors.right, + * speed: float OR { x: 0, y: 0 } + * }); + * ``` + * + * Movement is precise and has no 'smoothing' applied to it. + * + * You must call the `update` method of this controller every frame. + * + * @class FixedKeyControl + * @memberof Phaser.Cameras.Controls + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Cameras.Controls.FixedKeyControlConfig} config - The Fixed Key Control configuration object. + */ +var FixedKeyControl = new Class({ + + initialize: + + function FixedKeyControl (config) + { + /** + * The Camera that this Control will update. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#camera + * @type {?Phaser.Cameras.Scene2D.Camera} + * @default null + * @since 3.0.0 + */ + this.camera = GetValue(config, 'camera', null); + + /** + * The Key to be pressed that will move the Camera left. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#left + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.left = GetValue(config, 'left', null); + + /** + * The Key to be pressed that will move the Camera right. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#right + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.right = GetValue(config, 'right', null); + + /** + * The Key to be pressed that will move the Camera up. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#up + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.up = GetValue(config, 'up', null); + + /** + * The Key to be pressed that will move the Camera down. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#down + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.down = GetValue(config, 'down', null); + + /** + * The Key to be pressed that will zoom the Camera in. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#zoomIn + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomIn = GetValue(config, 'zoomIn', null); + + /** + * The Key to be pressed that will zoom the Camera out. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#zoomOut + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomOut = GetValue(config, 'zoomOut', null); + + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#zoomSpeed + * @type {number} + * @default 0.01 + * @since 3.0.0 + */ + this.zoomSpeed = GetValue(config, 'zoomSpeed', 0.01); + + /** + * The horizontal speed the camera will move. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#speedX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.speedX = 0; + + /** + * The vertical speed the camera will move. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#speedY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.speedY = 0; + + var speed = GetValue(config, 'speed', null); + + if (typeof speed === 'number') + { + this.speedX = speed; + this.speedY = speed; + } + else + { + this.speedX = GetValue(config, 'speed.x', 0); + this.speedY = GetValue(config, 'speed.y', 0); + } + + /** + * Internal property to track the current zoom level. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#_zoom + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._zoom = 0; + + /** + * A flag controlling if the Controls will update the Camera or not. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#active + * @type {boolean} + * @since 3.0.0 + */ + this.active = (this.camera !== null); + }, + + /** + * Starts the Key Control running, providing it has been linked to a camera. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#start + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. + */ + start: function () + { + this.active = (this.camera !== null); + + return this; + }, + + /** + * Stops this Key Control from running. Call `start` to start it again. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#stop + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. + */ + stop: function () + { + this.active = false; + + return this; + }, + + /** + * Binds this Key Control to a camera. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#setCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to bind this Key Control to. + * + * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. + */ + setCamera: function (camera) + { + this.camera = camera; + + return this; + }, + + /** + * 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. + */ + update: function (delta) + { + if (!this.active) + { + return; + } + + if (delta === undefined) { delta = 1; } + + var cam = this.camera; + + if (this.up && this.up.isDown) + { + cam.scrollY -= ((this.speedY * delta) | 0); + } + else if (this.down && this.down.isDown) + { + cam.scrollY += ((this.speedY * delta) | 0); + } + + if (this.left && this.left.isDown) + { + cam.scrollX -= ((this.speedX * delta) | 0); + } + else if (this.right && this.right.isDown) + { + cam.scrollX += ((this.speedX * delta) | 0); + } + + // Camera zoom + + if (this.zoomIn && this.zoomIn.isDown) + { + cam.zoom -= this.zoomSpeed; + + if (cam.zoom < 0.1) + { + cam.zoom = 0.1; + } + } + else if (this.zoomOut && this.zoomOut.isDown) + { + cam.zoom += this.zoomSpeed; + } + }, + + /** + * Destroys this Key Control. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.camera = null; + + this.left = null; + this.right = null; + this.up = null; + this.down = null; + + this.zoomIn = null; + this.zoomOut = null; + } + +}); + +module.exports = FixedKeyControl; + + +/***/ }), +/* 671 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetValue = __webpack_require__(5); + +/** + * @classdesc + * A Smoothed Key Camera Control. + * + * This allows you to control the movement and zoom of a camera using the defined keys. + * Unlike the Fixed Camera Control you can also provide physics values for acceleration, drag and maxSpeed for smoothing effects. + * + * ```javascript + * var controlConfig = { + * camera: this.cameras.main, + * left: cursors.left, + * right: cursors.right, + * up: cursors.up, + * down: cursors.down, + * zoomIn: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q), + * zoomOut: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.E), + * zoomSpeed: 0.02, + * acceleration: 0.06, + * drag: 0.0005, + * maxSpeed: 1.0 + * }; + * ``` + * + * You must call the `update` method of this controller every frame. + * + * @class SmoothedKeyControl + * @memberof Phaser.Cameras.Controls + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Cameras.Controls.SmoothedKeyControlConfig} config - The Smoothed Key Control configuration object. + */ +var SmoothedKeyControl = new Class({ + + initialize: + + function SmoothedKeyControl (config) + { + /** + * The Camera that this Control will update. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#camera + * @type {?Phaser.Cameras.Scene2D.Camera} + * @default null + * @since 3.0.0 + */ + this.camera = GetValue(config, 'camera', null); + + /** + * The Key to be pressed that will move the Camera left. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#left + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.left = GetValue(config, 'left', null); + + /** + * The Key to be pressed that will move the Camera right. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#right + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.right = GetValue(config, 'right', null); + + /** + * The Key to be pressed that will move the Camera up. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#up + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.up = GetValue(config, 'up', null); + + /** + * The Key to be pressed that will move the Camera down. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#down + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.down = GetValue(config, 'down', null); + + /** + * The Key to be pressed that will zoom the Camera in. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomIn + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomIn = GetValue(config, 'zoomIn', null); + + /** + * The Key to be pressed that will zoom the Camera out. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomOut + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomOut = GetValue(config, 'zoomOut', null); + + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomSpeed + * @type {number} + * @default 0.01 + * @since 3.0.0 + */ + this.zoomSpeed = GetValue(config, 'zoomSpeed', 0.01); + + /** + * The horizontal acceleration the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#accelX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelX = 0; + + /** + * The vertical acceleration the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#accelY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelY = 0; + + var accel = GetValue(config, 'acceleration', null); + + if (typeof accel === 'number') + { + this.accelX = accel; + this.accelY = accel; + } + else + { + this.accelX = GetValue(config, 'acceleration.x', 0); + this.accelY = GetValue(config, 'acceleration.y', 0); + } + + /** + * The horizontal drag applied to the camera when it is moving. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#dragX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragX = 0; + + /** + * The vertical drag applied to the camera when it is moving. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#dragY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragY = 0; + + var drag = GetValue(config, 'drag', null); + + if (typeof drag === 'number') + { + this.dragX = drag; + this.dragY = drag; + } + else + { + this.dragX = GetValue(config, 'drag.x', 0); + this.dragY = GetValue(config, 'drag.y', 0); + } + + /** + * The maximum horizontal speed the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#maxSpeedX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.maxSpeedX = 0; + + /** + * The maximum vertical speed the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#maxSpeedY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.maxSpeedY = 0; + + var maxSpeed = GetValue(config, 'maxSpeed', null); + + if (typeof maxSpeed === 'number') + { + this.maxSpeedX = maxSpeed; + this.maxSpeedY = maxSpeed; + } + else + { + this.maxSpeedX = GetValue(config, 'maxSpeed.x', 0); + this.maxSpeedY = GetValue(config, 'maxSpeed.y', 0); + } + + /** + * Internal property to track the speed of the control. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#_speedX + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._speedX = 0; + + /** + * Internal property to track the speed of the control. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#_speedY + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._speedY = 0; + + /** + * Internal property to track the zoom of the control. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#_zoom + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._zoom = 0; + + /** + * A flag controlling if the Controls will update the Camera or not. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#active + * @type {boolean} + * @since 3.0.0 + */ + this.active = (this.camera !== null); + }, + + /** + * Starts the Key Control running, providing it has been linked to a camera. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#start + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. + */ + start: function () + { + this.active = (this.camera !== null); + + return this; + }, + + /** + * Stops this Key Control from running. Call `start` to start it again. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#stop + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. + */ + stop: function () + { + this.active = false; + + return this; + }, + + /** + * Binds this Key Control to a camera. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#setCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to bind this Key Control to. + * + * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. + */ + setCamera: function (camera) + { + this.camera = camera; + + return this; + }, + + /** + * 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. + */ + update: function (delta) + { + if (!this.active) + { + return; + } + + if (delta === undefined) { delta = 1; } + + var cam = this.camera; + + // Apply Deceleration + + if (this._speedX > 0) + { + this._speedX -= this.dragX * delta; + + if (this._speedX < 0) + { + this._speedX = 0; + } + } + else if (this._speedX < 0) + { + this._speedX += this.dragX * delta; + + if (this._speedX > 0) + { + this._speedX = 0; + } + } + + if (this._speedY > 0) + { + this._speedY -= this.dragY * delta; + + if (this._speedY < 0) + { + this._speedY = 0; + } + } + else if (this._speedY < 0) + { + this._speedY += this.dragY * delta; + + if (this._speedY > 0) + { + this._speedY = 0; + } + } + + // Check for keys + + if (this.up && this.up.isDown) + { + this._speedY += this.accelY; + + if (this._speedY > this.maxSpeedY) + { + this._speedY = this.maxSpeedY; + } + } + else if (this.down && this.down.isDown) + { + this._speedY -= this.accelY; + + if (this._speedY < -this.maxSpeedY) + { + this._speedY = -this.maxSpeedY; + } + } + + if (this.left && this.left.isDown) + { + this._speedX += this.accelX; + + if (this._speedX > this.maxSpeedX) + { + this._speedX = this.maxSpeedX; + } + } + else if (this.right && this.right.isDown) + { + this._speedX -= this.accelX; + + if (this._speedX < -this.maxSpeedX) + { + this._speedX = -this.maxSpeedX; + } + } + + // Camera zoom + + if (this.zoomIn && this.zoomIn.isDown) + { + this._zoom = -this.zoomSpeed; + } + else if (this.zoomOut && this.zoomOut.isDown) + { + this._zoom = this.zoomSpeed; + } + else + { + this._zoom = 0; + } + + // Apply to Camera + + if (this._speedX !== 0) + { + cam.scrollX -= ((this._speedX * delta) | 0); + } + + if (this._speedY !== 0) + { + cam.scrollY -= ((this._speedY * delta) | 0); + } + + if (this._zoom !== 0) + { + cam.zoom += this._zoom; + + if (cam.zoom < 0.001) + { + cam.zoom = 0.001; + } + } + }, + + /** + * Destroys this Key Control. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.camera = null; + + this.left = null; + this.right = null; + this.up = null; + this.down = null; + + this.zoomIn = null; + this.zoomOut = null; + } + +}); + +module.exports = SmoothedKeyControl; + + +/***/ }), +/* 672 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Scene2D + */ + +module.exports = { + + Camera: __webpack_require__(312), + BaseCamera: __webpack_require__(103), + CameraManager: __webpack_require__(725), + Effects: __webpack_require__(320), + Events: __webpack_require__(55) + +}; + + +/***/ }), +/* 673 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Destroy Camera Event. + * + * This event is dispatched by a Camera instance when it is destroyed by the Camera Manager. + * + * @event Phaser.Cameras.Scene2D.Events#DESTROY + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that was destroyed. + */ +module.exports = 'cameradestroy'; + + +/***/ }), +/* 674 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade In Complete Event. + * + * This event is dispatched by a Camera instance when the Fade In Effect completes. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeincomplete', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + */ +module.exports = 'camerafadeincomplete'; + + +/***/ }), +/* 675 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade In Start Event. + * + * This event is dispatched by a Camera instance when the Fade In Effect starts. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeinstart', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {integer} red - The red color channel value. + * @param {integer} green - The green color channel value. + * @param {integer} blue - The blue color channel value. + */ +module.exports = 'camerafadeinstart'; + + +/***/ }), +/* 676 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade Out Complete Event. + * + * This event is dispatched by a Camera instance when the Fade Out Effect completes. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeoutcomplete', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + */ +module.exports = 'camerafadeoutcomplete'; + + +/***/ }), +/* 677 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade Out Start Event. + * + * This event is dispatched by a Camera instance when the Fade Out Effect starts. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeoutstart', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {integer} red - The red color channel value. + * @param {integer} green - The green color channel value. + * @param {integer} blue - The blue color channel value. + */ +module.exports = 'camerafadeoutstart'; + + +/***/ }), +/* 678 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Flash Complete Event. + * + * This event is dispatched by a Camera instance when the Flash Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Flash} effect - A reference to the effect instance. + */ +module.exports = 'cameraflashcomplete'; + + +/***/ }), +/* 679 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Flash Start Event. + * + * This event is dispatched by a Camera instance when the Flash Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#FLASH_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Flash} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {integer} red - The red color channel value. + * @param {integer} green - The green color channel value. + * @param {integer} blue - The blue color channel value. + */ +module.exports = 'cameraflashstart'; + + +/***/ }), +/* 680 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Pan Complete Event. + * + * This event is dispatched by a Camera instance when the Pan Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Pan} effect - A reference to the effect instance. + */ +module.exports = 'camerapancomplete'; + + +/***/ }), +/* 681 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Pan Start Event. + * + * This event is dispatched by a Camera instance when the Pan Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#PAN_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Pan} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {number} x - The destination scroll x coordinate. + * @param {number} y - The destination scroll y coordinate. + */ +module.exports = 'camerapanstart'; + + +/***/ }), +/* 682 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Post-Render Event. + * + * This event is dispatched by a Camera instance after is has finished rendering. + * It is only dispatched if the Camera is rendering to a texture. + * + * Listen to it from a Camera instance using: `camera.on('postrender', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#POST_RENDER + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that has finished rendering to a texture. + */ +module.exports = 'postrender'; + + +/***/ }), +/* 683 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Pre-Render Event. + * + * This event is dispatched by a Camera instance when it is about to render. + * It is only dispatched if the Camera is rendering to a texture. + * + * Listen to it from a Camera instance using: `camera.on('prerender', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#PRE_RENDER + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that is about to render to a texture. + */ +module.exports = 'prerender'; + + +/***/ }), +/* 684 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Shake Complete Event. + * + * This event is dispatched by a Camera instance when the Shake Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Shake} effect - A reference to the effect instance. + */ +module.exports = 'camerashakecomplete'; + + +/***/ }), +/* 685 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Shake Start Event. + * + * This event is dispatched by a Camera instance when the Shake Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#SHAKE_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Shake} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {number} intensity - The intensity of the effect. + */ +module.exports = 'camerashakestart'; + + +/***/ }), +/* 686 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Zoom Complete Event. + * + * This event is dispatched by a Camera instance when the Zoom Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance. + */ +module.exports = 'camerazoomcomplete'; + + +/***/ }), +/* 687 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Zoom Start Event. + * + * This event is dispatched by a Camera instance when the Zoom Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#ZOOM_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {number} zoom - The destination zoom value. + */ +module.exports = 'camerazoomstart'; + + +/***/ }), +/* 688 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var Events = __webpack_require__(55); + +/** + * @classdesc + * A Camera Fade effect. + * + * This effect will fade the camera viewport to the given color, over the duration specified. + * + * Only the camera viewport is faded. None of the objects it is displaying are impacted, i.e. their colors 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 Fade + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.5.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Fade = new Class({ + + initialize: + + function Fade (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.5.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isRunning = false; + + /** + * Has this effect finished running? + * + * This is different from `isRunning` because it remains set to `true` when the effect is over, + * until the effect is either reset or started again. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#isComplete + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isComplete = false; + + /** + * The direction of the fade. + * `true` = fade out (transparent to color), `false` = fade in (color to transparent) + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#direction + * @type {boolean} + * @readonly + * @since 3.5.0 + */ + this.direction = true; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.5.0 + */ + this.duration = 0; + + /** + * The value of the red color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#red + * @type {integer} + * @private + * @since 3.5.0 + */ + this.red = 0; + + /** + * The value of the green color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#green + * @type {integer} + * @private + * @since 3.5.0 + */ + this.green = 0; + + /** + * The value of the blue color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#blue + * @type {integer} + * @private + * @since 3.5.0 + */ + this.blue = 0; + + /** + * The value of the alpha channel used during the fade effect. + * A value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#alpha + * @type {number} + * @private + * @since 3.5.0 + */ + this.alpha = 0; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#progress + * @type {number} + * @since 3.5.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#_elapsed + * @type {number} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraFadeCallback} + * @private + * @default null + * @since 3.5.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#_onUpdateScope + * @type {any} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + }, + + /** + * Fades the Camera to or from the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#start + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @since 3.5.0 + * + * @param {boolean} [direction=true] - The direction of the fade. `true` = fade out (transparent to color), `false` = fade in (color to transparent) + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraFadeCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (direction, duration, red, green, blue, force, callback, context) + { + if (direction === undefined) { direction = true; } + if (duration === undefined) { duration = 1000; } + if (red === undefined) { red = 0; } + if (green === undefined) { green = 0; } + if (blue === undefined) { blue = 0; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + if (!force && this.isRunning) + { + return this.camera; + } + + this.isRunning = true; + this.isComplete = false; + this.duration = duration; + this.direction = direction; + this.progress = 0; + + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = (direction) ? Number.MIN_VALUE : 1; + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + var eventName = (direction) ? Events.FADE_OUT_START : Events.FADE_IN_START; + + this.camera.emit(eventName, this.camera, this, duration, red, green, blue); + + return this.camera; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#update + * @since 3.5.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); + } + + if (this._elapsed < this.duration) + { + this.alpha = (this.direction) ? this.progress : 1 - this.progress; + } + else + { + this.alpha = (this.direction) ? 1 : 0; + this.effectComplete(); + } + }, + + /** + * Called internally by the Canvas Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#postRenderCanvas + * @since 3.5.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas context to render to. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderCanvas: function (ctx) + { + if (!this.isRunning && !this.isComplete) + { + return false; + } + + var camera = this.camera; + + ctx.fillStyle = 'rgba(' + this.red + ',' + this.green + ',' + this.blue + ',' + this.alpha + ')'; + ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); + + return true; + }, + + /** + * Called internally by the WebGL Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#postRenderWebGL + * @since 3.5.0 + * + * @param {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} pipeline - The WebGL Pipeline to render to. + * @param {function} getTintFunction - A function that will return the gl safe tint colors. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderWebGL: function (pipeline, getTintFunction) + { + if (!this.isRunning && !this.isComplete) + { + return false; + } + + var camera = this.camera; + var red = this.red / 255; + var blue = this.blue / 255; + var green = this.green / 255; + + pipeline.drawFillRect( + camera._cx, camera._cy, camera._cw, camera._ch, + getTintFunction(red, green, blue, 1), + this.alpha + ); + + return true; + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.5.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + this.isComplete = true; + + var eventName = (this.direction) ? Events.FADE_OUT_COMPLETE : Events.FADE_IN_COMPLETE; + + this.camera.emit(eventName, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#reset + * @since 3.5.0 + */ + reset: function () + { + this.isRunning = false; + this.isComplete = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + } + +}); + +module.exports = Fade; + + +/***/ }), +/* 689 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var Events = __webpack_require__(55); + +/** + * @classdesc + * A Camera Flash effect. + * + * This effect will flash the camera viewport to the given color, over the duration specified. + * + * Only the camera viewport is flashed. None of the objects it is displaying are impacted, i.e. their colors 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 Flash + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.5.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Flash = new Class({ + + initialize: + + function Flash (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.5.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.5.0 + */ + this.duration = 0; + + /** + * The value of the red color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#red + * @type {integer} + * @private + * @since 3.5.0 + */ + this.red = 0; + + /** + * The value of the green color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#green + * @type {integer} + * @private + * @since 3.5.0 + */ + this.green = 0; + + /** + * The value of the blue color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#blue + * @type {integer} + * @private + * @since 3.5.0 + */ + this.blue = 0; + + /** + * The value of the alpha channel used during the fade effect. + * A value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#alpha + * @type {number} + * @private + * @since 3.5.0 + */ + this.alpha = 0; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#progress + * @type {number} + * @since 3.5.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#_elapsed + * @type {number} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraFlashCallback} + * @private + * @default null + * @since 3.5.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#_onUpdateScope + * @type {any} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + }, + + /** + * Flashes the Camera to or from the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#start + * @fires Phaser.Cameras.Scene2D.Events#FLASH_START + * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.5.0 + * + * @param {integer} [duration=250] - The duration of the effect in milliseconds. + * @param {integer} [red=255] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=255] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=255] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraFlashCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (duration, red, green, blue, force, callback, context) + { + if (duration === undefined) { duration = 250; } + if (red === undefined) { red = 255; } + if (green === undefined) { green = 255; } + if (blue === undefined) { blue = 255; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + if (!force && this.isRunning) + { + return this.camera; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = 1; + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.FLASH_START, this.camera, this, duration, red, green, blue); + + return this.camera; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#update + * @since 3.5.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); + } + + if (this._elapsed < this.duration) + { + this.alpha = 1 - this.progress; + } + else + { + this.effectComplete(); + } + }, + + /** + * Called internally by the Canvas Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#postRenderCanvas + * @since 3.5.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas context to render to. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderCanvas: function (ctx) + { + if (!this.isRunning) + { + return false; + } + + var camera = this.camera; + + ctx.fillStyle = 'rgba(' + this.red + ',' + this.green + ',' + this.blue + ',' + this.alpha + ')'; + ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); + + return true; + }, + + /** + * Called internally by the WebGL Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#postRenderWebGL + * @since 3.5.0 + * + * @param {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} pipeline - The WebGL Pipeline to render to. + * @param {function} getTintFunction - A function that will return the gl safe tint colors. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderWebGL: function (pipeline, getTintFunction) + { + if (!this.isRunning) + { + return false; + } + + var camera = this.camera; + var red = this.red / 255; + var blue = this.blue / 255; + var green = this.green / 255; + + pipeline.drawFillRect( + camera._cx, camera._cy, camera._cw, camera._ch, + getTintFunction(red, green, blue, 1), + this.alpha + ); + + return true; + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.5.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.FLASH_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#reset + * @since 3.5.0 + */ + reset: function () + { + this.isRunning = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + } + +}); + +module.exports = Flash; + + +/***/ }), +/* 690 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var EaseMap = __webpack_require__(179); +var Events = __webpack_require__(55); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Camera Pan effect. + * + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * Only the camera scroll is moved. 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 Pan + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.11.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Pan = new Class({ + + initialize: + + function Pan (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.11.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.11.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.11.0 + */ + this.duration = 0; + + /** + * The starting scroll coordinates to pan the camera from. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#source + * @type {Phaser.Math.Vector2} + * @since 3.11.0 + */ + this.source = new Vector2(); + + /** + * The constantly updated value based on zoom. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#current + * @type {Phaser.Math.Vector2} + * @since 3.11.0 + */ + this.current = new Vector2(); + + /** + * The destination scroll coordinates to pan the camera to. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#destination + * @type {Phaser.Math.Vector2} + * @since 3.11.0 + */ + this.destination = new Vector2(); + + /** + * The ease function to use during the pan. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#ease + * @type {function} + * @since 3.11.0 + */ + this.ease; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#progress + * @type {number} + * @since 3.11.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#_elapsed + * @type {number} + * @private + * @since 3.11.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraPanCallback} + * @private + * @default null + * @since 3.11.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#_onUpdateScope + * @type {any} + * @private + * @since 3.11.0 + */ + this._onUpdateScope; + }, + + /** + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#start + * @fires Phaser.Cameras.Scene2D.Events#PAN_START + * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.11.0 + * + * @param {number} x - The destination x coordinate to scroll the center of the Camera viewport to. + * @param {number} y - The destination y coordinate to scroll the center of the Camera viewport to. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (x, y, duration, ease, force, callback, context) + { + if (duration === undefined) { duration = 1000; } + if (ease === undefined) { ease = EaseMap.Linear; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + var cam = this.camera; + + if (!force && this.isRunning) + { + return cam; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + // Starting from + this.source.set(cam.scrollX, cam.scrollY); + + // Destination + this.destination.set(x, y); + + // Zoom factored version + cam.getScroll(x, y, this.current); + + // Using this ease + if (typeof ease === 'string' && EaseMap.hasOwnProperty(ease)) + { + this.ease = EaseMap[ease]; + } + else if (typeof ease === 'function') + { + this.ease = ease; + } + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.PAN_START, this.camera, this, duration, x, y); + + return cam; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#update + * @since 3.11.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + var progress = Clamp(this._elapsed / this.duration, 0, 1); + + this.progress = progress; + + var cam = this.camera; + + if (this._elapsed < this.duration) + { + var v = this.ease(progress); + + cam.getScroll(this.destination.x, this.destination.y, this.current); + + var x = this.source.x + ((this.current.x - this.source.x) * v); + var y = this.source.y + ((this.current.y - this.source.y) * v); + + cam.setScroll(x, y); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, cam, progress, x, y); + } + } + else + { + cam.centerOn(this.destination.x, this.destination.y); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, cam, progress, cam.scrollX, cam.scrollY); + } + + this.effectComplete(); + } + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.11.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.PAN_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#reset + * @since 3.11.0 + */ + reset: function () + { + this.isRunning = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#destroy + * @since 3.11.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + this.source = null; + this.destination = null; + } + +}); + +module.exports = Pan; + + +/***/ }), +/* 691 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Back ease-in. + * + * @function Phaser.Math.Easing.Back.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [overshoot=1.70158] - The overshoot amount. + * + * @return {number} The tweened value. + */ +var In = function (v, overshoot) +{ + if (overshoot === undefined) { overshoot = 1.70158; } + + return v * v * ((overshoot + 1) * v - overshoot); +}; + +module.exports = In; + + +/***/ }), +/* 692 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Back ease-out. + * + * @function Phaser.Math.Easing.Back.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [overshoot=1.70158] - The overshoot amount. + * + * @return {number} The tweened value. + */ +var Out = function (v, overshoot) +{ + if (overshoot === undefined) { overshoot = 1.70158; } + + return --v * v * ((overshoot + 1) * v + overshoot) + 1; +}; + +module.exports = Out; + + +/***/ }), +/* 693 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Back ease-in/out. + * + * @function Phaser.Math.Easing.Back.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [overshoot=1.70158] - The overshoot amount. + * + * @return {number} The tweened value. + */ +var InOut = function (v, overshoot) +{ + if (overshoot === undefined) { overshoot = 1.70158; } + + var s = overshoot * 1.525; + + if ((v *= 2) < 1) + { + return 0.5 * (v * v * ((s + 1) * v - s)); + } + else + { + return 0.5 * ((v -= 2) * v * ((s + 1) * v + s) + 2); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 694 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Bounce ease-in. + * + * @function Phaser.Math.Easing.Bounce.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + v = 1 - v; + + if (v < 1 / 2.75) + { + return 1 - (7.5625 * v * v); + } + else if (v < 2 / 2.75) + { + return 1 - (7.5625 * (v -= 1.5 / 2.75) * v + 0.75); + } + else if (v < 2.5 / 2.75) + { + return 1 - (7.5625 * (v -= 2.25 / 2.75) * v + 0.9375); + } + else + { + return 1 - (7.5625 * (v -= 2.625 / 2.75) * v + 0.984375); + } +}; + +module.exports = In; + + +/***/ }), +/* 695 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Bounce ease-out. + * + * @function Phaser.Math.Easing.Bounce.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + if (v < 1 / 2.75) + { + return 7.5625 * v * v; + } + else if (v < 2 / 2.75) + { + return 7.5625 * (v -= 1.5 / 2.75) * v + 0.75; + } + else if (v < 2.5 / 2.75) + { + return 7.5625 * (v -= 2.25 / 2.75) * v + 0.9375; + } + else + { + return 7.5625 * (v -= 2.625 / 2.75) * v + 0.984375; + } +}; + +module.exports = Out; + + +/***/ }), +/* 696 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Bounce ease-in/out. + * + * @function Phaser.Math.Easing.Bounce.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + var reverse = false; + + if (v < 0.5) + { + v = 1 - (v * 2); + reverse = true; + } + else + { + v = (v * 2) - 1; + } + + if (v < 1 / 2.75) + { + v = 7.5625 * v * v; + } + else if (v < 2 / 2.75) + { + v = 7.5625 * (v -= 1.5 / 2.75) * v + 0.75; + } + else if (v < 2.5 / 2.75) + { + v = 7.5625 * (v -= 2.25 / 2.75) * v + 0.9375; + } + else + { + v = 7.5625 * (v -= 2.625 / 2.75) * v + 0.984375; + } + + if (reverse) + { + return (1 - v) * 0.5; + } + else + { + return v * 0.5 + 0.5; + } +}; + +module.exports = InOut; + + +/***/ }), +/* 697 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Circular ease-in. + * + * @function Phaser.Math.Easing.Circular.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return 1 - Math.sqrt(1 - v * v); +}; + +module.exports = In; + + +/***/ }), +/* 698 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Circular ease-out. + * + * @function Phaser.Math.Easing.Circular.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return Math.sqrt(1 - (--v * v)); +}; + +module.exports = Out; + + +/***/ }), +/* 699 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Circular ease-in/out. + * + * @function Phaser.Math.Easing.Circular.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return -0.5 * (Math.sqrt(1 - v * v) - 1); + } + else + { + return 0.5 * (Math.sqrt(1 - (v -= 2) * v) + 1); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 700 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Cubic ease-in. + * + * @function Phaser.Math.Easing.Cubic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v * v; +}; + +module.exports = In; + + +/***/ }), +/* 701 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Cubic ease-out. + * + * @function Phaser.Math.Easing.Cubic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return --v * v * v + 1; +}; + +module.exports = Out; + + +/***/ }), +/* 702 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Cubic ease-in/out. + * + * @function Phaser.Math.Easing.Cubic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v * v; + } + else + { + return 0.5 * ((v -= 2) * v * v + 2); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 703 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Elastic ease-in. + * + * @function Phaser.Math.Easing.Elastic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. + * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. + * + * @return {number} The tweened value. + */ +var In = function (v, amplitude, period) +{ + if (amplitude === undefined) { amplitude = 0.1; } + if (period === undefined) { period = 0.1; } + + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + var s = period / 4; + + if (amplitude < 1) + { + amplitude = 1; + } + else + { + s = period * Math.asin(1 / amplitude) / (2 * Math.PI); + } + + return -(amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)); + } +}; + +module.exports = In; + + +/***/ }), +/* 704 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Elastic ease-out. + * + * @function Phaser.Math.Easing.Elastic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. + * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. + * + * @return {number} The tweened value. + */ +var Out = function (v, amplitude, period) +{ + if (amplitude === undefined) { amplitude = 0.1; } + if (period === undefined) { period = 0.1; } + + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + var s = period / 4; + + if (amplitude < 1) + { + amplitude = 1; + } + else + { + s = period * Math.asin(1 / amplitude) / (2 * Math.PI); + } + + return (amplitude * Math.pow(2, -10 * v) * Math.sin((v - s) * (2 * Math.PI) / period) + 1); + } +}; + +module.exports = Out; + + +/***/ }), +/* 705 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Elastic ease-in/out. + * + * @function Phaser.Math.Easing.Elastic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. + * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. + * + * @return {number} The tweened value. + */ +var InOut = function (v, amplitude, period) +{ + if (amplitude === undefined) { amplitude = 0.1; } + if (period === undefined) { period = 0.1; } + + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + var s = period / 4; + + if (amplitude < 1) + { + amplitude = 1; + } + else + { + s = period * Math.asin(1 / amplitude) / (2 * Math.PI); + } + + if ((v *= 2) < 1) + { + return -0.5 * (amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)); + } + else + { + return amplitude * Math.pow(2, -10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period) * 0.5 + 1; + } + } +}; + +module.exports = InOut; + + +/***/ }), +/* 706 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Exponential ease-in. + * + * @function Phaser.Math.Easing.Expo.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return Math.pow(2, 10 * (v - 1)) - 0.001; +}; + +module.exports = In; + + +/***/ }), +/* 707 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Exponential ease-out. + * + * @function Phaser.Math.Easing.Expo.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return 1 - Math.pow(2, -10 * v); +}; + +module.exports = Out; + + +/***/ }), +/* 708 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Exponential ease-in/out. + * + * @function Phaser.Math.Easing.Expo.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * Math.pow(2, 10 * (v - 1)); + } + else + { + return 0.5 * (2 - Math.pow(2, -10 * (v - 1))); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 709 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Linear easing (no variation). + * + * @function Phaser.Math.Easing.Linear.Linear + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Linear = function (v) +{ + return v; +}; + +module.exports = Linear; + + +/***/ }), +/* 710 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quadratic ease-in. + * + * @function Phaser.Math.Easing.Quadratic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v; +}; + +module.exports = In; + + +/***/ }), +/* 711 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quadratic ease-out. + * + * @function Phaser.Math.Easing.Quadratic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return v * (2 - v); +}; + +module.exports = Out; + + +/***/ }), +/* 712 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quadratic ease-in/out. + * + * @function Phaser.Math.Easing.Quadratic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v; + } + else + { + return -0.5 * (--v * (v - 2) - 1); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 713 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quartic ease-in. + * + * @function Phaser.Math.Easing.Quartic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v * v * v; +}; + +module.exports = In; + + +/***/ }), +/* 714 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quartic ease-out. + * + * @function Phaser.Math.Easing.Quartic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return 1 - (--v * v * v * v); +}; + +module.exports = Out; + + +/***/ }), +/* 715 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quartic ease-in/out. + * + * @function Phaser.Math.Easing.Quartic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v * v * v; + } + else + { + return -0.5 * ((v -= 2) * v * v * v - 2); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 716 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quintic ease-in. + * + * @function Phaser.Math.Easing.Quintic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v * v * v * v; +}; + +module.exports = In; + + +/***/ }), +/* 717 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quintic ease-out. + * + * @function Phaser.Math.Easing.Quintic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return --v * v * v * v * v + 1; +}; + +module.exports = Out; + + +/***/ }), +/* 718 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quintic ease-in/out. + * + * @function Phaser.Math.Easing.Quintic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v * v * v * v; + } + else + { + return 0.5 * ((v -= 2) * v * v * v * v + 2); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 719 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sinusoidal ease-in. + * + * @function Phaser.Math.Easing.Sine.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + return 1 - Math.cos(v * Math.PI / 2); + } +}; + +module.exports = In; + + +/***/ }), +/* 720 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sinusoidal ease-out. + * + * @function Phaser.Math.Easing.Sine.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + return Math.sin(v * Math.PI / 2); + } +}; + +module.exports = Out; + + +/***/ }), +/* 721 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sinusoidal ease-in/out. + * + * @function Phaser.Math.Easing.Sine.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + return 0.5 * (1 - Math.cos(Math.PI * v)); + } +}; + +module.exports = InOut; + + +/***/ }), +/* 722 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Stepped easing. + * + * @function Phaser.Math.Easing.Stepped.Stepped + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [steps=1] - The number of steps in the ease. + * + * @return {number} The tweened value. + */ +var Stepped = function (v, steps) +{ + if (steps === undefined) { steps = 1; } + + if (v <= 0) + { + return 0; + } + else if (v >= 1) + { + return 1; + } + else + { + return (((steps * v) | 0) + 1) * (1 / steps); + } +}; + +module.exports = Stepped; + + +/***/ }), +/* 723 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var Events = __webpack_require__(55); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A Camera Shake effect. + * + * This effect will shake the camera viewport by a random amount, bounded by the specified intensity, each frame. + * + * Only the camera viewport is moved. 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 Shake + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.5.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Shake = new Class({ + + initialize: + + function Shake (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.5.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.5.0 + */ + this.duration = 0; + + /** + * The intensity of the effect. Use small float values. The default when the effect starts is 0.05. + * This is a Vector2 object, allowing you to control the shake intensity independently across x and y. + * You can modify this value while the effect is active to create more varied shake effects. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#intensity + * @type {Phaser.Math.Vector2} + * @since 3.5.0 + */ + this.intensity = new Vector2(); + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#progress + * @type {number} + * @since 3.5.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_elapsed + * @type {number} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * How much to offset the camera by horizontally. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_offsetX + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._offsetX = 0; + + /** + * How much to offset the camera by vertically. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_offsetY + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._offsetY = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraShakeCallback} + * @private + * @default null + * @since 3.5.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_onUpdateScope + * @type {any} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + }, + + /** + * Shakes the Camera by the given intensity over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#start + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_START + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.5.0 + * + * @param {integer} [duration=100] - The duration of the effect in milliseconds. + * @param {(number|Phaser.Math.Vector2)} [intensity=0.05] - The intensity of the shake. + * @param {boolean} [force=false] - Force the shake effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraShakeCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (duration, intensity, force, callback, context) + { + if (duration === undefined) { duration = 100; } + if (intensity === undefined) { intensity = 0.05; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + if (!force && this.isRunning) + { + return this.camera; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + if (typeof intensity === 'number') + { + this.intensity.set(intensity); + } + else + { + this.intensity.set(intensity.x, intensity.y); + } + + this._elapsed = 0; + this._offsetX = 0; + this._offsetY = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.SHAKE_START, this.camera, this, duration, intensity); + + return this.camera; + }, + + /** + * The pre-render step for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#preRender + * @since 3.5.0 + */ + preRender: function () + { + if (this.isRunning) + { + this.camera.matrix.translate(this._offsetX, this._offsetY); + } + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#update + * @since 3.5.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); + } + + if (this._elapsed < this.duration) + { + var intensity = this.intensity; + var width = this.camera._cw; + var height = this.camera._ch; + var zoom = this.camera.zoom; + + this._offsetX = (Math.random() * intensity.x * width * 2 - intensity.x * width) * zoom; + this._offsetY = (Math.random() * intensity.y * height * 2 - intensity.y * height) * zoom; + + if (this.camera.roundPixels) + { + this._offsetX = Math.round(this._offsetX); + this._offsetY = Math.round(this._offsetY); + } + } + else + { + this.effectComplete(); + } + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.5.0 + */ + effectComplete: function () + { + this._offsetX = 0; + this._offsetY = 0; + + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.SHAKE_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#reset + * @since 3.5.0 + */ + reset: function () + { + this.isRunning = false; + + this._offsetX = 0; + this._offsetY = 0; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + this.intensity = null; + } + +}); + +module.exports = Shake; + + +/***/ }), +/* 724 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var EaseMap = __webpack_require__(179); +var Events = __webpack_require__(55); + +/** + * @classdesc + * A Camera Zoom effect. + * + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * 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 Zoom + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.11.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Zoom = new Class({ + + initialize: + + function Zoom (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.11.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.11.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.11.0 + */ + this.duration = 0; + + /** + * The starting zoom value; + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#source + * @type {number} + * @since 3.11.0 + */ + this.source = 1; + + /** + * The destination zoom value. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#destination + * @type {number} + * @since 3.11.0 + */ + this.destination = 1; + + /** + * The ease function to use during the zoom. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#ease + * @type {function} + * @since 3.11.0 + */ + this.ease; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#progress + * @type {number} + * @since 3.11.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#_elapsed + * @type {number} + * @private + * @since 3.11.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraZoomCallback} + * @private + * @default null + * @since 3.11.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#_onUpdateScope + * @type {any} + * @private + * @since 3.11.0 + */ + this._onUpdateScope; + }, + + /** + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#start + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_START + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.11.0 + * + * @param {number} zoom - The target Camera zoom value. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the Zoom. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the zoom effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraZoomCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent three arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * and the current camera zoom value. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (zoom, duration, ease, force, callback, context) + { + if (duration === undefined) { duration = 1000; } + if (ease === undefined) { ease = EaseMap.Linear; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + var cam = this.camera; + + if (!force && this.isRunning) + { + return cam; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + // Starting from + this.source = cam.zoom; + + // Zooming to + this.destination = zoom; + + // Using this ease + if (typeof ease === 'string' && EaseMap.hasOwnProperty(ease)) + { + this.ease = EaseMap[ease]; + } + else if (typeof ease === 'function') + { + this.ease = ease; + } + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.ZOOM_START, this.camera, this, duration, zoom); + + return cam; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#update + * @since 3.11.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._elapsed < this.duration) + { + this.camera.zoom = this.source + ((this.destination - this.source) * this.ease(this.progress)); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.camera.zoom); + } + } + else + { + this.camera.zoom = this.destination; + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.destination); + } + + this.effectComplete(); + } + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.11.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.ZOOM_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#reset + * @since 3.11.0 + */ + reset: function () + { + this.isRunning = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#destroy + * @since 3.11.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + } + +}); + +module.exports = Zoom; + + +/***/ }), +/* 725 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Camera = __webpack_require__(312); +var Class = __webpack_require__(0); +var GetFastValue = __webpack_require__(1); +var PluginCache = __webpack_require__(22); +var RectangleContains = __webpack_require__(53); +var ScaleEvents = __webpack_require__(104); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * The Camera Manager is a plugin that belongs to a Scene and is responsible for managing all of the Scene Cameras. + * + * By default you can access the Camera Manager from within a Scene using `this.cameras`, although this can be changed + * in your game config. + * + * Create new Cameras using the `add` method. Or extend the Camera class with your own addition code and then add + * the new Camera in using the `addExisting` method. + * + * Cameras provide a view into your game world, and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. The Camera Manager can manage up to 31 unique + * 'Game Object ignore capable' Cameras. Any Cameras beyond 31 that you create will all be given a Camera ID of + * zero, meaning that they cannot be used for Game Object exclusion. This means if you need your Camera to ignore + * Game Objects, make sure it's one of the first 31 created. + * + * A Camera also has built-in special effects including Fade, Flash, Camera Shake, Pan and Zoom. + * + * @class CameraManager + * @memberof Phaser.Cameras.Scene2D + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that owns the Camera Manager plugin. + */ +var CameraManager = new Class({ + + initialize: + + function CameraManager (scene) + { + /** + * The Scene that owns the Camera Manager plugin. + * + * @name Phaser.Cameras.Scene2D.CameraManager#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene.Systems handler for the Scene that owns the Camera Manager. + * + * @name Phaser.Cameras.Scene2D.CameraManager#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * All Cameras created by, or added to, this Camera Manager, will have their `roundPixels` + * property set to match this value. By default it is set to match the value set in the + * game configuration, but can be changed at any point. Equally, individual cameras can + * also be changed as needed. + * + * @name Phaser.Cameras.Scene2D.CameraManager#roundPixels + * @type {boolean} + * @since 3.11.0 + */ + this.roundPixels = scene.sys.game.config.roundPixels; + + /** + * An Array of the Camera objects being managed by this Camera Manager. + * The Cameras are updated and rendered in the same order in which they appear in this array. + * Do not directly add or remove entries to this array. However, you can move the contents + * around the array should you wish to adjust the display order. + * + * @name Phaser.Cameras.Scene2D.CameraManager#cameras + * @type {Phaser.Cameras.Scene2D.Camera[]} + * @since 3.0.0 + */ + this.cameras = []; + + /** + * A handy reference to the 'main' camera. By default this is the first Camera the + * Camera Manager creates. You can also set it directly, or use the `makeMain` argument + * in the `add` and `addExisting` methods. It allows you to access it from your game: + * + * ```javascript + * var cam = this.cameras.main; + * ``` + * + * Also see the properties `camera1`, `camera2` and so on. + * + * @name Phaser.Cameras.Scene2D.CameraManager#main + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.0.0 + */ + this.main; + + /** + * A default un-transformed Camera that doesn't exist on the camera list and doesn't + * count towards the total number of cameras being managed. It exists for other + * systems, as well as your own code, should they require a basic un-transformed + * camera instance from which to calculate a view matrix. + * + * @name Phaser.Cameras.Scene2D.CameraManager#default + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.17.0 + */ + this.default; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Cameras.Scene2D.CameraManager#boot + * @private + * @listens Phaser.Scenes.Events#DESTROY + * @since 3.5.1 + */ + boot: function () + { + var sys = this.systems; + + if (sys.settings.cameras) + { + // We have cameras to create + this.fromJSON(sys.settings.cameras); + } + else + { + // Make one + this.add(); + } + + this.main = this.cameras[0]; + + // Create a default camera + this.default = new Camera(0, 0, sys.scale.width, sys.scale.height).setScene(this.scene); + + sys.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Cameras.Scene2D.CameraManager#start + * @private + * @listens Phaser.Scenes.Events#UPDATE + * @listens Phaser.Scenes.Events#SHUTDOWN + * @since 3.5.0 + */ + start: function () + { + if (!this.main) + { + var sys = this.systems; + + if (sys.settings.cameras) + { + // We have cameras to create + this.fromJSON(sys.settings.cameras); + } + else + { + // Make one + this.add(); + } + + this.main = this.cameras[0]; + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.update, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * 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 {integer} [x=0] - The horizontal position of the Camera viewport. + * @param {integer} [y=0] - The vertical position of the Camera viewport. + * @param {integer} [width] - The width of the Camera viewport. If not given it'll be the game config size. + * @param {integer} [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. + */ + add: function (x, y, width, height, makeMain, name) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (makeMain === undefined) { makeMain = false; } + if (name === undefined) { name = ''; } + + var camera = new Camera(x, y, width, height); + + camera.setName(name); + camera.setScene(this.scene); + camera.setRoundPixels(this.roundPixels); + + camera.id = this.getNextID(); + + this.cameras.push(camera); + + if (makeMain) + { + this.main = camera; + } + + return camera; + }, + + /** + * Adds an existing Camera into the Camera Manager. + * + * The Camera should either be a `Phaser.Cameras.Scene2D.Camera` instance, or a class that extends from it. + * + * The Camera will have its `roundPixels` property set to whatever `CameraManager.roundPixels` is. You can change + * it after addition if required. + * + * The Camera will be assigned an ID, which is used for Game Object exclusion and then added to the + * manager. As long as it doesn't already exist in the manager it will be added then returned. + * + * If this method returns `null` then the Camera already exists in this Camera Manager. + * + * @method Phaser.Cameras.Scene2D.CameraManager#addExisting + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to be added to the Camera Manager. + * @param {boolean} [makeMain=false] - Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. + * + * @return {?Phaser.Cameras.Scene2D.Camera} The Camera that was added to the Camera Manager, or `null` if it couldn't be added. + */ + addExisting: function (camera, makeMain) + { + if (makeMain === undefined) { makeMain = false; } + + var index = this.cameras.indexOf(camera); + + if (index === -1) + { + camera.id = this.getNextID(); + + camera.setRoundPixels(this.roundPixels); + + this.cameras.push(camera); + + if (makeMain) + { + this.main = camera; + } + + return camera; + } + + return null; + }, + + /** + * Gets the next available Camera ID number. + * + * The Camera Manager supports up to 31 unique cameras, after which the ID returned will always be zero. + * You can create additional cameras beyond 31, but they cannot be used for Game Object exclusion. + * + * @method Phaser.Cameras.Scene2D.CameraManager#getNextID + * @private + * @since 3.11.0 + * + * @return {number} The next available Camera ID, or 0 if they're all already in use. + */ + getNextID: function () + { + var cameras = this.cameras; + + var testID = 1; + + // Find the first free camera ID we can use + + for (var t = 0; t < 32; t++) + { + var found = false; + + for (var i = 0; i < cameras.length; i++) + { + var camera = cameras[i]; + + if (camera && camera.id === testID) + { + found = true; + continue; + } + } + + if (found) + { + testID = testID << 1; + } + else + { + return testID; + } + } + + return 0; + }, + + /** + * Gets the total number of Cameras in this Camera Manager. + * + * If the optional `isVisible` argument is set it will only count Cameras that are currently visible. + * + * @method Phaser.Cameras.Scene2D.CameraManager#getTotal + * @since 3.11.0 + * + * @param {boolean} [isVisible=false] - Set the `true` to only include visible Cameras in the total. + * + * @return {integer} The total number of Cameras in this Camera Manager. + */ + getTotal: function (isVisible) + { + if (isVisible === undefined) { isVisible = false; } + + var total = 0; + + var cameras = this.cameras; + + for (var i = 0; i < cameras.length; i++) + { + var camera = cameras[i]; + + if (!isVisible || (isVisible && camera.visible)) + { + total++; + } + } + + return total; + }, + + /** + * 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 {Phaser.Cameras.Scene2D.CameraManager} This Camera Manager instance. + */ + fromJSON: function (config) + { + if (!Array.isArray(config)) + { + config = [ config ]; + } + + var gameWidth = this.scene.sys.scale.width; + var gameHeight = this.scene.sys.scale.height; + + for (var i = 0; i < config.length; i++) + { + var cameraConfig = config[i]; + + var x = GetFastValue(cameraConfig, 'x', 0); + var y = GetFastValue(cameraConfig, 'y', 0); + var width = GetFastValue(cameraConfig, 'width', gameWidth); + var height = GetFastValue(cameraConfig, 'height', gameHeight); + + var camera = this.add(x, y, width, height); + + // Direct properties + camera.name = GetFastValue(cameraConfig, 'name', ''); + camera.zoom = GetFastValue(cameraConfig, 'zoom', 1); + camera.rotation = GetFastValue(cameraConfig, 'rotation', 0); + camera.scrollX = GetFastValue(cameraConfig, 'scrollX', 0); + camera.scrollY = GetFastValue(cameraConfig, 'scrollY', 0); + camera.roundPixels = GetFastValue(cameraConfig, 'roundPixels', false); + camera.visible = GetFastValue(cameraConfig, 'visible', true); + + // Background Color + + var backgroundColor = GetFastValue(cameraConfig, 'backgroundColor', false); + + if (backgroundColor) + { + camera.setBackgroundColor(backgroundColor); + } + + // Bounds + + var boundsConfig = GetFastValue(cameraConfig, 'bounds', null); + + if (boundsConfig) + { + var bx = GetFastValue(boundsConfig, 'x', 0); + var by = GetFastValue(boundsConfig, 'y', 0); + var bwidth = GetFastValue(boundsConfig, 'width', gameWidth); + var bheight = GetFastValue(boundsConfig, 'height', gameHeight); + + camera.setBounds(bx, by, bwidth, bheight); + } + } + + return this; + }, + + /** + * 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`. + */ + getCamera: function (name) + { + var cameras = this.cameras; + + for (var i = 0; i < cameras.length; i++) + { + if (cameras[i].name === name) + { + return cameras[i]; + } + } + + return null; + }, + + /** + * Returns an array of all cameras below the given Pointer. + * + * The first camera in the array is the top-most camera in the camera list. + * + * @method Phaser.Cameras.Scene2D.CameraManager#getCamerasBelowPointer + * @since 3.10.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to check against. + * + * @return {Phaser.Cameras.Scene2D.Camera[]} An array of cameras below the Pointer. + */ + getCamerasBelowPointer: function (pointer) + { + var cameras = this.cameras; + + var x = pointer.x; + var y = pointer.y; + + var output = []; + + for (var i = 0; i < cameras.length; i++) + { + var camera = cameras[i]; + + if (camera.visible && camera.inputEnabled && RectangleContains(camera, x, y)) + { + // So the top-most camera is at the top of the search array + output.unshift(camera); + } + } + + return output; + }, + + /** + * Removes the given Camera, or an array of Cameras, from this Camera Manager. + * + * If found in the Camera Manager it will be immediately removed from the local cameras array. + * If also currently the 'main' camera, 'main' will be reset to be camera 0. + * + * The removed Cameras are automatically destroyed if the `runDestroy` argument is `true`, which is the default. + * If you wish to re-use the cameras then set this to `false`, but know that they will retain their references + * and internal data until destroyed or re-added to a Camera Manager. + * + * @method Phaser.Cameras.Scene2D.CameraManager#remove + * @since 3.0.0 + * + * @param {(Phaser.Cameras.Scene2D.Camera|Phaser.Cameras.Scene2D.Camera[])} camera - The Camera, or an array of Cameras, to be removed from this Camera Manager. + * @param {boolean} [runDestroy=true] - Automatically call `Camera.destroy` on each Camera removed from this Camera Manager. + * + * @return {integer} The total number of Cameras removed. + */ + remove: function (camera, runDestroy) + { + if (runDestroy === undefined) { runDestroy = true; } + + if (!Array.isArray(camera)) + { + camera = [ camera ]; + } + + var total = 0; + var cameras = this.cameras; + + for (var i = 0; i < camera.length; i++) + { + var index = cameras.indexOf(camera[i]); + + if (index !== -1) + { + if (runDestroy) + { + cameras[index].destroy(); + } + + cameras.splice(index, 1); + + total++; + } + } + + if (!this.main && cameras[0]) + { + this.main = cameras[0]; + } + + return total; + }, + + /** + * The internal render method. This is called automatically by the Scene and should not be invoked directly. + * + * It will iterate through all local cameras and render them in turn, as long as they're visible and have + * an alpha level > 0. + * + * @method Phaser.Cameras.Scene2D.CameraManager#render + * @protected + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Renderer that will render the children to this camera. + * @param {Phaser.GameObjects.GameObject[]} children - An array of renderable Game Objects. + * @param {number} interpolation - Interpolation value. Reserved for future use. + */ + render: function (renderer, children, interpolation) + { + var scene = this.scene; + var cameras = this.cameras; + + for (var i = 0; i < this.cameras.length; i++) + { + var camera = cameras[i]; + + if (camera.visible && camera.alpha > 0) + { + // Hard-coded to 1 for now + camera.preRender(1); + + renderer.render(scene, children, interpolation, camera); + } + } + }, + + /** + * Resets this Camera Manager. + * + * This will iterate through all current Cameras, destroying them all, then it will reset the + * cameras array, reset the ID counter and create 1 new single camera using the default values. + * + * @method Phaser.Cameras.Scene2D.CameraManager#resetAll + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} The freshly created main Camera. + */ + resetAll: function () + { + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].destroy(); + } + + this.cameras = []; + + this.main = this.add(); + + return this.main; + }, + + /** + * The main update loop. Called automatically when the Scene steps. + * + * @method Phaser.Cameras.Scene2D.CameraManager#update + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].update(time, delta); + } + }, + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * + * @method Phaser.Cameras.Scene2D.CameraManager#onResize + * @since 3.18.0 + * + * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. + * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + */ + onResize: function (gameSize, baseSize, displaySize, resolution, previousWidth, previousHeight) + { + for (var i = 0; i < this.cameras.length; i++) + { + var cam = this.cameras[i]; + + // 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 + + if (cam._x === 0 && cam._y === 0 && cam._width === previousWidth && cam._height === previousHeight) + { + cam.setSize(baseSize.width, baseSize.height); + } + } + }, + + /** + * Resizes all cameras to the given dimensions. + * + * @method Phaser.Cameras.Scene2D.CameraManager#resize + * @since 3.2.0 + * + * @param {number} width - The new width of the camera. + * @param {number} height - The new height of the camera. + */ + resize: function (width, height) + { + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].setSize(width, height); + } + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Cameras.Scene2D.CameraManager#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.main = undefined; + + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].destroy(); + } + + this.cameras = []; + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.update, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Cameras.Scene2D.CameraManager#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.default.destroy(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('CameraManager', CameraManager, 'cameras'); + +module.exports = CameraManager; + + +/***/ }), +/* 726 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager has successfully entered fullscreen mode. + * + * @event Phaser.Scale.Events#ENTER_FULLSCREEN + * @since 3.16.1 + */ +module.exports = 'enterfullscreen'; + + +/***/ }), +/* 727 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager tried to enter fullscreen mode but failed. + * + * @event Phaser.Scale.Events#FULLSCREEN_FAILED + * @since 3.17.0 + */ +module.exports = 'fullscreenfailed'; + + +/***/ }), +/* 728 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager tried to enter fullscreen mode, but it is unsupported by the browser. + * + * @event Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED + * @since 3.16.1 + */ +module.exports = 'fullscreenunsupported'; + + +/***/ }), +/* 729 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager was in fullscreen mode, but has since left, either directly via game code, + * or via a user gestured, such as pressing the ESC key. + * + * @event Phaser.Scale.Events#LEAVE_FULLSCREEN + * @since 3.16.1 + */ +module.exports = 'leavefullscreen'; + + +/***/ }), +/* 730 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager Orientation Change Event. + * + * @event Phaser.Scale.Events#ORIENTATION_CHANGE + * @since 3.16.1 + * + * @param {string} orientation - + */ +module.exports = 'orientationchange'; + + +/***/ }), +/* 731 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager Resize Event. + * + * This event is dispatched whenever the Scale Manager detects a resize event from the browser. + * It sends three parameters to the callback, each of them being Size components. You can read + * the `width`, `height`, `aspectRatio` and other properties of these components to help with + * scaling your own game content. + * + * @event Phaser.Scale.Events#RESIZE + * @since 3.16.1 + * + * @param {Phaser.Structs.Size} gameSize - A reference to the Game Size component. This is the un-scaled size of your game canvas. + * @param {Phaser.Structs.Size} baseSize - A reference to the Base Size component. This is the game size multiplied by resolution. + * @param {Phaser.Structs.Size} displaySize - A reference to the Display Size component. This is the scaled canvas size, after applying zoom and scale mode. + * @param {number} resolution - The current resolution. Defaults to 1 at the moment. + * @param {number} previousWidth - If the `gameSize` has changed, this value contains its previous width, otherwise it contains the current width. + * @param {number} previousHeight - If the `gameSize` has changed, this value contains its previous height, otherwise it contains the current height. + */ +module.exports = 'resize'; + + +/***/ }), +/* 732 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Boot Event. + * + * This event is dispatched by a Scene during the Scene Systems boot process. Primarily used by Scene Plugins. + * + * Listen to it from a Scene using `this.scene.events.on('boot', listener)`. + * + * @event Phaser.Scenes.Events#BOOT + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + */ +module.exports = 'boot'; + + +/***/ }), +/* 733 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Create Event. + * + * This event is dispatched by a Scene after it has been created by the Scene Manager. + * + * If a Scene has a `create` method then this event is emitted _after_ that has run. + * + * If there is a transition, this event will be fired after the `TRANSITION_START` event. + * + * Listen to it from a Scene using `this.scene.events.on('create', listener)`. + * + * @event Phaser.Scenes.Events#CREATE + * @since 3.17.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that emitted this event. + */ +module.exports = 'create'; + + +/***/ }), +/* 734 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Destroy Event. + * + * This event is dispatched by a Scene during the Scene Systems destroy process. + * + * Listen to it from a Scene using `this.scene.events.on('destroy', listener)`. + * + * You should destroy any resources that may be in use by your Scene in this event handler. + * + * @event Phaser.Scenes.Events#DESTROY + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + */ +module.exports = 'destroy'; + + +/***/ }), +/* 735 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Pause Event. + * + * This event is dispatched by a Scene when it is paused, either directly via the `pause` method, or as an + * action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('pause', listener)`. + * + * @event Phaser.Scenes.Events#PAUSE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was paused. + */ +module.exports = 'pause'; + + +/***/ }), +/* 736 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('postupdate', listener)`. + * + * A Scene will only run its step if it is active. + * + * @event Phaser.Scenes.Events#POST_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @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. + */ +module.exports = 'postupdate'; + + +/***/ }), +/* 737 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('preupdate', listener)`. + * + * A Scene will only run its step if it is active. + * + * @event Phaser.Scenes.Events#PRE_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @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. + */ +module.exports = 'preupdate'; + + +/***/ }), +/* 738 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Ready Event. + * + * This event is dispatched by a Scene during the Scene Systems start process. + * By this point in the process the Scene is now fully active and rendering. + * This event is meant for your game code to use, as all plugins have responded to the earlier 'start' event. + * + * Listen to it from a Scene using `this.scene.events.on('ready', listener)`. + * + * @event Phaser.Scenes.Events#READY + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was started. + */ +module.exports = 'ready'; + + +/***/ }), +/* 739 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Render 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('render', listener)`. + * + * A Scene will only render if it is visible and active. + * By the time this event is dispatched, the Scene will have already been rendered. + * + * @event Phaser.Scenes.Events#RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer that rendered the Scene. + */ +module.exports = 'render'; + + +/***/ }), +/* 740 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Resume Event. + * + * This event is dispatched by a Scene when it is resumed from a paused state, either directly via the `resume` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('resume', listener)`. + * + * @event Phaser.Scenes.Events#RESUME + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was resumed. + */ +module.exports = 'resume'; + + +/***/ }), +/* 741 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Shutdown Event. + * + * This event is dispatched by a Scene during the Scene Systems shutdown process. + * + * Listen to it from a Scene using `this.scene.events.on('shutdown', listener)`. + * + * You should free-up any resources that may be in use by your Scene in this event handler, on the understanding + * that the Scene may, at any time, become active again. A shutdown Scene is not 'destroyed', it's simply not + * currently active. Use the [DESTROY]{@linkcode Phaser.Scenes.Events#event:DESTROY} event to completely clear resources. + * + * @event Phaser.Scenes.Events#SHUTDOWN + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was shutdown. + */ +module.exports = 'shutdown'; + + +/***/ }), +/* 742 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Sleep Event. + * + * This event is dispatched by a Scene when it is sent to sleep, either directly via the `sleep` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('sleep', listener)`. + * + * @event Phaser.Scenes.Events#SLEEP + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was sent to sleep. + */ +module.exports = 'sleep'; + + +/***/ }), +/* 743 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Start Event. + * + * This event is dispatched by a Scene during the Scene Systems start process. Primarily used by Scene Plugins. + * + * Listen to it from a Scene using `this.scene.events.on('start', listener)`. + * + * @event Phaser.Scenes.Events#START + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + */ +module.exports = 'start'; + + +/***/ }), +/* 744 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Complete Event. + * + * This event is dispatched by the Target Scene of a transition. + * + * It happens when the transition process has completed. This occurs when the duration timer equals or exceeds the duration + * of the transition. + * + * Listen to it from a Scene using `this.scene.events.on('transitioncomplete', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_COMPLETE + * @since 3.5.0 + * + * @param {Phaser.Scene} scene -The Scene on which the transitioned completed. + */ +module.exports = 'transitioncomplete'; + + +/***/ }), +/* 745 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Init Event. + * + * This event is dispatched by the Target Scene of a transition. + * + * It happens immediately after the `Scene.init` method is called. If the Scene does not have an `init` method, + * this event is not dispatched. + * + * Listen to it from a Scene using `this.scene.events.on('transitioninit', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_INIT + * @since 3.5.0 + * + * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitioninit'; + + +/***/ }), +/* 746 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Out Event. + * + * This event is dispatched by a Scene when it initiates a transition to another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('transitionout', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_OUT + * @since 3.5.0 + * + * @param {Phaser.Scene} target - A reference to the Scene that is being transitioned to. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitionout'; + + +/***/ }), +/* 747 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Start Event. + * + * This event is dispatched by the Target Scene of a transition, only if that Scene was not asleep. + * + * It happens immediately after the `Scene.create` method is called. If the Scene does not have a `create` method, + * this event is dispatched anyway. + * + * If the Target Scene was sleeping then the [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} event is + * dispatched instead of this event. + * + * Listen to it from a Scene using `this.scene.events.on('transitionstart', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_START + * @since 3.5.0 + * + * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitionstart'; + + +/***/ }), +/* 748 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Wake Event. + * + * This event is dispatched by the Target Scene of a transition, only if that Scene was asleep before + * the transition began. If the Scene was not asleep the [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} event is dispatched instead. + * + * Listen to it from a Scene using `this.scene.events.on('transitionwake', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_WAKE + * @since 3.5.0 + * + * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitionwake'; + + +/***/ }), +/* 749 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE} + * 5. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('update', listener)`. + * + * A Scene will only run its step if it is active. + * + * @event Phaser.Scenes.Events#UPDATE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @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. + */ +module.exports = 'update'; + + +/***/ }), +/* 750 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Wake Event. + * + * This event is dispatched by a Scene when it is woken from sleep, either directly via the `wake` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('wake', listener)`. + * + * @event Phaser.Scenes.Events#WAKE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was woken up. + */ +module.exports = 'wake'; + + +/***/ }), +/* 751 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Core + */ + +module.exports = { + + Config: __webpack_require__(333), + CreateRenderer: __webpack_require__(356), + DebugHeader: __webpack_require__(366), + Events: __webpack_require__(21), + TimeStep: __webpack_require__(367), + VisibilityHandler: __webpack_require__(369) + +}; + + +/***/ }), +/* 752 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 753 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Browser = __webpack_require__(125); + +/** + * Determines the input support of the browser 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.input` from within any Scene. + * + * @typedef {object} Phaser.Device.Input + * @since 3.0.0 + * + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @property {boolean} gamepads - Is navigator.getGamepads available? + * @property {boolean} mspointer - Is mspointer available? + * @property {boolean} touch - Is touch available? + */ +var Input = { + + gamepads: false, + mspointer: false, + touch: false, + wheelEvent: null + +}; + +function init () +{ + if ('ontouchstart' in document.documentElement || (navigator.maxTouchPoints && navigator.maxTouchPoints >= 1)) + { + Input.touch = true; + } + + if (navigator.msPointerEnabled || navigator.pointerEnabled) + { + Input.mspointer = true; + } + + if (navigator.getGamepads) + { + Input.gamepads = true; + } + + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (Browser.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + Input.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + Input.wheelEvent = 'mousewheel'; + } + else if (Browser.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + Input.wheelEvent = 'DOMMouseScroll'; + } + + return Input; +} + +module.exports = init(); + + +/***/ }), +/* 754 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Browser = __webpack_require__(125); + +/** + * Determines the audio playback capabilities of the device 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.audio` from within any Scene. + * + * @typedef {object} Phaser.Device.Audio + * @since 3.0.0 + * + * @property {boolean} audioData - Can this device play HTML Audio tags? + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @property {boolean} m4a - Can this device can play m4a files. + * @property {boolean} mp3 - Can this device play mp3 files? + * @property {boolean} ogg - Can this device play ogg files? + * @property {boolean} opus - Can this device play opus files? + * @property {boolean} wav - Can this device play wav files? + * @property {boolean} webAudio - Does this device have the Web Audio API? + * @property {boolean} webm - Can this device play webm files? + */ +var Audio = { + + audioData: false, + dolby: false, + m4a: false, + mp3: false, + ogg: false, + opus: false, + wav: false, + webAudio: false, + webm: false + +}; + +function init () +{ + Audio.audioData = !!(window['Audio']); + + Audio.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + + var audioElement = document.createElement('audio'); + + var result = !!audioElement.canPlayType; + + try + { + if (result) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + Audio.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + Audio.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + Audio.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + Audio.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + Audio.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + Audio.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (Browser.edge) + { + Audio.dolby = true; + } + else if (Browser.safari && Browser.safariVersion >= 9) + { + if ((/Mac OS X (\d+)_(\d+)/).test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + Audio.dolby = true; + } + } + } + } + } + } + catch (e) + { + // Nothing to do here + } + + return Audio; +} + +module.exports = init(); + + +/***/ }), +/* 755 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines the video support of the browser 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.video` from within any Scene. + * + * In Phaser 3.20 the properties were renamed to drop the 'Video' suffix. + * + * @typedef {object} Phaser.Device.Video + * @since 3.0.0 + * + * @property {boolean} h264 - Can this device play h264 mp4 video files? + * @property {boolean} hls - Can this device play hls video files? + * @property {boolean} mp4 - Can this device play h264 mp4 video files? + * @property {boolean} ogg - Can this device play ogg video files? + * @property {boolean} vp9 - Can this device play vp9 video files? + * @property {boolean} webm - Can this device play webm video files? + */ +var Video = { + + h264: false, + hls: false, + mp4: false, + ogg: false, + vp9: false, + webm: false + +}; + +function init () +{ + var videoElement = document.createElement('video'); + var result = !!videoElement.canPlayType; + + try + { + if (result) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + Video.ogg = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + Video.h264 = true; + Video.mp4 = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + Video.webm = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + Video.vp9 = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + Video.hls = true; + } + } + } + catch (e) + { + // Nothing to do + } + + return Video; +} + +module.exports = init(); + + +/***/ }), +/* 756 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines the full screen support of the browser 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.fullscreen` from within any Scene. + * + * @typedef {object} Phaser.Device.Fullscreen + * @since 3.0.0 + * + * @property {boolean} available - Does the browser support the Full Screen API? + * @property {boolean} keyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @property {string} cancel - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @property {string} request - If the browser supports the Full Screen API this holds the call you need to use to activate it. + */ +var Fullscreen = { + + available: false, + cancel: '', + keyboard: false, + request: '' + +}; + +/** +* Checks for support of the Full Screen API. +* +* @ignore +*/ +function init () +{ + var i; + + var suffix1 = 'Fullscreen'; + var suffix2 = 'FullScreen'; + + var fs = [ + 'request' + suffix1, + 'request' + suffix2, + 'webkitRequest' + suffix1, + 'webkitRequest' + suffix2, + 'msRequest' + suffix1, + 'msRequest' + suffix2, + 'mozRequest' + suffix2, + 'mozRequest' + suffix1 + ]; + + for (i = 0; i < fs.length; i++) + { + if (document.documentElement[fs[i]]) + { + Fullscreen.available = true; + Fullscreen.request = fs[i]; + break; + } + } + + var cfs = [ + 'cancel' + suffix2, + 'exit' + suffix1, + 'webkitCancel' + suffix2, + 'webkitExit' + suffix1, + 'msCancel' + suffix2, + 'msExit' + suffix1, + 'mozCancel' + suffix2, + 'mozExit' + suffix1 + ]; + + if (Fullscreen.available) + { + for (i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + Fullscreen.cancel = cfs[i]; + break; + } + } + } + + // Keyboard Input? + // Safari 5.1 says it supports fullscreen keyboard, but is lying. + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'] && !(/ Version\/5\.1(?:\.\d+)? Safari\//).test(navigator.userAgent)) + { + Fullscreen.keyboard = true; + } + + Object.defineProperty(Fullscreen, 'active', { get: function () { return !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement); } }); + + return Fullscreen; +} + +module.exports = init(); + + +/***/ }), +/* 757 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Angle + */ + +module.exports = { + + Between: __webpack_require__(336), + BetweenPoints: __webpack_require__(758), + BetweenPointsY: __webpack_require__(759), + BetweenY: __webpack_require__(760), + CounterClockwise: __webpack_require__(761), + Normalize: __webpack_require__(337), + Reverse: __webpack_require__(762), + RotateTo: __webpack_require__(763), + ShortestBetween: __webpack_require__(764), + Wrap: __webpack_require__(165), + WrapDegrees: __webpack_require__(166) + +}; + + +/***/ }), +/* 758 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * Calculates the angle of the vector from the first point to the second point. + * + * @function Phaser.Math.Angle.BetweenPoints + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point1 - The first point. + * @param {(Phaser.Geom.Point|object)} point2 - The second point. + * + * @return {number} The angle in radians. + */ +var BetweenPoints = function (point1, point2) +{ + return Math.atan2(point2.y - point1.y, point2.x - point1.x); +}; + +module.exports = BetweenPoints; + + +/***/ }), +/* 759 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * The difference between this method and {@link Phaser.Math.Angle.BetweenPoints} is that this assumes the y coordinate + * travels down the screen. + * + * @function Phaser.Math.Angle.BetweenPointsY + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point1 - The first point. + * @param {(Phaser.Geom.Point|object)} point2 - The second point. + * + * @return {number} The angle in radians. + */ +var BetweenPointsY = function (point1, point2) +{ + return Math.atan2(point2.x - point1.x, point2.y - point1.y); +}; + +module.exports = BetweenPointsY; + + +/***/ }), +/* 760 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and {@link Phaser.Math.Angle.Between} is that this assumes the y coordinate + * travels down the screen. + * + * @function Phaser.Math.Angle.BetweenY + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The angle in radians. + */ +var BetweenY = function (x1, y1, x2, y2) +{ + return Math.atan2(x2 - x1, y2 - y1); +}; + +module.exports = BetweenY; + + +/***/ }), +/* 761 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(13); + +/** + * Takes an angle in Phasers default clockwise format and converts it so that + * 0 is North, 90 is West, 180 is South and 270 is East, + * therefore running counter-clockwise instead of clockwise. + * + * You can pass in the angle from a Game Object using: + * + * ```javascript + * var converted = CounterClockwise(gameobject.rotation); + * ``` + * + * All values for this function are in radians. + * + * @function Phaser.Math.Angle.CounterClockwise + * @since 3.16.0 + * + * @param {number} angle - The angle to convert, in radians. + * + * @return {number} The converted angle, in radians. + */ +var CounterClockwise = function (angle) +{ + if (angle > Math.PI) + { + angle -= CONST.PI2; + } + + return Math.abs((((angle + CONST.TAU) % CONST.PI2) - CONST.PI2) % CONST.PI2); +}; + +module.exports = CounterClockwise; + + +/***/ }), +/* 762 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Normalize = __webpack_require__(337); + +/** + * Reverse the given angle. + * + * @function Phaser.Math.Angle.Reverse + * @since 3.0.0 + * + * @param {number} angle - The angle to reverse, in radians. + * + * @return {number} The reversed angle, in radians. + */ +var Reverse = function (angle) +{ + return Normalize(angle + Math.PI); +}; + +module.exports = Reverse; + + +/***/ }), +/* 763 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = __webpack_require__(13); + +/** + * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. + * + * @function Phaser.Math.Angle.RotateTo + * @since 3.0.0 + * + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * + * @return {number} The adjusted angle. + */ +var RotateTo = function (currentAngle, targetAngle, lerp) +{ + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (MATH_CONST.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += MATH_CONST.PI2; + } + else + { + targetAngle -= MATH_CONST.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; +}; + +module.exports = RotateTo; + + +/***/ }), +/* 764 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Gets the shortest angle between `angle1` and `angle2`. + * + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * TODO: Wrap the angles in this function? + * + * @function Phaser.Math.Angle.ShortestBetween + * @since 3.0.0 + * + * @param {number} angle1 - The first angle in the range -180 to 180. + * @param {number} angle2 - The second angle in the range -180 to 180. + * + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ +var ShortestBetween = function (angle1, angle2) +{ + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + +}; + +module.exports = ShortestBetween; + + +/***/ }), +/* 765 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Distance + */ + +module.exports = { + + Between: __webpack_require__(54), + BetweenPoints: __webpack_require__(766), + BetweenPointsSquared: __webpack_require__(767), + Chebyshev: __webpack_require__(768), + Power: __webpack_require__(769), + Snake: __webpack_require__(770), + Squared: __webpack_require__(338) + +}; + + +/***/ }), +/* 766 */ +/***/ (function(module, exports) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two points. + * + * @function Phaser.Math.Distance.BetweenPoints + * @since 3.22.0 + * + * @param {Phaser.Types.Math.Vector2Like} a - The first point. + * @param {Phaser.Types.Math.Vector2Like} b - The second point. + * + * @return {number} The distance between the points. + */ +var DistanceBetweenPoints = function (a, b) +{ + var dx = a.x - b.x; + var dy = a.y - b.y; + + return Math.sqrt(dx * dx + dy * dy); +}; + +module.exports = DistanceBetweenPoints; + + +/***/ }), +/* 767 */ +/***/ (function(module, exports) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the squared distance between two points. + * + * @function Phaser.Math.Distance.BetweenPointsSquared + * @since 3.22.0 + * + * @param {Phaser.Types.Math.Vector2Like} a - The first point. + * @param {Phaser.Types.Math.Vector2Like} b - The second point. + * + * @return {number} The squared distance between the points. + */ +var DistanceBetweenPointsSquared = function (a, b) +{ + var dx = a.x - b.x; + var dy = a.y - b.y; + + return dx * dx + dy * dy; +}; + +module.exports = DistanceBetweenPointsSquared; + + +/***/ }), +/* 768 */ +/***/ (function(module, exports) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the Chebyshev distance between two sets of coordinates (points). + * + * Chebyshev distance (or chessboard distance) is the maximum of the horizontal and vertical distances. + * It's the effective distance when movement can be horizontal, vertical, or diagonal. + * + * @function Phaser.Math.Distance.Chebyshev + * @since 3.22.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point. + */ +var ChebyshevDistance = function (x1, y1, x2, y2) +{ + return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); +}; + +module.exports = ChebyshevDistance; + + +/***/ }), +/* 769 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two sets of coordinates (points) to the power of `pow`. + * + * @function Phaser.Math.Distance.Power + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * @param {number} pow - The exponent. + * + * @return {number} The distance between each point. + */ +var DistancePower = function (x1, y1, x2, y2, pow) +{ + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); +}; + +module.exports = DistancePower; + + +/***/ }), +/* 770 */ +/***/ (function(module, exports) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the snake distance between two sets of coordinates (points). + * + * Snake distance (rectilinear distance, Manhattan distance) is the sum of the horizontal and vertical distances. + * It's the effective distance when movement is allowed only horizontally or vertically (but not both). + * + * @function Phaser.Math.Distance.Snake + * @since 3.22.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point. + */ +var SnakeDistance = function (x1, y1, x2, y2) +{ + return Math.abs(x1 - x2) + Math.abs(y1 - y2); +}; + +module.exports = SnakeDistance; + + +/***/ }), +/* 771 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing + */ + +module.exports = { + + Back: __webpack_require__(321), + Bounce: __webpack_require__(322), + Circular: __webpack_require__(323), + Cubic: __webpack_require__(324), + Elastic: __webpack_require__(325), + Expo: __webpack_require__(326), + Linear: __webpack_require__(327), + Quadratic: __webpack_require__(328), + Quartic: __webpack_require__(329), + Quintic: __webpack_require__(330), + Sine: __webpack_require__(331), + Stepped: __webpack_require__(332) + +}; + + +/***/ }), +/* 772 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Fuzzy + */ + +module.exports = { + + Ceil: __webpack_require__(773), + Equal: __webpack_require__(126), + Floor: __webpack_require__(774), + GreaterThan: __webpack_require__(339), + LessThan: __webpack_require__(340) + +}; + + +/***/ }), +/* 773 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the fuzzy ceiling of the given value. + * + * @function Phaser.Math.Fuzzy.Ceil + * @since 3.0.0 + * + * @param {number} value - The value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {number} The fuzzy ceiling of the value. + */ +var Ceil = function (value, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(value - epsilon); +}; + +module.exports = Ceil; + + +/***/ }), +/* 774 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the fuzzy floor of the given value. + * + * @function Phaser.Math.Fuzzy.Floor + * @since 3.0.0 + * + * @param {number} value - The value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {number} The floor of the value. + */ +var Floor = function (value, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(value + epsilon); +}; + +module.exports = Floor; + + +/***/ }), +/* 775 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Interpolation + */ + +module.exports = { + + Bezier: __webpack_require__(776), + CatmullRom: __webpack_require__(777), + CubicBezier: __webpack_require__(343), + Linear: __webpack_require__(778), + QuadraticBezier: __webpack_require__(344), + SmoothStep: __webpack_require__(345), + SmootherStep: __webpack_require__(779) + +}; + + +/***/ }), +/* 776 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bernstein = __webpack_require__(341); + +/** + * A bezier interpolation method. + * + * @function Phaser.Math.Interpolation.Bezier + * @since 3.0.0 + * + * @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. + */ +var BezierInterpolation = function (v, k) +{ + var b = 0; + var n = v.length - 1; + + for (var i = 0; i <= n; i++) + { + b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * Bernstein(n, i); + } + + return b; +}; + +module.exports = BezierInterpolation; + + +/***/ }), +/* 777 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CatmullRom = __webpack_require__(182); + +/** + * A Catmull-Rom interpolation method. + * + * @function Phaser.Math.Interpolation.CatmullRom + * @since 3.0.0 + * + * @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. + */ +var CatmullRomInterpolation = function (v, k) +{ + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (v[0] === v[m]) + { + if (k < 0) + { + i = Math.floor(f = m * (1 + k)); + } + + return CatmullRom(f - i, v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m]); + } + else + { + if (k < 0) + { + return v[0] - (CatmullRom(-f, v[0], v[0], v[1], v[1]) - v[0]); + } + + if (k > 1) + { + return v[m] - (CatmullRom(f - m, v[m], v[m], v[m - 1], v[m - 1]) - v[m]); + } + + return CatmullRom(f - i, v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2]); + } +}; + +module.exports = CatmullRomInterpolation; + + +/***/ }), +/* 778 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Linear = __webpack_require__(123); + +/** + * A linear interpolation method. + * + * @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. + */ +var LinearInterpolation = function (v, k) +{ + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return Linear(v[0], v[1], f); + } + else if (k > 1) + { + return Linear(v[m], v[m - 1], m - f); + } + else + { + return Linear(v[i], v[(i + 1 > m) ? m : i + 1], f - i); + } +}; + +module.exports = LinearInterpolation; + + +/***/ }), +/* 779 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SmootherStep = __webpack_require__(170); + +/** + * A Smoother Step interpolation method. + * + * @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. + */ +var SmootherStepInterpolation = function (t, min, max) +{ + return min + (max - min) * SmootherStep(t, 0, 1); +}; + +module.exports = SmootherStepInterpolation; + + +/***/ }), +/* 780 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Pow2 + */ + +module.exports = { + + GetNext: __webpack_require__(346), + IsSize: __webpack_require__(127), + IsValue: __webpack_require__(781) + +}; + + +/***/ }), +/* 781 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tests the value and returns `true` if it is a power of two. + * + * @function Phaser.Math.Pow2.IsValue + * @since 3.0.0 + * + * @param {number} value - The value to check if it's a power of two. + * + * @return {boolean} Returns `true` if `value` is a power of two, otherwise `false`. + */ +var IsValuePowerOfTwo = function (value) +{ + return (value > 0 && (value & (value - 1)) === 0); +}; + +module.exports = IsValuePowerOfTwo; + + +/***/ }), +/* 782 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Snap + */ + +module.exports = { + + Ceil: __webpack_require__(347), + Floor: __webpack_require__(105), + To: __webpack_require__(783) + +}; + + +/***/ }), +/* 783 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10` whereas `14` will snap to `15`. + * + * @function Phaser.Math.Snap.To + * @since 3.0.0 + * + * @param {number} value - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. + * + * @return {number} The snapped value. + */ +var SnapTo = function (value, gap, start, divide) +{ + if (start === undefined) { start = 0; } + + if (gap === 0) + { + return value; + } + + value -= start; + value = gap * Math.round(value / gap); + + return (divide) ? (start + value) / gap : start + value; +}; + +module.exports = SnapTo; + + +/***/ }), +/* 784 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); + +/** + * @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. + */ +var RandomDataGenerator = new Class({ + + initialize: + + function RandomDataGenerator (seeds) + { + if (seeds === undefined) { seeds = [ (Date.now() * Math.random()).toString() ]; } + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#c + * @type {number} + * @default 1 + * @private + * @since 3.0.0 + */ + this.c = 1; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#s0 + * @type {number} + * @default 0 + * @private + * @since 3.0.0 + */ + this.s0 = 0; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#s1 + * @type {number} + * @default 0 + * @private + * @since 3.0.0 + */ + this.s1 = 0; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#s2 + * @type {number} + * @default 0 + * @private + * @since 3.0.0 + */ + this.s2 = 0; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#n + * @type {number} + * @default 0 + * @private + * @since 3.2.0 + */ + this.n = 0; + + /** + * Signs to choose from. + * + * @name Phaser.Math.RandomDataGenerator#signs + * @type {number[]} + * @since 3.0.0 + */ + this.signs = [ -1, 1 ]; + + if (seeds) + { + this.init(seeds); + } + }, + + /** + * Private random helper. + * + * @method Phaser.Math.RandomDataGenerator#rnd + * @since 3.0.0 + * @private + * + * @return {number} A random number. + */ + rnd: function () + { + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.Math.RandomDataGenerator#hash + * @since 3.0.0 + * @private + * + * @param {string} data - The value to hash. + * + * @return {number} The hashed value. + */ + hash: function (data) + { + var h; + var n = this.n; + + data = data.toString(); + + for (var i = 0; i < data.length; i++) + { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + this.n = n; + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + }, + + /** + * Initialize the state of the random data generator. + * + * @method Phaser.Math.RandomDataGenerator#init + * @since 3.0.0 + * + * @param {(string|string[])} seeds - The seeds to initialize the random data generator with. + */ + init: function (seeds) + { + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.Math.RandomDataGenerator#sow + * @since 3.0.0 + * + * @param {string[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) + { + // Always reset to default seed + this.n = 0xefc8249d; + this.s0 = this.hash(' '); + this.s1 = this.hash(' '); + this.s2 = this.hash(' '); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var seed = seeds[i]; + + this.s0 -= this.hash(seed); + this.s0 += ~~(this.s0 < 0); + this.s1 -= this.hash(seed); + this.s1 += ~~(this.s1 < 0); + this.s2 -= this.hash(seed); + this.s2 += ~~(this.s2 < 0); + } + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.Math.RandomDataGenerator#integer + * @since 3.0.0 + * + * @return {number} A random integer between 0 and 2^32. + */ + integer: function () + { + // 2^32 + return this.rnd() * 0x100000000; + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.Math.RandomDataGenerator#frac + * @since 3.0.0 + * + * @return {number} A random real number between 0 and 1. + */ + frac: function () + { + // 2^-53 + return this.rnd() + (this.rnd() * 0x200000 | 0) * 1.1102230246251565e-16; + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.Math.RandomDataGenerator#real + * @since 3.0.0 + * + * @return {number} A random real number between 0 and 2^32. + */ + real: function () + { + return this.integer() + this.frac(); + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.Math.RandomDataGenerator#integerInRange + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) + { + return Math.floor(this.realInRange(0, max - min + 1) + min); + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.Math.RandomDataGenerator#between + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random number between min and max. + */ + between: function (min, max) + { + return Math.floor(this.realInRange(0, max - min + 1) + min); + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.Math.RandomDataGenerator#realInRange + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) + { + return this.frac() * (max - min) + min; + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.Math.RandomDataGenerator#normal + * @since 3.0.0 + * + * @return {number} A random real number between -1 and 1. + */ + normal: function () + { + return 1 - (2 * this.frac()); + }, + + /** + * 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 + */ + uuid: function () + { + var a = ''; + var b = ''; + + for (b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac() * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') + { + // eslint-disable-next-line no-empty + } + + return b; + }, + + /** + * Returns a random element from within the given array. + * + * @method Phaser.Math.RandomDataGenerator#pick + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [array] + * @genericUse {T} - [$return] + * + * @param {T[]} array - The array to pick a random element from. + * + * @return {T} A random member of the array. + */ + pick: function (array) + { + return array[this.integerInRange(0, array.length - 1)]; + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.Math.RandomDataGenerator#sign + * @since 3.0.0 + * + * @return {number} -1 or +1. + */ + sign: function () + { + return this.pick(this.signs); + }, + + /** + * Returns a random element from within the given array, favoring the earlier entries. + * + * @method Phaser.Math.RandomDataGenerator#weightedPick + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [array] + * @genericUse {T} - [$return] + * + * @param {T[]} array - The array to pick a random element from. + * + * @return {T} A random member of the array. + */ + weightedPick: function (array) + { + return array[~~(Math.pow(this.frac(), 2) * (array.length - 1) + 0.5)]; + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.Math.RandomDataGenerator#timestamp + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) + { + return this.realInRange(min || 946684800000, max || 1577862000000); + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.Math.RandomDataGenerator#angle + * @since 3.0.0 + * + * @return {number} A random number between -180 and 180. + */ + angle: function () + { + return this.integerInRange(-180, 180); + }, + + /** + * Returns a random rotation in radians, between -3.141 and 3.141 + * + * @method Phaser.Math.RandomDataGenerator#rotation + * @since 3.0.0 + * + * @return {number} A random number between -3.141 and 3.141 + */ + rotation: function () + { + return this.realInRange(-3.1415926, 3.1415926); + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.Math.RandomDataGenerator#state + * @since 3.0.0 + * + * @param {string} [state] - Generator state to be set. + * + * @return {string} The current state of the generator. + */ + state: function (state) + { + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return [ '!rnd', this.c, this.s0, this.s1, this.s2 ].join(','); + }, + + /** + * Shuffles the given array, using the current seed. + * + * @method Phaser.Math.RandomDataGenerator#shuffle + * @since 3.7.0 + * + * @generic T + * @genericUse {T[]} - [array,$return] + * + * @param {T[]} [array] - The array to be shuffled. + * + * @return {T[]} The shuffled array. + */ + shuffle: function (array) + { + var len = array.length - 1; + + for (var i = len; i > 0; i--) + { + var randomIndex = Math.floor(this.frac() * (i + 1)); + var itemAtIndex = array[randomIndex]; + + array[randomIndex] = array[i]; + array[i] = itemAtIndex; + } + + return array; + } + +}); + +module.exports = RandomDataGenerator; + + +/***/ }), +/* 785 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the mean average of the given values. + * + * @function Phaser.Math.Average + * @since 3.0.0 + * + * @param {number[]} values - The values to average. + * + * @return {number} The average value. + */ +var Average = function (values) +{ + var sum = 0; + + for (var i = 0; i < values.length; i++) + { + sum += (+values[i]); + } + + return sum / values.length; +}; + +module.exports = Average; + + +/***/ }), +/* 786 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * + * The `place` is represented by the power applied to `base` to get that place. + * + * @function Phaser.Math.CeilTo + * @since 3.0.0 + * + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. + * + * @return {number} The rounded value. + */ +var CeilTo = function (value, place, base) +{ + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; +}; + +module.exports = CeilTo; + + +/***/ }), +/* 787 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the positive difference of two given numbers. + * + * @function Phaser.Math.Difference + * @since 3.0.0 + * + * @param {number} a - The first number in the calculation. + * @param {number} b - The second number in the calculation. + * + * @return {number} The positive difference of the two given numbers. + */ +var Difference = function (a, b) +{ + return Math.abs(a - b); +}; + +module.exports = Difference; + + +/***/ }), +/* 788 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * + * The `place` is represented by the power applied to `base` to get that place. + * + * @function Phaser.Math.FloorTo + * @since 3.0.0 + * + * @param {number} value - The value to round. + * @param {integer} [place=0] - The place to round to. + * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. + * + * @return {number} The rounded value. + */ +var FloorTo = function (value, place, base) +{ + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; +}; + +module.exports = FloorTo; + + +/***/ }), +/* 789 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate a per-ms speed from a distance and time (given in seconds). + * + * @function Phaser.Math.GetSpeed + * @since 3.0.0 + * + * @param {number} distance - The distance. + * @param {integer} time - The time, in seconds. + * + * @return {number} The speed, in distance per ms. + * + * @example + * // 400px over 1 second is 0.4 px/ms + * Phaser.Math.GetSpeed(400, 1) // -> 0.4 + */ +var GetSpeed = function (distance, time) +{ + return (distance / time) / 1000; +}; + +module.exports = GetSpeed; + + +/***/ }), +/* 790 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check if a given value is an even number. + * + * @function Phaser.Math.IsEven + * @since 3.0.0 + * + * @param {number} value - The number to perform the check with. + * + * @return {boolean} Whether the number is even or not. + */ +var IsEven = function (value) +{ + // Use abstract equality == for "is number" test + + // eslint-disable-next-line eqeqeq + return (value == parseFloat(value)) ? !(value % 2) : void 0; +}; + +module.exports = IsEven; + + +/***/ }), +/* 791 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check if a given value is an even number using a strict type check. + * + * @function Phaser.Math.IsEvenStrict + * @since 3.0.0 + * + * @param {number} value - The number to perform the check with. + * + * @return {boolean} Whether the number is even or not. + */ +var IsEvenStrict = function (value) +{ + // Use strict equality === for "is number" test + return (value === parseFloat(value)) ? !(value % 2) : void 0; +}; + +module.exports = IsEvenStrict; + + +/***/ }), +/* 792 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Add an `amount` to a `value`, limiting the maximum result to `max`. + * + * @function Phaser.Math.MaxAdd + * @since 3.0.0 + * + * @param {number} value - The value to add to. + * @param {number} amount - The amount to add. + * @param {number} max - The maximum value to return. + * + * @return {number} The resulting value. + */ +var MaxAdd = function (value, amount, max) +{ + return Math.min(value + amount, max); +}; + +module.exports = MaxAdd; + + +/***/ }), +/* 793 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Subtract an `amount` from `value`, limiting the minimum result to `min`. + * + * @function Phaser.Math.MinSub + * @since 3.0.0 + * + * @param {number} value - The value to subtract from. + * @param {number} amount - The amount to subtract. + * @param {number} min - The minimum value to return. + * + * @return {number} The resulting value. + */ +var MinSub = function (value, amount, min) +{ + return Math.max(value - amount, min); +}; + +module.exports = MinSub; + + +/***/ }), +/* 794 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Work out what percentage `value` is of the range between `min` and `max`. + * If `max` isn't given then it will return the percentage of `value` to `min`. + * + * You can optionally specify an `upperMax` value, which is a mid-way point in the range that represents 100%, after which the % starts to go down to zero again. + * + * @function Phaser.Math.Percent + * @since 3.0.0 + * + * @param {number} value - The value to determine the percentage of. + * @param {number} min - The minimum value. + * @param {number} [max] - The maximum value. + * @param {number} [upperMax] - The mid-way point in the range that represents 100%. + * + * @return {number} A value between 0 and 1 representing the percentage. + */ +var Percent = function (value, min, max, upperMax) +{ + if (max === undefined) { max = min + 1; } + + var percentage = (value - min) / (max - min); + + if (percentage > 1) + { + if (upperMax !== undefined) + { + percentage = ((upperMax - value)) / (upperMax - max); + + if (percentage < 0) + { + percentage = 0; + } + } + else + { + percentage = 1; + } + } + else if (percentage < 0) + { + percentage = 0; + } + + return percentage; +}; + +module.exports = Percent; + + +/***/ }), +/* 795 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random unit vector. + * + * Computes random values for the given vector between -1 and 1 that can be used to represent a direction. + * + * Optionally accepts a scale value to scale the resulting vector by. + * + * @function Phaser.Math.RandomXY + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} vector - The Vector to compute random values for. + * @param {number} [scale=1] - The scale of the random values. + * + * @return {Phaser.Math.Vector2} The given Vector. + */ +var RandomXY = function (vector, scale) +{ + if (scale === undefined) { scale = 1; } + + var r = Math.random() * 2 * Math.PI; + + vector.x = Math.cos(r) * scale; + vector.y = Math.sin(r) * scale; + + return vector; +}; + +module.exports = RandomXY; + + +/***/ }), +/* 796 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random position vector in a spherical area, optionally defined by the given radius. + * + * @function Phaser.Math.RandomXYZ + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} vec3 - The Vector to compute random values for. + * @param {number} [radius=1] - The radius. + * + * @return {Phaser.Math.Vector3} The given Vector. + */ +var RandomXYZ = function (vec3, radius) +{ + if (radius === undefined) { radius = 1; } + + var r = Math.random() * 2 * Math.PI; + var z = (Math.random() * 2) - 1; + var zScale = Math.sqrt(1 - z * z) * radius; + + vec3.x = Math.cos(r) * zScale; + vec3.y = Math.sin(r) * zScale; + vec3.z = z * radius; + + return vec3; +}; + +module.exports = RandomXYZ; + + +/***/ }), +/* 797 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random four-dimensional vector. + * + * @function Phaser.Math.RandomXYZW + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} vec4 - The Vector to compute random values for. + * @param {number} [scale=1] - The scale of the random values. + * + * @return {Phaser.Math.Vector4} The given Vector. + */ +var RandomXYZW = function (vec4, scale) +{ + if (scale === undefined) { scale = 1; } + + // TODO: Not spherical; should fix this for more uniform distribution + vec4.x = (Math.random() * 2 - 1) * scale; + vec4.y = (Math.random() * 2 - 1) * scale; + vec4.z = (Math.random() * 2 - 1) * scale; + vec4.w = (Math.random() * 2 - 1) * scale; + + return vec4; +}; + +module.exports = RandomXYZW; + + +/***/ }), +/* 798 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Round a value to the given precision. + * + * For example: + * + * ```javascript + * RoundTo(123.456, 0) = 123 + * RoundTo(123.456, 1) = 120 + * RoundTo(123.456, 2) = 100 + * ``` + * + * To round the decimal, i.e. to round to precision, pass in a negative `place`: + * + * ```javascript + * RoundTo(123.456789, 0) = 123 + * RoundTo(123.456789, -1) = 123.5 + * RoundTo(123.456789, -2) = 123.46 + * RoundTo(123.456789, -3) = 123.457 + * ``` + * + * @function Phaser.Math.RoundTo + * @since 3.0.0 + * + * @param {number} value - The value to round. + * @param {integer} [place=0] - The place to round to. Positive to round the units, negative to round the decimal. + * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. + * + * @return {number} The rounded value. + */ +var RoundTo = function (value, place, base) +{ + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; +}; + +module.exports = RoundTo; + + +/***/ }), +/* 799 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Generate a series of sine and cosine values. + * + * @function Phaser.Math.SinCosTableGenerator + * @since 3.0.0 + * + * @param {number} length - The number of values to generate. + * @param {number} [sinAmp=1] - The sine value amplitude. + * @param {number} [cosAmp=1] - The cosine value amplitude. + * @param {number} [frequency=1] - The frequency of the values. + * + * @return {Phaser.Types.Math.SinCosTable} The generated values. + */ +var SinCosTableGenerator = function (length, sinAmp, cosAmp, frequency) +{ + if (sinAmp === undefined) { sinAmp = 1; } + if (cosAmp === undefined) { cosAmp = 1; } + if (frequency === undefined) { frequency = 1; } + + frequency *= Math.PI / length; + + var cos = []; + var sin = []; + + for (var c = 0; c < length; c++) + { + cosAmp -= sinAmp * frequency; + sinAmp += cosAmp * frequency; + + cos[c] = cosAmp; + sin[c] = sinAmp; + } + + return { + sin: sin, + cos: cos, + length: length + }; +}; + +module.exports = SinCosTableGenerator; + + +/***/ }), +/* 800 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = __webpack_require__(3); + +/** + * Returns a Vector2 containing the x and y position of the given index in a `width` x `height` sized grid. + * + * For example, in a 6 x 4 grid, index 16 would equal x: 4 y: 2. + * + * If the given index is out of range an empty Vector2 is returned. + * + * @function Phaser.Math.ToXY + * @since 3.19.0 + * + * @param {integer} index - The position within the grid to get the x/y value for. + * @param {integer} width - The width of the grid. + * @param {integer} height - The height of the grid. + * @param {Phaser.Math.Vector2} [out] - An optional Vector2 to store the result in. If not given, a new Vector2 instance will be created. + * + * @return {Phaser.Math.Vector2} A Vector2 where the x and y properties contain the given grid index. + */ +var ToXY = function (index, width, height, out) +{ + if (out === undefined) { out = new Vector2(); } + + var x = 0; + var y = 0; + var total = width * height; + + if (index > 0 && index <= total) + { + if (index > width - 1) + { + y = Math.floor(index / width); + x = index - (y * width); + } + else + { + x = index; + } + + out.set(x, y); + } + + return out; +}; + +module.exports = ToXY; + + +/***/ }), +/* 801 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the two values are within the given `tolerance` of each other. + * + * @function Phaser.Math.Within + * @since 3.0.0 + * + * @param {number} a - The first value to use in the calculation. + * @param {number} b - The second value to use in the calculation. + * @param {number} tolerance - The tolerance. Anything equal to or less than this value is considered as being within range. + * + * @return {boolean} Returns `true` if `a` is less than or equal to the tolerance of `b`. + */ +var Within = function (a, b, tolerance) +{ + return (Math.abs(a - b) <= tolerance); +}; + +module.exports = Within; + + +/***/ }), +/* 802 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector3 = __webpack_require__(185); +var Matrix4 = __webpack_require__(354); +var Quaternion = __webpack_require__(355); + +var tmpMat4 = new Matrix4(); +var tmpQuat = new Quaternion(); +var tmpVec3 = new Vector3(); + +/** + * Rotates a vector in place by axis angle. + * + * This is the same as transforming a point by an + * axis-angle quaternion, but it has higher precision. + * + * @function Phaser.Math.RotateVec3 + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} vec - The vector to be rotated. + * @param {Phaser.Math.Vector3} axis - The axis to rotate around. + * @param {number} radians - The angle of rotation in radians. + * + * @return {Phaser.Math.Vector3} The given vector. + */ +var RotateVec3 = function (vec, axis, radians) +{ + // Set the quaternion to our axis angle + tmpQuat.setAxisAngle(axis, radians); + + // Create a rotation matrix from the axis angle + tmpMat4.fromRotationTranslation(tmpQuat, tmpVec3.set(0, 0, 0)); + + // Multiply our vector by the rotation matrix + return vec.transformMat4(tmpMat4); +}; + +module.exports = RotateVec3; + + +/***/ }), +/* 803 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Add Event. + * + * This event is dispatched by the Texture Manager when a texture is added to it. + * + * Listen to this event from within a Scene using: `this.textures.on('addtexture', listener)`. + * + * @event Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that was added to the Texture Manager. + * @param {Phaser.Textures.Texture} texture - A reference to the Texture that was added to the Texture Manager. + */ +module.exports = 'addtexture'; + + +/***/ }), +/* 804 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Load Error Event. + * + * This event is dispatched by the Texture Manager when a texture it requested to load failed. + * This only happens when base64 encoded textures fail. All other texture types are loaded via the Loader Plugin. + * + * Listen to this event from within a Scene using: `this.textures.on('onerror', listener)`. + * + * @event Phaser.Textures.Events#ERROR + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that failed to load into the Texture Manager. + */ +module.exports = 'onerror'; + + +/***/ }), +/* 805 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Load Event. + * + * This event is dispatched by the Texture Manager when a texture has finished loading on it. + * This only happens for base64 encoded textures. All other texture types are loaded via the Loader Plugin. + * + * Listen to this event from within a Scene using: `this.textures.on('onload', listener)`. + * + * This event is dispatched after the [ADD]{@linkcode Phaser.Textures.Events#event:ADD} event. + * + * @event Phaser.Textures.Events#LOAD + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that was loaded by the Texture Manager. + * @param {Phaser.Textures.Texture} texture - A reference to the Texture that was loaded by the Texture Manager. + */ +module.exports = 'onload'; + + +/***/ }), +/* 806 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This internal event signifies that the Texture Manager is now ready and the Game can continue booting. + * + * When a Phaser Game instance is booting for the first time, the Texture Manager has to wait on a couple of non-blocking + * async events before it's fully ready to carry on. When those complete the Texture Manager emits this event via the Game + * instance, which tells the Game to carry on booting. + * + * @event Phaser.Textures.Events#READY + * @since 3.16.1 + */ +module.exports = 'ready'; + + +/***/ }), +/* 807 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Remove Event. + * + * This event is dispatched by the Texture Manager when a texture is removed from it. + * + * Listen to this event from within a Scene using: `this.textures.on('removetexture', listener)`. + * + * If you have any Game Objects still using the removed texture, they will start throwing + * errors the next time they try to render. Be sure to clear all use of the texture in this event handler. + * + * @event Phaser.Textures.Events#REMOVE + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that was removed from the Texture Manager. + */ +module.exports = 'removetexture'; + + +/***/ }), +/* 808 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_BITMAP_MASK_FS', + '', + 'precision mediump float;', + '', + 'uniform vec2 uResolution;', + 'uniform sampler2D uMainSampler;', + 'uniform sampler2D uMaskSampler;', + 'uniform bool uInvertMaskAlpha;', + '', + 'void main()', + '{', + ' vec2 uv = gl_FragCoord.xy / uResolution;', + ' vec4 mainColor = texture2D(uMainSampler, uv);', + ' vec4 maskColor = texture2D(uMaskSampler, uv);', + ' float alpha = mainColor.a;', + '', + ' if (!uInvertMaskAlpha)', + ' {', + ' alpha *= (maskColor.a);', + ' }', + ' else', + ' {', + ' alpha *= (1.0 - maskColor.a);', + ' }', + '', + ' gl_FragColor = vec4(mainColor.rgb * alpha, alpha);', + '}', + '' +].join('\n'); + + +/***/ }), +/* 809 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_BITMAP_MASK_VS', + '', + 'precision mediump float;', + '', + 'attribute vec2 inPosition;', + '', + 'void main()', + '{', + ' gl_Position = vec4(inPosition, 0.0, 1.0);', + '}', + '' +].join('\n'); + + +/***/ }), +/* 810 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS', + '', + 'precision mediump float;', + '', + 'struct Light', + '{', + ' vec2 position;', + ' vec3 color;', + ' float intensity;', + ' float radius;', + '};', + '', + 'const int kMaxLights = %LIGHT_COUNT%;', + '', + 'uniform vec4 uCamera; /* x, y, rotation, zoom */', + 'uniform vec2 uResolution;', + 'uniform sampler2D uMainSampler;', + 'uniform sampler2D uNormSampler;', + 'uniform vec3 uAmbientLightColor;', + 'uniform Light uLights[kMaxLights];', + 'uniform mat3 uInverseRotationMatrix;', + '', + 'varying vec2 outTexCoord;', + 'varying vec4 outTint;', + '', + 'void main()', + '{', + ' vec3 finalColor = vec3(0.0, 0.0, 0.0);', + ' vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);', + ' vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;', + ' vec3 normal = normalize(uInverseRotationMatrix * vec3(normalMap * 2.0 - 1.0));', + ' vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;', + '', + ' for (int index = 0; index < kMaxLights; ++index)', + ' {', + ' Light light = uLights[index];', + ' vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);', + ' vec3 lightNormal = normalize(lightDir);', + ' float distToSurf = length(lightDir) * uCamera.w;', + ' float diffuseFactor = max(dot(normal, lightNormal), 0.0);', + ' float radius = (light.radius / res.x * uCamera.w) * uCamera.w;', + ' float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);', + ' vec3 diffuse = light.color * diffuseFactor;', + ' finalColor += (attenuation * diffuse) * light.intensity;', + ' }', + '', + ' vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);', + ' gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);', + '', + '}', + '' +].join('\n'); + + +/***/ }), +/* 811 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_TEXTURE_TINT_FS', + '', + 'precision mediump float;', + '', + 'uniform sampler2D uMainSampler;', + '', + 'varying vec2 outTexCoord;', + 'varying float outTintEffect;', + 'varying vec4 outTint;', + '', + 'void main()', + '{', + ' vec4 texture = texture2D(uMainSampler, outTexCoord);', + ' vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);', + ' vec4 color = texture;', + '', + ' if (outTintEffect == 0.0)', + ' {', + ' // Multiply texture tint', + ' color = texture * texel;', + ' }', + ' else if (outTintEffect == 1.0)', + ' {', + ' // Solid color + texture alpha', + ' color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);', + ' color.a = texture.a * texel.a;', + ' }', + ' else if (outTintEffect == 2.0)', + ' {', + ' // Solid color, no texture', + ' color = texel;', + ' }', + '', + ' gl_FragColor = color;', + '}', + '' +].join('\n'); + + +/***/ }), +/* 812 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_TEXTURE_TINT_VS', + '', + 'precision mediump float;', + '', + 'uniform mat4 uProjectionMatrix;', + 'uniform mat4 uViewMatrix;', + 'uniform mat4 uModelMatrix;', + '', + 'attribute vec2 inPosition;', + 'attribute vec2 inTexCoord;', + 'attribute float inTintEffect;', + 'attribute vec4 inTint;', + '', + 'varying vec2 outTexCoord;', + 'varying float outTintEffect;', + 'varying vec4 outTint;', + '', + 'void main ()', + '{', + ' gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);', + '', + ' outTexCoord = inTexCoord;', + ' outTint = inTint;', + ' outTintEffect = inTintEffect;', + '}', + '', + '' +].join('\n'); + + +/***/ }), +/* 813 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Create + */ + +module.exports = { + + GenerateTexture: __webpack_require__(370), + Palettes: __webpack_require__(814) + +}; + + +/***/ }), +/* 814 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Create.Palettes + */ + +module.exports = { + + ARNE16: __webpack_require__(371), + C64: __webpack_require__(815), + CGA: __webpack_require__(816), + JMP: __webpack_require__(817), + MSX: __webpack_require__(818) + +}; + + +/***/ }), +/* 815 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color palette inspired by the Commodore 64. + * + * @name Phaser.Create.Palettes.C64 + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#fff', + 2: '#8b4131', + 3: '#7bbdc5', + 4: '#8b41ac', + 5: '#6aac41', + 6: '#3931a4', + 7: '#d5de73', + 8: '#945a20', + 9: '#5a4100', + A: '#bd736a', + B: '#525252', + C: '#838383', + D: '#acee8b', + E: '#7b73de', + F: '#acacac' +}; + + +/***/ }), +/* 816 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color CGA inspired palette by [Arne](http://androidarts.com/palette/16pal.htm) + * + * @name Phaser.Create.Palettes.CGA + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#2234d1', + 2: '#0c7e45', + 3: '#44aacc', + 4: '#8a3622', + 5: '#5c2e78', + 6: '#aa5c3d', + 7: '#b5b5b5', + 8: '#5e606e', + 9: '#4c81fb', + A: '#6cd947', + B: '#7be2f9', + C: '#eb8a60', + D: '#e23d69', + E: '#ffd93f', + F: '#fff' +}; + + +/***/ }), +/* 817 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color JMP palette by [Arne](http://androidarts.com/palette/16pal.htm) + * + * @name Phaser.Create.Palettes.JMP + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#191028', + 2: '#46af45', + 3: '#a1d685', + 4: '#453e78', + 5: '#7664fe', + 6: '#833129', + 7: '#9ec2e8', + 8: '#dc534b', + 9: '#e18d79', + A: '#d6b97b', + B: '#e9d8a1', + C: '#216c4b', + D: '#d365c8', + E: '#afaab9', + F: '#f5f4eb' +}; + + +/***/ }), +/* 818 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color palette inspired by Japanese computers like the MSX. + * + * @name Phaser.Create.Palettes.MSX + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#191028', + 2: '#46af45', + 3: '#a1d685', + 4: '#453e78', + 5: '#7664fe', + 6: '#833129', + 7: '#9ec2e8', + 8: '#dc534b', + 9: '#e18d79', + A: '#d6b97b', + B: '#e9d8a1', + C: '#216c4b', + D: '#d365c8', + E: '#afaab9', + F: '#fff' +}; + + +/***/ }), +/* 819 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Curves + */ + +module.exports = { + Path: __webpack_require__(820), + + CubicBezier: __webpack_require__(372), + Curve: __webpack_require__(86), + Ellipse: __webpack_require__(373), + Line: __webpack_require__(374), + QuadraticBezier: __webpack_require__(375), + Spline: __webpack_require__(376) +}; + + +/***/ }), +/* 820 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = __webpack_require__(0); +var CubicBezierCurve = __webpack_require__(372); +var EllipseCurve = __webpack_require__(373); +var GameObjectFactory = __webpack_require__(6); +var LineCurve = __webpack_require__(374); +var MovePathTo = __webpack_require__(821); +var QuadraticBezierCurve = __webpack_require__(375); +var Rectangle = __webpack_require__(11); +var SplineCurve = __webpack_require__(376); +var Vector2 = __webpack_require__(3); +var MATH_CONST = __webpack_require__(13); + +/** + * @classdesc + * A Path combines multiple Curves into one continuous compound curve. + * It does not matter how many Curves are in the Path or what type they are. + * + * A Curve in a Path does not have to start where the previous Curve ends - that is to say, a Path does not + * have to be an uninterrupted curve. Only the order of the Curves influences the actual points on the Path. + * + * @class Path + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The X coordinate of the Path's starting point or a {@link Phaser.Types.Curves.JSONPath}. + * @param {number} [y=0] - The Y coordinate of the Path's starting point. + */ +var Path = new Class({ + + initialize: + + function Path (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * The name of this Path. + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.Curves.Path#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * The list of Curves which make up this Path. + * + * @name Phaser.Curves.Path#curves + * @type {Phaser.Curves.Curve[]} + * @default [] + * @since 3.0.0 + */ + this.curves = []; + + /** + * The cached length of each Curve in the Path. + * + * Used internally by {@link #getCurveLengths}. + * + * @name Phaser.Curves.Path#cacheLengths + * @type {number[]} + * @default [] + * @since 3.0.0 + */ + this.cacheLengths = []; + + /** + * Automatically closes the path. + * + * @name Phaser.Curves.Path#autoClose + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.autoClose = false; + + /** + * The starting point of the Path. + * + * This is not necessarily equivalent to the starting point of the first Curve in the Path. In an empty Path, it's also treated as the ending point. + * + * @name Phaser.Curves.Path#startPoint + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.startPoint = new Vector2(); + + /** + * A temporary vector used to avoid object creation when adding a Curve to the Path. + * + * @name Phaser.Curves.Path#_tmpVec2A + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2A = new Vector2(); + + /** + * A temporary vector used to avoid object creation when adding a Curve to the Path. + * + * @name Phaser.Curves.Path#_tmpVec2B + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2B = new Vector2(); + + if (typeof x === 'object') + { + this.fromJSON(x); + } + else + { + this.startPoint.set(x, y); + } + }, + + /** + * Appends a Curve to the end of the Path. + * + * The Curve does not have to start where the Path ends or, for an empty Path, at its defined starting point. + * + * @method Phaser.Curves.Path#add + * @since 3.0.0 + * + * @param {Phaser.Curves.Curve} curve - The Curve to append. + * + * @return {Phaser.Curves.Path} This Path object. + */ + add: function (curve) + { + this.curves.push(curve); + + return this; + }, + + /** + * Creates a circular Ellipse Curve positioned at the end of the Path. + * + * @method Phaser.Curves.Path#circleTo + * @since 3.0.0 + * + * @param {number} radius - The radius of the circle. + * @param {boolean} [clockwise=false] - `true` to create a clockwise circle as opposed to a counter-clockwise circle. + * @param {number} [rotation=0] - The rotation of the circle in degrees. + * + * @return {Phaser.Curves.Path} This Path object. + */ + circleTo: function (radius, clockwise, rotation) + { + if (clockwise === undefined) { clockwise = false; } + + return this.ellipseTo(radius, radius, 0, 360, clockwise, rotation); + }, + + /** + * Ensures that the Path is closed. + * + * A closed Path starts and ends at the same point. If the Path is not closed, a straight Line Curve will be created from the ending point directly to the starting point. During the check, the actual starting point of the Path, i.e. the starting point of the first Curve, will be used as opposed to the Path's defined {@link startPoint}, which could differ. + * + * Calling this method on an empty Path will result in an error. + * + * @method Phaser.Curves.Path#closePath + * @since 3.0.0 + * + * @return {Phaser.Curves.Path} This Path object. + */ + closePath: function () + { + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[0].getPoint(0); + var endPoint = this.curves[this.curves.length - 1].getPoint(1); + + if (!startPoint.equals(endPoint)) + { + // This will copy a reference to the vectors, which probably isn't sensible + this.curves.push(new LineCurve(endPoint, startPoint)); + } + + return this; + }, + + /** + * Creates a cubic bezier curve starting at the previous end point and ending at p3, using p1 and p2 as control points. + * + * @method Phaser.Curves.Path#cubicBezierTo + * @since 3.0.0 + * + * @param {(number|Phaser.Math.Vector2)} x - The x coordinate of the end point. Or, if a Vector2, the p1 value. + * @param {(number|Phaser.Math.Vector2)} y - The y coordinate of the end point. Or, if a Vector2, the p2 value. + * @param {(number|Phaser.Math.Vector2)} control1X - The x coordinate of the first control point. Or, if a Vector2, the p3 value. + * @param {number} [control1Y] - The y coordinate of the first control point. Not used if Vector2s are provided as the first 3 arguments. + * @param {number} [control2X] - The x coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. + * @param {number} [control2Y] - The y coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. + * + * @return {Phaser.Curves.Path} This Path object. + */ + cubicBezierTo: function (x, y, control1X, control1Y, control2X, control2Y) + { + var p0 = this.getEndPoint(); + var p1; + var p2; + var p3; + + // Assume they're all Vector2s + if (x instanceof Vector2) + { + p1 = x; + p2 = y; + p3 = control1X; + } + else + { + p1 = new Vector2(control1X, control1Y); + p2 = new Vector2(control2X, control2Y); + p3 = new Vector2(x, y); + } + + return this.add(new CubicBezierCurve(p0, p1, p2, p3)); + }, + + // Creates a quadratic bezier curve starting at the previous end point and ending at p2, using p1 as a control point + + /** + * Creates a Quadratic Bezier Curve starting at the ending point of the Path. + * + * @method Phaser.Curves.Path#quadraticBezierTo + * @since 3.2.0 + * + * @param {(number|Phaser.Math.Vector2[])} x - The X coordinate of the second control point or, if it's a `Vector2`, the first control point. + * @param {number} [y] - The Y coordinate of the second control point or, if `x` is a `Vector2`, the second control point. + * @param {number} [controlX] - If `x` is not a `Vector2`, the X coordinate of the first control point. + * @param {number} [controlY] - If `x` is not a `Vector2`, the Y coordinate of the first control point. + * + * @return {Phaser.Curves.Path} This Path object. + */ + quadraticBezierTo: function (x, y, controlX, controlY) + { + var p0 = this.getEndPoint(); + var p1; + var p2; + + // Assume they're all Vector2s + if (x instanceof Vector2) + { + p1 = x; + p2 = y; + } + else + { + p1 = new Vector2(controlX, controlY); + p2 = new Vector2(x, y); + } + + return this.add(new QuadraticBezierCurve(p0, p1, p2)); + }, + + /** + * Draws all Curves in the Path to a Graphics Game Object. + * + * @method Phaser.Curves.Path#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [out,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics Game Object to draw to. + * @param {integer} [pointsTotal=32] - The number of points to draw for each Curve. Higher numbers result in a smoother curve but require more processing. + * + * @return {Phaser.GameObjects.Graphics} The Graphics object which was drawn to. + */ + draw: function (graphics, pointsTotal) + { + for (var i = 0; i < this.curves.length; i++) + { + var curve = this.curves[i]; + + if (!curve.active) + { + continue; + } + + curve.draw(graphics, pointsTotal); + } + + return graphics; + }, + + /** + * Creates an ellipse curve positioned at the previous end point, using the given parameters. + * + * @method Phaser.Curves.Path#ellipseTo + * @since 3.0.0 + * + * @param {number} [xRadius=0] - The horizontal radius of ellipse. + * @param {number} [yRadius=0] - The vertical radius of ellipse. + * @param {integer} [startAngle=0] - The start angle of the ellipse, in degrees. + * @param {integer} [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. + * + * @return {Phaser.Curves.Path} This Path object. + */ + ellipseTo: function (xRadius, yRadius, startAngle, endAngle, clockwise, rotation) + { + var ellipse = new EllipseCurve(0, 0, xRadius, yRadius, startAngle, endAngle, clockwise, rotation); + + var end = this.getEndPoint(this._tmpVec2A); + + // Calculate where to center the ellipse + var start = ellipse.getStartPoint(this._tmpVec2B); + + end.subtract(start); + + ellipse.x = end.x; + ellipse.y = end.y; + + return this.add(ellipse); + }, + + /** + * Creates a Path from a Path Configuration object. + * + * The provided object should be a {@link Phaser.Types.Curves.JSONPath}, as returned by {@link #toJSON}. Providing a malformed object may cause errors. + * + * @method Phaser.Curves.Path#fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONPath} data - The JSON object containing the Path data. + * + * @return {Phaser.Curves.Path} This Path object. + */ + fromJSON: function (data) + { + // data should be an object matching the Path.toJSON object structure. + + this.curves = []; + this.cacheLengths = []; + + this.startPoint.set(data.x, data.y); + + this.autoClose = data.autoClose; + + for (var i = 0; i < data.curves.length; i++) + { + var curve = data.curves[i]; + + switch (curve.type) + { + case 'LineCurve': + this.add(LineCurve.fromJSON(curve)); + break; + + case 'EllipseCurve': + this.add(EllipseCurve.fromJSON(curve)); + break; + + case 'SplineCurve': + this.add(SplineCurve.fromJSON(curve)); + break; + + case 'CubicBezierCurve': + this.add(CubicBezierCurve.fromJSON(curve)); + break; + + case 'QuadraticBezierCurve': + this.add(QuadraticBezierCurve.fromJSON(curve)); + break; + } + } + + return this; + }, + + /** + * Returns a Rectangle with a position and size matching the bounds of this Path. + * + * @method Phaser.Curves.Path#getBounds + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the bounds in. + * @param {integer} [accuracy=16] - The accuracy of the bounds calculations. Higher values are more accurate at the cost of calculation speed. + * + * @return {Phaser.Geom.Rectangle} The modified `out` Rectangle, or a new Rectangle if none was provided. + */ + getBounds: function (out, accuracy) + { + if (out === undefined) { out = new Rectangle(); } + if (accuracy === undefined) { accuracy = 16; } + + out.x = Number.MAX_VALUE; + out.y = Number.MAX_VALUE; + + var bounds = new Rectangle(); + var maxRight = MATH_CONST.MIN_SAFE_INTEGER; + var maxBottom = MATH_CONST.MIN_SAFE_INTEGER; + + for (var i = 0; i < this.curves.length; i++) + { + var curve = this.curves[i]; + + if (!curve.active) + { + continue; + } + + curve.getBounds(bounds, accuracy); + + out.x = Math.min(out.x, bounds.x); + out.y = Math.min(out.y, bounds.y); + + maxRight = Math.max(maxRight, bounds.right); + maxBottom = Math.max(maxBottom, bounds.bottom); + } + + out.right = maxRight; + out.bottom = maxBottom; + + return out; + }, + + /** + * Returns an array containing the length of the Path at the end of each Curve. + * + * The result of this method will be cached to avoid recalculating it in subsequent calls. The cache is only invalidated when the {@link #curves} array changes in length, leading to potential inaccuracies if a Curve in the Path is changed, or if a Curve is removed and another is added in its place. + * + * @method Phaser.Curves.Path#getCurveLengths + * @since 3.0.0 + * + * @return {number[]} An array containing the length of the Path at the end of each one of its Curves. + */ + getCurveLengths: function () + { + // We use cache values if curves and cache array are same length + + if (this.cacheLengths.length === this.curves.length) + { + return this.cacheLengths; + } + + // Get length of sub-curve + // Push sums into cached array + + var lengths = []; + var sums = 0; + + for (var i = 0; i < this.curves.length; i++) + { + sums += this.curves[i].getLength(); + + lengths.push(sums); + } + + this.cacheLengths = lengths; + + return lengths; + }, + + /** + * Returns the ending point of the Path. + * + * A Path's ending point is equivalent to the ending point of the last Curve in the Path. For an empty Path, the ending point is at the Path's defined {@link #startPoint}. + * + * @method Phaser.Curves.Path#getEndPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - The object to store the point in. + * + * @return {Phaser.Math.Vector2} The modified `out` object, or a new Vector2 if none was provided. + */ + getEndPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + if (this.curves.length > 0) + { + this.curves[this.curves.length - 1].getPoint(1, out); + } + else + { + out.copy(this.startPoint); + } + + return out; + }, + + /** + * Returns the total length of the Path. + * + * @see {@link #getCurveLengths} + * + * @method Phaser.Curves.Path#getLength + * @since 3.0.0 + * + * @return {number} The total length of the Path. + */ + getLength: function () + { + var lens = this.getCurveLengths(); + + return lens[lens.length - 1]; + }, + + // 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') + + /** + * Calculates the coordinates of the point at the given normalized location (between 0 and 1) on the Path. + * + * The location is relative to the entire Path, not to an individual Curve. A location of 0.5 is always in the middle of the Path and is thus an equal distance away from both its starting and ending points. In a Path with one Curve, it would be in the middle of the Curve; in a Path with two Curves, it could be anywhere on either one of them depending on their lengths. + * + * @method Phaser.Curves.Path#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The location of the point to return, between 0 and 1. + * @param {Phaser.Math.Vector2} [out] - The object in which to store the calculated point. + * + * @return {?Phaser.Math.Vector2} The modified `out` object, or a new `Vector2` if none was provided. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0; + + while (i < curveLengths.length) + { + if (curveLengths[i] >= d) + { + var diff = curveLengths[i] - d; + var curve = this.curves[i]; + + var segmentLength = curve.getLength(); + var u = (segmentLength === 0) ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt(u, out); + } + + i++; + } + + // loop where sum != 0, sum > d , sum+1 1 && !points[points.length - 1].equals(points[0])) + { + points.push(points[0]); + } + + return points; + }, + + /** + * Returns a randomly chosen point anywhere on the path. This follows the same rules as `getPoint` in that it may return a point on any Curve inside this path. + * + * When calling this method multiple times, the points are not guaranteed to be equally spaced spatially. + * + * @method Phaser.Curves.Path#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. + * + * @return {Phaser.Math.Vector2} The modified `out` object, or a new `Vector2` if none was provided. + */ + getRandomPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPoint(Math.random(), out); + }, + + /** + * Divides this Path into a set of equally spaced points, + * + * The resulting points are equally spaced with respect to the points' position on the path, but not necessarily equally spaced spatially. + * + * @method Phaser.Curves.Path#getSpacedPoints + * @since 3.0.0 + * + * @param {integer} [divisions=40] - The amount of points to divide this Path into. + * + * @return {Phaser.Math.Vector2[]} A list of the points this path was subdivided into. + */ + getSpacedPoints: function (divisions) + { + if (divisions === undefined) { divisions = 40; } + + var points = []; + + for (var i = 0; i <= divisions; i++) + { + points.push(this.getPoint(i / divisions)); + } + + if (this.autoClose) + { + points.push(points[0]); + } + + return points; + }, + + /** + * Returns the starting point of the Path. + * + * @method Phaser.Curves.Path#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. + * + * @return {Phaser.Math.Vector2} The modified `out` object, or a new Vector2 if none was provided. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.startPoint); + }, + + /** + * Creates a line curve from the previous end point to x/y. + * + * @method Phaser.Curves.Path#lineTo + * @since 3.0.0 + * + * @param {(number|Phaser.Math.Vector2)} x - The X coordinate of the line's end point, or a `Vector2` containing the entire end point. + * @param {number} [y] - The Y coordinate of the line's end point, if a number was passed as the X parameter. + * + * @return {Phaser.Curves.Path} This Path object. + */ + lineTo: function (x, y) + { + if (x instanceof Vector2) + { + this._tmpVec2B.copy(x); + } + else + { + this._tmpVec2B.set(x, y); + } + + var end = this.getEndPoint(this._tmpVec2A); + + return this.add(new LineCurve([ end.x, end.y, this._tmpVec2B.x, this._tmpVec2B.y ])); + }, + + /** + * Creates a spline curve starting at the previous end point, using the given points on the curve. + * + * @method Phaser.Curves.Path#splineTo + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2[]} points - The points the newly created spline curve should consist of. + * + * @return {Phaser.Curves.Path} This Path object. + */ + splineTo: function (points) + { + points.unshift(this.getEndPoint()); + + return this.add(new SplineCurve(points)); + }, + + /** + * Creates a "gap" in this path from the path's current end point to the given coordinates. + * + * After calling this function, this Path's end point will be equal to the given coordinates + * + * @method Phaser.Curves.Path#moveTo + * @since 3.0.0 + * + * @param {(number|Phaser.Math.Vector2)} x - The X coordinate of the position to move the path's end point to, or a `Vector2` containing the entire new end point. + * @param {number} y - The Y coordinate of the position to move the path's end point to, if a number was passed as the X coordinate. + * + * @return {Phaser.Curves.Path} This Path object. + */ + moveTo: function (x, y) + { + if (x instanceof Vector2) + { + return this.add(new MovePathTo(x.x, x.y)); + } + else + { + return this.add(new MovePathTo(x, y)); + } + }, + + /** + * Converts this Path to a JSON object containing the path information and its constituent curves. + * + * @method Phaser.Curves.Path#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONPath} The JSON object containing this path's data. + */ + toJSON: function () + { + var out = []; + + for (var i = 0; i < this.curves.length; i++) + { + out.push(this.curves[i].toJSON()); + } + + return { + type: 'Path', + x: this.startPoint.x, + y: this.startPoint.y, + autoClose: this.autoClose, + curves: out + }; + }, + + /** + * cacheLengths must be recalculated. + * + * @method Phaser.Curves.Path#updateArcLengths + * @since 3.0.0 + */ + updateArcLengths: function () + { + this.cacheLengths = []; + + this.getCurveLengths(); + }, + + /** + * Disposes of this Path, clearing its internal references to objects so they can be garbage-collected. + * + * @method Phaser.Curves.Path#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.curves.length = 0; + this.cacheLengths.length = 0; + this.startPoint = undefined; + } + +}); + +/** + * Creates a new Path Object. + * + * @method Phaser.GameObjects.GameObjectFactory#path + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this Path. + * @param {number} y - The vertical position of this Path. + * + * @return {Phaser.Curves.Path} The Path Object that was created. + */ +GameObjectFactory.register('path', function (x, y) +{ + return new Path(x, y); +}); + +// 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 + +module.exports = Path; + + +/***/ }), +/* 821 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Vector2 = __webpack_require__(3); + +/** + * @classdesc + * A MoveTo Curve is a very simple curve consisting of only a single point. Its intended use is to move the ending point in a Path. + * + * @class MoveTo + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - `x` pixel coordinate. + * @param {number} [y] - `y` pixel coordinate. + */ +var MoveTo = new Class({ + + initialize: + + function MoveTo (x, y) + { + // Skip length calcs in paths + + /** + * Denotes that this Curve does not influence the bounds, points, and drawing of its parent Path. Must be `false` or some methods in the parent Path will throw errors. + * + * @name Phaser.Curves.MoveTo#active + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.active = false; + + /** + * The lone point which this curve consists of. + * + * @name Phaser.Curves.MoveTo#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = new Vector2(x, y); + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.MoveTo#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * Retrieves the point at given position in the curve. This will always return this curve's only point. + * + * @method Phaser.Curves.MoveTo#getPointAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The position in the path to retrieve, between 0 and 1. Not used. + * @param {Phaser.Math.Vector2} [out] - An optional vector in which to store the point. + * + * @return {Phaser.Math.Vector2} The modified `out` vector, or a new `Vector2` if none was provided. + */ + getPointAt: function (u, out) + { + return this.getPoint(u, out); + }, + + /** + * Gets the resolution of this curve. + * + * @method Phaser.Curves.MoveTo#getResolution + * @since 3.0.0 + * + * @return {number} The resolution of this curve. For a MoveTo the value is always 1. + */ + getResolution: function () + { + return 1; + }, + + /** + * Gets the length of this curve. + * + * @method Phaser.Curves.MoveTo#getLength + * @since 3.0.0 + * + * @return {number} The length of this curve. For a MoveTo the value is always 0. + */ + getLength: function () + { + return 0; + }, + + /** + * Converts this curve into a JSON-serializable object. + * + * @method Phaser.Curves.MoveTo#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} A primitive object with the curve's type and only point. + */ + toJSON: function () + { + return { + type: 'MoveTo', + points: [ + this.p0.x, this.p0.y + ] + }; + } + +}); + +module.exports = MoveTo; + + +/***/ }), +/* 822 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Data + */ + +module.exports = { + + DataManager: __webpack_require__(101), + DataManagerPlugin: __webpack_require__(823), + Events: __webpack_require__(303) + +}; + + +/***/ }), +/* 823 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var DataManager = __webpack_require__(101); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * The Data Component features a means to store pieces of data specific to a Game Object, System or Plugin. + * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, + * or have a property called `events` that is an instance of it. + * + * @class DataManagerPlugin + * @extends Phaser.Data.DataManager + * @memberof Phaser.Data + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that this DataManager belongs to. + */ +var DataManagerPlugin = new Class({ + + Extends: DataManager, + + initialize: + + function DataManagerPlugin (scene) + { + DataManager.call(this, scene, scene.sys.events); + + /** + * A reference to the Scene that this DataManager belongs to. + * + * @name Phaser.Data.DataManagerPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene's Systems. + * + * @name Phaser.Data.DataManagerPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Data.DataManagerPlugin#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.events = this.systems.events; + + this.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Data.DataManagerPlugin#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Data.DataManagerPlugin#shutdown + * @private + * @since 3.5.0 + */ + shutdown: function () + { + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Data.DataManagerPlugin#destroy + * @since 3.5.0 + */ + destroy: function () + { + DataManager.prototype.destroy.call(this); + + this.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('DataManagerPlugin', DataManagerPlugin, 'data'); + +module.exports = DataManagerPlugin; + + +/***/ }), +/* 824 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display + */ + +module.exports = { + + Align: __webpack_require__(825), + BaseShader: __webpack_require__(377), + Bounds: __webpack_require__(828), + Canvas: __webpack_require__(831), + Color: __webpack_require__(378), + Masks: __webpack_require__(840) + +}; + + +/***/ }), +/* 825 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(97); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Display.Align + */ + +var Align = { + + In: __webpack_require__(826), + To: __webpack_require__(827) + +}; + +// Merge in the consts +Align = Extend(false, Align, CONST); + +module.exports = Align; + + +/***/ }), +/* 826 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Align.In + */ + +module.exports = { + + BottomCenter: __webpack_require__(274), + BottomLeft: __webpack_require__(275), + BottomRight: __webpack_require__(276), + Center: __webpack_require__(277), + LeftCenter: __webpack_require__(279), + QuickSet: __webpack_require__(273), + RightCenter: __webpack_require__(280), + TopCenter: __webpack_require__(281), + TopLeft: __webpack_require__(282), + TopRight: __webpack_require__(283) + +}; + + +/***/ }), +/* 827 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Align.To + */ + +module.exports = { + + BottomCenter: __webpack_require__(261), + BottomLeft: __webpack_require__(262), + BottomRight: __webpack_require__(263), + LeftBottom: __webpack_require__(264), + LeftCenter: __webpack_require__(265), + LeftTop: __webpack_require__(266), + QuickSet: __webpack_require__(260), + RightBottom: __webpack_require__(267), + RightCenter: __webpack_require__(268), + RightTop: __webpack_require__(269), + TopCenter: __webpack_require__(270), + TopLeft: __webpack_require__(271), + TopRight: __webpack_require__(272) + +}; + + +/***/ }), +/* 828 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Bounds + */ + +module.exports = { + + CenterOn: __webpack_require__(278), + GetBottom: __webpack_require__(44), + GetCenterX: __webpack_require__(81), + GetCenterY: __webpack_require__(83), + GetLeft: __webpack_require__(46), + GetOffsetX: __webpack_require__(829), + GetOffsetY: __webpack_require__(830), + GetRight: __webpack_require__(48), + GetTop: __webpack_require__(51), + SetBottom: __webpack_require__(50), + SetCenterX: __webpack_require__(82), + SetCenterY: __webpack_require__(84), + SetLeft: __webpack_require__(47), + SetRight: __webpack_require__(49), + SetTop: __webpack_require__(45) + +}; + + +/***/ }), +/* 829 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * origin.x`. + * This value will only be > 0 if `origin.x` is not equal to zero. + * + * @function Phaser.Display.Bounds.GetOffsetX + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The horizontal offset of the Game Object. + */ +var GetOffsetX = function (gameObject) +{ + return gameObject.width * gameObject.originX; +}; + +module.exports = GetOffsetX; + + +/***/ }), +/* 830 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the amount the Game Object is visually offset from its y coordinate. + * This is the same as `width * origin.y`. + * This value will only be > 0 if `origin.y` is not equal to zero. + * + * @function Phaser.Display.Bounds.GetOffsetY + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The vertical offset of the Game Object. + */ +var GetOffsetY = function (gameObject) +{ + return gameObject.height * gameObject.originY; +}; + +module.exports = GetOffsetY; + + +/***/ }), +/* 831 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Canvas + */ + +module.exports = { + + CanvasInterpolation: __webpack_require__(357), + CanvasPool: __webpack_require__(28), + Smoothing: __webpack_require__(177), + TouchAction: __webpack_require__(832), + UserSelect: __webpack_require__(833) + +}; + + +/***/ }), +/* 832 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @function Phaser.Display.Canvas.TouchAction + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas element to have the style applied to. + * @param {string} [value='none'] - The touch action value to set on the canvas. Set to `none` to disable touch actions. + * + * @return {HTMLCanvasElement} The canvas element. + */ +var TouchAction = function (canvas, value) +{ + if (value === undefined) { value = 'none'; } + + canvas.style['msTouchAction'] = value; + canvas.style['ms-touch-action'] = value; + canvas.style['touch-action'] = value; + + return canvas; +}; + +module.exports = TouchAction; + + +/***/ }), +/* 833 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @function Phaser.Display.Canvas.UserSelect + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas element to have the style applied to. + * @param {string} [value='none'] - The touch callout value to set on the canvas. Set to `none` to disable touch callouts. + * + * @return {HTMLCanvasElement} The canvas element. + */ +var UserSelect = function (canvas, value) +{ + if (value === undefined) { value = 'none'; } + + var vendors = [ + '-webkit-', + '-khtml-', + '-moz-', + '-ms-', + '' + ]; + + vendors.forEach(function (vendor) + { + canvas.style[vendor + 'user-select'] = value; + }); + + canvas.style['-webkit-touch-callout'] = value; + canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)'; + + return canvas; +}; + +module.exports = UserSelect; + + +/***/ }), +/* 834 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts the given color value into an Object containing r,g,b and a properties. + * + * @function Phaser.Display.Color.ColorToRGBA + * @since 3.0.0 + * + * @param {number} color - A color value, optionally including the alpha value. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the parsed color values. + */ +var ColorToRGBA = function (color) +{ + var output = { + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF, + a: 255 + }; + + if (color > 16777215) + { + output.a = color >>> 24; + } + + return output; +}; + +module.exports = ColorToRGBA; + + +/***/ }), +/* 835 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = __webpack_require__(36); +var HueToComponent = __webpack_require__(380); + +/** + * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. + * + * @function Phaser.Display.Color.HSLToColor + * @since 3.0.0 + * + * @param {number} h - The hue value in the range 0 to 1. + * @param {number} s - The saturation value in the range 0 to 1. + * @param {number} l - The lightness value in the range 0 to 1. + * + * @return {Phaser.Display.Color} A Color object created from the results of the h, s and l values. + */ +var HSLToColor = function (h, s, l) +{ + // achromatic by default + var r = l; + var g = l; + var b = l; + + if (s !== 0) + { + var q = (l < 0.5) ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + + r = HueToComponent(p, q, h + 1 / 3); + g = HueToComponent(p, q, h); + b = HueToComponent(p, q, h - 1 / 3); + } + + var color = new Color(); + + return color.setGLTo(r, g, b, 1); +}; + +module.exports = HSLToColor; + + +/***/ }), +/* 836 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HSVToRGB = __webpack_require__(176); + +/** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @function Phaser.Display.Color.HSVColorWheel + * @since 3.0.0 + * + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * + * @return {Phaser.Types.Display.ColorObject[]} An array containing 360 elements, where each contains a single numeric value corresponding to the color at that point in the HSV color wheel. + */ +var HSVColorWheel = function (s, v) +{ + if (s === undefined) { s = 1; } + if (v === undefined) { v = 1; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(HSVToRGB(c / 359, s, v)); + } + + return colors; +}; + +module.exports = HSVColorWheel; + + +/***/ }), +/* 837 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Linear = __webpack_require__(123); + +/** + * @namespace Phaser.Display.Color.Interpolate + * @memberof Phaser.Display.Color + * @since 3.0.0 + */ + +/** + * Interpolates between the two given color ranges over the length supplied. + * + * @function Phaser.Display.Color.Interpolate.RGBWithRGB + * @memberof Phaser.Display.Color.Interpolate + * @static + * @since 3.0.0 + * + * @param {number} r1 - Red value. + * @param {number} g1 - Blue value. + * @param {number} b1 - Green value. + * @param {number} r2 - Red value. + * @param {number} g2 - Blue value. + * @param {number} b2 - Green value. + * @param {number} [length=100] - Distance to interpolate over. + * @param {number} [index=0] - Index to start from. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. + */ +var RGBWithRGB = function (r1, g1, b1, r2, g2, b2, length, index) +{ + if (length === undefined) { length = 100; } + if (index === undefined) { index = 0; } + + var t = index / length; + + return { + r: Linear(r1, r2, t), + g: Linear(g1, g2, t), + b: Linear(b1, b2, t) + }; +}; + +/** + * Interpolates between the two given color objects over the length supplied. + * + * @function Phaser.Display.Color.Interpolate.ColorWithColor + * @memberof Phaser.Display.Color.Interpolate + * @static + * @since 3.0.0 + * + * @param {Phaser.Display.Color} color1 - The first Color object. + * @param {Phaser.Display.Color} color2 - The second Color object. + * @param {number} [length=100] - Distance to interpolate over. + * @param {number} [index=0] - Index to start from. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. + */ +var ColorWithColor = function (color1, color2, length, index) +{ + if (length === undefined) { length = 100; } + if (index === undefined) { index = 0; } + + return RGBWithRGB(color1.r, color1.g, color1.b, color2.r, color2.g, color2.b, length, index); +}; + +/** + * Interpolates between the Color object and color values over the length supplied. + * + * @function Phaser.Display.Color.Interpolate.ColorWithRGB + * @memberof Phaser.Display.Color.Interpolate + * @static + * @since 3.0.0 + * + * @param {Phaser.Display.Color} color1 - The first Color object. + * @param {number} r - Red value. + * @param {number} g - Blue value. + * @param {number} b - Green value. + * @param {number} [length=100] - Distance to interpolate over. + * @param {number} [index=0] - Index to start from. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. + */ +var ColorWithRGB = function (color, r, g, b, length, index) +{ + if (length === undefined) { length = 100; } + if (index === undefined) { index = 0; } + + return RGBWithRGB(color.r, color.g, color.b, r, g, b, length, index); +}; + +module.exports = { + + RGBWithRGB: RGBWithRGB, + ColorWithRGB: ColorWithRGB, + ColorWithColor: ColorWithColor + +}; + + +/***/ }), +/* 838 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Between = __webpack_require__(183); +var Color = __webpack_require__(36); + +/** + * 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 {integer} [min=0] - The minimum value to set the random range from (between 0 and 255) + * @param {integer} [max=255] - The maximum value to set the random range from (between 0 and 255) + * + * @return {Phaser.Display.Color} A Color object. + */ +var RandomRGB = function (min, max) +{ + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + + return new Color(Between(min, max), Between(min, max), Between(min, max)); +}; + +module.exports = RandomRGB; + + +/***/ }), +/* 839 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ComponentToHex = __webpack_require__(379); + +/** + * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. + * + * @function Phaser.Display.Color.RGBToString + * @since 3.0.0 + * + * @param {integer} r - The red color value. A number between 0 and 255. + * @param {integer} g - The green color value. A number between 0 and 255. + * @param {integer} b - The blue color value. A number between 0 and 255. + * @param {integer} [a=255] - The alpha value. A number between 0 and 255. + * @param {string} [prefix=#] - The prefix of the string. Either `#` or `0x`. + * + * @return {string} A string-based representation of the color values. + */ +var RGBToString = function (r, g, b, a, prefix) +{ + if (a === undefined) { a = 255; } + if (prefix === undefined) { prefix = '#'; } + + if (prefix === '#') + { + return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); + } + else + { + return '0x' + ComponentToHex(a) + ComponentToHex(r) + ComponentToHex(g) + ComponentToHex(b); + } +}; + +module.exports = RGBToString; + + +/***/ }), +/* 840 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Masks + */ + +module.exports = { + + BitmapMask: __webpack_require__(297), + GeometryMask: __webpack_require__(298) + +}; + + +/***/ }), +/* 841 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.DOM + */ + +var Dom = { + + AddToDOM: __webpack_require__(129), + DOMContentLoaded: __webpack_require__(381), + GetScreenOrientation: __webpack_require__(382), + GetTarget: __webpack_require__(387), + ParseXML: __webpack_require__(388), + RemoveFromDOM: __webpack_require__(191), + RequestAnimationFrame: __webpack_require__(368) + +}; + +module.exports = Dom; + + +/***/ }), +/* 842 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Events + */ + +module.exports = { EventEmitter: __webpack_require__(843) }; + + +/***/ }), +/* 843 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EE = __webpack_require__(9); +var PluginCache = __webpack_require__(22); + +/** + * @classdesc + * EventEmitter is a Scene Systems plugin compatible version of eventemitter3. + * + * @class EventEmitter + * @memberof Phaser.Events + * @constructor + * @since 3.0.0 + */ +var EventEmitter = new Class({ + + Extends: EE, + + initialize: + + function EventEmitter () + { + EE.call(this); + }, + + /** + * Removes all listeners. + * + * @method Phaser.Events.EventEmitter#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAllListeners(); + }, + + /** + * Removes all listeners. + * + * @method Phaser.Events.EventEmitter#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + } + +}); + +/** + * Return an array listing the events for which the emitter has registered listeners. + * + * @method Phaser.Events.EventEmitter#eventNames + * @since 3.0.0 + * + * @return {Array.} + */ + +/** + * Return the listeners registered for a given event. + * + * @method Phaser.Events.EventEmitter#listeners + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * + * @return {Function[]} The registered listeners. + */ + +/** + * Return the number of listeners listening to a given event. + * + * @method Phaser.Events.EventEmitter#listenerCount + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * + * @return {number} The number of listeners. + */ + +/** + * Calls each of the listeners registered for a given event. + * + * @method Phaser.Events.EventEmitter#emit + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {...*} [args] - Additional arguments that will be passed to the event handler. + * + * @return {boolean} `true` if the event had listeners, else `false`. + */ + +/** + * Add a listener for a given event. + * + * @method Phaser.Events.EventEmitter#on + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} fn - The listener function. + * @param {*} [context=this] - The context to invoke the listener with. + * + * @return {this} `this`. + */ + +/** + * Add a listener for a given event. + * + * @method Phaser.Events.EventEmitter#addListener + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} fn - The listener function. + * @param {*} [context=this] - The context to invoke the listener with. + * + * @return {this} `this`. + */ + +/** + * Add a one-time listener for a given event. + * + * @method Phaser.Events.EventEmitter#once + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} fn - The listener function. + * @param {*} [context=this] - The context to invoke the listener with. + * + * @return {this} `this`. + */ + +/** + * Remove the listeners of a given event. + * + * @method Phaser.Events.EventEmitter#removeListener + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} [fn] - Only remove the listeners that match this function. + * @param {*} [context] - Only remove the listeners that have this context. + * @param {boolean} [once] - Only remove one-time listeners. + * + * @return {this} `this`. + */ + +/** + * Remove the listeners of a given event. + * + * @method Phaser.Events.EventEmitter#off + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} [fn] - Only remove the listeners that match this function. + * @param {*} [context] - Only remove the listeners that have this context. + * @param {boolean} [once] - Only remove one-time listeners. + * + * @return {this} `this`. + */ + +/** + * Remove all listeners, or those of the specified event. + * + * @method Phaser.Events.EventEmitter#removeAllListeners + * @since 3.0.0 + * + * @param {(string|symbol)} [event] - The event name. + * + * @return {this} `this`. + */ + +PluginCache.register('EventEmitter', EventEmitter, 'events'); + +module.exports = EventEmitter; + + +/***/ }), +/* 844 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AddToDOM = __webpack_require__(129); +var AnimationManager = __webpack_require__(308); +var CacheManager = __webpack_require__(311); +var CanvasPool = __webpack_require__(28); +var Class = __webpack_require__(0); +var Config = __webpack_require__(333); +var CreateDOMContainer = __webpack_require__(845); +var CreateRenderer = __webpack_require__(356); +var DataManager = __webpack_require__(101); +var DebugHeader = __webpack_require__(366); +var Device = __webpack_require__(334); +var DOMContentLoaded = __webpack_require__(381); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(21); +var InputManager = __webpack_require__(389); +var PluginCache = __webpack_require__(22); +var PluginManager = __webpack_require__(394); +var ScaleManager = __webpack_require__(395); +var SceneManager = __webpack_require__(397); +var TextureEvents = __webpack_require__(128); +var TextureManager = __webpack_require__(400); +var TimeStep = __webpack_require__(367); +var VisibilityHandler = __webpack_require__(369); + +if (true) +{ + var SoundManagerCreator = __webpack_require__(404); +} + +if (true) +{ + var FacebookInstantGamesPlugin = __webpack_require__(412); +} + +/** + * @classdesc + * The Phaser.Game instance is the main controller for the entire Phaser game. It is responsible + * for handling the boot process, parsing the configuration values, creating the renderer, + * and setting-up all of the global Phaser systems, such as sound and input. + * Once that is complete it will start the Scene Manager and then begin the main game loop. + * + * You should generally avoid accessing any of the systems created by Game, and instead use those + * made available to you via the Phaser.Scene Systems class instead. + * + * @class Game + * @memberof Phaser + * @constructor + * @fires Phaser.Core.Events#BLUR + * @fires Phaser.Core.Events#FOCUS + * @fires Phaser.Core.Events#HIDDEN + * @fires Phaser.Core.Events#VISIBLE + * @since 3.0.0 + * + * @param {Phaser.Types.Core.GameConfig} [GameConfig] - The configuration object for your Phaser Game instance. + */ +var Game = new Class({ + + initialize: + + function Game (config) + { + /** + * The parsed Game Configuration object. + * + * The values stored within this object are read-only and should not be changed at run-time. + * + * @name Phaser.Game#config + * @type {Phaser.Core.Config} + * @readonly + * @since 3.0.0 + */ + this.config = new Config(config); + + /** + * A reference to either the Canvas or WebGL Renderer that this Game is using. + * + * @name Phaser.Game#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.0.0 + */ + this.renderer = null; + + /** + * A reference to an HTML Div Element used as the DOM Element Container. + * + * Only set if `createDOMContainer` is `true` in the game config (by default it is `false`) and + * if you provide a parent element to insert the Phaser Game inside. + * + * See the DOM Element Game Object for more details. + * + * @name Phaser.Game#domContainer + * @type {HTMLDivElement} + * @since 3.17.0 + */ + this.domContainer = null; + + /** + * A reference to the HTML Canvas Element that Phaser uses to render the game. + * This is created automatically by Phaser unless you provide a `canvas` property + * in your Game Config. + * + * @name Phaser.Game#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas = null; + + /** + * A reference to the Rendering Context belonging to the Canvas Element this game is rendering to. + * If the game is running under Canvas it will be a 2d Canvas Rendering Context. + * If the game is running under WebGL it will be a WebGL Rendering Context. + * This context is created automatically by Phaser unless you provide a `context` property + * in your Game Config. + * + * @name Phaser.Game#context + * @type {(CanvasRenderingContext2D|WebGLRenderingContext)} + * @since 3.0.0 + */ + this.context = null; + + /** + * A flag indicating when this Game instance has finished its boot process. + * + * @name Phaser.Game#isBooted + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isBooted = false; + + /** + * A flag indicating if this Game is currently running its game step or not. + * + * @name Phaser.Game#isRunning + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isRunning = false; + + /** + * An Event Emitter which is used to broadcast game-level events from the global systems. + * + * @name Phaser.Game#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = new EventEmitter(); + + /** + * An instance of the Animation Manager. + * + * The Animation Manager is a global system responsible for managing all animations used within your game. + * + * @name Phaser.Game#anims + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.anims = new AnimationManager(this); + + /** + * An instance of the Texture Manager. + * + * The Texture Manager is a global system responsible for managing all textures being used by your game. + * + * @name Phaser.Game#textures + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.textures = new TextureManager(this); + + /** + * An instance of the Cache Manager. + * + * The Cache Manager is a global system responsible for caching, accessing and releasing external game assets. + * + * @name Phaser.Game#cache + * @type {Phaser.Cache.CacheManager} + * @since 3.0.0 + */ + this.cache = new CacheManager(this); + + /** + * An instance of the Data Manager + * + * @name Phaser.Game#registry + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.registry = new DataManager(this); + + /** + * An instance of the Input Manager. + * + * The Input Manager is a global system responsible for the capture of browser-level input events. + * + * @name Phaser.Game#input + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.input = new InputManager(this, this.config); + + /** + * An instance of the Scene Manager. + * + * The Scene Manager is a global system responsible for creating, modifying and updating the Scenes in your game. + * + * @name Phaser.Game#scene + * @type {Phaser.Scenes.SceneManager} + * @since 3.0.0 + */ + this.scene = new SceneManager(this, this.config.sceneConfig); + + /** + * A reference to the Device inspector. + * + * Contains information about the device running this game, such as OS, browser vendor and feature support. + * Used by various systems to determine capabilities and code paths. + * + * @name Phaser.Game#device + * @type {Phaser.DeviceConf} + * @since 3.0.0 + */ + this.device = Device; + + /** + * An instance of the Scale Manager. + * + * The Scale Manager is a global system responsible for handling scaling of the game canvas. + * + * @name Phaser.Game#scale + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.0 + */ + this.scale = new ScaleManager(this, this.config); + + /** + * An instance of the base Sound Manager. + * + * The Sound Manager is a global system responsible for the playback and updating of all audio in your game. + * + * You can disable the inclusion of the Sound Manager in your build by toggling the webpack `FEATURE_SOUND` flag. + * + * @name Phaser.Game#sound + * @type {(Phaser.Sound.NoAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager)} + * @since 3.0.0 + */ + this.sound = null; + + if (true) + { + this.sound = SoundManagerCreator.create(this); + } + + /** + * An instance of the Time Step. + * + * The Time Step is a global system responsible for setting-up and responding to the browser frame events, processing + * them and calculating delta values. It then automatically calls the game step. + * + * @name Phaser.Game#loop + * @type {Phaser.Core.TimeStep} + * @since 3.0.0 + */ + this.loop = new TimeStep(this, this.config.fps); + + /** + * An instance of the Plugin Manager. + * + * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install + * those plugins into Scenes as required. + * + * @name Phaser.Game#plugins + * @type {Phaser.Plugins.PluginManager} + * @since 3.0.0 + */ + this.plugins = new PluginManager(this, this.config); + + if (true) + { + /** + * An instance of the Facebook Instant Games Plugin. + * + * This will only be available if the plugin has been built into Phaser, + * or you're using the special Facebook Instant Games custom build. + * + * @name Phaser.Game#facebook + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.13.0 + */ + this.facebook = new FacebookInstantGamesPlugin(this); + } + + /** + * Is this Game pending destruction at the start of the next frame? + * + * @name Phaser.Game#pendingDestroy + * @type {boolean} + * @private + * @since 3.5.0 + */ + this.pendingDestroy = false; + + /** + * Remove the Canvas once the destroy is over? + * + * @name Phaser.Game#removeCanvas + * @type {boolean} + * @private + * @since 3.5.0 + */ + this.removeCanvas = false; + + /** + * Remove everything when the game is destroyed. + * You cannot create a new Phaser instance on the same web page after doing this. + * + * @name Phaser.Game#noReturn + * @type {boolean} + * @private + * @since 3.12.0 + */ + this.noReturn = false; + + /** + * Does the window the game is running in currently have focus or not? + * This is modified by the VisibilityHandler. + * + * @name Phaser.Game#hasFocus + * @type {boolean} + * @readonly + * @since 3.9.0 + */ + this.hasFocus = false; + + // Wait for the DOM Ready event, then call boot. + DOMContentLoaded(this.boot.bind(this)); + }, + + /** + * This method is called automatically when the DOM is ready. It is responsible for creating the renderer, + * displaying the Debug Header, adding the game canvas to the DOM and emitting the 'boot' event. + * It listens for a 'ready' event from the base systems and once received it will call `Game.start`. + * + * @method Phaser.Game#boot + * @protected + * @fires Phaser.Core.Events#BOOT + * @listens Phaser.Textures.Events#READY + * @since 3.0.0 + */ + boot: function () + { + if (!PluginCache.hasCore('EventEmitter')) + { + console.warn('Aborting. Core Plugins missing.'); + return; + } + + this.isBooted = true; + + this.config.preBoot(this); + + this.scale.preBoot(); + + CreateRenderer(this); + + CreateDOMContainer(this); + + DebugHeader(this); + + AddToDOM(this.canvas, this.config.parent); + + // 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: + this.textures.once(TextureEvents.READY, this.texturesReady, this); + + this.events.emit(Events.BOOT); + }, + + /** + * Called automatically when the Texture Manager has finished setting up and preparing the + * default textures. + * + * @method Phaser.Game#texturesReady + * @private + * @fires Phaser.Game#ready + * @since 3.12.0 + */ + texturesReady: function () + { + // Start all the other systems + this.events.emit(Events.READY); + + this.start(); + }, + + /** + * Called automatically by Game.boot once all of the global systems have finished setting themselves up. + * By this point the Game is now ready to start the main loop running. + * It will also enable the Visibility Handler. + * + * @method Phaser.Game#start + * @protected + * @since 3.0.0 + */ + start: function () + { + this.isRunning = true; + + this.config.postBoot(this); + + if (this.renderer) + { + this.loop.start(this.step.bind(this)); + } + else + { + this.loop.start(this.headlessStep.bind(this)); + } + + VisibilityHandler(this); + + var eventEmitter = this.events; + + eventEmitter.on(Events.HIDDEN, this.onHidden, this); + eventEmitter.on(Events.VISIBLE, this.onVisible, this); + eventEmitter.on(Events.BLUR, this.onBlur, this); + eventEmitter.on(Events.FOCUS, this.onFocus, this); + }, + + /** + * 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_EVENT + * @fires Phaser.Core.Events#STEP_EVENT + * @fires Phaser.Core.Events#POST_STEP_EVENT + * @fires Phaser.Core.Events#PRE_RENDER_EVENT + * @fires Phaser.Core.Events#POST_RENDER_EVENT + * @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. + */ + step: function (time, delta) + { + if (this.pendingDestroy) + { + return this.runDestroy(); + } + + var eventEmitter = this.events; + + // Global Managers like Input and Sound update in the prestep + + eventEmitter.emit(Events.PRE_STEP, time, delta); + + // This is mostly meant for user-land code and plugins + + eventEmitter.emit(Events.STEP, time, delta); + + // Update the Scene Manager and all active Scenes + + this.scene.update(time, delta); + + // Our final event before rendering starts + + eventEmitter.emit(Events.POST_STEP, time, delta); + + var renderer = this.renderer; + + // Run the Pre-render (clearing the canvas, setting background colors, etc) + + renderer.preRender(); + + eventEmitter.emit(Events.PRE_RENDER, renderer, time, delta); + + // The main render loop. Iterates all Scenes and all Cameras in those scenes, rendering to the renderer instance. + + this.scene.render(renderer); + + // The Post-Render call. Tidies up loose end, takes snapshots, etc. + + renderer.postRender(); + + // The final event before the step repeats. Your last chance to do anything to the canvas before it all starts again. + + eventEmitter.emit(Events.POST_RENDER, renderer, time, delta); + }, + + /** + * 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.Game#prerenderEvent + * @fires Phaser.Game#postrenderEvent + * @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. + */ + headlessStep: function (time, delta) + { + if (this.pendingDestroy) + { + return this.runDestroy(); + } + + var eventEmitter = this.events; + + // Global Managers + + eventEmitter.emit(Events.PRE_STEP, time, delta); + + eventEmitter.emit(Events.STEP, time, delta); + + // Scenes + + this.scene.update(time, delta); + + eventEmitter.emit(Events.POST_STEP, time, delta); + + // Render + + eventEmitter.emit(Events.PRE_RENDER); + + eventEmitter.emit(Events.POST_RENDER); + }, + + /** + * Called automatically by the Visibility Handler. + * This will pause the main loop and then emit a pause event. + * + * @method Phaser.Game#onHidden + * @protected + * @fires Phaser.Core.Events#PAUSE + * @since 3.0.0 + */ + onHidden: function () + { + this.loop.pause(); + + this.events.emit(Events.PAUSE); + }, + + /** + * Called automatically by the Visibility Handler. + * This will resume the main loop and then emit a resume event. + * + * @method Phaser.Game#onVisible + * @protected + * @fires Phaser.Core.Events#RESUME + * @since 3.0.0 + */ + onVisible: function () + { + this.loop.resume(); + + this.events.emit(Events.RESUME); + }, + + /** + * Called automatically by the Visibility Handler. + * This will set the main loop into a 'blurred' state, which pauses it. + * + * @method Phaser.Game#onBlur + * @protected + * @since 3.0.0 + */ + onBlur: function () + { + this.hasFocus = false; + + this.loop.blur(); + }, + + /** + * Called automatically by the Visibility Handler. + * This will set the main loop into a 'focused' state, which resumes it. + * + * @method Phaser.Game#onFocus + * @protected + * @since 3.0.0 + */ + onFocus: function () + { + this.hasFocus = true; + + this.loop.focus(); + }, + + /** + * Returns the current game frame. + * + * When the game starts running, the frame is incremented every time Request Animation Frame, or Set Timeout, fires. + * + * @method Phaser.Game#getFrame + * @since 3.16.0 + * + * @return {number} The current game frame. + */ + getFrame: function () + { + return this.loop.frame; + }, + + /** + * 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. + */ + getTime: function () + { + return this.loop.now; + }, + + /** + * Flags this Game instance as needing to be destroyed on the _next frame_, making this an asynchronous operation. + * + * It will wait until the current frame has completed and then call `runDestroy` internally. + * + * If you need to react to the games eventual destruction, listen for the `DESTROY` event. + * + * If you **do not** need to run Phaser again on the same web page you can set the `noReturn` argument to `true` and it will free-up + * memory being held by the core Phaser plugins. If you do need to create another game instance on the same page, leave this as `false`. + * + * @method Phaser.Game#destroy + * @fires Phaser.Core.Events#DESTROY + * @since 3.0.0 + * + * @param {boolean} removeCanvas - Set to `true` if you would like the parent canvas element removed from the DOM, or `false` to leave it in place. + * @param {boolean} [noReturn=false] - If `true` all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this. + */ + destroy: function (removeCanvas, noReturn) + { + if (noReturn === undefined) { noReturn = false; } + + this.pendingDestroy = true; + + this.removeCanvas = removeCanvas; + this.noReturn = noReturn; + }, + + /** + * Destroys this Phaser.Game instance, all global systems, all sub-systems and all Scenes. + * + * @method Phaser.Game#runDestroy + * @private + * @since 3.5.0 + */ + runDestroy: function () + { + this.scene.destroy(); + + this.events.emit(Events.DESTROY); + + this.events.removeAllListeners(); + + if (this.renderer) + { + this.renderer.destroy(); + } + + if (this.removeCanvas && this.canvas) + { + CanvasPool.remove(this.canvas); + + if (this.canvas.parentNode) + { + this.canvas.parentNode.removeChild(this.canvas); + } + } + + if (this.domContainer) + { + this.domContainer.parentNode.removeChild(this.domContainer); + } + + this.loop.destroy(); + + this.pendingDestroy = false; + } + +}); + +module.exports = Game; + +/** + * "Computers are good at following instructions, but not at reading your mind." - Donald Knuth + */ + + +/***/ }), +/* 845 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AddToDOM = __webpack_require__(129); + +var CreateDOMContainer = function (game) +{ + var config = game.config; + + if (!config.parent || !config.domCreateContainer) + { + return; + } + + // DOM Element Container + var div = document.createElement('div'); + + div.style.cssText = [ + 'display: block;', + 'width: ' + game.scale.width + 'px;', + 'height: ' + game.scale.height + 'px;', + 'padding: 0; margin: 0;', + 'position: absolute;', + 'overflow: hidden;', + 'pointer-events: none;', + 'transform: scale(1);', + 'transform-origin: left top;' + ].join(' '); + + game.domContainer = div; + + AddToDOM(div, config.parent); +}; + +module.exports = CreateDOMContainer; + + +/***/ }), +/* 846 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Boot Event. + * + * This internal event is dispatched by the Input Plugin when it boots, signalling to all of its systems to create themselves. + * + * @event Phaser.Input.Events#BOOT + * @since 3.0.0 + */ +module.exports = 'boot'; + + +/***/ }), +/* 847 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Destroy Event. + * + * This internal event is dispatched by the Input Plugin when it is destroyed, signalling to all of its systems to destroy themselves. + * + * @event Phaser.Input.Events#DESTROY + * @since 3.0.0 + */ +module.exports = 'destroy'; + + +/***/ }), +/* 848 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag End Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer stops dragging a Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('dragend', listener)`. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_END]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_END} event instead. + * + * @event Phaser.Input.Events#DRAG_END + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer stopped dragging. + */ +module.exports = 'dragend'; + + +/***/ }), +/* 849 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Enter Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object into a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('dragenter', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_ENTER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_ENTER} event instead. + * + * @event Phaser.Input.Events#DRAG_ENTER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved into. + */ +module.exports = 'dragenter'; + + +/***/ }), +/* 850 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves while dragging a Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('drag', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG} event instead. + * + * @event Phaser.Input.Events#DRAG + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. + */ +module.exports = 'drag'; + + +/***/ }), +/* 851 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Leave Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object out of a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('dragleave', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_LEAVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_LEAVE} event instead. + * + * @event Phaser.Input.Events#DRAG_LEAVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has left. + */ +module.exports = 'dragleave'; + + +/***/ }), +/* 852 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object over a Drag Target. + * + * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within + * the drag target, it will emit this event instead. + * + * Listen to this event from within a Scene using: `this.input.on('dragover', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_OVER} event instead. + * + * @event Phaser.Input.Events#DRAG_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved over. + */ +module.exports = 'dragover'; + + +/***/ }), +/* 853 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Start Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer starts to drag any Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('dragstart', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_START]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_START} event instead. + * + * @event Phaser.Input.Events#DRAG_START + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + */ +module.exports = 'dragstart'; + + +/***/ }), +/* 854 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drop Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drops a Game Object on a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('drop', listener)`. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DROP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DROP} event instead. + * + * @event Phaser.Input.Events#DROP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer was dragging. + * @param {Phaser.GameObjects.GameObject} target - The Drag Target the `gameObject` has been dropped on. + */ +module.exports = 'drop'; + + +/***/ }), +/* 855 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Game Out Event. + * + * This event is dispatched by the Input Plugin if the active pointer leaves the game canvas and is now + * outside of it, elsewhere on the web page. + * + * Listen to this event from within a Scene using: `this.input.on('gameout', listener)`. + * + * @event Phaser.Input.Events#GAME_OUT + * @since 3.16.1 + * + * @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 {(MouseEvent|TouchEvent)} event - The DOM Event that triggered the canvas out. + */ +module.exports = 'gameout'; + + +/***/ }), +/* 856 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Game Over Event. + * + * This event is dispatched by the Input Plugin if the active pointer enters the game canvas and is now + * over of it, having previously been elsewhere on the web page. + * + * Listen to this event from within a Scene using: `this.input.on('gameover', listener)`. + * + * @event Phaser.Input.Events#GAME_OVER + * @since 3.16.1 + * + * @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 {(MouseEvent|TouchEvent)} event - The DOM Event that triggered the canvas over. + */ +module.exports = 'gameover'; + + +/***/ }), +/* 857 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Down Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down on _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectdown', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was pressed down on. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectdown'; + + +/***/ }), +/* 858 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag End Event. + * + * This event is dispatched by an interactive Game Object if a pointer stops dragging it. + * + * Listen to this event from a Game Object using: `gameObject.on('dragend', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive](Phaser.GameObjects.GameObject#setInteractive) for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_END + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} dragX - The x coordinate where the Pointer stopped dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer stopped dragging the Game Object, in world space. + */ +module.exports = 'dragend'; + + +/***/ }), +/* 859 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Enter Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it into a drag target. + * + * Listen to this event from a Game Object using: `gameObject.on('dragenter', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_ENTER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved into. + */ +module.exports = 'dragenter'; + + +/***/ }), +/* 860 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves while dragging it. + * + * Listen to this event from a Game Object using: `gameObject.on('drag', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. + */ +module.exports = 'drag'; + + +/***/ }), +/* 861 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Leave Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it out of a drag target. + * + * Listen to this event from a Game Object using: `gameObject.on('dragleave', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_LEAVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has left. + */ +module.exports = 'dragleave'; + + +/***/ }), +/* 862 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Over Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it over a drag target. + * + * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within + * the drag target, it will emit this event instead. + * + * Listen to this event from a Game Object using: `gameObject.on('dragover', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved over. + */ +module.exports = 'dragover'; + + +/***/ }), +/* 863 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Start Event. + * + * This event is dispatched by an interactive Game Object if a pointer starts to drag it. + * + * Listen to this event from a Game Object using: `gameObject.on('dragstart', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * There are lots of useful drag related properties that are set within the Game Object when dragging occurs. + * For example, `gameObject.input.dragStartX`, `dragStartY` and so on. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_START + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. + */ +module.exports = 'dragstart'; + + +/***/ }), +/* 864 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drop Event. + * + * This event is dispatched by an interactive Game Object if a pointer drops it on a Drag Target. + * + * Listen to this event from a Game Object using: `gameObject.on('drop', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DROP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The Drag Target the `gameObject` has been dropped on. + */ +module.exports = 'drop'; + + +/***/ }), +/* 865 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Move Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved across _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectmove', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was moved on. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectmove'; + + +/***/ }), +/* 866 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Out Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectout', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer moved out of. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectout'; + + +/***/ }), +/* 867 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectover', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer moved over. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectover'; + + +/***/ }), +/* 868 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Down Event. + * + * This event is dispatched by an interactive Game Object if a pointer is pressed down on it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerdown', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerdown'; + + +/***/ }), +/* 869 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Move Event. + * + * This event is dispatched by an interactive Game Object if a pointer is moved while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointermove', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointermove'; + + +/***/ }), +/* 870 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Out Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves out of it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerout', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerout'; + + +/***/ }), +/* 871 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Over Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerover', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerover'; + + +/***/ }), +/* 872 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Up Event. + * + * This event is dispatched by an interactive Game Object if a pointer is released while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerup', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_UP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerup'; + + +/***/ }), +/* 873 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Wheel Event. + * + * This event is dispatched by an interactive Game Object if a pointer has its wheel moved while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('wheel', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'wheel'; + + +/***/ }), +/* 874 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Up Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released while over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectup', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_UP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was over when released. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectup'; + + +/***/ }), +/* 875 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Wheel Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel moved while over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectwheel', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was over when the wheel changed. + * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectwheel'; + + +/***/ }), +/* 876 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Manager Boot Event. + * + * This internal event is dispatched by the Input Manager when it boots. + * + * @event Phaser.Input.Events#MANAGER_BOOT + * @since 3.0.0 + */ +module.exports = 'boot'; + + +/***/ }), +/* 877 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'process'; + + +/***/ }), +/* 878 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Manager Update Event. + * + * This internal event is dispatched by the Input Manager as part of its update step. + * + * @event Phaser.Input.Events#MANAGER_UPDATE + * @since 3.0.0 + */ +module.exports = 'update'; + + +/***/ }), +/* 879 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Down Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointerdown', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + */ +module.exports = 'pointerdown'; + + +/***/ }), +/* 880 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Down Outside Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere outside of the game canvas. + * + * Listen to this event from within a Scene using: `this.input.on('pointerdownoutside', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_DOWN_OUTSIDE + * @since 3.16.1 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + */ +module.exports = 'pointerdownoutside'; + + +/***/ }), +/* 881 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Move Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointermove', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + */ +module.exports = 'pointermove'; + + +/***/ }), +/* 882 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Out Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of any interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('pointerout', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} justOut - An array containing all interactive Game Objects that the pointer moved out of when the event was created. + */ +module.exports = 'pointerout'; + + +/***/ }), +/* 883 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over any interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('pointerover', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} justOver - An array containing all interactive Game Objects that the pointer moved over when the event was created. + */ +module.exports = 'pointerover'; + + +/***/ }), +/* 884 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Up Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointerup', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_UP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + */ +module.exports = 'pointerup'; + + +/***/ }), +/* 885 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Up Outside Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere outside of the game canvas. + * + * Listen to this event from within a Scene using: `this.input.on('pointerupoutside', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_UP_OUTSIDE + * @since 3.16.1 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + */ +module.exports = 'pointerupoutside'; + + +/***/ }), +/* 886 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Wheel Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel updated. + * + * Listen to this event from within a Scene using: `this.input.on('wheel', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + */ +module.exports = 'wheel'; + + +/***/ }), +/* 887 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Manager Pointer Lock Change Event. + * + * This event is dispatched by the Input Manager when it is processing a native Pointer Lock Change DOM Event. + * + * @event Phaser.Input.Events#POINTERLOCK_CHANGE + * @since 3.0.0 + * + * @param {Event} event - The native DOM Event. + * @param {boolean} locked - The locked state of the Mouse Pointer. + */ +module.exports = 'pointerlockchange'; + + +/***/ }), +/* 888 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Pre-Update Event. + * + * This internal event is dispatched by the Input Plugin at the start of its `preUpdate` method. + * This hook is designed specifically for input plugins, but can also be listened to from user-land code. + * + * @event Phaser.Input.Events#PRE_UPDATE + * @since 3.0.0 + */ +module.exports = 'preupdate'; + + +/***/ }), +/* 889 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Shutdown Event. + * + * This internal event is dispatched by the Input Plugin when it shuts down, signalling to all of its systems to shut themselves down. + * + * @event Phaser.Input.Events#SHUTDOWN + * @since 3.0.0 + */ +module.exports = 'shutdown'; + + +/***/ }), +/* 890 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Start Event. + * + * This internal event is dispatched by the Input Plugin when it has finished setting-up, + * signalling to all of its internal systems to start. + * + * @event Phaser.Input.Events#START + * @since 3.0.0 + */ +module.exports = 'start'; + + +/***/ }), +/* 891 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'update'; + + +/***/ }), +/* 892 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Attempts to determine the document inner height across iOS and standard devices. + * 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 value. + */ +var GetInnerHeight = function (iOS) +{ + + if (!iOS) + { + return window.innerHeight; + } + + var axis = Math.abs(window.orientation); + + var size = { w: 0, h: 0 }; + + var ruler = document.createElement('div'); + + ruler.setAttribute('style', 'position: fixed; height: 100vh; width: 0; top: 0'); + + document.documentElement.appendChild(ruler); + + size.w = (axis === 90) ? ruler.offsetHeight : window.innerWidth; + size.h = (axis === 90) ? window.innerWidth : ruler.offsetHeight; + + document.documentElement.removeChild(ruler); + + ruler = null; + + if (Math.abs(window.orientation) !== 90) + { + return size.h; + } + else + { + return size.w; + } +}; + +module.exports = GetInnerHeight; + + +/***/ }), +/* 893 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Add File Event. + * + * This event is dispatched when a new file is successfully added to the Loader and placed into the load queue. + * + * Listen to it from a Scene using: `this.load.on('addfile', listener)`. + * + * If you add lots of files to a Loader from a `preload` method, it will dispatch this event for each one of them. + * + * @event Phaser.Loader.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique key of the file that was added to the Loader. + * @param {string} type - The [file type]{@link Phaser.Loader.File#type} string of the file that was added to the Loader, i.e. `image`. + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + * @param {Phaser.Loader.File} file - A reference to the File which was added to the Loader. + */ +module.exports = 'addfile'; + + +/***/ }), +/* 894 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Complete Event. + * + * This event is dispatched when the Loader has fully processed everything in the load queue. + * By this point every loaded file will now be in its associated cache and ready for use. + * + * Listen to it from a Scene using: `this.load.on('complete', listener)`. + * + * @event Phaser.Loader.Events#COMPLETE + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + * @param {integer} totalComplete - The total number of files that successfully loaded. + * @param {integer} totalFailed - The total number of files that failed to load. + */ +module.exports = 'complete'; + + +/***/ }), +/* 895 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Complete Event. + * + * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. + * + * Listen to it from a Scene using: `this.load.on('filecomplete', listener)`. + * + * You can also listen for the completion of a specific file. See the [FILE_KEY_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_KEY_COMPLETE} event. + * + * @event Phaser.Loader.Events#FILE_COMPLETE + * @since 3.0.0 + * + * @param {string} key - The key of the file that just loaded and finished processing. + * @param {string} type - The [file type]{@link Phaser.Loader.File#type} of the file that just loaded, i.e. `image`. + * @param {any} data - The raw data the file contained. + */ +module.exports = 'filecomplete'; + + +/***/ }), +/* 896 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Complete Event. + * + * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. + * + * It uses a special dynamic event name constructed from the key and type of the file. + * + * For example, if you have loaded an `image` with a key of `monster`, you can listen for it + * using the following: + * + * ```javascript + * this.load.on('filecomplete-image-monster', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * Or, if you have loaded a texture `atlas` with a key of `Level1`: + * + * ```javascript + * this.load.on('filecomplete-atlas-Level1', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * Or, if you have loaded a sprite sheet with a key of `Explosion` and a prefix of `GAMEOVER`: + * + * ```javascript + * this.load.on('filecomplete-spritesheet-GAMEOVERExplosion', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * You can also listen for the generic completion of files. See the [FILE_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_COMPLETE} event. + * + * @event Phaser.Loader.Events#FILE_KEY_COMPLETE + * @since 3.0.0 + * + * @param {string} key - The key of the file that just loaded and finished processing. + * @param {string} type - The [file type]{@link Phaser.Loader.File#type} of the file that just loaded, i.e. `image`. + * @param {any} data - The raw data the file contained. + */ +module.exports = 'filecomplete-'; + + +/***/ }), +/* 897 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Error Event. + * + * This event is dispatched by the Loader Plugin when a file fails to load. + * + * Listen to it from a Scene using: `this.load.on('loaderror', listener)`. + * + * @event Phaser.Loader.Events#FILE_LOAD_ERROR + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - A reference to the File which errored during load. + */ +module.exports = 'loaderror'; + + +/***/ }), +/* 898 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Event. + * + * This event is dispatched by the Loader Plugin when a file finishes loading, + * but _before_ it is processed and added to the internal Phaser caches. + * + * Listen to it from a Scene using: `this.load.on('load', listener)`. + * + * @event Phaser.Loader.Events#FILE_LOAD + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - A reference to the File which just finished loading. + */ +module.exports = 'load'; + + +/***/ }), +/* 899 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Progress Event. + * + * This event is dispatched by the Loader Plugin during the load of a file, if the browser receives a DOM ProgressEvent and + * the `lengthComputable` event property is true. Depending on the size of the file and browser in use, this may, or may not happen. + * + * Listen to it from a Scene using: `this.load.on('fileprogress', listener)`. + * + * @event Phaser.Loader.Events#FILE_PROGRESS + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - A reference to the File which errored during load. + * @param {number} percentComplete - A value between 0 and 1 indicating how 'complete' this file is. + */ +module.exports = 'fileprogress'; + + +/***/ }), +/* 900 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Post Process Event. + * + * This event is dispatched by the Loader Plugin when the Loader has finished loading everything in the load queue. + * It is dispatched before the internal lists are cleared and each File is destroyed. + * + * Use this hook to perform any last minute processing of files that can only happen once the + * Loader has completed, but prior to it emitting the `complete` event. + * + * Listen to it from a Scene using: `this.load.on('postprocess', listener)`. + * + * @event Phaser.Loader.Events#POST_PROCESS + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + */ +module.exports = 'postprocess'; + + +/***/ }), +/* 901 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Progress Event. + * + * This event is dispatched when the Loader updates its load progress, typically as a result of a file having completed loading. + * + * Listen to it from a Scene using: `this.load.on('progress', listener)`. + * + * @event Phaser.Loader.Events#PROGRESS + * @since 3.0.0 + * + * @param {number} progress - The current progress of the load. A value between 0 and 1. + */ +module.exports = 'progress'; + + +/***/ }), +/* 902 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Start Event. + * + * This event is dispatched when the Loader starts running. At this point load progress is zero. + * + * This event is dispatched even if there aren't any files in the load queue. + * + * Listen to it from a Scene using: `this.load.on('start', listener)`. + * + * @event Phaser.Loader.Events#START + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + */ +module.exports = 'start'; + + +/***/ }), +/* 903 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); +var UppercaseFirst = __webpack_require__(194); + +/** + * Builds an array of which physics plugins should be activated for the given Scene. + * + * @function Phaser.Scenes.GetPhysicsPlugins + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - The scene system to get the physics systems of. + * + * @return {array} An array of Physics systems to start for this Scene. + */ +var GetPhysicsPlugins = function (sys) +{ + var defaultSystem = sys.game.config.defaultPhysicsSystem; + var sceneSystems = GetFastValue(sys.settings, 'physics', false); + + if (!defaultSystem && !sceneSystems) + { + // No default physics system or systems in this scene + return; + } + + // Let's build the systems array + var output = []; + + if (defaultSystem) + { + output.push(UppercaseFirst(defaultSystem + 'Physics')); + } + + if (sceneSystems) + { + for (var key in sceneSystems) + { + key = UppercaseFirst(key.concat('Physics')); + + if (output.indexOf(key) === -1) + { + output.push(key); + } + } + } + + // An array of Physics systems to start for this Scene + return output; +}; + +module.exports = GetPhysicsPlugins; + + +/***/ }), +/* 904 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * Builds an array of which plugins (not including physics plugins) should be activated for the given Scene. + * + * @function Phaser.Scenes.GetScenePlugins + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - The Scene Systems object to check for plugins. + * + * @return {array} An array of all plugins which should be activated, either the default ones or the ones configured in the Scene Systems object. + */ +var GetScenePlugins = function (sys) +{ + var defaultPlugins = sys.plugins.getDefaultScenePlugins(); + + var scenePlugins = GetFastValue(sys.settings, 'plugins', false); + + // Scene Plugins always override Default Plugins + if (Array.isArray(scenePlugins)) + { + return scenePlugins; + } + else if (defaultPlugins) + { + return defaultPlugins; + } + else + { + // No default plugins or plugins in this scene + return []; + } +}; + +module.exports = GetScenePlugins; + + +/***/ }), +/* 905 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// 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' +// } +// }; + +var InjectionMap = { + + game: 'game', + + anims: 'anims', + cache: 'cache', + plugins: 'plugins', + registry: 'registry', + scale: 'scale', + sound: 'sound', + textures: 'textures', + + events: 'events', + cameras: 'cameras', + add: 'add', + make: 'make', + scenePlugin: 'scene', + displayList: 'children', + lights: 'lights', + + data: 'data', + input: 'input', + load: 'load', + time: 'time', + tweens: 'tweens', + + arcadePhysics: 'physics', + impactPhysics: 'impact', + matterPhysics: 'matter' + +}; + +if (false) +{} + +if (true) +{ + InjectionMap.facebook = 'facebook'; +} + +module.exports = InjectionMap; + + +/***/ }), +/* 906 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Parses an XML Texture Atlas object and adds all the Frames into a Texture. + * + * @function Phaser.Textures.Parsers.AtlasXML + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.7.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {*} xml - The XML data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var AtlasXML = function (texture, sourceIndex, xml) +{ + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn('Invalid Texture Atlas XML given'); + return; + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + // By this stage frames is a fully parsed array + var frames = xml.getElementsByTagName('SubTexture'); + + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + var frame = frames[i].attributes; + + var name = frame.name.value; + var x = parseInt(frame.x.value, 10); + var y = parseInt(frame.y.value, 10); + var width = parseInt(frame.width.value, 10); + var height = parseInt(frame.height.value, 10); + + // The frame values are the exact coordinates to cut the frame out of the atlas from + newFrame = texture.add(name, sourceIndex, x, y, width, height); + + // These are the original (non-trimmed) sprite values + if (frame.frameX) + { + var frameX = Math.abs(parseInt(frame.frameX.value, 10)); + var frameY = Math.abs(parseInt(frame.frameY.value, 10)); + var frameWidth = parseInt(frame.frameWidth.value, 10); + var frameHeight = parseInt(frame.frameHeight.value, 10); + + newFrame.setTrim( + width, + height, + frameX, + frameY, + frameWidth, + frameHeight + ); + } + } + + return texture; +}; + +module.exports = AtlasXML; + + +/***/ }), +/* 907 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds a Canvas Element to a Texture. + * + * @function Phaser.Textures.Parsers.Canvas + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var Canvas = function (texture, sourceIndex) +{ + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + return texture; +}; + +module.exports = Canvas; + + +/***/ }), +/* 908 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds an Image Element to a Texture. + * + * @function Phaser.Textures.Parsers.Image + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var Image = function (texture, sourceIndex) +{ + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + return texture; +}; + +module.exports = Image; + + +/***/ }), +/* 909 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(73); + +/** + * Parses a Texture Atlas JSON Array and adds the Frames to the Texture. + * JSON format expected to match that defined by Texture Packer, with the frames property containing an array of Frames. + * + * @function Phaser.Textures.Parsers.JSONArray + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {object} json - The JSON data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var JSONArray = function (texture, sourceIndex, json) +{ + // Malformed? + if (!json['frames'] && !json['textures']) + { + console.warn('Invalid Texture Atlas JSON Array'); + return; + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + // By this stage frames is a fully parsed array + var frames = (Array.isArray(json.textures)) ? json.textures[sourceIndex].frames : json.frames; + + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + var src = frames[i]; + + // The frame values are the exact coordinates to cut the frame out of the atlas from + newFrame = texture.add(src.filename, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); + + // These are the original (non-trimmed) sprite values + if (src.trimmed) + { + newFrame.setTrim( + src.sourceSize.w, + src.sourceSize.h, + src.spriteSourceSize.x, + src.spriteSourceSize.y, + src.spriteSourceSize.w, + src.spriteSourceSize.h + ); + } + + if (src.rotated) + { + newFrame.rotated = true; + newFrame.updateUVsInverted(); + } + + if (src.anchor) + { + newFrame.customPivot = true; + newFrame.pivotX = src.anchor.x; + newFrame.pivotY = src.anchor.y; + } + + // Copy over any extra data + newFrame.customData = Clone(src); + } + + // Copy over any additional data that was in the JSON to Texture.customData + for (var dataKey in json) + { + if (dataKey === 'frames') + { + continue; + } + + if (Array.isArray(json[dataKey])) + { + texture.customData[dataKey] = json[dataKey].slice(0); + } + else + { + texture.customData[dataKey] = json[dataKey]; + } + } + + return texture; +}; + +module.exports = JSONArray; + + +/***/ }), +/* 910 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(73); + +/** + * Parses a Texture Atlas JSON Hash and adds the Frames to the Texture. + * JSON format expected to match that defined by Texture Packer, with the frames property containing an object of Frames. + * + * @function Phaser.Textures.Parsers.JSONHash + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {object} json - The JSON data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var JSONHash = function (texture, sourceIndex, json) +{ + // Malformed? + if (!json['frames']) + { + console.warn('Invalid Texture Atlas JSON Hash given, missing \'frames\' Object'); + return; + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + // By this stage frames is a fully parsed Object + var frames = json['frames']; + var newFrame; + + for (var key in frames) + { + var src = frames[key]; + + // The frame values are the exact coordinates to cut the frame out of the atlas from + newFrame = texture.add(key, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); + + // These are the original (non-trimmed) sprite values + if (src.trimmed) + { + newFrame.setTrim( + src.sourceSize.w, + src.sourceSize.h, + src.spriteSourceSize.x, + src.spriteSourceSize.y, + src.spriteSourceSize.w, + src.spriteSourceSize.h + ); + } + + if (src.rotated) + { + newFrame.rotated = true; + newFrame.updateUVsInverted(); + } + + // Copy over any extra data + newFrame.customData = Clone(src); + } + + // Copy over any additional data that was in the JSON to Texture.customData + for (var dataKey in json) + { + if (dataKey === 'frames') + { + continue; + } + + if (Array.isArray(json[dataKey])) + { + texture.customData[dataKey] = json[dataKey].slice(0); + } + else + { + texture.customData[dataKey] = json[dataKey]; + } + } + + return texture; +}; + +module.exports = JSONHash; + + +/***/ }), +/* 911 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * Parses a Sprite Sheet and adds the Frames to the Texture. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @function Phaser.Textures.Parsers.SpriteSheet + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {integer} x - [description] + * @param {integer} y - [description] + * @param {integer} width - [description] + * @param {integer} height - [description] + * @param {object} config - An object describing how to parse the Sprite Sheet. + * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. + * @param {number} [config.startFrame=0] - [description] + * @param {number} [config.endFrame=-1] - [description] + * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var SpriteSheet = function (texture, sourceIndex, x, y, width, height, config) +{ + var frameWidth = GetFastValue(config, 'frameWidth', null); + var frameHeight = GetFastValue(config, 'frameHeight', frameWidth); + + // If missing we can't proceed + if (frameWidth === null) + { + throw new Error('TextureManager.SpriteSheet: Invalid frameWidth given.'); + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + var startFrame = GetFastValue(config, 'startFrame', 0); + var endFrame = GetFastValue(config, 'endFrame', -1); + var margin = GetFastValue(config, 'margin', 0); + var spacing = GetFastValue(config, 'spacing', 0); + + var row = Math.floor((width - margin + spacing) / (frameWidth + spacing)); + var column = Math.floor((height - margin + spacing) / (frameHeight + spacing)); + var total = row * column; + + if (total === 0) + { + console.warn('SpriteSheet frame dimensions will result in zero frames.'); + } + + if (startFrame > total || startFrame < -total) + { + startFrame = 0; + } + + if (startFrame < 0) + { + // Allow negative skipframes. + startFrame = total + startFrame; + } + + if (endFrame !== -1) + { + total = startFrame + (endFrame + 1); + } + + var fx = margin; + var fy = margin; + var ax = 0; + var ay = 0; + + for (var i = 0; i < total; i++) + { + ax = 0; + ay = 0; + + var w = fx + frameWidth; + var h = fy + frameHeight; + + if (w > width) + { + ax = w - width; + } + + if (h > height) + { + ay = h - height; + } + + texture.add(i, sourceIndex, x + fx, y + fy, frameWidth - ax, frameHeight - ay); + + fx += frameWidth + spacing; + + if (fx + frameWidth > width) + { + fx = margin; + fy += frameHeight + spacing; + } + } + + return texture; +}; + +module.exports = SpriteSheet; + + +/***/ }), +/* 912 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * Parses a Sprite Sheet and adds the Frames to the Texture, where the Sprite Sheet is stored as a frame within an Atlas. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @function Phaser.Textures.Parsers.SpriteSheetFromAtlas + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {Phaser.Textures.Frame} frame - The Frame that contains the Sprite Sheet. + * @param {object} config - An object describing how to parse the Sprite Sheet. + * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. + * @param {number} [config.startFrame=0] - Index of the start frame in the sprite sheet + * @param {number} [config.endFrame=-1] - Index of the end frame in the sprite sheet. -1 mean all the rest of the frames + * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var SpriteSheetFromAtlas = function (texture, frame, config) +{ + var frameWidth = GetFastValue(config, 'frameWidth', null); + var frameHeight = GetFastValue(config, 'frameHeight', frameWidth); + + // If missing we can't proceed + if (!frameWidth) + { + throw new Error('TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.'); + } + + // Add in a __BASE entry (for the entire atlas frame) + var source = texture.source[0]; + texture.add('__BASE', 0, 0, 0, source.width, source.height); + + var startFrame = GetFastValue(config, 'startFrame', 0); + var endFrame = GetFastValue(config, 'endFrame', -1); + var margin = GetFastValue(config, 'margin', 0); + var spacing = GetFastValue(config, 'spacing', 0); + + var x = frame.cutX; + var y = frame.cutY; + + var cutWidth = frame.cutWidth; + var cutHeight = frame.cutHeight; + var sheetWidth = frame.realWidth; + var sheetHeight = frame.realHeight; + + var row = Math.floor((sheetWidth - margin + spacing) / (frameWidth + spacing)); + var column = Math.floor((sheetHeight - margin + spacing) / (frameHeight + spacing)); + var total = row * column; + + // trim offsets + + var leftPad = frame.x; + var leftWidth = frameWidth - leftPad; + + var rightWidth = frameWidth - ((sheetWidth - cutWidth) - leftPad); + + var topPad = frame.y; + var topHeight = frameHeight - topPad; + + var bottomHeight = frameHeight - ((sheetHeight - cutHeight) - topPad); + + if (startFrame > total || startFrame < -total) + { + startFrame = 0; + } + + if (startFrame < 0) + { + // Allow negative skipframes. + startFrame = total + startFrame; + } + + if (endFrame !== -1) + { + total = startFrame + (endFrame + 1); + } + + var sheetFrame; + var frameX = margin; + var frameY = margin; + var frameIndex = 0; + var sourceIndex = frame.sourceIndex; + + for (var sheetY = 0; sheetY < column; sheetY++) + { + var topRow = (sheetY === 0); + var bottomRow = (sheetY === column - 1); + + for (var sheetX = 0; sheetX < row; sheetX++) + { + var leftRow = (sheetX === 0); + var rightRow = (sheetX === row - 1); + + sheetFrame = texture.add(frameIndex, sourceIndex, x + frameX, y + frameY, frameWidth, frameHeight); + + if (leftRow || topRow || rightRow || bottomRow) + { + var destX = (leftRow) ? leftPad : 0; + var destY = (topRow) ? topPad : 0; + + var trimWidth = 0; + var trimHeight = 0; + + if (leftRow) + { + trimWidth += (frameWidth - leftWidth); + } + + if (rightRow) + { + trimWidth += (frameWidth - rightWidth); + } + + if (topRow) + { + trimHeight += (frameHeight - topHeight); + } + + if (bottomRow) + { + trimHeight += (frameHeight - bottomHeight); + } + + var destWidth = frameWidth - trimWidth; + var destHeight = frameHeight - trimHeight; + + sheetFrame.cutWidth = destWidth; + sheetFrame.cutHeight = destHeight; + + sheetFrame.setTrim(frameWidth, frameHeight, destX, destY, destWidth, destHeight); + } + + frameX += spacing; + + if (leftRow) + { + frameX += leftWidth; + } + else if (rightRow) + { + frameX += rightWidth; + } + else + { + frameX += frameWidth; + } + + frameIndex++; + } + + frameX = margin; + frameY += spacing; + + if (topRow) + { + frameY += topHeight; + } + else if (bottomRow) + { + frameY += bottomHeight; + } + else + { + frameY += frameHeight; + } + } + + return texture; +}; + +module.exports = SpriteSheetFromAtlas; + + +/***/ }), +/* 913 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var imageHeight = 0; + +/** + * @function addFrame + * @private + * @since 3.0.0 + */ +var addFrame = function (texture, sourceIndex, name, frame) +{ + // The frame values are the exact coordinates to cut the frame out of the atlas from + + var y = imageHeight - frame.y - frame.height; + + texture.add(name, sourceIndex, frame.x, y, frame.width, frame.height); + + // These are the original (non-trimmed) sprite values + /* + if (src.trimmed) + { + newFrame.setTrim( + src.sourceSize.w, + src.sourceSize.h, + src.spriteSourceSize.x, + src.spriteSourceSize.y, + src.spriteSourceSize.w, + src.spriteSourceSize.h + ); + } + */ +}; + +/** + * 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 {integer} sourceIndex - The index of the TextureSource. + * @param {object} yaml - The YAML data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var UnityYAML = function (texture, sourceIndex, yaml) +{ + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + imageHeight = source.height; + + var data = yaml.split('\n'); + + var lineRegExp = /^[ ]*(- )*(\w+)+[: ]+(.*)/; + + var prevSprite = ''; + var currentSprite = ''; + var rect = { x: 0, y: 0, width: 0, height: 0 }; + + // var pivot = { x: 0, y: 0 }; + // var border = { x: 0, y: 0, z: 0, w: 0 }; + + for (var i = 0; i < data.length; i++) + { + var results = data[i].match(lineRegExp); + + if (!results) + { + continue; + } + + var isList = (results[1] === '- '); + var key = results[2]; + var value = results[3]; + + if (isList) + { + if (currentSprite !== prevSprite) + { + addFrame(texture, sourceIndex, currentSprite, rect); + + prevSprite = currentSprite; + } + + rect = { x: 0, y: 0, width: 0, height: 0 }; + } + + if (key === 'name') + { + // Start new list + currentSprite = value; + continue; + } + + switch (key) + { + case 'x': + case 'y': + case 'width': + case 'height': + rect[key] = parseInt(value, 10); + break; + + // case 'pivot': + // pivot = eval('var obj = ' + value); + // break; + + // case 'border': + // border = eval('var obj = ' + value); + // break; + } + } + + if (currentSprite !== prevSprite) + { + addFrame(texture, sourceIndex, currentSprite, rect); + } + + return texture; +}; + +module.exports = UnityYAML; + +/* +Example data: + +TextureImporter: + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + spriteSheet: + sprites: + - name: asteroids_0 + rect: + serializedVersion: 2 + x: 5 + y: 328 + width: 65 + height: 82 + alignment: 0 + pivot: {x: 0, y: 0} + border: {x: 0, y: 0, z: 0, w: 0} + - name: asteroids_1 + rect: + serializedVersion: 2 + x: 80 + y: 322 + width: 53 + height: 88 + alignment: 0 + pivot: {x: 0, y: 0} + border: {x: 0, y: 0, z: 0, w: 0} + spritePackingTag: Asteroids +*/ + + +/***/ }), +/* 914 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Complete Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they complete playback. + * + * Listen to it from a Sound instance using `Sound.on('complete', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('complete', listener); + * music.play(); + * ``` + * + * @event Phaser.Sound.Events#COMPLETE + * @since 3.16.1 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'complete'; + + +/***/ }), +/* 915 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Audio Data Decoded Event. + * + * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method. + * + * Listen to it from the Sound Manager in a Scene using `this.sound.on('decoded', listener)`, i.e.: + * + * ```javascript + * this.sound.on('decoded', handler); + * this.sound.decodeAudio(key, audioData); + * ``` + * + * @event Phaser.Sound.Events#DECODED + * @since 3.18.0 + * + * @param {string} key - The key of the audio file that was decoded and added to the audio cache. + */ +module.exports = 'decoded'; + + +/***/ }), +/* 916 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Audio Data Decoded All Event. + * + * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method, + * once all files passed to the method have been decoded (or errored). + * + * Use `Phaser.Sound.Events#DECODED` to listen for single sounds being decoded, and `DECODED_ALL` to + * listen for them all completing. + * + * Listen to it from the Sound Manager in a Scene using `this.sound.on('decodedall', listener)`, i.e.: + * + * ```javascript + * this.sound.once('decodedall', handler); + * this.sound.decodeAudio([ audioFiles ]); + * ``` + * + * @event Phaser.Sound.Events#DECODED_ALL + * @since 3.18.0 + */ +module.exports = 'decodedall'; + + +/***/ }), +/* 917 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Destroy Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are destroyed, either + * directly or via a Sound Manager. + * + * Listen to it from a Sound instance using `Sound.on('destroy', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('destroy', listener); + * music.destroy(); + * ``` + * + * @event Phaser.Sound.Events#DESTROY + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'destroy'; + + +/***/ }), +/* 918 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Detune Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their detune value changes. + * + * Listen to it from a Sound instance using `Sound.on('detune', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('detune', listener); + * music.play(); + * music.setDetune(200); + * ``` + * + * @event Phaser.Sound.Events#DETUNE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} detune - The new detune value of the Sound. + */ +module.exports = 'detune'; + + +/***/ }), +/* 919 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Detune Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `detune` property of the Sound Manager is changed, which globally + * adjusts the detuning of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('rate', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_DETUNE + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + * @param {number} detune - The updated detune value. + */ +module.exports = 'detune'; + + +/***/ }), +/* 920 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Mute Event. + * + * This event is dispatched by the Sound Manager when its `mute` property is changed, either directly + * or via the `setMute` method. This changes the mute state of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('mute', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the Sound Manager that emitted the event. + * @param {boolean} mute - The mute value. `true` if the Sound Manager is now muted, otherwise `false`. + */ +module.exports = 'mute'; + + +/***/ }), +/* 921 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Rate Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `rate` property of the Sound Manager is changed, which globally + * adjusts the playback rate of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('rate', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_RATE + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + * @param {number} rate - The updated rate value. + */ +module.exports = 'rate'; + + +/***/ }), +/* 922 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Volume Event. + * + * This event is dispatched by the Sound Manager when its `volume` property is changed, either directly + * or via the `setVolume` method. This changes the volume of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('volume', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the sound manager that emitted the event. + * @param {number} volume - The new global volume of the Sound Manager. + */ +module.exports = 'volume'; + + +/***/ }), +/* 923 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Loop Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their loop state is changed. + * + * Listen to it from a Sound instance using `Sound.on('loop', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('loop', listener); + * music.setLoop(true); + * ``` + * + * This is not to be confused with the [LOOPED]{@linkcode Phaser.Sound.Events#event:LOOPED} event, which emits each time a Sound loops during playback. + * + * @event Phaser.Sound.Events#LOOP + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {boolean} loop - The new loop value. `true` if the Sound will loop, otherwise `false`. + */ +module.exports = 'loop'; + + +/***/ }), +/* 924 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Looped Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they loop during playback. + * + * Listen to it from a Sound instance using `Sound.on('looped', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('looped', listener); + * music.setLoop(true); + * music.play(); + * ``` + * + * This is not to be confused with the [LOOP]{@linkcode Phaser.Sound.Events#event:LOOP} event, which only emits when the loop state of a Sound is changed. + * + * @event Phaser.Sound.Events#LOOPED + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'looped'; + + +/***/ }), +/* 925 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Mute Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their mute state changes. + * + * Listen to it from a Sound instance using `Sound.on('mute', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('mute', listener); + * music.play(); + * music.setMute(true); + * ``` + * + * @event Phaser.Sound.Events#MUTE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {boolean} mute - The mute value. `true` if the Sound is now muted, otherwise `false`. + */ +module.exports = 'mute'; + + +/***/ }), +/* 926 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pause All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `pauseAll` method is invoked and after all current Sounds + * have been paused. + * + * Listen to it from a Scene using: `this.sound.on('pauseall', listener)`. + * + * @event Phaser.Sound.Events#PAUSE_ALL + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'pauseall'; + + +/***/ }), +/* 927 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Pause Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are paused. + * + * Listen to it from a Sound instance using `Sound.on('pause', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('pause', listener); + * music.play(); + * music.pause(); + * ``` + * + * @event Phaser.Sound.Events#PAUSE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'pause'; + + +/***/ }), +/* 928 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Play Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are played. + * + * Listen to it from a Sound instance using `Sound.on('play', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('play', listener); + * music.play(); + * ``` + * + * @event Phaser.Sound.Events#PLAY + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'play'; + + +/***/ }), +/* 929 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Rate Change Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their rate changes. + * + * Listen to it from a Sound instance using `Sound.on('rate', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('rate', listener); + * music.play(); + * music.setRate(0.5); + * ``` + * + * @event Phaser.Sound.Events#RATE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} rate - The new rate of the Sound. + */ +module.exports = 'rate'; + + +/***/ }), +/* 930 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Resume All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `resumeAll` method is invoked and after all current Sounds + * have been resumed. + * + * Listen to it from a Scene using: `this.sound.on('resumeall', listener)`. + * + * @event Phaser.Sound.Events#RESUME_ALL + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'resumeall'; + + +/***/ }), +/* 931 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Resume Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are resumed from a paused state. + * + * Listen to it from a Sound instance using `Sound.on('resume', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('resume', listener); + * music.play(); + * music.pause(); + * music.resume(); + * ``` + * + * @event Phaser.Sound.Events#RESUME + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'resume'; + + +/***/ }), +/* 932 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Seek Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are seeked to a new position. + * + * Listen to it from a Sound instance using `Sound.on('seek', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('seek', listener); + * music.play(); + * music.setSeek(5000); + * ``` + * + * @event Phaser.Sound.Events#SEEK + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} detune - The new detune value of the Sound. + */ +module.exports = 'seek'; + + +/***/ }), +/* 933 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Stop All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `stopAll` method is invoked and after all current Sounds + * have been stopped. + * + * Listen to it from a Scene using: `this.sound.on('stopall', listener)`. + * + * @event Phaser.Sound.Events#STOP_ALL + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'stopall'; + + +/***/ }), +/* 934 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Stop Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are stopped. + * + * Listen to it from a Sound instance using `Sound.on('stop', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('stop', listener); + * music.play(); + * music.stop(); + * ``` + * + * @event Phaser.Sound.Events#STOP + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'stop'; + + +/***/ }), +/* 935 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Unlocked Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched during the update loop when the Sound Manager becomes unlocked. For + * Web Audio this is on the first user gesture on the page. + * + * Listen to it from a Scene using: `this.sound.on('unlocked', listener)`. + * + * @event Phaser.Sound.Events#UNLOCKED + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'unlocked'; + + +/***/ }), +/* 936 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Volume Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their volume changes. + * + * Listen to it from a Sound instance using `Sound.on('volume', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('volume', listener); + * music.play(); + * music.setVolume(0.5); + * ``` + * + * @event Phaser.Sound.Events#VOLUME + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} volume - The new volume of the Sound. + */ +module.exports = 'volume'; + + +/***/ }), +/* 937 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * @typedef {object} AdInstance + * + * @property {any} instance - Represents an instance of an ad. + * @property {string} placementID - The Audience Network placement ID of this ad instance. + * @property {boolean} shown - Has this ad already been shown in-game? + * @property {boolean} video - Is this a video ad? + */ + +var AdInstance = function (placementID, instance, video) +{ + return { + instance: instance, + placementID: placementID, + shown: false, + video: video + }; +}; + +module.exports = AdInstance; + + +/***/ }), +/* 938 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var LeaderboardScore = __webpack_require__(939); + +/** + * @classdesc + * This class represents one single Leaderboard that belongs to a Facebook Instant Game. + * + * You do not need to instantiate this class directly, it will be created when you use the + * `getLeaderboard()` method of the main plugin. + * + * @class FacebookInstantGamesLeaderboard + * @memberOf Phaser + * @constructor + * @extends Phaser.Events.EventEmitter + * @since 3.13.0 + * + * @param {Phaser.FacebookInstantGamesPlugin} plugin - A reference to the Facebook Instant Games Plugin. + * @param {any} data - An Instant Game leaderboard instance. + */ +var Leaderboard = new Class({ + + Extends: EventEmitter, + + initialize: + + function Leaderboard (plugin, data) + { + EventEmitter.call(this); + + /** + * A reference to the Facebook Instant Games Plugin. + * + * @name Phaser.FacebookInstantGamesLeaderboard#plugin + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.13.0 + */ + this.plugin = plugin; + + /** + * An Instant Game leaderboard instance. + * + * @name Phaser.FacebookInstantGamesLeaderboard#ref + * @type {any} + * @since 3.13.0 + */ + this.ref = data; + + /** + * The name of the leaderboard. + * + * @name Phaser.FacebookInstantGamesLeaderboard#name + * @type {string} + * @since 3.13.0 + */ + this.name = data.getName(); + + /** + * The ID of the context that the leaderboard is associated with, or null if the leaderboard is not tied to a particular context. + * + * @name Phaser.FacebookInstantGamesLeaderboard#contextID + * @type {string} + * @since 3.13.0 + */ + this.contextID = data.getContextID(); + + /** + * The total number of player entries in the leaderboard. + * This value defaults to zero. Populate it via the `getEntryCount()` method. + * + * @name Phaser.FacebookInstantGamesLeaderboard#entryCount + * @type {integer} + * @since 3.13.0 + */ + this.entryCount = 0; + + /** + * The players score object. + * This value defaults to `null`. Populate it via the `getPlayerScore()` method. + * + * @name Phaser.FacebookInstantGamesLeaderboard#playerScore + * @type {LeaderboardScore} + * @since 3.13.0 + */ + this.playerScore = null; + + /** + * The scores in the Leaderboard from the currently requested range. + * This value defaults to an empty array. Populate it via the `getScores()` method. + * The contents of this array are reset each time `getScores()` is called. + * + * @name Phaser.FacebookInstantGamesLeaderboard#scores + * @type {LeaderboardScore[]} + * @since 3.13.0 + */ + this.scores = []; + + this.getEntryCount(); + }, + + /** + * Fetches the total number of player entries in the leaderboard. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getentrycount` event along with the count and name of the Leaderboard. + * + * @method Phaser.FacebookInstantGamesLeaderboard#getEntryCount + * @since 3.13.0 + * + * @return {this} This Leaderboard instance. + */ + getEntryCount: function () + { + var _this = this; + + this.ref.getEntryCountAsync().then(function (count) + { + _this.entryCount = count; + + _this.emit('getentrycount', count, _this.name); + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + }, + + /** + * Updates the player's score. If the player has an existing score, the old score will only be replaced if the new score is better than it. + * NOTE: If the leaderboard is associated with a specific context, the game must be in that context to set a score for the player. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `setscore` event along with the LeaderboardScore object and the name of the Leaderboard. + * + * If the save fails the event will send `null` as the score value. + * + * @method Phaser.FacebookInstantGamesLeaderboard#setScore + * @since 3.13.0 + * + * @param {integer} score - The new score for the player. Must be a 64-bit integer number. + * @param {(string|any)} [data] - Metadata to associate with the stored score. Must be less than 2KB in size. If an object is given it will be passed to `JSON.stringify`. + * + * @return {this} This Leaderboard instance. + */ + setScore: function (score, data) + { + if (data === undefined) { data = ''; } + + if (typeof data === 'object') + { + data = JSON.stringify(data); + } + + var _this = this; + + this.ref.setScoreAsync(score, data).then(function (entry) + { + if (entry) + { + var score = LeaderboardScore(entry); + + _this.playerScore = score; + + _this.emit('setscore', score, _this.name); + } + else + { + _this.emit('setscore', null, _this.name); + } + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + }, + + /** + * Gets the players leaderboard entry and stores it in the `playerScore` property. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getplayerscore` event along with the score and the name of the Leaderboard. + * + * If the player has not yet saved a score, the event will send `null` as the score value, and `playerScore` will be set to `null` as well. + * + * @method Phaser.FacebookInstantGamesLeaderboard#getPlayerScore + * @since 3.13.0 + * + * @return {this} This Leaderboard instance. + */ + getPlayerScore: function () + { + var _this = this; + + this.ref.getPlayerEntryAsync().then(function (entry) + { + if (entry) + { + var score = LeaderboardScore(entry); + + _this.playerScore = score; + + _this.emit('getplayerscore', score, _this.name); + } + else + { + _this.emit('getplayerscore', null, _this.name); + } + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + }, + + /** + * Retrieves a set of leaderboard entries, ordered by score ranking in the leaderboard. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getscores` event along with an array of LeaderboardScore entries and the name of the Leaderboard. + * + * @method Phaser.FacebookInstantGamesLeaderboard#getScores + * @since 3.13.0 + * + * @param {integer} [count=10] - The number of entries to attempt to fetch from the leaderboard. Currently, up to a maximum of 100 entries may be fetched per query. + * @param {integer} [offset=0] - The offset from the top of the leaderboard that entries will be fetched from. + * + * @return {this} This Leaderboard instance. + */ + getScores: function (count, offset) + { + if (count === undefined) { count = 10; } + if (offset === undefined) { offset = 0; } + + var _this = this; + + this.ref.getEntriesAsync(count, offset).then(function (entries) + { + _this.scores = []; + + entries.forEach(function (entry) + { + _this.scores.push(LeaderboardScore(entry)); + }); + + _this.emit('getscores', _this.scores, _this.name); + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + }, + + /** + * Retrieves a set of leaderboard entries, based on the current player's connected players (including the current player), ordered by local rank within the set of connected players. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getconnectedscores` event along with an array of LeaderboardScore entries and the name of the Leaderboard. + * + * @method Phaser.FacebookInstantGamesLeaderboard#getConnectedScores + * @since 3.16.0 + * + * @return {this} This Leaderboard instance. + */ + getConnectedScores: function () + { + var _this = this; + + this.ref.getConnectedPlayerEntriesAsync().then(function (entries) + { + _this.scores = []; + + entries.forEach(function (entry) + { + _this.scores.push(LeaderboardScore(entry)); + }); + + _this.emit('getconnectedscores', _this.scores, _this.name); + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + } + +}); + +module.exports = Leaderboard; + + +/***/ }), +/* 939 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * @typedef {object} LeaderboardScore + * + * @property {integer} score - An integer score value. + * @property {string} scoreFormatted - The score value, formatted with the score format associated with the leaderboard. + * @property {integer} timestamp - The Unix timestamp of when the leaderboard entry was last updated. + * @property {integer} rank - The entry's leaderboard ranking. + * @property {string} data - The developer-specified payload associated with the score, or null if one was not set. + * @property {string} playerName - The player's localized display name. + * @property {string} playerPhotoURL - A url to the player's public profile photo. + * @property {string} playerID - The game's unique identifier for the player. + */ + +var LeaderboardScore = function (entry) +{ + return { + score: entry.getScore(), + scoreFormatted: entry.getFormattedScore(), + timestamp: entry.getTimestamp(), + rank: entry.getRank(), + data: entry.getExtraData(), + playerName: entry.getPlayer().getName(), + playerPhotoURL: entry.getPlayer().getPhoto(), + playerID: entry.getPlayer().getID() + }; +}; + +module.exports = LeaderboardScore; + + +/***/ }), +/* 940 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * @typedef {object} Product + * + * @property {string} [title] - The title of the product. + * @property {string} [productID] - The product's game-specified identifier. + * @property {string} [description] - The product description. + * @property {string} [imageURI] - A link to the product's associated image. + * @property {string} [price] - The price of the product. + * @property {string} [priceCurrencyCode] - The currency code for the product. + */ + +var Product = function (data) +{ + return { + title: GetFastValue(data, 'title', ''), + productID: GetFastValue(data, 'productID', ''), + description: GetFastValue(data, 'description', ''), + imageURI: GetFastValue(data, 'imageURI', ''), + price: GetFastValue(data, 'price', ''), + priceCurrencyCode: GetFastValue(data, 'priceCurrencyCode', '') + }; +}; + +module.exports = Product; + + +/***/ }), +/* 941 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var GetFastValue = __webpack_require__(1); + +/** + * @typedef {object} Purchase + * + * @property {string} [developerPayload] - A developer-specified string, provided during the purchase of the product. + * @property {string} [paymentID] - The identifier for the purchase transaction. + * @property {string} [productID] - The product's game-specified identifier. + * @property {string} [purchaseTime] - Unix timestamp of when the purchase occurred. + * @property {string} [purchaseToken] - A token representing the purchase that may be used to consume the purchase. + * @property {string} [signedRequest] - Server-signed encoding of the purchase request. + */ + +var Purchase = function (data) +{ + return { + developerPayload: GetFastValue(data, 'developerPayload', ''), + paymentID: GetFastValue(data, 'paymentID', ''), + productID: GetFastValue(data, 'productID', ''), + purchaseTime: GetFastValue(data, 'purchaseTime', ''), + purchaseToken: GetFastValue(data, 'purchaseToken', ''), + signedRequest: GetFastValue(data, 'signedRequest', '') + }; +}; + +module.exports = Purchase; + + +/***/ }), +/* 942 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects + */ + +var GameObjects = { + + Events: __webpack_require__(102), + + DisplayList: __webpack_require__(943), + GameObjectCreator: __webpack_require__(16), + GameObjectFactory: __webpack_require__(6), + UpdateList: __webpack_require__(971), + + Components: __webpack_require__(12), + + BuildGameObject: __webpack_require__(30), + BuildGameObjectAnimation: __webpack_require__(416), + GameObject: __webpack_require__(14), + BitmapText: __webpack_require__(138), + Blitter: __webpack_require__(201), + Container: __webpack_require__(202), + DOMElement: __webpack_require__(418), + DynamicBitmapText: __webpack_require__(203), + Extern: __webpack_require__(420), + Graphics: __webpack_require__(204), + Group: __webpack_require__(109), + Image: __webpack_require__(89), + Particles: __webpack_require__(1003), + PathFollower: __webpack_require__(432), + RenderTexture: __webpack_require__(208), + RetroFont: __webpack_require__(1012), + Sprite: __webpack_require__(65), + Text: __webpack_require__(210), + TileSprite: __webpack_require__(211), + Zone: __webpack_require__(118), + Video: __webpack_require__(212), + + // Shapes + + Shape: __webpack_require__(33), + Arc: __webpack_require__(433), + Curve: __webpack_require__(434), + Ellipse: __webpack_require__(435), + Grid: __webpack_require__(436), + IsoBox: __webpack_require__(437), + IsoTriangle: __webpack_require__(438), + Line: __webpack_require__(439), + Polygon: __webpack_require__(440), + Rectangle: __webpack_require__(445), + Star: __webpack_require__(446), + Triangle: __webpack_require__(447), + + // Game Object Factories + + Factories: { + Blitter: __webpack_require__(1060), + Container: __webpack_require__(1061), + DOMElement: __webpack_require__(1062), + DynamicBitmapText: __webpack_require__(1063), + Extern: __webpack_require__(1064), + Graphics: __webpack_require__(1065), + Group: __webpack_require__(1066), + Image: __webpack_require__(1067), + Particles: __webpack_require__(1068), + PathFollower: __webpack_require__(1069), + RenderTexture: __webpack_require__(1070), + Sprite: __webpack_require__(1071), + StaticBitmapText: __webpack_require__(1072), + Text: __webpack_require__(1073), + TileSprite: __webpack_require__(1074), + Zone: __webpack_require__(1075), + Video: __webpack_require__(1076), + + // Shapes + Arc: __webpack_require__(1077), + Curve: __webpack_require__(1078), + Ellipse: __webpack_require__(1079), + Grid: __webpack_require__(1080), + IsoBox: __webpack_require__(1081), + IsoTriangle: __webpack_require__(1082), + Line: __webpack_require__(1083), + Polygon: __webpack_require__(1084), + Rectangle: __webpack_require__(1085), + Star: __webpack_require__(1086), + Triangle: __webpack_require__(1087) + }, + + Creators: { + Blitter: __webpack_require__(1088), + Container: __webpack_require__(1089), + DynamicBitmapText: __webpack_require__(1090), + Graphics: __webpack_require__(1091), + Group: __webpack_require__(1092), + Image: __webpack_require__(1093), + Particles: __webpack_require__(1094), + RenderTexture: __webpack_require__(1095), + Sprite: __webpack_require__(1096), + StaticBitmapText: __webpack_require__(1097), + Text: __webpack_require__(1098), + TileSprite: __webpack_require__(1099), + Zone: __webpack_require__(1100), + Video: __webpack_require__(1101) + } + +}; + +if (true) +{ + // WebGL only Game Objects + GameObjects.Mesh = __webpack_require__(139); + GameObjects.Quad = __webpack_require__(215); + GameObjects.Shader = __webpack_require__(216); + + GameObjects.Factories.Mesh = __webpack_require__(1108); + GameObjects.Factories.Quad = __webpack_require__(1109); + GameObjects.Factories.Shader = __webpack_require__(1110); + + GameObjects.Creators.Mesh = __webpack_require__(1111); + GameObjects.Creators.Quad = __webpack_require__(1112); + GameObjects.Creators.Shader = __webpack_require__(1113); + + GameObjects.Light = __webpack_require__(451); + + __webpack_require__(452); + __webpack_require__(1114); +} + +module.exports = GameObjects; + + +/***/ }), +/* 943 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var List = __webpack_require__(135); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); +var StableSort = __webpack_require__(137); + +/** + * @classdesc + * The Display List plugin. + * + * Display Lists belong to a Scene and maintain the list of Game Objects to render every frame. + * + * Some of these Game Objects may also be part of the Scene's [Update List]{@link Phaser.GameObjects.UpdateList}, for updating. + * + * @class DisplayList + * @extends Phaser.Structs.List. + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this Display List belongs to. + */ +var DisplayList = new Class({ + + Extends: List, + + initialize: + + function DisplayList (scene) + { + List.call(this, scene); + + /** + * The flag the determines whether Game Objects should be sorted when `depthSort()` is called. + * + * @name Phaser.GameObjects.DisplayList#sortChildrenFlag + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.sortChildrenFlag = false; + + /** + * The Scene that this Display List belongs to. + * + * @name Phaser.GameObjects.DisplayList#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene's Systems. + * + * @name Phaser.GameObjects.DisplayList#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.DisplayList#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.DisplayList#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Force a sort of the display list on the next call to depthSort. + * + * @method Phaser.GameObjects.DisplayList#queueDepthSort + * @since 3.0.0 + */ + queueDepthSort: function () + { + this.sortChildrenFlag = true; + }, + + /** + * Immediately sorts the display list if the flag is set. + * + * @method Phaser.GameObjects.DisplayList#depthSort + * @since 3.0.0 + */ + depthSort: function () + { + if (this.sortChildrenFlag) + { + StableSort.inplace(this.list, this.sortByDepth); + + this.sortChildrenFlag = false; + } + }, + + /** + * Compare the depth of two Game Objects. + * + * @method Phaser.GameObjects.DisplayList#sortByDepth + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} childA - The first Game Object. + * @param {Phaser.GameObjects.GameObject} childB - The second Game Object. + * + * @return {integer} The difference between the depths of each Game Object. + */ + sortByDepth: function (childA, childB) + { + return childA._depth - childB._depth; + }, + + /** + * Returns an array which contains all objects currently on the Display List. + * This is a reference to the main list array, not a copy of it, so be careful not to modify it. + * + * @method Phaser.GameObjects.DisplayList#getChildren + * @since 3.12.0 + * + * @return {Phaser.GameObjects.GameObject[]} The group members. + */ + getChildren: function () + { + return this.list; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.DisplayList#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var i = this.list.length; + + while (i--) + { + this.list[i].destroy(true); + } + + this.list.length = 0; + + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.DisplayList#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('DisplayList', DisplayList, 'displayList'); + +module.exports = DisplayList; + + +/***/ }), +/* 944 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Array.Matrix + */ + +module.exports = { + + CheckMatrix: __webpack_require__(197), + MatrixToString: __webpack_require__(945), + ReverseColumns: __webpack_require__(946), + ReverseRows: __webpack_require__(947), + Rotate180: __webpack_require__(948), + RotateLeft: __webpack_require__(949), + RotateMatrix: __webpack_require__(136), + RotateRight: __webpack_require__(950), + TransposeMatrix: __webpack_require__(413) + +}; + + +/***/ }), +/* 945 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Pad = __webpack_require__(173); +var CheckMatrix = __webpack_require__(197); + +/** + * Generates a string (which you can pass to console.log) from the given Array Matrix. + * + * @function Phaser.Utils.Array.Matrix.MatrixToString + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix] + * + * @param {T[][]} [matrix] - A 2-dimensional array. + * + * @return {string} A string representing the matrix. + */ +var MatrixToString = function (matrix) +{ + var str = ''; + + if (!CheckMatrix(matrix)) + { + return str; + } + + for (var r = 0; r < matrix.length; r++) + { + for (var c = 0; c < matrix[r].length; c++) + { + var cell = matrix[r][c].toString(); + + if (cell !== 'undefined') + { + str += Pad(cell, 2); + } + else + { + str += '?'; + } + + if (c < matrix[r].length - 1) + { + str += ' |'; + } + } + + if (r < matrix.length - 1) + { + str += '\n'; + + for (var i = 0; i < matrix[r].length; i++) + { + str += '---'; + + if (i < matrix[r].length - 1) + { + str += '+'; + } + } + + str += '\n'; + } + + } + + return str; +}; + +module.exports = MatrixToString; + + +/***/ }), +/* 946 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Reverses the columns in the given Array Matrix. + * + * @function Phaser.Utils.Array.Matrix.ReverseColumns + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array matrix to reverse the columns for. + * + * @return {T[][]} The column reversed matrix. + */ +var ReverseColumns = function (matrix) +{ + return matrix.reverse(); +}; + +module.exports = ReverseColumns; + + +/***/ }), +/* 947 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Reverses the rows in the given Array Matrix. + * + * @function Phaser.Utils.Array.Matrix.ReverseRows + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array matrix to reverse the rows for. + * + * @return {T[][]} The column reversed matrix. + */ +var ReverseRows = function (matrix) +{ + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + return matrix; +}; + +module.exports = ReverseRows; + + +/***/ }), +/* 948 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateMatrix = __webpack_require__(136); + +/** + * Rotates the array matrix 180 degrees. + * + * @function Phaser.Utils.Array.Matrix.Rotate180 + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array to rotate. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var Rotate180 = function (matrix) +{ + return RotateMatrix(matrix, 180); +}; + +module.exports = Rotate180; + + +/***/ }), +/* 949 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateMatrix = __webpack_require__(136); + +/** + * Rotates the array matrix to the left (or 90 degrees) + * + * @function Phaser.Utils.Array.Matrix.RotateLeft + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array to rotate. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var RotateLeft = function (matrix) +{ + return RotateMatrix(matrix, 90); +}; + +module.exports = RotateLeft; + + +/***/ }), +/* 950 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateMatrix = __webpack_require__(136); + +/** + * Rotates the array matrix to the left (or -90 degrees) + * + * @function Phaser.Utils.Array.Matrix.RotateRight + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array to rotate. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var RotateRight = function (matrix) +{ + return RotateMatrix(matrix, -90); +}; + +module.exports = RotateRight; + + +/***/ }), +/* 951 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds the given item, or array of items, to the array. + * + * Each item must be unique within the array. + * + * The array is modified in-place and returned. + * + * You can optionally specify a limit to the maximum size of the array. If the quantity of items being + * added will take the array length over this limit, it will stop adding once the limit is reached. + * + * You can optionally specify a callback to be invoked for each item successfully added to the array. + * + * @function Phaser.Utils.Array.Add + * @since 3.4.0 + * + * @param {array} array - The array to be added to. + * @param {any|any[]} item - The item, or array of items, to add to the array. Each item must be unique within the array. + * @param {integer} [limit] - Optional limit which caps the size of the array. + * @param {function} [callback] - A callback to be invoked for each item successfully added to the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {array} The input array. + */ +var Add = function (array, item, limit, callback, context) +{ + if (context === undefined) { context = array; } + + if (limit > 0) + { + var remaining = limit - array.length; + + // There's nothing more we can do here, the array is full + if (remaining <= 0) + { + return null; + } + } + + // Fast path to avoid array mutation and iteration + if (!Array.isArray(item)) + { + if (array.indexOf(item) === -1) + { + array.push(item); + + if (callback) + { + callback.call(context, item); + } + + return item; + } + else + { + return null; + } + } + + // If we got this far, we have an array of items to insert + + // Ensure all the items are unique + var itemLength = item.length - 1; + + while (itemLength >= 0) + { + if (array.indexOf(item[itemLength]) !== -1) + { + // Already exists in array, so remove it + item.splice(itemLength, 1); + } + + itemLength--; + } + + // Anything left? + itemLength = item.length; + + if (itemLength === 0) + { + return null; + } + + if (limit > 0 && itemLength > remaining) + { + item.splice(remaining); + + itemLength = remaining; + } + + for (var i = 0; i < itemLength; i++) + { + var entry = item[i]; + + array.push(entry); + + if (callback) + { + callback.call(context, entry); + } + } + + return item; +}; + +module.exports = Add; + + +/***/ }), +/* 952 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds the given item, or array of items, to the array starting at the index specified. + * + * Each item must be unique within the array. + * + * Existing elements in the array are shifted up. + * + * The array is modified in-place and returned. + * + * You can optionally specify a limit to the maximum size of the array. If the quantity of items being + * added will take the array length over this limit, it will stop adding once the limit is reached. + * + * You can optionally specify a callback to be invoked for each item successfully added to the array. + * + * @function Phaser.Utils.Array.AddAt + * @since 3.4.0 + * + * @param {array} array - The array to be added to. + * @param {any|any[]} item - The item, or array of items, to add to the array. + * @param {integer} [index=0] - The index in the array where the item will be inserted. + * @param {integer} [limit] - Optional limit which caps the size of the array. + * @param {function} [callback] - A callback to be invoked for each item successfully added to the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {array} The input array. + */ +var AddAt = function (array, item, index, limit, callback, context) +{ + if (index === undefined) { index = 0; } + if (context === undefined) { context = array; } + + if (limit > 0) + { + var remaining = limit - array.length; + + // There's nothing more we can do here, the array is full + if (remaining <= 0) + { + return null; + } + } + + // Fast path to avoid array mutation and iteration + if (!Array.isArray(item)) + { + if (array.indexOf(item) === -1) + { + array.splice(index, 0, item); + + if (callback) + { + callback.call(context, item); + } + + return item; + } + else + { + return null; + } + } + + // If we got this far, we have an array of items to insert + + // Ensure all the items are unique + var itemLength = item.length - 1; + + while (itemLength >= 0) + { + if (array.indexOf(item[itemLength]) !== -1) + { + // Already exists in array, so remove it + item.pop(); + } + + itemLength--; + } + + // Anything left? + itemLength = item.length; + + if (itemLength === 0) + { + return null; + } + + // Truncate to the limit + if (limit > 0 && itemLength > remaining) + { + item.splice(remaining); + + itemLength = remaining; + } + + for (var i = itemLength - 1; i >= 0; i--) + { + var entry = item[i]; + + array.splice(index, 0, entry); + + if (callback) + { + callback.call(context, entry); + } + } + + return item; +}; + +module.exports = AddAt; + + +/***/ }), +/* 953 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given element to the top of the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.BringToTop + * @since 3.4.0 + * + * @param {array} array - The array. + * @param {*} item - The element to move. + * + * @return {*} The element that was moved. + */ +var BringToTop = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex !== -1 && currentIndex < array.length) + { + array.splice(currentIndex, 1); + array.push(item); + } + + return item; +}; + +module.exports = BringToTop; + + +/***/ }), +/* 954 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = __webpack_require__(74); + +/** + * Returns the total number of elements in the array which have a property matching the given value. + * + * @function Phaser.Utils.Array.CountAllMatching + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @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 {integer} [startIndex] - An optional start index to search from. + * @param {integer} [endIndex] - An optional end index to search to. + * + * @return {integer} The total number of elements with properties matching the given value. + */ +var CountAllMatching = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + var total = 0; + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var child = array[i]; + + if (child[property] === value) + { + total++; + } + } + } + + return total; +}; + +module.exports = CountAllMatching; + + +/***/ }), +/* 955 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Passes each element in the array to the given callback. + * + * @function Phaser.Utils.Array.Each + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @param {function} callback - A callback to be invoked for each item in the array. + * @param {object} context - The context in which the callback is invoked. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the current array item. + * + * @return {array} The input array. + */ +var Each = function (array, callback, context) +{ + var i; + var args = [ null ]; + + for (i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < array.length; i++) + { + args[0] = array[i]; + + callback.apply(context, args); + } + + return array; +}; + +module.exports = Each; + + +/***/ }), +/* 956 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = __webpack_require__(74); + +/** + * Passes each element in the array, between the start and end indexes, to the given callback. + * + * @function Phaser.Utils.Array.EachInRange + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @param {function} callback - A callback to be invoked for each item in the array. + * @param {object} context - The context in which the callback is invoked. + * @param {integer} startIndex - The start index to search from. + * @param {integer} endIndex - The end index to search to. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {array} The input array. + */ +var EachInRange = function (array, callback, context, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + if (SafeRange(array, startIndex, endIndex)) + { + var i; + var args = [ null ]; + + for (i = 5; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = startIndex; i < endIndex; i++) + { + args[0] = array[i]; + + callback.apply(context, args); + } + } + + return array; +}; + +module.exports = EachInRange; + + +/***/ }), +/* 957 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = __webpack_require__(74); + +/** + * Returns all elements in the array. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('visible', true)` would return only elements that have their visible property set. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 elements. + * + * @function Phaser.Utils.Array.GetAll + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @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 {integer} [startIndex] - An optional start index to search from. + * @param {integer} [endIndex] - An optional end index to search to. + * + * @return {array} All matching elements from the array. + */ +var GetAll = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + var output = []; + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var child = array[i]; + + if (!property || + (property && value === undefined && child.hasOwnProperty(property)) || + (property && value !== undefined && child[property] === value)) + { + output.push(child); + } + } + } + + return output; +}; + +module.exports = GetAll; + + +/***/ }), +/* 958 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = __webpack_require__(74); + +/** + * Returns the first element in the array. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('visible', true)` would return the first element that had its `visible` property set. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would search only the first 50 elements. + * + * @function Phaser.Utils.Array.GetFirst + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @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 {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=array.length] - An optional end index to search up to (but not included) + * + * @return {object} The first matching element from the array, or `null` if no element could be found in the range given. + */ +var GetFirst = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var child = array[i]; + + if (!property || + (property && value === undefined && child.hasOwnProperty(property)) || + (property && value !== undefined && child[property] === value)) + { + return child; + } + } + } + + return null; +}; + +module.exports = GetFirst; + + +/***/ }), +/* 959 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given array element down one place in the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.MoveDown + * @since 3.4.0 + * + * @param {array} array - The input array. + * @param {*} item - The element to move down the array. + * + * @return {array} The input array. + */ +var MoveDown = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex > 0) + { + var item2 = array[currentIndex - 1]; + + var index2 = array.indexOf(item2); + + array[currentIndex] = item2; + array[index2] = item; + } + + return array; +}; + +module.exports = MoveDown; + + +/***/ }), +/* 960 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves an element in an array to a new position within the same array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.MoveTo + * @since 3.4.0 + * + * @param {array} array - The array. + * @param {*} item - The element to move. + * @param {integer} index - The new index that the element will be moved to. + * + * @return {*} The element that was moved. + */ +var MoveTo = function (array, item, index) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex === -1 || index < 0 || index >= array.length) + { + throw new Error('Supplied index out of bounds'); + } + + if (currentIndex !== index) + { + // Remove + array.splice(currentIndex, 1); + + // Add in new location + array.splice(index, 0, item); + } + + return item; +}; + +module.exports = MoveTo; + + +/***/ }), +/* 961 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given array element up one place in the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.MoveUp + * @since 3.4.0 + * + * @param {array} array - The input array. + * @param {*} item - The element to move up the array. + * + * @return {array} The input array. + */ +var MoveUp = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex !== -1 && currentIndex < array.length - 1) + { + // The element one above `item` in the array + var item2 = array[currentIndex + 1]; + var index2 = array.indexOf(item2); + + array[currentIndex] = item2; + array[index2] = item; + } + + return array; +}; + +module.exports = MoveUp; + + +/***/ }), +/* 962 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Create an array representing the range of numbers (usually integers), between, and inclusive of, + * the given `start` and `end` arguments. For example: + * + * `var array = numberArray(2, 4); // array = [2, 3, 4]` + * `var array = numberArray(0, 9); // array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` + * + * This is equivalent to `numberArrayStep(start, end, 1)`. + * + * You can optionally provide a prefix and / or suffix string. If given the array will contain + * strings, not integers. For example: + * + * `var array = numberArray(1, 4, 'Level '); // array = ["Level 1", "Level 2", "Level 3", "Level 4"]` + * `var array = numberArray(5, 7, 'HD-', '.png'); // array = ["HD-5.png", "HD-6.png", "HD-7.png"]` + * + * @function Phaser.Utils.Array.NumberArray + * @since 3.0.0 + * + * @param {number} start - The minimum value the array starts with. + * @param {number} end - The maximum value the array contains. + * @param {string} [prefix] - Optional prefix to place before the number. If provided the array will contain strings, not integers. + * @param {string} [suffix] - Optional suffix to place after the number. If provided the array will contain strings, not integers. + * + * @return {(number[]|string[])} The array of number values, or strings if a prefix or suffix was provided. + */ +var NumberArray = function (start, end, prefix, suffix) +{ + var result = []; + + for (var i = start; i <= end; i++) + { + if (prefix || suffix) + { + var key = (prefix) ? prefix + i.toString() : i.toString(); + + if (suffix) + { + key = key.concat(suffix); + } + + result.push(key); + } + else + { + result.push(i); + } + } + + return result; +}; + +module.exports = NumberArray; + + +/***/ }), +/* 963 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RoundAwayFromZero = __webpack_require__(350); + +/** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @example + * NumberArrayStep(4); + * // => [0, 1, 2, 3] + * + * NumberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * NumberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * NumberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * NumberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * NumberArrayStep(0); + * // => [] + * + * @function Phaser.Utils.Array.NumberArrayStep + * @since 3.0.0 + * + * @param {number} [start=0] - The start of the range. + * @param {number} [end=null] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * + * @return {number[]} The array of number values. + */ +var NumberArrayStep = function (start, end, step) +{ + if (start === undefined) { start = 0; } + if (end === undefined) { end = null; } + if (step === undefined) { step = 1; } + + if (end === null) + { + end = start; + start = 0; + } + + var result = []; + + var total = Math.max(RoundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; +}; + +module.exports = NumberArrayStep; + + +/***/ }), +/* 964 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SpliceOne = __webpack_require__(85); + +/** + * Removes the item from the given position in the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for the item if it is successfully removed from the array. + * + * @function Phaser.Utils.Array.RemoveAt + * @since 3.4.0 + * + * @param {array} array - The array to be modified. + * @param {integer} index - The array index to remove the item from. The index must be in bounds or it will throw an error. + * @param {function} [callback] - A callback to be invoked for the item removed from the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {*} The item that was removed. + */ +var RemoveAt = function (array, index, callback, context) +{ + if (context === undefined) { context = array; } + + if (index < 0 || index > array.length - 1) + { + throw new Error('Index out of bounds'); + } + + var item = SpliceOne(array, index); + + if (callback) + { + callback.call(context, item); + } + + return item; +}; + +module.exports = RemoveAt; + + +/***/ }), +/* 965 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = __webpack_require__(74); + +/** + * Removes the item within the given range in the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for the item/s successfully removed from the array. + * + * @function Phaser.Utils.Array.RemoveBetween + * @since 3.4.0 + * + * @param {array} array - The array to be modified. + * @param {integer} startIndex - The start index to remove from. + * @param {integer} endIndex - The end index to remove to. + * @param {function} [callback] - A callback to be invoked for the item removed from the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {Array.<*>} An array of items that were removed. + */ +var RemoveBetween = function (array, startIndex, endIndex, callback, context) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + if (context === undefined) { context = array; } + + if (SafeRange(array, startIndex, endIndex)) + { + var size = endIndex - startIndex; + + var removed = array.splice(startIndex, size); + + if (callback) + { + for (var i = 0; i < removed.length; i++) + { + var entry = removed[i]; + + callback.call(context, entry); + } + } + + return removed; + } + else + { + return []; + } +}; + +module.exports = RemoveBetween; + + +/***/ }), +/* 966 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SpliceOne = __webpack_require__(85); + +/** + * Removes a random object from the given array and returns it. + * Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. + * + * @function Phaser.Utils.Array.RemoveRandomElement + * @since 3.0.0 + * + * @param {array} array - The array to removed a random element from. + * @param {integer} [start=0] - The array index to start the search from. + * @param {integer} [length=array.length] - Optional restriction on the number of elements to randomly select from. + * + * @return {object} The random element that was removed, or `null` if there were no array elements that fell within the given range. + */ +var RemoveRandomElement = function (array, start, length) +{ + if (start === undefined) { start = 0; } + if (length === undefined) { length = array.length; } + + var randomIndex = start + Math.floor(Math.random() * length); + + return SpliceOne(array, randomIndex); +}; + +module.exports = RemoveRandomElement; + + +/***/ }), +/* 967 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Replaces an element of the array with the new element. + * The new element cannot already be a member of the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.Replace + * @since 3.4.0 + * + * @param {array} array - The array to search within. + * @param {*} oldChild - The element in the array that will be replaced. + * @param {*} newChild - The element to be inserted into the array at the position of `oldChild`. + * + * @return {boolean} Returns true if the oldChild was successfully replaced, otherwise returns false. + */ +var Replace = function (array, oldChild, newChild) +{ + var index1 = array.indexOf(oldChild); + var index2 = array.indexOf(newChild); + + if (index1 !== -1 && index2 === -1) + { + array[index1] = newChild; + + return true; + } + else + { + return false; + } +}; + +module.exports = Replace; + + +/***/ }), +/* 968 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given element to the bottom of the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.SendToBack + * @since 3.4.0 + * + * @param {array} array - The array. + * @param {*} item - The element to move. + * + * @return {*} The element that was moved. + */ +var SendToBack = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex !== -1 && currentIndex > 0) + { + array.splice(currentIndex, 1); + array.unshift(item); + } + + return item; +}; + +module.exports = SendToBack; + + +/***/ }), +/* 969 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = __webpack_require__(74); + +/** + * Scans the array for elements with the given property. If found, the property is set to the `value`. + * + * For example: `SetAll('visible', true)` would set all elements that have a `visible` property to `false`. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would update only the first 50 elements. + * + * @function Phaser.Utils.Array.SetAll + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @param {string} property - The property to test for on each array element. + * @param {*} value - The value to set the property to. + * @param {integer} [startIndex] - An optional start index to search from. + * @param {integer} [endIndex] - An optional end index to search to. + * + * @return {array} The input array. + */ +var SetAll = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var entry = array[i]; + + if (entry.hasOwnProperty(property)) + { + entry[property] = value; + } + } + } + + return array; +}; + +module.exports = SetAll; + + +/***/ }), +/* 970 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Swaps the position of two elements in the given array. + * The elements must exist in the same array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.Swap + * @since 3.4.0 + * + * @param {array} array - The input array. + * @param {*} item1 - The first element to swap. + * @param {*} item2 - The second element to swap. + * + * @return {array} The input array. + */ +var Swap = function (array, item1, item2) +{ + if (item1 === item2) + { + return; + } + + var index1 = array.indexOf(item1); + var index2 = array.indexOf(item2); + + if (index1 < 0 || index2 < 0) + { + throw new Error('Supplied items must be elements of the same array'); + } + + array[index1] = item2; + array[index2] = item1; + + return array; +}; + +module.exports = Swap; + + +/***/ }), +/* 971 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var ProcessQueue = __webpack_require__(199); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * The Update List plugin. + * + * Update Lists belong to a Scene and maintain the list Game Objects to be updated every frame. + * + * Some or all of these Game Objects may also be part of the Scene's [Display List]{@link Phaser.GameObjects.DisplayList}, for Rendering. + * + * @class UpdateList + * @extends Phaser.Structs.ProcessQueue. + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that the Update List belongs to. + */ +var UpdateList = new Class({ + + Extends: ProcessQueue, + + initialize: + + function UpdateList (scene) + { + ProcessQueue.call(this); + + /** + * The Scene that the Update List belongs to. + * + * @name Phaser.GameObjects.UpdateList#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene's Systems. + * + * @name Phaser.GameObjects.UpdateList#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * + * @name Phaser.GameObjects.UpdateList#_pending + * @type {Array.<*>} + * @private + * @default [] + * @since 3.20.0 + */ + + /** + * The `active` list is a selection of items which are considered active and should be updated. + * + * @name Phaser.GameObjects.UpdateList#_active + * @type {Array.<*>} + * @private + * @default [] + * @since 3.20.0 + */ + + /** + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * @name Phaser.GameObjects.UpdateList#_destroy + * @type {Array.<*>} + * @private + * @default [] + * @since 3.20.0 + */ + + /** + * The total number of items awaiting processing. + * + * @name Phaser.GameObjects.UpdateList#_toProcess + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.UpdateList#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.UpdateList#start + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.PRE_UPDATE, this.update, this); + eventEmitter.on(SceneEvents.UPDATE, this.sceneUpdate, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The update step. + * + * Pre-updates every active Game Object in the list. + * + * @method Phaser.GameObjects.UpdateList#sceneUpdate + * @since 3.20.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time elapsed since the last frame. + */ + sceneUpdate: function (time, delta) + { + var list = this._active; + var length = list.length; + + for (var i = 0; i < length; i++) + { + var gameObject = list[i]; + + if (gameObject.active) + { + gameObject.preUpdate.call(gameObject, time, delta); + } + } + }, + + /** + * The Scene that owns this plugin is shutting down. + * + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.UpdateList#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + var i = this._active.length; + + while (i--) + { + this._active[i].destroy(true); + } + + i = this._pending.length; + + while (i--) + { + this._pending[i].destroy(true); + } + + i = this._destroy.length; + + while (i--) + { + this._destroy[i].destroy(true); + } + + this._toProcess = 0; + + this._pending = []; + this._active = []; + this._destroy = []; + + this.removeAllListeners(); + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.off(SceneEvents.UPDATE, this.sceneUpdate, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.UpdateList#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.systems.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + + /** + * Adds a new item to the Update List. + * + * The item is added to the pending list and made active in the next update. + * + * @method Phaser.GameObjects.UpdateList#add + * @since 3.0.0 + * + * @param {*} item - The item to add to the queue. + * + * @return {*} The item that was added. + */ + + /** + * Removes an item from the Update List. + * + * The item is added to the pending destroy and fully removed in the next update. + * + * @method Phaser.GameObjects.UpdateList#remove + * @since 3.0.0 + * + * @param {*} item - The item to be removed from the queue. + * + * @return {*} The item that was removed. + */ + + /** + * Removes all active items from this Update List. + * + * All the items are marked as 'pending destroy' and fully removed in the next update. + * + * @method Phaser.GameObjects.UpdateList#removeAll + * @since 3.20.0 + * + * @return {this} This Update List object. + */ + + /** + * Update this queue. First it will process any items awaiting destruction, and remove them. + * + * Then it will check to see if there are any items pending insertion, and move them to an + * active state. Finally, it will return a list of active items for further processing. + * + * @method Phaser.GameObjects.UpdateList#update + * @since 3.0.0 + * + * @return {Array.<*>} A list of active items. + */ + + /** + * Returns the current list of active items. + * + * This method returns a reference to the active list array, not a copy of it. + * Therefore, be careful to not modify this array outside of the ProcessQueue. + * + * @method Phaser.GameObjects.UpdateList#getActive + * @since 3.0.0 + * + * @return {Array.<*>} A list of active items. + */ + + /** + * The number of entries in the active list. + * + * @name Phaser.GameObjects.UpdateList#length + * @type {integer} + * @readonly + * @since 3.20.0 + */ +}); + +PluginCache.register('UpdateList', UpdateList, 'updateList'); + +module.exports = UpdateList; + + +/***/ }), +/* 972 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Structs.Events + */ + +module.exports = { + + PROCESS_QUEUE_ADD: __webpack_require__(973), + PROCESS_QUEUE_REMOVE: __webpack_require__(974) + +}; + + +/***/ }), +/* 973 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Process Queue Add Event. + * + * This event is dispatched by a Process Queue when a new item is successfully moved to its active list. + * + * You will most commonly see this used by a Scene's Update List when a new Game Object has been added. + * + * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('add', listener)`. + * + * @event Phaser.Structs.Events#PROCESS_QUEUE_ADD + * @since 3.20.0 + * + * @param {*} item - The item that was added to the Process Queue. + */ +module.exports = 'add'; + + +/***/ }), +/* 974 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Process Queue Remove Event. + * + * This event is dispatched by a Process Queue when a new item is successfully removed from its active list. + * + * You will most commonly see this used by a Scene's Update List when a Game Object has been removed. + * + * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('remove', listener)`. + * + * @event Phaser.Structs.Events#PROCESS_QUEUE_REMOVE + * @since 3.20.0 + * + * @param {*} item - The item that was removed from the Process Queue. + */ +module.exports = 'remove'; + + +/***/ }), +/* 975 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the position, width and height of a BitmapText Game Object. + * + * Returns a BitmapTextSize object that contains global and local variants of the Game Objects x and y coordinates and + * its width and height. + * + * The global position and size take into account the Game Object's position and scale. + * + * The local position and size just takes into account the font data. + * + * @function GetBitmapTextSize + * @since 3.0.0 + * @private + * + * @param {(Phaser.GameObjects.DynamicBitmapText|Phaser.GameObjects.BitmapText)} src - The BitmapText to calculate the position, width and height of. + * @param {boolean} [round] - Whether to round the results to the nearest integer. + * @param {object} [out] - Optional object to store the results in, to save constant object creation. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} The calculated position, width and height of the BitmapText. + */ +var GetBitmapTextSize = function (src, round, out) +{ + if (out === undefined) + { + out = { + local: { + x: 0, + y: 0, + width: 0, + height: 0 + }, + global: { + x: 0, + y: 0, + width: 0, + height: 0 + }, + lines: { + shortest: 0, + longest: 0, + lengths: null, + height: 0 + }, + wrappedText: '', + words: [], + scaleX: 0, + scaleY: 0 + }; + + return out; + } + + var text = src.text; + var textLength = text.length; + var maxWidth = src.maxWidth; + var wordWrapCharCode = src.wordWrapCharCode; + + var bx = Number.MAX_VALUE; + var by = Number.MAX_VALUE; + var bw = 0; + var bh = 0; + + var chars = src.fontData.chars; + var lineHeight = src.fontData.lineHeight; + var letterSpacing = src.letterSpacing; + + var xAdvance = 0; + var yAdvance = 0; + + var charCode = 0; + + var glyph = null; + + var x = 0; + var y = 0; + + var scale = (src.fontSize / src.fontData.size); + var sx = scale * src.scaleX; + var sy = scale * src.scaleY; + + var lastGlyph = null; + var lastCharCode = 0; + var lineWidths = []; + var shortestLine = Number.MAX_VALUE; + var longestLine = 0; + var currentLine = 0; + var currentLineWidth = 0; + + var i; + var words = []; + var current = null; + + // Scan for breach of maxWidth and insert carriage-returns + if (maxWidth > 0) + { + for (i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy, + cr: true + }); + + current = null; + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + if (lastGlyph !== null) + { + var glyphKerningOffset = glyph.kerning[lastCharCode]; + } + + if (charCode === wordWrapCharCode) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy, + cr: false + }); + + current = null; + } + } + else + { + if (current === null) + { + // We're starting a new word, recording the starting index, etc + current = { word: '', i: i, x: xAdvance, y: yAdvance, w: 0, h: lineHeight, cr: false }; + } + + current.word = current.word.concat(text[i]); + current.w += glyph.xOffset + glyph.xAdvance + ((glyphKerningOffset !== undefined) ? glyphKerningOffset : 0); + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + } + + // Last word + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy, + cr: false + }); + } + + // Reset for the next loop + xAdvance = 0; + yAdvance = 0; + lastGlyph = null; + lastCharCode = 0; + + // Loop through the words array and see if we've got any > maxWidth + var prev; + var offset = 0; + var crs = []; + + for (i = 0; i < words.length; i++) + { + var entry = words[i]; + var left = entry.x; + var right = entry.x + entry.w; + + if (prev) + { + var diff = left - (prev.x + prev.w); + + offset = left - (diff + prev.w); + + prev = null; + } + + var checkLeft = left - offset; + var checkRight = right - offset; + + if (checkLeft > maxWidth || checkRight > maxWidth) + { + crs.push(entry.i - 1); + + if (entry.cr) + { + crs.push(entry.i + entry.word.length); + + offset = 0; + prev = null; + } + else + { + prev = entry; + } + } + else if (entry.cr) + { + crs.push(entry.i + entry.word.length); + + offset = 0; + prev = null; + } + } + + var stringInsert = function (str, index, value) + { + return str.substr(0, index) + value + str.substr(index + 1); + }; + + for (i = crs.length - 1; i >= 0; i--) + { + // eslint-disable-next-line quotes + text = stringInsert(text, crs[i], "\n"); + } + + out.wrappedText = text; + + textLength = text.length; + + // Recalculated in the next loop + words = []; + current = null; + } + + for (i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy + }); + + current = null; + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + lineWidths[currentLine] = currentLineWidth; + + if (currentLineWidth > longestLine) + { + longestLine = currentLineWidth; + } + + if (currentLineWidth < shortestLine) + { + shortestLine = currentLineWidth; + } + + currentLine++; + currentLineWidth = 0; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + x = xAdvance; + y = yAdvance; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + if (bx > x) + { + bx = x; + } + + if (by > y) + { + by = y; + } + + var gw = x + glyph.xAdvance; + var gh = y + lineHeight; + + if (bw < gw) + { + bw = gw; + } + + if (bh < gh) + { + bh = gh; + } + + if (charCode === wordWrapCharCode) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy + }); + + current = null; + } + } + else + { + if (current === null) + { + // We're starting a new word, recording the starting index, etc + current = { word: '', i: i, x: xAdvance, y: yAdvance, w: 0, h: lineHeight }; + } + + current.word = current.word.concat(text[i]); + current.w += glyph.xOffset + glyph.xAdvance + ((kerningOffset !== undefined) ? kerningOffset : 0); + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + currentLineWidth = gw * scale; + } + + // Last word + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy + }); + } + + lineWidths[currentLine] = currentLineWidth; + + if (currentLineWidth > longestLine) + { + longestLine = currentLineWidth; + } + + if (currentLineWidth < shortestLine) + { + shortestLine = currentLineWidth; + } + + var local = out.local; + var global = out.global; + var lines = out.lines; + + local.x = bx * scale; + local.y = by * scale; + local.width = bw * scale; + local.height = bh * scale; + + global.x = (src.x - src.displayOriginX) + (bx * sx); + global.y = (src.y - src.displayOriginY) + (by * sy); + global.width = bw * sx; + global.height = bh * sy; + + lines.shortest = shortestLine; + lines.longest = longestLine; + lines.lengths = lineWidths; + + if (round) + { + local.x = Math.round(local.x); + local.y = Math.round(local.y); + local.width = Math.round(local.width); + local.height = Math.round(local.height); + + global.x = Math.round(global.x); + global.y = Math.round(global.y); + global.width = Math.round(global.width); + global.height = Math.round(global.height); + + lines.shortest = Math.round(shortestLine); + lines.longest = Math.round(longestLine); + } + + out.words = words; + out.lines.height = lineHeight; + out.scaleX = src.scaleX; + out.scaleY = src.scaleY; + + return out; +}; + +module.exports = GetBitmapTextSize; + + +/***/ }), +/* 976 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ParseXMLBitmapFont = __webpack_require__(200); + +/** + * Parse an XML Bitmap Font from an Atlas. + * + * Adds the parsed Bitmap Font data to the cache with the `fontName` key. + * + * @function ParseFromAtlas + * @since 3.0.0 + * @private + * + * @param {Phaser.Scene} scene - The Scene to parse the Bitmap Font for. + * @param {string} fontName - The key of the font to add to the Bitmap Font cache. + * @param {string} textureKey - The key of the BitmapFont's texture. + * @param {string} frameKey - The key of the BitmapFont texture's frame. + * @param {string} xmlKey - The key of the XML data of the font to parse. + * @param {integer} [xSpacing] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing] - The y-axis spacing to add to the line height. + * + * @return {boolean} Whether the parsing was successful or not. + */ +var ParseFromAtlas = function (scene, fontName, textureKey, frameKey, xmlKey, xSpacing, ySpacing) +{ + var frame = scene.sys.textures.getFrame(textureKey, frameKey); + var xml = scene.sys.cache.xml.get(xmlKey); + + if (frame && xml) + { + var data = ParseXMLBitmapFont(xml, xSpacing, ySpacing, frame); + + scene.sys.cache.bitmapFont.add(fontName, { data: data, texture: textureKey, frame: frameKey }); + + return true; + } + else + { + return false; + } +}; + +module.exports = ParseFromAtlas; + + +/***/ }), +/* 977 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(978); +} + +if (true) +{ + renderCanvas = __webpack_require__(979); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 978 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.BitmapText#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.BitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BitmapTextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src._text; + var textLength = text.length; + + if (textLength === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + var textureX = frame.cutX; + var textureY = frame.cutY; + var textureWidth = texture.width; + var textureHeight = texture.height; + + var tintEffect = (src._isTinted && src.tintFill); + var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); + var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); + var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); + var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); + + pipeline.setTexture2D(texture, 0); + + var xAdvance = 0; + var yAdvance = 0; + var charCode = 0; + var lastCharCode = 0; + var letterSpacing = src._letterSpacing; + var glyph; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + var lastGlyph; + + var fontData = src.fontData; + var chars = fontData.chars; + var lineHeight = fontData.lineHeight; + var scale = (src._fontSize / fontData.size); + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + var bounds = src.getTextBounds(false); + + // In case the method above changed it (word wrapping) + if (src.maxWidth > 0) + { + text = bounds.wrappedText; + textLength = text.length; + } + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + var roundPixels = camera.roundPixels; + + for (var i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + // Carriage-return + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + var x = glyph.xOffset + xAdvance; + var y = glyph.yOffset + yAdvance; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + x *= scale; + y *= scale; + + x -= src.displayOriginX; + y -= src.displayOriginY; + + x += lineOffsetX; + + var u0 = glyphX / textureWidth; + var v0 = glyphY / textureHeight; + var u1 = (glyphX + glyphW) / textureWidth; + var v1 = (glyphY + glyphH) / textureHeight; + + var xw = x + (glyphW * scale); + var yh = y + (glyphH * scale); + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + } +}; + +module.exports = BitmapTextWebGLRenderer; + + +/***/ }), +/* 979 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.BitmapText#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.BitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src._text; + var textLength = text.length; + + var ctx = renderer.currentContext; + + if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + return; + } + + var textureFrame = src.frame; + + var chars = src.fontData.chars; + var lineHeight = src.fontData.lineHeight; + var letterSpacing = src._letterSpacing; + + var xAdvance = 0; + var yAdvance = 0; + + var charCode = 0; + + var glyph = null; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + + var x = 0; + var y = 0; + + var lastGlyph = null; + var lastCharCode = 0; + + var image = src.frame.source.image; + + var textureX = textureFrame.cutX; + var textureY = textureFrame.cutY; + + var scale = (src._fontSize / src.fontData.size); + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + var bounds = src.getTextBounds(false); + + // In case the method above changed it (word wrapping) + if (src.maxWidth > 0) + { + text = bounds.wrappedText; + textLength = text.length; + } + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + ctx.translate(-src.displayOriginX, -src.displayOriginY); + + var roundPixels = camera.roundPixels; + + for (var i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + x = glyph.xOffset + xAdvance; + y = glyph.yOffset + yAdvance; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + x *= scale; + y *= scale; + + x += lineOffsetX; + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + if (roundPixels) + { + x = Math.round(x); + y = Math.round(y); + } + + ctx.save(); + + ctx.translate(x, y); + + ctx.scale(scale, scale); + + ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); + + ctx.restore(); + } + + ctx.restore(); +}; + +module.exports = BitmapTextCanvasRenderer; + + +/***/ }), +/* 980 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(981); +} + +if (true) +{ + renderCanvas = __webpack_require__(982); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 981 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Blitter#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Blitter} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BlitterWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var list = src.getRenderList(); + + if (list.length === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var cameraScrollX = camera.scrollX * src.scrollFactorX; + var cameraScrollY = camera.scrollY * src.scrollFactorY; + + var calcMatrix = pipeline._tempMatrix1; + + calcMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + calcMatrix.multiplyWithOffset(parentMatrix, -cameraScrollX, -cameraScrollY); + + cameraScrollX = 0; + cameraScrollY = 0; + } + + var blitterX = src.x - cameraScrollX; + var blitterY = src.y - cameraScrollY; + var prevTextureSourceIndex = -1; + var tintEffect = false; + var alpha = camera.alpha * src.alpha; + var roundPixels = camera.roundPixels; + + for (var index = 0; index < list.length; index++) + { + var bob = list[index]; + var frame = bob.frame; + var bobAlpha = bob.alpha * alpha; + + if (bobAlpha === 0) + { + continue; + } + + var width = frame.width; + var height = frame.height; + + var x = blitterX + bob.x + frame.x; + var y = blitterY + bob.y + frame.y; + + if (bob.flipX) + { + width *= -1; + x += frame.width; + } + + if (bob.flipY) + { + height *= -1; + y += frame.height; + } + + var xw = x + width; + var yh = y + height; + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(xw, yh); + var ty1 = calcMatrix.getY(xw, yh); + + var tint = Utils.getTintAppendFloatAlpha(bob.tint, bobAlpha); + + // Bind texture only if the Texture Source is different from before + if (frame.sourceIndex !== prevTextureSourceIndex) + { + pipeline.setTexture2D(frame.glTexture, 0); + + prevTextureSourceIndex = frame.sourceIndex; + } + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + } + + // TL x/y, BL x/y, BR x/y, TR x/y + if (pipeline.batchQuad(tx0, ty0, tx0, ty1, tx1, ty1, tx1, ty0, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect, frame.glTexture, 0)) + { + prevTextureSourceIndex = -1; + } + } +}; + +module.exports = BlitterWebGLRenderer; + + +/***/ }), +/* 982 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Blitter#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Blitter} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BlitterCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var list = src.getRenderList(); + + if (list.length === 0) + { + return; + } + + var ctx = renderer.currentContext; + + var alpha = camera.alpha * src.alpha; + + if (alpha === 0) + { + // Nothing to see, so abort early + return; + } + + // Blend Mode + Scale Mode + ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + + ctx.imageSmoothingEnabled = !(!renderer.antialias || src.frame.source.scaleMode); + + var cameraScrollX = src.x - camera.scrollX * src.scrollFactorX; + var cameraScrollY = src.y - camera.scrollY * src.scrollFactorY; + + ctx.save(); + + if (parentMatrix) + { + parentMatrix.copyToContext(ctx); + } + + var roundPixels = camera.roundPixels; + + // Render bobs + for (var i = 0; i < list.length; i++) + { + var bob = list[i]; + var flip = (bob.flipX || bob.flipY); + var frame = bob.frame; + var cd = frame.canvasData; + var dx = frame.x; + var dy = frame.y; + var fx = 1; + var fy = 1; + + var bobAlpha = bob.alpha * alpha; + + if (bobAlpha === 0) + { + continue; + } + + ctx.globalAlpha = bobAlpha; + + if (!flip) + { + if (roundPixels) + { + dx = Math.round(dx); + dy = Math.round(dy); + } + + ctx.drawImage( + frame.source.image, + cd.x, + cd.y, + cd.width, + cd.height, + dx + bob.x + cameraScrollX, + dy + bob.y + cameraScrollY, + cd.width, + cd.height + ); + } + else + { + if (bob.flipX) + { + fx = -1; + dx -= cd.width; + } + + if (bob.flipY) + { + fy = -1; + dy -= cd.height; + } + + ctx.save(); + ctx.translate(bob.x + cameraScrollX, bob.y + cameraScrollY); + ctx.scale(fx, fy); + ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, dx, dy, cd.width, cd.height); + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = BlitterCanvasRenderer; + + +/***/ }), +/* 983 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Frame = __webpack_require__(106); + +/** + * @classdesc + * A Bob Game Object. + * + * A Bob belongs to a Blitter Game Object. The Blitter is responsible for managing and rendering this object. + * + * A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle + * the flipped and visible state of the Bob. The Frame the Bob uses to render can be changed dynamically, but it + * must be a Frame within the Texture used by the parent Blitter. + * + * Bob positions are relative to the Blitter parent. So if you move the Blitter parent, all Bob children will + * have their positions impacted by this change as well. + * + * You can manipulate Bob objects directly from your game code, but the creation and destruction of them should be + * handled via the Blitter parent. + * + * @class Bob + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Blitter} blitter - The parent Blitter object is responsible for updating this Bob. + * @param {number} x - The horizontal position of this Game Object in the world, relative to the parent Blitter position. + * @param {number} y - The vertical position of this Game Object in the world, relative to the parent Blitter position. + * @param {(string|integer)} frame - The Frame this Bob will render with, as defined in the Texture the parent Blitter is using. + * @param {boolean} visible - Should the Bob render visible or not to start with? + */ +var Bob = new Class({ + + initialize: + + function Bob (blitter, x, y, frame, visible) + { + /** + * The Blitter object that this Bob belongs to. + * + * @name Phaser.GameObjects.Bob#parent + * @type {Phaser.GameObjects.Blitter} + * @since 3.0.0 + */ + this.parent = blitter; + + /** + * The x position of this Bob, relative to the x position of the Blitter. + * + * @name Phaser.GameObjects.Bob#x + * @type {number} + * @since 3.0.0 + */ + this.x = x; + + /** + * The y position of this Bob, relative to the y position of the Blitter. + * + * @name Phaser.GameObjects.Bob#y + * @type {number} + * @since 3.0.0 + */ + this.y = y; + + /** + * The frame that the Bob uses to render with. + * To change the frame use the `Bob.setFrame` method. + * + * @name Phaser.GameObjects.Bob#frame + * @type {Phaser.Textures.Frame} + * @protected + * @since 3.0.0 + */ + this.frame = frame; + + /** + * A blank object which can be used to store data related to this Bob in. + * + * @name Phaser.GameObjects.Bob#data + * @type {object} + * @default {} + * @since 3.0.0 + */ + this.data = {}; + + /** + * The tint value of this Bob. + * + * @name Phaser.GameObjects.Bob#tint + * @type {number} + * @default 0xffffff + * @since 3.20.0 + */ + this.tint = 0xffffff; + + /** + * The visible state of this Bob. + * + * @name Phaser.GameObjects.Bob#_visible + * @type {boolean} + * @private + * @since 3.0.0 + */ + this._visible = visible; + + /** + * The alpha value of this Bob. + * + * @name Phaser.GameObjects.Bob#_alpha + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + this._alpha = 1; + + /** + * The horizontally flipped state of the Bob. + * A Bob that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture. + * + * @name Phaser.GameObjects.Bob#flipX + * @type {boolean} + * @since 3.0.0 + */ + this.flipX = false; + + /** + * The vertically flipped state of the Bob. + * A Bob that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture. + * + * @name Phaser.GameObjects.Bob#flipY + * @type {boolean} + * @since 3.0.0 + */ + this.flipY = false; + }, + + /** + * Changes the Texture Frame being used by this Bob. + * The frame must be part of the Texture the parent Blitter is using. + * If no value is given it will use the default frame of the Blitter parent. + * + * @method Phaser.GameObjects.Bob#setFrame + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The frame to be used during rendering. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setFrame: function (frame) + { + if (frame === undefined) + { + this.frame = this.parent.frame; + } + else if (frame instanceof Frame && frame.texture === this.parent.texture) + { + this.frame = frame; + } + else + { + this.frame = this.parent.texture.get(frame); + } + + return this; + }, + + /** + * Resets the horizontal and vertical flipped state of this Bob back to their default un-flipped state. + * + * @method Phaser.GameObjects.Bob#resetFlip + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + resetFlip: function () + { + this.flipX = false; + this.flipY = false; + + return this; + }, + + /** + * Resets this Bob. + * + * Changes the position to the values given, and optionally changes the frame. + * + * Also resets the flipX and flipY values, sets alpha back to 1 and visible to true. + * + * @method Phaser.GameObjects.Bob#reset + * @since 3.0.0 + * + * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + reset: function (x, y, frame) + { + this.x = x; + this.y = y; + + this.flipX = false; + this.flipY = false; + + this._alpha = 1; + this._visible = true; + + this.parent.dirty = true; + + if (frame) + { + this.setFrame(frame); + } + + return this; + }, + + /** + * Changes the position of this Bob to the values given. + * + * @method Phaser.GameObjects.Bob#setPosition + * @since 3.20.0 + * + * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setPosition: function (x, y) + { + this.x = x; + this.y = y; + + return this; + }, + + /** + * Sets the horizontal flipped state of this Bob. + * + * @method Phaser.GameObjects.Bob#setFlipX + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setFlipX: function (value) + { + this.flipX = value; + + return this; + }, + + /** + * Sets the vertical flipped state of this Bob. + * + * @method Phaser.GameObjects.Bob#setFlipY + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setFlipY: function (value) + { + this.flipY = value; + + return this; + }, + + /** + * Sets the horizontal and vertical flipped state of this Bob. + * + * @method Phaser.GameObjects.Bob#setFlip + * @since 3.0.0 + * + * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setFlip: function (x, y) + { + this.flipX = x; + this.flipY = y; + + return this; + }, + + /** + * Sets the visibility of this Bob. + * + * An invisible Bob will skip rendering. + * + * @method Phaser.GameObjects.Bob#setVisible + * @since 3.0.0 + * + * @param {boolean} value - The visible state of the Game Object. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setVisible: function (value) + { + this.visible = value; + + return this; + }, + + /** + * Set the Alpha level of this Bob. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * A Bob with alpha 0 will skip rendering. + * + * @method Phaser.GameObjects.Bob#setAlpha + * @since 3.0.0 + * + * @param {number} value - The alpha value used for this Bob. Between 0 and 1. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setAlpha: function (value) + { + this.alpha = value; + + return this; + }, + + /** + * Sets the tint of this Bob. + * + * @method Phaser.GameObjects.Bob#setTint + * @since 3.20.0 + * + * @param {number} value - The tint value used for this Bob. Between 0 and 0xffffff. + * + * @return {Phaser.GameObjects.Bob} This Bob Game Object. + */ + setTint: function (value) + { + this.tint = value; + + return this; + }, + + /** + * Destroys this Bob instance. + * Removes itself from the Blitter and clears the parent, frame and data properties. + * + * @method Phaser.GameObjects.Bob#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.parent.dirty = true; + + this.parent.children.remove(this); + + this.parent = undefined; + this.frame = undefined; + this.data = undefined; + }, + + /** + * The visible state of the Bob. + * + * An invisible Bob will skip rendering. + * + * @name Phaser.GameObjects.Bob#visible + * @type {boolean} + * @since 3.0.0 + */ + visible: { + + get: function () + { + return this._visible; + }, + + set: function (value) + { + this.parent.dirty |= (this._visible !== value); + this._visible = value; + } + + }, + + /** + * The alpha value of the Bob, between 0 and 1. + * + * A Bob with alpha 0 will skip rendering. + * + * @name Phaser.GameObjects.Bob#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this._alpha; + }, + + set: function (value) + { + this.parent.dirty |= ((this._alpha > 0) !== (value > 0)); + this._alpha = value; + } + + } + +}); + +module.exports = Bob; + + +/***/ }), +/* 984 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(985); +} + +if (true) +{ + renderCanvas = __webpack_require__(986); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 985 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Container#renderWebGL + * @since 3.4.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Container} container - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ContainerWebGLRenderer = function (renderer, container, interpolationPercentage, camera, parentMatrix) +{ + var children = container.list; + + if (children.length === 0) + { + return; + } + + var transformMatrix = container.localTransform; + + if (parentMatrix) + { + transformMatrix.loadIdentity(); + transformMatrix.multiply(parentMatrix); + transformMatrix.translate(container.x, container.y); + transformMatrix.rotate(container.rotation); + transformMatrix.scale(container.scaleX, container.scaleY); + } + else + { + transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY); + } + + var containerHasBlendMode = (container.blendMode !== -1); + + if (!containerHasBlendMode) + { + // If Container is SKIP_TEST then set blend mode to be Normal + renderer.setBlendMode(0); + } + + var alpha = container.alpha; + + var scrollFactorX = container.scrollFactorX; + var scrollFactorY = container.scrollFactorY; + + var list = children; + var childCount = children.length; + + for (var i = 0; i < childCount; i++) + { + var child = children[i]; + + if (!child.willRender(camera)) + { + continue; + } + + var childAlphaTopLeft; + var childAlphaTopRight; + var childAlphaBottomLeft; + var childAlphaBottomRight; + + if (child.alphaTopLeft !== undefined) + { + childAlphaTopLeft = child.alphaTopLeft; + childAlphaTopRight = child.alphaTopRight; + childAlphaBottomLeft = child.alphaBottomLeft; + childAlphaBottomRight = child.alphaBottomRight; + } + else + { + var childAlpha = child.alpha; + + childAlphaTopLeft = childAlpha; + childAlphaTopRight = childAlpha; + childAlphaBottomLeft = childAlpha; + childAlphaBottomRight = childAlpha; + } + + var childScrollFactorX = child.scrollFactorX; + var childScrollFactorY = child.scrollFactorY; + + if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) + { + // If Container doesn't have its own blend mode, then a child can have one + renderer.setBlendMode(child.blendMode); + } + + var mask = child.mask; + + if (mask) + { + mask.preRenderWebGL(renderer, child, camera); + } + + var type = child.type; + + if (type !== renderer.currentType) + { + renderer.newType = true; + renderer.currentType = type; + } + + renderer.nextTypeMatch = (i < childCount - 1) ? (list[i + 1].type === renderer.currentType) : false; + + // Set parent values + child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); + + child.setAlpha(childAlphaTopLeft * alpha, childAlphaTopRight * alpha, childAlphaBottomLeft * alpha, childAlphaBottomRight * alpha); + + // Render + child.renderWebGL(renderer, child, interpolationPercentage, camera, transformMatrix); + + // Restore original values + + child.setAlpha(childAlphaTopLeft, childAlphaTopRight, childAlphaBottomLeft, childAlphaBottomRight); + + child.setScrollFactor(childScrollFactorX, childScrollFactorY); + + if (mask) + { + mask.postRenderWebGL(renderer, camera); + } + + renderer.newType = false; + } +}; + +module.exports = ContainerWebGLRenderer; + + +/***/ }), +/* 986 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Container#renderCanvas + * @since 3.4.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Container} container - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ContainerCanvasRenderer = function (renderer, container, interpolationPercentage, camera, parentMatrix) +{ + var children = container.list; + + if (children.length === 0) + { + return; + } + + var transformMatrix = container.localTransform; + + if (parentMatrix) + { + transformMatrix.loadIdentity(); + transformMatrix.multiply(parentMatrix); + transformMatrix.translate(container.x, container.y); + transformMatrix.rotate(container.rotation); + transformMatrix.scale(container.scaleX, container.scaleY); + } + else + { + transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY); + } + + var containerHasBlendMode = (container.blendMode !== -1); + + if (!containerHasBlendMode) + { + // If Container is SKIP_TEST then set blend mode to be Normal + renderer.setBlendMode(0); + } + + var alpha = container._alpha; + var scrollFactorX = container.scrollFactorX; + var scrollFactorY = container.scrollFactorY; + + for (var i = 0; i < children.length; i++) + { + var child = children[i]; + + if (!child.willRender(camera)) + { + continue; + } + + var childAlpha = child.alpha; + var childScrollFactorX = child.scrollFactorX; + var childScrollFactorY = child.scrollFactorY; + + if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) + { + // If Container doesn't have its own blend mode, then a child can have one + renderer.setBlendMode(child.blendMode); + } + + // Set parent values + child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); + child.setAlpha(childAlpha * alpha); + + // Render + child.renderCanvas(renderer, child, interpolationPercentage, camera, transformMatrix); + + // Restore original values + child.setAlpha(childAlpha); + child.setScrollFactor(childScrollFactorX, childScrollFactorY); + } +}; + +module.exports = ContainerCanvasRenderer; + + +/***/ }), +/* 987 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(419); +} + +if (true) +{ + renderCanvas = __webpack_require__(419); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 988 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Blend Modes to CSS Blend Modes Map. + * + * @name Phaser.CSSBlendModes + * @enum {string} + * @memberof Phaser + * @readonly + * @since 3.12.0 + */ + +module.exports = [ + 'normal', + 'multiply', + 'multiply', + 'screen', + 'overlay', + 'darken', + 'lighten', + 'color-dodge', + 'color-burn', + 'hard-light', + 'soft-light', + 'difference', + 'exclusion', + 'hue', + 'saturation', + 'color', + 'luminosity' +]; + + +/***/ }), +/* 989 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(990); +} + +if (true) +{ + renderCanvas = __webpack_require__(991); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 990 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.DynamicBitmapText#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.DynamicBitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DynamicBitmapTextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src.text; + var textLength = text.length; + + if (textLength === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var crop = (src.cropWidth > 0 || src.cropHeight > 0); + + if (crop) + { + pipeline.flush(); + + renderer.pushScissor( + src.x, + src.y, + src.cropWidth * src.scaleX, + src.cropHeight * src.scaleY + ); + } + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + var fontMatrix = pipeline._tempMatrix4; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + var textureX = frame.cutX; + var textureY = frame.cutY; + var textureWidth = texture.width; + var textureHeight = texture.height; + + var tintEffect = (src._isTinted && src.tintFill); + var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); + var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); + var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); + var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); + + pipeline.setTexture2D(texture, 0); + + var xAdvance = 0; + var yAdvance = 0; + var charCode = 0; + var lastCharCode = 0; + var letterSpacing = src.letterSpacing; + var glyph; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + var lastGlyph; + var scrollX = src.scrollX; + var scrollY = src.scrollY; + + var fontData = src.fontData; + var chars = fontData.chars; + var lineHeight = fontData.lineHeight; + var scale = (src.fontSize / fontData.size); + var rotation = 0; + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + src.getTextBounds(false); + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + var roundPixels = camera.roundPixels; + var displayCallback = src.displayCallback; + var callbackData = src.callbackData; + + for (var i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + // Carriage-return + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + var x = (glyph.xOffset + xAdvance) - scrollX; + var y = (glyph.yOffset + yAdvance) - scrollY; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + scale = (src.fontSize / src.fontData.size); + rotation = 0; + + if (displayCallback) + { + callbackData.color = 0; + callbackData.tint.topLeft = tintTL; + callbackData.tint.topRight = tintTR; + callbackData.tint.bottomLeft = tintBL; + callbackData.tint.bottomRight = tintBR; + callbackData.index = i; + callbackData.charCode = charCode; + callbackData.x = x; + callbackData.y = y; + callbackData.scale = scale; + callbackData.rotation = rotation; + callbackData.data = glyph.data; + + var output = displayCallback(callbackData); + + x = output.x; + y = output.y; + scale = output.scale; + rotation = output.rotation; + + if (output.color) + { + tintTL = output.color; + tintTR = output.color; + tintBL = output.color; + tintBR = output.color; + } + else + { + tintTL = output.tint.topLeft; + tintTR = output.tint.topRight; + tintBL = output.tint.bottomLeft; + tintBR = output.tint.bottomRight; + } + + tintTL = Utils.getTintAppendFloatAlpha(tintTL, camera.alpha * src._alphaTL); + tintTR = Utils.getTintAppendFloatAlpha(tintTR, camera.alpha * src._alphaTR); + tintBL = Utils.getTintAppendFloatAlpha(tintBL, camera.alpha * src._alphaBL); + tintBR = Utils.getTintAppendFloatAlpha(tintBR, camera.alpha * src._alphaBR); + } + + x *= scale; + y *= scale; + + x -= src.displayOriginX; + y -= src.displayOriginY; + + x += lineOffsetX; + + fontMatrix.applyITRS(x, y, rotation, scale, scale); + + calcMatrix.multiply(fontMatrix, spriteMatrix); + + var u0 = glyphX / textureWidth; + var v0 = glyphY / textureHeight; + var u1 = (glyphX + glyphW) / textureWidth; + var v1 = (glyphY + glyphH) / textureHeight; + + var xw = glyphW; + var yh = glyphH; + + var tx0 = spriteMatrix.e; + var ty0 = spriteMatrix.f; + + var tx1 = yh * spriteMatrix.c + spriteMatrix.e; + var ty1 = yh * spriteMatrix.d + spriteMatrix.f; + + var tx2 = xw * spriteMatrix.a + yh * spriteMatrix.c + spriteMatrix.e; + var ty2 = xw * spriteMatrix.b + yh * spriteMatrix.d + spriteMatrix.f; + + var tx3 = xw * spriteMatrix.a + spriteMatrix.e; + var ty3 = xw * spriteMatrix.b + spriteMatrix.f; + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + } + + if (crop) + { + pipeline.flush(); + + renderer.popScissor(); + } +}; + +module.exports = DynamicBitmapTextWebGLRenderer; + + +/***/ }), +/* 991 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.DynamicBitmapText#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.DynamicBitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DynamicBitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src._text; + var textLength = text.length; + + var ctx = renderer.currentContext; + + if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + return; + } + + var textureFrame = src.frame; + + var displayCallback = src.displayCallback; + var callbackData = src.callbackData; + + var chars = src.fontData.chars; + var lineHeight = src.fontData.lineHeight; + var letterSpacing = src._letterSpacing; + + var xAdvance = 0; + var yAdvance = 0; + + var charCode = 0; + + var glyph = null; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + + var x = 0; + var y = 0; + + var lastGlyph = null; + var lastCharCode = 0; + + var image = src.frame.source.image; + + var textureX = textureFrame.cutX; + var textureY = textureFrame.cutY; + + var rotation = 0; + var scale = 0; + var baseScale = (src._fontSize / src.fontData.size); + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + src.getTextBounds(false); + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + ctx.translate(-src.displayOriginX, -src.displayOriginY); + + var roundPixels = camera.roundPixels; + + if (src.cropWidth > 0 && src.cropHeight > 0) + { + ctx.beginPath(); + ctx.rect(0, 0, src.cropWidth, src.cropHeight); + ctx.clip(); + } + + for (var i = 0; i < textLength; i++) + { + // Reset the scale (in case the callback changed it) + scale = baseScale; + rotation = 0; + + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + x = (glyph.xOffset + xAdvance) - src.scrollX; + y = (glyph.yOffset + yAdvance) - src.scrollY; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + if (displayCallback) + { + callbackData.index = i; + callbackData.charCode = charCode; + callbackData.x = x; + callbackData.y = y; + callbackData.scale = scale; + callbackData.rotation = rotation; + callbackData.data = glyph.data; + + var output = displayCallback(callbackData); + + x = output.x; + y = output.y; + scale = output.scale; + rotation = output.rotation; + } + + x *= scale; + y *= scale; + + x += lineOffsetX; + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + if (roundPixels) + { + x = Math.round(x); + y = Math.round(y); + } + + ctx.save(); + + ctx.translate(x, y); + + ctx.rotate(rotation); + + ctx.scale(scale, scale); + + ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); + + ctx.restore(); + } + + ctx.restore(); +}; + +module.exports = DynamicBitmapTextCanvasRenderer; + + +/***/ }), +/* 992 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(993); +} + +if (true) +{ + renderCanvas = __webpack_require__(994); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 993 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Extern#renderWebGL + * @since 3.16.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Extern} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ExternWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = renderer.currentPipeline; + + renderer.clearPipeline(); + + var camMatrix = renderer._tempMatrix1; + var spriteMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + // Callback + src.render.call(src, renderer, camera, calcMatrix); + + renderer.rebindPipeline(pipeline); +}; + +module.exports = ExternWebGLRenderer; + + +/***/ }), +/* 994 */ +/***/ (function(module, exports) { + + + +/***/ }), +/* 995 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(996); + + // Needed for Graphics.generateTexture + renderCanvas = __webpack_require__(424); +} + +if (true) +{ + renderCanvas = __webpack_require__(424); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 996 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Commands = __webpack_require__(205); +var Utils = __webpack_require__(10); + +// TODO: Remove the use of this +var Point = function (x, y, width) +{ + this.x = x; + this.y = y; + this.width = width; +}; + +// TODO: Remove the use of this +var Path = function (x, y, width) +{ + this.points = []; + this.pointsLength = 1; + this.points[0] = new Point(x, y, width); +}; + +var matrixStack = []; + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Graphics#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Graphics} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var GraphicsWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (src.commandBuffer.length === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = src._tempMatrix1; + var graphicsMatrix = src._tempMatrix2; + var currentMatrix = src._tempMatrix3; + + currentMatrix.loadIdentity(); + + graphicsMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + graphicsMatrix.e = src.x; + graphicsMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(graphicsMatrix); + } + else + { + graphicsMatrix.e -= camera.scrollX * src.scrollFactorX; + graphicsMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(graphicsMatrix); + } + + var commands = src.commandBuffer; + var alpha = camera.alpha * src.alpha; + + var lineWidth = 1; + var fillTint = pipeline.fillTint; + var strokeTint = pipeline.strokeTint; + + var tx = 0; + var ty = 0; + var ta = 0; + var iterStep = 0.01; + var PI2 = Math.PI * 2; + + var cmd; + + var path = []; + var pathIndex = 0; + var pathOpen = false; + var lastPath = null; + + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + + var currentTexture = renderer.blankTexture.glTexture; + + for (var cmdIndex = 0; cmdIndex < commands.length; cmdIndex++) + { + cmd = commands[cmdIndex]; + + switch (cmd) + { + case Commands.BEGIN_PATH: + + path.length = 0; + lastPath = null; + pathOpen = true; + break; + + case Commands.CLOSE_PATH: + + pathOpen = false; + + if (lastPath && lastPath.points.length) + { + lastPath.points.push(lastPath.points[0]); + } + break; + + case Commands.FILL_PATH: + for (pathIndex = 0; pathIndex < path.length; pathIndex++) + { + pipeline.setTexture2D(currentTexture); + + pipeline.batchFillPath( + path[pathIndex].points, + currentMatrix, + camMatrix + ); + } + break; + + case Commands.STROKE_PATH: + for (pathIndex = 0; pathIndex < path.length; pathIndex++) + { + pipeline.setTexture2D(currentTexture); + + pipeline.batchStrokePath( + path[pathIndex].points, + lineWidth, + pathOpen, + currentMatrix, + camMatrix + ); + } + break; + + case Commands.LINE_STYLE: + lineWidth = commands[++cmdIndex]; + var strokeColor = commands[++cmdIndex]; + var strokeAlpha = commands[++cmdIndex] * alpha; + var strokeTintColor = getTint(strokeColor, strokeAlpha); + strokeTint.TL = strokeTintColor; + strokeTint.TR = strokeTintColor; + strokeTint.BL = strokeTintColor; + strokeTint.BR = strokeTintColor; + break; + + case Commands.FILL_STYLE: + var fillColor = commands[++cmdIndex]; + var fillAlpha = commands[++cmdIndex] * alpha; + var fillTintColor = getTint(fillColor, fillAlpha); + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + break; + + case Commands.GRADIENT_FILL_STYLE: + var gradientFillAlpha = commands[++cmdIndex] * alpha; + fillTint.TL = getTint(commands[++cmdIndex], gradientFillAlpha); + fillTint.TR = getTint(commands[++cmdIndex], gradientFillAlpha); + fillTint.BL = getTint(commands[++cmdIndex], gradientFillAlpha); + fillTint.BR = getTint(commands[++cmdIndex], gradientFillAlpha); + break; + + case Commands.GRADIENT_LINE_STYLE: + lineWidth = commands[++cmdIndex]; + var gradientLineAlpha = commands[++cmdIndex] * alpha; + strokeTint.TL = getTint(commands[++cmdIndex], gradientLineAlpha); + strokeTint.TR = getTint(commands[++cmdIndex], gradientLineAlpha); + strokeTint.BL = getTint(commands[++cmdIndex], gradientLineAlpha); + strokeTint.BR = getTint(commands[++cmdIndex], gradientLineAlpha); + break; + + case Commands.ARC: + var iteration = 0; + var x = commands[++cmdIndex]; + var y = commands[++cmdIndex]; + var radius = commands[++cmdIndex]; + var startAngle = commands[++cmdIndex]; + var endAngle = commands[++cmdIndex]; + var anticlockwise = commands[++cmdIndex]; + var overshoot = commands[++cmdIndex]; + + endAngle -= startAngle; + + if (anticlockwise) + { + if (endAngle < -PI2) + { + endAngle = -PI2; + } + else if (endAngle > 0) + { + endAngle = -PI2 + endAngle % PI2; + } + } + else if (endAngle > PI2) + { + endAngle = PI2; + } + else if (endAngle < 0) + { + endAngle = PI2 + endAngle % PI2; + } + + if (lastPath === null) + { + lastPath = new Path(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius, lineWidth); + path.push(lastPath); + iteration += iterStep; + } + + while (iteration < 1 + overshoot) + { + ta = endAngle * iteration + startAngle; + tx = x + Math.cos(ta) * radius; + ty = y + Math.sin(ta) * radius; + + lastPath.points.push(new Point(tx, ty, lineWidth)); + + iteration += iterStep; + } + + ta = endAngle + startAngle; + tx = x + Math.cos(ta) * radius; + ty = y + Math.sin(ta) * radius; + + lastPath.points.push(new Point(tx, ty, lineWidth)); + + break; + + case Commands.FILL_RECT: + pipeline.setTexture2D(currentTexture); + pipeline.batchFillRect( + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + currentMatrix, + camMatrix + ); + break; + + case Commands.FILL_TRIANGLE: + pipeline.setTexture2D(currentTexture); + pipeline.batchFillTriangle( + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + currentMatrix, + camMatrix + ); + break; + + case Commands.STROKE_TRIANGLE: + pipeline.setTexture2D(currentTexture); + pipeline.batchStrokeTriangle( + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + lineWidth, + currentMatrix, + camMatrix + ); + break; + + case Commands.LINE_TO: + if (lastPath !== null) + { + lastPath.points.push(new Point(commands[++cmdIndex], commands[++cmdIndex], lineWidth)); + } + else + { + lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); + path.push(lastPath); + } + break; + + case Commands.MOVE_TO: + lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); + path.push(lastPath); + break; + + case Commands.SAVE: + matrixStack.push(currentMatrix.copyToArray()); + break; + + case Commands.RESTORE: + currentMatrix.copyFromArray(matrixStack.pop()); + break; + + case Commands.TRANSLATE: + x = commands[++cmdIndex]; + y = commands[++cmdIndex]; + currentMatrix.translate(x, y); + break; + + case Commands.SCALE: + x = commands[++cmdIndex]; + y = commands[++cmdIndex]; + currentMatrix.scale(x, y); + break; + + case Commands.ROTATE: + currentMatrix.rotate(commands[++cmdIndex]); + break; + + case Commands.SET_TEXTURE: + var frame = commands[++cmdIndex]; + var mode = commands[++cmdIndex]; + + pipeline.currentFrame = frame; + pipeline.setTexture2D(frame.glTexture, 0); + pipeline.tintEffect = mode; + + currentTexture = frame.glTexture; + + break; + + case Commands.CLEAR_TEXTURE: + pipeline.currentFrame = renderer.blankTexture; + pipeline.tintEffect = 2; + currentTexture = renderer.blankTexture.glTexture; + break; + } + } +}; + +module.exports = GraphicsWebGLRenderer; + + +/***/ }), +/* 997 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(998); +} + +if (true) +{ + renderCanvas = __webpack_require__(999); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 998 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Sprite#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var SpriteWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + this.pipeline.batchSprite(src, camera, parentMatrix); +}; + +module.exports = SpriteWebGLRenderer; + + +/***/ }), +/* 999 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Sprite#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var SpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = SpriteCanvasRenderer; + + +/***/ }), +/* 1000 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1001); +} + +if (true) +{ + renderCanvas = __webpack_require__(1002); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1001 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Image#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Image} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ImageWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + this.pipeline.batchSprite(src, camera, parentMatrix); +}; + +module.exports = ImageWebGLRenderer; + + +/***/ }), +/* 1002 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Image#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Image} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ImageCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = ImageCanvasRenderer; + + +/***/ }), +/* 1003 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Particles + */ + +module.exports = { + + GravityWell: __webpack_require__(425), + Particle: __webpack_require__(426), + ParticleEmitter: __webpack_require__(427), + ParticleEmitterManager: __webpack_require__(207), + Zones: __webpack_require__(1008) + +}; + + +/***/ }), +/* 1004 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FloatBetween = __webpack_require__(348); +var GetEaseFunction = __webpack_require__(90); +var GetFastValue = __webpack_require__(1); +var Wrap = __webpack_require__(63); + +/** + * @classdesc + * A Particle Emitter property. + * + * Facilitates changing Particle properties as they are emitted and throughout their lifetime. + * + * @class EmitterOp + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for the Particle Emitter that owns this property. + * @param {string} key - The name of the property. + * @param {number} defaultValue - The default value of the property. + * @param {boolean} [emitOnly=false] - Whether the property can only be modified when a Particle is emitted. + */ +var EmitterOp = new Class({ + + initialize: + + function EmitterOp (config, key, defaultValue, emitOnly) + { + if (emitOnly === undefined) + { + emitOnly = false; + } + + /** + * The name of this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#propertyKey + * @type {string} + * @since 3.0.0 + */ + this.propertyKey = key; + + /** + * The value of this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#propertyValue + * @type {number} + * @since 3.0.0 + */ + this.propertyValue = defaultValue; + + /** + * The default value of this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#defaultValue + * @type {number} + * @since 3.0.0 + */ + this.defaultValue = defaultValue; + + /** + * The number of steps for stepped easing between {@link Phaser.GameObjects.Particles.EmitterOp#start} and + * {@link Phaser.GameObjects.Particles.EmitterOp#end} values, per emit. + * + * @name Phaser.GameObjects.Particles.EmitterOp#steps + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.steps = 0; + + /** + * The step counter for stepped easing, per emit. + * + * @name Phaser.GameObjects.Particles.EmitterOp#counter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.counter = 0; + + /** + * The start value for this property to ease between. + * + * @name Phaser.GameObjects.Particles.EmitterOp#start + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.start = 0; + + /** + * The end value for this property to ease between. + * + * @name Phaser.GameObjects.Particles.EmitterOp#end + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.end = 0; + + /** + * The easing function to use for updating this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#ease + * @type {?function} + * @since 3.0.0 + */ + this.ease; + + /** + * Whether this property can only be modified when a Particle is emitted. + * + * Set to `true` to allow only {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} callbacks to be set and + * affect this property. + * + * Set to `false` to allow both {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and + * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks to be set and affect this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#emitOnly + * @type {boolean} + * @since 3.0.0 + */ + this.emitOnly = emitOnly; + + /** + * The callback to run for Particles when they are emitted from the Particle Emitter. + * + * @name Phaser.GameObjects.Particles.EmitterOp#onEmit + * @type {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback} + * @since 3.0.0 + */ + this.onEmit = this.defaultEmit; + + /** + * The callback to run for Particles when they are updated. + * + * @name Phaser.GameObjects.Particles.EmitterOp#onUpdate + * @type {Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback} + * @since 3.0.0 + */ + this.onUpdate = this.defaultUpdate; + + this.loadConfig(config); + }, + + /** + * Load the property from a Particle Emitter configuration object. + * + * Optionally accepts a new property key to use, replacing the current one. + * + * @method Phaser.GameObjects.Particles.EmitterOp#loadConfig + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} [config] - Settings for the Particle Emitter that owns this property. + * @param {string} [newKey] - The new key to use for this property, if any. + */ + loadConfig: function (config, newKey) + { + if (config === undefined) + { + config = {}; + } + + if (newKey) + { + this.propertyKey = newKey; + } + + this.propertyValue = GetFastValue( + config, + this.propertyKey, + this.defaultValue + ); + + this.setMethods(); + + if (this.emitOnly) + { + // Reset it back again + this.onUpdate = this.defaultUpdate; + } + }, + + /** + * Build a JSON representation of this Particle Emitter property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#toJSON + * @since 3.0.0 + * + * @return {object} A JSON representation of this Particle Emitter property. + */ + toJSON: function () + { + return this.propertyValue; + }, + + /** + * Change the current value of the property and update its callback methods. + * + * @method Phaser.GameObjects.Particles.EmitterOp#onChange + * @since 3.0.0 + * + * @param {number} value - The value of the property. + * + * @return {Phaser.GameObjects.Particles.EmitterOp} This Emitter Op object. + */ + onChange: function (value) + { + this.propertyValue = value; + + return this.setMethods(); + }, + + /** + * Update the {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and + * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks based on the type of the current + * {@link Phaser.GameObjects.Particles.EmitterOp#propertyValue}. + * + * @method Phaser.GameObjects.Particles.EmitterOp#setMethods + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.EmitterOp} This Emitter Op object. + */ + setMethods: function () + { + var value = this.propertyValue; + + var t = typeof value; + + if (t === 'number') + { + // Explicit static value: + // x: 400 + + this.onEmit = this.staticValueEmit; + this.onUpdate = this.staticValueUpdate; // How? + } + else if (Array.isArray(value)) + { + // Picks a random element from the array: + // x: [ 100, 200, 300, 400 ] + + this.onEmit = this.randomStaticValueEmit; + } + else if (t === 'function') + { + // The same as setting just the onUpdate function and no onEmit (unless this op is an emitOnly one) + // Custom callback, must return a value: + + /* + x: function (particle, key, t, value) + { + return value + 50; + } + */ + + if (this.emitOnly) + { + this.onEmit = value; + } + else + { + this.onUpdate = value; + } + } + else if (t === 'object' && (this.has(value, 'random') || this.hasBoth(value, 'start', 'end') || this.hasBoth(value, 'min', 'max'))) + { + this.start = this.has(value, 'start') ? value.start : value.min; + this.end = this.has(value, 'end') ? value.end : value.max; + + var isRandom = (this.hasBoth(value, 'min', 'max') || !!value.random); + + // A random starting value (using 'min | max' instead of 'start | end' automatically implies a random value) + + // x: { start: 100, end: 400, random: true } OR { min: 100, max: 400 } OR { random: [ 100, 400 ] } + + if (isRandom) + { + var rnd = value.random; + + // x: { random: [ 100, 400 ] } = the same as doing: x: { start: 100, end: 400, random: true } + if (Array.isArray(rnd)) + { + this.start = rnd[0]; + this.end = rnd[1]; + } + + this.onEmit = this.randomRangedValueEmit; + } + + if (this.has(value, 'steps')) + { + // A stepped (per emit) range + + // x: { start: 100, end: 400, steps: 64 } + + // Increments a value stored in the emitter + + this.steps = value.steps; + this.counter = this.start; + + this.onEmit = this.steppedEmit; + } + else + { + // An eased range (defaults to Linear if not specified) + + // x: { start: 100, end: 400, [ ease: 'Linear' ] } + + var easeType = this.has(value, 'ease') ? value.ease : 'Linear'; + + this.ease = GetEaseFunction(easeType); + + if (!isRandom) + { + this.onEmit = this.easedValueEmit; + } + + // BUG: alpha, rotate, scaleX, scaleY, or tint are eased here if {min, max} is given. + // Probably this branch should exclude isRandom entirely. + + this.onUpdate = this.easeValueUpdate; + } + } + else if (t === 'object' && this.hasEither(value, 'onEmit', 'onUpdate')) + { + // Custom onEmit and onUpdate callbacks + + /* + x: { + // Called at the start of the particles life, when it is being created + onEmit: function (particle, key, t, value) + { + return value; + }, + + // Called during the particles life on each update + onUpdate: function (particle, key, t, value) + { + return value; + } + } + */ + + if (this.has(value, 'onEmit')) + { + this.onEmit = value.onEmit; + } + + if (this.has(value, 'onUpdate')) + { + this.onUpdate = value.onUpdate; + } + } + + return this; + }, + + /** + * Check whether an object has the given property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#has + * @since 3.0.0 + * + * @param {object} object - The object to check. + * @param {string} key - The key of the property to look for in the object. + * + * @return {boolean} `true` if the property exists in the object, `false` otherwise. + */ + has: function (object, key) + { + return object.hasOwnProperty(key); + }, + + /** + * Check whether an object has both of the given properties. + * + * @method Phaser.GameObjects.Particles.EmitterOp#hasBoth + * @since 3.0.0 + * + * @param {object} object - The object to check. + * @param {string} key1 - The key of the first property to check the object for. + * @param {string} key2 - The key of the second property to check the object for. + * + * @return {boolean} `true` if both properties exist in the object, `false` otherwise. + */ + hasBoth: function (object, key1, key2) + { + return object.hasOwnProperty(key1) && object.hasOwnProperty(key2); + }, + + /** + * Check whether an object has at least one of the given properties. + * + * @method Phaser.GameObjects.Particles.EmitterOp#hasEither + * @since 3.0.0 + * + * @param {object} object - The object to check. + * @param {string} key1 - The key of the first property to check the object for. + * @param {string} key2 - The key of the second property to check the object for. + * + * @return {boolean} `true` if at least one of the properties exists in the object, `false` if neither exist. + */ + hasEither: function (object, key1, key2) + { + return object.hasOwnProperty(key1) || object.hasOwnProperty(key2); + }, + + /** + * The returned value sets what the property will be at the START of the particles life, on emit. + * + * @method Phaser.GameObjects.Particles.EmitterOp#defaultEmit + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * @param {number} [value] - The current value of the property. + * + * @return {number} The new value of the property. + */ + defaultEmit: function (particle, key, value) + { + return value; + }, + + /** + * The returned value updates the property for the duration of the particles life. + * + * @method Phaser.GameObjects.Particles.EmitterOp#defaultUpdate + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * @param {number} t - The T value (between 0 and 1) + * @param {number} value - The current value of the property. + * + * @return {number} The new value of the property. + */ + defaultUpdate: function (particle, key, t, value) + { + return value; + }, + + /** + * An `onEmit` callback that returns the current value of the property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#staticValueEmit + * @since 3.0.0 + * + * @return {number} The current value of the property. + */ + staticValueEmit: function () + { + return this.propertyValue; + }, + + /** + * An `onUpdate` callback that returns the current value of the property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#staticValueUpdate + * @since 3.0.0 + * + * @return {number} The current value of the property. + */ + staticValueUpdate: function () + { + return this.propertyValue; + }, + + /** + * An `onEmit` callback that returns a random value from the current value array. + * + * @method Phaser.GameObjects.Particles.EmitterOp#randomStaticValueEmit + * @since 3.0.0 + * + * @return {number} The new value of the property. + */ + randomStaticValueEmit: function () + { + var randomIndex = Math.floor(Math.random() * this.propertyValue.length); + + return this.propertyValue[randomIndex]; + }, + + /** + * An `onEmit` callback that returns a value between the {@link Phaser.GameObjects.Particles.EmitterOp#start} and + * {@link Phaser.GameObjects.Particles.EmitterOp#end} range. + * + * @method Phaser.GameObjects.Particles.EmitterOp#randomRangedValueEmit + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The key of the property. + * + * @return {number} The new value of the property. + */ + randomRangedValueEmit: function (particle, key) + { + var value = FloatBetween(this.start, this.end); + + if (particle && particle.data[key]) + { + particle.data[key].min = value; + } + + return value; + }, + + /** + * An `onEmit` callback that returns a stepped value between the + * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} + * range. + * + * @method Phaser.GameObjects.Particles.EmitterOp#steppedEmit + * @since 3.0.0 + * + * @return {number} The new value of the property. + */ + steppedEmit: function () + { + var current = this.counter; + + var next = this.counter + (this.end - this.start) / this.steps; + + this.counter = Wrap(next, this.start, this.end); + + return current; + }, + + /** + * An `onEmit` callback for an eased property. + * + * It prepares the particle for easing by {@link Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate}. + * + * @method Phaser.GameObjects.Particles.EmitterOp#easedValueEmit + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * + * @return {number} {@link Phaser.GameObjects.Particles.EmitterOp#start}, as the new value of the property. + */ + easedValueEmit: function (particle, key) + { + if (particle && particle.data[key]) + { + var data = particle.data[key]; + + data.min = this.start; + data.max = this.end; + } + + return this.start; + }, + + /** + * An `onUpdate` callback that returns an eased value between the + * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} + * range. + * + * @method Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * @param {number} t - The T value (between 0 and 1) + * + * @return {number} The new value of the property. + */ + easeValueUpdate: function (particle, key, t) + { + var data = particle.data[key]; + + return (data.max - data.min) * this.ease(t) + data.min; + } +}); + +module.exports = EmitterOp; + + +/***/ }), +/* 1005 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1006); +} + +if (true) +{ + renderCanvas = __webpack_require__(1007); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1006 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Particles.EmitterManager#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} emitterManager - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ParticleManagerWebGLRenderer = function (renderer, emitterManager, interpolationPercentage, camera, parentMatrix) +{ + var emitters = emitterManager.emitters.list; + var emittersLength = emitters.length; + + if (emittersLength === 0) + { + return; + } + + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1.copyFrom(camera.matrix); + var calcMatrix = pipeline._tempMatrix2; + var particleMatrix = pipeline._tempMatrix3; + var managerMatrix = pipeline._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); + + camMatrix.multiply(managerMatrix); + + renderer.setPipeline(pipeline); + + var roundPixels = camera.roundPixels; + var texture = emitterManager.defaultFrame.glTexture; + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + + pipeline.setTexture2D(texture, 0); + + for (var e = 0; e < emittersLength; e++) + { + var emitter = emitters[e]; + var particles = emitter.alive; + var particleCount = particles.length; + + if (!emitter.visible || particleCount === 0) + { + continue; + } + + var scrollX = camera.scrollX * emitter.scrollFactorX; + var scrollY = camera.scrollY * emitter.scrollFactorY; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); + + scrollX = 0; + scrollY = 0; + } + + if (renderer.setBlendMode(emitter.blendMode)) + { + // Rebind the texture if we've flushed + pipeline.setTexture2D(texture, 0); + } + + if (emitter.mask) + { + emitter.mask.preRenderWebGL(renderer, emitter, camera); + pipeline.setTexture2D(texture, 0); + } + + var tintEffect = 0; + + for (var i = 0; i < particleCount; i++) + { + var particle = particles[i]; + + var alpha = particle.alpha * camera.alpha; + + if (alpha <= 0) + { + continue; + } + + var frame = particle.frame; + + var x = -(frame.halfWidth); + var y = -(frame.halfHeight); + var xw = x + frame.width; + var yh = y + frame.height; + + particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); + + particleMatrix.e = particle.x - scrollX; + particleMatrix.f = particle.y - scrollY; + + camMatrix.multiply(particleMatrix, calcMatrix); + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + var tint = getTint(particle.tint, alpha); + + pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect, texture, 0); + } + + if (emitter.mask) + { + emitter.mask.postRenderWebGL(renderer, camera); + pipeline.setTexture2D(texture, 0); + } + } +}; + +module.exports = ParticleManagerWebGLRenderer; + + +/***/ }), +/* 1007 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Particles.EmitterManager#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} emitterManager - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ParticleManagerCanvasRenderer = function (renderer, emitterManager, interpolationPercentage, camera, parentMatrix) +{ + var emitters = emitterManager.emitters.list; + var emittersLength = emitters.length; + + if (emittersLength === 0) + { + return; + } + + var camMatrix = renderer._tempMatrix1.copyFrom(camera.matrix); + var calcMatrix = renderer._tempMatrix2; + var particleMatrix = renderer._tempMatrix3; + var managerMatrix = renderer._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); + + camMatrix.multiply(managerMatrix); + + var roundPixels = camera.roundPixels; + + var ctx = renderer.currentContext; + + ctx.save(); + + for (var e = 0; e < emittersLength; e++) + { + var emitter = emitters[e]; + var particles = emitter.alive; + var particleCount = particles.length; + + if (!emitter.visible || particleCount === 0) + { + continue; + } + + var scrollX = camera.scrollX * emitter.scrollFactorX; + var scrollY = camera.scrollY * emitter.scrollFactorY; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); + + scrollX = 0; + scrollY = 0; + } + + ctx.globalCompositeOperation = renderer.blendModes[emitter.blendMode]; + + for (var i = 0; i < particleCount; i++) + { + var particle = particles[i]; + + var alpha = particle.alpha * camera.alpha; + + if (alpha <= 0) + { + continue; + } + + var frame = particle.frame; + var cd = frame.canvasData; + + var x = -(frame.halfWidth); + var y = -(frame.halfHeight); + + particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); + + particleMatrix.e = particle.x - scrollX; + particleMatrix.f = particle.y - scrollY; + + camMatrix.multiply(particleMatrix, calcMatrix); + + ctx.globalAlpha = alpha; + + ctx.save(); + + calcMatrix.copyToContext(ctx); + + if (roundPixels) + { + x = Math.round(x); + y = Math.round(y); + } + + ctx.imageSmoothingEnabled = !(!renderer.antialias || frame.source.scaleMode); + + ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); + + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = ParticleManagerCanvasRenderer; + + +/***/ }), +/* 1008 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Particles.Zones + */ + +module.exports = { + + DeathZone: __webpack_require__(428), + EdgeZone: __webpack_require__(429), + RandomZone: __webpack_require__(431) + +}; + + +/***/ }), +/* 1009 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1010); +} + +if (true) +{ + renderCanvas = __webpack_require__(1011); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1010 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.RenderTexture#renderWebGL + * @since 3.2.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.RenderTexture} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RenderTextureWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var frame = src.frame; + var width = frame.width; + var height = frame.height; + var getTint = Utils.getTintAppendFloatAlpha; + + this.pipeline.batchTexture( + src, + frame.glTexture, + width, height, + src.x, src.y, + width, height, + src.scaleX, src.scaleY, + src.rotation, + src.flipX, !src.flipY, + src.scrollFactorX, src.scrollFactorY, + src.displayOriginX, src.displayOriginY, + 0, 0, width, height, + getTint(src._tintTL, camera.alpha * src._alphaTL), + getTint(src._tintTR, camera.alpha * src._alphaTR), + getTint(src._tintBL, camera.alpha * src._alphaBL), + getTint(src._tintBR, camera.alpha * src._alphaBR), + (src._isTinted && src.tintFill), + 0, 0, + camera, + parentMatrix + ); + + // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it + renderer.setBlankTexture(true); +}; + +module.exports = RenderTextureWebGLRenderer; + + +/***/ }), +/* 1011 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.RenderTexture#renderCanvas + * @since 3.2.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.RenderTexture} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RenderTextureCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = RenderTextureCanvasRenderer; + + +/***/ }), +/* 1012 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RETRO_FONT_CONST = __webpack_require__(1013); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.GameObjects.RetroFont + * @since 3.6.0 + */ + +var RetroFont = { Parse: __webpack_require__(1014) }; + +// Merge in the consts +RetroFont = Extend(false, RetroFont, RETRO_FONT_CONST); + +module.exports = RetroFont; + + +/***/ }), +/* 1013 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RETRO_FONT_CONST = { + + /** + * Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET1 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET1: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~', + + /** + * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET2 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET2: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET3 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET3: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ', + + /** + * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET4 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET4: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789', + + /** + * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET5 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET5: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() \'!?-*:0123456789', + + /** + * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET6 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET6: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.\' ', + + /** + * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET7 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET7: 'AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-\'39', + + /** + * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET8 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET8: '0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET9 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET9: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,\'"?!', + + /** + * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET10 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET10: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET11 + * @since 3.6.0 + * @type {string} + */ + TEXT_SET11: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()\':;0123456789' + +}; + +module.exports = RETRO_FONT_CONST; + + +/***/ }), +/* 1014 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = __webpack_require__(5); + +/** + * Parses a Retro Font configuration object so you can pass it to the BitmapText constructor + * and create a BitmapText object using a fixed-width retro font. + * + * @function Phaser.GameObjects.RetroFont.Parse + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Phaser Scene. + * @param {Phaser.Types.GameObjects.BitmapText.RetroFontConfig} config - The font configuration object. + * + * @return {object} A parsed Bitmap Font data entry for the Bitmap Font cache. + */ +var ParseRetroFont = function (scene, config) +{ + var w = config.width; + var h = config.height; + var cx = Math.floor(w / 2); + var cy = Math.floor(h / 2); + var letters = GetValue(config, 'chars', ''); + + if (letters === '') + { + return; + } + + var key = GetValue(config, 'image', ''); + var offsetX = GetValue(config, 'offset.x', 0); + var offsetY = GetValue(config, 'offset.y', 0); + var spacingX = GetValue(config, 'spacing.x', 0); + var spacingY = GetValue(config, 'spacing.y', 0); + var lineSpacing = GetValue(config, 'lineSpacing', 0); + + var charsPerRow = GetValue(config, 'charsPerRow', null); + + if (charsPerRow === null) + { + charsPerRow = scene.sys.textures.getFrame(key).width / w; + + if (charsPerRow > letters.length) + { + charsPerRow = letters.length; + } + } + + var x = offsetX; + var y = offsetY; + + var data = { + retroFont: true, + font: key, + size: w, + lineHeight: h + lineSpacing, + chars: {} + }; + + var r = 0; + + for (var i = 0; i < letters.length; i++) + { + // var node = letters[i]; + + var charCode = letters.charCodeAt(i); + + data.chars[charCode] = + { + x: x, + y: y, + width: w, + height: h, + centerX: cx, + centerY: cy, + xOffset: 0, + yOffset: 0, + xAdvance: w, + data: {}, + kerning: {} + }; + + r++; + + if (r === charsPerRow) + { + r = 0; + x = offsetX; + y += h + spacingY; + } + else + { + x += w + spacingX; + } + } + + var entry = { + data: data, + frame: null, + texture: key + }; + + return entry; +}; + +module.exports = ParseRetroFont; + + +/***/ }), +/* 1015 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns an object containing dimensions of the Text object. + * + * @function Phaser.GameObjects.Text.GetTextSize + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Text} text - The Text object to calculate the size from. + * @param {Phaser.Types.GameObjects.Text.TextMetrics} size - The Text metrics to use when calculating the size. + * @param {array} lines - The lines of text to calculate the size from. + * + * @return {object} An object containing dimensions of the Text object. + */ +var GetTextSize = function (text, size, lines) +{ + var canvas = text.canvas; + var context = text.context; + var style = text.style; + + var lineWidths = []; + var maxLineWidth = 0; + var drawnLines = lines.length; + + if (style.maxLines > 0 && style.maxLines < lines.length) + { + drawnLines = style.maxLines; + } + + style.syncFont(canvas, context); + + // Text Width + + for (var i = 0; i < drawnLines; i++) + { + var lineWidth = style.strokeThickness; + + lineWidth += context.measureText(lines[i]).width; + + // Adjust for wrapped text + if (style.wordWrap) + { + lineWidth -= context.measureText(' ').width; + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + // Text Height + + var lineHeight = size.fontSize + style.strokeThickness; + var height = lineHeight * drawnLines; + var lineSpacing = text.lineSpacing; + + // Adjust for line spacing + if (drawnLines > 1) + { + height += lineSpacing * (drawnLines - 1); + } + + return { + width: maxLineWidth, + height: height, + lines: drawnLines, + lineWidths: lineWidths, + lineSpacing: lineSpacing, + lineHeight: lineHeight + }; +}; + +module.exports = GetTextSize; + + +/***/ }), +/* 1016 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1017); +} + +if (true) +{ + renderCanvas = __webpack_require__(1018); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1017 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Text#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Text} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if ((src.width === 0) || (src.height === 0)) + { + return; + } + + var frame = src.frame; + var width = frame.width; + var height = frame.height; + var getTint = Utils.getTintAppendFloatAlpha; + + this.pipeline.batchTexture( + src, + frame.glTexture, + width, height, + src.x, src.y, + width / src.style.resolution, height / src.style.resolution, + src.scaleX, src.scaleY, + src.rotation, + src.flipX, src.flipY, + src.scrollFactorX, src.scrollFactorY, + src.displayOriginX, src.displayOriginY, + 0, 0, width, height, + getTint(src._tintTL, camera.alpha * src._alphaTL), + getTint(src._tintTR, camera.alpha * src._alphaTR), + getTint(src._tintBL, camera.alpha * src._alphaBL), + getTint(src._tintBR, camera.alpha * src._alphaBR), + (src._isTinted && src.tintFill), + 0, 0, + camera, + parentMatrix + ); +}; + +module.exports = TextWebGLRenderer; + + +/***/ }), +/* 1018 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Text#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Text} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if ((src.width === 0) || (src.height === 0)) + { + return; + } + + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = TextCanvasRenderer; + + +/***/ }), +/* 1019 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var GetAdvancedValue = __webpack_require__(15); +var GetValue = __webpack_require__(5); +var MeasureText = __webpack_require__(1020); + +// Key: [ Object Key, Default Value ] + +var propertyMap = { + fontFamily: [ 'fontFamily', 'Courier' ], + fontSize: [ 'fontSize', '16px' ], + fontStyle: [ 'fontStyle', '' ], + backgroundColor: [ 'backgroundColor', null ], + color: [ 'color', '#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', 0 ], + fixedHeight: [ 'fixedHeight', 0 ], + resolution: [ 'resolution', 0 ], + rtl: [ 'rtl', false ], + testString: [ 'testString', '|MÉqgy' ], + baselineX: [ 'baselineX', 1.2 ], + baselineY: [ 'baselineY', 1.4 ], + wordWrapWidth: [ 'wordWrap.width', null ], + wordWrapCallback: [ 'wordWrap.callback', null ], + wordWrapCallbackScope: [ 'wordWrap.callbackScope', null ], + wordWrapUseAdvanced: [ 'wordWrap.useAdvancedWrap', false ] +}; + +/** + * @classdesc + * A TextStyle class manages all of the style settings for a Text object. + * + * Text Game Objects create a TextStyle instance automatically, which is + * accessed via the `Text.style` property. You do not normally need to + * instantiate one yourself. + * + * @class TextStyle + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Text} text - The Text object that this TextStyle is styling. + * @param {Phaser.Types.GameObjects.Text.TextStyle} style - The style settings to set. + */ +var TextStyle = new Class({ + + initialize: + + function TextStyle (text, style) + { + /** + * The Text object that this TextStyle is styling. + * + * @name Phaser.GameObjects.TextStyle#parent + * @type {Phaser.GameObjects.Text} + * @since 3.0.0 + */ + this.parent = text; + + /** + * The font family. + * + * @name Phaser.GameObjects.TextStyle#fontFamily + * @type {string} + * @default 'Courier' + * @since 3.0.0 + */ + this.fontFamily; + + /** + * The font size. + * + * @name Phaser.GameObjects.TextStyle#fontSize + * @type {string} + * @default '16px' + * @since 3.0.0 + */ + this.fontSize; + + /** + * The font style. + * + * @name Phaser.GameObjects.TextStyle#fontStyle + * @type {string} + * @since 3.0.0 + */ + this.fontStyle; + + /** + * The background color. + * + * @name Phaser.GameObjects.TextStyle#backgroundColor + * @type {string} + * @since 3.0.0 + */ + this.backgroundColor; + + /** + * The text fill color. + * + * @name Phaser.GameObjects.TextStyle#color + * @type {string} + * @default '#fff' + * @since 3.0.0 + */ + this.color; + + /** + * The text stroke color. + * + * @name Phaser.GameObjects.TextStyle#stroke + * @type {string} + * @default '#fff' + * @since 3.0.0 + */ + this.stroke; + + /** + * The text stroke thickness. + * + * @name Phaser.GameObjects.TextStyle#strokeThickness + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.strokeThickness; + + /** + * The horizontal shadow offset. + * + * @name Phaser.GameObjects.TextStyle#shadowOffsetX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.shadowOffsetX; + + /** + * The vertical shadow offset. + * + * @name Phaser.GameObjects.TextStyle#shadowOffsetY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.shadowOffsetY; + + /** + * The shadow color. + * + * @name Phaser.GameObjects.TextStyle#shadowColor + * @type {string} + * @default '#000' + * @since 3.0.0 + */ + this.shadowColor; + + /** + * The shadow blur radius. + * + * @name Phaser.GameObjects.TextStyle#shadowBlur + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.shadowBlur; + + /** + * Whether shadow stroke is enabled or not. + * + * @name Phaser.GameObjects.TextStyle#shadowStroke + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.shadowStroke; + + /** + * Whether shadow fill is enabled or not. + * + * @name Phaser.GameObjects.TextStyle#shadowFill + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.shadowFill; + + /** + * The text alignment. + * + * @name Phaser.GameObjects.TextStyle#align + * @type {string} + * @default 'left' + * @since 3.0.0 + */ + this.align; + + /** + * The maximum number of lines to draw. + * + * @name Phaser.GameObjects.TextStyle#maxLines + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.maxLines; + + /** + * The fixed width of the text. + * + * `0` means no fixed with. + * + * @name Phaser.GameObjects.TextStyle#fixedWidth + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.fixedWidth; + + /** + * The fixed height of the text. + * + * `0` means no fixed height. + * + * @name Phaser.GameObjects.TextStyle#fixedHeight + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.fixedHeight; + + /** + * The resolution the text is rendered to its internal canvas at. + * The default is 0, which means it will use the resolution set in the Game Config. + * + * @name Phaser.GameObjects.TextStyle#resolution + * @type {number} + * @default 0 + * @since 3.12.0 + */ + this.resolution; + + /** + * Whether the text should render right to left. + * + * @name Phaser.GameObjects.TextStyle#rtl + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.rtl; + + /** + * The test string to use when measuring the font. + * + * @name Phaser.GameObjects.TextStyle#testString + * @type {string} + * @default '|MÉqgy' + * @since 3.0.0 + */ + this.testString; + + /** + * The amount of horizontal padding added to the width of the text when calculating the font metrics. + * + * @name Phaser.GameObjects.TextStyle#baselineX + * @type {number} + * @default 1.2 + * @since 3.3.0 + */ + this.baselineX; + + /** + * The amount of vertical padding added to the height of the text when calculating the font metrics. + * + * @name Phaser.GameObjects.TextStyle#baselineY + * @type {number} + * @default 1.4 + * @since 3.3.0 + */ + this.baselineY; + + /** + * The font style, size and family. + * + * @name Phaser.GameObjects.TextStyle#_font + * @type {string} + * @private + * @since 3.0.0 + */ + this._font; + + // Set to defaults + user style + this.setStyle(style, false, true); + + var metrics = GetValue(style, 'metrics', false); + + // 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 + if (metrics) + { + this.metrics = { + ascent: GetValue(metrics, 'ascent', 0), + descent: GetValue(metrics, 'descent', 0), + fontSize: GetValue(metrics, 'fontSize', 0) + }; + } + else + { + this.metrics = MeasureText(this); + } + }, + + /** + * Set the text style. + * + * @example + * text.setStyle({ + * fontSize: '64px', + * fontFamily: 'Arial', + * color: '#ffffff', + * align: 'center', + * backgroundColor: '#ff00ff' + * }); + * + * @method Phaser.GameObjects.TextStyle#setStyle + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Text.TextStyle} style - The style settings to set. + * @param {boolean} [updateText=true] - Whether to update the text immediately. + * @param {boolean} [setDefaults=false] - Use the default values is not set, or the local values. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setStyle: function (style, updateText, setDefaults) + { + if (updateText === undefined) { updateText = true; } + if (setDefaults === undefined) { setDefaults = false; } + + // Avoid type mutation + if (style && style.hasOwnProperty('fontSize') && typeof style.fontSize === 'number') + { + style.fontSize = style.fontSize.toString() + 'px'; + } + + for (var key in propertyMap) + { + var value = (setDefaults) ? propertyMap[key][1] : this[key]; + + if (key === 'wordWrapCallback' || key === 'wordWrapCallbackScope') + { + // Callback & scope should be set without processing the values + this[key] = GetValue(style, propertyMap[key][0], value); + } + else + { + this[key] = GetAdvancedValue(style, propertyMap[key][0], value); + } + } + + // Allow for 'font' override + var font = GetValue(style, 'font', null); + + if (font !== null) + { + this.setFont(font, false); + } + + this._font = [ this.fontStyle, this.fontSize, this.fontFamily ].join(' ').trim(); + + // Allow for 'fill' to be used in place of 'color' + var fill = GetValue(style, 'fill', null); + + if (fill !== null) + { + this.color = fill; + } + + if (updateText) + { + return this.update(true); + } + else + { + return this.parent; + } + }, + + /** + * Synchronize the font settings to the given Canvas Rendering Context. + * + * @method Phaser.GameObjects.TextStyle#syncFont + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The Canvas Element. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + */ + syncFont: function (canvas, context) + { + context.font = this._font; + }, + + /** + * Synchronize the text style settings to the given Canvas Rendering Context. + * + * @method Phaser.GameObjects.TextStyle#syncStyle + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The Canvas Element. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + */ + syncStyle: function (canvas, context) + { + context.textBaseline = 'alphabetic'; + + context.fillStyle = this.color; + context.strokeStyle = this.stroke; + + context.lineWidth = this.strokeThickness; + context.lineCap = 'round'; + context.lineJoin = 'round'; + }, + + /** + * Synchronize the shadow settings to the given Canvas Rendering Context. + * + * @method Phaser.GameObjects.TextStyle#syncShadow + * @since 3.0.0 + * + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + * @param {boolean} enabled - Whether shadows are enabled or not. + */ + syncShadow: function (context, enabled) + { + if (enabled) + { + context.shadowOffsetX = this.shadowOffsetX; + context.shadowOffsetY = this.shadowOffsetY; + context.shadowColor = this.shadowColor; + context.shadowBlur = this.shadowBlur; + } + else + { + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + context.shadowColor = 0; + context.shadowBlur = 0; + } + }, + + /** + * Update the style settings for the parent Text object. + * + * @method Phaser.GameObjects.TextStyle#update + * @since 3.0.0 + * + * @param {boolean} recalculateMetrics - Whether to recalculate font and text metrics. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + update: function (recalculateMetrics) + { + if (recalculateMetrics) + { + this._font = [ this.fontStyle, this.fontSize, this.fontFamily ].join(' ').trim(); + + this.metrics = MeasureText(this); + } + + return this.parent.updateText(); + }, + + /** + * 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. + * + * @method Phaser.GameObjects.TextStyle#setFont + * @since 3.0.0 + * + * @param {(string|object)} font - The font family or font settings to set. + * @param {boolean} [updateText=true] - Whether to update the text immediately. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFont: function (font, updateText) + { + if (updateText === undefined) { updateText = true; } + + var fontFamily = font; + var fontSize = ''; + var fontStyle = ''; + + if (typeof font !== 'string') + { + fontFamily = GetValue(font, 'fontFamily', 'Courier'); + fontSize = GetValue(font, 'fontSize', '16px'); + fontStyle = GetValue(font, 'fontStyle', ''); + } + else + { + var fontSplit = font.split(' '); + + var i = 0; + + fontStyle = (fontSplit.length > 2) ? fontSplit[i++] : ''; + fontSize = fontSplit[i++] || '16px'; + fontFamily = fontSplit[i++] || 'Courier'; + } + + if (fontFamily !== this.fontFamily || fontSize !== this.fontSize || fontStyle !== this.fontStyle) + { + this.fontFamily = fontFamily; + this.fontSize = fontSize; + this.fontStyle = fontStyle; + + if (updateText) + { + this.update(true); + } + } + + return this.parent; + }, + + /** + * Set the font family. + * + * @method Phaser.GameObjects.TextStyle#setFontFamily + * @since 3.0.0 + * + * @param {string} family - The font family. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFontFamily: function (family) + { + if (this.fontFamily !== family) + { + this.fontFamily = family; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the font style. + * + * @method Phaser.GameObjects.TextStyle#setFontStyle + * @since 3.0.0 + * + * @param {string} style - The font style. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFontStyle: function (style) + { + if (this.fontStyle !== style) + { + this.fontStyle = style; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the font size. + * + * @method Phaser.GameObjects.TextStyle#setFontSize + * @since 3.0.0 + * + * @param {(number|string)} size - The font size. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFontSize: function (size) + { + if (typeof size === 'number') + { + size = size.toString() + 'px'; + } + + if (this.fontSize !== size) + { + this.fontSize = size; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the test string to use when measuring the font. + * + * @method Phaser.GameObjects.TextStyle#setTestString + * @since 3.0.0 + * + * @param {string} string - The test string to use when measuring the font. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setTestString: function (string) + { + this.testString = string; + + return this.update(true); + }, + + /** + * Set a fixed width and height for the text. + * + * Pass in `0` for either of these parameters to disable fixed width or height respectively. + * + * @method Phaser.GameObjects.TextStyle#setFixedSize + * @since 3.0.0 + * + * @param {number} width - The fixed width to set. + * @param {number} height - The fixed height to set. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFixedSize: function (width, height) + { + this.fixedWidth = width; + this.fixedHeight = height; + + if (width) + { + this.parent.width = width; + } + + if (height) + { + this.parent.height = height; + } + + return this.update(false); + }, + + /** + * Set the background color. + * + * @method Phaser.GameObjects.TextStyle#setBackgroundColor + * @since 3.0.0 + * + * @param {string} color - The background color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setBackgroundColor: function (color) + { + this.backgroundColor = color; + + return this.update(false); + }, + + /** + * Set the text fill color. + * + * @method Phaser.GameObjects.TextStyle#setFill + * @since 3.0.0 + * + * @param {string} color - The text fill color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFill: function (color) + { + this.color = color; + + return this.update(false); + }, + + /** + * Set the text fill color. + * + * @method Phaser.GameObjects.TextStyle#setColor + * @since 3.0.0 + * + * @param {string} color - The text fill color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setColor: function (color) + { + this.color = color; + + return this.update(false); + }, + + /** + * Set the resolution used by the Text object. + * + * By default it will be set to match the resolution set in the Game Config, + * but you can override it via this method. It allows for much clearer text on High DPI devices, + * at the cost of memory because it uses larger internal Canvas textures for the Text. + * + * Please use with caution, as the more high res Text you have, the more memory it uses up. + * + * @method Phaser.GameObjects.TextStyle#setResolution + * @since 3.12.0 + * + * @param {number} value - The resolution for this Text object to use. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setResolution: function (value) + { + this.resolution = value; + + return this.update(false); + }, + + /** + * Set the stroke settings. + * + * @method Phaser.GameObjects.TextStyle#setStroke + * @since 3.0.0 + * + * @param {string} color - The stroke color. + * @param {number} thickness - The stroke thickness. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setStroke: function (color, thickness) + { + if (thickness === undefined) { thickness = this.strokeThickness; } + + if (color === undefined && this.strokeThickness !== 0) + { + // Reset the stroke to zero (disabling it) + this.strokeThickness = 0; + + this.update(true); + } + else if (this.stroke !== color || this.strokeThickness !== thickness) + { + this.stroke = color; + this.strokeThickness = thickness; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the shadow settings. + * + * Calling this method always re-measures the parent Text object, + * so only call it when you actually change the shadow settings. + * + * @method Phaser.GameObjects.TextStyle#setShadow + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal shadow offset. + * @param {number} [y=0] - The vertical shadow offset. + * @param {string} [color='#000'] - The shadow color. + * @param {number} [blur=0] - The shadow blur radius. + * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. + * @param {boolean} [shadowFill=true] - Whether to fill the shadow. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadow: function (x, y, color, blur, shadowStroke, shadowFill) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = '#000'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = false; } + if (shadowFill === undefined) { shadowFill = true; } + + this.shadowOffsetX = x; + this.shadowOffsetY = y; + this.shadowColor = color; + this.shadowBlur = blur; + this.shadowStroke = shadowStroke; + this.shadowFill = shadowFill; + + return this.update(false); + }, + + /** + * Set the shadow offset. + * + * @method Phaser.GameObjects.TextStyle#setShadowOffset + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal shadow offset. + * @param {number} [y=0] - The vertical shadow offset. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowOffset: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.shadowOffsetX = x; + this.shadowOffsetY = y; + + return this.update(false); + }, + + /** + * Set the shadow color. + * + * @method Phaser.GameObjects.TextStyle#setShadowColor + * @since 3.0.0 + * + * @param {string} [color='#000'] - The shadow color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowColor: function (color) + { + if (color === undefined) { color = '#000'; } + + this.shadowColor = color; + + return this.update(false); + }, + + /** + * Set the shadow blur radius. + * + * @method Phaser.GameObjects.TextStyle#setShadowBlur + * @since 3.0.0 + * + * @param {number} [blur=0] - The shadow blur radius. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowBlur: function (blur) + { + if (blur === undefined) { blur = 0; } + + this.shadowBlur = blur; + + return this.update(false); + }, + + /** + * Enable or disable shadow stroke. + * + * @method Phaser.GameObjects.TextStyle#setShadowStroke + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow stroke is enabled or not. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowStroke: function (enabled) + { + this.shadowStroke = enabled; + + return this.update(false); + }, + + /** + * Enable or disable shadow fill. + * + * @method Phaser.GameObjects.TextStyle#setShadowFill + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow fill is enabled or not. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowFill: function (enabled) + { + this.shadowFill = enabled; + + return this.update(false); + }, + + /** + * Set the width (in pixels) to use for wrapping lines. + * + * Pass in null to remove wrapping by width. + * + * @method Phaser.GameObjects.TextStyle#setWordWrapWidth + * @since 3.0.0 + * + * @param {number} width - The maximum width of a line in pixels. Set to null to remove wrapping. + * @param {boolean} [useAdvancedWrap=false] - Whether or not to use the advanced wrapping + * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, + * spaces and whitespace are left as is. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setWordWrapWidth: function (width, useAdvancedWrap) + { + if (useAdvancedWrap === undefined) { useAdvancedWrap = false; } + + this.wordWrapWidth = width; + this.wordWrapUseAdvanced = useAdvancedWrap; + + return this.update(false); + }, + + /** + * Set a custom callback for wrapping lines. + * + * Pass in null to remove wrapping by callback. + * + * @method Phaser.GameObjects.TextStyle#setWordWrapCallback + * @since 3.0.0 + * + * @param {TextStyleWordWrapCallback} callback - A custom function that will be responsible for wrapping the + * text. It will receive two arguments: text (the string to wrap), textObject (this Text + * instance). It should return the wrapped lines either as an array of lines or as a string with + * newline characters in place to indicate where breaks should happen. + * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setWordWrapCallback: function (callback, scope) + { + if (scope === undefined) { scope = null; } + + this.wordWrapCallback = callback; + this.wordWrapCallbackScope = scope; + + return this.update(false); + }, + + /** + * Set the alignment of the text in this Text object. + * + * The argument can be one of: `left`, `right`, `center` or `justify`. + * + * Alignment only works if the Text object has more than one line of text. + * + * @method Phaser.GameObjects.TextStyle#setAlign + * @since 3.0.0 + * + * @param {string} [align='left'] - The text alignment for multi-line text. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setAlign: function (align) + { + if (align === undefined) { align = 'left'; } + + this.align = align; + + return this.update(false); + }, + + /** + * Set the maximum number of lines to draw. + * + * @method Phaser.GameObjects.TextStyle#setMaxLines + * @since 3.0.0 + * + * @param {integer} [max=0] - The maximum number of lines to draw. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setMaxLines: function (max) + { + if (max === undefined) { max = 0; } + + this.maxLines = max; + + return this.update(false); + }, + + /** + * Get the current text metrics. + * + * @method Phaser.GameObjects.TextStyle#getTextMetrics + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.Text.TextMetrics} The text metrics. + */ + getTextMetrics: function () + { + var metrics = this.metrics; + + return { + ascent: metrics.ascent, + descent: metrics.descent, + fontSize: metrics.fontSize + }; + }, + + /** + * Build a JSON representation of this Text Style. + * + * @method Phaser.GameObjects.TextStyle#toJSON + * @since 3.0.0 + * + * @return {object} A JSON representation of this Text Style. + */ + toJSON: function () + { + var output = {}; + + for (var key in propertyMap) + { + output[key] = this[key]; + } + + output.metrics = this.getTextMetrics(); + + return output; + }, + + /** + * Destroy this Text Style. + * + * @method Phaser.GameObjects.TextStyle#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.parent = undefined; + } + +}); + +module.exports = TextStyle; + + +/***/ }), +/* 1020 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = __webpack_require__(28); + +/** + * Calculates the ascent, descent and fontSize of a given font style. + * + * @function Phaser.GameObjects.Text.MeasureText + * @since 3.0.0 + * + * @param {Phaser.GameObjects.TextStyle} textStyle - The TextStyle object to measure. + * + * @return {Phaser.Types.GameObjects.Text.TextMetrics} An object containing the ascent, descent and fontSize of the TextStyle. + */ +var MeasureText = function (textStyle) +{ + // @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + var canvas = CanvasPool.create(this); + + // @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + var context = canvas.getContext('2d'); + + textStyle.syncFont(canvas, context); + + var width = Math.ceil(context.measureText(textStyle.testString).width * textStyle.baselineX); + var baseline = width; + var height = 2 * baseline; + + baseline = baseline * textStyle.baselineY | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = textStyle._font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(textStyle.testString, 0, baseline); + + var output = { + ascent: 0, + descent: 0, + fontSize: 0 + }; + + if (!context.getImageData(0, 0, width, height)) + { + output.ascent = baseline; + output.descent = baseline + 6; + output.fontSize = output.ascent + output.descent; + + CanvasPool.remove(canvas); + + return output; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + var i; + var j; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + output.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + output.descent = (i - baseline); + output.fontSize = output.ascent + output.descent; + + CanvasPool.remove(canvas); + + return output; +}; + +module.exports = MeasureText; + + +/***/ }), +/* 1021 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1022); +} + +if (true) +{ + renderCanvas = __webpack_require__(1023); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1022 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.TileSprite#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.TileSprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TileSpriteWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.updateCanvas(); + + var getTint = Utils.getTintAppendFloatAlpha; + + this.pipeline.batchTexture( + src, + src.fillPattern, + src.displayFrame.width * src.tileScaleX, src.displayFrame.height * src.tileScaleY, + src.x, src.y, + src.width, src.height, + src.scaleX, src.scaleY, + src.rotation, + src.flipX, src.flipY, + src.scrollFactorX, src.scrollFactorY, + src.originX * src.width, src.originY * src.height, + 0, 0, src.width, src.height, + getTint(src._tintTL, camera.alpha * src._alphaTL), + getTint(src._tintTR, camera.alpha * src._alphaTR), + getTint(src._tintBL, camera.alpha * src._alphaBL), + getTint(src._tintBR, camera.alpha * src._alphaBR), + (src._isTinted && src.tintFill), + (src.tilePositionX % src.displayFrame.width) / src.displayFrame.width, + (src.tilePositionY % src.displayFrame.height) / src.displayFrame.height, + camera, + parentMatrix + ); +}; + +module.exports = TileSpriteWebGLRenderer; + + +/***/ }), +/* 1023 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.TileSprite#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.TileSprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TileSpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.updateCanvas(); + + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = TileSpriteCanvasRenderer; + + +/***/ }), +/* 1024 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1025); +} + +if (true) +{ + renderCanvas = __webpack_require__(1026); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1025 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Video#renderWebGL + * @since 3.20.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Video} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var VideoWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (src.videoTexture) + { + this.pipeline.batchSprite(src, camera, parentMatrix); + } +}; + +module.exports = VideoWebGLRenderer; + + +/***/ }), +/* 1026 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Video#renderCanvas + * @since 3.20.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Video} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var VideoCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (src.videoTexture) + { + renderer.batchSprite(src, src.frame, camera, parentMatrix); + } +}; + +module.exports = VideoCanvasRenderer; + + +/***/ }), +/* 1027 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1028); +} + +if (true) +{ + renderCanvas = __webpack_require__(1029); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1028 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = __webpack_require__(111); +var StrokePathWebGL = __webpack_require__(75); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Arc#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Arc} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ArcWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = ArcWebGLRenderer; + + +/***/ }), +/* 1029 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DegToRad = __webpack_require__(40); +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Arc#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Arc} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ArcCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var radius = src.radius; + + ctx.beginPath(); + + ctx.arc( + (radius) - src.originX * (radius * 2), + (radius) - src.originY * (radius * 2), + radius, + DegToRad(src._startAngle), + DegToRad(src._endAngle), + src.anticlockwise + ); + + if (src.closePath) + { + ctx.closePath(); + } + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = ArcCanvasRenderer; + + +/***/ }), +/* 1030 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1031); +} + +if (true) +{ + renderCanvas = __webpack_require__(1032); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1031 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = __webpack_require__(111); +var StrokePathWebGL = __webpack_require__(75); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Curve#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Curve} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var CurveWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX + src._curveBounds.x; + var dy = src._displayOriginY + src._curveBounds.y; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = CurveWebGLRenderer; + + +/***/ }), +/* 1032 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Curve#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Curve} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var CurveCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX + src._curveBounds.x; + var dy = src._displayOriginY + src._curveBounds.y; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + if (src.closePath) + { + ctx.closePath(); + } + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = CurveCanvasRenderer; + + +/***/ }), +/* 1033 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1034); +} + +if (true) +{ + renderCanvas = __webpack_require__(1035); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1034 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = __webpack_require__(111); +var StrokePathWebGL = __webpack_require__(75); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Ellipse#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Ellipse} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var EllipseWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = EllipseWebGLRenderer; + + +/***/ }), +/* 1035 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Ellipse#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Ellipse} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var EllipseCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = EllipseCanvasRenderer; + + +/***/ }), +/* 1036 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1037); +} + +if (true) +{ + renderCanvas = __webpack_require__(1038); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1037 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Grid#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Grid} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var GridWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + calcMatrix.translate(-src._displayOriginX, -src._displayOriginY); + + var alpha = camera.alpha * src.alpha; + + // Work out the grid size + + var width = src.width; + var height = src.height; + + var cellWidth = src.cellWidth; + var cellHeight = src.cellHeight; + + var gridWidth = Math.ceil(width / cellWidth); + var gridHeight = Math.ceil(height / cellHeight); + + var cellWidthA = cellWidth; + var cellHeightA = cellHeight; + + var cellWidthB = cellWidth - ((gridWidth * cellWidth) - width); + var cellHeightB = cellHeight - ((gridHeight * cellHeight) - height); + + var fillTint; + var fillTintColor; + + var showCells = src.showCells; + var showAltCells = src.showAltCells; + var showOutline = src.showOutline; + + var x = 0; + var y = 0; + var r = 0; + var cw = 0; + var ch = 0; + + if (showOutline) + { + // To make room for the grid lines (in case alpha < 1) + cellWidthA--; + cellHeightA--; + + if (cellWidthB === cellWidth) + { + cellWidthB--; + } + + if (cellHeightB === cellHeight) + { + cellHeightB--; + } + } + + if (showCells && src.fillAlpha > 0) + { + fillTint = pipeline.fillTint; + fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && r) + { + r = 0; + continue; + } + + r++; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + pipeline.setTexture2D(); + + pipeline.batchFillRect( + x * cellWidth, + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showAltCells && src.altFillAlpha > 0) + { + fillTint = pipeline.fillTint; + fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.altFillColor, src.altFillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && !r) + { + r = 1; + continue; + } + + r = 0; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + pipeline.setTexture2D(); + + pipeline.batchFillRect( + x * cellWidth, + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showOutline && src.outlineFillAlpha > 0) + { + var strokeTint = pipeline.strokeTint; + var color = Utils.getTintAppendFloatAlphaAndSwap(src.outlineFillColor, src.outlineFillAlpha * alpha); + + strokeTint.TL = color; + strokeTint.TR = color; + strokeTint.BL = color; + strokeTint.BR = color; + + for (x = 1; x < gridWidth; x++) + { + var x1 = x * cellWidth; + + pipeline.setTexture2D(); + + pipeline.batchLine(x1, 0, x1, height, 1, 1, 1, 0, false); + } + + for (y = 1; y < gridHeight; y++) + { + var y1 = y * cellHeight; + + pipeline.setTexture2D(); + + pipeline.batchLine(0, y1, width, y1, 1, 1, 1, 0, false); + } + } +}; + +module.exports = GridWebGLRenderer; + + +/***/ }), +/* 1038 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Grid#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Grid} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var GridCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = -src._displayOriginX; + var dy = -src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + // Work out the grid size + + var width = src.width; + var height = src.height; + + var cellWidth = src.cellWidth; + var cellHeight = src.cellHeight; + + var gridWidth = Math.ceil(width / cellWidth); + var gridHeight = Math.ceil(height / cellHeight); + + var cellWidthA = cellWidth; + var cellHeightA = cellHeight; + + var cellWidthB = cellWidth - ((gridWidth * cellWidth) - width); + var cellHeightB = cellHeight - ((gridHeight * cellHeight) - height); + + var showCells = src.showCells; + var showAltCells = src.showAltCells; + var showOutline = src.showOutline; + + var x = 0; + var y = 0; + var r = 0; + var cw = 0; + var ch = 0; + + if (showOutline) + { + // To make room for the grid lines (in case alpha < 1) + cellWidthA--; + cellHeightA--; + + if (cellWidthB === cellWidth) + { + cellWidthB--; + } + + if (cellHeightB === cellHeight) + { + cellHeightB--; + } + } + + if (showCells && src.fillAlpha > 0) + { + FillStyleCanvas(ctx, src); + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && r) + { + r = 0; + continue; + } + + r++; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + ctx.fillRect( + dx + x * cellWidth, + dy + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showAltCells && src.altFillAlpha > 0) + { + FillStyleCanvas(ctx, src, src.altFillColor, src.altFillAlpha * alpha); + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && !r) + { + r = 1; + continue; + } + + r = 0; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + ctx.fillRect( + dx + x * cellWidth, + dy + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showOutline && src.outlineFillAlpha > 0) + { + LineStyleCanvas(ctx, src, src.outlineFillColor, src.outlineFillAlpha * alpha); + + for (x = 1; x < gridWidth; x++) + { + var x1 = x * cellWidth; + + ctx.beginPath(); + + ctx.moveTo(x1 + dx, dy); + ctx.lineTo(x1 + dx, height + dy); + + ctx.stroke(); + } + + for (y = 1; y < gridHeight; y++) + { + var y1 = y * cellHeight; + + ctx.beginPath(); + + ctx.moveTo(dx, y1 + dy); + ctx.lineTo(dx + width, y1 + dy); + + ctx.stroke(); + } + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = GridCanvasRenderer; + + +/***/ }), +/* 1039 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1040); +} + +if (true) +{ + renderCanvas = __webpack_require__(1041); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1040 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoBox#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.IsoBox} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoBoxWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + var alpha = camera.alpha * src.alpha; + + if (!src.isFilled) + { + return; + } + + var tint; + + var x0; + var y0; + + var x1; + var y1; + + var x2; + var y2; + + var x3; + var y3; + + // Top Face + + if (src.showTop) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); + + x0 = calcMatrix.getX(-sizeA, -height); + y0 = calcMatrix.getY(-sizeA, -height); + + x1 = calcMatrix.getX(0, -sizeB - height); + y1 = calcMatrix.getY(0, -sizeB - height); + + x2 = calcMatrix.getX(sizeA, -height); + y2 = calcMatrix.getY(sizeA, -height); + + x3 = calcMatrix.getX(0, sizeB - height); + y3 = calcMatrix.getY(0, sizeB - height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } + + // Left Face + + if (src.showLeft) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); + + x0 = calcMatrix.getX(-sizeA, 0); + y0 = calcMatrix.getY(-sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + + x3 = calcMatrix.getX(-sizeA, -height); + y3 = calcMatrix.getY(-sizeA, -height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } + + // Right Face + + if (src.showRight) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); + + x0 = calcMatrix.getX(sizeA, 0); + y0 = calcMatrix.getY(sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + + x3 = calcMatrix.getX(sizeA, -height); + y3 = calcMatrix.getY(sizeA, -height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } +}; + +module.exports = IsoBoxWebGLRenderer; + + +/***/ }), +/* 1041 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoBox#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.IsoBox} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoBoxCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) + { + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + // Top Face + + if (src.showTop) + { + FillStyleCanvas(ctx, src, src.fillTop); + + ctx.beginPath(); + + ctx.moveTo(-sizeA, -height); + ctx.lineTo(0, -sizeB - height); + ctx.lineTo(sizeA, -height); + ctx.lineTo(sizeA, -1); + ctx.lineTo(0, sizeB - 1); + ctx.lineTo(-sizeA, -1); + ctx.lineTo(-sizeA, -height); + + ctx.fill(); + } + + // Left Face + + if (src.showLeft) + { + FillStyleCanvas(ctx, src, src.fillLeft); + + ctx.beginPath(); + + ctx.moveTo(-sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + ctx.lineTo(-sizeA, -height); + ctx.lineTo(-sizeA, 0); + + ctx.fill(); + } + + // Right Face + + if (src.showRight) + { + FillStyleCanvas(ctx, src, src.fillRight); + + ctx.beginPath(); + + ctx.moveTo(sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + ctx.lineTo(sizeA, -height); + ctx.lineTo(sizeA, 0); + + ctx.fill(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = IsoBoxCanvasRenderer; + + +/***/ }), +/* 1042 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1043); +} + +if (true) +{ + renderCanvas = __webpack_require__(1044); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1043 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoTriangle#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.IsoTriangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoTriangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + var reversed = src.isReversed; + + var alpha = camera.alpha * src.alpha; + + if (!src.isFilled) + { + return; + } + + var tint; + + var x0; + var y0; + + var x1; + var y1; + + var x2; + var y2; + + // Top Face + + if (src.showTop && reversed) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); + + x0 = calcMatrix.getX(-sizeA, -height); + y0 = calcMatrix.getY(-sizeA, -height); + + x1 = calcMatrix.getX(0, -sizeB - height); + y1 = calcMatrix.getY(0, -sizeB - height); + + x2 = calcMatrix.getX(sizeA, -height); + y2 = calcMatrix.getY(sizeA, -height); + + var x3 = calcMatrix.getX(0, sizeB - height); + var y3 = calcMatrix.getY(0, sizeB - height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } + + // Left Face + + if (src.showLeft) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); + + if (reversed) + { + x0 = calcMatrix.getX(-sizeA, -height); + y0 = calcMatrix.getY(-sizeA, -height); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + else + { + x0 = calcMatrix.getX(-sizeA, 0); + y0 = calcMatrix.getY(-sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + + pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2); + } + + // Right Face + + if (src.showRight) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); + + if (reversed) + { + x0 = calcMatrix.getX(sizeA, -height); + y0 = calcMatrix.getY(sizeA, -height); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + else + { + x0 = calcMatrix.getX(sizeA, 0); + y0 = calcMatrix.getY(sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + + pipeline.setTexture2D(); + + pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2); + } +}; + +module.exports = IsoTriangleWebGLRenderer; + + +/***/ }), +/* 1044 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoTriangle#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.IsoTriangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoTriangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) + { + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + var reversed = src.isReversed; + + // Top Face + + if (src.showTop && reversed) + { + FillStyleCanvas(ctx, src, src.fillTop); + + ctx.beginPath(); + + ctx.moveTo(-sizeA, -height); + ctx.lineTo(0, -sizeB - height); + ctx.lineTo(sizeA, -height); + ctx.lineTo(0, sizeB - height); + + ctx.fill(); + } + + // Left Face + + if (src.showLeft) + { + FillStyleCanvas(ctx, src, src.fillLeft); + + ctx.beginPath(); + + if (reversed) + { + ctx.moveTo(-sizeA, -height); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + else + { + ctx.moveTo(-sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + + ctx.fill(); + } + + // Right Face + + if (src.showRight) + { + FillStyleCanvas(ctx, src, src.fillRight); + + ctx.beginPath(); + + if (reversed) + { + ctx.moveTo(sizeA, -height); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + else + { + ctx.moveTo(sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + + ctx.fill(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = IsoTriangleCanvasRenderer; + + +/***/ }), +/* 1045 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1046); +} + +if (true) +{ + renderCanvas = __webpack_require__(1047); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1046 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Line#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var LineWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + var alpha = camera.alpha * src.alpha; + + if (src.isStroked) + { + var strokeTint = pipeline.strokeTint; + var color = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); + + strokeTint.TL = color; + strokeTint.TR = color; + strokeTint.BL = color; + strokeTint.BR = color; + + var startWidth = src._startWidth; + var endWidth = src._endWidth; + + pipeline.setTexture2D(); + + pipeline.batchLine( + src.geom.x1 - dx, + src.geom.y1 - dy, + src.geom.x2 - dx, + src.geom.y2 - dy, + startWidth, + endWidth, + 1, + 0, + false, + shapeMatrix, + camMatrix + ); + } +}; + +module.exports = LineWebGLRenderer; + + +/***/ }), +/* 1047 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Line#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var LineCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.beginPath(); + + ctx.moveTo(src.geom.x1 - dx, src.geom.y1 - dy); + ctx.lineTo(src.geom.x2 - dx, src.geom.y2 - dy); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = LineCanvasRenderer; + + +/***/ }), +/* 1048 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1049); +} + +if (true) +{ + renderCanvas = __webpack_require__(1050); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1049 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = __webpack_require__(111); +var StrokePathWebGL = __webpack_require__(75); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Polygon#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Polygon} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var PolygonWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = PolygonWebGLRenderer; + + +/***/ }), +/* 1050 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Polygon#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Polygon} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var PolygonCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = PolygonCanvasRenderer; + + +/***/ }), +/* 1051 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1052); +} + +if (true) +{ + renderCanvas = __webpack_require__(1053); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1052 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var StrokePathWebGL = __webpack_require__(75); +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Rectangle#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Rectangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RectangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + var fillTint = pipeline.fillTint; + var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + pipeline.setTexture2D(); + + pipeline.batchFillRect( + -dx, + -dy, + src.width, + src.height + ); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = RectangleWebGLRenderer; + + +/***/ }), +/* 1053 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Rectangle#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Rectangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RectangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fillRect( + -dx, + -dy, + src.width, + src.height + ); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.beginPath(); + + ctx.rect( + -dx, + -dy, + src.width, + src.height + ); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = RectangleCanvasRenderer; + + +/***/ }), +/* 1054 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1055); +} + +if (true) +{ + renderCanvas = __webpack_require__(1056); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1055 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = __webpack_require__(111); +var StrokePathWebGL = __webpack_require__(75); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Star#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Star} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var StarWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = StarWebGLRenderer; + + +/***/ }), +/* 1056 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Star#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Star} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var StarCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = StarCanvasRenderer; + + +/***/ }), +/* 1057 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1058); +} + +if (true) +{ + renderCanvas = __webpack_require__(1059); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1058 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var StrokePathWebGL = __webpack_require__(75); +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Triangle#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Triangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TriangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + var fillTint = pipeline.fillTint; + var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + var x1 = src.geom.x1 - dx; + var y1 = src.geom.y1 - dy; + var x2 = src.geom.x2 - dx; + var y2 = src.geom.y2 - dy; + var x3 = src.geom.x3 - dx; + var y3 = src.geom.y3 - dy; + + pipeline.setTexture2D(); + + pipeline.batchFillTriangle( + x1, + y1, + x2, + y2, + x3, + y3, + shapeMatrix, + camMatrix + ); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = TriangleWebGLRenderer; + + +/***/ }), +/* 1059 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = __webpack_require__(41); +var LineStyleCanvas = __webpack_require__(57); +var SetTransform = __webpack_require__(29); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Triangle#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Triangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TriangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var x1 = src.geom.x1 - dx; + var y1 = src.geom.y1 - dy; + var x2 = src.geom.x2 - dx; + var y2 = src.geom.y2 - dy; + var x3 = src.geom.x3 - dx; + var y3 = src.geom.y3 - dy; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.lineTo(x3, y3); + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = TriangleCanvasRenderer; + + +/***/ }), +/* 1060 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Blitter = __webpack_require__(201); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Blitter Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Blitter Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#blitter + * @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} key - The key of the Texture the Blitter object will use. + * @param {(string|integer)} [frame] - The default Frame children of the Blitter will use. + * + * @return {Phaser.GameObjects.Blitter} The Game Object that was created. + */ +GameObjectFactory.register('blitter', function (x, y, key, frame) +{ + return this.displayList.add(new Blitter(this.scene, x, y, key, frame)); +}); + +// 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 + + +/***/ }), +/* 1061 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Container = __webpack_require__(202); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Container Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Container Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#container + * @since 3.4.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 {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to this Container. + * + * @return {Phaser.GameObjects.Container} The Game Object that was created. + */ +GameObjectFactory.register('container', function (x, y, children) +{ + return this.displayList.add(new Container(this.scene, x, y, children)); +}); + + +/***/ }), +/* 1062 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DOMElement = __webpack_require__(418); +var GameObjectFactory = __webpack_require__(6); + +/** + * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. + * + * In order for DOM Elements to display you have to enable them by adding the following to your game + * configuration object: + * + * ```javascript + * dom { + * createContainer: true + * } + * ``` + * + * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top + * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of + * settings within the Scale Manager, the dom container is resized accordingly. + * + * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing + * Element that you wish to be placed under the control of Phaser. For example: + * + * ```javascript + * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); + * ``` + * + * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in + * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, + * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + * + * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control + * alignment and positioning of the elements next to regular game content. + * + * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the + * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other + * methods available in this class to help construct your elements. + * + * Once the element has been created you can then control it like you would any other Game Object. You can set its + * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped + * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that + * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have + * a DOM Element, then a Sprite, then another DOM Element behind it. + * + * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event + * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas + * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you + * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. + * + * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. + * + * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert + * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. + * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and + * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top + * of your game, and should treat it accordingly. + * + * Note: This method will only be available if the DOM Element Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#dom + * @since 3.17.0 + * + * @param {number} x - The horizontal position of this DOM Element in the world. + * @param {number} y - The vertical position of this DOM Element in the world. + * @param {(HTMLElement|string)} [element] - An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. + * @param {(string|any)} [style] - If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. + * @param {string} [innerText] - If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. + * + * @return {Phaser.GameObjects.DOMElement} The Game Object that was created. + */ +GameObjectFactory.register('dom', function (x, y, element, style, innerText) +{ + var gameObject = new DOMElement(this.scene, x, y, element, style, innerText); + + this.displayList.add(gameObject); + this.updateList.add(gameObject); + + return gameObject; +}); + + +/***/ }), +/* 1063 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DynamicBitmapText = __webpack_require__(203); +var GameObjectFactory = __webpack_require__(6); + +/** + * 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 for 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): 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. + */ +GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size) +{ + return this.displayList.add(new DynamicBitmapText(this.scene, x, y, font, text, size)); +}); + +// 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 + + +/***/ }), +/* 1064 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extern = __webpack_require__(420); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Extern Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Extern Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#extern + * @since 3.16.0 + * + * @return {Phaser.GameObjects.Extern} The Game Object that was created. + */ +GameObjectFactory.register('extern', function () +{ + var extern = new Extern(this.scene); + + this.displayList.add(extern); + this.updateList.add(extern); + + return extern; +}); + +// 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 + + +/***/ }), +/* 1065 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Graphics = __webpack_require__(204); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Graphics Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Graphics Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#graphics + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Graphics.Options} [config] - The Graphics configuration. + * + * @return {Phaser.GameObjects.Graphics} The Game Object that was created. + */ +GameObjectFactory.register('graphics', function (config) +{ + return this.displayList.add(new Graphics(this.scene, config)); +}); + +// 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 + + +/***/ }), +/* 1066 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Group = __webpack_require__(109); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Group Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Group Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#group + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupConfig[])} [children] - Game Objects to add to this Group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - A Group Configuration object. + * + * @return {Phaser.GameObjects.Group} The Game Object that was created. + */ +GameObjectFactory.register('group', function (children, config) +{ + return this.updateList.add(new Group(this.scene, children, config)); +}); + + +/***/ }), +/* 1067 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Image = __webpack_require__(89); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Image Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#image + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Image} The Game Object that was created. + */ +GameObjectFactory.register('image', function (x, y, key, frame) +{ + return this.displayList.add(new Image(this.scene, x, y, key, frame)); +}); + +// 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 + + +/***/ }), +/* 1068 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var ParticleEmitterManager = __webpack_require__(207); + +/** + * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Particles Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#particles + * @since 3.0.0 + * + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer|object)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} The Game Object that was created. + */ +GameObjectFactory.register('particles', function (key, frame, emitters) +{ + var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); + + this.displayList.add(manager); + this.updateList.add(manager); + + return manager; +}); + +// 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 + + +/***/ }), +/* 1069 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var PathFollower = __webpack_require__(432); + +/** + * Creates a new PathFollower Game Object and adds it to the Scene. + * + * Note: This method will only be available if the PathFollower Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#follower + * @since 3.0.0 + * + * @param {Phaser.Curves.Path} path - The Path this PathFollower is connected to. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.PathFollower} The Game Object that was created. + */ +GameObjectFactory.register('follower', function (path, x, y, key, frame) +{ + var sprite = new PathFollower(this.scene, path, x, y, key, frame); + + this.displayList.add(sprite); + this.updateList.add(sprite); + + return sprite; +}); + +// 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 + + +/***/ }), +/* 1070 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var RenderTexture = __webpack_require__(208); + +/** + * Creates a new Render Texture Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. + * + * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and + * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic + * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. + * + * @method Phaser.GameObjects.GameObjectFactory#renderTexture + * @since 3.2.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 {integer} [width=32] - The width of the Render Texture. + * @param {integer} [height=32] - The height of the Render Texture. + * @property {string} [key] - The texture key to make the RenderTexture from. + * @property {string} [frame] - the frame to make the RenderTexture from. + * + * @return {Phaser.GameObjects.RenderTexture} The Game Object that was created. + */ +GameObjectFactory.register('renderTexture', function (x, y, width, height, key, frame) +{ + return this.displayList.add(new RenderTexture(this.scene, x, y, width, height, key, frame)); +}); + + +/***/ }), +/* 1071 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Sprite = __webpack_require__(65); + +/** + * Creates a new Sprite Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Sprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#sprite + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Sprite} The Game Object that was created. + */ +GameObjectFactory.register('sprite', function (x, y, key, frame) +{ + var sprite = new Sprite(this.scene, x, y, key, frame); + + this.displayList.add(sprite); + this.updateList.add(sprite); + + return sprite; +}); + +// 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 + + +/***/ }), +/* 1072 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = __webpack_require__(138); +var GameObjectFactory = __webpack_require__(6); + +/** + * 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 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): 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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. + * + * @return {Phaser.GameObjects.BitmapText} The Game Object that was created. + */ +GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align) +{ + return this.displayList.add(new BitmapText(this.scene, x, y, font, text, size, align)); +}); + +// 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 + + +/***/ }), +/* 1073 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Text = __webpack_require__(210); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Text Game Object and adds it to the Scene. + * + * 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. + * + * You can only display fonts that are currently loaded and available to the browser: therefore fonts must + * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, + * or have the fonts ready 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 {object} [style] - The Text style configuration object. + * + * @return {Phaser.GameObjects.Text} The Game Object that was created. + */ +GameObjectFactory.register('text', function (x, y, text, style) +{ + return this.displayList.add(new Text(this.scene, x, y, text, style)); +}); + +// 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 + + +/***/ }), +/* 1074 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TileSprite = __webpack_require__(211); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new TileSprite Game Object and adds it to the Scene. + * + * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#tileSprite + * @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 {integer} width - The width of the Game Object. If zero it will use the size of the texture frame. + * @param {integer} height - The height of the Game Object. If zero it will use the size of the texture frame. + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.TileSprite} The Game Object that was created. + */ +GameObjectFactory.register('tileSprite', function (x, y, width, height, key, frame) +{ + return this.displayList.add(new TileSprite(this.scene, x, y, width, height, key, frame)); +}); + +// 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 + + +/***/ }), +/* 1075 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Zone = __webpack_require__(118); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Zone Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Zone Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#zone + * @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 {number} width - The width of the Game Object. + * @param {number} height - The height of the Game Object. + * + * @return {Phaser.GameObjects.Zone} The Game Object that was created. + */ +GameObjectFactory.register('zone', function (x, y, width, height) +{ + return this.displayList.add(new Zone(this.scene, x, y, width, height)); +}); + +// 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 + + +/***/ }), +/* 1076 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Video = __webpack_require__(212); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Image Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Image 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Image} The Game Object that was created. + */ +GameObjectFactory.register('video', function (x, y, key) +{ + var video = new Video(this.scene, x, y, key); + + this.displayList.add(video); + this.updateList.add(video); + + return video; +}); + +// 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 + + +/***/ }), +/* 1077 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Arc = __webpack_require__(433); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Arc Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Arc Game Object has been built into Phaser. + * + * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an arc shape. You can control the start and end angles of the arc, + * as well as if the angles are winding clockwise or anti-clockwise. With the default settings + * it renders as a complete circle. By changing the angles you can create other arc shapes, + * such as half-circles. + * + * @method Phaser.GameObjects.GameObjectFactory#arc + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [radius=128] - The radius of the arc. + * @param {integer} [startAngle=0] - The start angle of the arc, in degrees. + * @param {integer} [endAngle=360] - The end angle of the arc, in degrees. + * @param {boolean} [anticlockwise=false] - The winding order of the start and end angles. + * @param {number} [fillColor] - The color the arc will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Arc} The Game Object that was created. + */ +GameObjectFactory.register('arc', function (x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) +{ + return this.displayList.add(new Arc(this.scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha)); +}); + +/** + * Creates a new Circle Shape Game Object and adds it to the Scene. + * + * A Circle is an Arc with no defined start and end angle, making it render as a complete circle. + * + * Note: This method will only be available if the Arc Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#circle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [radius=128] - The radius of the circle. + * @param {number} [fillColor] - The color the circle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the circle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Arc} The Game Object that was created. + */ +GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlpha) +{ + return this.displayList.add(new Arc(this.scene, x, y, radius, 0, 360, false, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1078 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Curve = __webpack_require__(434); + +/** + * Creates a new Curve Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Curve Game Object has been built into Phaser. + * + * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to + * the Curve Shape in the constructor. + * + * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @method Phaser.GameObjects.GameObjectFactory#curve + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {Phaser.Curves.Curve} [curve] - The Curve object to use to create the Shape. + * @param {number} [fillColor] - The color the curve will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Curve} The Game Object that was created. + */ +GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) +{ + return this.displayList.add(new Curve(this.scene, x, y, curve, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1079 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Ellipse = __webpack_require__(435); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Ellipse Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Ellipse Game Object has been built into Phaser. + * + * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. + * If the width and height match it will render as a circle. If the width is less than the height, + * it will look more like an egg shape. + * + * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @method Phaser.GameObjects.GameObjectFactory#ellipse + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [height=128] - The height of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [fillColor] - The color the ellipse will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Ellipse} The Game Object that was created. + */ +GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, fillAlpha) +{ + return this.displayList.add(new Ellipse(this.scene, x, y, width, height, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1080 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Grid = __webpack_require__(436); + +/** + * Creates a new Grid Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Grid Game Object has been built into Phaser. + * + * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * A Grid Shape allows you to display a grid in your game, where you can control the size of the + * grid as well as the width and height of the grid cells. You can set a fill color for each grid + * cell as well as an alternate fill color. When the alternate fill color is set then the grid + * cells will alternate the fill colors as they render, creating a chess-board effect. You can + * also optionally have an outline fill color. If set, this draws lines between the grid cells + * in the given color. If you specify an outline color with an alpha of zero, then it will draw + * the cells spaced out, but without the lines between them. + * + * @method Phaser.GameObjects.GameObjectFactory#grid + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the grid. + * @param {number} [height=128] - The height of the grid. + * @param {number} [cellWidth=32] - The width of one cell in the grid. + * @param {number} [cellHeight=32] - The height of one cell in the grid. + * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * @param {number} [outlineFillColor] - The color of the lines between the grid cells. + * @param {number} [outlineFillAlpha] - The alpha of the lines between the grid cells. + * + * @return {Phaser.GameObjects.Grid} The Game Object that was created. + */ +GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) +{ + return this.displayList.add(new Grid(this.scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha)); +}); + + +/***/ }), +/* 1081 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var IsoBox = __webpack_require__(437); + +/** + * Creates a new IsoBox Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the IsoBox Game Object has been built into Phaser. + * + * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set + * the color of the top, left and right faces of the rectangle respectively. You can also choose + * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting + * the `projection` property. + * + * @method Phaser.GameObjects.GameObjectFactory#isobox + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso box in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso box. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso box. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso box. + * + * @return {Phaser.GameObjects.IsoBox} The Game Object that was created. + */ +GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fillLeft, fillRight) +{ + return this.displayList.add(new IsoBox(this.scene, x, y, size, height, fillTop, fillLeft, fillRight)); +}); + + +/***/ }), +/* 1082 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var IsoTriangle = __webpack_require__(438); + +/** + * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser. + * + * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different + * fill color. You can set the color of the top, left and right faces of the triangle respectively + * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting + * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside + * down or not. + * + * @method Phaser.GameObjects.GameObjectFactory#isotriangle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. + * @param {boolean} [reversed=false] - Is the iso triangle upside down? + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle. + * + * @return {Phaser.GameObjects.IsoTriangle} The Game Object that was created. + */ +GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed, fillTop, fillLeft, fillRight) +{ + return this.displayList.add(new IsoTriangle(this.scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight)); +}); + + +/***/ }), +/* 1083 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Line = __webpack_require__(439); + +/** + * Creates a new Line Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Line Game Object has been built into Phaser. + * + * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only stroke colors and cannot be filled. + * + * A Line Shape allows you to draw a line between two points in your game. You can control the + * stroke color and thickness of the line. In WebGL only you can also specify a different + * thickness for the start and end of the line, allowing you to render lines that taper-off. + * + * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. + * + * @method Phaser.GameObjects.GameObjectFactory#line + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the start of the line. + * @param {number} [y1=0] - The vertical position of the start of the line. + * @param {number} [x2=128] - The horizontal position of the end of the line. + * @param {number} [y2=0] - The vertical position of the end of the line. + * @param {number} [strokeColor] - The color the line will be drawn in, i.e. 0xff0000 for red. + * @param {number} [strokeAlpha] - The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Line} The Game Object that was created. + */ +GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) +{ + return this.displayList.add(new Line(this.scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha)); +}); + + +/***/ }), +/* 1084 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Polygon = __webpack_require__(440); + +/** + * Creates a new Polygon Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Polygon Game Object has been built into Phaser. + * + * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Polygon Shape is created by providing a list of points, which are then used to create an + * internal Polygon geometry object. The points can be set from a variety of formats: + * + * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending + * on the coordinates of the points provided, the final shape may be rendered offset from its origin. + * + * @method Phaser.GameObjects.GameObjectFactory#polygon + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {any} [points] - The points that make up the polygon. + * @param {number} [fillColor] - The color the polygon will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Polygon} The Game Object that was created. + */ +GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlpha) +{ + return this.displayList.add(new Polygon(this.scene, x, y, points, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1085 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Rectangle = __webpack_require__(445); + +/** + * Creates a new Rectangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Rectangle Game Object has been built into Phaser. + * + * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * You can change the size of the rectangle by changing the `width` and `height` properties. + * + * @method Phaser.GameObjects.GameObjectFactory#rectangle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the rectangle. + * @param {number} [height=128] - The height of the rectangle. + * @param {number} [fillColor] - The color the rectangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Rectangle} The Game Object that was created. + */ +GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor, fillAlpha) +{ + return this.displayList.add(new Rectangle(this.scene, x, y, width, height, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1086 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Star = __webpack_require__(446); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Star Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Star Game Object has been built into Phaser. + * + * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * As the name implies, the Star shape will display a star in your game. You can control several + * aspects of it including the number of points that constitute the star. The default is 5. If + * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky + * star shape. + * + * You can also control the inner and outer radius, which is how 'long' each point of the star is. + * Modify these values to create more interesting shapes. + * + * @method Phaser.GameObjects.GameObjectFactory#star + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [points=5] - The number of points on the star. + * @param {number} [innerRadius=32] - The inner radius of the star. + * @param {number} [outerRadius=64] - The outer radius of the star. + * @param {number} [fillColor] - The color the star will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Star} The Game Object that was created. + */ +GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) +{ + return this.displayList.add(new Star(this.scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1087 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var Triangle = __webpack_require__(447); + +/** + * Creates a new Triangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Triangle Game Object has been built into Phaser. + * + * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the + * position of each point of these lines. The triangle is always closed and cannot have an open + * face. If you require that, consider using a Polygon instead. + * + * @method Phaser.GameObjects.GameObjectFactory#triangle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the first point in the triangle. + * @param {number} [y1=128] - The vertical position of the first point in the triangle. + * @param {number} [x2=64] - The horizontal position of the second point in the triangle. + * @param {number} [y2=0] - The vertical position of the second point in the triangle. + * @param {number} [x3=128] - The horizontal position of the third point in the triangle. + * @param {number} [y3=128] - The vertical position of the third point in the triangle. + * @param {number} [fillColor] - The color the triangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Triangle} The Game Object that was created. + */ +GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) +{ + return this.displayList.add(new Triangle(this.scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha)); +}); + + +/***/ }), +/* 1088 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Blitter = __webpack_require__(201); +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); + +/** + * Creates a new Blitter Game Object and returns it. + * + * Note: This method will only be available if the Blitter Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#blitter + * @since 3.0.0 + * + * @param {object} 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.Blitter} The Game Object that was created. + */ +GameObjectCreator.register('blitter', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var blitter = new Blitter(this.scene, 0, 0, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, blitter, config); + + return blitter; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1089 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var Container = __webpack_require__(202); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); + +/** + * Creates a new Container Game Object and returns it. + * + * Note: This method will only be available if the Container Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#container + * @since 3.4.0 + * + * @param {object} 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.Container} The Game Object that was created. + */ +GameObjectCreator.register('container', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + + var container = new Container(this.scene, x, y); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, container, config); + + return container; +}); + + +/***/ }), +/* 1090 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = __webpack_require__(203); +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); + +/** + * Creates a new Dynamic Bitmap Text Game Object and returns it. + * + * Note: This method will only be available if the Dynamic Bitmap Text Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#dynamicBitmapText + * @since 3.0.0 + *² + * @param {Phaser.Types.GameObjects.BitmapText.BitmapTextConfig} 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.DynamicBitmapText} The Game Object that was created. + */ +GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var font = GetAdvancedValue(config, 'font', ''); + var text = GetAdvancedValue(config, 'text', ''); + var size = GetAdvancedValue(config, 'size', false); + + var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, bitmapText, config); + + return bitmapText; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1091 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = __webpack_require__(16); +var Graphics = __webpack_require__(204); + +/** + * Creates a new Graphics Game Object and returns it. + * + * Note: This method will only be available if the Graphics Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#graphics + * @since 3.0.0 + * + * @param {object} 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.Graphics} The Game Object that was created. + */ +GameObjectCreator.register('graphics', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + var graphics = new Graphics(this.scene, config); + + if (config.add) + { + this.scene.sys.displayList.add(graphics); + } + + return graphics; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1092 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = __webpack_require__(16); +var Group = __webpack_require__(109); + +/** + * Creates a new Group Game Object and returns it. + * + * Note: This method will only be available if the Group Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#group + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} config - The configuration object this Game Object will use to create itself. + * + * @return {Phaser.GameObjects.Group} The Game Object that was created. + */ +GameObjectCreator.register('group', function (config) +{ + return new Group(this.scene, null, config); +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1093 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Image = __webpack_require__(89); + +/** + * Creates a new Image Game Object and returns it. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#image + * @since 3.0.0 + * + * @param {object} 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.Image} The Game Object that was created. + */ +GameObjectCreator.register('image', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var image = new Image(this.scene, 0, 0, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, image, config); + + return image; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1094 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var GetFastValue = __webpack_require__(1); +var ParticleEmitterManager = __webpack_require__(207); + +/** + * Creates a new Particle Emitter Manager Game Object and returns it. + * + * 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 {object} 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.ParticleEmitterManager} The Game Object that was created. + */ +GameObjectCreator.register('particles', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + var emitters = GetFastValue(config, 'emitters', null); + + // frame is optional and can contain the emitters array or object if skipped + var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + var add = GetFastValue(config, 'add', false); + + if (add) + { + this.displayList.add(manager); + } + + this.updateList.add(manager); + + return manager; +}); + + +/***/ }), +/* 1095 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var RenderTexture = __webpack_require__(208); + +/** + * Creates a new Render Texture Game Object and returns it. + * + * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#renderTexture + * @since 3.2.0 + * + * @param {Phaser.Types.GameObjects.RenderTexture.RenderTextureConfig} 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.RenderTexture} The Game Object that was created. + */ +GameObjectCreator.register('renderTexture', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 32); + var height = GetAdvancedValue(config, 'height', 32); + var key = GetAdvancedValue(config, 'key', undefined); + var frame = GetAdvancedValue(config, 'frame', undefined); + + var renderTexture = new RenderTexture(this.scene, x, y, width, height, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, renderTexture, config); + + return renderTexture; +}); + + +/***/ }), +/* 1096 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var BuildGameObjectAnimation = __webpack_require__(416); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Sprite = __webpack_require__(65); + +/** + * Creates a new Sprite Game Object and returns it. + * + * Note: This method will only be available if the Sprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#sprite + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} 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.Sprite} The Game Object that was created. + */ +GameObjectCreator.register('sprite', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var sprite = new Sprite(this.scene, 0, 0, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, sprite, config); + + // Sprite specific config options: + + BuildGameObjectAnimation(sprite, config); + + return sprite; +}); + + +/***/ }), +/* 1097 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = __webpack_require__(138); +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var GetValue = __webpack_require__(5); + +/** + * Creates a new Bitmap Text Game Object and returns it. + * + * Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#bitmapText + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.BitmapText.BitmapTextConfig} 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.BitmapText} The Game Object that was created. + */ +GameObjectCreator.register('bitmapText', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var font = GetValue(config, 'font', ''); + var text = GetAdvancedValue(config, 'text', ''); + var size = GetAdvancedValue(config, 'size', false); + var align = GetValue(config, 'align', 0); + + var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size, align); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, bitmapText, config); + + return bitmapText; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1098 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Text = __webpack_require__(210); + +/** + * Creates a new Text Game Object and returns it. + * + * Note: This method will only be available if the Text Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#text + * @since 3.0.0 + * + * @param {object} 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.Text} The Game Object that was created. + */ +GameObjectCreator.register('text', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + // 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 ] + // } + + var content = GetAdvancedValue(config, 'text', ''); + var style = GetAdvancedValue(config, 'style', null); + + // Padding + // { padding: 2 } + // { padding: { x: , y: }} + // { padding: { left: , top: }} + // { padding: { left: , right: , top: , bottom: }} + + var padding = GetAdvancedValue(config, 'padding', null); + + if (padding !== null) + { + style.padding = padding; + } + + var text = new Text(this.scene, 0, 0, content, style); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, text, config); + + // Text specific config options: + + text.autoRound = GetAdvancedValue(config, 'autoRound', true); + text.resolution = GetAdvancedValue(config, 'resolution', 1); + + return text; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1099 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var TileSprite = __webpack_require__(211); + +/** + * Creates a new TileSprite Game Object and returns it. + * + * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#tileSprite + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.TileSprite.TileSpriteConfig} 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.TileSprite} The Game Object that was created. + */ +GameObjectCreator.register('tileSprite', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 512); + var height = GetAdvancedValue(config, 'height', 512); + var key = GetAdvancedValue(config, 'key', ''); + var frame = GetAdvancedValue(config, 'frame', ''); + + var tile = new TileSprite(this.scene, x, y, width, height, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, tile, config); + + return tile; +}); + + +/***/ }), +/* 1100 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Zone = __webpack_require__(118); + +/** + * Creates a new Zone Game Object and returns it. + * + * Note: This method will only be available if the Zone Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#zone + * @since 3.0.0 + * + * @param {object} config - The configuration object this Game Object will use to create itself. + * + * @return {Phaser.GameObjects.Zone} The Game Object that was created. + */ +GameObjectCreator.register('zone', function (config) +{ + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 1); + var height = GetAdvancedValue(config, 'height', width); + + return new Zone(this.scene, x, y, width, height); +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1101 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Video = __webpack_require__(212); + +/** + * Creates a new Video Game Object and returns it. + * + * Note: This method will only be available if the Video Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#video + * @since 3.20.0 + * + * @param {object} 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.Video} The Game Object that was created. + */ +GameObjectCreator.register('video', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + + var video = new Video(this.scene, 0, 0, key); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, video, config); + + return video; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1102 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1103); +} + +if (true) +{ + renderCanvas = __webpack_require__(1104); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1103 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Mesh#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Mesh} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var MeshWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + + var vertices = src.vertices; + var uvs = src.uv; + var colors = src.colors; + var alphas = src.alphas; + + var meshVerticesLength = vertices.length; + var vertexCount = Math.floor(meshVerticesLength * 0.5); + + if (pipeline.vertexCount + vertexCount > pipeline.vertexCapacity) + { + pipeline.flush(); + } + + pipeline.setTexture2D(texture, 0); + + var vertexViewF32 = pipeline.vertexViewF32; + var vertexViewU32 = pipeline.vertexViewU32; + + var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; + + var colorIndex = 0; + var tintEffect = src.tintFill; + + for (var i = 0; i < meshVerticesLength; i += 2) + { + var x = vertices[i + 0]; + var y = vertices[i + 1]; + + var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; + var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; + + if (camera.roundPixels) + { + tx = Math.round(tx); + ty = Math.round(ty); + } + + vertexViewF32[++vertexOffset] = tx; + vertexViewF32[++vertexOffset] = ty; + vertexViewF32[++vertexOffset] = uvs[i + 0]; + vertexViewF32[++vertexOffset] = uvs[i + 1]; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = Utils.getTintAppendFloatAlpha(colors[colorIndex], camera.alpha * alphas[colorIndex]); + + colorIndex++; + } + + pipeline.vertexCount += vertexCount; +}; + +module.exports = MeshWebGLRenderer; + + +/***/ }), +/* 1104 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a stub function for Mesh.Render. There is no Canvas renderer for Mesh objects. + * + * @method Phaser.GameObjects.Mesh#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Mesh} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var MeshCanvasRenderer = function () +{ +}; + +module.exports = MeshCanvasRenderer; + + +/***/ }), +/* 1105 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1106); +} + +if (true) +{ + renderCanvas = __webpack_require__(1107); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1106 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Shader#renderWebGL + * @since 3.17.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Shader} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ShaderWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (!src.shader) + { + return; + } + + var pipeline = renderer.currentPipeline; + + renderer.clearPipeline(); + + if (src.renderToTexture) + { + src.load(); + src.flush(); + } + else + { + var camMatrix = src._tempMatrix1; + var shapeMatrix = src._tempMatrix2; + var calcMatrix = src._tempMatrix3; + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + // Renderer size changed? + if (renderer.width !== src._rendererWidth || renderer.height !== src._rendererHeight) + { + src.projOrtho(0, renderer.width, renderer.height, 0); + } + + src.load(calcMatrix.matrix); + src.flush(); + } + + renderer.rebindPipeline(pipeline); +}; + +module.exports = ShaderWebGLRenderer; + + +/***/ }), +/* 1107 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a stub function for Shader.Render. There is no Canvas renderer for Shader objects. + * + * @method Phaser.GameObjects.Shader#renderCanvas + * @since 3.17.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Shader} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var ShaderCanvasRenderer = function () +{ +}; + +module.exports = ShaderCanvasRenderer; + + +/***/ }), +/* 1108 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Mesh = __webpack_require__(139); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Mesh Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#mesh + * @webglOnly + * @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 {number[]} vertices - An array containing the vertices data for this Mesh. + * @param {number[]} uv - An array containing the uv data for this Mesh. + * @param {number[]} colors - An array containing the color data for this Mesh. + * @param {number[]} alphas - An array containing the alpha data for this Mesh. + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Mesh} The Game Object that was created. + */ +if (true) +{ + GameObjectFactory.register('mesh', function (x, y, vertices, uv, colors, alphas, texture, frame) + { + return this.displayList.add(new Mesh(this.scene, x, y, vertices, uv, colors, alphas, texture, frame)); + }); +} + +// 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 + + +/***/ }), +/* 1109 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Quad = __webpack_require__(215); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Quad Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#quad + * @webglOnly + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Quad} The Game Object that was created. + */ +if (true) +{ + GameObjectFactory.register('quad', function (x, y, key, frame) + { + return this.displayList.add(new Quad(this.scene, x, y, key, frame)); + }); +} + +// 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 + + +/***/ }), +/* 1110 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Shader = __webpack_require__(216); +var GameObjectFactory = __webpack_require__(6); + +/** + * Creates a new Shader Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#shader + * @webglOnly + * @since 3.17.0 + * + * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the Game Object. + * @param {number} [height=128] - The height of the Game Object. + * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param {object} [textureData] - Optional additional texture data. + * + * @return {Phaser.GameObjects.Shader} The Game Object that was created. + */ +if (true) +{ + GameObjectFactory.register('shader', function (key, x, y, width, height, textures, textureData) + { + return this.displayList.add(new Shader(this.scene, key, x, y, width, height, textures, textureData)); + }); +} + + +/***/ }), +/* 1111 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var GetValue = __webpack_require__(5); +var Mesh = __webpack_require__(139); + +/** + * Creates a new Mesh Game Object and returns it. + * + * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#mesh + * @since 3.0.0 + * + * @param {object} 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.Mesh} The Game Object that was created. + */ +GameObjectCreator.register('mesh', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + var vertices = GetValue(config, 'vertices', []); + var colors = GetValue(config, 'colors', []); + var alphas = GetValue(config, 'alphas', []); + var uv = GetValue(config, 'uv', []); + + var mesh = new Mesh(this.scene, 0, 0, vertices, uv, colors, alphas, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, mesh, config); + + return mesh; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1112 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Quad = __webpack_require__(215); + +/** + * Creates a new Quad Game Object and returns it. + * + * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#quad + * @since 3.0.0 + * + * @param {object} 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.Quad} The Game Object that was created. + */ +GameObjectCreator.register('quad', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var quad = new Quad(this.scene, x, y, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, quad, config); + + return quad; +}); + + +/***/ }), +/* 1113 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = __webpack_require__(30); +var GameObjectCreator = __webpack_require__(16); +var GetAdvancedValue = __webpack_require__(15); +var Shader = __webpack_require__(216); + +/** + * Creates a new Shader Game Object and returns it. + * + * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#shader + * @since 3.17.0 + * + * @param {object} 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.Shader} The Game Object that was created. + */ +GameObjectCreator.register('shader', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 128); + var height = GetAdvancedValue(config, 'height', 128); + + var shader = new Shader(this.scene, key, x, y, width, height); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, shader, config); + + return shader; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + + +/***/ }), +/* 1114 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var LightsManager = __webpack_require__(452); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * A Scene plugin that provides a {@link Phaser.GameObjects.LightsManager} for the Light2D pipeline. + * + * Available from within a Scene via `this.lights`. + * + * Add Lights using the {@link Phaser.GameObjects.LightsManager#addLight} method: + * + * ```javascript + * // Enable the Lights Manager because it is disabled by default + * this.lights.enable(); + * + * // Create a Light at [400, 300] with a radius of 200 + * this.lights.addLight(400, 300, 200); + * ``` + * + * For Game Objects to be affected by the Lights when rendered, you will need to set them to use the `Light2D` pipeline like so: + * + * ```javascript + * sprite.setPipeline('Light2D'); + * ``` + * + * @class LightsPlugin + * @extends Phaser.GameObjects.LightsManager + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this Lights Plugin belongs to. + */ +var LightsPlugin = new Class({ + + Extends: LightsManager, + + initialize: + + function LightsPlugin (scene) + { + /** + * A reference to the Scene that this Lights Plugin belongs to. + * + * @name Phaser.GameObjects.LightsPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene's systems. + * + * @name Phaser.GameObjects.LightsPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + if (!scene.sys.settings.isBooted) + { + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + } + + LightsManager.call(this); + }, + + /** + * Boot the Lights Plugin. + * + * @method Phaser.GameObjects.LightsPlugin#boot + * @since 3.0.0 + */ + boot: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.SHUTDOWN, this.shutdown, this); + eventEmitter.on(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * Destroy the Lights Plugin. + * + * Cleans up all references. + * + * @method Phaser.GameObjects.LightsPlugin#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene = undefined; + this.systems = undefined; + } + +}); + +PluginCache.register('LightsPlugin', LightsPlugin, 'lights'); + +module.exports = LightsPlugin; + + +/***/ }), +/* 1115 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = __webpack_require__(71); + +Circle.Area = __webpack_require__(1116); +Circle.Circumference = __webpack_require__(286); +Circle.CircumferencePoint = __webpack_require__(158); +Circle.Clone = __webpack_require__(1117); +Circle.Contains = __webpack_require__(60); +Circle.ContainsPoint = __webpack_require__(1118); +Circle.ContainsRect = __webpack_require__(1119); +Circle.CopyFrom = __webpack_require__(1120); +Circle.Equals = __webpack_require__(1121); +Circle.GetBounds = __webpack_require__(1122); +Circle.GetPoint = __webpack_require__(284); +Circle.GetPoints = __webpack_require__(285); +Circle.Offset = __webpack_require__(1123); +Circle.OffsetPoint = __webpack_require__(1124); +Circle.Random = __webpack_require__(159); + +module.exports = Circle; + + +/***/ }), +/* 1116 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the area of the circle. + * + * @function Phaser.Geom.Circle.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the area of. + * + * @return {number} The area of the Circle. + */ +var Area = function (circle) +{ + return (circle.radius > 0) ? Math.PI * circle.radius * circle.radius : 0; +}; + +module.exports = Area; + + +/***/ }), +/* 1117 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = __webpack_require__(71); + +/** + * 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. + */ +var Clone = function (source) +{ + return new Circle(source.x, source.y, source.radius); +}; + +module.exports = Clone; + + +/***/ }), +/* 1118 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(60); + +/** + * Check to see if the Circle contains the given Point object. + * + * @function Phaser.Geom.Circle.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to check. + * @param {(Phaser.Geom.Point|object)} point - The Point object to check if it's within the Circle or not. + * + * @return {boolean} True if the Point coordinates are within the circle, otherwise false. + */ +var ContainsPoint = function (circle, point) +{ + return Contains(circle, point.x, point.y); +}; + +module.exports = ContainsPoint; + + +/***/ }), +/* 1119 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(60); + +/** + * Check to see if the Circle contains all four points of the given Rectangle object. + * + * @function Phaser.Geom.Circle.ContainsRect + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to check. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle object to check if it's within the Circle or not. + * + * @return {boolean} True if all of the Rectangle coordinates are within the circle, otherwise false. + */ +var ContainsRect = function (circle, rect) +{ + return ( + Contains(circle, rect.x, rect.y) && + Contains(circle, rect.right, rect.y) && + Contains(circle, rect.x, rect.bottom) && + Contains(circle, rect.right, rect.bottom) + ); +}; + +module.exports = ContainsRect; + + +/***/ }), +/* 1120 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copies the `x`, `y` and `radius` properties from the `source` Circle + * into the given `dest` Circle, then returns the `dest` Circle. + * + * @function Phaser.Geom.Circle.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Circle} O - [dest,$return] + * + * @param {Phaser.Geom.Circle} source - The source Circle to copy the values from. + * @param {Phaser.Geom.Circle} dest - The destination Circle to copy the values to. + * + * @return {Phaser.Geom.Circle} The destination Circle. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y, source.radius); +}; + +module.exports = CopyFrom; + + +/***/ }), +/* 1121 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compares the `x`, `y` and `radius` properties of the two given Circles. + * Returns `true` if they all match, otherwise returns `false`. + * + * @function Phaser.Geom.Circle.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The first Circle to compare. + * @param {Phaser.Geom.Circle} toCompare - The second Circle to compare. + * + * @return {boolean} `true` if the two Circles equal each other, otherwise `false`. + */ +var Equals = function (circle, toCompare) +{ + return ( + circle.x === toCompare.x && + circle.y === toCompare.y && + circle.radius === toCompare.radius + ); +}; + +module.exports = Equals; + + +/***/ }), +/* 1122 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +/** + * Returns the bounds of the Circle object. + * + * @function Phaser.Geom.Circle.GetBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the bounds from. + * @param {(Phaser.Geom.Rectangle|object)} [out] - A Rectangle, or rectangle-like object, to store the circle bounds in. If not given a new Rectangle will be created. + * + * @return {(Phaser.Geom.Rectangle|object)} The Rectangle object containing the Circles bounds. + */ +var GetBounds = function (circle, out) +{ + if (out === undefined) { out = new Rectangle(); } + + out.x = circle.left; + out.y = circle.top; + out.width = circle.diameter; + out.height = circle.diameter; + + return out; +}; + +module.exports = GetBounds; + + +/***/ }), +/* 1123 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Circle by the values given. + * + * @function Phaser.Geom.Circle.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Circle} O - [circle,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to be offset (translated.) + * @param {number} x - The amount to horizontally offset the Circle by. + * @param {number} y - The amount to vertically offset the Circle by. + * + * @return {Phaser.Geom.Circle} The Circle that was offset. + */ +var Offset = function (circle, x, y) +{ + circle.x += x; + circle.y += y; + + return circle; +}; + +module.exports = Offset; + + +/***/ }), +/* 1124 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Circle by the values given in the `x` and `y` properties of the Point object. + * + * @function Phaser.Geom.Circle.OffsetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Circle} O - [circle,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to be offset (translated.) + * @param {(Phaser.Geom.Point|object)} point - The Point object containing the values to offset the Circle by. + * + * @return {Phaser.Geom.Circle} The Circle that was offset. + */ +var OffsetPoint = function (circle, point) +{ + circle.x += point.x; + circle.y += point.y; + + return circle; +}; + +module.exports = OffsetPoint; + + +/***/ }), +/* 1125 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Ellipse = __webpack_require__(107); + +Ellipse.Area = __webpack_require__(1126); +Ellipse.Circumference = __webpack_require__(423); +Ellipse.CircumferencePoint = __webpack_require__(206); +Ellipse.Clone = __webpack_require__(1127); +Ellipse.Contains = __webpack_require__(108); +Ellipse.ContainsPoint = __webpack_require__(1128); +Ellipse.ContainsRect = __webpack_require__(1129); +Ellipse.CopyFrom = __webpack_require__(1130); +Ellipse.Equals = __webpack_require__(1131); +Ellipse.GetBounds = __webpack_require__(1132); +Ellipse.GetPoint = __webpack_require__(421); +Ellipse.GetPoints = __webpack_require__(422); +Ellipse.Offset = __webpack_require__(1133); +Ellipse.OffsetPoint = __webpack_require__(1134); +Ellipse.Random = __webpack_require__(167); + +module.exports = Ellipse; + + +/***/ }), +/* 1126 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the area of the Ellipse. + * + * @function Phaser.Geom.Ellipse.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the area of. + * + * @return {number} The area of the Ellipse. + */ +var Area = function (ellipse) +{ + if (ellipse.isEmpty()) + { + return 0; + } + + // units squared + return (ellipse.getMajorRadius() * ellipse.getMinorRadius() * Math.PI); +}; + +module.exports = Area; + + +/***/ }), +/* 1127 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Ellipse = __webpack_require__(107); + +/** + * 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 a ellipse-like object, with x, y, width and height properties. + * + * @return {Phaser.Geom.Ellipse} A clone of the source Ellipse. + */ +var Clone = function (source) +{ + return new Ellipse(source.x, source.y, source.width, source.height); +}; + +module.exports = Clone; + + +/***/ }), +/* 1128 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(108); + +/** + * Check to see if the Ellipse contains the given Point object. + * + * @function Phaser.Geom.Ellipse.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. + * @param {(Phaser.Geom.Point|object)} point - The Point object to check if it's within the Circle or not. + * + * @return {boolean} True if the Point coordinates are within the circle, otherwise false. + */ +var ContainsPoint = function (ellipse, point) +{ + return Contains(ellipse, point.x, point.y); +}; + +module.exports = ContainsPoint; + + +/***/ }), +/* 1129 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(108); + +/** + * Check to see if the Ellipse contains all four points of the given Rectangle object. + * + * @function Phaser.Geom.Ellipse.ContainsRect + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle object to check if it's within the Ellipse or not. + * + * @return {boolean} True if all of the Rectangle coordinates are within the ellipse, otherwise false. + */ +var ContainsRect = function (ellipse, rect) +{ + return ( + Contains(ellipse, rect.x, rect.y) && + Contains(ellipse, rect.right, rect.y) && + Contains(ellipse, rect.x, rect.bottom) && + Contains(ellipse, rect.right, rect.bottom) + ); +}; + +module.exports = ContainsRect; + + +/***/ }), +/* 1130 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copies the `x`, `y`, `width` and `height` properties from the `source` Ellipse + * into the given `dest` Ellipse, then returns the `dest` Ellipse. + * + * @function Phaser.Geom.Ellipse.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Ellipse} O - [dest,$return] + * + * @param {Phaser.Geom.Ellipse} source - The source Ellipse to copy the values from. + * @param {Phaser.Geom.Ellipse} dest - The destination Ellipse to copy the values to. + * + * @return {Phaser.Geom.Ellipse} The destination Ellipse. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y, source.width, source.height); +}; + +module.exports = CopyFrom; + + +/***/ }), +/* 1131 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compares the `x`, `y`, `width` and `height` properties of the two given Ellipses. + * Returns `true` if they all match, otherwise returns `false`. + * + * @function Phaser.Geom.Ellipse.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The first Ellipse to compare. + * @param {Phaser.Geom.Ellipse} toCompare - The second Ellipse to compare. + * + * @return {boolean} `true` if the two Ellipse equal each other, otherwise `false`. + */ +var Equals = function (ellipse, toCompare) +{ + return ( + ellipse.x === toCompare.x && + ellipse.y === toCompare.y && + ellipse.width === toCompare.width && + ellipse.height === toCompare.height + ); +}; + +module.exports = Equals; + + +/***/ }), +/* 1132 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +/** + * Returns the bounds of the Ellipse object. + * + * @function Phaser.Geom.Ellipse.GetBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the bounds from. + * @param {(Phaser.Geom.Rectangle|object)} [out] - A Rectangle, or rectangle-like object, to store the ellipse bounds in. If not given a new Rectangle will be created. + * + * @return {(Phaser.Geom.Rectangle|object)} The Rectangle object containing the Ellipse bounds. + */ +var GetBounds = function (ellipse, out) +{ + if (out === undefined) { out = new Rectangle(); } + + out.x = ellipse.left; + out.y = ellipse.top; + out.width = ellipse.width; + out.height = ellipse.height; + + return out; +}; + +module.exports = GetBounds; + + +/***/ }), +/* 1133 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Ellipse by the values given. + * + * @function Phaser.Geom.Ellipse.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Ellipse} O - [ellipse,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to be offset (translated.) + * @param {number} x - The amount to horizontally offset the Ellipse by. + * @param {number} y - The amount to vertically offset the Ellipse by. + * + * @return {Phaser.Geom.Ellipse} The Ellipse that was offset. + */ +var Offset = function (ellipse, x, y) +{ + ellipse.x += x; + ellipse.y += y; + + return ellipse; +}; + +module.exports = Offset; + + +/***/ }), +/* 1134 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Ellipse by the values given in the `x` and `y` properties of the Point object. + * + * @function Phaser.Geom.Ellipse.OffsetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Ellipse} O - [ellipse,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to be offset (translated.) + * @param {(Phaser.Geom.Point|object)} point - The Point object containing the values to offset the Ellipse by. + * + * @return {Phaser.Geom.Ellipse} The Ellipse that was offset. + */ +var OffsetPoint = function (ellipse, point) +{ + ellipse.x += point.x; + ellipse.y += point.y; + + return ellipse; +}; + +module.exports = OffsetPoint; + + +/***/ }), +/* 1135 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var CircleToCircle = __webpack_require__(217); + +/** + * Checks if two Circles intersect and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetCircleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circleA - The first Circle to check for intersection. + * @param {Phaser.Geom.Circle} circleB - The second Circle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetCircleToCircle = function (circleA, circleB, out) +{ + if (out === undefined) { out = []; } + + if (CircleToCircle(circleA, circleB)) + { + var x0 = circleA.x; + var y0 = circleA.y; + var r0 = circleA.radius; + + var x1 = circleB.x; + var y1 = circleB.y; + var r1 = circleB.radius; + + var coefficientA, coefficientB, coefficientC, lambda, x; + + if (y0 === y1) + { + x = ((r1 * r1) - (r0 * r0) - (x1 * x1) + (x0 * x0)) / (2 * (x0 - x1)); + + coefficientA = 1; + coefficientB = -2 * y1; + coefficientC = (x1 * x1) + (x * x) - (2 * x1 * x) + (y1 * y1) - (r1 * r1); + + lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); + + if (lambda === 0) + { + out.push(new Point(x, (-coefficientB / (2 * coefficientA)))); + } + else if (lambda > 0) + { + out.push(new Point(x, (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA))); + out.push(new Point(x, (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA))); + } + } + else + { + var v1 = (x0 - x1) / (y0 - y1); + var n = (r1 * r1 - r0 * r0 - x1 * x1 + x0 * x0 - y1 * y1 + y0 * y0) / (2 * (y0 - y1)); + + coefficientA = (v1 * v1) + 1; + coefficientB = (2 * y0 * v1) - (2 * n * v1) - (2 * x0); + coefficientC = (x0 * x0) + (y0 * y0) + (n * n) - (r0 * r0) - (2 * y0 * n); + + lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); + + if (lambda === 0) + { + x = (-coefficientB / (2 * coefficientA)); + out.push(new Point(x, (n - (x * v1)))); + } + else if (lambda > 0) + { + x = (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA); + out.push(new Point(x, (n - (x * v1)))); + x = (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA); + out.push(new Point(x, (n - (x * v1)))); + } + } + } + + return out; +}; + +module.exports = GetCircleToCircle; + + +/***/ }), +/* 1136 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLineToCircle = __webpack_require__(219); +var CircleToRectangle = __webpack_require__(218); + +/** + * Checks for intersection between a circle and a rectangle, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetCircleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to be checked. + * @param {Phaser.Geom.Rectangle} rect - The rectangle to be checked. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetCircleToRectangle = function (circle, rect, out) +{ + if (out === undefined) { out = []; } + + if (CircleToRectangle(circle, rect)) + { + var lineA = rect.getLineA(); + var lineB = rect.getLineB(); + var lineC = rect.getLineC(); + var lineD = rect.getLineD(); + + GetLineToCircle(lineA, circle, out); + GetLineToCircle(lineB, circle, out); + GetLineToCircle(lineC, circle, out); + GetLineToCircle(lineD, circle, out); + } + + return out; +}; + +module.exports = GetCircleToRectangle; + + +/***/ }), +/* 1137 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); +var RectangleToRectangle = __webpack_require__(140); + +/** + * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. + * + * If optional `output` parameter is omitted, new Rectangle object is created and returned. If there is intersection, it will contain intersection area. If there is no intersection, it wil be empty Rectangle (all values set to zero). + * + * If Rectangle object is passed as `output` and there is intersection, then intersection area data will be loaded into it and it will be returned. If there is no intersection, it will be returned without any change. + * + * @function Phaser.Geom.Intersects.GetRectangleIntersection + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [output,$return] + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle object. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle object. + * @param {Phaser.Geom.Rectangle} [output] - Optional Rectangle object. If given, the intersection data will be loaded into it (in case of no intersection, it will be left unchanged). Otherwise, new Rectangle object will be created and returned with either intersection data or empty (all values set to zero), if there is no intersection. + * + * @return {Phaser.Geom.Rectangle} A rectangle object with intersection data. + */ +var GetRectangleIntersection = function (rectA, rectB, output) +{ + if (output === undefined) { output = new Rectangle(); } + + if (RectangleToRectangle(rectA, rectB)) + { + output.x = Math.max(rectA.x, rectB.x); + output.y = Math.max(rectA.y, rectB.y); + output.width = Math.min(rectA.right, rectB.right) - output.x; + output.height = Math.min(rectA.bottom, rectB.bottom) - output.y; + } + + return output; +}; + +module.exports = GetRectangleIntersection; + + +/***/ }), +/* 1138 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLineToRectangle = __webpack_require__(221); +var RectangleToRectangle = __webpack_require__(140); + +/** + * Checks if two Rectangles intersect and returns the intersection points as a Point object array. + * + * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. As such, the two Rectangles are considered "solid". A Rectangle with no width or no height will never intersect another Rectangle. + * + * @function Phaser.Geom.Intersects.GetRectangleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetRectangleToRectangle = function (rectA, rectB, out) +{ + if (out === undefined) { out = []; } + + if (RectangleToRectangle(rectA, rectB)) + { + var lineA = rectA.getLineA(); + var lineB = rectA.getLineB(); + var lineC = rectA.getLineC(); + var lineD = rectA.getLineD(); + + GetLineToRectangle(lineA, rectB, out); + GetLineToRectangle(lineB, rectB, out); + GetLineToRectangle(lineC, rectB, out); + GetLineToRectangle(lineD, rectB, out); + } + + return out; +}; + +module.exports = GetRectangleToRectangle; + + +/***/ }), +/* 1139 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RectangleToTriangle = __webpack_require__(456); +var GetLineToRectangle = __webpack_require__(221); + +/** + * Checks for intersection between Rectangle shape and Triangle shape, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetRectangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - Rectangle object to test. + * @param {Phaser.Geom.Triangle} triangle - Triangle object to test. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetRectangleToTriangle = function (rect, triangle, out) +{ + if (out === undefined) { out = []; } + + if (RectangleToTriangle(rect, triangle)) + { + var lineA = triangle.getLineA(); + var lineB = triangle.getLineB(); + var lineC = triangle.getLineC(); + + GetLineToRectangle(lineA, rect, out); + GetLineToRectangle(lineB, rect, out); + GetLineToRectangle(lineC, rect, out); + } + + return out; +}; + +module.exports = GetRectangleToTriangle; + + +/***/ }), +/* 1140 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLineToCircle = __webpack_require__(219); +var TriangleToCircle = __webpack_require__(458); + +/** + * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. + * + * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. + * + * @function Phaser.Geom.Intersects.GetTriangleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check for intersection. + * @param {Phaser.Geom.Circle} circle - The Circle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetTriangleToCircle = function (triangle, circle, out) +{ + if (out === undefined) { out = []; } + + if (TriangleToCircle(triangle, circle)) + { + var lineA = triangle.getLineA(); + var lineB = triangle.getLineB(); + var lineC = triangle.getLineC(); + + GetLineToCircle(lineA, circle, out); + GetLineToCircle(lineB, circle, out); + GetLineToCircle(lineC, circle, out); + } + + return out; +}; + +module.exports = GetTriangleToCircle; + + +/***/ }), +/* 1141 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TriangleToTriangle = __webpack_require__(461); +var GetTriangleToLine = __webpack_require__(459); + +/** + * Checks if two Triangles intersect, and returns the intersection points as a Point object array. + * + * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". + * + * @function Phaser.Geom.Intersects.GetTriangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangleA - The first Triangle to check for intersection. + * @param {Phaser.Geom.Triangle} triangleB - The second Triangle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetTriangleToTriangle = function (triangleA, triangleB, out) +{ + if (out === undefined) { out = []; } + + if (TriangleToTriangle(triangleA, triangleB)) + { + var lineA = triangleB.getLineA(); + var lineB = triangleB.getLineB(); + var lineC = triangleB.getLineC(); + + GetTriangleToLine(triangleA, lineA, out); + GetTriangleToLine(triangleA, lineB, out); + GetTriangleToLine(triangleA, lineC, out); + } + + return out; +}; + +module.exports = GetTriangleToTriangle; + + +/***/ }), +/* 1142 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PointToLine = __webpack_require__(463); + +/** + * Checks if a Point is located on the given line segment. + * + * @function Phaser.Geom.Intersects.PointToLineSegment + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - The Point to check for intersection. + * @param {Phaser.Geom.Line} line - The line segment to check for intersection. + * + * @return {boolean} `true` if the Point is on the given line segment, otherwise `false`. + */ +var PointToLineSegment = function (point, line) +{ + if (!PointToLine(point, line)) + { + return false; + } + + var xMin = Math.min(line.x1, line.x2); + var xMax = Math.max(line.x1, line.x2); + var yMin = Math.min(line.y1, line.y2); + var yMax = Math.max(line.y1, line.y2); + + return ((point.x >= xMin && point.x <= xMax) && (point.y >= yMin && point.y <= yMax)); +}; + +module.exports = PointToLineSegment; + + +/***/ }), +/* 1143 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check if rectangle intersects with values. + * + * @function Phaser.Geom.Intersects.RectangleToValues + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle object + * @param {number} left - The x coordinate of the left of the Rectangle. + * @param {number} right - The x coordinate of the right of the Rectangle. + * @param {number} top - The y coordinate of the top of the Rectangle. + * @param {number} bottom - The y coordinate of the bottom of the Rectangle. + * @param {number} [tolerance=0] - Tolerance allowed in the calculation, expressed in pixels. + * + * @return {boolean} Returns true if there is an intersection. + */ +var RectangleToValues = function (rect, left, right, top, bottom, tolerance) +{ + if (tolerance === undefined) { tolerance = 0; } + + return !( + left > rect.right + tolerance || + right < rect.left - tolerance || + top > rect.bottom + tolerance || + bottom < rect.top - tolerance + ); +}; + +module.exports = RectangleToValues; + + +/***/ }), +/* 1144 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Line = __webpack_require__(61); + +Line.Angle = __webpack_require__(94); +Line.BresenhamPoints = __webpack_require__(307); +Line.CenterOn = __webpack_require__(1145); +Line.Clone = __webpack_require__(1146); +Line.CopyFrom = __webpack_require__(1147); +Line.Equals = __webpack_require__(1148); +Line.Extend = __webpack_require__(1149); +Line.GetMidPoint = __webpack_require__(1150); +Line.GetNearestPoint = __webpack_require__(1151); +Line.GetNormal = __webpack_require__(1152); +Line.GetPoint = __webpack_require__(294); +Line.GetPoints = __webpack_require__(162); +Line.GetShortestDistance = __webpack_require__(1153); +Line.Height = __webpack_require__(1154); +Line.Length = __webpack_require__(62); +Line.NormalAngle = __webpack_require__(464); +Line.NormalX = __webpack_require__(1155); +Line.NormalY = __webpack_require__(1156); +Line.Offset = __webpack_require__(1157); +Line.PerpSlope = __webpack_require__(1158); +Line.Random = __webpack_require__(163); +Line.ReflectAngle = __webpack_require__(1159); +Line.Rotate = __webpack_require__(1160); +Line.RotateAroundPoint = __webpack_require__(1161); +Line.RotateAroundXY = __webpack_require__(223); +Line.SetToAngle = __webpack_require__(1162); +Line.Slope = __webpack_require__(1163); +Line.Width = __webpack_require__(1164); + +module.exports = Line; + + +/***/ }), +/* 1145 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + + +/** + * Center a line on the given coordinates. + * + * @function Phaser.Geom.Line.CenterOn + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to center. + * @param {number} x - The horizontal coordinate to center the line on. + * @param {number} y - The vertical coordinate to center the line on. + * + * @return {Phaser.Geom.Line} The centered line. + */ +var CenterOn = function (line, x, y) +{ + var tx = x - ((line.x1 + line.x2) / 2); + var ty = y - ((line.y1 + line.y2) / 2); + + line.x1 += tx; + line.y1 += ty; + + line.x2 += tx; + line.y2 += ty; + + return line; +}; + +module.exports = CenterOn; + + +/***/ }), +/* 1146 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Line = __webpack_require__(61); + +/** + * Clone the given line. + * + * @function Phaser.Geom.Line.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} source - The source line to clone. + * + * @return {Phaser.Geom.Line} The cloned line. + */ +var Clone = function (source) +{ + return new Line(source.x1, source.y1, source.x2, source.y2); +}; + +module.exports = Clone; + + +/***/ }), +/* 1147 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one line to a destination line. + * + * @function Phaser.Geom.Line.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [dest,$return] + * + * @param {Phaser.Geom.Line} source - The source line to copy the values from. + * @param {Phaser.Geom.Line} dest - The destination line to copy the values to. + * + * @return {Phaser.Geom.Line} The destination line. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x1, source.y1, source.x2, source.y2); +}; + +module.exports = CopyFrom; + + +/***/ }), +/* 1148 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compare two lines for strict equality. + * + * @function Phaser.Geom.Line.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The first line to compare. + * @param {Phaser.Geom.Line} toCompare - The second line to compare. + * + * @return {boolean} Whether the two lines are equal. + */ +var Equals = function (line, toCompare) +{ + return ( + line.x1 === toCompare.x1 && + line.y1 === toCompare.y1 && + line.x2 === toCompare.x2 && + line.y2 === toCompare.y2 + ); +}; + +module.exports = Equals; + + +/***/ }), +/* 1149 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = __webpack_require__(62); + +/** + * Extends the start and end points of a Line by the given amounts. + * + * The amounts can be positive or negative. Positive points will increase the length of the line, + * while negative ones will decrease it. + * + * If no `right` value is provided it will extend the length of the line equally in both directions. + * + * Pass a value of zero to leave the start or end point unchanged. + * + * @function Phaser.Geom.Line.Extend + * @since 3.16.0 + * + * @param {Phaser.Geom.Line} line - The line instance to extend. + * @param {number} left - The amount to extend the start of the line by. + * @param {number} [right] - The amount to extend the end of the line by. If not given it will be set to the `left` value. + * + * @return {Phaser.Geom.Line} The modified Line instance. + */ +var Extend = function (line, left, right) +{ + if (right === undefined) { right = left; } + + var length = Length(line); + + var slopX = line.x2 - line.x1; + var slopY = line.y2 - line.y1; + + if (left) + { + line.x1 = line.x1 - slopX / length * left; + line.y1 = line.y1 - slopY / length * left; + } + + if (right) + { + line.x2 = line.x2 + slopX / length * right; + line.y2 = line.y2 + slopY / length * right; + } + + return line; +}; + +module.exports = Extend; + + +/***/ }), +/* 1150 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Get the midpoint of the given line. + * + * @function Phaser.Geom.Line.GetMidPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to get the midpoint of. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point object to store the midpoint in. + * + * @return {(Phaser.Geom.Point|object)} The midpoint of the Line. + */ +var GetMidPoint = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = (line.x1 + line.x2) / 2; + out.y = (line.y1 + line.y2) / 2; + + return out; +}; + +module.exports = GetMidPoint; + + +/***/ }), +/* 1151 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Florian Mertens + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Get the nearest point on a line perpendicular to the given point. + * + * @function Phaser.Geom.Line.GetNearestPoint + * @since 3.16.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to get the nearest point on. + * @param {(Phaser.Geom.Point|object)} point - The point to get the nearest point to. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the nearest point on the line. + * + * @return {(Phaser.Geom.Point|object)} The nearest point on the line. + */ +var GetNearestPoint = function (line, point, out) +{ + if (out === undefined) { out = new Point(); } + + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); + + if (L2 === 0) + { + return out; + } + + var r = (((point.x - x1) * (x2 - x1)) + ((point.y - y1) * (y2 - y1))) / L2; + + out.x = x1 + (r * (x2 - x1)); + out.y = y1 + (r * (y2 - y1)); + + return out; +}; + +module.exports = GetNearestPoint; + + +/***/ }), +/* 1152 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(94); +var Point = __webpack_require__(4); + +/** + * Calculate the normal of the given line. + * + * The normal of a line is a vector that points perpendicular from it. + * + * @function Phaser.Geom.Line.GetNormal + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to calculate the normal of. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point object to store the normal in. + * + * @return {(Phaser.Geom.Point|object)} The normal of the Line. + */ +var GetNormal = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + var a = Angle(line) - MATH_CONST.TAU; + + out.x = Math.cos(a); + out.y = Math.sin(a); + + return out; +}; + +module.exports = GetNormal; + + +/***/ }), +/* 1153 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @author Florian Mertens + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Get the shortest distance from a Line to the given Point. + * + * @function Phaser.Geom.Line.GetShortestDistance + * @since 3.16.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to get the distance from. + * @param {(Phaser.Geom.Point|object)} point - The point to get the shortest distance to. + * + * @return {number} The shortest distance from the line to the point. + */ +var GetShortestDistance = function (line, point) +{ + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); + + if (L2 === 0) + { + return false; + } + + var s = (((y1 - point.y) * (x2 - x1)) - ((x1 - point.x) * (y2 - y1))) / L2; + + return Math.abs(s) * Math.sqrt(L2); +}; + +module.exports = GetShortestDistance; + + +/***/ }), +/* 1154 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the height of the given line. + * + * @function Phaser.Geom.Line.Height + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the height of. + * + * @return {number} The height of the line. + */ +var Height = function (line) +{ + return Math.abs(line.y1 - line.y2); +}; + +module.exports = Height; + + +/***/ }), +/* 1155 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(94); + +/** + * [description] + * + * @function Phaser.Geom.Line.NormalX + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The Line object to get the normal value from. + * + * @return {number} [description] + */ +var NormalX = function (line) +{ + return Math.cos(Angle(line) - MATH_CONST.TAU); +}; + +module.exports = NormalX; + + +/***/ }), +/* 1156 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(94); + +/** + * The Y value of the normal of the given line. + * The normal of a line is a vector that points perpendicular from it. + * + * @function Phaser.Geom.Line.NormalY + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the normal of. + * + * @return {number} The Y value of the normal of the Line. + */ +var NormalY = function (line) +{ + return Math.sin(Angle(line) - MATH_CONST.TAU); +}; + +module.exports = NormalY; + + +/***/ }), +/* 1157 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offset a line by the given amount. + * + * @function Phaser.Geom.Line.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to offset. + * @param {number} x - The horizontal offset to add to the line. + * @param {number} y - The vertical offset to add to the line. + * + * @return {Phaser.Geom.Line} The offset line. + */ +var Offset = function (line, x, y) +{ + line.x1 += x; + line.y1 += y; + + line.x2 += x; + line.y2 += y; + + return line; +}; + +module.exports = Offset; + + +/***/ }), +/* 1158 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the perpendicular slope of the given line. + * + * @function Phaser.Geom.Line.PerpSlope + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the perpendicular slope of. + * + * @return {number} The perpendicular slope of the line. + */ +var PerpSlope = function (line) +{ + return -((line.x2 - line.x1) / (line.y2 - line.y1)); +}; + +module.exports = PerpSlope; + + +/***/ }), +/* 1159 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Angle = __webpack_require__(94); +var NormalAngle = __webpack_require__(464); + +/** + * Calculate the reflected angle between two lines. + * + * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. + * + * @function Phaser.Geom.Line.ReflectAngle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} lineA - The first line. + * @param {Phaser.Geom.Line} lineB - The second line. + * + * @return {number} The reflected angle between each line. + */ +var ReflectAngle = function (lineA, lineB) +{ + return (2 * NormalAngle(lineB) - Math.PI - Angle(lineA)); +}; + +module.exports = ReflectAngle; + + +/***/ }), +/* 1160 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = __webpack_require__(223); + +/** + * Rotate a line around its midpoint by the given angle in radians. + * + * @function Phaser.Geom.Line.Rotate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to rotate. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Line} The rotated line. + */ +var Rotate = function (line, angle) +{ + var x = (line.x1 + line.x2) / 2; + var y = (line.y1 + line.y2) / 2; + + return RotateAroundXY(line, x, y, angle); +}; + +module.exports = Rotate; + + +/***/ }), +/* 1161 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = __webpack_require__(223); + +/** + * Rotate a line around a point by the given angle in radians. + * + * @function Phaser.Geom.Line.RotateAroundPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to rotate. + * @param {(Phaser.Geom.Point|object)} point - The point to rotate the line around. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Line} The rotated line. + */ +var RotateAroundPoint = function (line, point, angle) +{ + return RotateAroundXY(line, point.x, point.y, angle); +}; + +module.exports = RotateAroundPoint; + + +/***/ }), +/* 1162 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Set a line to a given position, angle and length. + * + * @function Phaser.Geom.Line.SetToAngle + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to set. + * @param {number} x - The horizontal start position of the line. + * @param {number} y - The vertical start position of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line. + * + * @return {Phaser.Geom.Line} The updated line. + */ +var SetToAngle = function (line, x, y, angle, length) +{ + line.x1 = x; + line.y1 = y; + + line.x2 = x + (Math.cos(angle) * length); + line.y2 = y + (Math.sin(angle) * length); + + return line; +}; + +module.exports = SetToAngle; + + +/***/ }), +/* 1163 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the slope of the given line. + * + * @function Phaser.Geom.Line.Slope + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the slope of. + * + * @return {number} The slope of the line. + */ +var Slope = function (line) +{ + return (line.y2 - line.y1) / (line.x2 - line.x1); +}; + +module.exports = Slope; + + +/***/ }), +/* 1164 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the width of the given line. + * + * @function Phaser.Geom.Line.Width + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the width of. + * + * @return {number} The width of the line. + */ +var Width = function (line) +{ + return Math.abs(line.x1 - line.x2); +}; + +module.exports = Width; + + +/***/ }), +/* 1165 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +Point.Ceil = __webpack_require__(1166); +Point.Clone = __webpack_require__(1167); +Point.CopyFrom = __webpack_require__(1168); +Point.Equals = __webpack_require__(1169); +Point.Floor = __webpack_require__(1170); +Point.GetCentroid = __webpack_require__(1171); +Point.GetMagnitude = __webpack_require__(465); +Point.GetMagnitudeSq = __webpack_require__(466); +Point.GetRectangleFromPoints = __webpack_require__(1172); +Point.Interpolate = __webpack_require__(1173); +Point.Invert = __webpack_require__(1174); +Point.Negative = __webpack_require__(1175); +Point.Project = __webpack_require__(1176); +Point.ProjectUnit = __webpack_require__(1177); +Point.SetMagnitude = __webpack_require__(1178); + +module.exports = Point; + + +/***/ }), +/* 1166 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Apply `Math.ceil()` to each coordinate of the given Point. + * + * @function Phaser.Geom.Point.Ceil + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to ceil. + * + * @return {Phaser.Geom.Point} The Point with `Math.ceil()` applied to its coordinates. + */ +var Ceil = function (point) +{ + return point.setTo(Math.ceil(point.x), Math.ceil(point.y)); +}; + +module.exports = Ceil; + + +/***/ }), +/* 1167 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Clone the given Point. + * + * @function Phaser.Geom.Point.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} source - The source Point to clone. + * + * @return {Phaser.Geom.Point} The cloned Point. + */ +var Clone = function (source) +{ + return new Point(source.x, source.y); +}; + +module.exports = Clone; + + +/***/ }), +/* 1168 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one Point to a destination Point. + * + * @function Phaser.Geom.Point.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [dest,$return] + * + * @param {Phaser.Geom.Point} source - The source Point to copy the values from. + * @param {Phaser.Geom.Point} dest - The destination Point to copy the values to. + * + * @return {Phaser.Geom.Point} The destination Point. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y); +}; + +module.exports = CopyFrom; + + +/***/ }), +/* 1169 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A comparison of two `Point` objects to see if they are equal. + * + * @function Phaser.Geom.Point.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - The original `Point` to compare against. + * @param {Phaser.Geom.Point} toCompare - The second `Point` to compare. + * + * @return {boolean} Returns true if the both `Point` objects are equal. + */ +var Equals = function (point, toCompare) +{ + return (point.x === toCompare.x && point.y === toCompare.y); +}; + +module.exports = Equals; + + +/***/ }), +/* 1170 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Apply `Math.ceil()` to each coordinate of the given Point. + * + * @function Phaser.Geom.Point.Floor + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to floor. + * + * @return {Phaser.Geom.Point} The Point with `Math.floor()` applied to its coordinates. + */ +var Floor = function (point) +{ + return point.setTo(Math.floor(point.x), Math.floor(point.y)); +}; + +module.exports = Floor; + + +/***/ }), +/* 1171 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Get the centroid or geometric center of a plane figure (the arithmetic mean position of all the points in the figure). + * Informally, it is the point at which a cutout of the shape could be perfectly balanced on the tip of a pin. + * + * @function Phaser.Geom.Point.GetCentroid + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point[]} points - [description] + * @param {Phaser.Geom.Point} [out] - [description] + * + * @return {Phaser.Geom.Point} [description] + */ +var GetCentroid = function (points, out) +{ + if (out === undefined) { out = new Point(); } + + if (!Array.isArray(points)) + { + throw new Error('GetCentroid points argument must be an array'); + } + + var len = points.length; + + if (len < 1) + { + throw new Error('GetCentroid points array must not be empty'); + } + else if (len === 1) + { + out.x = points[0].x; + out.y = points[0].y; + } + else + { + for (var i = 0; i < len; i++) + { + out.x += points[i].x; + out.y += points[i].y; + } + + out.x /= len; + out.y /= len; + } + + return out; +}; + +module.exports = GetCentroid; + + +/***/ }), +/* 1172 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +/** + * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. + * + * @function Phaser.Geom.Point.GetRectangleFromPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Point[]} points - [description] + * @param {Phaser.Geom.Rectangle} [out] - [description] + * + * @return {Phaser.Geom.Rectangle} [description] + */ +var GetRectangleFromPoints = function (points, out) +{ + if (out === undefined) { out = new Rectangle(); } + + var xMax = Number.NEGATIVE_INFINITY; + var xMin = Number.POSITIVE_INFINITY; + var yMax = Number.NEGATIVE_INFINITY; + var yMin = Number.POSITIVE_INFINITY; + + for (var i = 0; i < points.length; i++) + { + var point = points[i]; + + if (point.x > xMax) + { + xMax = point.x; + } + + if (point.x < xMin) + { + xMin = point.x; + } + + if (point.y > yMax) + { + yMax = point.y; + } + + if (point.y < yMin) + { + yMin = point.y; + } + } + + out.x = xMin; + out.y = yMin; + out.width = xMax - xMin; + out.height = yMax - yMin; + + return out; +}; + +module.exports = GetRectangleFromPoints; + + +/***/ }), +/* 1173 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * [description] + * + * @function Phaser.Geom.Point.Interpolate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} pointA - The starting `Point` for the interpolation. + * @param {Phaser.Geom.Point} pointB - The target `Point` for the interpolation. + * @param {number} [t=0] - The amount to interpolate between the two points. Generally, a value between 0 (returns the starting `Point`) and 1 (returns the target `Point`). If omitted, 0 is used. + * @param {(Phaser.Geom.Point|object)} [out] - An optional `Point` object whose `x` and `y` values will be set to the result of the interpolation (can also be any object with `x` and `y` properties). If omitted, a new `Point` created and returned. + * + * @return {(Phaser.Geom.Point|object)} Either the object from the `out` argument with the properties `x` and `y` set to the result of the interpolation or a newly created `Point` object. + */ +var Interpolate = function (pointA, pointB, t, out) +{ + if (t === undefined) { t = 0; } + if (out === undefined) { out = new Point(); } + + out.x = pointA.x + ((pointB.x - pointA.x) * t); + out.y = pointA.y + ((pointB.y - pointA.y) * t); + + return out; +}; + +module.exports = Interpolate; + + +/***/ }), +/* 1174 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Swaps the X and the Y coordinate of a point. + * + * @function Phaser.Geom.Point.Invert + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to modify. + * + * @return {Phaser.Geom.Point} The modified `point`. + */ +var Invert = function (point) +{ + return point.setTo(point.y, point.x); +}; + +module.exports = Invert; + + +/***/ }), +/* 1175 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Inverts a Point's coordinates. + * + * @function Phaser.Geom.Point.Negative + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} point - The Point to invert. + * @param {Phaser.Geom.Point} [out] - The Point to return the inverted coordinates in. + * + * @return {Phaser.Geom.Point} The modified `out` Point, or a new Point if none was provided. + */ +var Negative = function (point, out) +{ + if (out === undefined) { out = new Point(); } + + return out.setTo(-point.x, -point.y); +}; + +module.exports = Negative; + + +/***/ }), +/* 1176 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var GetMagnitudeSq = __webpack_require__(466); + +/** + * [description] + * + * @function Phaser.Geom.Point.Project + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} pointA - [description] + * @param {Phaser.Geom.Point} pointB - [description] + * @param {Phaser.Geom.Point} [out] - [description] + * + * @return {Phaser.Geom.Point} [description] + */ +var Project = function (pointA, pointB, out) +{ + if (out === undefined) { out = new Point(); } + + var dot = ((pointA.x * pointB.x) + (pointA.y * pointB.y)); + var amt = dot / GetMagnitudeSq(pointB); + + if (amt !== 0) + { + out.x = amt * pointB.x; + out.y = amt * pointB.y; + } + + return out; +}; + +module.exports = Project; + + +/***/ }), +/* 1177 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * [description] + * + * @function Phaser.Geom.Point.ProjectUnit + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} pointA - [description] + * @param {Phaser.Geom.Point} pointB - [description] + * @param {Phaser.Geom.Point} [out] - [description] + * + * @return {Phaser.Geom.Point} [description] + */ +var ProjectUnit = function (pointA, pointB, out) +{ + if (out === undefined) { out = new Point(); } + + var amt = ((pointA.x * pointB.x) + (pointA.y * pointB.y)); + + if (amt !== 0) + { + out.x = amt * pointB.x; + out.y = amt * pointB.y; + } + + return out; +}; + +module.exports = ProjectUnit; + + +/***/ }), +/* 1178 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetMagnitude = __webpack_require__(465); + +/** + * Changes the magnitude (length) of a two-dimensional vector without changing its direction. + * + * @function Phaser.Geom.Point.SetMagnitude + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to treat as the end point of the vector. + * @param {number} magnitude - The new magnitude of the vector. + * + * @return {Phaser.Geom.Point} The modified Point. + */ +var SetMagnitude = function (point, magnitude) +{ + if (point.x !== 0 || point.y !== 0) + { + var m = GetMagnitude(point); + + point.x /= m; + point.y /= m; + } + + point.x *= magnitude; + point.y *= magnitude; + + return point; +}; + +module.exports = SetMagnitude; + + +/***/ }), +/* 1179 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Polygon = __webpack_require__(213); + +Polygon.Clone = __webpack_require__(1180); +Polygon.Contains = __webpack_require__(214); +Polygon.ContainsPoint = __webpack_require__(1181); +Polygon.GetAABB = __webpack_require__(441); +Polygon.GetNumberArray = __webpack_require__(1182); +Polygon.GetPoints = __webpack_require__(442); +Polygon.Perimeter = __webpack_require__(443); +Polygon.Reverse = __webpack_require__(1183); +Polygon.Smooth = __webpack_require__(444); + +module.exports = Polygon; + + +/***/ }), +/* 1180 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Polygon = __webpack_require__(213); + +/** + * 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. + */ +var Clone = function (polygon) +{ + return new Polygon(polygon.points); +}; + +module.exports = Clone; + + +/***/ }), +/* 1181 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(214); + +/** + * [description] + * + * @function Phaser.Geom.Polygon.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Polygon} polygon - [description] + * @param {Phaser.Geom.Point} point - [description] + * + * @return {boolean} [description] + */ +var ContainsPoint = function (polygon, point) +{ + return Contains(polygon, point.x, point.y); +}; + +module.exports = ContainsPoint; + + +/***/ }), +/* 1182 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + +/** + * Stores all of the points of a Polygon into a flat array of numbers following the sequence [ x,y, x,y, x,y ], + * i.e. each point of the Polygon, in the order it's defined, corresponds to two elements of the resultant + * array for the point's X and Y coordinate. + * + * @function Phaser.Geom.Polygon.GetNumberArray + * @since 3.0.0 + * + * @generic {number[]} O - [output,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon whose points to export. + * @param {(array|number[])} [output] - An array to which the points' coordinates should be appended. + * + * @return {(array|number[])} The modified `output` array, or a new array if none was given. + */ +var GetNumberArray = function (polygon, output) +{ + if (output === undefined) { output = []; } + + for (var i = 0; i < polygon.points.length; i++) + { + output.push(polygon.points[i].x); + output.push(polygon.points[i].y); + } + + return output; +}; + +module.exports = GetNumberArray; + + +/***/ }), +/* 1183 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Reverses the order of the points of a Polygon. + * + * @function Phaser.Geom.Polygon.Reverse + * @since 3.0.0 + * + * @generic {Phaser.Geom.Polygon} O - [polygon,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to modify. + * + * @return {Phaser.Geom.Polygon} The modified Polygon. + */ +var Reverse = function (polygon) +{ + polygon.points.reverse(); + + return polygon; +}; + +module.exports = Reverse; + + +/***/ }), +/* 1184 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the area of the given Rectangle object. + * + * @function Phaser.Geom.Rectangle.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to calculate the area of. + * + * @return {number} The area of the Rectangle object. + */ +var Area = function (rect) +{ + return rect.width * rect.height; +}; + +module.exports = Area; + + +/***/ }), +/* 1185 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds a Rectangle's position up to the smallest integer greater than or equal to each current coordinate. + * + * @function Phaser.Geom.Rectangle.Ceil + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var Ceil = function (rect) +{ + rect.x = Math.ceil(rect.x); + rect.y = Math.ceil(rect.y); + + return rect; +}; + +module.exports = Ceil; + + +/***/ }), +/* 1186 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds a Rectangle's position and size up to the smallest integer greater than or equal to each respective value. + * + * @function Phaser.Geom.Rectangle.CeilAll + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to modify. + * + * @return {Phaser.Geom.Rectangle} The modified Rectangle. + */ +var CeilAll = function (rect) +{ + rect.x = Math.ceil(rect.x); + rect.y = Math.ceil(rect.y); + rect.width = Math.ceil(rect.width); + rect.height = Math.ceil(rect.height); + + return rect; +}; + +module.exports = CeilAll; + + +/***/ }), +/* 1187 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); + +/** + * Creates a new Rectangle which is identical to the given one. + * + * @function Phaser.Geom.Rectangle.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} source - The Rectangle to clone. + * + * @return {Phaser.Geom.Rectangle} The newly created Rectangle, which is separate from the given one. + */ +var Clone = function (source) +{ + return new Rectangle(source.x, source.y, source.width, source.height); +}; + +module.exports = Clone; + + +/***/ }), +/* 1188 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(53); + +/** + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. + * + * @function Phaser.Geom.Rectangle.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle object. + * @param {Phaser.Geom.Point} point - The point object to be checked. Can be a Phaser Point object or any object with x and y values. + * + * @return {boolean} A value of true if the Rectangle object contains the specified point, otherwise false. + */ +var ContainsPoint = function (rect, point) +{ + return Contains(rect, point.x, point.y); +}; + +module.exports = ContainsPoint; + + +/***/ }), +/* 1189 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one Rectangle to a destination Rectangle. + * + * @function Phaser.Geom.Rectangle.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [dest,$return] + * + * @param {Phaser.Geom.Rectangle} source - The source Rectangle to copy the values from. + * @param {Phaser.Geom.Rectangle} dest - The destination Rectangle to copy the values to. + * + * @return {Phaser.Geom.Rectangle} The destination Rectangle. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y, source.width, source.height); +}; + +module.exports = CopyFrom; + + +/***/ }), +/* 1190 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compares the `x`, `y`, `width` and `height` properties of two rectangles. + * + * @function Phaser.Geom.Rectangle.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - Rectangle A + * @param {Phaser.Geom.Rectangle} toCompare - Rectangle B + * + * @return {boolean} `true` if the rectangles' properties are an exact match, otherwise `false`. + */ +var Equals = function (rect, toCompare) +{ + return ( + rect.x === toCompare.x && + rect.y === toCompare.y && + rect.width === toCompare.width && + rect.height === toCompare.height + ); +}; + +module.exports = Equals; + + +/***/ }), +/* 1191 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetAspectRatio = __webpack_require__(224); + +/** + * Adjusts the target rectangle, changing its width, height and position, + * so that it fits inside the area of the source rectangle, while maintaining its original + * aspect ratio. + * + * Unlike the `FitOutside` function, there may be some space inside the source area not covered. + * + * @function Phaser.Geom.Rectangle.FitInside + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The target rectangle to adjust. + * @param {Phaser.Geom.Rectangle} source - The source rectangle to envelop the target in. + * + * @return {Phaser.Geom.Rectangle} The modified target rectangle instance. + */ +var FitInside = function (target, source) +{ + var ratio = GetAspectRatio(target); + + if (ratio < GetAspectRatio(source)) + { + // Taller than Wide + target.setSize(source.height * ratio, source.height); + } + else + { + // Wider than Tall + target.setSize(source.width, source.width / ratio); + } + + return target.setPosition( + source.centerX - (target.width / 2), + source.centerY - (target.height / 2) + ); +}; + +module.exports = FitInside; + + +/***/ }), +/* 1192 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetAspectRatio = __webpack_require__(224); + +/** + * Adjusts the target rectangle, changing its width, height and position, + * so that it fully covers the area of the source rectangle, while maintaining its original + * aspect ratio. + * + * Unlike the `FitInside` function, the target rectangle may extend further out than the source. + * + * @function Phaser.Geom.Rectangle.FitOutside + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The target rectangle to adjust. + * @param {Phaser.Geom.Rectangle} source - The source rectangle to envelope the target in. + * + * @return {Phaser.Geom.Rectangle} The modified target rectangle instance. + */ +var FitOutside = function (target, source) +{ + var ratio = GetAspectRatio(target); + + if (ratio > GetAspectRatio(source)) + { + // Wider than Tall + target.setSize(source.height * ratio, source.height); + } + else + { + // Taller than Wide + target.setSize(source.width, source.width / ratio); + } + + return target.setPosition( + source.centerX - target.width / 2, + source.centerY - target.height / 2 + ); +}; + +module.exports = FitOutside; + + +/***/ }), +/* 1193 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds down (floors) the top left X and Y coordinates of the given Rectangle to the largest integer less than or equal to them + * + * @function Phaser.Geom.Rectangle.Floor + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to floor the top left X and Y coordinates of + * + * @return {Phaser.Geom.Rectangle} The rectangle that was passed to this function with its coordinates floored. + */ +var Floor = function (rect) +{ + rect.x = Math.floor(rect.x); + rect.y = Math.floor(rect.y); + + return rect; +}; + +module.exports = Floor; + + +/***/ }), +/* 1194 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds a Rectangle's position and size down to the largest integer less than or equal to each current coordinate or dimension. + * + * @function Phaser.Geom.Rectangle.FloorAll + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var FloorAll = function (rect) +{ + rect.x = Math.floor(rect.x); + rect.y = Math.floor(rect.y); + rect.width = Math.floor(rect.width); + rect.height = Math.floor(rect.height); + + return rect; +}; + +module.exports = FloorAll; + + +/***/ }), +/* 1195 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + +/** + * Returns the center of a Rectangle as a Point. + * + * @function Phaser.Geom.Rectangle.GetCenter + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the center of. + * @param {(Phaser.Geom.Point|object)} [out] - Optional point-like object to update with the center coordinates. + * + * @return {(Phaser.Geom.Point|object)} The modified `out` object, or a new Point if none was provided. + */ +var GetCenter = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.centerX; + out.y = rect.centerY; + + return out; +}; + +module.exports = GetCenter; + + +/***/ }), +/* 1196 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); + + +/** + * The size of the Rectangle object, expressed as a Point object + * with the values of the width and height properties. + * + * @function Phaser.Geom.Rectangle.GetSize + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - [description] + * @param {(Phaser.Geom.Point|object)} [out] - [description] + * + * @return {(Phaser.Geom.Point|object)} [description] + */ +var GetSize = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.width; + out.y = rect.height; + + return out; +}; + +module.exports = GetSize; + + +/***/ }), +/* 1197 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CenterOn = __webpack_require__(178); + + +/** + * Increases the size of a Rectangle by a specified amount. + * + * The center of the Rectangle stays the same. The amounts are added to each side, so the actual increase in width or height is two times bigger than the respective argument. + * + * @function Phaser.Geom.Rectangle.Inflate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to inflate. + * @param {number} x - How many pixels the left and the right side should be moved by horizontally. + * @param {number} y - How many pixels the top and the bottom side should be moved by vertically. + * + * @return {Phaser.Geom.Rectangle} The inflated Rectangle. + */ +var Inflate = function (rect, x, y) +{ + var cx = rect.centerX; + var cy = rect.centerY; + + rect.setSize(rect.width + (x * 2), rect.height + (y * 2)); + + return CenterOn(rect, cx, cy); +}; + +module.exports = Inflate; + + +/***/ }), +/* 1198 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = __webpack_require__(11); +var Intersects = __webpack_require__(140); + +/** + * Takes two Rectangles and first checks to see if they intersect. + * If they intersect it will return the area of intersection in the `out` Rectangle. + * If they do not intersect, the `out` Rectangle will have a width and height of zero. + * + * @function Phaser.Geom.Rectangle.Intersection + * @since 3.11.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to get the intersection from. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to get the intersection from. + * @param {Phaser.Geom.Rectangle} [out] - A Rectangle to store the intersection results in. + * + * @return {Phaser.Geom.Rectangle} The intersection result. If the width and height are zero, no intersection occurred. + */ +var Intersection = function (rectA, rectB, out) +{ + if (out === undefined) { out = new Rectangle(); } + + if (Intersects(rectA, rectB)) + { + out.x = Math.max(rectA.x, rectB.x); + out.y = Math.max(rectA.y, rectB.y); + out.width = Math.min(rectA.right, rectB.right) - out.x; + out.height = Math.min(rectA.bottom, rectB.bottom) - out.y; + } + else + { + out.setEmpty(); + } + + return out; +}; + +module.exports = Intersection; + + +/***/ }), +/* 1199 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Merges a Rectangle with a list of points by repositioning and/or resizing it such that all points are located on or within its bounds. + * + * @function Phaser.Geom.Rectangle.MergePoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The Rectangle which should be merged. + * @param {Phaser.Geom.Point[]} points - An array of Points (or any object with public `x` and `y` properties) which should be merged with the Rectangle. + * + * @return {Phaser.Geom.Rectangle} The modified Rectangle. + */ +var MergePoints = function (target, points) +{ + var minX = target.x; + var maxX = target.right; + var minY = target.y; + var maxY = target.bottom; + + for (var i = 0; i < points.length; i++) + { + minX = Math.min(minX, points[i].x); + maxX = Math.max(maxX, points[i].x); + minY = Math.min(minY, points[i].y); + maxY = Math.max(maxY, points[i].y); + } + + target.x = minX; + target.y = minY; + target.width = maxX - minX; + target.height = maxY - minY; + + return target; +}; + +module.exports = MergePoints; + + +/***/ }), +/* 1200 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Merges source rectangle into target rectangle and returns target +// Neither rect should have negative widths or heights + +/** + * Merges the source rectangle into the target rectangle and returns the target. + * Neither rectangle should have a negative width or height. + * + * @function Phaser.Geom.Rectangle.MergeRect + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - Target rectangle. Will be modified to include source rectangle. + * @param {Phaser.Geom.Rectangle} source - Rectangle that will be merged into target rectangle. + * + * @return {Phaser.Geom.Rectangle} Modified target rectangle that contains source rectangle. + */ +var MergeRect = function (target, source) +{ + var minX = Math.min(target.x, source.x); + var maxX = Math.max(target.right, source.right); + + target.x = minX; + target.width = maxX - minX; + + var minY = Math.min(target.y, source.y); + var maxY = Math.max(target.bottom, source.bottom); + + target.y = minY; + target.height = maxY - minY; + + return target; +}; + +module.exports = MergeRect; + + +/***/ }), +/* 1201 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Merges a Rectangle with a point by repositioning and/or resizing it so that the point is on or within its bounds. + * + * @function Phaser.Geom.Rectangle.MergeXY + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The Rectangle which should be merged and modified. + * @param {number} x - The X coordinate of the point which should be merged. + * @param {number} y - The Y coordinate of the point which should be merged. + * + * @return {Phaser.Geom.Rectangle} The modified `target` Rectangle. + */ +var MergeXY = function (target, x, y) +{ + var minX = Math.min(target.x, x); + var maxX = Math.max(target.right, x); + + target.x = minX; + target.width = maxX - minX; + + var minY = Math.min(target.y, y); + var maxY = Math.max(target.bottom, y); + + target.y = minY; + target.height = maxY - minY; + + return target; +}; + +module.exports = MergeXY; + + +/***/ }), +/* 1202 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Nudges (translates) the top left corner of a Rectangle by a given offset. + * + * @function Phaser.Geom.Rectangle.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * @param {number} x - The distance to move the Rectangle horizontally. + * @param {number} y - The distance to move the Rectangle vertically. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var Offset = function (rect, x, y) +{ + rect.x += x; + rect.y += y; + + return rect; +}; + +module.exports = Offset; + + +/***/ }), +/* 1203 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Nudges (translates) the top-left corner of a Rectangle by the coordinates of a point (translation vector). + * + * @function Phaser.Geom.Rectangle.OffsetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2)} point - The point whose coordinates should be used as an offset. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var OffsetPoint = function (rect, point) +{ + rect.x += point.x; + rect.y += point.y; + + return rect; +}; + +module.exports = OffsetPoint; + + +/***/ }), +/* 1204 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if two Rectangles overlap. If a Rectangle is within another Rectangle, the two will be considered overlapping. Thus, the Rectangles are treated as "solid". + * + * @function Phaser.Geom.Rectangle.Overlaps + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check. + * + * @return {boolean} `true` if the two Rectangles overlap, `false` otherwise. + */ +var Overlaps = function (rectA, rectB) +{ + return ( + rectA.x < rectB.right && + rectA.right > rectB.x && + rectA.y < rectB.bottom && + rectA.bottom > rectB.y + ); +}; + +module.exports = Overlaps; + + +/***/ }), +/* 1205 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = __webpack_require__(4); +var DegToRad = __webpack_require__(40); + +/** + * [description] + * + * @function Phaser.Geom.Rectangle.PerimeterPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectangle - [description] + * @param {integer} angle - [description] + * @param {Phaser.Geom.Point} [out] - [description] + * + * @return {Phaser.Geom.Point} [description] + */ +var PerimeterPoint = function (rectangle, angle, out) +{ + if (out === undefined) { out = new Point(); } + + angle = DegToRad(angle); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var dx = (c > 0) ? rectangle.width / 2 : rectangle.width / -2; + var dy = (s > 0) ? rectangle.height / 2 : rectangle.height / -2; + + if (Math.abs(dx * s) < Math.abs(dy * c)) + { + dy = (dx * s) / c; + } + else + { + dx = (dy * c) / s; + } + + out.x = dx + rectangle.centerX; + out.y = dy + rectangle.centerY; + + return out; +}; + +module.exports = PerimeterPoint; + + +/***/ }), +/* 1206 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Between = __webpack_require__(183); +var ContainsRect = __webpack_require__(468); +var Point = __webpack_require__(4); + +/** + * Calculates a random point that lies within the `outer` Rectangle, but outside of the `inner` Rectangle. + * The inner Rectangle must be fully contained within the outer rectangle. + * + * @function Phaser.Geom.Rectangle.RandomOutside + * @since 3.10.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} outer - The outer Rectangle to get the random point within. + * @param {Phaser.Geom.Rectangle} inner - The inner Rectangle to exclude from the returned point. + * @param {Phaser.Geom.Point} [out] - A Point, or Point-like object to store the result in. If not specified, a new Point will be created. + * + * @return {Phaser.Geom.Point} A Point object containing the random values in its `x` and `y` properties. + */ +var RandomOutside = function (outer, inner, out) +{ + if (out === undefined) { out = new Point(); } + + if (ContainsRect(outer, inner)) + { + // 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 + + switch (Between(0, 3)) + { + case 0: // Top + out.x = outer.x + (Math.random() * (inner.right - outer.x)); + out.y = outer.y + (Math.random() * (inner.top - outer.y)); + break; + + case 1: // Bottom + out.x = inner.x + (Math.random() * (outer.right - inner.x)); + out.y = inner.bottom + (Math.random() * (outer.bottom - inner.bottom)); + break; + + case 2: // Left + out.x = outer.x + (Math.random() * (inner.x - outer.x)); + out.y = inner.y + (Math.random() * (outer.bottom - inner.y)); + break; + + case 3: // Right + out.x = inner.right + (Math.random() * (outer.right - inner.right)); + out.y = outer.y + (Math.random() * (inner.bottom - outer.y)); + break; + } + } + + return out; +}; + +module.exports = RandomOutside; + + +/***/ }), +/* 1207 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. + * + * @function Phaser.Geom.Rectangle.SameDimensions + * @since 3.15.0 + * + * @param {Phaser.Geom.Rectangle} rect - The first Rectangle object. + * @param {Phaser.Geom.Rectangle} toCompare - The second Rectangle object. + * + * @return {boolean} `true` if the objects have equivalent values for the `width` and `height` properties, otherwise `false`. + */ +var SameDimensions = function (rect, toCompare) +{ + return (rect.width === toCompare.width && rect.height === toCompare.height); +}; + +module.exports = SameDimensions; + + +/***/ }), +/* 1208 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Scales the width and height of this Rectangle by the given amounts. + +/** + * Scales the width and height of this Rectangle by the given amounts. + * + * @function Phaser.Geom.Rectangle.Scale + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The `Rectangle` object that will be scaled by the specified amount(s). + * @param {number} x - The factor by which to scale the rectangle horizontally. + * @param {number} y - The amount by which to scale the rectangle vertically. If this is not specified, the rectangle will be scaled by the factor `x` in both directions. + * + * @return {Phaser.Geom.Rectangle} The rectangle object with updated `width` and `height` properties as calculated from the scaling factor(s). + */ +var Scale = function (rect, x, y) +{ + if (y === undefined) { y = x; } + + rect.width *= x; + rect.height *= y; + + return rect; +}; + +module.exports = Scale; + + +/***/ }), +/* 1209 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = __webpack_require__(76); + +Triangle.Area = __webpack_require__(1210); +Triangle.BuildEquilateral = __webpack_require__(1211); +Triangle.BuildFromPolygon = __webpack_require__(1212); +Triangle.BuildRight = __webpack_require__(1213); +Triangle.CenterOn = __webpack_require__(1214); +Triangle.Centroid = __webpack_require__(469); +Triangle.CircumCenter = __webpack_require__(1215); +Triangle.CircumCircle = __webpack_require__(1216); +Triangle.Clone = __webpack_require__(1217); +Triangle.Contains = __webpack_require__(92); +Triangle.ContainsArray = __webpack_require__(222); +Triangle.ContainsPoint = __webpack_require__(1218); +Triangle.CopyFrom = __webpack_require__(1219); +Triangle.Decompose = __webpack_require__(462); +Triangle.Equals = __webpack_require__(1220); +Triangle.GetPoint = __webpack_require__(448); +Triangle.GetPoints = __webpack_require__(449); +Triangle.InCenter = __webpack_require__(471); +Triangle.Perimeter = __webpack_require__(1221); +Triangle.Offset = __webpack_require__(470); +Triangle.Random = __webpack_require__(168); +Triangle.Rotate = __webpack_require__(1222); +Triangle.RotateAroundPoint = __webpack_require__(1223); +Triangle.RotateAroundXY = __webpack_require__(225); + +module.exports = Triangle; + + +/***/ }), +/* 1210 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// The 2D area of a triangle. The area value is always non-negative. + +/** + * Returns the area of a Triangle. + * + * @function Phaser.Geom.Triangle.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to use. + * + * @return {number} The area of the Triangle, always non-negative. + */ +var Area = function (triangle) +{ + var x1 = triangle.x1; + var y1 = triangle.y1; + + var x2 = triangle.x2; + var y2 = triangle.y2; + + var x3 = triangle.x3; + var y3 = triangle.y3; + + return Math.abs(((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1)) / 2); +}; + +module.exports = Area; + + +/***/ }), +/* 1211 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = __webpack_require__(76); + +/** + * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). + * The x/y specifies the top-middle of the triangle (x1/y1) and length is the length of each side. + * + * @function Phaser.Geom.Triangle.BuildEquilateral + * @since 3.0.0 + * + * @param {number} x - x coordinate of the top point of the triangle. + * @param {number} y - y coordinate of the top point of the triangle. + * @param {number} length - Length of each side of the triangle. + * + * @return {Phaser.Geom.Triangle} The Triangle object of the given size. + */ +var BuildEquilateral = function (x, y, length) +{ + var height = length * (Math.sqrt(3) / 2); + + var x1 = x; + var y1 = y; + + var x2 = x + (length / 2); + var y2 = y + height; + + var x3 = x - (length / 2); + var y3 = y + height; + + return new Triangle(x1, y1, x2, y2, x3, y3); +}; + +module.exports = BuildEquilateral; + + +/***/ }), +/* 1212 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var EarCut = __webpack_require__(72); +var Triangle = __webpack_require__(76); + +/** + * [description] + * + * @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] - [description] + * @param {number} [scaleY=1] - [description] + * @param {(array|Phaser.Geom.Triangle[])} [out] - [description] + * + * @return {(array|Phaser.Geom.Triangle[])} [description] + */ +var BuildFromPolygon = function (data, holes, scaleX, scaleY, out) +{ + if (holes === undefined) { holes = null; } + if (scaleX === undefined) { scaleX = 1; } + if (scaleY === undefined) { scaleY = 1; } + if (out === undefined) { out = []; } + + var tris = EarCut(data, holes); + + var a; + var b; + var c; + + var x1; + var y1; + + var x2; + var y2; + + var x3; + var y3; + + for (var i = 0; i < tris.length; i += 3) + { + a = tris[i]; + b = tris[i + 1]; + c = tris[i + 2]; + + x1 = data[a * 2] * scaleX; + y1 = data[(a * 2) + 1] * scaleY; + + x2 = data[b * 2] * scaleX; + y2 = data[(b * 2) + 1] * scaleY; + + x3 = data[c * 2] * scaleX; + y3 = data[(c * 2) + 1] * scaleY; + + out.push(new Triangle(x1, y1, x2, y2, x3, y3)); + } + + return out; +}; + +module.exports = BuildFromPolygon; + + +/***/ }), +/* 1213 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = __webpack_require__(76); + +// 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 + +/** + * Builds a right triangle, i.e. one which has a 90-degree angle and two acute angles. + * + * @function Phaser.Geom.Triangle.BuildRight + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the right angle, which will also be the first X coordinate of the constructed Triangle. + * @param {number} y - The Y coordinate of the right angle, which will also be the first Y coordinate of the constructed Triangle. + * @param {number} width - The length of the side which is to the left or to the right of the right angle. + * @param {number} height - The length of the side which is above or below the right angle. + * + * @return {Phaser.Geom.Triangle} The constructed right Triangle. + */ +var BuildRight = function (x, y, width, height) +{ + if (height === undefined) { height = width; } + + // 90 degree angle + var x1 = x; + var y1 = y; + + var x2 = x; + var y2 = y - height; + + var x3 = x + width; + var y3 = y; + + return new Triangle(x1, y1, x2, y2, x3, y3); +}; + +module.exports = BuildRight; + + +/***/ }), +/* 1214 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Centroid = __webpack_require__(469); +var Offset = __webpack_require__(470); + +/** + * @callback CenterFunction + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to return the center coordinates of. + * + * @return {Phaser.Math.Vector2} The center point of the Triangle according to the function. + */ + +/** + * Positions the Triangle so that it is centered on the given coordinates. + * + * @function Phaser.Geom.Triangle.CenterOn + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The triangle to be positioned. + * @param {number} x - The horizontal coordinate to center on. + * @param {number} y - The vertical coordinate to center on. + * @param {CenterFunction} [centerFunc] - The function used to center the triangle. Defaults to Centroid centering. + * + * @return {Phaser.Geom.Triangle} The Triangle that was centered. + */ +var CenterOn = function (triangle, x, y, centerFunc) +{ + if (centerFunc === undefined) { centerFunc = Centroid; } + + // Get the center of the triangle + var center = centerFunc(triangle); + + // Difference + var diffX = x - center.x; + var diffY = y - center.y; + + return Offset(triangle, diffX, diffY); +}; + +module.exports = CenterOn; + + +/***/ }), +/* 1215 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = __webpack_require__(3); + +// Adapted from http://bjornharrtell.github.io/jsts/doc/api/jsts_geom_Triangle.js.html + +/** + * Computes the determinant of a 2x2 matrix. Uses standard double-precision arithmetic, so is susceptible to round-off error. + * + * @function det + * @private + * @since 3.0.0 + * + * @param {number} m00 - The [0,0] entry of the matrix. + * @param {number} m01 - The [0,1] entry of the matrix. + * @param {number} m10 - The [1,0] entry of the matrix. + * @param {number} m11 - The [1,1] entry of the matrix. + * + * @return {number} the determinant. + */ +function det (m00, m01, m10, m11) +{ + return (m00 * m11) - (m01 * m10); +} + +/** + * Computes the circumcentre of a triangle. The circumcentre is the centre of + * the circumcircle, the smallest circle which encloses 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. + * + * @function Phaser.Geom.Triangle.CircumCenter + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - [description] + * @param {Phaser.Math.Vector2} [out] - [description] + * + * @return {Phaser.Math.Vector2} [description] + */ +var CircumCenter = function (triangle, out) +{ + if (out === undefined) { out = new Vector2(); } + + var cx = triangle.x3; + var cy = triangle.y3; + + var ax = triangle.x1 - cx; + var ay = triangle.y1 - cy; + + var bx = triangle.x2 - cx; + var by = triangle.y2 - cy; + + var denom = 2 * det(ax, ay, bx, by); + var numx = det(ay, ax * ax + ay * ay, by, bx * bx + by * by); + var numy = det(ax, ax * ax + ay * ay, bx, bx * bx + by * by); + + out.x = cx - numx / denom; + out.y = cy + numy / denom; + + return out; +}; + +module.exports = CircumCenter; + + +/***/ }), +/* 1216 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = __webpack_require__(71); + +// Adapted from https://gist.github.com/mutoo/5617691 + +/** + * Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices. + * + * @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. + */ +var CircumCircle = function (triangle, out) +{ + if (out === undefined) { out = new Circle(); } + + // A + var x1 = triangle.x1; + var y1 = triangle.y1; + + // B + var x2 = triangle.x2; + var y2 = triangle.y2; + + // C + var x3 = triangle.x3; + var y3 = triangle.y3; + + var A = x2 - x1; + var B = y2 - y1; + var C = x3 - x1; + var D = y3 - y1; + var E = A * (x1 + x2) + B * (y1 + y2); + var F = C * (x1 + x3) + D * (y1 + y3); + var G = 2 * (A * (y3 - y2) - B * (x3 - x2)); + + var dx; + var dy; + + // If the points of the triangle are collinear, then just find the + // extremes and use the midpoint as the center of the circumcircle. + + if (Math.abs(G) < 0.000001) + { + var minX = Math.min(x1, x2, x3); + var minY = Math.min(y1, y2, y3); + dx = (Math.max(x1, x2, x3) - minX) * 0.5; + dy = (Math.max(y1, y2, y3) - minY) * 0.5; + + out.x = minX + dx; + out.y = minY + dy; + out.radius = Math.sqrt(dx * dx + dy * dy); + } + else + { + out.x = (D * E - B * F) / G; + out.y = (A * F - C * E) / G; + dx = out.x - x1; + dy = out.y - y1; + out.radius = Math.sqrt(dx * dx + dy * dy); + } + + return out; +}; + +module.exports = CircumCircle; + + +/***/ }), +/* 1217 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = __webpack_require__(76); + +/** + * Clones a Triangle object. + * + * @function Phaser.Geom.Triangle.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} source - The Triangle to clone. + * + * @return {Phaser.Geom.Triangle} A new Triangle identical to the given one but separate from it. + */ +var Clone = function (source) +{ + return new Triangle(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3); +}; + +module.exports = Clone; + + +/***/ }), +/* 1218 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = __webpack_require__(92); + +/** + * Tests if a triangle contains a point. + * + * @function Phaser.Geom.Triangle.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle. + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|any)} point - The point to test, or any point-like object with public `x` and `y` properties. + * + * @return {boolean} `true` if the point is within the triangle, otherwise `false`. + */ +var ContainsPoint = function (triangle, point) +{ + return Contains(triangle, point.x, point.y); +}; + +module.exports = ContainsPoint; + + +/***/ }), +/* 1219 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one Triangle to a destination Triangle. + * + * @function Phaser.Geom.Triangle.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [dest,$return] + * + * @param {Phaser.Geom.Triangle} source - The source Triangle to copy the values from. + * @param {Phaser.Geom.Triangle} dest - The destination Triangle to copy the values to. + * + * @return {Phaser.Geom.Triangle} The destination Triangle. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3); +}; + +module.exports = CopyFrom; + + +/***/ }), +/* 1220 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns true if two triangles have the same coordinates. + * + * @function Phaser.Geom.Triangle.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The first triangle to check. + * @param {Phaser.Geom.Triangle} toCompare - The second triangle to check. + * + * @return {boolean} `true` if the two given triangles have the exact same coordinates, otherwise `false`. + */ +var Equals = function (triangle, toCompare) +{ + return ( + triangle.x1 === toCompare.x1 && + triangle.y1 === toCompare.y1 && + triangle.x2 === toCompare.x2 && + triangle.y2 === toCompare.y2 && + triangle.x3 === toCompare.x3 && + triangle.y3 === toCompare.y3 + ); +}; + +module.exports = Equals; + + +/***/ }), +/* 1221 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = __webpack_require__(62); + +// The 2D area of a triangle. The area value is always non-negative. + +/** + * Gets the length of the perimeter of the given triangle. + * + * @function Phaser.Geom.Triangle.Perimeter + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - [description] + * + * @return {number} [description] + */ +var Perimeter = function (triangle) +{ + var line1 = triangle.getLineA(); + var line2 = triangle.getLineB(); + var line3 = triangle.getLineC(); + + return (Length(line1) + Length(line2) + Length(line3)); +}; + +module.exports = Perimeter; + + +/***/ }), +/* 1222 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = __webpack_require__(225); +var InCenter = __webpack_require__(471); + +/** + * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. + * + * @function Phaser.Geom.Triangle.Rotate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. + * @param {number} angle - The angle by which to rotate the Triangle, in radians. + * + * @return {Phaser.Geom.Triangle} The rotated Triangle. + */ +var Rotate = function (triangle, angle) +{ + var point = InCenter(triangle); + + return RotateAroundXY(triangle, point.x, point.y, angle); +}; + +module.exports = Rotate; + + +/***/ }), +/* 1223 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = __webpack_require__(225); + +/** + * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. + * + * @function Phaser.Geom.Triangle.RotateAroundPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. + * @param {Phaser.Geom.Point} point - The Point to rotate the Triangle about. + * @param {number} angle - The angle by which to rotate the Triangle, in radians. + * + * @return {Phaser.Geom.Triangle} The rotated Triangle. + */ +var RotateAroundPoint = function (triangle, point, angle) +{ + return RotateAroundXY(triangle, point.x, point.y, angle); +}; + +module.exports = RotateAroundPoint; + + +/***/ }), +/* 1224 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(192); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Input + */ + +var Input = { + + CreateInteractiveObject: __webpack_require__(472), + Events: __webpack_require__(56), + Gamepad: __webpack_require__(1225), + InputManager: __webpack_require__(389), + InputPlugin: __webpack_require__(1237), + InputPluginCache: __webpack_require__(141), + Keyboard: __webpack_require__(1239), + Mouse: __webpack_require__(1256), + Pointer: __webpack_require__(392), + Touch: __webpack_require__(1257) + +}; + +// Merge in the consts +Input = Extend(false, Input, CONST); + +module.exports = Input; + + +/***/ }), +/* 1225 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Gamepad + */ + +module.exports = { + + Axis: __webpack_require__(473), + Button: __webpack_require__(474), + Events: __webpack_require__(226), + Gamepad: __webpack_require__(475), + GamepadPlugin: __webpack_require__(1232), + + Configs: __webpack_require__(1233) +}; + + +/***/ }), +/* 1226 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Down Event. + * + * This event is dispatched by the Gamepad Plugin when a button has been pressed on any active Gamepad. + * + * Listen to this event from within a Scene using: `this.input.gamepad.on('down', listener)`. + * + * You can also listen for a DOWN event from a Gamepad instance. See the [GAMEPAD_BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_DOWN} event for details. + * + * @event Phaser.Input.Gamepad.Events#BUTTON_DOWN + * @since 3.10.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad on which the button was pressed. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was pressed. + * @param {number} value - The value of the button at the time it was pressed. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + */ +module.exports = 'down'; + + +/***/ }), +/* 1227 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Up Event. + * + * This event is dispatched by the Gamepad Plugin when a button has been released on any active Gamepad. + * + * Listen to this event from within a Scene using: `this.input.gamepad.on('up', listener)`. + * + * You can also listen for an UP event from a Gamepad instance. See the [GAMEPAD_BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_UP} event for details. + * + * @event Phaser.Input.Gamepad.Events#BUTTON_UP + * @since 3.10.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad on which the button was released. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was released. + * @param {number} value - The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + */ +module.exports = 'up'; + + +/***/ }), +/* 1228 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Connected Event. + * + * This event is dispatched by the Gamepad Plugin when a Gamepad has been connected. + * + * Listen to this event from within a Scene using: `this.input.gamepad.once('connected', listener)`. + * + * 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. + * + * @event Phaser.Input.Gamepad.Events#CONNECTED + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad which was connected. + * @param {Event} event - The native DOM Event that triggered the connection. + */ +module.exports = 'connected'; + + +/***/ }), +/* 1229 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Disconnected Event. + * + * This event is dispatched by the Gamepad Plugin when a Gamepad has been disconnected. + * + * Listen to this event from within a Scene using: `this.input.gamepad.once('disconnected', listener)`. + * + * @event Phaser.Input.Gamepad.Events#DISCONNECTED + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad which was disconnected. + * @param {Event} event - The native DOM Event that triggered the disconnection. + */ +module.exports = 'disconnected'; + + +/***/ }), +/* 1230 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Down Event. + * + * This event is dispatched by a Gamepad instance when a button has been pressed on it. + * + * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: + * `this.input.gamepad.pad1.on('down', listener)`. + * + * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. + * + * You can also listen for a DOWN event from the Gamepad Plugin. See the [BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_DOWN} event for details. + * + * @event Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_DOWN + * @since 3.10.0 + * + * @param {integer} index - The index of the button that was pressed. + * @param {number} value - The value of the button at the time it was pressed. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was pressed. + */ +module.exports = 'down'; + + +/***/ }), +/* 1231 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Up Event. + * + * This event is dispatched by a Gamepad instance when a button has been released on it. + * + * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: + * `this.input.gamepad.pad1.on('up', listener)`. + * + * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. + * + * You can also listen for an UP event from the Gamepad Plugin. See the [BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_UP} event for details. + * + * @event Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_UP + * @since 3.10.0 + * + * @param {integer} index - The index of the button that was released. + * @param {number} value - The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was released. + */ +module.exports = 'up'; + + +/***/ }), +/* 1232 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(226); +var Gamepad = __webpack_require__(475); +var GetValue = __webpack_require__(5); +var InputPluginCache = __webpack_require__(141); +var InputEvents = __webpack_require__(56); + +/** + * @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. + * + * 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 KeyboardPlugin belongs to. + */ +var GamepadPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function GamepadPlugin (sceneInputPlugin) + { + EventEmitter.call(this); + + /** + * A reference to the Scene that this Input Plugin is responsible for. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#scene + * @type {Phaser.Scene} + * @since 3.10.0 + */ + this.scene = sceneInputPlugin.scene; + + /** + * A reference to the Scene Systems Settings. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.10.0 + */ + this.settings = this.scene.sys.settings; + + /** + * A reference to the Scene Input Plugin that created this Keyboard Plugin. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#sceneInputPlugin + * @type {Phaser.Input.InputPlugin} + * @since 3.10.0 + */ + this.sceneInputPlugin = sceneInputPlugin; + + /** + * A boolean that controls if the Gamepad Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#enabled + * @type {boolean} + * @default true + * @since 3.10.0 + */ + this.enabled = true; + + /** + * The Gamepad Event target, as defined in the Game Config. + * Typically the browser window, but can be any interactive DOM element. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#target + * @type {any} + * @since 3.10.0 + */ + this.target; + + /** + * An array of the connected Gamepads. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#gamepads + * @type {Phaser.Input.Gamepad.Gamepad[]} + * @default [] + * @since 3.10.0 + */ + this.gamepads = []; + + /** + * An internal event queue. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#queue + * @type {GamepadEvent[]} + * @private + * @since 3.10.0 + */ + this.queue = []; + + /** + * Internal event handler. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#onGamepadHandler + * @type {function} + * @private + * @since 3.10.0 + */ + this.onGamepadHandler; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad1 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad1; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad2 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad2; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad3 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad3; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad4 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad4; + + sceneInputPlugin.pluginEvents.once(InputEvents.BOOT, this.boot, this); + sceneInputPlugin.pluginEvents.on(InputEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#boot + * @private + * @since 3.10.0 + */ + boot: function () + { + var game = this.scene.sys.game; + var settings = this.settings.input; + var config = game.config; + + this.enabled = GetValue(settings, 'gamepad', config.inputGamepad) && game.device.input.gamepads; + this.target = GetValue(settings, 'gamepad.target', config.inputGamepadEventTarget); + + this.sceneInputPlugin.pluginEvents.once(InputEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#start + * @private + * @since 3.10.0 + */ + start: function () + { + if (this.enabled) + { + this.startListeners(); + } + + this.sceneInputPlugin.pluginEvents.once(InputEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#isActive + * @since 3.10.0 + * + * @return {boolean} `true` if the plugin and the Scene it belongs to is active. + */ + isActive: function () + { + return (this.enabled && this.scene.sys.isActive()); + }, + + /** + * Starts the Gamepad Event listeners running. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#startListeners + * @private + * @since 3.10.0 + */ + startListeners: function () + { + var _this = this; + var target = this.target; + + var handler = function (event) + { + if (event.defaultPrevented || !_this.isActive()) + { + // Do nothing if event already handled + return; + } + + _this.refreshPads(); + + _this.queue.push(event); + }; + + this.onGamepadHandler = handler; + + target.addEventListener('gamepadconnected', handler, false); + target.addEventListener('gamepaddisconnected', handler, false); + + // 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 + this.sceneInputPlugin.pluginEvents.on(InputEvents.UPDATE, this.update, this); + }, + + /** + * Stops the Gamepad Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#stopListeners + * @private + * @since 3.10.0 + */ + stopListeners: function () + { + this.target.removeEventListener('gamepadconnected', this.onGamepadHandler); + this.target.removeEventListener('gamepaddisconnected', this.onGamepadHandler); + + this.sceneInputPlugin.pluginEvents.off(InputEvents.UPDATE, this.update); + }, + + /** + * Disconnects all current Gamepads. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#disconnectAll + * @since 3.10.0 + */ + disconnectAll: function () + { + for (var i = 0; i < this.gamepads.length; i++) + { + this.gamepads.connected = false; + } + }, + + /** + * Refreshes the list of connected Gamepads. + * + * This is called automatically when a gamepad is connected or disconnected, + * and during the update loop. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#refreshPads + * @private + * @since 3.10.0 + */ + refreshPads: function () + { + var connectedPads = navigator.getGamepads(); + + if (!connectedPads) + { + this.disconnectAll(); + } + else + { + var currentPads = this.gamepads; + + for (var i = 0; i < connectedPads.length; i++) + { + var livePad = connectedPads[i]; + + // Because sometimes they're null (yes, really) + if (!livePad) + { + continue; + } + + var id = livePad.id; + var index = livePad.index; + var currentPad = currentPads[index]; + + if (!currentPad) + { + // A new Gamepad, not currently stored locally + var newPad = new Gamepad(this, livePad); + + currentPads[index] = newPad; + + if (!this._pad1) + { + this._pad1 = newPad; + } + else if (!this._pad2) + { + this._pad2 = newPad; + } + else if (!this._pad3) + { + this._pad3 = newPad; + } + else if (!this._pad4) + { + this._pad4 = newPad; + } + } + else if (currentPad.id !== id) + { + // A new Gamepad with a different vendor string, but it has got the same index as an old one + currentPad.destroy(); + + currentPads[index] = new Gamepad(this, livePad); + } + else + { + // If neither of these, it's a pad we've already got, so update it + currentPad.update(livePad); + } + } + } + }, + + /** + * Returns an array of all currently connected Gamepads. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#getAll + * @since 3.10.0 + * + * @return {Phaser.Input.Gamepad.Gamepad[]} An array of all currently connected Gamepads. + */ + getAll: function () + { + var out = []; + var pads = this.gamepads; + + for (var i = 0; i < pads.length; i++) + { + if (pads[i]) + { + out.push(pads[i]); + } + } + + return out; + }, + + /** + * 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. + */ + getPad: function (index) + { + var pads = this.gamepads; + + for (var i = 0; i < pads.length; i++) + { + if (pads[i] && pads[i].index === index) + { + return pads[i]; + } + } + }, + + /** + * The internal update loop. Refreshes all connected gamepads and processes their events. + * + * Called automatically by the Input Manager, invoked from the Game step. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#update + * @private + * @fires Phaser.Input.Gamepad.Events#CONNECTED + * @fires Phaser.Input.Gamepad.Events#DISCONNECTED + * @since 3.10.0 + */ + update: function () + { + if (!this.enabled) + { + return; + } + + this.refreshPads(); + + var len = this.queue.length; + + if (len === 0) + { + return; + } + + var queue = this.queue.splice(0, len); + + // Process the event queue, dispatching all of the events that have stored up + for (var i = 0; i < len; i++) + { + var event = queue[i]; + var pad = this.getPad(event.gamepad.index); + + if (event.type === 'gamepadconnected') + { + this.emit(Events.CONNECTED, pad, event); + } + else if (event.type === 'gamepaddisconnected') + { + this.emit(Events.DISCONNECTED, pad, event); + } + } + }, + + /** + * Shuts the Gamepad Plugin down. + * All this does is remove any listeners bound to it. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#shutdown + * @private + * @since 3.10.0 + */ + shutdown: function () + { + this.stopListeners(); + + this.disconnectAll(); + + this.removeAllListeners(); + }, + + /** + * Destroys this Gamepad Plugin, disconnecting all Gamepads and releasing internal references. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#destroy + * @private + * @since 3.10.0 + */ + destroy: function () + { + this.shutdown(); + + for (var i = 0; i < this.gamepads.length; i++) + { + if (this.gamepads[i]) + { + this.gamepads[i].destroy(); + } + } + + this.gamepads = []; + + this.scene = null; + this.settings = null; + this.sceneInputPlugin = null; + this.target = null; + }, + + /** + * The total number of connected game pads. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#total + * @type {integer} + * @since 3.10.0 + */ + total: { + + get: function () + { + return this.gamepads.length; + } + + }, + + /** + * A reference to the first connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad1 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad1: { + + get: function () + { + return this._pad1; + } + + }, + + /** + * A reference to the second connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad2 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad2: { + + get: function () + { + return this._pad2; + } + + }, + + /** + * A reference to the third connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad3 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad3: { + + get: function () + { + return this._pad3; + } + + }, + + /** + * A reference to the fourth connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad4 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad4: { + + get: function () + { + return this._pad4; + } + + } + +}); + +/** + * An instance of the Gamepad Plugin class, if enabled via the `input.gamepad` Scene or Game Config property. + * Use this to create access Gamepads connected to the browser and respond to gamepad buttons. + * + * @name Phaser.Input.InputPlugin#gamepad + * @type {?Phaser.Input.Gamepad.GamepadPlugin} + * @since 3.10.0 + */ +InputPluginCache.register('GamepadPlugin', GamepadPlugin, 'gamepad', 'gamepad', 'inputGamepad'); + +module.exports = GamepadPlugin; + + +/***/ }), +/* 1233 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Gamepad.Configs + */ + +module.exports = { + + DUALSHOCK_4: __webpack_require__(1234), + SNES_USB: __webpack_require__(1235), + XBOX_360: __webpack_require__(1236) + +}; + + +/***/ }), +/* 1234 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * PlayStation DualShock 4 Gamepad Configuration. + * Sony PlayStation DualShock 4 (v2) wireless controller + * + * @name Phaser.Input.Gamepad.Configs.DUALSHOCK_4 + * @type {object} + * @since 3.0.0 + */ +module.exports = { + + UP: 12, + DOWN: 13, + LEFT: 14, + RIGHT: 15, + + SHARE: 8, + OPTIONS: 9, + PS: 16, + TOUCHBAR: 17, + + X: 0, + CIRCLE: 1, + SQUARE: 2, + TRIANGLE: 3, + + L1: 4, + R1: 5, + L2: 6, + R2: 7, + L3: 10, + R3: 11, + + LEFT_STICK_H: 0, + LEFT_STICK_V: 1, + RIGHT_STICK_H: 2, + RIGHT_STICK_V: 3 + +}; + + +/***/ }), +/* 1235 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tatar SNES USB Controller Gamepad Configuration. + * USB Gamepad (STANDARD GAMEPAD Vendor: 0079 Product: 0011) + * + * @name Phaser.Input.Gamepad.Configs.SNES_USB + * @type {object} + * @since 3.0.0 + */ +module.exports = { + + UP: 12, + DOWN: 13, + LEFT: 14, + RIGHT: 15, + + SELECT: 8, + START: 9, + + B: 0, + A: 1, + Y: 2, + X: 3, + + LEFT_SHOULDER: 4, + RIGHT_SHOULDER: 5 + +}; + + +/***/ }), +/* 1236 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * XBox 360 Gamepad Configuration. + * + * @name Phaser.Input.Gamepad.Configs.XBOX_360 + * @type {object} + * @since 3.0.0 + */ +module.exports = { + + UP: 12, + DOWN: 13, + LEFT: 14, + RIGHT: 15, + + MENU: 16, + + A: 0, + B: 1, + X: 2, + Y: 3, + + LB: 4, + RB: 5, + + LT: 6, + RT: 7, + + BACK: 8, + START: 9, + + LS: 10, + RS: 11, + + LEFT_STICK_H: 0, + LEFT_STICK_V: 1, + RIGHT_STICK_H: 2, + RIGHT_STICK_V: 3 + +}; + + +/***/ }), +/* 1237 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = __webpack_require__(71); +var CircleContains = __webpack_require__(60); +var Class = __webpack_require__(0); +var CONST = __webpack_require__(192); +var CreateInteractiveObject = __webpack_require__(472); +var CreatePixelPerfectHandler = __webpack_require__(1238); +var DistanceBetween = __webpack_require__(54); +var Ellipse = __webpack_require__(107); +var EllipseContains = __webpack_require__(108); +var Events = __webpack_require__(56); +var EventEmitter = __webpack_require__(9); +var GetFastValue = __webpack_require__(1); +var GEOM_CONST = __webpack_require__(52); +var InputPluginCache = __webpack_require__(141); +var IsPlainObject = __webpack_require__(7); +var PluginCache = __webpack_require__(22); +var Rectangle = __webpack_require__(11); +var RectangleContains = __webpack_require__(53); +var SceneEvents = __webpack_require__(18); +var Triangle = __webpack_require__(76); +var TriangleContains = __webpack_require__(92); + +/** + * @classdesc + * The Input Plugin belongs to a Scene and handles all input related events and operations for it. + * + * You can access it from within a Scene using `this.input`. + * + * It emits events directly. For example, you can do: + * + * ```javascript + * this.input.on('pointerdown', callback, context); + * ``` + * + * To listen for a pointer down event anywhere on the game canvas. + * + * Game Objects can be enabled for input by calling their `setInteractive` method. After which they + * will directly emit input events: + * + * ```javascript + * var sprite = this.add.sprite(x, y, texture); + * sprite.setInteractive(); + * sprite.on('pointerdown', callback, context); + * ``` + * + * There are lots of game configuration options available relating to input. + * See the [Input Config object]{@linkcode Phaser.Types.Core.InputConfig} for more details, including how to deal with Phaser + * listening for input events outside of the canvas, how to set a default number of pointers, input + * capture settings and more. + * + * Please also see the Input examples and tutorials for further information. + * + * @class InputPlugin + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Input + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that this Input Plugin is responsible for. + */ +var InputPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function InputPlugin (scene) + { + EventEmitter.call(this); + + /** + * A reference to the Scene that this Input Plugin is responsible for. + * + * @name Phaser.Input.InputPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems class. + * + * @name Phaser.Input.InputPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the Scene Systems Settings. + * + * @name Phaser.Input.InputPlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.5.0 + */ + this.settings = scene.sys.settings; + + /** + * A reference to the Game Input Manager. + * + * @name Phaser.Input.InputPlugin#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = scene.sys.game.input; + + /** + * Internal event queue used for plugins only. + * + * @name Phaser.Input.InputPlugin#pluginEvents + * @type {Phaser.Events.EventEmitter} + * @private + * @since 3.10.0 + */ + this.pluginEvents = new EventEmitter(); + + /** + * If `true` this Input Plugin will process DOM input events. + * + * @name Phaser.Input.InputPlugin#enabled + * @type {boolean} + * @default true + * @since 3.5.0 + */ + this.enabled = true; + + /** + * A reference to the Scene Display List. This property is set during the `boot` method. + * + * @name Phaser.Input.InputPlugin#displayList + * @type {Phaser.GameObjects.DisplayList} + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene Cameras Manager. This property is set during the `boot` method. + * + * @name Phaser.Input.InputPlugin#cameras + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.0.0 + */ + this.cameras; + + // Inject the available input plugins into this class + InputPluginCache.install(this); + + /** + * A reference to the Mouse Manager. + * + * This property is only set if Mouse support has been enabled in your Game Configuration file. + * + * If you just wish to get access to the mouse pointer, use the `mousePointer` property instead. + * + * @name Phaser.Input.InputPlugin#mouse + * @type {?Phaser.Input.Mouse.MouseManager} + * @since 3.0.0 + */ + this.mouse = this.manager.mouse; + + /** + * When set to `true` (the default) the Input Plugin will emulate DOM behavior by only emitting events from + * the top-most Game Objects in the Display List. + * + * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. + * + * @name Phaser.Input.InputPlugin#topOnly + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.topOnly = true; + + /** + * How often should the Pointers be checked? + * + * The value is a time, given in ms, and is the time that must have elapsed between game steps before + * the Pointers will be polled again. When a pointer is polled it runs a hit test to see which Game + * Objects are currently below it, or being interacted with it. + * + * Pointers will *always* be checked if they have been moved by the user, or press or released. + * + * This property only controls how often they will be polled if they have not been updated. + * You should set this if you want to have Game Objects constantly check against the pointers, even + * if the pointer didn't itself move. + * + * Set to 0 to poll constantly. Set to -1 to only poll on user movement. + * + * @name Phaser.Input.InputPlugin#pollRate + * @type {integer} + * @default -1 + * @since 3.0.0 + */ + this.pollRate = -1; + + /** + * Internal poll timer value. + * + * @name Phaser.Input.InputPlugin#_pollTimer + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._pollTimer = 0; + + var _eventData = { cancelled: false }; + + /** + * Internal event propagation callback container. + * + * @name Phaser.Input.InputPlugin#_eventContainer + * @type {Phaser.Types.Input.EventData} + * @private + * @since 3.13.0 + */ + this._eventContainer = { + stopPropagation: function () + { + _eventData.cancelled = true; + } + }; + + /** + * Internal event propagation data object. + * + * @name Phaser.Input.InputPlugin#_eventData + * @type {object} + * @private + * @since 3.13.0 + */ + this._eventData = _eventData; + + /** + * The distance, in pixels, a pointer has to move while being held down, before it thinks it is being dragged. + * + * @name Phaser.Input.InputPlugin#dragDistanceThreshold + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragDistanceThreshold = 0; + + /** + * The amount of time, in ms, a pointer has to be held down before it thinks it is dragging. + * + * The default polling rate is to poll only on move so once the time threshold is reached the + * drag event will not start until you move the mouse. If you want it to start immediately + * when the time threshold is reached, you must increase the polling rate by calling + * [setPollAlways]{@linkcode Phaser.Input.InputPlugin#setPollAlways} or + * [setPollRate]{@linkcode Phaser.Input.InputPlugin#setPollRate}. + * + * @name Phaser.Input.InputPlugin#dragTimeThreshold + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragTimeThreshold = 0; + + /** + * Used to temporarily store the results of the Hit Test + * + * @name Phaser.Input.InputPlugin#_temp + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this._temp = []; + + /** + * Used to temporarily store the results of the Hit Test dropZones + * + * @name Phaser.Input.InputPlugin#_tempZones + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this._tempZones = []; + + /** + * A list of all Game Objects that have been set to be interactive in the Scene this Input Plugin is managing. + * + * @name Phaser.Input.InputPlugin#_list + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._list = []; + + /** + * Objects waiting to be inserted to the list on the next call to 'begin'. + * + * @name Phaser.Input.InputPlugin#_pendingInsertion + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingInsertion = []; + + /** + * Objects waiting to be removed from the list on the next call to 'begin'. + * + * @name Phaser.Input.InputPlugin#_pendingRemoval + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingRemoval = []; + + /** + * A list of all Game Objects that have been enabled for dragging. + * + * @name Phaser.Input.InputPlugin#_draggable + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._draggable = []; + + /** + * A list of all Interactive Objects currently considered as being 'draggable' by any pointer, indexed by pointer ID. + * + * @name Phaser.Input.InputPlugin#_drag + * @type {{0:Array,1:Array,2:Array,3:Array,4:Array,5:Array,6:Array,7:Array,8:Array,9:Array,10:Array}} + * @private + * @since 3.0.0 + */ + this._drag = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; + + /** + * A array containing the dragStates, for this Scene, index by the Pointer ID. + * + * @name Phaser.Input.InputPlugin#_dragState + * @type {integer[]} + * @private + * @since 3.16.0 + */ + this._dragState = []; + + /** + * A list of all Interactive Objects currently considered as being 'over' by any pointer, indexed by pointer ID. + * + * @name Phaser.Input.InputPlugin#_over + * @type {{0:Array,1:Array,2:Array,3:Array,4:Array,5:Array,6:Array,7:Array,8:Array,9:Array,10:Array}} + * @private + * @since 3.0.0 + */ + this._over = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; + + /** + * A list of valid DOM event types. + * + * @name Phaser.Input.InputPlugin#_validTypes + * @type {string[]} + * @private + * @since 3.0.0 + */ + this._validTypes = [ 'onDown', 'onUp', 'onOver', 'onOut', 'onMove', 'onDragStart', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragLeave', 'onDragOver', 'onDrop' ]; + + /** + * Internal property that tracks frame event state. + * + * @name Phaser.Input.InputPlugin#_updatedThisFrame + * @type {boolean} + * @private + * @since 3.18.0 + */ + this._updatedThisFrame = false; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Input.InputPlugin#boot + * @fires Phaser.Input.Events#BOOT + * @private + * @since 3.5.1 + */ + boot: function () + { + this.cameras = this.systems.cameras; + + this.displayList = this.systems.displayList; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + + // Registered input plugins listen for this + this.pluginEvents.emit(Events.BOOT); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Input.InputPlugin#start + * @fires Phaser.Input.Events#START + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.TRANSITION_START, this.transitionIn, this); + eventEmitter.on(SceneEvents.TRANSITION_OUT, this.transitionOut, this); + eventEmitter.on(SceneEvents.TRANSITION_COMPLETE, this.transitionComplete, this); + eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.manager.events.on(Events.GAME_OUT, this.onGameOut, this); + this.manager.events.on(Events.GAME_OVER, this.onGameOver, this); + + this.enabled = true; + + // Populate the pointer drag states + this._dragState = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; + + // Registered input plugins listen for this + this.pluginEvents.emit(Events.START); + }, + + /** + * Game Over handler. + * + * @method Phaser.Input.InputPlugin#onGameOver + * @fires Phaser.Input.Events#GAME_OVER + * @private + * @since 3.16.2 + */ + onGameOver: function (event) + { + if (this.isActive()) + { + this.emit(Events.GAME_OVER, event.timeStamp, event); + } + }, + + /** + * Game Out handler. + * + * @method Phaser.Input.InputPlugin#onGameOut + * @fires Phaser.Input.Events#GAME_OUT + * @private + * @since 3.16.2 + */ + onGameOut: function (event) + { + if (this.isActive()) + { + this.emit(Events.GAME_OUT, event.timeStamp, event); + } + }, + + /** + * The pre-update handler is responsible for checking the pending removal and insertion lists and + * deleting old Game Objects. + * + * @method Phaser.Input.InputPlugin#preUpdate + * @private + * @fires Phaser.Input.Events#PRE_UPDATE + * @since 3.0.0 + */ + preUpdate: function () + { + // Registered input plugins listen for this + this.pluginEvents.emit(Events.PRE_UPDATE); + + var removeList = this._pendingRemoval; + var insertList = this._pendingInsertion; + + var toRemove = removeList.length; + var toInsert = insertList.length; + + if (toRemove === 0 && toInsert === 0) + { + // Quick bail + return; + } + + var current = this._list; + + // Delete old gameObjects + for (var i = 0; i < toRemove; i++) + { + var gameObject = removeList[i]; + + var index = current.indexOf(gameObject); + + if (index > -1) + { + current.splice(index, 1); + + this.clear(gameObject, true); + } + } + + // Clear the removal list + removeList.length = 0; + this._pendingRemoval.length = 0; + + // Move pendingInsertion to list (also clears pendingInsertion at the same time) + this._list = current.concat(insertList.splice(0)); + }, + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + * + * @method Phaser.Input.InputPlugin#isActive + * @since 3.10.0 + * + * @return {boolean} `true` if the plugin and the Scene it belongs to is active. + */ + isActive: function () + { + return (this.enabled && this.scene.sys.isActive()); + }, + + /** + * 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. + */ + updatePoll: function (time, delta) + { + if (!this.isActive()) + { + return false; + } + + // The plugins should update every frame, regardless if there has been + // any DOM input events or not (such as the Gamepad and Keyboard) + this.pluginEvents.emit(Events.UPDATE, time, delta); + + // We can leave now if we've already updated once this frame via the immediate DOM event handlers + if (this._updatedThisFrame) + { + this._updatedThisFrame = false; + + return false; + } + + var i; + var manager = this.manager; + + var pointers = manager.pointers; + var pointersTotal = manager.pointersTotal; + + for (i = 0; i < pointersTotal; i++) + { + pointers[i].updateMotion(); + } + + // No point going any further if there aren't any interactive objects + if (this._list.length === 0) + { + return false; + } + + var rate = this.pollRate; + + if (rate === -1) + { + return false; + } + else if (rate > 0) + { + this._pollTimer -= delta; + + if (this._pollTimer < 0) + { + // Discard timer diff, we're ready to poll again + this._pollTimer = this.pollRate; + } + else + { + // Not enough time has elapsed since the last poll, so abort now + return false; + } + } + + // We got this far? Then we should poll for movement + var captured = false; + + for (i = 0; i < pointersTotal; i++) + { + var total = 0; + + var pointer = pointers[i]; + + // Always reset this array + this._tempZones = []; + + // _temp contains a hit tested and camera culled list of IO objects + this._temp = this.hitTestPointer(pointer); + + this.sortGameObjects(this._temp); + this.sortGameObjects(this._tempZones); + + if (this.topOnly) + { + // Only the top-most one counts now, so safely ignore the rest + if (this._temp.length) + { + this._temp.splice(1); + } + + if (this._tempZones.length) + { + this._tempZones.splice(1); + } + } + + total += this.processOverOutEvents(pointer); + + if (this.getDragState(pointer) === 2) + { + this.processDragThresholdEvent(pointer, time); + } + + if (total > 0) + { + // We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame + captured = true; + } + } + + return captured; + }, + + /** + * This method is called when a DOM Event is received by the Input Manager. It handles dispatching the events + * to relevant input enabled Game Objects in this scene. + * + * @method Phaser.Input.InputPlugin#update + * @private + * @fires Phaser.Input.Events#UPDATE + * @since 3.0.0 + * + * @param {integer} type - The type of event to process. + * @param {Phaser.Input.Pointer[]} pointers - An array of Pointers on which the event occurred. + * + * @return {boolean} `true` if this Scene has captured the input events from all other Scenes, otherwise `false`. + */ + update: function (type, pointers) + { + if (!this.isActive()) + { + return false; + } + + var pointersTotal = pointers.length; + var captured = false; + + for (var i = 0; i < pointersTotal; i++) + { + var total = 0; + var pointer = pointers[i]; + + // Always reset this array + this._tempZones = []; + + // _temp contains a hit tested and camera culled list of IO objects + this._temp = this.hitTestPointer(pointer); + + this.sortGameObjects(this._temp); + this.sortGameObjects(this._tempZones); + + if (this.topOnly) + { + // Only the top-most one counts now, so safely ignore the rest + if (this._temp.length) + { + this._temp.splice(1); + } + + if (this._tempZones.length) + { + this._tempZones.splice(1); + } + } + + switch (type) + { + case CONST.MOUSE_DOWN: + total += this.processDragDownEvent(pointer); + total += this.processDownEvents(pointer); + total += this.processOverOutEvents(pointer); + break; + + case CONST.MOUSE_UP: + total += this.processDragUpEvent(pointer); + total += this.processUpEvents(pointer); + total += this.processOverOutEvents(pointer); + break; + + case CONST.TOUCH_START: + total += this.processDragDownEvent(pointer); + total += this.processDownEvents(pointer); + total += this.processOverEvents(pointer); + break; + + case CONST.TOUCH_END: + case CONST.TOUCH_CANCEL: + total += this.processDragUpEvent(pointer); + total += this.processUpEvents(pointer); + total += this.processOutEvents(pointer); + break; + + case CONST.MOUSE_MOVE: + case CONST.TOUCH_MOVE: + total += this.processDragMoveEvent(pointer); + total += this.processMoveEvents(pointer); + total += this.processOverOutEvents(pointer); + break; + + case CONST.MOUSE_WHEEL: + total += this.processWheelEvent(pointer); + break; + } + + if (total > 0) + { + // We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame + captured = true; + } + } + + this._updatedThisFrame = true; + + return captured; + }, + + /** + * Clears a Game Object so it no longer has an Interactive Object associated with it. + * The Game Object is then queued for removal from the Input Plugin on the next update. + * + * @method Phaser.Input.InputPlugin#clear + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will have its Interactive Object removed. + * @param {boolean} [skipQueue=false] - Skip adding this Game Object into the removal queue? + * + * @return {Phaser.GameObjects.GameObject} The Game Object that had its Interactive Object removed. + */ + clear: function (gameObject, skipQueue) + { + if (skipQueue === undefined) { skipQueue = false; } + + var input = gameObject.input; + + // If GameObject.input already cleared from higher class + if (!input) + { + return; + } + + if (!skipQueue) + { + this.queueForRemoval(gameObject); + } + + input.gameObject = undefined; + input.target = undefined; + input.hitArea = undefined; + input.hitAreaCallback = undefined; + input.callbackContext = undefined; + + this.manager.resetCursor(input); + + gameObject.input = null; + + // Clear from _draggable, _drag and _over + var index = this._draggable.indexOf(gameObject); + + if (index > -1) + { + this._draggable.splice(index, 1); + } + + index = this._drag[0].indexOf(gameObject); + + if (index > -1) + { + this._drag[0].splice(index, 1); + } + + index = this._over[0].indexOf(gameObject); + + if (index > -1) + { + this._over[0].splice(index, 1); + } + + return gameObject; + }, + + /** + * Disables Input on a single Game Object. + * + * An input disabled Game Object still retains its Interactive Object component and can be re-enabled + * at any time, by passing it to `InputPlugin.enable`. + * + * @method Phaser.Input.InputPlugin#disable + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to have its input system disabled. + */ + disable: function (gameObject) + { + gameObject.input.enabled = false; + }, + + /** + * 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)} [shape] - 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} [callback] - 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 {Phaser.Input.InputPlugin} This Input Plugin. + */ + enable: function (gameObject, shape, callback, dropZone) + { + if (dropZone === undefined) { dropZone = false; } + + if (gameObject.input) + { + // If it is already has an InteractiveObject then just enable it and return + gameObject.input.enabled = true; + } + else + { + // Create an InteractiveObject and enable it + this.setHitArea(gameObject, shape, callback); + } + + if (gameObject.input && dropZone && !gameObject.input.dropZone) + { + gameObject.input.dropZone = dropZone; + } + + return this; + }, + + /** + * Takes the given Pointer and performs a hit test against it, to see which interactive Game Objects + * it is currently above. + * + * The hit test is performed against which-ever Camera the Pointer is over. If it is over multiple + * cameras, it starts checking the camera at the top of the camera list, and if nothing is found, iterates down the list. + * + * @method Phaser.Input.InputPlugin#hitTestPointer + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to check against the Game Objects. + * + * @return {Phaser.GameObjects.GameObject[]} An array of all the interactive Game Objects the Pointer was above. + */ + hitTestPointer: function (pointer) + { + var cameras = this.cameras.getCamerasBelowPointer(pointer); + + for (var c = 0; c < cameras.length; c++) + { + var camera = cameras[c]; + + // 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. + var over = this.manager.hitTest(pointer, this._list, camera); + + // Filter out the drop zones + for (var i = 0; i < over.length; i++) + { + var obj = over[i]; + + if (obj.input.dropZone) + { + this._tempZones.push(obj); + } + } + + if (over.length > 0) + { + pointer.camera = camera; + + return over; + } + } + + // 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 + + pointer.camera = cameras[0]; + + return []; + }, + + /** + * An internal method that handles the Pointer down event. + * + * @method Phaser.Input.InputPlugin#processDownEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_DOWN + * @fires Phaser.Input.Events#GAMEOBJECT_DOWN + * @fires Phaser.Input.Events#POINTER_DOWN + * @fires Phaser.Input.Events#POINTER_DOWN_OUTSIDE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer being tested. + * + * @return {integer} The total number of objects interacted with. + */ + processDownEvents: function (pointer) + { + var total = 0; + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + total++; + + gameObject.emit(Events.GAMEOBJECT_POINTER_DOWN, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_DOWN, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + // If they released outside the canvas, but pressed down inside it, we'll still dispatch the event. + if (!aborted && this.manager) + { + if (pointer.downElement === this.manager.game.canvas) + { + this.emit(Events.POINTER_DOWN, pointer, currentlyOver); + } + else + { + this.emit(Events.POINTER_DOWN_OUTSIDE, pointer); + } + } + + return total; + }, + + /** + * Returns the drag state of the given Pointer for this Input Plugin. + * + * The state will be one of the following: + * + * 0 = Not dragging anything + * 1 = Primary button down and objects below, so collect a draglist + * 2 = Pointer being checked if meets drag criteria + * 3 = Pointer meets criteria, notify the draglist + * 4 = Pointer actively dragging the draglist and has moved + * 5 = Pointer actively dragging but has been released, notify draglist + * + * @method Phaser.Input.InputPlugin#getDragState + * @since 3.16.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to get the drag state for. + * + * @return {integer} The drag state of the given Pointer. + */ + getDragState: function (pointer) + { + return this._dragState[pointer.id]; + }, + + /** + * Sets the drag state of the given Pointer for this Input Plugin. + * + * The state must be one of the following values: + * + * 0 = Not dragging anything + * 1 = Primary button down and objects below, so collect a draglist + * 2 = Pointer being checked if meets drag criteria + * 3 = Pointer meets criteria, notify the draglist + * 4 = Pointer actively dragging the draglist and has moved + * 5 = Pointer actively dragging but has been released, notify draglist + * + * @method Phaser.Input.InputPlugin#setDragState + * @since 3.16.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to set the drag state for. + * @param {integer} state - The drag state value. An integer between 0 and 5. + */ + setDragState: function (pointer, state) + { + this._dragState[pointer.id] = state; + }, + + /** + * 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. + */ + processDragThresholdEvent: function (pointer, time) + { + var passed = false; + var timeThreshold = this.dragTimeThreshold; + var distanceThreshold = this.dragDistanceThreshold; + + if (distanceThreshold > 0 && DistanceBetween(pointer.x, pointer.y, pointer.downX, pointer.downY) >= distanceThreshold) + { + // It has moved far enough to be considered a drag + passed = true; + } + else if (timeThreshold > 0 && (time >= pointer.downTime + timeThreshold)) + { + // It has been held down long enough to be considered a drag + passed = true; + } + + if (passed) + { + this.setDragState(pointer, 3); + + return this.processDragStartList(pointer); + } + }, + + /** + * Processes the drag list for the given pointer and dispatches the start events for each object on it. + * + * @method Phaser.Input.InputPlugin#processDragStartList + * @private + * @fires Phaser.Input.Events#DRAG_START + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_START + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that DRAG_START was called on. + */ + processDragStartList: function (pointer) + { + // 3 = Pointer meets criteria and is freshly down, notify the draglist + if (this.getDragState(pointer) !== 3) + { + return 0; + } + + var list = this._drag[pointer.id]; + + for (var i = 0; i < list.length; i++) + { + var gameObject = list[i]; + + var input = gameObject.input; + + input.dragState = 2; + + input.dragStartX = gameObject.x; + input.dragStartY = gameObject.y; + + input.dragStartXGlobal = pointer.x; + input.dragStartYGlobal = pointer.y; + + input.dragX = input.dragStartXGlobal - input.dragStartX; + input.dragY = input.dragStartYGlobal - input.dragStartY; + + gameObject.emit(Events.GAMEOBJECT_DRAG_START, pointer, input.dragX, input.dragY); + + this.emit(Events.DRAG_START, pointer, gameObject); + } + + this.setDragState(pointer, 4); + + return list.length; + }, + + /** + * Processes a 'drag down' event for the given pointer. Checks the pointer state, builds-up the drag list + * and prepares them all for interaction. + * + * @method Phaser.Input.InputPlugin#processDragDownEvent + * @private + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that were collected on the drag list. + */ + processDragDownEvent: function (pointer) + { + var currentlyOver = this._temp; + + if (this._draggable.length === 0 || currentlyOver.length === 0 || !pointer.primaryDown || this.getDragState(pointer) !== 0) + { + // There are no draggable items, no over items or the pointer isn't down, so let's not even bother going further + return 0; + } + + // 1 = Primary button down and objects below, so collect a draglist + this.setDragState(pointer, 1); + + // Get draggable objects, sort them, pick the top (or all) and store them somewhere + var draglist = []; + + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (gameObject.input.draggable && (gameObject.input.dragState === 0)) + { + draglist.push(gameObject); + } + } + + if (draglist.length === 0) + { + this.setDragState(pointer, 0); + + return 0; + } + else if (draglist.length > 1) + { + this.sortGameObjects(draglist); + + if (this.topOnly) + { + draglist.splice(1); + } + } + + // draglist now contains all potential candidates for dragging + this._drag[pointer.id] = draglist; + + if (this.dragDistanceThreshold === 0 && this.dragTimeThreshold === 0) + { + // No drag criteria, so snap immediately to mode 3 + this.setDragState(pointer, 3); + + return this.processDragStartList(pointer); + } + else + { + // Check the distance / time on the next event + this.setDragState(pointer, 2); + + return 0; + } + }, + + /** + * Processes a 'drag move' event for the given pointer. + * + * @method Phaser.Input.InputPlugin#processDragMoveEvent + * @private + * @fires Phaser.Input.Events#DRAG_ENTER + * @fires Phaser.Input.Events#DRAG + * @fires Phaser.Input.Events#DRAG_LEAVE + * @fires Phaser.Input.Events#DRAG_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_ENTER + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_LEAVE + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_OVER + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that were updated by this drag event. + */ + processDragMoveEvent: function (pointer) + { + // 2 = Pointer being checked if meets drag criteria + if (this.getDragState(pointer) === 2) + { + this.processDragThresholdEvent(pointer, this.manager.game.loop.now); + } + + if (this.getDragState(pointer) !== 4) + { + return 0; + } + + // 4 = Pointer actively dragging the draglist and has moved + var dropZones = this._tempZones; + + var list = this._drag[pointer.id]; + + for (var i = 0; i < list.length; i++) + { + var gameObject = list[i]; + + var input = gameObject.input; + + var target = input.target; + + // If this GO has a target then let's check it + if (target) + { + var index = dropZones.indexOf(target); + + // Got a target, are we still over it? + if (index === 0) + { + // We're still over it, and it's still the top of the display list, phew ... + gameObject.emit(Events.GAMEOBJECT_DRAG_OVER, pointer, target); + + this.emit(Events.DRAG_OVER, pointer, gameObject, target); + } + else if (index > 0) + { + // Still over it but it's no longer top of the display list (targets must always be at the top) + gameObject.emit(Events.GAMEOBJECT_DRAG_LEAVE, pointer, target); + + this.emit(Events.DRAG_LEAVE, pointer, gameObject, target); + + input.target = dropZones[0]; + + target = input.target; + + gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); + + this.emit(Events.DRAG_ENTER, pointer, gameObject, target); + } + else + { + // Nope, we've moved on (or the target has!), leave the old target + gameObject.emit(Events.GAMEOBJECT_DRAG_LEAVE, pointer, target); + + this.emit(Events.DRAG_LEAVE, pointer, gameObject, target); + + // Anything new to replace it? + // Yup! + if (dropZones[0]) + { + input.target = dropZones[0]; + + target = input.target; + + gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); + + this.emit(Events.DRAG_ENTER, pointer, gameObject, target); + } + else + { + // Nope + input.target = null; + } + } + } + else if (!target && dropZones[0]) + { + input.target = dropZones[0]; + + target = input.target; + + gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); + + this.emit(Events.DRAG_ENTER, pointer, gameObject, target); + } + + var dragX; + var dragY; + + if (!gameObject.parentContainer) + { + dragX = pointer.x - input.dragX; + dragY = pointer.y - input.dragY; + } + else + { + var dx = pointer.x - input.dragStartXGlobal; + var dy = pointer.y - input.dragStartYGlobal; + + var rotation = gameObject.getParentRotation(); + + var dxRotated = dx * Math.cos(rotation) + dy * Math.sin(rotation); + var dyRotated = dy * Math.cos(rotation) - dx * Math.sin(rotation); + + dxRotated *= (1 / gameObject.parentContainer.scaleX); + dyRotated *= (1 / gameObject.parentContainer.scaleY); + + dragX = dxRotated + input.dragStartX; + dragY = dyRotated + input.dragStartY; + } + + gameObject.emit(Events.GAMEOBJECT_DRAG, pointer, dragX, dragY); + + this.emit(Events.DRAG, pointer, gameObject, dragX, dragY); + } + + return list.length; + }, + + /** + * Processes a 'drag down' event for the given pointer. Checks the pointer state, builds-up the drag list + * and prepares them all for interaction. + * + * @method Phaser.Input.InputPlugin#processDragUpEvent + * @fires Phaser.Input.Events#DRAG_END + * @fires Phaser.Input.Events#DROP + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_END + * @fires Phaser.Input.Events#GAMEOBJECT_DROP + * @private + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that were updated by this drag event. + */ + processDragUpEvent: function (pointer) + { + // 5 = Pointer was actively dragging but has been released, notify draglist + var list = this._drag[pointer.id]; + + for (var i = 0; i < list.length; i++) + { + var gameObject = list[i]; + + var input = gameObject.input; + + if (input && input.dragState === 2) + { + input.dragState = 0; + + input.dragX = input.localX - gameObject.displayOriginX; + input.dragY = input.localY - gameObject.displayOriginY; + + var dropped = false; + + var target = input.target; + + if (target) + { + gameObject.emit(Events.GAMEOBJECT_DROP, pointer, target); + + this.emit(Events.DROP, pointer, gameObject, target); + + input.target = null; + + dropped = true; + } + + // And finally the dragend event + + if (gameObject.input) + { + gameObject.emit(Events.GAMEOBJECT_DRAG_END, pointer, input.dragX, input.dragY, dropped); + + this.emit(Events.DRAG_END, pointer, gameObject, dropped); + } + } + } + + this.setDragState(pointer, 0); + + list.splice(0); + + return 0; + }, + + /** + * An internal method that handles the Pointer movement event. + * + * @method Phaser.Input.InputPlugin#processMoveEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_MOVE + * @fires Phaser.Input.Events#GAMEOBJECT_MOVE + * @fires Phaser.Input.Events#POINTER_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processMoveEvents: function (pointer) + { + var total = 0; + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + total++; + + gameObject.emit(Events.GAMEOBJECT_POINTER_MOVE, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_MOVE, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + if (this.topOnly) + { + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_MOVE, pointer, currentlyOver); + } + + return total; + }, + + /** + * An internal method that handles a mouse wheel event. + * + * @method Phaser.Input.InputPlugin#processWheelEvent + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_WHEEL + * @fires Phaser.Input.Events#GAMEOBJECT_WHEEL + * @fires Phaser.Input.Events#POINTER_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processWheelEvent: function (pointer) + { + var total = 0; + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + var dx = pointer.deltaX; + var dy = pointer.deltaY; + var dz = pointer.deltaZ; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + total++; + + gameObject.emit(Events.GAMEOBJECT_POINTER_WHEEL, pointer, dx, dy, dz, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_WHEEL, pointer, gameObject, dx, dy, dz, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_WHEEL, pointer, currentlyOver, dx, dy, dz); + } + + return total; + }, + + /** + * An internal method that handles the Pointer over events. + * This is called when a touch input hits the canvas, having previously been off of it. + * + * @method Phaser.Input.InputPlugin#processOverEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_OVER + * @fires Phaser.Input.Events#POINTER_OVER + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processOverEvents: function (pointer) + { + var currentlyOver = this._temp; + + var totalInteracted = 0; + + var total = currentlyOver.length; + + var justOver = []; + + if (total > 0) + { + var manager = this.manager; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + for (var i = 0; i < total; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + justOver.push(gameObject); + + manager.setCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OVER, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OVER, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OVER, pointer, justOver); + } + } + + // Then sort it into display list order + this._over[pointer.id] = justOver; + + return totalInteracted; + }, + + /** + * An internal method that handles the Pointer out events. + * This is called when a touch input leaves the canvas, as it can never be 'over' in this case. + * + * @method Phaser.Input.InputPlugin#processOutEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OUT + * @fires Phaser.Input.Events#GAMEOBJECT_OUT + * @fires Phaser.Input.Events#POINTER_OUT + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processOutEvents: function (pointer) + { + var previouslyOver = this._over[pointer.id]; + + var totalInteracted = 0; + + var total = previouslyOver.length; + + if (total > 0) + { + var manager = this.manager; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + this.sortGameObjects(previouslyOver); + + for (var i = 0; i < total; i++) + { + var gameObject = previouslyOver[i]; + + // Call onOut for everything in the previouslyOver array + for (i = 0; i < total; i++) + { + gameObject = previouslyOver[i]; + + if (!gameObject.input) + { + continue; + } + + manager.resetCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OUT, pointer, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OUT, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OUT, pointer, previouslyOver); + } + } + + this._over[pointer.id] = []; + } + + return totalInteracted; + }, + + /** + * An internal method that handles the Pointer over and out events. + * + * @method Phaser.Input.InputPlugin#processOverOutEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_OVER + * @fires Phaser.Input.Events#POINTER_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OUT + * @fires Phaser.Input.Events#GAMEOBJECT_OUT + * @fires Phaser.Input.Events#POINTER_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processOverOutEvents: function (pointer) + { + var currentlyOver = this._temp; + + var i; + var gameObject; + var justOut = []; + var justOver = []; + var stillOver = []; + var previouslyOver = this._over[pointer.id]; + var currentlyDragging = this._drag[pointer.id]; + + var manager = this.manager; + + // 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 + + for (i = 0; i < previouslyOver.length; i++) + { + gameObject = previouslyOver[i]; + + if (currentlyOver.indexOf(gameObject) === -1 && currentlyDragging.indexOf(gameObject) === -1) + { + // Not in the currentlyOver array, so must be outside of this object now + justOut.push(gameObject); + } + else + { + // In the currentlyOver array + stillOver.push(gameObject); + } + } + + // 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 + for (i = 0; i < currentlyOver.length; i++) + { + gameObject = currentlyOver[i]; + + // Is this newly over? + + if (previouslyOver.indexOf(gameObject) === -1) + { + justOver.push(gameObject); + } + } + + // By this point the arrays are filled, so now we can process what happened... + + // Process the Just Out objects + var total = justOut.length; + + var totalInteracted = 0; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + if (total > 0) + { + this.sortGameObjects(justOut); + + // Call onOut for everything in the justOut array + for (i = 0; i < total; i++) + { + gameObject = justOut[i]; + + if (!gameObject.input) + { + continue; + } + + // Reset cursor before we emit the event, in case they want to change it during the event + manager.resetCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OUT, pointer, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OUT, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OUT, pointer, justOut); + } + } + + // Process the Just Over objects + total = justOver.length; + + _eventData.cancelled = false; + + aborted = false; + + if (total > 0) + { + this.sortGameObjects(justOver); + + // Call onOver for everything in the justOver array + for (i = 0; i < total; i++) + { + gameObject = justOver[i]; + + if (!gameObject.input) + { + continue; + } + + // Set cursor before we emit the event, in case they want to change it during the event + manager.setCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OVER, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OVER, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OVER, pointer, justOver); + } + } + + // Add the contents of justOver to the previously over array + previouslyOver = stillOver.concat(justOver); + + // Then sort it into display list order + this._over[pointer.id] = this.sortGameObjects(previouslyOver); + + return totalInteracted; + }, + + /** + * An internal method that handles the Pointer up events. + * + * @method Phaser.Input.InputPlugin#processUpEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_UP + * @fires Phaser.Input.Events#GAMEOBJECT_UP + * @fires Phaser.Input.Events#POINTER_UP + * @fires Phaser.Input.Events#POINTER_UP_OUTSIDE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processUpEvents: function (pointer) + { + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + gameObject.emit(Events.GAMEOBJECT_POINTER_UP, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_UP, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + // If they released outside the canvas, but pressed down inside it, we'll still dispatch the event. + if (!aborted && this.manager) + { + if (pointer.upElement === this.manager.game.canvas) + { + this.emit(Events.POINTER_UP, pointer, currentlyOver); + } + else + { + this.emit(Events.POINTER_UP_OUTSIDE, pointer); + } + } + + return currentlyOver.length; + }, + + /** + * Queues a Game Object for insertion into this Input Plugin on the next update. + * + * @method Phaser.Input.InputPlugin#queueForInsertion + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + queueForInsertion: function (child) + { + if (this._pendingInsertion.indexOf(child) === -1 && this._list.indexOf(child) === -1) + { + this._pendingInsertion.push(child); + } + + return this; + }, + + /** + * Queues a Game Object for removal from this Input Plugin on the next update. + * + * @method Phaser.Input.InputPlugin#queueForRemoval + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to remove. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + queueForRemoval: function (child) + { + this._pendingRemoval.push(child); + + return this; + }, + + /** + * Sets the draggable state of the given array of Game Objects. + * + * They can either be set to be draggable, or can have their draggable state removed by passing `false`. + * + * A Game Object will not fire drag events unless it has been specifically enabled for drag. + * + * @method Phaser.Input.InputPlugin#setDraggable + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to change the draggable state on. + * @param {boolean} [value=true] - Set to `true` if the Game Objects should be made draggable, `false` if they should be unset. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setDraggable: function (gameObjects, value) + { + if (value === undefined) { value = true; } + + if (!Array.isArray(gameObjects)) + { + gameObjects = [ gameObjects ]; + } + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + gameObject.input.draggable = value; + + var index = this._draggable.indexOf(gameObject); + + if (value && index === -1) + { + this._draggable.push(gameObject); + } + else if (!value && index > -1) + { + this._draggable.splice(index, 1); + } + } + + return this; + }, + + /** + * Creates a function that can be passed to `setInteractive`, `enable` or `setHitArea` that will handle + * pixel-perfect input detection on an Image or Sprite based Game Object, or any custom class that extends them. + * + * The following will create a sprite that is clickable on any pixel that has an alpha value >= 1. + * + * ```javascript + * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect()); + * ``` + * + * The following will create a sprite that is clickable on any pixel that has an alpha value >= 150. + * + * ```javascript + * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect(150)); + * ``` + * + * Once you have made an Interactive Object pixel perfect it impacts all input related events for it: down, up, + * dragstart, drag, etc. + * + * As a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from + * the given coordinates and checking its color values. This is an expensive process, so should only be enabled on + * Game Objects that really need it. + * + * You cannot make non-texture based Game Objects pixel perfect. So this will not work on Graphics, BitmapText, + * Render Textures, Text, Tilemaps, Containers or Particles. + * + * @method Phaser.Input.InputPlugin#makePixelPerfect + * @since 3.10.0 + * + * @param {integer} [alphaTolerance=1] - The alpha level that the pixel should be above to be included as a successful interaction. + * + * @return {function} A Pixel Perfect Handler for use as a hitArea shape callback. + */ + makePixelPerfect: function (alphaTolerance) + { + if (alphaTolerance === undefined) { alphaTolerance = 1; } + + var textureManager = this.systems.textures; + + return CreatePixelPerfectHandler(textureManager, alphaTolerance); + }, + + /** + * 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`. + * + * @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|any)} [shape] - 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} [callback] - The 'contains' function to invoke to check if the pointer is within the hit area. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitArea: function (gameObjects, shape, callback) + { + if (shape === undefined) + { + return this.setHitAreaFromTexture(gameObjects); + } + + if (!Array.isArray(gameObjects)) + { + gameObjects = [ gameObjects ]; + } + + var draggable = false; + var dropZone = false; + var cursor = false; + var useHandCursor = false; + var pixelPerfect = false; + var customHitArea = true; + + // Config object? + if (IsPlainObject(shape)) + { + var config = shape; + + shape = GetFastValue(config, 'hitArea', null); + callback = GetFastValue(config, 'hitAreaCallback', null); + draggable = GetFastValue(config, 'draggable', false); + dropZone = GetFastValue(config, 'dropZone', false); + cursor = GetFastValue(config, 'cursor', false); + useHandCursor = GetFastValue(config, 'useHandCursor', false); + + pixelPerfect = GetFastValue(config, 'pixelPerfect', false); + var alphaTolerance = GetFastValue(config, 'alphaTolerance', 1); + + if (pixelPerfect) + { + shape = {}; + callback = this.makePixelPerfect(alphaTolerance); + } + + // Still no hitArea or callback? + if (!shape || !callback) + { + this.setHitAreaFromTexture(gameObjects); + customHitArea = false; + } + } + else if (typeof shape === 'function' && !callback) + { + callback = shape; + shape = {}; + } + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + if (pixelPerfect && gameObject.type === 'Container') + { + console.warn('Cannot pixelPerfect test a Container. Use a custom callback.'); + continue; + } + + var io = (!gameObject.input) ? CreateInteractiveObject(gameObject, shape, callback) : gameObject.input; + + io.customHitArea = customHitArea; + io.dropZone = dropZone; + io.cursor = (useHandCursor) ? 'pointer' : cursor; + + gameObject.input = io; + + if (draggable) + { + this.setDraggable(gameObject); + } + + this.queueForInsertion(gameObject); + } + + return this; + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Circle` shape, using + * the given coordinates and radius to control its position and size. + * + * @method Phaser.Input.InputPlugin#setHitAreaCircle + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a circle hit area. + * @param {number} x - The center of the circle. + * @param {number} y - The center of the circle. + * @param {number} radius - The radius of the circle. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Circle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaCircle: function (gameObjects, x, y, radius, callback) + { + if (callback === undefined) { callback = CircleContains; } + + var shape = new Circle(x, y, radius); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Ellipse` shape, using + * the given coordinates and dimensions to control its position and size. + * + * @method Phaser.Input.InputPlugin#setHitAreaEllipse + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having an ellipse hit area. + * @param {number} x - The center of the ellipse. + * @param {number} y - The center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Ellipse.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaEllipse: function (gameObjects, x, y, width, height, callback) + { + if (callback === undefined) { callback = EllipseContains; } + + var shape = new Ellipse(x, y, width, height); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * 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 an ellipse hit area. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaFromTexture: function (gameObjects, callback) + { + if (callback === undefined) { callback = RectangleContains; } + + if (!Array.isArray(gameObjects)) + { + gameObjects = [ gameObjects ]; + } + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + var frame = gameObject.frame; + + var width = 0; + var height = 0; + + if (gameObject.width) + { + width = gameObject.width; + height = gameObject.height; + } + else if (frame) + { + width = frame.realWidth; + height = frame.realHeight; + } + + if (gameObject.type === 'Container' && (width === 0 || height === 0)) + { + console.warn('Container.setInteractive must specify a Shape or call setSize() first'); + continue; + } + + if (width !== 0 && height !== 0) + { + gameObject.input = CreateInteractiveObject(gameObject, new Rectangle(0, 0, width, height), callback); + + this.queueForInsertion(gameObject); + } + } + + return this; + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Rectangle` shape, using + * the given coordinates and dimensions to control its position and size. + * + * @method Phaser.Input.InputPlugin#setHitAreaRectangle + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a rectangular hit area. + * @param {number} x - The top-left of the rectangle. + * @param {number} y - The top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaRectangle: function (gameObjects, x, y, width, height, callback) + { + if (callback === undefined) { callback = RectangleContains; } + + var shape = new Rectangle(x, y, width, height); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Triangle` shape, using + * the given coordinates to control the position of its points. + * + * @method Phaser.Input.InputPlugin#setHitAreaTriangle + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a triangular hit area. + * @param {number} x1 - The x coordinate of the first point of the triangle. + * @param {number} y1 - The y coordinate of the first point of the triangle. + * @param {number} x2 - The x coordinate of the second point of the triangle. + * @param {number} y2 - The y coordinate of the second point of the triangle. + * @param {number} x3 - The x coordinate of the third point of the triangle. + * @param {number} y3 - The y coordinate of the third point of the triangle. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Triangle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaTriangle: function (gameObjects, x1, y1, x2, y2, x3, y3, callback) + { + if (callback === undefined) { callback = TriangleContains; } + + var shape = new Triangle(x1, y1, x2, y2, x3, y3); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * Creates an Input Debug Shape for the given Game Object. + * + * The Game Object must have _already_ been enabled for input prior to calling this method. + * + * This is intended to assist you during development and debugging. + * + * Debug Shapes can only be created for Game Objects that are using standard Phaser Geometry for input, + * including: Circle, Ellipse, Line, Polygon, Rectangle and Triangle. + * + * Game Objects that are using their automatic hit areas are using Rectangles by default, so will also work. + * + * The Debug Shape is created and added to the display list and is then kept in sync with the Game Object + * it is connected with. Should you need to modify it yourself, such as to hide it, you can access it via + * the Game Object property: `GameObject.input.hitAreaDebug`. + * + * Calling this method on a Game Object that already has a Debug Shape will first destroy the old shape, + * before creating a new one. If you wish to remove the Debug Shape entirely, you should call the + * method `InputPlugin.removeDebug`. + * + * Note that the debug shape will only show the outline of the input area. If the input test is using a + * pixel perfect check, for example, then this is not displayed. If you are using a custom shape, that + * doesn't extend one of the base Phaser Geometry objects, as your hit area, then this method will not + * work. + * + * @method Phaser.Input.InputPlugin#enableDebug + * @since 3.19.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to create the input debug shape for. + * @param {number} [color=0x00ff00] - The outline color of the debug shape. + * + * @return {Phaser.Input.InputPlugin} This Input Plugin. + */ + enableDebug: function (gameObject, color) + { + if (color === undefined) { color = 0x00ff00; } + + var input = gameObject.input; + + if (!input || !input.hitArea) + { + return this; + } + + var shape = input.hitArea; + var shapeType = shape.type; + var debug = input.hitAreaDebug; + var factory = this.systems.add; + var updateList = this.systems.updateList; + + if (debug) + { + updateList.remove(debug); + + debug.destroy(); + + debug = null; + } + + var offsetx = 0; + var offsety = 0; + switch (shapeType) + { + case GEOM_CONST.CIRCLE: + debug = factory.arc(0, 0, shape.radius); + offsetx = shape.x - shape.radius; + offsety = shape.y - shape.radius; + break; + + case GEOM_CONST.ELLIPSE: + debug = factory.ellipse(0, 0, shape.width, shape.height); + offsetx = shape.x - shape.width / 2; + offsety = shape.y - shape.height / 2; + break; + + case GEOM_CONST.LINE: + debug = factory.line(0, 0, shape.x1, shape.y1, shape.x2, shape.y2); + break; + + case GEOM_CONST.POLYGON: + debug = factory.polygon(0, 0, shape.points); + break; + + case GEOM_CONST.RECTANGLE: + debug = factory.rectangle(0, 0, shape.width, shape.height); + offsetx = shape.x; + offsety = shape.y; + break; + + case GEOM_CONST.TRIANGLE: + debug = factory.triangle(0, 0, shape.x1, shape.y1, shape.x2, shape.y2, shape.x3, shape.y3); + break; + } + + if (debug) + { + debug.isFilled = false; + + debug.preUpdate = function () + { + debug.setStrokeStyle(1 / gameObject.scale, color); + + debug.setDisplayOrigin(gameObject.displayOriginX, gameObject.displayOriginY); + debug.setRotation(gameObject.rotation); + debug.setScale(gameObject.scaleX, gameObject.scaleY); + debug.setPosition(gameObject.x + offsetx, gameObject.y + offsety); + debug.setScrollFactor(gameObject.scrollFactorX, gameObject.scrollFactorY); + }; + + updateList.add(debug); + + input.hitAreaDebug = debug; + } + + return this; + }, + + /** + * Removes an Input Debug Shape from the given Game Object. + * + * The shape is destroyed immediately and the `hitAreaDebug` property is set to `null`. + * + * @method Phaser.Input.InputPlugin#removeDebug + * @since 3.19.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to remove the input debug shape from. + * + * @return {Phaser.Input.InputPlugin} This Input Plugin. + */ + removeDebug: function (gameObject) + { + var input = gameObject.input; + + if (input && input.hitAreaDebug) + { + var debug = input.hitAreaDebug; + + this.systems.updateList.remove(debug); + + debug.destroy(); + + input.hitAreaDebug = null; + } + + return this; + }, + + /** + * Sets the Pointers to always poll. + * + * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, + * or being interacted with it, regardless if the Pointer has actually moved or not. + * + * You should enable this if you want objects in your game to fire over / out events, and the objects + * are constantly moving, but the pointer may not have. Polling every frame has additional computation + * costs, especially if there are a large number of interactive objects in your game. + * + * @method Phaser.Input.InputPlugin#setPollAlways + * @since 3.0.0 + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setPollAlways: function () + { + return this.setPollRate(0); + }, + + /** + * Sets the Pointers to only poll when they are moved or updated. + * + * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, + * or being interacted with it. + * + * @method Phaser.Input.InputPlugin#setPollOnMove + * @since 3.0.0 + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setPollOnMove: function () + { + return this.setPollRate(-1); + }, + + /** + * Sets the poll rate value. This is the amount of time that should have elapsed before a pointer + * will be polled again. See the `setPollAlways` and `setPollOnMove` methods. + * + * @method Phaser.Input.InputPlugin#setPollRate + * @since 3.0.0 + * + * @param {number} value - The amount of time, in ms, that should elapsed before re-polling the pointers. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setPollRate: function (value) + { + this.pollRate = value; + this._pollTimer = 0; + + return this; + }, + + /** + * When set to `true` the global Input Manager will emulate DOM behavior by only emitting events from + * the top-most Scene in the Scene List. By default, if a Scene receives an input event it will then stop the event + * from flowing down to any Scenes below it in the Scene list. To disable this behavior call this method with `false`. + * + * @method Phaser.Input.InputPlugin#setGlobalTopOnly + * @since 3.0.0 + * + * @param {boolean} value - Set to `true` to stop processing input events on the Scene that receives it, or `false` to let the event continue down the Scene list. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setGlobalTopOnly: function (value) + { + this.manager.globalTopOnly = value; + + return this; + }, + + /** + * When set to `true` this Input Plugin will emulate DOM behavior by only emitting events from + * the top-most Game Objects in the Display List. + * + * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. + * + * @method Phaser.Input.InputPlugin#setTopOnly + * @since 3.0.0 + * + * @param {boolean} value - `true` to only include the top-most Game Object, or `false` to include all Game Objects in a hit test. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setTopOnly: function (value) + { + this.topOnly = value; + + return this; + }, + + /** + * Given an array of Game Objects, sort the array and return it, so that the objects are in depth index order + * with the lowest at the bottom. + * + * @method Phaser.Input.InputPlugin#sortGameObjects + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject[]} gameObjects - An array of Game Objects to be sorted. + * + * @return {Phaser.GameObjects.GameObject[]} The sorted array of Game Objects. + */ + sortGameObjects: function (gameObjects) + { + if (gameObjects.length < 2) + { + return gameObjects; + } + + this.scene.sys.depthSort(); + + return gameObjects.sort(this.sortHandlerGO.bind(this)); + }, + + /** + * Return the child lowest down the display list (with the smallest index) + * Will iterate through all parent containers, if present. + * + * @method Phaser.Input.InputPlugin#sortHandlerGO + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} childA - The first Game Object to compare. + * @param {Phaser.GameObjects.GameObject} childB - The second Game Object to compare. + * + * @return {integer} Returns either a negative or positive integer, or zero if they match. + */ + sortHandlerGO: function (childA, childB) + { + if (!childA.parentContainer && !childB.parentContainer) + { + // Quick bail out when neither child has a container + return this.displayList.getIndex(childB) - this.displayList.getIndex(childA); + } + else if (childA.parentContainer === childB.parentContainer) + { + // Quick bail out when both children have the same container + return childB.parentContainer.getIndex(childB) - childA.parentContainer.getIndex(childA); + } + else if (childA.parentContainer === childB) + { + // Quick bail out when childA is a child of childB + return -1; + } + else if (childB.parentContainer === childA) + { + // Quick bail out when childA is a child of childB + return 1; + } + else + { + // Container index check + var listA = childA.getIndexList(); + var listB = childB.getIndexList(); + var len = Math.min(listA.length, listB.length); + + for (var i = 0; i < len; i++) + { + var indexA = listA[i]; + var indexB = listB[i]; + + if (indexA === indexB) + { + // Go to the next level down + continue; + } + else + { + // Non-matching parents, so return + return indexB - indexA; + } + } + } + + // Technically this shouldn't happen, but ... + return 0; + }, + + /** + * This method should be called from within an input event handler, such as `pointerdown`. + * + * When called, it stops the Input Manager from allowing _this specific event_ to be processed by any other Scene + * not yet handled in the scene list. + * + * @method Phaser.Input.InputPlugin#stopPropagation + * @since 3.0.0 + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + stopPropagation: function () + { + this.manager._tempSkip = true; + + return this; + }, + + /** + * Adds new Pointer objects to the Input Manager. + * + * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. + * + * You can create more either by calling this method, or by setting the `input.activePointers` property + * in the Game Config, up to a maximum of 10 pointers. + * + * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added + * via this method. + * + * @method Phaser.Input.InputPlugin#addPointer + * @since 3.10.0 + * + * @param {integer} [quantity=1] The number of new Pointers to create. A maximum of 10 is allowed in total. + * + * @return {Phaser.Input.Pointer[]} An array containing all of the new Pointer objects that were created. + */ + addPointer: function (quantity) + { + return this.manager.addPointer(quantity); + }, + + /** + * 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 {Phaser.Input.InputPlugin} This Input instance. + */ + setDefaultCursor: function (cursor) + { + this.manager.setDefaultCursor(cursor); + + return this; + }, + + /** + * The Scene that owns this plugin is transitioning in. + * + * @method Phaser.Input.InputPlugin#transitionIn + * @private + * @since 3.5.0 + */ + transitionIn: function () + { + this.enabled = this.settings.transitionAllowInput; + }, + + /** + * The Scene that owns this plugin has finished transitioning in. + * + * @method Phaser.Input.InputPlugin#transitionComplete + * @private + * @since 3.5.0 + */ + transitionComplete: function () + { + if (!this.settings.transitionAllowInput) + { + this.enabled = true; + } + }, + + /** + * The Scene that owns this plugin is transitioning out. + * + * @method Phaser.Input.InputPlugin#transitionOut + * @private + * @since 3.5.0 + */ + transitionOut: function () + { + this.enabled = this.settings.transitionAllowInput; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Input.InputPlugin#shutdown + * @fires Phaser.Input.Events#SHUTDOWN + * @private + * @since 3.0.0 + */ + shutdown: function () + { + // Registered input plugins listen for this + this.pluginEvents.emit(Events.SHUTDOWN); + + this._temp.length = 0; + this._list.length = 0; + this._draggable.length = 0; + this._pendingRemoval.length = 0; + this._pendingInsertion.length = 0; + this._dragState.length = 0; + + for (var i = 0; i < 10; i++) + { + this._drag[i] = []; + this._over[i] = []; + } + + this.removeAllListeners(); + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.TRANSITION_START, this.transitionIn, this); + eventEmitter.off(SceneEvents.TRANSITION_OUT, this.transitionOut, this); + eventEmitter.off(SceneEvents.TRANSITION_COMPLETE, this.transitionComplete, this); + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + + this.manager.events.off(Events.GAME_OUT, this.onGameOut, this); + this.manager.events.off(Events.GAME_OVER, this.onGameOver, this); + + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Input.InputPlugin#destroy + * @fires Phaser.Input.Events#DESTROY + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + // Registered input plugins listen for this + this.pluginEvents.emit(Events.DESTROY); + + this.pluginEvents.removeAllListeners(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.cameras = null; + this.manager = null; + this.events = null; + this.mouse = null; + }, + + /** + * The x coordinates 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 + */ + x: { + + get: function () + { + return this.manager.activePointer.x; + } + + }, + + /** + * The y coordinates 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 + */ + y: { + + get: function () + { + return this.manager.activePointer.y; + } + + }, + + /** + * Are any mouse or touch pointers currently over the game canvas? + * + * @name Phaser.Input.InputPlugin#isOver + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isOver: { + + get: function () + { + return this.manager.isOver; + } + + }, + + /** + * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. + * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` + * which will always map to the most recently interacted pointer. + * + * @name Phaser.Input.InputPlugin#mousePointer + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + mousePointer: { + + get: function () + { + return this.manager.mousePointer; + } + + }, + + /** + * The current active input Pointer. + * + * @name Phaser.Input.InputPlugin#activePointer + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.0.0 + */ + activePointer: { + + get: function () + { + return this.manager.activePointer; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer1 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer1: { + + get: function () + { + return this.manager.pointers[1]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer2 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer2: { + + get: function () + { + return this.manager.pointers[2]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer3 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer3: { + + get: function () + { + return this.manager.pointers[3]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer4 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer4: { + + get: function () + { + return this.manager.pointers[4]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer5 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer5: { + + get: function () + { + return this.manager.pointers[5]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer6 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer6: { + + get: function () + { + return this.manager.pointers[6]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer7 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer7: { + + get: function () + { + return this.manager.pointers[7]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer8 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer8: { + + get: function () + { + return this.manager.pointers[8]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer9 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer9: { + + get: function () + { + return this.manager.pointers[9]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer10 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer10: { + + get: function () + { + return this.manager.pointers[10]; + } + + } + +}); + +PluginCache.register('InputPlugin', InputPlugin, 'input'); + +module.exports = InputPlugin; + + +/***/ }), +/* 1238 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates a new Pixel Perfect Handler function. + * + * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. + * + * @function Phaser.Input.CreatePixelPerfectHandler + * @since 3.10.0 + * + * @param {Phaser.Textures.TextureManager} textureManager - A reference to the Texture Manager. + * @param {integer} alphaTolerance - The alpha level that the pixel should be above to be included as a successful interaction. + * + * @return {function} The new Pixel Perfect Handler function. + */ +var CreatePixelPerfectHandler = function (textureManager, alphaTolerance) +{ + return function (hitArea, x, y, gameObject) + { + var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.name); + + return (alpha && alpha >= alphaTolerance); + }; +}; + +module.exports = CreatePixelPerfectHandler; + + +/***/ }), +/* 1239 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Keyboard + */ + +module.exports = { + + Events: __webpack_require__(142), + + KeyboardManager: __webpack_require__(390), + KeyboardPlugin: __webpack_require__(1247), + + Key: __webpack_require__(476), + KeyCodes: __webpack_require__(131), + + KeyCombo: __webpack_require__(477), + + JustDown: __webpack_require__(1252), + JustUp: __webpack_require__(1253), + DownDuration: __webpack_require__(1254), + UpDuration: __webpack_require__(1255) + +}; + + +/***/ }), +/* 1240 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'keydown'; + + +/***/ }), +/* 1241 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Global Key Up Event. + * + * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. + * + * Listen to this event from within a Scene using: `this.input.keyboard.on('keyup', listener)`. + * + * You can also listen for a specific key being released. See [Keyboard.Events.KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:KEY_UP} for details. + * + * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. + * + * @event Phaser.Input.Keyboard.Events#ANY_KEY_UP + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was released, any modifiers, etc. + */ +module.exports = 'keyup'; + + +/***/ }), +/* 1242 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Combo Match Event. + * + * This event is dispatched by the Keyboard Plugin when a [Key Combo]{@link Phaser.Input.Keyboard.KeyCombo} is matched. + * + * Listen for this event from the Key Plugin after a combo has been created: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * @event Phaser.Input.Keyboard.Events#COMBO_MATCH + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyCombo} keycombo - The Key Combo object that was matched. + * @param {KeyboardEvent} event - The native DOM Keyboard Event of the final key in the combo. You can inspect this to learn more about any modifiers, etc. + */ +module.exports = 'keycombomatch'; + + +/***/ }), +/* 1243 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Down Event. + * + * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is pressed. + * + * Listen for this event from the Key object instance directly: + * + * ```javascript + * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); + * + * spaceBar.on('down', 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. + * + * @event Phaser.Input.Keyboard.Events#DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key object that was pressed. + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about any modifiers, etc. + */ +module.exports = 'down'; + + +/***/ }), +/* 1244 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'keydown-'; + + +/***/ }), +/* 1245 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Up Event. + * + * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. + * + * Unlike the `ANY_KEY_UP` event, this one has a special dynamic event name. For example, to listen for the `A` key being released + * use the following from within a Scene: `this.input.keyboard.on('keyup-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('keyup-SPACE', listener)`. + * + * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. + * + * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. + * + * @event Phaser.Input.Keyboard.Events#KEY_UP + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was released, any modifiers, etc. + */ +module.exports = 'keyup-'; + + +/***/ }), +/* 1246 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Up Event. + * + * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is released. + * + * Listen for this event from the Key object instance directly: + * + * ```javascript + * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); + * + * spaceBar.on('up', listener) + * ``` + * + * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. + * + * @event Phaser.Input.Keyboard.Events#UP + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key object that was released. + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about any modifiers, etc. + */ +module.exports = 'up'; + + +/***/ }), +/* 1247 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(142); +var GameEvents = __webpack_require__(21); +var GetValue = __webpack_require__(5); +var InputEvents = __webpack_require__(56); +var InputPluginCache = __webpack_require__(141); +var Key = __webpack_require__(476); +var KeyCodes = __webpack_require__(131); +var KeyCombo = __webpack_require__(477); +var KeyMap = __webpack_require__(1251); +var SnapFloor = __webpack_require__(105); + +/** + * @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. + * + * 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. + */ +var KeyboardPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function KeyboardPlugin (sceneInputPlugin) + { + EventEmitter.call(this); + + /** + * A reference to the core game, so we can listen for visibility events. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#game + * @type {Phaser.Game} + * @since 3.16.0 + */ + this.game = sceneInputPlugin.systems.game; + + /** + * A reference to the Scene that this Input Plugin is responsible for. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#scene + * @type {Phaser.Scene} + * @since 3.10.0 + */ + this.scene = sceneInputPlugin.scene; + + /** + * A reference to the Scene Systems Settings. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.10.0 + */ + this.settings = this.scene.sys.settings; + + /** + * A reference to the Scene Input Plugin that created this Keyboard Plugin. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#sceneInputPlugin + * @type {Phaser.Input.InputPlugin} + * @since 3.10.0 + */ + this.sceneInputPlugin = sceneInputPlugin; + + /** + * A reference to the global Keyboard Manager. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#manager + * @type {Phaser.Input.InputPlugin} + * @since 3.16.0 + */ + this.manager = sceneInputPlugin.manager.keyboard; + + /** + * A boolean that controls if this Keyboard Plugin is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#enabled + * @type {boolean} + * @default true + * @since 3.10.0 + */ + this.enabled = true; + + /** + * An array of Key objects to process. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#keys + * @type {Phaser.Input.Keyboard.Key[]} + * @since 3.10.0 + */ + this.keys = []; + + /** + * An array of KeyCombo objects to process. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#combos + * @type {Phaser.Input.Keyboard.KeyCombo[]} + * @since 3.10.0 + */ + this.combos = []; + + sceneInputPlugin.pluginEvents.once(InputEvents.BOOT, this.boot, this); + sceneInputPlugin.pluginEvents.on(InputEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#boot + * @private + * @since 3.10.0 + */ + boot: function () + { + var settings = this.settings.input; + + this.enabled = GetValue(settings, 'keyboard', true); + + var captures = GetValue(settings, 'keyboard.capture', null); + + if (captures) + { + this.addCaptures(captures); + } + + this.sceneInputPlugin.pluginEvents.once(InputEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#start + * @private + * @since 3.10.0 + */ + start: function () + { + if (this.sceneInputPlugin.manager.useQueue) + { + this.sceneInputPlugin.pluginEvents.on(InputEvents.UPDATE, this.update, this); + } + else + { + this.sceneInputPlugin.manager.events.on(InputEvents.MANAGER_PROCESS, this.update, this); + } + + this.sceneInputPlugin.pluginEvents.once(InputEvents.SHUTDOWN, this.shutdown, this); + + this.game.events.on(GameEvents.BLUR, this.resetKeys, this); + }, + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#isActive + * @since 3.10.0 + * + * @return {boolean} `true` if the plugin and the Scene it belongs to is active. + */ + isActive: function () + { + return (this.enabled && this.scene.sys.isActive()); + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * This `addCapture` method enables consuming keyboard events for specific keys, so they don't bubble up the browser + * and cause the default behaviors. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent + * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. + * + * You can pass a single key code value: + * + * ```javascript + * this.input.keyboard.addCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.addCapture([ 62, 63, 64 ]); + * ``` + * + * Or, a comma-delimited string: + * + * ```javascript + * this.input.keyboard.addCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#addCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to enable event capture for. + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + addCapture: function (keycode) + { + this.manager.addCapture(keycode); + + return this; + }, + + /** + * Removes an existing key capture. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove + * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. + * + * You can pass a single key code value: + * + * ```javascript + * this.input.keyboard.removeCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.removeCapture([ 62, 63, 64 ]); + * ``` + * + * Or, a comma-delimited string: + * + * ```javascript + * this.input.keyboard.removeCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#removeCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to disable event capture for. + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + removeCapture: function (keycode) + { + this.manager.removeCapture(keycode); + + return this; + }, + + /** + * Returns an array that contains all of the keyboard captures currently enabled. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#getCaptures + * @since 3.16.0 + * + * @return {integer[]} An array of all the currently capturing key codes. + */ + getCaptures: function () + { + return this.manager.captures; + }, + + /** + * Allows Phaser to prevent any key captures you may have defined from bubbling up the browser. + * You can use this to re-enable event capturing if you had paused it via `disableGlobalCapture`. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#enableGlobalCapture + * @since 3.16.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + enableGlobalCapture: function () + { + this.manager.preventDefault = true; + + return this; + }, + + /** + * Disables Phaser from preventing any key captures you may have defined, without actually removing them. + * You can use this to temporarily disable event capturing if, for example, you swap to a DOM element. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#disableGlobalCapture + * @since 3.16.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + disableGlobalCapture: function () + { + this.manager.preventDefault = false; + + return this; + }, + + /** + * Removes all keyboard captures. + * + * Note that this is a global change. It will clear all event captures across your game, not just for this specific Scene. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#clearCaptures + * @since 3.16.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + clearCaptures: function () + { + this.manager.clearCaptures(); + + return this; + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right, and also Space Bar and shift. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#createCursorKeys + * @since 3.10.0 + * + * @return {Phaser.Types.Input.Keyboard.CursorKeys} An object containing the properties: `up`, `down`, `left`, `right`, `space` and `shift`. + */ + createCursorKeys: function () + { + return this.addKeys({ + up: KeyCodes.UP, + down: KeyCodes.DOWN, + left: KeyCodes.LEFT, + right: KeyCodes.RIGHT, + space: KeyCodes.SPACE, + shift: KeyCodes.SHIFT + }); + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example: + * + * ```javascript + * this.input.keyboard.addKeys({ 'up': Phaser.Input.Keyboard.KeyCodes.W, 'down': Phaser.Input.Keyboard.KeyCodes.S }); + * ``` + * + * would return an object containing the properties (`up` and `down`) mapped to W and S {@link Phaser.Input.Keyboard.Key} objects. + * + * You can also pass in a comma-separated string: + * + * ```javascript + * this.input.keyboard.addKeys('W,S,A,D'); + * ``` + * + * Which will return an object with the properties W, S, A and D mapped to the relevant Key objects. + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#addKeys + * @since 3.10.0 + * + * @param {(object|string)} keys - An object containing Key Codes, or a comma-separated string. + * @param {boolean} [enableCapture=true] - Automatically call `preventDefault` on the native DOM browser event for the key codes being added. + * @param {boolean} [emitOnRepeat=false] - Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). + * + * @return {object} An object containing Key objects mapped to the input properties. + */ + addKeys: function (keys, enableCapture, emitOnRepeat) + { + if (enableCapture === undefined) { enableCapture = true; } + if (emitOnRepeat === undefined) { emitOnRepeat = false; } + + var output = {}; + + if (typeof keys === 'string') + { + keys = keys.split(','); + + for (var i = 0; i < keys.length; i++) + { + var currentKey = keys[i].trim(); + + if (currentKey) + { + output[currentKey] = this.addKey(currentKey, enableCapture, emitOnRepeat); + } + } + } + else + { + for (var key in keys) + { + output[key] = this.addKey(keys[key], enableCapture, emitOnRepeat); + } + } + + return output; + }, + + /** + * Adds a Key object to this Keyboard Plugin. + * + * The given argument can be either an existing Key object, a string, such as `A` or `SPACE`, or a key code value. + * + * If a Key object is given, and one already exists matching the same key code, the existing one is replaced with the new one. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#addKey + * @since 3.10.0 + * + * @param {(Phaser.Input.Keyboard.Key|string|integer)} key - Either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param {boolean} [enableCapture=true] - Automatically call `preventDefault` on the native DOM browser event for the key codes being added. + * @param {boolean} [emitOnRepeat=false] - Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). + * + * @return {Phaser.Input.Keyboard.Key} The newly created Key object, or a reference to it if it already existed in the keys array. + */ + addKey: function (key, enableCapture, emitOnRepeat) + { + if (enableCapture === undefined) { enableCapture = true; } + if (emitOnRepeat === undefined) { emitOnRepeat = false; } + + var keys = this.keys; + + if (key instanceof Key) + { + var idx = keys.indexOf(key); + + if (idx > -1) + { + keys[idx] = key; + } + else + { + keys[key.keyCode] = key; + } + + if (enableCapture) + { + this.addCapture(key.keyCode); + } + + key.setEmitOnRepeat(emitOnRepeat); + + return key; + } + + if (typeof key === 'string') + { + key = KeyCodes[key.toUpperCase()]; + } + + if (!keys[key]) + { + keys[key] = new Key(this, key); + + if (enableCapture) + { + this.addCapture(key); + } + + keys[key].setEmitOnRepeat(emitOnRepeat); + } + + return keys[key]; + }, + + /** + * Removes a Key object from this Keyboard Plugin. + * + * The given argument can be either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#removeKey + * @since 3.10.0 + * + * @param {(Phaser.Input.Keyboard.Key|string|integer)} key - Either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param {boolean} [destroy=false] - Call `Key.destroy` on the removed Key object? + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + removeKey: function (key, destroy) + { + if (destroy === undefined) { destroy = false; } + + var keys = this.keys; + var ref; + + if (key instanceof Key) + { + var idx = keys.indexOf(key); + + if (idx > -1) + { + ref = this.keys[idx]; + + this.keys[idx] = undefined; + } + } + else if (typeof key === 'string') + { + key = KeyCodes[key.toUpperCase()]; + } + + if (keys[key]) + { + ref = keys[key]; + + keys[key] = undefined; + } + + if (ref) + { + ref.plugin = null; + + if (destroy) + { + ref.destroy(); + } + } + + return this; + }, + + /** + * Creates a new KeyCombo. + * + * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them + * it will emit a `keycombomatch` event from this Keyboard Plugin. + * + * The keys to be listened for can be defined as: + * + * A string (i.e. 'ATARI') + * An array of either integers (key codes) or strings, or a mixture of both + * An array of objects (such as Key objects) with a public 'keyCode' property + * + * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) + * you could pass the following array of key codes: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * Or, to listen for the user entering the word PHASER: + * + * ```javascript + * this.input.keyboard.createCombo('PHASER'); + * ``` + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#createCombo + * @since 3.10.0 + * + * @param {(string|integer[]|object[])} keys - The keys that comprise this combo. + * @param {Phaser.Types.Input.Keyboard.KeyComboConfig} [config] - A Key Combo configuration object. + * + * @return {Phaser.Input.Keyboard.KeyCombo} The new KeyCombo object. + */ + createCombo: function (keys, config) + { + return new KeyCombo(this, keys, config); + }, + + /** + * Checks if the given Key object is currently being held down. + * + * The difference between this method and checking the `Key.isDown` property directly is that you can provide + * a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted + * it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it + * will only return `true` every 100ms. + * + * If the Keyboard Plugin has been disabled, this method will always return `false`. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#checkDown + * @since 3.11.0 + * + * @param {Phaser.Input.Keyboard.Key} key - A Key object. + * @param {number} [duration=0] - The duration which must have elapsed before this Key is considered as being down. + * + * @return {boolean} `true` if the Key is down within the duration specified, otherwise `false`. + */ + checkDown: function (key, duration) + { + if (this.enabled && key.isDown) + { + var t = SnapFloor(this.time - key.timeDown, duration); + + if (t > key._tick) + { + key._tick = t; + + return true; + } + } + + return false; + }, + + /** + * Internal update handler called by the Input Plugin, which is in turn invoked by the Game step. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#update + * @private + * @since 3.10.0 + */ + update: function () + { + var queue = this.manager.queue; + var len = queue.length; + + if (!this.isActive() || len === 0) + { + return; + } + + var keys = this.keys; + + // Process the event queue, dispatching all of the events that have stored up + for (var i = 0; i < len; i++) + { + var event = queue[i]; + var code = event.keyCode; + var key = keys[code]; + var repeat = false; + + // Override the default functions (it's too late for the browser to use them anyway, so we may as well) + if (event.cancelled === undefined) + { + // Event allowed to flow across all handlers in this Scene, and any other Scene in the Scene list + event.cancelled = 0; + + // Won't reach any more local (Scene level) handlers + event.stopImmediatePropagation = function () + { + event.cancelled = 1; + }; + + // Won't reach any more handlers in any Scene further down the Scene list + event.stopPropagation = function () + { + event.cancelled = -1; + }; + } + + if (event.cancelled === -1) + { + // This event has been stopped from broadcasting to any other Scene, so abort. + continue; + } + + if (event.type === 'keydown') + { + // Key specific callback first + if (key) + { + repeat = key.isDown; + + key.onDown(event); + } + + if (!event.cancelled && (!key || !repeat)) + { + if (KeyMap[code]) + { + this.emit(Events.KEY_DOWN + KeyMap[code], event); + + // Deprecated, kept in for compatibility with 3.15 + // To be removed by 3.20. + this.emit('keydown_' + KeyMap[code], event); + } + + if (!event.cancelled) + { + this.emit(Events.ANY_KEY_DOWN, event); + } + } + } + else + { + // Key specific callback first + if (key) + { + key.onUp(event); + } + + if (!event.cancelled) + { + if (KeyMap[code]) + { + this.emit(Events.KEY_UP + KeyMap[code], event); + + // Deprecated, kept in for compatibility with 3.15 + // To be removed by 3.20. + this.emit('keyup_' + KeyMap[code], event); + } + + if (!event.cancelled) + { + this.emit(Events.ANY_KEY_UP, event); + } + } + } + + // Reset the cancel state for other Scenes to use + if (event.cancelled === 1) + { + event.cancelled = 0; + } + } + }, + + /** + * Resets all Key objects created by _this_ Keyboard Plugin back to their default un-pressed states. + * This can only reset keys created via the `addKey`, `addKeys` or `createCursorKeys` methods. + * If you have created a Key object directly you'll need to reset it yourself. + * + * This method is called automatically when the Keyboard Plugin shuts down, but can be + * invoked directly at any time you require. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#resetKeys + * @since 3.15.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + resetKeys: function () + { + var keys = this.keys; + + for (var i = 0; i < keys.length; i++) + { + // Because it's a sparsely populated array + if (keys[i]) + { + keys[i].reset(); + } + } + + return this; + }, + + /** + * Shuts this Keyboard Plugin down. This performs the following tasks: + * + * 1 - Resets all keys created by this Keyboard plugin. + * 2 - Stops and removes the keyboard event listeners. + * 3 - Clears out any pending requests in the queue, without processing them. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#shutdown + * @private + * @since 3.10.0 + */ + shutdown: function () + { + this.resetKeys(); + + if (this.sceneInputPlugin.manager.useQueue) + { + this.sceneInputPlugin.pluginEvents.off(InputEvents.UPDATE, this.update, this); + } + else + { + this.sceneInputPlugin.manager.events.off(InputEvents.MANAGER_PROCESS, this.update, this); + } + + this.game.events.off(GameEvents.BLUR, this.resetKeys); + + this.removeAllListeners(); + + this.queue = []; + }, + + /** + * Destroys this Keyboard Plugin instance and all references it holds, plus clears out local arrays. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#destroy + * @private + * @since 3.10.0 + */ + destroy: function () + { + this.shutdown(); + + var keys = this.keys; + + for (var i = 0; i < keys.length; i++) + { + // Because it's a sparsely populated array + if (keys[i]) + { + keys[i].destroy(); + } + } + + this.keys = []; + this.combos = []; + this.queue = []; + + this.scene = null; + this.settings = null; + this.sceneInputPlugin = null; + this.manager = null; + }, + + /** + * Internal time value. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#time + * @type {number} + * @private + * @since 3.11.0 + */ + time: { + + get: function () + { + return this.sceneInputPlugin.manager.time; + } + + } + +}); + +/** + * An instance of the Keyboard Plugin class, if enabled via the `input.keyboard` Scene or Game Config property. + * Use this to create Key objects and listen for keyboard specific events. + * + * @name Phaser.Input.InputPlugin#keyboard + * @type {?Phaser.Input.Keyboard.KeyboardPlugin} + * @since 3.10.0 + */ +InputPluginCache.register('KeyboardPlugin', KeyboardPlugin, 'keyboard', 'keyboard', 'inputKeyboard'); + +module.exports = KeyboardPlugin; + + +/***/ }), +/* 1248 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AdvanceKeyCombo = __webpack_require__(1249); + +/** + * Used internally by the KeyCombo class. + * + * @function Phaser.Input.Keyboard.KeyCombo.ProcessKeyCombo + * @private + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native Keyboard Event. + * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo object to be processed. + * + * @return {boolean} `true` if the combo was matched, otherwise `false`. + */ +var ProcessKeyCombo = function (event, combo) +{ + if (combo.matched) + { + return true; + } + + var comboMatched = false; + var keyMatched = false; + + if (event.keyCode === combo.current) + { + // Key was correct + + if (combo.index > 0 && combo.maxKeyDelay > 0) + { + // We have to check to see if the delay between + // the new key and the old one was too long (if enabled) + + var timeLimit = combo.timeLastMatched + combo.maxKeyDelay; + + // Check if they pressed it in time or not + if (event.timeStamp <= timeLimit) + { + keyMatched = true; + comboMatched = AdvanceKeyCombo(event, combo); + } + } + else + { + keyMatched = true; + + // We don't check the time for the first key pressed, so just advance it + comboMatched = AdvanceKeyCombo(event, combo); + } + } + + if (!keyMatched && combo.resetOnWrongKey) + { + // Wrong key was pressed + combo.index = 0; + combo.current = combo.keyCodes[0]; + } + + if (comboMatched) + { + combo.timeLastMatched = event.timeStamp; + combo.matched = true; + combo.timeMatched = event.timeStamp; + } + + return comboMatched; +}; + +module.exports = ProcessKeyCombo; + + +/***/ }), +/* 1249 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Used internally by the KeyCombo class. + * Return `true` if it reached the end of the combo, `false` if not. + * + * @function Phaser.Input.Keyboard.KeyCombo.AdvanceKeyCombo + * @private + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native Keyboard Event. + * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo object to advance. + * + * @return {boolean} `true` if it reached the end of the combo, `false` if not. + */ +var AdvanceKeyCombo = function (event, combo) +{ + combo.timeLastMatched = event.timeStamp; + combo.index++; + + if (combo.index === combo.size) + { + return true; + } + else + { + combo.current = combo.keyCodes[combo.index]; + return false; + } +}; + +module.exports = AdvanceKeyCombo; + + +/***/ }), +/* 1250 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Used internally by the KeyCombo class. + * + * @function Phaser.Input.Keyboard.KeyCombo.ResetKeyCombo + * @private + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo to reset. + * + * @return {Phaser.Input.Keyboard.KeyCombo} The KeyCombo. + */ +var ResetKeyCombo = function (combo) +{ + combo.current = combo.keyCodes[0]; + combo.index = 0; + combo.timeLastMatched = 0; + combo.matched = false; + combo.timeMatched = 0; + + return combo; +}; + +module.exports = ResetKeyCombo; + + +/***/ }), +/* 1251 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var KeyCodes = __webpack_require__(131); + +var KeyMap = {}; + +for (var key in KeyCodes) +{ + KeyMap[KeyCodes[key]] = key; +} + +module.exports = KeyMap; + + +/***/ }), +/* 1252 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The justDown value allows you to test if this Key has just been pressed down or not. + * + * When you check this value it will return `true` if the Key is down, otherwise `false`. + * + * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. + * This allows you to use it in situations where you want to check if this key is down without using an event, such as in a core game loop. + * + * @function Phaser.Input.Keyboard.JustDown + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key to check to see if it's just down or not. + * + * @return {boolean} `true` if the Key was just pressed, otherwise `false`. + */ +var JustDown = function (key) +{ + if (key._justDown) + { + key._justDown = false; + + return true; + } + else + { + return false; + } +}; + +module.exports = JustDown; + + +/***/ }), +/* 1253 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The justUp value allows you to test if this Key has just been released or not. + * + * When you check this value it will return `true` if the Key is up, otherwise `false`. + * + * You can only call JustUp once per key release. It will only return `true` once, until the Key is pressed down and released again. + * This allows you to use it in situations where you want to check if this key is up without using an event, such as in a core game loop. + * + * @function Phaser.Input.Keyboard.JustUp + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key to check to see if it's just up or not. + * + * @return {boolean} `true` if the Key was just released, otherwise `false`. + */ +var JustUp = function (key) +{ + if (key._justUp) + { + key._justUp = false; + + return true; + } + else + { + return false; + } +}; + +module.exports = JustUp; + + +/***/ }), +/* 1254 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} [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`. + */ +var DownDuration = function (key, duration) +{ + if (duration === undefined) { duration = 50; } + + var current = key.plugin.game.loop.time - key.timeDown; + + return (key.isDown && current < duration); +}; + +module.exports = DownDuration; + + +/***/ }), +/* 1255 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} [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`. + */ +var UpDuration = function (key, duration) +{ + if (duration === undefined) { duration = 50; } + + var current = key.plugin.game.loop.time - key.timeUp; + + return (key.isUp && current < duration); +}; + +module.exports = UpDuration; + + +/***/ }), +/* 1256 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Mouse + */ + +/* eslint-disable */ +module.exports = { + + MouseManager: __webpack_require__(391) + +}; +/* eslint-enable */ + + +/***/ }), +/* 1257 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Touch + */ + +/* eslint-disable */ +module.exports = { + + TouchManager: __webpack_require__(393) + +}; +/* eslint-enable */ + + +/***/ }), +/* 1258 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(23); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Loader + */ + +var Loader = { + + Events: __webpack_require__(87), + + FileTypes: __webpack_require__(1259), + + File: __webpack_require__(24), + FileTypesManager: __webpack_require__(8), + GetURL: __webpack_require__(143), + LoaderPlugin: __webpack_require__(1283), + MergeXHRSettings: __webpack_require__(227), + MultiFile: __webpack_require__(67), + XHRLoader: __webpack_require__(478), + XHRSettings: __webpack_require__(144) + +}; + +// Merge in the consts +Loader = Extend(false, Loader, CONST); + +module.exports = Loader; + + +/***/ }), +/* 1259 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Loader.FileTypes + */ + +module.exports = { + + AnimationJSONFile: __webpack_require__(1260), + AtlasJSONFile: __webpack_require__(1261), + AtlasXMLFile: __webpack_require__(1262), + AudioFile: __webpack_require__(479), + AudioSpriteFile: __webpack_require__(1263), + BinaryFile: __webpack_require__(1264), + BitmapFontFile: __webpack_require__(1265), + CSSFile: __webpack_require__(1266), + GLSLFile: __webpack_require__(1267), + HTML5AudioFile: __webpack_require__(480), + HTMLFile: __webpack_require__(1268), + HTMLTextureFile: __webpack_require__(1269), + ImageFile: __webpack_require__(77), + JSONFile: __webpack_require__(66), + MultiAtlasFile: __webpack_require__(1270), + MultiScriptFile: __webpack_require__(1271), + PackFile: __webpack_require__(1272), + PluginFile: __webpack_require__(1273), + SceneFile: __webpack_require__(1274), + ScenePluginFile: __webpack_require__(1275), + ScriptFile: __webpack_require__(481), + SpriteSheetFile: __webpack_require__(1276), + SVGFile: __webpack_require__(1277), + TextFile: __webpack_require__(482), + TilemapCSVFile: __webpack_require__(1278), + TilemapImpactFile: __webpack_require__(1279), + TilemapJSONFile: __webpack_require__(1280), + UnityAtlasFile: __webpack_require__(1281), + VideoFile: __webpack_require__(1282), + XMLFile: __webpack_require__(228) + +}; + + +/***/ }), +/* 1260 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var JSONFile = __webpack_require__(66); +var LoaderEvents = __webpack_require__(87); + +/** + * @classdesc + * A single Animation JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#animation method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#animation. + * + * @class AnimationJSONFile + * @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.JSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. + */ +var AnimationJSONFile = new Class({ + + Extends: JSONFile, + + initialize: + + // 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 + + function AnimationJSONFile (loader, key, url, xhrSettings, dataKey) + { + JSONFile.call(this, loader, key, url, xhrSettings, dataKey); + + this.type = 'animationJSON'; + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.AnimationJSONFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + // We need to hook into this event: + this.loader.once(LoaderEvents.POST_PROCESS, this.onLoadComplete, this); + + // But the rest is the same as a normal JSON file + JSONFile.prototype.onProcess.call(this); + }, + + /** + * Called at the end of the load process, after the Loader has finished all files in its queue. + * + * @method Phaser.Loader.FileTypes.AnimationJSONFile#onLoadComplete + * @since 3.7.0 + */ + onLoadComplete: function () + { + this.loader.systems.anims.fromJSON(this.data); + + this.pendingDestroy(); + } + +}); + +/** + * Adds an Animation JSON Data file, or array of Animation JSON 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.animation('baddieAnims', 'files/BaddieAnims.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 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.animation({ + * key: 'baddieAnims', + * url: 'files/BaddieAnims.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. + * + * Once the file has finished loading it will automatically be passed to the global Animation Managers `fromJSON` method. + * This will parse all of the JSON data and create animation data from it. This process happens at the very end + * of the Loader, once every other file in the load queue has finished. The reason for this is to allow you to load + * both animation data and the images it relies upon in the same load call. + * + * Once the animation data has been parsed you will be able to play animations using that data. + * Please see the Animation Manager `fromJSON` method for more details about the format and playback. + * + * You can also access the raw animation data from its Cache using its key: + * + * ```javascript + * this.load.animation('baddieAnims', 'files/BaddieAnims.json'); + * // and later in your game ... + * var data = this.cache.json.get('baddieAnims'); + * ``` + * + * 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 if you only wanted to create animations from the `boss` data, 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 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#animation + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.JSONFileConfig|Phaser.Types.Loader.FileTypes.JSONFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {string} [dataKey] - When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('animation', function (key, url, dataKey, xhrSettings) +{ + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + this.addFile(new AnimationJSONFile(this, key[i])); + } + } + else + { + this.addFile(new AnimationJSONFile(this, key, url, xhrSettings, dataKey)); + } + + return this; +}); + +module.exports = AnimationJSONFile; + + +/***/ }), +/* 1261 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var ImageFile = __webpack_require__(77); +var IsPlainObject = __webpack_require__(7); +var JSONFile = __webpack_require__(66); +var MultiFile = __webpack_require__(67); + +/** + * @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. + * + * https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm + * + * @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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @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. + */ +var AtlasJSONFile = new Class({ + + Extends: MultiFile, + + initialize: + + function AtlasJSONFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new JSONFile(loader, { + key: key, + url: GetFastValue(config, 'atlasURL'), + extension: GetFastValue(config, 'atlasExtension', 'json'), + xhrSettings: GetFastValue(config, 'atlasXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'atlasjson', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'atlasjson', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.AtlasJSONFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var json = this.files[1]; + var normalMap = (this.files[2]) ? this.files[2].data : null; + + this.loader.textureManager.addAtlas(image.key, image.data, json.data, normalMap); + + json.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * 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, Shoebox and Adobe Flash / Animate. + * 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.LoaderPlugin#addFileEvent + * @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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('atlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new AtlasJSONFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new AtlasJSONFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = AtlasJSONFile; + + +/***/ }), +/* 1262 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var ImageFile = __webpack_require__(77); +var IsPlainObject = __webpack_require__(7); +var MultiFile = __webpack_require__(67); +var XMLFile = __webpack_require__(228); + +/** + * @classdesc + * A single XML based Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#atlasXML method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#atlasXML. + * + * @class AtlasXMLFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.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 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 xml file. Used in replacement of the Loaders default XHR Settings. + */ +var AtlasXMLFile = new Class({ + + Extends: MultiFile, + + initialize: + + function AtlasXMLFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new XMLFile(loader, { + key: key, + url: GetFastValue(config, 'atlasURL'), + extension: GetFastValue(config, 'atlasExtension', 'xml'), + xhrSettings: GetFastValue(config, 'atlasXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new XMLFile(loader, key, atlasURL, atlasXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'atlasxml', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'atlasxml', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.AtlasXMLFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var xml = this.files[1]; + var normalMap = (this.files[2]) ? this.files[2].data : null; + + this.loader.textureManager.addAtlasXML(image.key, image.data, xml.data, normalMap); + + xml.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * Adds an XML 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.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 atlas data to be provided in an XML file format. + * These files are created by software such as Shoebox and Adobe Flash / Animate. + * + * 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.atlasXML({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * atlasURL: 'images/MainMenu.xml' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig` for more details. + * + * 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.xml'); + * // 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.atlasXML('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.xml'); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.atlasXML({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * normalMap: 'images/MainMenu-n.png', + * atlasURL: 'images/MainMenu.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 Atlas XML 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#atlasXML + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.7.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.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 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 xml file. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('atlasXML', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new AtlasXMLFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new AtlasXMLFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = AtlasXMLFile; + + +/***/ }), +/* 1263 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AudioFile = __webpack_require__(479); +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); +var JSONFile = __webpack_require__(66); +var MultiFile = __webpack_require__(67); + +/** + * @classdesc + * An Audio Sprite File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#audioSprite method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audioSprite. + * + * @class AudioSpriteFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig)} key - The key to use for this file, or a file configuration object. + * @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. + */ +var AudioSpriteFile = new Class({ + + Extends: MultiFile, + + initialize: + + function AudioSpriteFile (loader, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + jsonURL = GetFastValue(config, 'jsonURL'); + audioURL = GetFastValue(config, 'audioURL'); + audioConfig = GetFastValue(config, 'audioConfig'); + audioXhrSettings = GetFastValue(config, 'audioXhrSettings'); + jsonXhrSettings = GetFastValue(config, 'jsonXhrSettings'); + } + + var data; + + // No url? then we're going to do a json load and parse it from that + if (!audioURL) + { + data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); + + MultiFile.call(this, loader, 'audiosprite', key, [ data ]); + + this.config.resourceLoad = true; + this.config.audioConfig = audioConfig; + this.config.audioXhrSettings = audioXhrSettings; + } + else + { + var audio = AudioFile.create(loader, key, audioURL, audioConfig, audioXhrSettings); + + if (audio) + { + data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); + + MultiFile.call(this, loader, 'audiosprite', key, [ audio, data ]); + + this.config.resourceLoad = false; + } + } + }, + + /** + * Called by each File when it finishes loading. + * + * @method Phaser.Loader.FileTypes.AudioSpriteFile#onFileComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has completed processing. + */ + onFileComplete: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.pending--; + + if (this.config.resourceLoad && file.type === 'json' && file.data.hasOwnProperty('resources')) + { + // Inspect the data for the files to now load + var urls = file.data.resources; + + var audioConfig = GetFastValue(this.config, 'audioConfig'); + var audioXhrSettings = GetFastValue(this.config, 'audioXhrSettings'); + + var audio = AudioFile.create(this.loader, file.key, urls, audioConfig, audioXhrSettings); + + if (audio) + { + this.addToMultiFile(audio); + + this.loader.addFile(audio); + } + } + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.AudioSpriteFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var fileA = this.files[0]; + var fileB = this.files[1]; + + fileA.addToCache(); + fileB.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * 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 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. + * + * 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.LoaderPlugin#addFileEvent + * @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 {Phaser.Loader.LoaderPlugin} The Loader. + */ +FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) +{ + var game = this.systems.game; + var gameAudioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + if ((gameAudioConfig && gameAudioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + // Sounds are disabled, so skip loading audio + return this; + } + + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new AudioSpriteFile(this, key[i]); + + if (multifile.files) + { + this.addFile(multifile.files); + } + } + } + else + { + multifile = new AudioSpriteFile(this, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings); + + if (multifile.files) + { + this.addFile(multifile.files); + } + } + + return this; +}); + + +/***/ }), +/* 1264 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Binary File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#binary method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#binary. + * + * @class BinaryFile + * @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.BinaryFileConfig)} 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 `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + */ +var BinaryFile = new Class({ + + Extends: File, + + initialize: + + function BinaryFile (loader, key, url, xhrSettings, dataType) + { + var extension = 'bin'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + dataType = GetFastValue(config, 'dataType', dataType); + } + + var fileConfig = { + type: 'binary', + cache: loader.cacheManager.binary, + extension: extension, + responseType: 'arraybuffer', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { dataType: dataType } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.BinaryFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var ctor = this.config.dataType; + + this.data = (ctor) ? new ctor(this.xhrLoader.response) : this.xhrLoader.response; + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Binary file, or array of Binary 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.binary('doom', 'files/Doom.wad'); + * } + * ``` + * + * 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 Binary Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Binary 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 Binary Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.binary({ + * key: 'doom', + * url: 'files/Doom.wad', + * dataType: Uint8Array + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.BinaryFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.binary('doom', 'files/Doom.wad'); + * // and later in your game ... + * var data = this.cache.binary.get('doom'); + * ``` + * + * 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 `Data` the final key will be `LEVEL1.Data` and + * this is what you would use to retrieve the text from the Binary 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 "doom" + * and no URL is given then the Loader will set the URL to be "doom.bin". It will always add `.bin` 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 Binary 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#binary + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.BinaryFileConfig|Phaser.Types.Loader.FileTypes.BinaryFileConfig[])} 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 `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('binary', function (key, url, dataType, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new BinaryFile(this, key[i])); + } + } + else + { + this.addFile(new BinaryFile(this, key, url, xhrSettings, dataType)); + } + + return this; +}); + +module.exports = BinaryFile; + + +/***/ }), +/* 1265 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var ImageFile = __webpack_require__(77); +var IsPlainObject = __webpack_require__(7); +var MultiFile = __webpack_require__(67); +var ParseXMLBitmapFont = __webpack_require__(200); +var XMLFile = __webpack_require__(228); + +/** + * @classdesc + * A single Bitmap Font based File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#bitmapFont method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#bitmapFont. + * + * @class BitmapFontFile + * @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.BitmapFontFileConfig)} 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 font image file from. If undefined or `null` it will be set to `.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 `.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. + */ +var BitmapFontFile = new Class({ + + Extends: MultiFile, + + initialize: + + function BitmapFontFile (loader, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new XMLFile(loader, { + key: key, + url: GetFastValue(config, 'fontDataURL'), + extension: GetFastValue(config, 'fontDataExtension', 'xml'), + xhrSettings: GetFastValue(config, 'fontDataXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new XMLFile(loader, key, fontDataURL, fontDataXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'bitmapfont', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'bitmapfont', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.BitmapFontFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var xml = this.files[1]; + + image.addToCache(); + xml.addToCache(); + + this.loader.cacheManager.bitmapFont.add(image.key, { data: ParseXMLBitmapFont(xml.data), texture: image.key, frame: null }); + + this.complete = true; + } + } + +}); + +/** + * 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 atlas has finished loading you can use 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.LoaderPlugin#addFileEvent + * @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 `.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 `.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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('bitmapFont', function (key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new BitmapFontFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new BitmapFontFile(this, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = BitmapFontFile; + + +/***/ }), +/* 1266 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single CSS File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#css method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#css. + * + * @class CSSFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.17.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var CSSFile = new Class({ + + Extends: File, + + initialize: + + function CSSFile (loader, key, url, xhrSettings) + { + var extension = 'css'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'script', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.CSSFile#onProcess + * @since 3.17.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('style'); + this.data.defer = false; + this.data.innerHTML = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + this.onProcessComplete(); + } + +}); + +/** + * Adds a CSS file, or array of CSS 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.css('headers', 'styles/headers.css'); + * } + * ``` + * + * 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.css({ + * key: 'headers', + * url: 'styles/headers.css' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.CSSFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a style DOM element + * via `document.createElement('style')`. It will have its `defer` property set to false and then the + * resulting element will be appended to `document.head`. The CSS styles are then applied to the current document. + * + * 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.css". It will always add `.css` 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 CSS 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#css + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.17.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig|Phaser.Types.Loader.FileTypes.CSSFileConfig[])} 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 `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('css', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new CSSFile(this, key[i])); + } + } + else + { + this.addFile(new CSSFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = CSSFile; + + +/***/ }), +/* 1267 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); +var Shader = __webpack_require__(377); + +/** + * @classdesc + * A single GLSL File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#glsl method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#glsl. + * + * @class GLSLFile + * @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.GLSLFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var GLSLFile = new Class({ + + Extends: File, + + initialize: + + function GLSLFile (loader, key, url, shaderType, xhrSettings) + { + var extension = 'glsl'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + shaderType = GetFastValue(config, 'shaderType', 'fragment'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + else if (shaderType === undefined) + { + shaderType = 'fragment'; + } + + var fileConfig = { + type: 'glsl', + cache: loader.cacheManager.shader, + extension: extension, + responseType: 'text', + key: key, + url: url, + config: { + shaderType: shaderType + }, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.GLSLFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.GLSLFile#addToCache + * @since 3.17.0 + */ + addToCache: function () + { + var data = this.data.split('\n'); + + // Check to see if this is a shader bundle, or raw glsl file. + var block = this.extractBlock(data, 0); + + if (block) + { + while (block) + { + var key = this.getShaderName(block.header); + var shaderType = this.getShaderType(block.header); + var uniforms = this.getShaderUniforms(block.header); + var shaderSrc = block.shader; + + if (this.cache.has(key)) + { + var shader = this.cache.get(key); + + if (shaderType === 'fragment') + { + shader.fragmentSrc = shaderSrc; + } + else + { + shader.vertexSrc = shaderSrc; + } + + if (!shader.uniforms) + { + shader.uniforms = uniforms; + } + } + else if (shaderType === 'fragment') + { + this.cache.add(key, new Shader(key, shaderSrc, '', uniforms)); + } + else + { + this.cache.add(key, new Shader(key, '', shaderSrc, uniforms)); + } + + block = this.extractBlock(data, block.offset); + } + } + else if (this.config.shaderType === 'fragment') + { + // Single shader + this.cache.add(this.key, new Shader(this.key, this.data)); + } + else + { + this.cache.add(this.key, new Shader(this.key, '', this.data)); + } + + this.pendingDestroy(); + }, + + /** + * Returns the name of the shader from the header block. + * + * @method Phaser.Loader.FileTypes.GLSLFile#getShaderName + * @since 3.17.0 + * + * @param {string[]} headerSource - The header data. + * + * @return {string} The shader name. + */ + getShaderName: function (headerSource) + { + for (var i = 0; i < headerSource.length; i++) + { + var line = headerSource[i].trim(); + + if (line.substring(0, 5) === 'name:') + { + return line.substring(5).trim(); + } + } + + return this.key; + }, + + /** + * Returns the type of the shader from the header block. + * + * @method Phaser.Loader.FileTypes.GLSLFile#getShaderType + * @since 3.17.0 + * + * @param {string[]} headerSource - The header data. + * + * @return {string} The shader type. Either 'fragment' or 'vertex'. + */ + getShaderType: function (headerSource) + { + for (var i = 0; i < headerSource.length; i++) + { + var line = headerSource[i].trim(); + + if (line.substring(0, 5) === 'type:') + { + return line.substring(5).trim(); + } + } + + return this.config.shaderType; + }, + + /** + * Returns the shader uniforms from the header block. + * + * @method Phaser.Loader.FileTypes.GLSLFile#getShaderUniforms + * @since 3.17.0 + * + * @param {string[]} headerSource - The header data. + * + * @return {any} The shader uniforms object. + */ + getShaderUniforms: function (headerSource) + { + var uniforms = {}; + + for (var i = 0; i < headerSource.length; i++) + { + var line = headerSource[i].trim(); + + if (line.substring(0, 8) === 'uniform.') + { + var pos = line.indexOf(':'); + + if (pos) + { + var key = line.substring(8, pos); + + try + { + uniforms[key] = JSON.parse(line.substring(pos + 1)); + } + catch (e) + { + console.warn('Invalid uniform JSON: ' + key); + } + } + } + } + + return uniforms; + }, + + /** + * Processes the shader file and extracts the relevant data. + * + * @method Phaser.Loader.FileTypes.GLSLFile#extractBlock + * @private + * @since 3.17.0 + * + * @param {string[]} data - The array of shader data to process. + * @param {integer} offset - The offset to start processing from. + * + * @return {any} The processed shader block, or null. + */ + extractBlock: function (data, offset) + { + var headerStart = -1; + var headerEnd = -1; + var blockEnd = -1; + var headerOpen = false; + var captureSource = false; + var headerSource = []; + var shaderSource = []; + + for (var i = offset; i < data.length; i++) + { + var line = data[i].trim(); + + if (line === '---') + { + if (headerStart === -1) + { + headerStart = i; + headerOpen = true; + } + else if (headerOpen) + { + headerEnd = i; + headerOpen = false; + captureSource = true; + } + else + { + // We've hit another --- delimiter, break out + captureSource = false; + break; + } + } + else if (headerOpen) + { + headerSource.push(line); + } + else if (captureSource) + { + shaderSource.push(line); + blockEnd = i; + } + } + + if (!headerOpen && headerEnd !== -1) + { + return { header: headerSource, shader: shaderSource.join('\n'), offset: blockEnd }; + } + else + { + return null; + } + } + +}); + +/** + * Adds a GLSL file, or array of GLSL files, to the current load queue. + * In Phaser 3 GLSL files are just plain Text files at the current moment in time. + * + * 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.glsl('plasma', 'shaders/Plasma.glsl'); + * } + * ``` + * + * 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 Shader Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Shader 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 Shader Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.glsl({ + * key: 'plasma', + * shaderType: 'fragment', + * url: 'shaders/Plasma.glsl' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.GLSLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.glsl('plasma', 'shaders/Plasma.glsl'); + * // and later in your game ... + * var data = this.cache.shader.get('plasma'); + * ``` + * + * 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 `FX.` and the key was `Plasma` the final key will be `FX.Plasma` and + * this is what you would use to retrieve the text from the Shader 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 "plasma" + * and no URL is given then the Loader will set the URL to be "plasma.glsl". It will always add `.glsl` 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 GLSL 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#glsl + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.GLSLFileConfig|Phaser.Types.Loader.FileTypes.GLSLFileConfig[])} 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 `.glsl`, i.e. if `key` was "alien" then the URL will be "alien.glsl". + * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('glsl', function (key, url, shaderType, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new GLSLFile(this, key[i])); + } + } + else + { + this.addFile(new GLSLFile(this, key, url, shaderType, xhrSettings)); + } + + return this; +}); + +module.exports = GLSLFile; + + +/***/ }), +/* 1268 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single HTML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#html method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#html. + * + * @class HTMLFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.12.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.HTMLFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var HTMLFile = new Class({ + + Extends: File, + + initialize: + + function HTMLFile (loader, key, url, xhrSettings) + { + var extension = 'html'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'text', + cache: loader.cacheManager.html, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.HTMLFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + } + +}); + +/** + * Adds an HTML file, or array of HTML 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.html('story', 'files/LoginForm.html'); + * } + * ``` + * + * 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 HTML Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the HTML 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 HTML Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.html({ + * key: 'login', + * url: 'files/LoginForm.html' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.HTMLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.html('login', 'files/LoginForm.html'); + * // and later in your game ... + * var data = this.cache.html.get('login'); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the html from the HTML 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 "story" + * and no URL is given then the Loader will set the URL to be "story.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. + * + * Note: The ability to load this type of file will only be available if the HTML 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#html + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.12.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.HTMLFileConfig|Phaser.Types.Loader.FileTypes.HTMLFileConfig[])} 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 `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('html', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new HTMLFile(this, key[i])); + } + } + else + { + this.addFile(new HTMLFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = HTMLFile; + + +/***/ }), +/* 1269 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single HTML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#htmlTexture method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#htmlTexture. + * + * @class HTMLTextureFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.12.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {integer} [width] - The width of the texture the HTML will be rendered to. + * @param {integer} [height] - The height of the texture the HTML will be rendered to. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var HTMLTextureFile = new Class({ + + Extends: File, + + initialize: + + function HTMLTextureFile (loader, key, url, width, height, xhrSettings) + { + if (width === undefined) { width = 512; } + if (height === undefined) { height = 512; } + + var extension = 'html'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + width = GetFastValue(config, 'width', width); + height = GetFastValue(config, 'height', height); + } + + var fileConfig = { + type: 'html', + cache: loader.textureManager, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + width: width, + height: height + } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.HTMLTextureFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var w = this.config.width; + var h = this.config.height; + + var data = []; + + data.push(''); + data.push(''); + data.push(''); + data.push(this.xhrLoader.responseText); + data.push(''); + data.push(''); + data.push(''); + + var svg = [ data.join('\n') ]; + var _this = this; + + try + { + var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' }); + } + catch (e) + { + _this.state = CONST.FILE_ERRORED; + + _this.onProcessComplete(); + + return; + } + + this.data = new Image(); + + this.data.crossOrigin = this.crossOrigin; + + this.data.onload = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessError(); + }; + + File.createObjectURL(this.data, blob, 'image/svg+xml'); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.HTMLTextureFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture = this.cache.addImage(this.key, this.data); + + this.pendingDestroy(texture); + } + +}); + +/** + * 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.LoaderPlugin#addFileEvent + * @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 `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param {integer} [width=512] - The width of the texture the HTML will be rendered to. + * @param {integer} [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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('htmlTexture', function (key, url, width, height, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new HTMLTextureFile(this, key[i])); + } + } + else + { + this.addFile(new HTMLTextureFile(this, key, url, width, height, xhrSettings)); + } + + return this; +}); + +module.exports = HTMLTextureFile; + + +/***/ }), +/* 1270 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var ImageFile = __webpack_require__(77); +var IsPlainObject = __webpack_require__(7); +var JSONFile = __webpack_require__(66); +var MultiFile = __webpack_require__(67); + +/** + * @classdesc + * A single Multi Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#multiatlas method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#multiatlas. + * + * @class MultiAtlasFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig)} key - The key of the file. Must be unique within both the Loader and the Texture Manager. Or a config object. + * @param {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from. + * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data. + * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. + * @param {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file. + * @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files. + */ +var MultiAtlasFile = new Class({ + + Extends: MultiFile, + + initialize: + + function MultiAtlasFile (loader, key, atlasURL, path, baseURL, atlasXhrSettings, textureXhrSettings) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + if (GetFastValue(config, 'url', false)) + { + atlasURL = GetFastValue(config, 'url'); + } + else + { + atlasURL = GetFastValue(config, 'atlasURL'); + } + + atlasXhrSettings = GetFastValue(config, 'xhrSettings'); + path = GetFastValue(config, 'path'); + baseURL = GetFastValue(config, 'baseURL'); + textureXhrSettings = GetFastValue(config, 'textureXhrSettings'); + } + + var data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); + + MultiFile.call(this, loader, 'multiatlas', key, [ data ]); + + this.config.path = path; + this.config.baseURL = baseURL; + this.config.textureXhrSettings = textureXhrSettings; + }, + + /** + * Called by each File when it finishes loading. + * + * @method Phaser.Loader.FileTypes.MultiAtlasFile#onFileComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has completed processing. + */ + onFileComplete: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.pending--; + + if (file.type === 'json' && file.data.hasOwnProperty('textures')) + { + // Inspect the data for the files to now load + var textures = file.data.textures; + + var config = this.config; + var loader = this.loader; + + var currentBaseURL = loader.baseURL; + var currentPath = loader.path; + var currentPrefix = loader.prefix; + + var baseURL = GetFastValue(config, 'baseURL', this.baseURL); + var path = GetFastValue(config, 'path', this.path); + var prefix = GetFastValue(config, 'prefix', this.prefix); + var textureXhrSettings = GetFastValue(config, 'textureXhrSettings'); + + loader.setBaseURL(baseURL); + loader.setPath(path); + loader.setPrefix(prefix); + + for (var i = 0; i < textures.length; i++) + { + // "image": "texture-packer-multi-atlas-0.png", + var textureURL = textures[i].image; + + var key = 'MA' + this.multiKeyIndex + '_' + textureURL; + + var image = new ImageFile(loader, key, textureURL, textureXhrSettings); + + this.addToMultiFile(image); + + loader.addFile(image); + + // "normalMap": "texture-packer-multi-atlas-0_n.png", + if (textures[i].normalMap) + { + var normalMap = new ImageFile(loader, key, textures[i].normalMap, textureXhrSettings); + + normalMap.type = 'normalMap'; + + image.setLink(normalMap); + + this.addToMultiFile(normalMap); + + loader.addFile(normalMap); + } + } + + // Reset the loader settings + loader.setBaseURL(currentBaseURL); + loader.setPath(currentPath); + loader.setPrefix(currentPrefix); + } + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.MultiAtlasFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var fileJSON = this.files[0]; + + var data = []; + var images = []; + var normalMaps = []; + + for (var i = 1; i < this.files.length; i++) + { + var file = this.files[i]; + + if (file.type === 'normalMap') + { + continue; + } + + var pos = file.key.indexOf('_'); + var key = file.key.substr(pos + 1); + + var image = file.data; + + // Now we need to find out which json entry this mapped to + for (var t = 0; t < fileJSON.data.textures.length; t++) + { + var item = fileJSON.data.textures[t]; + + if (item.image === key) + { + images.push(image); + + data.push(item); + + if (file.linkFile) + { + normalMaps.push(file.linkFile.data); + } + + break; + } + } + } + + if (normalMaps.length === 0) + { + normalMaps = undefined; + } + + this.loader.textureManager.addAtlasJSONArray(this.key, images, data, normalMaps); + + this.complete = true; + + for (i = 0; i < this.files.length; i++) + { + this.files[i].pendingDestroy(); + } + } + } + +}); + +/** + * Adds a Multi Texture Atlas, or array of multi 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.multiatlas('level1', 'images/Level1.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 as exported from the application Texture Packer, + * version 4.6.3 or above, where you have made sure to use the Phaser 3 Export option. + * + * The way it works internally is that you provide a URL to the JSON file. Phaser then loads this JSON, parses it and + * extracts which texture files it also needs to load to complete the process. If the JSON also defines normal maps, + * Phaser will load those as well. + * + * 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.multiatlas({ + * key: 'level1', + * atlasURL: 'images/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig` 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.multiatlas('level1', 'images/Level1.json'); + * // and later in your game ... + * this.add.image(x, y, 'level1', '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. + * + * Note: The ability to load this type of file will only be available if the Multi Atlas 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#multiatlas + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.7.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data. + * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. + * @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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('multiatlas', function (key, atlasURL, path, baseURL, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new MultiAtlasFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new MultiAtlasFile(this, key, atlasURL, path, baseURL, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = MultiAtlasFile; + + +/***/ }), +/* 1271 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); +var MultiFile = __webpack_require__(67); +var ScriptFile = __webpack_require__(481); + +/** + * @classdesc + * A Multi Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#scripts method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scripts. + * + * @class MultiScriptFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.17.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {string[]} [url] - An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object for the script files. Used in replacement of the Loaders default XHR Settings. + */ +var MultiScriptFile = new Class({ + + Extends: MultiFile, + + initialize: + + function MultiScriptFile (loader, key, url, xhrSettings) + { + var extension = 'js'; + var files = []; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + if (!Array.isArray(url)) + { + url = [ url ]; + } + + for (var i = 0; i < url.length; i++) + { + var scriptFile = new ScriptFile(loader, { + key: key + '_' + i.toString(), + url: url[i], + extension: extension, + xhrSettings: xhrSettings + }); + + // Override the default onProcess function + scriptFile.onProcess = function () + { + this.onProcessComplete(); + }; + + files.push(scriptFile); + } + + MultiFile.call(this, loader, 'scripts', key, files); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.MultiScriptFile#addToCache + * @since 3.17.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + for (var i = 0; i < this.files.length; i++) + { + var file = this.files[i]; + + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = file.xhrLoader.responseText; + + document.head.appendChild(file.data); + } + + this.complete = true; + } + } + +}); + +/** + * Adds an array of Script files to the current load queue. + * + * The difference between this and the `ScriptFile` file type is that you give an array of scripts to this method, + * and the scripts are then processed _exactly_ in that order. This allows you to load a bunch of scripts that + * may have dependencies on each other without worrying about the async nature of traditional script loading. + * + * 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.scripts('PostProcess', [ + * 'libs/shaders/CopyShader.js', + * 'libs/postprocessing/EffectComposer.js', + * 'libs/postprocessing/RenderPass.js', + * 'libs/postprocessing/MaskPass.js', + * 'libs/postprocessing/ShaderPass.js', + * 'libs/postprocessing/AfterimagePass.js' + * ]); + * } + * ``` + * + * In the code above the script files will all be loaded in parallel but only processed (i.e. invoked) in the exact + * order given in the array. + * + * The files are **not** loaded right away. They are 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 files are queued + * it means you cannot use the files immediately after calling this method, but must wait for the files 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.scripts({ + * key: 'PostProcess', + * url: [ + * 'libs/shaders/CopyShader.js', + * 'libs/postprocessing/EffectComposer.js', + * 'libs/postprocessing/RenderPass.js', + * 'libs/postprocessing/MaskPass.js', + * 'libs/postprocessing/ShaderPass.js', + * 'libs/postprocessing/AfterimagePass.js' + * ] + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.MultiScriptFileConfig` for more details. + * + * Once all the files have finished loading they will automatically be converted into a script element + * via `document.createElement('script')`. They will have their language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. This is done in the exact order the files are specified in the url array. + * + * The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them. + * + * Note: The ability to load this type of file will only be available if the MultiScript 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#scripts + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.17.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {string[]} [url] - An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + * @param {string} [extension='js'] - The default file extension to use if no url is provided. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for these files. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('scripts', function (key, url, xhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new MultiScriptFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new MultiScriptFile(this, key, url, xhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = MultiScriptFile; + + +/***/ }), +/* 1272 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var FileTypesManager = __webpack_require__(8); +var JSONFile = __webpack_require__(66); + +/** + * @classdesc + * A single JSON Pack File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#pack method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#pack. + * + * @class PackFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.PackFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. + */ +var PackFile = new Class({ + + Extends: JSONFile, + + initialize: + + // 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 + + function PackFile (loader, key, url, xhrSettings, dataKey) + { + JSONFile.call(this, loader, key, url, xhrSettings, dataKey); + + this.type = 'packfile'; + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.PackFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + if (this.state !== CONST.FILE_POPULATED) + { + this.state = CONST.FILE_PROCESSING; + + this.data = JSON.parse(this.xhrLoader.responseText); + } + + // Let's pass the pack file data over to the Loader ... + this.loader.addPack(this.data, this.config); + + this.onProcessComplete(); + } + +}); + +/** + * 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. + * + * 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.LoaderPlugin#addFileEvent + * @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 `.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 {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('pack', function (key, url, packKey, xhrSettings) +{ + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + this.addFile(new PackFile(this, key[i])); + } + } + else + { + this.addFile(new PackFile(this, key, url, xhrSettings, packKey)); + } + + return this; +}); + +module.exports = PackFile; + + +/***/ }), +/* 1273 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Plugin Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#plugin method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#plugin. + * + * @class PluginFile + * @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.PluginFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {boolean} [start=false] - Automatically start the plugin after loading? + * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var PluginFile = new Class({ + + Extends: File, + + initialize: + + function PluginFile (loader, key, url, start, mapping, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + start = GetFastValue(config, 'start'); + mapping = GetFastValue(config, 'mapping'); + } + + var fileConfig = { + type: 'plugin', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + start: start, + mapping: mapping + } + }; + + File.call(this, loader, fileConfig); + + // If the url variable refers to a class, add the plugin directly + if (typeof url === 'function') + { + this.data = url; + + this.state = CONST.FILE_POPULATED; + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.PluginFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + var pluginManager = this.loader.systems.plugins; + var config = this.config; + + var start = GetFastValue(config, 'start', false); + var mapping = GetFastValue(config, 'mapping', null); + + if (this.state === CONST.FILE_POPULATED) + { + pluginManager.install(this.key, this.data, start, mapping); + } + else + { + // Plugin added via a js file + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('script'); + this.data.language = 'javascript'; + this.data.type = 'text/javascript'; + this.data.defer = false; + this.data.text = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + var plugin = pluginManager.install(this.key, window[this.key], start, mapping); + + if (start || mapping) + { + // Install into the current Scene Systems and Scene + this.loader.systems[mapping] = plugin; + this.loader.scene[mapping] = plugin; + } + } + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Plugin Script file, or array of plugin 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.plugin('modplayer', 'plugins/ModPlayer.js'); + * } + * ``` + * + * 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.plugin({ + * key: 'modplayer', + * url: 'plugins/ModPlayer.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.PluginFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. It will then be passed to the Phaser PluginCache.register method. + * + * 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.js". It will always add `.js` 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 Plugin 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#plugin + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.PluginFileConfig|Phaser.Types.Loader.FileTypes.PluginFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {(string|function)} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, a plugin function. + * @param {boolean} [start] - Automatically start the plugin after loading? + * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('plugin', function (key, url, start, mapping, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new PluginFile(this, key[i])); + } + } + else + { + this.addFile(new PluginFile(this, key, url, start, mapping, xhrSettings)); + } + + return this; +}); + +module.exports = PluginFile; + + +/***/ }), +/* 1274 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * An external Scene JavaScript File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#sceneFile method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#sceneFile. + * + * @class SceneFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.16.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.SceneFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var SceneFile = new Class({ + + Extends: File, + + initialize: + + function SceneFile (loader, key, url, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'text', + cache: loader.cacheManager.text, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.SceneFile#onProcess + * @since 3.16.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.SceneFile#addToCache + * @since 3.16.0 + */ + addToCache: function () + { + var code = this.data.concat('(function(){\n' + 'return new ' + this.key + '();\n' + '}).call(this);'); + + // Stops rollup from freaking out during build + var eval2 = eval; + + this.loader.sceneManager.add(this.key, eval2(code)); + + this.complete = true; + } + +}); + +/** + * Adds an external Scene file, or array of Scene 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.sceneFile('Level1', 'src/Level1.js'); + * } + * ``` + * + * 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 Scene Manager upon a successful load. + * + * For a Scene File it's vitally important that the key matches the class name in the JavaScript file. + * + * For example here is the source file: + * + * ```javascript + * class ExternalScene extends Phaser.Scene { + * + * constructor () + * { + * super('myScene'); + * } + * + * } + * ``` + * + * Because the class is called `ExternalScene` that is the exact same key you must use when loading it: + * + * ```javascript + * function preload () + * { + * this.load.sceneFile('ExternalScene', 'src/yourScene.js'); + * } + * ``` + * + * The key that is used within the Scene Manager can either be set to the same, or you can override it in the Scene + * constructor, as we've done in the example above, where the Scene key was changed to `myScene`. + * + * The key should be unique both in terms of files being loaded and Scenes already present in the Scene 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 Scene Manager first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.sceneFile({ + * key: 'Level1', + * url: 'src/Level1.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SceneFileConfig` for more details. + * + * Once the file has finished loading it will be added to the Scene Manager. + * + * ```javascript + * this.load.sceneFile('Level1', 'src/Level1.js'); + * // and later in your game ... + * this.scene.start('Level1'); + * ``` + * + * 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 `WORLD1.` and the key was `Story` the final key will be `WORLD1.Story` and + * this is what you would use to retrieve the text from the Scene 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 "story" + * and no URL is given then the Loader will set the URL to be "story.js". It will always add `.js` 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 Scene 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#sceneFile + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.16.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.SceneFileConfig|Phaser.Types.Loader.FileTypes.SceneFileConfig[])} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('sceneFile', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new SceneFile(this, key[i])); + } + } + else + { + this.addFile(new SceneFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = SceneFile; + + +/***/ }), +/* 1275 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Scene Plugin Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#scenePlugin method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scenePlugin. + * + * @class ScenePluginFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.8.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {string} [systemKey] - If this plugin is to be added to Scene.Systems, this is the property key for it. + * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var ScenePluginFile = new Class({ + + Extends: File, + + initialize: + + function ScenePluginFile (loader, key, url, systemKey, sceneKey, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + systemKey = GetFastValue(config, 'systemKey'); + sceneKey = GetFastValue(config, 'sceneKey'); + } + + var fileConfig = { + type: 'scenePlugin', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + systemKey: systemKey, + sceneKey: sceneKey + } + }; + + File.call(this, loader, fileConfig); + + // If the url variable refers to a class, add the plugin directly + if (typeof url === 'function') + { + this.data = url; + + this.state = CONST.FILE_POPULATED; + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.ScenePluginFile#onProcess + * @since 3.8.0 + */ + onProcess: function () + { + var pluginManager = this.loader.systems.plugins; + var config = this.config; + + var key = this.key; + var systemKey = GetFastValue(config, 'systemKey', key); + var sceneKey = GetFastValue(config, 'sceneKey', key); + + if (this.state === CONST.FILE_POPULATED) + { + pluginManager.installScenePlugin(systemKey, this.data, sceneKey, this.loader.scene, true); + } + else + { + // Plugin added via a js file + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('script'); + this.data.language = 'javascript'; + this.data.type = 'text/javascript'; + this.data.defer = false; + this.data.text = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + pluginManager.installScenePlugin(systemKey, window[this.key], sceneKey, this.loader.scene, true); + } + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Scene Plugin Script file, or array of plugin 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.scenePlugin('ModPlayer', 'plugins/ModPlayer.js', 'modPlayer', 'mods'); + * } + * ``` + * + * 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.scenePlugin({ + * key: 'modplayer', + * url: 'plugins/ModPlayer.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ScenePluginFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. It will then be passed to the Phaser PluginCache.register method. + * + * 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.js". It will always add `.js` 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 Script 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#scenePlugin + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.8.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {(string|function)} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, set to a plugin function. + * @param {string} [systemKey] - If this plugin is to be added to Scene.Systems, this is the property key for it. + * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('scenePlugin', function (key, url, systemKey, sceneKey, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new ScenePluginFile(this, key[i])); + } + } + else + { + this.addFile(new ScenePluginFile(this, key, url, systemKey, sceneKey, xhrSettings)); + } + + return this; +}); + +module.exports = ScenePluginFile; + + +/***/ }), +/* 1276 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var ImageFile = __webpack_require__(77); + +/** + * @classdesc + * A single Sprite Sheet Image File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#spritesheet method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spritesheet. + * + * @class SpriteSheetFile + * @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.SpriteSheetFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var SpriteSheetFile = new Class({ + + Extends: ImageFile, + + initialize: + + function SpriteSheetFile (loader, key, url, frameConfig, xhrSettings) + { + ImageFile.call(this, loader, key, url, xhrSettings, frameConfig); + + this.type = 'spritesheet'; + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.SpriteSheetFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture = this.cache.addSpriteSheet(this.key, this.data, this.config); + + this.pendingDestroy(texture); + } + +}); + +/** + * Adds a Sprite Sheet Image, or array of Sprite Sheet Images, to the current load queue. + * + * The term 'Sprite Sheet' in Phaser means a fixed-size sheet. Where every frame in the sheet is the exact same size, + * and you reference those frames using numbers, not frame names. This is not the same thing as a Texture Atlas, where + * the frames are packed in a way where they take up the least amount of space, and are referenced by their names, + * not numbers. Some articles and software use the term 'Sprite Sheet' to mean Texture Atlas, so please be aware of + * what sort of file you're actually trying to load. + * + * 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); + * } + * ``` + * + * 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. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback + * of animated gifs to Canvas elements. + * + * 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.spritesheet({ + * key: 'bot', + * url: 'images/robot.png', + * frameConfig: { + * frameWidth: 32, + * frameHeight: 38, + * startFrame: 0, + * endFrame: 8 + * } + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig` 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); + * // and later in your game ... + * this.add.image(x, y, 'bot', 0); + * ``` + * + * 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 `PLAYER.` and the key was `Running` the final key will be `PLAYER.Running` 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.spritesheet('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ], { frameWidth: 256, frameHeight: 80 }); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.spritesheet({ + * key: 'logo', + * url: 'images/AtariLogo.png', + * normalMap: 'images/AtariLogo-n.png', + * frameConfig: { + * frameWidth: 256, + * frameHeight: 80 + * } + * }); + * ``` + * + * 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 Sprite Sheet 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#spritesheet + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig|Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. At a minimum it should have a `frameWidth` property. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('spritesheet', function (key, url, frameConfig, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new SpriteSheetFile(this, key[i])); + } + } + else + { + this.addFile(new SpriteSheetFile(this, key, url, frameConfig, xhrSettings)); + } + + return this; +}); + +module.exports = SpriteSheetFile; + + +/***/ }), +/* 1277 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single SVG File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#svg method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#svg. + * + * @class SVGFile + * @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.SVGFileConfig)} 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 `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". + * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var SVGFile = new Class({ + + Extends: File, + + initialize: + + function SVGFile (loader, key, url, svgConfig, xhrSettings) + { + var extension = 'svg'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + svgConfig = GetFastValue(config, 'svgConfig', {}); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'svg', + cache: loader.textureManager, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + width: GetFastValue(svgConfig, 'width'), + height: GetFastValue(svgConfig, 'height'), + scale: GetFastValue(svgConfig, 'scale') + } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.SVGFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var text = this.xhrLoader.responseText; + var svg = [ text ]; + var width = this.config.width; + var height = this.config.height; + var scale = this.config.scale; + + resize: if (width && height || scale) + { + var xml = null; + var parser = new DOMParser(); + xml = parser.parseFromString(text, 'text/xml'); + var svgXML = xml.getElementsByTagName('svg')[0]; + + var hasViewBox = svgXML.hasAttribute('viewBox'); + var svgWidth = parseFloat(svgXML.getAttribute('width')); + var svgHeight = parseFloat(svgXML.getAttribute('height')); + + if (!hasViewBox && svgWidth && svgHeight) + { + // If there's no viewBox attribute, set one + svgXML.setAttribute('viewBox', '0 0 ' + svgWidth + ' ' + svgHeight); + } + else if (hasViewBox && !svgWidth && !svgHeight) + { + // Get the w/h from the viewbox + var viewBox = svgXML.getAttribute('viewBox').split(/\s+|,/); + + svgWidth = viewBox[2]; + svgHeight = viewBox[3]; + } + + if (scale) + { + if (svgWidth && svgHeight) + { + width = svgWidth * scale; + height = svgHeight * scale; + } + else + { + break resize; + } + } + + svgXML.setAttribute('width', width.toString() + 'px'); + svgXML.setAttribute('height', height.toString() + 'px'); + + svg = [ (new XMLSerializer()).serializeToString(svgXML) ]; + } + + try + { + var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' }); + } + catch (e) + { + this.onProcessError(); + + return; + } + + this.data = new Image(); + + this.data.crossOrigin = this.crossOrigin; + + var _this = this; + var retry = false; + + this.data.onload = function () + { + if (!retry) + { + File.revokeObjectURL(_this.data); + } + + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + // Safari 8 re-try + if (!retry) + { + retry = true; + + File.revokeObjectURL(_this.data); + + _this.data.src = 'data:image/svg+xml,' + encodeURIComponent(svg.join('')); + } + else + { + _this.onProcessError(); + } + }; + + File.createObjectURL(this.data, blob, 'image/svg+xml'); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.SVGFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture = this.cache.addImage(this.key, this.data); + + this.pendingDestroy(texture); + } + +}); + +/** + * Adds an SVG File, or array of SVG Files, to the current load queue. When the files are loaded they + * will be rendered to bitmap 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.svg('morty', 'images/Morty.svg'); + * } + * ``` + * + * 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.svg({ + * key: 'morty', + * url: 'images/Morty.svg' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SVGFileConfig` 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.svg('morty', 'images/Morty.svg'); + * // and later in your game ... + * this.add.image(x, y, 'morty'); + * ``` + * + * 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. + * + * You can optionally pass an SVG Resize Configuration object when you load an SVG file. By default the SVG will be rendered to a texture + * at the same size defined in the SVG file attributes. However, this isn't always desirable. You may wish to resize the SVG (either down + * or up) to improve texture clarity, or reduce texture memory consumption. You can either specify an exact width and height to resize + * the SVG to: + * + * ```javascript + * function preload () + * { + * this.load.svg('morty', 'images/Morty.svg', { width: 300, height: 600 }); + * } + * ``` + * + * Or when using a configuration object: + * + * ```javascript + * this.load.svg({ + * key: 'morty', + * url: 'images/Morty.svg', + * svgConfig: { + * width: 300, + * height: 600 + * } + * }); + * ``` + * + * Alternatively, you can just provide a scale factor instead: + * + * ```javascript + * function preload () + * { + * this.load.svg('morty', 'images/Morty.svg', { scale: 2.5 }); + * } + * ``` + * + * Or when using a configuration object: + * + * ```javascript + * this.load.svg({ + * key: 'morty', + * url: 'images/Morty.svg', + * svgConfig: { + * scale: 2.5 + * } + * }); + * ``` + * + * If scale, width and height values are all given, the scale has priority and the width and height values are ignored. + * + * Note: The ability to load this type of file will only be available if the SVG 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#svg + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.SVGFileConfig|Phaser.Types.Loader.FileTypes.SVGFileConfig[])} 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 `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". + * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('svg', function (key, url, svgConfig, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new SVGFile(this, key[i])); + } + } + else + { + this.addFile(new SVGFile(this, key, url, svgConfig, xhrSettings)); + } + + return this; +}); + +module.exports = SVGFile; + + + +/***/ }), +/* 1278 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); +var TILEMAP_FORMATS = __webpack_require__(34); + +/** + * @classdesc + * A single Tilemap CSV File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapCSV method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapCSV. + * + * @class TilemapCSVFile + * @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.TilemapCSVFileConfig)} 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 `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TilemapCSVFile = new Class({ + + Extends: File, + + initialize: + + function TilemapCSVFile (loader, key, url, xhrSettings) + { + var extension = 'csv'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'tilemapCSV', + cache: loader.cacheManager.tilemap, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + + this.tilemapFormat = TILEMAP_FORMATS.CSV; + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.TilemapCSVFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.TilemapCSVFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var tiledata = { format: this.tilemapFormat, data: this.data }; + + this.cache.add(this.key, tiledata); + + this.pendingDestroy(tiledata); + } + +}); + +/** + * Adds a CSV Tilemap file, or array of CSV 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.tilemapCSV('level1', 'maps/Level1.csv'); + * } + * ``` + * + * Tilemap CSV data can be created in a text editor, or a 3rd party app that exports as CSV. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapCSV({ + * key: 'level1', + * url: 'maps/Level1.csv' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapCSV('level1', 'maps/Level1.csv'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.csv". It will always add `.csv` 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 Tilemap CSV 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#tilemapCSV + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig|Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig[])} 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 `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('tilemapCSV', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TilemapCSVFile(this, key[i])); + } + } + else + { + this.addFile(new TilemapCSVFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TilemapCSVFile; + + +/***/ }), +/* 1279 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var JSONFile = __webpack_require__(66); +var TILEMAP_FORMATS = __webpack_require__(34); + +/** + * @classdesc + * A single Impact.js Tilemap JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapImpact method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapImpact. + * + * @class TilemapImpactFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TilemapImpactFile = new Class({ + + Extends: JSONFile, + + initialize: + + function TilemapImpactFile (loader, key, url, xhrSettings) + { + JSONFile.call(this, loader, key, url, xhrSettings); + + this.type = 'tilemapJSON'; + + this.cache = loader.cacheManager.tilemap; + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.TilemapImpactFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var tiledata = { format: TILEMAP_FORMATS.WELTMEISTER, data: this.data }; + + this.cache.add(this.key, tiledata); + + this.pendingDestroy(tiledata); + } + +}); + +/** + * Adds an Impact.js Tilemap file, or array of map 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.tilemapImpact('level1', 'maps/Level1.json'); + * } + * ``` + * + * Impact Tilemap data is created the Impact.js Map Editor called Weltmeister. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapImpact({ + * key: 'level1', + * url: 'maps/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapImpact('level1', 'maps/Level1.json'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.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. + * + * Note: The ability to load this type of file will only be available if the Tilemap Impact 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#tilemapImpact + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.7.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('tilemapImpact', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TilemapImpactFile(this, key[i])); + } + } + else + { + this.addFile(new TilemapImpactFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TilemapImpactFile; + + +/***/ }), +/* 1280 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var JSONFile = __webpack_require__(66); +var TILEMAP_FORMATS = __webpack_require__(34); + +/** + * @classdesc + * A single Tiled Tilemap JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapTiledJSON method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapTiledJSON. + * + * @class TilemapJSONFile + * @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.TilemapJSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TilemapJSONFile = new Class({ + + Extends: JSONFile, + + initialize: + + function TilemapJSONFile (loader, key, url, xhrSettings) + { + JSONFile.call(this, loader, key, url, xhrSettings); + + this.type = 'tilemapJSON'; + + this.cache = loader.cacheManager.tilemap; + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.TilemapJSONFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var tiledata = { format: TILEMAP_FORMATS.TILED_JSON, data: this.data }; + + this.cache.add(this.key, tiledata); + + this.pendingDestroy(tiledata); + } + +}); + +/** + * Adds a Tiled JSON Tilemap file, or array of map 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.tilemapTiledJSON('level1', 'maps/Level1.json'); + * } + * ``` + * + * The Tilemap data is created using the Tiled Map Editor and selecting JSON as the export format. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapTiledJSON({ + * key: 'level1', + * url: 'maps/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapTiledJSON('level1', 'maps/Level1.json'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.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. + * + * Note: The ability to load this type of file will only be available if the Tilemap 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#tilemapTiledJSON + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig|Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('tilemapTiledJSON', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TilemapJSONFile(this, key[i])); + } + } + else + { + this.addFile(new TilemapJSONFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TilemapJSONFile; + + +/***/ }), +/* 1281 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var ImageFile = __webpack_require__(77); +var IsPlainObject = __webpack_require__(7); +var MultiFile = __webpack_require__(67); +var TextFile = __webpack_require__(482); + +/** + * @classdesc + * A single text file based Unity Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#unityAtlas method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#unityAtlas. + * + * @class UnityAtlasFile + * @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.UnityAtlasFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @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 data file. Used in replacement of the Loaders default XHR Settings. + */ +var UnityAtlasFile = new Class({ + + Extends: MultiFile, + + initialize: + + function UnityAtlasFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new TextFile(loader, { + key: key, + url: GetFastValue(config, 'atlasURL'), + extension: GetFastValue(config, 'atlasExtension', 'txt'), + xhrSettings: GetFastValue(config, 'atlasXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new TextFile(loader, key, atlasURL, atlasXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'unityatlas', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'unityatlas', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.UnityAtlasFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var text = this.files[1]; + var normalMap = (this.files[2]) ? this.files[2].data : null; + + this.loader.textureManager.addUnityAtlas(image.key, image.data, text.data, normalMap); + + text.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * Adds a Unity YAML 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.unityAtlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.txt'); + * } + * ``` + * + * 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 YAML formatted text file as exported from Unity. + * + * 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.unityAtlas({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * atlasURL: 'images/MainMenu.txt' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig` for more details. + * + * 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.unityAtlas('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.unityAtlas('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.txt'); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.unityAtlas({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * normalMap: 'images/MainMenu-n.png', + * atlasURL: 'images/MainMenu.txt' + * }); + * ``` + * + * 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 Unity Atlas 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#unityAtlas + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig|Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @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 data file. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('unityAtlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new UnityAtlasFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new UnityAtlasFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = UnityAtlasFile; + + +/***/ }), +/* 1282 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(32); +var File = __webpack_require__(24); +var FileTypesManager = __webpack_require__(8); +var GetURL = __webpack_require__(143); +var GetFastValue = __webpack_require__(1); +var IsPlainObject = __webpack_require__(7); + +/** + * @classdesc + * A single Video File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#video method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#video. + * + * @class VideoFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.20.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.VideoFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {any} [urlConfig] - The absolute or relative URL to load this file from in a config object. + * @param {string} [loadEvent] - The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. + * @param {boolean} [asBlob] - Load the video as a data blob, or via the Video element? + * @param {boolean} [noAudio] - Does the video have an audio track? If not you can enable auto-playing on it. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var VideoFile = new Class({ + + Extends: File, + + initialize: + + // URL is an object created by VideoFile.getVideoURL + function VideoFile (loader, key, urlConfig, loadEvent, asBlob, noAudio, xhrSettings) + { + if (loadEvent === undefined) { loadEvent = 'loadeddata'; } + if (asBlob === undefined) { asBlob = false; } + if (noAudio === undefined) { noAudio = false; } + + if (loadEvent !== 'loadeddata' && loadEvent !== 'canplay' && loadEvent !== 'canplaythrough') + { + loadEvent = 'loadeddata'; + } + + var fileConfig = { + type: 'video', + cache: loader.cacheManager.video, + extension: urlConfig.type, + responseType: 'blob', + key: key, + url: urlConfig.url, + xhrSettings: xhrSettings, + config: { + loadEvent: loadEvent, + asBlob: asBlob, + noAudio: noAudio + } + }; + + this.onLoadCallback = this.onVideoLoadHandler.bind(this); + this.onErrorCallback = this.onVideoErrorHandler.bind(this); + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.VideoFile#onProcess + * @since 3.20.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + if (!this.config.asBlob) + { + this.onProcessComplete(); + + return; + } + + // Load Video as blob + + var video = this.createVideoElement(); + + this.data = video; + + var _this = this; + + this.data.onloadeddata = function () + { + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessError(); + }; + + File.createObjectURL(video, this.xhrLoader.response, ''); + + video.load(); + }, + + /** + * Creates a Video Element within the DOM. + * + * @method Phaser.Loader.FileTypes.VideoFile#createVideoElement + * @private + * @since 3.20.0 + * + * @return {HTMLVideoElement} The newly created Video element. + */ + createVideoElement: function () + { + var video = document.createElement('video'); + + video.controls = false; + video.crossOrigin = this.loader.crossOrigin; + + if (this.config.noAudio) + { + video.muted = true; + video.defaultMuted = true; + + video.setAttribute('autoplay', 'autoplay'); + } + + video.setAttribute('playsinline', 'playsinline'); + video.setAttribute('preload', 'auto'); + + return video; + }, + + /** + * Internal load event callback. + * + * @method Phaser.Loader.FileTypes.VideoFile#onVideoLoadHandler + * @private + * @since 3.20.0 + * + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. + */ + onVideoLoadHandler: function (event) + { + var video = event.target; + + video.removeEventListener(this.config.loadEvent, this.onLoadCallback, true); + video.removeEventListener('error', this.onErrorCallback, true); + + this.data = video; + + this.resetXHR(); + + this.loader.nextFile(this, true); + }, + + /** + * Internal load error event callback. + * + * @method Phaser.Loader.FileTypes.VideoFile#onVideoErrorHandler + * @private + * @since 3.20.0 + * + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. + */ + onVideoErrorHandler: function (event) + { + var video = event.target; + + if (video) + { + video.removeEventListener(this.config.loadEvent, this.onLoadCallback, true); + video.removeEventListener('error', this.onErrorCallback, true); + } + + this.resetXHR(); + + this.loader.nextFile(this, false); + }, + + /** + * 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.FileTypes.VideoFile#load + * @since 3.20.0 + */ + load: function () + { + var loadEvent = this.config.loadEvent; + + if (this.config.asBlob) + { + File.prototype.load.call(this); + } + else + { + this.percentComplete = 0; + + var video = this.createVideoElement(); + + video.addEventListener(loadEvent, this.onLoadCallback, true); + video.addEventListener('error', this.onErrorCallback, true); + + video.src = GetURL(this, this.loader.baseURL); + + video.load(); + } + } + +}); + +VideoFile.create = function (loader, key, urls, loadEvent, asBlob, noAudio, xhrSettings) +{ + var game = loader.systems.game; + + // url may be inside key, which may be an object + if (IsPlainObject(key)) + { + urls = GetFastValue(key, 'url', []); + loadEvent = GetFastValue(key, 'loadEvent', 'loadeddata'); + asBlob = GetFastValue(key, 'asBlob', false); + noAudio = GetFastValue(key, 'noAudio', false); + xhrSettings = GetFastValue(key, 'xhrSettings'); + } + + var urlConfig = VideoFile.getVideoURL(game, urls); + + if (urlConfig) + { + return new VideoFile(loader, key, urlConfig, loadEvent, asBlob, noAudio, xhrSettings); + } +}; + +VideoFile.getVideoURL = function (game, urls) +{ + if (!Array.isArray(urls)) + { + urls = [ urls ]; + } + + for (var i = 0; i < urls.length; i++) + { + var url = GetFastValue(urls[i], 'url', urls[i]); + + if (url.indexOf('blob:') === 0) + { + return url; + } + + var videoType; + + if (url.indexOf('data:') === 0) + { + videoType = url.split(',')[0].match(/\/(.*?);/); + } + else + { + videoType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); + } + + videoType = GetFastValue(urls[i], 'type', (videoType) ? videoType[1] : '').toLowerCase(); + + if (game.device.video[videoType]) + { + return { + url: url, + type: videoType + }; + } + } + + return null; +}; + +/** + * 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' ], + * asBlob: false, + * 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.LoaderPlugin#addFileEvent + * @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[])} [urls] - The absolute or relative URL to load the video files from. + * @param {string} [loadEvent='loadeddata'] - The load event to listen for when _not_ loading as a blob. Either `loadeddata`, `canplay` or `canplaythrough`. + * @param {boolean} [asBlob=false] - Load the video as a data blob, or stream it via the Video element? + * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + * + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. + */ +FileTypesManager.register('video', function (key, urls, loadEvent, asBlob, noAudio, xhrSettings) +{ + var videoFile; + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + videoFile = VideoFile.create(this, key[i]); + + if (videoFile) + { + this.addFile(videoFile); + } + } + } + else + { + videoFile = VideoFile.create(this, key, urls, loadEvent, asBlob, noAudio, xhrSettings); + + if (videoFile) + { + this.addFile(videoFile); + } + } + + return this; +}); + +module.exports = VideoFile; + + +/***/ }), +/* 1283 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var CONST = __webpack_require__(23); +var CustomSet = __webpack_require__(110); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(87); +var FileTypesManager = __webpack_require__(8); +var GetFastValue = __webpack_require__(1); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); +var XHRSettings = __webpack_require__(144); + +/** + * @classdesc + * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. + * You typically interact with it via `this.load` in your Scene. Scenes can have a `preload` method, which is always + * called before the Scenes `create` method, allowing you to preload assets that the Scene may need. + * + * If you call any `this.load` methods from outside of `Scene.preload` then you need to start the Loader going + * yourself by calling `Loader.start()`. It's only automatically started during the Scene preload. + * + * The Loader uses a combination of tag loading (eg. Audio elements) and XHR and provides progress and completion events. + * Files are loaded in parallel by default. The amount of concurrent connections can be controlled in your Game Configuration. + * + * Once the Loader has started loading you are still able to add files to it. These can be injected as a result of a loader + * event, the type of file being loaded (such as a pack file) or other external events. As long as the Loader hasn't finished + * simply adding a new file to it, while running, will ensure it's added into the current queue. + * + * Every Scene has its own instance of the Loader and they are bound to the Scene in which they are created. However, + * assets loaded by the Loader are placed into global game-level caches. For example, loading an XML file will place that + * file inside `Game.cache.xml`, which is accessible from every Scene in your game, no matter who was responsible + * for loading it. The same is true of Textures. A texture loaded in one Scene is instantly available to all other Scenes + * in your game. + * + * The Loader works by using custom File Types. These are stored in the FileTypesManager, which injects them into the Loader + * when it's instantiated. You can create your own custom file types by extending either the File or MultiFile classes. + * See those files for more details. + * + * @class LoaderPlugin + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Loader + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which owns this Loader instance. + */ +var LoaderPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function LoaderPlugin (scene) + { + EventEmitter.call(this); + + var gameConfig = scene.sys.game.config; + var sceneConfig = scene.sys.settings.loader; + + /** + * The Scene which owns this Loader instance. + * + * @name Phaser.Loader.LoaderPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems. + * + * @name Phaser.Loader.LoaderPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the global Cache Manager. + * + * @name Phaser.Loader.LoaderPlugin#cacheManager + * @type {Phaser.Cache.CacheManager} + * @since 3.7.0 + */ + this.cacheManager = scene.sys.cache; + + /** + * A reference to the global Texture Manager. + * + * @name Phaser.Loader.LoaderPlugin#textureManager + * @type {Phaser.Textures.TextureManager} + * @since 3.7.0 + */ + this.textureManager = scene.sys.textures; + + /** + * A reference to the global Scene Manager. + * + * @name Phaser.Loader.LoaderPlugin#sceneManager + * @type {Phaser.Scenes.SceneManager} + * @protected + * @since 3.16.0 + */ + this.sceneManager = scene.sys.game.scene; + + // Inject the available filetypes into the Loader + FileTypesManager.install(this); + + /** + * An optional prefix that is automatically prepended to the start of every file key. + * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. + * You can set this directly, or call `Loader.setPrefix()`. 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. + * + * @name Phaser.Loader.LoaderPlugin#prefix + * @type {string} + * @default '' + * @since 3.7.0 + */ + this.prefix = ''; + + /** + * 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 + */ + this.path = ''; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * + * Useful if allowing the asset base url to be configured outside of the game code. + * + * If you set this property directly then it _must_ end with a "/". Alternatively, call `setBaseURL()` and it'll do it for you. + * + * @name Phaser.Loader.LoaderPlugin#baseURL + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.baseURL = ''; + + this.setBaseURL(GetFastValue(sceneConfig, 'baseURL', gameConfig.loaderBaseURL)); + + this.setPath(GetFastValue(sceneConfig, 'path', gameConfig.loaderPath)); + + this.setPrefix(GetFastValue(sceneConfig, 'prefix', gameConfig.loaderPrefix)); + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Old browsers limit 6 requests per domain; modern ones, especially those with HTTP/2 don't limit it at all. + * + * The default is 32 but you can change this in your Game Config, or by changing this property before the Loader starts. + * + * @name Phaser.Loader.LoaderPlugin#maxParallelDownloads + * @type {integer} + * @since 3.0.0 + */ + this.maxParallelDownloads = GetFastValue(sceneConfig, 'maxParallelDownloads', gameConfig.loaderMaxParallelDownloads); + + /** + * xhr specific global settings (can be overridden on a per-file basis) + * + * @name Phaser.Loader.LoaderPlugin#xhr + * @type {Phaser.Types.Loader.XHRSettingsObject} + * @since 3.0.0 + */ + this.xhr = XHRSettings( + GetFastValue(sceneConfig, 'responseType', gameConfig.loaderResponseType), + GetFastValue(sceneConfig, 'async', gameConfig.loaderAsync), + GetFastValue(sceneConfig, 'user', gameConfig.loaderUser), + GetFastValue(sceneConfig, 'password', gameConfig.loaderPassword), + GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout) + ); + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * + * @name Phaser.Loader.LoaderPlugin#crossOrigin + * @type {string} + * @since 3.0.0 + */ + this.crossOrigin = GetFastValue(sceneConfig, 'crossOrigin', gameConfig.loaderCrossOrigin); + + /** + * The total number of files to load. It may not always be accurate because you may add to the Loader during the process + * of loading, especially if you load a Pack File. Therefore this value can change, but in most cases remains static. + * + * @name Phaser.Loader.LoaderPlugin#totalToLoad + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.totalToLoad = 0; + + /** + * The progress of the current load queue, as a float value between 0 and 1. + * This is updated automatically as files complete loading. + * Note that it is possible for this value to go down again if you add content to the current load queue during a load. + * + * @name Phaser.Loader.LoaderPlugin#progress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.progress = 0; + + /** + * Files are placed in this Set when they're added to the Loader via `addFile`. + * + * They are moved to the `inflight` Set when they start loading, and assuming a successful + * load, to the `queue` Set for further processing. + * + * By the end of the load process this Set will be empty. + * + * @name Phaser.Loader.LoaderPlugin#list + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.list = new CustomSet(); + + /** + * Files are stored in this Set while they're in the process of being loaded. + * + * Upon a successful load they are moved to the `queue` Set. + * + * By the end of the load process this Set will be empty. + * + * @name Phaser.Loader.LoaderPlugin#inflight + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.inflight = new CustomSet(); + + /** + * Files are stored in this Set while they're being processed. + * + * If the process is successful they are moved to their final destination, which could be + * a Cache or the Texture Manager. + * + * At the end of the load process this Set will be empty. + * + * @name Phaser.Loader.LoaderPlugin#queue + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.queue = new CustomSet(); + + /** + * A temporary Set in which files are stored after processing, + * awaiting destruction at the end of the load process. + * + * @name Phaser.Loader.LoaderPlugin#_deleteQueue + * @type {Phaser.Structs.Set.} + * @private + * @since 3.7.0 + */ + this._deleteQueue = new CustomSet(); + + /** + * The total number of files that failed to load during the most recent load. + * This value is reset when you call `Loader.start`. + * + * @name Phaser.Loader.LoaderPlugin#totalFailed + * @type {integer} + * @default 0 + * @since 3.7.0 + */ + this.totalFailed = 0; + + /** + * The total number of files that successfully loaded during the most recent load. + * This value is reset when you call `Loader.start`. + * + * @name Phaser.Loader.LoaderPlugin#totalComplete + * @type {integer} + * @default 0 + * @since 3.7.0 + */ + this.totalComplete = 0; + + /** + * The current state of the Loader. + * + * @name Phaser.Loader.LoaderPlugin#state + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.state = CONST.LOADER_IDLE; + + /** + * The current index being used by multi-file loaders to avoid key clashes. + * + * @name Phaser.Loader.LoaderPlugin#multiKeyIndex + * @type {integer} + * @private + * @since 3.20.0 + */ + this.multiKeyIndex = 0; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.pluginStart, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Loader.LoaderPlugin#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Loader.LoaderPlugin#pluginStart + * @private + * @since 3.5.1 + */ + pluginStart: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * If you want to append a URL before the path of any asset you can set this here. + * + * Useful if allowing the asset base url to be configured outside of the game code. + * + * Once a base URL is set it will affect every file loaded by the Loader from that point on. It does _not_ change any + * file _already_ being loaded. To reset it, call this method with no arguments. + * + * @method Phaser.Loader.LoaderPlugin#setBaseURL + * @since 3.0.0 + * + * @param {string} [url] - The URL to use. Leave empty to reset. + * + * @return {Phaser.Loader.LoaderPlugin} This Loader object. + */ + setBaseURL: function (url) + { + if (url === undefined) { url = ''; } + + if (url !== '' && url.substr(-1) !== '/') + { + url = url.concat('/'); + } + + this.baseURL = url; + + return this; + }, + + /** + * 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 {Phaser.Loader.LoaderPlugin} This Loader object. + */ + setPath: function (path) + { + if (path === undefined) { path = ''; } + + if (path !== '' && path.substr(-1) !== '/') + { + path = path.concat('/'); + } + + this.path = path; + + return this; + }, + + /** + * An optional prefix that is automatically prepended to the start of every file key. + * + * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. + * + * Once a prefix 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#setPrefix + * @since 3.7.0 + * + * @param {string} [prefix] - The prefix to use. Leave empty to reset. + * + * @return {Phaser.Loader.LoaderPlugin} This Loader object. + */ + setPrefix: function (prefix) + { + if (prefix === undefined) { prefix = ''; } + + this.prefix = prefix; + + return this; + }, + + /** + * 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 {Phaser.Loader.LoaderPlugin} This Loader object. + */ + setCORS: function (crossOrigin) + { + this.crossOrigin = crossOrigin; + + return this; + }, + + /** + * Adds a file, or array of files, into the load queue. + * + * The file must be an instance of `Phaser.Loader.File`, or a class that extends it. The Loader will check that the key + * used by the file won't conflict with any other key either in the loader, the inflight queue or the target cache. + * If allowed it will then add the file into the pending list, read for the load to start. Or, if the load has already + * started, ready for the next batch of files to be pulled from the list to the inflight queue. + * + * You should not normally call this method directly, but rather use one of the Loader methods like `image` or `atlas`, + * however you can call this as long as the file given to it is well formed. + * + * @method Phaser.Loader.LoaderPlugin#addFile + * @fires Phaser.Loader.Events#ADD + * @since 3.0.0 + * + * @param {(Phaser.Loader.File|Phaser.Loader.File[])} file - The file, or array of files, to be added to the load queue. + */ + addFile: function (file) + { + if (!Array.isArray(file)) + { + file = [ file ]; + } + + for (var i = 0; i < file.length; i++) + { + var item = file[i]; + + // 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 (!this.keyExists(item)) + { + this.list.set(item); + + this.emit(Events.ADD, item.key, item.type, this, item); + + if (this.isLoading()) + { + this.totalToLoad++; + this.updateProgress(); + } + } + } + }, + + /** + * Checks the key and type of the given file to see if it will conflict with anything already + * in a Cache, the Texture Manager, or the list or inflight queues. + * + * @method Phaser.Loader.LoaderPlugin#keyExists + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The file to check the key of. + * + * @return {boolean} `true` if adding this file will cause a cache or queue conflict, otherwise `false`. + */ + keyExists: function (file) + { + var keyConflict = file.hasCacheConflict(); + + if (!keyConflict) + { + this.list.iterate(function (item) + { + if (item.type === file.type && item.key === file.key) + { + keyConflict = true; + + return false; + } + + }); + } + + if (!keyConflict && this.isLoading()) + { + this.inflight.iterate(function (item) + { + if (item.type === file.type && item.key === file.key) + { + keyConflict = true; + + return false; + } + + }); + + this.queue.iterate(function (item) + { + if (item.type === file.type && item.key === file.key) + { + keyConflict = true; + + return false; + } + + }); + } + + return keyConflict; + }, + + /** + * Takes a well formed, fully parsed pack file object and adds its entries into the load queue. Usually you do not call + * this method directly, but instead use `Loader.pack` and supply a path to a JSON file that holds the + * pack data. However, if you've got the data prepared you can pass it to this method. + * + * You can also provide an optional key. If you do then it will only add the entries from that part of the pack into + * to the load queue. If not specified it will add all entries it finds. For more details about the pack file format + * see the `LoaderPlugin.pack` method. + * + * @method Phaser.Loader.LoaderPlugin#addPack + * @since 3.7.0 + * + * @param {any} data - The Pack File data to be parsed and each entry of it to added to the load queue. + * @param {string} [packKey] - An optional key to use from the pack file data. + * + * @return {boolean} `true` if any files were added to the queue, otherwise `false`. + */ + addPack: function (pack, packKey) + { + // if no packKey provided we'll add everything to the queue + if (packKey && pack.hasOwnProperty(packKey)) + { + pack = { packKey: pack[packKey] }; + } + + var total = 0; + + // Store the loader settings in case this pack replaces them + var currentBaseURL = this.baseURL; + var currentPath = this.path; + var currentPrefix = this.prefix; + + // Here we go ... + for (var key in pack) + { + var config = pack[key]; + + // Any meta data to process? + var baseURL = GetFastValue(config, 'baseURL', currentBaseURL); + var path = GetFastValue(config, 'path', currentPath); + var prefix = GetFastValue(config, 'prefix', currentPrefix); + var files = GetFastValue(config, 'files', null); + var defaultType = GetFastValue(config, 'defaultType', 'void'); + + if (Array.isArray(files)) + { + this.setBaseURL(baseURL); + this.setPath(path); + this.setPrefix(prefix); + + for (var i = 0; i < files.length; i++) + { + var file = files[i]; + var type = (file.hasOwnProperty('type')) ? file.type : defaultType; + + if (this[type]) + { + this[type](file); + total++; + } + } + } + } + + // Reset the loader settings + this.setBaseURL(currentBaseURL); + this.setPath(currentPath); + this.setPrefix(currentPrefix); + + return (total > 0); + }, + + /** + * Is the Loader actively loading, or processing loaded files? + * + * @method Phaser.Loader.LoaderPlugin#isLoading + * @since 3.0.0 + * + * @return {boolean} `true` if the Loader is busy loading or processing, otherwise `false`. + */ + isLoading: function () + { + return (this.state === CONST.LOADER_LOADING || this.state === CONST.LOADER_PROCESSING); + }, + + /** + * Is the Loader ready to start a new load? + * + * @method Phaser.Loader.LoaderPlugin#isReady + * @since 3.0.0 + * + * @return {boolean} `true` if the Loader is ready to start a new load, otherwise `false`. + */ + isReady: function () + { + return (this.state === CONST.LOADER_IDLE || this.state === CONST.LOADER_COMPLETE); + }, + + /** + * Starts the Loader running. This will reset the progress and totals and then emit a `start` event. + * If there is nothing in the queue the Loader will immediately complete, otherwise it will start + * loading the first batch of files. + * + * The Loader is started automatically if the queue is populated within your Scenes `preload` method. + * + * However, outside of this, you need to call this method to start it. + * + * If the Loader is already running this method will simply return. + * + * @method Phaser.Loader.LoaderPlugin#start + * @fires Phaser.Loader.Events#START + * @since 3.0.0 + */ + start: function () + { + if (!this.isReady()) + { + return; + } + + this.progress = 0; + + this.totalFailed = 0; + this.totalComplete = 0; + this.totalToLoad = this.list.size; + + this.emit(Events.START, this); + + if (this.list.size === 0) + { + this.loadComplete(); + } + else + { + this.state = CONST.LOADER_LOADING; + + this.inflight.clear(); + this.queue.clear(); + + this.updateProgress(); + + this.checkLoadQueue(); + + this.systems.events.on(SceneEvents.UPDATE, this.update, this); + } + }, + + /** + * Called automatically during the load process. + * It updates the `progress` value and then emits a progress event, which you can use to + * display a loading bar in your game. + * + * @method Phaser.Loader.LoaderPlugin#updateProgress + * @fires Phaser.Loader.Events#PROGRESS + * @since 3.0.0 + */ + updateProgress: function () + { + this.progress = 1 - ((this.list.size + this.inflight.size) / this.totalToLoad); + + this.emit(Events.PROGRESS, this.progress); + }, + + /** + * Called automatically during the load process. + * + * @method Phaser.Loader.LoaderPlugin#update + * @since 3.10.0 + */ + update: function () + { + if (this.state === CONST.LOADER_LOADING && this.list.size > 0 && this.inflight.size < this.maxParallelDownloads) + { + this.checkLoadQueue(); + } + }, + + /** + * An internal method called by the Loader. + * + * It will check to see if there are any more files in the pending list that need loading, and if so it will move + * them from the list Set into the inflight Set, set their CORs flag and start them loading. + * + * It will carrying on doing this for each file in the pending list until it runs out, or hits the max allowed parallel downloads. + * + * @method Phaser.Loader.LoaderPlugin#checkLoadQueue + * @private + * @since 3.7.0 + */ + checkLoadQueue: function () + { + this.list.each(function (file) + { + if (file.state === CONST.FILE_POPULATED || (file.state === CONST.FILE_PENDING && this.inflight.size < this.maxParallelDownloads)) + { + this.inflight.set(file); + + this.list.delete(file); + + // If the file doesn't have its own crossOrigin set, we'll use the Loaders (which is undefined by default) + if (!file.crossOrigin) + { + file.crossOrigin = this.crossOrigin; + } + + file.load(); + } + + if (this.inflight.size === this.maxParallelDownloads) + { + // Tells the Set iterator to abort + return false; + } + + }, this); + }, + + /** + * An internal method called automatically by the XHRLoader belong to a File. + * + * This method will remove the given file from the inflight Set and update the load progress. + * If the file was successful its `onProcess` method is called, otherwise it is added to the delete queue. + * + * @method Phaser.Loader.LoaderPlugin#nextFile + * @fires Phaser.Loader.Events#FILE_LOAD + * @fires Phaser.Loader.Events#FILE_LOAD_ERROR + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - The File that just finished loading, or errored during load. + * @param {boolean} success - `true` if the file loaded successfully, otherwise `false`. + */ + nextFile: function (file, success) + { + // Has the game been destroyed during load? If so, bail out now. + if (!this.inflight) + { + return; + } + + this.inflight.delete(file); + + this.updateProgress(); + + if (success) + { + this.totalComplete++; + + this.queue.set(file); + + this.emit(Events.FILE_LOAD, file); + + file.onProcess(); + } + else + { + this.totalFailed++; + + this._deleteQueue.set(file); + + this.emit(Events.FILE_LOAD_ERROR, file); + + this.fileProcessComplete(file); + } + }, + + /** + * An internal method that is called automatically by the File when it has finished processing. + * + * If the process was successful, and the File isn't part of a MultiFile, its `addToCache` method is called. + * + * It this then removed from the queue. If there are no more files to load `loadComplete` is called. + * + * @method Phaser.Loader.LoaderPlugin#fileProcessComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The file that has finished processing. + */ + fileProcessComplete: function (file) + { + // Has the game been destroyed during load? If so, bail out now. + if (!this.scene || !this.systems || !this.systems.game || this.systems.game.pendingDestroy) + { + return; + } + + // This file has failed, so move it to the failed Set + if (file.state === CONST.FILE_ERRORED) + { + if (file.multiFile) + { + file.multiFile.onFileFailed(file); + } + } + else if (file.state === CONST.FILE_COMPLETE) + { + if (file.multiFile) + { + if (file.multiFile.isReadyToProcess()) + { + // If we got here then all files the link file needs are ready to add to the cache + file.multiFile.addToCache(); + } + } + else + { + // If we got here, then the file processed, so let it add itself to its cache + file.addToCache(); + } + } + + // Remove it from the queue + this.queue.delete(file); + + // Nothing left to do? + + if (this.list.size === 0 && this.inflight.size === 0 && this.queue.size === 0) + { + this.loadComplete(); + } + }, + + /** + * Called at the end when the load queue is exhausted and all files have either loaded or errored. + * By this point every loaded file will now be in its associated cache and ready for use. + * + * Also clears down the Sets, puts progress to 1 and clears the deletion queue. + * + * @method Phaser.Loader.LoaderPlugin#loadComplete + * @fires Phaser.Loader.Events#COMPLETE + * @fires Phaser.Loader.Events#POST_PROCESS + * @since 3.7.0 + */ + loadComplete: function () + { + this.emit(Events.POST_PROCESS, this); + + this.list.clear(); + this.inflight.clear(); + this.queue.clear(); + + this.progress = 1; + + this.state = CONST.LOADER_COMPLETE; + + this.systems.events.off(SceneEvents.UPDATE, this.update, this); + + // Call 'destroy' on each file ready for deletion + this._deleteQueue.iterateLocal('destroy'); + + this._deleteQueue.clear(); + + this.emit(Events.COMPLETE, this, this.totalComplete, this.totalFailed); + }, + + /** + * Adds a File into the pending-deletion queue. + * + * @method Phaser.Loader.LoaderPlugin#flagForRemoval + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File to be queued for deletion when the Loader completes. + */ + flagForRemoval: function (file) + { + this._deleteQueue.set(file); + }, + + /** + * Converts the given JSON data into a file that the browser then prompts you to download so you can save it locally. + * + * The data must be well formed JSON and ready-parsed, not a JavaScript object. + * + * @method Phaser.Loader.LoaderPlugin#saveJSON + * @since 3.0.0 + * + * @param {*} data - The JSON data, ready parsed. + * @param {string} [filename=file.json] - The name to save the JSON file as. + * + * @return {Phaser.Loader.LoaderPlugin} This Loader plugin. + */ + saveJSON: function (data, filename) + { + return this.save(JSON.stringify(data), filename); + }, + + /** + * 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 {Phaser.Loader.LoaderPlugin} This Loader plugin. + */ + save: function (data, filename, filetype) + { + if (filename === undefined) { filename = 'file.json'; } + if (filetype === undefined) { filetype = 'application/json'; } + + var blob = new Blob([ data ], { type: filetype }); + + var url = URL.createObjectURL(blob); + + var a = document.createElement('a'); + + a.download = filename; + a.textContent = 'Download ' + filename; + a.href = url; + a.click(); + + return this; + }, + + /** + * Resets the Loader. + * + * This will clear all lists and reset the base URL, path and prefix. + * + * Warning: If the Loader is currently downloading files, or has files in its queue, they will be aborted. + * + * @method Phaser.Loader.LoaderPlugin#reset + * @since 3.0.0 + */ + reset: function () + { + this.list.clear(); + this.inflight.clear(); + this.queue.clear(); + + var gameConfig = this.systems.game.config; + var sceneConfig = this.systems.settings.loader; + + this.setBaseURL(GetFastValue(sceneConfig, 'baseURL', gameConfig.loaderBaseURL)); + this.setPath(GetFastValue(sceneConfig, 'path', gameConfig.loaderPath)); + this.setPrefix(GetFastValue(sceneConfig, 'prefix', gameConfig.loaderPrefix)); + + this.state = CONST.LOADER_IDLE; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Loader.LoaderPlugin#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.reset(); + + this.state = CONST.LOADER_SHUTDOWN; + + this.systems.events.off(SceneEvents.UPDATE, this.update, this); + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Loader.LoaderPlugin#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.state = CONST.LOADER_DESTROYED; + + this.systems.events.off(SceneEvents.UPDATE, this.update, this); + this.systems.events.off(SceneEvents.START, this.pluginStart, this); + + this.list = null; + this.inflight = null; + this.queue = null; + + this.scene = null; + this.systems = null; + this.textureManager = null; + this.cacheManager = null; + this.sceneManager = null; + } + +}); + +PluginCache.register('Loader', LoaderPlugin, 'load'); + +module.exports = LoaderPlugin; + + +/***/ }), +/* 1284 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics + */ + +/** + * @namespace Phaser.Types.Physics + */ + +module.exports = { + + Arcade: __webpack_require__(1285), + Impact: __webpack_require__(1316), + Matter: __webpack_require__(1339) + +}; + + +/***/ }), +/* 1285 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(58); +var Extend = __webpack_require__(17); + +/** + * @callback ArcadePhysicsCallback + * + * @param {Phaser.GameObjects.GameObject} object1 - The first Body to separate. + * @param {Phaser.GameObjects.GameObject} object2 - The second Body to separate. + */ + +/** + * @namespace Phaser.Physics.Arcade + */ + +var Arcade = { + + ArcadePhysics: __webpack_require__(1286), + Body: __webpack_require__(489), + Collider: __webpack_require__(490), + Components: __webpack_require__(229), + Events: __webpack_require__(230), + Factory: __webpack_require__(483), + Group: __webpack_require__(485), + Image: __webpack_require__(484), + Sprite: __webpack_require__(145), + StaticBody: __webpack_require__(495), + StaticGroup: __webpack_require__(486), + World: __webpack_require__(488) + +}; + +// Merge in the consts +Arcade = Extend(false, Arcade, CONST); + +module.exports = Arcade; + + +/***/ }), +/* 1286 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var DegToRad = __webpack_require__(40); +var DistanceBetween = __webpack_require__(54); +var DistanceSquared = __webpack_require__(338); +var Factory = __webpack_require__(483); +var GetFastValue = __webpack_require__(1); +var Merge = __webpack_require__(88); +var OverlapCirc = __webpack_require__(1299); +var OverlapRect = __webpack_require__(487); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); +var Vector2 = __webpack_require__(3); +var World = __webpack_require__(488); + +/** + * @classdesc + * The Arcade Physics Plugin belongs to a Scene and sets up and manages the Scene's physics simulation. + * It also holds some useful methods for moving and rotating Arcade Physics Bodies. + * + * You can access it from within a Scene using `this.physics`. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * + * @class ArcadePhysics + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this Plugin belongs to. + */ +var ArcadePhysics = new Class({ + + initialize: + + function ArcadePhysics (scene) + { + /** + * The Scene that this Plugin belongs to. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene's Systems. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A configuration object. Union of the `physics.arcade.*` properties of the GameConfig and SceneConfig objects. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#config + * @type {object} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * The physics simulation. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world; + + /** + * An object holding the Arcade Physics factory methods. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#add + * @type {Phaser.Physics.Arcade.Factory} + * @since 3.0.0 + */ + this.add; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Creates the physics configuration for the current Scene. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#getConfig + * @since 3.0.0 + * + * @return {object} The physics configuration. + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'arcade', {}), + GetFastValue(gameConfig, 'arcade', {}) + ); + + return config; + }, + + /** + * Tests if Game Objects overlap. See {@link Phaser.Physics.Arcade.World#overlap} + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlap + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {*} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if at least one Game Object overlaps another. + * + * @see Phaser.Physics.Arcade.World#overlap + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) + { + if (overlapCallback === undefined) { overlapCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = overlapCallback; } + + return this.world.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + }, + + /** + * Performs a collision check and separation between the two physics enabled objects given, which can be single + * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. + * + * If you don't require separation then use {@link #overlap} instead. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. + * + * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding + * objects are passed to it. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#collide + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {*} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any overlapping Game Objects were separated, otherwise false. + * + * @see Phaser.Physics.Arcade.World#collide + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + return this.world.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + }, + + /** + * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. + * + * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for collision with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions + * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have + * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the + * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on + * dynamic maps, this method can prove very useful. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#collideTiles + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + return this.world.collideTiles(sprite, tiles, collideCallback, processCallback, callbackContext); + }, + + /** + * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. + * + * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap + * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlapTiles + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + overlapTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + return this.world.overlapTiles(sprite, tiles, collideCallback, processCallback, callbackContext); + }, + + /** + * Pauses the simulation. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#pause + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} The simulation. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * Resumes the simulation (if paused). + * + * @method Phaser.Physics.Arcade.ArcadePhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} The simulation. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) + * + * You must give a maximum speed value, beyond which the game object won't go any faster. + * + * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. + * Note: The game object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#accelerateTo + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The acceleration (change in speed) in pixels per second squared. + * @param {number} [xSpeedMax=500] - The maximum x velocity the game object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the game object can reach. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + accelerateTo: function (gameObject, x, y, speed, xSpeedMax, ySpeedMax) + { + if (speed === undefined) { speed = 60; } + + var angle = Math.atan2(y - gameObject.y, x - gameObject.x); + + gameObject.body.acceleration.setToPolar(angle, speed); + + if (xSpeedMax !== undefined && ySpeedMax !== undefined) + { + gameObject.body.maxVelocity.set(xSpeedMax, ySpeedMax); + } + + return angle; + }, + + /** + * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) + * + * You must give a maximum speed value, beyond which the game object won't go any faster. + * + * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. + * Note: The game object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#accelerateToObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {Phaser.GameObjects.GameObject} destination - The Game Object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The acceleration (change in speed) in pixels per second squared. + * @param {number} [xSpeedMax=500] - The maximum x velocity the game object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the game object can reach. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + accelerateToObject: function (gameObject, destination, speed, xSpeedMax, ySpeedMax) + { + return this.accelerateTo(gameObject, destination.x, destination.y, speed, xSpeedMax, ySpeedMax); + }, + + /** + * Finds the Body or Game Object closest to a source point or object. + * + * If a `targets` argument is passed, this method finds the closest of those. + * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. + * + * If no `targets` argument is passed, this method finds the closest Dynamic Body. + * + * If two or more targets are the exact same distance from the source point, only the first target + * is returned. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#closest + * @since 3.0.0 + * + * @param {any} source - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[]|Phaser.GameObjects.GameObject[])} [targets] - The targets. + * + * @return {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody|Phaser.GameObjects.GameObject)} The target closest to the given source point. + */ + closest: function (source, targets) + { + if (!targets) + { + targets = this.world.bodies.entries; + } + + var min = Number.MAX_VALUE; + var closest = null; + var x = source.x; + var y = source.y; + var len = targets.length; + + for (var i = 0; i < len; i++) + { + var target = targets[i]; + var body = target.body || target; + + if (source === target || source === body || source === body.gameObject || source === body.center) + { + continue; + } + + var distance = DistanceSquared(x, y, body.center.x, body.center.y); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * Finds the Body or Game Object farthest from a source point or object. + * + * If a `targets` argument is passed, this method finds the farthest of those. + * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. + * + * If no `targets` argument is passed, this method finds the farthest Dynamic Body. + * + * If two or more targets are the exact same distance from the source point, only the first target + * is returned. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#furthest + * @since 3.0.0 + * + * @param {any} source - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[]|Phaser.GameObjects.GameObject[])} [targets] - The targets. + * + * @return {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody|Phaser.GameObjects.GameObject)} The target farthest from the given source point. + */ + furthest: function (source, targets) + { + if (!targets) + { + targets = this.world.bodies.entries; + } + + var max = -1; + var farthest = null; + var x = source.x; + var y = source.y; + var len = targets.length; + + for (var i = 0; i < len; i++) + { + var target = targets[i]; + var body = target.body || target; + + if (source === target || source === body || source === body.gameObject || source === body.center) + { + continue; + } + + var distance = DistanceSquared(x, y, body.center.x, body.center.y); + + if (distance > max) + { + farthest = target; + max = distance; + } + + } + + return farthest; + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade.ArcadePhysics#moveTo + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveTo: function (gameObject, x, y, speed, maxTime) + { + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - gameObject.y, x - gameObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = DistanceBetween(gameObject.x, gameObject.y, x, y) / (maxTime / 1000); + } + + gameObject.body.velocity.setToPolar(angle, speed); + + return angle; + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade.ArcadePhysics#moveToObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {object} destination - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (gameObject, destination, speed, maxTime) + { + return this.moveTo(gameObject, destination.x, destination.y, speed, maxTime); + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a vector, or set it to the given vector object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#velocityFromAngle + * @since 3.0.0 + * + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second squared. + * @param {Phaser.Math.Vector2} [vec2] - The Vector2 in which the x and y properties will be set to the calculated velocity. + * + * @return {Phaser.Math.Vector2} The Vector2 that stores the velocity. + */ + velocityFromAngle: function (angle, speed, vec2) + { + if (speed === undefined) { speed = 60; } + if (vec2 === undefined) { vec2 = new Vector2(); } + + return vec2.setToPolar(DegToRad(angle), speed); + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a vector, or set it to the given vector object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#velocityFromRotation + * @since 3.0.0 + * + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second squared + * @param {Phaser.Math.Vector2} [vec2] - The Vector2 in which the x and y properties will be set to the calculated velocity. + * + * @return {Phaser.Math.Vector2} The Vector2 that stores the velocity. + */ + velocityFromRotation: function (rotation, speed, vec2) + { + if (speed === undefined) { speed = 60; } + if (vec2 === undefined) { vec2 = new Vector2(); } + + return vec2.setToPolar(rotation, speed); + }, + + /** + * This method will search the given rectangular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, + * otherwise the search is O(N) for Dynamic Bodies. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlapRect + * @since 3.17.0 + * + * @param {number} x - The top-left x coordinate of the area to search within. + * @param {number} y - The top-left y coordinate of the area to search within. + * @param {number} width - The width of the area to search within. + * @param {number} height - The height of the area to search within. + * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? + * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? + * + * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. + */ + overlapRect: function (x, y, width, height, includeDynamic, includeStatic) + { + return OverlapRect(this.world, x, y, width, height, includeDynamic, includeStatic); + }, + + /** + * This method will search the given circular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, + * otherwise the search is O(N) for Dynamic Bodies. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlapCirc + * @since 3.21.0 + * + * @param {number} x - The x coordinate of the center of the area to search within. + * @param {number} y - The y coordinate of the center of the area to search within. + * @param {number} radius - The radius of the area to search within. + * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? + * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? + * + * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. + */ + overlapCirc: function (x, y, radius, includeDynamic, includeStatic) + { + return OverlapCirc(this.world, x, y, radius, includeDynamic, includeStatic); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + if (!this.world) + { + // Already destroyed + return; + } + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.add.destroy(); + this.world.destroy(); + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('ArcadePhysics', ArcadePhysics, 'arcadePhysics'); + +module.exports = ArcadePhysics; + + +/***/ }), +/* 1287 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the acceleration properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Acceleration + * @since 3.0.0 + */ +var Acceleration = { + + /** + * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. + * + * @method Phaser.Physics.Arcade.Components.Acceleration#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The horizontal acceleration + * @param {number} [y=x] - The vertical acceleration + * + * @return {this} This Game Object. + */ + setAcceleration: function (x, y) + { + this.body.acceleration.set(x, y); + + return this; + }, + + /** + * Sets the body's horizontal acceleration. + * + * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationX + * @since 3.0.0 + * + * @param {number} value - The horizontal acceleration + * + * @return {this} This Game Object. + */ + setAccelerationX: function (value) + { + this.body.acceleration.x = value; + + return this; + }, + + /** + * Sets the body's vertical acceleration. + * + * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationY + * @since 3.0.0 + * + * @param {number} value - The vertical acceleration + * + * @return {this} This Game Object. + */ + setAccelerationY: function (value) + { + this.body.acceleration.y = value; + + return this; + } + +}; + +module.exports = Acceleration; + + +/***/ }), +/* 1288 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the angular acceleration properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Angular + * @since 3.0.0 + */ +var Angular = { + + /** + * Sets the angular velocity of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * + * @method Phaser.Physics.Arcade.Components.Angular#setAngularVelocity + * @since 3.0.0 + * + * @param {number} value - The amount of angular velocity. + * + * @return {this} This Game Object. + */ + setAngularVelocity: function (value) + { + this.body.angularVelocity = value; + + return this; + }, + + /** + * Sets the angular acceleration of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * + * @method Phaser.Physics.Arcade.Components.Angular#setAngularAcceleration + * @since 3.0.0 + * + * @param {number} value - The amount of angular acceleration. + * + * @return {this} This Game Object. + */ + setAngularAcceleration: function (value) + { + this.body.angularAcceleration = value; + + return this; + }, + + /** + * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. + * + * @method Phaser.Physics.Arcade.Components.Angular#setAngularDrag + * @since 3.0.0 + * + * @param {number} value - The amount of drag. + * + * @return {this} This Game Object. + */ + setAngularDrag: function (value) + { + this.body.angularDrag = value; + + return this; + } + +}; + +module.exports = Angular; + + +/***/ }), +/* 1289 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the bounce properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the bounce values of this body. + * + * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. + * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setBounce + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * @param {number} [y=x] - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + * + * @return {this} This Game Object. + */ + setBounce: function (x, y) + { + this.body.bounce.set(x, y); + + return this; + }, + + /** + * Sets the horizontal bounce value for this body. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setBounceX + * @since 3.0.0 + * + * @param {number} value - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * + * @return {this} This Game Object. + */ + setBounceX: function (value) + { + this.body.bounce.x = value; + + return this; + }, + + /** + * Sets the vertical bounce value for this body. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setBounceY + * @since 3.0.0 + * + * @param {number} value - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + * + * @return {this} This Game Object. + */ + setBounceY: function (value) + { + this.body.bounce.y = value; + + return this; + }, + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setCollideWorldBounds + * @since 3.0.0 + * + * @param {boolean} [value=true] - `true` if this body should collide with the world bounds, otherwise `false`. + * @param {number} [bounceX] - If given this will be replace the `worldBounce.x` value. + * @param {number} [bounceY] - If given this will be replace the `worldBounce.y` value. + * + * @return {this} This Game Object. + */ + setCollideWorldBounds: function (value, bounceX, bounceY) + { + this.body.setCollideWorldBounds(value, bounceX, bounceY); + + return this; + } + +}; + +module.exports = Bounce; + + +/***/ }), +/* 1290 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the debug properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Debug + * @since 3.0.0 + */ +var Debug = { + + /** + * Sets the debug values of this body. + * + * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. + * Note that there is a performance cost in drawing debug displays. It should never be used in production. + * + * @method Phaser.Physics.Arcade.Components.Debug#setDebug + * @since 3.0.0 + * + * @param {boolean} showBody - Set to `true` to have this body render its outline to the debug display. + * @param {boolean} showVelocity - Set to `true` to have this body render a velocity marker to the debug display. + * @param {number} bodyColor - The color of the body outline when rendered to the debug display. + * + * @return {this} This Game Object. + */ + setDebug: function (showBody, showVelocity, bodyColor) + { + this.debugShowBody = showBody; + this.debugShowVelocity = showVelocity; + this.debugBodyColor = bodyColor; + + return this; + }, + + /** + * Sets the color of the body outline when it renders to the debug display. + * + * @method Phaser.Physics.Arcade.Components.Debug#setDebugBodyColor + * @since 3.0.0 + * + * @param {number} value - The color of the body outline when rendered to the debug display. + * + * @return {this} This Game Object. + */ + setDebugBodyColor: function (value) + { + this.body.debugBodyColor = value; + + return this; + }, + + /** + * Set to `true` to have this body render its outline to the debug display. + * + * @name Phaser.Physics.Arcade.Components.Debug#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + debugShowBody: { + + get: function () + { + return this.body.debugShowBody; + }, + + set: function (value) + { + this.body.debugShowBody = value; + } + + }, + + /** + * Set to `true` to have this body render a velocity marker to the debug display. + * + * @name Phaser.Physics.Arcade.Components.Debug#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + debugShowVelocity: { + + get: function () + { + return this.body.debugShowVelocity; + }, + + set: function (value) + { + this.body.debugShowVelocity = value; + } + + }, + + /** + * The color of the body outline when it renders to the debug display. + * + * @name Phaser.Physics.Arcade.Components.Debug#debugBodyColor + * @type {number} + * @since 3.0.0 + */ + debugBodyColor: { + + get: function () + { + return this.body.debugBodyColor; + }, + + set: function (value) + { + this.body.debugBodyColor = value; + } + + } + +}; + +module.exports = Debug; + + +/***/ }), +/* 1291 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the drag properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Drag + * @since 3.0.0 + */ +var Drag = { + + /** + * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDrag + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal drag to apply. + * @param {number} [y=x] - The amount of vertical drag to apply. + * + * @return {this} This Game Object. + */ + setDrag: function (x, y) + { + this.body.drag.set(x, y); + + return this; + }, + + /** + * Sets the body's horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDragX + * @since 3.0.0 + * + * @param {number} value - The amount of horizontal drag to apply. + * + * @return {this} This Game Object. + */ + setDragX: function (value) + { + this.body.drag.x = value; + + return this; + }, + + /** + * Sets the body's vertical drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDragY + * @since 3.0.0 + * + * @param {number} value - The amount of vertical drag to apply. + * + * @return {this} This Game Object. + */ + setDragY: function (value) + { + this.body.drag.y = value; + + return this; + }, + + /** + * If this Body is using `drag` for deceleration this function controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDamping + * @since 3.10.0 + * + * @param {boolean} value - `true` to use damping for deceleration, or `false` to use linear deceleration. + * + * @return {this} This Game Object. + */ + setDamping: function (value) + { + this.body.useDamping = value; + + return this; + } + +}; + +module.exports = Drag; + + +/***/ }), +/* 1292 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the enable properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Enable + * @since 3.0.0 + */ +var Enable = { + + /** + * Enables this Game Object's Body. + * + * @method Phaser.Physics.Arcade.Components.Enable#enableBody + * @since 3.0.0 + * + * @param {boolean} reset - Also reset the Body and place it at (x, y). + * @param {number} x - The horizontal position to place the Game Object and Body. + * @param {number} y - The horizontal position to place the Game Object and Body. + * @param {boolean} enableGameObject - Also activate this Game Object. + * @param {boolean} showGameObject - Also show this Game Object. + * + * @return {this} This Game Object. + * + * @see Phaser.Physics.Arcade.Body#enable + * @see Phaser.Physics.Arcade.StaticBody#enable + * @see Phaser.Physics.Arcade.Body#reset + * @see Phaser.Physics.Arcade.StaticBody#reset + * @see Phaser.GameObjects.GameObject#active + * @see Phaser.GameObjects.GameObject#visible + */ + enableBody: function (reset, x, y, enableGameObject, showGameObject) + { + if (reset) + { + this.body.reset(x, y); + } + + if (enableGameObject) + { + this.body.gameObject.active = true; + } + + if (showGameObject) + { + this.body.gameObject.visible = true; + } + + this.body.enable = true; + + return this; + }, + + /** + * Stops and disables this Game Object's Body. + * + * @method Phaser.Physics.Arcade.Components.Enable#disableBody + * @since 3.0.0 + * + * @param {boolean} [disableGameObject=false] - Also deactivate this Game Object. + * @param {boolean} [hideGameObject=false] - Also hide this Game Object. + * + * @return {this} This Game Object. + * + * @see Phaser.Physics.Arcade.Body#enable + * @see Phaser.Physics.Arcade.StaticBody#enable + * @see Phaser.GameObjects.GameObject#active + * @see Phaser.GameObjects.GameObject#visible + */ + disableBody: function (disableGameObject, hideGameObject) + { + if (disableGameObject === undefined) { disableGameObject = false; } + if (hideGameObject === undefined) { hideGameObject = false; } + + this.body.stop(); + + this.body.enable = false; + + if (disableGameObject) + { + this.body.gameObject.active = false; + } + + if (hideGameObject) + { + this.body.gameObject.visible = false; + } + + return this; + }, + + /** + * 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 + */ + refreshBody: function () + { + this.body.updateFromGameObject(); + + return this; + } + +}; + +module.exports = Enable; + + +/***/ }), +/* 1293 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @namespace Phaser.Physics.Arcade.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @method Phaser.Physics.Arcade.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal friction to apply. + * @param {number} [y=x] - The amount of vertical friction to apply. + * + * @return {this} This Game Object. + */ + setFriction: function (x, y) + { + this.body.friction.set(x, y); + + return this; + }, + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @method Phaser.Physics.Arcade.Components.Friction#setFrictionX + * @since 3.0.0 + * + * @param {number} x - The amount of friction to apply. + * + * @return {this} This Game Object. + */ + setFrictionX: function (x) + { + this.body.friction.x = x; + + return this; + }, + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @method Phaser.Physics.Arcade.Components.Friction#setFrictionY + * @since 3.0.0 + * + * @param {number} x - The amount of friction to apply. + * + * @return {this} This Game Object. + */ + setFrictionY: function (y) + { + this.body.friction.y = y; + + return this; + } + +}; + +module.exports = Friction; + + +/***/ }), +/* 1294 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods for setting the gravity properties of an Arcade Physics Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.Physics.Arcade.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. + * + * If only one value is provided, this value will be used for both the X and Y axis. + * + * @method Phaser.Physics.Arcade.Components.Gravity#setGravity + * @since 3.0.0 + * + * @param {number} x - The gravitational force to be applied to the X-axis. + * @param {number} [y=x] - The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. + * + * @return {this} This Game Object. + */ + setGravity: function (x, y) + { + this.body.gravity.set(x, y); + + return this; + }, + + /** + * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. + * + * @method Phaser.Physics.Arcade.Components.Gravity#setGravityX + * @since 3.0.0 + * + * @param {number} x - The gravitational force to be applied to the X-axis. + * + * @return {this} This Game Object. + */ + setGravityX: function (x) + { + this.body.gravity.x = x; + + return this; + }, + + /** + * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. + * + * @method Phaser.Physics.Arcade.Components.Gravity#setGravityY + * @since 3.0.0 + * + * @param {number} y - The gravitational force to be applied to the Y-axis. + * + * @return {this} This Game Object. + */ + setGravityY: function (y) + { + this.body.gravity.y = y; + + return this; + } + +}; + +module.exports = Gravity; + + +/***/ }), +/* 1295 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the immovable properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Immovable + * @since 3.0.0 + */ +var Immovable = { + + /** + * Sets Whether this Body can be moved by collisions with another Body. + * + * @method Phaser.Physics.Arcade.Components.Immovable#setImmovable + * @since 3.0.0 + * + * @param {boolean} [value=true] - Sets if this body can be moved by collisions with another Body. + * + * @return {this} This Game Object. + */ + setImmovable: function (value) + { + if (value === undefined) { value = true; } + + this.body.immovable = value; + + return this; + } + +}; + +module.exports = Immovable; + + +/***/ }), +/* 1296 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the mass properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Mass + * @since 3.0.0 + */ +var Mass = { + + /** + * Sets the mass of the physics body + * + * @method Phaser.Physics.Arcade.Components.Mass#setMass + * @since 3.0.0 + * + * @param {number} value - New value for the mass of the body. + * + * @return {this} This Game Object. + */ + setMass: function (value) + { + this.body.mass = value; + + return this; + } + +}; + +module.exports = Mass; + + +/***/ }), +/* 1297 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods for setting the size of an Arcade Physics Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.Physics.Arcade.Components.Size + * @since 3.0.0 + */ +var Size = { + + /** + * Sets the body offset. This allows you to adjust the difference between the center of the body + * and the x and y coordinates of the parent Game Object. + * + * @method Phaser.Physics.Arcade.Components.Size#setOffset + * @since 3.0.0 + * + * @param {number} x - The amount to offset the body from the parent Game Object along the x-axis. + * @param {number} [y=x] - The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. + * + * @return {this} This Game Object. + */ + setOffset: function (x, y) + { + this.body.setOffset(x, y); + + return this; + }, + + /** + * Sets the size of this physics body. Setting the size does not adjust the dimensions + * of the parent Game Object. + * + * @method Phaser.Physics.Arcade.Components.Size#setSize + * @since 3.0.0 + * + * @param {number} width - The new width of the physics body, in pixels. + * @param {number} height - The new height of the physics body, in pixels. + * @param {boolean} [center=true] - Should the body be re-positioned so its center aligns with the parent Game Object? + * + * @return {this} This Game Object. + */ + setSize: function (width, height, center) + { + this.body.setSize(width, height, center); + + return this; + }, + + /** + * Sets this physics body to use a circle for collision instead of a rectangle. + * + * @method Phaser.Physics.Arcade.Components.Size#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the physics body, in pixels. + * @param {number} [offsetX] - The amount to offset the body from the parent Game Object along the x-axis. + * @param {number} [offsetY] - The amount to offset the body from the parent Game Object along the y-axis. + * + * @return {this} This Game Object. + */ + setCircle: function (radius, offsetX, offsetY) + { + this.body.setCircle(radius, offsetX, offsetY); + + return this; + } + +}; + +module.exports = Size; + + +/***/ }), +/* 1298 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods for modifying the velocity of an Arcade Physics body. + * + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.Physics.Arcade.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the velocity of the Body. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. + * @param {number} [y=x] - The vertical velocity of the body. Positive values move the body down, while negative values move it up. + * + * @return {this} This Game Object. + */ + setVelocity: function (x, y) + { + this.body.setVelocity(x, y); + + return this; + }, + + /** + * Sets the horizontal component of the body's velocity. + * + * Positive values move the body to the right, while negative values move it to the left. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The new horizontal velocity. + * + * @return {this} This Game Object. + */ + setVelocityX: function (x) + { + this.body.setVelocityX(x); + + return this; + }, + + /** + * Sets the vertical component of the body's velocity. + * + * Positive values move the body down, while negative values move it up. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The new vertical velocity of the body. + * + * @return {this} This Game Object. + */ + setVelocityY: function (y) + { + this.body.setVelocityY(y); + + return this; + }, + + /** + * Sets the maximum velocity of the body. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setMaxVelocity + * @since 3.0.0 + * + * @param {number} x - The new maximum horizontal velocity. + * @param {number} [y=x] - The new maximum vertical velocity. + * + * @return {this} This Game Object. + */ + setMaxVelocity: function (x, y) + { + this.body.maxVelocity.set(x, y); + + return this; + } + +}; + +module.exports = Velocity; + + +/***/ }), +/* 1299 */ +/***/ (function(module, exports, __webpack_require__) { + +var OverlapRect = __webpack_require__(487); +var Circle = __webpack_require__(71); +var CircleToCircle = __webpack_require__(217); +var CircleToRectangle = __webpack_require__(218); + +/** + * This method will search the given circular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, + * otherwise the search is O(N) for Dynamic Bodies. + * + * @function Phaser.Physics.Arcade.Components.OverlapCirc + * @since 3.21.0 + * + * @param {number} x - The x coordinate of the center of the area to search within. + * @param {number} y - The y coordinate of the center of the area to search within. + * @param {number} radius - The radius of the area to search within. + * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? + * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? + * + * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. + */ +var OverlapCirc = function (world, x, y, radius, includeDynamic, includeStatic) +{ + var bodiesInRect = OverlapRect(world, x - radius, y - radius, 2 * radius, 2 * radius, includeDynamic, includeStatic); + + if (bodiesInRect.length === 0) + { + return bodiesInRect; + } + + var area = new Circle(x, y, radius); + var circFromBody = new Circle(); + var bodiesInArea = []; + + for (var i = 0; i < bodiesInRect.length; i++) + { + var body = bodiesInRect[i]; + + if (body.isCircle) + { + circFromBody.setTo(body.center.x, body.center.y, body.halfWidth); + + if (CircleToCircle(area, circFromBody)) + { + bodiesInArea.push(body); + } + } + else if (CircleToRectangle(area, body)) + { + bodiesInArea.push(body); + } + } + + return bodiesInArea; +}; + +module.exports = OverlapCirc; + + +/***/ }), +/* 1300 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Collide Event. + * + * This event is dispatched by an Arcade Physics World instance if two bodies collide _and_ at least + * one of them has their [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('collide', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject1 - The first Game Object involved in the collision. This is the parent of `body1`. + * @param {Phaser.GameObjects.GameObject} gameObject2 - The second Game Object involved in the collision. This is the parent of `body2`. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body1 - The first Physics Body involved in the collision. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body2 - The second Physics Body involved in the collision. + */ +module.exports = 'collide'; + + +/***/ }), +/* 1301 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Overlap Event. + * + * This event is dispatched by an Arcade Physics World instance if two bodies overlap _and_ at least + * one of them has their [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. + * + * It provides an alternative means to handling overlap events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('overlap', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#OVERLAP + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject1 - The first Game Object involved in the overlap. This is the parent of `body1`. + * @param {Phaser.GameObjects.GameObject} gameObject2 - The second Game Object involved in the overlap. This is the parent of `body2`. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body1 - The first Physics Body involved in the overlap. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body2 - The second Physics Body involved in the overlap. + */ +module.exports = 'overlap'; + + +/***/ }), +/* 1302 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Pause Event. + * + * This event is dispatched by an Arcade Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.physics.world.on('pause', listener)`. + * + * @event Phaser.Physics.Arcade.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; + + +/***/ }), +/* 1303 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Resume Event. + * + * This event is dispatched by an Arcade Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.physics.world.on('resume', listener)`. + * + * @event Phaser.Physics.Arcade.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; + + +/***/ }), +/* 1304 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics Tile Collide Event. + * + * This event is dispatched by an Arcade Physics World instance if a body collides with a Tile _and_ + * has its [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('tilecollide', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @since 3.16.1 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object involved in the collision. This is the parent of `body`. + * @param {Phaser.Tilemaps.Tile} tile - The tile the body collided with. + * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body of the Game Object involved in the collision. + */ +module.exports = 'tilecollide'; + + +/***/ }), +/* 1305 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics Tile Overlap Event. + * + * This event is dispatched by an Arcade Physics World instance if a body overlaps with a Tile _and_ + * has its [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. + * + * It provides an alternative means to handling overlap events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('tileoverlap', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.16.1 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object involved in the overlap. This is the parent of `body`. + * @param {Phaser.Tilemaps.Tile} tile - The tile the body overlapped. + * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body of the Game Object involved in the overlap. + */ +module.exports = 'tileoverlap'; + + +/***/ }), +/* 1306 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Bounds Event. + * + * This event is dispatched by an Arcade Physics World instance if a body makes contact with the world bounds _and_ + * it has its [onWorldBounds]{@link Phaser.Physics.Arcade.Body#onWorldBounds} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('worldbounds', listener)`. + * + * @event Phaser.Physics.Arcade.Events#WORLD_BOUNDS + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body that hit the world bounds. + * @param {boolean} up - Is the Body blocked up? I.e. collided with the top of the world bounds. + * @param {boolean} down - Is the Body blocked down? I.e. collided with the bottom of the world bounds. + * @param {boolean} left - Is the Body blocked left? I.e. collided with the left of the world bounds. + * @param {boolean} right - Is the Body blocked right? I.e. collided with the right of the world bounds. + */ +module.exports = 'worldbounds'; + + +/***/ }), +/* 1307 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Step Event. + * + * This event is dispatched by an Arcade Physics World instance whenever a physics step is run. + * It is emitted _after_ the bodies and colliders have been updated. + * + * In high framerate settings this can be multiple times per game frame. + * + * Listen to it from a Scene using: `this.physics.world.on('worldstep', listener)`. + * + * @event Phaser.Physics.Arcade.Events#WORLD_STEP + * @since 3.18.0 + */ +module.exports = 'worldstep'; + + +/***/ }), +/* 1308 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A function to process the collision callbacks between a single tile and an Arcade Physics enabled Game Object. + * + * @function Phaser.Physics.Arcade.Tilemap.ProcessTileCallbacks + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The Tile to process. + * @param {Phaser.GameObjects.Sprite} sprite - The Game Object to process with the Tile. + * + * @return {boolean} The result of the callback, `true` for further processing, or `false` to skip this pair. + */ +var ProcessTileCallbacks = function (tile, sprite) +{ + // Tile callbacks take priority over layer level callbacks + if (tile.collisionCallback) + { + return !tile.collisionCallback.call(tile.collisionCallbackContext, sprite, tile); + } + else if (tile.layer.callbacks[tile.index]) + { + return !tile.layer.callbacks[tile.index].callback.call( + tile.layer.callbacks[tile.index].callbackContext, sprite, tile + ); + } + + return true; +}; + +module.exports = ProcessTileCallbacks; + + +/***/ }), +/* 1309 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TileCheckX = __webpack_require__(1310); +var TileCheckY = __webpack_require__(1312); +var TileIntersectsBody = __webpack_require__(494); + +/** + * The core separation function to separate a physics body and a tile. + * + * @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.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemapLayer to collide against. + * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @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`. + */ +var SeparateTile = function (i, body, tile, tileWorldRect, tilemapLayer, tileBias, isLayer) +{ + var tileLeft = tileWorldRect.left; + var tileTop = tileWorldRect.top; + var tileRight = tileWorldRect.right; + var tileBottom = tileWorldRect.bottom; + var faceHorizontal = tile.faceLeft || tile.faceRight; + var faceVertical = tile.faceTop || tile.faceBottom; + + if (!isLayer) + { + faceHorizontal = true; + faceVertical = true; + } + + // 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. + if (!faceHorizontal && !faceVertical) + { + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && faceHorizontal && faceVertical) + { + // We only need do this if both axes have colliding faces AND we're moving in both + // directions + minX = Math.min(Math.abs(body.position.x - tileRight), Math.abs(body.right - tileLeft)); + minY = Math.min(Math.abs(body.position.y - tileBottom), Math.abs(body.bottom - tileTop)); + } + + if (minX < minY) + { + if (faceHorizontal) + { + ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias, isLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !TileIntersectsBody(tileWorldRect, body)) + { + return true; + } + } + + if (faceVertical) + { + oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias, isLayer); + } + } + else + { + if (faceVertical) + { + oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias, isLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !TileIntersectsBody(tileWorldRect, body)) + { + return true; + } + } + + if (faceHorizontal) + { + ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias, isLayer); + } + } + + return (ox !== 0 || oy !== 0); +}; + +module.exports = SeparateTile; + + +/***/ }), +/* 1310 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ProcessTileSeparationX = __webpack_require__(1311); + +/** + * Check the body against the given tile on the X axis. + * Used internally by the SeparateTile function. + * + * @function Phaser.Physics.Arcade.Tilemap.TileCheckX + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tilemaps.Tile} tile - The tile to check. + * @param {number} tileLeft - The left position of the tile within the tile world. + * @param {number} tileRight - The right position of the tile within the tile world. + * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles? + * + * @return {number} The amount of separation that occurred. + */ +var TileCheckX = function (body, tile, tileLeft, tileRight, tileBias, isLayer) +{ + var ox = 0; + + var faceLeft = tile.faceLeft; + var faceRight = tile.faceRight; + var collideLeft = tile.collideLeft; + var collideRight = tile.collideRight; + + if (!isLayer) + { + faceLeft = true; + faceRight = true; + collideLeft = true; + collideRight = true; + } + + if (body.deltaX() < 0 && collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (faceRight && body.x < tileRight) + { + ox = body.x - tileRight; + + if (ox < -tileBias) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (faceLeft && body.right > tileLeft) + { + ox = body.right - tileLeft; + + if (ox > tileBias) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + ProcessTileSeparationX(body, ox); + } + } + + return ox; +}; + +module.exports = TileCheckX; + + +/***/ }), +/* 1311 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internal function to process the separation of a physics body from a tile. + * + * @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 separation amount. + */ +var ProcessTileSeparationX = function (body, x) +{ + if (x < 0) + { + body.blocked.none = false; + body.blocked.left = true; + } + else if (x > 0) + { + body.blocked.none = false; + body.blocked.right = true; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } +}; + +module.exports = ProcessTileSeparationX; + + +/***/ }), +/* 1312 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ProcessTileSeparationY = __webpack_require__(1313); + +/** + * Check the body against the given tile on the Y axis. + * Used internally by the SeparateTile function. + * + * @function Phaser.Physics.Arcade.Tilemap.TileCheckY + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tilemaps.Tile} tile - The tile to check. + * @param {number} tileTop - The top position of the tile within the tile world. + * @param {number} tileBottom - The bottom position of the tile within the tile world. + * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles? + * + * @return {number} The amount of separation that occurred. + */ +var TileCheckY = function (body, tile, tileTop, tileBottom, tileBias, isLayer) +{ + var oy = 0; + + var faceTop = tile.faceTop; + var faceBottom = tile.faceBottom; + var collideUp = tile.collideUp; + var collideDown = tile.collideDown; + + if (!isLayer) + { + faceTop = true; + faceBottom = true; + collideUp = true; + collideDown = true; + } + + if (body.deltaY() < 0 && collideDown && body.checkCollision.up) + { + // Body is moving UP + if (faceBottom && body.y < tileBottom) + { + oy = body.y - tileBottom; + + if (oy < -tileBias) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (faceTop && body.bottom > tileTop) + { + oy = body.bottom - tileTop; + + if (oy > tileBias) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + ProcessTileSeparationY(body, oy); + } + } + + return oy; +}; + +module.exports = TileCheckY; + + +/***/ }), +/* 1313 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internal function to process the separation of a physics body from a tile. + * + * @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 y separation amount. + */ +var ProcessTileSeparationY = function (body, y) +{ + if (y < 0) + { + body.blocked.none = false; + body.blocked.up = true; + } + else if (y > 0) + { + body.blocked.none = false; + body.blocked.down = true; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } +}; + +module.exports = ProcessTileSeparationY; + + +/***/ }), +/* 1314 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetOverlapX = __webpack_require__(491); + +/** + * 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 they are static, or if either one uses custom logic for its separation. + * + * @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. + * + * @return {boolean} `true` if the two bodies overlap horizontally, otherwise `false`. + */ +var SeparateX = function (body1, body2, overlapOnly, bias) +{ + var overlap = GetOverlapX(body1, body2, overlapOnly, bias); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; +}; + +module.exports = SeparateX; + + +/***/ }), +/* 1315 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetOverlapY = __webpack_require__(492); + +/** + * 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. + * + * @return {boolean} `true` if the two bodies overlap vertically, otherwise `false`. + */ +var SeparateY = function (body1, body2, overlapOnly, bias) +{ + var overlap = GetOverlapY(body1, body2, overlapOnly, bias); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; +}; + +module.exports = SeparateY; + + +/***/ }), +/* 1316 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * An Impact.js compatible physics world, body and solver, for those who are used + * to the Impact way of defining and controlling physics bodies. Also works with + * the new Loader support for Weltmeister map data. + * + * World updated to run off the Phaser main loop. + * Body extended to support additional setter functions. + * + * To create the map data you'll need Weltmeister, which comes with Impact + * and can be purchased from http://impactjs.com + * + * My thanks to Dominic Szablewski for his permission to support Impact in Phaser. + * + * @namespace Phaser.Physics.Impact + */ +module.exports = { + + Body: __webpack_require__(496), + Events: __webpack_require__(231), + COLLIDES: __webpack_require__(112), + CollisionMap: __webpack_require__(497), + Factory: __webpack_require__(498), + Image: __webpack_require__(500), + ImpactBody: __webpack_require__(499), + ImpactPhysics: __webpack_require__(1335), + Sprite: __webpack_require__(501), + TYPE: __webpack_require__(113), + World: __webpack_require__(502) + +}; + + +/***/ }), +/* 1317 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); + +/** + * [description] + * + * @function Phaser.Physics.Impact.GetVelocity + * @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. + * @param {number} vel - [description] + * @param {number} accel - [description] + * @param {number} friction - [description] + * @param {number} max - [description] + * + * @return {number} [description] + */ +var GetVelocity = function (delta, vel, accel, friction, max) +{ + if (accel) + { + return Clamp(vel + accel * delta, -max, max); + } + else if (friction) + { + var frictionDelta = friction * delta; + + if (vel - frictionDelta > 0) + { + return vel - frictionDelta; + } + else if (vel + frictionDelta < 0) + { + return vel + frictionDelta; + } + else + { + return 0; + } + } + + return Clamp(vel, -max, max); +}; + +module.exports = GetVelocity; + + +/***/ }), +/* 1318 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Set up the trace-result + * var res = { + * collision: {x: false, y: false, slope: false}, + * pos: {x: x, y: y}, + * tile: {x: 0, y: 0} + * }; + * + * @function Phaser.Physics.Impact.UpdateMotion + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {object} res - [description] + */ +var UpdateMotion = function (body, res) +{ + body.standing = false; + + // Y + if (res.collision.y) + { + if (body.bounciness > 0 && Math.abs(body.vel.y) > body.minBounceVelocity) + { + body.vel.y *= -body.bounciness; + } + else + { + if (body.vel.y > 0) + { + body.standing = true; + } + + body.vel.y = 0; + } + } + + // X + if (res.collision.x) + { + if (body.bounciness > 0 && Math.abs(body.vel.x) > body.minBounceVelocity) + { + body.vel.x *= -body.bounciness; + } + else + { + body.vel.x = 0; + } + } + + // SLOPE + if (res.collision.slope) + { + var s = res.collision.slope; + + if (body.bounciness > 0) + { + var proj = body.vel.x * s.nx + body.vel.y * s.ny; + + body.vel.x = (body.vel.x - s.nx * proj * 2) * body.bounciness; + body.vel.y = (body.vel.y - s.ny * proj * 2) * body.bounciness; + } + else + { + var lengthSquared = s.x * s.x + s.y * s.y; + var dot = (body.vel.x * s.x + body.vel.y * s.y) / lengthSquared; + + body.vel.x = s.x * dot; + body.vel.y = s.y * dot; + + var angle = Math.atan2(s.x, s.y); + + if (angle > body.slopeStanding.min && angle < body.slopeStanding.max) + { + body.standing = true; + } + } + } + + body.pos.x = res.pos.x; + body.pos.y = res.pos.y; +}; + +module.exports = UpdateMotion; + + +/***/ }), +/* 1319 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Collide Event. + * + * This event is dispatched by an Impact Physics World instance if two bodies collide. + * + * Listen to it from a Scene using: `this.impact.world.on('collide', listener)`. + * + * @event Phaser.Physics.Impact.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} bodyA - The first body involved in the collision. + * @param {Phaser.Physics.Impact.Body} bodyB - The second body involved in the collision. + * @param {string} axis - The collision axis. Either `x` or `y`. + */ +module.exports = 'collide'; + + +/***/ }), +/* 1320 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Pause Event. + * + * This event is dispatched by an Impact Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.impact.world.on('pause', listener)`. + * + * @event Phaser.Physics.Impact.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; + + +/***/ }), +/* 1321 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Resume Event. + * + * This event is dispatched by an Impact Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.impact.world.on('resume', listener)`. + * + * @event Phaser.Physics.Impact.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; + + +/***/ }), +/* 1322 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var H = 0.5; +var N = 1 / 3; +var M = 2 / 3; + +// Tile ID to Slope defs. +// First 4 elements = line data, final = solid or non-solid behind the line + +module.exports = { + + 2: [ 0, 1, 1, 0, true ], + 3: [ 0, 1, 1, H, true ], + 4: [ 0, H, 1, 0, true ], + 5: [ 0, 1, 1, M, true ], + 6: [ 0, M, 1, N, true ], + 7: [ 0, N, 1, 0, true ], + 8: [ H, 1, 0, 0, true ], + 9: [ 1, 0, H, 1, true ], + 10: [ H, 1, 1, 0, true ], + 11: [ 0, 0, H, 1, true ], + 12: [ 0, 0, 1, 0, false ], + 13: [ 1, 1, 0, 0, true ], + 14: [ 1, H, 0, 0, true ], + 15: [ 1, 1, 0, H, true ], + 16: [ 1, N, 0, 0, true ], + 17: [ 1, M, 0, N, true ], + 18: [ 1, 1, 0, M, true ], + 19: [ 1, 1, H, 0, true ], + 20: [ H, 0, 0, 1, true ], + 21: [ 0, 1, H, 0, true ], + 22: [ H, 0, 1, 1, true ], + 23: [ 1, 1, 0, 1, false ], + 24: [ 0, 0, 1, 1, true ], + 25: [ 0, 0, 1, H, true ], + 26: [ 0, H, 1, 1, true ], + 27: [ 0, 0, 1, N, true ], + 28: [ 0, N, 1, M, true ], + 29: [ 0, M, 1, 1, true ], + 30: [ N, 1, 0, 0, true ], + 31: [ 1, 0, M, 1, true ], + 32: [ M, 1, 1, 0, true ], + 33: [ 0, 0, N, 1, true ], + 34: [ 1, 0, 1, 1, false ], + 35: [ 1, 0, 0, 1, true ], + 36: [ 1, H, 0, 1, true ], + 37: [ 1, 0, 0, H, true ], + 38: [ 1, M, 0, 1, true ], + 39: [ 1, N, 0, M, true ], + 40: [ 1, 0, 0, N, true ], + 41: [ M, 1, N, 0, true ], + 42: [ M, 0, N, 1, true ], + 43: [ N, 1, M, 0, true ], + 44: [ N, 0, M, 1, true ], + 45: [ 0, 1, 0, 0, false ], + 52: [ 1, 1, M, 0, true ], + 53: [ N, 0, 0, 1, true ], + 54: [ 0, 1, N, 0, true ], + 55: [ M, 0, 1, 1, true ] + +}; + + +/***/ }), +/* 1323 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Acceleration component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Acceleration + * @since 3.0.0 + */ +var Acceleration = { + + /** + * Sets the horizontal acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationX + * @since 3.0.0 + * + * @param {number} x - The amount of acceleration to apply. + * + * @return {this} This Game Object. + */ + setAccelerationX: function (x) + { + this.accel.x = x; + + return this; + }, + + /** + * Sets the vertical acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationY + * @since 3.0.0 + * + * @param {number} y - The amount of acceleration to apply. + * + * @return {this} This Game Object. + */ + setAccelerationY: function (y) + { + this.accel.y = y; + + return this; + }, + + /** + * Sets the horizontal and vertical acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal acceleration to apply. + * @param {number} y - The amount of vertical acceleration to apply. + * + * @return {this} This Game Object. + */ + setAcceleration: function (x, y) + { + this.accel.x = x; + this.accel.y = y; + + return this; + } + +}; + +module.exports = Acceleration; + + +/***/ }), +/* 1324 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Body Scale component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.BodyScale + * @since 3.0.0 + */ +var BodyScale = { + + /** + * Sets the size of the physics body. + * + * @method Phaser.Physics.Impact.Components.BodyScale#setBodySize + * @since 3.0.0 + * + * @param {number} width - The width of the body in pixels. + * @param {number} [height=width] - The height of the body in pixels. + * + * @return {this} This Game Object. + */ + setBodySize: function (width, height) + { + if (height === undefined) { height = width; } + + this.body.size.x = Math.round(width); + this.body.size.y = Math.round(height); + + return this; + }, + + /** + * Sets the scale of the physics body. + * + * @method Phaser.Physics.Impact.Components.BodyScale#setBodyScale + * @since 3.0.0 + * + * @param {number} scaleX - The horizontal scale of the body. + * @param {number} [scaleY] - The vertical scale of the body. If not given, will use the horizontal scale value. + * + * @return {this} This Game Object. + */ + setBodyScale: function (scaleX, scaleY) + { + if (scaleY === undefined) { scaleY = scaleX; } + + var gameObject = this.body.gameObject; + + if (gameObject) + { + gameObject.setScale(scaleX, scaleY); + + return this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); + } + else + { + return this.setBodySize(this.body.size.x * scaleX, this.body.size.y * scaleY); + } + } + +}; + +module.exports = BodyScale; + + +/***/ }), +/* 1325 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TYPE = __webpack_require__(113); + +/** + * The Impact Body Type component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.BodyType + * @since 3.0.0 + */ +var BodyType = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#getBodyType + * @since 3.0.0 + * + * @return {number} [description] + */ + getBodyType: function () + { + return this.body.type; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeNone + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeNone: function () + { + this.body.type = TYPE.NONE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeA: function () + { + this.body.type = TYPE.A; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeB: function () + { + this.body.type = TYPE.B; + + return this; + } + +}; + +module.exports = BodyType; + + +/***/ }), +/* 1326 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Bounce component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the impact physics bounce, or restitution, value. + * + * @method Phaser.Physics.Impact.Components.Bounce#setBounce + * @since 3.0.0 + * + * @param {number} value - A value between 0 (no rebound) and 1 (full rebound) + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setBounce: function (value) + { + this.body.bounciness = value; + + return this; + }, + + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * + * @method Phaser.Physics.Impact.Components.Bounce#setMinBounceVelocity + * @since 3.0.0 + * + * @param {number} value - The minimum allowed velocity. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setMinBounceVelocity: function (value) + { + this.body.minBounceVelocity = value; + + return this; + }, + + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + * + * @name Phaser.Physics.Impact.Components.Bounce#bounce + * @type {number} + * @since 3.0.0 + */ + bounce: { + + get: function () + { + return this.body.bounciness; + }, + + set: function (value) + { + this.body.bounciness = value; + } + + } + +}; + +module.exports = Bounce; + + +/***/ }), +/* 1327 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TYPE = __webpack_require__(113); + +/** + * The Impact Check Against component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.CheckAgainst + * @since 3.0.0 + */ +var CheckAgainst = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setAvsB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setAvsB: function () + { + this.setTypeA(); + + return this.setCheckAgainstB(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setBvsA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setBvsA: function () + { + this.setTypeB(); + + return this.setCheckAgainstA(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstNone + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstNone: function () + { + this.body.checkAgainst = TYPE.NONE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstA: function () + { + this.body.checkAgainst = TYPE.A; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstB: function () + { + this.body.checkAgainst = TYPE.B; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.CheckAgainst#checkAgainst + * @type {number} + * @since 3.0.0 + */ + checkAgainst: { + + get: function () + { + return this.body.checkAgainst; + }, + + set: function (value) + { + this.body.checkAgainst = value; + } + + } + +}; + +module.exports = CheckAgainst; + + +/***/ }), +/* 1328 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var COLLIDES = __webpack_require__(112); + +/** + * @callback CollideCallback + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {Phaser.Physics.Impact.Body} other - [description] + * @param {string} axis - [description] + */ + +/** + * The Impact Collides component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Collides + * @since 3.0.0 + */ +var Collides = { + + _collideCallback: null, + _callbackScope: null, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setCollideCallback + * @since 3.0.0 + * + * @param {CollideCallback} callback - [description] + * @param {*} scope - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollideCallback: function (callback, scope) + { + this._collideCallback = callback; + + if (scope) + { + this._callbackScope = scope; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setCollidesNever + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollidesNever: function () + { + this.body.collides = COLLIDES.NEVER; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setLiteCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setLiteCollision: function () + { + this.body.collides = COLLIDES.LITE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setPassiveCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setPassiveCollision: function () + { + this.body.collides = COLLIDES.PASSIVE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setActiveCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setActiveCollision: function () + { + this.body.collides = COLLIDES.ACTIVE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setFixedCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFixedCollision: function () + { + this.body.collides = COLLIDES.FIXED; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Collides#collides + * @type {number} + * @since 3.0.0 + */ + collides: { + + get: function () + { + return this.body.collides; + }, + + set: function (value) + { + this.body.collides = value; + } + + } + +}; + +module.exports = Collides; + + +/***/ }), +/* 1329 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Debug component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Debug + * @since 3.0.0 + */ +var Debug = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Debug#setDebug + * @since 3.0.0 + * + * @param {boolean} showBody - [description] + * @param {boolean} showVelocity - [description] + * @param {number} bodyColor - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDebug: function (showBody, showVelocity, bodyColor) + { + this.debugShowBody = showBody; + this.debugShowVelocity = showVelocity; + this.debugBodyColor = bodyColor; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Debug#setDebugBodyColor + * @since 3.0.0 + * + * @param {number} value - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDebugBodyColor: function (value) + { + this.body.debugBodyColor = value; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + debugShowBody: { + + get: function () + { + return this.body.debugShowBody; + }, + + set: function (value) + { + this.body.debugShowBody = value; + } + + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + debugShowVelocity: { + + get: function () + { + return this.body.debugShowVelocity; + }, + + set: function (value) + { + this.body.debugShowVelocity = value; + } + + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugBodyColor + * @type {number} + * @since 3.0.0 + */ + debugBodyColor: { + + get: function () + { + return this.body.debugBodyColor; + }, + + set: function (value) + { + this.body.debugBodyColor = value; + } + + } + +}; + +module.exports = Debug; + + +/***/ }), +/* 1330 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Friction component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFrictionX + * @since 3.0.0 + * + * @param {number} x - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionX: function (x) + { + this.friction.x = x; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFrictionY + * @since 3.0.0 + * + * @param {number} y - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionY: function (y) + { + this.friction.y = y; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFriction: function (x, y) + { + this.friction.x = x; + this.friction.y = y; + + return this; + } + +}; + +module.exports = Friction; + + +/***/ }), +/* 1331 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Gravity component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Gravity#setGravity + * @since 3.0.0 + * + * @param {number} value - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setGravity: function (value) + { + this.body.gravityFactor = value; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Gravity#gravity + * @type {number} + * @since 3.0.0 + */ + gravity: { + + get: function () + { + return this.body.gravityFactor; + }, + + set: function (value) + { + this.body.gravityFactor = value; + } + + } + +}; + +module.exports = Gravity; + + +/***/ }), +/* 1332 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Offset component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Offset + * @since 3.0.0 + */ +var Offset = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Offset#setOffset + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} [width] - [description] + * @param {number} [height] - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOffset: function (x, y, width, height) + { + this.body.offset.x = x; + this.body.offset.y = y; + + if (width) + { + this.setBodySize(width, height); + } + + return this; + } + +}; + +module.exports = Offset; + + +/***/ }), +/* 1333 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Set Game Object component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.SetGameObject + * @since 3.0.0 + */ +var SetGameObject = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.SetGameObject#setGameObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - [description] + * @param {boolean} [sync=true] - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setGameObject: function (gameObject, sync) + { + if (sync === undefined) { sync = true; } + + if (gameObject) + { + this.body.gameObject = gameObject; + + if (sync) + { + this.syncGameObject(); + } + } + else + { + this.body.gameObject = null; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.SetGameObject#syncGameObject + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + syncGameObject: function () + { + var gameObject = this.body.gameObject; + + if (gameObject) + { + this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); + } + + return this; + } + +}; + +module.exports = SetGameObject; + + +/***/ }), +/* 1334 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Velocity component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the horizontal velocity of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * + * @return {this} This Game Object. + */ + setVelocityX: function (x) + { + this.vel.x = x; + + return this; + }, + + /** + * Sets the vertical velocity of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The vertical velocity value. + * + * @return {this} This Game Object. + */ + setVelocityY: function (y) + { + this.vel.y = y; + + return this; + }, + + /** + * Sets the horizontal and vertical velocities of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * @param {number} [y=x] - The vertical velocity value. If not given, defaults to the horizontal value. + * + * @return {this} This Game Object. + */ + setVelocity: function (x, y) + { + if (y === undefined) { y = x; } + + this.vel.x = x; + this.vel.y = y; + + return this; + }, + + /** + * Sets the maximum velocity this body can travel at. + * + * @method Phaser.Physics.Impact.Components.Velocity#setMaxVelocity + * @since 3.0.0 + * + * @param {number} x - The maximum allowed horizontal velocity. + * @param {number} [y=x] - The maximum allowed vertical velocity. If not given, defaults to the horizontal value. + * + * @return {this} This Game Object. + */ + setMaxVelocity: function (x, y) + { + if (y === undefined) { y = x; } + + this.maxVel.x = x; + this.maxVel.y = y; + + return this; + } + +}; + +module.exports = Velocity; + + +/***/ }), +/* 1335 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Factory = __webpack_require__(498); +var GetFastValue = __webpack_require__(1); +var Merge = __webpack_require__(88); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); +var World = __webpack_require__(502); + +/** + * @classdesc + * [description] + * + * @class ImpactPhysics + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - [description] + */ +var ImpactPhysics = new Class({ + + initialize: + + function ImpactPhysics (scene) + { + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#config + * @type {object} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#add + * @type {Phaser.Physics.Impact.Factory} + * @since 3.0.0 + */ + this.add; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Impact.ImpactPhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Impact.ImpactPhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#getConfig + * @since 3.0.0 + * + * @return {object} [description] + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'impact', {}), + GetFastValue(gameConfig, 'impact', {}) + ); + + return config; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#pause + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} The Impact World object. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} The Impact World object. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Impact.ImpactPhysics#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.add.destroy(); + this.world.destroy(); + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Impact.ImpactPhysics#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('ImpactPhysics', ImpactPhysics, 'impactPhysics'); + +module.exports = ImpactPhysics; + + +/***/ }), +/* 1336 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var COLLIDES = __webpack_require__(112); +var Events = __webpack_require__(231); +var SeparateX = __webpack_require__(1337); +var SeparateY = __webpack_require__(1338); + +/** + * Impact Physics Solver + * + * @function Phaser.Physics.Impact.Solver + * @fires Phaser.Physics.Impact.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - The Impact simulation to run the solver in. + * @param {Phaser.Physics.Impact.Body} bodyA - The first body in the collision. + * @param {Phaser.Physics.Impact.Body} bodyB - The second body in the collision. + */ +var Solver = function (world, bodyA, bodyB) +{ + var weak = null; + + if (bodyA.collides === COLLIDES.LITE || bodyB.collides === COLLIDES.FIXED) + { + weak = bodyA; + } + else if (bodyB.collides === COLLIDES.LITE || bodyA.collides === COLLIDES.FIXED) + { + weak = bodyB; + } + + if (bodyA.last.x + bodyA.size.x > bodyB.last.x && bodyA.last.x < bodyB.last.x + bodyB.size.x) + { + if (bodyA.last.y < bodyB.last.y) + { + SeparateY(world, bodyA, bodyB, weak); + } + else + { + SeparateY(world, bodyB, bodyA, weak); + } + + bodyA.collideWith(bodyB, 'y'); + bodyB.collideWith(bodyA, 'y'); + + world.emit(Events.COLLIDE, bodyA, bodyB, 'y'); + } + else if (bodyA.last.y + bodyA.size.y > bodyB.last.y && bodyA.last.y < bodyB.last.y + bodyB.size.y) + { + if (bodyA.last.x < bodyB.last.x) + { + SeparateX(world, bodyA, bodyB, weak); + } + else + { + SeparateX(world, bodyB, bodyA, weak); + } + + bodyA.collideWith(bodyB, 'x'); + bodyB.collideWith(bodyA, 'x'); + + world.emit(Events.COLLIDE, bodyA, bodyB, 'x'); + } +}; + +module.exports = Solver; + + +/***/ }), +/* 1337 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * [description] + * + * @function Phaser.Physics.Impact.SeparateX + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {Phaser.Physics.Impact.Body} left - [description] + * @param {Phaser.Physics.Impact.Body} right - [description] + * @param {Phaser.Physics.Impact.Body} [weak] - [description] + */ +var SeparateX = function (world, left, right, weak) +{ + var nudge = left.pos.x + left.size.x - right.pos.x; + + // We have a weak entity, so just move this one + if (weak) + { + var strong = (left === weak) ? right : left; + + weak.vel.x = -weak.vel.x * weak.bounciness + strong.vel.x; + + var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, weak === left ? -nudge : nudge, 0, weak.size.x, weak.size.y); + + weak.pos.x = resWeak.pos.x; + } + else + { + var v2 = (left.vel.x - right.vel.x) / 2; + + left.vel.x = -v2; + right.vel.x = v2; + + var resLeft = world.collisionMap.trace(left.pos.x, left.pos.y, -nudge / 2, 0, left.size.x, left.size.y); + + left.pos.x = Math.floor(resLeft.pos.x); + + var resRight = world.collisionMap.trace(right.pos.x, right.pos.y, nudge / 2, 0, right.size.x, right.size.y); + + right.pos.x = Math.ceil(resRight.pos.x); + } +}; + +module.exports = SeparateX; + + +/***/ }), +/* 1338 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * [description] + * + * @function Phaser.Physics.Impact.SeparateY + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {Phaser.Physics.Impact.Body} top - [description] + * @param {Phaser.Physics.Impact.Body} bottom - [description] + * @param {Phaser.Physics.Impact.Body} [weak] - [description] + */ +var SeparateY = function (world, top, bottom, weak) +{ + var nudge = (top.pos.y + top.size.y - bottom.pos.y); + var nudgeX; + var resTop; + + if (weak) + { + var strong = (top === weak) ? bottom : top; + + weak.vel.y = -weak.vel.y * weak.bounciness + strong.vel.y; + + // Riding on a platform? + nudgeX = 0; + + if (weak === top && Math.abs(weak.vel.y - strong.vel.y) < weak.minBounceVelocity) + { + weak.standing = true; + nudgeX = strong.vel.x * world.delta; + } + + var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, nudgeX, weak === top ? -nudge : nudge, weak.size.x, weak.size.y); + + weak.pos.y = resWeak.pos.y; + weak.pos.x = resWeak.pos.x; + } + else if (world.gravity && (bottom.standing || top.vel.y > 0)) + { + resTop = world.collisionMap.trace(top.pos.x, top.pos.y, 0, -(top.pos.y + top.size.y - bottom.pos.y), top.size.x, top.size.y); + + top.pos.y = resTop.pos.y; + + if (top.bounciness > 0 && top.vel.y > top.minBounceVelocity) + { + top.vel.y *= -top.bounciness; + } + else + { + top.standing = true; + top.vel.y = 0; + } + } + else + { + var v2 = (top.vel.y - bottom.vel.y) / 2; + + top.vel.y = -v2; + bottom.vel.y = v2; + + nudgeX = bottom.vel.x * world.delta; + + resTop = world.collisionMap.trace(top.pos.x, top.pos.y, nudgeX, -nudge / 2, top.size.x, top.size.y); + + top.pos.y = resTop.pos.y; + + var resBottom = world.collisionMap.trace(bottom.pos.x, bottom.pos.y, 0, nudge / 2, bottom.size.x, bottom.size.y); + + bottom.pos.y = resBottom.pos.y; + } +}; + +module.exports = SeparateY; + + +/***/ }), +/* 1339 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter + */ + +module.exports = { + + BodyBounds: __webpack_require__(503), + Factory: __webpack_require__(504), + Image: __webpack_require__(506), + Matter: __webpack_require__(239), + MatterPhysics: __webpack_require__(1371), + PolyDecomp: __webpack_require__(505), + Sprite: __webpack_require__(507), + TileBody: __webpack_require__(238), + PhysicsEditorParser: __webpack_require__(235), + PhysicsJSONParser: __webpack_require__(236), + World: __webpack_require__(511) + +}; + + +/***/ }), +/* 1340 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Components = __webpack_require__(147); +var GetFastValue = __webpack_require__(1); +var Vector2 = __webpack_require__(3); + +/** + * Internal function to check if the object has a getter or setter. + * + * @function hasGetterOrSetter + * @private + * + * @param {object} def - The object to check. + * + * @return {boolean} True if it has a getter or setter, otherwise false. + */ +function hasGetterOrSetter (def) +{ + return (!!def.get && typeof def.get === 'function') || (!!def.set && typeof def.set === 'function'); +} + +/** + * A Matter Game Object is a generic object that allows you to combine any Phaser Game Object, + * including those you have extended or created yourself, with all of the Matter Components. + * + * This enables you to use component methods such as `setVelocity` or `isSensor` directly from + * this Game Object. + * + * @function Phaser.Physics.Matter.MatterGameObject + * @since 3.3.0 + * + * @param {Phaser.Physics.Matter.World} world - The Matter world to add the body to. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will have the Matter body applied to it. + * @param {(Phaser.Types.Physics.Matter.MatterBodyConfig|MatterJS.Body)} [options] - A Matter Body configuration object, or an instance of a Matter Body. + * @param {boolean} [addToWorld=true] - Should the newly created body be immediately added to the World? + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was created with the Matter body. + */ +var MatterGameObject = function (world, gameObject, options, addToWorld) +{ + if (options === undefined) { options = {}; } + if (addToWorld === undefined) { addToWorld = true; } + + var x = gameObject.x; + var y = gameObject.y; + + // Temp body pos to avoid body null checks + gameObject.body = { + temp: true, + position: { + x: x, + y: y + } + }; + + var mixins = [ + Components.Bounce, + Components.Collision, + Components.Force, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.SetBody, + Components.Sleep, + Components.Static, + Components.Transform, + Components.Velocity + ]; + + // First let's inject all of the components into the Game Object + mixins.forEach(function (mixin) + { + for (var key in mixin) + { + if (hasGetterOrSetter(mixin[key])) + { + Object.defineProperty(gameObject, key, { + get: mixin[key].get, + set: mixin[key].set + }); + } + else + { + Object.defineProperty(gameObject, key, {value: mixin[key]}); + } + } + + }); + + gameObject.world = world; + + gameObject._tempVec2 = new Vector2(x, y); + + if (options.hasOwnProperty('type') && options.type === 'body') + { + gameObject.setExistingBody(options, addToWorld); + } + else + { + var shape = GetFastValue(options, 'shape', null); + + if (!shape) + { + shape = 'rectangle'; + } + + options.addToWorld = addToWorld; + + gameObject.setBody(shape, options); + } + + return gameObject; +}; + +module.exports = MatterGameObject; + + +/***/ }), +/* 1341 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A component to set restitution on objects. + * + * @namespace Phaser.Physics.Matter.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the restitution on the physics object. + * + * @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 {Phaser.GameObjects.GameObject} This Game Object. + */ + setBounce: function (value) + { + this.body.restitution = value; + + return this; + } + +}; + +module.exports = Bounce; + + +/***/ }), +/* 1342 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Contains methods for changing the collision filter of a Matter Body. Should be used as a mixin and not called directly. + * + * @namespace Phaser.Physics.Matter.Components.Collision + * @since 3.0.0 + */ +var Collision = { + + /** + * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. + * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * + * @method Phaser.Physics.Matter.Components.Collision#setCollisionCategory + * @since 3.0.0 + * + * @param {number} value - Unique category bitfield. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollisionCategory: function (value) + { + this.body.collisionFilter.category = value; + + return this; + }, + + /** + * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, + * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, + * they will never collide. + * + * @method Phaser.Physics.Matter.Components.Collision#setCollisionGroup + * @since 3.0.0 + * + * @param {number} value - Unique group index. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollisionGroup: function (value) + { + this.body.collisionFilter.group = value; + + return this; + }, + + /** + * 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 {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollidesWith: function (categories) + { + var flags = 0; + + if (!Array.isArray(categories)) + { + flags = categories; + } + else + { + for (var i = 0; i < categories.length; i++) + { + flags |= categories[i]; + } + } + + this.body.collisionFilter.mask = flags; + + return this; + }, + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollide + * @since 3.22.0 + * + * @param {function} callback - The callback to invoke when this body starts colliding with another. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollide: function (callback) + { + this.body.onCollideCallback = callback; + + return this; + }, + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollideEnd + * @since 3.22.0 + * + * @param {function} callback - The callback to invoke when this body stops colliding with another. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollideEnd: function (callback) + { + this.body.onCollideEndCallback = callback; + + return this; + }, + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollideActive + * @since 3.22.0 + * + * @param {function} callback - The callback to invoke for the duration of this body colliding with another. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollideActive: function (callback) + { + this.body.onCollideActiveCallback = callback; + + return this; + }, + + /** + * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollideWith + * @since 3.22.0 + * + * @param {(MatterJS.Body|MatterJS.Body[])} body - The body, or an array of bodies, to test for collisions with. + * @param {function} callback - The callback to invoke when this body collides with the given body or bodies. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollideWith: function (body, callback) + { + if (!Array.isArray(body)) + { + body = [ body ]; + } + + for (var i = 0; i < body.length; i++) + { + var src = (body[i].hasOwnProperty('body')) ? body[i].body : body[i]; + + this.body.setOnCollideWith(src, callback); + } + + return this; + } + +}; + +module.exports = Collision; + + +/***/ }), +/* 1343 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(25); + +/** + * A component to apply force to Matter.js bodies. + * + * @namespace Phaser.Physics.Matter.Components.Force + * @since 3.0.0 + */ +var Force = { + + // force = vec2 / point + + /** + * Applies a force to a body. + * + * @method Phaser.Physics.Matter.Components.Force#applyForce + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} force - A Vector that specifies the force to apply. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + applyForce: function (force) + { + this._tempVec2.set(this.body.position.x, this.body.position.y); + + Body.applyForce(this.body, this._tempVec2, force); + + return this; + }, + + /** + * Applies a force to a body from a given position. + * + * @method Phaser.Physics.Matter.Components.Force#applyForceFrom + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} position - The position in which the force comes from. + * @param {Phaser.Math.Vector2} force - A Vector that specifies the force to apply. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + applyForceFrom: function (position, force) + { + Body.applyForce(this.body, position, force); + + return this; + }, + + /** + * Apply thrust to the forward position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrust + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrust: function (speed) + { + var angle = this.body.angle; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + }, + + /** + * Apply thrust to the left position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrustLeft + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrustLeft: function (speed) + { + var angle = this.body.angle - Math.PI / 2; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + }, + + /** + * Apply thrust to the right position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrustRight + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrustRight: function (speed) + { + var angle = this.body.angle + Math.PI / 2; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + }, + + /** + * Apply thrust to the back position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrustBack + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrustBack: function (speed) + { + var angle = this.body.angle - Math.PI; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + } + +}; + +module.exports = Force; + + +/***/ }), +/* 1344 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Contains methods for changing the friction of a Game Object's Matter Body. Should be used a mixin, not called directly. + * + * @namespace Phaser.Physics.Matter.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * Sets new friction values for this Game Object's Matter Body. + * + * @method Phaser.Physics.Matter.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} value - The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. + * @param {number} [air] - If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. + * @param {number} [fstatic] - If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFriction: function (value, air, fstatic) + { + this.body.friction = value; + + if (air !== undefined) + { + this.body.frictionAir = air; + } + + if (fstatic !== undefined) + { + this.body.frictionStatic = fstatic; + } + + return this; + }, + + /** + * Sets a new air resistance for this Game Object's Matter Body. + * A value of 0 means the Body will never slow as it moves through space. + * The higher the value, the faster a Body slows when moving through space. + * + * @method Phaser.Physics.Matter.Components.Friction#setFrictionAir + * @since 3.0.0 + * + * @param {number} value - The new air resistance for the Body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionAir: function (value) + { + this.body.frictionAir = value; + + return this; + }, + + /** + * Sets a new static friction for this Game Object's Matter Body. + * A value of 0 means the Body will never "stick" when it is nearly stationary. + * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. + * + * @method Phaser.Physics.Matter.Components.Friction#setFrictionStatic + * @since 3.0.0 + * + * @param {number} value - The new static friction for the Body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionStatic: function (value) + { + this.body.frictionStatic = value; + + return this; + } + +}; + +module.exports = Friction; + + +/***/ }), +/* 1345 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A component to manipulate world gravity for Matter.js bodies. + * + * @namespace Phaser.Physics.Matter.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * A togglable function for ignoring world gravity in real-time on the current body. + * + * @method Phaser.Physics.Matter.Components.Gravity#setIgnoreGravity + * @since 3.0.0 + * + * @param {boolean} value - Set to true to ignore the effect of world gravity, or false to not ignore it. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setIgnoreGravity: function (value) + { + this.body.ignoreGravity = value; + + return this; + } + +}; + +module.exports = Gravity; + + +/***/ }), +/* 1346 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(25); +var Vector2 = __webpack_require__(3); + +/** + * Allows accessing the mass, density, and center of mass of a Matter-enabled Game Object. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.Mass + * @since 3.0.0 + */ +var Mass = { + + /** + * Sets the mass of the Game Object's Matter Body. + * + * @method Phaser.Physics.Matter.Components.Mass#setMass + * @since 3.0.0 + * + * @param {number} value - The new mass of the body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setMass: function (value) + { + Body.setMass(this.body, value); + + return this; + }, + + /** + * Sets density of the body. + * + * @method Phaser.Physics.Matter.Components.Mass#setDensity + * @since 3.0.0 + * + * @param {number} value - The new density of the body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDensity: function (value) + { + Body.setDensity(this.body, value); + + return this; + }, + + /** + * The body's center of mass. + * + * Calling this creates a new `Vector2 each time to avoid mutation. + * + * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. + * + * @name Phaser.Physics.Matter.Components.Mass#centerOfMass + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.10.0 + * + * @return {Phaser.Math.Vector2} The center of mass. + */ + centerOfMass: { + + get: function () + { + return new Vector2(this.body.centerOfMass.x, this.body.centerOfMass.y); + } + } + +}; + +module.exports = Mass; + + +/***/ }), +/* 1347 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(25); + +/** + * Provides methods used for getting and setting the static state of a physics body. + * + * @namespace Phaser.Physics.Matter.Components.Static + * @since 3.0.0 + */ +var Static = { + + /** + * Changes the physics body to be either static `true` or dynamic `false`. + * + * @method Phaser.Physics.Matter.Components.Static#setStatic + * @since 3.0.0 + * + * @param {boolean} value - `true` to set the body as being static, or `false` to make it dynamic. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setStatic: function (value) + { + Body.setStatic(this.body, value); + + return this; + }, + + /** + * Returns `true` if the body is static, otherwise `false` for a dynamic body. + * + * @method Phaser.Physics.Matter.Components.Static#isStatic + * @since 3.0.0 + * + * @return {boolean} `true` if the body is static, otherwise `false`. + */ + isStatic: function () + { + return this.body.isStatic; + } + +}; + +module.exports = Static; + + +/***/ }), +/* 1348 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Enables a Matter-enabled Game Object to be a sensor. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.Sensor + * @since 3.0.0 + */ +var Sensor = { + + /** + * Set the body belonging to this Game Object to be a sensor. + * Sensors trigger collision events, but don't react with colliding body physically. + * + * @method Phaser.Physics.Matter.Components.Sensor#setSensor + * @since 3.0.0 + * + * @param {boolean} value - `true` to set the body as a sensor, or `false` to disable it. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setSensor: function (value) + { + this.body.isSensor = value; + + return this; + }, + + /** + * Is the body belonging to this Game Object a sensor or not? + * + * @method Phaser.Physics.Matter.Components.Sensor#isSensor + * @since 3.0.0 + * + * @return {boolean} `true` if the body is a sensor, otherwise `false`. + */ + isSensor: function () + { + return this.body.isSensor; + } + +}; + +module.exports = Sensor; + + +/***/ }), +/* 1349 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = __webpack_require__(42); +var Body = __webpack_require__(25); +var FuzzyEquals = __webpack_require__(126); +var GetFastValue = __webpack_require__(1); +var PhysicsEditorParser = __webpack_require__(235); +var PhysicsJSONParser = __webpack_require__(236); +var Vertices = __webpack_require__(31); + +/** + * Enables a Matter-enabled Game Object to set its Body. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.SetBody + * @since 3.0.0 + */ +var SetBody = { + + /** + * Set the body on a Game Object to a rectangle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setRectangle + * @since 3.0.0 + * + * @param {number} width - Width of the rectangle. + * @param {number} height - Height of the rectangle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setRectangle: function (width, height, options) + { + return this.setBody({ type: 'rectangle', width: width, height: height }, options); + }, + + /** + * Set the body on a Game Object to a circle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the circle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCircle: function (radius, options) + { + return this.setBody({ type: 'circle', radius: radius }, options); + }, + + /** + * Set the body on the Game Object to a polygon shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setPolygon + * @since 3.0.0 + * + * @param {number} sides - The number of sides the polygon will have. + * @param {number} radius - The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setPolygon: function (radius, sides, options) + { + return this.setBody({ type: 'polygon', sides: sides, radius: radius }, options); + }, + + /** + * Set the body on the Game Object to a trapezoid shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setTrapezoid + * @since 3.0.0 + * + * @param {number} width - The width of the trapezoid Body. + * @param {number} height - The height of the trapezoid Body. + * @param {number} slope - The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTrapezoid: function (width, height, slope, options) + { + return this.setBody({ type: 'trapezoid', width: width, height: height, slope: slope }, options); + }, + + /** + * Set this Game Object to use the given existing Matter Body. + * + * The body is first removed from the world before being added to this Game Object. + * + * @method Phaser.Physics.Matter.Components.SetBody#setExistingBody + * @since 3.0.0 + * + * @param {MatterJS.BodyType} body - The Body this Game Object should use. + * @param {boolean} [addToWorld=true] - Should the body be immediately added to the World? + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setExistingBody: function (body, addToWorld) + { + if (addToWorld === undefined) { addToWorld = true; } + + if (this.body) + { + this.world.remove(this.body, true); + } + + this.body = body; + + for (var i = 0; i < body.parts.length; i++) + { + body.parts[i].gameObject = this; + } + + var _this = this; + + body.destroy = function destroy () + { + _this.world.remove(_this.body, true); + _this.body.gameObject = null; + }; + + if (addToWorld) + { + if (this.world.has(body)) + { + // Because it could be part of another Composite + this.world.remove(body, true); + } + + this.world.add(body); + } + + if (this._originComponent) + { + var rx = body.render.sprite.xOffset; + var ry = body.render.sprite.yOffset; + + var comx = body.centerOfMass.x; + var comy = body.centerOfMass.y; + + if (FuzzyEquals(comx, 0.5) && FuzzyEquals(comy, 0.5)) + { + this.setOrigin(rx + 0.5, ry + 0.5); + } + else + { + var cx = body.centerOffset.x; + var cy = body.centerOffset.y; + + this.setOrigin(rx + (cx / this.displayWidth), ry + (cy / this.displayHeight)); + } + } + + return this; + }, + + /** + * Set this Game Object to create and use a new Body based on the configuration object given. + * + * Calling this method resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if 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 {Phaser.GameObjects.GameObject} This Game Object. + */ + setBody: function (config, options) + { + if (!config) + { + return this; + } + + var body; + + // Allow them to do: shape: 'circle' instead of shape: { type: 'circle' } + if (typeof config === 'string') + { + // Using defaults + config = { type: config }; + } + + var shapeType = GetFastValue(config, 'type', 'rectangle'); + var bodyX = GetFastValue(config, 'x', this._tempVec2.x); + var bodyY = GetFastValue(config, 'y', this._tempVec2.y); + var bodyWidth = GetFastValue(config, 'width', this.width); + var bodyHeight = GetFastValue(config, 'height', this.height); + + switch (shapeType) + { + case 'rectangle': + body = Bodies.rectangle(bodyX, bodyY, bodyWidth, bodyHeight, options); + break; + + case 'circle': + var radius = GetFastValue(config, 'radius', Math.max(bodyWidth, bodyHeight) / 2); + var maxSides = GetFastValue(config, 'maxSides', 25); + body = Bodies.circle(bodyX, bodyY, radius, options, maxSides); + break; + + case 'trapezoid': + var slope = GetFastValue(config, 'slope', 0.5); + body = Bodies.trapezoid(bodyX, bodyY, bodyWidth, bodyHeight, slope, options); + break; + + case 'polygon': + var sides = GetFastValue(config, 'sides', 5); + var pRadius = GetFastValue(config, 'radius', Math.max(bodyWidth, bodyHeight) / 2); + body = Bodies.polygon(bodyX, bodyY, sides, pRadius, options); + break; + + case 'fromVertices': + case 'fromVerts': + + var verts = GetFastValue(config, 'verts', null); + + if (verts) + { + // Has the verts array come from Vertices.fromPath, or is it raw? + if (typeof verts === 'string') + { + verts = Vertices.fromPath(verts); + } + + if (this.body && !this.body.hasOwnProperty('temp')) + { + Body.setVertices(this.body, verts); + + body = this.body; + } + else + { + var flagInternal = GetFastValue(config, 'flagInternal', false); + var removeCollinear = GetFastValue(config, 'removeCollinear', 0.01); + var minimumArea = GetFastValue(config, 'minimumArea', 10); + + body = Bodies.fromVertices(bodyX, bodyY, verts, options, flagInternal, removeCollinear, minimumArea); + } + } + + break; + + case 'fromPhysicsEditor': + body = PhysicsEditorParser.parseBody(bodyX, bodyY, config, options); + break; + + case 'fromPhysicsTracer': + body = PhysicsJSONParser.parseBody(bodyX, bodyY, config, options); + break; + } + + if (body) + { + this.setExistingBody(body, config.addToWorld); + } + + return this; + } + +}; + +module.exports = SetBody; + + +/***/ }), +/* 1350 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Events = __webpack_require__(237); +var Sleeping = __webpack_require__(95); +var MatterEvents = __webpack_require__(96); + +/** + * Enables a Matter-enabled Game Object to be able to go to sleep. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.Sleep + * @since 3.0.0 + */ +var Sleep = { + + /** + * Sets this Body to sleep. + * + * @method Phaser.Physics.Matter.Components.Sleep#setToSleep + * @since 3.22.0 + * + * @return {this} This Game Object. + */ + setToSleep: function () + { + Sleeping.set(this.body, true); + }, + + /** + * Wakes this Body if asleep. + * + * @method Phaser.Physics.Matter.Components.Sleep#setAwake + * @since 3.22.0 + * + * @return {this} This Game Object. + */ + setAwake: function () + { + Sleeping.set(this.body, false); + }, + + /** + * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepThreshold + * @since 3.0.0 + * + * @param {number} [value=60] - A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. + * + * @return {this} This Game Object. + */ + setSleepThreshold: function (value) + { + if (value === undefined) { value = 60; } + + this.body.sleepThreshold = value; + + return this; + }, + + /** + * Enable sleep and wake events for this body. + * + * By default when a body goes to sleep, or wakes up, it will not emit any events. + * + * The events are emitted by the Matter World instance and can be listened to via + * the `SLEEP_START` and `SLEEP_END` events. + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepEvents + * @since 3.0.0 + * + * @param {boolean} start - `true` if you want the sleep start event to be emitted for this body. + * @param {boolean} end - `true` if you want the sleep end event to be emitted for this body. + * + * @return {this} This Game Object. + */ + setSleepEvents: function (start, end) + { + this.setSleepStartEvent(start); + this.setSleepEndEvent(end); + + return this; + }, + + /** + * Enables or disables the Sleep Start event for this body. + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepStartEvent + * @since 3.0.0 + * + * @param {boolean} value - `true` to enable the sleep event, or `false` to disable it. + * + * @return {this} This Game Object. + */ + setSleepStartEvent: function (value) + { + if (value) + { + var world = this.world; + + MatterEvents.on(this.body, 'sleepStart', function (event) + { + world.emit(Events.SLEEP_START, event, this); + }); + } + else + { + MatterEvents.off(this.body, 'sleepStart'); + } + + return this; + }, + + /** + * Enables or disables the Sleep End event for this body. + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepEndEvent + * @since 3.0.0 + * + * @param {boolean} value - `true` to enable the sleep event, or `false` to disable it. + * + * @return {this} This Game Object. + */ + setSleepEndEvent: function (value) + { + if (value) + { + var world = this.world; + + MatterEvents.on(this.body, 'sleepEnd', function (event) + { + world.emit(Events.SLEEP_END, event, this); + }); + } + else + { + MatterEvents.off(this.body, 'sleepEnd'); + } + + return this; + } + +}; + +module.exports = Sleep; + + +/***/ }), +/* 1351 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.AfterAddEvent + * + * @property {any[]} object - An array of the object(s) that have been added. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics After Add Event. + * + * This event is dispatched by a Matter Physics World instance at the end of the process when a new Body + * or Constraint has just been added to the world. + * + * Listen to it from a Scene using: `this.matter.world.on('afteradd', listener)`. + * + * @event Phaser.Physics.Matter.Events#AFTER_ADD + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.AfterAddEvent} event - The Add Event object. + */ +module.exports = 'afteradd'; + + +/***/ }), +/* 1352 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.AfterRemoveEvent + * + * @property {any[]} object - An array of the object(s) that were removed. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics After Remove Event. + * + * This event is dispatched by a Matter Physics World instance at the end of the process when a + * Body or Constraint was removed from the world. + * + * Listen to it from a Scene using: `this.matter.world.on('afterremove', listener)`. + * + * @event Phaser.Physics.Matter.Events#AFTER_REMOVE + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.AfterRemoveEvent} event - The Remove Event object. + */ +module.exports = 'afterremove'; + + +/***/ }), +/* 1353 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.AfterUpdateEvent + * + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics After Update Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated and all collision events have resolved. + * + * Listen to it from a Scene using: `this.matter.world.on('afterupdate', listener)`. + * + * @event Phaser.Physics.Matter.Events#AFTER_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.AfterUpdateEvent} event - The Update Event object. + */ +module.exports = 'afterupdate'; + + +/***/ }), +/* 1354 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.BeforeAddEvent + * + * @property {any[]} object - An array of the object(s) to be added. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Before Add Event. + * + * This event is dispatched by a Matter Physics World instance at the start of the process when a new Body + * or Constraint is being added to the world. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeadd', listener)`. + * + * @event Phaser.Physics.Matter.Events#BEFORE_ADD + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.BeforeAddEvent} event - The Add Event object. + */ +module.exports = 'beforeadd'; + + +/***/ }), +/* 1355 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.BeforeRemoveEvent + * + * @property {any[]} object - An array of the object(s) to be removed. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Before Remove Event. + * + * This event is dispatched by a Matter Physics World instance at the start of the process when a + * Body or Constraint is being removed from the world. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeremove', listener)`. + * + * @event Phaser.Physics.Matter.Events#BEFORE_REMOVE + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.BeforeRemoveEvent} event - The Remove Event object. + */ +module.exports = 'beforeremove'; + + +/***/ }), +/* 1356 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.BeforeUpdateEvent + * + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Before Update Event. + * + * This event is dispatched by a Matter Physics World instance right before all the collision processing takes place. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeupdate', listener)`. + * + * @event Phaser.Physics.Matter.Events#BEFORE_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.BeforeUpdateEvent} event - The Update Event object. + */ +module.exports = 'beforeupdate'; + + +/***/ }), +/* 1357 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.CollisionActiveEvent + * + * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Collision Active Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that are colliding in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionactive', listener)`. + * + * @event Phaser.Physics.Matter.Events#COLLISION_ACTIVE + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.CollisionActiveEvent} event - The Collision Event object. + * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + */ +module.exports = 'collisionactive'; + + +/***/ }), +/* 1358 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.CollisionEndEvent + * + * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Collision End Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that have finished colliding in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionend', listener)`. + * + * @event Phaser.Physics.Matter.Events#COLLISION_END + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.CollisionEndEvent} event - The Collision Event object. + * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + */ +module.exports = 'collisionend'; + + +/***/ }), +/* 1359 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.CollisionStartEvent + * + * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Collision Start Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that have started to collide in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionstart', listener)`. + * + * @event Phaser.Physics.Matter.Events#COLLISION_START + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.CollisionStartEvent} event - The Collision Event object. + * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + */ +module.exports = 'collisionstart'; + + +/***/ }), +/* 1360 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics Drag End Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * stops dragging a body. + * + * Listen to it from a Scene using: `this.matter.world.on('dragend', listener)`. + * + * @event Phaser.Physics.Matter.Events#DRAG_END + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Body that has stopped being dragged. This is a Matter Body, not a Phaser Game Object. + * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that was dragging the body. + */ +module.exports = 'dragend'; + + +/***/ }), +/* 1361 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics Drag Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * is actively dragging a body. It is emitted each time the pointer moves. + * + * Listen to it from a Scene using: `this.matter.world.on('drag', listener)`. + * + * @event Phaser.Physics.Matter.Events#DRAG + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Body that is being dragged. This is a Matter Body, not a Phaser Game Object. + * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. + */ +module.exports = 'drag'; + + +/***/ }), +/* 1362 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics Drag Start Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * starts dragging a body. + * + * Listen to it from a Scene using: `this.matter.world.on('dragstart', listener)`. + * + * @event Phaser.Physics.Matter.Events#DRAG_START + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Body that has started being dragged. This is a Matter Body, not a Phaser Game Object. + * @param {MatterJS.BodyType} part - The part of the body that was clicked on. + * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. + */ +module.exports = 'dragstart'; + + +/***/ }), +/* 1363 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics World Pause Event. + * + * This event is dispatched by an Matter Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.matter.world.on('pause', listener)`. + * + * @event Phaser.Physics.Matter.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; + + +/***/ }), +/* 1364 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics World Resume Event. + * + * This event is dispatched by an Matter Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.matter.world.on('resume', listener)`. + * + * @event Phaser.Physics.Matter.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; + + +/***/ }), +/* 1365 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.SleepEndEvent + * + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Sleep End Event. + * + * This event is dispatched by a Matter Physics World instance when a Body stop sleeping. + * + * Listen to it from a Scene using: `this.matter.world.on('sleepend', listener)`. + * + * @event Phaser.Physics.Matter.Events#SLEEP_END + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.SleepEndEvent} event - The Sleep Event object. + * @param {MatterJS.BodyType} body - The body that has stopped sleeping. + */ +module.exports = 'sleepend'; + + +/***/ }), +/* 1366 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.SleepStartEvent + * + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Sleep Start Event. + * + * This event is dispatched by a Matter Physics World instance when a Body goes to sleep. + * + * Listen to it from a Scene using: `this.matter.world.on('sleepstart', listener)`. + * + * @event Phaser.Physics.Matter.Events#SLEEP_START + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.SleepStartEvent} event - The Sleep Event object. + * @param {MatterJS.BodyType} body - The body that has gone to sleep. + */ +module.exports = 'sleepstart'; + + +/***/ }), +/* 1367 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(25); +var MATH_CONST = __webpack_require__(13); +var WrapAngle = __webpack_require__(165); +var WrapAngleDegrees = __webpack_require__(166); + +// global bitmask flag for GameObject.renderMask (used by Scale) +var _FLAG = 4; // 0100 + +// Transform Component + +/** + * Provides methods used for getting and setting the position, scale and rotation of a Game Object. + * + * @namespace Phaser.Physics.Matter.Components.Transform + * @since 3.0.0 + */ +var Transform = { + + /** + * The x position of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.body.position.x; + }, + + set: function (value) + { + this._tempVec2.set(value, this.y); + + Body.setPosition(this.body, this._tempVec2); + } + + }, + + /** + * The y position of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.body.position.y; + }, + + set: function (value) + { + this._tempVec2.set(this.x, value); + + Body.setPosition(this.body, this._tempVec2); + } + + }, + + /** + * The horizontal scale of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#scaleX + * @type {number} + * @since 3.0.0 + */ + scaleX: { + + get: function () + { + return this._scaleX; + }, + + set: function (value) + { + var factorX = 1 / this._scaleX; + var factorY = 1 / this._scaleY; + + this._scaleX = value; + + if (this._scaleX === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + // Reset Matter scale back to 1 (sigh) + Body.scale(this.body, factorX, factorY); + + Body.scale(this.body, value, this._scaleY); + } + + }, + + /** + * The vertical scale of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#scaleY + * @type {number} + * @since 3.0.0 + */ + scaleY: { + + get: function () + { + return this._scaleY; + }, + + set: function (value) + { + var factorX = 1 / this._scaleX; + var factorY = 1 / this._scaleY; + + this._scaleY = value; + + if (this._scaleY === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + Body.scale(this.body, factorX, factorY); + + Body.scale(this.body, this._scaleX, value); + } + + }, + + /** + * Use `angle` to set or get rotation of the physics body associated to this GameObject. + * Unlike rotation, when using set the value can be in degrees, which will be converted to radians internally. + * + * @name Phaser.Physics.Matter.Components.Transform#angle + * @type {number} + * @since 3.0.0 + */ + angle: { + + get: function () + { + return WrapAngleDegrees(this.body.angle * MATH_CONST.RAD_TO_DEG); + }, + + set: function (value) + { + // value is in degrees + this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD; + } + }, + + /** + * Use `rotation` to set or get the rotation of the physics body associated with this GameObject. + * The value when set must be in radians. + * + * @name Phaser.Physics.Matter.Components.Transform#rotation + * @type {number} + * @since 3.0.0 + */ + rotation: { + + get: function () + { + return this.body.angle; + }, + + set: function (value) + { + // value is in radians + this._rotation = WrapAngle(value); + + Body.setAngle(this.body, this._rotation); + } + }, + + /** + * Sets the position of the physics body along x and y axes. + * Both the parameters to this function are optional and if not passed any they default to 0. + * Velocity, angle, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Transform#setPosition + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal position of the body. + * @param {number} [y=x] - The vertical position of the body. + * + * @return {this} This Game Object. + */ + setPosition: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this._tempVec2.set(x, y); + + Body.setPosition(this.body, this._tempVec2); + + return this; + }, + + /** + * Immediately sets the angle of the Body. + * Angular velocity, position, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Transform#setRotation + * @since 3.0.0 + * + * @param {number} [radians=0] - The angle of the body, in radians. + * + * @return {this} This Game Object. + */ + setRotation: function (radians) + { + if (radians === undefined) { radians = 0; } + + this._rotation = WrapAngle(radians); + + Body.setAngle(this.body, radians); + + return this; + }, + + /** + * Setting fixed rotation sets the Body inertia to Infinity, which stops it + * from being able to rotate when forces are applied to it. + * + * @method Phaser.Physics.Matter.Components.Transform#setFixedRotation + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + setFixedRotation: function () + { + Body.setInertia(this.body, Infinity); + + return this; + }, + + /** + * Immediately sets the angle of the Body. + * Angular velocity, position, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Transform#setAngle + * @since 3.0.0 + * + * @param {number} [degrees=0] - The angle to set, in degrees. + * + * @return {this} This Game Object. + */ + setAngle: function (degrees) + { + if (degrees === undefined) { degrees = 0; } + + this.angle = degrees; + + Body.setAngle(this.body, this.rotation); + + return this; + }, + + /** + * Sets the scale of this Game Object. + * + * @method Phaser.Physics.Matter.Components.Transform#setScale + * @since 3.0.0 + * + * @param {number} [x=1] - The horizontal scale of this Game Object. + * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the x value. + * @param {Phaser.Math.Vector2} [point] - The point (Vector2) from which scaling will occur. + * + * @return {this} This Game Object. + */ + setScale: function (x, y, point) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + var factorX = 1 / this._scaleX; + var factorY = 1 / this._scaleY; + + this._scaleX = x; + this._scaleY = y; + + Body.scale(this.body, factorX, factorY, point); + + Body.scale(this.body, x, y, point); + + return this; + } + +}; + +module.exports = Transform; + + +/***/ }), +/* 1368 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(25); + +/** + * Contains methods for changing the velocity of a Matter Body. Should be used as a mixin and not called directly. + * + * @namespace Phaser.Physics.Matter.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the angular velocity of the body instantly. + * Position, angle, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Velocity#setAngularVelocity + * @since 3.0.0 + * + * @param {number} value - The angular velocity. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setAngularVelocity: function (value) + { + Body.setAngularVelocity(this.body, value); + + return this; + }, + + /** + * Sets the horizontal velocity of the physics body. + * + * @method Phaser.Physics.Matter.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setVelocityX: function (x) + { + this._tempVec2.set(x, this.body.velocity.y); + + Body.setVelocity(this.body, this._tempVec2); + + return this; + }, + + /** + * Sets vertical velocity of the physics body. + * + * @method Phaser.Physics.Matter.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The vertical velocity value. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setVelocityY: function (y) + { + this._tempVec2.set(this.body.velocity.x, y); + + Body.setVelocity(this.body, this._tempVec2); + + return this; + }, + + /** + * Sets both the horizontal and vertical velocity of the physics body. + * + * @method Phaser.Physics.Matter.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * @param {number} [y=x] - The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setVelocity: function (x, y) + { + this._tempVec2.set(x, y); + + Body.setVelocity(this.body, this._tempVec2); + + return this; + } + +}; + +module.exports = Velocity; + + +/***/ }), +/* 1369 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bounds = __webpack_require__(38); +var Class = __webpack_require__(0); +var Composite = __webpack_require__(68); +var Constraint = __webpack_require__(78); +var Detector = __webpack_require__(148); +var Events = __webpack_require__(237); +var InputEvents = __webpack_require__(56); +var Merge = __webpack_require__(88); +var Sleeping = __webpack_require__(95); +var Vector2 = __webpack_require__(3); +var Vertices = __webpack_require__(31); + +/** + * @classdesc + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * + * @class PointerConstraint + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene to which this Pointer Constraint belongs. + * @param {Phaser.Physics.Matter.World} world - A reference to the Matter World instance to which this Constraint belongs. + * @param {object} [options] - A Constraint configuration object. + */ +var PointerConstraint = new Class({ + + initialize: + + function PointerConstraint (scene, world, options) + { + if (options === undefined) { options = {}; } + + // Defaults + var defaults = { + label: 'Pointer Constraint', + pointA: { x: 0, y: 0 }, + pointB: { x: 0, y: 0 }, + length: 0.01, + stiffness: 0.1, + angularStiffness: 1, + collisionFilter: { + category: 0x0001, + mask: 0xFFFFFFFF, + group: 0 + } + }; + + /** + * A reference to the Scene to which this Pointer Constraint belongs. + * This is the same Scene as the Matter World instance. + * + * @name Phaser.Physics.Matter.PointerConstraint#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Matter World instance to which this Constraint belongs. + * + * @name Phaser.Physics.Matter.PointerConstraint#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Camera the Pointer was interacting with when the input + * down event was processed. + * + * @name Phaser.Physics.Matter.PointerConstraint#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.0.0 + */ + this.camera = null; + + /** + * A reference to the Input Pointer that activated this Constraint. + * This is set in the `onDown` handler. + * + * @name Phaser.Physics.Matter.PointerConstraint#pointer + * @type {Phaser.Input.Pointer} + * @default null + * @since 3.0.0 + */ + this.pointer = null; + + /** + * Is this Constraint active or not? + * + * An active constraint will be processed each update. An inactive one will be skipped. + * Use this to toggle a Pointer Constraint on and off. + * + * @name Phaser.Physics.Matter.PointerConstraint#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * The internal transformed position. + * + * @name Phaser.Physics.Matter.PointerConstraint#position + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.position = new Vector2(); + + /** + * The body that is currently being dragged, if any. + * + * @name Phaser.Physics.Matter.PointerConstraint#body + * @type {?MatterJS.BodyType} + * @since 3.16.2 + */ + this.body = null; + + /** + * The part of the body that was clicked on to start the drag. + * + * @name Phaser.Physics.Matter.PointerConstraint#part + * @type {?MatterJS.BodyType} + * @since 3.16.2 + */ + this.part = null; + + /** + * The native Matter Constraint that is used to attach to bodies. + * + * @name Phaser.Physics.Matter.PointerConstraint#constraint + * @type {MatterJS.ConstraintType} + * @since 3.0.0 + */ + this.constraint = Constraint.create(Merge(options, defaults)); + + this.world.on(Events.BEFORE_UPDATE, this.update, this); + + scene.sys.input.on(InputEvents.POINTER_DOWN, this.onDown, this); + scene.sys.input.on(InputEvents.POINTER_UP, this.onUp, this); + }, + + /** + * A Pointer has been pressed down onto the Scene. + * + * If this Constraint doesn't have an active Pointer then a hit test is set to + * run against all active bodies in the world during the _next_ call to `update`. + * If a body is found, it is bound to this constraint and the drag begins. + * + * @method Phaser.Physics.Matter.PointerConstraint#onDown + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - A reference to the Pointer that was pressed. + */ + onDown: function (pointer) + { + if (!this.pointer) + { + this.pointer = pointer; + this.camera = pointer.camera; + } + }, + + /** + * A Pointer has been released from the Scene. If it was the one this constraint was using, it's cleared. + * + * @method Phaser.Physics.Matter.PointerConstraint#onUp + * @since 3.22.0 + * + * @param {Phaser.Input.Pointer} pointer - A reference to the Pointer that was pressed. + */ + onUp: function (pointer) + { + if (pointer === this.pointer) + { + this.pointer = null; + } + }, + + /** + * Scans all active bodies in the current Matter World to see if any of them + * are hit by the Pointer. The _first one_ found to hit is set as the active contraint + * body. + * + * @method Phaser.Physics.Matter.PointerConstraint#getBody + * @fires Phaser.Physics.Matter.Events#DRAG_START + * @since 3.16.2 + * + * @return {boolean} `true` if a body was found and set, otherwise `false`. + */ + getBody: function (pointer) + { + var pos = this.position; + var constraint = this.constraint; + + this.camera.getWorldPoint(pointer.x, pointer.y, pos); + + var bodies = Composite.allBodies(this.world.localWorld); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + if (!body.ignorePointer && + Bounds.contains(body.bounds, pos) && + Detector.canCollide(body.collisionFilter, constraint.collisionFilter)) + { + if (this.hitTestBody(body, pos)) + { + this.world.emit(Events.DRAG_START, body, this.part, this); + + return true; + } + } + } + + return false; + }, + + /** + * Scans the current body to determine if a part of it was clicked on. + * If a part is found the body is set as the `constraint.bodyB` property, + * as well as the `body` property of this class. The part is also set. + * + * @method Phaser.Physics.Matter.PointerConstraint#hitTestBody + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Matter Body to check. + * @param {Phaser.Math.Vector2} position - A translated hit test position. + * + * @return {boolean} `true` if a part of the body was hit, otherwise `false`. + */ + hitTestBody: function (body, position) + { + var constraint = this.constraint; + var partsLength = body.parts.length; + + var start = (partsLength > 1) ? 1 : 0; + + for (var i = start; i < partsLength; i++) + { + var part = body.parts[i]; + + if (Vertices.contains(part.vertices, position)) + { + constraint.pointA = position; + constraint.pointB = { x: position.x - body.position.x, y: position.y - body.position.y }; + + constraint.bodyB = body; + constraint.angleB = body.angle; + + Sleeping.set(body, false); + + this.part = part; + this.body = body; + + return true; + } + } + + return false; + }, + + /** + * Internal update handler. Called in the Matter BEFORE_UPDATE step. + * + * @method Phaser.Physics.Matter.PointerConstraint#update + * @fires Phaser.Physics.Matter.Events#DRAG + * @since 3.0.0 + */ + update: function () + { + var pointer = this.pointer; + var body = this.body; + + if (!this.active || !pointer) + { + if (body) + { + this.stopDrag(); + } + + return; + } + + if (!pointer.isDown && body) + { + this.stopDrag(); + + return; + } + else if (pointer.isDown) + { + if (!body && !this.getBody(pointer)) + { + return; + } + + body = this.body; + + var pos = this.position; + var constraint = this.constraint; + + this.camera.getWorldPoint(pointer.x, pointer.y, pos); + + // Drag update + constraint.pointA.x = pos.x; + constraint.pointA.y = pos.y; + + Sleeping.set(body, false); + + this.world.emit(Events.DRAG, body, this); + } + }, + + /** + * Stops the Pointer Constraint from dragging the body any further. + * + * This is called automatically if the Pointer is released while actively + * dragging a body. Or, you can call it manually to release a body from a + * constraint without having to first release the pointer. + * + * @method Phaser.Physics.Matter.PointerConstraint#stopDrag + * @fires Phaser.Physics.Matter.Events#DRAG_END + * @since 3.16.2 + */ + stopDrag: function () + { + var body = this.body; + var constraint = this.constraint; + + constraint.bodyB = null; + constraint.pointB = null; + + this.pointer = null; + this.body = null; + this.part = null; + + if (body) + { + this.world.emit(Events.DRAG_END, body, this); + } + }, + + /** + * Destroys this Pointer Constraint instance and all of its references. + * + * @method Phaser.Physics.Matter.PointerConstraint#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.removeConstraint(this.constraint); + + this.pointer = null; + this.constraint = null; + this.body = null; + this.part = null; + + this.world.off(Events.BEFORE_UPDATE, this.update); + + this.scene.sys.input.off(InputEvents.POINTER_DOWN, this.onDown, this); + this.scene.sys.input.off(InputEvents.POINTER_UP, this.onUp, this); + } + +}); + +module.exports = PointerConstraint; + + +/***/ }), +/* 1370 */ +/***/ (function(module, exports, __webpack_require__) { + +// @if DEBUG +/** +* _Internal Class_, not generally used outside of the engine's internals. +* +*/ + +var Metrics = {}; + +module.exports = Metrics; + +var Composite = __webpack_require__(68); +var Common = __webpack_require__(19); + +(function() { + + /** + * Creates a new metrics. + * @method create + * @private + * @return {metrics} A new metrics + */ + Metrics.create = function(options) { + var defaults = { + extended: false, + narrowDetections: 0, + narrowphaseTests: 0, + narrowReuse: 0, + narrowReuseCount: 0, + midphaseTests: 0, + broadphaseTests: 0, + narrowEff: 0.0001, + midEff: 0.0001, + broadEff: 0.0001, + collisions: 0, + buckets: 0, + bodies: 0, + pairs: 0 + }; + + return Common.extend(defaults, false, options); + }; + + /** + * Resets metrics. + * @method reset + * @private + * @param {metrics} metrics + */ + Metrics.reset = function(metrics) { + if (metrics.extended) { + metrics.narrowDetections = 0; + metrics.narrowphaseTests = 0; + metrics.narrowReuse = 0; + metrics.narrowReuseCount = 0; + metrics.midphaseTests = 0; + metrics.broadphaseTests = 0; + metrics.narrowEff = 0; + metrics.midEff = 0; + metrics.broadEff = 0; + metrics.collisions = 0; + metrics.buckets = 0; + metrics.pairs = 0; + metrics.bodies = 0; + } + }; + + /** + * Updates metrics. + * @method update + * @private + * @param {metrics} metrics + * @param {engine} engine + */ + Metrics.update = function(metrics, engine) { + if (metrics.extended) { + var world = engine.world, + bodies = Composite.allBodies(world); + + metrics.collisions = metrics.narrowDetections; + metrics.pairs = engine.pairs.list.length; + metrics.bodies = bodies.length; + metrics.midEff = (metrics.narrowDetections / (metrics.midphaseTests || 1)).toFixed(2); + metrics.narrowEff = (metrics.narrowDetections / (metrics.narrowphaseTests || 1)).toFixed(2); + metrics.broadEff = (1 - (metrics.broadphaseTests / (bodies.length || 1))).toFixed(2); + metrics.narrowReuse = (metrics.narrowReuseCount / (metrics.narrowphaseTests || 1)).toFixed(2); + //var broadphase = engine.broadphase[engine.broadphase.current]; + //if (broadphase.instance) + // metrics.buckets = Common.keys(broadphase.instance.buckets).length; + } + }; + +})(); +// @endif + + +/***/ }), +/* 1371 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = __webpack_require__(97); +var Axes = __webpack_require__(146); +var Bodies = __webpack_require__(42); +var Body = __webpack_require__(25); +var BodyBounds = __webpack_require__(503); +var Bounds = __webpack_require__(38); +var Class = __webpack_require__(0); +var Composite = __webpack_require__(68); +var Composites = __webpack_require__(233); +var Constraint = __webpack_require__(78); +var Detector = __webpack_require__(148); +var DistanceBetween = __webpack_require__(54); +var Factory = __webpack_require__(504); +var GetFastValue = __webpack_require__(1); +var GetValue = __webpack_require__(5); +var Grid = __webpack_require__(242); +var MatterAttractors = __webpack_require__(1372); +var MatterCollisionEvents = __webpack_require__(1373); +var MatterLib = __webpack_require__(508); +var MatterWrap = __webpack_require__(1374); +var Merge = __webpack_require__(88); +var Pair = __webpack_require__(114); +var Pairs = __webpack_require__(243); +var Plugin = __webpack_require__(240); +var PluginCache = __webpack_require__(22); +var Query = __webpack_require__(509); +var Resolver = __webpack_require__(244); +var SAT = __webpack_require__(149); +var SceneEvents = __webpack_require__(18); +var Svg = __webpack_require__(234); +var Vector = __webpack_require__(37); +var Vertices = __webpack_require__(31); +var World = __webpack_require__(511); + +/** + * @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. + */ +var MatterPhysics = new Class({ + + initialize: + + function MatterPhysics (scene) + { + /** + * The Phaser Scene that owns this Matter Physics instance + * + * @name Phaser.Physics.Matter.MatterPhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems that belong to the Scene owning this Matter Physics instance. + * + * @name Phaser.Physics.Matter.MatterPhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The parsed Matter Configuration object. + * + * @name Phaser.Physics.Matter.MatterPhysics#config + * @type {Phaser.Types.Physics.Matter.MatterWorldConfig} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * An instance of the Matter World class. This class is responsible for the updating of the + * Matter Physics world, as well as handling debug drawing functions. + * + * @name Phaser.Physics.Matter.MatterPhysics#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world; + + /** + * An instance of the Matter Factory. This class provides lots of functions for creating a + * wide variety of physics objects and adds them automatically to the Matter World. + * + * You can use this class to cut-down on the amount of code required in your game, however, + * use of the Factory is entirely optional and should be seen as a development aid. It's + * perfectly possible to create and add components to the Matter world without using it. + * + * @name Phaser.Physics.Matter.MatterPhysics#add + * @type {Phaser.Physics.Matter.Factory} + * @since 3.0.0 + */ + this.add; + + /** + * An instance of the Body Bounds class. This class contains functions used for getting the + * world position from various points around the bounds of a physics body. + * + * @name Phaser.Physics.Matter.MatterPhysics#bodyBounds + * @type {Phaser.Physics.Matter.BodyBounds} + * @since 3.22.0 + */ + this.bodyBounds; + + // Body + + /** + * A reference to the `Matter.Body` module. + * + * 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 `Bodies` module. + * + * @name Phaser.Physics.Matter.MatterPhysics#body + * @type {MatterJS.BodyFactory} + * @since 3.18.0 + */ + this.body = Body; + + /** + * A reference to the `Matter.Composite` module. + * + * 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`. + * + * @name Phaser.Physics.Matter.MatterPhysics#composite + * @type {MatterJS.CompositeFactory} + * @since 3.22.0 + */ + this.composite = Composite; + + // Collision: + + /** + * A reference to the `Matter.Detector` module. + * + * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. + * + * @name Phaser.Physics.Matter.MatterPhysics#detector + * @type {MatterJS.DetectorFactory} + * @since 3.22.0 + */ + this.detector = Detector; + + /** + * A reference to the `Matter.Grid` module. + * + * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. + * + * @name Phaser.Physics.Matter.MatterPhysics#grid + * @type {MatterJS.GridFactory} + * @since 3.22.0 + */ + this.grid = Grid; + + /** + * A reference to the `Matter.Pair` module. + * + * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. + * + * @name Phaser.Physics.Matter.MatterPhysics#pair + * @type {MatterJS.PairFactory} + * @since 3.22.0 + */ + this.pair = Pair; + + /** + * A reference to the `Matter.Pairs` module. + * + * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. + * + * @name Phaser.Physics.Matter.MatterPhysics#pairs + * @type {MatterJS.PairsFactory} + * @since 3.22.0 + */ + this.pairs = Pairs; + + /** + * A reference to the `Matter.Query` module. + * + * The `Matter.Query` module contains methods for performing collision queries. + * + * @name Phaser.Physics.Matter.MatterPhysics#query + * @type {MatterJS.QueryFactory} + * @since 3.22.0 + */ + this.query = Query; + + /** + * A reference to the `Matter.Resolver` module. + * + * The `Matter.Resolver` module contains methods for resolving collision pairs. + * + * @name Phaser.Physics.Matter.MatterPhysics#resolver + * @type {MatterJS.ResolverFactory} + * @since 3.22.0 + */ + this.resolver = Resolver; + + /** + * A reference to the `Matter.SAT` module. + * + * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. + * + * @name Phaser.Physics.Matter.MatterPhysics#sat + * @type {MatterJS.SATFactory} + * @since 3.22.0 + */ + this.sat = SAT; + + // Constraint + + /** + * A reference to the `Matter.Constraint` module. + * + * 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. + * + * @name Phaser.Physics.Matter.MatterPhysics#constraint + * @type {MatterJS.ConstraintFactory} + * @since 3.22.0 + */ + this.constraint = Constraint; + + // Factory + + /** + * A reference to the `Matter.Bodies` module. + * + * The `Matter.Bodies` module contains factory methods for creating rigid bodies + * with commonly used body configurations (such as rectangles, circles and other polygons). + * + * @name Phaser.Physics.Matter.MatterPhysics#bodies + * @type {MatterJS.BodiesFactory} + * @since 3.18.0 + */ + this.bodies = Bodies; + + /** + * A reference to the `Matter.Composites` module. + * + * The `Matter.Composites` module contains factory methods for creating composite bodies + * with commonly used configurations (such as stacks and chains). + * + * @name Phaser.Physics.Matter.MatterPhysics#composites + * @type {MatterJS.CompositesFactory} + * @since 3.22.0 + */ + this.composites = Composites; + + // Geometry + + /** + * A reference to the `Matter.Axes` module. + * + * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. + * + * @name Phaser.Physics.Matter.MatterPhysics#axes + * @type {MatterJS.AxesFactory} + * @since 3.22.0 + */ + this.axes = Axes; + + /** + * A reference to the `Matter.Bounds` module. + * + * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). + * + * @name Phaser.Physics.Matter.MatterPhysics#bounds + * @type {MatterJS.BoundsFactory} + * @since 3.22.0 + */ + this.bounds = Bounds; + + /** + * 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 + */ + this.svg = Svg; + + /** + * A reference to the `Matter.Vector` module. + * + * 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 }`. + * + * @name Phaser.Physics.Matter.MatterPhysics#vector + * @type {MatterJS.VectorFactory} + * @since 3.22.0 + */ + this.vector = Vector; + + /** + * A reference to the `Matter.Vertices` module. + * + * 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). + * + * @name Phaser.Physics.Matter.MatterPhysics#vertices + * @type {MatterJS.VerticesFactory} + * @since 3.22.0 + */ + this.vertices = Vertices; + + /** + * A reference to the `Matter.Vertices` module. + * + * 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). + * + * @name Phaser.Physics.Matter.MatterPhysics#verts + * @type {MatterJS.VerticesFactory} + * @since 3.14.0 + */ + this.verts = Vertices; + + /** + * An internal temp vector used for velocity and force calculations. + * + * @name Phaser.Physics.Matter.MatterPhysics#_tempVec2 + * @type {MatterJS.Vector} + * @private + * @since 3.22.0 + */ + this._tempVec2 = Vector.create(); + + // Matter plugins + + if (GetValue(this.config, 'plugins.collisionevents', true)) + { + this.enableCollisionEventsPlugin(); + } + + if (GetValue(this.config, 'plugins.attractors', false)) + { + this.enableAttractorPlugin(); + } + + if (GetValue(this.config, 'plugins.wrap', false)) + { + this.enableWrapPlugin(); + } + + Resolver._restingThresh = GetValue(this.config, 'restingThresh', 4); + Resolver._restingThreshTangent = GetValue(this.config, 'restingThreshTangent', 6); + Resolver._positionDampen = GetValue(this.config, 'positionDampen', 0.9); + Resolver._positionWarming = GetValue(this.config, 'positionWarming', 0.8); + Resolver._frictionNormalMultiplier = GetValue(this.config, 'frictionNormalMultiplier', 5); + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Matter.MatterPhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + this.bodyBounds = new BodyBounds(); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Matter.MatterPhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * This internal method is called when this class starts and retrieves the final Matter World Config. + * + * @method Phaser.Physics.Matter.MatterPhysics#getConfig + * @since 3.0.0 + * + * @return {Phaser.Types.Physics.Matter.MatterWorldConfig} The Matter World Config. + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'matter', {}), + GetFastValue(gameConfig, 'matter', {}) + ); + + return config; + }, + + /** + * Enables the Matter Attractors Plugin. + * + * The attractors plugin that makes it easy to apply continual forces on bodies. + * It's possible to simulate effects such as wind, gravity and magnetism. + * + * https://github.com/liabru/matter-attractors + * + * This method is called automatically if `plugins.attractors` is set in the Matter World Config. + * However, you can also call it directly from within your game. + * + * @method Phaser.Physics.Matter.MatterPhysics#enableAttractorPlugin + * @since 3.0.0 + * + * @return {this} This Matter Physics instance. + */ + enableAttractorPlugin: function () + { + Plugin.register(MatterAttractors); + Plugin.use(MatterLib, MatterAttractors); + + return this; + }, + + /** + * Enables the Matter Wrap Plugin. + * + * The coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay + * within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, + * while maintaining its velocity. + * + * https://github.com/liabru/matter-wrap + * + * This method is called automatically if `plugins.wrap` is set in the Matter World Config. + * However, you can also call it directly from within your game. + * + * @method Phaser.Physics.Matter.MatterPhysics#enableWrapPlugin + * @since 3.0.0 + * + * @return {this} This Matter Physics instance. + */ + enableWrapPlugin: function () + { + Plugin.register(MatterWrap); + Plugin.use(MatterLib, MatterWrap); + + return this; + }, + + /** + * Enables the Matter Collision Events Plugin. + * + * Note that this plugin is enabled by default. So you should only ever need to call this + * method if you have specifically disabled the plugin in your Matter World Config. + * You can disable it by setting `plugins.collisionevents: false` in your Matter World Config. + * + * This plugin triggers three new events on Matter.Body: + * + * 1. `onCollide` + * 2. `onCollideEnd` + * 3. `onCollideActive` + * + * These events correspond to the Matter.js events `collisionStart`, `collisionActive` and `collisionEnd`, respectively. + * You can listen to these events via Matter.Events or they will also be emitted from the Matter World. + * + * This plugin also extends Matter.Body with three convenience functions: + * + * `Matter.Body.setOnCollide(callback)` + * `Matter.Body.setOnCollideEnd(callback)` + * `Matter.Body.setOnCollideActive(callback)` + * + * You can register event callbacks by providing a function of type (pair: Matter.Pair) => void + * + * https://github.com/dxu/matter-collision-events + * + * @method Phaser.Physics.Matter.MatterPhysics#enableCollisionEventsPlugin + * @since 3.22.0 + * + * @return {this} This Matter Physics instance. + */ + enableCollisionEventsPlugin: function () + { + Plugin.register(MatterCollisionEvents); + Plugin.use(MatterLib, MatterCollisionEvents); + + return this; + }, + + /** + * Pauses the Matter World instance and sets `enabled` to `false`. + * + * A paused world will not run any simulations for the duration it is paused. + * + * @method Phaser.Physics.Matter.MatterPhysics#pause + * @fires Phaser.Physics.Matter.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.World} The Matter World object. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. + * + * @method Phaser.Physics.Matter.MatterPhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.World} The Matter World object. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * Sets the Matter Engine to run at fixed timestep of 60Hz and enables `autoUpdate`. + * If you have set a custom `getDelta` function then this will override it. + * + * @method Phaser.Physics.Matter.MatterPhysics#set60Hz + * @since 3.4.0 + * + * @return {this} This Matter Physics instance. + */ + set60Hz: function () + { + this.world.getDelta = this.world.update60Hz; + this.world.autoUpdate = true; + + return this; + }, + + /** + * Sets the Matter Engine to run at fixed timestep of 30Hz and enables `autoUpdate`. + * If you have set a custom `getDelta` function then this will override it. + * + * @method Phaser.Physics.Matter.MatterPhysics#set30Hz + * @since 3.4.0 + * + * @return {this} This Matter Physics instance. + */ + set30Hz: function () + { + this.world.getDelta = this.world.update30Hz; + this.world.autoUpdate = true; + + return this; + }, + + /** + * Manually advances the physics simulation by one iteration. + * + * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. + * If undefined they use the Matter defaults of 60Hz and no correction. + * + * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. + * + * It also ignores any custom `getDelta` functions, as you should be passing the delta + * value in to this call. + * + * You can adjust the number of iterations that Engine.update performs internally. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * + * @method Phaser.Physics.Matter.MatterPhysics#step + * @since 3.4.0 + * + * @param {number} [delta=16.666] - The delta value. + * @param {number} [correction=1] - Optional delta correction value. + */ + step: function (delta, correction) + { + this.world.step(delta, correction); + }, + + /** + * Checks if the vertices of the given body, or an array of bodies, contains the given point, or not. + * + * You can pass in either a single body, or an array of bodies to be checked. This method will + * return `true` if _any_ of the bodies in the array contain the point. See the `intersectPoint` method if you need + * to get a list of intersecting bodies. + * + * The point should be transformed into the Matter World coordinate system in advance. This happens by + * default with Input Pointers, but if you wish to use points from another system you may need to + * transform them before passing them. + * + * @method Phaser.Physics.Matter.MatterPhysics#containsPoint + * @since 3.22.0 + * + * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} body - The body, or an array of bodies, to check against the point. + * @param {number} x - The horizontal coordinate of the point. + * @param {number} y - The vertical coordinate of the point. + * + * @return {boolean} `true` if the point is within one of the bodies given, otherwise `false`. + */ + containsPoint: function (body, x, y) + { + body = this.getMatterBodies(body); + + var position = Vector.create(x, y); + + var result = Query.point(body, position); + + return (result.length > 0) ? true : false; + }, + + /** + * Checks the given coordinates to see if any vertices of the given bodies contain it. + * + * If no bodies are provided it will search all bodies in the Matter World, including within Composites. + * + * The coordinates should be transformed into the Matter World coordinate system in advance. This happens by + * default with Input Pointers, but if you wish to use coordinates from another system you may need to + * transform them before passing them. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectPoint + * @since 3.22.0 + * + * @param {number} x - The horizontal coordinate of the point. + * @param {number} y - The vertical coordinate of the point. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies which contain the given point. + */ + intersectPoint: function (x, y, bodies) + { + bodies = this.getMatterBodies(bodies); + + var position = Vector.create(x, y); + + var output = []; + + var result = Query.point(bodies, position); + + result.forEach(function (body) + { + if (output.indexOf(body) === -1) + { + output.push(body); + } + }); + + return output; + }, + + /** + * Checks the given rectangular area to see if any vertices of the given bodies intersect with it. + * Or, if the `outside` parameter is set to `true`, it checks to see which bodies do not + * intersect with it. + * + * If no bodies are provided it will search all bodies in the Matter World, including within Composites. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectRect + * @since 3.22.0 + * + * @param {number} x - The horizontal coordinate of the top-left of the area. + * @param {number} y - The vertical coordinate of the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {boolean} [outside=false] - If `false` it checks for vertices inside the area, if `true` it checks for vertices outside the area. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies that intersect with the given area. + */ + intersectRect: function (x, y, width, height, outside, bodies) + { + if (outside === undefined) { outside = false; } + + bodies = this.getMatterBodies(bodies); + + var bounds = { + min: { x: x, y: y }, + max: { x: x + width, y: y + height } + }; + + var output = []; + + var result = Query.region(bodies, bounds, outside); + + result.forEach(function (body) + { + if (output.indexOf(body) === -1) + { + output.push(body); + } + }); + + return output; + }, + + /** + * Checks the given ray segment to see if any vertices of the given bodies intersect with it. + * + * If no bodies are provided it will search all bodies in the Matter World. + * + * The width of the ray can be specified via the `rayWidth` parameter. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectRay + * @since 3.22.0 + * + * @param {number} x1 - The horizontal coordinate of the start of the ray segment. + * @param {number} y1 - The vertical coordinate of the start of the ray segment. + * @param {number} x2 - The horizontal coordinate of the end of the ray segment. + * @param {number} y2 - The vertical coordinate of the end of the ray segment. + * @param {number} [rayWidth=1] - The width of the ray segment. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with the ray segment. + */ + intersectRay: function (x1, y1, x2, y2, rayWidth, bodies) + { + if (rayWidth === undefined) { rayWidth = 1; } + + bodies = this.getMatterBodies(bodies); + + var result = []; + var collisions = Query.ray(bodies, Vector.create(x1, y1), Vector.create(x2, y2), rayWidth); + + for (var i = 0; i < collisions.length; i++) + { + result.push(collisions[i].body); + } + + return result; + }, + + /** + * Checks the given Matter Body to see if it intersects with any of the given bodies. + * + * If no bodies are provided it will check against all bodies in the Matter World. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectBody + * @since 3.22.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBody} body - The target body. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check the target body against. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with target body. + */ + intersectBody: function (body, bodies) + { + bodies = this.getMatterBodies(bodies); + + var result = []; + var collisions = Query.collides(body, bodies); + + for (var i = 0; i < collisions.length; i++) + { + var pair = collisions[i]; + + if (pair.bodyA === body) + { + result.push(pair.bodyB); + } + else + { + result.push(pair.bodyA); + } + } + + return result; + }, + + /** + * Checks to see if the target body, or an array of target bodies, intersects with any of the given bodies. + * + * If intersection occurs this method will return `true` and, if provided, invoke the callbacks. + * + * If no bodies are provided for the second parameter the target will check again all bodies in the Matter World. + * + * Note that bodies can only overlap if they are in non-colliding collision groups or categories. + * + * If you provide a `processCallback` then the two bodies that overlap are sent to it. This callback + * must return a boolean and is used to allow you to perform additional processing tests before a final + * outcome is decided. If it returns `true` then the bodies are finally passed to the `overlapCallback`, if set. + * + * If you provide an `overlapCallback` then the matching pairs of overlapping bodies will be sent to it. + * + * Both callbacks have the following signature: `function (bodyA, bodyB, collisionInfo)` where `bodyA` is always + * the target body. The `collisionInfo` object contains additional data, such as the angle and depth of penetration. + * + * @method Phaser.Physics.Matter.MatterPhysics#overlap + * @since 3.22.0 + * + * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} target - The target body, or array of target bodies, to check. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - The second body, or array of bodies, to check. If falsey it will check against all bodies in the world. + * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the bodies overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two bodies if they overlap. If this is set then `overlapCallback` will only be invoked if this callback returns `true`. + * @param {*} [callbackContext] - The context, or scope, in which to run the callbacks. + * + * @return {boolean} `true` if the target body intersects with _any_ of the bodies given, otherwise `false`. + */ + overlap: function (target, bodies, overlapCallback, processCallback, callbackContext) + { + if (overlapCallback === undefined) { overlapCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = overlapCallback; } + + if (!Array.isArray(target)) + { + target = [ target ]; + } + + target = this.getMatterBodies(target); + bodies = this.getMatterBodies(bodies); + + var match = false; + + for (var i = 0; i < target.length; i++) + { + var entry = target[i]; + + var collisions = Query.collides(entry, bodies); + + for (var c = 0; c < collisions.length; c++) + { + var info = collisions[c]; + var bodyB = (info.bodyA.id === entry.id) ? info.bodyB : info.bodyA; + + if (!processCallback || processCallback.call(callbackContext, entry, bodyB, info)) + { + match = true; + + if (overlapCallback) + { + overlapCallback.call(callbackContext, entry, bodyB, info); + } + else if (!processCallback) + { + // If there are no callbacks we don't need to test every body, just exit when the first is found + return true; + } + } + } + } + + return match; + }, + + /** + * Sets the collision filter category of all given Matter Bodies to the given value. + * + * This number must be a power of two between 2^0 (= 1) and 2^31. + * + * Bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * + * @method Phaser.Physics.Matter.MatterPhysics#setCollisionCategory + * @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} value - Unique category bitfield. + * + * @return {this} This Matter Physics instance. + */ + setCollisionCategory: function (bodies, value) + { + bodies = this.getMatterBodies(bodies); + + bodies.forEach(function (body) + { + body.collisionFilter.category = value; + }); + + return this; + }, + + /** + * Sets the collision filter group of all given Matter Bodies to the given value. + * + * If the group value is zero, or if two Matter Bodies have different group values, + * they will collide according to the usual collision filter rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * + * If two Matter Bodies have the same positive group value, they will always collide; + * if they have the same negative group value they will never collide. + * + * @method Phaser.Physics.Matter.MatterPhysics#setCollisionGroup + * @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} value - Unique group index. + * + * @return {this} This Matter Physics instance. + */ + setCollisionGroup: function (bodies, value) + { + bodies = this.getMatterBodies(bodies); + + bodies.forEach(function (body) + { + body.collisionFilter.group = value; + }); + + return this; + }, + + /** + * 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. + */ + setCollidesWith: function (bodies, categories) + { + bodies = this.getMatterBodies(bodies); + + var flags = 0; + + if (!Array.isArray(categories)) + { + flags = categories; + } + else + { + for (var i = 0; i < categories.length; i++) + { + flags |= categories[i]; + } + } + + bodies.forEach(function (body) + { + body.collisionFilter.mask = flags; + }); + + return this; + }, + + /** + * Takes an array and returns a new array made from all of the Matter Bodies found in the original array. + * + * For example, passing in Matter Game Objects, such as a bunch of Matter Sprites, to this method, would + * return an array containing all of their native Matter Body objects. + * + * If the `bodies` argument is falsey, it will return all bodies in the world. + * + * @method Phaser.Physics.Matter.MatterPhysics#getMatterBodies + * @since 3.22.0 + * + * @param {array} [bodies] - An array of objects to extract the bodies from. If falsey, it will return all bodies in the world. + * + * @return {MatterJS.BodyType[]} An array of native Matter Body objects. + */ + getMatterBodies: function (bodies) + { + if (!bodies) + { + return this.world.getAllBodies(); + } + + if (!Array.isArray(bodies)) + { + bodies = [ bodies ]; + } + + var output = []; + + for (var i = 0; i < bodies.length; i++) + { + var body = (bodies[i].hasOwnProperty('body')) ? bodies[i].body : bodies[i]; + + output.push(body); + } + + return output; + }, + + /** + * Sets both the horizontal and vertical linear velocity of the physics bodies. + * + * @method Phaser.Physics.Matter.MatterPhysics#setVelocity + * @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} x - The horizontal linear velocity value. + * @param {number} y - The vertical linear velocity value. + * + * @return {this} This Matter Physics instance. + */ + setVelocity: function (bodies, x, y) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + vec2.x = x; + vec2.y = y; + + bodies.forEach(function (body) + { + Body.setVelocity(body, vec2); + }); + + return this; + }, + + /** + * Sets just the horizontal linear velocity of the physics bodies. + * The vertical velocity of the body is unchanged. + * + * @method Phaser.Physics.Matter.MatterPhysics#setVelocityX + * @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} x - The horizontal linear velocity value. + * + * @return {this} This Matter Physics instance. + */ + setVelocityX: function (bodies, x) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + vec2.x = x; + + bodies.forEach(function (body) + { + vec2.y = body.velocity.y; + Body.setVelocity(body, vec2); + }); + + return this; + }, + + /** + * Sets just the vertical linear velocity of the physics bodies. + * The horizontal velocity of the body is unchanged. + * + * @method Phaser.Physics.Matter.MatterPhysics#setVelocityY + * @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} y - The vertical linear velocity value. + * + * @return {this} This Matter Physics instance. + */ + setVelocityY: function (bodies, y) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + vec2.y = y; + + bodies.forEach(function (body) + { + vec2.x = body.velocity.x; + Body.setVelocity(body, vec2); + }); + + return this; + }, + + /** + * Sets the angular velocity of the bodies instantly. + * Position, angle, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.MatterPhysics#setAngularVelocity + * @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} value - The angular velocity. + * + * @return {this} This Matter Physics instance. + */ + setAngularVelocity: function (bodies, value) + { + bodies = this.getMatterBodies(bodies); + + bodies.forEach(function (body) + { + Body.setAngularVelocity(body, value); + }); + + return this; + }, + + /** + * Applies a force to a body, at the bodies current position, including resulting torque. + * + * @method Phaser.Physics.Matter.MatterPhysics#applyForce + * @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 {Phaser.Types.Math.Vector2Like} force - A Vector that specifies the force to apply. + * + * @return {this} This Matter Physics instance. + */ + applyForce: function (bodies, force) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + bodies.forEach(function (body) + { + vec2.x = body.position.x; + vec2.y = body.position.y; + + Body.applyForce(body, vec2, force); + }); + + return this; + }, + + /** + * Applies a force to a body, from the given world position, including resulting torque. + * 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#applyForceFromPosition + * @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 {Phaser.Types.Math.Vector2Like} position - A Vector that specifies the world-space position to apply the force at. + * @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. + */ + applyForceFromPosition: function (bodies, position, speed, angle) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + bodies.forEach(function (body) + { + if (angle === undefined) + { + angle = body.angle; + } + + vec2.x = speed * Math.cos(angle); + vec2.y = speed * Math.sin(angle); + + Body.applyForce(body, position, vec2); + }); + + return this; + }, + + /** + * 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. + */ + applyForceFromAngle: function (bodies, speed, angle) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + bodies.forEach(function (body) + { + if (angle === undefined) + { + angle = body.angle; + } + + vec2.x = speed * Math.cos(angle); + vec2.y = speed * Math.sin(angle); + + Body.applyForce(body, { x: body.position.x, y: body.position.y }, vec2); + }); + + return this; + }, + + /** + * Returns the length of the given constraint, which is the distance between the two points. + * + * @method Phaser.Physics.Matter.MatterPhysics#getConstraintLength + * @since 3.22.0 + * + * @param {MatterJS.ConstraintType} constraint - The constraint to get the length from. + * + * @return {number} The length of the constraint. + */ + getConstraintLength: function (constraint) + { + var aX = constraint.pointA.x; + var aY = constraint.pointA.y; + var bX = constraint.pointB.x; + var bY = constraint.pointB.y; + + if (constraint.bodyA) + { + aX += constraint.bodyA.position.x; + aY += constraint.bodyA.position.y; + } + + if (constraint.bodyB) + { + bX += constraint.bodyB.position.x; + bY += constraint.bodyB.position.y; + } + + return DistanceBetween(aX, aY, bX, bY); + }, + + /** + * 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 {integer} align - One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`. + * + * @return {this} This Matter Physics instance. + */ + alignBody: function (body, x, y, align) + { + body = (body.hasOwnProperty('body')) ? body.body : body; + + var pos; + + switch (align) + { + case ALIGN_CONST.TOP_LEFT: + case ALIGN_CONST.LEFT_TOP: + pos = this.bodyBounds.getTopLeft(body, x, y); + break; + + case ALIGN_CONST.TOP_CENTER: + pos = this.bodyBounds.getTopCenter(body, x, y); + break; + + case ALIGN_CONST.TOP_RIGHT: + case ALIGN_CONST.RIGHT_TOP: + pos = this.bodyBounds.getTopRight(body, x, y); + break; + + case ALIGN_CONST.LEFT_CENTER: + pos = this.bodyBounds.getLeftCenter(body, x, y); + break; + + case ALIGN_CONST.CENTER: + pos = this.bodyBounds.getCenter(body, x, y); + break; + + case ALIGN_CONST.RIGHT_CENTER: + pos = this.bodyBounds.getRightCenter(body, x, y); + break; + + case ALIGN_CONST.LEFT_BOTTOM: + case ALIGN_CONST.BOTTOM_LEFT: + pos = this.bodyBounds.getBottomLeft(body, x, y); + break; + + case ALIGN_CONST.BOTTOM_CENTER: + pos = this.bodyBounds.getBottomCenter(body, x, y); + break; + + case ALIGN_CONST.BOTTOM_RIGHT: + case ALIGN_CONST.RIGHT_BOTTOM: + pos = this.bodyBounds.getBottomRight(body, x, y); + break; + } + + if (pos) + { + Body.setPosition(body, pos); + } + + return this; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Matter.MatterPhysics#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + if (this.world) + { + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + } + + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + if (this.add) + { + this.add.destroy(); + } + + if (this.world) + { + this.world.destroy(); + } + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Matter.MatterPhysics#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('MatterPhysics', MatterPhysics, 'matterPhysics'); + +module.exports = MatterPhysics; + + +/***/ }), +/* 1372 */ +/***/ (function(module, exports, __webpack_require__) { + +var Matter = __webpack_require__(239); + +/** + * An attractors plugin for matter.js. + * See the readme for usage and examples. + * @module MatterAttractors + */ +var MatterAttractors = { + // plugin meta + name: 'matter-attractors', // PLUGIN_NAME + version: '0.1.7', // PLUGIN_VERSION + for: 'matter-js@^0.14.2', + silent: true, // no console log please + + // installs the plugin where `base` is `Matter` + // you should not need to call this directly. + install: function(base) { + base.after('Body.create', function() { + MatterAttractors.Body.init(this); + }); + + base.before('Engine.update', function(engine) { + MatterAttractors.Engine.update(engine); + }); + }, + + Body: { + /** + * Initialises the `body` to support attractors. + * This is called automatically by the plugin. + * @function MatterAttractors.Body.init + * @param {Matter.Body} body The body to init. + * @returns {void} No return value. + */ + init: function(body) { + body.plugin.attractors = body.plugin.attractors || []; + } + }, + + Engine: { + /** + * Applies all attractors for all bodies in the `engine`. + * This is called automatically by the plugin. + * @function MatterAttractors.Engine.update + * @param {Matter.Engine} engine The engine to update. + * @returns {void} No return value. + */ + update: function(engine) { + var world = engine.world, + bodies = Matter.Composite.allBodies(world); + + for (var i = 0; i < bodies.length; i += 1) { + var bodyA = bodies[i], + attractors = bodyA.plugin.attractors; + + if (attractors && attractors.length > 0) { + for (var j = i + 1; j < bodies.length; j += 1) { + var bodyB = bodies[j]; + + for (var k = 0; k < attractors.length; k += 1) { + var attractor = attractors[k], + forceVector = attractor; + + if (Matter.Common.isFunction(attractor)) { + forceVector = attractor(bodyA, bodyB); + } + + if (forceVector) { + Matter.Body.applyForce(bodyB, bodyB.position, forceVector); + } + } + } + } + } + } + }, + + /** + * Defines some useful common attractor functions that can be used + * by pushing them to your body's `body.plugin.attractors` array. + * @namespace MatterAttractors.Attractors + * @property {number} gravityConstant The gravitational constant used by the gravity attractor. + */ + Attractors: { + gravityConstant: 0.001, + + /** + * An attractor function that applies Newton's law of gravitation. + * Use this by pushing `MatterAttractors.Attractors.gravity` to your body's `body.plugin.attractors` array. + * The gravitational constant defaults to `0.001` which you can change + * at `MatterAttractors.Attractors.gravityConstant`. + * @function MatterAttractors.Attractors.gravity + * @param {Matter.Body} bodyA The first body. + * @param {Matter.Body} bodyB The second body. + * @returns {void} No return value. + */ + gravity: function(bodyA, bodyB) { + // use Newton's law of gravitation + var bToA = Matter.Vector.sub(bodyB.position, bodyA.position), + distanceSq = Matter.Vector.magnitudeSquared(bToA) || 0.0001, + normal = Matter.Vector.normalise(bToA), + magnitude = -MatterAttractors.Attractors.gravityConstant * (bodyA.mass * bodyB.mass / distanceSq), + force = Matter.Vector.mult(normal, magnitude); + + // to apply forces to both bodies + Matter.Body.applyForce(bodyA, bodyA.position, Matter.Vector.neg(force)); + Matter.Body.applyForce(bodyB, bodyB.position, force); + } + } +}; + +module.exports = MatterAttractors; + +/** + * @namespace Matter.Body + * @see http://brm.io/matter-js/docs/classes/Body.html + */ + +/** + * This plugin adds a new property `body.plugin.attractors` to instances of `Matter.Body`. + * This is an array of callback functions that will be called automatically + * for every pair of bodies, on every engine update. + * @property {Function[]} body.plugin.attractors + * @memberof Matter.Body + */ + +/** + * An attractor function calculates the force to be applied + * to `bodyB`, it should either: + * - return the force vector to be applied to `bodyB` + * - or apply the force to the body(s) itself + * @callback AttractorFunction + * @param {Matter.Body} bodyA + * @param {Matter.Body} bodyB + * @returns {(Vector|undefined)} a force vector (optional) + */ + + +/***/ }), +/* 1373 */ +/***/ (function(module, exports) { + +/** + * @author @dxu https://github.com/dxu/matter-collision-events + * @author Richard Davey + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MatterCollisionEvents = { + + name: 'matter-collision-events', + version: '0.1.6', + for: 'matter-js@^0.14.2', + silent: true, + + install: function (matter) + { + matter.after('Engine.create', function () + { + matter.Events.on(this, 'collisionStart', function (event) + { + event.pairs.map(function (pair) + { + var bodyA = pair.bodyA; + var bodyB = pair.bodyB; + + if (bodyA.gameObject) + { + bodyA.gameObject.emit('collide', bodyA, bodyB, pair); + } + + if (bodyB.gameObject) + { + bodyB.gameObject.emit('collide', bodyB, bodyA, pair); + } + + matter.Events.trigger(bodyA, 'onCollide', { pair: pair }); + matter.Events.trigger(bodyB, 'onCollide', { pair: pair }); + + if (bodyA.onCollideCallback) + { + bodyA.onCollideCallback(pair); + } + + if (bodyB.onCollideCallback) + { + bodyB.onCollideCallback(pair); + } + + if (bodyA.onCollideWith[bodyB.id]) + { + bodyA.onCollideWith[bodyB.id](bodyB, pair); + } + + if (bodyB.onCollideWith[bodyA.id]) + { + bodyB.onCollideWith[bodyA.id](bodyA, pair); + } + }); + }); + + matter.Events.on(this, 'collisionActive', function (event) + { + event.pairs.map(function (pair) + { + var bodyA = pair.bodyA; + var bodyB = pair.bodyB; + + if (bodyA.gameObject) + { + bodyA.gameObject.emit('collideActive', bodyA, bodyB, pair); + } + + if (bodyB.gameObject) + { + bodyB.gameObject.emit('collideActive', bodyB, bodyA, pair); + } + + matter.Events.trigger(bodyA, 'onCollideActive', { pair: pair }); + matter.Events.trigger(bodyB, 'onCollideActive', { pair: pair }); + + if (bodyA.onCollideActiveCallback) + { + bodyA.onCollideActiveCallback(pair); + } + + if (bodyB.onCollideActiveCallback) + { + bodyB.onCollideActiveCallback(pair); + } + }); + }); + + matter.Events.on(this, 'collisionEnd', function (event) + { + event.pairs.map(function (pair) + { + var bodyA = pair.bodyA; + var bodyB = pair.bodyB; + + if (bodyA.gameObject) + { + bodyA.gameObject.emit('collideEnd', bodyA, bodyB, pair); + } + + if (bodyB.gameObject) + { + bodyB.gameObject.emit('collideEnd', bodyB, bodyA, pair); + } + + matter.Events.trigger(bodyA, 'onCollideEnd', { pair: pair }); + matter.Events.trigger(bodyB, 'onCollideEnd', { pair: pair }); + + if (bodyA.onCollideEndCallback) + { + bodyA.onCollideEndCallback(pair); + } + + if (bodyB.onCollideEndCallback) + { + bodyB.onCollideEndCallback(pair); + } + }); + }); + }); + } +}; + +module.exports = MatterCollisionEvents; + + +/***/ }), +/* 1374 */ +/***/ (function(module, exports, __webpack_require__) { + +var Matter = __webpack_require__(239); + +/** + * A coordinate wrapping plugin for matter.js. + * See the readme for usage and examples. + * @module MatterWrap + */ +var MatterWrap = { + // plugin meta + name: 'matter-wrap', // PLUGIN_NAME + version: '0.1.4', // PLUGIN_VERSION + for: 'matter-js@^0.14.2', + silent: true, // no console log please + + // installs the plugin where `base` is `Matter` + // you should not need to call this directly. + install: function(base) { + base.after('Engine.update', function() { + MatterWrap.Engine.update(this); + }); + }, + + Engine: { + /** + * Updates the engine by wrapping bodies and composites inside `engine.world`. + * This is called automatically by the plugin. + * @function MatterWrap.Engine.update + * @param {Matter.Engine} engine The engine to update. + * @returns {void} No return value. + */ + update: function(engine) { + var world = engine.world, + bodies = Matter.Composite.allBodies(world), + composites = Matter.Composite.allComposites(world); + + for (var i = 0; i < bodies.length; i += 1) { + var body = bodies[i]; + + if (body.plugin.wrap) { + MatterWrap.Body.wrap(body, body.plugin.wrap); + } + } + + for (i = 0; i < composites.length; i += 1) { + var composite = composites[i]; + + if (composite.plugin.wrap) { + MatterWrap.Composite.wrap(composite, composite.plugin.wrap); + } + } + } + }, + + Bounds: { + /** + * Returns a translation vector that wraps the `objectBounds` inside the `bounds`. + * @function MatterWrap.Bounds.wrap + * @param {Matter.Bounds} objectBounds The bounds of the object to wrap inside the bounds. + * @param {Matter.Bounds} bounds The bounds to wrap the body inside. + * @returns {?Matter.Vector} A translation vector (only if wrapping is required). + */ + wrap: function(objectBounds, bounds) { + var x = null, + y = null; + + if (typeof bounds.min.x !== 'undefined' && typeof bounds.max.x !== 'undefined') { + if (objectBounds.min.x > bounds.max.x) { + x = bounds.min.x - objectBounds.max.x; + } else if (objectBounds.max.x < bounds.min.x) { + x = bounds.max.x - objectBounds.min.x; + } + } + + if (typeof bounds.min.y !== 'undefined' && typeof bounds.max.y !== 'undefined') { + if (objectBounds.min.y > bounds.max.y) { + y = bounds.min.y - objectBounds.max.y; + } else if (objectBounds.max.y < bounds.min.y) { + y = bounds.max.y - objectBounds.min.y; + } + } + + if (x !== null || y !== null) { + return { + x: x || 0, + y: y || 0 + }; + } + } + }, + + Body: { + /** + * Wraps the `body` position such that it always stays within the given bounds. + * Upon crossing a boundary the body will appear on the opposite side of the bounds, + * while maintaining its velocity. + * This is called automatically by the plugin. + * @function MatterWrap.Body.wrap + * @param {Matter.Body} body The body to wrap. + * @param {Matter.Bounds} bounds The bounds to wrap the body inside. + * @returns {?Matter.Vector} The translation vector that was applied (only if wrapping was required). + */ + wrap: function(body, bounds) { + var translation = MatterWrap.Bounds.wrap(body.bounds, bounds); + + if (translation) { + Matter.Body.translate(body, translation); + } + + return translation; + } + }, + + Composite: { + /** + * Returns the union of the bounds of all of the composite's bodies + * (not accounting for constraints). + * @function MatterWrap.Composite.bounds + * @param {Matter.Composite} composite The composite. + * @returns {Matter.Bounds} The composite bounds. + */ + bounds: function(composite) { + var bodies = Matter.Composite.allBodies(composite), + vertices = []; + + for (var i = 0; i < bodies.length; i += 1) { + var body = bodies[i]; + vertices.push(body.bounds.min, body.bounds.max); + } + + return Matter.Bounds.create(vertices); + }, + + /** + * Wraps the `composite` position such that it always stays within the given bounds. + * Upon crossing a boundary the composite will appear on the opposite side of the bounds, + * while maintaining its velocity. + * This is called automatically by the plugin. + * @function MatterWrap.Composite.wrap + * @param {Matter.Composite} composite The composite to wrap. + * @param {Matter.Bounds} bounds The bounds to wrap the composite inside. + * @returns {?Matter.Vector} The translation vector that was applied (only if wrapping was required). + */ + wrap: function(composite, bounds) { + var translation = MatterWrap.Bounds.wrap( + MatterWrap.Composite.bounds(composite), + bounds + ); + + if (translation) { + Matter.Composite.translate(composite, translation); + } + + return translation; + } + } +}; + +module.exports = MatterWrap; + +/** + * @namespace Matter.Body + * @see http://brm.io/matter-js/docs/classes/Body.html + */ + +/** + * This plugin adds a new property `body.plugin.wrap` to instances of `Matter.Body`. + * This is a `Matter.Bounds` instance that specifies the wrapping region. + * @property {Matter.Bounds} body.plugin.wrap + * @memberof Matter.Body + */ + +/** + * This plugin adds a new property `composite.plugin.wrap` to instances of `Matter.Composite`. + * This is a `Matter.Bounds` instance that specifies the wrapping region. + * @property {Matter.Bounds} composite.plugin.wrap + * @memberof Matter.Composite + */ + +/***/ }), +/* 1375 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Plugins + */ + +module.exports = { + + BasePlugin: __webpack_require__(512), + DefaultPlugins: __webpack_require__(186), + PluginCache: __webpack_require__(22), + PluginManager: __webpack_require__(394), + ScenePlugin: __webpack_require__(1376) + +}; + + +/***/ }), +/* 1376 */ +/***/ (function(module, exports, __webpack_require__) { + +/** +* @author Richard Davey +* @copyright 2020 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} +*/ + +var BasePlugin = __webpack_require__(512); +var Class = __webpack_require__(0); +var SceneEvents = __webpack_require__(18); + +/** + * @classdesc + * A Scene Level Plugin is installed into every Scene and belongs to that Scene. + * It can listen for Scene events and respond to them. + * It can map itself to a Scene property, or into the Scene Systems, or both. + * + * @class ScenePlugin + * @memberof Phaser.Plugins + * @extends Phaser.Plugins.BasePlugin + * @constructor + * @since 3.8.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that has installed this plugin. + * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Plugin Manager. + */ +var ScenePlugin = new Class({ + + Extends: BasePlugin, + + initialize: + + function ScenePlugin (scene, pluginManager) + { + BasePlugin.call(this, pluginManager); + + /** + * A reference to the Scene that has installed this plugin. + * Only set if it's a Scene Plugin, otherwise `null`. + * This property is only set when the plugin is instantiated and added to the Scene, not before. + * You can use it during the `boot` method. + * + * @name Phaser.Plugins.ScenePlugin#scene + * @type {?Phaser.Scene} + * @protected + * @since 3.8.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems of the Scene that has installed this plugin. + * Only set if it's a Scene Plugin, otherwise `null`. + * This property is only set when the plugin is instantiated and added to the Scene, not before. + * You can use it during the `boot` method. + * + * @name Phaser.Plugins.ScenePlugin#systems + * @type {?Phaser.Scenes.Systems} + * @protected + * @since 3.8.0 + */ + this.systems = scene.sys; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + }, + + /** + * This method is called when the Scene boots. It is only ever called once. + * + * By this point the plugin properties `scene` and `systems` will have already been set. + * + * In here you can listen for {@link Phaser.Scenes.Events Scene events} and set-up whatever you need for this plugin to run. + * Here are the Scene events you can listen to: + * + * - start + * - ready + * - preupdate + * - update + * - postupdate + * - resize + * - pause + * - resume + * - sleep + * - wake + * - transitioninit + * - transitionstart + * - transitioncomplete + * - transitionout + * - shutdown + * - destroy + * + * At the very least you should offer a destroy handler for when the Scene closes down, i.e: + * + * ```javascript + * var eventEmitter = this.systems.events; + * eventEmitter.once('destroy', this.sceneDestroy, this); + * ``` + * + * @method Phaser.Plugins.ScenePlugin#boot + * @since 3.8.0 + */ + boot: function () + { + }, + + /** + * Game instance has been destroyed. + * + * You must release everything in here, all references, all objects, free it all up. + * + * @method Phaser.Plugins.ScenePlugin#destroy + * @since 3.8.0 + */ + destroy: function () + { + this.pluginManager = null; + this.game = null; + this.scene = null; + this.systems = null; + } + +}); + +module.exports = ScenePlugin; + + +/***/ }), +/* 1377 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer + */ + +/** + * @namespace Phaser.Types.Renderer + */ + +module.exports = { + + Canvas: __webpack_require__(1378), + Snapshot: __webpack_require__(1379), + WebGL: __webpack_require__(1380) + +}; + + +/***/ }), +/* 1378 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.Canvas + */ + +module.exports = { + + CanvasRenderer: __webpack_require__(358), + GetBlendModes: __webpack_require__(360), + SetTransform: __webpack_require__(29) + +}; + + +/***/ }), +/* 1379 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.Snapshot + */ + +module.exports = { + + Canvas: __webpack_require__(359), + WebGL: __webpack_require__(362) + +}; + + +/***/ }), +/* 1380 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.WebGL + */ + +module.exports = { + + Utils: __webpack_require__(10), + WebGLPipeline: __webpack_require__(187), + WebGLRenderer: __webpack_require__(361), + Pipelines: __webpack_require__(1381), + + // Constants + BYTE: 0, + SHORT: 1, + UNSIGNED_BYTE: 2, + UNSIGNED_SHORT: 3, + FLOAT: 4 + +}; + + +/***/ }), +/* 1381 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.WebGL.Pipelines + */ + +module.exports = { + + BitmapMaskPipeline: __webpack_require__(363), + ForwardDiffuseLightPipeline: __webpack_require__(364), + TextureTintPipeline: __webpack_require__(188), + ModelViewProjection: __webpack_require__(365) + +}; + + +/***/ }), +/* 1382 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = __webpack_require__(17); +var CONST = __webpack_require__(190); + +/** + * @namespace Phaser.Scale + * + * @borrows Phaser.Scale.Center.NO_CENTER as NO_CENTER + * @borrows Phaser.Scale.Center.CENTER_BOTH as CENTER_BOTH + * @borrows Phaser.Scale.Center.CENTER_HORIZONTALLY as CENTER_HORIZONTALLY + * @borrows Phaser.Scale.Center.CENTER_VERTICALLY as CENTER_VERTICALLY + * + * @borrows Phaser.Scale.Orientation.LANDSCAPE as LANDSCAPE + * @borrows Phaser.Scale.Orientation.PORTRAIT as PORTRAIT + * + * @borrows Phaser.Scale.ScaleModes.NONE as NONE + * @borrows Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT as WIDTH_CONTROLS_HEIGHT + * @borrows Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH as HEIGHT_CONTROLS_WIDTH + * @borrows Phaser.Scale.ScaleModes.FIT as FIT + * @borrows Phaser.Scale.ScaleModes.ENVELOP as ENVELOP + * @borrows Phaser.Scale.ScaleModes.RESIZE as RESIZE + * + * @borrows Phaser.Scale.Zoom.NO_ZOOM as NO_ZOOM + * @borrows Phaser.Scale.Zoom.ZOOM_2X as ZOOM_2X + * @borrows Phaser.Scale.Zoom.ZOOM_4X as ZOOM_4X + * @borrows Phaser.Scale.Zoom.MAX_ZOOM as MAX_ZOOM + */ + +var Scale = { + + Center: __webpack_require__(383), + Events: __webpack_require__(104), + Orientation: __webpack_require__(384), + ScaleManager: __webpack_require__(395), + ScaleModes: __webpack_require__(385), + Zoom: __webpack_require__(386) + +}; + +Scale = Extend(false, Scale, CONST.CENTER); +Scale = Extend(false, Scale, CONST.ORIENTATION); +Scale = Extend(false, Scale, CONST.SCALE_MODE); +Scale = Extend(false, Scale, CONST.ZOOM); + +module.exports = Scale; + + +/***/ }), +/* 1383 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(132); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Scenes + */ + +var Scene = { + + Events: __webpack_require__(18), + SceneManager: __webpack_require__(397), + ScenePlugin: __webpack_require__(1384), + Settings: __webpack_require__(399), + Systems: __webpack_require__(193) + +}; + +// Merge in the consts +Scene = Extend(false, Scene, CONST); + +module.exports = Scene; + + +/***/ }), +/* 1384 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(20); +var Class = __webpack_require__(0); +var Events = __webpack_require__(18); +var GetFastValue = __webpack_require__(1); +var PluginCache = __webpack_require__(22); + +/** + * @classdesc + * A proxy class to the Global Scene Manager. + * + * @class ScenePlugin + * @memberof Phaser.Scenes + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this ScenePlugin belongs to. + */ +var ScenePlugin = new Class({ + + initialize: + + function ScenePlugin (scene) + { + /** + * The Scene that this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene Systems instance of the Scene that this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The settings of the Scene this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.0.0 + */ + this.settings = scene.sys.settings; + + /** + * The key of the Scene this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#key + * @type {string} + * @since 3.0.0 + */ + this.key = scene.sys.settings.key; + + /** + * The Game's SceneManager. + * + * @name Phaser.Scenes.ScenePlugin#manager + * @type {Phaser.Scenes.SceneManager} + * @since 3.0.0 + */ + this.manager = scene.sys.game.scene; + + /** + * If this Scene is currently transitioning to another, this holds + * the current percentage of the transition progress, between 0 and 1. + * + * @name Phaser.Scenes.ScenePlugin#transitionProgress + * @type {number} + * @since 3.5.0 + */ + this.transitionProgress = 0; + + /** + * Transition elapsed timer. + * + * @name Phaser.Scenes.ScenePlugin#_elapsed + * @type {integer} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * Transition elapsed timer. + * + * @name Phaser.Scenes.ScenePlugin#_target + * @type {?Phaser.Scenes.Scene} + * @private + * @since 3.5.0 + */ + this._target = null; + + /** + * Transition duration. + * + * @name Phaser.Scenes.ScenePlugin#_duration + * @type {integer} + * @private + * @since 3.5.0 + */ + this._duration = 0; + + /** + * Transition callback. + * + * @name Phaser.Scenes.ScenePlugin#_onUpdate + * @type {function} + * @private + * @since 3.5.0 + */ + this._onUpdate; + + /** + * Transition callback scope. + * + * @name Phaser.Scenes.ScenePlugin#_onUpdateScope + * @type {object} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + + /** + * Will this Scene sleep (true) after the transition, or stop (false) + * + * @name Phaser.Scenes.ScenePlugin#_willSleep + * @type {boolean} + * @private + * @since 3.5.0 + */ + this._willSleep = false; + + /** + * Will this Scene be removed from the Scene Manager after the transition completes? + * + * @name Phaser.Scenes.ScenePlugin#_willRemove + * @type {boolean} + * @private + * @since 3.5.0 + */ + this._willRemove = false; + + scene.sys.events.once(Events.BOOT, this.boot, this); + scene.sys.events.on(Events.START, this.pluginStart, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Scenes.ScenePlugin#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + this.systems.events.once(Events.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Scenes.ScenePlugin#pluginStart + * @private + * @since 3.5.0 + */ + pluginStart: function () + { + this._target = null; + + this.systems.events.once(Events.SHUTDOWN, this.shutdown, this); + }, + + /** + * Shutdown this Scene and run the given one. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#start + * @since 3.0.0 + * + * @param {string} [key] - The Scene to start. + * @param {object} [data] - The Scene data. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + start: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('stop', this.key); + this.manager.queueOp('start', key, data); + + return this; + }, + + /** + * Restarts this Scene. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#restart + * @since 3.4.0 + * + * @param {object} [data] - The Scene data. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + restart: function (data) + { + var key = this.key; + + this.manager.queueOp('stop', key); + this.manager.queueOp('start', key, data); + + return this; + }, + + /** + * This will start a transition from the current Scene to the target Scene given. + * + * The transition will last for the duration specified in milliseconds. + * + * You can have the target Scene moved above or below this one in the display list. + * + * You can specify an update callback. This callback will be invoked _every frame_ for the duration + * of the transition. + * + * This Scene can either be sent to sleep at the end of the transition, or stopped. The default is to stop. + * + * There are also 5 transition related events: This scene will emit the event `transitionout` when + * the transition begins, which is typically the frame after calling this method. + * + * The target Scene will emit the event `transitioninit` when that Scene's `init` method is called. + * It will then emit the event `transitionstart` when its `create` method is called. + * If the Scene was sleeping and has been woken up, it will emit the event `transitionwake` instead of these two, + * as the Scenes `init` and `create` methods are not invoked when a Scene wakes up. + * + * When the duration of the transition has elapsed it will emit the event `transitioncomplete`. + * These events are cleared of all listeners when the Scene shuts down, but not if it is sent to sleep. + * + * It's important to understand that the duration of the transition begins the moment you call this method. + * If the Scene you are transitioning to includes delayed processes, such as waiting for files to load, the + * time still counts down even while that is happening. If the game itself pauses, or something else causes + * this Scenes update loop to stop, then the transition will also pause for that duration. There are + * checks in place to prevent you accidentally stopping a transitioning Scene but if you've got code to + * override this understand that until the target Scene completes it might never be unlocked for input events. + * + * @method Phaser.Scenes.ScenePlugin#transition + * @fires Phaser.Scenes.Events#TRANSITION_OUT + * @since 3.5.0 + * + * @param {Phaser.Types.Scenes.SceneTransitionConfig} config - The transition configuration object. + * + * @return {boolean} `true` is the transition was started, otherwise `false`. + */ + transition: function (config) + { + if (config === undefined) { config = {}; } + + var key = GetFastValue(config, 'target', false); + + var target = this.manager.getScene(key); + + if (!key || !this.checkValidTransition(target)) + { + return false; + } + + var duration = GetFastValue(config, 'duration', 1000); + + this._elapsed = 0; + this._target = target; + this._duration = duration; + this._willSleep = GetFastValue(config, 'sleep', false); + this._willRemove = GetFastValue(config, 'remove', false); + + var callback = GetFastValue(config, 'onUpdate', null); + + if (callback) + { + this._onUpdate = callback; + this._onUpdateScope = GetFastValue(config, 'onUpdateScope', this.scene); + } + + var allowInput = GetFastValue(config, 'allowInput', false); + + this.settings.transitionAllowInput = allowInput; + + var targetSettings = target.sys.settings; + + targetSettings.isTransition = true; + targetSettings.transitionFrom = this.scene; + targetSettings.transitionDuration = duration; + targetSettings.transitionAllowInput = allowInput; + + if (GetFastValue(config, 'moveAbove', false)) + { + this.manager.moveAbove(this.key, key); + } + else if (GetFastValue(config, 'moveBelow', false)) + { + this.manager.moveBelow(this.key, key); + } + + if (target.sys.isSleeping()) + { + target.sys.wake(); + } + else + { + this.manager.start(key, GetFastValue(config, 'data')); + } + + this.systems.events.emit(Events.TRANSITION_OUT, target, duration); + + this.systems.events.on(Events.UPDATE, this.step, this); + + return true; + }, + + /** + * Checks to see if this Scene can transition to the target Scene or not. + * + * @method Phaser.Scenes.ScenePlugin#checkValidTransition + * @private + * @since 3.5.0 + * + * @param {Phaser.Scene} target - The Scene to test against. + * + * @return {boolean} `true` if this Scene can transition, otherwise `false`. + */ + checkValidTransition: function (target) + { + // Not a valid target if it doesn't exist, isn't active or is already transitioning in or out + if (!target || target.sys.isActive() || target.sys.isTransitioning() || target === this.scene || this.systems.isTransitioning()) + { + return false; + } + + return true; + }, + + /** + * 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. + */ + step: function (time, delta) + { + this._elapsed += delta; + + this.transitionProgress = Clamp(this._elapsed / this._duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.transitionProgress); + } + + if (this._elapsed >= this._duration) + { + this.transitionComplete(); + } + }, + + /** + * Called by `step` when the transition out of this scene to another is over. + * + * @method Phaser.Scenes.ScenePlugin#transitionComplete + * @private + * @fires Phaser.Scenes.Events#TRANSITION_COMPLETE + * @since 3.5.0 + */ + transitionComplete: function () + { + var targetSys = this._target.sys; + var targetSettings = this._target.sys.settings; + + // Stop the step + this.systems.events.off(Events.UPDATE, this.step, this); + + // Notify target scene + targetSys.events.emit(Events.TRANSITION_COMPLETE, this.scene); + + // Clear target scene settings + targetSettings.isTransition = false; + targetSettings.transitionFrom = null; + + // Clear local settings + this._duration = 0; + this._target = null; + this._onUpdate = null; + this._onUpdateScope = null; + + // Now everything is clear we can handle what happens to this Scene + if (this._willRemove) + { + this.manager.remove(this.key); + } + else if (this._willSleep) + { + this.systems.sleep(); + } + else + { + this.manager.stop(this.key); + } + }, + + /** + * Add the Scene into the Scene Manager and start it if 'autoStart' is true or the Scene config 'active' property is set. + * + * @method Phaser.Scenes.ScenePlugin#add + * @since 3.0.0 + * + * @param {string} key - The Scene key. + * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene. + * @param {boolean} autoStart - Whether to start the Scene after it's added. + * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. + * + * @return {Phaser.Scene} An instance of the Scene that was added to the Scene Manager. + */ + add: function (key, sceneConfig, autoStart, data) + { + return this.manager.add(key, sceneConfig, autoStart, data); + }, + + /** + * Launch the given Scene and run it in parallel with this one. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#launch + * @since 3.0.0 + * + * @param {string} key - The Scene to launch. + * @param {object} [data] - The Scene data. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + launch: function (key, data) + { + if (key && key !== this.key) + { + this.manager.queueOp('start', key, data); + } + + return this; + }, + + /** + * Runs the given Scene, but does not change the state of this Scene. + * + * This will happen at the next Scene Manager update, not immediately. + * + * If the given Scene is paused, it will resume it. If sleeping, it will wake it. + * If not running at all, it will be started. + * + * Use this if you wish to open a modal Scene by calling `pause` on the current + * Scene, then `run` on the modal Scene. + * + * @method Phaser.Scenes.ScenePlugin#run + * @since 3.10.0 + * + * @param {string} key - The Scene to run. + * @param {object} [data] - A data object that will be passed to the Scene and emitted in its ready, wake, or resume events. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + run: function (key, data) + { + if (key && key !== this.key) + { + this.manager.queueOp('run', key, data); + } + + return this; + }, + + /** + * Pause the Scene - this stops the update step from happening but it still renders. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#pause + * @since 3.0.0 + * + * @param {string} [key] - The Scene to pause. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its pause event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + pause: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('pause', key, data); + + return this; + }, + + /** + * Resume the Scene - starts the update loop again. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#resume + * @since 3.0.0 + * + * @param {string} [key] - The Scene to resume. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its resume event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + resume: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('resume', key, data); + + return this; + }, + + /** + * Makes the Scene sleep (no update, no render) but doesn't shutdown. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#sleep + * @since 3.0.0 + * + * @param {string} [key] - The Scene to put to sleep. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its sleep event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + sleep: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('sleep', key, data); + + return this; + }, + + /** + * Makes the Scene wake-up (starts update and render) + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#wake + * @since 3.0.0 + * + * @param {string} [key] - The Scene to wake up. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its wake event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + wake: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('wake', key, data); + + return this; + }, + + /** + * Makes this Scene sleep then starts the Scene given. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#switch + * @since 3.0.0 + * + * @param {string} key - The Scene to start. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + switch: function (key) + { + if (key !== this.key) + { + this.manager.queueOp('switch', this.key, key); + } + + return this; + }, + + /** + * Shutdown the Scene, clearing display list, timers, etc. + * + * This happens at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#stop + * @since 3.0.0 + * + * @param {string} [key] - The Scene to stop. + * @param {any} [data] - Optional data object to pass to Scene.Systems.shutdown. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + stop: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('stop', key, data); + + return this; + }, + + /** + * Sets the active state of the given Scene. + * + * @method Phaser.Scenes.ScenePlugin#setActive + * @since 3.0.0 + * + * @param {boolean} value - If `true` the Scene will be resumed. If `false` it will be paused. + * @param {string} [key] - The Scene to set the active state of. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted with its events. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + setActive: function (value, key, data) + { + if (key === undefined) { key = this.key; } + + var scene = this.manager.getScene(key); + + if (scene) + { + scene.sys.setActive(value, data); + } + + return this; + }, + + /** + * Sets the visible state of the given Scene. + * + * @method Phaser.Scenes.ScenePlugin#setVisible + * @since 3.0.0 + * + * @param {boolean} value - The visible value. + * @param {string} [key] - The Scene to set the visible state for. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + setVisible: function (value, key) + { + if (key === undefined) { key = this.key; } + + var scene = this.manager.getScene(key); + + if (scene) + { + scene.sys.setVisible(value); + } + + return this; + }, + + /** + * Checks if the given Scene is sleeping or not? + * + * @method Phaser.Scenes.ScenePlugin#isSleeping + * @since 3.0.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is sleeping. + */ + isSleeping: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isSleeping(key); + }, + + /** + * Checks if the given Scene is running or not? + * + * @method Phaser.Scenes.ScenePlugin#isActive + * @since 3.0.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is running. + */ + isActive: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isActive(key); + }, + + /** + * Checks if the given Scene is paused or not? + * + * @method Phaser.Scenes.ScenePlugin#isPaused + * @since 3.17.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is paused. + */ + isPaused: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isPaused(key); + }, + + /** + * Checks if the given Scene is visible or not? + * + * @method Phaser.Scenes.ScenePlugin#isVisible + * @since 3.0.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is visible. + */ + isVisible: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isVisible(key); + }, + + /** + * Swaps the position of two scenes in the Scenes list. + * + * This controls the order in which they are rendered and updated. + * + * @method Phaser.Scenes.ScenePlugin#swapPosition + * @since 3.2.0 + * + * @param {string} keyA - The first Scene to swap. + * @param {string} [keyB] - The second Scene to swap. If none is given it defaults to this Scene. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + swapPosition: function (keyA, keyB) + { + if (keyB === undefined) { keyB = this.key; } + + if (keyA !== keyB) + { + this.manager.swapPosition(keyA, keyB); + } + + return this; + }, + + /** + * Swaps the position of two scenes in the Scenes list, so that Scene B is directly above Scene A. + * + * This controls the order in which they are rendered and updated. + * + * @method Phaser.Scenes.ScenePlugin#moveAbove + * @since 3.2.0 + * + * @param {string} keyA - The Scene that Scene B will be moved to be above. + * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveAbove: function (keyA, keyB) + { + if (keyB === undefined) { keyB = this.key; } + + if (keyA !== keyB) + { + this.manager.moveAbove(keyA, keyB); + } + + return this; + }, + + /** + * Swaps the position of two scenes in the Scenes list, so that Scene B is directly below Scene A. + * + * This controls the order in which they are rendered and updated. + * + * @method Phaser.Scenes.ScenePlugin#moveBelow + * @since 3.2.0 + * + * @param {string} keyA - The Scene that Scene B will be moved to be below. + * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveBelow: function (keyA, keyB) + { + if (keyB === undefined) { keyB = this.key; } + + if (keyA !== keyB) + { + this.manager.moveBelow(keyA, keyB); + } + + return this; + }, + + /** + * Removes a Scene from the SceneManager. + * + * The Scene is removed from the local scenes array, it's key is cleared from the keys + * cache and Scene.Systems.destroy is then called on it. + * + * If the SceneManager is processing the Scenes when this method is called it will + * queue the operation for the next update sequence. + * + * @method Phaser.Scenes.ScenePlugin#remove + * @since 3.2.0 + * + * @param {(string|Phaser.Scene)} [key] - The Scene to be removed. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + remove: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.remove(key); + + return this; + }, + + /** + * Moves a Scene up one position in the Scenes list. + * + * @method Phaser.Scenes.ScenePlugin#moveUp + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveUp: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.moveUp(key); + + return this; + }, + + /** + * Moves a Scene down one position in the Scenes list. + * + * @method Phaser.Scenes.ScenePlugin#moveDown + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveDown: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.moveDown(key); + + return this; + }, + + /** + * Brings a Scene to the top of the Scenes list. + * + * This means it will render above all other Scenes. + * + * @method Phaser.Scenes.ScenePlugin#bringToTop + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + bringToTop: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.bringToTop(key); + + return this; + }, + + /** + * Sends a Scene to the back of the Scenes list. + * + * This means it will render below all other Scenes. + * + * @method Phaser.Scenes.ScenePlugin#sendToBack + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + sendToBack: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.sendToBack(key); + + return this; + }, + + /** + * Retrieve a Scene. + * + * @method Phaser.Scenes.ScenePlugin#get + * @since 3.0.0 + * + * @param {string} key - The Scene to retrieve. + * + * @return {Phaser.Scene} The Scene. + */ + get: function (key) + { + return this.manager.getScene(key); + }, + + /** + * Retrieves the numeric index of a Scene in the Scenes list. + * + * @method Phaser.Scenes.ScenePlugin#getIndex + * @since 3.7.0 + * + * @param {(string|Phaser.Scene)} [key] - The Scene to get the index of. + * + * @return {integer} The index of the Scene. + */ + getIndex: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.getIndex(key); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Scenes.ScenePlugin#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.off(Events.SHUTDOWN, this.shutdown, this); + eventEmitter.off(Events.POST_UPDATE, this.step, this); + eventEmitter.off(Events.TRANSITION_OUT); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Scenes.ScenePlugin#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(Events.START, this.start, this); + + this.scene = null; + this.systems = null; + this.settings = null; + this.manager = null; + } + +}); + +PluginCache.register('ScenePlugin', ScenePlugin, 'scenePlugin'); + +module.exports = ScenePlugin; + + +/***/ }), +/* 1385 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Structs + */ + +module.exports = { + + List: __webpack_require__(135), + Map: __webpack_require__(172), + ProcessQueue: __webpack_require__(199), + RTree: __webpack_require__(493), + Set: __webpack_require__(110), + Size: __webpack_require__(396) + +}; + + +/***/ }), +/* 1386 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = __webpack_require__(17); +var FilterMode = __webpack_require__(1387); + +/** + * @namespace Phaser.Textures + */ + +/** + * Linear filter type. + * + * @name Phaser.Textures.LINEAR + * @type {integer} + * @const + * @since 3.0.0 + */ + +/** + * Nearest Neighbor filter type. + * + * @name Phaser.Textures.NEAREST + * @type {integer} + * @const + * @since 3.0.0 + */ + +var Textures = { + + CanvasTexture: __webpack_require__(401), + Events: __webpack_require__(128), + FilterMode: FilterMode, + Frame: __webpack_require__(106), + Parsers: __webpack_require__(403), + Texture: __webpack_require__(195), + TextureManager: __webpack_require__(400), + TextureSource: __webpack_require__(402) + +}; + +Textures = Extend(false, Textures, FilterMode); + +module.exports = Textures; + + +/***/ }), +/* 1387 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Filter Types. + * + * @namespace Phaser.Textures.FilterMode + * @memberof Phaser.Textures + * @since 3.0.0 + */ +var CONST = { + + /** + * Linear filter type. + * + * @name Phaser.Textures.FilterMode.LINEAR + * @type {integer} + * @const + * @since 3.0.0 + */ + LINEAR: 0, + + /** + * Nearest neighbor filter type. + * + * @name Phaser.Textures.FilterMode.NEAREST + * @type {integer} + * @const + * @since 3.0.0 + */ + NEAREST: 1 + +}; + +module.exports = CONST; + + +/***/ }), +/* 1388 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps + */ + +module.exports = { + + Components: __webpack_require__(150), + Parsers: __webpack_require__(1418), + + Formats: __webpack_require__(34), + ImageCollection: __webpack_require__(523), + ParseToTilemap: __webpack_require__(252), + Tile: __webpack_require__(80), + Tilemap: __webpack_require__(532), + TilemapCreator: __webpack_require__(1427), + TilemapFactory: __webpack_require__(1428), + Tileset: __webpack_require__(154), + + LayerData: __webpack_require__(116), + MapData: __webpack_require__(117), + ObjectLayer: __webpack_require__(526), + + DynamicTilemapLayer: __webpack_require__(533), + StaticTilemapLayer: __webpack_require__(534) + +}; + + +/***/ }), +/* 1389 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); +var CalculateFacesWithin = __webpack_require__(59); + +/** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * @function Phaser.Tilemaps.Components.Copy + * @private + * @since 3.0.0 + * + * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} width - The width of the area to copy, in tiles, not pixels. + * @param {integer} height - The height of the area to copy, in tiles, not pixels. + * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. + * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var Copy = function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) +{ + if (srcTileX < 0) { srcTileX = 0; } + if (srcTileY < 0) { srcTileY = 0; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + var srcTiles = GetTilesWithin(srcTileX, srcTileY, width, height, null, layer); + + var offsetX = destTileX - srcTileX; + var offsetY = destTileY - srcTileY; + + for (var i = 0; i < srcTiles.length; i++) + { + var tileX = srcTiles[i].x + offsetX; + var tileY = srcTiles[i].y + offsetY; + if (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height) + { + if (layer.data[tileY][tileX]) + { + layer.data[tileY][tileX].copy(srcTiles[i]); + } + } + } + + if (recalculateFaces) + { + // Recalculate the faces within the destination area and neighboring tiles + CalculateFacesWithin(destTileX - 1, destTileY - 1, width + 2, height + 2, layer); + } +}; + +module.exports = Copy; + + +/***/ }), +/* 1390 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TileToWorldX = __webpack_require__(152); +var TileToWorldY = __webpack_require__(153); +var GetTilesWithin = __webpack_require__(26); +var ReplaceByIndex = __webpack_require__(513); + +/** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @function Phaser.Tilemaps.Components.CreateFromTiles + * @private + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ +var CreateFromTiles = function (indexes, replacements, spriteConfig, scene, camera, layer) +{ + if (spriteConfig === undefined) { spriteConfig = {}; } + + if (!Array.isArray(indexes)) { indexes = [ indexes ]; } + + var tilemapLayer = layer.tilemapLayer; + if (scene === undefined) { scene = tilemapLayer.scene; } + if (camera === undefined) { camera = scene.cameras.main; } + + var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); + var sprites = []; + var i; + + for (i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + if (indexes.indexOf(tile.index) !== -1) + { + spriteConfig.x = TileToWorldX(tile.x, camera, layer); + spriteConfig.y = TileToWorldY(tile.y, camera, layer); + + var sprite = scene.make.sprite(spriteConfig); + sprites.push(sprite); + } + } + + if (typeof replacements === 'number') + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < indexes.length; i++) + { + ReplaceByIndex(indexes[i], replacements, 0, 0, layer.width, layer.height, layer); + } + } + else if (Array.isArray(replacements)) + { + // Assume 1 to 1 mapping with indexes array + for (i = 0; i < indexes.length; i++) + { + ReplaceByIndex(indexes[i], replacements[i], 0, 0, layer.width, layer.height, layer); + } + } + + return sprites; +}; + +module.exports = CreateFromTiles; + + +/***/ }), +/* 1391 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SnapFloor = __webpack_require__(105); +var SnapCeil = __webpack_require__(347); + +/** + * Returns the tiles in the given layer that are within the camera's viewport. This is used internally. + * + * @function Phaser.Tilemaps.Components.CullTiles + * @private + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + * @param {array} [outputArray] - An optional array to store the Tile objects within. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ +var CullTiles = function (layer, camera, outputArray, renderOrder) +{ + if (outputArray === undefined) { outputArray = []; } + if (renderOrder === undefined) { renderOrder = 0; } + + outputArray.length = 0; + + var tilemap = layer.tilemapLayer.tilemap; + var tilemapLayer = layer.tilemapLayer; + + var mapData = layer.data; + var mapWidth = layer.width; + var mapHeight = layer.height; + + // 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. + var tileW = Math.floor(tilemap.tileWidth * tilemapLayer.scaleX); + var tileH = Math.floor(tilemap.tileHeight * tilemapLayer.scaleY); + + var drawLeft = 0; + var drawRight = mapWidth; + var drawTop = 0; + var drawBottom = mapHeight; + + if (!tilemapLayer.skipCull && tilemapLayer.scrollFactorX === 1 && tilemapLayer.scrollFactorY === 1) + { + // Camera world view bounds, snapped for scaled tile size + // Cull Padding values are given in tiles, not pixels + + var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; + var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; + var boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; + var boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; + + drawLeft = Math.max(0, boundsLeft); + drawRight = Math.min(mapWidth, boundsRight); + drawTop = Math.max(0, boundsTop); + drawBottom = Math.min(mapHeight, boundsBottom); + } + + var x; + var y; + var tile; + + if (renderOrder === 0) + { + // right-down + + for (y = drawTop; y < drawBottom; y++) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 1) + { + // left-down + + for (y = drawTop; y < drawBottom; y++) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 2) + { + // right-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + + tilemapLayer.tilesDrawn = outputArray.length; + tilemapLayer.tilesTotal = mapWidth * mapHeight; + + return outputArray; +}; + +module.exports = CullTiles; + + +/***/ }), +/* 1392 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); +var CalculateFacesWithin = __webpack_require__(59); +var SetTileCollision = __webpack_require__(79); + +/** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * @function Phaser.Tilemaps.Components.Fill + * @private + * @since 3.0.0 + * + * @param {integer} index - The tile index to fill the area with. + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {boolean} recalculateFaces - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The tile layer to use. If not given the current layer is used. + */ +var Fill = function (index, tileX, tileY, width, height, recalculateFaces, layer) +{ + var doesIndexCollide = (layer.collideIndexes.indexOf(index) !== -1); + + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + tiles[i].index = index; + + SetTileCollision(tiles[i], doesIndexCollide); + } + + if (recalculateFaces) + { + // Recalculate the faces within the area and neighboring tiles + CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer); + } +}; + +module.exports = Fill; + + +/***/ }), +/* 1393 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @function Phaser.Tilemaps.Components.FilterTiles + * @private + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} The filtered array of Tiles. + */ +var FilterTiles = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + + return tiles.filter(callback, context); +}; + +module.exports = FilterTiles; + + + +/***/ }), +/* 1394 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * + * @function Phaser.Tilemaps.Components.FindByIndex + * @private + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?Phaser.Tilemaps.Tile} The first (or n skipped) tile with the matching index. + */ +var FindByIndex = function (findIndex, skip, reverse, layer) +{ + if (skip === undefined) { skip = 0; } + if (reverse === undefined) { reverse = false; } + + var count = 0; + var tx; + var ty; + var tile; + + if (reverse) + { + for (ty = layer.height - 1; ty >= 0; ty--) + { + for (tx = layer.width - 1; tx >= 0; tx--) + { + tile = layer.data[ty][tx]; + if (tile && tile.index === findIndex) + { + if (count === skip) + { + return tile; + } + else + { + count += 1; + } + } + } + } + } + else + { + for (ty = 0; ty < layer.height; ty++) + { + for (tx = 0; tx < layer.width; tx++) + { + tile = layer.data[ty][tx]; + if (tile && tile.index === findIndex) + { + if (count === skip) + { + return tile; + } + else + { + count += 1; + } + } + } + } + } + + return null; +}; + +module.exports = FindByIndex; + + +/***/ }), +/* 1395 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * @callback FindTileCallback + * + * @param {Phaser.Tilemaps.Tile} value - The Tile. + * @param {integer} index - The index of the tile. + * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. + * + * @return {boolean} Return `true` if the callback should run, otherwise `false`. + */ + +/** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * + * @function Phaser.Tilemaps.Components.FindTile + * @private + * @since 3.0.0 + * + * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?Phaser.Tilemaps.Tile} A Tile that matches the search, or null if no Tile found + */ +var FindTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + return tiles.find(callback, context) || null; +}; + +module.exports = FindTile; + + +/***/ }), +/* 1396 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * @callback EachTileCallback + * + * @param {Phaser.Tilemaps.Tile} value - The Tile. + * @param {integer} index - The index of the tile. + * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. + */ + +/** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * @function Phaser.Tilemaps.Components.ForEachTile + * @private + * @since 3.0.0 + * + * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var ForEachTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + + tiles.forEach(callback, context); +}; + +module.exports = ForEachTile; + + +/***/ }), +/* 1397 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTileAt = __webpack_require__(151); +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); + +/** + * Gets a tile at the given world coordinates from the given layer. + * + * @function Phaser.Tilemaps.Components.GetTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ +var GetTileAtWorldXY = function (worldX, worldY, nonNull, camera, layer) +{ + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + + return GetTileAt(tileX, tileY, nonNull, layer); +}; + +module.exports = GetTileAtWorldXY; + + +/***/ }), +/* 1398 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Geom = __webpack_require__(453); +var GetTilesWithin = __webpack_require__(26); +var Intersects = __webpack_require__(454); +var NOOP = __webpack_require__(2); +var TileToWorldX = __webpack_require__(152); +var TileToWorldY = __webpack_require__(153); +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); + +var TriangleToRectangle = function (triangle, rect) +{ + return Intersects.RectangleToTriangle(rect, triangle); +}; + +// Note: Could possibly be optimized by copying the shape and shifting it into tilemapLayer +// coordinates instead of shifting the tiles. + +/** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * + * @function Phaser.Tilemaps.Components.GetTilesWithinShape + * @private + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. + */ +var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) +{ + if (shape === undefined) { return []; } + + // intersectTest is a function with parameters: shape, rect + var intersectTest = NOOP; + if (shape instanceof Geom.Circle) { intersectTest = Intersects.CircleToRectangle; } + else if (shape instanceof Geom.Rectangle) { intersectTest = Intersects.RectangleToRectangle; } + else if (shape instanceof Geom.Triangle) { intersectTest = TriangleToRectangle; } + else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle; } + + // Top left corner of the shapes's bounding box, rounded down to include partial tiles + var xStart = WorldToTileX(shape.left, true, camera, layer); + var yStart = WorldToTileY(shape.top, true, camera, layer); + + // Bottom right corner of the shapes's bounding box, rounded up to include partial tiles + var xEnd = Math.ceil(WorldToTileX(shape.right, false, camera, layer)); + var yEnd = Math.ceil(WorldToTileY(shape.bottom, false, camera, layer)); + + // 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). + var width = Math.max(xEnd - xStart, 1); + var height = Math.max(yEnd - yStart, 1); + var tiles = GetTilesWithin(xStart, yStart, width, height, filteringOptions, layer); + + var tileWidth = layer.tileWidth; + var tileHeight = layer.tileHeight; + if (layer.tilemapLayer) + { + tileWidth *= layer.tilemapLayer.scaleX; + tileHeight *= layer.tilemapLayer.scaleY; + } + + var results = []; + var tileRect = new Geom.Rectangle(0, 0, tileWidth, tileHeight); + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + tileRect.x = TileToWorldX(tile.x, camera, layer); + tileRect.y = TileToWorldY(tile.y, camera, layer); + if (intersectTest(shape, tileRect)) + { + results.push(tile); + } + } + + return results; +}; + +module.exports = GetTilesWithinShape; + + +/***/ }), +/* 1399 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); + +/** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * + * @function Phaser.Tilemaps.Components.GetTilesWithinWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The world x coordinate for the top-left of the area. + * @param {number} worldY - The world y coordinate for the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. + */ +var GetTilesWithinWorldXY = function (worldX, worldY, width, height, filteringOptions, camera, layer) +{ + // Top left corner of the rect, rounded down to include partial tiles + var xStart = WorldToTileX(worldX, true, camera, layer); + var yStart = WorldToTileY(worldY, true, camera, layer); + + // Bottom right corner of the rect, rounded up to include partial tiles + var xEnd = Math.ceil(WorldToTileX(worldX + width, false, camera, layer)); + var yEnd = Math.ceil(WorldToTileY(worldY + height, false, camera, layer)); + + return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer); +}; + +module.exports = GetTilesWithinWorldXY; + + +/***/ }), +/* 1400 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HasTileAt = __webpack_require__(514); +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); + +/** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @function Phaser.Tilemaps.Components.HasTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate of the world position. + * @param {number} worldY - The Y coordinate of the world position. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ +var HasTileAtWorldXY = function (worldX, worldY, camera, layer) +{ + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + + return HasTileAt(tileX, tileY, layer); +}; + +module.exports = HasTileAtWorldXY; + + +/***/ }), +/* 1401 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PutTileAt = __webpack_require__(246); +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); + +/** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * @function Phaser.Tilemaps.Components.PutTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. + */ +var PutTileAtWorldXY = function (tile, worldX, worldY, recalculateFaces, camera, layer) +{ + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + return PutTileAt(tile, tileX, tileY, recalculateFaces, layer); +}; + +module.exports = PutTileAtWorldXY; + + +/***/ }), +/* 1402 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CalculateFacesWithin = __webpack_require__(59); +var PutTileAt = __webpack_require__(246); + +/** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * @function Phaser.Tilemaps.Components.PutTilesAt + * @private + * @since 3.0.0 + * + * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var PutTilesAt = function (tilesArray, tileX, tileY, recalculateFaces, layer) +{ + if (!Array.isArray(tilesArray)) { return null; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + // Force the input array to be a 2D array + if (!Array.isArray(tilesArray[0])) + { + tilesArray = [ tilesArray ]; + } + + var height = tilesArray.length; + var width = tilesArray[0].length; + + for (var ty = 0; ty < height; ty++) + { + for (var tx = 0; tx < width; tx++) + { + var tile = tilesArray[ty][tx]; + PutTileAt(tile, tileX + tx, tileY + ty, false, layer); + } + } + + if (recalculateFaces) + { + // Recalculate the faces within the destination area and neighboring tiles + CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer); + } +}; + +module.exports = PutTilesAt; + + + +/***/ }), +/* 1403 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); +var GetRandom = __webpack_require__(198); + +/** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * @function Phaser.Tilemaps.Components.Randomize + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var Randomize = function (tileX, tileY, width, height, indexes, layer) +{ + var i; + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + // If no indices are given, then find all the unique indexes within the specified region + if (indexes === undefined) + { + indexes = []; + for (i = 0; i < tiles.length; i++) + { + if (indexes.indexOf(tiles[i].index) === -1) + { + indexes.push(tiles[i].index); + } + } + } + + for (i = 0; i < tiles.length; i++) + { + tiles[i].index = GetRandom(indexes); + } +}; + +module.exports = Randomize; + + +/***/ }), +/* 1404 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RemoveTileAt = __webpack_require__(515); +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); + +/** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. + */ +var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) +{ + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); +}; + +module.exports = RemoveTileAtWorldXY; + + +/***/ }), +/* 1405 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); +var Color = __webpack_require__(378); + +var defaultTileColor = new Color(105, 210, 231, 150); +var defaultCollidingTileColor = new Color(243, 134, 48, 200); +var defaultFaceColor = new Color(40, 39, 37, 150); + +/** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * @function Phaser.Tilemaps.Components.RenderDebug + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {object} styleConfig - An object specifying the colors to use for the debug drawing. + * @param {?Phaser.Display.Color} [styleConfig.tileColor=blue] - Color to use for drawing a filled rectangle at + * non-colliding tile locations. If set to null, non-colliding tiles will not be drawn. + * @param {?Phaser.Display.Color} [styleConfig.collidingTileColor=orange] - Color to use for drawing a filled + * rectangle at colliding tile locations. If set to null, colliding tiles will not be drawn. + * @param {?Phaser.Display.Color} [styleConfig.faceColor=grey] - Color to use for drawing a line at interesting + * tile faces. If set to null, interesting tile faces will not be drawn. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var RenderDebug = function (graphics, styleConfig, layer) +{ + if (styleConfig === undefined) { styleConfig = {}; } + + // Default colors without needlessly creating Color objects + var tileColor = (styleConfig.tileColor !== undefined) ? styleConfig.tileColor : defaultTileColor; + var collidingTileColor = (styleConfig.collidingTileColor !== undefined) ? styleConfig.collidingTileColor : defaultCollidingTileColor; + var faceColor = (styleConfig.faceColor !== undefined) ? styleConfig.faceColor : defaultFaceColor; + + var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); + + graphics.translateCanvas(layer.tilemapLayer.x, layer.tilemapLayer.y); + graphics.scaleCanvas(layer.tilemapLayer.scaleX, layer.tilemapLayer.scaleY); + + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + var tw = tile.width; + var th = tile.height; + var x = tile.pixelX; + var y = tile.pixelY; + + var color = tile.collides ? collidingTileColor : tileColor; + + if (color !== null) + { + graphics.fillStyle(color.color, color.alpha / 255); + graphics.fillRect(x, y, tw, th); + } + + // Inset the face line to prevent neighboring tile's lines from overlapping + x += 1; + y += 1; + tw -= 2; + th -= 2; + + if (faceColor !== null) + { + graphics.lineStyle(1, faceColor.color, faceColor.alpha / 255); + + if (tile.faceTop) { graphics.lineBetween(x, y, x + tw, y); } + if (tile.faceRight) { graphics.lineBetween(x + tw, y, x + tw, y + th); } + if (tile.faceBottom) { graphics.lineBetween(x, y + th, x + tw, y + th); } + if (tile.faceLeft) { graphics.lineBetween(x, y, x, y + th); } + } + } +}; + +module.exports = RenderDebug; + + +/***/ }), +/* 1406 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = __webpack_require__(79); +var CalculateFacesWithin = __webpack_require__(59); +var SetLayerCollisionIndex = __webpack_require__(247); + +/** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollision + * @private + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * @param {boolean} updateLayer - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + */ +var SetCollision = function (indexes, collides, recalculateFaces, layer, updateLayer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + if (!Array.isArray(indexes)) { indexes = [ indexes ]; } + if (updateLayer === undefined) { updateLayer = true; } + + // Update the array of colliding indexes + for (var i = 0; i < indexes.length; i++) + { + SetLayerCollisionIndex(indexes[i], collides, layer); + } + + // Update the tiles + if (updateLayer) + { + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (tile && indexes.indexOf(tile.index) !== -1) + { + SetTileCollision(tile, collides); + } + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollision; + + +/***/ }), +/* 1407 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = __webpack_require__(79); +var CalculateFacesWithin = __webpack_require__(59); +var SetLayerCollisionIndex = __webpack_require__(247); + +/** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollisionBetween + * @private + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + */ +var SetCollisionBetween = function (start, stop, collides, recalculateFaces, layer, updateLayer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + if (updateLayer === undefined) { updateLayer = true; } + + if (start > stop) { return; } + + // Update the array of colliding indexes + for (var index = start; index <= stop; index++) + { + SetLayerCollisionIndex(index, collides, layer); + } + + // Update the tiles + if (updateLayer) + { + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (tile) + { + if (tile.index >= start && tile.index <= stop) + { + SetTileCollision(tile, collides); + } + } + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionBetween; + + +/***/ }), +/* 1408 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = __webpack_require__(79); +var CalculateFacesWithin = __webpack_require__(59); +var SetLayerCollisionIndex = __webpack_require__(247); + +/** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollisionByExclusion + * @private + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetCollisionByExclusion = function (indexes, collides, recalculateFaces, layer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + if (!Array.isArray(indexes)) { indexes = [ indexes ]; } + + // Note: this only updates layer.collideIndexes for tile indexes found currently in the layer + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + if (tile && indexes.indexOf(tile.index) === -1) + { + SetTileCollision(tile, collides); + SetLayerCollisionIndex(tile.index, collides, layer); + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionByExclusion; + + +/***/ }), +/* 1409 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = __webpack_require__(79); +var CalculateFacesWithin = __webpack_require__(59); +var HasValue = __webpack_require__(91); + +/** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * @function Phaser.Tilemaps.Components.SetCollisionByProperty + * @private + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetCollisionByProperty = function (properties, collides, recalculateFaces, layer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (!tile) { continue; } + + for (var property in properties) + { + if (!HasValue(tile.properties, property)) { continue; } + + var values = properties[property]; + if (!Array.isArray(values)) + { + values = [ values ]; + } + + for (var i = 0; i < values.length; i++) + { + if (tile.properties[property] === values[i]) + { + SetTileCollision(tile, collides); + } + } + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionByProperty; + + +/***/ }), +/* 1410 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = __webpack_require__(79); +var CalculateFacesWithin = __webpack_require__(59); + +/** + * Sets collision on the tiles within a layer by checking each tile's collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tile's collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollisionFromCollisionGroup + * @private + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetCollisionFromCollisionGroup = function (collides, recalculateFaces, layer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (!tile) { continue; } + + var collisionGroup = tile.getCollisionGroup(); + + // It's possible in Tiled to have a collision group without any shapes, e.g. create a + // shape and then delete the shape. + if (collisionGroup && collisionGroup.objects && collisionGroup.objects.length > 0) + { + SetTileCollision(tile, collides); + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionFromCollisionGroup; + + +/***/ }), +/* 1411 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * @function Phaser.Tilemaps.Components.SetTileIndexCallback + * @private + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetTileIndexCallback = function (indexes, callback, callbackContext, layer) +{ + if (typeof indexes === 'number') + { + layer.callbacks[indexes] = (callback !== null) + ? { callback: callback, callbackContext: callbackContext } + : undefined; + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + layer.callbacks[indexes[i]] = (callback !== null) + ? { callback: callback, callbackContext: callbackContext } + : undefined; + } + } +}; + +module.exports = SetTileIndexCallback; + + +/***/ }), +/* 1412 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * @function Phaser.Tilemaps.Components.SetTileLocationCallback + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetTileLocationCallback = function (tileX, tileY, width, height, callback, callbackContext, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + tiles[i].setCollisionCallback(callback, callbackContext); + } + +}; + +module.exports = SetTileLocationCallback; + + +/***/ }), +/* 1413 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); +var ShuffleArray = __webpack_require__(122); + +/** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * @function Phaser.Tilemaps.Components.Shuffle + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var Shuffle = function (tileX, tileY, width, height, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + var indexes = tiles.map(function (tile) { return tile.index; }); + ShuffleArray(indexes); + + for (var i = 0; i < tiles.length; i++) + { + tiles[i].index = indexes[i]; + } +}; + +module.exports = Shuffle; + + +/***/ }), +/* 1414 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * @function Phaser.Tilemaps.Components.SwapByIndex + * @private + * @since 3.0.0 + * + * @param {integer} tileA - First tile index. + * @param {integer} tileB - Second tile index. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SwapByIndex = function (indexA, indexB, tileX, tileY, width, height, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + for (var i = 0; i < tiles.length; i++) + { + if (tiles[i]) + { + if (tiles[i].index === indexA) + { + tiles[i].index = indexB; + } + else if (tiles[i].index === indexB) + { + tiles[i].index = indexA; + } + } + } +}; + +module.exports = SwapByIndex; + + +/***/ }), +/* 1415 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TileToWorldX = __webpack_require__(152); +var TileToWorldY = __webpack_require__(153); +var Vector2 = __webpack_require__(3); + +/** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.TileToWorldXY + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in world coordinates. + */ +var TileToWorldXY = function (tileX, tileY, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + point.x = TileToWorldX(tileX, camera, layer); + point.y = TileToWorldY(tileY, camera, layer); + + return point; +}; + +module.exports = TileToWorldXY; + + +/***/ }), +/* 1416 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = __webpack_require__(26); + +/** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * @function Phaser.Tilemaps.Components.WeightedRandomize + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var WeightedRandomize = function (tileX, tileY, width, height, weightedIndexes, layer) +{ + if (weightedIndexes === undefined) { return; } + + var i; + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + var weightTotal = 0; + for (i = 0; i < weightedIndexes.length; i++) + { + weightTotal += weightedIndexes[i].weight; + } + + if (weightTotal <= 0) { return; } + + for (i = 0; i < tiles.length; i++) + { + var rand = Math.random() * weightTotal; + var sum = 0; + var randomIndex = -1; + for (var j = 0; j < weightedIndexes.length; j++) + { + sum += weightedIndexes[j].weight; + if (rand <= sum) + { + var chosen = weightedIndexes[j].index; + randomIndex = Array.isArray(chosen) + ? chosen[Math.floor(Math.random() * chosen.length)] + : chosen; + break; + } + } + + tiles[i].index = randomIndex; + } +}; + +module.exports = WeightedRandomize; + + +/***/ }), +/* 1417 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var WorldToTileX = __webpack_require__(69); +var WorldToTileY = __webpack_require__(70); +var Vector2 = __webpack_require__(3); + +/** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.WorldToTileXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in tile units. + */ +var WorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + point.x = WorldToTileX(worldX, snapToFloor, camera, layer); + point.y = WorldToTileY(worldY, snapToFloor, camera, layer); + + return point; +}; + +module.exports = WorldToTileXY; + + +/***/ }), +/* 1418 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Parsers + */ + +module.exports = { + + Parse: __webpack_require__(516), + Parse2DArray: __webpack_require__(248), + ParseCSV: __webpack_require__(517), + + Impact: __webpack_require__(1419), + Tiled: __webpack_require__(1420) + +}; + + +/***/ }), +/* 1419 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Parsers.Impact + */ + +module.exports = { + + ParseTileLayers: __webpack_require__(530), + ParseTilesets: __webpack_require__(531), + ParseWeltmeister: __webpack_require__(529) + +}; + + +/***/ }), +/* 1420 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Parsers.Tiled + */ + +module.exports = { + + AssignTileProperties: __webpack_require__(528), + Base64Decode: __webpack_require__(520), + BuildTilesetIndex: __webpack_require__(527), + ParseGID: __webpack_require__(249), + ParseImageLayers: __webpack_require__(521), + ParseJSONTiled: __webpack_require__(518), + ParseObject: __webpack_require__(251), + ParseObjectLayers: __webpack_require__(525), + ParseTileLayers: __webpack_require__(519), + ParseTilesets: __webpack_require__(522) + +}; + + +/***/ }), +/* 1421 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1422); +} + +if (true) +{ + renderCanvas = __webpack_require__(1423); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1422 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera) +{ + src.cull(camera); + + var renderTiles = src.culledTiles; + var tileCount = renderTiles.length; + var alpha = camera.alpha * src.alpha; + + if (tileCount === 0 || alpha <= 0) + { + return; + } + + var gidMap = src.gidMap; + var pipeline = src.pipeline; + + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + + var scrollFactorX = src.scrollFactorX; + var scrollFactorY = src.scrollFactorY; + + var x = src.x; + var y = src.y; + + var sx = src.scaleX; + var sy = src.scaleY; + + var tilesets = src.tileset; + + // Loop through each tileset in this layer, drawing just the tiles that are in that set each time + // Doing it this way around allows us to batch tiles using the same tileset + for (var c = 0; c < tilesets.length; c++) + { + var currentSet = tilesets[c]; + var texture = currentSet.glTexture; + + for (var i = 0; i < tileCount; i++) + { + var tile = renderTiles[i]; + + var tileset = gidMap[tile.index]; + + if (tileset !== currentSet) + { + // Skip tiles that aren't in this set + continue; + } + + var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); + + if (tileTexCoords === null) + { + continue; + } + + var frameWidth = tile.width; + var frameHeight = tile.height; + + var frameX = tileTexCoords.x; + var frameY = tileTexCoords.y; + + var tw = tile.width * 0.5; + var th = tile.height * 0.5; + + var tint = getTint(tile.tint, alpha * tile.alpha); + + pipeline.batchTexture( + src, + texture, + texture.width, texture.height, + x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy), + tile.width, tile.height, + sx, sy, + tile.rotation, + tile.flipX, tile.flipY, + scrollFactorX, scrollFactorY, + tw, th, + frameX, frameY, frameWidth, frameHeight, + tint, tint, tint, tint, false, + 0, 0, + camera, + null, + true + ); + } + } +}; + +module.exports = DynamicTilemapLayerWebGLRenderer; + + +/***/ }), +/* 1423 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.cull(camera); + + var renderTiles = src.culledTiles; + var tileCount = renderTiles.length; + + if (tileCount === 0) + { + return; + } + + var camMatrix = renderer._tempMatrix1; + var layerMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + var ctx = renderer.currentContext; + var gidMap = src.gidMap; + + ctx.save(); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + layerMatrix.e = src.x; + layerMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(layerMatrix, calcMatrix); + + calcMatrix.copyToContext(ctx); + } + else + { + layerMatrix.e -= camera.scrollX * src.scrollFactorX; + layerMatrix.f -= camera.scrollY * src.scrollFactorY; + + layerMatrix.copyToContext(ctx); + } + + var alpha = camera.alpha * src.alpha; + + if (!renderer.antialias || src.scaleX > 1 || src.scaleY > 1) + { + ctx.imageSmoothingEnabled = false; + } + + for (var i = 0; i < tileCount; i++) + { + var tile = renderTiles[i]; + + var tileset = gidMap[tile.index]; + + if (!tileset) + { + continue; + } + + var image = tileset.image.getSourceImage(); + var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); + + if (tileTexCoords) + { + var halfWidth = tile.width / 2; + var halfHeight = tile.height / 2; + + ctx.save(); + + ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); + + if (tile.rotation !== 0) + { + ctx.rotate(tile.rotation); + } + + if (tile.flipX || tile.flipY) + { + ctx.scale((tile.flipX) ? -1 : 1, (tile.flipY) ? -1 : 1); + } + + ctx.globalAlpha = alpha * tile.alpha; + + ctx.drawImage( + image, + tileTexCoords.x, tileTexCoords.y, + tile.width, tile.height, + -halfWidth, -halfHeight, + tile.width, tile.height + ); + + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = DynamicTilemapLayerCanvasRenderer; + + +/***/ }), +/* 1424 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = __webpack_require__(2); +var renderCanvas = __webpack_require__(2); + +if (true) +{ + renderWebGL = __webpack_require__(1425); +} + +if (true) +{ + renderCanvas = __webpack_require__(1426); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; + + +/***/ }), +/* 1425 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * A Static Tilemap Layer renders immediately and does not use any batching. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var StaticTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera) +{ + var tilesets = src.tileset; + + var pipeline = src.pipeline; + var pipelineVertexBuffer = pipeline.vertexBuffer; + + renderer.setPipeline(pipeline); + + pipeline.modelIdentity(); + pipeline.modelTranslate(src.x - (camera.scrollX * src.scrollFactorX), src.y - (camera.scrollY * src.scrollFactorY), 0); + pipeline.modelScale(src.scaleX, src.scaleY, 1); + pipeline.viewLoad2D(camera.matrix.matrix); + + for (var i = 0; i < tilesets.length; i++) + { + src.upload(camera, i); + + if (src.vertexCount[i] > 0) + { + if (renderer.currentPipeline && renderer.currentPipeline.vertexCount > 0) + { + renderer.flush(); + } + + pipeline.vertexBuffer = src.vertexBuffer[i]; + + renderer.setPipeline(pipeline); + + renderer.setTexture2D(tilesets[i].glTexture, 0); + + renderer.gl.drawArrays(pipeline.topology, 0, src.vertexCount[i]); + } + } + + // Restore the pipeline + pipeline.vertexBuffer = pipelineVertexBuffer; + + pipeline.viewIdentity(); + pipeline.modelIdentity(); +}; + +module.exports = StaticTilemapLayerWebGLRenderer; + + +/***/ }), +/* 1426 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var StaticTilemapLayerCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.cull(camera); + + var renderTiles = src.culledTiles; + var tileCount = renderTiles.length; + + if (tileCount === 0) + { + return; + } + + var camMatrix = renderer._tempMatrix1; + var layerMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + var ctx = renderer.currentContext; + var gidMap = src.gidMap; + + ctx.save(); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + layerMatrix.e = src.x; + layerMatrix.f = src.y; + + camMatrix.multiply(layerMatrix, calcMatrix); + + calcMatrix.copyToContext(ctx); + } + else + { + // Undo the camera scroll + layerMatrix.e -= camera.scrollX * src.scrollFactorX; + layerMatrix.f -= camera.scrollY * src.scrollFactorY; + + layerMatrix.copyToContext(ctx); + } + + var alpha = camera.alpha * src.alpha; + + if (!renderer.antialias || src.scaleX > 1 || src.scaleY > 1) + { + ctx.imageSmoothingEnabled = false; + } + + for (var i = 0; i < tileCount; i++) + { + var tile = renderTiles[i]; + + var tileset = gidMap[tile.index]; + + if (!tileset) + { + continue; + } + + var image = tileset.image.getSourceImage(); + var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); + + if (tileTexCoords) + { + var tileWidth = tileset.tileWidth; + var tileHeight = tileset.tileHeight; + var halfWidth = tileWidth / 2; + var halfHeight = tileHeight / 2; + + ctx.save(); + + ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); + + if (tile.rotation !== 0) + { + ctx.rotate(tile.rotation); + } + + if (tile.flipX || tile.flipY) + { + ctx.scale((tile.flipX) ? -1 : 1, (tile.flipY) ? -1 : 1); + } + + ctx.globalAlpha = alpha * tile.alpha; + + ctx.drawImage( + image, + tileTexCoords.x, tileTexCoords.y, + tileWidth, tileHeight, + -halfWidth, -halfHeight, + tileWidth, tileHeight + ); + + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = StaticTilemapLayerCanvasRenderer; + + +/***/ }), +/* 1427 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = __webpack_require__(16); +var ParseToTilemap = __webpack_require__(252); + +/** + * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. + * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing + * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map + * data. For an empty map, you should specify tileWidth, tileHeight, width & height. + * + * @method Phaser.GameObjects.GameObjectCreator#tilemap + * @since 3.0.0 + * + * @param {Phaser.Types.Tilemaps.TilemapConfig} [config] - The config options for the Tilemap. + * + * @return {Phaser.Tilemaps.Tilemap} + */ +GameObjectCreator.register('tilemap', function (config) +{ + // Defaults are applied in ParseToTilemap + var c = (config !== undefined) ? config : {}; + + return ParseToTilemap( + this.scene, + c.key, + c.tileWidth, + c.tileHeight, + c.width, + c.height, + c.data, + c.insertNull + ); +}); + + +/***/ }), +/* 1428 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = __webpack_require__(6); +var ParseToTilemap = __webpack_require__(252); + +/** + * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. + * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing + * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map + * data. For an empty map, you should specify tileWidth, tileHeight, width & height. + * + * @method Phaser.GameObjects.GameObjectFactory#tilemap + * @since 3.0.0 + * + * @param {string} [key] - The key in the Phaser cache that corresponds to the loaded tilemap data. + * @param {integer} [tileWidth=32] - The width of a tile in pixels. Pass in `null` to leave as the + * default. + * @param {integer} [tileHeight=32] - The height of a tile in pixels. Pass in `null` to leave as the + * default. + * @param {integer} [width=10] - The width of the map in tiles. Pass in `null` to leave as the + * default. + * @param {integer} [height=10] - The height of the map in tiles. Pass in `null` to leave as the + * default. + * @param {integer[][]} [data] - Instead of loading from the cache, you can also load directly from + * a 2D array of tile indexes. Pass in `null` for no data. + * @param {boolean} [insertNull=false] - 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've 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.Tilemap} + */ +GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, width, height, data, insertNull) +{ + // 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. + + if (key === null) { key = undefined; } + if (tileWidth === null) { tileWidth = undefined; } + if (tileHeight === null) { tileHeight = undefined; } + if (width === null) { width = undefined; } + if (height === null) { height = undefined; } + + return ParseToTilemap(this.scene, key, tileWidth, tileHeight, width, height, data, insertNull); +}); + +// 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 + + +/***/ }), +/* 1429 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Time + */ + +module.exports = { + + Clock: __webpack_require__(1430), + TimerEvent: __webpack_require__(535) + +}; + + +/***/ }), +/* 1430 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); +var TimerEvent = __webpack_require__(535); + +/** + * @classdesc + * The Clock is a Scene plugin which creates and updates Timer Events for its Scene. + * + * @class Clock + * @memberof Phaser.Time + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which owns this Clock. + */ +var Clock = new Class({ + + initialize: + + function Clock (scene) + { + /** + * The Scene which owns this Clock. + * + * @name Phaser.Time.Clock#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene Systems object of the Scene which owns this Clock. + * + * @name Phaser.Time.Clock#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The current time of the Clock, in milliseconds. + * + * If accessed externally, this is equivalent to the `time` parameter normally passed to a Scene's `update` method. + * + * @name Phaser.Time.Clock#now + * @type {number} + * @since 3.0.0 + */ + this.now = 0; + + // Scale the delta time coming into the Clock by this factor + // which then influences anything using this Clock for calculations, like TimerEvents + + /** + * The scale of the Clock's time delta. + * + * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Clock and anything which uses it, such as its Timer Events. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing the Clock. + * + * @name Phaser.Time.Clock#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Whether the Clock is paused (`true`) or active (`false`). + * + * When paused, the Clock will not update any of its Timer Events, thus freezing time. + * + * @name Phaser.Time.Clock#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * An array of all Timer Events whose delays haven't expired - these are actively updating Timer Events. + * + * @name Phaser.Time.Clock#_active + * @type {Phaser.Time.TimerEvent[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._active = []; + + /** + * An array of all Timer Events which will be added to the Clock at the start of the frame. + * + * @name Phaser.Time.Clock#_pendingInsertion + * @type {Phaser.Time.TimerEvent[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingInsertion = []; + + /** + * An array of all Timer Events which will be removed from the Clock at the start of the frame. + * + * @name Phaser.Time.Clock#_pendingRemoval + * @type {Phaser.Time.TimerEvent[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingRemoval = []; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Time.Clock#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + // Sync with the TimeStep + this.now = this.systems.game.loop.time; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Time.Clock#start + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.on(SceneEvents.UPDATE, this.update, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Creates a Timer Event and adds it to the Clock at the start of the frame. + * + * @method Phaser.Time.Clock#addEvent + * @since 3.0.0 + * + * @param {Phaser.Types.Time.TimerEventConfig} config - The configuration for the Timer Event. + * + * @return {Phaser.Time.TimerEvent} The Timer Event which was created. + */ + addEvent: function (config) + { + var event = new TimerEvent(config); + + this._pendingInsertion.push(event); + + return event; + }, + + /** + * Creates a Timer Event and adds it to the Clock at the start of the frame. + * + * This is a shortcut for {@link #addEvent} which can be shorter and is compatible with the syntax of the GreenSock Animation Platform (GSAP). + * + * @method Phaser.Time.Clock#delayedCall + * @since 3.0.0 + * + * @param {number} delay - The delay of the function call, in milliseconds. + * @param {function} callback - The function to call after the delay expires. + * @param {Array.<*>} [args] - The arguments to call the function with. + * @param {*} [callbackScope] - The scope (`this` object) to call the function with. + * + * @return {Phaser.Time.TimerEvent} The Timer Event which was created. + */ + delayedCall: function (delay, callback, args, callbackScope) + { + return this.addEvent({ delay: delay, callback: callback, args: args, callbackScope: callbackScope }); + }, + + /** + * Clears and recreates the array of pending Timer Events. + * + * @method Phaser.Time.Clock#clearPendingEvents + * @since 3.0.0 + * + * @return {Phaser.Time.Clock} This Clock object. + */ + clearPendingEvents: function () + { + this._pendingInsertion = []; + + return this; + }, + + /** + * Schedules all active Timer Events for removal at the start of the frame. + * + * @method Phaser.Time.Clock#removeAllEvents + * @since 3.0.0 + * + * @return {Phaser.Time.Clock} This Clock object. + */ + removeAllEvents: function () + { + this._pendingRemoval = this._pendingRemoval.concat(this._active); + + return this; + }, + + /** + * Updates the arrays of active and pending Timer Events. Called at the start of the frame. + * + * @method Phaser.Time.Clock#preUpdate + * @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. + */ + preUpdate: function () + { + var toRemove = this._pendingRemoval.length; + var toInsert = this._pendingInsertion.length; + + if (toRemove === 0 && toInsert === 0) + { + // Quick bail + return; + } + + var i; + var event; + + // Delete old events + for (i = 0; i < toRemove; i++) + { + event = this._pendingRemoval[i]; + + var index = this._active.indexOf(event); + + if (index > -1) + { + this._active.splice(index, 1); + } + + // Pool them? + event.destroy(); + } + + for (i = 0; i < toInsert; i++) + { + event = this._pendingInsertion[i]; + + this._active.push(event); + } + + // Clear the lists + this._pendingRemoval.length = 0; + this._pendingInsertion.length = 0; + }, + + /** + * 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. + */ + update: function (time, delta) + { + this.now = time; + + if (this.paused) + { + return; + } + + delta *= this.timeScale; + + for (var i = 0; i < this._active.length; i++) + { + var event = this._active[i]; + + if (event.paused) + { + continue; + } + + // Use delta time to increase elapsed. + // Avoids needing to adjust for pause / resume. + // Automatically smoothed by TimeStep class. + // In testing accurate to +- 1ms! + event.elapsed += delta * event.timeScale; + + if (event.elapsed >= event.delay) + { + var remainder = event.elapsed - event.delay; + + // Limit it, in case it's checked in the callback + event.elapsed = event.delay; + + // Process the event + if (!event.hasDispatched && event.callback) + { + event.hasDispatched = true; + event.callback.apply(event.callbackScope, event.args); + } + + if (event.repeatCount > 0) + { + event.repeatCount--; + + event.elapsed = remainder; + event.hasDispatched = false; + } + else + { + this._pendingRemoval.push(event); + } + } + } + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Time.Clock#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var i; + + for (i = 0; i < this._pendingInsertion.length; i++) + { + this._pendingInsertion[i].destroy(); + } + + for (i = 0; i < this._active.length; i++) + { + this._active[i].destroy(); + } + + for (i = 0; i < this._pendingRemoval.length; i++) + { + this._pendingRemoval[i].destroy(); + } + + this._active.length = 0; + this._pendingRemoval.length = 0; + this._pendingInsertion.length = 0; + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.off(SceneEvents.UPDATE, this.update, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Time.Clock#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('Clock', Clock, 'time'); + +module.exports = Clock; + + +/***/ }), +/* 1431 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(100); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Tweens + */ + +var Tweens = { + + Builders: __webpack_require__(1432), + Events: __webpack_require__(257), + + TweenManager: __webpack_require__(1447), + Tween: __webpack_require__(256), + TweenData: __webpack_require__(258), + Timeline: __webpack_require__(541) + +}; + +// Merge in the consts +Tweens = Extend(false, Tweens, CONST); + +module.exports = Tweens; + + +/***/ }), +/* 1432 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tweens.Builders + */ + +module.exports = { + + GetBoolean: __webpack_require__(99), + GetEaseFunction: __webpack_require__(90), + GetNewValue: __webpack_require__(155), + GetProps: __webpack_require__(536), + GetTargets: __webpack_require__(253), + GetTweens: __webpack_require__(537), + GetValueOp: __webpack_require__(254), + NumberTweenBuilder: __webpack_require__(538), + StaggerBuilder: __webpack_require__(539), + TimelineBuilder: __webpack_require__(540), + TweenBuilder: __webpack_require__(156) + +}; + + +/***/ }), +/* 1433 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// 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 +// 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: +// offset: Used when the Tween is part of a Timeline +// 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. +// useFrames: Use frames or milliseconds? +// yoyo: boolean - Does the tween reverse itself (yoyo) when it reaches the end? + +module.exports = [ + 'callbackScope', + 'completeDelay', + 'delay', + 'duration', + 'ease', + 'easeParams', + 'flipX', + 'flipY', + 'hold', + 'loop', + 'loopDelay', + 'offset', + 'onActive', + 'onActiveParams', + 'onActiveScope', + 'onComplete', + 'onCompleteParams', + 'onCompleteScope', + 'onLoop', + 'onLoopParams', + 'onLoopScope', + 'onRepeat', + 'onRepeatParams', + 'onRepeatScope', + 'onStart', + 'onStartParams', + 'onStartScope', + 'onUpdate', + 'onUpdateParams', + 'onUpdateScope', + 'onYoyo', + 'onYoyoParams', + 'onYoyoScope', + 'paused', + 'props', + 'repeat', + 'repeatDelay', + 'targets', + 'useFrames', + 'yoyo' +]; + + +/***/ }), +/* 1434 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Complete Event. + * + * This event is dispatched by a Tween Timeline when it completes playback. + * + * Listen to it from a Timeline instance using `Timeline.on('complete', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('complete', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_COMPLETE + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'complete'; + + +/***/ }), +/* 1435 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Loop Event. + * + * This event is dispatched by a Tween Timeline every time it loops. + * + * Listen to it from a Timeline instance using `Timeline.on('loop', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * loop: 4, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('loop', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_LOOP + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'loop'; + + +/***/ }), +/* 1436 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Pause Event. + * + * This event is dispatched by a Tween Timeline when it is paused. + * + * Listen to it from a Timeline instance using `Timeline.on('pause', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('pause', listener); + * // At some point later ... + * timeline.pause(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_PAUSE + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'pause'; + + +/***/ }), +/* 1437 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Resume Event. + * + * This event is dispatched by a Tween Timeline when it is resumed from a paused state. + * + * Listen to it from a Timeline instance using `Timeline.on('resume', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('resume', listener); + * // At some point later ... + * timeline.resume(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_RESUME + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'resume'; + + +/***/ }), +/* 1438 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Start Event. + * + * This event is dispatched by a Tween Timeline when it starts. + * + * Listen to it from a Timeline instance using `Timeline.on('start', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('start', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_START + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'start'; + + +/***/ }), +/* 1439 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Update Event. + * + * This event is dispatched by a Tween Timeline every time it updates, which can happen a lot of times per second, + * so be careful about listening to this event unless you absolutely require it. + * + * Listen to it from a Timeline instance using `Timeline.on('update', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('update', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'update'; + + +/***/ }), +/* 1440 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Active Event. + * + * This event is dispatched by a Tween when it becomes active within the Tween Manager. + * + * An 'active' Tween is one that is now progressing, although it may not yet be updating + * any target properties, due to settings such as `delay`. If you need an event for when + * the Tween starts actually updating its first property, see `TWEEN_START`. + * + * Listen to it from a Tween instance using `Tween.on('active', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('active', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_ACTIVE + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'active'; + + +/***/ }), +/* 1441 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Complete Event. + * + * This event is dispatched by a Tween when it completes playback entirely, factoring in repeats and loops. + * + * If the Tween has been set to loop or repeat infinitely, this event will not be dispatched + * unless the `Tween.stop` method is called. + * + * If a Tween has a `completeDelay` set, this event will fire after that delay expires. + * + * Listen to it from a Tween instance using `Tween.on('complete', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('complete', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_COMPLETE + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'complete'; + + +/***/ }), +/* 1442 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Loop Event. + * + * This event is dispatched by a Tween when it loops. + * + * This event will only be dispatched if the Tween has a loop count set. + * + * If a Tween has a `loopDelay` set, this event will fire after that delay expires. + * + * The difference between `loop` and `repeat` is that `repeat` is a property setting, + * where-as `loop` applies to the entire Tween. + * + * Listen to it from a Tween instance using `Tween.on('loop', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * loop: 6 + * }); + * tween.on('loop', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_LOOP + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'loop'; + + +/***/ }), +/* 1443 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Repeat Event. + * + * This event is dispatched by a Tween when one of the properties it is tweening repeats. + * + * This event will only be dispatched if the Tween has a property with a repeat count set. + * + * If a Tween has a `repeatDelay` set, this event will fire after that delay expires. + * + * The difference between `loop` and `repeat` is that `repeat` is a property setting, + * where-as `loop` applies to the entire Tween. + * + * Listen to it from a Tween instance using `Tween.on('repeat', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * repeat: 4 + * }); + * tween.on('repeat', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_REPEAT + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {string} key - The key of the property that just repeated. + * @param {any} target - The target that the property just repeated on. + */ +module.exports = 'repeat'; + + +/***/ }), +/* 1444 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Start Event. + * + * This event is dispatched by a Tween when it starts tweening its first property. + * + * A Tween will only emit this event once, as it can only start once. + * + * If a Tween has a `delay` set, this event will fire after that delay expires. + * + * Listen to it from a Tween instance using `Tween.on('start', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('start', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_START + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'start'; + + +/***/ }), +/* 1445 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Update Event. + * + * This event is dispatched by a Tween every time it updates _any_ of the properties it is tweening. + * + * A Tween that is changing 3 properties of a target will emit this event 3 times per change, once per property. + * + * **Note:** This is a very high frequency event and may be dispatched multiple times, every single frame. + * + * Listen to it from a Tween instance using `Tween.on('update', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * }); + * tween.on('update', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_UPDATE + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {string} key - The property that was updated, i.e. `x` or `scale`. + * @param {any} target - The target object that was updated. Usually a Game Object, but can be of any type. + * @param {number} current - The current value of the property that was tweened. + * @param {number} previous - The previous value of the property that was tweened, prior to this update. + */ +module.exports = 'update'; + + +/***/ }), +/* 1446 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Yoyo Event. + * + * This event is dispatched by a Tween whenever a property it is tweening yoyos. + * + * This event will only be dispatched if the Tween has a property with `yoyo` set. + * + * If the Tween has a `hold` value, this event is dispatched when the hold expires. + * + * This event is dispatched for every property, and for every target, that yoyos. + * For example, if a Tween was updating 2 properties and had 10 targets, this event + * would be dispatched 20 times (twice per target). So be careful how you use it! + * + * Listen to it from a Tween instance using `Tween.on('yoyo', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * yoyo: true + * }); + * tween.on('yoyo', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_YOYO + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {string} key - The property that yoyo'd, i.e. `x` or `scale`. + * @param {any} target - The target object that was yoyo'd. Usually a Game Object, but can be of any type. + */ +module.exports = 'yoyo'; + + +/***/ }), +/* 1447 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayRemove = __webpack_require__(130); +var Class = __webpack_require__(0); +var NumberTweenBuilder = __webpack_require__(538); +var PluginCache = __webpack_require__(22); +var SceneEvents = __webpack_require__(18); +var StaggerBuilder = __webpack_require__(539); +var TimelineBuilder = __webpack_require__(540); +var TWEEN_CONST = __webpack_require__(100); +var TweenBuilder = __webpack_require__(156); + +/** + * @classdesc + * The Tween Manager is a default Scene Plugin which controls and updates Tweens and Timelines. + * + * @class TweenManager + * @memberof Phaser.Tweens + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which owns this Tween Manager. + */ +var TweenManager = new Class({ + + initialize: + + function TweenManager (scene) + { + /** + * The Scene which owns this Tween Manager. + * + * @name Phaser.Tweens.TweenManager#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Systems object of the Scene which owns this Tween Manager. + * + * @name Phaser.Tweens.TweenManager#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The time scale of the Tween Manager. + * + * This value scales the time delta between two frames, thus influencing the speed of time for all Tweens owned by this Tween Manager. + * + * @name Phaser.Tweens.TweenManager#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * An array of Tweens and Timelines which will be added to the Tween Manager at the start of the frame. + * + * @name Phaser.Tweens.TweenManager#_add + * @type {array} + * @private + * @since 3.0.0 + */ + this._add = []; + + /** + * An array of Tweens and Timelines pending to be later added to the Tween Manager. + * + * @name Phaser.Tweens.TweenManager#_pending + * @type {array} + * @private + * @since 3.0.0 + */ + this._pending = []; + + /** + * An array of Tweens and Timelines which are still incomplete and are actively processed by the Tween Manager. + * + * @name Phaser.Tweens.TweenManager#_active + * @type {array} + * @private + * @since 3.0.0 + */ + this._active = []; + + /** + * An array of Tweens and Timelines which will be removed from the Tween Manager at the start of the frame. + * + * @name Phaser.Tweens.TweenManager#_destroy + * @type {array} + * @private + * @since 3.0.0 + */ + this._destroy = []; + + /** + * The number of Tweens and Timelines which need to be processed by the Tween Manager at the start of the frame. + * + * @name Phaser.Tweens.TweenManager#_toProcess + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._toProcess = 0; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Tweens.TweenManager#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Tweens.TweenManager#start + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.on(SceneEvents.UPDATE, this.update, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.timeScale = 1; + }, + + /** + * Create a Tween Timeline and return it, but do NOT add it to the active or pending Tween lists. + * + * @method Phaser.Tweens.TweenManager#createTimeline + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} [config] - The configuration object for the Timeline and its Tweens. + * + * @return {Phaser.Tweens.Timeline} The created Timeline object. + */ + createTimeline: function (config) + { + return TimelineBuilder(this, config); + }, + + /** + * Create a Tween Timeline and add it to the active Tween list/ + * + * @method Phaser.Tweens.TweenManager#timeline + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} [config] - The configuration object for the Timeline and its Tweens. + * + * @return {Phaser.Tweens.Timeline} The created Timeline object. + */ + timeline: function (config) + { + var timeline = TimelineBuilder(this, config); + + if (!timeline.paused) + { + this._add.push(timeline); + + this._toProcess++; + } + + return timeline; + }, + + /** + * Create a Tween and return it, but do NOT add it to the active or pending Tween lists. + * + * @method Phaser.Tweens.TweenManager#create + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The configuration object for the Tween. + * + * @return {Phaser.Tweens.Tween} The created Tween object. + */ + create: function (config) + { + return TweenBuilder(this, config); + }, + + /** + * Create a Tween and add it to the active Tween list. + * + * @method Phaser.Tweens.TweenManager#add + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The configuration object for the Tween. + * + * @return {Phaser.Tweens.Tween} The created Tween. + */ + add: function (config) + { + var tween = TweenBuilder(this, config); + + this._add.push(tween); + + this._toProcess++; + + return tween; + }, + + /** + * Add an existing tween into the active Tween list. + * + * @method Phaser.Tweens.TweenManager#existing + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to add. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager object. + */ + existing: function (tween) + { + this._add.push(tween); + + this._toProcess++; + + return this; + }, + + /** + * Create a Number Tween and add it to the active Tween list. + * + * @method Phaser.Tweens.TweenManager#addCounter + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.NumberTweenBuilderConfig} config - The configuration object for the Number Tween. + * + * @return {Phaser.Tweens.Tween} The created Number Tween. + */ + addCounter: function (config) + { + var tween = NumberTweenBuilder(this, config); + + this._add.push(tween); + + this._toProcess++; + + return tween; + }, + + /** + * 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' }) + * }); + * ``` + * + * @method Phaser.Tweens.TweenManager#stagger + * @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} config - The configuration object for the Stagger function. + * + * @return {function} The stagger function. + */ + stagger: function (value, options) + { + return StaggerBuilder(value, options); + }, + + /** + * Updates the Tween Manager's internal lists at the start of the frame. + * + * This method will return immediately if no changes have been indicated. + * + * @method Phaser.Tweens.TweenManager#preUpdate + * @since 3.0.0 + */ + preUpdate: function () + { + if (this._toProcess === 0) + { + // Quick bail + return; + } + + var list = this._destroy; + var active = this._active; + var pending = this._pending; + var i; + var tween; + + // Clear the 'destroy' list + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + // Remove from the 'active' array + var idx = active.indexOf(tween); + + if (idx === -1) + { + // Not in the active array, is it in pending instead? + idx = pending.indexOf(tween); + + if (idx > -1) + { + tween.state = TWEEN_CONST.REMOVED; + pending.splice(idx, 1); + } + } + else + { + tween.state = TWEEN_CONST.REMOVED; + active.splice(idx, 1); + } + } + + list.length = 0; + + // Process the addition list + // This stops callbacks and out of sync events from populating the active array mid-way during the update + + list = this._add; + + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + if (tween.state === TWEEN_CONST.PENDING_ADD) + { + // Return true if the Tween should be started right away, otherwise false + if (tween.init()) + { + tween.play(); + + this._active.push(tween); + } + else + { + this._pending.push(tween); + } + } + } + + list.length = 0; + + this._toProcess = 0; + }, + + /** + * Updates all Tweens and Timelines of the Tween Manager. + * + * @method Phaser.Tweens.TweenManager#update + * @since 3.0.0 + * + * @param {number} timestamp - The current time in milliseconds. + * @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update: function (timestamp, delta) + { + // Process active tweens + var list = this._active; + var tween; + + // Scale the delta + delta *= this.timeScale; + + for (var i = 0; i < list.length; i++) + { + tween = list[i]; + + // If Tween.update returns 'true' then it means it has completed, + // so move it to the destroy list + if (tween.update(timestamp, delta)) + { + this._destroy.push(tween); + this._toProcess++; + } + } + }, + + /** + * Removes the given tween from the Tween Manager, regardless of its state (pending or active). + * + * @method Phaser.Tweens.TweenManager#remove + * @since 3.17.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to be removed. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager object. + */ + remove: function (tween) + { + ArrayRemove(this._add, tween); + ArrayRemove(this._pending, tween); + ArrayRemove(this._active, tween); + ArrayRemove(this._destroy, tween); + + tween.state = TWEEN_CONST.REMOVED; + + return this; + }, + + /** + * Checks if a Tween or Timeline is active and adds it to the Tween Manager at the start of the frame if it isn't. + * + * @method Phaser.Tweens.TweenManager#makeActive + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to check. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager object. + */ + makeActive: function (tween) + { + if (this._add.indexOf(tween) !== -1 || this._active.indexOf(tween) !== -1) + { + return this; + } + + var idx = this._pending.indexOf(tween); + + if (idx !== -1) + { + this._pending.splice(idx, 1); + } + + this._add.push(tween); + + tween.state = TWEEN_CONST.PENDING_ADD; + + this._toProcess++; + + return this; + }, + + /** + * Passes all Tweens to the given callback. + * + * @method Phaser.Tweens.TweenManager#each + * @since 3.0.0 + * + * @param {function} callback - The function to call. + * @param {object} [scope] - The scope (`this` object) to call the function with. + * @param {...*} [args] - The arguments to pass into the function. Its first argument will always be the Tween currently being iterated. + */ + each: function (callback, scope) + { + var args = [ null ]; + + for (var i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var texture in this.list) + { + args[0] = this.list[texture]; + + callback.apply(scope, args); + } + }, + + /** + * Returns an array of all active Tweens and Timelines in the Tween Manager. + * + * @method Phaser.Tweens.TweenManager#getAllTweens + * @since 3.0.0 + * + * @return {Phaser.Tweens.Tween[]} A new array containing references to all active Tweens and Timelines. + */ + getAllTweens: function () + { + var list = this._active; + var output = []; + + for (var i = 0; i < list.length; i++) + { + output.push(list[i]); + } + + return output; + }, + + /** + * Returns the scale of the time delta for all Tweens and Timelines owned by this Tween Manager. + * + * @method Phaser.Tweens.TweenManager#getGlobalTimeScale + * @since 3.0.0 + * + * @return {number} The scale of the time delta, usually 1. + */ + getGlobalTimeScale: function () + { + return this.timeScale; + }, + + /** + * Returns an array of all Tweens or Timelines in the Tween Manager which affect the given target or array of targets. + * + * @method Phaser.Tweens.TweenManager#getTweensOf + * @since 3.0.0 + * + * @param {(object|array)} target - The target to look for. Provide an array to look for multiple targets. + * + * @return {Phaser.Tweens.Tween[]} A new array containing all Tweens and Timelines which affect the given target(s). + */ + getTweensOf: function (target) + { + var list = this._active; + var tween; + var output = []; + var i; + + if (Array.isArray(target)) + { + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + for (var t = 0; t < target.length; t++) + { + if (tween.hasTarget(target[t])) + { + output.push(tween); + } + } + } + } + else + { + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + if (tween.hasTarget(target)) + { + output.push(tween); + } + } + } + + return output; + }, + + /** + * Checks if the given object is being affected by a playing Tween. + * + * @method Phaser.Tweens.TweenManager#isTweening + * @since 3.0.0 + * + * @param {object} target - target Phaser.Tweens.Tween object + * + * @return {boolean} returns if target tween object is active or not + */ + isTweening: function (target) + { + var list = this._active; + var tween; + + for (var i = 0; i < list.length; i++) + { + tween = list[i]; + + if (tween.hasTarget(target) && tween.isPlaying()) + { + return true; + } + } + + return false; + }, + + /** + * Stops all Tweens in this Tween Manager. They will be removed at the start of the frame. + * + * @method Phaser.Tweens.TweenManager#killAll + * @since 3.0.0 + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + killAll: function () + { + var tweens = this.getAllTweens(); + + for (var i = 0; i < tweens.length; i++) + { + tweens[i].stop(); + } + + return this; + }, + + /** + * Stops all Tweens which affect the given target or array of targets. The Tweens will be removed from the Tween Manager at the start of the frame. + * + * @see {@link #getTweensOf} + * + * @method Phaser.Tweens.TweenManager#killTweensOf + * @since 3.0.0 + * + * @param {(object|array)} target - The target to look for. Provide an array to look for multiple targets. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + killTweensOf: function (target) + { + var tweens = this.getTweensOf(target); + + for (var i = 0; i < tweens.length; i++) + { + tweens[i].stop(); + } + + return this; + }, + + /** + * Pauses all Tweens in this Tween Manager. + * + * @method Phaser.Tweens.TweenManager#pauseAll + * @since 3.0.0 + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + pauseAll: function () + { + var list = this._active; + + for (var i = 0; i < list.length; i++) + { + list[i].pause(); + } + + return this; + }, + + /** + * Resumes all Tweens in this Tween Manager. + * + * @method Phaser.Tweens.TweenManager#resumeAll + * @since 3.0.0 + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + resumeAll: function () + { + var list = this._active; + + for (var i = 0; i < list.length; i++) + { + list[i].resume(); + } + + return this; + }, + + /** + * Sets a new scale of the time delta for this Tween Manager. + * + * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Tween Manager and all Tweens it owns. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing all Tweens. + * + * @method Phaser.Tweens.TweenManager#setGlobalTimeScale + * @since 3.0.0 + * + * @param {number} value - The new scale of the time delta, where 1 is the normal speed. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + setGlobalTimeScale: function (value) + { + this.timeScale = value; + + return this; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Tweens.TweenManager#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.killAll(); + + this._add = []; + this._pending = []; + this._active = []; + this._destroy = []; + + this._toProcess = 0; + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.off(SceneEvents.UPDATE, this.update, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Tweens.TweenManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('TweenManager', TweenManager, 'tweens'); + +module.exports = TweenManager; + + +/***/ }), +/* 1448 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils + */ + +module.exports = { + + Array: __webpack_require__(196), + Base64: __webpack_require__(1449), + Objects: __webpack_require__(1451), + String: __webpack_require__(1455) + +}; + + +/***/ }), +/* 1449 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Base64 + */ + +module.exports = { + + ArrayBufferToBase64: __webpack_require__(1450), + Base64ToArrayBuffer: __webpack_require__(410) + +}; + + +/***/ }), +/* 1450 */ +/***/ (function(module, exports) { + +/** + * @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer) + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +/** + * 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. + */ +var ArrayBufferToBase64 = function (arrayBuffer, mediaType) +{ + var bytes = new Uint8Array(arrayBuffer); + var len = bytes.length; + + var base64 = (mediaType) ? 'data:' + mediaType + ';base64,' : ''; + + for (var i = 0; i < len; i += 3) + { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + + if ((len % 3) === 2) + { + base64 = base64.substring(0, base64.length - 1) + '='; + } + else if (len % 3 === 1) + { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + + return base64; +}; + +module.exports = ArrayBufferToBase64; + + +/***/ }), +/* 1451 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Objects + */ + +module.exports = { + + Clone: __webpack_require__(73), + Extend: __webpack_require__(17), + GetAdvancedValue: __webpack_require__(15), + GetFastValue: __webpack_require__(1), + GetMinMaxValue: __webpack_require__(1452), + GetValue: __webpack_require__(5), + HasAll: __webpack_require__(1453), + HasAny: __webpack_require__(430), + HasValue: __webpack_require__(91), + IsPlainObject: __webpack_require__(7), + Merge: __webpack_require__(88), + MergeRight: __webpack_require__(1454), + Pick: __webpack_require__(524), + SetValue: __webpack_require__(450) + +}; + + +/***/ }), +/* 1452 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = __webpack_require__(5); +var Clamp = __webpack_require__(20); + +/** + * Retrieves and clamps a numerical value from an object. + * + * @function Phaser.Utils.Objects.GetMinMaxValue + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @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 (`.`). + * @param {number} min - The minimum value which can be returned. + * @param {number} max - The maximum value which can be returned. + * @param {number} defaultValue - The value to return if the property doesn't exist. It's also constrained to the given bounds. + * + * @return {number} The clamped value from the `source` object. + */ +var GetMinMaxValue = function (source, key, min, max, defaultValue) +{ + if (defaultValue === undefined) { defaultValue = min; } + + var value = GetValue(source, key, defaultValue); + + return Clamp(value, min, max); +}; + +module.exports = GetMinMaxValue; + + +/***/ }), +/* 1453 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Verifies that an object contains all requested keys + * + * @function Phaser.Utils.Objects.HasAll + * @since 3.0.0 + * + * @param {object} source - an object on which to check for key existence + * @param {string[]} keys - an array of keys to ensure the source object contains + * + * @return {boolean} true if the source object contains all keys, false otherwise. + */ +var HasAll = function (source, keys) +{ + for (var i = 0; i < keys.length; i++) + { + if (!source.hasOwnProperty(keys[i])) + { + return false; + } + } + + return true; +}; + +module.exports = HasAll; + + +/***/ }), +/* 1454 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(73); + +/** + * Creates a new Object using all values from obj1. + * + * Then scans obj2. If a property is found in obj2 that *also* exists in obj1, the value from obj2 is used, otherwise the property is skipped. + * + * @function Phaser.Utils.Objects.MergeRight + * @since 3.0.0 + * + * @param {object} obj1 - The first object to merge. + * @param {object} obj2 - The second object to merge. Keys from this object which also exist in `obj1` will be copied to `obj1`. + * + * @return {object} The merged object. `obj1` and `obj2` are not modified. + */ +var MergeRight = function (obj1, obj2) +{ + var clone = Clone(obj1); + + for (var key in obj2) + { + if (clone.hasOwnProperty(key)) + { + clone[key] = obj2[key]; + } + } + + return clone; +}; + +module.exports = MergeRight; + + +/***/ }), +/* 1455 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.String + */ + +module.exports = { + + Format: __webpack_require__(1456), + Pad: __webpack_require__(173), + Reverse: __webpack_require__(1457), + UppercaseFirst: __webpack_require__(194), + UUID: __webpack_require__(209) + +}; + + +/***/ }), +/* 1456 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes a string and replaces instances of markers with values in the given array. + * The markers take the form of `%1`, `%2`, etc. I.e.: + * + * `Format("The %1 is worth %2 gold", [ 'Sword', 500 ])` + * + * @function Phaser.Utils.String.Format + * @since 3.0.0 + * + * @param {string} string - The string containing the replacement markers. + * @param {array} values - An array containing values that will replace the markers. If no value exists an empty string is inserted instead. + * + * @return {string} The string containing replaced values. + */ +var Format = function (string, values) +{ + return string.replace(/%([0-9]+)/g, function (s, n) + { + return values[Number(n) - 1]; + }); +}; + +module.exports = Format; + + +/***/ }), +/* 1457 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @function Phaser.Utils.String.Reverse + * @since 3.0.0 + * + * @param {string} string - The string to be reversed. + * + * @return {string} The reversed string. + */ +var Reverse = function (string) +{ + return string.split('').reverse().join(''); +}; + +module.exports = Reverse; + + +/***/ }), +/* 1458 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Sound + */ + +module.exports = { + + SoundManagerCreator: __webpack_require__(404), + + Events: __webpack_require__(64), + + BaseSound: __webpack_require__(134), + BaseSoundManager: __webpack_require__(133), + + WebAudioSound: __webpack_require__(411), + WebAudioSoundManager: __webpack_require__(409), + + HTML5AudioSound: __webpack_require__(406), + HTML5AudioSoundManager: __webpack_require__(405), + + NoAudioSound: __webpack_require__(408), + NoAudioSoundManager: __webpack_require__(407) + +}; + + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/phaser-facebook-instant-games.min.js b/dist/phaser-facebook-instant-games.min.js new file mode 100644 index 000000000..1c170e033 --- /dev/null +++ b/dist/phaser-facebook-instant-games.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("Phaser",[],e):"object"==typeof exports?exports.Phaser=e():t.Phaser=e()}(window,function(){return function(t){var e={};function i(n){if(e[n])return e[n].exports;var s=e[n]={i:n,l:!1,exports:{}};return t[n].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)i.d(n,s,function(e){return t[e]}.bind(null,s));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=542)}([function(t,e){function i(t,e,i){var n=i?t[e]:Object.getOwnPropertyDescriptor(t,e);return!i&&n.value&&"object"==typeof n.value&&(n=n.value),!(!n||!function(t){return!!t.get&&"function"==typeof t.get||!!t.set&&"function"==typeof t.set}(n))&&(void 0===n.enumerable&&(n.enumerable=!0),void 0===n.configurable&&(n.configurable=!0),n)}function n(t,e){var i=Object.getOwnPropertyDescriptor(t,e);return!!i&&(i.value&&"object"==typeof i.value&&(i=i.value),!1===i.configurable)}function s(t,e,s,r){for(var a in e)if(e.hasOwnProperty(a)){var h=i(e,a,s);if(!1!==h){if(n((r||t).prototype,a)){if(o.ignoreFinals)continue;throw new Error("cannot override final property '"+a+"', set Class.ignoreFinals = true to skip")}Object.defineProperty(t.prototype,a,h)}else t.prototype[a]=e[a]}}function r(t,e){if(e){Array.isArray(e)||(e=[e]);for(var i=0;i0&&(i=1/Math.sqrt(i),this.x=t*i,this.y=e*i),this},normalizeRightHand:function(){var t=this.x;return this.x=-1*this.y,this.y=t,this},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this},transformMat3:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this},transformMat4:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[4]*i+n[12],this.y=n[1]*e+n[5]*i+n[13],this},reset:function(){return this.x=0,this.y=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0),n.LEFT=new n(-1,0),n.UP=new n(0,-1),n.DOWN=new n(0,1),n.ONE=new n(1,1),t.exports=n},function(t,e,i){var n=i(0),s=i(52),r=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=t),this.type=s.POINT,this.x=t,this.y=e},setTo:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.x=t,this.y=e,this}});t.exports=r},function(t,e){t.exports=function(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=i,o=0;o>>0},getTintAppendFloatAlpha:function(t,e){return((255&(255*e|0))<<24|t)>>>0},getTintAppendFloatAlphaAndSwap:function(t,e){return((255&(255*e|0))<<24|(255&(0|t))<<16|(255&(t>>8|0))<<8|255&(t>>16|0))>>>0},getFloatsFromUintRGB:function(t){return[(255&(t>>16|0))/255,(255&(t>>8|0))/255,(255&(0|t))/255]},getComponentCount:function(t,e){for(var i=0,n=0;n=this.right?this.width=0:this.width=this.right-t,this.x=t}},right:{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}},top:{get:function(){return this.y},set:function(t){t>=this.bottom?this.height=0:this.height=this.bottom-t,this.y=t}},bottom:{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}},centerX:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},centerY:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=u},function(t,e,i){t.exports={Alpha:i(559),AlphaSingle:i(287),Animation:i(288),BlendMode:i(291),ComputedSize:i(578),Crop:i(579),Depth:i(292),Flip:i(580),GetBounds:i(581),Mask:i(296),Origin:i(598),PathFollower:i(599),Pipeline:i(121),ScrollFactor:i(299),Size:i(600),Texture:i(601),TextureCrop:i(602),Tint:i(603),ToJSON:i(300),Transform:i(301),TransformMatrix:i(35),Visible:i(302)}},function(t,e){var i={PI2:2*Math.PI,TAU:.5*Math.PI,EPSILON:1e-6,DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,RND:null,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER||-9007199254740991,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991};t.exports=i},function(t,e,i){var n=i(0),s=i(300),r=i(101),o=i(9),a=i(102),h=new n({Extends:o,initialize:function(t,e){o.call(this),this.scene=t,this.type=e,this.state=0,this.parentContainer=null,this.name="",this.active=!0,this.tabIndex=-1,this.data=null,this.renderFlags=15,this.cameraFilter=0,this.input=null,this.body=null,this.ignoreDestroy=!1,t.sys.queueDepthSort()},setActive:function(t){return this.active=t,this},setName:function(t){return this.name=t,this},setState:function(t){return this.state=t,this},setDataEnabled:function(){return this.data||(this.data=new r(this)),this},setData:function(t,e){return this.data||(this.data=new r(this)),this.data.set(t,e),this},getData:function(t){return this.data||(this.data=new r(this)),this.data.get(t)},setInteractive:function(t,e,i){return this.scene.sys.input.enable(this,t,e,i),this},disableInteractive:function(){return this.input&&(this.input.enabled=!1),this},removeInteractive:function(){return this.scene.sys.input.clear(this),this.input=void 0,this},update:function(){},toJSON:function(){return s(this)},willRender:function(t){return!(h.RENDER_MASK!==this.renderFlags||0!==this.cameraFilter&&this.cameraFilter&t.id)},getIndexList:function(){for(var t=this,e=this.parentContainer,i=[];e&&(i.unshift(e.getIndex(t)),t=e,e.parentContainer);)e=e.parentContainer;return i.unshift(this.scene.sys.displayList.getIndex(t)),i},destroy:function(t){if(void 0===t&&(t=!1),this.scene&&!this.ignoreDestroy){this.preDestroy&&this.preDestroy.call(this),this.emit(a.DESTROY,this);var e=this.scene.sys;t||(e.displayList.remove(this),e.updateList.remove(this)),this.input&&(e.input.clear(this),this.input=void 0),this.data&&(this.data.destroy(),this.data=void 0),this.body&&(this.body.destroy(),this.body=void 0),t||e.queueDepthSort(),this.active=!1,this.visible=!1,this.scene=void 0,this.parentContainer=void 0,this.removeAllListeners()}}});h.RENDER_MASK=15,t.exports=h},function(t,e,i){var n=i(181),s=i(5);t.exports=function(t,e,i){var r=s(t,e,null);if(null===r)return i;if(Array.isArray(r))return n.RND.pick(r);if("object"==typeof r){if(r.hasOwnProperty("randInt"))return n.RND.integerInRange(r.randInt[0],r.randInt[1]);if(r.hasOwnProperty("randFloat"))return n.RND.realInRange(r.randFloat[0],r.randFloat[1])}else if("function"==typeof r)return r(e);return r}},function(t,e,i){var n=i(0),s=i(22),r=i(18),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectCreator",o,"make"),t.exports=o},function(t,e,i){var n=i(7),s=function(){var t,e,i,r,o,a,h=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof h&&(c=h,h=arguments[1]||{},l=2),u===l&&(h=this,--l);l0;e--){var n=Math.floor(i.random()*(e+1)),s=t[e];t[e]=t[n],t[n]=s}return t},i.choose=function(t){return t[Math.floor(i.random()*t.length)]},i.isElement=function(t){return"undefined"!=typeof HTMLElement?t instanceof HTMLElement:!!(t&&t.nodeType&&t.nodeName)},i.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},i.isFunction=function(t){return"function"==typeof t},i.isPlainObject=function(t){return"object"==typeof t&&t.constructor===Object},i.isString=function(t){return"[object String]"===toString.call(t)},i.clamp=function(t,e,i){return ti?i:t},i.sign=function(t){return t<0?-1:1},i.now=function(){if("undefined"!=typeof window&&window.performance){if(window.performance.now)return window.performance.now();if(window.performance.webkitNow)return window.performance.webkitNow()}return new Date-i._nowStartTime},i.random=function(e,i){return e=void 0!==e?e:0,i=void 0!==i?i:1,e+t()*(i-e)};var t=function(){return i._seed=(9301*i._seed+49297)%233280,i._seed/233280};i.colorToNumber=function(t){return 3==(t=t.replace("#","")).length&&(t=t.charAt(0)+t.charAt(0)+t.charAt(1)+t.charAt(1)+t.charAt(2)+t.charAt(2)),parseInt(t,16)},i.logLevel=1,i.log=function(){console&&i.logLevel>0&&i.logLevel<=3&&console.log.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.info=function(){console&&i.logLevel>0&&i.logLevel<=2&&console.info.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.warn=function(){console&&i.logLevel>0&&i.logLevel<=3&&console.warn.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.nextId=function(){return i._nextId++},i.indexOf=function(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0;i=400&&t.status<=599&&(n=!1),this.resetXHR(),this.loader.nextFile(this,n)},onError:function(){this.resetXHR(),this.loader.nextFile(this,!1)},onProgress:function(t){t.lengthComputable&&(this.bytesLoaded=t.loaded,this.bytesTotal=t.total,this.percentComplete=Math.min(this.bytesLoaded/this.bytesTotal,1),this.loader.emit(r.FILE_PROGRESS,this,this.percentComplete))},onProcess:function(){this.state=s.FILE_PROCESSING,this.onProcessComplete()},onProcessComplete:function(){this.state=s.FILE_COMPLETE,this.multiFile&&this.multiFile.onFileComplete(this),this.loader.fileProcessComplete(this)},onProcessError:function(){this.state=s.FILE_ERRORED,this.multiFile&&this.multiFile.onFileFailed(this),this.loader.fileProcessComplete(this)},hasCacheConflict:function(){return this.cache&&this.cache.exists(this.key)},addToCache:function(){this.cache&&this.cache.add(this.key,this.data),this.pendingDestroy()},pendingDestroy:function(t){void 0===t&&(t=this.data);var e=this.key,i=this.type;this.loader.emit(r.FILE_COMPLETE,e,i,t),this.loader.emit(r.FILE_KEY_COMPLETE+i+"-"+e,e,i,t),this.loader.flagForRemoval(this)},destroy:function(){this.loader=null,this.cache=null,this.xhrSettings=null,this.multiFile=null,this.linkFile=null,this.data=null}});c.createObjectURL=function(t,e,i){if("function"==typeof URL)t.src=URL.createObjectURL(e);else{var n=new FileReader;n.onload=function(){t.removeAttribute("crossOrigin"),t.src="data:"+(e.type||i)+";base64,"+n.result.split(",")[1]},n.onerror=t.onerror,n.readAsDataURL(e)}},c.revokeObjectURL=function(t){"function"==typeof URL&&URL.revokeObjectURL(t.src)},t.exports=c},function(t,e,i){var n={};t.exports=n;var s=i(31),r=i(37),o=i(95),a=i(19),h=i(38),l=i(146);!function(){n._inertiaScale=4,n._nextCollidingGroupId=1,n._nextNonCollidingGroupId=-1,n._nextCategory=1,n.create=function(e){var i={id:a.nextId(),type:"body",label:"Body",parts:[],plugin:{},angle:0,vertices:null,position:{x:0,y:0},force:{x:0,y:0},torque:0,positionImpulse:{x:0,y:0},previousPositionImpulse:{x:0,y:0},constraintImpulse:{x:0,y:0,angle:0},totalContacts:0,speed:0,angularSpeed:0,velocity:{x:0,y:0},angularVelocity:0,isSensor:!1,isStatic:!1,isSleeping:!1,motion:0,sleepThreshold:60,density:.001,restitution:0,friction:.1,frictionStatic:.5,frictionAir:.01,collisionFilter:{category:1,mask:4294967295,group:0},slop:.05,timeScale:1,events:null,bounds:null,chamfer:null,circleRadius:0,positionPrev:null,anglePrev:0,parent:null,axes:null,area:0,mass:0,inverseMass:0,inertia:0,inverseInertia:0,_original:null,render:{visible:!0,opacity:1,sprite:{xOffset:0,yOffset:0},fillColor:null,fillOpacity:null,lineColor:null,lineOpacity:null,lineThickness:null},gameObject:null,scale:{x:1,y:1},centerOfMass:{x:0,y:0},centerOffset:{x:0,y:0},gravityScale:{x:1,y:1},ignoreGravity:!1,ignorePointer:!1,onCollideCallback:null,onCollideEndCallback:null,onCollideActiveCallback:null,onCollideWith:{}};!e.hasOwnProperty("position")&&e.hasOwnProperty("vertices")?e.position=s.centre(e.vertices):e.hasOwnProperty("vertices")||(i.vertices=s.fromPath("L 0 0 L 40 0 L 40 40 L 0 40"));var n=a.extend(i,e);return t(n,e),n.setOnCollideWith=function(t,e){return e?this.onCollideWith[t.id]=e:delete this.onCollideWith[t.id],this},n},n.nextGroup=function(t){return t?n._nextNonCollidingGroupId--:n._nextCollidingGroupId++},n.nextCategory=function(){return n._nextCategory=n._nextCategory<<1,n._nextCategory};var t=function(t,e){e=e||{},n.set(t,{bounds:t.bounds||h.create(t.vertices),positionPrev:t.positionPrev||r.clone(t.position),anglePrev:t.anglePrev||t.angle,vertices:t.vertices,parts:t.parts||[t],isStatic:t.isStatic,isSleeping:t.isSleeping,parent:t.parent||t});var i=t.bounds;if(s.rotate(t.vertices,t.angle,t.position),l.rotate(t.axes,t.angle),h.update(i,t.vertices,t.velocity),n.set(t,{axes:e.axes||t.axes,area:e.area||t.area,mass:e.mass||t.mass,inertia:e.inertia||t.inertia}),1===t.parts.length){var o=t.centerOfMass,a=t.centerOffset,u=i.max.x-i.min.x,c=i.max.y-i.min.y;o.x=-(i.min.x-t.position.x)/u,o.y=-(i.min.y-t.position.y)/c,a.x=u*o.x,a.y=c*o.y}};n.set=function(t,e,i){var s;for(s in"string"==typeof e&&(s=e,(e={})[s]=i),e)if(Object.prototype.hasOwnProperty.call(e,s))switch(i=e[s],s){case"isStatic":n.setStatic(t,i);break;case"isSleeping":o.set(t,i);break;case"mass":n.setMass(t,i);break;case"density":n.setDensity(t,i);break;case"inertia":n.setInertia(t,i);break;case"vertices":n.setVertices(t,i);break;case"position":n.setPosition(t,i);break;case"angle":n.setAngle(t,i);break;case"velocity":n.setVelocity(t,i);break;case"angularVelocity":n.setAngularVelocity(t,i);break;case"parts":n.setParts(t,i);break;case"centre":n.setCentre(t,i);break;default:t[s]=i}},n.setStatic=function(t,e){for(var i=0;i0&&r.rotateAbout(o.position,i,t.position,o.position)}},n.setVelocity=function(t,e){t.positionPrev.x=t.position.x-e.x,t.positionPrev.y=t.position.y-e.y,t.velocity.x=e.x,t.velocity.y=e.y,t.speed=r.magnitude(t.velocity)},n.setAngularVelocity=function(t,e){t.anglePrev=t.angle-e,t.angularVelocity=e,t.angularSpeed=Math.abs(t.angularVelocity)},n.translate=function(t,e){n.setPosition(t,r.add(t.position,e))},n.rotate=function(t,e,i){if(i){var s=Math.cos(e),r=Math.sin(e),o=t.position.x-i.x,a=t.position.y-i.y;n.setPosition(t,{x:i.x+(o*s-a*r),y:i.y+(o*r+a*s)}),n.setAngle(t,t.angle+e)}else n.setAngle(t,t.angle+e)},n.scale=function(t,e,i,r){var o=0,a=0;r=r||t.position;for(var u=0;u0&&(o+=c.area,a+=c.inertia),c.position.x=r.x+(c.position.x-r.x)*e,c.position.y=r.y+(c.position.y-r.y)*i,h.update(c.bounds,c.vertices,t.velocity)}t.parts.length>1&&(t.area=o,t.isStatic||(n.setMass(t,t.density*o),n.setInertia(t,a))),t.circleRadius&&(e===i?t.circleRadius*=e:t.circleRadius=null)},n.update=function(t,e,i,n){var o=Math.pow(e*i*t.timeScale,2),a=1-t.frictionAir*i*t.timeScale,u=t.position.x-t.positionPrev.x,c=t.position.y-t.positionPrev.y;t.velocity.x=u*a*n+t.force.x/t.mass*o,t.velocity.y=c*a*n+t.force.y/t.mass*o,t.positionPrev.x=t.position.x,t.positionPrev.y=t.position.y,t.position.x+=t.velocity.x,t.position.y+=t.velocity.y,t.angularVelocity=(t.angle-t.anglePrev)*a*n+t.torque/t.inertia*o,t.anglePrev=t.angle,t.angle+=t.angularVelocity,t.speed=r.magnitude(t.velocity),t.angularSpeed=Math.abs(t.angularVelocity);for(var d=0;d0&&(f.position.x+=t.velocity.x,f.position.y+=t.velocity.y),0!==t.angularVelocity&&(s.rotate(f.vertices,t.angularVelocity,t.position),l.rotate(f.axes,t.angularVelocity),d>0&&r.rotateAbout(f.position,t.angularVelocity,t.position,f.position)),h.update(f.bounds,f.vertices,t.velocity)}},n.applyForce=function(t,e,i){t.force.x+=i.x,t.force.y+=i.y;var n=e.x-t.position.x,s=e.y-t.position.y;t.torque+=n*i.y-s*i.x},n._totalProperties=function(t){for(var e={mass:0,area:0,inertia:0,centre:{x:0,y:0}},i=1===t.parts.length?0:1;io.width&&(i=Math.max(o.width-t,0)),e+s>o.height&&(s=Math.max(o.height-e,0));for(var u=[],c=e;c=0;o--)t[o][e]=i+a*n,a++;return t}},function(t,e,i){var n,s,r,o=i(32),a=i(177),h=[],l=!1;t.exports={create2D:function(t,e,i){return n(t,e,i,o.CANVAS)},create:n=function(t,e,i,n,r){var u;void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=o.CANVAS),void 0===r&&(r=!1);var c=s(n);return null===c?(c={parent:t,canvas:document.createElement("canvas"),type:n},n===o.CANVAS&&h.push(c),u=c.canvas):(c.parent=t,u=c.canvas),r&&(c.parent=u),u.width=e,u.height=i,l&&n===o.CANVAS&&a.disable(u.getContext("2d")),u},createWebGL:function(t,e,i){return n(t,e,i,o.WEBGL)},disableSmoothing:function(){l=!0},enableSmoothing:function(){l=!1},first:s=function(t){if(void 0===t&&(t=o.CANVAS),t===o.WEBGL)return null;for(var e=0;e0)return!1}return!0},n.scale=function(t,e,i,r){if(1===e&&1===i)return t;var o,a;r=r||n.centre(t);for(var h=0;h=0?h-1:t.length-1],u=t[h],c=t[(h+1)%t.length],d=e[h0&&(r|=2),3===r)return!1;return 0!==r||null},n.hull=function(t){var e,i,n=[],r=[];for((t=t.slice(0)).sort(function(t,e){var i=t.x-e.x;return 0!==i?i:t.y-e.y}),i=0;i=2&&s.cross3(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}for(i=t.length-1;i>=0;i-=1){for(e=t[i];n.length>=2&&s.cross3(n[n.length-2],n[n.length-1],e)<=0;)n.pop();n.push(e)}return n.pop(),r.pop(),n.concat(r)}},function(t,e,i){var n={VERSION:"3.22.0",BlendModes:i(43),ScaleModes:i(157),AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,FOREVER:-1,NONE:4,UP:5,DOWN:6,LEFT:7,RIGHT:8};t.exports=n},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(61),a=new n({Extends:r,Mixins:[s.AlphaSingle,s.BlendMode,s.ComputedSize,s.Depth,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Transform,s.Visible],initialize:function(t,e,i){void 0===e&&(e="Shape"),r.call(this,t,e),this.geom=i,this.pathData=[],this.pathIndexes=[],this.fillColor=16777215,this.fillAlpha=1,this.strokeColor=16777215,this.strokeAlpha=1,this.lineWidth=1,this.isFilled=!1,this.isStroked=!1,this.closePath=!0,this._tempLine=new o,this.initPipeline()},setFillStyle:function(t,e){return void 0===e&&(e=1),void 0===t?this.isFilled=!1:(this.fillColor=t,this.fillAlpha=e,this.isFilled=!0),this},setStrokeStyle:function(t,e,i){return void 0===i&&(i=1),void 0===t?this.isStroked=!1:(this.lineWidth=t,this.strokeColor=e,this.strokeAlpha=i,this.isStroked=!0),this},setClosePath:function(t){return this.closePath=t,this},preDestroy:function(){this.geom=null,this._tempLine=null,this.pathData=[],this.pathIndexes=[]}});t.exports=a},function(t,e){t.exports={CSV:0,TILED_JSON:1,ARRAY_2D:2,WELTMEISTER:3}},function(t,e,i){var n=i(0),s=i(13),r=i(3),o=new n({initialize:function(t,e,i,n,s,r){void 0===t&&(t=1),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=1),void 0===s&&(s=0),void 0===r&&(r=0),this.matrix=new Float32Array([t,e,i,n,s,r,0,0,1]),this.decomposedMatrix={translateX:0,translateY:0,scaleX:1,scaleY:1,rotation:0}},a:{get:function(){return this.matrix[0]},set:function(t){this.matrix[0]=t}},b:{get:function(){return this.matrix[1]},set:function(t){this.matrix[1]=t}},c:{get:function(){return this.matrix[2]},set:function(t){this.matrix[2]=t}},d:{get:function(){return this.matrix[3]},set:function(t){this.matrix[3]=t}},e:{get:function(){return this.matrix[4]},set:function(t){this.matrix[4]=t}},f:{get:function(){return this.matrix[5]},set:function(t){this.matrix[5]=t}},tx:{get:function(){return this.matrix[4]},set:function(t){this.matrix[4]=t}},ty:{get:function(){return this.matrix[5]},set:function(t){this.matrix[5]=t}},rotation:{get:function(){return Math.acos(this.a/this.scaleX)*(Math.atan(-this.c/this.a)<0?-1:1)}},rotationNormalized:{get:function(){var t=this.matrix,e=t[0],i=t[1],n=t[2],r=t[3];return e||i?i>0?Math.acos(e/this.scaleX):-Math.acos(e/this.scaleX):n||r?s.TAU-(r>0?Math.acos(-n/this.scaleY):-Math.acos(n/this.scaleY)):0}},scaleX:{get:function(){return Math.sqrt(this.a*this.a+this.b*this.b)}},scaleY:{get:function(){return Math.sqrt(this.c*this.c+this.d*this.d)}},loadIdentity:function(){var t=this.matrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,this},translate:function(t,e){var i=this.matrix;return i[4]=i[0]*t+i[2]*e+i[4],i[5]=i[1]*t+i[3]*e+i[5],this},scale:function(t,e){var i=this.matrix;return i[0]*=t,i[1]*=t,i[2]*=e,i[3]*=e,this},rotate:function(t){var e=Math.sin(t),i=Math.cos(t),n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3];return n[0]=s*i+o*e,n[1]=r*i+a*e,n[2]=s*-e+o*i,n[3]=r*-e+a*i,this},multiply:function(t,e){var i=this.matrix,n=t.matrix,s=i[0],r=i[1],o=i[2],a=i[3],h=i[4],l=i[5],u=n[0],c=n[1],d=n[2],f=n[3],p=n[4],g=n[5],v=void 0===e?this:e;return v.a=u*s+c*o,v.b=u*r+c*a,v.c=d*s+f*o,v.d=d*r+f*a,v.e=p*s+g*o+h,v.f=p*r+g*a+l,v},multiplyWithOffset:function(t,e,i){var n=this.matrix,s=t.matrix,r=n[0],o=n[1],a=n[2],h=n[3],l=e*r+i*a+n[4],u=e*o+i*h+n[5],c=s[0],d=s[1],f=s[2],p=s[3],g=s[4],v=s[5];return n[0]=c*r+d*a,n[1]=c*o+d*h,n[2]=f*r+p*a,n[3]=f*o+p*h,n[4]=g*r+v*a+l,n[5]=g*o+v*h+u,this},transform:function(t,e,i,n,s,r){var o=this.matrix,a=o[0],h=o[1],l=o[2],u=o[3],c=o[4],d=o[5];return o[0]=t*a+e*l,o[1]=t*h+e*u,o[2]=i*a+n*l,o[3]=i*h+n*u,o[4]=s*a+r*l+c,o[5]=s*h+r*u+d,this},transformPoint:function(t,e,i){void 0===i&&(i={x:0,y:0});var n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5];return i.x=t*s+e*o+h,i.y=t*r+e*a+l,i},invert:function(){var t=this.matrix,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=e*s-i*n;return t[0]=s/a,t[1]=-i/a,t[2]=-n/a,t[3]=e/a,t[4]=(n*o-s*r)/a,t[5]=-(e*o-i*r)/a,this},copyFrom:function(t){var e=this.matrix;return e[0]=t.a,e[1]=t.b,e[2]=t.c,e[3]=t.d,e[4]=t.e,e[5]=t.f,this},copyFromArray:function(t){var e=this.matrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],this},copyToContext:function(t){var e=this.matrix;return t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t},setToContext:function(t){var e=this.matrix;return t.setTransform(e[0],e[1],e[2],e[3],e[4],e[5]),t},copyToArray:function(t){var e=this.matrix;return void 0===t?t=[e[0],e[1],e[2],e[3],e[4],e[5]]:(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]),t},setTransform:function(t,e,i,n,s,r){var o=this.matrix;return o[0]=t,o[1]=e,o[2]=i,o[3]=n,o[4]=s,o[5]=r,this},decomposeMatrix:function(){var t=this.decomposedMatrix,e=this.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(t.translateX=e[4],t.translateY=e[5],i||n){var a=Math.sqrt(i*i+n*n);t.rotation=n>0?Math.acos(i/a):-Math.acos(i/a),t.scaleX=a,t.scaleY=o/a}else if(s||r){var h=Math.sqrt(s*s+r*r);t.rotation=.5*Math.PI-(r>0?Math.acos(-s/h):-Math.acos(s/h)),t.scaleX=o/h,t.scaleY=h}else t.rotation=0,t.scaleX=0,t.scaleY=0;return t},applyITRS:function(t,e,i,n,s){var r=this.matrix,o=Math.sin(i),a=Math.cos(i);return r[4]=t,r[5]=e,r[0]=a*n,r[1]=o*n,r[2]=-o*s,r[3]=a*s,this},applyInverse:function(t,e,i){void 0===i&&(i=new r);var n=this.matrix,s=n[0],o=n[1],a=n[2],h=n[3],l=n[4],u=n[5],c=1/(s*h+a*-o);return i.x=h*c*t+-a*c*e+(u*a-l*h)*c,i.y=s*c*e+-o*c*t+(-u*s+l*o)*c,i},getX:function(t,e){return t*this.a+e*this.c+this.e},getY:function(t,e){return t*this.b+e*this.d+this.f},getCSSMatrix:function(){var t=this.matrix;return"matrix("+t[0]+","+t[1]+","+t[2]+","+t[3]+","+t[4]+","+t[5]+")"},destroy:function(){this.matrix=null,this.decomposedMatrix=null}});t.exports=o},function(t,e,i){var n=i(0),s=i(175),r=i(314),o=i(176),a=i(315),h=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=255),this.r=0,this.g=0,this.b=0,this.a=255,this._h=0,this._s=0,this._v=0,this._locked=!1,this.gl=[0,0,0,1],this._color=0,this._color32=0,this._rgba="",this.setTo(t,e,i,n)},transparent:function(){return this._locked=!0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this._locked=!1,this.update(!0)},setTo:function(t,e,i,n,s){return void 0===n&&(n=255),void 0===s&&(s=!0),this._locked=!0,this.red=t,this.green=e,this.blue=i,this.alpha=n,this._locked=!1,this.update(s)},setGLTo:function(t,e,i,n){return void 0===n&&(n=1),this._locked=!0,this.redGL=t,this.greenGL=e,this.blueGL=i,this.alphaGL=n,this._locked=!1,this.update(!0)},setFromRGB:function(t){return this._locked=!0,this.red=t.r,this.green=t.g,this.blue=t.b,t.hasOwnProperty("a")&&(this.alpha=t.a),this._locked=!1,this.update(!0)},setFromHSV:function(t,e,i){return o(t,e,i,this)},update:function(t){if(void 0===t&&(t=!1),this._locked)return this;var e=this.r,i=this.g,n=this.b,o=this.a;return this._color=s(e,i,n),this._color32=r(e,i,n,o),this._rgba="rgba("+e+","+i+","+n+","+o/255+")",t&&a(e,i,n,this),this},updateHSV:function(){var t=this.r,e=this.g,i=this.b;return a(t,e,i,this),this},clone:function(){return new h(this.r,this.g,this.b,this.a)},gray:function(t){return this.setTo(t,t,t)},random:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t)),n=Math.floor(t+Math.random()*(e-t)),s=Math.floor(t+Math.random()*(e-t));return this.setTo(i,n,s)},randomGray:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t));return this.setTo(i,i,i)},saturate:function(t){return this.s+=t/100,this},desaturate:function(t){return this.s-=t/100,this},lighten:function(t){return this.v+=t/100,this},darken:function(t){return this.v-=t/100,this},brighten:function(t){var e=this.r,i=this.g,n=this.b;return e=Math.max(0,Math.min(255,e-Math.round(-t/100*255))),i=Math.max(0,Math.min(255,i-Math.round(-t/100*255))),n=Math.max(0,Math.min(255,n-Math.round(-t/100*255))),this.setTo(e,i,n)},color:{get:function(){return this._color}},color32:{get:function(){return this._color32}},rgba:{get:function(){return this._rgba}},redGL:{get:function(){return this.gl[0]},set:function(t){this.gl[0]=Math.min(Math.abs(t),1),this.r=Math.floor(255*this.gl[0]),this.update(!0)}},greenGL:{get:function(){return this.gl[1]},set:function(t){this.gl[1]=Math.min(Math.abs(t),1),this.g=Math.floor(255*this.gl[1]),this.update(!0)}},blueGL:{get:function(){return this.gl[2]},set:function(t){this.gl[2]=Math.min(Math.abs(t),1),this.b=Math.floor(255*this.gl[2]),this.update(!0)}},alphaGL:{get:function(){return this.gl[3]},set:function(t){this.gl[3]=Math.min(Math.abs(t),1),this.a=Math.floor(255*this.gl[3]),this.update()}},red:{get:function(){return this.r},set:function(t){t=Math.floor(Math.abs(t)),this.r=Math.min(t,255),this.gl[0]=t/255,this.update(!0)}},green:{get:function(){return this.g},set:function(t){t=Math.floor(Math.abs(t)),this.g=Math.min(t,255),this.gl[1]=t/255,this.update(!0)}},blue:{get:function(){return this.b},set:function(t){t=Math.floor(Math.abs(t)),this.b=Math.min(t,255),this.gl[2]=t/255,this.update(!0)}},alpha:{get:function(){return this.a},set:function(t){t=Math.floor(Math.abs(t)),this.a=Math.min(t,255),this.gl[3]=t/255,this.update()}},h:{get:function(){return this._h},set:function(t){this._h=t,o(t,this._s,this._v,this)}},s:{get:function(){return this._s},set:function(t){this._s=t,o(this._h,t,this._v,this)}},v:{get:function(){return this._v},set:function(t){this._v=t,o(this._h,this._s,t,this)}}});t.exports=h},function(t,e){var i={};t.exports=i,i.create=function(t,e){return{x:t||0,y:e||0}},i.clone=function(t){return{x:t.x,y:t.y}},i.magnitude=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},i.magnitudeSquared=function(t){return t.x*t.x+t.y*t.y},i.rotate=function(t,e,i){var n=Math.cos(e),s=Math.sin(e);i||(i={});var r=t.x*n-t.y*s;return i.y=t.x*s+t.y*n,i.x=r,i},i.rotateAbout=function(t,e,i,n){var s=Math.cos(e),r=Math.sin(e);n||(n={});var o=i.x+((t.x-i.x)*s-(t.y-i.y)*r);return n.y=i.y+((t.x-i.x)*r+(t.y-i.y)*s),n.x=o,n},i.normalise=function(t){var e=i.magnitude(t);return 0===e?{x:0,y:0}:{x:t.x/e,y:t.y/e}},i.dot=function(t,e){return t.x*e.x+t.y*e.y},i.cross=function(t,e){return t.x*e.y-t.y*e.x},i.cross3=function(t,e,i){return(e.x-t.x)*(i.y-t.y)-(e.y-t.y)*(i.x-t.x)},i.add=function(t,e,i){return i||(i={}),i.x=t.x+e.x,i.y=t.y+e.y,i},i.sub=function(t,e,i){return i||(i={}),i.x=t.x-e.x,i.y=t.y-e.y,i},i.mult=function(t,e){return{x:t.x*e,y:t.y*e}},i.div=function(t,e){return{x:t.x/e,y:t.y/e}},i.perp=function(t,e){return{x:(e=!0===e?-1:1)*-t.y,y:e*t.x}},i.neg=function(t){return{x:-t.x,y:-t.y}},i.angle=function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},i._temp=[i.create(),i.create(),i.create(),i.create(),i.create(),i.create()]},function(t,e){var i={};t.exports=i,i.create=function(t){var e={min:{x:0,y:0},max:{x:0,y:0}};return t&&i.update(e,t),e},i.update=function(t,e,i){t.min.x=1/0,t.max.x=-1/0,t.min.y=1/0,t.max.y=-1/0;for(var n=0;nt.max.x&&(t.max.x=s.x),s.xt.max.y&&(t.max.y=s.y),s.y0?t.max.x+=i.x:t.min.x+=i.x,i.y>0?t.max.y+=i.y:t.min.y+=i.y)},i.contains=function(t,e){return e.x>=t.min.x&&e.x<=t.max.x&&e.y>=t.min.y&&e.y<=t.max.y},i.overlaps=function(t,e){return t.min.x<=e.max.x&&t.max.x>=e.min.x&&t.max.y>=e.min.y&&t.min.y<=e.max.y},i.translate=function(t,e){t.min.x+=e.x,t.max.x+=e.x,t.min.y+=e.y,t.max.y+=e.y},i.shift=function(t,e){var i=t.max.x-t.min.x,n=t.max.y-t.min.y;t.min.x=e.x,t.max.x=e.x+i,t.min.y=e.y,t.max.y=e.y+n}},function(t,e){t.exports=function(t,e,i,n,s,r){var o;void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=1);var a=0,h=t.length;if(1===r)for(o=s;o=0;o--)t[o][e]+=i+a*n,a++;return t}},function(t,e,i){var n=i(13);t.exports=function(t){return t*n.DEG_TO_RAD}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.fillColor,r=n||e.fillAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.fillStyle="rgba("+o+","+a+","+h+","+r+")"}},function(t,e,i){var n={};t.exports=n;var s=i(31),r=i(19),o=i(25),a=i(38),h=i(37),l=i(505);n.rectangle=function(t,e,i,n,a){a=a||{};var h={label:"Rectangle Body",position:{x:t,y:e},vertices:s.fromPath("L 0 0 L "+i+" 0 L "+i+" "+n+" L 0 "+n)};if(a.chamfer){var l=a.chamfer;h.vertices=s.chamfer(h.vertices,l.radius,l.quality,l.qualityMin,l.qualityMax),delete a.chamfer}return o.create(r.extend({},h,a))},n.trapezoid=function(t,e,i,n,a,h){h=h||{};var l,u=i*(a*=.5),c=u+(1-2*a)*i,d=c+u;l=a<.5?"L 0 0 L "+u+" "+-n+" L "+c+" "+-n+" L "+d+" 0":"L 0 0 L "+c+" "+-n+" L "+d+" 0";var f={label:"Trapezoid Body",position:{x:t,y:e},vertices:s.fromPath(l)};if(h.chamfer){var p=h.chamfer;f.vertices=s.chamfer(f.vertices,p.radius,p.quality,p.qualityMin,p.qualityMax),delete h.chamfer}return o.create(r.extend({},f,h))},n.circle=function(t,e,i,s,o){s=s||{};var a={label:"Circle Body",circleRadius:i};o=o||25;var h=Math.ceil(Math.max(10,Math.min(o,i)));return h%2==1&&(h+=1),n.polygon(t,e,h,i,r.extend({},a,s))},n.polygon=function(t,e,i,a,h){if(h=h||{},i<3)return n.circle(t,e,a,h);for(var l=2*Math.PI/i,u="",c=.5*l,d=0;d0&&s.area(T)1?(d=o.create(r.extend({parts:f.slice(0)},a)),o.setPosition(d,{x:t,y:e}),d):f[0]},n.flagCoincidentParts=function(t,e){void 0===e&&(e=5);for(var i=0;i=e&&t.y<=i&&t.y+t.height>=i}},function(t,e){t.exports=function(t,e,i,n){var s=t-i,r=e-n;return Math.sqrt(s*s+r*r)}},function(t,e,i){t.exports={DESTROY:i(673),FADE_IN_COMPLETE:i(674),FADE_IN_START:i(675),FADE_OUT_COMPLETE:i(676),FADE_OUT_START:i(677),FLASH_COMPLETE:i(678),FLASH_START:i(679),PAN_COMPLETE:i(680),PAN_START:i(681),POST_RENDER:i(682),PRE_RENDER:i(683),SHAKE_COMPLETE:i(684),SHAKE_START:i(685),ZOOM_COMPLETE:i(686),ZOOM_START:i(687)}},function(t,e,i){t.exports={BOOT:i(846),DESTROY:i(847),DRAG_END:i(848),DRAG_ENTER:i(849),DRAG:i(850),DRAG_LEAVE:i(851),DRAG_OVER:i(852),DRAG_START:i(853),DROP:i(854),GAME_OUT:i(855),GAME_OVER:i(856),GAMEOBJECT_DOWN:i(857),GAMEOBJECT_DRAG_END:i(858),GAMEOBJECT_DRAG_ENTER:i(859),GAMEOBJECT_DRAG:i(860),GAMEOBJECT_DRAG_LEAVE:i(861),GAMEOBJECT_DRAG_OVER:i(862),GAMEOBJECT_DRAG_START:i(863),GAMEOBJECT_DROP:i(864),GAMEOBJECT_MOVE:i(865),GAMEOBJECT_OUT:i(866),GAMEOBJECT_OVER:i(867),GAMEOBJECT_POINTER_DOWN:i(868),GAMEOBJECT_POINTER_MOVE:i(869),GAMEOBJECT_POINTER_OUT:i(870),GAMEOBJECT_POINTER_OVER:i(871),GAMEOBJECT_POINTER_UP:i(872),GAMEOBJECT_POINTER_WHEEL:i(873),GAMEOBJECT_UP:i(874),GAMEOBJECT_WHEEL:i(875),MANAGER_BOOT:i(876),MANAGER_PROCESS:i(877),MANAGER_UPDATE:i(878),POINTER_DOWN:i(879),POINTER_DOWN_OUTSIDE:i(880),POINTER_MOVE:i(881),POINTER_OUT:i(882),POINTER_OVER:i(883),POINTER_UP:i(884),POINTER_UP_OUTSIDE:i(885),POINTER_WHEEL:i(886),POINTERLOCK_CHANGE:i(887),PRE_UPDATE:i(888),SHUTDOWN:i(889),START:i(890),UPDATE:i(891)}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.strokeColor,r=n||e.strokeAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.strokeStyle="rgba("+o+","+a+","+h+","+r+")",t.lineWidth=e.lineWidth}},function(t,e){t.exports={DYNAMIC_BODY:0,STATIC_BODY:1,GROUP:2,TILEMAPLAYER:3,FACING_NONE:10,FACING_UP:11,FACING_DOWN:12,FACING_LEFT:13,FACING_RIGHT:14}},function(t,e,i){var n=i(151),s=i(26);t.exports=function(t,e,i,r,o){for(var a=null,h=null,l=null,u=null,c=s(t,e,i,r,null,o),d=0;d0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}},function(t,e,i){var n=i(0),s=i(294),r=i(162),o=i(52),a=i(163),h=i(3),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=o.LINE,this.x1=t,this.y1=e,this.x2=i,this.y2=n},getPoint:function(t,e){return s(this,t,e)},getPoints:function(t,e,i){return r(this,t,e,i)},getRandomPoint:function(t){return a(this,t)},setTo:function(t,e,i,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x1=t,this.y1=e,this.x2=i,this.y2=n,this},getPointA:function(t){return void 0===t&&(t=new h),t.set(this.x1,this.y1),t},getPointB:function(t){return void 0===t&&(t=new h),t.set(this.x2,this.y2),t},left:{get:function(){return Math.min(this.x1,this.x2)},set:function(t){this.x1<=this.x2?this.x1=t:this.x2=t}},right:{get:function(){return Math.max(this.x1,this.x2)},set:function(t){this.x1>this.x2?this.x1=t:this.x2=t}},top:{get:function(){return Math.min(this.y1,this.y2)},set:function(t){this.y1<=this.y2?this.y1=t:this.y2=t}},bottom:{get:function(){return Math.max(this.y1,this.y2)},set:function(t){this.y1>this.y2?this.y1=t:this.y2=t}}});t.exports=l},function(t,e){t.exports=function(t){return Math.sqrt((t.x2-t.x1)*(t.x2-t.x1)+(t.y2-t.y1)*(t.y2-t.y1))}},function(t,e){t.exports=function(t,e,i){var n=i-e;return e+((t-e)%n+n)%n}},function(t,e,i){t.exports={COMPLETE:i(914),DECODED:i(915),DECODED_ALL:i(916),DESTROY:i(917),DETUNE:i(918),GLOBAL_DETUNE:i(919),GLOBAL_MUTE:i(920),GLOBAL_RATE:i(921),GLOBAL_VOLUME:i(922),LOOP:i(923),LOOPED:i(924),MUTE:i(925),PAUSE_ALL:i(926),PAUSE:i(927),PLAY:i(928),RATE:i(929),RESUME_ALL:i(930),RESUME:i(931),SEEK:i(932),STOP_ALL:i(933),STOP:i(934),UNLOCKED:i(935),VOLUME:i(936)}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(997),a=new n({Extends:r,Mixins:[s.Alpha,s.BlendMode,s.Depth,s.Flip,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Size,s.TextureCrop,s.Tint,s.Transform,s.Visible,o],initialize:function(t,e,i,n,o){r.call(this,t,"Sprite"),this._crop=this.resetCropObject(),this.anims=new s.Animation(this),this.setTexture(n,o),this.setPosition(e,i),this.setSizeToFrame(),this.setOriginFromFrame(),this.initPipeline()},preUpdate:function(t,e){this.anims.update(t,e)},play:function(t,e,i){return this.anims.play(t,e,i),this},toJSON:function(){return s.ToJSON(this)},preDestroy:function(){this.anims.destroy(),this.anims=void 0}});t.exports=a},function(t,e,i){var n=i(0),s=i(23),r=i(24),o=i(8),a=i(1),h=i(5),l=i(7),u=new n({Extends:r,initialize:function(t,e,i,n,o){var u="json";if(l(e)){var c=e;e=a(c,"key"),i=a(c,"url"),n=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"dataKey",o)}var d={type:"json",cache:t.cacheManager.json,extension:u,responseType:"text",key:e,url:i,xhrSettings:n,config:o};r.call(this,t,d),l(i)&&(this.data=o?h(i,o):i,this.state=s.FILE_POPULATED)},onProcess:function(){if(this.state!==s.FILE_POPULATED){this.state=s.FILE_PROCESSING;var t=JSON.parse(this.xhrLoader.responseText),e=this.config;this.data="string"==typeof e?h(t,e,t):t}this.onProcessComplete()}});o.register("json",function(t,e,i,n){if(Array.isArray(t))for(var s=0;s80*i){n=h=t[0],a=l=t[1];for(var T=i;Th&&(h=u),f>l&&(l=f);g=0!==(g=Math.max(h-n,l-a))?1/g:0}return o(m,x,i,n,a,g),x}function s(t,e,i,n,s){var r,o;if(s===A(t,e,i,n)>0)for(r=e;r=e;r-=n)o=b(r,t[r],t[r+1],o);return o&&m(o,o.next)&&(E(o),o=o.next),o}function r(t,e){if(!t)return t;e||(e=t);var i,n=t;do{if(i=!1,n.steiner||!m(n,n.next)&&0!==y(n.prev,n,n.next))n=n.next;else{if(E(n),(n=e=n.prev)===n.next)break;i=!0}}while(i||n!==e);return e}function o(t,e,i,n,s,c,d){if(t){!d&&c&&function(t,e,i,n){var s=t;do{null===s.z&&(s.z=f(s.x,s.y,e,i,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,n,s,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,n=i,a=0,e=0;e0||h>0&&n;)0!==a&&(0===h||!n||i.z<=n.z)?(s=i,i=i.nextZ,a--):(s=n,n=n.nextZ,h--),r?r.nextZ=s:t=s,s.prevZ=r,r=s;i=n}r.nextZ=null,l*=2}while(o>1)}(s)}(t,n,s,c);for(var p,g,v=t;t.prev!==t.next;)if(p=t.prev,g=t.next,c?h(t,n,s,c):a(t))e.push(p.i/i),e.push(t.i/i),e.push(g.i/i),E(t),t=g.next,v=g.next;else if((t=g)===v){d?1===d?o(t=l(t,e,i),e,i,n,s,c,2):2===d&&u(t,e,i,n,s,c):o(r(t),e,i,n,s,c,1);break}}}function a(t){var e=t.prev,i=t,n=t.next;if(y(e,i,n)>=0)return!1;for(var s=t.next.next;s!==t.prev;){if(g(e.x,e.y,i.x,i.y,n.x,n.y,s.x,s.y)&&y(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function h(t,e,i,n){var s=t.prev,r=t,o=t.next;if(y(s,r,o)>=0)return!1;for(var a=s.xr.x?s.x>o.x?s.x:o.x:r.x>o.x?r.x:o.x,u=s.y>r.y?s.y>o.y?s.y:o.y:r.y>o.y?r.y:o.y,c=f(a,h,e,i,n),d=f(l,u,e,i,n),p=t.prevZ,v=t.nextZ;p&&p.z>=c&&v&&v.z<=d;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&y(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&y(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&y(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;v&&v.z<=d;){if(v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&y(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function l(t,e,i){var n=t;do{var s=n.prev,r=n.next.next;!m(s,r)&&x(s,n,n.next,r)&&T(s,r)&&T(r,s)&&(e.push(s.i/i),e.push(n.i/i),e.push(r.i/i),E(n),E(n.next),n=t=r),n=n.next}while(n!==t);return n}function u(t,e,i,n,s,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&v(h,l)){var u=w(h,l);return h=r(h,h.next),u=r(u,u.next),o(h,e,i,n,s,a),void o(u,e,i,n,s,a)}l=l.next}h=h.next}while(h!==t)}function c(t,e){return t.x-e.x}function d(t,e){if(e=function(t,e){var i,n=e,s=t.x,r=t.y,o=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){var a=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=s&&a>o){if(o=a,a===s){if(r===n.y)return n;if(r===n.next.y)return n.next}i=n.x=n.x&&n.x>=u&&s!==n.x&&g(ri.x)&&T(n,t)&&(i=n,d=h),n=n.next;return i}(t,e)){var i=w(e,t);r(i,i.next)}}function f(t,e,i,n,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*s)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*s)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function p(t){var e=t,i=t;do{e.x=0&&(t-o)*(n-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(s-o)*(n-a)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&x(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&T(t,e)&&T(e,t)&&function(t,e){var i=t,n=!1,s=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&i.next.y!==i.y&&s<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)}function y(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function m(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,i,n){return!!(m(t,e)&&m(i,n)||m(t,n)&&m(i,e))||y(t,e,i)>0!=y(t,e,n)>0&&y(i,n,t)>0!=y(i,n,e)>0}function T(t,e){return y(t.prev,t,t.next)<0?y(t,e,t.next)>=0&&y(t,t.prev,e)>=0:y(t,e,t.prev)<0||y(t,t.next,e)<0}function w(t,e){var i=new S(t.i,t.x,t.y),n=new S(e.i,e.x,e.y),s=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,n.next=i,i.prev=n,r.next=n,n.prev=r,n}function b(t,e,i,n){var s=new S(t,e,i);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function E(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function S(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,i,n){for(var s=0,r=e,o=i-n;r0&&(n+=t[s-1].length,i.holes.push(n))}return i}},function(t,e){t.exports=function(t){var e={};for(var i in t)Array.isArray(t[i])?e[i]=t[i].slice(0):e[i]=t[i];return e}},function(t,e){t.exports=function(t,e,i,n){var s=t.length;if(e<0||e>s||e>=i||i>s||e+i>s){if(n)throw new Error("Range Error: Values outside acceptable range");return!1}return!0}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){var o=t.strokeTint,a=n.getTintAppendFloatAlphaAndSwap(e.strokeColor,e.strokeAlpha*i);o.TL=a,o.TR=a,o.BL=a,o.BR=a;var h=e.pathData,l=h.length-1,u=e.lineWidth,c=u/2,d=h[0]-s,f=h[1]-r;e.closePath||(l-=2);for(var p=2;p=this.x2&&this.x1>=this.x3?this.x1-t:this.x2>=this.x1&&this.x2>=this.x3?this.x2-t:this.x3-t,this.x1-=e,this.x2-=e,this.x3-=e}},top:{get:function(){return Math.min(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1<=this.y2&&this.y1<=this.y3?this.y1-t:this.y2<=this.y1&&this.y2<=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}},bottom:{get:function(){return Math.max(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1>=this.y2&&this.y1>=this.y3?this.y1-t:this.y2>=this.y1&&this.y2>=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}}});t.exports=u},function(t,e,i){var n=i(0),s=i(23),r=i(24),o=i(8),a=i(1),h=i(7),l=new n({Extends:r,initialize:function t(e,i,n,s,o){var l,u="png";if(h(i)){var c=i;i=a(c,"key"),n=a(c,"url"),l=a(c,"normalMap"),s=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"frameConfig")}Array.isArray(n)&&(l=n[1],n=n[0]);var d={type:"image",cache:e.textureManager,extension:u,responseType:"blob",key:i,url:n,xhrSettings:s,config:o};if(r.call(this,e,d),l){var f=new t(e,this.key,l,s,o);f.type="normalMap",this.setLink(f),e.addFile(f)}},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=new Image,this.data.crossOrigin=this.crossOrigin;var t=this;this.data.onload=function(){r.revokeObjectURL(t.data),t.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(t.data),t.onProcessError()},r.createObjectURL(this.data,this.xhrLoader.response,"image/png")},addToCache:function(){var t,e=this.linkFile;e&&e.state===s.FILE_COMPLETE?(t="image"===this.type?this.cache.addImage(this.key,this.data,e.data):this.cache.addImage(e.key,e.data,this.data),this.pendingDestroy(t),e.pendingDestroy(t)):e||(t=this.cache.addImage(this.key,this.data),this.pendingDestroy(t))}});o.register("image",function(t,e,i){if(Array.isArray(t))for(var n=0;n0?1:.7),e.damping=e.damping||0,e.angularStiffness=e.angularStiffness||0,e.angleA=e.bodyA?e.bodyA.angle:e.angleA,e.angleB=e.bodyB?e.bodyB.angle:e.angleB,e.plugin={};var o={visible:!0,type:"line",anchors:!0,lineColor:null,lineOpacity:null,lineThickness:null,pinSize:null,anchorColor:null,anchorSize:null};return 0===e.length&&e.stiffness>.1?(o.type="pin",o.anchors=!1):e.stiffness<.9&&(o.type="spring"),e.render=l.extend(o,e.render),e},n.preSolveAll=function(t){for(var e=0;e0&&(c.position.x+=l.x,c.position.y+=l.y),0!==l.angle&&(s.rotate(c.vertices,l.angle,i.position),h.rotate(c.axes,l.angle),u>0&&r.rotateAbout(c.position,l.angle,i.position,c.position)),a.update(c.bounds,c.vertices,i.velocity)}l.angle*=n._warming,l.x*=n._warming,l.y*=n._warming}}},n.pointAWorld=function(t){return{x:(t.bodyA?t.bodyA.position.x:0)+t.pointA.x,y:(t.bodyA?t.bodyA.position.y:0)+t.pointA.y}},n.pointBWorld=function(t){return{x:(t.bodyB?t.bodyB.position.x:0)+t.pointB.x,y:(t.bodyB?t.bodyB.position.y:0)+t.pointB.y}}},function(t,e){t.exports=function(t,e){e?t.setCollision(!0,!0,!0,!0,!1):t.resetCollision(!1)}},function(t,e,i){var n=i(0),s=i(12),r=i(467),o=new n({Mixins:[s.Alpha,s.Flip,s.Visible],initialize:function(t,e,i,n,s,r,o,a){this.layer=t,this.index=e,this.x=i,this.y=n,this.width=s,this.height=r,this.baseWidth=void 0!==o?o:s,this.baseHeight=void 0!==a?a:r,this.pixelX=0,this.pixelY=0,this.updatePixelXY(),this.properties={},this.rotation=0,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceLeft=!1,this.faceRight=!1,this.faceTop=!1,this.faceBottom=!1,this.collisionCallback=null,this.collisionCallbackContext=this,this.tint=16777215,this.physics={}},containsPoint:function(t,e){return!(tthis.right||e>this.bottom)},copy:function(t){return this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.visible=t.visible,this.setFlip(t.flipX,t.flipY),this.tint=t.tint,this.rotation=t.rotation,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext,this},getCollisionGroup:function(){return this.tileset?this.tileset.getTileCollisionGroup(this.index):null},getTileData:function(){return this.tileset?this.tileset.getTileData(this.index):null},getLeft:function(t){var e=this.tilemapLayer;return e?e.tileToWorldX(this.x,t):this.x*this.baseWidth},getRight:function(t){var e=this.tilemapLayer;return e?this.getLeft(t)+this.width*e.scaleX:this.getLeft(t)+this.width},getTop:function(t){var e=this.tilemapLayer;return e?e.tileToWorldY(this.y,t)-(this.height-this.baseHeight)*e.scaleY:this.y*this.baseHeight-(this.height-this.baseHeight)},getBottom:function(t){var e=this.tilemapLayer;return e?this.getTop(t)+this.height*e.scaleY:this.getTop(t)+this.height},getBounds:function(t,e){return void 0===e&&(e=new r),e.x=this.getLeft(),e.y=this.getTop(),e.width=this.getRight()-e.x,e.height=this.getBottom()-e.y,e},getCenterX:function(t){return(this.getLeft(t)+this.getRight(t))/2},getCenterY:function(t){return(this.getTop(t)+this.getBottom(t))/2},destroy:function(){this.collisionCallback=void 0,this.collisionCallbackContext=void 0,this.properties=void 0},intersects:function(t,e,i,n){return!(i<=this.pixelX||n<=this.pixelY||t>=this.right||e>=this.bottom)},isInteresting:function(t,e){return t&&e?this.canCollide||this.hasInterestingFace:t?this.collides:!!e&&this.hasInterestingFace},resetCollision:function(t){(void 0===t&&(t=!0),this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,t)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},resetFaces:function(){return this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this},setCollision:function(t,e,i,n,s){(void 0===e&&(e=t),void 0===i&&(i=t),void 0===n&&(n=t),void 0===s&&(s=!0),this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=n,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=n,s)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},setCollisionCallback:function(t,e){return null===t?(this.collisionCallback=void 0,this.collisionCallbackContext=void 0):(this.collisionCallback=t,this.collisionCallbackContext=e),this},setSize:function(t,e,i,n){return void 0!==t&&(this.width=t),void 0!==e&&(this.height=e),void 0!==i&&(this.baseWidth=i),void 0!==n&&(this.baseHeight=n),this.updatePixelXY(),this},updatePixelXY:function(){return this.pixelX=this.x*this.baseWidth,this.pixelY=this.y*this.baseHeight,this},canCollide:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}},collides:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}},hasInterestingFace:{get:function(){return this.faceTop||this.faceBottom||this.faceLeft||this.faceRight}},tileset:{get:function(){var t=this.layer.tilemapLayer;if(t){var e=t.gidMap[this.index];if(e)return e}return null}},tilemapLayer:{get:function(){return this.layer.tilemapLayer}},tilemap:{get:function(){var t=this.tilemapLayer;return t?t.tilemap:null}}});t.exports=o},function(t,e){t.exports=function(t){return t.x-t.width*t.originX+.5*t.width}},function(t,e){t.exports=function(t,e){var i=t.width*t.originX;return t.x=e+i-.5*t.width,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY+.5*t.height}},function(t,e){t.exports=function(t,e){var i=t.height*t.originY;return t.y=e+i-.5*t.height,t}},function(t,e){t.exports=function(t,e){if(!(e>=t.length)){for(var i=t.length-1,n=t[e],s=e;si&&(e=i/2);var n=Math.max(1,Math.round(i/e));return s(this.getSpacedPoints(n),t)},getDistancePoints:function(t){var e=this.getLength(),i=Math.max(1,e/t);return this.getSpacedPoints(i)},getEndPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(1,t)},getLength:function(){var t=this.getLengths();return t[t.length-1]},getLengths:function(t){if(void 0===t&&(t=this.arcLengthDivisions),this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,i=[],n=this.getPoint(0,this._tmpVec2A),s=0;i.push(0);for(var r=1;r<=t;r++)s+=(e=this.getPoint(r/t,this._tmpVec2B)).distance(n),i.push(s),n.copy(e);return this.cacheArcLengths=i,i},getPointAt:function(t,e){var i=this.getUtoTmapping(t);return this.getPoint(i,e)},getPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++)i.push(this.getPoint(n/t));return i},getRandomPoint:function(t){return void 0===t&&(t=new o),this.getPoint(Math.random(),t)},getSpacedPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++){var s=this.getUtoTmapping(n/t,null,t);i.push(this.getPoint(s))}return i},getStartPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(0,t)},getTangent:function(t,e){void 0===e&&(e=new o);var i=t-1e-4,n=t+1e-4;return i<0&&(i=0),n>1&&(n=1),this.getPoint(i,this._tmpVec2A),this.getPoint(n,e),e.subtract(this._tmpVec2A).normalize()},getTangentAt:function(t,e){var i=this.getUtoTmapping(t);return this.getTangent(i,e)},getTFromDistance:function(t,e){return t<=0?0:this.getUtoTmapping(0,t,e)},getUtoTmapping:function(t,e,i){var n,s=this.getLengths(i),r=0,o=s.length;n=e?Math.min(e,s[o-1]):t*s[o-1];for(var a,h=0,l=o-1;h<=l;)if((a=s[r=Math.floor(h+(l-h)/2)]-n)<0)h=r+1;else{if(!(a>0)){l=r;break}l=r-1}if(s[r=l]===n)return r/(o-1);var u=s[r];return(r+(n-u)/(s[r+1]-u))/(o-1)},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths()}});t.exports=a},function(t,e,i){t.exports={ADD:i(893),COMPLETE:i(894),FILE_COMPLETE:i(895),FILE_KEY_COMPLETE:i(896),FILE_LOAD_ERROR:i(897),FILE_LOAD:i(898),FILE_PROGRESS:i(899),POST_PROCESS:i(900),PROGRESS:i(901),START:i(902)}},function(t,e,i){var n=i(73);t.exports=function(t,e){var i=n(t);for(var s in e)i.hasOwnProperty(s)||(i[s]=e[s]);return i}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(1e3),a=new n({Extends:r,Mixins:[s.Alpha,s.BlendMode,s.Depth,s.Flip,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Size,s.TextureCrop,s.Tint,s.Transform,s.Visible,o],initialize:function(t,e,i,n,s){r.call(this,t,"Image"),this._crop=this.resetCropObject(),this.setTexture(n,s),this.setPosition(e,i),this.setSizeToFrame(),this.setOriginFromFrame(),this.initPipeline()}});t.exports=a},function(t,e,i){var n=i(179),s=i(194);t.exports=function(t,e){var i=n.Power0;if("string"==typeof t)if(n.hasOwnProperty(t))i=n[t];else{var r="";t.indexOf(".")&&("in"===(r=t.substr(t.indexOf(".")+1)).toLowerCase()?r="easeIn":"out"===r.toLowerCase()?r="easeOut":"inout"===r.toLowerCase()&&(r="easeInOut")),t=s(t.substr(0,t.indexOf(".")+1)+r),n.hasOwnProperty(t)&&(i=n[t])}else"function"==typeof t?i=t:Array.isArray(t)&&t.length;if(!e)return i;var o=e.slice(0);return o.unshift(0),function(t){return o[0]=t,i.apply(this,o)}}},function(t,e){t.exports=function(t,e){return t.hasOwnProperty(e)}},function(t,e){t.exports=function(t,e,i){var n=t.x3-t.x1,s=t.y3-t.y1,r=t.x2-t.x1,o=t.y2-t.y1,a=e-t.x1,h=i-t.y1,l=n*n+s*s,u=n*r+s*o,c=n*a+s*h,d=r*r+o*o,f=r*a+o*h,p=l*d-u*u,g=0===p?0:1/p,v=(d*c-u*f)*g,y=(l*f-u*c)*g;return v>=0&&y>=0&&v+y<1}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.x1,r=t.y1,o=t.x2,a=t.y2,h=e.x1,l=e.y1,u=e.x2,c=e.y2,d=(u-h)*(r-l)-(c-l)*(s-h),f=(o-s)*(r-l)-(a-r)*(s-h),p=(c-l)*(o-s)-(u-h)*(a-r);if(0===p)return!1;var g=d/p,v=f/p;return g>=0&&g<=1&&v>=0&&v<=1&&(i.x=s+g*(o-s),i.y=r+g*(a-r),!0)}},function(t,e){t.exports=function(t){return Math.atan2(t.y2-t.y1,t.x2-t.x1)}},function(t,e,i){var n={};t.exports=n;var s=i(96);n._motionWakeThreshold=.18,n._motionSleepThreshold=.08,n._minBias=.9,n.update=function(t,e){for(var i=e*e*e,s=0;s0&&r.motion=r.sleepThreshold&&n.set(r,!0)):r.sleepCounter>0&&(r.sleepCounter-=1)}else n.set(r,!1)}},n.afterCollisions=function(t,e){for(var i=e*e*e,s=0;sn._motionWakeThreshold*i&&n.set(l,!1)}}}},n.set=function(t,e){var i=t.isSleeping;e?(t.isSleeping=!0,t.sleepCounter=t.sleepThreshold,t.positionImpulse.x=0,t.positionImpulse.y=0,t.positionPrev.x=t.position.x,t.positionPrev.y=t.position.y,t.anglePrev=t.angle,t.speed=0,t.angularSpeed=0,t.motion=0,i||s.trigger(t,"sleepStart")):(t.isSleeping=!1,t.sleepCounter=0,i&&s.trigger(t,"sleepEnd"))}},function(t,e,i){var n={};t.exports=n;var s=i(19);n.on=function(t,e,i){for(var n,s=e.split(" "),r=0;r0){i||(i={}),n=e.split(" ");for(var l=0;lC&&wA&&b<_&&f.push(v)}else f.push(v)}return f},getWorldPoint:function(t,e,i){void 0===i&&(i=new c);var n=this.matrix.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5],u=s*a-r*o;if(!u)return i.x=t,i.y=e,i;var d=a*(u=1/u),f=-r*u,p=-o*u,g=s*u,v=(o*l-a*h)*u,y=(r*h-s*l)*u,m=Math.cos(this.rotation),x=Math.sin(this.rotation),T=this.zoom,w=this.resolution,b=this.scrollX,E=this.scrollY,S=t+(b*m-E*x)*T,A=e+(b*x+E*m)*T;return i.x=(S*d+A*p)*w+v,i.y=(S*f+A*g)*w+y,i},ignore:function(t){var e=this.id;Array.isArray(t)||(t=[t]);for(var i=0;is&&(t=s),t},clampY:function(t){var e=this._bounds,i=this.displayHeight,n=e.y+(i-this.height)/2,s=Math.max(n,n+e.height-i);return ts&&(t=s),t},removeBounds:function(){return this.useBounds=!1,this.dirty=!0,this._bounds.setEmpty(),this},setAngle:function(t){return void 0===t&&(t=0),this.rotation=r(t),this},setBackgroundColor:function(t){return void 0===t&&(t="rgba(0,0,0,0)"),this.backgroundColor=u(t),this.transparent=0===this.backgroundColor.alpha,this},setBounds:function(t,e,i,n,s){return void 0===s&&(s=!1),this._bounds.setTo(t,e,i,n),this.dirty=!0,this.useBounds=!0,s?this.centerToBounds():(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},getBounds:function(t){void 0===t&&(t=new h);var e=this._bounds;return t.setTo(e.x,e.y,e.width,e.height),t},setName:function(t){return void 0===t&&(t=""),this.name=t,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setRotation:function(t){return void 0===t&&(t=0),this.rotation=t,this},setRoundPixels:function(t){return this.roundPixels=t,this},setScene:function(t){this.scene&&this._customViewport&&this.sceneManager.customViewports--,this.scene=t;var e=t.sys;this.sceneManager=e.game.scene,this.scaleManager=e.scale,this.cameraManager=e.cameras;var i=this.scaleManager.resolution;return this.resolution=i,this._cx=this._x*i,this._cy=this._y*i,this._cw=this._width*i,this._ch=this._height*i,this.updateSystem(),this},setScroll:function(t,e){return void 0===e&&(e=t),this.scrollX=t,this.scrollY=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},setViewport:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setZoom:function(t){return void 0===t&&(t=1),0===t&&(t=.001),this.zoom=t,this},setMask:function(t,e){return void 0===e&&(e=!0),this.mask=t,this._maskCamera=e?this.cameraManager.default:this,this},clearMask:function(t){return void 0===t&&(t=!1),t&&this.mask&&this.mask.destroy(),this.mask=null,this},toJSON:function(){var t={name:this.name,x:this.x,y:this.y,width:this.width,height:this.height,zoom:this.zoom,rotation:this.rotation,roundPixels:this.roundPixels,scrollX:this.scrollX,scrollY:this.scrollY,backgroundColor:this.backgroundColor.rgba};return this.useBounds&&(t.bounds={x:this._bounds.x,y:this._bounds.y,width:this._bounds.width,height:this._bounds.height}),t},update:function(){},updateSystem:function(){if(this.scaleManager){var t=0!==this._x||0!==this._y||this.scaleManager.width!==this._width||this.scaleManager.height!==this._height,e=this.sceneManager;t&&!this._customViewport?e.customViewports++:!t&&this._customViewport&&e.customViewports--,this.dirty=!0,this._customViewport=t}},destroy:function(){this.emit(a.DESTROY,this),this.removeAllListeners(),this.matrix.destroy(),this.culledObjects=[],this._customViewport&&this.sceneManager.customViewports--,this._bounds=null,this.scene=null,this.scaleManager=null,this.sceneManager=null,this.cameraManager=null},x:{get:function(){return this._x},set:function(t){this._x=t,this._cx=t*this.resolution,this.updateSystem()}},y:{get:function(){return this._y},set:function(t){this._y=t,this._cy=t*this.resolution,this.updateSystem()}},width:{get:function(){return this._width},set:function(t){this._width=t,this._cw=t*this.resolution,this.updateSystem()}},height:{get:function(){return this._height},set:function(t){this._height=t,this._ch=t*this.resolution,this.updateSystem()}},scrollX:{get:function(){return this._scrollX},set:function(t){this._scrollX=t,this.dirty=!0}},scrollY:{get:function(){return this._scrollY},set:function(t){this._scrollY=t,this.dirty=!0}},zoom:{get:function(){return this._zoom},set:function(t){this._zoom=t,this.dirty=!0}},rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this.dirty=!0}},centerX:{get:function(){return this.x+.5*this.width}},centerY:{get:function(){return this.y+.5*this.height}},displayWidth:{get:function(){return this.width/this.zoom}},displayHeight:{get:function(){return this.height/this.zoom}}});t.exports=d},function(t,e,i){t.exports={ENTER_FULLSCREEN:i(726),FULLSCREEN_FAILED:i(727),FULLSCREEN_UNSUPPORTED:i(728),LEAVE_FULLSCREEN:i(729),ORIENTATION_CHANGE:i(730),RESIZE:i(731)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=i(0),s=i(20),r=i(17),o=new n({initialize:function(t,e,i,n,s,r,o){this.texture=t,this.name=e,this.source=t.source[i],this.sourceIndex=i,this.glTexture=this.source.glTexture,this.cutX,this.cutY,this.cutWidth,this.cutHeight,this.x=0,this.y=0,this.width,this.height,this.halfWidth,this.halfHeight,this.centerX,this.centerY,this.pivotX=0,this.pivotY=0,this.customPivot=!1,this.rotated=!1,this.autoRound=-1,this.customData={},this.u0=0,this.v0=0,this.u1=0,this.v1=0,this.data={cut:{x:0,y:0,w:0,h:0,r:0,b:0},trim:!1,sourceSize:{w:0,h:0},spriteSourceSize:{x:0,y:0,w:0,h:0,r:0,b:0},radius:0,drawImage:{x:0,y:0,width:0,height:0}},this.setSize(r,o,n,s)},setSize:function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this.cutX=i,this.cutY=n,this.cutWidth=t,this.cutHeight=e,this.width=t,this.height=e,this.halfWidth=Math.floor(.5*t),this.halfHeight=Math.floor(.5*e),this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2);var s=this.data,r=s.cut;r.x=i,r.y=n,r.w=t,r.h=e,r.r=i+t,r.b=n+e,s.sourceSize.w=t,s.sourceSize.h=e,s.spriteSourceSize.w=t,s.spriteSourceSize.h=e,s.radius=.5*Math.sqrt(t*t+e*e);var o=s.drawImage;return o.x=i,o.y=n,o.width=t,o.height=e,this.updateUVs()},setTrim:function(t,e,i,n,s,r){var o=this.data,a=o.spriteSourceSize;return o.trim=!0,o.sourceSize.w=t,o.sourceSize.h=e,a.x=i,a.y=n,a.w=s,a.h=r,a.r=i+s,a.b=n+r,this.x=i,this.y=n,this.width=s,this.height=r,this.halfWidth=.5*s,this.halfHeight=.5*r,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.updateUVs()},setCropUVs:function(t,e,i,n,r,o,a){var h=this.cutX,l=this.cutY,u=this.cutWidth,c=this.cutHeight,d=this.realWidth,f=this.realHeight,p=h+(e=s(e,0,d)),g=l+(i=s(i,0,f)),v=n=s(n,0,d-e),y=r=s(r,0,f-i),m=this.data;if(m.trim){var x=m.spriteSourceSize,T=e+(n=s(n,0,u-e)),w=i+(r=s(r,0,c-i));if(!(x.rT||x.y>w)){var b=Math.max(x.x,e),E=Math.max(x.y,i),S=Math.min(x.r,T)-b,A=Math.min(x.b,w)-E;v=S,y=A,p=o?h+(u-(b-x.x)-S):h+(b-x.x),g=a?l+(c-(E-x.y)-A):l+(E-x.y),e=b,i=E,n=S,r=A}else p=0,g=0,v=0,y=0}else o&&(p=h+(u-e-n)),a&&(g=l+(c-i-r));var _=this.source.width,C=this.source.height;return t.u0=Math.max(0,p/_),t.v0=Math.max(0,g/C),t.u1=Math.min(1,(p+v)/_),t.v1=Math.min(1,(g+y)/C),t.x=e,t.y=i,t.cx=p,t.cy=g,t.cw=v,t.ch=y,t.width=n,t.height=r,t.flipX=o,t.flipY=a,t},updateCropUVs:function(t,e,i){return this.setCropUVs(t,t.x,t.y,t.width,t.height,e,i)},updateUVs:function(){var t=this.cutX,e=this.cutY,i=this.cutWidth,n=this.cutHeight,s=this.data.drawImage;s.width=i,s.height=n;var r=this.source.width,o=this.source.height;return this.u0=t/r,this.v0=e/o,this.u1=(t+i)/r,this.v1=(e+n)/o,this},updateUVsInverted:function(){var t=this.source.width,e=this.source.height;return this.u0=(this.cutX+this.cutHeight)/t,this.v0=this.cutY/e,this.u1=this.cutX/t,this.v1=(this.cutY+this.cutWidth)/e,this},clone:function(){var t=new o(this.texture,this.name,this.sourceIndex);return t.cutX=this.cutX,t.cutY=this.cutY,t.cutWidth=this.cutWidth,t.cutHeight=this.cutHeight,t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t.halfWidth=this.halfWidth,t.halfHeight=this.halfHeight,t.centerX=this.centerX,t.centerY=this.centerY,t.rotated=this.rotated,t.data=r(!0,t.data,this.data),t.updateUVs(),t},destroy:function(){this.source=null,this.texture=null,this.glTexture=null,this.customData=null,this.data=null},realWidth:{get:function(){return this.data.sourceSize.w}},realHeight:{get:function(){return this.data.sourceSize.h}},radius:{get:function(){return this.data.radius}},trimmed:{get:function(){return this.data.trim}},canvasData:{get:function(){return this.data.drawImage}}});t.exports=o},function(t,e,i){var n=i(0),s=i(108),r=i(421),o=i(422),a=i(52),h=i(167),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=a.ELLIPSE,this.x=t,this.y=e,this.width=i,this.height=n},contains:function(t,e){return s(this,t,e)},getPoint:function(t,e){return r(this,t,e)},getPoints:function(t,e,i){return o(this,t,e,i)},getRandomPoint:function(t){return h(this,t)},setTo:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setEmpty:function(){return this.width=0,this.height=0,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},isEmpty:function(){return this.width<=0||this.height<=0},getMinorRadius:function(){return Math.min(this.width,this.height)/2},getMajorRadius:function(){return Math.max(this.width,this.height)/2},left:{get:function(){return this.x-this.width/2},set:function(t){this.x=t+this.width/2}},right:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},top:{get:function(){return this.y-this.height/2},set:function(t){this.y=t+this.height/2}},bottom:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=l},function(t,e){t.exports=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var n=(e-t.x)/t.width,s=(i-t.y)/t.height;return(n*=n)+(s*=s)<.25}},function(t,e,i){var n=i(259),s=i(0),r=i(102),o=i(1),a=i(5),h=i(7),l=i(415),u=i(110),c=i(65),d=new s({initialize:function(t,e,i){i?e&&!Array.isArray(e)&&(e=[e]):Array.isArray(e)?h(e[0])&&(i=e,e=null):h(e)&&(i=e,e=null),this.scene=t,this.children=new u(e),this.isParent=!0,this.type="Group",this.classType=o(i,"classType",c),this.name=o(i,"name",""),this.active=o(i,"active",!0),this.maxSize=o(i,"maxSize",-1),this.defaultKey=o(i,"defaultKey",null),this.defaultFrame=o(i,"defaultFrame",null),this.runChildUpdate=o(i,"runChildUpdate",!1),this.createCallback=o(i,"createCallback",null),this.removeCallback=o(i,"removeCallback",null),this.createMultipleCallback=o(i,"createMultipleCallback",null),this.internalCreateCallback=o(i,"internalCreateCallback",null),this.internalRemoveCallback=o(i,"internalRemoveCallback",null),i&&this.createMultiple(i)},create:function(t,e,i,n,s,r){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.defaultKey),void 0===n&&(n=this.defaultFrame),void 0===s&&(s=!0),void 0===r&&(r=!0),this.isFull())return null;var o=new this.classType(this.scene,t,e,i,n);return this.scene.sys.displayList.add(o),o.preUpdate&&this.scene.sys.updateList.add(o),o.visible=s,o.setActive(r),this.add(o),o},createMultiple:function(t){if(this.isFull())return[];Array.isArray(t)||(t=[t]);var e=[];if(t[0].key)for(var i=0;i=0;u--)if((l=d[u]).active===i){if(++c===e)break}else l=null;return l?("number"==typeof s&&(l.x=s),"number"==typeof r&&(l.y=r),l):n?this.create(s,r,o,a,h):null},get:function(t,e,i,n,s){return this.getFirst(!1,!0,t,e,i,n,s)},getFirstAlive:function(t,e,i,n,s,r){return this.getFirst(!0,t,e,i,n,s,r)},getFirstDead:function(t,e,i,n,s,r){return this.getFirst(!1,t,e,i,n,s,r)},playAnimation:function(t,e){return n.PlayAnimation(this.children.entries,t,e),this},isFull:function(){return-1!==this.maxSize&&this.children.size>=this.maxSize},countActive:function(t){void 0===t&&(t=!0);for(var e=0,i=0;i-1&&this.entries.splice(e,1),this},dump:function(){console.group("Set");for(var t=0;t-1},union:function(t){var e=new n;return t.entries.forEach(function(t){e.set(t)}),this.entries.forEach(function(t){e.set(t)}),e},intersect:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)&&e.set(i)}),e},difference:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)||e.set(i)}),e},size:{get:function(){return this.entries.length},set:function(t){return t=0&&t=0&&e0;e--){var i=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[i],t[i]=n}return t}},function(t,e){t.exports=function(t,e,i){return(e-t)*i+t}},function(t,e,i){(function(e){var i={android:!1,chromeOS:!1,cordova:!1,crosswalk:!1,desktop:!1,ejecta:!1,electron:!1,iOS:!1,iOSVersion:0,iPad:!1,iPhone:!1,kindle:!1,linux:!1,macOS:!1,node:!1,nodeWebkit:!1,pixelRatio:1,webApp:!1,windows:!1,windowsPhone:!1};t.exports=function(){var t=navigator.userAgent;/Windows/.test(t)?i.windows=!0:/Mac OS/.test(t)&&!/like Mac OS/.test(t)?i.macOS=!0:/Android/.test(t)?i.android=!0:/Linux/.test(t)?i.linux=!0:/iP[ao]d|iPhone/i.test(t)?(i.iOS=!0,navigator.appVersion.match(/OS (\d+)/),i.iOSVersion=parseInt(RegExp.$1,10),i.iPhone=-1!==t.toLowerCase().indexOf("iphone"),i.iPad=-1!==t.toLowerCase().indexOf("ipad")):/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?i.kindle=!0:/CrOS/.test(t)&&(i.chromeOS=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(i.android=!1,i.iOS=!1,i.macOS=!1,i.windows=!0,i.windowsPhone=!0);var n=/Silk/.test(t);return(i.windows||i.macOS||i.linux&&!n||i.chromeOS)&&(i.desktop=!0),(i.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(i.desktop=!1),navigator.standalone&&(i.webApp=!0),void 0!==window.cordova&&(i.cordova=!0),void 0!==e&&e.versions&&e.versions.node&&(i.node=!0),i.node&&"object"==typeof e.versions&&(i.nodeWebkit=!!e.versions["node-webkit"],i.electron=!!e.versions.electron),void 0!==window.ejecta&&(i.ejecta=!0),/Crosswalk/.test(t)&&(i.crosswalk=!0),i.pixelRatio=window.devicePixelRatio||1,i}()}).call(this,i(752))},function(t,e,i){var n,s=i(124),r={chrome:!1,chromeVersion:0,edge:!1,firefox:!1,firefoxVersion:0,ie:!1,ieVersion:0,mobileSafari:!1,opera:!1,safari:!1,safariVersion:0,silk:!1,trident:!1,tridentVersion:0};t.exports=(n=navigator.userAgent,/Edge\/\d+/.test(n)?r.edge=!0:/Chrome\/(\d+)/.test(n)&&!s.windowsPhone?(r.chrome=!0,r.chromeVersion=parseInt(RegExp.$1,10)):/Firefox\D+(\d+)/.test(n)?(r.firefox=!0,r.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(n)&&s.iOS?r.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(n)?(r.ie=!0,r.ieVersion=parseInt(RegExp.$1,10)):/Opera/.test(n)?r.opera=!0:/Safari/.test(n)&&!s.windowsPhone?r.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(n)&&(r.ie=!0,r.trident=!0,r.tridentVersion=parseInt(RegExp.$1,10),r.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(n)&&(r.silk=!0),r)},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)0&&0==(t&t-1)&&e>0&&0==(e&e-1)}},function(t,e,i){t.exports={ADD:i(803),ERROR:i(804),LOAD:i(805),READY:i(806),REMOVE:i(807)}},function(t,e){t.exports=function(t,e){var i;if(e)"string"==typeof e?i=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(i=e);else if(t.parentElement)return t;return i||(i=document.body),i.appendChild(t),t}},function(t,e,i){var n=i(85);t.exports=function(t,e,i,s){var r;if(void 0===s&&(s=t),!Array.isArray(e))return-1!==(r=t.indexOf(e))?(n(t,r),i&&i.call(s,e),e):null;for(var o=e.length-1;o>=0;){var a=e[o];-1!==(r=t.indexOf(a))?(n(t,r),i&&i.call(s,a)):e.pop(),o--}return e}},function(t,e){t.exports={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:42,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,NUMPAD_ZERO:96,NUMPAD_ONE:97,NUMPAD_TWO:98,NUMPAD_THREE:99,NUMPAD_FOUR:100,NUMPAD_FIVE:101,NUMPAD_SIX:102,NUMPAD_SEVEN:103,NUMPAD_EIGHT:104,NUMPAD_NINE:105,NUMPAD_ADD:107,NUMPAD_SUBTRACT:109,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,SEMICOLON:186,PLUS:187,COMMA:188,MINUS:189,PERIOD:190,FORWARD_SLASH:191,BACK_SLASH:220,QUOTES:222,BACKTICK:192,OPEN_BRACKET:219,CLOSED_BRACKET:221,SEMICOLON_FIREFOX:59,COLON:58,COMMA_FIREFOX_WINDOWS:60,COMMA_FIREFOX:62,BRACKET_RIGHT_FIREFOX:174,BRACKET_LEFT_FIREFOX:175}},function(t,e){t.exports={PENDING:0,INIT:1,START:2,LOADING:3,CREATING:4,RUNNING:5,PAUSED:6,SLEEPING:7,SHUTDOWN:8,DESTROYED:9}},function(t,e,i){var n=i(0),s=i(73),r=i(9),o=i(64),a=i(21),h=i(2),l=new n({Extends:r,initialize:function(t){r.call(this),this.game=t,this.jsonCache=t.cache.json,this.sounds=[],this.mute=!1,this.volume=1,this.pauseOnBlur=!0,this._rate=1,this._detune=0,this.locked=this.locked||!1,this.unlocked=!1,t.events.on(a.BLUR,function(){this.pauseOnBlur&&this.onBlur()},this),t.events.on(a.FOCUS,function(){this.pauseOnBlur&&this.onFocus()},this),t.events.on(a.PRE_STEP,this.update,this),t.events.once(a.DESTROY,this.destroy,this)},add:h,addAudioSprite:function(t,e){void 0===e&&(e={});var i=this.add(t,e);for(var n in i.spritemap=this.jsonCache.get(t).spritemap,i.spritemap)if(i.spritemap.hasOwnProperty(n)){var r=s(e),o=i.spritemap[n];r.loop=!!o.hasOwnProperty("loop")&&o.loop,i.addMarker({name:n,start:o.start,duration:o.end-o.start,config:r})}return i},play:function(t,e){var i=this.add(t);return i.once(o.COMPLETE,i.destroy,i),e?e.name?(i.addMarker(e),i.play(e.name)):i.play(e):i.play()},playAudioSprite:function(t,e,i){var n=this.addAudioSprite(t);return n.once(o.COMPLETE,n.destroy,n),n.play(e,i)},remove:function(t){var e=this.sounds.indexOf(t);return-1!==e&&(t.destroy(),this.sounds.splice(e,1),!0)},removeByKey:function(t){for(var e=0,i=this.sounds.length-1;i>=0;i--){var n=this.sounds[i];n.key===t&&(n.destroy(),this.sounds.splice(i,1),e++)}return e},pauseAll:function(){this.forEachActiveSound(function(t){t.pause()}),this.emit(o.PAUSE_ALL,this)},resumeAll:function(){this.forEachActiveSound(function(t){t.resume()}),this.emit(o.RESUME_ALL,this)},stopAll:function(){this.forEachActiveSound(function(t){t.stop()}),this.emit(o.STOP_ALL,this)},unlock:h,onBlur:h,onFocus:h,update:function(t,e){this.unlocked&&(this.unlocked=!1,this.locked=!1,this.emit(o.UNLOCKED,this));for(var i=this.sounds.length-1;i>=0;i--)this.sounds[i].pendingRemove&&this.sounds.splice(i,1);this.sounds.forEach(function(i){i.update(t,e)})},destroy:function(){this.removeAllListeners(),this.forEachActiveSound(function(t){t.destroy()}),this.sounds.length=0,this.sounds=null,this.game=null},forEachActiveSound:function(t,e){var i=this;this.sounds.forEach(function(n,s){n&&!n.pendingRemove&&t.call(e||i,n,s,i.sounds)})},setRate:function(t){return this.rate=t,this},rate:{get:function(){return this._rate},set:function(t){this._rate=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_RATE,this,t)}},setDetune:function(t){return this.detune=t,this},detune:{get:function(){return this._detune},set:function(t){this._detune=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_DETUNE,this,t)}}});t.exports=l},function(t,e,i){var n=i(0),s=i(9),r=i(64),o=i(17),a=i(2),h=new n({Extends:s,initialize:function(t,e,i){s.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=this.duration||0,this.totalDuration=this.totalDuration||0,this.config={mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},this.currentConfig=this.config,this.config=o(this.config,i),this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(console.error("addMarker "+t.name+" already exists in Sound"),!1):(t=o(!0,{name:"",start:0,duration:this.totalDuration-(t.start||0),config:{mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0}},t),this.markers[t.name]=t,!0))},updateMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(this.markers[t.name]=o(!0,this.markers[t.name],t),!0):(console.warn("Audio Marker: "+t.name+" missing in Sound: "+this.key),!1))},removeMarker:function(t){var e=this.markers[t];return e?(this.markers[t]=null,e):null},play:function(t,e){if(void 0===t&&(t=""),"object"==typeof t&&(e=t,t=""),"string"!=typeof t)return!1;if(t){if(!this.markers[t])return console.warn("Marker: "+t+" missing in Sound: "+this.key),!1;this.currentMarker=this.markers[t],this.currentConfig=this.currentMarker.config,this.duration=this.currentMarker.duration}else this.currentMarker=null,this.currentConfig=this.config,this.duration=this.totalDuration;return this.resetConfig(),this.currentConfig=o(this.currentConfig,e),this.isPlaying=!0,this.isPaused=!1,!0},pause:function(){return!(this.isPaused||!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!0,!0)},resume:function(){return!(!this.isPaused||this.isPlaying)&&(this.isPlaying=!0,this.isPaused=!1,!0)},stop:function(){return!(!this.isPaused&&!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!1,this.resetConfig(),!0)},applyConfig:function(){this.mute=this.currentConfig.mute,this.volume=this.currentConfig.volume,this.rate=this.currentConfig.rate,this.detune=this.currentConfig.detune,this.loop=this.currentConfig.loop},resetConfig:function(){this.currentConfig.seek=0,this.currentConfig.delay=0},update:a,calculateRate:function(){var t=this.currentConfig.detune+this.manager.detune,e=Math.pow(1.0005777895065548,t);this.totalRate=this.currentConfig.rate*this.manager.rate*e},destroy:function(){this.pendingRemove||(this.emit(r.DESTROY,this),this.pendingRemove=!0,this.manager=null,this.key="",this.removeAllListeners(),this.isPlaying=!1,this.isPaused=!1,this.config=null,this.currentConfig=null,this.markers=null,this.currentMarker=null)}});t.exports=h},function(t,e,i){var n=i(196),s=i(0),r=i(2),o=i(137),a=new s({initialize:function(t){this.parent=t,this.list=[],this.position=0,this.addCallback=r,this.removeCallback=r,this._sortKey=""},add:function(t,e){return e?n.Add(this.list,t):n.Add(this.list,t,0,this.addCallback,this)},addAt:function(t,e,i){return i?n.AddAt(this.list,t,e):n.AddAt(this.list,t,e,0,this.addCallback,this)},getAt:function(t){return this.list[t]},getIndex:function(t){return this.list.indexOf(t)},sort:function(t,e){return t?(void 0===e&&(e=function(e,i){return e[t]-i[t]}),o.inplace(this.list,e),this):this},getByName:function(t){return n.GetFirst(this.list,"name",t)},getRandom:function(t,e){return n.GetRandom(this.list,t,e)},getFirst:function(t,e,i,s){return n.GetFirst(this.list,t,e,i,s)},getAll:function(t,e,i,s){return n.GetAll(this.list,t,e,i,s)},count:function(t,e){return n.CountAllMatching(this.list,t,e)},swap:function(t,e){n.Swap(this.list,t,e)},moveTo:function(t,e){return n.MoveTo(this.list,t,e)},remove:function(t,e){return e?n.Remove(this.list,t):n.Remove(this.list,t,this.removeCallback,this)},removeAt:function(t,e){return e?n.RemoveAt(this.list,t):n.RemoveAt(this.list,t,this.removeCallback,this)},removeBetween:function(t,e,i){return i?n.RemoveBetween(this.list,t,e):n.RemoveBetween(this.list,t,e,this.removeCallback,this)},removeAll:function(t){for(var e=this.list.length;e--;)this.remove(this.list[e],t);return this},bringToTop:function(t){return n.BringToTop(this.list,t)},sendToBack:function(t){return n.SendToBack(this.list,t)},moveUp:function(t){return n.MoveUp(this.list,t),t},moveDown:function(t){return n.MoveDown(this.list,t),t},reverse:function(){return this.list.reverse(),this},shuffle:function(){return n.Shuffle(this.list),this},replace:function(t,e){return n.Replace(this.list,t,e)},exists:function(t){return this.list.indexOf(t)>-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){for(var i=[null],n=2;n0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}}});t.exports=a},function(t,e,i){var n=i(197),s=i(413);t.exports=function(t,e){if(void 0===e&&(e=90),!n(t))return null;if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)(t=s(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t.reverse(),t=s(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;il&&(r=l),o>l&&(o=l),a=s,h=r;;)if(a0&&o.length0&&a.lengthe.right||t.y>e.bottom)}},function(t,e,i){var n=i(5),s={},r={register:function(t,e,i,n,r){s[t]={plugin:e,mapping:i,settingsKey:n,configKey:r}},getPlugin:function(t){return s[t]},install:function(t){var e=t.scene.sys,i=e.settings.input,r=e.game.config;for(var o in s){var a=s[o].plugin,h=s[o].mapping,l=s[o].settingsKey,u=s[o].configKey;n(i,l,r[u])&&(t[h]=new a(t))}},remove:function(t){s.hasOwnProperty(t)&&delete s[t]}};t.exports=r},function(t,e,i){t.exports={ANY_KEY_DOWN:i(1240),ANY_KEY_UP:i(1241),COMBO_MATCH:i(1242),DOWN:i(1243),KEY_DOWN:i(1244),KEY_UP:i(1245),UP:i(1246)}},function(t,e){t.exports=function(t,e){return!!t.url&&(t.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t.url:e+t.url)}},function(t,e){t.exports=function(t,e,i,n,s){return void 0===t&&(t=""),void 0===e&&(e=!0),void 0===i&&(i=""),void 0===n&&(n=""),void 0===s&&(s=0),{responseType:t,async:e,user:i,password:n,timeout:s,header:void 0,headerValue:void 0,requestedWith:!1,overrideMimeType:void 0}}},function(t,e,i){var n=i(0),s=i(229),r=i(65),o=new n({Extends:r,Mixins:[s.Acceleration,s.Angular,s.Bounce,s.Debug,s.Drag,s.Enable,s.Friction,s.Gravity,s.Immovable,s.Mass,s.Size,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t,e,i,n,s),this.body=null}});t.exports=o},function(t,e,i){var n={};t.exports=n;var s=i(37),r=i(19);n.fromVertices=function(t){for(var e={},i=0;i1?1:0;d1?1:0;p0:0!=(t.mask&e.category)&&0!=(e.mask&t.category)}},function(t,e,i){var n={};t.exports=n;var s=i(31),r=i(37);n.collides=function(t,e,i){var o,a,h,l,u=!1;if(i){var c=t.parent,d=e.parent,f=c.speed*c.speed+c.angularSpeed*c.angularSpeed+d.speed*d.speed+d.angularSpeed*d.angularSpeed;u=i&&i.collided&&f<.2,l=i}else l={collided:!1,bodyA:t,bodyB:e};if(i&&u){var p=l.axisBody,g=p===t?e:t,v=[p.axes[i.axisNumber]];if(h=n._overlapAxes(p.vertices,g.vertices,v),l.reused=!0,h.overlap<=0)return l.collided=!1,l}else{if((o=n._overlapAxes(t.vertices,e.vertices,t.axes)).overlap<=0)return l.collided=!1,l;if((a=n._overlapAxes(e.vertices,t.vertices,e.axes)).overlap<=0)return l.collided=!1,l;o.overlaps?s=a:a=0?o.index-1:u.length-1],l.x=s.x-c.x,l.y=s.y-c.y,h=-r.dot(i,l),a=s,s=u[(o.index+1)%u.length],l.x=s.x-c.x,l.y=s.y-c.y,(n=-r.dot(i,l))=this.firstgid&&t1?2-s:s,o=r*Math.cos(i),a=r*Math.sin(i);return e.x=t.x+o*t.radius,e.y=t.y+a*t.radius,e}},function(t,e,i){var n=i(20),s=i(0),r=i(9),o=i(119),a=i(289),h=i(290),l=i(5),u=new s({Extends:r,initialize:function(t,e,i){r.call(this),this.manager=t,this.key=e,this.type="frame",this.frames=this.getFrames(t.textureManager,l(i,"frames",[]),l(i,"defaultTextureKey",null)),this.frameRate=l(i,"frameRate",null),this.duration=l(i,"duration",null),null===this.duration&&null===this.frameRate?(this.frameRate=24,this.duration=this.frameRate/this.frames.length*1e3):this.duration&&null===this.frameRate?this.frameRate=this.frames.length/(this.duration/1e3):this.duration=this.frames.length/this.frameRate*1e3,this.msPerFrame=1e3/this.frameRate,this.skipMissedFrames=l(i,"skipMissedFrames",!0),this.delay=l(i,"delay",0),this.repeat=l(i,"repeat",0),this.repeatDelay=l(i,"repeatDelay",0),this.yoyo=l(i,"yoyo",!1),this.showOnStart=l(i,"showOnStart",!1),this.hideOnComplete=l(i,"hideOnComplete",!1),this.paused=!1,this.manager.on(o.PAUSE_ALL,this.pause,this),this.manager.on(o.RESUME_ALL,this.resume,this)},addFrame:function(t){return this.addFrameAt(this.frames.length,t)},addFrameAt:function(t,e){var i=this.getFrames(this.manager.textureManager,e);if(i.length>0){if(0===t)this.frames=i.concat(this.frames);else if(t===this.frames.length)this.frames=this.frames.concat(i);else{var n=this.frames.slice(0,t),s=this.frames.slice(t);this.frames=n.concat(i,s)}this.updateFrameSequence()}return this},checkFrame:function(t){return t>=0&&t0){s.isLast=!0,s.nextFrame=a[0],a[0].prevFrame=s;var v=1/(a.length-1);for(r=0;r=this.frames.length&&(e=0),t.currentAnim!==this&&(t.currentAnim=this,t.frameRate=this.frameRate,t.duration=this.duration,t.msPerFrame=this.msPerFrame,t.skipMissedFrames=this.skipMissedFrames,t._delay=this.delay,t._repeat=this.repeat,t._repeatDelay=this.repeatDelay,t._yoyo=this.yoyo);var i=this.frames[e];0!==e||t.forward||(i=this.getLastFrame()),t.updateFrame(i)},getFrameByProgress:function(t){return t=n(t,0,1),a(t,this.frames,"progress")},nextFrame:function(t){var e=t.currentFrame;e.isLast?t._yoyo?this.handleYoyoFrame(t,!1):t.repeatCounter>0?t._reverse&&t.forward?t.forward=!1:this.repeatAnimation(t):this.completeAnimation(t):this.updateAndGetNextTick(t,e.nextFrame)},handleYoyoFrame:function(t,e){if(e||(e=!1),t._reverse===!e&&t.repeatCounter>0)return t.forward=e,void this.repeatAnimation(t);if(t._reverse===e||0!==t.repeatCounter){t.forward=e;var i=e?t.currentFrame.nextFrame:t.currentFrame.prevFrame;this.updateAndGetNextTick(t,i)}else this.completeAnimation(t)},getLastFrame:function(){return this.frames[this.frames.length-1]},previousFrame:function(t){var e=t.currentFrame;e.isFirst?t._yoyo?this.handleYoyoFrame(t,!0):t.repeatCounter>0?t._reverse&&!t.forward?(t.currentFrame=this.getLastFrame(),this.repeatAnimation(t)):(t.forward=!0,this.repeatAnimation(t)):this.completeAnimation(t):this.updateAndGetNextTick(t,e.prevFrame)},updateAndGetNextTick:function(t,e){t.updateFrame(e),this.getNextTick(t)},removeFrame:function(t){var e=this.frames.indexOf(t);return-1!==e&&this.removeFrameAt(e),this},removeFrameAt:function(t){return this.frames.splice(t,1),this.updateFrameSequence(),this},repeatAnimation:function(t){if(2===t._pendingStop)return this.completeAnimation(t);if(t._repeatDelay>0&&!1===t.pendingRepeat)t.pendingRepeat=!0,t.accumulator-=t.nextTick,t.nextTick+=t._repeatDelay;else if(t.repeatCounter--,t.updateFrame(t.currentFrame[t.forward?"nextFrame":"prevFrame"]),t.isPlaying){this.getNextTick(t),t.pendingRepeat=!1;var e=t.currentFrame,i=t.parent;this.emit(o.ANIMATION_REPEAT,this,e),i.emit(o.SPRITE_ANIMATION_KEY_REPEAT+this.key,this,e,t.repeatCounter,i),i.emit(o.SPRITE_ANIMATION_REPEAT,this,e,t.repeatCounter,i)}},setFrame:function(t){t.forward?this.nextFrame(t):this.previousFrame(t)},toJSON:function(){var t={key:this.key,type:this.type,frames:[],frameRate:this.frameRate,duration:this.duration,skipMissedFrames:this.skipMissedFrames,delay:this.delay,repeat:this.repeat,repeatDelay:this.repeatDelay,yoyo:this.yoyo,showOnStart:this.showOnStart,hideOnComplete:this.hideOnComplete};return this.frames.forEach(function(e){t.frames.push(e.toJSON())}),t},updateFrameSequence:function(){for(var t,e=this.frames.length,i=1/(e-1),n=0;n1?(t.isLast=!0,t.prevFrame=this.frames[e-2],t.nextFrame=this.frames[0]):e>1&&(t.prevFrame=this.frames[n-1],t.nextFrame=this.frames[n+1]);return this},pause:function(){return this.paused=!0,this},resume:function(){return this.paused=!1,this},destroy:function(){this.removeAllListeners(),this.manager.off(o.PAUSE_ALL,this.pause,this),this.manager.off(o.RESUME_ALL,this.resume,this),this.manager.remove(this.key);for(var t=0;t=1)return i.x=t.x,i.y=t.y,i;var r=n(t)*e;return e>.5?(r-=t.width+t.height)<=t.width?(i.x=t.right-r,i.y=t.bottom):(i.x=t.x,i.y=t.bottom-(r-t.width)):r<=t.width?(i.x=t.x+r,i.y=t.y):(i.x=t.right,i.y=t.y+(r-t.width)),i}},function(t,e,i){var n=i(62),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=n(t)/i);for(var o=t.x1,a=t.y1,h=t.x2,l=t.y2,u=0;u=1&&(a=1-a,h=1-h),e.x=t.x1+(i*a+r*h),e.y=t.y1+(s*a+o*h),e}},function(t,e){t.exports=function(t,e,i,n,s){var r=n+Math.atan2(t.y-i,t.x-e);return t.x=e+s*Math.cos(r),t.y=i+s*Math.sin(r),t}},function(t,e){t.exports=function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)}},function(t,e){t.exports=function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){if(this.entries={},this.size=0,Array.isArray(t))for(var e=0;e=(t=t.toString()).length)switch(n){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((s=e-t.length)/2);t=new Array(s-r+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t}},function(t,e,i){var n=i(313),s=i(316),r=i(318),o=i(319);t.exports=function(t){switch(typeof t){case"string":return"rgb"===t.substr(0,3).toLowerCase()?o(t):n(t);case"number":return s(t);case"object":return r(t)}}},function(t,e){t.exports=function(t,e,i){return t<<16|e<<8|i}},function(t,e,i){var n=i(175);t.exports=function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1);var r=Math.floor(6*t),o=6*t-r,a=Math.floor(i*(1-e)*255),h=Math.floor(i*(1-o*e)*255),l=Math.floor(i*(1-(1-o)*e)*255),u=i=Math.floor(i*=255),c=i,d=i,f=r%6;return 0===f?(c=l,d=a):1===f?(u=h,d=a):2===f?(u=a,d=l):3===f?(u=a,c=h):4===f?(u=l,c=a):5===f&&(c=a,d=h),s?s.setTo?s.setTo(u,c,d,s.alpha,!1):(s.r=u,s.g=c,s.b=d,s.color=n(u,c,d),s):{r:u,g:c,b:d,color:n(u,c,d)}}},function(t,e){var i,n="";t.exports={disable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!1),t},enable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!0),t},getPrefix:i=function(t){for(var e=["i","webkitI","msI","mozI","oI"],i=0;i0&&(n=1/Math.sqrt(n),this.x=t*n,this.y=e*n,this.z=i*n),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},cross:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z;return this.x=i*o-n*r,this.y=n*s-e*o,this.z=e*r-i*s,this},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this},transformMat3:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=e*s[0]+i*s[3]+n*s[6],this.y=e*s[1]+i*s[4]+n*s[7],this.z=e*s[2]+i*s[5]+n*s[8],this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=s[0]*e+s[4]*i+s[8]*n+s[12],this.y=s[1]*e+s[5]*i+s[9]*n+s[13],this.z=s[2]*e+s[6]*i+s[10]*n+s[14],this},transformCoordinates:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=e*s[0]+i*s[4]+n*s[8]+s[12],o=e*s[1]+i*s[5]+n*s[9]+s[13],a=e*s[2]+i*s[6]+n*s[10]+s[14],h=e*s[3]+i*s[7]+n*s[11]+s[15];return this.x=r/h,this.y=o/h,this.z=a/h,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},project:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=s[0],o=s[1],a=s[2],h=s[3],l=s[4],u=s[5],c=s[6],d=s[7],f=s[8],p=s[9],g=s[10],v=s[11],y=s[12],m=s[13],x=s[14],T=1/(e*h+i*d+n*v+s[15]);return this.x=(e*r+i*l+n*f+y)*T,this.y=(e*o+i*u+n*p+m)*T,this.z=(e*a+i*c+n*g+x)*T,this},unproject:function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,o=this.x-i,a=r-this.y-1-n,h=this.z;return this.x=2*o/s-1,this.y=2*a/r-1,this.z=2*h-1,this.project(e)},reset:function(){return this.x=0,this.y=0,this.z=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0,0),n.LEFT=new n(-1,0,0),n.UP=new n(0,-1,0),n.DOWN=new n(0,1,0),n.FORWARD=new n(0,0,1),n.BACK=new n(0,0,-1),n.ONE=new n(1,1,1),t.exports=n},function(t,e,i){var n={Global:["game","anims","cache","plugins","registry","scale","sound","textures"],CoreScene:["EventEmitter","CameraManager","GameObjectCreator","GameObjectFactory","ScenePlugin","DisplayList","UpdateList"],DefaultScene:["Clock","DataManagerPlugin","InputPlugin","Loader","TweenManager","LightsPlugin"]};n.Global.push("facebook"),t.exports=n},function(t,e,i){var n=i(0),s=i(10),r=new n({initialize:function(t){this.name="WebGLPipeline",this.game=t.game,this.view=t.game.canvas,this.resolution=1,this.width=0,this.height=0,this.gl=t.gl,this.vertexCount=0,this.vertexCapacity=t.vertexCapacity,this.renderer=t.renderer,this.vertexData=t.vertices?t.vertices:new ArrayBuffer(t.vertexCapacity*t.vertexSize),this.vertexBuffer=this.renderer.createVertexBuffer(t.vertices?t.vertices:this.vertexData.byteLength,this.gl.STREAM_DRAW),this.program=this.renderer.createProgram(t.vertShader,t.fragShader),this.attributes=t.attributes,this.vertexSize=t.vertexSize,this.topology=t.topology,this.bytes=new Uint8Array(this.vertexData),this.vertexComponentCount=s.getComponentCount(t.attributes,this.gl),this.flushLocked=!1,this.active=!1},boot:function(){},addAttribute:function(t,e,i,n,r){return this.attributes.push({name:t,size:e,type:this.renderer.glFormats[i],normalized:n,offset:r}),this.vertexComponentCount=s.getComponentCount(this.attributes,this.gl),this},shouldFlush:function(){return this.vertexCount>=this.vertexCapacity},resize:function(t,e,i){return this.width=t*i,this.height=e*i,this.resolution=i,this},bind:function(){var t=this.gl,e=this.vertexBuffer,i=this.attributes,n=this.program,s=this.renderer,r=this.vertexSize;s.setProgram(n),s.setVertexBuffer(e);for(var o=0;o=0?(t.enableVertexAttribArray(h),t.vertexAttribPointer(h,a.size,a.type,a.normalized,r,a.offset)):-1!==h&&t.disableVertexAttribArray(h)}return this},onBind:function(){return this},onPreRender:function(){return this},onRender:function(){return this},onPostRender:function(){return this},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t=this.gl,e=this.vertexCount,i=this.topology,n=this.vertexSize;if(0!==e)return t.bufferSubData(t.ARRAY_BUFFER,0,this.bytes.subarray(0,e*n)),t.drawArrays(i,0,e),this.vertexCount=0,this.flushLocked=!1,this;this.flushLocked=!1},destroy:function(){var t=this.gl;return t.deleteProgram(this.program),t.deleteBuffer(this.vertexBuffer),delete this.program,delete this.vertexBuffer,delete this.gl,this},setFloat1:function(t,e){return this.renderer.setFloat1(this.program,t,e),this},setFloat2:function(t,e,i){return this.renderer.setFloat2(this.program,t,e,i),this},setFloat3:function(t,e,i,n){return this.renderer.setFloat3(this.program,t,e,i,n),this},setFloat4:function(t,e,i,n,s){return this.renderer.setFloat4(this.program,t,e,i,n,s),this},setFloat1v:function(t,e){return this.renderer.setFloat1v(this.program,t,e),this},setFloat2v:function(t,e){return this.renderer.setFloat2v(this.program,t,e),this},setFloat3v:function(t,e){return this.renderer.setFloat3v(this.program,t,e),this},setFloat4v:function(t,e){return this.renderer.setFloat4v(this.program,t,e),this},setInt1:function(t,e){return this.renderer.setInt1(this.program,t,e),this},setInt2:function(t,e,i){return this.renderer.setInt2(this.program,t,e,i),this},setInt3:function(t,e,i,n){return this.renderer.setInt3(this.program,t,e,i,n),this},setInt4:function(t,e,i,n,s){return this.renderer.setInt4(this.program,t,e,i,n,s),this},setMatrix2:function(t,e,i){return this.renderer.setMatrix2(this.program,t,e,i),this},setMatrix3:function(t,e,i){return this.renderer.setMatrix3(this.program,t,e,i),this},setMatrix4:function(t,e,i){return this.renderer.setMatrix4(this.program,t,e,i),this}});t.exports=r},function(t,e,i){var n=i(0),s=i(72),r=i(1),o=i(365),a=i(811),h=i(812),l=i(35),u=i(10),c=i(187),d=new n({Extends:c,Mixins:[o],initialize:function(t){var e=t.renderer.config;c.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:r(t,"topology",t.renderer.gl.TRIANGLES),vertShader:r(t,"vertShader",h),fragShader:r(t,"fragShader",a),vertexCapacity:r(t,"vertexCapacity",6*e.batchSize),vertexSize:r(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.tempTriangle=[{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0}],this.tintEffect=2,this.strokeTint={TL:0,TR:0,BL:0,BR:0},this.fillTint={TL:0,TR:0,BL:0,BR:0},this.currentFrame={u0:0,v0:0,u1:1,v1:1},this.firstQuad=[0,0,0,0,0],this.prevQuad=[0,0,0,0,0],this.polygonCache=[],this.mvpInit()},onBind:function(){return c.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return c.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this},batchSprite:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix1,s=this._tempMatrix2,r=this._tempMatrix3,o=t.frame,a=o.glTexture,h=o.u0,l=o.v0,c=o.u1,d=o.v1,f=o.x,p=o.y,g=o.cutWidth,v=o.cutHeight,y=o.customPivot,m=t.displayOriginX,x=t.displayOriginY,T=-m+f,w=-x+p;if(t.isCropped){var b=t._crop;b.flipX===t.flipX&&b.flipY===t.flipY||o.updateCropUVs(b,t.flipX,t.flipY),h=b.u0,l=b.v0,c=b.u1,d=b.v1,g=b.width,v=b.height,T=-m+(f=b.x),w=-x+(p=b.y)}var E=1,S=1;t.flipX&&(y||(T+=-o.realWidth+2*m),E=-1),(t.flipY||o.source.isGLTexture&&!a.flipY)&&(y||(w+=-o.realHeight+2*x),S=-1),s.applyITRS(t.x,t.y,t.rotation,t.scaleX*E,t.scaleY*S),n.copyFrom(e.matrix),i?(n.multiplyWithOffset(i,-e.scrollX*t.scrollFactorX,-e.scrollY*t.scrollFactorY),s.e=t.x,s.f=t.y,n.multiply(s,r)):(s.e-=e.scrollX*t.scrollFactorX,s.f-=e.scrollY*t.scrollFactorY,n.multiply(s,r));var A=T+g,_=w+v,C=r.getX(T,w),M=r.getY(T,w),P=r.getX(T,_),O=r.getY(T,_),R=r.getX(A,_),L=r.getY(A,_),D=r.getX(A,w),k=r.getY(A,w),F=u.getTintAppendFloatAlpha(t._tintTL,e.alpha*t._alphaTL),I=u.getTintAppendFloatAlpha(t._tintTR,e.alpha*t._alphaTR),B=u.getTintAppendFloatAlpha(t._tintBL,e.alpha*t._alphaBL),N=u.getTintAppendFloatAlpha(t._tintBR,e.alpha*t._alphaBR);e.roundPixels&&(C=Math.round(C),M=Math.round(M),P=Math.round(P),O=Math.round(O),R=Math.round(R),L=Math.round(L),D=Math.round(D),k=Math.round(k)),this.setTexture2D(a,0);var Y=t._isTinted&&t.tintFill;this.batchQuad(C,M,P,O,R,L,D,k,h,l,c,d,F,I,B,N,Y,a,0)},batchQuad:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,y,m){var x=!1;this.vertexCount+6>this.vertexCapacity&&(this.flush(),x=!0,this.setTexture2D(y,m));var T=this.vertexViewF32,w=this.vertexViewU32,b=this.vertexCount*this.vertexComponentCount-1;return T[++b]=t,T[++b]=e,T[++b]=h,T[++b]=l,T[++b]=v,w[++b]=d,T[++b]=i,T[++b]=n,T[++b]=h,T[++b]=c,T[++b]=v,w[++b]=p,T[++b]=s,T[++b]=r,T[++b]=u,T[++b]=c,T[++b]=v,w[++b]=g,T[++b]=t,T[++b]=e,T[++b]=h,T[++b]=l,T[++b]=v,w[++b]=d,T[++b]=s,T[++b]=r,T[++b]=u,T[++b]=c,T[++b]=v,w[++b]=g,T[++b]=o,T[++b]=a,T[++b]=u,T[++b]=l,T[++b]=v,w[++b]=f,this.vertexCount+=6,x},batchTri:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g){var v=!1;this.vertexCount+3>this.vertexCapacity&&(this.flush(),this.setTexture2D(p,g),v=!0);var y=this.vertexViewF32,m=this.vertexViewU32,x=this.vertexCount*this.vertexComponentCount-1;return y[++x]=t,y[++x]=e,y[++x]=o,y[++x]=a,y[++x]=f,m[++x]=u,y[++x]=i,y[++x]=n,y[++x]=o,y[++x]=l,y[++x]=f,m[++x]=c,y[++x]=s,y[++x]=r,y[++x]=h,y[++x]=l,y[++x]=f,m[++x]=d,this.vertexCount+=3,v},batchTexture:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,y,m,x,T,w,b,E,S,A,_,C,M,P,O){this.renderer.setPipeline(this,t);var R=this._tempMatrix1,L=this._tempMatrix2,D=this._tempMatrix3,k=y/i+_,F=m/n+C,I=(y+x)/i+_,B=(m+T)/n+C,N=o,Y=a,X=-g,z=-v;if(t.isCropped){var U=t._crop;N=U.width,Y=U.height,o=U.width,a=U.height;var G=y=U.x,W=m=U.y;c&&(G=x-U.x-U.width),d&&!e.isRenderTexture&&(W=T-U.y-U.height),k=G/i+_,F=W/n+C,I=(G+U.width)/i+_,B=(W+U.height)/n+C,X=-g+y,z=-v+m}d^=!O&&e.isRenderTexture?1:0,c&&(N*=-1,X+=o),d&&(Y*=-1,z+=a);var V=X+N,H=z+Y;L.applyITRS(s,r,u,h,l),R.copyFrom(M.matrix),P?(R.multiplyWithOffset(P,-M.scrollX*f,-M.scrollY*p),L.e=s,L.f=r,R.multiply(L,D)):(L.e-=M.scrollX*f,L.f-=M.scrollY*p,R.multiply(L,D));var j=D.getX(X,z),q=D.getY(X,z),K=D.getX(X,H),J=D.getY(X,H),Z=D.getX(V,H),Q=D.getY(V,H),$=D.getX(V,z),tt=D.getY(V,z);M.roundPixels&&(j=Math.round(j),q=Math.round(q),K=Math.round(K),J=Math.round(J),Z=Math.round(Z),Q=Math.round(Q),$=Math.round($),tt=Math.round(tt)),this.setTexture2D(e,0),this.batchQuad(j,q,K,J,Z,Q,$,tt,k,F,I,B,w,b,E,S,A,e,0)},batchTextureFrame:function(t,e,i,n,s,r,o){this.renderer.setPipeline(this);var a=this._tempMatrix1.copyFrom(r),h=this._tempMatrix2,l=e+t.width,c=i+t.height;o?a.multiply(o,h):h=a;var d=h.getX(e,i),f=h.getY(e,i),p=h.getX(e,c),g=h.getY(e,c),v=h.getX(l,c),y=h.getY(l,c),m=h.getX(l,i),x=h.getY(l,i);this.setTexture2D(t.glTexture,0),n=u.getTintAppendFloatAlpha(n,s),this.batchQuad(d,f,p,g,v,y,m,x,t.u0,t.v0,t.u1,t.v1,n,n,n,n,0,t.glTexture,0)},drawFillRect:function(t,e,i,n,s,r){var o=t+i,a=e+n;this.setTexture2D();var h=u.getTintAppendFloatAlphaAndSwap(s,r);this.batchQuad(t,e,t,a,o,a,o,e,0,0,1,1,h,h,h,h,2)},batchFillRect:function(t,e,i,n,s,r){this.renderer.setPipeline(this);var o=this._tempMatrix3;r&&r.multiply(s,o);var a=t+i,h=e+n,l=o.getX(t,e),u=o.getY(t,e),c=o.getX(t,h),d=o.getY(t,h),f=o.getX(a,h),p=o.getY(a,h),g=o.getX(a,e),v=o.getY(a,e),y=this.currentFrame,m=y.u0,x=y.v0,T=y.u1,w=y.v1;this.batchQuad(l,u,c,d,f,p,g,v,m,x,T,w,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.fillTint.BR,this.tintEffect)},batchFillTriangle:function(t,e,i,n,s,r,o,a){this.renderer.setPipeline(this);var h=this._tempMatrix3;a&&a.multiply(o,h);var l=h.getX(t,e),u=h.getY(t,e),c=h.getX(i,n),d=h.getY(i,n),f=h.getX(s,r),p=h.getY(s,r),g=this.currentFrame,v=g.u0,y=g.v0,m=g.u1,x=g.v1;this.batchTri(l,u,c,d,f,p,v,y,m,x,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.tintEffect)},batchStrokeTriangle:function(t,e,i,n,s,r,o,a,h){var l=this.tempTriangle;l[0].x=t,l[0].y=e,l[0].width=o,l[1].x=i,l[1].y=n,l[1].width=o,l[2].x=s,l[2].y=r,l[2].width=o,l[3].x=t,l[3].y=e,l[3].width=o,this.batchStrokePath(l,o,!1,a,h)},batchFillPath:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix3;i&&i.multiply(e,n);for(var r,o,a=t.length,h=this.polygonCache,l=this.fillTint.TL,u=this.fillTint.TR,c=this.fillTint.BL,d=this.tintEffect,f=0;f0&&H[4]?this.batchQuad(D,k,P,O,H[0],H[1],H[2],H[3],U,G,W,V,B,N,Y,X,I):(j[0]=D,j[1]=k,j[2]=P,j[3]=O,j[4]=1),h&&j[4]?this.batchQuad(C,M,R,L,j[0],j[1],j[2],j[3],U,G,W,V,B,N,Y,X,I):(H[0]=C,H[1]=M,H[2]=R,H[3]=L,H[4]=1)}}});t.exports=d},function(t,e,i){var n=i(11),s=i(13);t.exports=function(t,e){if(void 0===e&&(e=new n),0===t.length)return e;for(var i,r,o,a=Number.MAX_VALUE,h=Number.MAX_VALUE,l=s.MIN_SAFE_INTEGER,u=s.MIN_SAFE_INTEGER,c=0;c0},isTransitionIn:function(){return this.settings.isTransition},isVisible:function(){return this.settings.visible},setVisible:function(t){return this.settings.visible=t,this},setActive:function(t,e){return t?this.resume(e):this.pause(e)},start:function(t){t&&(this.settings.data=t),this.settings.status=s.START,this.settings.active=!0,this.settings.visible=!0,this.events.emit(o.START,this),this.events.emit(o.READY,this,t)},shutdown:function(t){this.events.off(o.TRANSITION_INIT),this.events.off(o.TRANSITION_START),this.events.off(o.TRANSITION_COMPLETE),this.events.off(o.TRANSITION_OUT),this.settings.status=s.SHUTDOWN,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.SHUTDOWN,this,t)},destroy:function(){this.settings.status=s.DESTROYED,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.DESTROY,this),this.events.removeAllListeners();for(var t=["scene","game","anims","cache","plugins","registry","sound","textures","add","camera","displayList","events","make","scenePlugin","updateList"],e=0;e0},getRenderList:function(){return this.dirty&&(this.renderList=this.children.list.filter(this.childCanRender,this),this.dirty=!1),this.renderList},clear:function(){this.children.removeAll(),this.dirty=!0},preDestroy:function(){this.children.destroy(),this.renderList=[]}});t.exports=u},function(t,e,i){var n=i(196),s=i(43),r=i(0),o=i(12),a=i(102),h=i(14),l=i(11),u=i(984),c=i(417),d=i(3),f=new r({Extends:h,Mixins:[o.AlphaSingle,o.BlendMode,o.ComputedSize,o.Depth,o.Mask,o.Transform,o.Visible,u],initialize:function(t,e,i,n){h.call(this,t,"Container"),this.list=[],this.exclusive=!0,this.maxSize=-1,this.position=0,this.localTransform=new o.TransformMatrix,this.tempTransformMatrix=new o.TransformMatrix,this._displayList=t.sys.displayList,this._sortKey="",this._sysEvents=t.sys.events,this.scrollFactorX=1,this.scrollFactorY=1,this.setPosition(e,i),this.clearAlpha(),this.setBlendMode(s.SKIP_CHECK),n&&this.add(n)},originX:{get:function(){return.5}},originY:{get:function(){return.5}},displayOriginX:{get:function(){return.5*this.width}},displayOriginY:{get:function(){return.5*this.height}},setExclusive:function(t){return void 0===t&&(t=!0),this.exclusive=t,this},getBounds:function(t){if(void 0===t&&(t=new l),t.setTo(this.x,this.y,0,0),this.list.length>0)for(var e=this.list,i=new l,n=0;n-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){var i,n=[null],s=this.list.slice(),r=s.length;for(i=2;i0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}},preDestroy:function(){this.removeAll(!!this.exclusive),this.localTransform.destroy(),this.tempTransformMatrix.destroy(),this.list=[],this._displayList=null}});t.exports=f},function(t,e,i){var n=i(138),s=i(0),r=i(989),o=new s({Extends:n,Mixins:[r],initialize:function(t,e,i,s,r,o,a){n.call(this,t,e,i,s,r,o,a),this.type="DynamicBitmapText",this.scrollX=0,this.scrollY=0,this.cropWidth=0,this.cropHeight=0,this.displayCallback,this.callbackData={parent:this,color:0,tint:{topLeft:0,topRight:0,bottomLeft:0,bottomRight:0},index:0,charCode:0,x:0,y:0,scale:0,rotation:0,data:0}},setSize:function(t,e){return this.cropWidth=t,this.cropHeight=e,this},setDisplayCallback:function(t){return this.displayCallback=t,this},setScrollX:function(t){return this.scrollX=t,this},setScrollY:function(t){return this.scrollY=t,this}});t.exports=o},function(t,e,i){var n=i(103),s=i(0),r=i(205),o=i(287),a=i(291),h=i(292),l=i(296),u=i(121),c=i(301),d=i(302),f=i(299),p=i(35),g=i(107),v=i(14),y=i(1),m=i(5),x=i(13),T=i(995),w=new s({Extends:v,Mixins:[o,a,h,l,u,c,d,f,T],initialize:function(t,e){var i=m(e,"x",0),n=m(e,"y",0);v.call(this,t,"Graphics"),this.setPosition(i,n),this.initPipeline(),this.displayOriginX=0,this.displayOriginY=0,this.commandBuffer=[],this.defaultFillColor=-1,this.defaultFillAlpha=1,this.defaultStrokeWidth=1,this.defaultStrokeColor=-1,this.defaultStrokeAlpha=1,this._lineWidth=1,this._tempMatrix1=new p,this._tempMatrix2=new p,this._tempMatrix3=new p,this.setDefaultStyles(e)},setDefaultStyles:function(t){return m(t,"lineStyle",null)&&(this.defaultStrokeWidth=m(t,"lineStyle.width",1),this.defaultStrokeColor=m(t,"lineStyle.color",16777215),this.defaultStrokeAlpha=m(t,"lineStyle.alpha",1),this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha)),m(t,"fillStyle",null)&&(this.defaultFillColor=m(t,"fillStyle.color",16777215),this.defaultFillAlpha=m(t,"fillStyle.alpha",1),this.fillStyle(this.defaultFillColor,this.defaultFillAlpha)),this},lineStyle:function(t,e,i){return void 0===i&&(i=1),this.commandBuffer.push(r.LINE_STYLE,t,e,i),this._lineWidth=t,this},fillStyle:function(t,e){return void 0===e&&(e=1),this.commandBuffer.push(r.FILL_STYLE,t,e),this},fillGradientStyle:function(t,e,i,n,s){return void 0===s&&(s=1),this.commandBuffer.push(r.GRADIENT_FILL_STYLE,s,t,e,i,n),this},lineGradientStyle:function(t,e,i,n,s,o){return void 0===o&&(o=1),this.commandBuffer.push(r.GRADIENT_LINE_STYLE,t,o,e,i,n,s),this},setTexture:function(t,e,i){if(void 0===i&&(i=0),void 0===t)this.commandBuffer.push(r.CLEAR_TEXTURE);else{var n=this.scene.sys.textures.getFrame(t,e);n&&(2===i&&(i=3),this.commandBuffer.push(r.SET_TEXTURE,n,i))}return this},beginPath:function(){return this.commandBuffer.push(r.BEGIN_PATH),this},closePath:function(){return this.commandBuffer.push(r.CLOSE_PATH),this},fillPath:function(){return this.commandBuffer.push(r.FILL_PATH),this},fill:function(){return this.commandBuffer.push(r.FILL_PATH),this},strokePath:function(){return this.commandBuffer.push(r.STROKE_PATH),this},stroke:function(){return this.commandBuffer.push(r.STROKE_PATH),this},fillCircleShape:function(t){return this.fillCircle(t.x,t.y,t.radius)},strokeCircleShape:function(t){return this.strokeCircle(t.x,t.y,t.radius)},fillCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.fillPath(),this},strokeCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.strokePath(),this},fillRectShape:function(t){return this.fillRect(t.x,t.y,t.width,t.height)},strokeRectShape:function(t){return this.strokeRect(t.x,t.y,t.width,t.height)},fillRect:function(t,e,i,n){return this.commandBuffer.push(r.FILL_RECT,t,e,i,n),this},strokeRect:function(t,e,i,n){var s=this._lineWidth/2,r=t-s,o=t+s;return this.beginPath(),this.moveTo(t,e),this.lineTo(t,e+n),this.strokePath(),this.beginPath(),this.moveTo(t+i,e),this.lineTo(t+i,e+n),this.strokePath(),this.beginPath(),this.moveTo(r,e),this.lineTo(o+i,e),this.strokePath(),this.beginPath(),this.moveTo(r,e+n),this.lineTo(o+i,e+n),this.strokePath(),this},fillRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=y(s,"tl",20),o=y(s,"tr",20),a=y(s,"bl",20),h=y(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.fillPath(),this},strokeRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=y(s,"tl",20),o=y(s,"tr",20),a=y(s,"bl",20),h=y(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.strokePath(),this},fillPointShape:function(t,e){return this.fillPoint(t.x,t.y,e)},fillPoint:function(t,e,i){return!i||i<1?i=1:(t-=i/2,e-=i/2),this.commandBuffer.push(r.FILL_RECT,t,e,i,i),this},fillTriangleShape:function(t){return this.fillTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},strokeTriangleShape:function(t){return this.strokeTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},fillTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.FILL_TRIANGLE,t,e,i,n,s,o),this},strokeTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.STROKE_TRIANGLE,t,e,i,n,s,o),this},strokeLineShape:function(t){return this.lineBetween(t.x1,t.y1,t.x2,t.y2)},lineBetween:function(t,e,i,n){return this.beginPath(),this.moveTo(t,e),this.lineTo(i,n),this.strokePath(),this},lineTo:function(t,e){return this.commandBuffer.push(r.LINE_TO,t,e),this},moveTo:function(t,e){return this.commandBuffer.push(r.MOVE_TO,t,e),this},strokePoints:function(t,e,i,n){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===n&&(n=t.length),this.beginPath(),this.moveTo(t[0].x,t[0].y);for(var s=1;s-1&&this.fillStyle(this.defaultFillColor,this.defaultFillAlpha),this.defaultStrokeColor>-1&&this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha),this},generateTexture:function(t,e,i){var n,s,r=this.scene.sys,o=r.game.renderer;if(void 0===e&&(e=r.scale.width),void 0===i&&(i=r.scale.height),w.TargetCamera.setScene(this.scene),w.TargetCamera.setViewport(0,0,e,i),w.TargetCamera.scrollX=this.x,w.TargetCamera.scrollY=this.y,"string"==typeof t)if(r.textures.exists(t)){var a=(n=r.textures.get(t)).getSourceImage();a instanceof HTMLCanvasElement&&(s=a.getContext("2d"))}else s=(n=r.textures.createCanvas(t,e,i)).getSourceImage().getContext("2d");else t instanceof HTMLCanvasElement&&(s=t.getContext("2d"));return s&&(this.renderCanvas(o,this,0,w.TargetCamera,null,s,!1),n&&n.refresh()),this},preDestroy:function(){this.commandBuffer=[]}});w.TargetCamera=new n,t.exports=w},function(t,e){t.exports={ARC:0,BEGIN_PATH:1,CLOSE_PATH:2,FILL_RECT:3,LINE_TO:4,MOVE_TO:5,LINE_STYLE:6,FILL_STYLE:7,FILL_PATH:8,STROKE_PATH:9,FILL_TRIANGLE:10,STROKE_TRIANGLE:11,SAVE:14,RESTORE:15,TRANSLATE:16,SCALE:17,ROTATE:18,SET_TEXTURE:19,CLEAR_TEXTURE:20,GRADIENT_FILL_STYLE:21,GRADIENT_LINE_STYLE:22}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.width/2,r=t.height/2;return i.x=t.x+s*Math.cos(e),i.y=t.y+r*Math.sin(e),i}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(425),a=i(135),h=i(427),l=i(1005),u=new n({Extends:r,Mixins:[s.Depth,s.Mask,s.Pipeline,s.Transform,s.Visible,l],initialize:function(t,e,i,n){if(r.call(this,t,"ParticleEmitterManager"),this.blendMode=-1,this.timeScale=1,this.texture=null,this.frame=null,this.frameNames=[],null===i||"object"!=typeof i&&!Array.isArray(i)||(n=i,i=null),this.setTexture(e,i),this.initPipeline(),this.emitters=new a(this),this.wells=new a(this),n){Array.isArray(n)||(n=[n]);for(var s=0;s0?e.defaultFrame=i[0]:e.defaultFrame=this.defaultFrame,this},addEmitter:function(t){return this.emitters.add(t)},createEmitter:function(t){return this.addEmitter(new h(this,t))},removeEmitter:function(t){return this.emitters.remove(t,!0)},addGravityWell:function(t){return this.wells.add(t)},createGravityWell:function(t){return this.addGravityWell(new o(t))},emitParticle:function(t,e,i){for(var n=this.emitters.list,s=0;ss.width&&(t=s.width-this.frame.cutX),this.frame.cutY+e>s.height&&(e=s.height-this.frame.cutY),this.frame.setSize(t,e,this.frame.cutX,this.frame.cutY)}this.updateDisplayOrigin();var r=this.input;return r&&!r.customHitArea&&(r.hitArea.width=t,r.hitArea.height=e),this},setGlobalTint:function(t){return this.globalTint=t,this},setGlobalAlpha:function(t){return this.globalAlpha=t,this},saveTexture:function(t){return this.textureManager.renameTexture(this.texture.key,t),this._saved=!0,this.texture},fill:function(t,e,i,n,s,r){void 0===e&&(e=1),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.frame.cutWidth),void 0===r&&(r=this.frame.cutHeight);var o=255&(t>>16|0),a=255&(t>>8|0),h=255&(0|t),l=this.gl,u=this.frame;if(this.camera.preRender(1,1),l){var c=this.camera._cx,f=this.camera._cy,p=this.camera._cw,g=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(c,f,p,g,g);var v=this.pipeline;v.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),v.drawFillRect(i,n,s,r,d.getTintFromFloats(o/255,a/255,h/255,1),e),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),v.projOrtho(0,v.width,v.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.context.fillStyle="rgba("+o+","+a+","+h+","+e+")",this.context.fillRect(i+u.cutX,n+u.cutY,s,r),this.renderer.setContext();return this.dirty=!0,this},clear:function(){if(this.dirty){var t=this.gl;if(t){var e=this.renderer;e.setFramebuffer(this.framebuffer,!0),this.frame.cutWidth===this.canvas.width&&this.frame.cutHeight===this.canvas.height||t.scissor(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),e.setFramebuffer(null,!0)}else{var i=this.context;i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),i.restore()}this.dirty=!1}return this},erase:function(t,e,i){this._eraseMode=!0;var s=this.renderer.currentBlendMode;return this.renderer.setBlendMode(n.ERASE),this.draw(t,e,i,1,16777215),this.renderer.setBlendMode(s),this._eraseMode=!1,this},draw:function(t,e,i,n,s){void 0===n&&(n=this.globalAlpha),s=void 0===s?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(s>>16)+(65280&s)+((255&s)<<16),Array.isArray(t)||(t=[t]);var r=this.gl;if(this.camera.preRender(1,1),r){var o=this.camera._cx,a=this.camera._cy,h=this.camera._cw,l=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(o,a,h,l,l);var u=this.pipeline;u.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),this.batchList(t,e,i,n,s),u.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),u.projOrtho(0,u.width,u.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.batchList(t,e,i,n,s),this.renderer.setContext();return this.dirty=!0,this},drawFrame:function(t,e,i,n,s,r){void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.globalAlpha),r=void 0===r?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(r>>16)+(65280&r)+((255&r)<<16);var o=this.gl,a=this.textureManager.getFrame(t,e);if(a){if(this.camera.preRender(1,1),o){var h=this.camera._cx,l=this.camera._cy,u=this.camera._cw,c=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(h,l,u,c,c);var d=this.pipeline;d.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),d.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,r,s,this.camera.matrix,null),d.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),d.projOrtho(0,d.width,d.height,0,-1e3,1e3)}else this.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,s,r);this.dirty=!0}return this},batchList:function(t,e,i,n,s){for(var r=0;rl){if(0===c){for(var g=f;g.length&&(g=g.slice(0,-1),!((p=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var v=d.substr(g.length);u[c]=v,h+=g}var y=u[c].length?c:c+1,m=u.slice(y).join(" ").replace(/[ \n]*$/gi,"");s[o+1]=m+" "+(s[o+1]||""),r=s.length;break}h+=f,l-=p}n+=h.replace(/[ \n]*$/gi,"")+"\n"}}return n=n.replace(/[\s|\n]*$/gi,"")},basicWordWrap:function(t,e,i){for(var n="",s=t.split(this.splitRegExp),r=s.length-1,o=e.measureText(" ").width,a=0;a<=r;a++){for(var h=i,l=s[a].split(" "),u=l.length-1,c=0;c<=u;c++){var d=l[c],f=e.measureText(d).width,p=f+o;p>h&&c>0&&(n+="\n",h=i),n+=d,c0&&(d+=h.lineSpacing*g),i.rtl)c=f-c;else if("right"===i.align)c+=o-h.lineWidths[g];else if("center"===i.align)c+=(o-h.lineWidths[g])/2;else if("justify"===i.align){if(h.lineWidths[g]/h.width>=.85){var v=h.width-h.lineWidths[g],y=e.measureText(" ").width,m=a[g].trim(),x=m.split(" ");v+=(a[g].length-m.length)*y;for(var T=Math.floor(v/y),w=0;T>0;)x[w]+=" ",w=(w+1)%(x.length-1||1),--T;a[g]=x.join(" ")}}this.autoRound&&(c=Math.round(c),d=Math.round(d)),i.strokeThickness&&(this.style.syncShadow(e,i.shadowStroke),e.strokeText(a[g],c,d)),i.color&&(this.style.syncShadow(e,i.shadowFill),e.fillText(a[g],c,d))}e.restore(),this.renderer.gl&&(this.frame.source.glTexture=this.renderer.canvasToTexture(t,this.frame.source.glTexture,!0),this.frame.glTexture=this.frame.source.glTexture),this.dirty=!0;var b=this.input;return b&&!b.customHitArea&&(b.hitArea.width=this.width,b.hitArea.height=this.height),this},getTextMetrics:function(){return this.style.getTextMetrics()},text:{get:function(){return this._text},set:function(t){this.setText(t)}},toJSON:function(){var t=o.ToJSON(this),e={autoRound:this.autoRound,text:this._text,style:this.style.toJSON(),padding:{left:this.padding.left,right:this.padding.right,top:this.padding.top,bottom:this.padding.bottom}};return t.data=e,t},preDestroy:function(){this.style.rtl&&c(this.canvas),s.remove(this.canvas),this.texture.destroy()}});t.exports=p},function(t,e,i){var n=i(28),s=i(0),r=i(12),o=i(21),a=i(14),h=i(346),l=i(177),u=i(1021),c=i(3),d=new s({Extends:a,Mixins:[r.Alpha,r.BlendMode,r.ComputedSize,r.Crop,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Tint,r.Transform,r.Visible,u],initialize:function(t,e,i,s,r,l,u){var d=t.sys.game.renderer;a.call(this,t,"TileSprite");var f=t.sys.textures.get(l),p=f.get(u);s&&r?(s=Math.floor(s),r=Math.floor(r)):(s=p.width,r=p.height),this._tilePosition=new c,this._tileScale=new c(1,1),this.dirty=!1,this.renderer=d,this.canvas=n.create(this,s,r),this.context=this.canvas.getContext("2d"),this.displayTexture=f,this.displayFrame=p,this._crop=this.resetCropObject(),this.texture=t.sys.textures.addCanvas(null,this.canvas,!0),this.frame=this.texture.get(),this.potWidth=h(p.width),this.potHeight=h(p.height),this.fillCanvas=n.create2D(this,this.potWidth,this.potHeight),this.fillContext=this.fillCanvas.getContext("2d"),this.fillPattern=null,this.setPosition(e,i),this.setSize(s,r),this.setFrame(u),this.setOriginFromFrame(),this.initPipeline(),t.sys.game.events.on(o.CONTEXT_RESTORED,function(t){var e=t.gl;this.dirty=!0,this.fillPattern=null,this.fillPattern=t.createTexture2D(0,e.LINEAR,e.LINEAR,e.REPEAT,e.REPEAT,e.RGBA,this.fillCanvas,this.potWidth,this.potHeight)},this)},setTexture:function(t,e){return this.displayTexture=this.scene.sys.textures.get(t),this.setFrame(e)},setFrame:function(t){var e=this.displayTexture.get(t);return this.potWidth=h(e.width),this.potHeight=h(e.height),this.canvas.width=0,e.cutWidth&&e.cutHeight?this.renderFlags|=8:this.renderFlags&=-9,this.displayFrame=e,this.dirty=!0,this.updateTileTexture(),this},setTilePosition:function(t,e){return void 0!==t&&(this.tilePositionX=t),void 0!==e&&(this.tilePositionY=e),this},setTileScale:function(t,e){return void 0===t&&(t=this.tileScaleX),void 0===e&&(e=t),this.tileScaleX=t,this.tileScaleY=e,this},updateTileTexture:function(){if(this.dirty&&this.renderer){var t=this.displayFrame;if(t.source.isRenderTexture||t.source.isGLTexture)return console.warn("TileSprites can only use Image or Canvas based textures"),void(this.dirty=!1);var e=this.fillContext,i=this.fillCanvas,n=this.potWidth,s=this.potHeight;this.renderer.gl||(n=t.cutWidth,s=t.cutHeight),e.clearRect(0,0,n,s),i.width=n,i.height=s,e.drawImage(t.source.image,t.cutX,t.cutY,t.cutWidth,t.cutHeight,0,0,n,s),this.renderer.gl?this.fillPattern=this.renderer.canvasToTexture(i,this.fillPattern):this.fillPattern=e.createPattern(i,"repeat"),this.updateCanvas(),this.dirty=!1}},updateCanvas:function(){var t=this.canvas;if(t.width===this.width&&t.height===this.height||(t.width=this.width,t.height=this.height,this.frame.setSize(this.width,this.height),this.updateDisplayOrigin(),this.dirty=!0),!this.dirty||this.renderer&&this.renderer.gl)this.dirty=!1;else{var e=this.context;this.scene.sys.game.config.antialias||l.disable(e);var i=this._tileScale.x,n=this._tileScale.y,s=this._tilePosition.x,r=this._tilePosition.y;e.clearRect(0,0,this.width,this.height),e.save(),e.scale(i,n),e.translate(-s,-r),e.fillStyle=this.fillPattern,e.fillRect(s,r,this.width/i,this.height/n),e.restore(),this.dirty=!1}},preDestroy:function(){this.renderer&&this.renderer.gl&&this.renderer.deleteTexture(this.fillPattern),n.remove(this.canvas),n.remove(this.fillCanvas),this.fillPattern=null,this.fillContext=null,this.fillCanvas=null,this.displayTexture=null,this.displayFrame=null,this.texture.destroy(),this.renderer=null},tilePositionX:{get:function(){return this._tilePosition.x},set:function(t){this._tilePosition.x=t,this.dirty=!0}},tilePositionY:{get:function(){return this._tilePosition.y},set:function(t){this._tilePosition.y=t,this.dirty=!0}},tileScaleX:{get:function(){return this._tileScale.x},set:function(t){this._tileScale.x=t,this.dirty=!0}},tileScaleY:{get:function(){return this._tileScale.y},set:function(t){this._tileScale.y=t,this.dirty=!0}}});t.exports=d},function(t,e,i){var n=i(0),s=i(20),r=i(12),o=i(102),a=i(21),h=i(14),l=i(64),u=i(209),c=i(1024),d=i(13),f=new n({Extends:h,Mixins:[r.Alpha,r.BlendMode,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Size,r.TextureCrop,r.Tint,r.Transform,r.Visible,c],initialize:function(t,e,i,n){h.call(this,t,"Video"),this.video=null,this.videoTexture=null,this.videoTextureSource=null,this.snapshotTexture=null,this.flipY=!1,this._key=u(),this.touchLocked=!0,this.playWhenUnlocked=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._systemMuted=!1,this._codeMuted=!1,this._systemPaused=!1,this._codePaused=!1,this._callbacks={play:this.playHandler.bind(this),error:this.loadErrorHandler.bind(this),end:this.completeHandler.bind(this),time:this.timeUpdateHandler.bind(this),seeking:this.seekingHandler.bind(this),seeked:this.seekedHandler.bind(this)},this._crop=this.resetCropObject(),this.markers={},this._markerIn=-1,this._markerOut=d.MAX_SAFE_INTEGER,this._lastUpdate=0,this._cacheKey="",this._isSeeking=!1,this.removeVideoElementOnDestroy=!1,this.setPosition(e,i),this.initPipeline(),n&&this.changeSource(n,!1);var s=t.sys.game.events;s.on(a.PAUSE,this.globalPause,this),s.on(a.RESUME,this.globalResume,this);var r=t.sys.sound;r&&r.on(l.GLOBAL_MUTE,this.globalMute,this)},play:function(t,e,i){if(this.touchLocked&&this.playWhenUnlocked||this.isPlaying())return this;var n=this.video;if(!n)return console.warn("Video not loaded"),this;void 0===t&&(t=n.loop);var s=this.scene.sys.sound;s&&s.mute&&this.setMute(!0),isNaN(e)||(this._markerIn=e),!isNaN(i)&&i>e&&(this._markerOut=i),n.loop=t;var r=this._callbacks,o=n.play();return void 0!==o?o.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)):(n.addEventListener("playing",r.play,!0),n.readyState<2&&(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval))),n.addEventListener("ended",r.end,!0),n.addEventListener("timeupdate",r.time,!0),n.addEventListener("seeking",r.seeking,!0),n.addEventListener("seeked",r.seeked,!0),this},changeSource:function(t,e,i,n,s){void 0===e&&(e=!0),this.video&&this.stop();var r=this.scene.sys.cache.video.get(t);return r?(this.video=r,this._cacheKey=t,this._codePaused=r.paused,this._codeMuted=r.muted,this.videoTexture?(this.scene.sys.textures.remove(this._key),this.videoTexture=this.scene.sys.textures.create(this._key,r,r.videoWidth,r.videoHeight),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,r.videoWidth,r.videoHeight),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,r.videoWidth,r.videoHeight)):this.updateTexture(),r.currentTime=0,this._lastUpdate=0,e&&this.play(i,n,s)):this.video=null,this},addMarker:function(t,e,i){return!isNaN(e)&&e>=0&&!isNaN(i)&&(this.markers[t]=[e,i]),this},playMarker:function(t,e){var i=this.markers[t];return i&&this.play(e,i[0],i[1]),this},removeMarker:function(t){return delete this.markers[t],this},snapshot:function(t,e){return void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.snapshotArea(0,0,this.width,this.height,t,e)},snapshotArea:function(t,e,i,n,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=this.height),void 0===s&&(s=i),void 0===r&&(r=n);var o=this.video,a=this.snapshotTexture;return a?(a.setSize(s,r),o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)):(a=this.scene.sys.textures.createCanvas(u(),s,r),this.snapshotTexture=a,o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)),a.update()},saveSnapshotTexture:function(t){return this.snapshotTexture?this.scene.sys.textures.renameTexture(this.snapshotTexture.key,t):this.snapshotTexture=this.scene.sys.textures.createCanvas(t,this.width,this.height),this.snapshotTexture},loadURL:function(t,e,i){void 0===e&&(e="loadeddata"),void 0===i&&(i=!1),this.video&&this.stop(),this.videoTexture&&this.scene.sys.textures.remove(this._key);var n=document.createElement("video");return n.controls=!1,i&&(n.muted=!0,n.defaultMuted=!0,n.setAttribute("autoplay","autoplay")),n.setAttribute("playsinline","playsinline"),n.setAttribute("preload","auto"),n.addEventListener("error",this._callbacks.error,!0),n.src=t,n.load(),this.video=n,this},playPromiseSuccessHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn)},playPromiseErrorHandler:function(t){this.scene.sys.input.once("pointerdown",this.unlockHandler,this),this.touchLocked=!0,this.playWhenUnlocked=!0,this.emit(o.VIDEO_ERROR,this,t)},playHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this.video.removeEventListener("playing",this._callbacks.play,!0)},loadErrorHandler:function(t){this.stop(),this.emit(o.VIDEO_ERROR,this,t)},unlockHandler:function(){this.touchLocked=!1,this.playWhenUnlocked=!1,this.emit(o.VIDEO_UNLOCKED,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn),this.video.play(),this.emit(o.VIDEO_PLAY,this)},completeHandler:function(){this.emit(o.VIDEO_COMPLETE,this)},timeUpdateHandler:function(){this.video&&this.video.currentTime=this._markerOut&&(t.loop?(t.currentTime=this._markerIn,this.updateTexture(),this._lastUpdate=e,this.emit(o.VIDEO_LOOP,this)):(this.emit(o.VIDEO_COMPLETE,this),this.stop())))}},checkVideoProgress:function(){this.video.readyState>=2?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):this.emit(o.VIDEO_TIMEOUT,this))},updateTexture:function(){var t=this.video,e=t.videoWidth,i=t.videoHeight;if(this.videoTexture){var n=this.videoTextureSource;n.source!==t&&(n.source=t,n.width=e,n.height=i),n.update()}else this.videoTexture=this.scene.sys.textures.create(this._key,t,e,i),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,e,i),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,e,i)},getVideoKey:function(){return this._cacheKey},seekTo:function(t){var e=this.video;if(e){var i=e.duration;if(i!==1/0&&!isNaN(i)){var n=i*t;this.setCurrentTime(n)}}return this},getCurrentTime:function(){return this.video?this.video.currentTime:0},setCurrentTime:function(t){var e=this.video;if(e){if("string"==typeof t){var i=t[0],n=parseFloat(t.substr(1));"+"===i?t=e.currentTime+n:"-"===i&&(t=e.currentTime-n)}e.currentTime=t,this._lastUpdate=t}return this},isSeeking:function(){return this._isSeeking},seekingHandler:function(){this._isSeeking=!0,this.emit(o.VIDEO_SEEKING,this)},seekedHandler:function(){this._isSeeking=!1,this.emit(o.VIDEO_SEEKED,this),this.video&&this.updateTexture()},getProgress:function(){var t=this.video;if(t){var e=t.currentTime,i=t.duration;if(i!==1/0&&!isNaN(i))return e/i}return 0},getDuration:function(){return this.video?this.video.duration:0},setMute:function(t){void 0===t&&(t=!0),this._codeMuted=t;var e=this.video;return e&&(e.muted=!!this._systemMuted||t),this},isMuted:function(){return this._codeMuted},globalMute:function(t,e){this._systemMuted=e;var i=this.video;i&&(i.muted=!!this._codeMuted||e)},globalPause:function(){this._systemPaused=!0,this.video&&this.video.pause()},globalResume:function(){this._systemPaused=!1,this.video&&!this._codePaused&&this.video.play()},setPaused:function(t){void 0===t&&(t=!0);var e=this.video;return this._codePaused=t,e&&(t?e.paused||e.pause():t||e.paused&&!this._systemPaused&&e.play()),this},getVolume:function(){return this.video?this.video.volume:1},setVolume:function(t){return void 0===t&&(t=1),this.video&&(this.video.volume=s(t,0,1)),this},getPlaybackRate:function(){return this.video?this.video.playbackRate:1},setPlaybackRate:function(t){return this.video&&(this.video.playbackRate=t),this},getLoop:function(){return!!this.video&&this.video.loop},setLoop:function(t){return void 0===t&&(t=!0),this.video&&(this.video.loop=t),this},isPlaying:function(){return!!this.video&&!(this.video.paused||this.video.ended)},isPaused:function(){return this.video&&this.video.paused||this._codePaused||this._systemPaused},saveTexture:function(t,e){return void 0===e&&(e=!1),this.videoTexture&&this.scene.sys.textures.renameTexture(this._key,t),this._key=t,this.flipY=e,this.videoTextureSource&&this.videoTextureSource.setFlipY(e),this.videoTexture},stop:function(){var t=this.video;if(t){var e=this._callbacks;for(var i in e)t.removeEventListener(i,e[i],!0);t.pause()}return this._retryID&&window.clearTimeout(this._retryID),this.emit(o.VIDEO_STOP,this),this},removeVideoElement:function(){var t=this.video;if(t){for(t.parentNode&&t.parentNode.removeChild(t);t.hasChildNodes();)t.removeChild(t.firstChild);t.removeAttribute("autoplay"),t.removeAttribute("src"),this.video=null}},preDestroy:function(){this.stop(),this.removeVideoElementOnDestroy&&this.removeVideoElement();var t=this.scene.sys.game.events;t.off(a.PAUSE,this.globalPause,this),t.off(a.RESUME,this.globalResume,this);var e=this.scene.sys.sound;e&&e.off(l.GLOBAL_MUTE,this.globalMute,this),this._retryID&&window.clearTimeout(this._retryID)}});t.exports=f},function(t,e,i){var n=i(0),s=i(214),r=i(442),o=i(52),a=new n({initialize:function(t){this.type=o.POLYGON,this.area=0,this.points=[],t&&this.setTo(t)},contains:function(t,e){return s(this,t,e)},setTo:function(t){if(this.area=0,this.points=[],"string"==typeof t&&(t=t.split(" ")),!Array.isArray(t))return this;for(var e,i=Number.MAX_VALUE,n=0;no||r>a)return!1;if(s<=i||r<=n)return!0;var h=s-i,l=r-n;return h*h+l*l<=t.radius*t.radius}},function(t,e,i){var n=i(4),s=i(220);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a=t.x1,h=t.y1,l=t.x2,u=t.y2,c=e.x,d=e.y,f=e.radius,p=l-a,g=u-h,v=a-c,y=h-d,m=p*p+g*g,x=2*(p*v+g*y),T=x*x-4*m*(v*v+y*y-f*f);if(0===T){var w=-x/(2*m);r=a+w*p,o=h+w*g,w>=0&&w<=1&&i.push(new n(r,o))}else if(T>0){var b=(-x-Math.sqrt(T))/(2*m);r=a+b*p,o=h+b*g,b>=0&&b<=1&&i.push(new n(r,o));var E=(-x+Math.sqrt(T))/(2*m);r=a+E*p,o=h+E*g,E>=0&&E<=1&&i.push(new n(r,o))}}return i}},function(t,e,i){var n=i(60),s=new(i(4));t.exports=function(t,e,i){if(void 0===i&&(i=s),n(e,t.x1,t.y1))return i.x=t.x1,i.y=t.y1,!0;if(n(e,t.x2,t.y2))return i.x=t.x2,i.y=t.y2,!0;var r=t.x2-t.x1,o=t.y2-t.y1,a=e.x-t.x1,h=e.y-t.y1,l=r*r+o*o,u=r,c=o;if(l>0){var d=(a*r+h*o)/l;u*=d,c*=d}return i.x=t.x1+u,i.y=t.y1+c,u*u+c*c<=l&&u*r+c*o>=0&&n(e,i.x,i.y)}},function(t,e,i){var n=i(4),s=i(93),r=i(455);t.exports=function(t,e,i){if(void 0===i&&(i=[]),r(t,e))for(var o=e.getLineA(),a=e.getLineB(),h=e.getLineC(),l=e.getLineD(),u=[new n,new n,new n,new n],c=[s(o,t,u[0]),s(a,t,u[1]),s(h,t,u[2]),s(l,t,u[3])],d=0;d<4;d++)c[d]&&i.push(u[d]);return i}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=!1),void 0===n&&(n=[]);for(var s,r,o,a,h,l,u=t.x3-t.x1,c=t.y3-t.y1,d=t.x2-t.x1,f=t.y2-t.y1,p=u*u+c*c,g=u*d+c*f,v=d*d+f*f,y=p*v-g*g,m=0===y?0:1/y,x=t.x1,T=t.y1,w=0;w=0&&r>=0&&s+r<1&&(n.push({x:e[w].x,y:e[w].y}),i)));w++);return n}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,t}},function(t,e){t.exports=function(t){return 0===t.height?NaN:t.width/t.height}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,o=t.x3-e,a=t.y3-i,t.x3=o*s-a*r+e,t.y3=o*r+a*s+i,t}},function(t,e,i){t.exports={BUTTON_DOWN:i(1226),BUTTON_UP:i(1227),CONNECTED:i(1228),DISCONNECTED:i(1229),GAMEPAD_BUTTON_DOWN:i(1230),GAMEPAD_BUTTON_UP:i(1231)}},function(t,e,i){var n=i(17),s=i(144);t.exports=function(t,e){var i=void 0===t?s():n({},t);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},function(t,e,i){var n=i(0),s=i(23),r=i(24),o=i(8),a=i(1),h=i(7),l=i(388),u=new n({Extends:r,initialize:function(t,e,i,n){var s="xml";if(h(e)){var o=e;e=a(o,"key"),i=a(o,"url"),n=a(o,"xhrSettings"),s=a(o,"extension",s)}var l={type:"xml",cache:t.cacheManager.xml,extension:s,responseType:"text",key:e,url:i,xhrSettings:n};r.call(this,t,l)},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=l(this.xhrLoader.responseText),this.data?this.onProcessComplete():(console.warn("Invalid XMLFile: "+this.key),this.onProcessError())}});o.register("xml",function(t,e,i){if(Array.isArray(t))for(var n=0;ng&&(g=m),a.translate(y,{x:.5*x,y:.5*m}),c=y.bounds.max.x+r,s.addBody(u,y),l=y,f+=1}else c+=r}d+=g+o,c=t}return u},n.chain=function(t,e,i,n,a,h){for(var l=t.bodies,u=1;u0)for(l=0;l0&&(d=f[l-1+(h-1)*e],s.addConstraint(t,r.create(o.extend({bodyA:d,bodyB:c},a)))),n&&ld||o<(l=d-l)||o>i-1-l))return 1===c&&a.translate(u,{x:(o+(i%2==1?1:-1))*f,y:0}),h(t+(u?o*f:0)+o*r,n,o,l,u,c)})},n.newtonsCradle=function(t,e,i,n,o){for(var a=s.create({label:"Newtons Cradle"}),l=0;l1;if(!d||t!=d.x||e!=d.y){d&&n?(f=d.x,p=d.y):(f=0,p=0);var s={x:f+t,y:p+e};!n&&d||(d=s),g.push(s),y=f+t,m=p+e}},T=function(t){var e=t.pathSegTypeAsLetter.toUpperCase();if("Z"!==e){switch(e){case"M":case"L":case"T":case"C":case"S":case"Q":y=t.x,m=t.y;break;case"H":y=t.x;break;case"V":m=t.y}x(y,m,t.pathSegType)}};for(n._svgPathToAbsolute(t),o=t.getTotalLength(),l=[],i=0;i0?this.setFromTileCollision(i):this.setFromTileRectangle(i)}},setFromTileRectangle:function(t){void 0===t&&(t={}),h(t,"isStatic")||(t.isStatic=!0),h(t,"addToWorld")||(t.addToWorld=!0);var e=this.tile.getBounds(),i=e.x+e.width/2,s=e.y+e.height/2,r=n.rectangle(i,s,e.width,e.height,t);return this.setBody(r,t.addToWorld),this},setFromTileCollision:function(t){void 0===t&&(t={}),h(t,"isStatic")||(t.isStatic=!0),h(t,"addToWorld")||(t.addToWorld=!0);for(var e=this.tile.tilemapLayer.scaleX,i=this.tile.tilemapLayer.scaleY,r=this.tile.getLeft(),o=this.tile.getTop(),u=this.tile.getCollisionGroup(),c=a(u,"objects",[]),d=[],f=0;f1&&(t.parts=d,this.setBody(s.create(t),t.addToWorld)),this},setBody:function(t,e){return void 0===e&&(e=!0),this.body&&this.removeBody(),this.body=t,this.body.gameObject=this,e&&this.world.add(this.body),this},removeBody:function(){return this.body&&(this.world.remove(this.body),this.body.gameObject=void 0,this.body=void 0),this},destroy:function(){this.removeBody(),this.tile.physics.matterBody=void 0}});t.exports=u},function(t,e,i){var n=i(508);n.Body=i(25),n.Composite=i(68),n.World=i(241),n.Detector=i(148),n.Grid=i(242),n.Pairs=i(243),n.Pair=i(114),n.Query=i(509),n.Resolver=i(244),n.SAT=i(149),n.Constraint=i(78),n.Common=i(19),n.Engine=i(510),n.Events=i(96),n.Sleeping=i(95),n.Plugin=i(240),n.Bodies=i(42),n.Composites=i(233),n.Axes=i(146),n.Bounds=i(38),n.Svg=i(234),n.Vector=i(37),n.Vertices=i(31),n.World.add=n.Composite.add,n.World.remove=n.Composite.remove,n.World.addComposite=n.Composite.addComposite,n.World.addBody=n.Composite.addBody,n.World.addConstraint=n.Composite.addConstraint,n.World.clear=n.Composite.clear,t.exports=n},function(t,e,i){var n={};t.exports=n;var s=i(19);n._registry={},n.register=function(t){if(n.isPlugin(t)||s.warn("Plugin.register:",n.toString(t),"does not implement all required fields."),t.name in n._registry){var e=n._registry[t.name],i=n.versionParse(t.version).number,r=n.versionParse(e.version).number;i>r?(s.warn("Plugin.register:",n.toString(e),"was upgraded to",n.toString(t)),n._registry[t.name]=t):i-1},n.isFor=function(t,e){var i=t.for&&n.dependencyParse(t.for);return!t.for||e.name===i.name&&n.versionSatisfies(e.version,i.range)},n.use=function(t,e){if(t.uses=(t.uses||[]).concat(e||[]),0!==t.uses.length){for(var i=n.dependencies(t),r=s.topologicalSort(i),o=[],a=0;a0&&!h.silent&&s.info(o.join(" "))}else s.warn("Plugin.use:",n.toString(t),"does not specify any dependencies to install.")},n.dependencies=function(t,e){var i=n.dependencyParse(t),r=i.name;if(!(r in(e=e||{}))){t=n.resolve(t)||t,e[r]=s.map(t.uses||[],function(e){n.isPlugin(e)&&n.register(e);var r=n.dependencyParse(e),o=n.resolve(e);return o&&!n.versionSatisfies(o.version,r.range)?(s.warn("Plugin.dependencies:",n.toString(o),"does not satisfy",n.toString(r),"used by",n.toString(i)+"."),o._warned=!0,t._warned=!0):o||(s.warn("Plugin.dependencies:",n.toString(e),"used by",n.toString(i),"could not be resolved."),t._warned=!0),r.name});for(var o=0;o=s[2];if("^"===i.operator)return s[0]>0?o[0]===s[0]&&r.number>=i.number:s[1]>0?o[1]===s[1]&&o[2]>=s[2]:o[2]===s[2]}return t===e||"*"===t}},function(t,e,i){var n={};t.exports=n;var s=i(68),r=(i(78),i(19));n.create=function(t){var e=s.create(),i={label:"World",gravity:{x:0,y:1,scale:.001},bounds:{min:{x:-1/0,y:-1/0},max:{x:1/0,y:1/0}}};return r.extend(e,i,t)}},function(t,e,i){var n={};t.exports=n;var s=i(114),r=i(148),o=i(19);n.create=function(t){var e={controller:n,detector:r.collisions,buckets:{},pairs:{},pairsList:[],bucketWidth:48,bucketHeight:48};return o.extend(e,t)},n.update=function(t,e,i,s){var r,o,a,h,l,u=i.world,c=t.buckets,d=!1,f=i.metrics;for(f.broadphaseTests=0,r=0;ru.bounds.max.x||p.bounds.max.yu.bounds.max.y)){var g=n._getRegion(t,p);if(!p.region||g.id!==p.region.id||s){f.broadphaseTests+=1,p.region&&!s||(p.region=g);var v=n._regionUnion(g,p.region);for(o=v.startCol;o<=v.endCol;o++)for(a=v.startRow;a<=v.endRow;a++){h=c[l=n._getBucketId(o,a)];var y=o>=g.startCol&&o<=g.endCol&&a>=g.startRow&&a<=g.endRow,m=o>=p.region.startCol&&o<=p.region.endCol&&a>=p.region.startRow&&a<=p.region.endRow;!y&&m&&m&&h&&n._bucketRemoveBody(t,h,p),(p.region===g||y&&!m||s)&&(h||(h=n._createBucket(c,l)),n._bucketAddBody(t,h,p))}p.region=g,d=!0}}}d&&(t.pairsList=n._createActivePairsList(t))},n.clear=function(t){t.buckets={},t.pairs={},t.pairsList=[]},n._regionUnion=function(t,e){var i=Math.min(t.startCol,e.startCol),s=Math.max(t.endCol,e.endCol),r=Math.min(t.startRow,e.startRow),o=Math.max(t.endRow,e.endRow);return n._createRegion(i,s,r,o)},n._getRegion=function(t,e){var i=e.bounds,s=Math.floor(i.min.x/t.bucketWidth),r=Math.floor(i.max.x/t.bucketWidth),o=Math.floor(i.min.y/t.bucketHeight),a=Math.floor(i.max.y/t.bucketHeight);return n._createRegion(s,r,o,a)},n._createRegion=function(t,e,i,n){return{id:t+","+e+","+i+","+n,startCol:t,endCol:e,startRow:i,endRow:n}},n._getBucketId=function(t,e){return"C"+t+"R"+e},n._createBucket=function(t,e){return t[e]=[]},n._bucketAddBody=function(t,e,i){for(var n=0;n0?n.push(i):delete t.pairs[e[s]];return n}},function(t,e,i){var n={};t.exports=n;var s=i(114),r=i(19);n._pairMaxIdleLife=1e3,n.create=function(t){return r.extend({table:{},list:[],collisionStart:[],collisionActive:[],collisionEnd:[]},t)},n.update=function(t,e,i){var n,r,o,a,h=t.list,l=t.table,u=t.collisionStart,c=t.collisionEnd,d=t.collisionActive;for(u.length=0,c.length=0,d.length=0,a=0;an._pairMaxIdleLife&&l.push(o);for(o=0;of.friction*f.frictionStatic*k*i&&(I=R,F=o.clamp(f.friction*L*i,-I,I));var B=r.cross(S,y),N=r.cross(A,y),Y=T/(g.inverseMass+v.inverseMass+g.inverseInertia*B*B+v.inverseInertia*N*N);if(D*=Y,F*=Y,P<0&&P*P>n._restingThresh*i)b.normalImpulse=0;else{var X=b.normalImpulse;b.normalImpulse=Math.min(b.normalImpulse+D,0),D=b.normalImpulse-X}if(O*O>n._restingThreshTangent*i)b.tangentImpulse=0;else{var z=b.tangentImpulse;b.tangentImpulse=o.clamp(b.tangentImpulse+F,-I,I),F=b.tangentImpulse-z}s.x=y.x*D+m.x*F,s.y=y.y*D+m.y*F,g.isStatic||g.isSleeping||(g.positionPrev.x+=s.x*g.inverseMass,g.positionPrev.y+=s.y*g.inverseMass,g.anglePrev+=r.cross(S,s)*g.inverseInertia),v.isStatic||v.isSleeping||(v.positionPrev.x-=s.x*v.inverseMass,v.positionPrev.y-=s.y*v.inverseMass,v.anglePrev-=r.cross(A,s)*v.inverseInertia)}}}}},function(t,e,i){var n=i(151);t.exports=function(t,e,i){var s=n(t,e,!0,i),r=n(t,e-1,!0,i),o=n(t,e+1,!0,i),a=n(t-1,e,!0,i),h=n(t+1,e,!0,i),l=s&&s.collides;return l&&(s.faceTop=!0,s.faceBottom=!0,s.faceLeft=!0,s.faceRight=!0),r&&r.collides&&(l&&(s.faceTop=!1),r.faceBottom=!l),o&&o.collides&&(l&&(s.faceBottom=!1),o.faceTop=!l),a&&a.collides&&(l&&(s.faceLeft=!1),a.faceRight=!l),h&&h.collides&&(l&&(s.faceRight=!1),h.faceLeft=!l),s&&!s.collides&&s.resetFaces(),s}},function(t,e,i){var n=i(80),s=i(115),r=i(245),o=i(79);t.exports=function(t,e,i,a,h){if(!s(e,i,h))return null;void 0===a&&(a=!0);var l=h.data[i][e],u=l&&l.collides;if(t instanceof n)null===h.data[i][e]&&(h.data[i][e]=new n(h,t.index,e,i,t.width,t.height)),h.data[i][e].copy(t);else{var c=t;null===h.data[i][e]?h.data[i][e]=new n(h,c,e,i,h.tileWidth,h.tileHeight):h.data[i][e].index=c}var d=h.data[i][e],f=-1!==h.collideIndexes.indexOf(d.index);return o(d,f),a&&u!==d.collides&&r(e,i,h),d}},function(t,e){t.exports=function(t,e,i){var n=i.collideIndexes.indexOf(t);e&&-1===n?i.collideIndexes.push(t):e||-1===n||i.collideIndexes.splice(n,1)}},function(t,e,i){var n=i(34),s=i(116),r=i(117),o=i(80);t.exports=function(t,e,i,a,h){for(var l=new s({tileWidth:i,tileHeight:a}),u=new r({name:t,tileWidth:i,tileHeight:a,format:n.ARRAY_2D,layers:[l]}),c=[],d=e.length,f=0,p=0;p0&&(s.totalDuration+=s.t2*s.repeat),s.totalDuration>t&&(t=s.totalDuration),s.delay0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay,this.startDelay=e},init:function(){if(this.paused&&!this.parentIsTimeline)return this.state=h.PENDING_ADD,this._pausedState=h.INIT,!1;for(var t=this.data,e=this.totalTargets,i=0;i0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweenData(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=h.LOOP_DELAY):(this.state=h.ACTIVE,this.dispatchTweenEvent(r.TWEEN_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=h.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=h.PENDING_REMOVE,this.dispatchTweenEvent(r.TWEEN_COMPLETE,this.callbacks.onComplete))},pause:function(){return this.state===h.PAUSED?this:(this.paused=!0,this._pausedState=this.state,this.state=h.PAUSED,this)},play:function(t){void 0===t&&(t=!1);var e=this.state;return e!==h.INIT||this.parentIsTimeline?e===h.ACTIVE||e===h.PENDING_ADD&&this._pausedState===h.PENDING_ADD?this:this.parentIsTimeline||e!==h.PENDING_REMOVE&&e!==h.REMOVED?(this.parentIsTimeline?(this.resetTweenData(t),0===this.calculatedOffset?this.state=h.ACTIVE:(this.countdown=this.calculatedOffset,this.state=h.OFFSET_DELAY)):this.paused?(this.paused=!1,this.makeActive()):(this.resetTweenData(t),this.state=h.ACTIVE,this.makeActive()),this):(this.seek(0),this.parent.makeActive(this),this):(this.resetTweenData(!1),this.state=h.ACTIVE,this)},resetTweenData:function(t){for(var e=this.data,i=this.totalData,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY),r.getActiveValue&&(o[a]=r.getActiveValue(r.target,r.key,r.start))}},resume:function(){return this.state===h.PAUSED?(this.paused=!1,this.state=this._pausedState):this.play(),this},seek:function(t,e){if(void 0===e&&(e=16.6),this.totalDuration>=36e5)return console.warn("Tween.seek duration too long"),this;this.state===h.REMOVED&&this.makeActive(),this.elapsed=0,this.progress=0,this.totalElapsed=0,this.totalProgress=0;for(var i=this.data,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY)}this.calcDuration();var c=!1;this.state===h.PAUSED&&(c=!0,this.state=h.ACTIVE),this.isSeeking=!0;do{this.update(0,e)}while(this.totalProgress0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.start=e.getStartValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},setStateFromStart:function(t,e,i){return e.repeatCounter>0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},updateTweenData:function(t,e,i){var n=e.target;switch(e.state){case h.PLAYING_FORWARD:case h.PLAYING_BACKWARD:if(!n){e.state=h.COMPLETE;break}var s=e.elapsed,o=e.duration,a=0;(s+=i)>o&&(a=s-o,s=o);var l=e.state===h.PLAYING_FORWARD,u=s/o;if(e.elapsed=s,e.progress=u,e.previous=e.current,1===u)l?(e.current=e.end,n[e.key]=e.end,e.hold>0?(e.elapsed=e.hold-a,e.state=h.HOLD_DELAY):e.state=this.setStateFromEnd(t,e,a)):(e.current=e.start,n[e.key]=e.start,e.state=this.setStateFromStart(t,e,a));else{var c=l?e.ease(u):e.ease(1-u);e.current=e.start+(e.end-e.start)*c,n[e.key]=e.current}this.dispatchTweenDataEvent(r.TWEEN_UPDATE,t.callbacks.onUpdate,e);break;case h.DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PENDING_RENDER);break;case h.REPEAT_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PLAYING_FORWARD,this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e));break;case h.HOLD_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.state=this.setStateFromEnd(t,e,Math.abs(e.elapsed)));break;case h.PENDING_RENDER:n?(e.start=e.getStartValue(n,e.key,n[e.key],e.index,t.totalTargets,t),e.end=e.getEndValue(n,e.key,e.start,e.index,t.totalTargets,t),e.current=e.start,n[e.key]=e.start,e.state=h.PLAYING_FORWARD):e.state=h.COMPLETE}return e.state!==h.COMPLETE}});u.TYPES=["onActive","onComplete","onLoop","onRepeat","onStart","onUpdate","onYoyo"],a.register("tween",function(t){return this.scene.sys.tweens.add(t)}),o.register("tween",function(t){return this.scene.sys.tweens.create(t)}),t.exports=u},function(t,e,i){t.exports={TIMELINE_COMPLETE:i(1434),TIMELINE_LOOP:i(1435),TIMELINE_PAUSE:i(1436),TIMELINE_RESUME:i(1437),TIMELINE_START:i(1438),TIMELINE_UPDATE:i(1439),TWEEN_ACTIVE:i(1440),TWEEN_COMPLETE:i(1441),TWEEN_LOOP:i(1442),TWEEN_REPEAT:i(1443),TWEEN_START:i(1444),TWEEN_UPDATE:i(1445),TWEEN_YOYO:i(1446)}},function(t,e){t.exports=function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p){return{target:t,index:e,key:i,getActiveValue:r,getEndValue:n,getStartValue:s,ease:o,duration:0,totalDuration:0,delay:0,yoyo:l,hold:0,repeat:0,repeatDelay:0,flipX:f,flipY:p,progress:0,elapsed:0,repeatCounter:0,start:0,previous:0,current:0,end:0,t1:0,t2:0,gen:{delay:a,duration:h,hold:u,repeat:c,repeatDelay:d},state:0}}},function(t,e,i){t.exports={AlignTo:i(553),Angle:i(554),Call:i(555),GetFirst:i(556),GetLast:i(557),GridAlign:i(558),IncAlpha:i(619),IncX:i(620),IncXY:i(621),IncY:i(622),PlaceOnCircle:i(623),PlaceOnEllipse:i(624),PlaceOnLine:i(625),PlaceOnRectangle:i(626),PlaceOnTriangle:i(627),PlayAnimation:i(628),PropertyValueInc:i(39),PropertyValueSet:i(27),RandomCircle:i(629),RandomEllipse:i(630),RandomLine:i(631),RandomRectangle:i(632),RandomTriangle:i(633),Rotate:i(634),RotateAround:i(635),RotateAroundDistance:i(636),ScaleX:i(637),ScaleXY:i(638),ScaleY:i(639),SetAlpha:i(640),SetBlendMode:i(641),SetDepth:i(642),SetHitArea:i(643),SetOrigin:i(644),SetRotation:i(645),SetScale:i(646),SetScaleX:i(647),SetScaleY:i(648),SetScrollFactor:i(649),SetScrollFactorX:i(650),SetScrollFactorY:i(651),SetTint:i(652),SetVisible:i(653),SetX:i(654),SetXY:i(655),SetY:i(656),ShiftPosition:i(657),Shuffle:i(658),SmootherStep:i(659),SmoothStep:i(660),Spread:i(661),ToggleVisible:i(662),WrapInRectangle:i(663)}},function(t,e,i){var n=i(97),s=[];s[n.BOTTOM_CENTER]=i(261),s[n.BOTTOM_LEFT]=i(262),s[n.BOTTOM_RIGHT]=i(263),s[n.LEFT_BOTTOM]=i(264),s[n.LEFT_CENTER]=i(265),s[n.LEFT_TOP]=i(266),s[n.RIGHT_BOTTOM]=i(267),s[n.RIGHT_CENTER]=i(268),s[n.RIGHT_TOP]=i(269),s[n.TOP_CENTER]=i(270),s[n.TOP_LEFT]=i(271),s[n.TOP_RIGHT]=i(272);t.exports=function(t,e,i,n,r){return s[i](t,e,n,r)}},function(t,e,i){var n=i(44),s=i(81),r=i(82),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)+i),o(t,n(e)+a),t}},function(t,e,i){var n=i(44),s=i(46),r=i(47),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)-i),o(t,n(e)+a),t}},function(t,e,i){var n=i(44),s=i(48),r=i(49),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,s(e)+i),o(t,n(e)+a),t}},function(t,e,i){var n=i(44),s=i(46),r=i(50),o=i(49);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(83),s=i(46),r=i(84),o=i(49);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(46),s=i(51),r=i(49),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)-i),o(t,s(e)-a),t}},function(t,e,i){var n=i(44),s=i(48),r=i(50),o=i(47);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(83),s=i(48),r=i(84),o=i(47);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(48),s=i(51),r=i(47),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(81),s=i(51),r=i(50),o=i(82);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)+i),r(t,s(e)-a),t}},function(t,e,i){var n=i(46),s=i(51),r=i(50),o=i(47);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)-i),r(t,s(e)-a),t}},function(t,e,i){var n=i(48),s=i(51),r=i(50),o=i(49);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,n(e)+i),r(t,s(e)-a),t}},function(t,e,i){var n=i(97),s=[];s[n.BOTTOM_CENTER]=i(274),s[n.BOTTOM_LEFT]=i(275),s[n.BOTTOM_RIGHT]=i(276),s[n.CENTER]=i(277),s[n.LEFT_CENTER]=i(279),s[n.RIGHT_CENTER]=i(280),s[n.TOP_CENTER]=i(281),s[n.TOP_LEFT]=i(282),s[n.TOP_RIGHT]=i(283),s[n.LEFT_BOTTOM]=s[n.BOTTOM_LEFT],s[n.LEFT_TOP]=s[n.TOP_LEFT],s[n.RIGHT_BOTTOM]=s[n.BOTTOM_RIGHT],s[n.RIGHT_TOP]=s[n.TOP_RIGHT];t.exports=function(t,e,i,n,r){return s[i](t,e,n,r)}},function(t,e,i){var n=i(44),s=i(81),r=i(50),o=i(82);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(44),s=i(46),r=i(50),o=i(47);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(44),s=i(48),r=i(50),o=i(49);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(278),s=i(81),r=i(83);t.exports=function(t,e,i,o){return void 0===i&&(i=0),void 0===o&&(o=0),n(t,s(e)+i,r(e)+o),t}},function(t,e,i){var n=i(82),s=i(84);t.exports=function(t,e,i){return n(t,e),s(t,i)}},function(t,e,i){var n=i(83),s=i(46),r=i(84),o=i(47);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)-i),r(t,n(e)+a),t}},function(t,e,i){var n=i(83),s=i(48),r=i(84),o=i(49);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),o(t,s(e)+i),r(t,n(e)+a),t}},function(t,e,i){var n=i(81),s=i(51),r=i(82),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(46),s=i(51),r=i(47),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)-i),o(t,s(e)-a),t}},function(t,e,i){var n=i(48),s=i(51),r=i(49),o=i(45);t.exports=function(t,e,i,a){return void 0===i&&(i=0),void 0===a&&(a=0),r(t,n(e)+i),o(t,s(e)-a),t}},function(t,e,i){var n=i(158),s=i(98),r=i(13),o=i(4);t.exports=function(t,e,i){void 0===i&&(i=new o);var a=s(e,0,r.PI2);return n(t,a,i)}},function(t,e,i){var n=i(286),s=i(158),r=i(98),o=i(13);t.exports=function(t,e,i,a){void 0===a&&(a=[]),e||(e=n(t)/i);for(var h=0;h=this.nextTick&&this.currentAnim.setFrame(this)}},setCurrentFrame:function(t){var e=this.parent;return this.currentFrame=t,e.texture=t.frame.texture,e.frame=t.frame,e.isCropped&&e.frame.updateCropUVs(e._crop,e.flipX,e.flipY),e.setSizeToFrame(),t.frame.customPivot?e.setOrigin(t.frame.pivotX,t.frame.pivotY):e.updateDisplayOrigin(),e},updateFrame:function(t){var e=this.setCurrentFrame(t);if(this.isPlaying){t.setAlpha&&(e.alpha=t.alpha);var i=this.currentAnim;e.emit(r.SPRITE_ANIMATION_KEY_UPDATE+i.key,i,t,e),e.emit(r.SPRITE_ANIMATION_UPDATE,i,t,e),3===this._pendingStop&&this._pendingStopValue===t&&this.currentAnim.completeAnimation(this)}},nextFrame:function(){return this.currentAnim&&this.currentAnim.nextFrame(this),this.parent},previousFrame:function(){return this.currentAnim&&this.currentAnim.previousFrame(this),this.parent},setYoyo:function(t){return void 0===t&&(t=!1),this._yoyo=t,this.parent},getYoyo:function(){return this._yoyo},destroy:function(){this.animationManager.off(r.REMOVE_ANIMATION,this.remove,this),this.animationManager=null,this.parent=null,this.currentAnim=null,this.currentFrame=null}});t.exports=o},function(t,e){t.exports=function(t,e,i){if(!e.length)return NaN;if(1===e.length)return e[0];var n,s,r=1;if(i){if(te.length&&(r=e.length),i?(n=e[r-1][i],(s=e[r][i])-t<=t-n?e[r]:e[r-1]):(n=e[r-1],(s=e[r])-t<=t-n?s:n)}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.textureKey=t,this.textureFrame=e,this.index=i,this.frame=n,this.isFirst=!1,this.isLast=!1,this.prevFrame=null,this.nextFrame=null,this.duration=0,this.progress=0},toJSON:function(){return{key:this.textureKey,frame:this.textureFrame,duration:this.duration}},destroy:function(){this.frame=void 0}});t.exports=n},function(t,e,i){var n=i(43),s={_blendMode:n.NORMAL,blendMode:{get:function(){return this._blendMode},set:function(t){"string"==typeof t&&(t=n[t]),(t|=0)>=-1&&(this._blendMode=t)}},setBlendMode:function(t){return this.blendMode=t,this}};t.exports=s},function(t,e){var i={_depth:0,depth:{get:function(){return this._depth},set:function(t){this.scene.sys.queueDepthSort(),this._depth=t}},setDepth:function(t){return void 0===t&&(t=0),this.depth=t,this}};t.exports=i},function(t,e,i){var n=i(161),s=i(120);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=s(t)/i);for(var o=0;o=t.right&&(h=1,a+=o-t.right,o=t.right);break;case 1:(a+=e)>=t.bottom&&(h=2,o-=a-t.bottom,a=t.bottom);break;case 2:(o-=e)<=t.left&&(h=3,a-=t.left-o,o=t.left);break;case 3:(a-=e)<=t.top&&(h=0,a=t.top)}return r}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);for(var i=null,n=0;n-h&&(c-=h,n+=l),fd.right&&(f=u(f,f+(g-d.right),this.lerp.x)),vd.bottom&&(p=u(p,p+(v-d.bottom),this.lerp.y))):(f=u(f,g-h,this.lerp.x),p=u(p,v-l,this.lerp.y))}this.useBounds&&(f=this.clampX(f),p=this.clampY(p)),this.roundPixels&&(h=Math.round(h),l=Math.round(l)),this.scrollX=f,this.scrollY=p;var y=f+n,m=p+s;this.midPoint.set(y,m);var x=e/o,T=i/o;this.worldView.setTo(y-x/2,m-T/2,x,T),a.applyITRS(this.x+h,this.y+l,this.rotation,o,o),a.translate(-h,-l),this.shakeEffect.preRender()},setLerp:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=t),this.lerp.set(t,e),this},setFollowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.followOffset.set(t,e),this},startFollow:function(t,e,i,n,s,r){void 0===e&&(e=!1),void 0===i&&(i=1),void 0===n&&(n=i),void 0===s&&(s=0),void 0===r&&(r=s),this._follow=t,this.roundPixels=e,i=o(i,0,1),n=o(n,0,1),this.lerp.set(i,n),this.followOffset.set(s,r);var a=this.width/2,h=this.height/2,l=t.x-s,u=t.y-r;return this.midPoint.set(l,u),this.scrollX=l-a,this.scrollY=u-h,this.useBounds&&(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},stopFollow:function(){return this._follow=null,this},resetFX:function(){return this.panEffect.reset(),this.shakeEffect.reset(),this.flashEffect.reset(),this.fadeEffect.reset(),this},update:function(t,e){this.visible&&(this.panEffect.update(t,e),this.zoomEffect.update(t,e),this.shakeEffect.update(t,e),this.flashEffect.update(t,e),this.fadeEffect.update(t,e))},destroy:function(){this.clearRenderToTexture(),this.resetFX(),n.prototype.destroy.call(this),this._follow=null,this.deadzone=null}});t.exports=f},function(t,e,i){var n=i(36);t.exports=function(t){var e=new n;t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,n){return e+e+i+i+n+n});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e.setTo(s,r,o)}return e}},function(t,e){t.exports=function(t,e,i,n){return n<<24|t<<16|e<<8|i}},function(t,e){t.exports=function(t,e,i,n){void 0===n&&(n={h:0,s:0,v:0}),t/=255,e/=255,i/=255;var s=Math.min(t,e,i),r=Math.max(t,e,i),o=r-s,a=0,h=0===r?0:o/r,l=r;return r!==s&&(r===t?a=(e-i)/o+(e16777215?{a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{a:255,r:t>>16&255,g:t>>8&255,b:255&t}}},function(t,e,i){var n=i(36);t.exports=function(t){return new n(t.r,t.g,t.b,t.a)}},function(t,e,i){var n=i(36);t.exports=function(t){var e=new n,i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t.toLowerCase());if(i){var s=parseInt(i[1],10),r=parseInt(i[2],10),o=parseInt(i[3],10),a=void 0!==i[4]?parseFloat(i[4]):1;e.setTo(s,r,o,255*a)}return e}},function(t,e,i){t.exports={Fade:i(688),Flash:i(689),Pan:i(690),Shake:i(723),Zoom:i(724)}},function(t,e,i){t.exports={In:i(691),Out:i(692),InOut:i(693)}},function(t,e,i){t.exports={In:i(694),Out:i(695),InOut:i(696)}},function(t,e,i){t.exports={In:i(697),Out:i(698),InOut:i(699)}},function(t,e,i){t.exports={In:i(700),Out:i(701),InOut:i(702)}},function(t,e,i){t.exports={In:i(703),Out:i(704),InOut:i(705)}},function(t,e,i){t.exports={In:i(706),Out:i(707),InOut:i(708)}},function(t,e,i){t.exports=i(709)},function(t,e,i){t.exports={In:i(710),Out:i(711),InOut:i(712)}},function(t,e,i){t.exports={In:i(713),Out:i(714),InOut:i(715)}},function(t,e,i){t.exports={In:i(716),Out:i(717),InOut:i(718)}},function(t,e,i){t.exports={In:i(719),Out:i(720),InOut:i(721)}},function(t,e,i){t.exports=i(722)},function(t,e,i){var n=i(0),s=i(32),r=i(334),o=i(1),a=i(5),h=i(7),l=i(181),u=i(2),c=i(186),d=i(174),f=new n({initialize:function(t){void 0===t&&(t={});this.width=a(t,"width",1024),this.height=a(t,"height",768),this.zoom=a(t,"zoom",1),this.resolution=a(t,"resolution",1),this.parent=a(t,"parent",void 0),this.scaleMode=a(t,"scaleMode",0),this.expandParent=a(t,"expandParent",!0),this.autoRound=a(t,"autoRound",!1),this.autoCenter=a(t,"autoCenter",0),this.resizeInterval=a(t,"resizeInterval",500),this.fullscreenTarget=a(t,"fullscreenTarget",null),this.minWidth=a(t,"minWidth",0),this.maxWidth=a(t,"maxWidth",0),this.minHeight=a(t,"minHeight",0),this.maxHeight=a(t,"maxHeight",0);var e=a(t,"scale",null);e&&(this.width=a(e,"width",this.width),this.height=a(e,"height",this.height),this.zoom=a(e,"zoom",this.zoom),this.resolution=a(e,"resolution",this.resolution),this.parent=a(e,"parent",this.parent),this.scaleMode=a(e,"mode",this.scaleMode),this.expandParent=a(e,"expandParent",this.expandParent),this.autoRound=a(e,"autoRound",this.autoRound),this.autoCenter=a(e,"autoCenter",this.autoCenter),this.resizeInterval=a(e,"resizeInterval",this.resizeInterval),this.fullscreenTarget=a(e,"fullscreenTarget",this.fullscreenTarget),this.minWidth=a(e,"min.width",this.minWidth),this.maxWidth=a(e,"max.width",this.maxWidth),this.minHeight=a(e,"min.height",this.minHeight),this.maxHeight=a(e,"max.height",this.maxHeight)),this.renderType=a(t,"type",s.AUTO),this.canvas=a(t,"canvas",null),this.context=a(t,"context",null),this.canvasStyle=a(t,"canvasStyle",null),this.customEnvironment=a(t,"customEnvironment",!1),this.sceneConfig=a(t,"scene",null),this.seed=a(t,"seed",[(Date.now()*Math.random()).toString()]),l.RND=new l.RandomDataGenerator(this.seed),this.gameTitle=a(t,"title",""),this.gameURL=a(t,"url","https://phaser.io"),this.gameVersion=a(t,"version",""),this.autoFocus=a(t,"autoFocus",!0),this.domCreateContainer=a(t,"dom.createContainer",!1),this.domBehindCanvas=a(t,"dom.behindCanvas",!1),this.inputKeyboard=a(t,"input.keyboard",!0),this.inputKeyboardEventTarget=a(t,"input.keyboard.target",window),this.inputKeyboardCapture=a(t,"input.keyboard.capture",[]),this.inputMouse=a(t,"input.mouse",!0),this.inputMouseEventTarget=a(t,"input.mouse.target",null),this.inputMouseCapture=a(t,"input.mouse.capture",!0),this.inputTouch=a(t,"input.touch",r.input.touch),this.inputTouchEventTarget=a(t,"input.touch.target",null),this.inputTouchCapture=a(t,"input.touch.capture",!0),this.inputActivePointers=a(t,"input.activePointers",1),this.inputSmoothFactor=a(t,"input.smoothFactor",0),this.inputWindowEvents=a(t,"input.windowEvents",!0),this.inputGamepad=a(t,"input.gamepad",!1),this.inputGamepadEventTarget=a(t,"input.gamepad.target",window),this.disableContextMenu=a(t,"disableContextMenu",!1),this.audio=a(t,"audio"),this.hideBanner=!1===a(t,"banner",null),this.hidePhaser=a(t,"banner.hidePhaser",!1),this.bannerTextColor=a(t,"banner.text","#ffffff"),this.bannerBackgroundColor=a(t,"banner.background",["#ff0000","#ffff00","#00ff00","#00ffff","#000000"]),""===this.gameTitle&&this.hidePhaser&&(this.hideBanner=!0),this.fps=a(t,"fps",null);var i=a(t,"render",t);this.antialias=a(i,"antialias",!0),this.antialiasGL=a(i,"antialiasGL",!0),this.mipmapFilter=a(i,"mipmapFilter","LINEAR"),this.desynchronized=a(i,"desynchronized",!1),this.roundPixels=a(i,"roundPixels",!1),this.pixelArt=a(i,"pixelArt",1!==this.zoom),this.pixelArt&&(this.antialias=!1,this.roundPixels=!0),this.transparent=a(i,"transparent",!1),this.clearBeforeRender=a(i,"clearBeforeRender",!0),this.premultipliedAlpha=a(i,"premultipliedAlpha",!0),this.failIfMajorPerformanceCaveat=a(i,"failIfMajorPerformanceCaveat",!1),this.powerPreference=a(i,"powerPreference","default"),this.batchSize=a(i,"batchSize",2e3),this.maxLights=a(i,"maxLights",10);var n=a(t,"backgroundColor",0);this.backgroundColor=d(n),0===n&&this.transparent&&(this.backgroundColor.alpha=0),this.preBoot=a(t,"callbacks.preBoot",u),this.postBoot=a(t,"callbacks.postBoot",u),this.physics=a(t,"physics",{}),this.defaultPhysicsSystem=a(this.physics,"default",!1),this.loaderBaseURL=a(t,"loader.baseURL",""),this.loaderPath=a(t,"loader.path",""),this.loaderMaxParallelDownloads=a(t,"loader.maxParallelDownloads",32),this.loaderCrossOrigin=a(t,"loader.crossOrigin",void 0),this.loaderResponseType=a(t,"loader.responseType",""),this.loaderAsync=a(t,"loader.async",!0),this.loaderUser=a(t,"loader.user",""),this.loaderPassword=a(t,"loader.password",""),this.loaderTimeout=a(t,"loader.timeout",0),this.installGlobalPlugins=[],this.installScenePlugins=[];var f=a(t,"plugins",null),p=c.DefaultScene;f&&(Array.isArray(f)?this.defaultPlugins=f:h(f)&&(this.installGlobalPlugins=o(f,"global",[]),this.installScenePlugins=o(f,"scene",[]),Array.isArray(f.default)?p=f.default:Array.isArray(f.defaultMerge)&&(p=p.concat(f.defaultMerge)))),this.defaultPlugins=p;var g="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg";this.defaultImage=a(t,"images.default",g+"AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="),this.missingImage=a(t,"images.missing",g+"CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="),window&&(window.FORCE_WEBGL?this.renderType=s.WEBGL:window.FORCE_CANVAS&&(this.renderType=s.CANVAS))}});t.exports=f},function(t,e,i){t.exports={os:i(124),browser:i(125),features:i(180),input:i(753),audio:i(754),video:i(755),fullscreen:i(756),canvasFeatures:i(335)}},function(t,e,i){var n,s,r,o=i(28),a={supportInverseAlpha:!1,supportNewBlendModes:!1};t.exports=(void 0!==document&&(a.supportNewBlendModes=(n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",s="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",(r=new Image).onload=function(){var t=new Image;t.onload=function(){var e=o.create(t,6,1).getContext("2d");if(e.globalCompositeOperation="multiply",e.drawImage(r,0,0),e.drawImage(t,2,0),!e.getImageData(2,0,1,1))return!1;var i=e.getImageData(2,0,1,1).data;o.remove(t),a.supportNewBlendModes=255===i[0]&&0===i[1]&&0===i[2]},t.src=n+"/wCKxvRF"+s},r.src=n+"AP804Oa6"+s,!1),a.supportInverseAlpha=function(){var t=o.create(this,2,1).getContext("2d");t.fillStyle="rgba(10, 20, 30, 0.5)",t.fillRect(0,0,1,1);var e=t.getImageData(0,0,1,1);if(null===e)return!1;t.putImageData(e,1,0);var i=t.getImageData(1,0,1,1);return i.data[0]===e.data[0]&&i.data[1]===e.data[1]&&i.data[2]===e.data[2]&&i.data[3]===e.data[3]}()),a)},function(t,e){t.exports=function(t,e,i,n){return Math.atan2(n-e,i-t)}},function(t,e){t.exports=function(t){return(t%=2*Math.PI)>=0?t:t+2*Math.PI}},function(t,e){t.exports=function(t,e,i,n){var s=t-i,r=e-n;return s*s+r*r}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t>e-i}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t0?Math.ceil(t):Math.floor(t)}},function(t,e,i){var n=i(3);t.exports=function(t,e,i,s,r,o,a,h){void 0===h&&(h=new n);var l=Math.sin(r),u=Math.cos(r),c=u*o,d=l*o,f=-l*a,p=u*a,g=1/(c*p+f*-d);return h.x=p*g*t+-f*g*e+(s*f-i*p)*g,h.y=c*g*e+-d*g*t+(-s*c+i*d)*g,h}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.x=0,this.y=0,this.z=0,this.w=0,"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},clone:function(){return new n(this.x,this.y,this.z,this.w)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z||0,this.w=t.w||0,this},equals:function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z||0,this.w+=t.w||0,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z||0,this.w-=t.w||0,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z||1,this.w*=t.w||1,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z||1,this.w/=t.w||1,this},distance:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return Math.sqrt(e*e+i*i+n*n+s*s)},distanceSq:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return e*e+i*i+n*n+s*s},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.val;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},reset:function(){return this.x=0,this.y=0,this.z=0,this.w=0,this}});n.prototype.sub=n.prototype.subtract,n.prototype.mul=n.prototype.multiply,n.prototype.div=n.prototype.divide,n.prototype.dist=n.prototype.distance,n.prototype.distSq=n.prototype.distanceSq,n.prototype.len=n.prototype.length,n.prototype.lenSq=n.prototype.lengthSq,t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(9),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this},fromMat4:function(t){var e=t.val,i=this.val;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[5];return t[1]=t[3],t[2]=t[6],t[3]=e,t[5]=t[7],t[6]=i,t[7]=n,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=l*r-o*h,c=-l*s+o*a,d=h*s-r*a,f=e*u+i*c+n*d;return f?(f=1/f,t[0]=u*f,t[1]=(-l*i+n*h)*f,t[2]=(o*i-n*r)*f,t[3]=c*f,t[4]=(l*e-n*a)*f,t[5]=(-o*e+n*s)*f,t[6]=d*f,t[7]=(-h*e+i*a)*f,t[8]=(r*e-i*s)*f,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return t[0]=r*l-o*h,t[1]=n*h-i*l,t[2]=i*o-n*r,t[3]=o*a-s*l,t[4]=e*l-n*a,t[5]=n*s-e*o,t[6]=s*h-r*a,t[7]=i*a-e*h,t[8]=e*r-i*s,this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*(l*r-o*h)+i*(-l*s+o*a)+n*(h*s-r*a)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=t.val,d=c[0],f=c[1],p=c[2],g=c[3],v=c[4],y=c[5],m=c[6],x=c[7],T=c[8];return e[0]=d*i+f*r+p*h,e[1]=d*n+f*o+p*l,e[2]=d*s+f*a+p*u,e[3]=g*i+v*r+y*h,e[4]=g*n+v*o+y*l,e[5]=g*s+v*a+y*u,e[6]=m*i+x*r+T*h,e[7]=m*n+x*o+T*l,e[8]=m*s+x*a+T*u,this},translate:function(t){var e=this.val,i=t.x,n=t.y;return e[6]=i*e[0]+n*e[3]+e[6],e[7]=i*e[1]+n*e[4]+e[7],e[8]=i*e[2]+n*e[5]+e[8],this},rotate:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=Math.sin(t),l=Math.cos(t);return e[0]=l*i+h*r,e[1]=l*n+h*o,e[2]=l*s+h*a,e[3]=l*r-h*i,e[4]=l*o-h*n,e[5]=l*a-h*s,this},scale:function(t){var e=this.val,i=t.x,n=t.y;return e[0]=i*e[0],e[1]=i*e[1],e[2]=i*e[2],e[3]=n*e[3],e[4]=n*e[4],e[5]=n*e[5],this},fromQuat:function(t){var e=t.x,i=t.y,n=t.z,s=t.w,r=e+e,o=i+i,a=n+n,h=e*r,l=e*o,u=e*a,c=i*o,d=i*a,f=n*a,p=s*r,g=s*o,v=s*a,y=this.val;return y[0]=1-(c+f),y[3]=l+v,y[6]=u-g,y[1]=l-v,y[4]=1-(h+f),y[7]=d+p,y[2]=u+g,y[5]=d-p,y[8]=1-(h+c),this},normalFromMat4:function(t){var e=t.val,i=this.val,n=e[0],s=e[1],r=e[2],o=e[3],a=e[4],h=e[5],l=e[6],u=e[7],c=e[8],d=e[9],f=e[10],p=e[11],g=e[12],v=e[13],y=e[14],m=e[15],x=n*h-s*a,T=n*l-r*a,w=n*u-o*a,b=s*l-r*h,E=s*u-o*h,S=r*u-o*l,A=c*v-d*g,_=c*y-f*g,C=c*m-p*g,M=d*y-f*v,P=d*m-p*v,O=f*m-p*y,R=x*O-T*P+w*M+b*C-E*_+S*A;return R?(R=1/R,i[0]=(h*O-l*P+u*M)*R,i[1]=(l*C-a*O-u*_)*R,i[2]=(a*P-h*C+u*A)*R,i[3]=(r*P-s*O-o*M)*R,i[4]=(n*O-r*C+o*_)*R,i[5]=(s*C-n*P-o*A)*R,i[6]=(v*S-y*E+m*b)*R,i[7]=(y*w-g*S-m*T)*R,i[8]=(g*E-v*w+m*x)*R,this):null}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(16),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},zero:function(){var t=this.val;return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=0,this},xyz:function(t,e,i){this.identity();var n=this.val;return n[12]=t,n[13]=e,n[14]=i,this},scaling:function(t,e,i){this.zero();var n=this.val;return n[0]=t,n[5]=e,n[10]=i,n[15]=1,this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[3],s=t[6],r=t[7],o=t[11];return t[1]=t[4],t[2]=t[8],t[3]=t[12],t[4]=e,t[6]=t[9],t[7]=t[13],t[8]=i,t[9]=s,t[11]=t[14],t[12]=n,t[13]=r,t[14]=o,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15],y=e*o-i*r,m=e*a-n*r,x=e*h-s*r,T=i*a-n*o,w=i*h-s*o,b=n*h-s*a,E=l*p-u*f,S=l*g-c*f,A=l*v-d*f,_=u*g-c*p,C=u*v-d*p,M=c*v-d*g,P=y*M-m*C+x*_+T*A-w*S+b*E;return P?(P=1/P,t[0]=(o*M-a*C+h*_)*P,t[1]=(n*C-i*M-s*_)*P,t[2]=(p*b-g*w+v*T)*P,t[3]=(c*w-u*b-d*T)*P,t[4]=(a*A-r*M-h*S)*P,t[5]=(e*M-n*A+s*S)*P,t[6]=(g*x-f*b-v*m)*P,t[7]=(l*b-c*x+d*m)*P,t[8]=(r*C-o*A+h*E)*P,t[9]=(i*A-e*C-s*E)*P,t[10]=(f*w-p*x+v*y)*P,t[11]=(u*x-l*w-d*y)*P,t[12]=(o*S-r*_-a*E)*P,t[13]=(e*_-i*S+n*E)*P,t[14]=(p*m-f*T-g*y)*P,t[15]=(l*T-u*m+c*y)*P,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return t[0]=o*(c*v-d*g)-u*(a*v-h*g)+p*(a*d-h*c),t[1]=-(i*(c*v-d*g)-u*(n*v-s*g)+p*(n*d-s*c)),t[2]=i*(a*v-h*g)-o*(n*v-s*g)+p*(n*h-s*a),t[3]=-(i*(a*d-h*c)-o*(n*d-s*c)+u*(n*h-s*a)),t[4]=-(r*(c*v-d*g)-l*(a*v-h*g)+f*(a*d-h*c)),t[5]=e*(c*v-d*g)-l*(n*v-s*g)+f*(n*d-s*c),t[6]=-(e*(a*v-h*g)-r*(n*v-s*g)+f*(n*h-s*a)),t[7]=e*(a*d-h*c)-r*(n*d-s*c)+l*(n*h-s*a),t[8]=r*(u*v-d*p)-l*(o*v-h*p)+f*(o*d-h*u),t[9]=-(e*(u*v-d*p)-l*(i*v-s*p)+f*(i*d-s*u)),t[10]=e*(o*v-h*p)-r*(i*v-s*p)+f*(i*h-s*o),t[11]=-(e*(o*d-h*u)-r*(i*d-s*u)+l*(i*h-s*o)),t[12]=-(r*(u*g-c*p)-l*(o*g-a*p)+f*(o*c-a*u)),t[13]=e*(u*g-c*p)-l*(i*g-n*p)+f*(i*c-n*u),t[14]=-(e*(o*g-a*p)-r*(i*g-n*p)+f*(i*a-n*o)),t[15]=e*(o*c-a*u)-r*(i*c-n*u)+l*(i*a-n*o),this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return(e*o-i*r)*(c*v-d*g)-(e*a-n*r)*(u*v-d*p)+(e*h-s*r)*(u*g-c*p)+(i*a-n*o)*(l*v-d*f)-(i*h-s*o)*(l*g-c*f)+(n*h-s*a)*(l*p-u*f)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=e[9],d=e[10],f=e[11],p=e[12],g=e[13],v=e[14],y=e[15],m=t.val,x=m[0],T=m[1],w=m[2],b=m[3];return e[0]=x*i+T*o+w*u+b*p,e[1]=x*n+T*a+w*c+b*g,e[2]=x*s+T*h+w*d+b*v,e[3]=x*r+T*l+w*f+b*y,x=m[4],T=m[5],w=m[6],b=m[7],e[4]=x*i+T*o+w*u+b*p,e[5]=x*n+T*a+w*c+b*g,e[6]=x*s+T*h+w*d+b*v,e[7]=x*r+T*l+w*f+b*y,x=m[8],T=m[9],w=m[10],b=m[11],e[8]=x*i+T*o+w*u+b*p,e[9]=x*n+T*a+w*c+b*g,e[10]=x*s+T*h+w*d+b*v,e[11]=x*r+T*l+w*f+b*y,x=m[12],T=m[13],w=m[14],b=m[15],e[12]=x*i+T*o+w*u+b*p,e[13]=x*n+T*a+w*c+b*g,e[14]=x*s+T*h+w*d+b*v,e[15]=x*r+T*l+w*f+b*y,this},multiplyLocal:function(t){var e=[],i=this.val,n=t.val;return e[0]=i[0]*n[0]+i[1]*n[4]+i[2]*n[8]+i[3]*n[12],e[1]=i[0]*n[1]+i[1]*n[5]+i[2]*n[9]+i[3]*n[13],e[2]=i[0]*n[2]+i[1]*n[6]+i[2]*n[10]+i[3]*n[14],e[3]=i[0]*n[3]+i[1]*n[7]+i[2]*n[11]+i[3]*n[15],e[4]=i[4]*n[0]+i[5]*n[4]+i[6]*n[8]+i[7]*n[12],e[5]=i[4]*n[1]+i[5]*n[5]+i[6]*n[9]+i[7]*n[13],e[6]=i[4]*n[2]+i[5]*n[6]+i[6]*n[10]+i[7]*n[14],e[7]=i[4]*n[3]+i[5]*n[7]+i[6]*n[11]+i[7]*n[15],e[8]=i[8]*n[0]+i[9]*n[4]+i[10]*n[8]+i[11]*n[12],e[9]=i[8]*n[1]+i[9]*n[5]+i[10]*n[9]+i[11]*n[13],e[10]=i[8]*n[2]+i[9]*n[6]+i[10]*n[10]+i[11]*n[14],e[11]=i[8]*n[3]+i[9]*n[7]+i[10]*n[11]+i[11]*n[15],e[12]=i[12]*n[0]+i[13]*n[4]+i[14]*n[8]+i[15]*n[12],e[13]=i[12]*n[1]+i[13]*n[5]+i[14]*n[9]+i[15]*n[13],e[14]=i[12]*n[2]+i[13]*n[6]+i[14]*n[10]+i[15]*n[14],e[15]=i[12]*n[3]+i[13]*n[7]+i[14]*n[11]+i[15]*n[15],this.fromArray(e)},translate:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[12]=s[0]*e+s[4]*i+s[8]*n+s[12],s[13]=s[1]*e+s[5]*i+s[9]*n+s[13],s[14]=s[2]*e+s[6]*i+s[10]*n+s[14],s[15]=s[3]*e+s[7]*i+s[11]*n+s[15],this},translateXYZ:function(t,e,i){var n=this.val;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this},scale:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[0]=s[0]*e,s[1]=s[1]*e,s[2]=s[2]*e,s[3]=s[3]*e,s[4]=s[4]*i,s[5]=s[5]*i,s[6]=s[6]*i,s[7]=s[7]*i,s[8]=s[8]*n,s[9]=s[9]*n,s[10]=s[10]*n,s[11]=s[11]*n,this},scaleXYZ:function(t,e,i){var n=this.val;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this},makeRotationAxis:function(t,e){var i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,o=t.y,a=t.z,h=s*r,l=s*o;return this.fromArray([h*r+i,h*o-n*a,h*a+n*o,0,h*o+n*a,l*o+i,l*a-n*r,0,h*a-n*o,l*a+n*r,s*a*a+i,0,0,0,0,1]),this},rotate:function(t,e){var i=this.val,n=e.x,s=e.y,r=e.z,o=Math.sqrt(n*n+s*s+r*r);if(Math.abs(o)<1e-6)return null;n*=o=1/o,s*=o,r*=o;var a=Math.sin(t),h=Math.cos(t),l=1-h,u=i[0],c=i[1],d=i[2],f=i[3],p=i[4],g=i[5],v=i[6],y=i[7],m=i[8],x=i[9],T=i[10],w=i[11],b=n*n*l+h,E=s*n*l+r*a,S=r*n*l-s*a,A=n*s*l-r*a,_=s*s*l+h,C=r*s*l+n*a,M=n*r*l+s*a,P=s*r*l-n*a,O=r*r*l+h;return i[0]=u*b+p*E+m*S,i[1]=c*b+g*E+x*S,i[2]=d*b+v*E+T*S,i[3]=f*b+y*E+w*S,i[4]=u*A+p*_+m*C,i[5]=c*A+g*_+x*C,i[6]=d*A+v*_+T*C,i[7]=f*A+y*_+w*C,i[8]=u*M+p*P+m*O,i[9]=c*M+g*P+x*O,i[10]=d*M+v*P+T*O,i[11]=f*M+y*P+w*O,this},rotateX:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this},rotateY:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this},rotateZ:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this},fromRotationTranslation:function(t,e){var i=this.val,n=t.x,s=t.y,r=t.z,o=t.w,a=n+n,h=s+s,l=r+r,u=n*a,c=n*h,d=n*l,f=s*h,p=s*l,g=r*l,v=o*a,y=o*h,m=o*l;return i[0]=1-(f+g),i[1]=c+m,i[2]=d-y,i[3]=0,i[4]=c-m,i[5]=1-(u+g),i[6]=p+v,i[7]=0,i[8]=d+y,i[9]=p-v,i[10]=1-(u+f),i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this},fromQuat:function(t){var e=this.val,i=t.x,n=t.y,s=t.z,r=t.w,o=i+i,a=n+n,h=s+s,l=i*o,u=i*a,c=i*h,d=n*a,f=n*h,p=s*h,g=r*o,v=r*a,y=r*h;return e[0]=1-(d+p),e[1]=u+y,e[2]=c-v,e[3]=0,e[4]=u-y,e[5]=1-(l+p),e[6]=f+g,e[7]=0,e[8]=c+v,e[9]=f-g,e[10]=1-(l+d),e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},frustum:function(t,e,i,n,s,r){var o=this.val,a=1/(e-t),h=1/(n-i),l=1/(s-r);return o[0]=2*s*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*s*h,o[6]=0,o[7]=0,o[8]=(e+t)*a,o[9]=(n+i)*h,o[10]=(r+s)*l,o[11]=-1,o[12]=0,o[13]=0,o[14]=r*s*2*l,o[15]=0,this},perspective:function(t,e,i,n){var s=this.val,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this},perspectiveLH:function(t,e,i,n){var s=this.val;return s[0]=2*i/t,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/e,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-n/(i-n),s[11]=1,s[12]=0,s[13]=0,s[14]=i*n/(i-n),s[15]=0,this},ortho:function(t,e,i,n,s,r){var o=this.val,a=t-e,h=i-n,l=s-r;return a=0===a?a:1/a,h=0===h?h:1/h,l=0===l?l:1/l,o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this},lookAt:function(t,e,i){var n=this.val,s=t.x,r=t.y,o=t.z,a=i.x,h=i.y,l=i.z,u=e.x,c=e.y,d=e.z;if(Math.abs(s-u)<1e-6&&Math.abs(r-c)<1e-6&&Math.abs(o-d)<1e-6)return this.identity();var f=s-u,p=r-c,g=o-d,v=1/Math.sqrt(f*f+p*p+g*g),y=h*(g*=v)-l*(p*=v),m=l*(f*=v)-a*g,x=a*p-h*f;(v=Math.sqrt(y*y+m*m+x*x))?(y*=v=1/v,m*=v,x*=v):(y=0,m=0,x=0);var T=p*x-g*m,w=g*y-f*x,b=f*m-p*y;return(v=Math.sqrt(T*T+w*w+b*b))?(T*=v=1/v,w*=v,b*=v):(T=0,w=0,b=0),n[0]=y,n[1]=T,n[2]=f,n[3]=0,n[4]=m,n[5]=w,n[6]=p,n[7]=0,n[8]=x,n[9]=b,n[10]=g,n[11]=0,n[12]=-(y*s+m*r+x*o),n[13]=-(T*s+w*r+b*o),n[14]=-(f*s+p*r+g*o),n[15]=1,this},yawPitchRoll:function(t,e,i){this.zero(),s.zero(),r.zero();var n=this.val,o=s.val,a=r.val,h=Math.sin(i),l=Math.cos(i);return n[10]=1,n[15]=1,n[0]=l,n[1]=h,n[4]=-h,n[5]=l,h=Math.sin(e),l=Math.cos(e),o[0]=1,o[15]=1,o[5]=l,o[10]=l,o[9]=-h,o[6]=h,h=Math.sin(t),l=Math.cos(t),a[5]=1,a[15]=1,a[0]=l,a[2]=-h,a[8]=h,a[10]=l,this.multiplyLocal(s),this.multiplyLocal(r),this},setWorldMatrix:function(t,e,i,n,o){return this.yawPitchRoll(t.y,t.x,t.z),s.scaling(i.x,i.y,i.z),r.xyz(e.x,e.y,e.z),this.multiplyLocal(s),this.multiplyLocal(r),void 0!==n&&this.multiplyLocal(n),void 0!==o&&this.multiplyLocal(o),this}}),s=new n,r=new n;t.exports=n},function(t,e,i){var n=i(0),s=i(185),r=i(353),o=new Int8Array([1,2,0]),a=new Float32Array([0,0,0]),h=new s(1,0,0),l=new s(0,1,0),u=new s,c=new r,d=new n({initialize:function(t,e,i,n){"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},rotationTo:function(t,e){var i=t.x*e.x+t.y*e.y+t.z*e.z;return i<-.999999?(u.copy(h).cross(t).length()<1e-6&&u.copy(l).cross(t),u.normalize(),this.setAxisAngle(u,Math.PI)):i>.999999?(this.x=0,this.y=0,this.z=0,this.w=1,this):(u.copy(t).cross(e),this.x=u.x,this.y=u.y,this.z=u.z,this.w=1+i,this.normalize())},setAxes:function(t,e,i){var n=c.val;return n[0]=e.x,n[3]=e.y,n[6]=e.z,n[1]=i.x,n[4]=i.y,n[7]=i.z,n[2]=-t.x,n[5]=-t.y,n[8]=-t.z,this.fromMat3(c).normalize()},identity:function(){return this.x=0,this.y=0,this.z=0,this.w=1,this},setAxisAngle:function(t,e){e*=.5;var i=Math.sin(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=Math.cos(e),this},multiply:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,o=t.y,a=t.z,h=t.w;return this.x=e*h+s*r+i*a-n*o,this.y=i*h+s*o+n*r-e*a,this.z=n*h+s*a+e*o-i*r,this.w=s*h-e*r-i*o-n*a,this},slerp:function(t,e){var i=this.x,n=this.y,s=this.z,r=this.w,o=t.x,a=t.y,h=t.z,l=t.w,u=i*o+n*a+s*h+r*l;u<0&&(u=-u,o=-o,a=-a,h=-h,l=-l);var c=1-e,d=e;if(1-u>1e-6){var f=Math.acos(u),p=Math.sin(f);c=Math.sin((1-e)*f)/p,d=Math.sin(e*f)/p}return this.x=c*i+d*o,this.y=c*n+d*a,this.z=c*s+d*h,this.w=c*r+d*l,this},invert:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n,r=s?1/s:0;return this.x=-t*r,this.y=-e*r,this.z=-i*r,this.w=n*r,this},conjugate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},rotateX:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+s*r,this.y=i*o+n*r,this.z=n*o-i*r,this.w=s*o-e*r,this},rotateY:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o-n*r,this.y=i*o+s*r,this.z=n*o+e*r,this.w=s*o-i*r,this},rotateZ:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+i*r,this.y=i*o-e*r,this.z=n*o+s*r,this.w=s*o-n*r,this},calculateW:function(){var t=this.x,e=this.y,i=this.z;return this.w=-Math.sqrt(1-t*t-e*e-i*i),this},fromMat3:function(t){var e,i=t.val,n=i[0]+i[4]+i[8];if(n>0)e=Math.sqrt(n+1),this.w=.5*e,e=.5/e,this.x=(i[7]-i[5])*e,this.y=(i[2]-i[6])*e,this.z=(i[3]-i[1])*e;else{var s=0;i[4]>i[0]&&(s=1),i[8]>i[3*s+s]&&(s=2);var r=o[s],h=o[r];e=Math.sqrt(i[3*s+s]-i[3*r+r]-i[3*h+h]+1),a[s]=.5*e,e=.5/e,a[r]=(i[3*r+s]+i[3*s+r])*e,a[h]=(i[3*h+s]+i[3*s+h])*e,this.x=a[0],this.y=a[1],this.z=a[2],this.w=(i[3*h+r]-i[3*r+h])*e}return this}});t.exports=d},function(t,e,i){var n=i(357),s=i(28),r=i(32),o=i(180);t.exports=function(t){var e=t.config;if((e.customEnvironment||e.canvas)&&e.renderType===r.AUTO)throw new Error("Must set explicit renderType in custom environment");if(!e.customEnvironment&&!e.canvas&&e.renderType!==r.HEADLESS)if(e.renderType===r.CANVAS||e.renderType!==r.CANVAS&&!o.webGL){if(!o.canvas)throw new Error("Cannot create Canvas or WebGL context, aborting.");e.renderType=r.CANVAS}else e.renderType=r.WEBGL;e.antialias||s.disableSmoothing();var a,h,l=t.scale.baseSize,u=l.width,c=l.height;e.canvas?(t.canvas=e.canvas,t.canvas.width=u,t.canvas.height=c):t.canvas=s.create(t,u,c,e.renderType),e.canvasStyle&&(t.canvas.style=e.canvasStyle),e.antialias||n.setCrisp(t.canvas),e.renderType!==r.HEADLESS&&(a=i(358),h=i(361),e.renderType===r.WEBGL?t.renderer=new h(t):(t.renderer=new a(t),t.context=t.renderer.gameContext))}},function(t,e){t.exports={setCrisp:function(t){return["optimizeSpeed","-moz-crisp-edges","-o-crisp-edges","-webkit-optimize-contrast","optimize-contrast","crisp-edges","pixelated"].forEach(function(e){t.style["image-rendering"]=e}),t.style.msInterpolationMode="nearest-neighbor",t},setBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}}},function(t,e,i){var n=i(359),s=i(55),r=i(0),o=i(32),a=i(360),h=i(104),l=i(35),u=new r({initialize:function(t){this.game=t,this.type=o.CANVAS,this.drawCount=0,this.width=0,this.height=0,this.config={clearBeforeRender:t.config.clearBeforeRender,backgroundColor:t.config.backgroundColor,resolution:t.config.resolution,antialias:t.config.antialias,roundPixels:t.config.roundPixels},this.gameCanvas=t.canvas;var e={alpha:t.config.transparent,desynchronized:t.config.desynchronized};this.gameContext=this.game.config.context?this.game.config.context:this.gameCanvas.getContext("2d",e),this.currentContext=this.gameContext,this.antialias=t.config.antialias,this.blendModes=a(),this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92},this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.init()},init:function(){this.game.scale.on(h.RESIZE,this.onResize,this);var t=this.game.scale.baseSize;this.resize(t.width,t.height)},onResize:function(t,e){e.width===this.width&&e.height===this.height||this.resize(e.width,e.height)},resize:function(t,e){this.width=t,this.height=e},resetTransform:function(){this.currentContext.setTransform(1,0,0,1,0,0)},setBlendMode:function(t){return this.currentContext.globalCompositeOperation=t,this},setContext:function(t){return this.currentContext=t||this.gameContext,this},setAlpha:function(t){return this.currentContext.globalAlpha=t,this},preRender:function(){var t=this.gameContext,e=this.config,i=this.width,n=this.height;t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),e.clearBeforeRender&&t.clearRect(0,0,i,n),e.transparent||(t.fillStyle=e.backgroundColor.rgba,t.fillRect(0,0,i,n)),t.save(),this.drawCount=0},render:function(t,e,i,n){var r=e.list,o=r.length,a=n._cx,h=n._cy,l=n._cw,u=n._ch,c=n.renderToTexture?n.context:t.sys.context;c.save(),this.game.scene.customViewports&&(c.beginPath(),c.rect(a,h,l,u),c.clip()),this.currentContext=c;var d=n.mask;d&&d.preRenderCanvas(this,null,n._maskCamera),n.transparent||(c.fillStyle=n.backgroundColor.rgba,c.fillRect(a,h,l,u)),c.globalAlpha=n.alpha,c.globalCompositeOperation="source-over",this.drawCount+=r.length,n.renderToTexture&&n.emit(s.PRE_RENDER,n),n.matrix.copyToContext(c);for(var f=0;f=0?m=-(m+d):m<0&&(m=Math.abs(m)-d)),t.flipY&&(x>=0?x=-(x+f):x<0&&(x=Math.abs(x)-f))}var w=1,b=1;t.flipX&&(p||(m+=-e.realWidth+2*v),w=-1),t.flipY&&(p||(x+=-e.realHeight+2*y),b=-1),a.applyITRS(t.x,t.y,t.rotation,t.scaleX*w,t.scaleY*b),o.copyFrom(i.matrix),n?(o.multiplyWithOffset(n,-i.scrollX*t.scrollFactorX,-i.scrollY*t.scrollFactorY),a.e=t.x,a.f=t.y,o.multiply(a,h)):(a.e-=i.scrollX*t.scrollFactorX,a.f-=i.scrollY*t.scrollFactorY,o.multiply(a,h)),r.save(),h.setToContext(r),r.globalCompositeOperation=this.blendModes[t.blendMode],r.globalAlpha=s,r.imageSmoothingEnabled=!(!this.antialias||e.source.scaleMode),r.drawImage(e.source.image,u,c,d,f,m,x,d/g,f/g),r.restore()}},destroy:function(){this.gameCanvas=null,this.gameContext=null,this.game=null}});t.exports=u},function(t,e,i){var n=i(28),s=i(36),r=i(1);t.exports=function(t,e){var i=r(e,"callback"),o=r(e,"type","image/png"),a=r(e,"encoder",.92),h=Math.abs(Math.round(r(e,"x",0))),l=Math.abs(Math.round(r(e,"y",0))),u=r(e,"width",t.width),c=r(e,"height",t.height);if(r(e,"getPixel",!1)){var d=t.getContext("2d").getImageData(h,l,1,1).data;i.call(null,new s(d[0],d[1],d[2],d[3]/255))}else if(0!==h||0!==l||u!==t.width||c!==t.height){var f=n.createWebGL(this,u,c);f.getContext("2d").drawImage(t,h,l,u,c,0,0,u,c);var p=new Image;p.onerror=function(){i.call(null),n.remove(f)},p.onload=function(){i.call(null,p),n.remove(f)},p.src=f.toDataURL(o,a)}else{var g=new Image;g.onerror=function(){i.call(null)},g.onload=function(){i.call(null,g)},g.src=t.toDataURL(o,a)}}},function(t,e,i){var n=i(43),s=i(335);t.exports=function(){var t=[],e=s.supportNewBlendModes,i="source-over";return t[n.NORMAL]=i,t[n.ADD]="lighter",t[n.MULTIPLY]=e?"multiply":i,t[n.SCREEN]=e?"screen":i,t[n.OVERLAY]=e?"overlay":i,t[n.DARKEN]=e?"darken":i,t[n.LIGHTEN]=e?"lighten":i,t[n.COLOR_DODGE]=e?"color-dodge":i,t[n.COLOR_BURN]=e?"color-burn":i,t[n.HARD_LIGHT]=e?"hard-light":i,t[n.SOFT_LIGHT]=e?"soft-light":i,t[n.DIFFERENCE]=e?"difference":i,t[n.EXCLUSION]=e?"exclusion":i,t[n.HUE]=e?"hue":i,t[n.SATURATION]=e?"saturation":i,t[n.COLOR]=e?"color":i,t[n.LUMINOSITY]=e?"luminosity":i,t[n.ERASE]="destination-out",t[n.SOURCE_IN]="source-in",t[n.SOURCE_OUT]="source-out",t[n.SOURCE_ATOP]="source-atop",t[n.DESTINATION_OVER]="destination-over",t[n.DESTINATION_IN]="destination-in",t[n.DESTINATION_OUT]="destination-out",t[n.DESTINATION_ATOP]="destination-atop",t[n.LIGHTER]="lighter",t[n.COPY]="copy",t[n.XOR]="xor",t}},function(t,e,i){var n=i(103),s=i(55),r=i(0),o=i(32),a=i(21),h=i(127),l=i(2),u=i(104),c=i(85),d=i(128),f=i(35),p=i(10),g=i(362),v=i(363),y=i(364),m=i(188),x=new r({initialize:function(t){var e=t.config,i={alpha:e.transparent,desynchronized:e.desynchronized,depth:!1,antialias:e.antialiasGL,premultipliedAlpha:e.premultipliedAlpha,stencil:!0,failIfMajorPerformanceCaveat:e.failIfMajorPerformanceCaveat,powerPreference:e.powerPreference};this.config={clearBeforeRender:e.clearBeforeRender,antialias:e.antialias,backgroundColor:e.backgroundColor,contextCreation:i,resolution:e.resolution,roundPixels:e.roundPixels,maxTextures:e.maxTextures,maxTextureSize:e.maxTextureSize,batchSize:e.batchSize,maxLights:e.maxLights,mipmapFilter:e.mipmapFilter},this.game=t,this.type=o.WEBGL,this.width=0,this.height=0,this.canvas=t.canvas,this.blendModes=[],this.nativeTextures=[],this.contextLost=!1,this.pipelines=null,this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92,isFramebuffer:!1,bufferWidth:0,bufferHeight:0},this.currentActiveTextureUnit=0,this.currentTextures=new Array(16),this.currentFramebuffer=null,this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.currentBlendMode=1/0,this.currentScissorEnabled=!1,this.currentScissor=null,this.scissorStack=[],this.contextLostHandler=l,this.contextRestoredHandler=l,this.gl=null,this.supportedExtensions=null,this.extensions={},this.glFormats=[],this.compression={ETC1:!1,PVRTC:!1,S3TC:!1},this.drawingBufferHeight=0,this.blankTexture=null,this.defaultCamera=new n(0,0,0,0),this._tempMatrix1=new f,this._tempMatrix2=new f,this._tempMatrix3=new f,this._tempMatrix4=new f,this.maskCount=0,this.maskStack=[],this.currentMask={mask:null,camera:null},this.currentCameraMask={mask:null,camera:null},this.glFuncMap=null,this.currentType="",this.newType=!1,this.nextTypeMatch=!1,this.mipmapFilter=null,this.init(this.config)},init:function(t){var e,i=this.game,n=this.canvas,s=t.backgroundColor;if(!(e=i.config.context?i.config.context:n.getContext("webgl",t.contextCreation)||n.getContext("experimental-webgl",t.contextCreation))||e.isContextLost())throw this.contextLost=!0,new Error("WebGL unsupported");this.gl=e;var r=this;this.contextLostHandler=function(t){r.contextLost=!0,r.game.events.emit(a.CONTEXT_LOST,r),t.preventDefault()},this.contextRestoredHandler=function(){r.contextLost=!1,r.init(r.config),r.game.events.emit(a.CONTEXT_RESTORED,r)},n.addEventListener("webglcontextlost",this.contextLostHandler,!1),n.addEventListener("webglcontextrestored",this.contextRestoredHandler,!1),i.context=e;for(var h=0;h<=27;h++)this.blendModes.push({func:[e.ONE,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_ADD});this.blendModes[1].func=[e.ONE,e.DST_ALPHA],this.blendModes[2].func=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA],this.blendModes[3].func=[e.ONE,e.ONE_MINUS_SRC_COLOR],this.blendModes[17]={func:[e.ZERO,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_REVERSE_SUBTRACT},this.glFormats[0]=e.BYTE,this.glFormats[1]=e.SHORT,this.glFormats[2]=e.UNSIGNED_BYTE,this.glFormats[3]=e.UNSIGNED_SHORT,this.glFormats[4]=e.FLOAT,this.glFuncMap={mat2:{func:e.uniformMatrix2fv,length:1,matrix:!0},mat3:{func:e.uniformMatrix3fv,length:1,matrix:!0},mat4:{func:e.uniformMatrix4fv,length:1,matrix:!0},"1f":{func:e.uniform1f,length:1},"1fv":{func:e.uniform1fv,length:1},"1i":{func:e.uniform1i,length:1},"1iv":{func:e.uniform1iv,length:1},"2f":{func:e.uniform2f,length:2},"2fv":{func:e.uniform2fv,length:1},"2i":{func:e.uniform2i,length:2},"2iv":{func:e.uniform2iv,length:1},"3f":{func:e.uniform3f,length:3},"3fv":{func:e.uniform3fv,length:1},"3i":{func:e.uniform3i,length:3},"3iv":{func:e.uniform3iv,length:1},"4f":{func:e.uniform4f,length:4},"4fv":{func:e.uniform4fv,length:1},"4i":{func:e.uniform4i,length:4},"4iv":{func:e.uniform4iv,length:1}};var l=e.getSupportedExtensions();t.maxTextures||(t.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)),t.maxTextureSize||(t.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE));var u="WEBGL_compressed_texture_",c="WEBKIT_"+u;this.compression.ETC1=e.getExtension(u+"etc1")||e.getExtension(c+"etc1"),this.compression.PVRTC=e.getExtension(u+"pvrtc")||e.getExtension(c+"pvrtc"),this.compression.S3TC=e.getExtension(u+"s3tc")||e.getExtension(c+"s3tc"),this.supportedExtensions=l,e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.clearColor(s.redGL,s.greenGL,s.blueGL,s.alphaGL),this.mipmapFilter=e[t.mipmapFilter];for(var f=0;f0&&n>0;if(o&&a){var h=o[0],l=o[1],u=o[2],c=o[3];a=h!==t||l!==e||u!==i||c!==n}a&&(this.flush(),r.scissor(t,s-e-n,i,n))},popScissor:function(){var t=this.scissorStack;t.pop();var e=t[t.length-1];e&&this.setScissor(e[0],e[1],e[2],e[3]),this.currentScissor=e},setPipeline:function(t,e){return this.currentPipeline===t&&this.currentPipeline.vertexBuffer===this.currentVertexBuffer&&this.currentPipeline.program===this.currentProgram||(this.flush(),this.currentPipeline=t,this.currentPipeline.bind()),this.currentPipeline.onBind(e),this.currentPipeline},hasActiveStencilMask:function(){var t=this.currentMask.mask,e=this.currentCameraMask.mask;return t&&t.isStencil||e&&e.isStencil},rebindPipeline:function(t){var e=this.gl;e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),this.hasActiveStencilMask()?e.clear(e.DEPTH_BUFFER_BIT):(e.disable(e.STENCIL_TEST),e.clear(e.DEPTH_BUFFER_BIT|e.STENCIL_BUFFER_BIT)),e.viewport(0,0,this.width,this.height),this.setBlendMode(0,!0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.blankTexture.glTexture),this.currentActiveTextureUnit=0,this.currentTextures[0]=this.blankTexture.glTexture,this.currentPipeline=t,this.currentPipeline.bind(),this.currentPipeline.onBind()},clearPipeline:function(){this.flush(),this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.setBlendMode(0,!0)},setBlendMode:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.blendModes[t];return!!(e||t!==o.BlendModes.SKIP_CHECK&&this.currentBlendMode!==t)&&(this.flush(),i.enable(i.BLEND),i.blendEquation(n.equation),n.func.length>2?i.blendFuncSeparate(n.func[0],n.func[1],n.func[2],n.func[3]):i.blendFunc(n.func[0],n.func[1]),this.currentBlendMode=t,!0)},addBlendMode:function(t,e){return this.blendModes.push({func:t,equation:e})-1},updateBlendMode:function(t,e,i){return this.blendModes[t]&&(this.blendModes[t].func=e,i&&(this.blendModes[t].equation=i)),this},removeBlendMode:function(t){return t>17&&this.blendModes[t]&&this.blendModes.splice(t,1),this},setBlankTexture:function(t){void 0===t&&(t=!1),!t&&0===this.currentActiveTextureUnit&&this.currentTextures[0]||this.setTexture2D(this.blankTexture.glTexture,0)},setTexture2D:function(t,e,i){void 0===i&&(i=!0);var n=this.gl;return t!==this.currentTextures[e]&&(i&&this.flush(),this.currentActiveTextureUnit!==e&&(n.activeTexture(n.TEXTURE0+e),this.currentActiveTextureUnit=e),n.bindTexture(n.TEXTURE_2D,t),this.currentTextures[e]=t),this},setFramebuffer:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.width,s=this.height;return t!==this.currentFramebuffer&&(t&&t.renderTexture?(n=t.renderTexture.width,s=t.renderTexture.height):this.flush(),i.bindFramebuffer(i.FRAMEBUFFER,t),i.viewport(0,0,n,s),e&&(t?(this.drawingBufferHeight=s,this.pushScissor(0,0,n,s)):(this.drawingBufferHeight=this.height,this.popScissor())),this.currentFramebuffer=t),this},setProgram:function(t){var e=this.gl;return t!==this.currentProgram&&(this.flush(),e.useProgram(t),this.currentProgram=t),this},setVertexBuffer:function(t){var e=this.gl;return t!==this.currentVertexBuffer&&(this.flush(),e.bindBuffer(e.ARRAY_BUFFER,t),this.currentVertexBuffer=t),this},setIndexBuffer:function(t){var e=this.gl;return t!==this.currentIndexBuffer&&(this.flush(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.currentIndexBuffer=t),this},createTextureFromSource:function(t,e,i,n){var s=this.gl,r=s.NEAREST,a=s.NEAREST,l=s.CLAMP_TO_EDGE;e=t?t.width:e,i=t?t.height:i;var u=h(e,i);return u&&(l=s.REPEAT),n===o.ScaleModes.LINEAR&&this.config.antialias&&(r=u?this.mipmapFilter:s.LINEAR,a=s.LINEAR),t||"number"!=typeof e||"number"!=typeof i?this.createTexture2D(0,r,a,l,l,s.RGBA,t):this.createTexture2D(0,r,a,l,l,s.RGBA,null,e,i)},createTexture2D:function(t,e,i,n,s,r,o,a,l,u,c,d){u=void 0===u||null===u||u,void 0===c&&(c=!1),void 0===d&&(d=!1);var f=this.gl,p=f.createTexture();return this.setTexture2D(p,0),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,e),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,i),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,s),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,n),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u),f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,d),null===o||void 0===o?f.texImage2D(f.TEXTURE_2D,t,r,a,l,0,r,f.UNSIGNED_BYTE,null):(c||(a=o.width,l=o.height),f.texImage2D(f.TEXTURE_2D,t,r,r,f.UNSIGNED_BYTE,o)),h(a,l)&&f.generateMipmap(f.TEXTURE_2D),this.setTexture2D(null,0),p.isAlphaPremultiplied=u,p.isRenderTexture=!1,p.width=a,p.height=l,this.nativeTextures.push(p),p},createFramebuffer:function(t,e,i,n){var s,r=this.gl,o=r.createFramebuffer();if(this.setFramebuffer(o),n){var a=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,a),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,a)}if(i.isRenderTexture=!0,i.isAlphaPremultiplied=!1,r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),(s=r.checkFramebufferStatus(r.FRAMEBUFFER))!==r.FRAMEBUFFER_COMPLETE){throw new Error("Framebuffer incomplete. Framebuffer status: "+{36054:"Incomplete Attachment",36055:"Missing Attachment",36057:"Incomplete Dimensions",36061:"Framebuffer Unsupported"}[s])}return o.renderTexture=i,this.setFramebuffer(null),o},createProgram:function(t,e){var i=this.gl,n=i.createProgram(),s=i.createShader(i.VERTEX_SHADER),r=i.createShader(i.FRAGMENT_SHADER);if(i.shaderSource(s,t),i.shaderSource(r,e),i.compileShader(s),i.compileShader(r),!i.getShaderParameter(s,i.COMPILE_STATUS))throw new Error("Failed to compile Vertex Shader:\n"+i.getShaderInfoLog(s));if(!i.getShaderParameter(r,i.COMPILE_STATUS))throw new Error("Failed to compile Fragment Shader:\n"+i.getShaderInfoLog(r));if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw new Error("Failed to link program:\n"+i.getProgramInfoLog(n));return n},createVertexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setVertexBuffer(n),i.bufferData(i.ARRAY_BUFFER,t,e),this.setVertexBuffer(null),n},createIndexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setIndexBuffer(n),i.bufferData(i.ELEMENT_ARRAY_BUFFER,t,e),this.setIndexBuffer(null),n},deleteTexture:function(t){var e=this.nativeTextures.indexOf(t);return-1!==e&&c(this.nativeTextures,e),this.gl.deleteTexture(t),this.currentTextures[0]!==t||this.game.pendingDestroy||this.setBlankTexture(!0),this},deleteFramebuffer:function(t){return this.gl.deleteFramebuffer(t),this},deleteProgram:function(t){return this.gl.deleteProgram(t),this},deleteBuffer:function(t){return this.gl.deleteBuffer(t),this},preRenderCamera:function(t){var e=t._cx,i=t._cy,n=t._cw,r=t._ch,o=this.pipelines.TextureTintPipeline,a=t.backgroundColor;if(t.renderToTexture){this.flush(),this.pushScissor(e,i,n,-r),this.setFramebuffer(t.framebuffer);var h=this.gl;h.clearColor(0,0,0,0),h.clear(h.COLOR_BUFFER_BIT),o.projOrtho(e,n+e,i,r+i,-1e3,1e3),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n+e,r+i,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL),t.emit(s.PRE_RENDER,t)}else this.pushScissor(e,i,n,r),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n,r,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL)},getCurrentStencilMask:function(){var t=null,e=this.maskStack,i=this.currentCameraMask;return e.length>0?t=e[e.length-1]:i.mask&&i.mask.isStencil&&(t=i),t},postRenderCamera:function(t){var e=this.pipelines.TextureTintPipeline;if(t.flashEffect.postRenderWebGL(e,p.getTintFromFloats),t.fadeEffect.postRenderWebGL(e,p.getTintFromFloats),t.dirty=!1,this.popScissor(),t.renderToTexture){e.flush(),this.setFramebuffer(null),t.emit(s.POST_RENDER,t),e.projOrtho(0,e.width,e.height,0,-1e3,1e3);var i=p.getTintAppendFloatAlpha;(t.pipeline?t.pipeline:e).batchTexture(t,t.glTexture,t.width,t.height,t.x,t.y,t.width,t.height,t.zoom,t.zoom,t.rotation,t.flipX,!t.flipY,1,1,0,0,0,0,t.width,t.height,i(t._tintTL,t._alphaTL),i(t._tintTR,t._alphaTR),i(t._tintBL,t._alphaBL),i(t._tintBR,t._alphaBR),t._isTinted&&t.tintFill,0,0,this.defaultCamera,null),this.setBlankTexture(!0)}t.mask&&(this.currentCameraMask.mask=null,t.mask.postRenderWebGL(this,t._maskCamera))},preRender:function(){if(!this.contextLost){var t=this.gl,e=this.pipelines;if(t.bindFramebuffer(t.FRAMEBUFFER,null),this.config.clearBeforeRender){var i=this.config.backgroundColor;t.clearColor(i.redGL,i.greenGL,i.blueGL,i.alphaGL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT)}for(var n in t.enable(t.SCISSOR_TEST),e)e[n].onPreRender();this.currentScissor=[0,0,this.width,this.height],this.scissorStack=[this.currentScissor],this.game.scene.customViewports&&t.scissor(0,this.drawingBufferHeight-this.height,this.width,this.height),this.currentMask.mask=null,this.currentCameraMask.mask=null,this.maskStack.length=0,this.setPipeline(this.pipelines.TextureTintPipeline)}},render:function(t,e,i,n){if(!this.contextLost){var s=e.list,r=s.length,a=this.pipelines;for(var h in a)a[h].onRender(t,n);if(this.preRenderCamera(n),0===r)return this.setBlendMode(o.BlendModes.NORMAL),void this.postRenderCamera(n);this.currentType="";for(var l=this.currentMask,u=0;u0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},createVideoTexture:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=this.gl,s=n.NEAREST,r=n.NEAREST,o=t.videoWidth,a=t.videoHeight,l=n.CLAMP_TO_EDGE,u=h(o,a);return!e&&u&&(l=n.REPEAT),this.config.antialias&&(s=u?this.mipmapFilter:n.LINEAR,r=n.LINEAR),this.createTexture2D(0,s,r,l,l,n.RGBA,t,o,a,!0,!0,i)},updateVideoTexture:function(t,e,i){void 0===i&&(i=!1);var n=this.gl,s=t.videoWidth,r=t.videoHeight;return s>0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},setTextureFilter:function(t,e){var i=this.gl,n=[i.LINEAR,i.NEAREST][e];return this.setTexture2D(t,0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,n),this.setTexture2D(null,0),this},setFloat1:function(t,e,i){return this.setProgram(t),this.gl.uniform1f(this.gl.getUniformLocation(t,e),i),this},setFloat2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2f(this.gl.getUniformLocation(t,e),i,n),this},setFloat3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3f(this.gl.getUniformLocation(t,e),i,n,s),this},setFloat4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4f(this.gl.getUniformLocation(t,e),i,n,s,r),this},setFloat1v:function(t,e,i){return this.setProgram(t),this.gl.uniform1fv(this.gl.getUniformLocation(t,e),i),this},setFloat2v:function(t,e,i){return this.setProgram(t),this.gl.uniform2fv(this.gl.getUniformLocation(t,e),i),this},setFloat3v:function(t,e,i){return this.setProgram(t),this.gl.uniform3fv(this.gl.getUniformLocation(t,e),i),this},setFloat4v:function(t,e,i){return this.setProgram(t),this.gl.uniform4fv(this.gl.getUniformLocation(t,e),i),this},setInt1:function(t,e,i){return this.setProgram(t),this.gl.uniform1i(this.gl.getUniformLocation(t,e),i),this},setInt2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2i(this.gl.getUniformLocation(t,e),i,n),this},setInt3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3i(this.gl.getUniformLocation(t,e),i,n,s),this},setInt4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4i(this.gl.getUniformLocation(t,e),i,n,s,r),this},setMatrix2:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix2fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix3:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix3fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix4:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix4fv(this.gl.getUniformLocation(t,e),i,n),this},getMaxTextures:function(){return this.config.maxTextures},getMaxTextureSize:function(){return this.config.maxTextureSize},destroy:function(){for(var t=0;t0&&this.flush();var e=this.inverseRotationMatrix;if(t){var i=-t,n=Math.cos(i),s=Math.sin(i);e[1]=s,e[3]=-s,e[0]=e[4]=n}else e[0]=e[4]=1,e[1]=e[3]=0;this.renderer.setMatrix3(this.program,"uInverseRotationMatrix",!1,e),this.currentNormalMapRotation=t}},batchSprite:function(t,e,i){if(this.active){var n=t.texture.dataSource[t.frame.sourceIndex];n&&(this.renderer.setPipeline(this),this.setTexture2D(n.glTexture,1),this.setNormalMapRotation(t.rotation),r.prototype.batchSprite.call(this,t,e,i))}}});a.LIGHT_COUNT=o,t.exports=a},function(t,e){var i={modelMatrixDirty:!1,viewMatrixDirty:!1,projectionMatrixDirty:!1,modelMatrix:null,viewMatrix:null,projectionMatrix:null,mvpInit:function(){return this.modelMatrixDirty=!0,this.viewMatrixDirty=!0,this.projectionMatrixDirty=!0,this.modelMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.viewMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.projectionMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this},mvpUpdate:function(){var t=this.program;return this.modelMatrixDirty&&(this.renderer.setMatrix4(t,"uModelMatrix",!1,this.modelMatrix),this.modelMatrixDirty=!1),this.viewMatrixDirty&&(this.renderer.setMatrix4(t,"uViewMatrix",!1,this.viewMatrix),this.viewMatrixDirty=!1),this.projectionMatrixDirty&&(this.renderer.setMatrix4(t,"uProjectionMatrix",!1,this.projectionMatrix),this.projectionMatrixDirty=!1),this},modelIdentity:function(){var t=this.modelMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.modelMatrixDirty=!0,this},modelScale:function(t,e,i){var n=this.modelMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.modelMatrixDirty=!0,this},modelTranslate:function(t,e,i){var n=this.modelMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.modelMatrixDirty=!0,this},modelRotateX:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.modelMatrixDirty=!0,this},modelRotateY:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.modelMatrixDirty=!0,this},modelRotateZ:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.modelMatrixDirty=!0,this},viewIdentity:function(){var t=this.viewMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.viewMatrixDirty=!0,this},viewScale:function(t,e,i){var n=this.viewMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.viewMatrixDirty=!0,this},viewTranslate:function(t,e,i){var n=this.viewMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.viewMatrixDirty=!0,this},viewRotateX:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.viewMatrixDirty=!0,this},viewRotateY:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.viewMatrixDirty=!0,this},viewRotateZ:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.viewMatrixDirty=!0,this},viewLoad2D:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=0,e[3]=0,e[4]=t[2],e[5]=t[3],e[6]=0,e[7]=0,e[8]=t[4],e[9]=t[5],e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this.viewMatrixDirty=!0,this},viewLoad:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this.viewMatrixDirty=!0,this},projIdentity:function(){var t=this.projectionMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.projectionMatrixDirty=!0,this},projOrtho:function(t,e,i,n,s,r){var o=this.projectionMatrix,a=1/(t-e),h=1/(i-n),l=1/(s-r);return o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this.projectionMatrixDirty=!0,this},projPersp:function(t,e,i,n){var s=this.projectionMatrix,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this.projectionMatrixDirty=!0,this}};t.exports=i},function(t,e,i){var n=i(32);t.exports=function(t){var e=t.config;if(!e.hideBanner){var i="WebGL";e.renderType===n.CANVAS?i="Canvas":e.renderType===n.HEADLESS&&(i="Headless");var s,r=e.audio,o=t.device.audio;if(s=!o.webAudio||r&&r.disableWebAudio?r&&r.noAudio||!o.webAudio&&!o.audioData?"No Audio":"HTML5 Audio":"Web Audio",t.device.browser.ie)window.console&&console.log("Phaser v"+n.VERSION+" / https://phaser.io");else{var a,h="",l=[h];Array.isArray(e.bannerBackgroundColor)?(e.bannerBackgroundColor.forEach(function(t){h=h.concat("%c "),l.push("background: "+t),a=t}),l[l.length-1]="color: "+e.bannerTextColor+"; background: "+a):(h=h.concat("%c "),l.push("color: "+e.bannerTextColor+"; background: "+e.bannerBackgroundColor)),l.push("background: #fff"),e.gameTitle&&(h=h.concat(e.gameTitle),e.gameVersion&&(h=h.concat(" v"+e.gameVersion)),e.hidePhaser||(h=h.concat(" / "))),e.hidePhaser||(h=h.concat("Phaser v"+n.VERSION+"-FB ("+i+" | "+s+")")),h=h.concat(" %c "+e.gameURL),l[0]=h,console.log.apply(console,l)}}}},function(t,e,i){var n=i(0),s=i(5),r=i(2),o=i(368),a=new n({initialize:function(t,e){this.game=t,this.raf=new o,this.started=!1,this.running=!1,this.minFps=s(e,"min",5),this.targetFps=s(e,"target",60),this._min=1e3/this.minFps,this._target=1e3/this.targetFps,this.actualFps=this.targetFps,this.nextFpsUpdate=0,this.framesThisSecond=0,this.callback=r,this.forceSetTimeOut=s(e,"forceSetTimeOut",!1),this.time=0,this.startTime=0,this.lastTime=0,this.frame=0,this.inFocus=!0,this._pauseTime=0,this._coolDown=0,this.delta=0,this.deltaIndex=0,this.deltaHistory=[],this.deltaSmoothingMax=s(e,"deltaHistory",10),this.panicMax=s(e,"panicMax",120),this.rawDelta=0,this.now=0,this.smoothStep=s(e,"smoothStep",!0)},blur:function(){this.inFocus=!1},focus:function(){this.inFocus=!0,this.resetDelta()},pause:function(){this._pauseTime=window.performance.now()},resume:function(){this.resetDelta(),this.startTime+=this.time-this._pauseTime},resetDelta:function(){var t=window.performance.now();this.time=t,this.lastTime=t,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0;for(var e=0;e0||!this.inFocus)&&(this._coolDown--,r=Math.min(r,this._target)),r>this._min&&(r=n[i],r=Math.min(r,this._min)),n[i]=r,this.deltaIndex++,this.deltaIndex>s&&(this.deltaIndex=0),o=0;for(var a=0;athis.nextFpsUpdate&&(this.actualFps=.25*this.framesThisSecond+.75*this.actualFps,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0),this.framesThisSecond++;var h=o/this._target;this.callback(t,o,h),this.lastTime=t,this.frame++},tick:function(){this.step()},sleep:function(){this.running&&(this.raf.stop(),this.running=!1)},wake:function(t){this.running?this.sleep():t&&(this.startTime+=-this.lastTime+(this.lastTime+window.performance.now())),this.raf.start(this.step.bind(this),this.useRAF),this.running=!0,this.step()},getDuration:function(){return Math.round(this.lastTime-this.startTime)/1e3},getDurationMS:function(){return Math.round(this.lastTime-this.startTime)},stop:function(){return this.running=!1,this.started=!1,this.raf.stop(),this},destroy:function(){this.stop(),this.callback=r,this.raf=null,this.game=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(2),r=new n({initialize:function(){this.isRunning=!1,this.callback=s,this.tick=0,this.isSetTimeOut=!1,this.timeOutID=null,this.lastTime=0,this.target=0;var t=this;this.step=function e(){var i=window.performance.now();t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.requestAnimationFrame(e)},this.stepTimeout=function e(){var i=Date.now(),n=Math.min(Math.max(2*t.target+t.tick-i,0),t.target);t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.setTimeout(e,n)}},start:function(t,e,i){this.isRunning||(this.callback=t,this.isSetTimeOut=e,this.target=i,this.isRunning=!0,this.timeOutID=e?window.setTimeout(this.stepTimeout,0):window.requestAnimationFrame(this.step))},stop:function(){this.isRunning=!1,this.isSetTimeOut?clearTimeout(this.timeOutID):window.cancelAnimationFrame(this.timeOutID)},destroy:function(){this.stop(),this.callback=s}});t.exports=r},function(t,e,i){var n=i(21);t.exports=function(t){var e,i=t.events;void 0!==document.hidden?e="visibilitychange":["webkit","moz","ms"].forEach(function(t){void 0!==document[t+"Hidden"]&&(document.hidden=function(){return document[t+"Hidden"]},e=t+"visibilitychange")});e&&document.addEventListener(e,function(t){document.hidden||"pause"===t.type?i.emit(n.HIDDEN):i.emit(n.VISIBLE)},!1),window.onblur=function(){i.emit(n.BLUR)},window.onfocus=function(){i.emit(n.FOCUS)},window.focus&&t.config.autoFocus&&window.focus()}},function(t,e,i){var n=i(371),s=i(28),r=i(5);t.exports=function(t){var e=r(t,"data",[]),i=r(t,"canvas",null),o=r(t,"palette",n),a=r(t,"pixelWidth",1),h=r(t,"pixelHeight",a),l=r(t,"resizeCanvas",!0),u=r(t,"clearCanvas",!0),c=r(t,"preRender",null),d=r(t,"postRender",null),f=Math.floor(Math.abs(e[0].length*a)),p=Math.floor(Math.abs(e.length*h));i||(i=s.create2D(this,f,p),l=!1,u=!1),l&&(i.width=f,i.height=p);var g=i.getContext("2d");u&&g.clearRect(0,0,f,p),c&&c(i,g);for(var v=0;vi;)n-=i;ni.length-2?i.length-1:r+1],c=i[r>i.length-3?i.length-1:r+2];return e.set(n(a,h.x,l.x,u.x,c.x),n(a,h.y,l.y,u.y,c.y))},toJSON:function(){for(var t=[],e=0;e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}},function(t,e,i){var n=i(124);t.exports=function(t){if("complete"!==document.readyState&&"interactive"!==document.readyState){var e=function(){document.removeEventListener("deviceready",e,!0),document.removeEventListener("DOMContentLoaded",e,!0),window.removeEventListener("load",e,!0),t()};document.body?n.cordova?document.addEventListener("deviceready",e,!1):(document.addEventListener("DOMContentLoaded",e,!0),window.addEventListener("load",e,!0)):window.setTimeout(e,20)}else t()}},function(t,e,i){var n=i(190);t.exports=function(t,e){var i=window.screen,s=!!i&&(i.orientation||i.mozOrientation||i.msOrientation);if(s&&"string"==typeof s.type)return s.type;if("string"==typeof s)return s;if(i)return i.height>i.width?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if("number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return n.ORIENTATION.PORTRAIT;if(window.matchMedia("(orientation: landscape)").matches)return n.ORIENTATION.LANDSCAPE}return e>t?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE}},function(t,e){t.exports={NO_CENTER:0,CENTER_BOTH:1,CENTER_HORIZONTALLY:2,CENTER_VERTICALLY:3}},function(t,e){t.exports={LANDSCAPE:"landscape-primary",PORTRAIT:"portrait-primary"}},function(t,e){t.exports={NONE:0,WIDTH_CONTROLS_HEIGHT:1,HEIGHT_CONTROLS_WIDTH:2,FIT:3,ENVELOP:4,RESIZE:5}},function(t,e){t.exports={NO_ZOOM:1,ZOOM_2X:2,ZOOM_4X:4,MAX_ZOOM:-1}},function(t,e){t.exports=function(t){var e;return""!==t&&("string"==typeof t?e=document.getElementById(t):t&&1===t.nodeType&&(e=t)),e||(e=document.body),e}},function(t,e){t.exports=function(t){var e="";try{window.DOMParser?e=(new DOMParser).parseFromString(t,"text/xml"):(e=new ActiveXObject("Microsoft.XMLDOM")).loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null}},function(t,e,i){var n=i(0),s=i(192),r=i(9),o=i(56),a=i(21),h=i(390),l=i(391),u=i(392),c=i(393),d=i(35),f=i(351),p=new n({initialize:function(t,e){this.game=t,this.scaleManager,this.canvas,this.config=e,this.enabled=!0,this.events=new r,this.isOver=!0,this.defaultCursor="",this.keyboard=e.inputKeyboard?new h(this):null,this.mouse=e.inputMouse?new l(this):null,this.touch=e.inputTouch?new c(this):null,this.pointers=[],this.pointersTotal=e.inputActivePointers,e.inputTouch&&1===this.pointersTotal&&(this.pointersTotal=2);for(var i=0;i<=this.pointersTotal;i++){var n=new u(this,i);n.smoothFactor=e.inputSmoothFactor,this.pointers.push(n)}this.mousePointer=e.inputMouse?this.pointers[0]:null,this.activePointer=this.pointers[0],this.globalTopOnly=!0,this.time=0,this._tempPoint={x:0,y:0},this._tempHitTest=[],this._tempMatrix=new d,this._tempMatrix2=new d,this._tempSkip=!1,this.mousePointerContainer=[this.mousePointer],t.events.once(a.BOOT,this.boot,this)},boot:function(){this.canvas=this.game.canvas,this.scaleManager=this.game.scale,this.events.emit(o.MANAGER_BOOT),this.game.events.on(a.PRE_RENDER,this.preRender,this),this.game.events.once(a.DESTROY,this.destroy,this)},setCanvasOver:function(t){this.isOver=!0,this.events.emit(o.GAME_OVER,t)},setCanvasOut:function(t){this.isOver=!1,this.events.emit(o.GAME_OUT,t)},preRender:function(){var t=this.game.loop.now,e=this.game.loop.delta,i=this.game.scene.getScenes(!0,!0);this.time=t,this.events.emit(o.MANAGER_UPDATE);for(var n=0;n10&&(t=10-this.pointersTotal);for(var i=0;i-1&&e.preventDefault()}},this.onKeyUp=function(e){if(!e.defaultPrevented&&t.enabled&&t.manager){t.queue.push(e),t.manager.useQueue||t.manager.events.emit(o.MANAGER_PROCESS);var i=e.altKey||e.ctrlKey||e.shiftKey||e.metaKey;t.preventDefault&&!i&&t.captures.indexOf(e.keyCode)>-1&&e.preventDefault()}};var e=this.target;e&&(e.addEventListener("keydown",this.onKeyDown,!1),e.addEventListener("keyup",this.onKeyUp,!1),this.enabled=!0)},stopListeners:function(){var t=this.target;t.removeEventListener("keydown",this.onKeyDown,!1),t.removeEventListener("keyup",this.onKeyUp,!1),this.enabled=!1},postUpdate:function(){this.queue=[]},addCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},removeCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},clearCaptures:function(){this.captures=[],this.preventDefault=!1},destroy:function(){this.stopListeners(),this.clearCaptures(),this.queue=[],this.manager.game.events.off(r.POST_RENDER,this.postUpdate,this),this.target=null,this.enabled=!1,this.manager=null}});t.exports=l},function(t,e,i){var n=i(0),s=i(180),r=i(56),o=i(0),a=new n({initialize:function(t){this.manager=t,this.capture=!0,this.enabled=!1,this.target,this.locked=!1,this.onMouseMove=o,this.onMouseDown=o,this.onMouseUp=o,this.onMouseDownWindow=o,this.onMouseUpWindow=o,this.onMouseOver=o,this.onMouseOut=o,this.onMouseWheel=o,this.pointerLockChange=o,t.events.once(r.MANAGER_BOOT,this.boot,this)},boot:function(){var t=this.manager.config;this.enabled=t.inputMouse,this.target=t.inputMouseEventTarget,this.capture=t.inputMouseCapture,this.target?"string"==typeof this.target&&(this.target=document.getElementById(this.target)):this.target=this.manager.game.canvas,t.disableContextMenu&&this.disableContextMenu(),this.enabled&&this.target&&this.startListeners()},disableContextMenu:function(){return document.body.addEventListener("contextmenu",function(t){return t.preventDefault(),!1}),this},requestPointerLock:function(){if(s.pointerLock){var t=this.target;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock()}},releasePointerLock:function(){s.pointerLock&&(document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock())},startListeners:function(){var t=this,e=this.manager.canvas,i=window&&window.focus&&this.manager.game.config.autoFocus;this.onMouseMove=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseMove(e),t.capture&&e.preventDefault())},this.onMouseDown=function(n){i&&window.focus(),!n.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseDown(n),t.capture&&n.target===e&&n.preventDefault())},this.onMouseDownWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseDown(i)},this.onMouseUp=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseUp(i),t.capture&&i.target===e&&i.preventDefault())},this.onMouseUpWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseUp(i)},this.onMouseOver=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOver(e)},this.onMouseOut=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOut(e)},this.onMouseWheel=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.onMouseWheel(e)};var n=this.target;if(n){var r={passive:!0},o={passive:!1};n.addEventListener("mousemove",this.onMouseMove,this.capture?o:r),n.addEventListener("mousedown",this.onMouseDown,this.capture?o:r),n.addEventListener("mouseup",this.onMouseUp,this.capture?o:r),n.addEventListener("mouseover",this.onMouseOver,this.capture?o:r),n.addEventListener("mouseout",this.onMouseOut,this.capture?o:r),n.addEventListener("wheel",this.onMouseWheel,this.capture?o:r),window&&this.manager.game.config.inputWindowEvents&&(window.addEventListener("mousedown",this.onMouseDownWindow,o),window.addEventListener("mouseup",this.onMouseUpWindow,o)),s.pointerLock&&(this.pointerLockChange=function(e){var i=t.target;t.locked=document.pointerLockElement===i||document.mozPointerLockElement===i||document.webkitPointerLockElement===i,t.manager.onPointerLockChange(e)},document.addEventListener("pointerlockchange",this.pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this.pointerLockChange,!0)),this.enabled=!0}},stopListeners:function(){var t=this.target;t.removeEventListener("mousemove",this.onMouseMove),t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("mouseup",this.onMouseUp),t.removeEventListener("mouseover",this.onMouseOver),t.removeEventListener("mouseout",this.onMouseOut),window&&(window.removeEventListener("mousedown",this.onMouseDownWindow),window.removeEventListener("mouseup",this.onMouseUpWindow)),s.pointerLock&&(document.removeEventListener("pointerlockchange",this.pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this.pointerLockChange,!0))},destroy:function(){this.stopListeners(),this.target=null,this.enabled=!1,this.manager=null}});t.exports=a},function(t,e,i){var n=i(336),s=i(0),r=i(54),o=i(126),a=i(345),h=i(3),l=new s({initialize:function(t,e){this.manager=t,this.id=e,this.event,this.downElement,this.upElement,this.camera=null,this.button=0,this.buttons=0,this.position=new h,this.prevPosition=new h,this.midPoint=new h(-1,-1),this.velocity=new h,this.angle=0,this.distance=0,this.smoothFactor=0,this.motionFactor=.2,this.worldX=0,this.worldY=0,this.moveTime=0,this.downX=0,this.downY=0,this.downTime=0,this.upX=0,this.upY=0,this.upTime=0,this.primaryDown=!1,this.isDown=!1,this.wasTouch=!1,this.wasCanceled=!1,this.movementX=0,this.movementY=0,this.identifier=0,this.pointerId=null,this.active=0===e,this.locked=!1,this.deltaX=0,this.deltaY=0,this.deltaZ=0},updateWorldPoint:function(t){var e=this.x,i=this.y;1!==t.resolution&&(e+=t._x,i+=t._y);var n=t.getWorldPoint(e,i);return this.worldX=n.x,this.worldY=n.y,this},positionToCamera:function(t,e){return t.getWorldPoint(this.x,this.y,e)},updateMotion:function(){var t=this.position.x,e=this.position.y,i=this.midPoint.x,s=this.midPoint.y;if(t!==i||e!==s){var r=a(this.motionFactor,i,t),h=a(this.motionFactor,s,e);o(r,t,.1)&&(r=t),o(h,e,.1)&&(h=e),this.midPoint.set(r,h);var l=t-r,u=e-h;this.velocity.set(l,u),this.angle=n(r,h,t,e),this.distance=Math.sqrt(l*l+u*u)}},up:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=t.timeStamp),this.isDown=!1,this.wasTouch=!1},down:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=t.timeStamp),this.isDown=!0,this.wasTouch=!1},move:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.locked&&(this.movementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.movementY=t.movementY||t.mozMovementY||t.webkitMovementY||0),this.moveTime=t.timeStamp,this.wasTouch=!1},wheel:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ,this.wasTouch=!1},touchstart:function(t,e){t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.active=!0,this.buttons=1,this.event=e,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=e.timeStamp,this.isDown=!0,this.wasTouch=!0,this.wasCanceled=!1,this.updateMotion()},touchmove:function(t,e){this.event=e,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.moveTime=e.timeStamp,this.wasTouch=!0,this.updateMotion()},touchend:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!1,this.active=!1,this.updateMotion()},touchcancel:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!0,this.active=!1},noButtonDown:function(){return 0===this.buttons},leftButtonDown:function(){return!!(1&this.buttons)},rightButtonDown:function(){return!!(2&this.buttons)},middleButtonDown:function(){return!!(4&this.buttons)},backButtonDown:function(){return!!(8&this.buttons)},forwardButtonDown:function(){return!!(16&this.buttons)},leftButtonReleased:function(){return 0===this.button&&!this.isDown},rightButtonReleased:function(){return 2===this.button&&!this.isDown},middleButtonReleased:function(){return 1===this.button&&!this.isDown},backButtonReleased:function(){return 3===this.button&&!this.isDown},forwardButtonReleased:function(){return 4===this.button&&!this.isDown},getDistance:function(){return this.isDown?r(this.downX,this.downY,this.x,this.y):r(this.downX,this.downY,this.upX,this.upY)},getDistanceX:function(){return this.isDown?Math.abs(this.downX-this.x):Math.abs(this.downX-this.upX)},getDistanceY:function(){return this.isDown?Math.abs(this.downY-this.y):Math.abs(this.downY-this.upY)},getDuration:function(){return this.isDown?this.manager.time-this.downTime:this.upTime-this.downTime},getAngle:function(){return this.isDown?n(this.downX,this.downY,this.x,this.y):n(this.downX,this.downY,this.upX,this.upY)},getInterpolatedPosition:function(t,e){void 0===t&&(t=10),void 0===e&&(e=[]);for(var i=this.prevPosition.x,n=this.prevPosition.y,s=this.position.x,r=this.position.y,o=0;o0&&this.parentSize.height>0&&this.displaySize.setParent(this.parentSize),this.refresh()),t.events.on(a.PRE_STEP,this.step,this),t.events.once(a.DESTROY,this.destroy,this),this.startListeners()},parseConfig:function(t){this.getParent(t),this.getParentBounds();var e=t.width,i=t.height,s=t.scaleMode,r=t.resolution,o=t.zoom,a=t.autoRound;if("string"==typeof e){var h=this.parentSize.width;0===h&&(h=window.innerWidth);var l=parseInt(e,10)/100;e=Math.floor(h*l)}if("string"==typeof i){var c=this.parentSize.height;0===c&&(c=window.innerHeight);var d=parseInt(i,10)/100;i=Math.floor(c*d)}this.resolution=1,this.scaleMode=s,this.autoRound=a,this.autoCenter=t.autoCenter,this.resizeInterval=t.resizeInterval,a&&(e=Math.floor(e),i=Math.floor(i)),this.gameSize.setSize(e,i),o===n.ZOOM.MAX_ZOOM&&(o=this.getMaxZoom()),this.zoom=o,1!==o&&(this._resetZoom=!0),this.baseSize.setSize(e*r,i*r),a&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),t.minWidth>0&&this.displaySize.setMin(t.minWidth*o,t.minHeight*o),t.maxWidth>0&&this.displaySize.setMax(t.maxWidth*o,t.maxHeight*o),this.displaySize.setSize(e,i),this.orientation=u(e,i)},getParent:function(t){var e=t.parent;if(null!==e){if(this.parent=l(e),this.parentIsWindow=this.parent===document.body,t.expandParent&&t.scaleMode!==n.SCALE_MODE.NONE){var i=this.parent.getBoundingClientRect();(this.parentIsWindow||0===i.height)&&(document.documentElement.style.height="100%",document.body.style.height="100%",i=this.parent.getBoundingClientRect(),this.parentIsWindow||0!==i.height||(this.parent.style.overflow="hidden",this.parent.style.width="100%",this.parent.style.height="100%"))}t.fullscreenTarget&&!this.fullscreenTarget&&(this.fullscreenTarget=l(t.fullscreenTarget))}},getParentBounds:function(){if(!this.parent)return!1;var t=this.parentSize,e=this.parent.getBoundingClientRect();this.parentIsWindow&&this.game.device.os.iOS&&(e.height=h(!0));var i=this.resolution,n=e.width*i,s=e.height*i;return(t.width!==n||t.height!==s)&&(t.setSize(n,s),!0)},lockOrientation:function(t){var e=screen.lockOrientation||screen.mozLockOrientation||screen.msLockOrientation;return!!e&&e(t)},setParentSize:function(t,e){return this.parentSize.setSize(t,e),this.refresh()},setGameSize:function(t,e){var i=this.autoRound,n=this.resolution;i&&(t=Math.floor(t),e=Math.floor(e));var s=this.width,r=this.height;return this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),i&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t,e),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height,this.refresh(s,r)},resize:function(t,e){var i=this.zoom,n=this.resolution,s=this.autoRound;s&&(t=Math.floor(t),e=Math.floor(e));var r=this.width,o=this.height;this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),s&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t*i*n,e*i*n),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height;var a=this.canvas.style,h=t*i,l=e*i;return s&&(h=Math.floor(h),l=Math.floor(l)),h===t&&l===e||(a.width=h+"px",a.height=l+"px"),this.refresh(r,o)},setZoom:function(t){return this.zoom=t,this._resetZoom=!0,this.refresh()},setMaxZoom:function(){return this.zoom=this.getMaxZoom(),this._resetZoom=!0,this.refresh()},refresh:function(t,e){void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.updateScale(),this.updateBounds(),this.updateOrientation(),this.displayScale.set(this.baseSize.width/this.canvasBounds.width,this.baseSize.height/this.canvasBounds.height);var i=this.game.domContainer;if(i){this.baseSize.setCSS(i);var n=this.canvas.style,s=i.style;s.transform="scale("+this.displaySize.width/this.baseSize.width+","+this.displaySize.height/this.baseSize.height+")",s.marginLeft=n.marginLeft,s.marginTop=n.marginTop}return this.emit(o.RESIZE,this.gameSize,this.baseSize,this.displaySize,this.resolution,t,e),this},updateOrientation:function(){if(this._checkOrientation){this._checkOrientation=!1;var t=u(this.width,this.height);t!==this.orientation&&(this.orientation=t,this.emit(o.ORIENTATION_CHANGE,t))}},updateScale:function(){var t,e,i=this.canvas.style,s=this.gameSize.width,r=this.gameSize.height,o=this.zoom,a=this.autoRound;this.scaleMode===n.SCALE_MODE.NONE?(this.displaySize.setSize(s*o*1,r*o*1),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this._resetZoom&&(i.width=t+"px",i.height=e+"px",this._resetZoom=!1)):this.scaleMode===n.SCALE_MODE.RESIZE?(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),this.gameSize.setSize(this.displaySize.width,this.displaySize.height),this.baseSize.setSize(1*this.displaySize.width,1*this.displaySize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this.canvas.width=t,this.canvas.height=e):(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),i.width=t+"px",i.height=e+"px"),this.getParentBounds(),this.updateCenter()},getMaxZoom:function(){var t=p(this.parentSize.width,this.gameSize.width,0,!0),e=p(this.parentSize.height,this.gameSize.height,0,!0);return Math.max(Math.min(t,e),1)},updateCenter:function(){var t=this.autoCenter;if(t!==n.CENTER.NO_CENTER){var e=this.canvas,i=e.style,s=e.getBoundingClientRect(),r=s.width,o=s.height,a=Math.floor((this.parentSize.width-r)/2),h=Math.floor((this.parentSize.height-o)/2);t===n.CENTER.CENTER_HORIZONTALLY?h=0:t===n.CENTER.CENTER_VERTICALLY&&(a=0),i.marginLeft=a+"px",i.marginTop=h+"px"}},updateBounds:function(){var t=this.canvasBounds,e=this.canvas.getBoundingClientRect();t.x=e.left+(window.pageXOffset||0)-(document.documentElement.clientLeft||0),t.y=e.top+(window.pageYOffset||0)-(document.documentElement.clientTop||0),t.width=e.width,t.height=e.height},transformX:function(t){return(t-this.canvasBounds.left)*this.displayScale.x},transformY:function(t){return(t-this.canvasBounds.top)*this.displayScale.y},startFullscreen:function(t){void 0===t&&(t={navigationUI:"hide"});var e=this.fullscreen;if(e.available){if(!e.active){var i,n=this.getFullscreenTarget();(i=e.keyboard?n[e.request](Element.ALLOW_KEYBOARD_INPUT):n[e.request](t))?i.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)):e.active?this.fullscreenSuccessHandler():this.fullscreenErrorHandler()}}else this.emit(o.FULLSCREEN_UNSUPPORTED)},fullscreenSuccessHandler:function(){this.getParentBounds(),this.refresh(),this.emit(o.ENTER_FULLSCREEN)},fullscreenErrorHandler:function(t){this.removeFullscreenTarget(),this.emit(o.FULLSCREEN_FAILED,t)},getFullscreenTarget:function(){if(!this.fullscreenTarget){var t=document.createElement("div");t.style.margin="0",t.style.padding="0",t.style.width="100%",t.style.height="100%",this.fullscreenTarget=t,this._createdFullscreenTarget=!0}this._createdFullscreenTarget&&(this.canvas.parentNode.insertBefore(this.fullscreenTarget,this.canvas),this.fullscreenTarget.appendChild(this.canvas));return this.fullscreenTarget},removeFullscreenTarget:function(){if(this._createdFullscreenTarget){var t=this.fullscreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.canvas,t),e.removeChild(t)}}},stopFullscreen:function(){var t=this.fullscreen;if(!t.available)return this.emit(o.FULLSCREEN_UNSUPPORTED),!1;t.active&&document[t.cancel](),this.removeFullscreenTarget(),this.getParentBounds(),this.emit(o.LEAVE_FULLSCREEN),this.refresh()},toggleFullscreen:function(t){this.fullscreen.active?this.stopFullscreen():this.startFullscreen(t)},startListeners:function(){var t=this,e=this.listeners;if(e.orientationChange=function(){t._checkOrientation=!0,t.dirty=!0},e.windowResize=function(){t.dirty=!0},window.addEventListener("orientationchange",e.orientationChange,!1),window.addEventListener("resize",e.windowResize,!1),this.fullscreen.available){e.fullScreenChange=function(e){return t.onFullScreenChange(e)},e.fullScreenError=function(e){return t.onFullScreenError(e)};["webkit","moz",""].forEach(function(t){document.addEventListener(t+"fullscreenchange",e.fullScreenChange,!1),document.addEventListener(t+"fullscreenerror",e.fullScreenError,!1)}),document.addEventListener("MSFullscreenChange",e.fullScreenChange,!1),document.addEventListener("MSFullscreenError",e.fullScreenError,!1)}},onFullScreenChange:function(){document.fullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||this.stopFullscreen()},onFullScreenError:function(){this.removeFullscreenTarget()},step:function(t,e){this.parent&&(this._lastCheck+=e,(this.dirty||this._lastCheck>this.resizeInterval)&&(this.getParentBounds()&&this.refresh(),this.dirty=!1,this._lastCheck=0))},stopListeners:function(){var t=this.listeners;window.removeEventListener("orientationchange",t.orientationChange,!1),window.removeEventListener("resize",t.windowResize,!1);["webkit","moz",""].forEach(function(e){document.removeEventListener(e+"fullscreenchange",t.fullScreenChange,!1),document.removeEventListener(e+"fullscreenerror",t.fullScreenError,!1)}),document.removeEventListener("MSFullscreenChange",t.fullScreenChange,!1),document.removeEventListener("MSFullscreenError",t.fullScreenError,!1)},destroy:function(){this.removeAllListeners(),this.stopListeners(),this.game=null,this.canvas=null,this.canvasBounds=null,this.parent=null,this.fullscreenTarget=null,this.parentSize.destroy(),this.gameSize.destroy(),this.baseSize.destroy(),this.displaySize.destroy()},isFullscreen:{get:function(){return this.fullscreen.active}},width:{get:function(){return this.gameSize.width}},height:{get:function(){return this.gameSize.height}},isPortrait:{get:function(){return this.orientation===n.ORIENTATION.PORTRAIT}},isLandscape:{get:function(){return this.orientation===n.ORIENTATION.LANDSCAPE}},isGamePortrait:{get:function(){return this.height>this.width}},isGameLandscape:{get:function(){return this.width>this.height}}});t.exports=v},function(t,e,i){var n=i(20),s=i(0),r=i(105),o=i(3),a=new s({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=0),void 0===n&&(n=null),this._width=t,this._height=e,this._parent=n,this.aspectMode=i,this.aspectRatio=0===e?1:t/e,this.minWidth=0,this.minHeight=0,this.maxWidth=Number.MAX_VALUE,this.maxHeight=Number.MAX_VALUE,this.snapTo=new o},setAspectMode:function(t){return void 0===t&&(t=0),this.aspectMode=t,this.setSize(this._width,this._height)},setSnap:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.snapTo.set(t,e),this.setSize(this._width,this._height)},setParent:function(t){return this._parent=t,this.setSize(this._width,this._height)},setMin:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.minWidth=n(t,0,this.maxWidth),this.minHeight=n(e,0,this.maxHeight),this.setSize(this._width,this._height)},setMax:function(t,e){return void 0===t&&(t=Number.MAX_VALUE),void 0===e&&(e=t),this.maxWidth=n(t,this.minWidth,Number.MAX_VALUE),this.maxHeight=n(e,this.minHeight,Number.MAX_VALUE),this.setSize(this._width,this._height)},setSize:function(t,e){switch(void 0===t&&(t=0),void 0===e&&(e=t),this.aspectMode){case a.NONE:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height;break;case a.WIDTH_CONTROLS_HEIGHT:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(this._width*(1/this.aspectRatio),!1);break;case a.HEIGHT_CONTROLS_WIDTH:this._height=this.getNewHeight(r(e,this.snapTo.y)),this._width=this.getNewWidth(this._height*this.aspectRatio,!1);break;case a.FIT:this.constrain(t,e,!0);break;case a.ENVELOP:this.constrain(t,e,!1)}return this},setAspectRatio:function(t){return this.aspectRatio=t,this.setSize(this._width,this._height)},resize:function(t,e){return this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height,this},getNewWidth:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minWidth,this.maxWidth),e&&this._parent&&t>this._parent.width&&(t=Math.max(this.minWidth,this._parent.width)),t},getNewHeight:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minHeight,this.maxHeight),e&&this._parent&&t>this._parent.height&&(t=Math.max(this.minHeight,this._parent.height)),t},constrain:function(t,e,i){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=!0),t=this.getNewWidth(t),e=this.getNewHeight(e);var n=this.snapTo,s=0===e?1:t/e;return i&&this.aspectRatio>s||!i&&this.aspectRatio0&&(t=(e=r(e,n.y))*this.aspectRatio)):(i&&this.aspectRatios)&&(t=(e=r(e,n.y))*this.aspectRatio,n.x>0&&(e=(t=r(t,n.x))*(1/this.aspectRatio))),this._width=t,this._height=e,this},fitTo:function(t,e){return this.constrain(t,e,!0)},envelop:function(t,e){return this.constrain(t,e,!1)},setWidth:function(t){return this.setSize(t,this._height)},setHeight:function(t){return this.setSize(this._width,t)},toString:function(){return"[{ Size (width="+this._width+" height="+this._height+" aspectRatio="+this.aspectRatio+" aspectMode="+this.aspectMode+") }]"},setCSS:function(t){t&&t.style&&(t.style.width=this._width+"px",t.style.height=this._height+"px")},copy:function(t){return t.setAspectMode(this.aspectMode),t.aspectRatio=this.aspectRatio,t.setSize(this.width,this.height)},destroy:function(){this._parent=null,this.snapTo=null},width:{get:function(){return this._width},set:function(t){this.setSize(t,this._height)}},height:{get:function(){return this._height},set:function(t){this.setSize(this._width,t)}}});a.NONE=0,a.WIDTH_CONTROLS_HEIGHT=1,a.HEIGHT_CONTROLS_WIDTH=2,a.FIT=3,a.ENVELOP=4,t.exports=a},function(t,e,i){var n=i(0),s=i(132),r=i(18),o=i(21),a=i(5),h=i(87),l=i(2),u=i(398),c=i(193),d=new n({initialize:function(t,e){if(this.game=t,this.keys={},this.scenes=[],this._pending=[],this._start=[],this._queue=[],this._data={},this.isProcessing=!1,this.isBooted=!1,this.customViewports=0,e){Array.isArray(e)||(e=[e]);for(var i=0;i-1&&(delete this.keys[n],this.scenes.splice(i,1),this._start.indexOf(n)>-1&&(i=this._start.indexOf(n),this._start.splice(i,1)),e.sys.destroy())}return this},bootScene:function(t){var e,i=t.sys,n=i.settings;t.init&&(t.init.call(t,n.data),n.status=s.INIT,n.isTransition&&i.events.emit(r.TRANSITION_INIT,n.transitionFrom,n.transitionDuration)),i.load&&(e=i.load).reset(),e&&t.preload?(t.preload.call(t),0===e.list.size?this.create(t):(n.status=s.LOADING,e.once(h.COMPLETE,this.loadComplete,this),e.start())):this.create(t)},loadComplete:function(t){var e=t.scene;this.game.sound&&this.game.sound.onBlurPausedSounds&&this.game.sound.unlock(),this.create(e)},payloadComplete:function(t){this.bootScene(t.scene)},update:function(t,e){this.processQueue(),this.isProcessing=!0;for(var i=this.scenes.length-1;i>=0;i--){var n=this.scenes[i].sys;n.settings.status>s.START&&n.settings.status<=s.RUNNING&&n.step(t,e)}},render:function(t){for(var e=0;e=s.LOADING&&i.settings.status0){var i=this.getScene(t);this.scenes.splice(e,1),this.scenes.unshift(i)}}return this},moveDown:function(t){if(this.isProcessing)this._queue.push({op:"moveDown",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e>0){var i=e-1,n=this.getScene(t),s=this.getAt(i);this.scenes[e]=s,this.scenes[i]=n}}return this},moveUp:function(t){if(this.isProcessing)this._queue.push({op:"moveUp",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e=r.x&&t=r.y&&e=r.x&&t=r.y&&e-1){var o=this.context.getImageData(t,e,1,1);o.data[0]=i,o.data[1]=n,o.data[2]=s,o.data[3]=r,this.context.putImageData(o,t,e)}return this},putData:function(t,e,i,n,s,r,o){return void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=t.width),void 0===o&&(o=t.height),this.context.putImageData(t,e,i,n,s,r,o),this},getData:function(t,e,i,n){return t=s(Math.floor(t),0,this.width-1),e=s(Math.floor(e),0,this.height-1),i=s(i,1,this.width-t),n=s(n,1,this.height-e),this.context.getImageData(t,e,i,n)},getPixel:function(t,e,i){i||(i=new r);var n=this.getIndex(t,e);if(n>-1){var s=this.data,o=s[n+0],a=s[n+1],h=s[n+2],l=s[n+3];i.setTo(o,a,h,l)}return i},getPixels:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=i),t=Math.abs(Math.round(t)),e=Math.abs(Math.round(e));for(var o=s(t,0,this.width),a=s(t+i,0,this.width),h=s(e,0,this.height),l=s(e+n,0,this.height),u=new r,c=[],d=h;d0)&&(!!n.prototype.pause.call(this)&&(this.currentConfig.seek=this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0),this.stopAndReleaseAudioTag(),this.emit(r.PAUSE,this),!0)))},resume:function(){return!this.manager.isLocked(this,"resume")&&(!(this.startTime>0)&&(!!n.prototype.resume.call(this)&&(!!this.pickAndPlayAudioTag()&&(this.emit(r.RESUME,this),!0))))},stop:function(){return!this.manager.isLocked(this,"stop")&&(!!n.prototype.stop.call(this)&&(this.stopAndReleaseAudioTag(),this.emit(r.STOP,this),!0))},pickAndPlayAudioTag:function(){if(!this.pickAudioTag())return this.reset(),!1;var t=this.currentConfig.seek,e=this.currentConfig.delay,i=(this.currentMarker?this.currentMarker.start:0)+t;return this.previousTime=i,this.audio.currentTime=i,this.applyConfig(),0===e?(this.startTime=0,this.audio.paused&&this.playCatchPromise()):(this.startTime=window.performance.now()+1e3*e,this.audio.paused||this.audio.pause()),this.resetConfig(),!0},pickAudioTag:function(){if(this.audio)return!0;for(var t=0;t0)this.startTime=n-this.manager.loopEndOffset?(this.audio.currentTime=i+Math.max(0,s-n),s=this.audio.currentTime):s=n)return this.reset(),this.stopAndReleaseAudioTag(),void this.emit(r.COMPLETE,this);this.previousTime=s}},destroy:function(){n.prototype.destroy.call(this),this.tags=null,this.audio&&this.stopAndReleaseAudioTag()},updateMute:function(){this.audio&&(this.audio.muted=this.currentConfig.mute||this.manager.mute)},updateVolume:function(){this.audio&&(this.audio.volume=this.currentConfig.volume*this.manager.volume)},calculateRate:function(){n.prototype.calculateRate.call(this),this.audio&&(this.audio.playbackRate=this.totalRate)},mute:{get:function(){return this.currentConfig.mute},set:function(t){this.currentConfig.mute=t,this.manager.isLocked(this,"mute",t)||(this.updateMute(),this.emit(r.MUTE,this,t))}},setMute:function(t){return this.mute=t,this},volume:{get:function(){return this.currentConfig.volume},set:function(t){this.currentConfig.volume=t,this.manager.isLocked(this,"volume",t)||(this.updateVolume(),this.emit(r.VOLUME,this,t))}},setVolume:function(t){return this.volume=t,this},rate:{get:function(){return this.currentConfig.rate},set:function(t){this.currentConfig.rate=t,this.manager.isLocked(this,r.RATE,t)||(this.calculateRate(),this.emit(r.RATE,this,t))}},setRate:function(t){return this.rate=t,this},detune:{get:function(){return this.currentConfig.detune},set:function(t){this.currentConfig.detune=t,this.manager.isLocked(this,r.DETUNE,t)||(this.calculateRate(),this.emit(r.DETUNE,this,t))}},setDetune:function(t){return this.detune=t,this},seek:{get:function(){return this.isPlaying?this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0):this.isPaused?this.currentConfig.seek:0},set:function(t){this.manager.isLocked(this,"seek",t)||this.startTime>0||(this.isPlaying||this.isPaused)&&(t=Math.min(Math.max(0,t),this.duration),this.isPlaying?(this.previousTime=t,this.audio.currentTime=t):this.isPaused&&(this.currentConfig.seek=t),this.emit(r.SEEK,this,t))}},setSeek:function(t){return this.seek=t,this},loop:{get:function(){return this.currentConfig.loop},set:function(t){this.currentConfig.loop=t,this.manager.isLocked(this,"loop",t)||(this.audio&&(this.audio.loop=t),this.emit(r.LOOP,this,t))}},setLoop:function(t){return this.loop=t,this}});t.exports=o},function(t,e,i){var n=i(133),s=i(0),r=i(9),o=i(408),a=i(2),h=new s({Extends:r,initialize:function(t){r.call(this),this.game=t,this.sounds=[],this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.pauseOnBlur=!0,this.locked=!1},add:function(t,e){var i=new o(this,t,e);return this.sounds.push(i),i},addAudioSprite:function(t,e){var i=this.add(t,e);return i.spritemap={},i},play:function(t,e){return!1},playAudioSprite:function(t,e,i){return!1},remove:function(t){return n.prototype.remove.call(this,t)},removeByKey:function(t){return n.prototype.removeByKey.call(this,t)},pauseAll:a,resumeAll:a,stopAll:a,update:a,setRate:a,setDetune:a,setMute:a,setVolume:a,forEachActiveSound:function(t,e){n.prototype.forEachActiveSound.call(this,t,e)},destroy:function(){n.prototype.destroy.call(this)}});t.exports=h},function(t,e,i){var n=i(134),s=i(0),r=i(9),o=i(17),a=new s({Extends:r,initialize:function(t,e,i){void 0===i&&(i={}),r.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=0,this.totalDuration=0,this.config=o({mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},i),this.currentConfig=this.config,this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.seek=0,this.loop=!1,this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!1},updateMarker:function(t){return!1},removeMarker:function(t){return null},play:function(t,e){return!1},pause:function(){return!1},resume:function(){return!1},stop:function(){return!1},destroy:function(){this.manager.remove(this),n.prototype.destroy.call(this)}});t.exports=a},function(t,e,i){var n=i(410),s=i(133),r=i(0),o=i(64),a=i(411),h=new r({Extends:s,initialize:function(t){this.context=this.createAudioContext(t),this.masterMuteNode=this.context.createGain(),this.masterVolumeNode=this.context.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(this.context.destination),this.destination=this.masterMuteNode,this.locked="suspended"===this.context.state&&("ontouchstart"in window||"onclick"in window),s.call(this,t),this.locked&&this.unlock()},createAudioContext:function(t){var e=t.config.audio;return e&&e.context?(e.context.resume(),e.context):new AudioContext},setAudioContext:function(t){return this.context&&this.context.close(),this.masterMuteNode&&this.masterMuteNode.disconnect(),this.masterVolumeNode&&this.masterVolumeNode.disconnect(),this.context=t,this.masterMuteNode=t.createGain(),this.masterVolumeNode=t.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(t.destination),this.destination=this.masterMuteNode,this},add:function(t,e){var i=new a(this,t,e);return this.sounds.push(i),i},decodeAudio:function(t,e){var i;i=Array.isArray(t)?t:[{key:t,data:e}];for(var s=this.game.cache.audio,r=i.length,a=0;a>4,u[h++]=(15&i)<<4|s>>2,u[h++]=(3&s)<<6|63&r;return l}},function(t,e,i){var n=i(134),s=i(0),r=i(64),o=new s({Extends:n,initialize:function(t,e,i){if(void 0===i&&(i={}),this.audioBuffer=t.game.cache.audio.get(e),!this.audioBuffer)throw new Error('There is no audio asset with key "'+e+'" in the audio cache');this.source=null,this.loopSource=null,this.muteNode=t.context.createGain(),this.volumeNode=t.context.createGain(),this.playTime=0,this.startTime=0,this.loopTime=0,this.rateUpdates=[],this.hasEnded=!1,this.hasLooped=!1,this.muteNode.connect(this.volumeNode),this.volumeNode.connect(t.destination),this.duration=this.audioBuffer.duration,this.totalDuration=this.audioBuffer.duration,n.call(this,t,e,i)},play:function(t,e){return!!n.prototype.play.call(this,t,e)&&(this.stopAndRemoveBufferSource(),this.createAndStartBufferSource(),this.emit(r.PLAY,this),!0)},pause:function(){return!(this.manager.context.currentTime1e3)return console.warn("Switch Game data too long. Max 1000 chars."),this;var i=this;return FBInstant.switchGameAsync(t,e).then(function(){i.emit("switchgame",t)}).catch(function(t){i.emit("switchgamefail",t)}),this},createShortcut:function(){var t=this;return FBInstant.canCreateShortcutAsync().then(function(e){e&&FBInstant.createShortcutAsync().then(function(){t.emit("shortcutcreated")}).catch(function(e){t.emit("shortcutfailed",e)})}),this},quit:function(){FBInstant.quit()},log:function(t,e,i){return this.checkAPI("logEvent")?(void 0===i&&(i={}),t.length>=2&&t.length<=40&&FBInstant.logEvent(t,parseFloat(e),i),this):this},preloadAds:function(t){if(!this.checkAPI("getInterstitialAdAsync"))return this;var e;Array.isArray(t)||(t=[t]);var i=this,s=0;for(e=0;e=3)return console.warn("Too many AdInstances. Show an ad before loading more"),this;for(e=0;e=3)return console.warn("Too many AdInstances. Show an ad before loading more"),this;for(e=0;e-1;r--)n[s][r]=t[r][s]}return n}},function(t,e){function i(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function n(t,e){return te?1:0}var s=function(t,e,r,o,a){for(void 0===r&&(r=0),void 0===o&&(o=t.length-1),void 0===a&&(a=n);o>r;){if(o-r>600){var h=o-r+1,l=e-r+1,u=Math.log(h),c=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*c*(h-c)/h)*(l-h/2<0?-1:1),f=Math.max(r,Math.floor(e-l*c/h+d)),p=Math.min(o,Math.floor(e+(h-l)*c/h+d));s(t,e,f,p,a)}var g=t[e],v=r,y=o;for(i(t,r,e),a(t[o],g)>0&&i(t,r,o);v0;)y--}0===a(t[r],g)?i(t,r,y):i(t,++y,o),y<=e&&(r=y+1),e<=y&&(o=y-1)}};t.exports=s},function(t,e,i){var n=i(5),s=i(122),r=function(t,e,i){for(var n=[],s=0;s0?s.delayedPlay(d,r,o):s.load(r)}return t}},function(t,e,i){var n=i(11);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.right,e.right)-s,a=Math.max(t.bottom,e.bottom)-r;return i.setTo(s,r,o,a)}},function(t,e,i){var n=i(0),s=i(12),r=i(987),o=i(14),a=i(7),h=i(191),l=i(18),u=i(352),c=new n({Extends:o,Mixins:[s.AlphaSingle,s.BlendMode,s.Depth,s.Origin,s.ScrollFactor,s.Transform,s.Visible,r],initialize:function(t,e,i,n,s,r){o.call(this,t,"DOMElement"),this.parent=t.sys.game.domContainer,this.cache=t.sys.cache.html,this.node,this.transformOnly=!1,this.skewX=0,this.skewY=0,this.rotate3d=new u,this.rotate3dAngle="deg",this.width=0,this.height=0,this.displayWidth=0,this.displayHeight=0,this.handler=this.dispatchNativeEvent.bind(this),this.setPosition(e,i),"string"==typeof n?"#"===n[0]?this.setElement(n.substr(1),s,r):this.createElement(n,s,r):n&&this.setElement(n,s,r),t.sys.events.on(l.SLEEP,this.handleSceneEvent,this),t.sys.events.on(l.WAKE,this.handleSceneEvent,this)},handleSceneEvent:function(t){var e=this.node,i=e.style;e&&(i.display=t.settings.visible?"block":"none")},setSkew:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.skewX=t,this.skewY=e,this},setPerspective:function(t){return this.parent.style.perspective=t+"px",this},perspective:{get:function(){return parseFloat(this.parent.style.perspective)},set:function(t){this.parent.style.perspective=t+"px"}},addListener:function(t){if(this.node){t=t.split(" ");for(var e=0;e>>16,m=(65280&p)>>>8,x=255&p,c.strokeStyle="rgba("+y+","+m+","+x+","+d+")",c.lineWidth=v,T+=3;break;case n.FILL_STYLE:g=l[T+1],f=l[T+2],y=(16711680&g)>>>16,m=(65280&g)>>>8,x=255&g,c.fillStyle="rgba("+y+","+m+","+x+","+f+")",T+=2;break;case n.BEGIN_PATH:c.beginPath();break;case n.CLOSE_PATH:c.closePath();break;case n.FILL_PATH:h||c.fill();break;case n.STROKE_PATH:h||c.stroke();break;case n.FILL_RECT:h?c.rect(l[T+1],l[T+2],l[T+3],l[T+4]):c.fillRect(l[T+1],l[T+2],l[T+3],l[T+4]),T+=4;break;case n.FILL_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.fill(),T+=6;break;case n.STROKE_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.stroke(),T+=6;break;case n.LINE_TO:c.lineTo(l[T+1],l[T+2]),T+=2;break;case n.MOVE_TO:c.moveTo(l[T+1],l[T+2]),T+=2;break;case n.LINE_FX_TO:c.lineTo(l[T+1],l[T+2]),T+=5;break;case n.MOVE_FX_TO:c.moveTo(l[T+1],l[T+2]),T+=5;break;case n.SAVE:c.save();break;case n.RESTORE:c.restore();break;case n.TRANSLATE:c.translate(l[T+1],l[T+2]),T+=2;break;case n.SCALE:c.scale(l[T+1],l[T+2]),T+=2;break;case n.ROTATE:c.rotate(l[T+1]),T+=1;break;case n.GRADIENT_FILL_STYLE:T+=5;break;case n.GRADIENT_LINE_STYLE:T+=6;break;case n.SET_TEXTURE:T+=2}c.restore()}}},function(t,e,i){var n=i(0),s=i(1),r=new n({initialize:function(t,e,i,n,r){if("object"==typeof t){var o=t;t=s(o,"x",0),e=s(o,"y",0),i=s(o,"power",0),n=s(o,"epsilon",100),r=s(o,"gravity",50)}else void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=100),void 0===r&&(r=50);this.x=t,this.y=e,this.active=!0,this._gravity=r,this._power=0,this._epsilon=0,this.power=i,this.epsilon=n},update:function(t,e){var i=this.x-t.x,n=this.y-t.y,s=i*i+n*n;if(0!==s){var r=Math.sqrt(s);s0},resetPosition:function(){this.x=0,this.y=0},fire:function(t,e){var i=this.emitter;this.frame=i.getFrame(),i.emitZone&&i.emitZone.getPoint(this),void 0===t?(i.follow&&(this.x+=i.follow.x+i.followOffset.x),this.x+=i.x.onEmit(this,"x")):this.x+=t,void 0===e?(i.follow&&(this.y+=i.follow.y+i.followOffset.y),this.y+=i.y.onEmit(this,"y")):this.y+=e,this.life=i.lifespan.onEmit(this,"lifespan"),this.lifeCurrent=this.life,this.lifeT=0;var n=i.speedX.onEmit(this,"speedX"),o=i.speedY?i.speedY.onEmit(this,"speedY"):n;if(i.radial){var a=s(i.angle.onEmit(this,"angle"));this.velocityX=Math.cos(a)*Math.abs(n),this.velocityY=Math.sin(a)*Math.abs(o)}else if(i.moveTo){var h=i.moveToX.onEmit(this,"moveToX"),l=i.moveToY?i.moveToY.onEmit(this,"moveToY"):h,u=Math.atan2(l-this.y,h-this.x),c=r(this.x,this.y,h,l)/(this.life/1e3);this.velocityX=Math.cos(u)*c,this.velocityY=Math.sin(u)*c}else this.velocityX=n,this.velocityY=o;i.acceleration&&(this.accelerationX=i.accelerationX.onEmit(this,"accelerationX"),this.accelerationY=i.accelerationY.onEmit(this,"accelerationY")),this.maxVelocityX=i.maxVelocityX.onEmit(this,"maxVelocityX"),this.maxVelocityY=i.maxVelocityY.onEmit(this,"maxVelocityY"),this.delayCurrent=i.delay.onEmit(this,"delay"),this.scaleX=i.scaleX.onEmit(this,"scaleX"),this.scaleY=i.scaleY?i.scaleY.onEmit(this,"scaleY"):this.scaleX,this.angle=i.rotate.onEmit(this,"rotate"),this.rotation=s(this.angle),this.bounce=i.bounce.onEmit(this,"bounce"),this.alpha=i.alpha.onEmit(this,"alpha"),this.tint=i.tint.onEmit(this,"tint")},computeVelocity:function(t,e,i,n){var s=this.velocityX,r=this.velocityY,o=this.accelerationX,a=this.accelerationY,h=this.maxVelocityX,l=this.maxVelocityY;s+=t.gravityX*i,r+=t.gravityY*i,o&&(s+=o*i),a&&(r+=a*i),s>h?s=h:s<-h&&(s=-h),r>l?r=l:r<-l&&(r=-l),this.velocityX=s,this.velocityY=r;for(var u=0;ue.right&&t.collideRight&&(this.x=e.right,this.velocityX*=i),this.ye.bottom&&t.collideBottom&&(this.y=e.bottom,this.velocityY*=i)},update:function(t,e,i){if(this.delayCurrent>0)return this.delayCurrent-=t,!1;var n=this.emitter,r=1-this.lifeCurrent/this.life;return this.lifeT=r,this.computeVelocity(n,t,e,i),this.x+=this.velocityX*e,this.y+=this.velocityY*e,n.bounds&&this.checkBounds(n),n.deathZone&&n.deathZone.willKill(this)?(this.lifeCurrent=0,!0):(this.scaleX=n.scaleX.onUpdate(this,"scaleX",r,this.scaleX),n.scaleY?this.scaleY=n.scaleY.onUpdate(this,"scaleY",r,this.scaleY):this.scaleY=this.scaleX,this.angle=n.rotate.onUpdate(this,"rotate",r,this.angle),this.rotation=s(this.angle),this.alpha=n.alpha.onUpdate(this,"alpha",r,this.alpha),this.tint=n.tint.onUpdate(this,"tint",r,this.tint),this.lifeCurrent-=t,this.lifeCurrent<=0)}});t.exports=o},function(t,e,i){var n=i(43),s=i(0),r=i(12),o=i(428),a=i(429),h=i(1004),l=i(1),u=i(198),c=i(430),d=i(91),f=i(426),p=i(431),g=i(11),v=i(137),y=i(3),m=i(63),x=new s({Mixins:[r.BlendMode,r.Mask,r.ScrollFactor,r.Visible],initialize:function(t,e){this.manager=t,this.texture=t.texture,this.frames=[t.defaultFrame],this.defaultFrame=t.defaultFrame,this.configFastMap=["active","blendMode","collideBottom","collideLeft","collideRight","collideTop","deathCallback","deathCallbackScope","emitCallback","emitCallbackScope","follow","frequency","gravityX","gravityY","maxParticles","name","on","particleBringToTop","particleClass","radial","timeScale","trackVisible","visible"],this.configOpMap=["accelerationX","accelerationY","angle","alpha","bounce","delay","lifespan","maxVelocityX","maxVelocityY","moveToX","moveToY","quantity","rotate","scaleX","scaleY","speedX","speedY","tint","x","y"],this.name="",this.particleClass=f,this.x=new h(e,"x",0,!0),this.y=new h(e,"y",0,!0),this.radial=!0,this.gravityX=0,this.gravityY=0,this.acceleration=!1,this.accelerationX=new h(e,"accelerationX",0,!0),this.accelerationY=new h(e,"accelerationY",0,!0),this.maxVelocityX=new h(e,"maxVelocityX",1e4,!0),this.maxVelocityY=new h(e,"maxVelocityY",1e4,!0),this.speedX=new h(e,"speedX",0,!0),this.speedY=new h(e,"speedY",0,!0),this.moveTo=!1,this.moveToX=new h(e,"moveToX",0,!0),this.moveToY=new h(e,"moveToY",0,!0),this.bounce=new h(e,"bounce",0,!0),this.scaleX=new h(e,"scaleX",1),this.scaleY=new h(e,"scaleY",1),this.tint=new h(e,"tint",4294967295),this.alpha=new h(e,"alpha",1),this.lifespan=new h(e,"lifespan",1e3,!0),this.angle=new h(e,"angle",{min:0,max:360},!0),this.rotate=new h(e,"rotate",0),this.emitCallback=null,this.emitCallbackScope=null,this.deathCallback=null,this.deathCallbackScope=null,this.maxParticles=0,this.quantity=new h(e,"quantity",1,!0),this.delay=new h(e,"delay",0,!0),this.frequency=0,this.on=!0,this.particleBringToTop=!0,this.timeScale=1,this.emitZone=null,this.deathZone=null,this.bounds=null,this.collideLeft=!0,this.collideRight=!0,this.collideTop=!0,this.collideBottom=!0,this.active=!0,this.visible=!0,this.blendMode=n.NORMAL,this.follow=null,this.followOffset=new y,this.trackVisible=!1,this.currentFrame=0,this.randomFrame=!0,this.frameQuantity=1,this.dead=[],this.alive=[],this._counter=0,this._frameCounter=0,e&&this.fromJSON(e)},fromJSON:function(t){if(!t)return this;var e=0,i="";for(e=0;e0&&this.getParticleCount()===this.maxParticles},onParticleEmit:function(t,e){return void 0===t?(this.emitCallback=null,this.emitCallbackScope=null):"function"==typeof t&&(this.emitCallback=t,e&&(this.emitCallbackScope=e)),this},onParticleDeath:function(t,e){return void 0===t?(this.deathCallback=null,this.deathCallbackScope=null):"function"==typeof t&&(this.deathCallback=t,e&&(this.deathCallbackScope=e)),this},killAll:function(){for(var t=this.dead,e=this.alive;e.length>0;)t.push(e.pop());return this},forEachAlive:function(t,e){for(var i=this.alive,n=i.length,s=0;s0){var u=this.deathCallback,c=this.deathCallbackScope;for(o=h-1;o>=0;o--){var d=a[o];s.splice(d.index,1),r.push(d.particle),u&&u.call(c,d.particle),d.particle.resetPosition()}}this.on&&(0===this.frequency?this.emitParticle():this.frequency>0&&(this._counter-=e,this._counter<=0&&(this.emitParticle(),this._counter=this.frequency-Math.abs(this._counter))))},depthSortCallback:function(t,e){return t.y-e.y}});t.exports=x},function(t,e,i){var n=new(i(0))({initialize:function(t,e){this.source=t,this.killOnEnter=e},willKill:function(t){var e=this.source.contains(t.x,t.y);return e&&this.killOnEnter||!e&&!this.killOnEnter}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s){void 0===n&&(n=!1),void 0===s&&(s=!0),this.source=t,this.points=[],this.quantity=e,this.stepRate=i,this.yoyo=n,this.counter=-1,this.seamless=s,this._length=0,this._direction=0,this.updateSource()},updateSource:function(){if(this.points=this.source.getPoints(this.quantity,this.stepRate),this.seamless){var t=this.points[0],e=this.points[this.points.length-1];t.x===e.x&&t.y===e.y&&this.points.pop()}var i=this._length;return this._length=this.points.length,this._lengththis._length&&(this.counter=this._length-1),this},changeSource:function(t){return this.source=t,this.updateSource()},getPoint:function(t){0===this._direction?(this.counter++,this.counter>=this._length&&(this.yoyo?(this._direction=1,this.counter=this._length-1):this.counter=0)):(this.counter--,-1===this.counter&&(this.yoyo?(this._direction=0,this.counter=0):this.counter=this._length-1));var e=this.points[this.counter];e&&(t.x=e.x,t.y=e.y)}});t.exports=n},function(t,e){t.exports=function(t,e){for(var i=0;i0&&(s=-h.PI2+s%h.PI2):s>h.PI2?s=h.PI2:s<0&&(s=h.PI2+s%h.PI2);for(var u,c=[a+Math.cos(n)*i,l+Math.sin(n)*i];e<1;)u=s*e+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),e+=t;return u=s+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),c.push(a+Math.cos(n)*i,l+Math.sin(n)*i),this.pathIndexes=o(c),this.pathData=c,this}});t.exports=u},function(t,e,i){var n=i(0),s=i(1030),r=i(72),o=i(11),a=i(33),h=new n({Extends:a,Mixins:[s],initialize:function(t,e,i,n,s,r){void 0===e&&(e=0),void 0===i&&(i=0),a.call(this,t,"Curve",n),this._smoothness=32,this._curveBounds=new o,this.closePath=!1,this.setPosition(e,i),void 0!==s&&this.setFillStyle(s,r),this.updateData()},smoothness:{get:function(){return this._smoothness},set:function(t){this._smoothness=t,this.updateData()}},setSmoothness:function(t){return this._smoothness=t,this.updateData()},updateData:function(){var t=this._curveBounds,e=this._smoothness;this.geom.getBounds(t,e),this.setSize(t.width,t.height),this.updateDisplayOrigin();for(var i=[],n=this.geom.getPoints(e),s=0;sc+v)){var y=g.getPoint((u-c)/v);o.push(y);break}c+=v}return o}},function(t,e,i){var n=i(62),s=i(61);t.exports=function(t){for(var e=t.points,i=0,r=0;r0&&r.push(i([0,0],n[0])),e=0;e1&&r.push(i([0,0],n[n.length-1])),t.setTo(r)}},function(t,e,i){var n=i(0),s=i(11),r=i(33),o=i(1051),a=new n({Extends:r,Mixins:[o],initialize:function(t,e,i,n,o,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=128),void 0===o&&(o=128),r.call(this,t,"Rectangle",new s(0,0,n,o)),this.setPosition(e,i),this.setSize(n,o),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},updateData:function(){var t=[],e=this.geom,i=this._tempLine;return e.getLineA(i),t.push(i.x1,i.y1,i.x2,i.y2),e.getLineB(i),t.push(i.x2,i.y2),e.getLineC(i),t.push(i.x2,i.y2),e.getLineD(i),t.push(i.x2,i.y2),this.pathData=t,this}});t.exports=a},function(t,e,i){var n=i(1054),s=i(0),r=i(72),o=i(33),a=new s({Extends:o,Mixins:[n],initialize:function(t,e,i,n,s,r,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=5),void 0===s&&(s=32),void 0===r&&(r=64),o.call(this,t,"Star",null),this._points=n,this._innerRadius=s,this._outerRadius=r,this.setPosition(e,i),this.setSize(2*r,2*r),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},setPoints:function(t){return this._points=t,this.updateData()},setInnerRadius:function(t){return this._innerRadius=t,this.updateData()},setOuterRadius:function(t){return this._outerRadius=t,this.updateData()},points:{get:function(){return this._points},set:function(t){this._points=t,this.updateData()}},innerRadius:{get:function(){return this._innerRadius},set:function(t){this._innerRadius=t,this.updateData()}},outerRadius:{get:function(){return this._outerRadius},set:function(t){this._outerRadius=t,this.updateData()}},updateData:function(){var t=[],e=this._points,i=this._innerRadius,n=this._outerRadius,s=Math.PI/2*3,o=Math.PI/e,a=n,h=n;t.push(a,h+-n);for(var l=0;l=1)return i.x=r.x1,i.y=r.y1,i;var h=s(r),l=s(o),u=s(a),c=(h+l+u)*e,d=0;return ch+l?(d=(c-=h+l)/u,i.x=a.x1+(a.x2-a.x1)*d,i.y=a.y1+(a.y2-a.y1)*d):(d=(c-=h)/l,i.x=o.x1+(o.x2-o.x1)*d,i.y=o.y1+(o.y2-o.y1)*d),i}},function(t,e,i){var n=i(62),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]);var o=t.getLineA(),a=t.getLineB(),h=t.getLineC(),l=n(o),u=n(a),c=n(h),d=l+u+c;e||(e=d/i);for(var f=0;fl+u?(g=(p-=l+u)/c,v.x=h.x1+(h.x2-h.x1)*g,v.y=h.y1+(h.y2-h.y1)*g):(g=(p-=l)/u,v.x=a.x1+(a.x2-a.x1)*g,v.y=a.y1+(a.y2-a.y1)*g),r.push(v)}return r}},function(t,e){t.exports=function(t,e,i){if(!t||"number"==typeof t)return!1;if(t.hasOwnProperty(e))return t[e]=i,!0;if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=t,o=0;o0?(h=this.lightPool.pop()).set(t,e,i,a[0],a[1],a[2],o):h=new s(t,e,i,a[0],a[1],a[2],o),this.lights.push(h),h},removeLight:function(t){var e=this.lights.indexOf(t);return e>=0&&(this.lightPool.push(t),this.lights.splice(e,1)),this},shutdown:function(){for(;this.lights.length>0;)this.lightPool.push(this.lights.pop());this.ambientColor={r:.1,g:.1,b:.1},this.culledLights.length=0,this.lights.length=0},destroy:function(){this.shutdown()}});t.exports=o},function(t,e,i){var n=i(52),s=i(17),r={Circle:i(1115),Ellipse:i(1125),Intersects:i(454),Line:i(1144),Point:i(1165),Polygon:i(1179),Rectangle:i(467),Triangle:i(1209)};r=s(!1,r,n),t.exports=r},function(t,e,i){t.exports={CircleToCircle:i(217),CircleToRectangle:i(218),GetCircleToCircle:i(1135),GetCircleToRectangle:i(1136),GetLineToCircle:i(219),GetLineToRectangle:i(221),GetRectangleIntersection:i(1137),GetRectangleToRectangle:i(1138),GetRectangleToTriangle:i(1139),GetTriangleToCircle:i(1140),GetTriangleToLine:i(459),GetTriangleToTriangle:i(1141),LineToCircle:i(220),LineToLine:i(93),LineToRectangle:i(455),PointToLine:i(463),PointToLineSegment:i(1142),RectangleToRectangle:i(140),RectangleToTriangle:i(456),RectangleToValues:i(1143),TriangleToCircle:i(458),TriangleToLine:i(460),TriangleToTriangle:i(461)}},function(t,e){t.exports=function(t,e){var i=t.x1,n=t.y1,s=t.x2,r=t.y2,o=e.x,a=e.y,h=e.right,l=e.bottom,u=0;if(i>=o&&i<=h&&n>=a&&n<=l||s>=o&&s<=h&&r>=a&&r<=l)return!0;if(i=o){if((u=n+(r-n)*(o-i)/(s-i))>a&&u<=l)return!0}else if(i>h&&s<=h&&(u=n+(r-n)*(h-i)/(s-i))>=a&&u<=l)return!0;if(n=a){if((u=i+(s-i)*(a-n)/(r-n))>=o&&u<=h)return!0}else if(n>l&&r<=l&&(u=i+(s-i)*(l-n)/(r-n))>=o&&u<=h)return!0;return!1}},function(t,e,i){var n=i(93),s=i(53),r=i(222),o=i(457);t.exports=function(t,e){if(e.left>t.right||e.rightt.bottom||e.bottom0}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x,y:t.y}),e.push({x:t.right,y:t.y}),e.push({x:t.right,y:t.bottom}),e.push({x:t.x,y:t.bottom}),e}},function(t,e,i){var n=i(220),s=i(92);t.exports=function(t,e){return!(t.left>e.right||t.righte.bottom||t.bottome.right||t.righte.bottom||t.bottom0||(c=s(e),(d=n(t,c,!0)).length>0)}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x1,y:t.y1}),e.push({x:t.x2,y:t.y2}),e.push({x:t.x3,y:t.y3}),e}},function(t,e){t.exports=function(t,e,i){void 0===i&&(i=1);var n=e.x1,s=e.y1,r=e.x2,o=e.y2,a=t.x,h=t.y,l=(r-n)*(r-n)+(o-s)*(o-s);if(0===l)return!1;var u=((a-n)*(r-n)+(h-s)*(o-s))/l;if(u<0)return Math.sqrt((n-a)*(n-a)+(s-h)*(s-h))<=i;if(u>=0&&u<=1){var c=((s-h)*(r-n)-(n-a)*(o-s))/l;return Math.abs(c)*Math.sqrt(l)<=i}return Math.sqrt((r-a)*(r-a)+(o-h)*(o-h))<=i}},function(t,e,i){var n=i(13),s=i(63),r=i(94);t.exports=function(t){var e=r(t)-n.TAU;return s(e,-Math.PI,Math.PI)}},function(t,e){t.exports=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)}},function(t,e){t.exports=function(t){return t.x*t.x+t.y*t.y}},function(t,e,i){var n=i(11);n.Area=i(1184),n.Ceil=i(1185),n.CeilAll=i(1186),n.CenterOn=i(178),n.Clone=i(1187),n.Contains=i(53),n.ContainsPoint=i(1188),n.ContainsRect=i(468),n.CopyFrom=i(1189),n.Decompose=i(457),n.Equals=i(1190),n.FitInside=i(1191),n.FitOutside=i(1192),n.Floor=i(1193),n.FloorAll=i(1194),n.FromPoints=i(189),n.GetAspectRatio=i(224),n.GetCenter=i(1195),n.GetPoint=i(161),n.GetPoints=i(293),n.GetSize=i(1196),n.Inflate=i(1197),n.Intersection=i(1198),n.MarchingAnts=i(304),n.MergePoints=i(1199),n.MergeRect=i(1200),n.MergeXY=i(1201),n.Offset=i(1202),n.OffsetPoint=i(1203),n.Overlaps=i(1204),n.Perimeter=i(120),n.PerimeterPoint=i(1205),n.Random=i(164),n.RandomOutside=i(1206),n.SameDimensions=i(1207),n.Scale=i(1208),n.Union=i(417),t.exports=n},function(t,e){t.exports=function(t,e){return!(e.width*e.height>t.width*t.height)&&e.x>t.x&&e.xt.x&&e.rightt.y&&e.yt.y&&e.bottom=this.threshold?this.pressed||(this.pressed=!0,this.events.emit(s.BUTTON_DOWN,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_DOWN,i,t,this)):this.pressed&&(this.pressed=!1,this.events.emit(s.BUTTON_UP,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_UP,i,t,this))},destroy:function(){this.pad=null,this.events=null}});t.exports=r},function(t,e,i){var n=i(473),s=i(474),r=i(0),o=i(9),a=i(3),h=new r({Extends:o,initialize:function(t,e){o.call(this),this.manager=t,this.pad=e,this.id=e.id,this.index=e.index;for(var i=[],r=0;r=2&&(this.leftStick.set(r[0].getValue(),r[1].getValue()),s>=4&&this.rightStick.set(r[2].getValue(),r[3].getValue()))},destroy:function(){var t;for(this.removeAllListeners(),this.manager=null,this.pad=null,t=0;t=r;for(i=0;i=r;)this._elapsed-=r,this.step(s)}},step:function(t){var e,i,n=this.bodies.entries,s=n.length;for(e=0;e0){var l=this.tree,u=this.staticTree;for(n=(i=h.entries).length,t=0;t-1&&p>g&&(t.velocity.normalize().scale(g),p=g),t.speed=p},separate:function(t,e,i,n,s){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(n,t.gameObject,e.gameObject))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,s);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h=o.center;if((h.ya.bottom)&&(h.xa.right))return this.separateCircle(t,e,s)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)r.right&&(s=h(o.x,o.y,r.right,r.y)-o.radius):o.y>r.bottom&&(o.xr.right&&(s=h(o.x,o.y,r.right,r.bottom)-o.radius)),s*=-1}else s=t.halfWidth+e.halfWidth-h(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s&&(t.onOverlap||e.onOverlap)&&this.emit(u.OVERLAP,t.gameObject,e.gameObject,t,e),0!==s;var a=t.center.x-e.center.x,l=t.center.y-e.center.y,c=Math.sqrt(Math.pow(a,2)+Math.pow(l,2)),d=(e.center.x-t.center.x)/c||0,f=(e.center.y-t.center.y)/c||0,v=2*(t.velocity.x*d+t.velocity.y*f-e.velocity.x*d-e.velocity.y*f)/(t.mass+e.mass);t.immovable||(t.velocity.x=t.velocity.x-v*t.mass*d,t.velocity.y=t.velocity.y-v*t.mass*f),e.immovable||(e.velocity.x=e.velocity.x+v*e.mass*d,e.velocity.y=e.velocity.y+v*e.mass*f);var y=e.velocity.x-t.velocity.x,m=e.velocity.y-t.velocity.y,x=Math.atan2(m,y),T=this._frameTime;return t.immovable||e.immovable||(s/=2),t.immovable||(t.x+=t.velocity.x*T-s*Math.cos(x),t.y+=t.velocity.y*T-s*Math.sin(x)),e.immovable||(e.x+=e.velocity.x*T+s*Math.cos(x),e.y+=e.velocity.y*T+s*Math.sin(x)),t.velocity.x*=t.bounce.x,t.velocity.y*=t.bounce.y,e.velocity.x*=e.bounce.x,e.velocity.y*=e.bounce.y,(t.onCollide||e.onCollide)&&this.emit(u.COLLIDE,t.gameObject,e.gameObject,t,e),!0},intersects:function(t,e){return t!==e&&(t.isCircle||e.isCircle?t.isCircle?e.isCircle?h(t.center.x,t.center.y,e.center.x,e.center.y)<=t.halfWidth+e.halfWidth:this.circleBodyIntersects(t,e):this.circleBodyIntersects(e,t):!(t.right<=e.position.x||t.bottom<=e.position.y||t.position.x>=e.right||t.position.y>=e.bottom))},circleBodyIntersects:function(t,e){var i=s(t.center.x,e.left,e.right),n=s(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},overlap:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!0)},collide:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!1)},collideObjects:function(t,e,i,n,s,r){var o,a;t.isParent&&void 0===t.physicsType&&(t=t.children.entries),e&&e.isParent&&void 0===e.physicsType&&(e=e.children.entries);var h=Array.isArray(t),l=Array.isArray(e);if(this._total=0,h||l)if(!h&&l)for(o=0;o0},collideHandler:function(t,e,i,n,s,r){if(void 0===e&&t.isParent)return this.collideGroupVsGroup(t,t,i,n,s,r);if(!t||!e)return!1;if(t.body){if(e.body)return this.collideSpriteVsSprite(t,e,i,n,s,r);if(e.isParent)return this.collideSpriteVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideSpriteVsTilemapLayer(t,e,i,n,s,r)}else if(t.isParent){if(e.body)return this.collideSpriteVsGroup(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideGroupVsTilemapLayer(t,e,i,n,s,r)}else if(t.isTilemap){if(e.body)return this.collideSpriteVsTilemapLayer(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsTilemapLayer(e,t,i,n,s,r)}},collideSpriteVsSprite:function(t,e,i,n,s,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,n,s,r)&&(i&&i.call(s,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,n,s,r){var o,h,l,u=t.body;if(0!==e.length&&u&&u.enable)if(this.useTree){var c=this.treeMinMax;c.minX=u.left,c.minY=u.top,c.maxX=u.right,c.maxY=u.bottom;var d=e.physicsType===a.DYNAMIC_BODY?this.tree.search(c):this.staticTree.search(c);for(h=d.length,o=0;oc.baseTileWidth){var d=(c.tileWidth-c.baseTileWidth)*e.scaleX;a-=d,l+=d}c.tileHeight>c.baseTileHeight&&(u+=(c.tileHeight-c.baseTileHeight)*e.scaleY);var f=e.getTilesWithinWorldXY(a,h,l,u);return 0!==f.length&&this.collideSpriteVsTilesHandler(t,f,i,n,s,r,!0)},collideSpriteVsTilesHandler:function(t,e,i,n,s,r,o){for(var a,h,l=t.body,c={left:0,right:0,top:0,bottom:0},d=!1,f=0;f0&&t>i&&(t=i)),0!==n&&0!==e&&(e<0&&e<-n?e=-n:e>0&&e>n&&(e=n)),this.gameObject.x+=t,this.gameObject.y+=e}t<0?this.facing=s.FACING_LEFT:t>0&&(this.facing=s.FACING_RIGHT),e<0?this.facing=s.FACING_UP:e>0&&(this.facing=s.FACING_DOWN),this.allowRotation&&(this.gameObject.angle+=this.deltaZ()),this._tx=t,this._ty=e},setBoundsRectangle:function(t){return this.customBoundsRectangle=t||this.world.bounds,this},checkWorldBounds:function(){var t=this.position,e=this.customBoundsRectangle,i=this.world.checkCollision,n=this.worldBounce?-this.worldBounce.x:-this.bounce.x,s=this.worldBounce?-this.worldBounce.y:-this.bounce.y,r=!1;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=n,this.blocked.right=!0,r=!0),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=s,this.blocked.down=!0,r=!0),r&&(this.blocked.none=!1),r},setOffset:function(t,e){return void 0===e&&(e=t),this.offset.set(t,e),this.updateCenter(),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter(),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.offset.set(s-this.halfWidth,r-this.halfHeight)}return this.isCircle=!1,this.radius=0,this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter()):this.isCircle=!1,this},reset:function(t,e){this.stop();var i=this.gameObject;i.setPosition(t,e),i.getTopLeft?i.getTopLeft(this.position):this.position.set(t,e),this.prev.copy(this.position),this.prevFrame.copy(this.position),this.rotation=i.angle,this.preRotation=i.angle,this.updateBounds(),this.updateCenter()},stop:function(){return this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?this.radius>0&&t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom&&(this.center.x-t)*(this.center.x-t)+(this.center.y-e)*(this.center.y-e)<=this.radius*this.radius:h(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this._dx>0?this._dx:-this._dx},deltaAbsY:function(){return this._dy>0?this._dy:-this._dy},deltaX:function(){return this._dx},deltaY:function(){return this._dy},deltaXFinal:function(){return this._tx},deltaYFinal:function(){return this._ty},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.enable=!1,this.world&&this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor),this.isCircle?t.strokeCircle(i,n,this.width/2):(this.checkCollision.up&&t.lineBetween(e.x,e.y,e.x+this.width,e.y),this.checkCollision.right&&t.lineBetween(e.x+this.width,e.y,e.x+this.width,e.y+this.height),this.checkCollision.down&&t.lineBetween(e.x,e.y+this.height,e.x+this.width,e.y+this.height),this.checkCollision.left&&t.lineBetween(e.x,e.y,e.x,e.y+this.height))),this.debugShowVelocity&&(t.lineStyle(t.defaultStrokeWidth,this.world.defaults.velocityDebugColor,1),t.lineBetween(i,n,i+this.velocity.x/2,n+this.velocity.y/2))},willDrawDebug:function(){return this.debugShowBody||this.debugShowVelocity},setCollideWorldBounds:function(t,e,i){void 0===t&&(t=!0),this.collideWorldBounds=t;var n=void 0!==e,s=void 0!==i;return(n||s)&&(this.worldBounce||(this.worldBounce=new l),n&&(this.worldBounce.x=e),s&&(this.worldBounce.y=i)),this},setVelocity:function(t,e){return this.velocity.set(t,e),t=this.velocity.x,e=this.velocity.y,this.speed=Math.sqrt(t*t+e*e),this},setVelocityX:function(t){this.velocity.x=t;var e=t,i=this.velocity.y;return this.speed=Math.sqrt(e*e+i*i),this},setVelocityY:function(t){this.velocity.y=t;var e=this.velocity.x,i=t;return this.speed=Math.sqrt(e*e+i*i),this},setMaxVelocity:function(t,e){return this.maxVelocity.set(t,e),this},setMaxSpeed:function(t){return this.maxSpeed=t,this},setBounce:function(t,e){return this.bounce.set(t,e),this},setBounceX:function(t){return this.bounce.x=t,this},setBounceY:function(t){return this.bounce.y=t,this},setAcceleration:function(t,e){return this.acceleration.set(t,e),this},setAccelerationX:function(t){return this.acceleration.x=t,this},setAccelerationY:function(t){return this.acceleration.y=t,this},setAllowDrag:function(t){return void 0===t&&(t=!0),this.allowDrag=t,this},setAllowGravity:function(t){return void 0===t&&(t=!0),this.allowGravity=t,this},setAllowRotation:function(t){return void 0===t&&(t=!0),this.allowRotation=t,this},setDrag:function(t,e){return this.drag.set(t,e),this},setDragX:function(t){return this.drag.x=t,this},setDragY:function(t){return this.drag.y=t,this},setGravity:function(t,e){return this.gravity.set(t,e),this},setGravityX:function(t){return this.gravity.x=t,this},setGravityY:function(t){return this.gravity.y=t,this},setFriction:function(t,e){return this.friction.set(t,e),this},setFrictionX:function(t){return this.friction.x=t,this},setFrictionY:function(t){return this.friction.y=t,this},setAngularVelocity:function(t){return this.angularVelocity=t,this},setAngularAcceleration:function(t){return this.angularAcceleration=t,this},setAngularDrag:function(t){return this.angularDrag=t,this},setMass:function(t){return this.mass=t,this},setImmovable:function(t){return void 0===t&&(t=!0),this.immovable=t,this},setEnable:function(t){return void 0===t&&(t=!0),this.enable=t,this},x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=u},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o){this.world=t,this.name="",this.active=!0,this.overlapOnly=e,this.object1=i,this.object2=n,this.collideCallback=s,this.processCallback=r,this.callbackContext=o},setName:function(t){return this.name=t,this},update:function(){this.world.collideObjects(this.object1,this.object2,this.collideCallback,this.processCallback,this.callbackContext,this.overlapOnly)},destroy:function(){this.world.removeCollider(this),this.active=!1,this.world=null,this.object1=null,this.object2=null,this.collideCallback=null,this.processCallback=null,this.callbackContext=null}});t.exports=n},function(t,e,i){var n=i(58);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsX()+e.deltaAbsX()+s;return 0===t._dx&&0===e._dx?(t.embedded=!0,e.embedded=!0):t._dx>e._dx?(r=t.right-e.x)>o&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?r=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.right=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.left=!0)):t._dxo&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?r=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.left=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.right=!0))),t.overlapX=r,e.overlapX=r,r}},function(t,e,i){var n=i(58);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsY()+e.deltaAbsY()+s;return 0===t._dy&&0===e._dy?(t.embedded=!0,e.embedded=!0):t._dy>e._dy?(r=t.bottom-e.y)>o&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?r=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.down=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.up=!0)):t._dyo&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?r=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.up=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.down=!0))),t.overlapY=r,e.overlapY=r,r}},function(t,e,i){var n=i(414);function s(t){if(!(this instanceof s))return new s(t,[".left",".top",".right",".bottom"]);this._maxEntries=Math.max(4,t||9),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}function r(t,e,i){if(!i)return e.indexOf(t);for(var n=0;n=t.minX&&e.maxY>=t.minY}function g(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function v(t,e,i,s,r){for(var o,a=[e,i];a.length;)(i=a.pop())-(e=a.pop())<=s||(o=e+Math.ceil((i-e)/s/2)*s,n(t,o,e,i,r),a.push(e,o,o,i))}s.prototype={all:function(){return this._all(this.data,[])},search:function(t){var e=this.data,i=[],n=this.toBBox;if(!p(t,e))return i;for(var s,r,o,a,h=[];e;){for(s=0,r=e.children.length;s=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)},_split:function(t,e){var i=t[e],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);var r=this._chooseSplitIndex(i,s,n),a=g(i.children.splice(r,i.children.length-r));a.height=i.height,a.leaf=i.leaf,o(i,this.toBBox),o(a,this.toBBox),e?t[e-1].children.push(a):this._splitRoot(i,a)},_splitRoot:function(t,e){this.data=g([t,e]),this.data.height=t.height+1,this.data.leaf=!1,o(this.data,this.toBBox)},_chooseSplitIndex:function(t,e,i){var n,s,r,o,h,l,u,d,f,p,g,v,y,m;for(l=u=1/0,n=e;n<=i-e;n++)s=a(t,0,n,this.toBBox),r=a(t,n,i,this.toBBox),f=s,p=r,void 0,void 0,void 0,void 0,g=Math.max(f.minX,p.minX),v=Math.max(f.minY,p.minY),y=Math.min(f.maxX,p.maxX),m=Math.min(f.maxY,p.maxY),o=Math.max(0,y-g)*Math.max(0,m-v),h=c(s)+c(r),o=e;s--)r=t.children[s],h(u,t.leaf?o(r):r),c+=d(u);return c},_adjustParentBBoxes:function(t,e,i){for(var n=i;n>=0;n--)h(e[n],t)},_condense:function(t){for(var e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children).splice(e.indexOf(t[i]),1):this.clear():o(t[i],this.toBBox)},compareMinX:function(t,e){return t.left-e.left},compareMinY:function(t,e){return t.top-e.top},toBBox:function(t){return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}},t.exports=s},function(t,e){t.exports=function(t,e){return!(e.right<=t.left||e.bottom<=t.top||e.position.x>=t.right||e.position.y>=t.bottom)}},function(t,e,i){var n=i(60),s=i(0),r=i(58),o=i(53),a=i(3),h=new s({initialize:function(t,e){var i=e.width?e.width:64,n=e.height?e.height:64;this.world=t,this.gameObject=e,this.debugShowBody=t.defaults.debugShowStaticBody,this.debugBodyColor=t.defaults.staticBodyDebugColor,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new a,this.position=new a(e.x-e.displayOriginX,e.y-e.displayOriginY),this.width=i,this.height=n,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center=new a(e.x+this.halfWidth,e.y+this.halfHeight),this.velocity=a.ZERO,this.allowGravity=!1,this.gravity=a.ZERO,this.bounce=a.ZERO,this.onWorldBounds=!1,this.onCollide=!1,this.onOverlap=!1,this.mass=1,this.immovable=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.physicsType=r.STATIC_BODY,this._dx=0,this._dy=0},setGameObject:function(t,e){return t&&t!==this.gameObject&&(this.gameObject.body=null,t.body=this,this.gameObject=t),e&&this.updateFromGameObject(),this},updateFromGameObject:function(){this.world.staticTree.remove(this);var t=this.gameObject;return t.getTopLeft(this.position),this.width=t.displayWidth,this.height=t.displayHeight,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.world.staticTree.insert(this),this},setOffset:function(t,e){return void 0===e&&(e=t),this.world.staticTree.remove(this),this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(t,e),this.position.x+=this.offset.x,this.position.y+=this.offset.y,this.updateCenter(),this.world.staticTree.insert(this),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.world.staticTree.remove(this),this.width=t,this.height=e,this.halfWidth=Math.floor(t/2),this.halfHeight=Math.floor(e/2),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(s-this.halfWidth,r-this.halfHeight),this.position.x+=this.offset.x,this.position.y+=this.offset.y}return this.updateCenter(),this.isCircle=!1,this.radius=0,this.world.staticTree.insert(this),this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.world.staticTree.remove(this),this.isCircle=!0,this.radius=t,this.width=2*t,this.height=2*t,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter(),this.world.staticTree.insert(this)):this.isCircle=!1,this},updateCenter:function(){this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(t,e){var i=this.gameObject;void 0===t&&(t=i.x),void 0===e&&(e=i.y),this.world.staticTree.remove(this),i.setPosition(t,e),i.getTopLeft(this.position),this.updateCenter(),this.world.staticTree.insert(this)},stop:function(){return this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?n(this,t,e):o(this,t,e)},postUpdate:function(){},deltaAbsX:function(){return 0},deltaAbsY:function(){return 0},deltaX:function(){return 0},deltaY:function(){return 0},deltaZ:function(){return 0},destroy:function(){this.enable=!1,this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor,1),this.isCircle?t.strokeCircle(i,n,this.width/2):t.strokeRect(e.x,e.y,this.width,this.height))},willDrawDebug:function(){return this.debugShowBody},setMass:function(t){return t<=0&&(t=.1),this.mass=t,this},x:{get:function(){return this.position.x},set:function(t){this.world.staticTree.remove(this),this.position.x=t,this.world.staticTree.insert(this)}},y:{get:function(){return this.position.y},set:function(t){this.world.staticTree.remove(this),this.position.y=t,this.world.staticTree.insert(this)}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=h},function(t,e,i){var n=i(0),s=i(112),r=i(1317),o=i(113),a=i(1318),h=new n({initialize:function(t,e,i,n,r){void 0===n&&(n=16),void 0===r&&(r=n),this.world=t,this.gameObject=null,this.enabled=!0,this.parent,this.id=t.getNextID(),this.name="",this.size={x:n,y:r},this.offset={x:0,y:0},this.pos={x:e,y:i},this.last={x:e,y:i},this.vel={x:0,y:0},this.accel={x:0,y:0},this.friction={x:0,y:0},this.maxVel={x:t.defaults.maxVelocityX,y:t.defaults.maxVelocityY},this.standing=!1,this.gravityFactor=t.defaults.gravityFactor,this.bounciness=t.defaults.bounciness,this.minBounceVelocity=t.defaults.minBounceVelocity,this.accelGround=0,this.accelAir=0,this.jumpSpeed=0,this.type=o.NONE,this.checkAgainst=o.NONE,this.collides=s.NEVER,this.debugShowBody=t.defaults.debugShowBody,this.debugShowVelocity=t.defaults.debugShowVelocity,this.debugBodyColor=t.defaults.bodyDebugColor,this.updateCallback,this.slopeStanding={min:.767944870877505,max:2.3736477827122884}},reset:function(t,e){this.pos={x:t,y:e},this.last={x:t,y:e},this.vel={x:0,y:0},this.accel={x:0,y:0},this.friction={x:0,y:0},this.maxVel={x:100,y:100},this.standing=!1,this.gravityFactor=1,this.bounciness=0,this.minBounceVelocity=40,this.accelGround=0,this.accelAir=0,this.jumpSpeed=0,this.type=o.NONE,this.checkAgainst=o.NONE,this.collides=s.NEVER},update:function(t){var e=this.pos;this.last.x=e.x,this.last.y=e.y,this.vel.y+=this.world.gravity*t*this.gravityFactor,this.vel.x=r(t,this.vel.x,this.accel.x,this.friction.x,this.maxVel.x),this.vel.y=r(t,this.vel.y,this.accel.y,this.friction.y,this.maxVel.y);var i=this.vel.x*t,n=this.vel.y*t,s=this.world.collisionMap.trace(e.x,e.y,i,n,this.size.x,this.size.y);this.handleMovementTrace(s)&&a(this,s);var o=this.gameObject;o&&(o.x=e.x-this.offset.x+o.displayOriginX*o.scaleX,o.y=e.y-this.offset.y+o.displayOriginY*o.scaleY),this.updateCallback&&this.updateCallback(this)},drawDebug:function(t){var e=this.pos;if(this.debugShowBody&&(t.lineStyle(1,this.debugBodyColor,1),t.strokeRect(e.x,e.y,this.size.x,this.size.y)),this.debugShowVelocity){var i=e.x+this.size.x/2,n=e.y+this.size.y/2;t.lineStyle(1,this.world.defaults.velocityDebugColor,1),t.lineBetween(i,n,i+this.vel.x,n+this.vel.y)}},willDrawDebug:function(){return this.debugShowBody||this.debugShowVelocity},skipHash:function(){return!this.enabled||0===this.type&&0===this.checkAgainst&&0===this.collides},touches:function(t){return!(this.pos.x>=t.pos.x+t.size.x||this.pos.x+this.size.x<=t.pos.x||this.pos.y>=t.pos.y+t.size.y||this.pos.y+this.size.y<=t.pos.y)},resetSize:function(t,e,i,n){return this.pos.x=t,this.pos.y=e,this.size.x=i,this.size.y=n,this},toJSON:function(){return{name:this.name,size:{x:this.size.x,y:this.size.y},pos:{x:this.pos.x,y:this.pos.y},vel:{x:this.vel.x,y:this.vel.y},accel:{x:this.accel.x,y:this.accel.y},friction:{x:this.friction.x,y:this.friction.y},maxVel:{x:this.maxVel.x,y:this.maxVel.y},gravityFactor:this.gravityFactor,bounciness:this.bounciness,minBounceVelocity:this.minBounceVelocity,type:this.type,checkAgainst:this.checkAgainst,collides:this.collides}},fromJSON:function(){},check:function(){},collideWith:function(t,e){this.parent&&this.parent._collideCallback&&this.parent._collideCallback.call(this.parent._callbackScope,this,t,e)},handleMovementTrace:function(){return!0},destroy:function(){this.world.remove(this),this.enabled=!1,this.world=null,this.gameObject=null,this.parent=null}});t.exports=h},function(t,e,i){var n=i(0),s=i(1322),r=new n({initialize:function(t,e){void 0===t&&(t=32),this.tilesize=t,this.data=Array.isArray(e)?e:[],this.width=Array.isArray(e)?e[0].length:0,this.height=Array.isArray(e)?e.length:0,this.lastSlope=55,this.tiledef=s},trace:function(t,e,i,n,s,r){var o={collision:{x:!1,y:!1,slope:!1},pos:{x:t+i,y:e+n},tile:{x:0,y:0}};if(!this.data)return o;var a=Math.ceil(Math.max(Math.abs(i),Math.abs(n))/this.tilesize);if(a>1)for(var h=i/a,l=n/a,u=0;u0?r:0,y=n<0?f:0,m=Math.max(Math.floor(i/f),0),x=Math.min(Math.ceil((i+o)/f),g);u=Math.floor((t.pos.x+v)/f);var T=Math.floor((e+v)/f);if((l>0||u===T||T<0||T>=p)&&(T=-1),u>=0&&u1&&d<=this.lastSlope&&this.checkDef(t,d,e,i,a,h,r,o,T,c));c++)if(1===(d=this.data[c][u])||d>this.lastSlope||d>1&&this.checkDef(t,d,e,i,a,h,r,o,u,c)){if(d>1&&d<=this.lastSlope&&t.collision.slope)break;t.collision.x=!0,t.tile.x=d,t.pos.x=u*f-v+y,e=t.pos.x,a=0;break}}if(s){var w=s>0?o:0,b=s<0?f:0,E=Math.max(Math.floor(t.pos.x/f),0),S=Math.min(Math.ceil((t.pos.x+r)/f),p);c=Math.floor((t.pos.y+w)/f);var A=Math.floor((i+w)/f);if((l>0||c===A||A<0||A>=g)&&(A=-1),c>=0&&c1&&d<=this.lastSlope&&this.checkDef(t,d,e,i,a,h,r,o,u,A));u++)if(1===(d=this.data[c][u])||d>this.lastSlope||d>1&&this.checkDef(t,d,e,i,a,h,r,o,u,c)){if(d>1&&d<=this.lastSlope&&t.collision.slope)break;t.collision.y=!0,t.tile.y=d,t.pos.y=c*f-w+b;break}}},checkDef:function(t,e,i,n,s,r,o,a,h,l){var u=this.tiledef[e];if(!u)return!1;var c=this.tilesize,d=(h+u[0])*c,f=(l+u[1])*c,p=(u[2]-u[0])*c,g=(u[3]-u[1])*c,v=u[4],y=i+s+(g<0?o:0)-d,m=n+r+(p>0?a:0)-f;if(p*m-g*y>0){if(s*-g+r*p<0)return v;var x=Math.sqrt(p*p+g*g),T=g/x,w=-p/x,b=y*T+m*w,E=T*b,S=w*b;return E*E+S*S>=s*s+r*r?v||p*(m-r)-g*(y-s)<.5:(t.pos.x=i+s-E,t.pos.y=n+r-S,t.collision.slope={x:p,y:g,nx:T,ny:w},!0)}return!1}});t.exports=r},function(t,e,i){var n=i(0),s=i(499),r=i(500),o=i(501),a=new n({initialize:function(t){this.world=t,this.sys=t.scene.sys},body:function(t,e,i,n){return new s(this.world,t,e,i,n)},existing:function(t){var e=t.x-t.frame.centerX,i=t.y-t.frame.centerY,n=t.width,s=t.height;return t.body=this.world.create(e,i,n,s),t.body.parent=t,t.body.gameObject=t,t},image:function(t,e,i,n){var s=new r(this.world,t,e,i,n);return this.sys.displayList.add(s),s},sprite:function(t,e,i,n){var s=new o(this.world,t,e,i,n);return this.sys.displayList.add(s),this.sys.updateList.add(s),s},destroy:function(){this.world=null,this.sys=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(232),r=new n({Mixins:[s.Acceleration,s.BodyScale,s.BodyType,s.Bounce,s.CheckAgainst,s.Collides,s.Debug,s.Friction,s.Gravity,s.Offset,s.SetGameObject,s.Velocity],initialize:function(t,e,i,n,s){this.body=t.create(e,i,n,s),this.body.parent=this,this.size=this.body.size,this.offset=this.body.offset,this.vel=this.body.vel,this.accel=this.body.accel,this.friction=this.body.friction,this.maxVel=this.body.maxVel}});t.exports=r},function(t,e,i){var n=i(0),s=i(232),r=i(89),o=new n({Extends:r,Mixins:[s.Acceleration,s.BodyScale,s.BodyType,s.Bounce,s.CheckAgainst,s.Collides,s.Debug,s.Friction,s.Gravity,s.Offset,s.SetGameObject,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t.scene,e,i,n,s),this.body=t.create(e-this.frame.centerX,i-this.frame.centerY,this.width,this.height),this.body.parent=this,this.body.gameObject=this,this.size=this.body.size,this.offset=this.body.offset,this.vel=this.body.vel,this.accel=this.body.accel,this.friction=this.body.friction,this.maxVel=this.body.maxVel}});t.exports=o},function(t,e,i){var n=i(0),s=i(232),r=i(65),o=new n({Extends:r,Mixins:[s.Acceleration,s.BodyScale,s.BodyType,s.Bounce,s.CheckAgainst,s.Collides,s.Debug,s.Friction,s.Gravity,s.Offset,s.SetGameObject,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t.scene,e,i,n,s),this.body=t.create(e-this.frame.centerX,i-this.frame.centerY,this.width,this.height),this.body.parent=this,this.body.gameObject=this,this.size=this.body.size,this.offset=this.body.offset,this.vel=this.body.vel,this.accel=this.body.accel,this.friction=this.body.friction,this.maxVel=this.body.maxVel}});t.exports=o},function(t,e,i){var n=i(496),s=i(0),r=i(112),o=i(497),a=i(9),h=i(231),l=i(1),u=i(91),c=i(110),d=i(1336),f=i(34),p=i(113),g=new s({Extends:a,initialize:function(t,e){a.call(this),this.scene=t,this.bodies=new c,this.gravity=l(e,"gravity",0),this.cellSize=l(e,"cellSize",64),this.collisionMap=new o,this.timeScale=l(e,"timeScale",1),this.maxStep=l(e,"maxStep",.05),this.enabled=!0,this.drawDebug=l(e,"debug",!1),this.debugGraphic;var i=l(e,"maxVelocity",100);if(this.defaults={debugShowBody:l(e,"debugShowBody",!0),debugShowVelocity:l(e,"debugShowVelocity",!0),bodyDebugColor:l(e,"debugBodyColor",16711935),velocityDebugColor:l(e,"debugVelocityColor",65280),maxVelocityX:l(e,"maxVelocityX",i),maxVelocityY:l(e,"maxVelocityY",i),minBounceVelocity:l(e,"minBounceVelocity",40),gravityFactor:l(e,"gravityFactor",1),bounciness:l(e,"bounciness",0)},this.walls={left:null,right:null,top:null,bottom:null},this.delta=0,this._lastId=0,l(e,"setBounds",!1)){var n=e.setBounds;if("boolean"==typeof n)this.setBounds();else{var s=l(n,"x",0),r=l(n,"y",0),h=l(n,"width",t.sys.scale.width),u=l(n,"height",t.sys.scale.height),d=l(n,"thickness",64),f=l(n,"left",!0),p=l(n,"right",!0),g=l(n,"top",!0),v=l(n,"bottom",!0);this.setBounds(s,r,h,u,d,f,p,g,v)}}this.drawDebug&&this.createDebugGraphic()},setCollisionMap:function(t,e){if("string"==typeof t){var i=this.scene.cache.tilemap.get(t);if(!i||i.format!==f.WELTMEISTER)return console.warn("The specified key does not correspond to a Weltmeister tilemap: "+t),null;for(var n,s=i.data.layer,r=0;rr.ACTIVE&&d(this,t,e))},setCollidesNever:function(t){for(var e=0;e=0&&h<=1&&l>=0&&l<=1}function s(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])}function r(t,e,i){return s(t,e,i)>0}function o(t,e,i){return s(t,e,i)>=0}function a(t,e,i){return s(t,e,i)<0}function h(t,e,i){return s(t,e,i)<=0}t.exports={decomp:function(t){var e=function t(e){var i=[],n=[],s=[],r=[];var o=Number.MAX_VALUE;for(var a=0;a0?function t(e,i){if(0===i.length)return[e];if(i instanceof Array&&i.length&&i[0]instanceof Array&&2===i[0].length&&i[0][0]instanceof Array){for(var n=[e],s=0;su)return console.warn("quickDecomp: max level ("+u+") reached."),i;for(var L=0;LA&&(A+=e.length),S=Number.MAX_VALUE,A<_)return i;for(var D=_;D<=A;++D)o(f(O,L-1),f(O,L),f(O,D))&&h(f(O,L+1),f(O,L),f(O,D))&&(E=d(f(O,L),f(O,D)))3&&n>=0;--n)c(f(t,n-1),f(t,n),f(t,n+1),e)&&(t.splice(n%t.length,1),i++);return i},removeDuplicatePoints:function(t,e){for(var i=t.length-1;i>=1;--i)for(var n=t[i],s=i-1;s>=0;--s)E(n,t[s],e)&&t.splice(i,1)},makeCCW:function(t){for(var e=0,i=t,n=1;ni[e][0])&&(e=n);return!r(f(t,e-1),f(t,e),f(t,e+1))&&(function(t){for(var e=[],i=t.length,n=0;n!==i;n++)e.push(t.pop());for(var n=0;n!==i;n++)t[n]=e[n]}(t),!0)}};var l=[],u=[];function c(t,e,i,n){if(n){var r=l,o=u;r[0]=e[0]-t[0],r[1]=e[1]-t[1],o[0]=i[0]-e[0],o[1]=i[1]-e[1];var a=r[0]*o[0]+r[1]*o[1],h=Math.sqrt(r[0]*r[0]+r[1]*r[1]),c=Math.sqrt(o[0]*o[0]+o[1]*o[1]);return Math.acos(a/(h*c))0&&u.trigger(t,"collisionStart",{pairs:T.collisionStart}),o.preSolvePosition(T.list),s=0;s0&&u.trigger(t,"collisionActive",{pairs:T.collisionActive}),T.collisionEnd.length>0&&u.trigger(t,"collisionEnd",{pairs:T.collisionEnd}),h.update(t.metrics,t),n._bodiesClearForces(y),u.trigger(t,"afterUpdate",v),t},n.merge=function(t,e){if(f.extend(t,e),e.world){t.world=e.world,n.clear(t);for(var i=c.allBodies(t.world),s=0;s0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_START,e,i,n)}),p.on(e,"collisionActive",function(e){var i,n,s=e.pairs;s.length>0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_ACTIVE,e,i,n)}),p.on(e,"collisionEnd",function(e){var i,n,s=e.pairs;s.length>0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_END,e,i,n)})},setBounds:function(t,e,i,n,s,r,o,a,h){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.scene.sys.scale.width),void 0===n&&(n=this.scene.sys.scale.height),void 0===s&&(s=64),void 0===r&&(r=!0),void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===h&&(h=!0),this.updateWall(r,"left",t-s,e-s,s,n+2*s),this.updateWall(o,"right",t+i,e-s,s,n+2*s),this.updateWall(a,"top",t,e-s,i,s),this.updateWall(h,"bottom",t,e+n,i,s),this},updateWall:function(t,e,i,n,s,r){var o=this.walls[e];t?(o&&v.remove(this.localWorld,o),i+=s/2,n+=r/2,this.walls[e]=this.create(i,n,s,r,{isStatic:!0,friction:0,frictionStatic:0})):(o&&v.remove(this.localWorld,o),this.walls[e]=null)},createDebugGraphic:function(){var t=this.scene.sys.add.graphics({x:0,y:0});return t.setDepth(Number.MAX_VALUE),this.debugGraphic=t,this.drawDebug=!0,t},disableGravity:function(){return this.localWorld.gravity.x=0,this.localWorld.gravity.y=0,this.localWorld.gravity.scale=0,this},setGravity:function(t,e,i){return void 0===t&&(t=0),void 0===e&&(e=1),this.localWorld.gravity.x=t,this.localWorld.gravity.y=e,void 0!==i&&(this.localWorld.gravity.scale=i),this},create:function(t,e,i,s,r){var o=n.rectangle(t,e,i,s,r);return v.add(this.localWorld,o),o},add:function(t){return v.add(this.localWorld,t),this},remove:function(t,e){Array.isArray(t)||(t=[t]);for(var i=0;in.deltaMax?n.deltaMax:e)/n.delta,n.delta=e),0!==n.timeScalePrev&&(r*=s.timeScale/n.timeScalePrev),0===s.timeScale&&(r=0),n.timeScalePrev=s.timeScale,n.correction=r,n.frameCounter+=1,t-n.counterTimestamp>=1e3&&(n.fps=n.frameCounter*((t-n.counterTimestamp)/1e3),n.counterTimestamp=t,n.frameCounter=0),h.update(i,e,r)}},step:function(t,e){h.update(this.engine,t,e)},update60Hz:function(){return 1e3/60},update30Hz:function(){return 1e3/30},has:function(t){var e=t.hasOwnProperty("body")?t.body:t;return null!==a.get(this.localWorld,e.id,e.type)},getAllBodies:function(){return a.allBodies(this.localWorld)},getAllConstraints:function(){return a.allConstraints(this.localWorld)},getAllComposites:function(){return a.allComposites(this.localWorld)},postUpdate:function(){if(this.drawDebug){var t=this.debugConfig,e=this.engine,i=this.debugGraphic,n=a.allBodies(this.localWorld);this.debugGraphic.clear(),t.showBroadphase&&e.broadphase.controller&&this.renderGrid(e.broadphase,i,t.broadphaseColor,.5),t.showBounds&&this.renderBodyBounds(n,i,t.boundsColor,.5),(t.showBody||t.showStaticBody)&&this.renderBodies(n),t.showJoint&&this.renderJoints(),(t.showAxes||t.showAngleIndicator)&&this.renderBodyAxes(n,i,t.showAxes,t.angleColor,.5),t.showVelocity&&this.renderBodyVelocity(n,i,t.velocityColor,1,2),t.showSeparations&&this.renderSeparations(e.pairs.list,i,t.separationColor),t.showCollisions&&this.renderCollisions(e.pairs.list,i,t.collisionColor)}},renderGrid:function(t,e,i,n){e.lineStyle(1,i,n);for(var s=o.keys(t.buckets),r=0;r0){var l=h[0].vertex.x,u=h[0].vertex.y;2===h.length&&(l=(h[0].vertex.x+h[1].vertex.x)/2,u=(h[0].vertex.y+h[1].vertex.y)/2),a.bodyB===a.supports[0].body||a.bodyA.isStatic?e.lineBetween(l-8*a.normal.x,u-8*a.normal.y,l,u):e.lineBetween(l+8*a.normal.x,u+8*a.normal.y,l,u)}}return this},renderBodyBounds:function(t,e,i,n){e.lineStyle(1,i,n);for(var s=0;s1?1:0;h1?1:0;a1?1:0;a1&&this.renderConvexHull(g,e,f,m)}}},renderBody:function(t,e,i,n,s,r,o,a){void 0===n&&(n=null),void 0===s&&(s=null),void 0===r&&(r=1),void 0===o&&(o=null),void 0===a&&(a=null);for(var h=this.debugConfig,l=h.sensorFillColor,u=h.sensorLineColor,c=t.parts,d=c.length,f=d>1?1:0;f1){var s=t.vertices;e.lineStyle(n,i),e.beginPath(),e.moveTo(s[0].x,s[0].y);for(var r=1;r0&&(e.fillStyle(a),e.fillCircle(u.x,u.y,h),e.fillCircle(c.x,c.y,h)),this},resetCollisionIDs:function(){return s._nextCollidingGroupId=1,s._nextNonCollidingGroupId=-1,s._nextCategory=1,this},shutdown:function(){p.off(this.engine),this.removeAllListeners(),v.clear(this.localWorld,!1),h.clear(this.engine),this.drawDebug&&this.debugGraphic.destroy()},destroy:function(){this.shutdown()}});t.exports=m},function(t,e,i){var n=new(i(0))({initialize:function(t){this.pluginManager=t,this.game=t.game},init:function(){},start:function(){},stop:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=n},function(t,e,i){var n=i(26);t.exports=function(t,e,i,s,r,o,a){for(var h=n(i,s,r,o,null,a),l=0;l-1}return!1}},function(t,e,i){var n=i(80),s=i(115),r=i(245);t.exports=function(t,e,i,o,a){if(void 0===i&&(i=!1),void 0===o&&(o=!0),!s(t,e,a))return null;var h=a.data[e][t];return h?(a.data[e][t]=i?null:new n(a,-1,t,e,h.width,h.height),o&&h&&h.collides&&r(t,e,a),h):null}},function(t,e,i){var n=i(34),s=i(248),r=i(517),o=i(518),a=i(529);t.exports=function(t,e,i,h,l,u){var c;switch(e){case n.ARRAY_2D:c=s(t,i,h,l,u);break;case n.CSV:c=r(t,i,h,l,u);break;case n.TILED_JSON:c=o(t,i,u);break;case n.WELTMEISTER:c=a(t,i,u);break;default:console.warn("Unrecognized tilemap data format: "+e),c=null}return c}},function(t,e,i){var n=i(34),s=i(248);t.exports=function(t,e,i,r,o){var a=e.trim().split("\n").map(function(t){return t.split(",")}),h=s(t,a,i,r,o);return h.format=n.CSV,h}},function(t,e,i){var n=i(34),s=i(117),r=i(519),o=i(521),a=i(522),h=i(525),l=i(527),u=i(528);t.exports=function(t,e,i){if("orthogonal"!==e.orientation)return console.warn("Only orthogonal map types are supported in this version of Phaser"),null;var c=new s({width:e.width,height:e.height,name:t,tileWidth:e.tilewidth,tileHeight:e.tileheight,orientation:e.orientation,format:n.TILED_JSON,version:e.version,properties:e.properties,renderOrder:e.renderorder,infinite:e.infinite});c.layers=r(e,i),c.images=o(e);var d=a(e);return c.tilesets=d.tilesets,c.imageCollections=d.imageCollections,c.objects=h(e),c.tiles=l(c),u(c),c}},function(t,e,i){var n=i(520),s=i(1),r=i(116),o=i(249),a=i(80),h=i(250);t.exports=function(t,e){for(var i=s(t,"infinite",!1),l=[],u=[],c=h(t);c.i0;)if(c.i>=c.layers.length){if(u.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}c=u.pop()}else{var d=c.layers[c.i];if(c.i++,"tilelayer"===d.type)if(d.compression)console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+d.name+"'");else{if(d.encoding&&"base64"===d.encoding){if(d.chunks)for(var f=0;f0?((v=new a(p,g.gid,O,R,t.tilewidth,t.tileheight)).rotation=g.rotation,v.flipX=g.flipped,m[R][O]=v):(y=e?null:new a(p,-1,O,R,t.tilewidth,t.tileheight),m[R][O]=y),++x===S.width&&(C++,x=0)}}else{p=new r({name:c.name+d.name,x:c.x+s(d,"offsetx",0)+d.x,y:c.y+s(d,"offsety",0)+d.y,width:d.width,height:d.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,alpha:c.opacity*d.opacity,visible:c.visible&&d.visible,properties:s(d,"properties",{})});for(var L=[],D=0,k=d.data.length;D0?((v=new a(p,g.gid,x,m.length,t.tilewidth,t.tileheight)).rotation=g.rotation,v.flipX=g.flipped,L.push(v)):(y=e?null:new a(p,-1,x,m.length,t.tilewidth,t.tileheight),L.push(y)),++x===d.width&&(m.push(L),x=0,L=[])}p.data=m,l.push(p)}else if("group"===d.type){var F=h(t,d,c);u.push(c),c=F}}return l}},function(t,e){t.exports=function(t){for(var e=window.atob(t),i=e.length,n=new Array(i/4),s=0;s>>0;return n}},function(t,e,i){var n=i(1),s=i(250);t.exports=function(t){for(var e=[],i=[],r=s(t);r.i0;)if(r.i>=r.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}r=i.pop()}else{var o=r.layers[r.i];if(r.i++,"imagelayer"===o.type){var a=n(o,"offsetx",0)+n(o,"startx",0),h=n(o,"offsety",0)+n(o,"starty",0);e.push({name:r.name+o.name,image:o.image,x:r.x+a+o.x,y:r.y+h+o.y,alpha:r.opacity*o.opacity,visible:r.visible&&o.visible,properties:n(o,"properties",{})})}else if("group"===o.type){var l=s(t,o,r);i.push(r),r=l}}return e}},function(t,e,i){var n=i(154),s=i(523),r=i(251);t.exports=function(t){for(var e,i=[],o=[],a=null,h=0;h1){if(Array.isArray(l.tiles)){for(var c={},d={},f=0;f=this.firstgid&&t0;)if(a.i>=a.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}a=i.pop()}else{var h=a.layers[a.i];if(a.i++,h.opacity*=a.opacity,h.visible=a.visible&&h.visible,"objectgroup"===h.type){h.name=a.name+h.name;for(var l=a.x+n(h,"startx",0)+n(h,"offsetx",0),u=a.y+n(h,"starty",0)+n(h,"offsety",0),c=[],d=0;da&&(a=e.layer[l].width),e.layer[l].height>h&&(h=e.layer[l].height);var u=new s({width:a,height:h,name:t,tileWidth:e.layer[0].tilesize,tileHeight:e.layer[0].tilesize,format:n.WELTMEISTER});return u.layers=r(e,i),u.tilesets=o(e),u}},function(t,e,i){var n=i(116),s=i(80);t.exports=function(t,e){for(var i=[],r=0;r-1?new s(a,f,c,u,o.tilesize,o.tilesize):e?null:new s(a,-1,c,u,o.tilesize,o.tilesize),h.push(d)}l.push(h),h=[]}a.data=l,i.push(a)}return i}},function(t,e,i){var n=i(154);t.exports=function(t){for(var e=[],i=[],s=0;s-1&&(this.renderOrder=t),this},addTilesetImage:function(t,e,i,n,s,r,o){if(void 0===t)return null;if(void 0!==e&&null!==e||(e=t),!this.scene.sys.textures.exists(e))return console.warn("Invalid Tileset Image: "+e),null;var h=this.scene.sys.textures.get(e),l=this.getTilesetIndex(t);if(null===l&&this.format===a.TILED_JSON)return console.warn("No data found for Tileset: "+t),null;var u=this.tilesets[l];return u?(u.setTileSize(i,n),u.setSpacing(s,r),u.setImage(h),u):(void 0===i&&(i=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o=0),(u=new p(t,o,i,n,s,r)).setImage(h),this.tilesets.push(u),u)},convertLayerToStatic:function(t){if(null===(t=this.getLayer(t)))return null;var e=t.tilemapLayer;if(!(e&&e instanceof r))return null;var i=new c(e.scene,e.tilemap,e.layerIndex,e.tileset,e.x,e.y);return this.scene.sys.displayList.add(i),e.destroy(),i},copy:function(t,e,i,n,s,r,o,a){return a=this.getLayer(a),this._isStaticCall(a,"copy")?this:null!==a?(f.Copy(t,e,i,n,s,r,o,a),this):null},createBlankDynamicLayer:function(t,e,i,n,s,o,a,l){if(void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.width),void 0===o&&(o=this.height),void 0===a&&(a=this.tileWidth),void 0===l&&(l=this.tileHeight),null!==this.getLayerIndex(t))return console.warn("Invalid Tilemap Layer ID: "+t),null;for(var u,c=new h({name:t,tileWidth:a,tileHeight:l,width:s,height:o}),f=0;f-1&&this.putTileAt(e,r.x,r.y,i,r.tilemapLayer)}return n},removeTileAt:function(t,e,i,n,s){return s=this.getLayer(s),this._isStaticCall(s,"removeTileAt")?null:null===s?null:f.RemoveTileAt(t,e,i,n,s)},removeTileAtWorldXY:function(t,e,i,n,s,r){return r=this.getLayer(r),this._isStaticCall(r,"removeTileAtWorldXY")?null:null===r?null:f.RemoveTileAtWorldXY(t,e,i,n,s,r)},renderDebug:function(t,e,i){return null===(i=this.getLayer(i))?null:(f.RenderDebug(t,e,i),this)},renderDebugFull:function(t,e){for(var i=this.layers,n=0;n=0&&t<4&&(this._renderOrder=t),this},calculateFacesAt:function(t,e){return a.CalculateFacesAt(t,e,this.layer),this},calculateFacesWithin:function(t,e,i,n){return a.CalculateFacesWithin(t,e,i,n,this.layer),this},createFromTiles:function(t,e,i,n,s){return a.CreateFromTiles(t,e,i,n,s,this.layer)},cull:function(t){return this.cullCallback(this.layer,t,this.culledTiles,this._renderOrder)},copy:function(t,e,i,n,s,r,o){return a.Copy(t,e,i,n,s,r,o,this.layer),this},destroy:function(t){void 0===t&&(t=!0),this.tilemap&&(this.layer.tilemapLayer===this&&(this.layer.tilemapLayer=void 0),t&&this.tilemap.removeLayer(this),this.tilemap=void 0,this.layer=void 0,this.culledTiles.length=0,this.cullCallback=null,this.gidMap=[],this.tileset=[],o.prototype.destroy.call(this))},fill:function(t,e,i,n,s,r){return a.Fill(t,e,i,n,s,r,this.layer),this},filterTiles:function(t,e,i,n,s,r,o){return a.FilterTiles(t,e,i,n,s,r,o,this.layer)},findByIndex:function(t,e,i){return a.FindByIndex(t,e,i,this.layer)},findTile:function(t,e,i,n,s,r,o){return a.FindTile(t,e,i,n,s,r,o,this.layer)},forEachTile:function(t,e,i,n,s,r,o){return a.ForEachTile(t,e,i,n,s,r,o,this.layer),this},getTileAt:function(t,e,i){return a.GetTileAt(t,e,i,this.layer)},getTileAtWorldXY:function(t,e,i,n){return a.GetTileAtWorldXY(t,e,i,n,this.layer)},getTilesWithin:function(t,e,i,n,s){return a.GetTilesWithin(t,e,i,n,s,this.layer)},getTilesWithinShape:function(t,e,i){return a.GetTilesWithinShape(t,e,i,this.layer)},getTilesWithinWorldXY:function(t,e,i,n,s,r){return a.GetTilesWithinWorldXY(t,e,i,n,s,r,this.layer)},hasTileAt:function(t,e){return a.HasTileAt(t,e,this.layer)},hasTileAtWorldXY:function(t,e,i){return a.HasTileAtWorldXY(t,e,i,this.layer)},putTileAt:function(t,e,i,n){return a.PutTileAt(t,e,i,n,this.layer)},putTileAtWorldXY:function(t,e,i,n,s){return a.PutTileAtWorldXY(t,e,i,n,s,this.layer)},putTilesAt:function(t,e,i,n){return a.PutTilesAt(t,e,i,n,this.layer),this},randomize:function(t,e,i,n,s){return a.Randomize(t,e,i,n,s,this.layer),this},removeTileAt:function(t,e,i,n){return a.RemoveTileAt(t,e,i,n,this.layer)},removeTileAtWorldXY:function(t,e,i,n,s){return a.RemoveTileAtWorldXY(t,e,i,n,s,this.layer)},renderDebug:function(t,e){return a.RenderDebug(t,e,this.layer),this},replaceByIndex:function(t,e,i,n,s,r){return a.ReplaceByIndex(t,e,i,n,s,r,this.layer),this},setSkipCull:function(t){return void 0===t&&(t=!0),this.skipCull=t,this},setCullPadding:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=1),this.cullPaddingX=t,this.cullPaddingY=e,this},setCollision:function(t,e,i,n){return a.SetCollision(t,e,i,this.layer,n),this},setCollisionBetween:function(t,e,i,n){return a.SetCollisionBetween(t,e,i,n,this.layer),this},setCollisionByProperty:function(t,e,i){return a.SetCollisionByProperty(t,e,i,this.layer),this},setCollisionByExclusion:function(t,e,i){return a.SetCollisionByExclusion(t,e,i,this.layer),this},setCollisionFromCollisionGroup:function(t,e){return a.SetCollisionFromCollisionGroup(t,e,this.layer),this},setTileIndexCallback:function(t,e,i){return a.SetTileIndexCallback(t,e,i,this.layer),this},setTileLocationCallback:function(t,e,i,n,s,r){return a.SetTileLocationCallback(t,e,i,n,s,r,this.layer),this},shuffle:function(t,e,i,n){return a.Shuffle(t,e,i,n,this.layer),this},swapByIndex:function(t,e,i,n,s,r){return a.SwapByIndex(t,e,i,n,s,r,this.layer),this},tileToWorldX:function(t,e){return a.TileToWorldX(t,e,this.layer)},tileToWorldY:function(t,e){return a.TileToWorldY(t,e,this.layer)},tileToWorldXY:function(t,e,i,n){return a.TileToWorldXY(t,e,i,n,this.layer)},weightedRandomize:function(t,e,i,n,s){return a.WeightedRandomize(t,e,i,n,s,this.layer),this},worldToTileX:function(t,e,i){return a.WorldToTileX(t,e,i,this.layer)},worldToTileY:function(t,e,i){return a.WorldToTileY(t,e,i,this.layer)},worldToTileXY:function(t,e,i,n,s){return a.WorldToTileXY(t,e,i,n,s,this.layer)}});t.exports=h},function(t,e,i){var n=i(0),s=i(12),r=i(21),o=i(14),a=i(1424),h=i(150),l=i(35),u=i(10),c=new n({Extends:o,Mixins:[s.Alpha,s.BlendMode,s.ComputedSize,s.Depth,s.Flip,s.GetBounds,s.Origin,s.Pipeline,s.Transform,s.Visible,s.ScrollFactor,a],initialize:function(t,e,i,n,s,a){o.call(this,t,"StaticTilemapLayer"),this.isTilemap=!0,this.tilemap=e,this.layerIndex=i,this.layer=e.layers[i],this.layer.tilemapLayer=this,this.tileset=[],this.culledTiles=[],this.skipCull=!1,this.tilesDrawn=0,this.tilesTotal=this.layer.width*this.layer.height,this.cullPaddingX=1,this.cullPaddingY=1,this.cullCallback=h.CullTiles,this.renderer=t.sys.game.renderer,this.vertexBuffer=[],this.bufferData=[],this.vertexViewF32=[],this.vertexViewU32=[],this.dirty=[],this.vertexCount=[],this._renderOrder=0,this._tempMatrix=new l,this.gidMap=[],this.setTilesets(n),this.setAlpha(this.layer.alpha),this.setPosition(s,a),this.setOrigin(),this.setSize(e.tileWidth*this.layer.width,e.tileHeight*this.layer.height),this.updateVBOData(),this.initPipeline("TextureTintPipeline"),t.sys.game.events.on(r.CONTEXT_RESTORED,function(){this.updateVBOData()},this)},setTilesets:function(t){var e=[],i=[],n=this.tilemap;Array.isArray(t)||(t=[t]);for(var s=0;sv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(1===p)for(o=0;o=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(2===p)for(o=u-1;o>=0;o--)for(a=0;av||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(3===p)for(o=u-1;o>=0;o--)for(a=l-1;a>=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));this.dirty[e]=!1,null===y?(y=i.createVertexBuffer(m,n.STATIC_DRAW),this.vertexBuffer[e]=y):(i.setVertexBuffer(y),n.bufferSubData(n.ARRAY_BUFFER,0,m))}return this},batchTile:function(t,e,i,n,s,r,o){var a=i.getTileTextureCoordinates(e.index);if(!a)return t;var h=i.tileWidth,l=i.tileHeight,c=h/2,d=l/2,f=a.x/n,p=a.y/s,g=(a.x+h)/n,v=(a.y+l)/s,y=this._tempMatrix,m=-c,x=-d;e.flipX&&(h*=-1,m+=i.tileWidth),e.flipY&&(l*=-1,x+=i.tileHeight);var T=m+h,w=x+l;y.applyITRS(c+e.pixelX,d+e.pixelY,e.rotation,1,1);var b=u.getTintAppendFloatAlpha(16777215,r.alpha*this.alpha*e.alpha),E=y.getX(m,x),S=y.getY(m,x),A=y.getX(m,w),_=y.getY(m,w),C=y.getX(T,w),M=y.getY(T,w),P=y.getX(T,x),O=y.getY(T,x);r.roundPixels&&(E=Math.round(E),S=Math.round(S),A=Math.round(A),_=Math.round(_),C=Math.round(C),M=Math.round(M),P=Math.round(P),O=Math.round(O));var R=this.vertexViewF32[o],L=this.vertexViewU32[o];return R[++t]=E,R[++t]=S,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=b,R[++t]=A,R[++t]=_,R[++t]=f,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=E,R[++t]=S,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=b,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=P,R[++t]=O,R[++t]=g,R[++t]=p,R[++t]=0,L[++t]=b,this.vertexCount[o]+=6,t},setRenderOrder:function(t){if("string"==typeof t&&(t=["right-down","left-down","right-up","left-up"].indexOf(t)),t>=0&&t<4){this._renderOrder=t;for(var e=0;e0){var t=this.delay+this.delay*this.repeat;return(this.elapsed+this.delay*(this.repeat-this.repeatCount))/t}return this.getProgress()},getRepeatCount:function(){return this.repeatCount},getElapsed:function(){return this.elapsed},getElapsedSeconds:function(){return.001*this.elapsed},remove:function(t){void 0===t&&(t=!1),this.elapsed=this.delay,this.hasDispatched=!t,this.repeatCount=0},destroy:function(){this.callback=void 0,this.callbackScope=void 0,this.args=[]}});t.exports=r},function(t,e,i){var n=i(1433);t.exports=function(t){var e,i=[];if(t.hasOwnProperty("props"))for(e in t.props)"_"!==e.substr(0,1)&&i.push({key:e,value:t.props[e]});else for(e in t)-1===n.indexOf(e)&&"_"!==e.substr(0,1)&&i.push({key:e,value:t[e]});return i}},function(t,e,i){var n=i(5);t.exports=function(t){var e=n(t,"tweens",null);return null===e?[]:("function"==typeof e&&(e=e.call()),Array.isArray(e)||(e=[e]),e)}},function(t,e,i){var n=i(255),s=i(15),r=i(99),o=i(90),a=i(155),h=i(5),l=i(254),u=i(256),c=i(258);t.exports=function(t,e,i){void 0===i&&(i=n);var d=h(e,"from",0),f=h(e,"to",1),p=[{value:d}],g=a(e,"delay",i.delay),v=a(e,"duration",i.duration),y=h(e,"easeParams",i.easeParams),m=o(h(e,"ease",i.ease),y),x=a(e,"hold",i.hold),T=a(e,"repeat",i.repeat),w=a(e,"repeatDelay",i.repeatDelay),b=r(e,"yoyo",i.yoyo),E=[],S=l("value",f),A=c(p[0],0,"value",S.getEnd,S.getStart,S.getActive,m,g,v,b,x,T,w,!1,!1);A.start=d,A.current=d,A.to=f,E.push(A);var _=new u(t,E,p);_.offset=s(e,"offset",null),_.completeDelay=s(e,"completeDelay",0),_.loop=Math.round(s(e,"loop",0)),_.loopDelay=Math.round(s(e,"loopDelay",0)),_.paused=r(e,"paused",!1),_.useFrames=r(e,"useFrames",!1);for(var C=h(e,"callbackScope",_),M=[_,null],P=u.TYPES,O=0;OS&&(S=C),E[A][_]=C}}}var M=o?n(o):null;return a?function(t,e,n,s){var r,o=0,a=s%y,h=Math.floor(s/y);if(a>=0&&a=0&&h0?Math.floor(v/p.length):h(e,"duration",g.duration),g.delay=h(e,"delay",g.delay),g.easeParams=c(e,"easeParams",g.easeParams),g.ease=a(c(e,"ease",g.ease),g.easeParams),g.hold=h(e,"hold",g.hold),g.repeat=h(e,"repeat",g.repeat),g.repeatDelay=h(e,"repeatDelay",g.repeatDelay),g.yoyo=o(e,"yoyo",g.yoyo),g.flipX=o(e,"flipX",g.flipX),g.flipY=o(e,"flipY",g.flipY);for(var y=0;y0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay},init:function(){return this.calcDuration(),this.progress=0,this.totalProgress=0,!this.paused||(this.state=a.PAUSED,!1)},resetTweens:function(t){for(var e=0;e0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweens(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=a.LOOP_DELAY):(this.state=a.ACTIVE,this.dispatchTimelineEvent(r.TIMELINE_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=a.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=a.PENDING_REMOVE,this.dispatchTimelineEvent(r.TIMELINE_COMPLETE,this.callbacks.onComplete))},update:function(t,e){if(this.state!==a.PAUSED){switch(this.useFrames&&(e=1*this.manager.timeScale),e*=this.timeScale,this.elapsed+=e,this.progress=Math.min(this.elapsed/this.duration,1),this.totalElapsed+=e,this.totalProgress=Math.min(this.totalElapsed/this.totalDuration,1),this.state){case a.ACTIVE:for(var i=this.totalData,n=0;n>>0;if("function"!=typeof t)throw new TypeError;for(var n=arguments.length>=2?arguments[1]:void 0,s=0;s>16)+(65280&t)+((255&t)<<16)},n={_tintTL:16777215,_tintTR:16777215,_tintBL:16777215,_tintBR:16777215,_isTinted:!1,tintFill:!1,clearTint:function(){return this.setTint(16777215),this._isTinted=!1,this},setTint:function(t,e,n,s){return void 0===t&&(t=16777215),void 0===e&&(e=t,n=t,s=t),this._tintTL=i(t),this._tintTR=i(e),this._tintBL=i(n),this._tintBR=i(s),this._isTinted=!0,this.tintFill=!1,this},setTintFill:function(t,e,i,n){return this.setTint(t,e,i,n),this.tintFill=!0,this},tintTopLeft:{get:function(){return this._tintTL},set:function(t){this._tintTL=i(t),this._isTinted=!0}},tintTopRight:{get:function(){return this._tintTR},set:function(t){this._tintTR=i(t),this._isTinted=!0}},tintBottomLeft:{get:function(){return this._tintBL},set:function(t){this._tintBL=i(t),this._isTinted=!0}},tintBottomRight:{get:function(){return this._tintBR},set:function(t){this._tintBR=i(t),this._isTinted=!0}},tint:{set:function(t){this.setTint(t,t,t,t)}},isTinted:{get:function(){return this._isTinted}}};t.exports=n},function(t,e){t.exports="changedata"},function(t,e){t.exports="changedata-"},function(t,e){t.exports="removedata"},function(t,e){t.exports="setdata"},function(t,e){t.exports="destroy"},function(t,e){t.exports="complete"},function(t,e){t.exports="created"},function(t,e){t.exports="error"},function(t,e){t.exports="loop"},function(t,e){t.exports="play"},function(t,e){t.exports="seeked"},function(t,e){t.exports="seeking"},function(t,e){t.exports="stop"},function(t,e){t.exports="timeout"},function(t,e){t.exports="unlocked"},function(t,e,i){var n=i(39);t.exports=function(t,e,i,s,r){return n(t,"alpha",e,i,s,r)}},function(t,e,i){var n=i(39);t.exports=function(t,e,i,s,r){return n(t,"x",e,i,s,r)}},function(t,e,i){var n=i(39);t.exports=function(t,e,i,s,r,o,a){return void 0!==i&&null!==i||(i=e),n(t,"x",e,s,o,a),n(t,"y",i,r,o,a)}},function(t,e,i){var n=i(39);t.exports=function(t,e,i,s,r){return n(t,"y",e,i,s,r)}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=6.28);for(var s=i,r=(n-i)/t.length,o=0;o0?s(o,i):i<0&&r(o,Math.abs(i));for(var a=0;a1)if(0===s){var d=t.length-1;for(o=t[d].x,a=t[d].y,h=d-1;h>=0;h--)l=(c=t[h]).x,u=c.y,c.x=o,c.y=a,o=l,a=u;t[d].x=e,t[d].y=i}else{for(o=t[0].x,a=t[0].y,h=1;h0?(this._speedX-=this.dragX*t,this._speedX<0&&(this._speedX=0)):this._speedX<0&&(this._speedX+=this.dragX*t,this._speedX>0&&(this._speedX=0)),this._speedY>0?(this._speedY-=this.dragY*t,this._speedY<0&&(this._speedY=0)):this._speedY<0&&(this._speedY+=this.dragY*t,this._speedY>0&&(this._speedY=0)),this.up&&this.up.isDown?(this._speedY+=this.accelY,this._speedY>this.maxSpeedY&&(this._speedY=this.maxSpeedY)):this.down&&this.down.isDown&&(this._speedY-=this.accelY,this._speedY<-this.maxSpeedY&&(this._speedY=-this.maxSpeedY)),this.left&&this.left.isDown?(this._speedX+=this.accelX,this._speedX>this.maxSpeedX&&(this._speedX=this.maxSpeedX)):this.right&&this.right.isDown&&(this._speedX-=this.accelX,this._speedX<-this.maxSpeedX&&(this._speedX=-this.maxSpeedX)),this.zoomIn&&this.zoomIn.isDown?this._zoom=-this.zoomSpeed:this.zoomOut&&this.zoomOut.isDown?this._zoom=this.zoomSpeed:this._zoom=0,0!==this._speedX&&(e.scrollX-=this._speedX*t|0),0!==this._speedY&&(e.scrollY-=this._speedY*t|0),0!==this._zoom&&(e.zoom+=this._zoom,e.zoom<.001&&(e.zoom=.001))}},destroy:function(){this.camera=null,this.left=null,this.right=null,this.up=null,this.down=null,this.zoomIn=null,this.zoomOut=null}});t.exports=r},function(t,e,i){t.exports={Camera:i(312),BaseCamera:i(103),CameraManager:i(725),Effects:i(320),Events:i(55)}},function(t,e){t.exports="cameradestroy"},function(t,e){t.exports="camerafadeincomplete"},function(t,e){t.exports="camerafadeinstart"},function(t,e){t.exports="camerafadeoutcomplete"},function(t,e){t.exports="camerafadeoutstart"},function(t,e){t.exports="cameraflashcomplete"},function(t,e){t.exports="cameraflashstart"},function(t,e){t.exports="camerapancomplete"},function(t,e){t.exports="camerapanstart"},function(t,e){t.exports="postrender"},function(t,e){t.exports="prerender"},function(t,e){t.exports="camerashakecomplete"},function(t,e){t.exports="camerashakestart"},function(t,e){t.exports="camerazoomcomplete"},function(t,e){t.exports="camerazoomstart"},function(t,e,i){var n=i(20),s=i(0),r=i(55),o=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.isComplete=!1,this.direction=!0,this.duration=0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this.progress=0,this._elapsed=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s,o,a,h){if(void 0===t&&(t=!0),void 0===e&&(e=1e3),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=0),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===h&&(h=this.camera.scene),!o&&this.isRunning)return this.camera;this.isRunning=!0,this.isComplete=!1,this.duration=e,this.direction=t,this.progress=0,this.red=i,this.green=n,this.blue=s,this.alpha=t?Number.MIN_VALUE:1,this._elapsed=0,this._onUpdate=a,this._onUpdateScope=h;var l=t?r.FADE_OUT_START:r.FADE_IN_START;return this.camera.emit(l,this.camera,this,e,i,n,s),this.camera},update:function(t,e){this.isRunning&&(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed=1?1:1/e*(1+(e*t|0))}},function(t,e,i){var n=i(20),s=i(0),r=i(55),o=i(3),a=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.duration=0,this.intensity=new o,this.progress=0,this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s){return void 0===t&&(t=100),void 0===e&&(e=.05),void 0===i&&(i=!1),void 0===n&&(n=null),void 0===s&&(s=this.camera.scene),!i&&this.isRunning?this.camera:(this.isRunning=!0,this.duration=t,this.progress=0,"number"==typeof e?this.intensity.set(e):this.intensity.set(e.x,e.y),this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate=n,this._onUpdateScope=s,this.camera.emit(r.SHAKE_START,this.camera,this,t,e),this.camera)},preRender:function(){this.isRunning&&this.camera.matrix.translate(this._offsetX,this._offsetY)},update:function(t,e){if(this.isRunning)if(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed0&&(o.preRender(1),t.render(n,e,i,o))}},resetAll:function(){for(var t=0;t1)for(var i=1;i=1)&&(s.touch=!0),(navigator.msPointerEnabled||navigator.pointerEnabled)&&(s.mspointer=!0),navigator.getGamepads&&(s.gamepads=!0),"onwheel"in window||n.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":n.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"),s)},function(t,e,i){var n=i(125),s={audioData:!1,dolby:!1,m4a:!1,mp3:!1,ogg:!1,opus:!1,wav:!1,webAudio:!1,webm:!1};t.exports=function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio"),e=!!t.canPlayType;try{if(e&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(n.edge)s.dolby=!0;else if(n.safari&&n.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var i=parseInt(RegExp.$1,10),r=parseInt(RegExp.$2,10);(10===i&&r>=11||i>10)&&(s.dolby=!0)}}catch(t){}return s}()},function(t,e){var i={h264:!1,hls:!1,mp4:!1,ogg:!1,vp9:!1,webm:!1};t.exports=function(){var t=document.createElement("video"),e=!!t.canPlayType;try{e&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(i.ogg=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.h264=!0,i.mp4=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(i.webm=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(i.vp9=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.hls=!0))}catch(t){}return i}()},function(t,e){var i={available:!1,cancel:"",keyboard:!1,request:""};t.exports=function(){var t,e="Fullscreen",n="FullScreen",s=["request"+e,"request"+n,"webkitRequest"+e,"webkitRequest"+n,"msRequest"+e,"msRequest"+n,"mozRequest"+n,"mozRequest"+e];for(t=0;tMath.PI&&(t-=n.PI2),Math.abs(((t+n.TAU)%n.PI2-n.PI2)%n.PI2)}},function(t,e,i){var n=i(337);t.exports=function(t){return n(t+Math.PI)}},function(t,e,i){var n=i(13);t.exports=function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=i:e1?t[i]-(n(s-i,t[i],t[i],t[i-1],t[i-1])-t[i]):n(s-r,t[r?r-1:0],t[r],t[i1?n(t[i],t[i-1],i-s):n(t[r],t[r+1>i?i:r+1],s-r)}},function(t,e,i){var n=i(170);t.exports=function(t,e,i){return e+(i-e)*n(t,0,1)}},function(t,e,i){t.exports={GetNext:i(346),IsSize:i(127),IsValue:i(781)}},function(t,e){t.exports=function(t){return t>0&&0==(t&t-1)}},function(t,e,i){t.exports={Ceil:i(347),Floor:i(105),To:i(783)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){void 0===t&&(t=[(Date.now()*Math.random()).toString()]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.n=0,this.signs=[-1,1],t&&this.init(t)},rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},hash:function(t){var e,i=this.n;t=t.toString();for(var n=0;n>>0,i=(e*=i)>>>0,i+=4294967296*(e-=i);return this.n=i,2.3283064365386963e-10*(i>>>0)},init:function(t){"string"==typeof t?this.state(t):this.sow(t)},sow:function(t){if(this.n=4022871197,this.s0=this.hash(" "),this.s1=this.hash(" "),this.s2=this.hash(" "),this.c=1,t)for(var e=0;e0;e--){var i=Math.floor(this.frac()*(e+1)),n=t[i];t[i]=t[e],t[e]=n}return t}});t.exports=n},function(t,e){t.exports=function(t){for(var e=0,i=0;i1?void 0!==n?(s=(n-t)/(n-i))<0&&(s=0):s=1:s<0&&(s=0),s}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI;return t.x=Math.cos(i)*e,t.y=Math.sin(i)*e,t}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI,n=2*Math.random()-1,s=Math.sqrt(1-n*n)*e;return t.x=Math.cos(i)*s,t.y=Math.sin(i)*s,t.z=n*e,t}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=1),t.x=(2*Math.random()-1)*e,t.y=(2*Math.random()-1)*e,t.z=(2*Math.random()-1)*e,t.w=(2*Math.random()-1)*e,t}},function(t,e){t.exports=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var n=Math.pow(i,-e);return Math.round(t*n)/n}},function(t,e){t.exports=function(t,e,i,n){void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=1),n*=Math.PI/t;for(var s=[],r=[],o=0;o0&&t<=e*i&&(r=t>e-1?t-(o=Math.floor(t/e))*e:t,s.set(r,o)),s}},function(t,e){t.exports=function(t,e,i){return Math.abs(t-e)<=i}},function(t,e,i){var n=i(185),s=i(354),r=i(355),o=new s,a=new r,h=new n;t.exports=function(t,e,i){return a.setAxisAngle(e,i),o.fromRotationTranslation(a,h.set(0,0,0)),t.transformMat4(o)}},function(t,e){t.exports="addtexture"},function(t,e){t.exports="onerror"},function(t,e){t.exports="onload"},function(t,e){t.exports="ready"},function(t,e){t.exports="removetexture"},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_FS","","precision mediump float;","","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uMaskSampler;","uniform bool uInvertMaskAlpha;","","void main()","{"," vec2 uv = gl_FragCoord.xy / uResolution;"," vec4 mainColor = texture2D(uMainSampler, uv);"," vec4 maskColor = texture2D(uMaskSampler, uv);"," float alpha = mainColor.a;",""," if (!uInvertMaskAlpha)"," {"," alpha *= (maskColor.a);"," }"," else"," {"," alpha *= (1.0 - maskColor.a);"," }",""," gl_FragColor = vec4(mainColor.rgb * alpha, alpha);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_VS","","precision mediump float;","","attribute vec2 inPosition;","","void main()","{"," gl_Position = vec4(inPosition, 0.0, 1.0);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS","","precision mediump float;","","struct Light","{"," vec2 position;"," vec3 color;"," float intensity;"," float radius;","};","","const int kMaxLights = %LIGHT_COUNT%;","","uniform vec4 uCamera; /* x, y, rotation, zoom */","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uNormSampler;","uniform vec3 uAmbientLightColor;","uniform Light uLights[kMaxLights];","uniform mat3 uInverseRotationMatrix;","","varying vec2 outTexCoord;","varying vec4 outTint;","","void main()","{"," vec3 finalColor = vec3(0.0, 0.0, 0.0);"," vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);"," vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;"," vec3 normal = normalize(uInverseRotationMatrix * vec3(normalMap * 2.0 - 1.0));"," vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;",""," for (int index = 0; index < kMaxLights; ++index)"," {"," Light light = uLights[index];"," vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);"," vec3 lightNormal = normalize(lightDir);"," float distToSurf = length(lightDir) * uCamera.w;"," float diffuseFactor = max(dot(normal, lightNormal), 0.0);"," float radius = (light.radius / res.x * uCamera.w) * uCamera.w;"," float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);"," vec3 diffuse = light.color * diffuseFactor;"," finalColor += (attenuation * diffuse) * light.intensity;"," }",""," vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);"," gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);","","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_FS","","precision mediump float;","","uniform sampler2D uMainSampler;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main()","{"," vec4 texture = texture2D(uMainSampler, outTexCoord);"," vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);"," vec4 color = texture;",""," if (outTintEffect == 0.0)"," {"," // Multiply texture tint"," color = texture * texel;"," }"," else if (outTintEffect == 1.0)"," {"," // Solid color + texture alpha"," color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);"," color.a = texture.a * texel.a;"," }"," else if (outTintEffect == 2.0)"," {"," // Solid color, no texture"," color = texel;"," }",""," gl_FragColor = color;","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_VS","","precision mediump float;","","uniform mat4 uProjectionMatrix;","uniform mat4 uViewMatrix;","uniform mat4 uModelMatrix;","","attribute vec2 inPosition;","attribute vec2 inTexCoord;","attribute float inTintEffect;","attribute vec4 inTint;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main ()","{"," gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);",""," outTexCoord = inTexCoord;"," outTint = inTint;"," outTintEffect = inTintEffect;","}","",""].join("\n")},function(t,e,i){t.exports={GenerateTexture:i(370),Palettes:i(814)}},function(t,e,i){t.exports={ARNE16:i(371),C64:i(815),CGA:i(816),JMP:i(817),MSX:i(818)}},function(t,e){t.exports={0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"}},function(t,e){t.exports={0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}},function(t,e,i){t.exports={Path:i(820),CubicBezier:i(372),Curve:i(86),Ellipse:i(373),Line:i(374),QuadraticBezier:i(375),Spline:i(376)}},function(t,e,i){var n=i(0),s=i(372),r=i(373),o=i(6),a=i(374),h=i(821),l=i(375),u=i(11),c=i(376),d=i(3),f=i(13),p=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.name="",this.curves=[],this.cacheLengths=[],this.autoClose=!1,this.startPoint=new d,this._tmpVec2A=new d,this._tmpVec2B=new d,"object"==typeof t?this.fromJSON(t):this.startPoint.set(t,e)},add:function(t){return this.curves.push(t),this},circleTo:function(t,e,i){return void 0===e&&(e=!1),this.ellipseTo(t,t,0,360,e,i)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);return t.equals(e)||this.curves.push(new a(e,t)),this},cubicBezierTo:function(t,e,i,n,r,o){var a,h,l,u=this.getEndPoint();return t instanceof d?(a=t,h=e,l=i):(a=new d(i,n),h=new d(r,o),l=new d(t,e)),this.add(new s(u,a,h,l))},quadraticBezierTo:function(t,e,i,n){var s,r,o=this.getEndPoint();return t instanceof d?(s=t,r=e):(s=new d(i,n),r=new d(t,e)),this.add(new l(o,s,r))},draw:function(t,e){for(var i=0;i0?this.curves[this.curves.length-1].getPoint(1,t):t.copy(this.startPoint),t},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},getPoint:function(t,e){void 0===e&&(e=new d);for(var i=t*this.getLength(),n=this.getCurveLengths(),s=0;s=i){var r=n[s]-i,o=this.curves[s],a=o.getLength(),h=0===a?0:1-r/a;return o.getPointAt(h,e)}s++}return null},getPoints:function(t){void 0===t&&(t=12);for(var e,i=[],n=0;n1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},getRandomPoint:function(t){return void 0===t&&(t=new d),this.getPoint(Math.random(),t)},getSpacedPoints:function(t){void 0===t&&(t=40);for(var e=[],i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e},getStartPoint:function(t){return void 0===t&&(t=new d),t.copy(this.startPoint)},lineTo:function(t,e){t instanceof d?this._tmpVec2B.copy(t):this._tmpVec2B.set(t,e);var i=this.getEndPoint(this._tmpVec2A);return this.add(new a([i.x,i.y,this._tmpVec2B.x,this._tmpVec2B.y]))},splineTo:function(t){return t.unshift(this.getEndPoint()),this.add(new c(t))},moveTo:function(t,e){return t instanceof d?this.add(new h(t.x,t.y)):this.add(new h(t,e))},toJSON:function(){for(var t=[],e=0;e>16&255,g:t>>8&255,b:255&t,a:255};return t>16777215&&(e.a=t>>>24),e}},function(t,e,i){var n=i(36),s=i(380);t.exports=function(t,e,i){var r=i,o=i,a=i;if(0!==e){var h=i<.5?i*(1+e):i+e-i*e,l=2*i-h;r=s(l,h,t+1/3),o=s(l,h,t),a=s(l,h,t-1/3)}return(new n).setGLTo(r,o,a,1)}},function(t,e,i){var n=i(176);t.exports=function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n(s/359,t,e));return i}},function(t,e,i){var n=i(123),s=function(t,e,i,s,r,o,a,h){void 0===a&&(a=100),void 0===h&&(h=0);var l=h/a;return{r:n(t,s,l),g:n(e,r,l),b:n(i,o,l)}};t.exports={RGBWithRGB:s,ColorWithRGB:function(t,e,i,n,r,o){return void 0===r&&(r=100),void 0===o&&(o=0),s(t.r,t.g,t.b,e,i,n,r,o)},ColorWithColor:function(t,e,i,n){return void 0===i&&(i=100),void 0===n&&(n=0),s(t.r,t.g,t.b,e.r,e.g,e.b,i,n)}}},function(t,e,i){var n=i(183),s=i(36);t.exports=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=255),new s(n(t,e),n(t,e),n(t,e))}},function(t,e,i){var n=i(379);t.exports=function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n(s)+n(t)+n(e)+n(i)}},function(t,e,i){t.exports={BitmapMask:i(297),GeometryMask:i(298)}},function(t,e,i){var n={AddToDOM:i(129),DOMContentLoaded:i(381),GetScreenOrientation:i(382),GetTarget:i(387),ParseXML:i(388),RemoveFromDOM:i(191),RequestAnimationFrame:i(368)};t.exports=n},function(t,e,i){t.exports={EventEmitter:i(843)}},function(t,e,i){var n=i(0),s=i(9),r=i(22),o=new n({Extends:s,initialize:function(){s.call(this)},shutdown:function(){this.removeAllListeners()},destroy:function(){this.removeAllListeners()}});r.register("EventEmitter",o,"events"),t.exports=o},function(t,e,i){var n=i(129),s=i(308),r=i(311),o=i(28),a=i(0),h=i(333),l=i(845),u=i(356),c=i(101),d=i(366),f=i(334),p=i(381),g=i(9),v=i(21),y=i(389),m=i(22),x=i(394),T=i(395),w=i(397),b=i(128),E=i(400),S=i(367),A=i(369),_=i(404),C=i(412),M=new a({initialize:function(t){this.config=new h(t),this.renderer=null,this.domContainer=null,this.canvas=null,this.context=null,this.isBooted=!1,this.isRunning=!1,this.events=new g,this.anims=new s(this),this.textures=new E(this),this.cache=new r(this),this.registry=new c(this),this.input=new y(this,this.config),this.scene=new w(this,this.config.sceneConfig),this.device=f,this.scale=new T(this,this.config),this.sound=null,this.sound=_.create(this),this.loop=new S(this,this.config.fps),this.plugins=new x(this,this.config),this.facebook=new C(this),this.pendingDestroy=!1,this.removeCanvas=!1,this.noReturn=!1,this.hasFocus=!1,p(this.boot.bind(this))},boot:function(){m.hasCore("EventEmitter")?(this.isBooted=!0,this.config.preBoot(this),this.scale.preBoot(),u(this),l(this),d(this),n(this.canvas,this.config.parent),this.textures.once(b.READY,this.texturesReady,this),this.events.emit(v.BOOT)):console.warn("Aborting. Core Plugins missing.")},texturesReady:function(){this.events.emit(v.READY),this.start()},start:function(){this.isRunning=!0,this.config.postBoot(this),this.renderer?this.loop.start(this.step.bind(this)):this.loop.start(this.headlessStep.bind(this)),A(this);var t=this.events;t.on(v.HIDDEN,this.onHidden,this),t.on(v.VISIBLE,this.onVisible,this),t.on(v.BLUR,this.onBlur,this),t.on(v.FOCUS,this.onFocus,this)},step:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e);var n=this.renderer;n.preRender(),i.emit(v.PRE_RENDER,n,t,e),this.scene.render(n),n.postRender(),i.emit(v.POST_RENDER,n,t,e)},headlessStep:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e),i.emit(v.PRE_RENDER),i.emit(v.POST_RENDER)},onHidden:function(){this.loop.pause(),this.events.emit(v.PAUSE)},onVisible:function(){this.loop.resume(),this.events.emit(v.RESUME)},onBlur:function(){this.hasFocus=!1,this.loop.blur()},onFocus:function(){this.hasFocus=!0,this.loop.focus()},getFrame:function(){return this.loop.frame},getTime:function(){return this.loop.now},destroy:function(t,e){void 0===e&&(e=!1),this.pendingDestroy=!0,this.removeCanvas=t,this.noReturn=e},runDestroy:function(){this.scene.destroy(),this.events.emit(v.DESTROY),this.events.removeAllListeners(),this.renderer&&this.renderer.destroy(),this.removeCanvas&&this.canvas&&(o.remove(this.canvas),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)),this.domContainer&&this.domContainer.parentNode.removeChild(this.domContainer),this.loop.destroy(),this.pendingDestroy=!1}});t.exports=M},function(t,e,i){var n=i(129);t.exports=function(t){var e=t.config;if(e.parent&&e.domCreateContainer){var i=document.createElement("div");i.style.cssText=["display: block;","width: "+t.scale.width+"px;","height: "+t.scale.height+"px;","padding: 0; margin: 0;","position: absolute;","overflow: hidden;","pointer-events: none;","transform: scale(1);","transform-origin: left top;"].join(" "),t.domContainer=i,n(i,e.parent)}}},function(t,e){t.exports="boot"},function(t,e){t.exports="destroy"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameout"},function(t,e){t.exports="gameover"},function(t,e){t.exports="gameobjectdown"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameobjectmove"},function(t,e){t.exports="gameobjectout"},function(t,e){t.exports="gameobjectover"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="wheel"},function(t,e){t.exports="gameobjectup"},function(t,e){t.exports="gameobjectwheel"},function(t,e){t.exports="boot"},function(t,e){t.exports="process"},function(t,e){t.exports="update"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointerdownoutside"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="pointerupoutside"},function(t,e){t.exports="wheel"},function(t,e){t.exports="pointerlockchange"},function(t,e){t.exports="preupdate"},function(t,e){t.exports="shutdown"},function(t,e){t.exports="start"},function(t,e){t.exports="update"},function(t,e){t.exports=function(t){if(!t)return window.innerHeight;var e=Math.abs(window.orientation),i={w:0,h:0},n=document.createElement("div");return n.setAttribute("style","position: fixed; height: 100vh; width: 0; top: 0"),document.documentElement.appendChild(n),i.w=90===e?n.offsetHeight:window.innerWidth,i.h=90===e?window.innerWidth:n.offsetHeight,document.documentElement.removeChild(n),n=null,90!==Math.abs(window.orientation)?i.h:i.w}},function(t,e){t.exports="addfile"},function(t,e){t.exports="complete"},function(t,e){t.exports="filecomplete"},function(t,e){t.exports="filecomplete-"},function(t,e){t.exports="loaderror"},function(t,e){t.exports="load"},function(t,e){t.exports="fileprogress"},function(t,e){t.exports="postprocess"},function(t,e){t.exports="progress"},function(t,e){t.exports="start"},function(t,e,i){var n=i(1),s=i(194);t.exports=function(t){var e=t.game.config.defaultPhysicsSystem,i=n(t.settings,"physics",!1);if(e||i){var r=[];if(e&&r.push(s(e+"Physics")),i)for(var o in i)o=s(o.concat("Physics")),-1===r.indexOf(o)&&r.push(o);return r}}},function(t,e,i){var n=i(1);t.exports=function(t){var e=t.plugins.getDefaultScenePlugins(),i=n(t.settings,"plugins",!1);return Array.isArray(i)?i:e||[]}},function(t,e,i){var n={game:"game",anims:"anims",cache:"cache",plugins:"plugins",registry:"registry",scale:"scale",sound:"sound",textures:"textures",events:"events",cameras:"cameras",add:"add",make:"make",scenePlugin:"scene",displayList:"children",lights:"lights",data:"data",input:"input",load:"load",time:"time",tweens:"tweens",arcadePhysics:"physics",impactPhysics:"impact",matterPhysics:"matter"};n.facebook="facebook",t.exports=n},function(t,e){t.exports=function(t,e,i){if(i.getElementsByTagName("TextureAtlas")){var n=t.source[e];t.add("__BASE",e,0,0,n.width,n.height);for(var s,r=i.getElementsByTagName("SubTexture"),o=0;og||c<-g)&&(c=0),c<0&&(c=g+c),-1!==d&&(g=c+(d+1));for(var v=f,y=f,m=0,x=0,T=0;Tr&&(m=w-r),b>o&&(x=b-o),t.add(T,e,i+v,s+y,h-m,l-x),(v+=h+p)+h>r&&(v=f,y+=l+p)}return t}},function(t,e,i){var n=i(1);t.exports=function(t,e,i){var s=n(i,"frameWidth",null),r=n(i,"frameHeight",s);if(!s)throw new Error("TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.");var o=t.source[0];t.add("__BASE",0,0,0,o.width,o.height);var a,h=n(i,"startFrame",0),l=n(i,"endFrame",-1),u=n(i,"margin",0),c=n(i,"spacing",0),d=e.cutX,f=e.cutY,p=e.cutWidth,g=e.cutHeight,v=e.realWidth,y=e.realHeight,m=Math.floor((v-u+c)/(s+c)),x=Math.floor((y-u+c)/(r+c)),T=m*x,w=e.x,b=s-w,E=s-(v-p-w),S=e.y,A=r-S,_=r-(y-g-S);(h>T||h<-T)&&(h=0),h<0&&(h=T+h),-1!==l&&(T=h+(l+1));for(var C=u,M=u,P=0,O=e.sourceIndex,R=0;R0){var r=i-t.length;if(r<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.push(e),n&&n.call(s,e),e):null;for(var o=e.length-1;o>=0;)-1!==t.indexOf(e[o])&&e.splice(o,1),o--;if(0===(o=e.length))return null;i>0&&o>r&&(e.splice(r),o=r);for(var a=0;a0){var o=n-t.length;if(o<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.splice(i,0,e),s&&s.call(r,e),e):null;for(var a=e.length-1;a>=0;)-1!==t.indexOf(e[a])&&e.pop(),a--;if(0===(a=e.length))return null;n>0&&a>o&&(e.splice(o),a=o);for(var h=a-1;h>=0;h--){var l=e[h];t.splice(i,0,l),s&&s.call(r,l)}return e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);return-1!==i&&i0){var n=t[i-1],s=t.indexOf(n);t[i]=n,t[s]=e}return t}},function(t,e){t.exports=function(t,e,i){var n=t.indexOf(e);if(-1===n||i<0||i>=t.length)throw new Error("Supplied index out of bounds");return n!==i&&(t.splice(n,1),t.splice(i,0,e)),e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);if(-1!==i&&it.length-1)throw new Error("Index out of bounds");var r=n(t,e);return i&&i.call(s,r),r}},function(t,e,i){var n=i(74);t.exports=function(t,e,i,s,r){if(void 0===e&&(e=0),void 0===i&&(i=t.length),void 0===r&&(r=t),n(t,e,i)){var o=i-e,a=t.splice(e,o);if(s)for(var h=0;h0&&(t.splice(i,1),t.unshift(e)),e}},function(t,e,i){var n=i(74);t.exports=function(t,e,i,s,r){if(void 0===s&&(s=0),void 0===r&&(r=t.length),n(t,s,r))for(var o=s;o0){for(n=0;nl||U-N>l?(Y.push(X.i-1),X.cr?(Y.push(X.i+X.word.length),N=0,B=null):B=X):X.cr&&(Y.push(X.i+X.word.length),N=0,B=null)}for(n=Y.length-1;n>=0;n--)s=a,r=Y[n],o="\n",a=s.substr(0,r)+o+s.substr(r+1);i.wrappedText=a,h=a.length,k=[],F=null}for(n=0;nb&&(c=b),d>E&&(d=E);var W=b+w.xAdvance,V=E+v;fR&&(R=D),DR&&(R=D),D0&&(a=(o=z.wrappedText).length);var U=e._bounds.lines;1===N?X=(U.longest-U.lengths[0])/2:2===N&&(X=U.longest-U.lengths[0]);for(var G=s.roundPixels,W=0;W0&&(a=(o=L.wrappedText).length);var D=e._bounds.lines;1===P?R=(D.longest-D.lengths[0])/2:2===P&&(R=D.longest-D.lengths[0]),h.translate(-e.displayOriginX,-e.displayOriginY);for(var k=s.roundPixels,F=0;F0!=t>0,this._alpha=t}}});t.exports=r},function(t,e,i){var n=i(2),s=i(2);n=i(985),s=i(986),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){var r=e.list;if(0!==r.length){var o=e.localTransform;s?(o.loadIdentity(),o.multiply(s),o.translate(e.x,e.y),o.rotate(e.rotation),o.scale(e.scaleX,e.scaleY)):o.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);var a=-1!==e.blendMode;a||t.setBlendMode(0);for(var h=e.alpha,l=e.scrollFactorX,u=e.scrollFactorY,c=r,d=r.length,f=0;f0||e.cropHeight>0;l&&(h.flush(),t.pushScissor(e.x,e.y,e.cropWidth*e.scaleX,e.cropHeight*e.scaleY));var u=h._tempMatrix1,c=h._tempMatrix2,d=h._tempMatrix3,f=h._tempMatrix4;c.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),u.copyFrom(s.matrix),r?(u.multiplyWithOffset(r,-s.scrollX*e.scrollFactorX,-s.scrollY*e.scrollFactorY),c.e=e.x,c.f=e.y,u.multiply(c,d)):(c.e-=s.scrollX*e.scrollFactorX,c.f-=s.scrollY*e.scrollFactorY,u.multiply(c,d));var p=e.frame,g=p.glTexture,v=p.cutX,y=p.cutY,m=g.width,x=g.height,T=e._isTinted&&e.tintFill,w=n.getTintAppendFloatAlpha(e._tintTL,s.alpha*e._alphaTL),b=n.getTintAppendFloatAlpha(e._tintTR,s.alpha*e._alphaTR),E=n.getTintAppendFloatAlpha(e._tintBL,s.alpha*e._alphaBL),S=n.getTintAppendFloatAlpha(e._tintBR,s.alpha*e._alphaBR);h.setTexture2D(g,0);var A,_,C=0,M=0,P=0,O=0,R=e.letterSpacing,L=0,D=0,k=0,F=0,I=e.scrollX,B=e.scrollY,N=e.fontData,Y=N.chars,X=N.lineHeight,z=e.fontSize/N.size,U=0,G=e._align,W=0,V=0;e.getTextBounds(!1);var H=e._bounds.lines;1===G?V=(H.longest-H.lengths[0])/2:2===G&&(V=H.longest-H.lengths[0]);for(var j=s.roundPixels,q=e.displayCallback,K=e.callbackData,J=0;J0&&e.cropHeight>0&&(h.beginPath(),h.rect(0,0,e.cropWidth,e.cropHeight),h.clip());for(var N=0;N0&&(Y=Y%b-b):Y>b?Y=b:Y<0&&(Y=b+Y%b),null===_&&(_=new o(F+Math.cos(N)*B,I+Math.sin(N)*B,v),E.push(_),k+=.01);k<1+z;)w=Y*k+N,x=F+Math.cos(w)*B,T=I+Math.sin(w)*B,_.points.push(new r(x,T,v)),k+=.01;w=Y+N,x=F+Math.cos(w)*B,T=I+Math.sin(w)*B,_.points.push(new r(x,T,v));break;case n.FILL_RECT:u.setTexture2D(M),u.batchFillRect(p[++P],p[++P],p[++P],p[++P],f,c);break;case n.FILL_TRIANGLE:u.setTexture2D(M),u.batchFillTriangle(p[++P],p[++P],p[++P],p[++P],p[++P],p[++P],f,c);break;case n.STROKE_TRIANGLE:u.setTexture2D(M),u.batchStrokeTriangle(p[++P],p[++P],p[++P],p[++P],p[++P],p[++P],v,f,c);break;case n.LINE_TO:null!==_?_.points.push(new r(p[++P],p[++P],v)):(_=new o(p[++P],p[++P],v),E.push(_));break;case n.MOVE_TO:_=new o(p[++P],p[++P],v),E.push(_);break;case n.SAVE:a.push(f.copyToArray());break;case n.RESTORE:f.copyFromArray(a.pop());break;case n.TRANSLATE:F=p[++P],I=p[++P],f.translate(F,I);break;case n.SCALE:F=p[++P],I=p[++P],f.scale(F,I);break;case n.ROTATE:f.rotate(p[++P]);break;case n.SET_TEXTURE:var U=p[++P],G=p[++P];u.currentFrame=U,u.setTexture2D(U.glTexture,0),u.tintEffect=G,M=U.glTexture;break;case n.CLEAR_TEXTURE:u.currentFrame=t.blankTexture,u.tintEffect=2,M=t.blankTexture.glTexture}}}},function(t,e,i){var n=i(2),s=i(2);n=i(998),s=i(999),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(2),s=i(2);n=i(1001),s=i(1002),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){t.exports={GravityWell:i(425),Particle:i(426),ParticleEmitter:i(427),ParticleEmitterManager:i(207),Zones:i(1008)}},function(t,e,i){var n=i(0),s=i(348),r=i(90),o=i(1),a=i(63),h=new n({initialize:function(t,e,i,n){void 0===n&&(n=!1),this.propertyKey=e,this.propertyValue=i,this.defaultValue=i,this.steps=0,this.counter=0,this.start=0,this.end=0,this.ease,this.emitOnly=n,this.onEmit=this.defaultEmit,this.onUpdate=this.defaultUpdate,this.loadConfig(t)},loadConfig:function(t,e){void 0===t&&(t={}),e&&(this.propertyKey=e),this.propertyValue=o(t,this.propertyKey,this.defaultValue),this.setMethods(),this.emitOnly&&(this.onUpdate=this.defaultUpdate)},toJSON:function(){return this.propertyValue},onChange:function(t){return this.propertyValue=t,this.setMethods()},setMethods:function(){var t=this.propertyValue,e=typeof t;if("number"===e)this.onEmit=this.staticValueEmit,this.onUpdate=this.staticValueUpdate;else if(Array.isArray(t))this.onEmit=this.randomStaticValueEmit;else if("function"===e)this.emitOnly?this.onEmit=t:this.onUpdate=t;else if("object"===e&&(this.has(t,"random")||this.hasBoth(t,"start","end")||this.hasBoth(t,"min","max"))){this.start=this.has(t,"start")?t.start:t.min,this.end=this.has(t,"end")?t.end:t.max;var i=this.hasBoth(t,"min","max")||!!t.random;if(i){var n=t.random;Array.isArray(n)&&(this.start=n[0],this.end=n[1]),this.onEmit=this.randomRangedValueEmit}if(this.has(t,"steps"))this.steps=t.steps,this.counter=this.start,this.onEmit=this.steppedEmit;else{var s=this.has(t,"ease")?t.ease:"Linear";this.ease=r(s),i||(this.onEmit=this.easedValueEmit),this.onUpdate=this.easeValueUpdate}}else"object"===e&&this.hasEither(t,"onEmit","onUpdate")&&(this.has(t,"onEmit")&&(this.onEmit=t.onEmit),this.has(t,"onUpdate")&&(this.onUpdate=t.onUpdate));return this},has:function(t,e){return t.hasOwnProperty(e)},hasBoth:function(t,e,i){return t.hasOwnProperty(e)&&t.hasOwnProperty(i)},hasEither:function(t,e,i){return t.hasOwnProperty(e)||t.hasOwnProperty(i)},defaultEmit:function(t,e,i){return i},defaultUpdate:function(t,e,i,n){return n},staticValueEmit:function(){return this.propertyValue},staticValueUpdate:function(){return this.propertyValue},randomStaticValueEmit:function(){var t=Math.floor(Math.random()*this.propertyValue.length);return this.propertyValue[t]},randomRangedValueEmit:function(t,e){var i=s(this.start,this.end);return t&&t.data[e]&&(t.data[e].min=i),i},steppedEmit:function(){var t=this.counter,e=this.counter+(this.end-this.start)/this.steps;return this.counter=a(e,this.start,this.end),t},easedValueEmit:function(t,e){if(t&&t.data[e]){var i=t.data[e];i.min=this.start,i.max=this.end}return this.start},easeValueUpdate:function(t,e,i){var n=t.data[e];return(n.max-n.min)*this.ease(i)+n.min}});t.exports=h},function(t,e,i){var n=i(2),s=i(2);n=i(1006),s=i(1007),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){var o=e.emitters.list,a=o.length;if(0!==a){var h=this.pipeline,l=h._tempMatrix1.copyFrom(s.matrix),u=h._tempMatrix2,c=h._tempMatrix3,d=h._tempMatrix4.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);l.multiply(d),t.setPipeline(h);var f=s.roundPixels,p=e.defaultFrame.glTexture,g=n.getTintAppendFloatAlphaAndSwap;h.setTexture2D(p,0);for(var v=0;v?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",TEXT_SET2:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET3:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",TEXT_SET4:"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",TEXT_SET5:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",TEXT_SET6:"ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",TEXT_SET7:"AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",TEXT_SET8:"0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET9:"ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",TEXT_SET10:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET11:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"}},function(t,e,i){var n=i(5);t.exports=function(t,e){var i=e.width,s=e.height,r=Math.floor(i/2),o=Math.floor(s/2),a=n(e,"chars","");if(""!==a){var h=n(e,"image",""),l=n(e,"offset.x",0),u=n(e,"offset.y",0),c=n(e,"spacing.x",0),d=n(e,"spacing.y",0),f=n(e,"lineSpacing",0),p=n(e,"charsPerRow",null);null===p&&(p=t.sys.textures.getFrame(h).width/i)>a.length&&(p=a.length);for(var g=l,v=u,y={retroFont:!0,font:h,size:i,lineHeight:s+f,chars:{}},m=0,x=0;x0&&r.maxLines1&&(d+=f*(h-1)),{width:a,height:d,lines:h,lineWidths:o,lineSpacing:f,lineHeight:c}}},function(t,e,i){var n=i(2),s=i(2);n=i(1017),s=i(1018),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){if(0!==e.width&&0!==e.height){var o=e.frame,a=o.width,h=o.height,l=n.getTintAppendFloatAlpha;this.pipeline.batchTexture(e,o.glTexture,a,h,e.x,e.y,a/e.style.resolution,h/e.style.resolution,e.scaleX,e.scaleY,e.rotation,e.flipX,e.flipY,e.scrollFactorX,e.scrollFactorY,e.displayOriginX,e.displayOriginY,0,0,a,h,l(e._tintTL,s.alpha*e._alphaTL),l(e._tintTR,s.alpha*e._alphaTR),l(e._tintBL,s.alpha*e._alphaBL),l(e._tintBR,s.alpha*e._alphaBR),e._isTinted&&e.tintFill,0,0,s,r)}}},function(t,e){t.exports=function(t,e,i,n,s){0!==e.width&&0!==e.height&&t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(0),s=i(15),r=i(5),o=i(1020),a={fontFamily:["fontFamily","Courier"],fontSize:["fontSize","16px"],fontStyle:["fontStyle",""],backgroundColor:["backgroundColor",null],color:["color","#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",!1],shadowFill:["shadow.fill",!1],align:["align","left"],maxLines:["maxLines",0],fixedWidth:["fixedWidth",0],fixedHeight:["fixedHeight",0],resolution:["resolution",0],rtl:["rtl",!1],testString:["testString","|MÉqgy"],baselineX:["baselineX",1.2],baselineY:["baselineY",1.4],wordWrapWidth:["wordWrap.width",null],wordWrapCallback:["wordWrap.callback",null],wordWrapCallbackScope:["wordWrap.callbackScope",null],wordWrapUseAdvanced:["wordWrap.useAdvancedWrap",!1]},h=new n({initialize:function(t,e){this.parent=t,this.fontFamily,this.fontSize,this.fontStyle,this.backgroundColor,this.color,this.stroke,this.strokeThickness,this.shadowOffsetX,this.shadowOffsetY,this.shadowColor,this.shadowBlur,this.shadowStroke,this.shadowFill,this.align,this.maxLines,this.fixedWidth,this.fixedHeight,this.resolution,this.rtl,this.testString,this.baselineX,this.baselineY,this._font,this.setStyle(e,!1,!0);var i=r(e,"metrics",!1);this.metrics=i?{ascent:r(i,"ascent",0),descent:r(i,"descent",0),fontSize:r(i,"fontSize",0)}:o(this)},setStyle:function(t,e,i){for(var n in void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px"),a){var o=i?a[n][1]:this[n];this[n]="wordWrapCallback"===n||"wordWrapCallbackScope"===n?r(t,a[n][0],o):s(t,a[n][0],o)}var h=r(t,"font",null);null!==h&&this.setFont(h,!1),this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim();var l=r(t,"fill",null);return null!==l&&(this.color=l),e?this.update(!0):this.parent},syncFont:function(t,e){e.font=this._font},syncStyle:function(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"},syncShadow:function(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)},update:function(t){return t&&(this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim(),this.metrics=o(this)),this.parent.updateText()},setFont:function(t,e){void 0===e&&(e=!0);var i=t,n="",s="";if("string"!=typeof t)i=r(t,"fontFamily","Courier"),n=r(t,"fontSize","16px"),s=r(t,"fontStyle","");else{var o=t.split(" "),a=0;s=o.length>2?o[a++]:"",n=o[a++]||"16px",i=o[a++]||"Courier"}return i===this.fontFamily&&n===this.fontSize&&s===this.fontStyle||(this.fontFamily=i,this.fontSize=n,this.fontStyle=s,e&&this.update(!0)),this.parent},setFontFamily:function(t){return this.fontFamily!==t&&(this.fontFamily=t,this.update(!0)),this.parent},setFontStyle:function(t){return this.fontStyle!==t&&(this.fontStyle=t,this.update(!0)),this.parent},setFontSize:function(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize!==t&&(this.fontSize=t,this.update(!0)),this.parent},setTestString:function(t){return this.testString=t,this.update(!0)},setFixedSize:function(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(!1)},setBackgroundColor:function(t){return this.backgroundColor=t,this.update(!1)},setFill:function(t){return this.color=t,this.update(!1)},setColor:function(t){return this.color=t,this.update(!1)},setResolution:function(t){return this.resolution=t,this.update(!1)},setStroke:function(t,e){return void 0===e&&(e=this.strokeThickness),void 0===t&&0!==this.strokeThickness?(this.strokeThickness=0,this.update(!0)):this.stroke===t&&this.strokeThickness===e||(this.stroke=t,this.strokeThickness=e,this.update(!0)),this.parent},setShadow:function(t,e,i,n,s,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===n&&(n=0),void 0===s&&(s=!1),void 0===r&&(r=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=i,this.shadowBlur=n,this.shadowStroke=s,this.shadowFill=r,this.update(!1)},setShadowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)},setShadowColor:function(t){return void 0===t&&(t="#000"),this.shadowColor=t,this.update(!1)},setShadowBlur:function(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)},setShadowStroke:function(t){return this.shadowStroke=t,this.update(!1)},setShadowFill:function(t){return this.shadowFill=t,this.update(!1)},setWordWrapWidth:function(t,e){return void 0===e&&(e=!1),this.wordWrapWidth=t,this.wordWrapUseAdvanced=e,this.update(!1)},setWordWrapCallback:function(t,e){return void 0===e&&(e=null),this.wordWrapCallback=t,this.wordWrapCallbackScope=e,this.update(!1)},setAlign:function(t){return void 0===t&&(t="left"),this.align=t,this.update(!1)},setMaxLines:function(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)},getTextMetrics:function(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}},toJSON:function(){var t={};for(var e in a)t[e]=this[e];return t.metrics=this.getTextMetrics(),t},destroy:function(){this.parent=void 0}});t.exports=h},function(t,e,i){var n=i(28);t.exports=function(t){var e=n.create(this),i=e.getContext("2d");t.syncFont(e,i);var s=Math.ceil(i.measureText(t.testString).width*t.baselineX),r=s,o=2*r;r=r*t.baselineY|0,e.width=s,e.height=o,i.fillStyle="#f00",i.fillRect(0,0,s,o),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,r);var a={ascent:0,descent:0,fontSize:0};if(!i.getImageData(0,0,s,o))return a.ascent=r,a.descent=r+6,a.fontSize=a.ascent+a.descent,n.remove(e),a;var h,l,u=i.getImageData(0,0,s,o).data,c=u.length,d=4*s,f=0,p=!1;for(h=0;hr;h--){for(l=0;l0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.fillColor,e.fillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.altFillColor,e.altFillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0){var R=o.strokeTint,L=n.getTintAppendFloatAlphaAndSwap(e.outlineFillColor,e.outlineFillAlpha*d);for(R.TL=L,R.TR=L,R.BL=L,R.BR=L,_=1;_0)for(n(h,e),_=0;_0)for(n(h,e,e.altFillColor,e.altFillAlpha*c),_=0;_0){for(s(h,e,e.outlineFillColor,e.outlineFillAlpha*c),A=1;Ao.vertexCapacity&&o.flush(),o.setTexture2D(u,0);for(var y=o.vertexViewF32,m=o.vertexViewU32,x=o.vertexCount*o.vertexComponentCount-1,T=0,w=e.tintFill,b=0;b0?Math.PI*t.radius*t.radius:0}},function(t,e,i){var n=i(71);t.exports=function(t){return new n(t.x,t.y,t.radius)}},function(t,e,i){var n=i(60);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(60);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.radius)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.radius===e.radius}},function(t,e,i){var n=i(11);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.diameter,e.height=t.diameter,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(107);n.Area=i(1126),n.Circumference=i(423),n.CircumferencePoint=i(206),n.Clone=i(1127),n.Contains=i(108),n.ContainsPoint=i(1128),n.ContainsRect=i(1129),n.CopyFrom=i(1130),n.Equals=i(1131),n.GetBounds=i(1132),n.GetPoint=i(421),n.GetPoints=i(422),n.Offset=i(1133),n.OffsetPoint=i(1134),n.Random=i(167),t.exports=n},function(t,e){t.exports=function(t){return t.isEmpty()?0:t.getMajorRadius()*t.getMinorRadius()*Math.PI}},function(t,e,i){var n=i(107);t.exports=function(t){return new n(t.x,t.y,t.width,t.height)}},function(t,e,i){var n=i(108);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(108);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.width,t.height)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}},function(t,e,i){var n=i(11);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.width,e.height=t.height,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(4),s=i(217);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a,h,l=t.x,u=t.y,c=t.radius,d=e.x,f=e.y,p=e.radius;if(u===f)0==(a=(o=-2*f)*o-4*(r=1)*(d*d+(h=(p*p-c*c-d*d+l*l)/(2*(l-d)))*h-2*d*h+f*f-p*p))?i.push(new n(h,-o/(2*r))):a>0&&(i.push(new n(h,(-o+Math.sqrt(a))/(2*r))),i.push(new n(h,(-o-Math.sqrt(a))/(2*r))));else{var g=(l-d)/(u-f),v=(p*p-c*c-d*d+l*l-f*f+u*u)/(2*(u-f));0==(a=(o=2*u*g-2*v*g-2*l)*o-4*(r=g*g+1)*(l*l+u*u+v*v-c*c-2*u*v))?(h=-o/(2*r),i.push(new n(h,v-h*g))):a>0&&(h=(-o+Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)),h=(-o-Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)))}}return i}},function(t,e,i){var n=i(219),s=i(218);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC(),h=e.getLineD();n(r,t,i),n(o,t,i),n(a,t,i),n(h,t,i)}return i}},function(t,e,i){var n=i(11),s=i(140);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i}},function(t,e,i){var n=i(221),s=i(140);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC(),h=t.getLineD();n(r,e,i),n(o,e,i),n(a,e,i),n(h,e,i)}return i}},function(t,e,i){var n=i(456),s=i(221);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(r,t,i),s(o,t,i),s(a,t,i)}return i}},function(t,e,i){var n=i(219),s=i(458);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC();n(r,e,i),n(o,e,i),n(a,e,i)}return i}},function(t,e,i){var n=i(461),s=i(459);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(t,r,i),s(t,o,i),s(t,a,i)}return i}},function(t,e,i){var n=i(463);t.exports=function(t,e){if(!n(t,e))return!1;var i=Math.min(e.x1,e.x2),s=Math.max(e.x1,e.x2),r=Math.min(e.y1,e.y2),o=Math.max(e.y1,e.y2);return t.x>=i&&t.x<=s&&t.y>=r&&t.y<=o}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||si&&(i=h.x),h.xr&&(r=h.y),h.yn(e)?t.setSize(e.height*i,e.height):t.setSize(e.width,e.width/i),t.setPosition(e.centerX-t.width/2,e.centerY-t.height/2)}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t.width=Math.floor(t.width),t.height=Math.floor(t.height),t}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.centerX,e.y=t.centerY,e}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.width,e.y=t.height,e}},function(t,e,i){var n=i(178);t.exports=function(t,e,i){var s=t.centerX,r=t.centerY;return t.setSize(t.width+2*e,t.height+2*i),n(t,s,r)}},function(t,e,i){var n=i(11),s=i(140);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)?(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y):i.setEmpty(),i}},function(t,e){t.exports=function(t,e){for(var i=t.x,n=t.right,s=t.y,r=t.bottom,o=0;oe.x&&t.ye.y}},function(t,e,i){var n=i(4),s=i(40);t.exports=function(t,e,i){void 0===i&&(i=new n),e=s(e);var r=Math.sin(e),o=Math.cos(e),a=o>0?t.width/2:t.width/-2,h=r>0?t.height/2:t.height/-2;return Math.abs(a*r)-1&&(s.splice(a,1),this.clear(o,!0))}t.length=0,this._pendingRemoval.length=0,this._list=s.concat(e.splice(0))}},isActive:function(){return this.enabled&&this.scene.sys.isActive()},updatePoll:function(t,e){if(!this.isActive())return!1;if(this.pluginEvents.emit(d.UPDATE,t,e),this._updatedThisFrame)return this._updatedThisFrame=!1,!1;var i,n=this.manager,s=n.pointers,r=n.pointersTotal;for(i=0;i0){if(this._pollTimer-=e,!(this._pollTimer<0))return!1;this._pollTimer=this.pollRate}var a=!1;for(i=0;i0&&(a=!0)}return a},update:function(t,e){if(!this.isActive())return!1;for(var i=e.length,n=!1,s=0;s0&&(n=!0)}return this._updatedThisFrame=!0,n},clear:function(t,e){void 0===e&&(e=!1);var i=t.input;if(i){e||this.queueForRemoval(t),i.gameObject=void 0,i.target=void 0,i.hitArea=void 0,i.hitAreaCallback=void 0,i.callbackContext=void 0,this.manager.resetCursor(i),t.input=null;var n=this._draggable.indexOf(t);return n>-1&&this._draggable.splice(n,1),(n=this._drag[0].indexOf(t))>-1&&this._drag[0].splice(n,1),(n=this._over[0].indexOf(t))>-1&&this._over[0].splice(n,1),t}},disable:function(t){t.input.enabled=!1},enable:function(t,e,i,n){return void 0===n&&(n=!1),t.input?t.input.enabled=!0:this.setHitArea(t,e,i),t.input&&n&&!t.input.dropZone&&(t.input.dropZone=n),this},hitTestPointer:function(t){for(var e=this.cameras.getCamerasBelowPointer(t),i=0;i0)return t.camera=n,s}return t.camera=e[0],[]},processDownEvents:function(t){var e=0,i=this._temp,n=this._eventData,s=this._eventContainer;n.cancelled=!1;for(var r=!1,o=0;o0&&l(t.x,t.y,t.downX,t.downY)>=s?i=!0:n>0&&e>=t.downTime+n&&(i=!0),i)return this.setDragState(t,3),this.processDragStartList(t)},processDragStartList:function(t){if(3!==this.getDragState(t))return 0;for(var e=this._drag[t.id],i=0;i1&&(this.sortGameObjects(i),this.topOnly&&i.splice(1)),this._drag[t.id]=i,0===this.dragDistanceThreshold&&0===this.dragTimeThreshold?(this.setDragState(t,3),this.processDragStartList(t)):(this.setDragState(t,2),0))},processDragMoveEvent:function(t){if(2===this.getDragState(t)&&this.processDragThresholdEvent(t,this.manager.game.loop.now),4!==this.getDragState(t))return 0;for(var e=this._tempZones,i=this._drag[t.id],n=0;n0?(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),e[0]?(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):a.target=null)}else!h&&e[0]&&(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h));if(o.parentContainer){var u=t.x-a.dragStartXGlobal,c=t.y-a.dragStartYGlobal,f=o.getParentRotation(),p=u*Math.cos(f)+c*Math.sin(f),g=c*Math.cos(f)-u*Math.sin(f);p*=1/o.parentContainer.scaleX,g*=1/o.parentContainer.scaleY,s=p+a.dragStartX,r=g+a.dragStartY}else s=t.x-a.dragX,r=t.y-a.dragY;o.emit(d.GAMEOBJECT_DRAG,t,s,r),this.emit(d.DRAG,t,o,s,r)}return i.length},processDragUpEvent:function(t){for(var e=this._drag[t.id],i=0;i0){var r=this.manager,o=this._eventData,a=this._eventContainer;o.cancelled=!1;for(var h=!1,l=0;l0){var s=this.manager,r=this._eventData,o=this._eventContainer;r.cancelled=!1;var a=!1;this.sortGameObjects(e);for(var h=0;h0){for(this.sortGameObjects(s),e=0;e0){for(this.sortGameObjects(r),e=0;e-1&&this._draggable.splice(s,1)}return this},makePixelPerfect:function(t){void 0===t&&(t=1);var e=this.systems.textures;return h(e,t)},setHitArea:function(t,e,i){if(void 0===e)return this.setHitAreaFromTexture(t);Array.isArray(t)||(t=[t]);var n=!1,s=!1,r=!1,o=!1,h=!1,l=!0;if(y(e)){var u=e;e=p(u,"hitArea",null),i=p(u,"hitAreaCallback",null),n=p(u,"draggable",!1),s=p(u,"dropZone",!1),r=p(u,"cursor",!1),o=p(u,"useHandCursor",!1),h=p(u,"pixelPerfect",!1);var c=p(u,"alphaTolerance",1);h&&(e={},i=this.makePixelPerfect(c)),e&&i||(this.setHitAreaFromTexture(t),l=!1)}else"function"!=typeof e||i||(i=e,e={});for(var d=0;d=e}}},function(t,e,i){t.exports={Events:i(142),KeyboardManager:i(390),KeyboardPlugin:i(1247),Key:i(476),KeyCodes:i(131),KeyCombo:i(477),JustDown:i(1252),JustUp:i(1253),DownDuration:i(1254),UpDuration:i(1255)}},function(t,e){t.exports="keydown"},function(t,e){t.exports="keyup"},function(t,e){t.exports="keycombomatch"},function(t,e){t.exports="down"},function(t,e){t.exports="keydown-"},function(t,e){t.exports="keyup-"},function(t,e){t.exports="up"},function(t,e,i){var n=i(0),s=i(9),r=i(142),o=i(21),a=i(5),h=i(56),l=i(141),u=i(476),c=i(131),d=i(477),f=i(1251),p=i(105),g=new n({Extends:s,initialize:function(t){s.call(this),this.game=t.systems.game,this.scene=t.scene,this.settings=this.scene.sys.settings,this.sceneInputPlugin=t,this.manager=t.manager.keyboard,this.enabled=!0,this.keys=[],this.combos=[],t.pluginEvents.once(h.BOOT,this.boot,this),t.pluginEvents.on(h.START,this.start,this)},boot:function(){var t=this.settings.input;this.enabled=a(t,"keyboard",!0);var e=a(t,"keyboard.capture",null);e&&this.addCaptures(e),this.sceneInputPlugin.pluginEvents.once(h.DESTROY,this.destroy,this)},start:function(){this.sceneInputPlugin.manager.useQueue?this.sceneInputPlugin.pluginEvents.on(h.UPDATE,this.update,this):this.sceneInputPlugin.manager.events.on(h.MANAGER_PROCESS,this.update,this),this.sceneInputPlugin.pluginEvents.once(h.SHUTDOWN,this.shutdown,this),this.game.events.on(o.BLUR,this.resetKeys,this)},isActive:function(){return this.enabled&&this.scene.sys.isActive()},addCapture:function(t){return this.manager.addCapture(t),this},removeCapture:function(t){return this.manager.removeCapture(t),this},getCaptures:function(){return this.manager.captures},enableGlobalCapture:function(){return this.manager.preventDefault=!0,this},disableGlobalCapture:function(){return this.manager.preventDefault=!1,this},clearCaptures:function(){return this.manager.clearCaptures(),this},createCursorKeys:function(){return this.addKeys({up:c.UP,down:c.DOWN,left:c.LEFT,right:c.RIGHT,space:c.SPACE,shift:c.SHIFT})},addKeys:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1);var n={};if("string"==typeof t){t=t.split(",");for(var s=0;s-1?n[s]=t:n[t.keyCode]=t,e&&this.addCapture(t.keyCode),t.setEmitOnRepeat(i),t}return"string"==typeof t&&(t=c[t.toUpperCase()]),n[t]||(n[t]=new u(this,t),e&&this.addCapture(t),n[t].setEmitOnRepeat(i)),n[t]},removeKey:function(t,e){void 0===e&&(e=!1);var i,n=this.keys;if(t instanceof u){var s=n.indexOf(t);s>-1&&(i=this.keys[s],this.keys[s]=void 0)}else"string"==typeof t&&(t=c[t.toUpperCase()]);return n[t]&&(i=n[t],n[t]=void 0),i&&(i.plugin=null,e&&i.destroy()),this},createCombo:function(t,e){return new d(this,t,e)},checkDown:function(t,e){if(this.enabled&&t.isDown){var i=p(this.time-t.timeDown,e);if(i>t._tick)return t._tick=i,!0}return!1},update:function(){var t=this.manager.queue,e=t.length;if(this.isActive()&&0!==e)for(var i=this.keys,n=0;n0&&e.maxKeyDelay>0){var r=e.timeLastMatched+e.maxKeyDelay;t.timeStamp<=r&&(s=!0,i=n(t,e))}else s=!0,i=n(t,e);return!s&&e.resetOnWrongKey&&(e.index=0,e.current=e.keyCodes[0]),i&&(e.timeLastMatched=t.timeStamp,e.matched=!0,e.timeMatched=t.timeStamp),i}},function(t,e){t.exports=function(t,e){return e.timeLastMatched=t.timeStamp,e.index++,e.index===e.size||(e.current=e.keyCodes[e.index],!1)}},function(t,e){t.exports=function(t){return t.current=t.keyCodes[0],t.index=0,t.timeLastMatched=0,t.matched=!1,t.timeMatched=0,t}},function(t,e,i){var n=i(131),s={};for(var r in n)s[n[r]]=r;t.exports=s},function(t,e){t.exports=function(t){return!!t._justDown&&(t._justDown=!1,!0)}},function(t,e){t.exports=function(t){return!!t._justUp&&(t._justUp=!1,!0)}},function(t,e){t.exports=function(t,e){void 0===e&&(e=50);var i=t.plugin.game.loop.time-t.timeDown;return t.isDown&&i'),i.push(''),i.push(''),i.push(this.xhrLoader.responseText),i.push(""),i.push(""),i.push("");var n=[i.join("\n")],o=this;try{var a=new window.Blob(n,{type:"image/svg+xml;charset=utf-8"})}catch(t){return o.state=s.FILE_ERRORED,void o.onProcessComplete()}this.data=new Image,this.data.crossOrigin=this.crossOrigin,this.data.onload=function(){r.revokeObjectURL(o.data),o.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(o.data),o.onProcessError()},r.createObjectURL(this.data,a,"image/svg+xml")},addToCache:function(){var t=this.cache.addImage(this.key,this.data);this.pendingDestroy(t)}});o.register("htmlTexture",function(t,e,i,n,s){if(Array.isArray(t))for(var r=0;r0},isLoading:function(){return this.state===s.LOADER_LOADING||this.state===s.LOADER_PROCESSING},isReady:function(){return this.state===s.LOADER_IDLE||this.state===s.LOADER_COMPLETE},start:function(){this.isReady()&&(this.progress=0,this.totalFailed=0,this.totalComplete=0,this.totalToLoad=this.list.size,this.emit(a.START,this),0===this.list.size?this.loadComplete():(this.state=s.LOADER_LOADING,this.inflight.clear(),this.queue.clear(),this.updateProgress(),this.checkLoadQueue(),this.systems.events.on(c.UPDATE,this.update,this)))},updateProgress:function(){this.progress=1-(this.list.size+this.inflight.size)/this.totalToLoad,this.emit(a.PROGRESS,this.progress)},update:function(){this.state===s.LOADER_LOADING&&this.list.size>0&&this.inflight.sizei&&(n=l,i=c)}}return n},moveTo:function(t,e,i,n,s){void 0===n&&(n=60),void 0===s&&(s=0);var o=Math.atan2(i-t.y,e-t.x);return s>0&&(n=r(t.x,t.y,e,i)/(s/1e3)),t.body.velocity.setToPolar(o,n),o},moveToObject:function(t,e,i,n){return this.moveTo(t,e.x,e.y,i,n)},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(s(t),e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(t,e)},overlapRect:function(t,e,i,n,s,r){return c(this.world,t,e,i,n,s,r)},overlapCirc:function(t,e,i,n,s){return u(this.world,t,e,i,n,s)},shutdown:function(){if(this.world){var t=this.systems.events;t.off(f.UPDATE,this.world.update,this.world),t.off(f.POST_UPDATE,this.world.postUpdate,this.world),t.off(f.SHUTDOWN,this.shutdown,this),this.add.destroy(),this.world.destroy(),this.add=null,this.world=null}},destroy:function(){this.shutdown(),this.scene.sys.events.off(f.START,this.start,this),this.scene=null,this.systems=null}});d.register("ArcadePhysics",v,"arcadePhysics"),t.exports=v},function(t,e){t.exports={setAcceleration:function(t,e){return this.body.acceleration.set(t,e),this},setAccelerationX:function(t){return this.body.acceleration.x=t,this},setAccelerationY:function(t){return this.body.acceleration.y=t,this}}},function(t,e){t.exports={setAngularVelocity:function(t){return this.body.angularVelocity=t,this},setAngularAcceleration:function(t){return this.body.angularAcceleration=t,this},setAngularDrag:function(t){return this.body.angularDrag=t,this}}},function(t,e){t.exports={setBounce:function(t,e){return this.body.bounce.set(t,e),this},setBounceX:function(t){return this.body.bounce.x=t,this},setBounceY:function(t){return this.body.bounce.y=t,this},setCollideWorldBounds:function(t,e,i){return this.body.setCollideWorldBounds(t,e,i),this}}},function(t,e){t.exports={setDebug:function(t,e,i){return this.debugShowBody=t,this.debugShowVelocity=e,this.debugBodyColor=i,this},setDebugBodyColor:function(t){return this.body.debugBodyColor=t,this},debugShowBody:{get:function(){return this.body.debugShowBody},set:function(t){this.body.debugShowBody=t}},debugShowVelocity:{get:function(){return this.body.debugShowVelocity},set:function(t){this.body.debugShowVelocity=t}},debugBodyColor:{get:function(){return this.body.debugBodyColor},set:function(t){this.body.debugBodyColor=t}}}},function(t,e){t.exports={setDrag:function(t,e){return this.body.drag.set(t,e),this},setDragX:function(t){return this.body.drag.x=t,this},setDragY:function(t){return this.body.drag.y=t,this},setDamping:function(t){return this.body.useDamping=t,this}}},function(t,e){var i={enableBody:function(t,e,i,n,s){return t&&this.body.reset(e,i),n&&(this.body.gameObject.active=!0),s&&(this.body.gameObject.visible=!0),this.body.enable=!0,this},disableBody:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=!1),this.body.stop(),this.body.enable=!1,t&&(this.body.gameObject.active=!1),e&&(this.body.gameObject.visible=!1),this},refreshBody:function(){return this.body.updateFromGameObject(),this}};t.exports=i},function(t,e){t.exports={setFriction:function(t,e){return this.body.friction.set(t,e),this},setFrictionX:function(t){return this.body.friction.x=t,this},setFrictionY:function(t){return this.body.friction.y=t,this}}},function(t,e){t.exports={setGravity:function(t,e){return this.body.gravity.set(t,e),this},setGravityX:function(t){return this.body.gravity.x=t,this},setGravityY:function(t){return this.body.gravity.y=t,this}}},function(t,e){var i={setImmovable:function(t){return void 0===t&&(t=!0),this.body.immovable=t,this}};t.exports=i},function(t,e){t.exports={setMass:function(t){return this.body.mass=t,this}}},function(t,e){t.exports={setOffset:function(t,e){return this.body.setOffset(t,e),this},setSize:function(t,e,i){return this.body.setSize(t,e,i),this},setCircle:function(t,e,i){return this.body.setCircle(t,e,i),this}}},function(t,e){t.exports={setVelocity:function(t,e){return this.body.setVelocity(t,e),this},setVelocityX:function(t){return this.body.setVelocityX(t),this},setVelocityY:function(t){return this.body.setVelocityY(t),this},setMaxVelocity:function(t,e){return this.body.maxVelocity.set(t,e),this}}},function(t,e,i){var n=i(487),s=i(71),r=i(217),o=i(218);t.exports=function(t,e,i,a,h,l){var u=n(t,e-a,i-a,2*a,2*a,h,l);if(0===u.length)return u;for(var c=new s(e,i,a),d=new s,f=[],p=0;pe.deltaAbsY()?m=-1:e.deltaAbsX()0&&u&&t.checkCollision.right&&h&&t.right>i&&(a=t.right-i)>r&&(a=0),0!==a&&(t.customSeparateX?t.overlapX=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.left=!0):e>0&&(t.blocked.none=!1,t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x}},function(t,e,i){var n=i(1313);t.exports=function(t,e,i,s,r,o){var a=0,h=e.faceTop,l=e.faceBottom,u=e.collideUp,c=e.collideDown;return o||(h=!0,l=!0,u=!0,c=!0),t.deltaY()<0&&c&&t.checkCollision.up?l&&t.y0&&u&&t.checkCollision.down&&h&&t.bottom>i&&(a=t.bottom-i)>r&&(a=0),0!==a&&(t.customSeparateY?t.overlapY=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.up=!0):e>0&&(t.blocked.none=!1,t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},function(t,e,i){var n=i(491);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.x,a=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=r,e.velocity.x=o-a*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=r,t.velocity.x=a-o*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{r*=.5,t.x-=r,e.x+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.x=u+h*t.bounce.x,e.velocity.x=u+l*e.bounce.x}return!0}},function(t,e,i){var n=i(492);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.y,a=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=r,e.velocity.y=o-a*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=r,t.velocity.y=a-o*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{r*=.5,t.y-=r,e.y+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.y=u+h*t.bounce.y,e.velocity.y=u+l*e.bounce.y}return!0}},function(t,e,i){t.exports={Body:i(496),Events:i(231),COLLIDES:i(112),CollisionMap:i(497),Factory:i(498),Image:i(500),ImpactBody:i(499),ImpactPhysics:i(1335),Sprite:i(501),TYPE:i(113),World:i(502)}},function(t,e,i){var n=i(20);t.exports=function(t,e,i,s,r){if(i)return n(e+i*t,-r,r);if(s){var o=s*t;return e-o>0?e-o:e+o<0?e+o:0}return n(e,-r,r)}},function(t,e){t.exports=function(t,e){if(t.standing=!1,e.collision.y&&(t.bounciness>0&&Math.abs(t.vel.y)>t.minBounceVelocity?t.vel.y*=-t.bounciness:(t.vel.y>0&&(t.standing=!0),t.vel.y=0)),e.collision.x&&(t.bounciness>0&&Math.abs(t.vel.x)>t.minBounceVelocity?t.vel.x*=-t.bounciness:t.vel.x=0),e.collision.slope){var i=e.collision.slope;if(t.bounciness>0){var n=t.vel.x*i.nx+t.vel.y*i.ny;t.vel.x=(t.vel.x-i.nx*n*2)*t.bounciness,t.vel.y=(t.vel.y-i.ny*n*2)*t.bounciness}else{var s=i.x*i.x+i.y*i.y,r=(t.vel.x*i.x+t.vel.y*i.y)/s;t.vel.x=i.x*r,t.vel.y=i.y*r;var o=Math.atan2(i.x,i.y);o>t.slopeStanding.min&&oi.last.x&&e.last.xi.last.y&&e.last.y0))r=t.collisionMap.trace(e.pos.x,e.pos.y,0,-(e.pos.y+e.size.y-i.pos.y),e.size.x,e.size.y),e.pos.y=r.pos.y,e.bounciness>0&&e.vel.y>e.minBounceVelocity?e.vel.y*=-e.bounciness:(e.standing=!0,e.vel.y=0);else{var l=(e.vel.y-i.vel.y)/2;e.vel.y=-l,i.vel.y=l,s=i.vel.x*t.delta,r=t.collisionMap.trace(e.pos.x,e.pos.y,s,-o/2,e.size.x,e.size.y),e.pos.y=r.pos.y;var u=t.collisionMap.trace(i.pos.x,i.pos.y,0,o/2,i.size.x,i.size.y);i.pos.y=u.pos.y}}},function(t,e,i){t.exports={BodyBounds:i(503),Factory:i(504),Image:i(506),Matter:i(239),MatterPhysics:i(1371),PolyDecomp:i(505),Sprite:i(507),TileBody:i(238),PhysicsEditorParser:i(235),PhysicsJSONParser:i(236),World:i(511)}},function(t,e,i){var n=i(147),s=i(1),r=i(3);t.exports=function(t,e,i,o){void 0===i&&(i={}),void 0===o&&(o=!0);var a=e.x,h=e.y;if(e.body={temp:!0,position:{x:a,y:h}},[n.Bounce,n.Collision,n.Force,n.Friction,n.Gravity,n.Mass,n.Sensor,n.SetBody,n.Sleep,n.Static,n.Transform,n.Velocity].forEach(function(t){for(var i in t)(n=t[i]).get&&"function"==typeof n.get||n.set&&"function"==typeof n.set?Object.defineProperty(e,i,{get:t[i].get,set:t[i].set}):Object.defineProperty(e,i,{value:t[i]});var n}),e.world=t,e._tempVec2=new r(a,h),i.hasOwnProperty("type")&&"body"===i.type)e.setExistingBody(i,o);else{var l=s(i,"shape",null);l||(l="rectangle"),i.addToWorld=o,e.setBody(l,i)}return e}},function(t,e){t.exports={setBounce:function(t){return this.body.restitution=t,this}}},function(t,e){var i={setCollisionCategory:function(t){return this.body.collisionFilter.category=t,this},setCollisionGroup:function(t){return this.body.collisionFilter.group=t,this},setCollidesWith:function(t){var e=0;if(Array.isArray(t))for(var i=0;i1?1:0;s0},intersectPoint:function(t,e,i){i=this.getMatterBodies(i);var n=D.create(t,e),s=[];return M.point(i,n).forEach(function(t){-1===s.indexOf(t)&&s.push(t)}),s},intersectRect:function(t,e,i,n,s,r){void 0===s&&(s=!1),r=this.getMatterBodies(r);var o={min:{x:t,y:e},max:{x:t+i,y:e+n}},a=[];return M.region(r,o,s).forEach(function(t){-1===a.indexOf(t)&&a.push(t)}),a},intersectRay:function(t,e,i,n,s,r){void 0===s&&(s=1),r=this.getMatterBodies(r);for(var o=[],a=M.ray(r,D.create(t,e),D.create(i,n),s),h=0;h0)for(var a=s+1;ae.max.x?i=e.min.x-t.max.x:t.max.xe.max.y?n=e.min.y-t.max.y:t.max.y=this._duration&&this.transitionComplete()},transitionComplete:function(){var t=this._target.sys,e=this._target.sys.settings;this.systems.events.off(r.UPDATE,this.step,this),t.events.emit(r.TRANSITION_COMPLETE,this.scene),e.isTransition=!1,e.transitionFrom=null,this._duration=0,this._target=null,this._onUpdate=null,this._onUpdateScope=null,this._willRemove?this.manager.remove(this.key):this._willSleep?this.systems.sleep():this.manager.stop(this.key)},add:function(t,e,i,n){return this.manager.add(t,e,i,n)},launch:function(t,e){return t&&t!==this.key&&this.manager.queueOp("start",t,e),this},run:function(t,e){return t&&t!==this.key&&this.manager.queueOp("run",t,e),this},pause:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("pause",t,e),this},resume:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("resume",t,e),this},sleep:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("sleep",t,e),this},wake:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("wake",t,e),this},switch:function(t){return t!==this.key&&this.manager.queueOp("switch",this.key,t),this},stop:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",t,e),this},setActive:function(t,e,i){void 0===e&&(e=this.key);var n=this.manager.getScene(e);return n&&n.sys.setActive(t,i),this},setVisible:function(t,e){void 0===e&&(e=this.key);var i=this.manager.getScene(e);return i&&i.sys.setVisible(t),this},isSleeping:function(t){return void 0===t&&(t=this.key),this.manager.isSleeping(t)},isActive:function(t){return void 0===t&&(t=this.key),this.manager.isActive(t)},isPaused:function(t){return void 0===t&&(t=this.key),this.manager.isPaused(t)},isVisible:function(t){return void 0===t&&(t=this.key),this.manager.isVisible(t)},swapPosition:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.swapPosition(t,e),this},moveAbove:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveAbove(t,e),this},moveBelow:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveBelow(t,e),this},remove:function(t){return void 0===t&&(t=this.key),this.manager.remove(t),this},moveUp:function(t){return void 0===t&&(t=this.key),this.manager.moveUp(t),this},moveDown:function(t){return void 0===t&&(t=this.key),this.manager.moveDown(t),this},bringToTop:function(t){return void 0===t&&(t=this.key),this.manager.bringToTop(t),this},sendToBack:function(t){return void 0===t&&(t=this.key),this.manager.sendToBack(t),this},get:function(t){return this.manager.getScene(t)},getIndex:function(t){return void 0===t&&(t=this.key),this.manager.getIndex(t)},shutdown:function(){var t=this.systems.events;t.off(r.SHUTDOWN,this.shutdown,this),t.off(r.POST_UPDATE,this.step,this),t.off(r.TRANSITION_OUT)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.settings=null,this.manager=null}});a.register("ScenePlugin",h,"scenePlugin"),t.exports=h},function(t,e,i){t.exports={List:i(135),Map:i(172),ProcessQueue:i(199),RTree:i(493),Set:i(110),Size:i(396)}},function(t,e,i){var n=i(17),s=i(1387),r={CanvasTexture:i(401),Events:i(128),FilterMode:s,Frame:i(106),Parsers:i(403),Texture:i(195),TextureManager:i(400),TextureSource:i(402)};r=n(!1,r,s),t.exports=r},function(t,e){t.exports={LINEAR:0,NEAREST:1}},function(t,e,i){t.exports={Components:i(150),Parsers:i(1418),Formats:i(34),ImageCollection:i(523),ParseToTilemap:i(252),Tile:i(80),Tilemap:i(532),TilemapCreator:i(1427),TilemapFactory:i(1428),Tileset:i(154),LayerData:i(116),MapData:i(117),ObjectLayer:i(526),DynamicTilemapLayer:i(533),StaticTilemapLayer:i(534)}},function(t,e,i){var n=i(26),s=i(59);t.exports=function(t,e,i,r,o,a,h,l){t<0&&(t=0),e<0&&(e=0),void 0===h&&(h=!0);for(var u=n(t,e,i,r,null,l),c=o-t,d=a-e,f=0;f=0&&p=0&&g=v;o--)(h=c[a][o])&&-1!==h.index&&h.visible&&0!==h.alpha&&i.push(h);else if(2===r)for(a=x;a>=m;a--)for(o=v;c[a]&&o=m;a--)for(o=y;c[a]&&o>=v;o--)(h=c[a][o])&&-1!==h.index&&h.visible&&0!==h.alpha&&i.push(h);return u.tilesDrawn=i.length,u.tilesTotal=d*f,i}},function(t,e,i){var n=i(26),s=i(59),r=i(79);t.exports=function(t,e,i,o,a,h,l){for(var u=-1!==l.collideIndexes.indexOf(t),c=n(e,i,o,a,null,l),d=0;d=0;r--)for(s=n.width-1;s>=0;s--)if((o=n.data[r][s])&&o.index===t){if(a===e)return o;a+=1}}else for(r=0;re)){for(var l=t;l<=e;l++)r(l,i,a);if(h)for(var u=0;u=t&&d.index<=e&&n(d,i)}o&&s(0,0,a.width,a.height,a)}}},function(t,e,i){var n=i(79),s=i(59),r=i(247);t.exports=function(t,e,i,o){void 0===e&&(e=!0),void 0===i&&(i=!0),Array.isArray(t)||(t=[t]);for(var a=0;a0&&n(a,t)}}e&&s(0,0,i.width,i.height,i)}},function(t,e){t.exports=function(t,e,i,n){if("number"==typeof t)n.callbacks[t]=null!==e?{callback:e,callbackContext:i}:void 0;else for(var s=0,r=t.length;s1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f0&&(t.currentPipeline&&t.currentPipeline.vertexCount>0&&t.flush(),r.vertexBuffer=e.vertexBuffer[a],t.setPipeline(r),t.setTexture2D(s[a].glTexture,0),t.gl.drawArrays(r.topology,0,e.vertexCount[a]));r.vertexBuffer=o,r.viewIdentity(),r.modelIdentity()}},function(t,e){t.exports=function(t,e,i,n,s){e.cull(n);var r=e.culledTiles,o=r.length;if(0!==o){var a=t._tempMatrix1,h=t._tempMatrix2,l=t._tempMatrix3;h.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),a.copyFrom(n.matrix);var u=t.currentContext,c=e.gidMap;u.save(),s?(a.multiplyWithOffset(s,-n.scrollX*e.scrollFactorX,-n.scrollY*e.scrollFactorY),h.e=e.x,h.f=e.y,a.multiply(h,l),l.copyToContext(u)):(h.e-=n.scrollX*e.scrollFactorX,h.f-=n.scrollY*e.scrollFactorY,h.copyToContext(u));var d=n.alpha*e.alpha;(!t.antialias||e.scaleX>1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f-1&&this._active.splice(s,1),n.destroy()}for(i=0;i=n.delay)){var s=n.elapsed-n.delay;n.elapsed=n.delay,!n.hasDispatched&&n.callback&&(n.hasDispatched=!0,n.callback.apply(n.callbackScope,n.args)),n.repeatCount>0?(n.repeatCount--,n.elapsed=s,n.hasDispatched=!1):this._pendingRemoval.push(n)}}}},shutdown:function(){var t;for(t=0;t-1&&(e.state=u.REMOVED,s.splice(r,1)):(e.state=u.REMOVED,n.splice(r,1))}for(i.length=0,i=this._add,t=0;t>2],r+=i[(3&n[o])<<4|n[o+1]>>4],r+=i[(15&n[o+1])<<2|n[o+2]>>6],r+=i[63&n[o+2]];return s%3==2?r=r.substring(0,r.length-1)+"=":s%3==1&&(r=r.substring(0,r.length-2)+"=="),r}},function(t,e,i){t.exports={Clone:i(73),Extend:i(17),GetAdvancedValue:i(15),GetFastValue:i(1),GetMinMaxValue:i(1452),GetValue:i(5),HasAll:i(1453),HasAny:i(430),HasValue:i(91),IsPlainObject:i(7),Merge:i(88),MergeRight:i(1454),Pick:i(524),SetValue:i(450)}},function(t,e,i){var n=i(5),s=i(20);t.exports=function(t,e,i,r,o){void 0===o&&(o=i);var a=n(t,e,o);return s(a,i,r)}},function(t,e){t.exports=function(t,e){for(var i=0;i - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.WebGL.Utils - * @since 3.0.0 - */ -module.exports = { - - /** - * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats - * @since 3.0.0 - * - * @param {number} r - Red component in a range from 0.0 to 1.0 - * @param {number} g - Green component in a range from 0.0 to 1.0 - * @param {number} b - Blue component in a range from 0.0 to 1.0 - * @param {number} a - Alpha component in a range from 0.0 to 1.0 - * - * @return {number} The packed RGBA values as a Uint32. - */ - getTintFromFloats: function (r, g, b, a) - { - var ur = ((r * 255.0)|0) & 0xFF; - var ug = ((g * 255.0)|0) & 0xFF; - var ub = ((b * 255.0)|0) & 0xFF; - var ua = ((a * 255.0)|0) & 0xFF; - - return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; - }, - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha - * @since 3.0.0 - * - * @param {number} rgb - Uint24 representing RGB components - * @param {number} a - Float32 representing Alpha component - * - * @return {number} Packed RGBA as Uint32 - */ - getTintAppendFloatAlpha: function (rgb, a) - { - var ua = ((a * 255.0)|0) & 0xFF; - return ((ua << 24) | rgb) >>> 0; - }, - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a - * swizzled Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap - * @since 3.0.0 - * - * @param {number} rgb - Uint24 representing RGB components - * @param {number} a - Float32 representing Alpha component - * - * @return {number} Packed RGBA as Uint32 - */ - getTintAppendFloatAlphaAndSwap: function (rgb, a) - { - var ur = ((rgb >> 16)|0) & 0xff; - var ug = ((rgb >> 8)|0) & 0xff; - var ub = (rgb|0) & 0xff; - var ua = ((a * 255.0)|0) & 0xFF; - - return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; - }, - - /** - * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 - * - * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB - * @since 3.0.0 - * - * @param {number} rgb - RGB packed as a Uint24 - * - * @return {array} Array of floats representing each component as a float - */ - getFloatsFromUintRGB: function (rgb) - { - var ur = ((rgb >> 16)|0) & 0xff; - var ug = ((rgb >> 8)|0) & 0xff; - var ub = (rgb|0) & 0xff; - - return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; - }, - - /** - * Counts how many attributes of 32 bits a vertex has - * - * @function Phaser.Renderer.WebGL.Utils.getComponentCount - * @since 3.0.0 - * - * @param {array} attributes - Array of attributes - * @param {WebGLRenderingContext} glContext - WebGLContext used for check types - * - * @return {number} Count of 32 bit attributes in vertex - */ - getComponentCount: function (attributes, glContext) - { - var count = 0; - - for (var index = 0; index < attributes.length; ++index) - { - var element = attributes[index]; - - if (element.type === glContext.FLOAT) - { - count += element.size; - } - else - { - count += 1; // We'll force any other type to be 32 bit. for now - } - } - - return count; - } - -}; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Global constants. - * - * @ignore - */ - -var CONST = { - - /** - * Phaser Release Version - * - * @name Phaser.VERSION - * @const - * @type {string} - * @since 3.0.0 - */ - VERSION: '3.23.0-beta1', - - BlendModes: __webpack_require__(52), - - ScaleModes: __webpack_require__(229), - - /** - * AUTO Detect Renderer. - * - * @name Phaser.AUTO - * @const - * @type {integer} - * @since 3.0.0 - */ - AUTO: 0, - - /** - * Canvas Renderer. - * - * @name Phaser.CANVAS - * @const - * @type {integer} - * @since 3.0.0 - */ - CANVAS: 1, - - /** - * WebGL Renderer. - * - * @name Phaser.WEBGL - * @const - * @type {integer} - * @since 3.0.0 - */ - WEBGL: 2, - - /** - * Headless Renderer. - * - * @name Phaser.HEADLESS - * @const - * @type {integer} - * @since 3.0.0 - */ - HEADLESS: 3, - - /** - * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead - * to help you remember what the value is doing in your code. - * - * @name Phaser.FOREVER - * @const - * @type {integer} - * @since 3.0.0 - */ - FOREVER: -1, - - /** - * Direction constant. - * - * @name Phaser.NONE - * @const - * @type {integer} - * @since 3.0.0 - */ - NONE: 4, - - /** - * Direction constant. - * - * @name Phaser.UP - * @const - * @type {integer} - * @since 3.0.0 - */ - UP: 5, - - /** - * Direction constant. - * - * @name Phaser.DOWN - * @const - * @type {integer} - * @since 3.0.0 - */ - DOWN: 6, - - /** - * Direction constant. - * - * @name Phaser.LEFT - * @const - * @type {integer} - * @since 3.0.0 - */ - LEFT: 7, - - /** - * Direction constant. - * - * @name Phaser.RIGHT - * @const - * @type {integer} - * @since 3.0.0 - */ - RIGHT: 8, - - - /** - * Orientation constant. - * - * @name Phaser.ORTHOGONAL - * @const - * @type {integer} - * @since 3.2.2 - */ - ORTHOGONAL: 0, - - - /** - * Orientation constant. - * - * @name Phaser.ISOMETRIC - * @const - * @type {integer} - * @since 3.2.2 - */ - ISOMETRIC: 1, - - - /** - * Orientation constant. - * - * @name Phaser.STAGGERED - * @const - * @type {integer} - * @since 3.2.2 - */ - STAGGERED: 2, - - /** - * Orientation constant. - * - * @name Phaser.HEXAGONAL - * @const - * @type {integer} - * @since 3.2.2 - */ - HEXAGONAL: 3, - - fromOrientationString: function (orientation) - { - var constor = CONST.ORTHOGONAL; - - if (orientation === 'isometric') - { - constor = CONST.ISOMETRIC; - } - else if (orientation === 'staggered') - { - constor = CONST.STAGGERED; - } - else if (orientation === 'hexagonal') - { - constor = CONST.HEXAGONAL; - } - return constor; - } -}; - -module.exports = CONST; - - -/***/ }), -/* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2242,49 +1908,142 @@ if (true) { /***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { +/* 10 */ +/***/ (function(module, exports) { /** * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** - * @namespace Phaser.GameObjects.Components + * @namespace Phaser.Renderer.WebGL.Utils + * @since 3.0.0 */ - module.exports = { - Alpha: __webpack_require__(528), - AlphaSingle: __webpack_require__(264), - Animation: __webpack_require__(499), - BlendMode: __webpack_require__(267), - ComputedSize: __webpack_require__(547), - Crop: __webpack_require__(548), - Depth: __webpack_require__(268), - Flip: __webpack_require__(549), - GetBounds: __webpack_require__(550), - Mask: __webpack_require__(272), - Origin: __webpack_require__(567), - PathFollower: __webpack_require__(568), - Pipeline: __webpack_require__(150), - ScrollFactor: __webpack_require__(275), - Size: __webpack_require__(569), - Texture: __webpack_require__(570), - TextureCrop: __webpack_require__(571), - Tint: __webpack_require__(572), - ToJSON: __webpack_require__(276), - Transform: __webpack_require__(277), - TransformMatrix: __webpack_require__(30), - Visible: __webpack_require__(278) + /** + * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats + * @since 3.0.0 + * + * @param {number} r - Red component in a range from 0.0 to 1.0 + * @param {number} g - Green component in a range from 0.0 to 1.0 + * @param {number} b - Blue component in a range from 0.0 to 1.0 + * @param {number} a - Alpha component in a range from 0.0 to 1.0 + * + * @return {number} [description] + */ + getTintFromFloats: function (r, g, b, a) + { + var ur = ((r * 255.0)|0) & 0xFF; + var ug = ((g * 255.0)|0) & 0xFF; + var ub = ((b * 255.0)|0) & 0xFF; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlpha: function (rgb, a) + { + var ua = ((a * 255.0)|0) & 0xFF; + return ((ua << 24) | rgb) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a + * swizzled Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlphaAndSwap: function (rgb, a) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; + }, + + /** + * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 + * + * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB + * @since 3.0.0 + * + * @param {number} rgb - RGB packed as a Uint24 + * + * @return {array} Array of floats representing each component as a float + */ + getFloatsFromUintRGB: function (rgb) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + + return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; + }, + + /** + * Counts how many attributes of 32 bits a vertex has + * + * @function Phaser.Renderer.WebGL.Utils.getComponentCount + * @since 3.0.0 + * + * @param {array} attributes - Array of attributes + * @param {WebGLRenderingContext} glContext - WebGLContext used for check types + * + * @return {number} Count of 32 bit attributes in vertex + */ + getComponentCount: function (attributes, glContext) + { + var count = 0; + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + + if (element.type === glContext.FLOAT) + { + count += element.size; + } + else + { + count += 1; // We'll force any other type to be 32 bit. for now + } + } + + return count; + } }; /***/ }), -/* 13 */ +/* 11 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -2295,11 +2054,11 @@ module.exports = { var Class = __webpack_require__(0); var Contains = __webpack_require__(47); -var GetPoint = __webpack_require__(146); -var GetPoints = __webpack_require__(269); +var GetPoint = __webpack_require__(149); +var GetPoints = __webpack_require__(271); var GEOM_CONST = __webpack_require__(46); var Line = __webpack_require__(56); -var Random = __webpack_require__(149); +var Random = __webpack_require__(152); /** * @classdesc @@ -2794,6 +2553,140 @@ var Rectangle = new Class({ module.exports = Rectangle; +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Components + */ + +module.exports = { + + Alpha: __webpack_require__(527), + AlphaSingle: __webpack_require__(266), + Animation: __webpack_require__(498), + BlendMode: __webpack_require__(269), + ComputedSize: __webpack_require__(546), + Crop: __webpack_require__(547), + Depth: __webpack_require__(270), + Flip: __webpack_require__(548), + GetBounds: __webpack_require__(549), + Mask: __webpack_require__(274), + Origin: __webpack_require__(566), + PathFollower: __webpack_require__(567), + Pipeline: __webpack_require__(153), + ScrollFactor: __webpack_require__(277), + Size: __webpack_require__(568), + Texture: __webpack_require__(569), + TextureCrop: __webpack_require__(570), + Tint: __webpack_require__(571), + ToJSON: __webpack_require__(278), + Transform: __webpack_require__(279), + TransformMatrix: __webpack_require__(32), + Visible: __webpack_require__(280) + +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = { + + /** + * The value of PI * 2. + * + * @name Phaser.Math.PI2 + * @type {number} + * @since 3.0.0 + */ + PI2: Math.PI * 2, + + /** + * The value of PI * 0.5. + * + * @name Phaser.Math.TAU + * @type {number} + * @since 3.0.0 + */ + TAU: Math.PI * 0.5, + + /** + * An epsilon value (1.0e-6) + * + * @name Phaser.Math.EPSILON + * @type {number} + * @since 3.0.0 + */ + EPSILON: 1.0e-6, + + /** + * For converting degrees to radians (PI / 180) + * + * @name Phaser.Math.DEG_TO_RAD + * @type {number} + * @since 3.0.0 + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * For converting radians to degrees (180 / PI) + * + * @name Phaser.Math.RAD_TO_DEG + * @type {number} + * @since 3.0.0 + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * An instance of the Random Number Generator. + * This is not set until the Game boots. + * + * @name Phaser.Math.RND + * @type {Phaser.Math.RandomDataGenerator} + * @since 3.0.0 + */ + RND: null, + + /** + * The minimum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MIN_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, + + /** + * The maximum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MAX_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 + +}; + +module.exports = MATH_CONST; + + /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { @@ -2805,10 +2698,10 @@ module.exports = Rectangle; */ var Class = __webpack_require__(0); -var ComponentsToJSON = __webpack_require__(276); -var DataManager = __webpack_require__(109); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(88); +var ComponentsToJSON = __webpack_require__(278); +var DataManager = __webpack_require__(113); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(90); /** * @classdesc @@ -2966,10 +2859,10 @@ var GameObject = new Class({ this.input = null; /** - * If this Game Object is enabled for Arcade or Matter Physics then this property will contain a reference to a Physics Body. + * If this Game Object is enabled for physics then this property will contain a reference to a Physics Body. * * @name Phaser.GameObjects.GameObject#body - * @type {?(object|Phaser.Physics.Arcade.Body|MatterJS.BodyType)} + * @type {?(object|Phaser.Physics.Arcade.Body|Phaser.Physics.Impact.Body)} * @default null * @since 3.0.0 */ @@ -3445,7 +3338,7 @@ module.exports = GameObject; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH = __webpack_require__(165); +var MATH = __webpack_require__(168); var GetValue = __webpack_require__(6); /** @@ -3524,98 +3417,6 @@ module.exports = GetAdvancedValue; /***/ }), /* 16 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = { - - /** - * The value of PI * 2. - * - * @name Phaser.Math.PI2 - * @type {number} - * @since 3.0.0 - */ - PI2: Math.PI * 2, - - /** - * The value of PI * 0.5. - * - * @name Phaser.Math.TAU - * @type {number} - * @since 3.0.0 - */ - TAU: Math.PI * 0.5, - - /** - * An epsilon value (1.0e-6) - * - * @name Phaser.Math.EPSILON - * @type {number} - * @since 3.0.0 - */ - EPSILON: 1.0e-6, - - /** - * For converting degrees to radians (PI / 180) - * - * @name Phaser.Math.DEG_TO_RAD - * @type {number} - * @since 3.0.0 - */ - DEG_TO_RAD: Math.PI / 180, - - /** - * For converting radians to degrees (180 / PI) - * - * @name Phaser.Math.RAD_TO_DEG - * @type {number} - * @since 3.0.0 - */ - RAD_TO_DEG: 180 / Math.PI, - - /** - * An instance of the Random Number Generator. - * This is not set until the Game boots. - * - * @name Phaser.Math.RND - * @type {Phaser.Math.RandomDataGenerator} - * @since 3.0.0 - */ - RND: null, - - /** - * The minimum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - * - * @name Phaser.Math.MIN_SAFE_INTEGER - * @type {number} - * @since 3.21.0 - */ - MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, - - /** - * The maximum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - * - * @name Phaser.Math.MAX_SAFE_INTEGER - * @type {number} - * @since 3.21.0 - */ - MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 - -}; - -module.exports = MATH_CONST; - - -/***/ }), -/* 17 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -3625,8 +3426,8 @@ module.exports = MATH_CONST; */ var Class = __webpack_require__(0); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -3783,7 +3584,7 @@ module.exports = GameObjectCreator; /***/ }), -/* 18 */ +/* 17 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -3882,7 +3683,7 @@ module.exports = Extend; /***/ }), -/* 19 */ +/* 18 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -3897,22 +3698,61 @@ module.exports = Extend; module.exports = { - BLUR: __webpack_require__(551), - BOOT: __webpack_require__(552), - CONTEXT_LOST: __webpack_require__(553), - CONTEXT_RESTORED: __webpack_require__(554), - DESTROY: __webpack_require__(555), - FOCUS: __webpack_require__(556), - HIDDEN: __webpack_require__(557), - PAUSE: __webpack_require__(558), - POST_RENDER: __webpack_require__(559), - POST_STEP: __webpack_require__(560), - PRE_RENDER: __webpack_require__(561), - PRE_STEP: __webpack_require__(562), - READY: __webpack_require__(563), - RESUME: __webpack_require__(564), - STEP: __webpack_require__(565), - VISIBLE: __webpack_require__(566) + BLUR: __webpack_require__(550), + BOOT: __webpack_require__(551), + CONTEXT_LOST: __webpack_require__(552), + CONTEXT_RESTORED: __webpack_require__(553), + DESTROY: __webpack_require__(554), + FOCUS: __webpack_require__(555), + HIDDEN: __webpack_require__(556), + PAUSE: __webpack_require__(557), + POST_RENDER: __webpack_require__(558), + POST_STEP: __webpack_require__(559), + PRE_RENDER: __webpack_require__(560), + PRE_STEP: __webpack_require__(561), + READY: __webpack_require__(562), + RESUME: __webpack_require__(563), + STEP: __webpack_require__(564), + VISIBLE: __webpack_require__(565) + +}; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Scenes.Events + */ + +module.exports = { + + BOOT: __webpack_require__(700), + CREATE: __webpack_require__(701), + DESTROY: __webpack_require__(702), + PAUSE: __webpack_require__(703), + POST_UPDATE: __webpack_require__(704), + PRE_UPDATE: __webpack_require__(705), + READY: __webpack_require__(706), + RENDER: __webpack_require__(707), + RESUME: __webpack_require__(708), + SHUTDOWN: __webpack_require__(709), + SLEEP: __webpack_require__(710), + START: __webpack_require__(711), + TRANSITION_COMPLETE: __webpack_require__(712), + TRANSITION_INIT: __webpack_require__(713), + TRANSITION_OUT: __webpack_require__(714), + TRANSITION_START: __webpack_require__(715), + TRANSITION_WAKE: __webpack_require__(716), + UPDATE: __webpack_require__(717), + WAKE: __webpack_require__(718) }; @@ -4081,12 +3921,12 @@ module.exports = FILE_CONST; var Class = __webpack_require__(0); var CONST = __webpack_require__(20); -var Events = __webpack_require__(80); +var Events = __webpack_require__(81); var GetFastValue = __webpack_require__(2); -var GetURL = __webpack_require__(132); -var MergeXHRSettings = __webpack_require__(210); -var XHRLoader = __webpack_require__(448); -var XHRSettings = __webpack_require__(133); +var GetURL = __webpack_require__(134); +var MergeXHRSettings = __webpack_require__(212); +var XHRLoader = __webpack_require__(447); +var XHRSettings = __webpack_require__(135); /** * @classdesc @@ -4612,45 +4452,6 @@ module.exports = File; /***/ }), /* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Scenes.Events - */ - -module.exports = { - - BOOT: __webpack_require__(701), - CREATE: __webpack_require__(702), - DESTROY: __webpack_require__(703), - PAUSE: __webpack_require__(704), - POST_UPDATE: __webpack_require__(705), - PRE_UPDATE: __webpack_require__(706), - READY: __webpack_require__(707), - RENDER: __webpack_require__(708), - RESUME: __webpack_require__(709), - SHUTDOWN: __webpack_require__(710), - SLEEP: __webpack_require__(711), - START: __webpack_require__(712), - TRANSITION_COMPLETE: __webpack_require__(713), - TRANSITION_INIT: __webpack_require__(714), - TRANSITION_OUT: __webpack_require__(715), - TRANSITION_START: __webpack_require__(716), - TRANSITION_WAKE: __webpack_require__(717), - UPDATE: __webpack_require__(718), - WAKE: __webpack_require__(719) - -}; - - -/***/ }), -/* 23 */ /***/ (function(module, exports) { /** @@ -4680,7 +4481,7 @@ module.exports = Clamp; /***/ }), -/* 24 */ +/* 23 */ /***/ (function(module, exports) { /** @@ -4889,7 +4690,7 @@ module.exports = PluginCache; /***/ }), -/* 25 */ +/* 24 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -4973,7 +4774,7 @@ module.exports = GetTilesWithin; /***/ }), -/* 26 */ +/* 25 */ /***/ (function(module, exports) { /** @@ -5040,7 +4841,7 @@ module.exports = PropertyValueSet; /***/ }), -/* 27 */ +/* 26 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -5049,8 +4850,8 @@ module.exports = PropertyValueSet; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var Smoothing = __webpack_require__(161); +var CONST = __webpack_require__(29); +var Smoothing = __webpack_require__(164); // The pool into which the canvas elements are placed. var pool = []; @@ -5300,6 +5101,94 @@ var CanvasPool = function () module.exports = CanvasPool(); +/***/ }), +/* 27 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. + * + * 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`. + */ +var SetTransform = function (renderer, ctx, src, camera, parentMatrix) +{ + var alpha = camera.alpha * src.alpha; + + if (alpha <= 0) + { + // Nothing to see, so don't waste time calculating stuff + return false; + } + + var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); + var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + var calcMatrix = renderer._tempMatrix3; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + gameObjectMatrix.e = src.x; + gameObjectMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + else + { + gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; + gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + + // Blend Mode + ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + + // Alpha + ctx.globalAlpha = alpha; + + ctx.save(); + + calcMatrix.setToContext(ctx); + + ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); + + return true; +}; + +module.exports = SetTransform; + + /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { @@ -5430,7 +5319,7 @@ module.exports = BuildGameObject; /***/ }), /* 29 */ -/***/ (function(module, exports) { +/***/ (function(module, exports, __webpack_require__) { /** * @author Richard Davey @@ -5439,81 +5328,131 @@ module.exports = BuildGameObject; */ /** - * 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: + * Global constants. * - * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. - * - * 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`. + * @ignore */ -var SetTransform = function (renderer, ctx, src, camera, parentMatrix) -{ - var alpha = camera.alpha * src.alpha; - if (alpha <= 0) - { - // Nothing to see, so don't waste time calculating stuff - return false; - } +var CONST = { - var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); - var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - var calcMatrix = renderer._tempMatrix3; + /** + * Phaser Release Version + * + * @name Phaser.VERSION + * @const + * @type {string} + * @since 3.0.0 + */ + VERSION: '3.22.0', - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + BlendModes: __webpack_require__(52), - // Undo the camera scroll - gameObjectMatrix.e = src.x; - gameObjectMatrix.f = src.y; + ScaleModes: __webpack_require__(231), - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(gameObjectMatrix, calcMatrix); - } - else - { - gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; - gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; + /** + * AUTO Detect Renderer. + * + * @name Phaser.AUTO + * @const + * @type {integer} + * @since 3.0.0 + */ + AUTO: 0, - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(gameObjectMatrix, calcMatrix); - } + /** + * Canvas Renderer. + * + * @name Phaser.CANVAS + * @const + * @type {integer} + * @since 3.0.0 + */ + CANVAS: 1, - // Blend Mode - ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + /** + * WebGL Renderer. + * + * @name Phaser.WEBGL + * @const + * @type {integer} + * @since 3.0.0 + */ + WEBGL: 2, - // Alpha - ctx.globalAlpha = alpha; + /** + * Headless Renderer. + * + * @name Phaser.HEADLESS + * @const + * @type {integer} + * @since 3.0.0 + */ + HEADLESS: 3, - ctx.save(); + /** + * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead + * to help you remember what the value is doing in your code. + * + * @name Phaser.FOREVER + * @const + * @type {integer} + * @since 3.0.0 + */ + FOREVER: -1, - calcMatrix.setToContext(ctx); + /** + * Direction constant. + * + * @name Phaser.NONE + * @const + * @type {integer} + * @since 3.0.0 + */ + NONE: 4, - ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); + /** + * Direction constant. + * + * @name Phaser.UP + * @const + * @type {integer} + * @since 3.0.0 + */ + UP: 5, + + /** + * Direction constant. + * + * @name Phaser.DOWN + * @const + * @type {integer} + * @since 3.0.0 + */ + DOWN: 6, + + /** + * Direction constant. + * + * @name Phaser.LEFT + * @const + * @type {integer} + * @since 3.0.0 + */ + LEFT: 7, + + /** + * Direction constant. + * + * @name Phaser.RIGHT + * @const + * @type {integer} + * @since 3.0.0 + */ + RIGHT: 8 - return true; }; -module.exports = SetTransform; +module.exports = CONST; /***/ }), @@ -5527,7 +5466,362 @@ module.exports = SetTransform; */ var Class = __webpack_require__(0); -var MATH_CONST = __webpack_require__(16); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var Line = __webpack_require__(56); + +/** + * @classdesc + * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. + * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. + * + * @class Shape + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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 {string} [type] - The internal type of the Shape. + * @param {any} [data] - The data of the source shape geometry, if any. + */ +var Shape = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Transform, + Components.Visible + ], + + initialize: + + function Shape (scene, type, data) + { + if (type === undefined) { type = 'Shape'; } + + GameObject.call(this, scene, type); + + /** + * The source Shape data. Typically a geometry object. + * You should not manipulate this directly. + * + * @name Phaser.GameObjects.Shape#data + * @type {any} + * @readonly + * @since 3.13.0 + */ + this.geom = data; + + /** + * Holds the polygon path data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathData + * @type {number[]} + * @readonly + * @since 3.13.0 + */ + this.pathData = []; + + /** + * Holds the earcut polygon path index data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathIndexes + * @type {integer[]} + * @readonly + * @since 3.13.0 + */ + this.pathIndexes = []; + + /** + * The fill color used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillColor + * @type {number} + * @since 3.13.0 + */ + this.fillColor = 0xffffff; + + /** + * The fill alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillAlpha + * @type {number} + * @since 3.13.0 + */ + this.fillAlpha = 1; + + /** + * The stroke color used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeColor + * @type {number} + * @since 3.13.0 + */ + this.strokeColor = 0xffffff; + + /** + * The stroke alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeAlpha + * @type {number} + * @since 3.13.0 + */ + this.strokeAlpha = 1; + + /** + * The stroke line width used by this Shape. + * + * @name Phaser.GameObjects.Shape#lineWidth + * @type {number} + * @since 3.13.0 + */ + this.lineWidth = 1; + + /** + * Controls if this Shape is filled or not. + * Note that some Shapes do not support being filled (such as Line shapes) + * + * @name Phaser.GameObjects.Shape#isFilled + * @type {boolean} + * @since 3.13.0 + */ + this.isFilled = false; + + /** + * Controls if this Shape is stroked or not. + * Note that some Shapes do not support being stroked (such as Iso Box shapes) + * + * @name Phaser.GameObjects.Shape#isStroked + * @type {boolean} + * @since 3.13.0 + */ + this.isStroked = false; + + /** + * Controls if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * @name Phaser.GameObjects.Shape#closePath + * @type {boolean} + * @since 3.13.0 + */ + this.closePath = true; + + /** + * Private internal value. + * A Line used when parsing internal path data to avoid constant object re-creation. + * + * @name Phaser.GameObjects.Curve#_tempLine + * @type {Phaser.Geom.Line} + * @private + * @since 3.13.0 + */ + this._tempLine = new Line(); + + this.initPipeline(); + }, + + /** + * Sets the fill color and alpha for this Shape. + * + * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. + * + * Note that some Shapes do not support fill colors, such as the Line shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setFillStyle + * @since 3.13.0 + * + * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. + * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (color === undefined) + { + this.isFilled = false; + } + else + { + this.fillColor = color; + this.fillAlpha = alpha; + this.isFilled = true; + } + + return this; + }, + + /** + * Sets the stroke color and alpha for this Shape. + * + * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. + * + * Note that some Shapes do not support being stroked, such as the Iso Box shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setStrokeStyle + * @since 3.13.0 + * + * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. + * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. + * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. + * + * @return {this} This Game Object instance. + */ + setStrokeStyle: function (lineWidth, color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (lineWidth === undefined) + { + this.isStroked = false; + } + else + { + this.lineWidth = lineWidth; + this.strokeColor = color; + this.strokeAlpha = alpha; + this.isStroked = true; + } + + return this; + }, + + /** + * Sets if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setClosePath + * @since 3.13.0 + * + * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. + * + * @return {this} This Game Object instance. + */ + setClosePath: function (value) + { + this.closePath = value; + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Shape#preDestroy + * @protected + * @since 3.13.0 + */ + preDestroy: function () + { + this.geom = null; + this._tempLine = null; + this.pathData = []; + this.pathIndexes = []; + } + +}); + +module.exports = Shape; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Formats + */ + +module.exports = { + + /** + * CSV Map Type + * + * @name Phaser.Tilemaps.Formats.CSV + * @type {number} + * @since 3.0.0 + */ + CSV: 0, + + /** + * Tiled JSON Map Type + * + * @name Phaser.Tilemaps.Formats.TILED_JSON + * @type {number} + * @since 3.0.0 + */ + TILED_JSON: 1, + + /** + * 2D Array Map Type + * + * @name Phaser.Tilemaps.Formats.ARRAY_2D + * @type {number} + * @since 3.0.0 + */ + ARRAY_2D: 2, + + /** + * Weltmeister (Impact.js) Map Type + * + * @name Phaser.Tilemaps.Formats.WELTMEISTER + * @type {number} + * @since 3.0.0 + */ + WELTMEISTER: 3 + +}; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var MATH_CONST = __webpack_require__(13); var Vector2 = __webpack_require__(3); /** @@ -5960,7 +6254,7 @@ var TransformMatrix = new Class({ * @param {Phaser.GameObjects.Components.TransformMatrix} rhs - The Matrix to multiply by. * @param {Phaser.GameObjects.Components.TransformMatrix} [out] - An optional Matrix to store the results in. * - * @return {(this|Phaser.GameObjects.Components.TransformMatrix)} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. + * @return {Phaser.GameObjects.Components.TransformMatrix} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. */ multiply: function (rhs, out) { @@ -6485,7 +6779,7 @@ module.exports = TransformMatrix; /***/ }), -/* 31 */ +/* 33 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -6495,310 +6789,10 @@ module.exports = TransformMatrix; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameObject = __webpack_require__(14); -var Line = __webpack_require__(56); - -/** - * @classdesc - * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. - * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. - * - * @class Shape - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.ComputedSize - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @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 {string} [type] - The internal type of the Shape. - * @param {any} [data] - The data of the source shape geometry, if any. - */ -var Shape = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.ComputedSize, - Components.Depth, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Transform, - Components.Visible - ], - - initialize: - - function Shape (scene, type, data) - { - if (type === undefined) { type = 'Shape'; } - - GameObject.call(this, scene, type); - - /** - * The source Shape data. Typically a geometry object. - * You should not manipulate this directly. - * - * @name Phaser.GameObjects.Shape#data - * @type {any} - * @readonly - * @since 3.13.0 - */ - this.geom = data; - - /** - * Holds the polygon path data for filled rendering. - * - * @name Phaser.GameObjects.Shape#pathData - * @type {number[]} - * @readonly - * @since 3.13.0 - */ - this.pathData = []; - - /** - * Holds the earcut polygon path index data for filled rendering. - * - * @name Phaser.GameObjects.Shape#pathIndexes - * @type {integer[]} - * @readonly - * @since 3.13.0 - */ - this.pathIndexes = []; - - /** - * The fill color used by this Shape. - * - * @name Phaser.GameObjects.Shape#fillColor - * @type {number} - * @since 3.13.0 - */ - this.fillColor = 0xffffff; - - /** - * The fill alpha value used by this Shape. - * - * @name Phaser.GameObjects.Shape#fillAlpha - * @type {number} - * @since 3.13.0 - */ - this.fillAlpha = 1; - - /** - * The stroke color used by this Shape. - * - * @name Phaser.GameObjects.Shape#strokeColor - * @type {number} - * @since 3.13.0 - */ - this.strokeColor = 0xffffff; - - /** - * The stroke alpha value used by this Shape. - * - * @name Phaser.GameObjects.Shape#strokeAlpha - * @type {number} - * @since 3.13.0 - */ - this.strokeAlpha = 1; - - /** - * The stroke line width used by this Shape. - * - * @name Phaser.GameObjects.Shape#lineWidth - * @type {number} - * @since 3.13.0 - */ - this.lineWidth = 1; - - /** - * Controls if this Shape is filled or not. - * Note that some Shapes do not support being filled (such as Line shapes) - * - * @name Phaser.GameObjects.Shape#isFilled - * @type {boolean} - * @since 3.13.0 - */ - this.isFilled = false; - - /** - * Controls if this Shape is stroked or not. - * Note that some Shapes do not support being stroked (such as Iso Box shapes) - * - * @name Phaser.GameObjects.Shape#isStroked - * @type {boolean} - * @since 3.13.0 - */ - this.isStroked = false; - - /** - * Controls if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * @name Phaser.GameObjects.Shape#closePath - * @type {boolean} - * @since 3.13.0 - */ - this.closePath = true; - - /** - * Private internal value. - * A Line used when parsing internal path data to avoid constant object re-creation. - * - * @name Phaser.GameObjects.Curve#_tempLine - * @type {Phaser.Geom.Line} - * @private - * @since 3.13.0 - */ - this._tempLine = new Line(); - - this.initPipeline(); - }, - - /** - * Sets the fill color and alpha for this Shape. - * - * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. - * - * Note that some Shapes do not support fill colors, such as the Line shape. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setFillStyle - * @since 3.13.0 - * - * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. - * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. - * - * @return {this} This Game Object instance. - */ - setFillStyle: function (color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - if (color === undefined) - { - this.isFilled = false; - } - else - { - this.fillColor = color; - this.fillAlpha = alpha; - this.isFilled = true; - } - - return this; - }, - - /** - * Sets the stroke color and alpha for this Shape. - * - * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. - * - * Note that some Shapes do not support being stroked, such as the Iso Box shape. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setStrokeStyle - * @since 3.13.0 - * - * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. - * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. - * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. - * - * @return {this} This Game Object instance. - */ - setStrokeStyle: function (lineWidth, color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - if (lineWidth === undefined) - { - this.isStroked = false; - } - else - { - this.lineWidth = lineWidth; - this.strokeColor = color; - this.strokeAlpha = alpha; - this.isStroked = true; - } - - return this; - }, - - /** - * Sets if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setClosePath - * @since 3.13.0 - * - * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. - * - * @return {this} This Game Object instance. - */ - setClosePath: function (value) - { - this.closePath = value; - - return this; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Shape#preDestroy - * @protected - * @since 3.13.0 - */ - preDestroy: function () - { - this.geom = null; - this._tempLine = null; - this.pathData = []; - this.pathIndexes = []; - } - -}); - -module.exports = Shape; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); -var GetColor = __webpack_require__(159); -var GetColor32 = __webpack_require__(290); -var HSVToRGB = __webpack_require__(160); -var RGBToHSV = __webpack_require__(291); +var GetColor = __webpack_require__(162); +var GetColor32 = __webpack_require__(292); +var HSVToRGB = __webpack_require__(163); +var RGBToHSV = __webpack_require__(293); /** * @namespace Phaser.Display.Color @@ -7647,61 +7641,6 @@ var Color = new Class({ module.exports = Color; -/***/ }), -/* 33 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Formats - */ - -module.exports = { - - /** - * CSV Map Type - * - * @name Phaser.Tilemaps.Formats.CSV - * @type {number} - * @since 3.0.0 - */ - CSV: 0, - - /** - * Tiled JSON Map Type - * - * @name Phaser.Tilemaps.Formats.TILED_JSON - * @type {number} - * @since 3.0.0 - */ - TILED_JSON: 1, - - /** - * 2D Array Map Type - * - * @name Phaser.Tilemaps.Formats.ARRAY_2D - * @type {number} - * @since 3.0.0 - */ - ARRAY_2D: 2, - - /** - * Weltmeister (Impact.js) Map Type - * - * @name Phaser.Tilemaps.Formats.WELTMEISTER - * @type {number} - * @since 3.0.0 - */ - WELTMEISTER: 3 - -}; - - /***/ }), /* 34 */ /***/ (function(module, exports) { @@ -7779,7 +7718,7 @@ module.exports = PropertyValueInc; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); +var CONST = __webpack_require__(13); /** * Convert the given angle from degrees, to the equivalent angle in radians. @@ -8755,21 +8694,21 @@ module.exports = Contains; module.exports = { - DESTROY: __webpack_require__(642), - FADE_IN_COMPLETE: __webpack_require__(643), - FADE_IN_START: __webpack_require__(644), - FADE_OUT_COMPLETE: __webpack_require__(645), - FADE_OUT_START: __webpack_require__(646), - FLASH_COMPLETE: __webpack_require__(647), - FLASH_START: __webpack_require__(648), - PAN_COMPLETE: __webpack_require__(649), - PAN_START: __webpack_require__(650), - POST_RENDER: __webpack_require__(651), - PRE_RENDER: __webpack_require__(652), - SHAKE_COMPLETE: __webpack_require__(653), - SHAKE_START: __webpack_require__(654), - ZOOM_COMPLETE: __webpack_require__(655), - ZOOM_START: __webpack_require__(656) + DESTROY: __webpack_require__(641), + FADE_IN_COMPLETE: __webpack_require__(642), + FADE_IN_START: __webpack_require__(643), + FADE_OUT_COMPLETE: __webpack_require__(644), + FADE_OUT_START: __webpack_require__(645), + FLASH_COMPLETE: __webpack_require__(646), + FLASH_START: __webpack_require__(647), + PAN_COMPLETE: __webpack_require__(648), + PAN_START: __webpack_require__(649), + POST_RENDER: __webpack_require__(650), + PRE_RENDER: __webpack_require__(651), + SHAKE_COMPLETE: __webpack_require__(652), + SHAKE_START: __webpack_require__(653), + ZOOM_COMPLETE: __webpack_require__(654), + ZOOM_START: __webpack_require__(655) }; @@ -8951,8 +8890,8 @@ module.exports = CONST; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTileAt = __webpack_require__(136); -var GetTilesWithin = __webpack_require__(25); +var GetTileAt = __webpack_require__(138); +var GetTilesWithin = __webpack_require__(24); /** * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the @@ -9396,52 +9335,52 @@ module.exports = DistanceBetween; module.exports = { - BOOT: __webpack_require__(812), - DESTROY: __webpack_require__(813), - DRAG_END: __webpack_require__(814), - DRAG_ENTER: __webpack_require__(815), - DRAG: __webpack_require__(816), - DRAG_LEAVE: __webpack_require__(817), - DRAG_OVER: __webpack_require__(818), - DRAG_START: __webpack_require__(819), - DROP: __webpack_require__(820), - GAME_OUT: __webpack_require__(821), - GAME_OVER: __webpack_require__(822), - GAMEOBJECT_DOWN: __webpack_require__(823), - GAMEOBJECT_DRAG_END: __webpack_require__(824), - GAMEOBJECT_DRAG_ENTER: __webpack_require__(825), - GAMEOBJECT_DRAG: __webpack_require__(826), - GAMEOBJECT_DRAG_LEAVE: __webpack_require__(827), - GAMEOBJECT_DRAG_OVER: __webpack_require__(828), - GAMEOBJECT_DRAG_START: __webpack_require__(829), - GAMEOBJECT_DROP: __webpack_require__(830), - GAMEOBJECT_MOVE: __webpack_require__(831), - GAMEOBJECT_OUT: __webpack_require__(832), - GAMEOBJECT_OVER: __webpack_require__(833), - GAMEOBJECT_POINTER_DOWN: __webpack_require__(834), - GAMEOBJECT_POINTER_MOVE: __webpack_require__(835), - GAMEOBJECT_POINTER_OUT: __webpack_require__(836), - GAMEOBJECT_POINTER_OVER: __webpack_require__(837), - GAMEOBJECT_POINTER_UP: __webpack_require__(838), - GAMEOBJECT_POINTER_WHEEL: __webpack_require__(839), - GAMEOBJECT_UP: __webpack_require__(840), - GAMEOBJECT_WHEEL: __webpack_require__(841), - MANAGER_BOOT: __webpack_require__(842), - MANAGER_PROCESS: __webpack_require__(843), - MANAGER_UPDATE: __webpack_require__(844), - POINTER_DOWN: __webpack_require__(845), - POINTER_DOWN_OUTSIDE: __webpack_require__(846), - POINTER_MOVE: __webpack_require__(847), - POINTER_OUT: __webpack_require__(848), - POINTER_OVER: __webpack_require__(849), - POINTER_UP: __webpack_require__(850), - POINTER_UP_OUTSIDE: __webpack_require__(851), - POINTER_WHEEL: __webpack_require__(852), - POINTERLOCK_CHANGE: __webpack_require__(853), - PRE_UPDATE: __webpack_require__(854), - SHUTDOWN: __webpack_require__(855), - START: __webpack_require__(856), - UPDATE: __webpack_require__(857) + BOOT: __webpack_require__(814), + DESTROY: __webpack_require__(815), + DRAG_END: __webpack_require__(816), + DRAG_ENTER: __webpack_require__(817), + DRAG: __webpack_require__(818), + DRAG_LEAVE: __webpack_require__(819), + DRAG_OVER: __webpack_require__(820), + DRAG_START: __webpack_require__(821), + DROP: __webpack_require__(822), + GAME_OUT: __webpack_require__(823), + GAME_OVER: __webpack_require__(824), + GAMEOBJECT_DOWN: __webpack_require__(825), + GAMEOBJECT_DRAG_END: __webpack_require__(826), + GAMEOBJECT_DRAG_ENTER: __webpack_require__(827), + GAMEOBJECT_DRAG: __webpack_require__(828), + GAMEOBJECT_DRAG_LEAVE: __webpack_require__(829), + GAMEOBJECT_DRAG_OVER: __webpack_require__(830), + GAMEOBJECT_DRAG_START: __webpack_require__(831), + GAMEOBJECT_DROP: __webpack_require__(832), + GAMEOBJECT_MOVE: __webpack_require__(833), + GAMEOBJECT_OUT: __webpack_require__(834), + GAMEOBJECT_OVER: __webpack_require__(835), + GAMEOBJECT_POINTER_DOWN: __webpack_require__(836), + GAMEOBJECT_POINTER_MOVE: __webpack_require__(837), + GAMEOBJECT_POINTER_OUT: __webpack_require__(838), + GAMEOBJECT_POINTER_OVER: __webpack_require__(839), + GAMEOBJECT_POINTER_UP: __webpack_require__(840), + GAMEOBJECT_POINTER_WHEEL: __webpack_require__(841), + GAMEOBJECT_UP: __webpack_require__(842), + GAMEOBJECT_WHEEL: __webpack_require__(843), + MANAGER_BOOT: __webpack_require__(844), + MANAGER_PROCESS: __webpack_require__(845), + MANAGER_UPDATE: __webpack_require__(846), + POINTER_DOWN: __webpack_require__(847), + POINTER_DOWN_OUTSIDE: __webpack_require__(848), + POINTER_MOVE: __webpack_require__(849), + POINTER_OUT: __webpack_require__(850), + POINTER_OVER: __webpack_require__(851), + POINTER_UP: __webpack_require__(852), + POINTER_UP_OUTSIDE: __webpack_require__(853), + POINTER_WHEEL: __webpack_require__(854), + POINTERLOCK_CHANGE: __webpack_require__(855), + PRE_UPDATE: __webpack_require__(856), + SHUTDOWN: __webpack_require__(857), + START: __webpack_require__(858), + UPDATE: __webpack_require__(859) }; @@ -9498,10 +9437,10 @@ module.exports = Contains; */ var Class = __webpack_require__(0); -var GetPoint = __webpack_require__(270); -var GetPoints = __webpack_require__(147); +var GetPoint = __webpack_require__(272); +var GetPoints = __webpack_require__(150); var GEOM_CONST = __webpack_require__(46); -var Random = __webpack_require__(148); +var Random = __webpack_require__(151); var Vector2 = __webpack_require__(3); /** @@ -9900,29 +9839,29 @@ module.exports = Wrap; module.exports = { - COMPLETE: __webpack_require__(880), - DECODED: __webpack_require__(881), - DECODED_ALL: __webpack_require__(882), - DESTROY: __webpack_require__(883), - DETUNE: __webpack_require__(884), - GLOBAL_DETUNE: __webpack_require__(885), - GLOBAL_MUTE: __webpack_require__(886), - GLOBAL_RATE: __webpack_require__(887), - GLOBAL_VOLUME: __webpack_require__(888), - LOOP: __webpack_require__(889), - LOOPED: __webpack_require__(890), - MUTE: __webpack_require__(891), - PAUSE_ALL: __webpack_require__(892), - PAUSE: __webpack_require__(893), - PLAY: __webpack_require__(894), - RATE: __webpack_require__(895), - RESUME_ALL: __webpack_require__(896), - RESUME: __webpack_require__(897), - SEEK: __webpack_require__(898), - STOP_ALL: __webpack_require__(899), - STOP: __webpack_require__(900), - UNLOCKED: __webpack_require__(901), - VOLUME: __webpack_require__(902) + COMPLETE: __webpack_require__(882), + DECODED: __webpack_require__(883), + DECODED_ALL: __webpack_require__(884), + DESTROY: __webpack_require__(885), + DETUNE: __webpack_require__(886), + GLOBAL_DETUNE: __webpack_require__(887), + GLOBAL_MUTE: __webpack_require__(888), + GLOBAL_RATE: __webpack_require__(889), + GLOBAL_VOLUME: __webpack_require__(890), + LOOP: __webpack_require__(891), + LOOPED: __webpack_require__(892), + MUTE: __webpack_require__(893), + PAUSE_ALL: __webpack_require__(894), + PAUSE: __webpack_require__(895), + PLAY: __webpack_require__(896), + RATE: __webpack_require__(897), + RESUME_ALL: __webpack_require__(898), + RESUME: __webpack_require__(899), + SEEK: __webpack_require__(900), + STOP_ALL: __webpack_require__(901), + STOP: __webpack_require__(902), + UNLOCKED: __webpack_require__(903), + VOLUME: __webpack_require__(904) }; @@ -10134,7 +10073,7 @@ var JSONFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('json', function (key, url, dataKey, xhrSettings) { @@ -10408,12 +10347,12 @@ var Body = {}; module.exports = Body; -var Vertices = __webpack_require__(84); -var Vector = __webpack_require__(97); -var Sleeping = __webpack_require__(234); +var Vertices = __webpack_require__(86); +var Vector = __webpack_require__(101); +var Sleeping = __webpack_require__(236); var Common = __webpack_require__(37); -var Bounds = __webpack_require__(98); -var Axes = __webpack_require__(508); +var Bounds = __webpack_require__(102); +var Axes = __webpack_require__(507); (function() { @@ -11775,6 +11714,108 @@ var Axes = __webpack_require__(508); /***/ }), /* 63 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileX + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The X location in tile units. + */ +var WorldToTileX = function (worldX, snapToFloor, camera, layer) +{ + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + } + + return snapToFloor + ? Math.floor(worldX / tileWidth) + : worldX / tileWidth; +}; + +module.exports = WorldToTileX; + + +/***/ }), +/* 64 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileY + * @private + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The Y location in tile units. + */ +var WorldToTileY = function (worldY, snapToFloor, camera, layer) +{ + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + return snapToFloor + ? Math.floor(worldY / tileHeight) + : worldY / tileHeight; +}; + +module.exports = WorldToTileY; + + +/***/ }), +/* 65 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -11785,10 +11826,10 @@ var Axes = __webpack_require__(508); var Class = __webpack_require__(0); var Contains = __webpack_require__(55); -var GetPoint = __webpack_require__(261); -var GetPoints = __webpack_require__(262); +var GetPoint = __webpack_require__(263); +var GetPoints = __webpack_require__(264); var GEOM_CONST = __webpack_require__(46); -var Random = __webpack_require__(144); +var Random = __webpack_require__(147); /** * @classdesc @@ -12149,7 +12190,7 @@ module.exports = Circle; /***/ }), -/* 64 */ +/* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -12831,7 +12872,7 @@ earcut.flatten = function (data) { /***/ }), -/* 65 */ +/* 67 */ /***/ (function(module, exports) { /** @@ -12873,7 +12914,7 @@ module.exports = Clone; /***/ }), -/* 66 */ +/* 68 */ /***/ (function(module, exports) { /** @@ -12922,7 +12963,7 @@ module.exports = SafeRange; /***/ }), -/* 67 */ +/* 69 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -12931,107 +12972,176 @@ module.exports = SafeRange; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var EaseMap = __webpack_require__(163); -var UppercaseFirst = __webpack_require__(176); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var SpriteRender = __webpack_require__(960); /** - * This internal function is used to return the correct ease function for a Tween. - * - * It can take a variety of input, including an EaseMap based string, or a custom function. + * @classdesc + * A Sprite Game Object. * - * @function Phaser.Tweens.Builders.GetEaseFunction + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class Sprite + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor * @since 3.0.0 * - * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. - * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @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.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.TextureCrop + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible * - * @return {function} The ease function. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. */ -var GetEaseFunction = function (ease, easeParams) -{ - // Default ease function - var easeFunction = EaseMap.Power0; +var Sprite = new Class({ - // Prepare ease function - if (typeof ease === 'string') + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + SpriteRender + ], + + initialize: + + function Sprite (scene, x, y, texture, frame) { - // String based look-up + GameObject.call(this, scene, 'Sprite'); - // 1) They specified it correctly - if (EaseMap.hasOwnProperty(ease)) - { - easeFunction = EaseMap[ease]; - } - else - { - // Do some string manipulation to try and find it - var direction = ''; + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Sprite#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); - if (ease.indexOf('.')) - { - // quad.in = Quad.easeIn - // quad.out = Quad.easeOut - // quad.inout = Quad.easeInOut + /** + * The Animation Controller of this Sprite. + * + * @name Phaser.GameObjects.Sprite#anims + * @type {Phaser.GameObjects.Components.Animation} + * @since 3.0.0 + */ + this.anims = new Components.Animation(this); - direction = ease.substr(ease.indexOf('.') + 1); + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + }, - if (direction.toLowerCase() === 'in') - { - direction = 'easeIn'; - } - else if (direction.toLowerCase() === 'out') - { - direction = 'easeOut'; - } - else if (direction.toLowerCase() === 'inout') - { - direction = 'easeInOut'; - } - } - - ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); - - if (EaseMap.hasOwnProperty(ease)) - { - easeFunction = EaseMap[ease]; - } - } - } - else if (typeof ease === 'function') + /** + * Update this Sprite's animations. + * + * @method Phaser.GameObjects.Sprite#preUpdate + * @protected + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + preUpdate: function (time, delta) { - // Custom function - easeFunction = ease; - } - else if (Array.isArray(ease) && ease.length === 4) + this.anims.update(time, delta); + }, + + /** + * Start playing the given animation. + * + * @method Phaser.GameObjects.Sprite#play + * @since 3.0.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.Sprite} This Game Object. + */ + play: function (key, ignoreIfPlaying, startFrame) { - // Bezier function (TODO) + this.anims.play(key, ignoreIfPlaying, startFrame); + + return this; + }, + + /** + * Build a JSON representation of this Sprite. + * + * @method Phaser.GameObjects.Sprite#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ + toJSON: function () + { + var data = Components.ToJSON(this); + + // Extra Sprite data is added here + + return data; + }, + + /** + * Handles the pre-destroy step for the Sprite, which removes the Animation component. + * + * @method Phaser.GameObjects.Sprite#preDestroy + * @private + * @since 3.14.0 + */ + preDestroy: function () + { + this.anims.destroy(); + + this.anims = undefined; } - // No custom ease parameters? - if (!easeParams) - { - // Return ease function - return easeFunction; - } +}); - var cloneParams = easeParams.slice(0); - - cloneParams.unshift(0); - - // Return ease function with custom ease parameters - return function (v) - { - cloneParams[0] = v; - - return easeFunction.apply(this, cloneParams); - }; -}; - -module.exports = GetEaseFunction; +module.exports = Sprite; /***/ }), -/* 68 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13040,7 +13150,7 @@ module.exports = GetEaseFunction; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders a stroke outline around the given Shape. @@ -13106,7 +13216,7 @@ module.exports = StrokePathWebGL; /***/ }), -/* 69 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13116,12 +13226,12 @@ module.exports = StrokePathWebGL; */ var Class = __webpack_require__(0); -var Contains = __webpack_require__(81); -var GetPoint = __webpack_require__(418); -var GetPoints = __webpack_require__(419); +var Contains = __webpack_require__(83); +var GetPoint = __webpack_require__(417); +var GetPoints = __webpack_require__(418); var GEOM_CONST = __webpack_require__(46); var Line = __webpack_require__(56); -var Random = __webpack_require__(152); +var Random = __webpack_require__(155); /** * @classdesc @@ -13553,7 +13663,7 @@ module.exports = Triangle; /***/ }), -/* 70 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13803,7 +13913,7 @@ var ImageFile = new Class({ * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('image', function (key, url, xhrSettings) { @@ -13827,7 +13937,7 @@ module.exports = ImageFile; /***/ }), -/* 71 */ +/* 73 */ /***/ (function(module, exports) { /** @@ -13863,7 +13973,7 @@ module.exports = SetTileCollision; /***/ }), -/* 72 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -13872,10 +13982,9 @@ module.exports = SetTileCollision; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Rectangle = __webpack_require__(437); +var Rectangle = __webpack_require__(436); /** * @classdesc @@ -14575,34 +14684,14 @@ var Tile = new Class({ */ updatePixelXY: function () { - if (this.layer.orientation === CONST.ISOMETRIC) - { - // 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. - this.pixelX = (this.x - this.y) * this.baseWidth * 0.5; - this.pixelY = (this.x + this.y) * this.baseHeight * 0.5; - } - else if (this.layer.orientation === CONST.STAGGERED) - { - this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); - this.pixelY = this.y * (this.baseHeight / 2); - } - else if (this.layer.orientation === CONST.HEXAGONAL) - { - var sidel = this.layer.hexSideLength; - var rowHeight = ((this.baseHeight - sidel) / 2 + sidel); - this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); - this.pixelY = this.y * rowHeight; - } - else if (this.layer.orientation === CONST.ORTHOGONAL) - { - // 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. - this.pixelX = this.x * this.baseWidth; - this.pixelY = this.y * this.baseHeight; - - } + // 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. + this.pixelX = this.x * this.baseWidth; + this.pixelY = this.y * this.baseHeight; + + // this.pixelY = this.y * this.baseHeight - (this.height - this.baseHeight); + return this; }, @@ -14722,185 +14811,7 @@ module.exports = Tile; /***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameObject = __webpack_require__(14); -var SpriteRender = __webpack_require__(958); - -/** - * @classdesc - * A Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * - * @class Sprite - * @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.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var Sprite = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - SpriteRender - ], - - initialize: - - function Sprite (scene, x, y, texture, frame) - { - GameObject.call(this, scene, 'Sprite'); - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.Sprite#_crop - * @type {object} - * @private - * @since 3.11.0 - */ - this._crop = this.resetCropObject(); - - /** - * The Animation Controller of this Sprite. - * - * @name Phaser.GameObjects.Sprite#anims - * @type {Phaser.GameObjects.Components.Animation} - * @since 3.0.0 - */ - this.anims = new Components.Animation(this); - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.setOriginFromFrame(); - this.initPipeline(); - }, - - /** - * Update this Sprite's animations. - * - * @method Phaser.GameObjects.Sprite#preUpdate - * @protected - * @since 3.0.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - this.anims.update(time, delta); - }, - - /** - * Start playing the given animation. - * - * @method Phaser.GameObjects.Sprite#play - * @since 3.0.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Game Object. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - this.anims.play(key, ignoreIfPlaying, startFrame); - - return this; - }, - - /** - * Build a JSON representation of this Sprite. - * - * @method Phaser.GameObjects.Sprite#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. - */ - toJSON: function () - { - var data = Components.ToJSON(this); - - // Extra Sprite data is added here - - return data; - }, - - /** - * Handles the pre-destroy step for the Sprite, which removes the Animation component. - * - * @method Phaser.GameObjects.Sprite#preDestroy - * @private - * @since 3.14.0 - */ - preDestroy: function () - { - this.anims.destroy(); - - this.anims = undefined; - } - -}); - -module.exports = Sprite; - - -/***/ }), -/* 74 */ +/* 75 */ /***/ (function(module, exports) { /** @@ -14928,7 +14839,7 @@ module.exports = GetCenterX; /***/ }), -/* 75 */ +/* 76 */ /***/ (function(module, exports) { /** @@ -14963,7 +14874,7 @@ module.exports = SetCenterX; /***/ }), -/* 76 */ +/* 77 */ /***/ (function(module, exports) { /** @@ -14991,7 +14902,7 @@ module.exports = GetCenterY; /***/ }), -/* 77 */ +/* 78 */ /***/ (function(module, exports) { /** @@ -15026,7 +14937,7 @@ module.exports = SetCenterY; /***/ }), -/* 78 */ +/* 79 */ /***/ (function(module, exports) { /** @@ -15072,7 +14983,7 @@ module.exports = SpliceOne; /***/ }), -/* 79 */ +/* 80 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -15082,8 +14993,8 @@ module.exports = SpliceOne; */ var Class = __webpack_require__(0); -var FromPoints = __webpack_require__(171); -var Rectangle = __webpack_require__(13); +var FromPoints = __webpack_require__(174); +var Rectangle = __webpack_require__(11); var Vector2 = __webpack_require__(3); /** @@ -15692,7 +15603,7 @@ module.exports = Curve; /***/ }), -/* 80 */ +/* 81 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -15707,22 +15618,131 @@ module.exports = Curve; module.exports = { - ADD: __webpack_require__(859), - COMPLETE: __webpack_require__(860), - FILE_COMPLETE: __webpack_require__(861), - FILE_KEY_COMPLETE: __webpack_require__(862), - FILE_LOAD_ERROR: __webpack_require__(863), - FILE_LOAD: __webpack_require__(864), - FILE_PROGRESS: __webpack_require__(865), - POST_PROCESS: __webpack_require__(866), - PROGRESS: __webpack_require__(867), - START: __webpack_require__(868) + ADD: __webpack_require__(861), + COMPLETE: __webpack_require__(862), + FILE_COMPLETE: __webpack_require__(863), + FILE_KEY_COMPLETE: __webpack_require__(864), + FILE_LOAD_ERROR: __webpack_require__(865), + FILE_LOAD: __webpack_require__(866), + FILE_PROGRESS: __webpack_require__(867), + POST_PROCESS: __webpack_require__(868), + PROGRESS: __webpack_require__(869), + START: __webpack_require__(870) }; /***/ }), -/* 81 */ +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var EaseMap = __webpack_require__(166); +var UppercaseFirst = __webpack_require__(179); + +/** + * This internal function is used to return the correct ease function for a Tween. + * + * It can take a variety of input, including an EaseMap based string, or a custom function. + * + * @function Phaser.Tweens.Builders.GetEaseFunction + * @since 3.0.0 + * + * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. + * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * + * @return {function} The ease function. + */ +var GetEaseFunction = function (ease, easeParams) +{ + // Default ease function + var easeFunction = EaseMap.Power0; + + // Prepare ease function + if (typeof ease === 'string') + { + // String based look-up + + // 1) They specified it correctly + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + else + { + // Do some string manipulation to try and find it + var direction = ''; + + if (ease.indexOf('.')) + { + // quad.in = Quad.easeIn + // quad.out = Quad.easeOut + // quad.inout =Quad.easeInOut + + direction = ease.substr(ease.indexOf('.') + 1); + + if (direction.toLowerCase() === 'in') + { + direction = 'easeIn'; + } + else if (direction.toLowerCase() === 'out') + { + direction = 'easeOut'; + } + else if (direction.toLowerCase() === 'inout') + { + direction = 'easeInOut'; + } + } + + ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); + + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + } + } + else if (typeof ease === 'function') + { + // Custom function + easeFunction = ease; + } + else if (Array.isArray(ease) && ease.length === 4) + { + // Bezier function (TODO) + } + + // No custom ease parameters? + if (!easeParams) + { + // Return ease function + return easeFunction; + } + + var cloneParams = easeParams.slice(0); + + cloneParams.unshift(0); + + // Return ease function with custom ease parameters + return function (v) + { + cloneParams[0] = v; + + return easeFunction.apply(this, cloneParams); + }; +}; + +module.exports = GetEaseFunction; + + +/***/ }), +/* 83 */ /***/ (function(module, exports) { /** @@ -15775,7 +15795,7 @@ module.exports = Contains; /***/ }), -/* 82 */ +/* 84 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -15851,7 +15871,7 @@ module.exports = LineToLine; /***/ }), -/* 83 */ +/* 85 */ /***/ (function(module, exports) { /** @@ -15879,7 +15899,7 @@ module.exports = Angle; /***/ }), -/* 84 */ +/* 86 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -15896,7 +15916,7 @@ var Vertices = {}; module.exports = Vertices; -var Vector = __webpack_require__(97); +var Vector = __webpack_require__(101); var Common = __webpack_require__(37); (function() { @@ -16340,7 +16360,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 85 */ +/* 87 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -16349,7 +16369,7 @@ var Common = __webpack_require__(37); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); /** * Return a value based on the range between `min` and `max` and the percentage given. @@ -16374,7 +16394,7 @@ module.exports = FromPercent; /***/ }), -/* 86 */ +/* 88 */ /***/ (function(module, exports) { /** @@ -16415,7 +16435,7 @@ module.exports = GetBoolean; /***/ }), -/* 87 */ +/* 89 */ /***/ (function(module, exports) { /** @@ -16587,7 +16607,7 @@ module.exports = TWEEN_CONST; /***/ }), -/* 88 */ +/* 90 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -16602,23 +16622,23 @@ module.exports = TWEEN_CONST; module.exports = { - DESTROY: __webpack_require__(577), - VIDEO_COMPLETE: __webpack_require__(578), - VIDEO_CREATED: __webpack_require__(579), - VIDEO_ERROR: __webpack_require__(580), - VIDEO_LOOP: __webpack_require__(581), - VIDEO_PLAY: __webpack_require__(582), - VIDEO_SEEKED: __webpack_require__(583), - VIDEO_SEEKING: __webpack_require__(584), - VIDEO_STOP: __webpack_require__(585), - VIDEO_TIMEOUT: __webpack_require__(586), - VIDEO_UNLOCKED: __webpack_require__(587) + DESTROY: __webpack_require__(576), + VIDEO_COMPLETE: __webpack_require__(577), + VIDEO_CREATED: __webpack_require__(578), + VIDEO_ERROR: __webpack_require__(579), + VIDEO_LOOP: __webpack_require__(580), + VIDEO_PLAY: __webpack_require__(581), + VIDEO_SEEKED: __webpack_require__(582), + VIDEO_SEEKING: __webpack_require__(583), + VIDEO_STOP: __webpack_require__(584), + VIDEO_TIMEOUT: __webpack_require__(585), + VIDEO_UNLOCKED: __webpack_require__(586) }; /***/ }), -/* 89 */ +/* 91 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -16630,11 +16650,11 @@ module.exports = { var Class = __webpack_require__(0); var Components = __webpack_require__(12); var DegToRad = __webpack_require__(35); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(48); -var Rectangle = __webpack_require__(13); -var TransformMatrix = __webpack_require__(30); -var ValueToColor = __webpack_require__(158); +var Rectangle = __webpack_require__(11); +var TransformMatrix = __webpack_require__(32); +var ValueToColor = __webpack_require__(161); var Vector2 = __webpack_require__(3); /** @@ -18539,7 +18559,7 @@ module.exports = BaseCamera; /***/ }), -/* 90 */ +/* 92 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -18554,18 +18574,18 @@ module.exports = BaseCamera; module.exports = { - ENTER_FULLSCREEN: __webpack_require__(695), - FULLSCREEN_FAILED: __webpack_require__(696), - FULLSCREEN_UNSUPPORTED: __webpack_require__(697), - LEAVE_FULLSCREEN: __webpack_require__(698), - ORIENTATION_CHANGE: __webpack_require__(699), - RESIZE: __webpack_require__(700) + ENTER_FULLSCREEN: __webpack_require__(694), + FULLSCREEN_FAILED: __webpack_require__(695), + FULLSCREEN_UNSUPPORTED: __webpack_require__(696), + LEAVE_FULLSCREEN: __webpack_require__(697), + ORIENTATION_CHANGE: __webpack_require__(698), + RESIZE: __webpack_require__(699) }; /***/ }), -/* 91 */ +/* 93 */ /***/ (function(module, exports) { /** @@ -18609,7 +18629,7 @@ module.exports = SnapFloor; /***/ }), -/* 92 */ +/* 94 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -18619,8 +18639,8 @@ module.exports = SnapFloor; */ var Class = __webpack_require__(0); -var Clamp = __webpack_require__(23); -var Extend = __webpack_require__(18); +var Clamp = __webpack_require__(22); +var Extend = __webpack_require__(17); /** * @classdesc @@ -19428,7 +19448,7 @@ module.exports = Frame; /***/ }), -/* 93 */ +/* 95 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19438,11 +19458,11 @@ module.exports = Frame; */ var Class = __webpack_require__(0); -var Contains = __webpack_require__(94); -var GetPoint = __webpack_require__(391); -var GetPoints = __webpack_require__(392); +var Contains = __webpack_require__(96); +var GetPoint = __webpack_require__(390); +var GetPoints = __webpack_require__(391); var GEOM_CONST = __webpack_require__(46); -var Random = __webpack_require__(151); +var Random = __webpack_require__(154); /** * @classdesc @@ -19810,7 +19830,7 @@ module.exports = Ellipse; /***/ }), -/* 94 */ +/* 96 */ /***/ (function(module, exports) { /** @@ -19852,7 +19872,7 @@ module.exports = Contains; /***/ }), -/* 95 */ +/* 97 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -19861,15 +19881,15 @@ module.exports = Contains; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Actions = __webpack_require__(236); +var Actions = __webpack_require__(238); var Class = __webpack_require__(0); -var Events = __webpack_require__(88); +var Events = __webpack_require__(90); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); var IsPlainObject = __webpack_require__(7); -var Range = __webpack_require__(385); -var Set = __webpack_require__(127); -var Sprite = __webpack_require__(73); +var Range = __webpack_require__(384); +var Set = __webpack_require__(108); +var Sprite = __webpack_require__(69); /** * @classdesc @@ -20378,7 +20398,7 @@ var Group = new Class({ * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. * @param {boolean} [addToScene=false] - Also add the Game Object to the scene. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ add: function (child, addToScene) { @@ -20427,7 +20447,7 @@ var Group = new Class({ * @param {Phaser.GameObjects.GameObject[]} children - The Game Objects to add. * @param {boolean} [addToScene=false] - Also add the Game Objects to the scene. * - * @return {this} This group. + * @return {Phaser.GameObjects.Group} This group. */ addMultiple: function (children, addToScene) { @@ -20456,7 +20476,7 @@ var Group = new Class({ * @param {boolean} [removeFromScene=false] - Optionally remove the Group member from the Scene it belongs to. * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group member. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ remove: function (child, removeFromScene, destroyChild) { @@ -20510,7 +20530,7 @@ var Group = new Class({ * @param {boolean} [removeFromScene=false] - Optionally remove each Group member from the Scene. * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group members. * - * @return {this} This group. + * @return {Phaser.GameObjects.Group} This group. */ clear: function (removeFromScene, destroyChild) { @@ -20873,7 +20893,7 @@ var Group = new Class({ * @param {string} key - The string-based key of the animation to play. * @param {string} [startFrame=0] - Optionally start the animation playing from this frame index. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ playAnimation: function (key, startFrame) { @@ -20972,7 +20992,7 @@ var Group = new Class({ * @param {integer} [index=0] - An optional offset to start searching from within the items array. * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ propertyValueSet: function (key, value, step, index, direction) { @@ -20993,7 +21013,7 @@ var Group = new Class({ * @param {integer} [index=0] - An optional offset to start searching from within the items array. * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ propertyValueInc: function (key, value, step, index, direction) { @@ -21011,7 +21031,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setX: function (value, step) { @@ -21029,7 +21049,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setY: function (value, step) { @@ -21049,7 +21069,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setXY: function (x, y, stepX, stepY) { @@ -21067,7 +21087,7 @@ var Group = new Class({ * @param {number} value - The amount to be added to the `x` property. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ incX: function (value, step) { @@ -21085,7 +21105,7 @@ var Group = new Class({ * @param {number} value - The amount to be added to the `y` property. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ incY: function (value, step) { @@ -21105,7 +21125,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ incXY: function (x, y, stepX, stepY) { @@ -21127,7 +21147,7 @@ var Group = new Class({ * @param {number} y - The y coordinate to place the first item in the array at. * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ shiftPosition: function (x, y, direction) { @@ -21145,7 +21165,7 @@ var Group = new Class({ * @param {number} value - The amount to set the angle to, in degrees. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ angle: function (value, step) { @@ -21163,7 +21183,7 @@ var Group = new Class({ * @param {number} value - The amount to set the rotation to, in radians. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ rotate: function (value, step) { @@ -21181,7 +21201,7 @@ var Group = new Class({ * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. * @param {number} angle - The angle to rotate by, in radians. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ rotateAround: function (point, angle) { @@ -21200,7 +21220,7 @@ var Group = new Class({ * @param {number} angle - The angle to rotate by, in radians. * @param {number} distance - The distance from the point of rotation in pixels. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ rotateAroundDistance: function (point, angle, distance) { @@ -21218,7 +21238,7 @@ var Group = new Class({ * @param {number} value - The amount to set the alpha to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setAlpha: function (value, step) { @@ -21238,7 +21258,7 @@ var Group = new Class({ * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setTint: function (topLeft, topRight, bottomLeft, bottomRight) { @@ -21258,7 +21278,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setOrigin: function (originX, originY, stepX, stepY) { @@ -21276,7 +21296,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ scaleX: function (value, step) { @@ -21294,7 +21314,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ scaleY: function (value, step) { @@ -21314,7 +21334,7 @@ var Group = new Class({ * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ scaleXY: function (scaleX, scaleY, stepX, stepY) { @@ -21332,7 +21352,7 @@ var Group = new Class({ * @param {number} value - The amount to set the property to. * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setDepth: function (value, step) { @@ -21349,7 +21369,7 @@ var Group = new Class({ * * @param {number} value - The amount to set the property to. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setBlendMode: function (value) { @@ -21367,7 +21387,7 @@ var Group = new Class({ * @param {*} 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 - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setHitArea: function (hitArea, hitAreaCallback) { @@ -21382,7 +21402,7 @@ var Group = new Class({ * @method Phaser.GameObjects.Group#shuffle * @since 3.21.0 * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ shuffle: function () { @@ -21434,7 +21454,7 @@ var Group = new Class({ * @param {integer} [index=0] - An optional offset to start searching from within the items array. * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ setVisible: function (value, index, direction) { @@ -21449,7 +21469,7 @@ var Group = new Class({ * @method Phaser.GameObjects.Group#toggleVisible * @since 3.0.0 * - * @return {this} This Group object. + * @return {Phaser.GameObjects.Group} This Group object. */ toggleVisible: function () { @@ -21490,7 +21510,7 @@ module.exports = Group; /***/ }), -/* 96 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -21499,7 +21519,137 @@ module.exports = Group; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Class = __webpack_require__(0); +var Components = __webpack_require__(12); +var GameObject = __webpack_require__(14); +var ImageRender = __webpack_require__(963); + +/** + * @classdesc + * An Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class Image + * @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.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Image = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + ImageRender + ], + + initialize: + + function Image (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Image'); + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Image#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + } + +}); + +module.exports = Image; + + +/***/ }), +/* 99 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determine whether the source object has a property with the specified key. + * + * @function Phaser.Utils.Objects.HasValue + * @since 3.0.0 + * + * @param {object} source - The source object to be checked. + * @param {string} key - The property to check for within the object + * + * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. + */ +var HasValue = function (source, key) +{ + return (source.hasOwnProperty(key)); +}; + +module.exports = HasValue; + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = __webpack_require__(10); /** * Renders a filled path for the given Shape. @@ -21554,7 +21704,7 @@ module.exports = FillPathWebGL; /***/ }), -/* 97 */ +/* 101 */ /***/ (function(module, exports) { /** @@ -21798,7 +21948,7 @@ module.exports = Vector; })(); /***/ }), -/* 98 */ +/* 102 */ /***/ (function(module, exports) { /** @@ -21924,7 +22074,7 @@ module.exports = Bounds; /***/ }), -/* 99 */ +/* 103 */ /***/ (function(module, exports) { /** @@ -21955,7 +22105,7 @@ module.exports = IsInLayerBounds; /***/ }), -/* 100 */ +/* 104 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -21966,7 +22116,6 @@ module.exports = IsInLayerBounds; var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(2); -var CONST = __webpack_require__(10); /** * @classdesc @@ -22070,15 +22219,6 @@ var LayerData = new Class({ */ this.baseTileHeight = GetFastValue(config, 'baseTileHeight', this.tileHeight); - /** - * The layer's orientation, necessary to be able to determine a tile's pixelX and pixelY as well as the layer's width and height. - * - * @name Phaser.Tilemaps.LayerData#orientation - * @type {string} - * @since 3.23beta.PR_svipal - */ - this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); - /** * The width in pixels of the entire layer. * @@ -22177,16 +22317,6 @@ var LayerData = new Class({ * @since 3.0.0 */ this.tilemapLayer = GetFastValue(config, 'tilemapLayer', null); - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); - } }); @@ -22195,7 +22325,7 @@ module.exports = LayerData; /***/ }), -/* 101 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -22206,7 +22336,6 @@ module.exports = LayerData; var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(2); -var CONST = __webpack_require__(10); /** * @classdesc @@ -22317,7 +22446,7 @@ var MapData = new Class({ * @type {string} * @since 3.0.0 */ - this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); + this.orientation = GetFastValue(config, 'orientation', 'orthogonal'); /** * Determines the draw order of tilemap. Default is right-down @@ -22413,15 +22542,6 @@ var MapData = new Class({ * @since 3.0.0 */ this.tiles = GetFastValue(config, 'tiles', []); - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); } }); @@ -22430,7 +22550,7 @@ module.exports = MapData; /***/ }), -/* 102 */ +/* 106 */ /***/ (function(module, exports) { /** @@ -22564,7 +22684,52 @@ module.exports = ALIGN_CONST; /***/ }), -/* 103 */ +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = __webpack_require__(67); + +/** + * Creates a new Object using all values from obj1 and obj2. + * If a value exists in both obj1 and obj2, the value in obj1 is used. + * + * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this + * function on shallow objects. + * + * @function Phaser.Utils.Objects.Merge + * @since 3.0.0 + * + * @param {object} obj1 - The first object. + * @param {object} obj2 - The second object. + * + * @return {object} A new object containing the union of obj1's and obj2's properties. + */ +var Merge = function (obj1, obj2) +{ + var clone = Clone(obj1); + + for (var key in obj2) + { + if (!clone.hasOwnProperty(key)) + { + clone[key] = obj2[key]; + } + } + + return clone; +}; + +module.exports = Merge; + + +/***/ }), +/* 108 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -22574,127 +22739,446 @@ module.exports = ALIGN_CONST; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameObject = __webpack_require__(14); -var ImageRender = __webpack_require__(961); + +/** + * @callback EachSetCallback + * + * @param {E} entry - The Set entry. + * @param {number} index - The index of the entry within the Set. + * + * @return {?boolean} The callback result. + */ /** * @classdesc - * An Image Game Object. + * A Set is a collection of unique elements. * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * - * @class Image - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects + * @class Set + * @memberof Phaser.Structs * @constructor * @since 3.0.0 * - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @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.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.TextureCrop - * @extends Phaser.GameObjects.Components.Tint - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible + * @generic T + * @genericUse {T[]} - [elements] * - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. */ -var Image = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - ImageRender - ], +var Set = new Class({ initialize: - function Image (scene, x, y, texture, frame) + function Set (elements) { - GameObject.call(this, scene, 'Image'); - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * The entries of this Set. Stored internally as an array. * - * @name Phaser.GameObjects.Image#_crop - * @type {object} - * @private - * @since 3.11.0 + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.Set#entries + * @type {Array.<*>} + * @default [] + * @since 3.0.0 */ - this._crop = this.resetCropObject(); + this.entries = []; + + if (Array.isArray(elements)) + { + for (var i = 0; i < elements.length; i++) + { + this.set(elements[i]); + } + } + }, + + /** + * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. + * + * @method Phaser.Structs.Set#set + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to insert into this Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + set: function (value) + { + if (this.entries.indexOf(value) === -1) + { + this.entries.push(value); + } + + return this; + }, + + /** + * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. + * If no elements of this Set satisfy the condition then this method will return `null`. + * + * @method Phaser.Structs.Set#get + * @since 3.0.0 + * + * @genericUse {T} - [value,$return] + * + * @param {string} property - The property name to check on the elements of this Set. + * @param {*} value - The value to check for. + * + * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. + */ + get: function (property, value) + { + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + + if (entry[property] === value) + { + return entry; + } + } + }, + + /** + * Returns an array containing all the values in this Set. + * + * @method Phaser.Structs.Set#getArray + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} An array containing all the values in this Set. + */ + getArray: function () + { + return this.entries.slice(0); + }, + + /** + * Removes the given value from this Set if this Set contains that value. + * + * @method Phaser.Structs.Set#delete + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to remove from the Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + delete: function (value) + { + var index = this.entries.indexOf(value); + + if (index > -1) + { + this.entries.splice(index, 1); + } + + return this; + }, + + /** + * Dumps the contents of this Set to the console via `console.group`. + * + * @method Phaser.Structs.Set#dump + * @since 3.0.0 + */ + dump: function () + { + // eslint-disable-next-line no-console + console.group('Set'); + + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + console.log(entry); + } + + // eslint-disable-next-line no-console + console.groupEnd(); + }, + + /** + * Passes each value in this Set to the given callback. + * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. + * + * @method Phaser.Structs.Set#each + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + each: function (callback, callbackScope) + { + var i; + var temp = this.entries.slice(); + var len = temp.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, temp[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(temp[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Passes each value in this Set to the given callback. + * For when you absolutely know this Set won't be modified during the iteration. + * + * @method Phaser.Structs.Set#iterate + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterate: function (callback, callbackScope) + { + var i; + var len = this.entries.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, this.entries[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(this.entries[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. + * + * @method Phaser.Structs.Set#iterateLocal + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {string} callbackKey - The key of the function to be invoked on each Set entry. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterateLocal: function (callbackKey) + { + var i; + var args = []; + + for (i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + var len = this.entries.length; + + for (i = 0; i < len; i++) + { + var entry = this.entries[i]; + + entry[callbackKey].apply(entry, args); + } + + return this; + }, + + /** + * Clears this Set so that it no longer contains any values. + * + * @method Phaser.Structs.Set#clear + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @return {Phaser.Structs.Set} This Set object. + */ + clear: function () + { + this.entries.length = 0; + + return this; + }, + + /** + * Returns `true` if this Set contains the given value, otherwise returns `false`. + * + * @method Phaser.Structs.Set#contains + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {*} value - The value to check for in this Set. + * + * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. + */ + contains: function (value) + { + return (this.entries.indexOf(value) > -1); + }, + + /** + * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. + * + * @method Phaser.Structs.Set#union + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the union with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. + */ + union: function (set) + { + var newSet = new Set(); + + set.entries.forEach(function (value) + { + newSet.set(value); + }); + + this.entries.forEach(function (value) + { + newSet.set(value); + }); + + return newSet; + }, + + /** + * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. + * + * @method Phaser.Structs.Set#intersect + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to intersect this set with. + * + * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. + */ + intersect: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * Returns a new Set containing all the values in this Set which are *not* also in the given Set. + * + * @method Phaser.Structs.Set#difference + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the difference with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. + */ + difference: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (!set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * The size of this Set. This is the number of entries within it. + * Changing the size will truncate the Set if the given value is smaller than the current size. + * Increasing the size larger than the current size has no effect. + * + * @name Phaser.Structs.Set#size + * @type {integer} + * @since 3.0.0 + */ + size: { + + get: function () + { + return this.entries.length; + }, + + set: function (value) + { + if (value < this.entries.length) + { + return this.entries.length = value; + } + else + { + return this.entries.length; + } + } - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.setOriginFromFrame(); - this.initPipeline(); } }); -module.exports = Image; +module.exports = Set; /***/ }), -/* 104 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determine whether the source object has a property with the specified key. - * - * @function Phaser.Utils.Objects.HasValue - * @since 3.0.0 - * - * @param {object} source - The source object to be checked. - * @param {string} key - The property to check for within the object - * - * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. - */ -var HasValue = function (source, key) -{ - return (source.hasOwnProperty(key)); -}; - -module.exports = HasValue; - - -/***/ }), -/* 105 */ +/* 109 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -22712,12 +23196,12 @@ var Bodies = {}; module.exports = Bodies; -var Vertices = __webpack_require__(84); +var Vertices = __webpack_require__(86); var Common = __webpack_require__(37); var Body = __webpack_require__(62); -var Bounds = __webpack_require__(98); -var Vector = __webpack_require__(97); -var decomp = __webpack_require__(1378); +var Bounds = __webpack_require__(102); +var Vector = __webpack_require__(101); +var decomp = __webpack_require__(1380); (function() { @@ -23052,7 +23536,7 @@ var decomp = __webpack_require__(1378); /***/ }), -/* 106 */ +/* 110 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -23062,12 +23546,12 @@ var decomp = __webpack_require__(1378); */ var BlendModes = __webpack_require__(52); -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); var CircleContains = __webpack_require__(55); var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); var RectangleContains = __webpack_require__(47); /** @@ -23213,7 +23697,7 @@ var Zone = new Class({ * @param {number} height - The height of this Game Object. * @param {boolean} [resizeInput=true] - If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setSize: function (width, height, resizeInput) { @@ -23245,7 +23729,7 @@ var Zone = new Class({ * @param {number} width - The width of this Game Object. * @param {number} height - The height of this Game Object. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setDisplaySize: function (width, height) { @@ -23264,7 +23748,7 @@ var Zone = new Class({ * * @param {number} radius - The radius of the Circle that will form the Drop Zone. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setCircleDropZone: function (radius) { @@ -23281,7 +23765,7 @@ var Zone = new Class({ * @param {number} width - The width of the rectangle drop zone. * @param {number} height - The height of the rectangle drop zone. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setRectangleDropZone: function (width, height) { @@ -23297,7 +23781,7 @@ var Zone = new Class({ * @param {object} shape - A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. * @param {Phaser.Types.Input.HitAreaCallback} callback - A function that will return `true` if the given x/y coords it is sent are within the shape. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Zone} This Game Object. */ setDropZone: function (shape, callback) { @@ -23365,7 +23849,7 @@ module.exports = Zone; /***/ }), -/* 107 */ +/* 111 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -23380,30 +23864,30 @@ module.exports = Zone; module.exports = { - ADD_ANIMATION: __webpack_require__(529), - ANIMATION_COMPLETE: __webpack_require__(530), - ANIMATION_REPEAT: __webpack_require__(531), - ANIMATION_RESTART: __webpack_require__(532), - ANIMATION_START: __webpack_require__(533), - PAUSE_ALL: __webpack_require__(534), - REMOVE_ANIMATION: __webpack_require__(535), - RESUME_ALL: __webpack_require__(536), - SPRITE_ANIMATION_COMPLETE: __webpack_require__(537), - SPRITE_ANIMATION_KEY_COMPLETE: __webpack_require__(538), - SPRITE_ANIMATION_KEY_REPEAT: __webpack_require__(539), - SPRITE_ANIMATION_KEY_RESTART: __webpack_require__(540), - SPRITE_ANIMATION_KEY_START: __webpack_require__(541), - SPRITE_ANIMATION_KEY_UPDATE: __webpack_require__(542), - SPRITE_ANIMATION_REPEAT: __webpack_require__(543), - SPRITE_ANIMATION_RESTART: __webpack_require__(544), - SPRITE_ANIMATION_START: __webpack_require__(545), - SPRITE_ANIMATION_UPDATE: __webpack_require__(546) + ADD_ANIMATION: __webpack_require__(528), + ANIMATION_COMPLETE: __webpack_require__(529), + ANIMATION_REPEAT: __webpack_require__(530), + ANIMATION_RESTART: __webpack_require__(531), + ANIMATION_START: __webpack_require__(532), + PAUSE_ALL: __webpack_require__(533), + REMOVE_ANIMATION: __webpack_require__(534), + RESUME_ALL: __webpack_require__(535), + SPRITE_ANIMATION_COMPLETE: __webpack_require__(536), + SPRITE_ANIMATION_KEY_COMPLETE: __webpack_require__(537), + SPRITE_ANIMATION_KEY_REPEAT: __webpack_require__(538), + SPRITE_ANIMATION_KEY_RESTART: __webpack_require__(539), + SPRITE_ANIMATION_KEY_START: __webpack_require__(540), + SPRITE_ANIMATION_KEY_UPDATE: __webpack_require__(541), + SPRITE_ANIMATION_REPEAT: __webpack_require__(542), + SPRITE_ANIMATION_RESTART: __webpack_require__(543), + SPRITE_ANIMATION_START: __webpack_require__(544), + SPRITE_ANIMATION_UPDATE: __webpack_require__(545) }; /***/ }), -/* 108 */ +/* 112 */ /***/ (function(module, exports) { /** @@ -23431,7 +23915,7 @@ module.exports = Perimeter; /***/ }), -/* 109 */ +/* 113 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -23441,7 +23925,7 @@ module.exports = Perimeter; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(279); +var Events = __webpack_require__(281); /** * @callback DataEachCallback @@ -24072,7 +24556,7 @@ module.exports = DataManager; /***/ }), -/* 110 */ +/* 114 */ /***/ (function(module, exports) { /** @@ -24113,7 +24597,7 @@ module.exports = Shuffle; /***/ }), -/* 111 */ +/* 115 */ /***/ (function(module, exports) { /** @@ -24143,7 +24627,7 @@ module.exports = Linear; /***/ }), -/* 112 */ +/* 116 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** @@ -24312,10 +24796,10 @@ function init () module.exports = init(); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(721))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(720))) /***/ }), -/* 113 */ +/* 117 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -24324,7 +24808,7 @@ module.exports = init(); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var OS = __webpack_require__(112); +var OS = __webpack_require__(116); /** * Determines the browser type and version running this Phaser Game instance. @@ -24425,7 +24909,7 @@ module.exports = init(); /***/ }), -/* 114 */ +/* 118 */ /***/ (function(module, exports) { /** @@ -24455,7 +24939,7 @@ module.exports = IsSizePowerOfTwo; /***/ }), -/* 115 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -24480,7 +24964,7 @@ module.exports = { /***/ }), -/* 116 */ +/* 120 */ /***/ (function(module, exports) { /** @@ -24538,7 +25022,7 @@ module.exports = AddToDOM; /***/ }), -/* 117 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -24547,7 +25031,7 @@ module.exports = AddToDOM; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SpliceOne = __webpack_require__(78); +var SpliceOne = __webpack_require__(79); /** * Removes the given item, or array of items, from the array. @@ -24629,7 +25113,7 @@ module.exports = Remove; /***/ }), -/* 118 */ +/* 122 */ /***/ (function(module, exports) { /** @@ -25535,7 +26019,7 @@ module.exports = KeyCodes; /***/ }), -/* 119 */ +/* 123 */ /***/ (function(module, exports) { /** @@ -25658,52 +26142,7 @@ module.exports = CONST; /***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = __webpack_require__(65); - -/** - * Creates a new Object using all values from obj1 and obj2. - * If a value exists in both obj1 and obj2, the value in obj1 is used. - * - * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this - * function on shallow objects. - * - * @function Phaser.Utils.Objects.Merge - * @since 3.0.0 - * - * @param {object} obj1 - The first object. - * @param {object} obj2 - The second object. - * - * @return {object} A new object containing the union of obj1's and obj2's properties. - */ -var Merge = function (obj1, obj2) -{ - var clone = Clone(obj1); - - for (var key in obj2) - { - if (!clone.hasOwnProperty(key)) - { - clone[key] = obj2[key]; - } - } - - return clone; -}; - -module.exports = Merge; - - -/***/ }), -/* 121 */ +/* 124 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -25714,10 +26153,10 @@ module.exports = Merge; */ var Class = __webpack_require__(0); -var Clone = __webpack_require__(65); -var EventEmitter = __webpack_require__(11); +var Clone = __webpack_require__(67); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(59); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var NOOP = __webpack_require__(1); /** @@ -26328,7 +26767,7 @@ module.exports = BaseSoundManager; /***/ }), -/* 122 */ +/* 125 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26339,9 +26778,9 @@ module.exports = BaseSoundManager; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(59); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); var NOOP = __webpack_require__(1); /** @@ -26828,7 +27267,7 @@ module.exports = BaseSound; /***/ }), -/* 123 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -26837,10 +27276,10 @@ module.exports = BaseSound; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayUtils = __webpack_require__(178); +var ArrayUtils = __webpack_require__(181); var Class = __webpack_require__(0); var NOOP = __webpack_require__(1); -var StableSort = __webpack_require__(125); +var StableSort = __webpack_require__(128); /** * @callback EachListCallback @@ -27644,7 +28083,7 @@ module.exports = List; /***/ }), -/* 124 */ +/* 127 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -27653,8 +28092,8 @@ module.exports = List; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CheckMatrix = __webpack_require__(179); -var TransposeMatrix = __webpack_require__(383); +var CheckMatrix = __webpack_require__(182); +var TransposeMatrix = __webpack_require__(382); /** * Rotates the array matrix based on the given rotation value. @@ -27716,7 +28155,7 @@ module.exports = RotateMatrix; /***/ }), -/* 125 */ +/* 128 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -27861,7 +28300,7 @@ else {} })(); /***/ }), -/* 126 */ +/* 129 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -27873,10 +28312,10 @@ else {} var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var GetBitmapTextSize = __webpack_require__(936); -var ParseFromAtlas = __webpack_require__(937); -var ParseXMLBitmapFont = __webpack_require__(182); -var Render = __webpack_require__(938); +var GetBitmapTextSize = __webpack_require__(938); +var ParseFromAtlas = __webpack_require__(939); +var ParseXMLBitmapFont = __webpack_require__(185); +var Render = __webpack_require__(940); /** * @classdesc @@ -28590,456 +29029,7 @@ module.exports = BitmapText; /***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); - -/** - * @callback EachSetCallback - * - * @param {E} entry - The Set entry. - * @param {number} index - The index of the entry within the Set. - * - * @return {?boolean} The callback result. - */ - -/** - * @classdesc - * A Set is a collection of unique elements. - * - * @class Set - * @memberof Phaser.Structs - * @constructor - * @since 3.0.0 - * - * @generic T - * @genericUse {T[]} - [elements] - * - * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. - */ -var Set = new Class({ - - initialize: - - function Set (elements) - { - /** - * The entries of this Set. Stored internally as an array. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.Set#entries - * @type {Array.<*>} - * @default [] - * @since 3.0.0 - */ - this.entries = []; - - if (Array.isArray(elements)) - { - for (var i = 0; i < elements.length; i++) - { - this.set(elements[i]); - } - } - }, - - /** - * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. - * - * @method Phaser.Structs.Set#set - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {*} value - The value to insert into this Set. - * - * @return {Phaser.Structs.Set} This Set object. - */ - set: function (value) - { - if (this.entries.indexOf(value) === -1) - { - this.entries.push(value); - } - - return this; - }, - - /** - * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. - * If no elements of this Set satisfy the condition then this method will return `null`. - * - * @method Phaser.Structs.Set#get - * @since 3.0.0 - * - * @genericUse {T} - [value,$return] - * - * @param {string} property - The property name to check on the elements of this Set. - * @param {*} value - The value to check for. - * - * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. - */ - get: function (property, value) - { - for (var i = 0; i < this.entries.length; i++) - { - var entry = this.entries[i]; - - if (entry[property] === value) - { - return entry; - } - } - }, - - /** - * Returns an array containing all the values in this Set. - * - * @method Phaser.Structs.Set#getArray - * @since 3.0.0 - * - * @genericUse {T[]} - [$return] - * - * @return {Array.<*>} An array containing all the values in this Set. - */ - getArray: function () - { - return this.entries.slice(0); - }, - - /** - * Removes the given value from this Set if this Set contains that value. - * - * @method Phaser.Structs.Set#delete - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {*} value - The value to remove from the Set. - * - * @return {Phaser.Structs.Set} This Set object. - */ - delete: function (value) - { - var index = this.entries.indexOf(value); - - if (index > -1) - { - this.entries.splice(index, 1); - } - - return this; - }, - - /** - * Dumps the contents of this Set to the console via `console.group`. - * - * @method Phaser.Structs.Set#dump - * @since 3.0.0 - */ - dump: function () - { - // eslint-disable-next-line no-console - console.group('Set'); - - for (var i = 0; i < this.entries.length; i++) - { - var entry = this.entries[i]; - console.log(entry); - } - - // eslint-disable-next-line no-console - console.groupEnd(); - }, - - /** - * Passes each value in this Set to the given callback. - * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. - * - * @method Phaser.Structs.Set#each - * @since 3.0.0 - * - * @genericUse {EachSetCallback.} - [callback] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. - * @param {*} [callbackScope] - The scope of the callback. - * - * @return {Phaser.Structs.Set} This Set object. - */ - each: function (callback, callbackScope) - { - var i; - var temp = this.entries.slice(); - var len = temp.length; - - if (callbackScope) - { - for (i = 0; i < len; i++) - { - if (callback.call(callbackScope, temp[i], i) === false) - { - break; - } - } - } - else - { - for (i = 0; i < len; i++) - { - if (callback(temp[i], i) === false) - { - break; - } - } - } - - return this; - }, - - /** - * Passes each value in this Set to the given callback. - * For when you absolutely know this Set won't be modified during the iteration. - * - * @method Phaser.Structs.Set#iterate - * @since 3.0.0 - * - * @genericUse {EachSetCallback.} - [callback] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. - * @param {*} [callbackScope] - The scope of the callback. - * - * @return {Phaser.Structs.Set} This Set object. - */ - iterate: function (callback, callbackScope) - { - var i; - var len = this.entries.length; - - if (callbackScope) - { - for (i = 0; i < len; i++) - { - if (callback.call(callbackScope, this.entries[i], i) === false) - { - break; - } - } - } - else - { - for (i = 0; i < len; i++) - { - if (callback(this.entries[i], i) === false) - { - break; - } - } - } - - return this; - }, - - /** - * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. - * - * @method Phaser.Structs.Set#iterateLocal - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {string} callbackKey - The key of the function to be invoked on each Set entry. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - * - * @return {Phaser.Structs.Set} This Set object. - */ - iterateLocal: function (callbackKey) - { - var i; - var args = []; - - for (i = 1; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - var len = this.entries.length; - - for (i = 0; i < len; i++) - { - var entry = this.entries[i]; - - entry[callbackKey].apply(entry, args); - } - - return this; - }, - - /** - * Clears this Set so that it no longer contains any values. - * - * @method Phaser.Structs.Set#clear - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @return {Phaser.Structs.Set} This Set object. - */ - clear: function () - { - this.entries.length = 0; - - return this; - }, - - /** - * Returns `true` if this Set contains the given value, otherwise returns `false`. - * - * @method Phaser.Structs.Set#contains - * @since 3.0.0 - * - * @genericUse {T} - [value] - * - * @param {*} value - The value to check for in this Set. - * - * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. - */ - contains: function (value) - { - return (this.entries.indexOf(value) > -1); - }, - - /** - * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. - * - * @method Phaser.Structs.Set#union - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to perform the union with. - * - * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. - */ - union: function (set) - { - var newSet = new Set(); - - set.entries.forEach(function (value) - { - newSet.set(value); - }); - - this.entries.forEach(function (value) - { - newSet.set(value); - }); - - return newSet; - }, - - /** - * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. - * - * @method Phaser.Structs.Set#intersect - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to intersect this set with. - * - * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. - */ - intersect: function (set) - { - var newSet = new Set(); - - this.entries.forEach(function (value) - { - if (set.contains(value)) - { - newSet.set(value); - } - }); - - return newSet; - }, - - /** - * Returns a new Set containing all the values in this Set which are *not* also in the given Set. - * - * @method Phaser.Structs.Set#difference - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to perform the difference with. - * - * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. - */ - difference: function (set) - { - var newSet = new Set(); - - this.entries.forEach(function (value) - { - if (!set.contains(value)) - { - newSet.set(value); - } - }); - - return newSet; - }, - - /** - * The size of this Set. This is the number of entries within it. - * Changing the size will truncate the Set if the given value is smaller than the current size. - * Increasing the size larger than the current size has no effect. - * - * @name Phaser.Structs.Set#size - * @type {integer} - * @since 3.0.0 - */ - size: { - - get: function () - { - return this.entries.length; - }, - - set: function (value) - { - if (value < this.entries.length) - { - return this.entries.length = value; - } - else - { - return this.entries.length; - } - } - - } - -}); - -module.exports = Set; - - -/***/ }), -/* 128 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29051,7 +29041,7 @@ module.exports = Set; var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var MeshRender = __webpack_require__(1068); +var MeshRender = __webpack_require__(1065); var NOOP = __webpack_require__(1); /** @@ -29210,7 +29200,7 @@ module.exports = Mesh; /***/ }), -/* 129 */ +/* 131 */ /***/ (function(module, exports) { /** @@ -29248,7 +29238,7 @@ module.exports = RectangleToRectangle; /***/ }), -/* 130 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29356,7 +29346,7 @@ module.exports = InputPluginCache; /***/ }), -/* 131 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29371,19 +29361,19 @@ module.exports = InputPluginCache; module.exports = { - ANY_KEY_DOWN: __webpack_require__(1207), - ANY_KEY_UP: __webpack_require__(1208), - COMBO_MATCH: __webpack_require__(1209), - DOWN: __webpack_require__(1210), - KEY_DOWN: __webpack_require__(1211), - KEY_UP: __webpack_require__(1212), - UP: __webpack_require__(1213) + ANY_KEY_DOWN: __webpack_require__(1203), + ANY_KEY_UP: __webpack_require__(1204), + COMBO_MATCH: __webpack_require__(1205), + DOWN: __webpack_require__(1206), + KEY_DOWN: __webpack_require__(1207), + KEY_UP: __webpack_require__(1208), + UP: __webpack_require__(1209) }; /***/ }), -/* 132 */ +/* 134 */ /***/ (function(module, exports) { /** @@ -29424,7 +29414,7 @@ module.exports = GetURL; /***/ }), -/* 133 */ +/* 135 */ /***/ (function(module, exports) { /** @@ -29444,18 +29434,16 @@ module.exports = GetURL; * @param {string} [user=''] - Optional username for the XHR request. * @param {string} [password=''] - Optional password for the XHR request. * @param {integer} [timeout=0] - Optional XHR timeout value. - * @param {boolean} [withCredentials=false] - Optional XHR withCredentials value. * * @return {Phaser.Types.Loader.XHRSettingsObject} The XHRSettings object as used by the Loader. */ -var XHRSettings = function (responseType, async, user, password, timeout, withCredentials) +var XHRSettings = function (responseType, async, user, password, timeout) { if (responseType === undefined) { responseType = ''; } if (async === undefined) { async = true; } if (user === undefined) { user = ''; } if (password === undefined) { password = ''; } if (timeout === undefined) { timeout = 0; } - if (withCredentials === undefined) { withCredentials = false; } // Before sending a request, set the xhr.responseType to "text", // "arraybuffer", "blob", or "document", depending on your data needs. @@ -29481,10 +29469,7 @@ var XHRSettings = function (responseType, async, user, password, timeout, withCr requestedWith: false, // overrideMimeType - overrideMimeType: undefined, - - // withCredentials - withCredentials: withCredentials + overrideMimeType: undefined }; }; @@ -29493,7 +29478,7 @@ module.exports = XHRSettings; /***/ }), -/* 134 */ +/* 136 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29503,8 +29488,8 @@ module.exports = XHRSettings; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(212); -var Sprite = __webpack_require__(73); +var Components = __webpack_require__(214); +var Sprite = __webpack_require__(69); /** * @classdesc @@ -29594,7 +29579,7 @@ module.exports = ArcadeSprite; /***/ }), -/* 135 */ +/* 137 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29609,54 +29594,54 @@ module.exports = ArcadeSprite; module.exports = { - CalculateFacesAt: __webpack_require__(215), + CalculateFacesAt: __webpack_require__(217), CalculateFacesWithin: __webpack_require__(51), - Copy: __webpack_require__(1303), - CreateFromTiles: __webpack_require__(1304), - CullTiles: __webpack_require__(1305), - Fill: __webpack_require__(1307), - FilterTiles: __webpack_require__(1308), - FindByIndex: __webpack_require__(1309), - FindTile: __webpack_require__(1310), - ForEachTile: __webpack_require__(1311), - GetTileAt: __webpack_require__(136), - GetTileAtWorldXY: __webpack_require__(1312), - GetTilesWithin: __webpack_require__(25), - GetTilesWithinShape: __webpack_require__(1313), - GetTilesWithinWorldXY: __webpack_require__(1314), - HasTileAt: __webpack_require__(469), - HasTileAtWorldXY: __webpack_require__(1315), - IsInLayerBounds: __webpack_require__(99), - PutTileAt: __webpack_require__(216), - PutTileAtWorldXY: __webpack_require__(1316), - PutTilesAt: __webpack_require__(1317), - Randomize: __webpack_require__(1318), - RemoveTileAt: __webpack_require__(470), - RemoveTileAtWorldXY: __webpack_require__(1319), - RenderDebug: __webpack_require__(1320), - ReplaceByIndex: __webpack_require__(468), - SetCollision: __webpack_require__(1321), - SetCollisionBetween: __webpack_require__(1322), - SetCollisionByExclusion: __webpack_require__(1323), - SetCollisionByProperty: __webpack_require__(1324), - SetCollisionFromCollisionGroup: __webpack_require__(1325), - SetTileIndexCallback: __webpack_require__(1326), - SetTileLocationCallback: __webpack_require__(1327), - Shuffle: __webpack_require__(1328), - SwapByIndex: __webpack_require__(1329), - TileToWorldX: __webpack_require__(1330), - TileToWorldXY: __webpack_require__(1331), - TileToWorldY: __webpack_require__(1332), - WeightedRandomize: __webpack_require__(1333), - WorldToTileX: __webpack_require__(471), - WorldToTileXY: __webpack_require__(1334), - WorldToTileY: __webpack_require__(472) + Copy: __webpack_require__(1301), + CreateFromTiles: __webpack_require__(1302), + CullTiles: __webpack_require__(1303), + Fill: __webpack_require__(1304), + FilterTiles: __webpack_require__(1305), + FindByIndex: __webpack_require__(1306), + FindTile: __webpack_require__(1307), + ForEachTile: __webpack_require__(1308), + GetTileAt: __webpack_require__(138), + GetTileAtWorldXY: __webpack_require__(1309), + GetTilesWithin: __webpack_require__(24), + GetTilesWithinShape: __webpack_require__(1310), + GetTilesWithinWorldXY: __webpack_require__(1311), + HasTileAt: __webpack_require__(470), + HasTileAtWorldXY: __webpack_require__(1312), + IsInLayerBounds: __webpack_require__(103), + PutTileAt: __webpack_require__(218), + PutTileAtWorldXY: __webpack_require__(1313), + PutTilesAt: __webpack_require__(1314), + Randomize: __webpack_require__(1315), + RemoveTileAt: __webpack_require__(471), + RemoveTileAtWorldXY: __webpack_require__(1316), + RenderDebug: __webpack_require__(1317), + ReplaceByIndex: __webpack_require__(469), + SetCollision: __webpack_require__(1318), + SetCollisionBetween: __webpack_require__(1319), + SetCollisionByExclusion: __webpack_require__(1320), + SetCollisionByProperty: __webpack_require__(1321), + SetCollisionFromCollisionGroup: __webpack_require__(1322), + SetTileIndexCallback: __webpack_require__(1323), + SetTileLocationCallback: __webpack_require__(1324), + Shuffle: __webpack_require__(1325), + SwapByIndex: __webpack_require__(1326), + TileToWorldX: __webpack_require__(139), + TileToWorldXY: __webpack_require__(1327), + TileToWorldY: __webpack_require__(140), + WeightedRandomize: __webpack_require__(1328), + WorldToTileX: __webpack_require__(63), + WorldToTileXY: __webpack_require__(1329), + WorldToTileY: __webpack_require__(64) }; /***/ }), -/* 136 */ +/* 138 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -29665,7 +29650,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var IsInLayerBounds = __webpack_require__(99); +var IsInLayerBounds = __webpack_require__(103); /** * Gets a tile at the given tile coordinates from the given layer. @@ -29712,7 +29697,97 @@ module.exports = GetTileAt; /***/ }), -/* 137 */ +/* 139 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldX + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var TileToWorldX = function (tileX, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + var layerWorldX = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + + tileWidth *= tilemapLayer.scaleX; + } + + return layerWorldX + tileX * tileWidth; +}; + +module.exports = TileToWorldX; + + +/***/ }), +/* 140 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldY + * @private + * @since 3.0.0 + * + * @param {integer} tileY - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var TileToWorldY = function (tileY, camera, layer) +{ + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + return layerWorldY + tileY * tileHeight; +}; + +module.exports = TileToWorldY; + + +/***/ }), +/* 141 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30116,7 +30191,7 @@ module.exports = Tileset; /***/ }), -/* 138 */ +/* 142 */ /***/ (function(module, exports) { /** @@ -30180,7 +30255,7 @@ module.exports = GetNewValue; /***/ }), -/* 139 */ +/* 143 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -30189,17 +30264,17 @@ module.exports = GetNewValue; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Defaults = __webpack_require__(225); +var Defaults = __webpack_require__(227); var GetAdvancedValue = __webpack_require__(15); -var GetBoolean = __webpack_require__(86); -var GetEaseFunction = __webpack_require__(67); -var GetNewValue = __webpack_require__(138); -var GetProps = __webpack_require__(493); -var GetTargets = __webpack_require__(223); +var GetBoolean = __webpack_require__(88); +var GetEaseFunction = __webpack_require__(82); +var GetNewValue = __webpack_require__(142); +var GetProps = __webpack_require__(492); +var GetTargets = __webpack_require__(225); var GetValue = __webpack_require__(6); -var GetValueOp = __webpack_require__(224); -var Tween = __webpack_require__(226); -var TweenData = __webpack_require__(228); +var GetValueOp = __webpack_require__(226); +var Tween = __webpack_require__(228); +var TweenData = __webpack_require__(230); /** * Creates a new Tween. @@ -30313,7 +30388,7 @@ module.exports = TweenBuilder; /***/ }), -/* 140 */ +/* 144 */ /***/ (function(module, exports) { /** @@ -30347,776 +30422,7 @@ module.exports = Equal; /***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = __webpack_require__(0); -var Utils = __webpack_require__(9); - -/** - * @classdesc - * WebGLPipeline is a class that describes the way elements will be renderered - * in WebGL, specially focused on batching vertices (batching is not provided). - * Pipelines are mostly used for describing 2D rendering passes but it's - * flexible enough to be used for any type of rendering including 3D. - * Internally WebGLPipeline will handle things like compiling shaders, - * creating vertex buffers, assigning primitive topology and binding - * vertex attributes. - * - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - gl: Current WebGL context. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - vertices: An optional buffer of vertices - * - attributes: An array describing the vertex attributes - * - * The vertex attributes properties are: - * - name : String - Name of the attribute in the vertex shader - * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 - * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) - * - normalized : boolean - Is the attribute normalized - * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C - * Here you can find more information of how to describe an attribute: - * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer - * - * @class WebGLPipeline - * @memberof Phaser.Renderer.WebGL - * @constructor - * @since 3.0.0 - * - * @param {object} config - The configuration object for this WebGL Pipeline, as described above. - */ -var WebGLPipeline = new Class({ - - initialize: - - function WebGLPipeline (config) - { - /** - * Name of the Pipeline. Used for identifying - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#name - * @type {string} - * @since 3.0.0 - */ - this.name = 'WebGLPipeline'; - - /** - * The Game which owns this WebGL Pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = config.game; - - /** - * The canvas which this WebGL Pipeline renders to. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#view - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.view = config.game.canvas; - - /** - * Used to store the current game resolution - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution - * @type {number} - * @since 3.0.0 - */ - this.resolution = 1; - - /** - * Width of the current viewport - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#width - * @type {number} - * @since 3.0.0 - */ - this.width = 0; - - /** - * Height of the current viewport - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#height - * @type {number} - * @since 3.0.0 - */ - this.height = 0; - - /** - * The WebGL context this WebGL Pipeline uses. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#gl - * @type {WebGLRenderingContext} - * @since 3.0.0 - */ - this.gl = config.gl; - - /** - * How many vertices have been fed to the current pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.vertexCount = 0; - - /** - * The limit of vertices that the pipeline can hold - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity - * @type {integer} - * @since 3.0.0 - */ - this.vertexCapacity = config.vertexCapacity; - - /** - * The WebGL Renderer which owns this WebGL Pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer - * @type {Phaser.Renderer.WebGL.WebGLRenderer} - * @since 3.0.0 - */ - this.renderer = config.renderer; - - /** - * Raw byte buffer of vertices. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData - * @type {ArrayBuffer} - * @since 3.0.0 - */ - this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); - - /** - * The handle to a WebGL vertex buffer object. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer - * @type {WebGLBuffer} - * @since 3.0.0 - */ - this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); - - /** - * The handle to a WebGL program - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#program - * @type {WebGLProgram} - * @since 3.0.0 - */ - this.program = this.renderer.createProgram(config.vertShader, config.fragShader); - - /** - * Array of objects that describe the vertex attributes - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes - * @type {object} - * @since 3.0.0 - */ - this.attributes = config.attributes; - - /** - * The size in bytes of the vertex - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize - * @type {integer} - * @since 3.0.0 - */ - this.vertexSize = config.vertexSize; - - /** - * The primitive topology which the pipeline will use to submit draw calls - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#topology - * @type {integer} - * @since 3.0.0 - */ - this.topology = config.topology; - - /** - * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources - * to the GPU. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes - * @type {Uint8Array} - * @since 3.0.0 - */ - this.bytes = new Uint8Array(this.vertexData); - - /** - * This will store the amount of components of 32 bit length - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount - * @type {integer} - * @since 3.0.0 - */ - this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); - - /** - * Indicates if the current pipeline is flushing the contents to the GPU. - * When the variable is set the flush function will be locked. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked - * @type {boolean} - * @since 3.1.0 - */ - this.flushLocked = false; - - /** - * Indicates if the current pipeline is active or not for this frame only. - * Reset in the onRender method. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#active - * @type {boolean} - * @since 3.10.0 - */ - this.active = false; - }, - - /** - * Called when the Game has fully booted and the Renderer has finished setting up. - * - * By this stage all Game level systems are now in place and you can perform any final - * tasks that the pipeline may need that relied on game systems such as the Texture Manager. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#boot - * @since 3.11.0 - */ - boot: function () - { - }, - - /** - * Adds a description of vertex attribute to the pipeline - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute - * @since 3.2.0 - * - * @param {string} name - Name of the vertex attribute - * @param {integer} size - Vertex component size - * @param {integer} type - Type of the attribute - * @param {boolean} normalized - Is the value normalized to a range - * @param {integer} offset - Byte offset to the beginning of the first element in the vertex - * - * @return {this} This WebGLPipeline instance. - */ - addAttribute: function (name, size, type, normalized, offset) - { - this.attributes.push({ - name: name, - size: size, - type: this.renderer.glFormats[type], - normalized: normalized, - offset: offset - }); - - this.vertexComponentCount = Utils.getComponentCount( - this.attributes, - this.gl - ); - return this; - }, - - /** - * Check if the current batch of vertices is full. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush - * @since 3.0.0 - * - * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. - */ - shouldFlush: function () - { - return (this.vertexCount >= this.vertexCapacity); - }, - - /** - * Resizes the properties used to describe the viewport - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#resize - * @since 3.0.0 - * - * @param {number} width - The new width of this WebGL Pipeline. - * @param {number} height - The new height of this WebGL Pipeline. - * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - this.width = width * resolution; - this.height = height * resolution; - this.resolution = resolution; - - return this; - }, - - /** - * Binds the pipeline resources, including programs, vertex buffers and binds attributes - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#bind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - bind: function () - { - var gl = this.gl; - var vertexBuffer = this.vertexBuffer; - var attributes = this.attributes; - var program = this.program; - var renderer = this.renderer; - var vertexSize = this.vertexSize; - - renderer.setProgram(program); - renderer.setVertexBuffer(vertexBuffer); - - for (var index = 0; index < attributes.length; ++index) - { - var element = attributes[index]; - var location = gl.getAttribLocation(program, element.name); - - if (location >= 0) - { - gl.enableVertexAttribArray(location); - gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); - } - else if (location !== -1) - { - gl.disableVertexAttribArray(location); - } - } - - return this; - }, - - /** - * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. - * - * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - // This is for updating uniform data it's called on each bind attempt. - return this; - }, - - /** - * Called before each frame is rendered, but after the canvas has been cleared. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onPreRender: function () - { - // called once every frame - return this; - }, - - /** - * Called before a Scene's Camera is rendered. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene being rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. - * - * @return {this} This WebGLPipeline instance. - */ - onRender: function () - { - // called for each camera - return this; - }, - - /** - * Called after each frame has been completely rendered and snapshots have been taken. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onPostRender: function () - { - // called once every frame - return this; - }, - - /** - * Uploads the vertex data and emits a draw call - * for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#flush - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - flush: function () - { - if (this.flushLocked) { return this; } - - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - - if (vertexCount === 0) - { - this.flushLocked = false; - return; - } - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); - gl.drawArrays(topology, 0, vertexCount); - - this.vertexCount = 0; - this.flushLocked = false; - - return this; - }, - - /** - * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - destroy: function () - { - var gl = this.gl; - - gl.deleteProgram(this.program); - gl.deleteBuffer(this.vertexBuffer); - - delete this.program; - delete this.vertexBuffer; - delete this.gl; - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new value of the `float` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat1: function (name, x) - { - this.renderer.setFloat1(this.program, name, x); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new X component of the `vec2` uniform. - * @param {number} y - The new Y component of the `vec2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat2: function (name, x, y) - { - this.renderer.setFloat2(this.program, name, x, y); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new X component of the `vec3` uniform. - * @param {number} y - The new Y component of the `vec3` uniform. - * @param {number} z - The new Z component of the `vec3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat3: function (name, x, y, z) - { - this.renderer.setFloat3(this.program, name, x, y, z); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - X component of the uniform - * @param {number} y - Y component of the uniform - * @param {number} z - Z component of the uniform - * @param {number} w - W component of the uniform - * - * @return {this} This WebGLPipeline instance. - */ - setFloat4: function (name, x, y, z, w) - { - this.renderer.setFloat4(this.program, name, x, y, z, w); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat1v: function (name, arr) - { - this.renderer.setFloat1v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat2v: function (name, arr) - { - this.renderer.setFloat2v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat3v: function (name, arr) - { - this.renderer.setFloat3v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat4v: function (name, arr) - { - this.renderer.setFloat4v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new value of the `int` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt1: function (name, x) - { - this.renderer.setInt1(this.program, name, x); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new X component of the `ivec2` uniform. - * @param {integer} y - The new Y component of the `ivec2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt2: function (name, x, y) - { - this.renderer.setInt2(this.program, name, x, y); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new X component of the `ivec3` uniform. - * @param {integer} y - The new Y component of the `ivec3` uniform. - * @param {integer} z - The new Z component of the `ivec3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt3: function (name, x, y, z) - { - this.renderer.setInt3(this.program, name, x, y, z); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - X component of the uniform - * @param {integer} y - Y component of the uniform - * @param {integer} z - Z component of the uniform - * @param {integer} w - W component of the uniform - * - * @return {this} This WebGLPipeline instance. - */ - setInt4: function (name, x, y, z, w) - { - this.renderer.setInt4(this.program, name, x, y, z, w); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. - * @param {Float32Array} matrix - The new values for the `mat2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix2: function (name, transpose, matrix) - { - this.renderer.setMatrix2(this.program, name, transpose, matrix); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. - * @param {Float32Array} matrix - The new values for the `mat3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix3: function (name, transpose, matrix) - { - this.renderer.setMatrix3(this.program, name, transpose, matrix); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Should the matrix be transpose - * @param {Float32Array} matrix - Matrix data - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix4: function (name, transpose, matrix) - { - this.renderer.setMatrix4(this.program, name, transpose, matrix); - - return this; - } - -}); - -module.exports = WebGLPipeline; - - -/***/ }), -/* 142 */ +/* 145 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31134,9 +30440,9 @@ var Composite = {}; module.exports = Composite; -var Events = __webpack_require__(235); +var Events = __webpack_require__(237); var Common = __webpack_require__(37); -var Bounds = __webpack_require__(98); +var Bounds = __webpack_require__(102); var Body = __webpack_require__(62); (function() { @@ -31810,7 +31116,7 @@ var Body = __webpack_require__(62); /***/ }), -/* 143 */ +/* 146 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31849,7 +31155,7 @@ module.exports = CircumferencePoint; /***/ }), -/* 144 */ +/* 147 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31893,7 +31199,7 @@ module.exports = Random; /***/ }), -/* 145 */ +/* 148 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -31902,12 +31208,12 @@ module.exports = Random; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(107); -var FindClosestInSorted = __webpack_require__(265); -var Frame = __webpack_require__(266); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(111); +var FindClosestInSorted = __webpack_require__(267); +var Frame = __webpack_require__(268); var GetValue = __webpack_require__(6); /** @@ -32122,7 +31428,7 @@ var Animation = new Class({ * @method Phaser.Animations.Animation#addFrame * @since 3.0.0 * - * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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|Phaser.Types.Animations.AnimationFrame[])} config - [description] * * @return {Phaser.Animations.Animation} This Animation object. */ @@ -32138,7 +31444,7 @@ var Animation = new Class({ * @since 3.0.0 * * @param {integer} index - The index to insert the frame at within the animation. - * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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|Phaser.Types.Animations.AnimationFrame[])} config - [description] * * @return {Phaser.Animations.Animation} This Animation object. */ @@ -32186,14 +31492,13 @@ var Animation = new Class({ }, /** - * Called internally when this Animation completes playback. - * Optionally, hides the parent Game Object, then stops playback. + * [description] * * @method Phaser.Animations.Animation#completeAnimation * @protected * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ completeAnimation: function (component) { @@ -32206,15 +31511,14 @@ var Animation = new Class({ }, /** - * Called internally when this Animation first starts to play. - * Sets the accumulator and nextTick properties. + * [description] * * @method Phaser.Animations.Animation#getFirstTick * @protected * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - * @param {boolean} [includeDelay=true] - If `true` the Animation Components delay value will be added to the `nextTick` total. + * @param {Phaser.GameObjects.Components.Animation} component - [description] + * @param {boolean} [includeDelay=true] - [description] */ getFirstTick: function (component, includeDelay) { @@ -32247,16 +31551,16 @@ var Animation = new Class({ }, /** - * Creates AnimationFrame instances based on the given frame data. + * [description] * * @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. + * @param {Phaser.Textures.TextureManager} textureManager - [description] + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} frames - [description] + * @param {string} [defaultTextureKey] - [description] * - * @return {Phaser.Animations.AnimationFrame[]} An array of newly created AnimationFrame instances. + * @return {Phaser.Animations.AnimationFrame[]} [description] */ getFrames: function (textureManager, frames, defaultTextureKey) { @@ -32349,12 +31653,12 @@ var Animation = new Class({ }, /** - * Called internally. Sets the accumulator and nextTick values of the current Animation. + * [description] * * @method Phaser.Animations.Animation#getNextTick * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ getNextTick: function (component) { @@ -32524,13 +31828,12 @@ var Animation = new Class({ }, /** - * Called internally when the Animation is playing backwards. - * Sets the previous frame, causing a yoyo, repeat, complete or update, accordingly. + * [description] * * @method Phaser.Animations.Animation#previousFrame * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ previousFrame: function (component) { @@ -32588,13 +31891,12 @@ var Animation = new Class({ }, /** - * Removes the given AnimationFrame from this Animation instance. - * This is a global action. Any Game Object using this Animation will be impacted by this change. + * [description] * * @method Phaser.Animations.Animation#removeFrame * @since 3.0.0 * - * @param {Phaser.Animations.AnimationFrame} frame - The AnimationFrame to be removed. + * @param {Phaser.Animations.AnimationFrame} frame - [description] * * @return {Phaser.Animations.Animation} This Animation object. */ @@ -32631,8 +31933,7 @@ var Animation = new Class({ }, /** - * Called internally during playback. Forces the animation to repeat, providing there are enough counts left - * in the repeat counter. + * [description] * * @method Phaser.Animations.Animation#repeatAnimation * @fires Phaser.Animations.Events#ANIMATION_REPEAT @@ -32640,7 +31941,7 @@ var Animation = new Class({ * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ repeatAnimation: function (component) { @@ -32685,7 +31986,7 @@ var Animation = new Class({ * @method Phaser.Animations.Animation#setFrame * @since 3.0.0 * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {Phaser.GameObjects.Components.Animation} component - [description] */ setFrame: function (component) { @@ -32706,7 +32007,7 @@ var Animation = new Class({ * @method Phaser.Animations.Animation#toJSON * @since 3.0.0 * - * @return {Phaser.Types.Animations.JSONAnimation} The resulting JSONAnimation formatted object. + * @return {Phaser.Types.Animations.JSONAnimation} [description] */ toJSON: function () { @@ -32734,7 +32035,7 @@ var Animation = new Class({ }, /** - * Called internally whenever frames are added to, or removed from, this Animation. + * [description] * * @method Phaser.Animations.Animation#updateFrameSequence * @since 3.0.0 @@ -32791,7 +32092,7 @@ var Animation = new Class({ }, /** - * Pauses playback of this Animation. The paused state is set immediately. + * [description] * * @method Phaser.Animations.Animation#pause * @since 3.0.0 @@ -32806,7 +32107,7 @@ var Animation = new Class({ }, /** - * Resumes playback of this Animation. The paused state is reset immediately. + * [description] * * @method Phaser.Animations.Animation#resume * @since 3.0.0 @@ -32821,9 +32122,7 @@ var Animation = new Class({ }, /** - * Destroys this Animation instance. It will remove all event listeners, - * remove this animation and its key from the global Animation Manager, - * and then destroy all Animation Frames in turn. + * [description] * * @method Phaser.Animations.Animation#destroy * @since 3.0.0 @@ -32853,7 +32152,7 @@ module.exports = Animation; /***/ }), -/* 146 */ +/* 149 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -32862,26 +32161,22 @@ module.exports = Animation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Perimeter = __webpack_require__(108); +var Perimeter = __webpack_require__(112); var Point = __webpack_require__(4); /** - * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. - * - * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. - * - * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. + * Position is a value between 0 and 1 where 0 = the top-left of the rectangle and 0.5 = the bottom right. * * @function Phaser.Geom.Rectangle.GetPoint * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. - * @param {number} position - The normalized distance into the Rectangle's perimeter to return. - * @param {(Phaser.Geom.Point|object)} [out] - An object to update with the `x` and `y` coordinates of the point. + * @param {Phaser.Geom.Rectangle} rectangle - [description] + * @param {number} position - [description] + * @param {(Phaser.Geom.Point|object)} [out] - [description] * - * @return {Phaser.Geom.Point} The updated `output` object, or a new Point if no `output` object was given. + * @return {Phaser.Geom.Point} [description] */ var GetPoint = function (rectangle, position, out) { @@ -32934,7 +32229,7 @@ module.exports = GetPoint; /***/ }), -/* 147 */ +/* 150 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -32999,7 +32294,7 @@ module.exports = GetPoints; /***/ }), -/* 148 */ +/* 151 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33039,7 +32334,7 @@ module.exports = Random; /***/ }), -/* 149 */ +/* 152 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33077,7 +32372,7 @@ module.exports = Random; /***/ }), -/* 150 */ +/* 153 */ /***/ (function(module, exports) { /** @@ -33206,7 +32501,7 @@ module.exports = Pipeline; /***/ }), -/* 151 */ +/* 154 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33247,7 +32542,7 @@ module.exports = Random; /***/ }), -/* 152 */ +/* 155 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33259,17 +32554,17 @@ module.exports = Random; var Point = __webpack_require__(4); /** - * Returns a random Point from within the area of the given Triangle. + * [description] * * @function Phaser.Geom.Triangle.Random * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get a random point from. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Triangle} triangle - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of a random position within the Triangle. + * @return {Phaser.Geom.Point} [description] */ var Random = function (triangle, out) { @@ -33303,7 +32598,7 @@ module.exports = Random; /***/ }), -/* 153 */ +/* 156 */ /***/ (function(module, exports) { /** @@ -33340,7 +32635,7 @@ module.exports = RotateAroundDistance; /***/ }), -/* 154 */ +/* 157 */ /***/ (function(module, exports) { /** @@ -33379,7 +32674,7 @@ module.exports = SmootherStep; /***/ }), -/* 155 */ +/* 158 */ /***/ (function(module, exports) { /** @@ -33426,7 +32721,7 @@ module.exports = SmoothStep; /***/ }), -/* 156 */ +/* 159 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33799,7 +33094,7 @@ module.exports = Map; /***/ }), -/* 157 */ +/* 160 */ /***/ (function(module, exports) { /** @@ -33875,7 +33170,7 @@ module.exports = Pad; /***/ }), -/* 158 */ +/* 161 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33884,10 +33179,10 @@ module.exports = Pad; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HexStringToColor = __webpack_require__(289); -var IntegerToColor = __webpack_require__(292); -var ObjectToColor = __webpack_require__(294); -var RGBStringToColor = __webpack_require__(295); +var HexStringToColor = __webpack_require__(291); +var IntegerToColor = __webpack_require__(294); +var ObjectToColor = __webpack_require__(296); +var RGBStringToColor = __webpack_require__(297); /** * Converts the given source color value into an instance of a Color class. @@ -33931,7 +33226,7 @@ module.exports = ValueToColor; /***/ }), -/* 159 */ +/* 162 */ /***/ (function(module, exports) { /** @@ -33961,7 +33256,7 @@ module.exports = GetColor; /***/ }), -/* 160 */ +/* 163 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -33970,7 +33265,7 @@ module.exports = GetColor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetColor = __webpack_require__(159); +var GetColor = __webpack_require__(162); /** * Converts an HSV (hue, saturation and value) color value to RGB. @@ -34062,7 +33357,7 @@ module.exports = HSVToRGB; /***/ }), -/* 161 */ +/* 164 */ /***/ (function(module, exports) { /** @@ -34194,7 +33489,7 @@ module.exports = Smoothing(); /***/ }), -/* 162 */ +/* 165 */ /***/ (function(module, exports) { /** @@ -34231,7 +33526,7 @@ module.exports = CenterOn; /***/ }), -/* 163 */ +/* 166 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -34240,18 +33535,18 @@ module.exports = CenterOn; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Back = __webpack_require__(297); -var Bounce = __webpack_require__(298); -var Circular = __webpack_require__(299); -var Cubic = __webpack_require__(300); -var Elastic = __webpack_require__(301); -var Expo = __webpack_require__(302); -var Linear = __webpack_require__(303); -var Quadratic = __webpack_require__(304); -var Quartic = __webpack_require__(305); -var Quintic = __webpack_require__(306); -var Sine = __webpack_require__(307); -var Stepped = __webpack_require__(308); +var Back = __webpack_require__(299); +var Bounce = __webpack_require__(300); +var Circular = __webpack_require__(301); +var Cubic = __webpack_require__(302); +var Elastic = __webpack_require__(303); +var Expo = __webpack_require__(304); +var Linear = __webpack_require__(305); +var Quadratic = __webpack_require__(306); +var Quartic = __webpack_require__(307); +var Quintic = __webpack_require__(308); +var Sine = __webpack_require__(309); +var Stepped = __webpack_require__(310); // EaseMap module.exports = { @@ -34312,7 +33607,7 @@ module.exports = { /***/ }), -/* 164 */ +/* 167 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -34321,9 +33616,9 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var OS = __webpack_require__(112); -var Browser = __webpack_require__(113); -var CanvasPool = __webpack_require__(27); +var OS = __webpack_require__(116); +var Browser = __webpack_require__(117); +var CanvasPool = __webpack_require__(26); /** * Determines the features of the browser running this Phaser Game instance. @@ -34504,7 +33799,7 @@ module.exports = init(); /***/ }), -/* 165 */ +/* 168 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -34513,8 +33808,8 @@ module.exports = init(); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(13); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Math @@ -34523,8 +33818,8 @@ var Extend = __webpack_require__(18); var PhaserMath = { // Collections of functions - Angle: __webpack_require__(726), - Distance: __webpack_require__(734), + Angle: __webpack_require__(725), + Distance: __webpack_require__(733), Easing: __webpack_require__(739), Fuzzy: __webpack_require__(740), Interpolation: __webpack_require__(743), @@ -34536,48 +33831,48 @@ var PhaserMath = { // Single functions Average: __webpack_require__(753), - Bernstein: __webpack_require__(318), - Between: __webpack_require__(167), - CatmullRom: __webpack_require__(166), + Bernstein: __webpack_require__(319), + Between: __webpack_require__(170), + CatmullRom: __webpack_require__(169), CeilTo: __webpack_require__(754), - Clamp: __webpack_require__(23), + Clamp: __webpack_require__(22), DegToRad: __webpack_require__(35), Difference: __webpack_require__(755), - Factorial: __webpack_require__(319), - FloatBetween: __webpack_require__(325), + Factorial: __webpack_require__(320), + FloatBetween: __webpack_require__(326), FloorTo: __webpack_require__(756), - FromPercent: __webpack_require__(85), + FromPercent: __webpack_require__(87), GetSpeed: __webpack_require__(757), IsEven: __webpack_require__(758), IsEvenStrict: __webpack_require__(759), - Linear: __webpack_require__(111), + Linear: __webpack_require__(115), MaxAdd: __webpack_require__(760), MinSub: __webpack_require__(761), Percent: __webpack_require__(762), - RadToDeg: __webpack_require__(168), + RadToDeg: __webpack_require__(171), RandomXY: __webpack_require__(763), RandomXYZ: __webpack_require__(764), RandomXYZW: __webpack_require__(765), - Rotate: __webpack_require__(326), - RotateAround: __webpack_require__(271), - RotateAroundDistance: __webpack_require__(153), - RoundAwayFromZero: __webpack_require__(327), + Rotate: __webpack_require__(327), + RotateAround: __webpack_require__(273), + RotateAroundDistance: __webpack_require__(156), + RoundAwayFromZero: __webpack_require__(328), RoundTo: __webpack_require__(766), SinCosTableGenerator: __webpack_require__(767), - SmootherStep: __webpack_require__(154), - SmoothStep: __webpack_require__(155), + SmootherStep: __webpack_require__(157), + SmoothStep: __webpack_require__(158), ToXY: __webpack_require__(768), - TransformXY: __webpack_require__(328), + TransformXY: __webpack_require__(329), Within: __webpack_require__(769), Wrap: __webpack_require__(58), // Vector classes Vector2: __webpack_require__(3), - Vector3: __webpack_require__(169), - Vector4: __webpack_require__(329), - Matrix3: __webpack_require__(330), - Matrix4: __webpack_require__(331), - Quaternion: __webpack_require__(332), + Vector3: __webpack_require__(172), + Vector4: __webpack_require__(330), + Matrix3: __webpack_require__(331), + Matrix4: __webpack_require__(332), + Quaternion: __webpack_require__(333), RotateVec3: __webpack_require__(770) }; @@ -34592,7 +33887,7 @@ module.exports = PhaserMath; /***/ }), -/* 166 */ +/* 169 */ /***/ (function(module, exports) { /** @@ -34602,16 +33897,16 @@ module.exports = PhaserMath; */ /** - * Calculates a Catmull-Rom value from the given points, based on an alpha of 0.5. + * Calculates a Catmull-Rom value. * * @function Phaser.Math.CatmullRom * @since 3.0.0 * - * @param {number} t - The amount to interpolate by. - * @param {number} p0 - The first control point. - * @param {number} p1 - The second control point. - * @param {number} p2 - The third control point. - * @param {number} p3 - The fourth control point. + * @param {number} t - [description] + * @param {number} p0 - [description] + * @param {number} p1 - [description] + * @param {number} p2 - [description] + * @param {number} p3 - [description] * * @return {number} The Catmull-Rom value. */ @@ -34629,7 +33924,7 @@ module.exports = CatmullRom; /***/ }), -/* 167 */ +/* 170 */ /***/ (function(module, exports) { /** @@ -34658,7 +33953,7 @@ module.exports = Between; /***/ }), -/* 168 */ +/* 171 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -34667,7 +33962,7 @@ module.exports = Between; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); +var CONST = __webpack_require__(13); /** * Convert the given angle in radians, to the equivalent angle in degrees. @@ -34688,7 +33983,7 @@ module.exports = RadToDeg; /***/ }), -/* 169 */ +/* 172 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35498,7 +34793,7 @@ module.exports = Vector3; /***/ }), -/* 170 */ +/* 173 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35599,7 +34894,7 @@ module.exports = DefaultPlugins; /***/ }), -/* 171 */ +/* 174 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35608,8 +34903,8 @@ module.exports = DefaultPlugins; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var MATH_CONST = __webpack_require__(16); +var Rectangle = __webpack_require__(11); +var MATH_CONST = __webpack_require__(13); // points is an array of Point-like objects, // either 2 dimensional arrays, or objects with public x/y properties: @@ -35685,7 +34980,7 @@ module.exports = FromPoints; /***/ }), -/* 172 */ +/* 175 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35696,10 +34991,10 @@ module.exports = FromPoints; var CONST = { - CENTER: __webpack_require__(354), - ORIENTATION: __webpack_require__(355), - SCALE_MODE: __webpack_require__(356), - ZOOM: __webpack_require__(357) + CENTER: __webpack_require__(353), + ORIENTATION: __webpack_require__(354), + SCALE_MODE: __webpack_require__(355), + ZOOM: __webpack_require__(356) }; @@ -35707,7 +35002,7 @@ module.exports = CONST; /***/ }), -/* 173 */ +/* 176 */ /***/ (function(module, exports) { /** @@ -35736,7 +35031,7 @@ module.exports = RemoveFromDOM; /***/ }), -/* 174 */ +/* 177 */ /***/ (function(module, exports) { /** @@ -35834,7 +35129,7 @@ module.exports = INPUT_CONST; /***/ }), -/* 175 */ +/* 178 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -35844,13 +35139,13 @@ module.exports = INPUT_CONST; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(119); -var DefaultPlugins = __webpack_require__(170); -var Events = __webpack_require__(22); -var GetPhysicsPlugins = __webpack_require__(869); -var GetScenePlugins = __webpack_require__(870); +var CONST = __webpack_require__(123); +var DefaultPlugins = __webpack_require__(173); +var Events = __webpack_require__(19); +var GetPhysicsPlugins = __webpack_require__(871); +var GetScenePlugins = __webpack_require__(872); var NOOP = __webpack_require__(1); -var Settings = __webpack_require__(370); +var Settings = __webpack_require__(369); /** * @classdesc @@ -36608,7 +35903,7 @@ module.exports = Systems; /***/ }), -/* 176 */ +/* 179 */ /***/ (function(module, exports) { /** @@ -36645,7 +35940,7 @@ module.exports = UppercaseFirst; /***/ }), -/* 177 */ +/* 180 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -36655,8 +35950,8 @@ module.exports = UppercaseFirst; */ var Class = __webpack_require__(0); -var Frame = __webpack_require__(92); -var TextureSource = __webpack_require__(373); +var Frame = __webpack_require__(94); +var TextureSource = __webpack_require__(372); var TEXTURE_MISSING_ERROR = 'Texture.frame missing: '; @@ -37165,7 +36460,7 @@ module.exports = Texture; /***/ }), -/* 178 */ +/* 181 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -37180,45 +36475,45 @@ module.exports = Texture; module.exports = { - Matrix: __webpack_require__(905), + Matrix: __webpack_require__(907), - Add: __webpack_require__(912), - AddAt: __webpack_require__(913), - BringToTop: __webpack_require__(914), - CountAllMatching: __webpack_require__(915), - Each: __webpack_require__(916), - EachInRange: __webpack_require__(917), - FindClosestInSorted: __webpack_require__(265), - GetAll: __webpack_require__(918), - GetFirst: __webpack_require__(919), - GetRandom: __webpack_require__(180), - MoveDown: __webpack_require__(920), - MoveTo: __webpack_require__(921), - MoveUp: __webpack_require__(922), - NumberArray: __webpack_require__(923), - NumberArrayStep: __webpack_require__(924), - QuickSelect: __webpack_require__(384), - Range: __webpack_require__(385), - Remove: __webpack_require__(117), - RemoveAt: __webpack_require__(925), - RemoveBetween: __webpack_require__(926), - RemoveRandomElement: __webpack_require__(927), - Replace: __webpack_require__(928), - RotateLeft: __webpack_require__(281), - RotateRight: __webpack_require__(282), - SafeRange: __webpack_require__(66), - SendToBack: __webpack_require__(929), - SetAll: __webpack_require__(930), - Shuffle: __webpack_require__(110), - SpliceOne: __webpack_require__(78), - StableSort: __webpack_require__(125), - Swap: __webpack_require__(931) + Add: __webpack_require__(914), + AddAt: __webpack_require__(915), + BringToTop: __webpack_require__(916), + CountAllMatching: __webpack_require__(917), + Each: __webpack_require__(918), + EachInRange: __webpack_require__(919), + FindClosestInSorted: __webpack_require__(267), + GetAll: __webpack_require__(920), + GetFirst: __webpack_require__(921), + GetRandom: __webpack_require__(183), + MoveDown: __webpack_require__(922), + MoveTo: __webpack_require__(923), + MoveUp: __webpack_require__(924), + NumberArray: __webpack_require__(925), + NumberArrayStep: __webpack_require__(926), + QuickSelect: __webpack_require__(383), + Range: __webpack_require__(384), + Remove: __webpack_require__(121), + RemoveAt: __webpack_require__(927), + RemoveBetween: __webpack_require__(928), + RemoveRandomElement: __webpack_require__(929), + Replace: __webpack_require__(930), + RotateLeft: __webpack_require__(283), + RotateRight: __webpack_require__(284), + SafeRange: __webpack_require__(68), + SendToBack: __webpack_require__(931), + SetAll: __webpack_require__(932), + Shuffle: __webpack_require__(114), + SpliceOne: __webpack_require__(79), + StableSort: __webpack_require__(128), + Swap: __webpack_require__(933) }; /***/ }), -/* 179 */ +/* 182 */ /***/ (function(module, exports) { /** @@ -37279,7 +36574,7 @@ module.exports = CheckMatrix; /***/ }), -/* 180 */ +/* 183 */ /***/ (function(module, exports) { /** @@ -37314,7 +36609,7 @@ module.exports = GetRandom; /***/ }), -/* 181 */ +/* 184 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -37324,8 +36619,8 @@ module.exports = GetRandom; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(933); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(935); /** * @classdesc @@ -37605,7 +36900,7 @@ module.exports = ProcessQueue; /***/ }), -/* 182 */ +/* 185 */ /***/ (function(module, exports) { /** @@ -37744,7 +37039,7 @@ module.exports = ParseXMLBitmapFont; /***/ }), -/* 183 */ +/* 186 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -37753,13 +37048,13 @@ module.exports = ParseXMLBitmapFont; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BlitterRender = __webpack_require__(941); -var Bob = __webpack_require__(944); +var BlitterRender = __webpack_require__(943); +var Bob = __webpack_require__(946); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Frame = __webpack_require__(92); +var Frame = __webpack_require__(94); var GameObject = __webpack_require__(14); -var List = __webpack_require__(123); +var List = __webpack_require__(126); /** * @callback CreateCallback @@ -38043,7 +37338,7 @@ module.exports = Blitter; /***/ }), -/* 184 */ +/* 187 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -38053,15 +37348,15 @@ module.exports = Blitter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayUtils = __webpack_require__(178); +var ArrayUtils = __webpack_require__(181); var BlendModes = __webpack_require__(52); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Events = __webpack_require__(88); +var Events = __webpack_require__(90); var GameObject = __webpack_require__(14); -var Rectangle = __webpack_require__(13); -var Render = __webpack_require__(945); -var Union = __webpack_require__(387); +var Rectangle = __webpack_require__(11); +var Render = __webpack_require__(947); +var Union = __webpack_require__(386); var Vector2 = __webpack_require__(3); /** @@ -38395,7 +37690,7 @@ var Container = new Class({ * * @param {boolean} [value=true] - The exclusive state of this Container. * - * @return {this} This Container. + * @return {Phaser.GameObjects.Container} This Container. */ setExclusive: function (value) { @@ -38556,7 +37851,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ add: function (child) { @@ -38578,7 +37873,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. * @param {integer} [index=0] - The position to insert the Game Object/s at. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ addAt: function (child, index) { @@ -38627,7 +37922,7 @@ var Container = new Class({ * @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 boolean. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ sort: function (property, handler) { @@ -38769,7 +38064,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject} child1 - The first Game Object to swap. * @param {Phaser.GameObjects.GameObject} child2 - The second Game Object to swap. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ swap: function (child1, child2) { @@ -38792,7 +38087,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject} child - The Game Object to move. * @param {integer} index - The new position of the Game Object in this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ moveTo: function (child, index) { @@ -38814,7 +38109,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to be removed from the Container. * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each child successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ remove: function (child, destroyChild) { @@ -38847,7 +38142,7 @@ var Container = new Class({ * @param {integer} index - The index of the Game Object to be removed. * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ removeAt: function (index, destroyChild) { @@ -38873,7 +38168,7 @@ var Container = new Class({ * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ removeBetween: function (startIndex, endIndex, destroyChild) { @@ -38900,7 +38195,7 @@ var Container = new Class({ * * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ removeAll: function (destroyChild) { @@ -38926,7 +38221,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to bring to the top of the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ bringToTop: function (child) { @@ -38944,7 +38239,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to send to the bottom of the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ sendToBack: function (child) { @@ -38961,7 +38256,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ moveUp: function (child) { @@ -38978,7 +38273,7 @@ var Container = new Class({ * * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ moveDown: function (child) { @@ -38993,7 +38288,7 @@ var Container = new Class({ * @method Phaser.GameObjects.Container#reverse * @since 3.4.0 * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ reverse: function () { @@ -39008,7 +38303,7 @@ var Container = new Class({ * @method Phaser.GameObjects.Container#shuffle * @since 3.4.0 * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ shuffle: function () { @@ -39028,7 +38323,7 @@ var Container = new Class({ * @param {Phaser.GameObjects.GameObject} newChild - The Game Object to be added to this Container. * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ replace: function (oldChild, newChild, destroyChild) { @@ -39080,7 +38375,7 @@ var Container = new Class({ * @param {integer} [startIndex=0] - An optional start index to search from. * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ setAll: function (property, value, startIndex, endIndex) { @@ -39113,7 +38408,7 @@ var Container = new Class({ * @param {object} [context] - Value to use as `this` when executing callback. * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ each: function (callback, context) { @@ -39150,7 +38445,7 @@ var Container = new Class({ * @param {object} [context] - Value to use as `this` when executing callback. * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. * - * @return {this} This Container instance. + * @return {Phaser.GameObjects.Container} This Container instance. */ iterate: function (callback, context) { @@ -39368,7 +38663,7 @@ module.exports = Container; /***/ }), -/* 185 */ +/* 188 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -39377,9 +38672,9 @@ module.exports = Container; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(126); +var BitmapText = __webpack_require__(129); var Class = __webpack_require__(0); -var Render = __webpack_require__(950); +var Render = __webpack_require__(952); /** * @classdesc @@ -39528,7 +38823,7 @@ var DynamicBitmapText = new Class({ * @param {number} width - The width of the crop. * @param {number} height - The height of the crop. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setSize: function (width, height) { @@ -39552,7 +38847,7 @@ var DynamicBitmapText = new Class({ * * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallback} callback - The display callback to set. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setDisplayCallback: function (callback) { @@ -39569,7 +38864,7 @@ var DynamicBitmapText = new Class({ * * @param {number} value - The horizontal scroll position to set. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setScrollX: function (value) { @@ -39586,7 +38881,7 @@ var DynamicBitmapText = new Class({ * * @param {number} value - The vertical scroll position to set. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object. */ setScrollY: function (value) { @@ -39601,7 +38896,7 @@ module.exports = DynamicBitmapText; /***/ }), -/* 186 */ +/* 189 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -39610,26 +38905,26 @@ module.exports = DynamicBitmapText; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCamera = __webpack_require__(89); +var BaseCamera = __webpack_require__(91); var Class = __webpack_require__(0); -var Commands = __webpack_require__(187); -var ComponentsAlpha = __webpack_require__(264); -var ComponentsBlendMode = __webpack_require__(267); -var ComponentsDepth = __webpack_require__(268); -var ComponentsMask = __webpack_require__(272); -var ComponentsPipeline = __webpack_require__(150); -var ComponentsTransform = __webpack_require__(277); -var ComponentsVisible = __webpack_require__(278); -var ComponentsScrollFactor = __webpack_require__(275); +var Commands = __webpack_require__(190); +var ComponentsAlpha = __webpack_require__(266); +var ComponentsBlendMode = __webpack_require__(269); +var ComponentsDepth = __webpack_require__(270); +var ComponentsMask = __webpack_require__(274); +var ComponentsPipeline = __webpack_require__(153); +var ComponentsTransform = __webpack_require__(279); +var ComponentsVisible = __webpack_require__(280); +var ComponentsScrollFactor = __webpack_require__(277); -var TransformMatrix = __webpack_require__(30); +var TransformMatrix = __webpack_require__(32); -var Ellipse = __webpack_require__(93); +var Ellipse = __webpack_require__(95); var GameObject = __webpack_require__(14); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); -var MATH_CONST = __webpack_require__(16); -var Render = __webpack_require__(956); +var MATH_CONST = __webpack_require__(13); +var Render = __webpack_require__(958); /** * @classdesc @@ -39849,7 +39144,7 @@ var Graphics = new Class({ * * @param {Phaser.Types.GameObjects.Graphics.Styles} options - The styles to set as defaults. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ setDefaultStyles: function (options) { @@ -39883,7 +39178,7 @@ var Graphics = new Class({ * @param {number} color - The stroke color. * @param {number} [alpha=1] - The stroke alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineStyle: function (lineWidth, color, alpha) { @@ -39908,7 +39203,7 @@ var Graphics = new Class({ * @param {number} color - The fill color. * @param {number} [alpha=1] - The fill alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillStyle: function (color, alpha) { @@ -39947,7 +39242,7 @@ var Graphics = new Class({ * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. * @param {number} [alpha=1] - The fill alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillGradientStyle: function (topLeft, topRight, bottomLeft, bottomRight, alpha) { @@ -39985,7 +39280,7 @@ var Graphics = new Class({ * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. * @param {number} [alpha=1] - The fill alpha. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineGradientStyle: function (lineWidth, topLeft, topRight, bottomLeft, bottomRight, alpha) { @@ -40061,7 +39356,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#beginPath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ beginPath: function () { @@ -40078,7 +39373,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#closePath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ closePath: function () { @@ -40095,7 +39390,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#fillPath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPath: function () { @@ -40115,7 +39410,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#fill * @since 3.16.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fill: function () { @@ -40132,7 +39427,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#strokePath * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokePath: function () { @@ -40152,7 +39447,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#stroke * @since 3.16.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ stroke: function () { @@ -40171,7 +39466,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Circle} circle - The circle to fill. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillCircleShape: function (circle) { @@ -40186,7 +39481,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Circle} circle - The circle to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeCircleShape: function (circle) { @@ -40203,7 +39498,7 @@ var Graphics = new Class({ * @param {number} y - The y coordinate of the center of the circle. * @param {number} radius - The radius of the circle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillCircle: function (x, y, radius) { @@ -40224,7 +39519,7 @@ var Graphics = new Class({ * @param {number} y - The y coordinate of the center of the circle. * @param {number} radius - The radius of the circle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeCircle: function (x, y, radius) { @@ -40243,7 +39538,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Rectangle} rect - The rectangle to fill. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillRectShape: function (rect) { @@ -40258,7 +39553,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Rectangle} rect - The rectangle to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeRectShape: function (rect) { @@ -40276,7 +39571,7 @@ var Graphics = new Class({ * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillRect: function (x, y, width, height) { @@ -40299,7 +39594,7 @@ var Graphics = new Class({ * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeRect: function (x, y, width, height) { @@ -40342,7 +39637,7 @@ var Graphics = new Class({ * @param {number} height - The height of the rectangle. * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillRoundedRect: function (x, y, width, height, radius) { @@ -40388,7 +39683,7 @@ var Graphics = new Class({ * @param {number} height - The height of the rectangle. * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeRoundedRect: function (x, y, width, height, radius) { @@ -40433,7 +39728,7 @@ var Graphics = new Class({ * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The point to fill. * @param {number} [size=1] - The size of the square to draw. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPointShape: function (point, size) { @@ -40452,7 +39747,7 @@ var Graphics = new Class({ * @param {number} y - The y coordinate of the point. * @param {number} [size=1] - The size of the square to draw. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPoint: function (x, y, size) { @@ -40482,7 +39777,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Triangle} triangle - The triangle to fill. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillTriangleShape: function (triangle) { @@ -40497,7 +39792,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Triangle} triangle - The triangle to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeTriangleShape: function (triangle) { @@ -40517,7 +39812,7 @@ var Graphics = new Class({ * @param {number} x2 - The x coordinate of the third point. * @param {number} y2 - The y coordinate of the third point. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillTriangle: function (x0, y0, x1, y1, x2, y2) { @@ -40542,7 +39837,7 @@ var Graphics = new Class({ * @param {number} x2 - The x coordinate of the third point. * @param {number} y2 - The y coordinate of the third point. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeTriangle: function (x0, y0, x1, y1, x2, y2) { @@ -40562,7 +39857,7 @@ var Graphics = new Class({ * * @param {Phaser.Geom.Line} line - The line to stroke. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeLineShape: function (line) { @@ -40580,7 +39875,7 @@ var Graphics = new Class({ * @param {number} x2 - The x coordinate of the end point of the line. * @param {number} y2 - The y coordinate of the end point of the line. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineBetween: function (x1, y1, x2, y2) { @@ -40603,7 +39898,7 @@ var Graphics = new Class({ * @param {number} x - The x coordinate to draw the line to. * @param {number} y - The y coordinate to draw the line to. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ lineTo: function (x, y) { @@ -40624,7 +39919,7 @@ var Graphics = new Class({ * @param {number} x - The x coordinate to move to. * @param {number} y - The y coordinate to move to. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ moveTo: function (x, y) { @@ -40651,7 +39946,7 @@ var Graphics = new Class({ * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. * @param {integer} [endIndex] - The index of `points` to stop drawing at. Defaults to `points.length`. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokePoints: function (points, closeShape, closePath, endIndex) { @@ -40698,7 +39993,7 @@ var Graphics = new Class({ * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. * @param {integer} [endIndex] - The index of `points` to stop at. Defaults to `points.length`. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillPoints: function (points, closeShape, closePath, endIndex) { @@ -40739,7 +40034,7 @@ var Graphics = new Class({ * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to stroke. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeEllipseShape: function (ellipse, smoothness) { @@ -40762,7 +40057,7 @@ var Graphics = new Class({ * @param {number} height - The height of the ellipse. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ strokeEllipse: function (x, y, width, height, smoothness) { @@ -40784,7 +40079,7 @@ var Graphics = new Class({ * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to fill. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillEllipseShape: function (ellipse, smoothness) { @@ -40807,7 +40102,7 @@ var Graphics = new Class({ * @param {number} height - The height of the ellipse. * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ fillEllipse: function (x, y, width, height, smoothness) { @@ -40846,7 +40141,7 @@ var Graphics = new Class({ * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. * @param {number} [overshoot=0] - This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ arc: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) { @@ -40882,7 +40177,7 @@ var Graphics = new Class({ * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. * @param {number} [overshoot=0] - This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ slice: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) { @@ -40908,7 +40203,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#save * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ save: function () { @@ -40929,7 +40224,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#restore * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ restore: function () { @@ -40955,7 +40250,7 @@ var Graphics = new Class({ * @param {number} x - The horizontal translation to apply. * @param {number} y - The vertical translation to apply. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ translateCanvas: function (x, y) { @@ -40982,7 +40277,7 @@ var Graphics = new Class({ * @param {number} x - The horizontal scale to apply. * @param {number} y - The vertical scale to apply. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ scaleCanvas: function (x, y) { @@ -41008,7 +40303,7 @@ var Graphics = new Class({ * * @param {number} radians - The rotation angle, in radians. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ rotateCanvas: function (radians) { @@ -41026,7 +40321,7 @@ var Graphics = new Class({ * @method Phaser.GameObjects.Graphics#clear * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ clear: function () { @@ -41061,7 +40356,7 @@ var Graphics = new Class({ * @param {integer} [width] - The width of the graphics to generate. * @param {integer} [height] - The height of the graphics to generate. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Graphics} This Game Object. */ generateTexture: function (key, width, height) { @@ -41151,7 +40446,7 @@ module.exports = Graphics; /***/ }), -/* 187 */ +/* 190 */ /***/ (function(module, exports) { /** @@ -41188,7 +40483,7 @@ module.exports = { /***/ }), -/* 188 */ +/* 191 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -41230,7 +40525,7 @@ module.exports = CircumferencePoint; /***/ }), -/* 189 */ +/* 192 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -41242,10 +40537,10 @@ module.exports = CircumferencePoint; var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var GravityWell = __webpack_require__(395); -var List = __webpack_require__(123); -var ParticleEmitter = __webpack_require__(397); -var Render = __webpack_require__(966); +var GravityWell = __webpack_require__(394); +var List = __webpack_require__(126); +var ParticleEmitter = __webpack_require__(396); +var Render = __webpack_require__(968); /** * @classdesc @@ -41395,7 +40690,7 @@ var ParticleEmitterManager = new Class({ * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ setTexture: function (key, frame) { @@ -41416,7 +40711,7 @@ var ParticleEmitterManager = new Class({ * * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ setFrame: function (frame) { @@ -41447,7 +40742,7 @@ var ParticleEmitterManager = new Class({ * @param {(Phaser.Textures.Frame|Phaser.Textures.Frame[])} frames - The texture frames. * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The particle emitter to modify. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ setEmitterFrames: function (frames, emitter) { @@ -41567,7 +40862,7 @@ var ParticleEmitterManager = new Class({ * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ emitParticle: function (count, x, y) { @@ -41596,7 +40891,7 @@ var ParticleEmitterManager = new Class({ * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ emitParticleAt: function (x, y, count) { @@ -41613,7 +40908,7 @@ var ParticleEmitterManager = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitterManager#pause * @since 3.0.0 * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ pause: function () { @@ -41628,7 +40923,7 @@ var ParticleEmitterManager = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitterManager#resume * @since 3.0.0 * - * @return {this} This Emitter Manager. + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} This Emitter Manager. */ resume: function () { @@ -41719,7 +41014,7 @@ module.exports = ParticleEmitterManager; /***/ }), -/* 190 */ +/* 193 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -41729,16 +41024,16 @@ module.exports = ParticleEmitterManager; */ var BlendModes = __webpack_require__(52); -var Camera = __webpack_require__(89); -var CanvasPool = __webpack_require__(27); +var Camera = __webpack_require__(91); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var CONST = __webpack_require__(10); -var Frame = __webpack_require__(92); +var CONST = __webpack_require__(29); +var Frame = __webpack_require__(94); var GameObject = __webpack_require__(14); -var Render = __webpack_require__(970); -var Utils = __webpack_require__(9); -var UUID = __webpack_require__(191); +var Render = __webpack_require__(972); +var Utils = __webpack_require__(10); +var UUID = __webpack_require__(194); /** * @classdesc @@ -42958,7 +42253,7 @@ module.exports = RenderTexture; /***/ }), -/* 191 */ +/* 194 */ /***/ (function(module, exports) { /** @@ -42993,7 +42288,7 @@ module.exports = UUID; /***/ }), -/* 192 */ +/* 195 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -43002,1123 +42297,17 @@ module.exports = UUID; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ +var AddToDOM = __webpack_require__(120); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); var Components = __webpack_require__(12); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); -var RopeRender = __webpack_require__(976); -var Vector2 = __webpack_require__(3); - -/** - * @classdesc - * A Rope Game Object. - * - * A Ropes origin is always 0.5 x 0.5 and cannot be changed. - * - * @class Rope - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @webglOnly - * @since 3.23.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * @extends Phaser.GameObjects.Components.ScrollFactor - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {string} [texture] - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. If not given, `__DEFAULT` is used. - * @param {(string|integer|null)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {(integer|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. See `setPoints` to set this post-creation. - * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? - * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. - * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. - */ -var Rope = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.Mask, - Components.Pipeline, - Components.Size, - Components.Texture, - Components.Transform, - Components.Visible, - Components.ScrollFactor, - RopeRender - ], - - initialize: - - function Rope (scene, x, y, texture, frame, points, horizontal, colors, alphas) - { - if (texture === undefined) { texture = '__DEFAULT'; } - if (points === undefined) { points = 2; } - if (horizontal === undefined) { horizontal = true; } - - GameObject.call(this, scene, 'Rope'); - - /** - * The Animation Controller of this Rope. - * - * @name Phaser.GameObjects.Rope#anims - * @type {Phaser.GameObjects.Components.Animation} - * @since 3.23.0 - */ - this.anims = new Components.Animation(this); - - /** - * An array containing the points data for this Rope. - * - * Each point should be given as a Vector2Like object (i.e. a Vector2, Geom.Point or object with public x/y properties). - * - * The point coordinates are given in local space, where 0 x 0 is the start of the Rope strip. - * - * You can modify the contents of this array directly in real-time to create interesting effects. - * If you do so, be sure to call `setDirty` _after_ modifying this array, so that the vertices data is - * updated before the next render. Alternatively, you can use the `setPoints` method instead. - * - * Should you need to change the _size_ of this array, then you should always use the `setPoints` method. - * - * @name Phaser.GameObjects.Rope#points - * @type {Phaser.Math.Types.Vector2Like[]} - * @since 3.23.0 - */ - this.points = points; - - /** - * 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 - */ - this.vertices; - - /** - * 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 - */ - this.uv; - - /** - * An array containing the color data for this Rope. - * - * Colors should be given as numeric RGB values, such as 0xff0000. - * You should provide _two_ color values for every point in the Rope, one for the top and one for the bottom of each quad. - * - * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ - * of the array, then you should use the `setColors` method instead. - * - * @name Phaser.GameObjects.Rope#colors - * @type {Uint32Array} - * @since 3.23.0 - */ - this.colors; - - /** - * An array containing the alpha data for this Rope. - * - * Alphas should be given as float values, such as 0.5. - * You should provide _two_ alpha values for every point in the Rope, one for the top and one for the bottom of each quad. - * - * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ - * of the array, then you should use the `setAlphas` method instead. - * - * @name Phaser.GameObjects.Rope#alphas - * @type {Float32Array} - * @since 3.23.0 - */ - this.alphas; - - /** - * The tint fill mode. - * - * 0 = An additive tint (the default), where vertices colors are blended with the texture. - * 1 = A fill tint, where the vertices colors replace the texture, but respects texture alpha. - * 2 = A complete tint, where the vertices colors replace the texture, including alpha, entirely. - * - * @name Phaser.GameObjects.Rope#tintFill - * @type {integer} - * @since 3.23.0 - */ - this.tintFill = (texture === '__DEFAULT') ? 2 : 0; - - /** - * If the Rope is marked as `dirty` it will automatically recalculate its vertices - * the next time it renders. You can also force this by calling `updateVertices`. - * - * @name Phaser.GameObjects.Rope#dirty - * @type {boolean} - * @since 3.23.0 - */ - this.dirty = false; - - /** - * Are the Rope vertices aligned horizontally, in a strip, or vertically, in a column? - * - * This property is set during instantiation and cannot be changed directly. - * See the `setVertical` and `setHorizontal` methods. - * - * @name Phaser.GameObjects.Rope#horizontal - * @type {boolean} - * @readonly - * @since 3.23.0 - */ - this.horizontal = horizontal; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#_flipX - * @type {boolean} - * @default false - * @private - * @since 3.23.0 - */ - this._flipX = false; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipY - * @type {boolean} - * @default false - * @private - * @since 3.23.0 - */ - this._flipY = false; - - /** - * Internal Vector2 used for vertices updates. - * - * @name Phaser.GameObjects.Rope#_perp - * @type {Phaser.Math.Vector2} - * @private - * @since 3.23.0 - */ - this._perp = new Vector2(); - - /** - * You can optionally choose to render the vertices of this Rope to a Graphics instance. - * - * Achieve this by setting the `debugCallback` and the `debugGraphic` properties. - * - * You can do this in a single call via the `Rope.setDebug` method, which will use the - * built-in debug function. You can also set it to your own callback. The callback - * will be invoked _once per render_ and sent the following parameters: - * - * `debugCallback(src, meshLength, verts)` - * - * `src` is the Rope instance being debugged. - * `meshLength` is the number of mesh vertices in total. - * `verts` is an array of the translated vertex coordinates. - * - * To disable rendering, set this property back to `null`. - * - * @name Phaser.GameObjects.Rope#debugCallback - * @type {function} - * @since 3.23.0 - */ - this.debugCallback = null; - - /** - * The Graphics instance that the debug vertices will be drawn to, if `setDebug` has - * been called. - * - * @name Phaser.GameObjects.Rope#debugGraphic - * @type {Phaser.GameObjects.Graphics} - * @since 3.23.0 - */ - this.debugGraphic = null; - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.initPipeline('TextureTintStripPipeline'); - - if (Array.isArray(points)) - { - this.resizeArrays(points.length); - } - - this.setPoints(points, colors, alphas); - - this.updateVertices(); - }, - - /** - * The Rope update loop. - * - * @method Phaser.GameObjects.Rope#preUpdate - * @protected - * @since 3.23.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - var prevFrame = this.anims.currentFrame; - - this.anims.update(time, delta); - - if (this.anims.currentFrame !== prevFrame) - { - this.updateUVs(); - this.updateVertices(); - } - }, - - /** - * Start playing the given animation. - * - * @method Phaser.GameObjects.Rope#play - * @since 3.23.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Game Object. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - this.anims.play(key, ignoreIfPlaying, startFrame); - - return this; - }, - - /** - * Flags this Rope as being dirty. A dirty rope will recalculate all of its vertices data - * the _next_ time it renders. You should set this rope as dirty if you update the points - * array directly. - * - * @method Phaser.GameObjects.Rope#setDirty - * @since 3.23.0 - * - * @return {this} This Game Object instance. - */ - setDirty: function () - { - this.dirty = true; - - return this; - }, - - /** - * Sets the alignment of the points in this Rope to be horizontal, in a strip format. - * - * Calling this method will reset this Rope. The current points, vertices, colors and alpha - * values will be reset to thoes values given as parameters. - * - * @method Phaser.GameObjects.Rope#setHorizontal - * @since 3.23.0 - * - * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. - * @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. - */ - setHorizontal: function (points, colors, alphas) - { - if (points === undefined) { points = this.points.length; } - - if (this.horizontal) - { - return this; - } - - this.horizontal = true; - - return this.setPoints(points, colors, alphas); - }, - - /** - * Sets the alignment of the points in this Rope to be vertical, in a column format. - * - * Calling this method will reset this Rope. The current points, vertices, colors and alpha - * values will be reset to thoes values given as parameters. - * - * @method Phaser.GameObjects.Rope#setVertical - * @since 3.23.0 - * - * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. - * @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. - */ - setVertical: function (points, colors, alphas) - { - if (points === undefined) { points = this.points.length; } - - if (!this.horizontal) - { - return this; - } - - this.horizontal = false; - - return this.setPoints(points, colors, alphas); - }, - - /** - * Sets the tint fill mode. - * - * Mode 0 is an additive tint, the default, which blends the vertices colors with the texture. - * This mode respects the texture alpha. - * - * Mode 1 is a fill tint. Unlike an additive tint, a fill-tint literally replaces the pixel colors - * from the texture with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. This mode respects the texture alpha. - * - * Mode 2 is a complete tint. The texture colors and alpha are replaced entirely by the vertices colors. - * - * See the `setColors` method for details of how to color each of the vertices. - * - * @method Phaser.GameObjects.Rope#setTintFill - * @webglOnly - * @since 3.23.0 - * - * @param {integer} [value=0] - Set to 0 for an Additive tint, 1 for a fill tint with alpha, or 2 for a fill tint without alpha. - * - * @return {this} This Game Object instance. - */ - setTintFill: function (value) - { - if (value === undefined) { value = 0; } - - this.tintFill = value; - - return this; - }, - - /** - * Set the alpha values used by the Rope during rendering. - * - * You can provide the values in a number of ways: - * - * 1) One single numeric value: `setAlphas(0.5)` - This will set a single alpha for the whole Rope. - * 2) Two numeric value: `setAlphas(1, 0.5)` - This will set a 'top' and 'bottom' alpha value across the whole Rope. - * 3) An array of values: `setAlphas([ 1, 0.5, 0.2 ])` - * - * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it - * will use each alpha value per rope segment. - * - * If the provided array has a different number of values than `points` then it will use the values in order, from - * the first Rope segment and on, until it runs out of values. This allows you to control the alpha values at all - * vertices in the Rope. - * - * Note this method is called `setAlphas` (plural) and not `setAlpha`. - * - * @method Phaser.GameObjects.Rope#setAlphas - * @since 3.23.0 - * - * @param {(number|number[])} [alphas] - Either a single alpha value, or an array of values. If nothing is provided alpha is reset to 1. - * @param {number} [bottomAlpha] - An optional bottom alpha value. See the method description for details. - * - * @return {this} This Game Object instance. - */ - setAlphas: function (alphas, bottomAlpha) - { - var total = this.points.length; - - if (total < 1) - { - return this; - } - - var currentAlphas = this.alphas; - - if (alphas === undefined) - { - alphas = [ 1 ]; - } - else if (!Array.isArray(alphas) && bottomAlpha === undefined) - { - alphas = [ alphas ]; - } - - var i; - var index = 0; - - if (bottomAlpha !== undefined) - { - // Top / Bottom alpha pair - for (i = 0; i < total; i++) - { - index = i * 2; - - currentAlphas[index] = alphas; - currentAlphas[index + 1] = bottomAlpha; - } - } - else if (alphas.length === total) - { - // If there are exactly the same number of alphas as points, we'll combine the alphas - for (i = 0; i < total; i++) - { - index = i * 2; - - currentAlphas[index] = alphas[i]; - currentAlphas[index + 1] = alphas[i]; - } - } - else - { - var prevAlpha = alphas[0]; - - for (i = 0; i < total; i++) - { - index = i * 2; - - if (alphas.length > index) - { - prevAlpha = alphas[index]; - } - - currentAlphas[index] = prevAlpha; - - if (alphas.length > index + 1) - { - prevAlpha = alphas[index + 1]; - } - - currentAlphas[index + 1] = prevAlpha; - } - } - - return this; - - }, - - /** - * Set the color values used by the Rope during rendering. - * - * Colors are used to control the level of tint applied across the Rope texture. - * - * You can provide the values in a number of ways: - * - * * One single numeric value: `setColors(0xff0000)` - This will set a single color tint for the whole Rope. - * * An array of values: `setColors([ 0xff0000, 0x00ff00, 0x0000ff ])` - * - * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it - * will use each color per rope segment. - * - * If the provided array has a different number of values than `points` then it will use the values in order, from - * the first Rope segment and on, until it runs out of values. This allows you to control the color values at all - * vertices in the Rope. - * - * @method Phaser.GameObjects.Rope#setColors - * @since 3.23.0 - * - * @param {(number|number[])} [colors] - Either a single color value, or an array of values. If nothing is provided color is reset to 0xffffff. - * - * @return {this} This Game Object instance. - */ - setColors: function (colors) - { - var total = this.points.length; - - if (total < 1) - { - return this; - } - - var currentColors = this.colors; - - if (colors === undefined) - { - colors = [ 0xffffff ]; - } - else if (!Array.isArray(colors)) - { - colors = [ colors ]; - } - - var i; - var index = 0; - - if (colors.length === total) - { - // If there are exactly the same number of colors as points, we'll combine the colors - for (i = 0; i < total; i++) - { - index = i * 2; - - currentColors[index] = colors[i]; - currentColors[index + 1] = colors[i]; - } - } - else - { - var prevColor = colors[0]; - - for (i = 0; i < total; i++) - { - index = i * 2; - - if (colors.length > index) - { - prevColor = colors[index]; - } - - currentColors[index] = prevColor; - - if (colors.length > index + 1) - { - prevColor = colors[index + 1]; - } - - currentColors[index + 1] = prevColor; - } - } - - return this; - }, - - /** - * 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 {(integer|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. - */ - setPoints: function (points, colors, alphas) - { - if (points === undefined) { points = 2; } - - if (typeof points === 'number') - { - // Generate an array based on the points - var segments = points; - - if (segments < 2) - { - segments = 2; - } - - points = []; - - var s; - var frameSegment; - var offset; - - if (this.horizontal) - { - offset = -(this.frame.halfWidth); - frameSegment = this.frame.width / (segments - 1); - - for (s = 0; s < segments; s++) - { - points.push({ x: offset + s * frameSegment, y: 0 }); - } - } - else - { - offset = -(this.frame.halfHeight); - frameSegment = this.frame.height / (segments - 1); - - for (s = 0; s < segments; s++) - { - points.push({ x: 0, y: offset + s * frameSegment }); - } - } - } - - var total = points.length; - var currentTotal = this.points.length; - - if (total < 1) - { - console.warn('Rope: Not enough points given'); - - return this; - } - else if (total === 1) - { - points.unshift({ x: 0, y: 0 }); - total++; - } - - if (currentTotal !== total) - { - this.resizeArrays(total); - } - - this.points = points; - - this.updateUVs(); - - if (colors !== undefined && colors !== null) - { - this.setColors(colors); - } - - if (alphas !== undefined && alphas !== null) - { - this.setAlphas(alphas); - } - - return this; - }, - - /** - * 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. - */ - updateUVs: function () - { - var currentUVs = this.uv; - var total = this.points.length; - - var u0 = this.frame.u0; - var v0 = this.frame.v0; - var u1 = this.frame.u1; - var v1 = this.frame.v1; - - var partH = (u1 - u0) / (total - 1); - var partV = (v1 - v0) / (total - 1); - - for (var i = 0; i < total; i++) - { - var index = i * 4; - - var uv0; - var uv1; - var uv2; - var uv3; - - if (this.horizontal) - { - if (this._flipX) - { - uv0 = u1 - (i * partH); - uv2 = u1 - (i * partH); - } - else - { - uv0 = u0 + (i * partH); - uv2 = u0 + (i * partH); - } - - if (this._flipY) - { - uv1 = v1; - uv3 = v0; - } - else - { - uv1 = v0; - uv3 = v1; - } - } - else - { - if (this._flipX) - { - uv0 = u0; - uv2 = u1; - } - else - { - uv0 = u1; - uv2 = u0; - } - - if (this._flipY) - { - uv1 = v1 - (i * partV); - uv3 = v1 - (i * partV); - } - else - { - uv1 = v0 + (i * partV); - uv3 = v0 + (i * partV); - } - } - - currentUVs[index + 0] = uv0; - currentUVs[index + 1] = uv1; - currentUVs[index + 2] = uv2; - currentUVs[index + 3] = uv3; - } - - return this; - }, - - /** - * Resizes all of the internal arrays: `vertices`, `uv`, `colors` and `alphas` to the new - * given Rope segment total. - * - * @method Phaser.GameObjects.Rope#resizeArrays - * @since 3.23.0 - * - * @param {integer} newSize - The amount of segments to split the Rope in to. - * - * @return {this} This Game Object instance. - */ - resizeArrays: function (newSize) - { - var colors = this.colors; - var alphas = this.alphas; - - this.vertices = new Float32Array(newSize * 4); - this.uv = new Float32Array(newSize * 4); - - colors = new Uint32Array(newSize * 2); - alphas = new Float32Array(newSize * 2); - - for (var i = 0; i < newSize * 2; i++) - { - colors[i] = 0xffffff; - alphas[i] = 1; - } - - this.colors = colors; - this.alphas = alphas; - - // updateVertices during next render - this.dirty = true; - - return this; - }, - - /** - * 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. - */ - updateVertices: function () - { - var perp = this._perp; - var points = this.points; - var vertices = this.vertices; - - var total = points.length; - - this.dirty = false; - - if (total < 1) - { - return; - } - - var nextPoint; - var lastPoint = points[0]; - - var frameSize = (this.horizontal) ? this.frame.halfHeight : this.frame.halfWidth; - - for (var i = 0; i < total; i++) - { - var point = points[i]; - var index = i * 4; - - if (i < total - 1) - { - nextPoint = points[i + 1]; - } - else - { - nextPoint = point; - } - - perp.x = nextPoint.y - lastPoint.y; - perp.y = -(nextPoint.x - lastPoint.x); - - var perpLength = perp.length(); - - perp.x /= perpLength; - perp.y /= perpLength; - - perp.x *= frameSize; - perp.y *= frameSize; - - vertices[index] = point.x + perp.x; - vertices[index + 1] = point.y + perp.y; - vertices[index + 2] = point.x - perp.x; - vertices[index + 3] = point.y - perp.y; - - lastPoint = point; - } - - return this; - }, - - /** - * This method enables rendering of the Rope vertices to the given Graphics instance. - * - * If you enable this feature, you must call `Graphics.clear()` in your Scene `update`, - * otherwise the Graphics instance will fill-in with draw calls. This is not done automatically - * to allow for you to debug render multiple Rope objects to a single Graphics instance. - * - * The Rope class has a built-in debug rendering callback `Rope.renderDebugVerts`, however - * you can also provide your own callback to be used instead. Do this by setting the `callback` parameter. - * - * The callback is invoked _once per render_ and sent the following parameters: - * - * `callback(src, meshLength, verts)` - * - * `src` is the Rope instance being debugged. - * `meshLength` is the number of mesh vertices in total. - * `verts` is an array of the translated vertex coordinates. - * - * If using your own callback you do not have to provide a Graphics instance to this method. - * - * To disable debug rendering, to either your own callback or the built-in one, call this method - * with no arguments. - * - * @method Phaser.GameObjects.Rope#setDebug - * @since 3.23.0 - * - * @param {Phaser.GameObjects.Graphics} [graphic] - The Graphic instance to render to if using the built-in callback. - * @param {function} [callback] - The callback to invoke during debug render. Leave as undefined to use the built-in callback. - * - * @return {this} This Game Object instance. - */ - setDebug: function (graphic, callback) - { - this.debugGraphic = graphic; - - if (!graphic && !callback) - { - this.debugCallback = null; - } - else if (!callback) - { - this.debugCallback = this.renderDebugVerts; - } - else - { - this.debugCallback = callback; - } - - return this; - }, - - /** - * The built-in Rope vertices debug rendering method. - * - * See `Rope.setDebug` for more details. - * - * @method Phaser.GameObjects.Rope#renderDebugVerts - * @since 3.23.0 - * - * @param {Phaser.GameObjects.Rope} src - The Rope object being rendered. - * @param {integer} meshLength - The number of vertices in the mesh. - * @param {number[]} verts - An array of translated vertex coordinates. - */ - renderDebugVerts: function (src, meshLength, verts) - { - var graphic = src.debugGraphic; - - var px0 = verts[0]; - var py0 = verts[1]; - var px1 = verts[2]; - var py1 = verts[3]; - - graphic.lineBetween(px0, py0, px1, py1); - - for (var i = 4; i < meshLength; i += 4) - { - var x0 = verts[i + 0]; - var y0 = verts[i + 1]; - var x1 = verts[i + 2]; - var y1 = verts[i + 3]; - - graphic.lineBetween(px0, py0, x0, y0); - graphic.lineBetween(px1, py1, x1, y1); - graphic.lineBetween(px1, py1, x0, y0); - graphic.lineBetween(x0, y0, x1, y1); - - px0 = x0; - py0 = y0; - px1 = x1; - py1 = y1; - } - }, - - /** - * Handles the pre-destroy step for the Rope, which removes the Animation component and typed arrays. - * - * @method Phaser.GameObjects.Rope#preDestroy - * @private - * @since 3.23.0 - */ - preDestroy: function () - { - this.anims.destroy(); - - this.anims = undefined; - - this.points = null; - this.vertices = null; - this.uv = null; - this.colors = null; - this.alphas = null; - - this.debugCallback = null; - this.debugGraphic = null; - }, - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipX - * @type {boolean} - * @default false - * @since 3.23.0 - */ - flipX: { - - get: function () - { - return this._flipX; - }, - - set: function (value) - { - this._flipX = value; - - return this.updateUVs(); - } - - }, - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipY - * @type {boolean} - * @default false - * @since 3.23.0 - */ - flipY: { - - get: function () - { - return this._flipY; - }, - - set: function (value) - { - this._flipY = value; - - return this.updateUVs(); - } - - } - -}); - -module.exports = Rope; - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AddToDOM = __webpack_require__(116); -var CanvasPool = __webpack_require__(27); -var Class = __webpack_require__(0); -var Components = __webpack_require__(12); -var GameEvents = __webpack_require__(19); -var GameObject = __webpack_require__(14); -var GetTextSize = __webpack_require__(979); +var GetTextSize = __webpack_require__(978); var GetValue = __webpack_require__(6); -var RemoveFromDOM = __webpack_require__(173); -var TextRender = __webpack_require__(980); -var TextStyle = __webpack_require__(983); +var RemoveFromDOM = __webpack_require__(176); +var TextRender = __webpack_require__(979); +var TextStyle = __webpack_require__(982); /** * @classdesc @@ -44692,7 +42881,7 @@ var Text = new Class({ * * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this Text object. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setText: function (value) { @@ -44733,7 +42922,7 @@ var Text = new Class({ * * @param {object} style - The style settings to set. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setStyle: function (style) { @@ -44767,7 +42956,7 @@ var Text = new Class({ * * @param {string} font - The font family or font settings to set. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFont: function (font) { @@ -44796,7 +42985,7 @@ var Text = new Class({ * * @param {string} family - The font family. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFontFamily: function (family) { @@ -44811,7 +43000,7 @@ var Text = new Class({ * * @param {number} size - The font size. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFontSize: function (size) { @@ -44826,7 +43015,7 @@ var Text = new Class({ * * @param {string} style - The font style. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFontStyle: function (style) { @@ -44844,7 +43033,7 @@ var Text = new Class({ * @param {number} width - The fixed width to set. `0` disables fixed width. * @param {number} height - The fixed height to set. `0` disables fixed height. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFixedSize: function (width, height) { @@ -44859,7 +43048,7 @@ var Text = new Class({ * * @param {string} color - The background color. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setBackgroundColor: function (color) { @@ -44879,7 +43068,7 @@ var Text = new Class({ * * @param {(string|any)} color - The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setFill: function (fillStyle) { @@ -44894,7 +43083,7 @@ var Text = new Class({ * * @param {string} color - The text fill color. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setColor: function (color) { @@ -44910,7 +43099,7 @@ var Text = new Class({ * @param {string} color - The stroke color. * @param {number} thickness - The stroke thickness. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setStroke: function (color, thickness) { @@ -44930,7 +43119,7 @@ var Text = new Class({ * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. * @param {boolean} [shadowFill=true] - Whether to fill the shadow. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadow: function (x, y, color, blur, shadowStroke, shadowFill) { @@ -44946,7 +43135,7 @@ var Text = new Class({ * @param {number} x - The horizontal shadow offset. * @param {number} y - The vertical shadow offset. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowOffset: function (x, y) { @@ -44961,7 +43150,7 @@ var Text = new Class({ * * @param {string} color - The shadow color. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowColor: function (color) { @@ -44976,7 +43165,7 @@ var Text = new Class({ * * @param {number} blur - The shadow blur radius. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowBlur: function (blur) { @@ -44991,7 +43180,7 @@ var Text = new Class({ * * @param {boolean} enabled - Whether shadow stroke is enabled or not. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowStroke: function (enabled) { @@ -45006,7 +43195,7 @@ var Text = new Class({ * * @param {boolean} enabled - Whether shadow fill is enabled or not. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setShadowFill: function (enabled) { @@ -45024,7 +43213,7 @@ var Text = new Class({ * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, * spaces and whitespace are left as is. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setWordWrapWidth: function (width, useAdvancedWrap) { @@ -45043,7 +43232,7 @@ var Text = new Class({ * newline characters in place to indicate where breaks should happen. * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setWordWrapCallback: function (callback, scope) { @@ -45062,7 +43251,7 @@ var Text = new Class({ * * @param {string} [align='left'] - The text alignment for multi-line text. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setAlign: function (align) { @@ -45085,7 +43274,7 @@ var Text = new Class({ * * @param {number} value - The resolution for this Text object to use. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setResolution: function (value) { @@ -45103,7 +43292,7 @@ var Text = new Class({ * * @param {number} value - The amount to add to the font height to achieve the overall line height. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setLineSpacing: function (value) { @@ -45127,7 +43316,7 @@ var Text = new Class({ * @param {number} right - The right padding value. * @param {number} bottom - The bottom padding value. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setPadding: function (left, top, right, bottom) { @@ -45186,7 +43375,7 @@ var Text = new Class({ * * @param {integer} [max=0] - The maximum number of lines to draw. * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ setMaxLines: function (max) { @@ -45199,7 +43388,7 @@ var Text = new Class({ * @method Phaser.GameObjects.Text#updateText * @since 3.0.0 * - * @return {this} This Text object. + * @return {Phaser.GameObjects.Text} This Text object. */ updateText: function () { @@ -45508,7 +43697,7 @@ module.exports = Text; /***/ }), -/* 194 */ +/* 196 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -45517,14 +43706,14 @@ module.exports = Text; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); -var GetPowerOfTwo = __webpack_require__(323); -var Smoothing = __webpack_require__(161); -var TileSpriteRender = __webpack_require__(985); +var GetPowerOfTwo = __webpack_require__(324); +var Smoothing = __webpack_require__(164); +var TileSpriteRender = __webpack_require__(984); var Vector2 = __webpack_require__(3); // bitmask flag for GameObject.renderMask @@ -46160,7 +44349,7 @@ module.exports = TileSprite; /***/ }), -/* 195 */ +/* 197 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -46170,15 +44359,15 @@ module.exports = TileSprite; */ var Class = __webpack_require__(0); -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Components = __webpack_require__(12); -var Events = __webpack_require__(88); -var GameEvents = __webpack_require__(19); +var Events = __webpack_require__(90); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); var SoundEvents = __webpack_require__(59); -var UUID = __webpack_require__(191); -var VideoRender = __webpack_require__(988); -var MATH_CONST = __webpack_require__(16); +var UUID = __webpack_require__(194); +var VideoRender = __webpack_require__(987); +var MATH_CONST = __webpack_require__(13); /** * @classdesc @@ -47929,7 +46118,7 @@ module.exports = Video; /***/ }), -/* 196 */ +/* 198 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -47939,8 +46128,8 @@ module.exports = Video; */ var Class = __webpack_require__(0); -var Contains = __webpack_require__(197); -var GetPoints = __webpack_require__(412); +var Contains = __webpack_require__(199); +var GetPoints = __webpack_require__(411); var GEOM_CONST = __webpack_require__(46); /** @@ -48163,7 +46352,7 @@ module.exports = Polygon; /***/ }), -/* 197 */ +/* 199 */ /***/ (function(module, exports) { /** @@ -48212,7 +46401,7 @@ module.exports = Contains; /***/ }), -/* 198 */ +/* 200 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -48222,7 +46411,7 @@ module.exports = Contains; */ var Class = __webpack_require__(0); -var Mesh = __webpack_require__(128); +var Mesh = __webpack_require__(130); /** * @classdesc @@ -48716,7 +46905,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setTopLeft: function (x, y) { @@ -48735,7 +46924,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setTopRight: function (x, y) { @@ -48754,7 +46943,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setBottomLeft: function (x, y) { @@ -48773,7 +46962,7 @@ var Quad = new Class({ * @param {number} x - The horizontal coordinate of the vertex. * @param {number} y - The vertical coordinate of the vertex. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ setBottomRight: function (x, y) { @@ -48789,7 +46978,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#resetPosition * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ resetPosition: function () { @@ -48812,7 +47001,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#resetAlpha * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ resetAlpha: function () { @@ -48834,7 +47023,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#resetColors * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ resetColors: function () { @@ -48856,7 +47045,7 @@ var Quad = new Class({ * @method Phaser.GameObjects.Quad#reset * @since 3.0.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.Quad} This Game Object. */ reset: function () { @@ -48873,7 +47062,7 @@ module.exports = Quad; /***/ }), -/* 199 */ +/* 201 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -48886,10 +47075,10 @@ var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); var GetFastValue = __webpack_require__(2); -var Extend = __webpack_require__(18); -var SetValue = __webpack_require__(420); -var ShaderRender = __webpack_require__(1071); -var TransformMatrix = __webpack_require__(30); +var Extend = __webpack_require__(17); +var SetValue = __webpack_require__(419); +var ShaderRender = __webpack_require__(1068); +var TransformMatrix = __webpack_require__(32); /** * @classdesc @@ -50096,7 +48285,7 @@ module.exports = Shader; /***/ }), -/* 200 */ +/* 202 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50127,7 +48316,7 @@ module.exports = CircleToCircle; /***/ }), -/* 201 */ +/* 203 */ /***/ (function(module, exports) { /** @@ -50181,7 +48370,7 @@ module.exports = CircleToRectangle; /***/ }), -/* 202 */ +/* 204 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50192,7 +48381,7 @@ module.exports = CircleToRectangle; */ var Point = __webpack_require__(4); -var LineToCircle = __webpack_require__(203); +var LineToCircle = __webpack_require__(205); /** * Checks for intersection between the line segment and circle, @@ -50273,7 +48462,7 @@ module.exports = GetLineToCircle; /***/ }), -/* 203 */ +/* 205 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50357,7 +48546,7 @@ module.exports = LineToCircle; /***/ }), -/* 204 */ +/* 206 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50368,8 +48557,8 @@ module.exports = LineToCircle; */ var Point = __webpack_require__(4); -var LineToLine = __webpack_require__(82); -var LineToRectangle = __webpack_require__(425); +var LineToLine = __webpack_require__(84); +var LineToRectangle = __webpack_require__(424); /** * Checks for intersection between the Line and a Rectangle shape, @@ -50417,7 +48606,7 @@ module.exports = GetLineToRectangle; /***/ }), -/* 205 */ +/* 207 */ /***/ (function(module, exports) { /** @@ -50504,7 +48693,7 @@ module.exports = ContainsArray; /***/ }), -/* 206 */ +/* 208 */ /***/ (function(module, exports) { /** @@ -50552,7 +48741,7 @@ module.exports = RotateAroundXY; /***/ }), -/* 207 */ +/* 209 */ /***/ (function(module, exports) { /** @@ -50580,7 +48769,7 @@ module.exports = GetAspectRatio; /***/ }), -/* 208 */ +/* 210 */ /***/ (function(module, exports) { /** @@ -50634,7 +48823,7 @@ module.exports = RotateAroundXY; /***/ }), -/* 209 */ +/* 211 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50649,18 +48838,18 @@ module.exports = RotateAroundXY; module.exports = { - BUTTON_DOWN: __webpack_require__(1193), - BUTTON_UP: __webpack_require__(1194), - CONNECTED: __webpack_require__(1195), - DISCONNECTED: __webpack_require__(1196), - GAMEPAD_BUTTON_DOWN: __webpack_require__(1197), - GAMEPAD_BUTTON_UP: __webpack_require__(1198) + BUTTON_DOWN: __webpack_require__(1189), + BUTTON_UP: __webpack_require__(1190), + CONNECTED: __webpack_require__(1191), + DISCONNECTED: __webpack_require__(1192), + GAMEPAD_BUTTON_DOWN: __webpack_require__(1193), + GAMEPAD_BUTTON_UP: __webpack_require__(1194) }; /***/ }), -/* 210 */ +/* 212 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50669,8 +48858,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); -var XHRSettings = __webpack_require__(133); +var Extend = __webpack_require__(17); +var XHRSettings = __webpack_require__(135); /** * Takes two XHRSettings Objects and creates a new XHRSettings object from them. @@ -50708,7 +48897,7 @@ module.exports = MergeXHRSettings; /***/ }), -/* 211 */ +/* 213 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50723,7 +48912,7 @@ var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); -var ParseXML = __webpack_require__(359); +var ParseXML = __webpack_require__(358); /** * @classdesc @@ -50869,7 +49058,7 @@ var XMLFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('xml', function (key, url, xhrSettings) { @@ -50893,7 +49082,7 @@ module.exports = XMLFile; /***/ }), -/* 212 */ +/* 214 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50908,24 +49097,24 @@ module.exports = XMLFile; module.exports = { - Acceleration: __webpack_require__(1253), - Angular: __webpack_require__(1254), - Bounce: __webpack_require__(1255), - Debug: __webpack_require__(1256), - Drag: __webpack_require__(1257), - Enable: __webpack_require__(1258), - Friction: __webpack_require__(1259), - Gravity: __webpack_require__(1260), - Immovable: __webpack_require__(1261), - Mass: __webpack_require__(1262), - Size: __webpack_require__(1263), - Velocity: __webpack_require__(1264) + Acceleration: __webpack_require__(1249), + Angular: __webpack_require__(1250), + Bounce: __webpack_require__(1251), + Debug: __webpack_require__(1252), + Drag: __webpack_require__(1253), + Enable: __webpack_require__(1254), + Friction: __webpack_require__(1255), + Gravity: __webpack_require__(1256), + Immovable: __webpack_require__(1257), + Mass: __webpack_require__(1258), + Size: __webpack_require__(1259), + Velocity: __webpack_require__(1260) }; /***/ }), -/* 213 */ +/* 215 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50940,20 +49129,20 @@ module.exports = { module.exports = { - COLLIDE: __webpack_require__(1266), - OVERLAP: __webpack_require__(1267), - PAUSE: __webpack_require__(1268), - RESUME: __webpack_require__(1269), - TILE_COLLIDE: __webpack_require__(1270), - TILE_OVERLAP: __webpack_require__(1271), - WORLD_BOUNDS: __webpack_require__(1272), - WORLD_STEP: __webpack_require__(1273) + COLLIDE: __webpack_require__(1262), + OVERLAP: __webpack_require__(1263), + PAUSE: __webpack_require__(1264), + RESUME: __webpack_require__(1265), + TILE_COLLIDE: __webpack_require__(1266), + TILE_OVERLAP: __webpack_require__(1267), + WORLD_BOUNDS: __webpack_require__(1268), + WORLD_STEP: __webpack_require__(1269) }; /***/ }), -/* 214 */ +/* 216 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -50970,11 +49159,11 @@ var Constraint = {}; module.exports = Constraint; -var Vertices = __webpack_require__(84); -var Vector = __webpack_require__(97); -var Sleeping = __webpack_require__(234); -var Bounds = __webpack_require__(98); -var Axes = __webpack_require__(508); +var Vertices = __webpack_require__(86); +var Vector = __webpack_require__(101); +var Sleeping = __webpack_require__(236); +var Bounds = __webpack_require__(102); +var Axes = __webpack_require__(507); var Common = __webpack_require__(37); (function() { @@ -51442,7 +49631,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 215 */ +/* 217 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -51451,7 +49640,7 @@ var Common = __webpack_require__(37); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTileAt = __webpack_require__(136); +var GetTileAt = __webpack_require__(138); /** * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting @@ -51518,7 +49707,7 @@ module.exports = CalculateFacesAt; /***/ }), -/* 216 */ +/* 218 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -51527,10 +49716,10 @@ module.exports = CalculateFacesAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tile = __webpack_require__(72); -var IsInLayerBounds = __webpack_require__(99); -var CalculateFacesAt = __webpack_require__(215); -var SetTileCollision = __webpack_require__(71); +var Tile = __webpack_require__(74); +var IsInLayerBounds = __webpack_require__(103); +var CalculateFacesAt = __webpack_require__(217); +var SetTileCollision = __webpack_require__(73); /** * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index @@ -51562,7 +49751,7 @@ var PutTileAt = function (tile, tileX, tileY, recalculateFaces, layer) { if (layer.data[tileY][tileX] === null) { - layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, layer.tileWidth, layer.tileHeight); + layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, tile.width, tile.height); } layer.data[tileY][tileX].copy(tile); } @@ -51598,7 +49787,7 @@ module.exports = PutTileAt; /***/ }), -/* 217 */ +/* 219 */ /***/ (function(module, exports) { /** @@ -51637,7 +49826,7 @@ module.exports = SetLayerCollisionIndex; /***/ }), -/* 218 */ +/* 220 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -51646,10 +49835,10 @@ module.exports = SetLayerCollisionIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var LayerData = __webpack_require__(100); -var MapData = __webpack_require__(101); -var Tile = __webpack_require__(72); +var Formats = __webpack_require__(31); +var LayerData = __webpack_require__(104); +var MapData = __webpack_require__(105); +var Tile = __webpack_require__(74); /** * Parses a 2D array of tile indexes into a new MapData object with a single layer. @@ -51676,6 +49865,7 @@ var Parse2DArray = function (name, data, tileWidth, tileHeight, insertNull) tileWidth: tileWidth, tileHeight: tileHeight }); + var mapData = new MapData({ name: name, tileWidth: tileWidth, @@ -51728,7 +49918,7 @@ module.exports = Parse2DArray; /***/ }), -/* 219 */ +/* 221 */ /***/ (function(module, exports) { /** @@ -51818,7 +50008,7 @@ module.exports = ParseGID; /***/ }), -/* 220 */ +/* 222 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -51879,7 +50069,7 @@ module.exports = CreateGroupLayer; /***/ }), -/* 221 */ +/* 223 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -51888,8 +50078,8 @@ module.exports = CreateGroupLayer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Pick = __webpack_require__(481); -var ParseGID = __webpack_require__(219); +var Pick = __webpack_require__(480); +var ParseGID = __webpack_require__(221); var copyPoints = function (p) { return { x: p.x, y: p.y }; }; @@ -51961,7 +50151,7 @@ module.exports = ParseObject; /***/ }), -/* 222 */ +/* 224 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -51970,10 +50160,10 @@ module.exports = ParseObject; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var MapData = __webpack_require__(101); -var Parse = __webpack_require__(473); -var Tilemap = __webpack_require__(489); +var Formats = __webpack_require__(31); +var MapData = __webpack_require__(105); +var Parse = __webpack_require__(472); +var Tilemap = __webpack_require__(488); /** * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When @@ -52047,7 +50237,7 @@ module.exports = ParseToTilemap; /***/ }), -/* 223 */ +/* 225 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52096,7 +50286,7 @@ module.exports = GetTargets; /***/ }), -/* 224 */ +/* 226 */ /***/ (function(module, exports) { /** @@ -52364,7 +50554,7 @@ module.exports = GetValueOp; /***/ }), -/* 225 */ +/* 227 */ /***/ (function(module, exports) { /** @@ -52408,7 +50598,7 @@ module.exports = TWEEN_DEFAULTS; /***/ }), -/* 226 */ +/* 228 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -52418,12 +50608,12 @@ module.exports = TWEEN_DEFAULTS; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(227); -var GameObjectCreator = __webpack_require__(17); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(229); +var GameObjectCreator = __webpack_require__(16); var GameObjectFactory = __webpack_require__(5); -var TWEEN_CONST = __webpack_require__(87); -var MATH_CONST = __webpack_require__(16); +var TWEEN_CONST = __webpack_require__(89); +var MATH_CONST = __webpack_require__(13); /** * @classdesc @@ -54052,7 +52242,7 @@ module.exports = Tween; /***/ }), -/* 227 */ +/* 229 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54067,25 +52257,25 @@ module.exports = Tween; module.exports = { - TIMELINE_COMPLETE: __webpack_require__(1351), - TIMELINE_LOOP: __webpack_require__(1352), - TIMELINE_PAUSE: __webpack_require__(1353), - TIMELINE_RESUME: __webpack_require__(1354), - TIMELINE_START: __webpack_require__(1355), - TIMELINE_UPDATE: __webpack_require__(1356), - TWEEN_ACTIVE: __webpack_require__(1357), - TWEEN_COMPLETE: __webpack_require__(1358), - TWEEN_LOOP: __webpack_require__(1359), - TWEEN_REPEAT: __webpack_require__(1360), - TWEEN_START: __webpack_require__(1361), - TWEEN_UPDATE: __webpack_require__(1362), - TWEEN_YOYO: __webpack_require__(1363) + TIMELINE_COMPLETE: __webpack_require__(1346), + TIMELINE_LOOP: __webpack_require__(1347), + TIMELINE_PAUSE: __webpack_require__(1348), + TIMELINE_RESUME: __webpack_require__(1349), + TIMELINE_START: __webpack_require__(1350), + TIMELINE_UPDATE: __webpack_require__(1351), + TWEEN_ACTIVE: __webpack_require__(1352), + TWEEN_COMPLETE: __webpack_require__(1353), + TWEEN_LOOP: __webpack_require__(1354), + TWEEN_REPEAT: __webpack_require__(1355), + TWEEN_START: __webpack_require__(1356), + TWEEN_UPDATE: __webpack_require__(1357), + TWEEN_YOYO: __webpack_require__(1358) }; /***/ }), -/* 228 */ +/* 230 */ /***/ (function(module, exports) { /** @@ -54212,7 +52402,7 @@ module.exports = TweenData; /***/ }), -/* 229 */ +/* 231 */ /***/ (function(module, exports) { /** @@ -54266,7 +52456,7 @@ module.exports = ScaleModes; /***/ }), -/* 230 */ +/* 232 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54298,7 +52488,7 @@ module.exports = Wrap; /***/ }), -/* 231 */ +/* 233 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54330,7 +52520,7 @@ module.exports = WrapDegrees; /***/ }), -/* 232 */ +/* 234 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -54341,14 +52531,783 @@ module.exports = WrapDegrees; */ var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); +var Utils = __webpack_require__(10); + +/** + * @classdesc + * WebGLPipeline is a class that describes the way elements will be renderered + * in WebGL, specially focused on batching vertices (batching is not provided). + * Pipelines are mostly used for describing 2D rendering passes but it's + * flexible enough to be used for any type of rendering including 3D. + * Internally WebGLPipeline will handle things like compiling shaders, + * creating vertex buffers, assigning primitive topology and binding + * vertex attributes. + * + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - gl: Current WebGL context. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * - vertices: An optional buffer of vertices + * - attributes: An array describing the vertex attributes + * + * The vertex attributes properties are: + * - name : String - Name of the attribute in the vertex shader + * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 + * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) + * - normalized : boolean - Is the attribute normalized + * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C + * Here you can find more information of how to describe an attribute: + * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer + * + * @class WebGLPipeline + * @memberof Phaser.Renderer.WebGL + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration object for this WebGL Pipeline, as described above. + */ +var WebGLPipeline = new Class({ + + initialize: + + function WebGLPipeline (config) + { + /** + * Name of the Pipeline. Used for identifying + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'WebGLPipeline'; + + /** + * The Game which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = config.game; + + /** + * The canvas which this WebGL Pipeline renders to. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#view + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.view = config.game.canvas; + + /** + * Used to store the current game resolution + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution + * @type {number} + * @since 3.0.0 + */ + this.resolution = 1; + + /** + * Width of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#width + * @type {number} + * @since 3.0.0 + */ + this.width = 0; + + /** + * Height of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#height + * @type {number} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The WebGL context this WebGL Pipeline uses. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#gl + * @type {WebGLRenderingContext} + * @since 3.0.0 + */ + this.gl = config.gl; + + /** + * How many vertices have been fed to the current pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.vertexCount = 0; + + /** + * The limit of vertices that the pipeline can hold + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity + * @type {integer} + * @since 3.0.0 + */ + this.vertexCapacity = config.vertexCapacity; + + /** + * The WebGL Renderer which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer + * @type {Phaser.Renderer.WebGL.WebGLRenderer} + * @since 3.0.0 + */ + this.renderer = config.renderer; + + /** + * Raw byte buffer of vertices. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData + * @type {ArrayBuffer} + * @since 3.0.0 + */ + this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); + + /** + * The handle to a WebGL vertex buffer object. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer + * @type {WebGLBuffer} + * @since 3.0.0 + */ + this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); + + /** + * The handle to a WebGL program + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#program + * @type {WebGLProgram} + * @since 3.0.0 + */ + this.program = this.renderer.createProgram(config.vertShader, config.fragShader); + + /** + * Array of objects that describe the vertex attributes + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes + * @type {object} + * @since 3.0.0 + */ + this.attributes = config.attributes; + + /** + * The size in bytes of the vertex + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize + * @type {integer} + * @since 3.0.0 + */ + this.vertexSize = config.vertexSize; + + /** + * The primitive topology which the pipeline will use to submit draw calls + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#topology + * @type {integer} + * @since 3.0.0 + */ + this.topology = config.topology; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources + * to the GPU. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes + * @type {Uint8Array} + * @since 3.0.0 + */ + this.bytes = new Uint8Array(this.vertexData); + + /** + * This will store the amount of components of 32 bit length + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount + * @type {integer} + * @since 3.0.0 + */ + this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); + + /** + * Indicates if the current pipeline is flushing the contents to the GPU. + * When the variable is set the flush function will be locked. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked + * @type {boolean} + * @since 3.1.0 + */ + this.flushLocked = false; + + /** + * Indicates if the current pipeline is active or not for this frame only. + * Reset in the onRender method. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#active + * @type {boolean} + * @since 3.10.0 + */ + this.active = false; + }, + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#boot + * @since 3.11.0 + */ + boot: function () + { + }, + + /** + * Adds a description of vertex attribute to the pipeline + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute + * @since 3.2.0 + * + * @param {string} name - Name of the vertex attribute + * @param {integer} size - Vertex component size + * @param {integer} type - Type of the attribute + * @param {boolean} normalized - Is the value normalized to a range + * @param {integer} offset - Byte offset to the beginning of the first element in the vertex + * + * @return {this} This WebGLPipeline instance. + */ + addAttribute: function (name, size, type, normalized, offset) + { + this.attributes.push({ + name: name, + size: size, + type: this.renderer.glFormats[type], + normalized: normalized, + offset: offset + }); + + this.vertexComponentCount = Utils.getComponentCount( + this.attributes, + this.gl + ); + return this; + }, + + /** + * Check if the current batch of vertices is full. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush + * @since 3.0.0 + * + * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. + */ + shouldFlush: function () + { + return (this.vertexCount >= this.vertexCapacity); + }, + + /** + * Resizes the properties used to describe the viewport + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width of this WebGL Pipeline. + * @param {number} height - The new height of this WebGL Pipeline. + * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + this.width = width * resolution; + this.height = height * resolution; + this.resolution = resolution; + + return this; + }, + + /** + * Binds the pipeline resources, including programs, vertex buffers and binds attributes + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#bind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + bind: function () + { + var gl = this.gl; + var vertexBuffer = this.vertexBuffer; + var attributes = this.attributes; + var program = this.program; + var renderer = this.renderer; + var vertexSize = this.vertexSize; + + renderer.setProgram(program); + renderer.setVertexBuffer(vertexBuffer); + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + var location = gl.getAttribLocation(program, element.name); + + if (location >= 0) + { + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); + } + else if (location !== -1) + { + gl.disableVertexAttribArray(location); + } + } + + return this; + }, + + /** + * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. + * + * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + // This is for updating uniform data it's called on each bind attempt. + return this; + }, + + /** + * Called before each frame is rendered, but after the canvas has been cleared. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPreRender: function () + { + // called once every frame + return this; + }, + + /** + * Called before a Scene's Camera is rendered. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. + * + * @return {this} This WebGLPipeline instance. + */ + onRender: function () + { + // called for each camera + return this; + }, + + /** + * Called after each frame has been completely rendered and snapshots have been taken. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPostRender: function () + { + // called once every frame + return this; + }, + + /** + * Uploads the vertex data and emits a draw call + * for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#flush + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) { return this; } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + + if (vertexCount === 0) + { + this.flushLocked = false; + return; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + gl.drawArrays(topology, 0, vertexCount); + + this.vertexCount = 0; + this.flushLocked = false; + + return this; + }, + + /** + * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + destroy: function () + { + var gl = this.gl; + + gl.deleteProgram(this.program); + gl.deleteBuffer(this.vertexBuffer); + + delete this.program; + delete this.vertexBuffer; + delete this.gl; + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new value of the `float` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1: function (name, x) + { + this.renderer.setFloat1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec2` uniform. + * @param {number} y - The new Y component of the `vec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2: function (name, x, y) + { + this.renderer.setFloat2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec3` uniform. + * @param {number} y - The new Y component of the `vec3` uniform. + * @param {number} z - The new Z component of the `vec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3: function (name, x, y, z) + { + this.renderer.setFloat3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - X component of the uniform + * @param {number} y - Y component of the uniform + * @param {number} z - Z component of the uniform + * @param {number} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4: function (name, x, y, z, w) + { + this.renderer.setFloat4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1v: function (name, arr) + { + this.renderer.setFloat1v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2v: function (name, arr) + { + this.renderer.setFloat2v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3v: function (name, arr) + { + this.renderer.setFloat3v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4v: function (name, arr) + { + this.renderer.setFloat4v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new value of the `int` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt1: function (name, x) + { + this.renderer.setInt1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec2` uniform. + * @param {integer} y - The new Y component of the `ivec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt2: function (name, x, y) + { + this.renderer.setInt2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec3` uniform. + * @param {integer} y - The new Y component of the `ivec3` uniform. + * @param {integer} z - The new Z component of the `ivec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt3: function (name, x, y, z) + { + this.renderer.setInt3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - X component of the uniform + * @param {integer} y - Y component of the uniform + * @param {integer} z - Z component of the uniform + * @param {integer} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setInt4: function (name, x, y, z, w) + { + this.renderer.setInt4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix2: function (name, transpose, matrix) + { + this.renderer.setMatrix2(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix3: function (name, transpose, matrix) + { + this.renderer.setMatrix3(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Should the matrix be transpose + * @param {Float32Array} matrix - Matrix data + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix4: function (name, transpose, matrix) + { + this.renderer.setMatrix4(this.program, name, transpose, matrix); + + return this; + } + +}); + +module.exports = WebGLPipeline; + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Earcut = __webpack_require__(66); var GetFastValue = __webpack_require__(2); -var ModelViewProjection = __webpack_require__(233); -var ShaderSourceFS = __webpack_require__(335); -var ShaderSourceVS = __webpack_require__(336); -var TransformMatrix = __webpack_require__(30); -var Utils = __webpack_require__(9); -var WebGLPipeline = __webpack_require__(141); +var ModelViewProjection = __webpack_require__(506); +var ShaderSourceFS = __webpack_require__(779); +var ShaderSourceVS = __webpack_require__(780); +var TransformMatrix = __webpack_require__(32); +var Utils = __webpack_require__(10); +var WebGLPipeline = __webpack_require__(234); /** * @classdesc @@ -55838,757 +54797,7 @@ module.exports = TextureTintPipeline; /***/ }), -/* 233 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Implements a model view projection matrices. - * Pipelines can implement this for doing 2D and 3D rendering. - * - * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection - * @since 3.0.0 - */ -var ModelViewProjection = { - - /** - * Dirty flag for checking if model matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - modelMatrixDirty: false, - - /** - * Dirty flag for checking if view matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - viewMatrixDirty: false, - - /** - * Dirty flag for checking if projection matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - projectionMatrixDirty: false, - - /** - * Model matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - modelMatrix: null, - - /** - * View matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - viewMatrix: null, - - /** - * Projection matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - projectionMatrix: null, - - /** - * Initializes MVP matrices with an identity matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit - * @since 3.0.0 - */ - mvpInit: function () - { - this.modelMatrixDirty = true; - this.viewMatrixDirty = true; - this.projectionMatrixDirty = true; - - this.modelMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - this.viewMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - this.projectionMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - return this; - }, - - /** - * If dirty flags are set then the matrices are uploaded to the GPU. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate - * @since 3.0.0 - */ - mvpUpdate: function () - { - var program = this.program; - - if (this.modelMatrixDirty) - { - this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); - this.modelMatrixDirty = false; - } - - if (this.viewMatrixDirty) - { - this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); - this.viewMatrixDirty = false; - } - - if (this.projectionMatrixDirty) - { - this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); - this.projectionMatrixDirty = false; - } - - return this; - }, - - /** - * Loads an identity matrix to the model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity - * @since 3.0.0 - */ - modelIdentity: function () - { - var modelMatrix = this.modelMatrix; - - modelMatrix[0] = 1; - modelMatrix[1] = 0; - modelMatrix[2] = 0; - modelMatrix[3] = 0; - modelMatrix[4] = 0; - modelMatrix[5] = 1; - modelMatrix[6] = 0; - modelMatrix[7] = 0; - modelMatrix[8] = 0; - modelMatrix[9] = 0; - modelMatrix[10] = 1; - modelMatrix[11] = 0; - modelMatrix[12] = 0; - modelMatrix[13] = 0; - modelMatrix[14] = 0; - modelMatrix[15] = 1; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Scale model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - modelScale: function (x, y, z) - { - var modelMatrix = this.modelMatrix; - - modelMatrix[0] = modelMatrix[0] * x; - modelMatrix[1] = modelMatrix[1] * x; - modelMatrix[2] = modelMatrix[2] * x; - modelMatrix[3] = modelMatrix[3] * x; - modelMatrix[4] = modelMatrix[4] * y; - modelMatrix[5] = modelMatrix[5] * y; - modelMatrix[6] = modelMatrix[6] * y; - modelMatrix[7] = modelMatrix[7] * y; - modelMatrix[8] = modelMatrix[8] * z; - modelMatrix[9] = modelMatrix[9] * z; - modelMatrix[10] = modelMatrix[10] * z; - modelMatrix[11] = modelMatrix[11] * z; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Translate model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - modelTranslate: function (x, y, z) - { - var modelMatrix = this.modelMatrix; - - modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; - modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; - modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; - modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the X axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateX: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a10 = modelMatrix[4]; - var a11 = modelMatrix[5]; - var a12 = modelMatrix[6]; - var a13 = modelMatrix[7]; - var a20 = modelMatrix[8]; - var a21 = modelMatrix[9]; - var a22 = modelMatrix[10]; - var a23 = modelMatrix[11]; - - modelMatrix[4] = a10 * c + a20 * s; - modelMatrix[5] = a11 * c + a21 * s; - modelMatrix[6] = a12 * c + a22 * s; - modelMatrix[7] = a13 * c + a23 * s; - modelMatrix[8] = a20 * c - a10 * s; - modelMatrix[9] = a21 * c - a11 * s; - modelMatrix[10] = a22 * c - a12 * s; - modelMatrix[11] = a23 * c - a13 * s; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the Y axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateY: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = modelMatrix[0]; - var a01 = modelMatrix[1]; - var a02 = modelMatrix[2]; - var a03 = modelMatrix[3]; - var a20 = modelMatrix[8]; - var a21 = modelMatrix[9]; - var a22 = modelMatrix[10]; - var a23 = modelMatrix[11]; - - modelMatrix[0] = a00 * c - a20 * s; - modelMatrix[1] = a01 * c - a21 * s; - modelMatrix[2] = a02 * c - a22 * s; - modelMatrix[3] = a03 * c - a23 * s; - modelMatrix[8] = a00 * s + a20 * c; - modelMatrix[9] = a01 * s + a21 * c; - modelMatrix[10] = a02 * s + a22 * c; - modelMatrix[11] = a03 * s + a23 * c; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the Z axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateZ: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = modelMatrix[0]; - var a01 = modelMatrix[1]; - var a02 = modelMatrix[2]; - var a03 = modelMatrix[3]; - var a10 = modelMatrix[4]; - var a11 = modelMatrix[5]; - var a12 = modelMatrix[6]; - var a13 = modelMatrix[7]; - - modelMatrix[0] = a00 * c + a10 * s; - modelMatrix[1] = a01 * c + a11 * s; - modelMatrix[2] = a02 * c + a12 * s; - modelMatrix[3] = a03 * c + a13 * s; - modelMatrix[4] = a10 * c - a00 * s; - modelMatrix[5] = a11 * c - a01 * s; - modelMatrix[6] = a12 * c - a02 * s; - modelMatrix[7] = a13 * c - a03 * s; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Loads identity matrix into the view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity - * @since 3.0.0 - * - * @return {this} This Model View Projection. - */ - viewIdentity: function () - { - var viewMatrix = this.viewMatrix; - - viewMatrix[0] = 1; - viewMatrix[1] = 0; - viewMatrix[2] = 0; - viewMatrix[3] = 0; - viewMatrix[4] = 0; - viewMatrix[5] = 1; - viewMatrix[6] = 0; - viewMatrix[7] = 0; - viewMatrix[8] = 0; - viewMatrix[9] = 0; - viewMatrix[10] = 1; - viewMatrix[11] = 0; - viewMatrix[12] = 0; - viewMatrix[13] = 0; - viewMatrix[14] = 0; - viewMatrix[15] = 1; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Scales view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - viewScale: function (x, y, z) - { - var viewMatrix = this.viewMatrix; - - viewMatrix[0] = viewMatrix[0] * x; - viewMatrix[1] = viewMatrix[1] * x; - viewMatrix[2] = viewMatrix[2] * x; - viewMatrix[3] = viewMatrix[3] * x; - viewMatrix[4] = viewMatrix[4] * y; - viewMatrix[5] = viewMatrix[5] * y; - viewMatrix[6] = viewMatrix[6] * y; - viewMatrix[7] = viewMatrix[7] * y; - viewMatrix[8] = viewMatrix[8] * z; - viewMatrix[9] = viewMatrix[9] * z; - viewMatrix[10] = viewMatrix[10] * z; - viewMatrix[11] = viewMatrix[11] * z; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Translates view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - viewTranslate: function (x, y, z) - { - var viewMatrix = this.viewMatrix; - - viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; - viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; - viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; - viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the X axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateX: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a10 = viewMatrix[4]; - var a11 = viewMatrix[5]; - var a12 = viewMatrix[6]; - var a13 = viewMatrix[7]; - var a20 = viewMatrix[8]; - var a21 = viewMatrix[9]; - var a22 = viewMatrix[10]; - var a23 = viewMatrix[11]; - - viewMatrix[4] = a10 * c + a20 * s; - viewMatrix[5] = a11 * c + a21 * s; - viewMatrix[6] = a12 * c + a22 * s; - viewMatrix[7] = a13 * c + a23 * s; - viewMatrix[8] = a20 * c - a10 * s; - viewMatrix[9] = a21 * c - a11 * s; - viewMatrix[10] = a22 * c - a12 * s; - viewMatrix[11] = a23 * c - a13 * s; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the Y axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateY: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = viewMatrix[0]; - var a01 = viewMatrix[1]; - var a02 = viewMatrix[2]; - var a03 = viewMatrix[3]; - var a20 = viewMatrix[8]; - var a21 = viewMatrix[9]; - var a22 = viewMatrix[10]; - var a23 = viewMatrix[11]; - - viewMatrix[0] = a00 * c - a20 * s; - viewMatrix[1] = a01 * c - a21 * s; - viewMatrix[2] = a02 * c - a22 * s; - viewMatrix[3] = a03 * c - a23 * s; - viewMatrix[8] = a00 * s + a20 * c; - viewMatrix[9] = a01 * s + a21 * c; - viewMatrix[10] = a02 * s + a22 * c; - viewMatrix[11] = a03 * s + a23 * c; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the Z axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateZ: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = viewMatrix[0]; - var a01 = viewMatrix[1]; - var a02 = viewMatrix[2]; - var a03 = viewMatrix[3]; - var a10 = viewMatrix[4]; - var a11 = viewMatrix[5]; - var a12 = viewMatrix[6]; - var a13 = viewMatrix[7]; - - viewMatrix[0] = a00 * c + a10 * s; - viewMatrix[1] = a01 * c + a11 * s; - viewMatrix[2] = a02 * c + a12 * s; - viewMatrix[3] = a03 * c + a13 * s; - viewMatrix[4] = a10 * c - a00 * s; - viewMatrix[5] = a11 * c - a01 * s; - viewMatrix[6] = a12 * c - a02 * s; - viewMatrix[7] = a13 * c - a03 * s; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D - * @since 3.0.0 - * - * @param {Float32Array} matrix2D - The Matrix2D. - * - * @return {this} This Model View Projection. - */ - viewLoad2D: function (matrix2D) - { - var vm = this.viewMatrix; - - vm[0] = matrix2D[0]; - vm[1] = matrix2D[1]; - vm[2] = 0.0; - vm[3] = 0.0; - vm[4] = matrix2D[2]; - vm[5] = matrix2D[3]; - vm[6] = 0.0; - vm[7] = 0.0; - vm[8] = matrix2D[4]; - vm[9] = matrix2D[5]; - vm[10] = 1.0; - vm[11] = 0.0; - vm[12] = 0.0; - vm[13] = 0.0; - vm[14] = 0.0; - vm[15] = 1.0; - - this.viewMatrixDirty = true; - - return this; - }, - - - /** - * Copies a 4x4 matrix into the view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad - * @since 3.0.0 - * - * @param {Float32Array} matrix - The Matrix2D. - * - * @return {this} This Model View Projection. - */ - viewLoad: function (matrix) - { - var vm = this.viewMatrix; - - vm[0] = matrix[0]; - vm[1] = matrix[1]; - vm[2] = matrix[2]; - vm[3] = matrix[3]; - vm[4] = matrix[4]; - vm[5] = matrix[5]; - vm[6] = matrix[6]; - vm[7] = matrix[7]; - vm[8] = matrix[8]; - vm[9] = matrix[9]; - vm[10] = matrix[10]; - vm[11] = matrix[11]; - vm[12] = matrix[12]; - vm[13] = matrix[13]; - vm[14] = matrix[14]; - vm[15] = matrix[15]; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Loads identity matrix into the projection matrix. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity - * @since 3.0.0 - * - * @return {this} This Model View Projection. - */ - projIdentity: function () - { - var projectionMatrix = this.projectionMatrix; - - projectionMatrix[0] = 1; - projectionMatrix[1] = 0; - projectionMatrix[2] = 0; - projectionMatrix[3] = 0; - projectionMatrix[4] = 0; - projectionMatrix[5] = 1; - projectionMatrix[6] = 0; - projectionMatrix[7] = 0; - projectionMatrix[8] = 0; - projectionMatrix[9] = 0; - projectionMatrix[10] = 1; - projectionMatrix[11] = 0; - projectionMatrix[12] = 0; - projectionMatrix[13] = 0; - projectionMatrix[14] = 0; - projectionMatrix[15] = 1; - - this.projectionMatrixDirty = true; - - return this; - }, - - /** - * Sets up an orthographic projection matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho - * @since 3.0.0 - * - * @param {number} left - The left value. - * @param {number} right - The right value. - * @param {number} bottom - The bottom value. - * @param {number} top - The top value. - * @param {number} near - The near value. - * @param {number} far - The far value. - * - * @return {this} This Model View Projection. - */ - projOrtho: function (left, right, bottom, top, near, far) - { - var projectionMatrix = this.projectionMatrix; - var leftRight = 1.0 / (left - right); - var bottomTop = 1.0 / (bottom - top); - var nearFar = 1.0 / (near - far); - - projectionMatrix[0] = -2.0 * leftRight; - projectionMatrix[1] = 0.0; - projectionMatrix[2] = 0.0; - projectionMatrix[3] = 0.0; - projectionMatrix[4] = 0.0; - projectionMatrix[5] = -2.0 * bottomTop; - projectionMatrix[6] = 0.0; - projectionMatrix[7] = 0.0; - projectionMatrix[8] = 0.0; - projectionMatrix[9] = 0.0; - projectionMatrix[10] = 2.0 * nearFar; - projectionMatrix[11] = 0.0; - projectionMatrix[12] = (left + right) * leftRight; - projectionMatrix[13] = (top + bottom) * bottomTop; - projectionMatrix[14] = (far + near) * nearFar; - projectionMatrix[15] = 1.0; - - this.projectionMatrixDirty = true; - - return this; - }, - - /** - * Sets up a perspective projection matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp - * @since 3.0.0 - * - * @param {number} fovY - The fov value. - * @param {number} aspectRatio - The aspectRatio value. - * @param {number} near - The near value. - * @param {number} far - The far value. - * - * @return {this} This Model View Projection. - */ - projPersp: function (fovY, aspectRatio, near, far) - { - var projectionMatrix = this.projectionMatrix; - var fov = 1.0 / Math.tan(fovY / 2.0); - var nearFar = 1.0 / (near - far); - - projectionMatrix[0] = fov / aspectRatio; - projectionMatrix[1] = 0.0; - projectionMatrix[2] = 0.0; - projectionMatrix[3] = 0.0; - projectionMatrix[4] = 0.0; - projectionMatrix[5] = fov; - projectionMatrix[6] = 0.0; - projectionMatrix[7] = 0.0; - projectionMatrix[8] = 0.0; - projectionMatrix[9] = 0.0; - projectionMatrix[10] = (far + near) * nearFar; - projectionMatrix[11] = -1.0; - projectionMatrix[12] = 0.0; - projectionMatrix[13] = 0.0; - projectionMatrix[14] = (2.0 * far * near) * nearFar; - projectionMatrix[15] = 0.0; - - this.projectionMatrixDirty = true; - - return this; - } -}; - -module.exports = ModelViewProjection; - - -/***/ }), -/* 234 */ +/* 236 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56601,7 +54810,7 @@ var Sleeping = {}; module.exports = Sleeping; -var Events = __webpack_require__(235); +var Events = __webpack_require__(237); (function() { @@ -56723,7 +54932,7 @@ var Events = __webpack_require__(235); /***/ }), -/* 235 */ +/* 237 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56841,7 +55050,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 236 */ +/* 238 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56856,65 +55065,65 @@ var Common = __webpack_require__(37); module.exports = { - AlignTo: __webpack_require__(522), - Angle: __webpack_require__(523), - Call: __webpack_require__(524), - GetFirst: __webpack_require__(525), - GetLast: __webpack_require__(526), - GridAlign: __webpack_require__(527), - IncAlpha: __webpack_require__(588), - IncX: __webpack_require__(589), - IncXY: __webpack_require__(590), - IncY: __webpack_require__(591), - PlaceOnCircle: __webpack_require__(592), - PlaceOnEllipse: __webpack_require__(593), - PlaceOnLine: __webpack_require__(594), - PlaceOnRectangle: __webpack_require__(595), - PlaceOnTriangle: __webpack_require__(596), - PlayAnimation: __webpack_require__(597), + AlignTo: __webpack_require__(521), + Angle: __webpack_require__(522), + Call: __webpack_require__(523), + GetFirst: __webpack_require__(524), + GetLast: __webpack_require__(525), + GridAlign: __webpack_require__(526), + IncAlpha: __webpack_require__(587), + IncX: __webpack_require__(588), + IncXY: __webpack_require__(589), + IncY: __webpack_require__(590), + PlaceOnCircle: __webpack_require__(591), + PlaceOnEllipse: __webpack_require__(592), + PlaceOnLine: __webpack_require__(593), + PlaceOnRectangle: __webpack_require__(594), + PlaceOnTriangle: __webpack_require__(595), + PlayAnimation: __webpack_require__(596), PropertyValueInc: __webpack_require__(34), - PropertyValueSet: __webpack_require__(26), - RandomCircle: __webpack_require__(598), - RandomEllipse: __webpack_require__(599), - RandomLine: __webpack_require__(600), - RandomRectangle: __webpack_require__(601), - RandomTriangle: __webpack_require__(602), - Rotate: __webpack_require__(603), - RotateAround: __webpack_require__(604), - RotateAroundDistance: __webpack_require__(605), - ScaleX: __webpack_require__(606), - ScaleXY: __webpack_require__(607), - ScaleY: __webpack_require__(608), - SetAlpha: __webpack_require__(609), - SetBlendMode: __webpack_require__(610), - SetDepth: __webpack_require__(611), - SetHitArea: __webpack_require__(612), - SetOrigin: __webpack_require__(613), - SetRotation: __webpack_require__(614), - SetScale: __webpack_require__(615), - SetScaleX: __webpack_require__(616), - SetScaleY: __webpack_require__(617), - SetScrollFactor: __webpack_require__(618), - SetScrollFactorX: __webpack_require__(619), - SetScrollFactorY: __webpack_require__(620), - SetTint: __webpack_require__(621), - SetVisible: __webpack_require__(622), - SetX: __webpack_require__(623), - SetXY: __webpack_require__(624), - SetY: __webpack_require__(625), - ShiftPosition: __webpack_require__(626), - Shuffle: __webpack_require__(627), - SmootherStep: __webpack_require__(628), - SmoothStep: __webpack_require__(629), - Spread: __webpack_require__(630), - ToggleVisible: __webpack_require__(631), - WrapInRectangle: __webpack_require__(632) + PropertyValueSet: __webpack_require__(25), + RandomCircle: __webpack_require__(597), + RandomEllipse: __webpack_require__(598), + RandomLine: __webpack_require__(599), + RandomRectangle: __webpack_require__(600), + RandomTriangle: __webpack_require__(601), + Rotate: __webpack_require__(602), + RotateAround: __webpack_require__(603), + RotateAroundDistance: __webpack_require__(604), + ScaleX: __webpack_require__(605), + ScaleXY: __webpack_require__(606), + ScaleY: __webpack_require__(607), + SetAlpha: __webpack_require__(608), + SetBlendMode: __webpack_require__(609), + SetDepth: __webpack_require__(610), + SetHitArea: __webpack_require__(611), + SetOrigin: __webpack_require__(612), + SetRotation: __webpack_require__(613), + SetScale: __webpack_require__(614), + SetScaleX: __webpack_require__(615), + SetScaleY: __webpack_require__(616), + SetScrollFactor: __webpack_require__(617), + SetScrollFactorX: __webpack_require__(618), + SetScrollFactorY: __webpack_require__(619), + SetTint: __webpack_require__(620), + SetVisible: __webpack_require__(621), + SetX: __webpack_require__(622), + SetXY: __webpack_require__(623), + SetY: __webpack_require__(624), + ShiftPosition: __webpack_require__(625), + Shuffle: __webpack_require__(626), + SmootherStep: __webpack_require__(627), + SmoothStep: __webpack_require__(628), + Spread: __webpack_require__(629), + ToggleVisible: __webpack_require__(630), + WrapInRectangle: __webpack_require__(631) }; /***/ }), -/* 237 */ +/* 239 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56923,22 +55132,22 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ALIGN_CONST = __webpack_require__(102); +var ALIGN_CONST = __webpack_require__(106); var AlignToMap = []; -AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(238); -AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(239); -AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(240); -AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = __webpack_require__(241); -AlignToMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(242); -AlignToMap[ALIGN_CONST.LEFT_TOP] = __webpack_require__(243); -AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = __webpack_require__(244); -AlignToMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(245); -AlignToMap[ALIGN_CONST.RIGHT_TOP] = __webpack_require__(246); -AlignToMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(247); -AlignToMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(248); -AlignToMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(249); +AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(240); +AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(241); +AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(242); +AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = __webpack_require__(243); +AlignToMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(244); +AlignToMap[ALIGN_CONST.LEFT_TOP] = __webpack_require__(245); +AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = __webpack_require__(246); +AlignToMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(247); +AlignToMap[ALIGN_CONST.RIGHT_TOP] = __webpack_require__(248); +AlignToMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(249); +AlignToMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(250); +AlignToMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(251); /** * Takes a Game Object and aligns it next to another, at the given position. @@ -56966,7 +55175,7 @@ module.exports = QuickSet; /***/ }), -/* 238 */ +/* 240 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -56976,8 +55185,8 @@ module.exports = QuickSet; */ var GetBottom = __webpack_require__(38); -var GetCenterX = __webpack_require__(74); -var SetCenterX = __webpack_require__(75); +var GetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); var SetTop = __webpack_require__(39); /** @@ -57010,7 +55219,7 @@ module.exports = BottomCenter; /***/ }), -/* 239 */ +/* 241 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57054,7 +55263,7 @@ module.exports = BottomLeft; /***/ }), -/* 240 */ +/* 242 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57098,7 +55307,7 @@ module.exports = BottomRight; /***/ }), -/* 241 */ +/* 243 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57142,7 +55351,7 @@ module.exports = LeftBottom; /***/ }), -/* 242 */ +/* 244 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57151,9 +55360,9 @@ module.exports = LeftBottom; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetLeft = __webpack_require__(40); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetRight = __webpack_require__(43); /** @@ -57186,7 +55395,7 @@ module.exports = LeftCenter; /***/ }), -/* 243 */ +/* 245 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57230,7 +55439,7 @@ module.exports = LeftTop; /***/ }), -/* 244 */ +/* 246 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57274,7 +55483,7 @@ module.exports = RightBottom; /***/ }), -/* 245 */ +/* 247 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57283,9 +55492,9 @@ module.exports = RightBottom; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetRight = __webpack_require__(42); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetLeft = __webpack_require__(41); /** @@ -57318,7 +55527,7 @@ module.exports = RightCenter; /***/ }), -/* 246 */ +/* 248 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57362,7 +55571,7 @@ module.exports = RightTop; /***/ }), -/* 247 */ +/* 249 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57371,10 +55580,10 @@ module.exports = RightTop; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterX = __webpack_require__(74); +var GetCenterX = __webpack_require__(75); var GetTop = __webpack_require__(45); var SetBottom = __webpack_require__(44); -var SetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); /** * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. @@ -57406,7 +55615,7 @@ module.exports = TopCenter; /***/ }), -/* 248 */ +/* 250 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57450,7 +55659,7 @@ module.exports = TopLeft; /***/ }), -/* 249 */ +/* 251 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57494,7 +55703,7 @@ module.exports = TopRight; /***/ }), -/* 250 */ +/* 252 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57503,19 +55712,19 @@ module.exports = TopRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ALIGN_CONST = __webpack_require__(102); +var ALIGN_CONST = __webpack_require__(106); var AlignInMap = []; -AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(251); -AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(252); -AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(253); -AlignInMap[ALIGN_CONST.CENTER] = __webpack_require__(254); -AlignInMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(256); -AlignInMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(257); -AlignInMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(258); -AlignInMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(259); -AlignInMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(260); +AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(253); +AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(254); +AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(255); +AlignInMap[ALIGN_CONST.CENTER] = __webpack_require__(256); +AlignInMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(258); +AlignInMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(259); +AlignInMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(260); +AlignInMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(261); +AlignInMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(262); AlignInMap[ALIGN_CONST.LEFT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_LEFT]; AlignInMap[ALIGN_CONST.LEFT_TOP] = AlignInMap[ALIGN_CONST.TOP_LEFT]; AlignInMap[ALIGN_CONST.RIGHT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_RIGHT]; @@ -57547,7 +55756,7 @@ module.exports = QuickSet; /***/ }), -/* 251 */ +/* 253 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57557,9 +55766,9 @@ module.exports = QuickSet; */ var GetBottom = __webpack_require__(38); -var GetCenterX = __webpack_require__(74); +var GetCenterX = __webpack_require__(75); var SetBottom = __webpack_require__(44); -var SetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); /** * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. @@ -57591,7 +55800,7 @@ module.exports = BottomCenter; /***/ }), -/* 252 */ +/* 254 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57635,7 +55844,7 @@ module.exports = BottomLeft; /***/ }), -/* 253 */ +/* 255 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57679,7 +55888,7 @@ module.exports = BottomRight; /***/ }), -/* 254 */ +/* 256 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57688,9 +55897,9 @@ module.exports = BottomRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CenterOn = __webpack_require__(255); -var GetCenterX = __webpack_require__(74); -var GetCenterY = __webpack_require__(76); +var CenterOn = __webpack_require__(257); +var GetCenterX = __webpack_require__(75); +var GetCenterY = __webpack_require__(77); /** * Takes given Game Object and aligns it so that it is positioned in the center of the other. @@ -57721,7 +55930,7 @@ module.exports = Center; /***/ }), -/* 255 */ +/* 257 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57730,8 +55939,8 @@ module.exports = Center; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetCenterX = __webpack_require__(75); -var SetCenterY = __webpack_require__(77); +var SetCenterX = __webpack_require__(76); +var SetCenterY = __webpack_require__(78); /** * Positions the Game Object so that it is centered on the given coordinates. @@ -57758,7 +55967,7 @@ module.exports = CenterOn; /***/ }), -/* 256 */ +/* 258 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57767,9 +55976,9 @@ module.exports = CenterOn; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetLeft = __webpack_require__(40); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetLeft = __webpack_require__(41); /** @@ -57802,7 +56011,7 @@ module.exports = LeftCenter; /***/ }), -/* 257 */ +/* 259 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57811,9 +56020,9 @@ module.exports = LeftCenter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterY = __webpack_require__(76); +var GetCenterY = __webpack_require__(77); var GetRight = __webpack_require__(42); -var SetCenterY = __webpack_require__(77); +var SetCenterY = __webpack_require__(78); var SetRight = __webpack_require__(43); /** @@ -57846,7 +56055,7 @@ module.exports = RightCenter; /***/ }), -/* 258 */ +/* 260 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57855,9 +56064,9 @@ module.exports = RightCenter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetCenterX = __webpack_require__(74); +var GetCenterX = __webpack_require__(75); var GetTop = __webpack_require__(45); -var SetCenterX = __webpack_require__(75); +var SetCenterX = __webpack_require__(76); var SetTop = __webpack_require__(39); /** @@ -57890,7 +56099,7 @@ module.exports = TopCenter; /***/ }), -/* 259 */ +/* 261 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57934,7 +56143,7 @@ module.exports = TopLeft; /***/ }), -/* 260 */ +/* 262 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57978,7 +56187,7 @@ module.exports = TopRight; /***/ }), -/* 261 */ +/* 263 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -57987,9 +56196,9 @@ module.exports = TopRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CircumferencePoint = __webpack_require__(143); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var CircumferencePoint = __webpack_require__(146); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); var Point = __webpack_require__(4); /** @@ -58021,7 +56230,7 @@ module.exports = GetPoint; /***/ }), -/* 262 */ +/* 264 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58030,10 +56239,10 @@ module.exports = GetPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circumference = __webpack_require__(263); -var CircumferencePoint = __webpack_require__(143); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var Circumference = __webpack_require__(265); +var CircumferencePoint = __webpack_require__(146); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); /** * Returns an array of Point objects containing the coordinates of the points around the circumference of the Circle, @@ -58073,7 +56282,7 @@ module.exports = GetPoints; /***/ }), -/* 263 */ +/* 265 */ /***/ (function(module, exports) { /** @@ -58101,7 +56310,7 @@ module.exports = Circumference; /***/ }), -/* 264 */ +/* 266 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58110,7 +56319,7 @@ module.exports = Circumference; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); // bitmask flag for GameObject.renderMask var _FLAG = 2; // 0010 @@ -58211,7 +56420,7 @@ module.exports = AlphaSingle; /***/ }), -/* 265 */ +/* 267 */ /***/ (function(module, exports) { /** @@ -58295,7 +56504,7 @@ module.exports = FindClosestInSorted; /***/ }), -/* 266 */ +/* 268 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58469,7 +56678,7 @@ module.exports = AnimationFrame; /***/ }), -/* 267 */ +/* 269 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58591,7 +56800,7 @@ module.exports = BlendMode; /***/ }), -/* 268 */ +/* 270 */ /***/ (function(module, exports) { /** @@ -58684,7 +56893,7 @@ module.exports = Depth; /***/ }), -/* 269 */ +/* 271 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58693,8 +56902,8 @@ module.exports = Depth; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetPoint = __webpack_require__(146); -var Perimeter = __webpack_require__(108); +var GetPoint = __webpack_require__(149); +var Perimeter = __webpack_require__(112); // Return an array of points from the perimeter of the rectangle // each spaced out based on the quantity or step required @@ -58738,7 +56947,7 @@ module.exports = GetPoints; /***/ }), -/* 270 */ +/* 272 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58777,7 +56986,7 @@ module.exports = GetPoint; /***/ }), -/* 271 */ +/* 273 */ /***/ (function(module, exports) { /** @@ -58817,7 +57026,7 @@ module.exports = RotateAround; /***/ }), -/* 272 */ +/* 274 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58826,8 +57035,8 @@ module.exports = RotateAround; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapMask = __webpack_require__(273); -var GeometryMask = __webpack_require__(274); +var BitmapMask = __webpack_require__(275); +var GeometryMask = __webpack_require__(276); /** * Provides methods used for getting and setting the mask of a Game Object. @@ -58964,7 +57173,7 @@ module.exports = Mask; /***/ }), -/* 273 */ +/* 275 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -58974,7 +57183,7 @@ module.exports = Mask; */ var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); /** * @classdesc @@ -59257,7 +57466,7 @@ module.exports = BitmapMask; /***/ }), -/* 274 */ +/* 276 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -59572,7 +57781,7 @@ module.exports = GeometryMask; /***/ }), -/* 275 */ +/* 277 */ /***/ (function(module, exports) { /** @@ -59679,7 +57888,7 @@ module.exports = ScrollFactor; /***/ }), -/* 276 */ +/* 278 */ /***/ (function(module, exports) { /** @@ -59740,7 +57949,7 @@ module.exports = ToJSON; /***/ }), -/* 277 */ +/* 279 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -59749,10 +57958,10 @@ module.exports = ToJSON; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var TransformMatrix = __webpack_require__(30); -var WrapAngle = __webpack_require__(230); -var WrapAngleDegrees = __webpack_require__(231); +var MATH_CONST = __webpack_require__(13); +var TransformMatrix = __webpack_require__(32); +var WrapAngle = __webpack_require__(232); +var WrapAngleDegrees = __webpack_require__(233); // global bitmask flag for GameObject.renderMask (used by Scale) var _FLAG = 4; // 0100 @@ -60279,7 +58488,7 @@ module.exports = Transform; /***/ }), -/* 278 */ +/* 280 */ /***/ (function(module, exports) { /** @@ -60368,7 +58577,7 @@ module.exports = Visible; /***/ }), -/* 279 */ +/* 281 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -60383,16 +58592,16 @@ module.exports = Visible; module.exports = { - CHANGE_DATA: __webpack_require__(573), - CHANGE_DATA_KEY: __webpack_require__(574), - REMOVE_DATA: __webpack_require__(575), - SET_DATA: __webpack_require__(576) + CHANGE_DATA: __webpack_require__(572), + CHANGE_DATA_KEY: __webpack_require__(573), + REMOVE_DATA: __webpack_require__(574), + SET_DATA: __webpack_require__(575) }; /***/ }), -/* 280 */ +/* 282 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -60401,25 +58610,25 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Perimeter = __webpack_require__(108); +var Perimeter = __webpack_require__(112); var Point = __webpack_require__(4); /** - * Returns an array of points from the perimeter of the Rectangle, where each point is spaced out based - * on either the `step` value, or the `quantity`. + * Return an array of points from the perimeter of the rectangle + * each spaced out based on the quantity or step required * * @function Phaser.Geom.Rectangle.MarchingAnts * @since 3.0.0 * * @generic {Phaser.Geom.Point[]} 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 {integer} [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 {(array|Phaser.Geom.Point[])} [out] - An array in which the perimeter points will be stored. If not given, a new array instance is created. + * @param {Phaser.Geom.Rectangle} rect - [description] + * @param {number} step - [description] + * @param {integer} quantity - [description] + * @param {(array|Phaser.Geom.Point[])} [out] - [description] * - * @return {(array|Phaser.Geom.Point[])} An array containing the perimeter points from the Rectangle. + * @return {(array|Phaser.Geom.Point[])} [description] */ var MarchingAnts = function (rect, step, quantity, out) { @@ -60511,7 +58720,7 @@ module.exports = MarchingAnts; /***/ }), -/* 281 */ +/* 283 */ /***/ (function(module, exports) { /** @@ -60551,7 +58760,7 @@ module.exports = RotateLeft; /***/ }), -/* 282 */ +/* 284 */ /***/ (function(module, exports) { /** @@ -60591,7 +58800,7 @@ module.exports = RotateRight; /***/ }), -/* 283 */ +/* 285 */ /***/ (function(module, exports) { /** @@ -60665,7 +58874,7 @@ module.exports = BresenhamPoints; /***/ }), -/* 284 */ +/* 286 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -60674,14 +58883,14 @@ module.exports = BresenhamPoints; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Animation = __webpack_require__(145); +var Animation = __webpack_require__(148); var Class = __webpack_require__(0); -var CustomMap = __webpack_require__(156); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(107); -var GameEvents = __webpack_require__(19); +var CustomMap = __webpack_require__(159); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(111); +var GameEvents = __webpack_require__(18); var GetValue = __webpack_require__(6); -var Pad = __webpack_require__(157); +var Pad = __webpack_require__(160); /** * @classdesc @@ -60932,34 +59141,7 @@ var AnimationManager = new Class({ }, /** - * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. - * - * Generates objects with string based frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNames}. - * - * It's a helper method, designed to make it easier for you to extract all of the frame names from texture atlases. - * If you're working with a sprite sheet, see the `generateFrameNumbers` method instead. - * - * Example: - * - * If you have a texture atlases loaded called `gems` and it contains 6 frames called `ruby_0001`, `ruby_0002`, and so on, - * then you can call this method using: `this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 })`. - * - * The `end` value tells it to look for 6 frames, incrementally numbered, all starting with the prefix `ruby_`. The `zeroPad` - * value tells it how many zeroes pad out the numbers. To create an animation using this method, you can do: - * - * ```javascript - * this.anims.create({ - * key: 'ruby', - * repeat: -1, - * frames: this.anims.generateFrameNames('gems', { - * prefix: 'ruby_', - * end: 6, - * zeroPad: 4 - * }) - * }); - * ``` - * - * Please see the animation examples for further details. + * [description] * * @method Phaser.Animations.AnimationManager#generateFrameNames * @since 3.0.0 @@ -61037,8 +59219,6 @@ var AnimationManager = new Class({ * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. * * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. - * - * If you're working with a texture atlas, see the `generateFrameNames` method instead. * * @method Phaser.Animations.AnimationManager#generateFrameNumbers * @since 3.0.0 @@ -61204,10 +59384,7 @@ var AnimationManager = new Class({ }, /** - * 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. + * Remove an animation. * * @method Phaser.Animations.AnimationManager#remove * @fires Phaser.Animations.Events#REMOVE_ANIMATION @@ -61215,7 +59392,7 @@ var AnimationManager = new Class({ * * @param {string} key - The key of the animation to remove. * - * @return {Phaser.Animations.Animation} The Animation instance that was removed from the Animation Manager. + * @return {Phaser.Animations.Animation} [description] */ remove: function (key) { @@ -61293,36 +59470,35 @@ var AnimationManager = new Class({ }, /** - * Returns the Animation data as JavaScript object based on the given key. - * Or, if not key is defined, it will return the data of all animations as array of objects. + * Get the animation data as javascript object by giving key, or get the data of all animations as array of objects, if key wasn't provided. * * @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. + * @param {string} key - [description] * - * @return {Phaser.Types.Animations.JSONAnimations} The resulting JSONAnimations formatted object. + * @return {Phaser.Types.Animations.JSONAnimations} [description] */ toJSON: function (key) { - var output = { - anims: [], - globalTimeScale: this.globalTimeScale - }; - if (key !== undefined && key !== '') { - output.anims.push(this.anims.get(key).toJSON()); + return this.anims.get(key).toJSON(); } else { + var output = { + anims: [], + globalTimeScale: this.globalTimeScale + }; + this.anims.each(function (animationKey, animation) { output.anims.push(animation.toJSON()); }); - } - return output; + return output; + } }, /** @@ -61347,7 +59523,7 @@ module.exports = AnimationManager; /***/ }), -/* 285 */ +/* 287 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -61357,9 +59533,9 @@ module.exports = AnimationManager; */ var Class = __webpack_require__(0); -var CustomMap = __webpack_require__(156); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(286); +var CustomMap = __webpack_require__(159); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(288); /** * @classdesc @@ -61533,7 +59709,7 @@ module.exports = BaseCache; /***/ }), -/* 286 */ +/* 288 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -61548,14 +59724,14 @@ module.exports = BaseCache; module.exports = { - ADD: __webpack_require__(635), - REMOVE: __webpack_require__(636) + ADD: __webpack_require__(634), + REMOVE: __webpack_require__(635) }; /***/ }), -/* 287 */ +/* 289 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -61564,9 +59740,9 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCache = __webpack_require__(285); +var BaseCache = __webpack_require__(287); var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); /** * @classdesc @@ -61789,7 +59965,7 @@ module.exports = CacheManager; /***/ }), -/* 288 */ +/* 290 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -61798,15 +59974,15 @@ module.exports = CacheManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCamera = __webpack_require__(89); -var CanvasPool = __webpack_require__(27); -var CenterOn = __webpack_require__(162); -var Clamp = __webpack_require__(23); +var BaseCamera = __webpack_require__(91); +var CanvasPool = __webpack_require__(26); +var CenterOn = __webpack_require__(165); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Effects = __webpack_require__(296); -var Linear = __webpack_require__(111); -var Rectangle = __webpack_require__(13); +var Effects = __webpack_require__(298); +var Linear = __webpack_require__(115); +var Rectangle = __webpack_require__(11); var Vector2 = __webpack_require__(3); /** @@ -62002,24 +60178,6 @@ var Camera = new Class({ */ this.renderToTexture = false; - /** - * If this Camera is rendering to a texture (via `setRenderToTexture`) then you - * have the option to control if it should also render to the Game canvas as well. - * - * By default, a Camera will render both to its texture and to the Game canvas. - * - * However, if you set ths property to `false` it will only render to the texture - * and skip rendering to the Game canvas. - * - * Setting this property if the Camera isn't rendering to a texture has no effect. - * - * @name Phaser.Cameras.Scene2D.Camera#renderToGame - * @type {boolean} - * @default true - * @since 3.23.0 - */ - this.renderToGame = true; - /** * If this Camera has been set to render to a texture then this holds a reference * to the HTML Canvas Element that the Camera is drawing to. @@ -62116,9 +60274,6 @@ var Camera = new Class({ * * You should not enable this unless you plan on actually using the texture it creates * somehow, otherwise you're just doubling the work required to render your game. - * - * If you only require the Camera to render to a texture, and not also to the Game, - * them set the `renderToGame` parameter to `false`. * * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. * @@ -62129,14 +60284,11 @@ var Camera = new Class({ * @since 3.13.0 * * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. - * @param {boolean} [renderToGame=true] - If you do not need the Camera to still render to the Game, set this parameter to `false`. * * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. */ - setRenderToTexture: function (pipeline, renderToGame) + setRenderToTexture: function (pipeline) { - if (renderToGame === undefined) { renderToGame = true; } - var renderer = this.scene.sys.game.renderer; if (renderer.gl) @@ -62151,7 +60303,6 @@ var Camera = new Class({ } this.renderToTexture = true; - this.renderToGame = renderToGame; if (pipeline) { @@ -62807,7 +60958,7 @@ module.exports = Camera; /***/ }), -/* 289 */ +/* 291 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -62816,7 +60967,7 @@ module.exports = Camera; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); /** * Converts a hex string into a Phaser Color object. @@ -62860,7 +61011,7 @@ module.exports = HexStringToColor; /***/ }), -/* 290 */ +/* 292 */ /***/ (function(module, exports) { /** @@ -62891,7 +61042,7 @@ module.exports = GetColor32; /***/ }), -/* 291 */ +/* 293 */ /***/ (function(module, exports) { /** @@ -62971,7 +61122,7 @@ module.exports = RGBToHSV; /***/ }), -/* 292 */ +/* 294 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -62980,8 +61131,8 @@ module.exports = RGBToHSV; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); -var IntegerToRGB = __webpack_require__(293); +var Color = __webpack_require__(33); +var IntegerToRGB = __webpack_require__(295); /** * Converts the given color value into an instance of a Color object. @@ -63004,7 +61155,7 @@ module.exports = IntegerToColor; /***/ }), -/* 293 */ +/* 295 */ /***/ (function(module, exports) { /** @@ -63052,7 +61203,7 @@ module.exports = IntegerToRGB; /***/ }), -/* 294 */ +/* 296 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -63061,7 +61212,7 @@ module.exports = IntegerToRGB; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); /** * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. @@ -63082,7 +61233,7 @@ module.exports = ObjectToColor; /***/ }), -/* 295 */ +/* 297 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -63091,7 +61242,7 @@ module.exports = ObjectToColor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); /** * Converts a CSS 'web' string into a Phaser Color object. @@ -63128,7 +61279,7 @@ module.exports = RGBStringToColor; /***/ }), -/* 296 */ +/* 298 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -63143,57 +61294,11 @@ module.exports = RGBStringToColor; module.exports = { - Fade: __webpack_require__(657), - Flash: __webpack_require__(658), - Pan: __webpack_require__(659), - Shake: __webpack_require__(692), - Zoom: __webpack_require__(693) - -}; - - -/***/ }), -/* 297 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Back - */ - -module.exports = { - - In: __webpack_require__(660), - Out: __webpack_require__(661), - InOut: __webpack_require__(662) - -}; - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Bounce - */ - -module.exports = { - - In: __webpack_require__(663), - Out: __webpack_require__(664), - InOut: __webpack_require__(665) + Fade: __webpack_require__(656), + Flash: __webpack_require__(657), + Pan: __webpack_require__(658), + Shake: __webpack_require__(691), + Zoom: __webpack_require__(692) }; @@ -63209,14 +61314,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Circular + * @namespace Phaser.Math.Easing.Back */ module.exports = { - In: __webpack_require__(666), - Out: __webpack_require__(667), - InOut: __webpack_require__(668) + In: __webpack_require__(659), + Out: __webpack_require__(660), + InOut: __webpack_require__(661) }; @@ -63232,14 +61337,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Cubic + * @namespace Phaser.Math.Easing.Bounce */ module.exports = { - In: __webpack_require__(669), - Out: __webpack_require__(670), - InOut: __webpack_require__(671) + In: __webpack_require__(662), + Out: __webpack_require__(663), + InOut: __webpack_require__(664) }; @@ -63255,14 +61360,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Elastic + * @namespace Phaser.Math.Easing.Circular */ module.exports = { - In: __webpack_require__(672), - Out: __webpack_require__(673), - InOut: __webpack_require__(674) + In: __webpack_require__(665), + Out: __webpack_require__(666), + InOut: __webpack_require__(667) }; @@ -63278,14 +61383,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Expo + * @namespace Phaser.Math.Easing.Cubic */ module.exports = { - In: __webpack_require__(675), - Out: __webpack_require__(676), - InOut: __webpack_require__(677) + In: __webpack_require__(668), + Out: __webpack_require__(669), + InOut: __webpack_require__(670) }; @@ -63301,10 +61406,16 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Linear + * @namespace Phaser.Math.Easing.Elastic */ -module.exports = __webpack_require__(678); +module.exports = { + + In: __webpack_require__(671), + Out: __webpack_require__(672), + InOut: __webpack_require__(673) + +}; /***/ }), @@ -63318,14 +61429,14 @@ module.exports = __webpack_require__(678); */ /** - * @namespace Phaser.Math.Easing.Quadratic + * @namespace Phaser.Math.Easing.Expo */ module.exports = { - In: __webpack_require__(679), - Out: __webpack_require__(680), - InOut: __webpack_require__(681) + In: __webpack_require__(674), + Out: __webpack_require__(675), + InOut: __webpack_require__(676) }; @@ -63341,16 +61452,10 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Quartic + * @namespace Phaser.Math.Easing.Linear */ -module.exports = { - - In: __webpack_require__(682), - Out: __webpack_require__(683), - InOut: __webpack_require__(684) - -}; +module.exports = __webpack_require__(677); /***/ }), @@ -63364,14 +61469,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Quintic + * @namespace Phaser.Math.Easing.Quadratic */ module.exports = { - In: __webpack_require__(685), - Out: __webpack_require__(686), - InOut: __webpack_require__(687) + In: __webpack_require__(678), + Out: __webpack_require__(679), + InOut: __webpack_require__(680) }; @@ -63387,14 +61492,14 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Sine + * @namespace Phaser.Math.Easing.Quartic */ module.exports = { - In: __webpack_require__(688), - Out: __webpack_require__(689), - InOut: __webpack_require__(690) + In: __webpack_require__(681), + Out: __webpack_require__(682), + InOut: __webpack_require__(683) }; @@ -63410,16 +61515,62 @@ module.exports = { */ /** - * @namespace Phaser.Math.Easing.Stepped + * @namespace Phaser.Math.Easing.Quintic */ -module.exports = __webpack_require__(691); +module.exports = { + + In: __webpack_require__(684), + Out: __webpack_require__(685), + InOut: __webpack_require__(686) + +}; /***/ }), /* 309 */ /***/ (function(module, exports, __webpack_require__) { +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Sine + */ + +module.exports = { + + In: __webpack_require__(687), + Out: __webpack_require__(688), + InOut: __webpack_require__(689) + +}; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Stepped + */ + +module.exports = __webpack_require__(690); + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -63427,15 +61578,15 @@ module.exports = __webpack_require__(691); */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); -var Device = __webpack_require__(310); +var CONST = __webpack_require__(29); +var Device = __webpack_require__(312); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); var IsPlainObject = __webpack_require__(7); -var PhaserMath = __webpack_require__(165); +var PhaserMath = __webpack_require__(168); var NOOP = __webpack_require__(1); -var DefaultPlugins = __webpack_require__(170); -var ValueToColor = __webpack_require__(158); +var DefaultPlugins = __webpack_require__(173); +var ValueToColor = __webpack_require__(161); /** * @classdesc @@ -63902,11 +62053,6 @@ var Config = new Class({ */ this.loaderTimeout = GetValue(config, 'loader.timeout', 0); - /** - * @const {boolean} Phaser.Core.Config#loaderWithCredentials - Optional XHR withCredentials value. - */ - this.loaderWithCredentials = GetValue(config, 'loader.withCredentials', false); - /* * Allows `plugins` property to either be an array, in which case it just replaces * the default plugins like previously, or a config object. @@ -63998,7 +62144,7 @@ module.exports = Config; /***/ }), -/* 310 */ +/* 312 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64032,20 +62178,20 @@ module.exports = Config; module.exports = { - os: __webpack_require__(112), - browser: __webpack_require__(113), - features: __webpack_require__(164), - input: __webpack_require__(722), - audio: __webpack_require__(723), - video: __webpack_require__(724), - fullscreen: __webpack_require__(725), - canvasFeatures: __webpack_require__(311) + os: __webpack_require__(116), + browser: __webpack_require__(117), + features: __webpack_require__(167), + input: __webpack_require__(721), + audio: __webpack_require__(722), + video: __webpack_require__(723), + fullscreen: __webpack_require__(724), + canvasFeatures: __webpack_require__(313) }; /***/ }), -/* 311 */ +/* 313 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64054,7 +62200,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); /** * Determines the canvas features of the browser running this Phaser Game instance. @@ -64159,7 +62305,7 @@ module.exports = init(); /***/ }), -/* 312 */ +/* 314 */ /***/ (function(module, exports) { /** @@ -64190,7 +62336,7 @@ module.exports = Between; /***/ }), -/* 313 */ +/* 315 */ /***/ (function(module, exports) { /** @@ -64227,39 +62373,7 @@ module.exports = Normalize; /***/ }), -/* 314 */ -/***/ (function(module, exports) { - -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the distance between two points. - * - * @function Phaser.Math.Distance.BetweenPoints - * @since 3.22.0 - * - * @param {Phaser.Types.Math.Vector2Like} a - The first point. - * @param {Phaser.Types.Math.Vector2Like} b - The second point. - * - * @return {number} The distance between the points. - */ -var DistanceBetweenPoints = function (a, b) -{ - var dx = a.x - b.x; - var dy = a.y - b.y; - - return Math.sqrt(dx * dx + dy * dy); -}; - -module.exports = DistanceBetweenPoints; - - -/***/ }), -/* 315 */ +/* 316 */ /***/ (function(module, exports) { /** @@ -64293,7 +62407,7 @@ module.exports = DistanceSquared; /***/ }), -/* 316 */ +/* 317 */ /***/ (function(module, exports) { /** @@ -64327,7 +62441,7 @@ module.exports = GreaterThan; /***/ }), -/* 317 */ +/* 318 */ /***/ (function(module, exports) { /** @@ -64361,7 +62475,7 @@ module.exports = LessThan; /***/ }), -/* 318 */ +/* 319 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64370,18 +62484,18 @@ module.exports = LessThan; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Factorial = __webpack_require__(319); +var Factorial = __webpack_require__(320); /** - * Calculates the Bernstein basis from the three factorial coefficients. + * [description] * * @function Phaser.Math.Bernstein * @since 3.0.0 * - * @param {number} n - The first value. - * @param {number} i - The second value. + * @param {number} n - [description] + * @param {number} i - [description] * - * @return {number} The Bernstein basis of Factorial(n) / Factorial(i) / Factorial(n - i) + * @return {number} [description] */ var Bernstein = function (n, i) { @@ -64392,7 +62506,7 @@ module.exports = Bernstein; /***/ }), -/* 319 */ +/* 320 */ /***/ (function(module, exports) { /** @@ -64432,7 +62546,7 @@ module.exports = Factorial; /***/ }), -/* 320 */ +/* 321 */ /***/ (function(module, exports) { /** @@ -64502,7 +62616,7 @@ module.exports = CubicBezierInterpolation; /***/ }), -/* 321 */ +/* 322 */ /***/ (function(module, exports) { /** @@ -64561,7 +62675,7 @@ module.exports = QuadraticBezierInterpolation; /***/ }), -/* 322 */ +/* 323 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64570,7 +62684,7 @@ module.exports = QuadraticBezierInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SmoothStep = __webpack_require__(155); +var SmoothStep = __webpack_require__(158); /** * A Smooth Step interpolation method. @@ -64594,7 +62708,7 @@ module.exports = SmoothStepInterpolation; /***/ }), -/* 323 */ +/* 324 */ /***/ (function(module, exports) { /** @@ -64624,7 +62738,7 @@ module.exports = GetPowerOfTwo; /***/ }), -/* 324 */ +/* 325 */ /***/ (function(module, exports) { /** @@ -64668,7 +62782,7 @@ module.exports = SnapCeil; /***/ }), -/* 325 */ +/* 326 */ /***/ (function(module, exports) { /** @@ -64697,7 +62811,7 @@ module.exports = FloatBetween; /***/ }), -/* 326 */ +/* 327 */ /***/ (function(module, exports) { /** @@ -64732,7 +62846,7 @@ module.exports = Rotate; /***/ }), -/* 327 */ +/* 328 */ /***/ (function(module, exports) { /** @@ -64761,7 +62875,7 @@ module.exports = RoundAwayFromZero; /***/ }), -/* 328 */ +/* 329 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -64816,7 +62930,7 @@ module.exports = TransformXY; /***/ }), -/* 329 */ +/* 330 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -65361,7 +63475,7 @@ module.exports = Vector4; /***/ }), -/* 330 */ +/* 331 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -65874,12 +63988,12 @@ var Matrix3 = new Class({ }, /** - * Set the values of this Matrix3 to be normalized from the given Matrix4. + * [description] * * @method Phaser.Math.Matrix3#normalFromMat4 * @since 3.0.0 * - * @param {Phaser.Math.Matrix4} m - The Matrix4 to normalize the values from. + * @param {Phaser.Math.Matrix4} m - [description] * * @return {Phaser.Math.Matrix3} This Matrix3. */ @@ -65954,7 +64068,7 @@ module.exports = Matrix3; /***/ }), -/* 331 */ +/* 332 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -66518,12 +64632,12 @@ var Matrix4 = new Class({ }, /** - * Multiply the values of this Matrix4 by those given in the `src` argument. + * [description] * * @method Phaser.Math.Matrix4#multiplyLocal * @since 3.0.0 * - * @param {Phaser.Math.Matrix4} src - The source Matrix4 that this Matrix4 is multiplied by. + * @param {Phaser.Math.Matrix4} src - [description] * * @return {Phaser.Math.Matrix4} This Matrix4. */ @@ -67315,9 +65429,9 @@ var Matrix4 = new Class({ * @method Phaser.Math.Matrix4#yawPitchRoll * @since 3.0.0 * - * @param {number} yaw - The yaw value. - * @param {number} pitch - The pitch value. - * @param {number} roll - The roll value. + * @param {number} yaw - [description] + * @param {number} pitch - [description] + * @param {number} roll - [description] * * @return {Phaser.Math.Matrix4} This Matrix4. */ @@ -67416,7 +65530,7 @@ module.exports = Matrix4; /***/ }), -/* 332 */ +/* 333 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -67429,8 +65543,8 @@ module.exports = Matrix4; // and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl var Class = __webpack_require__(0); -var Vector3 = __webpack_require__(169); -var Matrix3 = __webpack_require__(330); +var Vector3 = __webpack_require__(172); +var Matrix3 = __webpack_require__(331); var EPSILON = 0.000001; @@ -67738,13 +65852,13 @@ var Quaternion = new Class({ }, /** - * Rotates this Quaternion based on the two given vectors. + * [description] * * @method Phaser.Math.Quaternion#rotationTo * @since 3.0.0 * - * @param {Phaser.Math.Vector3} a - The transform rotation vector. - * @param {Phaser.Math.Vector3} b - The target rotation vector. + * @param {Phaser.Math.Vector3} a - [description] + * @param {Phaser.Math.Vector3} b - [description] * * @return {Phaser.Math.Quaternion} This Quaternion. */ @@ -68188,7 +66302,7 @@ module.exports = Quaternion; /***/ }), -/* 333 */ +/* 334 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -68197,10 +66311,10 @@ module.exports = Quaternion; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasInterpolation = __webpack_require__(334); -var CanvasPool = __webpack_require__(27); -var CONST = __webpack_require__(10); -var Features = __webpack_require__(164); +var CanvasInterpolation = __webpack_require__(335); +var CanvasPool = __webpack_require__(26); +var CONST = __webpack_require__(29); +var Features = __webpack_require__(167); /** * Called automatically by Phaser.Game and responsible for creating the renderer it will use. @@ -68290,8 +66404,8 @@ var CreateRenderer = function (game) if (true) { - CanvasRenderer = __webpack_require__(500); - WebGLRenderer = __webpack_require__(503); + CanvasRenderer = __webpack_require__(499); + WebGLRenderer = __webpack_require__(502); // Let the config pick the renderer type, as both are included if (config.renderType === CONST.WEBGL) @@ -68316,7 +66430,7 @@ module.exports = CreateRenderer; /***/ }), -/* 334 */ +/* 335 */ /***/ (function(module, exports) { /** @@ -68378,87 +66492,8 @@ var CanvasInterpolation = { module.exports = CanvasInterpolation; -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - -module.exports = [ - '#define SHADER_NAME PHASER_TEXTURE_TINT_FS', - '', - 'precision mediump float;', - '', - 'uniform sampler2D uMainSampler;', - '', - 'varying vec2 outTexCoord;', - 'varying float outTintEffect;', - 'varying vec4 outTint;', - '', - 'void main()', - '{', - ' vec4 texture = texture2D(uMainSampler, outTexCoord);', - ' vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);', - ' vec4 color = texture;', - '', - ' if (outTintEffect == 0.0)', - ' {', - ' // Multiply texture tint', - ' color = texture * texel;', - ' }', - ' else if (outTintEffect == 1.0)', - ' {', - ' // Solid color + texture alpha', - ' color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);', - ' color.a = texture.a * texel.a;', - ' }', - ' else if (outTintEffect == 2.0)', - ' {', - ' // Solid color, no texture', - ' color = texel;', - ' }', - '', - ' gl_FragColor = color;', - '}', - '' -].join('\n'); - - /***/ }), /* 336 */ -/***/ (function(module, exports) { - -module.exports = [ - '#define SHADER_NAME PHASER_TEXTURE_TINT_VS', - '', - 'precision mediump float;', - '', - 'uniform mat4 uProjectionMatrix;', - 'uniform mat4 uViewMatrix;', - 'uniform mat4 uModelMatrix;', - '', - 'attribute vec2 inPosition;', - 'attribute vec2 inTexCoord;', - 'attribute float inTintEffect;', - 'attribute vec4 inTint;', - '', - 'varying vec2 outTexCoord;', - 'varying float outTintEffect;', - 'varying vec4 outTint;', - '', - 'void main ()', - '{', - ' gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);', - '', - ' outTexCoord = inTexCoord;', - ' outTint = inTint;', - ' outTintEffect = inTintEffect;', - '}', - '', - '' -].join('\n'); - - -/***/ }), -/* 337 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -68467,7 +66502,7 @@ module.exports = [ * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); +var CONST = __webpack_require__(29); /** * Called automatically by Phaser.Game and responsible for creating the console.log debug header. @@ -68588,7 +66623,7 @@ module.exports = DebugHeader; /***/ }), -/* 338 */ +/* 337 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -68600,7 +66635,7 @@ module.exports = DebugHeader; var Class = __webpack_require__(0); var GetValue = __webpack_require__(6); var NOOP = __webpack_require__(1); -var RequestAnimationFrame = __webpack_require__(339); +var RequestAnimationFrame = __webpack_require__(338); // http://www.testufo.com/#test=animation-time-graph @@ -69318,7 +67353,7 @@ module.exports = TimeStep; /***/ }), -/* 339 */ +/* 338 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -69532,7 +67567,7 @@ module.exports = RequestAnimationFrame; /***/ }), -/* 340 */ +/* 339 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -69541,7 +67576,7 @@ module.exports = RequestAnimationFrame; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Events = __webpack_require__(19); +var Events = __webpack_require__(18); /** * The Visibility Handler is responsible for listening out for document level visibility change events. @@ -69623,7 +67658,7 @@ module.exports = VisibilityHandler; /***/ }), -/* 341 */ +/* 340 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -69632,47 +67667,19 @@ module.exports = VisibilityHandler; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Arne16 = __webpack_require__(342); -var CanvasPool = __webpack_require__(27); +var Arne16 = __webpack_require__(341); +var CanvasPool = __webpack_require__(26); var GetValue = __webpack_require__(6); /** - * Generates a texture based on the given Create configuration object. - * - * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the - * data cells map to a single color. For example, if the texture config looked like this: - * - * ```javascript - * var star = [ - * '.....828.....', - * '....72227....', - * '....82228....', - * '...7222227...', - * '2222222222222', - * '8222222222228', - * '.72222222227.', - * '..787777787..', - * '..877777778..', - * '.78778887787.', - * '.27887.78872.', - * '.787.....787.' - * ]; - * - * this.textures.generate('star', { data: star, pixelWidth: 4 }); - * ``` - * - * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array - * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color - * number 8 in the palette. If a cell contains a period character `.` then it is transparent. - * - * The default palette is Arne16, but you can specify your own using the `palette` property. + * [description] * * @function Phaser.Create.GenerateTexture * @since 3.0.0 * - * @param {Phaser.Types.Create.GenerateTextureConfig} config - The Generate Texture Configuration object. + * @param {Phaser.Types.Create.GenerateTextureConfig} config - [description] * - * @return {HTMLCanvasElement} An HTMLCanvasElement which contains the generated texture drawn to it. + * @return {HTMLCanvasElement} [description] */ var GenerateTexture = function (config) { @@ -69745,7 +67752,7 @@ module.exports = GenerateTexture; /***/ }), -/* 342 */ +/* 341 */ /***/ (function(module, exports) { /** @@ -69783,7 +67790,7 @@ module.exports = { /***/ }), -/* 343 */ +/* 342 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -69795,8 +67802,8 @@ module.exports = { // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var CubicBezier = __webpack_require__(320); -var Curve = __webpack_require__(79); +var CubicBezier = __webpack_require__(321); +var Curve = __webpack_require__(80); var Vector2 = __webpack_require__(3); /** @@ -70010,7 +68017,7 @@ module.exports = CubicBezierCurve; /***/ }), -/* 344 */ +/* 343 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -70022,10 +68029,10 @@ module.exports = CubicBezierCurve; // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); +var Curve = __webpack_require__(80); var DegToRad = __webpack_require__(35); var GetValue = __webpack_require__(6); -var RadToDeg = __webpack_require__(168); +var RadToDeg = __webpack_require__(171); var Vector2 = __webpack_require__(3); /** @@ -70634,7 +68641,7 @@ module.exports = EllipseCurve; /***/ }), -/* 345 */ +/* 344 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -70646,9 +68653,9 @@ module.exports = EllipseCurve; // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); -var FromPoints = __webpack_require__(171); -var Rectangle = __webpack_require__(13); +var Curve = __webpack_require__(80); +var FromPoints = __webpack_require__(174); +var Rectangle = __webpack_require__(11); var Vector2 = __webpack_require__(3); var tmpVec2 = new Vector2(); @@ -70939,7 +68946,7 @@ module.exports = LineCurve; /***/ }), -/* 346 */ +/* 345 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -70949,8 +68956,8 @@ module.exports = LineCurve; */ var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); -var QuadraticBezierInterpolation = __webpack_require__(321); +var Curve = __webpack_require__(80); +var QuadraticBezierInterpolation = __webpack_require__(322); var Vector2 = __webpack_require__(3); /** @@ -71153,7 +69160,7 @@ module.exports = QuadraticBezier; /***/ }), -/* 347 */ +/* 346 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71164,9 +69171,9 @@ module.exports = QuadraticBezier; // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) -var CatmullRom = __webpack_require__(166); +var CatmullRom = __webpack_require__(169); var Class = __webpack_require__(0); -var Curve = __webpack_require__(79); +var Curve = __webpack_require__(80); var Vector2 = __webpack_require__(3); /** @@ -71378,7 +69385,7 @@ module.exports = SplineCurve; /***/ }), -/* 348 */ +/* 347 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71502,7 +69509,7 @@ module.exports = BaseShader; /***/ }), -/* 349 */ +/* 348 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71511,32 +69518,32 @@ module.exports = BaseShader; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); +var Color = __webpack_require__(33); -Color.ColorToRGBA = __webpack_require__(800); -Color.ComponentToHex = __webpack_require__(350); -Color.GetColor = __webpack_require__(159); -Color.GetColor32 = __webpack_require__(290); -Color.HexStringToColor = __webpack_require__(289); -Color.HSLToColor = __webpack_require__(801); -Color.HSVColorWheel = __webpack_require__(802); -Color.HSVToRGB = __webpack_require__(160); -Color.HueToComponent = __webpack_require__(351); -Color.IntegerToColor = __webpack_require__(292); -Color.IntegerToRGB = __webpack_require__(293); -Color.Interpolate = __webpack_require__(803); -Color.ObjectToColor = __webpack_require__(294); -Color.RandomRGB = __webpack_require__(804); -Color.RGBStringToColor = __webpack_require__(295); -Color.RGBToHSV = __webpack_require__(291); -Color.RGBToString = __webpack_require__(805); -Color.ValueToColor = __webpack_require__(158); +Color.ColorToRGBA = __webpack_require__(802); +Color.ComponentToHex = __webpack_require__(349); +Color.GetColor = __webpack_require__(162); +Color.GetColor32 = __webpack_require__(292); +Color.HexStringToColor = __webpack_require__(291); +Color.HSLToColor = __webpack_require__(803); +Color.HSVColorWheel = __webpack_require__(804); +Color.HSVToRGB = __webpack_require__(163); +Color.HueToComponent = __webpack_require__(350); +Color.IntegerToColor = __webpack_require__(294); +Color.IntegerToRGB = __webpack_require__(295); +Color.Interpolate = __webpack_require__(805); +Color.ObjectToColor = __webpack_require__(296); +Color.RandomRGB = __webpack_require__(806); +Color.RGBStringToColor = __webpack_require__(297); +Color.RGBToHSV = __webpack_require__(293); +Color.RGBToString = __webpack_require__(807); +Color.ValueToColor = __webpack_require__(161); module.exports = Color; /***/ }), -/* 350 */ +/* 349 */ /***/ (function(module, exports) { /** @@ -71566,7 +69573,7 @@ module.exports = ComponentToHex; /***/ }), -/* 351 */ +/* 350 */ /***/ (function(module, exports) { /** @@ -71622,7 +69629,7 @@ module.exports = HueToComponent; /***/ }), -/* 352 */ +/* 351 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71631,7 +69638,7 @@ module.exports = HueToComponent; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var OS = __webpack_require__(112); +var OS = __webpack_require__(116); /** * @callback ContentLoadedCallback @@ -71685,7 +69692,7 @@ module.exports = DOMContentLoaded; /***/ }), -/* 353 */ +/* 352 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71694,7 +69701,7 @@ module.exports = DOMContentLoaded; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(172); +var CONST = __webpack_require__(175); /** * Attempts to determine the screen orientation using the Orientation API. @@ -71751,7 +69758,7 @@ module.exports = GetScreenOrientation; /***/ }), -/* 354 */ +/* 353 */ /***/ (function(module, exports) { /** @@ -71837,7 +69844,7 @@ module.exports = { /***/ }), -/* 355 */ +/* 354 */ /***/ (function(module, exports) { /** @@ -71890,7 +69897,7 @@ module.exports = { /***/ }), -/* 356 */ +/* 355 */ /***/ (function(module, exports) { /** @@ -71988,7 +69995,7 @@ module.exports = { /***/ }), -/* 357 */ +/* 356 */ /***/ (function(module, exports) { /** @@ -72062,7 +70069,7 @@ module.exports = { /***/ }), -/* 358 */ +/* 357 */ /***/ (function(module, exports) { /** @@ -72113,7 +70120,7 @@ module.exports = GetTarget; /***/ }), -/* 359 */ +/* 358 */ /***/ (function(module, exports) { /** @@ -72170,7 +70177,7 @@ module.exports = ParseXML; /***/ }), -/* 360 */ +/* 359 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -72180,16 +70187,16 @@ module.exports = ParseXML; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(174); -var EventEmitter = __webpack_require__(11); +var CONST = __webpack_require__(177); +var EventEmitter = __webpack_require__(9); var Events = __webpack_require__(54); -var GameEvents = __webpack_require__(19); -var Keyboard = __webpack_require__(361); -var Mouse = __webpack_require__(362); -var Pointer = __webpack_require__(363); -var Touch = __webpack_require__(364); -var TransformMatrix = __webpack_require__(30); -var TransformXY = __webpack_require__(328); +var GameEvents = __webpack_require__(18); +var Keyboard = __webpack_require__(360); +var Mouse = __webpack_require__(361); +var Pointer = __webpack_require__(362); +var Touch = __webpack_require__(363); +var TransformMatrix = __webpack_require__(32); +var TransformXY = __webpack_require__(329); /** * @classdesc @@ -73252,7 +71259,7 @@ module.exports = InputManager; /***/ }), -/* 361 */ +/* 360 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -73261,11 +71268,11 @@ module.exports = InputManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayRemove = __webpack_require__(117); +var ArrayRemove = __webpack_require__(121); var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var InputEvents = __webpack_require__(54); -var KeyCodes = __webpack_require__(118); +var KeyCodes = __webpack_require__(122); var NOOP = __webpack_require__(0); /** @@ -73702,7 +71709,7 @@ module.exports = KeyboardManager; /***/ }), -/* 362 */ +/* 361 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -73712,7 +71719,7 @@ module.exports = KeyboardManager; */ var Class = __webpack_require__(0); -var Features = __webpack_require__(164); +var Features = __webpack_require__(167); var InputEvents = __webpack_require__(54); var NOOP = __webpack_require__(0); @@ -74188,7 +72195,7 @@ module.exports = MouseManager; /***/ }), -/* 363 */ +/* 362 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -74197,11 +72204,11 @@ module.exports = MouseManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Angle = __webpack_require__(312); +var Angle = __webpack_require__(314); var Class = __webpack_require__(0); var Distance = __webpack_require__(53); -var FuzzyEqual = __webpack_require__(140); -var SmoothStepInterpolation = __webpack_require__(322); +var FuzzyEqual = __webpack_require__(144); +var SmoothStepInterpolation = __webpack_require__(323); var Vector2 = __webpack_require__(3); /** @@ -75466,7 +73473,7 @@ module.exports = Pointer; /***/ }), -/* 364 */ +/* 363 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -75879,7 +73886,7 @@ module.exports = TouchManager; /***/ }), -/* 365 */ +/* 364 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -75889,14 +73896,14 @@ module.exports = TouchManager; */ var Class = __webpack_require__(0); -var GameEvents = __webpack_require__(19); -var EventEmitter = __webpack_require__(11); +var GameEvents = __webpack_require__(18); +var EventEmitter = __webpack_require__(9); var FileTypesManager = __webpack_require__(8); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GameObjectFactory = __webpack_require__(5); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); -var Remove = __webpack_require__(117); +var PluginCache = __webpack_require__(23); +var Remove = __webpack_require__(121); /** * @classdesc @@ -76781,7 +74788,7 @@ module.exports = PluginManager; /***/ }), -/* 366 */ +/* 365 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -76790,18 +74797,18 @@ module.exports = PluginManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(172); +var CONST = __webpack_require__(175); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(90); -var GameEvents = __webpack_require__(19); -var GetInnerHeight = __webpack_require__(858); -var GetTarget = __webpack_require__(358); -var GetScreenOrientation = __webpack_require__(353); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(92); +var GameEvents = __webpack_require__(18); +var GetInnerHeight = __webpack_require__(860); +var GetTarget = __webpack_require__(357); +var GetScreenOrientation = __webpack_require__(352); var NOOP = __webpack_require__(1); -var Rectangle = __webpack_require__(13); -var Size = __webpack_require__(367); -var SnapFloor = __webpack_require__(91); +var Rectangle = __webpack_require__(11); +var Size = __webpack_require__(366); +var SnapFloor = __webpack_require__(93); var Vector2 = __webpack_require__(3); /** @@ -78498,7 +76505,7 @@ module.exports = ScaleManager; /***/ }), -/* 367 */ +/* 366 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -78507,9 +76514,9 @@ module.exports = ScaleManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var SnapFloor = __webpack_require__(91); +var SnapFloor = __webpack_require__(93); var Vector2 = __webpack_require__(3); /** @@ -79276,7 +77283,7 @@ module.exports = Size; /***/ }), -/* 368 */ +/* 367 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -79286,14 +77293,14 @@ module.exports = Size; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(119); -var Events = __webpack_require__(22); -var GameEvents = __webpack_require__(19); +var CONST = __webpack_require__(123); +var Events = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var GetValue = __webpack_require__(6); -var LoaderEvents = __webpack_require__(80); +var LoaderEvents = __webpack_require__(81); var NOOP = __webpack_require__(1); -var Scene = __webpack_require__(369); -var Systems = __webpack_require__(175); +var Scene = __webpack_require__(368); +var Systems = __webpack_require__(178); /** * @classdesc @@ -80916,7 +78923,7 @@ module.exports = SceneManager; /***/ }), -/* 369 */ +/* 368 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -80926,7 +78933,7 @@ module.exports = SceneManager; */ var Class = __webpack_require__(0); -var Systems = __webpack_require__(175); +var Systems = __webpack_require__(178); /** * @classdesc @@ -81146,6 +79153,16 @@ var Scene = new Class({ */ this.physics; + /** + * A scene level Impact Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#impact + * @type {Phaser.Physics.Impact.ImpactPhysics} + * @since 3.0.0 + */ + this.impact; + /** * A scene level Matter Physics Plugin. * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. @@ -81202,7 +79219,7 @@ module.exports = Scene; /***/ }), -/* 370 */ +/* 369 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -81211,10 +79228,10 @@ module.exports = Scene; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(119); +var CONST = __webpack_require__(123); var GetValue = __webpack_require__(6); -var Merge = __webpack_require__(120); -var InjectionMap = __webpack_require__(871); +var Merge = __webpack_require__(107); +var InjectionMap = __webpack_require__(873); /** * @namespace Phaser.Scenes.Settings @@ -81298,7 +79315,7 @@ module.exports = Settings; /***/ }), -/* 371 */ +/* 370 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -81307,18 +79324,18 @@ module.exports = Settings; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); -var CanvasTexture = __webpack_require__(372); +var CanvasPool = __webpack_require__(26); +var CanvasTexture = __webpack_require__(371); var Class = __webpack_require__(0); -var Color = __webpack_require__(32); -var CONST = __webpack_require__(10); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(115); -var GameEvents = __webpack_require__(19); -var GenerateTexture = __webpack_require__(341); +var Color = __webpack_require__(33); +var CONST = __webpack_require__(29); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(119); +var GameEvents = __webpack_require__(18); +var GenerateTexture = __webpack_require__(340); var GetValue = __webpack_require__(6); -var Parser = __webpack_require__(374); -var Texture = __webpack_require__(177); +var Parser = __webpack_require__(373); +var Texture = __webpack_require__(180); /** * @callback EachTextureCallback @@ -81602,8 +79619,8 @@ var TextureManager = new Class({ * * @param {string} key - The unique string-based key of the Texture. * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. - * @param {string} [type='image/png'] - A DOMString indicating the image format. The default format type is image/png. - * @param {number} [encoderOptions=0.92] - A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored. + * @param {string} [type='image/png'] - [description] + * @param {number} [encoderOptions=0.92] - [description] * * @return {string} The base64 encoded data, or an empty string if the texture frame could not be found. */ @@ -81746,44 +79763,14 @@ var TextureManager = new Class({ /** * Creates a new Texture using the given config values. - * * Generated textures consist of a Canvas element to which the texture data is drawn. - * - * Generates a texture based on the given Create configuration object. - * - * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the - * data cells map to a single color. For example, if the texture config looked like this: - * - * ```javascript - * var star = [ - * '.....828.....', - * '....72227....', - * '....82228....', - * '...7222227...', - * '2222222222222', - * '8222222222228', - * '.72222222227.', - * '..787777787..', - * '..877777778..', - * '.78778887787.', - * '.27887.78872.', - * '.787.....787.' - * ]; - * - * this.textures.generate('star', { data: star, pixelWidth: 4 }); - * ``` - * - * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array - * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color - * number 8 in the palette. If a cell contains a period character `.` then it is transparent. - * - * The default palette is Arne16, but you can specify your own using the `palette` property. + * See the Phaser.Create function for the more direct way to create textures. * * @method Phaser.Textures.TextureManager#generate * @since 3.0.0 * * @param {string} key - The unique string-based key of the Texture. - * @param {Phaser.Types.Create.GenerateTextureConfig} config - The configuration object needed to generate the texture. + * @param {object} config - The configuration object needed to generate the texture. * * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. */ @@ -82500,7 +80487,7 @@ module.exports = TextureManager; /***/ }), -/* 372 */ +/* 371 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -82510,11 +80497,11 @@ module.exports = TextureManager; */ var Class = __webpack_require__(0); -var Clamp = __webpack_require__(23); -var Color = __webpack_require__(32); -var CONST = __webpack_require__(10); -var IsSizePowerOfTwo = __webpack_require__(114); -var Texture = __webpack_require__(177); +var Clamp = __webpack_require__(22); +var Color = __webpack_require__(33); +var CONST = __webpack_require__(29); +var IsSizePowerOfTwo = __webpack_require__(118); +var Texture = __webpack_require__(180); /** * @classdesc @@ -83131,7 +81118,7 @@ module.exports = CanvasTexture; /***/ }), -/* 373 */ +/* 372 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83140,10 +81127,10 @@ module.exports = CanvasTexture; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); -var IsSizePowerOfTwo = __webpack_require__(114); -var ScaleModes = __webpack_require__(229); +var IsSizePowerOfTwo = __webpack_require__(118); +var ScaleModes = __webpack_require__(231); /** * @classdesc @@ -83472,7 +81459,7 @@ module.exports = TextureSource; /***/ }), -/* 374 */ +/* 373 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83487,20 +81474,20 @@ module.exports = TextureSource; module.exports = { - AtlasXML: __webpack_require__(872), - Canvas: __webpack_require__(873), - Image: __webpack_require__(874), - JSONArray: __webpack_require__(875), - JSONHash: __webpack_require__(876), - SpriteSheet: __webpack_require__(877), - SpriteSheetFromAtlas: __webpack_require__(878), - UnityYAML: __webpack_require__(879) + AtlasXML: __webpack_require__(874), + Canvas: __webpack_require__(875), + Image: __webpack_require__(876), + JSONArray: __webpack_require__(877), + JSONHash: __webpack_require__(878), + SpriteSheet: __webpack_require__(879), + SpriteSheetFromAtlas: __webpack_require__(880), + UnityYAML: __webpack_require__(881) }; /***/ }), -/* 375 */ +/* 374 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83510,9 +81497,9 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HTML5AudioSoundManager = __webpack_require__(376); -var NoAudioSoundManager = __webpack_require__(378); -var WebAudioSoundManager = __webpack_require__(380); +var HTML5AudioSoundManager = __webpack_require__(375); +var NoAudioSoundManager = __webpack_require__(377); +var WebAudioSoundManager = __webpack_require__(379); /** * Creates a Web Audio, HTML5 Audio or No Audio Sound Manager based on config and device settings. @@ -83552,7 +81539,7 @@ module.exports = SoundManagerCreator; /***/ }), -/* 376 */ +/* 375 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -83562,10 +81549,10 @@ module.exports = SoundManagerCreator; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSoundManager = __webpack_require__(121); +var BaseSoundManager = __webpack_require__(124); var Class = __webpack_require__(0); var Events = __webpack_require__(59); -var HTML5AudioSound = __webpack_require__(377); +var HTML5AudioSound = __webpack_require__(376); /** * HTML5 Audio implementation of the Sound Manager. @@ -84017,7 +82004,7 @@ module.exports = HTML5AudioSoundManager; /***/ }), -/* 377 */ +/* 376 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -84027,7 +82014,7 @@ module.exports = HTML5AudioSoundManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSound = __webpack_require__(122); +var BaseSound = __webpack_require__(125); var Class = __webpack_require__(0); var Events = __webpack_require__(59); @@ -84942,7 +82929,7 @@ module.exports = HTML5AudioSound; /***/ }), -/* 378 */ +/* 377 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -84952,10 +82939,10 @@ module.exports = HTML5AudioSound; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSoundManager = __webpack_require__(121); +var BaseSoundManager = __webpack_require__(124); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var NoAudioSound = __webpack_require__(379); +var EventEmitter = __webpack_require__(9); +var NoAudioSound = __webpack_require__(378); var NOOP = __webpack_require__(1); /** @@ -85060,7 +83047,7 @@ module.exports = NoAudioSoundManager; /***/ }), -/* 379 */ +/* 378 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -85070,10 +83057,10 @@ module.exports = NoAudioSoundManager; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSound = __webpack_require__(122); +var BaseSound = __webpack_require__(125); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Extend = __webpack_require__(18); +var EventEmitter = __webpack_require__(9); +var Extend = __webpack_require__(17); /** * @classdesc @@ -85187,7 +83174,7 @@ module.exports = NoAudioSound; /***/ }), -/* 380 */ +/* 379 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -85197,11 +83184,11 @@ module.exports = NoAudioSound; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Base64ToArrayBuffer = __webpack_require__(381); -var BaseSoundManager = __webpack_require__(121); +var Base64ToArrayBuffer = __webpack_require__(380); +var BaseSoundManager = __webpack_require__(124); var Class = __webpack_require__(0); var Events = __webpack_require__(59); -var WebAudioSound = __webpack_require__(382); +var WebAudioSound = __webpack_require__(381); /** * @classdesc @@ -85646,7 +83633,7 @@ module.exports = WebAudioSoundManager; /***/ }), -/* 381 */ +/* 380 */ /***/ (function(module, exports) { /** @@ -85721,7 +83708,7 @@ module.exports = Base64ToArrayBuffer; /***/ }), -/* 382 */ +/* 381 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -85731,7 +83718,7 @@ module.exports = Base64ToArrayBuffer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseSound = __webpack_require__(122); +var BaseSound = __webpack_require__(125); var Class = __webpack_require__(0); var Events = __webpack_require__(59); @@ -86627,7 +84614,7 @@ module.exports = WebAudioSound; /***/ }), -/* 383 */ +/* 382 */ /***/ (function(module, exports) { /** @@ -86675,7 +84662,7 @@ module.exports = TransposeMatrix; /***/ }), -/* 384 */ +/* 383 */ /***/ (function(module, exports) { /** @@ -86797,7 +84784,7 @@ module.exports = QuickSelect; /***/ }), -/* 385 */ +/* 384 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -86807,7 +84794,7 @@ module.exports = QuickSelect; */ var GetValue = __webpack_require__(6); -var Shuffle = __webpack_require__(110); +var Shuffle = __webpack_require__(114); var BuildChunk = function (a, b, qty) { @@ -86935,7 +84922,7 @@ module.exports = Range; /***/ }), -/* 386 */ +/* 385 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87024,7 +85011,7 @@ module.exports = BuildGameObjectAnimation; /***/ }), -/* 387 */ +/* 386 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87033,7 +85020,7 @@ module.exports = BuildGameObjectAnimation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. @@ -87066,7 +85053,7 @@ module.exports = Union; /***/ }), -/* 388 */ +/* 387 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -87077,12 +85064,12 @@ module.exports = Union; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var DOMElementRender = __webpack_require__(948); +var DOMElementRender = __webpack_require__(950); var GameObject = __webpack_require__(14); var IsPlainObject = __webpack_require__(7); -var RemoveFromDOM = __webpack_require__(173); -var SCENE_EVENTS = __webpack_require__(22); -var Vector4 = __webpack_require__(329); +var RemoveFromDOM = __webpack_require__(176); +var SCENE_EVENTS = __webpack_require__(19); +var Vector4 = __webpack_require__(330); /** * @classdesc @@ -88040,7 +86027,7 @@ module.exports = DOMElement; /***/ }), -/* 389 */ +/* 388 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88049,7 +86036,7 @@ module.exports = DOMElement; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CSSBlendModes = __webpack_require__(949); +var CSSBlendModes = __webpack_require__(951); var GameObject = __webpack_require__(14); /** @@ -88162,7 +86149,7 @@ module.exports = DOMElementCSSRenderer; /***/ }), -/* 390 */ +/* 389 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88174,7 +86161,7 @@ module.exports = DOMElementCSSRenderer; var Class = __webpack_require__(0); var Components = __webpack_require__(12); var GameObject = __webpack_require__(14); -var ExternRender = __webpack_require__(953); +var ExternRender = __webpack_require__(955); /** * @classdesc @@ -88258,7 +86245,7 @@ module.exports = Extern; /***/ }), -/* 391 */ +/* 390 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88267,9 +86254,9 @@ module.exports = Extern; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CircumferencePoint = __webpack_require__(188); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var CircumferencePoint = __webpack_require__(191); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); var Point = __webpack_require__(4); /** @@ -88301,7 +86288,7 @@ module.exports = GetPoint; /***/ }), -/* 392 */ +/* 391 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88310,10 +86297,10 @@ module.exports = GetPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circumference = __webpack_require__(393); -var CircumferencePoint = __webpack_require__(188); -var FromPercent = __webpack_require__(85); -var MATH_CONST = __webpack_require__(16); +var Circumference = __webpack_require__(392); +var CircumferencePoint = __webpack_require__(191); +var FromPercent = __webpack_require__(87); +var MATH_CONST = __webpack_require__(13); /** * Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse, @@ -88355,7 +86342,7 @@ module.exports = GetPoints; /***/ }), -/* 393 */ +/* 392 */ /***/ (function(module, exports) { /** @@ -88387,7 +86374,7 @@ module.exports = Circumference; /***/ }), -/* 394 */ +/* 393 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88396,8 +86383,8 @@ module.exports = Circumference; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Commands = __webpack_require__(187); -var SetTransform = __webpack_require__(29); +var Commands = __webpack_require__(190); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -88637,7 +86624,7 @@ module.exports = GraphicsCanvasRenderer; /***/ }), -/* 395 */ +/* 394 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -88856,7 +86843,7 @@ module.exports = GravityWell; /***/ }), -/* 396 */ +/* 395 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89425,7 +87412,7 @@ module.exports = Particle; /***/ }), -/* 397 */ +/* 396 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -89437,17 +87424,17 @@ module.exports = Particle; var BlendModes = __webpack_require__(52); var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var DeathZone = __webpack_require__(398); -var EdgeZone = __webpack_require__(399); -var EmitterOp = __webpack_require__(965); +var DeathZone = __webpack_require__(397); +var EdgeZone = __webpack_require__(398); +var EmitterOp = __webpack_require__(967); var GetFastValue = __webpack_require__(2); -var GetRandom = __webpack_require__(180); -var HasAny = __webpack_require__(400); -var HasValue = __webpack_require__(104); -var Particle = __webpack_require__(396); -var RandomZone = __webpack_require__(401); -var Rectangle = __webpack_require__(13); -var StableSort = __webpack_require__(125); +var GetRandom = __webpack_require__(183); +var HasAny = __webpack_require__(399); +var HasValue = __webpack_require__(99); +var Particle = __webpack_require__(395); +var RandomZone = __webpack_require__(400); +var Rectangle = __webpack_require__(11); +var StableSort = __webpack_require__(128); var Vector2 = __webpack_require__(3); var Wrap = __webpack_require__(58); @@ -90200,7 +88187,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ fromJSON: function (config) { @@ -90357,7 +88344,7 @@ var ParticleEmitter = new Class({ * @param {number} [offsetY=0] - Vertical offset of the particle origin from the Game Object. * @param {boolean} [trackVisible=false] - Whether the emitter's visible state will track the target's visible state. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ startFollow: function (target, offsetX, offsetY, trackVisible) { @@ -90378,7 +88365,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#stopFollow * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ stopFollow: function () { @@ -90439,7 +88426,7 @@ var ParticleEmitter = new Class({ * @param {boolean} [pickRandom=true] - Whether frames should be assigned at random from `frames`. * @param {integer} [quantity=1] - The number of consecutive particles that will receive each frame. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setFrame: function (frames, pickRandom, quantity) { @@ -90494,7 +88481,7 @@ var ParticleEmitter = new Class({ * * @param {boolean} [value=true] - Radial mode (true) or point mode (true). * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setRadial: function (value) { @@ -90515,7 +88502,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} x - The x-coordinate of the particle origin. * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} y - The y-coordinate of the particle origin. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setPosition: function (x, y) { @@ -90538,7 +88525,7 @@ var ParticleEmitter = new Class({ * @param {number} width - The width of the boundary. * @param {number} height - The height of the boundary. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setBounds: function (x, y, width, height) { @@ -90573,7 +88560,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setSpeedX: function (value) { @@ -90594,7 +88581,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setSpeedY: function (value) { @@ -90618,7 +88605,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setSpeed: function (value) { @@ -90639,7 +88626,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setScaleX: function (value) { @@ -90656,7 +88643,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setScaleY: function (value) { @@ -90673,7 +88660,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setScale: function (value) { @@ -90691,7 +88678,7 @@ var ParticleEmitter = new Class({ * * @param {number} value - Acceleration due to gravity, in pixels per second squared. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setGravityX: function (value) { @@ -90708,7 +88695,7 @@ var ParticleEmitter = new Class({ * * @param {number} value - Acceleration due to gravity, in pixels per second squared. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setGravityY: function (value) { @@ -90726,7 +88713,7 @@ var ParticleEmitter = new Class({ * @param {number} x - Horizontal acceleration due to gravity, in pixels per second squared. * @param {number} y - Vertical acceleration due to gravity, in pixels per second squared. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setGravity: function (x, y) { @@ -90744,7 +88731,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 (transparent) and 1 (opaque). * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setAlpha: function (value) { @@ -90761,7 +88748,7 @@ var ParticleEmitter = new Class({ * * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 and 0xffffff. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setTint: function (value) { @@ -90778,7 +88765,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setEmitterAngle: function (value) { @@ -90795,7 +88782,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setAngle: function (value) { @@ -90812,7 +88799,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The particle lifespan, in ms. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setLifespan: function (value) { @@ -90829,7 +88816,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} quantity - The number of particles to release at each flow cycle or explosion. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setQuantity: function (quantity) { @@ -90848,7 +88835,7 @@ var ParticleEmitter = new Class({ * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [quantity] - The number of particles to release at each flow cycle or explosion. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setFrequency: function (frequency, quantity) { @@ -90876,7 +88863,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current emit zone. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setEmitZone: function (zoneConfig) { @@ -90925,7 +88912,7 @@ var ParticleEmitter = new Class({ * * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current death zone. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ setDeathZone: function (zoneConfig) { @@ -90961,7 +88948,7 @@ var ParticleEmitter = new Class({ * * @param {integer} particleCount - The number of particles to create. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ reserve: function (particleCount) { @@ -91036,7 +89023,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. * @param {*} [context] - The calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ onParticleEmit: function (callback, context) { @@ -91068,7 +89055,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleDeathCallback} callback - The function. * @param {*} [context] - The function's calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ onParticleDeath: function (callback, context) { @@ -91097,7 +89084,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#killAll * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ killAll: function () { @@ -91121,7 +89108,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. * @param {*} context - The function's calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ forEachAlive: function (callback, context) { @@ -91146,7 +89133,7 @@ var ParticleEmitter = new Class({ * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. * @param {*} context - The function's calling context. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ forEachDead: function (callback, context) { @@ -91173,7 +89160,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#start * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ start: function () { @@ -91190,7 +89177,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#stop * @since 3.11.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ stop: function () { @@ -91205,7 +89192,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#pause * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ pause: function () { @@ -91220,7 +89207,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#resume * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ resume: function () { @@ -91235,7 +89222,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#remove * @since 3.22.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ remove: function () { @@ -91250,7 +89237,7 @@ var ParticleEmitter = new Class({ * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSort * @since 3.0.0 * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ depthSort: function () { @@ -91270,7 +89257,7 @@ var ParticleEmitter = new Class({ * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms. * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [count=1] - The number of particles to emit at each flow cycle. * - * @return {this} This Particle Emitter. + * @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter. */ flow: function (frequency, count) { @@ -91496,7 +89483,7 @@ module.exports = ParticleEmitter; /***/ }), -/* 398 */ +/* 397 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91574,7 +89561,7 @@ module.exports = DeathZone; /***/ }), -/* 399 */ +/* 398 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91710,7 +89697,7 @@ var EdgeZone = new Class({ * @method Phaser.GameObjects.Particles.Zones.EdgeZone#updateSource * @since 3.0.0 * - * @return {this} This Edge Zone. + * @return {Phaser.GameObjects.Particles.Zones.EdgeZone} This Edge Zone. */ updateSource: function () { @@ -91749,7 +89736,7 @@ var EdgeZone = new Class({ * * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. * - * @return {this} This Edge Zone. + * @return {Phaser.GameObjects.Particles.Zones.EdgeZone} This Edge Zone. */ changeSource: function (source) { @@ -91818,7 +89805,7 @@ module.exports = EdgeZone; /***/ }), -/* 400 */ +/* 399 */ /***/ (function(module, exports) { /** @@ -91855,7 +89842,7 @@ module.exports = HasAny; /***/ }), -/* 401 */ +/* 400 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91928,7 +89915,7 @@ module.exports = RandomZone; /***/ }), -/* 402 */ +/* 401 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -91939,7 +89926,7 @@ module.exports = RandomZone; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var Sprite = __webpack_require__(73); +var Sprite = __webpack_require__(69); /** * @classdesc @@ -92010,7 +89997,7 @@ module.exports = PathFollower; /***/ }), -/* 403 */ +/* 402 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92019,13 +90006,13 @@ module.exports = PathFollower; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcRender = __webpack_require__(991); +var ArcRender = __webpack_require__(990); var Class = __webpack_require__(0); var DegToRad = __webpack_require__(35); -var Earcut = __webpack_require__(64); -var GeomCircle = __webpack_require__(63); -var MATH_CONST = __webpack_require__(16); -var Shape = __webpack_require__(31); +var Earcut = __webpack_require__(66); +var GeomCircle = __webpack_require__(65); +var MATH_CONST = __webpack_require__(13); +var Shape = __webpack_require__(30); /** * @classdesc @@ -92419,7 +90406,7 @@ module.exports = Arc; /***/ }), -/* 404 */ +/* 403 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92429,10 +90416,10 @@ module.exports = Arc; */ var Class = __webpack_require__(0); -var CurveRender = __webpack_require__(994); -var Earcut = __webpack_require__(64); -var Rectangle = __webpack_require__(13); -var Shape = __webpack_require__(31); +var CurveRender = __webpack_require__(993); +var Earcut = __webpack_require__(66); +var Rectangle = __webpack_require__(11); +var Shape = __webpack_require__(30); /** * @classdesc @@ -92601,7 +90588,7 @@ module.exports = Curve; /***/ }), -/* 405 */ +/* 404 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92611,10 +90598,10 @@ module.exports = Curve; */ var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); -var EllipseRender = __webpack_require__(997); -var GeomEllipse = __webpack_require__(93); -var Shape = __webpack_require__(31); +var Earcut = __webpack_require__(66); +var EllipseRender = __webpack_require__(996); +var GeomEllipse = __webpack_require__(95); +var Shape = __webpack_require__(30); /** * @classdesc @@ -92788,7 +90775,7 @@ module.exports = Ellipse; /***/ }), -/* 406 */ +/* 405 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92798,8 +90785,8 @@ module.exports = Ellipse; */ var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); -var GridRender = __webpack_require__(1000); +var Shape = __webpack_require__(30); +var GridRender = __webpack_require__(999); /** * @classdesc @@ -93070,7 +91057,7 @@ module.exports = Grid; /***/ }), -/* 407 */ +/* 406 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93079,9 +91066,9 @@ module.exports = Grid; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var IsoBoxRender = __webpack_require__(1003); +var IsoBoxRender = __webpack_require__(1002); var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); +var Shape = __webpack_require__(30); /** * @classdesc @@ -93285,7 +91272,7 @@ module.exports = IsoBox; /***/ }), -/* 408 */ +/* 407 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93295,8 +91282,8 @@ module.exports = IsoBox; */ var Class = __webpack_require__(0); -var IsoTriangleRender = __webpack_require__(1006); -var Shape = __webpack_require__(31); +var IsoTriangleRender = __webpack_require__(1005); +var Shape = __webpack_require__(30); /** * @classdesc @@ -93531,7 +91518,7 @@ module.exports = IsoTriangle; /***/ }), -/* 409 */ +/* 408 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93541,9 +91528,9 @@ module.exports = IsoTriangle; */ var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); +var Shape = __webpack_require__(30); var GeomLine = __webpack_require__(56); -var LineRender = __webpack_require__(1009); +var LineRender = __webpack_require__(1008); /** * @classdesc @@ -93698,7 +91685,7 @@ module.exports = Line; /***/ }), -/* 410 */ +/* 409 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93707,13 +91694,13 @@ module.exports = Line; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PolygonRender = __webpack_require__(1012); +var PolygonRender = __webpack_require__(1011); var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); -var GetAABB = __webpack_require__(411); -var GeomPolygon = __webpack_require__(196); -var Shape = __webpack_require__(31); -var Smooth = __webpack_require__(414); +var Earcut = __webpack_require__(66); +var GetAABB = __webpack_require__(410); +var GeomPolygon = __webpack_require__(198); +var Shape = __webpack_require__(30); +var Smooth = __webpack_require__(413); /** * @classdesc @@ -93837,7 +91824,7 @@ module.exports = Polygon; /***/ }), -/* 411 */ +/* 410 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93846,7 +91833,7 @@ module.exports = Polygon; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Calculates the bounding AABB rectangle of a polygon. @@ -93893,7 +91880,7 @@ module.exports = GetAABB; /***/ }), -/* 412 */ +/* 411 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93904,7 +91891,7 @@ module.exports = GetAABB; var Length = __webpack_require__(57); var Line = __webpack_require__(56); -var Perimeter = __webpack_require__(413); +var Perimeter = __webpack_require__(412); /** * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, @@ -93970,7 +91957,7 @@ module.exports = GetPoints; /***/ }), -/* 413 */ +/* 412 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94018,7 +92005,7 @@ module.exports = Perimeter; /***/ }), -/* 414 */ +/* 413 */ /***/ (function(module, exports) { /** @@ -94094,7 +92081,7 @@ module.exports = Smooth; /***/ }), -/* 415 */ +/* 414 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94104,9 +92091,9 @@ module.exports = Smooth; */ var Class = __webpack_require__(0); -var GeomRectangle = __webpack_require__(13); -var Shape = __webpack_require__(31); -var RectangleRender = __webpack_require__(1015); +var GeomRectangle = __webpack_require__(11); +var Shape = __webpack_require__(30); +var RectangleRender = __webpack_require__(1014); /** * @classdesc @@ -94206,7 +92193,7 @@ module.exports = Rectangle; /***/ }), -/* 416 */ +/* 415 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94215,10 +92202,10 @@ module.exports = Rectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var StarRender = __webpack_require__(1018); +var StarRender = __webpack_require__(1017); var Class = __webpack_require__(0); -var Earcut = __webpack_require__(64); -var Shape = __webpack_require__(31); +var Earcut = __webpack_require__(66); +var Shape = __webpack_require__(30); /** * @classdesc @@ -94494,7 +92481,7 @@ module.exports = Star; /***/ }), -/* 417 */ +/* 416 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94504,9 +92491,9 @@ module.exports = Star; */ var Class = __webpack_require__(0); -var Shape = __webpack_require__(31); -var GeomTriangle = __webpack_require__(69); -var TriangleRender = __webpack_require__(1021); +var Shape = __webpack_require__(30); +var GeomTriangle = __webpack_require__(71); +var TriangleRender = __webpack_require__(1020); /** * @classdesc @@ -94637,7 +92624,7 @@ module.exports = Triangle; /***/ }), -/* 418 */ +/* 417 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94724,7 +92711,7 @@ module.exports = GetPoint; /***/ }), -/* 419 */ +/* 418 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94817,7 +92804,7 @@ module.exports = GetPoints; /***/ }), -/* 420 */ +/* 419 */ /***/ (function(module, exports) { /** @@ -94900,7 +92887,7 @@ module.exports = SetValue; /***/ }), -/* 421 */ +/* 420 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94910,7 +92897,7 @@ module.exports = SetValue; */ var Class = __webpack_require__(0); -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * @classdesc @@ -95040,7 +93027,7 @@ var Light = new Class({ * @param {number} b - The blue color. A value between 0 and 1. * @param {number} intensity - The intensity of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ set: function (x, y, radius, r, g, b, intensity) { @@ -95070,7 +93057,7 @@ var Light = new Class({ * @param {number} x - The horizontal scroll factor of the light. * @param {number} y - The vertical scroll factor of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setScrollFactor: function (x, y) { @@ -95091,7 +93078,7 @@ var Light = new Class({ * * @param {number} rgb - The integer RGB color of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setColor: function (rgb) { @@ -95112,7 +93099,7 @@ var Light = new Class({ * * @param {number} intensity - The intensity of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setIntensity: function (intensity) { @@ -95130,7 +93117,7 @@ var Light = new Class({ * @param {number} x - The horizontal position of the light. * @param {number} y - The vertical position of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setPosition: function (x, y) { @@ -95148,7 +93135,7 @@ var Light = new Class({ * * @param {number} radius - The radius of the light. * - * @return {this} This Light object. + * @return {Phaser.GameObjects.Light} This Light object. */ setRadius: function (radius) { @@ -95163,7 +93150,7 @@ module.exports = Light; /***/ }), -/* 422 */ +/* 421 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95173,8 +93160,8 @@ module.exports = Light; */ var Class = __webpack_require__(0); -var Light = __webpack_require__(421); -var Utils = __webpack_require__(9); +var Light = __webpack_require__(420); +var Utils = __webpack_require__(10); /** * @callback LightForEach @@ -95526,7 +93513,7 @@ module.exports = LightsManager; /***/ }), -/* 423 */ +/* 422 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95536,7 +93523,7 @@ module.exports = LightsManager; */ var CONST = __webpack_require__(46); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Geom @@ -95544,14 +93531,14 @@ var Extend = __webpack_require__(18); var Geom = { - Circle: __webpack_require__(1081), - Ellipse: __webpack_require__(1091), - Intersects: __webpack_require__(424), - Line: __webpack_require__(1110), - Point: __webpack_require__(1132), - Polygon: __webpack_require__(1146), - Rectangle: __webpack_require__(437), - Triangle: __webpack_require__(1176) + Circle: __webpack_require__(1078), + Ellipse: __webpack_require__(1088), + Intersects: __webpack_require__(423), + Line: __webpack_require__(1107), + Point: __webpack_require__(1128), + Polygon: __webpack_require__(1142), + Rectangle: __webpack_require__(436), + Triangle: __webpack_require__(1172) }; @@ -95562,7 +93549,7 @@ module.exports = Geom; /***/ }), -/* 424 */ +/* 423 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95577,35 +93564,35 @@ module.exports = Geom; module.exports = { - CircleToCircle: __webpack_require__(200), - CircleToRectangle: __webpack_require__(201), - GetCircleToCircle: __webpack_require__(1101), - GetCircleToRectangle: __webpack_require__(1102), - GetLineToCircle: __webpack_require__(202), - GetLineToRectangle: __webpack_require__(204), - GetRectangleIntersection: __webpack_require__(1103), - GetRectangleToRectangle: __webpack_require__(1104), - GetRectangleToTriangle: __webpack_require__(1105), - GetTriangleToCircle: __webpack_require__(1106), - GetTriangleToLine: __webpack_require__(429), - GetTriangleToTriangle: __webpack_require__(1107), - LineToCircle: __webpack_require__(203), - LineToLine: __webpack_require__(82), - LineToRectangle: __webpack_require__(425), - PointToLine: __webpack_require__(433), - PointToLineSegment: __webpack_require__(1108), - RectangleToRectangle: __webpack_require__(129), - RectangleToTriangle: __webpack_require__(426), - RectangleToValues: __webpack_require__(1109), - TriangleToCircle: __webpack_require__(428), - TriangleToLine: __webpack_require__(430), - TriangleToTriangle: __webpack_require__(431) + CircleToCircle: __webpack_require__(202), + CircleToRectangle: __webpack_require__(203), + GetCircleToCircle: __webpack_require__(1098), + GetCircleToRectangle: __webpack_require__(1099), + GetLineToCircle: __webpack_require__(204), + GetLineToRectangle: __webpack_require__(206), + GetRectangleIntersection: __webpack_require__(1100), + GetRectangleToRectangle: __webpack_require__(1101), + GetRectangleToTriangle: __webpack_require__(1102), + GetTriangleToCircle: __webpack_require__(1103), + GetTriangleToLine: __webpack_require__(428), + GetTriangleToTriangle: __webpack_require__(1104), + LineToCircle: __webpack_require__(205), + LineToLine: __webpack_require__(84), + LineToRectangle: __webpack_require__(424), + PointToLine: __webpack_require__(432), + PointToLineSegment: __webpack_require__(1105), + RectangleToRectangle: __webpack_require__(131), + RectangleToTriangle: __webpack_require__(425), + RectangleToValues: __webpack_require__(1106), + TriangleToCircle: __webpack_require__(427), + TriangleToLine: __webpack_require__(429), + TriangleToTriangle: __webpack_require__(430) }; /***/ }), -/* 425 */ +/* 424 */ /***/ (function(module, exports) { /** @@ -95706,7 +93693,7 @@ module.exports = LineToRectangle; /***/ }), -/* 426 */ +/* 425 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95715,10 +93702,10 @@ module.exports = LineToRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var LineToLine = __webpack_require__(82); +var LineToLine = __webpack_require__(84); var Contains = __webpack_require__(47); -var ContainsArray = __webpack_require__(205); -var Decompose = __webpack_require__(427); +var ContainsArray = __webpack_require__(207); +var Decompose = __webpack_require__(426); /** * Checks for intersection between Rectangle shape and Triangle shape. @@ -95799,7 +93786,7 @@ module.exports = RectangleToTriangle; /***/ }), -/* 427 */ +/* 426 */ /***/ (function(module, exports) { /** @@ -95836,7 +93823,7 @@ module.exports = Decompose; /***/ }), -/* 428 */ +/* 427 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95845,8 +93832,8 @@ module.exports = Decompose; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var LineToCircle = __webpack_require__(203); -var Contains = __webpack_require__(81); +var LineToCircle = __webpack_require__(205); +var Contains = __webpack_require__(83); /** * Checks if a Triangle and a Circle intersect. @@ -95901,7 +93888,7 @@ module.exports = TriangleToCircle; /***/ }), -/* 429 */ +/* 428 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95912,8 +93899,8 @@ module.exports = TriangleToCircle; */ var Point = __webpack_require__(4); -var TriangleToLine = __webpack_require__(430); -var LineToLine = __webpack_require__(82); +var TriangleToLine = __webpack_require__(429); +var LineToLine = __webpack_require__(84); /** * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. @@ -95960,7 +93947,7 @@ module.exports = GetTriangleToLine; /***/ }), -/* 430 */ +/* 429 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -95969,8 +93956,8 @@ module.exports = GetTriangleToLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(81); -var LineToLine = __webpack_require__(82); +var Contains = __webpack_require__(83); +var LineToLine = __webpack_require__(84); /** * Checks if a Triangle and a Line intersect. @@ -96016,7 +94003,7 @@ module.exports = TriangleToLine; /***/ }), -/* 431 */ +/* 430 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96025,9 +94012,9 @@ module.exports = TriangleToLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ContainsArray = __webpack_require__(205); -var Decompose = __webpack_require__(432); -var LineToLine = __webpack_require__(82); +var ContainsArray = __webpack_require__(207); +var Decompose = __webpack_require__(431); +var LineToLine = __webpack_require__(84); /** * Checks if two Triangles intersect. @@ -96106,7 +94093,7 @@ module.exports = TriangleToTriangle; /***/ }), -/* 432 */ +/* 431 */ /***/ (function(module, exports) { /** @@ -96141,7 +94128,7 @@ module.exports = Decompose; /***/ }), -/* 433 */ +/* 432 */ /***/ (function(module, exports) { /** @@ -96211,7 +94198,7 @@ module.exports = PointToLine; /***/ }), -/* 434 */ +/* 433 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96220,9 +94207,9 @@ module.exports = PointToLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); var Wrap = __webpack_require__(58); -var Angle = __webpack_require__(83); +var Angle = __webpack_require__(85); /** * Get the angle of the normal of the given line in radians. @@ -96245,7 +94232,7 @@ module.exports = NormalAngle; /***/ }), -/* 435 */ +/* 434 */ /***/ (function(module, exports) { /** @@ -96273,7 +94260,7 @@ module.exports = GetMagnitude; /***/ }), -/* 436 */ +/* 435 */ /***/ (function(module, exports) { /** @@ -96301,7 +94288,7 @@ module.exports = GetMagnitudeSq; /***/ }), -/* 437 */ +/* 436 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96310,51 +94297,51 @@ module.exports = GetMagnitudeSq; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); -Rectangle.Area = __webpack_require__(1151); -Rectangle.Ceil = __webpack_require__(1152); -Rectangle.CeilAll = __webpack_require__(1153); -Rectangle.CenterOn = __webpack_require__(162); -Rectangle.Clone = __webpack_require__(1154); +Rectangle.Area = __webpack_require__(1147); +Rectangle.Ceil = __webpack_require__(1148); +Rectangle.CeilAll = __webpack_require__(1149); +Rectangle.CenterOn = __webpack_require__(165); +Rectangle.Clone = __webpack_require__(1150); Rectangle.Contains = __webpack_require__(47); -Rectangle.ContainsPoint = __webpack_require__(1155); -Rectangle.ContainsRect = __webpack_require__(438); -Rectangle.CopyFrom = __webpack_require__(1156); -Rectangle.Decompose = __webpack_require__(427); -Rectangle.Equals = __webpack_require__(1157); -Rectangle.FitInside = __webpack_require__(1158); -Rectangle.FitOutside = __webpack_require__(1159); -Rectangle.Floor = __webpack_require__(1160); -Rectangle.FloorAll = __webpack_require__(1161); -Rectangle.FromPoints = __webpack_require__(171); -Rectangle.GetAspectRatio = __webpack_require__(207); -Rectangle.GetCenter = __webpack_require__(1162); -Rectangle.GetPoint = __webpack_require__(146); -Rectangle.GetPoints = __webpack_require__(269); -Rectangle.GetSize = __webpack_require__(1163); -Rectangle.Inflate = __webpack_require__(1164); -Rectangle.Intersection = __webpack_require__(1165); -Rectangle.MarchingAnts = __webpack_require__(280); -Rectangle.MergePoints = __webpack_require__(1166); -Rectangle.MergeRect = __webpack_require__(1167); -Rectangle.MergeXY = __webpack_require__(1168); -Rectangle.Offset = __webpack_require__(1169); -Rectangle.OffsetPoint = __webpack_require__(1170); -Rectangle.Overlaps = __webpack_require__(1171); -Rectangle.Perimeter = __webpack_require__(108); -Rectangle.PerimeterPoint = __webpack_require__(1172); -Rectangle.Random = __webpack_require__(149); -Rectangle.RandomOutside = __webpack_require__(1173); -Rectangle.SameDimensions = __webpack_require__(1174); -Rectangle.Scale = __webpack_require__(1175); -Rectangle.Union = __webpack_require__(387); +Rectangle.ContainsPoint = __webpack_require__(1151); +Rectangle.ContainsRect = __webpack_require__(437); +Rectangle.CopyFrom = __webpack_require__(1152); +Rectangle.Decompose = __webpack_require__(426); +Rectangle.Equals = __webpack_require__(1153); +Rectangle.FitInside = __webpack_require__(1154); +Rectangle.FitOutside = __webpack_require__(1155); +Rectangle.Floor = __webpack_require__(1156); +Rectangle.FloorAll = __webpack_require__(1157); +Rectangle.FromPoints = __webpack_require__(174); +Rectangle.GetAspectRatio = __webpack_require__(209); +Rectangle.GetCenter = __webpack_require__(1158); +Rectangle.GetPoint = __webpack_require__(149); +Rectangle.GetPoints = __webpack_require__(271); +Rectangle.GetSize = __webpack_require__(1159); +Rectangle.Inflate = __webpack_require__(1160); +Rectangle.Intersection = __webpack_require__(1161); +Rectangle.MarchingAnts = __webpack_require__(282); +Rectangle.MergePoints = __webpack_require__(1162); +Rectangle.MergeRect = __webpack_require__(1163); +Rectangle.MergeXY = __webpack_require__(1164); +Rectangle.Offset = __webpack_require__(1165); +Rectangle.OffsetPoint = __webpack_require__(1166); +Rectangle.Overlaps = __webpack_require__(1167); +Rectangle.Perimeter = __webpack_require__(112); +Rectangle.PerimeterPoint = __webpack_require__(1168); +Rectangle.Random = __webpack_require__(152); +Rectangle.RandomOutside = __webpack_require__(1169); +Rectangle.SameDimensions = __webpack_require__(1170); +Rectangle.Scale = __webpack_require__(1171); +Rectangle.Union = __webpack_require__(386); module.exports = Rectangle; /***/ }), -/* 438 */ +/* 437 */ /***/ (function(module, exports) { /** @@ -96394,7 +94381,7 @@ module.exports = ContainsRect; /***/ }), -/* 439 */ +/* 438 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96438,7 +94425,7 @@ module.exports = Centroid; /***/ }), -/* 440 */ +/* 439 */ /***/ (function(module, exports) { /** @@ -96479,7 +94466,7 @@ module.exports = Offset; /***/ }), -/* 441 */ +/* 440 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96544,7 +94531,7 @@ module.exports = InCenter; /***/ }), -/* 442 */ +/* 441 */ /***/ (function(module, exports) { /** @@ -96615,7 +94602,7 @@ module.exports = CreateInteractiveObject; /***/ }), -/* 443 */ +/* 442 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96740,7 +94727,7 @@ module.exports = Axis; /***/ }), -/* 444 */ +/* 443 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96750,7 +94737,7 @@ module.exports = Axis; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(209); +var Events = __webpack_require__(211); /** * @classdesc @@ -96886,7 +94873,7 @@ module.exports = Button; /***/ }), -/* 445 */ +/* 444 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -96895,10 +94882,10 @@ module.exports = Button; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Axis = __webpack_require__(443); -var Button = __webpack_require__(444); +var Axis = __webpack_require__(442); +var Button = __webpack_require__(443); var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var Vector2 = __webpack_require__(3); /** @@ -97644,7 +95631,7 @@ module.exports = Gamepad; /***/ }), -/* 446 */ +/* 445 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -97654,8 +95641,8 @@ module.exports = Gamepad; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(131); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(133); /** * @classdesc @@ -98046,7 +96033,7 @@ module.exports = Key; /***/ }), -/* 447 */ +/* 446 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -98056,10 +96043,10 @@ module.exports = Key; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(131); +var Events = __webpack_require__(133); var GetFastValue = __webpack_require__(2); -var ProcessKeyCombo = __webpack_require__(1215); -var ResetKeyCombo = __webpack_require__(1217); +var ProcessKeyCombo = __webpack_require__(1211); +var ResetKeyCombo = __webpack_require__(1213); /** * @classdesc @@ -98339,7 +96326,7 @@ module.exports = KeyCombo; /***/ }), -/* 448 */ +/* 447 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -98348,7 +96335,7 @@ module.exports = KeyCombo; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MergeXHRSettings = __webpack_require__(210); +var MergeXHRSettings = __webpack_require__(212); /** * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings @@ -98389,11 +96376,6 @@ var XHRLoader = function (file, globalXHRSettings) xhr.overrideMimeType(config.overrideMimeType); } - if (config.withCredentials) - { - xhr.withCredentials = true; - } - // 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.) xhr.onload = file.onLoad.bind(file, xhr); @@ -98412,7 +96394,7 @@ module.exports = XHRLoader; /***/ }), -/* 449 */ +/* 448 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -98422,11 +96404,11 @@ module.exports = XHRLoader; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); +var CONST = __webpack_require__(29); var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var HTML5AudioFile = __webpack_require__(450); +var HTML5AudioFile = __webpack_require__(449); var IsPlainObject = __webpack_require__(7); /** @@ -98637,7 +96619,7 @@ AudioFile.getAudioURL = function (game, urls) * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('audio', function (key, urls, config, xhrSettings) { @@ -98683,7 +96665,7 @@ module.exports = AudioFile; /***/ }), -/* 450 */ +/* 449 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -98693,10 +96675,10 @@ module.exports = AudioFile; */ var Class = __webpack_require__(0); -var Events = __webpack_require__(80); +var Events = __webpack_require__(81); var File = __webpack_require__(21); var GetFastValue = __webpack_require__(2); -var GetURL = __webpack_require__(132); +var GetURL = __webpack_require__(134); var IsPlainObject = __webpack_require__(7); /** @@ -98881,7 +96863,7 @@ module.exports = HTML5AudioFile; /***/ }), -/* 451 */ +/* 450 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -99028,7 +97010,7 @@ var ScriptFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('script', function (key, url, xhrSettings) { @@ -99052,7 +97034,7 @@ module.exports = ScriptFile; /***/ }), -/* 452 */ +/* 451 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -99203,7 +97185,7 @@ var TextFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('text', function (key, url, xhrSettings) { @@ -99227,7 +97209,7 @@ module.exports = TextFile; /***/ }), -/* 453 */ +/* 452 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -99236,12 +97218,12 @@ module.exports = TextFile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcadeImage = __webpack_require__(454); -var ArcadeSprite = __webpack_require__(134); +var ArcadeImage = __webpack_require__(453); +var ArcadeSprite = __webpack_require__(136); var Class = __webpack_require__(0); var CONST = __webpack_require__(50); -var PhysicsGroup = __webpack_require__(455); -var StaticPhysicsGroup = __webpack_require__(456); +var PhysicsGroup = __webpack_require__(454); +var StaticPhysicsGroup = __webpack_require__(455); /** * @classdesc @@ -99498,7 +97480,7 @@ module.exports = Factory; /***/ }), -/* 454 */ +/* 453 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -99508,8 +97490,8 @@ module.exports = Factory; */ var Class = __webpack_require__(0); -var Components = __webpack_require__(212); -var Image = __webpack_require__(103); +var Components = __webpack_require__(214); +var Image = __webpack_require__(98); /** * @classdesc @@ -99598,7 +97580,7 @@ module.exports = ArcadeImage; /***/ }), -/* 455 */ +/* 454 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -99607,11 +97589,11 @@ module.exports = ArcadeImage; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcadeSprite = __webpack_require__(134); +var ArcadeSprite = __webpack_require__(136); var Class = __webpack_require__(0); var CONST = __webpack_require__(50); var GetFastValue = __webpack_require__(2); -var Group = __webpack_require__(95); +var Group = __webpack_require__(97); var IsPlainObject = __webpack_require__(7); /** @@ -99883,7 +97865,7 @@ module.exports = PhysicsGroup; /***/ }), -/* 456 */ +/* 455 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -99892,11 +97874,11 @@ module.exports = PhysicsGroup; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArcadeSprite = __webpack_require__(134); +var ArcadeSprite = __webpack_require__(136); var Class = __webpack_require__(0); var CONST = __webpack_require__(50); var GetFastValue = __webpack_require__(2); -var Group = __webpack_require__(95); +var Group = __webpack_require__(97); var IsPlainObject = __webpack_require__(7); /** @@ -100074,7 +98056,7 @@ module.exports = StaticPhysicsGroup; /***/ }), -/* 457 */ +/* 456 */ /***/ (function(module, exports) { /** @@ -100159,7 +98141,7 @@ module.exports = OverlapRect; /***/ }), -/* 458 */ +/* 457 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -100168,31 +98150,31 @@ module.exports = OverlapRect; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Body = __webpack_require__(459); -var Clamp = __webpack_require__(23); +var Body = __webpack_require__(458); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var Collider = __webpack_require__(460); +var Collider = __webpack_require__(459); var CONST = __webpack_require__(50); var DistanceBetween = __webpack_require__(53); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(213); -var FuzzyEqual = __webpack_require__(140); -var FuzzyGreaterThan = __webpack_require__(316); -var FuzzyLessThan = __webpack_require__(317); -var GetOverlapX = __webpack_require__(461); -var GetOverlapY = __webpack_require__(462); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(215); +var FuzzyEqual = __webpack_require__(144); +var FuzzyGreaterThan = __webpack_require__(317); +var FuzzyLessThan = __webpack_require__(318); +var GetOverlapX = __webpack_require__(460); +var GetOverlapY = __webpack_require__(461); var GetValue = __webpack_require__(6); -var ProcessQueue = __webpack_require__(181); -var ProcessTileCallbacks = __webpack_require__(1274); -var Rectangle = __webpack_require__(13); -var RTree = __webpack_require__(463); -var SeparateTile = __webpack_require__(1275); -var SeparateX = __webpack_require__(1280); -var SeparateY = __webpack_require__(1281); -var Set = __webpack_require__(127); -var StaticBody = __webpack_require__(465); -var TileIntersectsBody = __webpack_require__(464); -var TransformMatrix = __webpack_require__(30); +var ProcessQueue = __webpack_require__(184); +var ProcessTileCallbacks = __webpack_require__(1270); +var Rectangle = __webpack_require__(11); +var RTree = __webpack_require__(462); +var SeparateTile = __webpack_require__(1271); +var SeparateX = __webpack_require__(1276); +var SeparateY = __webpack_require__(1277); +var Set = __webpack_require__(108); +var StaticBody = __webpack_require__(464); +var TileIntersectsBody = __webpack_require__(463); +var TransformMatrix = __webpack_require__(32); var Vector2 = __webpack_require__(3); var Wrap = __webpack_require__(58); @@ -102548,7 +100530,7 @@ module.exports = World; /***/ }), -/* 459 */ +/* 458 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102560,9 +100542,9 @@ module.exports = World; var Class = __webpack_require__(0); var CONST = __webpack_require__(50); -var Events = __webpack_require__(213); -var RadToDeg = __webpack_require__(168); -var Rectangle = __webpack_require__(13); +var Events = __webpack_require__(215); +var RadToDeg = __webpack_require__(171); +var Rectangle = __webpack_require__(11); var RectangleContains = __webpack_require__(47); var Vector2 = __webpack_require__(3); @@ -102586,8 +100568,8 @@ var Body = new Class({ function Body (world, gameObject) { - var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; - var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; + var width = (gameObject.width) ? gameObject.width : 64; + var height = (gameObject.height) ? gameObject.height : 64; /** * The Arcade Physics simulation this Body belongs to. @@ -102701,10 +100683,7 @@ var Body = new Class({ * @type {Phaser.Math.Vector2} * @since 3.0.0 */ - this.position = new Vector2( - gameObject.x - gameObject.scaleX * gameObject.displayOriginX, - gameObject.y - gameObject.scaleY * gameObject.displayOriginY - ); + this.position = new Vector2(gameObject.x, gameObject.y); /** * The position of this Body during the previous step. @@ -102834,7 +100813,7 @@ var Body = new Class({ * @type {Phaser.Math.Vector2} * @since 3.0.0 */ - this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); /** * The Body's velocity, in pixels per second. @@ -103460,27 +101439,23 @@ var Body = new Class({ resetFlags: function () { // Store and reset collision flags - var wasTouching = this.wasTouching; - var touching = this.touching; - var blocked = this.blocked; + this.wasTouching.none = this.touching.none; + this.wasTouching.up = this.touching.up; + this.wasTouching.down = this.touching.down; + this.wasTouching.left = this.touching.left; + this.wasTouching.right = this.touching.right; - wasTouching.none = touching.none; - wasTouching.up = touching.up; - wasTouching.down = touching.down; - wasTouching.left = touching.left; - wasTouching.right = touching.right; + this.touching.none = true; + this.touching.up = false; + this.touching.down = false; + this.touching.left = false; + this.touching.right = false; - touching.none = true; - touching.up = false; - touching.down = false; - touching.left = false; - touching.right = false; - - blocked.none = true; - blocked.up = false; - blocked.down = false; - blocked.left = false; - blocked.right = false; + this.blocked.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; this.overlapR = 0; this.overlapX = 0; @@ -103793,10 +101768,10 @@ var Body = new Class({ if (center && gameObject.getCenter) { - var ox = (gameObject.width - width) / 2; - var oy = (gameObject.height - height) / 2; + var ox = gameObject.displayWidth / 2; + var oy = gameObject.displayHeight / 2; - this.offset.set(ox, oy); + this.offset.set(ox - this.halfWidth, oy - this.halfHeight); } this.isCircle = false; @@ -104883,7 +102858,7 @@ module.exports = Body; /***/ }), -/* 460 */ +/* 459 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -105066,7 +103041,7 @@ module.exports = Collider; /***/ }), -/* 461 */ +/* 460 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -105174,7 +103149,7 @@ module.exports = GetOverlapX; /***/ }), -/* 462 */ +/* 461 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -105282,7 +103257,7 @@ module.exports = GetOverlapY; /***/ }), -/* 463 */ +/* 462 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -105292,7 +103267,7 @@ module.exports = GetOverlapY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var quickselect = __webpack_require__(384); +var quickselect = __webpack_require__(383); /** * @classdesc @@ -105893,7 +103868,7 @@ function multiSelect (arr, left, right, n, compare) module.exports = rbush; /***/ }), -/* 464 */ +/* 463 */ /***/ (function(module, exports) { /** @@ -105929,7 +103904,7 @@ module.exports = TileIntersectsBody; /***/ }), -/* 465 */ +/* 464 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -105949,7 +103924,7 @@ var Vector2 = __webpack_require__(3); * A Static Arcade Physics Body. * * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. - * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Static Body manually. + * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Body manually. * * A Static Body can collide with other Bodies, but is never moved by collisions. * @@ -105969,8 +103944,8 @@ var StaticBody = new Class({ function StaticBody (world, gameObject) { - var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; - var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; + var width = (gameObject.width) ? gameObject.width : 64; + var height = (gameObject.height) ? gameObject.height : 64; /** * The Arcade Physics simulation this Static Body belongs to. @@ -106029,8 +104004,8 @@ var StaticBody = new Class({ this.isCircle = false; /** - * If this Static Body is circular, this is the radius of the boundary, as set by {@link Phaser.Physics.Arcade.StaticBody#setCircle}, in pixels. - * Equal to `halfWidth`. + * If this Static Body is circular, this is the unscaled radius of the Static Body's boundary, as set by {@link #setCircle}, in source pixels. + * The true radius is equal to `halfWidth`. * * @name Phaser.Physics.Arcade.StaticBody#radius * @type {number} @@ -106040,13 +104015,12 @@ var StaticBody = new Class({ this.radius = 0; /** - * The offset set by {@link Phaser.Physics.Arcade.StaticBody#setCircle} or {@link Phaser.Physics.Arcade.StaticBody#setSize}. + * The offset of this Static Body's actual position from any updated position. * - * This doesn't affect the Static Body's position, because a Static Body does not follow its Game Object. + * Unlike a dynamic Body, a Static Body does not follow its Game Object. As such, this offset is only applied when resizing the Static Body. * * @name Phaser.Physics.Arcade.StaticBody#offset * @type {Phaser.Math.Vector2} - * @readonly * @since 3.0.0 */ this.offset = new Vector2(); @@ -106108,7 +104082,7 @@ var StaticBody = new Class({ * @type {Phaser.Math.Vector2} * @since 3.0.0 */ - this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); /** * A constant zero velocity used by the Arcade Physics simulation for calculations. @@ -106324,7 +104298,7 @@ var StaticBody = new Class({ this.physicsType = CONST.STATIC_BODY; /** - * The calculated change in the Static Body's horizontal position during the current step. + * The calculated change in the Body's horizontal position during the current step. * For a static body this is always zero. * * @name Phaser.Physics.Arcade.StaticBody#_dx @@ -106336,7 +104310,7 @@ var StaticBody = new Class({ this._dx = 0; /** - * The calculated change in the Static Body's vertical position during the current step. + * The calculated change in the Body's vertical position during the current step. * For a static body this is always zero. * * @name Phaser.Physics.Arcade.StaticBody#_dy @@ -106385,7 +104359,7 @@ var StaticBody = new Class({ }, /** - * Syncs the Static Body's position and size with its parent Game Object. + * Syncs the Body's position and size with its parent Game Object. * * @method Phaser.Physics.Arcade.StaticBody#updateFromGameObject * @since 3.1.0 @@ -106414,13 +104388,13 @@ var StaticBody = new Class({ }, /** - * Positions the Static Body at an offset from its Game Object. + * Sets the offset of the body. * * @method Phaser.Physics.Arcade.StaticBody#setOffset * @since 3.4.0 * - * @param {number} x - The horizontal offset of the Static Body from the Game Object's `x`. - * @param {number} y - The vertical offset of the Static Body from the Game Object's `y`. + * @param {number} x - The horizontal offset of the Body from the Game Object's center. + * @param {number} y - The vertical offset of the Body from the Game Object's center. * * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. */ @@ -106446,16 +104420,15 @@ var StaticBody = new Class({ }, /** - * Sets the size of the Static Body. - * When `center` is true, also repositions it. + * Sets the size of the body. * Resets the width and height to match current frame, if no width and height provided and a frame is found. * * @method Phaser.Physics.Arcade.StaticBody#setSize * @since 3.0.0 * - * @param {integer} [width] - The width of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. - * @param {integer} [height] - The height of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. - * @param {boolean} [center=true] - Place the Static Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. + * @param {integer} [width] - The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param {integer} [height] - The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param {boolean} [center=true] - Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. * * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. */ @@ -106508,7 +104481,7 @@ var StaticBody = new Class({ }, /** - * Sets this Static Body to have a circular body and sets its size and position. + * Sets this Static Body to have a circular body and sets its sizes and position. * * @method Phaser.Physics.Arcade.StaticBody#setCircle * @since 3.0.0 @@ -106917,10 +104890,157 @@ var StaticBody = new Class({ module.exports = StaticBody; +/***/ }), +/* 465 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + * + * @namespace Phaser.Physics.Impact.COLLIDES + * @memberof Phaser.Physics.Impact + * @since 3.0.0 + */ + +module.exports = { + + /** + * Never collides. + * + * @name Phaser.Physics.Impact.COLLIDES.NEVER + * @type {integer} + * @const + * @since 3.0.0 + */ + NEVER: 0, + + /** + * Lite collision. + * + * @name Phaser.Physics.Impact.COLLIDES.LITE + * @type {integer} + * @const + * @since 3.0.0 + */ + LITE: 1, + + /** + * Passive collision. + * + * @name Phaser.Physics.Impact.COLLIDES.PASSIVE + * @type {integer} + * @const + * @since 3.0.0 + */ + PASSIVE: 2, + + /** + * Active collision. + * + * @name Phaser.Physics.Impact.COLLIDES.ACTIVE + * @type {integer} + * @const + * @since 3.0.0 + */ + ACTIVE: 4, + + /** + * Fixed collision. + * + * @name Phaser.Physics.Impact.COLLIDES.FIXED + * @type {integer} + * @const + * @since 3.0.0 + */ + FIXED: 8 + +}; + + /***/ }), /* 466 */ /***/ (function(module, exports) { +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + * + * @namespace Phaser.Physics.Impact.TYPE + * @memberof Phaser.Physics.Impact + * @since 3.0.0 + */ +module.exports = { + + /** + * Collides with nothing. + * + * @name Phaser.Physics.Impact.TYPE.NONE + * @type {integer} + * @const + * @since 3.0.0 + */ + NONE: 0, + + /** + * Type A. Collides with Type B. + * + * @name Phaser.Physics.Impact.TYPE.A + * @type {integer} + * @const + * @since 3.0.0 + */ + A: 1, + + /** + * Type B. Collides with Type A. + * + * @name Phaser.Physics.Impact.TYPE.B + * @type {integer} + * @const + * @since 3.0.0 + */ + B: 2, + + /** + * Collides with both types A and B. + * + * @name Phaser.Physics.Impact.TYPE.BOTH + * @type {integer} + * @const + * @since 3.0.0 + */ + BOTH: 3 + +}; + + +/***/ }), +/* 467 */ +/***/ (function(module, exports) { + /** * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. * @@ -107044,7 +105164,7 @@ module.exports = Pair; /***/ }), -/* 467 */ +/* 468 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107174,7 +105294,7 @@ module.exports = BasePlugin; /***/ }), -/* 468 */ +/* 469 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107183,7 +105303,7 @@ module.exports = BasePlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching @@ -107219,7 +105339,7 @@ module.exports = ReplaceByIndex; /***/ }), -/* 469 */ +/* 470 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107228,7 +105348,7 @@ module.exports = ReplaceByIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var IsInLayerBounds = __webpack_require__(99); +var IsInLayerBounds = __webpack_require__(103); /** * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns @@ -107262,7 +105382,7 @@ module.exports = HasTileAt; /***/ }), -/* 470 */ +/* 471 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107271,9 +105391,9 @@ module.exports = HasTileAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tile = __webpack_require__(72); -var IsInLayerBounds = __webpack_require__(99); -var CalculateFacesAt = __webpack_require__(215); +var Tile = __webpack_require__(74); +var IsInLayerBounds = __webpack_require__(103); +var CalculateFacesAt = __webpack_require__(217); /** * Removes the tile at the given tile coordinates in the specified layer and updates the layer's @@ -107309,7 +105429,7 @@ var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, la } else { - layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, layer.tileWidth, layer.tileHeight); + layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, tile.width, tile.height); } // Recalculate faces only if the removed tile was a colliding tile @@ -107324,81 +105444,6 @@ var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, la module.exports = RemoveTileAt; -/***/ }), -/* 471 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = __webpack_require__(10); - -/** - * Converts from world X coordinates (pixels) to orthogonal tile X coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.WorldToTileX - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The X location in tile units. - */ -var OrthoWorldToTileX = function (worldX, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - return snapToFloor - ? Math.floor(worldX / tileWidth) - : worldX / tileWidth; - -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the WorldToTileXY function.'); - return null; -}; - -var WorldToTileX = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoWorldToTileX; - - default: - return nullFunc; - - } - -}; - -module.exports = WorldToTileX; - - /***/ }), /* 472 */ /***/ (function(module, exports, __webpack_require__) { @@ -107409,173 +105454,11 @@ module.exports = WorldToTileX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); - -/** - * Converts from world Y coordinates (pixels) to orthogonal tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.OrthoWorldToTileY - * @private - * @since 3.0.0 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var OrthoWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - return snapToFloor - ? Math.floor(worldY / tileHeight) - : worldY / tileHeight; - -}; - -/** - * Converts from world Y coordinates (pixels) to staggered tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.StagWorldToTileY - * @private - * @since 3.2.2 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var StagWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - return snapToFloor - ? Math.floor(worldY / (tileHeight / 2)) - : worldY / (tileHeight / 2); -}; - -/** - * Converts from world Y coordinates (pixels) to hexagonal tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.HexWorldToTileY - * @private - * @since 3.2.2 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var HexWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - return snapToFloor - ? Math.floor(worldY / rowHeight) - : worldY / rowHeight; -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the WorldToTileXY function.'); - return null; -}; - -var WorldToTileY = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoWorldToTileY; - - case CONST.HEXAGONAL: - return HexWorldToTileY; - - case CONST.STAGGERED: - return StagWorldToTileY; - - default: - return nullFunc; - - } - -}; - -module.exports = WorldToTileY; - - -/***/ }), -/* 473 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = __webpack_require__(33); -var Parse2DArray = __webpack_require__(218); -var ParseCSV = __webpack_require__(474); -var ParseJSONTiled = __webpack_require__(475); -var ParseWeltmeister = __webpack_require__(486); +var Formats = __webpack_require__(31); +var Parse2DArray = __webpack_require__(220); +var ParseCSV = __webpack_require__(473); +var ParseJSONTiled = __webpack_require__(474); +var ParseWeltmeister = __webpack_require__(485); /** * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format @@ -107632,7 +105515,7 @@ module.exports = Parse; /***/ }), -/* 474 */ +/* 473 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107641,8 +105524,8 @@ module.exports = Parse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var Parse2DArray = __webpack_require__(218); +var Formats = __webpack_require__(31); +var Parse2DArray = __webpack_require__(220); /** * Parses a CSV string of tile indexes into a new MapData object with a single layer. @@ -107680,7 +105563,7 @@ module.exports = ParseCSV; /***/ }), -/* 475 */ +/* 474 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107689,15 +105572,14 @@ module.exports = ParseCSV; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var Formats = __webpack_require__(33); -var MapData = __webpack_require__(101); -var ParseTileLayers = __webpack_require__(476); -var ParseImageLayers = __webpack_require__(478); -var ParseTilesets = __webpack_require__(479); -var ParseObjectLayers = __webpack_require__(482); -var BuildTilesetIndex = __webpack_require__(484); -var AssignTileProperties = __webpack_require__(485); +var Formats = __webpack_require__(31); +var MapData = __webpack_require__(105); +var ParseTileLayers = __webpack_require__(475); +var ParseImageLayers = __webpack_require__(477); +var ParseTilesets = __webpack_require__(478); +var ParseObjectLayers = __webpack_require__(481); +var BuildTilesetIndex = __webpack_require__(483); +var AssignTileProperties = __webpack_require__(484); /** * Parses a Tiled JSON object into a new MapData object. @@ -107718,21 +105600,12 @@ var AssignTileProperties = __webpack_require__(485); */ var ParseJSONTiled = function (name, json, insertNull) { - if (json.orientation === 'isometric' || json.orientation === 'staggered') + if (json.orientation !== 'orthogonal') { - console.warn('Isometric map types are WIP in this version of Phaser'); - } - else if (json.orientation === 'hexagonal') - { - console.warn('Hexagonal map types are WIP in this version of Phaser'); - } - else if (json.orientation !== 'orthogonal') - { - console.warn('Only orthogonal, hexagonal and isometric map types are supported in this version of Phaser'); + console.warn('Only orthogonal map types are supported in this version of Phaser'); return null; } - // Map data will consist of: layers, objects, images, tilesets, sizes var mapData = new MapData({ width: json.width, @@ -107740,7 +105613,7 @@ var ParseJSONTiled = function (name, json, insertNull) name: name, tileWidth: json.tilewidth, tileHeight: json.tileheight, - orientation: CONST.fromOrientationString(json.orientation), + orientation: json.orientation, format: Formats.TILED_JSON, version: json.version, properties: json.properties, @@ -107748,14 +105621,6 @@ var ParseJSONTiled = function (name, json, insertNull) infinite: json.infinite }); - - - - if (mapData.orientation === CONST.HEXAGONAL) - { - mapData.hexSideLength = json.hexsidelength; - } - mapData.layers = ParseTileLayers(json, insertNull); mapData.images = ParseImageLayers(json); @@ -107776,7 +105641,7 @@ module.exports = ParseJSONTiled; /***/ }), -/* 476 */ +/* 475 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -107785,13 +105650,12 @@ module.exports = ParseJSONTiled; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var Base64Decode = __webpack_require__(477); +var Base64Decode = __webpack_require__(476); var GetFastValue = __webpack_require__(2); -var LayerData = __webpack_require__(100); -var ParseGID = __webpack_require__(219); -var Tile = __webpack_require__(72); -var CreateGroupLayer = __webpack_require__(220); +var LayerData = __webpack_require__(104); +var ParseGID = __webpack_require__(221); +var Tile = __webpack_require__(74); +var CreateGroupLayer = __webpack_require__(222); /** * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. @@ -107909,15 +105773,9 @@ var ParseTileLayers = function (json, insertNull) tileHeight: json.tileheight, alpha: (curGroupState.opacity * curl.opacity), visible: (curGroupState.visible && curl.visible), - properties: GetFastValue(curl, 'properties', {}), - orientation: CONST.fromOrientationString(json.orientation) + properties: GetFastValue(curl, 'properties', {}) }); - if (layerData.orientation === CONST.HEXAGONAL) - { - layerData.hexSideLength = json.hexsidelength; - } - for (var c = 0; c < curl.height; c++) { output.push([ null ]); @@ -107988,14 +105846,9 @@ var ParseTileLayers = function (json, insertNull) tileHeight: json.tileheight, alpha: (curGroupState.opacity * curl.opacity), visible: (curGroupState.visible && curl.visible), - properties: GetFastValue(curl, 'properties', {}), - orientation: CONST.fromOrientationString(json.orientation) + properties: GetFastValue(curl, 'properties', {}) }); - if (layerData.orientation === CONST.HEXAGONAL) - { - layerData.hexSideLength = json.hexsidelength; - } var row = []; // Loop through the data field in the JSON. @@ -108046,7 +105899,7 @@ module.exports = ParseTileLayers; /***/ }), -/* 477 */ +/* 476 */ /***/ (function(module, exports) { /** @@ -108089,7 +105942,7 @@ module.exports = Base64Decode; /***/ }), -/* 478 */ +/* 477 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108099,7 +105952,7 @@ module.exports = Base64Decode; */ var GetFastValue = __webpack_require__(2); -var CreateGroupLayer = __webpack_require__(220); +var CreateGroupLayer = __webpack_require__(222); /** * Parses a Tiled JSON object into an array of objects with details about the image layers. @@ -108177,7 +106030,7 @@ module.exports = ParseImageLayers; /***/ }), -/* 479 */ +/* 478 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108186,9 +106039,9 @@ module.exports = ParseImageLayers; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tileset = __webpack_require__(137); -var ImageCollection = __webpack_require__(480); -var ParseObject = __webpack_require__(221); +var Tileset = __webpack_require__(141); +var ImageCollection = __webpack_require__(479); +var ParseObject = __webpack_require__(223); /** * Tilesets and Image Collections @@ -108346,7 +106199,7 @@ module.exports = ParseTilesets; /***/ }), -/* 480 */ +/* 479 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108518,7 +106371,7 @@ module.exports = ImageCollection; /***/ }), -/* 481 */ +/* 480 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108527,7 +106380,7 @@ module.exports = ImageCollection; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HasValue = __webpack_require__(104); +var HasValue = __webpack_require__(99); /** * Returns a new object that only contains the `keys` that were found on the object provided. @@ -108562,7 +106415,7 @@ module.exports = Pick; /***/ }), -/* 482 */ +/* 481 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108572,9 +106425,9 @@ module.exports = Pick; */ var GetFastValue = __webpack_require__(2); -var ParseObject = __webpack_require__(221); -var ObjectLayer = __webpack_require__(483); -var CreateGroupLayer = __webpack_require__(220); +var ParseObject = __webpack_require__(223); +var ObjectLayer = __webpack_require__(482); +var CreateGroupLayer = __webpack_require__(222); /** * Parses a Tiled JSON object into an array of ObjectLayer objects. @@ -108661,7 +106514,7 @@ module.exports = ParseObjectLayers; /***/ }), -/* 483 */ +/* 482 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108783,7 +106636,7 @@ module.exports = ObjectLayer; /***/ }), -/* 484 */ +/* 483 */ /***/ (function(module, exports) { /** @@ -108856,7 +106709,7 @@ module.exports = BuildTilesetIndex; /***/ }), -/* 485 */ +/* 484 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108865,7 +106718,7 @@ module.exports = BuildTilesetIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * Copy properties from tileset to tiles. @@ -108929,7 +106782,7 @@ module.exports = AssignTileProperties; /***/ }), -/* 486 */ +/* 485 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -108938,10 +106791,10 @@ module.exports = AssignTileProperties; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Formats = __webpack_require__(33); -var MapData = __webpack_require__(101); -var ParseTileLayers = __webpack_require__(487); -var ParseTilesets = __webpack_require__(488); +var Formats = __webpack_require__(31); +var MapData = __webpack_require__(105); +var ParseTileLayers = __webpack_require__(486); +var ParseTilesets = __webpack_require__(487); /** * Parses a Weltmeister JSON object into a new MapData object. @@ -108996,7 +106849,7 @@ module.exports = ParseWeltmeister; /***/ }), -/* 487 */ +/* 486 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -109005,8 +106858,8 @@ module.exports = ParseWeltmeister; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var LayerData = __webpack_require__(100); -var Tile = __webpack_require__(72); +var LayerData = __webpack_require__(104); +var Tile = __webpack_require__(74); /** * [description] @@ -109080,7 +106933,7 @@ module.exports = ParseTileLayers; /***/ }), -/* 488 */ +/* 487 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -109089,7 +106942,7 @@ module.exports = ParseTileLayers; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Tileset = __webpack_require__(137); +var Tileset = __webpack_require__(141); /** * [description] @@ -109131,7 +106984,7 @@ module.exports = ParseTilesets; /***/ }), -/* 489 */ +/* 488 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -109142,16 +106995,16 @@ module.exports = ParseTilesets; var Class = __webpack_require__(0); var DegToRad = __webpack_require__(35); -var DynamicTilemapLayer = __webpack_require__(490); -var Extend = __webpack_require__(18); -var Formats = __webpack_require__(33); -var LayerData = __webpack_require__(100); -var Rotate = __webpack_require__(326); -var SpliceOne = __webpack_require__(78); -var StaticTilemapLayer = __webpack_require__(491); -var Tile = __webpack_require__(72); -var TilemapComponents = __webpack_require__(135); -var Tileset = __webpack_require__(137); +var DynamicTilemapLayer = __webpack_require__(489); +var Extend = __webpack_require__(17); +var Formats = __webpack_require__(31); +var LayerData = __webpack_require__(104); +var Rotate = __webpack_require__(327); +var SpliceOne = __webpack_require__(79); +var StaticTilemapLayer = __webpack_require__(490); +var Tile = __webpack_require__(74); +var TilemapComponents = __webpack_require__(137); +var Tileset = __webpack_require__(141); /** * @callback TilemapFilterCallback @@ -109387,28 +107240,6 @@ var Tilemap = new Class({ * @since 3.0.0 */ this.currentLayerIndex = 0; - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = mapData.hexSideLength; - - /** - * Components used for conversions between real world coordinates and tile coordinates, - * initialized here to prevent switching between them at runtime depending on map orientation. - * refer to the components themselves for documentation. - * @since 3.2.2 - */ - this.WorldToTileXY = TilemapComponents.WorldToTileXY(this.orientation); - this.WorldToTileX = TilemapComponents.WorldToTileX(this.orientation); - this.WorldToTileY = TilemapComponents.WorldToTileY(this.orientation); - this.TileToWorldXY = TilemapComponents.TileToWorldXY(this.orientation); - this.TileToWorldX = TilemapComponents.TileToWorldX(this.orientation); - this.TileToWorldY = TilemapComponents.TileToWorldY(this.orientation); }, /** @@ -109659,8 +107490,7 @@ var Tilemap = new Class({ tileWidth: tileWidth, tileHeight: tileHeight, width: width, - height: height, - orientation: this.orientation + height: height }); var row; @@ -111504,7 +109334,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.TileToWorldX(tileX, camera, layer); + return TilemapComponents.TileToWorldX(tileX, camera, layer); }, /** @@ -111529,7 +109359,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.TileToWorldY(tileX, camera, layer); + return TilemapComponents.TileToWorldY(tileX, camera, layer); }, /** @@ -111550,14 +109380,13 @@ var Tilemap = new Class({ * * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. */ - tileToWorldXY: function (tileX, tileY, point, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null; } - return this.TileToWorldXY(tileX, tileY, point, camera, layer); + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, layer); }, /** @@ -111628,7 +109457,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.WorldToTileX(worldX, snapToFloor, camera, layer); + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, layer); }, /** @@ -111653,7 +109482,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.WorldToTileY(worldY, snapToFloor, camera, layer); + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, layer); }, /** @@ -111681,7 +109510,7 @@ var Tilemap = new Class({ if (layer === null) { return null; } - return this.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); }, /** @@ -111712,7 +109541,7 @@ module.exports = Tilemap; /***/ }), -/* 490 */ +/* 489 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -111723,10 +109552,9 @@ module.exports = Tilemap; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var DynamicTilemapLayerRender = __webpack_require__(1338); +var DynamicTilemapLayerRender = __webpack_require__(1333); var GameObject = __webpack_require__(14); -var TilemapComponents = __webpack_require__(135); -var Vector2 = __webpack_require__(3); +var TilemapComponents = __webpack_require__(137); /** * @classdesc @@ -111829,7 +109657,7 @@ var DynamicTilemapLayer = new Class({ // Link the LayerData with this static tilemap layer this.layer.tilemapLayer = this; - + /** * The Tileset/s associated with this layer. * @@ -111864,18 +109692,6 @@ var DynamicTilemapLayer = new Class({ */ this.skipCull = false; - /** - * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. - * By default the camera will allow 1 full tile in all directions. - * - * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#isoCullDistances - * @type {Phaser.Math.Vector2} - * @since 3.23.0 - */ - this.isoCullDistances = new Vector2(1, 1); - /** * The total number of tiles drawn by the renderer in the last frame. * @@ -112908,7 +110724,7 @@ var DynamicTilemapLayer = new Class({ */ tileToWorldX: function (tileX, camera) { - return this.tilemap.TileToWorldX(tileX, camera, this.layer); + return TilemapComponents.TileToWorldX(tileX, camera, this.layer); }, /** @@ -112925,7 +110741,7 @@ var DynamicTilemapLayer = new Class({ */ tileToWorldY: function (tileY, camera) { - return this.tilemap.TileToWorldY(tileY, camera, this.layer); + return TilemapComponents.TileToWorldY(tileY, camera, this.layer); }, /** @@ -112945,7 +110761,7 @@ var DynamicTilemapLayer = new Class({ */ tileToWorldXY: function (tileX, tileY, point, camera) { - return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer); }, /** @@ -112998,7 +110814,7 @@ var DynamicTilemapLayer = new Class({ */ worldToTileX: function (worldX, snapToFloor, camera) { - return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer); }, /** @@ -113016,7 +110832,7 @@ var DynamicTilemapLayer = new Class({ */ worldToTileY: function (worldY, snapToFloor, camera) { - return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer); }, /** @@ -113037,7 +110853,7 @@ var DynamicTilemapLayer = new Class({ */ worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) { - return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); } }); @@ -113046,7 +110862,7 @@ module.exports = DynamicTilemapLayer; /***/ }), -/* 491 */ +/* 490 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -113057,13 +110873,12 @@ module.exports = DynamicTilemapLayer; var Class = __webpack_require__(0); var Components = __webpack_require__(12); -var GameEvents = __webpack_require__(19); +var GameEvents = __webpack_require__(18); var GameObject = __webpack_require__(14); -var StaticTilemapLayerRender = __webpack_require__(1341); -var TilemapComponents = __webpack_require__(135); -var TransformMatrix = __webpack_require__(30); -var Utils = __webpack_require__(9); -var Vector2 = __webpack_require__(3); +var StaticTilemapLayerRender = __webpack_require__(1336); +var TilemapComponents = __webpack_require__(137); +var TransformMatrix = __webpack_require__(32); +var Utils = __webpack_require__(10); /** * @classdesc @@ -113202,18 +111017,6 @@ var StaticTilemapLayer = new Class({ */ this.skipCull = false; - /** - * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. - * By default the camera will allow 1 full tile in all directions. - * - * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#isoCullDistances - * @type {Phaser.Math.Vector2} - * @since 3.23.0 - */ - this.isoCullDistances = new Vector2(1, 1); - /** * Canvas only. * @@ -113427,7 +111230,6 @@ var StaticTilemapLayer = new Class({ { this.updateVBOData(); }, this); - }, /** @@ -114398,7 +112200,7 @@ var StaticTilemapLayer = new Class({ */ tileToWorldX: function (tileX, camera) { - return this.tilemap.TileToWorldX(tileX, camera, this.layer); + return TilemapComponents.TileToWorldX(tileX, camera, this.layer); }, /** @@ -114415,7 +112217,7 @@ var StaticTilemapLayer = new Class({ */ tileToWorldY: function (tileY, camera) { - return this.tilemap.TileToWorldY(tileY, camera, this.layer); + return TilemapComponents.TileToWorldY(tileY, camera, this.layer); }, /** @@ -114435,7 +112237,7 @@ var StaticTilemapLayer = new Class({ */ tileToWorldXY: function (tileX, tileY, point, camera) { - return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); + return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer); }, /** @@ -114454,7 +112256,7 @@ var StaticTilemapLayer = new Class({ */ worldToTileX: function (worldX, snapToFloor, camera) { - return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer); }, /** @@ -114473,7 +112275,7 @@ var StaticTilemapLayer = new Class({ */ worldToTileY: function (worldY, snapToFloor, camera) { - return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); + return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer); }, /** @@ -114495,7 +112297,7 @@ var StaticTilemapLayer = new Class({ */ worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) { - return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); }, /** @@ -114554,7 +112356,7 @@ module.exports = StaticTilemapLayer; /***/ }), -/* 492 */ +/* 491 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -114867,7 +112669,7 @@ module.exports = TimerEvent; /***/ }), -/* 493 */ +/* 492 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -114876,7 +112678,7 @@ module.exports = TimerEvent; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RESERVED = __webpack_require__(1350); +var RESERVED = __webpack_require__(1345); /** * Internal function used by the Tween Builder to return an array of properties @@ -114928,7 +112730,7 @@ module.exports = GetProps; /***/ }), -/* 494 */ +/* 493 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -114976,7 +112778,7 @@ module.exports = GetTweens; /***/ }), -/* 495 */ +/* 494 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -114985,15 +112787,15 @@ module.exports = GetTweens; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Defaults = __webpack_require__(225); +var Defaults = __webpack_require__(227); var GetAdvancedValue = __webpack_require__(15); -var GetBoolean = __webpack_require__(86); -var GetEaseFunction = __webpack_require__(67); -var GetNewValue = __webpack_require__(138); +var GetBoolean = __webpack_require__(88); +var GetEaseFunction = __webpack_require__(82); +var GetNewValue = __webpack_require__(142); var GetValue = __webpack_require__(6); -var GetValueOp = __webpack_require__(224); -var Tween = __webpack_require__(226); -var TweenData = __webpack_require__(228); +var GetValueOp = __webpack_require__(226); +var Tween = __webpack_require__(228); +var TweenData = __webpack_require__(230); /** * Creates a new Number Tween. @@ -115106,7 +112908,7 @@ module.exports = NumberTweenBuilder; /***/ }), -/* 496 */ +/* 495 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -115115,9 +112917,9 @@ module.exports = NumberTweenBuilder; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetEaseFunction = __webpack_require__(67); +var GetEaseFunction = __webpack_require__(82); var GetValue = __webpack_require__(6); -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); /** * Creates a Stagger function to be used by a Tween property. @@ -115352,7 +113154,7 @@ module.exports = StaggerBuilder; /***/ }), -/* 497 */ +/* 496 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -115361,17 +113163,17 @@ module.exports = StaggerBuilder; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); -var Defaults = __webpack_require__(225); +var Clone = __webpack_require__(67); +var Defaults = __webpack_require__(227); var GetAdvancedValue = __webpack_require__(15); -var GetBoolean = __webpack_require__(86); -var GetEaseFunction = __webpack_require__(67); -var GetNewValue = __webpack_require__(138); -var GetTargets = __webpack_require__(223); -var GetTweens = __webpack_require__(494); +var GetBoolean = __webpack_require__(88); +var GetEaseFunction = __webpack_require__(82); +var GetNewValue = __webpack_require__(142); +var GetTargets = __webpack_require__(225); +var GetTweens = __webpack_require__(493); var GetValue = __webpack_require__(6); -var Timeline = __webpack_require__(498); -var TweenBuilder = __webpack_require__(139); +var Timeline = __webpack_require__(497); +var TweenBuilder = __webpack_require__(143); /** * Builds a Timeline of Tweens based on a configuration object. @@ -115504,7 +113306,7 @@ module.exports = TimelineBuilder; /***/ }), -/* 498 */ +/* 497 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -115514,10 +113316,10 @@ module.exports = TimelineBuilder; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(227); -var TweenBuilder = __webpack_require__(139); -var TWEEN_CONST = __webpack_require__(87); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(229); +var TweenBuilder = __webpack_require__(143); +var TWEEN_CONST = __webpack_require__(89); /** * @classdesc @@ -116409,7 +114211,7 @@ module.exports = Timeline; /***/ }), -/* 499 */ +/* 498 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -116418,9 +114220,9 @@ module.exports = Timeline; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseAnimation = __webpack_require__(145); +var BaseAnimation = __webpack_require__(148); var Class = __webpack_require__(0); -var Events = __webpack_require__(107); +var Events = __webpack_require__(111); /** * @classdesc @@ -117434,16 +115236,13 @@ var Animation = new Class({ gameObject.setSizeToFrame(); - if (gameObject._originComponent) + if (animationFrame.frame.customPivot) { - if (animationFrame.frame.customPivot) - { - gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); - } - else - { - gameObject.updateDisplayOrigin(); - } + gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); + } + else + { + gameObject.updateDisplayOrigin(); } return gameObject; @@ -117587,7 +115386,7 @@ module.exports = Animation; /***/ }), -/* 500 */ +/* 499 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -117597,13 +115396,13 @@ module.exports = Animation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasSnapshot = __webpack_require__(501); +var CanvasSnapshot = __webpack_require__(500); var CameraEvents = __webpack_require__(48); var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); -var GetBlendModes = __webpack_require__(502); -var ScaleEvents = __webpack_require__(90); -var TransformMatrix = __webpack_require__(30); +var CONST = __webpack_require__(29); +var GetBlendModes = __webpack_require__(501); +var ScaleEvents = __webpack_require__(92); +var TransformMatrix = __webpack_require__(32); /** * @classdesc @@ -118048,10 +115847,7 @@ var CanvasRenderer = new Class({ { camera.emit(CameraEvents.POST_RENDER, camera); - if (camera.renderToGame) - { - scene.sys.context.drawImage(camera.canvas, cx, cy); - } + scene.sys.context.drawImage(camera.canvas, cx, cy); } }, @@ -118384,7 +116180,7 @@ module.exports = CanvasRenderer; /***/ }), -/* 501 */ +/* 500 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118393,8 +116189,8 @@ module.exports = CanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); -var Color = __webpack_require__(32); +var CanvasPool = __webpack_require__(26); +var Color = __webpack_require__(33); var GetFastValue = __webpack_require__(2); /** @@ -118477,7 +116273,7 @@ module.exports = CanvasSnapshot; /***/ }), -/* 502 */ +/* 501 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118487,7 +116283,7 @@ module.exports = CanvasSnapshot; */ var modes = __webpack_require__(52); -var CanvasFeatures = __webpack_require__(311); +var CanvasFeatures = __webpack_require__(313); /** * Returns an array which maps the default blend modes to supported Canvas blend modes. @@ -118541,7 +116337,7 @@ module.exports = GetBlendModes; /***/ }), -/* 503 */ +/* 502 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -118551,25 +116347,24 @@ module.exports = GetBlendModes; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BaseCamera = __webpack_require__(89); +var BaseCamera = __webpack_require__(91); var CameraEvents = __webpack_require__(48); var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); -var GameEvents = __webpack_require__(19); -var IsSizePowerOfTwo = __webpack_require__(114); +var CONST = __webpack_require__(29); +var GameEvents = __webpack_require__(18); +var IsSizePowerOfTwo = __webpack_require__(118); var NOOP = __webpack_require__(1); -var ScaleEvents = __webpack_require__(90); -var SpliceOne = __webpack_require__(78); -var TextureEvents = __webpack_require__(115); -var TransformMatrix = __webpack_require__(30); -var Utils = __webpack_require__(9); -var WebGLSnapshot = __webpack_require__(504); +var ScaleEvents = __webpack_require__(92); +var SpliceOne = __webpack_require__(79); +var TextureEvents = __webpack_require__(119); +var TransformMatrix = __webpack_require__(32); +var Utils = __webpack_require__(10); +var WebGLSnapshot = __webpack_require__(503); // Default Pipelines -var BitmapMaskPipeline = __webpack_require__(505); -var ForwardDiffuseLightPipeline = __webpack_require__(506); -var TextureTintPipeline = __webpack_require__(232); -var TextureTintStripPipeline = __webpack_require__(507); +var BitmapMaskPipeline = __webpack_require__(504); +var ForwardDiffuseLightPipeline = __webpack_require__(505); +var TextureTintPipeline = __webpack_require__(235); /** * @callback WebGLContextCallback @@ -119258,7 +117053,6 @@ var WebGLRenderer = new Class({ this.pipelines = {}; this.addPipeline('TextureTintPipeline', new TextureTintPipeline({ game: game, renderer: this })); - this.addPipeline('TextureTintStripPipeline', new TextureTintStripPipeline({ game: game, renderer: this })); this.addPipeline('BitmapMaskPipeline', new BitmapMaskPipeline({ game: game, renderer: this })); this.addPipeline('Light2D', new ForwardDiffuseLightPipeline({ game: game, renderer: this, maxLights: config.maxLights })); @@ -120486,36 +118280,33 @@ var WebGLRenderer = new Class({ camera.emit(CameraEvents.POST_RENDER, camera); - if (camera.renderToGame) - { - TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); + TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); - var getTint = Utils.getTintAppendFloatAlpha; - - var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; - - pipeline.batchTexture( - camera, - camera.glTexture, - camera.width, camera.height, - camera.x, camera.y, - camera.width, camera.height, - camera.zoom, camera.zoom, - camera.rotation, - camera.flipX, !camera.flipY, - 1, 1, - 0, 0, - 0, 0, camera.width, camera.height, - getTint(camera._tintTL, camera._alphaTL), - getTint(camera._tintTR, camera._alphaTR), - getTint(camera._tintBL, camera._alphaBL), - getTint(camera._tintBR, camera._alphaBR), - (camera._isTinted && camera.tintFill), - 0, 0, - this.defaultCamera, - null - ); - } + var getTint = Utils.getTintAppendFloatAlpha; + + var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; + + pipeline.batchTexture( + camera, + camera.glTexture, + camera.width, camera.height, + camera.x, camera.y, + camera.width, camera.height, + camera.zoom, camera.zoom, + camera.rotation, + camera.flipX, !camera.flipY, + 1, 1, + 0, 0, + 0, 0, camera.width, camera.height, + getTint(camera._tintTL, camera._alphaTL), + getTint(camera._tintTR, camera._alphaTR), + getTint(camera._tintBL, camera._alphaBL), + getTint(camera._tintBR, camera._alphaBR), + (camera._isTinted && camera.tintFill), + 0, 0, + this.defaultCamera, + null + ); // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it this.setBlankTexture(true); @@ -121093,16 +118884,14 @@ var WebGLRenderer = new Class({ }, /** - * Sets a 1f uniform value on the given shader. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 1f value to set on the named uniform. + * @param {number} x - [description] * * @return {this} This WebGL Renderer instance. */ @@ -121116,17 +118905,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 2f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 2f x value to set on the named uniform. - * @param {number} y - The 2f y value to set on the named uniform. + * @param {number} x - [description] + * @param {number} y - [description] * * @return {this} This WebGL Renderer instance. */ @@ -121140,18 +118927,16 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 3f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 3f x value to set on the named uniform. - * @param {number} y - The 3f y value to set on the named uniform. - * @param {number} z - The 3f z value to set on the named uniform. + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} z - [description] * * @return {this} This WebGL Renderer instance. */ @@ -121165,19 +118950,17 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 4f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets uniform of a WebGLProgram * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 4f x value to set on the named uniform. - * @param {number} y - The 4f y value to set on the named uniform. - * @param {number} z - The 4f z value to set on the named uniform. - * @param {number} w - The 4f w value to set on the named uniform. + * @param {number} x - X component + * @param {number} y - Y component + * @param {number} z - Z component + * @param {number} w - W component * * @return {this} This WebGL Renderer instance. */ @@ -121191,9 +118974,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 1fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1v * @since 3.13.0 @@ -121214,9 +118995,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 2fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2v * @since 3.13.0 @@ -121237,9 +119016,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 3fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3v * @since 3.13.0 @@ -121260,9 +119037,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a 4fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4v * @since 3.13.0 @@ -121284,16 +119059,14 @@ var WebGLRenderer = new Class({ }, /** - * Sets a 1i uniform value on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt1 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 1i value to set on the named uniform. + * @param {integer} x - [description] * * @return {this} This WebGL Renderer instance. */ @@ -121307,17 +119080,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 2i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt2 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 2i x value to set on the named uniform. - * @param {integer} y - The 2i y value to set on the named uniform. + * @param {integer} x - The new X component + * @param {integer} y - The new Y component * * @return {this} This WebGL Renderer instance. */ @@ -121331,18 +119102,16 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 3i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt3 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 3i x value to set on the named uniform. - * @param {integer} y - The 3i y value to set on the named uniform. - * @param {integer} z - The 3i z value to set on the named uniform. + * @param {integer} x - The new X component + * @param {integer} y - The new Y component + * @param {integer} z - The new Z component * * @return {this} This WebGL Renderer instance. */ @@ -121356,19 +119125,17 @@ var WebGLRenderer = new Class({ }, /** - * Sets the 4i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt4 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 4i x value to set on the named uniform. - * @param {integer} y - The 4i y value to set on the named uniform. - * @param {integer} z - The 4i z value to set on the named uniform. - * @param {integer} w - The 4i w value to set on the named uniform. + * @param {integer} x - X component + * @param {integer} y - Y component + * @param {integer} z - Z component + * @param {integer} w - W component * * @return {this} This WebGL Renderer instance. */ @@ -121382,9 +119149,7 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a matrix 2fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets the value of a 2x2 matrix uniform variable in the given WebGLProgram. * * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix2 * @since 3.0.0 @@ -121392,7 +119157,7 @@ var WebGLRenderer = new Class({ * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 4 float values. + * @param {Float32Array} matrix - The new matrix value. * * @return {this} This WebGL Renderer instance. */ @@ -121406,17 +119171,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a matrix 3fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * [description] * * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix3 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 9 float values. + * @param {boolean} transpose - [description] + * @param {Float32Array} matrix - [description] * * @return {this} This WebGL Renderer instance. */ @@ -121430,17 +119193,15 @@ var WebGLRenderer = new Class({ }, /** - * Sets the value of a matrix 4fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. + * Sets uniform of a WebGLProgram * * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix4 * @since 3.0.0 * * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 16 float values. + * @param {boolean} transpose - Is the matrix transposed + * @param {Float32Array} matrix - Matrix data * * @return {this} This WebGL Renderer instance. */ @@ -121530,7 +119291,7 @@ module.exports = WebGLRenderer; /***/ }), -/* 504 */ +/* 503 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -121539,8 +119300,8 @@ module.exports = WebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); -var Color = __webpack_require__(32); +var CanvasPool = __webpack_require__(26); +var Color = __webpack_require__(33); var GetFastValue = __webpack_require__(2); /** @@ -121640,7 +119401,7 @@ module.exports = WebGLSnapshot; /***/ }), -/* 505 */ +/* 504 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -121653,7 +119414,7 @@ module.exports = WebGLSnapshot; var Class = __webpack_require__(0); var ShaderSourceFS = __webpack_require__(776); var ShaderSourceVS = __webpack_require__(777); -var WebGLPipeline = __webpack_require__(141); +var WebGLPipeline = __webpack_require__(234); /** * @classdesc @@ -121771,23 +119532,21 @@ var BitmapMaskPipeline = new Class({ }, /** - * Resizes this pipeline and updates the projection. + * [description] * * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resize * @since 3.0.0 * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} resolution - [description] * * @return {this} This WebGLPipeline instance. */ resize: function (width, height, resolution) { WebGLPipeline.prototype.resize.call(this, width, height, resolution); - this.resolutionDirty = true; - return this; }, @@ -121800,7 +119559,7 @@ var BitmapMaskPipeline = new Class({ * * @param {Phaser.GameObjects.GameObject} mask - GameObject used as mask. * @param {Phaser.GameObjects.GameObject} maskedObject - GameObject masked by the mask GameObject. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera rendering the current mask. + * @param {Phaser.Cameras.Scene2D.Camera} camera - [description] */ beginMask: function (mask, maskedObject, camera) { @@ -121905,7 +119664,7 @@ module.exports = BitmapMaskPipeline; /***/ }), -/* 506 */ +/* 505 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -121917,7 +119676,7 @@ module.exports = BitmapMaskPipeline; var Class = __webpack_require__(0); var ShaderSourceFS = __webpack_require__(778); -var TextureTintPipeline = __webpack_require__(232); +var TextureTintPipeline = __webpack_require__(235); var LIGHT_COUNT = 10; @@ -122426,417 +120185,757 @@ module.exports = ForwardDiffuseLightPipeline; /***/ }), -/* 507 */ -/***/ (function(module, exports, __webpack_require__) { +/* 506 */ +/***/ (function(module, exports) { /** * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Class = __webpack_require__(0); -var GetFastValue = __webpack_require__(2); -var ModelViewProjection = __webpack_require__(233); -var ShaderSourceFS = __webpack_require__(335); -var ShaderSourceVS = __webpack_require__(336); -var TransformMatrix = __webpack_require__(30); -var WebGLPipeline = __webpack_require__(141); - /** - * @classdesc - * TextureTintStripPipeline implements the rendering infrastructure - * for displaying textured objects - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. + * Implements a model view projection matrices. + * Pipelines can implement this for doing 2D and 3D rendering. * - * @class TextureTintStripPipeline - * @extends Phaser.Renderer.WebGL.WebGLPipeline - * @memberof Phaser.Renderer.WebGL.Pipelines - * @constructor - * @since 3.23.0 - * - * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. + * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection + * @since 3.0.0 */ -var TextureTintStripPipeline = new Class({ - - Extends: WebGLPipeline, - - Mixins: [ - ModelViewProjection - ], - - initialize: - - function TextureTintStripPipeline (config) - { - var rendererConfig = config.renderer.config; - - // Vertex Size = attribute size added together (2 + 2 + 1 + 4) - - WebGLPipeline.call(this, { - game: config.game, - renderer: config.renderer, - gl: config.renderer.gl, - topology: config.renderer.gl.TRIANGLE_STRIP, - vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), - fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), - vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), - vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), - attributes: [ - { - name: 'inPosition', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: 0 - }, - { - name: 'inTexCoord', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 2 - }, - { - name: 'inTintEffect', - size: 1, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 4 - }, - { - name: 'inTint', - size: 4, - type: config.renderer.gl.UNSIGNED_BYTE, - normalized: true, - offset: Float32Array.BYTES_PER_ELEMENT * 5 - } - ] - }); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewF32 - * @type {Float32Array} - * @since 3.23.0 - */ - this.vertexViewF32 = new Float32Array(this.vertexData); - - /** - * Uint32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewU32 - * @type {Uint32Array} - * @since 3.23.0 - */ - this.vertexViewU32 = new Uint32Array(this.vertexData); - - /** - * Size of the batch. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#maxQuads - * @type {integer} - * @since 3.23.0 - */ - this.maxQuads = rendererConfig.batchSize; - - /** - * Collection of batch information - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#batches - * @type {array} - * @since 3.23.0 - */ - this.batches = []; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - this.mvpInit(); - }, +var ModelViewProjection = { /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#onBind - * @since 3.23.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - WebGLPipeline.prototype.onBind.call(this); - - this.mvpUpdate(); - - return this; - }, - - /** - * Resizes this pipeline and updates the projection. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#resize - * @since 3.23.0 - * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - WebGLPipeline.prototype.resize.call(this, width, height, resolution); - - this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); - - return this; - }, - - /** - * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#setTexture2D - * @since 3.23.0 - * - * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. - * - * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline} This pipeline instance. - */ - setTexture2D: function (texture, unit) - { - if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } - if (unit === undefined) { unit = 0; } - - if (this.requireTextureBatch(texture, unit)) - { - this.pushBatch(texture, unit); - } - - return this; - }, - - /** - * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#requireTextureBatch - * @since 3.23.0 - * - * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} unit - Texture unit to which the texture needs to be bound. - * - * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. - */ - requireTextureBatch: function (texture, unit) - { - var batches = this.batches; - var batchLength = batches.length; - - if (batchLength > 0) - { - // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property - var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; - - return !(currentTexture === texture); - } - - return true; - }, - - /** - * Creates a new batch object and pushes it to a batch array. - * The batch object contains information relevant to the current - * vertex batch like the offset in the vertex buffer, vertex count and - * the textures used by that batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#pushBatch - * @since 3.23.0 + * Dirty flag for checking if model matrix needs to be updated on GPU. * - * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. - * @param {integer} unit - Texture unit to which the texture needs to be bound. + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty + * @type {boolean} + * @since 3.0.0 */ - pushBatch: function (texture, unit) + modelMatrixDirty: false, + + /** + * Dirty flag for checking if view matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + viewMatrixDirty: false, + + /** + * Dirty flag for checking if projection matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + projectionMatrixDirty: false, + + /** + * Model matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + modelMatrix: null, + + /** + * View matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + viewMatrix: null, + + /** + * Projection matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + projectionMatrix: null, + + /** + * Initializes MVP matrices with an identity matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit + * @since 3.0.0 + */ + mvpInit: function () { - if (unit === 0) - { - this.batches.push({ - first: this.vertexCount, - texture: texture, - textures: [] - }); - } - else - { - var textures = []; - - textures[unit - 1] = texture; - - this.batches.push({ - first: this.vertexCount, - texture: null, - textures: textures - }); - } + this.modelMatrixDirty = true; + this.viewMatrixDirty = true; + this.projectionMatrixDirty = true; + + this.modelMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.viewMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.projectionMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + return this; }, /** - * Uploads the vertex data and emits a draw call for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#flush - * @since 3.23.0 - * - * @return {this} This WebGLPipeline instance. + * If dirty flags are set then the matrices are uploaded to the GPU. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate + * @since 3.0.0 */ - flush: function () + mvpUpdate: function () { - if (this.flushLocked) + var program = this.program; + + if (this.modelMatrixDirty) { - return this; + this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); + this.modelMatrixDirty = false; + } + + if (this.viewMatrixDirty) + { + this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); + this.viewMatrixDirty = false; } - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - var renderer = this.renderer; - - var batches = this.batches; - var batchCount = batches.length; - var batchVertexCount = 0; - var batch = null; - var batchNext; - var textureIndex; - var nTexture; - - if (batchCount === 0 || vertexCount === 0) + if (this.projectionMatrixDirty) { - this.flushLocked = false; - - return this; + this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + this.projectionMatrixDirty = false; } - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + return this; + }, - // Process the TEXTURE BATCHES + /** + * Loads an identity matrix to the model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity + * @since 3.0.0 + */ + modelIdentity: function () + { + var modelMatrix = this.modelMatrix; + + modelMatrix[0] = 1; + modelMatrix[1] = 0; + modelMatrix[2] = 0; + modelMatrix[3] = 0; + modelMatrix[4] = 0; + modelMatrix[5] = 1; + modelMatrix[6] = 0; + modelMatrix[7] = 0; + modelMatrix[8] = 0; + modelMatrix[9] = 0; + modelMatrix[10] = 1; + modelMatrix[11] = 0; + modelMatrix[12] = 0; + modelMatrix[13] = 0; + modelMatrix[14] = 0; + modelMatrix[15] = 1; - for (var index = 0; index < batchCount - 1; index++) - { - batch = batches[index]; - batchNext = batches[index + 1]; + this.modelMatrixDirty = true; + + return this; + }, - // Multi-texture check (for non-zero texture units) - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; + /** + * Scale model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelScale: function (x, y, z) + { + var modelMatrix = this.modelMatrix; - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } + modelMatrix[0] = modelMatrix[0] * x; + modelMatrix[1] = modelMatrix[1] * x; + modelMatrix[2] = modelMatrix[2] * x; + modelMatrix[3] = modelMatrix[3] * x; + modelMatrix[4] = modelMatrix[4] * y; + modelMatrix[5] = modelMatrix[5] * y; + modelMatrix[6] = modelMatrix[6] * y; + modelMatrix[7] = modelMatrix[7] * y; + modelMatrix[8] = modelMatrix[8] * z; + modelMatrix[9] = modelMatrix[9] * z; + modelMatrix[10] = modelMatrix[10] * z; + modelMatrix[11] = modelMatrix[11] * z; + + this.modelMatrixDirty = true; - gl.activeTexture(gl.TEXTURE0); - } + return this; + }, - batchVertexCount = batchNext.first - batch.first; + /** + * Translate model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelTranslate: function (x, y, z) + { + var modelMatrix = this.modelMatrix; - // Bail out if texture property is null (i.e. if a texture unit > 0) - if (batch.texture === null || batchVertexCount <= 0) - { - continue; - } + modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; + modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; + modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; + modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; - renderer.setTexture2D(batch.texture, 0, false); + this.modelMatrixDirty = true; - gl.drawArrays(topology, batch.first, batchVertexCount); - } + return this; + }, - // Left over data - batch = batches[batchCount - 1]; + /** + * Rotates the model matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateX: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; - // Multi-texture check (for non-zero texture units) + modelMatrix[4] = a10 * c + a20 * s; + modelMatrix[5] = a11 * c + a21 * s; + modelMatrix[6] = a12 * c + a22 * s; + modelMatrix[7] = a13 * c + a23 * s; + modelMatrix[8] = a20 * c - a10 * s; + modelMatrix[9] = a21 * c - a11 * s; + modelMatrix[10] = a22 * c - a12 * s; + modelMatrix[11] = a23 * c - a13 * s; - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; + this.modelMatrixDirty = true; - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } + return this; + }, - gl.activeTexture(gl.TEXTURE0); - } + /** + * Rotates the model matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateY: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; - batchVertexCount = vertexCount - batch.first; + modelMatrix[0] = a00 * c - a20 * s; + modelMatrix[1] = a01 * c - a21 * s; + modelMatrix[2] = a02 * c - a22 * s; + modelMatrix[3] = a03 * c - a23 * s; + modelMatrix[8] = a00 * s + a20 * c; + modelMatrix[9] = a01 * s + a21 * c; + modelMatrix[10] = a02 * s + a22 * c; + modelMatrix[11] = a03 * s + a23 * c; - if (batch.texture && batchVertexCount > 0) - { - renderer.setTexture2D(batch.texture, 0, false); + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateZ: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; - gl.drawArrays(topology, batch.first, batchVertexCount); - } + modelMatrix[0] = a00 * c + a10 * s; + modelMatrix[1] = a01 * c + a11 * s; + modelMatrix[2] = a02 * c + a12 * s; + modelMatrix[3] = a03 * c + a13 * s; + modelMatrix[4] = a10 * c - a00 * s; + modelMatrix[5] = a11 * c - a01 * s; + modelMatrix[6] = a12 * c - a02 * s; + modelMatrix[7] = a13 * c - a03 * s; - this.vertexCount = 0; + this.modelMatrixDirty = true; - batches.length = 0; + return this; + }, - this.flushLocked = false; + /** + * Loads identity matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + viewIdentity: function () + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = 1; + viewMatrix[1] = 0; + viewMatrix[2] = 0; + viewMatrix[3] = 0; + viewMatrix[4] = 0; + viewMatrix[5] = 1; + viewMatrix[6] = 0; + viewMatrix[7] = 0; + viewMatrix[8] = 0; + viewMatrix[9] = 0; + viewMatrix[10] = 1; + viewMatrix[11] = 0; + viewMatrix[12] = 0; + viewMatrix[13] = 0; + viewMatrix[14] = 0; + viewMatrix[15] = 1; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Scales view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewScale: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = viewMatrix[0] * x; + viewMatrix[1] = viewMatrix[1] * x; + viewMatrix[2] = viewMatrix[2] * x; + viewMatrix[3] = viewMatrix[3] * x; + viewMatrix[4] = viewMatrix[4] * y; + viewMatrix[5] = viewMatrix[5] * y; + viewMatrix[6] = viewMatrix[6] * y; + viewMatrix[7] = viewMatrix[7] * y; + viewMatrix[8] = viewMatrix[8] * z; + viewMatrix[9] = viewMatrix[9] * z; + viewMatrix[10] = viewMatrix[10] * z; + viewMatrix[11] = viewMatrix[11] * z; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Translates view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewTranslate: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; + viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; + viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; + viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateX: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[4] = a10 * c + a20 * s; + viewMatrix[5] = a11 * c + a21 * s; + viewMatrix[6] = a12 * c + a22 * s; + viewMatrix[7] = a13 * c + a23 * s; + viewMatrix[8] = a20 * c - a10 * s; + viewMatrix[9] = a21 * c - a11 * s; + viewMatrix[10] = a22 * c - a12 * s; + viewMatrix[11] = a23 * c - a13 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateY: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[0] = a00 * c - a20 * s; + viewMatrix[1] = a01 * c - a21 * s; + viewMatrix[2] = a02 * c - a22 * s; + viewMatrix[3] = a03 * c - a23 * s; + viewMatrix[8] = a00 * s + a20 * c; + viewMatrix[9] = a01 * s + a21 * c; + viewMatrix[10] = a02 * s + a22 * c; + viewMatrix[11] = a03 * s + a23 * c; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateZ: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + + viewMatrix[0] = a00 * c + a10 * s; + viewMatrix[1] = a01 * c + a11 * s; + viewMatrix[2] = a02 * c + a12 * s; + viewMatrix[3] = a03 * c + a13 * s; + viewMatrix[4] = a10 * c - a00 * s; + viewMatrix[5] = a11 * c - a01 * s; + viewMatrix[6] = a12 * c - a02 * s; + viewMatrix[7] = a13 * c - a03 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D + * @since 3.0.0 + * + * @param {Float32Array} matrix2D - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad2D: function (matrix2D) + { + var vm = this.viewMatrix; + + vm[0] = matrix2D[0]; + vm[1] = matrix2D[1]; + vm[2] = 0.0; + vm[3] = 0.0; + vm[4] = matrix2D[2]; + vm[5] = matrix2D[3]; + vm[6] = 0.0; + vm[7] = 0.0; + vm[8] = matrix2D[4]; + vm[9] = matrix2D[5]; + vm[10] = 1.0; + vm[11] = 0.0; + vm[12] = 0.0; + vm[13] = 0.0; + vm[14] = 0.0; + vm[15] = 1.0; + + this.viewMatrixDirty = true; + + return this; + }, + + + /** + * Copies a 4x4 matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad + * @since 3.0.0 + * + * @param {Float32Array} matrix - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad: function (matrix) + { + var vm = this.viewMatrix; + + vm[0] = matrix[0]; + vm[1] = matrix[1]; + vm[2] = matrix[2]; + vm[3] = matrix[3]; + vm[4] = matrix[4]; + vm[5] = matrix[5]; + vm[6] = matrix[6]; + vm[7] = matrix[7]; + vm[8] = matrix[8]; + vm[9] = matrix[9]; + vm[10] = matrix[10]; + vm[11] = matrix[11]; + vm[12] = matrix[12]; + vm[13] = matrix[13]; + vm[14] = matrix[14]; + vm[15] = matrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads identity matrix into the projection matrix. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + projIdentity: function () + { + var projectionMatrix = this.projectionMatrix; + + projectionMatrix[0] = 1; + projectionMatrix[1] = 0; + projectionMatrix[2] = 0; + projectionMatrix[3] = 0; + projectionMatrix[4] = 0; + projectionMatrix[5] = 1; + projectionMatrix[6] = 0; + projectionMatrix[7] = 0; + projectionMatrix[8] = 0; + projectionMatrix[9] = 0; + projectionMatrix[10] = 1; + projectionMatrix[11] = 0; + projectionMatrix[12] = 0; + projectionMatrix[13] = 0; + projectionMatrix[14] = 0; + projectionMatrix[15] = 1; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up an orthographic projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho + * @since 3.0.0 + * + * @param {number} left - The left value. + * @param {number} right - The right value. + * @param {number} bottom - The bottom value. + * @param {number} top - The top value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projOrtho: function (left, right, bottom, top, near, far) + { + var projectionMatrix = this.projectionMatrix; + var leftRight = 1.0 / (left - right); + var bottomTop = 1.0 / (bottom - top); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = -2.0 * leftRight; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = -2.0 * bottomTop; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = 2.0 * nearFar; + projectionMatrix[11] = 0.0; + projectionMatrix[12] = (left + right) * leftRight; + projectionMatrix[13] = (top + bottom) * bottomTop; + projectionMatrix[14] = (far + near) * nearFar; + projectionMatrix[15] = 1.0; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up a perspective projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp + * @since 3.0.0 + * + * @param {number} fovY - The fov value. + * @param {number} aspectRatio - The aspectRatio value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projPersp: function (fovY, aspectRatio, near, far) + { + var projectionMatrix = this.projectionMatrix; + var fov = 1.0 / Math.tan(fovY / 2.0); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = fov / aspectRatio; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = fov; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = (far + near) * nearFar; + projectionMatrix[11] = -1.0; + projectionMatrix[12] = 0.0; + projectionMatrix[13] = 0.0; + projectionMatrix[14] = (2.0 * far * near) * nearFar; + projectionMatrix[15] = 0.0; + + this.projectionMatrixDirty = true; return this; } +}; -}); - -module.exports = TextureTintStripPipeline; +module.exports = ModelViewProjection; /***/ }), -/* 508 */ +/* 507 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -122849,7 +120948,7 @@ var Axes = {}; module.exports = Axes; -var Vector = __webpack_require__(97); +var Vector = __webpack_require__(101); var Common = __webpack_require__(37); (function() { @@ -122906,7 +121005,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 509 */ +/* 508 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -122921,24 +121020,24 @@ var Common = __webpack_require__(37); module.exports = { - Bounce: __webpack_require__(1389), - Collision: __webpack_require__(1390), - Force: __webpack_require__(1391), - Friction: __webpack_require__(1392), - Gravity: __webpack_require__(1393), - Mass: __webpack_require__(1394), - Static: __webpack_require__(1395), - Sensor: __webpack_require__(1396), - SetBody: __webpack_require__(1397), - Sleep: __webpack_require__(1398), - Transform: __webpack_require__(1415), - Velocity: __webpack_require__(1416) + Bounce: __webpack_require__(1414), + Collision: __webpack_require__(1415), + Force: __webpack_require__(1416), + Friction: __webpack_require__(1417), + Gravity: __webpack_require__(1418), + Mass: __webpack_require__(1419), + Static: __webpack_require__(1420), + Sensor: __webpack_require__(1421), + SetBody: __webpack_require__(1422), + Sleep: __webpack_require__(1423), + Transform: __webpack_require__(1440), + Velocity: __webpack_require__(1441) }; /***/ }), -/* 510 */ +/* 509 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -122953,9 +121052,9 @@ var Detector = {}; module.exports = Detector; -var SAT = __webpack_require__(511); -var Pair = __webpack_require__(466); -var Bounds = __webpack_require__(98); +var SAT = __webpack_require__(510); +var Pair = __webpack_require__(467); +var Bounds = __webpack_require__(102); (function() { @@ -123051,7 +121150,7 @@ var Bounds = __webpack_require__(98); /***/ }), -/* 511 */ +/* 510 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123066,8 +121165,8 @@ var SAT = {}; module.exports = SAT; -var Vertices = __webpack_require__(84); -var Vector = __webpack_require__(97); +var Vertices = __webpack_require__(86); +var Vector = __webpack_require__(101); (function() { @@ -123327,7 +121426,7 @@ var Vector = __webpack_require__(97); /***/ }), -/* 512 */ +/* 511 */ /***/ (function(module, exports) { var g; @@ -123353,9 +121452,10 @@ module.exports = g; /***/ }), -/* 513 */ +/* 512 */ /***/ (function(module, exports, __webpack_require__) { +__webpack_require__(513); __webpack_require__(514); __webpack_require__(515); __webpack_require__(516); @@ -123363,11 +121463,10 @@ __webpack_require__(517); __webpack_require__(518); __webpack_require__(519); __webpack_require__(520); -__webpack_require__(521); /***/ }), -/* 514 */ +/* 513 */ /***/ (function(module, exports) { /** @@ -123407,7 +121506,7 @@ if (!Array.prototype.forEach) /***/ }), -/* 515 */ +/* 514 */ /***/ (function(module, exports) { /** @@ -123423,7 +121522,7 @@ if (!Array.isArray) /***/ }), -/* 516 */ +/* 515 */ /***/ (function(module, exports) { /* Copyright 2013 Chris Wilson @@ -123610,7 +121709,7 @@ BiquadFilterNode.type and OscillatorNode.type. /***/ }), -/* 517 */ +/* 516 */ /***/ (function(module, exports) { /** @@ -123625,7 +121724,7 @@ if (!window.console) /***/ }), -/* 518 */ +/* 517 */ /***/ (function(module, exports) { // ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc @@ -123637,7 +121736,7 @@ if (!Math.trunc) { /***/ }), -/* 519 */ +/* 518 */ /***/ (function(module, exports) { /** @@ -123674,7 +121773,7 @@ if (!Math.trunc) { /***/ }), -/* 520 */ +/* 519 */ /***/ (function(module, exports) { // References: @@ -123731,7 +121830,7 @@ if (!window.cancelAnimationFrame) /***/ }), -/* 521 */ +/* 520 */ /***/ (function(module, exports) { /** @@ -123784,7 +121883,7 @@ if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'o /***/ }), -/* 522 */ +/* 521 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123793,7 +121892,7 @@ if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'o * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var QuickSet = __webpack_require__(237); +var QuickSet = __webpack_require__(239); /** * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. @@ -123832,7 +121931,7 @@ module.exports = AlignTo; /***/ }), -/* 523 */ +/* 522 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -123873,7 +121972,7 @@ module.exports = Angle; /***/ }), -/* 524 */ +/* 523 */ /***/ (function(module, exports) { /** @@ -123912,7 +122011,7 @@ module.exports = Call; /***/ }), -/* 525 */ +/* 524 */ /***/ (function(module, exports) { /** @@ -123970,7 +122069,7 @@ module.exports = GetFirst; /***/ }), -/* 526 */ +/* 525 */ /***/ (function(module, exports) { /** @@ -124028,7 +122127,7 @@ module.exports = GetLast; /***/ }), -/* 527 */ +/* 526 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124037,11 +122136,11 @@ module.exports = GetLast; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AlignIn = __webpack_require__(250); -var CONST = __webpack_require__(102); +var AlignIn = __webpack_require__(252); +var CONST = __webpack_require__(106); var GetFastValue = __webpack_require__(2); var NOOP = __webpack_require__(1); -var Zone = __webpack_require__(106); +var Zone = __webpack_require__(110); var tempZone = new Zone({ sys: { queueDepthSort: NOOP, events: { once: NOOP } } }, 0, 0, 1, 1); @@ -124127,7 +122226,7 @@ module.exports = GridAlign; /***/ }), -/* 528 */ +/* 527 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -124136,7 +122235,7 @@ module.exports = GridAlign; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); // bitmask flag for GameObject.renderMask var _FLAG = 2; // 0010 @@ -124422,7 +122521,7 @@ module.exports = Alpha; /***/ }), -/* 529 */ +/* 528 */ /***/ (function(module, exports) { /** @@ -124449,7 +122548,7 @@ module.exports = 'add'; /***/ }), -/* 530 */ +/* 529 */ /***/ (function(module, exports) { /** @@ -124477,7 +122576,7 @@ module.exports = 'complete'; /***/ }), -/* 531 */ +/* 530 */ /***/ (function(module, exports) { /** @@ -124504,7 +122603,7 @@ module.exports = 'repeat'; /***/ }), -/* 532 */ +/* 531 */ /***/ (function(module, exports) { /** @@ -124532,7 +122631,7 @@ module.exports = 'restart'; /***/ }), -/* 533 */ +/* 532 */ /***/ (function(module, exports) { /** @@ -124560,7 +122659,7 @@ module.exports = 'start'; /***/ }), -/* 534 */ +/* 533 */ /***/ (function(module, exports) { /** @@ -124584,7 +122683,7 @@ module.exports = 'pauseall'; /***/ }), -/* 535 */ +/* 534 */ /***/ (function(module, exports) { /** @@ -124608,7 +122707,7 @@ module.exports = 'remove'; /***/ }), -/* 536 */ +/* 535 */ /***/ (function(module, exports) { /** @@ -124631,7 +122730,7 @@ module.exports = 'resumeall'; /***/ }), -/* 537 */ +/* 536 */ /***/ (function(module, exports) { /** @@ -124660,7 +122759,7 @@ module.exports = 'animationcomplete'; /***/ }), -/* 538 */ +/* 537 */ /***/ (function(module, exports) { /** @@ -124688,7 +122787,7 @@ module.exports = 'animationcomplete-'; /***/ }), -/* 539 */ +/* 538 */ /***/ (function(module, exports) { /** @@ -124717,7 +122816,7 @@ module.exports = 'animationrepeat-'; /***/ }), -/* 540 */ +/* 539 */ /***/ (function(module, exports) { /** @@ -124745,7 +122844,7 @@ module.exports = 'animationrestart-'; /***/ }), -/* 541 */ +/* 540 */ /***/ (function(module, exports) { /** @@ -124773,7 +122872,7 @@ module.exports = 'animationstart-'; /***/ }), -/* 542 */ +/* 541 */ /***/ (function(module, exports) { /** @@ -124802,7 +122901,7 @@ module.exports = 'animationupdate-'; /***/ }), -/* 543 */ +/* 542 */ /***/ (function(module, exports) { /** @@ -124832,7 +122931,7 @@ module.exports = 'animationrepeat'; /***/ }), -/* 544 */ +/* 543 */ /***/ (function(module, exports) { /** @@ -124861,7 +122960,7 @@ module.exports = 'animationrestart'; /***/ }), -/* 545 */ +/* 544 */ /***/ (function(module, exports) { /** @@ -124890,7 +122989,7 @@ module.exports = 'animationstart'; /***/ }), -/* 546 */ +/* 545 */ /***/ (function(module, exports) { /** @@ -124920,7 +123019,7 @@ module.exports = 'animationupdate'; /***/ }), -/* 547 */ +/* 546 */ /***/ (function(module, exports) { /** @@ -125069,7 +123168,7 @@ module.exports = ComputedSize; /***/ }), -/* 548 */ +/* 547 */ /***/ (function(module, exports) { /** @@ -125194,7 +123293,7 @@ module.exports = Crop; /***/ }), -/* 549 */ +/* 548 */ /***/ (function(module, exports) { /** @@ -125358,7 +123457,7 @@ module.exports = Flip; /***/ }), -/* 550 */ +/* 549 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -125367,8 +123466,8 @@ module.exports = Flip; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var RotateAround = __webpack_require__(271); +var Rectangle = __webpack_require__(11); +var RotateAround = __webpack_require__(273); var Vector2 = __webpack_require__(3); /** @@ -125717,7 +123816,7 @@ module.exports = GetBounds; /***/ }), -/* 551 */ +/* 550 */ /***/ (function(module, exports) { /** @@ -125740,7 +123839,7 @@ module.exports = 'blur'; /***/ }), -/* 552 */ +/* 551 */ /***/ (function(module, exports) { /** @@ -125762,7 +123861,7 @@ module.exports = 'boot'; /***/ }), -/* 553 */ +/* 552 */ /***/ (function(module, exports) { /** @@ -125785,7 +123884,7 @@ module.exports = 'contextlost'; /***/ }), -/* 554 */ +/* 553 */ /***/ (function(module, exports) { /** @@ -125808,7 +123907,7 @@ module.exports = 'contextrestored'; /***/ }), -/* 555 */ +/* 554 */ /***/ (function(module, exports) { /** @@ -125831,7 +123930,7 @@ module.exports = 'destroy'; /***/ }), -/* 556 */ +/* 555 */ /***/ (function(module, exports) { /** @@ -125853,7 +123952,7 @@ module.exports = 'focus'; /***/ }), -/* 557 */ +/* 556 */ /***/ (function(module, exports) { /** @@ -125879,7 +123978,7 @@ module.exports = 'hidden'; /***/ }), -/* 558 */ +/* 557 */ /***/ (function(module, exports) { /** @@ -125900,7 +123999,7 @@ module.exports = 'pause'; /***/ }), -/* 559 */ +/* 558 */ /***/ (function(module, exports) { /** @@ -125926,7 +124025,7 @@ module.exports = 'postrender'; /***/ }), -/* 560 */ +/* 559 */ /***/ (function(module, exports) { /** @@ -125951,7 +124050,7 @@ module.exports = 'poststep'; /***/ }), -/* 561 */ +/* 560 */ /***/ (function(module, exports) { /** @@ -125976,7 +124075,7 @@ module.exports = 'prerender'; /***/ }), -/* 562 */ +/* 561 */ /***/ (function(module, exports) { /** @@ -126001,7 +124100,7 @@ module.exports = 'prestep'; /***/ }), -/* 563 */ +/* 562 */ /***/ (function(module, exports) { /** @@ -126023,7 +124122,7 @@ module.exports = 'ready'; /***/ }), -/* 564 */ +/* 563 */ /***/ (function(module, exports) { /** @@ -126044,7 +124143,7 @@ module.exports = 'resume'; /***/ }), -/* 565 */ +/* 564 */ /***/ (function(module, exports) { /** @@ -126069,7 +124168,7 @@ module.exports = 'step'; /***/ }), -/* 566 */ +/* 565 */ /***/ (function(module, exports) { /** @@ -126093,7 +124192,7 @@ module.exports = 'visible'; /***/ }), -/* 567 */ +/* 566 */ /***/ (function(module, exports) { /** @@ -126296,7 +124395,7 @@ module.exports = Origin; /***/ }), -/* 568 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -126306,9 +124405,9 @@ module.exports = Origin; */ var DegToRad = __webpack_require__(35); -var GetBoolean = __webpack_require__(86); +var GetBoolean = __webpack_require__(88); var GetValue = __webpack_require__(6); -var TWEEN_CONST = __webpack_require__(87); +var TWEEN_CONST = __webpack_require__(89); var Vector2 = __webpack_require__(3); /** @@ -126411,7 +124510,7 @@ var PathFollower = { * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path at a time. * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config] - Settings for the PathFollower. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ setPath: function (path, config) { @@ -126443,7 +124542,7 @@ var PathFollower = { * @param {boolean} value - Whether the PathFollower should automatically rotate to point in the direction of the Path. * @param {number} [offset=0] - Rotation offset in degrees. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ setRotateToPath: function (value, offset) { @@ -126482,7 +124581,7 @@ var PathFollower = { * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config={}] - The duration of the follow, or a PathFollower config object. * @param {number} [startAt=0] - Optional start position of the follow, between 0 and 1. * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ startFollow: function (config, startAt) { @@ -126572,7 +124671,7 @@ var PathFollower = { * @method Phaser.GameObjects.Components.PathFollower#pauseFollow * @since 3.3.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ pauseFollow: function () { @@ -126594,7 +124693,7 @@ var PathFollower = { * @method Phaser.GameObjects.Components.PathFollower#resumeFollow * @since 3.3.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ resumeFollow: function () { @@ -126616,7 +124715,7 @@ var PathFollower = { * @method Phaser.GameObjects.Components.PathFollower#stopFollow * @since 3.3.0 * - * @return {this} This Game Object. + * @return {Phaser.GameObjects.PathFollower} This Game Object. */ stopFollow: function () { @@ -126647,7 +124746,7 @@ var PathFollower = { var tweenData = tween.data[0]; var pathVector = this.pathVector; - if (tweenData.state === TWEEN_CONST.COMPLETE) + if (tweenData.state !== TWEEN_CONST.COMPLETE) { this.path.getPoint(1, pathVector); @@ -126702,7 +124801,7 @@ module.exports = PathFollower; /***/ }), -/* 569 */ +/* 568 */ /***/ (function(module, exports) { /** @@ -126889,7 +124988,7 @@ module.exports = Size; /***/ }), -/* 570 */ +/* 569 */ /***/ (function(module, exports) { /** @@ -127019,7 +125118,7 @@ module.exports = Texture; /***/ }), -/* 571 */ +/* 570 */ /***/ (function(module, exports) { /** @@ -127227,7 +125326,7 @@ module.exports = TextureCrop; /***/ }), -/* 572 */ +/* 571 */ /***/ (function(module, exports) { /** @@ -127567,7 +125666,7 @@ module.exports = Tint; /***/ }), -/* 573 */ +/* 572 */ /***/ (function(module, exports) { /** @@ -127599,7 +125698,7 @@ module.exports = 'changedata'; /***/ }), -/* 574 */ +/* 573 */ /***/ (function(module, exports) { /** @@ -127629,7 +125728,7 @@ module.exports = 'changedata-'; /***/ }), -/* 575 */ +/* 574 */ /***/ (function(module, exports) { /** @@ -127657,7 +125756,7 @@ module.exports = 'removedata'; /***/ }), -/* 576 */ +/* 575 */ /***/ (function(module, exports) { /** @@ -127685,7 +125784,7 @@ module.exports = 'setdata'; /***/ }), -/* 577 */ +/* 576 */ /***/ (function(module, exports) { /** @@ -127710,7 +125809,7 @@ module.exports = 'destroy'; /***/ }), -/* 578 */ +/* 577 */ /***/ (function(module, exports) { /** @@ -127742,7 +125841,7 @@ module.exports = 'complete'; /***/ }), -/* 579 */ +/* 578 */ /***/ (function(module, exports) { /** @@ -127771,7 +125870,7 @@ module.exports = 'created'; /***/ }), -/* 580 */ +/* 579 */ /***/ (function(module, exports) { /** @@ -127797,7 +125896,7 @@ module.exports = 'error'; /***/ }), -/* 581 */ +/* 580 */ /***/ (function(module, exports) { /** @@ -127829,7 +125928,7 @@ module.exports = 'loop'; /***/ }), -/* 582 */ +/* 581 */ /***/ (function(module, exports) { /** @@ -127857,7 +125956,7 @@ module.exports = 'play'; /***/ }), -/* 583 */ +/* 582 */ /***/ (function(module, exports) { /** @@ -127882,7 +125981,7 @@ module.exports = 'seeked'; /***/ }), -/* 584 */ +/* 583 */ /***/ (function(module, exports) { /** @@ -127908,7 +126007,7 @@ module.exports = 'seeking'; /***/ }), -/* 585 */ +/* 584 */ /***/ (function(module, exports) { /** @@ -127934,7 +126033,7 @@ module.exports = 'stop'; /***/ }), -/* 586 */ +/* 585 */ /***/ (function(module, exports) { /** @@ -127960,7 +126059,7 @@ module.exports = 'timeout'; /***/ }), -/* 587 */ +/* 586 */ /***/ (function(module, exports) { /** @@ -127986,7 +126085,7 @@ module.exports = 'unlocked'; /***/ }), -/* 588 */ +/* 587 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128027,7 +126126,7 @@ module.exports = IncAlpha; /***/ }), -/* 589 */ +/* 588 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128068,7 +126167,7 @@ module.exports = IncX; /***/ }), -/* 590 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128115,7 +126214,7 @@ module.exports = IncXY; /***/ }), -/* 591 */ +/* 590 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128156,7 +126255,7 @@ module.exports = IncY; /***/ }), -/* 592 */ +/* 591 */ /***/ (function(module, exports) { /** @@ -128205,7 +126304,7 @@ module.exports = PlaceOnCircle; /***/ }), -/* 593 */ +/* 592 */ /***/ (function(module, exports) { /** @@ -128257,7 +126356,7 @@ module.exports = PlaceOnEllipse; /***/ }), -/* 594 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128266,7 +126365,7 @@ module.exports = PlaceOnEllipse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetPoints = __webpack_require__(147); +var GetPoints = __webpack_require__(150); /** * Positions an array of Game Objects on evenly spaced points of a Line. @@ -128301,7 +126400,7 @@ module.exports = PlaceOnLine; /***/ }), -/* 595 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128310,9 +126409,9 @@ module.exports = PlaceOnLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MarchingAnts = __webpack_require__(280); -var RotateLeft = __webpack_require__(281); -var RotateRight = __webpack_require__(282); +var MarchingAnts = __webpack_require__(282); +var RotateLeft = __webpack_require__(283); +var RotateRight = __webpack_require__(284); /** * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. @@ -128359,7 +126458,7 @@ module.exports = PlaceOnRectangle; /***/ }), -/* 596 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128368,7 +126467,7 @@ module.exports = PlaceOnRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BresenhamPoints = __webpack_require__(283); +var BresenhamPoints = __webpack_require__(285); /** * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. @@ -128420,7 +126519,7 @@ module.exports = PlaceOnTriangle; /***/ }), -/* 597 */ +/* 596 */ /***/ (function(module, exports) { /** @@ -128457,7 +126556,7 @@ module.exports = PlayAnimation; /***/ }), -/* 598 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128466,7 +126565,7 @@ module.exports = PlayAnimation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(144); +var Random = __webpack_require__(147); /** * Takes an array of Game Objects and positions them at random locations within the Circle. @@ -128497,7 +126596,7 @@ module.exports = RandomCircle; /***/ }), -/* 599 */ +/* 598 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128506,7 +126605,7 @@ module.exports = RandomCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(151); +var Random = __webpack_require__(154); /** * Takes an array of Game Objects and positions them at random locations within the Ellipse. @@ -128537,7 +126636,7 @@ module.exports = RandomEllipse; /***/ }), -/* 600 */ +/* 599 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128546,7 +126645,7 @@ module.exports = RandomEllipse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(148); +var Random = __webpack_require__(151); /** * Takes an array of Game Objects and positions them at random locations on the Line. @@ -128577,7 +126676,7 @@ module.exports = RandomLine; /***/ }), -/* 601 */ +/* 600 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128586,7 +126685,7 @@ module.exports = RandomLine; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(149); +var Random = __webpack_require__(152); /** * Takes an array of Game Objects and positions them at random locations within the Rectangle. @@ -128615,7 +126714,7 @@ module.exports = RandomRectangle; /***/ }), -/* 602 */ +/* 601 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128624,7 +126723,7 @@ module.exports = RandomRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Random = __webpack_require__(152); +var Random = __webpack_require__(155); /** * Takes an array of Game Objects and positions them at random locations within the Triangle. @@ -128655,7 +126754,7 @@ module.exports = RandomTriangle; /***/ }), -/* 603 */ +/* 602 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128696,7 +126795,7 @@ module.exports = Rotate; /***/ }), -/* 604 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128705,7 +126804,7 @@ module.exports = Rotate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundDistance = __webpack_require__(153); +var RotateAroundDistance = __webpack_require__(156); var DistanceBetween = __webpack_require__(53); /** @@ -128742,7 +126841,7 @@ module.exports = RotateAround; /***/ }), -/* 605 */ +/* 604 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128751,7 +126850,7 @@ module.exports = RotateAround; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MathRotateAroundDistance = __webpack_require__(153); +var MathRotateAroundDistance = __webpack_require__(156); /** * Rotates an array of Game Objects around a point by the given angle and distance. @@ -128791,7 +126890,7 @@ module.exports = RotateAroundDistance; /***/ }), -/* 606 */ +/* 605 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128832,7 +126931,7 @@ module.exports = ScaleX; /***/ }), -/* 607 */ +/* 606 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128879,7 +126978,7 @@ module.exports = ScaleXY; /***/ }), -/* 608 */ +/* 607 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128920,7 +127019,7 @@ module.exports = ScaleY; /***/ }), -/* 609 */ +/* 608 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128929,7 +127028,7 @@ module.exports = ScaleY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `alpha` @@ -128961,7 +127060,7 @@ module.exports = SetAlpha; /***/ }), -/* 610 */ +/* 609 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -128970,7 +127069,7 @@ module.exports = SetAlpha; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `blendMode` @@ -129001,7 +127100,7 @@ module.exports = SetBlendMode; /***/ }), -/* 611 */ +/* 610 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129010,7 +127109,7 @@ module.exports = SetBlendMode; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `depth` @@ -129042,7 +127141,7 @@ module.exports = SetDepth; /***/ }), -/* 612 */ +/* 611 */ /***/ (function(module, exports) { /** @@ -129081,7 +127180,7 @@ module.exports = SetHitArea; /***/ }), -/* 613 */ +/* 612 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129090,7 +127189,7 @@ module.exports = SetHitArea; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` @@ -129128,7 +127227,7 @@ module.exports = SetOrigin; /***/ }), -/* 614 */ +/* 613 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129137,7 +127236,7 @@ module.exports = SetOrigin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `rotation` @@ -129169,7 +127268,7 @@ module.exports = SetRotation; /***/ }), -/* 615 */ +/* 614 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129178,7 +127277,7 @@ module.exports = SetRotation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` @@ -129216,7 +127315,7 @@ module.exports = SetScale; /***/ }), -/* 616 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129225,7 +127324,7 @@ module.exports = SetScale; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scaleX` @@ -129257,7 +127356,7 @@ module.exports = SetScaleX; /***/ }), -/* 617 */ +/* 616 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129266,7 +127365,7 @@ module.exports = SetScaleX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scaleY` @@ -129298,7 +127397,7 @@ module.exports = SetScaleY; /***/ }), -/* 618 */ +/* 617 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129307,7 +127406,7 @@ module.exports = SetScaleY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` @@ -129345,7 +127444,7 @@ module.exports = SetScrollFactor; /***/ }), -/* 619 */ +/* 618 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129354,7 +127453,7 @@ module.exports = SetScrollFactor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` @@ -129386,7 +127485,7 @@ module.exports = SetScrollFactorX; /***/ }), -/* 620 */ +/* 619 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129395,7 +127494,7 @@ module.exports = SetScrollFactorX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` @@ -129427,7 +127526,7 @@ module.exports = SetScrollFactorY; /***/ }), -/* 621 */ +/* 620 */ /***/ (function(module, exports) { /** @@ -129466,7 +127565,7 @@ module.exports = SetTint; /***/ }), -/* 622 */ +/* 621 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129475,7 +127574,7 @@ module.exports = SetTint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `visible` @@ -129504,7 +127603,7 @@ module.exports = SetVisible; /***/ }), -/* 623 */ +/* 622 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129513,7 +127612,7 @@ module.exports = SetVisible; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `x` @@ -129545,7 +127644,7 @@ module.exports = SetX; /***/ }), -/* 624 */ +/* 623 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129554,7 +127653,7 @@ module.exports = SetX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` @@ -129592,7 +127691,7 @@ module.exports = SetXY; /***/ }), -/* 625 */ +/* 624 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129601,7 +127700,7 @@ module.exports = SetXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PropertyValueSet = __webpack_require__(26); +var PropertyValueSet = __webpack_require__(25); /** * Takes an array of Game Objects, or any objects that have the public property `y` @@ -129633,7 +127732,7 @@ module.exports = SetY; /***/ }), -/* 626 */ +/* 625 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129763,7 +127862,7 @@ module.exports = ShiftPosition; /***/ }), -/* 627 */ +/* 626 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129772,7 +127871,7 @@ module.exports = ShiftPosition; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayShuffle = __webpack_require__(110); +var ArrayShuffle = __webpack_require__(114); /** * Shuffles the array in place. The shuffled array is both modified and returned. @@ -129796,7 +127895,7 @@ module.exports = Shuffle; /***/ }), -/* 628 */ +/* 627 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129805,7 +127904,7 @@ module.exports = Shuffle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MathSmootherStep = __webpack_require__(154); +var MathSmootherStep = __webpack_require__(157); /** * Smootherstep is a sigmoid-like interpolation and clamping function. @@ -129854,7 +127953,7 @@ module.exports = SmootherStep; /***/ }), -/* 629 */ +/* 628 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -129863,7 +127962,7 @@ module.exports = SmootherStep; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MathSmoothStep = __webpack_require__(155); +var MathSmoothStep = __webpack_require__(158); /** * Smoothstep is a sigmoid-like interpolation and clamping function. @@ -129912,7 +128011,7 @@ module.exports = SmoothStep; /***/ }), -/* 630 */ +/* 629 */ /***/ (function(module, exports) { /** @@ -129975,7 +128074,7 @@ module.exports = Spread; /***/ }), -/* 631 */ +/* 630 */ /***/ (function(module, exports) { /** @@ -130011,7 +128110,7 @@ module.exports = ToggleVisible; /***/ }), -/* 632 */ +/* 631 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130060,7 +128159,7 @@ module.exports = WrapInRectangle; /***/ }), -/* 633 */ +/* 632 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130075,16 +128174,16 @@ module.exports = WrapInRectangle; module.exports = { - Animation: __webpack_require__(145), - AnimationFrame: __webpack_require__(266), - AnimationManager: __webpack_require__(284), - Events: __webpack_require__(107) + Animation: __webpack_require__(148), + AnimationFrame: __webpack_require__(268), + AnimationManager: __webpack_require__(286), + Events: __webpack_require__(111) }; /***/ }), -/* 634 */ +/* 633 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130099,15 +128198,15 @@ module.exports = { module.exports = { - BaseCache: __webpack_require__(285), - CacheManager: __webpack_require__(287), - Events: __webpack_require__(286) + BaseCache: __webpack_require__(287), + CacheManager: __webpack_require__(289), + Events: __webpack_require__(288) }; /***/ }), -/* 635 */ +/* 634 */ /***/ (function(module, exports) { /** @@ -130132,7 +128231,7 @@ module.exports = 'add'; /***/ }), -/* 636 */ +/* 635 */ /***/ (function(module, exports) { /** @@ -130157,7 +128256,7 @@ module.exports = 'remove'; /***/ }), -/* 637 */ +/* 636 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130176,14 +128275,14 @@ module.exports = 'remove'; module.exports = { - Controls: __webpack_require__(638), - Scene2D: __webpack_require__(641) + Controls: __webpack_require__(637), + Scene2D: __webpack_require__(640) }; /***/ }), -/* 638 */ +/* 637 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130198,14 +128297,14 @@ module.exports = { module.exports = { - FixedKeyControl: __webpack_require__(639), - SmoothedKeyControl: __webpack_require__(640) + FixedKeyControl: __webpack_require__(638), + SmoothedKeyControl: __webpack_require__(639) }; /***/ }), -/* 639 */ +/* 638 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130511,7 +128610,7 @@ module.exports = FixedKeyControl; /***/ }), -/* 640 */ +/* 639 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -130994,7 +129093,7 @@ module.exports = SmoothedKeyControl; /***/ }), -/* 641 */ +/* 640 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131009,17 +129108,17 @@ module.exports = SmoothedKeyControl; module.exports = { - Camera: __webpack_require__(288), - BaseCamera: __webpack_require__(89), - CameraManager: __webpack_require__(694), - Effects: __webpack_require__(296), + Camera: __webpack_require__(290), + BaseCamera: __webpack_require__(91), + CameraManager: __webpack_require__(693), + Effects: __webpack_require__(298), Events: __webpack_require__(48) }; /***/ }), -/* 642 */ +/* 641 */ /***/ (function(module, exports) { /** @@ -131042,7 +129141,7 @@ module.exports = 'cameradestroy'; /***/ }), -/* 643 */ +/* 642 */ /***/ (function(module, exports) { /** @@ -131068,7 +129167,7 @@ module.exports = 'camerafadeincomplete'; /***/ }), -/* 644 */ +/* 643 */ /***/ (function(module, exports) { /** @@ -131098,7 +129197,7 @@ module.exports = 'camerafadeinstart'; /***/ }), -/* 645 */ +/* 644 */ /***/ (function(module, exports) { /** @@ -131124,7 +129223,7 @@ module.exports = 'camerafadeoutcomplete'; /***/ }), -/* 646 */ +/* 645 */ /***/ (function(module, exports) { /** @@ -131154,7 +129253,7 @@ module.exports = 'camerafadeoutstart'; /***/ }), -/* 647 */ +/* 646 */ /***/ (function(module, exports) { /** @@ -131178,7 +129277,7 @@ module.exports = 'cameraflashcomplete'; /***/ }), -/* 648 */ +/* 647 */ /***/ (function(module, exports) { /** @@ -131206,7 +129305,7 @@ module.exports = 'cameraflashstart'; /***/ }), -/* 649 */ +/* 648 */ /***/ (function(module, exports) { /** @@ -131230,7 +129329,7 @@ module.exports = 'camerapancomplete'; /***/ }), -/* 650 */ +/* 649 */ /***/ (function(module, exports) { /** @@ -131257,7 +129356,7 @@ module.exports = 'camerapanstart'; /***/ }), -/* 651 */ +/* 650 */ /***/ (function(module, exports) { /** @@ -131283,7 +129382,7 @@ module.exports = 'postrender'; /***/ }), -/* 652 */ +/* 651 */ /***/ (function(module, exports) { /** @@ -131309,7 +129408,7 @@ module.exports = 'prerender'; /***/ }), -/* 653 */ +/* 652 */ /***/ (function(module, exports) { /** @@ -131333,7 +129432,7 @@ module.exports = 'camerashakecomplete'; /***/ }), -/* 654 */ +/* 653 */ /***/ (function(module, exports) { /** @@ -131359,7 +129458,7 @@ module.exports = 'camerashakestart'; /***/ }), -/* 655 */ +/* 654 */ /***/ (function(module, exports) { /** @@ -131383,7 +129482,7 @@ module.exports = 'camerazoomcomplete'; /***/ }), -/* 656 */ +/* 655 */ /***/ (function(module, exports) { /** @@ -131409,7 +129508,7 @@ module.exports = 'camerazoomstart'; /***/ }), -/* 657 */ +/* 656 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131418,7 +129517,7 @@ module.exports = 'camerazoomstart'; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Events = __webpack_require__(48); @@ -131797,7 +129896,7 @@ module.exports = Fade; /***/ }), -/* 658 */ +/* 657 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -131806,7 +129905,7 @@ module.exports = Fade; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Events = __webpack_require__(48); @@ -132148,7 +130247,7 @@ module.exports = Flash; /***/ }), -/* 659 */ +/* 658 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -132157,9 +130256,9 @@ module.exports = Flash; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var EaseMap = __webpack_require__(163); +var EaseMap = __webpack_require__(166); var Events = __webpack_require__(48); var Vector2 = __webpack_require__(3); @@ -132473,7 +130572,7 @@ module.exports = Pan; /***/ }), -/* 660 */ +/* 659 */ /***/ (function(module, exports) { /** @@ -132504,7 +130603,7 @@ module.exports = In; /***/ }), -/* 661 */ +/* 660 */ /***/ (function(module, exports) { /** @@ -132535,7 +130634,7 @@ module.exports = Out; /***/ }), -/* 662 */ +/* 661 */ /***/ (function(module, exports) { /** @@ -132575,7 +130674,7 @@ module.exports = InOut; /***/ }), -/* 663 */ +/* 662 */ /***/ (function(module, exports) { /** @@ -132620,7 +130719,7 @@ module.exports = In; /***/ }), -/* 664 */ +/* 663 */ /***/ (function(module, exports) { /** @@ -132663,7 +130762,7 @@ module.exports = Out; /***/ }), -/* 665 */ +/* 664 */ /***/ (function(module, exports) { /** @@ -132727,7 +130826,7 @@ module.exports = InOut; /***/ }), -/* 666 */ +/* 665 */ /***/ (function(module, exports) { /** @@ -132755,7 +130854,7 @@ module.exports = In; /***/ }), -/* 667 */ +/* 666 */ /***/ (function(module, exports) { /** @@ -132783,7 +130882,7 @@ module.exports = Out; /***/ }), -/* 668 */ +/* 667 */ /***/ (function(module, exports) { /** @@ -132818,7 +130917,7 @@ module.exports = InOut; /***/ }), -/* 669 */ +/* 668 */ /***/ (function(module, exports) { /** @@ -132846,7 +130945,7 @@ module.exports = In; /***/ }), -/* 670 */ +/* 669 */ /***/ (function(module, exports) { /** @@ -132874,7 +130973,7 @@ module.exports = Out; /***/ }), -/* 671 */ +/* 670 */ /***/ (function(module, exports) { /** @@ -132909,7 +131008,7 @@ module.exports = InOut; /***/ }), -/* 672 */ +/* 671 */ /***/ (function(module, exports) { /** @@ -132964,7 +131063,7 @@ module.exports = In; /***/ }), -/* 673 */ +/* 672 */ /***/ (function(module, exports) { /** @@ -133019,7 +131118,7 @@ module.exports = Out; /***/ }), -/* 674 */ +/* 673 */ /***/ (function(module, exports) { /** @@ -133081,7 +131180,7 @@ module.exports = InOut; /***/ }), -/* 675 */ +/* 674 */ /***/ (function(module, exports) { /** @@ -133109,7 +131208,7 @@ module.exports = In; /***/ }), -/* 676 */ +/* 675 */ /***/ (function(module, exports) { /** @@ -133137,7 +131236,7 @@ module.exports = Out; /***/ }), -/* 677 */ +/* 676 */ /***/ (function(module, exports) { /** @@ -133172,7 +131271,7 @@ module.exports = InOut; /***/ }), -/* 678 */ +/* 677 */ /***/ (function(module, exports) { /** @@ -133200,7 +131299,7 @@ module.exports = Linear; /***/ }), -/* 679 */ +/* 678 */ /***/ (function(module, exports) { /** @@ -133228,7 +131327,7 @@ module.exports = In; /***/ }), -/* 680 */ +/* 679 */ /***/ (function(module, exports) { /** @@ -133256,7 +131355,7 @@ module.exports = Out; /***/ }), -/* 681 */ +/* 680 */ /***/ (function(module, exports) { /** @@ -133291,7 +131390,7 @@ module.exports = InOut; /***/ }), -/* 682 */ +/* 681 */ /***/ (function(module, exports) { /** @@ -133319,7 +131418,7 @@ module.exports = In; /***/ }), -/* 683 */ +/* 682 */ /***/ (function(module, exports) { /** @@ -133347,7 +131446,7 @@ module.exports = Out; /***/ }), -/* 684 */ +/* 683 */ /***/ (function(module, exports) { /** @@ -133382,7 +131481,7 @@ module.exports = InOut; /***/ }), -/* 685 */ +/* 684 */ /***/ (function(module, exports) { /** @@ -133410,7 +131509,7 @@ module.exports = In; /***/ }), -/* 686 */ +/* 685 */ /***/ (function(module, exports) { /** @@ -133438,7 +131537,7 @@ module.exports = Out; /***/ }), -/* 687 */ +/* 686 */ /***/ (function(module, exports) { /** @@ -133473,7 +131572,7 @@ module.exports = InOut; /***/ }), -/* 688 */ +/* 687 */ /***/ (function(module, exports) { /** @@ -133512,7 +131611,7 @@ module.exports = In; /***/ }), -/* 689 */ +/* 688 */ /***/ (function(module, exports) { /** @@ -133551,7 +131650,7 @@ module.exports = Out; /***/ }), -/* 690 */ +/* 689 */ /***/ (function(module, exports) { /** @@ -133590,7 +131689,7 @@ module.exports = InOut; /***/ }), -/* 691 */ +/* 690 */ /***/ (function(module, exports) { /** @@ -133632,7 +131731,7 @@ module.exports = Stepped; /***/ }), -/* 692 */ +/* 691 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -133641,7 +131740,7 @@ module.exports = Stepped; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); var Events = __webpack_require__(48); var Vector2 = __webpack_require__(3); @@ -133951,7 +132050,7 @@ module.exports = Shake; /***/ }), -/* 693 */ +/* 692 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -133960,9 +132059,9 @@ module.exports = Shake; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var EaseMap = __webpack_require__(163); +var EaseMap = __webpack_require__(166); var Events = __webpack_require__(48); /** @@ -134244,7 +132343,7 @@ module.exports = Zoom; /***/ }), -/* 694 */ +/* 693 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -134253,13 +132352,13 @@ module.exports = Zoom; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Camera = __webpack_require__(288); +var Camera = __webpack_require__(290); var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); +var PluginCache = __webpack_require__(23); var RectangleContains = __webpack_require__(47); -var ScaleEvents = __webpack_require__(90); -var SceneEvents = __webpack_require__(22); +var ScaleEvents = __webpack_require__(92); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -134992,7 +133091,7 @@ module.exports = CameraManager; /***/ }), -/* 695 */ +/* 694 */ /***/ (function(module, exports) { /** @@ -135011,7 +133110,7 @@ module.exports = 'enterfullscreen'; /***/ }), -/* 696 */ +/* 695 */ /***/ (function(module, exports) { /** @@ -135030,7 +133129,7 @@ module.exports = 'fullscreenfailed'; /***/ }), -/* 697 */ +/* 696 */ /***/ (function(module, exports) { /** @@ -135049,7 +133148,7 @@ module.exports = 'fullscreenunsupported'; /***/ }), -/* 698 */ +/* 697 */ /***/ (function(module, exports) { /** @@ -135069,7 +133168,7 @@ module.exports = 'leavefullscreen'; /***/ }), -/* 699 */ +/* 698 */ /***/ (function(module, exports) { /** @@ -135090,7 +133189,7 @@ module.exports = 'orientationchange'; /***/ }), -/* 700 */ +/* 699 */ /***/ (function(module, exports) { /** @@ -135121,7 +133220,7 @@ module.exports = 'resize'; /***/ }), -/* 701 */ +/* 700 */ /***/ (function(module, exports) { /** @@ -135146,7 +133245,7 @@ module.exports = 'boot'; /***/ }), -/* 702 */ +/* 701 */ /***/ (function(module, exports) { /** @@ -135175,7 +133274,7 @@ module.exports = 'create'; /***/ }), -/* 703 */ +/* 702 */ /***/ (function(module, exports) { /** @@ -135202,7 +133301,7 @@ module.exports = 'destroy'; /***/ }), -/* 704 */ +/* 703 */ /***/ (function(module, exports) { /** @@ -135229,7 +133328,7 @@ module.exports = 'pause'; /***/ }), -/* 705 */ +/* 704 */ /***/ (function(module, exports) { /** @@ -135266,7 +133365,7 @@ module.exports = 'postupdate'; /***/ }), -/* 706 */ +/* 705 */ /***/ (function(module, exports) { /** @@ -135303,7 +133402,7 @@ module.exports = 'preupdate'; /***/ }), -/* 707 */ +/* 706 */ /***/ (function(module, exports) { /** @@ -135331,7 +133430,7 @@ module.exports = 'ready'; /***/ }), -/* 708 */ +/* 707 */ /***/ (function(module, exports) { /** @@ -135367,7 +133466,7 @@ module.exports = 'render'; /***/ }), -/* 709 */ +/* 708 */ /***/ (function(module, exports) { /** @@ -135394,7 +133493,7 @@ module.exports = 'resume'; /***/ }), -/* 710 */ +/* 709 */ /***/ (function(module, exports) { /** @@ -135424,7 +133523,7 @@ module.exports = 'shutdown'; /***/ }), -/* 711 */ +/* 710 */ /***/ (function(module, exports) { /** @@ -135451,7 +133550,7 @@ module.exports = 'sleep'; /***/ }), -/* 712 */ +/* 711 */ /***/ (function(module, exports) { /** @@ -135476,7 +133575,7 @@ module.exports = 'start'; /***/ }), -/* 713 */ +/* 712 */ /***/ (function(module, exports) { /** @@ -135512,7 +133611,7 @@ module.exports = 'transitioncomplete'; /***/ }), -/* 714 */ +/* 713 */ /***/ (function(module, exports) { /** @@ -135549,7 +133648,7 @@ module.exports = 'transitioninit'; /***/ }), -/* 715 */ +/* 714 */ /***/ (function(module, exports) { /** @@ -135583,7 +133682,7 @@ module.exports = 'transitionout'; /***/ }), -/* 716 */ +/* 715 */ /***/ (function(module, exports) { /** @@ -135623,7 +133722,7 @@ module.exports = 'transitionstart'; /***/ }), -/* 717 */ +/* 716 */ /***/ (function(module, exports) { /** @@ -135658,7 +133757,7 @@ module.exports = 'transitionwake'; /***/ }), -/* 718 */ +/* 717 */ /***/ (function(module, exports) { /** @@ -135695,7 +133794,7 @@ module.exports = 'update'; /***/ }), -/* 719 */ +/* 718 */ /***/ (function(module, exports) { /** @@ -135722,7 +133821,7 @@ module.exports = 'wake'; /***/ }), -/* 720 */ +/* 719 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135737,18 +133836,18 @@ module.exports = 'wake'; module.exports = { - Config: __webpack_require__(309), - CreateRenderer: __webpack_require__(333), - DebugHeader: __webpack_require__(337), - Events: __webpack_require__(19), - TimeStep: __webpack_require__(338), - VisibilityHandler: __webpack_require__(340) + Config: __webpack_require__(311), + CreateRenderer: __webpack_require__(334), + DebugHeader: __webpack_require__(336), + Events: __webpack_require__(18), + TimeStep: __webpack_require__(337), + VisibilityHandler: __webpack_require__(339) }; /***/ }), -/* 721 */ +/* 720 */ /***/ (function(module, exports) { // shim for using process in browser @@ -135938,7 +134037,7 @@ process.umask = function() { return 0; }; /***/ }), -/* 722 */ +/* 721 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -135947,7 +134046,7 @@ process.umask = function() { return 0; }; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Browser = __webpack_require__(113); +var Browser = __webpack_require__(117); /** * Determines the input support of the browser running this Phaser Game instance. @@ -136013,7 +134112,7 @@ module.exports = init(); /***/ }), -/* 723 */ +/* 722 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136022,7 +134121,7 @@ module.exports = init(); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Browser = __webpack_require__(113); +var Browser = __webpack_require__(117); /** * Determines the audio playback capabilities of the device running this Phaser Game instance. @@ -136138,7 +134237,7 @@ module.exports = init(); /***/ }), -/* 724 */ +/* 723 */ /***/ (function(module, exports) { /** @@ -136225,7 +134324,7 @@ module.exports = init(); /***/ }), -/* 725 */ +/* 724 */ /***/ (function(module, exports) { /** @@ -136329,7 +134428,7 @@ module.exports = init(); /***/ }), -/* 726 */ +/* 725 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136344,23 +134443,23 @@ module.exports = init(); module.exports = { - Between: __webpack_require__(312), - BetweenPoints: __webpack_require__(727), - BetweenPointsY: __webpack_require__(728), - BetweenY: __webpack_require__(729), - CounterClockwise: __webpack_require__(730), - Normalize: __webpack_require__(313), - Reverse: __webpack_require__(731), - RotateTo: __webpack_require__(732), - ShortestBetween: __webpack_require__(733), - Wrap: __webpack_require__(230), - WrapDegrees: __webpack_require__(231) + Between: __webpack_require__(314), + BetweenPoints: __webpack_require__(726), + BetweenPointsY: __webpack_require__(727), + BetweenY: __webpack_require__(728), + CounterClockwise: __webpack_require__(729), + Normalize: __webpack_require__(315), + Reverse: __webpack_require__(730), + RotateTo: __webpack_require__(731), + ShortestBetween: __webpack_require__(732), + Wrap: __webpack_require__(232), + WrapDegrees: __webpack_require__(233) }; /***/ }), -/* 727 */ +/* 726 */ /***/ (function(module, exports) { /** @@ -136377,8 +134476,8 @@ module.exports = { * @function Phaser.Math.Angle.BetweenPoints * @since 3.0.0 * - * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. - * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. + * @param {(Phaser.Geom.Point|object)} point1 - The first point. + * @param {(Phaser.Geom.Point|object)} point2 - The second point. * * @return {number} The angle in radians. */ @@ -136391,7 +134490,7 @@ module.exports = BetweenPoints; /***/ }), -/* 728 */ +/* 727 */ /***/ (function(module, exports) { /** @@ -136409,8 +134508,8 @@ module.exports = BetweenPoints; * @function Phaser.Math.Angle.BetweenPointsY * @since 3.0.0 * - * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. - * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. + * @param {(Phaser.Geom.Point|object)} point1 - The first point. + * @param {(Phaser.Geom.Point|object)} point2 - The second point. * * @return {number} The angle in radians. */ @@ -136423,7 +134522,7 @@ module.exports = BetweenPointsY; /***/ }), -/* 729 */ +/* 728 */ /***/ (function(module, exports) { /** @@ -136457,7 +134556,7 @@ module.exports = BetweenY; /***/ }), -/* 730 */ +/* 729 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136466,7 +134565,7 @@ module.exports = BetweenY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(16); +var CONST = __webpack_require__(13); /** * Takes an angle in Phasers default clockwise format and converts it so that @@ -136502,7 +134601,7 @@ module.exports = CounterClockwise; /***/ }), -/* 731 */ +/* 730 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136511,7 +134610,7 @@ module.exports = CounterClockwise; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Normalize = __webpack_require__(313); +var Normalize = __webpack_require__(315); /** * Reverse the given angle. @@ -136532,7 +134631,7 @@ module.exports = Reverse; /***/ }), -/* 732 */ +/* 731 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136541,7 +134640,7 @@ module.exports = Reverse; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); /** * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. @@ -136599,7 +134698,7 @@ module.exports = RotateTo; /***/ }), -/* 733 */ +/* 732 */ /***/ (function(module, exports) { /** @@ -136648,7 +134747,7 @@ module.exports = ShortestBetween; /***/ }), -/* 734 */ +/* 733 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -136664,16 +134763,48 @@ module.exports = ShortestBetween; module.exports = { Between: __webpack_require__(53), - BetweenPoints: __webpack_require__(314), + BetweenPoints: __webpack_require__(734), BetweenPointsSquared: __webpack_require__(735), Chebyshev: __webpack_require__(736), Power: __webpack_require__(737), Snake: __webpack_require__(738), - Squared: __webpack_require__(315) + Squared: __webpack_require__(316) }; +/***/ }), +/* 734 */ +/***/ (function(module, exports) { + +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two points. + * + * @function Phaser.Math.Distance.BetweenPoints + * @since 3.22.0 + * + * @param {Phaser.Types.Math.Vector2Like} a - The first point. + * @param {Phaser.Types.Math.Vector2Like} b - The second point. + * + * @return {number} The distance between the points. + */ +var DistanceBetweenPoints = function (a, b) +{ + var dx = a.x - b.x; + var dy = a.y - b.y; + + return Math.sqrt(dx * dx + dy * dy); +}; + +module.exports = DistanceBetweenPoints; + + /***/ }), /* 735 */ /***/ (function(module, exports) { @@ -136824,18 +134955,18 @@ module.exports = SnakeDistance; module.exports = { - Back: __webpack_require__(297), - Bounce: __webpack_require__(298), - Circular: __webpack_require__(299), - Cubic: __webpack_require__(300), - Elastic: __webpack_require__(301), - Expo: __webpack_require__(302), - Linear: __webpack_require__(303), - Quadratic: __webpack_require__(304), - Quartic: __webpack_require__(305), - Quintic: __webpack_require__(306), - Sine: __webpack_require__(307), - Stepped: __webpack_require__(308) + Back: __webpack_require__(299), + Bounce: __webpack_require__(300), + Circular: __webpack_require__(301), + Cubic: __webpack_require__(302), + Elastic: __webpack_require__(303), + Expo: __webpack_require__(304), + Linear: __webpack_require__(305), + Quadratic: __webpack_require__(306), + Quartic: __webpack_require__(307), + Quintic: __webpack_require__(308), + Sine: __webpack_require__(309), + Stepped: __webpack_require__(310) }; @@ -136857,10 +134988,10 @@ module.exports = { module.exports = { Ceil: __webpack_require__(741), - Equal: __webpack_require__(140), + Equal: __webpack_require__(144), Floor: __webpack_require__(742), - GreaterThan: __webpack_require__(316), - LessThan: __webpack_require__(317) + GreaterThan: __webpack_require__(317), + LessThan: __webpack_require__(318) }; @@ -136945,10 +135076,10 @@ module.exports = { Bezier: __webpack_require__(744), CatmullRom: __webpack_require__(745), - CubicBezier: __webpack_require__(320), + CubicBezier: __webpack_require__(321), Linear: __webpack_require__(746), - QuadraticBezier: __webpack_require__(321), - SmoothStep: __webpack_require__(322), + QuadraticBezier: __webpack_require__(322), + SmoothStep: __webpack_require__(323), SmootherStep: __webpack_require__(747) }; @@ -136964,7 +135095,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bernstein = __webpack_require__(318); +var Bernstein = __webpack_require__(319); /** * A bezier interpolation method. @@ -137003,7 +135134,7 @@ module.exports = BezierInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CatmullRom = __webpack_require__(166); +var CatmullRom = __webpack_require__(169); /** * A Catmull-Rom interpolation method. @@ -137060,7 +135191,7 @@ module.exports = CatmullRomInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Linear = __webpack_require__(111); +var Linear = __webpack_require__(115); /** * A linear interpolation method. @@ -137107,7 +135238,7 @@ module.exports = LinearInterpolation; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SmootherStep = __webpack_require__(154); +var SmootherStep = __webpack_require__(157); /** * A Smoother Step interpolation method. @@ -137146,8 +135277,8 @@ module.exports = SmootherStepInterpolation; module.exports = { - GetNext: __webpack_require__(323), - IsSize: __webpack_require__(114), + GetNext: __webpack_require__(324), + IsSize: __webpack_require__(118), IsValue: __webpack_require__(749) }; @@ -137197,8 +135328,8 @@ module.exports = IsValuePowerOfTwo; module.exports = { - Ceil: __webpack_require__(324), - Floor: __webpack_require__(91), + Ceil: __webpack_require__(325), + Floor: __webpack_require__(93), To: __webpack_require__(751) }; @@ -138426,9 +136557,9 @@ module.exports = Within; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Vector3 = __webpack_require__(169); -var Matrix4 = __webpack_require__(331); -var Quaternion = __webpack_require__(332); +var Vector3 = __webpack_require__(172); +var Matrix4 = __webpack_require__(332); +var Quaternion = __webpack_require__(333); var tmpMat4 = new Matrix4(); var tmpQuat = new Quaternion(); @@ -138712,6 +136843,85 @@ module.exports = [ /***/ }), /* 779 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_TEXTURE_TINT_FS', + '', + 'precision mediump float;', + '', + 'uniform sampler2D uMainSampler;', + '', + 'varying vec2 outTexCoord;', + 'varying float outTintEffect;', + 'varying vec4 outTint;', + '', + 'void main()', + '{', + ' vec4 texture = texture2D(uMainSampler, outTexCoord);', + ' vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);', + ' vec4 color = texture;', + '', + ' if (outTintEffect == 0.0)', + ' {', + ' // Multiply texture tint', + ' color = texture * texel;', + ' }', + ' else if (outTintEffect == 1.0)', + ' {', + ' // Solid color + texture alpha', + ' color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);', + ' color.a = texture.a * texel.a;', + ' }', + ' else if (outTintEffect == 2.0)', + ' {', + ' // Solid color, no texture', + ' color = texel;', + ' }', + '', + ' gl_FragColor = color;', + '}', + '' +].join('\n'); + + +/***/ }), +/* 780 */ +/***/ (function(module, exports) { + +module.exports = [ + '#define SHADER_NAME PHASER_TEXTURE_TINT_VS', + '', + 'precision mediump float;', + '', + 'uniform mat4 uProjectionMatrix;', + 'uniform mat4 uViewMatrix;', + 'uniform mat4 uModelMatrix;', + '', + 'attribute vec2 inPosition;', + 'attribute vec2 inTexCoord;', + 'attribute float inTintEffect;', + 'attribute vec4 inTint;', + '', + 'varying vec2 outTexCoord;', + 'varying float outTintEffect;', + 'varying vec4 outTint;', + '', + 'void main ()', + '{', + ' gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);', + '', + ' outTexCoord = inTexCoord;', + ' outTint = inTint;', + ' outTintEffect = inTintEffect;', + '}', + '', + '' +].join('\n'); + + +/***/ }), +/* 781 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138726,14 +136936,14 @@ module.exports = [ module.exports = { - GenerateTexture: __webpack_require__(341), - Palettes: __webpack_require__(780) + GenerateTexture: __webpack_require__(340), + Palettes: __webpack_require__(782) }; /***/ }), -/* 780 */ +/* 782 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138748,17 +136958,17 @@ module.exports = { module.exports = { - ARNE16: __webpack_require__(342), - C64: __webpack_require__(781), - CGA: __webpack_require__(782), - JMP: __webpack_require__(783), - MSX: __webpack_require__(784) + ARNE16: __webpack_require__(341), + C64: __webpack_require__(783), + CGA: __webpack_require__(784), + JMP: __webpack_require__(785), + MSX: __webpack_require__(786) }; /***/ }), -/* 781 */ +/* 783 */ /***/ (function(module, exports) { /** @@ -138796,7 +137006,7 @@ module.exports = { /***/ }), -/* 782 */ +/* 784 */ /***/ (function(module, exports) { /** @@ -138834,7 +137044,7 @@ module.exports = { /***/ }), -/* 783 */ +/* 785 */ /***/ (function(module, exports) { /** @@ -138872,7 +137082,7 @@ module.exports = { /***/ }), -/* 784 */ +/* 786 */ /***/ (function(module, exports) { /** @@ -138910,7 +137120,7 @@ module.exports = { /***/ }), -/* 785 */ +/* 787 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138924,19 +137134,19 @@ module.exports = { */ module.exports = { - Path: __webpack_require__(786), + Path: __webpack_require__(788), - CubicBezier: __webpack_require__(343), - Curve: __webpack_require__(79), - Ellipse: __webpack_require__(344), - Line: __webpack_require__(345), - QuadraticBezier: __webpack_require__(346), - Spline: __webpack_require__(347) + CubicBezier: __webpack_require__(342), + Curve: __webpack_require__(80), + Ellipse: __webpack_require__(343), + Line: __webpack_require__(344), + QuadraticBezier: __webpack_require__(345), + Spline: __webpack_require__(346) }; /***/ }), -/* 786 */ +/* 788 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -138948,16 +137158,16 @@ module.exports = { // Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) var Class = __webpack_require__(0); -var CubicBezierCurve = __webpack_require__(343); -var EllipseCurve = __webpack_require__(344); +var CubicBezierCurve = __webpack_require__(342); +var EllipseCurve = __webpack_require__(343); var GameObjectFactory = __webpack_require__(5); -var LineCurve = __webpack_require__(345); -var MovePathTo = __webpack_require__(787); -var QuadraticBezierCurve = __webpack_require__(346); -var Rectangle = __webpack_require__(13); -var SplineCurve = __webpack_require__(347); +var LineCurve = __webpack_require__(344); +var MovePathTo = __webpack_require__(789); +var QuadraticBezierCurve = __webpack_require__(345); +var Rectangle = __webpack_require__(11); +var SplineCurve = __webpack_require__(346); var Vector2 = __webpack_require__(3); -var MATH_CONST = __webpack_require__(16); +var MATH_CONST = __webpack_require__(13); /** * @classdesc @@ -139785,7 +137995,7 @@ module.exports = Path; /***/ }), -/* 787 */ +/* 789 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -139925,7 +138135,7 @@ module.exports = MoveTo; /***/ }), -/* 788 */ +/* 790 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -139940,15 +138150,15 @@ module.exports = MoveTo; module.exports = { - DataManager: __webpack_require__(109), - DataManagerPlugin: __webpack_require__(789), - Events: __webpack_require__(279) + DataManager: __webpack_require__(113), + DataManagerPlugin: __webpack_require__(791), + Events: __webpack_require__(281) }; /***/ }), -/* 789 */ +/* 791 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -139958,9 +138168,9 @@ module.exports = { */ var Class = __webpack_require__(0); -var DataManager = __webpack_require__(109); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var DataManager = __webpack_require__(113); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -140075,7 +138285,7 @@ module.exports = DataManagerPlugin; /***/ }), -/* 790 */ +/* 792 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140090,72 +138300,12 @@ module.exports = DataManagerPlugin; module.exports = { - Align: __webpack_require__(791), - BaseShader: __webpack_require__(348), - Bounds: __webpack_require__(794), - Canvas: __webpack_require__(797), - Color: __webpack_require__(349), - Masks: __webpack_require__(806) - -}; - - -/***/ }), -/* 791 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = __webpack_require__(102); -var Extend = __webpack_require__(18); - -/** - * @namespace Phaser.Display.Align - */ - -var Align = { - - In: __webpack_require__(792), - To: __webpack_require__(793) - -}; - -// Merge in the consts -Align = Extend(false, Align, CONST); - -module.exports = Align; - - -/***/ }), -/* 792 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Align.In - */ - -module.exports = { - - BottomCenter: __webpack_require__(251), - BottomLeft: __webpack_require__(252), - BottomRight: __webpack_require__(253), - Center: __webpack_require__(254), - LeftCenter: __webpack_require__(256), - QuickSet: __webpack_require__(250), - RightCenter: __webpack_require__(257), - TopCenter: __webpack_require__(258), - TopLeft: __webpack_require__(259), - TopRight: __webpack_require__(260) + Align: __webpack_require__(793), + BaseShader: __webpack_require__(347), + Bounds: __webpack_require__(796), + Canvas: __webpack_require__(799), + Color: __webpack_require__(348), + Masks: __webpack_require__(808) }; @@ -140164,6 +138314,66 @@ module.exports = { /* 793 */ /***/ (function(module, exports, __webpack_require__) { +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = __webpack_require__(106); +var Extend = __webpack_require__(17); + +/** + * @namespace Phaser.Display.Align + */ + +var Align = { + + In: __webpack_require__(794), + To: __webpack_require__(795) + +}; + +// Merge in the consts +Align = Extend(false, Align, CONST); + +module.exports = Align; + + +/***/ }), +/* 794 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Align.In + */ + +module.exports = { + + BottomCenter: __webpack_require__(253), + BottomLeft: __webpack_require__(254), + BottomRight: __webpack_require__(255), + Center: __webpack_require__(256), + LeftCenter: __webpack_require__(258), + QuickSet: __webpack_require__(252), + RightCenter: __webpack_require__(259), + TopCenter: __webpack_require__(260), + TopLeft: __webpack_require__(261), + TopRight: __webpack_require__(262) + +}; + + +/***/ }), +/* 795 */ +/***/ (function(module, exports, __webpack_require__) { + /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -140176,25 +138386,25 @@ module.exports = { module.exports = { - BottomCenter: __webpack_require__(238), - BottomLeft: __webpack_require__(239), - BottomRight: __webpack_require__(240), - LeftBottom: __webpack_require__(241), - LeftCenter: __webpack_require__(242), - LeftTop: __webpack_require__(243), - QuickSet: __webpack_require__(237), - RightBottom: __webpack_require__(244), - RightCenter: __webpack_require__(245), - RightTop: __webpack_require__(246), - TopCenter: __webpack_require__(247), - TopLeft: __webpack_require__(248), - TopRight: __webpack_require__(249) + BottomCenter: __webpack_require__(240), + BottomLeft: __webpack_require__(241), + BottomRight: __webpack_require__(242), + LeftBottom: __webpack_require__(243), + LeftCenter: __webpack_require__(244), + LeftTop: __webpack_require__(245), + QuickSet: __webpack_require__(239), + RightBottom: __webpack_require__(246), + RightCenter: __webpack_require__(247), + RightTop: __webpack_require__(248), + TopCenter: __webpack_require__(249), + TopLeft: __webpack_require__(250), + TopRight: __webpack_require__(251) }; /***/ }), -/* 794 */ +/* 796 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140209,18 +138419,18 @@ module.exports = { module.exports = { - CenterOn: __webpack_require__(255), + CenterOn: __webpack_require__(257), GetBottom: __webpack_require__(38), - GetCenterX: __webpack_require__(74), - GetCenterY: __webpack_require__(76), + GetCenterX: __webpack_require__(75), + GetCenterY: __webpack_require__(77), GetLeft: __webpack_require__(40), - GetOffsetX: __webpack_require__(795), - GetOffsetY: __webpack_require__(796), + GetOffsetX: __webpack_require__(797), + GetOffsetY: __webpack_require__(798), GetRight: __webpack_require__(42), GetTop: __webpack_require__(45), SetBottom: __webpack_require__(44), - SetCenterX: __webpack_require__(75), - SetCenterY: __webpack_require__(77), + SetCenterX: __webpack_require__(76), + SetCenterY: __webpack_require__(78), SetLeft: __webpack_require__(41), SetRight: __webpack_require__(43), SetTop: __webpack_require__(39) @@ -140229,7 +138439,7 @@ module.exports = { /***/ }), -/* 795 */ +/* 797 */ /***/ (function(module, exports) { /** @@ -140259,7 +138469,7 @@ module.exports = GetOffsetX; /***/ }), -/* 796 */ +/* 798 */ /***/ (function(module, exports) { /** @@ -140289,7 +138499,7 @@ module.exports = GetOffsetY; /***/ }), -/* 797 */ +/* 799 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140304,17 +138514,17 @@ module.exports = GetOffsetY; module.exports = { - CanvasInterpolation: __webpack_require__(334), - CanvasPool: __webpack_require__(27), - Smoothing: __webpack_require__(161), - TouchAction: __webpack_require__(798), - UserSelect: __webpack_require__(799) + CanvasInterpolation: __webpack_require__(335), + CanvasPool: __webpack_require__(26), + Smoothing: __webpack_require__(164), + TouchAction: __webpack_require__(800), + UserSelect: __webpack_require__(801) }; /***/ }), -/* 798 */ +/* 800 */ /***/ (function(module, exports) { /** @@ -140349,7 +138559,7 @@ module.exports = TouchAction; /***/ }), -/* 799 */ +/* 801 */ /***/ (function(module, exports) { /** @@ -140396,7 +138606,7 @@ module.exports = UserSelect; /***/ }), -/* 800 */ +/* 802 */ /***/ (function(module, exports) { /** @@ -140436,7 +138646,7 @@ module.exports = ColorToRGBA; /***/ }), -/* 801 */ +/* 803 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140445,8 +138655,8 @@ module.exports = ColorToRGBA; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Color = __webpack_require__(32); -var HueToComponent = __webpack_require__(351); +var Color = __webpack_require__(33); +var HueToComponent = __webpack_require__(350); /** * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. @@ -140486,7 +138696,7 @@ module.exports = HSLToColor; /***/ }), -/* 802 */ +/* 804 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140495,7 +138705,7 @@ module.exports = HSLToColor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HSVToRGB = __webpack_require__(160); +var HSVToRGB = __webpack_require__(163); /** * Get HSV color wheel values in an array which will be 360 elements in size. @@ -140527,7 +138737,7 @@ module.exports = HSVColorWheel; /***/ }), -/* 803 */ +/* 805 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140536,7 +138746,7 @@ module.exports = HSVColorWheel; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Linear = __webpack_require__(111); +var Linear = __webpack_require__(115); /** * @namespace Phaser.Display.Color.Interpolate @@ -140635,7 +138845,7 @@ module.exports = { /***/ }), -/* 804 */ +/* 806 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140644,8 +138854,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Between = __webpack_require__(167); -var Color = __webpack_require__(32); +var Between = __webpack_require__(170); +var Color = __webpack_require__(33); /** * Creates a new Color object where the r, g, and b values have been set to random values @@ -140671,7 +138881,7 @@ module.exports = RandomRGB; /***/ }), -/* 805 */ +/* 807 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140680,7 +138890,7 @@ module.exports = RandomRGB; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ComponentToHex = __webpack_require__(350); +var ComponentToHex = __webpack_require__(349); /** * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. @@ -140715,7 +138925,7 @@ module.exports = RGBToString; /***/ }), -/* 806 */ +/* 808 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140730,14 +138940,14 @@ module.exports = RGBToString; module.exports = { - BitmapMask: __webpack_require__(273), - GeometryMask: __webpack_require__(274) + BitmapMask: __webpack_require__(275), + GeometryMask: __webpack_require__(276) }; /***/ }), -/* 807 */ +/* 809 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140752,13 +138962,13 @@ module.exports = { var Dom = { - AddToDOM: __webpack_require__(116), - DOMContentLoaded: __webpack_require__(352), - GetScreenOrientation: __webpack_require__(353), - GetTarget: __webpack_require__(358), - ParseXML: __webpack_require__(359), - RemoveFromDOM: __webpack_require__(173), - RequestAnimationFrame: __webpack_require__(339) + AddToDOM: __webpack_require__(120), + DOMContentLoaded: __webpack_require__(351), + GetScreenOrientation: __webpack_require__(352), + GetTarget: __webpack_require__(357), + ParseXML: __webpack_require__(358), + RemoveFromDOM: __webpack_require__(176), + RequestAnimationFrame: __webpack_require__(338) }; @@ -140766,7 +138976,7 @@ module.exports = Dom; /***/ }), -/* 808 */ +/* 810 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140779,11 +138989,11 @@ module.exports = Dom; * @namespace Phaser.Events */ -module.exports = { EventEmitter: __webpack_require__(809) }; +module.exports = { EventEmitter: __webpack_require__(811) }; /***/ }), -/* 809 */ +/* 811 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140793,8 +139003,8 @@ module.exports = { EventEmitter: __webpack_require__(809) }; */ var Class = __webpack_require__(0); -var EE = __webpack_require__(11); -var PluginCache = __webpack_require__(24); +var EE = __webpack_require__(9); +var PluginCache = __webpack_require__(23); /** * @classdesc @@ -140967,7 +139177,7 @@ module.exports = EventEmitter; /***/ }), -/* 810 */ +/* 812 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -140976,33 +139186,33 @@ module.exports = EventEmitter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AddToDOM = __webpack_require__(116); -var AnimationManager = __webpack_require__(284); -var CacheManager = __webpack_require__(287); -var CanvasPool = __webpack_require__(27); +var AddToDOM = __webpack_require__(120); +var AnimationManager = __webpack_require__(286); +var CacheManager = __webpack_require__(289); +var CanvasPool = __webpack_require__(26); var Class = __webpack_require__(0); -var Config = __webpack_require__(309); -var CreateDOMContainer = __webpack_require__(811); -var CreateRenderer = __webpack_require__(333); -var DataManager = __webpack_require__(109); -var DebugHeader = __webpack_require__(337); -var Device = __webpack_require__(310); -var DOMContentLoaded = __webpack_require__(352); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(19); -var InputManager = __webpack_require__(360); -var PluginCache = __webpack_require__(24); -var PluginManager = __webpack_require__(365); -var ScaleManager = __webpack_require__(366); -var SceneManager = __webpack_require__(368); -var TextureEvents = __webpack_require__(115); -var TextureManager = __webpack_require__(371); -var TimeStep = __webpack_require__(338); -var VisibilityHandler = __webpack_require__(340); +var Config = __webpack_require__(311); +var CreateDOMContainer = __webpack_require__(813); +var CreateRenderer = __webpack_require__(334); +var DataManager = __webpack_require__(113); +var DebugHeader = __webpack_require__(336); +var Device = __webpack_require__(312); +var DOMContentLoaded = __webpack_require__(351); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(18); +var InputManager = __webpack_require__(359); +var PluginCache = __webpack_require__(23); +var PluginManager = __webpack_require__(364); +var ScaleManager = __webpack_require__(365); +var SceneManager = __webpack_require__(367); +var TextureEvents = __webpack_require__(119); +var TextureManager = __webpack_require__(370); +var TimeStep = __webpack_require__(337); +var VisibilityHandler = __webpack_require__(339); if (true) { - var SoundManagerCreator = __webpack_require__(375); + var SoundManagerCreator = __webpack_require__(374); } if (false) @@ -141670,7 +139880,7 @@ module.exports = Game; /***/ }), -/* 811 */ +/* 813 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -141679,7 +139889,7 @@ module.exports = Game; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AddToDOM = __webpack_require__(116); +var AddToDOM = __webpack_require__(120); var CreateDOMContainer = function (game) { @@ -141714,7 +139924,7 @@ module.exports = CreateDOMContainer; /***/ }), -/* 812 */ +/* 814 */ /***/ (function(module, exports) { /** @@ -141735,7 +139945,7 @@ module.exports = 'boot'; /***/ }), -/* 813 */ +/* 815 */ /***/ (function(module, exports) { /** @@ -141756,7 +139966,7 @@ module.exports = 'destroy'; /***/ }), -/* 814 */ +/* 816 */ /***/ (function(module, exports) { /** @@ -141784,7 +139994,7 @@ module.exports = 'dragend'; /***/ }), -/* 815 */ +/* 817 */ /***/ (function(module, exports) { /** @@ -141815,7 +140025,7 @@ module.exports = 'dragenter'; /***/ }), -/* 816 */ +/* 818 */ /***/ (function(module, exports) { /** @@ -141847,7 +140057,7 @@ module.exports = 'drag'; /***/ }), -/* 817 */ +/* 819 */ /***/ (function(module, exports) { /** @@ -141878,7 +140088,7 @@ module.exports = 'dragleave'; /***/ }), -/* 818 */ +/* 820 */ /***/ (function(module, exports) { /** @@ -141912,7 +140122,7 @@ module.exports = 'dragover'; /***/ }), -/* 819 */ +/* 821 */ /***/ (function(module, exports) { /** @@ -141942,7 +140152,7 @@ module.exports = 'dragstart'; /***/ }), -/* 820 */ +/* 822 */ /***/ (function(module, exports) { /** @@ -141971,7 +140181,7 @@ module.exports = 'drop'; /***/ }), -/* 821 */ +/* 823 */ /***/ (function(module, exports) { /** @@ -141998,7 +140208,7 @@ module.exports = 'gameout'; /***/ }), -/* 822 */ +/* 824 */ /***/ (function(module, exports) { /** @@ -142025,7 +140235,7 @@ module.exports = 'gameover'; /***/ }), -/* 823 */ +/* 825 */ /***/ (function(module, exports) { /** @@ -142066,7 +140276,7 @@ module.exports = 'gameobjectdown'; /***/ }), -/* 824 */ +/* 826 */ /***/ (function(module, exports) { /** @@ -142097,7 +140307,7 @@ module.exports = 'dragend'; /***/ }), -/* 825 */ +/* 827 */ /***/ (function(module, exports) { /** @@ -142127,7 +140337,7 @@ module.exports = 'dragenter'; /***/ }), -/* 826 */ +/* 828 */ /***/ (function(module, exports) { /** @@ -142158,7 +140368,7 @@ module.exports = 'drag'; /***/ }), -/* 827 */ +/* 829 */ /***/ (function(module, exports) { /** @@ -142188,7 +140398,7 @@ module.exports = 'dragleave'; /***/ }), -/* 828 */ +/* 830 */ /***/ (function(module, exports) { /** @@ -142221,7 +140431,7 @@ module.exports = 'dragover'; /***/ }), -/* 829 */ +/* 831 */ /***/ (function(module, exports) { /** @@ -142255,7 +140465,7 @@ module.exports = 'dragstart'; /***/ }), -/* 830 */ +/* 832 */ /***/ (function(module, exports) { /** @@ -142285,7 +140495,7 @@ module.exports = 'drop'; /***/ }), -/* 831 */ +/* 833 */ /***/ (function(module, exports) { /** @@ -142326,7 +140536,7 @@ module.exports = 'gameobjectmove'; /***/ }), -/* 832 */ +/* 834 */ /***/ (function(module, exports) { /** @@ -142367,7 +140577,7 @@ module.exports = 'gameobjectout'; /***/ }), -/* 833 */ +/* 835 */ /***/ (function(module, exports) { /** @@ -142408,7 +140618,7 @@ module.exports = 'gameobjectover'; /***/ }), -/* 834 */ +/* 836 */ /***/ (function(module, exports) { /** @@ -142449,7 +140659,7 @@ module.exports = 'pointerdown'; /***/ }), -/* 835 */ +/* 837 */ /***/ (function(module, exports) { /** @@ -142490,7 +140700,7 @@ module.exports = 'pointermove'; /***/ }), -/* 836 */ +/* 838 */ /***/ (function(module, exports) { /** @@ -142529,7 +140739,7 @@ module.exports = 'pointerout'; /***/ }), -/* 837 */ +/* 839 */ /***/ (function(module, exports) { /** @@ -142570,7 +140780,7 @@ module.exports = 'pointerover'; /***/ }), -/* 838 */ +/* 840 */ /***/ (function(module, exports) { /** @@ -142611,7 +140821,7 @@ module.exports = 'pointerup'; /***/ }), -/* 839 */ +/* 841 */ /***/ (function(module, exports) { /** @@ -142653,7 +140863,7 @@ module.exports = 'wheel'; /***/ }), -/* 840 */ +/* 842 */ /***/ (function(module, exports) { /** @@ -142694,7 +140904,7 @@ module.exports = 'gameobjectup'; /***/ }), -/* 841 */ +/* 843 */ /***/ (function(module, exports) { /** @@ -142738,7 +140948,7 @@ module.exports = 'gameobjectwheel'; /***/ }), -/* 842 */ +/* 844 */ /***/ (function(module, exports) { /** @@ -142759,7 +140969,7 @@ module.exports = 'boot'; /***/ }), -/* 843 */ +/* 845 */ /***/ (function(module, exports) { /** @@ -142784,7 +140994,7 @@ module.exports = 'process'; /***/ }), -/* 844 */ +/* 846 */ /***/ (function(module, exports) { /** @@ -142805,7 +141015,7 @@ module.exports = 'update'; /***/ }), -/* 845 */ +/* 847 */ /***/ (function(module, exports) { /** @@ -142840,7 +141050,7 @@ module.exports = 'pointerdown'; /***/ }), -/* 846 */ +/* 848 */ /***/ (function(module, exports) { /** @@ -142874,7 +141084,7 @@ module.exports = 'pointerdownoutside'; /***/ }), -/* 847 */ +/* 849 */ /***/ (function(module, exports) { /** @@ -142909,7 +141119,7 @@ module.exports = 'pointermove'; /***/ }), -/* 848 */ +/* 850 */ /***/ (function(module, exports) { /** @@ -142944,7 +141154,7 @@ module.exports = 'pointerout'; /***/ }), -/* 849 */ +/* 851 */ /***/ (function(module, exports) { /** @@ -142979,7 +141189,7 @@ module.exports = 'pointerover'; /***/ }), -/* 850 */ +/* 852 */ /***/ (function(module, exports) { /** @@ -143014,7 +141224,7 @@ module.exports = 'pointerup'; /***/ }), -/* 851 */ +/* 853 */ /***/ (function(module, exports) { /** @@ -143048,7 +141258,7 @@ module.exports = 'pointerupoutside'; /***/ }), -/* 852 */ +/* 854 */ /***/ (function(module, exports) { /** @@ -143086,7 +141296,7 @@ module.exports = 'wheel'; /***/ }), -/* 853 */ +/* 855 */ /***/ (function(module, exports) { /** @@ -143110,7 +141320,7 @@ module.exports = 'pointerlockchange'; /***/ }), -/* 854 */ +/* 856 */ /***/ (function(module, exports) { /** @@ -143132,7 +141342,7 @@ module.exports = 'preupdate'; /***/ }), -/* 855 */ +/* 857 */ /***/ (function(module, exports) { /** @@ -143153,7 +141363,7 @@ module.exports = 'shutdown'; /***/ }), -/* 856 */ +/* 858 */ /***/ (function(module, exports) { /** @@ -143175,7 +141385,7 @@ module.exports = 'start'; /***/ }), -/* 857 */ +/* 859 */ /***/ (function(module, exports) { /** @@ -143200,7 +141410,7 @@ module.exports = 'update'; /***/ }), -/* 858 */ +/* 860 */ /***/ (function(module, exports) { /** @@ -143259,7 +141469,7 @@ module.exports = GetInnerHeight; /***/ }), -/* 859 */ +/* 861 */ /***/ (function(module, exports) { /** @@ -143289,7 +141499,7 @@ module.exports = 'addfile'; /***/ }), -/* 860 */ +/* 862 */ /***/ (function(module, exports) { /** @@ -143317,7 +141527,7 @@ module.exports = 'complete'; /***/ }), -/* 861 */ +/* 863 */ /***/ (function(module, exports) { /** @@ -143346,7 +141556,7 @@ module.exports = 'filecomplete'; /***/ }), -/* 862 */ +/* 864 */ /***/ (function(module, exports) { /** @@ -143400,7 +141610,7 @@ module.exports = 'filecomplete-'; /***/ }), -/* 863 */ +/* 865 */ /***/ (function(module, exports) { /** @@ -143425,7 +141635,7 @@ module.exports = 'loaderror'; /***/ }), -/* 864 */ +/* 866 */ /***/ (function(module, exports) { /** @@ -143451,7 +141661,7 @@ module.exports = 'load'; /***/ }), -/* 865 */ +/* 867 */ /***/ (function(module, exports) { /** @@ -143478,7 +141688,7 @@ module.exports = 'fileprogress'; /***/ }), -/* 866 */ +/* 868 */ /***/ (function(module, exports) { /** @@ -143507,7 +141717,7 @@ module.exports = 'postprocess'; /***/ }), -/* 867 */ +/* 869 */ /***/ (function(module, exports) { /** @@ -143532,7 +141742,7 @@ module.exports = 'progress'; /***/ }), -/* 868 */ +/* 870 */ /***/ (function(module, exports) { /** @@ -143559,7 +141769,7 @@ module.exports = 'start'; /***/ }), -/* 869 */ +/* 871 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143569,7 +141779,7 @@ module.exports = 'start'; */ var GetFastValue = __webpack_require__(2); -var UppercaseFirst = __webpack_require__(176); +var UppercaseFirst = __webpack_require__(179); /** * Builds an array of which physics plugins should be activated for the given Scene. @@ -143621,7 +141831,7 @@ module.exports = GetPhysicsPlugins; /***/ }), -/* 870 */ +/* 872 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143668,7 +141878,7 @@ module.exports = GetScenePlugins; /***/ }), -/* 871 */ +/* 873 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143729,7 +141939,7 @@ module.exports = InjectionMap; /***/ }), -/* 872 */ +/* 874 */ /***/ (function(module, exports) { /** @@ -143810,7 +142020,7 @@ module.exports = AtlasXML; /***/ }), -/* 873 */ +/* 875 */ /***/ (function(module, exports) { /** @@ -143845,7 +142055,7 @@ module.exports = Canvas; /***/ }), -/* 874 */ +/* 876 */ /***/ (function(module, exports) { /** @@ -143880,7 +142090,7 @@ module.exports = Image; /***/ }), -/* 875 */ +/* 877 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143889,7 +142099,7 @@ module.exports = Image; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); +var Clone = __webpack_require__(67); /** * Parses a Texture Atlas JSON Array and adds the Frames to the Texture. @@ -143987,7 +142197,7 @@ module.exports = JSONArray; /***/ }), -/* 876 */ +/* 878 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -143996,7 +142206,7 @@ module.exports = JSONArray; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); +var Clone = __webpack_require__(67); /** * Parses a Texture Atlas JSON Hash and adds the Frames to the Texture. @@ -144086,7 +142296,7 @@ module.exports = JSONHash; /***/ }), -/* 877 */ +/* 879 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144110,15 +142320,15 @@ var GetFastValue = __webpack_require__(2); * * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. * @param {integer} sourceIndex - The index of the TextureSource. - * @param {integer} x - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. - * @param {integer} y - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. - * @param {integer} width - The width of the source image. - * @param {integer} height - The height of the source image. + * @param {integer} x - [description] + * @param {integer} y - [description] + * @param {integer} width - [description] + * @param {integer} height - [description] * @param {object} config - An object describing how to parse the Sprite Sheet. * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. - * @param {number} [config.startFrame=0] - The frame to start extracting from. Defaults to zero. - * @param {number} [config.endFrame=-1] - The frame to finish extracting at. Defaults to -1, which means 'all frames'. + * @param {number} [config.startFrame=0] - [description] + * @param {number} [config.endFrame=-1] - [description] * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. * @@ -144211,7 +142421,7 @@ module.exports = SpriteSheet; /***/ }), -/* 878 */ +/* 880 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -144402,7 +142612,7 @@ module.exports = SpriteSheetFromAtlas; /***/ }), -/* 879 */ +/* 881 */ /***/ (function(module, exports) { /** @@ -144572,7 +142782,7 @@ TextureImporter: /***/ }), -/* 880 */ +/* 882 */ /***/ (function(module, exports) { /** @@ -144603,7 +142813,7 @@ module.exports = 'complete'; /***/ }), -/* 881 */ +/* 883 */ /***/ (function(module, exports) { /** @@ -144633,7 +142843,7 @@ module.exports = 'decoded'; /***/ }), -/* 882 */ +/* 884 */ /***/ (function(module, exports) { /** @@ -144665,7 +142875,7 @@ module.exports = 'decodedall'; /***/ }), -/* 883 */ +/* 885 */ /***/ (function(module, exports) { /** @@ -144697,7 +142907,7 @@ module.exports = 'destroy'; /***/ }), -/* 884 */ +/* 886 */ /***/ (function(module, exports) { /** @@ -144730,7 +142940,7 @@ module.exports = 'detune'; /***/ }), -/* 885 */ +/* 887 */ /***/ (function(module, exports) { /** @@ -144758,7 +142968,7 @@ module.exports = 'detune'; /***/ }), -/* 886 */ +/* 888 */ /***/ (function(module, exports) { /** @@ -144785,7 +142995,7 @@ module.exports = 'mute'; /***/ }), -/* 887 */ +/* 889 */ /***/ (function(module, exports) { /** @@ -144813,7 +143023,7 @@ module.exports = 'rate'; /***/ }), -/* 888 */ +/* 890 */ /***/ (function(module, exports) { /** @@ -144840,7 +143050,7 @@ module.exports = 'volume'; /***/ }), -/* 889 */ +/* 891 */ /***/ (function(module, exports) { /** @@ -144874,7 +143084,7 @@ module.exports = 'loop'; /***/ }), -/* 890 */ +/* 892 */ /***/ (function(module, exports) { /** @@ -144908,7 +143118,7 @@ module.exports = 'looped'; /***/ }), -/* 891 */ +/* 893 */ /***/ (function(module, exports) { /** @@ -144941,7 +143151,7 @@ module.exports = 'mute'; /***/ }), -/* 892 */ +/* 894 */ /***/ (function(module, exports) { /** @@ -144968,7 +143178,7 @@ module.exports = 'pauseall'; /***/ }), -/* 893 */ +/* 895 */ /***/ (function(module, exports) { /** @@ -145000,7 +143210,7 @@ module.exports = 'pause'; /***/ }), -/* 894 */ +/* 896 */ /***/ (function(module, exports) { /** @@ -145031,7 +143241,7 @@ module.exports = 'play'; /***/ }), -/* 895 */ +/* 897 */ /***/ (function(module, exports) { /** @@ -145064,7 +143274,7 @@ module.exports = 'rate'; /***/ }), -/* 896 */ +/* 898 */ /***/ (function(module, exports) { /** @@ -145091,7 +143301,7 @@ module.exports = 'resumeall'; /***/ }), -/* 897 */ +/* 899 */ /***/ (function(module, exports) { /** @@ -145124,7 +143334,7 @@ module.exports = 'resume'; /***/ }), -/* 898 */ +/* 900 */ /***/ (function(module, exports) { /** @@ -145157,7 +143367,7 @@ module.exports = 'seek'; /***/ }), -/* 899 */ +/* 901 */ /***/ (function(module, exports) { /** @@ -145184,7 +143394,7 @@ module.exports = 'stopall'; /***/ }), -/* 900 */ +/* 902 */ /***/ (function(module, exports) { /** @@ -145216,7 +143426,7 @@ module.exports = 'stop'; /***/ }), -/* 901 */ +/* 903 */ /***/ (function(module, exports) { /** @@ -145243,7 +143453,7 @@ module.exports = 'unlocked'; /***/ }), -/* 902 */ +/* 904 */ /***/ (function(module, exports) { /** @@ -145276,7 +143486,7 @@ module.exports = 'volume'; /***/ }), -/* 903 */ +/* 905 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145291,105 +143501,102 @@ module.exports = 'volume'; var GameObjects = { - Events: __webpack_require__(88), + Events: __webpack_require__(90), - DisplayList: __webpack_require__(904), - GameObjectCreator: __webpack_require__(17), + DisplayList: __webpack_require__(906), + GameObjectCreator: __webpack_require__(16), GameObjectFactory: __webpack_require__(5), - UpdateList: __webpack_require__(932), + UpdateList: __webpack_require__(934), Components: __webpack_require__(12), BuildGameObject: __webpack_require__(28), - BuildGameObjectAnimation: __webpack_require__(386), + BuildGameObjectAnimation: __webpack_require__(385), GameObject: __webpack_require__(14), - BitmapText: __webpack_require__(126), - Blitter: __webpack_require__(183), - Container: __webpack_require__(184), - DOMElement: __webpack_require__(388), - DynamicBitmapText: __webpack_require__(185), - Extern: __webpack_require__(390), - Graphics: __webpack_require__(186), - Group: __webpack_require__(95), - Image: __webpack_require__(103), - Particles: __webpack_require__(964), - PathFollower: __webpack_require__(402), - RenderTexture: __webpack_require__(190), - RetroFont: __webpack_require__(973), - Rope: __webpack_require__(192), - Sprite: __webpack_require__(73), - Text: __webpack_require__(193), - TileSprite: __webpack_require__(194), - Zone: __webpack_require__(106), - Video: __webpack_require__(195), + BitmapText: __webpack_require__(129), + Blitter: __webpack_require__(186), + Container: __webpack_require__(187), + DOMElement: __webpack_require__(387), + DynamicBitmapText: __webpack_require__(188), + Extern: __webpack_require__(389), + Graphics: __webpack_require__(189), + Group: __webpack_require__(97), + Image: __webpack_require__(98), + Particles: __webpack_require__(966), + PathFollower: __webpack_require__(401), + RenderTexture: __webpack_require__(193), + RetroFont: __webpack_require__(975), + Sprite: __webpack_require__(69), + Text: __webpack_require__(195), + TileSprite: __webpack_require__(196), + Zone: __webpack_require__(110), + Video: __webpack_require__(197), // Shapes - Shape: __webpack_require__(31), - Arc: __webpack_require__(403), - Curve: __webpack_require__(404), - Ellipse: __webpack_require__(405), - Grid: __webpack_require__(406), - IsoBox: __webpack_require__(407), - IsoTriangle: __webpack_require__(408), - Line: __webpack_require__(409), - Polygon: __webpack_require__(410), - Rectangle: __webpack_require__(415), - Star: __webpack_require__(416), - Triangle: __webpack_require__(417), + Shape: __webpack_require__(30), + Arc: __webpack_require__(402), + Curve: __webpack_require__(403), + Ellipse: __webpack_require__(404), + Grid: __webpack_require__(405), + IsoBox: __webpack_require__(406), + IsoTriangle: __webpack_require__(407), + Line: __webpack_require__(408), + Polygon: __webpack_require__(409), + Rectangle: __webpack_require__(414), + Star: __webpack_require__(415), + Triangle: __webpack_require__(416), // Game Object Factories Factories: { - Blitter: __webpack_require__(1024), - Container: __webpack_require__(1025), - DOMElement: __webpack_require__(1026), - DynamicBitmapText: __webpack_require__(1027), - Extern: __webpack_require__(1028), - Graphics: __webpack_require__(1029), - Group: __webpack_require__(1030), - Image: __webpack_require__(1031), - Particles: __webpack_require__(1032), - PathFollower: __webpack_require__(1033), - RenderTexture: __webpack_require__(1034), - Rope: __webpack_require__(1035), - Sprite: __webpack_require__(1036), - StaticBitmapText: __webpack_require__(1037), - Text: __webpack_require__(1038), - TileSprite: __webpack_require__(1039), - Zone: __webpack_require__(1040), - Video: __webpack_require__(1041), + Blitter: __webpack_require__(1023), + Container: __webpack_require__(1024), + DOMElement: __webpack_require__(1025), + DynamicBitmapText: __webpack_require__(1026), + Extern: __webpack_require__(1027), + Graphics: __webpack_require__(1028), + Group: __webpack_require__(1029), + Image: __webpack_require__(1030), + Particles: __webpack_require__(1031), + PathFollower: __webpack_require__(1032), + RenderTexture: __webpack_require__(1033), + Sprite: __webpack_require__(1034), + StaticBitmapText: __webpack_require__(1035), + Text: __webpack_require__(1036), + TileSprite: __webpack_require__(1037), + Zone: __webpack_require__(1038), + Video: __webpack_require__(1039), // Shapes - Arc: __webpack_require__(1042), - Curve: __webpack_require__(1043), - Ellipse: __webpack_require__(1044), - Grid: __webpack_require__(1045), - IsoBox: __webpack_require__(1046), - IsoTriangle: __webpack_require__(1047), - Line: __webpack_require__(1048), - Polygon: __webpack_require__(1049), - Rectangle: __webpack_require__(1050), - Star: __webpack_require__(1051), - Triangle: __webpack_require__(1052) + Arc: __webpack_require__(1040), + Curve: __webpack_require__(1041), + Ellipse: __webpack_require__(1042), + Grid: __webpack_require__(1043), + IsoBox: __webpack_require__(1044), + IsoTriangle: __webpack_require__(1045), + Line: __webpack_require__(1046), + Polygon: __webpack_require__(1047), + Rectangle: __webpack_require__(1048), + Star: __webpack_require__(1049), + Triangle: __webpack_require__(1050) }, Creators: { - Blitter: __webpack_require__(1053), - Container: __webpack_require__(1054), - DynamicBitmapText: __webpack_require__(1055), - Graphics: __webpack_require__(1056), - Group: __webpack_require__(1057), - Image: __webpack_require__(1058), - Particles: __webpack_require__(1059), - RenderTexture: __webpack_require__(1060), - Rope: __webpack_require__(1061), - Sprite: __webpack_require__(1062), - StaticBitmapText: __webpack_require__(1063), - Text: __webpack_require__(1064), - TileSprite: __webpack_require__(1065), - Zone: __webpack_require__(1066), - Video: __webpack_require__(1067) + Blitter: __webpack_require__(1051), + Container: __webpack_require__(1052), + DynamicBitmapText: __webpack_require__(1053), + Graphics: __webpack_require__(1054), + Group: __webpack_require__(1055), + Image: __webpack_require__(1056), + Particles: __webpack_require__(1057), + RenderTexture: __webpack_require__(1058), + Sprite: __webpack_require__(1059), + StaticBitmapText: __webpack_require__(1060), + Text: __webpack_require__(1061), + TileSprite: __webpack_require__(1062), + Zone: __webpack_require__(1063), + Video: __webpack_require__(1064) } }; @@ -145397,29 +143604,29 @@ var GameObjects = { if (true) { // WebGL only Game Objects - GameObjects.Mesh = __webpack_require__(128); - GameObjects.Quad = __webpack_require__(198); - GameObjects.Shader = __webpack_require__(199); + GameObjects.Mesh = __webpack_require__(130); + GameObjects.Quad = __webpack_require__(200); + GameObjects.Shader = __webpack_require__(201); - GameObjects.Factories.Mesh = __webpack_require__(1074); - GameObjects.Factories.Quad = __webpack_require__(1075); - GameObjects.Factories.Shader = __webpack_require__(1076); + GameObjects.Factories.Mesh = __webpack_require__(1071); + GameObjects.Factories.Quad = __webpack_require__(1072); + GameObjects.Factories.Shader = __webpack_require__(1073); - GameObjects.Creators.Mesh = __webpack_require__(1077); - GameObjects.Creators.Quad = __webpack_require__(1078); - GameObjects.Creators.Shader = __webpack_require__(1079); + GameObjects.Creators.Mesh = __webpack_require__(1074); + GameObjects.Creators.Quad = __webpack_require__(1075); + GameObjects.Creators.Shader = __webpack_require__(1076); - GameObjects.Light = __webpack_require__(421); + GameObjects.Light = __webpack_require__(420); - __webpack_require__(422); - __webpack_require__(1080); + __webpack_require__(421); + __webpack_require__(1077); } module.exports = GameObjects; /***/ }), -/* 904 */ +/* 906 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145429,10 +143636,10 @@ module.exports = GameObjects; */ var Class = __webpack_require__(0); -var List = __webpack_require__(123); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var StableSort = __webpack_require__(125); +var List = __webpack_require__(126); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var StableSort = __webpack_require__(128); /** * @classdesc @@ -145624,7 +143831,7 @@ module.exports = DisplayList; /***/ }), -/* 905 */ +/* 907 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145639,21 +143846,21 @@ module.exports = DisplayList; module.exports = { - CheckMatrix: __webpack_require__(179), - MatrixToString: __webpack_require__(906), - ReverseColumns: __webpack_require__(907), - ReverseRows: __webpack_require__(908), - Rotate180: __webpack_require__(909), - RotateLeft: __webpack_require__(910), - RotateMatrix: __webpack_require__(124), - RotateRight: __webpack_require__(911), - TransposeMatrix: __webpack_require__(383) + CheckMatrix: __webpack_require__(182), + MatrixToString: __webpack_require__(908), + ReverseColumns: __webpack_require__(909), + ReverseRows: __webpack_require__(910), + Rotate180: __webpack_require__(911), + RotateLeft: __webpack_require__(912), + RotateMatrix: __webpack_require__(127), + RotateRight: __webpack_require__(913), + TransposeMatrix: __webpack_require__(382) }; /***/ }), -/* 906 */ +/* 908 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145662,8 +143869,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Pad = __webpack_require__(157); -var CheckMatrix = __webpack_require__(179); +var Pad = __webpack_require__(160); +var CheckMatrix = __webpack_require__(182); /** * Generates a string (which you can pass to console.log) from the given Array Matrix. @@ -145734,7 +143941,7 @@ module.exports = MatrixToString; /***/ }), -/* 907 */ +/* 909 */ /***/ (function(module, exports) { /** @@ -145765,7 +143972,7 @@ module.exports = ReverseColumns; /***/ }), -/* 908 */ +/* 910 */ /***/ (function(module, exports) { /** @@ -145801,7 +144008,7 @@ module.exports = ReverseRows; /***/ }), -/* 909 */ +/* 911 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145810,7 +144017,7 @@ module.exports = ReverseRows; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateMatrix = __webpack_require__(124); +var RotateMatrix = __webpack_require__(127); /** * Rotates the array matrix 180 degrees. @@ -145834,7 +144041,7 @@ module.exports = Rotate180; /***/ }), -/* 910 */ +/* 912 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145843,7 +144050,7 @@ module.exports = Rotate180; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateMatrix = __webpack_require__(124); +var RotateMatrix = __webpack_require__(127); /** * Rotates the array matrix to the left (or 90 degrees) @@ -145867,7 +144074,7 @@ module.exports = RotateLeft; /***/ }), -/* 911 */ +/* 913 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -145876,7 +144083,7 @@ module.exports = RotateLeft; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateMatrix = __webpack_require__(124); +var RotateMatrix = __webpack_require__(127); /** * Rotates the array matrix to the left (or -90 degrees) @@ -145900,7 +144107,7 @@ module.exports = RotateRight; /***/ }), -/* 912 */ +/* 914 */ /***/ (function(module, exports) { /** @@ -146017,7 +144224,7 @@ module.exports = Add; /***/ }), -/* 913 */ +/* 915 */ /***/ (function(module, exports) { /** @@ -146139,7 +144346,7 @@ module.exports = AddAt; /***/ }), -/* 914 */ +/* 916 */ /***/ (function(module, exports) { /** @@ -146177,7 +144384,7 @@ module.exports = BringToTop; /***/ }), -/* 915 */ +/* 917 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146186,7 +144393,7 @@ module.exports = BringToTop; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Returns the total number of elements in the array which have a property matching the given value. @@ -146229,7 +144436,7 @@ module.exports = CountAllMatching; /***/ }), -/* 916 */ +/* 918 */ /***/ (function(module, exports) { /** @@ -146275,7 +144482,7 @@ module.exports = Each; /***/ }), -/* 917 */ +/* 919 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146284,7 +144491,7 @@ module.exports = Each; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Passes each element in the array, between the start and end indexes, to the given callback. @@ -146331,7 +144538,7 @@ module.exports = EachInRange; /***/ }), -/* 918 */ +/* 920 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146340,7 +144547,7 @@ module.exports = EachInRange; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Returns all elements in the array. @@ -146393,7 +144600,7 @@ module.exports = GetAll; /***/ }), -/* 919 */ +/* 921 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146402,7 +144609,7 @@ module.exports = GetAll; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Returns the first element in the array. @@ -146452,7 +144659,7 @@ module.exports = GetFirst; /***/ }), -/* 920 */ +/* 922 */ /***/ (function(module, exports) { /** @@ -146494,7 +144701,7 @@ module.exports = MoveDown; /***/ }), -/* 921 */ +/* 923 */ /***/ (function(module, exports) { /** @@ -146541,7 +144748,7 @@ module.exports = MoveTo; /***/ }), -/* 922 */ +/* 924 */ /***/ (function(module, exports) { /** @@ -146583,7 +144790,7 @@ module.exports = MoveUp; /***/ }), -/* 923 */ +/* 925 */ /***/ (function(module, exports) { /** @@ -146647,7 +144854,7 @@ module.exports = NumberArray; /***/ }), -/* 924 */ +/* 926 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146656,7 +144863,7 @@ module.exports = NumberArray; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RoundAwayFromZero = __webpack_require__(327); +var RoundAwayFromZero = __webpack_require__(328); /** * Create an array of numbers (positive and/or negative) progressing from `start` @@ -146724,7 +144931,7 @@ module.exports = NumberArrayStep; /***/ }), -/* 925 */ +/* 927 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146733,7 +144940,7 @@ module.exports = NumberArrayStep; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SpliceOne = __webpack_require__(78); +var SpliceOne = __webpack_require__(79); /** * Removes the item from the given position in the array. @@ -146775,7 +144982,7 @@ module.exports = RemoveAt; /***/ }), -/* 926 */ +/* 928 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146784,7 +144991,7 @@ module.exports = RemoveAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Removes the item within the given range in the array. @@ -146838,7 +145045,7 @@ module.exports = RemoveBetween; /***/ }), -/* 927 */ +/* 929 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146847,7 +145054,7 @@ module.exports = RemoveBetween; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SpliceOne = __webpack_require__(78); +var SpliceOne = __webpack_require__(79); /** * Removes a random object from the given array and returns it. @@ -146876,7 +145083,7 @@ module.exports = RemoveRandomElement; /***/ }), -/* 928 */ +/* 930 */ /***/ (function(module, exports) { /** @@ -146920,7 +145127,7 @@ module.exports = Replace; /***/ }), -/* 929 */ +/* 931 */ /***/ (function(module, exports) { /** @@ -146958,7 +145165,7 @@ module.exports = SendToBack; /***/ }), -/* 930 */ +/* 932 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -146967,7 +145174,7 @@ module.exports = SendToBack; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SafeRange = __webpack_require__(66); +var SafeRange = __webpack_require__(68); /** * Scans the array for elements with the given property. If found, the property is set to the `value`. @@ -147013,7 +145220,7 @@ module.exports = SetAll; /***/ }), -/* 931 */ +/* 933 */ /***/ (function(module, exports) { /** @@ -147061,7 +145268,7 @@ module.exports = Swap; /***/ }), -/* 932 */ +/* 934 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147071,9 +145278,9 @@ module.exports = Swap; */ var Class = __webpack_require__(0); -var ProcessQueue = __webpack_require__(181); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var ProcessQueue = __webpack_require__(184); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -147362,7 +145569,7 @@ module.exports = UpdateList; /***/ }), -/* 933 */ +/* 935 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147377,14 +145584,14 @@ module.exports = UpdateList; module.exports = { - PROCESS_QUEUE_ADD: __webpack_require__(934), - PROCESS_QUEUE_REMOVE: __webpack_require__(935) + PROCESS_QUEUE_ADD: __webpack_require__(936), + PROCESS_QUEUE_REMOVE: __webpack_require__(937) }; /***/ }), -/* 934 */ +/* 936 */ /***/ (function(module, exports) { /** @@ -147411,7 +145618,7 @@ module.exports = 'add'; /***/ }), -/* 935 */ +/* 937 */ /***/ (function(module, exports) { /** @@ -147438,7 +145645,7 @@ module.exports = 'remove'; /***/ }), -/* 936 */ +/* 938 */ /***/ (function(module, exports) { /** @@ -147891,7 +146098,7 @@ module.exports = GetBitmapTextSize; /***/ }), -/* 937 */ +/* 939 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147900,7 +146107,7 @@ module.exports = GetBitmapTextSize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ParseXMLBitmapFont = __webpack_require__(182); +var ParseXMLBitmapFont = __webpack_require__(185); /** * Parse an XML Bitmap Font from an Atlas. @@ -147944,7 +146151,7 @@ module.exports = ParseFromAtlas; /***/ }), -/* 938 */ +/* 940 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147958,12 +146165,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(939); + renderWebGL = __webpack_require__(941); } if (true) { - renderCanvas = __webpack_require__(940); + renderCanvas = __webpack_require__(942); } module.exports = { @@ -147975,7 +146182,7 @@ module.exports = { /***/ }), -/* 939 */ +/* 941 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -147984,7 +146191,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -148211,7 +146418,7 @@ module.exports = BitmapTextWebGLRenderer; /***/ }), -/* 940 */ +/* 942 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148220,7 +146427,7 @@ module.exports = BitmapTextWebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -148393,7 +146600,7 @@ module.exports = BitmapTextCanvasRenderer; /***/ }), -/* 941 */ +/* 943 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148407,12 +146614,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(942); + renderWebGL = __webpack_require__(944); } if (true) { - renderCanvas = __webpack_require__(943); + renderCanvas = __webpack_require__(945); } module.exports = { @@ -148424,7 +146631,7 @@ module.exports = { /***/ }), -/* 942 */ +/* 944 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148433,7 +146640,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -148554,7 +146761,7 @@ module.exports = BlitterWebGLRenderer; /***/ }), -/* 943 */ +/* 945 */ /***/ (function(module, exports) { /** @@ -148684,7 +146891,7 @@ module.exports = BlitterCanvasRenderer; /***/ }), -/* 944 */ +/* 946 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -148694,7 +146901,7 @@ module.exports = BlitterCanvasRenderer; */ var Class = __webpack_require__(0); -var Frame = __webpack_require__(92); +var Frame = __webpack_require__(94); /** * @classdesc @@ -148841,7 +147048,7 @@ var Bob = new Class({ * * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The frame to be used during rendering. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFrame: function (frame) { @@ -148867,7 +147074,7 @@ var Bob = new Class({ * @method Phaser.GameObjects.Bob#resetFlip * @since 3.0.0 * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ resetFlip: function () { @@ -148891,7 +147098,7 @@ var Bob = new Class({ * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ reset: function (x, y, frame) { @@ -148923,7 +147130,7 @@ var Bob = new Class({ * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setPosition: function (x, y) { @@ -148941,7 +147148,7 @@ var Bob = new Class({ * * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFlipX: function (value) { @@ -148958,7 +147165,7 @@ var Bob = new Class({ * * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFlipY: function (value) { @@ -148976,7 +147183,7 @@ var Bob = new Class({ * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setFlip: function (x, y) { @@ -148996,7 +147203,7 @@ var Bob = new Class({ * * @param {boolean} value - The visible state of the Game Object. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setVisible: function (value) { @@ -149016,7 +147223,7 @@ var Bob = new Class({ * * @param {number} value - The alpha value used for this Bob. Between 0 and 1. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setAlpha: function (value) { @@ -149033,7 +147240,7 @@ var Bob = new Class({ * * @param {number} value - The tint value used for this Bob. Between 0 and 0xffffff. * - * @return {this} This Bob Game Object. + * @return {Phaser.GameObjects.Bob} This Bob Game Object. */ setTint: function (value) { @@ -149114,7 +147321,7 @@ module.exports = Bob; /***/ }), -/* 945 */ +/* 947 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149129,12 +147336,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(946); + renderWebGL = __webpack_require__(948); } if (true) { - renderCanvas = __webpack_require__(947); + renderCanvas = __webpack_require__(949); } module.exports = { @@ -149146,7 +147353,7 @@ module.exports = { /***/ }), -/* 946 */ +/* 948 */ /***/ (function(module, exports) { /** @@ -149295,7 +147502,7 @@ module.exports = ContainerWebGLRenderer; /***/ }), -/* 947 */ +/* 949 */ /***/ (function(module, exports) { /** @@ -149392,7 +147599,7 @@ module.exports = ContainerCanvasRenderer; /***/ }), -/* 948 */ +/* 950 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149406,12 +147613,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(389); + renderWebGL = __webpack_require__(388); } if (true) { - renderCanvas = __webpack_require__(389); + renderCanvas = __webpack_require__(388); } module.exports = { @@ -149423,7 +147630,7 @@ module.exports = { /***/ }), -/* 949 */ +/* 951 */ /***/ (function(module, exports) { /** @@ -149464,7 +147671,7 @@ module.exports = [ /***/ }), -/* 950 */ +/* 952 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149478,12 +147685,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(951); + renderWebGL = __webpack_require__(953); } if (true) { - renderCanvas = __webpack_require__(952); + renderCanvas = __webpack_require__(954); } module.exports = { @@ -149495,7 +147702,7 @@ module.exports = { /***/ }), -/* 951 */ +/* 953 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149504,7 +147711,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -149801,7 +148008,7 @@ module.exports = DynamicBitmapTextWebGLRenderer; /***/ }), -/* 952 */ +/* 954 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -149810,7 +148017,7 @@ module.exports = DynamicBitmapTextWebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -150012,7 +148219,7 @@ module.exports = DynamicBitmapTextCanvasRenderer; /***/ }), -/* 953 */ +/* 955 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150026,12 +148233,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(954); + renderWebGL = __webpack_require__(956); } if (true) { - renderCanvas = __webpack_require__(955); + renderCanvas = __webpack_require__(957); } module.exports = { @@ -150043,7 +148250,7 @@ module.exports = { /***/ }), -/* 954 */ +/* 956 */ /***/ (function(module, exports) { /** @@ -150112,13 +148319,13 @@ module.exports = ExternWebGLRenderer; /***/ }), -/* 955 */ +/* 957 */ /***/ (function(module, exports) { /***/ }), -/* 956 */ +/* 958 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150132,15 +148339,15 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(957); + renderWebGL = __webpack_require__(959); // Needed for Graphics.generateTexture - renderCanvas = __webpack_require__(394); + renderCanvas = __webpack_require__(393); } if (true) { - renderCanvas = __webpack_require__(394); + renderCanvas = __webpack_require__(393); } module.exports = { @@ -150152,7 +148359,7 @@ module.exports = { /***/ }), -/* 957 */ +/* 959 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150161,8 +148368,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Commands = __webpack_require__(187); -var Utils = __webpack_require__(9); +var Commands = __webpack_require__(190); +var Utils = __webpack_require__(10); // TODO: Remove the use of this var Point = function (x, y, width) @@ -150517,7 +148724,7 @@ module.exports = GraphicsWebGLRenderer; /***/ }), -/* 958 */ +/* 960 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150531,12 +148738,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(959); + renderWebGL = __webpack_require__(961); } if (true) { - renderCanvas = __webpack_require__(960); + renderCanvas = __webpack_require__(962); } module.exports = { @@ -150548,7 +148755,7 @@ module.exports = { /***/ }), -/* 959 */ +/* 961 */ /***/ (function(module, exports) { /** @@ -150581,7 +148788,7 @@ module.exports = SpriteWebGLRenderer; /***/ }), -/* 960 */ +/* 962 */ /***/ (function(module, exports) { /** @@ -150614,7 +148821,7 @@ module.exports = SpriteCanvasRenderer; /***/ }), -/* 961 */ +/* 963 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150628,12 +148835,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(962); + renderWebGL = __webpack_require__(964); } if (true) { - renderCanvas = __webpack_require__(963); + renderCanvas = __webpack_require__(965); } module.exports = { @@ -150645,7 +148852,7 @@ module.exports = { /***/ }), -/* 962 */ +/* 964 */ /***/ (function(module, exports) { /** @@ -150678,7 +148885,7 @@ module.exports = ImageWebGLRenderer; /***/ }), -/* 963 */ +/* 965 */ /***/ (function(module, exports) { /** @@ -150711,7 +148918,7 @@ module.exports = ImageCanvasRenderer; /***/ }), -/* 964 */ +/* 966 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150726,17 +148933,17 @@ module.exports = ImageCanvasRenderer; module.exports = { - GravityWell: __webpack_require__(395), - Particle: __webpack_require__(396), - ParticleEmitter: __webpack_require__(397), - ParticleEmitterManager: __webpack_require__(189), - Zones: __webpack_require__(969) + GravityWell: __webpack_require__(394), + Particle: __webpack_require__(395), + ParticleEmitter: __webpack_require__(396), + ParticleEmitterManager: __webpack_require__(192), + Zones: __webpack_require__(971) }; /***/ }), -/* 965 */ +/* 967 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -150746,8 +148953,8 @@ module.exports = { */ var Class = __webpack_require__(0); -var FloatBetween = __webpack_require__(325); -var GetEaseFunction = __webpack_require__(67); +var FloatBetween = __webpack_require__(326); +var GetEaseFunction = __webpack_require__(82); var GetFastValue = __webpack_require__(2); var Wrap = __webpack_require__(58); @@ -150950,7 +149157,7 @@ var EmitterOp = new Class({ * * @param {number} value - The value of the property. * - * @return {this} This Emitter Op object. + * @return {Phaser.GameObjects.Particles.EmitterOp} This Emitter Op object. */ onChange: function (value) { @@ -150967,7 +149174,7 @@ var EmitterOp = new Class({ * @method Phaser.GameObjects.Particles.EmitterOp#setMethods * @since 3.0.0 * - * @return {this} This Emitter Op object. + * @return {Phaser.GameObjects.Particles.EmitterOp} This Emitter Op object. */ setMethods: function () { @@ -151327,7 +149534,7 @@ module.exports = EmitterOp; /***/ }), -/* 966 */ +/* 968 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151341,12 +149548,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(967); + renderWebGL = __webpack_require__(969); } if (true) { - renderCanvas = __webpack_require__(968); + renderCanvas = __webpack_require__(970); } module.exports = { @@ -151358,7 +149565,7 @@ module.exports = { /***/ }), -/* 967 */ +/* 969 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151367,7 +149574,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -151517,7 +149724,7 @@ module.exports = ParticleManagerWebGLRenderer; /***/ }), -/* 968 */ +/* 970 */ /***/ (function(module, exports) { /** @@ -151640,7 +149847,7 @@ module.exports = ParticleManagerCanvasRenderer; /***/ }), -/* 969 */ +/* 971 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151655,15 +149862,15 @@ module.exports = ParticleManagerCanvasRenderer; module.exports = { - DeathZone: __webpack_require__(398), - EdgeZone: __webpack_require__(399), - RandomZone: __webpack_require__(401) + DeathZone: __webpack_require__(397), + EdgeZone: __webpack_require__(398), + RandomZone: __webpack_require__(400) }; /***/ }), -/* 970 */ +/* 972 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151677,12 +149884,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(971); + renderWebGL = __webpack_require__(973); } if (true) { - renderCanvas = __webpack_require__(972); + renderCanvas = __webpack_require__(974); } module.exports = { @@ -151694,7 +149901,7 @@ module.exports = { /***/ }), -/* 971 */ +/* 973 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151703,7 +149910,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -151757,7 +149964,7 @@ module.exports = RenderTextureWebGLRenderer; /***/ }), -/* 972 */ +/* 974 */ /***/ (function(module, exports) { /** @@ -151790,7 +149997,7 @@ module.exports = RenderTextureCanvasRenderer; /***/ }), -/* 973 */ +/* 975 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -151799,15 +150006,15 @@ module.exports = RenderTextureCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RETRO_FONT_CONST = __webpack_require__(974); -var Extend = __webpack_require__(18); +var RETRO_FONT_CONST = __webpack_require__(976); +var Extend = __webpack_require__(17); /** * @namespace Phaser.GameObjects.RetroFont * @since 3.6.0 */ -var RetroFont = { Parse: __webpack_require__(975) }; +var RetroFont = { Parse: __webpack_require__(977) }; // Merge in the consts RetroFont = Extend(false, RetroFont, RETRO_FONT_CONST); @@ -151816,7 +150023,7 @@ module.exports = RetroFont; /***/ }), -/* 974 */ +/* 976 */ /***/ (function(module, exports) { /** @@ -151932,7 +150139,7 @@ module.exports = RETRO_FONT_CONST; /***/ }), -/* 975 */ +/* 977 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152047,209 +150254,10 @@ var ParseRetroFont = function (scene, config) module.exports = ParseRetroFont; -/***/ }), -/* 976 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = __webpack_require__(1); -var renderCanvas = __webpack_require__(1); - -if (true) -{ - renderWebGL = __webpack_require__(977); -} - -if (true) -{ - renderCanvas = __webpack_require__(978); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; - - -/***/ }), -/* 977 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = __webpack_require__(9); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Rope#renderWebGL - * @since 3.23.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RopeWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = src.pipeline; - - renderer.setPipeline(pipeline, src); - - var camMatrix = pipeline._tempMatrix1; - var spriteMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var frame = src.frame; - var texture = frame.glTexture; - - var vertices = src.vertices; - var uvs = src.uv; - var colors = src.colors; - var alphas = src.alphas; - var alpha = src.alpha; - var getTint = Utils.getTintAppendFloatAlphaAndSwap; - var roundPixels = camera.roundPixels; - - var meshVerticesLength = vertices.length; - var vertexCount = Math.floor(meshVerticesLength * 0.5); - - // Because it's a triangle strip and we don't want lots of degenerate triangles joining things up - pipeline.flush(); - - pipeline.setTexture2D(texture, 0); - - var vertexViewF32 = pipeline.vertexViewF32; - var vertexViewU32 = pipeline.vertexViewU32; - - var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; - - var colorIndex = 0; - - var tintEffect = src.tintFill; - - if (src.dirty) - { - src.updateVertices(); - } - - var debugCallback = src.debugCallback; - var debugVerts = []; - - for (var i = 0; i < meshVerticesLength; i += 2) - { - var x = vertices[i + 0]; - var y = vertices[i + 1]; - - var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; - var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; - - if (roundPixels) - { - tx = Math.round(tx); - ty = Math.round(ty); - } - - vertexViewF32[++vertexOffset] = tx; - vertexViewF32[++vertexOffset] = ty; - vertexViewF32[++vertexOffset] = uvs[i + 0]; - vertexViewF32[++vertexOffset] = uvs[i + 1]; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = getTint(colors[colorIndex], camera.alpha * (alphas[colorIndex] * alpha)); - - colorIndex++; - - if (debugCallback) - { - debugVerts[i + 0] = tx; - debugVerts[i + 1] = ty; - } - } - - if (debugCallback) - { - debugCallback.call(src, src, meshVerticesLength, debugVerts); - } - - pipeline.vertexCount += vertexCount; -}; - -module.exports = RopeWebGLRenderer; - - /***/ }), /* 978 */ /***/ (function(module, exports) { -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This is a stub function for Rope.Render. There is no Canvas renderer for Rope objects. - * - * @method Phaser.GameObjects.Rope#renderCanvas - * @since 3.23.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var RopeCanvasRenderer = function () -{ -}; - -module.exports = RopeCanvasRenderer; - - -/***/ }), -/* 979 */ -/***/ (function(module, exports) { - /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -152329,7 +150337,7 @@ module.exports = GetTextSize; /***/ }), -/* 980 */ +/* 979 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152343,12 +150351,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(981); + renderWebGL = __webpack_require__(980); } if (true) { - renderCanvas = __webpack_require__(982); + renderCanvas = __webpack_require__(981); } module.exports = { @@ -152360,7 +150368,7 @@ module.exports = { /***/ }), -/* 981 */ +/* 980 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152369,7 +150377,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -152425,7 +150433,7 @@ module.exports = TextWebGLRenderer; /***/ }), -/* 982 */ +/* 981 */ /***/ (function(module, exports) { /** @@ -152463,7 +150471,7 @@ module.exports = TextCanvasRenderer; /***/ }), -/* 983 */ +/* 982 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -152475,7 +150483,7 @@ module.exports = TextCanvasRenderer; var Class = __webpack_require__(0); var GetAdvancedValue = __webpack_require__(15); var GetValue = __webpack_require__(6); -var MeasureText = __webpack_require__(984); +var MeasureText = __webpack_require__(983); // Key: [ Object Key, Default Value ] @@ -153516,7 +151524,7 @@ module.exports = TextStyle; /***/ }), -/* 984 */ +/* 983 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153525,7 +151533,7 @@ module.exports = TextStyle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CanvasPool = __webpack_require__(27); +var CanvasPool = __webpack_require__(26); /** * Calculates the ascent, descent and fontSize of a given font style. @@ -153651,7 +151659,7 @@ module.exports = MeasureText; /***/ }), -/* 985 */ +/* 984 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153665,12 +151673,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(986); + renderWebGL = __webpack_require__(985); } if (true) { - renderCanvas = __webpack_require__(987); + renderCanvas = __webpack_require__(986); } module.exports = { @@ -153682,7 +151690,7 @@ module.exports = { /***/ }), -/* 986 */ +/* 985 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153691,7 +151699,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -153742,7 +151750,7 @@ module.exports = TileSpriteWebGLRenderer; /***/ }), -/* 987 */ +/* 986 */ /***/ (function(module, exports) { /** @@ -153777,7 +151785,7 @@ module.exports = TileSpriteCanvasRenderer; /***/ }), -/* 988 */ +/* 987 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153791,12 +151799,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(989); + renderWebGL = __webpack_require__(988); } if (true) { - renderCanvas = __webpack_require__(990); + renderCanvas = __webpack_require__(989); } module.exports = { @@ -153808,7 +151816,7 @@ module.exports = { /***/ }), -/* 989 */ +/* 988 */ /***/ (function(module, exports) { /** @@ -153844,7 +151852,7 @@ module.exports = VideoWebGLRenderer; /***/ }), -/* 990 */ +/* 989 */ /***/ (function(module, exports) { /** @@ -153880,7 +151888,7 @@ module.exports = VideoCanvasRenderer; /***/ }), -/* 991 */ +/* 990 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153894,12 +151902,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(992); + renderWebGL = __webpack_require__(991); } if (true) { - renderCanvas = __webpack_require__(993); + renderCanvas = __webpack_require__(992); } module.exports = { @@ -153911,7 +151919,7 @@ module.exports = { /***/ }), -/* 992 */ +/* 991 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -153920,8 +151928,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -153989,7 +151997,7 @@ module.exports = ArcWebGLRenderer; /***/ }), -/* 993 */ +/* 992 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154001,7 +152009,7 @@ module.exports = ArcWebGLRenderer; var DegToRad = __webpack_require__(35); var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -154065,7 +152073,7 @@ module.exports = ArcCanvasRenderer; /***/ }), -/* 994 */ +/* 993 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154079,12 +152087,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(995); + renderWebGL = __webpack_require__(994); } if (true) { - renderCanvas = __webpack_require__(996); + renderCanvas = __webpack_require__(995); } module.exports = { @@ -154096,7 +152104,7 @@ module.exports = { /***/ }), -/* 995 */ +/* 994 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154105,8 +152113,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -154174,7 +152182,7 @@ module.exports = CurveWebGLRenderer; /***/ }), -/* 996 */ +/* 995 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154185,7 +152193,7 @@ module.exports = CurveWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -154262,7 +152270,7 @@ module.exports = CurveCanvasRenderer; /***/ }), -/* 997 */ +/* 996 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154276,12 +152284,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(998); + renderWebGL = __webpack_require__(997); } if (true) { - renderCanvas = __webpack_require__(999); + renderCanvas = __webpack_require__(998); } module.exports = { @@ -154293,7 +152301,7 @@ module.exports = { /***/ }), -/* 998 */ +/* 997 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154302,8 +152310,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -154371,7 +152379,7 @@ module.exports = EllipseWebGLRenderer; /***/ }), -/* 999 */ +/* 998 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154382,7 +152390,7 @@ module.exports = EllipseWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -154456,7 +152464,7 @@ module.exports = EllipseCanvasRenderer; /***/ }), -/* 1000 */ +/* 999 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154470,12 +152478,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1001); + renderWebGL = __webpack_require__(1000); } if (true) { - renderCanvas = __webpack_require__(1002); + renderCanvas = __webpack_require__(1001); } module.exports = { @@ -154487,7 +152495,7 @@ module.exports = { /***/ }), -/* 1001 */ +/* 1000 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154496,7 +152504,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -154713,7 +152721,7 @@ module.exports = GridWebGLRenderer; /***/ }), -/* 1002 */ +/* 1001 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154724,7 +152732,7 @@ module.exports = GridWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -154902,7 +152910,7 @@ module.exports = GridCanvasRenderer; /***/ }), -/* 1003 */ +/* 1002 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154916,12 +152924,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1004); + renderWebGL = __webpack_require__(1003); } if (true) { - renderCanvas = __webpack_require__(1005); + renderCanvas = __webpack_require__(1004); } module.exports = { @@ -154933,7 +152941,7 @@ module.exports = { /***/ }), -/* 1004 */ +/* 1003 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -154942,7 +152950,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -155091,7 +153099,7 @@ module.exports = IsoBoxWebGLRenderer; /***/ }), -/* 1005 */ +/* 1004 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155101,7 +153109,7 @@ module.exports = IsoBoxWebGLRenderer; */ var FillStyleCanvas = __webpack_require__(36); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -155192,7 +153200,7 @@ module.exports = IsoBoxCanvasRenderer; /***/ }), -/* 1006 */ +/* 1005 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155206,12 +153214,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1007); + renderWebGL = __webpack_require__(1006); } if (true) { - renderCanvas = __webpack_require__(1008); + renderCanvas = __webpack_require__(1007); } module.exports = { @@ -155223,7 +153231,7 @@ module.exports = { /***/ }), -/* 1007 */ +/* 1006 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155232,7 +153240,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -155400,7 +153408,7 @@ module.exports = IsoTriangleWebGLRenderer; /***/ }), -/* 1008 */ +/* 1007 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155410,7 +153418,7 @@ module.exports = IsoTriangleWebGLRenderer; */ var FillStyleCanvas = __webpack_require__(36); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -155514,7 +153522,7 @@ module.exports = IsoTriangleCanvasRenderer; /***/ }), -/* 1009 */ +/* 1008 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155528,12 +153536,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1010); + renderWebGL = __webpack_require__(1009); } if (true) { - renderCanvas = __webpack_require__(1011); + renderCanvas = __webpack_require__(1010); } module.exports = { @@ -155545,7 +153553,7 @@ module.exports = { /***/ }), -/* 1010 */ +/* 1009 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155554,7 +153562,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -155638,7 +153646,7 @@ module.exports = LineWebGLRenderer; /***/ }), -/* 1011 */ +/* 1010 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155648,7 +153656,7 @@ module.exports = LineWebGLRenderer; */ var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -155695,7 +153703,7 @@ module.exports = LineCanvasRenderer; /***/ }), -/* 1012 */ +/* 1011 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155709,12 +153717,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1013); + renderWebGL = __webpack_require__(1012); } if (true) { - renderCanvas = __webpack_require__(1014); + renderCanvas = __webpack_require__(1013); } module.exports = { @@ -155726,7 +153734,7 @@ module.exports = { /***/ }), -/* 1013 */ +/* 1012 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155735,8 +153743,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -155804,7 +153812,7 @@ module.exports = PolygonWebGLRenderer; /***/ }), -/* 1014 */ +/* 1013 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155815,7 +153823,7 @@ module.exports = PolygonWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -155889,7 +153897,7 @@ module.exports = PolygonCanvasRenderer; /***/ }), -/* 1015 */ +/* 1014 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155903,12 +153911,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1016); + renderWebGL = __webpack_require__(1015); } if (true) { - renderCanvas = __webpack_require__(1017); + renderCanvas = __webpack_require__(1016); } module.exports = { @@ -155920,7 +153928,7 @@ module.exports = { /***/ }), -/* 1016 */ +/* 1015 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -155929,8 +153937,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var StrokePathWebGL = __webpack_require__(68); -var Utils = __webpack_require__(9); +var StrokePathWebGL = __webpack_require__(70); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -156012,7 +154020,7 @@ module.exports = RectangleWebGLRenderer; /***/ }), -/* 1017 */ +/* 1016 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156023,7 +154031,7 @@ module.exports = RectangleWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -156086,7 +154094,7 @@ module.exports = RectangleCanvasRenderer; /***/ }), -/* 1018 */ +/* 1017 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156100,12 +154108,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1019); + renderWebGL = __webpack_require__(1018); } if (true) { - renderCanvas = __webpack_require__(1020); + renderCanvas = __webpack_require__(1019); } module.exports = { @@ -156117,7 +154125,7 @@ module.exports = { /***/ }), -/* 1019 */ +/* 1018 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156126,8 +154134,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var FillPathWebGL = __webpack_require__(96); -var StrokePathWebGL = __webpack_require__(68); +var FillPathWebGL = __webpack_require__(100); +var StrokePathWebGL = __webpack_require__(70); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -156195,7 +154203,7 @@ module.exports = StarWebGLRenderer; /***/ }), -/* 1020 */ +/* 1019 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156206,7 +154214,7 @@ module.exports = StarWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -156280,7 +154288,7 @@ module.exports = StarCanvasRenderer; /***/ }), -/* 1021 */ +/* 1020 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156294,12 +154302,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1022); + renderWebGL = __webpack_require__(1021); } if (true) { - renderCanvas = __webpack_require__(1023); + renderCanvas = __webpack_require__(1022); } module.exports = { @@ -156311,7 +154319,7 @@ module.exports = { /***/ }), -/* 1022 */ +/* 1021 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156320,8 +154328,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var StrokePathWebGL = __webpack_require__(68); -var Utils = __webpack_require__(9); +var StrokePathWebGL = __webpack_require__(70); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -156414,7 +154422,7 @@ module.exports = TriangleWebGLRenderer; /***/ }), -/* 1023 */ +/* 1022 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156425,7 +154433,7 @@ module.exports = TriangleWebGLRenderer; var FillStyleCanvas = __webpack_require__(36); var LineStyleCanvas = __webpack_require__(49); -var SetTransform = __webpack_require__(29); +var SetTransform = __webpack_require__(27); /** * Renders this Game Object with the Canvas Renderer to the given Camera. @@ -156489,7 +154497,7 @@ module.exports = TriangleCanvasRenderer; /***/ }), -/* 1024 */ +/* 1023 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156498,7 +154506,7 @@ module.exports = TriangleCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Blitter = __webpack_require__(183); +var Blitter = __webpack_require__(186); var GameObjectFactory = __webpack_require__(5); /** @@ -156531,7 +154539,7 @@ GameObjectFactory.register('blitter', function (x, y, key, frame) /***/ }), -/* 1025 */ +/* 1024 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156541,7 +154549,7 @@ GameObjectFactory.register('blitter', function (x, y, key, frame) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Container = __webpack_require__(184); +var Container = __webpack_require__(187); var GameObjectFactory = __webpack_require__(5); /** @@ -156565,7 +154573,7 @@ GameObjectFactory.register('container', function (x, y, children) /***/ }), -/* 1026 */ +/* 1025 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156574,7 +154582,7 @@ GameObjectFactory.register('container', function (x, y, children) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var DOMElement = __webpack_require__(388); +var DOMElement = __webpack_require__(387); var GameObjectFactory = __webpack_require__(5); /** @@ -156655,7 +154663,7 @@ GameObjectFactory.register('dom', function (x, y, element, style, innerText) /***/ }), -/* 1027 */ +/* 1026 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156664,7 +154672,7 @@ GameObjectFactory.register('dom', function (x, y, element, style, innerText) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var DynamicBitmapText = __webpack_require__(185); +var DynamicBitmapText = __webpack_require__(188); var GameObjectFactory = __webpack_require__(5); /** @@ -156724,7 +154732,7 @@ GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size /***/ }), -/* 1028 */ +/* 1027 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156733,7 +154741,7 @@ GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extern = __webpack_require__(390); +var Extern = __webpack_require__(389); var GameObjectFactory = __webpack_require__(5); /** @@ -156766,7 +154774,7 @@ GameObjectFactory.register('extern', function () /***/ }), -/* 1029 */ +/* 1028 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156775,7 +154783,7 @@ GameObjectFactory.register('extern', function () * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Graphics = __webpack_require__(186); +var Graphics = __webpack_require__(189); var GameObjectFactory = __webpack_require__(5); /** @@ -156805,7 +154813,7 @@ GameObjectFactory.register('graphics', function (config) /***/ }), -/* 1030 */ +/* 1029 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156814,7 +154822,7 @@ GameObjectFactory.register('graphics', function (config) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Group = __webpack_require__(95); +var Group = __webpack_require__(97); var GameObjectFactory = __webpack_require__(5); /** @@ -156837,7 +154845,7 @@ GameObjectFactory.register('group', function (children, config) /***/ }), -/* 1031 */ +/* 1030 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156846,7 +154854,7 @@ GameObjectFactory.register('group', function (children, config) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Image = __webpack_require__(103); +var Image = __webpack_require__(98); var GameObjectFactory = __webpack_require__(5); /** @@ -156879,7 +154887,7 @@ GameObjectFactory.register('image', function (x, y, key, frame) /***/ }), -/* 1032 */ +/* 1031 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156889,7 +154897,7 @@ GameObjectFactory.register('image', function (x, y, key, frame) */ var GameObjectFactory = __webpack_require__(5); -var ParticleEmitterManager = __webpack_require__(189); +var ParticleEmitterManager = __webpack_require__(192); /** * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. @@ -156925,7 +154933,7 @@ GameObjectFactory.register('particles', function (key, frame, emitters) /***/ }), -/* 1033 */ +/* 1032 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156935,7 +154943,7 @@ GameObjectFactory.register('particles', function (key, frame, emitters) */ var GameObjectFactory = __webpack_require__(5); -var PathFollower = __webpack_require__(402); +var PathFollower = __webpack_require__(401); /** * Creates a new PathFollower Game Object and adds it to the Scene. @@ -156973,7 +154981,7 @@ GameObjectFactory.register('follower', function (path, x, y, key, frame) /***/ }), -/* 1034 */ +/* 1033 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -156983,7 +154991,7 @@ GameObjectFactory.register('follower', function (path, x, y, key, frame) */ var GameObjectFactory = __webpack_require__(5); -var RenderTexture = __webpack_require__(190); +var RenderTexture = __webpack_require__(193); /** * Creates a new Render Texture Game Object and adds it to the Scene. @@ -157013,61 +155021,7 @@ GameObjectFactory.register('renderTexture', function (x, y, width, height, key, /***/ }), -/* 1035 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rope = __webpack_require__(192); -var GameObjectFactory = __webpack_require__(5); - -/** - * Creates a new Rope Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#mesh - * @webglOnly - * @since 3.23.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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {Phaser.Types.Math.Vector2Like[]} [points] - An array containing the vertices data for this Rope. If none is provided a simple quad is created. See `setPoints` to set this post-creation. - * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? - * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. - * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. - * - * @return {Phaser.GameObjects.Rope} The Game Object that was created. - */ -if (true) -{ - GameObjectFactory.register('rope', function (x, y, texture, frame, points, horizontal, colors, alphas) - { - var rope = new Rope(this.scene, x, y, texture, frame, points, horizontal, colors, alphas); - - this.displayList.add(rope); - - return this.updateList.add(rope); - }); -} - -// 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 - - -/***/ }), -/* 1036 */ +/* 1034 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157077,7 +155031,7 @@ if (true) */ var GameObjectFactory = __webpack_require__(5); -var Sprite = __webpack_require__(73); +var Sprite = __webpack_require__(69); /** * Creates a new Sprite Game Object and adds it to the Scene. @@ -157114,7 +155068,7 @@ GameObjectFactory.register('sprite', function (x, y, key, frame) /***/ }), -/* 1037 */ +/* 1035 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157123,7 +155077,7 @@ GameObjectFactory.register('sprite', function (x, y, key, frame) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(126); +var BitmapText = __webpack_require__(129); var GameObjectFactory = __webpack_require__(5); /** @@ -157178,7 +155132,7 @@ GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align /***/ }), -/* 1038 */ +/* 1036 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157187,7 +155141,7 @@ GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Text = __webpack_require__(193); +var Text = __webpack_require__(195); var GameObjectFactory = __webpack_require__(5); /** @@ -157243,7 +155197,7 @@ GameObjectFactory.register('text', function (x, y, text, style) /***/ }), -/* 1039 */ +/* 1037 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157252,7 +155206,7 @@ GameObjectFactory.register('text', function (x, y, text, style) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var TileSprite = __webpack_require__(194); +var TileSprite = __webpack_require__(196); var GameObjectFactory = __webpack_require__(5); /** @@ -157287,7 +155241,7 @@ GameObjectFactory.register('tileSprite', function (x, y, width, height, key, fra /***/ }), -/* 1040 */ +/* 1038 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157296,7 +155250,7 @@ GameObjectFactory.register('tileSprite', function (x, y, width, height, key, fra * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Zone = __webpack_require__(106); +var Zone = __webpack_require__(110); var GameObjectFactory = __webpack_require__(5); /** @@ -157329,7 +155283,7 @@ GameObjectFactory.register('zone', function (x, y, width, height) /***/ }), -/* 1041 */ +/* 1039 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157338,7 +155292,7 @@ GameObjectFactory.register('zone', function (x, y, width, height) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Video = __webpack_require__(195); +var Video = __webpack_require__(197); var GameObjectFactory = __webpack_require__(5); /** @@ -157376,7 +155330,7 @@ GameObjectFactory.register('video', function (x, y, key) /***/ }), -/* 1042 */ +/* 1040 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157385,7 +155339,7 @@ GameObjectFactory.register('video', function (x, y, key) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Arc = __webpack_require__(403); +var Arc = __webpack_require__(402); var GameObjectFactory = __webpack_require__(5); /** @@ -157449,7 +155403,7 @@ GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlph /***/ }), -/* 1043 */ +/* 1041 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157459,7 +155413,7 @@ GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlph */ var GameObjectFactory = __webpack_require__(5); -var Curve = __webpack_require__(404); +var Curve = __webpack_require__(403); /** * Creates a new Curve Shape Game Object and adds it to the Scene. @@ -157499,7 +155453,7 @@ GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) /***/ }), -/* 1044 */ +/* 1042 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157508,7 +155462,7 @@ GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Ellipse = __webpack_require__(405); +var Ellipse = __webpack_require__(404); var GameObjectFactory = __webpack_require__(5); /** @@ -157551,7 +155505,7 @@ GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, /***/ }), -/* 1045 */ +/* 1043 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157561,7 +155515,7 @@ GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, */ var GameObjectFactory = __webpack_require__(5); -var Grid = __webpack_require__(406); +var Grid = __webpack_require__(405); /** * Creates a new Grid Shape Game Object and adds it to the Scene. @@ -157606,7 +155560,7 @@ GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cel /***/ }), -/* 1046 */ +/* 1044 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157616,7 +155570,7 @@ GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cel */ var GameObjectFactory = __webpack_require__(5); -var IsoBox = __webpack_require__(407); +var IsoBox = __webpack_require__(406); /** * Creates a new IsoBox Shape Game Object and adds it to the Scene. @@ -157657,7 +155611,7 @@ GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fill /***/ }), -/* 1047 */ +/* 1045 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157667,7 +155621,7 @@ GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fill */ var GameObjectFactory = __webpack_require__(5); -var IsoTriangle = __webpack_require__(408); +var IsoTriangle = __webpack_require__(407); /** * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. @@ -157710,7 +155664,7 @@ GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed /***/ }), -/* 1048 */ +/* 1046 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157720,7 +155674,7 @@ GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed */ var GameObjectFactory = __webpack_require__(5); -var Line = __webpack_require__(409); +var Line = __webpack_require__(408); /** * Creates a new Line Shape Game Object and adds it to the Scene. @@ -157761,7 +155715,7 @@ GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, /***/ }), -/* 1049 */ +/* 1047 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157771,7 +155725,7 @@ GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, */ var GameObjectFactory = __webpack_require__(5); -var Polygon = __webpack_require__(410); +var Polygon = __webpack_require__(409); /** * Creates a new Polygon Shape Game Object and adds it to the Scene. @@ -157814,7 +155768,7 @@ GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlp /***/ }), -/* 1050 */ +/* 1048 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157824,7 +155778,7 @@ GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlp */ var GameObjectFactory = __webpack_require__(5); -var Rectangle = __webpack_require__(415); +var Rectangle = __webpack_require__(414); /** * Creates a new Rectangle Shape Game Object and adds it to the Scene. @@ -157859,7 +155813,7 @@ GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor /***/ }), -/* 1051 */ +/* 1049 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157868,7 +155822,7 @@ GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Star = __webpack_require__(416); +var Star = __webpack_require__(415); var GameObjectFactory = __webpack_require__(5); /** @@ -157911,7 +155865,7 @@ GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRad /***/ }), -/* 1052 */ +/* 1050 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157921,7 +155875,7 @@ GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRad */ var GameObjectFactory = __webpack_require__(5); -var Triangle = __webpack_require__(417); +var Triangle = __webpack_require__(416); /** * Creates a new Triangle Shape Game Object and adds it to the Scene. @@ -157962,7 +155916,7 @@ GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, f /***/ }), -/* 1053 */ +/* 1051 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -157971,9 +155925,9 @@ GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, f * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Blitter = __webpack_require__(183); +var Blitter = __webpack_require__(186); var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); /** @@ -158012,7 +155966,7 @@ GameObjectCreator.register('blitter', function (config, addToScene) /***/ }), -/* 1054 */ +/* 1052 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158023,8 +155977,8 @@ GameObjectCreator.register('blitter', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var Container = __webpack_require__(184); -var GameObjectCreator = __webpack_require__(17); +var Container = __webpack_require__(187); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); /** @@ -158061,7 +156015,7 @@ GameObjectCreator.register('container', function (config, addToScene) /***/ }), -/* 1055 */ +/* 1053 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158070,9 +156024,9 @@ GameObjectCreator.register('container', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(185); +var BitmapText = __webpack_require__(188); var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); /** @@ -158112,7 +156066,7 @@ GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) /***/ }), -/* 1056 */ +/* 1054 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158121,8 +156075,8 @@ GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); -var Graphics = __webpack_require__(186); +var GameObjectCreator = __webpack_require__(16); +var Graphics = __webpack_require__(189); /** * Creates a new Graphics Game Object and returns it. @@ -158160,7 +156114,7 @@ GameObjectCreator.register('graphics', function (config, addToScene) /***/ }), -/* 1057 */ +/* 1055 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158169,8 +156123,8 @@ GameObjectCreator.register('graphics', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); -var Group = __webpack_require__(95); +var GameObjectCreator = __webpack_require__(16); +var Group = __webpack_require__(97); /** * Creates a new Group Game Object and returns it. @@ -158193,7 +156147,7 @@ GameObjectCreator.register('group', function (config) /***/ }), -/* 1058 */ +/* 1056 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158203,9 +156157,9 @@ GameObjectCreator.register('group', function (config) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Image = __webpack_require__(103); +var Image = __webpack_require__(98); /** * Creates a new Image Game Object and returns it. @@ -158243,7 +156197,7 @@ GameObjectCreator.register('image', function (config, addToScene) /***/ }), -/* 1059 */ +/* 1057 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158252,10 +156206,10 @@ GameObjectCreator.register('image', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); var GetFastValue = __webpack_require__(2); -var ParticleEmitterManager = __webpack_require__(189); +var ParticleEmitterManager = __webpack_require__(192); /** * Creates a new Particle Emitter Manager Game Object and returns it. @@ -158300,7 +156254,7 @@ GameObjectCreator.register('particles', function (config, addToScene) /***/ }), -/* 1060 */ +/* 1058 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158310,9 +156264,9 @@ GameObjectCreator.register('particles', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var RenderTexture = __webpack_require__(190); +var RenderTexture = __webpack_require__(193); /** * Creates a new Render Texture Game Object and returns it. @@ -158352,7 +156306,7 @@ GameObjectCreator.register('renderTexture', function (config, addToScene) /***/ }), -/* 1061 */ +/* 1059 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158362,65 +156316,10 @@ GameObjectCreator.register('renderTexture', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var BuildGameObjectAnimation = __webpack_require__(385); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var GetValue = __webpack_require__(6); -var Rope = __webpack_require__(192); - -/** - * Creates a new Rope Game Object and returns it. - * - * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#rope - * @since 3.23.0 - * - * @param {object} 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.Rope} The Game Object that was created. - */ -GameObjectCreator.register('rope', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - var horizontal = GetAdvancedValue(config, 'horizontal', true); - var points = GetValue(config, 'points', undefined); - var colors = GetValue(config, 'colors', undefined); - var alphas = GetValue(config, 'alphas', undefined); - - var rope = new Rope(this.scene, 0, 0, key, frame, points, horizontal, colors, alphas); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, rope, config); - - return rope; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. - - -/***/ }), -/* 1062 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = __webpack_require__(28); -var BuildGameObjectAnimation = __webpack_require__(386); -var GameObjectCreator = __webpack_require__(17); -var GetAdvancedValue = __webpack_require__(15); -var Sprite = __webpack_require__(73); +var Sprite = __webpack_require__(69); /** * Creates a new Sprite Game Object and returns it. @@ -158460,7 +156359,7 @@ GameObjectCreator.register('sprite', function (config, addToScene) /***/ }), -/* 1063 */ +/* 1060 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158469,9 +156368,9 @@ GameObjectCreator.register('sprite', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var BitmapText = __webpack_require__(126); +var BitmapText = __webpack_require__(129); var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); var GetValue = __webpack_require__(6); @@ -158513,7 +156412,7 @@ GameObjectCreator.register('bitmapText', function (config, addToScene) /***/ }), -/* 1064 */ +/* 1061 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158523,9 +156422,9 @@ GameObjectCreator.register('bitmapText', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Text = __webpack_require__(193); +var Text = __webpack_require__(195); /** * Creates a new Text Game Object and returns it. @@ -158600,7 +156499,7 @@ GameObjectCreator.register('text', function (config, addToScene) /***/ }), -/* 1065 */ +/* 1062 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158610,9 +156509,9 @@ GameObjectCreator.register('text', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var TileSprite = __webpack_require__(194); +var TileSprite = __webpack_require__(196); /** * Creates a new TileSprite Game Object and returns it. @@ -158652,7 +156551,7 @@ GameObjectCreator.register('tileSprite', function (config, addToScene) /***/ }), -/* 1066 */ +/* 1063 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158661,9 +156560,9 @@ GameObjectCreator.register('tileSprite', function (config, addToScene) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Zone = __webpack_require__(106); +var Zone = __webpack_require__(110); /** * Creates a new Zone Game Object and returns it. @@ -158691,7 +156590,7 @@ GameObjectCreator.register('zone', function (config) /***/ }), -/* 1067 */ +/* 1064 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158701,9 +156600,9 @@ GameObjectCreator.register('zone', function (config) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Video = __webpack_require__(195); +var Video = __webpack_require__(197); /** * Creates a new Video Game Object and returns it. @@ -158740,7 +156639,7 @@ GameObjectCreator.register('video', function (config, addToScene) /***/ }), -/* 1068 */ +/* 1065 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158754,12 +156653,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1069); + renderWebGL = __webpack_require__(1066); } if (true) { - renderCanvas = __webpack_require__(1070); + renderCanvas = __webpack_require__(1067); } module.exports = { @@ -158771,7 +156670,7 @@ module.exports = { /***/ }), -/* 1069 */ +/* 1066 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158780,7 +156679,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Utils = __webpack_require__(9); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -158889,7 +156788,7 @@ module.exports = MeshWebGLRenderer; /***/ }), -/* 1070 */ +/* 1067 */ /***/ (function(module, exports) { /** @@ -158918,7 +156817,7 @@ module.exports = MeshCanvasRenderer; /***/ }), -/* 1071 */ +/* 1068 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -158932,12 +156831,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1072); + renderWebGL = __webpack_require__(1069); } if (true) { - renderCanvas = __webpack_require__(1073); + renderCanvas = __webpack_require__(1070); } module.exports = { @@ -158949,7 +156848,7 @@ module.exports = { /***/ }), -/* 1072 */ +/* 1069 */ /***/ (function(module, exports) { /** @@ -159033,7 +156932,7 @@ module.exports = ShaderWebGLRenderer; /***/ }), -/* 1073 */ +/* 1070 */ /***/ (function(module, exports) { /** @@ -159062,7 +156961,7 @@ module.exports = ShaderCanvasRenderer; /***/ }), -/* 1074 */ +/* 1071 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159071,7 +156970,7 @@ module.exports = ShaderCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Mesh = __webpack_require__(128); +var Mesh = __webpack_require__(130); var GameObjectFactory = __webpack_require__(5); /** @@ -159112,7 +157011,7 @@ if (true) /***/ }), -/* 1075 */ +/* 1072 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159121,7 +157020,7 @@ if (true) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Quad = __webpack_require__(198); +var Quad = __webpack_require__(200); var GameObjectFactory = __webpack_require__(5); /** @@ -159158,7 +157057,7 @@ if (true) /***/ }), -/* 1076 */ +/* 1073 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159167,7 +157066,7 @@ if (true) * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Shader = __webpack_require__(199); +var Shader = __webpack_require__(201); var GameObjectFactory = __webpack_require__(5); /** @@ -159199,7 +157098,7 @@ if (true) /***/ }), -/* 1077 */ +/* 1074 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159209,10 +157108,10 @@ if (true) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); var GetValue = __webpack_require__(6); -var Mesh = __webpack_require__(128); +var Mesh = __webpack_require__(130); /** * Creates a new Mesh Game Object and returns it. @@ -159254,7 +157153,7 @@ GameObjectCreator.register('mesh', function (config, addToScene) /***/ }), -/* 1078 */ +/* 1075 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159264,9 +157163,9 @@ GameObjectCreator.register('mesh', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Quad = __webpack_require__(198); +var Quad = __webpack_require__(200); /** * Creates a new Quad Game Object and returns it. @@ -159304,7 +157203,7 @@ GameObjectCreator.register('quad', function (config, addToScene) /***/ }), -/* 1079 */ +/* 1076 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159314,9 +157213,9 @@ GameObjectCreator.register('quad', function (config, addToScene) */ var BuildGameObject = __webpack_require__(28); -var GameObjectCreator = __webpack_require__(17); +var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(15); -var Shader = __webpack_require__(199); +var Shader = __webpack_require__(201); /** * Creates a new Shader Game Object and returns it. @@ -159357,7 +157256,7 @@ GameObjectCreator.register('shader', function (config, addToScene) /***/ }), -/* 1080 */ +/* 1077 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159367,9 +157266,9 @@ GameObjectCreator.register('shader', function (config, addToScene) */ var Class = __webpack_require__(0); -var LightsManager = __webpack_require__(422); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var LightsManager = __webpack_require__(421); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -159473,7 +157372,7 @@ module.exports = LightsPlugin; /***/ }), -/* 1081 */ +/* 1078 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159482,29 +157381,29 @@ module.exports = LightsPlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); -Circle.Area = __webpack_require__(1082); -Circle.Circumference = __webpack_require__(263); -Circle.CircumferencePoint = __webpack_require__(143); -Circle.Clone = __webpack_require__(1083); +Circle.Area = __webpack_require__(1079); +Circle.Circumference = __webpack_require__(265); +Circle.CircumferencePoint = __webpack_require__(146); +Circle.Clone = __webpack_require__(1080); Circle.Contains = __webpack_require__(55); -Circle.ContainsPoint = __webpack_require__(1084); -Circle.ContainsRect = __webpack_require__(1085); -Circle.CopyFrom = __webpack_require__(1086); -Circle.Equals = __webpack_require__(1087); -Circle.GetBounds = __webpack_require__(1088); -Circle.GetPoint = __webpack_require__(261); -Circle.GetPoints = __webpack_require__(262); -Circle.Offset = __webpack_require__(1089); -Circle.OffsetPoint = __webpack_require__(1090); -Circle.Random = __webpack_require__(144); +Circle.ContainsPoint = __webpack_require__(1081); +Circle.ContainsRect = __webpack_require__(1082); +Circle.CopyFrom = __webpack_require__(1083); +Circle.Equals = __webpack_require__(1084); +Circle.GetBounds = __webpack_require__(1085); +Circle.GetPoint = __webpack_require__(263); +Circle.GetPoints = __webpack_require__(264); +Circle.Offset = __webpack_require__(1086); +Circle.OffsetPoint = __webpack_require__(1087); +Circle.Random = __webpack_require__(147); module.exports = Circle; /***/ }), -/* 1082 */ +/* 1079 */ /***/ (function(module, exports) { /** @@ -159532,7 +157431,7 @@ module.exports = Area; /***/ }), -/* 1083 */ +/* 1080 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159541,7 +157440,7 @@ module.exports = Area; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); /** * Creates a new Circle instance based on the values contained in the given source. @@ -159562,7 +157461,7 @@ module.exports = Clone; /***/ }), -/* 1084 */ +/* 1081 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159593,7 +157492,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1085 */ +/* 1082 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159629,7 +157528,7 @@ module.exports = ContainsRect; /***/ }), -/* 1086 */ +/* 1083 */ /***/ (function(module, exports) { /** @@ -159661,7 +157560,7 @@ module.exports = CopyFrom; /***/ }), -/* 1087 */ +/* 1084 */ /***/ (function(module, exports) { /** @@ -159695,7 +157594,7 @@ module.exports = Equals; /***/ }), -/* 1088 */ +/* 1085 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159704,7 +157603,7 @@ module.exports = Equals; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Returns the bounds of the Circle object. @@ -159735,7 +157634,7 @@ module.exports = GetBounds; /***/ }), -/* 1089 */ +/* 1086 */ /***/ (function(module, exports) { /** @@ -159770,7 +157669,7 @@ module.exports = Offset; /***/ }), -/* 1090 */ +/* 1087 */ /***/ (function(module, exports) { /** @@ -159804,7 +157703,7 @@ module.exports = OffsetPoint; /***/ }), -/* 1091 */ +/* 1088 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159813,29 +157712,29 @@ module.exports = OffsetPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Ellipse = __webpack_require__(93); +var Ellipse = __webpack_require__(95); -Ellipse.Area = __webpack_require__(1092); -Ellipse.Circumference = __webpack_require__(393); -Ellipse.CircumferencePoint = __webpack_require__(188); -Ellipse.Clone = __webpack_require__(1093); -Ellipse.Contains = __webpack_require__(94); -Ellipse.ContainsPoint = __webpack_require__(1094); -Ellipse.ContainsRect = __webpack_require__(1095); -Ellipse.CopyFrom = __webpack_require__(1096); -Ellipse.Equals = __webpack_require__(1097); -Ellipse.GetBounds = __webpack_require__(1098); -Ellipse.GetPoint = __webpack_require__(391); -Ellipse.GetPoints = __webpack_require__(392); -Ellipse.Offset = __webpack_require__(1099); -Ellipse.OffsetPoint = __webpack_require__(1100); -Ellipse.Random = __webpack_require__(151); +Ellipse.Area = __webpack_require__(1089); +Ellipse.Circumference = __webpack_require__(392); +Ellipse.CircumferencePoint = __webpack_require__(191); +Ellipse.Clone = __webpack_require__(1090); +Ellipse.Contains = __webpack_require__(96); +Ellipse.ContainsPoint = __webpack_require__(1091); +Ellipse.ContainsRect = __webpack_require__(1092); +Ellipse.CopyFrom = __webpack_require__(1093); +Ellipse.Equals = __webpack_require__(1094); +Ellipse.GetBounds = __webpack_require__(1095); +Ellipse.GetPoint = __webpack_require__(390); +Ellipse.GetPoints = __webpack_require__(391); +Ellipse.Offset = __webpack_require__(1096); +Ellipse.OffsetPoint = __webpack_require__(1097); +Ellipse.Random = __webpack_require__(154); module.exports = Ellipse; /***/ }), -/* 1092 */ +/* 1089 */ /***/ (function(module, exports) { /** @@ -159869,7 +157768,7 @@ module.exports = Area; /***/ }), -/* 1093 */ +/* 1090 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159878,7 +157777,7 @@ module.exports = Area; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Ellipse = __webpack_require__(93); +var Ellipse = __webpack_require__(95); /** * Creates a new Ellipse instance based on the values contained in the given source. @@ -159899,7 +157798,7 @@ module.exports = Clone; /***/ }), -/* 1094 */ +/* 1091 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159908,7 +157807,7 @@ module.exports = Clone; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(94); +var Contains = __webpack_require__(96); /** * Check to see if the Ellipse contains the given Point object. @@ -159930,7 +157829,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1095 */ +/* 1092 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -159939,7 +157838,7 @@ module.exports = ContainsPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(94); +var Contains = __webpack_require__(96); /** * Check to see if the Ellipse contains all four points of the given Rectangle object. @@ -159966,7 +157865,7 @@ module.exports = ContainsRect; /***/ }), -/* 1096 */ +/* 1093 */ /***/ (function(module, exports) { /** @@ -159998,7 +157897,7 @@ module.exports = CopyFrom; /***/ }), -/* 1097 */ +/* 1094 */ /***/ (function(module, exports) { /** @@ -160033,7 +157932,7 @@ module.exports = Equals; /***/ }), -/* 1098 */ +/* 1095 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160042,7 +157941,7 @@ module.exports = Equals; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Returns the bounds of the Ellipse object. @@ -160073,7 +157972,7 @@ module.exports = GetBounds; /***/ }), -/* 1099 */ +/* 1096 */ /***/ (function(module, exports) { /** @@ -160108,7 +158007,7 @@ module.exports = Offset; /***/ }), -/* 1100 */ +/* 1097 */ /***/ (function(module, exports) { /** @@ -160142,7 +158041,7 @@ module.exports = OffsetPoint; /***/ }), -/* 1101 */ +/* 1098 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160153,7 +158052,7 @@ module.exports = OffsetPoint; */ var Point = __webpack_require__(4); -var CircleToCircle = __webpack_require__(200); +var CircleToCircle = __webpack_require__(202); /** * Checks if two Circles intersect and returns the intersection points as a Point object array. @@ -160236,7 +158135,7 @@ module.exports = GetCircleToCircle; /***/ }), -/* 1102 */ +/* 1099 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160246,8 +158145,8 @@ module.exports = GetCircleToCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetLineToCircle = __webpack_require__(202); -var CircleToRectangle = __webpack_require__(201); +var GetLineToCircle = __webpack_require__(204); +var CircleToRectangle = __webpack_require__(203); /** * Checks for intersection between a circle and a rectangle, @@ -160286,7 +158185,7 @@ module.exports = GetCircleToRectangle; /***/ }), -/* 1103 */ +/* 1100 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160295,8 +158194,8 @@ module.exports = GetCircleToRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var RectangleToRectangle = __webpack_require__(129); +var Rectangle = __webpack_require__(11); +var RectangleToRectangle = __webpack_require__(131); /** * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. @@ -160335,7 +158234,7 @@ module.exports = GetRectangleIntersection; /***/ }), -/* 1104 */ +/* 1101 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160345,8 +158244,8 @@ module.exports = GetRectangleIntersection; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetLineToRectangle = __webpack_require__(204); -var RectangleToRectangle = __webpack_require__(129); +var GetLineToRectangle = __webpack_require__(206); +var RectangleToRectangle = __webpack_require__(131); /** * Checks if two Rectangles intersect and returns the intersection points as a Point object array. @@ -160386,7 +158285,7 @@ module.exports = GetRectangleToRectangle; /***/ }), -/* 1105 */ +/* 1102 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160396,8 +158295,8 @@ module.exports = GetRectangleToRectangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RectangleToTriangle = __webpack_require__(426); -var GetLineToRectangle = __webpack_require__(204); +var RectangleToTriangle = __webpack_require__(425); +var GetLineToRectangle = __webpack_require__(206); /** * Checks for intersection between Rectangle shape and Triangle shape, @@ -160434,7 +158333,7 @@ module.exports = GetRectangleToTriangle; /***/ }), -/* 1106 */ +/* 1103 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160444,8 +158343,8 @@ module.exports = GetRectangleToTriangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetLineToCircle = __webpack_require__(202); -var TriangleToCircle = __webpack_require__(428); +var GetLineToCircle = __webpack_require__(204); +var TriangleToCircle = __webpack_require__(427); /** * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. @@ -160483,7 +158382,7 @@ module.exports = GetTriangleToCircle; /***/ }), -/* 1107 */ +/* 1104 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160493,8 +158392,8 @@ module.exports = GetTriangleToCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var TriangleToTriangle = __webpack_require__(431); -var GetTriangleToLine = __webpack_require__(429); +var TriangleToTriangle = __webpack_require__(430); +var GetTriangleToLine = __webpack_require__(428); /** * Checks if two Triangles intersect, and returns the intersection points as a Point object array. @@ -160532,7 +158431,7 @@ module.exports = GetTriangleToTriangle; /***/ }), -/* 1108 */ +/* 1105 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160541,7 +158440,7 @@ module.exports = GetTriangleToTriangle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PointToLine = __webpack_require__(433); +var PointToLine = __webpack_require__(432); /** * Checks if a Point is located on the given line segment. @@ -160573,7 +158472,7 @@ module.exports = PointToLineSegment; /***/ }), -/* 1109 */ +/* 1106 */ /***/ (function(module, exports) { /** @@ -160613,7 +158512,7 @@ module.exports = RectangleToValues; /***/ }), -/* 1110 */ +/* 1107 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160624,41 +158523,40 @@ module.exports = RectangleToValues; var Line = __webpack_require__(56); -Line.Angle = __webpack_require__(83); -Line.BresenhamPoints = __webpack_require__(283); -Line.CenterOn = __webpack_require__(1111); -Line.Clone = __webpack_require__(1112); -Line.CopyFrom = __webpack_require__(1113); -Line.Equals = __webpack_require__(1114); -Line.Extend = __webpack_require__(1115); -Line.GetEasedPoints = __webpack_require__(1116); -Line.GetMidPoint = __webpack_require__(1117); -Line.GetNearestPoint = __webpack_require__(1118); -Line.GetNormal = __webpack_require__(1119); -Line.GetPoint = __webpack_require__(270); -Line.GetPoints = __webpack_require__(147); -Line.GetShortestDistance = __webpack_require__(1120); -Line.Height = __webpack_require__(1121); +Line.Angle = __webpack_require__(85); +Line.BresenhamPoints = __webpack_require__(285); +Line.CenterOn = __webpack_require__(1108); +Line.Clone = __webpack_require__(1109); +Line.CopyFrom = __webpack_require__(1110); +Line.Equals = __webpack_require__(1111); +Line.Extend = __webpack_require__(1112); +Line.GetMidPoint = __webpack_require__(1113); +Line.GetNearestPoint = __webpack_require__(1114); +Line.GetNormal = __webpack_require__(1115); +Line.GetPoint = __webpack_require__(272); +Line.GetPoints = __webpack_require__(150); +Line.GetShortestDistance = __webpack_require__(1116); +Line.Height = __webpack_require__(1117); Line.Length = __webpack_require__(57); -Line.NormalAngle = __webpack_require__(434); -Line.NormalX = __webpack_require__(1122); -Line.NormalY = __webpack_require__(1123); -Line.Offset = __webpack_require__(1124); -Line.PerpSlope = __webpack_require__(1125); -Line.Random = __webpack_require__(148); -Line.ReflectAngle = __webpack_require__(1126); -Line.Rotate = __webpack_require__(1127); -Line.RotateAroundPoint = __webpack_require__(1128); -Line.RotateAroundXY = __webpack_require__(206); -Line.SetToAngle = __webpack_require__(1129); -Line.Slope = __webpack_require__(1130); -Line.Width = __webpack_require__(1131); +Line.NormalAngle = __webpack_require__(433); +Line.NormalX = __webpack_require__(1118); +Line.NormalY = __webpack_require__(1119); +Line.Offset = __webpack_require__(1120); +Line.PerpSlope = __webpack_require__(1121); +Line.Random = __webpack_require__(151); +Line.ReflectAngle = __webpack_require__(1122); +Line.Rotate = __webpack_require__(1123); +Line.RotateAroundPoint = __webpack_require__(1124); +Line.RotateAroundXY = __webpack_require__(208); +Line.SetToAngle = __webpack_require__(1125); +Line.Slope = __webpack_require__(1126); +Line.Width = __webpack_require__(1127); module.exports = Line; /***/ }), -/* 1111 */ +/* 1108 */ /***/ (function(module, exports) { /** @@ -160698,7 +158596,7 @@ module.exports = CenterOn; /***/ }), -/* 1112 */ +/* 1109 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160728,7 +158626,7 @@ module.exports = Clone; /***/ }), -/* 1113 */ +/* 1110 */ /***/ (function(module, exports) { /** @@ -160759,7 +158657,7 @@ module.exports = CopyFrom; /***/ }), -/* 1114 */ +/* 1111 */ /***/ (function(module, exports) { /** @@ -160793,7 +158691,7 @@ module.exports = Equals; /***/ }), -/* 1115 */ +/* 1112 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -160851,127 +158749,7 @@ module.exports = Extend; /***/ }), -/* 1116 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DistanceBetweenPoints = __webpack_require__(314); -var GetEaseFunction = __webpack_require__(67); -var Point = __webpack_require__(4); - -/** - * 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.Geom.Point[]} 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 {integer} 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 noisey eases. - * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. - * - * @return {Phaser.Geom.Point[]} An array of Geom.Points containing the coordinates of the points on the line. - */ -var GetEasedPoints = function (line, ease, quantity, collinearThreshold, easeParams) -{ - if (collinearThreshold === undefined) { collinearThreshold = 0; } - if (easeParams === undefined) { easeParams = []; } - - var results = []; - - var x1 = line.x1; - var y1 = line.y1; - - var spaceX = line.x2 - x1; - var spaceY = line.y2 - y1; - - var easeFunc = GetEaseFunction(ease, easeParams); - - var i; - var v; - var q = quantity - 1; - - for (i = 0; i < q; i++) - { - v = easeFunc(i / q); - - results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); - } - - // Always include the end of the line - v = easeFunc(1); - - results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); - - // Remove collinear parts - if (collinearThreshold > 0) - { - var prevPoint = results[0]; - - // Store the new results here - var sortedResults = [ prevPoint ]; - - for (i = 1; i < results.length - 1; i++) - { - var point = results[i]; - - if (DistanceBetweenPoints(prevPoint, point) >= collinearThreshold) - { - sortedResults.push(point); - prevPoint = point; - } - } - - // Top and tail - var endPoint = results[results.length - 1]; - - if (DistanceBetweenPoints(prevPoint, endPoint) < collinearThreshold) - { - sortedResults.pop(); - } - - sortedResults.push(endPoint); - - return sortedResults; - } - else - { - return results; - } -}; - -module.exports = GetEasedPoints; - - -/***/ }), -/* 1117 */ +/* 1113 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161009,7 +158787,7 @@ module.exports = GetMidPoint; /***/ }), -/* 1118 */ +/* 1114 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161064,7 +158842,7 @@ module.exports = GetNearestPoint; /***/ }), -/* 1119 */ +/* 1115 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161073,8 +158851,8 @@ module.exports = GetNearestPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var Angle = __webpack_require__(83); +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(85); var Point = __webpack_require__(4); /** @@ -161108,7 +158886,7 @@ module.exports = GetNormal; /***/ }), -/* 1120 */ +/* 1116 */ /***/ (function(module, exports) { /** @@ -161155,7 +158933,7 @@ module.exports = GetShortestDistance; /***/ }), -/* 1121 */ +/* 1117 */ /***/ (function(module, exports) { /** @@ -161183,7 +158961,7 @@ module.exports = Height; /***/ }), -/* 1122 */ +/* 1118 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161192,18 +158970,18 @@ module.exports = Height; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var Angle = __webpack_require__(83); +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(85); /** - * Returns the x component of the normal vector of the given line. + * [description] * * @function Phaser.Geom.Line.NormalX * @since 3.0.0 * * @param {Phaser.Geom.Line} line - The Line object to get the normal value from. * - * @return {number} The x component of the normal vector of the line. + * @return {number} [description] */ var NormalX = function (line) { @@ -161214,7 +158992,7 @@ module.exports = NormalX; /***/ }), -/* 1123 */ +/* 1119 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161223,8 +159001,8 @@ module.exports = NormalX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var MATH_CONST = __webpack_require__(16); -var Angle = __webpack_require__(83); +var MATH_CONST = __webpack_require__(13); +var Angle = __webpack_require__(85); /** * The Y value of the normal of the given line. @@ -161246,7 +159024,7 @@ module.exports = NormalY; /***/ }), -/* 1124 */ +/* 1120 */ /***/ (function(module, exports) { /** @@ -161284,7 +159062,7 @@ module.exports = Offset; /***/ }), -/* 1125 */ +/* 1121 */ /***/ (function(module, exports) { /** @@ -161312,7 +159090,7 @@ module.exports = PerpSlope; /***/ }), -/* 1126 */ +/* 1122 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161321,8 +159099,8 @@ module.exports = PerpSlope; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Angle = __webpack_require__(83); -var NormalAngle = __webpack_require__(434); +var Angle = __webpack_require__(85); +var NormalAngle = __webpack_require__(433); /** * Calculate the reflected angle between two lines. @@ -161346,7 +159124,7 @@ module.exports = ReflectAngle; /***/ }), -/* 1127 */ +/* 1123 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161355,7 +159133,7 @@ module.exports = ReflectAngle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(206); +var RotateAroundXY = __webpack_require__(208); /** * Rotate a line around its midpoint by the given angle in radians. @@ -161382,7 +159160,7 @@ module.exports = Rotate; /***/ }), -/* 1128 */ +/* 1124 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161391,7 +159169,7 @@ module.exports = Rotate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(206); +var RotateAroundXY = __webpack_require__(208); /** * Rotate a line around a point by the given angle in radians. @@ -161416,7 +159194,7 @@ module.exports = RotateAroundPoint; /***/ }), -/* 1129 */ +/* 1125 */ /***/ (function(module, exports) { /** @@ -161456,7 +159234,7 @@ module.exports = SetToAngle; /***/ }), -/* 1130 */ +/* 1126 */ /***/ (function(module, exports) { /** @@ -161484,7 +159262,7 @@ module.exports = Slope; /***/ }), -/* 1131 */ +/* 1127 */ /***/ (function(module, exports) { /** @@ -161512,7 +159290,7 @@ module.exports = Width; /***/ }), -/* 1132 */ +/* 1128 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161523,27 +159301,27 @@ module.exports = Width; var Point = __webpack_require__(4); -Point.Ceil = __webpack_require__(1133); -Point.Clone = __webpack_require__(1134); -Point.CopyFrom = __webpack_require__(1135); -Point.Equals = __webpack_require__(1136); -Point.Floor = __webpack_require__(1137); -Point.GetCentroid = __webpack_require__(1138); -Point.GetMagnitude = __webpack_require__(435); -Point.GetMagnitudeSq = __webpack_require__(436); -Point.GetRectangleFromPoints = __webpack_require__(1139); -Point.Interpolate = __webpack_require__(1140); -Point.Invert = __webpack_require__(1141); -Point.Negative = __webpack_require__(1142); -Point.Project = __webpack_require__(1143); -Point.ProjectUnit = __webpack_require__(1144); -Point.SetMagnitude = __webpack_require__(1145); +Point.Ceil = __webpack_require__(1129); +Point.Clone = __webpack_require__(1130); +Point.CopyFrom = __webpack_require__(1131); +Point.Equals = __webpack_require__(1132); +Point.Floor = __webpack_require__(1133); +Point.GetCentroid = __webpack_require__(1134); +Point.GetMagnitude = __webpack_require__(434); +Point.GetMagnitudeSq = __webpack_require__(435); +Point.GetRectangleFromPoints = __webpack_require__(1135); +Point.Interpolate = __webpack_require__(1136); +Point.Invert = __webpack_require__(1137); +Point.Negative = __webpack_require__(1138); +Point.Project = __webpack_require__(1139); +Point.ProjectUnit = __webpack_require__(1140); +Point.SetMagnitude = __webpack_require__(1141); module.exports = Point; /***/ }), -/* 1133 */ +/* 1129 */ /***/ (function(module, exports) { /** @@ -161573,7 +159351,7 @@ module.exports = Ceil; /***/ }), -/* 1134 */ +/* 1130 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161603,7 +159381,7 @@ module.exports = Clone; /***/ }), -/* 1135 */ +/* 1131 */ /***/ (function(module, exports) { /** @@ -161634,7 +159412,7 @@ module.exports = CopyFrom; /***/ }), -/* 1136 */ +/* 1132 */ /***/ (function(module, exports) { /** @@ -161663,7 +159441,7 @@ module.exports = Equals; /***/ }), -/* 1137 */ +/* 1133 */ /***/ (function(module, exports) { /** @@ -161693,7 +159471,7 @@ module.exports = Floor; /***/ }), -/* 1138 */ +/* 1134 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161713,10 +159491,10 @@ var Point = __webpack_require__(4); * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the geometric center of. - * @param {Phaser.Geom.Point} [out] - A Point object to store the output coordinates in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Point[]} points - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object representing the geometric center of the given points. + * @return {Phaser.Geom.Point} [description] */ var GetCentroid = function (points, out) { @@ -161757,7 +159535,7 @@ module.exports = GetCentroid; /***/ }), -/* 1139 */ +/* 1135 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161766,7 +159544,7 @@ module.exports = GetCentroid; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. @@ -161776,10 +159554,10 @@ var Rectangle = __webpack_require__(13); * * @generic {Phaser.Geom.Rectangle} O - [out,$return] * - * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the AABB from. - * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the results in. If not given, a new Rectangle instance is created. + * @param {Phaser.Geom.Point[]} points - [description] + * @param {Phaser.Geom.Rectangle} [out] - [description] * - * @return {Phaser.Geom.Rectangle} A Rectangle object holding the AABB values for the given points. + * @return {Phaser.Geom.Rectangle} [description] */ var GetRectangleFromPoints = function (points, out) { @@ -161827,7 +159605,7 @@ module.exports = GetRectangleFromPoints; /***/ }), -/* 1140 */ +/* 1136 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161839,7 +159617,7 @@ module.exports = GetRectangleFromPoints; var Point = __webpack_require__(4); /** - * Returns the linear interpolation point between the two given points, based on `t`. + * [description] * * @function Phaser.Geom.Point.Interpolate * @since 3.0.0 @@ -161868,7 +159646,7 @@ module.exports = Interpolate; /***/ }), -/* 1141 */ +/* 1137 */ /***/ (function(module, exports) { /** @@ -161898,7 +159676,7 @@ module.exports = Invert; /***/ }), -/* 1142 */ +/* 1138 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161933,7 +159711,7 @@ module.exports = Negative; /***/ }), -/* 1143 */ +/* 1139 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161943,22 +159721,21 @@ module.exports = Negative; */ var Point = __webpack_require__(4); -var GetMagnitudeSq = __webpack_require__(436); +var GetMagnitudeSq = __webpack_require__(435); /** - * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the - * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. + * [description] * * @function Phaser.Geom.Point.Project * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. - * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Point} pointA - [description] + * @param {Phaser.Geom.Point} pointB - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. + * @return {Phaser.Geom.Point} [description] */ var Project = function (pointA, pointB, out) { @@ -161980,7 +159757,7 @@ module.exports = Project; /***/ }), -/* 1144 */ +/* 1140 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -161992,19 +159769,18 @@ module.exports = Project; var Point = __webpack_require__(4); /** - * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the - * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. + * [description] * * @function Phaser.Geom.Point.ProjectUnit * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. Must be a normalized point with a magnitude of 1. - * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Point} pointA - [description] + * @param {Phaser.Geom.Point} pointB - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A unit Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. + * @return {Phaser.Geom.Point} [description] */ var ProjectUnit = function (pointA, pointB, out) { @@ -162025,7 +159801,7 @@ module.exports = ProjectUnit; /***/ }), -/* 1145 */ +/* 1141 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162034,7 +159810,7 @@ module.exports = ProjectUnit; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetMagnitude = __webpack_require__(435); +var GetMagnitude = __webpack_require__(434); /** * Changes the magnitude (length) of a two-dimensional vector without changing its direction. @@ -162069,7 +159845,7 @@ module.exports = SetMagnitude; /***/ }), -/* 1146 */ +/* 1142 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162078,23 +159854,23 @@ module.exports = SetMagnitude; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Polygon = __webpack_require__(196); +var Polygon = __webpack_require__(198); -Polygon.Clone = __webpack_require__(1147); -Polygon.Contains = __webpack_require__(197); -Polygon.ContainsPoint = __webpack_require__(1148); -Polygon.GetAABB = __webpack_require__(411); -Polygon.GetNumberArray = __webpack_require__(1149); -Polygon.GetPoints = __webpack_require__(412); -Polygon.Perimeter = __webpack_require__(413); -Polygon.Reverse = __webpack_require__(1150); -Polygon.Smooth = __webpack_require__(414); +Polygon.Clone = __webpack_require__(1143); +Polygon.Contains = __webpack_require__(199); +Polygon.ContainsPoint = __webpack_require__(1144); +Polygon.GetAABB = __webpack_require__(410); +Polygon.GetNumberArray = __webpack_require__(1145); +Polygon.GetPoints = __webpack_require__(411); +Polygon.Perimeter = __webpack_require__(412); +Polygon.Reverse = __webpack_require__(1146); +Polygon.Smooth = __webpack_require__(413); module.exports = Polygon; /***/ }), -/* 1147 */ +/* 1143 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162103,7 +159879,7 @@ module.exports = Polygon; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Polygon = __webpack_require__(196); +var Polygon = __webpack_require__(198); /** * Create a new polygon which is a copy of the specified polygon @@ -162124,7 +159900,7 @@ module.exports = Clone; /***/ }), -/* 1148 */ +/* 1144 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162133,18 +159909,18 @@ module.exports = Clone; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(197); +var Contains = __webpack_require__(199); /** - * Checks the given Point again the Polygon to see if the Point lays within its vertices. + * [description] * * @function Phaser.Geom.Polygon.ContainsPoint * @since 3.0.0 * - * @param {Phaser.Geom.Polygon} polygon - The Polygon to check. - * @param {Phaser.Geom.Point} point - The Point to check if it's within the Polygon. + * @param {Phaser.Geom.Polygon} polygon - [description] + * @param {Phaser.Geom.Point} point - [description] * - * @return {boolean} `true` if the Point is within the Polygon, otherwise `false`. + * @return {boolean} [description] */ var ContainsPoint = function (polygon, point) { @@ -162155,7 +159931,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1149 */ +/* 1145 */ /***/ (function(module, exports) { /** @@ -162198,7 +159974,7 @@ module.exports = GetNumberArray; /***/ }), -/* 1150 */ +/* 1146 */ /***/ (function(module, exports) { /** @@ -162230,7 +160006,7 @@ module.exports = Reverse; /***/ }), -/* 1151 */ +/* 1147 */ /***/ (function(module, exports) { /** @@ -162258,7 +160034,7 @@ module.exports = Area; /***/ }), -/* 1152 */ +/* 1148 */ /***/ (function(module, exports) { /** @@ -162291,7 +160067,7 @@ module.exports = Ceil; /***/ }), -/* 1153 */ +/* 1149 */ /***/ (function(module, exports) { /** @@ -162326,7 +160102,7 @@ module.exports = CeilAll; /***/ }), -/* 1154 */ +/* 1150 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162335,7 +160111,7 @@ module.exports = CeilAll; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); +var Rectangle = __webpack_require__(11); /** * Creates a new Rectangle which is identical to the given one. @@ -162356,7 +160132,7 @@ module.exports = Clone; /***/ }), -/* 1155 */ +/* 1151 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162387,7 +160163,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1156 */ +/* 1152 */ /***/ (function(module, exports) { /** @@ -162418,7 +160194,7 @@ module.exports = CopyFrom; /***/ }), -/* 1157 */ +/* 1153 */ /***/ (function(module, exports) { /** @@ -162452,7 +160228,7 @@ module.exports = Equals; /***/ }), -/* 1158 */ +/* 1154 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162461,7 +160237,7 @@ module.exports = Equals; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetAspectRatio = __webpack_require__(207); +var GetAspectRatio = __webpack_require__(209); /** * Adjusts the target rectangle, changing its width, height and position, @@ -162505,7 +160281,7 @@ module.exports = FitInside; /***/ }), -/* 1159 */ +/* 1155 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162514,7 +160290,7 @@ module.exports = FitInside; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetAspectRatio = __webpack_require__(207); +var GetAspectRatio = __webpack_require__(209); /** * Adjusts the target rectangle, changing its width, height and position, @@ -162558,7 +160334,7 @@ module.exports = FitOutside; /***/ }), -/* 1160 */ +/* 1156 */ /***/ (function(module, exports) { /** @@ -162591,7 +160367,7 @@ module.exports = Floor; /***/ }), -/* 1161 */ +/* 1157 */ /***/ (function(module, exports) { /** @@ -162626,7 +160402,7 @@ module.exports = FloorAll; /***/ }), -/* 1162 */ +/* 1158 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162664,7 +160440,7 @@ module.exports = GetCenter; /***/ }), -/* 1163 */ +/* 1159 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162677,18 +160453,18 @@ var Point = __webpack_require__(4); /** - * Returns the size of the Rectangle, expressed as a Point object. - * With the value of the `width` as the `x` property and the `height` as the `y` property. + * The size of the Rectangle object, expressed as a Point object + * with the values of the width and height properties. * * @function Phaser.Geom.Rectangle.GetSize * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the size from. - * @param {(Phaser.Geom.Point|object)} [out] - The Point object to store the size in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Rectangle} rect - [description] + * @param {(Phaser.Geom.Point|object)} [out] - [description] * - * @return {(Phaser.Geom.Point|object)} A Point object where `x` holds the width and `y` holds the height of the Rectangle. + * @return {(Phaser.Geom.Point|object)} [description] */ var GetSize = function (rect, out) { @@ -162704,7 +160480,7 @@ module.exports = GetSize; /***/ }), -/* 1164 */ +/* 1160 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162713,7 +160489,7 @@ module.exports = GetSize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CenterOn = __webpack_require__(162); +var CenterOn = __webpack_require__(165); /** @@ -162746,7 +160522,7 @@ module.exports = Inflate; /***/ }), -/* 1165 */ +/* 1161 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -162755,8 +160531,8 @@ module.exports = Inflate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Rectangle = __webpack_require__(13); -var Intersects = __webpack_require__(129); +var Rectangle = __webpack_require__(11); +var Intersects = __webpack_require__(131); /** * Takes two Rectangles and first checks to see if they intersect. @@ -162797,7 +160573,7 @@ module.exports = Intersection; /***/ }), -/* 1166 */ +/* 1162 */ /***/ (function(module, exports) { /** @@ -162846,7 +160622,7 @@ module.exports = MergePoints; /***/ }), -/* 1167 */ +/* 1163 */ /***/ (function(module, exports) { /** @@ -162893,7 +160669,7 @@ module.exports = MergeRect; /***/ }), -/* 1168 */ +/* 1164 */ /***/ (function(module, exports) { /** @@ -162937,7 +160713,7 @@ module.exports = MergeXY; /***/ }), -/* 1169 */ +/* 1165 */ /***/ (function(module, exports) { /** @@ -162972,7 +160748,7 @@ module.exports = Offset; /***/ }), -/* 1170 */ +/* 1166 */ /***/ (function(module, exports) { /** @@ -163006,7 +160782,7 @@ module.exports = OffsetPoint; /***/ }), -/* 1171 */ +/* 1167 */ /***/ (function(module, exports) { /** @@ -163040,7 +160816,7 @@ module.exports = Overlaps; /***/ }), -/* 1172 */ +/* 1168 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163053,18 +160829,18 @@ var Point = __webpack_require__(4); var DegToRad = __webpack_require__(35); /** - * Returns a Point from the perimeter of a Rectangle based on the given angle. + * [description] * * @function Phaser.Geom.Rectangle.PerimeterPoint * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. - * @param {integer} angle - The angle of the point, in degrees. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * @param {Phaser.Geom.Rectangle} rectangle - [description] + * @param {integer} angle - [description] + * @param {Phaser.Geom.Point} [out] - [description] * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of the Rectangle perimeter. + * @return {Phaser.Geom.Point} [description] */ var PerimeterPoint = function (rectangle, angle, out) { @@ -163097,7 +160873,7 @@ module.exports = PerimeterPoint; /***/ }), -/* 1173 */ +/* 1169 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163106,8 +160882,8 @@ module.exports = PerimeterPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Between = __webpack_require__(167); -var ContainsRect = __webpack_require__(438); +var Between = __webpack_require__(170); +var ContainsRect = __webpack_require__(437); var Point = __webpack_require__(4); /** @@ -163168,7 +160944,7 @@ module.exports = RandomOutside; /***/ }), -/* 1174 */ +/* 1170 */ /***/ (function(module, exports) { /** @@ -163197,7 +160973,7 @@ module.exports = SameDimensions; /***/ }), -/* 1175 */ +/* 1171 */ /***/ (function(module, exports) { /** @@ -163236,7 +161012,7 @@ module.exports = Scale; /***/ }), -/* 1176 */ +/* 1172 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163245,38 +161021,38 @@ module.exports = Scale; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); -Triangle.Area = __webpack_require__(1177); -Triangle.BuildEquilateral = __webpack_require__(1178); -Triangle.BuildFromPolygon = __webpack_require__(1179); -Triangle.BuildRight = __webpack_require__(1180); -Triangle.CenterOn = __webpack_require__(1181); -Triangle.Centroid = __webpack_require__(439); -Triangle.CircumCenter = __webpack_require__(1182); -Triangle.CircumCircle = __webpack_require__(1183); -Triangle.Clone = __webpack_require__(1184); -Triangle.Contains = __webpack_require__(81); -Triangle.ContainsArray = __webpack_require__(205); -Triangle.ContainsPoint = __webpack_require__(1185); -Triangle.CopyFrom = __webpack_require__(1186); -Triangle.Decompose = __webpack_require__(432); -Triangle.Equals = __webpack_require__(1187); -Triangle.GetPoint = __webpack_require__(418); -Triangle.GetPoints = __webpack_require__(419); -Triangle.InCenter = __webpack_require__(441); -Triangle.Perimeter = __webpack_require__(1188); -Triangle.Offset = __webpack_require__(440); -Triangle.Random = __webpack_require__(152); -Triangle.Rotate = __webpack_require__(1189); -Triangle.RotateAroundPoint = __webpack_require__(1190); -Triangle.RotateAroundXY = __webpack_require__(208); +Triangle.Area = __webpack_require__(1173); +Triangle.BuildEquilateral = __webpack_require__(1174); +Triangle.BuildFromPolygon = __webpack_require__(1175); +Triangle.BuildRight = __webpack_require__(1176); +Triangle.CenterOn = __webpack_require__(1177); +Triangle.Centroid = __webpack_require__(438); +Triangle.CircumCenter = __webpack_require__(1178); +Triangle.CircumCircle = __webpack_require__(1179); +Triangle.Clone = __webpack_require__(1180); +Triangle.Contains = __webpack_require__(83); +Triangle.ContainsArray = __webpack_require__(207); +Triangle.ContainsPoint = __webpack_require__(1181); +Triangle.CopyFrom = __webpack_require__(1182); +Triangle.Decompose = __webpack_require__(431); +Triangle.Equals = __webpack_require__(1183); +Triangle.GetPoint = __webpack_require__(417); +Triangle.GetPoints = __webpack_require__(418); +Triangle.InCenter = __webpack_require__(440); +Triangle.Perimeter = __webpack_require__(1184); +Triangle.Offset = __webpack_require__(439); +Triangle.Random = __webpack_require__(155); +Triangle.Rotate = __webpack_require__(1185); +Triangle.RotateAroundPoint = __webpack_require__(1186); +Triangle.RotateAroundXY = __webpack_require__(210); module.exports = Triangle; /***/ }), -/* 1177 */ +/* 1173 */ /***/ (function(module, exports) { /** @@ -163315,7 +161091,7 @@ module.exports = Area; /***/ }), -/* 1178 */ +/* 1174 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163324,7 +161100,7 @@ module.exports = Area; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); /** * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). @@ -163359,7 +161135,7 @@ module.exports = BuildEquilateral; /***/ }), -/* 1179 */ +/* 1175 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163368,12 +161144,11 @@ module.exports = BuildEquilateral; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var EarCut = __webpack_require__(64); -var Triangle = __webpack_require__(69); +var EarCut = __webpack_require__(66); +var Triangle = __webpack_require__(71); /** - * 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. + * [description] * * @function Phaser.Geom.Triangle.BuildFromPolygon * @since 3.0.0 @@ -163382,11 +161157,11 @@ var Triangle = __webpack_require__(69); * * @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. + * @param {number} [scaleX=1] - [description] + * @param {number} [scaleY=1] - [description] + * @param {(array|Phaser.Geom.Triangle[])} [out] - [description] * - * @return {(array|Phaser.Geom.Triangle[])} An array of Triangle instances, where each triangle is based on the decomposed vertices data. + * @return {(array|Phaser.Geom.Triangle[])} [description] */ var BuildFromPolygon = function (data, holes, scaleX, scaleY, out) { @@ -163435,7 +161210,7 @@ module.exports = BuildFromPolygon; /***/ }), -/* 1180 */ +/* 1176 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163444,7 +161219,7 @@ module.exports = BuildFromPolygon; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); // 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) @@ -163484,7 +161259,7 @@ module.exports = BuildRight; /***/ }), -/* 1181 */ +/* 1177 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163493,8 +161268,8 @@ module.exports = BuildRight; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Centroid = __webpack_require__(439); -var Offset = __webpack_require__(440); +var Centroid = __webpack_require__(438); +var Offset = __webpack_require__(439); /** * @callback CenterFunction @@ -163537,7 +161312,7 @@ module.exports = CenterOn; /***/ }), -/* 1182 */ +/* 1178 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163581,10 +161356,10 @@ function det (m00, m01, m10, m11) * * @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. + * @param {Phaser.Geom.Triangle} triangle - [description] + * @param {Phaser.Math.Vector2} [out] - [description] * - * @return {Phaser.Math.Vector2} A Vector2 object holding the coordinates of the circumcenter of the Triangle. + * @return {Phaser.Math.Vector2} [description] */ var CircumCenter = function (triangle, out) { @@ -163613,7 +161388,7 @@ module.exports = CircumCenter; /***/ }), -/* 1183 */ +/* 1179 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163622,7 +161397,7 @@ module.exports = CircumCenter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); // Adapted from https://gist.github.com/mutoo/5617691 @@ -163696,7 +161471,7 @@ module.exports = CircumCircle; /***/ }), -/* 1184 */ +/* 1180 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163705,7 +161480,7 @@ module.exports = CircumCircle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Triangle = __webpack_require__(69); +var Triangle = __webpack_require__(71); /** * Clones a Triangle object. @@ -163726,7 +161501,7 @@ module.exports = Clone; /***/ }), -/* 1185 */ +/* 1181 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163735,7 +161510,7 @@ module.exports = Clone; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Contains = __webpack_require__(81); +var Contains = __webpack_require__(83); /** * Tests if a triangle contains a point. @@ -163757,7 +161532,7 @@ module.exports = ContainsPoint; /***/ }), -/* 1186 */ +/* 1182 */ /***/ (function(module, exports) { /** @@ -163788,7 +161563,7 @@ module.exports = CopyFrom; /***/ }), -/* 1187 */ +/* 1183 */ /***/ (function(module, exports) { /** @@ -163824,7 +161599,7 @@ module.exports = Equals; /***/ }), -/* 1188 */ +/* 1184 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163835,16 +161610,17 @@ module.exports = Equals; var Length = __webpack_require__(57); +// The 2D area of a triangle. The area value is always non-negative. + /** * Gets the length of the perimeter of the given triangle. - * Calculated by adding together the length of each of the three sides. * * @function Phaser.Geom.Triangle.Perimeter * @since 3.0.0 * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the length from. + * @param {Phaser.Geom.Triangle} triangle - [description] * - * @return {number} The length of the Triangle. + * @return {number} [description] */ var Perimeter = function (triangle) { @@ -163859,7 +161635,7 @@ module.exports = Perimeter; /***/ }), -/* 1189 */ +/* 1185 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163868,8 +161644,8 @@ module.exports = Perimeter; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(208); -var InCenter = __webpack_require__(441); +var RotateAroundXY = __webpack_require__(210); +var InCenter = __webpack_require__(440); /** * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. @@ -163895,7 +161671,7 @@ module.exports = Rotate; /***/ }), -/* 1190 */ +/* 1186 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163904,7 +161680,7 @@ module.exports = Rotate; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RotateAroundXY = __webpack_require__(208); +var RotateAroundXY = __webpack_require__(210); /** * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. @@ -163929,7 +161705,7 @@ module.exports = RotateAroundPoint; /***/ }), -/* 1191 */ +/* 1187 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163938,8 +161714,8 @@ module.exports = RotateAroundPoint; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(174); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(177); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Input @@ -163947,16 +161723,16 @@ var Extend = __webpack_require__(18); var Input = { - CreateInteractiveObject: __webpack_require__(442), + CreateInteractiveObject: __webpack_require__(441), Events: __webpack_require__(54), - Gamepad: __webpack_require__(1192), - InputManager: __webpack_require__(360), - InputPlugin: __webpack_require__(1204), - InputPluginCache: __webpack_require__(130), - Keyboard: __webpack_require__(1206), - Mouse: __webpack_require__(1223), - Pointer: __webpack_require__(363), - Touch: __webpack_require__(1224) + Gamepad: __webpack_require__(1188), + InputManager: __webpack_require__(359), + InputPlugin: __webpack_require__(1200), + InputPluginCache: __webpack_require__(132), + Keyboard: __webpack_require__(1202), + Mouse: __webpack_require__(1219), + Pointer: __webpack_require__(362), + Touch: __webpack_require__(1220) }; @@ -163967,7 +161743,7 @@ module.exports = Input; /***/ }), -/* 1192 */ +/* 1188 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -163982,18 +161758,18 @@ module.exports = Input; module.exports = { - Axis: __webpack_require__(443), - Button: __webpack_require__(444), - Events: __webpack_require__(209), - Gamepad: __webpack_require__(445), - GamepadPlugin: __webpack_require__(1199), + Axis: __webpack_require__(442), + Button: __webpack_require__(443), + Events: __webpack_require__(211), + Gamepad: __webpack_require__(444), + GamepadPlugin: __webpack_require__(1195), - Configs: __webpack_require__(1200) + Configs: __webpack_require__(1196) }; /***/ }), -/* 1193 */ +/* 1189 */ /***/ (function(module, exports) { /** @@ -164022,7 +161798,7 @@ module.exports = 'down'; /***/ }), -/* 1194 */ +/* 1190 */ /***/ (function(module, exports) { /** @@ -164051,7 +161827,7 @@ module.exports = 'up'; /***/ }), -/* 1195 */ +/* 1191 */ /***/ (function(module, exports) { /** @@ -164082,7 +161858,7 @@ module.exports = 'connected'; /***/ }), -/* 1196 */ +/* 1192 */ /***/ (function(module, exports) { /** @@ -164108,7 +161884,7 @@ module.exports = 'disconnected'; /***/ }), -/* 1197 */ +/* 1193 */ /***/ (function(module, exports) { /** @@ -164140,7 +161916,7 @@ module.exports = 'down'; /***/ }), -/* 1198 */ +/* 1194 */ /***/ (function(module, exports) { /** @@ -164172,7 +161948,7 @@ module.exports = 'up'; /***/ }), -/* 1199 */ +/* 1195 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164182,11 +161958,11 @@ module.exports = 'up'; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(209); -var Gamepad = __webpack_require__(445); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(211); +var Gamepad = __webpack_require__(444); var GetValue = __webpack_require__(6); -var InputPluginCache = __webpack_require__(130); +var InputPluginCache = __webpack_require__(132); var InputEvents = __webpack_require__(54); /** @@ -164810,7 +162586,7 @@ module.exports = GamepadPlugin; /***/ }), -/* 1200 */ +/* 1196 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164825,15 +162601,15 @@ module.exports = GamepadPlugin; module.exports = { - DUALSHOCK_4: __webpack_require__(1201), - SNES_USB: __webpack_require__(1202), - XBOX_360: __webpack_require__(1203) + DUALSHOCK_4: __webpack_require__(1197), + SNES_USB: __webpack_require__(1198), + XBOX_360: __webpack_require__(1199) }; /***/ }), -/* 1201 */ +/* 1197 */ /***/ (function(module, exports) { /** @@ -164883,7 +162659,7 @@ module.exports = { /***/ }), -/* 1202 */ +/* 1198 */ /***/ (function(module, exports) { /** @@ -164922,7 +162698,7 @@ module.exports = { /***/ }), -/* 1203 */ +/* 1199 */ /***/ (function(module, exports) { /** @@ -164973,7 +162749,7 @@ module.exports = { /***/ }), -/* 1204 */ +/* 1200 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -164982,27 +162758,27 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Circle = __webpack_require__(63); +var Circle = __webpack_require__(65); var CircleContains = __webpack_require__(55); var Class = __webpack_require__(0); -var CONST = __webpack_require__(174); -var CreateInteractiveObject = __webpack_require__(442); -var CreatePixelPerfectHandler = __webpack_require__(1205); +var CONST = __webpack_require__(177); +var CreateInteractiveObject = __webpack_require__(441); +var CreatePixelPerfectHandler = __webpack_require__(1201); var DistanceBetween = __webpack_require__(53); -var Ellipse = __webpack_require__(93); -var EllipseContains = __webpack_require__(94); +var Ellipse = __webpack_require__(95); +var EllipseContains = __webpack_require__(96); var Events = __webpack_require__(54); -var EventEmitter = __webpack_require__(11); +var EventEmitter = __webpack_require__(9); var GetFastValue = __webpack_require__(2); var GEOM_CONST = __webpack_require__(46); -var InputPluginCache = __webpack_require__(130); +var InputPluginCache = __webpack_require__(132); var IsPlainObject = __webpack_require__(7); -var PluginCache = __webpack_require__(24); -var Rectangle = __webpack_require__(13); +var PluginCache = __webpack_require__(23); +var Rectangle = __webpack_require__(11); var RectangleContains = __webpack_require__(47); -var SceneEvents = __webpack_require__(22); -var Triangle = __webpack_require__(69); -var TriangleContains = __webpack_require__(81); +var SceneEvents = __webpack_require__(19); +var Triangle = __webpack_require__(71); +var TriangleContains = __webpack_require__(83); /** * @classdesc @@ -168125,7 +165901,7 @@ module.exports = InputPlugin; /***/ }), -/* 1205 */ +/* 1201 */ /***/ (function(module, exports) { /** @@ -168161,7 +165937,7 @@ module.exports = CreatePixelPerfectHandler; /***/ }), -/* 1206 */ +/* 1202 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168176,26 +165952,26 @@ module.exports = CreatePixelPerfectHandler; module.exports = { - Events: __webpack_require__(131), + Events: __webpack_require__(133), - KeyboardManager: __webpack_require__(361), - KeyboardPlugin: __webpack_require__(1214), + KeyboardManager: __webpack_require__(360), + KeyboardPlugin: __webpack_require__(1210), - Key: __webpack_require__(446), - KeyCodes: __webpack_require__(118), + Key: __webpack_require__(445), + KeyCodes: __webpack_require__(122), - KeyCombo: __webpack_require__(447), + KeyCombo: __webpack_require__(446), - JustDown: __webpack_require__(1219), - JustUp: __webpack_require__(1220), - DownDuration: __webpack_require__(1221), - UpDuration: __webpack_require__(1222) + JustDown: __webpack_require__(1215), + JustUp: __webpack_require__(1216), + DownDuration: __webpack_require__(1217), + UpDuration: __webpack_require__(1218) }; /***/ }), -/* 1207 */ +/* 1203 */ /***/ (function(module, exports) { /** @@ -168231,7 +166007,7 @@ module.exports = 'keydown'; /***/ }), -/* 1208 */ +/* 1204 */ /***/ (function(module, exports) { /** @@ -168260,7 +166036,7 @@ module.exports = 'keyup'; /***/ }), -/* 1209 */ +/* 1205 */ /***/ (function(module, exports) { /** @@ -168294,7 +166070,7 @@ module.exports = 'keycombomatch'; /***/ }), -/* 1210 */ +/* 1206 */ /***/ (function(module, exports) { /** @@ -168328,7 +166104,7 @@ module.exports = 'down'; /***/ }), -/* 1211 */ +/* 1207 */ /***/ (function(module, exports) { /** @@ -168367,7 +166143,7 @@ module.exports = 'keydown-'; /***/ }), -/* 1212 */ +/* 1208 */ /***/ (function(module, exports) { /** @@ -168399,7 +166175,7 @@ module.exports = 'keyup-'; /***/ }), -/* 1213 */ +/* 1209 */ /***/ (function(module, exports) { /** @@ -168433,7 +166209,7 @@ module.exports = 'up'; /***/ }), -/* 1214 */ +/* 1210 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -168443,17 +166219,17 @@ module.exports = 'up'; */ var Class = __webpack_require__(0); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(131); -var GameEvents = __webpack_require__(19); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(133); +var GameEvents = __webpack_require__(18); var GetValue = __webpack_require__(6); var InputEvents = __webpack_require__(54); -var InputPluginCache = __webpack_require__(130); -var Key = __webpack_require__(446); -var KeyCodes = __webpack_require__(118); -var KeyCombo = __webpack_require__(447); -var KeyMap = __webpack_require__(1218); -var SnapFloor = __webpack_require__(91); +var InputPluginCache = __webpack_require__(132); +var Key = __webpack_require__(445); +var KeyCodes = __webpack_require__(122); +var KeyCombo = __webpack_require__(446); +var KeyMap = __webpack_require__(1214); +var SnapFloor = __webpack_require__(93); /** * @classdesc @@ -169319,7 +167095,7 @@ module.exports = KeyboardPlugin; /***/ }), -/* 1215 */ +/* 1211 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169328,7 +167104,7 @@ module.exports = KeyboardPlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AdvanceKeyCombo = __webpack_require__(1216); +var AdvanceKeyCombo = __webpack_require__(1212); /** * Used internally by the KeyCombo class. @@ -169400,7 +167176,7 @@ module.exports = ProcessKeyCombo; /***/ }), -/* 1216 */ +/* 1212 */ /***/ (function(module, exports) { /** @@ -169442,7 +167218,7 @@ module.exports = AdvanceKeyCombo; /***/ }), -/* 1217 */ +/* 1213 */ /***/ (function(module, exports) { /** @@ -169477,7 +167253,7 @@ module.exports = ResetKeyCombo; /***/ }), -/* 1218 */ +/* 1214 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169486,7 +167262,7 @@ module.exports = ResetKeyCombo; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var KeyCodes = __webpack_require__(118); +var KeyCodes = __webpack_require__(122); var KeyMap = {}; @@ -169499,7 +167275,7 @@ module.exports = KeyMap; /***/ }), -/* 1219 */ +/* 1215 */ /***/ (function(module, exports) { /** @@ -169541,7 +167317,7 @@ module.exports = JustDown; /***/ }), -/* 1220 */ +/* 1216 */ /***/ (function(module, exports) { /** @@ -169583,7 +167359,7 @@ module.exports = JustUp; /***/ }), -/* 1221 */ +/* 1217 */ /***/ (function(module, exports) { /** @@ -169617,7 +167393,7 @@ module.exports = DownDuration; /***/ }), -/* 1222 */ +/* 1218 */ /***/ (function(module, exports) { /** @@ -169651,7 +167427,7 @@ module.exports = UpDuration; /***/ }), -/* 1223 */ +/* 1219 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169667,14 +167443,14 @@ module.exports = UpDuration; /* eslint-disable */ module.exports = { - MouseManager: __webpack_require__(362) + MouseManager: __webpack_require__(361) }; /* eslint-enable */ /***/ }), -/* 1224 */ +/* 1220 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169690,14 +167466,14 @@ module.exports = { /* eslint-disable */ module.exports = { - TouchManager: __webpack_require__(364) + TouchManager: __webpack_require__(363) }; /* eslint-enable */ /***/ }), -/* 1225 */ +/* 1221 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169707,7 +167483,7 @@ module.exports = { */ var CONST = __webpack_require__(20); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Loader @@ -169715,18 +167491,18 @@ var Extend = __webpack_require__(18); var Loader = { - Events: __webpack_require__(80), + Events: __webpack_require__(81), - FileTypes: __webpack_require__(1226), + FileTypes: __webpack_require__(1222), File: __webpack_require__(21), FileTypesManager: __webpack_require__(8), - GetURL: __webpack_require__(132), - LoaderPlugin: __webpack_require__(1250), - MergeXHRSettings: __webpack_require__(210), + GetURL: __webpack_require__(134), + LoaderPlugin: __webpack_require__(1246), + MergeXHRSettings: __webpack_require__(212), MultiFile: __webpack_require__(61), - XHRLoader: __webpack_require__(448), - XHRSettings: __webpack_require__(133) + XHRLoader: __webpack_require__(447), + XHRSettings: __webpack_require__(135) }; @@ -169737,7 +167513,7 @@ module.exports = Loader; /***/ }), -/* 1226 */ +/* 1222 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169752,42 +167528,42 @@ module.exports = Loader; module.exports = { - AnimationJSONFile: __webpack_require__(1227), - AtlasJSONFile: __webpack_require__(1228), - AtlasXMLFile: __webpack_require__(1229), - AudioFile: __webpack_require__(449), - AudioSpriteFile: __webpack_require__(1230), - BinaryFile: __webpack_require__(1231), - BitmapFontFile: __webpack_require__(1232), - CSSFile: __webpack_require__(1233), - GLSLFile: __webpack_require__(1234), - HTML5AudioFile: __webpack_require__(450), - HTMLFile: __webpack_require__(1235), - HTMLTextureFile: __webpack_require__(1236), - ImageFile: __webpack_require__(70), + AnimationJSONFile: __webpack_require__(1223), + AtlasJSONFile: __webpack_require__(1224), + AtlasXMLFile: __webpack_require__(1225), + AudioFile: __webpack_require__(448), + AudioSpriteFile: __webpack_require__(1226), + BinaryFile: __webpack_require__(1227), + BitmapFontFile: __webpack_require__(1228), + CSSFile: __webpack_require__(1229), + GLSLFile: __webpack_require__(1230), + HTML5AudioFile: __webpack_require__(449), + HTMLFile: __webpack_require__(1231), + HTMLTextureFile: __webpack_require__(1232), + ImageFile: __webpack_require__(72), JSONFile: __webpack_require__(60), - MultiAtlasFile: __webpack_require__(1237), - MultiScriptFile: __webpack_require__(1238), - PackFile: __webpack_require__(1239), - PluginFile: __webpack_require__(1240), - SceneFile: __webpack_require__(1241), - ScenePluginFile: __webpack_require__(1242), - ScriptFile: __webpack_require__(451), - SpriteSheetFile: __webpack_require__(1243), - SVGFile: __webpack_require__(1244), - TextFile: __webpack_require__(452), - TilemapCSVFile: __webpack_require__(1245), - TilemapImpactFile: __webpack_require__(1246), - TilemapJSONFile: __webpack_require__(1247), - UnityAtlasFile: __webpack_require__(1248), - VideoFile: __webpack_require__(1249), - XMLFile: __webpack_require__(211) + MultiAtlasFile: __webpack_require__(1233), + MultiScriptFile: __webpack_require__(1234), + PackFile: __webpack_require__(1235), + PluginFile: __webpack_require__(1236), + SceneFile: __webpack_require__(1237), + ScenePluginFile: __webpack_require__(1238), + ScriptFile: __webpack_require__(450), + SpriteSheetFile: __webpack_require__(1239), + SVGFile: __webpack_require__(1240), + TextFile: __webpack_require__(451), + TilemapCSVFile: __webpack_require__(1241), + TilemapImpactFile: __webpack_require__(1242), + TilemapJSONFile: __webpack_require__(1243), + UnityAtlasFile: __webpack_require__(1244), + VideoFile: __webpack_require__(1245), + XMLFile: __webpack_require__(213) }; /***/ }), -/* 1227 */ +/* 1223 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -169799,7 +167575,7 @@ module.exports = { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(60); -var LoaderEvents = __webpack_require__(80); +var LoaderEvents = __webpack_require__(81); /** * @classdesc @@ -169963,7 +167739,7 @@ var AnimationJSONFile = new Class({ * @param {string} [dataKey] - When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('animation', function (key, url, dataKey, xhrSettings) { @@ -169990,7 +167766,7 @@ module.exports = AnimationJSONFile; /***/ }), -/* 1228 */ +/* 1224 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -170002,7 +167778,7 @@ module.exports = AnimationJSONFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(60); var MultiFile = __webpack_require__(61); @@ -170206,7 +167982,7 @@ var AtlasJSONFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('atlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { @@ -170239,7 +168015,7 @@ module.exports = AtlasJSONFile; /***/ }), -/* 1229 */ +/* 1225 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -170251,10 +168027,10 @@ module.exports = AtlasJSONFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var XMLFile = __webpack_require__(211); +var XMLFile = __webpack_require__(213); /** * @classdesc @@ -170449,7 +168225,7 @@ var AtlasXMLFile = new Class({ * @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 xml file. Used in replacement of the Loaders default XHR Settings. * - * @return {this} The Loader instance. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('atlasXML', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { @@ -170482,7 +168258,7 @@ module.exports = AtlasXMLFile; /***/ }), -/* 1230 */ +/* 1226 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -170491,7 +168267,7 @@ module.exports = AtlasXMLFile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AudioFile = __webpack_require__(449); +var AudioFile = __webpack_require__(448); var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); @@ -170725,7 +168501,7 @@ var AudioSpriteFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader. */ FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) { @@ -170772,7 +168548,7 @@ FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audio /***/ }), -/* 1231 */ +/* 1227 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -170930,7 +168706,7 @@ var BinaryFile = new Class({ * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('binary', function (key, url, dataType, xhrSettings) { @@ -170954,7 +168730,7 @@ module.exports = BinaryFile; /***/ }), -/* 1232 */ +/* 1228 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -170966,11 +168742,11 @@ module.exports = BinaryFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var ParseXMLBitmapFont = __webpack_require__(182); -var XMLFile = __webpack_require__(211); +var ParseXMLBitmapFont = __webpack_require__(185); +var XMLFile = __webpack_require__(213); /** * @classdesc @@ -171164,7 +168940,7 @@ var BitmapFontFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('bitmapFont', function (key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) { @@ -171197,7 +168973,7 @@ module.exports = BitmapFontFile; /***/ }), -/* 1233 */ +/* 1229 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -171341,7 +169117,7 @@ var CSSFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('css', function (key, url, xhrSettings) { @@ -171365,7 +169141,7 @@ module.exports = CSSFile; /***/ }), -/* 1234 */ +/* 1230 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -171380,7 +169156,7 @@ var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); -var Shader = __webpack_require__(348); +var Shader = __webpack_require__(347); /** * @classdesc @@ -171752,7 +169528,7 @@ var GLSLFile = new Class({ * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('glsl', function (key, url, shaderType, xhrSettings) { @@ -171776,7 +169552,7 @@ module.exports = GLSLFile; /***/ }), -/* 1235 */ +/* 1231 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -171927,7 +169703,7 @@ var HTMLFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('html', function (key, url, xhrSettings) { @@ -171951,7 +169727,7 @@ module.exports = HTMLFile; /***/ }), -/* 1236 */ +/* 1232 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -172185,7 +169961,7 @@ var HTMLTextureFile = new Class({ * @param {integer} [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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('htmlTexture', function (key, url, width, height, xhrSettings) { @@ -172209,7 +169985,7 @@ module.exports = HTMLTextureFile; /***/ }), -/* 1237 */ +/* 1233 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -172221,7 +169997,7 @@ module.exports = HTMLTextureFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(60); var MultiFile = __webpack_require__(61); @@ -172509,7 +170285,7 @@ var MultiAtlasFile = new Class({ * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('multiatlas', function (key, atlasURL, path, baseURL, atlasXhrSettings) { @@ -172542,7 +170318,7 @@ module.exports = MultiAtlasFile; /***/ }), -/* 1238 */ +/* 1234 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -172556,7 +170332,7 @@ var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var ScriptFile = __webpack_require__(451); +var ScriptFile = __webpack_require__(450); /** * @classdesc @@ -172726,7 +170502,7 @@ var MultiScriptFile = new Class({ * @param {string} [extension='js'] - The default file extension to use if no url is provided. * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for these files. * - * @return {this} The Loader instance. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('scripts', function (key, url, xhrSettings) { @@ -172759,7 +170535,7 @@ module.exports = MultiScriptFile; /***/ }), -/* 1239 */ +/* 1235 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -172950,7 +170726,7 @@ var PackFile = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('pack', function (key, url, packKey, xhrSettings) { @@ -172977,7 +170753,7 @@ module.exports = PackFile; /***/ }), -/* 1240 */ +/* 1236 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173165,7 +170941,7 @@ var PluginFile = new Class({ * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('plugin', function (key, url, start, mapping, xhrSettings) { @@ -173189,7 +170965,7 @@ module.exports = PluginFile; /***/ }), -/* 1241 */ +/* 1237 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173386,7 +171162,7 @@ var SceneFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('sceneFile', function (key, url, xhrSettings) { @@ -173410,7 +171186,7 @@ module.exports = SceneFile; /***/ }), -/* 1242 */ +/* 1238 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173592,7 +171368,7 @@ var ScenePluginFile = new Class({ * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('scenePlugin', function (key, url, systemKey, sceneKey, xhrSettings) { @@ -173616,7 +171392,7 @@ module.exports = ScenePluginFile; /***/ }), -/* 1243 */ +/* 1239 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -173627,7 +171403,7 @@ module.exports = ScenePluginFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); /** * @classdesc @@ -173783,7 +171559,7 @@ var SpriteSheetFile = new Class({ * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. At a minimum it should have a `frameWidth` property. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('spritesheet', function (key, url, frameConfig, xhrSettings) { @@ -173807,7 +171583,7 @@ module.exports = SpriteSheetFile; /***/ }), -/* 1244 */ +/* 1240 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174121,7 +171897,7 @@ var SVGFile = new Class({ * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('svg', function (key, url, svgConfig, xhrSettings) { @@ -174146,7 +171922,7 @@ module.exports = SVGFile; /***/ }), -/* 1245 */ +/* 1241 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174161,7 +171937,7 @@ var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); -var TILEMAP_FORMATS = __webpack_require__(33); +var TILEMAP_FORMATS = __webpack_require__(31); /** * @classdesc @@ -174317,7 +172093,7 @@ var TilemapCSVFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('tilemapCSV', function (key, url, xhrSettings) { @@ -174341,7 +172117,7 @@ module.exports = TilemapCSVFile; /***/ }), -/* 1246 */ +/* 1242 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174353,7 +172129,7 @@ module.exports = TilemapCSVFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(60); -var TILEMAP_FORMATS = __webpack_require__(33); +var TILEMAP_FORMATS = __webpack_require__(31); /** * @classdesc @@ -174473,7 +172249,7 @@ var TilemapImpactFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('tilemapImpact', function (key, url, xhrSettings) { @@ -174497,7 +172273,7 @@ module.exports = TilemapImpactFile; /***/ }), -/* 1247 */ +/* 1243 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174509,7 +172285,7 @@ module.exports = TilemapImpactFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(60); -var TILEMAP_FORMATS = __webpack_require__(33); +var TILEMAP_FORMATS = __webpack_require__(31); /** * @classdesc @@ -174629,7 +172405,7 @@ var TilemapJSONFile = new Class({ * @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('tilemapTiledJSON', function (key, url, xhrSettings) { @@ -174653,7 +172429,7 @@ module.exports = TilemapJSONFile; /***/ }), -/* 1248 */ +/* 1244 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174665,10 +172441,10 @@ module.exports = TilemapJSONFile; var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var ImageFile = __webpack_require__(70); +var ImageFile = __webpack_require__(72); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(61); -var TextFile = __webpack_require__(452); +var TextFile = __webpack_require__(451); /** * @classdesc @@ -174862,7 +172638,7 @@ var UnityAtlasFile = new Class({ * @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 data file. Used in replacement of the Loaders default XHR Settings. * - * @return {this} The Loader instance. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('unityAtlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { @@ -174895,7 +172671,7 @@ module.exports = UnityAtlasFile; /***/ }), -/* 1249 */ +/* 1245 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -174905,10 +172681,10 @@ module.exports = UnityAtlasFile; */ var Class = __webpack_require__(0); -var CONST = __webpack_require__(10); +var CONST = __webpack_require__(29); var File = __webpack_require__(21); var FileTypesManager = __webpack_require__(8); -var GetURL = __webpack_require__(132); +var GetURL = __webpack_require__(134); var GetFastValue = __webpack_require__(2); var IsPlainObject = __webpack_require__(7); @@ -175250,7 +173026,7 @@ VideoFile.getVideoURL = function (game, urls) * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. * @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. + * @return {Phaser.Loader.LoaderPlugin} The Loader instance. */ FileTypesManager.register('video', function (key, urls, loadEvent, asBlob, noAudio, xhrSettings) { @@ -175286,7 +173062,7 @@ module.exports = VideoFile; /***/ }), -/* 1250 */ +/* 1246 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -175297,14 +173073,14 @@ module.exports = VideoFile; var Class = __webpack_require__(0); var CONST = __webpack_require__(20); -var CustomSet = __webpack_require__(127); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(80); +var CustomSet = __webpack_require__(108); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(81); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var XHRSettings = __webpack_require__(133); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var XHRSettings = __webpack_require__(135); /** * @classdesc @@ -175485,8 +173261,7 @@ var LoaderPlugin = new Class({ GetFastValue(sceneConfig, 'async', gameConfig.loaderAsync), GetFastValue(sceneConfig, 'user', gameConfig.loaderUser), GetFastValue(sceneConfig, 'password', gameConfig.loaderPassword), - GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout), - GetFastValue(sceneConfig, 'withCredentials', gameConfig.loaderWithCredentials) + GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout) ); /** @@ -175659,7 +173434,7 @@ var LoaderPlugin = new Class({ * * @param {string} [url] - The URL to use. Leave empty to reset. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setBaseURL: function (url) { @@ -175699,7 +173474,7 @@ var LoaderPlugin = new Class({ * * @param {string} [path] - The path to use. Leave empty to reset. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setPath: function (path) { @@ -175728,7 +173503,7 @@ var LoaderPlugin = new Class({ * * @param {string} [prefix] - The prefix to use. Leave empty to reset. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setPrefix: function (prefix) { @@ -175754,7 +173529,7 @@ var LoaderPlugin = new Class({ * * @param {string} [crossOrigin] - The value to use for the `crossOrigin` property in the load request. * - * @return {this} This Loader object. + * @return {Phaser.Loader.LoaderPlugin} This Loader object. */ setCORS: function (crossOrigin) { @@ -176243,7 +174018,7 @@ var LoaderPlugin = new Class({ * @param {*} data - The JSON data, ready parsed. * @param {string} [filename=file.json] - The name to save the JSON file as. * - * @return {this} This Loader plugin. + * @return {Phaser.Loader.LoaderPlugin} This Loader plugin. */ saveJSON: function (data, filename) { @@ -176263,7 +174038,7 @@ var LoaderPlugin = new Class({ * @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. + * @return {Phaser.Loader.LoaderPlugin} This Loader plugin. */ save: function (data, filename, filetype) { @@ -176364,7 +174139,7 @@ module.exports = LoaderPlugin; /***/ }), -/* 1251 */ +/* 1247 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176374,7 +174149,7 @@ module.exports = LoaderPlugin; */ var CONST = __webpack_require__(50); -var Extend = __webpack_require__(18); +var Extend = __webpack_require__(17); /** * @callback ArcadePhysicsCallback @@ -176389,18 +174164,18 @@ var Extend = __webpack_require__(18); var Arcade = { - ArcadePhysics: __webpack_require__(1252), - Body: __webpack_require__(459), - Collider: __webpack_require__(460), - Components: __webpack_require__(212), - Events: __webpack_require__(213), - Factory: __webpack_require__(453), - Group: __webpack_require__(455), - Image: __webpack_require__(454), - Sprite: __webpack_require__(134), - StaticBody: __webpack_require__(465), - StaticGroup: __webpack_require__(456), - World: __webpack_require__(458) + ArcadePhysics: __webpack_require__(1248), + Body: __webpack_require__(458), + Collider: __webpack_require__(459), + Components: __webpack_require__(214), + Events: __webpack_require__(215), + Factory: __webpack_require__(452), + Group: __webpack_require__(454), + Image: __webpack_require__(453), + Sprite: __webpack_require__(136), + StaticBody: __webpack_require__(464), + StaticGroup: __webpack_require__(455), + World: __webpack_require__(457) }; @@ -176411,7 +174186,7 @@ module.exports = Arcade; /***/ }), -/* 1252 */ +/* 1248 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -176423,16 +174198,16 @@ module.exports = Arcade; var Class = __webpack_require__(0); var DegToRad = __webpack_require__(35); var DistanceBetween = __webpack_require__(53); -var DistanceSquared = __webpack_require__(315); -var Factory = __webpack_require__(453); +var DistanceSquared = __webpack_require__(316); +var Factory = __webpack_require__(452); var GetFastValue = __webpack_require__(2); -var Merge = __webpack_require__(120); -var OverlapCirc = __webpack_require__(1265); -var OverlapRect = __webpack_require__(457); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); +var Merge = __webpack_require__(107); +var OverlapCirc = __webpack_require__(1261); +var OverlapRect = __webpack_require__(456); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); var Vector2 = __webpack_require__(3); -var World = __webpack_require__(458); +var World = __webpack_require__(457); /** * @classdesc @@ -177100,7 +174875,7 @@ module.exports = ArcadePhysics; /***/ }), -/* 1253 */ +/* 1249 */ /***/ (function(module, exports) { /** @@ -177175,7 +174950,7 @@ module.exports = Acceleration; /***/ }), -/* 1254 */ +/* 1250 */ /***/ (function(module, exports) { /** @@ -177257,7 +175032,7 @@ module.exports = Angular; /***/ }), -/* 1255 */ +/* 1251 */ /***/ (function(module, exports) { /** @@ -177356,7 +175131,7 @@ module.exports = Bounce; /***/ }), -/* 1256 */ +/* 1252 */ /***/ (function(module, exports) { /** @@ -177483,7 +175258,7 @@ module.exports = Debug; /***/ }), -/* 1257 */ +/* 1253 */ /***/ (function(module, exports) { /** @@ -177616,7 +175391,7 @@ module.exports = Drag; /***/ }), -/* 1258 */ +/* 1254 */ /***/ (function(module, exports) { /** @@ -177740,7 +175515,7 @@ module.exports = Enable; /***/ }), -/* 1259 */ +/* 1255 */ /***/ (function(module, exports) { /** @@ -177818,7 +175593,7 @@ module.exports = Friction; /***/ }), -/* 1260 */ +/* 1256 */ /***/ (function(module, exports) { /** @@ -177896,7 +175671,7 @@ module.exports = Gravity; /***/ }), -/* 1261 */ +/* 1257 */ /***/ (function(module, exports) { /** @@ -177938,7 +175713,7 @@ module.exports = Immovable; /***/ }), -/* 1262 */ +/* 1258 */ /***/ (function(module, exports) { /** @@ -177978,7 +175753,7 @@ module.exports = Mass; /***/ }), -/* 1263 */ +/* 1259 */ /***/ (function(module, exports) { /** @@ -178060,7 +175835,7 @@ module.exports = Size; /***/ }), -/* 1264 */ +/* 1260 */ /***/ (function(module, exports) { /** @@ -178159,13 +175934,13 @@ module.exports = Velocity; /***/ }), -/* 1265 */ +/* 1261 */ /***/ (function(module, exports, __webpack_require__) { -var OverlapRect = __webpack_require__(457); -var Circle = __webpack_require__(63); -var CircleToCircle = __webpack_require__(200); -var CircleToRectangle = __webpack_require__(201); +var OverlapRect = __webpack_require__(456); +var Circle = __webpack_require__(65); +var CircleToCircle = __webpack_require__(202); +var CircleToRectangle = __webpack_require__(203); /** * This method will search the given circular area and return an array of all physics bodies that @@ -178227,7 +176002,7 @@ module.exports = OverlapCirc; /***/ }), -/* 1266 */ +/* 1262 */ /***/ (function(module, exports) { /** @@ -178260,7 +176035,7 @@ module.exports = 'collide'; /***/ }), -/* 1267 */ +/* 1263 */ /***/ (function(module, exports) { /** @@ -178293,7 +176068,7 @@ module.exports = 'overlap'; /***/ }), -/* 1268 */ +/* 1264 */ /***/ (function(module, exports) { /** @@ -178316,7 +176091,7 @@ module.exports = 'pause'; /***/ }), -/* 1269 */ +/* 1265 */ /***/ (function(module, exports) { /** @@ -178339,7 +176114,7 @@ module.exports = 'resume'; /***/ }), -/* 1270 */ +/* 1266 */ /***/ (function(module, exports) { /** @@ -178371,7 +176146,7 @@ module.exports = 'tilecollide'; /***/ }), -/* 1271 */ +/* 1267 */ /***/ (function(module, exports) { /** @@ -178403,7 +176178,7 @@ module.exports = 'tileoverlap'; /***/ }), -/* 1272 */ +/* 1268 */ /***/ (function(module, exports) { /** @@ -178435,7 +176210,7 @@ module.exports = 'worldbounds'; /***/ }), -/* 1273 */ +/* 1269 */ /***/ (function(module, exports) { /** @@ -178461,7 +176236,7 @@ module.exports = 'worldstep'; /***/ }), -/* 1274 */ +/* 1270 */ /***/ (function(module, exports) { /** @@ -178502,7 +176277,7 @@ module.exports = ProcessTileCallbacks; /***/ }), -/* 1275 */ +/* 1271 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178511,9 +176286,9 @@ module.exports = ProcessTileCallbacks; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var TileCheckX = __webpack_require__(1276); -var TileCheckY = __webpack_require__(1278); -var TileIntersectsBody = __webpack_require__(464); +var TileCheckX = __webpack_require__(1272); +var TileCheckY = __webpack_require__(1274); +var TileIntersectsBody = __webpack_require__(463); /** * The core separation function to separate a physics body and a tile. @@ -178622,7 +176397,7 @@ module.exports = SeparateTile; /***/ }), -/* 1276 */ +/* 1272 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178631,7 +176406,7 @@ module.exports = SeparateTile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ProcessTileSeparationX = __webpack_require__(1277); +var ProcessTileSeparationX = __webpack_require__(1273); /** * Check the body against the given tile on the X axis. @@ -178712,7 +176487,7 @@ module.exports = TileCheckX; /***/ }), -/* 1277 */ +/* 1273 */ /***/ (function(module, exports) { /** @@ -178759,7 +176534,7 @@ module.exports = ProcessTileSeparationX; /***/ }), -/* 1278 */ +/* 1274 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178768,7 +176543,7 @@ module.exports = ProcessTileSeparationX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ProcessTileSeparationY = __webpack_require__(1279); +var ProcessTileSeparationY = __webpack_require__(1275); /** * Check the body against the given tile on the Y axis. @@ -178849,7 +176624,7 @@ module.exports = TileCheckY; /***/ }), -/* 1279 */ +/* 1275 */ /***/ (function(module, exports) { /** @@ -178896,7 +176671,7 @@ module.exports = ProcessTileSeparationY; /***/ }), -/* 1280 */ +/* 1276 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178905,7 +176680,7 @@ module.exports = ProcessTileSeparationY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetOverlapX = __webpack_require__(461); +var GetOverlapX = __webpack_require__(460); /** * Separates two overlapping bodies on the X-axis (horizontally). @@ -178987,7 +176762,7 @@ module.exports = SeparateX; /***/ }), -/* 1281 */ +/* 1277 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -178996,7 +176771,7 @@ module.exports = SeparateX; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetOverlapY = __webpack_require__(462); +var GetOverlapY = __webpack_require__(461); /** * Separates two overlapping bodies on the Y-axis (vertically). @@ -179078,7 +176853,62 @@ module.exports = SeparateY; /***/ }), -/* 1282 */ +/* 1278 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Impact.Events + */ + +module.exports = { + + COLLIDE: __webpack_require__(1392), + PAUSE: __webpack_require__(1393), + RESUME: __webpack_require__(1394) + +}; + + +/***/ }), +/* 1279 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Impact.Components + */ + +module.exports = { + + Acceleration: __webpack_require__(1396), + BodyScale: __webpack_require__(1397), + BodyType: __webpack_require__(1398), + Bounce: __webpack_require__(1399), + CheckAgainst: __webpack_require__(1400), + Collides: __webpack_require__(1401), + Debug: __webpack_require__(1402), + Friction: __webpack_require__(1403), + Gravity: __webpack_require__(1404), + Offset: __webpack_require__(1405), + SetGameObject: __webpack_require__(1406), + Velocity: __webpack_require__(1407) + +}; + + +/***/ }), +/* 1280 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179094,11 +176924,11 @@ var Composites = {}; module.exports = Composites; -var Composite = __webpack_require__(142); -var Constraint = __webpack_require__(214); +var Composite = __webpack_require__(145); +var Constraint = __webpack_require__(216); var Common = __webpack_require__(37); var Body = __webpack_require__(62); -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); (function() { @@ -179411,7 +177241,7 @@ var Bodies = __webpack_require__(105); /***/ }), -/* 1283 */ +/* 1281 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179428,7 +177258,7 @@ var Svg = {}; module.exports = Svg; -var Bounds = __webpack_require__(98); +var Bounds = __webpack_require__(102); var Common = __webpack_require__(37); (function() { @@ -179642,7 +177472,7 @@ var Common = __webpack_require__(37); })(); /***/ }), -/* 1284 */ +/* 1282 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179653,11 +177483,11 @@ var Common = __webpack_require__(37); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); var Body = __webpack_require__(62); var Common = __webpack_require__(37); var GetFastValue = __webpack_require__(2); -var Vertices = __webpack_require__(84); +var Vertices = __webpack_require__(86); /** * Use PhysicsEditorParser.parseBody() to build a Matter body object, based on a physics data file @@ -179784,7 +177614,7 @@ module.exports = PhysicsEditorParser; /***/ }), -/* 1285 */ +/* 1283 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179793,7 +177623,7 @@ module.exports = PhysicsEditorParser; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); var Body = __webpack_require__(62); /** @@ -179901,7 +177731,7 @@ module.exports = PhysicsJSONParser; /***/ }), -/* 1286 */ +/* 1284 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179916,28 +177746,28 @@ module.exports = PhysicsJSONParser; module.exports = { - AFTER_ADD: __webpack_require__(1399), - AFTER_REMOVE: __webpack_require__(1400), - AFTER_UPDATE: __webpack_require__(1401), - BEFORE_ADD: __webpack_require__(1402), - BEFORE_REMOVE: __webpack_require__(1403), - BEFORE_UPDATE: __webpack_require__(1404), - COLLISION_ACTIVE: __webpack_require__(1405), - COLLISION_END: __webpack_require__(1406), - COLLISION_START: __webpack_require__(1407), - DRAG_END: __webpack_require__(1408), - DRAG: __webpack_require__(1409), - DRAG_START: __webpack_require__(1410), - PAUSE: __webpack_require__(1411), - RESUME: __webpack_require__(1412), - SLEEP_END: __webpack_require__(1413), - SLEEP_START: __webpack_require__(1414) + AFTER_ADD: __webpack_require__(1424), + AFTER_REMOVE: __webpack_require__(1425), + AFTER_UPDATE: __webpack_require__(1426), + BEFORE_ADD: __webpack_require__(1427), + BEFORE_REMOVE: __webpack_require__(1428), + BEFORE_UPDATE: __webpack_require__(1429), + COLLISION_ACTIVE: __webpack_require__(1430), + COLLISION_END: __webpack_require__(1431), + COLLISION_START: __webpack_require__(1432), + DRAG_END: __webpack_require__(1433), + DRAG: __webpack_require__(1434), + DRAG_START: __webpack_require__(1435), + PAUSE: __webpack_require__(1436), + RESUME: __webpack_require__(1437), + SLEEP_END: __webpack_require__(1438), + SLEEP_START: __webpack_require__(1439) }; /***/ }), -/* 1287 */ +/* 1285 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -179946,14 +177776,13 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); var Body = __webpack_require__(62); var Class = __webpack_require__(0); -var Components = __webpack_require__(509); -var EventEmitter = __webpack_require__(11); +var Components = __webpack_require__(508); var GetFastValue = __webpack_require__(2); -var HasValue = __webpack_require__(104); -var Vertices = __webpack_require__(84); +var HasValue = __webpack_require__(99); +var Vertices = __webpack_require__(86); /** * @classdesc @@ -179970,7 +177799,6 @@ var Vertices = __webpack_require__(84); * * @class TileBody * @memberof Phaser.Physics.Matter - * @extends Phaser.Events.EventEmitter * @constructor * @since 3.0.0 * @@ -179989,8 +177817,6 @@ var Vertices = __webpack_require__(84); */ var MatterTileBody = new Class({ - Extends: EventEmitter, - Mixins: [ Components.Bounce, Components.Collision, @@ -180006,8 +177832,6 @@ var MatterTileBody = new Class({ function MatterTileBody (world, tile, options) { - EventEmitter.call(this); - /** * The tile object the body is associated with. * @@ -180248,7 +178072,6 @@ var MatterTileBody = new Class({ { this.removeBody(); this.tile.physics.matterBody = undefined; - this.removeAllListeners(); } }); @@ -180257,7 +178080,7 @@ module.exports = MatterTileBody; /***/ }), -/* 1288 */ +/* 1286 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180270,36 +178093,36 @@ module.exports = MatterTileBody; * @namespace Phaser.Physics.Matter.Matter */ -var Matter = __webpack_require__(1381); +var Matter = __webpack_require__(1383); Matter.Body = __webpack_require__(62); -Matter.Composite = __webpack_require__(142); -Matter.World = __webpack_require__(1290); +Matter.Composite = __webpack_require__(145); +Matter.World = __webpack_require__(1288); -Matter.Detector = __webpack_require__(510); -Matter.Grid = __webpack_require__(1291); -Matter.Pairs = __webpack_require__(1292); -Matter.Pair = __webpack_require__(466); -Matter.Query = __webpack_require__(1382); -Matter.Resolver = __webpack_require__(1293); -Matter.SAT = __webpack_require__(511); +Matter.Detector = __webpack_require__(509); +Matter.Grid = __webpack_require__(1289); +Matter.Pairs = __webpack_require__(1290); +Matter.Pair = __webpack_require__(467); +Matter.Query = __webpack_require__(1384); +Matter.Resolver = __webpack_require__(1291); +Matter.SAT = __webpack_require__(510); -Matter.Constraint = __webpack_require__(214); +Matter.Constraint = __webpack_require__(216); Matter.Common = __webpack_require__(37); -Matter.Engine = __webpack_require__(1383); -Matter.Events = __webpack_require__(235); -Matter.Sleeping = __webpack_require__(234); -Matter.Plugin = __webpack_require__(1289); +Matter.Engine = __webpack_require__(1385); +Matter.Events = __webpack_require__(237); +Matter.Sleeping = __webpack_require__(236); +Matter.Plugin = __webpack_require__(1287); -Matter.Bodies = __webpack_require__(105); -Matter.Composites = __webpack_require__(1282); +Matter.Bodies = __webpack_require__(109); +Matter.Composites = __webpack_require__(1280); -Matter.Axes = __webpack_require__(508); -Matter.Bounds = __webpack_require__(98); -Matter.Svg = __webpack_require__(1283); -Matter.Vector = __webpack_require__(97); -Matter.Vertices = __webpack_require__(84); +Matter.Axes = __webpack_require__(507); +Matter.Bounds = __webpack_require__(102); +Matter.Svg = __webpack_require__(1281); +Matter.Vector = __webpack_require__(101); +Matter.Vertices = __webpack_require__(86); // aliases @@ -180314,7 +178137,7 @@ module.exports = Matter; /***/ }), -/* 1289 */ +/* 1287 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180664,7 +178487,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 1290 */ +/* 1288 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180684,8 +178507,8 @@ var World = {}; module.exports = World; -var Composite = __webpack_require__(142); -var Constraint = __webpack_require__(214); +var Composite = __webpack_require__(145); +var Constraint = __webpack_require__(216); var Common = __webpack_require__(37); (function() { @@ -180817,7 +178640,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 1291 */ +/* 1289 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -180830,8 +178653,8 @@ var Grid = {}; module.exports = Grid; -var Pair = __webpack_require__(466); -var Detector = __webpack_require__(510); +var Pair = __webpack_require__(467); +var Detector = __webpack_require__(509); var Common = __webpack_require__(37); (function() { @@ -181144,7 +178967,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 1292 */ +/* 1290 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181157,7 +178980,7 @@ var Pairs = {}; module.exports = Pairs; -var Pair = __webpack_require__(466); +var Pair = __webpack_require__(467); var Common = __webpack_require__(37); (function() { @@ -181309,7 +179132,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 1293 */ +/* 1291 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181322,10 +179145,10 @@ var Resolver = {}; module.exports = Resolver; -var Vertices = __webpack_require__(84); -var Vector = __webpack_require__(97); +var Vertices = __webpack_require__(86); +var Vector = __webpack_require__(101); var Common = __webpack_require__(37); -var Bounds = __webpack_require__(98); +var Bounds = __webpack_require__(102); (function() { @@ -181665,7 +179488,7 @@ var Bounds = __webpack_require__(98); /***/ }), -/* 1294 */ +/* 1292 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181680,17 +179503,17 @@ var Bounds = __webpack_require__(98); module.exports = { - BasePlugin: __webpack_require__(467), - DefaultPlugins: __webpack_require__(170), - PluginCache: __webpack_require__(24), - PluginManager: __webpack_require__(365), - ScenePlugin: __webpack_require__(1295) + BasePlugin: __webpack_require__(468), + DefaultPlugins: __webpack_require__(173), + PluginCache: __webpack_require__(23), + PluginManager: __webpack_require__(364), + ScenePlugin: __webpack_require__(1293) }; /***/ }), -/* 1295 */ +/* 1293 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181699,9 +179522,9 @@ module.exports = { * @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} */ -var BasePlugin = __webpack_require__(467); +var BasePlugin = __webpack_require__(468); var Class = __webpack_require__(0); -var SceneEvents = __webpack_require__(22); +var SceneEvents = __webpack_require__(19); /** * @classdesc @@ -181818,7 +179641,7 @@ module.exports = ScenePlugin; /***/ }), -/* 1296 */ +/* 1294 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181827,8 +179650,8 @@ module.exports = ScenePlugin; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); -var CONST = __webpack_require__(172); +var Extend = __webpack_require__(17); +var CONST = __webpack_require__(175); /** * @namespace Phaser.Scale @@ -181856,12 +179679,12 @@ var CONST = __webpack_require__(172); var Scale = { - Center: __webpack_require__(354), - Events: __webpack_require__(90), - Orientation: __webpack_require__(355), - ScaleManager: __webpack_require__(366), - ScaleModes: __webpack_require__(356), - Zoom: __webpack_require__(357) + Center: __webpack_require__(353), + Events: __webpack_require__(92), + Orientation: __webpack_require__(354), + ScaleManager: __webpack_require__(365), + ScaleModes: __webpack_require__(355), + Zoom: __webpack_require__(356) }; @@ -181874,7 +179697,7 @@ module.exports = Scale; /***/ }), -/* 1297 */ +/* 1295 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181883,8 +179706,8 @@ module.exports = Scale; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(119); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(123); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Scenes @@ -181892,11 +179715,11 @@ var Extend = __webpack_require__(18); var Scene = { - Events: __webpack_require__(22), - SceneManager: __webpack_require__(368), - ScenePlugin: __webpack_require__(1298), - Settings: __webpack_require__(370), - Systems: __webpack_require__(175) + Events: __webpack_require__(19), + SceneManager: __webpack_require__(367), + ScenePlugin: __webpack_require__(1296), + Settings: __webpack_require__(369), + Systems: __webpack_require__(178) }; @@ -181907,7 +179730,7 @@ module.exports = Scene; /***/ }), -/* 1298 */ +/* 1296 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -181916,11 +179739,11 @@ module.exports = Scene; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); var Class = __webpack_require__(0); -var Events = __webpack_require__(22); +var Events = __webpack_require__(19); var GetFastValue = __webpack_require__(2); -var PluginCache = __webpack_require__(24); +var PluginCache = __webpack_require__(23); /** * @classdesc @@ -182917,7 +180740,7 @@ module.exports = ScenePlugin; /***/ }), -/* 1299 */ +/* 1297 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -182932,18 +180755,18 @@ module.exports = ScenePlugin; module.exports = { - List: __webpack_require__(123), - Map: __webpack_require__(156), - ProcessQueue: __webpack_require__(181), - RTree: __webpack_require__(463), - Set: __webpack_require__(127), - Size: __webpack_require__(367) + List: __webpack_require__(126), + Map: __webpack_require__(159), + ProcessQueue: __webpack_require__(184), + RTree: __webpack_require__(462), + Set: __webpack_require__(108), + Size: __webpack_require__(366) }; /***/ }), -/* 1300 */ +/* 1298 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -182952,8 +180775,8 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Extend = __webpack_require__(18); -var FilterMode = __webpack_require__(1301); +var Extend = __webpack_require__(17); +var FilterMode = __webpack_require__(1299); /** * @namespace Phaser.Textures @@ -182979,14 +180802,14 @@ var FilterMode = __webpack_require__(1301); var Textures = { - CanvasTexture: __webpack_require__(372), - Events: __webpack_require__(115), + CanvasTexture: __webpack_require__(371), + Events: __webpack_require__(119), FilterMode: FilterMode, - Frame: __webpack_require__(92), - Parsers: __webpack_require__(374), - Texture: __webpack_require__(177), - TextureManager: __webpack_require__(371), - TextureSource: __webpack_require__(373) + Frame: __webpack_require__(94), + Parsers: __webpack_require__(373), + Texture: __webpack_require__(180), + TextureManager: __webpack_require__(370), + TextureSource: __webpack_require__(372) }; @@ -182996,7 +180819,7 @@ module.exports = Textures; /***/ }), -/* 1301 */ +/* 1299 */ /***/ (function(module, exports) { /** @@ -183040,7 +180863,7 @@ module.exports = CONST; /***/ }), -/* 1302 */ +/* 1300 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183055,30 +180878,30 @@ module.exports = CONST; module.exports = { - Components: __webpack_require__(135), - Parsers: __webpack_require__(1335), + Components: __webpack_require__(137), + Parsers: __webpack_require__(1330), - Formats: __webpack_require__(33), - ImageCollection: __webpack_require__(480), - ParseToTilemap: __webpack_require__(222), - Tile: __webpack_require__(72), - Tilemap: __webpack_require__(489), - TilemapCreator: __webpack_require__(1344), - TilemapFactory: __webpack_require__(1345), - Tileset: __webpack_require__(137), + Formats: __webpack_require__(31), + ImageCollection: __webpack_require__(479), + ParseToTilemap: __webpack_require__(224), + Tile: __webpack_require__(74), + Tilemap: __webpack_require__(488), + TilemapCreator: __webpack_require__(1339), + TilemapFactory: __webpack_require__(1340), + Tileset: __webpack_require__(141), - LayerData: __webpack_require__(100), - MapData: __webpack_require__(101), - ObjectLayer: __webpack_require__(483), + LayerData: __webpack_require__(104), + MapData: __webpack_require__(105), + ObjectLayer: __webpack_require__(482), - DynamicTilemapLayer: __webpack_require__(490), - StaticTilemapLayer: __webpack_require__(491) + DynamicTilemapLayer: __webpack_require__(489), + StaticTilemapLayer: __webpack_require__(490) }; /***/ }), -/* 1303 */ +/* 1301 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183087,7 +180910,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); var CalculateFacesWithin = __webpack_require__(51); /** @@ -183143,7 +180966,7 @@ module.exports = Copy; /***/ }), -/* 1304 */ +/* 1302 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183152,9 +180975,10 @@ module.exports = Copy; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ - -var GetTilesWithin = __webpack_require__(25); -var ReplaceByIndex = __webpack_require__(468); +var TileToWorldX = __webpack_require__(139); +var TileToWorldY = __webpack_require__(140); +var GetTilesWithin = __webpack_require__(24); +var ReplaceByIndex = __webpack_require__(469); /** * Creates a Sprite for every object matching the given tile indexes in the layer. You can @@ -183195,9 +181019,9 @@ var CreateFromTiles = function (indexes, replacements, spriteConfig, scene, came if (indexes.indexOf(tile.index) !== -1) { - var point = tilemapLayer.tileToWorldXY(tile.x,tile.y, undefined, camera); - spriteConfig.x = point.x; - spriteConfig.y = point.y; + spriteConfig.x = TileToWorldX(tile.x, camera, layer); + spriteConfig.y = TileToWorldY(tile.y, camera, layer); + var sprite = scene.make.sprite(spriteConfig); sprites.push(sprite); } @@ -183227,7 +181051,7 @@ module.exports = CreateFromTiles; /***/ }), -/* 1305 */ +/* 1303 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183236,10 +181060,8 @@ module.exports = CreateFromTiles; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var SnapFloor = __webpack_require__(91); -var SnapCeil = __webpack_require__(324); -var CheckIsoBounds = __webpack_require__(1306); +var SnapFloor = __webpack_require__(93); +var SnapCeil = __webpack_require__(325); /** * Returns the tiles in the given layer that are within the camera's viewport. This is used internally. @@ -183281,224 +181103,100 @@ var CullTiles = function (layer, camera, outputArray, renderOrder) if (!tilemapLayer.skipCull && tilemapLayer.scrollFactorX === 1 && tilemapLayer.scrollFactorY === 1) { - if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) - { - // Camera world view bounds, snapped for scaled tile size - // Cull Padding values are given in tiles, not pixels - var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; - var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; + // Camera world view bounds, snapped for scaled tile size + // Cull Padding values are given in tiles, not pixels - var boundsTop; - var boundsBottom; + var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; + var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; + var boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; + var boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; - if (layer.orientation === CONST.ORTHOGONAL) - { - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; - } - else if (layer.orientation === CONST.STAGGERED) - { - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH / 2, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH / 2, 0, true) + tilemapLayer.cullPaddingY; - } - else if (layer.orientation === CONST.HEXAGONAL) - { - var sidel = layer.hexSideLength; - var rowH = ((tileH - sidel) / 2 + sidel); - - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, rowH, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, rowH, 0, true) + tilemapLayer.cullPaddingY; - } - - - - - drawLeft = Math.max(0, boundsLeft); - drawRight = Math.min(mapWidth, boundsRight); - drawTop = Math.max(0, boundsTop); - - drawBottom = Math.min(mapHeight, boundsBottom); - } + drawLeft = Math.max(0, boundsLeft); + drawRight = Math.min(mapWidth, boundsRight); + drawTop = Math.max(0, boundsTop); + drawBottom = Math.min(mapHeight, boundsBottom); } + var x; var y; var tile; - - if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) + if (renderOrder === 0) { + // right-down - if (renderOrder === 0) + for (y = drawTop; y < drawBottom; y++) { - // right-down - - for (y = drawTop; y < drawBottom; y++) + for (x = drawLeft; mapData[y] && x < drawRight; x++) { - for (x = drawLeft; mapData[y] && x < drawRight; x++) + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); + continue; } - } - } - else if (renderOrder === 1) - { - // left-down - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } + outputArray.push(tile); } } } - else if (layer.orientation === CONST.ISOMETRIC) + else if (renderOrder === 1) { - if (renderOrder === 0) + // left-down + + for (y = drawTop; y < drawBottom; y++) { - // right-down - - for (y = drawTop; y < drawBottom; y++) + for (x = drawRight; mapData[y] && x >= drawLeft; x--) { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; + tile = mapData[y][x]; - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; } + + outputArray.push(tile); } } - else if (renderOrder === 1) - { - // left-down - - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - } + else if (renderOrder === 2) + { + // right-up + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } tilemapLayer.tilesDrawn = outputArray.length; tilemapLayer.tilesTotal = mapWidth * mapHeight; @@ -183510,47 +181208,7 @@ module.exports = CullTiles; /***/ }), -/* 1306 */ -/***/ (function(module, exports) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * @function Phaser.Tilemaps.Components.CheckIsoBounds - * @private - * @since 3.2.3 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to check against. - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. - */ -var CheckIsoBounds = function (tileX,tileY,layer,camera) -{ - var tilemapLayer = layer.tilemapLayer; - var cullDistances = tilemapLayer.isoCullDistances; - var pos = tilemapLayer.tileToWorldXY(tileX,tileY,undefined,camera); - - // we always subtract 1/2 of the tile's height/width to make the culling distance start from the center of the tiles. - return pos.x > camera.worldView.x + tilemapLayer.scaleX * layer.tileWidth * (- cullDistances.x - 1 / 2) - && pos.x < camera.worldView.right + tilemapLayer.scaleX * layer.tileWidth * (cullDistances.x - 1 / 2) - && pos.y > camera.worldView.y + tilemapLayer.scaleY * layer.tileHeight * (- cullDistances.y - 1 / 2) - && pos.y < camera.worldView.bottom + tilemapLayer.scaleY * layer.tileHeight * (cullDistances.y - 1 / 2); -}; - -module.exports = CheckIsoBounds; - - -/***/ }), -/* 1307 */ +/* 1304 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183559,9 +181217,9 @@ module.exports = CheckIsoBounds; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); var CalculateFacesWithin = __webpack_require__(51); -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); /** * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the @@ -183604,7 +181262,7 @@ module.exports = Fill; /***/ }), -/* 1308 */ +/* 1305 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183613,7 +181271,7 @@ module.exports = Fill; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given @@ -183652,7 +181310,7 @@ module.exports = FilterTiles; /***/ }), -/* 1309 */ +/* 1306 */ /***/ (function(module, exports) { /** @@ -183740,7 +181398,7 @@ module.exports = FindByIndex; /***/ }), -/* 1310 */ +/* 1307 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183749,7 +181407,7 @@ module.exports = FindByIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * @callback FindTileCallback @@ -183794,7 +181452,7 @@ module.exports = FindTile; /***/ }), -/* 1311 */ +/* 1308 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183803,7 +181461,7 @@ module.exports = FindTile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * @callback EachTileCallback @@ -183844,7 +181502,7 @@ module.exports = ForEachTile; /***/ }), -/* 1312 */ +/* 1309 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183853,7 +181511,9 @@ module.exports = ForEachTile; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTileAt = __webpack_require__(136); +var GetTileAt = __webpack_require__(138); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Gets a tile at the given world coordinates from the given layer. @@ -183873,9 +181533,9 @@ var GetTileAt = __webpack_require__(136); */ var GetTileAtWorldXY = function (worldX, worldY, nonNull, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + return GetTileAt(tileX, tileY, nonNull, layer); }; @@ -183883,7 +181543,7 @@ module.exports = GetTileAtWorldXY; /***/ }), -/* 1313 */ +/* 1310 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183892,11 +181552,14 @@ module.exports = GetTileAtWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Geom = __webpack_require__(423); -var GetTilesWithin = __webpack_require__(25); -var Intersects = __webpack_require__(424); +var Geom = __webpack_require__(422); +var GetTilesWithin = __webpack_require__(24); +var Intersects = __webpack_require__(423); var NOOP = __webpack_require__(1); - +var TileToWorldX = __webpack_require__(139); +var TileToWorldY = __webpack_require__(140); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); var TriangleToRectangle = function (triangle, rect) { @@ -183936,14 +181599,12 @@ var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle; } // Top left corner of the shapes's bounding box, rounded down to include partial tiles - var pointStart = layer.tilemapLayer.worldToTileXY(shape.left, shape.top, true, undefined, camera); - var xStart = pointStart.x; - var yStart = pointStart.y; + var xStart = WorldToTileX(shape.left, true, camera, layer); + var yStart = WorldToTileY(shape.top, true, camera, layer); // Bottom right corner of the shapes's bounding box, rounded up to include partial tiles - var pointEnd = layer.tilemapLayer.worldToTileXY(shape.right, shape.bottom, true, undefined, camera); - var xEnd = Math.ceil(pointEnd.x); - var yEnd = Math.ceil(pointEnd.y); + var xEnd = Math.ceil(WorldToTileX(shape.right, false, camera, layer)); + var yEnd = Math.ceil(WorldToTileY(shape.bottom, false, camera, layer)); // 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). @@ -183964,9 +181625,8 @@ var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; - var point = layer.tilemapLayer.tileToWorldXY(tile.x, tile.y, undefined, camera); - tileRect.x = point.x; - tileRect.y = point.y; + tileRect.x = TileToWorldX(tile.x, camera, layer); + tileRect.y = TileToWorldY(tile.y, camera, layer); if (intersectTest(shape, tileRect)) { results.push(tile); @@ -183980,7 +181640,7 @@ module.exports = GetTilesWithinShape; /***/ }), -/* 1314 */ +/* 1311 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -183989,7 +181649,9 @@ module.exports = GetTilesWithinShape; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Gets the tiles in the given rectangular area (in world coordinates) of the layer. @@ -184013,16 +181675,13 @@ var GetTilesWithin = __webpack_require__(25); */ var GetTilesWithinWorldXY = function (worldX, worldY, width, height, filteringOptions, camera, layer) { - // Top left corner of the rect, rounded down to include partial tiles - var pointStart = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var xStart = pointStart.x; - var yStart = pointStart.y; + var xStart = WorldToTileX(worldX, true, camera, layer); + var yStart = WorldToTileY(worldY, true, camera, layer); // Bottom right corner of the rect, rounded up to include partial tiles - var pointEnd = layer.tilemapLayer.worldToTileXY(worldX + width, worldY + height, false, undefined, camera); - var xEnd = Math.ceil(pointEnd.x); - var yEnd = Math.ceil(pointEnd.y); + var xEnd = Math.ceil(WorldToTileX(worldX + width, false, camera, layer)); + var yEnd = Math.ceil(WorldToTileY(worldY + height, false, camera, layer)); return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer); }; @@ -184031,7 +181690,7 @@ module.exports = GetTilesWithinWorldXY; /***/ }), -/* 1315 */ +/* 1312 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184040,7 +181699,9 @@ module.exports = GetTilesWithinWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var HasTileAt = __webpack_require__(469); +var HasTileAt = __webpack_require__(470); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns @@ -184059,9 +181720,9 @@ var HasTileAt = __webpack_require__(469); */ var HasTileAtWorldXY = function (worldX, worldY, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); + return HasTileAt(tileX, tileY, layer); }; @@ -184069,7 +181730,7 @@ module.exports = HasTileAtWorldXY; /***/ }), -/* 1316 */ +/* 1313 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184078,7 +181739,9 @@ module.exports = HasTileAtWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var PutTileAt = __webpack_require__(216); +var PutTileAt = __webpack_require__(218); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either @@ -184096,14 +181759,13 @@ var PutTileAt = __webpack_require__(216); * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. */ var PutTileAtWorldXY = function (tile, worldX, worldY, recalculateFaces, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); return PutTileAt(tile, tileX, tileY, recalculateFaces, layer); }; @@ -184111,7 +181773,7 @@ module.exports = PutTileAtWorldXY; /***/ }), -/* 1317 */ +/* 1314 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184121,7 +181783,7 @@ module.exports = PutTileAtWorldXY; */ var CalculateFacesWithin = __webpack_require__(51); -var PutTileAt = __webpack_require__(216); +var PutTileAt = __webpack_require__(218); /** * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified @@ -184139,7 +181801,6 @@ var PutTileAt = __webpack_require__(216); * @param {integer} tileY - The y coordinate, in tiles, not pixels. * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * */ var PutTilesAt = function (tilesArray, tileX, tileY, recalculateFaces, layer) { @@ -184176,7 +181837,7 @@ module.exports = PutTilesAt; /***/ }), -/* 1318 */ +/* 1315 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184185,8 +181846,8 @@ module.exports = PutTilesAt; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); -var GetRandom = __webpack_require__(180); +var GetTilesWithin = __webpack_require__(24); +var GetRandom = __webpack_require__(183); /** * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the @@ -184234,7 +181895,7 @@ module.exports = Randomize; /***/ }), -/* 1319 */ +/* 1316 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184243,8 +181904,9 @@ module.exports = Randomize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var RemoveTileAt = __webpack_require__(470); - +var RemoveTileAt = __webpack_require__(471); +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); /** * Removes the tile at the given world coordinates in the specified layer and updates the layer's @@ -184260,14 +181922,13 @@ var RemoveTileAt = __webpack_require__(470); * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. */ var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) { - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; + var tileX = WorldToTileX(worldX, true, camera, layer); + var tileY = WorldToTileY(worldY, true, camera, layer); return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); }; @@ -184275,7 +181936,7 @@ module.exports = RemoveTileAtWorldXY; /***/ }), -/* 1320 */ +/* 1317 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184284,8 +181945,8 @@ module.exports = RemoveTileAtWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); -var Color = __webpack_require__(349); +var GetTilesWithin = __webpack_require__(24); +var Color = __webpack_require__(348); var defaultTileColor = new Color(105, 210, 231, 150); var defaultCollidingTileColor = new Color(243, 134, 48, 200); @@ -184364,7 +182025,7 @@ module.exports = RenderDebug; /***/ }), -/* 1321 */ +/* 1318 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184373,9 +182034,9 @@ module.exports = RenderDebug; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var SetLayerCollisionIndex = __webpack_require__(217); +var SetLayerCollisionIndex = __webpack_require__(219); /** * Sets collision on the given tile or tiles within a layer by index. You can pass in either a @@ -184433,7 +182094,7 @@ module.exports = SetCollision; /***/ }), -/* 1322 */ +/* 1319 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184442,9 +182103,9 @@ module.exports = SetCollision; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var SetLayerCollisionIndex = __webpack_require__(217); +var SetLayerCollisionIndex = __webpack_require__(219); /** * Sets collision on a range of tiles in a layer whose index is between the specified `start` and @@ -184508,7 +182169,7 @@ module.exports = SetCollisionBetween; /***/ }), -/* 1323 */ +/* 1320 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184517,9 +182178,9 @@ module.exports = SetCollisionBetween; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var SetLayerCollisionIndex = __webpack_require__(217); +var SetLayerCollisionIndex = __webpack_require__(219); /** * Sets collision on all tiles in the given layer, except for tiles that have an index specified in @@ -184565,7 +182226,7 @@ module.exports = SetCollisionByExclusion; /***/ }), -/* 1324 */ +/* 1321 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184574,9 +182235,9 @@ module.exports = SetCollisionByExclusion; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); -var HasValue = __webpack_require__(104); +var HasValue = __webpack_require__(99); /** * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property @@ -184640,7 +182301,7 @@ module.exports = SetCollisionByProperty; /***/ }), -/* 1325 */ +/* 1322 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184649,7 +182310,7 @@ module.exports = SetCollisionByProperty; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var SetTileCollision = __webpack_require__(71); +var SetTileCollision = __webpack_require__(73); var CalculateFacesWithin = __webpack_require__(51); /** @@ -184700,7 +182361,7 @@ module.exports = SetCollisionFromCollisionGroup; /***/ }), -/* 1326 */ +/* 1323 */ /***/ (function(module, exports) { /** @@ -184747,7 +182408,7 @@ module.exports = SetTileIndexCallback; /***/ }), -/* 1327 */ +/* 1324 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184756,7 +182417,7 @@ module.exports = SetTileIndexCallback; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. @@ -184790,7 +182451,7 @@ module.exports = SetTileLocationCallback; /***/ }), -/* 1328 */ +/* 1325 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184799,8 +182460,8 @@ module.exports = SetTileLocationCallback; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); -var ShuffleArray = __webpack_require__(110); +var GetTilesWithin = __webpack_require__(24); +var ShuffleArray = __webpack_require__(114); /** * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given @@ -184835,7 +182496,7 @@ module.exports = Shuffle; /***/ }), -/* 1329 */ +/* 1326 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184844,7 +182505,7 @@ module.exports = Shuffle; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching @@ -184886,7 +182547,7 @@ module.exports = SwapByIndex; /***/ }), -/* 1330 */ +/* 1327 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -184895,74 +182556,8 @@ module.exports = SwapByIndex; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); - -/** - * Converts from orthogonal tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.TileToWorldX - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var OrthoTileToWorldX = function (tileX, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - var layerWorldX = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - - tileWidth *= tilemapLayer.scaleX; - } - - return layerWorldX + tileX * tileWidth; - - -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the TileToWorldXY function.'); - return null; -}; - -var TileToWorldX = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoTileToWorldX; - default: - return nullFunc; - } - -}; - -module.exports = TileToWorldX; - - -/***/ }), -/* 1331 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = __webpack_require__(10); +var TileToWorldX = __webpack_require__(139); +var TileToWorldY = __webpack_require__(140); var Vector2 = __webpack_require__(3); /** @@ -184970,7 +182565,7 @@ var Vector2 = __webpack_require__(3); * layer's position, scale and scroll. This will return a new Vector2 object or update the given * `point` object. * - * @function Phaser.Tilemaps.Components.OrthoTileToWorldXY + * @function Phaser.Tilemaps.Components.TileToWorldXY * @private * @since 3.0.0 * @@ -184979,196 +182574,24 @@ var Vector2 = __webpack_require__(3); * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Math.Vector2} The XY location in world coordinates. */ -var OrthoTileToWorldXY = function (tileX, tileY, point, camera, layer) +var TileToWorldXY = function (tileX, tileY, point, camera, layer) { if (point === undefined) { point = new Vector2(0, 0); } - - var tileHeight = layer.baseTileHeight; - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - var layerWorldX = 0; - var layerWorldY = 0; - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + point.x = TileToWorldX(tileX, camera, layer); + point.y = TileToWorldY(tileY, camera, layer); - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - - tileWidth *= tilemapLayer.scaleX; - - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - } - - point.x = layerWorldX + tileX * tileWidth; - point.y = layerWorldY + tileY * tileHeight; - - - return point; }; -/** - * Converts from isometric tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.IsoTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var IsoTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - point.x = layerWorldX + (tileX - tileY) * (tileWidth / 2); - point.y = layerWorldY + (tileX + tileY) * (tileHeight / 2); - - - return point; -}; - -/** - * Converts from staggered tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.StagTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var StagTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); - point.y = layerWorldY + tileY * (tileHeight / 2); - - return point; -}; - -/** - * Converts from hexagonal tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.HexTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var HexTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // similar to staggered, because Tiled uses the oddr representation. - point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); - point.y = layerWorldY + tileY * rowHeight; - - return point; -}; - -var TileToWorldXY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagTileToWorldXY; - case CONST.ISOMETRIC: - return IsoTileToWorldXY; - case CONST.HEXAGONAL: - return HexTileToWorldXY; - default: - return OrthoTileToWorldXY; - } - -}; - module.exports = TileToWorldXY; /***/ }), -/* 1332 */ +/* 1328 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185177,146 +182600,7 @@ module.exports = TileToWorldXY; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ - -var CONST = __webpack_require__(10); - -/** - * Converts from orthogonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.TileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var OrthoTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - return layerWorldY + tileY * tileHeight; - -}; - - - -/** - * Converts from staggered tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.StagTileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var StagTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - return layerWorldY + tileY * (tileHeight / 2); - -}; - - -/** - * Converts from hexagonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.HexTileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var HexTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - var sidel = layer.tilemapLayer.tilemap.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // same as staggered - return layerWorldY + tileY * rowHeight; -}; - - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the TileToWorldXY function.'); - return null; -}; - -var TileToWorldY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagTileToWorldY; - case CONST.ISOMETRIC: - return nullFunc; - case CONST.HEXAGONAL: - return HexTileToWorldY; - default: - return OrthoTileToWorldY; - - } - -}; - -module.exports = TileToWorldY; - - -/***/ }), -/* 1333 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = __webpack_require__(25); +var GetTilesWithin = __webpack_require__(24); /** * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the @@ -185387,7 +182671,7 @@ module.exports = WeightedRandomize; /***/ }), -/* 1334 */ +/* 1329 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185396,17 +182680,16 @@ module.exports = WeightedRandomize; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); -var WorldToTileX = __webpack_require__(471).func; -var WorldToTileY = __webpack_require__(472).func; +var WorldToTileX = __webpack_require__(63); +var WorldToTileY = __webpack_require__(64); var Vector2 = __webpack_require__(3); /** - * Converts from world XY coordinates (pixels) to orthogonal tile XY coordinates (tile units), factoring in the + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the * layer's position, scale and scroll. This will return a new Vector2 object or update the given * `point` object. * - * @function Phaser.Tilemaps.Components.OrthoWorldToTileXY + * @function Phaser.Tilemaps.Components.WorldToTileXY * @private * @since 3.0.0 * @@ -185416,215 +182699,24 @@ var Vector2 = __webpack_require__(3); * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * + * * @return {Phaser.Math.Vector2} The XY location in tile units. */ -var OrthoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +var WorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) { if (point === undefined) { point = new Vector2(0, 0); } point.x = WorldToTileX(worldX, snapToFloor, camera, layer); point.y = WorldToTileY(worldY, snapToFloor, camera, layer); - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to isometric tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.IsoWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var IsoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - point.x = snapToFloor - ? Math.floor((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2) - : ((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2); - - point.y = snapToFloor - ? Math.floor((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2) - : ((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2); return point; }; -/** - * Converts from world XY coordinates (pixels) to hexagonal tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.HexWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var HexWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // similar to staggered, because Tiled uses the oddr representation. - point.y = snapToFloor - ? Math.floor((worldY / rowHeight)) - : (worldY / rowHeight); - point.x = snapToFloor - ? Math.floor((worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth) - : (worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth; - - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to staggered tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.StagWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var StagWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - - point.y = snapToFloor - ? Math.floor((worldY / (tileHeight / 2))) - : (worldY / (tileHeight / 2)); - point.x = snapToFloor - ? Math.floor((worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth) - : (worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth; - - - } - - return point; -}; - -var WorldToTileXY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagWorldToTileXY; - - case CONST.ISOMETRIC: - return IsoWorldToTileXY; - - case CONST.HEXAGONAL: - return HexWorldToTileXY; - - default: - return OrthoWorldToTileXY; - - } - -}; - module.exports = WorldToTileXY; /***/ }), -/* 1335 */ +/* 1330 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185639,18 +182731,18 @@ module.exports = WorldToTileXY; module.exports = { - Parse: __webpack_require__(473), - Parse2DArray: __webpack_require__(218), - ParseCSV: __webpack_require__(474), + Parse: __webpack_require__(472), + Parse2DArray: __webpack_require__(220), + ParseCSV: __webpack_require__(473), - Impact: __webpack_require__(1336), - Tiled: __webpack_require__(1337) + Impact: __webpack_require__(1331), + Tiled: __webpack_require__(1332) }; /***/ }), -/* 1336 */ +/* 1331 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185665,15 +182757,15 @@ module.exports = { module.exports = { - ParseTileLayers: __webpack_require__(487), - ParseTilesets: __webpack_require__(488), - ParseWeltmeister: __webpack_require__(486) + ParseTileLayers: __webpack_require__(486), + ParseTilesets: __webpack_require__(487), + ParseWeltmeister: __webpack_require__(485) }; /***/ }), -/* 1337 */ +/* 1332 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185688,22 +182780,22 @@ module.exports = { module.exports = { - AssignTileProperties: __webpack_require__(485), - Base64Decode: __webpack_require__(477), - BuildTilesetIndex: __webpack_require__(484), - ParseGID: __webpack_require__(219), - ParseImageLayers: __webpack_require__(478), - ParseJSONTiled: __webpack_require__(475), - ParseObject: __webpack_require__(221), - ParseObjectLayers: __webpack_require__(482), - ParseTileLayers: __webpack_require__(476), - ParseTilesets: __webpack_require__(479) + AssignTileProperties: __webpack_require__(484), + Base64Decode: __webpack_require__(476), + BuildTilesetIndex: __webpack_require__(483), + ParseGID: __webpack_require__(221), + ParseImageLayers: __webpack_require__(477), + ParseJSONTiled: __webpack_require__(474), + ParseObject: __webpack_require__(223), + ParseObjectLayers: __webpack_require__(481), + ParseTileLayers: __webpack_require__(475), + ParseTilesets: __webpack_require__(478) }; /***/ }), -/* 1338 */ +/* 1333 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185717,12 +182809,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1339); + renderWebGL = __webpack_require__(1334); } if (true) { - renderCanvas = __webpack_require__(1340); + renderCanvas = __webpack_require__(1335); } module.exports = { @@ -185734,7 +182826,7 @@ module.exports = { /***/ }), -/* 1339 */ +/* 1334 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -185743,9 +182835,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ - -var Utils = __webpack_require__(9); -var CONST = __webpack_require__(10); +var Utils = __webpack_require__(10); /** * Renders this Game Object with the WebGL Renderer to the given Camera. @@ -185816,26 +182906,14 @@ var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPer continue; } - var frameWidth = 0; - var frameHeight = 0; - - if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) - { - // we use the tileset width and height because in isometric maps the tileset's height is often different from the tilemap's. - frameWidth = tileset.tileWidth; - frameHeight = tileset.tileHeight; - } - else - { - frameWidth = tile.width; - frameHeight = tile.height; - } + var frameWidth = tile.width; + var frameHeight = tile.height; var frameX = tileTexCoords.x; var frameY = tileTexCoords.y; - var tw = frameWidth * 0.5; - var th = frameHeight * 0.5; + var tw = tile.width * 0.5; + var th = tile.height * 0.5; var tint = getTint(tile.tint, alpha * tile.alpha); @@ -185844,7 +182922,7 @@ var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPer texture, texture.width, texture.height, x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy), - frameWidth, frameHeight, + tile.width, tile.height, sx, sy, tile.rotation, tile.flipX, tile.flipY, @@ -185865,8 +182943,8 @@ module.exports = DynamicTilemapLayerWebGLRenderer; /***/ }), -/* 1340 */ -/***/ (function(module, exports, __webpack_require__) { +/* 1335 */ +/***/ (function(module, exports) { /** * @author Richard Davey @@ -185874,8 +182952,6 @@ module.exports = DynamicTilemapLayerWebGLRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(10); - /** * Renders this Game Object with the Canvas Renderer to the given Camera. * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. @@ -185897,6 +182973,7 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe var renderTiles = src.culledTiles; var tileCount = renderTiles.length; + if (tileCount === 0) { return; @@ -185946,8 +183023,8 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe for (var i = 0; i < tileCount; i++) { - var tile = renderTiles[i]; + var tileset = gidMap[tile.index]; if (!tileset) @@ -185956,23 +183033,12 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe } var image = tileset.image.getSourceImage(); - var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); - + if (tileTexCoords) { - var width = tile.width; - var height = tile.width; - - if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) - { - // we use the tileset width and height because in isometric and hexagonal maps the tileset's height is often different from the tilemap's. - width = tileset.tileWidth; - height = tileset.tileHeight; - } - - var halfWidth = width / 2; - var halfHeight = height / 2; + var halfWidth = tile.width / 2; + var halfHeight = tile.height / 2; ctx.save(); @@ -185989,18 +183055,17 @@ var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPe } ctx.globalAlpha = alpha * tile.alpha; - + ctx.drawImage( image, tileTexCoords.x, tileTexCoords.y, - tileset.tileWidth, tileset.tileHeight, + tile.width, tile.height, -halfWidth, -halfHeight, - width, height + tile.width, tile.height ); ctx.restore(); } - } ctx.restore(); @@ -186010,7 +183075,7 @@ module.exports = DynamicTilemapLayerCanvasRenderer; /***/ }), -/* 1341 */ +/* 1336 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186024,12 +183089,12 @@ var renderCanvas = __webpack_require__(1); if (true) { - renderWebGL = __webpack_require__(1342); + renderWebGL = __webpack_require__(1337); } if (true) { - renderCanvas = __webpack_require__(1343); + renderCanvas = __webpack_require__(1338); } module.exports = { @@ -186041,7 +183106,7 @@ module.exports = { /***/ }), -/* 1342 */ +/* 1337 */ /***/ (function(module, exports) { /** @@ -186113,7 +183178,7 @@ module.exports = StaticTilemapLayerWebGLRenderer; /***/ }), -/* 1343 */ +/* 1338 */ /***/ (function(module, exports) { /** @@ -186247,7 +183312,7 @@ module.exports = StaticTilemapLayerCanvasRenderer; /***/ }), -/* 1344 */ +/* 1339 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186256,8 +183321,8 @@ module.exports = StaticTilemapLayerCanvasRenderer; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var GameObjectCreator = __webpack_require__(17); -var ParseToTilemap = __webpack_require__(222); +var GameObjectCreator = __webpack_require__(16); +var ParseToTilemap = __webpack_require__(224); /** * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. @@ -186291,7 +183356,7 @@ GameObjectCreator.register('tilemap', function (config) /***/ }), -/* 1345 */ +/* 1340 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186301,7 +183366,7 @@ GameObjectCreator.register('tilemap', function (config) */ var GameObjectFactory = __webpack_require__(5); -var ParseToTilemap = __webpack_require__(222); +var ParseToTilemap = __webpack_require__(224); /** * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. @@ -186357,7 +183422,7 @@ GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, widt /***/ }), -/* 1346 */ +/* 1341 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186372,14 +183437,14 @@ GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, widt module.exports = { - Clock: __webpack_require__(1347), - TimerEvent: __webpack_require__(492) + Clock: __webpack_require__(1342), + TimerEvent: __webpack_require__(491) }; /***/ }), -/* 1347 */ +/* 1342 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186389,9 +183454,9 @@ module.exports = { */ var Class = __webpack_require__(0); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var TimerEvent = __webpack_require__(492); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var TimerEvent = __webpack_require__(491); /** * @classdesc @@ -186785,7 +183850,7 @@ module.exports = Clock; /***/ }), -/* 1348 */ +/* 1343 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186794,8 +183859,8 @@ module.exports = Clock; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var CONST = __webpack_require__(87); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(89); +var Extend = __webpack_require__(17); /** * @namespace Phaser.Tweens @@ -186803,13 +183868,13 @@ var Extend = __webpack_require__(18); var Tweens = { - Builders: __webpack_require__(1349), - Events: __webpack_require__(227), + Builders: __webpack_require__(1344), + Events: __webpack_require__(229), - TweenManager: __webpack_require__(1364), - Tween: __webpack_require__(226), - TweenData: __webpack_require__(228), - Timeline: __webpack_require__(498) + TweenManager: __webpack_require__(1359), + Tween: __webpack_require__(228), + TweenData: __webpack_require__(230), + Timeline: __webpack_require__(497) }; @@ -186820,7 +183885,7 @@ module.exports = Tweens; /***/ }), -/* 1349 */ +/* 1344 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -186835,23 +183900,23 @@ module.exports = Tweens; module.exports = { - GetBoolean: __webpack_require__(86), - GetEaseFunction: __webpack_require__(67), - GetNewValue: __webpack_require__(138), - GetProps: __webpack_require__(493), - GetTargets: __webpack_require__(223), - GetTweens: __webpack_require__(494), - GetValueOp: __webpack_require__(224), - NumberTweenBuilder: __webpack_require__(495), - StaggerBuilder: __webpack_require__(496), - TimelineBuilder: __webpack_require__(497), - TweenBuilder: __webpack_require__(139) + GetBoolean: __webpack_require__(88), + GetEaseFunction: __webpack_require__(82), + GetNewValue: __webpack_require__(142), + GetProps: __webpack_require__(492), + GetTargets: __webpack_require__(225), + GetTweens: __webpack_require__(493), + GetValueOp: __webpack_require__(226), + NumberTweenBuilder: __webpack_require__(494), + StaggerBuilder: __webpack_require__(495), + TimelineBuilder: __webpack_require__(496), + TweenBuilder: __webpack_require__(143) }; /***/ }), -/* 1350 */ +/* 1345 */ /***/ (function(module, exports) { /** @@ -186926,7 +183991,7 @@ module.exports = [ /***/ }), -/* 1351 */ +/* 1346 */ /***/ (function(module, exports) { /** @@ -186962,7 +184027,7 @@ module.exports = 'complete'; /***/ }), -/* 1352 */ +/* 1347 */ /***/ (function(module, exports) { /** @@ -186999,7 +184064,7 @@ module.exports = 'loop'; /***/ }), -/* 1353 */ +/* 1348 */ /***/ (function(module, exports) { /** @@ -187036,7 +184101,7 @@ module.exports = 'pause'; /***/ }), -/* 1354 */ +/* 1349 */ /***/ (function(module, exports) { /** @@ -187073,7 +184138,7 @@ module.exports = 'resume'; /***/ }), -/* 1355 */ +/* 1350 */ /***/ (function(module, exports) { /** @@ -187109,7 +184174,7 @@ module.exports = 'start'; /***/ }), -/* 1356 */ +/* 1351 */ /***/ (function(module, exports) { /** @@ -187146,7 +184211,7 @@ module.exports = 'update'; /***/ }), -/* 1357 */ +/* 1352 */ /***/ (function(module, exports) { /** @@ -187186,7 +184251,7 @@ module.exports = 'active'; /***/ }), -/* 1358 */ +/* 1353 */ /***/ (function(module, exports) { /** @@ -187227,7 +184292,7 @@ module.exports = 'complete'; /***/ }), -/* 1359 */ +/* 1354 */ /***/ (function(module, exports) { /** @@ -187271,7 +184336,7 @@ module.exports = 'loop'; /***/ }), -/* 1360 */ +/* 1355 */ /***/ (function(module, exports) { /** @@ -187316,7 +184381,7 @@ module.exports = 'repeat'; /***/ }), -/* 1361 */ +/* 1356 */ /***/ (function(module, exports) { /** @@ -187356,7 +184421,7 @@ module.exports = 'start'; /***/ }), -/* 1362 */ +/* 1357 */ /***/ (function(module, exports) { /** @@ -187399,7 +184464,7 @@ module.exports = 'update'; /***/ }), -/* 1363 */ +/* 1358 */ /***/ (function(module, exports) { /** @@ -187445,7 +184510,7 @@ module.exports = 'yoyo'; /***/ }), -/* 1364 */ +/* 1359 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -187454,15 +184519,15 @@ module.exports = 'yoyo'; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ArrayRemove = __webpack_require__(117); +var ArrayRemove = __webpack_require__(121); var Class = __webpack_require__(0); -var NumberTweenBuilder = __webpack_require__(495); -var PluginCache = __webpack_require__(24); -var SceneEvents = __webpack_require__(22); -var StaggerBuilder = __webpack_require__(496); -var TimelineBuilder = __webpack_require__(497); -var TWEEN_CONST = __webpack_require__(87); -var TweenBuilder = __webpack_require__(139); +var NumberTweenBuilder = __webpack_require__(494); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var StaggerBuilder = __webpack_require__(495); +var TimelineBuilder = __webpack_require__(496); +var TWEEN_CONST = __webpack_require__(89); +var TweenBuilder = __webpack_require__(143); /** * @classdesc @@ -188217,7 +185282,7 @@ module.exports = TweenManager; /***/ }), -/* 1365 */ +/* 1360 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188232,16 +185297,16 @@ module.exports = TweenManager; module.exports = { - Array: __webpack_require__(178), - Base64: __webpack_require__(1366), - Objects: __webpack_require__(1368), - String: __webpack_require__(1372) + Array: __webpack_require__(181), + Base64: __webpack_require__(1361), + Objects: __webpack_require__(1363), + String: __webpack_require__(1367) }; /***/ }), -/* 1366 */ +/* 1361 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188256,14 +185321,14 @@ module.exports = { module.exports = { - ArrayBufferToBase64: __webpack_require__(1367), - Base64ToArrayBuffer: __webpack_require__(381) + ArrayBufferToBase64: __webpack_require__(1362), + Base64ToArrayBuffer: __webpack_require__(380) }; /***/ }), -/* 1367 */ +/* 1362 */ /***/ (function(module, exports) { /** @@ -188321,7 +185386,7 @@ module.exports = ArrayBufferToBase64; /***/ }), -/* 1368 */ +/* 1363 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188336,26 +185401,26 @@ module.exports = ArrayBufferToBase64; module.exports = { - Clone: __webpack_require__(65), - Extend: __webpack_require__(18), + Clone: __webpack_require__(67), + Extend: __webpack_require__(17), GetAdvancedValue: __webpack_require__(15), GetFastValue: __webpack_require__(2), - GetMinMaxValue: __webpack_require__(1369), + GetMinMaxValue: __webpack_require__(1364), GetValue: __webpack_require__(6), - HasAll: __webpack_require__(1370), - HasAny: __webpack_require__(400), - HasValue: __webpack_require__(104), + HasAll: __webpack_require__(1365), + HasAny: __webpack_require__(399), + HasValue: __webpack_require__(99), IsPlainObject: __webpack_require__(7), - Merge: __webpack_require__(120), - MergeRight: __webpack_require__(1371), - Pick: __webpack_require__(481), - SetValue: __webpack_require__(420) + Merge: __webpack_require__(107), + MergeRight: __webpack_require__(1366), + Pick: __webpack_require__(480), + SetValue: __webpack_require__(419) }; /***/ }), -/* 1369 */ +/* 1364 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188365,7 +185430,7 @@ module.exports = { */ var GetValue = __webpack_require__(6); -var Clamp = __webpack_require__(23); +var Clamp = __webpack_require__(22); /** * Retrieves and clamps a numerical value from an object. @@ -188394,7 +185459,7 @@ module.exports = GetMinMaxValue; /***/ }), -/* 1370 */ +/* 1365 */ /***/ (function(module, exports) { /** @@ -188431,7 +185496,7 @@ module.exports = HasAll; /***/ }), -/* 1371 */ +/* 1366 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188440,7 +185505,7 @@ module.exports = HasAll; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Clone = __webpack_require__(65); +var Clone = __webpack_require__(67); /** * Creates a new Object using all values from obj1. @@ -188474,7 +185539,7 @@ module.exports = MergeRight; /***/ }), -/* 1372 */ +/* 1367 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188489,17 +185554,17 @@ module.exports = MergeRight; module.exports = { - Format: __webpack_require__(1373), - Pad: __webpack_require__(157), - Reverse: __webpack_require__(1374), - UppercaseFirst: __webpack_require__(176), - UUID: __webpack_require__(191) + Format: __webpack_require__(1368), + Pad: __webpack_require__(160), + Reverse: __webpack_require__(1369), + UppercaseFirst: __webpack_require__(179), + UUID: __webpack_require__(194) }; /***/ }), -/* 1373 */ +/* 1368 */ /***/ (function(module, exports) { /** @@ -188534,7 +185599,7 @@ module.exports = Format; /***/ }), -/* 1374 */ +/* 1369 */ /***/ (function(module, exports) { /** @@ -188563,7 +185628,7 @@ module.exports = Reverse; /***/ }), -/* 1375 */ +/* 1370 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -188579,29 +185644,2588 @@ module.exports = Reverse; module.exports = { - SoundManagerCreator: __webpack_require__(375), + SoundManagerCreator: __webpack_require__(374), Events: __webpack_require__(59), - BaseSound: __webpack_require__(122), - BaseSoundManager: __webpack_require__(121), + BaseSound: __webpack_require__(125), + BaseSoundManager: __webpack_require__(124), - WebAudioSound: __webpack_require__(382), - WebAudioSoundManager: __webpack_require__(380), + WebAudioSound: __webpack_require__(381), + WebAudioSoundManager: __webpack_require__(379), - HTML5AudioSound: __webpack_require__(377), - HTML5AudioSoundManager: __webpack_require__(376), + HTML5AudioSound: __webpack_require__(376), + HTML5AudioSoundManager: __webpack_require__(375), - NoAudioSound: __webpack_require__(379), - NoAudioSoundManager: __webpack_require__(378) + NoAudioSound: __webpack_require__(378), + NoAudioSoundManager: __webpack_require__(377) }; +/***/ }), +/* 1371 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var COLLIDES = __webpack_require__(465); +var GetVelocity = __webpack_require__(1390); +var TYPE = __webpack_require__(466); +var UpdateMotion = __webpack_require__(1391); + +/** + * @callback Phaser.Types.Physics.Impact.BodyUpdateCallback + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + */ + +/** + * @classdesc + * An Impact.js compatible physics body. + * This re-creates the properties you'd get on an Entity and the math needed to update them. + * + * @class Body + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} [sx=16] - [description] + * @param {number} [sy=16] - [description] + */ +var Body = new Class({ + + initialize: + + function Body (world, x, y, sx, sy) + { + if (sx === undefined) { sx = 16; } + if (sy === undefined) { sy = sx; } + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#gameObject + * @type {Phaser.GameObjects.GameObject} + * @default null + * @since 3.0.0 + */ + this.gameObject = null; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The ImpactBody, ImpactSprite or ImpactImage object that owns this Body, if any. + * + * @name Phaser.Physics.Impact.Body#parent + * @type {?(Phaser.Physics.Impact.ImpactBody|Phaser.Physics.Impact.ImpactImage|Phaser.Physics.Impact.ImpactSprite)} + * @since 3.0.0 + */ + this.parent; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#id + * @type {integer} + * @since 3.0.0 + */ + this.id = world.getNextID(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#size + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.size = { x: sx, y: sy }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#offset + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.offset = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#pos + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.pos = { x: x, y: y }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#last + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.last = { x: x, y: y }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#vel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.vel = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.accel = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#friction + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.friction = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#maxVel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.maxVel = { x: world.defaults.maxVelocityX, y: world.defaults.maxVelocityY }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#standing + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.standing = false; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#gravityFactor + * @type {number} + * @since 3.0.0 + */ + this.gravityFactor = world.defaults.gravityFactor; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#bounciness + * @type {number} + * @since 3.0.0 + */ + this.bounciness = world.defaults.bounciness; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#minBounceVelocity + * @type {number} + * @since 3.0.0 + */ + this.minBounceVelocity = world.defaults.minBounceVelocity; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accelGround + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelGround = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accelAir + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelAir = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#jumpSpeed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.jumpSpeed = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#type + * @type {Phaser.Physics.Impact.TYPE} + * @since 3.0.0 + */ + this.type = TYPE.NONE; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#checkAgainst + * @type {Phaser.Physics.Impact.TYPE} + * @since 3.0.0 + */ + this.checkAgainst = TYPE.NONE; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#collides + * @type {Phaser.Physics.Impact.COLLIDES} + * @since 3.0.0 + */ + this.collides = COLLIDES.NEVER; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowBody; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowVelocity = world.defaults.debugShowVelocity; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.bodyDebugColor; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#updateCallback + * @type {?Phaser.Types.Physics.Impact.BodyUpdateCallback} + * @since 3.0.0 + */ + this.updateCallback; + + /** + * min 44 deg, max 136 deg + * + * @name Phaser.Physics.Impact.Body#slopeStanding + * @type {{ min: number, max: number }} + * @since 3.0.0 + */ + this.slopeStanding = { min: 0.767944870877505, max: 2.3736477827122884 }; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#reset + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + */ + reset: function (x, y) + { + this.pos = { x: x, y: y }; + this.last = { x: x, y: y }; + this.vel = { x: 0, y: 0 }; + this.accel = { x: 0, y: 0 }; + this.friction = { x: 0, y: 0 }; + this.maxVel = { x: 100, y: 100 }; + + this.standing = false; + + this.gravityFactor = 1; + this.bounciness = 0; + this.minBounceVelocity = 40; + + this.accelGround = 0; + this.accelAir = 0; + this.jumpSpeed = 0; + + this.type = TYPE.NONE; + this.checkAgainst = TYPE.NONE; + this.collides = COLLIDES.NEVER; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#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. + */ + update: function (delta) + { + var pos = this.pos; + + this.last.x = pos.x; + this.last.y = pos.y; + + this.vel.y += this.world.gravity * delta * this.gravityFactor; + + this.vel.x = GetVelocity(delta, this.vel.x, this.accel.x, this.friction.x, this.maxVel.x); + this.vel.y = GetVelocity(delta, this.vel.y, this.accel.y, this.friction.y, this.maxVel.y); + + var mx = this.vel.x * delta; + var my = this.vel.y * delta; + + var res = this.world.collisionMap.trace(pos.x, pos.y, mx, my, this.size.x, this.size.y); + + if (this.handleMovementTrace(res)) + { + UpdateMotion(this, res); + } + + var go = this.gameObject; + + if (go) + { + go.x = (pos.x - this.offset.x) + go.displayOriginX * go.scaleX; + go.y = (pos.y - this.offset.y) + go.displayOriginY * go.scaleY; + } + + if (this.updateCallback) + { + this.updateCallback(this); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - [description] + */ + drawDebug: function (graphic) + { + var pos = this.pos; + + if (this.debugShowBody) + { + graphic.lineStyle(1, this.debugBodyColor, 1); + graphic.strokeRect(pos.x, pos.y, this.size.x, this.size.y); + } + + if (this.debugShowVelocity) + { + var x = pos.x + this.size.x / 2; + var y = pos.y + this.size.y / 2; + + graphic.lineStyle(1, this.world.defaults.velocityDebugColor, 1); + graphic.lineBetween(x, y, x + this.vel.x, y + this.vel.y); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} [description] + */ + willDrawDebug: function () + { + return (this.debugShowBody || this.debugShowVelocity); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#skipHash + * @since 3.0.0 + * + * @return {boolean} [description] + */ + skipHash: function () + { + return (!this.enabled || (this.type === 0 && this.checkAgainst === 0 && this.collides === 0)); + }, + + /** + * Determines whether the body collides with the `other` one or not. + * + * @method Phaser.Physics.Impact.Body#touches + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + * + * @return {boolean} [description] + */ + touches: function (other) + { + return !( + this.pos.x >= other.pos.x + other.size.x || + this.pos.x + this.size.x <= other.pos.x || + this.pos.y >= other.pos.y + other.size.y || + this.pos.y + this.size.y <= other.pos.y + ); + }, + + /** + * Reset the size and position of the physics body. + * + * @method Phaser.Physics.Impact.Body#resetSize + * @since 3.0.0 + * + * @param {number} x - The x coordinate to position the body. + * @param {number} y - The y coordinate to position the body. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * + * @return {Phaser.Physics.Impact.Body} This Body object. + */ + resetSize: function (x, y, width, height) + { + this.pos.x = x; + this.pos.y = y; + this.size.x = width; + this.size.y = height; + + return this; + }, + + /** + * Export this body object to JSON. + * + * @method Phaser.Physics.Impact.Body#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Physics.Impact.JSONImpactBody} JSON representation of this body object. + */ + toJSON: function () + { + var output = { + name: this.name, + size: { x: this.size.x, y: this.size.y }, + pos: { x: this.pos.x, y: this.pos.y }, + vel: { x: this.vel.x, y: this.vel.y }, + accel: { x: this.accel.x, y: this.accel.y }, + friction: { x: this.friction.x, y: this.friction.y }, + maxVel: { x: this.maxVel.x, y: this.maxVel.y }, + gravityFactor: this.gravityFactor, + bounciness: this.bounciness, + minBounceVelocity: this.minBounceVelocity, + type: this.type, + checkAgainst: this.checkAgainst, + collides: this.collides + }; + + return output; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#fromJSON + * @todo Code it! + * @since 3.0.0 + * + * @param {object} config - [description] + */ + fromJSON: function () + { + }, + + /** + * Can be overridden by user code + * + * @method Phaser.Physics.Impact.Body#check + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + */ + check: function () + { + }, + + /** + * Can be overridden by user code + * + * @method Phaser.Physics.Impact.Body#collideWith + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + * @param {string} axis - [description] + */ + collideWith: function (other, axis) + { + if (this.parent && this.parent._collideCallback) + { + this.parent._collideCallback.call(this.parent._callbackScope, this, other, axis); + } + }, + + /** + * Can be overridden by user code but must return a boolean. + * + * @method Phaser.Physics.Impact.Body#handleMovementTrace + * @since 3.0.0 + * + * @param {number} res - [description] + * + * @return {boolean} [description] + */ + handleMovementTrace: function () + { + return true; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.remove(this); + + this.enabled = false; + + this.world = null; + + this.gameObject = null; + + this.parent = null; + } + +}); + +module.exports = Body; + + +/***/ }), +/* 1372 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var DefaultDefs = __webpack_require__(1395); + +/** + * @classdesc + * [description] + * + * @class CollisionMap + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {integer} [tilesize=32] - [description] + * @param {array} [data] - [description] + */ +var CollisionMap = new Class({ + + initialize: + + function CollisionMap (tilesize, data) + { + if (tilesize === undefined) { tilesize = 32; } + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#tilesize + * @type {integer} + * @default 32 + * @since 3.0.0 + */ + this.tilesize = tilesize; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#data + * @type {array} + * @since 3.0.0 + */ + this.data = (Array.isArray(data)) ? data : []; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#width + * @type {number} + * @since 3.0.0 + */ + this.width = (Array.isArray(data)) ? data[0].length : 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#height + * @type {number} + * @since 3.0.0 + */ + this.height = (Array.isArray(data)) ? data.length : 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#lastSlope + * @type {integer} + * @default 55 + * @since 3.0.0 + */ + this.lastSlope = 55; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#tiledef + * @type {object} + * @since 3.0.0 + */ + this.tiledef = DefaultDefs; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#trace + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} objectWidth - [description] + * @param {number} objectHeight - [description] + * + * @return {boolean} [description] + */ + trace: function (x, y, vx, vy, objectWidth, objectHeight) + { + // Set up the trace-result + var res = { + collision: { x: false, y: false, slope: false }, + pos: { x: x + vx, y: y + vy }, + tile: { x: 0, y: 0 } + }; + + if (!this.data) + { + return res; + } + + var steps = Math.ceil(Math.max(Math.abs(vx), Math.abs(vy)) / this.tilesize); + + if (steps > 1) + { + var sx = vx / steps; + var sy = vy / steps; + + for (var i = 0; i < steps && (sx || sy); i++) + { + this.step(res, x, y, sx, sy, objectWidth, objectHeight, vx, vy, i); + + x = res.pos.x; + y = res.pos.y; + + if (res.collision.x) + { + sx = 0; + vx = 0; + } + + if (res.collision.y) + { + sy = 0; + vy = 0; + } + + if (res.collision.slope) + { + break; + } + } + } + else + { + this.step(res, x, y, vx, vy, objectWidth, objectHeight, vx, vy, 0); + } + + return res; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#step + * @since 3.0.0 + * + * @param {object} res - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} rvx - [description] + * @param {number} rvy - [description] + * @param {number} step - [description] + */ + step: function (res, x, y, vx, vy, width, height, rvx, rvy, step) + { + var t = 0; + var tileX; + var tileY; + var tilesize = this.tilesize; + var mapWidth = this.width; + var mapHeight = this.height; + + // Horizontal + if (vx) + { + var pxOffsetX = (vx > 0 ? width : 0); + var tileOffsetX = (vx < 0 ? tilesize : 0); + + var firstTileY = Math.max(Math.floor(y / tilesize), 0); + var lastTileY = Math.min(Math.ceil((y + height) / tilesize), mapHeight); + + tileX = Math.floor((res.pos.x + pxOffsetX) / tilesize); + + var prevTileX = Math.floor((x + pxOffsetX) / tilesize); + + if (step > 0 || tileX === prevTileX || prevTileX < 0 || prevTileX >= mapWidth) + { + prevTileX = -1; + } + + if (tileX >= 0 && tileX < mapWidth) + { + for (tileY = firstTileY; tileY < lastTileY; tileY++) + { + if (prevTileX !== -1) + { + t = this.data[tileY][prevTileX]; + + if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, prevTileX, tileY)) + { + break; + } + } + + t = this.data[tileY][tileX]; + + if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) + { + if (t > 1 && t <= this.lastSlope && res.collision.slope) + { + break; + } + + res.collision.x = true; + res.tile.x = t; + res.pos.x = (tileX * tilesize) - pxOffsetX + tileOffsetX; + x = res.pos.x; + rvx = 0; + + break; + } + } + } + } + + // Vertical + if (vy) + { + var pxOffsetY = (vy > 0 ? height : 0); + var tileOffsetY = (vy < 0 ? tilesize : 0); + + var firstTileX = Math.max(Math.floor(res.pos.x / tilesize), 0); + var lastTileX = Math.min(Math.ceil((res.pos.x + width) / tilesize), mapWidth); + + tileY = Math.floor((res.pos.y + pxOffsetY) / tilesize); + + var prevTileY = Math.floor((y + pxOffsetY) / tilesize); + + if (step > 0 || tileY === prevTileY || prevTileY < 0 || prevTileY >= mapHeight) + { + prevTileY = -1; + } + + if (tileY >= 0 && tileY < mapHeight) + { + for (tileX = firstTileX; tileX < lastTileX; tileX++) + { + if (prevTileY !== -1) + { + t = this.data[prevTileY][tileX]; + + if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, prevTileY)) + { + break; + } + } + + t = this.data[tileY][tileX]; + + if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) + { + if (t > 1 && t <= this.lastSlope && res.collision.slope) + { + break; + } + + res.collision.y = true; + res.tile.y = t; + res.pos.y = tileY * tilesize - pxOffsetY + tileOffsetY; + + break; + } + } + } + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#checkDef + * @since 3.0.0 + * + * @param {object} res - [description] + * @param {number} t - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} tileX - [description] + * @param {number} tileY - [description] + * + * @return {boolean} [description] + */ + checkDef: function (res, t, x, y, vx, vy, width, height, tileX, tileY) + { + var def = this.tiledef[t]; + + if (!def) + { + return false; + } + + var tilesize = this.tilesize; + + var lx = (tileX + def[0]) * tilesize; + var ly = (tileY + def[1]) * tilesize; + var lvx = (def[2] - def[0]) * tilesize; + var lvy = (def[3] - def[1]) * tilesize; + var solid = def[4]; + + var tx = x + vx + (lvy < 0 ? width : 0) - lx; + var ty = y + vy + (lvx > 0 ? height : 0) - ly; + + if (lvx * ty - lvy * tx > 0) + { + if (vx * -lvy + vy * lvx < 0) + { + return solid; + } + + var length = Math.sqrt(lvx * lvx + lvy * lvy); + var nx = lvy / length; + var ny = -lvx / length; + + var proj = tx * nx + ty * ny; + var px = nx * proj; + var py = ny * proj; + + if (px * px + py * py >= vx * vx + vy * vy) + { + return solid || (lvx * (ty - vy) - lvy * (tx - vx) < 0.5); + } + + res.pos.x = x + vx - px; + res.pos.y = y + vy - py; + res.collision.slope = { x: lvx, y: lvy, nx: nx, ny: ny }; + + return true; + } + + return false; + } + +}); + +module.exports = CollisionMap; + + +/***/ }), +/* 1373 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var ImpactBody = __webpack_require__(1374); +var ImpactImage = __webpack_require__(1375); +var ImpactSprite = __webpack_require__(1376); + +/** + * @classdesc + * The Impact Physics Factory allows you to easily create Impact Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + * + * @class Factory + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - A reference to the Impact Physics world. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * A reference to the Impact Physics world. + * + * @name Phaser.Physics.Impact.Factory#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * A reference to the Scene.Systems this Impact Physics instance belongs to. + * + * @name Phaser.Physics.Impact.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new ImpactBody object and adds it to the physics simulation. + * + * @method Phaser.Physics.Impact.Factory#body + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the body in the physics world. + * @param {number} y - The vertical position of the body in the physics world. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * + * @return {Phaser.Physics.Impact.ImpactBody} The ImpactBody object that was created. + */ + body: function (x, y, width, height) + { + return new ImpactBody(this.world, x, y, width, height); + }, + + /** + * Adds an Impact Physics Body to the given Game Object. + * + * @method Phaser.Physics.Impact.Factory#existing + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to receive the physics body. + * + * @return {Phaser.GameObjects.GameObject} The Game Object. + */ + existing: function (gameObject) + { + var x = gameObject.x - gameObject.frame.centerX; + var y = gameObject.y - gameObject.frame.centerY; + var w = gameObject.width; + var h = gameObject.height; + + gameObject.body = this.world.create(x, y, w, h); + + gameObject.body.parent = gameObject; + gameObject.body.gameObject = gameObject; + + return gameObject; + }, + + /** + * Creates a new ImpactImage object and adds it to the physics world. + * + * @method Phaser.Physics.Impact.Factory#image + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Impact.ImpactImage} The ImpactImage object that was created. + */ + image: function (x, y, key, frame) + { + var image = new ImpactImage(this.world, x, y, key, frame); + + this.sys.displayList.add(image); + + return image; + }, + + /** + * Creates a new ImpactSprite object and adds it to the physics world. + * + * @method Phaser.Physics.Impact.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Impact.ImpactSprite} The ImpactSprite object that was created. + */ + sprite: function (x, y, key, frame) + { + var sprite = new ImpactSprite(this.world, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + return sprite; + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Impact.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.sys = null; + } + +}); + +module.exports = Factory; + + +/***/ }), +/* 1374 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(1279); + +/** + * @classdesc + * [description] + * + * @class ImpactBody + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {number} x - x - The horizontal position of this physics body in the world. + * @param {number} y - y - The vertical position of this physics body in the world. + * @param {number} width - The width of the physics body in the world. + * @param {number} height - [description] + */ +var ImpactBody = new Class({ + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactBody (world, x, y, width, height) + { + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x, y, width, height); + + this.body.parent = this; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactBody; + + +/***/ }), +/* 1375 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(1279); +var Image = __webpack_require__(98); + +/** + * @classdesc + * An Impact Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class ImpactImage + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Impact.World} world - The physics world of the Impact physics system. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ImpactImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactImage (world, x, y, texture, frame) + { + Image.call(this, world.scene, x, y, texture, frame); + + /** + * The Physics Body linked to an ImpactImage. + * + * @name Phaser.Physics.Impact.ImpactImage#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); + + this.body.parent = this; + this.body.gameObject = this; + + /** + * The size of the physics Body. + * + * @name Phaser.Physics.Impact.ImpactImage#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * The X and Y offset of the Body from the left and top of the Image. + * + * @name Phaser.Physics.Impact.ImpactImage#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * The velocity, or rate of change the Body's position. Measured in pixels per second. + * + * @name Phaser.Physics.Impact.ImpactImage#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + * + * @name Phaser.Physics.Impact.ImpactImage#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * Friction between colliding bodies. + * + * @name Phaser.Physics.Impact.ImpactImage#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * The maximum velocity of the body. + * + * @name Phaser.Physics.Impact.ImpactImage#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactImage; + + /***/ }), /* 1376 */ /***/ (function(module, exports, __webpack_require__) { +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Components = __webpack_require__(1279); +var Sprite = __webpack_require__(69); + +/** + * @classdesc + * An Impact Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class ImpactSprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ImpactSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactSprite (world, x, y, texture, frame) + { + Sprite.call(this, world.scene, x, y, texture, frame); + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); + + this.body.parent = this; + this.body.gameObject = this; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactSprite; + + +/***/ }), +/* 1377 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = __webpack_require__(1371); +var Class = __webpack_require__(0); +var COLLIDES = __webpack_require__(465); +var CollisionMap = __webpack_require__(1372); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(1278); +var GetFastValue = __webpack_require__(2); +var HasValue = __webpack_require__(99); +var Set = __webpack_require__(108); +var Solver = __webpack_require__(1409); +var TILEMAP_FORMATS = __webpack_require__(31); +var TYPE = __webpack_require__(466); + +/** + * @classdesc + * [description] + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Impact World instance belongs. + * @param {Phaser.Types.Physics.Impact.WorldConfig} config - [description] + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#bodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.bodies = new Set(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#gravity + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.gravity = GetFastValue(config, 'gravity', 0); + + /** + * Spatial hash cell dimensions + * + * @name Phaser.Physics.Impact.World#cellSize + * @type {integer} + * @default 64 + * @since 3.0.0 + */ + this.cellSize = GetFastValue(config, 'cellSize', 64); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#collisionMap + * @type {Phaser.Physics.Impact.CollisionMap} + * @since 3.0.0 + */ + this.collisionMap = new CollisionMap(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = GetFastValue(config, 'timeScale', 1); + + /** + * Impacts maximum time step is 20 fps. + * + * @name Phaser.Physics.Impact.World#maxStep + * @type {number} + * @default 0.05 + * @since 3.0.0 + */ + this.maxStep = GetFastValue(config, 'maxStep', 0.05); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#drawDebug + * @type {boolean} + * @since 3.0.0 + */ + this.drawDebug = GetFastValue(config, 'debug', false); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + var _maxVelocity = GetFastValue(config, 'maxVelocity', 100); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#defaults + * @type {Phaser.Types.Physics.Impact.WorldDefaults} + * @since 3.0.0 + */ + this.defaults = { + debugShowBody: GetFastValue(config, 'debugShowBody', true), + debugShowVelocity: GetFastValue(config, 'debugShowVelocity', true), + bodyDebugColor: GetFastValue(config, 'debugBodyColor', 0xff00ff), + velocityDebugColor: GetFastValue(config, 'debugVelocityColor', 0x00ff00), + maxVelocityX: GetFastValue(config, 'maxVelocityX', _maxVelocity), + maxVelocityY: GetFastValue(config, 'maxVelocityY', _maxVelocity), + minBounceVelocity: GetFastValue(config, 'minBounceVelocity', 40), + gravityFactor: GetFastValue(config, 'gravityFactor', 1), + bounciness: GetFastValue(config, 'bounciness', 0) + }; + + /** + * An object containing the 4 wall bodies that bound the physics world. + * + * @name Phaser.Physics.Impact.World#walls + * @type {Phaser.Types.Physics.Impact.WorldWalls} + * @since 3.0.0 + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#delta + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.delta = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#_lastId + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._lastId = 0; + + if (GetFastValue(config, 'setBounds', false)) + { + var boundsConfig = config['setBounds']; + + if (typeof boundsConfig === 'boolean') + { + this.setBounds(); + } + else + { + var x = GetFastValue(boundsConfig, 'x', 0); + var y = GetFastValue(boundsConfig, 'y', 0); + var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); + var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); + var thickness = GetFastValue(boundsConfig, 'thickness', 64); + var left = GetFastValue(boundsConfig, 'left', true); + var right = GetFastValue(boundsConfig, 'right', true); + var top = GetFastValue(boundsConfig, 'top', true); + var bottom = GetFastValue(boundsConfig, 'bottom', true); + + this.setBounds(x, y, width, height, thickness, left, right, top, bottom); + } + } + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + }, + + /** + * Sets the collision map for the world either from a Weltmeister JSON level in the cache or from + * a 2D array. If loading from a Weltmeister level, the map must have a layer called "collision". + * + * @method Phaser.Physics.Impact.World#setCollisionMap + * @since 3.0.0 + * + * @param {(string|integer[][])} key - Either a string key that corresponds to a Weltmeister level + * in the cache, or a 2D array of collision IDs. + * @param {integer} tileSize - The size of a tile. This is optional if loading from a Weltmeister + * level in the cache. + * + * @return {?Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap, or null if the method failed to + * create the CollisionMap. + */ + setCollisionMap: function (key, tileSize) + { + if (typeof key === 'string') + { + var tilemapData = this.scene.cache.tilemap.get(key); + + if (!tilemapData || tilemapData.format !== TILEMAP_FORMATS.WELTMEISTER) + { + console.warn('The specified key does not correspond to a Weltmeister tilemap: ' + key); + return null; + } + + var layers = tilemapData.data.layer; + var collisionLayer; + for (var i = 0; i < layers.length; i++) + { + if (layers[i].name === 'collision') + { + collisionLayer = layers[i]; + break; + } + } + + if (tileSize === undefined) { tileSize = collisionLayer.tilesize; } + + this.collisionMap = new CollisionMap(tileSize, collisionLayer.data); + } + else if (Array.isArray(key)) + { + this.collisionMap = new CollisionMap(tileSize, key); + } + else + { + console.warn('Invalid Weltmeister collision map data: ' + key); + } + + return this.collisionMap; + }, + + /** + * Sets the collision map for the world from a tilemap layer. Only tiles that are marked as + * colliding will be used. You can specify the mapping from tiles to slope IDs in a couple of + * ways. The easiest is to use Tiled and the slopeTileProperty option. Alternatively, you can + * manually create a slopeMap that stores the mapping between tile indices and slope IDs. + * + * @method Phaser.Physics.Impact.World#setCollisionMapFromTilemapLayer + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemap layer to use. + * @param {Phaser.Types.Physics.Impact.CollisionOptions} [options] - Options for controlling the mapping from tiles to slope IDs. + * + * @return {Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap. + */ + setCollisionMapFromTilemapLayer: function (tilemapLayer, options) + { + if (options === undefined) { options = {}; } + var slopeProperty = GetFastValue(options, 'slopeProperty', null); + var slopeMap = GetFastValue(options, 'slopeMap', null); + var collidingSlope = GetFastValue(options, 'defaultCollidingSlope', null); + var nonCollidingSlope = GetFastValue(options, 'defaultNonCollidingSlope', 0); + + var layerData = tilemapLayer.layer; + var tileSize = layerData.baseTileWidth; + var collisionData = []; + + for (var ty = 0; ty < layerData.height; ty++) + { + collisionData[ty] = []; + + for (var tx = 0; tx < layerData.width; tx++) + { + var tile = layerData.data[ty][tx]; + + if (tile && tile.collides) + { + if (slopeProperty !== null && HasValue(tile.properties, slopeProperty)) + { + collisionData[ty][tx] = parseInt(tile.properties[slopeProperty], 10); + } + else if (slopeMap !== null && HasValue(slopeMap, tile.index)) + { + collisionData[ty][tx] = slopeMap[tile.index]; + } + else if (collidingSlope !== null) + { + collisionData[ty][tx] = collidingSlope; + } + else + { + collisionData[ty][tx] = tile.index; + } + } + else + { + collisionData[ty][tx] = nonCollidingSlope; + } + } + } + + this.collisionMap = new CollisionMap(tileSize, collisionData); + + return this.collisionMap; + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.Impact.World#setBounds + * @since 3.0.0 + * + * @param {number} [x] - The x coordinate of the top-left corner of the bounds. + * @param {number} [y] - The y coordinate of the top-left corner of the bounds. + * @param {number} [width] - The width of the bounds. + * @param {number} [height] - The height of the bounds. + * @param {number} [thickness=64] - [description] + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setBounds: function (x, y, width, height, thickness, left, right, top, bottom) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (thickness === undefined) { thickness = 64; } + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (bottom === undefined) { bottom = true; } + + this.updateWall(left, 'left', x - thickness, y, thickness, height); + this.updateWall(right, 'right', x + width, y, thickness, height); + this.updateWall(top, 'top', x, y - thickness, width, thickness); + this.updateWall(bottom, 'bottom', x, y + height, width, thickness); + + return this; + }, + + /** + * position = 'left', 'right', 'top' or 'bottom' + * + * @method Phaser.Physics.Impact.World#updateWall + * @since 3.0.0 + * + * @param {boolean} add - [description] + * @param {string} position - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} width - [description] + * @param {number} height - [description] + */ + updateWall: function (add, position, x, y, width, height) + { + var wall = this.walls[position]; + + if (add) + { + if (wall) + { + wall.resetSize(x, y, width, height); + } + else + { + this.walls[position] = this.create(x, y, width, height); + this.walls[position].name = position; + this.walls[position].gravityFactor = 0; + this.walls[position].collides = COLLIDES.FIXED; + } + } + else + { + if (wall) + { + this.bodies.remove(wall); + } + + this.walls[position] = null; + } + }, + + /** + * Creates a Graphics Game Object used for debug display and enables the world for debug drawing. + * + * @method Phaser.Physics.Impact.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The Graphics object created that will have the debug visuals drawn to it. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#getNextID + * @since 3.0.0 + * + * @return {integer} [description] + */ + getNextID: function () + { + return this._lastId++; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#create + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} sizeX - [description] + * @param {number} sizeY - [description] + * + * @return {Phaser.Physics.Impact.Body} The Body that was added to this World. + */ + create: function (x, y, sizeX, sizeY) + { + var body = new Body(this, x, y, sizeX, sizeY); + + this.bodies.set(body); + + return body; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#remove + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} object - The Body to remove from this World. + */ + remove: function (object) + { + this.bodies.delete(object); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#pause + * @fires Phaser.Physics.Impact.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + pause: function () + { + this.enabled = false; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#resume + * @fires Phaser.Physics.Impact.Events#RESUME + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + resume: function () + { + this.enabled = true; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.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. + */ + update: function (time, delta) + { + if (!this.enabled || this.bodies.size === 0) + { + return; + } + + // Impact uses a divided delta value that is clamped to the maxStep (20fps) maximum + + var clampedDelta = Math.min(delta / 1000, this.maxStep) * this.timeScale; + + this.delta = clampedDelta; + + // Update all active bodies + + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + var hash = {}; + var size = this.cellSize; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enabled) + { + body.update(clampedDelta); + } + } + + // Run collision against them all now they're in the new positions from the update + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body && !body.skipHash()) + { + this.checkHash(body, hash, size); + } + } + + if (this.drawDebug) + { + var graphics = this.debugGraphic; + + graphics.clear(); + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body && body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + } + }, + + /** + * Check the body against the spatial hash. + * + * @method Phaser.Physics.Impact.World#checkHash + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {object} hash - [description] + * @param {number} size - [description] + */ + checkHash: function (body, hash, size) + { + var checked = {}; + + var xmin = Math.floor(body.pos.x / size); + var ymin = Math.floor(body.pos.y / size); + var xmax = Math.floor((body.pos.x + body.size.x) / size) + 1; + var ymax = Math.floor((body.pos.y + body.size.y) / size) + 1; + + for (var x = xmin; x < xmax; x++) + { + for (var y = ymin; y < ymax; y++) + { + if (!hash[x]) + { + hash[x] = {}; + hash[x][y] = [ body ]; + } + else if (!hash[x][y]) + { + hash[x][y] = [ body ]; + } + else + { + var cell = hash[x][y]; + + for (var c = 0; c < cell.length; c++) + { + if (body.touches(cell[c]) && !checked[cell[c].id]) + { + checked[cell[c].id] = true; + + this.checkBodies(body, cell[c]); + } + } + + cell.push(body); + } + } + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#checkBodies + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} bodyA - [description] + * @param {Phaser.Physics.Impact.Body} bodyB - [description] + */ + checkBodies: function (bodyA, bodyB) + { + // 2 fixed bodies won't do anything + if (bodyA.collides === COLLIDES.FIXED && bodyB.collides === COLLIDES.FIXED) + { + return; + } + + // bitwise checks + if (bodyA.checkAgainst & bodyB.type) + { + bodyA.check(bodyB); + } + + if (bodyB.checkAgainst & bodyA.type) + { + bodyB.check(bodyA); + } + + if (bodyA.collides && bodyB.collides && bodyA.collides + bodyB.collides > COLLIDES.ACTIVE) + { + Solver(this, bodyA, bodyB); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCollidesNever + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCollidesNever: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.NEVER; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setLite + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setLite: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.LITE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setPassive + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setPassive: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.PASSIVE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setActive + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setActive: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.ACTIVE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setFixed + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setFixed: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.FIXED; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeNone + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeNone: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.NONE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setAvsB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setAvsB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.A; + bodies[i].checkAgainst = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setBvsA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setBvsA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.B; + bodies[i].checkAgainst = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstNone + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstNone: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.NONE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAllListeners(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.scene = null; + + this.bodies.clear(); + + this.bodies = null; + + this.collisionMap = null; + } + +}); + +module.exports = World; + + +/***/ }), +/* 1378 */ +/***/ (function(module, exports, __webpack_require__) { + /** * @author Richard Davey * @copyright 2020 Photon Storm Ltd. @@ -189005,7 +188629,7 @@ module.exports = BodyBounds; /***/ }), -/* 1377 */ +/* 1379 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -189014,19 +188638,19 @@ module.exports = BodyBounds; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); var Class = __webpack_require__(0); -var Composites = __webpack_require__(1282); -var Constraint = __webpack_require__(214); -var Svg = __webpack_require__(1283); -var MatterGameObject = __webpack_require__(1388); -var MatterImage = __webpack_require__(1379); -var MatterSprite = __webpack_require__(1380); -var MatterTileBody = __webpack_require__(1287); -var PhysicsEditorParser = __webpack_require__(1284); -var PhysicsJSONParser = __webpack_require__(1285); -var PointerConstraint = __webpack_require__(1417); -var Vertices = __webpack_require__(84); +var Composites = __webpack_require__(1280); +var Constraint = __webpack_require__(216); +var Svg = __webpack_require__(1281); +var MatterGameObject = __webpack_require__(1413); +var MatterImage = __webpack_require__(1381); +var MatterSprite = __webpack_require__(1382); +var MatterTileBody = __webpack_require__(1285); +var PhysicsEditorParser = __webpack_require__(1282); +var PhysicsJSONParser = __webpack_require__(1283); +var PointerConstraint = __webpack_require__(1442); +var Vertices = __webpack_require__(86); /** * @classdesc @@ -189935,7 +189559,7 @@ module.exports = Factory; /***/ }), -/* 1378 */ +/* 1380 */ /***/ (function(module, exports) { /** @@ -190605,7 +190229,7 @@ function points_eq(a,b,precision){ /***/ }), -/* 1379 */ +/* 1381 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -190615,11 +190239,11 @@ function points_eq(a,b,precision){ */ var Class = __webpack_require__(0); -var Components = __webpack_require__(509); +var Components = __webpack_require__(508); var GameObject = __webpack_require__(14); var GetFastValue = __webpack_require__(2); -var Image = __webpack_require__(103); -var Pipeline = __webpack_require__(150); +var Image = __webpack_require__(98); +var Pipeline = __webpack_require__(153); var Vector2 = __webpack_require__(3); /** @@ -190741,7 +190365,7 @@ module.exports = MatterImage; /***/ }), -/* 1380 */ +/* 1382 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -190750,13 +190374,13 @@ module.exports = MatterImage; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var AnimationComponent = __webpack_require__(499); +var AnimationComponent = __webpack_require__(498); var Class = __webpack_require__(0); -var Components = __webpack_require__(509); +var Components = __webpack_require__(508); var GameObject = __webpack_require__(14); var GetFastValue = __webpack_require__(2); -var Pipeline = __webpack_require__(150); -var Sprite = __webpack_require__(73); +var Pipeline = __webpack_require__(153); +var Sprite = __webpack_require__(69); var Vector2 = __webpack_require__(3); /** @@ -190883,7 +190507,7 @@ module.exports = MatterSprite; /***/ }), -/* 1381 */ +/* 1383 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -190896,7 +190520,7 @@ var Matter = {}; module.exports = Matter; -var Plugin = __webpack_require__(1289); +var Plugin = __webpack_require__(1287); var Common = __webpack_require__(37); (function() { @@ -190975,7 +190599,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 1382 */ +/* 1384 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -190990,11 +190614,11 @@ var Query = {}; module.exports = Query; -var Vector = __webpack_require__(97); -var SAT = __webpack_require__(511); -var Bounds = __webpack_require__(98); -var Bodies = __webpack_require__(105); -var Vertices = __webpack_require__(84); +var Vector = __webpack_require__(101); +var SAT = __webpack_require__(510); +var Bounds = __webpack_require__(102); +var Bodies = __webpack_require__(109); +var Vertices = __webpack_require__(86); (function() { @@ -191117,7 +190741,7 @@ var Vertices = __webpack_require__(84); /***/ }), -/* 1383 */ +/* 1385 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -191134,15 +190758,15 @@ var Engine = {}; module.exports = Engine; -var World = __webpack_require__(1290); -var Sleeping = __webpack_require__(234); -var Resolver = __webpack_require__(1293); -var Pairs = __webpack_require__(1292); -var Metrics = __webpack_require__(1418); -var Grid = __webpack_require__(1291); -var Events = __webpack_require__(235); -var Composite = __webpack_require__(142); -var Constraint = __webpack_require__(214); +var World = __webpack_require__(1288); +var Sleeping = __webpack_require__(236); +var Resolver = __webpack_require__(1291); +var Pairs = __webpack_require__(1290); +var Metrics = __webpack_require__(1443); +var Grid = __webpack_require__(1289); +var Events = __webpack_require__(237); +var Composite = __webpack_require__(145); +var Constraint = __webpack_require__(216); var Common = __webpack_require__(37); var Body = __webpack_require__(62); @@ -191610,7 +191234,7 @@ var Body = __webpack_require__(62); /***/ }), -/* 1384 */ +/* 1386 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -191619,21 +191243,21 @@ var Body = __webpack_require__(62); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); var Body = __webpack_require__(62); var Class = __webpack_require__(0); var Common = __webpack_require__(37); -var Composite = __webpack_require__(142); -var Engine = __webpack_require__(1383); -var EventEmitter = __webpack_require__(11); -var Events = __webpack_require__(1286); +var Composite = __webpack_require__(145); +var Engine = __webpack_require__(1385); +var EventEmitter = __webpack_require__(9); +var Events = __webpack_require__(1284); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); var MatterBody = __webpack_require__(62); -var MatterEvents = __webpack_require__(235); -var MatterTileBody = __webpack_require__(1287); -var MatterWorld = __webpack_require__(1290); -var Vector = __webpack_require__(97); +var MatterEvents = __webpack_require__(237); +var MatterTileBody = __webpack_require__(1285); +var MatterWorld = __webpack_require__(1288); +var Vector = __webpack_require__(101); /** * @classdesc @@ -193831,7 +193455,7 @@ module.exports = World; /***/ }), -/* 1385 */ +/* 1387 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** @@ -193840,10 +193464,10 @@ module.exports = World; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -__webpack_require__(513); +__webpack_require__(512); -var CONST = __webpack_require__(10); -var Extend = __webpack_require__(18); +var CONST = __webpack_require__(29); +var Extend = __webpack_require__(17); /** * @namespace Phaser @@ -193851,38 +193475,38 @@ var Extend = __webpack_require__(18); var Phaser = { - Actions: __webpack_require__(236), - Animations: __webpack_require__(633), + Actions: __webpack_require__(238), + Animations: __webpack_require__(632), BlendModes: __webpack_require__(52), - Cache: __webpack_require__(634), - Cameras: __webpack_require__(637), - Core: __webpack_require__(720), + Cache: __webpack_require__(633), + Cameras: __webpack_require__(636), + Core: __webpack_require__(719), Class: __webpack_require__(0), - Create: __webpack_require__(779), - Curves: __webpack_require__(785), - Data: __webpack_require__(788), - Display: __webpack_require__(790), - DOM: __webpack_require__(807), - Events: __webpack_require__(808), - Game: __webpack_require__(810), - GameObjects: __webpack_require__(903), - Geom: __webpack_require__(423), - Input: __webpack_require__(1191), - Loader: __webpack_require__(1225), - Math: __webpack_require__(165), - Physics: __webpack_require__(1386), - Plugins: __webpack_require__(1294), - Renderer: __webpack_require__(1423), - Scale: __webpack_require__(1296), - ScaleModes: __webpack_require__(229), - Scene: __webpack_require__(369), - Scenes: __webpack_require__(1297), - Structs: __webpack_require__(1299), - Textures: __webpack_require__(1300), - Tilemaps: __webpack_require__(1302), - Time: __webpack_require__(1346), - Tweens: __webpack_require__(1348), - Utils: __webpack_require__(1365) + Create: __webpack_require__(781), + Curves: __webpack_require__(787), + Data: __webpack_require__(790), + Display: __webpack_require__(792), + DOM: __webpack_require__(809), + Events: __webpack_require__(810), + Game: __webpack_require__(812), + GameObjects: __webpack_require__(905), + Geom: __webpack_require__(422), + Input: __webpack_require__(1187), + Loader: __webpack_require__(1221), + Math: __webpack_require__(168), + Physics: __webpack_require__(1388), + Plugins: __webpack_require__(1292), + Renderer: __webpack_require__(1448), + Scale: __webpack_require__(1294), + ScaleModes: __webpack_require__(231), + Scene: __webpack_require__(368), + Scenes: __webpack_require__(1295), + Structs: __webpack_require__(1297), + Textures: __webpack_require__(1298), + Tilemaps: __webpack_require__(1300), + Time: __webpack_require__(1341), + Tweens: __webpack_require__(1343), + Utils: __webpack_require__(1360) }; @@ -193890,7 +193514,7 @@ var Phaser = { if (true) { - Phaser.Sound = __webpack_require__(1375); + Phaser.Sound = __webpack_require__(1370); } if (false) @@ -193922,10 +193546,10 @@ global.Phaser = Phaser; * -- Dick Brandon */ -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(512))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(511))) /***/ }), -/* 1386 */ +/* 1388 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -193944,14 +193568,1869 @@ global.Phaser = Phaser; module.exports = { - Arcade: __webpack_require__(1251), - Matter: __webpack_require__(1387) + Arcade: __webpack_require__(1247), + Impact: __webpack_require__(1389), + Matter: __webpack_require__(1412) }; /***/ }), -/* 1387 */ +/* 1389 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * An Impact.js compatible physics world, body and solver, for those who are used + * to the Impact way of defining and controlling physics bodies. Also works with + * the new Loader support for Weltmeister map data. + * + * World updated to run off the Phaser main loop. + * Body extended to support additional setter functions. + * + * To create the map data you'll need Weltmeister, which comes with Impact + * and can be purchased from http://impactjs.com + * + * My thanks to Dominic Szablewski for his permission to support Impact in Phaser. + * + * @namespace Phaser.Physics.Impact + */ +module.exports = { + + Body: __webpack_require__(1371), + Events: __webpack_require__(1278), + COLLIDES: __webpack_require__(465), + CollisionMap: __webpack_require__(1372), + Factory: __webpack_require__(1373), + Image: __webpack_require__(1375), + ImpactBody: __webpack_require__(1374), + ImpactPhysics: __webpack_require__(1408), + Sprite: __webpack_require__(1376), + TYPE: __webpack_require__(466), + World: __webpack_require__(1377) + +}; + + +/***/ }), +/* 1390 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = __webpack_require__(22); + +/** + * [description] + * + * @function Phaser.Physics.Impact.GetVelocity + * @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. + * @param {number} vel - [description] + * @param {number} accel - [description] + * @param {number} friction - [description] + * @param {number} max - [description] + * + * @return {number} [description] + */ +var GetVelocity = function (delta, vel, accel, friction, max) +{ + if (accel) + { + return Clamp(vel + accel * delta, -max, max); + } + else if (friction) + { + var frictionDelta = friction * delta; + + if (vel - frictionDelta > 0) + { + return vel - frictionDelta; + } + else if (vel + frictionDelta < 0) + { + return vel + frictionDelta; + } + else + { + return 0; + } + } + + return Clamp(vel, -max, max); +}; + +module.exports = GetVelocity; + + +/***/ }), +/* 1391 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Set up the trace-result + * var res = { + * collision: {x: false, y: false, slope: false}, + * pos: {x: x, y: y}, + * tile: {x: 0, y: 0} + * }; + * + * @function Phaser.Physics.Impact.UpdateMotion + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {object} res - [description] + */ +var UpdateMotion = function (body, res) +{ + body.standing = false; + + // Y + if (res.collision.y) + { + if (body.bounciness > 0 && Math.abs(body.vel.y) > body.minBounceVelocity) + { + body.vel.y *= -body.bounciness; + } + else + { + if (body.vel.y > 0) + { + body.standing = true; + } + + body.vel.y = 0; + } + } + + // X + if (res.collision.x) + { + if (body.bounciness > 0 && Math.abs(body.vel.x) > body.minBounceVelocity) + { + body.vel.x *= -body.bounciness; + } + else + { + body.vel.x = 0; + } + } + + // SLOPE + if (res.collision.slope) + { + var s = res.collision.slope; + + if (body.bounciness > 0) + { + var proj = body.vel.x * s.nx + body.vel.y * s.ny; + + body.vel.x = (body.vel.x - s.nx * proj * 2) * body.bounciness; + body.vel.y = (body.vel.y - s.ny * proj * 2) * body.bounciness; + } + else + { + var lengthSquared = s.x * s.x + s.y * s.y; + var dot = (body.vel.x * s.x + body.vel.y * s.y) / lengthSquared; + + body.vel.x = s.x * dot; + body.vel.y = s.y * dot; + + var angle = Math.atan2(s.x, s.y); + + if (angle > body.slopeStanding.min && angle < body.slopeStanding.max) + { + body.standing = true; + } + } + } + + body.pos.x = res.pos.x; + body.pos.y = res.pos.y; +}; + +module.exports = UpdateMotion; + + +/***/ }), +/* 1392 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Collide Event. + * + * This event is dispatched by an Impact Physics World instance if two bodies collide. + * + * Listen to it from a Scene using: `this.impact.world.on('collide', listener)`. + * + * @event Phaser.Physics.Impact.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} bodyA - The first body involved in the collision. + * @param {Phaser.Physics.Impact.Body} bodyB - The second body involved in the collision. + * @param {string} axis - The collision axis. Either `x` or `y`. + */ +module.exports = 'collide'; + + +/***/ }), +/* 1393 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Pause Event. + * + * This event is dispatched by an Impact Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.impact.world.on('pause', listener)`. + * + * @event Phaser.Physics.Impact.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; + + +/***/ }), +/* 1394 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Resume Event. + * + * This event is dispatched by an Impact Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.impact.world.on('resume', listener)`. + * + * @event Phaser.Physics.Impact.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; + + +/***/ }), +/* 1395 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var H = 0.5; +var N = 1 / 3; +var M = 2 / 3; + +// Tile ID to Slope defs. +// First 4 elements = line data, final = solid or non-solid behind the line + +module.exports = { + + 2: [ 0, 1, 1, 0, true ], + 3: [ 0, 1, 1, H, true ], + 4: [ 0, H, 1, 0, true ], + 5: [ 0, 1, 1, M, true ], + 6: [ 0, M, 1, N, true ], + 7: [ 0, N, 1, 0, true ], + 8: [ H, 1, 0, 0, true ], + 9: [ 1, 0, H, 1, true ], + 10: [ H, 1, 1, 0, true ], + 11: [ 0, 0, H, 1, true ], + 12: [ 0, 0, 1, 0, false ], + 13: [ 1, 1, 0, 0, true ], + 14: [ 1, H, 0, 0, true ], + 15: [ 1, 1, 0, H, true ], + 16: [ 1, N, 0, 0, true ], + 17: [ 1, M, 0, N, true ], + 18: [ 1, 1, 0, M, true ], + 19: [ 1, 1, H, 0, true ], + 20: [ H, 0, 0, 1, true ], + 21: [ 0, 1, H, 0, true ], + 22: [ H, 0, 1, 1, true ], + 23: [ 1, 1, 0, 1, false ], + 24: [ 0, 0, 1, 1, true ], + 25: [ 0, 0, 1, H, true ], + 26: [ 0, H, 1, 1, true ], + 27: [ 0, 0, 1, N, true ], + 28: [ 0, N, 1, M, true ], + 29: [ 0, M, 1, 1, true ], + 30: [ N, 1, 0, 0, true ], + 31: [ 1, 0, M, 1, true ], + 32: [ M, 1, 1, 0, true ], + 33: [ 0, 0, N, 1, true ], + 34: [ 1, 0, 1, 1, false ], + 35: [ 1, 0, 0, 1, true ], + 36: [ 1, H, 0, 1, true ], + 37: [ 1, 0, 0, H, true ], + 38: [ 1, M, 0, 1, true ], + 39: [ 1, N, 0, M, true ], + 40: [ 1, 0, 0, N, true ], + 41: [ M, 1, N, 0, true ], + 42: [ M, 0, N, 1, true ], + 43: [ N, 1, M, 0, true ], + 44: [ N, 0, M, 1, true ], + 45: [ 0, 1, 0, 0, false ], + 52: [ 1, 1, M, 0, true ], + 53: [ N, 0, 0, 1, true ], + 54: [ 0, 1, N, 0, true ], + 55: [ M, 0, 1, 1, true ] + +}; + + +/***/ }), +/* 1396 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Acceleration component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Acceleration + * @since 3.0.0 + */ +var Acceleration = { + + /** + * Sets the horizontal acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationX + * @since 3.0.0 + * + * @param {number} x - The amount of acceleration to apply. + * + * @return {this} This Game Object. + */ + setAccelerationX: function (x) + { + this.accel.x = x; + + return this; + }, + + /** + * Sets the vertical acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationY + * @since 3.0.0 + * + * @param {number} y - The amount of acceleration to apply. + * + * @return {this} This Game Object. + */ + setAccelerationY: function (y) + { + this.accel.y = y; + + return this; + }, + + /** + * Sets the horizontal and vertical acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal acceleration to apply. + * @param {number} y - The amount of vertical acceleration to apply. + * + * @return {this} This Game Object. + */ + setAcceleration: function (x, y) + { + this.accel.x = x; + this.accel.y = y; + + return this; + } + +}; + +module.exports = Acceleration; + + +/***/ }), +/* 1397 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Body Scale component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.BodyScale + * @since 3.0.0 + */ +var BodyScale = { + + /** + * Sets the size of the physics body. + * + * @method Phaser.Physics.Impact.Components.BodyScale#setBodySize + * @since 3.0.0 + * + * @param {number} width - The width of the body in pixels. + * @param {number} [height=width] - The height of the body in pixels. + * + * @return {this} This Game Object. + */ + setBodySize: function (width, height) + { + if (height === undefined) { height = width; } + + this.body.size.x = Math.round(width); + this.body.size.y = Math.round(height); + + return this; + }, + + /** + * Sets the scale of the physics body. + * + * @method Phaser.Physics.Impact.Components.BodyScale#setBodyScale + * @since 3.0.0 + * + * @param {number} scaleX - The horizontal scale of the body. + * @param {number} [scaleY] - The vertical scale of the body. If not given, will use the horizontal scale value. + * + * @return {this} This Game Object. + */ + setBodyScale: function (scaleX, scaleY) + { + if (scaleY === undefined) { scaleY = scaleX; } + + var gameObject = this.body.gameObject; + + if (gameObject) + { + gameObject.setScale(scaleX, scaleY); + + return this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); + } + else + { + return this.setBodySize(this.body.size.x * scaleX, this.body.size.y * scaleY); + } + } + +}; + +module.exports = BodyScale; + + +/***/ }), +/* 1398 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TYPE = __webpack_require__(466); + +/** + * The Impact Body Type component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.BodyType + * @since 3.0.0 + */ +var BodyType = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#getBodyType + * @since 3.0.0 + * + * @return {number} [description] + */ + getBodyType: function () + { + return this.body.type; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeNone + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeNone: function () + { + this.body.type = TYPE.NONE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeA: function () + { + this.body.type = TYPE.A; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeB: function () + { + this.body.type = TYPE.B; + + return this; + } + +}; + +module.exports = BodyType; + + +/***/ }), +/* 1399 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Bounce component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the impact physics bounce, or restitution, value. + * + * @method Phaser.Physics.Impact.Components.Bounce#setBounce + * @since 3.0.0 + * + * @param {number} value - A value between 0 (no rebound) and 1 (full rebound) + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setBounce: function (value) + { + this.body.bounciness = value; + + return this; + }, + + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * + * @method Phaser.Physics.Impact.Components.Bounce#setMinBounceVelocity + * @since 3.0.0 + * + * @param {number} value - The minimum allowed velocity. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setMinBounceVelocity: function (value) + { + this.body.minBounceVelocity = value; + + return this; + }, + + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + * + * @name Phaser.Physics.Impact.Components.Bounce#bounce + * @type {number} + * @since 3.0.0 + */ + bounce: { + + get: function () + { + return this.body.bounciness; + }, + + set: function (value) + { + this.body.bounciness = value; + } + + } + +}; + +module.exports = Bounce; + + +/***/ }), +/* 1400 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TYPE = __webpack_require__(466); + +/** + * The Impact Check Against component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.CheckAgainst + * @since 3.0.0 + */ +var CheckAgainst = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setAvsB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setAvsB: function () + { + this.setTypeA(); + + return this.setCheckAgainstB(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setBvsA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setBvsA: function () + { + this.setTypeB(); + + return this.setCheckAgainstA(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstNone + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstNone: function () + { + this.body.checkAgainst = TYPE.NONE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstA: function () + { + this.body.checkAgainst = TYPE.A; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstB: function () + { + this.body.checkAgainst = TYPE.B; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.CheckAgainst#checkAgainst + * @type {number} + * @since 3.0.0 + */ + checkAgainst: { + + get: function () + { + return this.body.checkAgainst; + }, + + set: function (value) + { + this.body.checkAgainst = value; + } + + } + +}; + +module.exports = CheckAgainst; + + +/***/ }), +/* 1401 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var COLLIDES = __webpack_require__(465); + +/** + * @callback CollideCallback + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {Phaser.Physics.Impact.Body} other - [description] + * @param {string} axis - [description] + */ + +/** + * The Impact Collides component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Collides + * @since 3.0.0 + */ +var Collides = { + + _collideCallback: null, + _callbackScope: null, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setCollideCallback + * @since 3.0.0 + * + * @param {CollideCallback} callback - [description] + * @param {*} scope - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollideCallback: function (callback, scope) + { + this._collideCallback = callback; + + if (scope) + { + this._callbackScope = scope; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setCollidesNever + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollidesNever: function () + { + this.body.collides = COLLIDES.NEVER; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setLiteCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setLiteCollision: function () + { + this.body.collides = COLLIDES.LITE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setPassiveCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setPassiveCollision: function () + { + this.body.collides = COLLIDES.PASSIVE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setActiveCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setActiveCollision: function () + { + this.body.collides = COLLIDES.ACTIVE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setFixedCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFixedCollision: function () + { + this.body.collides = COLLIDES.FIXED; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Collides#collides + * @type {number} + * @since 3.0.0 + */ + collides: { + + get: function () + { + return this.body.collides; + }, + + set: function (value) + { + this.body.collides = value; + } + + } + +}; + +module.exports = Collides; + + +/***/ }), +/* 1402 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Debug component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Debug + * @since 3.0.0 + */ +var Debug = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Debug#setDebug + * @since 3.0.0 + * + * @param {boolean} showBody - [description] + * @param {boolean} showVelocity - [description] + * @param {number} bodyColor - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDebug: function (showBody, showVelocity, bodyColor) + { + this.debugShowBody = showBody; + this.debugShowVelocity = showVelocity; + this.debugBodyColor = bodyColor; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Debug#setDebugBodyColor + * @since 3.0.0 + * + * @param {number} value - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDebugBodyColor: function (value) + { + this.body.debugBodyColor = value; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + debugShowBody: { + + get: function () + { + return this.body.debugShowBody; + }, + + set: function (value) + { + this.body.debugShowBody = value; + } + + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + debugShowVelocity: { + + get: function () + { + return this.body.debugShowVelocity; + }, + + set: function (value) + { + this.body.debugShowVelocity = value; + } + + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugBodyColor + * @type {number} + * @since 3.0.0 + */ + debugBodyColor: { + + get: function () + { + return this.body.debugBodyColor; + }, + + set: function (value) + { + this.body.debugBodyColor = value; + } + + } + +}; + +module.exports = Debug; + + +/***/ }), +/* 1403 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Friction component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFrictionX + * @since 3.0.0 + * + * @param {number} x - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionX: function (x) + { + this.friction.x = x; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFrictionY + * @since 3.0.0 + * + * @param {number} y - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionY: function (y) + { + this.friction.y = y; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFriction: function (x, y) + { + this.friction.x = x; + this.friction.y = y; + + return this; + } + +}; + +module.exports = Friction; + + +/***/ }), +/* 1404 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Gravity component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Gravity#setGravity + * @since 3.0.0 + * + * @param {number} value - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setGravity: function (value) + { + this.body.gravityFactor = value; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Gravity#gravity + * @type {number} + * @since 3.0.0 + */ + gravity: { + + get: function () + { + return this.body.gravityFactor; + }, + + set: function (value) + { + this.body.gravityFactor = value; + } + + } + +}; + +module.exports = Gravity; + + +/***/ }), +/* 1405 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Offset component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Offset + * @since 3.0.0 + */ +var Offset = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Offset#setOffset + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} [width] - [description] + * @param {number} [height] - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOffset: function (x, y, width, height) + { + this.body.offset.x = x; + this.body.offset.y = y; + + if (width) + { + this.setBodySize(width, height); + } + + return this; + } + +}; + +module.exports = Offset; + + +/***/ }), +/* 1406 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Set Game Object component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.SetGameObject + * @since 3.0.0 + */ +var SetGameObject = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.SetGameObject#setGameObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - [description] + * @param {boolean} [sync=true] - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setGameObject: function (gameObject, sync) + { + if (sync === undefined) { sync = true; } + + if (gameObject) + { + this.body.gameObject = gameObject; + + if (sync) + { + this.syncGameObject(); + } + } + else + { + this.body.gameObject = null; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.SetGameObject#syncGameObject + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + syncGameObject: function () + { + var gameObject = this.body.gameObject; + + if (gameObject) + { + this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); + } + + return this; + } + +}; + +module.exports = SetGameObject; + + +/***/ }), +/* 1407 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Velocity component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the horizontal velocity of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * + * @return {this} This Game Object. + */ + setVelocityX: function (x) + { + this.vel.x = x; + + return this; + }, + + /** + * Sets the vertical velocity of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The vertical velocity value. + * + * @return {this} This Game Object. + */ + setVelocityY: function (y) + { + this.vel.y = y; + + return this; + }, + + /** + * Sets the horizontal and vertical velocities of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * @param {number} [y=x] - The vertical velocity value. If not given, defaults to the horizontal value. + * + * @return {this} This Game Object. + */ + setVelocity: function (x, y) + { + if (y === undefined) { y = x; } + + this.vel.x = x; + this.vel.y = y; + + return this; + }, + + /** + * Sets the maximum velocity this body can travel at. + * + * @method Phaser.Physics.Impact.Components.Velocity#setMaxVelocity + * @since 3.0.0 + * + * @param {number} x - The maximum allowed horizontal velocity. + * @param {number} [y=x] - The maximum allowed vertical velocity. If not given, defaults to the horizontal value. + * + * @return {this} This Game Object. + */ + setMaxVelocity: function (x, y) + { + if (y === undefined) { y = x; } + + this.maxVel.x = x; + this.maxVel.y = y; + + return this; + } + +}; + +module.exports = Velocity; + + +/***/ }), +/* 1408 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = __webpack_require__(0); +var Factory = __webpack_require__(1373); +var GetFastValue = __webpack_require__(2); +var Merge = __webpack_require__(107); +var PluginCache = __webpack_require__(23); +var SceneEvents = __webpack_require__(19); +var World = __webpack_require__(1377); + +/** + * @classdesc + * [description] + * + * @class ImpactPhysics + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - [description] + */ +var ImpactPhysics = new Class({ + + initialize: + + function ImpactPhysics (scene) + { + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#config + * @type {object} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#add + * @type {Phaser.Physics.Impact.Factory} + * @since 3.0.0 + */ + this.add; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Impact.ImpactPhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Impact.ImpactPhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#getConfig + * @since 3.0.0 + * + * @return {object} [description] + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'impact', {}), + GetFastValue(gameConfig, 'impact', {}) + ); + + return config; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#pause + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} The Impact World object. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} The Impact World object. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Impact.ImpactPhysics#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.add.destroy(); + this.world.destroy(); + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Impact.ImpactPhysics#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('ImpactPhysics', ImpactPhysics, 'impactPhysics'); + +module.exports = ImpactPhysics; + + +/***/ }), +/* 1409 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var COLLIDES = __webpack_require__(465); +var Events = __webpack_require__(1278); +var SeparateX = __webpack_require__(1410); +var SeparateY = __webpack_require__(1411); + +/** + * Impact Physics Solver + * + * @function Phaser.Physics.Impact.Solver + * @fires Phaser.Physics.Impact.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - The Impact simulation to run the solver in. + * @param {Phaser.Physics.Impact.Body} bodyA - The first body in the collision. + * @param {Phaser.Physics.Impact.Body} bodyB - The second body in the collision. + */ +var Solver = function (world, bodyA, bodyB) +{ + var weak = null; + + if (bodyA.collides === COLLIDES.LITE || bodyB.collides === COLLIDES.FIXED) + { + weak = bodyA; + } + else if (bodyB.collides === COLLIDES.LITE || bodyA.collides === COLLIDES.FIXED) + { + weak = bodyB; + } + + if (bodyA.last.x + bodyA.size.x > bodyB.last.x && bodyA.last.x < bodyB.last.x + bodyB.size.x) + { + if (bodyA.last.y < bodyB.last.y) + { + SeparateY(world, bodyA, bodyB, weak); + } + else + { + SeparateY(world, bodyB, bodyA, weak); + } + + bodyA.collideWith(bodyB, 'y'); + bodyB.collideWith(bodyA, 'y'); + + world.emit(Events.COLLIDE, bodyA, bodyB, 'y'); + } + else if (bodyA.last.y + bodyA.size.y > bodyB.last.y && bodyA.last.y < bodyB.last.y + bodyB.size.y) + { + if (bodyA.last.x < bodyB.last.x) + { + SeparateX(world, bodyA, bodyB, weak); + } + else + { + SeparateX(world, bodyB, bodyA, weak); + } + + bodyA.collideWith(bodyB, 'x'); + bodyB.collideWith(bodyA, 'x'); + + world.emit(Events.COLLIDE, bodyA, bodyB, 'x'); + } +}; + +module.exports = Solver; + + +/***/ }), +/* 1410 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * [description] + * + * @function Phaser.Physics.Impact.SeparateX + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {Phaser.Physics.Impact.Body} left - [description] + * @param {Phaser.Physics.Impact.Body} right - [description] + * @param {Phaser.Physics.Impact.Body} [weak] - [description] + */ +var SeparateX = function (world, left, right, weak) +{ + var nudge = left.pos.x + left.size.x - right.pos.x; + + // We have a weak entity, so just move this one + if (weak) + { + var strong = (left === weak) ? right : left; + + weak.vel.x = -weak.vel.x * weak.bounciness + strong.vel.x; + + var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, weak === left ? -nudge : nudge, 0, weak.size.x, weak.size.y); + + weak.pos.x = resWeak.pos.x; + } + else + { + var v2 = (left.vel.x - right.vel.x) / 2; + + left.vel.x = -v2; + right.vel.x = v2; + + var resLeft = world.collisionMap.trace(left.pos.x, left.pos.y, -nudge / 2, 0, left.size.x, left.size.y); + + left.pos.x = Math.floor(resLeft.pos.x); + + var resRight = world.collisionMap.trace(right.pos.x, right.pos.y, nudge / 2, 0, right.size.x, right.size.y); + + right.pos.x = Math.ceil(resRight.pos.x); + } +}; + +module.exports = SeparateX; + + +/***/ }), +/* 1411 */ +/***/ (function(module, exports) { + +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * [description] + * + * @function Phaser.Physics.Impact.SeparateY + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {Phaser.Physics.Impact.Body} top - [description] + * @param {Phaser.Physics.Impact.Body} bottom - [description] + * @param {Phaser.Physics.Impact.Body} [weak] - [description] + */ +var SeparateY = function (world, top, bottom, weak) +{ + var nudge = (top.pos.y + top.size.y - bottom.pos.y); + var nudgeX; + var resTop; + + if (weak) + { + var strong = (top === weak) ? bottom : top; + + weak.vel.y = -weak.vel.y * weak.bounciness + strong.vel.y; + + // Riding on a platform? + nudgeX = 0; + + if (weak === top && Math.abs(weak.vel.y - strong.vel.y) < weak.minBounceVelocity) + { + weak.standing = true; + nudgeX = strong.vel.x * world.delta; + } + + var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, nudgeX, weak === top ? -nudge : nudge, weak.size.x, weak.size.y); + + weak.pos.y = resWeak.pos.y; + weak.pos.x = resWeak.pos.x; + } + else if (world.gravity && (bottom.standing || top.vel.y > 0)) + { + resTop = world.collisionMap.trace(top.pos.x, top.pos.y, 0, -(top.pos.y + top.size.y - bottom.pos.y), top.size.x, top.size.y); + + top.pos.y = resTop.pos.y; + + if (top.bounciness > 0 && top.vel.y > top.minBounceVelocity) + { + top.vel.y *= -top.bounciness; + } + else + { + top.standing = true; + top.vel.y = 0; + } + } + else + { + var v2 = (top.vel.y - bottom.vel.y) / 2; + + top.vel.y = -v2; + bottom.vel.y = v2; + + nudgeX = bottom.vel.x * world.delta; + + resTop = world.collisionMap.trace(top.pos.x, top.pos.y, nudgeX, -nudge / 2, top.size.x, top.size.y); + + top.pos.y = resTop.pos.y; + + var resBottom = world.collisionMap.trace(bottom.pos.x, bottom.pos.y, 0, nudge / 2, bottom.size.x, bottom.size.y); + + bottom.pos.y = resBottom.pos.y; + } +}; + +module.exports = SeparateY; + + +/***/ }), +/* 1412 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -193966,23 +195445,23 @@ module.exports = { module.exports = { - BodyBounds: __webpack_require__(1376), - Factory: __webpack_require__(1377), - Image: __webpack_require__(1379), - Matter: __webpack_require__(1288), - MatterPhysics: __webpack_require__(1419), - PolyDecomp: __webpack_require__(1378), - Sprite: __webpack_require__(1380), - TileBody: __webpack_require__(1287), - PhysicsEditorParser: __webpack_require__(1284), - PhysicsJSONParser: __webpack_require__(1285), - World: __webpack_require__(1384) + BodyBounds: __webpack_require__(1378), + Factory: __webpack_require__(1379), + Image: __webpack_require__(1381), + Matter: __webpack_require__(1286), + MatterPhysics: __webpack_require__(1444), + PolyDecomp: __webpack_require__(1380), + Sprite: __webpack_require__(1382), + TileBody: __webpack_require__(1285), + PhysicsEditorParser: __webpack_require__(1282), + PhysicsJSONParser: __webpack_require__(1283), + World: __webpack_require__(1386) }; /***/ }), -/* 1388 */ +/* 1413 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -193991,7 +195470,7 @@ module.exports = { * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Components = __webpack_require__(509); +var Components = __webpack_require__(508); var GetFastValue = __webpack_require__(2); var Vector2 = __webpack_require__(3); @@ -194108,7 +195587,7 @@ module.exports = MatterGameObject; /***/ }), -/* 1389 */ +/* 1414 */ /***/ (function(module, exports) { /** @@ -194148,7 +195627,7 @@ module.exports = Bounce; /***/ }), -/* 1390 */ +/* 1415 */ /***/ (function(module, exports) { /** @@ -194334,7 +195813,7 @@ module.exports = Collision; /***/ }), -/* 1391 */ +/* 1416 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -194490,7 +195969,7 @@ module.exports = Force; /***/ }), -/* 1392 */ +/* 1417 */ /***/ (function(module, exports) { /** @@ -194580,7 +196059,7 @@ module.exports = Friction; /***/ }), -/* 1393 */ +/* 1418 */ /***/ (function(module, exports) { /** @@ -194620,7 +196099,7 @@ module.exports = Gravity; /***/ }), -/* 1394 */ +/* 1419 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -194702,7 +196181,7 @@ module.exports = Mass; /***/ }), -/* 1395 */ +/* 1420 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -194757,7 +196236,7 @@ module.exports = Static; /***/ }), -/* 1396 */ +/* 1421 */ /***/ (function(module, exports) { /** @@ -194811,7 +196290,7 @@ module.exports = Sensor; /***/ }), -/* 1397 */ +/* 1422 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -194820,13 +196299,13 @@ module.exports = Sensor; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bodies = __webpack_require__(105); +var Bodies = __webpack_require__(109); var Body = __webpack_require__(62); -var FuzzyEquals = __webpack_require__(140); +var FuzzyEquals = __webpack_require__(144); var GetFastValue = __webpack_require__(2); -var PhysicsEditorParser = __webpack_require__(1284); -var PhysicsJSONParser = __webpack_require__(1285); -var Vertices = __webpack_require__(84); +var PhysicsEditorParser = __webpack_require__(1282); +var PhysicsJSONParser = __webpack_require__(1283); +var Vertices = __webpack_require__(86); /** * Enables a Matter-enabled Game Object to set its Body. Should be used as a mixin and not directly. @@ -195101,7 +196580,7 @@ module.exports = SetBody; /***/ }), -/* 1398 */ +/* 1423 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -195110,9 +196589,9 @@ module.exports = SetBody; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Events = __webpack_require__(1286); -var Sleeping = __webpack_require__(234); -var MatterEvents = __webpack_require__(235); +var Events = __webpack_require__(1284); +var Sleeping = __webpack_require__(236); +var MatterEvents = __webpack_require__(237); /** * Enables a Matter-enabled Game Object to be able to go to sleep. Should be used as a mixin and not directly. @@ -195255,7 +196734,7 @@ module.exports = Sleep; /***/ }), -/* 1399 */ +/* 1424 */ /***/ (function(module, exports) { /** @@ -195289,7 +196768,7 @@ module.exports = 'afteradd'; /***/ }), -/* 1400 */ +/* 1425 */ /***/ (function(module, exports) { /** @@ -195323,7 +196802,7 @@ module.exports = 'afterremove'; /***/ }), -/* 1401 */ +/* 1426 */ /***/ (function(module, exports) { /** @@ -195356,7 +196835,7 @@ module.exports = 'afterupdate'; /***/ }), -/* 1402 */ +/* 1427 */ /***/ (function(module, exports) { /** @@ -195390,7 +196869,7 @@ module.exports = 'beforeadd'; /***/ }), -/* 1403 */ +/* 1428 */ /***/ (function(module, exports) { /** @@ -195424,7 +196903,7 @@ module.exports = 'beforeremove'; /***/ }), -/* 1404 */ +/* 1429 */ /***/ (function(module, exports) { /** @@ -195457,7 +196936,7 @@ module.exports = 'beforeupdate'; /***/ }), -/* 1405 */ +/* 1430 */ /***/ (function(module, exports) { /** @@ -195494,7 +196973,7 @@ module.exports = 'collisionactive'; /***/ }), -/* 1406 */ +/* 1431 */ /***/ (function(module, exports) { /** @@ -195531,7 +197010,7 @@ module.exports = 'collisionend'; /***/ }), -/* 1407 */ +/* 1432 */ /***/ (function(module, exports) { /** @@ -195568,7 +197047,7 @@ module.exports = 'collisionstart'; /***/ }), -/* 1408 */ +/* 1433 */ /***/ (function(module, exports) { /** @@ -195595,7 +197074,7 @@ module.exports = 'dragend'; /***/ }), -/* 1409 */ +/* 1434 */ /***/ (function(module, exports) { /** @@ -195622,7 +197101,7 @@ module.exports = 'drag'; /***/ }), -/* 1410 */ +/* 1435 */ /***/ (function(module, exports) { /** @@ -195650,7 +197129,7 @@ module.exports = 'dragstart'; /***/ }), -/* 1411 */ +/* 1436 */ /***/ (function(module, exports) { /** @@ -195673,7 +197152,7 @@ module.exports = 'pause'; /***/ }), -/* 1412 */ +/* 1437 */ /***/ (function(module, exports) { /** @@ -195696,7 +197175,7 @@ module.exports = 'resume'; /***/ }), -/* 1413 */ +/* 1438 */ /***/ (function(module, exports) { /** @@ -195729,7 +197208,7 @@ module.exports = 'sleepend'; /***/ }), -/* 1414 */ +/* 1439 */ /***/ (function(module, exports) { /** @@ -195762,7 +197241,7 @@ module.exports = 'sleepstart'; /***/ }), -/* 1415 */ +/* 1440 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -195772,9 +197251,9 @@ module.exports = 'sleepstart'; */ var Body = __webpack_require__(62); -var MATH_CONST = __webpack_require__(16); -var WrapAngle = __webpack_require__(230); -var WrapAngleDegrees = __webpack_require__(231); +var MATH_CONST = __webpack_require__(13); +var WrapAngle = __webpack_require__(232); +var WrapAngleDegrees = __webpack_require__(233); // global bitmask flag for GameObject.renderMask (used by Scale) var _FLAG = 4; // 0100 @@ -196077,7 +197556,7 @@ module.exports = Transform; /***/ }), -/* 1416 */ +/* 1441 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -196178,7 +197657,7 @@ module.exports = Velocity; /***/ }), -/* 1417 */ +/* 1442 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -196187,17 +197666,17 @@ module.exports = Velocity; * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var Bounds = __webpack_require__(98); +var Bounds = __webpack_require__(102); var Class = __webpack_require__(0); -var Composite = __webpack_require__(142); -var Constraint = __webpack_require__(214); -var Detector = __webpack_require__(510); -var Events = __webpack_require__(1286); +var Composite = __webpack_require__(145); +var Constraint = __webpack_require__(216); +var Detector = __webpack_require__(509); +var Events = __webpack_require__(1284); var InputEvents = __webpack_require__(54); -var Merge = __webpack_require__(120); -var Sleeping = __webpack_require__(234); +var Merge = __webpack_require__(107); +var Sleeping = __webpack_require__(236); var Vector2 = __webpack_require__(3); -var Vertices = __webpack_require__(84); +var Vertices = __webpack_require__(86); /** * @classdesc @@ -196566,7 +198045,7 @@ module.exports = PointerConstraint; /***/ }), -/* 1418 */ +/* 1443 */ /***/ (function(module, exports, __webpack_require__) { // @if DEBUG @@ -196579,7 +198058,7 @@ var Metrics = {}; module.exports = Metrics; -var Composite = __webpack_require__(142); +var Composite = __webpack_require__(145); var Common = __webpack_require__(37); (function() { @@ -196665,7 +198144,7 @@ var Common = __webpack_require__(37); /***/ }), -/* 1419 */ +/* 1444 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -196674,39 +198153,39 @@ var Common = __webpack_require__(37); * @license {@link https://opensource.org/licenses/MIT|MIT License} */ -var ALIGN_CONST = __webpack_require__(102); -var Axes = __webpack_require__(508); -var Bodies = __webpack_require__(105); +var ALIGN_CONST = __webpack_require__(106); +var Axes = __webpack_require__(507); +var Bodies = __webpack_require__(109); var Body = __webpack_require__(62); -var BodyBounds = __webpack_require__(1376); -var Bounds = __webpack_require__(98); +var BodyBounds = __webpack_require__(1378); +var Bounds = __webpack_require__(102); var Class = __webpack_require__(0); -var Composite = __webpack_require__(142); -var Composites = __webpack_require__(1282); -var Constraint = __webpack_require__(214); -var Detector = __webpack_require__(510); +var Composite = __webpack_require__(145); +var Composites = __webpack_require__(1280); +var Constraint = __webpack_require__(216); +var Detector = __webpack_require__(509); var DistanceBetween = __webpack_require__(53); -var Factory = __webpack_require__(1377); +var Factory = __webpack_require__(1379); var GetFastValue = __webpack_require__(2); var GetValue = __webpack_require__(6); -var Grid = __webpack_require__(1291); -var MatterAttractors = __webpack_require__(1420); -var MatterCollisionEvents = __webpack_require__(1421); -var MatterLib = __webpack_require__(1381); -var MatterWrap = __webpack_require__(1422); -var Merge = __webpack_require__(120); -var Pair = __webpack_require__(466); -var Pairs = __webpack_require__(1292); -var Plugin = __webpack_require__(1289); -var PluginCache = __webpack_require__(24); -var Query = __webpack_require__(1382); -var Resolver = __webpack_require__(1293); -var SAT = __webpack_require__(511); -var SceneEvents = __webpack_require__(22); -var Svg = __webpack_require__(1283); -var Vector = __webpack_require__(97); -var Vertices = __webpack_require__(84); -var World = __webpack_require__(1384); +var Grid = __webpack_require__(1289); +var MatterAttractors = __webpack_require__(1445); +var MatterCollisionEvents = __webpack_require__(1446); +var MatterLib = __webpack_require__(1383); +var MatterWrap = __webpack_require__(1447); +var Merge = __webpack_require__(107); +var Pair = __webpack_require__(467); +var Pairs = __webpack_require__(1290); +var Plugin = __webpack_require__(1287); +var PluginCache = __webpack_require__(23); +var Query = __webpack_require__(1384); +var Resolver = __webpack_require__(1291); +var SAT = __webpack_require__(510); +var SceneEvents = __webpack_require__(19); +var Svg = __webpack_require__(1281); +var Vector = __webpack_require__(101); +var Vertices = __webpack_require__(86); +var World = __webpack_require__(1386); /** * @classdesc @@ -198134,10 +199613,10 @@ module.exports = MatterPhysics; /***/ }), -/* 1420 */ +/* 1445 */ /***/ (function(module, exports, __webpack_require__) { -var Matter = __webpack_require__(1288); +var Matter = __webpack_require__(1286); /** * An attractors plugin for matter.js. @@ -198276,7 +199755,7 @@ module.exports = MatterAttractors; /***/ }), -/* 1421 */ +/* 1446 */ /***/ (function(module, exports) { /** @@ -198409,10 +199888,10 @@ module.exports = MatterCollisionEvents; /***/ }), -/* 1422 */ +/* 1447 */ /***/ (function(module, exports, __webpack_require__) { -var Matter = __webpack_require__(1288); +var Matter = __webpack_require__(1286); /** * A coordinate wrapping plugin for matter.js. @@ -198591,7 +200070,7 @@ module.exports = MatterWrap; */ /***/ }), -/* 1423 */ +/* 1448 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -198610,15 +200089,15 @@ module.exports = MatterWrap; module.exports = { - Canvas: __webpack_require__(1424), - Snapshot: __webpack_require__(1425), - WebGL: __webpack_require__(1426) + Canvas: __webpack_require__(1449), + Snapshot: __webpack_require__(1450), + WebGL: __webpack_require__(1451) }; /***/ }), -/* 1424 */ +/* 1449 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -198633,15 +200112,15 @@ module.exports = { module.exports = { - CanvasRenderer: __webpack_require__(500), - GetBlendModes: __webpack_require__(502), - SetTransform: __webpack_require__(29) + CanvasRenderer: __webpack_require__(499), + GetBlendModes: __webpack_require__(501), + SetTransform: __webpack_require__(27) }; /***/ }), -/* 1425 */ +/* 1450 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -198656,14 +200135,14 @@ module.exports = { module.exports = { - Canvas: __webpack_require__(501), - WebGL: __webpack_require__(504) + Canvas: __webpack_require__(500), + WebGL: __webpack_require__(503) }; /***/ }), -/* 1426 */ +/* 1451 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -198678,10 +200157,10 @@ module.exports = { module.exports = { - Utils: __webpack_require__(9), - WebGLPipeline: __webpack_require__(141), - WebGLRenderer: __webpack_require__(503), - Pipelines: __webpack_require__(1427), + Utils: __webpack_require__(10), + WebGLPipeline: __webpack_require__(234), + WebGLRenderer: __webpack_require__(502), + Pipelines: __webpack_require__(1452), // Constants BYTE: 0, @@ -198694,7 +200173,7 @@ module.exports = { /***/ }), -/* 1427 */ +/* 1452 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -198709,11 +200188,10 @@ module.exports = { module.exports = { - BitmapMaskPipeline: __webpack_require__(505), - ForwardDiffuseLightPipeline: __webpack_require__(506), - TextureTintPipeline: __webpack_require__(232), - TextureTintStripPipeline: __webpack_require__(507), - ModelViewProjection: __webpack_require__(233) + BitmapMaskPipeline: __webpack_require__(504), + ForwardDiffuseLightPipeline: __webpack_require__(505), + TextureTintPipeline: __webpack_require__(235), + ModelViewProjection: __webpack_require__(506) }; diff --git a/dist/phaser.min.js b/dist/phaser.min.js index f6fdb9f5d..efff29f22 100644 --- a/dist/phaser.min.js +++ b/dist/phaser.min.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("Phaser",[],e):"object"==typeof exports?exports.Phaser=e():t.Phaser=e()}(window,function(){return function(t){var e={};function i(n){if(e[n])return e[n].exports;var s=e[n]={i:n,l:!1,exports:{}};return t[n].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)i.d(n,s,function(e){return t[e]}.bind(null,s));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=1385)}([function(t,e){function i(t,e,i){var n=i?t[e]:Object.getOwnPropertyDescriptor(t,e);return!i&&n.value&&"object"==typeof n.value&&(n=n.value),!(!n||!function(t){return!!t.get&&"function"==typeof t.get||!!t.set&&"function"==typeof t.set}(n))&&(void 0===n.enumerable&&(n.enumerable=!0),void 0===n.configurable&&(n.configurable=!0),n)}function n(t,e){var i=Object.getOwnPropertyDescriptor(t,e);return!!i&&(i.value&&"object"==typeof i.value&&(i=i.value),!1===i.configurable)}function s(t,e,s,r){for(var a in e)if(e.hasOwnProperty(a)){var h=i(e,a,s);if(!1!==h){if(n((r||t).prototype,a)){if(o.ignoreFinals)continue;throw new Error("cannot override final property '"+a+"', set Class.ignoreFinals = true to skip")}Object.defineProperty(t.prototype,a,h)}else t.prototype[a]=e[a]}}function r(t,e){if(e){Array.isArray(e)||(e=[e]);for(var i=0;i0&&(i=1/Math.sqrt(i),this.x=t*i,this.y=e*i),this},normalizeRightHand:function(){var t=this.x;return this.x=-1*this.y,this.y=t,this},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this},transformMat3:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this},transformMat4:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[4]*i+n[12],this.y=n[1]*e+n[5]*i+n[13],this},reset:function(){return this.x=0,this.y=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0),n.LEFT=new n(-1,0),n.UP=new n(0,-1),n.DOWN=new n(0,1),n.ONE=new n(1,1),t.exports=n},function(t,e,i){var n=i(0),s=i(46),r=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=t),this.type=s.POINT,this.x=t,this.y=e},setTo:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.x=t,this.y=e,this}});t.exports=r},function(t,e,i){var n=i(0),s=i(24),r=i(22),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},existing:function(t){return(t.renderCanvas||t.renderWebGL)&&this.displayList.add(t),t.preUpdate&&this.updateList.add(t),t},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectFactory",o,"add"),t.exports=o},function(t,e){t.exports=function(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=i,o=0;o>>0},getTintAppendFloatAlpha:function(t,e){return((255&(255*e|0))<<24|t)>>>0},getTintAppendFloatAlphaAndSwap:function(t,e){return((255&(255*e|0))<<24|(255&(0|t))<<16|(255&(t>>8|0))<<8|255&(t>>16|0))>>>0},getFloatsFromUintRGB:function(t){return[(255&(t>>16|0))/255,(255&(t>>8|0))/255,(255&(0|t))/255]},getComponentCount:function(t,e){for(var i=0,n=0;n=this.right?this.width=0:this.width=this.right-t,this.x=t}},right:{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}},top:{get:function(){return this.y},set:function(t){t>=this.bottom?this.height=0:this.height=this.bottom-t,this.y=t}},bottom:{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}},centerX:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},centerY:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=u},function(t,e,i){var n=i(0),s=i(276),r=i(109),o=i(11),a=i(88),h=new n({Extends:o,initialize:function(t,e){o.call(this),this.scene=t,this.type=e,this.state=0,this.parentContainer=null,this.name="",this.active=!0,this.tabIndex=-1,this.data=null,this.renderFlags=15,this.cameraFilter=0,this.input=null,this.body=null,this.ignoreDestroy=!1,t.sys.queueDepthSort()},setActive:function(t){return this.active=t,this},setName:function(t){return this.name=t,this},setState:function(t){return this.state=t,this},setDataEnabled:function(){return this.data||(this.data=new r(this)),this},setData:function(t,e){return this.data||(this.data=new r(this)),this.data.set(t,e),this},getData:function(t){return this.data||(this.data=new r(this)),this.data.get(t)},setInteractive:function(t,e,i){return this.scene.sys.input.enable(this,t,e,i),this},disableInteractive:function(){return this.input&&(this.input.enabled=!1),this},removeInteractive:function(){return this.scene.sys.input.clear(this),this.input=void 0,this},update:function(){},toJSON:function(){return s(this)},willRender:function(t){return!(h.RENDER_MASK!==this.renderFlags||0!==this.cameraFilter&&this.cameraFilter&t.id)},getIndexList:function(){for(var t=this,e=this.parentContainer,i=[];e&&(i.unshift(e.getIndex(t)),t=e,e.parentContainer);)e=e.parentContainer;return i.unshift(this.scene.sys.displayList.getIndex(t)),i},destroy:function(t){if(void 0===t&&(t=!1),this.scene&&!this.ignoreDestroy){this.preDestroy&&this.preDestroy.call(this),this.emit(a.DESTROY,this);var e=this.scene.sys;t||(e.displayList.remove(this),e.updateList.remove(this)),this.input&&(e.input.clear(this),this.input=void 0),this.data&&(this.data.destroy(),this.data=void 0),this.body&&(this.body.destroy(),this.body=void 0),t||e.queueDepthSort(),this.active=!1,this.visible=!1,this.scene=void 0,this.parentContainer=void 0,this.removeAllListeners()}}});h.RENDER_MASK=15,t.exports=h},function(t,e,i){var n=i(165),s=i(6);t.exports=function(t,e,i){var r=s(t,e,null);if(null===r)return i;if(Array.isArray(r))return n.RND.pick(r);if("object"==typeof r){if(r.hasOwnProperty("randInt"))return n.RND.integerInRange(r.randInt[0],r.randInt[1]);if(r.hasOwnProperty("randFloat"))return n.RND.realInRange(r.randFloat[0],r.randFloat[1])}else if("function"==typeof r)return r(e);return r}},function(t,e){var i={PI2:2*Math.PI,TAU:.5*Math.PI,EPSILON:1e-6,DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,RND:null,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER||-9007199254740991,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991};t.exports=i},function(t,e,i){var n=i(0),s=i(24),r=i(22),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectCreator",o,"make"),t.exports=o},function(t,e,i){var n=i(7),s=function(){var t,e,i,r,o,a,h=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof h&&(c=h,h=arguments[1]||{},l=2),u===l&&(h=this,--l);l=400&&t.status<=599&&(n=!1),this.resetXHR(),this.loader.nextFile(this,n)},onError:function(){this.resetXHR(),this.loader.nextFile(this,!1)},onProgress:function(t){t.lengthComputable&&(this.bytesLoaded=t.loaded,this.bytesTotal=t.total,this.percentComplete=Math.min(this.bytesLoaded/this.bytesTotal,1),this.loader.emit(r.FILE_PROGRESS,this,this.percentComplete))},onProcess:function(){this.state=s.FILE_PROCESSING,this.onProcessComplete()},onProcessComplete:function(){this.state=s.FILE_COMPLETE,this.multiFile&&this.multiFile.onFileComplete(this),this.loader.fileProcessComplete(this)},onProcessError:function(){this.state=s.FILE_ERRORED,this.multiFile&&this.multiFile.onFileFailed(this),this.loader.fileProcessComplete(this)},hasCacheConflict:function(){return this.cache&&this.cache.exists(this.key)},addToCache:function(){this.cache&&this.cache.add(this.key,this.data),this.pendingDestroy()},pendingDestroy:function(t){void 0===t&&(t=this.data);var e=this.key,i=this.type;this.loader.emit(r.FILE_COMPLETE,e,i,t),this.loader.emit(r.FILE_KEY_COMPLETE+i+"-"+e,e,i,t),this.loader.flagForRemoval(this)},destroy:function(){this.loader=null,this.cache=null,this.xhrSettings=null,this.multiFile=null,this.linkFile=null,this.data=null}});c.createObjectURL=function(t,e,i){if("function"==typeof URL)t.src=URL.createObjectURL(e);else{var n=new FileReader;n.onload=function(){t.removeAttribute("crossOrigin"),t.src="data:"+(e.type||i)+";base64,"+n.result.split(",")[1]},n.onerror=t.onerror,n.readAsDataURL(e)}},c.revokeObjectURL=function(t){"function"==typeof URL&&URL.revokeObjectURL(t.src)},t.exports=c},function(t,e,i){t.exports={BOOT:i(701),CREATE:i(702),DESTROY:i(703),PAUSE:i(704),POST_UPDATE:i(705),PRE_UPDATE:i(706),READY:i(707),RENDER:i(708),RESUME:i(709),SHUTDOWN:i(710),SLEEP:i(711),START:i(712),TRANSITION_COMPLETE:i(713),TRANSITION_INIT:i(714),TRANSITION_OUT:i(715),TRANSITION_START:i(716),TRANSITION_WAKE:i(717),UPDATE:i(718),WAKE:i(719)}},function(t,e){t.exports=function(t,e,i){return Math.max(e,Math.min(i,t))}},function(t,e){var i={},n={},s={register:function(t,e,n,s){void 0===s&&(s=!1),i[t]={plugin:e,mapping:n,custom:s}},registerCustom:function(t,e,i,s){n[t]={plugin:e,mapping:i,data:s}},hasCore:function(t){return i.hasOwnProperty(t)},hasCustom:function(t){return n.hasOwnProperty(t)},getCore:function(t){return i[t]},getCustom:function(t){return n[t]},getCustomClass:function(t){return n.hasOwnProperty(t)?n[t].plugin:null},remove:function(t){i.hasOwnProperty(t)&&delete i[t]},removeCustom:function(t){n.hasOwnProperty(t)&&delete n[t]},destroyCorePlugins:function(){for(var t in i)i.hasOwnProperty(t)&&delete i[t]},destroyCustomPlugins:function(){for(var t in n)n.hasOwnProperty(t)&&delete n[t]}};t.exports=s},function(t,e,i){var n=i(2);t.exports=function(t,e,i,s,r,o){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=o.width),void 0===s&&(s=o.height);var a=n(r,"isNotEmpty",!1),h=n(r,"isColliding",!1),l=n(r,"hasInterestingFace",!1);t<0&&(i+=t,t=0),e<0&&(s+=e,e=0),t+i>o.width&&(i=Math.max(o.width-t,0)),e+s>o.height&&(s=Math.max(o.height-e,0));for(var u=[],c=e;c=0;o--)t[o][e]=i+a*n,a++;return t}},function(t,e,i){var n,s,r,o=i(10),a=i(161),h=[],l=!1;t.exports={create2D:function(t,e,i){return n(t,e,i,o.CANVAS)},create:n=function(t,e,i,n,r){var u;void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=o.CANVAS),void 0===r&&(r=!1);var c=s(n);return null===c?(c={parent:t,canvas:document.createElement("canvas"),type:n},n===o.CANVAS&&h.push(c),u=c.canvas):(c.parent=t,u=c.canvas),r&&(c.parent=u),u.width=e,u.height=i,l&&n===o.CANVAS&&a.disable(u.getContext("2d")),u},createWebGL:function(t,e,i){return n(t,e,i,o.WEBGL)},disableSmoothing:function(){l=!0},enableSmoothing:function(){l=!1},first:s=function(t){if(void 0===t&&(t=o.CANVAS),t===o.WEBGL)return null;for(var e=0;e0?Math.acos(e/this.scaleX):-Math.acos(e/this.scaleX):n||r?s.TAU-(r>0?Math.acos(-n/this.scaleY):-Math.acos(n/this.scaleY)):0}},scaleX:{get:function(){return Math.sqrt(this.a*this.a+this.b*this.b)}},scaleY:{get:function(){return Math.sqrt(this.c*this.c+this.d*this.d)}},loadIdentity:function(){var t=this.matrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,this},translate:function(t,e){var i=this.matrix;return i[4]=i[0]*t+i[2]*e+i[4],i[5]=i[1]*t+i[3]*e+i[5],this},scale:function(t,e){var i=this.matrix;return i[0]*=t,i[1]*=t,i[2]*=e,i[3]*=e,this},rotate:function(t){var e=Math.sin(t),i=Math.cos(t),n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3];return n[0]=s*i+o*e,n[1]=r*i+a*e,n[2]=s*-e+o*i,n[3]=r*-e+a*i,this},multiply:function(t,e){var i=this.matrix,n=t.matrix,s=i[0],r=i[1],o=i[2],a=i[3],h=i[4],l=i[5],u=n[0],c=n[1],d=n[2],f=n[3],p=n[4],g=n[5],v=void 0===e?this:e;return v.a=u*s+c*o,v.b=u*r+c*a,v.c=d*s+f*o,v.d=d*r+f*a,v.e=p*s+g*o+h,v.f=p*r+g*a+l,v},multiplyWithOffset:function(t,e,i){var n=this.matrix,s=t.matrix,r=n[0],o=n[1],a=n[2],h=n[3],l=e*r+i*a+n[4],u=e*o+i*h+n[5],c=s[0],d=s[1],f=s[2],p=s[3],g=s[4],v=s[5];return n[0]=c*r+d*a,n[1]=c*o+d*h,n[2]=f*r+p*a,n[3]=f*o+p*h,n[4]=g*r+v*a+l,n[5]=g*o+v*h+u,this},transform:function(t,e,i,n,s,r){var o=this.matrix,a=o[0],h=o[1],l=o[2],u=o[3],c=o[4],d=o[5];return o[0]=t*a+e*l,o[1]=t*h+e*u,o[2]=i*a+n*l,o[3]=i*h+n*u,o[4]=s*a+r*l+c,o[5]=s*h+r*u+d,this},transformPoint:function(t,e,i){void 0===i&&(i={x:0,y:0});var n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5];return i.x=t*s+e*o+h,i.y=t*r+e*a+l,i},invert:function(){var t=this.matrix,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=e*s-i*n;return t[0]=s/a,t[1]=-i/a,t[2]=-n/a,t[3]=e/a,t[4]=(n*o-s*r)/a,t[5]=-(e*o-i*r)/a,this},copyFrom:function(t){var e=this.matrix;return e[0]=t.a,e[1]=t.b,e[2]=t.c,e[3]=t.d,e[4]=t.e,e[5]=t.f,this},copyFromArray:function(t){var e=this.matrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],this},copyToContext:function(t){var e=this.matrix;return t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t},setToContext:function(t){var e=this.matrix;return t.setTransform(e[0],e[1],e[2],e[3],e[4],e[5]),t},copyToArray:function(t){var e=this.matrix;return void 0===t?t=[e[0],e[1],e[2],e[3],e[4],e[5]]:(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]),t},setTransform:function(t,e,i,n,s,r){var o=this.matrix;return o[0]=t,o[1]=e,o[2]=i,o[3]=n,o[4]=s,o[5]=r,this},decomposeMatrix:function(){var t=this.decomposedMatrix,e=this.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(t.translateX=e[4],t.translateY=e[5],i||n){var a=Math.sqrt(i*i+n*n);t.rotation=n>0?Math.acos(i/a):-Math.acos(i/a),t.scaleX=a,t.scaleY=o/a}else if(s||r){var h=Math.sqrt(s*s+r*r);t.rotation=.5*Math.PI-(r>0?Math.acos(-s/h):-Math.acos(s/h)),t.scaleX=o/h,t.scaleY=h}else t.rotation=0,t.scaleX=0,t.scaleY=0;return t},applyITRS:function(t,e,i,n,s){var r=this.matrix,o=Math.sin(i),a=Math.cos(i);return r[4]=t,r[5]=e,r[0]=a*n,r[1]=o*n,r[2]=-o*s,r[3]=a*s,this},applyInverse:function(t,e,i){void 0===i&&(i=new r);var n=this.matrix,s=n[0],o=n[1],a=n[2],h=n[3],l=n[4],u=n[5],c=1/(s*h+a*-o);return i.x=h*c*t+-a*c*e+(u*a-l*h)*c,i.y=s*c*e+-o*c*t+(-u*s+l*o)*c,i},getX:function(t,e){return t*this.a+e*this.c+this.e},getY:function(t,e){return t*this.b+e*this.d+this.f},getCSSMatrix:function(){var t=this.matrix;return"matrix("+t[0]+","+t[1]+","+t[2]+","+t[3]+","+t[4]+","+t[5]+")"},destroy:function(){this.matrix=null,this.decomposedMatrix=null}});t.exports=o},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(56),a=new n({Extends:r,Mixins:[s.AlphaSingle,s.BlendMode,s.ComputedSize,s.Depth,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Transform,s.Visible],initialize:function(t,e,i){void 0===e&&(e="Shape"),r.call(this,t,e),this.geom=i,this.pathData=[],this.pathIndexes=[],this.fillColor=16777215,this.fillAlpha=1,this.strokeColor=16777215,this.strokeAlpha=1,this.lineWidth=1,this.isFilled=!1,this.isStroked=!1,this.closePath=!0,this._tempLine=new o,this.initPipeline()},setFillStyle:function(t,e){return void 0===e&&(e=1),void 0===t?this.isFilled=!1:(this.fillColor=t,this.fillAlpha=e,this.isFilled=!0),this},setStrokeStyle:function(t,e,i){return void 0===i&&(i=1),void 0===t?this.isStroked=!1:(this.lineWidth=t,this.strokeColor=e,this.strokeAlpha=i,this.isStroked=!0),this},setClosePath:function(t){return this.closePath=t,this},preDestroy:function(){this.geom=null,this._tempLine=null,this.pathData=[],this.pathIndexes=[]}});t.exports=a},function(t,e,i){var n=i(0),s=i(159),r=i(290),o=i(160),a=i(291),h=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=255),this.r=0,this.g=0,this.b=0,this.a=255,this._h=0,this._s=0,this._v=0,this._locked=!1,this.gl=[0,0,0,1],this._color=0,this._color32=0,this._rgba="",this.setTo(t,e,i,n)},transparent:function(){return this._locked=!0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this._locked=!1,this.update(!0)},setTo:function(t,e,i,n,s){return void 0===n&&(n=255),void 0===s&&(s=!0),this._locked=!0,this.red=t,this.green=e,this.blue=i,this.alpha=n,this._locked=!1,this.update(s)},setGLTo:function(t,e,i,n){return void 0===n&&(n=1),this._locked=!0,this.redGL=t,this.greenGL=e,this.blueGL=i,this.alphaGL=n,this._locked=!1,this.update(!0)},setFromRGB:function(t){return this._locked=!0,this.red=t.r,this.green=t.g,this.blue=t.b,t.hasOwnProperty("a")&&(this.alpha=t.a),this._locked=!1,this.update(!0)},setFromHSV:function(t,e,i){return o(t,e,i,this)},update:function(t){if(void 0===t&&(t=!1),this._locked)return this;var e=this.r,i=this.g,n=this.b,o=this.a;return this._color=s(e,i,n),this._color32=r(e,i,n,o),this._rgba="rgba("+e+","+i+","+n+","+o/255+")",t&&a(e,i,n,this),this},updateHSV:function(){var t=this.r,e=this.g,i=this.b;return a(t,e,i,this),this},clone:function(){return new h(this.r,this.g,this.b,this.a)},gray:function(t){return this.setTo(t,t,t)},random:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t)),n=Math.floor(t+Math.random()*(e-t)),s=Math.floor(t+Math.random()*(e-t));return this.setTo(i,n,s)},randomGray:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t));return this.setTo(i,i,i)},saturate:function(t){return this.s+=t/100,this},desaturate:function(t){return this.s-=t/100,this},lighten:function(t){return this.v+=t/100,this},darken:function(t){return this.v-=t/100,this},brighten:function(t){var e=this.r,i=this.g,n=this.b;return e=Math.max(0,Math.min(255,e-Math.round(-t/100*255))),i=Math.max(0,Math.min(255,i-Math.round(-t/100*255))),n=Math.max(0,Math.min(255,n-Math.round(-t/100*255))),this.setTo(e,i,n)},color:{get:function(){return this._color}},color32:{get:function(){return this._color32}},rgba:{get:function(){return this._rgba}},redGL:{get:function(){return this.gl[0]},set:function(t){this.gl[0]=Math.min(Math.abs(t),1),this.r=Math.floor(255*this.gl[0]),this.update(!0)}},greenGL:{get:function(){return this.gl[1]},set:function(t){this.gl[1]=Math.min(Math.abs(t),1),this.g=Math.floor(255*this.gl[1]),this.update(!0)}},blueGL:{get:function(){return this.gl[2]},set:function(t){this.gl[2]=Math.min(Math.abs(t),1),this.b=Math.floor(255*this.gl[2]),this.update(!0)}},alphaGL:{get:function(){return this.gl[3]},set:function(t){this.gl[3]=Math.min(Math.abs(t),1),this.a=Math.floor(255*this.gl[3]),this.update()}},red:{get:function(){return this.r},set:function(t){t=Math.floor(Math.abs(t)),this.r=Math.min(t,255),this.gl[0]=t/255,this.update(!0)}},green:{get:function(){return this.g},set:function(t){t=Math.floor(Math.abs(t)),this.g=Math.min(t,255),this.gl[1]=t/255,this.update(!0)}},blue:{get:function(){return this.b},set:function(t){t=Math.floor(Math.abs(t)),this.b=Math.min(t,255),this.gl[2]=t/255,this.update(!0)}},alpha:{get:function(){return this.a},set:function(t){t=Math.floor(Math.abs(t)),this.a=Math.min(t,255),this.gl[3]=t/255,this.update()}},h:{get:function(){return this._h},set:function(t){this._h=t,o(t,this._s,this._v,this)}},s:{get:function(){return this._s},set:function(t){this._s=t,o(this._h,t,this._v,this)}},v:{get:function(){return this._v},set:function(t){this._v=t,o(this._h,this._s,t,this)}}});t.exports=h},function(t,e){t.exports={CSV:0,TILED_JSON:1,ARRAY_2D:2,WELTMEISTER:3}},function(t,e){t.exports=function(t,e,i,n,s,r){var o;void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=1);var a=0,h=t.length;if(1===r)for(o=s;o=0;o--)t[o][e]+=i+a*n,a++;return t}},function(t,e,i){var n=i(16);t.exports=function(t){return t*n.DEG_TO_RAD}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.fillColor,r=n||e.fillAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.fillStyle="rgba("+o+","+a+","+h+","+r+")"}},function(t,e){var i={};t.exports=i,function(){i._nextId=0,i._seed=0,i._nowStartTime=+new Date,i.extend=function(t,e){var n,s;"boolean"==typeof e?(n=2,s=e):(n=1,s=!0);for(var r=n;r0;e--){var n=Math.floor(i.random()*(e+1)),s=t[e];t[e]=t[n],t[n]=s}return t},i.choose=function(t){return t[Math.floor(i.random()*t.length)]},i.isElement=function(t){return"undefined"!=typeof HTMLElement?t instanceof HTMLElement:!!(t&&t.nodeType&&t.nodeName)},i.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},i.isFunction=function(t){return"function"==typeof t},i.isPlainObject=function(t){return"object"==typeof t&&t.constructor===Object},i.isString=function(t){return"[object String]"===toString.call(t)},i.clamp=function(t,e,i){return ti?i:t},i.sign=function(t){return t<0?-1:1},i.now=function(){if("undefined"!=typeof window&&window.performance){if(window.performance.now)return window.performance.now();if(window.performance.webkitNow)return window.performance.webkitNow()}return new Date-i._nowStartTime},i.random=function(e,i){return e=void 0!==e?e:0,i=void 0!==i?i:1,e+t()*(i-e)};var t=function(){return i._seed=(9301*i._seed+49297)%233280,i._seed/233280};i.colorToNumber=function(t){return 3==(t=t.replace("#","")).length&&(t=t.charAt(0)+t.charAt(0)+t.charAt(1)+t.charAt(1)+t.charAt(2)+t.charAt(2)),parseInt(t,16)},i.logLevel=1,i.log=function(){console&&i.logLevel>0&&i.logLevel<=3&&console.log.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.info=function(){console&&i.logLevel>0&&i.logLevel<=2&&console.info.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.warn=function(){console&&i.logLevel>0&&i.logLevel<=3&&console.warn.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.nextId=function(){return i._nextId++},i.indexOf=function(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0;i=e&&t.y<=i&&t.y+t.height>=i}},function(t,e,i){t.exports={DESTROY:i(642),FADE_IN_COMPLETE:i(643),FADE_IN_START:i(644),FADE_OUT_COMPLETE:i(645),FADE_OUT_START:i(646),FLASH_COMPLETE:i(647),FLASH_START:i(648),PAN_COMPLETE:i(649),PAN_START:i(650),POST_RENDER:i(651),PRE_RENDER:i(652),SHAKE_COMPLETE:i(653),SHAKE_START:i(654),ZOOM_COMPLETE:i(655),ZOOM_START:i(656)}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.strokeColor,r=n||e.strokeAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.strokeStyle="rgba("+o+","+a+","+h+","+r+")",t.lineWidth=e.lineWidth}},function(t,e){t.exports={DYNAMIC_BODY:0,STATIC_BODY:1,GROUP:2,TILEMAPLAYER:3,FACING_NONE:10,FACING_UP:11,FACING_DOWN:12,FACING_LEFT:13,FACING_RIGHT:14}},function(t,e,i){var n=i(136),s=i(25);t.exports=function(t,e,i,r,o){for(var a=null,h=null,l=null,u=null,c=s(t,e,i,r,null,o),d=0;d0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}},function(t,e,i){var n=i(0),s=i(270),r=i(147),o=i(46),a=i(148),h=i(3),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=o.LINE,this.x1=t,this.y1=e,this.x2=i,this.y2=n},getPoint:function(t,e){return s(this,t,e)},getPoints:function(t,e,i){return r(this,t,e,i)},getRandomPoint:function(t){return a(this,t)},setTo:function(t,e,i,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x1=t,this.y1=e,this.x2=i,this.y2=n,this},getPointA:function(t){return void 0===t&&(t=new h),t.set(this.x1,this.y1),t},getPointB:function(t){return void 0===t&&(t=new h),t.set(this.x2,this.y2),t},left:{get:function(){return Math.min(this.x1,this.x2)},set:function(t){this.x1<=this.x2?this.x1=t:this.x2=t}},right:{get:function(){return Math.max(this.x1,this.x2)},set:function(t){this.x1>this.x2?this.x1=t:this.x2=t}},top:{get:function(){return Math.min(this.y1,this.y2)},set:function(t){this.y1<=this.y2?this.y1=t:this.y2=t}},bottom:{get:function(){return Math.max(this.y1,this.y2)},set:function(t){this.y1>this.y2?this.y1=t:this.y2=t}}});t.exports=l},function(t,e){t.exports=function(t){return Math.sqrt((t.x2-t.x1)*(t.x2-t.x1)+(t.y2-t.y1)*(t.y2-t.y1))}},function(t,e){t.exports=function(t,e,i){var n=i-e;return e+((t-e)%n+n)%n}},function(t,e,i){t.exports={COMPLETE:i(880),DECODED:i(881),DECODED_ALL:i(882),DESTROY:i(883),DETUNE:i(884),GLOBAL_DETUNE:i(885),GLOBAL_MUTE:i(886),GLOBAL_RATE:i(887),GLOBAL_VOLUME:i(888),LOOP:i(889),LOOPED:i(890),MUTE:i(891),PAUSE_ALL:i(892),PAUSE:i(893),PLAY:i(894),RATE:i(895),RESUME_ALL:i(896),RESUME:i(897),SEEK:i(898),STOP_ALL:i(899),STOP:i(900),UNLOCKED:i(901),VOLUME:i(902)}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(6),l=i(7),u=new n({Extends:r,initialize:function(t,e,i,n,o){var u="json";if(l(e)){var c=e;e=a(c,"key"),i=a(c,"url"),n=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"dataKey",o)}var d={type:"json",cache:t.cacheManager.json,extension:u,responseType:"text",key:e,url:i,xhrSettings:n,config:o};r.call(this,t,d),l(i)&&(this.data=o?h(i,o):i,this.state=s.FILE_POPULATED)},onProcess:function(){if(this.state!==s.FILE_POPULATED){this.state=s.FILE_PROCESSING;var t=JSON.parse(this.xhrLoader.responseText),e=this.config;this.data="string"==typeof e?h(t,e,t):t}this.onProcessComplete()}});o.register("json",function(t,e,i,n){if(Array.isArray(t))for(var s=0;s0&&r.rotateAbout(o.position,i,t.position,o.position)}},n.setVelocity=function(t,e){t.positionPrev.x=t.position.x-e.x,t.positionPrev.y=t.position.y-e.y,t.velocity.x=e.x,t.velocity.y=e.y,t.speed=r.magnitude(t.velocity)},n.setAngularVelocity=function(t,e){t.anglePrev=t.angle-e,t.angularVelocity=e,t.angularSpeed=Math.abs(t.angularVelocity)},n.translate=function(t,e){n.setPosition(t,r.add(t.position,e))},n.rotate=function(t,e,i){if(i){var s=Math.cos(e),r=Math.sin(e),o=t.position.x-i.x,a=t.position.y-i.y;n.setPosition(t,{x:i.x+(o*s-a*r),y:i.y+(o*r+a*s)}),n.setAngle(t,t.angle+e)}else n.setAngle(t,t.angle+e)},n.scale=function(t,e,i,r){var o=0,a=0;r=r||t.position;for(var u=0;u0&&(o+=c.area,a+=c.inertia),c.position.x=r.x+(c.position.x-r.x)*e,c.position.y=r.y+(c.position.y-r.y)*i,h.update(c.bounds,c.vertices,t.velocity)}t.parts.length>1&&(t.area=o,t.isStatic||(n.setMass(t,t.density*o),n.setInertia(t,a))),t.circleRadius&&(e===i?t.circleRadius*=e:t.circleRadius=null)},n.update=function(t,e,i,n){var o=Math.pow(e*i*t.timeScale,2),a=1-t.frictionAir*i*t.timeScale,u=t.position.x-t.positionPrev.x,c=t.position.y-t.positionPrev.y;t.velocity.x=u*a*n+t.force.x/t.mass*o,t.velocity.y=c*a*n+t.force.y/t.mass*o,t.positionPrev.x=t.position.x,t.positionPrev.y=t.position.y,t.position.x+=t.velocity.x,t.position.y+=t.velocity.y,t.angularVelocity=(t.angle-t.anglePrev)*a*n+t.torque/t.inertia*o,t.anglePrev=t.angle,t.angle+=t.angularVelocity,t.speed=r.magnitude(t.velocity),t.angularSpeed=Math.abs(t.angularVelocity);for(var d=0;d0&&(f.position.x+=t.velocity.x,f.position.y+=t.velocity.y),0!==t.angularVelocity&&(s.rotate(f.vertices,t.angularVelocity,t.position),l.rotate(f.axes,t.angularVelocity),d>0&&r.rotateAbout(f.position,t.angularVelocity,t.position,f.position)),h.update(f.bounds,f.vertices,t.velocity)}},n.applyForce=function(t,e,i){t.force.x+=i.x,t.force.y+=i.y;var n=e.x-t.position.x,s=e.y-t.position.y;t.torque+=n*i.y-s*i.x},n._totalProperties=function(t){for(var e={mass:0,area:0,inertia:0,centre:{x:0,y:0}},i=1===t.parts.length?0:1;i80*i){n=h=t[0],a=l=t[1];for(var T=i;Th&&(h=u),f>l&&(l=f);g=0!==(g=Math.max(h-n,l-a))?1/g:0}return o(y,x,i,n,a,g),x}function s(t,e,i,n,s){var r,o;if(s===A(t,e,i,n)>0)for(r=e;r=e;r-=n)o=b(r,t[r],t[r+1],o);return o&&y(o,o.next)&&(E(o),o=o.next),o}function r(t,e){if(!t)return t;e||(e=t);var i,n=t;do{if(i=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(E(n),(n=e=n.prev)===n.next)break;i=!0}}while(i||n!==e);return e}function o(t,e,i,n,s,c,d){if(t){!d&&c&&function(t,e,i,n){var s=t;do{null===s.z&&(s.z=f(s.x,s.y,e,i,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,n,s,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,n=i,a=0,e=0;e0||h>0&&n;)0!==a&&(0===h||!n||i.z<=n.z)?(s=i,i=i.nextZ,a--):(s=n,n=n.nextZ,h--),r?r.nextZ=s:t=s,s.prevZ=r,r=s;i=n}r.nextZ=null,l*=2}while(o>1)}(s)}(t,n,s,c);for(var p,g,v=t;t.prev!==t.next;)if(p=t.prev,g=t.next,c?h(t,n,s,c):a(t))e.push(p.i/i),e.push(t.i/i),e.push(g.i/i),E(t),t=g.next,v=g.next;else if((t=g)===v){d?1===d?o(t=l(t,e,i),e,i,n,s,c,2):2===d&&u(t,e,i,n,s,c):o(r(t),e,i,n,s,c,1);break}}}function a(t){var e=t.prev,i=t,n=t.next;if(m(e,i,n)>=0)return!1;for(var s=t.next.next;s!==t.prev;){if(g(e.x,e.y,i.x,i.y,n.x,n.y,s.x,s.y)&&m(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function h(t,e,i,n){var s=t.prev,r=t,o=t.next;if(m(s,r,o)>=0)return!1;for(var a=s.xr.x?s.x>o.x?s.x:o.x:r.x>o.x?r.x:o.x,u=s.y>r.y?s.y>o.y?s.y:o.y:r.y>o.y?r.y:o.y,c=f(a,h,e,i,n),d=f(l,u,e,i,n),p=t.prevZ,v=t.nextZ;p&&p.z>=c&&v&&v.z<=d;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;v&&v.z<=d;){if(v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function l(t,e,i){var n=t;do{var s=n.prev,r=n.next.next;!y(s,r)&&x(s,n,n.next,r)&&T(s,r)&&T(r,s)&&(e.push(s.i/i),e.push(n.i/i),e.push(r.i/i),E(n),E(n.next),n=t=r),n=n.next}while(n!==t);return n}function u(t,e,i,n,s,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&v(h,l)){var u=w(h,l);return h=r(h,h.next),u=r(u,u.next),o(h,e,i,n,s,a),void o(u,e,i,n,s,a)}l=l.next}h=h.next}while(h!==t)}function c(t,e){return t.x-e.x}function d(t,e){if(e=function(t,e){var i,n=e,s=t.x,r=t.y,o=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){var a=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=s&&a>o){if(o=a,a===s){if(r===n.y)return n;if(r===n.next.y)return n.next}i=n.x=n.x&&n.x>=u&&s!==n.x&&g(ri.x)&&T(n,t)&&(i=n,d=h),n=n.next;return i}(t,e)){var i=w(e,t);r(i,i.next)}}function f(t,e,i,n,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*s)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*s)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function p(t){var e=t,i=t;do{e.x=0&&(t-o)*(n-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(s-o)*(n-a)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&x(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&T(t,e)&&T(e,t)&&function(t,e){var i=t,n=!1,s=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&i.next.y!==i.y&&s<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,i,n){return!!(y(t,e)&&y(i,n)||y(t,n)&&y(i,e))||m(t,e,i)>0!=m(t,e,n)>0&&m(i,n,t)>0!=m(i,n,e)>0}function T(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function w(t,e){var i=new S(t.i,t.x,t.y),n=new S(e.i,e.x,e.y),s=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,n.next=i,i.prev=n,r.next=n,n.prev=r,n}function b(t,e,i,n){var s=new S(t,e,i);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function E(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function S(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,i,n){for(var s=0,r=e,o=i-n;r0&&(n+=t[s-1].length,i.holes.push(n))}return i}},function(t,e){t.exports=function(t){var e={};for(var i in t)Array.isArray(t[i])?e[i]=t[i].slice(0):e[i]=t[i];return e}},function(t,e){t.exports=function(t,e,i,n){var s=t.length;if(e<0||e>s||e>=i||i>s||e+i>s){if(n)throw new Error("Range Error: Values outside acceptable range");return!1}return!0}},function(t,e,i){var n=i(163),s=i(176);t.exports=function(t,e){var i=n.Power0;if("string"==typeof t)if(n.hasOwnProperty(t))i=n[t];else{var r="";t.indexOf(".")&&("in"===(r=t.substr(t.indexOf(".")+1)).toLowerCase()?r="easeIn":"out"===r.toLowerCase()?r="easeOut":"inout"===r.toLowerCase()&&(r="easeInOut")),t=s(t.substr(0,t.indexOf(".")+1)+r),n.hasOwnProperty(t)&&(i=n[t])}else"function"==typeof t?i=t:Array.isArray(t)&&t.length;if(!e)return i;var o=e.slice(0);return o.unshift(0),function(t){return o[0]=t,i.apply(this,o)}}},function(t,e,i){var n=i(9);t.exports=function(t,e,i,s,r){var o=t.strokeTint,a=n.getTintAppendFloatAlphaAndSwap(e.strokeColor,e.strokeAlpha*i);o.TL=a,o.TR=a,o.BL=a,o.BR=a;var h=e.pathData,l=h.length-1,u=e.lineWidth,c=u/2,d=h[0]-s,f=h[1]-r;e.closePath||(l-=2);for(var p=2;p=this.x2&&this.x1>=this.x3?this.x1-t:this.x2>=this.x1&&this.x2>=this.x3?this.x2-t:this.x3-t,this.x1-=e,this.x2-=e,this.x3-=e}},top:{get:function(){return Math.min(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1<=this.y2&&this.y1<=this.y3?this.y1-t:this.y2<=this.y1&&this.y2<=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}},bottom:{get:function(){return Math.max(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1>=this.y2&&this.y1>=this.y3?this.y1-t:this.y2>=this.y1&&this.y2>=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}}});t.exports=u},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=new n({Extends:r,initialize:function t(e,i,n,s,o){var l,u="png";if(h(i)){var c=i;i=a(c,"key"),n=a(c,"url"),l=a(c,"normalMap"),s=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"frameConfig")}Array.isArray(n)&&(l=n[1],n=n[0]);var d={type:"image",cache:e.textureManager,extension:u,responseType:"blob",key:i,url:n,xhrSettings:s,config:o};if(r.call(this,e,d),l){var f=new t(e,this.key,l,s,o);f.type="normalMap",this.setLink(f),e.addFile(f)}},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=new Image,this.data.crossOrigin=this.crossOrigin;var t=this;this.data.onload=function(){r.revokeObjectURL(t.data),t.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(t.data),t.onProcessError()},r.createObjectURL(this.data,this.xhrLoader.response,"image/png")},addToCache:function(){var t,e=this.linkFile;e&&e.state===s.FILE_COMPLETE?(t="image"===this.type?this.cache.addImage(this.key,this.data,e.data):this.cache.addImage(e.key,e.data,this.data),this.pendingDestroy(t),e.pendingDestroy(t)):e||(t=this.cache.addImage(this.key,this.data),this.pendingDestroy(t))}});o.register("image",function(t,e,i){if(Array.isArray(t))for(var n=0;nthis.right||e>this.bottom)},copy:function(t){return this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.visible=t.visible,this.setFlip(t.flipX,t.flipY),this.tint=t.tint,this.rotation=t.rotation,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext,this},getCollisionGroup:function(){return this.tileset?this.tileset.getTileCollisionGroup(this.index):null},getTileData:function(){return this.tileset?this.tileset.getTileData(this.index):null},getLeft:function(t){var e=this.tilemapLayer;return e?e.tileToWorldX(this.x,t):this.x*this.baseWidth},getRight:function(t){var e=this.tilemapLayer;return e?this.getLeft(t)+this.width*e.scaleX:this.getLeft(t)+this.width},getTop:function(t){var e=this.tilemapLayer;return e?e.tileToWorldY(this.y,t)-(this.height-this.baseHeight)*e.scaleY:this.y*this.baseHeight-(this.height-this.baseHeight)},getBottom:function(t){var e=this.tilemapLayer;return e?this.getTop(t)+this.height*e.scaleY:this.getTop(t)+this.height},getBounds:function(t,e){return void 0===e&&(e=new o),e.x=this.getLeft(),e.y=this.getTop(),e.width=this.getRight()-e.x,e.height=this.getBottom()-e.y,e},getCenterX:function(t){return(this.getLeft(t)+this.getRight(t))/2},getCenterY:function(t){return(this.getTop(t)+this.getBottom(t))/2},destroy:function(){this.collisionCallback=void 0,this.collisionCallbackContext=void 0,this.properties=void 0},intersects:function(t,e,i,n){return!(i<=this.pixelX||n<=this.pixelY||t>=this.right||e>=this.bottom)},isInteresting:function(t,e){return t&&e?this.canCollide||this.hasInterestingFace:t?this.collides:!!e&&this.hasInterestingFace},resetCollision:function(t){(void 0===t&&(t=!0),this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,t)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},resetFaces:function(){return this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this},setCollision:function(t,e,i,n,s){(void 0===e&&(e=t),void 0===i&&(i=t),void 0===n&&(n=t),void 0===s&&(s=!0),this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=n,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=n,s)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},setCollisionCallback:function(t,e){return null===t?(this.collisionCallback=void 0,this.collisionCallbackContext=void 0):(this.collisionCallback=t,this.collisionCallbackContext=e),this},setSize:function(t,e,i,n){return void 0!==t&&(this.width=t),void 0!==e&&(this.height=e),void 0!==i&&(this.baseWidth=i),void 0!==n&&(this.baseHeight=n),this.updatePixelXY(),this},updatePixelXY:function(){if(this.layer.orientation===n.ISOMETRIC)this.pixelX=(this.x-this.y)*this.baseWidth*.5,this.pixelY=(this.x+this.y)*this.baseHeight*.5;else if(this.layer.orientation===n.STAGGERED)this.pixelX=this.x*this.baseWidth+this.y%2*(this.baseWidth/2),this.pixelY=this.y*(this.baseHeight/2);else if(this.layer.orientation===n.HEXAGONAL){var t=this.layer.hexSideLength,e=(this.baseHeight-t)/2+t;this.pixelX=this.x*this.baseWidth+this.y%2*(this.baseWidth/2),this.pixelY=this.y*e}else this.layer.orientation===n.ORTHOGONAL&&(this.pixelX=this.x*this.baseWidth,this.pixelY=this.y*this.baseHeight);return this},canCollide:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}},collides:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}},hasInterestingFace:{get:function(){return this.faceTop||this.faceBottom||this.faceLeft||this.faceRight}},tileset:{get:function(){var t=this.layer.tilemapLayer;if(t){var e=t.gidMap[this.index];if(e)return e}return null}},tilemapLayer:{get:function(){return this.layer.tilemapLayer}},tilemap:{get:function(){var t=this.tilemapLayer;return t?t.tilemap:null}}});t.exports=a},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(958),a=new n({Extends:r,Mixins:[s.Alpha,s.BlendMode,s.Depth,s.Flip,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Size,s.TextureCrop,s.Tint,s.Transform,s.Visible,o],initialize:function(t,e,i,n,o){r.call(this,t,"Sprite"),this._crop=this.resetCropObject(),this.anims=new s.Animation(this),this.setTexture(n,o),this.setPosition(e,i),this.setSizeToFrame(),this.setOriginFromFrame(),this.initPipeline()},preUpdate:function(t,e){this.anims.update(t,e)},play:function(t,e,i){return this.anims.play(t,e,i),this},toJSON:function(){return s.ToJSON(this)},preDestroy:function(){this.anims.destroy(),this.anims=void 0}});t.exports=a},function(t,e){t.exports=function(t){return t.x-t.width*t.originX+.5*t.width}},function(t,e){t.exports=function(t,e){var i=t.width*t.originX;return t.x=e+i-.5*t.width,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY+.5*t.height}},function(t,e){t.exports=function(t,e){var i=t.height*t.originY;return t.y=e+i-.5*t.height,t}},function(t,e){t.exports=function(t,e){if(!(e>=t.length)){for(var i=t.length-1,n=t[e],s=e;si&&(e=i/2);var n=Math.max(1,Math.round(i/e));return s(this.getSpacedPoints(n),t)},getDistancePoints:function(t){var e=this.getLength(),i=Math.max(1,e/t);return this.getSpacedPoints(i)},getEndPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(1,t)},getLength:function(){var t=this.getLengths();return t[t.length-1]},getLengths:function(t){if(void 0===t&&(t=this.arcLengthDivisions),this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,i=[],n=this.getPoint(0,this._tmpVec2A),s=0;i.push(0);for(var r=1;r<=t;r++)s+=(e=this.getPoint(r/t,this._tmpVec2B)).distance(n),i.push(s),n.copy(e);return this.cacheArcLengths=i,i},getPointAt:function(t,e){var i=this.getUtoTmapping(t);return this.getPoint(i,e)},getPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++)i.push(this.getPoint(n/t));return i},getRandomPoint:function(t){return void 0===t&&(t=new o),this.getPoint(Math.random(),t)},getSpacedPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++){var s=this.getUtoTmapping(n/t,null,t);i.push(this.getPoint(s))}return i},getStartPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(0,t)},getTangent:function(t,e){void 0===e&&(e=new o);var i=t-1e-4,n=t+1e-4;return i<0&&(i=0),n>1&&(n=1),this.getPoint(i,this._tmpVec2A),this.getPoint(n,e),e.subtract(this._tmpVec2A).normalize()},getTangentAt:function(t,e){var i=this.getUtoTmapping(t);return this.getTangent(i,e)},getTFromDistance:function(t,e){return t<=0?0:this.getUtoTmapping(0,t,e)},getUtoTmapping:function(t,e,i){var n,s=this.getLengths(i),r=0,o=s.length;n=e?Math.min(e,s[o-1]):t*s[o-1];for(var a,h=0,l=o-1;h<=l;)if((a=s[r=Math.floor(h+(l-h)/2)]-n)<0)h=r+1;else{if(!(a>0)){l=r;break}l=r-1}if(s[r=l]===n)return r/(o-1);var u=s[r];return(r+(n-u)/(s[r+1]-u))/(o-1)},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths()}});t.exports=a},function(t,e,i){t.exports={ADD:i(859),COMPLETE:i(860),FILE_COMPLETE:i(861),FILE_KEY_COMPLETE:i(862),FILE_LOAD_ERROR:i(863),FILE_LOAD:i(864),FILE_PROGRESS:i(865),POST_PROCESS:i(866),PROGRESS:i(867),START:i(868)}},function(t,e){t.exports=function(t,e,i){var n=t.x3-t.x1,s=t.y3-t.y1,r=t.x2-t.x1,o=t.y2-t.y1,a=e-t.x1,h=i-t.y1,l=n*n+s*s,u=n*r+s*o,c=n*a+s*h,d=r*r+o*o,f=r*a+o*h,p=l*d-u*u,g=0===p?0:1/p,v=(d*c-u*f)*g,m=(l*f-u*c)*g;return v>=0&&m>=0&&v+m<1}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.x1,r=t.y1,o=t.x2,a=t.y2,h=e.x1,l=e.y1,u=e.x2,c=e.y2,d=(u-h)*(r-l)-(c-l)*(s-h),f=(o-s)*(r-l)-(a-r)*(s-h),p=(c-l)*(o-s)-(u-h)*(a-r);if(0===p)return!1;var g=d/p,v=f/p;return g>=0&&g<=1&&v>=0&&v<=1&&(i.x=s+g*(o-s),i.y=r+g*(a-r),!0)}},function(t,e){t.exports=function(t){return Math.atan2(t.y2-t.y1,t.x2-t.x1)}},function(t,e,i){var n={};t.exports=n;var s=i(97),r=i(37);n.create=function(t,e){for(var i=[],n=0;n0)return!1}return!0},n.scale=function(t,e,i,r){if(1===e&&1===i)return t;var o,a;r=r||n.centre(t);for(var h=0;h=0?h-1:t.length-1],u=t[h],c=t[(h+1)%t.length],d=e[h0&&(r|=2),3===r)return!1;return 0!==r||null},n.hull=function(t){var e,i,n=[],r=[];for((t=t.slice(0)).sort(function(t,e){var i=t.x-e.x;return 0!==i?i:t.y-e.y}),i=0;i=2&&s.cross3(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}for(i=t.length-1;i>=0;i-=1){for(e=t[i];n.length>=2&&s.cross3(n[n.length-2],n[n.length-1],e)<=0;)n.pop();n.push(e)}return n.pop(),r.pop(),n.concat(r)}},function(t,e,i){var n=i(23);t.exports=function(t,e,i){return(i-e)*(t=n(t,0,1))}},function(t,e){t.exports=function(t,e,i){return t&&t.hasOwnProperty(e)?t[e]:i}},function(t,e){t.exports={CREATED:0,INIT:1,DELAY:2,OFFSET_DELAY:3,PENDING_RENDER:4,PLAYING_FORWARD:5,PLAYING_BACKWARD:6,HOLD_DELAY:7,REPEAT_DELAY:8,COMPLETE:9,PENDING_ADD:20,PAUSED:21,LOOP_DELAY:22,ACTIVE:23,COMPLETE_DELAY:24,PENDING_REMOVE:25,REMOVED:26}},function(t,e,i){t.exports={DESTROY:i(577),VIDEO_COMPLETE:i(578),VIDEO_CREATED:i(579),VIDEO_ERROR:i(580),VIDEO_LOOP:i(581),VIDEO_PLAY:i(582),VIDEO_SEEKED:i(583),VIDEO_SEEKING:i(584),VIDEO_STOP:i(585),VIDEO_TIMEOUT:i(586),VIDEO_UNLOCKED:i(587)}},function(t,e,i){var n=i(0),s=i(12),r=i(35),o=i(11),a=i(48),h=i(13),l=i(30),u=i(158),c=i(3),d=new n({Extends:o,Mixins:[s.Alpha,s.Visible],initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),o.call(this),this.scene,this.sceneManager,this.scaleManager,this.cameraManager,this.id=0,this.name="",this.resolution=1,this.roundPixels=!1,this.useBounds=!1,this.worldView=new h,this.dirty=!0,this._x=t,this._y=e,this._cx=0,this._cy=0,this._cw=0,this._ch=0,this._width=i,this._height=n,this._bounds=new h,this._scrollX=0,this._scrollY=0,this._zoom=1,this._rotation=0,this.matrix=new l,this.transparent=!0,this.backgroundColor=u("rgba(0,0,0,0)"),this.disableCull=!1,this.culledObjects=[],this.midPoint=new c(i/2,n/2),this.originX=.5,this.originY=.5,this._customViewport=!1,this.mask=null,this._maskCamera=null},setOrigin:function(t,e){return void 0===t&&(t=.5),void 0===e&&(e=t),this.originX=t,this.originY=e,this},getScroll:function(t,e,i){void 0===i&&(i=new c);var n=.5*this.width,s=.5*this.height;return i.x=t-n,i.y=e-s,this.useBounds&&(i.x=this.clampX(i.x),i.y=this.clampY(i.y)),i},centerOnX:function(t){var e=.5*this.width;return this.midPoint.x=t,this.scrollX=t-e,this.useBounds&&(this.scrollX=this.clampX(this.scrollX)),this},centerOnY:function(t){var e=.5*this.height;return this.midPoint.y=t,this.scrollY=t-e,this.useBounds&&(this.scrollY=this.clampY(this.scrollY)),this},centerOn:function(t,e){return this.centerOnX(t),this.centerOnY(e),this},centerToBounds:function(){if(this.useBounds){var t=this._bounds,e=.5*this.width,i=.5*this.height;this.midPoint.set(t.centerX,t.centerY),this.scrollX=t.centerX-e,this.scrollY=t.centerY-i}return this},centerToSize:function(){return this.scrollX=.5*this.width,this.scrollY=.5*this.height,this},cull:function(t){if(this.disableCull)return t;var e=this.matrix.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(!o)return t;var a=e[4],h=e[5],l=this.scrollX,u=this.scrollY,c=this.width,d=this.height,f=this.culledObjects,p=t.length;o=1/o,f.length=0;for(var g=0;gC&&wA&&b<_&&f.push(v)}else f.push(v)}return f},getWorldPoint:function(t,e,i){void 0===i&&(i=new c);var n=this.matrix.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5],u=s*a-r*o;if(!u)return i.x=t,i.y=e,i;var d=a*(u=1/u),f=-r*u,p=-o*u,g=s*u,v=(o*l-a*h)*u,m=(r*h-s*l)*u,y=Math.cos(this.rotation),x=Math.sin(this.rotation),T=this.zoom,w=this.resolution,b=this.scrollX,E=this.scrollY,S=t+(b*y-E*x)*T,A=e+(b*x+E*y)*T;return i.x=(S*d+A*p)*w+v,i.y=(S*f+A*g)*w+m,i},ignore:function(t){var e=this.id;Array.isArray(t)||(t=[t]);for(var i=0;is&&(t=s),t},clampY:function(t){var e=this._bounds,i=this.displayHeight,n=e.y+(i-this.height)/2,s=Math.max(n,n+e.height-i);return ts&&(t=s),t},removeBounds:function(){return this.useBounds=!1,this.dirty=!0,this._bounds.setEmpty(),this},setAngle:function(t){return void 0===t&&(t=0),this.rotation=r(t),this},setBackgroundColor:function(t){return void 0===t&&(t="rgba(0,0,0,0)"),this.backgroundColor=u(t),this.transparent=0===this.backgroundColor.alpha,this},setBounds:function(t,e,i,n,s){return void 0===s&&(s=!1),this._bounds.setTo(t,e,i,n),this.dirty=!0,this.useBounds=!0,s?this.centerToBounds():(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},getBounds:function(t){void 0===t&&(t=new h);var e=this._bounds;return t.setTo(e.x,e.y,e.width,e.height),t},setName:function(t){return void 0===t&&(t=""),this.name=t,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setRotation:function(t){return void 0===t&&(t=0),this.rotation=t,this},setRoundPixels:function(t){return this.roundPixels=t,this},setScene:function(t){this.scene&&this._customViewport&&this.sceneManager.customViewports--,this.scene=t;var e=t.sys;this.sceneManager=e.game.scene,this.scaleManager=e.scale,this.cameraManager=e.cameras;var i=this.scaleManager.resolution;return this.resolution=i,this._cx=this._x*i,this._cy=this._y*i,this._cw=this._width*i,this._ch=this._height*i,this.updateSystem(),this},setScroll:function(t,e){return void 0===e&&(e=t),this.scrollX=t,this.scrollY=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},setViewport:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setZoom:function(t){return void 0===t&&(t=1),0===t&&(t=.001),this.zoom=t,this},setMask:function(t,e){return void 0===e&&(e=!0),this.mask=t,this._maskCamera=e?this.cameraManager.default:this,this},clearMask:function(t){return void 0===t&&(t=!1),t&&this.mask&&this.mask.destroy(),this.mask=null,this},toJSON:function(){var t={name:this.name,x:this.x,y:this.y,width:this.width,height:this.height,zoom:this.zoom,rotation:this.rotation,roundPixels:this.roundPixels,scrollX:this.scrollX,scrollY:this.scrollY,backgroundColor:this.backgroundColor.rgba};return this.useBounds&&(t.bounds={x:this._bounds.x,y:this._bounds.y,width:this._bounds.width,height:this._bounds.height}),t},update:function(){},updateSystem:function(){if(this.scaleManager){var t=0!==this._x||0!==this._y||this.scaleManager.width!==this._width||this.scaleManager.height!==this._height,e=this.sceneManager;t&&!this._customViewport?e.customViewports++:!t&&this._customViewport&&e.customViewports--,this.dirty=!0,this._customViewport=t}},destroy:function(){this.emit(a.DESTROY,this),this.removeAllListeners(),this.matrix.destroy(),this.culledObjects=[],this._customViewport&&this.sceneManager.customViewports--,this._bounds=null,this.scene=null,this.scaleManager=null,this.sceneManager=null,this.cameraManager=null},x:{get:function(){return this._x},set:function(t){this._x=t,this._cx=t*this.resolution,this.updateSystem()}},y:{get:function(){return this._y},set:function(t){this._y=t,this._cy=t*this.resolution,this.updateSystem()}},width:{get:function(){return this._width},set:function(t){this._width=t,this._cw=t*this.resolution,this.updateSystem()}},height:{get:function(){return this._height},set:function(t){this._height=t,this._ch=t*this.resolution,this.updateSystem()}},scrollX:{get:function(){return this._scrollX},set:function(t){this._scrollX=t,this.dirty=!0}},scrollY:{get:function(){return this._scrollY},set:function(t){this._scrollY=t,this.dirty=!0}},zoom:{get:function(){return this._zoom},set:function(t){this._zoom=t,this.dirty=!0}},rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this.dirty=!0}},centerX:{get:function(){return this.x+.5*this.width}},centerY:{get:function(){return this.y+.5*this.height}},displayWidth:{get:function(){return this.width/this.zoom}},displayHeight:{get:function(){return this.height/this.zoom}}});t.exports=d},function(t,e,i){t.exports={ENTER_FULLSCREEN:i(695),FULLSCREEN_FAILED:i(696),FULLSCREEN_UNSUPPORTED:i(697),LEAVE_FULLSCREEN:i(698),ORIENTATION_CHANGE:i(699),RESIZE:i(700)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=i(0),s=i(23),r=i(18),o=new n({initialize:function(t,e,i,n,s,r,o){this.texture=t,this.name=e,this.source=t.source[i],this.sourceIndex=i,this.glTexture=this.source.glTexture,this.cutX,this.cutY,this.cutWidth,this.cutHeight,this.x=0,this.y=0,this.width,this.height,this.halfWidth,this.halfHeight,this.centerX,this.centerY,this.pivotX=0,this.pivotY=0,this.customPivot=!1,this.rotated=!1,this.autoRound=-1,this.customData={},this.u0=0,this.v0=0,this.u1=0,this.v1=0,this.data={cut:{x:0,y:0,w:0,h:0,r:0,b:0},trim:!1,sourceSize:{w:0,h:0},spriteSourceSize:{x:0,y:0,w:0,h:0,r:0,b:0},radius:0,drawImage:{x:0,y:0,width:0,height:0}},this.setSize(r,o,n,s)},setSize:function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this.cutX=i,this.cutY=n,this.cutWidth=t,this.cutHeight=e,this.width=t,this.height=e,this.halfWidth=Math.floor(.5*t),this.halfHeight=Math.floor(.5*e),this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2);var s=this.data,r=s.cut;r.x=i,r.y=n,r.w=t,r.h=e,r.r=i+t,r.b=n+e,s.sourceSize.w=t,s.sourceSize.h=e,s.spriteSourceSize.w=t,s.spriteSourceSize.h=e,s.radius=.5*Math.sqrt(t*t+e*e);var o=s.drawImage;return o.x=i,o.y=n,o.width=t,o.height=e,this.updateUVs()},setTrim:function(t,e,i,n,s,r){var o=this.data,a=o.spriteSourceSize;return o.trim=!0,o.sourceSize.w=t,o.sourceSize.h=e,a.x=i,a.y=n,a.w=s,a.h=r,a.r=i+s,a.b=n+r,this.x=i,this.y=n,this.width=s,this.height=r,this.halfWidth=.5*s,this.halfHeight=.5*r,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.updateUVs()},setCropUVs:function(t,e,i,n,r,o,a){var h=this.cutX,l=this.cutY,u=this.cutWidth,c=this.cutHeight,d=this.realWidth,f=this.realHeight,p=h+(e=s(e,0,d)),g=l+(i=s(i,0,f)),v=n=s(n,0,d-e),m=r=s(r,0,f-i),y=this.data;if(y.trim){var x=y.spriteSourceSize,T=e+(n=s(n,0,u-e)),w=i+(r=s(r,0,c-i));if(!(x.rT||x.y>w)){var b=Math.max(x.x,e),E=Math.max(x.y,i),S=Math.min(x.r,T)-b,A=Math.min(x.b,w)-E;v=S,m=A,p=o?h+(u-(b-x.x)-S):h+(b-x.x),g=a?l+(c-(E-x.y)-A):l+(E-x.y),e=b,i=E,n=S,r=A}else p=0,g=0,v=0,m=0}else o&&(p=h+(u-e-n)),a&&(g=l+(c-i-r));var _=this.source.width,C=this.source.height;return t.u0=Math.max(0,p/_),t.v0=Math.max(0,g/C),t.u1=Math.min(1,(p+v)/_),t.v1=Math.min(1,(g+m)/C),t.x=e,t.y=i,t.cx=p,t.cy=g,t.cw=v,t.ch=m,t.width=n,t.height=r,t.flipX=o,t.flipY=a,t},updateCropUVs:function(t,e,i){return this.setCropUVs(t,t.x,t.y,t.width,t.height,e,i)},updateUVs:function(){var t=this.cutX,e=this.cutY,i=this.cutWidth,n=this.cutHeight,s=this.data.drawImage;s.width=i,s.height=n;var r=this.source.width,o=this.source.height;return this.u0=t/r,this.v0=e/o,this.u1=(t+i)/r,this.v1=(e+n)/o,this},updateUVsInverted:function(){var t=this.source.width,e=this.source.height;return this.u0=(this.cutX+this.cutHeight)/t,this.v0=this.cutY/e,this.u1=this.cutX/t,this.v1=(this.cutY+this.cutWidth)/e,this},clone:function(){var t=new o(this.texture,this.name,this.sourceIndex);return t.cutX=this.cutX,t.cutY=this.cutY,t.cutWidth=this.cutWidth,t.cutHeight=this.cutHeight,t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t.halfWidth=this.halfWidth,t.halfHeight=this.halfHeight,t.centerX=this.centerX,t.centerY=this.centerY,t.rotated=this.rotated,t.data=r(!0,t.data,this.data),t.updateUVs(),t},destroy:function(){this.source=null,this.texture=null,this.glTexture=null,this.customData=null,this.data=null},realWidth:{get:function(){return this.data.sourceSize.w}},realHeight:{get:function(){return this.data.sourceSize.h}},radius:{get:function(){return this.data.radius}},trimmed:{get:function(){return this.data.trim}},canvasData:{get:function(){return this.data.drawImage}}});t.exports=o},function(t,e,i){var n=i(0),s=i(94),r=i(391),o=i(392),a=i(46),h=i(151),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=a.ELLIPSE,this.x=t,this.y=e,this.width=i,this.height=n},contains:function(t,e){return s(this,t,e)},getPoint:function(t,e){return r(this,t,e)},getPoints:function(t,e,i){return o(this,t,e,i)},getRandomPoint:function(t){return h(this,t)},setTo:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setEmpty:function(){return this.width=0,this.height=0,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},isEmpty:function(){return this.width<=0||this.height<=0},getMinorRadius:function(){return Math.min(this.width,this.height)/2},getMajorRadius:function(){return Math.max(this.width,this.height)/2},left:{get:function(){return this.x-this.width/2},set:function(t){this.x=t+this.width/2}},right:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},top:{get:function(){return this.y-this.height/2},set:function(t){this.y=t+this.height/2}},bottom:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=l},function(t,e){t.exports=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var n=(e-t.x)/t.width,s=(i-t.y)/t.height;return(n*=n)+(s*=s)<.25}},function(t,e,i){var n=i(236),s=i(0),r=i(88),o=i(2),a=i(6),h=i(7),l=i(385),u=i(127),c=i(73),d=new s({initialize:function(t,e,i){i?e&&!Array.isArray(e)&&(e=[e]):Array.isArray(e)?h(e[0])&&(i=e,e=null):h(e)&&(i=e,e=null),this.scene=t,this.children=new u(e),this.isParent=!0,this.type="Group",this.classType=o(i,"classType",c),this.name=o(i,"name",""),this.active=o(i,"active",!0),this.maxSize=o(i,"maxSize",-1),this.defaultKey=o(i,"defaultKey",null),this.defaultFrame=o(i,"defaultFrame",null),this.runChildUpdate=o(i,"runChildUpdate",!1),this.createCallback=o(i,"createCallback",null),this.removeCallback=o(i,"removeCallback",null),this.createMultipleCallback=o(i,"createMultipleCallback",null),this.internalCreateCallback=o(i,"internalCreateCallback",null),this.internalRemoveCallback=o(i,"internalRemoveCallback",null),i&&this.createMultiple(i)},create:function(t,e,i,n,s,r){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.defaultKey),void 0===n&&(n=this.defaultFrame),void 0===s&&(s=!0),void 0===r&&(r=!0),this.isFull())return null;var o=new this.classType(this.scene,t,e,i,n);return this.scene.sys.displayList.add(o),o.preUpdate&&this.scene.sys.updateList.add(o),o.visible=s,o.setActive(r),this.add(o),o},createMultiple:function(t){if(this.isFull())return[];Array.isArray(t)||(t=[t]);var e=[];if(t[0].key)for(var i=0;i=0;u--)if((l=d[u]).active===i){if(++c===e)break}else l=null;return l?("number"==typeof s&&(l.x=s),"number"==typeof r&&(l.y=r),l):n?this.create(s,r,o,a,h):null},get:function(t,e,i,n,s){return this.getFirst(!1,!0,t,e,i,n,s)},getFirstAlive:function(t,e,i,n,s,r){return this.getFirst(!0,t,e,i,n,s,r)},getFirstDead:function(t,e,i,n,s,r){return this.getFirst(!1,t,e,i,n,s,r)},playAnimation:function(t,e){return n.PlayAnimation(this.children.entries,t,e),this},isFull:function(){return-1!==this.maxSize&&this.children.size>=this.maxSize},countActive:function(t){void 0===t&&(t=!0);for(var e=0,i=0;it.max.x&&(t.max.x=s.x),s.xt.max.y&&(t.max.y=s.y),s.y0?t.max.x+=i.x:t.min.x+=i.x,i.y>0?t.max.y+=i.y:t.min.y+=i.y)},i.contains=function(t,e){return e.x>=t.min.x&&e.x<=t.max.x&&e.y>=t.min.y&&e.y<=t.max.y},i.overlaps=function(t,e){return t.min.x<=e.max.x&&t.max.x>=e.min.x&&t.max.y>=e.min.y&&t.min.y<=e.max.y},i.translate=function(t,e){t.min.x+=e.x,t.max.x+=e.x,t.min.y+=e.y,t.max.y+=e.y},i.shift=function(t,e){var i=t.max.x-t.min.x,n=t.max.y-t.min.y;t.min.x=e.x,t.max.x=e.x+i,t.min.y=e.y,t.max.y=e.y+n}},function(t,e){t.exports=function(t,e,i){return t>=0&&t=0&&e0&&s.area(T)1?(d=o.create(r.extend({parts:f.slice(0)},a)),o.setPosition(d,{x:t,y:e}),d):f[0]},n.flagCoincidentParts=function(t,e){void 0===e&&(e=5);for(var i=0;i0;e--){var i=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[i],t[i]=n}return t}},function(t,e){t.exports=function(t,e,i){return(e-t)*i+t}},function(t,e,i){(function(e){var i={android:!1,chromeOS:!1,cordova:!1,crosswalk:!1,desktop:!1,ejecta:!1,electron:!1,iOS:!1,iOSVersion:0,iPad:!1,iPhone:!1,kindle:!1,linux:!1,macOS:!1,node:!1,nodeWebkit:!1,pixelRatio:1,webApp:!1,windows:!1,windowsPhone:!1};t.exports=function(){var t=navigator.userAgent;/Windows/.test(t)?i.windows=!0:/Mac OS/.test(t)&&!/like Mac OS/.test(t)?i.macOS=!0:/Android/.test(t)?i.android=!0:/Linux/.test(t)?i.linux=!0:/iP[ao]d|iPhone/i.test(t)?(i.iOS=!0,navigator.appVersion.match(/OS (\d+)/),i.iOSVersion=parseInt(RegExp.$1,10),i.iPhone=-1!==t.toLowerCase().indexOf("iphone"),i.iPad=-1!==t.toLowerCase().indexOf("ipad")):/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?i.kindle=!0:/CrOS/.test(t)&&(i.chromeOS=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(i.android=!1,i.iOS=!1,i.macOS=!1,i.windows=!0,i.windowsPhone=!0);var n=/Silk/.test(t);return(i.windows||i.macOS||i.linux&&!n||i.chromeOS)&&(i.desktop=!0),(i.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(i.desktop=!1),navigator.standalone&&(i.webApp=!0),void 0!==window.cordova&&(i.cordova=!0),void 0!==e&&e.versions&&e.versions.node&&(i.node=!0),i.node&&"object"==typeof e.versions&&(i.nodeWebkit=!!e.versions["node-webkit"],i.electron=!!e.versions.electron),void 0!==window.ejecta&&(i.ejecta=!0),/Crosswalk/.test(t)&&(i.crosswalk=!0),i.pixelRatio=window.devicePixelRatio||1,i}()}).call(this,i(721))},function(t,e,i){var n,s=i(112),r={chrome:!1,chromeVersion:0,edge:!1,firefox:!1,firefoxVersion:0,ie:!1,ieVersion:0,mobileSafari:!1,opera:!1,safari:!1,safariVersion:0,silk:!1,trident:!1,tridentVersion:0};t.exports=(n=navigator.userAgent,/Edge\/\d+/.test(n)?r.edge=!0:/Chrome\/(\d+)/.test(n)&&!s.windowsPhone?(r.chrome=!0,r.chromeVersion=parseInt(RegExp.$1,10)):/Firefox\D+(\d+)/.test(n)?(r.firefox=!0,r.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(n)&&s.iOS?r.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(n)?(r.ie=!0,r.ieVersion=parseInt(RegExp.$1,10)):/Opera/.test(n)?r.opera=!0:/Safari/.test(n)&&!s.windowsPhone?r.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(n)&&(r.ie=!0,r.trident=!0,r.tridentVersion=parseInt(RegExp.$1,10),r.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(n)&&(r.silk=!0),r)},function(t,e){t.exports=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)}},function(t,e,i){t.exports={ADD:i(771),ERROR:i(772),LOAD:i(773),READY:i(774),REMOVE:i(775)}},function(t,e){t.exports=function(t,e){var i;if(e)"string"==typeof e?i=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(i=e);else if(t.parentElement)return t;return i||(i=document.body),i.appendChild(t),t}},function(t,e,i){var n=i(78);t.exports=function(t,e,i,s){var r;if(void 0===s&&(s=t),!Array.isArray(e))return-1!==(r=t.indexOf(e))?(n(t,r),i&&i.call(s,e),e):null;for(var o=e.length-1;o>=0;){var a=e[o];-1!==(r=t.indexOf(a))?(n(t,r),i&&i.call(s,a)):e.pop(),o--}return e}},function(t,e){t.exports={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:42,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,NUMPAD_ZERO:96,NUMPAD_ONE:97,NUMPAD_TWO:98,NUMPAD_THREE:99,NUMPAD_FOUR:100,NUMPAD_FIVE:101,NUMPAD_SIX:102,NUMPAD_SEVEN:103,NUMPAD_EIGHT:104,NUMPAD_NINE:105,NUMPAD_ADD:107,NUMPAD_SUBTRACT:109,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,SEMICOLON:186,PLUS:187,COMMA:188,MINUS:189,PERIOD:190,FORWARD_SLASH:191,BACK_SLASH:220,QUOTES:222,BACKTICK:192,OPEN_BRACKET:219,CLOSED_BRACKET:221,SEMICOLON_FIREFOX:59,COLON:58,COMMA_FIREFOX_WINDOWS:60,COMMA_FIREFOX:62,BRACKET_RIGHT_FIREFOX:174,BRACKET_LEFT_FIREFOX:175}},function(t,e){t.exports={PENDING:0,INIT:1,START:2,LOADING:3,CREATING:4,RUNNING:5,PAUSED:6,SLEEPING:7,SHUTDOWN:8,DESTROYED:9}},function(t,e,i){var n=i(65);t.exports=function(t,e){var i=n(t);for(var s in e)i.hasOwnProperty(s)||(i[s]=e[s]);return i}},function(t,e,i){var n=i(0),s=i(65),r=i(11),o=i(59),a=i(19),h=i(1),l=new n({Extends:r,initialize:function(t){r.call(this),this.game=t,this.jsonCache=t.cache.json,this.sounds=[],this.mute=!1,this.volume=1,this.pauseOnBlur=!0,this._rate=1,this._detune=0,this.locked=this.locked||!1,this.unlocked=!1,t.events.on(a.BLUR,function(){this.pauseOnBlur&&this.onBlur()},this),t.events.on(a.FOCUS,function(){this.pauseOnBlur&&this.onFocus()},this),t.events.on(a.PRE_STEP,this.update,this),t.events.once(a.DESTROY,this.destroy,this)},add:h,addAudioSprite:function(t,e){void 0===e&&(e={});var i=this.add(t,e);for(var n in i.spritemap=this.jsonCache.get(t).spritemap,i.spritemap)if(i.spritemap.hasOwnProperty(n)){var r=s(e),o=i.spritemap[n];r.loop=!!o.hasOwnProperty("loop")&&o.loop,i.addMarker({name:n,start:o.start,duration:o.end-o.start,config:r})}return i},play:function(t,e){var i=this.add(t);return i.once(o.COMPLETE,i.destroy,i),e?e.name?(i.addMarker(e),i.play(e.name)):i.play(e):i.play()},playAudioSprite:function(t,e,i){var n=this.addAudioSprite(t);return n.once(o.COMPLETE,n.destroy,n),n.play(e,i)},remove:function(t){var e=this.sounds.indexOf(t);return-1!==e&&(t.destroy(),this.sounds.splice(e,1),!0)},removeByKey:function(t){for(var e=0,i=this.sounds.length-1;i>=0;i--){var n=this.sounds[i];n.key===t&&(n.destroy(),this.sounds.splice(i,1),e++)}return e},pauseAll:function(){this.forEachActiveSound(function(t){t.pause()}),this.emit(o.PAUSE_ALL,this)},resumeAll:function(){this.forEachActiveSound(function(t){t.resume()}),this.emit(o.RESUME_ALL,this)},stopAll:function(){this.forEachActiveSound(function(t){t.stop()}),this.emit(o.STOP_ALL,this)},unlock:h,onBlur:h,onFocus:h,update:function(t,e){this.unlocked&&(this.unlocked=!1,this.locked=!1,this.emit(o.UNLOCKED,this));for(var i=this.sounds.length-1;i>=0;i--)this.sounds[i].pendingRemove&&this.sounds.splice(i,1);this.sounds.forEach(function(i){i.update(t,e)})},destroy:function(){this.removeAllListeners(),this.forEachActiveSound(function(t){t.destroy()}),this.sounds.length=0,this.sounds=null,this.game=null},forEachActiveSound:function(t,e){var i=this;this.sounds.forEach(function(n,s){n&&!n.pendingRemove&&t.call(e||i,n,s,i.sounds)})},setRate:function(t){return this.rate=t,this},rate:{get:function(){return this._rate},set:function(t){this._rate=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_RATE,this,t)}},setDetune:function(t){return this.detune=t,this},detune:{get:function(){return this._detune},set:function(t){this._detune=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_DETUNE,this,t)}}});t.exports=l},function(t,e,i){var n=i(0),s=i(11),r=i(59),o=i(18),a=i(1),h=new n({Extends:s,initialize:function(t,e,i){s.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=this.duration||0,this.totalDuration=this.totalDuration||0,this.config={mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},this.currentConfig=this.config,this.config=o(this.config,i),this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(console.error("addMarker "+t.name+" already exists in Sound"),!1):(t=o(!0,{name:"",start:0,duration:this.totalDuration-(t.start||0),config:{mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0}},t),this.markers[t.name]=t,!0))},updateMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(this.markers[t.name]=o(!0,this.markers[t.name],t),!0):(console.warn("Audio Marker: "+t.name+" missing in Sound: "+this.key),!1))},removeMarker:function(t){var e=this.markers[t];return e?(this.markers[t]=null,e):null},play:function(t,e){if(void 0===t&&(t=""),"object"==typeof t&&(e=t,t=""),"string"!=typeof t)return!1;if(t){if(!this.markers[t])return console.warn("Marker: "+t+" missing in Sound: "+this.key),!1;this.currentMarker=this.markers[t],this.currentConfig=this.currentMarker.config,this.duration=this.currentMarker.duration}else this.currentMarker=null,this.currentConfig=this.config,this.duration=this.totalDuration;return this.resetConfig(),this.currentConfig=o(this.currentConfig,e),this.isPlaying=!0,this.isPaused=!1,!0},pause:function(){return!(this.isPaused||!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!0,!0)},resume:function(){return!(!this.isPaused||this.isPlaying)&&(this.isPlaying=!0,this.isPaused=!1,!0)},stop:function(){return!(!this.isPaused&&!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!1,this.resetConfig(),!0)},applyConfig:function(){this.mute=this.currentConfig.mute,this.volume=this.currentConfig.volume,this.rate=this.currentConfig.rate,this.detune=this.currentConfig.detune,this.loop=this.currentConfig.loop},resetConfig:function(){this.currentConfig.seek=0,this.currentConfig.delay=0},update:a,calculateRate:function(){var t=this.currentConfig.detune+this.manager.detune,e=Math.pow(1.0005777895065548,t);this.totalRate=this.currentConfig.rate*this.manager.rate*e},destroy:function(){this.pendingRemove||(this.emit(r.DESTROY,this),this.pendingRemove=!0,this.manager=null,this.key="",this.removeAllListeners(),this.isPlaying=!1,this.isPaused=!1,this.config=null,this.currentConfig=null,this.markers=null,this.currentMarker=null)}});t.exports=h},function(t,e,i){var n=i(178),s=i(0),r=i(1),o=i(125),a=new s({initialize:function(t){this.parent=t,this.list=[],this.position=0,this.addCallback=r,this.removeCallback=r,this._sortKey=""},add:function(t,e){return e?n.Add(this.list,t):n.Add(this.list,t,0,this.addCallback,this)},addAt:function(t,e,i){return i?n.AddAt(this.list,t,e):n.AddAt(this.list,t,e,0,this.addCallback,this)},getAt:function(t){return this.list[t]},getIndex:function(t){return this.list.indexOf(t)},sort:function(t,e){return t?(void 0===e&&(e=function(e,i){return e[t]-i[t]}),o.inplace(this.list,e),this):this},getByName:function(t){return n.GetFirst(this.list,"name",t)},getRandom:function(t,e){return n.GetRandom(this.list,t,e)},getFirst:function(t,e,i,s){return n.GetFirst(this.list,t,e,i,s)},getAll:function(t,e,i,s){return n.GetAll(this.list,t,e,i,s)},count:function(t,e){return n.CountAllMatching(this.list,t,e)},swap:function(t,e){n.Swap(this.list,t,e)},moveTo:function(t,e){return n.MoveTo(this.list,t,e)},remove:function(t,e){return e?n.Remove(this.list,t):n.Remove(this.list,t,this.removeCallback,this)},removeAt:function(t,e){return e?n.RemoveAt(this.list,t):n.RemoveAt(this.list,t,this.removeCallback,this)},removeBetween:function(t,e,i){return i?n.RemoveBetween(this.list,t,e):n.RemoveBetween(this.list,t,e,this.removeCallback,this)},removeAll:function(t){for(var e=this.list.length;e--;)this.remove(this.list[e],t);return this},bringToTop:function(t){return n.BringToTop(this.list,t)},sendToBack:function(t){return n.SendToBack(this.list,t)},moveUp:function(t){return n.MoveUp(this.list,t),t},moveDown:function(t){return n.MoveDown(this.list,t),t},reverse:function(){return this.list.reverse(),this},shuffle:function(){return n.Shuffle(this.list),this},replace:function(t,e){return n.Replace(this.list,t,e)},exists:function(t){return this.list.indexOf(t)>-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){for(var i=[null],n=2;n0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}}});t.exports=a},function(t,e,i){var n=i(179),s=i(383);t.exports=function(t,e){if(void 0===e&&(e=90),!n(t))return null;if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)(t=s(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t.reverse(),t=s(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;il&&(r=l),o>l&&(o=l),a=s,h=r;;)if(a-1&&this.entries.splice(e,1),this},dump:function(){console.group("Set");for(var t=0;t-1},union:function(t){var e=new n;return t.entries.forEach(function(t){e.set(t)}),this.entries.forEach(function(t){e.set(t)}),e},intersect:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)&&e.set(i)}),e},difference:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)||e.set(i)}),e},size:{get:function(){return this.entries.length},set:function(t){return t0&&o.length0&&a.lengthe.right||t.y>e.bottom)}},function(t,e,i){var n=i(6),s={},r={register:function(t,e,i,n,r){s[t]={plugin:e,mapping:i,settingsKey:n,configKey:r}},getPlugin:function(t){return s[t]},install:function(t){var e=t.scene.sys,i=e.settings.input,r=e.game.config;for(var o in s){var a=s[o].plugin,h=s[o].mapping,l=s[o].settingsKey,u=s[o].configKey;n(i,l,r[u])&&(t[h]=new a(t))}},remove:function(t){s.hasOwnProperty(t)&&delete s[t]}};t.exports=r},function(t,e,i){t.exports={ANY_KEY_DOWN:i(1207),ANY_KEY_UP:i(1208),COMBO_MATCH:i(1209),DOWN:i(1210),KEY_DOWN:i(1211),KEY_UP:i(1212),UP:i(1213)}},function(t,e){t.exports=function(t,e){return!!t.url&&(t.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t.url:e+t.url)}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===t&&(t=""),void 0===e&&(e=!0),void 0===i&&(i=""),void 0===n&&(n=""),void 0===s&&(s=0),void 0===r&&(r=!1),{responseType:t,async:e,user:i,password:n,timeout:s,header:void 0,headerValue:void 0,requestedWith:!1,overrideMimeType:void 0,withCredentials:r}}},function(t,e,i){var n=i(0),s=i(212),r=i(73),o=new n({Extends:r,Mixins:[s.Acceleration,s.Angular,s.Bounce,s.Debug,s.Drag,s.Enable,s.Friction,s.Gravity,s.Immovable,s.Mass,s.Size,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t,e,i,n,s),this.body=null}});t.exports=o},function(t,e,i){t.exports={CalculateFacesAt:i(215),CalculateFacesWithin:i(51),Copy:i(1303),CreateFromTiles:i(1304),CullTiles:i(1305),Fill:i(1307),FilterTiles:i(1308),FindByIndex:i(1309),FindTile:i(1310),ForEachTile:i(1311),GetTileAt:i(136),GetTileAtWorldXY:i(1312),GetTilesWithin:i(25),GetTilesWithinShape:i(1313),GetTilesWithinWorldXY:i(1314),HasTileAt:i(469),HasTileAtWorldXY:i(1315),IsInLayerBounds:i(99),PutTileAt:i(216),PutTileAtWorldXY:i(1316),PutTilesAt:i(1317),Randomize:i(1318),RemoveTileAt:i(470),RemoveTileAtWorldXY:i(1319),RenderDebug:i(1320),ReplaceByIndex:i(468),SetCollision:i(1321),SetCollisionBetween:i(1322),SetCollisionByExclusion:i(1323),SetCollisionByProperty:i(1324),SetCollisionFromCollisionGroup:i(1325),SetTileIndexCallback:i(1326),SetTileLocationCallback:i(1327),Shuffle:i(1328),SwapByIndex:i(1329),TileToWorldX:i(1330),TileToWorldXY:i(1331),TileToWorldY:i(1332),WeightedRandomize:i(1333),WorldToTileX:i(471),WorldToTileXY:i(1334),WorldToTileY:i(472)}},function(t,e,i){var n=i(99);t.exports=function(t,e,i,s){if(void 0===i&&(i=!1),n(t,e,s)){var r=s.data[e][t]||null;return null===r?null:-1===r.index?i?r:null:r}return null}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o,a){(void 0===i||i<=0)&&(i=32),(void 0===n||n<=0)&&(n=32),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o={}),void 0===a&&(a={}),this.name=t,this.firstgid=e,this.tileWidth=i,this.tileHeight=n,this.tileMargin=s,this.tileSpacing=r,this.tileProperties=o,this.tileData=a,this.image=null,this.glTexture=null,this.rows=0,this.columns=0,this.total=0,this.texCoordinates=[]},getTileProperties:function(t){return this.containsTileIndex(t)?this.tileProperties[t-this.firstgid]:null},getTileData:function(t){return this.containsTileIndex(t)?this.tileData[t-this.firstgid]:null},getTileCollisionGroup:function(t){var e=this.getTileData(t);return e&&e.objectgroup?e.objectgroup:null},containsTileIndex:function(t){return t>=this.firstgid&&t=this.vertexCapacity},resize:function(t,e,i){return this.width=t*i,this.height=e*i,this.resolution=i,this},bind:function(){var t=this.gl,e=this.vertexBuffer,i=this.attributes,n=this.program,s=this.renderer,r=this.vertexSize;s.setProgram(n),s.setVertexBuffer(e);for(var o=0;o=0?(t.enableVertexAttribArray(h),t.vertexAttribPointer(h,a.size,a.type,a.normalized,r,a.offset)):-1!==h&&t.disableVertexAttribArray(h)}return this},onBind:function(){return this},onPreRender:function(){return this},onRender:function(){return this},onPostRender:function(){return this},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t=this.gl,e=this.vertexCount,i=this.topology,n=this.vertexSize;if(0!==e)return t.bufferSubData(t.ARRAY_BUFFER,0,this.bytes.subarray(0,e*n)),t.drawArrays(i,0,e),this.vertexCount=0,this.flushLocked=!1,this;this.flushLocked=!1},destroy:function(){var t=this.gl;return t.deleteProgram(this.program),t.deleteBuffer(this.vertexBuffer),delete this.program,delete this.vertexBuffer,delete this.gl,this},setFloat1:function(t,e){return this.renderer.setFloat1(this.program,t,e),this},setFloat2:function(t,e,i){return this.renderer.setFloat2(this.program,t,e,i),this},setFloat3:function(t,e,i,n){return this.renderer.setFloat3(this.program,t,e,i,n),this},setFloat4:function(t,e,i,n,s){return this.renderer.setFloat4(this.program,t,e,i,n,s),this},setFloat1v:function(t,e){return this.renderer.setFloat1v(this.program,t,e),this},setFloat2v:function(t,e){return this.renderer.setFloat2v(this.program,t,e),this},setFloat3v:function(t,e){return this.renderer.setFloat3v(this.program,t,e),this},setFloat4v:function(t,e){return this.renderer.setFloat4v(this.program,t,e),this},setInt1:function(t,e){return this.renderer.setInt1(this.program,t,e),this},setInt2:function(t,e,i){return this.renderer.setInt2(this.program,t,e,i),this},setInt3:function(t,e,i,n){return this.renderer.setInt3(this.program,t,e,i,n),this},setInt4:function(t,e,i,n,s){return this.renderer.setInt4(this.program,t,e,i,n,s),this},setMatrix2:function(t,e,i){return this.renderer.setMatrix2(this.program,t,e,i),this},setMatrix3:function(t,e,i){return this.renderer.setMatrix3(this.program,t,e,i),this},setMatrix4:function(t,e,i){return this.renderer.setMatrix4(this.program,t,e,i),this}});t.exports=r},function(t,e,i){var n={};t.exports=n;var s=i(235),r=i(37),o=i(98),a=i(62);n.create=function(t){return r.extend({id:r.nextId(),type:"composite",parent:null,isModified:!1,bodies:[],constraints:[],composites:[],label:"Composite",plugin:{}},t)},n.setModified=function(t,e,i,r){if(s.trigger(t,"compositeModified",t),t.isModified=e,i&&t.parent&&n.setModified(t.parent,e,i,r),r)for(var o=0;o1?2-s:s,o=r*Math.cos(i),a=r*Math.sin(i);return e.x=t.x+o*t.radius,e.y=t.y+a*t.radius,e}},function(t,e,i){var n=i(23),s=i(0),r=i(11),o=i(107),a=i(265),h=i(266),l=i(6),u=new s({Extends:r,initialize:function(t,e,i){r.call(this),this.manager=t,this.key=e,this.type="frame",this.frames=this.getFrames(t.textureManager,l(i,"frames",[]),l(i,"defaultTextureKey",null)),this.frameRate=l(i,"frameRate",null),this.duration=l(i,"duration",null),null===this.duration&&null===this.frameRate?(this.frameRate=24,this.duration=this.frameRate/this.frames.length*1e3):this.duration&&null===this.frameRate?this.frameRate=this.frames.length/(this.duration/1e3):this.duration=this.frames.length/this.frameRate*1e3,this.msPerFrame=1e3/this.frameRate,this.skipMissedFrames=l(i,"skipMissedFrames",!0),this.delay=l(i,"delay",0),this.repeat=l(i,"repeat",0),this.repeatDelay=l(i,"repeatDelay",0),this.yoyo=l(i,"yoyo",!1),this.showOnStart=l(i,"showOnStart",!1),this.hideOnComplete=l(i,"hideOnComplete",!1),this.paused=!1,this.manager.on(o.PAUSE_ALL,this.pause,this),this.manager.on(o.RESUME_ALL,this.resume,this)},addFrame:function(t){return this.addFrameAt(this.frames.length,t)},addFrameAt:function(t,e){var i=this.getFrames(this.manager.textureManager,e);if(i.length>0){if(0===t)this.frames=i.concat(this.frames);else if(t===this.frames.length)this.frames=this.frames.concat(i);else{var n=this.frames.slice(0,t),s=this.frames.slice(t);this.frames=n.concat(i,s)}this.updateFrameSequence()}return this},checkFrame:function(t){return t>=0&&t0){s.isLast=!0,s.nextFrame=a[0],a[0].prevFrame=s;var v=1/(a.length-1);for(r=0;r=this.frames.length&&(e=0),t.currentAnim!==this&&(t.currentAnim=this,t.frameRate=this.frameRate,t.duration=this.duration,t.msPerFrame=this.msPerFrame,t.skipMissedFrames=this.skipMissedFrames,t._delay=this.delay,t._repeat=this.repeat,t._repeatDelay=this.repeatDelay,t._yoyo=this.yoyo);var i=this.frames[e];0!==e||t.forward||(i=this.getLastFrame()),t.updateFrame(i)},getFrameByProgress:function(t){return t=n(t,0,1),a(t,this.frames,"progress")},nextFrame:function(t){var e=t.currentFrame;e.isLast?t._yoyo?this.handleYoyoFrame(t,!1):t.repeatCounter>0?t._reverse&&t.forward?t.forward=!1:this.repeatAnimation(t):this.completeAnimation(t):this.updateAndGetNextTick(t,e.nextFrame)},handleYoyoFrame:function(t,e){if(e||(e=!1),t._reverse===!e&&t.repeatCounter>0)return t.forward=e,void this.repeatAnimation(t);if(t._reverse===e||0!==t.repeatCounter){t.forward=e;var i=e?t.currentFrame.nextFrame:t.currentFrame.prevFrame;this.updateAndGetNextTick(t,i)}else this.completeAnimation(t)},getLastFrame:function(){return this.frames[this.frames.length-1]},previousFrame:function(t){var e=t.currentFrame;e.isFirst?t._yoyo?this.handleYoyoFrame(t,!0):t.repeatCounter>0?t._reverse&&!t.forward?(t.currentFrame=this.getLastFrame(),this.repeatAnimation(t)):(t.forward=!0,this.repeatAnimation(t)):this.completeAnimation(t):this.updateAndGetNextTick(t,e.prevFrame)},updateAndGetNextTick:function(t,e){t.updateFrame(e),this.getNextTick(t)},removeFrame:function(t){var e=this.frames.indexOf(t);return-1!==e&&this.removeFrameAt(e),this},removeFrameAt:function(t){return this.frames.splice(t,1),this.updateFrameSequence(),this},repeatAnimation:function(t){if(2===t._pendingStop)return this.completeAnimation(t);if(t._repeatDelay>0&&!1===t.pendingRepeat)t.pendingRepeat=!0,t.accumulator-=t.nextTick,t.nextTick+=t._repeatDelay;else if(t.repeatCounter--,t.updateFrame(t.currentFrame[t.forward?"nextFrame":"prevFrame"]),t.isPlaying){this.getNextTick(t),t.pendingRepeat=!1;var e=t.currentFrame,i=t.parent;this.emit(o.ANIMATION_REPEAT,this,e),i.emit(o.SPRITE_ANIMATION_KEY_REPEAT+this.key,this,e,t.repeatCounter,i),i.emit(o.SPRITE_ANIMATION_REPEAT,this,e,t.repeatCounter,i)}},setFrame:function(t){t.forward?this.nextFrame(t):this.previousFrame(t)},toJSON:function(){var t={key:this.key,type:this.type,frames:[],frameRate:this.frameRate,duration:this.duration,skipMissedFrames:this.skipMissedFrames,delay:this.delay,repeat:this.repeat,repeatDelay:this.repeatDelay,yoyo:this.yoyo,showOnStart:this.showOnStart,hideOnComplete:this.hideOnComplete};return this.frames.forEach(function(e){t.frames.push(e.toJSON())}),t},updateFrameSequence:function(){for(var t,e=this.frames.length,i=1/(e-1),n=0;n1?(t.isLast=!0,t.prevFrame=this.frames[e-2],t.nextFrame=this.frames[0]):e>1&&(t.prevFrame=this.frames[n-1],t.nextFrame=this.frames[n+1]);return this},pause:function(){return this.paused=!0,this},resume:function(){return this.paused=!1,this},destroy:function(){this.removeAllListeners(),this.manager.off(o.PAUSE_ALL,this.pause,this),this.manager.off(o.RESUME_ALL,this.resume,this),this.manager.remove(this.key);for(var t=0;t=1)return i.x=t.x,i.y=t.y,i;var r=n(t)*e;return e>.5?(r-=t.width+t.height)<=t.width?(i.x=t.right-r,i.y=t.bottom):(i.x=t.x,i.y=t.bottom-(r-t.width)):r<=t.width?(i.x=t.x+r,i.y=t.y):(i.x=t.right,i.y=t.y+(r-t.width)),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=n(t)/i);for(var o=t.x1,a=t.y1,h=t.x2,l=t.y2,u=0;u=1&&(a=1-a,h=1-h),e.x=t.x1+(i*a+r*h),e.y=t.y1+(s*a+o*h),e}},function(t,e){t.exports=function(t,e,i,n,s){var r=n+Math.atan2(t.y-i,t.x-e);return t.x=e+s*Math.cos(r),t.y=i+s*Math.sin(r),t}},function(t,e){t.exports=function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)}},function(t,e){t.exports=function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){if(this.entries={},this.size=0,Array.isArray(t))for(var e=0;e=(t=t.toString()).length)switch(n){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((s=e-t.length)/2);t=new Array(s-r+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t}},function(t,e,i){var n=i(289),s=i(292),r=i(294),o=i(295);t.exports=function(t){switch(typeof t){case"string":return"rgb"===t.substr(0,3).toLowerCase()?o(t):n(t);case"number":return s(t);case"object":return r(t)}}},function(t,e){t.exports=function(t,e,i){return t<<16|e<<8|i}},function(t,e,i){var n=i(159);t.exports=function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1);var r=Math.floor(6*t),o=6*t-r,a=Math.floor(i*(1-e)*255),h=Math.floor(i*(1-o*e)*255),l=Math.floor(i*(1-(1-o)*e)*255),u=i=Math.floor(i*=255),c=i,d=i,f=r%6;return 0===f?(c=l,d=a):1===f?(u=h,d=a):2===f?(u=a,d=l):3===f?(u=a,c=h):4===f?(u=l,c=a):5===f&&(c=a,d=h),s?s.setTo?s.setTo(u,c,d,s.alpha,!1):(s.r=u,s.g=c,s.b=d,s.color=n(u,c,d),s):{r:u,g:c,b:d,color:n(u,c,d)}}},function(t,e){var i,n="";t.exports={disable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!1),t},enable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!0),t},getPrefix:i=function(t){for(var e=["i","webkitI","msI","mozI","oI"],i=0;i0&&(n=1/Math.sqrt(n),this.x=t*n,this.y=e*n,this.z=i*n),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},cross:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z;return this.x=i*o-n*r,this.y=n*s-e*o,this.z=e*r-i*s,this},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this},transformMat3:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=e*s[0]+i*s[3]+n*s[6],this.y=e*s[1]+i*s[4]+n*s[7],this.z=e*s[2]+i*s[5]+n*s[8],this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=s[0]*e+s[4]*i+s[8]*n+s[12],this.y=s[1]*e+s[5]*i+s[9]*n+s[13],this.z=s[2]*e+s[6]*i+s[10]*n+s[14],this},transformCoordinates:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=e*s[0]+i*s[4]+n*s[8]+s[12],o=e*s[1]+i*s[5]+n*s[9]+s[13],a=e*s[2]+i*s[6]+n*s[10]+s[14],h=e*s[3]+i*s[7]+n*s[11]+s[15];return this.x=r/h,this.y=o/h,this.z=a/h,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},project:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=s[0],o=s[1],a=s[2],h=s[3],l=s[4],u=s[5],c=s[6],d=s[7],f=s[8],p=s[9],g=s[10],v=s[11],m=s[12],y=s[13],x=s[14],T=1/(e*h+i*d+n*v+s[15]);return this.x=(e*r+i*l+n*f+m)*T,this.y=(e*o+i*u+n*p+y)*T,this.z=(e*a+i*c+n*g+x)*T,this},unproject:function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,o=this.x-i,a=r-this.y-1-n,h=this.z;return this.x=2*o/s-1,this.y=2*a/r-1,this.z=2*h-1,this.project(e)},reset:function(){return this.x=0,this.y=0,this.z=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0,0),n.LEFT=new n(-1,0,0),n.UP=new n(0,-1,0),n.DOWN=new n(0,1,0),n.FORWARD=new n(0,0,1),n.BACK=new n(0,0,-1),n.ONE=new n(1,1,1),t.exports=n},function(t,e,i){t.exports={Global:["game","anims","cache","plugins","registry","scale","sound","textures"],CoreScene:["EventEmitter","CameraManager","GameObjectCreator","GameObjectFactory","ScenePlugin","DisplayList","UpdateList"],DefaultScene:["Clock","DataManagerPlugin","InputPlugin","Loader","TweenManager","LightsPlugin"]}},function(t,e,i){var n=i(13),s=i(16);t.exports=function(t,e){if(void 0===e&&(e=new n),0===t.length)return e;for(var i,r,o,a=Number.MAX_VALUE,h=Number.MAX_VALUE,l=s.MIN_SAFE_INTEGER,u=s.MIN_SAFE_INTEGER,c=0;c0},isTransitionIn:function(){return this.settings.isTransition},isVisible:function(){return this.settings.visible},setVisible:function(t){return this.settings.visible=t,this},setActive:function(t,e){return t?this.resume(e):this.pause(e)},start:function(t){t&&(this.settings.data=t),this.settings.status=s.START,this.settings.active=!0,this.settings.visible=!0,this.events.emit(o.START,this),this.events.emit(o.READY,this,t)},shutdown:function(t){this.events.off(o.TRANSITION_INIT),this.events.off(o.TRANSITION_START),this.events.off(o.TRANSITION_COMPLETE),this.events.off(o.TRANSITION_OUT),this.settings.status=s.SHUTDOWN,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.SHUTDOWN,this,t)},destroy:function(){this.settings.status=s.DESTROYED,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.DESTROY,this),this.events.removeAllListeners();for(var t=["scene","game","anims","cache","plugins","registry","sound","textures","add","camera","displayList","events","make","scenePlugin","updateList"],e=0;e0},getRenderList:function(){return this.dirty&&(this.renderList=this.children.list.filter(this.childCanRender,this),this.dirty=!1),this.renderList},clear:function(){this.children.removeAll(),this.dirty=!0},preDestroy:function(){this.children.destroy(),this.renderList=[]}});t.exports=u},function(t,e,i){var n=i(178),s=i(52),r=i(0),o=i(12),a=i(88),h=i(14),l=i(13),u=i(945),c=i(387),d=i(3),f=new r({Extends:h,Mixins:[o.AlphaSingle,o.BlendMode,o.ComputedSize,o.Depth,o.Mask,o.Transform,o.Visible,u],initialize:function(t,e,i,n){h.call(this,t,"Container"),this.list=[],this.exclusive=!0,this.maxSize=-1,this.position=0,this.localTransform=new o.TransformMatrix,this.tempTransformMatrix=new o.TransformMatrix,this._displayList=t.sys.displayList,this._sortKey="",this._sysEvents=t.sys.events,this.scrollFactorX=1,this.scrollFactorY=1,this.setPosition(e,i),this.clearAlpha(),this.setBlendMode(s.SKIP_CHECK),n&&this.add(n)},originX:{get:function(){return.5}},originY:{get:function(){return.5}},displayOriginX:{get:function(){return.5*this.width}},displayOriginY:{get:function(){return.5*this.height}},setExclusive:function(t){return void 0===t&&(t=!0),this.exclusive=t,this},getBounds:function(t){if(void 0===t&&(t=new l),t.setTo(this.x,this.y,0,0),this.list.length>0)for(var e=this.list,i=new l,n=0;n-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){var i,n=[null],s=this.list.slice(),r=s.length;for(i=2;i0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}},preDestroy:function(){this.removeAll(!!this.exclusive),this.localTransform.destroy(),this.tempTransformMatrix.destroy(),this.list=[],this._displayList=null}});t.exports=f},function(t,e,i){var n=i(126),s=i(0),r=i(950),o=new s({Extends:n,Mixins:[r],initialize:function(t,e,i,s,r,o,a){n.call(this,t,e,i,s,r,o,a),this.type="DynamicBitmapText",this.scrollX=0,this.scrollY=0,this.cropWidth=0,this.cropHeight=0,this.displayCallback,this.callbackData={parent:this,color:0,tint:{topLeft:0,topRight:0,bottomLeft:0,bottomRight:0},index:0,charCode:0,x:0,y:0,scale:0,rotation:0,data:0}},setSize:function(t,e){return this.cropWidth=t,this.cropHeight=e,this},setDisplayCallback:function(t){return this.displayCallback=t,this},setScrollX:function(t){return this.scrollX=t,this},setScrollY:function(t){return this.scrollY=t,this}});t.exports=o},function(t,e,i){var n=i(89),s=i(0),r=i(187),o=i(264),a=i(267),h=i(268),l=i(272),u=i(150),c=i(277),d=i(278),f=i(275),p=i(30),g=i(93),v=i(14),m=i(2),y=i(6),x=i(16),T=i(956),w=new s({Extends:v,Mixins:[o,a,h,l,u,c,d,f,T],initialize:function(t,e){var i=y(e,"x",0),n=y(e,"y",0);v.call(this,t,"Graphics"),this.setPosition(i,n),this.initPipeline(),this.displayOriginX=0,this.displayOriginY=0,this.commandBuffer=[],this.defaultFillColor=-1,this.defaultFillAlpha=1,this.defaultStrokeWidth=1,this.defaultStrokeColor=-1,this.defaultStrokeAlpha=1,this._lineWidth=1,this._tempMatrix1=new p,this._tempMatrix2=new p,this._tempMatrix3=new p,this.setDefaultStyles(e)},setDefaultStyles:function(t){return y(t,"lineStyle",null)&&(this.defaultStrokeWidth=y(t,"lineStyle.width",1),this.defaultStrokeColor=y(t,"lineStyle.color",16777215),this.defaultStrokeAlpha=y(t,"lineStyle.alpha",1),this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha)),y(t,"fillStyle",null)&&(this.defaultFillColor=y(t,"fillStyle.color",16777215),this.defaultFillAlpha=y(t,"fillStyle.alpha",1),this.fillStyle(this.defaultFillColor,this.defaultFillAlpha)),this},lineStyle:function(t,e,i){return void 0===i&&(i=1),this.commandBuffer.push(r.LINE_STYLE,t,e,i),this._lineWidth=t,this},fillStyle:function(t,e){return void 0===e&&(e=1),this.commandBuffer.push(r.FILL_STYLE,t,e),this},fillGradientStyle:function(t,e,i,n,s){return void 0===s&&(s=1),this.commandBuffer.push(r.GRADIENT_FILL_STYLE,s,t,e,i,n),this},lineGradientStyle:function(t,e,i,n,s,o){return void 0===o&&(o=1),this.commandBuffer.push(r.GRADIENT_LINE_STYLE,t,o,e,i,n,s),this},setTexture:function(t,e,i){if(void 0===i&&(i=0),void 0===t)this.commandBuffer.push(r.CLEAR_TEXTURE);else{var n=this.scene.sys.textures.getFrame(t,e);n&&(2===i&&(i=3),this.commandBuffer.push(r.SET_TEXTURE,n,i))}return this},beginPath:function(){return this.commandBuffer.push(r.BEGIN_PATH),this},closePath:function(){return this.commandBuffer.push(r.CLOSE_PATH),this},fillPath:function(){return this.commandBuffer.push(r.FILL_PATH),this},fill:function(){return this.commandBuffer.push(r.FILL_PATH),this},strokePath:function(){return this.commandBuffer.push(r.STROKE_PATH),this},stroke:function(){return this.commandBuffer.push(r.STROKE_PATH),this},fillCircleShape:function(t){return this.fillCircle(t.x,t.y,t.radius)},strokeCircleShape:function(t){return this.strokeCircle(t.x,t.y,t.radius)},fillCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.fillPath(),this},strokeCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.strokePath(),this},fillRectShape:function(t){return this.fillRect(t.x,t.y,t.width,t.height)},strokeRectShape:function(t){return this.strokeRect(t.x,t.y,t.width,t.height)},fillRect:function(t,e,i,n){return this.commandBuffer.push(r.FILL_RECT,t,e,i,n),this},strokeRect:function(t,e,i,n){var s=this._lineWidth/2,r=t-s,o=t+s;return this.beginPath(),this.moveTo(t,e),this.lineTo(t,e+n),this.strokePath(),this.beginPath(),this.moveTo(t+i,e),this.lineTo(t+i,e+n),this.strokePath(),this.beginPath(),this.moveTo(r,e),this.lineTo(o+i,e),this.strokePath(),this.beginPath(),this.moveTo(r,e+n),this.lineTo(o+i,e+n),this.strokePath(),this},fillRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.fillPath(),this},strokeRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.strokePath(),this},fillPointShape:function(t,e){return this.fillPoint(t.x,t.y,e)},fillPoint:function(t,e,i){return!i||i<1?i=1:(t-=i/2,e-=i/2),this.commandBuffer.push(r.FILL_RECT,t,e,i,i),this},fillTriangleShape:function(t){return this.fillTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},strokeTriangleShape:function(t){return this.strokeTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},fillTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.FILL_TRIANGLE,t,e,i,n,s,o),this},strokeTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.STROKE_TRIANGLE,t,e,i,n,s,o),this},strokeLineShape:function(t){return this.lineBetween(t.x1,t.y1,t.x2,t.y2)},lineBetween:function(t,e,i,n){return this.beginPath(),this.moveTo(t,e),this.lineTo(i,n),this.strokePath(),this},lineTo:function(t,e){return this.commandBuffer.push(r.LINE_TO,t,e),this},moveTo:function(t,e){return this.commandBuffer.push(r.MOVE_TO,t,e),this},strokePoints:function(t,e,i,n){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===n&&(n=t.length),this.beginPath(),this.moveTo(t[0].x,t[0].y);for(var s=1;s-1&&this.fillStyle(this.defaultFillColor,this.defaultFillAlpha),this.defaultStrokeColor>-1&&this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha),this},generateTexture:function(t,e,i){var n,s,r=this.scene.sys,o=r.game.renderer;if(void 0===e&&(e=r.scale.width),void 0===i&&(i=r.scale.height),w.TargetCamera.setScene(this.scene),w.TargetCamera.setViewport(0,0,e,i),w.TargetCamera.scrollX=this.x,w.TargetCamera.scrollY=this.y,"string"==typeof t)if(r.textures.exists(t)){var a=(n=r.textures.get(t)).getSourceImage();a instanceof HTMLCanvasElement&&(s=a.getContext("2d"))}else s=(n=r.textures.createCanvas(t,e,i)).getSourceImage().getContext("2d");else t instanceof HTMLCanvasElement&&(s=t.getContext("2d"));return s&&(this.renderCanvas(o,this,0,w.TargetCamera,null,s,!1),n&&n.refresh()),this},preDestroy:function(){this.commandBuffer=[]}});w.TargetCamera=new n,t.exports=w},function(t,e){t.exports={ARC:0,BEGIN_PATH:1,CLOSE_PATH:2,FILL_RECT:3,LINE_TO:4,MOVE_TO:5,LINE_STYLE:6,FILL_STYLE:7,FILL_PATH:8,STROKE_PATH:9,FILL_TRIANGLE:10,STROKE_TRIANGLE:11,SAVE:14,RESTORE:15,TRANSLATE:16,SCALE:17,ROTATE:18,SET_TEXTURE:19,CLEAR_TEXTURE:20,GRADIENT_FILL_STYLE:21,GRADIENT_LINE_STYLE:22}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.width/2,r=t.height/2;return i.x=t.x+s*Math.cos(e),i.y=t.y+r*Math.sin(e),i}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(395),a=i(123),h=i(397),l=i(966),u=new n({Extends:r,Mixins:[s.Depth,s.Mask,s.Pipeline,s.Transform,s.Visible,l],initialize:function(t,e,i,n){if(r.call(this,t,"ParticleEmitterManager"),this.blendMode=-1,this.timeScale=1,this.texture=null,this.frame=null,this.frameNames=[],null===i||"object"!=typeof i&&!Array.isArray(i)||(n=i,i=null),this.setTexture(e,i),this.initPipeline(),this.emitters=new a(this),this.wells=new a(this),n){Array.isArray(n)||(n=[n]);for(var s=0;s0?e.defaultFrame=i[0]:e.defaultFrame=this.defaultFrame,this},addEmitter:function(t){return this.emitters.add(t)},createEmitter:function(t){return this.addEmitter(new h(this,t))},removeEmitter:function(t){return this.emitters.remove(t,!0)},addGravityWell:function(t){return this.wells.add(t)},createGravityWell:function(t){return this.addGravityWell(new o(t))},emitParticle:function(t,e,i){for(var n=this.emitters.list,s=0;ss.width&&(t=s.width-this.frame.cutX),this.frame.cutY+e>s.height&&(e=s.height-this.frame.cutY),this.frame.setSize(t,e,this.frame.cutX,this.frame.cutY)}this.updateDisplayOrigin();var r=this.input;return r&&!r.customHitArea&&(r.hitArea.width=t,r.hitArea.height=e),this},setGlobalTint:function(t){return this.globalTint=t,this},setGlobalAlpha:function(t){return this.globalAlpha=t,this},saveTexture:function(t){return this.textureManager.renameTexture(this.texture.key,t),this._saved=!0,this.texture},fill:function(t,e,i,n,s,r){void 0===e&&(e=1),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.frame.cutWidth),void 0===r&&(r=this.frame.cutHeight);var o=255&(t>>16|0),a=255&(t>>8|0),h=255&(0|t),l=this.gl,u=this.frame;if(this.camera.preRender(1,1),l){var c=this.camera._cx,f=this.camera._cy,p=this.camera._cw,g=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(c,f,p,g,g);var v=this.pipeline;v.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),v.drawFillRect(i,n,s,r,d.getTintFromFloats(o/255,a/255,h/255,1),e),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),v.projOrtho(0,v.width,v.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.context.fillStyle="rgba("+o+","+a+","+h+","+e+")",this.context.fillRect(i+u.cutX,n+u.cutY,s,r),this.renderer.setContext();return this.dirty=!0,this},clear:function(){if(this.dirty){var t=this.gl;if(t){var e=this.renderer;e.setFramebuffer(this.framebuffer,!0),this.frame.cutWidth===this.canvas.width&&this.frame.cutHeight===this.canvas.height||t.scissor(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),e.setFramebuffer(null,!0)}else{var i=this.context;i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),i.restore()}this.dirty=!1}return this},erase:function(t,e,i){this._eraseMode=!0;var s=this.renderer.currentBlendMode;return this.renderer.setBlendMode(n.ERASE),this.draw(t,e,i,1,16777215),this.renderer.setBlendMode(s),this._eraseMode=!1,this},draw:function(t,e,i,n,s){void 0===n&&(n=this.globalAlpha),s=void 0===s?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(s>>16)+(65280&s)+((255&s)<<16),Array.isArray(t)||(t=[t]);var r=this.gl;if(this.camera.preRender(1,1),r){var o=this.camera._cx,a=this.camera._cy,h=this.camera._cw,l=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(o,a,h,l,l);var u=this.pipeline;u.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),this.batchList(t,e,i,n,s),u.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),u.projOrtho(0,u.width,u.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.batchList(t,e,i,n,s),this.renderer.setContext();return this.dirty=!0,this},drawFrame:function(t,e,i,n,s,r){void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.globalAlpha),r=void 0===r?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(r>>16)+(65280&r)+((255&r)<<16);var o=this.gl,a=this.textureManager.getFrame(t,e);if(a){if(this.camera.preRender(1,1),o){var h=this.camera._cx,l=this.camera._cy,u=this.camera._cw,c=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(h,l,u,c,c);var d=this.pipeline;d.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),d.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,r,s,this.camera.matrix,null),d.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),d.projOrtho(0,d.width,d.height,0,-1e3,1e3)}else this.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,s,r);this.dirty=!0}return this},batchList:function(t,e,i,n,s){for(var r=0;rr&&(o=t[r]),s[r]=o,t.length>r+1&&(o=t[r+1]),s[r+1]=o}return this},setColors:function(t){var e=this.points.length;if(e<1)return this;var i,n=this.colors;void 0===t?t=[16777215]:Array.isArray(t)||(t=[t]);var s=0;if(t.length===e)for(i=0;is&&(r=t[s]),n[s]=r,t.length>s+1&&(r=t[s+1]),n[s+1]=r}return this},setPoints:function(t,e,i){if(void 0===t&&(t=2),"number"==typeof t){var n,s,r,o=t;if(o<2&&(o=2),t=[],this.horizontal)for(r=-this.frame.halfWidth,s=this.frame.width/(o-1),n=0;nl){if(0===c){for(var g=f;g.length&&(g=g.slice(0,-1),!((p=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var v=d.substr(g.length);u[c]=v,h+=g}var m=u[c].length?c:c+1,y=u.slice(m).join(" ").replace(/[ \n]*$/gi,"");s[o+1]=y+" "+(s[o+1]||""),r=s.length;break}h+=f,l-=p}n+=h.replace(/[ \n]*$/gi,"")+"\n"}}return n=n.replace(/[\s|\n]*$/gi,"")},basicWordWrap:function(t,e,i){for(var n="",s=t.split(this.splitRegExp),r=s.length-1,o=e.measureText(" ").width,a=0;a<=r;a++){for(var h=i,l=s[a].split(" "),u=l.length-1,c=0;c<=u;c++){var d=l[c],f=e.measureText(d).width,p=f+o;p>h&&c>0&&(n+="\n",h=i),n+=d,c0&&(d+=h.lineSpacing*g),i.rtl)c=f-c;else if("right"===i.align)c+=o-h.lineWidths[g];else if("center"===i.align)c+=(o-h.lineWidths[g])/2;else if("justify"===i.align){if(h.lineWidths[g]/h.width>=.85){var v=h.width-h.lineWidths[g],m=e.measureText(" ").width,y=a[g].trim(),x=y.split(" ");v+=(a[g].length-y.length)*m;for(var T=Math.floor(v/m),w=0;T>0;)x[w]+=" ",w=(w+1)%(x.length-1||1),--T;a[g]=x.join(" ")}}this.autoRound&&(c=Math.round(c),d=Math.round(d)),i.strokeThickness&&(this.style.syncShadow(e,i.shadowStroke),e.strokeText(a[g],c,d)),i.color&&(this.style.syncShadow(e,i.shadowFill),e.fillText(a[g],c,d))}e.restore(),this.renderer.gl&&(this.frame.source.glTexture=this.renderer.canvasToTexture(t,this.frame.source.glTexture,!0),this.frame.glTexture=this.frame.source.glTexture),this.dirty=!0;var b=this.input;return b&&!b.customHitArea&&(b.hitArea.width=this.width,b.hitArea.height=this.height),this},getTextMetrics:function(){return this.style.getTextMetrics()},text:{get:function(){return this._text},set:function(t){this.setText(t)}},toJSON:function(){var t=o.ToJSON(this),e={autoRound:this.autoRound,text:this._text,style:this.style.toJSON(),padding:{left:this.padding.left,right:this.padding.right,top:this.padding.top,bottom:this.padding.bottom}};return t.data=e,t},preDestroy:function(){this.style.rtl&&c(this.canvas),s.remove(this.canvas),this.texture.destroy()}});t.exports=p},function(t,e,i){var n=i(27),s=i(0),r=i(12),o=i(19),a=i(14),h=i(323),l=i(161),u=i(985),c=i(3),d=new s({Extends:a,Mixins:[r.Alpha,r.BlendMode,r.ComputedSize,r.Crop,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Tint,r.Transform,r.Visible,u],initialize:function(t,e,i,s,r,l,u){var d=t.sys.game.renderer;a.call(this,t,"TileSprite");var f=t.sys.textures.get(l),p=f.get(u);s&&r?(s=Math.floor(s),r=Math.floor(r)):(s=p.width,r=p.height),this._tilePosition=new c,this._tileScale=new c(1,1),this.dirty=!1,this.renderer=d,this.canvas=n.create(this,s,r),this.context=this.canvas.getContext("2d"),this.displayTexture=f,this.displayFrame=p,this._crop=this.resetCropObject(),this.texture=t.sys.textures.addCanvas(null,this.canvas,!0),this.frame=this.texture.get(),this.potWidth=h(p.width),this.potHeight=h(p.height),this.fillCanvas=n.create2D(this,this.potWidth,this.potHeight),this.fillContext=this.fillCanvas.getContext("2d"),this.fillPattern=null,this.setPosition(e,i),this.setSize(s,r),this.setFrame(u),this.setOriginFromFrame(),this.initPipeline(),t.sys.game.events.on(o.CONTEXT_RESTORED,function(t){var e=t.gl;this.dirty=!0,this.fillPattern=null,this.fillPattern=t.createTexture2D(0,e.LINEAR,e.LINEAR,e.REPEAT,e.REPEAT,e.RGBA,this.fillCanvas,this.potWidth,this.potHeight)},this)},setTexture:function(t,e){return this.displayTexture=this.scene.sys.textures.get(t),this.setFrame(e)},setFrame:function(t){var e=this.displayTexture.get(t);return this.potWidth=h(e.width),this.potHeight=h(e.height),this.canvas.width=0,e.cutWidth&&e.cutHeight?this.renderFlags|=8:this.renderFlags&=-9,this.displayFrame=e,this.dirty=!0,this.updateTileTexture(),this},setTilePosition:function(t,e){return void 0!==t&&(this.tilePositionX=t),void 0!==e&&(this.tilePositionY=e),this},setTileScale:function(t,e){return void 0===t&&(t=this.tileScaleX),void 0===e&&(e=t),this.tileScaleX=t,this.tileScaleY=e,this},updateTileTexture:function(){if(this.dirty&&this.renderer){var t=this.displayFrame;if(t.source.isRenderTexture||t.source.isGLTexture)return console.warn("TileSprites can only use Image or Canvas based textures"),void(this.dirty=!1);var e=this.fillContext,i=this.fillCanvas,n=this.potWidth,s=this.potHeight;this.renderer.gl||(n=t.cutWidth,s=t.cutHeight),e.clearRect(0,0,n,s),i.width=n,i.height=s,e.drawImage(t.source.image,t.cutX,t.cutY,t.cutWidth,t.cutHeight,0,0,n,s),this.renderer.gl?this.fillPattern=this.renderer.canvasToTexture(i,this.fillPattern):this.fillPattern=e.createPattern(i,"repeat"),this.updateCanvas(),this.dirty=!1}},updateCanvas:function(){var t=this.canvas;if(t.width===this.width&&t.height===this.height||(t.width=this.width,t.height=this.height,this.frame.setSize(this.width,this.height),this.updateDisplayOrigin(),this.dirty=!0),!this.dirty||this.renderer&&this.renderer.gl)this.dirty=!1;else{var e=this.context;this.scene.sys.game.config.antialias||l.disable(e);var i=this._tileScale.x,n=this._tileScale.y,s=this._tilePosition.x,r=this._tilePosition.y;e.clearRect(0,0,this.width,this.height),e.save(),e.scale(i,n),e.translate(-s,-r),e.fillStyle=this.fillPattern,e.fillRect(s,r,this.width/i,this.height/n),e.restore(),this.dirty=!1}},preDestroy:function(){this.renderer&&this.renderer.gl&&this.renderer.deleteTexture(this.fillPattern),n.remove(this.canvas),n.remove(this.fillCanvas),this.fillPattern=null,this.fillContext=null,this.fillCanvas=null,this.displayTexture=null,this.displayFrame=null,this.texture.destroy(),this.renderer=null},tilePositionX:{get:function(){return this._tilePosition.x},set:function(t){this._tilePosition.x=t,this.dirty=!0}},tilePositionY:{get:function(){return this._tilePosition.y},set:function(t){this._tilePosition.y=t,this.dirty=!0}},tileScaleX:{get:function(){return this._tileScale.x},set:function(t){this._tileScale.x=t,this.dirty=!0}},tileScaleY:{get:function(){return this._tileScale.y},set:function(t){this._tileScale.y=t,this.dirty=!0}}});t.exports=d},function(t,e,i){var n=i(0),s=i(23),r=i(12),o=i(88),a=i(19),h=i(14),l=i(59),u=i(191),c=i(988),d=i(16),f=new n({Extends:h,Mixins:[r.Alpha,r.BlendMode,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Size,r.TextureCrop,r.Tint,r.Transform,r.Visible,c],initialize:function(t,e,i,n){h.call(this,t,"Video"),this.video=null,this.videoTexture=null,this.videoTextureSource=null,this.snapshotTexture=null,this.flipY=!1,this._key=u(),this.touchLocked=!0,this.playWhenUnlocked=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._systemMuted=!1,this._codeMuted=!1,this._systemPaused=!1,this._codePaused=!1,this._callbacks={play:this.playHandler.bind(this),error:this.loadErrorHandler.bind(this),end:this.completeHandler.bind(this),time:this.timeUpdateHandler.bind(this),seeking:this.seekingHandler.bind(this),seeked:this.seekedHandler.bind(this)},this._crop=this.resetCropObject(),this.markers={},this._markerIn=-1,this._markerOut=d.MAX_SAFE_INTEGER,this._lastUpdate=0,this._cacheKey="",this._isSeeking=!1,this.removeVideoElementOnDestroy=!1,this.setPosition(e,i),this.initPipeline(),n&&this.changeSource(n,!1);var s=t.sys.game.events;s.on(a.PAUSE,this.globalPause,this),s.on(a.RESUME,this.globalResume,this);var r=t.sys.sound;r&&r.on(l.GLOBAL_MUTE,this.globalMute,this)},play:function(t,e,i){if(this.touchLocked&&this.playWhenUnlocked||this.isPlaying())return this;var n=this.video;if(!n)return console.warn("Video not loaded"),this;void 0===t&&(t=n.loop);var s=this.scene.sys.sound;s&&s.mute&&this.setMute(!0),isNaN(e)||(this._markerIn=e),!isNaN(i)&&i>e&&(this._markerOut=i),n.loop=t;var r=this._callbacks,o=n.play();return void 0!==o?o.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)):(n.addEventListener("playing",r.play,!0),n.readyState<2&&(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval))),n.addEventListener("ended",r.end,!0),n.addEventListener("timeupdate",r.time,!0),n.addEventListener("seeking",r.seeking,!0),n.addEventListener("seeked",r.seeked,!0),this},changeSource:function(t,e,i,n,s){void 0===e&&(e=!0),this.video&&this.stop();var r=this.scene.sys.cache.video.get(t);return r?(this.video=r,this._cacheKey=t,this._codePaused=r.paused,this._codeMuted=r.muted,this.videoTexture?(this.scene.sys.textures.remove(this._key),this.videoTexture=this.scene.sys.textures.create(this._key,r,r.videoWidth,r.videoHeight),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,r.videoWidth,r.videoHeight),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,r.videoWidth,r.videoHeight)):this.updateTexture(),r.currentTime=0,this._lastUpdate=0,e&&this.play(i,n,s)):this.video=null,this},addMarker:function(t,e,i){return!isNaN(e)&&e>=0&&!isNaN(i)&&(this.markers[t]=[e,i]),this},playMarker:function(t,e){var i=this.markers[t];return i&&this.play(e,i[0],i[1]),this},removeMarker:function(t){return delete this.markers[t],this},snapshot:function(t,e){return void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.snapshotArea(0,0,this.width,this.height,t,e)},snapshotArea:function(t,e,i,n,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=this.height),void 0===s&&(s=i),void 0===r&&(r=n);var o=this.video,a=this.snapshotTexture;return a?(a.setSize(s,r),o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)):(a=this.scene.sys.textures.createCanvas(u(),s,r),this.snapshotTexture=a,o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)),a.update()},saveSnapshotTexture:function(t){return this.snapshotTexture?this.scene.sys.textures.renameTexture(this.snapshotTexture.key,t):this.snapshotTexture=this.scene.sys.textures.createCanvas(t,this.width,this.height),this.snapshotTexture},loadURL:function(t,e,i){void 0===e&&(e="loadeddata"),void 0===i&&(i=!1),this.video&&this.stop(),this.videoTexture&&this.scene.sys.textures.remove(this._key);var n=document.createElement("video");return n.controls=!1,i&&(n.muted=!0,n.defaultMuted=!0,n.setAttribute("autoplay","autoplay")),n.setAttribute("playsinline","playsinline"),n.setAttribute("preload","auto"),n.addEventListener("error",this._callbacks.error,!0),n.src=t,n.load(),this.video=n,this},playPromiseSuccessHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn)},playPromiseErrorHandler:function(t){this.scene.sys.input.once("pointerdown",this.unlockHandler,this),this.touchLocked=!0,this.playWhenUnlocked=!0,this.emit(o.VIDEO_ERROR,this,t)},playHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this.video.removeEventListener("playing",this._callbacks.play,!0)},loadErrorHandler:function(t){this.stop(),this.emit(o.VIDEO_ERROR,this,t)},unlockHandler:function(){this.touchLocked=!1,this.playWhenUnlocked=!1,this.emit(o.VIDEO_UNLOCKED,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn),this.video.play(),this.emit(o.VIDEO_PLAY,this)},completeHandler:function(){this.emit(o.VIDEO_COMPLETE,this)},timeUpdateHandler:function(){this.video&&this.video.currentTime=this._markerOut&&(t.loop?(t.currentTime=this._markerIn,this.updateTexture(),this._lastUpdate=e,this.emit(o.VIDEO_LOOP,this)):(this.emit(o.VIDEO_COMPLETE,this),this.stop())))}},checkVideoProgress:function(){this.video.readyState>=2?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):this.emit(o.VIDEO_TIMEOUT,this))},updateTexture:function(){var t=this.video,e=t.videoWidth,i=t.videoHeight;if(this.videoTexture){var n=this.videoTextureSource;n.source!==t&&(n.source=t,n.width=e,n.height=i),n.update()}else this.videoTexture=this.scene.sys.textures.create(this._key,t,e,i),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,e,i),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,e,i)},getVideoKey:function(){return this._cacheKey},seekTo:function(t){var e=this.video;if(e){var i=e.duration;if(i!==1/0&&!isNaN(i)){var n=i*t;this.setCurrentTime(n)}}return this},getCurrentTime:function(){return this.video?this.video.currentTime:0},setCurrentTime:function(t){var e=this.video;if(e){if("string"==typeof t){var i=t[0],n=parseFloat(t.substr(1));"+"===i?t=e.currentTime+n:"-"===i&&(t=e.currentTime-n)}e.currentTime=t,this._lastUpdate=t}return this},isSeeking:function(){return this._isSeeking},seekingHandler:function(){this._isSeeking=!0,this.emit(o.VIDEO_SEEKING,this)},seekedHandler:function(){this._isSeeking=!1,this.emit(o.VIDEO_SEEKED,this),this.video&&this.updateTexture()},getProgress:function(){var t=this.video;if(t){var e=t.currentTime,i=t.duration;if(i!==1/0&&!isNaN(i))return e/i}return 0},getDuration:function(){return this.video?this.video.duration:0},setMute:function(t){void 0===t&&(t=!0),this._codeMuted=t;var e=this.video;return e&&(e.muted=!!this._systemMuted||t),this},isMuted:function(){return this._codeMuted},globalMute:function(t,e){this._systemMuted=e;var i=this.video;i&&(i.muted=!!this._codeMuted||e)},globalPause:function(){this._systemPaused=!0,this.video&&this.video.pause()},globalResume:function(){this._systemPaused=!1,this.video&&!this._codePaused&&this.video.play()},setPaused:function(t){void 0===t&&(t=!0);var e=this.video;return this._codePaused=t,e&&(t?e.paused||e.pause():t||e.paused&&!this._systemPaused&&e.play()),this},getVolume:function(){return this.video?this.video.volume:1},setVolume:function(t){return void 0===t&&(t=1),this.video&&(this.video.volume=s(t,0,1)),this},getPlaybackRate:function(){return this.video?this.video.playbackRate:1},setPlaybackRate:function(t){return this.video&&(this.video.playbackRate=t),this},getLoop:function(){return!!this.video&&this.video.loop},setLoop:function(t){return void 0===t&&(t=!0),this.video&&(this.video.loop=t),this},isPlaying:function(){return!!this.video&&!(this.video.paused||this.video.ended)},isPaused:function(){return this.video&&this.video.paused||this._codePaused||this._systemPaused},saveTexture:function(t,e){return void 0===e&&(e=!1),this.videoTexture&&this.scene.sys.textures.renameTexture(this._key,t),this._key=t,this.flipY=e,this.videoTextureSource&&this.videoTextureSource.setFlipY(e),this.videoTexture},stop:function(){var t=this.video;if(t){var e=this._callbacks;for(var i in e)t.removeEventListener(i,e[i],!0);t.pause()}return this._retryID&&window.clearTimeout(this._retryID),this.emit(o.VIDEO_STOP,this),this},removeVideoElement:function(){var t=this.video;if(t){for(t.parentNode&&t.parentNode.removeChild(t);t.hasChildNodes();)t.removeChild(t.firstChild);t.removeAttribute("autoplay"),t.removeAttribute("src"),this.video=null}},preDestroy:function(){this.stop(),this.removeVideoElementOnDestroy&&this.removeVideoElement();var t=this.scene.sys.game.events;t.off(a.PAUSE,this.globalPause,this),t.off(a.RESUME,this.globalResume,this);var e=this.scene.sys.sound;e&&e.off(l.GLOBAL_MUTE,this.globalMute,this),this._retryID&&window.clearTimeout(this._retryID)}});t.exports=f},function(t,e,i){var n=i(0),s=i(197),r=i(412),o=i(46),a=new n({initialize:function(t){this.type=o.POLYGON,this.area=0,this.points=[],t&&this.setTo(t)},contains:function(t,e){return s(this,t,e)},setTo:function(t){if(this.area=0,this.points=[],"string"==typeof t&&(t=t.split(" ")),!Array.isArray(t))return this;for(var e,i=Number.MAX_VALUE,n=0;no||r>a)return!1;if(s<=i||r<=n)return!0;var h=s-i,l=r-n;return h*h+l*l<=t.radius*t.radius}},function(t,e,i){var n=i(4),s=i(203);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a=t.x1,h=t.y1,l=t.x2,u=t.y2,c=e.x,d=e.y,f=e.radius,p=l-a,g=u-h,v=a-c,m=h-d,y=p*p+g*g,x=2*(p*v+g*m),T=x*x-4*y*(v*v+m*m-f*f);if(0===T){var w=-x/(2*y);r=a+w*p,o=h+w*g,w>=0&&w<=1&&i.push(new n(r,o))}else if(T>0){var b=(-x-Math.sqrt(T))/(2*y);r=a+b*p,o=h+b*g,b>=0&&b<=1&&i.push(new n(r,o));var E=(-x+Math.sqrt(T))/(2*y);r=a+E*p,o=h+E*g,E>=0&&E<=1&&i.push(new n(r,o))}}return i}},function(t,e,i){var n=i(55),s=new(i(4));t.exports=function(t,e,i){if(void 0===i&&(i=s),n(e,t.x1,t.y1))return i.x=t.x1,i.y=t.y1,!0;if(n(e,t.x2,t.y2))return i.x=t.x2,i.y=t.y2,!0;var r=t.x2-t.x1,o=t.y2-t.y1,a=e.x-t.x1,h=e.y-t.y1,l=r*r+o*o,u=r,c=o;if(l>0){var d=(a*r+h*o)/l;u*=d,c*=d}return i.x=t.x1+u,i.y=t.y1+c,u*u+c*c<=l&&u*r+c*o>=0&&n(e,i.x,i.y)}},function(t,e,i){var n=i(4),s=i(82),r=i(425);t.exports=function(t,e,i){if(void 0===i&&(i=[]),r(t,e))for(var o=e.getLineA(),a=e.getLineB(),h=e.getLineC(),l=e.getLineD(),u=[new n,new n,new n,new n],c=[s(o,t,u[0]),s(a,t,u[1]),s(h,t,u[2]),s(l,t,u[3])],d=0;d<4;d++)c[d]&&i.push(u[d]);return i}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=!1),void 0===n&&(n=[]);for(var s,r,o,a,h,l,u=t.x3-t.x1,c=t.y3-t.y1,d=t.x2-t.x1,f=t.y2-t.y1,p=u*u+c*c,g=u*d+c*f,v=d*d+f*f,m=p*v-g*g,y=0===m?0:1/m,x=t.x1,T=t.y1,w=0;w=0&&r>=0&&s+r<1&&(n.push({x:e[w].x,y:e[w].y}),i)));w++);return n}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,t}},function(t,e){t.exports=function(t){return 0===t.height?NaN:t.width/t.height}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,o=t.x3-e,a=t.y3-i,t.x3=o*s-a*r+e,t.y3=o*r+a*s+i,t}},function(t,e,i){t.exports={BUTTON_DOWN:i(1193),BUTTON_UP:i(1194),CONNECTED:i(1195),DISCONNECTED:i(1196),GAMEPAD_BUTTON_DOWN:i(1197),GAMEPAD_BUTTON_UP:i(1198)}},function(t,e,i){var n=i(18),s=i(133);t.exports=function(t,e){var i=void 0===t?s():n({},t);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=i(359),u=new n({Extends:r,initialize:function(t,e,i,n){var s="xml";if(h(e)){var o=e;e=a(o,"key"),i=a(o,"url"),n=a(o,"xhrSettings"),s=a(o,"extension",s)}var l={type:"xml",cache:t.cacheManager.xml,extension:s,responseType:"text",key:e,url:i,xhrSettings:n};r.call(this,t,l)},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=l(this.xhrLoader.responseText),this.data?this.onProcessComplete():(console.warn("Invalid XMLFile: "+this.key),this.onProcessError())}});o.register("xml",function(t,e,i){if(Array.isArray(t))for(var n=0;n0?1:.7),e.damping=e.damping||0,e.angularStiffness=e.angularStiffness||0,e.angleA=e.bodyA?e.bodyA.angle:e.angleA,e.angleB=e.bodyB?e.bodyB.angle:e.angleB,e.plugin={};var o={visible:!0,type:"line",anchors:!0,lineColor:null,lineOpacity:null,lineThickness:null,pinSize:null,anchorColor:null,anchorSize:null};return 0===e.length&&e.stiffness>.1?(o.type="pin",o.anchors=!1):e.stiffness<.9&&(o.type="spring"),e.render=l.extend(o,e.render),e},n.preSolveAll=function(t){for(var e=0;e0&&(c.position.x+=l.x,c.position.y+=l.y),0!==l.angle&&(s.rotate(c.vertices,l.angle,i.position),h.rotate(c.axes,l.angle),u>0&&r.rotateAbout(c.position,l.angle,i.position,c.position)),a.update(c.bounds,c.vertices,i.velocity)}l.angle*=n._warming,l.x*=n._warming,l.y*=n._warming}}},n.pointAWorld=function(t){return{x:(t.bodyA?t.bodyA.position.x:0)+t.pointA.x,y:(t.bodyA?t.bodyA.position.y:0)+t.pointA.y}},n.pointBWorld=function(t){return{x:(t.bodyB?t.bodyB.position.x:0)+t.pointB.x,y:(t.bodyB?t.bodyB.position.y:0)+t.pointB.y}}},function(t,e,i){var n=i(136);t.exports=function(t,e,i){var s=n(t,e,!0,i),r=n(t,e-1,!0,i),o=n(t,e+1,!0,i),a=n(t-1,e,!0,i),h=n(t+1,e,!0,i),l=s&&s.collides;return l&&(s.faceTop=!0,s.faceBottom=!0,s.faceLeft=!0,s.faceRight=!0),r&&r.collides&&(l&&(s.faceTop=!1),r.faceBottom=!l),o&&o.collides&&(l&&(s.faceBottom=!1),o.faceTop=!l),a&&a.collides&&(l&&(s.faceLeft=!1),a.faceRight=!l),h&&h.collides&&(l&&(s.faceRight=!1),h.faceLeft=!l),s&&!s.collides&&s.resetFaces(),s}},function(t,e,i){var n=i(72),s=i(99),r=i(215),o=i(71);t.exports=function(t,e,i,a,h){if(!s(e,i,h))return null;void 0===a&&(a=!0);var l=h.data[i][e],u=l&&l.collides;if(t instanceof n)null===h.data[i][e]&&(h.data[i][e]=new n(h,t.index,e,i,h.tileWidth,h.tileHeight)),h.data[i][e].copy(t);else{var c=t;null===h.data[i][e]?h.data[i][e]=new n(h,c,e,i,h.tileWidth,h.tileHeight):h.data[i][e].index=c}var d=h.data[i][e],f=-1!==h.collideIndexes.indexOf(d.index);return o(d,f),a&&u!==d.collides&&r(e,i,h),d}},function(t,e){t.exports=function(t,e,i){var n=i.collideIndexes.indexOf(t);e&&-1===n?i.collideIndexes.push(t):e||-1===n||i.collideIndexes.splice(n,1)}},function(t,e,i){var n=i(33),s=i(100),r=i(101),o=i(72);t.exports=function(t,e,i,a,h){for(var l=new s({tileWidth:i,tileHeight:a}),u=new r({name:t,tileWidth:i,tileHeight:a,format:n.ARRAY_2D,layers:[l]}),c=[],d=e.length,f=0,p=0;p0&&(s.totalDuration+=s.t2*s.repeat),s.totalDuration>t&&(t=s.totalDuration),s.delay0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay,this.startDelay=e},init:function(){if(this.paused&&!this.parentIsTimeline)return this.state=h.PENDING_ADD,this._pausedState=h.INIT,!1;for(var t=this.data,e=this.totalTargets,i=0;i0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweenData(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=h.LOOP_DELAY):(this.state=h.ACTIVE,this.dispatchTweenEvent(r.TWEEN_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=h.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=h.PENDING_REMOVE,this.dispatchTweenEvent(r.TWEEN_COMPLETE,this.callbacks.onComplete))},pause:function(){return this.state===h.PAUSED?this:(this.paused=!0,this._pausedState=this.state,this.state=h.PAUSED,this)},play:function(t){void 0===t&&(t=!1);var e=this.state;return e!==h.INIT||this.parentIsTimeline?e===h.ACTIVE||e===h.PENDING_ADD&&this._pausedState===h.PENDING_ADD?this:this.parentIsTimeline||e!==h.PENDING_REMOVE&&e!==h.REMOVED?(this.parentIsTimeline?(this.resetTweenData(t),0===this.calculatedOffset?this.state=h.ACTIVE:(this.countdown=this.calculatedOffset,this.state=h.OFFSET_DELAY)):this.paused?(this.paused=!1,this.makeActive()):(this.resetTweenData(t),this.state=h.ACTIVE,this.makeActive()),this):(this.seek(0),this.parent.makeActive(this),this):(this.resetTweenData(!1),this.state=h.ACTIVE,this)},resetTweenData:function(t){for(var e=this.data,i=this.totalData,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY),r.getActiveValue&&(o[a]=r.getActiveValue(r.target,r.key,r.start))}},resume:function(){return this.state===h.PAUSED?(this.paused=!1,this.state=this._pausedState):this.play(),this},seek:function(t,e){if(void 0===e&&(e=16.6),this.totalDuration>=36e5)return console.warn("Tween.seek duration too long"),this;this.state===h.REMOVED&&this.makeActive(),this.elapsed=0,this.progress=0,this.totalElapsed=0,this.totalProgress=0;for(var i=this.data,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY)}this.calcDuration();var c=!1;this.state===h.PAUSED&&(c=!0,this.state=h.ACTIVE),this.isSeeking=!0;do{this.update(0,e)}while(this.totalProgress0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.start=e.getStartValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},setStateFromStart:function(t,e,i){return e.repeatCounter>0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},updateTweenData:function(t,e,i){var n=e.target;switch(e.state){case h.PLAYING_FORWARD:case h.PLAYING_BACKWARD:if(!n){e.state=h.COMPLETE;break}var s=e.elapsed,o=e.duration,a=0;(s+=i)>o&&(a=s-o,s=o);var l=e.state===h.PLAYING_FORWARD,u=s/o;if(e.elapsed=s,e.progress=u,e.previous=e.current,1===u)l?(e.current=e.end,n[e.key]=e.end,e.hold>0?(e.elapsed=e.hold-a,e.state=h.HOLD_DELAY):e.state=this.setStateFromEnd(t,e,a)):(e.current=e.start,n[e.key]=e.start,e.state=this.setStateFromStart(t,e,a));else{var c=l?e.ease(u):e.ease(1-u);e.current=e.start+(e.end-e.start)*c,n[e.key]=e.current}this.dispatchTweenDataEvent(r.TWEEN_UPDATE,t.callbacks.onUpdate,e);break;case h.DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PENDING_RENDER);break;case h.REPEAT_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PLAYING_FORWARD,this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e));break;case h.HOLD_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.state=this.setStateFromEnd(t,e,Math.abs(e.elapsed)));break;case h.PENDING_RENDER:n?(e.start=e.getStartValue(n,e.key,n[e.key],e.index,t.totalTargets,t),e.end=e.getEndValue(n,e.key,e.start,e.index,t.totalTargets,t),e.current=e.start,n[e.key]=e.start,e.state=h.PLAYING_FORWARD):e.state=h.COMPLETE}return e.state!==h.COMPLETE}});u.TYPES=["onActive","onComplete","onLoop","onRepeat","onStart","onUpdate","onYoyo"],a.register("tween",function(t){return this.scene.sys.tweens.add(t)}),o.register("tween",function(t){return this.scene.sys.tweens.create(t)}),t.exports=u},function(t,e,i){t.exports={TIMELINE_COMPLETE:i(1351),TIMELINE_LOOP:i(1352),TIMELINE_PAUSE:i(1353),TIMELINE_RESUME:i(1354),TIMELINE_START:i(1355),TIMELINE_UPDATE:i(1356),TWEEN_ACTIVE:i(1357),TWEEN_COMPLETE:i(1358),TWEEN_LOOP:i(1359),TWEEN_REPEAT:i(1360),TWEEN_START:i(1361),TWEEN_UPDATE:i(1362),TWEEN_YOYO:i(1363)}},function(t,e){t.exports=function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p){return{target:t,index:e,key:i,getActiveValue:r,getEndValue:n,getStartValue:s,ease:o,duration:0,totalDuration:0,delay:0,yoyo:l,hold:0,repeat:0,repeatDelay:0,flipX:f,flipY:p,progress:0,elapsed:0,repeatCounter:0,start:0,previous:0,current:0,end:0,t1:0,t2:0,gen:{delay:a,duration:h,hold:u,repeat:c,repeatDelay:d},state:0}}},function(t,e){t.exports={DEFAULT:0,LINEAR:0,NEAREST:1}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-Math.PI,Math.PI)}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-180,180)}},function(t,e,i){var n=i(0),s=i(64),r=i(2),o=i(233),a=i(335),h=i(336),l=i(30),u=i(9),c=i(141),d=new n({Extends:c,Mixins:[o],initialize:function(t){var e=t.renderer.config;c.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:r(t,"topology",t.renderer.gl.TRIANGLES),vertShader:r(t,"vertShader",h),fragShader:r(t,"fragShader",a),vertexCapacity:r(t,"vertexCapacity",6*e.batchSize),vertexSize:r(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.tempTriangle=[{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0}],this.tintEffect=2,this.strokeTint={TL:0,TR:0,BL:0,BR:0},this.fillTint={TL:0,TR:0,BL:0,BR:0},this.currentFrame={u0:0,v0:0,u1:1,v1:1},this.firstQuad=[0,0,0,0,0],this.prevQuad=[0,0,0,0,0],this.polygonCache=[],this.mvpInit()},onBind:function(){return c.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return c.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this},batchSprite:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix1,s=this._tempMatrix2,r=this._tempMatrix3,o=t.frame,a=o.glTexture,h=o.u0,l=o.v0,c=o.u1,d=o.v1,f=o.x,p=o.y,g=o.cutWidth,v=o.cutHeight,m=o.customPivot,y=t.displayOriginX,x=t.displayOriginY,T=-y+f,w=-x+p;if(t.isCropped){var b=t._crop;b.flipX===t.flipX&&b.flipY===t.flipY||o.updateCropUVs(b,t.flipX,t.flipY),h=b.u0,l=b.v0,c=b.u1,d=b.v1,g=b.width,v=b.height,T=-y+(f=b.x),w=-x+(p=b.y)}var E=1,S=1;t.flipX&&(m||(T+=-o.realWidth+2*y),E=-1),(t.flipY||o.source.isGLTexture&&!a.flipY)&&(m||(w+=-o.realHeight+2*x),S=-1),s.applyITRS(t.x,t.y,t.rotation,t.scaleX*E,t.scaleY*S),n.copyFrom(e.matrix),i?(n.multiplyWithOffset(i,-e.scrollX*t.scrollFactorX,-e.scrollY*t.scrollFactorY),s.e=t.x,s.f=t.y,n.multiply(s,r)):(s.e-=e.scrollX*t.scrollFactorX,s.f-=e.scrollY*t.scrollFactorY,n.multiply(s,r));var A=T+g,_=w+v,C=r.getX(T,w),M=r.getY(T,w),O=r.getX(T,_),P=r.getY(T,_),R=r.getX(A,_),L=r.getY(A,_),D=r.getX(A,w),F=r.getY(A,w),k=u.getTintAppendFloatAlpha(t._tintTL,e.alpha*t._alphaTL),I=u.getTintAppendFloatAlpha(t._tintTR,e.alpha*t._alphaTR),B=u.getTintAppendFloatAlpha(t._tintBL,e.alpha*t._alphaBL),Y=u.getTintAppendFloatAlpha(t._tintBR,e.alpha*t._alphaBR);e.roundPixels&&(C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P),R=Math.round(R),L=Math.round(L),D=Math.round(D),F=Math.round(F)),this.setTexture2D(a,0);var N=t._isTinted&&t.tintFill;this.batchQuad(C,M,O,P,R,L,D,F,h,l,c,d,k,I,B,Y,N,a,0)},batchQuad:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y){var x=!1;this.vertexCount+6>this.vertexCapacity&&(this.flush(),x=!0,this.setTexture2D(m,y));var T=this.vertexViewF32,w=this.vertexViewU32,b=this.vertexCount*this.vertexComponentCount-1;return T[++b]=t,T[++b]=e,T[++b]=h,T[++b]=l,T[++b]=v,w[++b]=d,T[++b]=i,T[++b]=n,T[++b]=h,T[++b]=c,T[++b]=v,w[++b]=p,T[++b]=s,T[++b]=r,T[++b]=u,T[++b]=c,T[++b]=v,w[++b]=g,T[++b]=t,T[++b]=e,T[++b]=h,T[++b]=l,T[++b]=v,w[++b]=d,T[++b]=s,T[++b]=r,T[++b]=u,T[++b]=c,T[++b]=v,w[++b]=g,T[++b]=o,T[++b]=a,T[++b]=u,T[++b]=l,T[++b]=v,w[++b]=f,this.vertexCount+=6,x},batchTri:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g){var v=!1;this.vertexCount+3>this.vertexCapacity&&(this.flush(),this.setTexture2D(p,g),v=!0);var m=this.vertexViewF32,y=this.vertexViewU32,x=this.vertexCount*this.vertexComponentCount-1;return m[++x]=t,m[++x]=e,m[++x]=o,m[++x]=a,m[++x]=f,y[++x]=u,m[++x]=i,m[++x]=n,m[++x]=o,m[++x]=l,m[++x]=f,y[++x]=c,m[++x]=s,m[++x]=r,m[++x]=h,m[++x]=l,m[++x]=f,y[++x]=d,this.vertexCount+=3,v},batchTexture:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y,x,T,w,b,E,S,A,_,C,M,O,P){this.renderer.setPipeline(this,t);var R=this._tempMatrix1,L=this._tempMatrix2,D=this._tempMatrix3,F=m/i+_,k=y/n+C,I=(m+x)/i+_,B=(y+T)/n+C,Y=o,N=a,X=-g,z=-v;if(t.isCropped){var U=t._crop;Y=U.width,N=U.height,o=U.width,a=U.height;var G=m=U.x,W=y=U.y;c&&(G=x-U.x-U.width),d&&!e.isRenderTexture&&(W=T-U.y-U.height),F=G/i+_,k=W/n+C,I=(G+U.width)/i+_,B=(W+U.height)/n+C,X=-g+m,z=-v+y}d^=!P&&e.isRenderTexture?1:0,c&&(Y*=-1,X+=o),d&&(N*=-1,z+=a);var V=X+Y,H=z+N;L.applyITRS(s,r,u,h,l),R.copyFrom(M.matrix),O?(R.multiplyWithOffset(O,-M.scrollX*f,-M.scrollY*p),L.e=s,L.f=r,R.multiply(L,D)):(L.e-=M.scrollX*f,L.f-=M.scrollY*p,R.multiply(L,D));var j=D.getX(X,z),q=D.getY(X,z),K=D.getX(X,H),J=D.getY(X,H),Z=D.getX(V,H),Q=D.getY(V,H),$=D.getX(V,z),tt=D.getY(V,z);M.roundPixels&&(j=Math.round(j),q=Math.round(q),K=Math.round(K),J=Math.round(J),Z=Math.round(Z),Q=Math.round(Q),$=Math.round($),tt=Math.round(tt)),this.setTexture2D(e,0),this.batchQuad(j,q,K,J,Z,Q,$,tt,F,k,I,B,w,b,E,S,A,e,0)},batchTextureFrame:function(t,e,i,n,s,r,o){this.renderer.setPipeline(this);var a=this._tempMatrix1.copyFrom(r),h=this._tempMatrix2,l=e+t.width,c=i+t.height;o?a.multiply(o,h):h=a;var d=h.getX(e,i),f=h.getY(e,i),p=h.getX(e,c),g=h.getY(e,c),v=h.getX(l,c),m=h.getY(l,c),y=h.getX(l,i),x=h.getY(l,i);this.setTexture2D(t.glTexture,0),n=u.getTintAppendFloatAlpha(n,s),this.batchQuad(d,f,p,g,v,m,y,x,t.u0,t.v0,t.u1,t.v1,n,n,n,n,0,t.glTexture,0)},drawFillRect:function(t,e,i,n,s,r){var o=t+i,a=e+n;this.setTexture2D();var h=u.getTintAppendFloatAlphaAndSwap(s,r);this.batchQuad(t,e,t,a,o,a,o,e,0,0,1,1,h,h,h,h,2)},batchFillRect:function(t,e,i,n,s,r){this.renderer.setPipeline(this);var o=this._tempMatrix3;r&&r.multiply(s,o);var a=t+i,h=e+n,l=o.getX(t,e),u=o.getY(t,e),c=o.getX(t,h),d=o.getY(t,h),f=o.getX(a,h),p=o.getY(a,h),g=o.getX(a,e),v=o.getY(a,e),m=this.currentFrame,y=m.u0,x=m.v0,T=m.u1,w=m.v1;this.batchQuad(l,u,c,d,f,p,g,v,y,x,T,w,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.fillTint.BR,this.tintEffect)},batchFillTriangle:function(t,e,i,n,s,r,o,a){this.renderer.setPipeline(this);var h=this._tempMatrix3;a&&a.multiply(o,h);var l=h.getX(t,e),u=h.getY(t,e),c=h.getX(i,n),d=h.getY(i,n),f=h.getX(s,r),p=h.getY(s,r),g=this.currentFrame,v=g.u0,m=g.v0,y=g.u1,x=g.v1;this.batchTri(l,u,c,d,f,p,v,m,y,x,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.tintEffect)},batchStrokeTriangle:function(t,e,i,n,s,r,o,a,h){var l=this.tempTriangle;l[0].x=t,l[0].y=e,l[0].width=o,l[1].x=i,l[1].y=n,l[1].width=o,l[2].x=s,l[2].y=r,l[2].width=o,l[3].x=t,l[3].y=e,l[3].width=o,this.batchStrokePath(l,o,!1,a,h)},batchFillPath:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix3;i&&i.multiply(e,n);for(var r,o,a=t.length,h=this.polygonCache,l=this.fillTint.TL,u=this.fillTint.TR,c=this.fillTint.BL,d=this.tintEffect,f=0;f0&&H[4]?this.batchQuad(D,F,O,P,H[0],H[1],H[2],H[3],U,G,W,V,B,Y,N,X,I):(j[0]=D,j[1]=F,j[2]=O,j[3]=P,j[4]=1),h&&j[4]?this.batchQuad(C,M,R,L,j[0],j[1],j[2],j[3],U,G,W,V,B,Y,N,X,I):(H[0]=C,H[1]=M,H[2]=R,H[3]=L,H[4]=1)}}});t.exports=d},function(t,e){var i={modelMatrixDirty:!1,viewMatrixDirty:!1,projectionMatrixDirty:!1,modelMatrix:null,viewMatrix:null,projectionMatrix:null,mvpInit:function(){return this.modelMatrixDirty=!0,this.viewMatrixDirty=!0,this.projectionMatrixDirty=!0,this.modelMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.viewMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.projectionMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this},mvpUpdate:function(){var t=this.program;return this.modelMatrixDirty&&(this.renderer.setMatrix4(t,"uModelMatrix",!1,this.modelMatrix),this.modelMatrixDirty=!1),this.viewMatrixDirty&&(this.renderer.setMatrix4(t,"uViewMatrix",!1,this.viewMatrix),this.viewMatrixDirty=!1),this.projectionMatrixDirty&&(this.renderer.setMatrix4(t,"uProjectionMatrix",!1,this.projectionMatrix),this.projectionMatrixDirty=!1),this},modelIdentity:function(){var t=this.modelMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.modelMatrixDirty=!0,this},modelScale:function(t,e,i){var n=this.modelMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.modelMatrixDirty=!0,this},modelTranslate:function(t,e,i){var n=this.modelMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.modelMatrixDirty=!0,this},modelRotateX:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.modelMatrixDirty=!0,this},modelRotateY:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.modelMatrixDirty=!0,this},modelRotateZ:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.modelMatrixDirty=!0,this},viewIdentity:function(){var t=this.viewMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.viewMatrixDirty=!0,this},viewScale:function(t,e,i){var n=this.viewMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.viewMatrixDirty=!0,this},viewTranslate:function(t,e,i){var n=this.viewMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.viewMatrixDirty=!0,this},viewRotateX:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.viewMatrixDirty=!0,this},viewRotateY:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.viewMatrixDirty=!0,this},viewRotateZ:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.viewMatrixDirty=!0,this},viewLoad2D:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=0,e[3]=0,e[4]=t[2],e[5]=t[3],e[6]=0,e[7]=0,e[8]=t[4],e[9]=t[5],e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this.viewMatrixDirty=!0,this},viewLoad:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this.viewMatrixDirty=!0,this},projIdentity:function(){var t=this.projectionMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.projectionMatrixDirty=!0,this},projOrtho:function(t,e,i,n,s,r){var o=this.projectionMatrix,a=1/(t-e),h=1/(i-n),l=1/(s-r);return o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this.projectionMatrixDirty=!0,this},projPersp:function(t,e,i,n){var s=this.projectionMatrix,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this.projectionMatrixDirty=!0,this}};t.exports=i},function(t,e,i){var n={};t.exports=n;var s=i(235);n._motionWakeThreshold=.18,n._motionSleepThreshold=.08,n._minBias=.9,n.update=function(t,e){for(var i=e*e*e,s=0;s0&&r.motion=r.sleepThreshold&&n.set(r,!0)):r.sleepCounter>0&&(r.sleepCounter-=1)}else n.set(r,!1)}},n.afterCollisions=function(t,e){for(var i=e*e*e,s=0;sn._motionWakeThreshold*i&&n.set(l,!1)}}}},n.set=function(t,e){var i=t.isSleeping;e?(t.isSleeping=!0,t.sleepCounter=t.sleepThreshold,t.positionImpulse.x=0,t.positionImpulse.y=0,t.positionPrev.x=t.position.x,t.positionPrev.y=t.position.y,t.anglePrev=t.angle,t.speed=0,t.angularSpeed=0,t.motion=0,i||s.trigger(t,"sleepStart")):(t.isSleeping=!1,t.sleepCounter=0,i&&s.trigger(t,"sleepEnd"))}},function(t,e,i){var n={};t.exports=n;var s=i(37);n.on=function(t,e,i){for(var n,s=e.split(" "),r=0;r0){i||(i={}),n=e.split(" ");for(var l=0;le.length&&(r=e.length),i?(n=e[r-1][i],(s=e[r][i])-t<=t-n?e[r]:e[r-1]):(n=e[r-1],(s=e[r])-t<=t-n?s:n)}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.textureKey=t,this.textureFrame=e,this.index=i,this.frame=n,this.isFirst=!1,this.isLast=!1,this.prevFrame=null,this.nextFrame=null,this.duration=0,this.progress=0},toJSON:function(){return{key:this.textureKey,frame:this.textureFrame,duration:this.duration}},destroy:function(){this.frame=void 0}});t.exports=n},function(t,e,i){var n=i(52),s={_blendMode:n.NORMAL,blendMode:{get:function(){return this._blendMode},set:function(t){"string"==typeof t&&(t=n[t]),(t|=0)>=-1&&(this._blendMode=t)}},setBlendMode:function(t){return this.blendMode=t,this}};t.exports=s},function(t,e){var i={_depth:0,depth:{get:function(){return this._depth},set:function(t){this.scene.sys.queueDepthSort(),this._depth=t}},setDepth:function(t){return void 0===t&&(t=0),this.depth=t,this}};t.exports=i},function(t,e,i){var n=i(146),s=i(108);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=s(t)/i);for(var o=0;o=t.right&&(h=1,a+=o-t.right,o=t.right);break;case 1:(a+=e)>=t.bottom&&(h=2,o-=a-t.bottom,a=t.bottom);break;case 2:(o-=e)<=t.left&&(h=3,a-=t.left-o,o=t.left);break;case 3:(a-=e)<=t.top&&(h=0,a=t.top)}return r}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);for(var i=null,n=0;n-h&&(c-=h,n+=l),fd.right&&(f=u(f,f+(g-d.right),this.lerp.x)),vd.bottom&&(p=u(p,p+(v-d.bottom),this.lerp.y))):(f=u(f,g-h,this.lerp.x),p=u(p,v-l,this.lerp.y))}this.useBounds&&(f=this.clampX(f),p=this.clampY(p)),this.roundPixels&&(h=Math.round(h),l=Math.round(l)),this.scrollX=f,this.scrollY=p;var m=f+n,y=p+s;this.midPoint.set(m,y);var x=e/o,T=i/o;this.worldView.setTo(m-x/2,y-T/2,x,T),a.applyITRS(this.x+h,this.y+l,this.rotation,o,o),a.translate(-h,-l),this.shakeEffect.preRender()},setLerp:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=t),this.lerp.set(t,e),this},setFollowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.followOffset.set(t,e),this},startFollow:function(t,e,i,n,s,r){void 0===e&&(e=!1),void 0===i&&(i=1),void 0===n&&(n=i),void 0===s&&(s=0),void 0===r&&(r=s),this._follow=t,this.roundPixels=e,i=o(i,0,1),n=o(n,0,1),this.lerp.set(i,n),this.followOffset.set(s,r);var a=this.width/2,h=this.height/2,l=t.x-s,u=t.y-r;return this.midPoint.set(l,u),this.scrollX=l-a,this.scrollY=u-h,this.useBounds&&(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},stopFollow:function(){return this._follow=null,this},resetFX:function(){return this.panEffect.reset(),this.shakeEffect.reset(),this.flashEffect.reset(),this.fadeEffect.reset(),this},update:function(t,e){this.visible&&(this.panEffect.update(t,e),this.zoomEffect.update(t,e),this.shakeEffect.update(t,e),this.flashEffect.update(t,e),this.fadeEffect.update(t,e))},destroy:function(){this.clearRenderToTexture(),this.resetFX(),n.prototype.destroy.call(this),this._follow=null,this.deadzone=null}});t.exports=f},function(t,e,i){var n=i(32);t.exports=function(t){var e=new n;t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,n){return e+e+i+i+n+n});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e.setTo(s,r,o)}return e}},function(t,e){t.exports=function(t,e,i,n){return n<<24|t<<16|e<<8|i}},function(t,e){t.exports=function(t,e,i,n){void 0===n&&(n={h:0,s:0,v:0}),t/=255,e/=255,i/=255;var s=Math.min(t,e,i),r=Math.max(t,e,i),o=r-s,a=0,h=0===r?0:o/r,l=r;return r!==s&&(r===t?a=(e-i)/o+(e16777215?{a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{a:255,r:t>>16&255,g:t>>8&255,b:255&t}}},function(t,e,i){var n=i(32);t.exports=function(t){return new n(t.r,t.g,t.b,t.a)}},function(t,e,i){var n=i(32);t.exports=function(t){var e=new n,i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t.toLowerCase());if(i){var s=parseInt(i[1],10),r=parseInt(i[2],10),o=parseInt(i[3],10),a=void 0!==i[4]?parseFloat(i[4]):1;e.setTo(s,r,o,255*a)}return e}},function(t,e,i){t.exports={Fade:i(657),Flash:i(658),Pan:i(659),Shake:i(692),Zoom:i(693)}},function(t,e,i){t.exports={In:i(660),Out:i(661),InOut:i(662)}},function(t,e,i){t.exports={In:i(663),Out:i(664),InOut:i(665)}},function(t,e,i){t.exports={In:i(666),Out:i(667),InOut:i(668)}},function(t,e,i){t.exports={In:i(669),Out:i(670),InOut:i(671)}},function(t,e,i){t.exports={In:i(672),Out:i(673),InOut:i(674)}},function(t,e,i){t.exports={In:i(675),Out:i(676),InOut:i(677)}},function(t,e,i){t.exports=i(678)},function(t,e,i){t.exports={In:i(679),Out:i(680),InOut:i(681)}},function(t,e,i){t.exports={In:i(682),Out:i(683),InOut:i(684)}},function(t,e,i){t.exports={In:i(685),Out:i(686),InOut:i(687)}},function(t,e,i){t.exports={In:i(688),Out:i(689),InOut:i(690)}},function(t,e,i){t.exports=i(691)},function(t,e,i){var n=i(0),s=i(10),r=i(310),o=i(2),a=i(6),h=i(7),l=i(165),u=i(1),c=i(170),d=i(158),f=new n({initialize:function(t){void 0===t&&(t={});this.width=a(t,"width",1024),this.height=a(t,"height",768),this.zoom=a(t,"zoom",1),this.resolution=a(t,"resolution",1),this.parent=a(t,"parent",void 0),this.scaleMode=a(t,"scaleMode",0),this.expandParent=a(t,"expandParent",!0),this.autoRound=a(t,"autoRound",!1),this.autoCenter=a(t,"autoCenter",0),this.resizeInterval=a(t,"resizeInterval",500),this.fullscreenTarget=a(t,"fullscreenTarget",null),this.minWidth=a(t,"minWidth",0),this.maxWidth=a(t,"maxWidth",0),this.minHeight=a(t,"minHeight",0),this.maxHeight=a(t,"maxHeight",0);var e=a(t,"scale",null);e&&(this.width=a(e,"width",this.width),this.height=a(e,"height",this.height),this.zoom=a(e,"zoom",this.zoom),this.resolution=a(e,"resolution",this.resolution),this.parent=a(e,"parent",this.parent),this.scaleMode=a(e,"mode",this.scaleMode),this.expandParent=a(e,"expandParent",this.expandParent),this.autoRound=a(e,"autoRound",this.autoRound),this.autoCenter=a(e,"autoCenter",this.autoCenter),this.resizeInterval=a(e,"resizeInterval",this.resizeInterval),this.fullscreenTarget=a(e,"fullscreenTarget",this.fullscreenTarget),this.minWidth=a(e,"min.width",this.minWidth),this.maxWidth=a(e,"max.width",this.maxWidth),this.minHeight=a(e,"min.height",this.minHeight),this.maxHeight=a(e,"max.height",this.maxHeight)),this.renderType=a(t,"type",s.AUTO),this.canvas=a(t,"canvas",null),this.context=a(t,"context",null),this.canvasStyle=a(t,"canvasStyle",null),this.customEnvironment=a(t,"customEnvironment",!1),this.sceneConfig=a(t,"scene",null),this.seed=a(t,"seed",[(Date.now()*Math.random()).toString()]),l.RND=new l.RandomDataGenerator(this.seed),this.gameTitle=a(t,"title",""),this.gameURL=a(t,"url","https://phaser.io"),this.gameVersion=a(t,"version",""),this.autoFocus=a(t,"autoFocus",!0),this.domCreateContainer=a(t,"dom.createContainer",!1),this.domBehindCanvas=a(t,"dom.behindCanvas",!1),this.inputKeyboard=a(t,"input.keyboard",!0),this.inputKeyboardEventTarget=a(t,"input.keyboard.target",window),this.inputKeyboardCapture=a(t,"input.keyboard.capture",[]),this.inputMouse=a(t,"input.mouse",!0),this.inputMouseEventTarget=a(t,"input.mouse.target",null),this.inputMouseCapture=a(t,"input.mouse.capture",!0),this.inputTouch=a(t,"input.touch",r.input.touch),this.inputTouchEventTarget=a(t,"input.touch.target",null),this.inputTouchCapture=a(t,"input.touch.capture",!0),this.inputActivePointers=a(t,"input.activePointers",1),this.inputSmoothFactor=a(t,"input.smoothFactor",0),this.inputWindowEvents=a(t,"input.windowEvents",!0),this.inputGamepad=a(t,"input.gamepad",!1),this.inputGamepadEventTarget=a(t,"input.gamepad.target",window),this.disableContextMenu=a(t,"disableContextMenu",!1),this.audio=a(t,"audio"),this.hideBanner=!1===a(t,"banner",null),this.hidePhaser=a(t,"banner.hidePhaser",!1),this.bannerTextColor=a(t,"banner.text","#ffffff"),this.bannerBackgroundColor=a(t,"banner.background",["#ff0000","#ffff00","#00ff00","#00ffff","#000000"]),""===this.gameTitle&&this.hidePhaser&&(this.hideBanner=!0),this.fps=a(t,"fps",null);var i=a(t,"render",t);this.antialias=a(i,"antialias",!0),this.antialiasGL=a(i,"antialiasGL",!0),this.mipmapFilter=a(i,"mipmapFilter","LINEAR"),this.desynchronized=a(i,"desynchronized",!1),this.roundPixels=a(i,"roundPixels",!1),this.pixelArt=a(i,"pixelArt",1!==this.zoom),this.pixelArt&&(this.antialias=!1,this.roundPixels=!0),this.transparent=a(i,"transparent",!1),this.clearBeforeRender=a(i,"clearBeforeRender",!0),this.premultipliedAlpha=a(i,"premultipliedAlpha",!0),this.failIfMajorPerformanceCaveat=a(i,"failIfMajorPerformanceCaveat",!1),this.powerPreference=a(i,"powerPreference","default"),this.batchSize=a(i,"batchSize",2e3),this.maxLights=a(i,"maxLights",10);var n=a(t,"backgroundColor",0);this.backgroundColor=d(n),0===n&&this.transparent&&(this.backgroundColor.alpha=0),this.preBoot=a(t,"callbacks.preBoot",u),this.postBoot=a(t,"callbacks.postBoot",u),this.physics=a(t,"physics",{}),this.defaultPhysicsSystem=a(this.physics,"default",!1),this.loaderBaseURL=a(t,"loader.baseURL",""),this.loaderPath=a(t,"loader.path",""),this.loaderMaxParallelDownloads=a(t,"loader.maxParallelDownloads",32),this.loaderCrossOrigin=a(t,"loader.crossOrigin",void 0),this.loaderResponseType=a(t,"loader.responseType",""),this.loaderAsync=a(t,"loader.async",!0),this.loaderUser=a(t,"loader.user",""),this.loaderPassword=a(t,"loader.password",""),this.loaderTimeout=a(t,"loader.timeout",0),this.loaderWithCredentials=a(t,"loader.withCredentials",!1),this.installGlobalPlugins=[],this.installScenePlugins=[];var f=a(t,"plugins",null),p=c.DefaultScene;f&&(Array.isArray(f)?this.defaultPlugins=f:h(f)&&(this.installGlobalPlugins=o(f,"global",[]),this.installScenePlugins=o(f,"scene",[]),Array.isArray(f.default)?p=f.default:Array.isArray(f.defaultMerge)&&(p=p.concat(f.defaultMerge)))),this.defaultPlugins=p;var g="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg";this.defaultImage=a(t,"images.default",g+"AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="),this.missingImage=a(t,"images.missing",g+"CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="),window&&(window.FORCE_WEBGL?this.renderType=s.WEBGL:window.FORCE_CANVAS&&(this.renderType=s.CANVAS))}});t.exports=f},function(t,e,i){t.exports={os:i(112),browser:i(113),features:i(164),input:i(722),audio:i(723),video:i(724),fullscreen:i(725),canvasFeatures:i(311)}},function(t,e,i){var n,s,r,o=i(27),a={supportInverseAlpha:!1,supportNewBlendModes:!1};t.exports=(void 0!==document&&(a.supportNewBlendModes=(n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",s="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",(r=new Image).onload=function(){var t=new Image;t.onload=function(){var e=o.create(t,6,1).getContext("2d");if(e.globalCompositeOperation="multiply",e.drawImage(r,0,0),e.drawImage(t,2,0),!e.getImageData(2,0,1,1))return!1;var i=e.getImageData(2,0,1,1).data;o.remove(t),a.supportNewBlendModes=255===i[0]&&0===i[1]&&0===i[2]},t.src=n+"/wCKxvRF"+s},r.src=n+"AP804Oa6"+s,!1),a.supportInverseAlpha=function(){var t=o.create(this,2,1).getContext("2d");t.fillStyle="rgba(10, 20, 30, 0.5)",t.fillRect(0,0,1,1);var e=t.getImageData(0,0,1,1);if(null===e)return!1;t.putImageData(e,1,0);var i=t.getImageData(1,0,1,1);return i.data[0]===e.data[0]&&i.data[1]===e.data[1]&&i.data[2]===e.data[2]&&i.data[3]===e.data[3]}()),a)},function(t,e){t.exports=function(t,e,i,n){return Math.atan2(n-e,i-t)}},function(t,e){t.exports=function(t){return(t%=2*Math.PI)>=0?t:t+2*Math.PI}},function(t,e){t.exports=function(t,e){var i=t.x-e.x,n=t.y-e.y;return Math.sqrt(i*i+n*n)}},function(t,e){t.exports=function(t,e,i,n){var s=t-i,r=e-n;return s*s+r*r}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t>e-i}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t0?Math.ceil(t):Math.floor(t)}},function(t,e,i){var n=i(3);t.exports=function(t,e,i,s,r,o,a,h){void 0===h&&(h=new n);var l=Math.sin(r),u=Math.cos(r),c=u*o,d=l*o,f=-l*a,p=u*a,g=1/(c*p+f*-d);return h.x=p*g*t+-f*g*e+(s*f-i*p)*g,h.y=c*g*e+-d*g*t+(-s*c+i*d)*g,h}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.x=0,this.y=0,this.z=0,this.w=0,"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},clone:function(){return new n(this.x,this.y,this.z,this.w)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z||0,this.w=t.w||0,this},equals:function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z||0,this.w+=t.w||0,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z||0,this.w-=t.w||0,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z||1,this.w*=t.w||1,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z||1,this.w/=t.w||1,this},distance:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return Math.sqrt(e*e+i*i+n*n+s*s)},distanceSq:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return e*e+i*i+n*n+s*s},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.val;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},reset:function(){return this.x=0,this.y=0,this.z=0,this.w=0,this}});n.prototype.sub=n.prototype.subtract,n.prototype.mul=n.prototype.multiply,n.prototype.div=n.prototype.divide,n.prototype.dist=n.prototype.distance,n.prototype.distSq=n.prototype.distanceSq,n.prototype.len=n.prototype.length,n.prototype.lenSq=n.prototype.lengthSq,t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(9),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this},fromMat4:function(t){var e=t.val,i=this.val;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[5];return t[1]=t[3],t[2]=t[6],t[3]=e,t[5]=t[7],t[6]=i,t[7]=n,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=l*r-o*h,c=-l*s+o*a,d=h*s-r*a,f=e*u+i*c+n*d;return f?(f=1/f,t[0]=u*f,t[1]=(-l*i+n*h)*f,t[2]=(o*i-n*r)*f,t[3]=c*f,t[4]=(l*e-n*a)*f,t[5]=(-o*e+n*s)*f,t[6]=d*f,t[7]=(-h*e+i*a)*f,t[8]=(r*e-i*s)*f,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return t[0]=r*l-o*h,t[1]=n*h-i*l,t[2]=i*o-n*r,t[3]=o*a-s*l,t[4]=e*l-n*a,t[5]=n*s-e*o,t[6]=s*h-r*a,t[7]=i*a-e*h,t[8]=e*r-i*s,this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*(l*r-o*h)+i*(-l*s+o*a)+n*(h*s-r*a)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=t.val,d=c[0],f=c[1],p=c[2],g=c[3],v=c[4],m=c[5],y=c[6],x=c[7],T=c[8];return e[0]=d*i+f*r+p*h,e[1]=d*n+f*o+p*l,e[2]=d*s+f*a+p*u,e[3]=g*i+v*r+m*h,e[4]=g*n+v*o+m*l,e[5]=g*s+v*a+m*u,e[6]=y*i+x*r+T*h,e[7]=y*n+x*o+T*l,e[8]=y*s+x*a+T*u,this},translate:function(t){var e=this.val,i=t.x,n=t.y;return e[6]=i*e[0]+n*e[3]+e[6],e[7]=i*e[1]+n*e[4]+e[7],e[8]=i*e[2]+n*e[5]+e[8],this},rotate:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=Math.sin(t),l=Math.cos(t);return e[0]=l*i+h*r,e[1]=l*n+h*o,e[2]=l*s+h*a,e[3]=l*r-h*i,e[4]=l*o-h*n,e[5]=l*a-h*s,this},scale:function(t){var e=this.val,i=t.x,n=t.y;return e[0]=i*e[0],e[1]=i*e[1],e[2]=i*e[2],e[3]=n*e[3],e[4]=n*e[4],e[5]=n*e[5],this},fromQuat:function(t){var e=t.x,i=t.y,n=t.z,s=t.w,r=e+e,o=i+i,a=n+n,h=e*r,l=e*o,u=e*a,c=i*o,d=i*a,f=n*a,p=s*r,g=s*o,v=s*a,m=this.val;return m[0]=1-(c+f),m[3]=l+v,m[6]=u-g,m[1]=l-v,m[4]=1-(h+f),m[7]=d+p,m[2]=u+g,m[5]=d-p,m[8]=1-(h+c),this},normalFromMat4:function(t){var e=t.val,i=this.val,n=e[0],s=e[1],r=e[2],o=e[3],a=e[4],h=e[5],l=e[6],u=e[7],c=e[8],d=e[9],f=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=n*h-s*a,T=n*l-r*a,w=n*u-o*a,b=s*l-r*h,E=s*u-o*h,S=r*u-o*l,A=c*v-d*g,_=c*m-f*g,C=c*y-p*g,M=d*m-f*v,O=d*y-p*v,P=f*y-p*m,R=x*P-T*O+w*M+b*C-E*_+S*A;return R?(R=1/R,i[0]=(h*P-l*O+u*M)*R,i[1]=(l*C-a*P-u*_)*R,i[2]=(a*O-h*C+u*A)*R,i[3]=(r*O-s*P-o*M)*R,i[4]=(n*P-r*C+o*_)*R,i[5]=(s*C-n*O-o*A)*R,i[6]=(v*S-m*E+y*b)*R,i[7]=(m*w-g*S-y*T)*R,i[8]=(g*E-v*w+y*x)*R,this):null}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(16),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},zero:function(){var t=this.val;return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=0,this},xyz:function(t,e,i){this.identity();var n=this.val;return n[12]=t,n[13]=e,n[14]=i,this},scaling:function(t,e,i){this.zero();var n=this.val;return n[0]=t,n[5]=e,n[10]=i,n[15]=1,this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[3],s=t[6],r=t[7],o=t[11];return t[1]=t[4],t[2]=t[8],t[3]=t[12],t[4]=e,t[6]=t[9],t[7]=t[13],t[8]=i,t[9]=s,t[11]=t[14],t[12]=n,t[13]=r,t[14]=o,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15],m=e*o-i*r,y=e*a-n*r,x=e*h-s*r,T=i*a-n*o,w=i*h-s*o,b=n*h-s*a,E=l*p-u*f,S=l*g-c*f,A=l*v-d*f,_=u*g-c*p,C=u*v-d*p,M=c*v-d*g,O=m*M-y*C+x*_+T*A-w*S+b*E;return O?(O=1/O,t[0]=(o*M-a*C+h*_)*O,t[1]=(n*C-i*M-s*_)*O,t[2]=(p*b-g*w+v*T)*O,t[3]=(c*w-u*b-d*T)*O,t[4]=(a*A-r*M-h*S)*O,t[5]=(e*M-n*A+s*S)*O,t[6]=(g*x-f*b-v*y)*O,t[7]=(l*b-c*x+d*y)*O,t[8]=(r*C-o*A+h*E)*O,t[9]=(i*A-e*C-s*E)*O,t[10]=(f*w-p*x+v*m)*O,t[11]=(u*x-l*w-d*m)*O,t[12]=(o*S-r*_-a*E)*O,t[13]=(e*_-i*S+n*E)*O,t[14]=(p*y-f*T-g*m)*O,t[15]=(l*T-u*y+c*m)*O,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return t[0]=o*(c*v-d*g)-u*(a*v-h*g)+p*(a*d-h*c),t[1]=-(i*(c*v-d*g)-u*(n*v-s*g)+p*(n*d-s*c)),t[2]=i*(a*v-h*g)-o*(n*v-s*g)+p*(n*h-s*a),t[3]=-(i*(a*d-h*c)-o*(n*d-s*c)+u*(n*h-s*a)),t[4]=-(r*(c*v-d*g)-l*(a*v-h*g)+f*(a*d-h*c)),t[5]=e*(c*v-d*g)-l*(n*v-s*g)+f*(n*d-s*c),t[6]=-(e*(a*v-h*g)-r*(n*v-s*g)+f*(n*h-s*a)),t[7]=e*(a*d-h*c)-r*(n*d-s*c)+l*(n*h-s*a),t[8]=r*(u*v-d*p)-l*(o*v-h*p)+f*(o*d-h*u),t[9]=-(e*(u*v-d*p)-l*(i*v-s*p)+f*(i*d-s*u)),t[10]=e*(o*v-h*p)-r*(i*v-s*p)+f*(i*h-s*o),t[11]=-(e*(o*d-h*u)-r*(i*d-s*u)+l*(i*h-s*o)),t[12]=-(r*(u*g-c*p)-l*(o*g-a*p)+f*(o*c-a*u)),t[13]=e*(u*g-c*p)-l*(i*g-n*p)+f*(i*c-n*u),t[14]=-(e*(o*g-a*p)-r*(i*g-n*p)+f*(i*a-n*o)),t[15]=e*(o*c-a*u)-r*(i*c-n*u)+l*(i*a-n*o),this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return(e*o-i*r)*(c*v-d*g)-(e*a-n*r)*(u*v-d*p)+(e*h-s*r)*(u*g-c*p)+(i*a-n*o)*(l*v-d*f)-(i*h-s*o)*(l*g-c*f)+(n*h-s*a)*(l*p-u*f)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=e[9],d=e[10],f=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=t.val,x=y[0],T=y[1],w=y[2],b=y[3];return e[0]=x*i+T*o+w*u+b*p,e[1]=x*n+T*a+w*c+b*g,e[2]=x*s+T*h+w*d+b*v,e[3]=x*r+T*l+w*f+b*m,x=y[4],T=y[5],w=y[6],b=y[7],e[4]=x*i+T*o+w*u+b*p,e[5]=x*n+T*a+w*c+b*g,e[6]=x*s+T*h+w*d+b*v,e[7]=x*r+T*l+w*f+b*m,x=y[8],T=y[9],w=y[10],b=y[11],e[8]=x*i+T*o+w*u+b*p,e[9]=x*n+T*a+w*c+b*g,e[10]=x*s+T*h+w*d+b*v,e[11]=x*r+T*l+w*f+b*m,x=y[12],T=y[13],w=y[14],b=y[15],e[12]=x*i+T*o+w*u+b*p,e[13]=x*n+T*a+w*c+b*g,e[14]=x*s+T*h+w*d+b*v,e[15]=x*r+T*l+w*f+b*m,this},multiplyLocal:function(t){var e=[],i=this.val,n=t.val;return e[0]=i[0]*n[0]+i[1]*n[4]+i[2]*n[8]+i[3]*n[12],e[1]=i[0]*n[1]+i[1]*n[5]+i[2]*n[9]+i[3]*n[13],e[2]=i[0]*n[2]+i[1]*n[6]+i[2]*n[10]+i[3]*n[14],e[3]=i[0]*n[3]+i[1]*n[7]+i[2]*n[11]+i[3]*n[15],e[4]=i[4]*n[0]+i[5]*n[4]+i[6]*n[8]+i[7]*n[12],e[5]=i[4]*n[1]+i[5]*n[5]+i[6]*n[9]+i[7]*n[13],e[6]=i[4]*n[2]+i[5]*n[6]+i[6]*n[10]+i[7]*n[14],e[7]=i[4]*n[3]+i[5]*n[7]+i[6]*n[11]+i[7]*n[15],e[8]=i[8]*n[0]+i[9]*n[4]+i[10]*n[8]+i[11]*n[12],e[9]=i[8]*n[1]+i[9]*n[5]+i[10]*n[9]+i[11]*n[13],e[10]=i[8]*n[2]+i[9]*n[6]+i[10]*n[10]+i[11]*n[14],e[11]=i[8]*n[3]+i[9]*n[7]+i[10]*n[11]+i[11]*n[15],e[12]=i[12]*n[0]+i[13]*n[4]+i[14]*n[8]+i[15]*n[12],e[13]=i[12]*n[1]+i[13]*n[5]+i[14]*n[9]+i[15]*n[13],e[14]=i[12]*n[2]+i[13]*n[6]+i[14]*n[10]+i[15]*n[14],e[15]=i[12]*n[3]+i[13]*n[7]+i[14]*n[11]+i[15]*n[15],this.fromArray(e)},translate:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[12]=s[0]*e+s[4]*i+s[8]*n+s[12],s[13]=s[1]*e+s[5]*i+s[9]*n+s[13],s[14]=s[2]*e+s[6]*i+s[10]*n+s[14],s[15]=s[3]*e+s[7]*i+s[11]*n+s[15],this},translateXYZ:function(t,e,i){var n=this.val;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this},scale:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[0]=s[0]*e,s[1]=s[1]*e,s[2]=s[2]*e,s[3]=s[3]*e,s[4]=s[4]*i,s[5]=s[5]*i,s[6]=s[6]*i,s[7]=s[7]*i,s[8]=s[8]*n,s[9]=s[9]*n,s[10]=s[10]*n,s[11]=s[11]*n,this},scaleXYZ:function(t,e,i){var n=this.val;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this},makeRotationAxis:function(t,e){var i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,o=t.y,a=t.z,h=s*r,l=s*o;return this.fromArray([h*r+i,h*o-n*a,h*a+n*o,0,h*o+n*a,l*o+i,l*a-n*r,0,h*a-n*o,l*a+n*r,s*a*a+i,0,0,0,0,1]),this},rotate:function(t,e){var i=this.val,n=e.x,s=e.y,r=e.z,o=Math.sqrt(n*n+s*s+r*r);if(Math.abs(o)<1e-6)return null;n*=o=1/o,s*=o,r*=o;var a=Math.sin(t),h=Math.cos(t),l=1-h,u=i[0],c=i[1],d=i[2],f=i[3],p=i[4],g=i[5],v=i[6],m=i[7],y=i[8],x=i[9],T=i[10],w=i[11],b=n*n*l+h,E=s*n*l+r*a,S=r*n*l-s*a,A=n*s*l-r*a,_=s*s*l+h,C=r*s*l+n*a,M=n*r*l+s*a,O=s*r*l-n*a,P=r*r*l+h;return i[0]=u*b+p*E+y*S,i[1]=c*b+g*E+x*S,i[2]=d*b+v*E+T*S,i[3]=f*b+m*E+w*S,i[4]=u*A+p*_+y*C,i[5]=c*A+g*_+x*C,i[6]=d*A+v*_+T*C,i[7]=f*A+m*_+w*C,i[8]=u*M+p*O+y*P,i[9]=c*M+g*O+x*P,i[10]=d*M+v*O+T*P,i[11]=f*M+m*O+w*P,this},rotateX:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this},rotateY:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this},rotateZ:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this},fromRotationTranslation:function(t,e){var i=this.val,n=t.x,s=t.y,r=t.z,o=t.w,a=n+n,h=s+s,l=r+r,u=n*a,c=n*h,d=n*l,f=s*h,p=s*l,g=r*l,v=o*a,m=o*h,y=o*l;return i[0]=1-(f+g),i[1]=c+y,i[2]=d-m,i[3]=0,i[4]=c-y,i[5]=1-(u+g),i[6]=p+v,i[7]=0,i[8]=d+m,i[9]=p-v,i[10]=1-(u+f),i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this},fromQuat:function(t){var e=this.val,i=t.x,n=t.y,s=t.z,r=t.w,o=i+i,a=n+n,h=s+s,l=i*o,u=i*a,c=i*h,d=n*a,f=n*h,p=s*h,g=r*o,v=r*a,m=r*h;return e[0]=1-(d+p),e[1]=u+m,e[2]=c-v,e[3]=0,e[4]=u-m,e[5]=1-(l+p),e[6]=f+g,e[7]=0,e[8]=c+v,e[9]=f-g,e[10]=1-(l+d),e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},frustum:function(t,e,i,n,s,r){var o=this.val,a=1/(e-t),h=1/(n-i),l=1/(s-r);return o[0]=2*s*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*s*h,o[6]=0,o[7]=0,o[8]=(e+t)*a,o[9]=(n+i)*h,o[10]=(r+s)*l,o[11]=-1,o[12]=0,o[13]=0,o[14]=r*s*2*l,o[15]=0,this},perspective:function(t,e,i,n){var s=this.val,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this},perspectiveLH:function(t,e,i,n){var s=this.val;return s[0]=2*i/t,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/e,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-n/(i-n),s[11]=1,s[12]=0,s[13]=0,s[14]=i*n/(i-n),s[15]=0,this},ortho:function(t,e,i,n,s,r){var o=this.val,a=t-e,h=i-n,l=s-r;return a=0===a?a:1/a,h=0===h?h:1/h,l=0===l?l:1/l,o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this},lookAt:function(t,e,i){var n=this.val,s=t.x,r=t.y,o=t.z,a=i.x,h=i.y,l=i.z,u=e.x,c=e.y,d=e.z;if(Math.abs(s-u)<1e-6&&Math.abs(r-c)<1e-6&&Math.abs(o-d)<1e-6)return this.identity();var f=s-u,p=r-c,g=o-d,v=1/Math.sqrt(f*f+p*p+g*g),m=h*(g*=v)-l*(p*=v),y=l*(f*=v)-a*g,x=a*p-h*f;(v=Math.sqrt(m*m+y*y+x*x))?(m*=v=1/v,y*=v,x*=v):(m=0,y=0,x=0);var T=p*x-g*y,w=g*m-f*x,b=f*y-p*m;return(v=Math.sqrt(T*T+w*w+b*b))?(T*=v=1/v,w*=v,b*=v):(T=0,w=0,b=0),n[0]=m,n[1]=T,n[2]=f,n[3]=0,n[4]=y,n[5]=w,n[6]=p,n[7]=0,n[8]=x,n[9]=b,n[10]=g,n[11]=0,n[12]=-(m*s+y*r+x*o),n[13]=-(T*s+w*r+b*o),n[14]=-(f*s+p*r+g*o),n[15]=1,this},yawPitchRoll:function(t,e,i){this.zero(),s.zero(),r.zero();var n=this.val,o=s.val,a=r.val,h=Math.sin(i),l=Math.cos(i);return n[10]=1,n[15]=1,n[0]=l,n[1]=h,n[4]=-h,n[5]=l,h=Math.sin(e),l=Math.cos(e),o[0]=1,o[15]=1,o[5]=l,o[10]=l,o[9]=-h,o[6]=h,h=Math.sin(t),l=Math.cos(t),a[5]=1,a[15]=1,a[0]=l,a[2]=-h,a[8]=h,a[10]=l,this.multiplyLocal(s),this.multiplyLocal(r),this},setWorldMatrix:function(t,e,i,n,o){return this.yawPitchRoll(t.y,t.x,t.z),s.scaling(i.x,i.y,i.z),r.xyz(e.x,e.y,e.z),this.multiplyLocal(s),this.multiplyLocal(r),void 0!==n&&this.multiplyLocal(n),void 0!==o&&this.multiplyLocal(o),this}}),s=new n,r=new n;t.exports=n},function(t,e,i){var n=i(0),s=i(169),r=i(330),o=new Int8Array([1,2,0]),a=new Float32Array([0,0,0]),h=new s(1,0,0),l=new s(0,1,0),u=new s,c=new r,d=new n({initialize:function(t,e,i,n){"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},rotationTo:function(t,e){var i=t.x*e.x+t.y*e.y+t.z*e.z;return i<-.999999?(u.copy(h).cross(t).length()<1e-6&&u.copy(l).cross(t),u.normalize(),this.setAxisAngle(u,Math.PI)):i>.999999?(this.x=0,this.y=0,this.z=0,this.w=1,this):(u.copy(t).cross(e),this.x=u.x,this.y=u.y,this.z=u.z,this.w=1+i,this.normalize())},setAxes:function(t,e,i){var n=c.val;return n[0]=e.x,n[3]=e.y,n[6]=e.z,n[1]=i.x,n[4]=i.y,n[7]=i.z,n[2]=-t.x,n[5]=-t.y,n[8]=-t.z,this.fromMat3(c).normalize()},identity:function(){return this.x=0,this.y=0,this.z=0,this.w=1,this},setAxisAngle:function(t,e){e*=.5;var i=Math.sin(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=Math.cos(e),this},multiply:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,o=t.y,a=t.z,h=t.w;return this.x=e*h+s*r+i*a-n*o,this.y=i*h+s*o+n*r-e*a,this.z=n*h+s*a+e*o-i*r,this.w=s*h-e*r-i*o-n*a,this},slerp:function(t,e){var i=this.x,n=this.y,s=this.z,r=this.w,o=t.x,a=t.y,h=t.z,l=t.w,u=i*o+n*a+s*h+r*l;u<0&&(u=-u,o=-o,a=-a,h=-h,l=-l);var c=1-e,d=e;if(1-u>1e-6){var f=Math.acos(u),p=Math.sin(f);c=Math.sin((1-e)*f)/p,d=Math.sin(e*f)/p}return this.x=c*i+d*o,this.y=c*n+d*a,this.z=c*s+d*h,this.w=c*r+d*l,this},invert:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n,r=s?1/s:0;return this.x=-t*r,this.y=-e*r,this.z=-i*r,this.w=n*r,this},conjugate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},rotateX:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+s*r,this.y=i*o+n*r,this.z=n*o-i*r,this.w=s*o-e*r,this},rotateY:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o-n*r,this.y=i*o+s*r,this.z=n*o+e*r,this.w=s*o-i*r,this},rotateZ:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+i*r,this.y=i*o-e*r,this.z=n*o+s*r,this.w=s*o-n*r,this},calculateW:function(){var t=this.x,e=this.y,i=this.z;return this.w=-Math.sqrt(1-t*t-e*e-i*i),this},fromMat3:function(t){var e,i=t.val,n=i[0]+i[4]+i[8];if(n>0)e=Math.sqrt(n+1),this.w=.5*e,e=.5/e,this.x=(i[7]-i[5])*e,this.y=(i[2]-i[6])*e,this.z=(i[3]-i[1])*e;else{var s=0;i[4]>i[0]&&(s=1),i[8]>i[3*s+s]&&(s=2);var r=o[s],h=o[r];e=Math.sqrt(i[3*s+s]-i[3*r+r]-i[3*h+h]+1),a[s]=.5*e,e=.5/e,a[r]=(i[3*r+s]+i[3*s+r])*e,a[h]=(i[3*h+s]+i[3*s+h])*e,this.x=a[0],this.y=a[1],this.z=a[2],this.w=(i[3*h+r]-i[3*r+h])*e}return this}});t.exports=d},function(t,e,i){var n=i(334),s=i(27),r=i(10),o=i(164);t.exports=function(t){var e=t.config;if((e.customEnvironment||e.canvas)&&e.renderType===r.AUTO)throw new Error("Must set explicit renderType in custom environment");if(!e.customEnvironment&&!e.canvas&&e.renderType!==r.HEADLESS)if(e.renderType===r.CANVAS||e.renderType!==r.CANVAS&&!o.webGL){if(!o.canvas)throw new Error("Cannot create Canvas or WebGL context, aborting.");e.renderType=r.CANVAS}else e.renderType=r.WEBGL;e.antialias||s.disableSmoothing();var a,h,l=t.scale.baseSize,u=l.width,c=l.height;e.canvas?(t.canvas=e.canvas,t.canvas.width=u,t.canvas.height=c):t.canvas=s.create(t,u,c,e.renderType),e.canvasStyle&&(t.canvas.style=e.canvasStyle),e.antialias||n.setCrisp(t.canvas),e.renderType!==r.HEADLESS&&(a=i(500),h=i(503),e.renderType===r.WEBGL?t.renderer=new h(t):(t.renderer=new a(t),t.context=t.renderer.gameContext))}},function(t,e){t.exports={setCrisp:function(t){return["optimizeSpeed","-moz-crisp-edges","-o-crisp-edges","-webkit-optimize-contrast","optimize-contrast","crisp-edges","pixelated"].forEach(function(e){t.style["image-rendering"]=e}),t.style.msInterpolationMode="nearest-neighbor",t},setBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}}},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_FS","","precision mediump float;","","uniform sampler2D uMainSampler;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main()","{"," vec4 texture = texture2D(uMainSampler, outTexCoord);"," vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);"," vec4 color = texture;",""," if (outTintEffect == 0.0)"," {"," // Multiply texture tint"," color = texture * texel;"," }"," else if (outTintEffect == 1.0)"," {"," // Solid color + texture alpha"," color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);"," color.a = texture.a * texel.a;"," }"," else if (outTintEffect == 2.0)"," {"," // Solid color, no texture"," color = texel;"," }",""," gl_FragColor = color;","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_VS","","precision mediump float;","","uniform mat4 uProjectionMatrix;","uniform mat4 uViewMatrix;","uniform mat4 uModelMatrix;","","attribute vec2 inPosition;","attribute vec2 inTexCoord;","attribute float inTintEffect;","attribute vec4 inTint;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main ()","{"," gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);",""," outTexCoord = inTexCoord;"," outTint = inTint;"," outTintEffect = inTintEffect;","}","",""].join("\n")},function(t,e,i){var n=i(10);t.exports=function(t){var e=t.config;if(!e.hideBanner){var i="WebGL";e.renderType===n.CANVAS?i="Canvas":e.renderType===n.HEADLESS&&(i="Headless");var s,r=e.audio,o=t.device.audio;if(s=!o.webAudio||r&&r.disableWebAudio?r&&r.noAudio||!o.webAudio&&!o.audioData?"No Audio":"HTML5 Audio":"Web Audio",t.device.browser.ie)window.console&&console.log("Phaser v"+n.VERSION+" / https://phaser.io");else{var a,h="",l=[h];Array.isArray(e.bannerBackgroundColor)?(e.bannerBackgroundColor.forEach(function(t){h=h.concat("%c "),l.push("background: "+t),a=t}),l[l.length-1]="color: "+e.bannerTextColor+"; background: "+a):(h=h.concat("%c "),l.push("color: "+e.bannerTextColor+"; background: "+e.bannerBackgroundColor)),l.push("background: #fff"),e.gameTitle&&(h=h.concat(e.gameTitle),e.gameVersion&&(h=h.concat(" v"+e.gameVersion)),e.hidePhaser||(h=h.concat(" / "))),e.hidePhaser||(h=h.concat("Phaser v"+n.VERSION+" ("+i+" | "+s+")")),h=h.concat(" %c "+e.gameURL),l[0]=h,console.log.apply(console,l)}}}},function(t,e,i){var n=i(0),s=i(6),r=i(1),o=i(339),a=new n({initialize:function(t,e){this.game=t,this.raf=new o,this.started=!1,this.running=!1,this.minFps=s(e,"min",5),this.targetFps=s(e,"target",60),this._min=1e3/this.minFps,this._target=1e3/this.targetFps,this.actualFps=this.targetFps,this.nextFpsUpdate=0,this.framesThisSecond=0,this.callback=r,this.forceSetTimeOut=s(e,"forceSetTimeOut",!1),this.time=0,this.startTime=0,this.lastTime=0,this.frame=0,this.inFocus=!0,this._pauseTime=0,this._coolDown=0,this.delta=0,this.deltaIndex=0,this.deltaHistory=[],this.deltaSmoothingMax=s(e,"deltaHistory",10),this.panicMax=s(e,"panicMax",120),this.rawDelta=0,this.now=0,this.smoothStep=s(e,"smoothStep",!0)},blur:function(){this.inFocus=!1},focus:function(){this.inFocus=!0,this.resetDelta()},pause:function(){this._pauseTime=window.performance.now()},resume:function(){this.resetDelta(),this.startTime+=this.time-this._pauseTime},resetDelta:function(){var t=window.performance.now();this.time=t,this.lastTime=t,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0;for(var e=0;e0||!this.inFocus)&&(this._coolDown--,r=Math.min(r,this._target)),r>this._min&&(r=n[i],r=Math.min(r,this._min)),n[i]=r,this.deltaIndex++,this.deltaIndex>s&&(this.deltaIndex=0),o=0;for(var a=0;athis.nextFpsUpdate&&(this.actualFps=.25*this.framesThisSecond+.75*this.actualFps,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0),this.framesThisSecond++;var h=o/this._target;this.callback(t,o,h),this.lastTime=t,this.frame++},tick:function(){this.step()},sleep:function(){this.running&&(this.raf.stop(),this.running=!1)},wake:function(t){this.running?this.sleep():t&&(this.startTime+=-this.lastTime+(this.lastTime+window.performance.now())),this.raf.start(this.step.bind(this),this.useRAF),this.running=!0,this.step()},getDuration:function(){return Math.round(this.lastTime-this.startTime)/1e3},getDurationMS:function(){return Math.round(this.lastTime-this.startTime)},stop:function(){return this.running=!1,this.started=!1,this.raf.stop(),this},destroy:function(){this.stop(),this.callback=r,this.raf=null,this.game=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(1),r=new n({initialize:function(){this.isRunning=!1,this.callback=s,this.tick=0,this.isSetTimeOut=!1,this.timeOutID=null,this.lastTime=0,this.target=0;var t=this;this.step=function e(){var i=window.performance.now();t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.requestAnimationFrame(e)},this.stepTimeout=function e(){var i=Date.now(),n=Math.min(Math.max(2*t.target+t.tick-i,0),t.target);t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.setTimeout(e,n)}},start:function(t,e,i){this.isRunning||(this.callback=t,this.isSetTimeOut=e,this.target=i,this.isRunning=!0,this.timeOutID=e?window.setTimeout(this.stepTimeout,0):window.requestAnimationFrame(this.step))},stop:function(){this.isRunning=!1,this.isSetTimeOut?clearTimeout(this.timeOutID):window.cancelAnimationFrame(this.timeOutID)},destroy:function(){this.stop(),this.callback=s}});t.exports=r},function(t,e,i){var n=i(19);t.exports=function(t){var e,i=t.events;void 0!==document.hidden?e="visibilitychange":["webkit","moz","ms"].forEach(function(t){void 0!==document[t+"Hidden"]&&(document.hidden=function(){return document[t+"Hidden"]},e=t+"visibilitychange")});e&&document.addEventListener(e,function(t){document.hidden||"pause"===t.type?i.emit(n.HIDDEN):i.emit(n.VISIBLE)},!1),window.onblur=function(){i.emit(n.BLUR)},window.onfocus=function(){i.emit(n.FOCUS)},window.focus&&t.config.autoFocus&&window.focus()}},function(t,e,i){var n=i(342),s=i(27),r=i(6);t.exports=function(t){var e=r(t,"data",[]),i=r(t,"canvas",null),o=r(t,"palette",n),a=r(t,"pixelWidth",1),h=r(t,"pixelHeight",a),l=r(t,"resizeCanvas",!0),u=r(t,"clearCanvas",!0),c=r(t,"preRender",null),d=r(t,"postRender",null),f=Math.floor(Math.abs(e[0].length*a)),p=Math.floor(Math.abs(e.length*h));i||(i=s.create2D(this,f,p),l=!1,u=!1),l&&(i.width=f,i.height=p);var g=i.getContext("2d");u&&g.clearRect(0,0,f,p),c&&c(i,g);for(var v=0;vi;)n-=i;ni.length-2?i.length-1:r+1],c=i[r>i.length-3?i.length-1:r+2];return e.set(n(a,h.x,l.x,u.x,c.x),n(a,h.y,l.y,u.y,c.y))},toJSON:function(){for(var t=[],e=0;e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}},function(t,e,i){var n=i(112);t.exports=function(t){if("complete"!==document.readyState&&"interactive"!==document.readyState){var e=function(){document.removeEventListener("deviceready",e,!0),document.removeEventListener("DOMContentLoaded",e,!0),window.removeEventListener("load",e,!0),t()};document.body?n.cordova?document.addEventListener("deviceready",e,!1):(document.addEventListener("DOMContentLoaded",e,!0),window.addEventListener("load",e,!0)):window.setTimeout(e,20)}else t()}},function(t,e,i){var n=i(172);t.exports=function(t,e){var i=window.screen,s=!!i&&(i.orientation||i.mozOrientation||i.msOrientation);if(s&&"string"==typeof s.type)return s.type;if("string"==typeof s)return s;if(i)return i.height>i.width?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if("number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return n.ORIENTATION.PORTRAIT;if(window.matchMedia("(orientation: landscape)").matches)return n.ORIENTATION.LANDSCAPE}return e>t?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE}},function(t,e){t.exports={NO_CENTER:0,CENTER_BOTH:1,CENTER_HORIZONTALLY:2,CENTER_VERTICALLY:3}},function(t,e){t.exports={LANDSCAPE:"landscape-primary",PORTRAIT:"portrait-primary"}},function(t,e){t.exports={NONE:0,WIDTH_CONTROLS_HEIGHT:1,HEIGHT_CONTROLS_WIDTH:2,FIT:3,ENVELOP:4,RESIZE:5}},function(t,e){t.exports={NO_ZOOM:1,ZOOM_2X:2,ZOOM_4X:4,MAX_ZOOM:-1}},function(t,e){t.exports=function(t){var e;return""!==t&&("string"==typeof t?e=document.getElementById(t):t&&1===t.nodeType&&(e=t)),e||(e=document.body),e}},function(t,e){t.exports=function(t){var e="";try{window.DOMParser?e=(new DOMParser).parseFromString(t,"text/xml"):(e=new ActiveXObject("Microsoft.XMLDOM")).loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null}},function(t,e,i){var n=i(0),s=i(174),r=i(11),o=i(54),a=i(19),h=i(361),l=i(362),u=i(363),c=i(364),d=i(30),f=i(328),p=new n({initialize:function(t,e){this.game=t,this.scaleManager,this.canvas,this.config=e,this.enabled=!0,this.events=new r,this.isOver=!0,this.defaultCursor="",this.keyboard=e.inputKeyboard?new h(this):null,this.mouse=e.inputMouse?new l(this):null,this.touch=e.inputTouch?new c(this):null,this.pointers=[],this.pointersTotal=e.inputActivePointers,e.inputTouch&&1===this.pointersTotal&&(this.pointersTotal=2);for(var i=0;i<=this.pointersTotal;i++){var n=new u(this,i);n.smoothFactor=e.inputSmoothFactor,this.pointers.push(n)}this.mousePointer=e.inputMouse?this.pointers[0]:null,this.activePointer=this.pointers[0],this.globalTopOnly=!0,this.time=0,this._tempPoint={x:0,y:0},this._tempHitTest=[],this._tempMatrix=new d,this._tempMatrix2=new d,this._tempSkip=!1,this.mousePointerContainer=[this.mousePointer],t.events.once(a.BOOT,this.boot,this)},boot:function(){this.canvas=this.game.canvas,this.scaleManager=this.game.scale,this.events.emit(o.MANAGER_BOOT),this.game.events.on(a.PRE_RENDER,this.preRender,this),this.game.events.once(a.DESTROY,this.destroy,this)},setCanvasOver:function(t){this.isOver=!0,this.events.emit(o.GAME_OVER,t)},setCanvasOut:function(t){this.isOver=!1,this.events.emit(o.GAME_OUT,t)},preRender:function(){var t=this.game.loop.now,e=this.game.loop.delta,i=this.game.scene.getScenes(!0,!0);this.time=t,this.events.emit(o.MANAGER_UPDATE);for(var n=0;n10&&(t=10-this.pointersTotal);for(var i=0;i-1&&e.preventDefault()}},this.onKeyUp=function(e){if(!e.defaultPrevented&&t.enabled&&t.manager){t.queue.push(e),t.manager.useQueue||t.manager.events.emit(o.MANAGER_PROCESS);var i=e.altKey||e.ctrlKey||e.shiftKey||e.metaKey;t.preventDefault&&!i&&t.captures.indexOf(e.keyCode)>-1&&e.preventDefault()}};var e=this.target;e&&(e.addEventListener("keydown",this.onKeyDown,!1),e.addEventListener("keyup",this.onKeyUp,!1),this.enabled=!0)},stopListeners:function(){var t=this.target;t.removeEventListener("keydown",this.onKeyDown,!1),t.removeEventListener("keyup",this.onKeyUp,!1),this.enabled=!1},postUpdate:function(){this.queue=[]},addCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},removeCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},clearCaptures:function(){this.captures=[],this.preventDefault=!1},destroy:function(){this.stopListeners(),this.clearCaptures(),this.queue=[],this.manager.game.events.off(r.POST_RENDER,this.postUpdate,this),this.target=null,this.enabled=!1,this.manager=null}});t.exports=l},function(t,e,i){var n=i(0),s=i(164),r=i(54),o=i(0),a=new n({initialize:function(t){this.manager=t,this.capture=!0,this.enabled=!1,this.target,this.locked=!1,this.onMouseMove=o,this.onMouseDown=o,this.onMouseUp=o,this.onMouseDownWindow=o,this.onMouseUpWindow=o,this.onMouseOver=o,this.onMouseOut=o,this.onMouseWheel=o,this.pointerLockChange=o,t.events.once(r.MANAGER_BOOT,this.boot,this)},boot:function(){var t=this.manager.config;this.enabled=t.inputMouse,this.target=t.inputMouseEventTarget,this.capture=t.inputMouseCapture,this.target?"string"==typeof this.target&&(this.target=document.getElementById(this.target)):this.target=this.manager.game.canvas,t.disableContextMenu&&this.disableContextMenu(),this.enabled&&this.target&&this.startListeners()},disableContextMenu:function(){return document.body.addEventListener("contextmenu",function(t){return t.preventDefault(),!1}),this},requestPointerLock:function(){if(s.pointerLock){var t=this.target;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock()}},releasePointerLock:function(){s.pointerLock&&(document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock())},startListeners:function(){var t=this,e=this.manager.canvas,i=window&&window.focus&&this.manager.game.config.autoFocus;this.onMouseMove=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseMove(e),t.capture&&e.preventDefault())},this.onMouseDown=function(n){i&&window.focus(),!n.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseDown(n),t.capture&&n.target===e&&n.preventDefault())},this.onMouseDownWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseDown(i)},this.onMouseUp=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseUp(i),t.capture&&i.target===e&&i.preventDefault())},this.onMouseUpWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseUp(i)},this.onMouseOver=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOver(e)},this.onMouseOut=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOut(e)},this.onMouseWheel=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.onMouseWheel(e)};var n=this.target;if(n){var r={passive:!0},o={passive:!1};n.addEventListener("mousemove",this.onMouseMove,this.capture?o:r),n.addEventListener("mousedown",this.onMouseDown,this.capture?o:r),n.addEventListener("mouseup",this.onMouseUp,this.capture?o:r),n.addEventListener("mouseover",this.onMouseOver,this.capture?o:r),n.addEventListener("mouseout",this.onMouseOut,this.capture?o:r),n.addEventListener("wheel",this.onMouseWheel,this.capture?o:r),window&&this.manager.game.config.inputWindowEvents&&(window.addEventListener("mousedown",this.onMouseDownWindow,o),window.addEventListener("mouseup",this.onMouseUpWindow,o)),s.pointerLock&&(this.pointerLockChange=function(e){var i=t.target;t.locked=document.pointerLockElement===i||document.mozPointerLockElement===i||document.webkitPointerLockElement===i,t.manager.onPointerLockChange(e)},document.addEventListener("pointerlockchange",this.pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this.pointerLockChange,!0)),this.enabled=!0}},stopListeners:function(){var t=this.target;t.removeEventListener("mousemove",this.onMouseMove),t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("mouseup",this.onMouseUp),t.removeEventListener("mouseover",this.onMouseOver),t.removeEventListener("mouseout",this.onMouseOut),window&&(window.removeEventListener("mousedown",this.onMouseDownWindow),window.removeEventListener("mouseup",this.onMouseUpWindow)),s.pointerLock&&(document.removeEventListener("pointerlockchange",this.pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this.pointerLockChange,!0))},destroy:function(){this.stopListeners(),this.target=null,this.enabled=!1,this.manager=null}});t.exports=a},function(t,e,i){var n=i(312),s=i(0),r=i(53),o=i(140),a=i(322),h=i(3),l=new s({initialize:function(t,e){this.manager=t,this.id=e,this.event,this.downElement,this.upElement,this.camera=null,this.button=0,this.buttons=0,this.position=new h,this.prevPosition=new h,this.midPoint=new h(-1,-1),this.velocity=new h,this.angle=0,this.distance=0,this.smoothFactor=0,this.motionFactor=.2,this.worldX=0,this.worldY=0,this.moveTime=0,this.downX=0,this.downY=0,this.downTime=0,this.upX=0,this.upY=0,this.upTime=0,this.primaryDown=!1,this.isDown=!1,this.wasTouch=!1,this.wasCanceled=!1,this.movementX=0,this.movementY=0,this.identifier=0,this.pointerId=null,this.active=0===e,this.locked=!1,this.deltaX=0,this.deltaY=0,this.deltaZ=0},updateWorldPoint:function(t){var e=this.x,i=this.y;1!==t.resolution&&(e+=t._x,i+=t._y);var n=t.getWorldPoint(e,i);return this.worldX=n.x,this.worldY=n.y,this},positionToCamera:function(t,e){return t.getWorldPoint(this.x,this.y,e)},updateMotion:function(){var t=this.position.x,e=this.position.y,i=this.midPoint.x,s=this.midPoint.y;if(t!==i||e!==s){var r=a(this.motionFactor,i,t),h=a(this.motionFactor,s,e);o(r,t,.1)&&(r=t),o(h,e,.1)&&(h=e),this.midPoint.set(r,h);var l=t-r,u=e-h;this.velocity.set(l,u),this.angle=n(r,h,t,e),this.distance=Math.sqrt(l*l+u*u)}},up:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=t.timeStamp),this.isDown=!1,this.wasTouch=!1},down:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=t.timeStamp),this.isDown=!0,this.wasTouch=!1},move:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.locked&&(this.movementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.movementY=t.movementY||t.mozMovementY||t.webkitMovementY||0),this.moveTime=t.timeStamp,this.wasTouch=!1},wheel:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ,this.wasTouch=!1},touchstart:function(t,e){t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.active=!0,this.buttons=1,this.event=e,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=e.timeStamp,this.isDown=!0,this.wasTouch=!0,this.wasCanceled=!1,this.updateMotion()},touchmove:function(t,e){this.event=e,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.moveTime=e.timeStamp,this.wasTouch=!0,this.updateMotion()},touchend:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!1,this.active=!1,this.updateMotion()},touchcancel:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!0,this.active=!1},noButtonDown:function(){return 0===this.buttons},leftButtonDown:function(){return!!(1&this.buttons)},rightButtonDown:function(){return!!(2&this.buttons)},middleButtonDown:function(){return!!(4&this.buttons)},backButtonDown:function(){return!!(8&this.buttons)},forwardButtonDown:function(){return!!(16&this.buttons)},leftButtonReleased:function(){return 0===this.button&&!this.isDown},rightButtonReleased:function(){return 2===this.button&&!this.isDown},middleButtonReleased:function(){return 1===this.button&&!this.isDown},backButtonReleased:function(){return 3===this.button&&!this.isDown},forwardButtonReleased:function(){return 4===this.button&&!this.isDown},getDistance:function(){return this.isDown?r(this.downX,this.downY,this.x,this.y):r(this.downX,this.downY,this.upX,this.upY)},getDistanceX:function(){return this.isDown?Math.abs(this.downX-this.x):Math.abs(this.downX-this.upX)},getDistanceY:function(){return this.isDown?Math.abs(this.downY-this.y):Math.abs(this.downY-this.upY)},getDuration:function(){return this.isDown?this.manager.time-this.downTime:this.upTime-this.downTime},getAngle:function(){return this.isDown?n(this.downX,this.downY,this.x,this.y):n(this.downX,this.downY,this.upX,this.upY)},getInterpolatedPosition:function(t,e){void 0===t&&(t=10),void 0===e&&(e=[]);for(var i=this.prevPosition.x,n=this.prevPosition.y,s=this.position.x,r=this.position.y,o=0;o0&&this.parentSize.height>0&&this.displaySize.setParent(this.parentSize),this.refresh()),t.events.on(a.PRE_STEP,this.step,this),t.events.once(a.DESTROY,this.destroy,this),this.startListeners()},parseConfig:function(t){this.getParent(t),this.getParentBounds();var e=t.width,i=t.height,s=t.scaleMode,r=t.resolution,o=t.zoom,a=t.autoRound;if("string"==typeof e){var h=this.parentSize.width;0===h&&(h=window.innerWidth);var l=parseInt(e,10)/100;e=Math.floor(h*l)}if("string"==typeof i){var c=this.parentSize.height;0===c&&(c=window.innerHeight);var d=parseInt(i,10)/100;i=Math.floor(c*d)}this.resolution=1,this.scaleMode=s,this.autoRound=a,this.autoCenter=t.autoCenter,this.resizeInterval=t.resizeInterval,a&&(e=Math.floor(e),i=Math.floor(i)),this.gameSize.setSize(e,i),o===n.ZOOM.MAX_ZOOM&&(o=this.getMaxZoom()),this.zoom=o,1!==o&&(this._resetZoom=!0),this.baseSize.setSize(e*r,i*r),a&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),t.minWidth>0&&this.displaySize.setMin(t.minWidth*o,t.minHeight*o),t.maxWidth>0&&this.displaySize.setMax(t.maxWidth*o,t.maxHeight*o),this.displaySize.setSize(e,i),this.orientation=u(e,i)},getParent:function(t){var e=t.parent;if(null!==e){if(this.parent=l(e),this.parentIsWindow=this.parent===document.body,t.expandParent&&t.scaleMode!==n.SCALE_MODE.NONE){var i=this.parent.getBoundingClientRect();(this.parentIsWindow||0===i.height)&&(document.documentElement.style.height="100%",document.body.style.height="100%",i=this.parent.getBoundingClientRect(),this.parentIsWindow||0!==i.height||(this.parent.style.overflow="hidden",this.parent.style.width="100%",this.parent.style.height="100%"))}t.fullscreenTarget&&!this.fullscreenTarget&&(this.fullscreenTarget=l(t.fullscreenTarget))}},getParentBounds:function(){if(!this.parent)return!1;var t=this.parentSize,e=this.parent.getBoundingClientRect();this.parentIsWindow&&this.game.device.os.iOS&&(e.height=h(!0));var i=this.resolution,n=e.width*i,s=e.height*i;return(t.width!==n||t.height!==s)&&(t.setSize(n,s),!0)},lockOrientation:function(t){var e=screen.lockOrientation||screen.mozLockOrientation||screen.msLockOrientation;return!!e&&e(t)},setParentSize:function(t,e){return this.parentSize.setSize(t,e),this.refresh()},setGameSize:function(t,e){var i=this.autoRound,n=this.resolution;i&&(t=Math.floor(t),e=Math.floor(e));var s=this.width,r=this.height;return this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),i&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t,e),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height,this.refresh(s,r)},resize:function(t,e){var i=this.zoom,n=this.resolution,s=this.autoRound;s&&(t=Math.floor(t),e=Math.floor(e));var r=this.width,o=this.height;this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),s&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t*i*n,e*i*n),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height;var a=this.canvas.style,h=t*i,l=e*i;return s&&(h=Math.floor(h),l=Math.floor(l)),h===t&&l===e||(a.width=h+"px",a.height=l+"px"),this.refresh(r,o)},setZoom:function(t){return this.zoom=t,this._resetZoom=!0,this.refresh()},setMaxZoom:function(){return this.zoom=this.getMaxZoom(),this._resetZoom=!0,this.refresh()},refresh:function(t,e){void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.updateScale(),this.updateBounds(),this.updateOrientation(),this.displayScale.set(this.baseSize.width/this.canvasBounds.width,this.baseSize.height/this.canvasBounds.height);var i=this.game.domContainer;if(i){this.baseSize.setCSS(i);var n=this.canvas.style,s=i.style;s.transform="scale("+this.displaySize.width/this.baseSize.width+","+this.displaySize.height/this.baseSize.height+")",s.marginLeft=n.marginLeft,s.marginTop=n.marginTop}return this.emit(o.RESIZE,this.gameSize,this.baseSize,this.displaySize,this.resolution,t,e),this},updateOrientation:function(){if(this._checkOrientation){this._checkOrientation=!1;var t=u(this.width,this.height);t!==this.orientation&&(this.orientation=t,this.emit(o.ORIENTATION_CHANGE,t))}},updateScale:function(){var t,e,i=this.canvas.style,s=this.gameSize.width,r=this.gameSize.height,o=this.zoom,a=this.autoRound;this.scaleMode===n.SCALE_MODE.NONE?(this.displaySize.setSize(s*o*1,r*o*1),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this._resetZoom&&(i.width=t+"px",i.height=e+"px",this._resetZoom=!1)):this.scaleMode===n.SCALE_MODE.RESIZE?(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),this.gameSize.setSize(this.displaySize.width,this.displaySize.height),this.baseSize.setSize(1*this.displaySize.width,1*this.displaySize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this.canvas.width=t,this.canvas.height=e):(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),i.width=t+"px",i.height=e+"px"),this.getParentBounds(),this.updateCenter()},getMaxZoom:function(){var t=p(this.parentSize.width,this.gameSize.width,0,!0),e=p(this.parentSize.height,this.gameSize.height,0,!0);return Math.max(Math.min(t,e),1)},updateCenter:function(){var t=this.autoCenter;if(t!==n.CENTER.NO_CENTER){var e=this.canvas,i=e.style,s=e.getBoundingClientRect(),r=s.width,o=s.height,a=Math.floor((this.parentSize.width-r)/2),h=Math.floor((this.parentSize.height-o)/2);t===n.CENTER.CENTER_HORIZONTALLY?h=0:t===n.CENTER.CENTER_VERTICALLY&&(a=0),i.marginLeft=a+"px",i.marginTop=h+"px"}},updateBounds:function(){var t=this.canvasBounds,e=this.canvas.getBoundingClientRect();t.x=e.left+(window.pageXOffset||0)-(document.documentElement.clientLeft||0),t.y=e.top+(window.pageYOffset||0)-(document.documentElement.clientTop||0),t.width=e.width,t.height=e.height},transformX:function(t){return(t-this.canvasBounds.left)*this.displayScale.x},transformY:function(t){return(t-this.canvasBounds.top)*this.displayScale.y},startFullscreen:function(t){void 0===t&&(t={navigationUI:"hide"});var e=this.fullscreen;if(e.available){if(!e.active){var i,n=this.getFullscreenTarget();(i=e.keyboard?n[e.request](Element.ALLOW_KEYBOARD_INPUT):n[e.request](t))?i.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)):e.active?this.fullscreenSuccessHandler():this.fullscreenErrorHandler()}}else this.emit(o.FULLSCREEN_UNSUPPORTED)},fullscreenSuccessHandler:function(){this.getParentBounds(),this.refresh(),this.emit(o.ENTER_FULLSCREEN)},fullscreenErrorHandler:function(t){this.removeFullscreenTarget(),this.emit(o.FULLSCREEN_FAILED,t)},getFullscreenTarget:function(){if(!this.fullscreenTarget){var t=document.createElement("div");t.style.margin="0",t.style.padding="0",t.style.width="100%",t.style.height="100%",this.fullscreenTarget=t,this._createdFullscreenTarget=!0}this._createdFullscreenTarget&&(this.canvas.parentNode.insertBefore(this.fullscreenTarget,this.canvas),this.fullscreenTarget.appendChild(this.canvas));return this.fullscreenTarget},removeFullscreenTarget:function(){if(this._createdFullscreenTarget){var t=this.fullscreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.canvas,t),e.removeChild(t)}}},stopFullscreen:function(){var t=this.fullscreen;if(!t.available)return this.emit(o.FULLSCREEN_UNSUPPORTED),!1;t.active&&document[t.cancel](),this.removeFullscreenTarget(),this.getParentBounds(),this.emit(o.LEAVE_FULLSCREEN),this.refresh()},toggleFullscreen:function(t){this.fullscreen.active?this.stopFullscreen():this.startFullscreen(t)},startListeners:function(){var t=this,e=this.listeners;if(e.orientationChange=function(){t._checkOrientation=!0,t.dirty=!0},e.windowResize=function(){t.dirty=!0},window.addEventListener("orientationchange",e.orientationChange,!1),window.addEventListener("resize",e.windowResize,!1),this.fullscreen.available){e.fullScreenChange=function(e){return t.onFullScreenChange(e)},e.fullScreenError=function(e){return t.onFullScreenError(e)};["webkit","moz",""].forEach(function(t){document.addEventListener(t+"fullscreenchange",e.fullScreenChange,!1),document.addEventListener(t+"fullscreenerror",e.fullScreenError,!1)}),document.addEventListener("MSFullscreenChange",e.fullScreenChange,!1),document.addEventListener("MSFullscreenError",e.fullScreenError,!1)}},onFullScreenChange:function(){document.fullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||this.stopFullscreen()},onFullScreenError:function(){this.removeFullscreenTarget()},step:function(t,e){this.parent&&(this._lastCheck+=e,(this.dirty||this._lastCheck>this.resizeInterval)&&(this.getParentBounds()&&this.refresh(),this.dirty=!1,this._lastCheck=0))},stopListeners:function(){var t=this.listeners;window.removeEventListener("orientationchange",t.orientationChange,!1),window.removeEventListener("resize",t.windowResize,!1);["webkit","moz",""].forEach(function(e){document.removeEventListener(e+"fullscreenchange",t.fullScreenChange,!1),document.removeEventListener(e+"fullscreenerror",t.fullScreenError,!1)}),document.removeEventListener("MSFullscreenChange",t.fullScreenChange,!1),document.removeEventListener("MSFullscreenError",t.fullScreenError,!1)},destroy:function(){this.removeAllListeners(),this.stopListeners(),this.game=null,this.canvas=null,this.canvasBounds=null,this.parent=null,this.fullscreenTarget=null,this.parentSize.destroy(),this.gameSize.destroy(),this.baseSize.destroy(),this.displaySize.destroy()},isFullscreen:{get:function(){return this.fullscreen.active}},width:{get:function(){return this.gameSize.width}},height:{get:function(){return this.gameSize.height}},isPortrait:{get:function(){return this.orientation===n.ORIENTATION.PORTRAIT}},isLandscape:{get:function(){return this.orientation===n.ORIENTATION.LANDSCAPE}},isGamePortrait:{get:function(){return this.height>this.width}},isGameLandscape:{get:function(){return this.width>this.height}}});t.exports=v},function(t,e,i){var n=i(23),s=i(0),r=i(91),o=i(3),a=new s({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=0),void 0===n&&(n=null),this._width=t,this._height=e,this._parent=n,this.aspectMode=i,this.aspectRatio=0===e?1:t/e,this.minWidth=0,this.minHeight=0,this.maxWidth=Number.MAX_VALUE,this.maxHeight=Number.MAX_VALUE,this.snapTo=new o},setAspectMode:function(t){return void 0===t&&(t=0),this.aspectMode=t,this.setSize(this._width,this._height)},setSnap:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.snapTo.set(t,e),this.setSize(this._width,this._height)},setParent:function(t){return this._parent=t,this.setSize(this._width,this._height)},setMin:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.minWidth=n(t,0,this.maxWidth),this.minHeight=n(e,0,this.maxHeight),this.setSize(this._width,this._height)},setMax:function(t,e){return void 0===t&&(t=Number.MAX_VALUE),void 0===e&&(e=t),this.maxWidth=n(t,this.minWidth,Number.MAX_VALUE),this.maxHeight=n(e,this.minHeight,Number.MAX_VALUE),this.setSize(this._width,this._height)},setSize:function(t,e){switch(void 0===t&&(t=0),void 0===e&&(e=t),this.aspectMode){case a.NONE:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height;break;case a.WIDTH_CONTROLS_HEIGHT:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(this._width*(1/this.aspectRatio),!1);break;case a.HEIGHT_CONTROLS_WIDTH:this._height=this.getNewHeight(r(e,this.snapTo.y)),this._width=this.getNewWidth(this._height*this.aspectRatio,!1);break;case a.FIT:this.constrain(t,e,!0);break;case a.ENVELOP:this.constrain(t,e,!1)}return this},setAspectRatio:function(t){return this.aspectRatio=t,this.setSize(this._width,this._height)},resize:function(t,e){return this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height,this},getNewWidth:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minWidth,this.maxWidth),e&&this._parent&&t>this._parent.width&&(t=Math.max(this.minWidth,this._parent.width)),t},getNewHeight:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minHeight,this.maxHeight),e&&this._parent&&t>this._parent.height&&(t=Math.max(this.minHeight,this._parent.height)),t},constrain:function(t,e,i){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=!0),t=this.getNewWidth(t),e=this.getNewHeight(e);var n=this.snapTo,s=0===e?1:t/e;return i&&this.aspectRatio>s||!i&&this.aspectRatio0&&(t=(e=r(e,n.y))*this.aspectRatio)):(i&&this.aspectRatios)&&(t=(e=r(e,n.y))*this.aspectRatio,n.x>0&&(e=(t=r(t,n.x))*(1/this.aspectRatio))),this._width=t,this._height=e,this},fitTo:function(t,e){return this.constrain(t,e,!0)},envelop:function(t,e){return this.constrain(t,e,!1)},setWidth:function(t){return this.setSize(t,this._height)},setHeight:function(t){return this.setSize(this._width,t)},toString:function(){return"[{ Size (width="+this._width+" height="+this._height+" aspectRatio="+this.aspectRatio+" aspectMode="+this.aspectMode+") }]"},setCSS:function(t){t&&t.style&&(t.style.width=this._width+"px",t.style.height=this._height+"px")},copy:function(t){return t.setAspectMode(this.aspectMode),t.aspectRatio=this.aspectRatio,t.setSize(this.width,this.height)},destroy:function(){this._parent=null,this.snapTo=null},width:{get:function(){return this._width},set:function(t){this.setSize(t,this._height)}},height:{get:function(){return this._height},set:function(t){this.setSize(this._width,t)}}});a.NONE=0,a.WIDTH_CONTROLS_HEIGHT=1,a.HEIGHT_CONTROLS_WIDTH=2,a.FIT=3,a.ENVELOP=4,t.exports=a},function(t,e,i){var n=i(0),s=i(119),r=i(22),o=i(19),a=i(6),h=i(80),l=i(1),u=i(369),c=i(175),d=new n({initialize:function(t,e){if(this.game=t,this.keys={},this.scenes=[],this._pending=[],this._start=[],this._queue=[],this._data={},this.isProcessing=!1,this.isBooted=!1,this.customViewports=0,e){Array.isArray(e)||(e=[e]);for(var i=0;i-1&&(delete this.keys[n],this.scenes.splice(i,1),this._start.indexOf(n)>-1&&(i=this._start.indexOf(n),this._start.splice(i,1)),e.sys.destroy())}return this},bootScene:function(t){var e,i=t.sys,n=i.settings;t.init&&(t.init.call(t,n.data),n.status=s.INIT,n.isTransition&&i.events.emit(r.TRANSITION_INIT,n.transitionFrom,n.transitionDuration)),i.load&&(e=i.load).reset(),e&&t.preload?(t.preload.call(t),0===e.list.size?this.create(t):(n.status=s.LOADING,e.once(h.COMPLETE,this.loadComplete,this),e.start())):this.create(t)},loadComplete:function(t){var e=t.scene;this.game.sound&&this.game.sound.onBlurPausedSounds&&this.game.sound.unlock(),this.create(e)},payloadComplete:function(t){this.bootScene(t.scene)},update:function(t,e){this.processQueue(),this.isProcessing=!0;for(var i=this.scenes.length-1;i>=0;i--){var n=this.scenes[i].sys;n.settings.status>s.START&&n.settings.status<=s.RUNNING&&n.step(t,e)}},render:function(t){for(var e=0;e=s.LOADING&&i.settings.status0){var i=this.getScene(t);this.scenes.splice(e,1),this.scenes.unshift(i)}}return this},moveDown:function(t){if(this.isProcessing)this._queue.push({op:"moveDown",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e>0){var i=e-1,n=this.getScene(t),s=this.getAt(i);this.scenes[e]=s,this.scenes[i]=n}}return this},moveUp:function(t){if(this.isProcessing)this._queue.push({op:"moveUp",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e=r.x&&t=r.y&&e=r.x&&t=r.y&&e-1){var o=this.context.getImageData(t,e,1,1);o.data[0]=i,o.data[1]=n,o.data[2]=s,o.data[3]=r,this.context.putImageData(o,t,e)}return this},putData:function(t,e,i,n,s,r,o){return void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=t.width),void 0===o&&(o=t.height),this.context.putImageData(t,e,i,n,s,r,o),this},getData:function(t,e,i,n){return t=s(Math.floor(t),0,this.width-1),e=s(Math.floor(e),0,this.height-1),i=s(i,1,this.width-t),n=s(n,1,this.height-e),this.context.getImageData(t,e,i,n)},getPixel:function(t,e,i){i||(i=new r);var n=this.getIndex(t,e);if(n>-1){var s=this.data,o=s[n+0],a=s[n+1],h=s[n+2],l=s[n+3];i.setTo(o,a,h,l)}return i},getPixels:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=i),t=Math.abs(Math.round(t)),e=Math.abs(Math.round(e));for(var o=s(t,0,this.width),a=s(t+i,0,this.width),h=s(e,0,this.height),l=s(e+n,0,this.height),u=new r,c=[],d=h;d0)&&(!!n.prototype.pause.call(this)&&(this.currentConfig.seek=this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0),this.stopAndReleaseAudioTag(),this.emit(r.PAUSE,this),!0)))},resume:function(){return!this.manager.isLocked(this,"resume")&&(!(this.startTime>0)&&(!!n.prototype.resume.call(this)&&(!!this.pickAndPlayAudioTag()&&(this.emit(r.RESUME,this),!0))))},stop:function(){return!this.manager.isLocked(this,"stop")&&(!!n.prototype.stop.call(this)&&(this.stopAndReleaseAudioTag(),this.emit(r.STOP,this),!0))},pickAndPlayAudioTag:function(){if(!this.pickAudioTag())return this.reset(),!1;var t=this.currentConfig.seek,e=this.currentConfig.delay,i=(this.currentMarker?this.currentMarker.start:0)+t;return this.previousTime=i,this.audio.currentTime=i,this.applyConfig(),0===e?(this.startTime=0,this.audio.paused&&this.playCatchPromise()):(this.startTime=window.performance.now()+1e3*e,this.audio.paused||this.audio.pause()),this.resetConfig(),!0},pickAudioTag:function(){if(this.audio)return!0;for(var t=0;t0)this.startTime=n-this.manager.loopEndOffset?(this.audio.currentTime=i+Math.max(0,s-n),s=this.audio.currentTime):s=n)return this.reset(),this.stopAndReleaseAudioTag(),void this.emit(r.COMPLETE,this);this.previousTime=s}},destroy:function(){n.prototype.destroy.call(this),this.tags=null,this.audio&&this.stopAndReleaseAudioTag()},updateMute:function(){this.audio&&(this.audio.muted=this.currentConfig.mute||this.manager.mute)},updateVolume:function(){this.audio&&(this.audio.volume=this.currentConfig.volume*this.manager.volume)},calculateRate:function(){n.prototype.calculateRate.call(this),this.audio&&(this.audio.playbackRate=this.totalRate)},mute:{get:function(){return this.currentConfig.mute},set:function(t){this.currentConfig.mute=t,this.manager.isLocked(this,"mute",t)||(this.updateMute(),this.emit(r.MUTE,this,t))}},setMute:function(t){return this.mute=t,this},volume:{get:function(){return this.currentConfig.volume},set:function(t){this.currentConfig.volume=t,this.manager.isLocked(this,"volume",t)||(this.updateVolume(),this.emit(r.VOLUME,this,t))}},setVolume:function(t){return this.volume=t,this},rate:{get:function(){return this.currentConfig.rate},set:function(t){this.currentConfig.rate=t,this.manager.isLocked(this,r.RATE,t)||(this.calculateRate(),this.emit(r.RATE,this,t))}},setRate:function(t){return this.rate=t,this},detune:{get:function(){return this.currentConfig.detune},set:function(t){this.currentConfig.detune=t,this.manager.isLocked(this,r.DETUNE,t)||(this.calculateRate(),this.emit(r.DETUNE,this,t))}},setDetune:function(t){return this.detune=t,this},seek:{get:function(){return this.isPlaying?this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0):this.isPaused?this.currentConfig.seek:0},set:function(t){this.manager.isLocked(this,"seek",t)||this.startTime>0||(this.isPlaying||this.isPaused)&&(t=Math.min(Math.max(0,t),this.duration),this.isPlaying?(this.previousTime=t,this.audio.currentTime=t):this.isPaused&&(this.currentConfig.seek=t),this.emit(r.SEEK,this,t))}},setSeek:function(t){return this.seek=t,this},loop:{get:function(){return this.currentConfig.loop},set:function(t){this.currentConfig.loop=t,this.manager.isLocked(this,"loop",t)||(this.audio&&(this.audio.loop=t),this.emit(r.LOOP,this,t))}},setLoop:function(t){return this.loop=t,this}});t.exports=o},function(t,e,i){var n=i(121),s=i(0),r=i(11),o=i(379),a=i(1),h=new s({Extends:r,initialize:function(t){r.call(this),this.game=t,this.sounds=[],this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.pauseOnBlur=!0,this.locked=!1},add:function(t,e){var i=new o(this,t,e);return this.sounds.push(i),i},addAudioSprite:function(t,e){var i=this.add(t,e);return i.spritemap={},i},play:function(t,e){return!1},playAudioSprite:function(t,e,i){return!1},remove:function(t){return n.prototype.remove.call(this,t)},removeByKey:function(t){return n.prototype.removeByKey.call(this,t)},pauseAll:a,resumeAll:a,stopAll:a,update:a,setRate:a,setDetune:a,setMute:a,setVolume:a,forEachActiveSound:function(t,e){n.prototype.forEachActiveSound.call(this,t,e)},destroy:function(){n.prototype.destroy.call(this)}});t.exports=h},function(t,e,i){var n=i(122),s=i(0),r=i(11),o=i(18),a=new s({Extends:r,initialize:function(t,e,i){void 0===i&&(i={}),r.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=0,this.totalDuration=0,this.config=o({mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},i),this.currentConfig=this.config,this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.seek=0,this.loop=!1,this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!1},updateMarker:function(t){return!1},removeMarker:function(t){return null},play:function(t,e){return!1},pause:function(){return!1},resume:function(){return!1},stop:function(){return!1},destroy:function(){this.manager.remove(this),n.prototype.destroy.call(this)}});t.exports=a},function(t,e,i){var n=i(381),s=i(121),r=i(0),o=i(59),a=i(382),h=new r({Extends:s,initialize:function(t){this.context=this.createAudioContext(t),this.masterMuteNode=this.context.createGain(),this.masterVolumeNode=this.context.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(this.context.destination),this.destination=this.masterMuteNode,this.locked="suspended"===this.context.state&&("ontouchstart"in window||"onclick"in window),s.call(this,t),this.locked&&this.unlock()},createAudioContext:function(t){var e=t.config.audio;return e&&e.context?(e.context.resume(),e.context):new AudioContext},setAudioContext:function(t){return this.context&&this.context.close(),this.masterMuteNode&&this.masterMuteNode.disconnect(),this.masterVolumeNode&&this.masterVolumeNode.disconnect(),this.context=t,this.masterMuteNode=t.createGain(),this.masterVolumeNode=t.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(t.destination),this.destination=this.masterMuteNode,this},add:function(t,e){var i=new a(this,t,e);return this.sounds.push(i),i},decodeAudio:function(t,e){var i;i=Array.isArray(t)?t:[{key:t,data:e}];for(var s=this.game.cache.audio,r=i.length,a=0;a>4,u[h++]=(15&i)<<4|s>>2,u[h++]=(3&s)<<6|63&r;return l}},function(t,e,i){var n=i(122),s=i(0),r=i(59),o=new s({Extends:n,initialize:function(t,e,i){if(void 0===i&&(i={}),this.audioBuffer=t.game.cache.audio.get(e),!this.audioBuffer)throw new Error('There is no audio asset with key "'+e+'" in the audio cache');this.source=null,this.loopSource=null,this.muteNode=t.context.createGain(),this.volumeNode=t.context.createGain(),this.playTime=0,this.startTime=0,this.loopTime=0,this.rateUpdates=[],this.hasEnded=!1,this.hasLooped=!1,this.muteNode.connect(this.volumeNode),this.volumeNode.connect(t.destination),this.duration=this.audioBuffer.duration,this.totalDuration=this.audioBuffer.duration,n.call(this,t,e,i)},play:function(t,e){return!!n.prototype.play.call(this,t,e)&&(this.stopAndRemoveBufferSource(),this.createAndStartBufferSource(),this.emit(r.PLAY,this),!0)},pause:function(){return!(this.manager.context.currentTime-1;r--)n[s][r]=t[r][s]}return n}},function(t,e){function i(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function n(t,e){return te?1:0}var s=function(t,e,r,o,a){for(void 0===r&&(r=0),void 0===o&&(o=t.length-1),void 0===a&&(a=n);o>r;){if(o-r>600){var h=o-r+1,l=e-r+1,u=Math.log(h),c=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*c*(h-c)/h)*(l-h/2<0?-1:1),f=Math.max(r,Math.floor(e-l*c/h+d)),p=Math.min(o,Math.floor(e+(h-l)*c/h+d));s(t,e,f,p,a)}var g=t[e],v=r,m=o;for(i(t,r,e),a(t[o],g)>0&&i(t,r,o);v0;)m--}0===a(t[r],g)?i(t,r,m):i(t,++m,o),m<=e&&(r=m+1),e<=m&&(o=m-1)}};t.exports=s},function(t,e,i){var n=i(6),s=i(110),r=function(t,e,i){for(var n=[],s=0;s0?s.delayedPlay(d,r,o):s.load(r)}return t}},function(t,e,i){var n=i(13);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.right,e.right)-s,a=Math.max(t.bottom,e.bottom)-r;return i.setTo(s,r,o,a)}},function(t,e,i){var n=i(0),s=i(12),r=i(948),o=i(14),a=i(7),h=i(173),l=i(22),u=i(329),c=new n({Extends:o,Mixins:[s.AlphaSingle,s.BlendMode,s.Depth,s.Origin,s.ScrollFactor,s.Transform,s.Visible,r],initialize:function(t,e,i,n,s,r){o.call(this,t,"DOMElement"),this.parent=t.sys.game.domContainer,this.cache=t.sys.cache.html,this.node,this.transformOnly=!1,this.skewX=0,this.skewY=0,this.rotate3d=new u,this.rotate3dAngle="deg",this.width=0,this.height=0,this.displayWidth=0,this.displayHeight=0,this.handler=this.dispatchNativeEvent.bind(this),this.setPosition(e,i),"string"==typeof n?"#"===n[0]?this.setElement(n.substr(1),s,r):this.createElement(n,s,r):n&&this.setElement(n,s,r),t.sys.events.on(l.SLEEP,this.handleSceneEvent,this),t.sys.events.on(l.WAKE,this.handleSceneEvent,this)},handleSceneEvent:function(t){var e=this.node,i=e.style;e&&(i.display=t.settings.visible?"block":"none")},setSkew:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.skewX=t,this.skewY=e,this},setPerspective:function(t){return this.parent.style.perspective=t+"px",this},perspective:{get:function(){return parseFloat(this.parent.style.perspective)},set:function(t){this.parent.style.perspective=t+"px"}},addListener:function(t){if(this.node){t=t.split(" ");for(var e=0;e>>16,y=(65280&p)>>>8,x=255&p,c.strokeStyle="rgba("+m+","+y+","+x+","+d+")",c.lineWidth=v,T+=3;break;case n.FILL_STYLE:g=l[T+1],f=l[T+2],m=(16711680&g)>>>16,y=(65280&g)>>>8,x=255&g,c.fillStyle="rgba("+m+","+y+","+x+","+f+")",T+=2;break;case n.BEGIN_PATH:c.beginPath();break;case n.CLOSE_PATH:c.closePath();break;case n.FILL_PATH:h||c.fill();break;case n.STROKE_PATH:h||c.stroke();break;case n.FILL_RECT:h?c.rect(l[T+1],l[T+2],l[T+3],l[T+4]):c.fillRect(l[T+1],l[T+2],l[T+3],l[T+4]),T+=4;break;case n.FILL_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.fill(),T+=6;break;case n.STROKE_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.stroke(),T+=6;break;case n.LINE_TO:c.lineTo(l[T+1],l[T+2]),T+=2;break;case n.MOVE_TO:c.moveTo(l[T+1],l[T+2]),T+=2;break;case n.LINE_FX_TO:c.lineTo(l[T+1],l[T+2]),T+=5;break;case n.MOVE_FX_TO:c.moveTo(l[T+1],l[T+2]),T+=5;break;case n.SAVE:c.save();break;case n.RESTORE:c.restore();break;case n.TRANSLATE:c.translate(l[T+1],l[T+2]),T+=2;break;case n.SCALE:c.scale(l[T+1],l[T+2]),T+=2;break;case n.ROTATE:c.rotate(l[T+1]),T+=1;break;case n.GRADIENT_FILL_STYLE:T+=5;break;case n.GRADIENT_LINE_STYLE:T+=6;break;case n.SET_TEXTURE:T+=2}c.restore()}}},function(t,e,i){var n=i(0),s=i(2),r=new n({initialize:function(t,e,i,n,r){if("object"==typeof t){var o=t;t=s(o,"x",0),e=s(o,"y",0),i=s(o,"power",0),n=s(o,"epsilon",100),r=s(o,"gravity",50)}else void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=100),void 0===r&&(r=50);this.x=t,this.y=e,this.active=!0,this._gravity=r,this._power=0,this._epsilon=0,this.power=i,this.epsilon=n},update:function(t,e){var i=this.x-t.x,n=this.y-t.y,s=i*i+n*n;if(0!==s){var r=Math.sqrt(s);s0},resetPosition:function(){this.x=0,this.y=0},fire:function(t,e){var i=this.emitter;this.frame=i.getFrame(),i.emitZone&&i.emitZone.getPoint(this),void 0===t?(i.follow&&(this.x+=i.follow.x+i.followOffset.x),this.x+=i.x.onEmit(this,"x")):this.x+=t,void 0===e?(i.follow&&(this.y+=i.follow.y+i.followOffset.y),this.y+=i.y.onEmit(this,"y")):this.y+=e,this.life=i.lifespan.onEmit(this,"lifespan"),this.lifeCurrent=this.life,this.lifeT=0;var n=i.speedX.onEmit(this,"speedX"),o=i.speedY?i.speedY.onEmit(this,"speedY"):n;if(i.radial){var a=s(i.angle.onEmit(this,"angle"));this.velocityX=Math.cos(a)*Math.abs(n),this.velocityY=Math.sin(a)*Math.abs(o)}else if(i.moveTo){var h=i.moveToX.onEmit(this,"moveToX"),l=i.moveToY?i.moveToY.onEmit(this,"moveToY"):h,u=Math.atan2(l-this.y,h-this.x),c=r(this.x,this.y,h,l)/(this.life/1e3);this.velocityX=Math.cos(u)*c,this.velocityY=Math.sin(u)*c}else this.velocityX=n,this.velocityY=o;i.acceleration&&(this.accelerationX=i.accelerationX.onEmit(this,"accelerationX"),this.accelerationY=i.accelerationY.onEmit(this,"accelerationY")),this.maxVelocityX=i.maxVelocityX.onEmit(this,"maxVelocityX"),this.maxVelocityY=i.maxVelocityY.onEmit(this,"maxVelocityY"),this.delayCurrent=i.delay.onEmit(this,"delay"),this.scaleX=i.scaleX.onEmit(this,"scaleX"),this.scaleY=i.scaleY?i.scaleY.onEmit(this,"scaleY"):this.scaleX,this.angle=i.rotate.onEmit(this,"rotate"),this.rotation=s(this.angle),this.bounce=i.bounce.onEmit(this,"bounce"),this.alpha=i.alpha.onEmit(this,"alpha"),this.tint=i.tint.onEmit(this,"tint")},computeVelocity:function(t,e,i,n){var s=this.velocityX,r=this.velocityY,o=this.accelerationX,a=this.accelerationY,h=this.maxVelocityX,l=this.maxVelocityY;s+=t.gravityX*i,r+=t.gravityY*i,o&&(s+=o*i),a&&(r+=a*i),s>h?s=h:s<-h&&(s=-h),r>l?r=l:r<-l&&(r=-l),this.velocityX=s,this.velocityY=r;for(var u=0;ue.right&&t.collideRight&&(this.x=e.right,this.velocityX*=i),this.ye.bottom&&t.collideBottom&&(this.y=e.bottom,this.velocityY*=i)},update:function(t,e,i){if(this.delayCurrent>0)return this.delayCurrent-=t,!1;var n=this.emitter,r=1-this.lifeCurrent/this.life;return this.lifeT=r,this.computeVelocity(n,t,e,i),this.x+=this.velocityX*e,this.y+=this.velocityY*e,n.bounds&&this.checkBounds(n),n.deathZone&&n.deathZone.willKill(this)?(this.lifeCurrent=0,!0):(this.scaleX=n.scaleX.onUpdate(this,"scaleX",r,this.scaleX),n.scaleY?this.scaleY=n.scaleY.onUpdate(this,"scaleY",r,this.scaleY):this.scaleY=this.scaleX,this.angle=n.rotate.onUpdate(this,"rotate",r,this.angle),this.rotation=s(this.angle),this.alpha=n.alpha.onUpdate(this,"alpha",r,this.alpha),this.tint=n.tint.onUpdate(this,"tint",r,this.tint),this.lifeCurrent-=t,this.lifeCurrent<=0)}});t.exports=o},function(t,e,i){var n=i(52),s=i(0),r=i(12),o=i(398),a=i(399),h=i(965),l=i(2),u=i(180),c=i(400),d=i(104),f=i(396),p=i(401),g=i(13),v=i(125),m=i(3),y=i(58),x=new s({Mixins:[r.BlendMode,r.Mask,r.ScrollFactor,r.Visible],initialize:function(t,e){this.manager=t,this.texture=t.texture,this.frames=[t.defaultFrame],this.defaultFrame=t.defaultFrame,this.configFastMap=["active","blendMode","collideBottom","collideLeft","collideRight","collideTop","deathCallback","deathCallbackScope","emitCallback","emitCallbackScope","follow","frequency","gravityX","gravityY","maxParticles","name","on","particleBringToTop","particleClass","radial","timeScale","trackVisible","visible"],this.configOpMap=["accelerationX","accelerationY","angle","alpha","bounce","delay","lifespan","maxVelocityX","maxVelocityY","moveToX","moveToY","quantity","rotate","scaleX","scaleY","speedX","speedY","tint","x","y"],this.name="",this.particleClass=f,this.x=new h(e,"x",0,!0),this.y=new h(e,"y",0,!0),this.radial=!0,this.gravityX=0,this.gravityY=0,this.acceleration=!1,this.accelerationX=new h(e,"accelerationX",0,!0),this.accelerationY=new h(e,"accelerationY",0,!0),this.maxVelocityX=new h(e,"maxVelocityX",1e4,!0),this.maxVelocityY=new h(e,"maxVelocityY",1e4,!0),this.speedX=new h(e,"speedX",0,!0),this.speedY=new h(e,"speedY",0,!0),this.moveTo=!1,this.moveToX=new h(e,"moveToX",0,!0),this.moveToY=new h(e,"moveToY",0,!0),this.bounce=new h(e,"bounce",0,!0),this.scaleX=new h(e,"scaleX",1),this.scaleY=new h(e,"scaleY",1),this.tint=new h(e,"tint",4294967295),this.alpha=new h(e,"alpha",1),this.lifespan=new h(e,"lifespan",1e3,!0),this.angle=new h(e,"angle",{min:0,max:360},!0),this.rotate=new h(e,"rotate",0),this.emitCallback=null,this.emitCallbackScope=null,this.deathCallback=null,this.deathCallbackScope=null,this.maxParticles=0,this.quantity=new h(e,"quantity",1,!0),this.delay=new h(e,"delay",0,!0),this.frequency=0,this.on=!0,this.particleBringToTop=!0,this.timeScale=1,this.emitZone=null,this.deathZone=null,this.bounds=null,this.collideLeft=!0,this.collideRight=!0,this.collideTop=!0,this.collideBottom=!0,this.active=!0,this.visible=!0,this.blendMode=n.NORMAL,this.follow=null,this.followOffset=new m,this.trackVisible=!1,this.currentFrame=0,this.randomFrame=!0,this.frameQuantity=1,this.dead=[],this.alive=[],this._counter=0,this._frameCounter=0,e&&this.fromJSON(e)},fromJSON:function(t){if(!t)return this;var e=0,i="";for(e=0;e0&&this.getParticleCount()===this.maxParticles},onParticleEmit:function(t,e){return void 0===t?(this.emitCallback=null,this.emitCallbackScope=null):"function"==typeof t&&(this.emitCallback=t,e&&(this.emitCallbackScope=e)),this},onParticleDeath:function(t,e){return void 0===t?(this.deathCallback=null,this.deathCallbackScope=null):"function"==typeof t&&(this.deathCallback=t,e&&(this.deathCallbackScope=e)),this},killAll:function(){for(var t=this.dead,e=this.alive;e.length>0;)t.push(e.pop());return this},forEachAlive:function(t,e){for(var i=this.alive,n=i.length,s=0;s0){var u=this.deathCallback,c=this.deathCallbackScope;for(o=h-1;o>=0;o--){var d=a[o];s.splice(d.index,1),r.push(d.particle),u&&u.call(c,d.particle),d.particle.resetPosition()}}this.on&&(0===this.frequency?this.emitParticle():this.frequency>0&&(this._counter-=e,this._counter<=0&&(this.emitParticle(),this._counter=this.frequency-Math.abs(this._counter))))},depthSortCallback:function(t,e){return t.y-e.y}});t.exports=x},function(t,e,i){var n=new(i(0))({initialize:function(t,e){this.source=t,this.killOnEnter=e},willKill:function(t){var e=this.source.contains(t.x,t.y);return e&&this.killOnEnter||!e&&!this.killOnEnter}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s){void 0===n&&(n=!1),void 0===s&&(s=!0),this.source=t,this.points=[],this.quantity=e,this.stepRate=i,this.yoyo=n,this.counter=-1,this.seamless=s,this._length=0,this._direction=0,this.updateSource()},updateSource:function(){if(this.points=this.source.getPoints(this.quantity,this.stepRate),this.seamless){var t=this.points[0],e=this.points[this.points.length-1];t.x===e.x&&t.y===e.y&&this.points.pop()}var i=this._length;return this._length=this.points.length,this._lengththis._length&&(this.counter=this._length-1),this},changeSource:function(t){return this.source=t,this.updateSource()},getPoint:function(t){0===this._direction?(this.counter++,this.counter>=this._length&&(this.yoyo?(this._direction=1,this.counter=this._length-1):this.counter=0)):(this.counter--,-1===this.counter&&(this.yoyo?(this._direction=0,this.counter=0):this.counter=this._length-1));var e=this.points[this.counter];e&&(t.x=e.x,t.y=e.y)}});t.exports=n},function(t,e){t.exports=function(t,e){for(var i=0;i0&&(s=-h.PI2+s%h.PI2):s>h.PI2?s=h.PI2:s<0&&(s=h.PI2+s%h.PI2);for(var u,c=[a+Math.cos(n)*i,l+Math.sin(n)*i];e<1;)u=s*e+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),e+=t;return u=s+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),c.push(a+Math.cos(n)*i,l+Math.sin(n)*i),this.pathIndexes=o(c),this.pathData=c,this}});t.exports=u},function(t,e,i){var n=i(0),s=i(994),r=i(64),o=i(13),a=i(31),h=new n({Extends:a,Mixins:[s],initialize:function(t,e,i,n,s,r){void 0===e&&(e=0),void 0===i&&(i=0),a.call(this,t,"Curve",n),this._smoothness=32,this._curveBounds=new o,this.closePath=!1,this.setPosition(e,i),void 0!==s&&this.setFillStyle(s,r),this.updateData()},smoothness:{get:function(){return this._smoothness},set:function(t){this._smoothness=t,this.updateData()}},setSmoothness:function(t){return this._smoothness=t,this.updateData()},updateData:function(){var t=this._curveBounds,e=this._smoothness;this.geom.getBounds(t,e),this.setSize(t.width,t.height),this.updateDisplayOrigin();for(var i=[],n=this.geom.getPoints(e),s=0;sc+v)){var m=g.getPoint((u-c)/v);o.push(m);break}c+=v}return o}},function(t,e,i){var n=i(57),s=i(56);t.exports=function(t){for(var e=t.points,i=0,r=0;r0&&r.push(i([0,0],n[0])),e=0;e1&&r.push(i([0,0],n[n.length-1])),t.setTo(r)}},function(t,e,i){var n=i(0),s=i(13),r=i(31),o=i(1015),a=new n({Extends:r,Mixins:[o],initialize:function(t,e,i,n,o,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=128),void 0===o&&(o=128),r.call(this,t,"Rectangle",new s(0,0,n,o)),this.setPosition(e,i),this.setSize(n,o),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},updateData:function(){var t=[],e=this.geom,i=this._tempLine;return e.getLineA(i),t.push(i.x1,i.y1,i.x2,i.y2),e.getLineB(i),t.push(i.x2,i.y2),e.getLineC(i),t.push(i.x2,i.y2),e.getLineD(i),t.push(i.x2,i.y2),this.pathData=t,this}});t.exports=a},function(t,e,i){var n=i(1018),s=i(0),r=i(64),o=i(31),a=new s({Extends:o,Mixins:[n],initialize:function(t,e,i,n,s,r,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=5),void 0===s&&(s=32),void 0===r&&(r=64),o.call(this,t,"Star",null),this._points=n,this._innerRadius=s,this._outerRadius=r,this.setPosition(e,i),this.setSize(2*r,2*r),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},setPoints:function(t){return this._points=t,this.updateData()},setInnerRadius:function(t){return this._innerRadius=t,this.updateData()},setOuterRadius:function(t){return this._outerRadius=t,this.updateData()},points:{get:function(){return this._points},set:function(t){this._points=t,this.updateData()}},innerRadius:{get:function(){return this._innerRadius},set:function(t){this._innerRadius=t,this.updateData()}},outerRadius:{get:function(){return this._outerRadius},set:function(t){this._outerRadius=t,this.updateData()}},updateData:function(){var t=[],e=this._points,i=this._innerRadius,n=this._outerRadius,s=Math.PI/2*3,o=Math.PI/e,a=n,h=n;t.push(a,h+-n);for(var l=0;l=1)return i.x=r.x1,i.y=r.y1,i;var h=s(r),l=s(o),u=s(a),c=(h+l+u)*e,d=0;return ch+l?(d=(c-=h+l)/u,i.x=a.x1+(a.x2-a.x1)*d,i.y=a.y1+(a.y2-a.y1)*d):(d=(c-=h)/l,i.x=o.x1+(o.x2-o.x1)*d,i.y=o.y1+(o.y2-o.y1)*d),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]);var o=t.getLineA(),a=t.getLineB(),h=t.getLineC(),l=n(o),u=n(a),c=n(h),d=l+u+c;e||(e=d/i);for(var f=0;fl+u?(g=(p-=l+u)/c,v.x=h.x1+(h.x2-h.x1)*g,v.y=h.y1+(h.y2-h.y1)*g):(g=(p-=l)/u,v.x=a.x1+(a.x2-a.x1)*g,v.y=a.y1+(a.y2-a.y1)*g),r.push(v)}return r}},function(t,e){t.exports=function(t,e,i){if(!t||"number"==typeof t)return!1;if(t.hasOwnProperty(e))return t[e]=i,!0;if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=t,o=0;o0?(h=this.lightPool.pop()).set(t,e,i,a[0],a[1],a[2],o):h=new s(t,e,i,a[0],a[1],a[2],o),this.lights.push(h),h},removeLight:function(t){var e=this.lights.indexOf(t);return e>=0&&(this.lightPool.push(t),this.lights.splice(e,1)),this},shutdown:function(){for(;this.lights.length>0;)this.lightPool.push(this.lights.pop());this.ambientColor={r:.1,g:.1,b:.1},this.culledLights.length=0,this.lights.length=0},destroy:function(){this.shutdown()}});t.exports=o},function(t,e,i){var n=i(46),s=i(18),r={Circle:i(1081),Ellipse:i(1091),Intersects:i(424),Line:i(1110),Point:i(1132),Polygon:i(1146),Rectangle:i(437),Triangle:i(1176)};r=s(!1,r,n),t.exports=r},function(t,e,i){t.exports={CircleToCircle:i(200),CircleToRectangle:i(201),GetCircleToCircle:i(1101),GetCircleToRectangle:i(1102),GetLineToCircle:i(202),GetLineToRectangle:i(204),GetRectangleIntersection:i(1103),GetRectangleToRectangle:i(1104),GetRectangleToTriangle:i(1105),GetTriangleToCircle:i(1106),GetTriangleToLine:i(429),GetTriangleToTriangle:i(1107),LineToCircle:i(203),LineToLine:i(82),LineToRectangle:i(425),PointToLine:i(433),PointToLineSegment:i(1108),RectangleToRectangle:i(129),RectangleToTriangle:i(426),RectangleToValues:i(1109),TriangleToCircle:i(428),TriangleToLine:i(430),TriangleToTriangle:i(431)}},function(t,e){t.exports=function(t,e){var i=t.x1,n=t.y1,s=t.x2,r=t.y2,o=e.x,a=e.y,h=e.right,l=e.bottom,u=0;if(i>=o&&i<=h&&n>=a&&n<=l||s>=o&&s<=h&&r>=a&&r<=l)return!0;if(i=o){if((u=n+(r-n)*(o-i)/(s-i))>a&&u<=l)return!0}else if(i>h&&s<=h&&(u=n+(r-n)*(h-i)/(s-i))>=a&&u<=l)return!0;if(n=a){if((u=i+(s-i)*(a-n)/(r-n))>=o&&u<=h)return!0}else if(n>l&&r<=l&&(u=i+(s-i)*(l-n)/(r-n))>=o&&u<=h)return!0;return!1}},function(t,e,i){var n=i(82),s=i(47),r=i(205),o=i(427);t.exports=function(t,e){if(e.left>t.right||e.rightt.bottom||e.bottom0}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x,y:t.y}),e.push({x:t.right,y:t.y}),e.push({x:t.right,y:t.bottom}),e.push({x:t.x,y:t.bottom}),e}},function(t,e,i){var n=i(203),s=i(81);t.exports=function(t,e){return!(t.left>e.right||t.righte.bottom||t.bottome.right||t.righte.bottom||t.bottom0||(c=s(e),(d=n(t,c,!0)).length>0)}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x1,y:t.y1}),e.push({x:t.x2,y:t.y2}),e.push({x:t.x3,y:t.y3}),e}},function(t,e){t.exports=function(t,e,i){void 0===i&&(i=1);var n=e.x1,s=e.y1,r=e.x2,o=e.y2,a=t.x,h=t.y,l=(r-n)*(r-n)+(o-s)*(o-s);if(0===l)return!1;var u=((a-n)*(r-n)+(h-s)*(o-s))/l;if(u<0)return Math.sqrt((n-a)*(n-a)+(s-h)*(s-h))<=i;if(u>=0&&u<=1){var c=((s-h)*(r-n)-(n-a)*(o-s))/l;return Math.abs(c)*Math.sqrt(l)<=i}return Math.sqrt((r-a)*(r-a)+(o-h)*(o-h))<=i}},function(t,e,i){var n=i(16),s=i(58),r=i(83);t.exports=function(t){var e=r(t)-n.TAU;return s(e,-Math.PI,Math.PI)}},function(t,e){t.exports=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)}},function(t,e){t.exports=function(t){return t.x*t.x+t.y*t.y}},function(t,e,i){var n=i(13);n.Area=i(1151),n.Ceil=i(1152),n.CeilAll=i(1153),n.CenterOn=i(162),n.Clone=i(1154),n.Contains=i(47),n.ContainsPoint=i(1155),n.ContainsRect=i(438),n.CopyFrom=i(1156),n.Decompose=i(427),n.Equals=i(1157),n.FitInside=i(1158),n.FitOutside=i(1159),n.Floor=i(1160),n.FloorAll=i(1161),n.FromPoints=i(171),n.GetAspectRatio=i(207),n.GetCenter=i(1162),n.GetPoint=i(146),n.GetPoints=i(269),n.GetSize=i(1163),n.Inflate=i(1164),n.Intersection=i(1165),n.MarchingAnts=i(280),n.MergePoints=i(1166),n.MergeRect=i(1167),n.MergeXY=i(1168),n.Offset=i(1169),n.OffsetPoint=i(1170),n.Overlaps=i(1171),n.Perimeter=i(108),n.PerimeterPoint=i(1172),n.Random=i(149),n.RandomOutside=i(1173),n.SameDimensions=i(1174),n.Scale=i(1175),n.Union=i(387),t.exports=n},function(t,e){t.exports=function(t,e){return!(e.width*e.height>t.width*t.height)&&e.x>t.x&&e.xt.x&&e.rightt.y&&e.yt.y&&e.bottom=this.threshold?this.pressed||(this.pressed=!0,this.events.emit(s.BUTTON_DOWN,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_DOWN,i,t,this)):this.pressed&&(this.pressed=!1,this.events.emit(s.BUTTON_UP,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_UP,i,t,this))},destroy:function(){this.pad=null,this.events=null}});t.exports=r},function(t,e,i){var n=i(443),s=i(444),r=i(0),o=i(11),a=i(3),h=new r({Extends:o,initialize:function(t,e){o.call(this),this.manager=t,this.pad=e,this.id=e.id,this.index=e.index;for(var i=[],r=0;r=2&&(this.leftStick.set(r[0].getValue(),r[1].getValue()),s>=4&&this.rightStick.set(r[2].getValue(),r[3].getValue()))},destroy:function(){var t;for(this.removeAllListeners(),this.manager=null,this.pad=null,t=0;t=r;for(i=0;i=r;)this._elapsed-=r,this.step(s)}},step:function(t){var e,i,n=this.bodies.entries,s=n.length;for(e=0;e0){var l=this.tree,u=this.staticTree;for(n=(i=h.entries).length,t=0;t-1&&p>g&&(t.velocity.normalize().scale(g),p=g),t.speed=p},separate:function(t,e,i,n,s){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(n,t.gameObject,e.gameObject))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,s);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h=o.center;if((h.ya.bottom)&&(h.xa.right))return this.separateCircle(t,e,s)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)r.right&&(s=h(o.x,o.y,r.right,r.y)-o.radius):o.y>r.bottom&&(o.xr.right&&(s=h(o.x,o.y,r.right,r.bottom)-o.radius)),s*=-1}else s=t.halfWidth+e.halfWidth-h(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s&&(t.onOverlap||e.onOverlap)&&this.emit(u.OVERLAP,t.gameObject,e.gameObject,t,e),0!==s;var a=t.center.x-e.center.x,l=t.center.y-e.center.y,c=Math.sqrt(Math.pow(a,2)+Math.pow(l,2)),d=(e.center.x-t.center.x)/c||0,f=(e.center.y-t.center.y)/c||0,v=2*(t.velocity.x*d+t.velocity.y*f-e.velocity.x*d-e.velocity.y*f)/(t.mass+e.mass);t.immovable||(t.velocity.x=t.velocity.x-v*t.mass*d,t.velocity.y=t.velocity.y-v*t.mass*f),e.immovable||(e.velocity.x=e.velocity.x+v*e.mass*d,e.velocity.y=e.velocity.y+v*e.mass*f);var m=e.velocity.x-t.velocity.x,y=e.velocity.y-t.velocity.y,x=Math.atan2(y,m),T=this._frameTime;return t.immovable||e.immovable||(s/=2),t.immovable||(t.x+=t.velocity.x*T-s*Math.cos(x),t.y+=t.velocity.y*T-s*Math.sin(x)),e.immovable||(e.x+=e.velocity.x*T+s*Math.cos(x),e.y+=e.velocity.y*T+s*Math.sin(x)),t.velocity.x*=t.bounce.x,t.velocity.y*=t.bounce.y,e.velocity.x*=e.bounce.x,e.velocity.y*=e.bounce.y,(t.onCollide||e.onCollide)&&this.emit(u.COLLIDE,t.gameObject,e.gameObject,t,e),!0},intersects:function(t,e){return t!==e&&(t.isCircle||e.isCircle?t.isCircle?e.isCircle?h(t.center.x,t.center.y,e.center.x,e.center.y)<=t.halfWidth+e.halfWidth:this.circleBodyIntersects(t,e):this.circleBodyIntersects(e,t):!(t.right<=e.position.x||t.bottom<=e.position.y||t.position.x>=e.right||t.position.y>=e.bottom))},circleBodyIntersects:function(t,e){var i=s(t.center.x,e.left,e.right),n=s(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},overlap:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!0)},collide:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!1)},collideObjects:function(t,e,i,n,s,r){var o,a;t.isParent&&void 0===t.physicsType&&(t=t.children.entries),e&&e.isParent&&void 0===e.physicsType&&(e=e.children.entries);var h=Array.isArray(t),l=Array.isArray(e);if(this._total=0,h||l)if(!h&&l)for(o=0;o0},collideHandler:function(t,e,i,n,s,r){if(void 0===e&&t.isParent)return this.collideGroupVsGroup(t,t,i,n,s,r);if(!t||!e)return!1;if(t.body){if(e.body)return this.collideSpriteVsSprite(t,e,i,n,s,r);if(e.isParent)return this.collideSpriteVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideSpriteVsTilemapLayer(t,e,i,n,s,r)}else if(t.isParent){if(e.body)return this.collideSpriteVsGroup(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideGroupVsTilemapLayer(t,e,i,n,s,r)}else if(t.isTilemap){if(e.body)return this.collideSpriteVsTilemapLayer(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsTilemapLayer(e,t,i,n,s,r)}},collideSpriteVsSprite:function(t,e,i,n,s,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,n,s,r)&&(i&&i.call(s,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,n,s,r){var o,h,l,u=t.body;if(0!==e.length&&u&&u.enable)if(this.useTree){var c=this.treeMinMax;c.minX=u.left,c.minY=u.top,c.maxX=u.right,c.maxY=u.bottom;var d=e.physicsType===a.DYNAMIC_BODY?this.tree.search(c):this.staticTree.search(c);for(h=d.length,o=0;oc.baseTileWidth){var d=(c.tileWidth-c.baseTileWidth)*e.scaleX;a-=d,l+=d}c.tileHeight>c.baseTileHeight&&(u+=(c.tileHeight-c.baseTileHeight)*e.scaleY);var f=e.getTilesWithinWorldXY(a,h,l,u);return 0!==f.length&&this.collideSpriteVsTilesHandler(t,f,i,n,s,r,!0)},collideSpriteVsTilesHandler:function(t,e,i,n,s,r,o){for(var a,h,l=t.body,c={left:0,right:0,top:0,bottom:0},d=!1,f=0;f0&&t>i&&(t=i)),0!==n&&0!==e&&(e<0&&e<-n?e=-n:e>0&&e>n&&(e=n)),this.gameObject.x+=t,this.gameObject.y+=e}t<0?this.facing=s.FACING_LEFT:t>0&&(this.facing=s.FACING_RIGHT),e<0?this.facing=s.FACING_UP:e>0&&(this.facing=s.FACING_DOWN),this.allowRotation&&(this.gameObject.angle+=this.deltaZ()),this._tx=t,this._ty=e},setBoundsRectangle:function(t){return this.customBoundsRectangle=t||this.world.bounds,this},checkWorldBounds:function(){var t=this.position,e=this.customBoundsRectangle,i=this.world.checkCollision,n=this.worldBounce?-this.worldBounce.x:-this.bounce.x,s=this.worldBounce?-this.worldBounce.y:-this.bounce.y,r=!1;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=n,this.blocked.right=!0,r=!0),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=s,this.blocked.down=!0,r=!0),r&&(this.blocked.none=!1),r},setOffset:function(t,e){return void 0===e&&(e=t),this.offset.set(t,e),this.updateCenter(),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter(),i&&n.getCenter){var s=(n.width-t)/2,r=(n.height-e)/2;this.offset.set(s,r)}return this.isCircle=!1,this.radius=0,this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter()):this.isCircle=!1,this},reset:function(t,e){this.stop();var i=this.gameObject;i.setPosition(t,e),i.getTopLeft?i.getTopLeft(this.position):this.position.set(t,e),this.prev.copy(this.position),this.prevFrame.copy(this.position),this.rotation=i.angle,this.preRotation=i.angle,this.updateBounds(),this.updateCenter()},stop:function(){return this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?this.radius>0&&t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom&&(this.center.x-t)*(this.center.x-t)+(this.center.y-e)*(this.center.y-e)<=this.radius*this.radius:h(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this._dx>0?this._dx:-this._dx},deltaAbsY:function(){return this._dy>0?this._dy:-this._dy},deltaX:function(){return this._dx},deltaY:function(){return this._dy},deltaXFinal:function(){return this._tx},deltaYFinal:function(){return this._ty},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.enable=!1,this.world&&this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor),this.isCircle?t.strokeCircle(i,n,this.width/2):(this.checkCollision.up&&t.lineBetween(e.x,e.y,e.x+this.width,e.y),this.checkCollision.right&&t.lineBetween(e.x+this.width,e.y,e.x+this.width,e.y+this.height),this.checkCollision.down&&t.lineBetween(e.x,e.y+this.height,e.x+this.width,e.y+this.height),this.checkCollision.left&&t.lineBetween(e.x,e.y,e.x,e.y+this.height))),this.debugShowVelocity&&(t.lineStyle(t.defaultStrokeWidth,this.world.defaults.velocityDebugColor,1),t.lineBetween(i,n,i+this.velocity.x/2,n+this.velocity.y/2))},willDrawDebug:function(){return this.debugShowBody||this.debugShowVelocity},setCollideWorldBounds:function(t,e,i){void 0===t&&(t=!0),this.collideWorldBounds=t;var n=void 0!==e,s=void 0!==i;return(n||s)&&(this.worldBounce||(this.worldBounce=new l),n&&(this.worldBounce.x=e),s&&(this.worldBounce.y=i)),this},setVelocity:function(t,e){return this.velocity.set(t,e),t=this.velocity.x,e=this.velocity.y,this.speed=Math.sqrt(t*t+e*e),this},setVelocityX:function(t){this.velocity.x=t;var e=t,i=this.velocity.y;return this.speed=Math.sqrt(e*e+i*i),this},setVelocityY:function(t){this.velocity.y=t;var e=this.velocity.x,i=t;return this.speed=Math.sqrt(e*e+i*i),this},setMaxVelocity:function(t,e){return this.maxVelocity.set(t,e),this},setMaxSpeed:function(t){return this.maxSpeed=t,this},setBounce:function(t,e){return this.bounce.set(t,e),this},setBounceX:function(t){return this.bounce.x=t,this},setBounceY:function(t){return this.bounce.y=t,this},setAcceleration:function(t,e){return this.acceleration.set(t,e),this},setAccelerationX:function(t){return this.acceleration.x=t,this},setAccelerationY:function(t){return this.acceleration.y=t,this},setAllowDrag:function(t){return void 0===t&&(t=!0),this.allowDrag=t,this},setAllowGravity:function(t){return void 0===t&&(t=!0),this.allowGravity=t,this},setAllowRotation:function(t){return void 0===t&&(t=!0),this.allowRotation=t,this},setDrag:function(t,e){return this.drag.set(t,e),this},setDragX:function(t){return this.drag.x=t,this},setDragY:function(t){return this.drag.y=t,this},setGravity:function(t,e){return this.gravity.set(t,e),this},setGravityX:function(t){return this.gravity.x=t,this},setGravityY:function(t){return this.gravity.y=t,this},setFriction:function(t,e){return this.friction.set(t,e),this},setFrictionX:function(t){return this.friction.x=t,this},setFrictionY:function(t){return this.friction.y=t,this},setAngularVelocity:function(t){return this.angularVelocity=t,this},setAngularAcceleration:function(t){return this.angularAcceleration=t,this},setAngularDrag:function(t){return this.angularDrag=t,this},setMass:function(t){return this.mass=t,this},setImmovable:function(t){return void 0===t&&(t=!0),this.immovable=t,this},setEnable:function(t){return void 0===t&&(t=!0),this.enable=t,this},x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=u},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o){this.world=t,this.name="",this.active=!0,this.overlapOnly=e,this.object1=i,this.object2=n,this.collideCallback=s,this.processCallback=r,this.callbackContext=o},setName:function(t){return this.name=t,this},update:function(){this.world.collideObjects(this.object1,this.object2,this.collideCallback,this.processCallback,this.callbackContext,this.overlapOnly)},destroy:function(){this.world.removeCollider(this),this.active=!1,this.world=null,this.object1=null,this.object2=null,this.collideCallback=null,this.processCallback=null,this.callbackContext=null}});t.exports=n},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsX()+e.deltaAbsX()+s;return 0===t._dx&&0===e._dx?(t.embedded=!0,e.embedded=!0):t._dx>e._dx?(r=t.right-e.x)>o&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?r=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.right=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.left=!0)):t._dxo&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?r=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.left=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.right=!0))),t.overlapX=r,e.overlapX=r,r}},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsY()+e.deltaAbsY()+s;return 0===t._dy&&0===e._dy?(t.embedded=!0,e.embedded=!0):t._dy>e._dy?(r=t.bottom-e.y)>o&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?r=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.down=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.up=!0)):t._dyo&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?r=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.up=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.down=!0))),t.overlapY=r,e.overlapY=r,r}},function(t,e,i){var n=i(384);function s(t){if(!(this instanceof s))return new s(t,[".left",".top",".right",".bottom"]);this._maxEntries=Math.max(4,t||9),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}function r(t,e,i){if(!i)return e.indexOf(t);for(var n=0;n=t.minX&&e.maxY>=t.minY}function g(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function v(t,e,i,s,r){for(var o,a=[e,i];a.length;)(i=a.pop())-(e=a.pop())<=s||(o=e+Math.ceil((i-e)/s/2)*s,n(t,o,e,i,r),a.push(e,o,o,i))}s.prototype={all:function(){return this._all(this.data,[])},search:function(t){var e=this.data,i=[],n=this.toBBox;if(!p(t,e))return i;for(var s,r,o,a,h=[];e;){for(s=0,r=e.children.length;s=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)},_split:function(t,e){var i=t[e],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);var r=this._chooseSplitIndex(i,s,n),a=g(i.children.splice(r,i.children.length-r));a.height=i.height,a.leaf=i.leaf,o(i,this.toBBox),o(a,this.toBBox),e?t[e-1].children.push(a):this._splitRoot(i,a)},_splitRoot:function(t,e){this.data=g([t,e]),this.data.height=t.height+1,this.data.leaf=!1,o(this.data,this.toBBox)},_chooseSplitIndex:function(t,e,i){var n,s,r,o,h,l,u,d,f,p,g,v,m,y;for(l=u=1/0,n=e;n<=i-e;n++)s=a(t,0,n,this.toBBox),r=a(t,n,i,this.toBBox),f=s,p=r,void 0,void 0,void 0,void 0,g=Math.max(f.minX,p.minX),v=Math.max(f.minY,p.minY),m=Math.min(f.maxX,p.maxX),y=Math.min(f.maxY,p.maxY),o=Math.max(0,m-g)*Math.max(0,y-v),h=c(s)+c(r),o=e;s--)r=t.children[s],h(u,t.leaf?o(r):r),c+=d(u);return c},_adjustParentBBoxes:function(t,e,i){for(var n=i;n>=0;n--)h(e[n],t)},_condense:function(t){for(var e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children).splice(e.indexOf(t[i]),1):this.clear():o(t[i],this.toBBox)},compareMinX:function(t,e){return t.left-e.left},compareMinY:function(t,e){return t.top-e.top},toBBox:function(t){return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}},t.exports=s},function(t,e){t.exports=function(t,e){return!(e.right<=t.left||e.bottom<=t.top||e.position.x>=t.right||e.position.y>=t.bottom)}},function(t,e,i){var n=i(55),s=i(0),r=i(50),o=i(47),a=i(3),h=new s({initialize:function(t,e){var i=e.displayWidth?e.displayWidth:64,n=e.displayHeight?e.displayHeight:64;this.world=t,this.gameObject=e,this.debugShowBody=t.defaults.debugShowStaticBody,this.debugBodyColor=t.defaults.staticBodyDebugColor,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new a,this.position=new a(e.x-e.displayOriginX,e.y-e.displayOriginY),this.width=i,this.height=n,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center=new a(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.velocity=a.ZERO,this.allowGravity=!1,this.gravity=a.ZERO,this.bounce=a.ZERO,this.onWorldBounds=!1,this.onCollide=!1,this.onOverlap=!1,this.mass=1,this.immovable=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.physicsType=r.STATIC_BODY,this._dx=0,this._dy=0},setGameObject:function(t,e){return t&&t!==this.gameObject&&(this.gameObject.body=null,t.body=this,this.gameObject=t),e&&this.updateFromGameObject(),this},updateFromGameObject:function(){this.world.staticTree.remove(this);var t=this.gameObject;return t.getTopLeft(this.position),this.width=t.displayWidth,this.height=t.displayHeight,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.world.staticTree.insert(this),this},setOffset:function(t,e){return void 0===e&&(e=t),this.world.staticTree.remove(this),this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(t,e),this.position.x+=this.offset.x,this.position.y+=this.offset.y,this.updateCenter(),this.world.staticTree.insert(this),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.world.staticTree.remove(this),this.width=t,this.height=e,this.halfWidth=Math.floor(t/2),this.halfHeight=Math.floor(e/2),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(s-this.halfWidth,r-this.halfHeight),this.position.x+=this.offset.x,this.position.y+=this.offset.y}return this.updateCenter(),this.isCircle=!1,this.radius=0,this.world.staticTree.insert(this),this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.world.staticTree.remove(this),this.isCircle=!0,this.radius=t,this.width=2*t,this.height=2*t,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter(),this.world.staticTree.insert(this)):this.isCircle=!1,this},updateCenter:function(){this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(t,e){var i=this.gameObject;void 0===t&&(t=i.x),void 0===e&&(e=i.y),this.world.staticTree.remove(this),i.setPosition(t,e),i.getTopLeft(this.position),this.updateCenter(),this.world.staticTree.insert(this)},stop:function(){return this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?n(this,t,e):o(this,t,e)},postUpdate:function(){},deltaAbsX:function(){return 0},deltaAbsY:function(){return 0},deltaX:function(){return 0},deltaY:function(){return 0},deltaZ:function(){return 0},destroy:function(){this.enable=!1,this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor,1),this.isCircle?t.strokeCircle(i,n,this.width/2):t.strokeRect(e.x,e.y,this.width,this.height))},willDrawDebug:function(){return this.debugShowBody},setMass:function(t){return t<=0&&(t=.1),this.mass=t,this},x:{get:function(){return this.position.x},set:function(t){this.world.staticTree.remove(this),this.position.x=t,this.world.staticTree.insert(this)}},y:{get:function(){return this.position.y},set:function(t){this.world.staticTree.remove(this),this.position.y=t,this.world.staticTree.insert(this)}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=h},function(t,e){var i={};t.exports=i,i.create=function(t,e){var n=t.bodyA,s=t.bodyB,r={id:i.id(n,s),bodyA:n,bodyB:s,activeContacts:[],separation:0,isActive:!0,confirmedActive:!0,isSensor:n.isSensor||s.isSensor,timeCreated:e,timeUpdated:e,collision:null,inverseMass:0,friction:0,frictionStatic:0,restitution:0,slop:0};return i.update(r,t,e),r},i.update=function(t,e,n){if(t.collision=e,e.collided){var s=e.supports,r=t.activeContacts,o=e.parentA,a=e.parentB;t.inverseMass=o.inverseMass+a.inverseMass,t.friction=Math.min(o.friction,a.friction),t.frictionStatic=Math.max(o.frictionStatic,a.frictionStatic),t.restitution=Math.max(o.restitution,a.restitution),t.slop=Math.max(o.slop,a.slop);for(var h=0;h-1}return!1}},function(t,e,i){var n=i(72),s=i(99),r=i(215);t.exports=function(t,e,i,o,a){if(void 0===i&&(i=!1),void 0===o&&(o=!0),!s(t,e,a))return null;var h=a.data[e][t];return h?(a.data[e][t]=i?null:new n(a,-1,t,e,a.tileWidth,a.tileHeight),o&&h&&h.collides&&r(t,e,a),h):null}},function(t,e,i){var n=i(10),s=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileWidth,r=n.tilemapLayer;return r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.x+i.scrollX*(1-r.scrollFactorX),s*=r.scaleX),e?Math.floor(t/s):t/s},r=function(){return console.warn("With the current map type you have to use the WorldToTileXY function."),null};t.exports=function(t){switch(t){case n.ORTHOGONAL:return s;default:return r}}},function(t,e,i){var n=i(10),s=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileHeight,r=n.tilemapLayer;return r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.y+i.scrollY*(1-r.scrollFactorY),s*=r.scaleY),e?Math.floor(t/s):t/s},r=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileHeight,r=n.tilemapLayer;return r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.y+i.scrollY*(1-r.scrollFactorY),s*=r.scaleY),e?Math.floor(t/(s/2)):t/(s/2)},o=function(t,e,i,n){void 0===e&&(e=!0);var s=n.baseTileHeight,r=n.tilemapLayer;r&&(void 0===i&&(i=r.scene.cameras.main),t-=r.y+i.scrollY*(1-r.scrollFactorY),s*=r.scaleY);var o=n.hexSideLength,a=(s-o)/2+o;return e?Math.floor(t/a):t/a},a=function(){return console.warn("With the current map type you have to use the WorldToTileXY function."),null};t.exports=function(t){switch(t){case n.ORTHOGONAL:return s;case n.HEXAGONAL:return o;case n.STAGGERED:return r;default:return a}}},function(t,e,i){var n=i(33),s=i(218),r=i(474),o=i(475),a=i(486);t.exports=function(t,e,i,h,l,u){var c;switch(e){case n.ARRAY_2D:c=s(t,i,h,l,u);break;case n.CSV:c=r(t,i,h,l,u);break;case n.TILED_JSON:c=o(t,i,u);break;case n.WELTMEISTER:c=a(t,i,u);break;default:console.warn("Unrecognized tilemap data format: "+e),c=null}return c}},function(t,e,i){var n=i(33),s=i(218);t.exports=function(t,e,i,r,o){var a=e.trim().split("\n").map(function(t){return t.split(",")}),h=s(t,a,i,r,o);return h.format=n.CSV,h}},function(t,e,i){var n=i(10),s=i(33),r=i(101),o=i(476),a=i(478),h=i(479),l=i(482),u=i(484),c=i(485);t.exports=function(t,e,i){if("isometric"===e.orientation||"staggered"===e.orientation)console.warn("Isometric map types are WIP in this version of Phaser");else if("hexagonal"===e.orientation)console.warn("Hexagonal map types are WIP in this version of Phaser");else if("orthogonal"!==e.orientation)return console.warn("Only orthogonal, hexagonal and isometric map types are supported in this version of Phaser"),null;var d=new r({width:e.width,height:e.height,name:t,tileWidth:e.tilewidth,tileHeight:e.tileheight,orientation:n.fromOrientationString(e.orientation),format:s.TILED_JSON,version:e.version,properties:e.properties,renderOrder:e.renderorder,infinite:e.infinite});d.orientation===n.HEXAGONAL&&(d.hexSideLength=e.hexsidelength),d.layers=o(e,i),d.images=a(e);var f=h(e);return d.tilesets=f.tilesets,d.imageCollections=f.imageCollections,d.objects=l(e),d.tiles=u(d),c(d),d}},function(t,e,i){var n=i(10),s=i(477),r=i(2),o=i(100),a=i(219),h=i(72),l=i(220);t.exports=function(t,e){for(var i=r(t,"infinite",!1),u=[],c=[],d=l(t);d.i0;)if(d.i>=d.layers.length){if(c.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}d=c.pop()}else{var f=d.layers[d.i];if(d.i++,"tilelayer"===f.type)if(f.compression)console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+f.name+"'");else{if(f.encoding&&"base64"===f.encoding){if(f.chunks)for(var p=0;p0?((m=new h(g,v.gid,R,L,t.tilewidth,t.tileheight)).rotation=v.rotation,m.flipX=v.flipped,x[L][R]=m):(y=e?null:new h(g,-1,R,L,t.tilewidth,t.tileheight),x[L][R]=y),++T===A.width&&(M++,T=0)}}else{(g=new o({name:d.name+f.name,x:d.x+r(f,"offsetx",0)+f.x,y:d.y+r(f,"offsety",0)+f.y,width:f.width,height:f.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,alpha:d.opacity*f.opacity,visible:d.visible&&f.visible,properties:r(f,"properties",{}),orientation:n.fromOrientationString(t.orientation)})).orientation===n.HEXAGONAL&&(g.hexSideLength=t.hexsidelength);for(var D=[],F=0,k=f.data.length;F0?((m=new h(g,v.gid,T,x.length,t.tilewidth,t.tileheight)).rotation=v.rotation,m.flipX=v.flipped,D.push(m)):(y=e?null:new h(g,-1,T,x.length,t.tilewidth,t.tileheight),D.push(y)),++T===f.width&&(x.push(D),T=0,D=[])}g.data=x,u.push(g)}else if("group"===f.type){var I=l(t,f,d);c.push(d),d=I}}return u}},function(t,e){t.exports=function(t){for(var e=window.atob(t),i=e.length,n=new Array(i/4),s=0;s>>0;return n}},function(t,e,i){var n=i(2),s=i(220);t.exports=function(t){for(var e=[],i=[],r=s(t);r.i0;)if(r.i>=r.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}r=i.pop()}else{var o=r.layers[r.i];if(r.i++,"imagelayer"===o.type){var a=n(o,"offsetx",0)+n(o,"startx",0),h=n(o,"offsety",0)+n(o,"starty",0);e.push({name:r.name+o.name,image:o.image,x:r.x+a+o.x,y:r.y+h+o.y,alpha:r.opacity*o.opacity,visible:r.visible&&o.visible,properties:n(o,"properties",{})})}else if("group"===o.type){var l=s(t,o,r);i.push(r),r=l}}return e}},function(t,e,i){var n=i(137),s=i(480),r=i(221);t.exports=function(t){for(var e,i=[],o=[],a=null,h=0;h1){if(Array.isArray(l.tiles)){for(var c={},d={},f=0;f=this.firstgid&&t0;)if(a.i>=a.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}a=i.pop()}else{var h=a.layers[a.i];if(a.i++,h.opacity*=a.opacity,h.visible=a.visible&&h.visible,"objectgroup"===h.type){h.name=a.name+h.name;for(var l=a.x+n(h,"startx",0)+n(h,"offsetx",0),u=a.y+n(h,"starty",0)+n(h,"offsety",0),c=[],d=0;da&&(a=e.layer[l].width),e.layer[l].height>h&&(h=e.layer[l].height);var u=new s({width:a,height:h,name:t,tileWidth:e.layer[0].tilesize,tileHeight:e.layer[0].tilesize,format:n.WELTMEISTER});return u.layers=r(e,i),u.tilesets=o(e),u}},function(t,e,i){var n=i(100),s=i(72);t.exports=function(t,e){for(var i=[],r=0;r-1?new s(a,f,c,u,o.tilesize,o.tilesize):e?null:new s(a,-1,c,u,o.tilesize,o.tilesize),h.push(d)}l.push(h),h=[]}a.data=l,i.push(a)}return i}},function(t,e,i){var n=i(137);t.exports=function(t){for(var e=[],i=[],s=0;s-1&&(this.renderOrder=t),this},addTilesetImage:function(t,e,i,n,s,r,o){if(void 0===t)return null;if(void 0!==e&&null!==e||(e=t),!this.scene.sys.textures.exists(e))return console.warn("Invalid Tileset Image: "+e),null;var h=this.scene.sys.textures.get(e),l=this.getTilesetIndex(t);if(null===l&&this.format===a.TILED_JSON)return console.warn("No data found for Tileset: "+t),null;var u=this.tilesets[l];return u?(u.setTileSize(i,n),u.setSpacing(s,r),u.setImage(h),u):(void 0===i&&(i=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o=0),(u=new p(t,o,i,n,s,r)).setImage(h),this.tilesets.push(u),u)},convertLayerToStatic:function(t){if(null===(t=this.getLayer(t)))return null;var e=t.tilemapLayer;if(!(e&&e instanceof r))return null;var i=new c(e.scene,e.tilemap,e.layerIndex,e.tileset,e.x,e.y);return this.scene.sys.displayList.add(i),e.destroy(),i},copy:function(t,e,i,n,s,r,o,a){return a=this.getLayer(a),this._isStaticCall(a,"copy")?this:null!==a?(f.Copy(t,e,i,n,s,r,o,a),this):null},createBlankDynamicLayer:function(t,e,i,n,s,o,a,l){if(void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.width),void 0===o&&(o=this.height),void 0===a&&(a=this.tileWidth),void 0===l&&(l=this.tileHeight),null!==this.getLayerIndex(t))return console.warn("Invalid Tilemap Layer ID: "+t),null;for(var u,c=new h({name:t,tileWidth:a,tileHeight:l,width:s,height:o,orientation:this.orientation}),f=0;f-1&&this.putTileAt(e,r.x,r.y,i,r.tilemapLayer)}return n},removeTileAt:function(t,e,i,n,s){return s=this.getLayer(s),this._isStaticCall(s,"removeTileAt")?null:null===s?null:f.RemoveTileAt(t,e,i,n,s)},removeTileAtWorldXY:function(t,e,i,n,s,r){return r=this.getLayer(r),this._isStaticCall(r,"removeTileAtWorldXY")?null:null===r?null:f.RemoveTileAtWorldXY(t,e,i,n,s,r)},renderDebug:function(t,e,i){return null===(i=this.getLayer(i))?null:(f.RenderDebug(t,e,i),this)},renderDebugFull:function(t,e){for(var i=this.layers,n=0;n=0&&t<4&&(this._renderOrder=t),this},calculateFacesAt:function(t,e){return a.CalculateFacesAt(t,e,this.layer),this},calculateFacesWithin:function(t,e,i,n){return a.CalculateFacesWithin(t,e,i,n,this.layer),this},createFromTiles:function(t,e,i,n,s){return a.CreateFromTiles(t,e,i,n,s,this.layer)},cull:function(t){return this.cullCallback(this.layer,t,this.culledTiles,this._renderOrder)},copy:function(t,e,i,n,s,r,o){return a.Copy(t,e,i,n,s,r,o,this.layer),this},destroy:function(t){void 0===t&&(t=!0),this.tilemap&&(this.layer.tilemapLayer===this&&(this.layer.tilemapLayer=void 0),t&&this.tilemap.removeLayer(this),this.tilemap=void 0,this.layer=void 0,this.culledTiles.length=0,this.cullCallback=null,this.gidMap=[],this.tileset=[],o.prototype.destroy.call(this))},fill:function(t,e,i,n,s,r){return a.Fill(t,e,i,n,s,r,this.layer),this},filterTiles:function(t,e,i,n,s,r,o){return a.FilterTiles(t,e,i,n,s,r,o,this.layer)},findByIndex:function(t,e,i){return a.FindByIndex(t,e,i,this.layer)},findTile:function(t,e,i,n,s,r,o){return a.FindTile(t,e,i,n,s,r,o,this.layer)},forEachTile:function(t,e,i,n,s,r,o){return a.ForEachTile(t,e,i,n,s,r,o,this.layer),this},getTileAt:function(t,e,i){return a.GetTileAt(t,e,i,this.layer)},getTileAtWorldXY:function(t,e,i,n){return a.GetTileAtWorldXY(t,e,i,n,this.layer)},getTilesWithin:function(t,e,i,n,s){return a.GetTilesWithin(t,e,i,n,s,this.layer)},getTilesWithinShape:function(t,e,i){return a.GetTilesWithinShape(t,e,i,this.layer)},getTilesWithinWorldXY:function(t,e,i,n,s,r){return a.GetTilesWithinWorldXY(t,e,i,n,s,r,this.layer)},hasTileAt:function(t,e){return a.HasTileAt(t,e,this.layer)},hasTileAtWorldXY:function(t,e,i){return a.HasTileAtWorldXY(t,e,i,this.layer)},putTileAt:function(t,e,i,n){return a.PutTileAt(t,e,i,n,this.layer)},putTileAtWorldXY:function(t,e,i,n,s){return a.PutTileAtWorldXY(t,e,i,n,s,this.layer)},putTilesAt:function(t,e,i,n){return a.PutTilesAt(t,e,i,n,this.layer),this},randomize:function(t,e,i,n,s){return a.Randomize(t,e,i,n,s,this.layer),this},removeTileAt:function(t,e,i,n){return a.RemoveTileAt(t,e,i,n,this.layer)},removeTileAtWorldXY:function(t,e,i,n,s){return a.RemoveTileAtWorldXY(t,e,i,n,s,this.layer)},renderDebug:function(t,e){return a.RenderDebug(t,e,this.layer),this},replaceByIndex:function(t,e,i,n,s,r){return a.ReplaceByIndex(t,e,i,n,s,r,this.layer),this},setSkipCull:function(t){return void 0===t&&(t=!0),this.skipCull=t,this},setCullPadding:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=1),this.cullPaddingX=t,this.cullPaddingY=e,this},setCollision:function(t,e,i,n){return a.SetCollision(t,e,i,this.layer,n),this},setCollisionBetween:function(t,e,i,n){return a.SetCollisionBetween(t,e,i,n,this.layer),this},setCollisionByProperty:function(t,e,i){return a.SetCollisionByProperty(t,e,i,this.layer),this},setCollisionByExclusion:function(t,e,i){return a.SetCollisionByExclusion(t,e,i,this.layer),this},setCollisionFromCollisionGroup:function(t,e){return a.SetCollisionFromCollisionGroup(t,e,this.layer),this},setTileIndexCallback:function(t,e,i){return a.SetTileIndexCallback(t,e,i,this.layer),this},setTileLocationCallback:function(t,e,i,n,s,r){return a.SetTileLocationCallback(t,e,i,n,s,r,this.layer),this},shuffle:function(t,e,i,n){return a.Shuffle(t,e,i,n,this.layer),this},swapByIndex:function(t,e,i,n,s,r){return a.SwapByIndex(t,e,i,n,s,r,this.layer),this},tileToWorldX:function(t,e){return this.tilemap.TileToWorldX(t,e,this.layer)},tileToWorldY:function(t,e){return this.tilemap.TileToWorldY(t,e,this.layer)},tileToWorldXY:function(t,e,i,n){return this.tilemap.TileToWorldXY(t,e,i,n,this.layer)},weightedRandomize:function(t,e,i,n,s){return a.WeightedRandomize(t,e,i,n,s,this.layer),this},worldToTileX:function(t,e,i){return this.tilemap.WorldToTileX(t,e,i,this.layer)},worldToTileY:function(t,e,i){return this.tilemap.WorldToTileY(t,e,i,this.layer)},worldToTileXY:function(t,e,i,n,s){return this.tilemap.WorldToTileXY(t,e,i,n,s,this.layer)}});t.exports=l},function(t,e,i){var n=i(0),s=i(12),r=i(19),o=i(14),a=i(1341),h=i(135),l=i(30),u=i(9),c=i(3),d=new n({Extends:o,Mixins:[s.Alpha,s.BlendMode,s.ComputedSize,s.Depth,s.Flip,s.GetBounds,s.Origin,s.Pipeline,s.Transform,s.Visible,s.ScrollFactor,a],initialize:function(t,e,i,n,s,a){o.call(this,t,"StaticTilemapLayer"),this.isTilemap=!0,this.tilemap=e,this.layerIndex=i,this.layer=e.layers[i],this.layer.tilemapLayer=this,this.tileset=[],this.culledTiles=[],this.skipCull=!1,this.isoCullDistances=new c(1,1),this.tilesDrawn=0,this.tilesTotal=this.layer.width*this.layer.height,this.cullPaddingX=1,this.cullPaddingY=1,this.cullCallback=h.CullTiles,this.renderer=t.sys.game.renderer,this.vertexBuffer=[],this.bufferData=[],this.vertexViewF32=[],this.vertexViewU32=[],this.dirty=[],this.vertexCount=[],this._renderOrder=0,this._tempMatrix=new l,this.gidMap=[],this.setTilesets(n),this.setAlpha(this.layer.alpha),this.setPosition(s,a),this.setOrigin(),this.setSize(e.tileWidth*this.layer.width,e.tileHeight*this.layer.height),this.updateVBOData(),this.initPipeline("TextureTintPipeline"),t.sys.game.events.on(r.CONTEXT_RESTORED,function(){this.updateVBOData()},this)},setTilesets:function(t){var e=[],i=[],n=this.tilemap;Array.isArray(t)||(t=[t]);for(var s=0;sv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(1===p)for(o=0;o=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(2===p)for(o=u-1;o>=0;o--)for(a=0;av||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(3===p)for(o=u-1;o>=0;o--)for(a=l-1;a>=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));this.dirty[e]=!1,null===m?(m=i.createVertexBuffer(y,n.STATIC_DRAW),this.vertexBuffer[e]=m):(i.setVertexBuffer(m),n.bufferSubData(n.ARRAY_BUFFER,0,y))}return this},batchTile:function(t,e,i,n,s,r,o){var a=i.getTileTextureCoordinates(e.index);if(!a)return t;var h=i.tileWidth,l=i.tileHeight,c=h/2,d=l/2,f=a.x/n,p=a.y/s,g=(a.x+h)/n,v=(a.y+l)/s,m=this._tempMatrix,y=-c,x=-d;e.flipX&&(h*=-1,y+=i.tileWidth),e.flipY&&(l*=-1,x+=i.tileHeight);var T=y+h,w=x+l;m.applyITRS(c+e.pixelX,d+e.pixelY,e.rotation,1,1);var b=u.getTintAppendFloatAlpha(16777215,r.alpha*this.alpha*e.alpha),E=m.getX(y,x),S=m.getY(y,x),A=m.getX(y,w),_=m.getY(y,w),C=m.getX(T,w),M=m.getY(T,w),O=m.getX(T,x),P=m.getY(T,x);r.roundPixels&&(E=Math.round(E),S=Math.round(S),A=Math.round(A),_=Math.round(_),C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P));var R=this.vertexViewF32[o],L=this.vertexViewU32[o];return R[++t]=E,R[++t]=S,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=b,R[++t]=A,R[++t]=_,R[++t]=f,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=E,R[++t]=S,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=b,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=O,R[++t]=P,R[++t]=g,R[++t]=p,R[++t]=0,L[++t]=b,this.vertexCount[o]+=6,t},setRenderOrder:function(t){if("string"==typeof t&&(t=["right-down","left-down","right-up","left-up"].indexOf(t)),t>=0&&t<4){this._renderOrder=t;for(var e=0;e0){var t=this.delay+this.delay*this.repeat;return(this.elapsed+this.delay*(this.repeat-this.repeatCount))/t}return this.getProgress()},getRepeatCount:function(){return this.repeatCount},getElapsed:function(){return this.elapsed},getElapsedSeconds:function(){return.001*this.elapsed},remove:function(t){void 0===t&&(t=!1),this.elapsed=this.delay,this.hasDispatched=!t,this.repeatCount=0},destroy:function(){this.callback=void 0,this.callbackScope=void 0,this.args=[]}});t.exports=r},function(t,e,i){var n=i(1350);t.exports=function(t){var e,i=[];if(t.hasOwnProperty("props"))for(e in t.props)"_"!==e.substr(0,1)&&i.push({key:e,value:t.props[e]});else for(e in t)-1===n.indexOf(e)&&"_"!==e.substr(0,1)&&i.push({key:e,value:t[e]});return i}},function(t,e,i){var n=i(6);t.exports=function(t){var e=n(t,"tweens",null);return null===e?[]:("function"==typeof e&&(e=e.call()),Array.isArray(e)||(e=[e]),e)}},function(t,e,i){var n=i(225),s=i(15),r=i(86),o=i(67),a=i(138),h=i(6),l=i(224),u=i(226),c=i(228);t.exports=function(t,e,i){void 0===i&&(i=n);var d=h(e,"from",0),f=h(e,"to",1),p=[{value:d}],g=a(e,"delay",i.delay),v=a(e,"duration",i.duration),m=h(e,"easeParams",i.easeParams),y=o(h(e,"ease",i.ease),m),x=a(e,"hold",i.hold),T=a(e,"repeat",i.repeat),w=a(e,"repeatDelay",i.repeatDelay),b=r(e,"yoyo",i.yoyo),E=[],S=l("value",f),A=c(p[0],0,"value",S.getEnd,S.getStart,S.getActive,y,g,v,b,x,T,w,!1,!1);A.start=d,A.current=d,A.to=f,E.push(A);var _=new u(t,E,p);_.offset=s(e,"offset",null),_.completeDelay=s(e,"completeDelay",0),_.loop=Math.round(s(e,"loop",0)),_.loopDelay=Math.round(s(e,"loopDelay",0)),_.paused=r(e,"paused",!1),_.useFrames=r(e,"useFrames",!1);for(var C=h(e,"callbackScope",_),M=[_,null],O=u.TYPES,P=0;PS&&(S=C),E[A][_]=C}}}var M=o?n(o):null;return a?function(t,e,n,s){var r,o=0,a=s%m,h=Math.floor(s/m);if(a>=0&&a=0&&h0?Math.floor(v/p.length):h(e,"duration",g.duration),g.delay=h(e,"delay",g.delay),g.easeParams=c(e,"easeParams",g.easeParams),g.ease=a(c(e,"ease",g.ease),g.easeParams),g.hold=h(e,"hold",g.hold),g.repeat=h(e,"repeat",g.repeat),g.repeatDelay=h(e,"repeatDelay",g.repeatDelay),g.yoyo=o(e,"yoyo",g.yoyo),g.flipX=o(e,"flipX",g.flipX),g.flipY=o(e,"flipY",g.flipY);for(var m=0;m0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay},init:function(){return this.calcDuration(),this.progress=0,this.totalProgress=0,!this.paused||(this.state=a.PAUSED,!1)},resetTweens:function(t){for(var e=0;e0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweens(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=a.LOOP_DELAY):(this.state=a.ACTIVE,this.dispatchTimelineEvent(r.TIMELINE_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=a.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=a.PENDING_REMOVE,this.dispatchTimelineEvent(r.TIMELINE_COMPLETE,this.callbacks.onComplete))},update:function(t,e){if(this.state!==a.PAUSED){switch(this.useFrames&&(e=1*this.manager.timeScale),e*=this.timeScale,this.elapsed+=e,this.progress=Math.min(this.elapsed/this.duration,1),this.totalElapsed+=e,this.totalProgress=Math.min(this.totalElapsed/this.totalDuration,1),this.state){case a.ACTIVE:for(var i=this.totalData,n=0;n=this.nextTick&&this.currentAnim.setFrame(this)}},setCurrentFrame:function(t){var e=this.parent;return this.currentFrame=t,e.texture=t.frame.texture,e.frame=t.frame,e.isCropped&&e.frame.updateCropUVs(e._crop,e.flipX,e.flipY),e.setSizeToFrame(),e._originComponent&&(t.frame.customPivot?e.setOrigin(t.frame.pivotX,t.frame.pivotY):e.updateDisplayOrigin()),e},updateFrame:function(t){var e=this.setCurrentFrame(t);if(this.isPlaying){t.setAlpha&&(e.alpha=t.alpha);var i=this.currentAnim;e.emit(r.SPRITE_ANIMATION_KEY_UPDATE+i.key,i,t,e),e.emit(r.SPRITE_ANIMATION_UPDATE,i,t,e),3===this._pendingStop&&this._pendingStopValue===t&&this.currentAnim.completeAnimation(this)}},nextFrame:function(){return this.currentAnim&&this.currentAnim.nextFrame(this),this.parent},previousFrame:function(){return this.currentAnim&&this.currentAnim.previousFrame(this),this.parent},setYoyo:function(t){return void 0===t&&(t=!1),this._yoyo=t,this.parent},getYoyo:function(){return this._yoyo},destroy:function(){this.animationManager.off(r.REMOVE_ANIMATION,this.remove,this),this.animationManager=null,this.parent=null,this.currentAnim=null,this.currentFrame=null}});t.exports=o},function(t,e,i){var n=i(501),s=i(48),r=i(0),o=i(10),a=i(502),h=i(90),l=i(30),u=new r({initialize:function(t){this.game=t,this.type=o.CANVAS,this.drawCount=0,this.width=0,this.height=0,this.config={clearBeforeRender:t.config.clearBeforeRender,backgroundColor:t.config.backgroundColor,resolution:t.config.resolution,antialias:t.config.antialias,roundPixels:t.config.roundPixels},this.gameCanvas=t.canvas;var e={alpha:t.config.transparent,desynchronized:t.config.desynchronized};this.gameContext=this.game.config.context?this.game.config.context:this.gameCanvas.getContext("2d",e),this.currentContext=this.gameContext,this.antialias=t.config.antialias,this.blendModes=a(),this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92},this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.init()},init:function(){this.game.scale.on(h.RESIZE,this.onResize,this);var t=this.game.scale.baseSize;this.resize(t.width,t.height)},onResize:function(t,e){e.width===this.width&&e.height===this.height||this.resize(e.width,e.height)},resize:function(t,e){this.width=t,this.height=e},resetTransform:function(){this.currentContext.setTransform(1,0,0,1,0,0)},setBlendMode:function(t){return this.currentContext.globalCompositeOperation=t,this},setContext:function(t){return this.currentContext=t||this.gameContext,this},setAlpha:function(t){return this.currentContext.globalAlpha=t,this},preRender:function(){var t=this.gameContext,e=this.config,i=this.width,n=this.height;t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),e.clearBeforeRender&&t.clearRect(0,0,i,n),e.transparent||(t.fillStyle=e.backgroundColor.rgba,t.fillRect(0,0,i,n)),t.save(),this.drawCount=0},render:function(t,e,i,n){var r=e.list,o=r.length,a=n._cx,h=n._cy,l=n._cw,u=n._ch,c=n.renderToTexture?n.context:t.sys.context;c.save(),this.game.scene.customViewports&&(c.beginPath(),c.rect(a,h,l,u),c.clip()),this.currentContext=c;var d=n.mask;d&&d.preRenderCanvas(this,null,n._maskCamera),n.transparent||(c.fillStyle=n.backgroundColor.rgba,c.fillRect(a,h,l,u)),c.globalAlpha=n.alpha,c.globalCompositeOperation="source-over",this.drawCount+=r.length,n.renderToTexture&&n.emit(s.PRE_RENDER,n),n.matrix.copyToContext(c);for(var f=0;f=0?y=-(y+d):y<0&&(y=Math.abs(y)-d)),t.flipY&&(x>=0?x=-(x+f):x<0&&(x=Math.abs(x)-f))}var w=1,b=1;t.flipX&&(p||(y+=-e.realWidth+2*v),w=-1),t.flipY&&(p||(x+=-e.realHeight+2*m),b=-1),a.applyITRS(t.x,t.y,t.rotation,t.scaleX*w,t.scaleY*b),o.copyFrom(i.matrix),n?(o.multiplyWithOffset(n,-i.scrollX*t.scrollFactorX,-i.scrollY*t.scrollFactorY),a.e=t.x,a.f=t.y,o.multiply(a,h)):(a.e-=i.scrollX*t.scrollFactorX,a.f-=i.scrollY*t.scrollFactorY,o.multiply(a,h)),r.save(),h.setToContext(r),r.globalCompositeOperation=this.blendModes[t.blendMode],r.globalAlpha=s,r.imageSmoothingEnabled=!(!this.antialias||e.source.scaleMode),r.drawImage(e.source.image,u,c,d,f,y,x,d/g,f/g),r.restore()}},destroy:function(){this.gameCanvas=null,this.gameContext=null,this.game=null}});t.exports=u},function(t,e,i){var n=i(27),s=i(32),r=i(2);t.exports=function(t,e){var i=r(e,"callback"),o=r(e,"type","image/png"),a=r(e,"encoder",.92),h=Math.abs(Math.round(r(e,"x",0))),l=Math.abs(Math.round(r(e,"y",0))),u=r(e,"width",t.width),c=r(e,"height",t.height);if(r(e,"getPixel",!1)){var d=t.getContext("2d").getImageData(h,l,1,1).data;i.call(null,new s(d[0],d[1],d[2],d[3]/255))}else if(0!==h||0!==l||u!==t.width||c!==t.height){var f=n.createWebGL(this,u,c);f.getContext("2d").drawImage(t,h,l,u,c,0,0,u,c);var p=new Image;p.onerror=function(){i.call(null),n.remove(f)},p.onload=function(){i.call(null,p),n.remove(f)},p.src=f.toDataURL(o,a)}else{var g=new Image;g.onerror=function(){i.call(null)},g.onload=function(){i.call(null,g)},g.src=t.toDataURL(o,a)}}},function(t,e,i){var n=i(52),s=i(311);t.exports=function(){var t=[],e=s.supportNewBlendModes,i="source-over";return t[n.NORMAL]=i,t[n.ADD]="lighter",t[n.MULTIPLY]=e?"multiply":i,t[n.SCREEN]=e?"screen":i,t[n.OVERLAY]=e?"overlay":i,t[n.DARKEN]=e?"darken":i,t[n.LIGHTEN]=e?"lighten":i,t[n.COLOR_DODGE]=e?"color-dodge":i,t[n.COLOR_BURN]=e?"color-burn":i,t[n.HARD_LIGHT]=e?"hard-light":i,t[n.SOFT_LIGHT]=e?"soft-light":i,t[n.DIFFERENCE]=e?"difference":i,t[n.EXCLUSION]=e?"exclusion":i,t[n.HUE]=e?"hue":i,t[n.SATURATION]=e?"saturation":i,t[n.COLOR]=e?"color":i,t[n.LUMINOSITY]=e?"luminosity":i,t[n.ERASE]="destination-out",t[n.SOURCE_IN]="source-in",t[n.SOURCE_OUT]="source-out",t[n.SOURCE_ATOP]="source-atop",t[n.DESTINATION_OVER]="destination-over",t[n.DESTINATION_IN]="destination-in",t[n.DESTINATION_OUT]="destination-out",t[n.DESTINATION_ATOP]="destination-atop",t[n.LIGHTER]="lighter",t[n.COPY]="copy",t[n.XOR]="xor",t}},function(t,e,i){var n=i(89),s=i(48),r=i(0),o=i(10),a=i(19),h=i(114),l=i(1),u=i(90),c=i(78),d=i(115),f=i(30),p=i(9),g=i(504),v=i(505),m=i(506),y=i(232),x=i(507),T=new r({initialize:function(t){var e=t.config,i={alpha:e.transparent,desynchronized:e.desynchronized,depth:!1,antialias:e.antialiasGL,premultipliedAlpha:e.premultipliedAlpha,stencil:!0,failIfMajorPerformanceCaveat:e.failIfMajorPerformanceCaveat,powerPreference:e.powerPreference};this.config={clearBeforeRender:e.clearBeforeRender,antialias:e.antialias,backgroundColor:e.backgroundColor,contextCreation:i,resolution:e.resolution,roundPixels:e.roundPixels,maxTextures:e.maxTextures,maxTextureSize:e.maxTextureSize,batchSize:e.batchSize,maxLights:e.maxLights,mipmapFilter:e.mipmapFilter},this.game=t,this.type=o.WEBGL,this.width=0,this.height=0,this.canvas=t.canvas,this.blendModes=[],this.nativeTextures=[],this.contextLost=!1,this.pipelines=null,this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92,isFramebuffer:!1,bufferWidth:0,bufferHeight:0},this.currentActiveTextureUnit=0,this.currentTextures=new Array(16),this.currentFramebuffer=null,this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.currentBlendMode=1/0,this.currentScissorEnabled=!1,this.currentScissor=null,this.scissorStack=[],this.contextLostHandler=l,this.contextRestoredHandler=l,this.gl=null,this.supportedExtensions=null,this.extensions={},this.glFormats=[],this.compression={ETC1:!1,PVRTC:!1,S3TC:!1},this.drawingBufferHeight=0,this.blankTexture=null,this.defaultCamera=new n(0,0,0,0),this._tempMatrix1=new f,this._tempMatrix2=new f,this._tempMatrix3=new f,this._tempMatrix4=new f,this.maskCount=0,this.maskStack=[],this.currentMask={mask:null,camera:null},this.currentCameraMask={mask:null,camera:null},this.glFuncMap=null,this.currentType="",this.newType=!1,this.nextTypeMatch=!1,this.mipmapFilter=null,this.init(this.config)},init:function(t){var e,i=this.game,n=this.canvas,s=t.backgroundColor;if(!(e=i.config.context?i.config.context:n.getContext("webgl",t.contextCreation)||n.getContext("experimental-webgl",t.contextCreation))||e.isContextLost())throw this.contextLost=!0,new Error("WebGL unsupported");this.gl=e;var r=this;this.contextLostHandler=function(t){r.contextLost=!0,r.game.events.emit(a.CONTEXT_LOST,r),t.preventDefault()},this.contextRestoredHandler=function(){r.contextLost=!1,r.init(r.config),r.game.events.emit(a.CONTEXT_RESTORED,r)},n.addEventListener("webglcontextlost",this.contextLostHandler,!1),n.addEventListener("webglcontextrestored",this.contextRestoredHandler,!1),i.context=e;for(var h=0;h<=27;h++)this.blendModes.push({func:[e.ONE,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_ADD});this.blendModes[1].func=[e.ONE,e.DST_ALPHA],this.blendModes[2].func=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA],this.blendModes[3].func=[e.ONE,e.ONE_MINUS_SRC_COLOR],this.blendModes[17]={func:[e.ZERO,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_REVERSE_SUBTRACT},this.glFormats[0]=e.BYTE,this.glFormats[1]=e.SHORT,this.glFormats[2]=e.UNSIGNED_BYTE,this.glFormats[3]=e.UNSIGNED_SHORT,this.glFormats[4]=e.FLOAT,this.glFuncMap={mat2:{func:e.uniformMatrix2fv,length:1,matrix:!0},mat3:{func:e.uniformMatrix3fv,length:1,matrix:!0},mat4:{func:e.uniformMatrix4fv,length:1,matrix:!0},"1f":{func:e.uniform1f,length:1},"1fv":{func:e.uniform1fv,length:1},"1i":{func:e.uniform1i,length:1},"1iv":{func:e.uniform1iv,length:1},"2f":{func:e.uniform2f,length:2},"2fv":{func:e.uniform2fv,length:1},"2i":{func:e.uniform2i,length:2},"2iv":{func:e.uniform2iv,length:1},"3f":{func:e.uniform3f,length:3},"3fv":{func:e.uniform3fv,length:1},"3i":{func:e.uniform3i,length:3},"3iv":{func:e.uniform3iv,length:1},"4f":{func:e.uniform4f,length:4},"4fv":{func:e.uniform4fv,length:1},"4i":{func:e.uniform4i,length:4},"4iv":{func:e.uniform4iv,length:1}};var l=e.getSupportedExtensions();t.maxTextures||(t.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)),t.maxTextureSize||(t.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE));var u="WEBGL_compressed_texture_",c="WEBKIT_"+u;this.compression.ETC1=e.getExtension(u+"etc1")||e.getExtension(c+"etc1"),this.compression.PVRTC=e.getExtension(u+"pvrtc")||e.getExtension(c+"pvrtc"),this.compression.S3TC=e.getExtension(u+"s3tc")||e.getExtension(c+"s3tc"),this.supportedExtensions=l,e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.clearColor(s.redGL,s.greenGL,s.blueGL,s.alphaGL),this.mipmapFilter=e[t.mipmapFilter];for(var f=0;f0&&n>0;if(o&&a){var h=o[0],l=o[1],u=o[2],c=o[3];a=h!==t||l!==e||u!==i||c!==n}a&&(this.flush(),r.scissor(t,s-e-n,i,n))},popScissor:function(){var t=this.scissorStack;t.pop();var e=t[t.length-1];e&&this.setScissor(e[0],e[1],e[2],e[3]),this.currentScissor=e},setPipeline:function(t,e){return this.currentPipeline===t&&this.currentPipeline.vertexBuffer===this.currentVertexBuffer&&this.currentPipeline.program===this.currentProgram||(this.flush(),this.currentPipeline=t,this.currentPipeline.bind()),this.currentPipeline.onBind(e),this.currentPipeline},hasActiveStencilMask:function(){var t=this.currentMask.mask,e=this.currentCameraMask.mask;return t&&t.isStencil||e&&e.isStencil},rebindPipeline:function(t){var e=this.gl;e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),this.hasActiveStencilMask()?e.clear(e.DEPTH_BUFFER_BIT):(e.disable(e.STENCIL_TEST),e.clear(e.DEPTH_BUFFER_BIT|e.STENCIL_BUFFER_BIT)),e.viewport(0,0,this.width,this.height),this.setBlendMode(0,!0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.blankTexture.glTexture),this.currentActiveTextureUnit=0,this.currentTextures[0]=this.blankTexture.glTexture,this.currentPipeline=t,this.currentPipeline.bind(),this.currentPipeline.onBind()},clearPipeline:function(){this.flush(),this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.setBlendMode(0,!0)},setBlendMode:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.blendModes[t];return!!(e||t!==o.BlendModes.SKIP_CHECK&&this.currentBlendMode!==t)&&(this.flush(),i.enable(i.BLEND),i.blendEquation(n.equation),n.func.length>2?i.blendFuncSeparate(n.func[0],n.func[1],n.func[2],n.func[3]):i.blendFunc(n.func[0],n.func[1]),this.currentBlendMode=t,!0)},addBlendMode:function(t,e){return this.blendModes.push({func:t,equation:e})-1},updateBlendMode:function(t,e,i){return this.blendModes[t]&&(this.blendModes[t].func=e,i&&(this.blendModes[t].equation=i)),this},removeBlendMode:function(t){return t>17&&this.blendModes[t]&&this.blendModes.splice(t,1),this},setBlankTexture:function(t){void 0===t&&(t=!1),!t&&0===this.currentActiveTextureUnit&&this.currentTextures[0]||this.setTexture2D(this.blankTexture.glTexture,0)},setTexture2D:function(t,e,i){void 0===i&&(i=!0);var n=this.gl;return t!==this.currentTextures[e]&&(i&&this.flush(),this.currentActiveTextureUnit!==e&&(n.activeTexture(n.TEXTURE0+e),this.currentActiveTextureUnit=e),n.bindTexture(n.TEXTURE_2D,t),this.currentTextures[e]=t),this},setFramebuffer:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.width,s=this.height;return t!==this.currentFramebuffer&&(t&&t.renderTexture?(n=t.renderTexture.width,s=t.renderTexture.height):this.flush(),i.bindFramebuffer(i.FRAMEBUFFER,t),i.viewport(0,0,n,s),e&&(t?(this.drawingBufferHeight=s,this.pushScissor(0,0,n,s)):(this.drawingBufferHeight=this.height,this.popScissor())),this.currentFramebuffer=t),this},setProgram:function(t){var e=this.gl;return t!==this.currentProgram&&(this.flush(),e.useProgram(t),this.currentProgram=t),this},setVertexBuffer:function(t){var e=this.gl;return t!==this.currentVertexBuffer&&(this.flush(),e.bindBuffer(e.ARRAY_BUFFER,t),this.currentVertexBuffer=t),this},setIndexBuffer:function(t){var e=this.gl;return t!==this.currentIndexBuffer&&(this.flush(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.currentIndexBuffer=t),this},createTextureFromSource:function(t,e,i,n){var s=this.gl,r=s.NEAREST,a=s.NEAREST,l=s.CLAMP_TO_EDGE;e=t?t.width:e,i=t?t.height:i;var u=h(e,i);return u&&(l=s.REPEAT),n===o.ScaleModes.LINEAR&&this.config.antialias&&(r=u?this.mipmapFilter:s.LINEAR,a=s.LINEAR),t||"number"!=typeof e||"number"!=typeof i?this.createTexture2D(0,r,a,l,l,s.RGBA,t):this.createTexture2D(0,r,a,l,l,s.RGBA,null,e,i)},createTexture2D:function(t,e,i,n,s,r,o,a,l,u,c,d){u=void 0===u||null===u||u,void 0===c&&(c=!1),void 0===d&&(d=!1);var f=this.gl,p=f.createTexture();return this.setTexture2D(p,0),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,e),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,i),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,s),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,n),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u),f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,d),null===o||void 0===o?f.texImage2D(f.TEXTURE_2D,t,r,a,l,0,r,f.UNSIGNED_BYTE,null):(c||(a=o.width,l=o.height),f.texImage2D(f.TEXTURE_2D,t,r,r,f.UNSIGNED_BYTE,o)),h(a,l)&&f.generateMipmap(f.TEXTURE_2D),this.setTexture2D(null,0),p.isAlphaPremultiplied=u,p.isRenderTexture=!1,p.width=a,p.height=l,this.nativeTextures.push(p),p},createFramebuffer:function(t,e,i,n){var s,r=this.gl,o=r.createFramebuffer();if(this.setFramebuffer(o),n){var a=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,a),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,a)}if(i.isRenderTexture=!0,i.isAlphaPremultiplied=!1,r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),(s=r.checkFramebufferStatus(r.FRAMEBUFFER))!==r.FRAMEBUFFER_COMPLETE){throw new Error("Framebuffer incomplete. Framebuffer status: "+{36054:"Incomplete Attachment",36055:"Missing Attachment",36057:"Incomplete Dimensions",36061:"Framebuffer Unsupported"}[s])}return o.renderTexture=i,this.setFramebuffer(null),o},createProgram:function(t,e){var i=this.gl,n=i.createProgram(),s=i.createShader(i.VERTEX_SHADER),r=i.createShader(i.FRAGMENT_SHADER);if(i.shaderSource(s,t),i.shaderSource(r,e),i.compileShader(s),i.compileShader(r),!i.getShaderParameter(s,i.COMPILE_STATUS))throw new Error("Failed to compile Vertex Shader:\n"+i.getShaderInfoLog(s));if(!i.getShaderParameter(r,i.COMPILE_STATUS))throw new Error("Failed to compile Fragment Shader:\n"+i.getShaderInfoLog(r));if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw new Error("Failed to link program:\n"+i.getProgramInfoLog(n));return n},createVertexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setVertexBuffer(n),i.bufferData(i.ARRAY_BUFFER,t,e),this.setVertexBuffer(null),n},createIndexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setIndexBuffer(n),i.bufferData(i.ELEMENT_ARRAY_BUFFER,t,e),this.setIndexBuffer(null),n},deleteTexture:function(t){var e=this.nativeTextures.indexOf(t);return-1!==e&&c(this.nativeTextures,e),this.gl.deleteTexture(t),this.currentTextures[0]!==t||this.game.pendingDestroy||this.setBlankTexture(!0),this},deleteFramebuffer:function(t){return this.gl.deleteFramebuffer(t),this},deleteProgram:function(t){return this.gl.deleteProgram(t),this},deleteBuffer:function(t){return this.gl.deleteBuffer(t),this},preRenderCamera:function(t){var e=t._cx,i=t._cy,n=t._cw,r=t._ch,o=this.pipelines.TextureTintPipeline,a=t.backgroundColor;if(t.renderToTexture){this.flush(),this.pushScissor(e,i,n,-r),this.setFramebuffer(t.framebuffer);var h=this.gl;h.clearColor(0,0,0,0),h.clear(h.COLOR_BUFFER_BIT),o.projOrtho(e,n+e,i,r+i,-1e3,1e3),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n+e,r+i,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL),t.emit(s.PRE_RENDER,t)}else this.pushScissor(e,i,n,r),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n,r,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL)},getCurrentStencilMask:function(){var t=null,e=this.maskStack,i=this.currentCameraMask;return e.length>0?t=e[e.length-1]:i.mask&&i.mask.isStencil&&(t=i),t},postRenderCamera:function(t){var e=this.pipelines.TextureTintPipeline;if(t.flashEffect.postRenderWebGL(e,p.getTintFromFloats),t.fadeEffect.postRenderWebGL(e,p.getTintFromFloats),t.dirty=!1,this.popScissor(),t.renderToTexture){if(e.flush(),this.setFramebuffer(null),t.emit(s.POST_RENDER,t),t.renderToGame){e.projOrtho(0,e.width,e.height,0,-1e3,1e3);var i=p.getTintAppendFloatAlpha;(t.pipeline?t.pipeline:e).batchTexture(t,t.glTexture,t.width,t.height,t.x,t.y,t.width,t.height,t.zoom,t.zoom,t.rotation,t.flipX,!t.flipY,1,1,0,0,0,0,t.width,t.height,i(t._tintTL,t._alphaTL),i(t._tintTR,t._alphaTR),i(t._tintBL,t._alphaBL),i(t._tintBR,t._alphaBR),t._isTinted&&t.tintFill,0,0,this.defaultCamera,null)}this.setBlankTexture(!0)}t.mask&&(this.currentCameraMask.mask=null,t.mask.postRenderWebGL(this,t._maskCamera))},preRender:function(){if(!this.contextLost){var t=this.gl,e=this.pipelines;if(t.bindFramebuffer(t.FRAMEBUFFER,null),this.config.clearBeforeRender){var i=this.config.backgroundColor;t.clearColor(i.redGL,i.greenGL,i.blueGL,i.alphaGL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT)}for(var n in t.enable(t.SCISSOR_TEST),e)e[n].onPreRender();this.currentScissor=[0,0,this.width,this.height],this.scissorStack=[this.currentScissor],this.game.scene.customViewports&&t.scissor(0,this.drawingBufferHeight-this.height,this.width,this.height),this.currentMask.mask=null,this.currentCameraMask.mask=null,this.maskStack.length=0,this.setPipeline(this.pipelines.TextureTintPipeline)}},render:function(t,e,i,n){if(!this.contextLost){var s=e.list,r=s.length,a=this.pipelines;for(var h in a)a[h].onRender(t,n);if(this.preRenderCamera(n),0===r)return this.setBlendMode(o.BlendModes.NORMAL),void this.postRenderCamera(n);this.currentType="";for(var l=this.currentMask,u=0;u0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},createVideoTexture:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=this.gl,s=n.NEAREST,r=n.NEAREST,o=t.videoWidth,a=t.videoHeight,l=n.CLAMP_TO_EDGE,u=h(o,a);return!e&&u&&(l=n.REPEAT),this.config.antialias&&(s=u?this.mipmapFilter:n.LINEAR,r=n.LINEAR),this.createTexture2D(0,s,r,l,l,n.RGBA,t,o,a,!0,!0,i)},updateVideoTexture:function(t,e,i){void 0===i&&(i=!1);var n=this.gl,s=t.videoWidth,r=t.videoHeight;return s>0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},setTextureFilter:function(t,e){var i=this.gl,n=[i.LINEAR,i.NEAREST][e];return this.setTexture2D(t,0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,n),this.setTexture2D(null,0),this},setFloat1:function(t,e,i){return this.setProgram(t),this.gl.uniform1f(this.gl.getUniformLocation(t,e),i),this},setFloat2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2f(this.gl.getUniformLocation(t,e),i,n),this},setFloat3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3f(this.gl.getUniformLocation(t,e),i,n,s),this},setFloat4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4f(this.gl.getUniformLocation(t,e),i,n,s,r),this},setFloat1v:function(t,e,i){return this.setProgram(t),this.gl.uniform1fv(this.gl.getUniformLocation(t,e),i),this},setFloat2v:function(t,e,i){return this.setProgram(t),this.gl.uniform2fv(this.gl.getUniformLocation(t,e),i),this},setFloat3v:function(t,e,i){return this.setProgram(t),this.gl.uniform3fv(this.gl.getUniformLocation(t,e),i),this},setFloat4v:function(t,e,i){return this.setProgram(t),this.gl.uniform4fv(this.gl.getUniformLocation(t,e),i),this},setInt1:function(t,e,i){return this.setProgram(t),this.gl.uniform1i(this.gl.getUniformLocation(t,e),i),this},setInt2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2i(this.gl.getUniformLocation(t,e),i,n),this},setInt3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3i(this.gl.getUniformLocation(t,e),i,n,s),this},setInt4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4i(this.gl.getUniformLocation(t,e),i,n,s,r),this},setMatrix2:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix2fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix3:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix3fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix4:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix4fv(this.gl.getUniformLocation(t,e),i,n),this},getMaxTextures:function(){return this.config.maxTextures},getMaxTextureSize:function(){return this.config.maxTextureSize},destroy:function(){for(var t=0;t0&&this.flush();var e=this.inverseRotationMatrix;if(t){var i=-t,n=Math.cos(i),s=Math.sin(i);e[1]=s,e[3]=-s,e[0]=e[4]=n}else e[0]=e[4]=1,e[1]=e[3]=0;this.renderer.setMatrix3(this.program,"uInverseRotationMatrix",!1,e),this.currentNormalMapRotation=t}},batchSprite:function(t,e,i){if(this.active){var n=t.texture.dataSource[t.frame.sourceIndex];n&&(this.renderer.setPipeline(this),this.setTexture2D(n.glTexture,1),this.setNormalMapRotation(t.rotation),r.prototype.batchSprite.call(this,t,e,i))}}});a.LIGHT_COUNT=o,t.exports=a},function(t,e,i){var n=i(0),s=i(2),r=i(233),o=i(335),a=i(336),h=i(30),l=i(141),u=new n({Extends:l,Mixins:[r],initialize:function(t){var e=t.renderer.config;l.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:t.renderer.gl.TRIANGLE_STRIP,vertShader:s(t,"vertShader",a),fragShader:s(t,"fragShader",o),vertexCapacity:s(t,"vertexCapacity",6*e.batchSize),vertexSize:s(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new h,this._tempMatrix2=new h,this._tempMatrix3=new h,this.mvpInit()},onBind:function(){return l.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return l.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this}});t.exports=u},function(t,e,i){var n={};t.exports=n;var s=i(97),r=i(37);n.fromVertices=function(t){for(var e={},i=0;i1?1:0;d1?1:0;p0:0!=(t.mask&e.category)&&0!=(e.mask&t.category)}},function(t,e,i){var n={};t.exports=n;var s=i(84),r=i(97);n.collides=function(t,e,i){var o,a,h,l,u=!1;if(i){var c=t.parent,d=e.parent,f=c.speed*c.speed+c.angularSpeed*c.angularSpeed+d.speed*d.speed+d.angularSpeed*d.angularSpeed;u=i&&i.collided&&f<.2,l=i}else l={collided:!1,bodyA:t,bodyB:e};if(i&&u){var p=l.axisBody,g=p===t?e:t,v=[p.axes[i.axisNumber]];if(h=n._overlapAxes(p.vertices,g.vertices,v),l.reused=!0,h.overlap<=0)return l.collided=!1,l}else{if((o=n._overlapAxes(t.vertices,e.vertices,t.axes)).overlap<=0)return l.collided=!1,l;if((a=n._overlapAxes(e.vertices,t.vertices,e.axes)).overlap<=0)return l.collided=!1,l;o.overlaps?s=a:a=0?o.index-1:u.length-1],l.x=s.x-c.x,l.y=s.y-c.y,h=-r.dot(i,l),a=s,s=u[(o.index+1)%u.length],l.x=s.x-c.x,l.y=s.y-c.y,(n=-r.dot(i,l))>>0;if("function"!=typeof t)throw new TypeError;for(var n=arguments.length>=2?arguments[1]:void 0,s=0;s>16)+(65280&t)+((255&t)<<16)},n={_tintTL:16777215,_tintTR:16777215,_tintBL:16777215,_tintBR:16777215,_isTinted:!1,tintFill:!1,clearTint:function(){return this.setTint(16777215),this._isTinted=!1,this},setTint:function(t,e,n,s){return void 0===t&&(t=16777215),void 0===e&&(e=t,n=t,s=t),this._tintTL=i(t),this._tintTR=i(e),this._tintBL=i(n),this._tintBR=i(s),this._isTinted=!0,this.tintFill=!1,this},setTintFill:function(t,e,i,n){return this.setTint(t,e,i,n),this.tintFill=!0,this},tintTopLeft:{get:function(){return this._tintTL},set:function(t){this._tintTL=i(t),this._isTinted=!0}},tintTopRight:{get:function(){return this._tintTR},set:function(t){this._tintTR=i(t),this._isTinted=!0}},tintBottomLeft:{get:function(){return this._tintBL},set:function(t){this._tintBL=i(t),this._isTinted=!0}},tintBottomRight:{get:function(){return this._tintBR},set:function(t){this._tintBR=i(t),this._isTinted=!0}},tint:{set:function(t){this.setTint(t,t,t,t)}},isTinted:{get:function(){return this._isTinted}}};t.exports=n},function(t,e){t.exports="changedata"},function(t,e){t.exports="changedata-"},function(t,e){t.exports="removedata"},function(t,e){t.exports="setdata"},function(t,e){t.exports="destroy"},function(t,e){t.exports="complete"},function(t,e){t.exports="created"},function(t,e){t.exports="error"},function(t,e){t.exports="loop"},function(t,e){t.exports="play"},function(t,e){t.exports="seeked"},function(t,e){t.exports="seeking"},function(t,e){t.exports="stop"},function(t,e){t.exports="timeout"},function(t,e){t.exports="unlocked"},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"alpha",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"x",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r,o,a){return void 0!==i&&null!==i||(i=e),n(t,"x",e,s,o,a),n(t,"y",i,r,o,a)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"y",e,i,s,r)}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=6.28);for(var s=i,r=(n-i)/t.length,o=0;o0?s(o,i):i<0&&r(o,Math.abs(i));for(var a=0;a1)if(0===s){var d=t.length-1;for(o=t[d].x,a=t[d].y,h=d-1;h>=0;h--)l=(c=t[h]).x,u=c.y,c.x=o,c.y=a,o=l,a=u;t[d].x=e,t[d].y=i}else{for(o=t[0].x,a=t[0].y,h=1;h0?(this._speedX-=this.dragX*t,this._speedX<0&&(this._speedX=0)):this._speedX<0&&(this._speedX+=this.dragX*t,this._speedX>0&&(this._speedX=0)),this._speedY>0?(this._speedY-=this.dragY*t,this._speedY<0&&(this._speedY=0)):this._speedY<0&&(this._speedY+=this.dragY*t,this._speedY>0&&(this._speedY=0)),this.up&&this.up.isDown?(this._speedY+=this.accelY,this._speedY>this.maxSpeedY&&(this._speedY=this.maxSpeedY)):this.down&&this.down.isDown&&(this._speedY-=this.accelY,this._speedY<-this.maxSpeedY&&(this._speedY=-this.maxSpeedY)),this.left&&this.left.isDown?(this._speedX+=this.accelX,this._speedX>this.maxSpeedX&&(this._speedX=this.maxSpeedX)):this.right&&this.right.isDown&&(this._speedX-=this.accelX,this._speedX<-this.maxSpeedX&&(this._speedX=-this.maxSpeedX)),this.zoomIn&&this.zoomIn.isDown?this._zoom=-this.zoomSpeed:this.zoomOut&&this.zoomOut.isDown?this._zoom=this.zoomSpeed:this._zoom=0,0!==this._speedX&&(e.scrollX-=this._speedX*t|0),0!==this._speedY&&(e.scrollY-=this._speedY*t|0),0!==this._zoom&&(e.zoom+=this._zoom,e.zoom<.001&&(e.zoom=.001))}},destroy:function(){this.camera=null,this.left=null,this.right=null,this.up=null,this.down=null,this.zoomIn=null,this.zoomOut=null}});t.exports=r},function(t,e,i){t.exports={Camera:i(288),BaseCamera:i(89),CameraManager:i(694),Effects:i(296),Events:i(48)}},function(t,e){t.exports="cameradestroy"},function(t,e){t.exports="camerafadeincomplete"},function(t,e){t.exports="camerafadeinstart"},function(t,e){t.exports="camerafadeoutcomplete"},function(t,e){t.exports="camerafadeoutstart"},function(t,e){t.exports="cameraflashcomplete"},function(t,e){t.exports="cameraflashstart"},function(t,e){t.exports="camerapancomplete"},function(t,e){t.exports="camerapanstart"},function(t,e){t.exports="postrender"},function(t,e){t.exports="prerender"},function(t,e){t.exports="camerashakecomplete"},function(t,e){t.exports="camerashakestart"},function(t,e){t.exports="camerazoomcomplete"},function(t,e){t.exports="camerazoomstart"},function(t,e,i){var n=i(23),s=i(0),r=i(48),o=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.isComplete=!1,this.direction=!0,this.duration=0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this.progress=0,this._elapsed=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s,o,a,h){if(void 0===t&&(t=!0),void 0===e&&(e=1e3),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=0),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===h&&(h=this.camera.scene),!o&&this.isRunning)return this.camera;this.isRunning=!0,this.isComplete=!1,this.duration=e,this.direction=t,this.progress=0,this.red=i,this.green=n,this.blue=s,this.alpha=t?Number.MIN_VALUE:1,this._elapsed=0,this._onUpdate=a,this._onUpdateScope=h;var l=t?r.FADE_OUT_START:r.FADE_IN_START;return this.camera.emit(l,this.camera,this,e,i,n,s),this.camera},update:function(t,e){this.isRunning&&(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed=1?1:1/e*(1+(e*t|0))}},function(t,e,i){var n=i(23),s=i(0),r=i(48),o=i(3),a=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.duration=0,this.intensity=new o,this.progress=0,this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s){return void 0===t&&(t=100),void 0===e&&(e=.05),void 0===i&&(i=!1),void 0===n&&(n=null),void 0===s&&(s=this.camera.scene),!i&&this.isRunning?this.camera:(this.isRunning=!0,this.duration=t,this.progress=0,"number"==typeof e?this.intensity.set(e):this.intensity.set(e.x,e.y),this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate=n,this._onUpdateScope=s,this.camera.emit(r.SHAKE_START,this.camera,this,t,e),this.camera)},preRender:function(){this.isRunning&&this.camera.matrix.translate(this._offsetX,this._offsetY)},update:function(t,e){if(this.isRunning)if(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed0&&(o.preRender(1),t.render(n,e,i,o))}},resetAll:function(){for(var t=0;t1)for(var i=1;i=1)&&(s.touch=!0),(navigator.msPointerEnabled||navigator.pointerEnabled)&&(s.mspointer=!0),navigator.getGamepads&&(s.gamepads=!0),"onwheel"in window||n.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":n.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"),s)},function(t,e,i){var n=i(113),s={audioData:!1,dolby:!1,m4a:!1,mp3:!1,ogg:!1,opus:!1,wav:!1,webAudio:!1,webm:!1};t.exports=function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio"),e=!!t.canPlayType;try{if(e&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(n.edge)s.dolby=!0;else if(n.safari&&n.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var i=parseInt(RegExp.$1,10),r=parseInt(RegExp.$2,10);(10===i&&r>=11||i>10)&&(s.dolby=!0)}}catch(t){}return s}()},function(t,e){var i={h264:!1,hls:!1,mp4:!1,ogg:!1,vp9:!1,webm:!1};t.exports=function(){var t=document.createElement("video"),e=!!t.canPlayType;try{e&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(i.ogg=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.h264=!0,i.mp4=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(i.webm=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(i.vp9=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.hls=!0))}catch(t){}return i}()},function(t,e){var i={available:!1,cancel:"",keyboard:!1,request:""};t.exports=function(){var t,e="Fullscreen",n="FullScreen",s=["request"+e,"request"+n,"webkitRequest"+e,"webkitRequest"+n,"msRequest"+e,"msRequest"+n,"mozRequest"+n,"mozRequest"+e];for(t=0;tMath.PI&&(t-=n.PI2),Math.abs(((t+n.TAU)%n.PI2-n.PI2)%n.PI2)}},function(t,e,i){var n=i(313);t.exports=function(t){return n(t+Math.PI)}},function(t,e,i){var n=i(16);t.exports=function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=i:e1?t[i]-(n(s-i,t[i],t[i],t[i-1],t[i-1])-t[i]):n(s-r,t[r?r-1:0],t[r],t[i1?n(t[i],t[i-1],i-s):n(t[r],t[r+1>i?i:r+1],s-r)}},function(t,e,i){var n=i(154);t.exports=function(t,e,i){return e+(i-e)*n(t,0,1)}},function(t,e,i){t.exports={GetNext:i(323),IsSize:i(114),IsValue:i(749)}},function(t,e){t.exports=function(t){return t>0&&0==(t&t-1)}},function(t,e,i){t.exports={Ceil:i(324),Floor:i(91),To:i(751)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){void 0===t&&(t=[(Date.now()*Math.random()).toString()]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.n=0,this.signs=[-1,1],t&&this.init(t)},rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},hash:function(t){var e,i=this.n;t=t.toString();for(var n=0;n>>0,i=(e*=i)>>>0,i+=4294967296*(e-=i);return this.n=i,2.3283064365386963e-10*(i>>>0)},init:function(t){"string"==typeof t?this.state(t):this.sow(t)},sow:function(t){if(this.n=4022871197,this.s0=this.hash(" "),this.s1=this.hash(" "),this.s2=this.hash(" "),this.c=1,t)for(var e=0;e0;e--){var i=Math.floor(this.frac()*(e+1)),n=t[i];t[i]=t[e],t[e]=n}return t}});t.exports=n},function(t,e){t.exports=function(t){for(var e=0,i=0;i1?void 0!==n?(s=(n-t)/(n-i))<0&&(s=0):s=1:s<0&&(s=0),s}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI;return t.x=Math.cos(i)*e,t.y=Math.sin(i)*e,t}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI,n=2*Math.random()-1,s=Math.sqrt(1-n*n)*e;return t.x=Math.cos(i)*s,t.y=Math.sin(i)*s,t.z=n*e,t}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=1),t.x=(2*Math.random()-1)*e,t.y=(2*Math.random()-1)*e,t.z=(2*Math.random()-1)*e,t.w=(2*Math.random()-1)*e,t}},function(t,e){t.exports=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var n=Math.pow(i,-e);return Math.round(t*n)/n}},function(t,e){t.exports=function(t,e,i,n){void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=1),n*=Math.PI/t;for(var s=[],r=[],o=0;o0&&t<=e*i&&(r=t>e-1?t-(o=Math.floor(t/e))*e:t,s.set(r,o)),s}},function(t,e){t.exports=function(t,e,i){return Math.abs(t-e)<=i}},function(t,e,i){var n=i(169),s=i(331),r=i(332),o=new s,a=new r,h=new n;t.exports=function(t,e,i){return a.setAxisAngle(e,i),o.fromRotationTranslation(a,h.set(0,0,0)),t.transformMat4(o)}},function(t,e){t.exports="addtexture"},function(t,e){t.exports="onerror"},function(t,e){t.exports="onload"},function(t,e){t.exports="ready"},function(t,e){t.exports="removetexture"},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_FS","","precision mediump float;","","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uMaskSampler;","uniform bool uInvertMaskAlpha;","","void main()","{"," vec2 uv = gl_FragCoord.xy / uResolution;"," vec4 mainColor = texture2D(uMainSampler, uv);"," vec4 maskColor = texture2D(uMaskSampler, uv);"," float alpha = mainColor.a;",""," if (!uInvertMaskAlpha)"," {"," alpha *= (maskColor.a);"," }"," else"," {"," alpha *= (1.0 - maskColor.a);"," }",""," gl_FragColor = vec4(mainColor.rgb * alpha, alpha);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_VS","","precision mediump float;","","attribute vec2 inPosition;","","void main()","{"," gl_Position = vec4(inPosition, 0.0, 1.0);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS","","precision mediump float;","","struct Light","{"," vec2 position;"," vec3 color;"," float intensity;"," float radius;","};","","const int kMaxLights = %LIGHT_COUNT%;","","uniform vec4 uCamera; /* x, y, rotation, zoom */","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uNormSampler;","uniform vec3 uAmbientLightColor;","uniform Light uLights[kMaxLights];","uniform mat3 uInverseRotationMatrix;","","varying vec2 outTexCoord;","varying vec4 outTint;","","void main()","{"," vec3 finalColor = vec3(0.0, 0.0, 0.0);"," vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);"," vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;"," vec3 normal = normalize(uInverseRotationMatrix * vec3(normalMap * 2.0 - 1.0));"," vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;",""," for (int index = 0; index < kMaxLights; ++index)"," {"," Light light = uLights[index];"," vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);"," vec3 lightNormal = normalize(lightDir);"," float distToSurf = length(lightDir) * uCamera.w;"," float diffuseFactor = max(dot(normal, lightNormal), 0.0);"," float radius = (light.radius / res.x * uCamera.w) * uCamera.w;"," float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);"," vec3 diffuse = light.color * diffuseFactor;"," finalColor += (attenuation * diffuse) * light.intensity;"," }",""," vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);"," gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);","","}",""].join("\n")},function(t,e,i){t.exports={GenerateTexture:i(341),Palettes:i(780)}},function(t,e,i){t.exports={ARNE16:i(342),C64:i(781),CGA:i(782),JMP:i(783),MSX:i(784)}},function(t,e){t.exports={0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"}},function(t,e){t.exports={0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}},function(t,e,i){t.exports={Path:i(786),CubicBezier:i(343),Curve:i(79),Ellipse:i(344),Line:i(345),QuadraticBezier:i(346),Spline:i(347)}},function(t,e,i){var n=i(0),s=i(343),r=i(344),o=i(5),a=i(345),h=i(787),l=i(346),u=i(13),c=i(347),d=i(3),f=i(16),p=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.name="",this.curves=[],this.cacheLengths=[],this.autoClose=!1,this.startPoint=new d,this._tmpVec2A=new d,this._tmpVec2B=new d,"object"==typeof t?this.fromJSON(t):this.startPoint.set(t,e)},add:function(t){return this.curves.push(t),this},circleTo:function(t,e,i){return void 0===e&&(e=!1),this.ellipseTo(t,t,0,360,e,i)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);return t.equals(e)||this.curves.push(new a(e,t)),this},cubicBezierTo:function(t,e,i,n,r,o){var a,h,l,u=this.getEndPoint();return t instanceof d?(a=t,h=e,l=i):(a=new d(i,n),h=new d(r,o),l=new d(t,e)),this.add(new s(u,a,h,l))},quadraticBezierTo:function(t,e,i,n){var s,r,o=this.getEndPoint();return t instanceof d?(s=t,r=e):(s=new d(i,n),r=new d(t,e)),this.add(new l(o,s,r))},draw:function(t,e){for(var i=0;i0?this.curves[this.curves.length-1].getPoint(1,t):t.copy(this.startPoint),t},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},getPoint:function(t,e){void 0===e&&(e=new d);for(var i=t*this.getLength(),n=this.getCurveLengths(),s=0;s=i){var r=n[s]-i,o=this.curves[s],a=o.getLength(),h=0===a?0:1-r/a;return o.getPointAt(h,e)}s++}return null},getPoints:function(t){void 0===t&&(t=12);for(var e,i=[],n=0;n1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},getRandomPoint:function(t){return void 0===t&&(t=new d),this.getPoint(Math.random(),t)},getSpacedPoints:function(t){void 0===t&&(t=40);for(var e=[],i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e},getStartPoint:function(t){return void 0===t&&(t=new d),t.copy(this.startPoint)},lineTo:function(t,e){t instanceof d?this._tmpVec2B.copy(t):this._tmpVec2B.set(t,e);var i=this.getEndPoint(this._tmpVec2A);return this.add(new a([i.x,i.y,this._tmpVec2B.x,this._tmpVec2B.y]))},splineTo:function(t){return t.unshift(this.getEndPoint()),this.add(new c(t))},moveTo:function(t,e){return t instanceof d?this.add(new h(t.x,t.y)):this.add(new h(t,e))},toJSON:function(){for(var t=[],e=0;e>16&255,g:t>>8&255,b:255&t,a:255};return t>16777215&&(e.a=t>>>24),e}},function(t,e,i){var n=i(32),s=i(351);t.exports=function(t,e,i){var r=i,o=i,a=i;if(0!==e){var h=i<.5?i*(1+e):i+e-i*e,l=2*i-h;r=s(l,h,t+1/3),o=s(l,h,t),a=s(l,h,t-1/3)}return(new n).setGLTo(r,o,a,1)}},function(t,e,i){var n=i(160);t.exports=function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n(s/359,t,e));return i}},function(t,e,i){var n=i(111),s=function(t,e,i,s,r,o,a,h){void 0===a&&(a=100),void 0===h&&(h=0);var l=h/a;return{r:n(t,s,l),g:n(e,r,l),b:n(i,o,l)}};t.exports={RGBWithRGB:s,ColorWithRGB:function(t,e,i,n,r,o){return void 0===r&&(r=100),void 0===o&&(o=0),s(t.r,t.g,t.b,e,i,n,r,o)},ColorWithColor:function(t,e,i,n){return void 0===i&&(i=100),void 0===n&&(n=0),s(t.r,t.g,t.b,e.r,e.g,e.b,i,n)}}},function(t,e,i){var n=i(167),s=i(32);t.exports=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=255),new s(n(t,e),n(t,e),n(t,e))}},function(t,e,i){var n=i(350);t.exports=function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n(s)+n(t)+n(e)+n(i)}},function(t,e,i){t.exports={BitmapMask:i(273),GeometryMask:i(274)}},function(t,e,i){var n={AddToDOM:i(116),DOMContentLoaded:i(352),GetScreenOrientation:i(353),GetTarget:i(358),ParseXML:i(359),RemoveFromDOM:i(173),RequestAnimationFrame:i(339)};t.exports=n},function(t,e,i){t.exports={EventEmitter:i(809)}},function(t,e,i){var n=i(0),s=i(11),r=i(24),o=new n({Extends:s,initialize:function(){s.call(this)},shutdown:function(){this.removeAllListeners()},destroy:function(){this.removeAllListeners()}});r.register("EventEmitter",o,"events"),t.exports=o},function(t,e,i){var n=i(116),s=i(284),r=i(287),o=i(27),a=i(0),h=i(309),l=i(811),u=i(333),c=i(109),d=i(337),f=i(310),p=i(352),g=i(11),v=i(19),m=i(360),y=i(24),x=i(365),T=i(366),w=i(368),b=i(115),E=i(371),S=i(338),A=i(340),_=i(375),C=new a({initialize:function(t){this.config=new h(t),this.renderer=null,this.domContainer=null,this.canvas=null,this.context=null,this.isBooted=!1,this.isRunning=!1,this.events=new g,this.anims=new s(this),this.textures=new E(this),this.cache=new r(this),this.registry=new c(this),this.input=new m(this,this.config),this.scene=new w(this,this.config.sceneConfig),this.device=f,this.scale=new T(this,this.config),this.sound=null,this.sound=_.create(this),this.loop=new S(this,this.config.fps),this.plugins=new x(this,this.config),this.pendingDestroy=!1,this.removeCanvas=!1,this.noReturn=!1,this.hasFocus=!1,p(this.boot.bind(this))},boot:function(){y.hasCore("EventEmitter")?(this.isBooted=!0,this.config.preBoot(this),this.scale.preBoot(),u(this),l(this),d(this),n(this.canvas,this.config.parent),this.textures.once(b.READY,this.texturesReady,this),this.events.emit(v.BOOT)):console.warn("Aborting. Core Plugins missing.")},texturesReady:function(){this.events.emit(v.READY),this.start()},start:function(){this.isRunning=!0,this.config.postBoot(this),this.renderer?this.loop.start(this.step.bind(this)):this.loop.start(this.headlessStep.bind(this)),A(this);var t=this.events;t.on(v.HIDDEN,this.onHidden,this),t.on(v.VISIBLE,this.onVisible,this),t.on(v.BLUR,this.onBlur,this),t.on(v.FOCUS,this.onFocus,this)},step:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e);var n=this.renderer;n.preRender(),i.emit(v.PRE_RENDER,n,t,e),this.scene.render(n),n.postRender(),i.emit(v.POST_RENDER,n,t,e)},headlessStep:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e),i.emit(v.PRE_RENDER),i.emit(v.POST_RENDER)},onHidden:function(){this.loop.pause(),this.events.emit(v.PAUSE)},onVisible:function(){this.loop.resume(),this.events.emit(v.RESUME)},onBlur:function(){this.hasFocus=!1,this.loop.blur()},onFocus:function(){this.hasFocus=!0,this.loop.focus()},getFrame:function(){return this.loop.frame},getTime:function(){return this.loop.now},destroy:function(t,e){void 0===e&&(e=!1),this.pendingDestroy=!0,this.removeCanvas=t,this.noReturn=e},runDestroy:function(){this.scene.destroy(),this.events.emit(v.DESTROY),this.events.removeAllListeners(),this.renderer&&this.renderer.destroy(),this.removeCanvas&&this.canvas&&(o.remove(this.canvas),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)),this.domContainer&&this.domContainer.parentNode.removeChild(this.domContainer),this.loop.destroy(),this.pendingDestroy=!1}});t.exports=C},function(t,e,i){var n=i(116);t.exports=function(t){var e=t.config;if(e.parent&&e.domCreateContainer){var i=document.createElement("div");i.style.cssText=["display: block;","width: "+t.scale.width+"px;","height: "+t.scale.height+"px;","padding: 0; margin: 0;","position: absolute;","overflow: hidden;","pointer-events: none;","transform: scale(1);","transform-origin: left top;"].join(" "),t.domContainer=i,n(i,e.parent)}}},function(t,e){t.exports="boot"},function(t,e){t.exports="destroy"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameout"},function(t,e){t.exports="gameover"},function(t,e){t.exports="gameobjectdown"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameobjectmove"},function(t,e){t.exports="gameobjectout"},function(t,e){t.exports="gameobjectover"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="wheel"},function(t,e){t.exports="gameobjectup"},function(t,e){t.exports="gameobjectwheel"},function(t,e){t.exports="boot"},function(t,e){t.exports="process"},function(t,e){t.exports="update"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointerdownoutside"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="pointerupoutside"},function(t,e){t.exports="wheel"},function(t,e){t.exports="pointerlockchange"},function(t,e){t.exports="preupdate"},function(t,e){t.exports="shutdown"},function(t,e){t.exports="start"},function(t,e){t.exports="update"},function(t,e){t.exports=function(t){if(!t)return window.innerHeight;var e=Math.abs(window.orientation),i={w:0,h:0},n=document.createElement("div");return n.setAttribute("style","position: fixed; height: 100vh; width: 0; top: 0"),document.documentElement.appendChild(n),i.w=90===e?n.offsetHeight:window.innerWidth,i.h=90===e?window.innerWidth:n.offsetHeight,document.documentElement.removeChild(n),n=null,90!==Math.abs(window.orientation)?i.h:i.w}},function(t,e){t.exports="addfile"},function(t,e){t.exports="complete"},function(t,e){t.exports="filecomplete"},function(t,e){t.exports="filecomplete-"},function(t,e){t.exports="loaderror"},function(t,e){t.exports="load"},function(t,e){t.exports="fileprogress"},function(t,e){t.exports="postprocess"},function(t,e){t.exports="progress"},function(t,e){t.exports="start"},function(t,e,i){var n=i(2),s=i(176);t.exports=function(t){var e=t.game.config.defaultPhysicsSystem,i=n(t.settings,"physics",!1);if(e||i){var r=[];if(e&&r.push(s(e+"Physics")),i)for(var o in i)o=s(o.concat("Physics")),-1===r.indexOf(o)&&r.push(o);return r}}},function(t,e,i){var n=i(2);t.exports=function(t){var e=t.plugins.getDefaultScenePlugins(),i=n(t.settings,"plugins",!1);return Array.isArray(i)?i:e||[]}},function(t,e,i){t.exports={game:"game",anims:"anims",cache:"cache",plugins:"plugins",registry:"registry",scale:"scale",sound:"sound",textures:"textures",events:"events",cameras:"cameras",add:"add",make:"make",scenePlugin:"scene",displayList:"children",lights:"lights",data:"data",input:"input",load:"load",time:"time",tweens:"tweens",arcadePhysics:"physics",impactPhysics:"impact",matterPhysics:"matter"}},function(t,e){t.exports=function(t,e,i){if(i.getElementsByTagName("TextureAtlas")){var n=t.source[e];t.add("__BASE",e,0,0,n.width,n.height);for(var s,r=i.getElementsByTagName("SubTexture"),o=0;og||c<-g)&&(c=0),c<0&&(c=g+c),-1!==d&&(g=c+(d+1));for(var v=f,m=f,y=0,x=0,T=0;Tr&&(y=w-r),b>o&&(x=b-o),t.add(T,e,i+v,s+m,h-y,l-x),(v+=h+p)+h>r&&(v=f,m+=l+p)}return t}},function(t,e,i){var n=i(2);t.exports=function(t,e,i){var s=n(i,"frameWidth",null),r=n(i,"frameHeight",s);if(!s)throw new Error("TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.");var o=t.source[0];t.add("__BASE",0,0,0,o.width,o.height);var a,h=n(i,"startFrame",0),l=n(i,"endFrame",-1),u=n(i,"margin",0),c=n(i,"spacing",0),d=e.cutX,f=e.cutY,p=e.cutWidth,g=e.cutHeight,v=e.realWidth,m=e.realHeight,y=Math.floor((v-u+c)/(s+c)),x=Math.floor((m-u+c)/(r+c)),T=y*x,w=e.x,b=s-w,E=s-(v-p-w),S=e.y,A=r-S,_=r-(m-g-S);(h>T||h<-T)&&(h=0),h<0&&(h=T+h),-1!==l&&(T=h+(l+1));for(var C=u,M=u,O=0,P=e.sourceIndex,R=0;R0){var r=i-t.length;if(r<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.push(e),n&&n.call(s,e),e):null;for(var o=e.length-1;o>=0;)-1!==t.indexOf(e[o])&&e.splice(o,1),o--;if(0===(o=e.length))return null;i>0&&o>r&&(e.splice(r),o=r);for(var a=0;a0){var o=n-t.length;if(o<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.splice(i,0,e),s&&s.call(r,e),e):null;for(var a=e.length-1;a>=0;)-1!==t.indexOf(e[a])&&e.pop(),a--;if(0===(a=e.length))return null;n>0&&a>o&&(e.splice(o),a=o);for(var h=a-1;h>=0;h--){var l=e[h];t.splice(i,0,l),s&&s.call(r,l)}return e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);return-1!==i&&i0){var n=t[i-1],s=t.indexOf(n);t[i]=n,t[s]=e}return t}},function(t,e){t.exports=function(t,e,i){var n=t.indexOf(e);if(-1===n||i<0||i>=t.length)throw new Error("Supplied index out of bounds");return n!==i&&(t.splice(n,1),t.splice(i,0,e)),e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);if(-1!==i&&it.length-1)throw new Error("Index out of bounds");var r=n(t,e);return i&&i.call(s,r),r}},function(t,e,i){var n=i(66);t.exports=function(t,e,i,s,r){if(void 0===e&&(e=0),void 0===i&&(i=t.length),void 0===r&&(r=t),n(t,e,i)){var o=i-e,a=t.splice(e,o);if(s)for(var h=0;h0&&(t.splice(i,1),t.unshift(e)),e}},function(t,e,i){var n=i(66);t.exports=function(t,e,i,s,r){if(void 0===s&&(s=0),void 0===r&&(r=t.length),n(t,s,r))for(var o=s;o0){for(n=0;nl||U-Y>l?(N.push(X.i-1),X.cr?(N.push(X.i+X.word.length),Y=0,B=null):B=X):X.cr&&(N.push(X.i+X.word.length),Y=0,B=null)}for(n=N.length-1;n>=0;n--)s=a,r=N[n],o="\n",a=s.substr(0,r)+o+s.substr(r+1);i.wrappedText=a,h=a.length,F=[],k=null}for(n=0;nb&&(c=b),d>E&&(d=E);var W=b+w.xAdvance,V=E+v;fR&&(R=D),DR&&(R=D),D0&&(a=(o=z.wrappedText).length);var U=e._bounds.lines;1===Y?X=(U.longest-U.lengths[0])/2:2===Y&&(X=U.longest-U.lengths[0]);for(var G=s.roundPixels,W=0;W0&&(a=(o=L.wrappedText).length);var D=e._bounds.lines;1===O?R=(D.longest-D.lengths[0])/2:2===O&&(R=D.longest-D.lengths[0]),h.translate(-e.displayOriginX,-e.displayOriginY);for(var F=s.roundPixels,k=0;k0!=t>0,this._alpha=t}}});t.exports=r},function(t,e,i){var n=i(1),s=i(1);n=i(946),s=i(947),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){var r=e.list;if(0!==r.length){var o=e.localTransform;s?(o.loadIdentity(),o.multiply(s),o.translate(e.x,e.y),o.rotate(e.rotation),o.scale(e.scaleX,e.scaleY)):o.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);var a=-1!==e.blendMode;a||t.setBlendMode(0);for(var h=e.alpha,l=e.scrollFactorX,u=e.scrollFactorY,c=r,d=r.length,f=0;f0||e.cropHeight>0;l&&(h.flush(),t.pushScissor(e.x,e.y,e.cropWidth*e.scaleX,e.cropHeight*e.scaleY));var u=h._tempMatrix1,c=h._tempMatrix2,d=h._tempMatrix3,f=h._tempMatrix4;c.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),u.copyFrom(s.matrix),r?(u.multiplyWithOffset(r,-s.scrollX*e.scrollFactorX,-s.scrollY*e.scrollFactorY),c.e=e.x,c.f=e.y,u.multiply(c,d)):(c.e-=s.scrollX*e.scrollFactorX,c.f-=s.scrollY*e.scrollFactorY,u.multiply(c,d));var p=e.frame,g=p.glTexture,v=p.cutX,m=p.cutY,y=g.width,x=g.height,T=e._isTinted&&e.tintFill,w=n.getTintAppendFloatAlpha(e._tintTL,s.alpha*e._alphaTL),b=n.getTintAppendFloatAlpha(e._tintTR,s.alpha*e._alphaTR),E=n.getTintAppendFloatAlpha(e._tintBL,s.alpha*e._alphaBL),S=n.getTintAppendFloatAlpha(e._tintBR,s.alpha*e._alphaBR);h.setTexture2D(g,0);var A,_,C=0,M=0,O=0,P=0,R=e.letterSpacing,L=0,D=0,F=0,k=0,I=e.scrollX,B=e.scrollY,Y=e.fontData,N=Y.chars,X=Y.lineHeight,z=e.fontSize/Y.size,U=0,G=e._align,W=0,V=0;e.getTextBounds(!1);var H=e._bounds.lines;1===G?V=(H.longest-H.lengths[0])/2:2===G&&(V=H.longest-H.lengths[0]);for(var j=s.roundPixels,q=e.displayCallback,K=e.callbackData,J=0;J0&&e.cropHeight>0&&(h.beginPath(),h.rect(0,0,e.cropWidth,e.cropHeight),h.clip());for(var Y=0;Y0&&(N=N%b-b):N>b?N=b:N<0&&(N=b+N%b),null===_&&(_=new o(k+Math.cos(Y)*B,I+Math.sin(Y)*B,v),E.push(_),F+=.01);F<1+z;)w=N*F+Y,x=k+Math.cos(w)*B,T=I+Math.sin(w)*B,_.points.push(new r(x,T,v)),F+=.01;w=N+Y,x=k+Math.cos(w)*B,T=I+Math.sin(w)*B,_.points.push(new r(x,T,v));break;case n.FILL_RECT:u.setTexture2D(M),u.batchFillRect(p[++O],p[++O],p[++O],p[++O],f,c);break;case n.FILL_TRIANGLE:u.setTexture2D(M),u.batchFillTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],f,c);break;case n.STROKE_TRIANGLE:u.setTexture2D(M),u.batchStrokeTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],v,f,c);break;case n.LINE_TO:null!==_?_.points.push(new r(p[++O],p[++O],v)):(_=new o(p[++O],p[++O],v),E.push(_));break;case n.MOVE_TO:_=new o(p[++O],p[++O],v),E.push(_);break;case n.SAVE:a.push(f.copyToArray());break;case n.RESTORE:f.copyFromArray(a.pop());break;case n.TRANSLATE:k=p[++O],I=p[++O],f.translate(k,I);break;case n.SCALE:k=p[++O],I=p[++O],f.scale(k,I);break;case n.ROTATE:f.rotate(p[++O]);break;case n.SET_TEXTURE:var U=p[++O],G=p[++O];u.currentFrame=U,u.setTexture2D(U.glTexture,0),u.tintEffect=G,M=U.glTexture;break;case n.CLEAR_TEXTURE:u.currentFrame=t.blankTexture,u.tintEffect=2,M=t.blankTexture.glTexture}}}},function(t,e,i){var n=i(1),s=i(1);n=i(959),s=i(960),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(1),s=i(1);n=i(962),s=i(963),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){t.exports={GravityWell:i(395),Particle:i(396),ParticleEmitter:i(397),ParticleEmitterManager:i(189),Zones:i(969)}},function(t,e,i){var n=i(0),s=i(325),r=i(67),o=i(2),a=i(58),h=new n({initialize:function(t,e,i,n){void 0===n&&(n=!1),this.propertyKey=e,this.propertyValue=i,this.defaultValue=i,this.steps=0,this.counter=0,this.start=0,this.end=0,this.ease,this.emitOnly=n,this.onEmit=this.defaultEmit,this.onUpdate=this.defaultUpdate,this.loadConfig(t)},loadConfig:function(t,e){void 0===t&&(t={}),e&&(this.propertyKey=e),this.propertyValue=o(t,this.propertyKey,this.defaultValue),this.setMethods(),this.emitOnly&&(this.onUpdate=this.defaultUpdate)},toJSON:function(){return this.propertyValue},onChange:function(t){return this.propertyValue=t,this.setMethods()},setMethods:function(){var t=this.propertyValue,e=typeof t;if("number"===e)this.onEmit=this.staticValueEmit,this.onUpdate=this.staticValueUpdate;else if(Array.isArray(t))this.onEmit=this.randomStaticValueEmit;else if("function"===e)this.emitOnly?this.onEmit=t:this.onUpdate=t;else if("object"===e&&(this.has(t,"random")||this.hasBoth(t,"start","end")||this.hasBoth(t,"min","max"))){this.start=this.has(t,"start")?t.start:t.min,this.end=this.has(t,"end")?t.end:t.max;var i=this.hasBoth(t,"min","max")||!!t.random;if(i){var n=t.random;Array.isArray(n)&&(this.start=n[0],this.end=n[1]),this.onEmit=this.randomRangedValueEmit}if(this.has(t,"steps"))this.steps=t.steps,this.counter=this.start,this.onEmit=this.steppedEmit;else{var s=this.has(t,"ease")?t.ease:"Linear";this.ease=r(s),i||(this.onEmit=this.easedValueEmit),this.onUpdate=this.easeValueUpdate}}else"object"===e&&this.hasEither(t,"onEmit","onUpdate")&&(this.has(t,"onEmit")&&(this.onEmit=t.onEmit),this.has(t,"onUpdate")&&(this.onUpdate=t.onUpdate));return this},has:function(t,e){return t.hasOwnProperty(e)},hasBoth:function(t,e,i){return t.hasOwnProperty(e)&&t.hasOwnProperty(i)},hasEither:function(t,e,i){return t.hasOwnProperty(e)||t.hasOwnProperty(i)},defaultEmit:function(t,e,i){return i},defaultUpdate:function(t,e,i,n){return n},staticValueEmit:function(){return this.propertyValue},staticValueUpdate:function(){return this.propertyValue},randomStaticValueEmit:function(){var t=Math.floor(Math.random()*this.propertyValue.length);return this.propertyValue[t]},randomRangedValueEmit:function(t,e){var i=s(this.start,this.end);return t&&t.data[e]&&(t.data[e].min=i),i},steppedEmit:function(){var t=this.counter,e=this.counter+(this.end-this.start)/this.steps;return this.counter=a(e,this.start,this.end),t},easedValueEmit:function(t,e){if(t&&t.data[e]){var i=t.data[e];i.min=this.start,i.max=this.end}return this.start},easeValueUpdate:function(t,e,i){var n=t.data[e];return(n.max-n.min)*this.ease(i)+n.min}});t.exports=h},function(t,e,i){var n=i(1),s=i(1);n=i(967),s=i(968),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(9);t.exports=function(t,e,i,s,r){var o=e.emitters.list,a=o.length;if(0!==a){var h=this.pipeline,l=h._tempMatrix1.copyFrom(s.matrix),u=h._tempMatrix2,c=h._tempMatrix3,d=h._tempMatrix4.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);l.multiply(d),t.setPipeline(h);var f=s.roundPixels,p=e.defaultFrame.glTexture,g=n.getTintAppendFloatAlphaAndSwap;h.setTexture2D(p,0);for(var v=0;v?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",TEXT_SET2:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET3:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",TEXT_SET4:"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",TEXT_SET5:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",TEXT_SET6:"ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",TEXT_SET7:"AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",TEXT_SET8:"0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET9:"ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",TEXT_SET10:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET11:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"}},function(t,e,i){var n=i(6);t.exports=function(t,e){var i=e.width,s=e.height,r=Math.floor(i/2),o=Math.floor(s/2),a=n(e,"chars","");if(""!==a){var h=n(e,"image",""),l=n(e,"offset.x",0),u=n(e,"offset.y",0),c=n(e,"spacing.x",0),d=n(e,"spacing.y",0),f=n(e,"lineSpacing",0),p=n(e,"charsPerRow",null);null===p&&(p=t.sys.textures.getFrame(h).width/i)>a.length&&(p=a.length);for(var g=l,v=u,m={retroFont:!0,font:h,size:i,lineHeight:s+f,chars:{}},y=0,x=0;x0&&r.maxLines1&&(d+=f*(h-1)),{width:a,height:d,lines:h,lineWidths:o,lineSpacing:f,lineHeight:c}}},function(t,e,i){var n=i(1),s=i(1);n=i(981),s=i(982),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(9);t.exports=function(t,e,i,s,r){if(0!==e.width&&0!==e.height){var o=e.frame,a=o.width,h=o.height,l=n.getTintAppendFloatAlpha;this.pipeline.batchTexture(e,o.glTexture,a,h,e.x,e.y,a/e.style.resolution,h/e.style.resolution,e.scaleX,e.scaleY,e.rotation,e.flipX,e.flipY,e.scrollFactorX,e.scrollFactorY,e.displayOriginX,e.displayOriginY,0,0,a,h,l(e._tintTL,s.alpha*e._alphaTL),l(e._tintTR,s.alpha*e._alphaTR),l(e._tintBL,s.alpha*e._alphaBL),l(e._tintBR,s.alpha*e._alphaBR),e._isTinted&&e.tintFill,0,0,s,r)}}},function(t,e){t.exports=function(t,e,i,n,s){0!==e.width&&0!==e.height&&t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(0),s=i(15),r=i(6),o=i(984),a={fontFamily:["fontFamily","Courier"],fontSize:["fontSize","16px"],fontStyle:["fontStyle",""],backgroundColor:["backgroundColor",null],color:["color","#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",!1],shadowFill:["shadow.fill",!1],align:["align","left"],maxLines:["maxLines",0],fixedWidth:["fixedWidth",0],fixedHeight:["fixedHeight",0],resolution:["resolution",0],rtl:["rtl",!1],testString:["testString","|MÉqgy"],baselineX:["baselineX",1.2],baselineY:["baselineY",1.4],wordWrapWidth:["wordWrap.width",null],wordWrapCallback:["wordWrap.callback",null],wordWrapCallbackScope:["wordWrap.callbackScope",null],wordWrapUseAdvanced:["wordWrap.useAdvancedWrap",!1]},h=new n({initialize:function(t,e){this.parent=t,this.fontFamily,this.fontSize,this.fontStyle,this.backgroundColor,this.color,this.stroke,this.strokeThickness,this.shadowOffsetX,this.shadowOffsetY,this.shadowColor,this.shadowBlur,this.shadowStroke,this.shadowFill,this.align,this.maxLines,this.fixedWidth,this.fixedHeight,this.resolution,this.rtl,this.testString,this.baselineX,this.baselineY,this._font,this.setStyle(e,!1,!0);var i=r(e,"metrics",!1);this.metrics=i?{ascent:r(i,"ascent",0),descent:r(i,"descent",0),fontSize:r(i,"fontSize",0)}:o(this)},setStyle:function(t,e,i){for(var n in void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px"),a){var o=i?a[n][1]:this[n];this[n]="wordWrapCallback"===n||"wordWrapCallbackScope"===n?r(t,a[n][0],o):s(t,a[n][0],o)}var h=r(t,"font",null);null!==h&&this.setFont(h,!1),this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim();var l=r(t,"fill",null);return null!==l&&(this.color=l),e?this.update(!0):this.parent},syncFont:function(t,e){e.font=this._font},syncStyle:function(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"},syncShadow:function(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)},update:function(t){return t&&(this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim(),this.metrics=o(this)),this.parent.updateText()},setFont:function(t,e){void 0===e&&(e=!0);var i=t,n="",s="";if("string"!=typeof t)i=r(t,"fontFamily","Courier"),n=r(t,"fontSize","16px"),s=r(t,"fontStyle","");else{var o=t.split(" "),a=0;s=o.length>2?o[a++]:"",n=o[a++]||"16px",i=o[a++]||"Courier"}return i===this.fontFamily&&n===this.fontSize&&s===this.fontStyle||(this.fontFamily=i,this.fontSize=n,this.fontStyle=s,e&&this.update(!0)),this.parent},setFontFamily:function(t){return this.fontFamily!==t&&(this.fontFamily=t,this.update(!0)),this.parent},setFontStyle:function(t){return this.fontStyle!==t&&(this.fontStyle=t,this.update(!0)),this.parent},setFontSize:function(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize!==t&&(this.fontSize=t,this.update(!0)),this.parent},setTestString:function(t){return this.testString=t,this.update(!0)},setFixedSize:function(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(!1)},setBackgroundColor:function(t){return this.backgroundColor=t,this.update(!1)},setFill:function(t){return this.color=t,this.update(!1)},setColor:function(t){return this.color=t,this.update(!1)},setResolution:function(t){return this.resolution=t,this.update(!1)},setStroke:function(t,e){return void 0===e&&(e=this.strokeThickness),void 0===t&&0!==this.strokeThickness?(this.strokeThickness=0,this.update(!0)):this.stroke===t&&this.strokeThickness===e||(this.stroke=t,this.strokeThickness=e,this.update(!0)),this.parent},setShadow:function(t,e,i,n,s,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===n&&(n=0),void 0===s&&(s=!1),void 0===r&&(r=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=i,this.shadowBlur=n,this.shadowStroke=s,this.shadowFill=r,this.update(!1)},setShadowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)},setShadowColor:function(t){return void 0===t&&(t="#000"),this.shadowColor=t,this.update(!1)},setShadowBlur:function(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)},setShadowStroke:function(t){return this.shadowStroke=t,this.update(!1)},setShadowFill:function(t){return this.shadowFill=t,this.update(!1)},setWordWrapWidth:function(t,e){return void 0===e&&(e=!1),this.wordWrapWidth=t,this.wordWrapUseAdvanced=e,this.update(!1)},setWordWrapCallback:function(t,e){return void 0===e&&(e=null),this.wordWrapCallback=t,this.wordWrapCallbackScope=e,this.update(!1)},setAlign:function(t){return void 0===t&&(t="left"),this.align=t,this.update(!1)},setMaxLines:function(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)},getTextMetrics:function(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}},toJSON:function(){var t={};for(var e in a)t[e]=this[e];return t.metrics=this.getTextMetrics(),t},destroy:function(){this.parent=void 0}});t.exports=h},function(t,e,i){var n=i(27);t.exports=function(t){var e=n.create(this),i=e.getContext("2d");t.syncFont(e,i);var s=Math.ceil(i.measureText(t.testString).width*t.baselineX),r=s,o=2*r;r=r*t.baselineY|0,e.width=s,e.height=o,i.fillStyle="#f00",i.fillRect(0,0,s,o),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,r);var a={ascent:0,descent:0,fontSize:0};if(!i.getImageData(0,0,s,o))return a.ascent=r,a.descent=r+6,a.fontSize=a.ascent+a.descent,n.remove(e),a;var h,l,u=i.getImageData(0,0,s,o).data,c=u.length,d=4*s,f=0,p=!1;for(h=0;hr;h--){for(l=0;l0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.fillColor,e.fillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.altFillColor,e.altFillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0){var R=o.strokeTint,L=n.getTintAppendFloatAlphaAndSwap(e.outlineFillColor,e.outlineFillAlpha*d);for(R.TL=L,R.TR=L,R.BL=L,R.BR=L,_=1;_0)for(n(h,e),_=0;_0)for(n(h,e,e.altFillColor,e.altFillAlpha*c),_=0;_0){for(s(h,e,e.outlineFillColor,e.outlineFillAlpha*c),A=1;Ao.vertexCapacity&&o.flush(),o.setTexture2D(u,0);for(var m=o.vertexViewF32,y=o.vertexViewU32,x=o.vertexCount*o.vertexComponentCount-1,T=0,w=e.tintFill,b=0;b0?Math.PI*t.radius*t.radius:0}},function(t,e,i){var n=i(63);t.exports=function(t){return new n(t.x,t.y,t.radius)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.radius)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.radius===e.radius}},function(t,e,i){var n=i(13);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.diameter,e.height=t.diameter,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(93);n.Area=i(1092),n.Circumference=i(393),n.CircumferencePoint=i(188),n.Clone=i(1093),n.Contains=i(94),n.ContainsPoint=i(1094),n.ContainsRect=i(1095),n.CopyFrom=i(1096),n.Equals=i(1097),n.GetBounds=i(1098),n.GetPoint=i(391),n.GetPoints=i(392),n.Offset=i(1099),n.OffsetPoint=i(1100),n.Random=i(151),t.exports=n},function(t,e){t.exports=function(t){return t.isEmpty()?0:t.getMajorRadius()*t.getMinorRadius()*Math.PI}},function(t,e,i){var n=i(93);t.exports=function(t){return new n(t.x,t.y,t.width,t.height)}},function(t,e,i){var n=i(94);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(94);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.width,t.height)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}},function(t,e,i){var n=i(13);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.width,e.height=t.height,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(4),s=i(200);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a,h,l=t.x,u=t.y,c=t.radius,d=e.x,f=e.y,p=e.radius;if(u===f)0==(a=(o=-2*f)*o-4*(r=1)*(d*d+(h=(p*p-c*c-d*d+l*l)/(2*(l-d)))*h-2*d*h+f*f-p*p))?i.push(new n(h,-o/(2*r))):a>0&&(i.push(new n(h,(-o+Math.sqrt(a))/(2*r))),i.push(new n(h,(-o-Math.sqrt(a))/(2*r))));else{var g=(l-d)/(u-f),v=(p*p-c*c-d*d+l*l-f*f+u*u)/(2*(u-f));0==(a=(o=2*u*g-2*v*g-2*l)*o-4*(r=g*g+1)*(l*l+u*u+v*v-c*c-2*u*v))?(h=-o/(2*r),i.push(new n(h,v-h*g))):a>0&&(h=(-o+Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)),h=(-o-Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)))}}return i}},function(t,e,i){var n=i(202),s=i(201);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC(),h=e.getLineD();n(r,t,i),n(o,t,i),n(a,t,i),n(h,t,i)}return i}},function(t,e,i){var n=i(13),s=i(129);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i}},function(t,e,i){var n=i(204),s=i(129);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC(),h=t.getLineD();n(r,e,i),n(o,e,i),n(a,e,i),n(h,e,i)}return i}},function(t,e,i){var n=i(426),s=i(204);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(r,t,i),s(o,t,i),s(a,t,i)}return i}},function(t,e,i){var n=i(202),s=i(428);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC();n(r,e,i),n(o,e,i),n(a,e,i)}return i}},function(t,e,i){var n=i(431),s=i(429);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(t,r,i),s(t,o,i),s(t,a,i)}return i}},function(t,e,i){var n=i(433);t.exports=function(t,e){if(!n(t,e))return!1;var i=Math.min(e.x1,e.x2),s=Math.max(e.x1,e.x2),r=Math.min(e.y1,e.y2),o=Math.max(e.y1,e.y2);return t.x>=i&&t.x<=s&&t.y>=r&&t.y<=o}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||s0){var m=u[0],y=[m];for(h=1;h=o&&(y.push(x),m=x)}var T=u[u.length-1];return n(m,T)i&&(i=h.x),h.xr&&(r=h.y),h.yn(e)?t.setSize(e.height*i,e.height):t.setSize(e.width,e.width/i),t.setPosition(e.centerX-t.width/2,e.centerY-t.height/2)}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t.width=Math.floor(t.width),t.height=Math.floor(t.height),t}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.centerX,e.y=t.centerY,e}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.width,e.y=t.height,e}},function(t,e,i){var n=i(162);t.exports=function(t,e,i){var s=t.centerX,r=t.centerY;return t.setSize(t.width+2*e,t.height+2*i),n(t,s,r)}},function(t,e,i){var n=i(13),s=i(129);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)?(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y):i.setEmpty(),i}},function(t,e){t.exports=function(t,e){for(var i=t.x,n=t.right,s=t.y,r=t.bottom,o=0;oe.x&&t.ye.y}},function(t,e,i){var n=i(4),s=i(35);t.exports=function(t,e,i){void 0===i&&(i=new n),e=s(e);var r=Math.sin(e),o=Math.cos(e),a=o>0?t.width/2:t.width/-2,h=r>0?t.height/2:t.height/-2;return Math.abs(a*r)-1&&(s.splice(a,1),this.clear(o,!0))}t.length=0,this._pendingRemoval.length=0,this._list=s.concat(e.splice(0))}},isActive:function(){return this.enabled&&this.scene.sys.isActive()},updatePoll:function(t,e){if(!this.isActive())return!1;if(this.pluginEvents.emit(d.UPDATE,t,e),this._updatedThisFrame)return this._updatedThisFrame=!1,!1;var i,n=this.manager,s=n.pointers,r=n.pointersTotal;for(i=0;i0){if(this._pollTimer-=e,!(this._pollTimer<0))return!1;this._pollTimer=this.pollRate}var a=!1;for(i=0;i0&&(a=!0)}return a},update:function(t,e){if(!this.isActive())return!1;for(var i=e.length,n=!1,s=0;s0&&(n=!0)}return this._updatedThisFrame=!0,n},clear:function(t,e){void 0===e&&(e=!1);var i=t.input;if(i){e||this.queueForRemoval(t),i.gameObject=void 0,i.target=void 0,i.hitArea=void 0,i.hitAreaCallback=void 0,i.callbackContext=void 0,this.manager.resetCursor(i),t.input=null;var n=this._draggable.indexOf(t);return n>-1&&this._draggable.splice(n,1),(n=this._drag[0].indexOf(t))>-1&&this._drag[0].splice(n,1),(n=this._over[0].indexOf(t))>-1&&this._over[0].splice(n,1),t}},disable:function(t){t.input.enabled=!1},enable:function(t,e,i,n){return void 0===n&&(n=!1),t.input?t.input.enabled=!0:this.setHitArea(t,e,i),t.input&&n&&!t.input.dropZone&&(t.input.dropZone=n),this},hitTestPointer:function(t){for(var e=this.cameras.getCamerasBelowPointer(t),i=0;i0)return t.camera=n,s}return t.camera=e[0],[]},processDownEvents:function(t){var e=0,i=this._temp,n=this._eventData,s=this._eventContainer;n.cancelled=!1;for(var r=!1,o=0;o0&&l(t.x,t.y,t.downX,t.downY)>=s?i=!0:n>0&&e>=t.downTime+n&&(i=!0),i)return this.setDragState(t,3),this.processDragStartList(t)},processDragStartList:function(t){if(3!==this.getDragState(t))return 0;for(var e=this._drag[t.id],i=0;i1&&(this.sortGameObjects(i),this.topOnly&&i.splice(1)),this._drag[t.id]=i,0===this.dragDistanceThreshold&&0===this.dragTimeThreshold?(this.setDragState(t,3),this.processDragStartList(t)):(this.setDragState(t,2),0))},processDragMoveEvent:function(t){if(2===this.getDragState(t)&&this.processDragThresholdEvent(t,this.manager.game.loop.now),4!==this.getDragState(t))return 0;for(var e=this._tempZones,i=this._drag[t.id],n=0;n0?(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),e[0]?(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):a.target=null)}else!h&&e[0]&&(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h));if(o.parentContainer){var u=t.x-a.dragStartXGlobal,c=t.y-a.dragStartYGlobal,f=o.getParentRotation(),p=u*Math.cos(f)+c*Math.sin(f),g=c*Math.cos(f)-u*Math.sin(f);p*=1/o.parentContainer.scaleX,g*=1/o.parentContainer.scaleY,s=p+a.dragStartX,r=g+a.dragStartY}else s=t.x-a.dragX,r=t.y-a.dragY;o.emit(d.GAMEOBJECT_DRAG,t,s,r),this.emit(d.DRAG,t,o,s,r)}return i.length},processDragUpEvent:function(t){for(var e=this._drag[t.id],i=0;i0){var r=this.manager,o=this._eventData,a=this._eventContainer;o.cancelled=!1;for(var h=!1,l=0;l0){var s=this.manager,r=this._eventData,o=this._eventContainer;r.cancelled=!1;var a=!1;this.sortGameObjects(e);for(var h=0;h0){for(this.sortGameObjects(s),e=0;e0){for(this.sortGameObjects(r),e=0;e-1&&this._draggable.splice(s,1)}return this},makePixelPerfect:function(t){void 0===t&&(t=1);var e=this.systems.textures;return h(e,t)},setHitArea:function(t,e,i){if(void 0===e)return this.setHitAreaFromTexture(t);Array.isArray(t)||(t=[t]);var n=!1,s=!1,r=!1,o=!1,h=!1,l=!0;if(m(e)){var u=e;e=p(u,"hitArea",null),i=p(u,"hitAreaCallback",null),n=p(u,"draggable",!1),s=p(u,"dropZone",!1),r=p(u,"cursor",!1),o=p(u,"useHandCursor",!1),h=p(u,"pixelPerfect",!1);var c=p(u,"alphaTolerance",1);h&&(e={},i=this.makePixelPerfect(c)),e&&i||(this.setHitAreaFromTexture(t),l=!1)}else"function"!=typeof e||i||(i=e,e={});for(var d=0;d=e}}},function(t,e,i){t.exports={Events:i(131),KeyboardManager:i(361),KeyboardPlugin:i(1214),Key:i(446),KeyCodes:i(118),KeyCombo:i(447),JustDown:i(1219),JustUp:i(1220),DownDuration:i(1221),UpDuration:i(1222)}},function(t,e){t.exports="keydown"},function(t,e){t.exports="keyup"},function(t,e){t.exports="keycombomatch"},function(t,e){t.exports="down"},function(t,e){t.exports="keydown-"},function(t,e){t.exports="keyup-"},function(t,e){t.exports="up"},function(t,e,i){var n=i(0),s=i(11),r=i(131),o=i(19),a=i(6),h=i(54),l=i(130),u=i(446),c=i(118),d=i(447),f=i(1218),p=i(91),g=new n({Extends:s,initialize:function(t){s.call(this),this.game=t.systems.game,this.scene=t.scene,this.settings=this.scene.sys.settings,this.sceneInputPlugin=t,this.manager=t.manager.keyboard,this.enabled=!0,this.keys=[],this.combos=[],t.pluginEvents.once(h.BOOT,this.boot,this),t.pluginEvents.on(h.START,this.start,this)},boot:function(){var t=this.settings.input;this.enabled=a(t,"keyboard",!0);var e=a(t,"keyboard.capture",null);e&&this.addCaptures(e),this.sceneInputPlugin.pluginEvents.once(h.DESTROY,this.destroy,this)},start:function(){this.sceneInputPlugin.manager.useQueue?this.sceneInputPlugin.pluginEvents.on(h.UPDATE,this.update,this):this.sceneInputPlugin.manager.events.on(h.MANAGER_PROCESS,this.update,this),this.sceneInputPlugin.pluginEvents.once(h.SHUTDOWN,this.shutdown,this),this.game.events.on(o.BLUR,this.resetKeys,this)},isActive:function(){return this.enabled&&this.scene.sys.isActive()},addCapture:function(t){return this.manager.addCapture(t),this},removeCapture:function(t){return this.manager.removeCapture(t),this},getCaptures:function(){return this.manager.captures},enableGlobalCapture:function(){return this.manager.preventDefault=!0,this},disableGlobalCapture:function(){return this.manager.preventDefault=!1,this},clearCaptures:function(){return this.manager.clearCaptures(),this},createCursorKeys:function(){return this.addKeys({up:c.UP,down:c.DOWN,left:c.LEFT,right:c.RIGHT,space:c.SPACE,shift:c.SHIFT})},addKeys:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1);var n={};if("string"==typeof t){t=t.split(",");for(var s=0;s-1?n[s]=t:n[t.keyCode]=t,e&&this.addCapture(t.keyCode),t.setEmitOnRepeat(i),t}return"string"==typeof t&&(t=c[t.toUpperCase()]),n[t]||(n[t]=new u(this,t),e&&this.addCapture(t),n[t].setEmitOnRepeat(i)),n[t]},removeKey:function(t,e){void 0===e&&(e=!1);var i,n=this.keys;if(t instanceof u){var s=n.indexOf(t);s>-1&&(i=this.keys[s],this.keys[s]=void 0)}else"string"==typeof t&&(t=c[t.toUpperCase()]);return n[t]&&(i=n[t],n[t]=void 0),i&&(i.plugin=null,e&&i.destroy()),this},createCombo:function(t,e){return new d(this,t,e)},checkDown:function(t,e){if(this.enabled&&t.isDown){var i=p(this.time-t.timeDown,e);if(i>t._tick)return t._tick=i,!0}return!1},update:function(){var t=this.manager.queue,e=t.length;if(this.isActive()&&0!==e)for(var i=this.keys,n=0;n0&&e.maxKeyDelay>0){var r=e.timeLastMatched+e.maxKeyDelay;t.timeStamp<=r&&(s=!0,i=n(t,e))}else s=!0,i=n(t,e);return!s&&e.resetOnWrongKey&&(e.index=0,e.current=e.keyCodes[0]),i&&(e.timeLastMatched=t.timeStamp,e.matched=!0,e.timeMatched=t.timeStamp),i}},function(t,e){t.exports=function(t,e){return e.timeLastMatched=t.timeStamp,e.index++,e.index===e.size||(e.current=e.keyCodes[e.index],!1)}},function(t,e){t.exports=function(t){return t.current=t.keyCodes[0],t.index=0,t.timeLastMatched=0,t.matched=!1,t.timeMatched=0,t}},function(t,e,i){var n=i(118),s={};for(var r in n)s[n[r]]=r;t.exports=s},function(t,e){t.exports=function(t){return!!t._justDown&&(t._justDown=!1,!0)}},function(t,e){t.exports=function(t){return!!t._justUp&&(t._justUp=!1,!0)}},function(t,e){t.exports=function(t,e){void 0===e&&(e=50);var i=t.plugin.game.loop.time-t.timeDown;return t.isDown&&i'),i.push(''),i.push(''),i.push(this.xhrLoader.responseText),i.push(""),i.push(""),i.push("");var n=[i.join("\n")],o=this;try{var a=new window.Blob(n,{type:"image/svg+xml;charset=utf-8"})}catch(t){return o.state=s.FILE_ERRORED,void o.onProcessComplete()}this.data=new Image,this.data.crossOrigin=this.crossOrigin,this.data.onload=function(){r.revokeObjectURL(o.data),o.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(o.data),o.onProcessError()},r.createObjectURL(this.data,a,"image/svg+xml")},addToCache:function(){var t=this.cache.addImage(this.key,this.data);this.pendingDestroy(t)}});o.register("htmlTexture",function(t,e,i,n,s){if(Array.isArray(t))for(var r=0;r0},isLoading:function(){return this.state===s.LOADER_LOADING||this.state===s.LOADER_PROCESSING},isReady:function(){return this.state===s.LOADER_IDLE||this.state===s.LOADER_COMPLETE},start:function(){this.isReady()&&(this.progress=0,this.totalFailed=0,this.totalComplete=0,this.totalToLoad=this.list.size,this.emit(a.START,this),0===this.list.size?this.loadComplete():(this.state=s.LOADER_LOADING,this.inflight.clear(),this.queue.clear(),this.updateProgress(),this.checkLoadQueue(),this.systems.events.on(c.UPDATE,this.update,this)))},updateProgress:function(){this.progress=1-(this.list.size+this.inflight.size)/this.totalToLoad,this.emit(a.PROGRESS,this.progress)},update:function(){this.state===s.LOADER_LOADING&&this.list.size>0&&this.inflight.sizei&&(n=l,i=c)}}return n},moveTo:function(t,e,i,n,s){void 0===n&&(n=60),void 0===s&&(s=0);var o=Math.atan2(i-t.y,e-t.x);return s>0&&(n=r(t.x,t.y,e,i)/(s/1e3)),t.body.velocity.setToPolar(o,n),o},moveToObject:function(t,e,i,n){return this.moveTo(t,e.x,e.y,i,n)},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(s(t),e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(t,e)},overlapRect:function(t,e,i,n,s,r){return c(this.world,t,e,i,n,s,r)},overlapCirc:function(t,e,i,n,s){return u(this.world,t,e,i,n,s)},shutdown:function(){if(this.world){var t=this.systems.events;t.off(f.UPDATE,this.world.update,this.world),t.off(f.POST_UPDATE,this.world.postUpdate,this.world),t.off(f.SHUTDOWN,this.shutdown,this),this.add.destroy(),this.world.destroy(),this.add=null,this.world=null}},destroy:function(){this.shutdown(),this.scene.sys.events.off(f.START,this.start,this),this.scene=null,this.systems=null}});d.register("ArcadePhysics",v,"arcadePhysics"),t.exports=v},function(t,e){t.exports={setAcceleration:function(t,e){return this.body.acceleration.set(t,e),this},setAccelerationX:function(t){return this.body.acceleration.x=t,this},setAccelerationY:function(t){return this.body.acceleration.y=t,this}}},function(t,e){t.exports={setAngularVelocity:function(t){return this.body.angularVelocity=t,this},setAngularAcceleration:function(t){return this.body.angularAcceleration=t,this},setAngularDrag:function(t){return this.body.angularDrag=t,this}}},function(t,e){t.exports={setBounce:function(t,e){return this.body.bounce.set(t,e),this},setBounceX:function(t){return this.body.bounce.x=t,this},setBounceY:function(t){return this.body.bounce.y=t,this},setCollideWorldBounds:function(t,e,i){return this.body.setCollideWorldBounds(t,e,i),this}}},function(t,e){t.exports={setDebug:function(t,e,i){return this.debugShowBody=t,this.debugShowVelocity=e,this.debugBodyColor=i,this},setDebugBodyColor:function(t){return this.body.debugBodyColor=t,this},debugShowBody:{get:function(){return this.body.debugShowBody},set:function(t){this.body.debugShowBody=t}},debugShowVelocity:{get:function(){return this.body.debugShowVelocity},set:function(t){this.body.debugShowVelocity=t}},debugBodyColor:{get:function(){return this.body.debugBodyColor},set:function(t){this.body.debugBodyColor=t}}}},function(t,e){t.exports={setDrag:function(t,e){return this.body.drag.set(t,e),this},setDragX:function(t){return this.body.drag.x=t,this},setDragY:function(t){return this.body.drag.y=t,this},setDamping:function(t){return this.body.useDamping=t,this}}},function(t,e){var i={enableBody:function(t,e,i,n,s){return t&&this.body.reset(e,i),n&&(this.body.gameObject.active=!0),s&&(this.body.gameObject.visible=!0),this.body.enable=!0,this},disableBody:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=!1),this.body.stop(),this.body.enable=!1,t&&(this.body.gameObject.active=!1),e&&(this.body.gameObject.visible=!1),this},refreshBody:function(){return this.body.updateFromGameObject(),this}};t.exports=i},function(t,e){t.exports={setFriction:function(t,e){return this.body.friction.set(t,e),this},setFrictionX:function(t){return this.body.friction.x=t,this},setFrictionY:function(t){return this.body.friction.y=t,this}}},function(t,e){t.exports={setGravity:function(t,e){return this.body.gravity.set(t,e),this},setGravityX:function(t){return this.body.gravity.x=t,this},setGravityY:function(t){return this.body.gravity.y=t,this}}},function(t,e){var i={setImmovable:function(t){return void 0===t&&(t=!0),this.body.immovable=t,this}};t.exports=i},function(t,e){t.exports={setMass:function(t){return this.body.mass=t,this}}},function(t,e){t.exports={setOffset:function(t,e){return this.body.setOffset(t,e),this},setSize:function(t,e,i){return this.body.setSize(t,e,i),this},setCircle:function(t,e,i){return this.body.setCircle(t,e,i),this}}},function(t,e){t.exports={setVelocity:function(t,e){return this.body.setVelocity(t,e),this},setVelocityX:function(t){return this.body.setVelocityX(t),this},setVelocityY:function(t){return this.body.setVelocityY(t),this},setMaxVelocity:function(t,e){return this.body.maxVelocity.set(t,e),this}}},function(t,e,i){var n=i(457),s=i(63),r=i(200),o=i(201);t.exports=function(t,e,i,a,h,l){var u=n(t,e-a,i-a,2*a,2*a,h,l);if(0===u.length)return u;for(var c=new s(e,i,a),d=new s,f=[],p=0;pe.deltaAbsY()?y=-1:e.deltaAbsX()0&&u&&t.checkCollision.right&&h&&t.right>i&&(a=t.right-i)>r&&(a=0),0!==a&&(t.customSeparateX?t.overlapX=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.left=!0):e>0&&(t.blocked.none=!1,t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x}},function(t,e,i){var n=i(1279);t.exports=function(t,e,i,s,r,o){var a=0,h=e.faceTop,l=e.faceBottom,u=e.collideUp,c=e.collideDown;return o||(h=!0,l=!0,u=!0,c=!0),t.deltaY()<0&&c&&t.checkCollision.up?l&&t.y0&&u&&t.checkCollision.down&&h&&t.bottom>i&&(a=t.bottom-i)>r&&(a=0),0!==a&&(t.customSeparateY?t.overlapY=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.up=!0):e>0&&(t.blocked.none=!1,t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},function(t,e,i){var n=i(461);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.x,a=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=r,e.velocity.x=o-a*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=r,t.velocity.x=a-o*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{r*=.5,t.x-=r,e.x+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.x=u+h*t.bounce.x,e.velocity.x=u+l*e.bounce.x}return!0}},function(t,e,i){var n=i(462);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.y,a=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=r,e.velocity.y=o-a*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=r,t.velocity.y=a-o*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{r*=.5,t.y-=r,e.y+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.y=u+h*t.bounce.y,e.velocity.y=u+l*e.bounce.y}return!0}},function(t,e,i){var n={};t.exports=n;var s=i(142),r=i(214),o=i(37),a=i(62),h=i(105);n.stack=function(t,e,i,n,r,o,h){for(var l,u=s.create({label:"Stack"}),c=t,d=e,f=0,p=0;pg&&(g=y),a.translate(m,{x:.5*x,y:.5*y}),c=m.bounds.max.x+r,s.addBody(u,m),l=m,f+=1}else c+=r}d+=g+o,c=t}return u},n.chain=function(t,e,i,n,a,h){for(var l=t.bodies,u=1;u0)for(l=0;l0&&(d=f[l-1+(h-1)*e],s.addConstraint(t,r.create(o.extend({bodyA:d,bodyB:c},a)))),n&&ld||o<(l=d-l)||o>i-1-l))return 1===c&&a.translate(u,{x:(o+(i%2==1?1:-1))*f,y:0}),h(t+(u?o*f:0)+o*r,n,o,l,u,c)})},n.newtonsCradle=function(t,e,i,n,o){for(var a=s.create({label:"Newtons Cradle"}),l=0;l1;if(!d||t!=d.x||e!=d.y){d&&n?(f=d.x,p=d.y):(f=0,p=0);var s={x:f+t,y:p+e};!n&&d||(d=s),g.push(s),m=f+t,y=p+e}},T=function(t){var e=t.pathSegTypeAsLetter.toUpperCase();if("Z"!==e){switch(e){case"M":case"L":case"T":case"C":case"S":case"Q":m=t.x,y=t.y;break;case"H":m=t.x;break;case"V":y=t.y}x(m,y,t.pathSegType)}};for(n._svgPathToAbsolute(t),o=t.getTotalLength(),l=[],i=0;i0?this.setFromTileCollision(i):this.setFromTileRectangle(i)}},setFromTileRectangle:function(t){void 0===t&&(t={}),l(t,"isStatic")||(t.isStatic=!0),l(t,"addToWorld")||(t.addToWorld=!0);var e=this.tile.getBounds(),i=e.x+e.width/2,s=e.y+e.height/2,r=n.rectangle(i,s,e.width,e.height,t);return this.setBody(r,t.addToWorld),this},setFromTileCollision:function(t){void 0===t&&(t={}),l(t,"isStatic")||(t.isStatic=!0),l(t,"addToWorld")||(t.addToWorld=!0);for(var e=this.tile.tilemapLayer.scaleX,i=this.tile.tilemapLayer.scaleY,r=this.tile.getLeft(),o=this.tile.getTop(),a=this.tile.getCollisionGroup(),c=h(a,"objects",[]),d=[],f=0;f1&&(t.parts=d,this.setBody(s.create(t),t.addToWorld)),this},setBody:function(t,e){return void 0===e&&(e=!0),this.body&&this.removeBody(),this.body=t,this.body.gameObject=this,e&&this.world.add(this.body),this},removeBody:function(){return this.body&&(this.world.remove(this.body),this.body.gameObject=void 0,this.body=void 0),this},destroy:function(){this.removeBody(),this.tile.physics.matterBody=void 0,this.removeAllListeners()}});t.exports=c},function(t,e,i){var n=i(1381);n.Body=i(62),n.Composite=i(142),n.World=i(1290),n.Detector=i(510),n.Grid=i(1291),n.Pairs=i(1292),n.Pair=i(466),n.Query=i(1382),n.Resolver=i(1293),n.SAT=i(511),n.Constraint=i(214),n.Common=i(37),n.Engine=i(1383),n.Events=i(235),n.Sleeping=i(234),n.Plugin=i(1289),n.Bodies=i(105),n.Composites=i(1282),n.Axes=i(508),n.Bounds=i(98),n.Svg=i(1283),n.Vector=i(97),n.Vertices=i(84),n.World.add=n.Composite.add,n.World.remove=n.Composite.remove,n.World.addComposite=n.Composite.addComposite,n.World.addBody=n.Composite.addBody,n.World.addConstraint=n.Composite.addConstraint,n.World.clear=n.Composite.clear,t.exports=n},function(t,e,i){var n={};t.exports=n;var s=i(37);n._registry={},n.register=function(t){if(n.isPlugin(t)||s.warn("Plugin.register:",n.toString(t),"does not implement all required fields."),t.name in n._registry){var e=n._registry[t.name],i=n.versionParse(t.version).number,r=n.versionParse(e.version).number;i>r?(s.warn("Plugin.register:",n.toString(e),"was upgraded to",n.toString(t)),n._registry[t.name]=t):i-1},n.isFor=function(t,e){var i=t.for&&n.dependencyParse(t.for);return!t.for||e.name===i.name&&n.versionSatisfies(e.version,i.range)},n.use=function(t,e){if(t.uses=(t.uses||[]).concat(e||[]),0!==t.uses.length){for(var i=n.dependencies(t),r=s.topologicalSort(i),o=[],a=0;a0&&!h.silent&&s.info(o.join(" "))}else s.warn("Plugin.use:",n.toString(t),"does not specify any dependencies to install.")},n.dependencies=function(t,e){var i=n.dependencyParse(t),r=i.name;if(!(r in(e=e||{}))){t=n.resolve(t)||t,e[r]=s.map(t.uses||[],function(e){n.isPlugin(e)&&n.register(e);var r=n.dependencyParse(e),o=n.resolve(e);return o&&!n.versionSatisfies(o.version,r.range)?(s.warn("Plugin.dependencies:",n.toString(o),"does not satisfy",n.toString(r),"used by",n.toString(i)+"."),o._warned=!0,t._warned=!0):o||(s.warn("Plugin.dependencies:",n.toString(e),"used by",n.toString(i),"could not be resolved."),t._warned=!0),r.name});for(var o=0;o=s[2];if("^"===i.operator)return s[0]>0?o[0]===s[0]&&r.number>=i.number:s[1]>0?o[1]===s[1]&&o[2]>=s[2]:o[2]===s[2]}return t===e||"*"===t}},function(t,e,i){var n={};t.exports=n;var s=i(142),r=(i(214),i(37));n.create=function(t){var e=s.create(),i={label:"World",gravity:{x:0,y:1,scale:.001},bounds:{min:{x:-1/0,y:-1/0},max:{x:1/0,y:1/0}}};return r.extend(e,i,t)}},function(t,e,i){var n={};t.exports=n;var s=i(466),r=i(510),o=i(37);n.create=function(t){var e={controller:n,detector:r.collisions,buckets:{},pairs:{},pairsList:[],bucketWidth:48,bucketHeight:48};return o.extend(e,t)},n.update=function(t,e,i,s){var r,o,a,h,l,u=i.world,c=t.buckets,d=!1,f=i.metrics;for(f.broadphaseTests=0,r=0;ru.bounds.max.x||p.bounds.max.yu.bounds.max.y)){var g=n._getRegion(t,p);if(!p.region||g.id!==p.region.id||s){f.broadphaseTests+=1,p.region&&!s||(p.region=g);var v=n._regionUnion(g,p.region);for(o=v.startCol;o<=v.endCol;o++)for(a=v.startRow;a<=v.endRow;a++){h=c[l=n._getBucketId(o,a)];var m=o>=g.startCol&&o<=g.endCol&&a>=g.startRow&&a<=g.endRow,y=o>=p.region.startCol&&o<=p.region.endCol&&a>=p.region.startRow&&a<=p.region.endRow;!m&&y&&y&&h&&n._bucketRemoveBody(t,h,p),(p.region===g||m&&!y||s)&&(h||(h=n._createBucket(c,l)),n._bucketAddBody(t,h,p))}p.region=g,d=!0}}}d&&(t.pairsList=n._createActivePairsList(t))},n.clear=function(t){t.buckets={},t.pairs={},t.pairsList=[]},n._regionUnion=function(t,e){var i=Math.min(t.startCol,e.startCol),s=Math.max(t.endCol,e.endCol),r=Math.min(t.startRow,e.startRow),o=Math.max(t.endRow,e.endRow);return n._createRegion(i,s,r,o)},n._getRegion=function(t,e){var i=e.bounds,s=Math.floor(i.min.x/t.bucketWidth),r=Math.floor(i.max.x/t.bucketWidth),o=Math.floor(i.min.y/t.bucketHeight),a=Math.floor(i.max.y/t.bucketHeight);return n._createRegion(s,r,o,a)},n._createRegion=function(t,e,i,n){return{id:t+","+e+","+i+","+n,startCol:t,endCol:e,startRow:i,endRow:n}},n._getBucketId=function(t,e){return"C"+t+"R"+e},n._createBucket=function(t,e){return t[e]=[]},n._bucketAddBody=function(t,e,i){for(var n=0;n0?n.push(i):delete t.pairs[e[s]];return n}},function(t,e,i){var n={};t.exports=n;var s=i(466),r=i(37);n._pairMaxIdleLife=1e3,n.create=function(t){return r.extend({table:{},list:[],collisionStart:[],collisionActive:[],collisionEnd:[]},t)},n.update=function(t,e,i){var n,r,o,a,h=t.list,l=t.table,u=t.collisionStart,c=t.collisionEnd,d=t.collisionActive;for(u.length=0,c.length=0,d.length=0,a=0;an._pairMaxIdleLife&&l.push(o);for(o=0;of.friction*f.frictionStatic*F*i&&(I=R,k=o.clamp(f.friction*L*i,-I,I));var B=r.cross(S,m),Y=r.cross(A,m),N=T/(g.inverseMass+v.inverseMass+g.inverseInertia*B*B+v.inverseInertia*Y*Y);if(D*=N,k*=N,O<0&&O*O>n._restingThresh*i)b.normalImpulse=0;else{var X=b.normalImpulse;b.normalImpulse=Math.min(b.normalImpulse+D,0),D=b.normalImpulse-X}if(P*P>n._restingThreshTangent*i)b.tangentImpulse=0;else{var z=b.tangentImpulse;b.tangentImpulse=o.clamp(b.tangentImpulse+k,-I,I),k=b.tangentImpulse-z}s.x=m.x*D+y.x*k,s.y=m.y*D+y.y*k,g.isStatic||g.isSleeping||(g.positionPrev.x+=s.x*g.inverseMass,g.positionPrev.y+=s.y*g.inverseMass,g.anglePrev+=r.cross(S,s)*g.inverseInertia),v.isStatic||v.isSleeping||(v.positionPrev.x-=s.x*v.inverseMass,v.positionPrev.y-=s.y*v.inverseMass,v.anglePrev-=r.cross(A,s)*v.inverseInertia)}}}}},function(t,e,i){t.exports={BasePlugin:i(467),DefaultPlugins:i(170),PluginCache:i(24),PluginManager:i(365),ScenePlugin:i(1295)}},function(t,e,i){var n=i(467),s=i(0),r=i(22),o=new s({Extends:n,initialize:function(t,e){n.call(this,e),this.scene=t,this.systems=t.sys,t.sys.events.once(r.BOOT,this.boot,this)},boot:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=o},function(t,e,i){var n=i(18),s=i(172),r={Center:i(354),Events:i(90),Orientation:i(355),ScaleManager:i(366),ScaleModes:i(356),Zoom:i(357)};r=n(!1,r=n(!1,r=n(!1,r=n(!1,r,s.CENTER),s.ORIENTATION),s.SCALE_MODE),s.ZOOM),t.exports=r},function(t,e,i){var n=i(119),s=i(18),r={Events:i(22),SceneManager:i(368),ScenePlugin:i(1298),Settings:i(370),Systems:i(175)};r=s(!1,r,n),t.exports=r},function(t,e,i){var n=i(23),s=i(0),r=i(22),o=i(2),a=i(24),h=new s({initialize:function(t){this.scene=t,this.systems=t.sys,this.settings=t.sys.settings,this.key=t.sys.settings.key,this.manager=t.sys.game.scene,this.transitionProgress=0,this._elapsed=0,this._target=null,this._duration=0,this._onUpdate,this._onUpdateScope,this._willSleep=!1,this._willRemove=!1,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.pluginStart,this)},boot:function(){this.systems.events.once(r.DESTROY,this.destroy,this)},pluginStart:function(){this._target=null,this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},start:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",this.key),this.manager.queueOp("start",t,e),this},restart:function(t){var e=this.key;return this.manager.queueOp("stop",e),this.manager.queueOp("start",e,t),this},transition:function(t){void 0===t&&(t={});var e=o(t,"target",!1),i=this.manager.getScene(e);if(!e||!this.checkValidTransition(i))return!1;var n=o(t,"duration",1e3);this._elapsed=0,this._target=i,this._duration=n,this._willSleep=o(t,"sleep",!1),this._willRemove=o(t,"remove",!1);var s=o(t,"onUpdate",null);s&&(this._onUpdate=s,this._onUpdateScope=o(t,"onUpdateScope",this.scene));var a=o(t,"allowInput",!1);this.settings.transitionAllowInput=a;var h=i.sys.settings;return h.isTransition=!0,h.transitionFrom=this.scene,h.transitionDuration=n,h.transitionAllowInput=a,o(t,"moveAbove",!1)?this.manager.moveAbove(this.key,e):o(t,"moveBelow",!1)&&this.manager.moveBelow(this.key,e),i.sys.isSleeping()?i.sys.wake():this.manager.start(e,o(t,"data")),this.systems.events.emit(r.TRANSITION_OUT,i,n),this.systems.events.on(r.UPDATE,this.step,this),!0},checkValidTransition:function(t){return!(!t||t.sys.isActive()||t.sys.isTransitioning()||t===this.scene||this.systems.isTransitioning())},step:function(t,e){this._elapsed+=e,this.transitionProgress=n(this._elapsed/this._duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.transitionProgress),this._elapsed>=this._duration&&this.transitionComplete()},transitionComplete:function(){var t=this._target.sys,e=this._target.sys.settings;this.systems.events.off(r.UPDATE,this.step,this),t.events.emit(r.TRANSITION_COMPLETE,this.scene),e.isTransition=!1,e.transitionFrom=null,this._duration=0,this._target=null,this._onUpdate=null,this._onUpdateScope=null,this._willRemove?this.manager.remove(this.key):this._willSleep?this.systems.sleep():this.manager.stop(this.key)},add:function(t,e,i,n){return this.manager.add(t,e,i,n)},launch:function(t,e){return t&&t!==this.key&&this.manager.queueOp("start",t,e),this},run:function(t,e){return t&&t!==this.key&&this.manager.queueOp("run",t,e),this},pause:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("pause",t,e),this},resume:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("resume",t,e),this},sleep:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("sleep",t,e),this},wake:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("wake",t,e),this},switch:function(t){return t!==this.key&&this.manager.queueOp("switch",this.key,t),this},stop:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",t,e),this},setActive:function(t,e,i){void 0===e&&(e=this.key);var n=this.manager.getScene(e);return n&&n.sys.setActive(t,i),this},setVisible:function(t,e){void 0===e&&(e=this.key);var i=this.manager.getScene(e);return i&&i.sys.setVisible(t),this},isSleeping:function(t){return void 0===t&&(t=this.key),this.manager.isSleeping(t)},isActive:function(t){return void 0===t&&(t=this.key),this.manager.isActive(t)},isPaused:function(t){return void 0===t&&(t=this.key),this.manager.isPaused(t)},isVisible:function(t){return void 0===t&&(t=this.key),this.manager.isVisible(t)},swapPosition:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.swapPosition(t,e),this},moveAbove:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveAbove(t,e),this},moveBelow:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveBelow(t,e),this},remove:function(t){return void 0===t&&(t=this.key),this.manager.remove(t),this},moveUp:function(t){return void 0===t&&(t=this.key),this.manager.moveUp(t),this},moveDown:function(t){return void 0===t&&(t=this.key),this.manager.moveDown(t),this},bringToTop:function(t){return void 0===t&&(t=this.key),this.manager.bringToTop(t),this},sendToBack:function(t){return void 0===t&&(t=this.key),this.manager.sendToBack(t),this},get:function(t){return this.manager.getScene(t)},getIndex:function(t){return void 0===t&&(t=this.key),this.manager.getIndex(t)},shutdown:function(){var t=this.systems.events;t.off(r.SHUTDOWN,this.shutdown,this),t.off(r.POST_UPDATE,this.step,this),t.off(r.TRANSITION_OUT)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.settings=null,this.manager=null}});a.register("ScenePlugin",h,"scenePlugin"),t.exports=h},function(t,e,i){t.exports={List:i(123),Map:i(156),ProcessQueue:i(181),RTree:i(463),Set:i(127),Size:i(367)}},function(t,e,i){var n=i(18),s=i(1301),r={CanvasTexture:i(372),Events:i(115),FilterMode:s,Frame:i(92),Parsers:i(374),Texture:i(177),TextureManager:i(371),TextureSource:i(373)};r=n(!1,r,s),t.exports=r},function(t,e){t.exports={LINEAR:0,NEAREST:1}},function(t,e,i){t.exports={Components:i(135),Parsers:i(1335),Formats:i(33),ImageCollection:i(480),ParseToTilemap:i(222),Tile:i(72),Tilemap:i(489),TilemapCreator:i(1344),TilemapFactory:i(1345),Tileset:i(137),LayerData:i(100),MapData:i(101),ObjectLayer:i(483),DynamicTilemapLayer:i(490),StaticTilemapLayer:i(491)}},function(t,e,i){var n=i(25),s=i(51);t.exports=function(t,e,i,r,o,a,h,l){t<0&&(t=0),e<0&&(e=0),void 0===h&&(h=!0);for(var u=n(t,e,i,r,null,l),c=o-t,d=a-e,f=0;f=0&&p=0&&g=y;h--)(u=f[l][h])&&-1!==u.index&&u.visible&&0!==u.alpha&&i.push(u);else if(2===a)for(l=w;l>=T;l--)for(h=y;f[l]&&h=T;l--)for(h=x;f[l]&&h>=y;h--)(u=f[l][h])&&-1!==u.index&&u.visible&&0!==u.alpha&&i.push(u)}else if(t.orientation===n.ISOMETRIC)if(0===a){for(l=T;l=y;h--)if(o(h,l,t,e)){if(!(u=f[l][h])||-1===u.index||!u.visible||0===u.alpha)continue;i.push(u)}}else if(2===a){for(l=w;l>=T;l--)for(h=y;f[l]&&h=T;l--)for(h=x;f[l]&&h>=y;h--)if(o(h,l,t,e)){if(!(u=f[l][h])||-1===u.index||!u.visible||0===u.alpha)continue;i.push(u)}return d.tilesDrawn=i.length,d.tilesTotal=p*g,i}},function(t,e){t.exports=function(t,e,i,n){var s=i.tilemapLayer,r=s.isoCullDistances,o=s.tileToWorldXY(t,e,void 0,n);return o.x>n.worldView.x+s.scaleX*i.tileWidth*(-r.x-.5)&&o.xn.worldView.y+s.scaleY*i.tileHeight*(-r.y-.5)&&o.y=0;r--)for(s=n.width-1;s>=0;s--)if((o=n.data[r][s])&&o.index===t){if(a===e)return o;a+=1}}else for(r=0;re)){for(var l=t;l<=e;l++)r(l,i,a);if(h)for(var u=0;u=t&&d.index<=e&&n(d,i)}o&&s(0,0,a.width,a.height,a)}}},function(t,e,i){var n=i(71),s=i(51),r=i(217);t.exports=function(t,e,i,o){void 0===e&&(e=!0),void 0===i&&(i=!0),Array.isArray(t)||(t=[t]);for(var a=0;a0&&n(a,t)}}e&&s(0,0,i.width,i.height,i)}},function(t,e){t.exports=function(t,e,i,n){if("number"==typeof t)n.callbacks[t]=null!==e?{callback:e,callbackContext:i}:void 0;else for(var s=0,r=t.length;s1||e.scaleY>1)&&(c.imageSmoothingEnabled=!1);for(var p=0;p0&&(t.currentPipeline&&t.currentPipeline.vertexCount>0&&t.flush(),r.vertexBuffer=e.vertexBuffer[a],t.setPipeline(r),t.setTexture2D(s[a].glTexture,0),t.gl.drawArrays(r.topology,0,e.vertexCount[a]));r.vertexBuffer=o,r.viewIdentity(),r.modelIdentity()}},function(t,e){t.exports=function(t,e,i,n,s){e.cull(n);var r=e.culledTiles,o=r.length;if(0!==o){var a=t._tempMatrix1,h=t._tempMatrix2,l=t._tempMatrix3;h.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),a.copyFrom(n.matrix);var u=t.currentContext,c=e.gidMap;u.save(),s?(a.multiplyWithOffset(s,-n.scrollX*e.scrollFactorX,-n.scrollY*e.scrollFactorY),h.e=e.x,h.f=e.y,a.multiply(h,l),l.copyToContext(u)):(h.e-=n.scrollX*e.scrollFactorX,h.f-=n.scrollY*e.scrollFactorY,h.copyToContext(u));var d=n.alpha*e.alpha;(!t.antialias||e.scaleX>1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f-1&&this._active.splice(s,1),n.destroy()}for(i=0;i=n.delay)){var s=n.elapsed-n.delay;n.elapsed=n.delay,!n.hasDispatched&&n.callback&&(n.hasDispatched=!0,n.callback.apply(n.callbackScope,n.args)),n.repeatCount>0?(n.repeatCount--,n.elapsed=s,n.hasDispatched=!1):this._pendingRemoval.push(n)}}}},shutdown:function(){var t;for(t=0;t-1&&(e.state=u.REMOVED,s.splice(r,1)):(e.state=u.REMOVED,n.splice(r,1))}for(i.length=0,i=this._add,t=0;t>2],r+=i[(3&n[o])<<4|n[o+1]>>4],r+=i[(15&n[o+1])<<2|n[o+2]>>6],r+=i[63&n[o+2]];return s%3==2?r=r.substring(0,r.length-1)+"=":s%3==1&&(r=r.substring(0,r.length-2)+"=="),r}},function(t,e,i){t.exports={Clone:i(65),Extend:i(18),GetAdvancedValue:i(15),GetFastValue:i(2),GetMinMaxValue:i(1369),GetValue:i(6),HasAll:i(1370),HasAny:i(400),HasValue:i(104),IsPlainObject:i(7),Merge:i(120),MergeRight:i(1371),Pick:i(481),SetValue:i(420)}},function(t,e,i){var n=i(6),s=i(23);t.exports=function(t,e,i,r,o){void 0===o&&(o=i);var a=n(t,e,o);return s(a,i,r)}},function(t,e){t.exports=function(t,e){for(var i=0;i=0&&h<=1&&l>=0&&l<=1}function s(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])}function r(t,e,i){return s(t,e,i)>0}function o(t,e,i){return s(t,e,i)>=0}function a(t,e,i){return s(t,e,i)<0}function h(t,e,i){return s(t,e,i)<=0}t.exports={decomp:function(t){var e=function t(e){var i=[],n=[],s=[],r=[];var o=Number.MAX_VALUE;for(var a=0;a0?function t(e,i){if(0===i.length)return[e];if(i instanceof Array&&i.length&&i[0]instanceof Array&&2===i[0].length&&i[0][0]instanceof Array){for(var n=[e],s=0;su)return console.warn("quickDecomp: max level ("+u+") reached."),i;for(var L=0;LA&&(A+=e.length),S=Number.MAX_VALUE,A<_)return i;for(var D=_;D<=A;++D)o(f(P,L-1),f(P,L),f(P,D))&&h(f(P,L+1),f(P,L),f(P,D))&&(E=d(f(P,L),f(P,D)))3&&n>=0;--n)c(f(t,n-1),f(t,n),f(t,n+1),e)&&(t.splice(n%t.length,1),i++);return i},removeDuplicatePoints:function(t,e){for(var i=t.length-1;i>=1;--i)for(var n=t[i],s=i-1;s>=0;--s)E(n,t[s],e)&&t.splice(i,1)},makeCCW:function(t){for(var e=0,i=t,n=1;ni[e][0])&&(e=n);return!r(f(t,e-1),f(t,e),f(t,e+1))&&(function(t){for(var e=[],i=t.length,n=0;n!==i;n++)e.push(t.pop());for(var n=0;n!==i;n++)t[n]=e[n]}(t),!0)}};var l=[],u=[];function c(t,e,i,n){if(n){var r=l,o=u;r[0]=e[0]-t[0],r[1]=e[1]-t[1],o[0]=i[0]-e[0],o[1]=i[1]-e[1];var a=r[0]*o[0]+r[1]*o[1],h=Math.sqrt(r[0]*r[0]+r[1]*r[1]),c=Math.sqrt(o[0]*o[0]+o[1]*o[1]);return Math.acos(a/(h*c))0&&u.trigger(t,"collisionStart",{pairs:T.collisionStart}),o.preSolvePosition(T.list),s=0;s0&&u.trigger(t,"collisionActive",{pairs:T.collisionActive}),T.collisionEnd.length>0&&u.trigger(t,"collisionEnd",{pairs:T.collisionEnd}),h.update(t.metrics,t),n._bodiesClearForces(m),u.trigger(t,"afterUpdate",v),t},n.merge=function(t,e){if(f.extend(t,e),e.world){t.world=e.world,n.clear(t);for(var i=c.allBodies(t.world),s=0;s0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_START,e,i,n)}),p.on(e,"collisionActive",function(e){var i,n,s=e.pairs;s.length>0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_ACTIVE,e,i,n)}),p.on(e,"collisionEnd",function(e){var i,n,s=e.pairs;s.length>0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_END,e,i,n)})},setBounds:function(t,e,i,n,s,r,o,a,h){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.scene.sys.scale.width),void 0===n&&(n=this.scene.sys.scale.height),void 0===s&&(s=64),void 0===r&&(r=!0),void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===h&&(h=!0),this.updateWall(r,"left",t-s,e-s,s,n+2*s),this.updateWall(o,"right",t+i,e-s,s,n+2*s),this.updateWall(a,"top",t,e-s,i,s),this.updateWall(h,"bottom",t,e+n,i,s),this},updateWall:function(t,e,i,n,s,r){var o=this.walls[e];t?(o&&v.remove(this.localWorld,o),i+=s/2,n+=r/2,this.walls[e]=this.create(i,n,s,r,{isStatic:!0,friction:0,frictionStatic:0})):(o&&v.remove(this.localWorld,o),this.walls[e]=null)},createDebugGraphic:function(){var t=this.scene.sys.add.graphics({x:0,y:0});return t.setDepth(Number.MAX_VALUE),this.debugGraphic=t,this.drawDebug=!0,t},disableGravity:function(){return this.localWorld.gravity.x=0,this.localWorld.gravity.y=0,this.localWorld.gravity.scale=0,this},setGravity:function(t,e,i){return void 0===t&&(t=0),void 0===e&&(e=1),this.localWorld.gravity.x=t,this.localWorld.gravity.y=e,void 0!==i&&(this.localWorld.gravity.scale=i),this},create:function(t,e,i,s,r){var o=n.rectangle(t,e,i,s,r);return v.add(this.localWorld,o),o},add:function(t){return v.add(this.localWorld,t),this},remove:function(t,e){Array.isArray(t)||(t=[t]);for(var i=0;in.deltaMax?n.deltaMax:e)/n.delta,n.delta=e),0!==n.timeScalePrev&&(r*=s.timeScale/n.timeScalePrev),0===s.timeScale&&(r=0),n.timeScalePrev=s.timeScale,n.correction=r,n.frameCounter+=1,t-n.counterTimestamp>=1e3&&(n.fps=n.frameCounter*((t-n.counterTimestamp)/1e3),n.counterTimestamp=t,n.frameCounter=0),h.update(i,e,r)}},step:function(t,e){h.update(this.engine,t,e)},update60Hz:function(){return 1e3/60},update30Hz:function(){return 1e3/30},has:function(t){var e=t.hasOwnProperty("body")?t.body:t;return null!==a.get(this.localWorld,e.id,e.type)},getAllBodies:function(){return a.allBodies(this.localWorld)},getAllConstraints:function(){return a.allConstraints(this.localWorld)},getAllComposites:function(){return a.allComposites(this.localWorld)},postUpdate:function(){if(this.drawDebug){var t=this.debugConfig,e=this.engine,i=this.debugGraphic,n=a.allBodies(this.localWorld);this.debugGraphic.clear(),t.showBroadphase&&e.broadphase.controller&&this.renderGrid(e.broadphase,i,t.broadphaseColor,.5),t.showBounds&&this.renderBodyBounds(n,i,t.boundsColor,.5),(t.showBody||t.showStaticBody)&&this.renderBodies(n),t.showJoint&&this.renderJoints(),(t.showAxes||t.showAngleIndicator)&&this.renderBodyAxes(n,i,t.showAxes,t.angleColor,.5),t.showVelocity&&this.renderBodyVelocity(n,i,t.velocityColor,1,2),t.showSeparations&&this.renderSeparations(e.pairs.list,i,t.separationColor),t.showCollisions&&this.renderCollisions(e.pairs.list,i,t.collisionColor)}},renderGrid:function(t,e,i,n){e.lineStyle(1,i,n);for(var s=o.keys(t.buckets),r=0;r0){var l=h[0].vertex.x,u=h[0].vertex.y;2===h.length&&(l=(h[0].vertex.x+h[1].vertex.x)/2,u=(h[0].vertex.y+h[1].vertex.y)/2),a.bodyB===a.supports[0].body||a.bodyA.isStatic?e.lineBetween(l-8*a.normal.x,u-8*a.normal.y,l,u):e.lineBetween(l+8*a.normal.x,u+8*a.normal.y,l,u)}}return this},renderBodyBounds:function(t,e,i,n){e.lineStyle(1,i,n);for(var s=0;s1?1:0;h1?1:0;a1?1:0;a1&&this.renderConvexHull(g,e,f,y)}}},renderBody:function(t,e,i,n,s,r,o,a){void 0===n&&(n=null),void 0===s&&(s=null),void 0===r&&(r=1),void 0===o&&(o=null),void 0===a&&(a=null);for(var h=this.debugConfig,l=h.sensorFillColor,u=h.sensorLineColor,c=t.parts,d=c.length,f=d>1?1:0;f1){var s=t.vertices;e.lineStyle(n,i),e.beginPath(),e.moveTo(s[0].x,s[0].y);for(var r=1;r0&&(e.fillStyle(a),e.fillCircle(u.x,u.y,h),e.fillCircle(c.x,c.y,h)),this},resetCollisionIDs:function(){return s._nextCollidingGroupId=1,s._nextNonCollidingGroupId=-1,s._nextCategory=1,this},shutdown:function(){p.off(this.engine),this.removeAllListeners(),v.clear(this.localWorld,!1),h.clear(this.engine),this.drawDebug&&this.debugGraphic.destroy()},destroy:function(){this.shutdown()}});t.exports=y},function(t,e,i){(function(e){i(513);var n=i(10),s=i(18),r={Actions:i(236),Animations:i(633),BlendModes:i(52),Cache:i(634),Cameras:i(637),Core:i(720),Class:i(0),Create:i(779),Curves:i(785),Data:i(788),Display:i(790),DOM:i(807),Events:i(808),Game:i(810),GameObjects:i(903),Geom:i(423),Input:i(1191),Loader:i(1225),Math:i(165),Physics:i(1386),Plugins:i(1294),Renderer:i(1423),Scale:i(1296),ScaleModes:i(229),Scene:i(369),Scenes:i(1297),Structs:i(1299),Textures:i(1300),Tilemaps:i(1302),Time:i(1346),Tweens:i(1348),Utils:i(1365)};r.Sound=i(1375),r=s(!1,r,n),t.exports=r,e.Phaser=r}).call(this,i(512))},function(t,e,i){t.exports={Arcade:i(1251),Matter:i(1387)}},function(t,e,i){t.exports={BodyBounds:i(1376),Factory:i(1377),Image:i(1379),Matter:i(1288),MatterPhysics:i(1419),PolyDecomp:i(1378),Sprite:i(1380),TileBody:i(1287),PhysicsEditorParser:i(1284),PhysicsJSONParser:i(1285),World:i(1384)}},function(t,e,i){var n=i(509),s=i(2),r=i(3);t.exports=function(t,e,i,o){void 0===i&&(i={}),void 0===o&&(o=!0);var a=e.x,h=e.y;if(e.body={temp:!0,position:{x:a,y:h}},[n.Bounce,n.Collision,n.Force,n.Friction,n.Gravity,n.Mass,n.Sensor,n.SetBody,n.Sleep,n.Static,n.Transform,n.Velocity].forEach(function(t){for(var i in t)(n=t[i]).get&&"function"==typeof n.get||n.set&&"function"==typeof n.set?Object.defineProperty(e,i,{get:t[i].get,set:t[i].set}):Object.defineProperty(e,i,{value:t[i]});var n}),e.world=t,e._tempVec2=new r(a,h),i.hasOwnProperty("type")&&"body"===i.type)e.setExistingBody(i,o);else{var l=s(i,"shape",null);l||(l="rectangle"),i.addToWorld=o,e.setBody(l,i)}return e}},function(t,e){t.exports={setBounce:function(t){return this.body.restitution=t,this}}},function(t,e){var i={setCollisionCategory:function(t){return this.body.collisionFilter.category=t,this},setCollisionGroup:function(t){return this.body.collisionFilter.group=t,this},setCollidesWith:function(t){var e=0;if(Array.isArray(t))for(var i=0;i1?1:0;s0},intersectPoint:function(t,e,i){i=this.getMatterBodies(i);var n=D.create(t,e),s=[];return M.point(i,n).forEach(function(t){-1===s.indexOf(t)&&s.push(t)}),s},intersectRect:function(t,e,i,n,s,r){void 0===s&&(s=!1),r=this.getMatterBodies(r);var o={min:{x:t,y:e},max:{x:t+i,y:e+n}},a=[];return M.region(r,o,s).forEach(function(t){-1===a.indexOf(t)&&a.push(t)}),a},intersectRay:function(t,e,i,n,s,r){void 0===s&&(s=1),r=this.getMatterBodies(r);for(var o=[],a=M.ray(r,D.create(t,e),D.create(i,n),s),h=0;h0)for(var a=s+1;ae.max.x?i=e.min.x-t.max.x:t.max.xe.max.y?n=e.min.y-t.max.y:t.max.y0&&(i=1/Math.sqrt(i),this.x=t*i,this.y=e*i),this},normalizeRightHand:function(){var t=this.x;return this.x=-1*this.y,this.y=t,this},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this},transformMat3:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this},transformMat4:function(t){var e=this.x,i=this.y,n=t.val;return this.x=n[0]*e+n[4]*i+n[12],this.y=n[1]*e+n[5]*i+n[13],this},reset:function(){return this.x=0,this.y=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0),n.LEFT=new n(-1,0),n.UP=new n(0,-1),n.DOWN=new n(0,1),n.ONE=new n(1,1),t.exports=n},function(t,e,i){var n=i(0),s=i(46),r=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=t),this.type=s.POINT,this.x=t,this.y=e},setTo:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.x=t,this.y=e,this}});t.exports=r},function(t,e,i){var n=i(0),s=i(23),r=i(19),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},existing:function(t){return(t.renderCanvas||t.renderWebGL)&&this.displayList.add(t),t.preUpdate&&this.updateList.add(t),t},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectFactory",o,"add"),t.exports=o},function(t,e){t.exports=function(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=i,o=0;o>>0},getTintAppendFloatAlpha:function(t,e){return((255&(255*e|0))<<24|t)>>>0},getTintAppendFloatAlphaAndSwap:function(t,e){return((255&(255*e|0))<<24|(255&(0|t))<<16|(255&(t>>8|0))<<8|255&(t>>16|0))>>>0},getFloatsFromUintRGB:function(t){return[(255&(t>>16|0))/255,(255&(t>>8|0))/255,(255&(0|t))/255]},getComponentCount:function(t,e){for(var i=0,n=0;n=this.right?this.width=0:this.width=this.right-t,this.x=t}},right:{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}},top:{get:function(){return this.y},set:function(t){t>=this.bottom?this.height=0:this.height=this.bottom-t,this.y=t}},bottom:{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}},centerX:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},centerY:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=u},function(t,e,i){t.exports={Alpha:i(527),AlphaSingle:i(266),Animation:i(498),BlendMode:i(269),ComputedSize:i(546),Crop:i(547),Depth:i(270),Flip:i(548),GetBounds:i(549),Mask:i(274),Origin:i(566),PathFollower:i(567),Pipeline:i(153),ScrollFactor:i(277),Size:i(568),Texture:i(569),TextureCrop:i(570),Tint:i(571),ToJSON:i(278),Transform:i(279),TransformMatrix:i(32),Visible:i(280)}},function(t,e){var i={PI2:2*Math.PI,TAU:.5*Math.PI,EPSILON:1e-6,DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,RND:null,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER||-9007199254740991,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991};t.exports=i},function(t,e,i){var n=i(0),s=i(278),r=i(113),o=i(9),a=i(90),h=new n({Extends:o,initialize:function(t,e){o.call(this),this.scene=t,this.type=e,this.state=0,this.parentContainer=null,this.name="",this.active=!0,this.tabIndex=-1,this.data=null,this.renderFlags=15,this.cameraFilter=0,this.input=null,this.body=null,this.ignoreDestroy=!1,t.sys.queueDepthSort()},setActive:function(t){return this.active=t,this},setName:function(t){return this.name=t,this},setState:function(t){return this.state=t,this},setDataEnabled:function(){return this.data||(this.data=new r(this)),this},setData:function(t,e){return this.data||(this.data=new r(this)),this.data.set(t,e),this},getData:function(t){return this.data||(this.data=new r(this)),this.data.get(t)},setInteractive:function(t,e,i){return this.scene.sys.input.enable(this,t,e,i),this},disableInteractive:function(){return this.input&&(this.input.enabled=!1),this},removeInteractive:function(){return this.scene.sys.input.clear(this),this.input=void 0,this},update:function(){},toJSON:function(){return s(this)},willRender:function(t){return!(h.RENDER_MASK!==this.renderFlags||0!==this.cameraFilter&&this.cameraFilter&t.id)},getIndexList:function(){for(var t=this,e=this.parentContainer,i=[];e&&(i.unshift(e.getIndex(t)),t=e,e.parentContainer);)e=e.parentContainer;return i.unshift(this.scene.sys.displayList.getIndex(t)),i},destroy:function(t){if(void 0===t&&(t=!1),this.scene&&!this.ignoreDestroy){this.preDestroy&&this.preDestroy.call(this),this.emit(a.DESTROY,this);var e=this.scene.sys;t||(e.displayList.remove(this),e.updateList.remove(this)),this.input&&(e.input.clear(this),this.input=void 0),this.data&&(this.data.destroy(),this.data=void 0),this.body&&(this.body.destroy(),this.body=void 0),t||e.queueDepthSort(),this.active=!1,this.visible=!1,this.scene=void 0,this.parentContainer=void 0,this.removeAllListeners()}}});h.RENDER_MASK=15,t.exports=h},function(t,e,i){var n=i(168),s=i(6);t.exports=function(t,e,i){var r=s(t,e,null);if(null===r)return i;if(Array.isArray(r))return n.RND.pick(r);if("object"==typeof r){if(r.hasOwnProperty("randInt"))return n.RND.integerInRange(r.randInt[0],r.randInt[1]);if(r.hasOwnProperty("randFloat"))return n.RND.realInRange(r.randFloat[0],r.randFloat[1])}else if("function"==typeof r)return r(e);return r}},function(t,e,i){var n=i(0),s=i(23),r=i(19),o=new n({initialize:function(t){this.scene=t,this.systems=t.sys,this.displayList,this.updateList,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.start,this)},boot:function(){this.displayList=this.systems.displayList,this.updateList=this.systems.updateList,this.systems.events.once(r.DESTROY,this.destroy,this)},start:function(){this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},shutdown:function(){this.systems.events.off(r.SHUTDOWN,this.shutdown,this)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.displayList=null,this.updateList=null}});o.register=function(t,e){o.prototype.hasOwnProperty(t)||(o.prototype[t]=e)},o.remove=function(t){o.prototype.hasOwnProperty(t)&&delete o.prototype[t]},s.register("GameObjectCreator",o,"make"),t.exports=o},function(t,e,i){var n=i(7),s=function(){var t,e,i,r,o,a,h=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof h&&(c=h,h=arguments[1]||{},l=2),u===l&&(h=this,--l);l=400&&t.status<=599&&(n=!1),this.resetXHR(),this.loader.nextFile(this,n)},onError:function(){this.resetXHR(),this.loader.nextFile(this,!1)},onProgress:function(t){t.lengthComputable&&(this.bytesLoaded=t.loaded,this.bytesTotal=t.total,this.percentComplete=Math.min(this.bytesLoaded/this.bytesTotal,1),this.loader.emit(r.FILE_PROGRESS,this,this.percentComplete))},onProcess:function(){this.state=s.FILE_PROCESSING,this.onProcessComplete()},onProcessComplete:function(){this.state=s.FILE_COMPLETE,this.multiFile&&this.multiFile.onFileComplete(this),this.loader.fileProcessComplete(this)},onProcessError:function(){this.state=s.FILE_ERRORED,this.multiFile&&this.multiFile.onFileFailed(this),this.loader.fileProcessComplete(this)},hasCacheConflict:function(){return this.cache&&this.cache.exists(this.key)},addToCache:function(){this.cache&&this.cache.add(this.key,this.data),this.pendingDestroy()},pendingDestroy:function(t){void 0===t&&(t=this.data);var e=this.key,i=this.type;this.loader.emit(r.FILE_COMPLETE,e,i,t),this.loader.emit(r.FILE_KEY_COMPLETE+i+"-"+e,e,i,t),this.loader.flagForRemoval(this)},destroy:function(){this.loader=null,this.cache=null,this.xhrSettings=null,this.multiFile=null,this.linkFile=null,this.data=null}});c.createObjectURL=function(t,e,i){if("function"==typeof URL)t.src=URL.createObjectURL(e);else{var n=new FileReader;n.onload=function(){t.removeAttribute("crossOrigin"),t.src="data:"+(e.type||i)+";base64,"+n.result.split(",")[1]},n.onerror=t.onerror,n.readAsDataURL(e)}},c.revokeObjectURL=function(t){"function"==typeof URL&&URL.revokeObjectURL(t.src)},t.exports=c},function(t,e){t.exports=function(t,e,i){return Math.max(e,Math.min(i,t))}},function(t,e){var i={},n={},s={register:function(t,e,n,s){void 0===s&&(s=!1),i[t]={plugin:e,mapping:n,custom:s}},registerCustom:function(t,e,i,s){n[t]={plugin:e,mapping:i,data:s}},hasCore:function(t){return i.hasOwnProperty(t)},hasCustom:function(t){return n.hasOwnProperty(t)},getCore:function(t){return i[t]},getCustom:function(t){return n[t]},getCustomClass:function(t){return n.hasOwnProperty(t)?n[t].plugin:null},remove:function(t){i.hasOwnProperty(t)&&delete i[t]},removeCustom:function(t){n.hasOwnProperty(t)&&delete n[t]},destroyCorePlugins:function(){for(var t in i)i.hasOwnProperty(t)&&delete i[t]},destroyCustomPlugins:function(){for(var t in n)n.hasOwnProperty(t)&&delete n[t]}};t.exports=s},function(t,e,i){var n=i(2);t.exports=function(t,e,i,s,r,o){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=o.width),void 0===s&&(s=o.height);var a=n(r,"isNotEmpty",!1),h=n(r,"isColliding",!1),l=n(r,"hasInterestingFace",!1);t<0&&(i+=t,t=0),e<0&&(s+=e,e=0),t+i>o.width&&(i=Math.max(o.width-t,0)),e+s>o.height&&(s=Math.max(o.height-e,0));for(var u=[],c=e;c=0;o--)t[o][e]=i+a*n,a++;return t}},function(t,e,i){var n,s,r,o=i(29),a=i(164),h=[],l=!1;t.exports={create2D:function(t,e,i){return n(t,e,i,o.CANVAS)},create:n=function(t,e,i,n,r){var u;void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=o.CANVAS),void 0===r&&(r=!1);var c=s(n);return null===c?(c={parent:t,canvas:document.createElement("canvas"),type:n},n===o.CANVAS&&h.push(c),u=c.canvas):(c.parent=t,u=c.canvas),r&&(c.parent=u),u.width=e,u.height=i,l&&n===o.CANVAS&&a.disable(u.getContext("2d")),u},createWebGL:function(t,e,i){return n(t,e,i,o.WEBGL)},disableSmoothing:function(){l=!0},enableSmoothing:function(){l=!1},first:s=function(t){if(void 0===t&&(t=o.CANVAS),t===o.WEBGL)return null;for(var e=0;e0?Math.acos(e/this.scaleX):-Math.acos(e/this.scaleX):n||r?s.TAU-(r>0?Math.acos(-n/this.scaleY):-Math.acos(n/this.scaleY)):0}},scaleX:{get:function(){return Math.sqrt(this.a*this.a+this.b*this.b)}},scaleY:{get:function(){return Math.sqrt(this.c*this.c+this.d*this.d)}},loadIdentity:function(){var t=this.matrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,this},translate:function(t,e){var i=this.matrix;return i[4]=i[0]*t+i[2]*e+i[4],i[5]=i[1]*t+i[3]*e+i[5],this},scale:function(t,e){var i=this.matrix;return i[0]*=t,i[1]*=t,i[2]*=e,i[3]*=e,this},rotate:function(t){var e=Math.sin(t),i=Math.cos(t),n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3];return n[0]=s*i+o*e,n[1]=r*i+a*e,n[2]=s*-e+o*i,n[3]=r*-e+a*i,this},multiply:function(t,e){var i=this.matrix,n=t.matrix,s=i[0],r=i[1],o=i[2],a=i[3],h=i[4],l=i[5],u=n[0],c=n[1],d=n[2],f=n[3],p=n[4],g=n[5],v=void 0===e?this:e;return v.a=u*s+c*o,v.b=u*r+c*a,v.c=d*s+f*o,v.d=d*r+f*a,v.e=p*s+g*o+h,v.f=p*r+g*a+l,v},multiplyWithOffset:function(t,e,i){var n=this.matrix,s=t.matrix,r=n[0],o=n[1],a=n[2],h=n[3],l=e*r+i*a+n[4],u=e*o+i*h+n[5],c=s[0],d=s[1],f=s[2],p=s[3],g=s[4],v=s[5];return n[0]=c*r+d*a,n[1]=c*o+d*h,n[2]=f*r+p*a,n[3]=f*o+p*h,n[4]=g*r+v*a+l,n[5]=g*o+v*h+u,this},transform:function(t,e,i,n,s,r){var o=this.matrix,a=o[0],h=o[1],l=o[2],u=o[3],c=o[4],d=o[5];return o[0]=t*a+e*l,o[1]=t*h+e*u,o[2]=i*a+n*l,o[3]=i*h+n*u,o[4]=s*a+r*l+c,o[5]=s*h+r*u+d,this},transformPoint:function(t,e,i){void 0===i&&(i={x:0,y:0});var n=this.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5];return i.x=t*s+e*o+h,i.y=t*r+e*a+l,i},invert:function(){var t=this.matrix,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=e*s-i*n;return t[0]=s/a,t[1]=-i/a,t[2]=-n/a,t[3]=e/a,t[4]=(n*o-s*r)/a,t[5]=-(e*o-i*r)/a,this},copyFrom:function(t){var e=this.matrix;return e[0]=t.a,e[1]=t.b,e[2]=t.c,e[3]=t.d,e[4]=t.e,e[5]=t.f,this},copyFromArray:function(t){var e=this.matrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],this},copyToContext:function(t){var e=this.matrix;return t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t},setToContext:function(t){var e=this.matrix;return t.setTransform(e[0],e[1],e[2],e[3],e[4],e[5]),t},copyToArray:function(t){var e=this.matrix;return void 0===t?t=[e[0],e[1],e[2],e[3],e[4],e[5]]:(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]),t},setTransform:function(t,e,i,n,s,r){var o=this.matrix;return o[0]=t,o[1]=e,o[2]=i,o[3]=n,o[4]=s,o[5]=r,this},decomposeMatrix:function(){var t=this.decomposedMatrix,e=this.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(t.translateX=e[4],t.translateY=e[5],i||n){var a=Math.sqrt(i*i+n*n);t.rotation=n>0?Math.acos(i/a):-Math.acos(i/a),t.scaleX=a,t.scaleY=o/a}else if(s||r){var h=Math.sqrt(s*s+r*r);t.rotation=.5*Math.PI-(r>0?Math.acos(-s/h):-Math.acos(s/h)),t.scaleX=o/h,t.scaleY=h}else t.rotation=0,t.scaleX=0,t.scaleY=0;return t},applyITRS:function(t,e,i,n,s){var r=this.matrix,o=Math.sin(i),a=Math.cos(i);return r[4]=t,r[5]=e,r[0]=a*n,r[1]=o*n,r[2]=-o*s,r[3]=a*s,this},applyInverse:function(t,e,i){void 0===i&&(i=new r);var n=this.matrix,s=n[0],o=n[1],a=n[2],h=n[3],l=n[4],u=n[5],c=1/(s*h+a*-o);return i.x=h*c*t+-a*c*e+(u*a-l*h)*c,i.y=s*c*e+-o*c*t+(-u*s+l*o)*c,i},getX:function(t,e){return t*this.a+e*this.c+this.e},getY:function(t,e){return t*this.b+e*this.d+this.f},getCSSMatrix:function(){var t=this.matrix;return"matrix("+t[0]+","+t[1]+","+t[2]+","+t[3]+","+t[4]+","+t[5]+")"},destroy:function(){this.matrix=null,this.decomposedMatrix=null}});t.exports=o},function(t,e,i){var n=i(0),s=i(162),r=i(292),o=i(163),a=i(293),h=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=255),this.r=0,this.g=0,this.b=0,this.a=255,this._h=0,this._s=0,this._v=0,this._locked=!1,this.gl=[0,0,0,1],this._color=0,this._color32=0,this._rgba="",this.setTo(t,e,i,n)},transparent:function(){return this._locked=!0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this._locked=!1,this.update(!0)},setTo:function(t,e,i,n,s){return void 0===n&&(n=255),void 0===s&&(s=!0),this._locked=!0,this.red=t,this.green=e,this.blue=i,this.alpha=n,this._locked=!1,this.update(s)},setGLTo:function(t,e,i,n){return void 0===n&&(n=1),this._locked=!0,this.redGL=t,this.greenGL=e,this.blueGL=i,this.alphaGL=n,this._locked=!1,this.update(!0)},setFromRGB:function(t){return this._locked=!0,this.red=t.r,this.green=t.g,this.blue=t.b,t.hasOwnProperty("a")&&(this.alpha=t.a),this._locked=!1,this.update(!0)},setFromHSV:function(t,e,i){return o(t,e,i,this)},update:function(t){if(void 0===t&&(t=!1),this._locked)return this;var e=this.r,i=this.g,n=this.b,o=this.a;return this._color=s(e,i,n),this._color32=r(e,i,n,o),this._rgba="rgba("+e+","+i+","+n+","+o/255+")",t&&a(e,i,n,this),this},updateHSV:function(){var t=this.r,e=this.g,i=this.b;return a(t,e,i,this),this},clone:function(){return new h(this.r,this.g,this.b,this.a)},gray:function(t){return this.setTo(t,t,t)},random:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t)),n=Math.floor(t+Math.random()*(e-t)),s=Math.floor(t+Math.random()*(e-t));return this.setTo(i,n,s)},randomGray:function(t,e){void 0===t&&(t=0),void 0===e&&(e=255);var i=Math.floor(t+Math.random()*(e-t));return this.setTo(i,i,i)},saturate:function(t){return this.s+=t/100,this},desaturate:function(t){return this.s-=t/100,this},lighten:function(t){return this.v+=t/100,this},darken:function(t){return this.v-=t/100,this},brighten:function(t){var e=this.r,i=this.g,n=this.b;return e=Math.max(0,Math.min(255,e-Math.round(-t/100*255))),i=Math.max(0,Math.min(255,i-Math.round(-t/100*255))),n=Math.max(0,Math.min(255,n-Math.round(-t/100*255))),this.setTo(e,i,n)},color:{get:function(){return this._color}},color32:{get:function(){return this._color32}},rgba:{get:function(){return this._rgba}},redGL:{get:function(){return this.gl[0]},set:function(t){this.gl[0]=Math.min(Math.abs(t),1),this.r=Math.floor(255*this.gl[0]),this.update(!0)}},greenGL:{get:function(){return this.gl[1]},set:function(t){this.gl[1]=Math.min(Math.abs(t),1),this.g=Math.floor(255*this.gl[1]),this.update(!0)}},blueGL:{get:function(){return this.gl[2]},set:function(t){this.gl[2]=Math.min(Math.abs(t),1),this.b=Math.floor(255*this.gl[2]),this.update(!0)}},alphaGL:{get:function(){return this.gl[3]},set:function(t){this.gl[3]=Math.min(Math.abs(t),1),this.a=Math.floor(255*this.gl[3]),this.update()}},red:{get:function(){return this.r},set:function(t){t=Math.floor(Math.abs(t)),this.r=Math.min(t,255),this.gl[0]=t/255,this.update(!0)}},green:{get:function(){return this.g},set:function(t){t=Math.floor(Math.abs(t)),this.g=Math.min(t,255),this.gl[1]=t/255,this.update(!0)}},blue:{get:function(){return this.b},set:function(t){t=Math.floor(Math.abs(t)),this.b=Math.min(t,255),this.gl[2]=t/255,this.update(!0)}},alpha:{get:function(){return this.a},set:function(t){t=Math.floor(Math.abs(t)),this.a=Math.min(t,255),this.gl[3]=t/255,this.update()}},h:{get:function(){return this._h},set:function(t){this._h=t,o(t,this._s,this._v,this)}},s:{get:function(){return this._s},set:function(t){this._s=t,o(this._h,t,this._v,this)}},v:{get:function(){return this._v},set:function(t){this._v=t,o(this._h,this._s,t,this)}}});t.exports=h},function(t,e){t.exports=function(t,e,i,n,s,r){var o;void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=1);var a=0,h=t.length;if(1===r)for(o=s;o=0;o--)t[o][e]+=i+a*n,a++;return t}},function(t,e,i){var n=i(13);t.exports=function(t){return t*n.DEG_TO_RAD}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.fillColor,r=n||e.fillAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.fillStyle="rgba("+o+","+a+","+h+","+r+")"}},function(t,e){var i={};t.exports=i,function(){i._nextId=0,i._seed=0,i._nowStartTime=+new Date,i.extend=function(t,e){var n,s;"boolean"==typeof e?(n=2,s=e):(n=1,s=!0);for(var r=n;r0;e--){var n=Math.floor(i.random()*(e+1)),s=t[e];t[e]=t[n],t[n]=s}return t},i.choose=function(t){return t[Math.floor(i.random()*t.length)]},i.isElement=function(t){return"undefined"!=typeof HTMLElement?t instanceof HTMLElement:!!(t&&t.nodeType&&t.nodeName)},i.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},i.isFunction=function(t){return"function"==typeof t},i.isPlainObject=function(t){return"object"==typeof t&&t.constructor===Object},i.isString=function(t){return"[object String]"===toString.call(t)},i.clamp=function(t,e,i){return ti?i:t},i.sign=function(t){return t<0?-1:1},i.now=function(){if("undefined"!=typeof window&&window.performance){if(window.performance.now)return window.performance.now();if(window.performance.webkitNow)return window.performance.webkitNow()}return new Date-i._nowStartTime},i.random=function(e,i){return e=void 0!==e?e:0,i=void 0!==i?i:1,e+t()*(i-e)};var t=function(){return i._seed=(9301*i._seed+49297)%233280,i._seed/233280};i.colorToNumber=function(t){return 3==(t=t.replace("#","")).length&&(t=t.charAt(0)+t.charAt(0)+t.charAt(1)+t.charAt(1)+t.charAt(2)+t.charAt(2)),parseInt(t,16)},i.logLevel=1,i.log=function(){console&&i.logLevel>0&&i.logLevel<=3&&console.log.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.info=function(){console&&i.logLevel>0&&i.logLevel<=2&&console.info.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.warn=function(){console&&i.logLevel>0&&i.logLevel<=3&&console.warn.apply(console,["matter-js:"].concat(Array.prototype.slice.call(arguments)))},i.nextId=function(){return i._nextId++},i.indexOf=function(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0;i=e&&t.y<=i&&t.y+t.height>=i}},function(t,e,i){t.exports={DESTROY:i(641),FADE_IN_COMPLETE:i(642),FADE_IN_START:i(643),FADE_OUT_COMPLETE:i(644),FADE_OUT_START:i(645),FLASH_COMPLETE:i(646),FLASH_START:i(647),PAN_COMPLETE:i(648),PAN_START:i(649),POST_RENDER:i(650),PRE_RENDER:i(651),SHAKE_COMPLETE:i(652),SHAKE_START:i(653),ZOOM_COMPLETE:i(654),ZOOM_START:i(655)}},function(t,e){t.exports=function(t,e,i,n){var s=i||e.strokeColor,r=n||e.strokeAlpha,o=(16711680&s)>>>16,a=(65280&s)>>>8,h=255&s;t.strokeStyle="rgba("+o+","+a+","+h+","+r+")",t.lineWidth=e.lineWidth}},function(t,e){t.exports={DYNAMIC_BODY:0,STATIC_BODY:1,GROUP:2,TILEMAPLAYER:3,FACING_NONE:10,FACING_UP:11,FACING_DOWN:12,FACING_LEFT:13,FACING_RIGHT:14}},function(t,e,i){var n=i(138),s=i(24);t.exports=function(t,e,i,r,o){for(var a=null,h=null,l=null,u=null,c=s(t,e,i,r,null,o),d=0;d0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}},function(t,e,i){var n=i(0),s=i(272),r=i(150),o=i(46),a=i(151),h=i(3),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=o.LINE,this.x1=t,this.y1=e,this.x2=i,this.y2=n},getPoint:function(t,e){return s(this,t,e)},getPoints:function(t,e,i){return r(this,t,e,i)},getRandomPoint:function(t){return a(this,t)},setTo:function(t,e,i,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x1=t,this.y1=e,this.x2=i,this.y2=n,this},getPointA:function(t){return void 0===t&&(t=new h),t.set(this.x1,this.y1),t},getPointB:function(t){return void 0===t&&(t=new h),t.set(this.x2,this.y2),t},left:{get:function(){return Math.min(this.x1,this.x2)},set:function(t){this.x1<=this.x2?this.x1=t:this.x2=t}},right:{get:function(){return Math.max(this.x1,this.x2)},set:function(t){this.x1>this.x2?this.x1=t:this.x2=t}},top:{get:function(){return Math.min(this.y1,this.y2)},set:function(t){this.y1<=this.y2?this.y1=t:this.y2=t}},bottom:{get:function(){return Math.max(this.y1,this.y2)},set:function(t){this.y1>this.y2?this.y1=t:this.y2=t}}});t.exports=l},function(t,e){t.exports=function(t){return Math.sqrt((t.x2-t.x1)*(t.x2-t.x1)+(t.y2-t.y1)*(t.y2-t.y1))}},function(t,e){t.exports=function(t,e,i){var n=i-e;return e+((t-e)%n+n)%n}},function(t,e,i){t.exports={COMPLETE:i(882),DECODED:i(883),DECODED_ALL:i(884),DESTROY:i(885),DETUNE:i(886),GLOBAL_DETUNE:i(887),GLOBAL_MUTE:i(888),GLOBAL_RATE:i(889),GLOBAL_VOLUME:i(890),LOOP:i(891),LOOPED:i(892),MUTE:i(893),PAUSE_ALL:i(894),PAUSE:i(895),PLAY:i(896),RATE:i(897),RESUME_ALL:i(898),RESUME:i(899),SEEK:i(900),STOP_ALL:i(901),STOP:i(902),UNLOCKED:i(903),VOLUME:i(904)}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(6),l=i(7),u=new n({Extends:r,initialize:function(t,e,i,n,o){var u="json";if(l(e)){var c=e;e=a(c,"key"),i=a(c,"url"),n=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"dataKey",o)}var d={type:"json",cache:t.cacheManager.json,extension:u,responseType:"text",key:e,url:i,xhrSettings:n,config:o};r.call(this,t,d),l(i)&&(this.data=o?h(i,o):i,this.state=s.FILE_POPULATED)},onProcess:function(){if(this.state!==s.FILE_POPULATED){this.state=s.FILE_PROCESSING;var t=JSON.parse(this.xhrLoader.responseText),e=this.config;this.data="string"==typeof e?h(t,e,t):t}this.onProcessComplete()}});o.register("json",function(t,e,i,n){if(Array.isArray(t))for(var s=0;s0&&r.rotateAbout(o.position,i,t.position,o.position)}},n.setVelocity=function(t,e){t.positionPrev.x=t.position.x-e.x,t.positionPrev.y=t.position.y-e.y,t.velocity.x=e.x,t.velocity.y=e.y,t.speed=r.magnitude(t.velocity)},n.setAngularVelocity=function(t,e){t.anglePrev=t.angle-e,t.angularVelocity=e,t.angularSpeed=Math.abs(t.angularVelocity)},n.translate=function(t,e){n.setPosition(t,r.add(t.position,e))},n.rotate=function(t,e,i){if(i){var s=Math.cos(e),r=Math.sin(e),o=t.position.x-i.x,a=t.position.y-i.y;n.setPosition(t,{x:i.x+(o*s-a*r),y:i.y+(o*r+a*s)}),n.setAngle(t,t.angle+e)}else n.setAngle(t,t.angle+e)},n.scale=function(t,e,i,r){var o=0,a=0;r=r||t.position;for(var u=0;u0&&(o+=c.area,a+=c.inertia),c.position.x=r.x+(c.position.x-r.x)*e,c.position.y=r.y+(c.position.y-r.y)*i,h.update(c.bounds,c.vertices,t.velocity)}t.parts.length>1&&(t.area=o,t.isStatic||(n.setMass(t,t.density*o),n.setInertia(t,a))),t.circleRadius&&(e===i?t.circleRadius*=e:t.circleRadius=null)},n.update=function(t,e,i,n){var o=Math.pow(e*i*t.timeScale,2),a=1-t.frictionAir*i*t.timeScale,u=t.position.x-t.positionPrev.x,c=t.position.y-t.positionPrev.y;t.velocity.x=u*a*n+t.force.x/t.mass*o,t.velocity.y=c*a*n+t.force.y/t.mass*o,t.positionPrev.x=t.position.x,t.positionPrev.y=t.position.y,t.position.x+=t.velocity.x,t.position.y+=t.velocity.y,t.angularVelocity=(t.angle-t.anglePrev)*a*n+t.torque/t.inertia*o,t.anglePrev=t.angle,t.angle+=t.angularVelocity,t.speed=r.magnitude(t.velocity),t.angularSpeed=Math.abs(t.angularVelocity);for(var d=0;d0&&(f.position.x+=t.velocity.x,f.position.y+=t.velocity.y),0!==t.angularVelocity&&(s.rotate(f.vertices,t.angularVelocity,t.position),l.rotate(f.axes,t.angularVelocity),d>0&&r.rotateAbout(f.position,t.angularVelocity,t.position,f.position)),h.update(f.bounds,f.vertices,t.velocity)}},n.applyForce=function(t,e,i){t.force.x+=i.x,t.force.y+=i.y;var n=e.x-t.position.x,s=e.y-t.position.y;t.torque+=n*i.y-s*i.x},n._totalProperties=function(t){for(var e={mass:0,area:0,inertia:0,centre:{x:0,y:0}},i=1===t.parts.length?0:1;i80*i){n=h=t[0],a=l=t[1];for(var T=i;Th&&(h=u),f>l&&(l=f);g=0!==(g=Math.max(h-n,l-a))?1/g:0}return o(y,x,i,n,a,g),x}function s(t,e,i,n,s){var r,o;if(s===A(t,e,i,n)>0)for(r=e;r=e;r-=n)o=b(r,t[r],t[r+1],o);return o&&y(o,o.next)&&(E(o),o=o.next),o}function r(t,e){if(!t)return t;e||(e=t);var i,n=t;do{if(i=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(E(n),(n=e=n.prev)===n.next)break;i=!0}}while(i||n!==e);return e}function o(t,e,i,n,s,c,d){if(t){!d&&c&&function(t,e,i,n){var s=t;do{null===s.z&&(s.z=f(s.x,s.y,e,i,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,n,s,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,n=i,a=0,e=0;e0||h>0&&n;)0!==a&&(0===h||!n||i.z<=n.z)?(s=i,i=i.nextZ,a--):(s=n,n=n.nextZ,h--),r?r.nextZ=s:t=s,s.prevZ=r,r=s;i=n}r.nextZ=null,l*=2}while(o>1)}(s)}(t,n,s,c);for(var p,g,v=t;t.prev!==t.next;)if(p=t.prev,g=t.next,c?h(t,n,s,c):a(t))e.push(p.i/i),e.push(t.i/i),e.push(g.i/i),E(t),t=g.next,v=g.next;else if((t=g)===v){d?1===d?o(t=l(t,e,i),e,i,n,s,c,2):2===d&&u(t,e,i,n,s,c):o(r(t),e,i,n,s,c,1);break}}}function a(t){var e=t.prev,i=t,n=t.next;if(m(e,i,n)>=0)return!1;for(var s=t.next.next;s!==t.prev;){if(g(e.x,e.y,i.x,i.y,n.x,n.y,s.x,s.y)&&m(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function h(t,e,i,n){var s=t.prev,r=t,o=t.next;if(m(s,r,o)>=0)return!1;for(var a=s.xr.x?s.x>o.x?s.x:o.x:r.x>o.x?r.x:o.x,u=s.y>r.y?s.y>o.y?s.y:o.y:r.y>o.y?r.y:o.y,c=f(a,h,e,i,n),d=f(l,u,e,i,n),p=t.prevZ,v=t.nextZ;p&&p.z>=c&&v&&v.z<=d;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,p.x,p.y)&&m(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;v&&v.z<=d;){if(v!==t.prev&&v!==t.next&&g(s.x,s.y,r.x,r.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function l(t,e,i){var n=t;do{var s=n.prev,r=n.next.next;!y(s,r)&&x(s,n,n.next,r)&&T(s,r)&&T(r,s)&&(e.push(s.i/i),e.push(n.i/i),e.push(r.i/i),E(n),E(n.next),n=t=r),n=n.next}while(n!==t);return n}function u(t,e,i,n,s,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&v(h,l)){var u=w(h,l);return h=r(h,h.next),u=r(u,u.next),o(h,e,i,n,s,a),void o(u,e,i,n,s,a)}l=l.next}h=h.next}while(h!==t)}function c(t,e){return t.x-e.x}function d(t,e){if(e=function(t,e){var i,n=e,s=t.x,r=t.y,o=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){var a=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=s&&a>o){if(o=a,a===s){if(r===n.y)return n;if(r===n.next.y)return n.next}i=n.x=n.x&&n.x>=u&&s!==n.x&&g(ri.x)&&T(n,t)&&(i=n,d=h),n=n.next;return i}(t,e)){var i=w(e,t);r(i,i.next)}}function f(t,e,i,n,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*s)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*s)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function p(t){var e=t,i=t;do{e.x=0&&(t-o)*(n-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(s-o)*(n-a)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&x(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&T(t,e)&&T(e,t)&&function(t,e){var i=t,n=!1,s=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&i.next.y!==i.y&&s<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,i,n){return!!(y(t,e)&&y(i,n)||y(t,n)&&y(i,e))||m(t,e,i)>0!=m(t,e,n)>0&&m(i,n,t)>0!=m(i,n,e)>0}function T(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function w(t,e){var i=new S(t.i,t.x,t.y),n=new S(e.i,e.x,e.y),s=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,n.next=i,i.prev=n,r.next=n,n.prev=r,n}function b(t,e,i,n){var s=new S(t,e,i);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function E(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function S(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,i,n){for(var s=0,r=e,o=i-n;r0&&(n+=t[s-1].length,i.holes.push(n))}return i}},function(t,e){t.exports=function(t){var e={};for(var i in t)Array.isArray(t[i])?e[i]=t[i].slice(0):e[i]=t[i];return e}},function(t,e){t.exports=function(t,e,i,n){var s=t.length;if(e<0||e>s||e>=i||i>s||e+i>s){if(n)throw new Error("Range Error: Values outside acceptable range");return!1}return!0}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(960),a=new n({Extends:r,Mixins:[s.Alpha,s.BlendMode,s.Depth,s.Flip,s.GetBounds,s.Mask,s.Origin,s.Pipeline,s.ScrollFactor,s.Size,s.TextureCrop,s.Tint,s.Transform,s.Visible,o],initialize:function(t,e,i,n,o){r.call(this,t,"Sprite"),this._crop=this.resetCropObject(),this.anims=new s.Animation(this),this.setTexture(n,o),this.setPosition(e,i),this.setSizeToFrame(),this.setOriginFromFrame(),this.initPipeline()},preUpdate:function(t,e){this.anims.update(t,e)},play:function(t,e,i){return this.anims.play(t,e,i),this},toJSON:function(){return s.ToJSON(this)},preDestroy:function(){this.anims.destroy(),this.anims=void 0}});t.exports=a},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){var o=t.strokeTint,a=n.getTintAppendFloatAlphaAndSwap(e.strokeColor,e.strokeAlpha*i);o.TL=a,o.TR=a,o.BL=a,o.BR=a;var h=e.pathData,l=h.length-1,u=e.lineWidth,c=u/2,d=h[0]-s,f=h[1]-r;e.closePath||(l-=2);for(var p=2;p=this.x2&&this.x1>=this.x3?this.x1-t:this.x2>=this.x1&&this.x2>=this.x3?this.x2-t:this.x3-t,this.x1-=e,this.x2-=e,this.x3-=e}},top:{get:function(){return Math.min(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1<=this.y2&&this.y1<=this.y3?this.y1-t:this.y2<=this.y1&&this.y2<=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}},bottom:{get:function(){return Math.max(this.y1,this.y2,this.y3)},set:function(t){var e=0;e=this.y1>=this.y2&&this.y1>=this.y3?this.y1-t:this.y2>=this.y1&&this.y2>=this.y3?this.y2-t:this.y3-t,this.y1-=e,this.y2-=e,this.y3-=e}}});t.exports=u},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=new n({Extends:r,initialize:function t(e,i,n,s,o){var l,u="png";if(h(i)){var c=i;i=a(c,"key"),n=a(c,"url"),l=a(c,"normalMap"),s=a(c,"xhrSettings"),u=a(c,"extension",u),o=a(c,"frameConfig")}Array.isArray(n)&&(l=n[1],n=n[0]);var d={type:"image",cache:e.textureManager,extension:u,responseType:"blob",key:i,url:n,xhrSettings:s,config:o};if(r.call(this,e,d),l){var f=new t(e,this.key,l,s,o);f.type="normalMap",this.setLink(f),e.addFile(f)}},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=new Image,this.data.crossOrigin=this.crossOrigin;var t=this;this.data.onload=function(){r.revokeObjectURL(t.data),t.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(t.data),t.onProcessError()},r.createObjectURL(this.data,this.xhrLoader.response,"image/png")},addToCache:function(){var t,e=this.linkFile;e&&e.state===s.FILE_COMPLETE?(t="image"===this.type?this.cache.addImage(this.key,this.data,e.data):this.cache.addImage(e.key,e.data,this.data),this.pendingDestroy(t),e.pendingDestroy(t)):e||(t=this.cache.addImage(this.key,this.data),this.pendingDestroy(t))}});o.register("image",function(t,e,i){if(Array.isArray(t))for(var n=0;nthis.right||e>this.bottom)},copy:function(t){return this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.visible=t.visible,this.setFlip(t.flipX,t.flipY),this.tint=t.tint,this.rotation=t.rotation,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext,this},getCollisionGroup:function(){return this.tileset?this.tileset.getTileCollisionGroup(this.index):null},getTileData:function(){return this.tileset?this.tileset.getTileData(this.index):null},getLeft:function(t){var e=this.tilemapLayer;return e?e.tileToWorldX(this.x,t):this.x*this.baseWidth},getRight:function(t){var e=this.tilemapLayer;return e?this.getLeft(t)+this.width*e.scaleX:this.getLeft(t)+this.width},getTop:function(t){var e=this.tilemapLayer;return e?e.tileToWorldY(this.y,t)-(this.height-this.baseHeight)*e.scaleY:this.y*this.baseHeight-(this.height-this.baseHeight)},getBottom:function(t){var e=this.tilemapLayer;return e?this.getTop(t)+this.height*e.scaleY:this.getTop(t)+this.height},getBounds:function(t,e){return void 0===e&&(e=new r),e.x=this.getLeft(),e.y=this.getTop(),e.width=this.getRight()-e.x,e.height=this.getBottom()-e.y,e},getCenterX:function(t){return(this.getLeft(t)+this.getRight(t))/2},getCenterY:function(t){return(this.getTop(t)+this.getBottom(t))/2},destroy:function(){this.collisionCallback=void 0,this.collisionCallbackContext=void 0,this.properties=void 0},intersects:function(t,e,i,n){return!(i<=this.pixelX||n<=this.pixelY||t>=this.right||e>=this.bottom)},isInteresting:function(t,e){return t&&e?this.canCollide||this.hasInterestingFace:t?this.collides:!!e&&this.hasInterestingFace},resetCollision:function(t){(void 0===t&&(t=!0),this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,t)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},resetFaces:function(){return this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this},setCollision:function(t,e,i,n,s){(void 0===e&&(e=t),void 0===i&&(i=t),void 0===n&&(n=t),void 0===s&&(s=!0),this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=n,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=n,s)&&(this.tilemapLayer&&this.tilemapLayer.calculateFacesAt(this.x,this.y));return this},setCollisionCallback:function(t,e){return null===t?(this.collisionCallback=void 0,this.collisionCallbackContext=void 0):(this.collisionCallback=t,this.collisionCallbackContext=e),this},setSize:function(t,e,i,n){return void 0!==t&&(this.width=t),void 0!==e&&(this.height=e),void 0!==i&&(this.baseWidth=i),void 0!==n&&(this.baseHeight=n),this.updatePixelXY(),this},updatePixelXY:function(){return this.pixelX=this.x*this.baseWidth,this.pixelY=this.y*this.baseHeight,this},canCollide:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}},collides:{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}},hasInterestingFace:{get:function(){return this.faceTop||this.faceBottom||this.faceLeft||this.faceRight}},tileset:{get:function(){var t=this.layer.tilemapLayer;if(t){var e=t.gidMap[this.index];if(e)return e}return null}},tilemapLayer:{get:function(){return this.layer.tilemapLayer}},tilemap:{get:function(){var t=this.tilemapLayer;return t?t.tilemap:null}}});t.exports=o},function(t,e){t.exports=function(t){return t.x-t.width*t.originX+.5*t.width}},function(t,e){t.exports=function(t,e){var i=t.width*t.originX;return t.x=e+i-.5*t.width,t}},function(t,e){t.exports=function(t){return t.y-t.height*t.originY+.5*t.height}},function(t,e){t.exports=function(t,e){var i=t.height*t.originY;return t.y=e+i-.5*t.height,t}},function(t,e){t.exports=function(t,e){if(!(e>=t.length)){for(var i=t.length-1,n=t[e],s=e;si&&(e=i/2);var n=Math.max(1,Math.round(i/e));return s(this.getSpacedPoints(n),t)},getDistancePoints:function(t){var e=this.getLength(),i=Math.max(1,e/t);return this.getSpacedPoints(i)},getEndPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(1,t)},getLength:function(){var t=this.getLengths();return t[t.length-1]},getLengths:function(t){if(void 0===t&&(t=this.arcLengthDivisions),this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var e,i=[],n=this.getPoint(0,this._tmpVec2A),s=0;i.push(0);for(var r=1;r<=t;r++)s+=(e=this.getPoint(r/t,this._tmpVec2B)).distance(n),i.push(s),n.copy(e);return this.cacheArcLengths=i,i},getPointAt:function(t,e){var i=this.getUtoTmapping(t);return this.getPoint(i,e)},getPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++)i.push(this.getPoint(n/t));return i},getRandomPoint:function(t){return void 0===t&&(t=new o),this.getPoint(Math.random(),t)},getSpacedPoints:function(t,e,i){void 0===i&&(i=[]),t||(t=e?this.getLength()/e:this.defaultDivisions);for(var n=0;n<=t;n++){var s=this.getUtoTmapping(n/t,null,t);i.push(this.getPoint(s))}return i},getStartPoint:function(t){return void 0===t&&(t=new o),this.getPointAt(0,t)},getTangent:function(t,e){void 0===e&&(e=new o);var i=t-1e-4,n=t+1e-4;return i<0&&(i=0),n>1&&(n=1),this.getPoint(i,this._tmpVec2A),this.getPoint(n,e),e.subtract(this._tmpVec2A).normalize()},getTangentAt:function(t,e){var i=this.getUtoTmapping(t);return this.getTangent(i,e)},getTFromDistance:function(t,e){return t<=0?0:this.getUtoTmapping(0,t,e)},getUtoTmapping:function(t,e,i){var n,s=this.getLengths(i),r=0,o=s.length;n=e?Math.min(e,s[o-1]):t*s[o-1];for(var a,h=0,l=o-1;h<=l;)if((a=s[r=Math.floor(h+(l-h)/2)]-n)<0)h=r+1;else{if(!(a>0)){l=r;break}l=r-1}if(s[r=l]===n)return r/(o-1);var u=s[r];return(r+(n-u)/(s[r+1]-u))/(o-1)},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths()}});t.exports=a},function(t,e,i){t.exports={ADD:i(861),COMPLETE:i(862),FILE_COMPLETE:i(863),FILE_KEY_COMPLETE:i(864),FILE_LOAD_ERROR:i(865),FILE_LOAD:i(866),FILE_PROGRESS:i(867),POST_PROCESS:i(868),PROGRESS:i(869),START:i(870)}},function(t,e,i){var n=i(166),s=i(179);t.exports=function(t,e){var i=n.Power0;if("string"==typeof t)if(n.hasOwnProperty(t))i=n[t];else{var r="";t.indexOf(".")&&("in"===(r=t.substr(t.indexOf(".")+1)).toLowerCase()?r="easeIn":"out"===r.toLowerCase()?r="easeOut":"inout"===r.toLowerCase()&&(r="easeInOut")),t=s(t.substr(0,t.indexOf(".")+1)+r),n.hasOwnProperty(t)&&(i=n[t])}else"function"==typeof t?i=t:Array.isArray(t)&&t.length;if(!e)return i;var o=e.slice(0);return o.unshift(0),function(t){return o[0]=t,i.apply(this,o)}}},function(t,e){t.exports=function(t,e,i){var n=t.x3-t.x1,s=t.y3-t.y1,r=t.x2-t.x1,o=t.y2-t.y1,a=e-t.x1,h=i-t.y1,l=n*n+s*s,u=n*r+s*o,c=n*a+s*h,d=r*r+o*o,f=r*a+o*h,p=l*d-u*u,g=0===p?0:1/p,v=(d*c-u*f)*g,m=(l*f-u*c)*g;return v>=0&&m>=0&&v+m<1}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.x1,r=t.y1,o=t.x2,a=t.y2,h=e.x1,l=e.y1,u=e.x2,c=e.y2,d=(u-h)*(r-l)-(c-l)*(s-h),f=(o-s)*(r-l)-(a-r)*(s-h),p=(c-l)*(o-s)-(u-h)*(a-r);if(0===p)return!1;var g=d/p,v=f/p;return g>=0&&g<=1&&v>=0&&v<=1&&(i.x=s+g*(o-s),i.y=r+g*(a-r),!0)}},function(t,e){t.exports=function(t){return Math.atan2(t.y2-t.y1,t.x2-t.x1)}},function(t,e,i){var n={};t.exports=n;var s=i(101),r=i(37);n.create=function(t,e){for(var i=[],n=0;n0)return!1}return!0},n.scale=function(t,e,i,r){if(1===e&&1===i)return t;var o,a;r=r||n.centre(t);for(var h=0;h=0?h-1:t.length-1],u=t[h],c=t[(h+1)%t.length],d=e[h0&&(r|=2),3===r)return!1;return 0!==r||null},n.hull=function(t){var e,i,n=[],r=[];for((t=t.slice(0)).sort(function(t,e){var i=t.x-e.x;return 0!==i?i:t.y-e.y}),i=0;i=2&&s.cross3(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}for(i=t.length-1;i>=0;i-=1){for(e=t[i];n.length>=2&&s.cross3(n[n.length-2],n[n.length-1],e)<=0;)n.pop();n.push(e)}return n.pop(),r.pop(),n.concat(r)}},function(t,e,i){var n=i(22);t.exports=function(t,e,i){return(i-e)*(t=n(t,0,1))}},function(t,e){t.exports=function(t,e,i){return t&&t.hasOwnProperty(e)?t[e]:i}},function(t,e){t.exports={CREATED:0,INIT:1,DELAY:2,OFFSET_DELAY:3,PENDING_RENDER:4,PLAYING_FORWARD:5,PLAYING_BACKWARD:6,HOLD_DELAY:7,REPEAT_DELAY:8,COMPLETE:9,PENDING_ADD:20,PAUSED:21,LOOP_DELAY:22,ACTIVE:23,COMPLETE_DELAY:24,PENDING_REMOVE:25,REMOVED:26}},function(t,e,i){t.exports={DESTROY:i(576),VIDEO_COMPLETE:i(577),VIDEO_CREATED:i(578),VIDEO_ERROR:i(579),VIDEO_LOOP:i(580),VIDEO_PLAY:i(581),VIDEO_SEEKED:i(582),VIDEO_SEEKING:i(583),VIDEO_STOP:i(584),VIDEO_TIMEOUT:i(585),VIDEO_UNLOCKED:i(586)}},function(t,e,i){var n=i(0),s=i(12),r=i(35),o=i(9),a=i(48),h=i(11),l=i(32),u=i(161),c=i(3),d=new n({Extends:o,Mixins:[s.Alpha,s.Visible],initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),o.call(this),this.scene,this.sceneManager,this.scaleManager,this.cameraManager,this.id=0,this.name="",this.resolution=1,this.roundPixels=!1,this.useBounds=!1,this.worldView=new h,this.dirty=!0,this._x=t,this._y=e,this._cx=0,this._cy=0,this._cw=0,this._ch=0,this._width=i,this._height=n,this._bounds=new h,this._scrollX=0,this._scrollY=0,this._zoom=1,this._rotation=0,this.matrix=new l,this.transparent=!0,this.backgroundColor=u("rgba(0,0,0,0)"),this.disableCull=!1,this.culledObjects=[],this.midPoint=new c(i/2,n/2),this.originX=.5,this.originY=.5,this._customViewport=!1,this.mask=null,this._maskCamera=null},setOrigin:function(t,e){return void 0===t&&(t=.5),void 0===e&&(e=t),this.originX=t,this.originY=e,this},getScroll:function(t,e,i){void 0===i&&(i=new c);var n=.5*this.width,s=.5*this.height;return i.x=t-n,i.y=e-s,this.useBounds&&(i.x=this.clampX(i.x),i.y=this.clampY(i.y)),i},centerOnX:function(t){var e=.5*this.width;return this.midPoint.x=t,this.scrollX=t-e,this.useBounds&&(this.scrollX=this.clampX(this.scrollX)),this},centerOnY:function(t){var e=.5*this.height;return this.midPoint.y=t,this.scrollY=t-e,this.useBounds&&(this.scrollY=this.clampY(this.scrollY)),this},centerOn:function(t,e){return this.centerOnX(t),this.centerOnY(e),this},centerToBounds:function(){if(this.useBounds){var t=this._bounds,e=.5*this.width,i=.5*this.height;this.midPoint.set(t.centerX,t.centerY),this.scrollX=t.centerX-e,this.scrollY=t.centerY-i}return this},centerToSize:function(){return this.scrollX=.5*this.width,this.scrollY=.5*this.height,this},cull:function(t){if(this.disableCull)return t;var e=this.matrix.matrix,i=e[0],n=e[1],s=e[2],r=e[3],o=i*r-n*s;if(!o)return t;var a=e[4],h=e[5],l=this.scrollX,u=this.scrollY,c=this.width,d=this.height,f=this.culledObjects,p=t.length;o=1/o,f.length=0;for(var g=0;gC&&wA&&b<_&&f.push(v)}else f.push(v)}return f},getWorldPoint:function(t,e,i){void 0===i&&(i=new c);var n=this.matrix.matrix,s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5],u=s*a-r*o;if(!u)return i.x=t,i.y=e,i;var d=a*(u=1/u),f=-r*u,p=-o*u,g=s*u,v=(o*l-a*h)*u,m=(r*h-s*l)*u,y=Math.cos(this.rotation),x=Math.sin(this.rotation),T=this.zoom,w=this.resolution,b=this.scrollX,E=this.scrollY,S=t+(b*y-E*x)*T,A=e+(b*x+E*y)*T;return i.x=(S*d+A*p)*w+v,i.y=(S*f+A*g)*w+m,i},ignore:function(t){var e=this.id;Array.isArray(t)||(t=[t]);for(var i=0;is&&(t=s),t},clampY:function(t){var e=this._bounds,i=this.displayHeight,n=e.y+(i-this.height)/2,s=Math.max(n,n+e.height-i);return ts&&(t=s),t},removeBounds:function(){return this.useBounds=!1,this.dirty=!0,this._bounds.setEmpty(),this},setAngle:function(t){return void 0===t&&(t=0),this.rotation=r(t),this},setBackgroundColor:function(t){return void 0===t&&(t="rgba(0,0,0,0)"),this.backgroundColor=u(t),this.transparent=0===this.backgroundColor.alpha,this},setBounds:function(t,e,i,n,s){return void 0===s&&(s=!1),this._bounds.setTo(t,e,i,n),this.dirty=!0,this.useBounds=!0,s?this.centerToBounds():(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},getBounds:function(t){void 0===t&&(t=new h);var e=this._bounds;return t.setTo(e.x,e.y,e.width,e.height),t},setName:function(t){return void 0===t&&(t=""),this.name=t,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setRotation:function(t){return void 0===t&&(t=0),this.rotation=t,this},setRoundPixels:function(t){return this.roundPixels=t,this},setScene:function(t){this.scene&&this._customViewport&&this.sceneManager.customViewports--,this.scene=t;var e=t.sys;this.sceneManager=e.game.scene,this.scaleManager=e.scale,this.cameraManager=e.cameras;var i=this.scaleManager.resolution;return this.resolution=i,this._cx=this._x*i,this._cy=this._y*i,this._cw=this._width*i,this._ch=this._height*i,this.updateSystem(),this},setScroll:function(t,e){return void 0===e&&(e=t),this.scrollX=t,this.scrollY=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},setViewport:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setZoom:function(t){return void 0===t&&(t=1),0===t&&(t=.001),this.zoom=t,this},setMask:function(t,e){return void 0===e&&(e=!0),this.mask=t,this._maskCamera=e?this.cameraManager.default:this,this},clearMask:function(t){return void 0===t&&(t=!1),t&&this.mask&&this.mask.destroy(),this.mask=null,this},toJSON:function(){var t={name:this.name,x:this.x,y:this.y,width:this.width,height:this.height,zoom:this.zoom,rotation:this.rotation,roundPixels:this.roundPixels,scrollX:this.scrollX,scrollY:this.scrollY,backgroundColor:this.backgroundColor.rgba};return this.useBounds&&(t.bounds={x:this._bounds.x,y:this._bounds.y,width:this._bounds.width,height:this._bounds.height}),t},update:function(){},updateSystem:function(){if(this.scaleManager){var t=0!==this._x||0!==this._y||this.scaleManager.width!==this._width||this.scaleManager.height!==this._height,e=this.sceneManager;t&&!this._customViewport?e.customViewports++:!t&&this._customViewport&&e.customViewports--,this.dirty=!0,this._customViewport=t}},destroy:function(){this.emit(a.DESTROY,this),this.removeAllListeners(),this.matrix.destroy(),this.culledObjects=[],this._customViewport&&this.sceneManager.customViewports--,this._bounds=null,this.scene=null,this.scaleManager=null,this.sceneManager=null,this.cameraManager=null},x:{get:function(){return this._x},set:function(t){this._x=t,this._cx=t*this.resolution,this.updateSystem()}},y:{get:function(){return this._y},set:function(t){this._y=t,this._cy=t*this.resolution,this.updateSystem()}},width:{get:function(){return this._width},set:function(t){this._width=t,this._cw=t*this.resolution,this.updateSystem()}},height:{get:function(){return this._height},set:function(t){this._height=t,this._ch=t*this.resolution,this.updateSystem()}},scrollX:{get:function(){return this._scrollX},set:function(t){this._scrollX=t,this.dirty=!0}},scrollY:{get:function(){return this._scrollY},set:function(t){this._scrollY=t,this.dirty=!0}},zoom:{get:function(){return this._zoom},set:function(t){this._zoom=t,this.dirty=!0}},rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this.dirty=!0}},centerX:{get:function(){return this.x+.5*this.width}},centerY:{get:function(){return this.y+.5*this.height}},displayWidth:{get:function(){return this.width/this.zoom}},displayHeight:{get:function(){return this.height/this.zoom}}});t.exports=d},function(t,e,i){t.exports={ENTER_FULLSCREEN:i(694),FULLSCREEN_FAILED:i(695),FULLSCREEN_UNSUPPORTED:i(696),LEAVE_FULLSCREEN:i(697),ORIENTATION_CHANGE:i(698),RESIZE:i(699)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=i(0),s=i(22),r=i(17),o=new n({initialize:function(t,e,i,n,s,r,o){this.texture=t,this.name=e,this.source=t.source[i],this.sourceIndex=i,this.glTexture=this.source.glTexture,this.cutX,this.cutY,this.cutWidth,this.cutHeight,this.x=0,this.y=0,this.width,this.height,this.halfWidth,this.halfHeight,this.centerX,this.centerY,this.pivotX=0,this.pivotY=0,this.customPivot=!1,this.rotated=!1,this.autoRound=-1,this.customData={},this.u0=0,this.v0=0,this.u1=0,this.v1=0,this.data={cut:{x:0,y:0,w:0,h:0,r:0,b:0},trim:!1,sourceSize:{w:0,h:0},spriteSourceSize:{x:0,y:0,w:0,h:0,r:0,b:0},radius:0,drawImage:{x:0,y:0,width:0,height:0}},this.setSize(r,o,n,s)},setSize:function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this.cutX=i,this.cutY=n,this.cutWidth=t,this.cutHeight=e,this.width=t,this.height=e,this.halfWidth=Math.floor(.5*t),this.halfHeight=Math.floor(.5*e),this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2);var s=this.data,r=s.cut;r.x=i,r.y=n,r.w=t,r.h=e,r.r=i+t,r.b=n+e,s.sourceSize.w=t,s.sourceSize.h=e,s.spriteSourceSize.w=t,s.spriteSourceSize.h=e,s.radius=.5*Math.sqrt(t*t+e*e);var o=s.drawImage;return o.x=i,o.y=n,o.width=t,o.height=e,this.updateUVs()},setTrim:function(t,e,i,n,s,r){var o=this.data,a=o.spriteSourceSize;return o.trim=!0,o.sourceSize.w=t,o.sourceSize.h=e,a.x=i,a.y=n,a.w=s,a.h=r,a.r=i+s,a.b=n+r,this.x=i,this.y=n,this.width=s,this.height=r,this.halfWidth=.5*s,this.halfHeight=.5*r,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.updateUVs()},setCropUVs:function(t,e,i,n,r,o,a){var h=this.cutX,l=this.cutY,u=this.cutWidth,c=this.cutHeight,d=this.realWidth,f=this.realHeight,p=h+(e=s(e,0,d)),g=l+(i=s(i,0,f)),v=n=s(n,0,d-e),m=r=s(r,0,f-i),y=this.data;if(y.trim){var x=y.spriteSourceSize,T=e+(n=s(n,0,u-e)),w=i+(r=s(r,0,c-i));if(!(x.rT||x.y>w)){var b=Math.max(x.x,e),E=Math.max(x.y,i),S=Math.min(x.r,T)-b,A=Math.min(x.b,w)-E;v=S,m=A,p=o?h+(u-(b-x.x)-S):h+(b-x.x),g=a?l+(c-(E-x.y)-A):l+(E-x.y),e=b,i=E,n=S,r=A}else p=0,g=0,v=0,m=0}else o&&(p=h+(u-e-n)),a&&(g=l+(c-i-r));var _=this.source.width,C=this.source.height;return t.u0=Math.max(0,p/_),t.v0=Math.max(0,g/C),t.u1=Math.min(1,(p+v)/_),t.v1=Math.min(1,(g+m)/C),t.x=e,t.y=i,t.cx=p,t.cy=g,t.cw=v,t.ch=m,t.width=n,t.height=r,t.flipX=o,t.flipY=a,t},updateCropUVs:function(t,e,i){return this.setCropUVs(t,t.x,t.y,t.width,t.height,e,i)},updateUVs:function(){var t=this.cutX,e=this.cutY,i=this.cutWidth,n=this.cutHeight,s=this.data.drawImage;s.width=i,s.height=n;var r=this.source.width,o=this.source.height;return this.u0=t/r,this.v0=e/o,this.u1=(t+i)/r,this.v1=(e+n)/o,this},updateUVsInverted:function(){var t=this.source.width,e=this.source.height;return this.u0=(this.cutX+this.cutHeight)/t,this.v0=this.cutY/e,this.u1=this.cutX/t,this.v1=(this.cutY+this.cutWidth)/e,this},clone:function(){var t=new o(this.texture,this.name,this.sourceIndex);return t.cutX=this.cutX,t.cutY=this.cutY,t.cutWidth=this.cutWidth,t.cutHeight=this.cutHeight,t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t.halfWidth=this.halfWidth,t.halfHeight=this.halfHeight,t.centerX=this.centerX,t.centerY=this.centerY,t.rotated=this.rotated,t.data=r(!0,t.data,this.data),t.updateUVs(),t},destroy:function(){this.source=null,this.texture=null,this.glTexture=null,this.customData=null,this.data=null},realWidth:{get:function(){return this.data.sourceSize.w}},realHeight:{get:function(){return this.data.sourceSize.h}},radius:{get:function(){return this.data.radius}},trimmed:{get:function(){return this.data.trim}},canvasData:{get:function(){return this.data.drawImage}}});t.exports=o},function(t,e,i){var n=i(0),s=i(96),r=i(390),o=i(391),a=i(46),h=i(154),l=new n({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.type=a.ELLIPSE,this.x=t,this.y=e,this.width=i,this.height=n},contains:function(t,e){return s(this,t,e)},getPoint:function(t,e){return r(this,t,e)},getPoints:function(t,e,i){return o(this,t,e,i)},getRandomPoint:function(t){return h(this,t)},setTo:function(t,e,i,n){return this.x=t,this.y=e,this.width=i,this.height=n,this},setEmpty:function(){return this.width=0,this.height=0,this},setPosition:function(t,e){return void 0===e&&(e=t),this.x=t,this.y=e,this},setSize:function(t,e){return void 0===e&&(e=t),this.width=t,this.height=e,this},isEmpty:function(){return this.width<=0||this.height<=0},getMinorRadius:function(){return Math.min(this.width,this.height)/2},getMajorRadius:function(){return Math.max(this.width,this.height)/2},left:{get:function(){return this.x-this.width/2},set:function(t){this.x=t+this.width/2}},right:{get:function(){return this.x+this.width/2},set:function(t){this.x=t-this.width/2}},top:{get:function(){return this.y-this.height/2},set:function(t){this.y=t+this.height/2}},bottom:{get:function(){return this.y+this.height/2},set:function(t){this.y=t-this.height/2}}});t.exports=l},function(t,e){t.exports=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var n=(e-t.x)/t.width,s=(i-t.y)/t.height;return(n*=n)+(s*=s)<.25}},function(t,e,i){var n=i(238),s=i(0),r=i(90),o=i(2),a=i(6),h=i(7),l=i(384),u=i(108),c=i(69),d=new s({initialize:function(t,e,i){i?e&&!Array.isArray(e)&&(e=[e]):Array.isArray(e)?h(e[0])&&(i=e,e=null):h(e)&&(i=e,e=null),this.scene=t,this.children=new u(e),this.isParent=!0,this.type="Group",this.classType=o(i,"classType",c),this.name=o(i,"name",""),this.active=o(i,"active",!0),this.maxSize=o(i,"maxSize",-1),this.defaultKey=o(i,"defaultKey",null),this.defaultFrame=o(i,"defaultFrame",null),this.runChildUpdate=o(i,"runChildUpdate",!1),this.createCallback=o(i,"createCallback",null),this.removeCallback=o(i,"removeCallback",null),this.createMultipleCallback=o(i,"createMultipleCallback",null),this.internalCreateCallback=o(i,"internalCreateCallback",null),this.internalRemoveCallback=o(i,"internalRemoveCallback",null),i&&this.createMultiple(i)},create:function(t,e,i,n,s,r){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.defaultKey),void 0===n&&(n=this.defaultFrame),void 0===s&&(s=!0),void 0===r&&(r=!0),this.isFull())return null;var o=new this.classType(this.scene,t,e,i,n);return this.scene.sys.displayList.add(o),o.preUpdate&&this.scene.sys.updateList.add(o),o.visible=s,o.setActive(r),this.add(o),o},createMultiple:function(t){if(this.isFull())return[];Array.isArray(t)||(t=[t]);var e=[];if(t[0].key)for(var i=0;i=0;u--)if((l=d[u]).active===i){if(++c===e)break}else l=null;return l?("number"==typeof s&&(l.x=s),"number"==typeof r&&(l.y=r),l):n?this.create(s,r,o,a,h):null},get:function(t,e,i,n,s){return this.getFirst(!1,!0,t,e,i,n,s)},getFirstAlive:function(t,e,i,n,s,r){return this.getFirst(!0,t,e,i,n,s,r)},getFirstDead:function(t,e,i,n,s,r){return this.getFirst(!1,t,e,i,n,s,r)},playAnimation:function(t,e){return n.PlayAnimation(this.children.entries,t,e),this},isFull:function(){return-1!==this.maxSize&&this.children.size>=this.maxSize},countActive:function(t){void 0===t&&(t=!0);for(var e=0,i=0;it.max.x&&(t.max.x=s.x),s.xt.max.y&&(t.max.y=s.y),s.y0?t.max.x+=i.x:t.min.x+=i.x,i.y>0?t.max.y+=i.y:t.min.y+=i.y)},i.contains=function(t,e){return e.x>=t.min.x&&e.x<=t.max.x&&e.y>=t.min.y&&e.y<=t.max.y},i.overlaps=function(t,e){return t.min.x<=e.max.x&&t.max.x>=e.min.x&&t.max.y>=e.min.y&&t.min.y<=e.max.y},i.translate=function(t,e){t.min.x+=e.x,t.max.x+=e.x,t.min.y+=e.y,t.max.y+=e.y},i.shift=function(t,e){var i=t.max.x-t.min.x,n=t.max.y-t.min.y;t.min.x=e.x,t.max.x=e.x+i,t.min.y=e.y,t.max.y=e.y+n}},function(t,e){t.exports=function(t,e,i){return t>=0&&t=0&&e-1&&this.entries.splice(e,1),this},dump:function(){console.group("Set");for(var t=0;t-1},union:function(t){var e=new n;return t.entries.forEach(function(t){e.set(t)}),this.entries.forEach(function(t){e.set(t)}),e},intersect:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)&&e.set(i)}),e},difference:function(t){var e=new n;return this.entries.forEach(function(i){t.contains(i)||e.set(i)}),e},size:{get:function(){return this.entries.length},set:function(t){return t0&&s.area(T)1?(d=o.create(r.extend({parts:f.slice(0)},a)),o.setPosition(d,{x:t,y:e}),d):f[0]},n.flagCoincidentParts=function(t,e){void 0===e&&(e=5);for(var i=0;i0;e--){var i=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[i],t[i]=n}return t}},function(t,e){t.exports=function(t,e,i){return(e-t)*i+t}},function(t,e,i){(function(e){var i={android:!1,chromeOS:!1,cordova:!1,crosswalk:!1,desktop:!1,ejecta:!1,electron:!1,iOS:!1,iOSVersion:0,iPad:!1,iPhone:!1,kindle:!1,linux:!1,macOS:!1,node:!1,nodeWebkit:!1,pixelRatio:1,webApp:!1,windows:!1,windowsPhone:!1};t.exports=function(){var t=navigator.userAgent;/Windows/.test(t)?i.windows=!0:/Mac OS/.test(t)&&!/like Mac OS/.test(t)?i.macOS=!0:/Android/.test(t)?i.android=!0:/Linux/.test(t)?i.linux=!0:/iP[ao]d|iPhone/i.test(t)?(i.iOS=!0,navigator.appVersion.match(/OS (\d+)/),i.iOSVersion=parseInt(RegExp.$1,10),i.iPhone=-1!==t.toLowerCase().indexOf("iphone"),i.iPad=-1!==t.toLowerCase().indexOf("ipad")):/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?i.kindle=!0:/CrOS/.test(t)&&(i.chromeOS=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(i.android=!1,i.iOS=!1,i.macOS=!1,i.windows=!0,i.windowsPhone=!0);var n=/Silk/.test(t);return(i.windows||i.macOS||i.linux&&!n||i.chromeOS)&&(i.desktop=!0),(i.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(i.desktop=!1),navigator.standalone&&(i.webApp=!0),void 0!==window.cordova&&(i.cordova=!0),void 0!==e&&e.versions&&e.versions.node&&(i.node=!0),i.node&&"object"==typeof e.versions&&(i.nodeWebkit=!!e.versions["node-webkit"],i.electron=!!e.versions.electron),void 0!==window.ejecta&&(i.ejecta=!0),/Crosswalk/.test(t)&&(i.crosswalk=!0),i.pixelRatio=window.devicePixelRatio||1,i}()}).call(this,i(720))},function(t,e,i){var n,s=i(116),r={chrome:!1,chromeVersion:0,edge:!1,firefox:!1,firefoxVersion:0,ie:!1,ieVersion:0,mobileSafari:!1,opera:!1,safari:!1,safariVersion:0,silk:!1,trident:!1,tridentVersion:0};t.exports=(n=navigator.userAgent,/Edge\/\d+/.test(n)?r.edge=!0:/Chrome\/(\d+)/.test(n)&&!s.windowsPhone?(r.chrome=!0,r.chromeVersion=parseInt(RegExp.$1,10)):/Firefox\D+(\d+)/.test(n)?(r.firefox=!0,r.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(n)&&s.iOS?r.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(n)?(r.ie=!0,r.ieVersion=parseInt(RegExp.$1,10)):/Opera/.test(n)?r.opera=!0:/Safari/.test(n)&&!s.windowsPhone?r.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(n)&&(r.ie=!0,r.trident=!0,r.tridentVersion=parseInt(RegExp.$1,10),r.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(n)&&(r.silk=!0),r)},function(t,e){t.exports=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)}},function(t,e,i){t.exports={ADD:i(771),ERROR:i(772),LOAD:i(773),READY:i(774),REMOVE:i(775)}},function(t,e){t.exports=function(t,e){var i;if(e)"string"==typeof e?i=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(i=e);else if(t.parentElement)return t;return i||(i=document.body),i.appendChild(t),t}},function(t,e,i){var n=i(79);t.exports=function(t,e,i,s){var r;if(void 0===s&&(s=t),!Array.isArray(e))return-1!==(r=t.indexOf(e))?(n(t,r),i&&i.call(s,e),e):null;for(var o=e.length-1;o>=0;){var a=e[o];-1!==(r=t.indexOf(a))?(n(t,r),i&&i.call(s,a)):e.pop(),o--}return e}},function(t,e){t.exports={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:42,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,NUMPAD_ZERO:96,NUMPAD_ONE:97,NUMPAD_TWO:98,NUMPAD_THREE:99,NUMPAD_FOUR:100,NUMPAD_FIVE:101,NUMPAD_SIX:102,NUMPAD_SEVEN:103,NUMPAD_EIGHT:104,NUMPAD_NINE:105,NUMPAD_ADD:107,NUMPAD_SUBTRACT:109,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,SEMICOLON:186,PLUS:187,COMMA:188,MINUS:189,PERIOD:190,FORWARD_SLASH:191,BACK_SLASH:220,QUOTES:222,BACKTICK:192,OPEN_BRACKET:219,CLOSED_BRACKET:221,SEMICOLON_FIREFOX:59,COLON:58,COMMA_FIREFOX_WINDOWS:60,COMMA_FIREFOX:62,BRACKET_RIGHT_FIREFOX:174,BRACKET_LEFT_FIREFOX:175}},function(t,e){t.exports={PENDING:0,INIT:1,START:2,LOADING:3,CREATING:4,RUNNING:5,PAUSED:6,SLEEPING:7,SHUTDOWN:8,DESTROYED:9}},function(t,e,i){var n=i(0),s=i(67),r=i(9),o=i(59),a=i(18),h=i(1),l=new n({Extends:r,initialize:function(t){r.call(this),this.game=t,this.jsonCache=t.cache.json,this.sounds=[],this.mute=!1,this.volume=1,this.pauseOnBlur=!0,this._rate=1,this._detune=0,this.locked=this.locked||!1,this.unlocked=!1,t.events.on(a.BLUR,function(){this.pauseOnBlur&&this.onBlur()},this),t.events.on(a.FOCUS,function(){this.pauseOnBlur&&this.onFocus()},this),t.events.on(a.PRE_STEP,this.update,this),t.events.once(a.DESTROY,this.destroy,this)},add:h,addAudioSprite:function(t,e){void 0===e&&(e={});var i=this.add(t,e);for(var n in i.spritemap=this.jsonCache.get(t).spritemap,i.spritemap)if(i.spritemap.hasOwnProperty(n)){var r=s(e),o=i.spritemap[n];r.loop=!!o.hasOwnProperty("loop")&&o.loop,i.addMarker({name:n,start:o.start,duration:o.end-o.start,config:r})}return i},play:function(t,e){var i=this.add(t);return i.once(o.COMPLETE,i.destroy,i),e?e.name?(i.addMarker(e),i.play(e.name)):i.play(e):i.play()},playAudioSprite:function(t,e,i){var n=this.addAudioSprite(t);return n.once(o.COMPLETE,n.destroy,n),n.play(e,i)},remove:function(t){var e=this.sounds.indexOf(t);return-1!==e&&(t.destroy(),this.sounds.splice(e,1),!0)},removeByKey:function(t){for(var e=0,i=this.sounds.length-1;i>=0;i--){var n=this.sounds[i];n.key===t&&(n.destroy(),this.sounds.splice(i,1),e++)}return e},pauseAll:function(){this.forEachActiveSound(function(t){t.pause()}),this.emit(o.PAUSE_ALL,this)},resumeAll:function(){this.forEachActiveSound(function(t){t.resume()}),this.emit(o.RESUME_ALL,this)},stopAll:function(){this.forEachActiveSound(function(t){t.stop()}),this.emit(o.STOP_ALL,this)},unlock:h,onBlur:h,onFocus:h,update:function(t,e){this.unlocked&&(this.unlocked=!1,this.locked=!1,this.emit(o.UNLOCKED,this));for(var i=this.sounds.length-1;i>=0;i--)this.sounds[i].pendingRemove&&this.sounds.splice(i,1);this.sounds.forEach(function(i){i.update(t,e)})},destroy:function(){this.removeAllListeners(),this.forEachActiveSound(function(t){t.destroy()}),this.sounds.length=0,this.sounds=null,this.game=null},forEachActiveSound:function(t,e){var i=this;this.sounds.forEach(function(n,s){n&&!n.pendingRemove&&t.call(e||i,n,s,i.sounds)})},setRate:function(t){return this.rate=t,this},rate:{get:function(){return this._rate},set:function(t){this._rate=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_RATE,this,t)}},setDetune:function(t){return this.detune=t,this},detune:{get:function(){return this._detune},set:function(t){this._detune=t,this.forEachActiveSound(function(t){t.calculateRate()}),this.emit(o.GLOBAL_DETUNE,this,t)}}});t.exports=l},function(t,e,i){var n=i(0),s=i(9),r=i(59),o=i(17),a=i(1),h=new n({Extends:s,initialize:function(t,e,i){s.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=this.duration||0,this.totalDuration=this.totalDuration||0,this.config={mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},this.currentConfig=this.config,this.config=o(this.config,i),this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(console.error("addMarker "+t.name+" already exists in Sound"),!1):(t=o(!0,{name:"",start:0,duration:this.totalDuration-(t.start||0),config:{mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0}},t),this.markers[t.name]=t,!0))},updateMarker:function(t){return!(!t||!t.name||"string"!=typeof t.name)&&(this.markers[t.name]?(this.markers[t.name]=o(!0,this.markers[t.name],t),!0):(console.warn("Audio Marker: "+t.name+" missing in Sound: "+this.key),!1))},removeMarker:function(t){var e=this.markers[t];return e?(this.markers[t]=null,e):null},play:function(t,e){if(void 0===t&&(t=""),"object"==typeof t&&(e=t,t=""),"string"!=typeof t)return!1;if(t){if(!this.markers[t])return console.warn("Marker: "+t+" missing in Sound: "+this.key),!1;this.currentMarker=this.markers[t],this.currentConfig=this.currentMarker.config,this.duration=this.currentMarker.duration}else this.currentMarker=null,this.currentConfig=this.config,this.duration=this.totalDuration;return this.resetConfig(),this.currentConfig=o(this.currentConfig,e),this.isPlaying=!0,this.isPaused=!1,!0},pause:function(){return!(this.isPaused||!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!0,!0)},resume:function(){return!(!this.isPaused||this.isPlaying)&&(this.isPlaying=!0,this.isPaused=!1,!0)},stop:function(){return!(!this.isPaused&&!this.isPlaying)&&(this.isPlaying=!1,this.isPaused=!1,this.resetConfig(),!0)},applyConfig:function(){this.mute=this.currentConfig.mute,this.volume=this.currentConfig.volume,this.rate=this.currentConfig.rate,this.detune=this.currentConfig.detune,this.loop=this.currentConfig.loop},resetConfig:function(){this.currentConfig.seek=0,this.currentConfig.delay=0},update:a,calculateRate:function(){var t=this.currentConfig.detune+this.manager.detune,e=Math.pow(1.0005777895065548,t);this.totalRate=this.currentConfig.rate*this.manager.rate*e},destroy:function(){this.pendingRemove||(this.emit(r.DESTROY,this),this.pendingRemove=!0,this.manager=null,this.key="",this.removeAllListeners(),this.isPlaying=!1,this.isPaused=!1,this.config=null,this.currentConfig=null,this.markers=null,this.currentMarker=null)}});t.exports=h},function(t,e,i){var n=i(181),s=i(0),r=i(1),o=i(128),a=new s({initialize:function(t){this.parent=t,this.list=[],this.position=0,this.addCallback=r,this.removeCallback=r,this._sortKey=""},add:function(t,e){return e?n.Add(this.list,t):n.Add(this.list,t,0,this.addCallback,this)},addAt:function(t,e,i){return i?n.AddAt(this.list,t,e):n.AddAt(this.list,t,e,0,this.addCallback,this)},getAt:function(t){return this.list[t]},getIndex:function(t){return this.list.indexOf(t)},sort:function(t,e){return t?(void 0===e&&(e=function(e,i){return e[t]-i[t]}),o.inplace(this.list,e),this):this},getByName:function(t){return n.GetFirst(this.list,"name",t)},getRandom:function(t,e){return n.GetRandom(this.list,t,e)},getFirst:function(t,e,i,s){return n.GetFirst(this.list,t,e,i,s)},getAll:function(t,e,i,s){return n.GetAll(this.list,t,e,i,s)},count:function(t,e){return n.CountAllMatching(this.list,t,e)},swap:function(t,e){n.Swap(this.list,t,e)},moveTo:function(t,e){return n.MoveTo(this.list,t,e)},remove:function(t,e){return e?n.Remove(this.list,t):n.Remove(this.list,t,this.removeCallback,this)},removeAt:function(t,e){return e?n.RemoveAt(this.list,t):n.RemoveAt(this.list,t,this.removeCallback,this)},removeBetween:function(t,e,i){return i?n.RemoveBetween(this.list,t,e):n.RemoveBetween(this.list,t,e,this.removeCallback,this)},removeAll:function(t){for(var e=this.list.length;e--;)this.remove(this.list[e],t);return this},bringToTop:function(t){return n.BringToTop(this.list,t)},sendToBack:function(t){return n.SendToBack(this.list,t)},moveUp:function(t){return n.MoveUp(this.list,t),t},moveDown:function(t){return n.MoveDown(this.list,t),t},reverse:function(){return this.list.reverse(),this},shuffle:function(){return n.Shuffle(this.list),this},replace:function(t,e){return n.Replace(this.list,t,e)},exists:function(t){return this.list.indexOf(t)>-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){for(var i=[null],n=2;n0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}}});t.exports=a},function(t,e,i){var n=i(182),s=i(382);t.exports=function(t,e){if(void 0===e&&(e=90),!n(t))return null;if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)(t=s(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t.reverse(),t=s(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;il&&(r=l),o>l&&(o=l),a=s,h=r;;)if(a0&&o.length0&&a.lengthe.right||t.y>e.bottom)}},function(t,e,i){var n=i(6),s={},r={register:function(t,e,i,n,r){s[t]={plugin:e,mapping:i,settingsKey:n,configKey:r}},getPlugin:function(t){return s[t]},install:function(t){var e=t.scene.sys,i=e.settings.input,r=e.game.config;for(var o in s){var a=s[o].plugin,h=s[o].mapping,l=s[o].settingsKey,u=s[o].configKey;n(i,l,r[u])&&(t[h]=new a(t))}},remove:function(t){s.hasOwnProperty(t)&&delete s[t]}};t.exports=r},function(t,e,i){t.exports={ANY_KEY_DOWN:i(1203),ANY_KEY_UP:i(1204),COMBO_MATCH:i(1205),DOWN:i(1206),KEY_DOWN:i(1207),KEY_UP:i(1208),UP:i(1209)}},function(t,e){t.exports=function(t,e){return!!t.url&&(t.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t.url:e+t.url)}},function(t,e){t.exports=function(t,e,i,n,s){return void 0===t&&(t=""),void 0===e&&(e=!0),void 0===i&&(i=""),void 0===n&&(n=""),void 0===s&&(s=0),{responseType:t,async:e,user:i,password:n,timeout:s,header:void 0,headerValue:void 0,requestedWith:!1,overrideMimeType:void 0}}},function(t,e,i){var n=i(0),s=i(214),r=i(69),o=new n({Extends:r,Mixins:[s.Acceleration,s.Angular,s.Bounce,s.Debug,s.Drag,s.Enable,s.Friction,s.Gravity,s.Immovable,s.Mass,s.Size,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t,e,i,n,s),this.body=null}});t.exports=o},function(t,e,i){t.exports={CalculateFacesAt:i(217),CalculateFacesWithin:i(51),Copy:i(1301),CreateFromTiles:i(1302),CullTiles:i(1303),Fill:i(1304),FilterTiles:i(1305),FindByIndex:i(1306),FindTile:i(1307),ForEachTile:i(1308),GetTileAt:i(138),GetTileAtWorldXY:i(1309),GetTilesWithin:i(24),GetTilesWithinShape:i(1310),GetTilesWithinWorldXY:i(1311),HasTileAt:i(470),HasTileAtWorldXY:i(1312),IsInLayerBounds:i(103),PutTileAt:i(218),PutTileAtWorldXY:i(1313),PutTilesAt:i(1314),Randomize:i(1315),RemoveTileAt:i(471),RemoveTileAtWorldXY:i(1316),RenderDebug:i(1317),ReplaceByIndex:i(469),SetCollision:i(1318),SetCollisionBetween:i(1319),SetCollisionByExclusion:i(1320),SetCollisionByProperty:i(1321),SetCollisionFromCollisionGroup:i(1322),SetTileIndexCallback:i(1323),SetTileLocationCallback:i(1324),Shuffle:i(1325),SwapByIndex:i(1326),TileToWorldX:i(139),TileToWorldXY:i(1327),TileToWorldY:i(140),WeightedRandomize:i(1328),WorldToTileX:i(63),WorldToTileXY:i(1329),WorldToTileY:i(64)}},function(t,e,i){var n=i(103);t.exports=function(t,e,i,s){if(void 0===i&&(i=!1),n(t,e,s)){var r=s.data[e][t]||null;return null===r?null:-1===r.index?i?r:null:r}return null}},function(t,e){t.exports=function(t,e,i){var n=i.baseTileWidth,s=i.tilemapLayer,r=0;return s&&(void 0===e&&(e=s.scene.cameras.main),r=s.x+e.scrollX*(1-s.scrollFactorX),n*=s.scaleX),r+t*n}},function(t,e){t.exports=function(t,e,i){var n=i.baseTileHeight,s=i.tilemapLayer,r=0;return s&&(void 0===e&&(e=s.scene.cameras.main),r=s.y+e.scrollY*(1-s.scrollFactorY),n*=s.scaleY),r+t*n}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o,a){(void 0===i||i<=0)&&(i=32),(void 0===n||n<=0)&&(n=32),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o={}),void 0===a&&(a={}),this.name=t,this.firstgid=e,this.tileWidth=i,this.tileHeight=n,this.tileMargin=s,this.tileSpacing=r,this.tileProperties=o,this.tileData=a,this.image=null,this.glTexture=null,this.rows=0,this.columns=0,this.total=0,this.texCoordinates=[]},getTileProperties:function(t){return this.containsTileIndex(t)?this.tileProperties[t-this.firstgid]:null},getTileData:function(t){return this.containsTileIndex(t)?this.tileData[t-this.firstgid]:null},getTileCollisionGroup:function(t){var e=this.getTileData(t);return e&&e.objectgroup?e.objectgroup:null},containsTileIndex:function(t){return t>=this.firstgid&&t1?2-s:s,o=r*Math.cos(i),a=r*Math.sin(i);return e.x=t.x+o*t.radius,e.y=t.y+a*t.radius,e}},function(t,e,i){var n=i(22),s=i(0),r=i(9),o=i(111),a=i(267),h=i(268),l=i(6),u=new s({Extends:r,initialize:function(t,e,i){r.call(this),this.manager=t,this.key=e,this.type="frame",this.frames=this.getFrames(t.textureManager,l(i,"frames",[]),l(i,"defaultTextureKey",null)),this.frameRate=l(i,"frameRate",null),this.duration=l(i,"duration",null),null===this.duration&&null===this.frameRate?(this.frameRate=24,this.duration=this.frameRate/this.frames.length*1e3):this.duration&&null===this.frameRate?this.frameRate=this.frames.length/(this.duration/1e3):this.duration=this.frames.length/this.frameRate*1e3,this.msPerFrame=1e3/this.frameRate,this.skipMissedFrames=l(i,"skipMissedFrames",!0),this.delay=l(i,"delay",0),this.repeat=l(i,"repeat",0),this.repeatDelay=l(i,"repeatDelay",0),this.yoyo=l(i,"yoyo",!1),this.showOnStart=l(i,"showOnStart",!1),this.hideOnComplete=l(i,"hideOnComplete",!1),this.paused=!1,this.manager.on(o.PAUSE_ALL,this.pause,this),this.manager.on(o.RESUME_ALL,this.resume,this)},addFrame:function(t){return this.addFrameAt(this.frames.length,t)},addFrameAt:function(t,e){var i=this.getFrames(this.manager.textureManager,e);if(i.length>0){if(0===t)this.frames=i.concat(this.frames);else if(t===this.frames.length)this.frames=this.frames.concat(i);else{var n=this.frames.slice(0,t),s=this.frames.slice(t);this.frames=n.concat(i,s)}this.updateFrameSequence()}return this},checkFrame:function(t){return t>=0&&t0){s.isLast=!0,s.nextFrame=a[0],a[0].prevFrame=s;var v=1/(a.length-1);for(r=0;r=this.frames.length&&(e=0),t.currentAnim!==this&&(t.currentAnim=this,t.frameRate=this.frameRate,t.duration=this.duration,t.msPerFrame=this.msPerFrame,t.skipMissedFrames=this.skipMissedFrames,t._delay=this.delay,t._repeat=this.repeat,t._repeatDelay=this.repeatDelay,t._yoyo=this.yoyo);var i=this.frames[e];0!==e||t.forward||(i=this.getLastFrame()),t.updateFrame(i)},getFrameByProgress:function(t){return t=n(t,0,1),a(t,this.frames,"progress")},nextFrame:function(t){var e=t.currentFrame;e.isLast?t._yoyo?this.handleYoyoFrame(t,!1):t.repeatCounter>0?t._reverse&&t.forward?t.forward=!1:this.repeatAnimation(t):this.completeAnimation(t):this.updateAndGetNextTick(t,e.nextFrame)},handleYoyoFrame:function(t,e){if(e||(e=!1),t._reverse===!e&&t.repeatCounter>0)return t.forward=e,void this.repeatAnimation(t);if(t._reverse===e||0!==t.repeatCounter){t.forward=e;var i=e?t.currentFrame.nextFrame:t.currentFrame.prevFrame;this.updateAndGetNextTick(t,i)}else this.completeAnimation(t)},getLastFrame:function(){return this.frames[this.frames.length-1]},previousFrame:function(t){var e=t.currentFrame;e.isFirst?t._yoyo?this.handleYoyoFrame(t,!0):t.repeatCounter>0?t._reverse&&!t.forward?(t.currentFrame=this.getLastFrame(),this.repeatAnimation(t)):(t.forward=!0,this.repeatAnimation(t)):this.completeAnimation(t):this.updateAndGetNextTick(t,e.prevFrame)},updateAndGetNextTick:function(t,e){t.updateFrame(e),this.getNextTick(t)},removeFrame:function(t){var e=this.frames.indexOf(t);return-1!==e&&this.removeFrameAt(e),this},removeFrameAt:function(t){return this.frames.splice(t,1),this.updateFrameSequence(),this},repeatAnimation:function(t){if(2===t._pendingStop)return this.completeAnimation(t);if(t._repeatDelay>0&&!1===t.pendingRepeat)t.pendingRepeat=!0,t.accumulator-=t.nextTick,t.nextTick+=t._repeatDelay;else if(t.repeatCounter--,t.updateFrame(t.currentFrame[t.forward?"nextFrame":"prevFrame"]),t.isPlaying){this.getNextTick(t),t.pendingRepeat=!1;var e=t.currentFrame,i=t.parent;this.emit(o.ANIMATION_REPEAT,this,e),i.emit(o.SPRITE_ANIMATION_KEY_REPEAT+this.key,this,e,t.repeatCounter,i),i.emit(o.SPRITE_ANIMATION_REPEAT,this,e,t.repeatCounter,i)}},setFrame:function(t){t.forward?this.nextFrame(t):this.previousFrame(t)},toJSON:function(){var t={key:this.key,type:this.type,frames:[],frameRate:this.frameRate,duration:this.duration,skipMissedFrames:this.skipMissedFrames,delay:this.delay,repeat:this.repeat,repeatDelay:this.repeatDelay,yoyo:this.yoyo,showOnStart:this.showOnStart,hideOnComplete:this.hideOnComplete};return this.frames.forEach(function(e){t.frames.push(e.toJSON())}),t},updateFrameSequence:function(){for(var t,e=this.frames.length,i=1/(e-1),n=0;n1?(t.isLast=!0,t.prevFrame=this.frames[e-2],t.nextFrame=this.frames[0]):e>1&&(t.prevFrame=this.frames[n-1],t.nextFrame=this.frames[n+1]);return this},pause:function(){return this.paused=!0,this},resume:function(){return this.paused=!1,this},destroy:function(){this.removeAllListeners(),this.manager.off(o.PAUSE_ALL,this.pause,this),this.manager.off(o.RESUME_ALL,this.resume,this),this.manager.remove(this.key);for(var t=0;t=1)return i.x=t.x,i.y=t.y,i;var r=n(t)*e;return e>.5?(r-=t.width+t.height)<=t.width?(i.x=t.right-r,i.y=t.bottom):(i.x=t.x,i.y=t.bottom-(r-t.width)):r<=t.width?(i.x=t.x+r,i.y=t.y):(i.x=t.right,i.y=t.y+(r-t.width)),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=n(t)/i);for(var o=t.x1,a=t.y1,h=t.x2,l=t.y2,u=0;u=1&&(a=1-a,h=1-h),e.x=t.x1+(i*a+r*h),e.y=t.y1+(s*a+o*h),e}},function(t,e){t.exports=function(t,e,i,n,s){var r=n+Math.atan2(t.y-i,t.x-e);return t.x=e+s*Math.cos(r),t.y=i+s*Math.sin(r),t}},function(t,e){t.exports=function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)}},function(t,e){t.exports=function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){if(this.entries={},this.size=0,Array.isArray(t))for(var e=0;e=(t=t.toString()).length)switch(n){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((s=e-t.length)/2);t=new Array(s-r+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t}},function(t,e,i){var n=i(291),s=i(294),r=i(296),o=i(297);t.exports=function(t){switch(typeof t){case"string":return"rgb"===t.substr(0,3).toLowerCase()?o(t):n(t);case"number":return s(t);case"object":return r(t)}}},function(t,e){t.exports=function(t,e,i){return t<<16|e<<8|i}},function(t,e,i){var n=i(162);t.exports=function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1);var r=Math.floor(6*t),o=6*t-r,a=Math.floor(i*(1-e)*255),h=Math.floor(i*(1-o*e)*255),l=Math.floor(i*(1-(1-o)*e)*255),u=i=Math.floor(i*=255),c=i,d=i,f=r%6;return 0===f?(c=l,d=a):1===f?(u=h,d=a):2===f?(u=a,d=l):3===f?(u=a,c=h):4===f?(u=l,c=a):5===f&&(c=a,d=h),s?s.setTo?s.setTo(u,c,d,s.alpha,!1):(s.r=u,s.g=c,s.b=d,s.color=n(u,c,d),s):{r:u,g:c,b:d,color:n(u,c,d)}}},function(t,e){var i,n="";t.exports={disable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!1),t},enable:function(t){return""===n&&(n=i(t)),n&&(t[n]=!0),t},getPrefix:i=function(t){for(var e=["i","webkitI","msI","mozI","oI"],i=0;i0&&(n=1/Math.sqrt(n),this.x=t*n,this.y=e*n,this.z=i*n),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},cross:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z;return this.x=i*o-n*r,this.y=n*s-e*o,this.z=e*r-i*s,this},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this},transformMat3:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=e*s[0]+i*s[3]+n*s[6],this.y=e*s[1]+i*s[4]+n*s[7],this.z=e*s[2]+i*s[5]+n*s[8],this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=t.val;return this.x=s[0]*e+s[4]*i+s[8]*n+s[12],this.y=s[1]*e+s[5]*i+s[9]*n+s[13],this.z=s[2]*e+s[6]*i+s[10]*n+s[14],this},transformCoordinates:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=e*s[0]+i*s[4]+n*s[8]+s[12],o=e*s[1]+i*s[5]+n*s[9]+s[13],a=e*s[2]+i*s[6]+n*s[10]+s[14],h=e*s[3]+i*s[7]+n*s[11]+s[15];return this.x=r/h,this.y=o/h,this.z=a/h,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},project:function(t){var e=this.x,i=this.y,n=this.z,s=t.val,r=s[0],o=s[1],a=s[2],h=s[3],l=s[4],u=s[5],c=s[6],d=s[7],f=s[8],p=s[9],g=s[10],v=s[11],m=s[12],y=s[13],x=s[14],T=1/(e*h+i*d+n*v+s[15]);return this.x=(e*r+i*l+n*f+m)*T,this.y=(e*o+i*u+n*p+y)*T,this.z=(e*a+i*c+n*g+x)*T,this},unproject:function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,o=this.x-i,a=r-this.y-1-n,h=this.z;return this.x=2*o/s-1,this.y=2*a/r-1,this.z=2*h-1,this.project(e)},reset:function(){return this.x=0,this.y=0,this.z=0,this}});n.ZERO=new n,n.RIGHT=new n(1,0,0),n.LEFT=new n(-1,0,0),n.UP=new n(0,-1,0),n.DOWN=new n(0,1,0),n.FORWARD=new n(0,0,1),n.BACK=new n(0,0,-1),n.ONE=new n(1,1,1),t.exports=n},function(t,e,i){t.exports={Global:["game","anims","cache","plugins","registry","scale","sound","textures"],CoreScene:["EventEmitter","CameraManager","GameObjectCreator","GameObjectFactory","ScenePlugin","DisplayList","UpdateList"],DefaultScene:["Clock","DataManagerPlugin","InputPlugin","Loader","TweenManager","LightsPlugin"]}},function(t,e,i){var n=i(11),s=i(13);t.exports=function(t,e){if(void 0===e&&(e=new n),0===t.length)return e;for(var i,r,o,a=Number.MAX_VALUE,h=Number.MAX_VALUE,l=s.MIN_SAFE_INTEGER,u=s.MIN_SAFE_INTEGER,c=0;c0},isTransitionIn:function(){return this.settings.isTransition},isVisible:function(){return this.settings.visible},setVisible:function(t){return this.settings.visible=t,this},setActive:function(t,e){return t?this.resume(e):this.pause(e)},start:function(t){t&&(this.settings.data=t),this.settings.status=s.START,this.settings.active=!0,this.settings.visible=!0,this.events.emit(o.START,this),this.events.emit(o.READY,this,t)},shutdown:function(t){this.events.off(o.TRANSITION_INIT),this.events.off(o.TRANSITION_START),this.events.off(o.TRANSITION_COMPLETE),this.events.off(o.TRANSITION_OUT),this.settings.status=s.SHUTDOWN,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.SHUTDOWN,this,t)},destroy:function(){this.settings.status=s.DESTROYED,this.settings.active=!1,this.settings.visible=!1,this.events.emit(o.DESTROY,this),this.events.removeAllListeners();for(var t=["scene","game","anims","cache","plugins","registry","sound","textures","add","camera","displayList","events","make","scenePlugin","updateList"],e=0;e0},getRenderList:function(){return this.dirty&&(this.renderList=this.children.list.filter(this.childCanRender,this),this.dirty=!1),this.renderList},clear:function(){this.children.removeAll(),this.dirty=!0},preDestroy:function(){this.children.destroy(),this.renderList=[]}});t.exports=u},function(t,e,i){var n=i(181),s=i(52),r=i(0),o=i(12),a=i(90),h=i(14),l=i(11),u=i(947),c=i(386),d=i(3),f=new r({Extends:h,Mixins:[o.AlphaSingle,o.BlendMode,o.ComputedSize,o.Depth,o.Mask,o.Transform,o.Visible,u],initialize:function(t,e,i,n){h.call(this,t,"Container"),this.list=[],this.exclusive=!0,this.maxSize=-1,this.position=0,this.localTransform=new o.TransformMatrix,this.tempTransformMatrix=new o.TransformMatrix,this._displayList=t.sys.displayList,this._sortKey="",this._sysEvents=t.sys.events,this.scrollFactorX=1,this.scrollFactorY=1,this.setPosition(e,i),this.clearAlpha(),this.setBlendMode(s.SKIP_CHECK),n&&this.add(n)},originX:{get:function(){return.5}},originY:{get:function(){return.5}},displayOriginX:{get:function(){return.5*this.width}},displayOriginY:{get:function(){return.5*this.height}},setExclusive:function(t){return void 0===t&&(t=!0),this.exclusive=t,this},getBounds:function(t){if(void 0===t&&(t=new l),t.setTo(this.x,this.y,0,0),this.list.length>0)for(var e=this.list,i=new l,n=0;n-1},setAll:function(t,e,i,s){return n.SetAll(this.list,t,e,i,s),this},each:function(t,e){var i,n=[null],s=this.list.slice(),r=s.length;for(i=2;i0?this.list[0]:null}},last:{get:function(){return this.list.length>0?(this.position=this.list.length-1,this.list[this.position]):null}},next:{get:function(){return this.position0?(this.position--,this.list[this.position]):null}},preDestroy:function(){this.removeAll(!!this.exclusive),this.localTransform.destroy(),this.tempTransformMatrix.destroy(),this.list=[],this._displayList=null}});t.exports=f},function(t,e,i){var n=i(129),s=i(0),r=i(952),o=new s({Extends:n,Mixins:[r],initialize:function(t,e,i,s,r,o,a){n.call(this,t,e,i,s,r,o,a),this.type="DynamicBitmapText",this.scrollX=0,this.scrollY=0,this.cropWidth=0,this.cropHeight=0,this.displayCallback,this.callbackData={parent:this,color:0,tint:{topLeft:0,topRight:0,bottomLeft:0,bottomRight:0},index:0,charCode:0,x:0,y:0,scale:0,rotation:0,data:0}},setSize:function(t,e){return this.cropWidth=t,this.cropHeight=e,this},setDisplayCallback:function(t){return this.displayCallback=t,this},setScrollX:function(t){return this.scrollX=t,this},setScrollY:function(t){return this.scrollY=t,this}});t.exports=o},function(t,e,i){var n=i(91),s=i(0),r=i(190),o=i(266),a=i(269),h=i(270),l=i(274),u=i(153),c=i(279),d=i(280),f=i(277),p=i(32),g=i(95),v=i(14),m=i(2),y=i(6),x=i(13),T=i(958),w=new s({Extends:v,Mixins:[o,a,h,l,u,c,d,f,T],initialize:function(t,e){var i=y(e,"x",0),n=y(e,"y",0);v.call(this,t,"Graphics"),this.setPosition(i,n),this.initPipeline(),this.displayOriginX=0,this.displayOriginY=0,this.commandBuffer=[],this.defaultFillColor=-1,this.defaultFillAlpha=1,this.defaultStrokeWidth=1,this.defaultStrokeColor=-1,this.defaultStrokeAlpha=1,this._lineWidth=1,this._tempMatrix1=new p,this._tempMatrix2=new p,this._tempMatrix3=new p,this.setDefaultStyles(e)},setDefaultStyles:function(t){return y(t,"lineStyle",null)&&(this.defaultStrokeWidth=y(t,"lineStyle.width",1),this.defaultStrokeColor=y(t,"lineStyle.color",16777215),this.defaultStrokeAlpha=y(t,"lineStyle.alpha",1),this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha)),y(t,"fillStyle",null)&&(this.defaultFillColor=y(t,"fillStyle.color",16777215),this.defaultFillAlpha=y(t,"fillStyle.alpha",1),this.fillStyle(this.defaultFillColor,this.defaultFillAlpha)),this},lineStyle:function(t,e,i){return void 0===i&&(i=1),this.commandBuffer.push(r.LINE_STYLE,t,e,i),this._lineWidth=t,this},fillStyle:function(t,e){return void 0===e&&(e=1),this.commandBuffer.push(r.FILL_STYLE,t,e),this},fillGradientStyle:function(t,e,i,n,s){return void 0===s&&(s=1),this.commandBuffer.push(r.GRADIENT_FILL_STYLE,s,t,e,i,n),this},lineGradientStyle:function(t,e,i,n,s,o){return void 0===o&&(o=1),this.commandBuffer.push(r.GRADIENT_LINE_STYLE,t,o,e,i,n,s),this},setTexture:function(t,e,i){if(void 0===i&&(i=0),void 0===t)this.commandBuffer.push(r.CLEAR_TEXTURE);else{var n=this.scene.sys.textures.getFrame(t,e);n&&(2===i&&(i=3),this.commandBuffer.push(r.SET_TEXTURE,n,i))}return this},beginPath:function(){return this.commandBuffer.push(r.BEGIN_PATH),this},closePath:function(){return this.commandBuffer.push(r.CLOSE_PATH),this},fillPath:function(){return this.commandBuffer.push(r.FILL_PATH),this},fill:function(){return this.commandBuffer.push(r.FILL_PATH),this},strokePath:function(){return this.commandBuffer.push(r.STROKE_PATH),this},stroke:function(){return this.commandBuffer.push(r.STROKE_PATH),this},fillCircleShape:function(t){return this.fillCircle(t.x,t.y,t.radius)},strokeCircleShape:function(t){return this.strokeCircle(t.x,t.y,t.radius)},fillCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.fillPath(),this},strokeCircle:function(t,e,i){return this.beginPath(),this.arc(t,e,i,0,x.PI2),this.strokePath(),this},fillRectShape:function(t){return this.fillRect(t.x,t.y,t.width,t.height)},strokeRectShape:function(t){return this.strokeRect(t.x,t.y,t.width,t.height)},fillRect:function(t,e,i,n){return this.commandBuffer.push(r.FILL_RECT,t,e,i,n),this},strokeRect:function(t,e,i,n){var s=this._lineWidth/2,r=t-s,o=t+s;return this.beginPath(),this.moveTo(t,e),this.lineTo(t,e+n),this.strokePath(),this.beginPath(),this.moveTo(t+i,e),this.lineTo(t+i,e+n),this.strokePath(),this.beginPath(),this.moveTo(r,e),this.lineTo(o+i,e),this.strokePath(),this.beginPath(),this.moveTo(r,e+n),this.lineTo(o+i,e+n),this.strokePath(),this},fillRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.fillPath(),this},strokeRoundedRect:function(t,e,i,n,s){void 0===s&&(s=20);var r=s,o=s,a=s,h=s;return"number"!=typeof s&&(r=m(s,"tl",20),o=m(s,"tr",20),a=m(s,"bl",20),h=m(s,"br",20)),this.beginPath(),this.moveTo(t+r,e),this.lineTo(t+i-o,e),this.arc(t+i-o,e+o,o,-x.TAU,0),this.lineTo(t+i,e+n-h),this.arc(t+i-h,e+n-h,h,0,x.TAU),this.lineTo(t+a,e+n),this.arc(t+a,e+n-a,a,x.TAU,Math.PI),this.lineTo(t,e+r),this.arc(t+r,e+r,r,-Math.PI,-x.TAU),this.strokePath(),this},fillPointShape:function(t,e){return this.fillPoint(t.x,t.y,e)},fillPoint:function(t,e,i){return!i||i<1?i=1:(t-=i/2,e-=i/2),this.commandBuffer.push(r.FILL_RECT,t,e,i,i),this},fillTriangleShape:function(t){return this.fillTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},strokeTriangleShape:function(t){return this.strokeTriangle(t.x1,t.y1,t.x2,t.y2,t.x3,t.y3)},fillTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.FILL_TRIANGLE,t,e,i,n,s,o),this},strokeTriangle:function(t,e,i,n,s,o){return this.commandBuffer.push(r.STROKE_TRIANGLE,t,e,i,n,s,o),this},strokeLineShape:function(t){return this.lineBetween(t.x1,t.y1,t.x2,t.y2)},lineBetween:function(t,e,i,n){return this.beginPath(),this.moveTo(t,e),this.lineTo(i,n),this.strokePath(),this},lineTo:function(t,e){return this.commandBuffer.push(r.LINE_TO,t,e),this},moveTo:function(t,e){return this.commandBuffer.push(r.MOVE_TO,t,e),this},strokePoints:function(t,e,i,n){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===n&&(n=t.length),this.beginPath(),this.moveTo(t[0].x,t[0].y);for(var s=1;s-1&&this.fillStyle(this.defaultFillColor,this.defaultFillAlpha),this.defaultStrokeColor>-1&&this.lineStyle(this.defaultStrokeWidth,this.defaultStrokeColor,this.defaultStrokeAlpha),this},generateTexture:function(t,e,i){var n,s,r=this.scene.sys,o=r.game.renderer;if(void 0===e&&(e=r.scale.width),void 0===i&&(i=r.scale.height),w.TargetCamera.setScene(this.scene),w.TargetCamera.setViewport(0,0,e,i),w.TargetCamera.scrollX=this.x,w.TargetCamera.scrollY=this.y,"string"==typeof t)if(r.textures.exists(t)){var a=(n=r.textures.get(t)).getSourceImage();a instanceof HTMLCanvasElement&&(s=a.getContext("2d"))}else s=(n=r.textures.createCanvas(t,e,i)).getSourceImage().getContext("2d");else t instanceof HTMLCanvasElement&&(s=t.getContext("2d"));return s&&(this.renderCanvas(o,this,0,w.TargetCamera,null,s,!1),n&&n.refresh()),this},preDestroy:function(){this.commandBuffer=[]}});w.TargetCamera=new n,t.exports=w},function(t,e){t.exports={ARC:0,BEGIN_PATH:1,CLOSE_PATH:2,FILL_RECT:3,LINE_TO:4,MOVE_TO:5,LINE_STYLE:6,FILL_STYLE:7,FILL_PATH:8,STROKE_PATH:9,FILL_TRIANGLE:10,STROKE_TRIANGLE:11,SAVE:14,RESTORE:15,TRANSLATE:16,SCALE:17,ROTATE:18,SET_TEXTURE:19,CLEAR_TEXTURE:20,GRADIENT_FILL_STYLE:21,GRADIENT_LINE_STYLE:22}},function(t,e,i){var n=i(4);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=t.width/2,r=t.height/2;return i.x=t.x+s*Math.cos(e),i.y=t.y+r*Math.sin(e),i}},function(t,e,i){var n=i(0),s=i(12),r=i(14),o=i(394),a=i(126),h=i(396),l=i(968),u=new n({Extends:r,Mixins:[s.Depth,s.Mask,s.Pipeline,s.Transform,s.Visible,l],initialize:function(t,e,i,n){if(r.call(this,t,"ParticleEmitterManager"),this.blendMode=-1,this.timeScale=1,this.texture=null,this.frame=null,this.frameNames=[],null===i||"object"!=typeof i&&!Array.isArray(i)||(n=i,i=null),this.setTexture(e,i),this.initPipeline(),this.emitters=new a(this),this.wells=new a(this),n){Array.isArray(n)||(n=[n]);for(var s=0;s0?e.defaultFrame=i[0]:e.defaultFrame=this.defaultFrame,this},addEmitter:function(t){return this.emitters.add(t)},createEmitter:function(t){return this.addEmitter(new h(this,t))},removeEmitter:function(t){return this.emitters.remove(t,!0)},addGravityWell:function(t){return this.wells.add(t)},createGravityWell:function(t){return this.addGravityWell(new o(t))},emitParticle:function(t,e,i){for(var n=this.emitters.list,s=0;ss.width&&(t=s.width-this.frame.cutX),this.frame.cutY+e>s.height&&(e=s.height-this.frame.cutY),this.frame.setSize(t,e,this.frame.cutX,this.frame.cutY)}this.updateDisplayOrigin();var r=this.input;return r&&!r.customHitArea&&(r.hitArea.width=t,r.hitArea.height=e),this},setGlobalTint:function(t){return this.globalTint=t,this},setGlobalAlpha:function(t){return this.globalAlpha=t,this},saveTexture:function(t){return this.textureManager.renameTexture(this.texture.key,t),this._saved=!0,this.texture},fill:function(t,e,i,n,s,r){void 0===e&&(e=1),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.frame.cutWidth),void 0===r&&(r=this.frame.cutHeight);var o=255&(t>>16|0),a=255&(t>>8|0),h=255&(0|t),l=this.gl,u=this.frame;if(this.camera.preRender(1,1),l){var c=this.camera._cx,f=this.camera._cy,p=this.camera._cw,g=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(c,f,p,g,g);var v=this.pipeline;v.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),v.drawFillRect(i,n,s,r,d.getTintFromFloats(o/255,a/255,h/255,1),e),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),v.projOrtho(0,v.width,v.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.context.fillStyle="rgba("+o+","+a+","+h+","+e+")",this.context.fillRect(i+u.cutX,n+u.cutY,s,r),this.renderer.setContext();return this.dirty=!0,this},clear:function(){if(this.dirty){var t=this.gl;if(t){var e=this.renderer;e.setFramebuffer(this.framebuffer,!0),this.frame.cutWidth===this.canvas.width&&this.frame.cutHeight===this.canvas.height||t.scissor(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),e.setFramebuffer(null,!0)}else{var i=this.context;i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(this.frame.cutX,this.frame.cutY,this.frame.cutWidth,this.frame.cutHeight),i.restore()}this.dirty=!1}return this},erase:function(t,e,i){this._eraseMode=!0;var s=this.renderer.currentBlendMode;return this.renderer.setBlendMode(n.ERASE),this.draw(t,e,i,1,16777215),this.renderer.setBlendMode(s),this._eraseMode=!1,this},draw:function(t,e,i,n,s){void 0===n&&(n=this.globalAlpha),s=void 0===s?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(s>>16)+(65280&s)+((255&s)<<16),Array.isArray(t)||(t=[t]);var r=this.gl;if(this.camera.preRender(1,1),r){var o=this.camera._cx,a=this.camera._cy,h=this.camera._cw,l=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(o,a,h,l,l);var u=this.pipeline;u.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),this.batchList(t,e,i,n,s),u.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),u.projOrtho(0,u.width,u.height,0,-1e3,1e3)}else this.renderer.setContext(this.context),this.batchList(t,e,i,n,s),this.renderer.setContext();return this.dirty=!0,this},drawFrame:function(t,e,i,n,s,r){void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.globalAlpha),r=void 0===r?(this.globalTint>>16)+(65280&this.globalTint)+((255&this.globalTint)<<16):(r>>16)+(65280&r)+((255&r)<<16);var o=this.gl,a=this.textureManager.getFrame(t,e);if(a){if(this.camera.preRender(1,1),o){var h=this.camera._cx,l=this.camera._cy,u=this.camera._cw,c=this.camera._ch;this.renderer.setFramebuffer(this.framebuffer,!1),this.renderer.pushScissor(h,l,u,c,c);var d=this.pipeline;d.projOrtho(0,this.texture.width,0,this.texture.height,-1e3,1e3),d.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,r,s,this.camera.matrix,null),d.flush(),this.renderer.setFramebuffer(null,!1),this.renderer.popScissor(),d.projOrtho(0,d.width,d.height,0,-1e3,1e3)}else this.batchTextureFrame(a,i+this.frame.cutX,n+this.frame.cutY,s,r);this.dirty=!0}return this},batchList:function(t,e,i,n,s){for(var r=0;rl){if(0===c){for(var g=f;g.length&&(g=g.slice(0,-1),!((p=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var v=d.substr(g.length);u[c]=v,h+=g}var m=u[c].length?c:c+1,y=u.slice(m).join(" ").replace(/[ \n]*$/gi,"");s[o+1]=y+" "+(s[o+1]||""),r=s.length;break}h+=f,l-=p}n+=h.replace(/[ \n]*$/gi,"")+"\n"}}return n=n.replace(/[\s|\n]*$/gi,"")},basicWordWrap:function(t,e,i){for(var n="",s=t.split(this.splitRegExp),r=s.length-1,o=e.measureText(" ").width,a=0;a<=r;a++){for(var h=i,l=s[a].split(" "),u=l.length-1,c=0;c<=u;c++){var d=l[c],f=e.measureText(d).width,p=f+o;p>h&&c>0&&(n+="\n",h=i),n+=d,c0&&(d+=h.lineSpacing*g),i.rtl)c=f-c;else if("right"===i.align)c+=o-h.lineWidths[g];else if("center"===i.align)c+=(o-h.lineWidths[g])/2;else if("justify"===i.align){if(h.lineWidths[g]/h.width>=.85){var v=h.width-h.lineWidths[g],m=e.measureText(" ").width,y=a[g].trim(),x=y.split(" ");v+=(a[g].length-y.length)*m;for(var T=Math.floor(v/m),w=0;T>0;)x[w]+=" ",w=(w+1)%(x.length-1||1),--T;a[g]=x.join(" ")}}this.autoRound&&(c=Math.round(c),d=Math.round(d)),i.strokeThickness&&(this.style.syncShadow(e,i.shadowStroke),e.strokeText(a[g],c,d)),i.color&&(this.style.syncShadow(e,i.shadowFill),e.fillText(a[g],c,d))}e.restore(),this.renderer.gl&&(this.frame.source.glTexture=this.renderer.canvasToTexture(t,this.frame.source.glTexture,!0),this.frame.glTexture=this.frame.source.glTexture),this.dirty=!0;var b=this.input;return b&&!b.customHitArea&&(b.hitArea.width=this.width,b.hitArea.height=this.height),this},getTextMetrics:function(){return this.style.getTextMetrics()},text:{get:function(){return this._text},set:function(t){this.setText(t)}},toJSON:function(){var t=o.ToJSON(this),e={autoRound:this.autoRound,text:this._text,style:this.style.toJSON(),padding:{left:this.padding.left,right:this.padding.right,top:this.padding.top,bottom:this.padding.bottom}};return t.data=e,t},preDestroy:function(){this.style.rtl&&c(this.canvas),s.remove(this.canvas),this.texture.destroy()}});t.exports=p},function(t,e,i){var n=i(26),s=i(0),r=i(12),o=i(18),a=i(14),h=i(324),l=i(164),u=i(984),c=i(3),d=new s({Extends:a,Mixins:[r.Alpha,r.BlendMode,r.ComputedSize,r.Crop,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Tint,r.Transform,r.Visible,u],initialize:function(t,e,i,s,r,l,u){var d=t.sys.game.renderer;a.call(this,t,"TileSprite");var f=t.sys.textures.get(l),p=f.get(u);s&&r?(s=Math.floor(s),r=Math.floor(r)):(s=p.width,r=p.height),this._tilePosition=new c,this._tileScale=new c(1,1),this.dirty=!1,this.renderer=d,this.canvas=n.create(this,s,r),this.context=this.canvas.getContext("2d"),this.displayTexture=f,this.displayFrame=p,this._crop=this.resetCropObject(),this.texture=t.sys.textures.addCanvas(null,this.canvas,!0),this.frame=this.texture.get(),this.potWidth=h(p.width),this.potHeight=h(p.height),this.fillCanvas=n.create2D(this,this.potWidth,this.potHeight),this.fillContext=this.fillCanvas.getContext("2d"),this.fillPattern=null,this.setPosition(e,i),this.setSize(s,r),this.setFrame(u),this.setOriginFromFrame(),this.initPipeline(),t.sys.game.events.on(o.CONTEXT_RESTORED,function(t){var e=t.gl;this.dirty=!0,this.fillPattern=null,this.fillPattern=t.createTexture2D(0,e.LINEAR,e.LINEAR,e.REPEAT,e.REPEAT,e.RGBA,this.fillCanvas,this.potWidth,this.potHeight)},this)},setTexture:function(t,e){return this.displayTexture=this.scene.sys.textures.get(t),this.setFrame(e)},setFrame:function(t){var e=this.displayTexture.get(t);return this.potWidth=h(e.width),this.potHeight=h(e.height),this.canvas.width=0,e.cutWidth&&e.cutHeight?this.renderFlags|=8:this.renderFlags&=-9,this.displayFrame=e,this.dirty=!0,this.updateTileTexture(),this},setTilePosition:function(t,e){return void 0!==t&&(this.tilePositionX=t),void 0!==e&&(this.tilePositionY=e),this},setTileScale:function(t,e){return void 0===t&&(t=this.tileScaleX),void 0===e&&(e=t),this.tileScaleX=t,this.tileScaleY=e,this},updateTileTexture:function(){if(this.dirty&&this.renderer){var t=this.displayFrame;if(t.source.isRenderTexture||t.source.isGLTexture)return console.warn("TileSprites can only use Image or Canvas based textures"),void(this.dirty=!1);var e=this.fillContext,i=this.fillCanvas,n=this.potWidth,s=this.potHeight;this.renderer.gl||(n=t.cutWidth,s=t.cutHeight),e.clearRect(0,0,n,s),i.width=n,i.height=s,e.drawImage(t.source.image,t.cutX,t.cutY,t.cutWidth,t.cutHeight,0,0,n,s),this.renderer.gl?this.fillPattern=this.renderer.canvasToTexture(i,this.fillPattern):this.fillPattern=e.createPattern(i,"repeat"),this.updateCanvas(),this.dirty=!1}},updateCanvas:function(){var t=this.canvas;if(t.width===this.width&&t.height===this.height||(t.width=this.width,t.height=this.height,this.frame.setSize(this.width,this.height),this.updateDisplayOrigin(),this.dirty=!0),!this.dirty||this.renderer&&this.renderer.gl)this.dirty=!1;else{var e=this.context;this.scene.sys.game.config.antialias||l.disable(e);var i=this._tileScale.x,n=this._tileScale.y,s=this._tilePosition.x,r=this._tilePosition.y;e.clearRect(0,0,this.width,this.height),e.save(),e.scale(i,n),e.translate(-s,-r),e.fillStyle=this.fillPattern,e.fillRect(s,r,this.width/i,this.height/n),e.restore(),this.dirty=!1}},preDestroy:function(){this.renderer&&this.renderer.gl&&this.renderer.deleteTexture(this.fillPattern),n.remove(this.canvas),n.remove(this.fillCanvas),this.fillPattern=null,this.fillContext=null,this.fillCanvas=null,this.displayTexture=null,this.displayFrame=null,this.texture.destroy(),this.renderer=null},tilePositionX:{get:function(){return this._tilePosition.x},set:function(t){this._tilePosition.x=t,this.dirty=!0}},tilePositionY:{get:function(){return this._tilePosition.y},set:function(t){this._tilePosition.y=t,this.dirty=!0}},tileScaleX:{get:function(){return this._tileScale.x},set:function(t){this._tileScale.x=t,this.dirty=!0}},tileScaleY:{get:function(){return this._tileScale.y},set:function(t){this._tileScale.y=t,this.dirty=!0}}});t.exports=d},function(t,e,i){var n=i(0),s=i(22),r=i(12),o=i(90),a=i(18),h=i(14),l=i(59),u=i(194),c=i(987),d=i(13),f=new n({Extends:h,Mixins:[r.Alpha,r.BlendMode,r.Depth,r.Flip,r.GetBounds,r.Mask,r.Origin,r.Pipeline,r.ScrollFactor,r.Size,r.TextureCrop,r.Tint,r.Transform,r.Visible,c],initialize:function(t,e,i,n){h.call(this,t,"Video"),this.video=null,this.videoTexture=null,this.videoTextureSource=null,this.snapshotTexture=null,this.flipY=!1,this._key=u(),this.touchLocked=!0,this.playWhenUnlocked=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._systemMuted=!1,this._codeMuted=!1,this._systemPaused=!1,this._codePaused=!1,this._callbacks={play:this.playHandler.bind(this),error:this.loadErrorHandler.bind(this),end:this.completeHandler.bind(this),time:this.timeUpdateHandler.bind(this),seeking:this.seekingHandler.bind(this),seeked:this.seekedHandler.bind(this)},this._crop=this.resetCropObject(),this.markers={},this._markerIn=-1,this._markerOut=d.MAX_SAFE_INTEGER,this._lastUpdate=0,this._cacheKey="",this._isSeeking=!1,this.removeVideoElementOnDestroy=!1,this.setPosition(e,i),this.initPipeline(),n&&this.changeSource(n,!1);var s=t.sys.game.events;s.on(a.PAUSE,this.globalPause,this),s.on(a.RESUME,this.globalResume,this);var r=t.sys.sound;r&&r.on(l.GLOBAL_MUTE,this.globalMute,this)},play:function(t,e,i){if(this.touchLocked&&this.playWhenUnlocked||this.isPlaying())return this;var n=this.video;if(!n)return console.warn("Video not loaded"),this;void 0===t&&(t=n.loop);var s=this.scene.sys.sound;s&&s.mute&&this.setMute(!0),isNaN(e)||(this._markerIn=e),!isNaN(i)&&i>e&&(this._markerOut=i),n.loop=t;var r=this._callbacks,o=n.play();return void 0!==o?o.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)):(n.addEventListener("playing",r.play,!0),n.readyState<2&&(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval))),n.addEventListener("ended",r.end,!0),n.addEventListener("timeupdate",r.time,!0),n.addEventListener("seeking",r.seeking,!0),n.addEventListener("seeked",r.seeked,!0),this},changeSource:function(t,e,i,n,s){void 0===e&&(e=!0),this.video&&this.stop();var r=this.scene.sys.cache.video.get(t);return r?(this.video=r,this._cacheKey=t,this._codePaused=r.paused,this._codeMuted=r.muted,this.videoTexture?(this.scene.sys.textures.remove(this._key),this.videoTexture=this.scene.sys.textures.create(this._key,r,r.videoWidth,r.videoHeight),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,r.videoWidth,r.videoHeight),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,r.videoWidth,r.videoHeight)):this.updateTexture(),r.currentTime=0,this._lastUpdate=0,e&&this.play(i,n,s)):this.video=null,this},addMarker:function(t,e,i){return!isNaN(e)&&e>=0&&!isNaN(i)&&(this.markers[t]=[e,i]),this},playMarker:function(t,e){var i=this.markers[t];return i&&this.play(e,i[0],i[1]),this},removeMarker:function(t){return delete this.markers[t],this},snapshot:function(t,e){return void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.snapshotArea(0,0,this.width,this.height,t,e)},snapshotArea:function(t,e,i,n,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=this.height),void 0===s&&(s=i),void 0===r&&(r=n);var o=this.video,a=this.snapshotTexture;return a?(a.setSize(s,r),o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)):(a=this.scene.sys.textures.createCanvas(u(),s,r),this.snapshotTexture=a,o&&a.context.drawImage(o,t,e,i,n,0,0,s,r)),a.update()},saveSnapshotTexture:function(t){return this.snapshotTexture?this.scene.sys.textures.renameTexture(this.snapshotTexture.key,t):this.snapshotTexture=this.scene.sys.textures.createCanvas(t,this.width,this.height),this.snapshotTexture},loadURL:function(t,e,i){void 0===e&&(e="loadeddata"),void 0===i&&(i=!1),this.video&&this.stop(),this.videoTexture&&this.scene.sys.textures.remove(this._key);var n=document.createElement("video");return n.controls=!1,i&&(n.muted=!0,n.defaultMuted=!0,n.setAttribute("autoplay","autoplay")),n.setAttribute("playsinline","playsinline"),n.setAttribute("preload","auto"),n.addEventListener("error",this._callbacks.error,!0),n.src=t,n.load(),this.video=n,this},playPromiseSuccessHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn)},playPromiseErrorHandler:function(t){this.scene.sys.input.once("pointerdown",this.unlockHandler,this),this.touchLocked=!0,this.playWhenUnlocked=!0,this.emit(o.VIDEO_ERROR,this,t)},playHandler:function(){this.touchLocked=!1,this.emit(o.VIDEO_PLAY,this),this.video.removeEventListener("playing",this._callbacks.play,!0)},loadErrorHandler:function(t){this.stop(),this.emit(o.VIDEO_ERROR,this,t)},unlockHandler:function(){this.touchLocked=!1,this.playWhenUnlocked=!1,this.emit(o.VIDEO_UNLOCKED,this),this._markerIn>-1&&(this.video.currentTime=this._markerIn),this.video.play(),this.emit(o.VIDEO_PLAY,this)},completeHandler:function(){this.emit(o.VIDEO_COMPLETE,this)},timeUpdateHandler:function(){this.video&&this.video.currentTime=this._markerOut&&(t.loop?(t.currentTime=this._markerIn,this.updateTexture(),this._lastUpdate=e,this.emit(o.VIDEO_LOOP,this)):(this.emit(o.VIDEO_COMPLETE,this),this.stop())))}},checkVideoProgress:function(){this.video.readyState>=2?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):this.emit(o.VIDEO_TIMEOUT,this))},updateTexture:function(){var t=this.video,e=t.videoWidth,i=t.videoHeight;if(this.videoTexture){var n=this.videoTextureSource;n.source!==t&&(n.source=t,n.width=e,n.height=i),n.update()}else this.videoTexture=this.scene.sys.textures.create(this._key,t,e,i),this.videoTextureSource=this.videoTexture.source[0],this.videoTexture.add("__BASE",0,0,0,e,i),this.setTexture(this.videoTexture),this.setSizeToFrame(),this.updateDisplayOrigin(),this.emit(o.VIDEO_CREATED,this,e,i)},getVideoKey:function(){return this._cacheKey},seekTo:function(t){var e=this.video;if(e){var i=e.duration;if(i!==1/0&&!isNaN(i)){var n=i*t;this.setCurrentTime(n)}}return this},getCurrentTime:function(){return this.video?this.video.currentTime:0},setCurrentTime:function(t){var e=this.video;if(e){if("string"==typeof t){var i=t[0],n=parseFloat(t.substr(1));"+"===i?t=e.currentTime+n:"-"===i&&(t=e.currentTime-n)}e.currentTime=t,this._lastUpdate=t}return this},isSeeking:function(){return this._isSeeking},seekingHandler:function(){this._isSeeking=!0,this.emit(o.VIDEO_SEEKING,this)},seekedHandler:function(){this._isSeeking=!1,this.emit(o.VIDEO_SEEKED,this),this.video&&this.updateTexture()},getProgress:function(){var t=this.video;if(t){var e=t.currentTime,i=t.duration;if(i!==1/0&&!isNaN(i))return e/i}return 0},getDuration:function(){return this.video?this.video.duration:0},setMute:function(t){void 0===t&&(t=!0),this._codeMuted=t;var e=this.video;return e&&(e.muted=!!this._systemMuted||t),this},isMuted:function(){return this._codeMuted},globalMute:function(t,e){this._systemMuted=e;var i=this.video;i&&(i.muted=!!this._codeMuted||e)},globalPause:function(){this._systemPaused=!0,this.video&&this.video.pause()},globalResume:function(){this._systemPaused=!1,this.video&&!this._codePaused&&this.video.play()},setPaused:function(t){void 0===t&&(t=!0);var e=this.video;return this._codePaused=t,e&&(t?e.paused||e.pause():t||e.paused&&!this._systemPaused&&e.play()),this},getVolume:function(){return this.video?this.video.volume:1},setVolume:function(t){return void 0===t&&(t=1),this.video&&(this.video.volume=s(t,0,1)),this},getPlaybackRate:function(){return this.video?this.video.playbackRate:1},setPlaybackRate:function(t){return this.video&&(this.video.playbackRate=t),this},getLoop:function(){return!!this.video&&this.video.loop},setLoop:function(t){return void 0===t&&(t=!0),this.video&&(this.video.loop=t),this},isPlaying:function(){return!!this.video&&!(this.video.paused||this.video.ended)},isPaused:function(){return this.video&&this.video.paused||this._codePaused||this._systemPaused},saveTexture:function(t,e){return void 0===e&&(e=!1),this.videoTexture&&this.scene.sys.textures.renameTexture(this._key,t),this._key=t,this.flipY=e,this.videoTextureSource&&this.videoTextureSource.setFlipY(e),this.videoTexture},stop:function(){var t=this.video;if(t){var e=this._callbacks;for(var i in e)t.removeEventListener(i,e[i],!0);t.pause()}return this._retryID&&window.clearTimeout(this._retryID),this.emit(o.VIDEO_STOP,this),this},removeVideoElement:function(){var t=this.video;if(t){for(t.parentNode&&t.parentNode.removeChild(t);t.hasChildNodes();)t.removeChild(t.firstChild);t.removeAttribute("autoplay"),t.removeAttribute("src"),this.video=null}},preDestroy:function(){this.stop(),this.removeVideoElementOnDestroy&&this.removeVideoElement();var t=this.scene.sys.game.events;t.off(a.PAUSE,this.globalPause,this),t.off(a.RESUME,this.globalResume,this);var e=this.scene.sys.sound;e&&e.off(l.GLOBAL_MUTE,this.globalMute,this),this._retryID&&window.clearTimeout(this._retryID)}});t.exports=f},function(t,e,i){var n=i(0),s=i(199),r=i(411),o=i(46),a=new n({initialize:function(t){this.type=o.POLYGON,this.area=0,this.points=[],t&&this.setTo(t)},contains:function(t,e){return s(this,t,e)},setTo:function(t){if(this.area=0,this.points=[],"string"==typeof t&&(t=t.split(" ")),!Array.isArray(t))return this;for(var e,i=Number.MAX_VALUE,n=0;no||r>a)return!1;if(s<=i||r<=n)return!0;var h=s-i,l=r-n;return h*h+l*l<=t.radius*t.radius}},function(t,e,i){var n=i(4),s=i(205);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a=t.x1,h=t.y1,l=t.x2,u=t.y2,c=e.x,d=e.y,f=e.radius,p=l-a,g=u-h,v=a-c,m=h-d,y=p*p+g*g,x=2*(p*v+g*m),T=x*x-4*y*(v*v+m*m-f*f);if(0===T){var w=-x/(2*y);r=a+w*p,o=h+w*g,w>=0&&w<=1&&i.push(new n(r,o))}else if(T>0){var b=(-x-Math.sqrt(T))/(2*y);r=a+b*p,o=h+b*g,b>=0&&b<=1&&i.push(new n(r,o));var E=(-x+Math.sqrt(T))/(2*y);r=a+E*p,o=h+E*g,E>=0&&E<=1&&i.push(new n(r,o))}}return i}},function(t,e,i){var n=i(55),s=new(i(4));t.exports=function(t,e,i){if(void 0===i&&(i=s),n(e,t.x1,t.y1))return i.x=t.x1,i.y=t.y1,!0;if(n(e,t.x2,t.y2))return i.x=t.x2,i.y=t.y2,!0;var r=t.x2-t.x1,o=t.y2-t.y1,a=e.x-t.x1,h=e.y-t.y1,l=r*r+o*o,u=r,c=o;if(l>0){var d=(a*r+h*o)/l;u*=d,c*=d}return i.x=t.x1+u,i.y=t.y1+c,u*u+c*c<=l&&u*r+c*o>=0&&n(e,i.x,i.y)}},function(t,e,i){var n=i(4),s=i(84),r=i(424);t.exports=function(t,e,i){if(void 0===i&&(i=[]),r(t,e))for(var o=e.getLineA(),a=e.getLineB(),h=e.getLineC(),l=e.getLineD(),u=[new n,new n,new n,new n],c=[s(o,t,u[0]),s(a,t,u[1]),s(h,t,u[2]),s(l,t,u[3])],d=0;d<4;d++)c[d]&&i.push(u[d]);return i}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=!1),void 0===n&&(n=[]);for(var s,r,o,a,h,l,u=t.x3-t.x1,c=t.y3-t.y1,d=t.x2-t.x1,f=t.y2-t.y1,p=u*u+c*c,g=u*d+c*f,v=d*d+f*f,m=p*v-g*g,y=0===m?0:1/m,x=t.x1,T=t.y1,w=0;w=0&&r>=0&&s+r<1&&(n.push({x:e[w].x,y:e[w].y}),i)));w++);return n}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,t}},function(t,e){t.exports=function(t){return 0===t.height?NaN:t.width/t.height}},function(t,e){t.exports=function(t,e,i,n){var s=Math.cos(n),r=Math.sin(n),o=t.x1-e,a=t.y1-i;return t.x1=o*s-a*r+e,t.y1=o*r+a*s+i,o=t.x2-e,a=t.y2-i,t.x2=o*s-a*r+e,t.y2=o*r+a*s+i,o=t.x3-e,a=t.y3-i,t.x3=o*s-a*r+e,t.y3=o*r+a*s+i,t}},function(t,e,i){t.exports={BUTTON_DOWN:i(1189),BUTTON_UP:i(1190),CONNECTED:i(1191),DISCONNECTED:i(1192),GAMEPAD_BUTTON_DOWN:i(1193),GAMEPAD_BUTTON_UP:i(1194)}},function(t,e,i){var n=i(17),s=i(135);t.exports=function(t,e){var i=void 0===t?s():n({},t);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},function(t,e,i){var n=i(0),s=i(20),r=i(21),o=i(8),a=i(2),h=i(7),l=i(358),u=new n({Extends:r,initialize:function(t,e,i,n){var s="xml";if(h(e)){var o=e;e=a(o,"key"),i=a(o,"url"),n=a(o,"xhrSettings"),s=a(o,"extension",s)}var l={type:"xml",cache:t.cacheManager.xml,extension:s,responseType:"text",key:e,url:i,xhrSettings:n};r.call(this,t,l)},onProcess:function(){this.state=s.FILE_PROCESSING,this.data=l(this.xhrLoader.responseText),this.data?this.onProcessComplete():(console.warn("Invalid XMLFile: "+this.key),this.onProcessError())}});o.register("xml",function(t,e,i){if(Array.isArray(t))for(var n=0;n0?1:.7),e.damping=e.damping||0,e.angularStiffness=e.angularStiffness||0,e.angleA=e.bodyA?e.bodyA.angle:e.angleA,e.angleB=e.bodyB?e.bodyB.angle:e.angleB,e.plugin={};var o={visible:!0,type:"line",anchors:!0,lineColor:null,lineOpacity:null,lineThickness:null,pinSize:null,anchorColor:null,anchorSize:null};return 0===e.length&&e.stiffness>.1?(o.type="pin",o.anchors=!1):e.stiffness<.9&&(o.type="spring"),e.render=l.extend(o,e.render),e},n.preSolveAll=function(t){for(var e=0;e0&&(c.position.x+=l.x,c.position.y+=l.y),0!==l.angle&&(s.rotate(c.vertices,l.angle,i.position),h.rotate(c.axes,l.angle),u>0&&r.rotateAbout(c.position,l.angle,i.position,c.position)),a.update(c.bounds,c.vertices,i.velocity)}l.angle*=n._warming,l.x*=n._warming,l.y*=n._warming}}},n.pointAWorld=function(t){return{x:(t.bodyA?t.bodyA.position.x:0)+t.pointA.x,y:(t.bodyA?t.bodyA.position.y:0)+t.pointA.y}},n.pointBWorld=function(t){return{x:(t.bodyB?t.bodyB.position.x:0)+t.pointB.x,y:(t.bodyB?t.bodyB.position.y:0)+t.pointB.y}}},function(t,e,i){var n=i(138);t.exports=function(t,e,i){var s=n(t,e,!0,i),r=n(t,e-1,!0,i),o=n(t,e+1,!0,i),a=n(t-1,e,!0,i),h=n(t+1,e,!0,i),l=s&&s.collides;return l&&(s.faceTop=!0,s.faceBottom=!0,s.faceLeft=!0,s.faceRight=!0),r&&r.collides&&(l&&(s.faceTop=!1),r.faceBottom=!l),o&&o.collides&&(l&&(s.faceBottom=!1),o.faceTop=!l),a&&a.collides&&(l&&(s.faceLeft=!1),a.faceRight=!l),h&&h.collides&&(l&&(s.faceRight=!1),h.faceLeft=!l),s&&!s.collides&&s.resetFaces(),s}},function(t,e,i){var n=i(74),s=i(103),r=i(217),o=i(73);t.exports=function(t,e,i,a,h){if(!s(e,i,h))return null;void 0===a&&(a=!0);var l=h.data[i][e],u=l&&l.collides;if(t instanceof n)null===h.data[i][e]&&(h.data[i][e]=new n(h,t.index,e,i,t.width,t.height)),h.data[i][e].copy(t);else{var c=t;null===h.data[i][e]?h.data[i][e]=new n(h,c,e,i,h.tileWidth,h.tileHeight):h.data[i][e].index=c}var d=h.data[i][e],f=-1!==h.collideIndexes.indexOf(d.index);return o(d,f),a&&u!==d.collides&&r(e,i,h),d}},function(t,e){t.exports=function(t,e,i){var n=i.collideIndexes.indexOf(t);e&&-1===n?i.collideIndexes.push(t):e||-1===n||i.collideIndexes.splice(n,1)}},function(t,e,i){var n=i(31),s=i(104),r=i(105),o=i(74);t.exports=function(t,e,i,a,h){for(var l=new s({tileWidth:i,tileHeight:a}),u=new r({name:t,tileWidth:i,tileHeight:a,format:n.ARRAY_2D,layers:[l]}),c=[],d=e.length,f=0,p=0;p0&&(s.totalDuration+=s.t2*s.repeat),s.totalDuration>t&&(t=s.totalDuration),s.delay0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay,this.startDelay=e},init:function(){if(this.paused&&!this.parentIsTimeline)return this.state=h.PENDING_ADD,this._pausedState=h.INIT,!1;for(var t=this.data,e=this.totalTargets,i=0;i0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweenData(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=h.LOOP_DELAY):(this.state=h.ACTIVE,this.dispatchTweenEvent(r.TWEEN_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=h.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=h.PENDING_REMOVE,this.dispatchTweenEvent(r.TWEEN_COMPLETE,this.callbacks.onComplete))},pause:function(){return this.state===h.PAUSED?this:(this.paused=!0,this._pausedState=this.state,this.state=h.PAUSED,this)},play:function(t){void 0===t&&(t=!1);var e=this.state;return e!==h.INIT||this.parentIsTimeline?e===h.ACTIVE||e===h.PENDING_ADD&&this._pausedState===h.PENDING_ADD?this:this.parentIsTimeline||e!==h.PENDING_REMOVE&&e!==h.REMOVED?(this.parentIsTimeline?(this.resetTweenData(t),0===this.calculatedOffset?this.state=h.ACTIVE:(this.countdown=this.calculatedOffset,this.state=h.OFFSET_DELAY)):this.paused?(this.paused=!1,this.makeActive()):(this.resetTweenData(t),this.state=h.ACTIVE,this.makeActive()),this):(this.seek(0),this.parent.makeActive(this),this):(this.resetTweenData(!1),this.state=h.ACTIVE,this)},resetTweenData:function(t){for(var e=this.data,i=this.totalData,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY),r.getActiveValue&&(o[a]=r.getActiveValue(r.target,r.key,r.start))}},resume:function(){return this.state===h.PAUSED?(this.paused=!1,this.state=this._pausedState):this.play(),this},seek:function(t,e){if(void 0===e&&(e=16.6),this.totalDuration>=36e5)return console.warn("Tween.seek duration too long"),this;this.state===h.REMOVED&&this.makeActive(),this.elapsed=0,this.progress=0,this.totalElapsed=0,this.totalProgress=0;for(var i=this.data,n=this.totalTargets,s=0;s0&&(r.elapsed=r.delay,r.state=h.DELAY)}this.calcDuration();var c=!1;this.state===h.PAUSED&&(c=!0,this.state=h.ACTIVE),this.isSeeking=!0;do{this.update(0,e)}while(this.totalProgress0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.start=e.getStartValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},setStateFromStart:function(t,e,i){return e.repeatCounter>0?(e.repeatCounter--,e.elapsed=i,e.progress=i/e.duration,e.flipX&&e.target.toggleFlipX(),e.flipY&&e.target.toggleFlipY(),e.end=e.getEndValue(e.target,e.key,e.start,e.index,t.totalTargets,t),e.repeatDelay>0?(e.elapsed=e.repeatDelay-i,e.current=e.start,e.target[e.key]=e.current,h.REPEAT_DELAY):(this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e),h.PLAYING_FORWARD)):h.COMPLETE},updateTweenData:function(t,e,i){var n=e.target;switch(e.state){case h.PLAYING_FORWARD:case h.PLAYING_BACKWARD:if(!n){e.state=h.COMPLETE;break}var s=e.elapsed,o=e.duration,a=0;(s+=i)>o&&(a=s-o,s=o);var l=e.state===h.PLAYING_FORWARD,u=s/o;if(e.elapsed=s,e.progress=u,e.previous=e.current,1===u)l?(e.current=e.end,n[e.key]=e.end,e.hold>0?(e.elapsed=e.hold-a,e.state=h.HOLD_DELAY):e.state=this.setStateFromEnd(t,e,a)):(e.current=e.start,n[e.key]=e.start,e.state=this.setStateFromStart(t,e,a));else{var c=l?e.ease(u):e.ease(1-u);e.current=e.start+(e.end-e.start)*c,n[e.key]=e.current}this.dispatchTweenDataEvent(r.TWEEN_UPDATE,t.callbacks.onUpdate,e);break;case h.DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PENDING_RENDER);break;case h.REPEAT_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.elapsed=Math.abs(e.elapsed),e.state=h.PLAYING_FORWARD,this.dispatchTweenDataEvent(r.TWEEN_REPEAT,t.callbacks.onRepeat,e));break;case h.HOLD_DELAY:e.elapsed-=i,e.elapsed<=0&&(e.state=this.setStateFromEnd(t,e,Math.abs(e.elapsed)));break;case h.PENDING_RENDER:n?(e.start=e.getStartValue(n,e.key,n[e.key],e.index,t.totalTargets,t),e.end=e.getEndValue(n,e.key,e.start,e.index,t.totalTargets,t),e.current=e.start,n[e.key]=e.start,e.state=h.PLAYING_FORWARD):e.state=h.COMPLETE}return e.state!==h.COMPLETE}});u.TYPES=["onActive","onComplete","onLoop","onRepeat","onStart","onUpdate","onYoyo"],a.register("tween",function(t){return this.scene.sys.tweens.add(t)}),o.register("tween",function(t){return this.scene.sys.tweens.create(t)}),t.exports=u},function(t,e,i){t.exports={TIMELINE_COMPLETE:i(1346),TIMELINE_LOOP:i(1347),TIMELINE_PAUSE:i(1348),TIMELINE_RESUME:i(1349),TIMELINE_START:i(1350),TIMELINE_UPDATE:i(1351),TWEEN_ACTIVE:i(1352),TWEEN_COMPLETE:i(1353),TWEEN_LOOP:i(1354),TWEEN_REPEAT:i(1355),TWEEN_START:i(1356),TWEEN_UPDATE:i(1357),TWEEN_YOYO:i(1358)}},function(t,e){t.exports=function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p){return{target:t,index:e,key:i,getActiveValue:r,getEndValue:n,getStartValue:s,ease:o,duration:0,totalDuration:0,delay:0,yoyo:l,hold:0,repeat:0,repeatDelay:0,flipX:f,flipY:p,progress:0,elapsed:0,repeatCounter:0,start:0,previous:0,current:0,end:0,t1:0,t2:0,gen:{delay:a,duration:h,hold:u,repeat:c,repeatDelay:d},state:0}}},function(t,e){t.exports={DEFAULT:0,LINEAR:0,NEAREST:1}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-Math.PI,Math.PI)}},function(t,e,i){var n=i(58);t.exports=function(t){return n(t,-180,180)}},function(t,e,i){var n=i(0),s=i(10),r=new n({initialize:function(t){this.name="WebGLPipeline",this.game=t.game,this.view=t.game.canvas,this.resolution=1,this.width=0,this.height=0,this.gl=t.gl,this.vertexCount=0,this.vertexCapacity=t.vertexCapacity,this.renderer=t.renderer,this.vertexData=t.vertices?t.vertices:new ArrayBuffer(t.vertexCapacity*t.vertexSize),this.vertexBuffer=this.renderer.createVertexBuffer(t.vertices?t.vertices:this.vertexData.byteLength,this.gl.STREAM_DRAW),this.program=this.renderer.createProgram(t.vertShader,t.fragShader),this.attributes=t.attributes,this.vertexSize=t.vertexSize,this.topology=t.topology,this.bytes=new Uint8Array(this.vertexData),this.vertexComponentCount=s.getComponentCount(t.attributes,this.gl),this.flushLocked=!1,this.active=!1},boot:function(){},addAttribute:function(t,e,i,n,r){return this.attributes.push({name:t,size:e,type:this.renderer.glFormats[i],normalized:n,offset:r}),this.vertexComponentCount=s.getComponentCount(this.attributes,this.gl),this},shouldFlush:function(){return this.vertexCount>=this.vertexCapacity},resize:function(t,e,i){return this.width=t*i,this.height=e*i,this.resolution=i,this},bind:function(){var t=this.gl,e=this.vertexBuffer,i=this.attributes,n=this.program,s=this.renderer,r=this.vertexSize;s.setProgram(n),s.setVertexBuffer(e);for(var o=0;o=0?(t.enableVertexAttribArray(h),t.vertexAttribPointer(h,a.size,a.type,a.normalized,r,a.offset)):-1!==h&&t.disableVertexAttribArray(h)}return this},onBind:function(){return this},onPreRender:function(){return this},onRender:function(){return this},onPostRender:function(){return this},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t=this.gl,e=this.vertexCount,i=this.topology,n=this.vertexSize;if(0!==e)return t.bufferSubData(t.ARRAY_BUFFER,0,this.bytes.subarray(0,e*n)),t.drawArrays(i,0,e),this.vertexCount=0,this.flushLocked=!1,this;this.flushLocked=!1},destroy:function(){var t=this.gl;return t.deleteProgram(this.program),t.deleteBuffer(this.vertexBuffer),delete this.program,delete this.vertexBuffer,delete this.gl,this},setFloat1:function(t,e){return this.renderer.setFloat1(this.program,t,e),this},setFloat2:function(t,e,i){return this.renderer.setFloat2(this.program,t,e,i),this},setFloat3:function(t,e,i,n){return this.renderer.setFloat3(this.program,t,e,i,n),this},setFloat4:function(t,e,i,n,s){return this.renderer.setFloat4(this.program,t,e,i,n,s),this},setFloat1v:function(t,e){return this.renderer.setFloat1v(this.program,t,e),this},setFloat2v:function(t,e){return this.renderer.setFloat2v(this.program,t,e),this},setFloat3v:function(t,e){return this.renderer.setFloat3v(this.program,t,e),this},setFloat4v:function(t,e){return this.renderer.setFloat4v(this.program,t,e),this},setInt1:function(t,e){return this.renderer.setInt1(this.program,t,e),this},setInt2:function(t,e,i){return this.renderer.setInt2(this.program,t,e,i),this},setInt3:function(t,e,i,n){return this.renderer.setInt3(this.program,t,e,i,n),this},setInt4:function(t,e,i,n,s){return this.renderer.setInt4(this.program,t,e,i,n,s),this},setMatrix2:function(t,e,i){return this.renderer.setMatrix2(this.program,t,e,i),this},setMatrix3:function(t,e,i){return this.renderer.setMatrix3(this.program,t,e,i),this},setMatrix4:function(t,e,i){return this.renderer.setMatrix4(this.program,t,e,i),this}});t.exports=r},function(t,e,i){var n=i(0),s=i(66),r=i(2),o=i(506),a=i(779),h=i(780),l=i(32),u=i(10),c=i(234),d=new n({Extends:c,Mixins:[o],initialize:function(t){var e=t.renderer.config;c.call(this,{game:t.game,renderer:t.renderer,gl:t.renderer.gl,topology:r(t,"topology",t.renderer.gl.TRIANGLES),vertShader:r(t,"vertShader",h),fragShader:r(t,"fragShader",a),vertexCapacity:r(t,"vertexCapacity",6*e.batchSize),vertexSize:r(t,"vertexSize",5*Float32Array.BYTES_PER_ELEMENT+4*Uint8Array.BYTES_PER_ELEMENT),attributes:[{name:"inPosition",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:0},{name:"inTexCoord",size:2,type:t.renderer.gl.FLOAT,normalized:!1,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"inTintEffect",size:1,type:t.renderer.gl.FLOAT,normalized:!1,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"inTint",size:4,type:t.renderer.gl.UNSIGNED_BYTE,normalized:!0,offset:5*Float32Array.BYTES_PER_ELEMENT}]}),this.vertexViewF32=new Float32Array(this.vertexData),this.vertexViewU32=new Uint32Array(this.vertexData),this.maxQuads=e.batchSize,this.batches=[],this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.tempTriangle=[{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0},{x:0,y:0,width:0}],this.tintEffect=2,this.strokeTint={TL:0,TR:0,BL:0,BR:0},this.fillTint={TL:0,TR:0,BL:0,BR:0},this.currentFrame={u0:0,v0:0,u1:1,v1:1},this.firstQuad=[0,0,0,0,0],this.prevQuad=[0,0,0,0,0],this.polygonCache=[],this.mvpInit()},onBind:function(){return c.prototype.onBind.call(this),this.mvpUpdate(),this},resize:function(t,e,i){return c.prototype.resize.call(this,t,e,i),this.projOrtho(0,this.width,this.height,0,-1e3,1e3),this},setTexture2D:function(t,e){return void 0===t&&(t=this.renderer.blankTexture.glTexture),void 0===e&&(e=0),this.requireTextureBatch(t,e)&&this.pushBatch(t,e),this},requireTextureBatch:function(t,e){var i=this.batches,n=i.length;return!(n>0)||!((e>0?i[n-1].textures[e-1]:i[n-1].texture)===t)},pushBatch:function(t,e){if(0===e)this.batches.push({first:this.vertexCount,texture:t,textures:[]});else{var i=[];i[e-1]=t,this.batches.push({first:this.vertexCount,texture:null,textures:i})}},flush:function(){if(this.flushLocked)return this;this.flushLocked=!0;var t,e,i,n=this.gl,s=this.vertexCount,r=this.topology,o=this.vertexSize,a=this.renderer,h=this.batches,l=h.length,u=0,c=null;if(0===l||0===s)return this.flushLocked=!1,this;n.bufferSubData(n.ARRAY_BUFFER,0,this.bytes.subarray(0,s*o));for(var d=0;d0){for(e=0;e0){for(e=0;e0&&(a.setTexture2D(c.texture,0,!1),n.drawArrays(r,c.first,u)),this.vertexCount=0,h.length=0,this.flushLocked=!1,this},batchSprite:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix1,s=this._tempMatrix2,r=this._tempMatrix3,o=t.frame,a=o.glTexture,h=o.u0,l=o.v0,c=o.u1,d=o.v1,f=o.x,p=o.y,g=o.cutWidth,v=o.cutHeight,m=o.customPivot,y=t.displayOriginX,x=t.displayOriginY,T=-y+f,w=-x+p;if(t.isCropped){var b=t._crop;b.flipX===t.flipX&&b.flipY===t.flipY||o.updateCropUVs(b,t.flipX,t.flipY),h=b.u0,l=b.v0,c=b.u1,d=b.v1,g=b.width,v=b.height,T=-y+(f=b.x),w=-x+(p=b.y)}var E=1,S=1;t.flipX&&(m||(T+=-o.realWidth+2*y),E=-1),(t.flipY||o.source.isGLTexture&&!a.flipY)&&(m||(w+=-o.realHeight+2*x),S=-1),s.applyITRS(t.x,t.y,t.rotation,t.scaleX*E,t.scaleY*S),n.copyFrom(e.matrix),i?(n.multiplyWithOffset(i,-e.scrollX*t.scrollFactorX,-e.scrollY*t.scrollFactorY),s.e=t.x,s.f=t.y,n.multiply(s,r)):(s.e-=e.scrollX*t.scrollFactorX,s.f-=e.scrollY*t.scrollFactorY,n.multiply(s,r));var A=T+g,_=w+v,C=r.getX(T,w),M=r.getY(T,w),O=r.getX(T,_),P=r.getY(T,_),R=r.getX(A,_),L=r.getY(A,_),k=r.getX(A,w),D=r.getY(A,w),F=u.getTintAppendFloatAlpha(t._tintTL,e.alpha*t._alphaTL),I=u.getTintAppendFloatAlpha(t._tintTR,e.alpha*t._alphaTR),B=u.getTintAppendFloatAlpha(t._tintBL,e.alpha*t._alphaBL),N=u.getTintAppendFloatAlpha(t._tintBR,e.alpha*t._alphaBR);e.roundPixels&&(C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P),R=Math.round(R),L=Math.round(L),k=Math.round(k),D=Math.round(D)),this.setTexture2D(a,0);var Y=t._isTinted&&t.tintFill;this.batchQuad(C,M,O,P,R,L,k,D,h,l,c,d,F,I,B,N,Y,a,0)},batchQuad:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y){var x=!1;this.vertexCount+6>this.vertexCapacity&&(this.flush(),x=!0,this.setTexture2D(m,y));var T=this.vertexViewF32,w=this.vertexViewU32,b=this.vertexCount*this.vertexComponentCount-1;return T[++b]=t,T[++b]=e,T[++b]=h,T[++b]=l,T[++b]=v,w[++b]=d,T[++b]=i,T[++b]=n,T[++b]=h,T[++b]=c,T[++b]=v,w[++b]=p,T[++b]=s,T[++b]=r,T[++b]=u,T[++b]=c,T[++b]=v,w[++b]=g,T[++b]=t,T[++b]=e,T[++b]=h,T[++b]=l,T[++b]=v,w[++b]=d,T[++b]=s,T[++b]=r,T[++b]=u,T[++b]=c,T[++b]=v,w[++b]=g,T[++b]=o,T[++b]=a,T[++b]=u,T[++b]=l,T[++b]=v,w[++b]=f,this.vertexCount+=6,x},batchTri:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g){var v=!1;this.vertexCount+3>this.vertexCapacity&&(this.flush(),this.setTexture2D(p,g),v=!0);var m=this.vertexViewF32,y=this.vertexViewU32,x=this.vertexCount*this.vertexComponentCount-1;return m[++x]=t,m[++x]=e,m[++x]=o,m[++x]=a,m[++x]=f,y[++x]=u,m[++x]=i,m[++x]=n,m[++x]=o,m[++x]=l,m[++x]=f,y[++x]=c,m[++x]=s,m[++x]=r,m[++x]=h,m[++x]=l,m[++x]=f,y[++x]=d,this.vertexCount+=3,v},batchTexture:function(t,e,i,n,s,r,o,a,h,l,u,c,d,f,p,g,v,m,y,x,T,w,b,E,S,A,_,C,M,O,P){this.renderer.setPipeline(this,t);var R=this._tempMatrix1,L=this._tempMatrix2,k=this._tempMatrix3,D=m/i+_,F=y/n+C,I=(m+x)/i+_,B=(y+T)/n+C,N=o,Y=a,X=-g,z=-v;if(t.isCropped){var U=t._crop;N=U.width,Y=U.height,o=U.width,a=U.height;var G=m=U.x,W=y=U.y;c&&(G=x-U.x-U.width),d&&!e.isRenderTexture&&(W=T-U.y-U.height),D=G/i+_,F=W/n+C,I=(G+U.width)/i+_,B=(W+U.height)/n+C,X=-g+m,z=-v+y}d^=!P&&e.isRenderTexture?1:0,c&&(N*=-1,X+=o),d&&(Y*=-1,z+=a);var V=X+N,H=z+Y;L.applyITRS(s,r,u,h,l),R.copyFrom(M.matrix),O?(R.multiplyWithOffset(O,-M.scrollX*f,-M.scrollY*p),L.e=s,L.f=r,R.multiply(L,k)):(L.e-=M.scrollX*f,L.f-=M.scrollY*p,R.multiply(L,k));var j=k.getX(X,z),q=k.getY(X,z),K=k.getX(X,H),J=k.getY(X,H),Z=k.getX(V,H),Q=k.getY(V,H),$=k.getX(V,z),tt=k.getY(V,z);M.roundPixels&&(j=Math.round(j),q=Math.round(q),K=Math.round(K),J=Math.round(J),Z=Math.round(Z),Q=Math.round(Q),$=Math.round($),tt=Math.round(tt)),this.setTexture2D(e,0),this.batchQuad(j,q,K,J,Z,Q,$,tt,D,F,I,B,w,b,E,S,A,e,0)},batchTextureFrame:function(t,e,i,n,s,r,o){this.renderer.setPipeline(this);var a=this._tempMatrix1.copyFrom(r),h=this._tempMatrix2,l=e+t.width,c=i+t.height;o?a.multiply(o,h):h=a;var d=h.getX(e,i),f=h.getY(e,i),p=h.getX(e,c),g=h.getY(e,c),v=h.getX(l,c),m=h.getY(l,c),y=h.getX(l,i),x=h.getY(l,i);this.setTexture2D(t.glTexture,0),n=u.getTintAppendFloatAlpha(n,s),this.batchQuad(d,f,p,g,v,m,y,x,t.u0,t.v0,t.u1,t.v1,n,n,n,n,0,t.glTexture,0)},drawFillRect:function(t,e,i,n,s,r){var o=t+i,a=e+n;this.setTexture2D();var h=u.getTintAppendFloatAlphaAndSwap(s,r);this.batchQuad(t,e,t,a,o,a,o,e,0,0,1,1,h,h,h,h,2)},batchFillRect:function(t,e,i,n,s,r){this.renderer.setPipeline(this);var o=this._tempMatrix3;r&&r.multiply(s,o);var a=t+i,h=e+n,l=o.getX(t,e),u=o.getY(t,e),c=o.getX(t,h),d=o.getY(t,h),f=o.getX(a,h),p=o.getY(a,h),g=o.getX(a,e),v=o.getY(a,e),m=this.currentFrame,y=m.u0,x=m.v0,T=m.u1,w=m.v1;this.batchQuad(l,u,c,d,f,p,g,v,y,x,T,w,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.fillTint.BR,this.tintEffect)},batchFillTriangle:function(t,e,i,n,s,r,o,a){this.renderer.setPipeline(this);var h=this._tempMatrix3;a&&a.multiply(o,h);var l=h.getX(t,e),u=h.getY(t,e),c=h.getX(i,n),d=h.getY(i,n),f=h.getX(s,r),p=h.getY(s,r),g=this.currentFrame,v=g.u0,m=g.v0,y=g.u1,x=g.v1;this.batchTri(l,u,c,d,f,p,v,m,y,x,this.fillTint.TL,this.fillTint.TR,this.fillTint.BL,this.tintEffect)},batchStrokeTriangle:function(t,e,i,n,s,r,o,a,h){var l=this.tempTriangle;l[0].x=t,l[0].y=e,l[0].width=o,l[1].x=i,l[1].y=n,l[1].width=o,l[2].x=s,l[2].y=r,l[2].width=o,l[3].x=t,l[3].y=e,l[3].width=o,this.batchStrokePath(l,o,!1,a,h)},batchFillPath:function(t,e,i){this.renderer.setPipeline(this);var n=this._tempMatrix3;i&&i.multiply(e,n);for(var r,o,a=t.length,h=this.polygonCache,l=this.fillTint.TL,u=this.fillTint.TR,c=this.fillTint.BL,d=this.tintEffect,f=0;f0&&H[4]?this.batchQuad(k,D,O,P,H[0],H[1],H[2],H[3],U,G,W,V,B,N,Y,X,I):(j[0]=k,j[1]=D,j[2]=O,j[3]=P,j[4]=1),h&&j[4]?this.batchQuad(C,M,R,L,j[0],j[1],j[2],j[3],U,G,W,V,B,N,Y,X,I):(H[0]=C,H[1]=M,H[2]=R,H[3]=L,H[4]=1)}}});t.exports=d},function(t,e,i){var n={};t.exports=n;var s=i(237);n._motionWakeThreshold=.18,n._motionSleepThreshold=.08,n._minBias=.9,n.update=function(t,e){for(var i=e*e*e,s=0;s0&&r.motion=r.sleepThreshold&&n.set(r,!0)):r.sleepCounter>0&&(r.sleepCounter-=1)}else n.set(r,!1)}},n.afterCollisions=function(t,e){for(var i=e*e*e,s=0;sn._motionWakeThreshold*i&&n.set(l,!1)}}}},n.set=function(t,e){var i=t.isSleeping;e?(t.isSleeping=!0,t.sleepCounter=t.sleepThreshold,t.positionImpulse.x=0,t.positionImpulse.y=0,t.positionPrev.x=t.position.x,t.positionPrev.y=t.position.y,t.anglePrev=t.angle,t.speed=0,t.angularSpeed=0,t.motion=0,i||s.trigger(t,"sleepStart")):(t.isSleeping=!1,t.sleepCounter=0,i&&s.trigger(t,"sleepEnd"))}},function(t,e,i){var n={};t.exports=n;var s=i(37);n.on=function(t,e,i){for(var n,s=e.split(" "),r=0;r0){i||(i={}),n=e.split(" ");for(var l=0;le.length&&(r=e.length),i?(n=e[r-1][i],(s=e[r][i])-t<=t-n?e[r]:e[r-1]):(n=e[r-1],(s=e[r])-t<=t-n?s:n)}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.textureKey=t,this.textureFrame=e,this.index=i,this.frame=n,this.isFirst=!1,this.isLast=!1,this.prevFrame=null,this.nextFrame=null,this.duration=0,this.progress=0},toJSON:function(){return{key:this.textureKey,frame:this.textureFrame,duration:this.duration}},destroy:function(){this.frame=void 0}});t.exports=n},function(t,e,i){var n=i(52),s={_blendMode:n.NORMAL,blendMode:{get:function(){return this._blendMode},set:function(t){"string"==typeof t&&(t=n[t]),(t|=0)>=-1&&(this._blendMode=t)}},setBlendMode:function(t){return this.blendMode=t,this}};t.exports=s},function(t,e){var i={_depth:0,depth:{get:function(){return this._depth},set:function(t){this.scene.sys.queueDepthSort(),this._depth=t}},setDepth:function(t){return void 0===t&&(t=0),this.depth=t,this}};t.exports=i},function(t,e,i){var n=i(149),s=i(112);t.exports=function(t,e,i,r){void 0===r&&(r=[]),e||(e=s(t)/i);for(var o=0;o=t.right&&(h=1,a+=o-t.right,o=t.right);break;case 1:(a+=e)>=t.bottom&&(h=2,o-=a-t.bottom,a=t.bottom);break;case 2:(o-=e)<=t.left&&(h=3,a-=t.left-o,o=t.left);break;case 3:(a-=e)<=t.top&&(h=0,a=t.top)}return r}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);for(var i=null,n=0;n-h&&(c-=h,n+=l),fd.right&&(f=u(f,f+(g-d.right),this.lerp.x)),vd.bottom&&(p=u(p,p+(v-d.bottom),this.lerp.y))):(f=u(f,g-h,this.lerp.x),p=u(p,v-l,this.lerp.y))}this.useBounds&&(f=this.clampX(f),p=this.clampY(p)),this.roundPixels&&(h=Math.round(h),l=Math.round(l)),this.scrollX=f,this.scrollY=p;var m=f+n,y=p+s;this.midPoint.set(m,y);var x=e/o,T=i/o;this.worldView.setTo(m-x/2,y-T/2,x,T),a.applyITRS(this.x+h,this.y+l,this.rotation,o,o),a.translate(-h,-l),this.shakeEffect.preRender()},setLerp:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=t),this.lerp.set(t,e),this},setFollowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.followOffset.set(t,e),this},startFollow:function(t,e,i,n,s,r){void 0===e&&(e=!1),void 0===i&&(i=1),void 0===n&&(n=i),void 0===s&&(s=0),void 0===r&&(r=s),this._follow=t,this.roundPixels=e,i=o(i,0,1),n=o(n,0,1),this.lerp.set(i,n),this.followOffset.set(s,r);var a=this.width/2,h=this.height/2,l=t.x-s,u=t.y-r;return this.midPoint.set(l,u),this.scrollX=l-a,this.scrollY=u-h,this.useBounds&&(this.scrollX=this.clampX(this.scrollX),this.scrollY=this.clampY(this.scrollY)),this},stopFollow:function(){return this._follow=null,this},resetFX:function(){return this.panEffect.reset(),this.shakeEffect.reset(),this.flashEffect.reset(),this.fadeEffect.reset(),this},update:function(t,e){this.visible&&(this.panEffect.update(t,e),this.zoomEffect.update(t,e),this.shakeEffect.update(t,e),this.flashEffect.update(t,e),this.fadeEffect.update(t,e))},destroy:function(){this.clearRenderToTexture(),this.resetFX(),n.prototype.destroy.call(this),this._follow=null,this.deadzone=null}});t.exports=f},function(t,e,i){var n=i(33);t.exports=function(t){var e=new n;t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,n){return e+e+i+i+n+n});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e.setTo(s,r,o)}return e}},function(t,e){t.exports=function(t,e,i,n){return n<<24|t<<16|e<<8|i}},function(t,e){t.exports=function(t,e,i,n){void 0===n&&(n={h:0,s:0,v:0}),t/=255,e/=255,i/=255;var s=Math.min(t,e,i),r=Math.max(t,e,i),o=r-s,a=0,h=0===r?0:o/r,l=r;return r!==s&&(r===t?a=(e-i)/o+(e16777215?{a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{a:255,r:t>>16&255,g:t>>8&255,b:255&t}}},function(t,e,i){var n=i(33);t.exports=function(t){return new n(t.r,t.g,t.b,t.a)}},function(t,e,i){var n=i(33);t.exports=function(t){var e=new n,i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t.toLowerCase());if(i){var s=parseInt(i[1],10),r=parseInt(i[2],10),o=parseInt(i[3],10),a=void 0!==i[4]?parseFloat(i[4]):1;e.setTo(s,r,o,255*a)}return e}},function(t,e,i){t.exports={Fade:i(656),Flash:i(657),Pan:i(658),Shake:i(691),Zoom:i(692)}},function(t,e,i){t.exports={In:i(659),Out:i(660),InOut:i(661)}},function(t,e,i){t.exports={In:i(662),Out:i(663),InOut:i(664)}},function(t,e,i){t.exports={In:i(665),Out:i(666),InOut:i(667)}},function(t,e,i){t.exports={In:i(668),Out:i(669),InOut:i(670)}},function(t,e,i){t.exports={In:i(671),Out:i(672),InOut:i(673)}},function(t,e,i){t.exports={In:i(674),Out:i(675),InOut:i(676)}},function(t,e,i){t.exports=i(677)},function(t,e,i){t.exports={In:i(678),Out:i(679),InOut:i(680)}},function(t,e,i){t.exports={In:i(681),Out:i(682),InOut:i(683)}},function(t,e,i){t.exports={In:i(684),Out:i(685),InOut:i(686)}},function(t,e,i){t.exports={In:i(687),Out:i(688),InOut:i(689)}},function(t,e,i){t.exports=i(690)},function(t,e,i){var n=i(0),s=i(29),r=i(312),o=i(2),a=i(6),h=i(7),l=i(168),u=i(1),c=i(173),d=i(161),f=new n({initialize:function(t){void 0===t&&(t={});this.width=a(t,"width",1024),this.height=a(t,"height",768),this.zoom=a(t,"zoom",1),this.resolution=a(t,"resolution",1),this.parent=a(t,"parent",void 0),this.scaleMode=a(t,"scaleMode",0),this.expandParent=a(t,"expandParent",!0),this.autoRound=a(t,"autoRound",!1),this.autoCenter=a(t,"autoCenter",0),this.resizeInterval=a(t,"resizeInterval",500),this.fullscreenTarget=a(t,"fullscreenTarget",null),this.minWidth=a(t,"minWidth",0),this.maxWidth=a(t,"maxWidth",0),this.minHeight=a(t,"minHeight",0),this.maxHeight=a(t,"maxHeight",0);var e=a(t,"scale",null);e&&(this.width=a(e,"width",this.width),this.height=a(e,"height",this.height),this.zoom=a(e,"zoom",this.zoom),this.resolution=a(e,"resolution",this.resolution),this.parent=a(e,"parent",this.parent),this.scaleMode=a(e,"mode",this.scaleMode),this.expandParent=a(e,"expandParent",this.expandParent),this.autoRound=a(e,"autoRound",this.autoRound),this.autoCenter=a(e,"autoCenter",this.autoCenter),this.resizeInterval=a(e,"resizeInterval",this.resizeInterval),this.fullscreenTarget=a(e,"fullscreenTarget",this.fullscreenTarget),this.minWidth=a(e,"min.width",this.minWidth),this.maxWidth=a(e,"max.width",this.maxWidth),this.minHeight=a(e,"min.height",this.minHeight),this.maxHeight=a(e,"max.height",this.maxHeight)),this.renderType=a(t,"type",s.AUTO),this.canvas=a(t,"canvas",null),this.context=a(t,"context",null),this.canvasStyle=a(t,"canvasStyle",null),this.customEnvironment=a(t,"customEnvironment",!1),this.sceneConfig=a(t,"scene",null),this.seed=a(t,"seed",[(Date.now()*Math.random()).toString()]),l.RND=new l.RandomDataGenerator(this.seed),this.gameTitle=a(t,"title",""),this.gameURL=a(t,"url","https://phaser.io"),this.gameVersion=a(t,"version",""),this.autoFocus=a(t,"autoFocus",!0),this.domCreateContainer=a(t,"dom.createContainer",!1),this.domBehindCanvas=a(t,"dom.behindCanvas",!1),this.inputKeyboard=a(t,"input.keyboard",!0),this.inputKeyboardEventTarget=a(t,"input.keyboard.target",window),this.inputKeyboardCapture=a(t,"input.keyboard.capture",[]),this.inputMouse=a(t,"input.mouse",!0),this.inputMouseEventTarget=a(t,"input.mouse.target",null),this.inputMouseCapture=a(t,"input.mouse.capture",!0),this.inputTouch=a(t,"input.touch",r.input.touch),this.inputTouchEventTarget=a(t,"input.touch.target",null),this.inputTouchCapture=a(t,"input.touch.capture",!0),this.inputActivePointers=a(t,"input.activePointers",1),this.inputSmoothFactor=a(t,"input.smoothFactor",0),this.inputWindowEvents=a(t,"input.windowEvents",!0),this.inputGamepad=a(t,"input.gamepad",!1),this.inputGamepadEventTarget=a(t,"input.gamepad.target",window),this.disableContextMenu=a(t,"disableContextMenu",!1),this.audio=a(t,"audio"),this.hideBanner=!1===a(t,"banner",null),this.hidePhaser=a(t,"banner.hidePhaser",!1),this.bannerTextColor=a(t,"banner.text","#ffffff"),this.bannerBackgroundColor=a(t,"banner.background",["#ff0000","#ffff00","#00ff00","#00ffff","#000000"]),""===this.gameTitle&&this.hidePhaser&&(this.hideBanner=!0),this.fps=a(t,"fps",null);var i=a(t,"render",t);this.antialias=a(i,"antialias",!0),this.antialiasGL=a(i,"antialiasGL",!0),this.mipmapFilter=a(i,"mipmapFilter","LINEAR"),this.desynchronized=a(i,"desynchronized",!1),this.roundPixels=a(i,"roundPixels",!1),this.pixelArt=a(i,"pixelArt",1!==this.zoom),this.pixelArt&&(this.antialias=!1,this.roundPixels=!0),this.transparent=a(i,"transparent",!1),this.clearBeforeRender=a(i,"clearBeforeRender",!0),this.premultipliedAlpha=a(i,"premultipliedAlpha",!0),this.failIfMajorPerformanceCaveat=a(i,"failIfMajorPerformanceCaveat",!1),this.powerPreference=a(i,"powerPreference","default"),this.batchSize=a(i,"batchSize",2e3),this.maxLights=a(i,"maxLights",10);var n=a(t,"backgroundColor",0);this.backgroundColor=d(n),0===n&&this.transparent&&(this.backgroundColor.alpha=0),this.preBoot=a(t,"callbacks.preBoot",u),this.postBoot=a(t,"callbacks.postBoot",u),this.physics=a(t,"physics",{}),this.defaultPhysicsSystem=a(this.physics,"default",!1),this.loaderBaseURL=a(t,"loader.baseURL",""),this.loaderPath=a(t,"loader.path",""),this.loaderMaxParallelDownloads=a(t,"loader.maxParallelDownloads",32),this.loaderCrossOrigin=a(t,"loader.crossOrigin",void 0),this.loaderResponseType=a(t,"loader.responseType",""),this.loaderAsync=a(t,"loader.async",!0),this.loaderUser=a(t,"loader.user",""),this.loaderPassword=a(t,"loader.password",""),this.loaderTimeout=a(t,"loader.timeout",0),this.installGlobalPlugins=[],this.installScenePlugins=[];var f=a(t,"plugins",null),p=c.DefaultScene;f&&(Array.isArray(f)?this.defaultPlugins=f:h(f)&&(this.installGlobalPlugins=o(f,"global",[]),this.installScenePlugins=o(f,"scene",[]),Array.isArray(f.default)?p=f.default:Array.isArray(f.defaultMerge)&&(p=p.concat(f.defaultMerge)))),this.defaultPlugins=p;var g="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg";this.defaultImage=a(t,"images.default",g+"AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="),this.missingImage=a(t,"images.missing",g+"CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="),window&&(window.FORCE_WEBGL?this.renderType=s.WEBGL:window.FORCE_CANVAS&&(this.renderType=s.CANVAS))}});t.exports=f},function(t,e,i){t.exports={os:i(116),browser:i(117),features:i(167),input:i(721),audio:i(722),video:i(723),fullscreen:i(724),canvasFeatures:i(313)}},function(t,e,i){var n,s,r,o=i(26),a={supportInverseAlpha:!1,supportNewBlendModes:!1};t.exports=(void 0!==document&&(a.supportNewBlendModes=(n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",s="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",(r=new Image).onload=function(){var t=new Image;t.onload=function(){var e=o.create(t,6,1).getContext("2d");if(e.globalCompositeOperation="multiply",e.drawImage(r,0,0),e.drawImage(t,2,0),!e.getImageData(2,0,1,1))return!1;var i=e.getImageData(2,0,1,1).data;o.remove(t),a.supportNewBlendModes=255===i[0]&&0===i[1]&&0===i[2]},t.src=n+"/wCKxvRF"+s},r.src=n+"AP804Oa6"+s,!1),a.supportInverseAlpha=function(){var t=o.create(this,2,1).getContext("2d");t.fillStyle="rgba(10, 20, 30, 0.5)",t.fillRect(0,0,1,1);var e=t.getImageData(0,0,1,1);if(null===e)return!1;t.putImageData(e,1,0);var i=t.getImageData(1,0,1,1);return i.data[0]===e.data[0]&&i.data[1]===e.data[1]&&i.data[2]===e.data[2]&&i.data[3]===e.data[3]}()),a)},function(t,e){t.exports=function(t,e,i,n){return Math.atan2(n-e,i-t)}},function(t,e){t.exports=function(t){return(t%=2*Math.PI)>=0?t:t+2*Math.PI}},function(t,e){t.exports=function(t,e,i,n){var s=t-i,r=e-n;return s*s+r*r}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t>e-i}},function(t,e){t.exports=function(t,e,i){return void 0===i&&(i=1e-4),t0?Math.ceil(t):Math.floor(t)}},function(t,e,i){var n=i(3);t.exports=function(t,e,i,s,r,o,a,h){void 0===h&&(h=new n);var l=Math.sin(r),u=Math.cos(r),c=u*o,d=l*o,f=-l*a,p=u*a,g=1/(c*p+f*-d);return h.x=p*g*t+-f*g*e+(s*f-i*p)*g,h.y=c*g*e+-d*g*t+(-s*c+i*d)*g,h}},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n){this.x=0,this.y=0,this.z=0,this.w=0,"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},clone:function(){return new n(this.x,this.y,this.z,this.w)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z||0,this.w=t.w||0,this},equals:function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z||0,this.w+=t.w||0,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z||0,this.w-=t.w||0,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z||1,this.w*=t.w||1,this},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z||1,this.w/=t.w||1,this},distance:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return Math.sqrt(e*e+i*i+n*n+s*s)},distanceSq:function(t){var e=t.x-this.x,i=t.y-this.y,n=t.z-this.z||0,s=t.w-this.w||0;return e*e+i*i+n*n+s*s},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},transformMat4:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.val;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this},transformQuat:function(t){var e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,o=t.z,a=t.w,h=a*e+r*n-o*i,l=a*i+o*e-s*n,u=a*n+s*i-r*e,c=-s*e-r*i-o*n;return this.x=h*a+c*-s+l*-o-u*-r,this.y=l*a+c*-r+u*-s-h*-o,this.z=u*a+c*-o+h*-r-l*-s,this},reset:function(){return this.x=0,this.y=0,this.z=0,this.w=0,this}});n.prototype.sub=n.prototype.subtract,n.prototype.mul=n.prototype.multiply,n.prototype.div=n.prototype.divide,n.prototype.dist=n.prototype.distance,n.prototype.distSq=n.prototype.distanceSq,n.prototype.len=n.prototype.length,n.prototype.lenSq=n.prototype.lengthSq,t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(9),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this},fromMat4:function(t){var e=t.val,i=this.val;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[5];return t[1]=t[3],t[2]=t[6],t[3]=e,t[5]=t[7],t[6]=i,t[7]=n,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=l*r-o*h,c=-l*s+o*a,d=h*s-r*a,f=e*u+i*c+n*d;return f?(f=1/f,t[0]=u*f,t[1]=(-l*i+n*h)*f,t[2]=(o*i-n*r)*f,t[3]=c*f,t[4]=(l*e-n*a)*f,t[5]=(-o*e+n*s)*f,t[6]=d*f,t[7]=(-h*e+i*a)*f,t[8]=(r*e-i*s)*f,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return t[0]=r*l-o*h,t[1]=n*h-i*l,t[2]=i*o-n*r,t[3]=o*a-s*l,t[4]=e*l-n*a,t[5]=n*s-e*o,t[6]=s*h-r*a,t[7]=i*a-e*h,t[8]=e*r-i*s,this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*(l*r-o*h)+i*(-l*s+o*a)+n*(h*s-r*a)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=t.val,d=c[0],f=c[1],p=c[2],g=c[3],v=c[4],m=c[5],y=c[6],x=c[7],T=c[8];return e[0]=d*i+f*r+p*h,e[1]=d*n+f*o+p*l,e[2]=d*s+f*a+p*u,e[3]=g*i+v*r+m*h,e[4]=g*n+v*o+m*l,e[5]=g*s+v*a+m*u,e[6]=y*i+x*r+T*h,e[7]=y*n+x*o+T*l,e[8]=y*s+x*a+T*u,this},translate:function(t){var e=this.val,i=t.x,n=t.y;return e[6]=i*e[0]+n*e[3]+e[6],e[7]=i*e[1]+n*e[4]+e[7],e[8]=i*e[2]+n*e[5]+e[8],this},rotate:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=Math.sin(t),l=Math.cos(t);return e[0]=l*i+h*r,e[1]=l*n+h*o,e[2]=l*s+h*a,e[3]=l*r-h*i,e[4]=l*o-h*n,e[5]=l*a-h*s,this},scale:function(t){var e=this.val,i=t.x,n=t.y;return e[0]=i*e[0],e[1]=i*e[1],e[2]=i*e[2],e[3]=n*e[3],e[4]=n*e[4],e[5]=n*e[5],this},fromQuat:function(t){var e=t.x,i=t.y,n=t.z,s=t.w,r=e+e,o=i+i,a=n+n,h=e*r,l=e*o,u=e*a,c=i*o,d=i*a,f=n*a,p=s*r,g=s*o,v=s*a,m=this.val;return m[0]=1-(c+f),m[3]=l+v,m[6]=u-g,m[1]=l-v,m[4]=1-(h+f),m[7]=d+p,m[2]=u+g,m[5]=d-p,m[8]=1-(h+c),this},normalFromMat4:function(t){var e=t.val,i=this.val,n=e[0],s=e[1],r=e[2],o=e[3],a=e[4],h=e[5],l=e[6],u=e[7],c=e[8],d=e[9],f=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=n*h-s*a,T=n*l-r*a,w=n*u-o*a,b=s*l-r*h,E=s*u-o*h,S=r*u-o*l,A=c*v-d*g,_=c*m-f*g,C=c*y-p*g,M=d*m-f*v,O=d*y-p*v,P=f*y-p*m,R=x*P-T*O+w*M+b*C-E*_+S*A;return R?(R=1/R,i[0]=(h*P-l*O+u*M)*R,i[1]=(l*C-a*P-u*_)*R,i[2]=(a*O-h*C+u*A)*R,i[3]=(r*O-s*P-o*M)*R,i[4]=(n*P-r*C+o*_)*R,i[5]=(s*C-n*O-o*A)*R,i[6]=(v*S-m*E+y*b)*R,i[7]=(m*w-g*S-y*T)*R,i[8]=(g*E-v*w+y*x)*R,this):null}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t){this.val=new Float32Array(16),t?this.copy(t):this.identity()},clone:function(){return new n(this)},set:function(t){return this.copy(t)},copy:function(t){var e=this.val,i=t.val;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this},fromArray:function(t){var e=this.val;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},zero:function(){var t=this.val;return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=0,this},xyz:function(t,e,i){this.identity();var n=this.val;return n[12]=t,n[13]=e,n[14]=i,this},scaling:function(t,e,i){this.zero();var n=this.val;return n[0]=t,n[5]=e,n[10]=i,n[15]=1,this},identity:function(){var t=this.val;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},transpose:function(){var t=this.val,e=t[1],i=t[2],n=t[3],s=t[6],r=t[7],o=t[11];return t[1]=t[4],t[2]=t[8],t[3]=t[12],t[4]=e,t[6]=t[9],t[7]=t[13],t[8]=i,t[9]=s,t[11]=t[14],t[12]=n,t[13]=r,t[14]=o,this},invert:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15],m=e*o-i*r,y=e*a-n*r,x=e*h-s*r,T=i*a-n*o,w=i*h-s*o,b=n*h-s*a,E=l*p-u*f,S=l*g-c*f,A=l*v-d*f,_=u*g-c*p,C=u*v-d*p,M=c*v-d*g,O=m*M-y*C+x*_+T*A-w*S+b*E;return O?(O=1/O,t[0]=(o*M-a*C+h*_)*O,t[1]=(n*C-i*M-s*_)*O,t[2]=(p*b-g*w+v*T)*O,t[3]=(c*w-u*b-d*T)*O,t[4]=(a*A-r*M-h*S)*O,t[5]=(e*M-n*A+s*S)*O,t[6]=(g*x-f*b-v*y)*O,t[7]=(l*b-c*x+d*y)*O,t[8]=(r*C-o*A+h*E)*O,t[9]=(i*A-e*C-s*E)*O,t[10]=(f*w-p*x+v*m)*O,t[11]=(u*x-l*w-d*m)*O,t[12]=(o*S-r*_-a*E)*O,t[13]=(e*_-i*S+n*E)*O,t[14]=(p*y-f*T-g*m)*O,t[15]=(l*T-u*y+c*m)*O,this):null},adjoint:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return t[0]=o*(c*v-d*g)-u*(a*v-h*g)+p*(a*d-h*c),t[1]=-(i*(c*v-d*g)-u*(n*v-s*g)+p*(n*d-s*c)),t[2]=i*(a*v-h*g)-o*(n*v-s*g)+p*(n*h-s*a),t[3]=-(i*(a*d-h*c)-o*(n*d-s*c)+u*(n*h-s*a)),t[4]=-(r*(c*v-d*g)-l*(a*v-h*g)+f*(a*d-h*c)),t[5]=e*(c*v-d*g)-l*(n*v-s*g)+f*(n*d-s*c),t[6]=-(e*(a*v-h*g)-r*(n*v-s*g)+f*(n*h-s*a)),t[7]=e*(a*d-h*c)-r*(n*d-s*c)+l*(n*h-s*a),t[8]=r*(u*v-d*p)-l*(o*v-h*p)+f*(o*d-h*u),t[9]=-(e*(u*v-d*p)-l*(i*v-s*p)+f*(i*d-s*u)),t[10]=e*(o*v-h*p)-r*(i*v-s*p)+f*(i*h-s*o),t[11]=-(e*(o*d-h*u)-r*(i*d-s*u)+l*(i*h-s*o)),t[12]=-(r*(u*g-c*p)-l*(o*g-a*p)+f*(o*c-a*u)),t[13]=e*(u*g-c*p)-l*(i*g-n*p)+f*(i*c-n*u),t[14]=-(e*(o*g-a*p)-r*(i*g-n*p)+f*(i*a-n*o)),t[15]=e*(o*c-a*u)-r*(i*c-n*u)+l*(i*a-n*o),this},determinant:function(){var t=this.val,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],u=t[9],c=t[10],d=t[11],f=t[12],p=t[13],g=t[14],v=t[15];return(e*o-i*r)*(c*v-d*g)-(e*a-n*r)*(u*v-d*p)+(e*h-s*r)*(u*g-c*p)+(i*a-n*o)*(l*v-d*f)-(i*h-s*o)*(l*g-c*f)+(n*h-s*a)*(l*p-u*f)},multiply:function(t){var e=this.val,i=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],h=e[6],l=e[7],u=e[8],c=e[9],d=e[10],f=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=t.val,x=y[0],T=y[1],w=y[2],b=y[3];return e[0]=x*i+T*o+w*u+b*p,e[1]=x*n+T*a+w*c+b*g,e[2]=x*s+T*h+w*d+b*v,e[3]=x*r+T*l+w*f+b*m,x=y[4],T=y[5],w=y[6],b=y[7],e[4]=x*i+T*o+w*u+b*p,e[5]=x*n+T*a+w*c+b*g,e[6]=x*s+T*h+w*d+b*v,e[7]=x*r+T*l+w*f+b*m,x=y[8],T=y[9],w=y[10],b=y[11],e[8]=x*i+T*o+w*u+b*p,e[9]=x*n+T*a+w*c+b*g,e[10]=x*s+T*h+w*d+b*v,e[11]=x*r+T*l+w*f+b*m,x=y[12],T=y[13],w=y[14],b=y[15],e[12]=x*i+T*o+w*u+b*p,e[13]=x*n+T*a+w*c+b*g,e[14]=x*s+T*h+w*d+b*v,e[15]=x*r+T*l+w*f+b*m,this},multiplyLocal:function(t){var e=[],i=this.val,n=t.val;return e[0]=i[0]*n[0]+i[1]*n[4]+i[2]*n[8]+i[3]*n[12],e[1]=i[0]*n[1]+i[1]*n[5]+i[2]*n[9]+i[3]*n[13],e[2]=i[0]*n[2]+i[1]*n[6]+i[2]*n[10]+i[3]*n[14],e[3]=i[0]*n[3]+i[1]*n[7]+i[2]*n[11]+i[3]*n[15],e[4]=i[4]*n[0]+i[5]*n[4]+i[6]*n[8]+i[7]*n[12],e[5]=i[4]*n[1]+i[5]*n[5]+i[6]*n[9]+i[7]*n[13],e[6]=i[4]*n[2]+i[5]*n[6]+i[6]*n[10]+i[7]*n[14],e[7]=i[4]*n[3]+i[5]*n[7]+i[6]*n[11]+i[7]*n[15],e[8]=i[8]*n[0]+i[9]*n[4]+i[10]*n[8]+i[11]*n[12],e[9]=i[8]*n[1]+i[9]*n[5]+i[10]*n[9]+i[11]*n[13],e[10]=i[8]*n[2]+i[9]*n[6]+i[10]*n[10]+i[11]*n[14],e[11]=i[8]*n[3]+i[9]*n[7]+i[10]*n[11]+i[11]*n[15],e[12]=i[12]*n[0]+i[13]*n[4]+i[14]*n[8]+i[15]*n[12],e[13]=i[12]*n[1]+i[13]*n[5]+i[14]*n[9]+i[15]*n[13],e[14]=i[12]*n[2]+i[13]*n[6]+i[14]*n[10]+i[15]*n[14],e[15]=i[12]*n[3]+i[13]*n[7]+i[14]*n[11]+i[15]*n[15],this.fromArray(e)},translate:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[12]=s[0]*e+s[4]*i+s[8]*n+s[12],s[13]=s[1]*e+s[5]*i+s[9]*n+s[13],s[14]=s[2]*e+s[6]*i+s[10]*n+s[14],s[15]=s[3]*e+s[7]*i+s[11]*n+s[15],this},translateXYZ:function(t,e,i){var n=this.val;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this},scale:function(t){var e=t.x,i=t.y,n=t.z,s=this.val;return s[0]=s[0]*e,s[1]=s[1]*e,s[2]=s[2]*e,s[3]=s[3]*e,s[4]=s[4]*i,s[5]=s[5]*i,s[6]=s[6]*i,s[7]=s[7]*i,s[8]=s[8]*n,s[9]=s[9]*n,s[10]=s[10]*n,s[11]=s[11]*n,this},scaleXYZ:function(t,e,i){var n=this.val;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this},makeRotationAxis:function(t,e){var i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,o=t.y,a=t.z,h=s*r,l=s*o;return this.fromArray([h*r+i,h*o-n*a,h*a+n*o,0,h*o+n*a,l*o+i,l*a-n*r,0,h*a-n*o,l*a+n*r,s*a*a+i,0,0,0,0,1]),this},rotate:function(t,e){var i=this.val,n=e.x,s=e.y,r=e.z,o=Math.sqrt(n*n+s*s+r*r);if(Math.abs(o)<1e-6)return null;n*=o=1/o,s*=o,r*=o;var a=Math.sin(t),h=Math.cos(t),l=1-h,u=i[0],c=i[1],d=i[2],f=i[3],p=i[4],g=i[5],v=i[6],m=i[7],y=i[8],x=i[9],T=i[10],w=i[11],b=n*n*l+h,E=s*n*l+r*a,S=r*n*l-s*a,A=n*s*l-r*a,_=s*s*l+h,C=r*s*l+n*a,M=n*r*l+s*a,O=s*r*l-n*a,P=r*r*l+h;return i[0]=u*b+p*E+y*S,i[1]=c*b+g*E+x*S,i[2]=d*b+v*E+T*S,i[3]=f*b+m*E+w*S,i[4]=u*A+p*_+y*C,i[5]=c*A+g*_+x*C,i[6]=d*A+v*_+T*C,i[7]=f*A+m*_+w*C,i[8]=u*M+p*O+y*P,i[9]=c*M+g*O+x*P,i[10]=d*M+v*O+T*P,i[11]=f*M+m*O+w*P,this},rotateX:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this},rotateY:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this},rotateZ:function(t){var e=this.val,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this},fromRotationTranslation:function(t,e){var i=this.val,n=t.x,s=t.y,r=t.z,o=t.w,a=n+n,h=s+s,l=r+r,u=n*a,c=n*h,d=n*l,f=s*h,p=s*l,g=r*l,v=o*a,m=o*h,y=o*l;return i[0]=1-(f+g),i[1]=c+y,i[2]=d-m,i[3]=0,i[4]=c-y,i[5]=1-(u+g),i[6]=p+v,i[7]=0,i[8]=d+m,i[9]=p-v,i[10]=1-(u+f),i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this},fromQuat:function(t){var e=this.val,i=t.x,n=t.y,s=t.z,r=t.w,o=i+i,a=n+n,h=s+s,l=i*o,u=i*a,c=i*h,d=n*a,f=n*h,p=s*h,g=r*o,v=r*a,m=r*h;return e[0]=1-(d+p),e[1]=u+m,e[2]=c-v,e[3]=0,e[4]=u-m,e[5]=1-(l+p),e[6]=f+g,e[7]=0,e[8]=c+v,e[9]=f-g,e[10]=1-(l+d),e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},frustum:function(t,e,i,n,s,r){var o=this.val,a=1/(e-t),h=1/(n-i),l=1/(s-r);return o[0]=2*s*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*s*h,o[6]=0,o[7]=0,o[8]=(e+t)*a,o[9]=(n+i)*h,o[10]=(r+s)*l,o[11]=-1,o[12]=0,o[13]=0,o[14]=r*s*2*l,o[15]=0,this},perspective:function(t,e,i,n){var s=this.val,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this},perspectiveLH:function(t,e,i,n){var s=this.val;return s[0]=2*i/t,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=2*i/e,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=-n/(i-n),s[11]=1,s[12]=0,s[13]=0,s[14]=i*n/(i-n),s[15]=0,this},ortho:function(t,e,i,n,s,r){var o=this.val,a=t-e,h=i-n,l=s-r;return a=0===a?a:1/a,h=0===h?h:1/h,l=0===l?l:1/l,o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this},lookAt:function(t,e,i){var n=this.val,s=t.x,r=t.y,o=t.z,a=i.x,h=i.y,l=i.z,u=e.x,c=e.y,d=e.z;if(Math.abs(s-u)<1e-6&&Math.abs(r-c)<1e-6&&Math.abs(o-d)<1e-6)return this.identity();var f=s-u,p=r-c,g=o-d,v=1/Math.sqrt(f*f+p*p+g*g),m=h*(g*=v)-l*(p*=v),y=l*(f*=v)-a*g,x=a*p-h*f;(v=Math.sqrt(m*m+y*y+x*x))?(m*=v=1/v,y*=v,x*=v):(m=0,y=0,x=0);var T=p*x-g*y,w=g*m-f*x,b=f*y-p*m;return(v=Math.sqrt(T*T+w*w+b*b))?(T*=v=1/v,w*=v,b*=v):(T=0,w=0,b=0),n[0]=m,n[1]=T,n[2]=f,n[3]=0,n[4]=y,n[5]=w,n[6]=p,n[7]=0,n[8]=x,n[9]=b,n[10]=g,n[11]=0,n[12]=-(m*s+y*r+x*o),n[13]=-(T*s+w*r+b*o),n[14]=-(f*s+p*r+g*o),n[15]=1,this},yawPitchRoll:function(t,e,i){this.zero(),s.zero(),r.zero();var n=this.val,o=s.val,a=r.val,h=Math.sin(i),l=Math.cos(i);return n[10]=1,n[15]=1,n[0]=l,n[1]=h,n[4]=-h,n[5]=l,h=Math.sin(e),l=Math.cos(e),o[0]=1,o[15]=1,o[5]=l,o[10]=l,o[9]=-h,o[6]=h,h=Math.sin(t),l=Math.cos(t),a[5]=1,a[15]=1,a[0]=l,a[2]=-h,a[8]=h,a[10]=l,this.multiplyLocal(s),this.multiplyLocal(r),this},setWorldMatrix:function(t,e,i,n,o){return this.yawPitchRoll(t.y,t.x,t.z),s.scaling(i.x,i.y,i.z),r.xyz(e.x,e.y,e.z),this.multiplyLocal(s),this.multiplyLocal(r),void 0!==n&&this.multiplyLocal(n),void 0!==o&&this.multiplyLocal(o),this}}),s=new n,r=new n;t.exports=n},function(t,e,i){var n=i(0),s=i(172),r=i(331),o=new Int8Array([1,2,0]),a=new Float32Array([0,0,0]),h=new s(1,0,0),l=new s(0,1,0),u=new s,c=new r,d=new n({initialize:function(t,e,i,n){"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},set:function(t,e,i,n){return"object"==typeof t?(this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this.w=t.w||0):(this.x=t||0,this.y=e||0,this.z=i||0,this.w=n||0),this},add:function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},subtract:function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},scale:function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},length:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return Math.sqrt(t*t+e*e+i*i+n*n)},lengthSq:function(){var t=this.x,e=this.y,i=this.z,n=this.w;return t*t+e*e+i*i+n*n},normalize:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n;return s>0&&(s=1/Math.sqrt(s),this.x=t*s,this.y=e*s,this.z=i*s,this.w=n*s),this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},lerp:function(t,e){void 0===e&&(e=0);var i=this.x,n=this.y,s=this.z,r=this.w;return this.x=i+e*(t.x-i),this.y=n+e*(t.y-n),this.z=s+e*(t.z-s),this.w=r+e*(t.w-r),this},rotationTo:function(t,e){var i=t.x*e.x+t.y*e.y+t.z*e.z;return i<-.999999?(u.copy(h).cross(t).length()<1e-6&&u.copy(l).cross(t),u.normalize(),this.setAxisAngle(u,Math.PI)):i>.999999?(this.x=0,this.y=0,this.z=0,this.w=1,this):(u.copy(t).cross(e),this.x=u.x,this.y=u.y,this.z=u.z,this.w=1+i,this.normalize())},setAxes:function(t,e,i){var n=c.val;return n[0]=e.x,n[3]=e.y,n[6]=e.z,n[1]=i.x,n[4]=i.y,n[7]=i.z,n[2]=-t.x,n[5]=-t.y,n[8]=-t.z,this.fromMat3(c).normalize()},identity:function(){return this.x=0,this.y=0,this.z=0,this.w=1,this},setAxisAngle:function(t,e){e*=.5;var i=Math.sin(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=Math.cos(e),this},multiply:function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,o=t.y,a=t.z,h=t.w;return this.x=e*h+s*r+i*a-n*o,this.y=i*h+s*o+n*r-e*a,this.z=n*h+s*a+e*o-i*r,this.w=s*h-e*r-i*o-n*a,this},slerp:function(t,e){var i=this.x,n=this.y,s=this.z,r=this.w,o=t.x,a=t.y,h=t.z,l=t.w,u=i*o+n*a+s*h+r*l;u<0&&(u=-u,o=-o,a=-a,h=-h,l=-l);var c=1-e,d=e;if(1-u>1e-6){var f=Math.acos(u),p=Math.sin(f);c=Math.sin((1-e)*f)/p,d=Math.sin(e*f)/p}return this.x=c*i+d*o,this.y=c*n+d*a,this.z=c*s+d*h,this.w=c*r+d*l,this},invert:function(){var t=this.x,e=this.y,i=this.z,n=this.w,s=t*t+e*e+i*i+n*n,r=s?1/s:0;return this.x=-t*r,this.y=-e*r,this.z=-i*r,this.w=n*r,this},conjugate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},rotateX:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+s*r,this.y=i*o+n*r,this.z=n*o-i*r,this.w=s*o-e*r,this},rotateY:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o-n*r,this.y=i*o+s*r,this.z=n*o+e*r,this.w=s*o-i*r,this},rotateZ:function(t){t*=.5;var e=this.x,i=this.y,n=this.z,s=this.w,r=Math.sin(t),o=Math.cos(t);return this.x=e*o+i*r,this.y=i*o-e*r,this.z=n*o+s*r,this.w=s*o-n*r,this},calculateW:function(){var t=this.x,e=this.y,i=this.z;return this.w=-Math.sqrt(1-t*t-e*e-i*i),this},fromMat3:function(t){var e,i=t.val,n=i[0]+i[4]+i[8];if(n>0)e=Math.sqrt(n+1),this.w=.5*e,e=.5/e,this.x=(i[7]-i[5])*e,this.y=(i[2]-i[6])*e,this.z=(i[3]-i[1])*e;else{var s=0;i[4]>i[0]&&(s=1),i[8]>i[3*s+s]&&(s=2);var r=o[s],h=o[r];e=Math.sqrt(i[3*s+s]-i[3*r+r]-i[3*h+h]+1),a[s]=.5*e,e=.5/e,a[r]=(i[3*r+s]+i[3*s+r])*e,a[h]=(i[3*h+s]+i[3*s+h])*e,this.x=a[0],this.y=a[1],this.z=a[2],this.w=(i[3*h+r]-i[3*r+h])*e}return this}});t.exports=d},function(t,e,i){var n=i(335),s=i(26),r=i(29),o=i(167);t.exports=function(t){var e=t.config;if((e.customEnvironment||e.canvas)&&e.renderType===r.AUTO)throw new Error("Must set explicit renderType in custom environment");if(!e.customEnvironment&&!e.canvas&&e.renderType!==r.HEADLESS)if(e.renderType===r.CANVAS||e.renderType!==r.CANVAS&&!o.webGL){if(!o.canvas)throw new Error("Cannot create Canvas or WebGL context, aborting.");e.renderType=r.CANVAS}else e.renderType=r.WEBGL;e.antialias||s.disableSmoothing();var a,h,l=t.scale.baseSize,u=l.width,c=l.height;e.canvas?(t.canvas=e.canvas,t.canvas.width=u,t.canvas.height=c):t.canvas=s.create(t,u,c,e.renderType),e.canvasStyle&&(t.canvas.style=e.canvasStyle),e.antialias||n.setCrisp(t.canvas),e.renderType!==r.HEADLESS&&(a=i(499),h=i(502),e.renderType===r.WEBGL?t.renderer=new h(t):(t.renderer=new a(t),t.context=t.renderer.gameContext))}},function(t,e){t.exports={setCrisp:function(t){return["optimizeSpeed","-moz-crisp-edges","-o-crisp-edges","-webkit-optimize-contrast","optimize-contrast","crisp-edges","pixelated"].forEach(function(e){t.style["image-rendering"]=e}),t.style.msInterpolationMode="nearest-neighbor",t},setBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}}},function(t,e,i){var n=i(29);t.exports=function(t){var e=t.config;if(!e.hideBanner){var i="WebGL";e.renderType===n.CANVAS?i="Canvas":e.renderType===n.HEADLESS&&(i="Headless");var s,r=e.audio,o=t.device.audio;if(s=!o.webAudio||r&&r.disableWebAudio?r&&r.noAudio||!o.webAudio&&!o.audioData?"No Audio":"HTML5 Audio":"Web Audio",t.device.browser.ie)window.console&&console.log("Phaser v"+n.VERSION+" / https://phaser.io");else{var a,h="",l=[h];Array.isArray(e.bannerBackgroundColor)?(e.bannerBackgroundColor.forEach(function(t){h=h.concat("%c "),l.push("background: "+t),a=t}),l[l.length-1]="color: "+e.bannerTextColor+"; background: "+a):(h=h.concat("%c "),l.push("color: "+e.bannerTextColor+"; background: "+e.bannerBackgroundColor)),l.push("background: #fff"),e.gameTitle&&(h=h.concat(e.gameTitle),e.gameVersion&&(h=h.concat(" v"+e.gameVersion)),e.hidePhaser||(h=h.concat(" / "))),e.hidePhaser||(h=h.concat("Phaser v"+n.VERSION+" ("+i+" | "+s+")")),h=h.concat(" %c "+e.gameURL),l[0]=h,console.log.apply(console,l)}}}},function(t,e,i){var n=i(0),s=i(6),r=i(1),o=i(338),a=new n({initialize:function(t,e){this.game=t,this.raf=new o,this.started=!1,this.running=!1,this.minFps=s(e,"min",5),this.targetFps=s(e,"target",60),this._min=1e3/this.minFps,this._target=1e3/this.targetFps,this.actualFps=this.targetFps,this.nextFpsUpdate=0,this.framesThisSecond=0,this.callback=r,this.forceSetTimeOut=s(e,"forceSetTimeOut",!1),this.time=0,this.startTime=0,this.lastTime=0,this.frame=0,this.inFocus=!0,this._pauseTime=0,this._coolDown=0,this.delta=0,this.deltaIndex=0,this.deltaHistory=[],this.deltaSmoothingMax=s(e,"deltaHistory",10),this.panicMax=s(e,"panicMax",120),this.rawDelta=0,this.now=0,this.smoothStep=s(e,"smoothStep",!0)},blur:function(){this.inFocus=!1},focus:function(){this.inFocus=!0,this.resetDelta()},pause:function(){this._pauseTime=window.performance.now()},resume:function(){this.resetDelta(),this.startTime+=this.time-this._pauseTime},resetDelta:function(){var t=window.performance.now();this.time=t,this.lastTime=t,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0;for(var e=0;e0||!this.inFocus)&&(this._coolDown--,r=Math.min(r,this._target)),r>this._min&&(r=n[i],r=Math.min(r,this._min)),n[i]=r,this.deltaIndex++,this.deltaIndex>s&&(this.deltaIndex=0),o=0;for(var a=0;athis.nextFpsUpdate&&(this.actualFps=.25*this.framesThisSecond+.75*this.actualFps,this.nextFpsUpdate=t+1e3,this.framesThisSecond=0),this.framesThisSecond++;var h=o/this._target;this.callback(t,o,h),this.lastTime=t,this.frame++},tick:function(){this.step()},sleep:function(){this.running&&(this.raf.stop(),this.running=!1)},wake:function(t){this.running?this.sleep():t&&(this.startTime+=-this.lastTime+(this.lastTime+window.performance.now())),this.raf.start(this.step.bind(this),this.useRAF),this.running=!0,this.step()},getDuration:function(){return Math.round(this.lastTime-this.startTime)/1e3},getDurationMS:function(){return Math.round(this.lastTime-this.startTime)},stop:function(){return this.running=!1,this.started=!1,this.raf.stop(),this},destroy:function(){this.stop(),this.callback=r,this.raf=null,this.game=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(1),r=new n({initialize:function(){this.isRunning=!1,this.callback=s,this.tick=0,this.isSetTimeOut=!1,this.timeOutID=null,this.lastTime=0,this.target=0;var t=this;this.step=function e(){var i=window.performance.now();t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.requestAnimationFrame(e)},this.stepTimeout=function e(){var i=Date.now(),n=Math.min(Math.max(2*t.target+t.tick-i,0),t.target);t.lastTime=t.tick,t.tick=i,t.callback(i),t.timeOutID=window.setTimeout(e,n)}},start:function(t,e,i){this.isRunning||(this.callback=t,this.isSetTimeOut=e,this.target=i,this.isRunning=!0,this.timeOutID=e?window.setTimeout(this.stepTimeout,0):window.requestAnimationFrame(this.step))},stop:function(){this.isRunning=!1,this.isSetTimeOut?clearTimeout(this.timeOutID):window.cancelAnimationFrame(this.timeOutID)},destroy:function(){this.stop(),this.callback=s}});t.exports=r},function(t,e,i){var n=i(18);t.exports=function(t){var e,i=t.events;void 0!==document.hidden?e="visibilitychange":["webkit","moz","ms"].forEach(function(t){void 0!==document[t+"Hidden"]&&(document.hidden=function(){return document[t+"Hidden"]},e=t+"visibilitychange")});e&&document.addEventListener(e,function(t){document.hidden||"pause"===t.type?i.emit(n.HIDDEN):i.emit(n.VISIBLE)},!1),window.onblur=function(){i.emit(n.BLUR)},window.onfocus=function(){i.emit(n.FOCUS)},window.focus&&t.config.autoFocus&&window.focus()}},function(t,e,i){var n=i(341),s=i(26),r=i(6);t.exports=function(t){var e=r(t,"data",[]),i=r(t,"canvas",null),o=r(t,"palette",n),a=r(t,"pixelWidth",1),h=r(t,"pixelHeight",a),l=r(t,"resizeCanvas",!0),u=r(t,"clearCanvas",!0),c=r(t,"preRender",null),d=r(t,"postRender",null),f=Math.floor(Math.abs(e[0].length*a)),p=Math.floor(Math.abs(e.length*h));i||(i=s.create2D(this,f,p),l=!1,u=!1),l&&(i.width=f,i.height=p);var g=i.getContext("2d");u&&g.clearRect(0,0,f,p),c&&c(i,g);for(var v=0;vi;)n-=i;ni.length-2?i.length-1:r+1],c=i[r>i.length-3?i.length-1:r+2];return e.set(n(a,h.x,l.x,u.x,c.x),n(a,h.y,l.y,u.y,c.y))},toJSON:function(){for(var t=[],e=0;e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}},function(t,e,i){var n=i(116);t.exports=function(t){if("complete"!==document.readyState&&"interactive"!==document.readyState){var e=function(){document.removeEventListener("deviceready",e,!0),document.removeEventListener("DOMContentLoaded",e,!0),window.removeEventListener("load",e,!0),t()};document.body?n.cordova?document.addEventListener("deviceready",e,!1):(document.addEventListener("DOMContentLoaded",e,!0),window.addEventListener("load",e,!0)):window.setTimeout(e,20)}else t()}},function(t,e,i){var n=i(175);t.exports=function(t,e){var i=window.screen,s=!!i&&(i.orientation||i.mozOrientation||i.msOrientation);if(s&&"string"==typeof s.type)return s.type;if("string"==typeof s)return s;if(i)return i.height>i.width?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if("number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return n.ORIENTATION.PORTRAIT;if(window.matchMedia("(orientation: landscape)").matches)return n.ORIENTATION.LANDSCAPE}return e>t?n.ORIENTATION.PORTRAIT:n.ORIENTATION.LANDSCAPE}},function(t,e){t.exports={NO_CENTER:0,CENTER_BOTH:1,CENTER_HORIZONTALLY:2,CENTER_VERTICALLY:3}},function(t,e){t.exports={LANDSCAPE:"landscape-primary",PORTRAIT:"portrait-primary"}},function(t,e){t.exports={NONE:0,WIDTH_CONTROLS_HEIGHT:1,HEIGHT_CONTROLS_WIDTH:2,FIT:3,ENVELOP:4,RESIZE:5}},function(t,e){t.exports={NO_ZOOM:1,ZOOM_2X:2,ZOOM_4X:4,MAX_ZOOM:-1}},function(t,e){t.exports=function(t){var e;return""!==t&&("string"==typeof t?e=document.getElementById(t):t&&1===t.nodeType&&(e=t)),e||(e=document.body),e}},function(t,e){t.exports=function(t){var e="";try{window.DOMParser?e=(new DOMParser).parseFromString(t,"text/xml"):(e=new ActiveXObject("Microsoft.XMLDOM")).loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null}},function(t,e,i){var n=i(0),s=i(177),r=i(9),o=i(54),a=i(18),h=i(360),l=i(361),u=i(362),c=i(363),d=i(32),f=i(329),p=new n({initialize:function(t,e){this.game=t,this.scaleManager,this.canvas,this.config=e,this.enabled=!0,this.events=new r,this.isOver=!0,this.defaultCursor="",this.keyboard=e.inputKeyboard?new h(this):null,this.mouse=e.inputMouse?new l(this):null,this.touch=e.inputTouch?new c(this):null,this.pointers=[],this.pointersTotal=e.inputActivePointers,e.inputTouch&&1===this.pointersTotal&&(this.pointersTotal=2);for(var i=0;i<=this.pointersTotal;i++){var n=new u(this,i);n.smoothFactor=e.inputSmoothFactor,this.pointers.push(n)}this.mousePointer=e.inputMouse?this.pointers[0]:null,this.activePointer=this.pointers[0],this.globalTopOnly=!0,this.time=0,this._tempPoint={x:0,y:0},this._tempHitTest=[],this._tempMatrix=new d,this._tempMatrix2=new d,this._tempSkip=!1,this.mousePointerContainer=[this.mousePointer],t.events.once(a.BOOT,this.boot,this)},boot:function(){this.canvas=this.game.canvas,this.scaleManager=this.game.scale,this.events.emit(o.MANAGER_BOOT),this.game.events.on(a.PRE_RENDER,this.preRender,this),this.game.events.once(a.DESTROY,this.destroy,this)},setCanvasOver:function(t){this.isOver=!0,this.events.emit(o.GAME_OVER,t)},setCanvasOut:function(t){this.isOver=!1,this.events.emit(o.GAME_OUT,t)},preRender:function(){var t=this.game.loop.now,e=this.game.loop.delta,i=this.game.scene.getScenes(!0,!0);this.time=t,this.events.emit(o.MANAGER_UPDATE);for(var n=0;n10&&(t=10-this.pointersTotal);for(var i=0;i-1&&e.preventDefault()}},this.onKeyUp=function(e){if(!e.defaultPrevented&&t.enabled&&t.manager){t.queue.push(e),t.manager.useQueue||t.manager.events.emit(o.MANAGER_PROCESS);var i=e.altKey||e.ctrlKey||e.shiftKey||e.metaKey;t.preventDefault&&!i&&t.captures.indexOf(e.keyCode)>-1&&e.preventDefault()}};var e=this.target;e&&(e.addEventListener("keydown",this.onKeyDown,!1),e.addEventListener("keyup",this.onKeyUp,!1),this.enabled=!0)},stopListeners:function(){var t=this.target;t.removeEventListener("keydown",this.onKeyDown,!1),t.removeEventListener("keyup",this.onKeyUp,!1),this.enabled=!1},postUpdate:function(){this.queue=[]},addCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},removeCapture:function(t){"string"==typeof t&&(t=t.split(",")),Array.isArray(t)||(t=[t]);for(var e=this.captures,i=0;i0},clearCaptures:function(){this.captures=[],this.preventDefault=!1},destroy:function(){this.stopListeners(),this.clearCaptures(),this.queue=[],this.manager.game.events.off(r.POST_RENDER,this.postUpdate,this),this.target=null,this.enabled=!1,this.manager=null}});t.exports=l},function(t,e,i){var n=i(0),s=i(167),r=i(54),o=i(0),a=new n({initialize:function(t){this.manager=t,this.capture=!0,this.enabled=!1,this.target,this.locked=!1,this.onMouseMove=o,this.onMouseDown=o,this.onMouseUp=o,this.onMouseDownWindow=o,this.onMouseUpWindow=o,this.onMouseOver=o,this.onMouseOut=o,this.onMouseWheel=o,this.pointerLockChange=o,t.events.once(r.MANAGER_BOOT,this.boot,this)},boot:function(){var t=this.manager.config;this.enabled=t.inputMouse,this.target=t.inputMouseEventTarget,this.capture=t.inputMouseCapture,this.target?"string"==typeof this.target&&(this.target=document.getElementById(this.target)):this.target=this.manager.game.canvas,t.disableContextMenu&&this.disableContextMenu(),this.enabled&&this.target&&this.startListeners()},disableContextMenu:function(){return document.body.addEventListener("contextmenu",function(t){return t.preventDefault(),!1}),this},requestPointerLock:function(){if(s.pointerLock){var t=this.target;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock()}},releasePointerLock:function(){s.pointerLock&&(document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock())},startListeners:function(){var t=this,e=this.manager.canvas,i=window&&window.focus&&this.manager.game.config.autoFocus;this.onMouseMove=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseMove(e),t.capture&&e.preventDefault())},this.onMouseDown=function(n){i&&window.focus(),!n.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseDown(n),t.capture&&n.target===e&&n.preventDefault())},this.onMouseDownWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseDown(i)},this.onMouseUp=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&(t.manager.onMouseUp(i),t.capture&&i.target===e&&i.preventDefault())},this.onMouseUpWindow=function(i){!i.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&i.target!==e&&t.manager.onMouseUp(i)},this.onMouseOver=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOver(e)},this.onMouseOut=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.setCanvasOut(e)},this.onMouseWheel=function(e){!e.defaultPrevented&&t.enabled&&t.manager&&t.manager.enabled&&t.manager.onMouseWheel(e)};var n=this.target;if(n){var r={passive:!0},o={passive:!1};n.addEventListener("mousemove",this.onMouseMove,this.capture?o:r),n.addEventListener("mousedown",this.onMouseDown,this.capture?o:r),n.addEventListener("mouseup",this.onMouseUp,this.capture?o:r),n.addEventListener("mouseover",this.onMouseOver,this.capture?o:r),n.addEventListener("mouseout",this.onMouseOut,this.capture?o:r),n.addEventListener("wheel",this.onMouseWheel,this.capture?o:r),window&&this.manager.game.config.inputWindowEvents&&(window.addEventListener("mousedown",this.onMouseDownWindow,o),window.addEventListener("mouseup",this.onMouseUpWindow,o)),s.pointerLock&&(this.pointerLockChange=function(e){var i=t.target;t.locked=document.pointerLockElement===i||document.mozPointerLockElement===i||document.webkitPointerLockElement===i,t.manager.onPointerLockChange(e)},document.addEventListener("pointerlockchange",this.pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this.pointerLockChange,!0)),this.enabled=!0}},stopListeners:function(){var t=this.target;t.removeEventListener("mousemove",this.onMouseMove),t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("mouseup",this.onMouseUp),t.removeEventListener("mouseover",this.onMouseOver),t.removeEventListener("mouseout",this.onMouseOut),window&&(window.removeEventListener("mousedown",this.onMouseDownWindow),window.removeEventListener("mouseup",this.onMouseUpWindow)),s.pointerLock&&(document.removeEventListener("pointerlockchange",this.pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this.pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this.pointerLockChange,!0))},destroy:function(){this.stopListeners(),this.target=null,this.enabled=!1,this.manager=null}});t.exports=a},function(t,e,i){var n=i(314),s=i(0),r=i(53),o=i(144),a=i(323),h=i(3),l=new s({initialize:function(t,e){this.manager=t,this.id=e,this.event,this.downElement,this.upElement,this.camera=null,this.button=0,this.buttons=0,this.position=new h,this.prevPosition=new h,this.midPoint=new h(-1,-1),this.velocity=new h,this.angle=0,this.distance=0,this.smoothFactor=0,this.motionFactor=.2,this.worldX=0,this.worldY=0,this.moveTime=0,this.downX=0,this.downY=0,this.downTime=0,this.upX=0,this.upY=0,this.upTime=0,this.primaryDown=!1,this.isDown=!1,this.wasTouch=!1,this.wasCanceled=!1,this.movementX=0,this.movementY=0,this.identifier=0,this.pointerId=null,this.active=0===e,this.locked=!1,this.deltaX=0,this.deltaY=0,this.deltaZ=0},updateWorldPoint:function(t){var e=this.x,i=this.y;1!==t.resolution&&(e+=t._x,i+=t._y);var n=t.getWorldPoint(e,i);return this.worldX=n.x,this.worldY=n.y,this},positionToCamera:function(t,e){return t.getWorldPoint(this.x,this.y,e)},updateMotion:function(){var t=this.position.x,e=this.position.y,i=this.midPoint.x,s=this.midPoint.y;if(t!==i||e!==s){var r=a(this.motionFactor,i,t),h=a(this.motionFactor,s,e);o(r,t,.1)&&(r=t),o(h,e,.1)&&(h=e),this.midPoint.set(r,h);var l=t-r,u=e-h;this.velocity.set(l,u),this.angle=n(r,h,t,e),this.distance=Math.sqrt(l*l+u*u)}},up:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=t.timeStamp),this.isDown=!1,this.wasTouch=!1},down:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.button=t.button,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),0===t.button&&(this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=t.timeStamp),this.isDown=!0,this.wasTouch=!1},move:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.locked&&(this.movementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.movementY=t.movementY||t.mozMovementY||t.webkitMovementY||0),this.moveTime=t.timeStamp,this.wasTouch=!1},wheel:function(t){"buttons"in t&&(this.buttons=t.buttons),this.event=t,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ,this.wasTouch=!1},touchstart:function(t,e){t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.active=!0,this.buttons=1,this.event=e,this.downElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!0,this.downX=this.x,this.downY=this.y,this.downTime=e.timeStamp,this.isDown=!0,this.wasTouch=!0,this.wasCanceled=!1,this.updateMotion()},touchmove:function(t,e){this.event=e,this.manager.transformPointer(this,t.pageX,t.pageY,!0),this.moveTime=e.timeStamp,this.wasTouch=!0,this.updateMotion()},touchend:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!1,this.active=!1,this.updateMotion()},touchcancel:function(t,e){this.buttons=0,this.event=e,this.upElement=t.target,this.manager.transformPointer(this,t.pageX,t.pageY,!1),this.primaryDown=!1,this.upX=this.x,this.upY=this.y,this.upTime=e.timeStamp,this.isDown=!1,this.wasTouch=!0,this.wasCanceled=!0,this.active=!1},noButtonDown:function(){return 0===this.buttons},leftButtonDown:function(){return!!(1&this.buttons)},rightButtonDown:function(){return!!(2&this.buttons)},middleButtonDown:function(){return!!(4&this.buttons)},backButtonDown:function(){return!!(8&this.buttons)},forwardButtonDown:function(){return!!(16&this.buttons)},leftButtonReleased:function(){return 0===this.button&&!this.isDown},rightButtonReleased:function(){return 2===this.button&&!this.isDown},middleButtonReleased:function(){return 1===this.button&&!this.isDown},backButtonReleased:function(){return 3===this.button&&!this.isDown},forwardButtonReleased:function(){return 4===this.button&&!this.isDown},getDistance:function(){return this.isDown?r(this.downX,this.downY,this.x,this.y):r(this.downX,this.downY,this.upX,this.upY)},getDistanceX:function(){return this.isDown?Math.abs(this.downX-this.x):Math.abs(this.downX-this.upX)},getDistanceY:function(){return this.isDown?Math.abs(this.downY-this.y):Math.abs(this.downY-this.upY)},getDuration:function(){return this.isDown?this.manager.time-this.downTime:this.upTime-this.downTime},getAngle:function(){return this.isDown?n(this.downX,this.downY,this.x,this.y):n(this.downX,this.downY,this.upX,this.upY)},getInterpolatedPosition:function(t,e){void 0===t&&(t=10),void 0===e&&(e=[]);for(var i=this.prevPosition.x,n=this.prevPosition.y,s=this.position.x,r=this.position.y,o=0;o0&&this.parentSize.height>0&&this.displaySize.setParent(this.parentSize),this.refresh()),t.events.on(a.PRE_STEP,this.step,this),t.events.once(a.DESTROY,this.destroy,this),this.startListeners()},parseConfig:function(t){this.getParent(t),this.getParentBounds();var e=t.width,i=t.height,s=t.scaleMode,r=t.resolution,o=t.zoom,a=t.autoRound;if("string"==typeof e){var h=this.parentSize.width;0===h&&(h=window.innerWidth);var l=parseInt(e,10)/100;e=Math.floor(h*l)}if("string"==typeof i){var c=this.parentSize.height;0===c&&(c=window.innerHeight);var d=parseInt(i,10)/100;i=Math.floor(c*d)}this.resolution=1,this.scaleMode=s,this.autoRound=a,this.autoCenter=t.autoCenter,this.resizeInterval=t.resizeInterval,a&&(e=Math.floor(e),i=Math.floor(i)),this.gameSize.setSize(e,i),o===n.ZOOM.MAX_ZOOM&&(o=this.getMaxZoom()),this.zoom=o,1!==o&&(this._resetZoom=!0),this.baseSize.setSize(e*r,i*r),a&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),t.minWidth>0&&this.displaySize.setMin(t.minWidth*o,t.minHeight*o),t.maxWidth>0&&this.displaySize.setMax(t.maxWidth*o,t.maxHeight*o),this.displaySize.setSize(e,i),this.orientation=u(e,i)},getParent:function(t){var e=t.parent;if(null!==e){if(this.parent=l(e),this.parentIsWindow=this.parent===document.body,t.expandParent&&t.scaleMode!==n.SCALE_MODE.NONE){var i=this.parent.getBoundingClientRect();(this.parentIsWindow||0===i.height)&&(document.documentElement.style.height="100%",document.body.style.height="100%",i=this.parent.getBoundingClientRect(),this.parentIsWindow||0!==i.height||(this.parent.style.overflow="hidden",this.parent.style.width="100%",this.parent.style.height="100%"))}t.fullscreenTarget&&!this.fullscreenTarget&&(this.fullscreenTarget=l(t.fullscreenTarget))}},getParentBounds:function(){if(!this.parent)return!1;var t=this.parentSize,e=this.parent.getBoundingClientRect();this.parentIsWindow&&this.game.device.os.iOS&&(e.height=h(!0));var i=this.resolution,n=e.width*i,s=e.height*i;return(t.width!==n||t.height!==s)&&(t.setSize(n,s),!0)},lockOrientation:function(t){var e=screen.lockOrientation||screen.mozLockOrientation||screen.msLockOrientation;return!!e&&e(t)},setParentSize:function(t,e){return this.parentSize.setSize(t,e),this.refresh()},setGameSize:function(t,e){var i=this.autoRound,n=this.resolution;i&&(t=Math.floor(t),e=Math.floor(e));var s=this.width,r=this.height;return this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),i&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t,e),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height,this.refresh(s,r)},resize:function(t,e){var i=this.zoom,n=this.resolution,s=this.autoRound;s&&(t=Math.floor(t),e=Math.floor(e));var r=this.width,o=this.height;this.gameSize.resize(t,e),this.baseSize.resize(t*n,e*n),s&&(this.baseSize.width=Math.floor(this.baseSize.width),this.baseSize.height=Math.floor(this.baseSize.height)),this.displaySize.setSize(t*i*n,e*i*n),this.canvas.width=this.baseSize.width,this.canvas.height=this.baseSize.height;var a=this.canvas.style,h=t*i,l=e*i;return s&&(h=Math.floor(h),l=Math.floor(l)),h===t&&l===e||(a.width=h+"px",a.height=l+"px"),this.refresh(r,o)},setZoom:function(t){return this.zoom=t,this._resetZoom=!0,this.refresh()},setMaxZoom:function(){return this.zoom=this.getMaxZoom(),this._resetZoom=!0,this.refresh()},refresh:function(t,e){void 0===t&&(t=this.width),void 0===e&&(e=this.height),this.updateScale(),this.updateBounds(),this.updateOrientation(),this.displayScale.set(this.baseSize.width/this.canvasBounds.width,this.baseSize.height/this.canvasBounds.height);var i=this.game.domContainer;if(i){this.baseSize.setCSS(i);var n=this.canvas.style,s=i.style;s.transform="scale("+this.displaySize.width/this.baseSize.width+","+this.displaySize.height/this.baseSize.height+")",s.marginLeft=n.marginLeft,s.marginTop=n.marginTop}return this.emit(o.RESIZE,this.gameSize,this.baseSize,this.displaySize,this.resolution,t,e),this},updateOrientation:function(){if(this._checkOrientation){this._checkOrientation=!1;var t=u(this.width,this.height);t!==this.orientation&&(this.orientation=t,this.emit(o.ORIENTATION_CHANGE,t))}},updateScale:function(){var t,e,i=this.canvas.style,s=this.gameSize.width,r=this.gameSize.height,o=this.zoom,a=this.autoRound;this.scaleMode===n.SCALE_MODE.NONE?(this.displaySize.setSize(s*o*1,r*o*1),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this._resetZoom&&(i.width=t+"px",i.height=e+"px",this._resetZoom=!1)):this.scaleMode===n.SCALE_MODE.RESIZE?(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),this.gameSize.setSize(this.displaySize.width,this.displaySize.height),this.baseSize.setSize(1*this.displaySize.width,1*this.displaySize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),this.canvas.width=t,this.canvas.height=e):(this.displaySize.setSize(this.parentSize.width,this.parentSize.height),t=this.displaySize.width/1,e=this.displaySize.height/1,a&&(t=Math.floor(t),e=Math.floor(e)),i.width=t+"px",i.height=e+"px"),this.getParentBounds(),this.updateCenter()},getMaxZoom:function(){var t=p(this.parentSize.width,this.gameSize.width,0,!0),e=p(this.parentSize.height,this.gameSize.height,0,!0);return Math.max(Math.min(t,e),1)},updateCenter:function(){var t=this.autoCenter;if(t!==n.CENTER.NO_CENTER){var e=this.canvas,i=e.style,s=e.getBoundingClientRect(),r=s.width,o=s.height,a=Math.floor((this.parentSize.width-r)/2),h=Math.floor((this.parentSize.height-o)/2);t===n.CENTER.CENTER_HORIZONTALLY?h=0:t===n.CENTER.CENTER_VERTICALLY&&(a=0),i.marginLeft=a+"px",i.marginTop=h+"px"}},updateBounds:function(){var t=this.canvasBounds,e=this.canvas.getBoundingClientRect();t.x=e.left+(window.pageXOffset||0)-(document.documentElement.clientLeft||0),t.y=e.top+(window.pageYOffset||0)-(document.documentElement.clientTop||0),t.width=e.width,t.height=e.height},transformX:function(t){return(t-this.canvasBounds.left)*this.displayScale.x},transformY:function(t){return(t-this.canvasBounds.top)*this.displayScale.y},startFullscreen:function(t){void 0===t&&(t={navigationUI:"hide"});var e=this.fullscreen;if(e.available){if(!e.active){var i,n=this.getFullscreenTarget();(i=e.keyboard?n[e.request](Element.ALLOW_KEYBOARD_INPUT):n[e.request](t))?i.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)):e.active?this.fullscreenSuccessHandler():this.fullscreenErrorHandler()}}else this.emit(o.FULLSCREEN_UNSUPPORTED)},fullscreenSuccessHandler:function(){this.getParentBounds(),this.refresh(),this.emit(o.ENTER_FULLSCREEN)},fullscreenErrorHandler:function(t){this.removeFullscreenTarget(),this.emit(o.FULLSCREEN_FAILED,t)},getFullscreenTarget:function(){if(!this.fullscreenTarget){var t=document.createElement("div");t.style.margin="0",t.style.padding="0",t.style.width="100%",t.style.height="100%",this.fullscreenTarget=t,this._createdFullscreenTarget=!0}this._createdFullscreenTarget&&(this.canvas.parentNode.insertBefore(this.fullscreenTarget,this.canvas),this.fullscreenTarget.appendChild(this.canvas));return this.fullscreenTarget},removeFullscreenTarget:function(){if(this._createdFullscreenTarget){var t=this.fullscreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.canvas,t),e.removeChild(t)}}},stopFullscreen:function(){var t=this.fullscreen;if(!t.available)return this.emit(o.FULLSCREEN_UNSUPPORTED),!1;t.active&&document[t.cancel](),this.removeFullscreenTarget(),this.getParentBounds(),this.emit(o.LEAVE_FULLSCREEN),this.refresh()},toggleFullscreen:function(t){this.fullscreen.active?this.stopFullscreen():this.startFullscreen(t)},startListeners:function(){var t=this,e=this.listeners;if(e.orientationChange=function(){t._checkOrientation=!0,t.dirty=!0},e.windowResize=function(){t.dirty=!0},window.addEventListener("orientationchange",e.orientationChange,!1),window.addEventListener("resize",e.windowResize,!1),this.fullscreen.available){e.fullScreenChange=function(e){return t.onFullScreenChange(e)},e.fullScreenError=function(e){return t.onFullScreenError(e)};["webkit","moz",""].forEach(function(t){document.addEventListener(t+"fullscreenchange",e.fullScreenChange,!1),document.addEventListener(t+"fullscreenerror",e.fullScreenError,!1)}),document.addEventListener("MSFullscreenChange",e.fullScreenChange,!1),document.addEventListener("MSFullscreenError",e.fullScreenError,!1)}},onFullScreenChange:function(){document.fullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement||document.mozFullScreenElement||this.stopFullscreen()},onFullScreenError:function(){this.removeFullscreenTarget()},step:function(t,e){this.parent&&(this._lastCheck+=e,(this.dirty||this._lastCheck>this.resizeInterval)&&(this.getParentBounds()&&this.refresh(),this.dirty=!1,this._lastCheck=0))},stopListeners:function(){var t=this.listeners;window.removeEventListener("orientationchange",t.orientationChange,!1),window.removeEventListener("resize",t.windowResize,!1);["webkit","moz",""].forEach(function(e){document.removeEventListener(e+"fullscreenchange",t.fullScreenChange,!1),document.removeEventListener(e+"fullscreenerror",t.fullScreenError,!1)}),document.removeEventListener("MSFullscreenChange",t.fullScreenChange,!1),document.removeEventListener("MSFullscreenError",t.fullScreenError,!1)},destroy:function(){this.removeAllListeners(),this.stopListeners(),this.game=null,this.canvas=null,this.canvasBounds=null,this.parent=null,this.fullscreenTarget=null,this.parentSize.destroy(),this.gameSize.destroy(),this.baseSize.destroy(),this.displaySize.destroy()},isFullscreen:{get:function(){return this.fullscreen.active}},width:{get:function(){return this.gameSize.width}},height:{get:function(){return this.gameSize.height}},isPortrait:{get:function(){return this.orientation===n.ORIENTATION.PORTRAIT}},isLandscape:{get:function(){return this.orientation===n.ORIENTATION.LANDSCAPE}},isGamePortrait:{get:function(){return this.height>this.width}},isGameLandscape:{get:function(){return this.width>this.height}}});t.exports=v},function(t,e,i){var n=i(22),s=i(0),r=i(93),o=i(3),a=new s({initialize:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=0),void 0===n&&(n=null),this._width=t,this._height=e,this._parent=n,this.aspectMode=i,this.aspectRatio=0===e?1:t/e,this.minWidth=0,this.minHeight=0,this.maxWidth=Number.MAX_VALUE,this.maxHeight=Number.MAX_VALUE,this.snapTo=new o},setAspectMode:function(t){return void 0===t&&(t=0),this.aspectMode=t,this.setSize(this._width,this._height)},setSnap:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.snapTo.set(t,e),this.setSize(this._width,this._height)},setParent:function(t){return this._parent=t,this.setSize(this._width,this._height)},setMin:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.minWidth=n(t,0,this.maxWidth),this.minHeight=n(e,0,this.maxHeight),this.setSize(this._width,this._height)},setMax:function(t,e){return void 0===t&&(t=Number.MAX_VALUE),void 0===e&&(e=t),this.maxWidth=n(t,this.minWidth,Number.MAX_VALUE),this.maxHeight=n(e,this.minHeight,Number.MAX_VALUE),this.setSize(this._width,this._height)},setSize:function(t,e){switch(void 0===t&&(t=0),void 0===e&&(e=t),this.aspectMode){case a.NONE:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height;break;case a.WIDTH_CONTROLS_HEIGHT:this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(this._width*(1/this.aspectRatio),!1);break;case a.HEIGHT_CONTROLS_WIDTH:this._height=this.getNewHeight(r(e,this.snapTo.y)),this._width=this.getNewWidth(this._height*this.aspectRatio,!1);break;case a.FIT:this.constrain(t,e,!0);break;case a.ENVELOP:this.constrain(t,e,!1)}return this},setAspectRatio:function(t){return this.aspectRatio=t,this.setSize(this._width,this._height)},resize:function(t,e){return this._width=this.getNewWidth(r(t,this.snapTo.x)),this._height=this.getNewHeight(r(e,this.snapTo.y)),this.aspectRatio=0===this._height?1:this._width/this._height,this},getNewWidth:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minWidth,this.maxWidth),e&&this._parent&&t>this._parent.width&&(t=Math.max(this.minWidth,this._parent.width)),t},getNewHeight:function(t,e){return void 0===e&&(e=!0),t=n(t,this.minHeight,this.maxHeight),e&&this._parent&&t>this._parent.height&&(t=Math.max(this.minHeight,this._parent.height)),t},constrain:function(t,e,i){void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=!0),t=this.getNewWidth(t),e=this.getNewHeight(e);var n=this.snapTo,s=0===e?1:t/e;return i&&this.aspectRatio>s||!i&&this.aspectRatio0&&(t=(e=r(e,n.y))*this.aspectRatio)):(i&&this.aspectRatios)&&(t=(e=r(e,n.y))*this.aspectRatio,n.x>0&&(e=(t=r(t,n.x))*(1/this.aspectRatio))),this._width=t,this._height=e,this},fitTo:function(t,e){return this.constrain(t,e,!0)},envelop:function(t,e){return this.constrain(t,e,!1)},setWidth:function(t){return this.setSize(t,this._height)},setHeight:function(t){return this.setSize(this._width,t)},toString:function(){return"[{ Size (width="+this._width+" height="+this._height+" aspectRatio="+this.aspectRatio+" aspectMode="+this.aspectMode+") }]"},setCSS:function(t){t&&t.style&&(t.style.width=this._width+"px",t.style.height=this._height+"px")},copy:function(t){return t.setAspectMode(this.aspectMode),t.aspectRatio=this.aspectRatio,t.setSize(this.width,this.height)},destroy:function(){this._parent=null,this.snapTo=null},width:{get:function(){return this._width},set:function(t){this.setSize(t,this._height)}},height:{get:function(){return this._height},set:function(t){this.setSize(this._width,t)}}});a.NONE=0,a.WIDTH_CONTROLS_HEIGHT=1,a.HEIGHT_CONTROLS_WIDTH=2,a.FIT=3,a.ENVELOP=4,t.exports=a},function(t,e,i){var n=i(0),s=i(123),r=i(19),o=i(18),a=i(6),h=i(81),l=i(1),u=i(368),c=i(178),d=new n({initialize:function(t,e){if(this.game=t,this.keys={},this.scenes=[],this._pending=[],this._start=[],this._queue=[],this._data={},this.isProcessing=!1,this.isBooted=!1,this.customViewports=0,e){Array.isArray(e)||(e=[e]);for(var i=0;i-1&&(delete this.keys[n],this.scenes.splice(i,1),this._start.indexOf(n)>-1&&(i=this._start.indexOf(n),this._start.splice(i,1)),e.sys.destroy())}return this},bootScene:function(t){var e,i=t.sys,n=i.settings;t.init&&(t.init.call(t,n.data),n.status=s.INIT,n.isTransition&&i.events.emit(r.TRANSITION_INIT,n.transitionFrom,n.transitionDuration)),i.load&&(e=i.load).reset(),e&&t.preload?(t.preload.call(t),0===e.list.size?this.create(t):(n.status=s.LOADING,e.once(h.COMPLETE,this.loadComplete,this),e.start())):this.create(t)},loadComplete:function(t){var e=t.scene;this.game.sound&&this.game.sound.onBlurPausedSounds&&this.game.sound.unlock(),this.create(e)},payloadComplete:function(t){this.bootScene(t.scene)},update:function(t,e){this.processQueue(),this.isProcessing=!0;for(var i=this.scenes.length-1;i>=0;i--){var n=this.scenes[i].sys;n.settings.status>s.START&&n.settings.status<=s.RUNNING&&n.step(t,e)}},render:function(t){for(var e=0;e=s.LOADING&&i.settings.status0){var i=this.getScene(t);this.scenes.splice(e,1),this.scenes.unshift(i)}}return this},moveDown:function(t){if(this.isProcessing)this._queue.push({op:"moveDown",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e>0){var i=e-1,n=this.getScene(t),s=this.getAt(i);this.scenes[e]=s,this.scenes[i]=n}}return this},moveUp:function(t){if(this.isProcessing)this._queue.push({op:"moveUp",keyA:t,keyB:null});else{var e=this.getIndex(t);if(e=r.x&&t=r.y&&e=r.x&&t=r.y&&e-1){var o=this.context.getImageData(t,e,1,1);o.data[0]=i,o.data[1]=n,o.data[2]=s,o.data[3]=r,this.context.putImageData(o,t,e)}return this},putData:function(t,e,i,n,s,r,o){return void 0===n&&(n=0),void 0===s&&(s=0),void 0===r&&(r=t.width),void 0===o&&(o=t.height),this.context.putImageData(t,e,i,n,s,r,o),this},getData:function(t,e,i,n){return t=s(Math.floor(t),0,this.width-1),e=s(Math.floor(e),0,this.height-1),i=s(i,1,this.width-t),n=s(n,1,this.height-e),this.context.getImageData(t,e,i,n)},getPixel:function(t,e,i){i||(i=new r);var n=this.getIndex(t,e);if(n>-1){var s=this.data,o=s[n+0],a=s[n+1],h=s[n+2],l=s[n+3];i.setTo(o,a,h,l)}return i},getPixels:function(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===n&&(n=i),t=Math.abs(Math.round(t)),e=Math.abs(Math.round(e));for(var o=s(t,0,this.width),a=s(t+i,0,this.width),h=s(e,0,this.height),l=s(e+n,0,this.height),u=new r,c=[],d=h;d0)&&(!!n.prototype.pause.call(this)&&(this.currentConfig.seek=this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0),this.stopAndReleaseAudioTag(),this.emit(r.PAUSE,this),!0)))},resume:function(){return!this.manager.isLocked(this,"resume")&&(!(this.startTime>0)&&(!!n.prototype.resume.call(this)&&(!!this.pickAndPlayAudioTag()&&(this.emit(r.RESUME,this),!0))))},stop:function(){return!this.manager.isLocked(this,"stop")&&(!!n.prototype.stop.call(this)&&(this.stopAndReleaseAudioTag(),this.emit(r.STOP,this),!0))},pickAndPlayAudioTag:function(){if(!this.pickAudioTag())return this.reset(),!1;var t=this.currentConfig.seek,e=this.currentConfig.delay,i=(this.currentMarker?this.currentMarker.start:0)+t;return this.previousTime=i,this.audio.currentTime=i,this.applyConfig(),0===e?(this.startTime=0,this.audio.paused&&this.playCatchPromise()):(this.startTime=window.performance.now()+1e3*e,this.audio.paused||this.audio.pause()),this.resetConfig(),!0},pickAudioTag:function(){if(this.audio)return!0;for(var t=0;t0)this.startTime=n-this.manager.loopEndOffset?(this.audio.currentTime=i+Math.max(0,s-n),s=this.audio.currentTime):s=n)return this.reset(),this.stopAndReleaseAudioTag(),void this.emit(r.COMPLETE,this);this.previousTime=s}},destroy:function(){n.prototype.destroy.call(this),this.tags=null,this.audio&&this.stopAndReleaseAudioTag()},updateMute:function(){this.audio&&(this.audio.muted=this.currentConfig.mute||this.manager.mute)},updateVolume:function(){this.audio&&(this.audio.volume=this.currentConfig.volume*this.manager.volume)},calculateRate:function(){n.prototype.calculateRate.call(this),this.audio&&(this.audio.playbackRate=this.totalRate)},mute:{get:function(){return this.currentConfig.mute},set:function(t){this.currentConfig.mute=t,this.manager.isLocked(this,"mute",t)||(this.updateMute(),this.emit(r.MUTE,this,t))}},setMute:function(t){return this.mute=t,this},volume:{get:function(){return this.currentConfig.volume},set:function(t){this.currentConfig.volume=t,this.manager.isLocked(this,"volume",t)||(this.updateVolume(),this.emit(r.VOLUME,this,t))}},setVolume:function(t){return this.volume=t,this},rate:{get:function(){return this.currentConfig.rate},set:function(t){this.currentConfig.rate=t,this.manager.isLocked(this,r.RATE,t)||(this.calculateRate(),this.emit(r.RATE,this,t))}},setRate:function(t){return this.rate=t,this},detune:{get:function(){return this.currentConfig.detune},set:function(t){this.currentConfig.detune=t,this.manager.isLocked(this,r.DETUNE,t)||(this.calculateRate(),this.emit(r.DETUNE,this,t))}},setDetune:function(t){return this.detune=t,this},seek:{get:function(){return this.isPlaying?this.audio.currentTime-(this.currentMarker?this.currentMarker.start:0):this.isPaused?this.currentConfig.seek:0},set:function(t){this.manager.isLocked(this,"seek",t)||this.startTime>0||(this.isPlaying||this.isPaused)&&(t=Math.min(Math.max(0,t),this.duration),this.isPlaying?(this.previousTime=t,this.audio.currentTime=t):this.isPaused&&(this.currentConfig.seek=t),this.emit(r.SEEK,this,t))}},setSeek:function(t){return this.seek=t,this},loop:{get:function(){return this.currentConfig.loop},set:function(t){this.currentConfig.loop=t,this.manager.isLocked(this,"loop",t)||(this.audio&&(this.audio.loop=t),this.emit(r.LOOP,this,t))}},setLoop:function(t){return this.loop=t,this}});t.exports=o},function(t,e,i){var n=i(124),s=i(0),r=i(9),o=i(378),a=i(1),h=new s({Extends:r,initialize:function(t){r.call(this),this.game=t,this.sounds=[],this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.pauseOnBlur=!0,this.locked=!1},add:function(t,e){var i=new o(this,t,e);return this.sounds.push(i),i},addAudioSprite:function(t,e){var i=this.add(t,e);return i.spritemap={},i},play:function(t,e){return!1},playAudioSprite:function(t,e,i){return!1},remove:function(t){return n.prototype.remove.call(this,t)},removeByKey:function(t){return n.prototype.removeByKey.call(this,t)},pauseAll:a,resumeAll:a,stopAll:a,update:a,setRate:a,setDetune:a,setMute:a,setVolume:a,forEachActiveSound:function(t,e){n.prototype.forEachActiveSound.call(this,t,e)},destroy:function(){n.prototype.destroy.call(this)}});t.exports=h},function(t,e,i){var n=i(125),s=i(0),r=i(9),o=i(17),a=new s({Extends:r,initialize:function(t,e,i){void 0===i&&(i={}),r.call(this),this.manager=t,this.key=e,this.isPlaying=!1,this.isPaused=!1,this.totalRate=1,this.duration=0,this.totalDuration=0,this.config=o({mute:!1,volume:1,rate:1,detune:0,seek:0,loop:!1,delay:0},i),this.currentConfig=this.config,this.mute=!1,this.volume=1,this.rate=1,this.detune=0,this.seek=0,this.loop=!1,this.markers={},this.currentMarker=null,this.pendingRemove=!1},addMarker:function(t){return!1},updateMarker:function(t){return!1},removeMarker:function(t){return null},play:function(t,e){return!1},pause:function(){return!1},resume:function(){return!1},stop:function(){return!1},destroy:function(){this.manager.remove(this),n.prototype.destroy.call(this)}});t.exports=a},function(t,e,i){var n=i(380),s=i(124),r=i(0),o=i(59),a=i(381),h=new r({Extends:s,initialize:function(t){this.context=this.createAudioContext(t),this.masterMuteNode=this.context.createGain(),this.masterVolumeNode=this.context.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(this.context.destination),this.destination=this.masterMuteNode,this.locked="suspended"===this.context.state&&("ontouchstart"in window||"onclick"in window),s.call(this,t),this.locked&&this.unlock()},createAudioContext:function(t){var e=t.config.audio;return e&&e.context?(e.context.resume(),e.context):new AudioContext},setAudioContext:function(t){return this.context&&this.context.close(),this.masterMuteNode&&this.masterMuteNode.disconnect(),this.masterVolumeNode&&this.masterVolumeNode.disconnect(),this.context=t,this.masterMuteNode=t.createGain(),this.masterVolumeNode=t.createGain(),this.masterMuteNode.connect(this.masterVolumeNode),this.masterVolumeNode.connect(t.destination),this.destination=this.masterMuteNode,this},add:function(t,e){var i=new a(this,t,e);return this.sounds.push(i),i},decodeAudio:function(t,e){var i;i=Array.isArray(t)?t:[{key:t,data:e}];for(var s=this.game.cache.audio,r=i.length,a=0;a>4,u[h++]=(15&i)<<4|s>>2,u[h++]=(3&s)<<6|63&r;return l}},function(t,e,i){var n=i(125),s=i(0),r=i(59),o=new s({Extends:n,initialize:function(t,e,i){if(void 0===i&&(i={}),this.audioBuffer=t.game.cache.audio.get(e),!this.audioBuffer)throw new Error('There is no audio asset with key "'+e+'" in the audio cache');this.source=null,this.loopSource=null,this.muteNode=t.context.createGain(),this.volumeNode=t.context.createGain(),this.playTime=0,this.startTime=0,this.loopTime=0,this.rateUpdates=[],this.hasEnded=!1,this.hasLooped=!1,this.muteNode.connect(this.volumeNode),this.volumeNode.connect(t.destination),this.duration=this.audioBuffer.duration,this.totalDuration=this.audioBuffer.duration,n.call(this,t,e,i)},play:function(t,e){return!!n.prototype.play.call(this,t,e)&&(this.stopAndRemoveBufferSource(),this.createAndStartBufferSource(),this.emit(r.PLAY,this),!0)},pause:function(){return!(this.manager.context.currentTime-1;r--)n[s][r]=t[r][s]}return n}},function(t,e){function i(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function n(t,e){return te?1:0}var s=function(t,e,r,o,a){for(void 0===r&&(r=0),void 0===o&&(o=t.length-1),void 0===a&&(a=n);o>r;){if(o-r>600){var h=o-r+1,l=e-r+1,u=Math.log(h),c=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*c*(h-c)/h)*(l-h/2<0?-1:1),f=Math.max(r,Math.floor(e-l*c/h+d)),p=Math.min(o,Math.floor(e+(h-l)*c/h+d));s(t,e,f,p,a)}var g=t[e],v=r,m=o;for(i(t,r,e),a(t[o],g)>0&&i(t,r,o);v0;)m--}0===a(t[r],g)?i(t,r,m):i(t,++m,o),m<=e&&(r=m+1),e<=m&&(o=m-1)}};t.exports=s},function(t,e,i){var n=i(6),s=i(114),r=function(t,e,i){for(var n=[],s=0;s0?s.delayedPlay(d,r,o):s.load(r)}return t}},function(t,e,i){var n=i(11);t.exports=function(t,e,i){void 0===i&&(i=new n);var s=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.right,e.right)-s,a=Math.max(t.bottom,e.bottom)-r;return i.setTo(s,r,o,a)}},function(t,e,i){var n=i(0),s=i(12),r=i(950),o=i(14),a=i(7),h=i(176),l=i(19),u=i(330),c=new n({Extends:o,Mixins:[s.AlphaSingle,s.BlendMode,s.Depth,s.Origin,s.ScrollFactor,s.Transform,s.Visible,r],initialize:function(t,e,i,n,s,r){o.call(this,t,"DOMElement"),this.parent=t.sys.game.domContainer,this.cache=t.sys.cache.html,this.node,this.transformOnly=!1,this.skewX=0,this.skewY=0,this.rotate3d=new u,this.rotate3dAngle="deg",this.width=0,this.height=0,this.displayWidth=0,this.displayHeight=0,this.handler=this.dispatchNativeEvent.bind(this),this.setPosition(e,i),"string"==typeof n?"#"===n[0]?this.setElement(n.substr(1),s,r):this.createElement(n,s,r):n&&this.setElement(n,s,r),t.sys.events.on(l.SLEEP,this.handleSceneEvent,this),t.sys.events.on(l.WAKE,this.handleSceneEvent,this)},handleSceneEvent:function(t){var e=this.node,i=e.style;e&&(i.display=t.settings.visible?"block":"none")},setSkew:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.skewX=t,this.skewY=e,this},setPerspective:function(t){return this.parent.style.perspective=t+"px",this},perspective:{get:function(){return parseFloat(this.parent.style.perspective)},set:function(t){this.parent.style.perspective=t+"px"}},addListener:function(t){if(this.node){t=t.split(" ");for(var e=0;e>>16,y=(65280&p)>>>8,x=255&p,c.strokeStyle="rgba("+m+","+y+","+x+","+d+")",c.lineWidth=v,T+=3;break;case n.FILL_STYLE:g=l[T+1],f=l[T+2],m=(16711680&g)>>>16,y=(65280&g)>>>8,x=255&g,c.fillStyle="rgba("+m+","+y+","+x+","+f+")",T+=2;break;case n.BEGIN_PATH:c.beginPath();break;case n.CLOSE_PATH:c.closePath();break;case n.FILL_PATH:h||c.fill();break;case n.STROKE_PATH:h||c.stroke();break;case n.FILL_RECT:h?c.rect(l[T+1],l[T+2],l[T+3],l[T+4]):c.fillRect(l[T+1],l[T+2],l[T+3],l[T+4]),T+=4;break;case n.FILL_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.fill(),T+=6;break;case n.STROKE_TRIANGLE:c.beginPath(),c.moveTo(l[T+1],l[T+2]),c.lineTo(l[T+3],l[T+4]),c.lineTo(l[T+5],l[T+6]),c.closePath(),h||c.stroke(),T+=6;break;case n.LINE_TO:c.lineTo(l[T+1],l[T+2]),T+=2;break;case n.MOVE_TO:c.moveTo(l[T+1],l[T+2]),T+=2;break;case n.LINE_FX_TO:c.lineTo(l[T+1],l[T+2]),T+=5;break;case n.MOVE_FX_TO:c.moveTo(l[T+1],l[T+2]),T+=5;break;case n.SAVE:c.save();break;case n.RESTORE:c.restore();break;case n.TRANSLATE:c.translate(l[T+1],l[T+2]),T+=2;break;case n.SCALE:c.scale(l[T+1],l[T+2]),T+=2;break;case n.ROTATE:c.rotate(l[T+1]),T+=1;break;case n.GRADIENT_FILL_STYLE:T+=5;break;case n.GRADIENT_LINE_STYLE:T+=6;break;case n.SET_TEXTURE:T+=2}c.restore()}}},function(t,e,i){var n=i(0),s=i(2),r=new n({initialize:function(t,e,i,n,r){if("object"==typeof t){var o=t;t=s(o,"x",0),e=s(o,"y",0),i=s(o,"power",0),n=s(o,"epsilon",100),r=s(o,"gravity",50)}else void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=100),void 0===r&&(r=50);this.x=t,this.y=e,this.active=!0,this._gravity=r,this._power=0,this._epsilon=0,this.power=i,this.epsilon=n},update:function(t,e){var i=this.x-t.x,n=this.y-t.y,s=i*i+n*n;if(0!==s){var r=Math.sqrt(s);s0},resetPosition:function(){this.x=0,this.y=0},fire:function(t,e){var i=this.emitter;this.frame=i.getFrame(),i.emitZone&&i.emitZone.getPoint(this),void 0===t?(i.follow&&(this.x+=i.follow.x+i.followOffset.x),this.x+=i.x.onEmit(this,"x")):this.x+=t,void 0===e?(i.follow&&(this.y+=i.follow.y+i.followOffset.y),this.y+=i.y.onEmit(this,"y")):this.y+=e,this.life=i.lifespan.onEmit(this,"lifespan"),this.lifeCurrent=this.life,this.lifeT=0;var n=i.speedX.onEmit(this,"speedX"),o=i.speedY?i.speedY.onEmit(this,"speedY"):n;if(i.radial){var a=s(i.angle.onEmit(this,"angle"));this.velocityX=Math.cos(a)*Math.abs(n),this.velocityY=Math.sin(a)*Math.abs(o)}else if(i.moveTo){var h=i.moveToX.onEmit(this,"moveToX"),l=i.moveToY?i.moveToY.onEmit(this,"moveToY"):h,u=Math.atan2(l-this.y,h-this.x),c=r(this.x,this.y,h,l)/(this.life/1e3);this.velocityX=Math.cos(u)*c,this.velocityY=Math.sin(u)*c}else this.velocityX=n,this.velocityY=o;i.acceleration&&(this.accelerationX=i.accelerationX.onEmit(this,"accelerationX"),this.accelerationY=i.accelerationY.onEmit(this,"accelerationY")),this.maxVelocityX=i.maxVelocityX.onEmit(this,"maxVelocityX"),this.maxVelocityY=i.maxVelocityY.onEmit(this,"maxVelocityY"),this.delayCurrent=i.delay.onEmit(this,"delay"),this.scaleX=i.scaleX.onEmit(this,"scaleX"),this.scaleY=i.scaleY?i.scaleY.onEmit(this,"scaleY"):this.scaleX,this.angle=i.rotate.onEmit(this,"rotate"),this.rotation=s(this.angle),this.bounce=i.bounce.onEmit(this,"bounce"),this.alpha=i.alpha.onEmit(this,"alpha"),this.tint=i.tint.onEmit(this,"tint")},computeVelocity:function(t,e,i,n){var s=this.velocityX,r=this.velocityY,o=this.accelerationX,a=this.accelerationY,h=this.maxVelocityX,l=this.maxVelocityY;s+=t.gravityX*i,r+=t.gravityY*i,o&&(s+=o*i),a&&(r+=a*i),s>h?s=h:s<-h&&(s=-h),r>l?r=l:r<-l&&(r=-l),this.velocityX=s,this.velocityY=r;for(var u=0;ue.right&&t.collideRight&&(this.x=e.right,this.velocityX*=i),this.ye.bottom&&t.collideBottom&&(this.y=e.bottom,this.velocityY*=i)},update:function(t,e,i){if(this.delayCurrent>0)return this.delayCurrent-=t,!1;var n=this.emitter,r=1-this.lifeCurrent/this.life;return this.lifeT=r,this.computeVelocity(n,t,e,i),this.x+=this.velocityX*e,this.y+=this.velocityY*e,n.bounds&&this.checkBounds(n),n.deathZone&&n.deathZone.willKill(this)?(this.lifeCurrent=0,!0):(this.scaleX=n.scaleX.onUpdate(this,"scaleX",r,this.scaleX),n.scaleY?this.scaleY=n.scaleY.onUpdate(this,"scaleY",r,this.scaleY):this.scaleY=this.scaleX,this.angle=n.rotate.onUpdate(this,"rotate",r,this.angle),this.rotation=s(this.angle),this.alpha=n.alpha.onUpdate(this,"alpha",r,this.alpha),this.tint=n.tint.onUpdate(this,"tint",r,this.tint),this.lifeCurrent-=t,this.lifeCurrent<=0)}});t.exports=o},function(t,e,i){var n=i(52),s=i(0),r=i(12),o=i(397),a=i(398),h=i(967),l=i(2),u=i(183),c=i(399),d=i(99),f=i(395),p=i(400),g=i(11),v=i(128),m=i(3),y=i(58),x=new s({Mixins:[r.BlendMode,r.Mask,r.ScrollFactor,r.Visible],initialize:function(t,e){this.manager=t,this.texture=t.texture,this.frames=[t.defaultFrame],this.defaultFrame=t.defaultFrame,this.configFastMap=["active","blendMode","collideBottom","collideLeft","collideRight","collideTop","deathCallback","deathCallbackScope","emitCallback","emitCallbackScope","follow","frequency","gravityX","gravityY","maxParticles","name","on","particleBringToTop","particleClass","radial","timeScale","trackVisible","visible"],this.configOpMap=["accelerationX","accelerationY","angle","alpha","bounce","delay","lifespan","maxVelocityX","maxVelocityY","moveToX","moveToY","quantity","rotate","scaleX","scaleY","speedX","speedY","tint","x","y"],this.name="",this.particleClass=f,this.x=new h(e,"x",0,!0),this.y=new h(e,"y",0,!0),this.radial=!0,this.gravityX=0,this.gravityY=0,this.acceleration=!1,this.accelerationX=new h(e,"accelerationX",0,!0),this.accelerationY=new h(e,"accelerationY",0,!0),this.maxVelocityX=new h(e,"maxVelocityX",1e4,!0),this.maxVelocityY=new h(e,"maxVelocityY",1e4,!0),this.speedX=new h(e,"speedX",0,!0),this.speedY=new h(e,"speedY",0,!0),this.moveTo=!1,this.moveToX=new h(e,"moveToX",0,!0),this.moveToY=new h(e,"moveToY",0,!0),this.bounce=new h(e,"bounce",0,!0),this.scaleX=new h(e,"scaleX",1),this.scaleY=new h(e,"scaleY",1),this.tint=new h(e,"tint",4294967295),this.alpha=new h(e,"alpha",1),this.lifespan=new h(e,"lifespan",1e3,!0),this.angle=new h(e,"angle",{min:0,max:360},!0),this.rotate=new h(e,"rotate",0),this.emitCallback=null,this.emitCallbackScope=null,this.deathCallback=null,this.deathCallbackScope=null,this.maxParticles=0,this.quantity=new h(e,"quantity",1,!0),this.delay=new h(e,"delay",0,!0),this.frequency=0,this.on=!0,this.particleBringToTop=!0,this.timeScale=1,this.emitZone=null,this.deathZone=null,this.bounds=null,this.collideLeft=!0,this.collideRight=!0,this.collideTop=!0,this.collideBottom=!0,this.active=!0,this.visible=!0,this.blendMode=n.NORMAL,this.follow=null,this.followOffset=new m,this.trackVisible=!1,this.currentFrame=0,this.randomFrame=!0,this.frameQuantity=1,this.dead=[],this.alive=[],this._counter=0,this._frameCounter=0,e&&this.fromJSON(e)},fromJSON:function(t){if(!t)return this;var e=0,i="";for(e=0;e0&&this.getParticleCount()===this.maxParticles},onParticleEmit:function(t,e){return void 0===t?(this.emitCallback=null,this.emitCallbackScope=null):"function"==typeof t&&(this.emitCallback=t,e&&(this.emitCallbackScope=e)),this},onParticleDeath:function(t,e){return void 0===t?(this.deathCallback=null,this.deathCallbackScope=null):"function"==typeof t&&(this.deathCallback=t,e&&(this.deathCallbackScope=e)),this},killAll:function(){for(var t=this.dead,e=this.alive;e.length>0;)t.push(e.pop());return this},forEachAlive:function(t,e){for(var i=this.alive,n=i.length,s=0;s0){var u=this.deathCallback,c=this.deathCallbackScope;for(o=h-1;o>=0;o--){var d=a[o];s.splice(d.index,1),r.push(d.particle),u&&u.call(c,d.particle),d.particle.resetPosition()}}this.on&&(0===this.frequency?this.emitParticle():this.frequency>0&&(this._counter-=e,this._counter<=0&&(this.emitParticle(),this._counter=this.frequency-Math.abs(this._counter))))},depthSortCallback:function(t,e){return t.y-e.y}});t.exports=x},function(t,e,i){var n=new(i(0))({initialize:function(t,e){this.source=t,this.killOnEnter=e},willKill:function(t){var e=this.source.contains(t.x,t.y);return e&&this.killOnEnter||!e&&!this.killOnEnter}});t.exports=n},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s){void 0===n&&(n=!1),void 0===s&&(s=!0),this.source=t,this.points=[],this.quantity=e,this.stepRate=i,this.yoyo=n,this.counter=-1,this.seamless=s,this._length=0,this._direction=0,this.updateSource()},updateSource:function(){if(this.points=this.source.getPoints(this.quantity,this.stepRate),this.seamless){var t=this.points[0],e=this.points[this.points.length-1];t.x===e.x&&t.y===e.y&&this.points.pop()}var i=this._length;return this._length=this.points.length,this._lengththis._length&&(this.counter=this._length-1),this},changeSource:function(t){return this.source=t,this.updateSource()},getPoint:function(t){0===this._direction?(this.counter++,this.counter>=this._length&&(this.yoyo?(this._direction=1,this.counter=this._length-1):this.counter=0)):(this.counter--,-1===this.counter&&(this.yoyo?(this._direction=0,this.counter=0):this.counter=this._length-1));var e=this.points[this.counter];e&&(t.x=e.x,t.y=e.y)}});t.exports=n},function(t,e){t.exports=function(t,e){for(var i=0;i0&&(s=-h.PI2+s%h.PI2):s>h.PI2?s=h.PI2:s<0&&(s=h.PI2+s%h.PI2);for(var u,c=[a+Math.cos(n)*i,l+Math.sin(n)*i];e<1;)u=s*e+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),e+=t;return u=s+n,c.push(a+Math.cos(u)*i,l+Math.sin(u)*i),c.push(a+Math.cos(n)*i,l+Math.sin(n)*i),this.pathIndexes=o(c),this.pathData=c,this}});t.exports=u},function(t,e,i){var n=i(0),s=i(993),r=i(66),o=i(11),a=i(30),h=new n({Extends:a,Mixins:[s],initialize:function(t,e,i,n,s,r){void 0===e&&(e=0),void 0===i&&(i=0),a.call(this,t,"Curve",n),this._smoothness=32,this._curveBounds=new o,this.closePath=!1,this.setPosition(e,i),void 0!==s&&this.setFillStyle(s,r),this.updateData()},smoothness:{get:function(){return this._smoothness},set:function(t){this._smoothness=t,this.updateData()}},setSmoothness:function(t){return this._smoothness=t,this.updateData()},updateData:function(){var t=this._curveBounds,e=this._smoothness;this.geom.getBounds(t,e),this.setSize(t.width,t.height),this.updateDisplayOrigin();for(var i=[],n=this.geom.getPoints(e),s=0;sc+v)){var m=g.getPoint((u-c)/v);o.push(m);break}c+=v}return o}},function(t,e,i){var n=i(57),s=i(56);t.exports=function(t){for(var e=t.points,i=0,r=0;r0&&r.push(i([0,0],n[0])),e=0;e1&&r.push(i([0,0],n[n.length-1])),t.setTo(r)}},function(t,e,i){var n=i(0),s=i(11),r=i(30),o=i(1014),a=new n({Extends:r,Mixins:[o],initialize:function(t,e,i,n,o,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=128),void 0===o&&(o=128),r.call(this,t,"Rectangle",new s(0,0,n,o)),this.setPosition(e,i),this.setSize(n,o),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},updateData:function(){var t=[],e=this.geom,i=this._tempLine;return e.getLineA(i),t.push(i.x1,i.y1,i.x2,i.y2),e.getLineB(i),t.push(i.x2,i.y2),e.getLineC(i),t.push(i.x2,i.y2),e.getLineD(i),t.push(i.x2,i.y2),this.pathData=t,this}});t.exports=a},function(t,e,i){var n=i(1017),s=i(0),r=i(66),o=i(30),a=new s({Extends:o,Mixins:[n],initialize:function(t,e,i,n,s,r,a,h){void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=5),void 0===s&&(s=32),void 0===r&&(r=64),o.call(this,t,"Star",null),this._points=n,this._innerRadius=s,this._outerRadius=r,this.setPosition(e,i),this.setSize(2*r,2*r),void 0!==a&&this.setFillStyle(a,h),this.updateDisplayOrigin(),this.updateData()},setPoints:function(t){return this._points=t,this.updateData()},setInnerRadius:function(t){return this._innerRadius=t,this.updateData()},setOuterRadius:function(t){return this._outerRadius=t,this.updateData()},points:{get:function(){return this._points},set:function(t){this._points=t,this.updateData()}},innerRadius:{get:function(){return this._innerRadius},set:function(t){this._innerRadius=t,this.updateData()}},outerRadius:{get:function(){return this._outerRadius},set:function(t){this._outerRadius=t,this.updateData()}},updateData:function(){var t=[],e=this._points,i=this._innerRadius,n=this._outerRadius,s=Math.PI/2*3,o=Math.PI/e,a=n,h=n;t.push(a,h+-n);for(var l=0;l=1)return i.x=r.x1,i.y=r.y1,i;var h=s(r),l=s(o),u=s(a),c=(h+l+u)*e,d=0;return ch+l?(d=(c-=h+l)/u,i.x=a.x1+(a.x2-a.x1)*d,i.y=a.y1+(a.y2-a.y1)*d):(d=(c-=h)/l,i.x=o.x1+(o.x2-o.x1)*d,i.y=o.y1+(o.y2-o.y1)*d),i}},function(t,e,i){var n=i(57),s=i(4);t.exports=function(t,e,i,r){void 0===r&&(r=[]);var o=t.getLineA(),a=t.getLineB(),h=t.getLineC(),l=n(o),u=n(a),c=n(h),d=l+u+c;e||(e=d/i);for(var f=0;fl+u?(g=(p-=l+u)/c,v.x=h.x1+(h.x2-h.x1)*g,v.y=h.y1+(h.y2-h.y1)*g):(g=(p-=l)/u,v.x=a.x1+(a.x2-a.x1)*g,v.y=a.y1+(a.y2-a.y1)*g),r.push(v)}return r}},function(t,e){t.exports=function(t,e,i){if(!t||"number"==typeof t)return!1;if(t.hasOwnProperty(e))return t[e]=i,!0;if(-1!==e.indexOf(".")){for(var n=e.split("."),s=t,r=t,o=0;o0?(h=this.lightPool.pop()).set(t,e,i,a[0],a[1],a[2],o):h=new s(t,e,i,a[0],a[1],a[2],o),this.lights.push(h),h},removeLight:function(t){var e=this.lights.indexOf(t);return e>=0&&(this.lightPool.push(t),this.lights.splice(e,1)),this},shutdown:function(){for(;this.lights.length>0;)this.lightPool.push(this.lights.pop());this.ambientColor={r:.1,g:.1,b:.1},this.culledLights.length=0,this.lights.length=0},destroy:function(){this.shutdown()}});t.exports=o},function(t,e,i){var n=i(46),s=i(17),r={Circle:i(1078),Ellipse:i(1088),Intersects:i(423),Line:i(1107),Point:i(1128),Polygon:i(1142),Rectangle:i(436),Triangle:i(1172)};r=s(!1,r,n),t.exports=r},function(t,e,i){t.exports={CircleToCircle:i(202),CircleToRectangle:i(203),GetCircleToCircle:i(1098),GetCircleToRectangle:i(1099),GetLineToCircle:i(204),GetLineToRectangle:i(206),GetRectangleIntersection:i(1100),GetRectangleToRectangle:i(1101),GetRectangleToTriangle:i(1102),GetTriangleToCircle:i(1103),GetTriangleToLine:i(428),GetTriangleToTriangle:i(1104),LineToCircle:i(205),LineToLine:i(84),LineToRectangle:i(424),PointToLine:i(432),PointToLineSegment:i(1105),RectangleToRectangle:i(131),RectangleToTriangle:i(425),RectangleToValues:i(1106),TriangleToCircle:i(427),TriangleToLine:i(429),TriangleToTriangle:i(430)}},function(t,e){t.exports=function(t,e){var i=t.x1,n=t.y1,s=t.x2,r=t.y2,o=e.x,a=e.y,h=e.right,l=e.bottom,u=0;if(i>=o&&i<=h&&n>=a&&n<=l||s>=o&&s<=h&&r>=a&&r<=l)return!0;if(i=o){if((u=n+(r-n)*(o-i)/(s-i))>a&&u<=l)return!0}else if(i>h&&s<=h&&(u=n+(r-n)*(h-i)/(s-i))>=a&&u<=l)return!0;if(n=a){if((u=i+(s-i)*(a-n)/(r-n))>=o&&u<=h)return!0}else if(n>l&&r<=l&&(u=i+(s-i)*(l-n)/(r-n))>=o&&u<=h)return!0;return!1}},function(t,e,i){var n=i(84),s=i(47),r=i(207),o=i(426);t.exports=function(t,e){if(e.left>t.right||e.rightt.bottom||e.bottom0}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x,y:t.y}),e.push({x:t.right,y:t.y}),e.push({x:t.right,y:t.bottom}),e.push({x:t.x,y:t.bottom}),e}},function(t,e,i){var n=i(205),s=i(83);t.exports=function(t,e){return!(t.left>e.right||t.righte.bottom||t.bottome.right||t.righte.bottom||t.bottom0||(c=s(e),(d=n(t,c,!0)).length>0)}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=[]),e.push({x:t.x1,y:t.y1}),e.push({x:t.x2,y:t.y2}),e.push({x:t.x3,y:t.y3}),e}},function(t,e){t.exports=function(t,e,i){void 0===i&&(i=1);var n=e.x1,s=e.y1,r=e.x2,o=e.y2,a=t.x,h=t.y,l=(r-n)*(r-n)+(o-s)*(o-s);if(0===l)return!1;var u=((a-n)*(r-n)+(h-s)*(o-s))/l;if(u<0)return Math.sqrt((n-a)*(n-a)+(s-h)*(s-h))<=i;if(u>=0&&u<=1){var c=((s-h)*(r-n)-(n-a)*(o-s))/l;return Math.abs(c)*Math.sqrt(l)<=i}return Math.sqrt((r-a)*(r-a)+(o-h)*(o-h))<=i}},function(t,e,i){var n=i(13),s=i(58),r=i(85);t.exports=function(t){var e=r(t)-n.TAU;return s(e,-Math.PI,Math.PI)}},function(t,e){t.exports=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)}},function(t,e){t.exports=function(t){return t.x*t.x+t.y*t.y}},function(t,e,i){var n=i(11);n.Area=i(1147),n.Ceil=i(1148),n.CeilAll=i(1149),n.CenterOn=i(165),n.Clone=i(1150),n.Contains=i(47),n.ContainsPoint=i(1151),n.ContainsRect=i(437),n.CopyFrom=i(1152),n.Decompose=i(426),n.Equals=i(1153),n.FitInside=i(1154),n.FitOutside=i(1155),n.Floor=i(1156),n.FloorAll=i(1157),n.FromPoints=i(174),n.GetAspectRatio=i(209),n.GetCenter=i(1158),n.GetPoint=i(149),n.GetPoints=i(271),n.GetSize=i(1159),n.Inflate=i(1160),n.Intersection=i(1161),n.MarchingAnts=i(282),n.MergePoints=i(1162),n.MergeRect=i(1163),n.MergeXY=i(1164),n.Offset=i(1165),n.OffsetPoint=i(1166),n.Overlaps=i(1167),n.Perimeter=i(112),n.PerimeterPoint=i(1168),n.Random=i(152),n.RandomOutside=i(1169),n.SameDimensions=i(1170),n.Scale=i(1171),n.Union=i(386),t.exports=n},function(t,e){t.exports=function(t,e){return!(e.width*e.height>t.width*t.height)&&e.x>t.x&&e.xt.x&&e.rightt.y&&e.yt.y&&e.bottom=this.threshold?this.pressed||(this.pressed=!0,this.events.emit(s.BUTTON_DOWN,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_DOWN,i,t,this)):this.pressed&&(this.pressed=!1,this.events.emit(s.BUTTON_UP,e,this,t),this.pad.emit(s.GAMEPAD_BUTTON_UP,i,t,this))},destroy:function(){this.pad=null,this.events=null}});t.exports=r},function(t,e,i){var n=i(442),s=i(443),r=i(0),o=i(9),a=i(3),h=new r({Extends:o,initialize:function(t,e){o.call(this),this.manager=t,this.pad=e,this.id=e.id,this.index=e.index;for(var i=[],r=0;r=2&&(this.leftStick.set(r[0].getValue(),r[1].getValue()),s>=4&&this.rightStick.set(r[2].getValue(),r[3].getValue()))},destroy:function(){var t;for(this.removeAllListeners(),this.manager=null,this.pad=null,t=0;t=r;for(i=0;i=r;)this._elapsed-=r,this.step(s)}},step:function(t){var e,i,n=this.bodies.entries,s=n.length;for(e=0;e0){var l=this.tree,u=this.staticTree;for(n=(i=h.entries).length,t=0;t-1&&p>g&&(t.velocity.normalize().scale(g),p=g),t.speed=p},separate:function(t,e,i,n,s){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(n,t.gameObject,e.gameObject))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,s);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h=o.center;if((h.ya.bottom)&&(h.xa.right))return this.separateCircle(t,e,s)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)r.right&&(s=h(o.x,o.y,r.right,r.y)-o.radius):o.y>r.bottom&&(o.xr.right&&(s=h(o.x,o.y,r.right,r.bottom)-o.radius)),s*=-1}else s=t.halfWidth+e.halfWidth-h(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s&&(t.onOverlap||e.onOverlap)&&this.emit(u.OVERLAP,t.gameObject,e.gameObject,t,e),0!==s;var a=t.center.x-e.center.x,l=t.center.y-e.center.y,c=Math.sqrt(Math.pow(a,2)+Math.pow(l,2)),d=(e.center.x-t.center.x)/c||0,f=(e.center.y-t.center.y)/c||0,v=2*(t.velocity.x*d+t.velocity.y*f-e.velocity.x*d-e.velocity.y*f)/(t.mass+e.mass);t.immovable||(t.velocity.x=t.velocity.x-v*t.mass*d,t.velocity.y=t.velocity.y-v*t.mass*f),e.immovable||(e.velocity.x=e.velocity.x+v*e.mass*d,e.velocity.y=e.velocity.y+v*e.mass*f);var m=e.velocity.x-t.velocity.x,y=e.velocity.y-t.velocity.y,x=Math.atan2(y,m),T=this._frameTime;return t.immovable||e.immovable||(s/=2),t.immovable||(t.x+=t.velocity.x*T-s*Math.cos(x),t.y+=t.velocity.y*T-s*Math.sin(x)),e.immovable||(e.x+=e.velocity.x*T+s*Math.cos(x),e.y+=e.velocity.y*T+s*Math.sin(x)),t.velocity.x*=t.bounce.x,t.velocity.y*=t.bounce.y,e.velocity.x*=e.bounce.x,e.velocity.y*=e.bounce.y,(t.onCollide||e.onCollide)&&this.emit(u.COLLIDE,t.gameObject,e.gameObject,t,e),!0},intersects:function(t,e){return t!==e&&(t.isCircle||e.isCircle?t.isCircle?e.isCircle?h(t.center.x,t.center.y,e.center.x,e.center.y)<=t.halfWidth+e.halfWidth:this.circleBodyIntersects(t,e):this.circleBodyIntersects(e,t):!(t.right<=e.position.x||t.bottom<=e.position.y||t.position.x>=e.right||t.position.y>=e.bottom))},circleBodyIntersects:function(t,e){var i=s(t.center.x,e.left,e.right),n=s(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},overlap:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!0)},collide:function(t,e,i,n,s){return void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=i),this.collideObjects(t,e,i,n,s,!1)},collideObjects:function(t,e,i,n,s,r){var o,a;t.isParent&&void 0===t.physicsType&&(t=t.children.entries),e&&e.isParent&&void 0===e.physicsType&&(e=e.children.entries);var h=Array.isArray(t),l=Array.isArray(e);if(this._total=0,h||l)if(!h&&l)for(o=0;o0},collideHandler:function(t,e,i,n,s,r){if(void 0===e&&t.isParent)return this.collideGroupVsGroup(t,t,i,n,s,r);if(!t||!e)return!1;if(t.body){if(e.body)return this.collideSpriteVsSprite(t,e,i,n,s,r);if(e.isParent)return this.collideSpriteVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideSpriteVsTilemapLayer(t,e,i,n,s,r)}else if(t.isParent){if(e.body)return this.collideSpriteVsGroup(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsGroup(t,e,i,n,s,r);if(e.isTilemap)return this.collideGroupVsTilemapLayer(t,e,i,n,s,r)}else if(t.isTilemap){if(e.body)return this.collideSpriteVsTilemapLayer(e,t,i,n,s,r);if(e.isParent)return this.collideGroupVsTilemapLayer(e,t,i,n,s,r)}},collideSpriteVsSprite:function(t,e,i,n,s,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,n,s,r)&&(i&&i.call(s,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,n,s,r){var o,h,l,u=t.body;if(0!==e.length&&u&&u.enable)if(this.useTree){var c=this.treeMinMax;c.minX=u.left,c.minY=u.top,c.maxX=u.right,c.maxY=u.bottom;var d=e.physicsType===a.DYNAMIC_BODY?this.tree.search(c):this.staticTree.search(c);for(h=d.length,o=0;oc.baseTileWidth){var d=(c.tileWidth-c.baseTileWidth)*e.scaleX;a-=d,l+=d}c.tileHeight>c.baseTileHeight&&(u+=(c.tileHeight-c.baseTileHeight)*e.scaleY);var f=e.getTilesWithinWorldXY(a,h,l,u);return 0!==f.length&&this.collideSpriteVsTilesHandler(t,f,i,n,s,r,!0)},collideSpriteVsTilesHandler:function(t,e,i,n,s,r,o){for(var a,h,l=t.body,c={left:0,right:0,top:0,bottom:0},d=!1,f=0;f0&&t>i&&(t=i)),0!==n&&0!==e&&(e<0&&e<-n?e=-n:e>0&&e>n&&(e=n)),this.gameObject.x+=t,this.gameObject.y+=e}t<0?this.facing=s.FACING_LEFT:t>0&&(this.facing=s.FACING_RIGHT),e<0?this.facing=s.FACING_UP:e>0&&(this.facing=s.FACING_DOWN),this.allowRotation&&(this.gameObject.angle+=this.deltaZ()),this._tx=t,this._ty=e},setBoundsRectangle:function(t){return this.customBoundsRectangle=t||this.world.bounds,this},checkWorldBounds:function(){var t=this.position,e=this.customBoundsRectangle,i=this.world.checkCollision,n=this.worldBounce?-this.worldBounce.x:-this.bounce.x,s=this.worldBounce?-this.worldBounce.y:-this.bounce.y,r=!1;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=n,this.blocked.right=!0,r=!0),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=s,this.blocked.down=!0,r=!0),r&&(this.blocked.none=!1),r},setOffset:function(t,e){return void 0===e&&(e=t),this.offset.set(t,e),this.updateCenter(),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter(),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.offset.set(s-this.halfWidth,r-this.halfHeight)}return this.isCircle=!1,this.radius=0,this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter()):this.isCircle=!1,this},reset:function(t,e){this.stop();var i=this.gameObject;i.setPosition(t,e),i.getTopLeft?i.getTopLeft(this.position):this.position.set(t,e),this.prev.copy(this.position),this.prevFrame.copy(this.position),this.rotation=i.angle,this.preRotation=i.angle,this.updateBounds(),this.updateCenter()},stop:function(){return this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?this.radius>0&&t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom&&(this.center.x-t)*(this.center.x-t)+(this.center.y-e)*(this.center.y-e)<=this.radius*this.radius:h(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this._dx>0?this._dx:-this._dx},deltaAbsY:function(){return this._dy>0?this._dy:-this._dy},deltaX:function(){return this._dx},deltaY:function(){return this._dy},deltaXFinal:function(){return this._tx},deltaYFinal:function(){return this._ty},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.enable=!1,this.world&&this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor),this.isCircle?t.strokeCircle(i,n,this.width/2):(this.checkCollision.up&&t.lineBetween(e.x,e.y,e.x+this.width,e.y),this.checkCollision.right&&t.lineBetween(e.x+this.width,e.y,e.x+this.width,e.y+this.height),this.checkCollision.down&&t.lineBetween(e.x,e.y+this.height,e.x+this.width,e.y+this.height),this.checkCollision.left&&t.lineBetween(e.x,e.y,e.x,e.y+this.height))),this.debugShowVelocity&&(t.lineStyle(t.defaultStrokeWidth,this.world.defaults.velocityDebugColor,1),t.lineBetween(i,n,i+this.velocity.x/2,n+this.velocity.y/2))},willDrawDebug:function(){return this.debugShowBody||this.debugShowVelocity},setCollideWorldBounds:function(t,e,i){void 0===t&&(t=!0),this.collideWorldBounds=t;var n=void 0!==e,s=void 0!==i;return(n||s)&&(this.worldBounce||(this.worldBounce=new l),n&&(this.worldBounce.x=e),s&&(this.worldBounce.y=i)),this},setVelocity:function(t,e){return this.velocity.set(t,e),t=this.velocity.x,e=this.velocity.y,this.speed=Math.sqrt(t*t+e*e),this},setVelocityX:function(t){this.velocity.x=t;var e=t,i=this.velocity.y;return this.speed=Math.sqrt(e*e+i*i),this},setVelocityY:function(t){this.velocity.y=t;var e=this.velocity.x,i=t;return this.speed=Math.sqrt(e*e+i*i),this},setMaxVelocity:function(t,e){return this.maxVelocity.set(t,e),this},setMaxSpeed:function(t){return this.maxSpeed=t,this},setBounce:function(t,e){return this.bounce.set(t,e),this},setBounceX:function(t){return this.bounce.x=t,this},setBounceY:function(t){return this.bounce.y=t,this},setAcceleration:function(t,e){return this.acceleration.set(t,e),this},setAccelerationX:function(t){return this.acceleration.x=t,this},setAccelerationY:function(t){return this.acceleration.y=t,this},setAllowDrag:function(t){return void 0===t&&(t=!0),this.allowDrag=t,this},setAllowGravity:function(t){return void 0===t&&(t=!0),this.allowGravity=t,this},setAllowRotation:function(t){return void 0===t&&(t=!0),this.allowRotation=t,this},setDrag:function(t,e){return this.drag.set(t,e),this},setDragX:function(t){return this.drag.x=t,this},setDragY:function(t){return this.drag.y=t,this},setGravity:function(t,e){return this.gravity.set(t,e),this},setGravityX:function(t){return this.gravity.x=t,this},setGravityY:function(t){return this.gravity.y=t,this},setFriction:function(t,e){return this.friction.set(t,e),this},setFrictionX:function(t){return this.friction.x=t,this},setFrictionY:function(t){return this.friction.y=t,this},setAngularVelocity:function(t){return this.angularVelocity=t,this},setAngularAcceleration:function(t){return this.angularAcceleration=t,this},setAngularDrag:function(t){return this.angularDrag=t,this},setMass:function(t){return this.mass=t,this},setImmovable:function(t){return void 0===t&&(t=!0),this.immovable=t,this},setEnable:function(t){return void 0===t&&(t=!0),this.enable=t,this},x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=u},function(t,e,i){var n=new(i(0))({initialize:function(t,e,i,n,s,r,o){this.world=t,this.name="",this.active=!0,this.overlapOnly=e,this.object1=i,this.object2=n,this.collideCallback=s,this.processCallback=r,this.callbackContext=o},setName:function(t){return this.name=t,this},update:function(){this.world.collideObjects(this.object1,this.object2,this.collideCallback,this.processCallback,this.callbackContext,this.overlapOnly)},destroy:function(){this.world.removeCollider(this),this.active=!1,this.world=null,this.object1=null,this.object2=null,this.collideCallback=null,this.processCallback=null,this.callbackContext=null}});t.exports=n},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsX()+e.deltaAbsX()+s;return 0===t._dx&&0===e._dx?(t.embedded=!0,e.embedded=!0):t._dx>e._dx?(r=t.right-e.x)>o&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?r=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.right=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.left=!0)):t._dxo&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?r=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.left=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.right=!0))),t.overlapX=r,e.overlapX=r,r}},function(t,e,i){var n=i(50);t.exports=function(t,e,i,s){var r=0,o=t.deltaAbsY()+e.deltaAbsY()+s;return 0===t._dy&&0===e._dy?(t.embedded=!0,e.embedded=!0):t._dy>e._dy?(r=t.bottom-e.y)>o&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?r=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.down=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.up=!0)):t._dyo&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?r=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0,e.physicsType===n.STATIC_BODY&&(t.blocked.none=!1,t.blocked.up=!0),t.physicsType===n.STATIC_BODY&&(e.blocked.none=!1,e.blocked.down=!0))),t.overlapY=r,e.overlapY=r,r}},function(t,e,i){var n=i(383);function s(t){if(!(this instanceof s))return new s(t,[".left",".top",".right",".bottom"]);this._maxEntries=Math.max(4,t||9),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}function r(t,e,i){if(!i)return e.indexOf(t);for(var n=0;n=t.minX&&e.maxY>=t.minY}function g(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function v(t,e,i,s,r){for(var o,a=[e,i];a.length;)(i=a.pop())-(e=a.pop())<=s||(o=e+Math.ceil((i-e)/s/2)*s,n(t,o,e,i,r),a.push(e,o,o,i))}s.prototype={all:function(){return this._all(this.data,[])},search:function(t){var e=this.data,i=[],n=this.toBBox;if(!p(t,e))return i;for(var s,r,o,a,h=[];e;){for(s=0,r=e.children.length;s=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)},_split:function(t,e){var i=t[e],n=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,n);var r=this._chooseSplitIndex(i,s,n),a=g(i.children.splice(r,i.children.length-r));a.height=i.height,a.leaf=i.leaf,o(i,this.toBBox),o(a,this.toBBox),e?t[e-1].children.push(a):this._splitRoot(i,a)},_splitRoot:function(t,e){this.data=g([t,e]),this.data.height=t.height+1,this.data.leaf=!1,o(this.data,this.toBBox)},_chooseSplitIndex:function(t,e,i){var n,s,r,o,h,l,u,d,f,p,g,v,m,y;for(l=u=1/0,n=e;n<=i-e;n++)s=a(t,0,n,this.toBBox),r=a(t,n,i,this.toBBox),f=s,p=r,void 0,void 0,void 0,void 0,g=Math.max(f.minX,p.minX),v=Math.max(f.minY,p.minY),m=Math.min(f.maxX,p.maxX),y=Math.min(f.maxY,p.maxY),o=Math.max(0,m-g)*Math.max(0,y-v),h=c(s)+c(r),o=e;s--)r=t.children[s],h(u,t.leaf?o(r):r),c+=d(u);return c},_adjustParentBBoxes:function(t,e,i){for(var n=i;n>=0;n--)h(e[n],t)},_condense:function(t){for(var e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children).splice(e.indexOf(t[i]),1):this.clear():o(t[i],this.toBBox)},compareMinX:function(t,e){return t.left-e.left},compareMinY:function(t,e){return t.top-e.top},toBBox:function(t){return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}},t.exports=s},function(t,e){t.exports=function(t,e){return!(e.right<=t.left||e.bottom<=t.top||e.position.x>=t.right||e.position.y>=t.bottom)}},function(t,e,i){var n=i(55),s=i(0),r=i(50),o=i(47),a=i(3),h=new s({initialize:function(t,e){var i=e.width?e.width:64,n=e.height?e.height:64;this.world=t,this.gameObject=e,this.debugShowBody=t.defaults.debugShowStaticBody,this.debugBodyColor=t.defaults.staticBodyDebugColor,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new a,this.position=new a(e.x-e.displayOriginX,e.y-e.displayOriginY),this.width=i,this.height=n,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center=new a(e.x+this.halfWidth,e.y+this.halfHeight),this.velocity=a.ZERO,this.allowGravity=!1,this.gravity=a.ZERO,this.bounce=a.ZERO,this.onWorldBounds=!1,this.onCollide=!1,this.onOverlap=!1,this.mass=1,this.immovable=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.physicsType=r.STATIC_BODY,this._dx=0,this._dy=0},setGameObject:function(t,e){return t&&t!==this.gameObject&&(this.gameObject.body=null,t.body=this,this.gameObject=t),e&&this.updateFromGameObject(),this},updateFromGameObject:function(){this.world.staticTree.remove(this);var t=this.gameObject;return t.getTopLeft(this.position),this.width=t.displayWidth,this.height=t.displayHeight,this.halfWidth=Math.abs(this.width/2),this.halfHeight=Math.abs(this.height/2),this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.world.staticTree.insert(this),this},setOffset:function(t,e){return void 0===e&&(e=t),this.world.staticTree.remove(this),this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(t,e),this.position.x+=this.offset.x,this.position.y+=this.offset.y,this.updateCenter(),this.world.staticTree.insert(this),this},setSize:function(t,e,i){void 0===i&&(i=!0);var n=this.gameObject;if(!t&&n.frame&&(t=n.frame.realWidth),!e&&n.frame&&(e=n.frame.realHeight),this.world.staticTree.remove(this),this.width=t,this.height=e,this.halfWidth=Math.floor(t/2),this.halfHeight=Math.floor(e/2),i&&n.getCenter){var s=n.displayWidth/2,r=n.displayHeight/2;this.position.x-=this.offset.x,this.position.y-=this.offset.y,this.offset.set(s-this.halfWidth,r-this.halfHeight),this.position.x+=this.offset.x,this.position.y+=this.offset.y}return this.updateCenter(),this.isCircle=!1,this.radius=0,this.world.staticTree.insert(this),this},setCircle:function(t,e,i){return void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.world.staticTree.remove(this),this.isCircle=!0,this.radius=t,this.width=2*t,this.height=2*t,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.set(e,i),this.updateCenter(),this.world.staticTree.insert(this)):this.isCircle=!1,this},updateCenter:function(){this.center.set(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(t,e){var i=this.gameObject;void 0===t&&(t=i.x),void 0===e&&(e=i.y),this.world.staticTree.remove(this),i.setPosition(t,e),i.getTopLeft(this.position),this.updateCenter(),this.world.staticTree.insert(this)},stop:function(){return this},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?n(this,t,e):o(this,t,e)},postUpdate:function(){},deltaAbsX:function(){return 0},deltaAbsY:function(){return 0},deltaX:function(){return 0},deltaY:function(){return 0},deltaZ:function(){return 0},destroy:function(){this.enable=!1,this.world.pendingDestroy.set(this)},drawDebug:function(t){var e=this.position,i=e.x+this.halfWidth,n=e.y+this.halfHeight;this.debugShowBody&&(t.lineStyle(t.defaultStrokeWidth,this.debugBodyColor,1),this.isCircle?t.strokeCircle(i,n,this.width/2):t.strokeRect(e.x,e.y,this.width,this.height))},willDrawDebug:function(){return this.debugShowBody},setMass:function(t){return t<=0&&(t=.1),this.mass=t,this},x:{get:function(){return this.position.x},set:function(t){this.world.staticTree.remove(this),this.position.x=t,this.world.staticTree.insert(this)}},y:{get:function(){return this.position.y},set:function(t){this.world.staticTree.remove(this),this.position.y=t,this.world.staticTree.insert(this)}},left:{get:function(){return this.position.x}},right:{get:function(){return this.position.x+this.width}},top:{get:function(){return this.position.y}},bottom:{get:function(){return this.position.y+this.height}}});t.exports=h},function(t,e){t.exports={NEVER:0,LITE:1,PASSIVE:2,ACTIVE:4,FIXED:8}},function(t,e){t.exports={NONE:0,A:1,B:2,BOTH:3}},function(t,e){var i={};t.exports=i,i.create=function(t,e){var n=t.bodyA,s=t.bodyB,r={id:i.id(n,s),bodyA:n,bodyB:s,activeContacts:[],separation:0,isActive:!0,confirmedActive:!0,isSensor:n.isSensor||s.isSensor,timeCreated:e,timeUpdated:e,collision:null,inverseMass:0,friction:0,frictionStatic:0,restitution:0,slop:0};return i.update(r,t,e),r},i.update=function(t,e,n){if(t.collision=e,e.collided){var s=e.supports,r=t.activeContacts,o=e.parentA,a=e.parentB;t.inverseMass=o.inverseMass+a.inverseMass,t.friction=Math.min(o.friction,a.friction),t.frictionStatic=Math.max(o.frictionStatic,a.frictionStatic),t.restitution=Math.max(o.restitution,a.restitution),t.slop=Math.max(o.slop,a.slop);for(var h=0;h-1}return!1}},function(t,e,i){var n=i(74),s=i(103),r=i(217);t.exports=function(t,e,i,o,a){if(void 0===i&&(i=!1),void 0===o&&(o=!0),!s(t,e,a))return null;var h=a.data[e][t];return h?(a.data[e][t]=i?null:new n(a,-1,t,e,h.width,h.height),o&&h&&h.collides&&r(t,e,a),h):null}},function(t,e,i){var n=i(31),s=i(220),r=i(473),o=i(474),a=i(485);t.exports=function(t,e,i,h,l,u){var c;switch(e){case n.ARRAY_2D:c=s(t,i,h,l,u);break;case n.CSV:c=r(t,i,h,l,u);break;case n.TILED_JSON:c=o(t,i,u);break;case n.WELTMEISTER:c=a(t,i,u);break;default:console.warn("Unrecognized tilemap data format: "+e),c=null}return c}},function(t,e,i){var n=i(31),s=i(220);t.exports=function(t,e,i,r,o){var a=e.trim().split("\n").map(function(t){return t.split(",")}),h=s(t,a,i,r,o);return h.format=n.CSV,h}},function(t,e,i){var n=i(31),s=i(105),r=i(475),o=i(477),a=i(478),h=i(481),l=i(483),u=i(484);t.exports=function(t,e,i){if("orthogonal"!==e.orientation)return console.warn("Only orthogonal map types are supported in this version of Phaser"),null;var c=new s({width:e.width,height:e.height,name:t,tileWidth:e.tilewidth,tileHeight:e.tileheight,orientation:e.orientation,format:n.TILED_JSON,version:e.version,properties:e.properties,renderOrder:e.renderorder,infinite:e.infinite});c.layers=r(e,i),c.images=o(e);var d=a(e);return c.tilesets=d.tilesets,c.imageCollections=d.imageCollections,c.objects=h(e),c.tiles=l(c),u(c),c}},function(t,e,i){var n=i(476),s=i(2),r=i(104),o=i(221),a=i(74),h=i(222);t.exports=function(t,e){for(var i=s(t,"infinite",!1),l=[],u=[],c=h(t);c.i0;)if(c.i>=c.layers.length){if(u.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}c=u.pop()}else{var d=c.layers[c.i];if(c.i++,"tilelayer"===d.type)if(d.compression)console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+d.name+"'");else{if(d.encoding&&"base64"===d.encoding){if(d.chunks)for(var f=0;f0?((v=new a(p,g.gid,P,R,t.tilewidth,t.tileheight)).rotation=g.rotation,v.flipX=g.flipped,y[R][P]=v):(m=e?null:new a(p,-1,P,R,t.tilewidth,t.tileheight),y[R][P]=m),++x===S.width&&(C++,x=0)}}else{p=new r({name:c.name+d.name,x:c.x+s(d,"offsetx",0)+d.x,y:c.y+s(d,"offsety",0)+d.y,width:d.width,height:d.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,alpha:c.opacity*d.opacity,visible:c.visible&&d.visible,properties:s(d,"properties",{})});for(var L=[],k=0,D=d.data.length;k0?((v=new a(p,g.gid,x,y.length,t.tilewidth,t.tileheight)).rotation=g.rotation,v.flipX=g.flipped,L.push(v)):(m=e?null:new a(p,-1,x,y.length,t.tilewidth,t.tileheight),L.push(m)),++x===d.width&&(y.push(L),x=0,L=[])}p.data=y,l.push(p)}else if("group"===d.type){var F=h(t,d,c);u.push(c),c=F}}return l}},function(t,e){t.exports=function(t){for(var e=window.atob(t),i=e.length,n=new Array(i/4),s=0;s>>0;return n}},function(t,e,i){var n=i(2),s=i(222);t.exports=function(t){for(var e=[],i=[],r=s(t);r.i0;)if(r.i>=r.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}r=i.pop()}else{var o=r.layers[r.i];if(r.i++,"imagelayer"===o.type){var a=n(o,"offsetx",0)+n(o,"startx",0),h=n(o,"offsety",0)+n(o,"starty",0);e.push({name:r.name+o.name,image:o.image,x:r.x+a+o.x,y:r.y+h+o.y,alpha:r.opacity*o.opacity,visible:r.visible&&o.visible,properties:n(o,"properties",{})})}else if("group"===o.type){var l=s(t,o,r);i.push(r),r=l}}return e}},function(t,e,i){var n=i(141),s=i(479),r=i(223);t.exports=function(t){for(var e,i=[],o=[],a=null,h=0;h1){if(Array.isArray(l.tiles)){for(var c={},d={},f=0;f=this.firstgid&&t0;)if(a.i>=a.layers.length){if(i.length<1){console.warn("TilemapParser.parseTiledJSON - Invalid layer group hierarchy");break}a=i.pop()}else{var h=a.layers[a.i];if(a.i++,h.opacity*=a.opacity,h.visible=a.visible&&h.visible,"objectgroup"===h.type){h.name=a.name+h.name;for(var l=a.x+n(h,"startx",0)+n(h,"offsetx",0),u=a.y+n(h,"starty",0)+n(h,"offsety",0),c=[],d=0;da&&(a=e.layer[l].width),e.layer[l].height>h&&(h=e.layer[l].height);var u=new s({width:a,height:h,name:t,tileWidth:e.layer[0].tilesize,tileHeight:e.layer[0].tilesize,format:n.WELTMEISTER});return u.layers=r(e,i),u.tilesets=o(e),u}},function(t,e,i){var n=i(104),s=i(74);t.exports=function(t,e){for(var i=[],r=0;r-1?new s(a,f,c,u,o.tilesize,o.tilesize):e?null:new s(a,-1,c,u,o.tilesize,o.tilesize),h.push(d)}l.push(h),h=[]}a.data=l,i.push(a)}return i}},function(t,e,i){var n=i(141);t.exports=function(t){for(var e=[],i=[],s=0;s-1&&(this.renderOrder=t),this},addTilesetImage:function(t,e,i,n,s,r,o){if(void 0===t)return null;if(void 0!==e&&null!==e||(e=t),!this.scene.sys.textures.exists(e))return console.warn("Invalid Tileset Image: "+e),null;var h=this.scene.sys.textures.get(e),l=this.getTilesetIndex(t);if(null===l&&this.format===a.TILED_JSON)return console.warn("No data found for Tileset: "+t),null;var u=this.tilesets[l];return u?(u.setTileSize(i,n),u.setSpacing(s,r),u.setImage(h),u):(void 0===i&&(i=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===s&&(s=0),void 0===r&&(r=0),void 0===o&&(o=0),(u=new p(t,o,i,n,s,r)).setImage(h),this.tilesets.push(u),u)},convertLayerToStatic:function(t){if(null===(t=this.getLayer(t)))return null;var e=t.tilemapLayer;if(!(e&&e instanceof r))return null;var i=new c(e.scene,e.tilemap,e.layerIndex,e.tileset,e.x,e.y);return this.scene.sys.displayList.add(i),e.destroy(),i},copy:function(t,e,i,n,s,r,o,a){return a=this.getLayer(a),this._isStaticCall(a,"copy")?this:null!==a?(f.Copy(t,e,i,n,s,r,o,a),this):null},createBlankDynamicLayer:function(t,e,i,n,s,o,a,l){if(void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=this.width),void 0===o&&(o=this.height),void 0===a&&(a=this.tileWidth),void 0===l&&(l=this.tileHeight),null!==this.getLayerIndex(t))return console.warn("Invalid Tilemap Layer ID: "+t),null;for(var u,c=new h({name:t,tileWidth:a,tileHeight:l,width:s,height:o}),f=0;f-1&&this.putTileAt(e,r.x,r.y,i,r.tilemapLayer)}return n},removeTileAt:function(t,e,i,n,s){return s=this.getLayer(s),this._isStaticCall(s,"removeTileAt")?null:null===s?null:f.RemoveTileAt(t,e,i,n,s)},removeTileAtWorldXY:function(t,e,i,n,s,r){return r=this.getLayer(r),this._isStaticCall(r,"removeTileAtWorldXY")?null:null===r?null:f.RemoveTileAtWorldXY(t,e,i,n,s,r)},renderDebug:function(t,e,i){return null===(i=this.getLayer(i))?null:(f.RenderDebug(t,e,i),this)},renderDebugFull:function(t,e){for(var i=this.layers,n=0;n=0&&t<4&&(this._renderOrder=t),this},calculateFacesAt:function(t,e){return a.CalculateFacesAt(t,e,this.layer),this},calculateFacesWithin:function(t,e,i,n){return a.CalculateFacesWithin(t,e,i,n,this.layer),this},createFromTiles:function(t,e,i,n,s){return a.CreateFromTiles(t,e,i,n,s,this.layer)},cull:function(t){return this.cullCallback(this.layer,t,this.culledTiles,this._renderOrder)},copy:function(t,e,i,n,s,r,o){return a.Copy(t,e,i,n,s,r,o,this.layer),this},destroy:function(t){void 0===t&&(t=!0),this.tilemap&&(this.layer.tilemapLayer===this&&(this.layer.tilemapLayer=void 0),t&&this.tilemap.removeLayer(this),this.tilemap=void 0,this.layer=void 0,this.culledTiles.length=0,this.cullCallback=null,this.gidMap=[],this.tileset=[],o.prototype.destroy.call(this))},fill:function(t,e,i,n,s,r){return a.Fill(t,e,i,n,s,r,this.layer),this},filterTiles:function(t,e,i,n,s,r,o){return a.FilterTiles(t,e,i,n,s,r,o,this.layer)},findByIndex:function(t,e,i){return a.FindByIndex(t,e,i,this.layer)},findTile:function(t,e,i,n,s,r,o){return a.FindTile(t,e,i,n,s,r,o,this.layer)},forEachTile:function(t,e,i,n,s,r,o){return a.ForEachTile(t,e,i,n,s,r,o,this.layer),this},getTileAt:function(t,e,i){return a.GetTileAt(t,e,i,this.layer)},getTileAtWorldXY:function(t,e,i,n){return a.GetTileAtWorldXY(t,e,i,n,this.layer)},getTilesWithin:function(t,e,i,n,s){return a.GetTilesWithin(t,e,i,n,s,this.layer)},getTilesWithinShape:function(t,e,i){return a.GetTilesWithinShape(t,e,i,this.layer)},getTilesWithinWorldXY:function(t,e,i,n,s,r){return a.GetTilesWithinWorldXY(t,e,i,n,s,r,this.layer)},hasTileAt:function(t,e){return a.HasTileAt(t,e,this.layer)},hasTileAtWorldXY:function(t,e,i){return a.HasTileAtWorldXY(t,e,i,this.layer)},putTileAt:function(t,e,i,n){return a.PutTileAt(t,e,i,n,this.layer)},putTileAtWorldXY:function(t,e,i,n,s){return a.PutTileAtWorldXY(t,e,i,n,s,this.layer)},putTilesAt:function(t,e,i,n){return a.PutTilesAt(t,e,i,n,this.layer),this},randomize:function(t,e,i,n,s){return a.Randomize(t,e,i,n,s,this.layer),this},removeTileAt:function(t,e,i,n){return a.RemoveTileAt(t,e,i,n,this.layer)},removeTileAtWorldXY:function(t,e,i,n,s){return a.RemoveTileAtWorldXY(t,e,i,n,s,this.layer)},renderDebug:function(t,e){return a.RenderDebug(t,e,this.layer),this},replaceByIndex:function(t,e,i,n,s,r){return a.ReplaceByIndex(t,e,i,n,s,r,this.layer),this},setSkipCull:function(t){return void 0===t&&(t=!0),this.skipCull=t,this},setCullPadding:function(t,e){return void 0===t&&(t=1),void 0===e&&(e=1),this.cullPaddingX=t,this.cullPaddingY=e,this},setCollision:function(t,e,i,n){return a.SetCollision(t,e,i,this.layer,n),this},setCollisionBetween:function(t,e,i,n){return a.SetCollisionBetween(t,e,i,n,this.layer),this},setCollisionByProperty:function(t,e,i){return a.SetCollisionByProperty(t,e,i,this.layer),this},setCollisionByExclusion:function(t,e,i){return a.SetCollisionByExclusion(t,e,i,this.layer),this},setCollisionFromCollisionGroup:function(t,e){return a.SetCollisionFromCollisionGroup(t,e,this.layer),this},setTileIndexCallback:function(t,e,i){return a.SetTileIndexCallback(t,e,i,this.layer),this},setTileLocationCallback:function(t,e,i,n,s,r){return a.SetTileLocationCallback(t,e,i,n,s,r,this.layer),this},shuffle:function(t,e,i,n){return a.Shuffle(t,e,i,n,this.layer),this},swapByIndex:function(t,e,i,n,s,r){return a.SwapByIndex(t,e,i,n,s,r,this.layer),this},tileToWorldX:function(t,e){return a.TileToWorldX(t,e,this.layer)},tileToWorldY:function(t,e){return a.TileToWorldY(t,e,this.layer)},tileToWorldXY:function(t,e,i,n){return a.TileToWorldXY(t,e,i,n,this.layer)},weightedRandomize:function(t,e,i,n,s){return a.WeightedRandomize(t,e,i,n,s,this.layer),this},worldToTileX:function(t,e,i){return a.WorldToTileX(t,e,i,this.layer)},worldToTileY:function(t,e,i){return a.WorldToTileY(t,e,i,this.layer)},worldToTileXY:function(t,e,i,n,s){return a.WorldToTileXY(t,e,i,n,s,this.layer)}});t.exports=h},function(t,e,i){var n=i(0),s=i(12),r=i(18),o=i(14),a=i(1336),h=i(137),l=i(32),u=i(10),c=new n({Extends:o,Mixins:[s.Alpha,s.BlendMode,s.ComputedSize,s.Depth,s.Flip,s.GetBounds,s.Origin,s.Pipeline,s.Transform,s.Visible,s.ScrollFactor,a],initialize:function(t,e,i,n,s,a){o.call(this,t,"StaticTilemapLayer"),this.isTilemap=!0,this.tilemap=e,this.layerIndex=i,this.layer=e.layers[i],this.layer.tilemapLayer=this,this.tileset=[],this.culledTiles=[],this.skipCull=!1,this.tilesDrawn=0,this.tilesTotal=this.layer.width*this.layer.height,this.cullPaddingX=1,this.cullPaddingY=1,this.cullCallback=h.CullTiles,this.renderer=t.sys.game.renderer,this.vertexBuffer=[],this.bufferData=[],this.vertexViewF32=[],this.vertexViewU32=[],this.dirty=[],this.vertexCount=[],this._renderOrder=0,this._tempMatrix=new l,this.gidMap=[],this.setTilesets(n),this.setAlpha(this.layer.alpha),this.setPosition(s,a),this.setOrigin(),this.setSize(e.tileWidth*this.layer.width,e.tileHeight*this.layer.height),this.updateVBOData(),this.initPipeline("TextureTintPipeline"),t.sys.game.events.on(r.CONTEXT_RESTORED,function(){this.updateVBOData()},this)},setTilesets:function(t){var e=[],i=[],n=this.tilemap;Array.isArray(t)||(t=[t]);for(var s=0;sv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(1===p)for(o=0;o=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(2===p)for(o=u-1;o>=0;o--)for(a=0;av||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));else if(3===p)for(o=u-1;o>=0;o--)for(a=l-1;a>=0;a--)!(r=f[o][a])||r.indexv||!r.visible||(x=this.batchTile(x,r,h,c,d,t,e));this.dirty[e]=!1,null===m?(m=i.createVertexBuffer(y,n.STATIC_DRAW),this.vertexBuffer[e]=m):(i.setVertexBuffer(m),n.bufferSubData(n.ARRAY_BUFFER,0,y))}return this},batchTile:function(t,e,i,n,s,r,o){var a=i.getTileTextureCoordinates(e.index);if(!a)return t;var h=i.tileWidth,l=i.tileHeight,c=h/2,d=l/2,f=a.x/n,p=a.y/s,g=(a.x+h)/n,v=(a.y+l)/s,m=this._tempMatrix,y=-c,x=-d;e.flipX&&(h*=-1,y+=i.tileWidth),e.flipY&&(l*=-1,x+=i.tileHeight);var T=y+h,w=x+l;m.applyITRS(c+e.pixelX,d+e.pixelY,e.rotation,1,1);var b=u.getTintAppendFloatAlpha(16777215,r.alpha*this.alpha*e.alpha),E=m.getX(y,x),S=m.getY(y,x),A=m.getX(y,w),_=m.getY(y,w),C=m.getX(T,w),M=m.getY(T,w),O=m.getX(T,x),P=m.getY(T,x);r.roundPixels&&(E=Math.round(E),S=Math.round(S),A=Math.round(A),_=Math.round(_),C=Math.round(C),M=Math.round(M),O=Math.round(O),P=Math.round(P));var R=this.vertexViewF32[o],L=this.vertexViewU32[o];return R[++t]=E,R[++t]=S,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=b,R[++t]=A,R[++t]=_,R[++t]=f,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=E,R[++t]=S,R[++t]=f,R[++t]=p,R[++t]=0,L[++t]=b,R[++t]=C,R[++t]=M,R[++t]=g,R[++t]=v,R[++t]=0,L[++t]=b,R[++t]=O,R[++t]=P,R[++t]=g,R[++t]=p,R[++t]=0,L[++t]=b,this.vertexCount[o]+=6,t},setRenderOrder:function(t){if("string"==typeof t&&(t=["right-down","left-down","right-up","left-up"].indexOf(t)),t>=0&&t<4){this._renderOrder=t;for(var e=0;e0){var t=this.delay+this.delay*this.repeat;return(this.elapsed+this.delay*(this.repeat-this.repeatCount))/t}return this.getProgress()},getRepeatCount:function(){return this.repeatCount},getElapsed:function(){return this.elapsed},getElapsedSeconds:function(){return.001*this.elapsed},remove:function(t){void 0===t&&(t=!1),this.elapsed=this.delay,this.hasDispatched=!t,this.repeatCount=0},destroy:function(){this.callback=void 0,this.callbackScope=void 0,this.args=[]}});t.exports=r},function(t,e,i){var n=i(1345);t.exports=function(t){var e,i=[];if(t.hasOwnProperty("props"))for(e in t.props)"_"!==e.substr(0,1)&&i.push({key:e,value:t.props[e]});else for(e in t)-1===n.indexOf(e)&&"_"!==e.substr(0,1)&&i.push({key:e,value:t[e]});return i}},function(t,e,i){var n=i(6);t.exports=function(t){var e=n(t,"tweens",null);return null===e?[]:("function"==typeof e&&(e=e.call()),Array.isArray(e)||(e=[e]),e)}},function(t,e,i){var n=i(227),s=i(15),r=i(88),o=i(82),a=i(142),h=i(6),l=i(226),u=i(228),c=i(230);t.exports=function(t,e,i){void 0===i&&(i=n);var d=h(e,"from",0),f=h(e,"to",1),p=[{value:d}],g=a(e,"delay",i.delay),v=a(e,"duration",i.duration),m=h(e,"easeParams",i.easeParams),y=o(h(e,"ease",i.ease),m),x=a(e,"hold",i.hold),T=a(e,"repeat",i.repeat),w=a(e,"repeatDelay",i.repeatDelay),b=r(e,"yoyo",i.yoyo),E=[],S=l("value",f),A=c(p[0],0,"value",S.getEnd,S.getStart,S.getActive,y,g,v,b,x,T,w,!1,!1);A.start=d,A.current=d,A.to=f,E.push(A);var _=new u(t,E,p);_.offset=s(e,"offset",null),_.completeDelay=s(e,"completeDelay",0),_.loop=Math.round(s(e,"loop",0)),_.loopDelay=Math.round(s(e,"loopDelay",0)),_.paused=r(e,"paused",!1),_.useFrames=r(e,"useFrames",!1);for(var C=h(e,"callbackScope",_),M=[_,null],O=u.TYPES,P=0;PS&&(S=C),E[A][_]=C}}}var M=o?n(o):null;return a?function(t,e,n,s){var r,o=0,a=s%m,h=Math.floor(s/m);if(a>=0&&a=0&&h0?Math.floor(v/p.length):h(e,"duration",g.duration),g.delay=h(e,"delay",g.delay),g.easeParams=c(e,"easeParams",g.easeParams),g.ease=a(c(e,"ease",g.ease),g.easeParams),g.hold=h(e,"hold",g.hold),g.repeat=h(e,"repeat",g.repeat),g.repeatDelay=h(e,"repeatDelay",g.repeatDelay),g.yoyo=o(e,"yoyo",g.yoyo),g.flipX=o(e,"flipX",g.flipX),g.flipY=o(e,"flipY",g.flipY);for(var m=0;m0?this.totalDuration=this.duration+this.completeDelay+(this.duration+this.loopDelay)*this.loopCounter:this.totalDuration=this.duration+this.completeDelay},init:function(){return this.calcDuration(),this.progress=0,this.totalProgress=0,!this.paused||(this.state=a.PAUSED,!1)},resetTweens:function(t){for(var e=0;e0?(this.elapsed=0,this.progress=0,this.loopCounter--,this.resetTweens(!0),this.loopDelay>0?(this.countdown=this.loopDelay,this.state=a.LOOP_DELAY):(this.state=a.ACTIVE,this.dispatchTimelineEvent(r.TIMELINE_LOOP,this.callbacks.onLoop))):this.completeDelay>0?(this.state=a.COMPLETE_DELAY,this.countdown=this.completeDelay):(this.state=a.PENDING_REMOVE,this.dispatchTimelineEvent(r.TIMELINE_COMPLETE,this.callbacks.onComplete))},update:function(t,e){if(this.state!==a.PAUSED){switch(this.useFrames&&(e=1*this.manager.timeScale),e*=this.timeScale,this.elapsed+=e,this.progress=Math.min(this.elapsed/this.duration,1),this.totalElapsed+=e,this.totalProgress=Math.min(this.totalElapsed/this.totalDuration,1),this.state){case a.ACTIVE:for(var i=this.totalData,n=0;n=this.nextTick&&this.currentAnim.setFrame(this)}},setCurrentFrame:function(t){var e=this.parent;return this.currentFrame=t,e.texture=t.frame.texture,e.frame=t.frame,e.isCropped&&e.frame.updateCropUVs(e._crop,e.flipX,e.flipY),e.setSizeToFrame(),t.frame.customPivot?e.setOrigin(t.frame.pivotX,t.frame.pivotY):e.updateDisplayOrigin(),e},updateFrame:function(t){var e=this.setCurrentFrame(t);if(this.isPlaying){t.setAlpha&&(e.alpha=t.alpha);var i=this.currentAnim;e.emit(r.SPRITE_ANIMATION_KEY_UPDATE+i.key,i,t,e),e.emit(r.SPRITE_ANIMATION_UPDATE,i,t,e),3===this._pendingStop&&this._pendingStopValue===t&&this.currentAnim.completeAnimation(this)}},nextFrame:function(){return this.currentAnim&&this.currentAnim.nextFrame(this),this.parent},previousFrame:function(){return this.currentAnim&&this.currentAnim.previousFrame(this),this.parent},setYoyo:function(t){return void 0===t&&(t=!1),this._yoyo=t,this.parent},getYoyo:function(){return this._yoyo},destroy:function(){this.animationManager.off(r.REMOVE_ANIMATION,this.remove,this),this.animationManager=null,this.parent=null,this.currentAnim=null,this.currentFrame=null}});t.exports=o},function(t,e,i){var n=i(500),s=i(48),r=i(0),o=i(29),a=i(501),h=i(92),l=i(32),u=new r({initialize:function(t){this.game=t,this.type=o.CANVAS,this.drawCount=0,this.width=0,this.height=0,this.config={clearBeforeRender:t.config.clearBeforeRender,backgroundColor:t.config.backgroundColor,resolution:t.config.resolution,antialias:t.config.antialias,roundPixels:t.config.roundPixels},this.gameCanvas=t.canvas;var e={alpha:t.config.transparent,desynchronized:t.config.desynchronized};this.gameContext=this.game.config.context?this.game.config.context:this.gameCanvas.getContext("2d",e),this.currentContext=this.gameContext,this.antialias=t.config.antialias,this.blendModes=a(),this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92},this._tempMatrix1=new l,this._tempMatrix2=new l,this._tempMatrix3=new l,this._tempMatrix4=new l,this.init()},init:function(){this.game.scale.on(h.RESIZE,this.onResize,this);var t=this.game.scale.baseSize;this.resize(t.width,t.height)},onResize:function(t,e){e.width===this.width&&e.height===this.height||this.resize(e.width,e.height)},resize:function(t,e){this.width=t,this.height=e},resetTransform:function(){this.currentContext.setTransform(1,0,0,1,0,0)},setBlendMode:function(t){return this.currentContext.globalCompositeOperation=t,this},setContext:function(t){return this.currentContext=t||this.gameContext,this},setAlpha:function(t){return this.currentContext.globalAlpha=t,this},preRender:function(){var t=this.gameContext,e=this.config,i=this.width,n=this.height;t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),e.clearBeforeRender&&t.clearRect(0,0,i,n),e.transparent||(t.fillStyle=e.backgroundColor.rgba,t.fillRect(0,0,i,n)),t.save(),this.drawCount=0},render:function(t,e,i,n){var r=e.list,o=r.length,a=n._cx,h=n._cy,l=n._cw,u=n._ch,c=n.renderToTexture?n.context:t.sys.context;c.save(),this.game.scene.customViewports&&(c.beginPath(),c.rect(a,h,l,u),c.clip()),this.currentContext=c;var d=n.mask;d&&d.preRenderCanvas(this,null,n._maskCamera),n.transparent||(c.fillStyle=n.backgroundColor.rgba,c.fillRect(a,h,l,u)),c.globalAlpha=n.alpha,c.globalCompositeOperation="source-over",this.drawCount+=r.length,n.renderToTexture&&n.emit(s.PRE_RENDER,n),n.matrix.copyToContext(c);for(var f=0;f=0?y=-(y+d):y<0&&(y=Math.abs(y)-d)),t.flipY&&(x>=0?x=-(x+f):x<0&&(x=Math.abs(x)-f))}var w=1,b=1;t.flipX&&(p||(y+=-e.realWidth+2*v),w=-1),t.flipY&&(p||(x+=-e.realHeight+2*m),b=-1),a.applyITRS(t.x,t.y,t.rotation,t.scaleX*w,t.scaleY*b),o.copyFrom(i.matrix),n?(o.multiplyWithOffset(n,-i.scrollX*t.scrollFactorX,-i.scrollY*t.scrollFactorY),a.e=t.x,a.f=t.y,o.multiply(a,h)):(a.e-=i.scrollX*t.scrollFactorX,a.f-=i.scrollY*t.scrollFactorY,o.multiply(a,h)),r.save(),h.setToContext(r),r.globalCompositeOperation=this.blendModes[t.blendMode],r.globalAlpha=s,r.imageSmoothingEnabled=!(!this.antialias||e.source.scaleMode),r.drawImage(e.source.image,u,c,d,f,y,x,d/g,f/g),r.restore()}},destroy:function(){this.gameCanvas=null,this.gameContext=null,this.game=null}});t.exports=u},function(t,e,i){var n=i(26),s=i(33),r=i(2);t.exports=function(t,e){var i=r(e,"callback"),o=r(e,"type","image/png"),a=r(e,"encoder",.92),h=Math.abs(Math.round(r(e,"x",0))),l=Math.abs(Math.round(r(e,"y",0))),u=r(e,"width",t.width),c=r(e,"height",t.height);if(r(e,"getPixel",!1)){var d=t.getContext("2d").getImageData(h,l,1,1).data;i.call(null,new s(d[0],d[1],d[2],d[3]/255))}else if(0!==h||0!==l||u!==t.width||c!==t.height){var f=n.createWebGL(this,u,c);f.getContext("2d").drawImage(t,h,l,u,c,0,0,u,c);var p=new Image;p.onerror=function(){i.call(null),n.remove(f)},p.onload=function(){i.call(null,p),n.remove(f)},p.src=f.toDataURL(o,a)}else{var g=new Image;g.onerror=function(){i.call(null)},g.onload=function(){i.call(null,g)},g.src=t.toDataURL(o,a)}}},function(t,e,i){var n=i(52),s=i(313);t.exports=function(){var t=[],e=s.supportNewBlendModes,i="source-over";return t[n.NORMAL]=i,t[n.ADD]="lighter",t[n.MULTIPLY]=e?"multiply":i,t[n.SCREEN]=e?"screen":i,t[n.OVERLAY]=e?"overlay":i,t[n.DARKEN]=e?"darken":i,t[n.LIGHTEN]=e?"lighten":i,t[n.COLOR_DODGE]=e?"color-dodge":i,t[n.COLOR_BURN]=e?"color-burn":i,t[n.HARD_LIGHT]=e?"hard-light":i,t[n.SOFT_LIGHT]=e?"soft-light":i,t[n.DIFFERENCE]=e?"difference":i,t[n.EXCLUSION]=e?"exclusion":i,t[n.HUE]=e?"hue":i,t[n.SATURATION]=e?"saturation":i,t[n.COLOR]=e?"color":i,t[n.LUMINOSITY]=e?"luminosity":i,t[n.ERASE]="destination-out",t[n.SOURCE_IN]="source-in",t[n.SOURCE_OUT]="source-out",t[n.SOURCE_ATOP]="source-atop",t[n.DESTINATION_OVER]="destination-over",t[n.DESTINATION_IN]="destination-in",t[n.DESTINATION_OUT]="destination-out",t[n.DESTINATION_ATOP]="destination-atop",t[n.LIGHTER]="lighter",t[n.COPY]="copy",t[n.XOR]="xor",t}},function(t,e,i){var n=i(91),s=i(48),r=i(0),o=i(29),a=i(18),h=i(118),l=i(1),u=i(92),c=i(79),d=i(119),f=i(32),p=i(10),g=i(503),v=i(504),m=i(505),y=i(235),x=new r({initialize:function(t){var e=t.config,i={alpha:e.transparent,desynchronized:e.desynchronized,depth:!1,antialias:e.antialiasGL,premultipliedAlpha:e.premultipliedAlpha,stencil:!0,failIfMajorPerformanceCaveat:e.failIfMajorPerformanceCaveat,powerPreference:e.powerPreference};this.config={clearBeforeRender:e.clearBeforeRender,antialias:e.antialias,backgroundColor:e.backgroundColor,contextCreation:i,resolution:e.resolution,roundPixels:e.roundPixels,maxTextures:e.maxTextures,maxTextureSize:e.maxTextureSize,batchSize:e.batchSize,maxLights:e.maxLights,mipmapFilter:e.mipmapFilter},this.game=t,this.type=o.WEBGL,this.width=0,this.height=0,this.canvas=t.canvas,this.blendModes=[],this.nativeTextures=[],this.contextLost=!1,this.pipelines=null,this.snapshotState={x:0,y:0,width:1,height:1,getPixel:!1,callback:null,type:"image/png",encoder:.92,isFramebuffer:!1,bufferWidth:0,bufferHeight:0},this.currentActiveTextureUnit=0,this.currentTextures=new Array(16),this.currentFramebuffer=null,this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.currentBlendMode=1/0,this.currentScissorEnabled=!1,this.currentScissor=null,this.scissorStack=[],this.contextLostHandler=l,this.contextRestoredHandler=l,this.gl=null,this.supportedExtensions=null,this.extensions={},this.glFormats=[],this.compression={ETC1:!1,PVRTC:!1,S3TC:!1},this.drawingBufferHeight=0,this.blankTexture=null,this.defaultCamera=new n(0,0,0,0),this._tempMatrix1=new f,this._tempMatrix2=new f,this._tempMatrix3=new f,this._tempMatrix4=new f,this.maskCount=0,this.maskStack=[],this.currentMask={mask:null,camera:null},this.currentCameraMask={mask:null,camera:null},this.glFuncMap=null,this.currentType="",this.newType=!1,this.nextTypeMatch=!1,this.mipmapFilter=null,this.init(this.config)},init:function(t){var e,i=this.game,n=this.canvas,s=t.backgroundColor;if(!(e=i.config.context?i.config.context:n.getContext("webgl",t.contextCreation)||n.getContext("experimental-webgl",t.contextCreation))||e.isContextLost())throw this.contextLost=!0,new Error("WebGL unsupported");this.gl=e;var r=this;this.contextLostHandler=function(t){r.contextLost=!0,r.game.events.emit(a.CONTEXT_LOST,r),t.preventDefault()},this.contextRestoredHandler=function(){r.contextLost=!1,r.init(r.config),r.game.events.emit(a.CONTEXT_RESTORED,r)},n.addEventListener("webglcontextlost",this.contextLostHandler,!1),n.addEventListener("webglcontextrestored",this.contextRestoredHandler,!1),i.context=e;for(var h=0;h<=27;h++)this.blendModes.push({func:[e.ONE,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_ADD});this.blendModes[1].func=[e.ONE,e.DST_ALPHA],this.blendModes[2].func=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA],this.blendModes[3].func=[e.ONE,e.ONE_MINUS_SRC_COLOR],this.blendModes[17]={func:[e.ZERO,e.ONE_MINUS_SRC_ALPHA],equation:e.FUNC_REVERSE_SUBTRACT},this.glFormats[0]=e.BYTE,this.glFormats[1]=e.SHORT,this.glFormats[2]=e.UNSIGNED_BYTE,this.glFormats[3]=e.UNSIGNED_SHORT,this.glFormats[4]=e.FLOAT,this.glFuncMap={mat2:{func:e.uniformMatrix2fv,length:1,matrix:!0},mat3:{func:e.uniformMatrix3fv,length:1,matrix:!0},mat4:{func:e.uniformMatrix4fv,length:1,matrix:!0},"1f":{func:e.uniform1f,length:1},"1fv":{func:e.uniform1fv,length:1},"1i":{func:e.uniform1i,length:1},"1iv":{func:e.uniform1iv,length:1},"2f":{func:e.uniform2f,length:2},"2fv":{func:e.uniform2fv,length:1},"2i":{func:e.uniform2i,length:2},"2iv":{func:e.uniform2iv,length:1},"3f":{func:e.uniform3f,length:3},"3fv":{func:e.uniform3fv,length:1},"3i":{func:e.uniform3i,length:3},"3iv":{func:e.uniform3iv,length:1},"4f":{func:e.uniform4f,length:4},"4fv":{func:e.uniform4fv,length:1},"4i":{func:e.uniform4i,length:4},"4iv":{func:e.uniform4iv,length:1}};var l=e.getSupportedExtensions();t.maxTextures||(t.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)),t.maxTextureSize||(t.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE));var u="WEBGL_compressed_texture_",c="WEBKIT_"+u;this.compression.ETC1=e.getExtension(u+"etc1")||e.getExtension(c+"etc1"),this.compression.PVRTC=e.getExtension(u+"pvrtc")||e.getExtension(c+"pvrtc"),this.compression.S3TC=e.getExtension(u+"s3tc")||e.getExtension(c+"s3tc"),this.supportedExtensions=l,e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.clearColor(s.redGL,s.greenGL,s.blueGL,s.alphaGL),this.mipmapFilter=e[t.mipmapFilter];for(var f=0;f0&&n>0;if(o&&a){var h=o[0],l=o[1],u=o[2],c=o[3];a=h!==t||l!==e||u!==i||c!==n}a&&(this.flush(),r.scissor(t,s-e-n,i,n))},popScissor:function(){var t=this.scissorStack;t.pop();var e=t[t.length-1];e&&this.setScissor(e[0],e[1],e[2],e[3]),this.currentScissor=e},setPipeline:function(t,e){return this.currentPipeline===t&&this.currentPipeline.vertexBuffer===this.currentVertexBuffer&&this.currentPipeline.program===this.currentProgram||(this.flush(),this.currentPipeline=t,this.currentPipeline.bind()),this.currentPipeline.onBind(e),this.currentPipeline},hasActiveStencilMask:function(){var t=this.currentMask.mask,e=this.currentCameraMask.mask;return t&&t.isStencil||e&&e.isStencil},rebindPipeline:function(t){var e=this.gl;e.disable(e.DEPTH_TEST),e.disable(e.CULL_FACE),this.hasActiveStencilMask()?e.clear(e.DEPTH_BUFFER_BIT):(e.disable(e.STENCIL_TEST),e.clear(e.DEPTH_BUFFER_BIT|e.STENCIL_BUFFER_BIT)),e.viewport(0,0,this.width,this.height),this.setBlendMode(0,!0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.blankTexture.glTexture),this.currentActiveTextureUnit=0,this.currentTextures[0]=this.blankTexture.glTexture,this.currentPipeline=t,this.currentPipeline.bind(),this.currentPipeline.onBind()},clearPipeline:function(){this.flush(),this.currentPipeline=null,this.currentProgram=null,this.currentVertexBuffer=null,this.currentIndexBuffer=null,this.setBlendMode(0,!0)},setBlendMode:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.blendModes[t];return!!(e||t!==o.BlendModes.SKIP_CHECK&&this.currentBlendMode!==t)&&(this.flush(),i.enable(i.BLEND),i.blendEquation(n.equation),n.func.length>2?i.blendFuncSeparate(n.func[0],n.func[1],n.func[2],n.func[3]):i.blendFunc(n.func[0],n.func[1]),this.currentBlendMode=t,!0)},addBlendMode:function(t,e){return this.blendModes.push({func:t,equation:e})-1},updateBlendMode:function(t,e,i){return this.blendModes[t]&&(this.blendModes[t].func=e,i&&(this.blendModes[t].equation=i)),this},removeBlendMode:function(t){return t>17&&this.blendModes[t]&&this.blendModes.splice(t,1),this},setBlankTexture:function(t){void 0===t&&(t=!1),!t&&0===this.currentActiveTextureUnit&&this.currentTextures[0]||this.setTexture2D(this.blankTexture.glTexture,0)},setTexture2D:function(t,e,i){void 0===i&&(i=!0);var n=this.gl;return t!==this.currentTextures[e]&&(i&&this.flush(),this.currentActiveTextureUnit!==e&&(n.activeTexture(n.TEXTURE0+e),this.currentActiveTextureUnit=e),n.bindTexture(n.TEXTURE_2D,t),this.currentTextures[e]=t),this},setFramebuffer:function(t,e){void 0===e&&(e=!1);var i=this.gl,n=this.width,s=this.height;return t!==this.currentFramebuffer&&(t&&t.renderTexture?(n=t.renderTexture.width,s=t.renderTexture.height):this.flush(),i.bindFramebuffer(i.FRAMEBUFFER,t),i.viewport(0,0,n,s),e&&(t?(this.drawingBufferHeight=s,this.pushScissor(0,0,n,s)):(this.drawingBufferHeight=this.height,this.popScissor())),this.currentFramebuffer=t),this},setProgram:function(t){var e=this.gl;return t!==this.currentProgram&&(this.flush(),e.useProgram(t),this.currentProgram=t),this},setVertexBuffer:function(t){var e=this.gl;return t!==this.currentVertexBuffer&&(this.flush(),e.bindBuffer(e.ARRAY_BUFFER,t),this.currentVertexBuffer=t),this},setIndexBuffer:function(t){var e=this.gl;return t!==this.currentIndexBuffer&&(this.flush(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.currentIndexBuffer=t),this},createTextureFromSource:function(t,e,i,n){var s=this.gl,r=s.NEAREST,a=s.NEAREST,l=s.CLAMP_TO_EDGE;e=t?t.width:e,i=t?t.height:i;var u=h(e,i);return u&&(l=s.REPEAT),n===o.ScaleModes.LINEAR&&this.config.antialias&&(r=u?this.mipmapFilter:s.LINEAR,a=s.LINEAR),t||"number"!=typeof e||"number"!=typeof i?this.createTexture2D(0,r,a,l,l,s.RGBA,t):this.createTexture2D(0,r,a,l,l,s.RGBA,null,e,i)},createTexture2D:function(t,e,i,n,s,r,o,a,l,u,c,d){u=void 0===u||null===u||u,void 0===c&&(c=!1),void 0===d&&(d=!1);var f=this.gl,p=f.createTexture();return this.setTexture2D(p,0),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,e),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,i),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,s),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,n),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u),f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,d),null===o||void 0===o?f.texImage2D(f.TEXTURE_2D,t,r,a,l,0,r,f.UNSIGNED_BYTE,null):(c||(a=o.width,l=o.height),f.texImage2D(f.TEXTURE_2D,t,r,r,f.UNSIGNED_BYTE,o)),h(a,l)&&f.generateMipmap(f.TEXTURE_2D),this.setTexture2D(null,0),p.isAlphaPremultiplied=u,p.isRenderTexture=!1,p.width=a,p.height=l,this.nativeTextures.push(p),p},createFramebuffer:function(t,e,i,n){var s,r=this.gl,o=r.createFramebuffer();if(this.setFramebuffer(o),n){var a=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,a),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,a)}if(i.isRenderTexture=!0,i.isAlphaPremultiplied=!1,r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),(s=r.checkFramebufferStatus(r.FRAMEBUFFER))!==r.FRAMEBUFFER_COMPLETE){throw new Error("Framebuffer incomplete. Framebuffer status: "+{36054:"Incomplete Attachment",36055:"Missing Attachment",36057:"Incomplete Dimensions",36061:"Framebuffer Unsupported"}[s])}return o.renderTexture=i,this.setFramebuffer(null),o},createProgram:function(t,e){var i=this.gl,n=i.createProgram(),s=i.createShader(i.VERTEX_SHADER),r=i.createShader(i.FRAGMENT_SHADER);if(i.shaderSource(s,t),i.shaderSource(r,e),i.compileShader(s),i.compileShader(r),!i.getShaderParameter(s,i.COMPILE_STATUS))throw new Error("Failed to compile Vertex Shader:\n"+i.getShaderInfoLog(s));if(!i.getShaderParameter(r,i.COMPILE_STATUS))throw new Error("Failed to compile Fragment Shader:\n"+i.getShaderInfoLog(r));if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw new Error("Failed to link program:\n"+i.getProgramInfoLog(n));return n},createVertexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setVertexBuffer(n),i.bufferData(i.ARRAY_BUFFER,t,e),this.setVertexBuffer(null),n},createIndexBuffer:function(t,e){var i=this.gl,n=i.createBuffer();return this.setIndexBuffer(n),i.bufferData(i.ELEMENT_ARRAY_BUFFER,t,e),this.setIndexBuffer(null),n},deleteTexture:function(t){var e=this.nativeTextures.indexOf(t);return-1!==e&&c(this.nativeTextures,e),this.gl.deleteTexture(t),this.currentTextures[0]!==t||this.game.pendingDestroy||this.setBlankTexture(!0),this},deleteFramebuffer:function(t){return this.gl.deleteFramebuffer(t),this},deleteProgram:function(t){return this.gl.deleteProgram(t),this},deleteBuffer:function(t){return this.gl.deleteBuffer(t),this},preRenderCamera:function(t){var e=t._cx,i=t._cy,n=t._cw,r=t._ch,o=this.pipelines.TextureTintPipeline,a=t.backgroundColor;if(t.renderToTexture){this.flush(),this.pushScissor(e,i,n,-r),this.setFramebuffer(t.framebuffer);var h=this.gl;h.clearColor(0,0,0,0),h.clear(h.COLOR_BUFFER_BIT),o.projOrtho(e,n+e,i,r+i,-1e3,1e3),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n+e,r+i,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL),t.emit(s.PRE_RENDER,t)}else this.pushScissor(e,i,n,r),t.mask&&(this.currentCameraMask.mask=t.mask,this.currentCameraMask.camera=t._maskCamera,t.mask.preRenderWebGL(this,t,t._maskCamera)),a.alphaGL>0&&o.drawFillRect(e,i,n,r,p.getTintFromFloats(a.redGL,a.greenGL,a.blueGL,1),a.alphaGL)},getCurrentStencilMask:function(){var t=null,e=this.maskStack,i=this.currentCameraMask;return e.length>0?t=e[e.length-1]:i.mask&&i.mask.isStencil&&(t=i),t},postRenderCamera:function(t){var e=this.pipelines.TextureTintPipeline;if(t.flashEffect.postRenderWebGL(e,p.getTintFromFloats),t.fadeEffect.postRenderWebGL(e,p.getTintFromFloats),t.dirty=!1,this.popScissor(),t.renderToTexture){e.flush(),this.setFramebuffer(null),t.emit(s.POST_RENDER,t),e.projOrtho(0,e.width,e.height,0,-1e3,1e3);var i=p.getTintAppendFloatAlpha;(t.pipeline?t.pipeline:e).batchTexture(t,t.glTexture,t.width,t.height,t.x,t.y,t.width,t.height,t.zoom,t.zoom,t.rotation,t.flipX,!t.flipY,1,1,0,0,0,0,t.width,t.height,i(t._tintTL,t._alphaTL),i(t._tintTR,t._alphaTR),i(t._tintBL,t._alphaBL),i(t._tintBR,t._alphaBR),t._isTinted&&t.tintFill,0,0,this.defaultCamera,null),this.setBlankTexture(!0)}t.mask&&(this.currentCameraMask.mask=null,t.mask.postRenderWebGL(this,t._maskCamera))},preRender:function(){if(!this.contextLost){var t=this.gl,e=this.pipelines;if(t.bindFramebuffer(t.FRAMEBUFFER,null),this.config.clearBeforeRender){var i=this.config.backgroundColor;t.clearColor(i.redGL,i.greenGL,i.blueGL,i.alphaGL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT)}for(var n in t.enable(t.SCISSOR_TEST),e)e[n].onPreRender();this.currentScissor=[0,0,this.width,this.height],this.scissorStack=[this.currentScissor],this.game.scene.customViewports&&t.scissor(0,this.drawingBufferHeight-this.height,this.width,this.height),this.currentMask.mask=null,this.currentCameraMask.mask=null,this.maskStack.length=0,this.setPipeline(this.pipelines.TextureTintPipeline)}},render:function(t,e,i,n){if(!this.contextLost){var s=e.list,r=s.length,a=this.pipelines;for(var h in a)a[h].onRender(t,n);if(this.preRenderCamera(n),0===r)return this.setBlendMode(o.BlendModes.NORMAL),void this.postRenderCamera(n);this.currentType="";for(var l=this.currentMask,u=0;u0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},createVideoTexture:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=this.gl,s=n.NEAREST,r=n.NEAREST,o=t.videoWidth,a=t.videoHeight,l=n.CLAMP_TO_EDGE,u=h(o,a);return!e&&u&&(l=n.REPEAT),this.config.antialias&&(s=u?this.mipmapFilter:n.LINEAR,r=n.LINEAR),this.createTexture2D(0,s,r,l,l,n.RGBA,t,o,a,!0,!0,i)},updateVideoTexture:function(t,e,i){void 0===i&&(i=!1);var n=this.gl,s=t.videoWidth,r=t.videoHeight;return s>0&&r>0&&(this.setTexture2D(e,0),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.width=s,e.height=r,this.setTexture2D(null,0)),e},setTextureFilter:function(t,e){var i=this.gl,n=[i.LINEAR,i.NEAREST][e];return this.setTexture2D(t,0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,n),this.setTexture2D(null,0),this},setFloat1:function(t,e,i){return this.setProgram(t),this.gl.uniform1f(this.gl.getUniformLocation(t,e),i),this},setFloat2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2f(this.gl.getUniformLocation(t,e),i,n),this},setFloat3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3f(this.gl.getUniformLocation(t,e),i,n,s),this},setFloat4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4f(this.gl.getUniformLocation(t,e),i,n,s,r),this},setFloat1v:function(t,e,i){return this.setProgram(t),this.gl.uniform1fv(this.gl.getUniformLocation(t,e),i),this},setFloat2v:function(t,e,i){return this.setProgram(t),this.gl.uniform2fv(this.gl.getUniformLocation(t,e),i),this},setFloat3v:function(t,e,i){return this.setProgram(t),this.gl.uniform3fv(this.gl.getUniformLocation(t,e),i),this},setFloat4v:function(t,e,i){return this.setProgram(t),this.gl.uniform4fv(this.gl.getUniformLocation(t,e),i),this},setInt1:function(t,e,i){return this.setProgram(t),this.gl.uniform1i(this.gl.getUniformLocation(t,e),i),this},setInt2:function(t,e,i,n){return this.setProgram(t),this.gl.uniform2i(this.gl.getUniformLocation(t,e),i,n),this},setInt3:function(t,e,i,n,s){return this.setProgram(t),this.gl.uniform3i(this.gl.getUniformLocation(t,e),i,n,s),this},setInt4:function(t,e,i,n,s,r){return this.setProgram(t),this.gl.uniform4i(this.gl.getUniformLocation(t,e),i,n,s,r),this},setMatrix2:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix2fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix3:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix3fv(this.gl.getUniformLocation(t,e),i,n),this},setMatrix4:function(t,e,i,n){return this.setProgram(t),this.gl.uniformMatrix4fv(this.gl.getUniformLocation(t,e),i,n),this},getMaxTextures:function(){return this.config.maxTextures},getMaxTextureSize:function(){return this.config.maxTextureSize},destroy:function(){for(var t=0;t0&&this.flush();var e=this.inverseRotationMatrix;if(t){var i=-t,n=Math.cos(i),s=Math.sin(i);e[1]=s,e[3]=-s,e[0]=e[4]=n}else e[0]=e[4]=1,e[1]=e[3]=0;this.renderer.setMatrix3(this.program,"uInverseRotationMatrix",!1,e),this.currentNormalMapRotation=t}},batchSprite:function(t,e,i){if(this.active){var n=t.texture.dataSource[t.frame.sourceIndex];n&&(this.renderer.setPipeline(this),this.setTexture2D(n.glTexture,1),this.setNormalMapRotation(t.rotation),r.prototype.batchSprite.call(this,t,e,i))}}});a.LIGHT_COUNT=o,t.exports=a},function(t,e){var i={modelMatrixDirty:!1,viewMatrixDirty:!1,projectionMatrixDirty:!1,modelMatrix:null,viewMatrix:null,projectionMatrix:null,mvpInit:function(){return this.modelMatrixDirty=!0,this.viewMatrixDirty=!0,this.projectionMatrixDirty=!0,this.modelMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.viewMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.projectionMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this},mvpUpdate:function(){var t=this.program;return this.modelMatrixDirty&&(this.renderer.setMatrix4(t,"uModelMatrix",!1,this.modelMatrix),this.modelMatrixDirty=!1),this.viewMatrixDirty&&(this.renderer.setMatrix4(t,"uViewMatrix",!1,this.viewMatrix),this.viewMatrixDirty=!1),this.projectionMatrixDirty&&(this.renderer.setMatrix4(t,"uProjectionMatrix",!1,this.projectionMatrix),this.projectionMatrixDirty=!1),this},modelIdentity:function(){var t=this.modelMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.modelMatrixDirty=!0,this},modelScale:function(t,e,i){var n=this.modelMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.modelMatrixDirty=!0,this},modelTranslate:function(t,e,i){var n=this.modelMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.modelMatrixDirty=!0,this},modelRotateX:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.modelMatrixDirty=!0,this},modelRotateY:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.modelMatrixDirty=!0,this},modelRotateZ:function(t){var e=this.modelMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.modelMatrixDirty=!0,this},viewIdentity:function(){var t=this.viewMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.viewMatrixDirty=!0,this},viewScale:function(t,e,i){var n=this.viewMatrix;return n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*t,n[3]=n[3]*t,n[4]=n[4]*e,n[5]=n[5]*e,n[6]=n[6]*e,n[7]=n[7]*e,n[8]=n[8]*i,n[9]=n[9]*i,n[10]=n[10]*i,n[11]=n[11]*i,this.viewMatrixDirty=!0,this},viewTranslate:function(t,e,i){var n=this.viewMatrix;return n[12]=n[0]*t+n[4]*e+n[8]*i+n[12],n[13]=n[1]*t+n[5]*e+n[9]*i+n[13],n[14]=n[2]*t+n[6]*e+n[10]*i+n[14],n[15]=n[3]*t+n[7]*e+n[11]*i+n[15],this.viewMatrixDirty=!0,this},viewRotateX:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[4],r=e[5],o=e[6],a=e[7],h=e[8],l=e[9],u=e[10],c=e[11];return e[4]=s*n+h*i,e[5]=r*n+l*i,e[6]=o*n+u*i,e[7]=a*n+c*i,e[8]=h*n-s*i,e[9]=l*n-r*i,e[10]=u*n-o*i,e[11]=c*n-a*i,this.viewMatrixDirty=!0,this},viewRotateY:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[8],l=e[9],u=e[10],c=e[11];return e[0]=s*n-h*i,e[1]=r*n-l*i,e[2]=o*n-u*i,e[3]=a*n-c*i,e[8]=s*i+h*n,e[9]=r*i+l*n,e[10]=o*i+u*n,e[11]=a*i+c*n,this.viewMatrixDirty=!0,this},viewRotateZ:function(t){var e=this.viewMatrix,i=Math.sin(t),n=Math.cos(t),s=e[0],r=e[1],o=e[2],a=e[3],h=e[4],l=e[5],u=e[6],c=e[7];return e[0]=s*n+h*i,e[1]=r*n+l*i,e[2]=o*n+u*i,e[3]=a*n+c*i,e[4]=h*n-s*i,e[5]=l*n-r*i,e[6]=u*n-o*i,e[7]=c*n-a*i,this.viewMatrixDirty=!0,this},viewLoad2D:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=0,e[3]=0,e[4]=t[2],e[5]=t[3],e[6]=0,e[7]=0,e[8]=t[4],e[9]=t[5],e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this.viewMatrixDirty=!0,this},viewLoad:function(t){var e=this.viewMatrix;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this.viewMatrixDirty=!0,this},projIdentity:function(){var t=this.projectionMatrix;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this.projectionMatrixDirty=!0,this},projOrtho:function(t,e,i,n,s,r){var o=this.projectionMatrix,a=1/(t-e),h=1/(i-n),l=1/(s-r);return o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*h,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*l,o[11]=0,o[12]=(t+e)*a,o[13]=(n+i)*h,o[14]=(r+s)*l,o[15]=1,this.projectionMatrixDirty=!0,this},projPersp:function(t,e,i,n){var s=this.projectionMatrix,r=1/Math.tan(t/2),o=1/(i-n);return s[0]=r/e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=(n+i)*o,s[11]=-1,s[12]=0,s[13]=0,s[14]=2*n*i*o,s[15]=0,this.projectionMatrixDirty=!0,this}};t.exports=i},function(t,e,i){var n={};t.exports=n;var s=i(101),r=i(37);n.fromVertices=function(t){for(var e={},i=0;i1?1:0;d1?1:0;p0:0!=(t.mask&e.category)&&0!=(e.mask&t.category)}},function(t,e,i){var n={};t.exports=n;var s=i(86),r=i(101);n.collides=function(t,e,i){var o,a,h,l,u=!1;if(i){var c=t.parent,d=e.parent,f=c.speed*c.speed+c.angularSpeed*c.angularSpeed+d.speed*d.speed+d.angularSpeed*d.angularSpeed;u=i&&i.collided&&f<.2,l=i}else l={collided:!1,bodyA:t,bodyB:e};if(i&&u){var p=l.axisBody,g=p===t?e:t,v=[p.axes[i.axisNumber]];if(h=n._overlapAxes(p.vertices,g.vertices,v),l.reused=!0,h.overlap<=0)return l.collided=!1,l}else{if((o=n._overlapAxes(t.vertices,e.vertices,t.axes)).overlap<=0)return l.collided=!1,l;if((a=n._overlapAxes(e.vertices,t.vertices,e.axes)).overlap<=0)return l.collided=!1,l;o.overlaps?s=a:a=0?o.index-1:u.length-1],l.x=s.x-c.x,l.y=s.y-c.y,h=-r.dot(i,l),a=s,s=u[(o.index+1)%u.length],l.x=s.x-c.x,l.y=s.y-c.y,(n=-r.dot(i,l))>>0;if("function"!=typeof t)throw new TypeError;for(var n=arguments.length>=2?arguments[1]:void 0,s=0;s>16)+(65280&t)+((255&t)<<16)},n={_tintTL:16777215,_tintTR:16777215,_tintBL:16777215,_tintBR:16777215,_isTinted:!1,tintFill:!1,clearTint:function(){return this.setTint(16777215),this._isTinted=!1,this},setTint:function(t,e,n,s){return void 0===t&&(t=16777215),void 0===e&&(e=t,n=t,s=t),this._tintTL=i(t),this._tintTR=i(e),this._tintBL=i(n),this._tintBR=i(s),this._isTinted=!0,this.tintFill=!1,this},setTintFill:function(t,e,i,n){return this.setTint(t,e,i,n),this.tintFill=!0,this},tintTopLeft:{get:function(){return this._tintTL},set:function(t){this._tintTL=i(t),this._isTinted=!0}},tintTopRight:{get:function(){return this._tintTR},set:function(t){this._tintTR=i(t),this._isTinted=!0}},tintBottomLeft:{get:function(){return this._tintBL},set:function(t){this._tintBL=i(t),this._isTinted=!0}},tintBottomRight:{get:function(){return this._tintBR},set:function(t){this._tintBR=i(t),this._isTinted=!0}},tint:{set:function(t){this.setTint(t,t,t,t)}},isTinted:{get:function(){return this._isTinted}}};t.exports=n},function(t,e){t.exports="changedata"},function(t,e){t.exports="changedata-"},function(t,e){t.exports="removedata"},function(t,e){t.exports="setdata"},function(t,e){t.exports="destroy"},function(t,e){t.exports="complete"},function(t,e){t.exports="created"},function(t,e){t.exports="error"},function(t,e){t.exports="loop"},function(t,e){t.exports="play"},function(t,e){t.exports="seeked"},function(t,e){t.exports="seeking"},function(t,e){t.exports="stop"},function(t,e){t.exports="timeout"},function(t,e){t.exports="unlocked"},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"alpha",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"x",e,i,s,r)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r,o,a){return void 0!==i&&null!==i||(i=e),n(t,"x",e,s,o,a),n(t,"y",i,r,o,a)}},function(t,e,i){var n=i(34);t.exports=function(t,e,i,s,r){return n(t,"y",e,i,s,r)}},function(t,e){t.exports=function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=6.28);for(var s=i,r=(n-i)/t.length,o=0;o0?s(o,i):i<0&&r(o,Math.abs(i));for(var a=0;a1)if(0===s){var d=t.length-1;for(o=t[d].x,a=t[d].y,h=d-1;h>=0;h--)l=(c=t[h]).x,u=c.y,c.x=o,c.y=a,o=l,a=u;t[d].x=e,t[d].y=i}else{for(o=t[0].x,a=t[0].y,h=1;h0?(this._speedX-=this.dragX*t,this._speedX<0&&(this._speedX=0)):this._speedX<0&&(this._speedX+=this.dragX*t,this._speedX>0&&(this._speedX=0)),this._speedY>0?(this._speedY-=this.dragY*t,this._speedY<0&&(this._speedY=0)):this._speedY<0&&(this._speedY+=this.dragY*t,this._speedY>0&&(this._speedY=0)),this.up&&this.up.isDown?(this._speedY+=this.accelY,this._speedY>this.maxSpeedY&&(this._speedY=this.maxSpeedY)):this.down&&this.down.isDown&&(this._speedY-=this.accelY,this._speedY<-this.maxSpeedY&&(this._speedY=-this.maxSpeedY)),this.left&&this.left.isDown?(this._speedX+=this.accelX,this._speedX>this.maxSpeedX&&(this._speedX=this.maxSpeedX)):this.right&&this.right.isDown&&(this._speedX-=this.accelX,this._speedX<-this.maxSpeedX&&(this._speedX=-this.maxSpeedX)),this.zoomIn&&this.zoomIn.isDown?this._zoom=-this.zoomSpeed:this.zoomOut&&this.zoomOut.isDown?this._zoom=this.zoomSpeed:this._zoom=0,0!==this._speedX&&(e.scrollX-=this._speedX*t|0),0!==this._speedY&&(e.scrollY-=this._speedY*t|0),0!==this._zoom&&(e.zoom+=this._zoom,e.zoom<.001&&(e.zoom=.001))}},destroy:function(){this.camera=null,this.left=null,this.right=null,this.up=null,this.down=null,this.zoomIn=null,this.zoomOut=null}});t.exports=r},function(t,e,i){t.exports={Camera:i(290),BaseCamera:i(91),CameraManager:i(693),Effects:i(298),Events:i(48)}},function(t,e){t.exports="cameradestroy"},function(t,e){t.exports="camerafadeincomplete"},function(t,e){t.exports="camerafadeinstart"},function(t,e){t.exports="camerafadeoutcomplete"},function(t,e){t.exports="camerafadeoutstart"},function(t,e){t.exports="cameraflashcomplete"},function(t,e){t.exports="cameraflashstart"},function(t,e){t.exports="camerapancomplete"},function(t,e){t.exports="camerapanstart"},function(t,e){t.exports="postrender"},function(t,e){t.exports="prerender"},function(t,e){t.exports="camerashakecomplete"},function(t,e){t.exports="camerashakestart"},function(t,e){t.exports="camerazoomcomplete"},function(t,e){t.exports="camerazoomstart"},function(t,e,i){var n=i(22),s=i(0),r=i(48),o=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.isComplete=!1,this.direction=!0,this.duration=0,this.red=0,this.green=0,this.blue=0,this.alpha=0,this.progress=0,this._elapsed=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s,o,a,h){if(void 0===t&&(t=!0),void 0===e&&(e=1e3),void 0===i&&(i=0),void 0===n&&(n=0),void 0===s&&(s=0),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===h&&(h=this.camera.scene),!o&&this.isRunning)return this.camera;this.isRunning=!0,this.isComplete=!1,this.duration=e,this.direction=t,this.progress=0,this.red=i,this.green=n,this.blue=s,this.alpha=t?Number.MIN_VALUE:1,this._elapsed=0,this._onUpdate=a,this._onUpdateScope=h;var l=t?r.FADE_OUT_START:r.FADE_IN_START;return this.camera.emit(l,this.camera,this,e,i,n,s),this.camera},update:function(t,e){this.isRunning&&(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed=1?1:1/e*(1+(e*t|0))}},function(t,e,i){var n=i(22),s=i(0),r=i(48),o=i(3),a=new s({initialize:function(t){this.camera=t,this.isRunning=!1,this.duration=0,this.intensity=new o,this.progress=0,this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate,this._onUpdateScope},start:function(t,e,i,n,s){return void 0===t&&(t=100),void 0===e&&(e=.05),void 0===i&&(i=!1),void 0===n&&(n=null),void 0===s&&(s=this.camera.scene),!i&&this.isRunning?this.camera:(this.isRunning=!0,this.duration=t,this.progress=0,"number"==typeof e?this.intensity.set(e):this.intensity.set(e.x,e.y),this._elapsed=0,this._offsetX=0,this._offsetY=0,this._onUpdate=n,this._onUpdateScope=s,this.camera.emit(r.SHAKE_START,this.camera,this,t,e),this.camera)},preRender:function(){this.isRunning&&this.camera.matrix.translate(this._offsetX,this._offsetY)},update:function(t,e){if(this.isRunning)if(this._elapsed+=e,this.progress=n(this._elapsed/this.duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.camera,this.progress),this._elapsed0&&(o.preRender(1),t.render(n,e,i,o))}},resetAll:function(){for(var t=0;t1)for(var i=1;i=1)&&(s.touch=!0),(navigator.msPointerEnabled||navigator.pointerEnabled)&&(s.mspointer=!0),navigator.getGamepads&&(s.gamepads=!0),"onwheel"in window||n.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":n.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"),s)},function(t,e,i){var n=i(117),s={audioData:!1,dolby:!1,m4a:!1,mp3:!1,ogg:!1,opus:!1,wav:!1,webAudio:!1,webm:!1};t.exports=function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio"),e=!!t.canPlayType;try{if(e&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(n.edge)s.dolby=!0;else if(n.safari&&n.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var i=parseInt(RegExp.$1,10),r=parseInt(RegExp.$2,10);(10===i&&r>=11||i>10)&&(s.dolby=!0)}}catch(t){}return s}()},function(t,e){var i={h264:!1,hls:!1,mp4:!1,ogg:!1,vp9:!1,webm:!1};t.exports=function(){var t=document.createElement("video"),e=!!t.canPlayType;try{e&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(i.ogg=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.h264=!0,i.mp4=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(i.webm=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(i.vp9=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(i.hls=!0))}catch(t){}return i}()},function(t,e){var i={available:!1,cancel:"",keyboard:!1,request:""};t.exports=function(){var t,e="Fullscreen",n="FullScreen",s=["request"+e,"request"+n,"webkitRequest"+e,"webkitRequest"+n,"msRequest"+e,"msRequest"+n,"mozRequest"+n,"mozRequest"+e];for(t=0;tMath.PI&&(t-=n.PI2),Math.abs(((t+n.TAU)%n.PI2-n.PI2)%n.PI2)}},function(t,e,i){var n=i(315);t.exports=function(t){return n(t+Math.PI)}},function(t,e,i){var n=i(13);t.exports=function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=i:e1?t[i]-(n(s-i,t[i],t[i],t[i-1],t[i-1])-t[i]):n(s-r,t[r?r-1:0],t[r],t[i1?n(t[i],t[i-1],i-s):n(t[r],t[r+1>i?i:r+1],s-r)}},function(t,e,i){var n=i(157);t.exports=function(t,e,i){return e+(i-e)*n(t,0,1)}},function(t,e,i){t.exports={GetNext:i(324),IsSize:i(118),IsValue:i(749)}},function(t,e){t.exports=function(t){return t>0&&0==(t&t-1)}},function(t,e,i){t.exports={Ceil:i(325),Floor:i(93),To:i(751)}},function(t,e){t.exports=function(t,e,i,n){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),n?(i+t)/e:i+t)}},function(t,e,i){var n=new(i(0))({initialize:function(t){void 0===t&&(t=[(Date.now()*Math.random()).toString()]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.n=0,this.signs=[-1,1],t&&this.init(t)},rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},hash:function(t){var e,i=this.n;t=t.toString();for(var n=0;n>>0,i=(e*=i)>>>0,i+=4294967296*(e-=i);return this.n=i,2.3283064365386963e-10*(i>>>0)},init:function(t){"string"==typeof t?this.state(t):this.sow(t)},sow:function(t){if(this.n=4022871197,this.s0=this.hash(" "),this.s1=this.hash(" "),this.s2=this.hash(" "),this.c=1,t)for(var e=0;e0;e--){var i=Math.floor(this.frac()*(e+1)),n=t[i];t[i]=t[e],t[e]=n}return t}});t.exports=n},function(t,e){t.exports=function(t){for(var e=0,i=0;i1?void 0!==n?(s=(n-t)/(n-i))<0&&(s=0):s=1:s<0&&(s=0),s}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI;return t.x=Math.cos(i)*e,t.y=Math.sin(i)*e,t}},function(t,e){t.exports=function(t,e){void 0===e&&(e=1);var i=2*Math.random()*Math.PI,n=2*Math.random()-1,s=Math.sqrt(1-n*n)*e;return t.x=Math.cos(i)*s,t.y=Math.sin(i)*s,t.z=n*e,t}},function(t,e){t.exports=function(t,e){return void 0===e&&(e=1),t.x=(2*Math.random()-1)*e,t.y=(2*Math.random()-1)*e,t.z=(2*Math.random()-1)*e,t.w=(2*Math.random()-1)*e,t}},function(t,e){t.exports=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var n=Math.pow(i,-e);return Math.round(t*n)/n}},function(t,e){t.exports=function(t,e,i,n){void 0===e&&(e=1),void 0===i&&(i=1),void 0===n&&(n=1),n*=Math.PI/t;for(var s=[],r=[],o=0;o0&&t<=e*i&&(r=t>e-1?t-(o=Math.floor(t/e))*e:t,s.set(r,o)),s}},function(t,e){t.exports=function(t,e,i){return Math.abs(t-e)<=i}},function(t,e,i){var n=i(172),s=i(332),r=i(333),o=new s,a=new r,h=new n;t.exports=function(t,e,i){return a.setAxisAngle(e,i),o.fromRotationTranslation(a,h.set(0,0,0)),t.transformMat4(o)}},function(t,e){t.exports="addtexture"},function(t,e){t.exports="onerror"},function(t,e){t.exports="onload"},function(t,e){t.exports="ready"},function(t,e){t.exports="removetexture"},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_FS","","precision mediump float;","","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uMaskSampler;","uniform bool uInvertMaskAlpha;","","void main()","{"," vec2 uv = gl_FragCoord.xy / uResolution;"," vec4 mainColor = texture2D(uMainSampler, uv);"," vec4 maskColor = texture2D(uMaskSampler, uv);"," float alpha = mainColor.a;",""," if (!uInvertMaskAlpha)"," {"," alpha *= (maskColor.a);"," }"," else"," {"," alpha *= (1.0 - maskColor.a);"," }",""," gl_FragColor = vec4(mainColor.rgb * alpha, alpha);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_BITMAP_MASK_VS","","precision mediump float;","","attribute vec2 inPosition;","","void main()","{"," gl_Position = vec4(inPosition, 0.0, 1.0);","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS","","precision mediump float;","","struct Light","{"," vec2 position;"," vec3 color;"," float intensity;"," float radius;","};","","const int kMaxLights = %LIGHT_COUNT%;","","uniform vec4 uCamera; /* x, y, rotation, zoom */","uniform vec2 uResolution;","uniform sampler2D uMainSampler;","uniform sampler2D uNormSampler;","uniform vec3 uAmbientLightColor;","uniform Light uLights[kMaxLights];","uniform mat3 uInverseRotationMatrix;","","varying vec2 outTexCoord;","varying vec4 outTint;","","void main()","{"," vec3 finalColor = vec3(0.0, 0.0, 0.0);"," vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);"," vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;"," vec3 normal = normalize(uInverseRotationMatrix * vec3(normalMap * 2.0 - 1.0));"," vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;",""," for (int index = 0; index < kMaxLights; ++index)"," {"," Light light = uLights[index];"," vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);"," vec3 lightNormal = normalize(lightDir);"," float distToSurf = length(lightDir) * uCamera.w;"," float diffuseFactor = max(dot(normal, lightNormal), 0.0);"," float radius = (light.radius / res.x * uCamera.w) * uCamera.w;"," float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);"," vec3 diffuse = light.color * diffuseFactor;"," finalColor += (attenuation * diffuse) * light.intensity;"," }",""," vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);"," gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);","","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_FS","","precision mediump float;","","uniform sampler2D uMainSampler;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main()","{"," vec4 texture = texture2D(uMainSampler, outTexCoord);"," vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);"," vec4 color = texture;",""," if (outTintEffect == 0.0)"," {"," // Multiply texture tint"," color = texture * texel;"," }"," else if (outTintEffect == 1.0)"," {"," // Solid color + texture alpha"," color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);"," color.a = texture.a * texel.a;"," }"," else if (outTintEffect == 2.0)"," {"," // Solid color, no texture"," color = texel;"," }",""," gl_FragColor = color;","}",""].join("\n")},function(t,e){t.exports=["#define SHADER_NAME PHASER_TEXTURE_TINT_VS","","precision mediump float;","","uniform mat4 uProjectionMatrix;","uniform mat4 uViewMatrix;","uniform mat4 uModelMatrix;","","attribute vec2 inPosition;","attribute vec2 inTexCoord;","attribute float inTintEffect;","attribute vec4 inTint;","","varying vec2 outTexCoord;","varying float outTintEffect;","varying vec4 outTint;","","void main ()","{"," gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);",""," outTexCoord = inTexCoord;"," outTint = inTint;"," outTintEffect = inTintEffect;","}","",""].join("\n")},function(t,e,i){t.exports={GenerateTexture:i(340),Palettes:i(782)}},function(t,e,i){t.exports={ARNE16:i(341),C64:i(783),CGA:i(784),JMP:i(785),MSX:i(786)}},function(t,e){t.exports={0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"}},function(t,e){t.exports={0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"}},function(t,e){t.exports={0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}},function(t,e,i){t.exports={Path:i(788),CubicBezier:i(342),Curve:i(80),Ellipse:i(343),Line:i(344),QuadraticBezier:i(345),Spline:i(346)}},function(t,e,i){var n=i(0),s=i(342),r=i(343),o=i(5),a=i(344),h=i(789),l=i(345),u=i(11),c=i(346),d=i(3),f=i(13),p=new n({initialize:function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.name="",this.curves=[],this.cacheLengths=[],this.autoClose=!1,this.startPoint=new d,this._tmpVec2A=new d,this._tmpVec2B=new d,"object"==typeof t?this.fromJSON(t):this.startPoint.set(t,e)},add:function(t){return this.curves.push(t),this},circleTo:function(t,e,i){return void 0===e&&(e=!1),this.ellipseTo(t,t,0,360,e,i)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);return t.equals(e)||this.curves.push(new a(e,t)),this},cubicBezierTo:function(t,e,i,n,r,o){var a,h,l,u=this.getEndPoint();return t instanceof d?(a=t,h=e,l=i):(a=new d(i,n),h=new d(r,o),l=new d(t,e)),this.add(new s(u,a,h,l))},quadraticBezierTo:function(t,e,i,n){var s,r,o=this.getEndPoint();return t instanceof d?(s=t,r=e):(s=new d(i,n),r=new d(t,e)),this.add(new l(o,s,r))},draw:function(t,e){for(var i=0;i0?this.curves[this.curves.length-1].getPoint(1,t):t.copy(this.startPoint),t},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},getPoint:function(t,e){void 0===e&&(e=new d);for(var i=t*this.getLength(),n=this.getCurveLengths(),s=0;s=i){var r=n[s]-i,o=this.curves[s],a=o.getLength(),h=0===a?0:1-r/a;return o.getPointAt(h,e)}s++}return null},getPoints:function(t){void 0===t&&(t=12);for(var e,i=[],n=0;n1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},getRandomPoint:function(t){return void 0===t&&(t=new d),this.getPoint(Math.random(),t)},getSpacedPoints:function(t){void 0===t&&(t=40);for(var e=[],i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e},getStartPoint:function(t){return void 0===t&&(t=new d),t.copy(this.startPoint)},lineTo:function(t,e){t instanceof d?this._tmpVec2B.copy(t):this._tmpVec2B.set(t,e);var i=this.getEndPoint(this._tmpVec2A);return this.add(new a([i.x,i.y,this._tmpVec2B.x,this._tmpVec2B.y]))},splineTo:function(t){return t.unshift(this.getEndPoint()),this.add(new c(t))},moveTo:function(t,e){return t instanceof d?this.add(new h(t.x,t.y)):this.add(new h(t,e))},toJSON:function(){for(var t=[],e=0;e>16&255,g:t>>8&255,b:255&t,a:255};return t>16777215&&(e.a=t>>>24),e}},function(t,e,i){var n=i(33),s=i(350);t.exports=function(t,e,i){var r=i,o=i,a=i;if(0!==e){var h=i<.5?i*(1+e):i+e-i*e,l=2*i-h;r=s(l,h,t+1/3),o=s(l,h,t),a=s(l,h,t-1/3)}return(new n).setGLTo(r,o,a,1)}},function(t,e,i){var n=i(163);t.exports=function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n(s/359,t,e));return i}},function(t,e,i){var n=i(115),s=function(t,e,i,s,r,o,a,h){void 0===a&&(a=100),void 0===h&&(h=0);var l=h/a;return{r:n(t,s,l),g:n(e,r,l),b:n(i,o,l)}};t.exports={RGBWithRGB:s,ColorWithRGB:function(t,e,i,n,r,o){return void 0===r&&(r=100),void 0===o&&(o=0),s(t.r,t.g,t.b,e,i,n,r,o)},ColorWithColor:function(t,e,i,n){return void 0===i&&(i=100),void 0===n&&(n=0),s(t.r,t.g,t.b,e.r,e.g,e.b,i,n)}}},function(t,e,i){var n=i(170),s=i(33);t.exports=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=255),new s(n(t,e),n(t,e),n(t,e))}},function(t,e,i){var n=i(349);t.exports=function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n(s)+n(t)+n(e)+n(i)}},function(t,e,i){t.exports={BitmapMask:i(275),GeometryMask:i(276)}},function(t,e,i){var n={AddToDOM:i(120),DOMContentLoaded:i(351),GetScreenOrientation:i(352),GetTarget:i(357),ParseXML:i(358),RemoveFromDOM:i(176),RequestAnimationFrame:i(338)};t.exports=n},function(t,e,i){t.exports={EventEmitter:i(811)}},function(t,e,i){var n=i(0),s=i(9),r=i(23),o=new n({Extends:s,initialize:function(){s.call(this)},shutdown:function(){this.removeAllListeners()},destroy:function(){this.removeAllListeners()}});r.register("EventEmitter",o,"events"),t.exports=o},function(t,e,i){var n=i(120),s=i(286),r=i(289),o=i(26),a=i(0),h=i(311),l=i(813),u=i(334),c=i(113),d=i(336),f=i(312),p=i(351),g=i(9),v=i(18),m=i(359),y=i(23),x=i(364),T=i(365),w=i(367),b=i(119),E=i(370),S=i(337),A=i(339),_=i(374),C=new a({initialize:function(t){this.config=new h(t),this.renderer=null,this.domContainer=null,this.canvas=null,this.context=null,this.isBooted=!1,this.isRunning=!1,this.events=new g,this.anims=new s(this),this.textures=new E(this),this.cache=new r(this),this.registry=new c(this),this.input=new m(this,this.config),this.scene=new w(this,this.config.sceneConfig),this.device=f,this.scale=new T(this,this.config),this.sound=null,this.sound=_.create(this),this.loop=new S(this,this.config.fps),this.plugins=new x(this,this.config),this.pendingDestroy=!1,this.removeCanvas=!1,this.noReturn=!1,this.hasFocus=!1,p(this.boot.bind(this))},boot:function(){y.hasCore("EventEmitter")?(this.isBooted=!0,this.config.preBoot(this),this.scale.preBoot(),u(this),l(this),d(this),n(this.canvas,this.config.parent),this.textures.once(b.READY,this.texturesReady,this),this.events.emit(v.BOOT)):console.warn("Aborting. Core Plugins missing.")},texturesReady:function(){this.events.emit(v.READY),this.start()},start:function(){this.isRunning=!0,this.config.postBoot(this),this.renderer?this.loop.start(this.step.bind(this)):this.loop.start(this.headlessStep.bind(this)),A(this);var t=this.events;t.on(v.HIDDEN,this.onHidden,this),t.on(v.VISIBLE,this.onVisible,this),t.on(v.BLUR,this.onBlur,this),t.on(v.FOCUS,this.onFocus,this)},step:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e);var n=this.renderer;n.preRender(),i.emit(v.PRE_RENDER,n,t,e),this.scene.render(n),n.postRender(),i.emit(v.POST_RENDER,n,t,e)},headlessStep:function(t,e){if(this.pendingDestroy)return this.runDestroy();var i=this.events;i.emit(v.PRE_STEP,t,e),i.emit(v.STEP,t,e),this.scene.update(t,e),i.emit(v.POST_STEP,t,e),i.emit(v.PRE_RENDER),i.emit(v.POST_RENDER)},onHidden:function(){this.loop.pause(),this.events.emit(v.PAUSE)},onVisible:function(){this.loop.resume(),this.events.emit(v.RESUME)},onBlur:function(){this.hasFocus=!1,this.loop.blur()},onFocus:function(){this.hasFocus=!0,this.loop.focus()},getFrame:function(){return this.loop.frame},getTime:function(){return this.loop.now},destroy:function(t,e){void 0===e&&(e=!1),this.pendingDestroy=!0,this.removeCanvas=t,this.noReturn=e},runDestroy:function(){this.scene.destroy(),this.events.emit(v.DESTROY),this.events.removeAllListeners(),this.renderer&&this.renderer.destroy(),this.removeCanvas&&this.canvas&&(o.remove(this.canvas),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)),this.domContainer&&this.domContainer.parentNode.removeChild(this.domContainer),this.loop.destroy(),this.pendingDestroy=!1}});t.exports=C},function(t,e,i){var n=i(120);t.exports=function(t){var e=t.config;if(e.parent&&e.domCreateContainer){var i=document.createElement("div");i.style.cssText=["display: block;","width: "+t.scale.width+"px;","height: "+t.scale.height+"px;","padding: 0; margin: 0;","position: absolute;","overflow: hidden;","pointer-events: none;","transform: scale(1);","transform-origin: left top;"].join(" "),t.domContainer=i,n(i,e.parent)}}},function(t,e){t.exports="boot"},function(t,e){t.exports="destroy"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameout"},function(t,e){t.exports="gameover"},function(t,e){t.exports="gameobjectdown"},function(t,e){t.exports="dragend"},function(t,e){t.exports="dragenter"},function(t,e){t.exports="drag"},function(t,e){t.exports="dragleave"},function(t,e){t.exports="dragover"},function(t,e){t.exports="dragstart"},function(t,e){t.exports="drop"},function(t,e){t.exports="gameobjectmove"},function(t,e){t.exports="gameobjectout"},function(t,e){t.exports="gameobjectover"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="wheel"},function(t,e){t.exports="gameobjectup"},function(t,e){t.exports="gameobjectwheel"},function(t,e){t.exports="boot"},function(t,e){t.exports="process"},function(t,e){t.exports="update"},function(t,e){t.exports="pointerdown"},function(t,e){t.exports="pointerdownoutside"},function(t,e){t.exports="pointermove"},function(t,e){t.exports="pointerout"},function(t,e){t.exports="pointerover"},function(t,e){t.exports="pointerup"},function(t,e){t.exports="pointerupoutside"},function(t,e){t.exports="wheel"},function(t,e){t.exports="pointerlockchange"},function(t,e){t.exports="preupdate"},function(t,e){t.exports="shutdown"},function(t,e){t.exports="start"},function(t,e){t.exports="update"},function(t,e){t.exports=function(t){if(!t)return window.innerHeight;var e=Math.abs(window.orientation),i={w:0,h:0},n=document.createElement("div");return n.setAttribute("style","position: fixed; height: 100vh; width: 0; top: 0"),document.documentElement.appendChild(n),i.w=90===e?n.offsetHeight:window.innerWidth,i.h=90===e?window.innerWidth:n.offsetHeight,document.documentElement.removeChild(n),n=null,90!==Math.abs(window.orientation)?i.h:i.w}},function(t,e){t.exports="addfile"},function(t,e){t.exports="complete"},function(t,e){t.exports="filecomplete"},function(t,e){t.exports="filecomplete-"},function(t,e){t.exports="loaderror"},function(t,e){t.exports="load"},function(t,e){t.exports="fileprogress"},function(t,e){t.exports="postprocess"},function(t,e){t.exports="progress"},function(t,e){t.exports="start"},function(t,e,i){var n=i(2),s=i(179);t.exports=function(t){var e=t.game.config.defaultPhysicsSystem,i=n(t.settings,"physics",!1);if(e||i){var r=[];if(e&&r.push(s(e+"Physics")),i)for(var o in i)o=s(o.concat("Physics")),-1===r.indexOf(o)&&r.push(o);return r}}},function(t,e,i){var n=i(2);t.exports=function(t){var e=t.plugins.getDefaultScenePlugins(),i=n(t.settings,"plugins",!1);return Array.isArray(i)?i:e||[]}},function(t,e,i){t.exports={game:"game",anims:"anims",cache:"cache",plugins:"plugins",registry:"registry",scale:"scale",sound:"sound",textures:"textures",events:"events",cameras:"cameras",add:"add",make:"make",scenePlugin:"scene",displayList:"children",lights:"lights",data:"data",input:"input",load:"load",time:"time",tweens:"tweens",arcadePhysics:"physics",impactPhysics:"impact",matterPhysics:"matter"}},function(t,e){t.exports=function(t,e,i){if(i.getElementsByTagName("TextureAtlas")){var n=t.source[e];t.add("__BASE",e,0,0,n.width,n.height);for(var s,r=i.getElementsByTagName("SubTexture"),o=0;og||c<-g)&&(c=0),c<0&&(c=g+c),-1!==d&&(g=c+(d+1));for(var v=f,m=f,y=0,x=0,T=0;Tr&&(y=w-r),b>o&&(x=b-o),t.add(T,e,i+v,s+m,h-y,l-x),(v+=h+p)+h>r&&(v=f,m+=l+p)}return t}},function(t,e,i){var n=i(2);t.exports=function(t,e,i){var s=n(i,"frameWidth",null),r=n(i,"frameHeight",s);if(!s)throw new Error("TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.");var o=t.source[0];t.add("__BASE",0,0,0,o.width,o.height);var a,h=n(i,"startFrame",0),l=n(i,"endFrame",-1),u=n(i,"margin",0),c=n(i,"spacing",0),d=e.cutX,f=e.cutY,p=e.cutWidth,g=e.cutHeight,v=e.realWidth,m=e.realHeight,y=Math.floor((v-u+c)/(s+c)),x=Math.floor((m-u+c)/(r+c)),T=y*x,w=e.x,b=s-w,E=s-(v-p-w),S=e.y,A=r-S,_=r-(m-g-S);(h>T||h<-T)&&(h=0),h<0&&(h=T+h),-1!==l&&(T=h+(l+1));for(var C=u,M=u,O=0,P=e.sourceIndex,R=0;R0){var r=i-t.length;if(r<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.push(e),n&&n.call(s,e),e):null;for(var o=e.length-1;o>=0;)-1!==t.indexOf(e[o])&&e.splice(o,1),o--;if(0===(o=e.length))return null;i>0&&o>r&&(e.splice(r),o=r);for(var a=0;a0){var o=n-t.length;if(o<=0)return null}if(!Array.isArray(e))return-1===t.indexOf(e)?(t.splice(i,0,e),s&&s.call(r,e),e):null;for(var a=e.length-1;a>=0;)-1!==t.indexOf(e[a])&&e.pop(),a--;if(0===(a=e.length))return null;n>0&&a>o&&(e.splice(o),a=o);for(var h=a-1;h>=0;h--){var l=e[h];t.splice(i,0,l),s&&s.call(r,l)}return e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);return-1!==i&&i0){var n=t[i-1],s=t.indexOf(n);t[i]=n,t[s]=e}return t}},function(t,e){t.exports=function(t,e,i){var n=t.indexOf(e);if(-1===n||i<0||i>=t.length)throw new Error("Supplied index out of bounds");return n!==i&&(t.splice(n,1),t.splice(i,0,e)),e}},function(t,e){t.exports=function(t,e){var i=t.indexOf(e);if(-1!==i&&it.length-1)throw new Error("Index out of bounds");var r=n(t,e);return i&&i.call(s,r),r}},function(t,e,i){var n=i(68);t.exports=function(t,e,i,s,r){if(void 0===e&&(e=0),void 0===i&&(i=t.length),void 0===r&&(r=t),n(t,e,i)){var o=i-e,a=t.splice(e,o);if(s)for(var h=0;h0&&(t.splice(i,1),t.unshift(e)),e}},function(t,e,i){var n=i(68);t.exports=function(t,e,i,s,r){if(void 0===s&&(s=0),void 0===r&&(r=t.length),n(t,s,r))for(var o=s;o0){for(n=0;nl||U-N>l?(Y.push(X.i-1),X.cr?(Y.push(X.i+X.word.length),N=0,B=null):B=X):X.cr&&(Y.push(X.i+X.word.length),N=0,B=null)}for(n=Y.length-1;n>=0;n--)s=a,r=Y[n],o="\n",a=s.substr(0,r)+o+s.substr(r+1);i.wrappedText=a,h=a.length,D=[],F=null}for(n=0;nb&&(c=b),d>E&&(d=E);var W=b+w.xAdvance,V=E+v;fR&&(R=k),kR&&(R=k),k0&&(a=(o=z.wrappedText).length);var U=e._bounds.lines;1===N?X=(U.longest-U.lengths[0])/2:2===N&&(X=U.longest-U.lengths[0]);for(var G=s.roundPixels,W=0;W0&&(a=(o=L.wrappedText).length);var k=e._bounds.lines;1===O?R=(k.longest-k.lengths[0])/2:2===O&&(R=k.longest-k.lengths[0]),h.translate(-e.displayOriginX,-e.displayOriginY);for(var D=s.roundPixels,F=0;F0!=t>0,this._alpha=t}}});t.exports=r},function(t,e,i){var n=i(1),s=i(1);n=i(948),s=i(949),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){var r=e.list;if(0!==r.length){var o=e.localTransform;s?(o.loadIdentity(),o.multiply(s),o.translate(e.x,e.y),o.rotate(e.rotation),o.scale(e.scaleX,e.scaleY)):o.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);var a=-1!==e.blendMode;a||t.setBlendMode(0);for(var h=e.alpha,l=e.scrollFactorX,u=e.scrollFactorY,c=r,d=r.length,f=0;f0||e.cropHeight>0;l&&(h.flush(),t.pushScissor(e.x,e.y,e.cropWidth*e.scaleX,e.cropHeight*e.scaleY));var u=h._tempMatrix1,c=h._tempMatrix2,d=h._tempMatrix3,f=h._tempMatrix4;c.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),u.copyFrom(s.matrix),r?(u.multiplyWithOffset(r,-s.scrollX*e.scrollFactorX,-s.scrollY*e.scrollFactorY),c.e=e.x,c.f=e.y,u.multiply(c,d)):(c.e-=s.scrollX*e.scrollFactorX,c.f-=s.scrollY*e.scrollFactorY,u.multiply(c,d));var p=e.frame,g=p.glTexture,v=p.cutX,m=p.cutY,y=g.width,x=g.height,T=e._isTinted&&e.tintFill,w=n.getTintAppendFloatAlpha(e._tintTL,s.alpha*e._alphaTL),b=n.getTintAppendFloatAlpha(e._tintTR,s.alpha*e._alphaTR),E=n.getTintAppendFloatAlpha(e._tintBL,s.alpha*e._alphaBL),S=n.getTintAppendFloatAlpha(e._tintBR,s.alpha*e._alphaBR);h.setTexture2D(g,0);var A,_,C=0,M=0,O=0,P=0,R=e.letterSpacing,L=0,k=0,D=0,F=0,I=e.scrollX,B=e.scrollY,N=e.fontData,Y=N.chars,X=N.lineHeight,z=e.fontSize/N.size,U=0,G=e._align,W=0,V=0;e.getTextBounds(!1);var H=e._bounds.lines;1===G?V=(H.longest-H.lengths[0])/2:2===G&&(V=H.longest-H.lengths[0]);for(var j=s.roundPixels,q=e.displayCallback,K=e.callbackData,J=0;J0&&e.cropHeight>0&&(h.beginPath(),h.rect(0,0,e.cropWidth,e.cropHeight),h.clip());for(var N=0;N0&&(Y=Y%b-b):Y>b?Y=b:Y<0&&(Y=b+Y%b),null===_&&(_=new o(F+Math.cos(N)*B,I+Math.sin(N)*B,v),E.push(_),D+=.01);D<1+z;)w=Y*D+N,x=F+Math.cos(w)*B,T=I+Math.sin(w)*B,_.points.push(new r(x,T,v)),D+=.01;w=Y+N,x=F+Math.cos(w)*B,T=I+Math.sin(w)*B,_.points.push(new r(x,T,v));break;case n.FILL_RECT:u.setTexture2D(M),u.batchFillRect(p[++O],p[++O],p[++O],p[++O],f,c);break;case n.FILL_TRIANGLE:u.setTexture2D(M),u.batchFillTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],f,c);break;case n.STROKE_TRIANGLE:u.setTexture2D(M),u.batchStrokeTriangle(p[++O],p[++O],p[++O],p[++O],p[++O],p[++O],v,f,c);break;case n.LINE_TO:null!==_?_.points.push(new r(p[++O],p[++O],v)):(_=new o(p[++O],p[++O],v),E.push(_));break;case n.MOVE_TO:_=new o(p[++O],p[++O],v),E.push(_);break;case n.SAVE:a.push(f.copyToArray());break;case n.RESTORE:f.copyFromArray(a.pop());break;case n.TRANSLATE:F=p[++O],I=p[++O],f.translate(F,I);break;case n.SCALE:F=p[++O],I=p[++O],f.scale(F,I);break;case n.ROTATE:f.rotate(p[++O]);break;case n.SET_TEXTURE:var U=p[++O],G=p[++O];u.currentFrame=U,u.setTexture2D(U.glTexture,0),u.tintEffect=G,M=U.glTexture;break;case n.CLEAR_TEXTURE:u.currentFrame=t.blankTexture,u.tintEffect=2,M=t.blankTexture.glTexture}}}},function(t,e,i){var n=i(1),s=i(1);n=i(961),s=i(962),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(1),s=i(1);n=i(964),s=i(965),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e){t.exports=function(t,e,i,n,s){this.pipeline.batchSprite(e,n,s)}},function(t,e){t.exports=function(t,e,i,n,s){t.batchSprite(e,e.frame,n,s)}},function(t,e,i){t.exports={GravityWell:i(394),Particle:i(395),ParticleEmitter:i(396),ParticleEmitterManager:i(192),Zones:i(971)}},function(t,e,i){var n=i(0),s=i(326),r=i(82),o=i(2),a=i(58),h=new n({initialize:function(t,e,i,n){void 0===n&&(n=!1),this.propertyKey=e,this.propertyValue=i,this.defaultValue=i,this.steps=0,this.counter=0,this.start=0,this.end=0,this.ease,this.emitOnly=n,this.onEmit=this.defaultEmit,this.onUpdate=this.defaultUpdate,this.loadConfig(t)},loadConfig:function(t,e){void 0===t&&(t={}),e&&(this.propertyKey=e),this.propertyValue=o(t,this.propertyKey,this.defaultValue),this.setMethods(),this.emitOnly&&(this.onUpdate=this.defaultUpdate)},toJSON:function(){return this.propertyValue},onChange:function(t){return this.propertyValue=t,this.setMethods()},setMethods:function(){var t=this.propertyValue,e=typeof t;if("number"===e)this.onEmit=this.staticValueEmit,this.onUpdate=this.staticValueUpdate;else if(Array.isArray(t))this.onEmit=this.randomStaticValueEmit;else if("function"===e)this.emitOnly?this.onEmit=t:this.onUpdate=t;else if("object"===e&&(this.has(t,"random")||this.hasBoth(t,"start","end")||this.hasBoth(t,"min","max"))){this.start=this.has(t,"start")?t.start:t.min,this.end=this.has(t,"end")?t.end:t.max;var i=this.hasBoth(t,"min","max")||!!t.random;if(i){var n=t.random;Array.isArray(n)&&(this.start=n[0],this.end=n[1]),this.onEmit=this.randomRangedValueEmit}if(this.has(t,"steps"))this.steps=t.steps,this.counter=this.start,this.onEmit=this.steppedEmit;else{var s=this.has(t,"ease")?t.ease:"Linear";this.ease=r(s),i||(this.onEmit=this.easedValueEmit),this.onUpdate=this.easeValueUpdate}}else"object"===e&&this.hasEither(t,"onEmit","onUpdate")&&(this.has(t,"onEmit")&&(this.onEmit=t.onEmit),this.has(t,"onUpdate")&&(this.onUpdate=t.onUpdate));return this},has:function(t,e){return t.hasOwnProperty(e)},hasBoth:function(t,e,i){return t.hasOwnProperty(e)&&t.hasOwnProperty(i)},hasEither:function(t,e,i){return t.hasOwnProperty(e)||t.hasOwnProperty(i)},defaultEmit:function(t,e,i){return i},defaultUpdate:function(t,e,i,n){return n},staticValueEmit:function(){return this.propertyValue},staticValueUpdate:function(){return this.propertyValue},randomStaticValueEmit:function(){var t=Math.floor(Math.random()*this.propertyValue.length);return this.propertyValue[t]},randomRangedValueEmit:function(t,e){var i=s(this.start,this.end);return t&&t.data[e]&&(t.data[e].min=i),i},steppedEmit:function(){var t=this.counter,e=this.counter+(this.end-this.start)/this.steps;return this.counter=a(e,this.start,this.end),t},easedValueEmit:function(t,e){if(t&&t.data[e]){var i=t.data[e];i.min=this.start,i.max=this.end}return this.start},easeValueUpdate:function(t,e,i){var n=t.data[e];return(n.max-n.min)*this.ease(i)+n.min}});t.exports=h},function(t,e,i){var n=i(1),s=i(1);n=i(969),s=i(970),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){var o=e.emitters.list,a=o.length;if(0!==a){var h=this.pipeline,l=h._tempMatrix1.copyFrom(s.matrix),u=h._tempMatrix2,c=h._tempMatrix3,d=h._tempMatrix4.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY);l.multiply(d),t.setPipeline(h);var f=s.roundPixels,p=e.defaultFrame.glTexture,g=n.getTintAppendFloatAlphaAndSwap;h.setTexture2D(p,0);for(var v=0;v?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",TEXT_SET2:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET3:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",TEXT_SET4:"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",TEXT_SET5:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",TEXT_SET6:"ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",TEXT_SET7:"AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",TEXT_SET8:"0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET9:"ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",TEXT_SET10:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",TEXT_SET11:"ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"}},function(t,e,i){var n=i(6);t.exports=function(t,e){var i=e.width,s=e.height,r=Math.floor(i/2),o=Math.floor(s/2),a=n(e,"chars","");if(""!==a){var h=n(e,"image",""),l=n(e,"offset.x",0),u=n(e,"offset.y",0),c=n(e,"spacing.x",0),d=n(e,"spacing.y",0),f=n(e,"lineSpacing",0),p=n(e,"charsPerRow",null);null===p&&(p=t.sys.textures.getFrame(h).width/i)>a.length&&(p=a.length);for(var g=l,v=u,m={retroFont:!0,font:h,size:i,lineHeight:s+f,chars:{}},y=0,x=0;x0&&r.maxLines1&&(d+=f*(h-1)),{width:a,height:d,lines:h,lineWidths:o,lineSpacing:f,lineHeight:c}}},function(t,e,i){var n=i(1),s=i(1);n=i(980),s=i(981),t.exports={renderWebGL:n,renderCanvas:s}},function(t,e,i){var n=i(10);t.exports=function(t,e,i,s,r){if(0!==e.width&&0!==e.height){var o=e.frame,a=o.width,h=o.height,l=n.getTintAppendFloatAlpha;this.pipeline.batchTexture(e,o.glTexture,a,h,e.x,e.y,a/e.style.resolution,h/e.style.resolution,e.scaleX,e.scaleY,e.rotation,e.flipX,e.flipY,e.scrollFactorX,e.scrollFactorY,e.displayOriginX,e.displayOriginY,0,0,a,h,l(e._tintTL,s.alpha*e._alphaTL),l(e._tintTR,s.alpha*e._alphaTR),l(e._tintBL,s.alpha*e._alphaBL),l(e._tintBR,s.alpha*e._alphaBR),e._isTinted&&e.tintFill,0,0,s,r)}}},function(t,e){t.exports=function(t,e,i,n,s){0!==e.width&&0!==e.height&&t.batchSprite(e,e.frame,n,s)}},function(t,e,i){var n=i(0),s=i(15),r=i(6),o=i(983),a={fontFamily:["fontFamily","Courier"],fontSize:["fontSize","16px"],fontStyle:["fontStyle",""],backgroundColor:["backgroundColor",null],color:["color","#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",!1],shadowFill:["shadow.fill",!1],align:["align","left"],maxLines:["maxLines",0],fixedWidth:["fixedWidth",0],fixedHeight:["fixedHeight",0],resolution:["resolution",0],rtl:["rtl",!1],testString:["testString","|MÉqgy"],baselineX:["baselineX",1.2],baselineY:["baselineY",1.4],wordWrapWidth:["wordWrap.width",null],wordWrapCallback:["wordWrap.callback",null],wordWrapCallbackScope:["wordWrap.callbackScope",null],wordWrapUseAdvanced:["wordWrap.useAdvancedWrap",!1]},h=new n({initialize:function(t,e){this.parent=t,this.fontFamily,this.fontSize,this.fontStyle,this.backgroundColor,this.color,this.stroke,this.strokeThickness,this.shadowOffsetX,this.shadowOffsetY,this.shadowColor,this.shadowBlur,this.shadowStroke,this.shadowFill,this.align,this.maxLines,this.fixedWidth,this.fixedHeight,this.resolution,this.rtl,this.testString,this.baselineX,this.baselineY,this._font,this.setStyle(e,!1,!0);var i=r(e,"metrics",!1);this.metrics=i?{ascent:r(i,"ascent",0),descent:r(i,"descent",0),fontSize:r(i,"fontSize",0)}:o(this)},setStyle:function(t,e,i){for(var n in void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px"),a){var o=i?a[n][1]:this[n];this[n]="wordWrapCallback"===n||"wordWrapCallbackScope"===n?r(t,a[n][0],o):s(t,a[n][0],o)}var h=r(t,"font",null);null!==h&&this.setFont(h,!1),this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim();var l=r(t,"fill",null);return null!==l&&(this.color=l),e?this.update(!0):this.parent},syncFont:function(t,e){e.font=this._font},syncStyle:function(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"},syncShadow:function(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)},update:function(t){return t&&(this._font=[this.fontStyle,this.fontSize,this.fontFamily].join(" ").trim(),this.metrics=o(this)),this.parent.updateText()},setFont:function(t,e){void 0===e&&(e=!0);var i=t,n="",s="";if("string"!=typeof t)i=r(t,"fontFamily","Courier"),n=r(t,"fontSize","16px"),s=r(t,"fontStyle","");else{var o=t.split(" "),a=0;s=o.length>2?o[a++]:"",n=o[a++]||"16px",i=o[a++]||"Courier"}return i===this.fontFamily&&n===this.fontSize&&s===this.fontStyle||(this.fontFamily=i,this.fontSize=n,this.fontStyle=s,e&&this.update(!0)),this.parent},setFontFamily:function(t){return this.fontFamily!==t&&(this.fontFamily=t,this.update(!0)),this.parent},setFontStyle:function(t){return this.fontStyle!==t&&(this.fontStyle=t,this.update(!0)),this.parent},setFontSize:function(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize!==t&&(this.fontSize=t,this.update(!0)),this.parent},setTestString:function(t){return this.testString=t,this.update(!0)},setFixedSize:function(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(!1)},setBackgroundColor:function(t){return this.backgroundColor=t,this.update(!1)},setFill:function(t){return this.color=t,this.update(!1)},setColor:function(t){return this.color=t,this.update(!1)},setResolution:function(t){return this.resolution=t,this.update(!1)},setStroke:function(t,e){return void 0===e&&(e=this.strokeThickness),void 0===t&&0!==this.strokeThickness?(this.strokeThickness=0,this.update(!0)):this.stroke===t&&this.strokeThickness===e||(this.stroke=t,this.strokeThickness=e,this.update(!0)),this.parent},setShadow:function(t,e,i,n,s,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===n&&(n=0),void 0===s&&(s=!1),void 0===r&&(r=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=i,this.shadowBlur=n,this.shadowStroke=s,this.shadowFill=r,this.update(!1)},setShadowOffset:function(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)},setShadowColor:function(t){return void 0===t&&(t="#000"),this.shadowColor=t,this.update(!1)},setShadowBlur:function(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)},setShadowStroke:function(t){return this.shadowStroke=t,this.update(!1)},setShadowFill:function(t){return this.shadowFill=t,this.update(!1)},setWordWrapWidth:function(t,e){return void 0===e&&(e=!1),this.wordWrapWidth=t,this.wordWrapUseAdvanced=e,this.update(!1)},setWordWrapCallback:function(t,e){return void 0===e&&(e=null),this.wordWrapCallback=t,this.wordWrapCallbackScope=e,this.update(!1)},setAlign:function(t){return void 0===t&&(t="left"),this.align=t,this.update(!1)},setMaxLines:function(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)},getTextMetrics:function(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}},toJSON:function(){var t={};for(var e in a)t[e]=this[e];return t.metrics=this.getTextMetrics(),t},destroy:function(){this.parent=void 0}});t.exports=h},function(t,e,i){var n=i(26);t.exports=function(t){var e=n.create(this),i=e.getContext("2d");t.syncFont(e,i);var s=Math.ceil(i.measureText(t.testString).width*t.baselineX),r=s,o=2*r;r=r*t.baselineY|0,e.width=s,e.height=o,i.fillStyle="#f00",i.fillRect(0,0,s,o),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,r);var a={ascent:0,descent:0,fontSize:0};if(!i.getImageData(0,0,s,o))return a.ascent=r,a.descent=r+6,a.fontSize=a.ascent+a.descent,n.remove(e),a;var h,l,u=i.getImageData(0,0,s,o).data,c=u.length,d=4*s,f=0,p=!1;for(h=0;hr;h--){for(l=0;l0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.fillColor,e.fillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0)for(u=o.fillTint,c=n.getTintAppendFloatAlphaAndSwap(e.altFillColor,e.altFillAlpha*d),u.TL=c,u.TR=c,u.BL=c,u.BR=c,C=0;C0){var R=o.strokeTint,L=n.getTintAppendFloatAlphaAndSwap(e.outlineFillColor,e.outlineFillAlpha*d);for(R.TL=L,R.TR=L,R.BL=L,R.BR=L,_=1;_0)for(n(h,e),_=0;_0)for(n(h,e,e.altFillColor,e.altFillAlpha*c),_=0;_0){for(s(h,e,e.outlineFillColor,e.outlineFillAlpha*c),A=1;Ao.vertexCapacity&&o.flush(),o.setTexture2D(u,0);for(var m=o.vertexViewF32,y=o.vertexViewU32,x=o.vertexCount*o.vertexComponentCount-1,T=0,w=e.tintFill,b=0;b0?Math.PI*t.radius*t.radius:0}},function(t,e,i){var n=i(65);t.exports=function(t){return new n(t.x,t.y,t.radius)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(55);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.radius)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.radius===e.radius}},function(t,e,i){var n=i(11);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.diameter,e.height=t.diameter,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(95);n.Area=i(1089),n.Circumference=i(392),n.CircumferencePoint=i(191),n.Clone=i(1090),n.Contains=i(96),n.ContainsPoint=i(1091),n.ContainsRect=i(1092),n.CopyFrom=i(1093),n.Equals=i(1094),n.GetBounds=i(1095),n.GetPoint=i(390),n.GetPoints=i(391),n.Offset=i(1096),n.OffsetPoint=i(1097),n.Random=i(154),t.exports=n},function(t,e){t.exports=function(t){return t.isEmpty()?0:t.getMajorRadius()*t.getMinorRadius()*Math.PI}},function(t,e,i){var n=i(95);t.exports=function(t){return new n(t.x,t.y,t.width,t.height)}},function(t,e,i){var n=i(96);t.exports=function(t,e){return n(t,e.x,e.y)}},function(t,e,i){var n=i(96);t.exports=function(t,e){return n(t,e.x,e.y)&&n(t,e.right,e.y)&&n(t,e.x,e.bottom)&&n(t,e.right,e.bottom)}},function(t,e){t.exports=function(t,e){return e.setTo(t.x,t.y,t.width,t.height)}},function(t,e){t.exports=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}},function(t,e,i){var n=i(11);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.left,e.y=t.top,e.width=t.width,e.height=t.height,e}},function(t,e){t.exports=function(t,e,i){return t.x+=e,t.y+=i,t}},function(t,e){t.exports=function(t,e){return t.x+=e.x,t.y+=e.y,t}},function(t,e,i){var n=i(4),s=i(202);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r,o,a,h,l=t.x,u=t.y,c=t.radius,d=e.x,f=e.y,p=e.radius;if(u===f)0==(a=(o=-2*f)*o-4*(r=1)*(d*d+(h=(p*p-c*c-d*d+l*l)/(2*(l-d)))*h-2*d*h+f*f-p*p))?i.push(new n(h,-o/(2*r))):a>0&&(i.push(new n(h,(-o+Math.sqrt(a))/(2*r))),i.push(new n(h,(-o-Math.sqrt(a))/(2*r))));else{var g=(l-d)/(u-f),v=(p*p-c*c-d*d+l*l-f*f+u*u)/(2*(u-f));0==(a=(o=2*u*g-2*v*g-2*l)*o-4*(r=g*g+1)*(l*l+u*u+v*v-c*c-2*u*v))?(h=-o/(2*r),i.push(new n(h,v-h*g))):a>0&&(h=(-o+Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)),h=(-o-Math.sqrt(a))/(2*r),i.push(new n(h,v-h*g)))}}return i}},function(t,e,i){var n=i(204),s=i(203);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC(),h=e.getLineD();n(r,t,i),n(o,t,i),n(a,t,i),n(h,t,i)}return i}},function(t,e,i){var n=i(11),s=i(131);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i}},function(t,e,i){var n=i(206),s=i(131);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC(),h=t.getLineD();n(r,e,i),n(o,e,i),n(a,e,i),n(h,e,i)}return i}},function(t,e,i){var n=i(425),s=i(206);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(r,t,i),s(o,t,i),s(a,t,i)}return i}},function(t,e,i){var n=i(204),s=i(427);t.exports=function(t,e,i){if(void 0===i&&(i=[]),s(t,e)){var r=t.getLineA(),o=t.getLineB(),a=t.getLineC();n(r,e,i),n(o,e,i),n(a,e,i)}return i}},function(t,e,i){var n=i(430),s=i(428);t.exports=function(t,e,i){if(void 0===i&&(i=[]),n(t,e)){var r=e.getLineA(),o=e.getLineB(),a=e.getLineC();s(t,r,i),s(t,o,i),s(t,a,i)}return i}},function(t,e,i){var n=i(432);t.exports=function(t,e){if(!n(t,e))return!1;var i=Math.min(e.x1,e.x2),s=Math.max(e.x1,e.x2),r=Math.min(e.y1,e.y2),o=Math.max(e.y1,e.y2);return t.x>=i&&t.x<=s&&t.y>=r&&t.y<=o}},function(t,e){t.exports=function(t,e,i,n,s,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||si&&(i=h.x),h.xr&&(r=h.y),h.yn(e)?t.setSize(e.height*i,e.height):t.setSize(e.width,e.width/i),t.setPosition(e.centerX-t.width/2,e.centerY-t.height/2)}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t}},function(t,e){t.exports=function(t){return t.x=Math.floor(t.x),t.y=Math.floor(t.y),t.width=Math.floor(t.width),t.height=Math.floor(t.height),t}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.centerX,e.y=t.centerY,e}},function(t,e,i){var n=i(4);t.exports=function(t,e){return void 0===e&&(e=new n),e.x=t.width,e.y=t.height,e}},function(t,e,i){var n=i(165);t.exports=function(t,e,i){var s=t.centerX,r=t.centerY;return t.setSize(t.width+2*e,t.height+2*i),n(t,s,r)}},function(t,e,i){var n=i(11),s=i(131);t.exports=function(t,e,i){return void 0===i&&(i=new n),s(t,e)?(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y):i.setEmpty(),i}},function(t,e){t.exports=function(t,e){for(var i=t.x,n=t.right,s=t.y,r=t.bottom,o=0;oe.x&&t.ye.y}},function(t,e,i){var n=i(4),s=i(35);t.exports=function(t,e,i){void 0===i&&(i=new n),e=s(e);var r=Math.sin(e),o=Math.cos(e),a=o>0?t.width/2:t.width/-2,h=r>0?t.height/2:t.height/-2;return Math.abs(a*r)-1&&(s.splice(a,1),this.clear(o,!0))}t.length=0,this._pendingRemoval.length=0,this._list=s.concat(e.splice(0))}},isActive:function(){return this.enabled&&this.scene.sys.isActive()},updatePoll:function(t,e){if(!this.isActive())return!1;if(this.pluginEvents.emit(d.UPDATE,t,e),this._updatedThisFrame)return this._updatedThisFrame=!1,!1;var i,n=this.manager,s=n.pointers,r=n.pointersTotal;for(i=0;i0){if(this._pollTimer-=e,!(this._pollTimer<0))return!1;this._pollTimer=this.pollRate}var a=!1;for(i=0;i0&&(a=!0)}return a},update:function(t,e){if(!this.isActive())return!1;for(var i=e.length,n=!1,s=0;s0&&(n=!0)}return this._updatedThisFrame=!0,n},clear:function(t,e){void 0===e&&(e=!1);var i=t.input;if(i){e||this.queueForRemoval(t),i.gameObject=void 0,i.target=void 0,i.hitArea=void 0,i.hitAreaCallback=void 0,i.callbackContext=void 0,this.manager.resetCursor(i),t.input=null;var n=this._draggable.indexOf(t);return n>-1&&this._draggable.splice(n,1),(n=this._drag[0].indexOf(t))>-1&&this._drag[0].splice(n,1),(n=this._over[0].indexOf(t))>-1&&this._over[0].splice(n,1),t}},disable:function(t){t.input.enabled=!1},enable:function(t,e,i,n){return void 0===n&&(n=!1),t.input?t.input.enabled=!0:this.setHitArea(t,e,i),t.input&&n&&!t.input.dropZone&&(t.input.dropZone=n),this},hitTestPointer:function(t){for(var e=this.cameras.getCamerasBelowPointer(t),i=0;i0)return t.camera=n,s}return t.camera=e[0],[]},processDownEvents:function(t){var e=0,i=this._temp,n=this._eventData,s=this._eventContainer;n.cancelled=!1;for(var r=!1,o=0;o0&&l(t.x,t.y,t.downX,t.downY)>=s?i=!0:n>0&&e>=t.downTime+n&&(i=!0),i)return this.setDragState(t,3),this.processDragStartList(t)},processDragStartList:function(t){if(3!==this.getDragState(t))return 0;for(var e=this._drag[t.id],i=0;i1&&(this.sortGameObjects(i),this.topOnly&&i.splice(1)),this._drag[t.id]=i,0===this.dragDistanceThreshold&&0===this.dragTimeThreshold?(this.setDragState(t,3),this.processDragStartList(t)):(this.setDragState(t,2),0))},processDragMoveEvent:function(t){if(2===this.getDragState(t)&&this.processDragThresholdEvent(t,this.manager.game.loop.now),4!==this.getDragState(t))return 0;for(var e=this._tempZones,i=this._drag[t.id],n=0;n0?(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):(o.emit(d.GAMEOBJECT_DRAG_LEAVE,t,h),this.emit(d.DRAG_LEAVE,t,o,h),e[0]?(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h)):a.target=null)}else!h&&e[0]&&(a.target=e[0],h=a.target,o.emit(d.GAMEOBJECT_DRAG_ENTER,t,h),this.emit(d.DRAG_ENTER,t,o,h));if(o.parentContainer){var u=t.x-a.dragStartXGlobal,c=t.y-a.dragStartYGlobal,f=o.getParentRotation(),p=u*Math.cos(f)+c*Math.sin(f),g=c*Math.cos(f)-u*Math.sin(f);p*=1/o.parentContainer.scaleX,g*=1/o.parentContainer.scaleY,s=p+a.dragStartX,r=g+a.dragStartY}else s=t.x-a.dragX,r=t.y-a.dragY;o.emit(d.GAMEOBJECT_DRAG,t,s,r),this.emit(d.DRAG,t,o,s,r)}return i.length},processDragUpEvent:function(t){for(var e=this._drag[t.id],i=0;i0){var r=this.manager,o=this._eventData,a=this._eventContainer;o.cancelled=!1;for(var h=!1,l=0;l0){var s=this.manager,r=this._eventData,o=this._eventContainer;r.cancelled=!1;var a=!1;this.sortGameObjects(e);for(var h=0;h0){for(this.sortGameObjects(s),e=0;e0){for(this.sortGameObjects(r),e=0;e-1&&this._draggable.splice(s,1)}return this},makePixelPerfect:function(t){void 0===t&&(t=1);var e=this.systems.textures;return h(e,t)},setHitArea:function(t,e,i){if(void 0===e)return this.setHitAreaFromTexture(t);Array.isArray(t)||(t=[t]);var n=!1,s=!1,r=!1,o=!1,h=!1,l=!0;if(m(e)){var u=e;e=p(u,"hitArea",null),i=p(u,"hitAreaCallback",null),n=p(u,"draggable",!1),s=p(u,"dropZone",!1),r=p(u,"cursor",!1),o=p(u,"useHandCursor",!1),h=p(u,"pixelPerfect",!1);var c=p(u,"alphaTolerance",1);h&&(e={},i=this.makePixelPerfect(c)),e&&i||(this.setHitAreaFromTexture(t),l=!1)}else"function"!=typeof e||i||(i=e,e={});for(var d=0;d=e}}},function(t,e,i){t.exports={Events:i(133),KeyboardManager:i(360),KeyboardPlugin:i(1210),Key:i(445),KeyCodes:i(122),KeyCombo:i(446),JustDown:i(1215),JustUp:i(1216),DownDuration:i(1217),UpDuration:i(1218)}},function(t,e){t.exports="keydown"},function(t,e){t.exports="keyup"},function(t,e){t.exports="keycombomatch"},function(t,e){t.exports="down"},function(t,e){t.exports="keydown-"},function(t,e){t.exports="keyup-"},function(t,e){t.exports="up"},function(t,e,i){var n=i(0),s=i(9),r=i(133),o=i(18),a=i(6),h=i(54),l=i(132),u=i(445),c=i(122),d=i(446),f=i(1214),p=i(93),g=new n({Extends:s,initialize:function(t){s.call(this),this.game=t.systems.game,this.scene=t.scene,this.settings=this.scene.sys.settings,this.sceneInputPlugin=t,this.manager=t.manager.keyboard,this.enabled=!0,this.keys=[],this.combos=[],t.pluginEvents.once(h.BOOT,this.boot,this),t.pluginEvents.on(h.START,this.start,this)},boot:function(){var t=this.settings.input;this.enabled=a(t,"keyboard",!0);var e=a(t,"keyboard.capture",null);e&&this.addCaptures(e),this.sceneInputPlugin.pluginEvents.once(h.DESTROY,this.destroy,this)},start:function(){this.sceneInputPlugin.manager.useQueue?this.sceneInputPlugin.pluginEvents.on(h.UPDATE,this.update,this):this.sceneInputPlugin.manager.events.on(h.MANAGER_PROCESS,this.update,this),this.sceneInputPlugin.pluginEvents.once(h.SHUTDOWN,this.shutdown,this),this.game.events.on(o.BLUR,this.resetKeys,this)},isActive:function(){return this.enabled&&this.scene.sys.isActive()},addCapture:function(t){return this.manager.addCapture(t),this},removeCapture:function(t){return this.manager.removeCapture(t),this},getCaptures:function(){return this.manager.captures},enableGlobalCapture:function(){return this.manager.preventDefault=!0,this},disableGlobalCapture:function(){return this.manager.preventDefault=!1,this},clearCaptures:function(){return this.manager.clearCaptures(),this},createCursorKeys:function(){return this.addKeys({up:c.UP,down:c.DOWN,left:c.LEFT,right:c.RIGHT,space:c.SPACE,shift:c.SHIFT})},addKeys:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1);var n={};if("string"==typeof t){t=t.split(",");for(var s=0;s-1?n[s]=t:n[t.keyCode]=t,e&&this.addCapture(t.keyCode),t.setEmitOnRepeat(i),t}return"string"==typeof t&&(t=c[t.toUpperCase()]),n[t]||(n[t]=new u(this,t),e&&this.addCapture(t),n[t].setEmitOnRepeat(i)),n[t]},removeKey:function(t,e){void 0===e&&(e=!1);var i,n=this.keys;if(t instanceof u){var s=n.indexOf(t);s>-1&&(i=this.keys[s],this.keys[s]=void 0)}else"string"==typeof t&&(t=c[t.toUpperCase()]);return n[t]&&(i=n[t],n[t]=void 0),i&&(i.plugin=null,e&&i.destroy()),this},createCombo:function(t,e){return new d(this,t,e)},checkDown:function(t,e){if(this.enabled&&t.isDown){var i=p(this.time-t.timeDown,e);if(i>t._tick)return t._tick=i,!0}return!1},update:function(){var t=this.manager.queue,e=t.length;if(this.isActive()&&0!==e)for(var i=this.keys,n=0;n0&&e.maxKeyDelay>0){var r=e.timeLastMatched+e.maxKeyDelay;t.timeStamp<=r&&(s=!0,i=n(t,e))}else s=!0,i=n(t,e);return!s&&e.resetOnWrongKey&&(e.index=0,e.current=e.keyCodes[0]),i&&(e.timeLastMatched=t.timeStamp,e.matched=!0,e.timeMatched=t.timeStamp),i}},function(t,e){t.exports=function(t,e){return e.timeLastMatched=t.timeStamp,e.index++,e.index===e.size||(e.current=e.keyCodes[e.index],!1)}},function(t,e){t.exports=function(t){return t.current=t.keyCodes[0],t.index=0,t.timeLastMatched=0,t.matched=!1,t.timeMatched=0,t}},function(t,e,i){var n=i(122),s={};for(var r in n)s[n[r]]=r;t.exports=s},function(t,e){t.exports=function(t){return!!t._justDown&&(t._justDown=!1,!0)}},function(t,e){t.exports=function(t){return!!t._justUp&&(t._justUp=!1,!0)}},function(t,e){t.exports=function(t,e){void 0===e&&(e=50);var i=t.plugin.game.loop.time-t.timeDown;return t.isDown&&i'),i.push(''),i.push(''),i.push(this.xhrLoader.responseText),i.push(""),i.push(""),i.push("");var n=[i.join("\n")],o=this;try{var a=new window.Blob(n,{type:"image/svg+xml;charset=utf-8"})}catch(t){return o.state=s.FILE_ERRORED,void o.onProcessComplete()}this.data=new Image,this.data.crossOrigin=this.crossOrigin,this.data.onload=function(){r.revokeObjectURL(o.data),o.onProcessComplete()},this.data.onerror=function(){r.revokeObjectURL(o.data),o.onProcessError()},r.createObjectURL(this.data,a,"image/svg+xml")},addToCache:function(){var t=this.cache.addImage(this.key,this.data);this.pendingDestroy(t)}});o.register("htmlTexture",function(t,e,i,n,s){if(Array.isArray(t))for(var r=0;r0},isLoading:function(){return this.state===s.LOADER_LOADING||this.state===s.LOADER_PROCESSING},isReady:function(){return this.state===s.LOADER_IDLE||this.state===s.LOADER_COMPLETE},start:function(){this.isReady()&&(this.progress=0,this.totalFailed=0,this.totalComplete=0,this.totalToLoad=this.list.size,this.emit(a.START,this),0===this.list.size?this.loadComplete():(this.state=s.LOADER_LOADING,this.inflight.clear(),this.queue.clear(),this.updateProgress(),this.checkLoadQueue(),this.systems.events.on(c.UPDATE,this.update,this)))},updateProgress:function(){this.progress=1-(this.list.size+this.inflight.size)/this.totalToLoad,this.emit(a.PROGRESS,this.progress)},update:function(){this.state===s.LOADER_LOADING&&this.list.size>0&&this.inflight.sizei&&(n=l,i=c)}}return n},moveTo:function(t,e,i,n,s){void 0===n&&(n=60),void 0===s&&(s=0);var o=Math.atan2(i-t.y,e-t.x);return s>0&&(n=r(t.x,t.y,e,i)/(s/1e3)),t.body.velocity.setToPolar(o,n),o},moveToObject:function(t,e,i,n){return this.moveTo(t,e.x,e.y,i,n)},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(s(t),e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),void 0===i&&(i=new p),i.setToPolar(t,e)},overlapRect:function(t,e,i,n,s,r){return c(this.world,t,e,i,n,s,r)},overlapCirc:function(t,e,i,n,s){return u(this.world,t,e,i,n,s)},shutdown:function(){if(this.world){var t=this.systems.events;t.off(f.UPDATE,this.world.update,this.world),t.off(f.POST_UPDATE,this.world.postUpdate,this.world),t.off(f.SHUTDOWN,this.shutdown,this),this.add.destroy(),this.world.destroy(),this.add=null,this.world=null}},destroy:function(){this.shutdown(),this.scene.sys.events.off(f.START,this.start,this),this.scene=null,this.systems=null}});d.register("ArcadePhysics",v,"arcadePhysics"),t.exports=v},function(t,e){t.exports={setAcceleration:function(t,e){return this.body.acceleration.set(t,e),this},setAccelerationX:function(t){return this.body.acceleration.x=t,this},setAccelerationY:function(t){return this.body.acceleration.y=t,this}}},function(t,e){t.exports={setAngularVelocity:function(t){return this.body.angularVelocity=t,this},setAngularAcceleration:function(t){return this.body.angularAcceleration=t,this},setAngularDrag:function(t){return this.body.angularDrag=t,this}}},function(t,e){t.exports={setBounce:function(t,e){return this.body.bounce.set(t,e),this},setBounceX:function(t){return this.body.bounce.x=t,this},setBounceY:function(t){return this.body.bounce.y=t,this},setCollideWorldBounds:function(t,e,i){return this.body.setCollideWorldBounds(t,e,i),this}}},function(t,e){t.exports={setDebug:function(t,e,i){return this.debugShowBody=t,this.debugShowVelocity=e,this.debugBodyColor=i,this},setDebugBodyColor:function(t){return this.body.debugBodyColor=t,this},debugShowBody:{get:function(){return this.body.debugShowBody},set:function(t){this.body.debugShowBody=t}},debugShowVelocity:{get:function(){return this.body.debugShowVelocity},set:function(t){this.body.debugShowVelocity=t}},debugBodyColor:{get:function(){return this.body.debugBodyColor},set:function(t){this.body.debugBodyColor=t}}}},function(t,e){t.exports={setDrag:function(t,e){return this.body.drag.set(t,e),this},setDragX:function(t){return this.body.drag.x=t,this},setDragY:function(t){return this.body.drag.y=t,this},setDamping:function(t){return this.body.useDamping=t,this}}},function(t,e){var i={enableBody:function(t,e,i,n,s){return t&&this.body.reset(e,i),n&&(this.body.gameObject.active=!0),s&&(this.body.gameObject.visible=!0),this.body.enable=!0,this},disableBody:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=!1),this.body.stop(),this.body.enable=!1,t&&(this.body.gameObject.active=!1),e&&(this.body.gameObject.visible=!1),this},refreshBody:function(){return this.body.updateFromGameObject(),this}};t.exports=i},function(t,e){t.exports={setFriction:function(t,e){return this.body.friction.set(t,e),this},setFrictionX:function(t){return this.body.friction.x=t,this},setFrictionY:function(t){return this.body.friction.y=t,this}}},function(t,e){t.exports={setGravity:function(t,e){return this.body.gravity.set(t,e),this},setGravityX:function(t){return this.body.gravity.x=t,this},setGravityY:function(t){return this.body.gravity.y=t,this}}},function(t,e){var i={setImmovable:function(t){return void 0===t&&(t=!0),this.body.immovable=t,this}};t.exports=i},function(t,e){t.exports={setMass:function(t){return this.body.mass=t,this}}},function(t,e){t.exports={setOffset:function(t,e){return this.body.setOffset(t,e),this},setSize:function(t,e,i){return this.body.setSize(t,e,i),this},setCircle:function(t,e,i){return this.body.setCircle(t,e,i),this}}},function(t,e){t.exports={setVelocity:function(t,e){return this.body.setVelocity(t,e),this},setVelocityX:function(t){return this.body.setVelocityX(t),this},setVelocityY:function(t){return this.body.setVelocityY(t),this},setMaxVelocity:function(t,e){return this.body.maxVelocity.set(t,e),this}}},function(t,e,i){var n=i(456),s=i(65),r=i(202),o=i(203);t.exports=function(t,e,i,a,h,l){var u=n(t,e-a,i-a,2*a,2*a,h,l);if(0===u.length)return u;for(var c=new s(e,i,a),d=new s,f=[],p=0;pe.deltaAbsY()?y=-1:e.deltaAbsX()0&&u&&t.checkCollision.right&&h&&t.right>i&&(a=t.right-i)>r&&(a=0),0!==a&&(t.customSeparateX?t.overlapX=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.left=!0):e>0&&(t.blocked.none=!1,t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x}},function(t,e,i){var n=i(1275);t.exports=function(t,e,i,s,r,o){var a=0,h=e.faceTop,l=e.faceBottom,u=e.collideUp,c=e.collideDown;return o||(h=!0,l=!0,u=!0,c=!0),t.deltaY()<0&&c&&t.checkCollision.up?l&&t.y0&&u&&t.checkCollision.down&&h&&t.bottom>i&&(a=t.bottom-i)>r&&(a=0),0!==a&&(t.customSeparateY?t.overlapY=a:n(t,a)),a}},function(t,e){t.exports=function(t,e){e<0?(t.blocked.none=!1,t.blocked.up=!0):e>0&&(t.blocked.none=!1,t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},function(t,e,i){var n=i(460);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.x,a=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=r,e.velocity.x=o-a*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=r,t.velocity.x=a-o*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{r*=.5,t.x-=r,e.x+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.x=u+h*t.bounce.x,e.velocity.x=u+l*e.bounce.x}return!0}},function(t,e,i){var n=i(461);t.exports=function(t,e,i,s){var r=n(t,e,i,s);if(i||0===r||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==r||t.embedded&&e.embedded;var o=t.velocity.y,a=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=r,e.velocity.y=o-a*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=r,t.velocity.y=a-o*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{r*=.5,t.y-=r,e.y+=r;var h=Math.sqrt(a*a*e.mass/t.mass)*(a>0?1:-1),l=Math.sqrt(o*o*t.mass/e.mass)*(o>0?1:-1),u=.5*(h+l);h-=u,l-=u,t.velocity.y=u+h*t.bounce.y,e.velocity.y=u+l*e.bounce.y}return!0}},function(t,e,i){t.exports={COLLIDE:i(1392),PAUSE:i(1393),RESUME:i(1394)}},function(t,e,i){t.exports={Acceleration:i(1396),BodyScale:i(1397),BodyType:i(1398),Bounce:i(1399),CheckAgainst:i(1400),Collides:i(1401),Debug:i(1402),Friction:i(1403),Gravity:i(1404),Offset:i(1405),SetGameObject:i(1406),Velocity:i(1407)}},function(t,e,i){var n={};t.exports=n;var s=i(145),r=i(216),o=i(37),a=i(62),h=i(109);n.stack=function(t,e,i,n,r,o,h){for(var l,u=s.create({label:"Stack"}),c=t,d=e,f=0,p=0;pg&&(g=y),a.translate(m,{x:.5*x,y:.5*y}),c=m.bounds.max.x+r,s.addBody(u,m),l=m,f+=1}else c+=r}d+=g+o,c=t}return u},n.chain=function(t,e,i,n,a,h){for(var l=t.bodies,u=1;u0)for(l=0;l0&&(d=f[l-1+(h-1)*e],s.addConstraint(t,r.create(o.extend({bodyA:d,bodyB:c},a)))),n&&ld||o<(l=d-l)||o>i-1-l))return 1===c&&a.translate(u,{x:(o+(i%2==1?1:-1))*f,y:0}),h(t+(u?o*f:0)+o*r,n,o,l,u,c)})},n.newtonsCradle=function(t,e,i,n,o){for(var a=s.create({label:"Newtons Cradle"}),l=0;l1;if(!d||t!=d.x||e!=d.y){d&&n?(f=d.x,p=d.y):(f=0,p=0);var s={x:f+t,y:p+e};!n&&d||(d=s),g.push(s),m=f+t,y=p+e}},T=function(t){var e=t.pathSegTypeAsLetter.toUpperCase();if("Z"!==e){switch(e){case"M":case"L":case"T":case"C":case"S":case"Q":m=t.x,y=t.y;break;case"H":m=t.x;break;case"V":y=t.y}x(m,y,t.pathSegType)}};for(n._svgPathToAbsolute(t),o=t.getTotalLength(),l=[],i=0;i0?this.setFromTileCollision(i):this.setFromTileRectangle(i)}},setFromTileRectangle:function(t){void 0===t&&(t={}),h(t,"isStatic")||(t.isStatic=!0),h(t,"addToWorld")||(t.addToWorld=!0);var e=this.tile.getBounds(),i=e.x+e.width/2,s=e.y+e.height/2,r=n.rectangle(i,s,e.width,e.height,t);return this.setBody(r,t.addToWorld),this},setFromTileCollision:function(t){void 0===t&&(t={}),h(t,"isStatic")||(t.isStatic=!0),h(t,"addToWorld")||(t.addToWorld=!0);for(var e=this.tile.tilemapLayer.scaleX,i=this.tile.tilemapLayer.scaleY,r=this.tile.getLeft(),o=this.tile.getTop(),u=this.tile.getCollisionGroup(),c=a(u,"objects",[]),d=[],f=0;f1&&(t.parts=d,this.setBody(s.create(t),t.addToWorld)),this},setBody:function(t,e){return void 0===e&&(e=!0),this.body&&this.removeBody(),this.body=t,this.body.gameObject=this,e&&this.world.add(this.body),this},removeBody:function(){return this.body&&(this.world.remove(this.body),this.body.gameObject=void 0,this.body=void 0),this},destroy:function(){this.removeBody(),this.tile.physics.matterBody=void 0}});t.exports=u},function(t,e,i){var n=i(1383);n.Body=i(62),n.Composite=i(145),n.World=i(1288),n.Detector=i(509),n.Grid=i(1289),n.Pairs=i(1290),n.Pair=i(467),n.Query=i(1384),n.Resolver=i(1291),n.SAT=i(510),n.Constraint=i(216),n.Common=i(37),n.Engine=i(1385),n.Events=i(237),n.Sleeping=i(236),n.Plugin=i(1287),n.Bodies=i(109),n.Composites=i(1280),n.Axes=i(507),n.Bounds=i(102),n.Svg=i(1281),n.Vector=i(101),n.Vertices=i(86),n.World.add=n.Composite.add,n.World.remove=n.Composite.remove,n.World.addComposite=n.Composite.addComposite,n.World.addBody=n.Composite.addBody,n.World.addConstraint=n.Composite.addConstraint,n.World.clear=n.Composite.clear,t.exports=n},function(t,e,i){var n={};t.exports=n;var s=i(37);n._registry={},n.register=function(t){if(n.isPlugin(t)||s.warn("Plugin.register:",n.toString(t),"does not implement all required fields."),t.name in n._registry){var e=n._registry[t.name],i=n.versionParse(t.version).number,r=n.versionParse(e.version).number;i>r?(s.warn("Plugin.register:",n.toString(e),"was upgraded to",n.toString(t)),n._registry[t.name]=t):i-1},n.isFor=function(t,e){var i=t.for&&n.dependencyParse(t.for);return!t.for||e.name===i.name&&n.versionSatisfies(e.version,i.range)},n.use=function(t,e){if(t.uses=(t.uses||[]).concat(e||[]),0!==t.uses.length){for(var i=n.dependencies(t),r=s.topologicalSort(i),o=[],a=0;a0&&!h.silent&&s.info(o.join(" "))}else s.warn("Plugin.use:",n.toString(t),"does not specify any dependencies to install.")},n.dependencies=function(t,e){var i=n.dependencyParse(t),r=i.name;if(!(r in(e=e||{}))){t=n.resolve(t)||t,e[r]=s.map(t.uses||[],function(e){n.isPlugin(e)&&n.register(e);var r=n.dependencyParse(e),o=n.resolve(e);return o&&!n.versionSatisfies(o.version,r.range)?(s.warn("Plugin.dependencies:",n.toString(o),"does not satisfy",n.toString(r),"used by",n.toString(i)+"."),o._warned=!0,t._warned=!0):o||(s.warn("Plugin.dependencies:",n.toString(e),"used by",n.toString(i),"could not be resolved."),t._warned=!0),r.name});for(var o=0;o=s[2];if("^"===i.operator)return s[0]>0?o[0]===s[0]&&r.number>=i.number:s[1]>0?o[1]===s[1]&&o[2]>=s[2]:o[2]===s[2]}return t===e||"*"===t}},function(t,e,i){var n={};t.exports=n;var s=i(145),r=(i(216),i(37));n.create=function(t){var e=s.create(),i={label:"World",gravity:{x:0,y:1,scale:.001},bounds:{min:{x:-1/0,y:-1/0},max:{x:1/0,y:1/0}}};return r.extend(e,i,t)}},function(t,e,i){var n={};t.exports=n;var s=i(467),r=i(509),o=i(37);n.create=function(t){var e={controller:n,detector:r.collisions,buckets:{},pairs:{},pairsList:[],bucketWidth:48,bucketHeight:48};return o.extend(e,t)},n.update=function(t,e,i,s){var r,o,a,h,l,u=i.world,c=t.buckets,d=!1,f=i.metrics;for(f.broadphaseTests=0,r=0;ru.bounds.max.x||p.bounds.max.yu.bounds.max.y)){var g=n._getRegion(t,p);if(!p.region||g.id!==p.region.id||s){f.broadphaseTests+=1,p.region&&!s||(p.region=g);var v=n._regionUnion(g,p.region);for(o=v.startCol;o<=v.endCol;o++)for(a=v.startRow;a<=v.endRow;a++){h=c[l=n._getBucketId(o,a)];var m=o>=g.startCol&&o<=g.endCol&&a>=g.startRow&&a<=g.endRow,y=o>=p.region.startCol&&o<=p.region.endCol&&a>=p.region.startRow&&a<=p.region.endRow;!m&&y&&y&&h&&n._bucketRemoveBody(t,h,p),(p.region===g||m&&!y||s)&&(h||(h=n._createBucket(c,l)),n._bucketAddBody(t,h,p))}p.region=g,d=!0}}}d&&(t.pairsList=n._createActivePairsList(t))},n.clear=function(t){t.buckets={},t.pairs={},t.pairsList=[]},n._regionUnion=function(t,e){var i=Math.min(t.startCol,e.startCol),s=Math.max(t.endCol,e.endCol),r=Math.min(t.startRow,e.startRow),o=Math.max(t.endRow,e.endRow);return n._createRegion(i,s,r,o)},n._getRegion=function(t,e){var i=e.bounds,s=Math.floor(i.min.x/t.bucketWidth),r=Math.floor(i.max.x/t.bucketWidth),o=Math.floor(i.min.y/t.bucketHeight),a=Math.floor(i.max.y/t.bucketHeight);return n._createRegion(s,r,o,a)},n._createRegion=function(t,e,i,n){return{id:t+","+e+","+i+","+n,startCol:t,endCol:e,startRow:i,endRow:n}},n._getBucketId=function(t,e){return"C"+t+"R"+e},n._createBucket=function(t,e){return t[e]=[]},n._bucketAddBody=function(t,e,i){for(var n=0;n0?n.push(i):delete t.pairs[e[s]];return n}},function(t,e,i){var n={};t.exports=n;var s=i(467),r=i(37);n._pairMaxIdleLife=1e3,n.create=function(t){return r.extend({table:{},list:[],collisionStart:[],collisionActive:[],collisionEnd:[]},t)},n.update=function(t,e,i){var n,r,o,a,h=t.list,l=t.table,u=t.collisionStart,c=t.collisionEnd,d=t.collisionActive;for(u.length=0,c.length=0,d.length=0,a=0;an._pairMaxIdleLife&&l.push(o);for(o=0;of.friction*f.frictionStatic*D*i&&(I=R,F=o.clamp(f.friction*L*i,-I,I));var B=r.cross(S,m),N=r.cross(A,m),Y=T/(g.inverseMass+v.inverseMass+g.inverseInertia*B*B+v.inverseInertia*N*N);if(k*=Y,F*=Y,O<0&&O*O>n._restingThresh*i)b.normalImpulse=0;else{var X=b.normalImpulse;b.normalImpulse=Math.min(b.normalImpulse+k,0),k=b.normalImpulse-X}if(P*P>n._restingThreshTangent*i)b.tangentImpulse=0;else{var z=b.tangentImpulse;b.tangentImpulse=o.clamp(b.tangentImpulse+F,-I,I),F=b.tangentImpulse-z}s.x=m.x*k+y.x*F,s.y=m.y*k+y.y*F,g.isStatic||g.isSleeping||(g.positionPrev.x+=s.x*g.inverseMass,g.positionPrev.y+=s.y*g.inverseMass,g.anglePrev+=r.cross(S,s)*g.inverseInertia),v.isStatic||v.isSleeping||(v.positionPrev.x-=s.x*v.inverseMass,v.positionPrev.y-=s.y*v.inverseMass,v.anglePrev-=r.cross(A,s)*v.inverseInertia)}}}}},function(t,e,i){t.exports={BasePlugin:i(468),DefaultPlugins:i(173),PluginCache:i(23),PluginManager:i(364),ScenePlugin:i(1293)}},function(t,e,i){var n=i(468),s=i(0),r=i(19),o=new s({Extends:n,initialize:function(t,e){n.call(this,e),this.scene=t,this.systems=t.sys,t.sys.events.once(r.BOOT,this.boot,this)},boot:function(){},destroy:function(){this.pluginManager=null,this.game=null,this.scene=null,this.systems=null}});t.exports=o},function(t,e,i){var n=i(17),s=i(175),r={Center:i(353),Events:i(92),Orientation:i(354),ScaleManager:i(365),ScaleModes:i(355),Zoom:i(356)};r=n(!1,r=n(!1,r=n(!1,r=n(!1,r,s.CENTER),s.ORIENTATION),s.SCALE_MODE),s.ZOOM),t.exports=r},function(t,e,i){var n=i(123),s=i(17),r={Events:i(19),SceneManager:i(367),ScenePlugin:i(1296),Settings:i(369),Systems:i(178)};r=s(!1,r,n),t.exports=r},function(t,e,i){var n=i(22),s=i(0),r=i(19),o=i(2),a=i(23),h=new s({initialize:function(t){this.scene=t,this.systems=t.sys,this.settings=t.sys.settings,this.key=t.sys.settings.key,this.manager=t.sys.game.scene,this.transitionProgress=0,this._elapsed=0,this._target=null,this._duration=0,this._onUpdate,this._onUpdateScope,this._willSleep=!1,this._willRemove=!1,t.sys.events.once(r.BOOT,this.boot,this),t.sys.events.on(r.START,this.pluginStart,this)},boot:function(){this.systems.events.once(r.DESTROY,this.destroy,this)},pluginStart:function(){this._target=null,this.systems.events.once(r.SHUTDOWN,this.shutdown,this)},start:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",this.key),this.manager.queueOp("start",t,e),this},restart:function(t){var e=this.key;return this.manager.queueOp("stop",e),this.manager.queueOp("start",e,t),this},transition:function(t){void 0===t&&(t={});var e=o(t,"target",!1),i=this.manager.getScene(e);if(!e||!this.checkValidTransition(i))return!1;var n=o(t,"duration",1e3);this._elapsed=0,this._target=i,this._duration=n,this._willSleep=o(t,"sleep",!1),this._willRemove=o(t,"remove",!1);var s=o(t,"onUpdate",null);s&&(this._onUpdate=s,this._onUpdateScope=o(t,"onUpdateScope",this.scene));var a=o(t,"allowInput",!1);this.settings.transitionAllowInput=a;var h=i.sys.settings;return h.isTransition=!0,h.transitionFrom=this.scene,h.transitionDuration=n,h.transitionAllowInput=a,o(t,"moveAbove",!1)?this.manager.moveAbove(this.key,e):o(t,"moveBelow",!1)&&this.manager.moveBelow(this.key,e),i.sys.isSleeping()?i.sys.wake():this.manager.start(e,o(t,"data")),this.systems.events.emit(r.TRANSITION_OUT,i,n),this.systems.events.on(r.UPDATE,this.step,this),!0},checkValidTransition:function(t){return!(!t||t.sys.isActive()||t.sys.isTransitioning()||t===this.scene||this.systems.isTransitioning())},step:function(t,e){this._elapsed+=e,this.transitionProgress=n(this._elapsed/this._duration,0,1),this._onUpdate&&this._onUpdate.call(this._onUpdateScope,this.transitionProgress),this._elapsed>=this._duration&&this.transitionComplete()},transitionComplete:function(){var t=this._target.sys,e=this._target.sys.settings;this.systems.events.off(r.UPDATE,this.step,this),t.events.emit(r.TRANSITION_COMPLETE,this.scene),e.isTransition=!1,e.transitionFrom=null,this._duration=0,this._target=null,this._onUpdate=null,this._onUpdateScope=null,this._willRemove?this.manager.remove(this.key):this._willSleep?this.systems.sleep():this.manager.stop(this.key)},add:function(t,e,i,n){return this.manager.add(t,e,i,n)},launch:function(t,e){return t&&t!==this.key&&this.manager.queueOp("start",t,e),this},run:function(t,e){return t&&t!==this.key&&this.manager.queueOp("run",t,e),this},pause:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("pause",t,e),this},resume:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("resume",t,e),this},sleep:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("sleep",t,e),this},wake:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("wake",t,e),this},switch:function(t){return t!==this.key&&this.manager.queueOp("switch",this.key,t),this},stop:function(t,e){return void 0===t&&(t=this.key),this.manager.queueOp("stop",t,e),this},setActive:function(t,e,i){void 0===e&&(e=this.key);var n=this.manager.getScene(e);return n&&n.sys.setActive(t,i),this},setVisible:function(t,e){void 0===e&&(e=this.key);var i=this.manager.getScene(e);return i&&i.sys.setVisible(t),this},isSleeping:function(t){return void 0===t&&(t=this.key),this.manager.isSleeping(t)},isActive:function(t){return void 0===t&&(t=this.key),this.manager.isActive(t)},isPaused:function(t){return void 0===t&&(t=this.key),this.manager.isPaused(t)},isVisible:function(t){return void 0===t&&(t=this.key),this.manager.isVisible(t)},swapPosition:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.swapPosition(t,e),this},moveAbove:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveAbove(t,e),this},moveBelow:function(t,e){return void 0===e&&(e=this.key),t!==e&&this.manager.moveBelow(t,e),this},remove:function(t){return void 0===t&&(t=this.key),this.manager.remove(t),this},moveUp:function(t){return void 0===t&&(t=this.key),this.manager.moveUp(t),this},moveDown:function(t){return void 0===t&&(t=this.key),this.manager.moveDown(t),this},bringToTop:function(t){return void 0===t&&(t=this.key),this.manager.bringToTop(t),this},sendToBack:function(t){return void 0===t&&(t=this.key),this.manager.sendToBack(t),this},get:function(t){return this.manager.getScene(t)},getIndex:function(t){return void 0===t&&(t=this.key),this.manager.getIndex(t)},shutdown:function(){var t=this.systems.events;t.off(r.SHUTDOWN,this.shutdown,this),t.off(r.POST_UPDATE,this.step,this),t.off(r.TRANSITION_OUT)},destroy:function(){this.shutdown(),this.scene.sys.events.off(r.START,this.start,this),this.scene=null,this.systems=null,this.settings=null,this.manager=null}});a.register("ScenePlugin",h,"scenePlugin"),t.exports=h},function(t,e,i){t.exports={List:i(126),Map:i(159),ProcessQueue:i(184),RTree:i(462),Set:i(108),Size:i(366)}},function(t,e,i){var n=i(17),s=i(1299),r={CanvasTexture:i(371),Events:i(119),FilterMode:s,Frame:i(94),Parsers:i(373),Texture:i(180),TextureManager:i(370),TextureSource:i(372)};r=n(!1,r,s),t.exports=r},function(t,e){t.exports={LINEAR:0,NEAREST:1}},function(t,e,i){t.exports={Components:i(137),Parsers:i(1330),Formats:i(31),ImageCollection:i(479),ParseToTilemap:i(224),Tile:i(74),Tilemap:i(488),TilemapCreator:i(1339),TilemapFactory:i(1340),Tileset:i(141),LayerData:i(104),MapData:i(105),ObjectLayer:i(482),DynamicTilemapLayer:i(489),StaticTilemapLayer:i(490)}},function(t,e,i){var n=i(24),s=i(51);t.exports=function(t,e,i,r,o,a,h,l){t<0&&(t=0),e<0&&(e=0),void 0===h&&(h=!0);for(var u=n(t,e,i,r,null,l),c=o-t,d=a-e,f=0;f=0&&p=0&&g=v;o--)(h=c[a][o])&&-1!==h.index&&h.visible&&0!==h.alpha&&i.push(h);else if(2===r)for(a=x;a>=y;a--)for(o=v;c[a]&&o=y;a--)for(o=m;c[a]&&o>=v;o--)(h=c[a][o])&&-1!==h.index&&h.visible&&0!==h.alpha&&i.push(h);return u.tilesDrawn=i.length,u.tilesTotal=d*f,i}},function(t,e,i){var n=i(24),s=i(51),r=i(73);t.exports=function(t,e,i,o,a,h,l){for(var u=-1!==l.collideIndexes.indexOf(t),c=n(e,i,o,a,null,l),d=0;d=0;r--)for(s=n.width-1;s>=0;s--)if((o=n.data[r][s])&&o.index===t){if(a===e)return o;a+=1}}else for(r=0;re)){for(var l=t;l<=e;l++)r(l,i,a);if(h)for(var u=0;u=t&&d.index<=e&&n(d,i)}o&&s(0,0,a.width,a.height,a)}}},function(t,e,i){var n=i(73),s=i(51),r=i(219);t.exports=function(t,e,i,o){void 0===e&&(e=!0),void 0===i&&(i=!0),Array.isArray(t)||(t=[t]);for(var a=0;a0&&n(a,t)}}e&&s(0,0,i.width,i.height,i)}},function(t,e){t.exports=function(t,e,i,n){if("number"==typeof t)n.callbacks[t]=null!==e?{callback:e,callbackContext:i}:void 0;else for(var s=0,r=t.length;s1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f0&&(t.currentPipeline&&t.currentPipeline.vertexCount>0&&t.flush(),r.vertexBuffer=e.vertexBuffer[a],t.setPipeline(r),t.setTexture2D(s[a].glTexture,0),t.gl.drawArrays(r.topology,0,e.vertexCount[a]));r.vertexBuffer=o,r.viewIdentity(),r.modelIdentity()}},function(t,e){t.exports=function(t,e,i,n,s){e.cull(n);var r=e.culledTiles,o=r.length;if(0!==o){var a=t._tempMatrix1,h=t._tempMatrix2,l=t._tempMatrix3;h.applyITRS(e.x,e.y,e.rotation,e.scaleX,e.scaleY),a.copyFrom(n.matrix);var u=t.currentContext,c=e.gidMap;u.save(),s?(a.multiplyWithOffset(s,-n.scrollX*e.scrollFactorX,-n.scrollY*e.scrollFactorY),h.e=e.x,h.f=e.y,a.multiply(h,l),l.copyToContext(u)):(h.e-=n.scrollX*e.scrollFactorX,h.f-=n.scrollY*e.scrollFactorY,h.copyToContext(u));var d=n.alpha*e.alpha;(!t.antialias||e.scaleX>1||e.scaleY>1)&&(u.imageSmoothingEnabled=!1);for(var f=0;f-1&&this._active.splice(s,1),n.destroy()}for(i=0;i=n.delay)){var s=n.elapsed-n.delay;n.elapsed=n.delay,!n.hasDispatched&&n.callback&&(n.hasDispatched=!0,n.callback.apply(n.callbackScope,n.args)),n.repeatCount>0?(n.repeatCount--,n.elapsed=s,n.hasDispatched=!1):this._pendingRemoval.push(n)}}}},shutdown:function(){var t;for(t=0;t-1&&(e.state=u.REMOVED,s.splice(r,1)):(e.state=u.REMOVED,n.splice(r,1))}for(i.length=0,i=this._add,t=0;t>2],r+=i[(3&n[o])<<4|n[o+1]>>4],r+=i[(15&n[o+1])<<2|n[o+2]>>6],r+=i[63&n[o+2]];return s%3==2?r=r.substring(0,r.length-1)+"=":s%3==1&&(r=r.substring(0,r.length-2)+"=="),r}},function(t,e,i){t.exports={Clone:i(67),Extend:i(17),GetAdvancedValue:i(15),GetFastValue:i(2),GetMinMaxValue:i(1364),GetValue:i(6),HasAll:i(1365),HasAny:i(399),HasValue:i(99),IsPlainObject:i(7),Merge:i(107),MergeRight:i(1366),Pick:i(480),SetValue:i(419)}},function(t,e,i){var n=i(6),s=i(22);t.exports=function(t,e,i,r,o){void 0===o&&(o=i);var a=n(t,e,o);return s(a,i,r)}},function(t,e){t.exports=function(t,e){for(var i=0;i=t.pos.x+t.size.x||this.pos.x+this.size.x<=t.pos.x||this.pos.y>=t.pos.y+t.size.y||this.pos.y+this.size.y<=t.pos.y)},resetSize:function(t,e,i,n){return this.pos.x=t,this.pos.y=e,this.size.x=i,this.size.y=n,this},toJSON:function(){return{name:this.name,size:{x:this.size.x,y:this.size.y},pos:{x:this.pos.x,y:this.pos.y},vel:{x:this.vel.x,y:this.vel.y},accel:{x:this.accel.x,y:this.accel.y},friction:{x:this.friction.x,y:this.friction.y},maxVel:{x:this.maxVel.x,y:this.maxVel.y},gravityFactor:this.gravityFactor,bounciness:this.bounciness,minBounceVelocity:this.minBounceVelocity,type:this.type,checkAgainst:this.checkAgainst,collides:this.collides}},fromJSON:function(){},check:function(){},collideWith:function(t,e){this.parent&&this.parent._collideCallback&&this.parent._collideCallback.call(this.parent._callbackScope,this,t,e)},handleMovementTrace:function(){return!0},destroy:function(){this.world.remove(this),this.enabled=!1,this.world=null,this.gameObject=null,this.parent=null}});t.exports=h},function(t,e,i){var n=i(0),s=i(1395),r=new n({initialize:function(t,e){void 0===t&&(t=32),this.tilesize=t,this.data=Array.isArray(e)?e:[],this.width=Array.isArray(e)?e[0].length:0,this.height=Array.isArray(e)?e.length:0,this.lastSlope=55,this.tiledef=s},trace:function(t,e,i,n,s,r){var o={collision:{x:!1,y:!1,slope:!1},pos:{x:t+i,y:e+n},tile:{x:0,y:0}};if(!this.data)return o;var a=Math.ceil(Math.max(Math.abs(i),Math.abs(n))/this.tilesize);if(a>1)for(var h=i/a,l=n/a,u=0;u0?r:0,m=n<0?f:0,y=Math.max(Math.floor(i/f),0),x=Math.min(Math.ceil((i+o)/f),g);u=Math.floor((t.pos.x+v)/f);var T=Math.floor((e+v)/f);if((l>0||u===T||T<0||T>=p)&&(T=-1),u>=0&&u1&&d<=this.lastSlope&&this.checkDef(t,d,e,i,a,h,r,o,T,c));c++)if(1===(d=this.data[c][u])||d>this.lastSlope||d>1&&this.checkDef(t,d,e,i,a,h,r,o,u,c)){if(d>1&&d<=this.lastSlope&&t.collision.slope)break;t.collision.x=!0,t.tile.x=d,t.pos.x=u*f-v+m,e=t.pos.x,a=0;break}}if(s){var w=s>0?o:0,b=s<0?f:0,E=Math.max(Math.floor(t.pos.x/f),0),S=Math.min(Math.ceil((t.pos.x+r)/f),p);c=Math.floor((t.pos.y+w)/f);var A=Math.floor((i+w)/f);if((l>0||c===A||A<0||A>=g)&&(A=-1),c>=0&&c1&&d<=this.lastSlope&&this.checkDef(t,d,e,i,a,h,r,o,u,A));u++)if(1===(d=this.data[c][u])||d>this.lastSlope||d>1&&this.checkDef(t,d,e,i,a,h,r,o,u,c)){if(d>1&&d<=this.lastSlope&&t.collision.slope)break;t.collision.y=!0,t.tile.y=d,t.pos.y=c*f-w+b;break}}},checkDef:function(t,e,i,n,s,r,o,a,h,l){var u=this.tiledef[e];if(!u)return!1;var c=this.tilesize,d=(h+u[0])*c,f=(l+u[1])*c,p=(u[2]-u[0])*c,g=(u[3]-u[1])*c,v=u[4],m=i+s+(g<0?o:0)-d,y=n+r+(p>0?a:0)-f;if(p*y-g*m>0){if(s*-g+r*p<0)return v;var x=Math.sqrt(p*p+g*g),T=g/x,w=-p/x,b=m*T+y*w,E=T*b,S=w*b;return E*E+S*S>=s*s+r*r?v||p*(y-r)-g*(m-s)<.5:(t.pos.x=i+s-E,t.pos.y=n+r-S,t.collision.slope={x:p,y:g,nx:T,ny:w},!0)}return!1}});t.exports=r},function(t,e,i){var n=i(0),s=i(1374),r=i(1375),o=i(1376),a=new n({initialize:function(t){this.world=t,this.sys=t.scene.sys},body:function(t,e,i,n){return new s(this.world,t,e,i,n)},existing:function(t){var e=t.x-t.frame.centerX,i=t.y-t.frame.centerY,n=t.width,s=t.height;return t.body=this.world.create(e,i,n,s),t.body.parent=t,t.body.gameObject=t,t},image:function(t,e,i,n){var s=new r(this.world,t,e,i,n);return this.sys.displayList.add(s),s},sprite:function(t,e,i,n){var s=new o(this.world,t,e,i,n);return this.sys.displayList.add(s),this.sys.updateList.add(s),s},destroy:function(){this.world=null,this.sys=null}});t.exports=a},function(t,e,i){var n=i(0),s=i(1279),r=new n({Mixins:[s.Acceleration,s.BodyScale,s.BodyType,s.Bounce,s.CheckAgainst,s.Collides,s.Debug,s.Friction,s.Gravity,s.Offset,s.SetGameObject,s.Velocity],initialize:function(t,e,i,n,s){this.body=t.create(e,i,n,s),this.body.parent=this,this.size=this.body.size,this.offset=this.body.offset,this.vel=this.body.vel,this.accel=this.body.accel,this.friction=this.body.friction,this.maxVel=this.body.maxVel}});t.exports=r},function(t,e,i){var n=i(0),s=i(1279),r=i(98),o=new n({Extends:r,Mixins:[s.Acceleration,s.BodyScale,s.BodyType,s.Bounce,s.CheckAgainst,s.Collides,s.Debug,s.Friction,s.Gravity,s.Offset,s.SetGameObject,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t.scene,e,i,n,s),this.body=t.create(e-this.frame.centerX,i-this.frame.centerY,this.width,this.height),this.body.parent=this,this.body.gameObject=this,this.size=this.body.size,this.offset=this.body.offset,this.vel=this.body.vel,this.accel=this.body.accel,this.friction=this.body.friction,this.maxVel=this.body.maxVel}});t.exports=o},function(t,e,i){var n=i(0),s=i(1279),r=i(69),o=new n({Extends:r,Mixins:[s.Acceleration,s.BodyScale,s.BodyType,s.Bounce,s.CheckAgainst,s.Collides,s.Debug,s.Friction,s.Gravity,s.Offset,s.SetGameObject,s.Velocity],initialize:function(t,e,i,n,s){r.call(this,t.scene,e,i,n,s),this.body=t.create(e-this.frame.centerX,i-this.frame.centerY,this.width,this.height),this.body.parent=this,this.body.gameObject=this,this.size=this.body.size,this.offset=this.body.offset,this.vel=this.body.vel,this.accel=this.body.accel,this.friction=this.body.friction,this.maxVel=this.body.maxVel}});t.exports=o},function(t,e,i){var n=i(1371),s=i(0),r=i(465),o=i(1372),a=i(9),h=i(1278),l=i(2),u=i(99),c=i(108),d=i(1409),f=i(31),p=i(466),g=new s({Extends:a,initialize:function(t,e){a.call(this),this.scene=t,this.bodies=new c,this.gravity=l(e,"gravity",0),this.cellSize=l(e,"cellSize",64),this.collisionMap=new o,this.timeScale=l(e,"timeScale",1),this.maxStep=l(e,"maxStep",.05),this.enabled=!0,this.drawDebug=l(e,"debug",!1),this.debugGraphic;var i=l(e,"maxVelocity",100);if(this.defaults={debugShowBody:l(e,"debugShowBody",!0),debugShowVelocity:l(e,"debugShowVelocity",!0),bodyDebugColor:l(e,"debugBodyColor",16711935),velocityDebugColor:l(e,"debugVelocityColor",65280),maxVelocityX:l(e,"maxVelocityX",i),maxVelocityY:l(e,"maxVelocityY",i),minBounceVelocity:l(e,"minBounceVelocity",40),gravityFactor:l(e,"gravityFactor",1),bounciness:l(e,"bounciness",0)},this.walls={left:null,right:null,top:null,bottom:null},this.delta=0,this._lastId=0,l(e,"setBounds",!1)){var n=e.setBounds;if("boolean"==typeof n)this.setBounds();else{var s=l(n,"x",0),r=l(n,"y",0),h=l(n,"width",t.sys.scale.width),u=l(n,"height",t.sys.scale.height),d=l(n,"thickness",64),f=l(n,"left",!0),p=l(n,"right",!0),g=l(n,"top",!0),v=l(n,"bottom",!0);this.setBounds(s,r,h,u,d,f,p,g,v)}}this.drawDebug&&this.createDebugGraphic()},setCollisionMap:function(t,e){if("string"==typeof t){var i=this.scene.cache.tilemap.get(t);if(!i||i.format!==f.WELTMEISTER)return console.warn("The specified key does not correspond to a Weltmeister tilemap: "+t),null;for(var n,s=i.data.layer,r=0;rr.ACTIVE&&d(this,t,e))},setCollidesNever:function(t){for(var e=0;e=0&&h<=1&&l>=0&&l<=1}function s(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])}function r(t,e,i){return s(t,e,i)>0}function o(t,e,i){return s(t,e,i)>=0}function a(t,e,i){return s(t,e,i)<0}function h(t,e,i){return s(t,e,i)<=0}t.exports={decomp:function(t){var e=function t(e){var i=[],n=[],s=[],r=[];var o=Number.MAX_VALUE;for(var a=0;a0?function t(e,i){if(0===i.length)return[e];if(i instanceof Array&&i.length&&i[0]instanceof Array&&2===i[0].length&&i[0][0]instanceof Array){for(var n=[e],s=0;su)return console.warn("quickDecomp: max level ("+u+") reached."),i;for(var L=0;LA&&(A+=e.length),S=Number.MAX_VALUE,A<_)return i;for(var k=_;k<=A;++k)o(f(P,L-1),f(P,L),f(P,k))&&h(f(P,L+1),f(P,L),f(P,k))&&(E=d(f(P,L),f(P,k)))3&&n>=0;--n)c(f(t,n-1),f(t,n),f(t,n+1),e)&&(t.splice(n%t.length,1),i++);return i},removeDuplicatePoints:function(t,e){for(var i=t.length-1;i>=1;--i)for(var n=t[i],s=i-1;s>=0;--s)E(n,t[s],e)&&t.splice(i,1)},makeCCW:function(t){for(var e=0,i=t,n=1;ni[e][0])&&(e=n);return!r(f(t,e-1),f(t,e),f(t,e+1))&&(function(t){for(var e=[],i=t.length,n=0;n!==i;n++)e.push(t.pop());for(var n=0;n!==i;n++)t[n]=e[n]}(t),!0)}};var l=[],u=[];function c(t,e,i,n){if(n){var r=l,o=u;r[0]=e[0]-t[0],r[1]=e[1]-t[1],o[0]=i[0]-e[0],o[1]=i[1]-e[1];var a=r[0]*o[0]+r[1]*o[1],h=Math.sqrt(r[0]*r[0]+r[1]*r[1]),c=Math.sqrt(o[0]*o[0]+o[1]*o[1]);return Math.acos(a/(h*c))0&&u.trigger(t,"collisionStart",{pairs:T.collisionStart}),o.preSolvePosition(T.list),s=0;s0&&u.trigger(t,"collisionActive",{pairs:T.collisionActive}),T.collisionEnd.length>0&&u.trigger(t,"collisionEnd",{pairs:T.collisionEnd}),h.update(t.metrics,t),n._bodiesClearForces(m),u.trigger(t,"afterUpdate",v),t},n.merge=function(t,e){if(f.extend(t,e),e.world){t.world=e.world,n.clear(t);for(var i=c.allBodies(t.world),s=0;s0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_START,e,i,n)}),p.on(e,"collisionActive",function(e){var i,n,s=e.pairs;s.length>0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_ACTIVE,e,i,n)}),p.on(e,"collisionEnd",function(e){var i,n,s=e.pairs;s.length>0&&(i=s[0].bodyA,n=s[0].bodyB),t.emit(u.COLLISION_END,e,i,n)})},setBounds:function(t,e,i,n,s,r,o,a,h){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.scene.sys.scale.width),void 0===n&&(n=this.scene.sys.scale.height),void 0===s&&(s=64),void 0===r&&(r=!0),void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===h&&(h=!0),this.updateWall(r,"left",t-s,e-s,s,n+2*s),this.updateWall(o,"right",t+i,e-s,s,n+2*s),this.updateWall(a,"top",t,e-s,i,s),this.updateWall(h,"bottom",t,e+n,i,s),this},updateWall:function(t,e,i,n,s,r){var o=this.walls[e];t?(o&&v.remove(this.localWorld,o),i+=s/2,n+=r/2,this.walls[e]=this.create(i,n,s,r,{isStatic:!0,friction:0,frictionStatic:0})):(o&&v.remove(this.localWorld,o),this.walls[e]=null)},createDebugGraphic:function(){var t=this.scene.sys.add.graphics({x:0,y:0});return t.setDepth(Number.MAX_VALUE),this.debugGraphic=t,this.drawDebug=!0,t},disableGravity:function(){return this.localWorld.gravity.x=0,this.localWorld.gravity.y=0,this.localWorld.gravity.scale=0,this},setGravity:function(t,e,i){return void 0===t&&(t=0),void 0===e&&(e=1),this.localWorld.gravity.x=t,this.localWorld.gravity.y=e,void 0!==i&&(this.localWorld.gravity.scale=i),this},create:function(t,e,i,s,r){var o=n.rectangle(t,e,i,s,r);return v.add(this.localWorld,o),o},add:function(t){return v.add(this.localWorld,t),this},remove:function(t,e){Array.isArray(t)||(t=[t]);for(var i=0;in.deltaMax?n.deltaMax:e)/n.delta,n.delta=e),0!==n.timeScalePrev&&(r*=s.timeScale/n.timeScalePrev),0===s.timeScale&&(r=0),n.timeScalePrev=s.timeScale,n.correction=r,n.frameCounter+=1,t-n.counterTimestamp>=1e3&&(n.fps=n.frameCounter*((t-n.counterTimestamp)/1e3),n.counterTimestamp=t,n.frameCounter=0),h.update(i,e,r)}},step:function(t,e){h.update(this.engine,t,e)},update60Hz:function(){return 1e3/60},update30Hz:function(){return 1e3/30},has:function(t){var e=t.hasOwnProperty("body")?t.body:t;return null!==a.get(this.localWorld,e.id,e.type)},getAllBodies:function(){return a.allBodies(this.localWorld)},getAllConstraints:function(){return a.allConstraints(this.localWorld)},getAllComposites:function(){return a.allComposites(this.localWorld)},postUpdate:function(){if(this.drawDebug){var t=this.debugConfig,e=this.engine,i=this.debugGraphic,n=a.allBodies(this.localWorld);this.debugGraphic.clear(),t.showBroadphase&&e.broadphase.controller&&this.renderGrid(e.broadphase,i,t.broadphaseColor,.5),t.showBounds&&this.renderBodyBounds(n,i,t.boundsColor,.5),(t.showBody||t.showStaticBody)&&this.renderBodies(n),t.showJoint&&this.renderJoints(),(t.showAxes||t.showAngleIndicator)&&this.renderBodyAxes(n,i,t.showAxes,t.angleColor,.5),t.showVelocity&&this.renderBodyVelocity(n,i,t.velocityColor,1,2),t.showSeparations&&this.renderSeparations(e.pairs.list,i,t.separationColor),t.showCollisions&&this.renderCollisions(e.pairs.list,i,t.collisionColor)}},renderGrid:function(t,e,i,n){e.lineStyle(1,i,n);for(var s=o.keys(t.buckets),r=0;r0){var l=h[0].vertex.x,u=h[0].vertex.y;2===h.length&&(l=(h[0].vertex.x+h[1].vertex.x)/2,u=(h[0].vertex.y+h[1].vertex.y)/2),a.bodyB===a.supports[0].body||a.bodyA.isStatic?e.lineBetween(l-8*a.normal.x,u-8*a.normal.y,l,u):e.lineBetween(l+8*a.normal.x,u+8*a.normal.y,l,u)}}return this},renderBodyBounds:function(t,e,i,n){e.lineStyle(1,i,n);for(var s=0;s1?1:0;h1?1:0;a1?1:0;a1&&this.renderConvexHull(g,e,f,y)}}},renderBody:function(t,e,i,n,s,r,o,a){void 0===n&&(n=null),void 0===s&&(s=null),void 0===r&&(r=1),void 0===o&&(o=null),void 0===a&&(a=null);for(var h=this.debugConfig,l=h.sensorFillColor,u=h.sensorLineColor,c=t.parts,d=c.length,f=d>1?1:0;f1){var s=t.vertices;e.lineStyle(n,i),e.beginPath(),e.moveTo(s[0].x,s[0].y);for(var r=1;r0&&(e.fillStyle(a),e.fillCircle(u.x,u.y,h),e.fillCircle(c.x,c.y,h)),this},resetCollisionIDs:function(){return s._nextCollidingGroupId=1,s._nextNonCollidingGroupId=-1,s._nextCategory=1,this},shutdown:function(){p.off(this.engine),this.removeAllListeners(),v.clear(this.localWorld,!1),h.clear(this.engine),this.drawDebug&&this.debugGraphic.destroy()},destroy:function(){this.shutdown()}});t.exports=y},function(t,e,i){(function(e){i(512);var n=i(29),s=i(17),r={Actions:i(238),Animations:i(632),BlendModes:i(52),Cache:i(633),Cameras:i(636),Core:i(719),Class:i(0),Create:i(781),Curves:i(787),Data:i(790),Display:i(792),DOM:i(809),Events:i(810),Game:i(812),GameObjects:i(905),Geom:i(422),Input:i(1187),Loader:i(1221),Math:i(168),Physics:i(1388),Plugins:i(1292),Renderer:i(1448),Scale:i(1294),ScaleModes:i(231),Scene:i(368),Scenes:i(1295),Structs:i(1297),Textures:i(1298),Tilemaps:i(1300),Time:i(1341),Tweens:i(1343),Utils:i(1360)};r.Sound=i(1370),r=s(!1,r,n),t.exports=r,e.Phaser=r}).call(this,i(511))},function(t,e,i){t.exports={Arcade:i(1247),Impact:i(1389),Matter:i(1412)}},function(t,e,i){t.exports={Body:i(1371),Events:i(1278),COLLIDES:i(465),CollisionMap:i(1372),Factory:i(1373),Image:i(1375),ImpactBody:i(1374),ImpactPhysics:i(1408),Sprite:i(1376),TYPE:i(466),World:i(1377)}},function(t,e,i){var n=i(22);t.exports=function(t,e,i,s,r){if(i)return n(e+i*t,-r,r);if(s){var o=s*t;return e-o>0?e-o:e+o<0?e+o:0}return n(e,-r,r)}},function(t,e){t.exports=function(t,e){if(t.standing=!1,e.collision.y&&(t.bounciness>0&&Math.abs(t.vel.y)>t.minBounceVelocity?t.vel.y*=-t.bounciness:(t.vel.y>0&&(t.standing=!0),t.vel.y=0)),e.collision.x&&(t.bounciness>0&&Math.abs(t.vel.x)>t.minBounceVelocity?t.vel.x*=-t.bounciness:t.vel.x=0),e.collision.slope){var i=e.collision.slope;if(t.bounciness>0){var n=t.vel.x*i.nx+t.vel.y*i.ny;t.vel.x=(t.vel.x-i.nx*n*2)*t.bounciness,t.vel.y=(t.vel.y-i.ny*n*2)*t.bounciness}else{var s=i.x*i.x+i.y*i.y,r=(t.vel.x*i.x+t.vel.y*i.y)/s;t.vel.x=i.x*r,t.vel.y=i.y*r;var o=Math.atan2(i.x,i.y);o>t.slopeStanding.min&&oi.last.x&&e.last.xi.last.y&&e.last.y0))r=t.collisionMap.trace(e.pos.x,e.pos.y,0,-(e.pos.y+e.size.y-i.pos.y),e.size.x,e.size.y),e.pos.y=r.pos.y,e.bounciness>0&&e.vel.y>e.minBounceVelocity?e.vel.y*=-e.bounciness:(e.standing=!0,e.vel.y=0);else{var l=(e.vel.y-i.vel.y)/2;e.vel.y=-l,i.vel.y=l,s=i.vel.x*t.delta,r=t.collisionMap.trace(e.pos.x,e.pos.y,s,-o/2,e.size.x,e.size.y),e.pos.y=r.pos.y;var u=t.collisionMap.trace(i.pos.x,i.pos.y,0,o/2,i.size.x,i.size.y);i.pos.y=u.pos.y}}},function(t,e,i){t.exports={BodyBounds:i(1378),Factory:i(1379),Image:i(1381),Matter:i(1286),MatterPhysics:i(1444),PolyDecomp:i(1380),Sprite:i(1382),TileBody:i(1285),PhysicsEditorParser:i(1282),PhysicsJSONParser:i(1283),World:i(1386)}},function(t,e,i){var n=i(508),s=i(2),r=i(3);t.exports=function(t,e,i,o){void 0===i&&(i={}),void 0===o&&(o=!0);var a=e.x,h=e.y;if(e.body={temp:!0,position:{x:a,y:h}},[n.Bounce,n.Collision,n.Force,n.Friction,n.Gravity,n.Mass,n.Sensor,n.SetBody,n.Sleep,n.Static,n.Transform,n.Velocity].forEach(function(t){for(var i in t)(n=t[i]).get&&"function"==typeof n.get||n.set&&"function"==typeof n.set?Object.defineProperty(e,i,{get:t[i].get,set:t[i].set}):Object.defineProperty(e,i,{value:t[i]});var n}),e.world=t,e._tempVec2=new r(a,h),i.hasOwnProperty("type")&&"body"===i.type)e.setExistingBody(i,o);else{var l=s(i,"shape",null);l||(l="rectangle"),i.addToWorld=o,e.setBody(l,i)}return e}},function(t,e){t.exports={setBounce:function(t){return this.body.restitution=t,this}}},function(t,e){var i={setCollisionCategory:function(t){return this.body.collisionFilter.category=t,this},setCollisionGroup:function(t){return this.body.collisionFilter.group=t,this},setCollidesWith:function(t){var e=0;if(Array.isArray(t))for(var i=0;i1?1:0;s0},intersectPoint:function(t,e,i){i=this.getMatterBodies(i);var n=k.create(t,e),s=[];return M.point(i,n).forEach(function(t){-1===s.indexOf(t)&&s.push(t)}),s},intersectRect:function(t,e,i,n,s,r){void 0===s&&(s=!1),r=this.getMatterBodies(r);var o={min:{x:t,y:e},max:{x:t+i,y:e+n}},a=[];return M.region(r,o,s).forEach(function(t){-1===a.indexOf(t)&&a.push(t)}),a},intersectRay:function(t,e,i,n,s,r){void 0===s&&(s=1),r=this.getMatterBodies(r);for(var o=[],a=M.ray(r,k.create(t,e),k.create(i,n),s),h=0;h0)for(var a=s+1;ae.max.x?i=e.min.x-t.max.x:t.max.xe.max.y?n=e.min.y-t.max.y:t.max.y= 2.1.2 < 3" - } - }, - "ignore-walk": { - "version": "3.0.3", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minimatch": "^3.0.4" - } - }, - "inflight": { - "version": "1.0.6", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "bundled": true, - "dev": true, - "optional": true - }, - "ini": { - "version": "1.3.5", - "bundled": true, - "dev": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "number-is-nan": "^1.0.0" - } - }, - "isarray": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "minimatch": { - "version": "3.0.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "0.0.8", - "bundled": true, - "dev": true, - "optional": true - }, - "minipass": { - "version": "2.9.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safe-buffer": "^5.1.2", - "yallist": "^3.0.0" - } - }, - "minizlib": { - "version": "1.3.3", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minipass": "^2.9.0" - } - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "minimist": "0.0.8" - } - }, - "ms": { - "version": "2.1.2", - "bundled": true, - "dev": true, - "optional": true - }, - "needle": { - "version": "2.4.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "debug": "^3.2.6", - "iconv-lite": "^0.4.4", - "sax": "^1.2.4" - } - }, - "node-pre-gyp": { - "version": "0.14.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "detect-libc": "^1.0.2", - "mkdirp": "^0.5.1", - "needle": "^2.2.1", - "nopt": "^4.0.1", - "npm-packlist": "^1.1.6", - "npmlog": "^4.0.2", - "rc": "^1.2.7", - "rimraf": "^2.6.1", - "semver": "^5.3.0", - "tar": "^4.4.2" - } - }, - "nopt": { - "version": "4.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "abbrev": "1", - "osenv": "^0.1.4" - } - }, - "npm-bundled": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "npm-normalize-package-bin": "^1.0.1" - } - }, - "npm-normalize-package-bin": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "npm-packlist": { - "version": "1.4.7", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ignore-walk": "^3.0.1", - "npm-bundled": "^1.0.1" - } - }, - "npmlog": { - "version": "4.1.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "are-we-there-yet": "~1.1.2", - "console-control-strings": "~1.1.0", - "gauge": "~2.7.3", - "set-blocking": "~2.0.0" - } - }, - "number-is-nan": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "wrappy": "1" - } - }, - "os-homedir": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "os-tmpdir": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "osenv": { - "version": "0.1.5", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "os-homedir": "^1.0.0", - "os-tmpdir": "^1.0.0" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "process-nextick-args": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "rc": { - "version": "1.2.8", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "readable-stream": { - "version": "2.3.6", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "rimraf": { - "version": "2.7.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "glob": "^7.1.3" - } - }, - "safe-buffer": { - "version": "5.1.2", - "bundled": true, - "dev": true, - "optional": true - }, - "safer-buffer": { - "version": "2.1.2", - "bundled": true, - "dev": true, - "optional": true - }, - "sax": { - "version": "1.2.4", - "bundled": true, - "dev": true, - "optional": true - }, - "semver": { - "version": "5.7.1", - "bundled": true, - "dev": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "string-width": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - }, - "string_decoder": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safe-buffer": "~5.1.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "tar": { - "version": "4.4.13", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "chownr": "^1.1.1", - "fs-minipass": "^1.2.5", - "minipass": "^2.8.6", - "minizlib": "^1.2.1", - "mkdirp": "^0.5.0", - "safe-buffer": "^5.1.2", - "yallist": "^3.0.3" - } - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "wide-align": { - "version": "1.1.3", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "string-width": "^1.0.2 || 2" - } - }, - "wrappy": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "yallist": { - "version": "3.1.1", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true - }, - "get-caller-file": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", - "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", - "dev": true - }, - "get-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", - "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", - "dev": true - }, - "get-value": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", - "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", - "dev": true - }, - "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "glob-parent": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", - "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", - "dev": true, - "requires": { - "is-glob": "^3.1.0", - "path-dirname": "^1.0.0" - }, - "dependencies": { - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "^2.1.0" - } - } - } - }, - "global-modules-path": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/global-modules-path/-/global-modules-path-2.3.0.tgz", - "integrity": "sha512-HchvMJNYh9dGSCy8pOQ2O8u/hoXaL+0XhnrwH0RyLiSXMMTl9W3N6KUU73+JFOg5PGjtzl6VZzUQsnrpm7Szag==", - "dev": true - }, - "globals": { - "version": "11.4.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.4.0.tgz", - "integrity": "sha512-Dyzmifil8n/TmSqYDEXbm+C8yitzJQqQIlJQLNRMwa+BOUJpRC19pyVeN12JAjt61xonvXjtff+hJruTRXn5HA==", - "dev": true - }, - "globby": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", - "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", - "dev": true, - "requires": { - "array-union": "^1.0.1", - "arrify": "^1.0.0", - "glob": "^7.0.3", - "object-assign": "^4.0.1", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0" - } - }, - "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", - "dev": true - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "has-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", - "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", - "dev": true, - "requires": { - "get-value": "^2.0.6", - "has-values": "^1.0.0", - "isobject": "^3.0.0" - } - }, - "has-values": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", - "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", - "dev": true, - "requires": { - "is-number": "^3.0.0", - "kind-of": "^4.0.0" - }, - "dependencies": { - "kind-of": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", - "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "hash-base": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", - "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", - "dev": true, - "requires": { - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "hash.js": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", - "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "minimalistic-assert": "^1.0.1" - } - }, - "hmac-drbg": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", - "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", - "dev": true, - "requires": { - "hash.js": "^1.0.3", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.1" - } - }, - "https-browserify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", - "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=", - "dev": true - }, - "iconv-lite": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", - "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==", - "dev": true - }, - "ieee754": { - "version": "1.1.13", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", - "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==", - "dev": true - }, - "iferr": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", - "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=", - "dev": true - }, - "ignore": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.7.tgz", - "integrity": "sha512-YGG3ejvBNHRqu0559EOxxNFihD0AjpvHlC/pdGKd3X3ofe+CoJkYazwNJYTNebqpPKN+VVQbh4ZFn1DivMNuHA==", - "dev": true - }, - "import-local": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz", - "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==", - "dev": true, - "requires": { - "pkg-dir": "^3.0.0", - "resolve-cwd": "^2.0.0" - }, - "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.0.0.tgz", - "integrity": "sha512-fl5s52lI5ahKCernzzIyAP0QAZbGIovtVHGwpcu1Jr/EpzLVDI2myISHwGqK7m8uQFugVWSrbxH7XnhGtvEc+A==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.0.0.tgz", - "integrity": "sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==", - "dev": true - }, - "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "dev": true, - "requires": { - "find-up": "^3.0.0" - } - } - } - }, - "imports-loader": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/imports-loader/-/imports-loader-0.8.0.tgz", - "integrity": "sha512-kXWL7Scp8KQ4552ZcdVTeaQCZSLW+e6nJfp3cwUMB673T7Hr98Xjx5JK+ql7ADlJUvj1JS5O01RLbKoutN5QDQ==", - "requires": { - "loader-utils": "^1.0.2", - "source-map": "^0.6.1" - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true - }, - "infer-owner": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", - "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", - "dev": true - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, - "inquirer": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.3.0.tgz", - "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", - "dev": true, - "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", - "cli-cursor": "^2.1.0", - "cli-width": "^2.0.0", - "external-editor": "^2.0.4", - "figures": "^2.0.0", - "lodash": "^4.3.0", - "mute-stream": "0.0.7", - "run-async": "^2.2.0", - "rx-lite": "^4.0.8", - "rx-lite-aggregates": "^4.0.8", - "string-width": "^2.1.0", - "strip-ansi": "^4.0.0", - "through": "^2.3.6" - } - }, - "interpret": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", - "integrity": "sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=", - "dev": true - }, - "invert-kv": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", - "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", - "dev": true - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "is-binary-path": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", - "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", - "dev": true, - "requires": { - "binary-extensions": "^1.0.0" - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "^0.1.6", - "is-data-descriptor": "^0.1.4", - "kind-of": "^5.0.0" - }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", - "dev": true - } - } - }, - "is-extendable": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", - "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", - "dev": true - }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", - "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dev": true, - "requires": { - "is-extglob": "^2.1.1" - } - }, - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "is-path-cwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", - "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=", - "dev": true - }, - "is-path-in-cwd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", - "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", - "dev": true, - "requires": { - "is-path-inside": "^1.0.0" - } - }, - "is-path-inside": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", - "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", - "dev": true, - "requires": { - "path-is-inside": "^1.0.1" - } - }, - "is-plain-object": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", - "dev": true, - "requires": { - "isobject": "^3.0.1" - } - }, - "is-promise": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", - "dev": true - }, - "is-resolvable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", - "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==", - "dev": true - }, - "is-stream": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", - "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", - "dev": true - }, - "is-windows": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", - "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", - "dev": true - }, - "is-wsl": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", - "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=", - "dev": true - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", - "dev": true - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", - "dev": true - }, - "js-yaml": { - "version": "3.13.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", - "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "js2xmlparser": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.0.tgz", - "integrity": "sha512-WuNgdZOXVmBk5kUPMcTcVUpbGRzLfNkv7+7APq7WiDihpXVKrgxo6wwRpRl9OQeEBgKCVk9mR7RbzrnNWC8oBw==", - "dev": true, - "requires": { - "xmlcreate": "^2.0.0" - } - }, - "jsdoc": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.3.tgz", - "integrity": "sha512-Yf1ZKA3r9nvtMWHO1kEuMZTlHOF8uoQ0vyo5eH7SQy5YeIiHM+B0DgKnn+X6y6KDYZcF7G2SPkKF+JORCXWE/A==", - "dev": true, - "requires": { - "@babel/parser": "^7.4.4", - "bluebird": "^3.5.4", - "catharsis": "^0.8.11", - "escape-string-regexp": "^2.0.0", - "js2xmlparser": "^4.0.0", - "klaw": "^3.0.0", - "markdown-it": "^8.4.2", - "markdown-it-anchor": "^5.0.2", - "marked": "^0.7.0", - "mkdirp": "^0.5.1", - "requizzle": "^0.2.3", - "strip-json-comments": "^3.0.1", - "taffydb": "2.6.2", - "underscore": "~1.9.1" - }, - "dependencies": { - "bluebird": { - "version": "3.7.1", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.1.tgz", - "integrity": "sha512-DdmyoGCleJnkbp3nkbxTLJ18rjDsE4yCggEwKNXkeV123sPNfOCYeDoeuOY+F2FrSjO1YXcTU+dsy96KMy+gcg==", - "dev": true - }, - "escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true - }, - "strip-json-comments": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.0.1.tgz", - "integrity": "sha512-VTyMAUfdm047mwKl+u79WIdrZxtFtn+nBxHeb844XBQ9uMNTuTHdx2hc5RiAJYqwTj3wc/xe5HLSdJSkJ+WfZw==", - "dev": true - } - } - }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true - }, - "json-schema-traverse": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", - "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=", - "dev": true - }, - "json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", - "dev": true - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=" - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.6" - } - }, - "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true - }, - "klaw": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", - "integrity": "sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.9" - } - }, - "lcid": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", - "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", - "dev": true, - "requires": { - "invert-kv": "^2.0.0" - } - }, - "levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" - } - }, - "linkify-it": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz", - "integrity": "sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==", - "dev": true, - "requires": { - "uc.micro": "^1.0.1" - } - }, - "loader-runner": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.4.0.tgz", - "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==", - "dev": true - }, - "loader-utils": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", - "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", - "requires": { - "big.js": "^3.1.3", - "emojis-list": "^2.0.0", - "json5": "^0.5.0" - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", - "dev": true, - "requires": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - } - }, - "lodash": { - "version": "4.17.15", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", - "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", - "dev": true - }, - "lru-cache": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.2.tgz", - "integrity": "sha512-wgeVXhrDwAWnIF/yZARsFnMBtdFXOg1b8RIrhilp+0iDYN4mdQcNZElDZ0e4B64BhaxeQ5zN7PMyvu7we1kPeQ==", - "dev": true, - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, - "make-dir": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", - "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", - "dev": true, - "requires": { - "pify": "^3.0.0" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "mamacro": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/mamacro/-/mamacro-0.0.3.tgz", - "integrity": "sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA==", - "dev": true - }, - "map-age-cleaner": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.2.tgz", - "integrity": "sha512-UN1dNocxQq44IhJyMI4TU8phc2m9BddacHRPRjKGLYaF0jqd3xLz0jS0skpAU9WgYyoR4gHtUpzytNBS385FWQ==", - "dev": true, - "requires": { - "p-defer": "^1.0.0" - } - }, - "map-cache": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", - "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", - "dev": true - }, - "map-visit": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", - "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", - "dev": true, - "requires": { - "object-visit": "^1.0.0" - } - }, - "markdown-it": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-8.4.2.tgz", - "integrity": "sha512-GcRz3AWTqSUphY3vsUqQSFMbgR38a4Lh3GWlHRh/7MRwz8mcu9n2IO7HOh+bXHrR9kOPDl5RNCaEsrneb+xhHQ==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "entities": "~1.1.1", - "linkify-it": "^2.0.0", - "mdurl": "^1.0.1", - "uc.micro": "^1.0.5" - } - }, - "markdown-it-anchor": { - "version": "5.2.5", - "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.2.5.tgz", - "integrity": "sha512-xLIjLQmtym3QpoY9llBgApknl7pxAcN3WDRc2d3rwpl+/YvDZHPmKscGs+L6E05xf2KrCXPBvosWt7MZukwSpQ==", - "dev": true - }, - "marked": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/marked/-/marked-0.7.0.tgz", - "integrity": "sha512-c+yYdCZJQrsRjTPhUx7VKkApw9bwDkNbHUKo1ovgcfDjb2kc8rLuRbIFyXL5WOEUwzSSKo3IXpph2K6DqB/KZg==", - "dev": true - }, - "md5.js": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", - "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", - "dev": true, - "requires": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - }, - "dependencies": { - "safe-buffer": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", - "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", - "dev": true - } - } - }, - "mdurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", - "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=", - "dev": true - }, - "mem": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-4.0.0.tgz", - "integrity": "sha512-WQxG/5xYc3tMbYLXoXPm81ET2WDULiU5FxbuIoNbJqLOOI8zehXFdZuiUEgfdrU2mVB1pxBZUGlYORSrpuJreA==", - "dev": true, - "requires": { - "map-age-cleaner": "^0.1.1", - "mimic-fn": "^1.0.0", - "p-is-promise": "^1.1.0" - } - }, - "memory-fs": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", - "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", - "dev": true, - "requires": { - "errno": "^0.1.3", - "readable-stream": "^2.0.1" - } - }, - "micromatch": { - "version": "3.1.10", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", - "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", - "dev": true, - "requires": { - "arr-diff": "^4.0.0", - "array-unique": "^0.3.2", - "braces": "^2.3.1", - "define-property": "^2.0.2", - "extend-shallow": "^3.0.2", - "extglob": "^2.0.4", - "fragment-cache": "^0.2.1", - "kind-of": "^6.0.2", - "nanomatch": "^1.2.9", - "object.pick": "^1.3.0", - "regex-not": "^1.0.0", - "snapdragon": "^0.8.1", - "to-regex": "^3.0.2" - } - }, - "miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", - "dev": true, - "requires": { - "bn.js": "^4.0.0", - "brorand": "^1.0.1" - } - }, - "mimic-fn": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", - "dev": true - }, - "minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "dev": true - }, - "minimalistic-crypto-utils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", - "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", - "dev": true - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true - }, - "mississippi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-2.0.0.tgz", - "integrity": "sha512-zHo8v+otD1J10j/tC+VNoGK9keCuByhKovAvdn74dmxJl9+mWHnx6EMsDN4lgRoMI/eYo2nchAxniIbUPb5onw==", - "dev": true, - "requires": { - "concat-stream": "^1.5.0", - "duplexify": "^3.4.2", - "end-of-stream": "^1.1.0", - "flush-write-stream": "^1.0.0", - "from2": "^2.1.0", - "parallel-transform": "^1.1.0", - "pump": "^2.0.1", - "pumpify": "^1.3.3", - "stream-each": "^1.1.0", - "through2": "^2.0.0" - } - }, - "mixin-deep": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", - "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", - "dev": true, - "requires": { - "for-in": "^1.0.2", - "is-extendable": "^1.0.1" - }, - "dependencies": { - "is-extendable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", - "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", - "dev": true, - "requires": { - "is-plain-object": "^2.0.4" - } - } - } - }, - "mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", - "dev": true, - "requires": { - "minimist": "0.0.8" - } - }, - "move-concurrently": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz", - "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=", - "dev": true, - "requires": { - "aproba": "^1.1.1", - "copy-concurrently": "^1.0.0", - "fs-write-stream-atomic": "^1.0.8", - "mkdirp": "^0.5.1", - "rimraf": "^2.5.4", - "run-queue": "^1.0.3" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "mute-stream": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", - "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", - "dev": true - }, - "nan": { - "version": "2.14.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz", - "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==", - "dev": true, - "optional": true - }, - "nanomatch": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", - "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", - "dev": true, - "requires": { - "arr-diff": "^4.0.0", - "array-unique": "^0.3.2", - "define-property": "^2.0.2", - "extend-shallow": "^3.0.2", - "fragment-cache": "^0.2.1", - "is-windows": "^1.0.2", - "kind-of": "^6.0.2", - "object.pick": "^1.3.0", - "regex-not": "^1.0.0", - "snapdragon": "^0.8.1", - "to-regex": "^3.0.1" - } - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", - "dev": true - }, - "neo-async": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.1.tgz", - "integrity": "sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==", - "dev": true - }, - "nice-try": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", - "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", - "dev": true - }, - "node-libs-browser": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.1.tgz", - "integrity": "sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q==", - "dev": true, - "requires": { - "assert": "^1.1.1", - "browserify-zlib": "^0.2.0", - "buffer": "^4.3.0", - "console-browserify": "^1.1.0", - "constants-browserify": "^1.0.0", - "crypto-browserify": "^3.11.0", - "domain-browser": "^1.1.1", - "events": "^3.0.0", - "https-browserify": "^1.0.0", - "os-browserify": "^0.3.0", - "path-browserify": "0.0.1", - "process": "^0.11.10", - "punycode": "^1.2.4", - "querystring-es3": "^0.2.0", - "readable-stream": "^2.3.3", - "stream-browserify": "^2.0.1", - "stream-http": "^2.7.2", - "string_decoder": "^1.0.0", - "timers-browserify": "^2.0.4", - "tty-browserify": "0.0.0", - "url": "^0.11.0", - "util": "^0.11.0", - "vm-browserify": "^1.0.1" - }, - "dependencies": { - "punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", - "dev": true - }, - "util": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz", - "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", - "dev": true, - "requires": { - "inherits": "2.0.3" - } - } - } - }, - "node-sloc": { - "version": "0.1.11", - "resolved": "https://registry.npmjs.org/node-sloc/-/node-sloc-0.1.11.tgz", - "integrity": "sha512-hKvVhaJliSdKaQ7MosSLPQfefwMd0GhncudU5zAmSk/iXZq2tZVxezSrZrUls5QyKufkRto9S2IMRfTzhKXQAw==", - "dev": true, - "requires": { - "chalk": "^1.1.3", - "graceful-fs": "^4.1.11", - "minimist": "^1.2.0", - "promisify-node": "^0.5.0" - }, - "dependencies": { - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "^2.0.0" - } - } - } - }, - "nodegit-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/nodegit-promise/-/nodegit-promise-4.0.0.tgz", - "integrity": "sha1-VyKxhPLfcycWEGSnkdLoQskWezQ=", - "dev": true, - "requires": { - "asap": "~2.0.3" - } - }, - "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true - }, - "npm-run-path": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", - "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", - "dev": true, - "requires": { - "path-key": "^2.0.0" - } - }, - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - }, - "object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true - }, - "object-copy": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", - "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", - "dev": true, - "requires": { - "copy-descriptor": "^0.1.0", - "define-property": "^0.2.5", - "kind-of": "^3.0.3" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "object-visit": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", - "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", - "dev": true, - "requires": { - "isobject": "^3.0.0" - } - }, - "object.pick": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", - "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", - "dev": true, - "requires": { - "isobject": "^3.0.1" - } - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, - "requires": { - "wrappy": "1" - } - }, - "onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", - "dev": true, - "requires": { - "mimic-fn": "^1.0.0" - } - }, - "optionator": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", - "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", - "dev": true, - "requires": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.4", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "wordwrap": "~1.0.0" - } - }, - "os-browserify": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", - "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", - "dev": true - }, - "os-locale": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.0.1.tgz", - "integrity": "sha512-7g5e7dmXPtzcP4bgsZ8ixDVqA7oWYuEz4lOSujeWyliPai4gfVDiFIcwBg3aGCPnmSGfzOKTK3ccPn0CKv3DBw==", - "dev": true, - "requires": { - "execa": "^0.10.0", - "lcid": "^2.0.0", - "mem": "^4.0.0" - } - }, - "os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", - "dev": true - }, - "p-defer": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", - "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", - "dev": true - }, - "p-finally": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", - "dev": true - }, - "p-is-promise": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-1.1.0.tgz", - "integrity": "sha1-nJRWmJ6fZYgBewQ01WCXZ1w9oF4=", - "dev": true - }, - "p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", - "dev": true, - "requires": { - "p-try": "^1.0.0" - } - }, - "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", - "dev": true, - "requires": { - "p-limit": "^1.1.0" - } - }, - "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true - }, - "pako": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.10.tgz", - "integrity": "sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw==", - "dev": true - }, - "parallel-transform": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.1.0.tgz", - "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", - "dev": true, - "requires": { - "cyclist": "~0.2.2", - "inherits": "^2.0.3", - "readable-stream": "^2.1.5" - } - }, - "parse-asn1": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.5.tgz", - "integrity": "sha512-jkMYn1dcJqF6d5CpU689bq7w/b5ALS9ROVSpQDPrZsqqesUJii9qutvoT5ltGedNXMO2e16YUWIghG9KxaViTQ==", - "dev": true, - "requires": { - "asn1.js": "^4.0.0", - "browserify-aes": "^1.0.0", - "create-hash": "^1.1.0", - "evp_bytestokey": "^1.0.0", - "pbkdf2": "^3.0.3", - "safe-buffer": "^5.1.1" - } - }, - "pascalcase": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", - "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", - "dev": true - }, - "path": { - "version": "0.12.7", - "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", - "integrity": "sha1-1NwqUGxM4hl+tIHr/NWzbAFAsQ8=", - "requires": { - "process": "^0.11.1", - "util": "^0.10.3" - } - }, - "path-browserify": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", - "integrity": "sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ==", - "dev": true - }, - "path-dirname": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", - "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", - "dev": true - }, - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true - }, - "path-is-inside": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", - "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", - "dev": true - }, - "path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", - "dev": true - }, - "pbkdf2": { - "version": "3.0.17", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz", - "integrity": "sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA==", - "dev": true, - "requires": { - "create-hash": "^1.1.2", - "create-hmac": "^1.1.4", - "ripemd160": "^2.0.1", - "safe-buffer": "^5.0.1", - "sha.js": "^2.4.8" - } - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "^2.0.0" - } - }, - "pkg-dir": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", - "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", - "dev": true, - "requires": { - "find-up": "^2.1.0" - } - }, - "pluralize": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", - "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==", - "dev": true - }, - "posix-character-classes": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", - "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", - "dev": true - }, - "prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", - "dev": true - }, - "process": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=" - }, - "process-nextick-args": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", - "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", - "dev": true - }, - "progress": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.0.tgz", - "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=", - "dev": true - }, - "promise-inflight": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", - "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", - "dev": true - }, - "promisify-node": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/promisify-node/-/promisify-node-0.5.0.tgz", - "integrity": "sha512-GR2E4qgCoKFTprhULqP2OP3bl8kHo16XtnqtkHH6be7tPW1yL6rXd15nl3oV2sLTFv1+j6tqoF69VVpFtJ/j+A==", - "dev": true, - "requires": { - "nodegit-promise": "^4.0.0", - "object-assign": "^4.1.1" - } - }, - "prr": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", - "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", - "dev": true - }, - "pseudomap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", - "dev": true - }, - "public-encrypt": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", - "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", - "dev": true, - "requires": { - "bn.js": "^4.1.0", - "browserify-rsa": "^4.0.0", - "create-hash": "^1.1.0", - "parse-asn1": "^5.0.0", - "randombytes": "^2.0.1", - "safe-buffer": "^5.1.2" - }, - "dependencies": { - "safe-buffer": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", - "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", - "dev": true - } - } - }, - "pump": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", - "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", - "dev": true, - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "pumpify": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", - "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", - "dev": true, - "requires": { - "duplexify": "^3.6.0", - "inherits": "^2.0.3", - "pump": "^2.0.0" - } - }, - "punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true - }, - "querystring": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", - "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", - "dev": true - }, - "querystring-es3": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", - "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", - "dev": true - }, - "randombytes": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "dev": true, - "requires": { - "safe-buffer": "^5.1.0" - } - }, - "randomfill": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", - "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", - "dev": true, - "requires": { - "randombytes": "^2.0.5", - "safe-buffer": "^5.1.0" - } - }, - "readable-stream": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.5.tgz", - "integrity": "sha512-tK0yDhrkygt/knjowCUiWP9YdV7c5R+8cR0r/kt9ZhBU906Fs6RpQJCEilamRJj1Nx2rWI6LkW9gKqjTkshhEw==", - "dev": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.0.3", - "util-deprecate": "~1.0.1" - } - }, - "readdirp": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", - "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.11", - "micromatch": "^3.1.10", - "readable-stream": "^2.0.2" - } - }, - "regex-not": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", - "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", - "dev": true, - "requires": { - "extend-shallow": "^3.0.2", - "safe-regex": "^1.1.0" - } - }, - "regexpp": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-1.0.1.tgz", - "integrity": "sha512-8Ph721maXiOYSLtaDGKVmDn5wdsNaF6Px85qFNeMPQq0r8K5Y10tgP6YuR65Ws35n4DvzFcCxEnRNBIXQunzLw==", - "dev": true - }, - "remove-files-webpack-plugin": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/remove-files-webpack-plugin/-/remove-files-webpack-plugin-1.1.3.tgz", - "integrity": "sha512-r53wQ/IlTkmcv11wri71CZ27S+GhFI5SjHbTbaAJbisPC3qGwg87vlA2C5Z1PuVA+aMI8SgimnE4SqI+ZYzu6Q==", - "dev": true - }, - "remove-trailing-separator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", - "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", - "dev": true - }, - "repeat-element": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", - "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", - "dev": true - }, - "repeat-string": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", - "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", - "dev": true - }, - "require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", - "dev": true - }, - "require-main-filename": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", - "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", - "dev": true - }, - "require-uncached": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", - "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", - "dev": true, - "requires": { - "caller-path": "^0.1.0", - "resolve-from": "^1.0.0" - } - }, - "requizzle": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.3.tgz", - "integrity": "sha512-YanoyJjykPxGHii0fZP0uUPEXpvqfBDxWV7s6GKAiiOsiqhX6vHNyW3Qzdmqp/iq/ExbhaGbVrjB4ruEVSM4GQ==", - "dev": true, - "requires": { - "lodash": "^4.17.14" - } - }, - "resolve-cwd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", - "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", - "dev": true, - "requires": { - "resolve-from": "^3.0.0" - }, - "dependencies": { - "resolve-from": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", - "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", - "dev": true - } - } - }, - "resolve-from": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", - "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=", - "dev": true - }, - "resolve-url": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", - "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", - "dev": true - }, - "restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", - "dev": true, - "requires": { - "onetime": "^2.0.0", - "signal-exit": "^3.0.2" - } - }, - "ret": { - "version": "0.1.15", - "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", - "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", - "dev": true - }, - "rimraf": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", - "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", - "dev": true, - "requires": { - "glob": "^7.0.5" - } - }, - "ripemd160": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", - "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", - "dev": true, - "requires": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1" - } - }, - "run-async": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", - "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", - "dev": true, - "requires": { - "is-promise": "^2.1.0" - } - }, - "run-queue": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz", - "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=", - "dev": true, - "requires": { - "aproba": "^1.1.1" - } - }, - "rx-lite": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-4.0.8.tgz", - "integrity": "sha1-Cx4Rr4vESDbwSmQH6S2kJGe3lEQ=", - "dev": true - }, - "rx-lite-aggregates": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz", - "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", - "dev": true, - "requires": { - "rx-lite": "*" - } - }, - "safe-buffer": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", - "dev": true - }, - "safe-regex": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", - "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", - "dev": true, - "requires": { - "ret": "~0.1.10" - } - }, - "schema-utils": { - "version": "0.4.7", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.7.tgz", - "integrity": "sha512-v/iwU6wvwGK8HbU9yi3/nhGzP0yGSuhQMzL6ySiec1FSrZZDkhm4noOSWzrNFo/jEc+SJY6jRTwuwbSXJPDUnQ==", - "dev": true, - "requires": { - "ajv": "^6.1.0", - "ajv-keywords": "^3.1.0" - }, - "dependencies": { - "ajv": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.5.4.tgz", - "integrity": "sha512-4Wyjt8+t6YszqaXnLDfMmG/8AlO5Zbcsy3ATHncCzjW/NoPzAId8AK6749Ybjmdt+kUY1gP60fCu46oDxPv/mg==", - "dev": true, - "requires": { - "fast-deep-equal": "^2.0.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ajv-keywords": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.2.0.tgz", - "integrity": "sha1-6GuBnGAs+IIa1jdBNpjx3sAhhHo=", - "dev": true - }, - "fast-deep-equal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", - "dev": true - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - } - } - }, - "semver": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", - "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==", - "dev": true - }, - "serialize-javascript": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.5.0.tgz", - "integrity": "sha512-Ga8c8NjAAp46Br4+0oZ2WxJCwIzwP60Gq1YPgU+39PiTVxyed/iKE/zyZI6+UlVYH5Q4PaQdHhcegIFPZTUfoQ==", - "dev": true - }, - "set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", - "dev": true - }, - "set-value": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", - "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", - "dev": true, - "requires": { - "extend-shallow": "^2.0.1", - "is-extendable": "^0.1.1", - "is-plain-object": "^2.0.3", - "split-string": "^3.0.1" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - } - } - }, - "setimmediate": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", - "dev": true - }, - "sha.js": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", - "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", - "dev": true, - "requires": { - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "dev": true, - "requires": { - "shebang-regex": "^1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", - "dev": true - }, - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", - "dev": true - }, - "slice-ansi": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", - "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", - "dev": true, - "requires": { - "is-fullwidth-code-point": "^2.0.0" - } - }, - "snapdragon": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", - "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", - "dev": true, - "requires": { - "base": "^0.11.1", - "debug": "^2.2.0", - "define-property": "^0.2.5", - "extend-shallow": "^2.0.1", - "map-cache": "^0.2.2", - "source-map": "^0.5.6", - "source-map-resolve": "^0.5.0", - "use": "^3.1.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - }, - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true - } - } - }, - "snapdragon-node": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", - "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", - "dev": true, - "requires": { - "define-property": "^1.0.0", - "isobject": "^3.0.0", - "snapdragon-util": "^3.0.1" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "dev": true, - "requires": { - "is-descriptor": "^1.0.0" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "dev": true, - "requires": { - "kind-of": "^6.0.0" - } - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "^1.0.0", - "is-data-descriptor": "^1.0.0", - "kind-of": "^6.0.2" - } - } - } - }, - "snapdragon-util": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", - "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", - "dev": true, - "requires": { - "kind-of": "^3.2.0" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "source-list-map": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", - "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==", - "dev": true - }, - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" - }, - "source-map-resolve": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz", - "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", - "dev": true, - "requires": { - "atob": "^2.1.2", - "decode-uri-component": "^0.2.0", - "resolve-url": "^0.2.1", - "source-map-url": "^0.4.0", - "urix": "^0.1.0" - } - }, - "source-map-support": { - "version": "0.5.16", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", - "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "source-map-url": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", - "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", - "dev": true - }, - "split-string": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", - "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", - "dev": true, - "requires": { - "extend-shallow": "^3.0.0" - } - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - }, - "ssri": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-5.3.0.tgz", - "integrity": "sha512-XRSIPqLij52MtgoQavH/x/dU1qVKtWUAAZeOHsR9c2Ddi4XerFy3mc1alf+dLJKl9EUIm/Ht+EowFkTUOA6GAQ==", - "dev": true, - "requires": { - "safe-buffer": "^5.1.1" - } - }, - "static-extend": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", - "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", - "dev": true, - "requires": { - "define-property": "^0.2.5", - "object-copy": "^0.1.0" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "^0.1.0" - } - } - } - }, - "stream-browserify": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.2.tgz", - "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==", - "dev": true, - "requires": { - "inherits": "~2.0.1", - "readable-stream": "^2.0.2" - } - }, - "stream-each": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz", - "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==", - "dev": true, - "requires": { - "end-of-stream": "^1.1.0", - "stream-shift": "^1.0.0" - } - }, - "stream-http": { - "version": "2.8.3", - "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz", - "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", - "dev": true, - "requires": { - "builtin-status-codes": "^3.0.0", - "inherits": "^2.0.1", - "readable-stream": "^2.3.6", - "to-arraybuffer": "^1.0.0", - "xtend": "^4.0.0" - }, - "dependencies": { - "readable-stream": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", - "dev": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.0" - } - } - } - }, - "stream-shift": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", - "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=", - "dev": true - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "dev": true, - "requires": { - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^4.0.0" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.0" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, - "requires": { - "ansi-regex": "^3.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true - } - } - }, - "strip-eof": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", - "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", - "dev": true - }, - "strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", - "dev": true - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - }, - "table": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/table/-/table-4.0.2.tgz", - "integrity": "sha512-UUkEAPdSGxtRpiV9ozJ5cMTtYiqz7Ni1OGqLXRCynrvzdtR1p+cfOWe2RJLwvUG8hNanaSRjecIqwOjqeatDsA==", - "dev": true, - "requires": { - "ajv": "^5.2.3", - "ajv-keywords": "^2.1.0", - "chalk": "^2.1.0", - "lodash": "^4.17.4", - "slice-ansi": "1.0.0", - "string-width": "^2.1.1" - } - }, - "taffydb": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", - "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg=", - "dev": true - }, - "tapable": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.0.0.tgz", - "integrity": "sha512-dQRhbNQkRnaqauC7WqSJ21EEksgT0fYZX2lqXzGkpo8JNig9zGZTYoMGvyI2nWmXlE2VSVXVDu7wLVGu/mQEsg==", - "dev": true - }, - "terser": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-4.5.0.tgz", - "integrity": "sha512-UEocwHeNeGFbZ2wHJSidpYu4pkEoRI/tyrjWjGYBL8P3MwKsAtprK5ZbHX1MopkHkTSDm6g6vscLxITFMyE3bw==", - "dev": true, - "requires": { - "commander": "^2.20.0", - "source-map": "~0.6.1", - "source-map-support": "~0.5.12" - }, - "dependencies": { - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true - } - } - }, - "terser-webpack-plugin": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.3.tgz", - "integrity": "sha512-QMxecFz/gHQwteWwSo5nTc6UaICqN1bMedC5sMtUc7y3Ha3Q8y6ZO0iCR8pq4RJC8Hjf0FEPEHZqcMB/+DFCrA==", - "dev": true, - "requires": { - "cacache": "^12.0.2", - "find-cache-dir": "^2.1.0", - "is-wsl": "^1.1.0", - "schema-utils": "^1.0.0", - "serialize-javascript": "^2.1.2", - "source-map": "^0.6.1", - "terser": "^4.1.2", - "webpack-sources": "^1.4.0", - "worker-farm": "^1.7.0" - }, - "dependencies": { - "ajv": { - "version": "6.10.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", - "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", - "dev": true, - "requires": { - "fast-deep-equal": "^2.0.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ajv-keywords": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.1.tgz", - "integrity": "sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ==", - "dev": true - }, - "bluebird": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", - "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", - "dev": true - }, - "cacache": { - "version": "12.0.3", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-12.0.3.tgz", - "integrity": "sha512-kqdmfXEGFepesTuROHMs3MpFLWrPkSSpRqOw80RCflZXy/khxaArvFrQ7uJxSUduzAufc6G0g1VUCOZXxWavPw==", - "dev": true, - "requires": { - "bluebird": "^3.5.5", - "chownr": "^1.1.1", - "figgy-pudding": "^3.5.1", - "glob": "^7.1.4", - "graceful-fs": "^4.1.15", - "infer-owner": "^1.0.3", - "lru-cache": "^5.1.1", - "mississippi": "^3.0.0", - "mkdirp": "^0.5.1", - "move-concurrently": "^1.0.1", - "promise-inflight": "^1.0.1", - "rimraf": "^2.6.3", - "ssri": "^6.0.1", - "unique-filename": "^1.1.1", - "y18n": "^4.0.0" - } - }, - "fast-deep-equal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", - "dev": true - }, - "find-cache-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", - "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", - "dev": true, - "requires": { - "commondir": "^1.0.1", - "make-dir": "^2.0.0", - "pkg-dir": "^3.0.0" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "graceful-fs": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", - "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==", - "dev": true - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "requires": { - "yallist": "^3.0.2" - } - }, - "make-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", - "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", - "dev": true, - "requires": { - "pify": "^4.0.1", - "semver": "^5.6.0" - } - }, - "mississippi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-3.0.0.tgz", - "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==", - "dev": true, - "requires": { - "concat-stream": "^1.5.0", - "duplexify": "^3.4.2", - "end-of-stream": "^1.1.0", - "flush-write-stream": "^1.0.0", - "from2": "^2.1.0", - "parallel-transform": "^1.1.0", - "pump": "^3.0.0", - "pumpify": "^1.3.3", - "stream-each": "^1.1.0", - "through2": "^2.0.0" - } - }, - "p-limit": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.2.tgz", - "integrity": "sha512-WGR+xHecKTr7EbUEhyLSh5Dube9JtdiG78ufaeLxTgpudf/20KqyMioIUZJAezlTIi6evxuoUs9YXc11cU+yzQ==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true - }, - "pify": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", - "dev": true - }, - "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", - "dev": true, - "requires": { - "find-up": "^3.0.0" - } - }, - "pump": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "dev": true, - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "dev": true, - "requires": { - "glob": "^7.1.3" - } - }, - "schema-utils": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", - "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", - "dev": true, - "requires": { - "ajv": "^6.1.0", - "ajv-errors": "^1.0.0", - "ajv-keywords": "^3.1.0" - } - }, - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - }, - "serialize-javascript": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-2.1.2.tgz", - "integrity": "sha512-rs9OggEUF0V4jUSecXazOYsLfu7OGK2qIn3c7IPBiffz32XniEp/TX9Xmc9LQfK2nQ2QKHvZ2oygKUGU0lG4jQ==", - "dev": true - }, - "ssri": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-6.0.1.tgz", - "integrity": "sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA==", - "dev": true, - "requires": { - "figgy-pudding": "^3.5.1" - } - }, - "webpack-sources": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.4.3.tgz", - "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==", - "dev": true, - "requires": { - "source-list-map": "^2.0.0", - "source-map": "~0.6.1" - } - }, - "worker-farm": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.7.0.tgz", - "integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==", - "dev": true, - "requires": { - "errno": "~0.1.7" - } - }, - "yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true - } - } - }, - "text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", - "dev": true - }, - "through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", - "dev": true - }, - "through2": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.3.tgz", - "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", - "dev": true, - "requires": { - "readable-stream": "^2.1.5", - "xtend": "~4.0.1" - } - }, - "timers-browserify": { - "version": "2.0.11", - "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.11.tgz", - "integrity": "sha512-60aV6sgJ5YEbzUdn9c8kYGIqOubPoUdqQCul3SBAsRCZ40s6Y5cMcrW4dt3/k/EsbLVJNl9n6Vz3fTc+k2GeKQ==", - "dev": true, - "requires": { - "setimmediate": "^1.0.4" - } - }, - "tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "dev": true, - "requires": { - "os-tmpdir": "~1.0.2" - } - }, - "to-arraybuffer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", - "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", - "dev": true - }, - "to-object-path": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", - "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", - "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } - }, - "to-regex": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", - "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", - "dev": true, - "requires": { - "define-property": "^2.0.2", - "extend-shallow": "^3.0.2", - "regex-not": "^1.0.2", - "safe-regex": "^1.1.0" - } - }, - "to-regex-range": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", - "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", - "dev": true, - "requires": { - "is-number": "^3.0.0", - "repeat-string": "^1.6.1" - } - }, - "tslib": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", - "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==", - "dev": true - }, - "tty-browserify": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", - "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", - "dev": true - }, - "type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2" - } - }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", - "dev": true - }, - "typescript": { - "version": "3.4.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.4.5.tgz", - "integrity": "sha512-YycBxUb49UUhdNMU5aJ7z5Ej2XGmaIBL0x34vZ82fn3hGvD+bgrMrVDpatgz2f7YxUMJxMkbWxJZeAvDxVe7Vw==", - "dev": true - }, - "uc.micro": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", - "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", - "dev": true - }, - "uglify-es": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/uglify-es/-/uglify-es-3.3.9.tgz", - "integrity": "sha512-r+MU0rfv4L/0eeW3xZrd16t4NZfK8Ld4SWVglYBb7ez5uXFWHuVRs6xCTrf1yirs9a4j4Y27nn7SRfO6v67XsQ==", - "dev": true, - "requires": { - "commander": "~2.13.0", - "source-map": "~0.6.1" - } - }, - "uglifyjs-webpack-plugin": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-1.3.0.tgz", - "integrity": "sha512-ovHIch0AMlxjD/97j9AYovZxG5wnHOPkL7T1GKochBADp/Zwc44pEWNqpKl1Loupp1WhFg7SlYmHZRUfdAacgw==", - "dev": true, - "requires": { - "cacache": "^10.0.4", - "find-cache-dir": "^1.0.0", - "schema-utils": "^0.4.5", - "serialize-javascript": "^1.4.0", - "source-map": "^0.6.1", - "uglify-es": "^3.3.4", - "webpack-sources": "^1.1.0", - "worker-farm": "^1.5.2" - } - }, - "underscore": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.9.1.tgz", - "integrity": "sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg==", - "dev": true - }, - "union-value": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", - "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", - "dev": true, - "requires": { - "arr-union": "^3.1.0", - "get-value": "^2.0.6", - "is-extendable": "^0.1.1", - "set-value": "^2.0.1" - } - }, - "unique-filename": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", - "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", - "dev": true, - "requires": { - "unique-slug": "^2.0.0" - } - }, - "unique-slug": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.1.tgz", - "integrity": "sha512-n9cU6+gITaVu7VGj1Z8feKMmfAjEAQGhwD9fE3zvpRRa0wEIx8ODYkVGfSc94M2OX00tUFV8wH3zYbm1I8mxFg==", - "dev": true, - "requires": { - "imurmurhash": "^0.1.4" - } - }, - "universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true - }, - "unset-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", - "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", - "dev": true, - "requires": { - "has-value": "^0.3.1", - "isobject": "^3.0.0" - }, - "dependencies": { - "has-value": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", - "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", - "dev": true, - "requires": { - "get-value": "^2.0.3", - "has-values": "^0.1.4", - "isobject": "^2.0.0" - }, - "dependencies": { - "isobject": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "dev": true, - "requires": { - "isarray": "1.0.0" - } - } - } - }, - "has-values": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", - "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", - "dev": true - } - } - }, - "upath": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz", - "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==", - "dev": true - }, - "uri-js": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", - "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", - "dev": true, - "requires": { - "punycode": "^2.1.0" - } - }, - "urix": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", - "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", - "dev": true - }, - "url": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", - "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", - "dev": true, - "requires": { - "punycode": "1.3.2", - "querystring": "0.2.0" - }, - "dependencies": { - "punycode": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", - "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", - "dev": true - } - } - }, - "use": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", - "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", - "dev": true - }, - "util": { - "version": "0.10.4", - "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", - "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", - "requires": { - "inherits": "2.0.3" - } - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "dev": true - }, - "v8-compile-cache": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.2.tgz", - "integrity": "sha512-1wFuMUIM16MDJRCrpbpuEPTUGmM5QMUg0cr3KFwra2XgOgFcPGDQHDh3CszSCD2Zewc/dh/pamNEW8CbfDebUw==", - "dev": true - }, - "vivid-cli": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vivid-cli/-/vivid-cli-1.1.2.tgz", - "integrity": "sha1-o83MkEmVVzBDI1gI4kGBxQg9Fa4=", - "dev": true - }, - "vm-browserify": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", - "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==", - "dev": true - }, - "watchpack": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", - "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", - "dev": true, - "requires": { - "chokidar": "^2.0.2", - "graceful-fs": "^4.1.2", - "neo-async": "^2.5.0" - } - }, - "webpack": { - "version": "4.41.5", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.41.5.tgz", - "integrity": "sha512-wp0Co4vpyumnp3KlkmpM5LWuzvZYayDwM2n17EHFr4qxBBbRokC7DJawPJC7TfSFZ9HZ6GsdH40EBj4UV0nmpw==", - "dev": true, - "requires": { - "@webassemblyjs/ast": "1.8.5", - "@webassemblyjs/helper-module-context": "1.8.5", - "@webassemblyjs/wasm-edit": "1.8.5", - "@webassemblyjs/wasm-parser": "1.8.5", - "acorn": "^6.2.1", - "ajv": "^6.10.2", - "ajv-keywords": "^3.4.1", - "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^4.1.0", - "eslint-scope": "^4.0.3", - "json-parse-better-errors": "^1.0.2", - "loader-runner": "^2.4.0", - "loader-utils": "^1.2.3", - "memory-fs": "^0.4.1", - "micromatch": "^3.1.10", - "mkdirp": "^0.5.1", - "neo-async": "^2.6.1", - "node-libs-browser": "^2.2.1", - "schema-utils": "^1.0.0", - "tapable": "^1.1.3", - "terser-webpack-plugin": "^1.4.3", - "watchpack": "^1.6.0", - "webpack-sources": "^1.4.1" - }, - "dependencies": { - "acorn": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.0.tgz", - "integrity": "sha512-gac8OEcQ2Li1dxIEWGZzsp2BitJxwkwcOm0zHAJLcPJaVvm58FRnk6RkuLRpU1EujipU2ZFODv2P9DLMfnV8mw==", - "dev": true - }, - "ajv": { - "version": "6.10.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", - "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", - "dev": true, - "requires": { - "fast-deep-equal": "^2.0.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ajv-keywords": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.1.tgz", - "integrity": "sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ==", - "dev": true - }, - "big.js": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", - "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", - "dev": true - }, - "eslint-scope": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", - "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", - "dev": true, - "requires": { - "esrecurse": "^4.1.0", - "estraverse": "^4.1.1" - } - }, - "fast-deep-equal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", - "dev": true - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, - "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", - "dev": true, - "requires": { - "minimist": "^1.2.0" - } - }, - "loader-utils": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", - "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", - "dev": true, - "requires": { - "big.js": "^5.2.2", - "emojis-list": "^2.0.0", - "json5": "^1.0.1" - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true - }, - "schema-utils": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", - "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", - "dev": true, - "requires": { - "ajv": "^6.1.0", - "ajv-errors": "^1.0.0", - "ajv-keywords": "^3.1.0" - } - }, - "tapable": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz", - "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==", - "dev": true - }, - "webpack-sources": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.4.3.tgz", - "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==", - "dev": true, - "requires": { - "source-list-map": "^2.0.0", - "source-map": "~0.6.1" - } - } - } - }, - "webpack-cli": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.1.2.tgz", - "integrity": "sha512-Cnqo7CeqeSvC6PTdts+dywNi5CRlIPbLx1AoUPK2T6vC1YAugMG3IOoO9DmEscd+Dghw7uRlnzV1KwOe5IrtgQ==", - "dev": true, - "requires": { - "chalk": "^2.4.1", - "cross-spawn": "^6.0.5", - "enhanced-resolve": "^4.1.0", - "global-modules-path": "^2.3.0", - "import-local": "^2.0.0", - "interpret": "^1.1.0", - "loader-utils": "^1.1.0", - "supports-color": "^5.5.0", - "v8-compile-cache": "^2.0.2", - "yargs": "^12.0.2" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha1-Sl7Hxk364iw6FBJNus3uhG2Ay8Q=", - "dev": true, - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "webpack-shell-plugin": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/webpack-shell-plugin/-/webpack-shell-plugin-0.5.0.tgz", - "integrity": "sha1-Kbih2A3erg3bEOcpZn9yhlPCx0I=", - "dev": true - }, - "webpack-sources": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.3.0.tgz", - "integrity": "sha512-OiVgSrbGu7NEnEvQJJgdSFPl2qWKkWq5lHMhgiToIiN9w34EBnjYzSYs+VbL5KoYiLNtFFa7BZIKxRED3I32pA==", - "dev": true, - "requires": { - "source-list-map": "^2.0.0", - "source-map": "~0.6.1" - } - }, - "which": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", - "integrity": "sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg==", - "dev": true, - "requires": { - "isexe": "^2.0.0" - } - }, - "which-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "dev": true - }, - "wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", - "dev": true - }, - "worker-farm": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.6.0.tgz", - "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", - "dev": true, - "requires": { - "errno": "~0.1.7" - } - }, - "wrap-ansi": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", - "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", - "dev": true, - "requires": { - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1" - }, - "dependencies": { - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "dev": true, - "requires": { - "number-is-nan": "^1.0.0" - } - }, - "string-width": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", - "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "^2.0.0" - } - } - } - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true - }, - "write": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", - "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", - "dev": true, - "requires": { - "mkdirp": "^0.5.1" - } - }, - "xmlcreate": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.1.tgz", - "integrity": "sha512-MjGsXhKG8YjTKrDCXseFo3ClbMGvUD4en29H2Cev1dv4P/chlpw6KdYmlCWDkhosBVKRDjM836+3e3pm1cBNJA==", - "dev": true - }, - "xregexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-4.0.0.tgz", - "integrity": "sha512-PHyM+sQouu7xspQQwELlGwwd05mXUFqwFYfqPO0cC7x4fxyHnnuetmQr6CjJiafIDoH4MogHb9dOoJzR/Y4rFg==", - "dev": true - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - }, - "y18n": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", - "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", - "dev": true - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - }, - "yargs": { - "version": "12.0.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.2.tgz", - "integrity": "sha512-e7SkEx6N6SIZ5c5H22RTZae61qtn3PYUE8JYbBFlK9sYmh3DMQ6E5ygtaG/2BW0JZi4WGgTR2IV5ChqlqrDGVQ==", - "dev": true, - "requires": { - "cliui": "^4.0.0", - "decamelize": "^2.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^1.0.1", - "os-locale": "^3.0.0", - "require-directory": "^2.1.1", - "require-main-filename": "^1.0.1", - "set-blocking": "^2.0.0", - "string-width": "^2.0.0", - "which-module": "^2.0.0", - "y18n": "^3.2.1 || ^4.0.0", - "yargs-parser": "^10.1.0" - }, - "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.0.0.tgz", - "integrity": "sha512-fl5s52lI5ahKCernzzIyAP0QAZbGIovtVHGwpcu1Jr/EpzLVDI2myISHwGqK7m8uQFugVWSrbxH7XnhGtvEc+A==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.0.0.tgz", - "integrity": "sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==", - "dev": true - } - } - }, - "yargs-parser": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-10.1.0.tgz", - "integrity": "sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==", - "dev": true, - "requires": { - "camelcase": "^4.1.0" - } - } - } -} +{ + "name": "phaser", + "version": "3.22.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/parser": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.7.3.tgz", + "integrity": "sha512-bqv+iCo9i+uLVbI0ILzKkvMorqxouI+GbV13ivcARXn9NNEabi2IEz912IgNpT/60BNXac5dgcfjb94NjsF33A==", + "dev": true + }, + "@webassemblyjs/ast": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.8.5.tgz", + "integrity": "sha512-aJMfngIZ65+t71C3y2nBBg5FFG0Okt9m0XEgWZ7Ywgn1oMAT8cNwx00Uv1cQyHtidq0Xn94R4TAywO+LCQ+ZAQ==", + "dev": true, + "requires": { + "@webassemblyjs/helper-module-context": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/wast-parser": "1.8.5" + } + }, + "@webassemblyjs/floating-point-hex-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.8.5.tgz", + "integrity": "sha512-9p+79WHru1oqBh9ewP9zW95E3XAo+90oth7S5Re3eQnECGq59ly1Ri5tsIipKGpiStHsUYmY3zMLqtk3gTcOtQ==", + "dev": true + }, + "@webassemblyjs/helper-api-error": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.8.5.tgz", + "integrity": "sha512-Za/tnzsvnqdaSPOUXHyKJ2XI7PDX64kWtURyGiJJZKVEdFOsdKUCPTNEVFZq3zJ2R0G5wc2PZ5gvdTRFgm81zA==", + "dev": true + }, + "@webassemblyjs/helper-buffer": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.8.5.tgz", + "integrity": "sha512-Ri2R8nOS0U6G49Q86goFIPNgjyl6+oE1abW1pS84BuhP1Qcr5JqMwRFT3Ah3ADDDYGEgGs1iyb1DGX+kAi/c/Q==", + "dev": true + }, + "@webassemblyjs/helper-code-frame": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.8.5.tgz", + "integrity": "sha512-VQAadSubZIhNpH46IR3yWO4kZZjMxN1opDrzePLdVKAZ+DFjkGD/rf4v1jap744uPVU6yjL/smZbRIIJTOUnKQ==", + "dev": true, + "requires": { + "@webassemblyjs/wast-printer": "1.8.5" + } + }, + "@webassemblyjs/helper-fsm": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.8.5.tgz", + "integrity": "sha512-kRuX/saORcg8se/ft6Q2UbRpZwP4y7YrWsLXPbbmtepKr22i8Z4O3V5QE9DbZK908dh5Xya4Un57SDIKwB9eow==", + "dev": true + }, + "@webassemblyjs/helper-module-context": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.8.5.tgz", + "integrity": "sha512-/O1B236mN7UNEU4t9X7Pj38i4VoU8CcMHyy3l2cV/kIF4U5KoHXDVqcDuOs1ltkac90IM4vZdHc52t1x8Yfs3g==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "mamacro": "^0.0.3" + } + }, + "@webassemblyjs/helper-wasm-bytecode": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.8.5.tgz", + "integrity": "sha512-Cu4YMYG3Ddl72CbmpjU/wbP6SACcOPVbHN1dI4VJNJVgFwaKf1ppeFJrwydOG3NDHxVGuCfPlLZNyEdIYlQ6QQ==", + "dev": true + }, + "@webassemblyjs/helper-wasm-section": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.8.5.tgz", + "integrity": "sha512-VV083zwR+VTrIWWtgIUpqfvVdK4ff38loRmrdDBgBT8ADXYsEZ5mPQ4Nde90N3UYatHdYoDIFb7oHzMncI02tA==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5" + } + }, + "@webassemblyjs/ieee754": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.8.5.tgz", + "integrity": "sha512-aaCvQYrvKbY/n6wKHb/ylAJr27GglahUO89CcGXMItrOBqRarUMxWLJgxm9PJNuKULwN5n1csT9bYoMeZOGF3g==", + "dev": true, + "requires": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "@webassemblyjs/leb128": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.8.5.tgz", + "integrity": "sha512-plYUuUwleLIziknvlP8VpTgO4kqNaH57Y3JnNa6DLpu/sGcP6hbVdfdX5aHAV716pQBKrfuU26BJK29qY37J7A==", + "dev": true, + "requires": { + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/utf8": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.8.5.tgz", + "integrity": "sha512-U7zgftmQriw37tfD934UNInokz6yTmn29inT2cAetAsaU9YeVCveWEwhKL1Mg4yS7q//NGdzy79nlXh3bT8Kjw==", + "dev": true + }, + "@webassemblyjs/wasm-edit": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.8.5.tgz", + "integrity": "sha512-A41EMy8MWw5yvqj7MQzkDjU29K7UJq1VrX2vWLzfpRHt3ISftOXqrtojn7nlPsZ9Ijhp5NwuODuycSvfAO/26Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/helper-wasm-section": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5", + "@webassemblyjs/wasm-opt": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5", + "@webassemblyjs/wast-printer": "1.8.5" + } + }, + "@webassemblyjs/wasm-gen": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.8.5.tgz", + "integrity": "sha512-BCZBT0LURC0CXDzj5FXSc2FPTsxwp3nWcqXQdOZE4U7h7i8FqtFK5Egia6f9raQLpEKT1VL7zr4r3+QX6zArWg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/ieee754": "1.8.5", + "@webassemblyjs/leb128": "1.8.5", + "@webassemblyjs/utf8": "1.8.5" + } + }, + "@webassemblyjs/wasm-opt": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.8.5.tgz", + "integrity": "sha512-HKo2mO/Uh9A6ojzu7cjslGaHaUU14LdLbGEKqTR7PBKwT6LdPtLLh9fPY33rmr5wcOMrsWDbbdCHq4hQUdd37Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5" + } + }, + "@webassemblyjs/wasm-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.8.5.tgz", + "integrity": "sha512-pi0SYE9T6tfcMkthwcgCpL0cM9nRYr6/6fjgDtL6q/ZqKHdMWvxitRi5JcZ7RI4SNJJYnYNaWy5UUrHQy998lw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-api-error": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/ieee754": "1.8.5", + "@webassemblyjs/leb128": "1.8.5", + "@webassemblyjs/utf8": "1.8.5" + } + }, + "@webassemblyjs/wast-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.8.5.tgz", + "integrity": "sha512-daXC1FyKWHF1i11obK086QRlsMsY4+tIOKgBqI1lxAnkp9xe9YMcgOxm9kLe+ttjs5aWV2KKE1TWJCN57/Btsg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/floating-point-hex-parser": "1.8.5", + "@webassemblyjs/helper-api-error": "1.8.5", + "@webassemblyjs/helper-code-frame": "1.8.5", + "@webassemblyjs/helper-fsm": "1.8.5", + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/wast-printer": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.8.5.tgz", + "integrity": "sha512-w0U0pD4EhlnvRyeJzBqaVSJAo9w/ce7/WPogeXLzGkO6hzhr4GnQIZ4W4uUt5b9ooAaXPtnXlj0gzsXEOUNYMg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/wast-parser": "1.8.5", + "@xtuc/long": "4.2.2" + } + }, + "@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "acorn": { + "version": "5.5.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.5.3.tgz", + "integrity": "sha512-jd5MkIUlbbmb07nXH0DT3y7rDVtkzDi4XZOUVWAer8ajmF/DTSSbl5oNFyDOl/OXA33Bl79+ypHhl2pN20VeOQ==", + "dev": true + }, + "acorn-jsx": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", + "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", + "dev": true, + "requires": { + "acorn": "^3.0.4" + }, + "dependencies": { + "acorn": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", + "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=", + "dev": true + } + } + }, + "ajv": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", + "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", + "dev": true, + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" + } + }, + "ajv-errors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ajv-errors/-/ajv-errors-1.0.1.tgz", + "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==", + "dev": true + }, + "ajv-keywords": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", + "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=", + "dev": true + }, + "ansi-escapes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", + "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==", + "dev": true + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "dev": true, + "requires": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + }, + "dependencies": { + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + } + } + }, + "aproba": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", + "dev": true + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=", + "dev": true + }, + "asn1.js": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.0.tgz", + "integrity": "sha512-EDsgawzwoun2CZkCgtxJbv392v4nbk9XDD06zI+kQYoBM/3RBWLlEyJARDOmhAAosBjWACEkKL6S+lIZtcAubA==", + "dev": true, + "requires": { + "object-assign": "^4.1.1", + "util": "0.10.3" + }, + "dependencies": { + "inherits": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=", + "dev": true + }, + "util": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", + "dev": true, + "requires": { + "inherits": "2.0.1" + } + } + } + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, + "async-each": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz", + "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==", + "dev": true + }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "^1.1.3", + "esutils": "^2.0.2", + "js-tokens": "^3.0.2" + }, + "dependencies": { + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "base64-js": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz", + "integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==", + "dev": true + }, + "big.js": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", + "integrity": "sha512-+hN/Zh2D08Mx65pZ/4g5bsmNiZUuChDiQfTUQ7qJr4/kuopCr88xZsAXv6mBoZEsUI4OuGHlX59qE94K2mMW8Q==" + }, + "binary-extensions": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz", + "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==", + "dev": true + }, + "bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "dev": true, + "optional": true, + "requires": { + "file-uri-to-path": "1.0.0" + } + }, + "bluebird": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.2.tgz", + "integrity": "sha512-dhHTWMI7kMx5whMQntl7Vr9C6BvV10lFXDAasnqnrMYhXVCzzk6IO9Fo2L75jXHT07WrOngL1WDXOp+yYS91Yg==", + "dev": true + }, + "bn.js": { + "version": "4.11.8", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", + "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", + "dev": true + }, + "browserify-aes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "dev": true, + "requires": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "dev": true, + "requires": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "browserify-des": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", + "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "dev": true + } + } + }, + "browserify-rsa": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + } + }, + "browserify-sign": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz", + "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", + "dev": true, + "requires": { + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" + } + }, + "browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "dev": true, + "requires": { + "pako": "~1.0.5" + } + }, + "buffer": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz", + "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==", + "dev": true, + "requires": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "buffer-from": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.0.0.tgz", + "integrity": "sha512-83apNb8KK0Se60UE1+4Ukbe3HbfELJ6UlI4ldtOGs7So4KD26orJM8hIY9lxdzP+UpItH1Yh/Y8GUvNFWFFRxA==", + "dev": true + }, + "buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "dev": true + }, + "builtin-status-codes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", + "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=", + "dev": true + }, + "cacache": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-10.0.4.tgz", + "integrity": "sha512-Dph0MzuH+rTQzGPNT9fAnrPmMmjKfST6trxJeK7NQuHRaVw24VzPRWTmg9MpcwOVQZO0E1FBICUlFeNaKPIfHA==", + "dev": true, + "requires": { + "bluebird": "^3.5.1", + "chownr": "^1.0.1", + "glob": "^7.1.2", + "graceful-fs": "^4.1.11", + "lru-cache": "^4.1.1", + "mississippi": "^2.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.2", + "ssri": "^5.2.4", + "unique-filename": "^1.1.0", + "y18n": "^4.0.0" + } + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "caller-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", + "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", + "dev": true, + "requires": { + "callsites": "^0.2.0" + } + }, + "callsites": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz", + "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=", + "dev": true + }, + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "dev": true + }, + "catharsis": { + "version": "0.8.11", + "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.11.tgz", + "integrity": "sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g==", + "dev": true, + "requires": { + "lodash": "^4.17.14" + } + }, + "chalk": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.2.tgz", + "integrity": "sha512-ZM4j2/ld/YZDc3Ma8PgN7gyAk+kHMMMyzLNryCPGhWrsfAuDVeuid5bpRFTDgMH9JBK2lA4dyyAkkZYF/WcqDQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "supports-color": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.3.0.tgz", + "integrity": "sha512-0aP01LLIskjKs3lq52EC0aGBAJhLq7B2Rd8HC/DR/PtNNpcLilNmHC12O+hu0usQpo7wtHNRqtrhBwtDb0+dNg==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "chardet": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz", + "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=", + "dev": true + }, + "chokidar": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.8.tgz", + "integrity": "sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg==", + "dev": true, + "requires": { + "anymatch": "^2.0.0", + "async-each": "^1.0.1", + "braces": "^2.3.2", + "fsevents": "^1.2.7", + "glob-parent": "^3.1.0", + "inherits": "^2.0.3", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "normalize-path": "^3.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.2.1", + "upath": "^1.1.1" + } + }, + "chownr": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", + "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==", + "dev": true + }, + "chrome-trace-event": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz", + "integrity": "sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "circular-json": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", + "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==", + "dev": true + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "clean-webpack-plugin": { + "version": "0.1.19", + "resolved": "https://registry.npmjs.org/clean-webpack-plugin/-/clean-webpack-plugin-0.1.19.tgz", + "integrity": "sha512-M1Li5yLHECcN2MahoreuODul5LkjohJGFxLPTjl3j1ttKrF5rgjZET1SJduuqxLAuT1gAPOdkhg03qcaaU1KeA==", + "dev": true, + "requires": { + "rimraf": "^2.6.1" + } + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "dev": true, + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "dev": true + }, + "cliui": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz", + "integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==", + "dev": true, + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" + } + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color-convert": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.1.tgz", + "integrity": "sha512-mjGanIiwQJskCC18rPR6OmrZ6fm2Lc7PeGFYwCmy5J34wC6F1PzdGL6xeMfmgicfYcNLGuVFA3WzXtIDCQSZxQ==", + "dev": true, + "requires": { + "color-name": "^1.1.1" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "commander": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.13.0.tgz", + "integrity": "sha512-MVuS359B+YzaWqjCL/c+22gfryv+mCBPHAv3zyVI2GN8EY6IRP8VwtasXn8jyyhvvq84R4ImN1OKRtcbIasjYA==", + "dev": true + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "console-browserify": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.2.0.tgz", + "integrity": "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==", + "dev": true + }, + "constants-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=", + "dev": true + }, + "copy-concurrently": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/copy-concurrently/-/copy-concurrently-1.0.5.tgz", + "integrity": "sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + } + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "create-ecdh": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.3.tgz", + "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" + } + }, + "create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "dev": true, + "requires": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + } + }, + "cyclist": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-0.2.2.tgz", + "integrity": "sha1-GzN5LhHpFKL9bW7WRHRkRE5fpkA=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-2.0.0.tgz", + "integrity": "sha512-Ikpp5scV3MSYxY39ymh45ZLEecsTdv/Xj2CaQfI8RLMuwi7XvjX9H/fhraiSuU+C5w5NTDu4ZU72xNiZnurBPg==", + "dev": true, + "requires": { + "xregexp": "4.0.0" + } + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "del": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", + "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", + "dev": true, + "requires": { + "globby": "^5.0.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "rimraf": "^2.2.8" + } + }, + "des.js": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", + "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "diffie-hellman": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", + "dev": true + }, + "dts-dom": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/dts-dom/-/dts-dom-3.5.0.tgz", + "integrity": "sha512-73WTIRTIgcvd44QNfNKi9Flh9JAFSLY4hknv/tGD8V6W91EsbMpsSu+kuG9ShsHzG79sHY/iWo2QR2PJTIxLZQ==", + "dev": true + }, + "duplexify": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.6.1.tgz", + "integrity": "sha512-vM58DwdnKmty+FSPzT14K9JXb90H+j5emaR4KYbr2KTIz00WHGbWOe5ghQTx233ZCLZtrGDALzKwcjEtSt35mA==", + "dev": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "elliptic": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.2.tgz", + "integrity": "sha512-f4x70okzZbIQl/NSRLkI/+tteV/9WqL98zx+SQ69KbXxmVrmjwsNUPn/gYJJ0sHvEak24cZgHIPegRePAtA/xw==", + "dev": true, + "requires": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + } + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=" + }, + "end-of-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "dev": true, + "requires": { + "once": "^1.4.0" + } + }, + "enhanced-resolve": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz", + "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "tapable": "^1.0.0" + } + }, + "entities": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", + "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==", + "dev": true + }, + "errno": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", + "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "dev": true, + "requires": { + "prr": "~1.0.1" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "eslint": { + "version": "4.19.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-4.19.1.tgz", + "integrity": "sha512-bT3/1x1EbZB7phzYu7vCr1v3ONuzDtX8WjuM9c0iYxe+cq+pwcKEoQjl7zd3RpC6YOLgnSy3cTN58M2jcoPDIQ==", + "dev": true, + "requires": { + "ajv": "^5.3.0", + "babel-code-frame": "^6.22.0", + "chalk": "^2.1.0", + "concat-stream": "^1.6.0", + "cross-spawn": "^5.1.0", + "debug": "^3.1.0", + "doctrine": "^2.1.0", + "eslint-scope": "^3.7.1", + "eslint-visitor-keys": "^1.0.0", + "espree": "^3.5.4", + "esquery": "^1.0.0", + "esutils": "^2.0.2", + "file-entry-cache": "^2.0.0", + "functional-red-black-tree": "^1.0.1", + "glob": "^7.1.2", + "globals": "^11.0.1", + "ignore": "^3.3.3", + "imurmurhash": "^0.1.4", + "inquirer": "^3.0.6", + "is-resolvable": "^1.0.0", + "js-yaml": "^3.9.1", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.4", + "minimatch": "^3.0.2", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.2", + "pluralize": "^7.0.0", + "progress": "^2.0.0", + "regexpp": "^1.0.1", + "require-uncached": "^1.0.3", + "semver": "^5.3.0", + "strip-ansi": "^4.0.0", + "strip-json-comments": "~2.0.1", + "table": "4.0.2", + "text-table": "~0.2.0" + } + }, + "eslint-plugin-es5": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-es5/-/eslint-plugin-es5-1.3.1.tgz", + "integrity": "sha512-2oq0R/3XoAsiMwllwsHmnk0gA7+KSvRHUAiJ7Pa/iKrClywVd1q/G7LDZHXU5YD+9kVNxlK155ElXrmX8uLW8A==", + "dev": true + }, + "eslint-scope": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz", + "integrity": "sha1-PWPD7f2gLgbgGkUq2IyqzHzctug=", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "dev": true + }, + "espree": { + "version": "3.5.4", + "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.4.tgz", + "integrity": "sha512-yAcIQxtmMiB/jL32dzEp2enBeidsB7xWPLNiw3IIkpVds1P+h7qF9YwJq1yUNzp2OKXgAprs4F61ih66UsoD1A==", + "dev": true, + "requires": { + "acorn": "^5.5.0", + "acorn-jsx": "^3.0.0" + } + }, + "esprima": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", + "integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw==", + "dev": true + }, + "esquery": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.0.tgz", + "integrity": "sha1-z7qLV9f7qT8XKYqKAGoEzaE9gPo=", + "dev": true, + "requires": { + "estraverse": "^4.0.0" + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eventemitter3": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz", + "integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA==" + }, + "events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.0.0.tgz", + "integrity": "sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA==", + "dev": true + }, + "evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "dev": true, + "requires": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "execa": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.10.0.tgz", + "integrity": "sha512-7XOMnz8Ynx1gGo/3hyV9loYNPWM94jG3+3T3Y8tsfSstFmETmENCMU/A/zj8Lyaj1lkgEepKepvd6240tBRvlw==", + "dev": true, + "requires": { + "cross-spawn": "^6.0.0", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + } + } + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "exports-loader": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/exports-loader/-/exports-loader-0.7.0.tgz", + "integrity": "sha512-RKwCrO4A6IiKm0pG3c9V46JxIHcDplwwGJn6+JJ1RcVnh/WSGJa0xkmk5cRVtgOPzCAtTMGj2F7nluh9L0vpSA==", + "requires": { + "loader-utils": "^1.1.0", + "source-map": "0.5.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.0.tgz", + "integrity": "sha1-D+llA6yGpa213mP05BKuSHLNvoY=" + } + } + }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "external-editor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-2.1.0.tgz", + "integrity": "sha512-E44iT5QVOUJBKij4IIV3uvxuNlbKS38Tw1HiupxEIHPv9qtC2PrDYohbXV5U+1jnfIXttny8gUhj+oZvflFlzA==", + "dev": true, + "requires": { + "chardet": "^0.4.0", + "iconv-lite": "^0.4.17", + "tmp": "^0.0.33" + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "fast-deep-equal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz", + "integrity": "sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ=", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "figgy-pudding": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.1.tgz", + "integrity": "sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w==", + "dev": true + }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-2.0.0.tgz", + "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", + "dev": true, + "requires": { + "flat-cache": "^1.2.1", + "object-assign": "^4.0.1" + } + }, + "file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "dev": true, + "optional": true + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "find-cache-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-1.0.0.tgz", + "integrity": "sha1-kojj6ePMN0hxfTnq3hfPcfww7m8=", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^1.0.0", + "pkg-dir": "^2.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "flat-cache": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.0.tgz", + "integrity": "sha1-0wMLMrOBVPTjt+nHCfSQ9++XxIE=", + "dev": true, + "requires": { + "circular-json": "^0.3.1", + "del": "^2.0.2", + "graceful-fs": "^4.1.2", + "write": "^0.2.1" + } + }, + "flush-write-stream": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.0.3.tgz", + "integrity": "sha512-calZMC10u0FMUqoiunI2AiGIIUtUIvifNwkHhNupZH4cbNnW1Itkoh/Nf5HFYmDrwWPjrUxpkZT0KhuCq0jmGw==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + } + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, + "from2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz", + "integrity": "sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "fs-extra": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-6.0.1.tgz", + "integrity": "sha512-GnyIkKhhzXZUWFCaJzvyDLEEgDkPfb4/TPvJCJVuS8MWZgoSsErf++QpiAlDnKFcqhRlm+tIOcencCjyJE6ZCA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "fs-write-stream-atomic": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz", + "integrity": "sha1-tH31NJPvkR33VzHnCp3tAYnbQMk=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fsevents": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.11.tgz", + "integrity": "sha512-+ux3lx6peh0BpvY0JebGyZoiR4D+oYzdPZMKJwkZ+sFkNJzpL7tXc/wehS49gUAxg3tmMHPHZkA8JU2rhhgDHw==", + "dev": true, + "optional": true, + "requires": { + "bindings": "^1.5.0", + "nan": "^2.12.1", + "node-pre-gyp": "*" + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chownr": { + "version": "1.1.3", + "bundled": true, + "dev": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "debug": { + "version": "3.2.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ms": "^2.1.1" + } + }, + "deep-extend": { + "version": "0.6.0", + "bundled": true, + "dev": true, + "optional": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "detect-libc": { + "version": "1.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "fs-minipass": { + "version": "1.2.7", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.6.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "glob": { + "version": "7.1.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "iconv-lite": { + "version": "0.4.24", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore-walk": { + "version": "3.0.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "bundled": true, + "dev": true, + "optional": true + }, + "ini": { + "version": "1.3.5", + "bundled": true, + "dev": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "bundled": true, + "dev": true, + "optional": true + }, + "minipass": { + "version": "2.9.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.3.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.9.0" + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "needle": { + "version": "2.4.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, + "node-pre-gyp": { + "version": "0.14.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.1", + "needle": "^2.2.1", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.2.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4.4.2" + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "npm-bundled": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npm-normalize-package-bin": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "npm-packlist": { + "version": "1.4.7", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "process-nextick-args": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "rc": { + "version": "1.2.8", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "rimraf": { + "version": "2.7.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "glob": "^7.1.3" + } + }, + "safe-buffer": { + "version": "5.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "sax": { + "version": "1.2.4", + "bundled": true, + "dev": true, + "optional": true + }, + "semver": { + "version": "5.7.1", + "bundled": true, + "dev": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "tar": { + "version": "4.4.13", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.8.6", + "minizlib": "^1.2.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.3" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "wide-align": { + "version": "1.1.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "yallist": { + "version": "3.1.1", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, + "get-caller-file": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", + "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", + "dev": true + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "dev": true + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "dev": true, + "requires": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "global-modules-path": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/global-modules-path/-/global-modules-path-2.3.0.tgz", + "integrity": "sha512-HchvMJNYh9dGSCy8pOQ2O8u/hoXaL+0XhnrwH0RyLiSXMMTl9W3N6KUU73+JFOg5PGjtzl6VZzUQsnrpm7Szag==", + "dev": true + }, + "globals": { + "version": "11.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.4.0.tgz", + "integrity": "sha512-Dyzmifil8n/TmSqYDEXbm+C8yitzJQqQIlJQLNRMwa+BOUJpRC19pyVeN12JAjt61xonvXjtff+hJruTRXn5HA==", + "dev": true + }, + "globby": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", + "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hash-base": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "dev": true, + "requires": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "https-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", + "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=", + "dev": true + }, + "iconv-lite": { + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", + "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==", + "dev": true + }, + "ieee754": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", + "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==", + "dev": true + }, + "iferr": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", + "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=", + "dev": true + }, + "ignore": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.7.tgz", + "integrity": "sha512-YGG3ejvBNHRqu0559EOxxNFihD0AjpvHlC/pdGKd3X3ofe+CoJkYazwNJYTNebqpPKN+VVQbh4ZFn1DivMNuHA==", + "dev": true + }, + "import-local": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz", + "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==", + "dev": true, + "requires": { + "pkg-dir": "^3.0.0", + "resolve-cwd": "^2.0.0" + }, + "dependencies": { + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.0.0.tgz", + "integrity": "sha512-fl5s52lI5ahKCernzzIyAP0QAZbGIovtVHGwpcu1Jr/EpzLVDI2myISHwGqK7m8uQFugVWSrbxH7XnhGtvEc+A==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.0.0.tgz", + "integrity": "sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==", + "dev": true + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + } + } + }, + "imports-loader": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/imports-loader/-/imports-loader-0.8.0.tgz", + "integrity": "sha512-kXWL7Scp8KQ4552ZcdVTeaQCZSLW+e6nJfp3cwUMB673T7Hr98Xjx5JK+ql7ADlJUvj1JS5O01RLbKoutN5QDQ==", + "requires": { + "loader-utils": "^1.0.2", + "source-map": "^0.6.1" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "infer-owner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", + "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "inquirer": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.3.0.tgz", + "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", + "dev": true, + "requires": { + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.0", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^2.0.4", + "figures": "^2.0.0", + "lodash": "^4.3.0", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rx-lite": "^4.0.8", + "rx-lite-aggregates": "^4.0.8", + "string-width": "^2.1.0", + "strip-ansi": "^4.0.0", + "through": "^2.3.6" + } + }, + "interpret": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", + "integrity": "sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=", + "dev": true + }, + "invert-kv": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", + "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", + "dev": true + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-binary-path": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", + "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", + "dev": true, + "requires": { + "binary-extensions": "^1.0.0" + } + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-path-cwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", + "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=", + "dev": true + }, + "is-path-in-cwd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", + "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", + "dev": true, + "requires": { + "is-path-inside": "^1.0.0" + } + }, + "is-path-inside": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "dev": true, + "requires": { + "path-is-inside": "^1.0.1" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", + "dev": true + }, + "is-resolvable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", + "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "js2xmlparser": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.0.tgz", + "integrity": "sha512-WuNgdZOXVmBk5kUPMcTcVUpbGRzLfNkv7+7APq7WiDihpXVKrgxo6wwRpRl9OQeEBgKCVk9mR7RbzrnNWC8oBw==", + "dev": true, + "requires": { + "xmlcreate": "^2.0.0" + } + }, + "jsdoc": { + "version": "3.6.3", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.3.tgz", + "integrity": "sha512-Yf1ZKA3r9nvtMWHO1kEuMZTlHOF8uoQ0vyo5eH7SQy5YeIiHM+B0DgKnn+X6y6KDYZcF7G2SPkKF+JORCXWE/A==", + "dev": true, + "requires": { + "@babel/parser": "^7.4.4", + "bluebird": "^3.5.4", + "catharsis": "^0.8.11", + "escape-string-regexp": "^2.0.0", + "js2xmlparser": "^4.0.0", + "klaw": "^3.0.0", + "markdown-it": "^8.4.2", + "markdown-it-anchor": "^5.0.2", + "marked": "^0.7.0", + "mkdirp": "^0.5.1", + "requizzle": "^0.2.3", + "strip-json-comments": "^3.0.1", + "taffydb": "2.6.2", + "underscore": "~1.9.1" + }, + "dependencies": { + "bluebird": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.1.tgz", + "integrity": "sha512-DdmyoGCleJnkbp3nkbxTLJ18rjDsE4yCggEwKNXkeV123sPNfOCYeDoeuOY+F2FrSjO1YXcTU+dsy96KMy+gcg==", + "dev": true + }, + "escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true + }, + "strip-json-comments": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.0.1.tgz", + "integrity": "sha512-VTyMAUfdm047mwKl+u79WIdrZxtFtn+nBxHeb844XBQ9uMNTuTHdx2hc5RiAJYqwTj3wc/xe5HLSdJSkJ+WfZw==", + "dev": true + } + } + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "json-schema-traverse": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", + "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=", + "dev": true + }, + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "json5": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", + "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=" + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "klaw": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", + "integrity": "sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.9" + } + }, + "lcid": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", + "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", + "dev": true, + "requires": { + "invert-kv": "^2.0.0" + } + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "linkify-it": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz", + "integrity": "sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==", + "dev": true, + "requires": { + "uc.micro": "^1.0.1" + } + }, + "loader-runner": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.4.0.tgz", + "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==", + "dev": true + }, + "loader-utils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", + "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", + "requires": { + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + }, + "lru-cache": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.2.tgz", + "integrity": "sha512-wgeVXhrDwAWnIF/yZARsFnMBtdFXOg1b8RIrhilp+0iDYN4mdQcNZElDZ0e4B64BhaxeQ5zN7PMyvu7we1kPeQ==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "dev": true, + "requires": { + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + } + } + }, + "mamacro": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/mamacro/-/mamacro-0.0.3.tgz", + "integrity": "sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA==", + "dev": true + }, + "map-age-cleaner": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.2.tgz", + "integrity": "sha512-UN1dNocxQq44IhJyMI4TU8phc2m9BddacHRPRjKGLYaF0jqd3xLz0jS0skpAU9WgYyoR4gHtUpzytNBS385FWQ==", + "dev": true, + "requires": { + "p-defer": "^1.0.0" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "^1.0.0" + } + }, + "markdown-it": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-8.4.2.tgz", + "integrity": "sha512-GcRz3AWTqSUphY3vsUqQSFMbgR38a4Lh3GWlHRh/7MRwz8mcu9n2IO7HOh+bXHrR9kOPDl5RNCaEsrneb+xhHQ==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "entities": "~1.1.1", + "linkify-it": "^2.0.0", + "mdurl": "^1.0.1", + "uc.micro": "^1.0.5" + } + }, + "markdown-it-anchor": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.2.5.tgz", + "integrity": "sha512-xLIjLQmtym3QpoY9llBgApknl7pxAcN3WDRc2d3rwpl+/YvDZHPmKscGs+L6E05xf2KrCXPBvosWt7MZukwSpQ==", + "dev": true + }, + "marked": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-0.7.0.tgz", + "integrity": "sha512-c+yYdCZJQrsRjTPhUx7VKkApw9bwDkNbHUKo1ovgcfDjb2kc8rLuRbIFyXL5WOEUwzSSKo3IXpph2K6DqB/KZg==", + "dev": true + }, + "md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "dev": true + } + } + }, + "mdurl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", + "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=", + "dev": true + }, + "mem": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mem/-/mem-4.0.0.tgz", + "integrity": "sha512-WQxG/5xYc3tMbYLXoXPm81ET2WDULiU5FxbuIoNbJqLOOI8zehXFdZuiUEgfdrU2mVB1pxBZUGlYORSrpuJreA==", + "dev": true, + "requires": { + "map-age-cleaner": "^0.1.1", + "mimic-fn": "^1.0.0", + "p-is-promise": "^1.1.0" + } + }, + "memory-fs": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", + "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", + "dev": true, + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + } + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mississippi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-2.0.0.tgz", + "integrity": "sha512-zHo8v+otD1J10j/tC+VNoGK9keCuByhKovAvdn74dmxJl9+mWHnx6EMsDN4lgRoMI/eYo2nchAxniIbUPb5onw==", + "dev": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^2.0.1", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + } + }, + "mixin-deep": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", + "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "move-concurrently": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz", + "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", + "dev": true + }, + "nan": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz", + "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==", + "dev": true, + "optional": true + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "neo-async": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.1.tgz", + "integrity": "sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==", + "dev": true + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node-libs-browser": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.1.tgz", + "integrity": "sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q==", + "dev": true, + "requires": { + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^3.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", + "path-browserify": "0.0.1", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.11.0", + "vm-browserify": "^1.0.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + }, + "util": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz", + "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", + "dev": true, + "requires": { + "inherits": "2.0.3" + } + } + } + }, + "node-sloc": { + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/node-sloc/-/node-sloc-0.1.11.tgz", + "integrity": "sha512-hKvVhaJliSdKaQ7MosSLPQfefwMd0GhncudU5zAmSk/iXZq2tZVxezSrZrUls5QyKufkRto9S2IMRfTzhKXQAw==", + "dev": true, + "requires": { + "chalk": "^1.1.3", + "graceful-fs": "^4.1.11", + "minimist": "^1.2.0", + "promisify-node": "^0.5.0" + }, + "dependencies": { + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "nodegit-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/nodegit-promise/-/nodegit-promise-4.0.0.tgz", + "integrity": "sha1-VyKxhPLfcycWEGSnkdLoQskWezQ=", + "dev": true, + "requires": { + "asap": "~2.0.3" + } + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, + "requires": { + "path-key": "^2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + } + }, + "os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", + "dev": true + }, + "os-locale": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.0.1.tgz", + "integrity": "sha512-7g5e7dmXPtzcP4bgsZ8ixDVqA7oWYuEz4lOSujeWyliPai4gfVDiFIcwBg3aGCPnmSGfzOKTK3ccPn0CKv3DBw==", + "dev": true, + "requires": { + "execa": "^0.10.0", + "lcid": "^2.0.0", + "mem": "^4.0.0" + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "p-defer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", + "dev": true + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, + "p-is-promise": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-1.1.0.tgz", + "integrity": "sha1-nJRWmJ6fZYgBewQ01WCXZ1w9oF4=", + "dev": true + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + }, + "pako": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.10.tgz", + "integrity": "sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw==", + "dev": true + }, + "parallel-transform": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.1.0.tgz", + "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", + "dev": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + } + }, + "parse-asn1": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.5.tgz", + "integrity": "sha512-jkMYn1dcJqF6d5CpU689bq7w/b5ALS9ROVSpQDPrZsqqesUJii9qutvoT5ltGedNXMO2e16YUWIghG9KxaViTQ==", + "dev": true, + "requires": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3", + "safe-buffer": "^5.1.1" + } + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, + "path": { + "version": "0.12.7", + "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", + "integrity": "sha1-1NwqUGxM4hl+tIHr/NWzbAFAsQ8=", + "requires": { + "process": "^0.11.1", + "util": "^0.10.3" + } + }, + "path-browserify": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", + "integrity": "sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ==", + "dev": true + }, + "path-dirname": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", + "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "pbkdf2": { + "version": "3.0.17", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz", + "integrity": "sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA==", + "dev": true, + "requires": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "^2.0.0" + } + }, + "pkg-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", + "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", + "dev": true, + "requires": { + "find-up": "^2.1.0" + } + }, + "pluralize": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", + "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==", + "dev": true + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=" + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "dev": true + }, + "progress": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.0.tgz", + "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=", + "dev": true + }, + "promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", + "dev": true + }, + "promisify-node": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/promisify-node/-/promisify-node-0.5.0.tgz", + "integrity": "sha512-GR2E4qgCoKFTprhULqP2OP3bl8kHo16XtnqtkHH6be7tPW1yL6rXd15nl3oV2sLTFv1+j6tqoF69VVpFtJ/j+A==", + "dev": true, + "requires": { + "nodegit-promise": "^4.0.0", + "object-assign": "^4.1.1" + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", + "dev": true + }, + "public-encrypt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", + "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "dev": true + } + } + }, + "pump": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", + "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", + "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", + "dev": true, + "requires": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", + "dev": true + }, + "querystring-es3": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", + "dev": true + }, + "randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.0" + } + }, + "randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "dev": true, + "requires": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "readable-stream": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.5.tgz", + "integrity": "sha512-tK0yDhrkygt/knjowCUiWP9YdV7c5R+8cR0r/kt9ZhBU906Fs6RpQJCEilamRJj1Nx2rWI6LkW9gKqjTkshhEw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.0.3", + "util-deprecate": "~1.0.1" + } + }, + "readdirp": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", + "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "micromatch": "^3.1.10", + "readable-stream": "^2.0.2" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "regexpp": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-1.0.1.tgz", + "integrity": "sha512-8Ph721maXiOYSLtaDGKVmDn5wdsNaF6Px85qFNeMPQq0r8K5Y10tgP6YuR65Ws35n4DvzFcCxEnRNBIXQunzLw==", + "dev": true + }, + "remove-files-webpack-plugin": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/remove-files-webpack-plugin/-/remove-files-webpack-plugin-1.1.3.tgz", + "integrity": "sha512-r53wQ/IlTkmcv11wri71CZ27S+GhFI5SjHbTbaAJbisPC3qGwg87vlA2C5Z1PuVA+aMI8SgimnE4SqI+ZYzu6Q==", + "dev": true + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "repeat-element": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", + "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", + "dev": true + }, + "require-uncached": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", + "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", + "dev": true, + "requires": { + "caller-path": "^0.1.0", + "resolve-from": "^1.0.0" + } + }, + "requizzle": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.3.tgz", + "integrity": "sha512-YanoyJjykPxGHii0fZP0uUPEXpvqfBDxWV7s6GKAiiOsiqhX6vHNyW3Qzdmqp/iq/ExbhaGbVrjB4ruEVSM4GQ==", + "dev": true, + "requires": { + "lodash": "^4.17.14" + } + }, + "resolve-cwd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", + "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", + "dev": true, + "requires": { + "resolve-from": "^3.0.0" + }, + "dependencies": { + "resolve-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", + "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", + "dev": true + } + } + }, + "resolve-from": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", + "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=", + "dev": true + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "dev": true, + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + } + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "dev": true, + "requires": { + "glob": "^7.0.5" + } + }, + "ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "run-async": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", + "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", + "dev": true, + "requires": { + "is-promise": "^2.1.0" + } + }, + "run-queue": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz", + "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=", + "dev": true, + "requires": { + "aproba": "^1.1.1" + } + }, + "rx-lite": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-4.0.8.tgz", + "integrity": "sha1-Cx4Rr4vESDbwSmQH6S2kJGe3lEQ=", + "dev": true + }, + "rx-lite-aggregates": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz", + "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", + "dev": true, + "requires": { + "rx-lite": "*" + } + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "dev": true + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "schema-utils": { + "version": "0.4.7", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.7.tgz", + "integrity": "sha512-v/iwU6wvwGK8HbU9yi3/nhGzP0yGSuhQMzL6ySiec1FSrZZDkhm4noOSWzrNFo/jEc+SJY6jRTwuwbSXJPDUnQ==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0" + }, + "dependencies": { + "ajv": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.5.4.tgz", + "integrity": "sha512-4Wyjt8+t6YszqaXnLDfMmG/8AlO5Zbcsy3ATHncCzjW/NoPzAId8AK6749Ybjmdt+kUY1gP60fCu46oDxPv/mg==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.2.0.tgz", + "integrity": "sha1-6GuBnGAs+IIa1jdBNpjx3sAhhHo=", + "dev": true + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + } + } + }, + "semver": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", + "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==", + "dev": true + }, + "serialize-javascript": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.5.0.tgz", + "integrity": "sha512-Ga8c8NjAAp46Br4+0oZ2WxJCwIzwP60Gq1YPgU+39PiTVxyed/iKE/zyZI6+UlVYH5Q4PaQdHhcegIFPZTUfoQ==", + "dev": true + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "set-value": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", + "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", + "dev": true + }, + "sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "slice-ansi": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", + "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0" + } + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "dev": true, + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "source-list-map": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", + "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + }, + "source-map-resolve": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz", + "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", + "dev": true, + "requires": { + "atob": "^2.1.2", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-support": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", + "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "ssri": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-5.3.0.tgz", + "integrity": "sha512-XRSIPqLij52MtgoQavH/x/dU1qVKtWUAAZeOHsR9c2Ddi4XerFy3mc1alf+dLJKl9EUIm/Ht+EowFkTUOA6GAQ==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.1" + } + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "stream-browserify": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.2.tgz", + "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==", + "dev": true, + "requires": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + } + }, + "stream-each": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz", + "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + } + }, + "stream-http": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz", + "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", + "dev": true, + "requires": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "stream-shift": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", + "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=", + "dev": true + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "string_decoder": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", + "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + } + } + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/table/-/table-4.0.2.tgz", + "integrity": "sha512-UUkEAPdSGxtRpiV9ozJ5cMTtYiqz7Ni1OGqLXRCynrvzdtR1p+cfOWe2RJLwvUG8hNanaSRjecIqwOjqeatDsA==", + "dev": true, + "requires": { + "ajv": "^5.2.3", + "ajv-keywords": "^2.1.0", + "chalk": "^2.1.0", + "lodash": "^4.17.4", + "slice-ansi": "1.0.0", + "string-width": "^2.1.1" + } + }, + "taffydb": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", + "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg=", + "dev": true + }, + "tapable": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.0.0.tgz", + "integrity": "sha512-dQRhbNQkRnaqauC7WqSJ21EEksgT0fYZX2lqXzGkpo8JNig9zGZTYoMGvyI2nWmXlE2VSVXVDu7wLVGu/mQEsg==", + "dev": true + }, + "terser": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-4.5.0.tgz", + "integrity": "sha512-UEocwHeNeGFbZ2wHJSidpYu4pkEoRI/tyrjWjGYBL8P3MwKsAtprK5ZbHX1MopkHkTSDm6g6vscLxITFMyE3bw==", + "dev": true, + "requires": { + "commander": "^2.20.0", + "source-map": "~0.6.1", + "source-map-support": "~0.5.12" + }, + "dependencies": { + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + } + } + }, + "terser-webpack-plugin": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.3.tgz", + "integrity": "sha512-QMxecFz/gHQwteWwSo5nTc6UaICqN1bMedC5sMtUc7y3Ha3Q8y6ZO0iCR8pq4RJC8Hjf0FEPEHZqcMB/+DFCrA==", + "dev": true, + "requires": { + "cacache": "^12.0.2", + "find-cache-dir": "^2.1.0", + "is-wsl": "^1.1.0", + "schema-utils": "^1.0.0", + "serialize-javascript": "^2.1.2", + "source-map": "^0.6.1", + "terser": "^4.1.2", + "webpack-sources": "^1.4.0", + "worker-farm": "^1.7.0" + }, + "dependencies": { + "ajv": { + "version": "6.10.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", + "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.1.tgz", + "integrity": "sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ==", + "dev": true + }, + "bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true + }, + "cacache": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-12.0.3.tgz", + "integrity": "sha512-kqdmfXEGFepesTuROHMs3MpFLWrPkSSpRqOw80RCflZXy/khxaArvFrQ7uJxSUduzAufc6G0g1VUCOZXxWavPw==", + "dev": true, + "requires": { + "bluebird": "^3.5.5", + "chownr": "^1.1.1", + "figgy-pudding": "^3.5.1", + "glob": "^7.1.4", + "graceful-fs": "^4.1.15", + "infer-owner": "^1.0.3", + "lru-cache": "^5.1.1", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.3", + "ssri": "^6.0.1", + "unique-filename": "^1.1.1", + "y18n": "^4.0.0" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "find-cache-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", + "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^2.0.0", + "pkg-dir": "^3.0.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", + "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "requires": { + "yallist": "^3.0.2" + } + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "mississippi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-3.0.0.tgz", + "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==", + "dev": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^3.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + } + }, + "p-limit": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.2.tgz", + "integrity": "sha512-WGR+xHecKTr7EbUEhyLSh5Dube9JtdiG78ufaeLxTgpudf/20KqyMioIUZJAezlTIi6evxuoUs9YXc11cU+yzQ==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "schema-utils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", + "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + }, + "serialize-javascript": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-2.1.2.tgz", + "integrity": "sha512-rs9OggEUF0V4jUSecXazOYsLfu7OGK2qIn3c7IPBiffz32XniEp/TX9Xmc9LQfK2nQ2QKHvZ2oygKUGU0lG4jQ==", + "dev": true + }, + "ssri": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-6.0.1.tgz", + "integrity": "sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA==", + "dev": true, + "requires": { + "figgy-pudding": "^3.5.1" + } + }, + "webpack-sources": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.4.3.tgz", + "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==", + "dev": true, + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + } + }, + "worker-farm": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.7.0.tgz", + "integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==", + "dev": true, + "requires": { + "errno": "~0.1.7" + } + }, + "yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + } + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "through2": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.3.tgz", + "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", + "dev": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + } + }, + "timers-browserify": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.11.tgz", + "integrity": "sha512-60aV6sgJ5YEbzUdn9c8kYGIqOubPoUdqQCul3SBAsRCZ40s6Y5cMcrW4dt3/k/EsbLVJNl9n6Vz3fTc+k2GeKQ==", + "dev": true, + "requires": { + "setimmediate": "^1.0.4" + } + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, + "to-arraybuffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", + "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", + "dev": true + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + }, + "tslib": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", + "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==", + "dev": true + }, + "tty-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true + }, + "typescript": { + "version": "3.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.4.5.tgz", + "integrity": "sha512-YycBxUb49UUhdNMU5aJ7z5Ej2XGmaIBL0x34vZ82fn3hGvD+bgrMrVDpatgz2f7YxUMJxMkbWxJZeAvDxVe7Vw==", + "dev": true + }, + "uc.micro": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", + "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", + "dev": true + }, + "uglify-es": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/uglify-es/-/uglify-es-3.3.9.tgz", + "integrity": "sha512-r+MU0rfv4L/0eeW3xZrd16t4NZfK8Ld4SWVglYBb7ez5uXFWHuVRs6xCTrf1yirs9a4j4Y27nn7SRfO6v67XsQ==", + "dev": true, + "requires": { + "commander": "~2.13.0", + "source-map": "~0.6.1" + } + }, + "uglifyjs-webpack-plugin": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-1.3.0.tgz", + "integrity": "sha512-ovHIch0AMlxjD/97j9AYovZxG5wnHOPkL7T1GKochBADp/Zwc44pEWNqpKl1Loupp1WhFg7SlYmHZRUfdAacgw==", + "dev": true, + "requires": { + "cacache": "^10.0.4", + "find-cache-dir": "^1.0.0", + "schema-utils": "^0.4.5", + "serialize-javascript": "^1.4.0", + "source-map": "^0.6.1", + "uglify-es": "^3.3.4", + "webpack-sources": "^1.1.0", + "worker-farm": "^1.5.2" + } + }, + "underscore": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.9.1.tgz", + "integrity": "sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg==", + "dev": true + }, + "union-value": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", + "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^2.0.1" + } + }, + "unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "dev": true, + "requires": { + "unique-slug": "^2.0.0" + } + }, + "unique-slug": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.1.tgz", + "integrity": "sha512-n9cU6+gITaVu7VGj1Z8feKMmfAjEAQGhwD9fE3zvpRRa0wEIx8ODYkVGfSc94M2OX00tUFV8wH3zYbm1I8mxFg==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, + "upath": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz", + "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==", + "dev": true + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "dev": true, + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", + "dev": true + } + } + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, + "util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", + "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", + "requires": { + "inherits": "2.0.3" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "v8-compile-cache": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.2.tgz", + "integrity": "sha512-1wFuMUIM16MDJRCrpbpuEPTUGmM5QMUg0cr3KFwra2XgOgFcPGDQHDh3CszSCD2Zewc/dh/pamNEW8CbfDebUw==", + "dev": true + }, + "vivid-cli": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vivid-cli/-/vivid-cli-1.1.2.tgz", + "integrity": "sha1-o83MkEmVVzBDI1gI4kGBxQg9Fa4=", + "dev": true + }, + "vm-browserify": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", + "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==", + "dev": true + }, + "watchpack": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", + "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", + "dev": true, + "requires": { + "chokidar": "^2.0.2", + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" + } + }, + "webpack": { + "version": "4.41.5", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.41.5.tgz", + "integrity": "sha512-wp0Co4vpyumnp3KlkmpM5LWuzvZYayDwM2n17EHFr4qxBBbRokC7DJawPJC7TfSFZ9HZ6GsdH40EBj4UV0nmpw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-module-context": "1.8.5", + "@webassemblyjs/wasm-edit": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5", + "acorn": "^6.2.1", + "ajv": "^6.10.2", + "ajv-keywords": "^3.4.1", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^4.1.0", + "eslint-scope": "^4.0.3", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^2.4.0", + "loader-utils": "^1.2.3", + "memory-fs": "^0.4.1", + "micromatch": "^3.1.10", + "mkdirp": "^0.5.1", + "neo-async": "^2.6.1", + "node-libs-browser": "^2.2.1", + "schema-utils": "^1.0.0", + "tapable": "^1.1.3", + "terser-webpack-plugin": "^1.4.3", + "watchpack": "^1.6.0", + "webpack-sources": "^1.4.1" + }, + "dependencies": { + "acorn": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.0.tgz", + "integrity": "sha512-gac8OEcQ2Li1dxIEWGZzsp2BitJxwkwcOm0zHAJLcPJaVvm58FRnk6RkuLRpU1EujipU2ZFODv2P9DLMfnV8mw==", + "dev": true + }, + "ajv": { + "version": "6.10.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", + "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.1.tgz", + "integrity": "sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ==", + "dev": true + }, + "big.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true + }, + "eslint-scope": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", + "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "loader-utils": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", + "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", + "dev": true, + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^2.0.0", + "json5": "^1.0.1" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "schema-utils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", + "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + } + }, + "tapable": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz", + "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==", + "dev": true + }, + "webpack-sources": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.4.3.tgz", + "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==", + "dev": true, + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + } + } + } + }, + "webpack-cli": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.1.2.tgz", + "integrity": "sha512-Cnqo7CeqeSvC6PTdts+dywNi5CRlIPbLx1AoUPK2T6vC1YAugMG3IOoO9DmEscd+Dghw7uRlnzV1KwOe5IrtgQ==", + "dev": true, + "requires": { + "chalk": "^2.4.1", + "cross-spawn": "^6.0.5", + "enhanced-resolve": "^4.1.0", + "global-modules-path": "^2.3.0", + "import-local": "^2.0.0", + "interpret": "^1.1.0", + "loader-utils": "^1.1.0", + "supports-color": "^5.5.0", + "v8-compile-cache": "^2.0.2", + "yargs": "^12.0.2" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha1-Sl7Hxk364iw6FBJNus3uhG2Ay8Q=", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "webpack-shell-plugin": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/webpack-shell-plugin/-/webpack-shell-plugin-0.5.0.tgz", + "integrity": "sha1-Kbih2A3erg3bEOcpZn9yhlPCx0I=", + "dev": true + }, + "webpack-sources": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.3.0.tgz", + "integrity": "sha512-OiVgSrbGu7NEnEvQJJgdSFPl2qWKkWq5lHMhgiToIiN9w34EBnjYzSYs+VbL5KoYiLNtFFa7BZIKxRED3I32pA==", + "dev": true, + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + } + }, + "which": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", + "integrity": "sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "worker-farm": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.6.0.tgz", + "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", + "dev": true, + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "dev": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "write": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", + "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", + "dev": true, + "requires": { + "mkdirp": "^0.5.1" + } + }, + "xmlcreate": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.1.tgz", + "integrity": "sha512-MjGsXhKG8YjTKrDCXseFo3ClbMGvUD4en29H2Cev1dv4P/chlpw6KdYmlCWDkhosBVKRDjM836+3e3pm1cBNJA==", + "dev": true + }, + "xregexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-4.0.0.tgz", + "integrity": "sha512-PHyM+sQouu7xspQQwELlGwwd05mXUFqwFYfqPO0cC7x4fxyHnnuetmQr6CjJiafIDoH4MogHb9dOoJzR/Y4rFg==", + "dev": true + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + }, + "yargs": { + "version": "12.0.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.2.tgz", + "integrity": "sha512-e7SkEx6N6SIZ5c5H22RTZae61qtn3PYUE8JYbBFlK9sYmh3DMQ6E5ygtaG/2BW0JZi4WGgTR2IV5ChqlqrDGVQ==", + "dev": true, + "requires": { + "cliui": "^4.0.0", + "decamelize": "^2.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^1.0.1", + "os-locale": "^3.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1 || ^4.0.0", + "yargs-parser": "^10.1.0" + }, + "dependencies": { + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.0.0.tgz", + "integrity": "sha512-fl5s52lI5ahKCernzzIyAP0QAZbGIovtVHGwpcu1Jr/EpzLVDI2myISHwGqK7m8uQFugVWSrbxH7XnhGtvEc+A==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.0.0.tgz", + "integrity": "sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==", + "dev": true + } + } + }, + "yargs-parser": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-10.1.0.tgz", + "integrity": "sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==", + "dev": true, + "requires": { + "camelcase": "^4.1.0" + } + } + } +} diff --git a/package.json b/package.json index f9b35fe44..d45a90291 100644 --- a/package.json +++ b/package.json @@ -1,88 +1,88 @@ -{ - "name": "phaser", - "version": "3.23.0-beta1", - "release": "Ginro", - "description": "A fast, free and fun HTML5 Game Framework for Desktop and Mobile web browsers.", - "author": "Richard Davey (http://www.photonstorm.com)", - "homepage": "http://phaser.io", - "bugs": "https://github.com/photonstorm/phaser/issues", - "license": "MIT", - "licenseUrl": "http://www.opensource.org/licenses/mit-license.php", - "main": "./src/phaser.js", - "types": "./types/phaser.d.ts", - "repository": { - "type": "git", - "url": "https://photonstorm@github.com/photonstorm/phaser.git" - }, - "scripts": { - "beta": "npm publish --tag beta", - "help": "node scripts/help.js", - "build": "webpack --config config/webpack.config.js", - "watch": "webpack --watch --config config/webpack.config.js", - "buildfb": "webpack --config config/webpack.fb.config.js", - "watchfb": "webpack --config config/webpack.fb.config.js --watch", - "dist": "webpack --config config/webpack.dist.config.js", - "distT": "webpack --config config/webpack.dist.config.js && npm run toT", - "toT": "@powershell Copy-Item ./dist/phaser.min.js ../phasertest/phaser.min.js", - "toT2": "@powershell Copy-Item ./dist/phaser.js ../phasertest/phaser.min.js", - "distfb": "webpack --config config/webpack.fb.dist.config.js", - "distfull": "npm run dist && npm run distfb", - "plugin.cam3d": "webpack --config plugins/camera3d/webpack.config.js", - "plugin.spine": "webpack --config plugins/spine/webpack.config.js", - "plugin.spine.dist": "webpack --config plugins/spine/webpack.auto.dist.config.js", - "plugin.spine.watch": "webpack --config plugins/spine/webpack.auto.config.js --watch --display-modules", - "plugin.spine.dev": "webpack --config plugins/spine/webpack.auto.config.js", - "plugin.spine.canvas.dist": "webpack --config plugins/spine/webpack.canvas.dist.config.js", - "plugin.spine.canvas.watch": "webpack --config plugins/spine/webpack.canvas.config.js --watch --display-modules", - "plugin.spine.canvas.dev": "webpack --config plugins/spine/webpack.canvas.config.js", - "plugin.spine.webgl.dist": "webpack --config plugins/spine/webpack.webgl.dist.config.js", - "plugin.spine.webgl.watch": "webpack --config plugins/spine/webpack.webgl.config.js --watch --display-modules", - "plugin.spine.webgl.dev": "webpack --config plugins/spine/webpack.webgl.config.js", - "plugin.spine.full": "npm run plugin.spine.dev && npm run plugin.spine.canvas.dev && npm run plugin.spine.webgl.dev", - "plugin.spine.full.dist": "npm run plugin.spine.dist && npm run plugin.spine.canvas.dist && npm run plugin.spine.webgl.dist", - "lint": "eslint --config .eslintrc.json \"src/**/*.js\"", - "lintfix": "eslint --config .eslintrc.json \"src/**/*.js\" --fix", - "sloc": "node-sloc \"./src\" --include-extensions \"js\"", - "bundleshaders": "node scripts/bundle-shaders.js", - "postinstall": "node scripts/support.js", - "build-tsgen": "cd scripts/tsgen && tsc", - "tsgen": "cd scripts/tsgen && jsdoc -c jsdoc-tsd.conf.json", - "test-ts": "cd scripts/tsgen/test && tsc > output.txt", - "ts": "npm run tsgen && npm run test-ts", - "tsdev": "npm run build-tsgen && npm run tsgen && npm run test-ts" - }, - "keywords": [ - "2d", - "HTML5", - "WebGL", - "canvas", - "game", - "javascript", - "physics", - "tweens", - "typescript", - "web audio" - ], - "devDependencies": { - "clean-webpack-plugin": "^0.1.19", - "dts-dom": "^3.3.0", - "eslint": "^4.19.1", - "eslint-plugin-es5": "^1.3.1", - "fs-extra": "^6.0.1", - "jsdoc": "^3.6.3", - "node-sloc": "^0.1.11", - "remove-files-webpack-plugin": "^1.1.3", - "typescript": "^3.4.5", - "uglifyjs-webpack-plugin": "^1.3.0", - "vivid-cli": "^1.1.2", - "webpack": "^4.23.0", - "webpack-cli": "^3.1.1", - "webpack-shell-plugin": "^0.5.0" - }, - "dependencies": { - "eventemitter3": "^3.1.0", - "exports-loader": "^0.7.0", - "imports-loader": "^0.8.0", - "path": "^0.12.7" - } -} +{ + "name": "phaser", + "version": "3.23.0-beta1", + "release": "Ginro", + "description": "A fast, free and fun HTML5 Game Framework for Desktop and Mobile web browsers.", + "author": "Richard Davey (http://www.photonstorm.com)", + "homepage": "http://phaser.io", + "bugs": "https://github.com/photonstorm/phaser/issues", + "license": "MIT", + "licenseUrl": "http://www.opensource.org/licenses/mit-license.php", + "main": "./src/phaser.js", + "types": "./types/phaser.d.ts", + "repository": { + "type": "git", + "url": "https://photonstorm@github.com/photonstorm/phaser.git" + }, + "scripts": { + "beta": "npm publish --tag beta", + "help": "node scripts/help.js", + "build": "webpack --config config/webpack.config.js", + "watch": "webpack --watch --config config/webpack.config.js", + "buildfb": "webpack --config config/webpack.fb.config.js", + "watchfb": "webpack --config config/webpack.fb.config.js --watch", + "dist": "webpack --config config/webpack.dist.config.js", + "distT": "webpack --config config/webpack.dist.config.js && npm run toT", + "toT": "@powershell Copy-Item ./dist/phaser.min.js ../phasertest/phaser.min.js", + "toT2": "@powershell Copy-Item ./dist/phaser.js ../phasertest/phaser.min.js", + "distfb": "webpack --config config/webpack.fb.dist.config.js", + "distfull": "npm run dist && npm run distfb", + "plugin.cam3d": "webpack --config plugins/camera3d/webpack.config.js", + "plugin.spine": "webpack --config plugins/spine/webpack.config.js", + "plugin.spine.dist": "webpack --config plugins/spine/webpack.auto.dist.config.js", + "plugin.spine.watch": "webpack --config plugins/spine/webpack.auto.config.js --watch --display-modules", + "plugin.spine.dev": "webpack --config plugins/spine/webpack.auto.config.js", + "plugin.spine.canvas.dist": "webpack --config plugins/spine/webpack.canvas.dist.config.js", + "plugin.spine.canvas.watch": "webpack --config plugins/spine/webpack.canvas.config.js --watch --display-modules", + "plugin.spine.canvas.dev": "webpack --config plugins/spine/webpack.canvas.config.js", + "plugin.spine.webgl.dist": "webpack --config plugins/spine/webpack.webgl.dist.config.js", + "plugin.spine.webgl.watch": "webpack --config plugins/spine/webpack.webgl.config.js --watch --display-modules", + "plugin.spine.webgl.dev": "webpack --config plugins/spine/webpack.webgl.config.js", + "plugin.spine.full": "npm run plugin.spine.dev && npm run plugin.spine.canvas.dev && npm run plugin.spine.webgl.dev", + "plugin.spine.full.dist": "npm run plugin.spine.dist && npm run plugin.spine.canvas.dist && npm run plugin.spine.webgl.dist", + "lint": "eslint --config .eslintrc.json \"src/**/*.js\"", + "lintfix": "eslint --config .eslintrc.json \"src/**/*.js\" --fix", + "sloc": "node-sloc \"./src\" --include-extensions \"js\"", + "bundleshaders": "node scripts/bundle-shaders.js", + "postinstall": "node scripts/support.js", + "build-tsgen": "cd scripts/tsgen && tsc", + "tsgen": "cd scripts/tsgen && jsdoc -c jsdoc-tsd.conf.json", + "test-ts": "cd scripts/tsgen/test && tsc > output.txt", + "ts": "npm run tsgen && npm run test-ts", + "tsdev": "npm run build-tsgen && npm run tsgen && npm run test-ts" + }, + "keywords": [ + "2d", + "HTML5", + "WebGL", + "canvas", + "game", + "javascript", + "physics", + "tweens", + "typescript", + "web audio" + ], + "devDependencies": { + "clean-webpack-plugin": "^0.1.19", + "dts-dom": "^3.3.0", + "eslint": "^4.19.1", + "eslint-plugin-es5": "^1.3.1", + "fs-extra": "^6.0.1", + "jsdoc": "^3.6.3", + "node-sloc": "^0.1.11", + "remove-files-webpack-plugin": "^1.1.3", + "typescript": "^3.4.5", + "uglifyjs-webpack-plugin": "^1.3.0", + "vivid-cli": "^1.1.2", + "webpack": "^4.23.0", + "webpack-cli": "^3.1.1", + "webpack-shell-plugin": "^0.5.0" + }, + "dependencies": { + "eventemitter3": "^3.1.0", + "exports-loader": "^0.7.0", + "imports-loader": "^0.8.0", + "path": "^0.12.7" + } +} diff --git a/plugins/fbinstant/src/FacebookInstantGamesPlugin.js b/plugins/fbinstant/src/FacebookInstantGamesPlugin.js index 4332132e9..56d4db249 100644 --- a/plugins/fbinstant/src/FacebookInstantGamesPlugin.js +++ b/plugins/fbinstant/src/FacebookInstantGamesPlugin.js @@ -1,2314 +1,2314 @@ -/* eslint no-console: 0 */ - -/** - * @author Richard Davey - * @copyright 2018 Photon Storm Ltd. - * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} - */ - -var AdInstance = require('./AdInstance'); -var Class = require('../../../src/utils/Class'); -var DataManager = require('../../../src/data/DataManager'); -var EventEmitter = require('eventemitter3'); -var Leaderboard = require('./Leaderboard'); -var Product = require('./Product'); -var Purchase = require('./Purchase'); - -/** - * @classdesc - * The Facebook Instant Games Plugin for Phaser 3 provides a seamless bridge between Phaser - * and the Facebook Instant Games API version 6.2. - * - * You can access this plugin via the `facebook` property in a Scene, i.e: - * - * ```javascript - * this.facebook.getPlatform(); - * ``` - * - * If this is unavailable please check to make sure you're using a build of Phaser that has - * this plugin within it. You can quickly check this by looking at the dev tools console - * header - the Phaser version number will have `-FB` after it if this plugin is loaded. - * - * If you are building your own version of Phaser then use this Webpack DefinePlugin flag: - * - * `"typeof PLUGIN_FBINSTANT": JSON.stringify(true)` - * - * You will find that every Instant Games API method has a mapping in this plugin. - * For a full list please consult either the plugin documentation, or the 6.2 SDK documentation - * at https://developers.facebook.com/docs/games/instant-games/sdk/fbinstant6.2 - * - * Internally this plugin uses its own Data Manager to handle seamless user data updates and provides - * handy functions for advertisement displaying, opening share dialogs, logging, leaderboards, purchase API requests, - * loader integration and more. - * - * To get started with Facebook Instant Games you will need to register on Facebook and create a new Instant - * Game app that has its own unique app ID. Facebook have also provided a dashboard interface for setting up - * various features for your game, including leaderboards, ad requests and the payments API. There are lots - * of guides on the Facebook Developers portal to assist with setting these - * various systems up: https://developers.facebook.com/docs/games/instant-games/guides - * - * For more details follow the Quick Start guide here: https://developers.facebook.com/docs/games/instant-games - * - * @class FacebookInstantGamesPlugin - * @memberOf Phaser - * @constructor - * @extends Phaser.Events.EventEmitter - * @since 3.13.0 - * - * @param {Phaser.Game} game - A reference to the Phaser.Game instance. - */ -var FacebookInstantGamesPlugin = new Class({ - - Extends: EventEmitter, - - initialize: - - function FacebookInstantGamesPlugin (game) - { - EventEmitter.call(this); - - /** - * A reference to the Phaser.Game instance. - * - * @name Phaser.FacebookInstantGamesPlugin#game - * @type {Phaser.Game} - * @readOnly - * @since 3.13.0 - */ - this.game = game; - - /** - * A Data Manager instance. - * It allows you to store, query and retrieve any key/value data you may need to store. - * It's also used internally by the plugin to store FBIG API data. - * - * @name Phaser.FacebookInstantGamesPlugin#data - * @type {Phaser.Data.DataManager} - * @since 3.13.0 - */ - this.data = new DataManager(this); - - this.on('setdata', this.setDataHandler, this); - this.on('changedata', this.changeDataHandler, this); - - /** - * Has the Facebook Instant Games API loaded yet? - * This is set automatically during the boot process. - * - * @name Phaser.FacebookInstantGamesPlugin#hasLoaded - * @type {boolean} - * @since 3.13.0 - */ - this.hasLoaded = false; - - /** - * Is the Data Manager currently locked? - * - * @name Phaser.FacebookInstantGamesPlugin#dataLocked - * @type {boolean} - * @since 3.13.0 - */ - this.dataLocked = false; - - /** - * A list of the Facebook Instant Games APIs that are available, - * based on the given platform, context and user privacy settings. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#supportedAPIs - * @type {string[]} - * @since 3.13.0 - */ - this.supportedAPIs = []; - - /** - * Holds the entry point that the game was launched from. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#entryPoint - * @type {string} - * @since 3.13.0 - */ - this.entryPoint = ''; - - /** - * An object that contains any data associated with the entry point that the game was launched from. - * The contents of the object are developer-defined, and can occur from entry points on different platforms. - * This will return null for older mobile clients, as well as when there is no data associated with the particular entry point. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#entryPointData - * @type {any} - * @since 3.13.0 - */ - this.entryPointData = null; - - /** - * A unique identifier for the current game context. This represents a specific context - * that the game is being played in (for example, a particular messenger conversation or facebook post). - * The identifier will be null if game is being played in a solo context. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#contextID - * @type {string} - * @since 3.13.0 - */ - this.contextID = null; - - /** - * The current context in which your game is running. This can be either `null` or - * one of: - * - * `POST` - The game is running inside of a Facebook post. - * `THREAD` - The game is running inside a Facebook Messenger thread. - * `GROUP` - The game is running inside a Facebook Group. - * `SOLO` - This is the default context, the player is the only participant. - * - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#contextType - * @type {?string} - * @since 3.13.0 - */ - this.contextType = null; - - /** - * The current locale. - * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. - * Use this to determine what languages the current game should be localized with. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#locale - * @type {?string} - * @since 3.13.0 - */ - this.locale = null; - - /** - * The platform on which the game is currently running, i.e. `IOS`. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#platform - * @type {?string} - * @since 3.13.0 - */ - this.platform = null; - - /** - * The string representation of the Facebook Instant Games SDK version being used. - * This value is populated automatically during boot. - * - * @name Phaser.FacebookInstantGamesPlugin#version - * @type {?string} - * @since 3.13.0 - */ - this.version = null; - - /** - * Holds the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. - * This value is populated automatically during boot if the API is supported. - * - * @name Phaser.FacebookInstantGamesPlugin#playerID - * @type {?string} - * @since 3.13.0 - */ - this.playerID = null; - - /** - * The player's localized display name. - * This value is populated automatically during boot if the API is supported. - * - * @name Phaser.FacebookInstantGamesPlugin#playerName - * @type {?string} - * @since 3.13.0 - */ - this.playerName = null; - - /** - * A url to the player's public profile photo. The photo will always be a square, and with dimensions - * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. - * It's recommended to always scale the image to a desired size before rendering. - * This value is populated automatically during boot if the API is supported. - * - * @name Phaser.FacebookInstantGamesPlugin#playerPhotoURL - * @type {?string} - * @since 3.13.0 - */ - this.playerPhotoURL = null; - - /** - * Whether a player can subscribe to the game bot or not. - * - * @name Phaser.FacebookInstantGamesPlugin#playerCanSubscribeBot - * @type {boolean} - * @since 3.13.0 - */ - this.playerCanSubscribeBot = false; - - /** - * Does the current platform and context allow for use of the payments API? - * Currently this is only available on Facebook.com and Android 6+. - * - * @name Phaser.FacebookInstantGamesPlugin#paymentsReady - * @type {boolean} - * @since 3.13.0 - */ - this.paymentsReady = false; - - /** - * The set of products that are registered to the game. - * - * @name Phaser.FacebookInstantGamesPlugin#catalog - * @type {Product[]} - * @since 3.13.0 - */ - this.catalog = []; - - /** - * Contains all of the player's unconsumed purchases. - * The game must fetch the current player's purchases as soon as the client indicates that it is ready to perform payments-related operations, - * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. - * - * @name Phaser.FacebookInstantGamesPlugin#purchases - * @type {Purchase[]} - * @since 3.13.0 - */ - this.purchases = []; - - /** - * Contains all of the leaderboard data, as populated by the `getLeaderboard()` method. - * - * @name Phaser.FacebookInstantGamesPlugin#leaderboards - * @type {Phaser.FacebookInstantGamesLeaderboard[]} - * @since 3.13.0 - */ - this.leaderboards = {}; - - /** - * Contains AdInstance objects, as created by the `preloadAds()` method. - * - * @name Phaser.FacebookInstantGamesPlugin#ads - * @type {AdInstance[]} - * @since 3.13.0 - */ - this.ads = []; - }, - - /** - * Internal set data handler. - * - * @method Phaser.FacebookInstantGamesPlugin#setDataHandler - * @private - * @since 3.13.0 - * - * @param {Phaser.Data.DataManager} parent - The parent Data Manager instance. - * @param {string} key - The key of the data. - * @param {any} value - The value of the data. - */ - setDataHandler: function (parent, key, value) - { - if (this.dataLocked) - { - return; - } - - var data = {}; - - data[key] = value; - - var _this = this; - - FBInstant.player.setDataAsync(data).then(function () - { - _this.emit('savedata', data); - }); - }, - - /** - * Internal change data handler. - * - * @method Phaser.FacebookInstantGamesPlugin#changeDataHandler - * @private - * @since 3.13.0 - * - * @param {Phaser.Data.DataManager} parent - The parent Data Manager instance. - * @param {string} key - The key of the data. - * @param {any} value - The value of the data. - */ - changeDataHandler: function (parent, key, value) - { - if (this.dataLocked) - { - return; - } - - var data = {}; - - data[key] = value; - - var _this = this; - - FBInstant.player.setDataAsync(data).then(function () - { - _this.emit('savedata', data); - }); - }, - - /** - * Call this method from your `Scene.preload` in order to sync the load progress - * of the Phaser Loader with the Facebook Instant Games loader display, i.e.: - * - * ```javascript - * this.facebook.showLoadProgress(this); - * this.facebook.once('startgame', this.startGame, this); - * ``` - * - * @method Phaser.FacebookInstantGamesPlugin#showLoadProgress - * @since 3.13.0 - * - * @param {Phaser.Scene} scene - The Scene for which you want to show loader progress for. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - showLoadProgress: function (scene) - { - scene.load.on('progress', function (value) - { - if (!this.hasLoaded) - { - FBInstant.setLoadingProgress(value * 100); - } - - }, this); - - scene.load.on('complete', function () - { - if (!this.hasLoaded) - { - this.hasLoaded = true; - - FBInstant.startGameAsync().then(this.gameStartedHandler.bind(this)); - } - - }, this); - - return this; - }, - - /** - * This method is called automatically when the game has finished loading, - * if you used the `showLoadProgress` method. If your game doesn't need to - * load any assets, or you're managing the load yourself, then call this - * method directly to start the API running. - * - * When the API has finished starting this plugin will emit a `startgame` event - * which you should listen for. - * - * @method Phaser.FacebookInstantGamesPlugin#gameStarted - * @since 3.13.0 - */ - gameStarted: function () - { - if (!this.hasLoaded) - { - this.hasLoaded = true; - - FBInstant.startGameAsync().then(this.gameStartedHandler.bind(this)); - } - else - { - this.gameStartedHandler(); - } - }, - - /** - * The internal gameStarted handler. - * - * @method Phaser.FacebookInstantGamesPlugin#gameStartedHandler - * @private - * @since 3.20.0 - */ - gameStartedHandler: function () - { - var APIs = FBInstant.getSupportedAPIs(); - - var supported = {}; - - var dotToUpper = function (match) - { - return match[1].toUpperCase(); - }; - - APIs.forEach(function (api) - { - api = api.replace(/\../g, dotToUpper); - - supported[api] = true; - }); - - this.supportedAPIs = supported; - - this.getID(); - this.getType(); - this.getLocale(); - this.getPlatform(); - this.getSDKVersion(); - - this.getPlayerID(); - this.getPlayerName(); - this.getPlayerPhotoURL(); - - var _this = this; - - FBInstant.onPause(function () - { - _this.emit('pause'); - }); - - FBInstant.getEntryPointAsync().then(function (entrypoint) - { - _this.entryPoint = entrypoint; - _this.entryPointData = FBInstant.getEntryPointData(); - - _this.emit('startgame'); - - }).catch(function (e) - { - console.warn(e); - }); - - // Facebook.com and Android 6 only - if (this.supportedAPIs.paymentsPurchaseAsync) - { - FBInstant.payments.onReady(function () - { - _this.paymentsReady = true; - - }).catch(function (e) - { - console.warn(e); - }); - } - }, - - /** - * Checks to see if a given Facebook Instant Games API is available or not. - * - * @method Phaser.FacebookInstantGamesPlugin#checkAPI - * @since 3.13.0 - * - * @param {string} api - The API to check for, i.e. `player.getID`. - * - * @return {boolean} `true` if the API is supported, otherwise `false`. - */ - checkAPI: function (api) - { - if (!this.supportedAPIs[api]) - { - return false; - } - else - { - return true; - } - }, - - /** - * Returns the unique identifier for the current game context. This represents a specific context - * that the game is being played in (for example, a particular messenger conversation or facebook post). - * The identifier will be null if game is being played in a solo context. - * - * It is only populated if `contextGetID` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getID - * @since 3.13.0 - * - * @return {string} The context ID. - */ - getID: function () - { - if (!this.contextID && this.supportedAPIs.contextGetID) - { - this.contextID = FBInstant.context.getID(); - } - - return this.contextID; - }, - - /** - * Returns the current context in which your game is running. This can be either `null` or one of: - * - * `POST` - The game is running inside of a Facebook post. - * `THREAD` - The game is running inside a Facebook Messenger thread. - * `GROUP` - The game is running inside a Facebook Group. - * `SOLO` - This is the default context, the player is the only participant. - * - * It is only populated if `contextGetType` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getType - * @since 3.13.0 - * - * @return {?string} The context type. - */ - getType: function () - { - if (!this.contextType && this.supportedAPIs.contextGetType) - { - this.contextType = FBInstant.context.getType(); - } - - return this.contextType; - }, - - /** - * Returns the current locale. - * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. - * Use this to determine what languages the current game should be localized with. - * It is only populated if `getLocale` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getLocale - * @since 3.13.0 - * - * @return {?string} The current locale. - */ - getLocale: function () - { - if (!this.locale && this.supportedAPIs.getLocale) - { - this.locale = FBInstant.getLocale(); - } - - return this.locale; - }, - - /** - * Returns the platform on which the game is currently running, i.e. `IOS`. - * It is only populated if `getPlatform` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getPlatform - * @since 3.13.0 - * - * @return {?string} The current platform. - */ - getPlatform: function () - { - if (!this.platform && this.supportedAPIs.getPlatform) - { - this.platform = FBInstant.getPlatform(); - } - - return this.platform; - }, - - /** - * Returns the string representation of the Facebook Instant Games SDK version being used. - * It is only populated if `getSDKVersion` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getSDKVersion - * @since 3.13.0 - * - * @return {?string} The sdk version. - */ - getSDKVersion: function () - { - if (!this.version && this.supportedAPIs.getSDKVersion) - { - this.version = FBInstant.getSDKVersion(); - } - - return this.version; - }, - - /** - * Returns the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. - * It is only populated if `playerGetID` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getPlayerID - * @since 3.13.0 - * - * @return {?string} The player ID. - */ - getPlayerID: function () - { - if (!this.playerID && this.supportedAPIs.playerGetID) - { - this.playerID = FBInstant.player.getID(); - } - - return this.playerID; - }, - - /** - * Returns the player's localized display name. - * It is only populated if `playerGetName` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getPlayerName - * @since 3.13.0 - * - * @return {?string} The player's localized display name. - */ - getPlayerName: function () - { - if (!this.playerName && this.supportedAPIs.playerGetName) - { - this.playerName = FBInstant.player.getName(); - } - - return this.playerName; - }, - - /** - * Returns the url to the player's public profile photo. The photo will always be a square, and with dimensions - * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. - * It's recommended to always scale the image to a desired size before rendering. - * It is only populated if `playerGetPhoto` is in the list of supported APIs. - * - * @method Phaser.FacebookInstantGamesPlugin#getPlayerPhotoURL - * @since 3.13.0 - * - * @return {?string} The player's photo url. - */ - getPlayerPhotoURL: function () - { - if (!this.playerPhotoURL && this.supportedAPIs.playerGetPhoto) - { - this.playerPhotoURL = FBInstant.player.getPhoto(); - } - - return this.playerPhotoURL; - }, - - /** - * Load the player's photo and store it in the Texture Manager, ready for use in-game. - * - * This method works by using a Scene Loader instance and then asking the Loader to - * retrieve the image. - * - * When complete the plugin will emit a `photocomplete` event, along with the key of the photo. - * - * ```javascript - * this.facebook.loadPlayerPhoto(this, 'player').once('photocomplete', function (key) { - * this.add.image(x, y, 'player'); - * }, this); - * ``` - * - * @method Phaser.FacebookInstantGamesPlugin#loadPlayerPhoto - * @since 3.13.0 - * - * @param {Phaser.Scene} scene - The Scene that will be responsible for loading this photo. - * @param {string} key - The key to use when storing the photo in the Texture Manager. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - loadPlayerPhoto: function (scene, key) - { - if (this.playerPhotoURL) - { - scene.load.setCORS('anonymous'); - - scene.load.image(key, this.playerPhotoURL); - - scene.load.once('filecomplete-image-' + key, function () - { - this.emit('photocomplete', key); - - }, this); - - scene.load.start(); - } - - return this; - }, - - /** - * Checks if the current player can subscribe to the game bot. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they can subscribe, the `playerCanSubscribeBot` property is set to `true` - * and this plugin will emit the `cansubscribebot` event. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `cansubscribebotfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#canSubscribeBot - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - canSubscribeBot: function () - { - if (this.supportedAPIs.playerCanSubscribeBotAsync) - { - var _this = this; - - FBInstant.player.canSubscribeBotAsync().then(function () - { - _this.playerCanSubscribeBot = true; - - _this.emit('cansubscribebot'); - - }).catch(function (e) - { - _this.emit('cansubscribebotfail', e); - }); - } - else - { - this.emit('cansubscribebotfail'); - } - - return this; - }, - - /** - * Subscribes the current player to the game bot. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `subscribebot` event. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `subscribebotfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#subscribeBot - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - subscribeBot: function () - { - if (this.playerCanSubscribeBot) - { - var _this = this; - - FBInstant.player.subscribeBotAsync().then(function () - { - _this.emit('subscribebot'); - - }).catch(function (e) - { - _this.emit('subscribebotfail', e); - }); - } - else - { - this.emit('subscribebotfail'); - } - - return this; - }, - - /** - * Gets the associated data from the player based on the given key, or array of keys. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the data is set into this plugins Data Manager and the - * `getdata` event will be emitted. - * - * @method Phaser.FacebookInstantGamesPlugin#getData - * @since 3.13.0 - * - * @param {(string|string[])} keys - The key/s of the data to retrieve. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - getData: function (keys) - { - if (!this.checkAPI('playerGetDataAsync')) - { - return this; - } - - if (!Array.isArray(keys)) - { - keys = [ keys ]; - } - - var _this = this; - - FBInstant.player.getDataAsync(keys).then(function (data) - { - _this.dataLocked = true; - - for (var key in data) - { - _this.data.set(key, data[key]); - } - - _this.dataLocked = false; - - _this.emit('getdata', data); - }); - - return this; - }, - - /** - * Set data to be saved to the designated cloud storage of the current player. The game can store up to 1MB of data for each unique player. - * - * The data save is requested in an async call, so the result isn't available immediately. - * - * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this - * method directly if you need to replace the data object directly. - * - * When the APIs `setDataAsync` call resolves it will emit the `savedata` event from this plugin. If the call fails for some - * reason it will emit `savedatafail` instead. - * - * The call resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was valid and - * has been scheduled to be saved. It also guarantees that all values that were set are now available in `getData`. - * - * @method Phaser.FacebookInstantGamesPlugin#saveData - * @since 3.13.0 - * - * @param {object} data - An object containing a set of key-value pairs that should be persisted to cloud storage. - * The object must contain only serializable values - any non-serializable values will cause the entire modification to be rejected. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - saveData: function (data) - { - if (!this.checkAPI('playerSetDataAsync')) - { - return this; - } - - var _this = this; - - FBInstant.player.setDataAsync(data).then(function () - { - _this.emit('savedata', data); - - }).catch(function (e) - { - _this.emit('savedatafail', e); - }); - - return this; - }, - - /** - * Immediately flushes any changes to the player data to the designated cloud storage. - * This function is expensive, and should primarily be used for critical changes where persistence needs to be immediate - * and known by the game. Non-critical changes should rely on the platform to persist them in the background. - * NOTE: Calls to player.setDataAsync will be rejected while this function's result is pending. - * - * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this - * method directly if you need to flush the data directly. - * - * When the APIs `flushDataAsync` call resolves it will emit the `flushdata` event from this plugin. If the call fails for some - * reason it will emit `flushdatafail` instead. - * - * @method Phaser.FacebookInstantGamesPlugin#flushData - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - flushData: function () - { - if (!this.checkAPI('playerFlushDataAsync')) - { - return this; - } - - var _this = this; - - FBInstant.player.flushDataAsync().then(function () - { - _this.emit('flushdata'); - - }).catch(function (e) - { - _this.emit('flushdatafail', e); - }); - - return this; - }, - - /** - * Retrieve stats from the designated cloud storage of the current player. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `getstats` event will be emitted along with the data object returned. - * - * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, - * it will emit a `getstatsfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#getStats - * @since 3.13.0 - * - * @param {string[]} [keys] - An optional array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - getStats: function (keys) - { - if (!this.checkAPI('playerGetStatsAsync')) - { - return this; - } - - var _this = this; - - FBInstant.player.getStatsAsync(keys).then(function (data) - { - _this.emit('getstats', data); - - }).catch(function (e) - { - _this.emit('getstatsfail', e); - }); - - return this; - }, - - /** - * Save the stats of the current player to the designated cloud storage. - * - * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, - * all other data types will be ignored. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `savestats` event will be emitted along with the data object returned. - * - * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, - * it will emit a `savestatsfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#saveStats - * @since 3.13.0 - * - * @param {object} data - An object containing a set of key-value pairs that should be persisted to cloud storage as stats. Note that only numerical values are stored. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - saveStats: function (data) - { - if (!this.checkAPI('playerSetStatsAsync')) - { - return this; - } - - var output = {}; - - for (var key in data) - { - if (typeof data[key] === 'number') - { - output[key] = data[key]; - } - } - - var _this = this; - - FBInstant.player.setStatsAsync(output).then(function () - { - _this.emit('savestats', output); - - }).catch(function (e) - { - _this.emit('savestatsfail', e); - }); - - return this; - }, - - /** - * Increment the stats of the current player and save them to the designated cloud storage. - * - * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, - * all other data types will be ignored. - * - * The data object provided for this call should contain offsets for how much to modify the stats by: - * - * ```javascript - * this.facebook.incStats({ - * level: 1, - * zombiesSlain: 17, - * rank: -1 - * }); - * ``` - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `incstats` event will be emitted along with the data object returned. - * - * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, - * it will emit a `incstatsfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#incStats - * @since 3.13.0 - * - * @param {object} data - An object containing a set of key-value pairs indicating how much to increment each stat in cloud storage. Note that only numerical values are processed. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - incStats: function (data) - { - if (!this.checkAPI('playerIncrementStatsAsync')) - { - return this; - } - - var output = {}; - - for (var key in data) - { - if (typeof data[key] === 'number') - { - output[key] = data[key]; - } - } - - var _this = this; - - FBInstant.player.incrementStatsAsync(output).then(function (stats) - { - _this.emit('incstats', stats); - - }).catch(function (e) - { - _this.emit('incstatsfail', e); - }); - - return this; - }, - - /** - * Sets the data associated with the individual gameplay session for the current context. - * - * This function should be called whenever the game would like to update the current session data. - * - * This session data may be used to populate a variety of payloads, such as game play webhooks. - * - * @method Phaser.FacebookInstantGamesPlugin#saveSession - * @since 3.13.0 - * - * @param {object} data - An arbitrary data object, which must be less than or equal to 1000 characters when stringified. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - saveSession: function (data) - { - if (!this.checkAPI('setSessionData')) - { - return this; - } - - var test = JSON.stringify(data); - - if (test.length <= 1000) - { - FBInstant.setSessionData(data); - } - else - { - console.warn('Session data too long. Max 1000 chars.'); - } - - return this; - }, - - /** - * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * - * @method Phaser.FacebookInstantGamesPlugin#openShare - * @since 3.13.0 - * - * @param {string} text - A text message to be shared. - * @param {string} key - The key of the texture to use as the share image. - * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {object} [sessionData] - A blob of data to attach to the share. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - openShare: function (text, key, frame, sessionData) - { - return this._share('SHARE', text, key, frame, sessionData); - }, - - /** - * This invokes a dialog to let the user invite a friend to play this game, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * - * @method Phaser.FacebookInstantGamesPlugin#openInvite - * @since 3.13.0 - * - * @param {string} text - A text message to be shared. - * @param {string} key - The key of the texture to use as the share image. - * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {object} [sessionData] - A blob of data to attach to the share. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - openInvite: function (text, key, frame, sessionData) - { - return this._share('INVITE', text, key, frame, sessionData); - }, - - /** - * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * - * @method Phaser.FacebookInstantGamesPlugin#openRequest - * @since 3.13.0 - * - * @param {string} text - A text message to be shared. - * @param {string} key - The key of the texture to use as the share image. - * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {object} [sessionData] - A blob of data to attach to the share. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - openRequest: function (text, key, frame, sessionData) - { - return this._share('REQUEST', text, key, frame, sessionData); - }, - - /** - * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * - * @method Phaser.FacebookInstantGamesPlugin#openChallenge - * @since 3.13.0 - * - * @param {string} text - A text message to be shared. - * @param {string} key - The key of the texture to use as the share image. - * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {object} [sessionData] - A blob of data to attach to the share. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - openChallenge: function (text, key, frame, sessionData) - { - return this._share('CHALLENGE', text, key, frame, sessionData); - }, - - /** - * Internal share handler. - * - * @method Phaser.FacebookInstantGamesPlugin#_share - * @private - * @since 3.13.0 - * - * @param {string} intent - ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share. - * @param {string} text - A text message to be shared. - * @param {string} key - The key of the texture to use as the share image. - * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {object} [sessionData] - A blob of data to attach to the share. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - _share: function (intent, text, key, frame, sessionData) - { - if (!this.checkAPI('shareAsync')) - { - return this; - } - - if (sessionData === undefined) { sessionData = {}; } - - if (key) - { - var imageData = this.game.textures.getBase64(key, frame); - } - - // intent ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share. - // image string A base64 encoded image to be shared. - // text string A text message to be shared. - // data Object? A blob of data to attach to the share. All game sessions launched from the share will be able to access this blob through FBInstant.getEntryPointData(). - - var payload = { - intent: intent, - image: imageData, - text: text, - data: sessionData - }; - - var _this = this; - - FBInstant.shareAsync(payload).then(function () - { - _this.emit('resume'); - }); - - return this; - }, - - /** - * This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. - * If one of the bounds is null only the other bound will be checked against. - * It will always return the original result for the first call made in a context in a given game play session. - * Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset. - * - * @method Phaser.FacebookInstantGamesPlugin#isSizeBetween - * @since 3.13.0 - * - * @param {integer} [min] - The minimum bound of the context size query. - * @param {integer} [max] - The maximum bound of the context size query. - * - * @return {object} The Context Size Response object in the format: `{answer: boolean, minSize: number?, maxSize: number?}`. - */ - isSizeBetween: function (min, max) - { - if (!this.checkAPI('contextIsSizeBetween')) - { - return this; - } - - return FBInstant.context.isSizeBetween(min, max); - }, - - /** - * Request a switch into a specific context. If the player does not have permission to enter that context, - * or if the player does not provide permission for the game to enter that context, this will emit a `switchfail` event. - * - * Otherwise, the plugin will emit the `switch` event when the game has switched into the specified context. - * - * @method Phaser.FacebookInstantGamesPlugin#switchContext - * @since 3.13.0 - * - * @param {string} contextID - The ID of the desired context. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - switchContext: function (contextID) - { - if (!this.checkAPI('contextSwitchAsync')) - { - return this; - } - - if (contextID !== this.contextID) - { - var _this = this; - - FBInstant.context.switchAsync(contextID).then(function () - { - _this.contextID = FBInstant.context.getID(); - - _this.emit('switch', _this.contextID); - - }).catch(function (e) - { - _this.emit('switchfail', e); - }); - } - - return this; - }, - - /** - * A filter that may be applied to a Context Choose operation. - * - * 'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been played in before. - * 'INCLUDE_EXISTING_CHALLENGES' - Include the "Existing Challenges" section, which surfaces actively played-in contexts that the player is a part of. - * 'NEW_PLAYERS_ONLY' - In sections containing individuals, prefer people who have not played the game. - * - * @typedef {string} ContextFilter - */ - - /** - * A configuration object that may be applied to a Context Choose operation. - * - * @typedef {object} ChooseContextConfig - * @property {ContextFilter[]} [filters] - The set of filters to apply to the context suggestions: 'NEW_CONTEXT_ONLY', 'INCLUDE_EXISTING_CHALLENGES' or 'NEW_PLAYERS_ONLY'. - * @property {number} [maxSize] - The maximum number of participants that a suggested context should ideally have. - * @property {number} [minSize] - The minimum number of participants that a suggested context should ideally have. - */ - - /** - * Opens a context selection dialog for the player. If the player selects an available context, - * the client will attempt to switch into that context, and emit the `choose` event if successful. - * Otherwise, if the player exits the menu or the client fails to switch into the new context, the `choosefail` event will be emitted. - * - * @method Phaser.FacebookInstantGamesPlugin#chooseContext - * @since 3.13.0 - * - * @param {ChooseContextConfig} [options] - An object specifying conditions on the contexts that should be offered. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - chooseContext: function (options) - { - if (!this.checkAPI('contextChooseAsync')) - { - return this; - } - - var _this = this; - - FBInstant.context.chooseAsync(options).then(function () - { - _this.contextID = FBInstant.context.getID(); - _this.emit('choose', _this.contextID); - - }).catch(function (e) - { - _this.emit('choosefail', e); - }); - - return this; - }, - - /** - * Attempts to create or switch into a context between a specified player and the current player. - * This plugin will emit the `create` event once the context switch is completed. - * If the API call fails, such as if the player listed is not a Connected Player of the current player or if the - * player does not provide permission to enter the new context, then the plugin will emit a 'createfail' event. - * - * @method Phaser.FacebookInstantGamesPlugin#createContext - * @since 3.13.0 - * - * @param {string} playerID - ID of the player. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - createContext: function (playerID) - { - if (!this.checkAPI('contextCreateAsync')) - { - return this; - } - - var _this = this; - - FBInstant.context.createAsync(playerID).then(function () - { - _this.contextID = FBInstant.context.getID(); - _this.emit('create', _this.contextID); - - }).catch(function (e) - { - _this.emit('createfail', e); - }); - - return this; - }, - - /** - * Fetches an array of ConnectedPlayer objects containing information about active players - * (people who played the game in the last 90 days) that are connected to the current player. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `players` event along - * with the player data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `playersfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#getPlayers - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - getPlayers: function () - { - if (!this.checkAPI('playerGetConnectedPlayersAsync')) - { - return this; - } - - var _this = this; - - FBInstant.player.getConnectedPlayersAsync().then(function (players) - { - _this.emit('players', players); - - }).catch(function (e) - { - _this.emit('playersfail', e); - }); - - return this; - }, - - /** - * Fetches the game's product catalog. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `getcatalog` event along - * with the catalog data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `getcatalogfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#getCatalog - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - getCatalog: function () - { - if (!this.paymentsReady) - { - return this; - } - - var _this = this; - var catalog = this.catalog; - - FBInstant.payments.getCatalogAsync().then(function (data) - { - catalog = []; - - data.forEach(function (item) - { - catalog.push(Product(item)); - }); - - _this.emit('getcatalog', catalog); - - }).catch(function (e) - { - _this.emit('getcatalogfail', e); - }); - - return this; - }, - - /** - * Fetches a single Product from the game's product catalog. - * - * The product catalog must have been populated using `getCatalog` prior to calling this method. - * - * Use this to look-up product details based on a purchase list. - * - * @method Phaser.FacebookInstantGamesPlugin#getProduct - * @since 3.17.0 - * - * @param {string} productID - The Product ID of the item to get from the catalog. - * - * @return {?Product} The Product from the catalog, or `null` if it couldn't be found or the catalog isn't populated. - */ - getProduct: function (productID) - { - for (var i = 0; i < this.catalog.length; i++) - { - if (this.catalog[i].productID === productID) - { - return this.catalog[i]; - } - } - - return null; - }, - - /** - * Begins the purchase flow for a specific product. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `purchase` event along - * with the purchase data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `purchasefail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#purchase - * @since 3.13.0 - * - * @param {string} productID - The identifier of the product to purchase. - * @param {string} [developerPayload] - An optional developer-specified payload, to be included in the returned purchase's signed request. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - purchase: function (productID, developerPayload) - { - if (!this.paymentsReady) - { - return this; - } - - var config = {productID: productID}; - - if (developerPayload) - { - config.developerPayload = developerPayload; - } - - var _this = this; - - FBInstant.payments.purchaseAsync(config).then(function (data) - { - var purchase = Purchase(data); - - _this.emit('purchase', purchase); - - }).catch(function (e) - { - _this.emit('purchasefail', e); - }); - - return this; - }, - - /** - * Fetches all of the player's unconsumed purchases. The game must fetch the current player's purchases - * as soon as the client indicates that it is ready to perform payments-related operations, - * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `getpurchases` event along - * with the purchase data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `getpurchasesfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#getPurchases - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - getPurchases: function () - { - if (!this.paymentsReady) - { - return this; - } - - var _this = this; - var purchases = this.purchases; - - FBInstant.payments.getPurchasesAsync().then(function (data) - { - purchases = []; - - data.forEach(function (item) - { - purchases.push(Purchase(item)); - }); - - _this.emit('getpurchases', purchases); - - }).catch(function (e) - { - _this.emit('getpurchasesfail', e); - }); - - return this; - }, - - /** - * Consumes a specific purchase belonging to the current player. Before provisioning a product's effects to the player, - * the game should request the consumption of the purchased product. Once the purchase is successfully consumed, - * the game should immediately provide the player with the effects of their purchase. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `consumepurchase` event along - * with the purchase data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `consumepurchasefail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#consumePurchase - * @since 3.17.0 - * - * @param {string} purchaseToken - The purchase token of the purchase that should be consumed. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - consumePurchase: function (purchaseToken) - { - if (!this.paymentsReady) - { - return this; - } - - var _this = this; - - FBInstant.payments.consumePurchaseAsync(purchaseToken).then(function () - { - _this.emit('consumepurchase', purchaseToken); - - }).catch(function (e) - { - _this.emit('consumepurchasefail', e); - }); - - return this; - }, - - /** - * Informs Facebook of a custom update that occurred in the game. - * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. - * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * The `text` parameter is an update payload with the following structure: - * - * ``` - * text: { - * default: 'X just invaded Y\'s village!', - * localizations: { - * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + - * '\u0642\u0631\u064A\u0629 Y!', - * en_US: 'X just invaded Y\'s village!', - * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', - * } - * } - * ``` - * - * @method Phaser.FacebookInstantGamesPlugin#update - * @since 3.13.0 - * - * @param {string} cta - The call to action text. - * @param {object} text - The text object. - * @param {string} key - The key of the texture to use as the share image. - * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {string} template - The update template key. - * @param {object} updateData - The update data object payload. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - update: function (cta, text, key, frame, template, updateData) - { - return this._update('CUSTOM', cta, text, key, frame, template, updateData); - }, - - /** - * Informs Facebook of a leaderboard update that occurred in the game. - * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. - * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * The `text` parameter is an update payload with the following structure: - * - * ``` - * text: { - * default: 'X just invaded Y\'s village!', - * localizations: { - * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + - * '\u0642\u0631\u064A\u0629 Y!', - * en_US: 'X just invaded Y\'s village!', - * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', - * } - * } - * ``` - * - * @method Phaser.FacebookInstantGamesPlugin#updateLeaderboard - * @since 3.13.0 - * - * @param {string} cta - The call to action text. - * @param {object} text - The text object. - * @param {string} key - The key of the texture to use as the share image. - * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {string} template - The update template key. - * @param {object} updateData - The update data object payload. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - updateLeaderboard: function (cta, text, key, frame, template, updateData) - { - return this._update('LEADERBOARD', cta, text, key, frame, template, updateData); - }, - - /** - * Internal update handler. - * - * @method Phaser.FacebookInstantGamesPlugin#_update - * @private - * @since 3.13.0 - * - * @param {string} action - The update action. - * @param {string} cta - The call to action text. - * @param {object} text - The text object. - * @param {string} key - The key of the texture to use as the share image. - * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param {string} template - The update template key. - * @param {object} updateData - The update data object payload. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - _update: function (action, cta, text, key, frame, template, updateData) - { - if (!this.checkAPI('shareAsync')) - { - return this; - } - - if (cta === undefined) { cta = ''; } - - if (typeof text === 'string') - { - text = {default: text}; - } - - if (updateData === undefined) { updateData = {}; } - - if (key) - { - var imageData = this.game.textures.getBase64(key, frame); - } - - var payload = { - action: action, - cta: cta, - image: imageData, - text: text, - template: template, - data: updateData, - strategy: 'IMMEDIATE', - notification: 'NO_PUSH' - }; - - var _this = this; - - FBInstant.updateAsync(payload).then(function () - { - _this.emit('update'); - - }).catch(function (e) - { - _this.emit('updatefail', e); - }); - - return this; - }, - - /** - * Request that the client switch to a different Instant Game. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If the game switches successfully this plugin will emit the `switchgame` event and the client will load the new game. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `switchgamefail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#switchGame - * @since 3.13.0 - * - * @param {string} appID - The Application ID of the Instant Game to switch to. The application must be an Instant Game, and must belong to the same business as the current game. - * @param {object} [data] - An optional data payload. This will be set as the entrypoint data for the game being switched to. Must be less than or equal to 1000 characters when stringified. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - switchGame: function (appID, data) - { - if (!this.checkAPI('switchGameAsync')) - { - return this; - } - - if (data) - { - var test = JSON.stringify(data); - - if (test.length > 1000) - { - console.warn('Switch Game data too long. Max 1000 chars.'); - return this; - } - } - - var _this = this; - - FBInstant.switchGameAsync(appID, data).then(function () - { - _this.emit('switchgame', appID); - - }).catch(function (e) - { - _this.emit('switchgamefail', e); - }); - - return this; - }, - - /** - * Prompts the user to create a shortcut to the game if they are eligible to. - * Can only be called once per session. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If the user choose to create a shortcut this plugin will emit the `shortcutcreated` event. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `shortcutcreatedfail` event instead. - * - * @method Phaser.FacebookInstantGamesPlugin#createShortcut - * @since 3.13.0 - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - createShortcut: function () - { - var _this = this; - - FBInstant.canCreateShortcutAsync().then(function (canCreateShortcut) - { - if (canCreateShortcut) - { - FBInstant.createShortcutAsync().then(function () - { - _this.emit('shortcutcreated'); - - }).catch(function (e) - { - _this.emit('shortcutfailed', e); - }); - } - }); - - return this; - }, - - /** - * Quits the game. - * - * @method Phaser.FacebookInstantGamesPlugin#quit - * @since 3.13.0 - */ - quit: function () - { - FBInstant.quit(); - }, - - /** - * Log an app event with FB Analytics. - * - * See https://developers.facebook.com/docs/javascript/reference/v2.8#app_events for more details about FB Analytics. - * - * @method Phaser.FacebookInstantGamesPlugin#log - * @since 3.13.0 - * - * @param {string} name - Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. - * @param {number} [value] - An optional numeric value that FB Analytics can calculate a sum with. - * @param {object} [params] - An optional object that can contain up to 25 key-value pairs to be logged with the event. Keys must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. Values must be less than 100 characters in length. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - log: function (name, value, params) - { - if (!this.checkAPI('logEvent')) - { - return this; - } - - if (params === undefined) { params = {}; } - - if (name.length >= 2 && name.length <= 40) - { - FBInstant.logEvent(name, parseFloat(value), params); - } - - return this; - }, - - /** - * Attempt to create an instance of an interstitial ad. - * - * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showAd()`. - * - * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. - * - * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. - * - * @method Phaser.FacebookInstantGamesPlugin#preloadAds - * @since 3.13.0 - * - * @param {(string|string[])} placementID - The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - preloadAds: function (placementID) - { - if (!this.checkAPI('getInterstitialAdAsync')) - { - return this; - } - - if (!Array.isArray(placementID)) - { - placementID = [ placementID ]; - } - - var i; - var _this = this; - - var total = 0; - - for (i = 0; i < this.ads.length; i++) - { - if (!this.ads[i].shown) - { - total++; - } - } - - if (total + placementID.length >= 3) - { - console.warn('Too many AdInstances. Show an ad before loading more'); - return this; - } - - for (i = 0; i < placementID.length; i++) - { - var id = placementID[i]; - var data; - - FBInstant.getInterstitialAdAsync(id).then(function (interstitial) - { - data = interstitial; - - return interstitial.loadAsync(); - - }).then(function () - { - var ad = AdInstance(id, data, false); - - _this.ads.push(ad); - - _this.emit('adloaded', ad); - - }).catch(function (e) - { - if (e.code === 'ADS_NO_FILL') - { - _this.emit('adsnofill', id); - } - else if (e.code === 'ADS_FREQUENT_LOAD') - { - _this.emit('adsfrequentload', id); - } - else - { - console.warn(e); - } - }); - } - - return this; - }, - - /** - * Attempt to create an instance of an rewarded video ad. - * - * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showVideo()`. - * - * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. - * - * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. - * - * @method Phaser.FacebookInstantGamesPlugin#preloadVideoAds - * @since 3.13.0 - * - * @param {(string|string[])} placementID - The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - preloadVideoAds: function (placementID) - { - if (!this.checkAPI('getRewardedVideoAsync')) - { - return this; - } - - if (!Array.isArray(placementID)) - { - placementID = [ placementID ]; - } - - var i; - var _this = this; - - var total = 0; - - for (i = 0; i < this.ads.length; i++) - { - if (!this.ads[i].shown) - { - total++; - } - } - - if (total + placementID.length >= 3) - { - console.warn('Too many AdInstances. Show an ad before loading more'); - return this; - } - - for (i = 0; i < placementID.length; i++) - { - var id = placementID[i]; - var data; - - FBInstant.getRewardedVideoAsync(id).then(function (reward) - { - data = reward; - - return reward.loadAsync(); - - }).then(function () - { - var ad = AdInstance(id, data, true); - - _this.ads.push(ad); - - _this.emit('adloaded', ad); - - }).catch(function (e) - { - if (e.code === 'ADS_NO_FILL') - { - _this.emit('adsnofill', id); - } - else if (e.code === 'ADS_FREQUENT_LOAD') - { - _this.emit('adsfrequentload', id); - } - else - { - console.warn(e); - } - }); - } - - return this; - }, - - /** - * Displays a previously loaded interstitial ad. - * - * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. - * - * If the ad cannot be displayed, it will emit the `adsnotloaded` event. - * - * @method Phaser.FacebookInstantGamesPlugin#showAd - * @since 3.13.0 - * - * @param {string} placementID - The ad placement ID to display. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - showAd: function (placementID) - { - var _this = this; - - for (var i = 0; i < this.ads.length; i++) - { - var ad = this.ads[i]; - - if (ad.placementID === placementID && !ad.shown) - { - ad.instance.showAsync().then(function () - { - ad.shown = true; - - _this.emit('adfinished', ad); - - }).catch(function (e) - { - if (e.code === 'ADS_NOT_LOADED') - { - _this.emit('adsnotloaded', ad); - } - else if (e.code === 'RATE_LIMITED') - { - _this.emit('adratelimited', ad); - } - - _this.emit('adshowerror', e, ad); - }); - - break; - } - } - - return this; - }, - - /** - * Displays a previously loaded interstitial video ad. - * - * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. - * - * If the ad cannot be displayed, it will emit the `adsnotloaded` event. - * - * @method Phaser.FacebookInstantGamesPlugin#showVideo - * @since 3.13.0 - * - * @param {string} placementID - The ad placement ID to display. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - showVideo: function (placementID) - { - var _this = this; - - for (var i = 0; i < this.ads.length; i++) - { - var ad = this.ads[i]; - - if (ad.placementID === placementID && ad.video && !ad.shown) - { - ad.instance.showAsync().then(function () - { - ad.shown = true; - - _this.emit('adfinished', ad); - - }).catch(function (e) - { - if (e.code === 'ADS_NOT_LOADED') - { - _this.emit('adsnotloaded', ad); - } - else if (e.code === 'RATE_LIMITED') - { - _this.emit('adratelimited', ad); - } - - _this.emit('adshowerror', e, ad); - }); - - break; - } - } - - return this; - }, - - /** - * Attempts to match the current player with other users looking for people to play with. - * If successful, a new Messenger group thread will be created containing the matched players and the player will - * be context switched to that thread. This plugin will also dispatch the `matchplayer` event, containing the new context ID and Type. - * - * The default minimum and maximum number of players in one matched thread are 2 and 20 respectively, - * depending on how many players are trying to get matched around the same time. - * - * The values can be changed in `fbapp-config.json`. See the Bundle Config documentation for documentation about `fbapp-config.json`. - * - * @method Phaser.FacebookInstantGamesPlugin#matchPlayer - * @since 3.13.0 - * - * @param {string} [matchTag] - Optional extra information about the player used to group them with similar players. Players will only be grouped with other players with exactly the same tag. The tag must only include letters, numbers, and underscores and be 100 characters or less in length. - * @param {boolean} [switchImmediately=false] - Optional extra parameter that specifies whether the player should be immediately switched to the new context when a match is found. By default this will be false which will mean the player needs explicitly press play after being matched to switch to the new context. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - matchPlayer: function (matchTag, switchImmediately) - { - if (matchTag === undefined) { matchTag = null; } - if (switchImmediately === undefined) { switchImmediately = false; } - - if (!this.checkAPI('matchPlayerAsync')) - { - return this; - } - - var _this = this; - - FBInstant.matchPlayerAsync(matchTag, switchImmediately).then(function () - { - _this.getID(); - _this.getType(); - - _this.emit('matchplayer', _this.contextID, _this.contextType); - }); - - return this; - }, - - /** - * Fetch a specific leaderboard belonging to this Instant Game. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `getleaderboard` event will be emitted along with a Leaderboard object instance. - * - * @method Phaser.FacebookInstantGamesPlugin#getLeaderboard - * @since 3.13.0 - * - * @param {string} name - The name of the leaderboard. Each leaderboard for an Instant Game must have its own distinct name. - * - * @return {this} This Facebook Instant Games Plugin instance. - */ - getLeaderboard: function (name) - { - if (!this.checkAPI('getLeaderboardAsync')) - { - return this; - } - - var _this = this; - - FBInstant.getLeaderboardAsync(name).then(function (data) - { - var leaderboard = new Leaderboard(_this, data); - - _this.leaderboards[name] = leaderboard; - - _this.emit('getleaderboard', leaderboard); - - }).catch(function (e) - { - console.warn(e); - }); - - return this; - }, - - /** - * Quits the Facebook API and then destroys this plugin. - * - * @method Phaser.FacebookInstantGamesPlugin#destroy - * @since 3.13.0 - */ - destroy: function () - { - FBInstant.quit(); - - this.data.destroy(); - - this.removeAllListeners(); - - this.catalog = []; - this.purchases = []; - this.leaderboards = []; - this.ads = []; - - this.game = null; - } - -}); - -module.exports = FacebookInstantGamesPlugin; +/* eslint no-console: 0 */ + +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var AdInstance = require('./AdInstance'); +var Class = require('../../../src/utils/Class'); +var DataManager = require('../../../src/data/DataManager'); +var EventEmitter = require('eventemitter3'); +var Leaderboard = require('./Leaderboard'); +var Product = require('./Product'); +var Purchase = require('./Purchase'); + +/** + * @classdesc + * The Facebook Instant Games Plugin for Phaser 3 provides a seamless bridge between Phaser + * and the Facebook Instant Games API version 6.2. + * + * You can access this plugin via the `facebook` property in a Scene, i.e: + * + * ```javascript + * this.facebook.getPlatform(); + * ``` + * + * If this is unavailable please check to make sure you're using a build of Phaser that has + * this plugin within it. You can quickly check this by looking at the dev tools console + * header - the Phaser version number will have `-FB` after it if this plugin is loaded. + * + * If you are building your own version of Phaser then use this Webpack DefinePlugin flag: + * + * `"typeof PLUGIN_FBINSTANT": JSON.stringify(true)` + * + * You will find that every Instant Games API method has a mapping in this plugin. + * For a full list please consult either the plugin documentation, or the 6.2 SDK documentation + * at https://developers.facebook.com/docs/games/instant-games/sdk/fbinstant6.2 + * + * Internally this plugin uses its own Data Manager to handle seamless user data updates and provides + * handy functions for advertisement displaying, opening share dialogs, logging, leaderboards, purchase API requests, + * loader integration and more. + * + * To get started with Facebook Instant Games you will need to register on Facebook and create a new Instant + * Game app that has its own unique app ID. Facebook have also provided a dashboard interface for setting up + * various features for your game, including leaderboards, ad requests and the payments API. There are lots + * of guides on the Facebook Developers portal to assist with setting these + * various systems up: https://developers.facebook.com/docs/games/instant-games/guides + * + * For more details follow the Quick Start guide here: https://developers.facebook.com/docs/games/instant-games + * + * @class FacebookInstantGamesPlugin + * @memberOf Phaser + * @constructor + * @extends Phaser.Events.EventEmitter + * @since 3.13.0 + * + * @param {Phaser.Game} game - A reference to the Phaser.Game instance. + */ +var FacebookInstantGamesPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function FacebookInstantGamesPlugin (game) + { + EventEmitter.call(this); + + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.FacebookInstantGamesPlugin#game + * @type {Phaser.Game} + * @readOnly + * @since 3.13.0 + */ + this.game = game; + + /** + * A Data Manager instance. + * It allows you to store, query and retrieve any key/value data you may need to store. + * It's also used internally by the plugin to store FBIG API data. + * + * @name Phaser.FacebookInstantGamesPlugin#data + * @type {Phaser.Data.DataManager} + * @since 3.13.0 + */ + this.data = new DataManager(this); + + this.on('setdata', this.setDataHandler, this); + this.on('changedata', this.changeDataHandler, this); + + /** + * Has the Facebook Instant Games API loaded yet? + * This is set automatically during the boot process. + * + * @name Phaser.FacebookInstantGamesPlugin#hasLoaded + * @type {boolean} + * @since 3.13.0 + */ + this.hasLoaded = false; + + /** + * Is the Data Manager currently locked? + * + * @name Phaser.FacebookInstantGamesPlugin#dataLocked + * @type {boolean} + * @since 3.13.0 + */ + this.dataLocked = false; + + /** + * A list of the Facebook Instant Games APIs that are available, + * based on the given platform, context and user privacy settings. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#supportedAPIs + * @type {string[]} + * @since 3.13.0 + */ + this.supportedAPIs = []; + + /** + * Holds the entry point that the game was launched from. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#entryPoint + * @type {string} + * @since 3.13.0 + */ + this.entryPoint = ''; + + /** + * An object that contains any data associated with the entry point that the game was launched from. + * The contents of the object are developer-defined, and can occur from entry points on different platforms. + * This will return null for older mobile clients, as well as when there is no data associated with the particular entry point. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#entryPointData + * @type {any} + * @since 3.13.0 + */ + this.entryPointData = null; + + /** + * A unique identifier for the current game context. This represents a specific context + * that the game is being played in (for example, a particular messenger conversation or facebook post). + * The identifier will be null if game is being played in a solo context. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#contextID + * @type {string} + * @since 3.13.0 + */ + this.contextID = null; + + /** + * The current context in which your game is running. This can be either `null` or + * one of: + * + * `POST` - The game is running inside of a Facebook post. + * `THREAD` - The game is running inside a Facebook Messenger thread. + * `GROUP` - The game is running inside a Facebook Group. + * `SOLO` - This is the default context, the player is the only participant. + * + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#contextType + * @type {?string} + * @since 3.13.0 + */ + this.contextType = null; + + /** + * The current locale. + * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. + * Use this to determine what languages the current game should be localized with. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#locale + * @type {?string} + * @since 3.13.0 + */ + this.locale = null; + + /** + * The platform on which the game is currently running, i.e. `IOS`. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#platform + * @type {?string} + * @since 3.13.0 + */ + this.platform = null; + + /** + * The string representation of the Facebook Instant Games SDK version being used. + * This value is populated automatically during boot. + * + * @name Phaser.FacebookInstantGamesPlugin#version + * @type {?string} + * @since 3.13.0 + */ + this.version = null; + + /** + * Holds the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. + * This value is populated automatically during boot if the API is supported. + * + * @name Phaser.FacebookInstantGamesPlugin#playerID + * @type {?string} + * @since 3.13.0 + */ + this.playerID = null; + + /** + * The player's localized display name. + * This value is populated automatically during boot if the API is supported. + * + * @name Phaser.FacebookInstantGamesPlugin#playerName + * @type {?string} + * @since 3.13.0 + */ + this.playerName = null; + + /** + * A url to the player's public profile photo. The photo will always be a square, and with dimensions + * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. + * It's recommended to always scale the image to a desired size before rendering. + * This value is populated automatically during boot if the API is supported. + * + * @name Phaser.FacebookInstantGamesPlugin#playerPhotoURL + * @type {?string} + * @since 3.13.0 + */ + this.playerPhotoURL = null; + + /** + * Whether a player can subscribe to the game bot or not. + * + * @name Phaser.FacebookInstantGamesPlugin#playerCanSubscribeBot + * @type {boolean} + * @since 3.13.0 + */ + this.playerCanSubscribeBot = false; + + /** + * Does the current platform and context allow for use of the payments API? + * Currently this is only available on Facebook.com and Android 6+. + * + * @name Phaser.FacebookInstantGamesPlugin#paymentsReady + * @type {boolean} + * @since 3.13.0 + */ + this.paymentsReady = false; + + /** + * The set of products that are registered to the game. + * + * @name Phaser.FacebookInstantGamesPlugin#catalog + * @type {Product[]} + * @since 3.13.0 + */ + this.catalog = []; + + /** + * Contains all of the player's unconsumed purchases. + * The game must fetch the current player's purchases as soon as the client indicates that it is ready to perform payments-related operations, + * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. + * + * @name Phaser.FacebookInstantGamesPlugin#purchases + * @type {Purchase[]} + * @since 3.13.0 + */ + this.purchases = []; + + /** + * Contains all of the leaderboard data, as populated by the `getLeaderboard()` method. + * + * @name Phaser.FacebookInstantGamesPlugin#leaderboards + * @type {Phaser.FacebookInstantGamesLeaderboard[]} + * @since 3.13.0 + */ + this.leaderboards = {}; + + /** + * Contains AdInstance objects, as created by the `preloadAds()` method. + * + * @name Phaser.FacebookInstantGamesPlugin#ads + * @type {AdInstance[]} + * @since 3.13.0 + */ + this.ads = []; + }, + + /** + * Internal set data handler. + * + * @method Phaser.FacebookInstantGamesPlugin#setDataHandler + * @private + * @since 3.13.0 + * + * @param {Phaser.Data.DataManager} parent - The parent Data Manager instance. + * @param {string} key - The key of the data. + * @param {any} value - The value of the data. + */ + setDataHandler: function (parent, key, value) + { + if (this.dataLocked) + { + return; + } + + var data = {}; + + data[key] = value; + + var _this = this; + + FBInstant.player.setDataAsync(data).then(function () + { + _this.emit('savedata', data); + }); + }, + + /** + * Internal change data handler. + * + * @method Phaser.FacebookInstantGamesPlugin#changeDataHandler + * @private + * @since 3.13.0 + * + * @param {Phaser.Data.DataManager} parent - The parent Data Manager instance. + * @param {string} key - The key of the data. + * @param {any} value - The value of the data. + */ + changeDataHandler: function (parent, key, value) + { + if (this.dataLocked) + { + return; + } + + var data = {}; + + data[key] = value; + + var _this = this; + + FBInstant.player.setDataAsync(data).then(function () + { + _this.emit('savedata', data); + }); + }, + + /** + * Call this method from your `Scene.preload` in order to sync the load progress + * of the Phaser Loader with the Facebook Instant Games loader display, i.e.: + * + * ```javascript + * this.facebook.showLoadProgress(this); + * this.facebook.once('startgame', this.startGame, this); + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#showLoadProgress + * @since 3.13.0 + * + * @param {Phaser.Scene} scene - The Scene for which you want to show loader progress for. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + showLoadProgress: function (scene) + { + scene.load.on('progress', function (value) + { + if (!this.hasLoaded) + { + FBInstant.setLoadingProgress(value * 100); + } + + }, this); + + scene.load.on('complete', function () + { + if (!this.hasLoaded) + { + this.hasLoaded = true; + + FBInstant.startGameAsync().then(this.gameStartedHandler.bind(this)); + } + + }, this); + + return this; + }, + + /** + * This method is called automatically when the game has finished loading, + * if you used the `showLoadProgress` method. If your game doesn't need to + * load any assets, or you're managing the load yourself, then call this + * method directly to start the API running. + * + * When the API has finished starting this plugin will emit a `startgame` event + * which you should listen for. + * + * @method Phaser.FacebookInstantGamesPlugin#gameStarted + * @since 3.13.0 + */ + gameStarted: function () + { + if (!this.hasLoaded) + { + this.hasLoaded = true; + + FBInstant.startGameAsync().then(this.gameStartedHandler.bind(this)); + } + else + { + this.gameStartedHandler(); + } + }, + + /** + * The internal gameStarted handler. + * + * @method Phaser.FacebookInstantGamesPlugin#gameStartedHandler + * @private + * @since 3.20.0 + */ + gameStartedHandler: function () + { + var APIs = FBInstant.getSupportedAPIs(); + + var supported = {}; + + var dotToUpper = function (match) + { + return match[1].toUpperCase(); + }; + + APIs.forEach(function (api) + { + api = api.replace(/\../g, dotToUpper); + + supported[api] = true; + }); + + this.supportedAPIs = supported; + + this.getID(); + this.getType(); + this.getLocale(); + this.getPlatform(); + this.getSDKVersion(); + + this.getPlayerID(); + this.getPlayerName(); + this.getPlayerPhotoURL(); + + var _this = this; + + FBInstant.onPause(function () + { + _this.emit('pause'); + }); + + FBInstant.getEntryPointAsync().then(function (entrypoint) + { + _this.entryPoint = entrypoint; + _this.entryPointData = FBInstant.getEntryPointData(); + + _this.emit('startgame'); + + }).catch(function (e) + { + console.warn(e); + }); + + // Facebook.com and Android 6 only + if (this.supportedAPIs.paymentsPurchaseAsync) + { + FBInstant.payments.onReady(function () + { + _this.paymentsReady = true; + + }).catch(function (e) + { + console.warn(e); + }); + } + }, + + /** + * Checks to see if a given Facebook Instant Games API is available or not. + * + * @method Phaser.FacebookInstantGamesPlugin#checkAPI + * @since 3.13.0 + * + * @param {string} api - The API to check for, i.e. `player.getID`. + * + * @return {boolean} `true` if the API is supported, otherwise `false`. + */ + checkAPI: function (api) + { + if (!this.supportedAPIs[api]) + { + return false; + } + else + { + return true; + } + }, + + /** + * Returns the unique identifier for the current game context. This represents a specific context + * that the game is being played in (for example, a particular messenger conversation or facebook post). + * The identifier will be null if game is being played in a solo context. + * + * It is only populated if `contextGetID` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getID + * @since 3.13.0 + * + * @return {string} The context ID. + */ + getID: function () + { + if (!this.contextID && this.supportedAPIs.contextGetID) + { + this.contextID = FBInstant.context.getID(); + } + + return this.contextID; + }, + + /** + * Returns the current context in which your game is running. This can be either `null` or one of: + * + * `POST` - The game is running inside of a Facebook post. + * `THREAD` - The game is running inside a Facebook Messenger thread. + * `GROUP` - The game is running inside a Facebook Group. + * `SOLO` - This is the default context, the player is the only participant. + * + * It is only populated if `contextGetType` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getType + * @since 3.13.0 + * + * @return {?string} The context type. + */ + getType: function () + { + if (!this.contextType && this.supportedAPIs.contextGetType) + { + this.contextType = FBInstant.context.getType(); + } + + return this.contextType; + }, + + /** + * Returns the current locale. + * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. + * Use this to determine what languages the current game should be localized with. + * It is only populated if `getLocale` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getLocale + * @since 3.13.0 + * + * @return {?string} The current locale. + */ + getLocale: function () + { + if (!this.locale && this.supportedAPIs.getLocale) + { + this.locale = FBInstant.getLocale(); + } + + return this.locale; + }, + + /** + * Returns the platform on which the game is currently running, i.e. `IOS`. + * It is only populated if `getPlatform` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlatform + * @since 3.13.0 + * + * @return {?string} The current platform. + */ + getPlatform: function () + { + if (!this.platform && this.supportedAPIs.getPlatform) + { + this.platform = FBInstant.getPlatform(); + } + + return this.platform; + }, + + /** + * Returns the string representation of the Facebook Instant Games SDK version being used. + * It is only populated if `getSDKVersion` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getSDKVersion + * @since 3.13.0 + * + * @return {?string} The sdk version. + */ + getSDKVersion: function () + { + if (!this.version && this.supportedAPIs.getSDKVersion) + { + this.version = FBInstant.getSDKVersion(); + } + + return this.version; + }, + + /** + * Returns the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. + * It is only populated if `playerGetID` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayerID + * @since 3.13.0 + * + * @return {?string} The player ID. + */ + getPlayerID: function () + { + if (!this.playerID && this.supportedAPIs.playerGetID) + { + this.playerID = FBInstant.player.getID(); + } + + return this.playerID; + }, + + /** + * Returns the player's localized display name. + * It is only populated if `playerGetName` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayerName + * @since 3.13.0 + * + * @return {?string} The player's localized display name. + */ + getPlayerName: function () + { + if (!this.playerName && this.supportedAPIs.playerGetName) + { + this.playerName = FBInstant.player.getName(); + } + + return this.playerName; + }, + + /** + * Returns the url to the player's public profile photo. The photo will always be a square, and with dimensions + * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. + * It's recommended to always scale the image to a desired size before rendering. + * It is only populated if `playerGetPhoto` is in the list of supported APIs. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayerPhotoURL + * @since 3.13.0 + * + * @return {?string} The player's photo url. + */ + getPlayerPhotoURL: function () + { + if (!this.playerPhotoURL && this.supportedAPIs.playerGetPhoto) + { + this.playerPhotoURL = FBInstant.player.getPhoto(); + } + + return this.playerPhotoURL; + }, + + /** + * Load the player's photo and store it in the Texture Manager, ready for use in-game. + * + * This method works by using a Scene Loader instance and then asking the Loader to + * retrieve the image. + * + * When complete the plugin will emit a `photocomplete` event, along with the key of the photo. + * + * ```javascript + * this.facebook.loadPlayerPhoto(this, 'player').once('photocomplete', function (key) { + * this.add.image(x, y, 'player'); + * }, this); + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#loadPlayerPhoto + * @since 3.13.0 + * + * @param {Phaser.Scene} scene - The Scene that will be responsible for loading this photo. + * @param {string} key - The key to use when storing the photo in the Texture Manager. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + loadPlayerPhoto: function (scene, key) + { + if (this.playerPhotoURL) + { + scene.load.setCORS('anonymous'); + + scene.load.image(key, this.playerPhotoURL); + + scene.load.once('filecomplete-image-' + key, function () + { + this.emit('photocomplete', key); + + }, this); + + scene.load.start(); + } + + return this; + }, + + /** + * Checks if the current player can subscribe to the game bot. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they can subscribe, the `playerCanSubscribeBot` property is set to `true` + * and this plugin will emit the `cansubscribebot` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `cansubscribebotfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#canSubscribeBot + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + canSubscribeBot: function () + { + if (this.supportedAPIs.playerCanSubscribeBotAsync) + { + var _this = this; + + FBInstant.player.canSubscribeBotAsync().then(function () + { + _this.playerCanSubscribeBot = true; + + _this.emit('cansubscribebot'); + + }).catch(function (e) + { + _this.emit('cansubscribebotfail', e); + }); + } + else + { + this.emit('cansubscribebotfail'); + } + + return this; + }, + + /** + * Subscribes the current player to the game bot. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `subscribebot` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `subscribebotfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#subscribeBot + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + subscribeBot: function () + { + if (this.playerCanSubscribeBot) + { + var _this = this; + + FBInstant.player.subscribeBotAsync().then(function () + { + _this.emit('subscribebot'); + + }).catch(function (e) + { + _this.emit('subscribebotfail', e); + }); + } + else + { + this.emit('subscribebotfail'); + } + + return this; + }, + + /** + * Gets the associated data from the player based on the given key, or array of keys. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the data is set into this plugins Data Manager and the + * `getdata` event will be emitted. + * + * @method Phaser.FacebookInstantGamesPlugin#getData + * @since 3.13.0 + * + * @param {(string|string[])} keys - The key/s of the data to retrieve. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getData: function (keys) + { + if (!this.checkAPI('playerGetDataAsync')) + { + return this; + } + + if (!Array.isArray(keys)) + { + keys = [ keys ]; + } + + var _this = this; + + FBInstant.player.getDataAsync(keys).then(function (data) + { + _this.dataLocked = true; + + for (var key in data) + { + _this.data.set(key, data[key]); + } + + _this.dataLocked = false; + + _this.emit('getdata', data); + }); + + return this; + }, + + /** + * Set data to be saved to the designated cloud storage of the current player. The game can store up to 1MB of data for each unique player. + * + * The data save is requested in an async call, so the result isn't available immediately. + * + * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this + * method directly if you need to replace the data object directly. + * + * When the APIs `setDataAsync` call resolves it will emit the `savedata` event from this plugin. If the call fails for some + * reason it will emit `savedatafail` instead. + * + * The call resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was valid and + * has been scheduled to be saved. It also guarantees that all values that were set are now available in `getData`. + * + * @method Phaser.FacebookInstantGamesPlugin#saveData + * @since 3.13.0 + * + * @param {object} data - An object containing a set of key-value pairs that should be persisted to cloud storage. + * The object must contain only serializable values - any non-serializable values will cause the entire modification to be rejected. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + saveData: function (data) + { + if (!this.checkAPI('playerSetDataAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.setDataAsync(data).then(function () + { + _this.emit('savedata', data); + + }).catch(function (e) + { + _this.emit('savedatafail', e); + }); + + return this; + }, + + /** + * Immediately flushes any changes to the player data to the designated cloud storage. + * This function is expensive, and should primarily be used for critical changes where persistence needs to be immediate + * and known by the game. Non-critical changes should rely on the platform to persist them in the background. + * NOTE: Calls to player.setDataAsync will be rejected while this function's result is pending. + * + * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this + * method directly if you need to flush the data directly. + * + * When the APIs `flushDataAsync` call resolves it will emit the `flushdata` event from this plugin. If the call fails for some + * reason it will emit `flushdatafail` instead. + * + * @method Phaser.FacebookInstantGamesPlugin#flushData + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + flushData: function () + { + if (!this.checkAPI('playerFlushDataAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.flushDataAsync().then(function () + { + _this.emit('flushdata'); + + }).catch(function (e) + { + _this.emit('flushdatafail', e); + }); + + return this; + }, + + /** + * Retrieve stats from the designated cloud storage of the current player. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `getstats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `getstatsfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getStats + * @since 3.13.0 + * + * @param {string[]} [keys] - An optional array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getStats: function (keys) + { + if (!this.checkAPI('playerGetStatsAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.getStatsAsync(keys).then(function (data) + { + _this.emit('getstats', data); + + }).catch(function (e) + { + _this.emit('getstatsfail', e); + }); + + return this; + }, + + /** + * Save the stats of the current player to the designated cloud storage. + * + * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, + * all other data types will be ignored. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `savestats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `savestatsfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#saveStats + * @since 3.13.0 + * + * @param {object} data - An object containing a set of key-value pairs that should be persisted to cloud storage as stats. Note that only numerical values are stored. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + saveStats: function (data) + { + if (!this.checkAPI('playerSetStatsAsync')) + { + return this; + } + + var output = {}; + + for (var key in data) + { + if (typeof data[key] === 'number') + { + output[key] = data[key]; + } + } + + var _this = this; + + FBInstant.player.setStatsAsync(output).then(function () + { + _this.emit('savestats', output); + + }).catch(function (e) + { + _this.emit('savestatsfail', e); + }); + + return this; + }, + + /** + * Increment the stats of the current player and save them to the designated cloud storage. + * + * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, + * all other data types will be ignored. + * + * The data object provided for this call should contain offsets for how much to modify the stats by: + * + * ```javascript + * this.facebook.incStats({ + * level: 1, + * zombiesSlain: 17, + * rank: -1 + * }); + * ``` + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `incstats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `incstatsfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#incStats + * @since 3.13.0 + * + * @param {object} data - An object containing a set of key-value pairs indicating how much to increment each stat in cloud storage. Note that only numerical values are processed. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + incStats: function (data) + { + if (!this.checkAPI('playerIncrementStatsAsync')) + { + return this; + } + + var output = {}; + + for (var key in data) + { + if (typeof data[key] === 'number') + { + output[key] = data[key]; + } + } + + var _this = this; + + FBInstant.player.incrementStatsAsync(output).then(function (stats) + { + _this.emit('incstats', stats); + + }).catch(function (e) + { + _this.emit('incstatsfail', e); + }); + + return this; + }, + + /** + * Sets the data associated with the individual gameplay session for the current context. + * + * This function should be called whenever the game would like to update the current session data. + * + * This session data may be used to populate a variety of payloads, such as game play webhooks. + * + * @method Phaser.FacebookInstantGamesPlugin#saveSession + * @since 3.13.0 + * + * @param {object} data - An arbitrary data object, which must be less than or equal to 1000 characters when stringified. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + saveSession: function (data) + { + if (!this.checkAPI('setSessionData')) + { + return this; + } + + var test = JSON.stringify(data); + + if (test.length <= 1000) + { + FBInstant.setSessionData(data); + } + else + { + console.warn('Session data too long. Max 1000 chars.'); + } + + return this; + }, + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openShare + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openShare: function (text, key, frame, sessionData) + { + return this._share('SHARE', text, key, frame, sessionData); + }, + + /** + * This invokes a dialog to let the user invite a friend to play this game, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openInvite + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openInvite: function (text, key, frame, sessionData) + { + return this._share('INVITE', text, key, frame, sessionData); + }, + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openRequest + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openRequest: function (text, key, frame, sessionData) + { + return this._share('REQUEST', text, key, frame, sessionData); + }, + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * + * @method Phaser.FacebookInstantGamesPlugin#openChallenge + * @since 3.13.0 + * + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + openChallenge: function (text, key, frame, sessionData) + { + return this._share('CHALLENGE', text, key, frame, sessionData); + }, + + /** + * Internal share handler. + * + * @method Phaser.FacebookInstantGamesPlugin#_share + * @private + * @since 3.13.0 + * + * @param {string} intent - ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share. + * @param {string} text - A text message to be shared. + * @param {string} key - The key of the texture to use as the share image. + * @param {string} [frame] - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {object} [sessionData] - A blob of data to attach to the share. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + _share: function (intent, text, key, frame, sessionData) + { + if (!this.checkAPI('shareAsync')) + { + return this; + } + + if (sessionData === undefined) { sessionData = {}; } + + if (key) + { + var imageData = this.game.textures.getBase64(key, frame); + } + + // intent ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share. + // image string A base64 encoded image to be shared. + // text string A text message to be shared. + // data Object? A blob of data to attach to the share. All game sessions launched from the share will be able to access this blob through FBInstant.getEntryPointData(). + + var payload = { + intent: intent, + image: imageData, + text: text, + data: sessionData + }; + + var _this = this; + + FBInstant.shareAsync(payload).then(function () + { + _this.emit('resume'); + }); + + return this; + }, + + /** + * This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. + * If one of the bounds is null only the other bound will be checked against. + * It will always return the original result for the first call made in a context in a given game play session. + * Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset. + * + * @method Phaser.FacebookInstantGamesPlugin#isSizeBetween + * @since 3.13.0 + * + * @param {integer} [min] - The minimum bound of the context size query. + * @param {integer} [max] - The maximum bound of the context size query. + * + * @return {object} The Context Size Response object in the format: `{answer: boolean, minSize: number?, maxSize: number?}`. + */ + isSizeBetween: function (min, max) + { + if (!this.checkAPI('contextIsSizeBetween')) + { + return this; + } + + return FBInstant.context.isSizeBetween(min, max); + }, + + /** + * Request a switch into a specific context. If the player does not have permission to enter that context, + * or if the player does not provide permission for the game to enter that context, this will emit a `switchfail` event. + * + * Otherwise, the plugin will emit the `switch` event when the game has switched into the specified context. + * + * @method Phaser.FacebookInstantGamesPlugin#switchContext + * @since 3.13.0 + * + * @param {string} contextID - The ID of the desired context. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + switchContext: function (contextID) + { + if (!this.checkAPI('contextSwitchAsync')) + { + return this; + } + + if (contextID !== this.contextID) + { + var _this = this; + + FBInstant.context.switchAsync(contextID).then(function () + { + _this.contextID = FBInstant.context.getID(); + + _this.emit('switch', _this.contextID); + + }).catch(function (e) + { + _this.emit('switchfail', e); + }); + } + + return this; + }, + + /** + * A filter that may be applied to a Context Choose operation. + * + * 'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been played in before. + * 'INCLUDE_EXISTING_CHALLENGES' - Include the "Existing Challenges" section, which surfaces actively played-in contexts that the player is a part of. + * 'NEW_PLAYERS_ONLY' - In sections containing individuals, prefer people who have not played the game. + * + * @typedef {string} ContextFilter + */ + + /** + * A configuration object that may be applied to a Context Choose operation. + * + * @typedef {object} ChooseContextConfig + * @property {ContextFilter[]} [filters] - The set of filters to apply to the context suggestions: 'NEW_CONTEXT_ONLY', 'INCLUDE_EXISTING_CHALLENGES' or 'NEW_PLAYERS_ONLY'. + * @property {number} [maxSize] - The maximum number of participants that a suggested context should ideally have. + * @property {number} [minSize] - The minimum number of participants that a suggested context should ideally have. + */ + + /** + * Opens a context selection dialog for the player. If the player selects an available context, + * the client will attempt to switch into that context, and emit the `choose` event if successful. + * Otherwise, if the player exits the menu or the client fails to switch into the new context, the `choosefail` event will be emitted. + * + * @method Phaser.FacebookInstantGamesPlugin#chooseContext + * @since 3.13.0 + * + * @param {ChooseContextConfig} [options] - An object specifying conditions on the contexts that should be offered. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + chooseContext: function (options) + { + if (!this.checkAPI('contextChooseAsync')) + { + return this; + } + + var _this = this; + + FBInstant.context.chooseAsync(options).then(function () + { + _this.contextID = FBInstant.context.getID(); + _this.emit('choose', _this.contextID); + + }).catch(function (e) + { + _this.emit('choosefail', e); + }); + + return this; + }, + + /** + * Attempts to create or switch into a context between a specified player and the current player. + * This plugin will emit the `create` event once the context switch is completed. + * If the API call fails, such as if the player listed is not a Connected Player of the current player or if the + * player does not provide permission to enter the new context, then the plugin will emit a 'createfail' event. + * + * @method Phaser.FacebookInstantGamesPlugin#createContext + * @since 3.13.0 + * + * @param {string} playerID - ID of the player. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + createContext: function (playerID) + { + if (!this.checkAPI('contextCreateAsync')) + { + return this; + } + + var _this = this; + + FBInstant.context.createAsync(playerID).then(function () + { + _this.contextID = FBInstant.context.getID(); + _this.emit('create', _this.contextID); + + }).catch(function (e) + { + _this.emit('createfail', e); + }); + + return this; + }, + + /** + * Fetches an array of ConnectedPlayer objects containing information about active players + * (people who played the game in the last 90 days) that are connected to the current player. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `players` event along + * with the player data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `playersfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getPlayers + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getPlayers: function () + { + if (!this.checkAPI('playerGetConnectedPlayersAsync')) + { + return this; + } + + var _this = this; + + FBInstant.player.getConnectedPlayersAsync().then(function (players) + { + _this.emit('players', players); + + }).catch(function (e) + { + _this.emit('playersfail', e); + }); + + return this; + }, + + /** + * Fetches the game's product catalog. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `getcatalog` event along + * with the catalog data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `getcatalogfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getCatalog + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getCatalog: function () + { + if (!this.paymentsReady) + { + return this; + } + + var _this = this; + var catalog = this.catalog; + + FBInstant.payments.getCatalogAsync().then(function (data) + { + catalog = []; + + data.forEach(function (item) + { + catalog.push(Product(item)); + }); + + _this.emit('getcatalog', catalog); + + }).catch(function (e) + { + _this.emit('getcatalogfail', e); + }); + + return this; + }, + + /** + * Fetches a single Product from the game's product catalog. + * + * The product catalog must have been populated using `getCatalog` prior to calling this method. + * + * Use this to look-up product details based on a purchase list. + * + * @method Phaser.FacebookInstantGamesPlugin#getProduct + * @since 3.17.0 + * + * @param {string} productID - The Product ID of the item to get from the catalog. + * + * @return {?Product} The Product from the catalog, or `null` if it couldn't be found or the catalog isn't populated. + */ + getProduct: function (productID) + { + for (var i = 0; i < this.catalog.length; i++) + { + if (this.catalog[i].productID === productID) + { + return this.catalog[i]; + } + } + + return null; + }, + + /** + * Begins the purchase flow for a specific product. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `purchase` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `purchasefail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#purchase + * @since 3.13.0 + * + * @param {string} productID - The identifier of the product to purchase. + * @param {string} [developerPayload] - An optional developer-specified payload, to be included in the returned purchase's signed request. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + purchase: function (productID, developerPayload) + { + if (!this.paymentsReady) + { + return this; + } + + var config = {productID: productID}; + + if (developerPayload) + { + config.developerPayload = developerPayload; + } + + var _this = this; + + FBInstant.payments.purchaseAsync(config).then(function (data) + { + var purchase = Purchase(data); + + _this.emit('purchase', purchase); + + }).catch(function (e) + { + _this.emit('purchasefail', e); + }); + + return this; + }, + + /** + * Fetches all of the player's unconsumed purchases. The game must fetch the current player's purchases + * as soon as the client indicates that it is ready to perform payments-related operations, + * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `getpurchases` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `getpurchasesfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#getPurchases + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getPurchases: function () + { + if (!this.paymentsReady) + { + return this; + } + + var _this = this; + var purchases = this.purchases; + + FBInstant.payments.getPurchasesAsync().then(function (data) + { + purchases = []; + + data.forEach(function (item) + { + purchases.push(Purchase(item)); + }); + + _this.emit('getpurchases', purchases); + + }).catch(function (e) + { + _this.emit('getpurchasesfail', e); + }); + + return this; + }, + + /** + * Consumes a specific purchase belonging to the current player. Before provisioning a product's effects to the player, + * the game should request the consumption of the purchased product. Once the purchase is successfully consumed, + * the game should immediately provide the player with the effects of their purchase. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `consumepurchase` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `consumepurchasefail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#consumePurchase + * @since 3.17.0 + * + * @param {string} purchaseToken - The purchase token of the purchase that should be consumed. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + consumePurchase: function (purchaseToken) + { + if (!this.paymentsReady) + { + return this; + } + + var _this = this; + + FBInstant.payments.consumePurchaseAsync(purchaseToken).then(function () + { + _this.emit('consumepurchase', purchaseToken); + + }).catch(function (e) + { + _this.emit('consumepurchasefail', e); + }); + + return this; + }, + + /** + * Informs Facebook of a custom update that occurred in the game. + * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. + * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * The `text` parameter is an update payload with the following structure: + * + * ``` + * text: { + * default: 'X just invaded Y\'s village!', + * localizations: { + * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + + * '\u0642\u0631\u064A\u0629 Y!', + * en_US: 'X just invaded Y\'s village!', + * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', + * } + * } + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#update + * @since 3.13.0 + * + * @param {string} cta - The call to action text. + * @param {object} text - The text object. + * @param {string} key - The key of the texture to use as the share image. + * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {string} template - The update template key. + * @param {object} updateData - The update data object payload. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + update: function (cta, text, key, frame, template, updateData) + { + return this._update('CUSTOM', cta, text, key, frame, template, updateData); + }, + + /** + * Informs Facebook of a leaderboard update that occurred in the game. + * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. + * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * The `text` parameter is an update payload with the following structure: + * + * ``` + * text: { + * default: 'X just invaded Y\'s village!', + * localizations: { + * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + + * '\u0642\u0631\u064A\u0629 Y!', + * en_US: 'X just invaded Y\'s village!', + * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', + * } + * } + * ``` + * + * @method Phaser.FacebookInstantGamesPlugin#updateLeaderboard + * @since 3.13.0 + * + * @param {string} cta - The call to action text. + * @param {object} text - The text object. + * @param {string} key - The key of the texture to use as the share image. + * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {string} template - The update template key. + * @param {object} updateData - The update data object payload. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + updateLeaderboard: function (cta, text, key, frame, template, updateData) + { + return this._update('LEADERBOARD', cta, text, key, frame, template, updateData); + }, + + /** + * Internal update handler. + * + * @method Phaser.FacebookInstantGamesPlugin#_update + * @private + * @since 3.13.0 + * + * @param {string} action - The update action. + * @param {string} cta - The call to action text. + * @param {object} text - The text object. + * @param {string} key - The key of the texture to use as the share image. + * @param {?(string|integer)} frame - The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param {string} template - The update template key. + * @param {object} updateData - The update data object payload. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + _update: function (action, cta, text, key, frame, template, updateData) + { + if (!this.checkAPI('shareAsync')) + { + return this; + } + + if (cta === undefined) { cta = ''; } + + if (typeof text === 'string') + { + text = {default: text}; + } + + if (updateData === undefined) { updateData = {}; } + + if (key) + { + var imageData = this.game.textures.getBase64(key, frame); + } + + var payload = { + action: action, + cta: cta, + image: imageData, + text: text, + template: template, + data: updateData, + strategy: 'IMMEDIATE', + notification: 'NO_PUSH' + }; + + var _this = this; + + FBInstant.updateAsync(payload).then(function () + { + _this.emit('update'); + + }).catch(function (e) + { + _this.emit('updatefail', e); + }); + + return this; + }, + + /** + * Request that the client switch to a different Instant Game. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If the game switches successfully this plugin will emit the `switchgame` event and the client will load the new game. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `switchgamefail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#switchGame + * @since 3.13.0 + * + * @param {string} appID - The Application ID of the Instant Game to switch to. The application must be an Instant Game, and must belong to the same business as the current game. + * @param {object} [data] - An optional data payload. This will be set as the entrypoint data for the game being switched to. Must be less than or equal to 1000 characters when stringified. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + switchGame: function (appID, data) + { + if (!this.checkAPI('switchGameAsync')) + { + return this; + } + + if (data) + { + var test = JSON.stringify(data); + + if (test.length > 1000) + { + console.warn('Switch Game data too long. Max 1000 chars.'); + return this; + } + } + + var _this = this; + + FBInstant.switchGameAsync(appID, data).then(function () + { + _this.emit('switchgame', appID); + + }).catch(function (e) + { + _this.emit('switchgamefail', e); + }); + + return this; + }, + + /** + * Prompts the user to create a shortcut to the game if they are eligible to. + * Can only be called once per session. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If the user choose to create a shortcut this plugin will emit the `shortcutcreated` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `shortcutcreatedfail` event instead. + * + * @method Phaser.FacebookInstantGamesPlugin#createShortcut + * @since 3.13.0 + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + createShortcut: function () + { + var _this = this; + + FBInstant.canCreateShortcutAsync().then(function (canCreateShortcut) + { + if (canCreateShortcut) + { + FBInstant.createShortcutAsync().then(function () + { + _this.emit('shortcutcreated'); + + }).catch(function (e) + { + _this.emit('shortcutfailed', e); + }); + } + }); + + return this; + }, + + /** + * Quits the game. + * + * @method Phaser.FacebookInstantGamesPlugin#quit + * @since 3.13.0 + */ + quit: function () + { + FBInstant.quit(); + }, + + /** + * Log an app event with FB Analytics. + * + * See https://developers.facebook.com/docs/javascript/reference/v2.8#app_events for more details about FB Analytics. + * + * @method Phaser.FacebookInstantGamesPlugin#log + * @since 3.13.0 + * + * @param {string} name - Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. + * @param {number} [value] - An optional numeric value that FB Analytics can calculate a sum with. + * @param {object} [params] - An optional object that can contain up to 25 key-value pairs to be logged with the event. Keys must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. Values must be less than 100 characters in length. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + log: function (name, value, params) + { + if (!this.checkAPI('logEvent')) + { + return this; + } + + if (params === undefined) { params = {}; } + + if (name.length >= 2 && name.length <= 40) + { + FBInstant.logEvent(name, parseFloat(value), params); + } + + return this; + }, + + /** + * Attempt to create an instance of an interstitial ad. + * + * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showAd()`. + * + * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. + * + * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. + * + * @method Phaser.FacebookInstantGamesPlugin#preloadAds + * @since 3.13.0 + * + * @param {(string|string[])} placementID - The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + preloadAds: function (placementID) + { + if (!this.checkAPI('getInterstitialAdAsync')) + { + return this; + } + + if (!Array.isArray(placementID)) + { + placementID = [ placementID ]; + } + + var i; + var _this = this; + + var total = 0; + + for (i = 0; i < this.ads.length; i++) + { + if (!this.ads[i].shown) + { + total++; + } + } + + if (total + placementID.length >= 3) + { + console.warn('Too many AdInstances. Show an ad before loading more'); + return this; + } + + for (i = 0; i < placementID.length; i++) + { + var id = placementID[i]; + var data; + + FBInstant.getInterstitialAdAsync(id).then(function (interstitial) + { + data = interstitial; + + return interstitial.loadAsync(); + + }).then(function () + { + var ad = AdInstance(id, data, false); + + _this.ads.push(ad); + + _this.emit('adloaded', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NO_FILL') + { + _this.emit('adsnofill', id); + } + else if (e.code === 'ADS_FREQUENT_LOAD') + { + _this.emit('adsfrequentload', id); + } + else + { + console.warn(e); + } + }); + } + + return this; + }, + + /** + * Attempt to create an instance of an rewarded video ad. + * + * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showVideo()`. + * + * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. + * + * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. + * + * @method Phaser.FacebookInstantGamesPlugin#preloadVideoAds + * @since 3.13.0 + * + * @param {(string|string[])} placementID - The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + preloadVideoAds: function (placementID) + { + if (!this.checkAPI('getRewardedVideoAsync')) + { + return this; + } + + if (!Array.isArray(placementID)) + { + placementID = [ placementID ]; + } + + var i; + var _this = this; + + var total = 0; + + for (i = 0; i < this.ads.length; i++) + { + if (!this.ads[i].shown) + { + total++; + } + } + + if (total + placementID.length >= 3) + { + console.warn('Too many AdInstances. Show an ad before loading more'); + return this; + } + + for (i = 0; i < placementID.length; i++) + { + var id = placementID[i]; + var data; + + FBInstant.getRewardedVideoAsync(id).then(function (reward) + { + data = reward; + + return reward.loadAsync(); + + }).then(function () + { + var ad = AdInstance(id, data, true); + + _this.ads.push(ad); + + _this.emit('adloaded', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NO_FILL') + { + _this.emit('adsnofill', id); + } + else if (e.code === 'ADS_FREQUENT_LOAD') + { + _this.emit('adsfrequentload', id); + } + else + { + console.warn(e); + } + }); + } + + return this; + }, + + /** + * Displays a previously loaded interstitial ad. + * + * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. + * + * If the ad cannot be displayed, it will emit the `adsnotloaded` event. + * + * @method Phaser.FacebookInstantGamesPlugin#showAd + * @since 3.13.0 + * + * @param {string} placementID - The ad placement ID to display. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + showAd: function (placementID) + { + var _this = this; + + for (var i = 0; i < this.ads.length; i++) + { + var ad = this.ads[i]; + + if (ad.placementID === placementID && !ad.shown) + { + ad.instance.showAsync().then(function () + { + ad.shown = true; + + _this.emit('adfinished', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NOT_LOADED') + { + _this.emit('adsnotloaded', ad); + } + else if (e.code === 'RATE_LIMITED') + { + _this.emit('adratelimited', ad); + } + + _this.emit('adshowerror', e, ad); + }); + + break; + } + } + + return this; + }, + + /** + * Displays a previously loaded interstitial video ad. + * + * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. + * + * If the ad cannot be displayed, it will emit the `adsnotloaded` event. + * + * @method Phaser.FacebookInstantGamesPlugin#showVideo + * @since 3.13.0 + * + * @param {string} placementID - The ad placement ID to display. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + showVideo: function (placementID) + { + var _this = this; + + for (var i = 0; i < this.ads.length; i++) + { + var ad = this.ads[i]; + + if (ad.placementID === placementID && ad.video && !ad.shown) + { + ad.instance.showAsync().then(function () + { + ad.shown = true; + + _this.emit('adfinished', ad); + + }).catch(function (e) + { + if (e.code === 'ADS_NOT_LOADED') + { + _this.emit('adsnotloaded', ad); + } + else if (e.code === 'RATE_LIMITED') + { + _this.emit('adratelimited', ad); + } + + _this.emit('adshowerror', e, ad); + }); + + break; + } + } + + return this; + }, + + /** + * Attempts to match the current player with other users looking for people to play with. + * If successful, a new Messenger group thread will be created containing the matched players and the player will + * be context switched to that thread. This plugin will also dispatch the `matchplayer` event, containing the new context ID and Type. + * + * The default minimum and maximum number of players in one matched thread are 2 and 20 respectively, + * depending on how many players are trying to get matched around the same time. + * + * The values can be changed in `fbapp-config.json`. See the Bundle Config documentation for documentation about `fbapp-config.json`. + * + * @method Phaser.FacebookInstantGamesPlugin#matchPlayer + * @since 3.13.0 + * + * @param {string} [matchTag] - Optional extra information about the player used to group them with similar players. Players will only be grouped with other players with exactly the same tag. The tag must only include letters, numbers, and underscores and be 100 characters or less in length. + * @param {boolean} [switchImmediately=false] - Optional extra parameter that specifies whether the player should be immediately switched to the new context when a match is found. By default this will be false which will mean the player needs explicitly press play after being matched to switch to the new context. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + matchPlayer: function (matchTag, switchImmediately) + { + if (matchTag === undefined) { matchTag = null; } + if (switchImmediately === undefined) { switchImmediately = false; } + + if (!this.checkAPI('matchPlayerAsync')) + { + return this; + } + + var _this = this; + + FBInstant.matchPlayerAsync(matchTag, switchImmediately).then(function () + { + _this.getID(); + _this.getType(); + + _this.emit('matchplayer', _this.contextID, _this.contextType); + }); + + return this; + }, + + /** + * Fetch a specific leaderboard belonging to this Instant Game. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `getleaderboard` event will be emitted along with a Leaderboard object instance. + * + * @method Phaser.FacebookInstantGamesPlugin#getLeaderboard + * @since 3.13.0 + * + * @param {string} name - The name of the leaderboard. Each leaderboard for an Instant Game must have its own distinct name. + * + * @return {this} This Facebook Instant Games Plugin instance. + */ + getLeaderboard: function (name) + { + if (!this.checkAPI('getLeaderboardAsync')) + { + return this; + } + + var _this = this; + + FBInstant.getLeaderboardAsync(name).then(function (data) + { + var leaderboard = new Leaderboard(_this, data); + + _this.leaderboards[name] = leaderboard; + + _this.emit('getleaderboard', leaderboard); + + }).catch(function (e) + { + console.warn(e); + }); + + return this; + }, + + /** + * Quits the Facebook API and then destroys this plugin. + * + * @method Phaser.FacebookInstantGamesPlugin#destroy + * @since 3.13.0 + */ + destroy: function () + { + FBInstant.quit(); + + this.data.destroy(); + + this.removeAllListeners(); + + this.catalog = []; + this.purchases = []; + this.leaderboards = []; + this.ads = []; + + this.game = null; + } + +}); + +module.exports = FacebookInstantGamesPlugin; diff --git a/plugins/impact/Body.js b/plugins/impact/Body.js index d4e51c002..9e3272863 100644 --- a/plugins/impact/Body.js +++ b/plugins/impact/Body.js @@ -1,595 +1,595 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var COLLIDES = require('./COLLIDES'); -var GetVelocity = require('./GetVelocity'); -var TYPE = require('./TYPE'); -var UpdateMotion = require('./UpdateMotion'); - -/** - * @callback Phaser.Types.Physics.Impact.BodyUpdateCallback - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} body - [description] - */ - -/** - * @classdesc - * An Impact.js compatible physics body. - * This re-creates the properties you'd get on an Entity and the math needed to update them. - * - * @class Body - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.World} world - [description] - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} [sx=16] - [description] - * @param {number} [sy=16] - [description] - */ -var Body = new Class({ - - initialize: - - function Body (world, x, y, sx, sy) - { - if (sx === undefined) { sx = 16; } - if (sy === undefined) { sy = sx; } - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#world - * @type {Phaser.Physics.Impact.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#gameObject - * @type {Phaser.GameObjects.GameObject} - * @default null - * @since 3.0.0 - */ - this.gameObject = null; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#enabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enabled = true; - - /** - * The ImpactBody, ImpactSprite or ImpactImage object that owns this Body, if any. - * - * @name Phaser.Physics.Impact.Body#parent - * @type {?(Phaser.Physics.Impact.ImpactBody|Phaser.Physics.Impact.ImpactImage|Phaser.Physics.Impact.ImpactSprite)} - * @since 3.0.0 - */ - this.parent; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#id - * @type {integer} - * @since 3.0.0 - */ - this.id = world.getNextID(); - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#name - * @type {string} - * @default '' - * @since 3.0.0 - */ - this.name = ''; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#size - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.size = { x: sx, y: sy }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#offset - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.offset = { x: 0, y: 0 }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#pos - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.pos = { x: x, y: y }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#last - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.last = { x: x, y: y }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#vel - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.vel = { x: 0, y: 0 }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#accel - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.accel = { x: 0, y: 0 }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#friction - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.friction = { x: 0, y: 0 }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#maxVel - * @type {Phaser.Types.Math.Vector2Like} - * @since 3.0.0 - */ - this.maxVel = { x: world.defaults.maxVelocityX, y: world.defaults.maxVelocityY }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#standing - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.standing = false; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#gravityFactor - * @type {number} - * @since 3.0.0 - */ - this.gravityFactor = world.defaults.gravityFactor; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#bounciness - * @type {number} - * @since 3.0.0 - */ - this.bounciness = world.defaults.bounciness; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#minBounceVelocity - * @type {number} - * @since 3.0.0 - */ - this.minBounceVelocity = world.defaults.minBounceVelocity; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#accelGround - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accelGround = 0; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#accelAir - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accelAir = 0; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#jumpSpeed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.jumpSpeed = 0; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#type - * @type {Phaser.Physics.Impact.TYPE} - * @since 3.0.0 - */ - this.type = TYPE.NONE; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#checkAgainst - * @type {Phaser.Physics.Impact.TYPE} - * @since 3.0.0 - */ - this.checkAgainst = TYPE.NONE; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#collides - * @type {Phaser.Physics.Impact.COLLIDES} - * @since 3.0.0 - */ - this.collides = COLLIDES.NEVER; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#debugShowBody - * @type {boolean} - * @since 3.0.0 - */ - this.debugShowBody = world.defaults.debugShowBody; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#debugShowVelocity - * @type {boolean} - * @since 3.0.0 - */ - this.debugShowVelocity = world.defaults.debugShowVelocity; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#debugBodyColor - * @type {integer} - * @since 3.0.0 - */ - this.debugBodyColor = world.defaults.bodyDebugColor; - - /** - * [description] - * - * @name Phaser.Physics.Impact.Body#updateCallback - * @type {?Phaser.Types.Physics.Impact.BodyUpdateCallback} - * @since 3.0.0 - */ - this.updateCallback; - - /** - * min 44 deg, max 136 deg - * - * @name Phaser.Physics.Impact.Body#slopeStanding - * @type {{ min: number, max: number }} - * @since 3.0.0 - */ - this.slopeStanding = { min: 0.767944870877505, max: 2.3736477827122884 }; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#reset - * @since 3.0.0 - * - * @param {number} x - [description] - * @param {number} y - [description] - */ - reset: function (x, y) - { - this.pos = { x: x, y: y }; - this.last = { x: x, y: y }; - this.vel = { x: 0, y: 0 }; - this.accel = { x: 0, y: 0 }; - this.friction = { x: 0, y: 0 }; - this.maxVel = { x: 100, y: 100 }; - - this.standing = false; - - this.gravityFactor = 1; - this.bounciness = 0; - this.minBounceVelocity = 40; - - this.accelGround = 0; - this.accelAir = 0; - this.jumpSpeed = 0; - - this.type = TYPE.NONE; - this.checkAgainst = TYPE.NONE; - this.collides = COLLIDES.NEVER; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#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. - */ - update: function (delta) - { - var pos = this.pos; - - this.last.x = pos.x; - this.last.y = pos.y; - - this.vel.y += this.world.gravity * delta * this.gravityFactor; - - this.vel.x = GetVelocity(delta, this.vel.x, this.accel.x, this.friction.x, this.maxVel.x); - this.vel.y = GetVelocity(delta, this.vel.y, this.accel.y, this.friction.y, this.maxVel.y); - - var mx = this.vel.x * delta; - var my = this.vel.y * delta; - - var res = this.world.collisionMap.trace(pos.x, pos.y, mx, my, this.size.x, this.size.y); - - if (this.handleMovementTrace(res)) - { - UpdateMotion(this, res); - } - - var go = this.gameObject; - - if (go) - { - go.x = (pos.x - this.offset.x) + go.displayOriginX * go.scaleX; - go.y = (pos.y - this.offset.y) + go.displayOriginY * go.scaleY; - } - - if (this.updateCallback) - { - this.updateCallback(this); - } - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#drawDebug - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphic - [description] - */ - drawDebug: function (graphic) - { - var pos = this.pos; - - if (this.debugShowBody) - { - graphic.lineStyle(1, this.debugBodyColor, 1); - graphic.strokeRect(pos.x, pos.y, this.size.x, this.size.y); - } - - if (this.debugShowVelocity) - { - var x = pos.x + this.size.x / 2; - var y = pos.y + this.size.y / 2; - - graphic.lineStyle(1, this.world.defaults.velocityDebugColor, 1); - graphic.lineBetween(x, y, x + this.vel.x, y + this.vel.y); - } - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#willDrawDebug - * @since 3.0.0 - * - * @return {boolean} [description] - */ - willDrawDebug: function () - { - return (this.debugShowBody || this.debugShowVelocity); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#skipHash - * @since 3.0.0 - * - * @return {boolean} [description] - */ - skipHash: function () - { - return (!this.enabled || (this.type === 0 && this.checkAgainst === 0 && this.collides === 0)); - }, - - /** - * Determines whether the body collides with the `other` one or not. - * - * @method Phaser.Physics.Impact.Body#touches - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} other - [description] - * - * @return {boolean} [description] - */ - touches: function (other) - { - return !( - this.pos.x >= other.pos.x + other.size.x || - this.pos.x + this.size.x <= other.pos.x || - this.pos.y >= other.pos.y + other.size.y || - this.pos.y + this.size.y <= other.pos.y - ); - }, - - /** - * Reset the size and position of the physics body. - * - * @method Phaser.Physics.Impact.Body#resetSize - * @since 3.0.0 - * - * @param {number} x - The x coordinate to position the body. - * @param {number} y - The y coordinate to position the body. - * @param {number} width - The width of the body. - * @param {number} height - The height of the body. - * - * @return {Phaser.Physics.Impact.Body} This Body object. - */ - resetSize: function (x, y, width, height) - { - this.pos.x = x; - this.pos.y = y; - this.size.x = width; - this.size.y = height; - - return this; - }, - - /** - * Export this body object to JSON. - * - * @method Phaser.Physics.Impact.Body#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Physics.Impact.JSONImpactBody} JSON representation of this body object. - */ - toJSON: function () - { - var output = { - name: this.name, - size: { x: this.size.x, y: this.size.y }, - pos: { x: this.pos.x, y: this.pos.y }, - vel: { x: this.vel.x, y: this.vel.y }, - accel: { x: this.accel.x, y: this.accel.y }, - friction: { x: this.friction.x, y: this.friction.y }, - maxVel: { x: this.maxVel.x, y: this.maxVel.y }, - gravityFactor: this.gravityFactor, - bounciness: this.bounciness, - minBounceVelocity: this.minBounceVelocity, - type: this.type, - checkAgainst: this.checkAgainst, - collides: this.collides - }; - - return output; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#fromJSON - * @todo Code it! - * @since 3.0.0 - * - * @param {object} config - [description] - */ - fromJSON: function () - { - }, - - /** - * Can be overridden by user code - * - * @method Phaser.Physics.Impact.Body#check - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} other - [description] - */ - check: function () - { - }, - - /** - * Can be overridden by user code - * - * @method Phaser.Physics.Impact.Body#collideWith - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} other - [description] - * @param {string} axis - [description] - */ - collideWith: function (other, axis) - { - if (this.parent && this.parent._collideCallback) - { - this.parent._collideCallback.call(this.parent._callbackScope, this, other, axis); - } - }, - - /** - * Can be overridden by user code but must return a boolean. - * - * @method Phaser.Physics.Impact.Body#handleMovementTrace - * @since 3.0.0 - * - * @param {number} res - [description] - * - * @return {boolean} [description] - */ - handleMovementTrace: function () - { - return true; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Body#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.world.remove(this); - - this.enabled = false; - - this.world = null; - - this.gameObject = null; - - this.parent = null; - } - -}); - -module.exports = Body; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var COLLIDES = require('./COLLIDES'); +var GetVelocity = require('./GetVelocity'); +var TYPE = require('./TYPE'); +var UpdateMotion = require('./UpdateMotion'); + +/** + * @callback Phaser.Types.Physics.Impact.BodyUpdateCallback + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + */ + +/** + * @classdesc + * An Impact.js compatible physics body. + * This re-creates the properties you'd get on an Entity and the math needed to update them. + * + * @class Body + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} [sx=16] - [description] + * @param {number} [sy=16] - [description] + */ +var Body = new Class({ + + initialize: + + function Body (world, x, y, sx, sy) + { + if (sx === undefined) { sx = 16; } + if (sy === undefined) { sy = sx; } + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#gameObject + * @type {Phaser.GameObjects.GameObject} + * @default null + * @since 3.0.0 + */ + this.gameObject = null; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The ImpactBody, ImpactSprite or ImpactImage object that owns this Body, if any. + * + * @name Phaser.Physics.Impact.Body#parent + * @type {?(Phaser.Physics.Impact.ImpactBody|Phaser.Physics.Impact.ImpactImage|Phaser.Physics.Impact.ImpactSprite)} + * @since 3.0.0 + */ + this.parent; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#id + * @type {integer} + * @since 3.0.0 + */ + this.id = world.getNextID(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#size + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.size = { x: sx, y: sy }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#offset + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.offset = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#pos + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.pos = { x: x, y: y }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#last + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.last = { x: x, y: y }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#vel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.vel = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.accel = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#friction + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.friction = { x: 0, y: 0 }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#maxVel + * @type {Phaser.Types.Math.Vector2Like} + * @since 3.0.0 + */ + this.maxVel = { x: world.defaults.maxVelocityX, y: world.defaults.maxVelocityY }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#standing + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.standing = false; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#gravityFactor + * @type {number} + * @since 3.0.0 + */ + this.gravityFactor = world.defaults.gravityFactor; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#bounciness + * @type {number} + * @since 3.0.0 + */ + this.bounciness = world.defaults.bounciness; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#minBounceVelocity + * @type {number} + * @since 3.0.0 + */ + this.minBounceVelocity = world.defaults.minBounceVelocity; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accelGround + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelGround = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#accelAir + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelAir = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#jumpSpeed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.jumpSpeed = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#type + * @type {Phaser.Physics.Impact.TYPE} + * @since 3.0.0 + */ + this.type = TYPE.NONE; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#checkAgainst + * @type {Phaser.Physics.Impact.TYPE} + * @since 3.0.0 + */ + this.checkAgainst = TYPE.NONE; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#collides + * @type {Phaser.Physics.Impact.COLLIDES} + * @since 3.0.0 + */ + this.collides = COLLIDES.NEVER; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowBody; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowVelocity = world.defaults.debugShowVelocity; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.bodyDebugColor; + + /** + * [description] + * + * @name Phaser.Physics.Impact.Body#updateCallback + * @type {?Phaser.Types.Physics.Impact.BodyUpdateCallback} + * @since 3.0.0 + */ + this.updateCallback; + + /** + * min 44 deg, max 136 deg + * + * @name Phaser.Physics.Impact.Body#slopeStanding + * @type {{ min: number, max: number }} + * @since 3.0.0 + */ + this.slopeStanding = { min: 0.767944870877505, max: 2.3736477827122884 }; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#reset + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + */ + reset: function (x, y) + { + this.pos = { x: x, y: y }; + this.last = { x: x, y: y }; + this.vel = { x: 0, y: 0 }; + this.accel = { x: 0, y: 0 }; + this.friction = { x: 0, y: 0 }; + this.maxVel = { x: 100, y: 100 }; + + this.standing = false; + + this.gravityFactor = 1; + this.bounciness = 0; + this.minBounceVelocity = 40; + + this.accelGround = 0; + this.accelAir = 0; + this.jumpSpeed = 0; + + this.type = TYPE.NONE; + this.checkAgainst = TYPE.NONE; + this.collides = COLLIDES.NEVER; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#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. + */ + update: function (delta) + { + var pos = this.pos; + + this.last.x = pos.x; + this.last.y = pos.y; + + this.vel.y += this.world.gravity * delta * this.gravityFactor; + + this.vel.x = GetVelocity(delta, this.vel.x, this.accel.x, this.friction.x, this.maxVel.x); + this.vel.y = GetVelocity(delta, this.vel.y, this.accel.y, this.friction.y, this.maxVel.y); + + var mx = this.vel.x * delta; + var my = this.vel.y * delta; + + var res = this.world.collisionMap.trace(pos.x, pos.y, mx, my, this.size.x, this.size.y); + + if (this.handleMovementTrace(res)) + { + UpdateMotion(this, res); + } + + var go = this.gameObject; + + if (go) + { + go.x = (pos.x - this.offset.x) + go.displayOriginX * go.scaleX; + go.y = (pos.y - this.offset.y) + go.displayOriginY * go.scaleY; + } + + if (this.updateCallback) + { + this.updateCallback(this); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - [description] + */ + drawDebug: function (graphic) + { + var pos = this.pos; + + if (this.debugShowBody) + { + graphic.lineStyle(1, this.debugBodyColor, 1); + graphic.strokeRect(pos.x, pos.y, this.size.x, this.size.y); + } + + if (this.debugShowVelocity) + { + var x = pos.x + this.size.x / 2; + var y = pos.y + this.size.y / 2; + + graphic.lineStyle(1, this.world.defaults.velocityDebugColor, 1); + graphic.lineBetween(x, y, x + this.vel.x, y + this.vel.y); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} [description] + */ + willDrawDebug: function () + { + return (this.debugShowBody || this.debugShowVelocity); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#skipHash + * @since 3.0.0 + * + * @return {boolean} [description] + */ + skipHash: function () + { + return (!this.enabled || (this.type === 0 && this.checkAgainst === 0 && this.collides === 0)); + }, + + /** + * Determines whether the body collides with the `other` one or not. + * + * @method Phaser.Physics.Impact.Body#touches + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + * + * @return {boolean} [description] + */ + touches: function (other) + { + return !( + this.pos.x >= other.pos.x + other.size.x || + this.pos.x + this.size.x <= other.pos.x || + this.pos.y >= other.pos.y + other.size.y || + this.pos.y + this.size.y <= other.pos.y + ); + }, + + /** + * Reset the size and position of the physics body. + * + * @method Phaser.Physics.Impact.Body#resetSize + * @since 3.0.0 + * + * @param {number} x - The x coordinate to position the body. + * @param {number} y - The y coordinate to position the body. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * + * @return {Phaser.Physics.Impact.Body} This Body object. + */ + resetSize: function (x, y, width, height) + { + this.pos.x = x; + this.pos.y = y; + this.size.x = width; + this.size.y = height; + + return this; + }, + + /** + * Export this body object to JSON. + * + * @method Phaser.Physics.Impact.Body#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Physics.Impact.JSONImpactBody} JSON representation of this body object. + */ + toJSON: function () + { + var output = { + name: this.name, + size: { x: this.size.x, y: this.size.y }, + pos: { x: this.pos.x, y: this.pos.y }, + vel: { x: this.vel.x, y: this.vel.y }, + accel: { x: this.accel.x, y: this.accel.y }, + friction: { x: this.friction.x, y: this.friction.y }, + maxVel: { x: this.maxVel.x, y: this.maxVel.y }, + gravityFactor: this.gravityFactor, + bounciness: this.bounciness, + minBounceVelocity: this.minBounceVelocity, + type: this.type, + checkAgainst: this.checkAgainst, + collides: this.collides + }; + + return output; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#fromJSON + * @todo Code it! + * @since 3.0.0 + * + * @param {object} config - [description] + */ + fromJSON: function () + { + }, + + /** + * Can be overridden by user code + * + * @method Phaser.Physics.Impact.Body#check + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + */ + check: function () + { + }, + + /** + * Can be overridden by user code + * + * @method Phaser.Physics.Impact.Body#collideWith + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} other - [description] + * @param {string} axis - [description] + */ + collideWith: function (other, axis) + { + if (this.parent && this.parent._collideCallback) + { + this.parent._collideCallback.call(this.parent._callbackScope, this, other, axis); + } + }, + + /** + * Can be overridden by user code but must return a boolean. + * + * @method Phaser.Physics.Impact.Body#handleMovementTrace + * @since 3.0.0 + * + * @param {number} res - [description] + * + * @return {boolean} [description] + */ + handleMovementTrace: function () + { + return true; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Body#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.remove(this); + + this.enabled = false; + + this.world = null; + + this.gameObject = null; + + this.parent = null; + } + +}); + +module.exports = Body; diff --git a/plugins/impact/COLLIDES.js b/plugins/impact/COLLIDES.js index c454a69d5..f1416958c 100644 --- a/plugins/impact/COLLIDES.js +++ b/plugins/impact/COLLIDES.js @@ -1,73 +1,73 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Collision Types - Determine if and how entities collide with each other. - * - * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, - * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE - * collisions, both entities are moved. LITE or PASSIVE entities don't collide - * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. - * FIXED collisions is undefined. - * - * @namespace Phaser.Physics.Impact.COLLIDES - * @memberof Phaser.Physics.Impact - * @since 3.0.0 - */ - -module.exports = { - - /** - * Never collides. - * - * @name Phaser.Physics.Impact.COLLIDES.NEVER - * @type {integer} - * @const - * @since 3.0.0 - */ - NEVER: 0, - - /** - * Lite collision. - * - * @name Phaser.Physics.Impact.COLLIDES.LITE - * @type {integer} - * @const - * @since 3.0.0 - */ - LITE: 1, - - /** - * Passive collision. - * - * @name Phaser.Physics.Impact.COLLIDES.PASSIVE - * @type {integer} - * @const - * @since 3.0.0 - */ - PASSIVE: 2, - - /** - * Active collision. - * - * @name Phaser.Physics.Impact.COLLIDES.ACTIVE - * @type {integer} - * @const - * @since 3.0.0 - */ - ACTIVE: 4, - - /** - * Fixed collision. - * - * @name Phaser.Physics.Impact.COLLIDES.FIXED - * @type {integer} - * @const - * @since 3.0.0 - */ - FIXED: 8 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + * + * @namespace Phaser.Physics.Impact.COLLIDES + * @memberof Phaser.Physics.Impact + * @since 3.0.0 + */ + +module.exports = { + + /** + * Never collides. + * + * @name Phaser.Physics.Impact.COLLIDES.NEVER + * @type {integer} + * @const + * @since 3.0.0 + */ + NEVER: 0, + + /** + * Lite collision. + * + * @name Phaser.Physics.Impact.COLLIDES.LITE + * @type {integer} + * @const + * @since 3.0.0 + */ + LITE: 1, + + /** + * Passive collision. + * + * @name Phaser.Physics.Impact.COLLIDES.PASSIVE + * @type {integer} + * @const + * @since 3.0.0 + */ + PASSIVE: 2, + + /** + * Active collision. + * + * @name Phaser.Physics.Impact.COLLIDES.ACTIVE + * @type {integer} + * @const + * @since 3.0.0 + */ + ACTIVE: 4, + + /** + * Fixed collision. + * + * @name Phaser.Physics.Impact.COLLIDES.FIXED + * @type {integer} + * @const + * @since 3.0.0 + */ + FIXED: 8 + +}; diff --git a/plugins/impact/CollisionMap.js b/plugins/impact/CollisionMap.js index c3e221835..862ce7524 100644 --- a/plugins/impact/CollisionMap.js +++ b/plugins/impact/CollisionMap.js @@ -1,358 +1,358 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var DefaultDefs = require('./DefaultDefs'); - -/** - * @classdesc - * [description] - * - * @class CollisionMap - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @param {integer} [tilesize=32] - [description] - * @param {array} [data] - [description] - */ -var CollisionMap = new Class({ - - initialize: - - function CollisionMap (tilesize, data) - { - if (tilesize === undefined) { tilesize = 32; } - - /** - * [description] - * - * @name Phaser.Physics.Impact.CollisionMap#tilesize - * @type {integer} - * @default 32 - * @since 3.0.0 - */ - this.tilesize = tilesize; - - /** - * [description] - * - * @name Phaser.Physics.Impact.CollisionMap#data - * @type {array} - * @since 3.0.0 - */ - this.data = (Array.isArray(data)) ? data : []; - - /** - * [description] - * - * @name Phaser.Physics.Impact.CollisionMap#width - * @type {number} - * @since 3.0.0 - */ - this.width = (Array.isArray(data)) ? data[0].length : 0; - - /** - * [description] - * - * @name Phaser.Physics.Impact.CollisionMap#height - * @type {number} - * @since 3.0.0 - */ - this.height = (Array.isArray(data)) ? data.length : 0; - - /** - * [description] - * - * @name Phaser.Physics.Impact.CollisionMap#lastSlope - * @type {integer} - * @default 55 - * @since 3.0.0 - */ - this.lastSlope = 55; - - /** - * [description] - * - * @name Phaser.Physics.Impact.CollisionMap#tiledef - * @type {object} - * @since 3.0.0 - */ - this.tiledef = DefaultDefs; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.CollisionMap#trace - * @since 3.0.0 - * - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} vx - [description] - * @param {number} vy - [description] - * @param {number} objectWidth - [description] - * @param {number} objectHeight - [description] - * - * @return {boolean} [description] - */ - trace: function (x, y, vx, vy, objectWidth, objectHeight) - { - // Set up the trace-result - var res = { - collision: { x: false, y: false, slope: false }, - pos: { x: x + vx, y: y + vy }, - tile: { x: 0, y: 0 } - }; - - if (!this.data) - { - return res; - } - - var steps = Math.ceil(Math.max(Math.abs(vx), Math.abs(vy)) / this.tilesize); - - if (steps > 1) - { - var sx = vx / steps; - var sy = vy / steps; - - for (var i = 0; i < steps && (sx || sy); i++) - { - this.step(res, x, y, sx, sy, objectWidth, objectHeight, vx, vy, i); - - x = res.pos.x; - y = res.pos.y; - - if (res.collision.x) - { - sx = 0; - vx = 0; - } - - if (res.collision.y) - { - sy = 0; - vy = 0; - } - - if (res.collision.slope) - { - break; - } - } - } - else - { - this.step(res, x, y, vx, vy, objectWidth, objectHeight, vx, vy, 0); - } - - return res; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.CollisionMap#step - * @since 3.0.0 - * - * @param {object} res - [description] - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} vx - [description] - * @param {number} vy - [description] - * @param {number} width - [description] - * @param {number} height - [description] - * @param {number} rvx - [description] - * @param {number} rvy - [description] - * @param {number} step - [description] - */ - step: function (res, x, y, vx, vy, width, height, rvx, rvy, step) - { - var t = 0; - var tileX; - var tileY; - var tilesize = this.tilesize; - var mapWidth = this.width; - var mapHeight = this.height; - - // Horizontal - if (vx) - { - var pxOffsetX = (vx > 0 ? width : 0); - var tileOffsetX = (vx < 0 ? tilesize : 0); - - var firstTileY = Math.max(Math.floor(y / tilesize), 0); - var lastTileY = Math.min(Math.ceil((y + height) / tilesize), mapHeight); - - tileX = Math.floor((res.pos.x + pxOffsetX) / tilesize); - - var prevTileX = Math.floor((x + pxOffsetX) / tilesize); - - if (step > 0 || tileX === prevTileX || prevTileX < 0 || prevTileX >= mapWidth) - { - prevTileX = -1; - } - - if (tileX >= 0 && tileX < mapWidth) - { - for (tileY = firstTileY; tileY < lastTileY; tileY++) - { - if (prevTileX !== -1) - { - t = this.data[tileY][prevTileX]; - - if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, prevTileX, tileY)) - { - break; - } - } - - t = this.data[tileY][tileX]; - - if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) - { - if (t > 1 && t <= this.lastSlope && res.collision.slope) - { - break; - } - - res.collision.x = true; - res.tile.x = t; - res.pos.x = (tileX * tilesize) - pxOffsetX + tileOffsetX; - x = res.pos.x; - rvx = 0; - - break; - } - } - } - } - - // Vertical - if (vy) - { - var pxOffsetY = (vy > 0 ? height : 0); - var tileOffsetY = (vy < 0 ? tilesize : 0); - - var firstTileX = Math.max(Math.floor(res.pos.x / tilesize), 0); - var lastTileX = Math.min(Math.ceil((res.pos.x + width) / tilesize), mapWidth); - - tileY = Math.floor((res.pos.y + pxOffsetY) / tilesize); - - var prevTileY = Math.floor((y + pxOffsetY) / tilesize); - - if (step > 0 || tileY === prevTileY || prevTileY < 0 || prevTileY >= mapHeight) - { - prevTileY = -1; - } - - if (tileY >= 0 && tileY < mapHeight) - { - for (tileX = firstTileX; tileX < lastTileX; tileX++) - { - if (prevTileY !== -1) - { - t = this.data[prevTileY][tileX]; - - if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, prevTileY)) - { - break; - } - } - - t = this.data[tileY][tileX]; - - if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) - { - if (t > 1 && t <= this.lastSlope && res.collision.slope) - { - break; - } - - res.collision.y = true; - res.tile.y = t; - res.pos.y = tileY * tilesize - pxOffsetY + tileOffsetY; - - break; - } - } - } - } - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.CollisionMap#checkDef - * @since 3.0.0 - * - * @param {object} res - [description] - * @param {number} t - [description] - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} vx - [description] - * @param {number} vy - [description] - * @param {number} width - [description] - * @param {number} height - [description] - * @param {number} tileX - [description] - * @param {number} tileY - [description] - * - * @return {boolean} [description] - */ - checkDef: function (res, t, x, y, vx, vy, width, height, tileX, tileY) - { - var def = this.tiledef[t]; - - if (!def) - { - return false; - } - - var tilesize = this.tilesize; - - var lx = (tileX + def[0]) * tilesize; - var ly = (tileY + def[1]) * tilesize; - var lvx = (def[2] - def[0]) * tilesize; - var lvy = (def[3] - def[1]) * tilesize; - var solid = def[4]; - - var tx = x + vx + (lvy < 0 ? width : 0) - lx; - var ty = y + vy + (lvx > 0 ? height : 0) - ly; - - if (lvx * ty - lvy * tx > 0) - { - if (vx * -lvy + vy * lvx < 0) - { - return solid; - } - - var length = Math.sqrt(lvx * lvx + lvy * lvy); - var nx = lvy / length; - var ny = -lvx / length; - - var proj = tx * nx + ty * ny; - var px = nx * proj; - var py = ny * proj; - - if (px * px + py * py >= vx * vx + vy * vy) - { - return solid || (lvx * (ty - vy) - lvy * (tx - vx) < 0.5); - } - - res.pos.x = x + vx - px; - res.pos.y = y + vy - py; - res.collision.slope = { x: lvx, y: lvy, nx: nx, ny: ny }; - - return true; - } - - return false; - } - -}); - -module.exports = CollisionMap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var DefaultDefs = require('./DefaultDefs'); + +/** + * @classdesc + * [description] + * + * @class CollisionMap + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {integer} [tilesize=32] - [description] + * @param {array} [data] - [description] + */ +var CollisionMap = new Class({ + + initialize: + + function CollisionMap (tilesize, data) + { + if (tilesize === undefined) { tilesize = 32; } + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#tilesize + * @type {integer} + * @default 32 + * @since 3.0.0 + */ + this.tilesize = tilesize; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#data + * @type {array} + * @since 3.0.0 + */ + this.data = (Array.isArray(data)) ? data : []; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#width + * @type {number} + * @since 3.0.0 + */ + this.width = (Array.isArray(data)) ? data[0].length : 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#height + * @type {number} + * @since 3.0.0 + */ + this.height = (Array.isArray(data)) ? data.length : 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#lastSlope + * @type {integer} + * @default 55 + * @since 3.0.0 + */ + this.lastSlope = 55; + + /** + * [description] + * + * @name Phaser.Physics.Impact.CollisionMap#tiledef + * @type {object} + * @since 3.0.0 + */ + this.tiledef = DefaultDefs; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#trace + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} objectWidth - [description] + * @param {number} objectHeight - [description] + * + * @return {boolean} [description] + */ + trace: function (x, y, vx, vy, objectWidth, objectHeight) + { + // Set up the trace-result + var res = { + collision: { x: false, y: false, slope: false }, + pos: { x: x + vx, y: y + vy }, + tile: { x: 0, y: 0 } + }; + + if (!this.data) + { + return res; + } + + var steps = Math.ceil(Math.max(Math.abs(vx), Math.abs(vy)) / this.tilesize); + + if (steps > 1) + { + var sx = vx / steps; + var sy = vy / steps; + + for (var i = 0; i < steps && (sx || sy); i++) + { + this.step(res, x, y, sx, sy, objectWidth, objectHeight, vx, vy, i); + + x = res.pos.x; + y = res.pos.y; + + if (res.collision.x) + { + sx = 0; + vx = 0; + } + + if (res.collision.y) + { + sy = 0; + vy = 0; + } + + if (res.collision.slope) + { + break; + } + } + } + else + { + this.step(res, x, y, vx, vy, objectWidth, objectHeight, vx, vy, 0); + } + + return res; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#step + * @since 3.0.0 + * + * @param {object} res - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} rvx - [description] + * @param {number} rvy - [description] + * @param {number} step - [description] + */ + step: function (res, x, y, vx, vy, width, height, rvx, rvy, step) + { + var t = 0; + var tileX; + var tileY; + var tilesize = this.tilesize; + var mapWidth = this.width; + var mapHeight = this.height; + + // Horizontal + if (vx) + { + var pxOffsetX = (vx > 0 ? width : 0); + var tileOffsetX = (vx < 0 ? tilesize : 0); + + var firstTileY = Math.max(Math.floor(y / tilesize), 0); + var lastTileY = Math.min(Math.ceil((y + height) / tilesize), mapHeight); + + tileX = Math.floor((res.pos.x + pxOffsetX) / tilesize); + + var prevTileX = Math.floor((x + pxOffsetX) / tilesize); + + if (step > 0 || tileX === prevTileX || prevTileX < 0 || prevTileX >= mapWidth) + { + prevTileX = -1; + } + + if (tileX >= 0 && tileX < mapWidth) + { + for (tileY = firstTileY; tileY < lastTileY; tileY++) + { + if (prevTileX !== -1) + { + t = this.data[tileY][prevTileX]; + + if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, prevTileX, tileY)) + { + break; + } + } + + t = this.data[tileY][tileX]; + + if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) + { + if (t > 1 && t <= this.lastSlope && res.collision.slope) + { + break; + } + + res.collision.x = true; + res.tile.x = t; + res.pos.x = (tileX * tilesize) - pxOffsetX + tileOffsetX; + x = res.pos.x; + rvx = 0; + + break; + } + } + } + } + + // Vertical + if (vy) + { + var pxOffsetY = (vy > 0 ? height : 0); + var tileOffsetY = (vy < 0 ? tilesize : 0); + + var firstTileX = Math.max(Math.floor(res.pos.x / tilesize), 0); + var lastTileX = Math.min(Math.ceil((res.pos.x + width) / tilesize), mapWidth); + + tileY = Math.floor((res.pos.y + pxOffsetY) / tilesize); + + var prevTileY = Math.floor((y + pxOffsetY) / tilesize); + + if (step > 0 || tileY === prevTileY || prevTileY < 0 || prevTileY >= mapHeight) + { + prevTileY = -1; + } + + if (tileY >= 0 && tileY < mapHeight) + { + for (tileX = firstTileX; tileX < lastTileX; tileX++) + { + if (prevTileY !== -1) + { + t = this.data[prevTileY][tileX]; + + if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, prevTileY)) + { + break; + } + } + + t = this.data[tileY][tileX]; + + if (t === 1 || t > this.lastSlope || (t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY))) + { + if (t > 1 && t <= this.lastSlope && res.collision.slope) + { + break; + } + + res.collision.y = true; + res.tile.y = t; + res.pos.y = tileY * tilesize - pxOffsetY + tileOffsetY; + + break; + } + } + } + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.CollisionMap#checkDef + * @since 3.0.0 + * + * @param {object} res - [description] + * @param {number} t - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} vx - [description] + * @param {number} vy - [description] + * @param {number} width - [description] + * @param {number} height - [description] + * @param {number} tileX - [description] + * @param {number} tileY - [description] + * + * @return {boolean} [description] + */ + checkDef: function (res, t, x, y, vx, vy, width, height, tileX, tileY) + { + var def = this.tiledef[t]; + + if (!def) + { + return false; + } + + var tilesize = this.tilesize; + + var lx = (tileX + def[0]) * tilesize; + var ly = (tileY + def[1]) * tilesize; + var lvx = (def[2] - def[0]) * tilesize; + var lvy = (def[3] - def[1]) * tilesize; + var solid = def[4]; + + var tx = x + vx + (lvy < 0 ? width : 0) - lx; + var ty = y + vy + (lvx > 0 ? height : 0) - ly; + + if (lvx * ty - lvy * tx > 0) + { + if (vx * -lvy + vy * lvx < 0) + { + return solid; + } + + var length = Math.sqrt(lvx * lvx + lvy * lvy); + var nx = lvy / length; + var ny = -lvx / length; + + var proj = tx * nx + ty * ny; + var px = nx * proj; + var py = ny * proj; + + if (px * px + py * py >= vx * vx + vy * vy) + { + return solid || (lvx * (ty - vy) - lvy * (tx - vx) < 0.5); + } + + res.pos.x = x + vx - px; + res.pos.y = y + vy - py; + res.collision.slope = { x: lvx, y: lvy, nx: nx, ny: ny }; + + return true; + } + + return false; + } + +}); + +module.exports = CollisionMap; diff --git a/plugins/impact/DefaultDefs.js b/plugins/impact/DefaultDefs.js index 0a7392307..609003fb0 100644 --- a/plugins/impact/DefaultDefs.js +++ b/plugins/impact/DefaultDefs.js @@ -1,65 +1,65 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var H = 0.5; -var N = 1 / 3; -var M = 2 / 3; - -// Tile ID to Slope defs. -// First 4 elements = line data, final = solid or non-solid behind the line - -module.exports = { - - 2: [ 0, 1, 1, 0, true ], - 3: [ 0, 1, 1, H, true ], - 4: [ 0, H, 1, 0, true ], - 5: [ 0, 1, 1, M, true ], - 6: [ 0, M, 1, N, true ], - 7: [ 0, N, 1, 0, true ], - 8: [ H, 1, 0, 0, true ], - 9: [ 1, 0, H, 1, true ], - 10: [ H, 1, 1, 0, true ], - 11: [ 0, 0, H, 1, true ], - 12: [ 0, 0, 1, 0, false ], - 13: [ 1, 1, 0, 0, true ], - 14: [ 1, H, 0, 0, true ], - 15: [ 1, 1, 0, H, true ], - 16: [ 1, N, 0, 0, true ], - 17: [ 1, M, 0, N, true ], - 18: [ 1, 1, 0, M, true ], - 19: [ 1, 1, H, 0, true ], - 20: [ H, 0, 0, 1, true ], - 21: [ 0, 1, H, 0, true ], - 22: [ H, 0, 1, 1, true ], - 23: [ 1, 1, 0, 1, false ], - 24: [ 0, 0, 1, 1, true ], - 25: [ 0, 0, 1, H, true ], - 26: [ 0, H, 1, 1, true ], - 27: [ 0, 0, 1, N, true ], - 28: [ 0, N, 1, M, true ], - 29: [ 0, M, 1, 1, true ], - 30: [ N, 1, 0, 0, true ], - 31: [ 1, 0, M, 1, true ], - 32: [ M, 1, 1, 0, true ], - 33: [ 0, 0, N, 1, true ], - 34: [ 1, 0, 1, 1, false ], - 35: [ 1, 0, 0, 1, true ], - 36: [ 1, H, 0, 1, true ], - 37: [ 1, 0, 0, H, true ], - 38: [ 1, M, 0, 1, true ], - 39: [ 1, N, 0, M, true ], - 40: [ 1, 0, 0, N, true ], - 41: [ M, 1, N, 0, true ], - 42: [ M, 0, N, 1, true ], - 43: [ N, 1, M, 0, true ], - 44: [ N, 0, M, 1, true ], - 45: [ 0, 1, 0, 0, false ], - 52: [ 1, 1, M, 0, true ], - 53: [ N, 0, 0, 1, true ], - 54: [ 0, 1, N, 0, true ], - 55: [ M, 0, 1, 1, true ] - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var H = 0.5; +var N = 1 / 3; +var M = 2 / 3; + +// Tile ID to Slope defs. +// First 4 elements = line data, final = solid or non-solid behind the line + +module.exports = { + + 2: [ 0, 1, 1, 0, true ], + 3: [ 0, 1, 1, H, true ], + 4: [ 0, H, 1, 0, true ], + 5: [ 0, 1, 1, M, true ], + 6: [ 0, M, 1, N, true ], + 7: [ 0, N, 1, 0, true ], + 8: [ H, 1, 0, 0, true ], + 9: [ 1, 0, H, 1, true ], + 10: [ H, 1, 1, 0, true ], + 11: [ 0, 0, H, 1, true ], + 12: [ 0, 0, 1, 0, false ], + 13: [ 1, 1, 0, 0, true ], + 14: [ 1, H, 0, 0, true ], + 15: [ 1, 1, 0, H, true ], + 16: [ 1, N, 0, 0, true ], + 17: [ 1, M, 0, N, true ], + 18: [ 1, 1, 0, M, true ], + 19: [ 1, 1, H, 0, true ], + 20: [ H, 0, 0, 1, true ], + 21: [ 0, 1, H, 0, true ], + 22: [ H, 0, 1, 1, true ], + 23: [ 1, 1, 0, 1, false ], + 24: [ 0, 0, 1, 1, true ], + 25: [ 0, 0, 1, H, true ], + 26: [ 0, H, 1, 1, true ], + 27: [ 0, 0, 1, N, true ], + 28: [ 0, N, 1, M, true ], + 29: [ 0, M, 1, 1, true ], + 30: [ N, 1, 0, 0, true ], + 31: [ 1, 0, M, 1, true ], + 32: [ M, 1, 1, 0, true ], + 33: [ 0, 0, N, 1, true ], + 34: [ 1, 0, 1, 1, false ], + 35: [ 1, 0, 0, 1, true ], + 36: [ 1, H, 0, 1, true ], + 37: [ 1, 0, 0, H, true ], + 38: [ 1, M, 0, 1, true ], + 39: [ 1, N, 0, M, true ], + 40: [ 1, 0, 0, N, true ], + 41: [ M, 1, N, 0, true ], + 42: [ M, 0, N, 1, true ], + 43: [ N, 1, M, 0, true ], + 44: [ N, 0, M, 1, true ], + 45: [ 0, 1, 0, 0, false ], + 52: [ 1, 1, M, 0, true ], + 53: [ N, 0, 0, 1, true ], + 54: [ 0, 1, N, 0, true ], + 55: [ M, 0, 1, 1, true ] + +}; diff --git a/plugins/impact/Factory.js b/plugins/impact/Factory.js index ac8035a51..9cecc7fa4 100644 --- a/plugins/impact/Factory.js +++ b/plugins/impact/Factory.js @@ -1,151 +1,151 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var ImpactBody = require('./ImpactBody'); -var ImpactImage = require('./ImpactImage'); -var ImpactSprite = require('./ImpactSprite'); - -/** - * @classdesc - * The Impact Physics Factory allows you to easily create Impact Physics enabled Game Objects. - * Objects that are created by this Factory are automatically added to the physics world. - * - * @class Factory - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.World} world - A reference to the Impact Physics world. - */ -var Factory = new Class({ - - initialize: - - function Factory (world) - { - /** - * A reference to the Impact Physics world. - * - * @name Phaser.Physics.Impact.Factory#world - * @type {Phaser.Physics.Impact.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * A reference to the Scene.Systems this Impact Physics instance belongs to. - * - * @name Phaser.Physics.Impact.Factory#sys - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.sys = world.scene.sys; - }, - - /** - * Creates a new ImpactBody object and adds it to the physics simulation. - * - * @method Phaser.Physics.Impact.Factory#body - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the body in the physics world. - * @param {number} y - The vertical position of the body in the physics world. - * @param {number} width - The width of the body. - * @param {number} height - The height of the body. - * - * @return {Phaser.Physics.Impact.ImpactBody} The ImpactBody object that was created. - */ - body: function (x, y, width, height) - { - return new ImpactBody(this.world, x, y, width, height); - }, - - /** - * Adds an Impact Physics Body to the given Game Object. - * - * @method Phaser.Physics.Impact.Factory#existing - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to receive the physics body. - * - * @return {Phaser.GameObjects.GameObject} The Game Object. - */ - existing: function (gameObject) - { - var x = gameObject.x - gameObject.frame.centerX; - var y = gameObject.y - gameObject.frame.centerY; - var w = gameObject.width; - var h = gameObject.height; - - gameObject.body = this.world.create(x, y, w, h); - - gameObject.body.parent = gameObject; - gameObject.body.gameObject = gameObject; - - return gameObject; - }, - - /** - * Creates a new ImpactImage object and adds it to the physics world. - * - * @method Phaser.Physics.Impact.Factory#image - * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.Physics.Impact.ImpactImage} The ImpactImage object that was created. - */ - image: function (x, y, key, frame) - { - var image = new ImpactImage(this.world, x, y, key, frame); - - this.sys.displayList.add(image); - - return image; - }, - - /** - * Creates a new ImpactSprite object and adds it to the physics world. - * - * @method Phaser.Physics.Impact.Factory#sprite - * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.Physics.Impact.ImpactSprite} The ImpactSprite object that was created. - */ - sprite: function (x, y, key, frame) - { - var sprite = new ImpactSprite(this.world, x, y, key, frame); - - this.sys.displayList.add(sprite); - this.sys.updateList.add(sprite); - - return sprite; - }, - - /** - * Destroys this Factory. - * - * @method Phaser.Physics.Impact.Factory#destroy - * @since 3.5.0 - */ - destroy: function () - { - this.world = null; - this.sys = null; - } - -}); - -module.exports = Factory; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var ImpactBody = require('./ImpactBody'); +var ImpactImage = require('./ImpactImage'); +var ImpactSprite = require('./ImpactSprite'); + +/** + * @classdesc + * The Impact Physics Factory allows you to easily create Impact Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + * + * @class Factory + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - A reference to the Impact Physics world. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * A reference to the Impact Physics world. + * + * @name Phaser.Physics.Impact.Factory#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * A reference to the Scene.Systems this Impact Physics instance belongs to. + * + * @name Phaser.Physics.Impact.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new ImpactBody object and adds it to the physics simulation. + * + * @method Phaser.Physics.Impact.Factory#body + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the body in the physics world. + * @param {number} y - The vertical position of the body in the physics world. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * + * @return {Phaser.Physics.Impact.ImpactBody} The ImpactBody object that was created. + */ + body: function (x, y, width, height) + { + return new ImpactBody(this.world, x, y, width, height); + }, + + /** + * Adds an Impact Physics Body to the given Game Object. + * + * @method Phaser.Physics.Impact.Factory#existing + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to receive the physics body. + * + * @return {Phaser.GameObjects.GameObject} The Game Object. + */ + existing: function (gameObject) + { + var x = gameObject.x - gameObject.frame.centerX; + var y = gameObject.y - gameObject.frame.centerY; + var w = gameObject.width; + var h = gameObject.height; + + gameObject.body = this.world.create(x, y, w, h); + + gameObject.body.parent = gameObject; + gameObject.body.gameObject = gameObject; + + return gameObject; + }, + + /** + * Creates a new ImpactImage object and adds it to the physics world. + * + * @method Phaser.Physics.Impact.Factory#image + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Impact.ImpactImage} The ImpactImage object that was created. + */ + image: function (x, y, key, frame) + { + var image = new ImpactImage(this.world, x, y, key, frame); + + this.sys.displayList.add(image); + + return image; + }, + + /** + * Creates a new ImpactSprite object and adds it to the physics world. + * + * @method Phaser.Physics.Impact.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Impact.ImpactSprite} The ImpactSprite object that was created. + */ + sprite: function (x, y, key, frame) + { + var sprite = new ImpactSprite(this.world, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + return sprite; + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Impact.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.sys = null; + } + +}); + +module.exports = Factory; diff --git a/plugins/impact/GetVelocity.js b/plugins/impact/GetVelocity.js index 30f8c0b15..3a0f40834 100644 --- a/plugins/impact/GetVelocity.js +++ b/plugins/impact/GetVelocity.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../math/Clamp'); - -/** - * [description] - * - * @function Phaser.Physics.Impact.GetVelocity - * @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. - * @param {number} vel - [description] - * @param {number} accel - [description] - * @param {number} friction - [description] - * @param {number} max - [description] - * - * @return {number} [description] - */ -var GetVelocity = function (delta, vel, accel, friction, max) -{ - if (accel) - { - return Clamp(vel + accel * delta, -max, max); - } - else if (friction) - { - var frictionDelta = friction * delta; - - if (vel - frictionDelta > 0) - { - return vel - frictionDelta; - } - else if (vel + frictionDelta < 0) - { - return vel + frictionDelta; - } - else - { - return 0; - } - } - - return Clamp(vel, -max, max); -}; - -module.exports = GetVelocity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../math/Clamp'); + +/** + * [description] + * + * @function Phaser.Physics.Impact.GetVelocity + * @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. + * @param {number} vel - [description] + * @param {number} accel - [description] + * @param {number} friction - [description] + * @param {number} max - [description] + * + * @return {number} [description] + */ +var GetVelocity = function (delta, vel, accel, friction, max) +{ + if (accel) + { + return Clamp(vel + accel * delta, -max, max); + } + else if (friction) + { + var frictionDelta = friction * delta; + + if (vel - frictionDelta > 0) + { + return vel - frictionDelta; + } + else if (vel + frictionDelta < 0) + { + return vel + frictionDelta; + } + else + { + return 0; + } + } + + return Clamp(vel, -max, max); +}; + +module.exports = GetVelocity; diff --git a/plugins/impact/ImpactBody.js b/plugins/impact/ImpactBody.js index c22c0d64a..3098f7e84 100644 --- a/plugins/impact/ImpactBody.js +++ b/plugins/impact/ImpactBody.js @@ -1,127 +1,127 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('./components'); - -/** - * @classdesc - * [description] - * - * @class ImpactBody - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Impact.Components.Acceleration - * @extends Phaser.Physics.Impact.Components.BodyScale - * @extends Phaser.Physics.Impact.Components.BodyType - * @extends Phaser.Physics.Impact.Components.Bounce - * @extends Phaser.Physics.Impact.Components.CheckAgainst - * @extends Phaser.Physics.Impact.Components.Collides - * @extends Phaser.Physics.Impact.Components.Debug - * @extends Phaser.Physics.Impact.Components.Friction - * @extends Phaser.Physics.Impact.Components.Gravity - * @extends Phaser.Physics.Impact.Components.Offset - * @extends Phaser.Physics.Impact.Components.SetGameObject - * @extends Phaser.Physics.Impact.Components.Velocity - * - * @param {Phaser.Physics.Impact.World} world - [description] - * @param {number} x - x - The horizontal position of this physics body in the world. - * @param {number} y - y - The vertical position of this physics body in the world. - * @param {number} width - The width of the physics body in the world. - * @param {number} height - [description] - */ -var ImpactBody = new Class({ - - Mixins: [ - Components.Acceleration, - Components.BodyScale, - Components.BodyType, - Components.Bounce, - Components.CheckAgainst, - Components.Collides, - Components.Debug, - Components.Friction, - Components.Gravity, - Components.Offset, - Components.SetGameObject, - Components.Velocity - ], - - initialize: - - function ImpactBody (world, x, y, width, height) - { - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#body - * @type {Phaser.Physics.Impact.Body} - * @since 3.0.0 - */ - this.body = world.create(x, y, width, height); - - this.body.parent = this; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#size - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.size = this.body.size; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#offset - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.offset = this.body.offset; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#vel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.vel = this.body.vel; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#accel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.accel = this.body.accel; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#friction - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.friction = this.body.friction; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactBody#maxVel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.maxVel = this.body.maxVel; - } - -}); - -module.exports = ImpactBody; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('./components'); + +/** + * @classdesc + * [description] + * + * @class ImpactBody + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {number} x - x - The horizontal position of this physics body in the world. + * @param {number} y - y - The vertical position of this physics body in the world. + * @param {number} width - The width of the physics body in the world. + * @param {number} height - [description] + */ +var ImpactBody = new Class({ + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactBody (world, x, y, width, height) + { + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x, y, width, height); + + this.body.parent = this; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactBody#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactBody; diff --git a/plugins/impact/ImpactImage.js b/plugins/impact/ImpactImage.js index 0f15a478c..173e8049a 100644 --- a/plugins/impact/ImpactImage.js +++ b/plugins/impact/ImpactImage.js @@ -1,152 +1,152 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('./components'); -var Image = require('../../gameobjects/image/Image'); - -/** - * @classdesc - * An Impact Physics Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * - * @class ImpactImage - * @extends Phaser.GameObjects.Image - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Impact.Components.Acceleration - * @extends Phaser.Physics.Impact.Components.BodyScale - * @extends Phaser.Physics.Impact.Components.BodyType - * @extends Phaser.Physics.Impact.Components.Bounce - * @extends Phaser.Physics.Impact.Components.CheckAgainst - * @extends Phaser.Physics.Impact.Components.Collides - * @extends Phaser.Physics.Impact.Components.Debug - * @extends Phaser.Physics.Impact.Components.Friction - * @extends Phaser.Physics.Impact.Components.Gravity - * @extends Phaser.Physics.Impact.Components.Offset - * @extends Phaser.Physics.Impact.Components.SetGameObject - * @extends Phaser.Physics.Impact.Components.Velocity - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Tint - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Physics.Impact.World} world - The physics world of the Impact physics system. - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var ImpactImage = new Class({ - - Extends: Image, - - Mixins: [ - Components.Acceleration, - Components.BodyScale, - Components.BodyType, - Components.Bounce, - Components.CheckAgainst, - Components.Collides, - Components.Debug, - Components.Friction, - Components.Gravity, - Components.Offset, - Components.SetGameObject, - Components.Velocity - ], - - initialize: - - function ImpactImage (world, x, y, texture, frame) - { - Image.call(this, world.scene, x, y, texture, frame); - - /** - * The Physics Body linked to an ImpactImage. - * - * @name Phaser.Physics.Impact.ImpactImage#body - * @type {Phaser.Physics.Impact.Body} - * @since 3.0.0 - */ - this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); - - this.body.parent = this; - this.body.gameObject = this; - - /** - * The size of the physics Body. - * - * @name Phaser.Physics.Impact.ImpactImage#size - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.size = this.body.size; - - /** - * The X and Y offset of the Body from the left and top of the Image. - * - * @name Phaser.Physics.Impact.ImpactImage#offset - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.offset = this.body.offset; - - /** - * The velocity, or rate of change the Body's position. Measured in pixels per second. - * - * @name Phaser.Physics.Impact.ImpactImage#vel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.vel = this.body.vel; - - /** - * The acceleration is the rate of change of the velocity. Measured in pixels per second squared. - * - * @name Phaser.Physics.Impact.ImpactImage#accel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.accel = this.body.accel; - - /** - * Friction between colliding bodies. - * - * @name Phaser.Physics.Impact.ImpactImage#friction - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.friction = this.body.friction; - - /** - * The maximum velocity of the body. - * - * @name Phaser.Physics.Impact.ImpactImage#maxVel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.maxVel = this.body.maxVel; - } - -}); - -module.exports = ImpactImage; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('./components'); +var Image = require('../../gameobjects/image/Image'); + +/** + * @classdesc + * An Impact Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class ImpactImage + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Impact.World} world - The physics world of the Impact physics system. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ImpactImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactImage (world, x, y, texture, frame) + { + Image.call(this, world.scene, x, y, texture, frame); + + /** + * The Physics Body linked to an ImpactImage. + * + * @name Phaser.Physics.Impact.ImpactImage#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); + + this.body.parent = this; + this.body.gameObject = this; + + /** + * The size of the physics Body. + * + * @name Phaser.Physics.Impact.ImpactImage#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * The X and Y offset of the Body from the left and top of the Image. + * + * @name Phaser.Physics.Impact.ImpactImage#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * The velocity, or rate of change the Body's position. Measured in pixels per second. + * + * @name Phaser.Physics.Impact.ImpactImage#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + * + * @name Phaser.Physics.Impact.ImpactImage#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * Friction between colliding bodies. + * + * @name Phaser.Physics.Impact.ImpactImage#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * The maximum velocity of the body. + * + * @name Phaser.Physics.Impact.ImpactImage#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactImage; diff --git a/plugins/impact/ImpactPhysics.js b/plugins/impact/ImpactPhysics.js index 593ed9ed6..38a42c28c 100644 --- a/plugins/impact/ImpactPhysics.js +++ b/plugins/impact/ImpactPhysics.js @@ -1,211 +1,211 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Factory = require('./Factory'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Merge = require('../../utils/object/Merge'); -var PluginCache = require('../../plugins/PluginCache'); -var SceneEvents = require('../../scene/events'); -var World = require('./World'); - -/** - * @classdesc - * [description] - * - * @class ImpactPhysics - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - [description] - */ -var ImpactPhysics = new Class({ - - initialize: - - function ImpactPhysics (scene) - { - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactPhysics#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactPhysics#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactPhysics#config - * @type {object} - * @since 3.0.0 - */ - this.config = this.getConfig(); - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactPhysics#world - * @type {Phaser.Physics.Impact.World} - * @since 3.0.0 - */ - this.world; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactPhysics#add - * @type {Phaser.Physics.Impact.Factory} - * @since 3.0.0 - */ - this.add; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Physics.Impact.ImpactPhysics#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.world = new World(this.scene, this.config); - this.add = new Factory(this.world); - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Physics.Impact.ImpactPhysics#start - * @private - * @since 3.5.0 - */ - start: function () - { - if (!this.world) - { - this.world = new World(this.scene, this.config); - this.add = new Factory(this.world); - } - - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.ImpactPhysics#getConfig - * @since 3.0.0 - * - * @return {object} [description] - */ - getConfig: function () - { - var gameConfig = this.systems.game.config.physics; - var sceneConfig = this.systems.settings.physics; - - var config = Merge( - GetFastValue(sceneConfig, 'impact', {}), - GetFastValue(gameConfig, 'impact', {}) - ); - - return config; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.ImpactPhysics#pause - * @since 3.0.0 - * - * @return {Phaser.Physics.Impact.World} The Impact World object. - */ - pause: function () - { - return this.world.pause(); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.ImpactPhysics#resume - * @since 3.0.0 - * - * @return {Phaser.Physics.Impact.World} The Impact World object. - */ - resume: function () - { - return this.world.resume(); - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Physics.Impact.ImpactPhysics#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - - this.add.destroy(); - this.world.destroy(); - - this.add = null; - this.world = null; - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Physics.Impact.ImpactPhysics#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('ImpactPhysics', ImpactPhysics, 'impactPhysics'); - -module.exports = ImpactPhysics; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Factory = require('./Factory'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Merge = require('../../utils/object/Merge'); +var PluginCache = require('../../plugins/PluginCache'); +var SceneEvents = require('../../scene/events'); +var World = require('./World'); + +/** + * @classdesc + * [description] + * + * @class ImpactPhysics + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - [description] + */ +var ImpactPhysics = new Class({ + + initialize: + + function ImpactPhysics (scene) + { + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#config + * @type {object} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#world + * @type {Phaser.Physics.Impact.World} + * @since 3.0.0 + */ + this.world; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactPhysics#add + * @type {Phaser.Physics.Impact.Factory} + * @since 3.0.0 + */ + this.add; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Impact.ImpactPhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Impact.ImpactPhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#getConfig + * @since 3.0.0 + * + * @return {object} [description] + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'impact', {}), + GetFastValue(gameConfig, 'impact', {}) + ); + + return config; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#pause + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} The Impact World object. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.ImpactPhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} The Impact World object. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Impact.ImpactPhysics#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.add.destroy(); + this.world.destroy(); + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Impact.ImpactPhysics#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('ImpactPhysics', ImpactPhysics, 'impactPhysics'); + +module.exports = ImpactPhysics; diff --git a/plugins/impact/ImpactSprite.js b/plugins/impact/ImpactSprite.js index aac3254e1..e8c861760 100644 --- a/plugins/impact/ImpactSprite.js +++ b/plugins/impact/ImpactSprite.js @@ -1,155 +1,155 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('./components'); -var Sprite = require('../../gameobjects/sprite/Sprite'); - -/** - * @classdesc - * An Impact Physics Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * - * @class ImpactSprite - * @extends Phaser.GameObjects.Sprite - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Impact.Components.Acceleration - * @extends Phaser.Physics.Impact.Components.BodyScale - * @extends Phaser.Physics.Impact.Components.BodyType - * @extends Phaser.Physics.Impact.Components.Bounce - * @extends Phaser.Physics.Impact.Components.CheckAgainst - * @extends Phaser.Physics.Impact.Components.Collides - * @extends Phaser.Physics.Impact.Components.Debug - * @extends Phaser.Physics.Impact.Components.Friction - * @extends Phaser.Physics.Impact.Components.Gravity - * @extends Phaser.Physics.Impact.Components.Offset - * @extends Phaser.Physics.Impact.Components.SetGameObject - * @extends Phaser.Physics.Impact.Components.Velocity - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Tint - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Physics.Impact.World} world - [description] - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var ImpactSprite = new Class({ - - Extends: Sprite, - - Mixins: [ - Components.Acceleration, - Components.BodyScale, - Components.BodyType, - Components.Bounce, - Components.CheckAgainst, - Components.Collides, - Components.Debug, - Components.Friction, - Components.Gravity, - Components.Offset, - Components.SetGameObject, - Components.Velocity - ], - - initialize: - - function ImpactSprite (world, x, y, texture, frame) - { - Sprite.call(this, world.scene, x, y, texture, frame); - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#body - * @type {Phaser.Physics.Impact.Body} - * @since 3.0.0 - */ - this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); - - this.body.parent = this; - this.body.gameObject = this; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#size - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.size = this.body.size; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#offset - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.offset = this.body.offset; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#vel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.vel = this.body.vel; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#accel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.accel = this.body.accel; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#friction - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.friction = this.body.friction; - - /** - * [description] - * - * @name Phaser.Physics.Impact.ImpactSprite#maxVel - * @type {{x: number, y: number}} - * @since 3.0.0 - */ - this.maxVel = this.body.maxVel; - } - -}); - -module.exports = ImpactSprite; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('./components'); +var Sprite = require('../../gameobjects/sprite/Sprite'); + +/** + * @classdesc + * An Impact Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class ImpactSprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Impact.Components.Acceleration + * @extends Phaser.Physics.Impact.Components.BodyScale + * @extends Phaser.Physics.Impact.Components.BodyType + * @extends Phaser.Physics.Impact.Components.Bounce + * @extends Phaser.Physics.Impact.Components.CheckAgainst + * @extends Phaser.Physics.Impact.Components.Collides + * @extends Phaser.Physics.Impact.Components.Debug + * @extends Phaser.Physics.Impact.Components.Friction + * @extends Phaser.Physics.Impact.Components.Gravity + * @extends Phaser.Physics.Impact.Components.Offset + * @extends Phaser.Physics.Impact.Components.SetGameObject + * @extends Phaser.Physics.Impact.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ImpactSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Acceleration, + Components.BodyScale, + Components.BodyType, + Components.Bounce, + Components.CheckAgainst, + Components.Collides, + Components.Debug, + Components.Friction, + Components.Gravity, + Components.Offset, + Components.SetGameObject, + Components.Velocity + ], + + initialize: + + function ImpactSprite (world, x, y, texture, frame) + { + Sprite.call(this, world.scene, x, y, texture, frame); + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#body + * @type {Phaser.Physics.Impact.Body} + * @since 3.0.0 + */ + this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); + + this.body.parent = this; + this.body.gameObject = this; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#size + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.size = this.body.size; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#offset + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.offset = this.body.offset; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#vel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.vel = this.body.vel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#accel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.accel = this.body.accel; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#friction + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.friction = this.body.friction; + + /** + * [description] + * + * @name Phaser.Physics.Impact.ImpactSprite#maxVel + * @type {{x: number, y: number}} + * @since 3.0.0 + */ + this.maxVel = this.body.maxVel; + } + +}); + +module.exports = ImpactSprite; diff --git a/plugins/impact/SeparateX.js b/plugins/impact/SeparateX.js index 06f88e6b0..3c7280c70 100644 --- a/plugins/impact/SeparateX.js +++ b/plugins/impact/SeparateX.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * [description] - * - * @function Phaser.Physics.Impact.SeparateX - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.World} world - [description] - * @param {Phaser.Physics.Impact.Body} left - [description] - * @param {Phaser.Physics.Impact.Body} right - [description] - * @param {Phaser.Physics.Impact.Body} [weak] - [description] - */ -var SeparateX = function (world, left, right, weak) -{ - var nudge = left.pos.x + left.size.x - right.pos.x; - - // We have a weak entity, so just move this one - if (weak) - { - var strong = (left === weak) ? right : left; - - weak.vel.x = -weak.vel.x * weak.bounciness + strong.vel.x; - - var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, weak === left ? -nudge : nudge, 0, weak.size.x, weak.size.y); - - weak.pos.x = resWeak.pos.x; - } - else - { - var v2 = (left.vel.x - right.vel.x) / 2; - - left.vel.x = -v2; - right.vel.x = v2; - - var resLeft = world.collisionMap.trace(left.pos.x, left.pos.y, -nudge / 2, 0, left.size.x, left.size.y); - - left.pos.x = Math.floor(resLeft.pos.x); - - var resRight = world.collisionMap.trace(right.pos.x, right.pos.y, nudge / 2, 0, right.size.x, right.size.y); - - right.pos.x = Math.ceil(resRight.pos.x); - } -}; - -module.exports = SeparateX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * [description] + * + * @function Phaser.Physics.Impact.SeparateX + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {Phaser.Physics.Impact.Body} left - [description] + * @param {Phaser.Physics.Impact.Body} right - [description] + * @param {Phaser.Physics.Impact.Body} [weak] - [description] + */ +var SeparateX = function (world, left, right, weak) +{ + var nudge = left.pos.x + left.size.x - right.pos.x; + + // We have a weak entity, so just move this one + if (weak) + { + var strong = (left === weak) ? right : left; + + weak.vel.x = -weak.vel.x * weak.bounciness + strong.vel.x; + + var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, weak === left ? -nudge : nudge, 0, weak.size.x, weak.size.y); + + weak.pos.x = resWeak.pos.x; + } + else + { + var v2 = (left.vel.x - right.vel.x) / 2; + + left.vel.x = -v2; + right.vel.x = v2; + + var resLeft = world.collisionMap.trace(left.pos.x, left.pos.y, -nudge / 2, 0, left.size.x, left.size.y); + + left.pos.x = Math.floor(resLeft.pos.x); + + var resRight = world.collisionMap.trace(right.pos.x, right.pos.y, nudge / 2, 0, right.size.x, right.size.y); + + right.pos.x = Math.ceil(resRight.pos.x); + } +}; + +module.exports = SeparateX; diff --git a/plugins/impact/SeparateY.js b/plugins/impact/SeparateY.js index d8f40ce13..5b1fdd02a 100644 --- a/plugins/impact/SeparateY.js +++ b/plugins/impact/SeparateY.js @@ -1,79 +1,79 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * [description] - * - * @function Phaser.Physics.Impact.SeparateY - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.World} world - [description] - * @param {Phaser.Physics.Impact.Body} top - [description] - * @param {Phaser.Physics.Impact.Body} bottom - [description] - * @param {Phaser.Physics.Impact.Body} [weak] - [description] - */ -var SeparateY = function (world, top, bottom, weak) -{ - var nudge = (top.pos.y + top.size.y - bottom.pos.y); - var nudgeX; - var resTop; - - if (weak) - { - var strong = (top === weak) ? bottom : top; - - weak.vel.y = -weak.vel.y * weak.bounciness + strong.vel.y; - - // Riding on a platform? - nudgeX = 0; - - if (weak === top && Math.abs(weak.vel.y - strong.vel.y) < weak.minBounceVelocity) - { - weak.standing = true; - nudgeX = strong.vel.x * world.delta; - } - - var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, nudgeX, weak === top ? -nudge : nudge, weak.size.x, weak.size.y); - - weak.pos.y = resWeak.pos.y; - weak.pos.x = resWeak.pos.x; - } - else if (world.gravity && (bottom.standing || top.vel.y > 0)) - { - resTop = world.collisionMap.trace(top.pos.x, top.pos.y, 0, -(top.pos.y + top.size.y - bottom.pos.y), top.size.x, top.size.y); - - top.pos.y = resTop.pos.y; - - if (top.bounciness > 0 && top.vel.y > top.minBounceVelocity) - { - top.vel.y *= -top.bounciness; - } - else - { - top.standing = true; - top.vel.y = 0; - } - } - else - { - var v2 = (top.vel.y - bottom.vel.y) / 2; - - top.vel.y = -v2; - bottom.vel.y = v2; - - nudgeX = bottom.vel.x * world.delta; - - resTop = world.collisionMap.trace(top.pos.x, top.pos.y, nudgeX, -nudge / 2, top.size.x, top.size.y); - - top.pos.y = resTop.pos.y; - - var resBottom = world.collisionMap.trace(bottom.pos.x, bottom.pos.y, 0, nudge / 2, bottom.size.x, bottom.size.y); - - bottom.pos.y = resBottom.pos.y; - } -}; - -module.exports = SeparateY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * [description] + * + * @function Phaser.Physics.Impact.SeparateY + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - [description] + * @param {Phaser.Physics.Impact.Body} top - [description] + * @param {Phaser.Physics.Impact.Body} bottom - [description] + * @param {Phaser.Physics.Impact.Body} [weak] - [description] + */ +var SeparateY = function (world, top, bottom, weak) +{ + var nudge = (top.pos.y + top.size.y - bottom.pos.y); + var nudgeX; + var resTop; + + if (weak) + { + var strong = (top === weak) ? bottom : top; + + weak.vel.y = -weak.vel.y * weak.bounciness + strong.vel.y; + + // Riding on a platform? + nudgeX = 0; + + if (weak === top && Math.abs(weak.vel.y - strong.vel.y) < weak.minBounceVelocity) + { + weak.standing = true; + nudgeX = strong.vel.x * world.delta; + } + + var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, nudgeX, weak === top ? -nudge : nudge, weak.size.x, weak.size.y); + + weak.pos.y = resWeak.pos.y; + weak.pos.x = resWeak.pos.x; + } + else if (world.gravity && (bottom.standing || top.vel.y > 0)) + { + resTop = world.collisionMap.trace(top.pos.x, top.pos.y, 0, -(top.pos.y + top.size.y - bottom.pos.y), top.size.x, top.size.y); + + top.pos.y = resTop.pos.y; + + if (top.bounciness > 0 && top.vel.y > top.minBounceVelocity) + { + top.vel.y *= -top.bounciness; + } + else + { + top.standing = true; + top.vel.y = 0; + } + } + else + { + var v2 = (top.vel.y - bottom.vel.y) / 2; + + top.vel.y = -v2; + bottom.vel.y = v2; + + nudgeX = bottom.vel.x * world.delta; + + resTop = world.collisionMap.trace(top.pos.x, top.pos.y, nudgeX, -nudge / 2, top.size.x, top.size.y); + + top.pos.y = resTop.pos.y; + + var resBottom = world.collisionMap.trace(bottom.pos.x, bottom.pos.y, 0, nudge / 2, bottom.size.x, bottom.size.y); + + bottom.pos.y = resBottom.pos.y; + } +}; + +module.exports = SeparateY; diff --git a/plugins/impact/Solver.js b/plugins/impact/Solver.js index 9e10fd1b9..bc748ac29 100644 --- a/plugins/impact/Solver.js +++ b/plugins/impact/Solver.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var COLLIDES = require('./COLLIDES'); -var Events = require('./events'); -var SeparateX = require('./SeparateX'); -var SeparateY = require('./SeparateY'); - -/** - * Impact Physics Solver - * - * @function Phaser.Physics.Impact.Solver - * @fires Phaser.Physics.Impact.Events#COLLIDE - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.World} world - The Impact simulation to run the solver in. - * @param {Phaser.Physics.Impact.Body} bodyA - The first body in the collision. - * @param {Phaser.Physics.Impact.Body} bodyB - The second body in the collision. - */ -var Solver = function (world, bodyA, bodyB) -{ - var weak = null; - - if (bodyA.collides === COLLIDES.LITE || bodyB.collides === COLLIDES.FIXED) - { - weak = bodyA; - } - else if (bodyB.collides === COLLIDES.LITE || bodyA.collides === COLLIDES.FIXED) - { - weak = bodyB; - } - - if (bodyA.last.x + bodyA.size.x > bodyB.last.x && bodyA.last.x < bodyB.last.x + bodyB.size.x) - { - if (bodyA.last.y < bodyB.last.y) - { - SeparateY(world, bodyA, bodyB, weak); - } - else - { - SeparateY(world, bodyB, bodyA, weak); - } - - bodyA.collideWith(bodyB, 'y'); - bodyB.collideWith(bodyA, 'y'); - - world.emit(Events.COLLIDE, bodyA, bodyB, 'y'); - } - else if (bodyA.last.y + bodyA.size.y > bodyB.last.y && bodyA.last.y < bodyB.last.y + bodyB.size.y) - { - if (bodyA.last.x < bodyB.last.x) - { - SeparateX(world, bodyA, bodyB, weak); - } - else - { - SeparateX(world, bodyB, bodyA, weak); - } - - bodyA.collideWith(bodyB, 'x'); - bodyB.collideWith(bodyA, 'x'); - - world.emit(Events.COLLIDE, bodyA, bodyB, 'x'); - } -}; - -module.exports = Solver; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var COLLIDES = require('./COLLIDES'); +var Events = require('./events'); +var SeparateX = require('./SeparateX'); +var SeparateY = require('./SeparateY'); + +/** + * Impact Physics Solver + * + * @function Phaser.Physics.Impact.Solver + * @fires Phaser.Physics.Impact.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.World} world - The Impact simulation to run the solver in. + * @param {Phaser.Physics.Impact.Body} bodyA - The first body in the collision. + * @param {Phaser.Physics.Impact.Body} bodyB - The second body in the collision. + */ +var Solver = function (world, bodyA, bodyB) +{ + var weak = null; + + if (bodyA.collides === COLLIDES.LITE || bodyB.collides === COLLIDES.FIXED) + { + weak = bodyA; + } + else if (bodyB.collides === COLLIDES.LITE || bodyA.collides === COLLIDES.FIXED) + { + weak = bodyB; + } + + if (bodyA.last.x + bodyA.size.x > bodyB.last.x && bodyA.last.x < bodyB.last.x + bodyB.size.x) + { + if (bodyA.last.y < bodyB.last.y) + { + SeparateY(world, bodyA, bodyB, weak); + } + else + { + SeparateY(world, bodyB, bodyA, weak); + } + + bodyA.collideWith(bodyB, 'y'); + bodyB.collideWith(bodyA, 'y'); + + world.emit(Events.COLLIDE, bodyA, bodyB, 'y'); + } + else if (bodyA.last.y + bodyA.size.y > bodyB.last.y && bodyA.last.y < bodyB.last.y + bodyB.size.y) + { + if (bodyA.last.x < bodyB.last.x) + { + SeparateX(world, bodyA, bodyB, weak); + } + else + { + SeparateX(world, bodyB, bodyA, weak); + } + + bodyA.collideWith(bodyB, 'x'); + bodyB.collideWith(bodyA, 'x'); + + world.emit(Events.COLLIDE, bodyA, bodyB, 'x'); + } +}; + +module.exports = Solver; diff --git a/plugins/impact/TYPE.js b/plugins/impact/TYPE.js index 1b3609cc3..3ae45279e 100644 --- a/plugins/impact/TYPE.js +++ b/plugins/impact/TYPE.js @@ -1,62 +1,62 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Collision Types - Determine if and how entities collide with each other. - * - * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, - * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE - * collisions, both entities are moved. LITE or PASSIVE entities don't collide - * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. - * FIXED collisions is undefined. - * - * @namespace Phaser.Physics.Impact.TYPE - * @memberof Phaser.Physics.Impact - * @since 3.0.0 - */ -module.exports = { - - /** - * Collides with nothing. - * - * @name Phaser.Physics.Impact.TYPE.NONE - * @type {integer} - * @const - * @since 3.0.0 - */ - NONE: 0, - - /** - * Type A. Collides with Type B. - * - * @name Phaser.Physics.Impact.TYPE.A - * @type {integer} - * @const - * @since 3.0.0 - */ - A: 1, - - /** - * Type B. Collides with Type A. - * - * @name Phaser.Physics.Impact.TYPE.B - * @type {integer} - * @const - * @since 3.0.0 - */ - B: 2, - - /** - * Collides with both types A and B. - * - * @name Phaser.Physics.Impact.TYPE.BOTH - * @type {integer} - * @const - * @since 3.0.0 - */ - BOTH: 3 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + * + * @namespace Phaser.Physics.Impact.TYPE + * @memberof Phaser.Physics.Impact + * @since 3.0.0 + */ +module.exports = { + + /** + * Collides with nothing. + * + * @name Phaser.Physics.Impact.TYPE.NONE + * @type {integer} + * @const + * @since 3.0.0 + */ + NONE: 0, + + /** + * Type A. Collides with Type B. + * + * @name Phaser.Physics.Impact.TYPE.A + * @type {integer} + * @const + * @since 3.0.0 + */ + A: 1, + + /** + * Type B. Collides with Type A. + * + * @name Phaser.Physics.Impact.TYPE.B + * @type {integer} + * @const + * @since 3.0.0 + */ + B: 2, + + /** + * Collides with both types A and B. + * + * @name Phaser.Physics.Impact.TYPE.BOTH + * @type {integer} + * @const + * @since 3.0.0 + */ + BOTH: 3 + +}; diff --git a/plugins/impact/UpdateMotion.js b/plugins/impact/UpdateMotion.js index c2241c2d0..27750ee83 100644 --- a/plugins/impact/UpdateMotion.js +++ b/plugins/impact/UpdateMotion.js @@ -1,89 +1,89 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Set up the trace-result - * var res = { - * collision: {x: false, y: false, slope: false}, - * pos: {x: x, y: y}, - * tile: {x: 0, y: 0} - * }; - * - * @function Phaser.Physics.Impact.UpdateMotion - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} body - [description] - * @param {object} res - [description] - */ -var UpdateMotion = function (body, res) -{ - body.standing = false; - - // Y - if (res.collision.y) - { - if (body.bounciness > 0 && Math.abs(body.vel.y) > body.minBounceVelocity) - { - body.vel.y *= -body.bounciness; - } - else - { - if (body.vel.y > 0) - { - body.standing = true; - } - - body.vel.y = 0; - } - } - - // X - if (res.collision.x) - { - if (body.bounciness > 0 && Math.abs(body.vel.x) > body.minBounceVelocity) - { - body.vel.x *= -body.bounciness; - } - else - { - body.vel.x = 0; - } - } - - // SLOPE - if (res.collision.slope) - { - var s = res.collision.slope; - - if (body.bounciness > 0) - { - var proj = body.vel.x * s.nx + body.vel.y * s.ny; - - body.vel.x = (body.vel.x - s.nx * proj * 2) * body.bounciness; - body.vel.y = (body.vel.y - s.ny * proj * 2) * body.bounciness; - } - else - { - var lengthSquared = s.x * s.x + s.y * s.y; - var dot = (body.vel.x * s.x + body.vel.y * s.y) / lengthSquared; - - body.vel.x = s.x * dot; - body.vel.y = s.y * dot; - - var angle = Math.atan2(s.x, s.y); - - if (angle > body.slopeStanding.min && angle < body.slopeStanding.max) - { - body.standing = true; - } - } - } - - body.pos.x = res.pos.x; - body.pos.y = res.pos.y; -}; - -module.exports = UpdateMotion; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Set up the trace-result + * var res = { + * collision: {x: false, y: false, slope: false}, + * pos: {x: x, y: y}, + * tile: {x: 0, y: 0} + * }; + * + * @function Phaser.Physics.Impact.UpdateMotion + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {object} res - [description] + */ +var UpdateMotion = function (body, res) +{ + body.standing = false; + + // Y + if (res.collision.y) + { + if (body.bounciness > 0 && Math.abs(body.vel.y) > body.minBounceVelocity) + { + body.vel.y *= -body.bounciness; + } + else + { + if (body.vel.y > 0) + { + body.standing = true; + } + + body.vel.y = 0; + } + } + + // X + if (res.collision.x) + { + if (body.bounciness > 0 && Math.abs(body.vel.x) > body.minBounceVelocity) + { + body.vel.x *= -body.bounciness; + } + else + { + body.vel.x = 0; + } + } + + // SLOPE + if (res.collision.slope) + { + var s = res.collision.slope; + + if (body.bounciness > 0) + { + var proj = body.vel.x * s.nx + body.vel.y * s.ny; + + body.vel.x = (body.vel.x - s.nx * proj * 2) * body.bounciness; + body.vel.y = (body.vel.y - s.ny * proj * 2) * body.bounciness; + } + else + { + var lengthSquared = s.x * s.x + s.y * s.y; + var dot = (body.vel.x * s.x + body.vel.y * s.y) / lengthSquared; + + body.vel.x = s.x * dot; + body.vel.y = s.y * dot; + + var angle = Math.atan2(s.x, s.y); + + if (angle > body.slopeStanding.min && angle < body.slopeStanding.max) + { + body.standing = true; + } + } + } + + body.pos.x = res.pos.x; + body.pos.y = res.pos.y; +}; + +module.exports = UpdateMotion; diff --git a/plugins/impact/World.js b/plugins/impact/World.js index 9acfba637..721b7e072 100644 --- a/plugins/impact/World.js +++ b/plugins/impact/World.js @@ -1,979 +1,979 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('./Body'); -var Class = require('../../utils/Class'); -var COLLIDES = require('./COLLIDES'); -var CollisionMap = require('./CollisionMap'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var HasValue = require('../../utils/object/HasValue'); -var Set = require('../../structs/Set'); -var Solver = require('./Solver'); -var TILEMAP_FORMATS = require('../../tilemaps/Formats'); -var TYPE = require('./TYPE'); - -/** - * @classdesc - * [description] - * - * @class World - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Physics.Impact - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Impact World instance belongs. - * @param {Phaser.Types.Physics.Impact.WorldConfig} config - [description] - */ -var World = new Class({ - - Extends: EventEmitter, - - initialize: - - function World (scene, config) - { - EventEmitter.call(this); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#bodies - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.bodies = new Set(); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#gravity - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.gravity = GetFastValue(config, 'gravity', 0); - - /** - * Spatial hash cell dimensions - * - * @name Phaser.Physics.Impact.World#cellSize - * @type {integer} - * @default 64 - * @since 3.0.0 - */ - this.cellSize = GetFastValue(config, 'cellSize', 64); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#collisionMap - * @type {Phaser.Physics.Impact.CollisionMap} - * @since 3.0.0 - */ - this.collisionMap = new CollisionMap(); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = GetFastValue(config, 'timeScale', 1); - - /** - * Impacts maximum time step is 20 fps. - * - * @name Phaser.Physics.Impact.World#maxStep - * @type {number} - * @default 0.05 - * @since 3.0.0 - */ - this.maxStep = GetFastValue(config, 'maxStep', 0.05); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#enabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enabled = true; - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#drawDebug - * @type {boolean} - * @since 3.0.0 - */ - this.drawDebug = GetFastValue(config, 'debug', false); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#debugGraphic - * @type {Phaser.GameObjects.Graphics} - * @since 3.0.0 - */ - this.debugGraphic; - - var _maxVelocity = GetFastValue(config, 'maxVelocity', 100); - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#defaults - * @type {Phaser.Types.Physics.Impact.WorldDefaults} - * @since 3.0.0 - */ - this.defaults = { - debugShowBody: GetFastValue(config, 'debugShowBody', true), - debugShowVelocity: GetFastValue(config, 'debugShowVelocity', true), - bodyDebugColor: GetFastValue(config, 'debugBodyColor', 0xff00ff), - velocityDebugColor: GetFastValue(config, 'debugVelocityColor', 0x00ff00), - maxVelocityX: GetFastValue(config, 'maxVelocityX', _maxVelocity), - maxVelocityY: GetFastValue(config, 'maxVelocityY', _maxVelocity), - minBounceVelocity: GetFastValue(config, 'minBounceVelocity', 40), - gravityFactor: GetFastValue(config, 'gravityFactor', 1), - bounciness: GetFastValue(config, 'bounciness', 0) - }; - - /** - * An object containing the 4 wall bodies that bound the physics world. - * - * @name Phaser.Physics.Impact.World#walls - * @type {Phaser.Types.Physics.Impact.WorldWalls} - * @since 3.0.0 - */ - this.walls = { left: null, right: null, top: null, bottom: null }; - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#delta - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.delta = 0; - - /** - * [description] - * - * @name Phaser.Physics.Impact.World#_lastId - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._lastId = 0; - - if (GetFastValue(config, 'setBounds', false)) - { - var boundsConfig = config['setBounds']; - - if (typeof boundsConfig === 'boolean') - { - this.setBounds(); - } - else - { - var x = GetFastValue(boundsConfig, 'x', 0); - var y = GetFastValue(boundsConfig, 'y', 0); - var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); - var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); - var thickness = GetFastValue(boundsConfig, 'thickness', 64); - var left = GetFastValue(boundsConfig, 'left', true); - var right = GetFastValue(boundsConfig, 'right', true); - var top = GetFastValue(boundsConfig, 'top', true); - var bottom = GetFastValue(boundsConfig, 'bottom', true); - - this.setBounds(x, y, width, height, thickness, left, right, top, bottom); - } - } - - if (this.drawDebug) - { - this.createDebugGraphic(); - } - }, - - /** - * Sets the collision map for the world either from a Weltmeister JSON level in the cache or from - * a 2D array. If loading from a Weltmeister level, the map must have a layer called "collision". - * - * @method Phaser.Physics.Impact.World#setCollisionMap - * @since 3.0.0 - * - * @param {(string|integer[][])} key - Either a string key that corresponds to a Weltmeister level - * in the cache, or a 2D array of collision IDs. - * @param {integer} tileSize - The size of a tile. This is optional if loading from a Weltmeister - * level in the cache. - * - * @return {?Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap, or null if the method failed to - * create the CollisionMap. - */ - setCollisionMap: function (key, tileSize) - { - if (typeof key === 'string') - { - var tilemapData = this.scene.cache.tilemap.get(key); - - if (!tilemapData || tilemapData.format !== TILEMAP_FORMATS.WELTMEISTER) - { - console.warn('The specified key does not correspond to a Weltmeister tilemap: ' + key); - return null; - } - - var layers = tilemapData.data.layer; - var collisionLayer; - for (var i = 0; i < layers.length; i++) - { - if (layers[i].name === 'collision') - { - collisionLayer = layers[i]; - break; - } - } - - if (tileSize === undefined) { tileSize = collisionLayer.tilesize; } - - this.collisionMap = new CollisionMap(tileSize, collisionLayer.data); - } - else if (Array.isArray(key)) - { - this.collisionMap = new CollisionMap(tileSize, key); - } - else - { - console.warn('Invalid Weltmeister collision map data: ' + key); - } - - return this.collisionMap; - }, - - /** - * Sets the collision map for the world from a tilemap layer. Only tiles that are marked as - * colliding will be used. You can specify the mapping from tiles to slope IDs in a couple of - * ways. The easiest is to use Tiled and the slopeTileProperty option. Alternatively, you can - * manually create a slopeMap that stores the mapping between tile indices and slope IDs. - * - * @method Phaser.Physics.Impact.World#setCollisionMapFromTilemapLayer - * @since 3.0.0 - * - * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemap layer to use. - * @param {Phaser.Types.Physics.Impact.CollisionOptions} [options] - Options for controlling the mapping from tiles to slope IDs. - * - * @return {Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap. - */ - setCollisionMapFromTilemapLayer: function (tilemapLayer, options) - { - if (options === undefined) { options = {}; } - var slopeProperty = GetFastValue(options, 'slopeProperty', null); - var slopeMap = GetFastValue(options, 'slopeMap', null); - var collidingSlope = GetFastValue(options, 'defaultCollidingSlope', null); - var nonCollidingSlope = GetFastValue(options, 'defaultNonCollidingSlope', 0); - - var layerData = tilemapLayer.layer; - var tileSize = layerData.baseTileWidth; - var collisionData = []; - - for (var ty = 0; ty < layerData.height; ty++) - { - collisionData[ty] = []; - - for (var tx = 0; tx < layerData.width; tx++) - { - var tile = layerData.data[ty][tx]; - - if (tile && tile.collides) - { - if (slopeProperty !== null && HasValue(tile.properties, slopeProperty)) - { - collisionData[ty][tx] = parseInt(tile.properties[slopeProperty], 10); - } - else if (slopeMap !== null && HasValue(slopeMap, tile.index)) - { - collisionData[ty][tx] = slopeMap[tile.index]; - } - else if (collidingSlope !== null) - { - collisionData[ty][tx] = collidingSlope; - } - else - { - collisionData[ty][tx] = tile.index; - } - } - else - { - collisionData[ty][tx] = nonCollidingSlope; - } - } - } - - this.collisionMap = new CollisionMap(tileSize, collisionData); - - return this.collisionMap; - }, - - /** - * Sets the bounds of the Physics world to match the given world pixel dimensions. - * You can optionally set which 'walls' to create: left, right, top or bottom. - * If none of the walls are given it will default to use the walls settings it had previously. - * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size - * the newly created bounds will also not have the left and right walls. - * Explicitly state them in the parameters to override this. - * - * @method Phaser.Physics.Impact.World#setBounds - * @since 3.0.0 - * - * @param {number} [x] - The x coordinate of the top-left corner of the bounds. - * @param {number} [y] - The y coordinate of the top-left corner of the bounds. - * @param {number} [width] - The width of the bounds. - * @param {number} [height] - The height of the bounds. - * @param {number} [thickness=64] - [description] - * @param {boolean} [left=true] - If true will create the left bounds wall. - * @param {boolean} [right=true] - If true will create the right bounds wall. - * @param {boolean} [top=true] - If true will create the top bounds wall. - * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setBounds: function (x, y, width, height, thickness, left, right, top, bottom) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.scene.sys.scale.width; } - if (height === undefined) { height = this.scene.sys.scale.height; } - if (thickness === undefined) { thickness = 64; } - if (left === undefined) { left = true; } - if (right === undefined) { right = true; } - if (top === undefined) { top = true; } - if (bottom === undefined) { bottom = true; } - - this.updateWall(left, 'left', x - thickness, y, thickness, height); - this.updateWall(right, 'right', x + width, y, thickness, height); - this.updateWall(top, 'top', x, y - thickness, width, thickness); - this.updateWall(bottom, 'bottom', x, y + height, width, thickness); - - return this; - }, - - /** - * position = 'left', 'right', 'top' or 'bottom' - * - * @method Phaser.Physics.Impact.World#updateWall - * @since 3.0.0 - * - * @param {boolean} add - [description] - * @param {string} position - [description] - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} width - [description] - * @param {number} height - [description] - */ - updateWall: function (add, position, x, y, width, height) - { - var wall = this.walls[position]; - - if (add) - { - if (wall) - { - wall.resetSize(x, y, width, height); - } - else - { - this.walls[position] = this.create(x, y, width, height); - this.walls[position].name = position; - this.walls[position].gravityFactor = 0; - this.walls[position].collides = COLLIDES.FIXED; - } - } - else - { - if (wall) - { - this.bodies.remove(wall); - } - - this.walls[position] = null; - } - }, - - /** - * Creates a Graphics Game Object used for debug display and enables the world for debug drawing. - * - * @method Phaser.Physics.Impact.World#createDebugGraphic - * @since 3.0.0 - * - * @return {Phaser.GameObjects.Graphics} The Graphics object created that will have the debug visuals drawn to it. - */ - createDebugGraphic: function () - { - var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); - - graphic.setDepth(Number.MAX_VALUE); - - this.debugGraphic = graphic; - - this.drawDebug = true; - - return graphic; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#getNextID - * @since 3.0.0 - * - * @return {integer} [description] - */ - getNextID: function () - { - return this._lastId++; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#create - * @since 3.0.0 - * - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} sizeX - [description] - * @param {number} sizeY - [description] - * - * @return {Phaser.Physics.Impact.Body} The Body that was added to this World. - */ - create: function (x, y, sizeX, sizeY) - { - var body = new Body(this, x, y, sizeX, sizeY); - - this.bodies.set(body); - - return body; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#remove - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} object - The Body to remove from this World. - */ - remove: function (object) - { - this.bodies.delete(object); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#pause - * @fires Phaser.Physics.Impact.Events#PAUSE - * @since 3.0.0 - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - pause: function () - { - this.enabled = false; - - this.emit(Events.PAUSE); - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#resume - * @fires Phaser.Physics.Impact.Events#RESUME - * @since 3.0.0 - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - resume: function () - { - this.enabled = true; - - this.emit(Events.RESUME); - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.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. - */ - update: function (time, delta) - { - if (!this.enabled || this.bodies.size === 0) - { - return; - } - - // Impact uses a divided delta value that is clamped to the maxStep (20fps) maximum - - var clampedDelta = Math.min(delta / 1000, this.maxStep) * this.timeScale; - - this.delta = clampedDelta; - - // Update all active bodies - - var i; - var body; - var bodies = this.bodies.entries; - var len = bodies.length; - var hash = {}; - var size = this.cellSize; - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body.enabled) - { - body.update(clampedDelta); - } - } - - // Run collision against them all now they're in the new positions from the update - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body && !body.skipHash()) - { - this.checkHash(body, hash, size); - } - } - - if (this.drawDebug) - { - var graphics = this.debugGraphic; - - graphics.clear(); - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body && body.willDrawDebug()) - { - body.drawDebug(graphics); - } - } - } - }, - - /** - * Check the body against the spatial hash. - * - * @method Phaser.Physics.Impact.World#checkHash - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} body - [description] - * @param {object} hash - [description] - * @param {number} size - [description] - */ - checkHash: function (body, hash, size) - { - var checked = {}; - - var xmin = Math.floor(body.pos.x / size); - var ymin = Math.floor(body.pos.y / size); - var xmax = Math.floor((body.pos.x + body.size.x) / size) + 1; - var ymax = Math.floor((body.pos.y + body.size.y) / size) + 1; - - for (var x = xmin; x < xmax; x++) - { - for (var y = ymin; y < ymax; y++) - { - if (!hash[x]) - { - hash[x] = {}; - hash[x][y] = [ body ]; - } - else if (!hash[x][y]) - { - hash[x][y] = [ body ]; - } - else - { - var cell = hash[x][y]; - - for (var c = 0; c < cell.length; c++) - { - if (body.touches(cell[c]) && !checked[cell[c].id]) - { - checked[cell[c].id] = true; - - this.checkBodies(body, cell[c]); - } - } - - cell.push(body); - } - } - } - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#checkBodies - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} bodyA - [description] - * @param {Phaser.Physics.Impact.Body} bodyB - [description] - */ - checkBodies: function (bodyA, bodyB) - { - // 2 fixed bodies won't do anything - if (bodyA.collides === COLLIDES.FIXED && bodyB.collides === COLLIDES.FIXED) - { - return; - } - - // bitwise checks - if (bodyA.checkAgainst & bodyB.type) - { - bodyA.check(bodyB); - } - - if (bodyB.checkAgainst & bodyA.type) - { - bodyB.check(bodyA); - } - - if (bodyA.collides && bodyB.collides && bodyA.collides + bodyB.collides > COLLIDES.ACTIVE) - { - Solver(this, bodyA, bodyB); - } - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setCollidesNever - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setCollidesNever: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].collides = COLLIDES.NEVER; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setLite - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setLite: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].collides = COLLIDES.LITE; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setPassive - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setPassive: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].collides = COLLIDES.PASSIVE; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setActive - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setActive: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].collides = COLLIDES.ACTIVE; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setFixed - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setFixed: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].collides = COLLIDES.FIXED; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setTypeNone - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setTypeNone: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].type = TYPE.NONE; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setTypeA - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setTypeA: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].type = TYPE.A; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setTypeB - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setTypeB: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].type = TYPE.B; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setAvsB - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setAvsB: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].type = TYPE.A; - bodies[i].checkAgainst = TYPE.B; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setBvsA - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setBvsA: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].type = TYPE.B; - bodies[i].checkAgainst = TYPE.A; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setCheckAgainstNone - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setCheckAgainstNone: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].checkAgainst = TYPE.NONE; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setCheckAgainstA - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setCheckAgainstA: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].checkAgainst = TYPE.A; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#setCheckAgainstB - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. - * - * @return {Phaser.Physics.Impact.World} This World object. - */ - setCheckAgainstB: function (bodies) - { - for (var i = 0; i < bodies.length; i++) - { - bodies[i].checkAgainst = TYPE.B; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - this.removeAllListeners(); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.World#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.removeAllListeners(); - - this.scene = null; - - this.bodies.clear(); - - this.bodies = null; - - this.collisionMap = null; - } - -}); - -module.exports = World; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('./Body'); +var Class = require('../../utils/Class'); +var COLLIDES = require('./COLLIDES'); +var CollisionMap = require('./CollisionMap'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var HasValue = require('../../utils/object/HasValue'); +var Set = require('../../structs/Set'); +var Solver = require('./Solver'); +var TILEMAP_FORMATS = require('../../tilemaps/Formats'); +var TYPE = require('./TYPE'); + +/** + * @classdesc + * [description] + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Impact + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Impact World instance belongs. + * @param {Phaser.Types.Physics.Impact.WorldConfig} config - [description] + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#bodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.bodies = new Set(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#gravity + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.gravity = GetFastValue(config, 'gravity', 0); + + /** + * Spatial hash cell dimensions + * + * @name Phaser.Physics.Impact.World#cellSize + * @type {integer} + * @default 64 + * @since 3.0.0 + */ + this.cellSize = GetFastValue(config, 'cellSize', 64); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#collisionMap + * @type {Phaser.Physics.Impact.CollisionMap} + * @since 3.0.0 + */ + this.collisionMap = new CollisionMap(); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = GetFastValue(config, 'timeScale', 1); + + /** + * Impacts maximum time step is 20 fps. + * + * @name Phaser.Physics.Impact.World#maxStep + * @type {number} + * @default 0.05 + * @since 3.0.0 + */ + this.maxStep = GetFastValue(config, 'maxStep', 0.05); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#drawDebug + * @type {boolean} + * @since 3.0.0 + */ + this.drawDebug = GetFastValue(config, 'debug', false); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + var _maxVelocity = GetFastValue(config, 'maxVelocity', 100); + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#defaults + * @type {Phaser.Types.Physics.Impact.WorldDefaults} + * @since 3.0.0 + */ + this.defaults = { + debugShowBody: GetFastValue(config, 'debugShowBody', true), + debugShowVelocity: GetFastValue(config, 'debugShowVelocity', true), + bodyDebugColor: GetFastValue(config, 'debugBodyColor', 0xff00ff), + velocityDebugColor: GetFastValue(config, 'debugVelocityColor', 0x00ff00), + maxVelocityX: GetFastValue(config, 'maxVelocityX', _maxVelocity), + maxVelocityY: GetFastValue(config, 'maxVelocityY', _maxVelocity), + minBounceVelocity: GetFastValue(config, 'minBounceVelocity', 40), + gravityFactor: GetFastValue(config, 'gravityFactor', 1), + bounciness: GetFastValue(config, 'bounciness', 0) + }; + + /** + * An object containing the 4 wall bodies that bound the physics world. + * + * @name Phaser.Physics.Impact.World#walls + * @type {Phaser.Types.Physics.Impact.WorldWalls} + * @since 3.0.0 + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#delta + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.delta = 0; + + /** + * [description] + * + * @name Phaser.Physics.Impact.World#_lastId + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._lastId = 0; + + if (GetFastValue(config, 'setBounds', false)) + { + var boundsConfig = config['setBounds']; + + if (typeof boundsConfig === 'boolean') + { + this.setBounds(); + } + else + { + var x = GetFastValue(boundsConfig, 'x', 0); + var y = GetFastValue(boundsConfig, 'y', 0); + var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); + var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); + var thickness = GetFastValue(boundsConfig, 'thickness', 64); + var left = GetFastValue(boundsConfig, 'left', true); + var right = GetFastValue(boundsConfig, 'right', true); + var top = GetFastValue(boundsConfig, 'top', true); + var bottom = GetFastValue(boundsConfig, 'bottom', true); + + this.setBounds(x, y, width, height, thickness, left, right, top, bottom); + } + } + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + }, + + /** + * Sets the collision map for the world either from a Weltmeister JSON level in the cache or from + * a 2D array. If loading from a Weltmeister level, the map must have a layer called "collision". + * + * @method Phaser.Physics.Impact.World#setCollisionMap + * @since 3.0.0 + * + * @param {(string|integer[][])} key - Either a string key that corresponds to a Weltmeister level + * in the cache, or a 2D array of collision IDs. + * @param {integer} tileSize - The size of a tile. This is optional if loading from a Weltmeister + * level in the cache. + * + * @return {?Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap, or null if the method failed to + * create the CollisionMap. + */ + setCollisionMap: function (key, tileSize) + { + if (typeof key === 'string') + { + var tilemapData = this.scene.cache.tilemap.get(key); + + if (!tilemapData || tilemapData.format !== TILEMAP_FORMATS.WELTMEISTER) + { + console.warn('The specified key does not correspond to a Weltmeister tilemap: ' + key); + return null; + } + + var layers = tilemapData.data.layer; + var collisionLayer; + for (var i = 0; i < layers.length; i++) + { + if (layers[i].name === 'collision') + { + collisionLayer = layers[i]; + break; + } + } + + if (tileSize === undefined) { tileSize = collisionLayer.tilesize; } + + this.collisionMap = new CollisionMap(tileSize, collisionLayer.data); + } + else if (Array.isArray(key)) + { + this.collisionMap = new CollisionMap(tileSize, key); + } + else + { + console.warn('Invalid Weltmeister collision map data: ' + key); + } + + return this.collisionMap; + }, + + /** + * Sets the collision map for the world from a tilemap layer. Only tiles that are marked as + * colliding will be used. You can specify the mapping from tiles to slope IDs in a couple of + * ways. The easiest is to use Tiled and the slopeTileProperty option. Alternatively, you can + * manually create a slopeMap that stores the mapping between tile indices and slope IDs. + * + * @method Phaser.Physics.Impact.World#setCollisionMapFromTilemapLayer + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemap layer to use. + * @param {Phaser.Types.Physics.Impact.CollisionOptions} [options] - Options for controlling the mapping from tiles to slope IDs. + * + * @return {Phaser.Physics.Impact.CollisionMap} The newly created CollisionMap. + */ + setCollisionMapFromTilemapLayer: function (tilemapLayer, options) + { + if (options === undefined) { options = {}; } + var slopeProperty = GetFastValue(options, 'slopeProperty', null); + var slopeMap = GetFastValue(options, 'slopeMap', null); + var collidingSlope = GetFastValue(options, 'defaultCollidingSlope', null); + var nonCollidingSlope = GetFastValue(options, 'defaultNonCollidingSlope', 0); + + var layerData = tilemapLayer.layer; + var tileSize = layerData.baseTileWidth; + var collisionData = []; + + for (var ty = 0; ty < layerData.height; ty++) + { + collisionData[ty] = []; + + for (var tx = 0; tx < layerData.width; tx++) + { + var tile = layerData.data[ty][tx]; + + if (tile && tile.collides) + { + if (slopeProperty !== null && HasValue(tile.properties, slopeProperty)) + { + collisionData[ty][tx] = parseInt(tile.properties[slopeProperty], 10); + } + else if (slopeMap !== null && HasValue(slopeMap, tile.index)) + { + collisionData[ty][tx] = slopeMap[tile.index]; + } + else if (collidingSlope !== null) + { + collisionData[ty][tx] = collidingSlope; + } + else + { + collisionData[ty][tx] = tile.index; + } + } + else + { + collisionData[ty][tx] = nonCollidingSlope; + } + } + } + + this.collisionMap = new CollisionMap(tileSize, collisionData); + + return this.collisionMap; + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.Impact.World#setBounds + * @since 3.0.0 + * + * @param {number} [x] - The x coordinate of the top-left corner of the bounds. + * @param {number} [y] - The y coordinate of the top-left corner of the bounds. + * @param {number} [width] - The width of the bounds. + * @param {number} [height] - The height of the bounds. + * @param {number} [thickness=64] - [description] + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setBounds: function (x, y, width, height, thickness, left, right, top, bottom) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (thickness === undefined) { thickness = 64; } + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (bottom === undefined) { bottom = true; } + + this.updateWall(left, 'left', x - thickness, y, thickness, height); + this.updateWall(right, 'right', x + width, y, thickness, height); + this.updateWall(top, 'top', x, y - thickness, width, thickness); + this.updateWall(bottom, 'bottom', x, y + height, width, thickness); + + return this; + }, + + /** + * position = 'left', 'right', 'top' or 'bottom' + * + * @method Phaser.Physics.Impact.World#updateWall + * @since 3.0.0 + * + * @param {boolean} add - [description] + * @param {string} position - [description] + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} width - [description] + * @param {number} height - [description] + */ + updateWall: function (add, position, x, y, width, height) + { + var wall = this.walls[position]; + + if (add) + { + if (wall) + { + wall.resetSize(x, y, width, height); + } + else + { + this.walls[position] = this.create(x, y, width, height); + this.walls[position].name = position; + this.walls[position].gravityFactor = 0; + this.walls[position].collides = COLLIDES.FIXED; + } + } + else + { + if (wall) + { + this.bodies.remove(wall); + } + + this.walls[position] = null; + } + }, + + /** + * Creates a Graphics Game Object used for debug display and enables the world for debug drawing. + * + * @method Phaser.Physics.Impact.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The Graphics object created that will have the debug visuals drawn to it. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#getNextID + * @since 3.0.0 + * + * @return {integer} [description] + */ + getNextID: function () + { + return this._lastId++; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#create + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} sizeX - [description] + * @param {number} sizeY - [description] + * + * @return {Phaser.Physics.Impact.Body} The Body that was added to this World. + */ + create: function (x, y, sizeX, sizeY) + { + var body = new Body(this, x, y, sizeX, sizeY); + + this.bodies.set(body); + + return body; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#remove + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} object - The Body to remove from this World. + */ + remove: function (object) + { + this.bodies.delete(object); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#pause + * @fires Phaser.Physics.Impact.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + pause: function () + { + this.enabled = false; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#resume + * @fires Phaser.Physics.Impact.Events#RESUME + * @since 3.0.0 + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + resume: function () + { + this.enabled = true; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.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. + */ + update: function (time, delta) + { + if (!this.enabled || this.bodies.size === 0) + { + return; + } + + // Impact uses a divided delta value that is clamped to the maxStep (20fps) maximum + + var clampedDelta = Math.min(delta / 1000, this.maxStep) * this.timeScale; + + this.delta = clampedDelta; + + // Update all active bodies + + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + var hash = {}; + var size = this.cellSize; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enabled) + { + body.update(clampedDelta); + } + } + + // Run collision against them all now they're in the new positions from the update + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body && !body.skipHash()) + { + this.checkHash(body, hash, size); + } + } + + if (this.drawDebug) + { + var graphics = this.debugGraphic; + + graphics.clear(); + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body && body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + } + }, + + /** + * Check the body against the spatial hash. + * + * @method Phaser.Physics.Impact.World#checkHash + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {object} hash - [description] + * @param {number} size - [description] + */ + checkHash: function (body, hash, size) + { + var checked = {}; + + var xmin = Math.floor(body.pos.x / size); + var ymin = Math.floor(body.pos.y / size); + var xmax = Math.floor((body.pos.x + body.size.x) / size) + 1; + var ymax = Math.floor((body.pos.y + body.size.y) / size) + 1; + + for (var x = xmin; x < xmax; x++) + { + for (var y = ymin; y < ymax; y++) + { + if (!hash[x]) + { + hash[x] = {}; + hash[x][y] = [ body ]; + } + else if (!hash[x][y]) + { + hash[x][y] = [ body ]; + } + else + { + var cell = hash[x][y]; + + for (var c = 0; c < cell.length; c++) + { + if (body.touches(cell[c]) && !checked[cell[c].id]) + { + checked[cell[c].id] = true; + + this.checkBodies(body, cell[c]); + } + } + + cell.push(body); + } + } + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#checkBodies + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} bodyA - [description] + * @param {Phaser.Physics.Impact.Body} bodyB - [description] + */ + checkBodies: function (bodyA, bodyB) + { + // 2 fixed bodies won't do anything + if (bodyA.collides === COLLIDES.FIXED && bodyB.collides === COLLIDES.FIXED) + { + return; + } + + // bitwise checks + if (bodyA.checkAgainst & bodyB.type) + { + bodyA.check(bodyB); + } + + if (bodyB.checkAgainst & bodyA.type) + { + bodyB.check(bodyA); + } + + if (bodyA.collides && bodyB.collides && bodyA.collides + bodyB.collides > COLLIDES.ACTIVE) + { + Solver(this, bodyA, bodyB); + } + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCollidesNever + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCollidesNever: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.NEVER; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setLite + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setLite: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.LITE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setPassive + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setPassive: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.PASSIVE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setActive + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setActive: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.ACTIVE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setFixed + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the collides value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setFixed: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].collides = COLLIDES.FIXED; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeNone + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeNone: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.NONE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setTypeB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setTypeB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setAvsB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setAvsB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.A; + bodies[i].checkAgainst = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setBvsA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setBvsA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].type = TYPE.B; + bodies[i].checkAgainst = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstNone + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstNone: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.NONE; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstA + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstA: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.A; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#setCheckAgainstB + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body[]} bodies - An Array of Impact Bodies to set the type value on. + * + * @return {Phaser.Physics.Impact.World} This World object. + */ + setCheckAgainstB: function (bodies) + { + for (var i = 0; i < bodies.length; i++) + { + bodies[i].checkAgainst = TYPE.B; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAllListeners(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.scene = null; + + this.bodies.clear(); + + this.bodies = null; + + this.collisionMap = null; + } + +}); + +module.exports = World; diff --git a/plugins/impact/components/Acceleration.js b/plugins/impact/components/Acceleration.js index 6ca198159..90aa8ce3d 100644 --- a/plugins/impact/components/Acceleration.js +++ b/plugins/impact/components/Acceleration.js @@ -1,71 +1,71 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Acceleration component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Acceleration - * @since 3.0.0 - */ -var Acceleration = { - - /** - * Sets the horizontal acceleration of this body. - * - * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationX - * @since 3.0.0 - * - * @param {number} x - The amount of acceleration to apply. - * - * @return {this} This Game Object. - */ - setAccelerationX: function (x) - { - this.accel.x = x; - - return this; - }, - - /** - * Sets the vertical acceleration of this body. - * - * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationY - * @since 3.0.0 - * - * @param {number} y - The amount of acceleration to apply. - * - * @return {this} This Game Object. - */ - setAccelerationY: function (y) - { - this.accel.y = y; - - return this; - }, - - /** - * Sets the horizontal and vertical acceleration of this body. - * - * @method Phaser.Physics.Impact.Components.Acceleration#setAcceleration - * @since 3.0.0 - * - * @param {number} x - The amount of horizontal acceleration to apply. - * @param {number} y - The amount of vertical acceleration to apply. - * - * @return {this} This Game Object. - */ - setAcceleration: function (x, y) - { - this.accel.x = x; - this.accel.y = y; - - return this; - } - -}; - -module.exports = Acceleration; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Acceleration component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Acceleration + * @since 3.0.0 + */ +var Acceleration = { + + /** + * Sets the horizontal acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationX + * @since 3.0.0 + * + * @param {number} x - The amount of acceleration to apply. + * + * @return {this} This Game Object. + */ + setAccelerationX: function (x) + { + this.accel.x = x; + + return this; + }, + + /** + * Sets the vertical acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAccelerationY + * @since 3.0.0 + * + * @param {number} y - The amount of acceleration to apply. + * + * @return {this} This Game Object. + */ + setAccelerationY: function (y) + { + this.accel.y = y; + + return this; + }, + + /** + * Sets the horizontal and vertical acceleration of this body. + * + * @method Phaser.Physics.Impact.Components.Acceleration#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal acceleration to apply. + * @param {number} y - The amount of vertical acceleration to apply. + * + * @return {this} This Game Object. + */ + setAcceleration: function (x, y) + { + this.accel.x = x; + this.accel.y = y; + + return this; + } + +}; + +module.exports = Acceleration; diff --git a/plugins/impact/components/BodyScale.js b/plugins/impact/components/BodyScale.js index 119849cbe..4dc0a5122 100644 --- a/plugins/impact/components/BodyScale.js +++ b/plugins/impact/components/BodyScale.js @@ -1,68 +1,68 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Body Scale component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.BodyScale - * @since 3.0.0 - */ -var BodyScale = { - - /** - * Sets the size of the physics body. - * - * @method Phaser.Physics.Impact.Components.BodyScale#setBodySize - * @since 3.0.0 - * - * @param {number} width - The width of the body in pixels. - * @param {number} [height=width] - The height of the body in pixels. - * - * @return {this} This Game Object. - */ - setBodySize: function (width, height) - { - if (height === undefined) { height = width; } - - this.body.size.x = Math.round(width); - this.body.size.y = Math.round(height); - - return this; - }, - - /** - * Sets the scale of the physics body. - * - * @method Phaser.Physics.Impact.Components.BodyScale#setBodyScale - * @since 3.0.0 - * - * @param {number} scaleX - The horizontal scale of the body. - * @param {number} [scaleY] - The vertical scale of the body. If not given, will use the horizontal scale value. - * - * @return {this} This Game Object. - */ - setBodyScale: function (scaleX, scaleY) - { - if (scaleY === undefined) { scaleY = scaleX; } - - var gameObject = this.body.gameObject; - - if (gameObject) - { - gameObject.setScale(scaleX, scaleY); - - return this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); - } - else - { - return this.setBodySize(this.body.size.x * scaleX, this.body.size.y * scaleY); - } - } - -}; - -module.exports = BodyScale; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Body Scale component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.BodyScale + * @since 3.0.0 + */ +var BodyScale = { + + /** + * Sets the size of the physics body. + * + * @method Phaser.Physics.Impact.Components.BodyScale#setBodySize + * @since 3.0.0 + * + * @param {number} width - The width of the body in pixels. + * @param {number} [height=width] - The height of the body in pixels. + * + * @return {this} This Game Object. + */ + setBodySize: function (width, height) + { + if (height === undefined) { height = width; } + + this.body.size.x = Math.round(width); + this.body.size.y = Math.round(height); + + return this; + }, + + /** + * Sets the scale of the physics body. + * + * @method Phaser.Physics.Impact.Components.BodyScale#setBodyScale + * @since 3.0.0 + * + * @param {number} scaleX - The horizontal scale of the body. + * @param {number} [scaleY] - The vertical scale of the body. If not given, will use the horizontal scale value. + * + * @return {this} This Game Object. + */ + setBodyScale: function (scaleX, scaleY) + { + if (scaleY === undefined) { scaleY = scaleX; } + + var gameObject = this.body.gameObject; + + if (gameObject) + { + gameObject.setScale(scaleX, scaleY); + + return this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); + } + else + { + return this.setBodySize(this.body.size.x * scaleX, this.body.size.y * scaleY); + } + } + +}; + +module.exports = BodyScale; diff --git a/plugins/impact/components/BodyType.js b/plugins/impact/components/BodyType.js index efd4548da..0eae106ef 100644 --- a/plugins/impact/components/BodyType.js +++ b/plugins/impact/components/BodyType.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var TYPE = require('../TYPE'); - -/** - * The Impact Body Type component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.BodyType - * @since 3.0.0 - */ -var BodyType = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.BodyType#getBodyType - * @since 3.0.0 - * - * @return {number} [description] - */ - getBodyType: function () - { - return this.body.type; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.BodyType#setTypeNone - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setTypeNone: function () - { - this.body.type = TYPE.NONE; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.BodyType#setTypeA - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setTypeA: function () - { - this.body.type = TYPE.A; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.BodyType#setTypeB - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setTypeB: function () - { - this.body.type = TYPE.B; - - return this; - } - -}; - -module.exports = BodyType; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TYPE = require('../TYPE'); + +/** + * The Impact Body Type component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.BodyType + * @since 3.0.0 + */ +var BodyType = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#getBodyType + * @since 3.0.0 + * + * @return {number} [description] + */ + getBodyType: function () + { + return this.body.type; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeNone + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeNone: function () + { + this.body.type = TYPE.NONE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeA: function () + { + this.body.type = TYPE.A; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.BodyType#setTypeB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTypeB: function () + { + this.body.type = TYPE.B; + + return this; + } + +}; + +module.exports = BodyType; diff --git a/plugins/impact/components/Bounce.js b/plugins/impact/components/Bounce.js index 567f99c54..0732ec429 100644 --- a/plugins/impact/components/Bounce.js +++ b/plugins/impact/components/Bounce.js @@ -1,74 +1,74 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Bounce component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Bounce - * @since 3.0.0 - */ -var Bounce = { - - /** - * Sets the impact physics bounce, or restitution, value. - * - * @method Phaser.Physics.Impact.Components.Bounce#setBounce - * @since 3.0.0 - * - * @param {number} value - A value between 0 (no rebound) and 1 (full rebound) - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setBounce: function (value) - { - this.body.bounciness = value; - - return this; - }, - - /** - * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. - * - * @method Phaser.Physics.Impact.Components.Bounce#setMinBounceVelocity - * @since 3.0.0 - * - * @param {number} value - The minimum allowed velocity. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setMinBounceVelocity: function (value) - { - this.body.minBounceVelocity = value; - - return this; - }, - - /** - * The bounce, or restitution, value of this body. - * A value between 0 (no rebound) and 1 (full rebound) - * - * @name Phaser.Physics.Impact.Components.Bounce#bounce - * @type {number} - * @since 3.0.0 - */ - bounce: { - - get: function () - { - return this.body.bounciness; - }, - - set: function (value) - { - this.body.bounciness = value; - } - - } - -}; - -module.exports = Bounce; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Bounce component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the impact physics bounce, or restitution, value. + * + * @method Phaser.Physics.Impact.Components.Bounce#setBounce + * @since 3.0.0 + * + * @param {number} value - A value between 0 (no rebound) and 1 (full rebound) + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setBounce: function (value) + { + this.body.bounciness = value; + + return this; + }, + + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * + * @method Phaser.Physics.Impact.Components.Bounce#setMinBounceVelocity + * @since 3.0.0 + * + * @param {number} value - The minimum allowed velocity. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setMinBounceVelocity: function (value) + { + this.body.minBounceVelocity = value; + + return this; + }, + + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + * + * @name Phaser.Physics.Impact.Components.Bounce#bounce + * @type {number} + * @since 3.0.0 + */ + bounce: { + + get: function () + { + return this.body.bounciness; + }, + + set: function (value) + { + this.body.bounciness = value; + } + + } + +}; + +module.exports = Bounce; diff --git a/plugins/impact/components/CheckAgainst.js b/plugins/impact/components/CheckAgainst.js index 5c62b4d58..0aa1fc617 100644 --- a/plugins/impact/components/CheckAgainst.js +++ b/plugins/impact/components/CheckAgainst.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var TYPE = require('../TYPE'); - -/** - * The Impact Check Against component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.CheckAgainst - * @since 3.0.0 - */ -var CheckAgainst = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.CheckAgainst#setAvsB - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setAvsB: function () - { - this.setTypeA(); - - return this.setCheckAgainstB(); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.CheckAgainst#setBvsA - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setBvsA: function () - { - this.setTypeB(); - - return this.setCheckAgainstA(); - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstNone - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCheckAgainstNone: function () - { - this.body.checkAgainst = TYPE.NONE; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstA - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCheckAgainstA: function () - { - this.body.checkAgainst = TYPE.A; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstB - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCheckAgainstB: function () - { - this.body.checkAgainst = TYPE.B; - - return this; - }, - - /** - * [description] - * - * @name Phaser.Physics.Impact.Components.CheckAgainst#checkAgainst - * @type {number} - * @since 3.0.0 - */ - checkAgainst: { - - get: function () - { - return this.body.checkAgainst; - }, - - set: function (value) - { - this.body.checkAgainst = value; - } - - } - -}; - -module.exports = CheckAgainst; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TYPE = require('../TYPE'); + +/** + * The Impact Check Against component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.CheckAgainst + * @since 3.0.0 + */ +var CheckAgainst = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setAvsB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setAvsB: function () + { + this.setTypeA(); + + return this.setCheckAgainstB(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setBvsA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setBvsA: function () + { + this.setTypeB(); + + return this.setCheckAgainstA(); + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstNone + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstNone: function () + { + this.body.checkAgainst = TYPE.NONE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstA + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstA: function () + { + this.body.checkAgainst = TYPE.A; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.CheckAgainst#setCheckAgainstB + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCheckAgainstB: function () + { + this.body.checkAgainst = TYPE.B; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.CheckAgainst#checkAgainst + * @type {number} + * @since 3.0.0 + */ + checkAgainst: { + + get: function () + { + return this.body.checkAgainst; + }, + + set: function (value) + { + this.body.checkAgainst = value; + } + + } + +}; + +module.exports = CheckAgainst; diff --git a/plugins/impact/components/Collides.js b/plugins/impact/components/Collides.js index 7a8a6f9fb..156e53513 100644 --- a/plugins/impact/components/Collides.js +++ b/plugins/impact/components/Collides.js @@ -1,150 +1,150 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var COLLIDES = require('../COLLIDES'); - -/** - * @callback CollideCallback - * - * @param {Phaser.Physics.Impact.Body} body - [description] - * @param {Phaser.Physics.Impact.Body} other - [description] - * @param {string} axis - [description] - */ - -/** - * The Impact Collides component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Collides - * @since 3.0.0 - */ -var Collides = { - - _collideCallback: null, - _callbackScope: null, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Collides#setCollideCallback - * @since 3.0.0 - * - * @param {CollideCallback} callback - [description] - * @param {*} scope - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCollideCallback: function (callback, scope) - { - this._collideCallback = callback; - - if (scope) - { - this._callbackScope = scope; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Collides#setCollidesNever - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCollidesNever: function () - { - this.body.collides = COLLIDES.NEVER; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Collides#setLiteCollision - * @since 3.6.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setLiteCollision: function () - { - this.body.collides = COLLIDES.LITE; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Collides#setPassiveCollision - * @since 3.6.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setPassiveCollision: function () - { - this.body.collides = COLLIDES.PASSIVE; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Collides#setActiveCollision - * @since 3.6.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setActiveCollision: function () - { - this.body.collides = COLLIDES.ACTIVE; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Collides#setFixedCollision - * @since 3.6.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFixedCollision: function () - { - this.body.collides = COLLIDES.FIXED; - - return this; - }, - - /** - * [description] - * - * @name Phaser.Physics.Impact.Components.Collides#collides - * @type {number} - * @since 3.0.0 - */ - collides: { - - get: function () - { - return this.body.collides; - }, - - set: function (value) - { - this.body.collides = value; - } - - } - -}; - -module.exports = Collides; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var COLLIDES = require('../COLLIDES'); + +/** + * @callback CollideCallback + * + * @param {Phaser.Physics.Impact.Body} body - [description] + * @param {Phaser.Physics.Impact.Body} other - [description] + * @param {string} axis - [description] + */ + +/** + * The Impact Collides component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Collides + * @since 3.0.0 + */ +var Collides = { + + _collideCallback: null, + _callbackScope: null, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setCollideCallback + * @since 3.0.0 + * + * @param {CollideCallback} callback - [description] + * @param {*} scope - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollideCallback: function (callback, scope) + { + this._collideCallback = callback; + + if (scope) + { + this._callbackScope = scope; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setCollidesNever + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollidesNever: function () + { + this.body.collides = COLLIDES.NEVER; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setLiteCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setLiteCollision: function () + { + this.body.collides = COLLIDES.LITE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setPassiveCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setPassiveCollision: function () + { + this.body.collides = COLLIDES.PASSIVE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setActiveCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setActiveCollision: function () + { + this.body.collides = COLLIDES.ACTIVE; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Collides#setFixedCollision + * @since 3.6.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFixedCollision: function () + { + this.body.collides = COLLIDES.FIXED; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Collides#collides + * @type {number} + * @since 3.0.0 + */ + collides: { + + get: function () + { + return this.body.collides; + }, + + set: function (value) + { + this.body.collides = value; + } + + } + +}; + +module.exports = Collides; diff --git a/plugins/impact/components/Debug.js b/plugins/impact/components/Debug.js index 5796e757f..7a0b5f2b8 100644 --- a/plugins/impact/components/Debug.js +++ b/plugins/impact/components/Debug.js @@ -1,119 +1,119 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Debug component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Debug - * @since 3.0.0 - */ -var Debug = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Debug#setDebug - * @since 3.0.0 - * - * @param {boolean} showBody - [description] - * @param {boolean} showVelocity - [description] - * @param {number} bodyColor - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setDebug: function (showBody, showVelocity, bodyColor) - { - this.debugShowBody = showBody; - this.debugShowVelocity = showVelocity; - this.debugBodyColor = bodyColor; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Debug#setDebugBodyColor - * @since 3.0.0 - * - * @param {number} value - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setDebugBodyColor: function (value) - { - this.body.debugBodyColor = value; - - return this; - }, - - /** - * [description] - * - * @name Phaser.Physics.Impact.Components.Debug#debugShowBody - * @type {boolean} - * @since 3.0.0 - */ - debugShowBody: { - - get: function () - { - return this.body.debugShowBody; - }, - - set: function (value) - { - this.body.debugShowBody = value; - } - - }, - - /** - * [description] - * - * @name Phaser.Physics.Impact.Components.Debug#debugShowVelocity - * @type {boolean} - * @since 3.0.0 - */ - debugShowVelocity: { - - get: function () - { - return this.body.debugShowVelocity; - }, - - set: function (value) - { - this.body.debugShowVelocity = value; - } - - }, - - /** - * [description] - * - * @name Phaser.Physics.Impact.Components.Debug#debugBodyColor - * @type {number} - * @since 3.0.0 - */ - debugBodyColor: { - - get: function () - { - return this.body.debugBodyColor; - }, - - set: function (value) - { - this.body.debugBodyColor = value; - } - - } - -}; - -module.exports = Debug; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Debug component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Debug + * @since 3.0.0 + */ +var Debug = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Debug#setDebug + * @since 3.0.0 + * + * @param {boolean} showBody - [description] + * @param {boolean} showVelocity - [description] + * @param {number} bodyColor - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDebug: function (showBody, showVelocity, bodyColor) + { + this.debugShowBody = showBody; + this.debugShowVelocity = showVelocity; + this.debugBodyColor = bodyColor; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Debug#setDebugBodyColor + * @since 3.0.0 + * + * @param {number} value - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDebugBodyColor: function (value) + { + this.body.debugBodyColor = value; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + debugShowBody: { + + get: function () + { + return this.body.debugShowBody; + }, + + set: function (value) + { + this.body.debugShowBody = value; + } + + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + debugShowVelocity: { + + get: function () + { + return this.body.debugShowVelocity; + }, + + set: function (value) + { + this.body.debugShowVelocity = value; + } + + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Debug#debugBodyColor + * @type {number} + * @since 3.0.0 + */ + debugBodyColor: { + + get: function () + { + return this.body.debugBodyColor; + }, + + set: function (value) + { + this.body.debugBodyColor = value; + } + + } + +}; + +module.exports = Debug; diff --git a/plugins/impact/components/Friction.js b/plugins/impact/components/Friction.js index c9118194a..e8ebcf16d 100644 --- a/plugins/impact/components/Friction.js +++ b/plugins/impact/components/Friction.js @@ -1,71 +1,71 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Friction component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Friction - * @since 3.0.0 - */ -var Friction = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Friction#setFrictionX - * @since 3.0.0 - * - * @param {number} x - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFrictionX: function (x) - { - this.friction.x = x; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Friction#setFrictionY - * @since 3.0.0 - * - * @param {number} y - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFrictionY: function (y) - { - this.friction.y = y; - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Friction#setFriction - * @since 3.0.0 - * - * @param {number} x - [description] - * @param {number} y - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFriction: function (x, y) - { - this.friction.x = x; - this.friction.y = y; - - return this; - } - -}; - -module.exports = Friction; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Friction component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFrictionX + * @since 3.0.0 + * + * @param {number} x - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionX: function (x) + { + this.friction.x = x; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFrictionY + * @since 3.0.0 + * + * @param {number} y - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionY: function (y) + { + this.friction.y = y; + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFriction: function (x, y) + { + this.friction.x = x; + this.friction.y = y; + + return this; + } + +}; + +module.exports = Friction; diff --git a/plugins/impact/components/Gravity.js b/plugins/impact/components/Gravity.js index 9748492c3..b78a73bcf 100644 --- a/plugins/impact/components/Gravity.js +++ b/plugins/impact/components/Gravity.js @@ -1,56 +1,56 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Gravity component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Gravity - * @since 3.0.0 - */ -var Gravity = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Gravity#setGravity - * @since 3.0.0 - * - * @param {number} value - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setGravity: function (value) - { - this.body.gravityFactor = value; - - return this; - }, - - /** - * [description] - * - * @name Phaser.Physics.Impact.Components.Gravity#gravity - * @type {number} - * @since 3.0.0 - */ - gravity: { - - get: function () - { - return this.body.gravityFactor; - }, - - set: function (value) - { - this.body.gravityFactor = value; - } - - } - -}; - -module.exports = Gravity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Gravity component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Gravity#setGravity + * @since 3.0.0 + * + * @param {number} value - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setGravity: function (value) + { + this.body.gravityFactor = value; + + return this; + }, + + /** + * [description] + * + * @name Phaser.Physics.Impact.Components.Gravity#gravity + * @type {number} + * @since 3.0.0 + */ + gravity: { + + get: function () + { + return this.body.gravityFactor; + }, + + set: function (value) + { + this.body.gravityFactor = value; + } + + } + +}; + +module.exports = Gravity; diff --git a/plugins/impact/components/Offset.js b/plugins/impact/components/Offset.js index 0f4b732de..328d61dc7 100644 --- a/plugins/impact/components/Offset.js +++ b/plugins/impact/components/Offset.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Offset component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Offset - * @since 3.0.0 - */ -var Offset = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.Offset#setOffset - * @since 3.0.0 - * - * @param {number} x - [description] - * @param {number} y - [description] - * @param {number} [width] - [description] - * @param {number} [height] - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setOffset: function (x, y, width, height) - { - this.body.offset.x = x; - this.body.offset.y = y; - - if (width) - { - this.setBodySize(width, height); - } - - return this; - } - -}; - -module.exports = Offset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Offset component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Offset + * @since 3.0.0 + */ +var Offset = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.Offset#setOffset + * @since 3.0.0 + * + * @param {number} x - [description] + * @param {number} y - [description] + * @param {number} [width] - [description] + * @param {number} [height] - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOffset: function (x, y, width, height) + { + this.body.offset.x = x; + this.body.offset.y = y; + + if (width) + { + this.setBodySize(width, height); + } + + return this; + } + +}; + +module.exports = Offset; diff --git a/plugins/impact/components/SetGameObject.js b/plugins/impact/components/SetGameObject.js index 0a9498879..d73cb03b9 100644 --- a/plugins/impact/components/SetGameObject.js +++ b/plugins/impact/components/SetGameObject.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Set Game Object component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.SetGameObject - * @since 3.0.0 - */ -var SetGameObject = { - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.SetGameObject#setGameObject - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - [description] - * @param {boolean} [sync=true] - [description] - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setGameObject: function (gameObject, sync) - { - if (sync === undefined) { sync = true; } - - if (gameObject) - { - this.body.gameObject = gameObject; - - if (sync) - { - this.syncGameObject(); - } - } - else - { - this.body.gameObject = null; - } - - return this; - }, - - /** - * [description] - * - * @method Phaser.Physics.Impact.Components.SetGameObject#syncGameObject - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - syncGameObject: function () - { - var gameObject = this.body.gameObject; - - if (gameObject) - { - this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); - } - - return this; - } - -}; - -module.exports = SetGameObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Set Game Object component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.SetGameObject + * @since 3.0.0 + */ +var SetGameObject = { + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.SetGameObject#setGameObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - [description] + * @param {boolean} [sync=true] - [description] + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setGameObject: function (gameObject, sync) + { + if (sync === undefined) { sync = true; } + + if (gameObject) + { + this.body.gameObject = gameObject; + + if (sync) + { + this.syncGameObject(); + } + } + else + { + this.body.gameObject = null; + } + + return this; + }, + + /** + * [description] + * + * @method Phaser.Physics.Impact.Components.SetGameObject#syncGameObject + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + syncGameObject: function () + { + var gameObject = this.body.gameObject; + + if (gameObject) + { + this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY); + } + + return this; + } + +}; + +module.exports = SetGameObject; diff --git a/plugins/impact/components/Velocity.js b/plugins/impact/components/Velocity.js index d5542dbdd..ba2b4bfc0 100644 --- a/plugins/impact/components/Velocity.js +++ b/plugins/impact/components/Velocity.js @@ -1,94 +1,94 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Velocity component. - * Should be applied as a mixin. - * - * @namespace Phaser.Physics.Impact.Components.Velocity - * @since 3.0.0 - */ -var Velocity = { - - /** - * Sets the horizontal velocity of the physics body. - * - * @method Phaser.Physics.Impact.Components.Velocity#setVelocityX - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity value. - * - * @return {this} This Game Object. - */ - setVelocityX: function (x) - { - this.vel.x = x; - - return this; - }, - - /** - * Sets the vertical velocity of the physics body. - * - * @method Phaser.Physics.Impact.Components.Velocity#setVelocityY - * @since 3.0.0 - * - * @param {number} y - The vertical velocity value. - * - * @return {this} This Game Object. - */ - setVelocityY: function (y) - { - this.vel.y = y; - - return this; - }, - - /** - * Sets the horizontal and vertical velocities of the physics body. - * - * @method Phaser.Physics.Impact.Components.Velocity#setVelocity - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity value. - * @param {number} [y=x] - The vertical velocity value. If not given, defaults to the horizontal value. - * - * @return {this} This Game Object. - */ - setVelocity: function (x, y) - { - if (y === undefined) { y = x; } - - this.vel.x = x; - this.vel.y = y; - - return this; - }, - - /** - * Sets the maximum velocity this body can travel at. - * - * @method Phaser.Physics.Impact.Components.Velocity#setMaxVelocity - * @since 3.0.0 - * - * @param {number} x - The maximum allowed horizontal velocity. - * @param {number} [y=x] - The maximum allowed vertical velocity. If not given, defaults to the horizontal value. - * - * @return {this} This Game Object. - */ - setMaxVelocity: function (x, y) - { - if (y === undefined) { y = x; } - - this.maxVel.x = x; - this.maxVel.y = y; - - return this; - } - -}; - -module.exports = Velocity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Velocity component. + * Should be applied as a mixin. + * + * @namespace Phaser.Physics.Impact.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the horizontal velocity of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * + * @return {this} This Game Object. + */ + setVelocityX: function (x) + { + this.vel.x = x; + + return this; + }, + + /** + * Sets the vertical velocity of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The vertical velocity value. + * + * @return {this} This Game Object. + */ + setVelocityY: function (y) + { + this.vel.y = y; + + return this; + }, + + /** + * Sets the horizontal and vertical velocities of the physics body. + * + * @method Phaser.Physics.Impact.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * @param {number} [y=x] - The vertical velocity value. If not given, defaults to the horizontal value. + * + * @return {this} This Game Object. + */ + setVelocity: function (x, y) + { + if (y === undefined) { y = x; } + + this.vel.x = x; + this.vel.y = y; + + return this; + }, + + /** + * Sets the maximum velocity this body can travel at. + * + * @method Phaser.Physics.Impact.Components.Velocity#setMaxVelocity + * @since 3.0.0 + * + * @param {number} x - The maximum allowed horizontal velocity. + * @param {number} [y=x] - The maximum allowed vertical velocity. If not given, defaults to the horizontal value. + * + * @return {this} This Game Object. + */ + setMaxVelocity: function (x, y) + { + if (y === undefined) { y = x; } + + this.maxVel.x = x; + this.maxVel.y = y; + + return this; + } + +}; + +module.exports = Velocity; diff --git a/plugins/impact/components/index.js b/plugins/impact/components/index.js index a96a5a25c..d36d86e1a 100644 --- a/plugins/impact/components/index.js +++ b/plugins/impact/components/index.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Impact.Components - */ - -module.exports = { - - Acceleration: require('./Acceleration'), - BodyScale: require('./BodyScale'), - BodyType: require('./BodyType'), - Bounce: require('./Bounce'), - CheckAgainst: require('./CheckAgainst'), - Collides: require('./Collides'), - Debug: require('./Debug'), - Friction: require('./Friction'), - Gravity: require('./Gravity'), - Offset: require('./Offset'), - SetGameObject: require('./SetGameObject'), - Velocity: require('./Velocity') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Impact.Components + */ + +module.exports = { + + Acceleration: require('./Acceleration'), + BodyScale: require('./BodyScale'), + BodyType: require('./BodyType'), + Bounce: require('./Bounce'), + CheckAgainst: require('./CheckAgainst'), + Collides: require('./Collides'), + Debug: require('./Debug'), + Friction: require('./Friction'), + Gravity: require('./Gravity'), + Offset: require('./Offset'), + SetGameObject: require('./SetGameObject'), + Velocity: require('./Velocity') + +}; diff --git a/plugins/impact/events/COLLIDE_EVENT.js b/plugins/impact/events/COLLIDE_EVENT.js index 40a9cdb3d..2e6d81e85 100644 --- a/plugins/impact/events/COLLIDE_EVENT.js +++ b/plugins/impact/events/COLLIDE_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Physics World Collide Event. - * - * This event is dispatched by an Impact Physics World instance if two bodies collide. - * - * Listen to it from a Scene using: `this.impact.world.on('collide', listener)`. - * - * @event Phaser.Physics.Impact.Events#COLLIDE - * @since 3.0.0 - * - * @param {Phaser.Physics.Impact.Body} bodyA - The first body involved in the collision. - * @param {Phaser.Physics.Impact.Body} bodyB - The second body involved in the collision. - * @param {string} axis - The collision axis. Either `x` or `y`. - */ -module.exports = 'collide'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Collide Event. + * + * This event is dispatched by an Impact Physics World instance if two bodies collide. + * + * Listen to it from a Scene using: `this.impact.world.on('collide', listener)`. + * + * @event Phaser.Physics.Impact.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.Physics.Impact.Body} bodyA - The first body involved in the collision. + * @param {Phaser.Physics.Impact.Body} bodyB - The second body involved in the collision. + * @param {string} axis - The collision axis. Either `x` or `y`. + */ +module.exports = 'collide'; diff --git a/plugins/impact/events/PAUSE_EVENT.js b/plugins/impact/events/PAUSE_EVENT.js index 19a430887..1e5c77ff9 100644 --- a/plugins/impact/events/PAUSE_EVENT.js +++ b/plugins/impact/events/PAUSE_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Physics World Pause Event. - * - * This event is dispatched by an Impact Physics World instance when it is paused. - * - * Listen to it from a Scene using: `this.impact.world.on('pause', listener)`. - * - * @event Phaser.Physics.Impact.Events#PAUSE - * @since 3.0.0 - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Pause Event. + * + * This event is dispatched by an Impact Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.impact.world.on('pause', listener)`. + * + * @event Phaser.Physics.Impact.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; diff --git a/plugins/impact/events/RESUME_EVENT.js b/plugins/impact/events/RESUME_EVENT.js index c3de2ff33..e52ac03e8 100644 --- a/plugins/impact/events/RESUME_EVENT.js +++ b/plugins/impact/events/RESUME_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Impact Physics World Resume Event. - * - * This event is dispatched by an Impact Physics World instance when it resumes from a paused state. - * - * Listen to it from a Scene using: `this.impact.world.on('resume', listener)`. - * - * @event Phaser.Physics.Impact.Events#RESUME - * @since 3.0.0 - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Impact Physics World Resume Event. + * + * This event is dispatched by an Impact Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.impact.world.on('resume', listener)`. + * + * @event Phaser.Physics.Impact.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; diff --git a/plugins/impact/events/index.js b/plugins/impact/events/index.js index d67d7d392..ea474798f 100644 --- a/plugins/impact/events/index.js +++ b/plugins/impact/events/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Impact.Events - */ - -module.exports = { - - COLLIDE: require('./COLLIDE_EVENT'), - PAUSE: require('./PAUSE_EVENT'), - RESUME: require('./RESUME_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Impact.Events + */ + +module.exports = { + + COLLIDE: require('./COLLIDE_EVENT'), + PAUSE: require('./PAUSE_EVENT'), + RESUME: require('./RESUME_EVENT') + +}; diff --git a/plugins/impact/index.js b/plugins/impact/index.js index f55a42b69..552e5f5b3 100644 --- a/plugins/impact/index.js +++ b/plugins/impact/index.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * An Impact.js compatible physics world, body and solver, for those who are used - * to the Impact way of defining and controlling physics bodies. Also works with - * the new Loader support for Weltmeister map data. - * - * World updated to run off the Phaser main loop. - * Body extended to support additional setter functions. - * - * To create the map data you'll need Weltmeister, which comes with Impact - * and can be purchased from http://impactjs.com - * - * My thanks to Dominic Szablewski for his permission to support Impact in Phaser. - * - * @namespace Phaser.Physics.Impact - */ -module.exports = { - - Body: require('./Body'), - Events: require('./events'), - COLLIDES: require('./COLLIDES'), - CollisionMap: require('./CollisionMap'), - Factory: require('./Factory'), - Image: require('./ImpactImage'), - ImpactBody: require('./ImpactBody'), - ImpactPhysics: require('./ImpactPhysics'), - Sprite: require('./ImpactSprite'), - TYPE: require('./TYPE'), - World: require('./World') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * An Impact.js compatible physics world, body and solver, for those who are used + * to the Impact way of defining and controlling physics bodies. Also works with + * the new Loader support for Weltmeister map data. + * + * World updated to run off the Phaser main loop. + * Body extended to support additional setter functions. + * + * To create the map data you'll need Weltmeister, which comes with Impact + * and can be purchased from http://impactjs.com + * + * My thanks to Dominic Szablewski for his permission to support Impact in Phaser. + * + * @namespace Phaser.Physics.Impact + */ +module.exports = { + + Body: require('./Body'), + Events: require('./events'), + COLLIDES: require('./COLLIDES'), + CollisionMap: require('./CollisionMap'), + Factory: require('./Factory'), + Image: require('./ImpactImage'), + ImpactBody: require('./ImpactBody'), + ImpactPhysics: require('./ImpactPhysics'), + Sprite: require('./ImpactSprite'), + TYPE: require('./TYPE'), + World: require('./World') + +}; diff --git a/plugins/impact/typedefs/CollisionOptions.js b/plugins/impact/typedefs/CollisionOptions.js index ba501bb35..0f5146a6c 100644 --- a/plugins/impact/typedefs/CollisionOptions.js +++ b/plugins/impact/typedefs/CollisionOptions.js @@ -1,14 +1,14 @@ -/** - * @typedef {object} Phaser.Types.Physics.Impact.CollisionOptions - * @since 3.0.0 - * - * @property {string} [slopeTileProperty=null] - Slope IDs can be stored on tiles directly - * using Impacts tileset editor. If a tile has a property with the given slopeTileProperty string - * name, the value of that property for the tile will be used for its slope mapping. E.g. a 45 - * degree slope upward could be given a "slope" property with a value of 2. - * @property {object} [slopeMap=null] - A tile index to slope definition map. - * @property {integer} [defaultCollidingSlope=null] - If specified, the default slope ID to - * assign to a colliding tile. If not specified, the tile's index is used. - * @property {integer} [defaultNonCollidingSlope=0] - The default slope ID to assign to a - * non-colliding tile. - */ +/** + * @typedef {object} Phaser.Types.Physics.Impact.CollisionOptions + * @since 3.0.0 + * + * @property {string} [slopeTileProperty=null] - Slope IDs can be stored on tiles directly + * using Impacts tileset editor. If a tile has a property with the given slopeTileProperty string + * name, the value of that property for the tile will be used for its slope mapping. E.g. a 45 + * degree slope upward could be given a "slope" property with a value of 2. + * @property {object} [slopeMap=null] - A tile index to slope definition map. + * @property {integer} [defaultCollidingSlope=null] - If specified, the default slope ID to + * assign to a colliding tile. If not specified, the tile's index is used. + * @property {integer} [defaultNonCollidingSlope=0] - The default slope ID to assign to a + * non-colliding tile. + */ diff --git a/plugins/impact/typedefs/JSONImpactBody.js b/plugins/impact/typedefs/JSONImpactBody.js index 64bb2ad16..5219c6a50 100644 --- a/plugins/impact/typedefs/JSONImpactBody.js +++ b/plugins/impact/typedefs/JSONImpactBody.js @@ -1,18 +1,18 @@ -/** - * @typedef {object} Phaser.Types.Physics.Impact.JSONImpactBody - * @since 3.0.0 - * - * @property {string} name - [description] - * @property {Phaser.Types.Math.Vector2Like} size - [description] - * @property {Phaser.Types.Math.Vector2Like} pos - The entity's position in the game world. - * @property {Phaser.Types.Math.Vector2Like} vel - Current velocity in pixels per second. - * @property {Phaser.Types.Math.Vector2Like} accel - Current acceleration to be added to the entity's velocity per second. E.g. an entity with a `vel.x` of 0 and `accel.x` of 10 will have a `vel.x` of 100 ten seconds later. - * @property {Phaser.Types.Math.Vector2Like} friction - Deceleration to be subtracted from the entity's velocity per second. Only applies if `accel` is 0. - * @property {Phaser.Types.Math.Vector2Like} maxVel - The maximum velocity a body can move. - * @property {number} gravityFactor - [description] - * @property {number} bounciness - [description] - * @property {number} minBounceVelocity - [description] - * @property {Phaser.Physics.Impact.TYPE} type - [description] - * @property {Phaser.Physics.Impact.TYPE} checkAgainst - [description] - * @property {Phaser.Physics.Impact.COLLIDES} collides - [description] - */ +/** + * @typedef {object} Phaser.Types.Physics.Impact.JSONImpactBody + * @since 3.0.0 + * + * @property {string} name - [description] + * @property {Phaser.Types.Math.Vector2Like} size - [description] + * @property {Phaser.Types.Math.Vector2Like} pos - The entity's position in the game world. + * @property {Phaser.Types.Math.Vector2Like} vel - Current velocity in pixels per second. + * @property {Phaser.Types.Math.Vector2Like} accel - Current acceleration to be added to the entity's velocity per second. E.g. an entity with a `vel.x` of 0 and `accel.x` of 10 will have a `vel.x` of 100 ten seconds later. + * @property {Phaser.Types.Math.Vector2Like} friction - Deceleration to be subtracted from the entity's velocity per second. Only applies if `accel` is 0. + * @property {Phaser.Types.Math.Vector2Like} maxVel - The maximum velocity a body can move. + * @property {number} gravityFactor - [description] + * @property {number} bounciness - [description] + * @property {number} minBounceVelocity - [description] + * @property {Phaser.Physics.Impact.TYPE} type - [description] + * @property {Phaser.Physics.Impact.TYPE} checkAgainst - [description] + * @property {Phaser.Physics.Impact.COLLIDES} collides - [description] + */ diff --git a/plugins/impact/typedefs/WorldConfig.js b/plugins/impact/typedefs/WorldConfig.js index 8460cc975..c0ef8ef5b 100644 --- a/plugins/impact/typedefs/WorldConfig.js +++ b/plugins/impact/typedefs/WorldConfig.js @@ -1,30 +1,30 @@ -/** - * @typedef {object} Phaser.Types.Physics.Impact.WorldConfig - * @since 3.0.0 - * - * @property {number} [gravity=0] - Sets {@link Phaser.Physics.Impact.World#gravity} - * @property {number} [cellSize=64] - The size of the cells used for the broadphase pass. Increase this value if you have lots of large objects in the world. - * @property {number} [timeScale=1] - A number that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - * @property {number} [maxStep=0.05] - [description] - * @property {boolean} [debug=false] - Sets {@link Phaser.Physics.Impact.World#debug}. - * @property {number} [maxVelocity=100] - The maximum velocity a body can move. - * @property {boolean} [debugShowBody=true] - Whether the Body's boundary is drawn to the debug display. - * @property {boolean} [debugShowVelocity=true] - Whether the Body's velocity is drawn to the debug display. - * @property {number} [debugBodyColor=0xff00ff] - The color of this Body on the debug display. - * @property {number} [debugVelocityColor=0x00ff00] - The color of the Body's velocity on the debug display. - * @property {number} [maxVelocityX=maxVelocity] - Maximum X velocity objects can move. - * @property {number} [maxVelocityY=maxVelocity] - Maximum Y velocity objects can move. - * @property {number} [minBounceVelocity=40] - The minimum velocity an object can be moving at to be considered for bounce. - * @property {number} [gravityFactor=1] - Gravity multiplier. Set to 0 for no gravity. - * @property {number} [bounciness=0] - The default bounce, or restitution, of bodies in the world. - * @property {(object|boolean)} [setBounds] - Should the world have bounds enabled by default? - * @property {number} [setBounds.x=0] - The x coordinate of the world bounds. - * @property {number} [setBounds.y=0] - The y coordinate of the world bounds. - * @property {number} [setBounds.width] - The width of the world bounds. - * @property {number} [setBounds.height] - The height of the world bounds. - * @property {number} [setBounds.thickness=64] - The thickness of the walls of the world bounds. - * @property {boolean} [setBounds.left=true] - Should the left-side world bounds wall be created? - * @property {boolean} [setBounds.right=true] - Should the right-side world bounds wall be created? - * @property {boolean} [setBounds.top=true] - Should the top world bounds wall be created? - * @property {boolean} [setBounds.bottom=true] - Should the bottom world bounds wall be created? - */ +/** + * @typedef {object} Phaser.Types.Physics.Impact.WorldConfig + * @since 3.0.0 + * + * @property {number} [gravity=0] - Sets {@link Phaser.Physics.Impact.World#gravity} + * @property {number} [cellSize=64] - The size of the cells used for the broadphase pass. Increase this value if you have lots of large objects in the world. + * @property {number} [timeScale=1] - A number that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + * @property {number} [maxStep=0.05] - [description] + * @property {boolean} [debug=false] - Sets {@link Phaser.Physics.Impact.World#debug}. + * @property {number} [maxVelocity=100] - The maximum velocity a body can move. + * @property {boolean} [debugShowBody=true] - Whether the Body's boundary is drawn to the debug display. + * @property {boolean} [debugShowVelocity=true] - Whether the Body's velocity is drawn to the debug display. + * @property {number} [debugBodyColor=0xff00ff] - The color of this Body on the debug display. + * @property {number} [debugVelocityColor=0x00ff00] - The color of the Body's velocity on the debug display. + * @property {number} [maxVelocityX=maxVelocity] - Maximum X velocity objects can move. + * @property {number} [maxVelocityY=maxVelocity] - Maximum Y velocity objects can move. + * @property {number} [minBounceVelocity=40] - The minimum velocity an object can be moving at to be considered for bounce. + * @property {number} [gravityFactor=1] - Gravity multiplier. Set to 0 for no gravity. + * @property {number} [bounciness=0] - The default bounce, or restitution, of bodies in the world. + * @property {(object|boolean)} [setBounds] - Should the world have bounds enabled by default? + * @property {number} [setBounds.x=0] - The x coordinate of the world bounds. + * @property {number} [setBounds.y=0] - The y coordinate of the world bounds. + * @property {number} [setBounds.width] - The width of the world bounds. + * @property {number} [setBounds.height] - The height of the world bounds. + * @property {number} [setBounds.thickness=64] - The thickness of the walls of the world bounds. + * @property {boolean} [setBounds.left=true] - Should the left-side world bounds wall be created? + * @property {boolean} [setBounds.right=true] - Should the right-side world bounds wall be created? + * @property {boolean} [setBounds.top=true] - Should the top world bounds wall be created? + * @property {boolean} [setBounds.bottom=true] - Should the bottom world bounds wall be created? + */ diff --git a/plugins/impact/typedefs/WorldDefaults.js b/plugins/impact/typedefs/WorldDefaults.js index bfa1f1619..a18e50d80 100644 --- a/plugins/impact/typedefs/WorldDefaults.js +++ b/plugins/impact/typedefs/WorldDefaults.js @@ -1,16 +1,16 @@ -/** - * An object containing the 4 wall bodies that bound the physics world. - * - * @typedef {object} Phaser.Types.Physics.Impact.WorldDefaults - * @since 3.0.0 - * - * @property {boolean} debugShowBody - Whether the Body's boundary is drawn to the debug display. - * @property {boolean} debugShowVelocity - Whether the Body's velocity is drawn to the debug display. - * @property {number} bodyDebugColor - The color of this Body on the debug display. - * @property {number} velocityDebugColor - The color of the Body's velocity on the debug display. - * @property {number} maxVelocityX - Maximum X velocity objects can move. - * @property {number} maxVelocityY - Maximum Y velocity objects can move. - * @property {number} minBounceVelocity - The minimum velocity an object can be moving at to be considered for bounce. - * @property {number} gravityFactor - Gravity multiplier. Set to 0 for no gravity. - * @property {number} bounciness - The default bounce, or restitution, of bodies in the world. - */ +/** + * An object containing the 4 wall bodies that bound the physics world. + * + * @typedef {object} Phaser.Types.Physics.Impact.WorldDefaults + * @since 3.0.0 + * + * @property {boolean} debugShowBody - Whether the Body's boundary is drawn to the debug display. + * @property {boolean} debugShowVelocity - Whether the Body's velocity is drawn to the debug display. + * @property {number} bodyDebugColor - The color of this Body on the debug display. + * @property {number} velocityDebugColor - The color of the Body's velocity on the debug display. + * @property {number} maxVelocityX - Maximum X velocity objects can move. + * @property {number} maxVelocityY - Maximum Y velocity objects can move. + * @property {number} minBounceVelocity - The minimum velocity an object can be moving at to be considered for bounce. + * @property {number} gravityFactor - Gravity multiplier. Set to 0 for no gravity. + * @property {number} bounciness - The default bounce, or restitution, of bodies in the world. + */ diff --git a/plugins/impact/typedefs/WorldWalls.js b/plugins/impact/typedefs/WorldWalls.js index 75ada77f6..111803f44 100644 --- a/plugins/impact/typedefs/WorldWalls.js +++ b/plugins/impact/typedefs/WorldWalls.js @@ -1,9 +1,9 @@ -/** - * @typedef {object} Phaser.Types.Physics.Impact.WorldWalls - * @since 3.0.0 - * - * @property {?Phaser.Physics.Impact.Body} left - The left-side wall of the world bounds. - * @property {?Phaser.Physics.Impact.Body} right - The right-side wall of the world bounds. - * @property {?Phaser.Physics.Impact.Body} top - The top wall of the world bounds. - * @property {?Phaser.Physics.Impact.Body} bottom - The bottom wall of the world bounds. - */ +/** + * @typedef {object} Phaser.Types.Physics.Impact.WorldWalls + * @since 3.0.0 + * + * @property {?Phaser.Physics.Impact.Body} left - The left-side wall of the world bounds. + * @property {?Phaser.Physics.Impact.Body} right - The right-side wall of the world bounds. + * @property {?Phaser.Physics.Impact.Body} top - The top wall of the world bounds. + * @property {?Phaser.Physics.Impact.Body} bottom - The bottom wall of the world bounds. + */ diff --git a/plugins/impact/typedefs/index.js b/plugins/impact/typedefs/index.js index 725199d1b..009a73c5f 100644 --- a/plugins/impact/typedefs/index.js +++ b/plugins/impact/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Physics.Impact - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Physics.Impact + */ diff --git a/scripts/tsgen/bin/Parser.js b/scripts/tsgen/bin/Parser.js index 95029d62e..437a15b70 100644 --- a/scripts/tsgen/bin/Parser.js +++ b/scripts/tsgen/bin/Parser.js @@ -1,510 +1,510 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const dom = require("dts-dom"); -const regexEndLine = /^(.*)\r\n|\n|\r/gm; -class Parser { - constructor(docs) { - this.topLevel = []; - this.objects = {}; - this.namespaces = {}; - // parse doclets and create corresponding dom objects - this.parseObjects(docs); - this.resolveObjects(docs); - // removes members inherited from classes - // possibly could be avoided if mixins were defined as such before JSDoc parses them and then we could globally remove all inherited (not - // overridden) members globally from the parsed DB - this.resolveInheritance(docs); - this.resolveParents(docs); - // add integer alias - this.topLevel.push(dom.create.alias('integer', dom.type.number)); - // add declare module - const phaserPkgModuleDOM = dom.create.module('phaser'); - phaserPkgModuleDOM.members.push(dom.create.exportEquals('Phaser')); - this.topLevel.push(phaserPkgModuleDOM); - } - emit() { - let ignored = []; - let result = '/// \n\n'; - result = result.concat(this.topLevel.reduce((out, obj) => { - return out + dom.emit(obj); - }, '')); - if (ignored.length > 0) { - console.log('ignored top level properties:'); - console.log(ignored); - } - return result; - } - parseObjects(docs) { - for (let i = 0; i < docs.length; i++) { - let doclet = docs[i]; - // TODO: Custom temporary rules - switch (doclet.longname) { - case 'Phaser.GameObjects.Components.Alpha': - case 'Phaser.GameObjects.Components.AlphaSingle': - case 'Phaser.GameObjects.Components.Animation': - case 'Phaser.GameObjects.Components.BlendMode': - case 'Phaser.GameObjects.Components.ComputedSize': - case 'Phaser.GameObjects.Components.Crop': - case 'Phaser.GameObjects.Components.Depth': - case 'Phaser.GameObjects.Components.Flip': - case 'Phaser.GameObjects.Components.GetBounds': - case 'Phaser.GameObjects.Components.Mask': - case 'Phaser.GameObjects.Components.Origin': - case 'Phaser.GameObjects.Components.PathFollower': - case 'Phaser.GameObjects.Components.Pipeline': - case 'Phaser.GameObjects.Components.ScrollFactor': - case 'Phaser.GameObjects.Components.Size': - case 'Phaser.GameObjects.Components.Texture': - case 'Phaser.GameObjects.Components.TextureCrop': - case 'Phaser.GameObjects.Components.Tint': - case 'Phaser.GameObjects.Components.ToJSON': - case 'Phaser.GameObjects.Components.Transform': - case 'Phaser.GameObjects.Components.Visible': - case 'Phaser.Renderer.WebGL.Pipelines.ModelViewProjection': - doclet.kind = 'mixin'; - break; - // Because, sod you TypeScript - case 'Phaser.BlendModes': - case 'Phaser.ScaleModes': - case 'Phaser.Physics.Impact.TYPE': - case 'Phaser.Physics.Impact.COLLIDES': - case 'Phaser.Scale.Center': - case 'Phaser.Scale.Orientation': - case 'Phaser.Scale.ScaleModes': - case 'Phaser.Scale.Zoom': - case 'Phaser.Textures.FilterMode': - // console.log('Forcing enum for ' + doclet.longname); - doclet.kind = 'member'; - doclet.isEnum = true; - break; - } - if ((doclet.longname.indexOf('Phaser.Physics.Arcade.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Impact.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Matter.Components.') == 0) && doclet.longname.indexOf('#') == -1) { - doclet.kind = 'mixin'; - } - let obj; - let container = this.objects; - switch (doclet.kind) { - case 'namespace': - obj = this.createNamespace(doclet); - container = this.namespaces; - break; - case 'class': - obj = this.createClass(doclet); - break; - case 'mixin': - obj = this.createInterface(doclet); - break; - case 'member': - if (doclet.isEnum === true) { - obj = this.createEnum(doclet); - break; - } - case 'constant': - obj = this.createMember(doclet); - break; - case 'function': - obj = this.createFunction(doclet); - break; - case 'typedef': - obj = this.createTypedef(doclet); - break; - case 'event': - obj = this.createEvent(doclet); - break; - default: - console.log('Ignored doclet kind: ' + doclet.kind); - break; - } - if (obj) { - if (container[doclet.longname]) { - console.log('Warning: ignoring duplicate doc name: ' + doclet.longname); - docs.splice(i--, 1); - continue; - } - container[doclet.longname] = obj; - if (doclet.description) { - let otherDocs = obj.jsDocComment || ''; - obj.jsDocComment = doclet.description.replace(regexEndLine, '$1\n') + otherDocs; - } - } - } - } - resolveObjects(docs) { - let allTypes = new Set(); - for (let doclet of docs) { - let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; - if (!obj) { - // TODO - console.log(`Warning: Didn't find object for ${doclet.longname}`); - continue; - } - if (!doclet.memberof) { - this.topLevel.push(obj); - } - else { - let isNamespaceMember = doclet.kind === 'class' || doclet.kind === 'typedef' || doclet.kind == 'namespace' || doclet.isEnum; - let parent = isNamespaceMember ? this.namespaces[doclet.memberof] : (this.objects[doclet.memberof] || this.namespaces[doclet.memberof]); - //TODO: this whole section should be removed once stable - if (!parent) { - console.log(`${doclet.longname} in ${doclet.meta.filename}@${doclet.meta.lineno} has parent '${doclet.memberof}' that is not defined.`); - let parts = doclet.memberof.split('.'); - let newParts = [parts.pop()]; - while (parts.length > 0 && this.objects[parts.join('.')] == null) - newParts.unshift(parts.pop()); - parent = this.objects[parts.join('.')]; - if (parent == null) { - parent = dom.create.namespace(doclet.memberof); - this.namespaces[doclet.memberof] = parent; - this.topLevel.push(parent); - } - else { - while (newParts.length > 0) { - let oldParent = parent; - parent = dom.create.namespace(newParts.shift()); - parts.push(parent.name); - this.namespaces[parts.join('.')] = parent; - oldParent.members.push(parent); - parent._parent = oldParent; - } - } - } - /////////////////////////////////////////////////////// - if (parent.members) { - parent.members.push(obj); - } - else { - console.log('Cannot find members array for:'); - console.log(parent); - } - obj._parent = parent; - // class/interface members have methods, not functions - if ((parent.kind === 'class' || parent.kind === 'interface') - && obj.kind === 'function') - obj.kind = 'method'; - // namespace members are vars or consts, not properties - if (parent.kind === 'namespace' && obj.kind === 'property') { - if (doclet.kind == 'constant') - obj.kind = 'const'; - else - obj.kind = 'var'; - } - } - } - } - resolveInheritance(docs) { - for (let doclet of docs) { - let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; - if (!obj) { - // TODO - console.log(`Didn't find type ${doclet.longname} ???`); - continue; - } - if (!obj._parent) - continue; - if (doclet.inherited) { // remove inherited members if they aren't from an interface - let from = this.objects[doclet.inherits]; - if (!from || !from._parent) - throw `'${doclet.longname}' should inherit from '${doclet.inherits}', which is not defined.`; - if (from._parent.kind != 'interface') { - obj._parent.members.splice(obj._parent.members.indexOf(obj), 1); - obj._parent = null; - } - } - } - } - resolveParents(docs) { - for (let doclet of docs) { - let obj = this.objects[doclet.longname]; - if (!obj || doclet.kind !== 'class') - continue; - let o = obj; - // resolve augments - if (doclet.augments && doclet.augments.length) { - for (let augment of doclet.augments) { - let name = this.prepareTypeName(augment); - let wrappingName = name.match(/[^<]+/s)[0]; //gets everything up to a first < (to handle augments with type parameters) - let baseType = this.objects[wrappingName]; - if (!baseType) { - console.log(`ERROR: Did not find base type: ${augment} for ${doclet.longname}`); - } - else { - if (baseType.kind == 'class') { - o.baseType = dom.create.class(name); - } - else { - o.implements.push(dom.create.interface(name)); - } - } - } - } - } - } - createNamespace(doclet) { - /** - namespace: { comment: '', - meta: - { filename: 'index.js', - lineno: 10, - columnno: 0, - path: '/Users/rich/Documents/GitHub/phaser/src/tweens', - code: {} }, - kind: 'namespace', - name: 'Tweens', - memberof: 'Phaser', - longname: 'Phaser.Tweens', - scope: 'static', - ___id: 'T000002R034468', - ___s: true } - */ - // console.log('namespace:', doclet.longname); - let obj = dom.create.namespace(doclet.name); - return obj; - } - createClass(doclet) { - let obj = dom.create.class(doclet.name); - let params = null; - if (doclet.params) { - let ctor = dom.create.constructor(null); - this.setParams(doclet, ctor); - params = ctor.parameters; - obj.members.push(ctor); - ctor._parent = obj; - } - this.processGeneric(doclet, obj, params); - if (doclet.classdesc) - doclet.description = doclet.classdesc.replace(regexEndLine, '$1\n'); // make sure docs will be added - return obj; - } - createInterface(doclet) { - return dom.create.interface(doclet.name); - } - createMember(doclet) { - let type = this.parseType(doclet); - let obj = dom.create.property(doclet.name, type); - this.processGeneric(doclet, obj, null); - this.processFlags(doclet, obj); - return obj; - } - createEvent(doclet) { - let type = this.parseType(doclet); - let obj = dom.create.const(doclet.name, type); - this.processFlags(doclet, obj); - return obj; - } - createEnum(doclet) { - let obj = dom.create.enum(doclet.name, false); - this.processFlags(doclet, obj); - return obj; - } - createFunction(doclet) { - let returnType = dom.type.void; - if (doclet.returns) { - returnType = this.parseType(doclet.returns[0]); - } - let obj = dom.create.function(doclet.name, null, returnType); - this.setParams(doclet, obj); - this.processGeneric(doclet, obj, obj.parameters); - this.processFlags(doclet, obj); - return obj; - } - createTypedef(doclet) { - const typeName = doclet.type.names[0]; - let type = null; - if (doclet.type.names[0] === 'object') { - let properties = []; - for (let propDoc of doclet.properties) { - let prop = this.createMember(propDoc); - properties.push(prop); - if (propDoc.description) - prop.jsDocComment = propDoc.description.replace(regexEndLine, '$1\n'); - } - type = dom.create.objectType(properties); - if (doclet.augments && doclet.augments.length) { - let intersectionTypes = []; - for (let i = 0; i < doclet.augments.length; i++) { - intersectionTypes.push(dom.create.namedTypeReference(doclet.augments[i])); - } - intersectionTypes.push(type); - type = dom.create.intersection(intersectionTypes); - } - } - else { - if (doclet.type.names[0] == "function") { - type = dom.create.functionType(null, dom.type.void); - this.setParams(doclet, type); - } - else { - type = this.parseType(doclet); - } - } - let alias = dom.create.alias(doclet.name, type); - this.processGeneric(doclet, alias, null); - return alias; - } - setParams(doclet, obj) { - let parameters = []; - if (doclet.params) { - let optional = false; - obj.jsDocComment = ''; - for (let paramDoc of doclet.params) { - // TODO REMOVE TEMP FIX - if (paramDoc.name.indexOf('.') != -1) { - console.log(`Warning: ignoring param with '.' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); - let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; - if (paramDoc.description) - obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; - else if (defaultVal.length) - obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; - continue; - } - /////////////////////// - let param = dom.create.parameter(paramDoc.name, this.parseType(paramDoc)); - parameters.push(param); - if (optional && paramDoc.optional != true) { - console.log(`Warning: correcting to optional: parameter '${paramDoc.name}' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); - paramDoc.optional = true; - } - this.processFlags(paramDoc, param); - optional = optional || paramDoc.optional === true; - let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; - if (paramDoc.description) - obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; - else if (defaultVal.length) - obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; - } - } - obj.parameters = parameters; - } - parseType(typeDoc) { - if (!typeDoc || !typeDoc.type) { - return dom.type.any; - } - else { - let types = []; - for (let name of typeDoc.type.names) { - name = this.prepareTypeName(name); - let type = dom.create.namedTypeReference(this.processTypeName(name)); - types.push(type); - } - if (types.length == 1) - return types[0]; - else - return dom.create.union(types); - } - } - prepareTypeName(name) { - if (name.indexOf('*') != -1) { - name = name.split('*').join('any'); - } - if (name.indexOf('.<') != -1 && name !== 'Array.') { - name = name.split('.<').join('<'); - } - return name; - } - processTypeName(name) { - if (name === 'float') - return 'number'; - if (name === 'function') - return 'Function'; - if (name === 'Array.') - return 'Function[]'; - if (name === 'array') - return 'any[]'; - if (name.startsWith('Array<')) { - let matches = name.match(/^Array<(.*)>$/); - if (matches && matches[1]) { - return this.processTypeName(matches[1]) + '[]'; - } - } - else if (name.startsWith('Object<')) { - let matches = name.match(/^Object<(.*)>$/); - if (matches && matches[1]) { - if (matches[1].indexOf(',') != -1) { - let parts = matches[1].split(','); - return `{[key: ${this.processTypeName(parts[0])}]: ${this.processTypeName(parts[1])}}`; - } - else { - return `{[key: string]: ${this.processTypeName(matches[1])}}`; - } - } - } - return name; - } - processFlags(doclet, obj) { - obj.flags = dom.DeclarationFlags.None; - if (doclet.variable === true) { - obj.flags |= dom.ParameterFlags.Rest; - let type = obj.type; - if (!type.name.endsWith('[]')) { - if (type.name != 'any') - console.log(`Warning: rest parameter should be an array type for ${doclet.longname}`); - type.name = type.name + '[]'; // Must be an array - } - } - else if (doclet.optional === true) { // Rest implies Optional – no need to flag it as such - if (obj['kind'] === 'parameter') - obj.flags |= dom.ParameterFlags.Optional; - else - obj.flags |= dom.DeclarationFlags.Optional; - } - switch (doclet.access) { - case 'protected': - obj.flags |= dom.DeclarationFlags.Protected; - break; - case 'private': - obj.flags |= dom.DeclarationFlags.Private; - break; - } - if (doclet.readonly || doclet.kind === 'constant') - obj.flags |= dom.DeclarationFlags.ReadOnly; - if (doclet.scope === 'static') - obj.flags |= dom.DeclarationFlags.Static; - } - processGeneric(doclet, obj, params) { - if (doclet.tags) - for (let tag of doclet.tags) { - if (tag.originalTitle === 'generic') { - /** - * {string} K - [key] - * 1 = string | 2 = null | 3 = K | 4 = key - * - * {string=string} K - [key] - * 1 = string | 2 = string | 3 = K | 4 = key - */ - const matches = tag.value.match(/(?:(?:{)([^}=]+)(?:=)?([^}=]+)?(?:}))?\s?([^\s]+)(?:\s?-\s?(?:\[)(.+)(?:\]))?/); - const [_, _type, _defaultType, _name, _paramsNames] = matches; - const typeParam = dom.create.typeParameter(_name, _type == null ? null : dom.create.typeParameter(_type)); - if (_defaultType != null) { - typeParam.defaultType = dom.create.typeParameter(_defaultType); - } - obj.typeParameters.push(typeParam); - handleOverrides(_paramsNames, _name); - } - else if (tag.originalTitle === 'genericUse') { - let matches = tag.value.match(/(?:(?:{)([^}]+)(?:}))(?:\s?-\s?(?:\[)(.+)(?:\]))?/); - let overrideType = this.prepareTypeName(matches[1]); - handleOverrides(matches[2], this.processTypeName(overrideType)); - } - } - function handleOverrides(matchedString, overrideType) { - if (matchedString != null) { - let overrides = matchedString.split(','); - if (params != null) { - for (let param of params) { - if (overrides.indexOf(param.name) != -1) { - param.type = dom.create.namedTypeReference(overrideType); - } - } - } - if (overrides.indexOf('$return') != -1) { // has $return, must be a function - obj.returnType = dom.create.namedTypeReference(overrideType); - } - if (overrides.indexOf('$type') != -1) { // has $type, must be a property - obj.type = dom.create.namedTypeReference(overrideType); - } - } - } - } -} -exports.Parser = Parser; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dom = require("dts-dom"); +const regexEndLine = /^(.*)\r\n|\n|\r/gm; +class Parser { + constructor(docs) { + this.topLevel = []; + this.objects = {}; + this.namespaces = {}; + // parse doclets and create corresponding dom objects + this.parseObjects(docs); + this.resolveObjects(docs); + // removes members inherited from classes + // possibly could be avoided if mixins were defined as such before JSDoc parses them and then we could globally remove all inherited (not + // overridden) members globally from the parsed DB + this.resolveInheritance(docs); + this.resolveParents(docs); + // add integer alias + this.topLevel.push(dom.create.alias('integer', dom.type.number)); + // add declare module + const phaserPkgModuleDOM = dom.create.module('phaser'); + phaserPkgModuleDOM.members.push(dom.create.exportEquals('Phaser')); + this.topLevel.push(phaserPkgModuleDOM); + } + emit() { + let ignored = []; + let result = '/// \n\n'; + result = result.concat(this.topLevel.reduce((out, obj) => { + return out + dom.emit(obj); + }, '')); + if (ignored.length > 0) { + console.log('ignored top level properties:'); + console.log(ignored); + } + return result; + } + parseObjects(docs) { + for (let i = 0; i < docs.length; i++) { + let doclet = docs[i]; + // TODO: Custom temporary rules + switch (doclet.longname) { + case 'Phaser.GameObjects.Components.Alpha': + case 'Phaser.GameObjects.Components.AlphaSingle': + case 'Phaser.GameObjects.Components.Animation': + case 'Phaser.GameObjects.Components.BlendMode': + case 'Phaser.GameObjects.Components.ComputedSize': + case 'Phaser.GameObjects.Components.Crop': + case 'Phaser.GameObjects.Components.Depth': + case 'Phaser.GameObjects.Components.Flip': + case 'Phaser.GameObjects.Components.GetBounds': + case 'Phaser.GameObjects.Components.Mask': + case 'Phaser.GameObjects.Components.Origin': + case 'Phaser.GameObjects.Components.PathFollower': + case 'Phaser.GameObjects.Components.Pipeline': + case 'Phaser.GameObjects.Components.ScrollFactor': + case 'Phaser.GameObjects.Components.Size': + case 'Phaser.GameObjects.Components.Texture': + case 'Phaser.GameObjects.Components.TextureCrop': + case 'Phaser.GameObjects.Components.Tint': + case 'Phaser.GameObjects.Components.ToJSON': + case 'Phaser.GameObjects.Components.Transform': + case 'Phaser.GameObjects.Components.Visible': + case 'Phaser.Renderer.WebGL.Pipelines.ModelViewProjection': + doclet.kind = 'mixin'; + break; + // Because, sod you TypeScript + case 'Phaser.BlendModes': + case 'Phaser.ScaleModes': + case 'Phaser.Physics.Impact.TYPE': + case 'Phaser.Physics.Impact.COLLIDES': + case 'Phaser.Scale.Center': + case 'Phaser.Scale.Orientation': + case 'Phaser.Scale.ScaleModes': + case 'Phaser.Scale.Zoom': + case 'Phaser.Textures.FilterMode': + // console.log('Forcing enum for ' + doclet.longname); + doclet.kind = 'member'; + doclet.isEnum = true; + break; + } + if ((doclet.longname.indexOf('Phaser.Physics.Arcade.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Impact.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Matter.Components.') == 0) && doclet.longname.indexOf('#') == -1) { + doclet.kind = 'mixin'; + } + let obj; + let container = this.objects; + switch (doclet.kind) { + case 'namespace': + obj = this.createNamespace(doclet); + container = this.namespaces; + break; + case 'class': + obj = this.createClass(doclet); + break; + case 'mixin': + obj = this.createInterface(doclet); + break; + case 'member': + if (doclet.isEnum === true) { + obj = this.createEnum(doclet); + break; + } + case 'constant': + obj = this.createMember(doclet); + break; + case 'function': + obj = this.createFunction(doclet); + break; + case 'typedef': + obj = this.createTypedef(doclet); + break; + case 'event': + obj = this.createEvent(doclet); + break; + default: + console.log('Ignored doclet kind: ' + doclet.kind); + break; + } + if (obj) { + if (container[doclet.longname]) { + console.log('Warning: ignoring duplicate doc name: ' + doclet.longname); + docs.splice(i--, 1); + continue; + } + container[doclet.longname] = obj; + if (doclet.description) { + let otherDocs = obj.jsDocComment || ''; + obj.jsDocComment = doclet.description.replace(regexEndLine, '$1\n') + otherDocs; + } + } + } + } + resolveObjects(docs) { + let allTypes = new Set(); + for (let doclet of docs) { + let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; + if (!obj) { + // TODO + console.log(`Warning: Didn't find object for ${doclet.longname}`); + continue; + } + if (!doclet.memberof) { + this.topLevel.push(obj); + } + else { + let isNamespaceMember = doclet.kind === 'class' || doclet.kind === 'typedef' || doclet.kind == 'namespace' || doclet.isEnum; + let parent = isNamespaceMember ? this.namespaces[doclet.memberof] : (this.objects[doclet.memberof] || this.namespaces[doclet.memberof]); + //TODO: this whole section should be removed once stable + if (!parent) { + console.log(`${doclet.longname} in ${doclet.meta.filename}@${doclet.meta.lineno} has parent '${doclet.memberof}' that is not defined.`); + let parts = doclet.memberof.split('.'); + let newParts = [parts.pop()]; + while (parts.length > 0 && this.objects[parts.join('.')] == null) + newParts.unshift(parts.pop()); + parent = this.objects[parts.join('.')]; + if (parent == null) { + parent = dom.create.namespace(doclet.memberof); + this.namespaces[doclet.memberof] = parent; + this.topLevel.push(parent); + } + else { + while (newParts.length > 0) { + let oldParent = parent; + parent = dom.create.namespace(newParts.shift()); + parts.push(parent.name); + this.namespaces[parts.join('.')] = parent; + oldParent.members.push(parent); + parent._parent = oldParent; + } + } + } + /////////////////////////////////////////////////////// + if (parent.members) { + parent.members.push(obj); + } + else { + console.log('Cannot find members array for:'); + console.log(parent); + } + obj._parent = parent; + // class/interface members have methods, not functions + if ((parent.kind === 'class' || parent.kind === 'interface') + && obj.kind === 'function') + obj.kind = 'method'; + // namespace members are vars or consts, not properties + if (parent.kind === 'namespace' && obj.kind === 'property') { + if (doclet.kind == 'constant') + obj.kind = 'const'; + else + obj.kind = 'var'; + } + } + } + } + resolveInheritance(docs) { + for (let doclet of docs) { + let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; + if (!obj) { + // TODO + console.log(`Didn't find type ${doclet.longname} ???`); + continue; + } + if (!obj._parent) + continue; + if (doclet.inherited) { // remove inherited members if they aren't from an interface + let from = this.objects[doclet.inherits]; + if (!from || !from._parent) + throw `'${doclet.longname}' should inherit from '${doclet.inherits}', which is not defined.`; + if (from._parent.kind != 'interface') { + obj._parent.members.splice(obj._parent.members.indexOf(obj), 1); + obj._parent = null; + } + } + } + } + resolveParents(docs) { + for (let doclet of docs) { + let obj = this.objects[doclet.longname]; + if (!obj || doclet.kind !== 'class') + continue; + let o = obj; + // resolve augments + if (doclet.augments && doclet.augments.length) { + for (let augment of doclet.augments) { + let name = this.prepareTypeName(augment); + let wrappingName = name.match(/[^<]+/s)[0]; //gets everything up to a first < (to handle augments with type parameters) + let baseType = this.objects[wrappingName]; + if (!baseType) { + console.log(`ERROR: Did not find base type: ${augment} for ${doclet.longname}`); + } + else { + if (baseType.kind == 'class') { + o.baseType = dom.create.class(name); + } + else { + o.implements.push(dom.create.interface(name)); + } + } + } + } + } + } + createNamespace(doclet) { + /** + namespace: { comment: '', + meta: + { filename: 'index.js', + lineno: 10, + columnno: 0, + path: '/Users/rich/Documents/GitHub/phaser/src/tweens', + code: {} }, + kind: 'namespace', + name: 'Tweens', + memberof: 'Phaser', + longname: 'Phaser.Tweens', + scope: 'static', + ___id: 'T000002R034468', + ___s: true } + */ + // console.log('namespace:', doclet.longname); + let obj = dom.create.namespace(doclet.name); + return obj; + } + createClass(doclet) { + let obj = dom.create.class(doclet.name); + let params = null; + if (doclet.params) { + let ctor = dom.create.constructor(null); + this.setParams(doclet, ctor); + params = ctor.parameters; + obj.members.push(ctor); + ctor._parent = obj; + } + this.processGeneric(doclet, obj, params); + if (doclet.classdesc) + doclet.description = doclet.classdesc.replace(regexEndLine, '$1\n'); // make sure docs will be added + return obj; + } + createInterface(doclet) { + return dom.create.interface(doclet.name); + } + createMember(doclet) { + let type = this.parseType(doclet); + let obj = dom.create.property(doclet.name, type); + this.processGeneric(doclet, obj, null); + this.processFlags(doclet, obj); + return obj; + } + createEvent(doclet) { + let type = this.parseType(doclet); + let obj = dom.create.const(doclet.name, type); + this.processFlags(doclet, obj); + return obj; + } + createEnum(doclet) { + let obj = dom.create.enum(doclet.name, false); + this.processFlags(doclet, obj); + return obj; + } + createFunction(doclet) { + let returnType = dom.type.void; + if (doclet.returns) { + returnType = this.parseType(doclet.returns[0]); + } + let obj = dom.create.function(doclet.name, null, returnType); + this.setParams(doclet, obj); + this.processGeneric(doclet, obj, obj.parameters); + this.processFlags(doclet, obj); + return obj; + } + createTypedef(doclet) { + const typeName = doclet.type.names[0]; + let type = null; + if (doclet.type.names[0] === 'object') { + let properties = []; + for (let propDoc of doclet.properties) { + let prop = this.createMember(propDoc); + properties.push(prop); + if (propDoc.description) + prop.jsDocComment = propDoc.description.replace(regexEndLine, '$1\n'); + } + type = dom.create.objectType(properties); + if (doclet.augments && doclet.augments.length) { + let intersectionTypes = []; + for (let i = 0; i < doclet.augments.length; i++) { + intersectionTypes.push(dom.create.namedTypeReference(doclet.augments[i])); + } + intersectionTypes.push(type); + type = dom.create.intersection(intersectionTypes); + } + } + else { + if (doclet.type.names[0] == "function") { + type = dom.create.functionType(null, dom.type.void); + this.setParams(doclet, type); + } + else { + type = this.parseType(doclet); + } + } + let alias = dom.create.alias(doclet.name, type); + this.processGeneric(doclet, alias, null); + return alias; + } + setParams(doclet, obj) { + let parameters = []; + if (doclet.params) { + let optional = false; + obj.jsDocComment = ''; + for (let paramDoc of doclet.params) { + // TODO REMOVE TEMP FIX + if (paramDoc.name.indexOf('.') != -1) { + console.log(`Warning: ignoring param with '.' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); + let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; + if (paramDoc.description) + obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; + else if (defaultVal.length) + obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; + continue; + } + /////////////////////// + let param = dom.create.parameter(paramDoc.name, this.parseType(paramDoc)); + parameters.push(param); + if (optional && paramDoc.optional != true) { + console.log(`Warning: correcting to optional: parameter '${paramDoc.name}' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); + paramDoc.optional = true; + } + this.processFlags(paramDoc, param); + optional = optional || paramDoc.optional === true; + let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; + if (paramDoc.description) + obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; + else if (defaultVal.length) + obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; + } + } + obj.parameters = parameters; + } + parseType(typeDoc) { + if (!typeDoc || !typeDoc.type) { + return dom.type.any; + } + else { + let types = []; + for (let name of typeDoc.type.names) { + name = this.prepareTypeName(name); + let type = dom.create.namedTypeReference(this.processTypeName(name)); + types.push(type); + } + if (types.length == 1) + return types[0]; + else + return dom.create.union(types); + } + } + prepareTypeName(name) { + if (name.indexOf('*') != -1) { + name = name.split('*').join('any'); + } + if (name.indexOf('.<') != -1 && name !== 'Array.') { + name = name.split('.<').join('<'); + } + return name; + } + processTypeName(name) { + if (name === 'float') + return 'number'; + if (name === 'function') + return 'Function'; + if (name === 'Array.') + return 'Function[]'; + if (name === 'array') + return 'any[]'; + if (name.startsWith('Array<')) { + let matches = name.match(/^Array<(.*)>$/); + if (matches && matches[1]) { + return this.processTypeName(matches[1]) + '[]'; + } + } + else if (name.startsWith('Object<')) { + let matches = name.match(/^Object<(.*)>$/); + if (matches && matches[1]) { + if (matches[1].indexOf(',') != -1) { + let parts = matches[1].split(','); + return `{[key: ${this.processTypeName(parts[0])}]: ${this.processTypeName(parts[1])}}`; + } + else { + return `{[key: string]: ${this.processTypeName(matches[1])}}`; + } + } + } + return name; + } + processFlags(doclet, obj) { + obj.flags = dom.DeclarationFlags.None; + if (doclet.variable === true) { + obj.flags |= dom.ParameterFlags.Rest; + let type = obj.type; + if (!type.name.endsWith('[]')) { + if (type.name != 'any') + console.log(`Warning: rest parameter should be an array type for ${doclet.longname}`); + type.name = type.name + '[]'; // Must be an array + } + } + else if (doclet.optional === true) { // Rest implies Optional – no need to flag it as such + if (obj['kind'] === 'parameter') + obj.flags |= dom.ParameterFlags.Optional; + else + obj.flags |= dom.DeclarationFlags.Optional; + } + switch (doclet.access) { + case 'protected': + obj.flags |= dom.DeclarationFlags.Protected; + break; + case 'private': + obj.flags |= dom.DeclarationFlags.Private; + break; + } + if (doclet.readonly || doclet.kind === 'constant') + obj.flags |= dom.DeclarationFlags.ReadOnly; + if (doclet.scope === 'static') + obj.flags |= dom.DeclarationFlags.Static; + } + processGeneric(doclet, obj, params) { + if (doclet.tags) + for (let tag of doclet.tags) { + if (tag.originalTitle === 'generic') { + /** + * {string} K - [key] + * 1 = string | 2 = null | 3 = K | 4 = key + * + * {string=string} K - [key] + * 1 = string | 2 = string | 3 = K | 4 = key + */ + const matches = tag.value.match(/(?:(?:{)([^}=]+)(?:=)?([^}=]+)?(?:}))?\s?([^\s]+)(?:\s?-\s?(?:\[)(.+)(?:\]))?/); + const [_, _type, _defaultType, _name, _paramsNames] = matches; + const typeParam = dom.create.typeParameter(_name, _type == null ? null : dom.create.typeParameter(_type)); + if (_defaultType != null) { + typeParam.defaultType = dom.create.typeParameter(_defaultType); + } + obj.typeParameters.push(typeParam); + handleOverrides(_paramsNames, _name); + } + else if (tag.originalTitle === 'genericUse') { + let matches = tag.value.match(/(?:(?:{)([^}]+)(?:}))(?:\s?-\s?(?:\[)(.+)(?:\]))?/); + let overrideType = this.prepareTypeName(matches[1]); + handleOverrides(matches[2], this.processTypeName(overrideType)); + } + } + function handleOverrides(matchedString, overrideType) { + if (matchedString != null) { + let overrides = matchedString.split(','); + if (params != null) { + for (let param of params) { + if (overrides.indexOf(param.name) != -1) { + param.type = dom.create.namedTypeReference(overrideType); + } + } + } + if (overrides.indexOf('$return') != -1) { // has $return, must be a function + obj.returnType = dom.create.namedTypeReference(overrideType); + } + if (overrides.indexOf('$type') != -1) { // has $type, must be a property + obj.type = dom.create.namedTypeReference(overrideType); + } + } + } + } +} +exports.Parser = Parser; //# sourceMappingURL=Parser.js.map \ No newline at end of file diff --git a/scripts/tsgen/src/Parser.ts b/scripts/tsgen/src/Parser.ts index b61480f3b..d01841a61 100644 --- a/scripts/tsgen/src/Parser.ts +++ b/scripts/tsgen/src/Parser.ts @@ -1,607 +1,607 @@ -import * as dom from 'dts-dom'; - -const regexEndLine = /^(.*)\r\n|\n|\r/gm; - -export class Parser { - - topLevel: dom.TopLevelDeclaration[]; - objects: { [key: string]: dom.DeclarationBase }; - namespaces: { [key: string]: dom.NamespaceDeclaration }; - - constructor(docs: any[]) { - - this.topLevel = []; - this.objects = {}; - this.namespaces = {}; - - // parse doclets and create corresponding dom objects - this.parseObjects(docs); - - this.resolveObjects(docs); - - // removes members inherited from classes - // possibly could be avoided if mixins were defined as such before JSDoc parses them and then we could globally remove all inherited (not - // overridden) members globally from the parsed DB - this.resolveInheritance(docs); - - this.resolveParents(docs); - - // add integer alias - this.topLevel.push(dom.create.alias('integer', dom.type.number)); - - // add declare module - const phaserPkgModuleDOM = dom.create.module('phaser'); - phaserPkgModuleDOM.members.push(dom.create.exportEquals('Phaser')); - this.topLevel.push(phaserPkgModuleDOM); - } - - emit() { - - let ignored = []; - - let result = '/// \n\n'; - - result = result.concat(this.topLevel.reduce((out: string, obj: dom.TopLevelDeclaration) => { - return out + dom.emit(obj); - }, '')); - - if (ignored.length > 0) - { - console.log('ignored top level properties:'); - console.log(ignored); - } - - return result; - } - - private parseObjects(docs: any[]) { - for (let i = 0; i < docs.length; i++) { - - let doclet = docs[i]; - - // TODO: Custom temporary rules - switch (doclet.longname) - { - case 'Phaser.GameObjects.Components.Alpha': - case 'Phaser.GameObjects.Components.AlphaSingle': - case 'Phaser.GameObjects.Components.Animation': - case 'Phaser.GameObjects.Components.BlendMode': - case 'Phaser.GameObjects.Components.ComputedSize': - case 'Phaser.GameObjects.Components.Crop': - case 'Phaser.GameObjects.Components.Depth': - case 'Phaser.GameObjects.Components.Flip': - case 'Phaser.GameObjects.Components.GetBounds': - case 'Phaser.GameObjects.Components.Mask': - case 'Phaser.GameObjects.Components.Origin': - case 'Phaser.GameObjects.Components.PathFollower': - case 'Phaser.GameObjects.Components.Pipeline': - case 'Phaser.GameObjects.Components.ScrollFactor': - case 'Phaser.GameObjects.Components.Size': - case 'Phaser.GameObjects.Components.Texture': - case 'Phaser.GameObjects.Components.TextureCrop': - case 'Phaser.GameObjects.Components.Tint': - case 'Phaser.GameObjects.Components.ToJSON': - case 'Phaser.GameObjects.Components.Transform': - case 'Phaser.GameObjects.Components.Visible': - case 'Phaser.Renderer.WebGL.Pipelines.ModelViewProjection': - doclet.kind = 'mixin'; - break; - - // Because, sod you TypeScript - case 'Phaser.BlendModes': - case 'Phaser.ScaleModes': - case 'Phaser.Physics.Impact.TYPE': - case 'Phaser.Physics.Impact.COLLIDES': - case 'Phaser.Scale.Center': - case 'Phaser.Scale.Orientation': - case 'Phaser.Scale.ScaleModes': - case 'Phaser.Scale.Zoom': - case 'Phaser.Textures.FilterMode': - // console.log('Forcing enum for ' + doclet.longname); - doclet.kind = 'member'; - doclet.isEnum = true; - break; - } - - if ((doclet.longname.indexOf('Phaser.Physics.Arcade.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Impact.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Matter.Components.') == 0) && doclet.longname.indexOf('#') == -1) - { - doclet.kind = 'mixin'; - } - - let obj: dom.DeclarationBase; - let container = this.objects; - - switch (doclet.kind) { - case 'namespace': - obj = this.createNamespace(doclet); - container = this.namespaces; - break; - case 'class': - obj = this.createClass(doclet); - break; - case 'mixin': - obj = this.createInterface(doclet); - break; - case 'member': - if (doclet.isEnum === true) { - obj = this.createEnum(doclet); - break; - } - case 'constant': - obj = this.createMember(doclet); - break; - case 'function': - obj = this.createFunction(doclet); - break; - case 'typedef': - obj = this.createTypedef(doclet); - break; - case 'event': - obj = this.createEvent(doclet); - break; - default: - console.log('Ignored doclet kind: ' + doclet.kind); - break; - } - - if (obj) { - if (container[doclet.longname]) { - console.log('Warning: ignoring duplicate doc name: ' + doclet.longname); - docs.splice(i--, 1); - continue; - } - container[doclet.longname] = obj; - if (doclet.description) { - let otherDocs = obj.jsDocComment || ''; - obj.jsDocComment = doclet.description.replace(regexEndLine, '$1\n') + otherDocs; - } - } - } - } - - private resolveObjects(docs: any[]) { - let allTypes = new Set(); - for (let doclet of docs) { - let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; - - if (!obj) { - - // TODO - console.log(`Warning: Didn't find object for ${doclet.longname}`); - - continue; - } - - if (!doclet.memberof) { - this.topLevel.push(obj as dom.TopLevelDeclaration); - } else { - let isNamespaceMember = doclet.kind === 'class' || doclet.kind === 'typedef' || doclet.kind == 'namespace' || doclet.isEnum; - let parent = isNamespaceMember ? this.namespaces[doclet.memberof] : (this.objects[doclet.memberof] || this.namespaces[doclet.memberof]); - - //TODO: this whole section should be removed once stable - if (!parent) { - console.log(`${doclet.longname} in ${doclet.meta.filename}@${doclet.meta.lineno} has parent '${doclet.memberof}' that is not defined.`); - let parts: string[] = doclet.memberof.split('.'); - let newParts = [parts.pop()]; - while (parts.length > 0 && this.objects[parts.join('.')] == null) newParts.unshift(parts.pop()); - parent = this.objects[parts.join('.')] as dom.NamespaceDeclaration; - if (parent == null) { - parent = dom.create.namespace(doclet.memberof); - this.namespaces[doclet.memberof] = parent; - this.topLevel.push(parent); - } else { - while (newParts.length > 0) { - let oldParent = parent; - parent = dom.create.namespace(newParts.shift()); - parts.push((parent).name); - this.namespaces[parts.join('.')] = parent; - oldParent.members.push(parent); - (parent)._parent = oldParent; - } - } - } - /////////////////////////////////////////////////////// - - if ((parent).members) { - (parent).members.push(obj); - } else { - console.log('Cannot find members array for:'); - console.log(parent); - } - - (obj)._parent = parent; - - // class/interface members have methods, not functions - if (((parent as any).kind === 'class' || (parent as any).kind === 'interface') - && (obj as any).kind === 'function') - (obj as any).kind = 'method'; - // namespace members are vars or consts, not properties - if ((parent as any).kind === 'namespace' && (obj as any).kind === 'property') { - if (doclet.kind == 'constant') (obj as any).kind = 'const'; - else (obj as any).kind = 'var'; - } - } - } - } - - private resolveInheritance(docs: any[]) { - for (let doclet of docs) { - let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; - if (!obj) { - - // TODO - console.log(`Didn't find type ${doclet.longname} ???`); - - continue; - } - if (!(obj)._parent) continue; - - if (doclet.inherited) {// remove inherited members if they aren't from an interface - let from = this.objects[doclet.inherits]; - if (!from || !(from)._parent) - throw `'${doclet.longname}' should inherit from '${doclet.inherits}', which is not defined.`; - - if ((from)._parent.kind != 'interface') { - (obj)._parent.members.splice((obj)._parent.members.indexOf(obj), 1); - (obj)._parent = null; - } - } - } - } - - private resolveParents(docs: any[]) { - for (let doclet of docs) { - let obj = this.objects[doclet.longname]; - if (!obj || doclet.kind !== 'class') continue; - - let o = obj as dom.ClassDeclaration; - - // resolve augments - if (doclet.augments && doclet.augments.length) { - for (let augment of doclet.augments) { - let name: string = this.prepareTypeName(augment); - - let wrappingName = name.match(/[^<]+/s)[0];//gets everything up to a first < (to handle augments with type parameters) - - let baseType = this.objects[wrappingName] as dom.ClassDeclaration | dom.InterfaceDeclaration; - - if (!baseType) { - console.log(`ERROR: Did not find base type: ${augment} for ${doclet.longname}`); - } else { - if (baseType.kind == 'class') { - o.baseType = dom.create.class(name); - } else { - o.implements.push(dom.create.interface(name)); - } - } - } - } - } - } - - private createNamespace(doclet: any): dom.NamespaceDeclaration { - - /** - namespace: { comment: '', - meta: - { filename: 'index.js', - lineno: 10, - columnno: 0, - path: '/Users/rich/Documents/GitHub/phaser/src/tweens', - code: {} }, - kind: 'namespace', - name: 'Tweens', - memberof: 'Phaser', - longname: 'Phaser.Tweens', - scope: 'static', - ___id: 'T000002R034468', - ___s: true } - */ - - // console.log('namespace:', doclet.longname); - - let obj = dom.create.namespace(doclet.name); - - return obj; - } - - private createClass(doclet: any): dom.ClassDeclaration { - let obj = dom.create.class(doclet.name); - - let params = null; - if (doclet.params) { - let ctor = dom.create.constructor(null); - this.setParams(doclet, ctor); - params = ctor.parameters; - - obj.members.push(ctor); - (ctor)._parent = obj; - } - - this.processGeneric(doclet, obj, params); - - if (doclet.classdesc) - doclet.description = doclet.classdesc.replace(regexEndLine, '$1\n'); // make sure docs will be added - - return obj; - } - - private createInterface(doclet: any): dom.InterfaceDeclaration { - return dom.create.interface(doclet.name); - } - - private createMember(doclet: any): dom.PropertyDeclaration { - let type = this.parseType(doclet); - - let obj = dom.create.property(doclet.name, type); - - this.processGeneric(doclet, obj, null); - - this.processFlags(doclet, obj); - - return obj; - } - - private createEvent(doclet: any): dom.ConstDeclaration { - - let type = this.parseType(doclet); - - let obj = dom.create.const(doclet.name, type); - - this.processFlags(doclet, obj); - - return obj; - } - - private createEnum(doclet: any): dom.EnumDeclaration { - let obj = dom.create.enum(doclet.name, false); - - this.processFlags(doclet, obj); - - return obj; - } - - private createFunction(doclet: any): dom.FunctionDeclaration { - let returnType: dom.Type = dom.type.void; - - if (doclet.returns) { - returnType = this.parseType(doclet.returns[0]); - } - - let obj = dom.create.function(doclet.name, null, returnType); - this.setParams(doclet, obj); - - this.processGeneric(doclet, obj, obj.parameters); - - this.processFlags(doclet, obj); - - return obj; - } - - private createTypedef(doclet: any): dom.TypeAliasDeclaration { - const typeName = doclet.type.names[0]; - let type = null; - - if (doclet.type.names[0] === 'object') { - let properties = []; - - for (let propDoc of doclet.properties) { - let prop = this.createMember(propDoc); - properties.push(prop); - if (propDoc.description) - prop.jsDocComment = propDoc.description.replace(regexEndLine, '$1\n'); - } - - type = dom.create.objectType(properties); - - if (doclet.augments && doclet.augments.length) { - let intersectionTypes = []; - for (let i = 0; i < doclet.augments.length; i++) { - intersectionTypes.push(dom.create.namedTypeReference(doclet.augments[i])); - } - intersectionTypes.push(type); - type = dom.create.intersection(intersectionTypes); - } - - } else { - if (doclet.type.names[0] == "function") { - type = dom.create.functionType(null, dom.type.void); - this.setParams(doclet, type); - } else { - type = this.parseType(doclet); - } - } - - let alias = dom.create.alias(doclet.name, type); - - this.processGeneric(doclet, alias, null); - - return alias; - } - - private setParams(doclet: any, obj: dom.FunctionDeclaration | dom.ConstructorDeclaration): void { - let parameters: dom.Parameter[] = []; - - if (doclet.params) { - - let optional = false; - - obj.jsDocComment = ''; - - for (let paramDoc of doclet.params) { - - // TODO REMOVE TEMP FIX - if (paramDoc.name.indexOf('.') != -1) { - console.log(`Warning: ignoring param with '.' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); - - let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; - if (paramDoc.description) - obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; - else if (defaultVal.length) - obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; - continue; - } - /////////////////////// - - let param = dom.create.parameter(paramDoc.name, this.parseType(paramDoc)); - parameters.push(param); - - if (optional && paramDoc.optional != true) { - console.log(`Warning: correcting to optional: parameter '${paramDoc.name}' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); - paramDoc.optional = true; - } - - this.processFlags(paramDoc, param); - - optional = optional || paramDoc.optional === true; - - let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; - - if (paramDoc.description) - obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; - else if (defaultVal.length) - obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; - } - } - - obj.parameters = parameters; - } - - private parseType(typeDoc: any): dom.Type { - if (!typeDoc || !typeDoc.type) { - return dom.type.any; - } else { - let types = []; - for (let name of typeDoc.type.names) { - - name = this.prepareTypeName(name); - - let type = dom.create.namedTypeReference(this.processTypeName(name)); - - types.push(type); - } - if (types.length == 1) return types[0]; - else return dom.create.union(types); - } - } - - private prepareTypeName(name: string): string { - if (name.indexOf('*') != -1) { - name = (name).split('*').join('any'); - } - if (name.indexOf('.<') != -1 && name !== 'Array.') { - name = (name).split('.<').join('<'); - } - return name; - } - - private processTypeName(name: string): string { - if (name === 'float') return 'number'; - if (name === 'function') return 'Function'; - if (name === 'Array.') return 'Function[]'; - if (name === 'array') return 'any[]'; - - if (name.startsWith('Array<')) { - let matches = name.match(/^Array<(.*)>$/); - - if (matches && matches[1]) { - return this.processTypeName(matches[1]) + '[]'; - } - } else if (name.startsWith('Object<')) { - let matches = name.match(/^Object<(.*)>$/); - - if (matches && matches[1]) { - if (matches[1].indexOf(',') != -1) { - let parts = matches[1].split(','); - return `{[key: ${this.processTypeName(parts[0])}]: ${this.processTypeName(parts[1])}}`; - } else { - return `{[key: string]: ${this.processTypeName(matches[1])}}`; - } - } - } - - return name; - } - - private processFlags(doclet: any, obj: dom.DeclarationBase | dom.Parameter) { - obj.flags = dom.DeclarationFlags.None; - if (doclet.variable === true) { - obj.flags |= dom.ParameterFlags.Rest; - let type: any = (obj).type; - if (!type.name.endsWith('[]')) { - if (type.name != 'any') - console.log(`Warning: rest parameter should be an array type for ${doclet.longname}`); - type.name = type.name + '[]'; // Must be an array - } - } else if (doclet.optional === true) {// Rest implies Optional – no need to flag it as such - if (obj['kind'] === 'parameter') obj.flags |= dom.ParameterFlags.Optional; - else obj.flags |= dom.DeclarationFlags.Optional; - } - switch (doclet.access) { - case 'protected': - obj.flags |= dom.DeclarationFlags.Protected; - break; - case 'private': - obj.flags |= dom.DeclarationFlags.Private; - break; - } - if (doclet.readonly || doclet.kind === 'constant') obj.flags |= dom.DeclarationFlags.ReadOnly; - if (doclet.scope === 'static') obj.flags |= dom.DeclarationFlags.Static; - } - - private processGeneric(doclet: any, obj: dom.ClassDeclaration | dom.FunctionDeclaration | dom.PropertyDeclaration | dom.TypeAliasDeclaration, params: dom.Parameter[]) { - if (doclet.tags) - for (let tag of doclet.tags) { - if (tag.originalTitle === 'generic') { - - /** - * {string} K - [key] - * 1 = string | 2 = null | 3 = K | 4 = key - * - * {string=string} K - [key] - * 1 = string | 2 = string | 3 = K | 4 = key - */ - const matches = (tag.value).match(/(?:(?:{)([^}=]+)(?:=)?([^}=]+)?(?:}))?\s?([^\s]+)(?:\s?-\s?(?:\[)(.+)(?:\]))?/); - const [_, _type, _defaultType, _name, _paramsNames] = matches; - - const typeParam = dom.create.typeParameter( - _name, - _type == null ? null : dom.create.typeParameter(_type) - ); - - if(_defaultType != null) { - typeParam.defaultType = dom.create.typeParameter(_defaultType); - } - - (obj).typeParameters.push(typeParam); - handleOverrides(_paramsNames, _name); - - } else if (tag.originalTitle === 'genericUse') { - let matches = (tag.value).match(/(?:(?:{)([^}]+)(?:}))(?:\s?-\s?(?:\[)(.+)(?:\]))?/); - let overrideType: string = this.prepareTypeName(matches[1]); - - handleOverrides(matches[2], this.processTypeName(overrideType)); - } - } - - function handleOverrides(matchedString: string, overrideType: string) { - if (matchedString != null) { - let overrides = matchedString.split(','); - if (params != null) { - for (let param of params) { - if (overrides.indexOf(param.name) != -1) { - param.type = dom.create.namedTypeReference(overrideType); - } - } - } - if (overrides.indexOf('$return') != -1) {// has $return, must be a function - (obj).returnType = dom.create.namedTypeReference(overrideType); - } - if (overrides.indexOf('$type') != -1) {// has $type, must be a property - (obj).type = dom.create.namedTypeReference(overrideType); - } - } - } - } - -} +import * as dom from 'dts-dom'; + +const regexEndLine = /^(.*)\r\n|\n|\r/gm; + +export class Parser { + + topLevel: dom.TopLevelDeclaration[]; + objects: { [key: string]: dom.DeclarationBase }; + namespaces: { [key: string]: dom.NamespaceDeclaration }; + + constructor(docs: any[]) { + + this.topLevel = []; + this.objects = {}; + this.namespaces = {}; + + // parse doclets and create corresponding dom objects + this.parseObjects(docs); + + this.resolveObjects(docs); + + // removes members inherited from classes + // possibly could be avoided if mixins were defined as such before JSDoc parses them and then we could globally remove all inherited (not + // overridden) members globally from the parsed DB + this.resolveInheritance(docs); + + this.resolveParents(docs); + + // add integer alias + this.topLevel.push(dom.create.alias('integer', dom.type.number)); + + // add declare module + const phaserPkgModuleDOM = dom.create.module('phaser'); + phaserPkgModuleDOM.members.push(dom.create.exportEquals('Phaser')); + this.topLevel.push(phaserPkgModuleDOM); + } + + emit() { + + let ignored = []; + + let result = '/// \n\n'; + + result = result.concat(this.topLevel.reduce((out: string, obj: dom.TopLevelDeclaration) => { + return out + dom.emit(obj); + }, '')); + + if (ignored.length > 0) + { + console.log('ignored top level properties:'); + console.log(ignored); + } + + return result; + } + + private parseObjects(docs: any[]) { + for (let i = 0; i < docs.length; i++) { + + let doclet = docs[i]; + + // TODO: Custom temporary rules + switch (doclet.longname) + { + case 'Phaser.GameObjects.Components.Alpha': + case 'Phaser.GameObjects.Components.AlphaSingle': + case 'Phaser.GameObjects.Components.Animation': + case 'Phaser.GameObjects.Components.BlendMode': + case 'Phaser.GameObjects.Components.ComputedSize': + case 'Phaser.GameObjects.Components.Crop': + case 'Phaser.GameObjects.Components.Depth': + case 'Phaser.GameObjects.Components.Flip': + case 'Phaser.GameObjects.Components.GetBounds': + case 'Phaser.GameObjects.Components.Mask': + case 'Phaser.GameObjects.Components.Origin': + case 'Phaser.GameObjects.Components.PathFollower': + case 'Phaser.GameObjects.Components.Pipeline': + case 'Phaser.GameObjects.Components.ScrollFactor': + case 'Phaser.GameObjects.Components.Size': + case 'Phaser.GameObjects.Components.Texture': + case 'Phaser.GameObjects.Components.TextureCrop': + case 'Phaser.GameObjects.Components.Tint': + case 'Phaser.GameObjects.Components.ToJSON': + case 'Phaser.GameObjects.Components.Transform': + case 'Phaser.GameObjects.Components.Visible': + case 'Phaser.Renderer.WebGL.Pipelines.ModelViewProjection': + doclet.kind = 'mixin'; + break; + + // Because, sod you TypeScript + case 'Phaser.BlendModes': + case 'Phaser.ScaleModes': + case 'Phaser.Physics.Impact.TYPE': + case 'Phaser.Physics.Impact.COLLIDES': + case 'Phaser.Scale.Center': + case 'Phaser.Scale.Orientation': + case 'Phaser.Scale.ScaleModes': + case 'Phaser.Scale.Zoom': + case 'Phaser.Textures.FilterMode': + // console.log('Forcing enum for ' + doclet.longname); + doclet.kind = 'member'; + doclet.isEnum = true; + break; + } + + if ((doclet.longname.indexOf('Phaser.Physics.Arcade.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Impact.Components.') == 0 || doclet.longname.indexOf('Phaser.Physics.Matter.Components.') == 0) && doclet.longname.indexOf('#') == -1) + { + doclet.kind = 'mixin'; + } + + let obj: dom.DeclarationBase; + let container = this.objects; + + switch (doclet.kind) { + case 'namespace': + obj = this.createNamespace(doclet); + container = this.namespaces; + break; + case 'class': + obj = this.createClass(doclet); + break; + case 'mixin': + obj = this.createInterface(doclet); + break; + case 'member': + if (doclet.isEnum === true) { + obj = this.createEnum(doclet); + break; + } + case 'constant': + obj = this.createMember(doclet); + break; + case 'function': + obj = this.createFunction(doclet); + break; + case 'typedef': + obj = this.createTypedef(doclet); + break; + case 'event': + obj = this.createEvent(doclet); + break; + default: + console.log('Ignored doclet kind: ' + doclet.kind); + break; + } + + if (obj) { + if (container[doclet.longname]) { + console.log('Warning: ignoring duplicate doc name: ' + doclet.longname); + docs.splice(i--, 1); + continue; + } + container[doclet.longname] = obj; + if (doclet.description) { + let otherDocs = obj.jsDocComment || ''; + obj.jsDocComment = doclet.description.replace(regexEndLine, '$1\n') + otherDocs; + } + } + } + } + + private resolveObjects(docs: any[]) { + let allTypes = new Set(); + for (let doclet of docs) { + let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; + + if (!obj) { + + // TODO + console.log(`Warning: Didn't find object for ${doclet.longname}`); + + continue; + } + + if (!doclet.memberof) { + this.topLevel.push(obj as dom.TopLevelDeclaration); + } else { + let isNamespaceMember = doclet.kind === 'class' || doclet.kind === 'typedef' || doclet.kind == 'namespace' || doclet.isEnum; + let parent = isNamespaceMember ? this.namespaces[doclet.memberof] : (this.objects[doclet.memberof] || this.namespaces[doclet.memberof]); + + //TODO: this whole section should be removed once stable + if (!parent) { + console.log(`${doclet.longname} in ${doclet.meta.filename}@${doclet.meta.lineno} has parent '${doclet.memberof}' that is not defined.`); + let parts: string[] = doclet.memberof.split('.'); + let newParts = [parts.pop()]; + while (parts.length > 0 && this.objects[parts.join('.')] == null) newParts.unshift(parts.pop()); + parent = this.objects[parts.join('.')] as dom.NamespaceDeclaration; + if (parent == null) { + parent = dom.create.namespace(doclet.memberof); + this.namespaces[doclet.memberof] = parent; + this.topLevel.push(parent); + } else { + while (newParts.length > 0) { + let oldParent = parent; + parent = dom.create.namespace(newParts.shift()); + parts.push((parent).name); + this.namespaces[parts.join('.')] = parent; + oldParent.members.push(parent); + (parent)._parent = oldParent; + } + } + } + /////////////////////////////////////////////////////// + + if ((parent).members) { + (parent).members.push(obj); + } else { + console.log('Cannot find members array for:'); + console.log(parent); + } + + (obj)._parent = parent; + + // class/interface members have methods, not functions + if (((parent as any).kind === 'class' || (parent as any).kind === 'interface') + && (obj as any).kind === 'function') + (obj as any).kind = 'method'; + // namespace members are vars or consts, not properties + if ((parent as any).kind === 'namespace' && (obj as any).kind === 'property') { + if (doclet.kind == 'constant') (obj as any).kind = 'const'; + else (obj as any).kind = 'var'; + } + } + } + } + + private resolveInheritance(docs: any[]) { + for (let doclet of docs) { + let obj = doclet.kind === 'namespace' ? this.namespaces[doclet.longname] : this.objects[doclet.longname]; + if (!obj) { + + // TODO + console.log(`Didn't find type ${doclet.longname} ???`); + + continue; + } + if (!(obj)._parent) continue; + + if (doclet.inherited) {// remove inherited members if they aren't from an interface + let from = this.objects[doclet.inherits]; + if (!from || !(from)._parent) + throw `'${doclet.longname}' should inherit from '${doclet.inherits}', which is not defined.`; + + if ((from)._parent.kind != 'interface') { + (obj)._parent.members.splice((obj)._parent.members.indexOf(obj), 1); + (obj)._parent = null; + } + } + } + } + + private resolveParents(docs: any[]) { + for (let doclet of docs) { + let obj = this.objects[doclet.longname]; + if (!obj || doclet.kind !== 'class') continue; + + let o = obj as dom.ClassDeclaration; + + // resolve augments + if (doclet.augments && doclet.augments.length) { + for (let augment of doclet.augments) { + let name: string = this.prepareTypeName(augment); + + let wrappingName = name.match(/[^<]+/s)[0];//gets everything up to a first < (to handle augments with type parameters) + + let baseType = this.objects[wrappingName] as dom.ClassDeclaration | dom.InterfaceDeclaration; + + if (!baseType) { + console.log(`ERROR: Did not find base type: ${augment} for ${doclet.longname}`); + } else { + if (baseType.kind == 'class') { + o.baseType = dom.create.class(name); + } else { + o.implements.push(dom.create.interface(name)); + } + } + } + } + } + } + + private createNamespace(doclet: any): dom.NamespaceDeclaration { + + /** + namespace: { comment: '', + meta: + { filename: 'index.js', + lineno: 10, + columnno: 0, + path: '/Users/rich/Documents/GitHub/phaser/src/tweens', + code: {} }, + kind: 'namespace', + name: 'Tweens', + memberof: 'Phaser', + longname: 'Phaser.Tweens', + scope: 'static', + ___id: 'T000002R034468', + ___s: true } + */ + + // console.log('namespace:', doclet.longname); + + let obj = dom.create.namespace(doclet.name); + + return obj; + } + + private createClass(doclet: any): dom.ClassDeclaration { + let obj = dom.create.class(doclet.name); + + let params = null; + if (doclet.params) { + let ctor = dom.create.constructor(null); + this.setParams(doclet, ctor); + params = ctor.parameters; + + obj.members.push(ctor); + (ctor)._parent = obj; + } + + this.processGeneric(doclet, obj, params); + + if (doclet.classdesc) + doclet.description = doclet.classdesc.replace(regexEndLine, '$1\n'); // make sure docs will be added + + return obj; + } + + private createInterface(doclet: any): dom.InterfaceDeclaration { + return dom.create.interface(doclet.name); + } + + private createMember(doclet: any): dom.PropertyDeclaration { + let type = this.parseType(doclet); + + let obj = dom.create.property(doclet.name, type); + + this.processGeneric(doclet, obj, null); + + this.processFlags(doclet, obj); + + return obj; + } + + private createEvent(doclet: any): dom.ConstDeclaration { + + let type = this.parseType(doclet); + + let obj = dom.create.const(doclet.name, type); + + this.processFlags(doclet, obj); + + return obj; + } + + private createEnum(doclet: any): dom.EnumDeclaration { + let obj = dom.create.enum(doclet.name, false); + + this.processFlags(doclet, obj); + + return obj; + } + + private createFunction(doclet: any): dom.FunctionDeclaration { + let returnType: dom.Type = dom.type.void; + + if (doclet.returns) { + returnType = this.parseType(doclet.returns[0]); + } + + let obj = dom.create.function(doclet.name, null, returnType); + this.setParams(doclet, obj); + + this.processGeneric(doclet, obj, obj.parameters); + + this.processFlags(doclet, obj); + + return obj; + } + + private createTypedef(doclet: any): dom.TypeAliasDeclaration { + const typeName = doclet.type.names[0]; + let type = null; + + if (doclet.type.names[0] === 'object') { + let properties = []; + + for (let propDoc of doclet.properties) { + let prop = this.createMember(propDoc); + properties.push(prop); + if (propDoc.description) + prop.jsDocComment = propDoc.description.replace(regexEndLine, '$1\n'); + } + + type = dom.create.objectType(properties); + + if (doclet.augments && doclet.augments.length) { + let intersectionTypes = []; + for (let i = 0; i < doclet.augments.length; i++) { + intersectionTypes.push(dom.create.namedTypeReference(doclet.augments[i])); + } + intersectionTypes.push(type); + type = dom.create.intersection(intersectionTypes); + } + + } else { + if (doclet.type.names[0] == "function") { + type = dom.create.functionType(null, dom.type.void); + this.setParams(doclet, type); + } else { + type = this.parseType(doclet); + } + } + + let alias = dom.create.alias(doclet.name, type); + + this.processGeneric(doclet, alias, null); + + return alias; + } + + private setParams(doclet: any, obj: dom.FunctionDeclaration | dom.ConstructorDeclaration): void { + let parameters: dom.Parameter[] = []; + + if (doclet.params) { + + let optional = false; + + obj.jsDocComment = ''; + + for (let paramDoc of doclet.params) { + + // TODO REMOVE TEMP FIX + if (paramDoc.name.indexOf('.') != -1) { + console.log(`Warning: ignoring param with '.' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); + + let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; + if (paramDoc.description) + obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; + else if (defaultVal.length) + obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; + continue; + } + /////////////////////// + + let param = dom.create.parameter(paramDoc.name, this.parseType(paramDoc)); + parameters.push(param); + + if (optional && paramDoc.optional != true) { + console.log(`Warning: correcting to optional: parameter '${paramDoc.name}' for '${doclet.longname}' in ${doclet.meta.filename}@${doclet.meta.lineno}`); + paramDoc.optional = true; + } + + this.processFlags(paramDoc, param); + + optional = optional || paramDoc.optional === true; + + let defaultVal = paramDoc.defaultvalue !== undefined ? ` Default ${String(paramDoc.defaultvalue)}.` : ''; + + if (paramDoc.description) + obj.jsDocComment += `\n@param ${paramDoc.name} ${paramDoc.description.replace(regexEndLine, '$1\n')}` + defaultVal; + else if (defaultVal.length) + obj.jsDocComment += `\n@param ${paramDoc.name} ` + defaultVal; + } + } + + obj.parameters = parameters; + } + + private parseType(typeDoc: any): dom.Type { + if (!typeDoc || !typeDoc.type) { + return dom.type.any; + } else { + let types = []; + for (let name of typeDoc.type.names) { + + name = this.prepareTypeName(name); + + let type = dom.create.namedTypeReference(this.processTypeName(name)); + + types.push(type); + } + if (types.length == 1) return types[0]; + else return dom.create.union(types); + } + } + + private prepareTypeName(name: string): string { + if (name.indexOf('*') != -1) { + name = (name).split('*').join('any'); + } + if (name.indexOf('.<') != -1 && name !== 'Array.') { + name = (name).split('.<').join('<'); + } + return name; + } + + private processTypeName(name: string): string { + if (name === 'float') return 'number'; + if (name === 'function') return 'Function'; + if (name === 'Array.') return 'Function[]'; + if (name === 'array') return 'any[]'; + + if (name.startsWith('Array<')) { + let matches = name.match(/^Array<(.*)>$/); + + if (matches && matches[1]) { + return this.processTypeName(matches[1]) + '[]'; + } + } else if (name.startsWith('Object<')) { + let matches = name.match(/^Object<(.*)>$/); + + if (matches && matches[1]) { + if (matches[1].indexOf(',') != -1) { + let parts = matches[1].split(','); + return `{[key: ${this.processTypeName(parts[0])}]: ${this.processTypeName(parts[1])}}`; + } else { + return `{[key: string]: ${this.processTypeName(matches[1])}}`; + } + } + } + + return name; + } + + private processFlags(doclet: any, obj: dom.DeclarationBase | dom.Parameter) { + obj.flags = dom.DeclarationFlags.None; + if (doclet.variable === true) { + obj.flags |= dom.ParameterFlags.Rest; + let type: any = (obj).type; + if (!type.name.endsWith('[]')) { + if (type.name != 'any') + console.log(`Warning: rest parameter should be an array type for ${doclet.longname}`); + type.name = type.name + '[]'; // Must be an array + } + } else if (doclet.optional === true) {// Rest implies Optional – no need to flag it as such + if (obj['kind'] === 'parameter') obj.flags |= dom.ParameterFlags.Optional; + else obj.flags |= dom.DeclarationFlags.Optional; + } + switch (doclet.access) { + case 'protected': + obj.flags |= dom.DeclarationFlags.Protected; + break; + case 'private': + obj.flags |= dom.DeclarationFlags.Private; + break; + } + if (doclet.readonly || doclet.kind === 'constant') obj.flags |= dom.DeclarationFlags.ReadOnly; + if (doclet.scope === 'static') obj.flags |= dom.DeclarationFlags.Static; + } + + private processGeneric(doclet: any, obj: dom.ClassDeclaration | dom.FunctionDeclaration | dom.PropertyDeclaration | dom.TypeAliasDeclaration, params: dom.Parameter[]) { + if (doclet.tags) + for (let tag of doclet.tags) { + if (tag.originalTitle === 'generic') { + + /** + * {string} K - [key] + * 1 = string | 2 = null | 3 = K | 4 = key + * + * {string=string} K - [key] + * 1 = string | 2 = string | 3 = K | 4 = key + */ + const matches = (tag.value).match(/(?:(?:{)([^}=]+)(?:=)?([^}=]+)?(?:}))?\s?([^\s]+)(?:\s?-\s?(?:\[)(.+)(?:\]))?/); + const [_, _type, _defaultType, _name, _paramsNames] = matches; + + const typeParam = dom.create.typeParameter( + _name, + _type == null ? null : dom.create.typeParameter(_type) + ); + + if(_defaultType != null) { + typeParam.defaultType = dom.create.typeParameter(_defaultType); + } + + (obj).typeParameters.push(typeParam); + handleOverrides(_paramsNames, _name); + + } else if (tag.originalTitle === 'genericUse') { + let matches = (tag.value).match(/(?:(?:{)([^}]+)(?:}))(?:\s?-\s?(?:\[)(.+)(?:\]))?/); + let overrideType: string = this.prepareTypeName(matches[1]); + + handleOverrides(matches[2], this.processTypeName(overrideType)); + } + } + + function handleOverrides(matchedString: string, overrideType: string) { + if (matchedString != null) { + let overrides = matchedString.split(','); + if (params != null) { + for (let param of params) { + if (overrides.indexOf(param.name) != -1) { + param.type = dom.create.namedTypeReference(overrideType); + } + } + } + if (overrides.indexOf('$return') != -1) {// has $return, must be a function + (obj).returnType = dom.create.namedTypeReference(overrideType); + } + if (overrides.indexOf('$type') != -1) {// has $type, must be a property + (obj).type = dom.create.namedTypeReference(overrideType); + } + } + } + } + +} diff --git a/src/actions/AlignTo.js b/src/actions/AlignTo.js index 088679357..6faba213b 100644 --- a/src/actions/AlignTo.js +++ b/src/actions/AlignTo.js @@ -1,42 +1,42 @@ -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var QuickSet = require('../display/align/to/QuickSet'); - -/** - * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. - * - * The first item isn't moved. The second item is aligned next to the first, then the third next to the second, and so on. - * - * @function Phaser.Actions.AlignTo - * @since 3.22.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 {integer} position - The position to align the items with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. - * @param {number} [offsetX=0] - Optional horizontal offset from the position. - * @param {number} [offsetY=0] - Optional vertical offset from the position. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var AlignTo = function (items, position, offsetX, offsetY) -{ - var target = items[0]; - - for (var i = 1; i < items.length; i++) - { - var item = items[i]; - - QuickSet(item, target, position, offsetX, offsetY); - - target = item; - } - - return items; -}; - -module.exports = AlignTo; +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var QuickSet = require('../display/align/to/QuickSet'); + +/** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. + * + * The first item isn't moved. The second item is aligned next to the first, then the third next to the second, and so on. + * + * @function Phaser.Actions.AlignTo + * @since 3.22.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 {integer} position - The position to align the items with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. + * @param {number} [offsetX=0] - Optional horizontal offset from the position. + * @param {number} [offsetY=0] - Optional vertical offset from the position. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var AlignTo = function (items, position, offsetX, offsetY) +{ + var target = items[0]; + + for (var i = 1; i < items.length; i++) + { + var item = items[i]; + + QuickSet(item, target, position, offsetX, offsetY); + + target = item; + } + + return items; +}; + +module.exports = AlignTo; diff --git a/src/actions/Angle.js b/src/actions/Angle.js index 65601e693..1c60e303c 100644 --- a/src/actions/Angle.js +++ b/src/actions/Angle.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `angle` property, - * and then adds the given value to each of their `angle` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `Angle(group.getChildren(), value, step)` - * - * @function Phaser.Actions.Angle - * @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 {number} value - The amount to be added to the `angle` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var Angle = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'angle', value, step, index, direction); -}; - -module.exports = Angle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `angle` property, + * and then adds the given value to each of their `angle` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `Angle(group.getChildren(), value, step)` + * + * @function Phaser.Actions.Angle + * @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 {number} value - The amount to be added to the `angle` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var Angle = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'angle', value, step, index, direction); +}; + +module.exports = Angle; diff --git a/src/actions/Call.js b/src/actions/Call.js index 403bdc150..f916f9589 100644 --- a/src/actions/Call.js +++ b/src/actions/Call.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of objects and passes each of them to the given callback. - * - * @function Phaser.Actions.Call - * @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.CallCallback} callback - The callback to be invoked. It will be passed just one argument: the item from the array. - * @param {*} context - The scope in which the callback will be invoked. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that was passed to this Action. - */ -var Call = function (items, callback, context) -{ - for (var i = 0; i < items.length; i++) - { - var item = items[i]; - - callback.call(context, item); - } - - return items; -}; - -module.exports = Call; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of objects and passes each of them to the given callback. + * + * @function Phaser.Actions.Call + * @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.CallCallback} callback - The callback to be invoked. It will be passed just one argument: the item from the array. + * @param {*} context - The scope in which the callback will be invoked. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that was passed to this Action. + */ +var Call = function (items, callback, context) +{ + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + + callback.call(context, item); + } + + return items; +}; + +module.exports = Call; diff --git a/src/actions/GetFirst.js b/src/actions/GetFirst.js index 65c632fc1..daa60f54f 100644 --- a/src/actions/GetFirst.js +++ b/src/actions/GetFirst.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of objects and returns the first element in the array that has properties which match - * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` - * then it would return the first item which had the property `scaleX` set to 0.5 and `alpha` set to 1. - * - * To use this with a Group: `GetFirst(group.getChildren(), compare, index)` - * - * @function Phaser.Actions.GetFirst - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject[]} G - [items] - * - * @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be searched by this action. - * @param {object} compare - The comparison object. Each property in this object will be checked against the items of the array. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * - * @return {?(object|Phaser.GameObjects.GameObject)} The first object in the array that matches the comparison object, or `null` if no match was found. - */ -var GetFirst = function (items, compare, index) -{ - if (index === undefined) { index = 0; } - - for (var i = index; i < items.length; i++) - { - var item = items[i]; - - var match = true; - - for (var property in compare) - { - if (item[property] !== compare[property]) - { - match = false; - } - } - - if (match) - { - return item; - } - } - - return null; -}; - -module.exports = GetFirst; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of objects and returns the first element in the array that has properties which match + * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` + * then it would return the first item which had the property `scaleX` set to 0.5 and `alpha` set to 1. + * + * To use this with a Group: `GetFirst(group.getChildren(), compare, index)` + * + * @function Phaser.Actions.GetFirst + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items] + * + * @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be searched by this action. + * @param {object} compare - The comparison object. Each property in this object will be checked against the items of the array. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * + * @return {?(object|Phaser.GameObjects.GameObject)} The first object in the array that matches the comparison object, or `null` if no match was found. + */ +var GetFirst = function (items, compare, index) +{ + if (index === undefined) { index = 0; } + + for (var i = index; i < items.length; i++) + { + var item = items[i]; + + var match = true; + + for (var property in compare) + { + if (item[property] !== compare[property]) + { + match = false; + } + } + + if (match) + { + return item; + } + } + + return null; +}; + +module.exports = GetFirst; diff --git a/src/actions/GetLast.js b/src/actions/GetLast.js index 4de1e6e1d..57b6ccaa3 100644 --- a/src/actions/GetLast.js +++ b/src/actions/GetLast.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of objects and returns the last element in the array that has properties which match - * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` - * then it would return the last item which had the property `scaleX` set to 0.5 and `alpha` set to 1. - * - * To use this with a Group: `GetLast(group.getChildren(), compare, index)` - * - * @function Phaser.Actions.GetLast - * @since 3.3.0 - * - * @generic {Phaser.GameObjects.GameObject[]} G - [items] - * - * @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be searched by this action. - * @param {object} compare - The comparison object. Each property in this object will be checked against the items of the array. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * - * @return {?(object|Phaser.GameObjects.GameObject)} The last object in the array that matches the comparison object, or `null` if no match was found. - */ -var GetLast = function (items, compare, index) -{ - if (index === undefined) { index = 0; } - - for (var i = index; i < items.length; i++) - { - var item = items[i]; - - var match = true; - - for (var property in compare) - { - if (item[property] !== compare[property]) - { - match = false; - } - } - - if (match) - { - return item; - } - } - - return null; -}; - -module.exports = GetLast; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of objects and returns the last element in the array that has properties which match + * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` + * then it would return the last item which had the property `scaleX` set to 0.5 and `alpha` set to 1. + * + * To use this with a Group: `GetLast(group.getChildren(), compare, index)` + * + * @function Phaser.Actions.GetLast + * @since 3.3.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items] + * + * @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be searched by this action. + * @param {object} compare - The comparison object. Each property in this object will be checked against the items of the array. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * + * @return {?(object|Phaser.GameObjects.GameObject)} The last object in the array that matches the comparison object, or `null` if no match was found. + */ +var GetLast = function (items, compare, index) +{ + if (index === undefined) { index = 0; } + + for (var i = index; i < items.length; i++) + { + var item = items[i]; + + var match = true; + + for (var property in compare) + { + if (item[property] !== compare[property]) + { + match = false; + } + } + + if (match) + { + return item; + } + } + + return null; +}; + +module.exports = GetLast; diff --git a/src/actions/GridAlign.js b/src/actions/GridAlign.js index c7aa00ffd..fe499cfce 100644 --- a/src/actions/GridAlign.js +++ b/src/actions/GridAlign.js @@ -1,93 +1,93 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AlignIn = require('../display/align/in/QuickSet'); -var CONST = require('../display/align/const'); -var GetFastValue = require('../utils/object/GetFastValue'); -var NOOP = require('../utils/NOOP'); -var Zone = require('../gameobjects/zone/Zone'); - -var tempZone = new Zone({ sys: { queueDepthSort: NOOP, events: { once: NOOP } } }, 0, 0, 1, 1); - -/** - * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, - * and then aligns them based on the grid configuration given to this action. - * - * @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. - */ -var GridAlign = function (items, options) -{ - if (options === undefined) { options = {}; } - - var widthSet = options.hasOwnProperty('width'); - var heightSet = options.hasOwnProperty('height'); - - var width = GetFastValue(options, 'width', -1); - var height = GetFastValue(options, 'height', -1); - - var cellWidth = GetFastValue(options, 'cellWidth', 1); - var cellHeight = GetFastValue(options, 'cellHeight', cellWidth); - - var position = GetFastValue(options, 'position', CONST.TOP_LEFT); - var x = GetFastValue(options, 'x', 0); - var y = GetFastValue(options, 'y', 0); - - var cx = 0; - var cy = 0; - var w = (width * cellWidth); - var h = (height * cellHeight); - - tempZone.setPosition(x, y); - tempZone.setSize(cellWidth, cellHeight); - - for (var i = 0; i < items.length; i++) - { - AlignIn(items[i], tempZone, position); - - if (widthSet && width === -1) - { - // We keep laying them out horizontally until we've done them all - tempZone.x += cellWidth; - } - else if (heightSet && height === -1) - { - // We keep laying them out vertically until we've done them all - tempZone.y += cellHeight; - } - else - { - // We keep laying them out until we hit the column limit - cx += cellWidth; - tempZone.x += cellWidth; - - if (cx === w) - { - cx = 0; - cy += cellHeight; - tempZone.x = x; - tempZone.y += cellHeight; - - if (cy === h) - { - // We've hit the column limit, so return, even if there are items left - break; - } - } - } - } - - return items; -}; - -module.exports = GridAlign; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AlignIn = require('../display/align/in/QuickSet'); +var CONST = require('../display/align/const'); +var GetFastValue = require('../utils/object/GetFastValue'); +var NOOP = require('../utils/NOOP'); +var Zone = require('../gameobjects/zone/Zone'); + +var tempZone = new Zone({ sys: { queueDepthSort: NOOP, events: { once: NOOP } } }, 0, 0, 1, 1); + +/** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, + * and then aligns them based on the grid configuration given to this action. + * + * @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. + */ +var GridAlign = function (items, options) +{ + if (options === undefined) { options = {}; } + + var widthSet = options.hasOwnProperty('width'); + var heightSet = options.hasOwnProperty('height'); + + var width = GetFastValue(options, 'width', -1); + var height = GetFastValue(options, 'height', -1); + + var cellWidth = GetFastValue(options, 'cellWidth', 1); + var cellHeight = GetFastValue(options, 'cellHeight', cellWidth); + + var position = GetFastValue(options, 'position', CONST.TOP_LEFT); + var x = GetFastValue(options, 'x', 0); + var y = GetFastValue(options, 'y', 0); + + var cx = 0; + var cy = 0; + var w = (width * cellWidth); + var h = (height * cellHeight); + + tempZone.setPosition(x, y); + tempZone.setSize(cellWidth, cellHeight); + + for (var i = 0; i < items.length; i++) + { + AlignIn(items[i], tempZone, position); + + if (widthSet && width === -1) + { + // We keep laying them out horizontally until we've done them all + tempZone.x += cellWidth; + } + else if (heightSet && height === -1) + { + // We keep laying them out vertically until we've done them all + tempZone.y += cellHeight; + } + else + { + // We keep laying them out until we hit the column limit + cx += cellWidth; + tempZone.x += cellWidth; + + if (cx === w) + { + cx = 0; + cy += cellHeight; + tempZone.x = x; + tempZone.y += cellHeight; + + if (cy === h) + { + // We've hit the column limit, so return, even if there are items left + break; + } + } + } + } + + return items; +}; + +module.exports = GridAlign; diff --git a/src/actions/IncAlpha.js b/src/actions/IncAlpha.js index c391f45fc..92e0a0348 100644 --- a/src/actions/IncAlpha.js +++ b/src/actions/IncAlpha.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `alpha` property, - * and then adds the given value to each of their `alpha` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncAlpha(group.getChildren(), value, step)` - * - * @function Phaser.Actions.IncAlpha - * @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 {number} value - The amount to be added to the `alpha` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var IncAlpha = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'alpha', value, step, index, direction); -}; - -module.exports = IncAlpha; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `alpha` property, + * and then adds the given value to each of their `alpha` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncAlpha(group.getChildren(), value, step)` + * + * @function Phaser.Actions.IncAlpha + * @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 {number} value - The amount to be added to the `alpha` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncAlpha = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'alpha', value, step, index, direction); +}; + +module.exports = IncAlpha; diff --git a/src/actions/IncX.js b/src/actions/IncX.js index 3ded566a8..75a87e77a 100644 --- a/src/actions/IncX.js +++ b/src/actions/IncX.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `x` property, - * and then adds the given value to each of their `x` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncX(group.getChildren(), value, step)` - * - * @function Phaser.Actions.IncX - * @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 {number} value - The amount to be added to the `x` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var IncX = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'x', value, step, index, direction); -}; - -module.exports = IncX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `x` property, + * and then adds the given value to each of their `x` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.IncX + * @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 {number} value - The amount to be added to the `x` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncX = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'x', value, step, index, direction); +}; + +module.exports = IncX; diff --git a/src/actions/IncXY.js b/src/actions/IncXY.js index 1174cf227..d229a36ae 100644 --- a/src/actions/IncXY.js +++ b/src/actions/IncXY.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, - * and then adds the given value to each of them. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncXY(group.getChildren(), x, y, stepX, stepY)` - * - * @function Phaser.Actions.IncXY - * @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 {number} x - The amount to be added to the `x` property. - * @param {number} [y=x] - The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. - * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var IncXY = function (items, x, y, stepX, stepY, index, direction) -{ - if (y === undefined || y === null) { y = x; } - - PropertyValueInc(items, 'x', x, stepX, index, direction); - - return PropertyValueInc(items, 'y', y, stepY, index, direction); -}; - -module.exports = IncXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, + * and then adds the given value to each of them. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncXY(group.getChildren(), x, y, stepX, stepY)` + * + * @function Phaser.Actions.IncXY + * @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 {number} x - The amount to be added to the `x` property. + * @param {number} [y=x] - The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncXY = function (items, x, y, stepX, stepY, index, direction) +{ + if (y === undefined || y === null) { y = x; } + + PropertyValueInc(items, 'x', x, stepX, index, direction); + + return PropertyValueInc(items, 'y', y, stepY, index, direction); +}; + +module.exports = IncXY; diff --git a/src/actions/IncY.js b/src/actions/IncY.js index 3f7af5ffe..53d91fb2e 100644 --- a/src/actions/IncY.js +++ b/src/actions/IncY.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `y` property, - * and then adds the given value to each of their `y` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncY(group.getChildren(), value, step)` - * - * @function Phaser.Actions.IncY - * @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 {number} value - The amount to be added to the `y` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var IncY = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'y', value, step, index, direction); -}; - -module.exports = IncY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `y` property, + * and then adds the given value to each of their `y` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.IncY + * @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 {number} value - The amount to be added to the `y` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var IncY = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'y', value, step, index, direction); +}; + +module.exports = IncY; diff --git a/src/actions/PlaceOnCircle.js b/src/actions/PlaceOnCircle.js index 687dad837..37150a5f8 100644 --- a/src/actions/PlaceOnCircle.js +++ b/src/actions/PlaceOnCircle.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Circle. - * - * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.PlaceOnCircle - * @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.Geom.Circle} circle - The Circle to position the Game Objects on. - * @param {number} [startAngle=0] - Optional angle to start position from, in radians. - * @param {number} [endAngle=6.28] - Optional angle to stop position at, in radians. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var PlaceOnCircle = function (items, circle, startAngle, endAngle) -{ - if (startAngle === undefined) { startAngle = 0; } - if (endAngle === undefined) { endAngle = 6.28; } - - var angle = startAngle; - var angleStep = (endAngle - startAngle) / items.length; - - for (var i = 0; i < items.length; i++) - { - items[i].x = circle.x + (circle.radius * Math.cos(angle)); - items[i].y = circle.y + (circle.radius * Math.sin(angle)); - - angle += angleStep; - } - - return items; -}; - -module.exports = PlaceOnCircle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Circle. + * + * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.PlaceOnCircle + * @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.Geom.Circle} circle - The Circle to position the Game Objects on. + * @param {number} [startAngle=0] - Optional angle to start position from, in radians. + * @param {number} [endAngle=6.28] - Optional angle to stop position at, in radians. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnCircle = function (items, circle, startAngle, endAngle) +{ + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 6.28; } + + var angle = startAngle; + var angleStep = (endAngle - startAngle) / items.length; + + for (var i = 0; i < items.length; i++) + { + items[i].x = circle.x + (circle.radius * Math.cos(angle)); + items[i].y = circle.y + (circle.radius * Math.sin(angle)); + + angle += angleStep; + } + + return items; +}; + +module.exports = PlaceOnCircle; diff --git a/src/actions/PlaceOnEllipse.js b/src/actions/PlaceOnEllipse.js index 0d5e49206..28a690c3c 100644 --- a/src/actions/PlaceOnEllipse.js +++ b/src/actions/PlaceOnEllipse.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of an Ellipse. - * - * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.PlaceOnEllipse - * @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.Geom.Ellipse} ellipse - The Ellipse to position the Game Objects on. - * @param {number} [startAngle=0] - Optional angle to start position from, in radians. - * @param {number} [endAngle=6.28] - Optional angle to stop position at, in radians. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var PlaceOnEllipse = function (items, ellipse, startAngle, endAngle) -{ - if (startAngle === undefined) { startAngle = 0; } - if (endAngle === undefined) { endAngle = 6.28; } - - var angle = startAngle; - var angleStep = (endAngle - startAngle) / items.length; - - var a = ellipse.width / 2; - var b = ellipse.height / 2; - - for (var i = 0; i < items.length; i++) - { - items[i].x = ellipse.x + a * Math.cos(angle); - items[i].y = ellipse.y + b * Math.sin(angle); - - angle += angleStep; - } - - return items; -}; - -module.exports = PlaceOnEllipse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of an Ellipse. + * + * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.PlaceOnEllipse + * @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.Geom.Ellipse} ellipse - The Ellipse to position the Game Objects on. + * @param {number} [startAngle=0] - Optional angle to start position from, in radians. + * @param {number} [endAngle=6.28] - Optional angle to stop position at, in radians. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnEllipse = function (items, ellipse, startAngle, endAngle) +{ + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 6.28; } + + var angle = startAngle; + var angleStep = (endAngle - startAngle) / items.length; + + var a = ellipse.width / 2; + var b = ellipse.height / 2; + + for (var i = 0; i < items.length; i++) + { + items[i].x = ellipse.x + a * Math.cos(angle); + items[i].y = ellipse.y + b * Math.sin(angle); + + angle += angleStep; + } + + return items; +}; + +module.exports = PlaceOnEllipse; diff --git a/src/actions/PlaceOnLine.js b/src/actions/PlaceOnLine.js index 025cc2e45..c5597f2c6 100644 --- a/src/actions/PlaceOnLine.js +++ b/src/actions/PlaceOnLine.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetPoints = require('../geom/line/GetPoints'); - -/** - * Positions an array of Game Objects on evenly spaced points of a Line. - * - * @function Phaser.Actions.PlaceOnLine - * @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.Geom.Line} line - The Line to position the Game Objects on. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var PlaceOnLine = function (items, line) -{ - var points = GetPoints(line, items.length); - - for (var i = 0; i < items.length; i++) - { - var item = items[i]; - var point = points[i]; - - item.x = point.x; - item.y = point.y; - } - - return items; -}; - -module.exports = PlaceOnLine; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetPoints = require('../geom/line/GetPoints'); + +/** + * Positions an array of Game Objects on evenly spaced points of a Line. + * + * @function Phaser.Actions.PlaceOnLine + * @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.Geom.Line} line - The Line to position the Game Objects on. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnLine = function (items, line) +{ + var points = GetPoints(line, items.length); + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + var point = points[i]; + + item.x = point.x; + item.y = point.y; + } + + return items; +}; + +module.exports = PlaceOnLine; diff --git a/src/actions/PlaceOnRectangle.js b/src/actions/PlaceOnRectangle.js index c70de95a2..4ed91d85c 100644 --- a/src/actions/PlaceOnRectangle.js +++ b/src/actions/PlaceOnRectangle.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MarchingAnts = require('../geom/rectangle/MarchingAnts'); -var RotateLeft = require('../utils/array/RotateLeft'); -var RotateRight = require('../utils/array/RotateRight'); - -/** - * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. - * - * Placement starts from the top-left of the rectangle, and proceeds in a clockwise direction. - * If the `shift` parameter is given you can offset where placement begins. - * - * @function Phaser.Actions.PlaceOnRectangle - * @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.Geom.Rectangle} rect - The Rectangle to position the Game Objects on. - * @param {integer} [shift=1] - An optional positional offset. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var PlaceOnRectangle = function (items, rect, shift) -{ - if (shift === undefined) { shift = 0; } - - var points = MarchingAnts(rect, false, items.length); - - if (shift > 0) - { - RotateLeft(points, shift); - } - else if (shift < 0) - { - RotateRight(points, Math.abs(shift)); - } - - for (var i = 0; i < items.length; i++) - { - items[i].x = points[i].x; - items[i].y = points[i].y; - } - - return items; -}; - -module.exports = PlaceOnRectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MarchingAnts = require('../geom/rectangle/MarchingAnts'); +var RotateLeft = require('../utils/array/RotateLeft'); +var RotateRight = require('../utils/array/RotateRight'); + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. + * + * Placement starts from the top-left of the rectangle, and proceeds in a clockwise direction. + * If the `shift` parameter is given you can offset where placement begins. + * + * @function Phaser.Actions.PlaceOnRectangle + * @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.Geom.Rectangle} rect - The Rectangle to position the Game Objects on. + * @param {integer} [shift=1] - An optional positional offset. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnRectangle = function (items, rect, shift) +{ + if (shift === undefined) { shift = 0; } + + var points = MarchingAnts(rect, false, items.length); + + if (shift > 0) + { + RotateLeft(points, shift); + } + else if (shift < 0) + { + RotateRight(points, Math.abs(shift)); + } + + for (var i = 0; i < items.length; i++) + { + items[i].x = points[i].x; + items[i].y = points[i].y; + } + + return items; +}; + +module.exports = PlaceOnRectangle; diff --git a/src/actions/PlaceOnTriangle.js b/src/actions/PlaceOnTriangle.js index e935cddd0..a4a19cc3b 100644 --- a/src/actions/PlaceOnTriangle.js +++ b/src/actions/PlaceOnTriangle.js @@ -1,55 +1,55 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BresenhamPoints = require('../geom/line/BresenhamPoints'); - -/** - * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. - * - * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.PlaceOnTriangle - * @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.Geom.Triangle} triangle - The Triangle to position the Game Objects on. - * @param {number} [stepRate=1] - An optional step rate, to increase or decrease the packing of the Game Objects on the lines. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var PlaceOnTriangle = function (items, triangle, stepRate) -{ - var p1 = BresenhamPoints({ x1: triangle.x1, y1: triangle.y1, x2: triangle.x2, y2: triangle.y2 }, stepRate); - var p2 = BresenhamPoints({ x1: triangle.x2, y1: triangle.y2, x2: triangle.x3, y2: triangle.y3 }, stepRate); - var p3 = BresenhamPoints({ x1: triangle.x3, y1: triangle.y3, x2: triangle.x1, y2: triangle.y1 }, stepRate); - - // Remove overlaps - p1.pop(); - p2.pop(); - p3.pop(); - - p1 = p1.concat(p2, p3); - - var step = p1.length / items.length; - var p = 0; - - for (var i = 0; i < items.length; i++) - { - var item = items[i]; - var point = p1[Math.floor(p)]; - - item.x = point.x; - item.y = point.y; - - p += step; - } - - return items; -}; - -module.exports = PlaceOnTriangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BresenhamPoints = require('../geom/line/BresenhamPoints'); + +/** + * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. + * + * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.PlaceOnTriangle + * @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.Geom.Triangle} triangle - The Triangle to position the Game Objects on. + * @param {number} [stepRate=1] - An optional step rate, to increase or decrease the packing of the Game Objects on the lines. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlaceOnTriangle = function (items, triangle, stepRate) +{ + var p1 = BresenhamPoints({ x1: triangle.x1, y1: triangle.y1, x2: triangle.x2, y2: triangle.y2 }, stepRate); + var p2 = BresenhamPoints({ x1: triangle.x2, y1: triangle.y2, x2: triangle.x3, y2: triangle.y3 }, stepRate); + var p3 = BresenhamPoints({ x1: triangle.x3, y1: triangle.y3, x2: triangle.x1, y2: triangle.y1 }, stepRate); + + // Remove overlaps + p1.pop(); + p2.pop(); + p3.pop(); + + p1 = p1.concat(p2, p3); + + var step = p1.length / items.length; + var p = 0; + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + var point = p1[Math.floor(p)]; + + item.x = point.x; + item.y = point.y; + + p += step; + } + + return items; +}; + +module.exports = PlaceOnTriangle; diff --git a/src/actions/PlayAnimation.js b/src/actions/PlayAnimation.js index f708b19f1..cf56a2ec2 100644 --- a/src/actions/PlayAnimation.js +++ b/src/actions/PlayAnimation.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Play an animation with the given key, starting at the given startFrame on all Game Objects in items. - * - * @function Phaser.Actions.PlayAnimation - * @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} key - The name of the animation to play. - * @param {(string|integer)} [startFrame] - The starting frame of the animation with the given key. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var PlayAnimation = function (items, key, startFrame) -{ - for (var i = 0; i < items.length; i++) - { - items[i].anims.play(key, startFrame); - } - - return items; -}; - -module.exports = PlayAnimation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Play an animation with the given key, starting at the given startFrame on all Game Objects in items. + * + * @function Phaser.Actions.PlayAnimation + * @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} key - The name of the animation to play. + * @param {(string|integer)} [startFrame] - The starting frame of the animation with the given key. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var PlayAnimation = function (items, key, startFrame) +{ + for (var i = 0; i < items.length; i++) + { + items[i].anims.play(key, startFrame); + } + + return items; +}; + +module.exports = PlayAnimation; diff --git a/src/actions/PropertyValueInc.js b/src/actions/PropertyValueInc.js index 31de3db64..9a77e74f7 100644 --- a/src/actions/PropertyValueInc.js +++ b/src/actions/PropertyValueInc.js @@ -1,61 +1,61 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, - * and then adds the given value to it. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `PropertyValueInc(group.getChildren(), key, value, step)` - * - * @function Phaser.Actions.PropertyValueInc - * @since 3.3.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 {string} key - The property to be updated. - * @param {number} value - The amount to be added to the property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var PropertyValueInc = function (items, key, value, step, index, direction) -{ - if (step === undefined) { step = 0; } - if (index === undefined) { index = 0; } - if (direction === undefined) { direction = 1; } - - var i; - var t = 0; - var end = items.length; - - if (direction === 1) - { - // Start to End - for (i = index; i < end; i++) - { - items[i][key] += value + (t * step); - t++; - } - } - else - { - // End to Start - for (i = index; i >= 0; i--) - { - items[i][key] += value + (t * step); - t++; - } - } - - return items; -}; - -module.exports = PropertyValueInc; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, + * and then adds the given value to it. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `PropertyValueInc(group.getChildren(), key, value, step)` + * + * @function Phaser.Actions.PropertyValueInc + * @since 3.3.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 {string} key - The property to be updated. + * @param {number} value - The amount to be added to the property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var PropertyValueInc = function (items, key, value, step, index, direction) +{ + if (step === undefined) { step = 0; } + if (index === undefined) { index = 0; } + if (direction === undefined) { direction = 1; } + + var i; + var t = 0; + var end = items.length; + + if (direction === 1) + { + // Start to End + for (i = index; i < end; i++) + { + items[i][key] += value + (t * step); + t++; + } + } + else + { + // End to Start + for (i = index; i >= 0; i--) + { + items[i][key] += value + (t * step); + t++; + } + } + + return items; +}; + +module.exports = PropertyValueInc; diff --git a/src/actions/PropertyValueSet.js b/src/actions/PropertyValueSet.js index f80287417..5a37901c3 100644 --- a/src/actions/PropertyValueSet.js +++ b/src/actions/PropertyValueSet.js @@ -1,61 +1,61 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `PropertyValueSet(group.getChildren(), key, value, step)` - * - * @function Phaser.Actions.PropertyValueSet - * @since 3.3.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 {string} key - The property to be updated. - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var PropertyValueSet = function (items, key, value, step, index, direction) -{ - if (step === undefined) { step = 0; } - if (index === undefined) { index = 0; } - if (direction === undefined) { direction = 1; } - - var i; - var t = 0; - var end = items.length; - - if (direction === 1) - { - // Start to End - for (i = index; i < end; i++) - { - items[i][key] = value + (t * step); - t++; - } - } - else - { - // End to Start - for (i = index; i >= 0; i--) - { - items[i][key] = value + (t * step); - t++; - } - } - - return items; -}; - -module.exports = PropertyValueSet; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `PropertyValueSet(group.getChildren(), key, value, step)` + * + * @function Phaser.Actions.PropertyValueSet + * @since 3.3.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 {string} key - The property to be updated. + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var PropertyValueSet = function (items, key, value, step, index, direction) +{ + if (step === undefined) { step = 0; } + if (index === undefined) { index = 0; } + if (direction === undefined) { direction = 1; } + + var i; + var t = 0; + var end = items.length; + + if (direction === 1) + { + // Start to End + for (i = index; i < end; i++) + { + items[i][key] = value + (t * step); + t++; + } + } + else + { + // End to Start + for (i = index; i >= 0; i--) + { + items[i][key] = value + (t * step); + t++; + } + } + + return items; +}; + +module.exports = PropertyValueSet; diff --git a/src/actions/RandomCircle.js b/src/actions/RandomCircle.js index 5038e8f44..dc3694e66 100644 --- a/src/actions/RandomCircle.js +++ b/src/actions/RandomCircle.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Random = require('../geom/circle/Random'); - -/** - * Takes an array of Game Objects and positions them at random locations within the Circle. - * - * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.RandomCircle - * @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.Geom.Circle} circle - The Circle to position the Game Objects within. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RandomCircle = function (items, circle) -{ - for (var i = 0; i < items.length; i++) - { - Random(circle, items[i]); - } - - return items; -}; - -module.exports = RandomCircle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = require('../geom/circle/Random'); + +/** + * Takes an array of Game Objects and positions them at random locations within the Circle. + * + * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomCircle + * @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.Geom.Circle} circle - The Circle to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomCircle = function (items, circle) +{ + for (var i = 0; i < items.length; i++) + { + Random(circle, items[i]); + } + + return items; +}; + +module.exports = RandomCircle; diff --git a/src/actions/RandomEllipse.js b/src/actions/RandomEllipse.js index 0b8a97b77..cf9f9b544 100644 --- a/src/actions/RandomEllipse.js +++ b/src/actions/RandomEllipse.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Random = require('../geom/ellipse/Random'); - -/** - * Takes an array of Game Objects and positions them at random locations within the Ellipse. - * - * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.RandomEllipse - * @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.Geom.Ellipse} ellipse - The Ellipse to position the Game Objects within. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RandomEllipse = function (items, ellipse) -{ - for (var i = 0; i < items.length; i++) - { - Random(ellipse, items[i]); - } - - return items; -}; - -module.exports = RandomEllipse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = require('../geom/ellipse/Random'); + +/** + * Takes an array of Game Objects and positions them at random locations within the Ellipse. + * + * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomEllipse + * @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.Geom.Ellipse} ellipse - The Ellipse to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomEllipse = function (items, ellipse) +{ + for (var i = 0; i < items.length; i++) + { + Random(ellipse, items[i]); + } + + return items; +}; + +module.exports = RandomEllipse; diff --git a/src/actions/RandomLine.js b/src/actions/RandomLine.js index 44220a435..ea96ecc16 100644 --- a/src/actions/RandomLine.js +++ b/src/actions/RandomLine.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Random = require('../geom/line/Random'); - -/** - * Takes an array of Game Objects and positions them at random locations on the Line. - * - * If you wish to pass a `Phaser.GameObjects.Line` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.RandomLine - * @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.Geom.Line} line - The Line to position the Game Objects randomly on. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RandomLine = function (items, line) -{ - for (var i = 0; i < items.length; i++) - { - Random(line, items[i]); - } - - return items; -}; - -module.exports = RandomLine; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = require('../geom/line/Random'); + +/** + * Takes an array of Game Objects and positions them at random locations on the Line. + * + * If you wish to pass a `Phaser.GameObjects.Line` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomLine + * @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.Geom.Line} line - The Line to position the Game Objects randomly on. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomLine = function (items, line) +{ + for (var i = 0; i < items.length; i++) + { + Random(line, items[i]); + } + + return items; +}; + +module.exports = RandomLine; diff --git a/src/actions/RandomRectangle.js b/src/actions/RandomRectangle.js index 4abec349c..2c4db795e 100644 --- a/src/actions/RandomRectangle.js +++ b/src/actions/RandomRectangle.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Random = require('../geom/rectangle/Random'); - -/** - * Takes an array of Game Objects and positions them at random locations within the Rectangle. - * - * @function Phaser.Actions.RandomRectangle - * @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.Geom.Rectangle} rect - The Rectangle to position the Game Objects within. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RandomRectangle = function (items, rect) -{ - for (var i = 0; i < items.length; i++) - { - Random(rect, items[i]); - } - - return items; -}; - -module.exports = RandomRectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = require('../geom/rectangle/Random'); + +/** + * Takes an array of Game Objects and positions them at random locations within the Rectangle. + * + * @function Phaser.Actions.RandomRectangle + * @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.Geom.Rectangle} rect - The Rectangle to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomRectangle = function (items, rect) +{ + for (var i = 0; i < items.length; i++) + { + Random(rect, items[i]); + } + + return items; +}; + +module.exports = RandomRectangle; diff --git a/src/actions/RandomTriangle.js b/src/actions/RandomTriangle.js index 091202cf3..490434d5d 100644 --- a/src/actions/RandomTriangle.js +++ b/src/actions/RandomTriangle.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Random = require('../geom/triangle/Random'); - -/** - * Takes an array of Game Objects and positions them at random locations within the Triangle. - * - * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. - * - * @function Phaser.Actions.RandomTriangle - * @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.Geom.Triangle} triangle - The Triangle to position the Game Objects within. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RandomTriangle = function (items, triangle) -{ - for (var i = 0; i < items.length; i++) - { - Random(triangle, items[i]); - } - - return items; -}; - -module.exports = RandomTriangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Random = require('../geom/triangle/Random'); + +/** + * Takes an array of Game Objects and positions them at random locations within the Triangle. + * + * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. + * + * @function Phaser.Actions.RandomTriangle + * @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.Geom.Triangle} triangle - The Triangle to position the Game Objects within. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RandomTriangle = function (items, triangle) +{ + for (var i = 0; i < items.length; i++) + { + Random(triangle, items[i]); + } + + return items; +}; + +module.exports = RandomTriangle; diff --git a/src/actions/Rotate.js b/src/actions/Rotate.js index 0c93ae668..4efe8405c 100644 --- a/src/actions/Rotate.js +++ b/src/actions/Rotate.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `rotation` property, - * and then adds the given value to each of their `rotation` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `Rotate(group.getChildren(), value, step)` - * - * @function Phaser.Actions.Rotate - * @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 {number} value - The amount to be added to the `rotation` property (in radians). - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var Rotate = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'rotation', value, step, index, direction); -}; - -module.exports = Rotate; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `rotation` property, + * and then adds the given value to each of their `rotation` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `Rotate(group.getChildren(), value, step)` + * + * @function Phaser.Actions.Rotate + * @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 {number} value - The amount to be added to the `rotation` property (in radians). + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var Rotate = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'rotation', value, step, index, direction); +}; + +module.exports = Rotate; diff --git a/src/actions/RotateAround.js b/src/actions/RotateAround.js index 6978dfc2f..501b2f503 100644 --- a/src/actions/RotateAround.js +++ b/src/actions/RotateAround.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateAroundDistance = require('../math/RotateAroundDistance'); -var DistanceBetween = require('../math/distance/DistanceBetween'); - -/** - * Rotates each item around the given point by the given angle. - * - * @function Phaser.Actions.RotateAround - * @since 3.0.0 - * @see Phaser.Math.RotateAroundDistance - * - * @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 {object} point - Any object with public `x` and `y` properties. - * @param {number} angle - The angle to rotate by, in radians. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RotateAround = function (items, point, angle) -{ - var x = point.x; - var y = point.y; - - for (var i = 0; i < items.length; i++) - { - var item = items[i]; - - RotateAroundDistance(item, x, y, angle, Math.max(1, DistanceBetween(item.x, item.y, x, y))); - } - - return items; -}; - -module.exports = RotateAround; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundDistance = require('../math/RotateAroundDistance'); +var DistanceBetween = require('../math/distance/DistanceBetween'); + +/** + * Rotates each item around the given point by the given angle. + * + * @function Phaser.Actions.RotateAround + * @since 3.0.0 + * @see Phaser.Math.RotateAroundDistance + * + * @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 {object} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RotateAround = function (items, point, angle) +{ + var x = point.x; + var y = point.y; + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + + RotateAroundDistance(item, x, y, angle, Math.max(1, DistanceBetween(item.x, item.y, x, y))); + } + + return items; +}; + +module.exports = RotateAround; diff --git a/src/actions/RotateAroundDistance.js b/src/actions/RotateAroundDistance.js index 724c33537..4feb382d4 100644 --- a/src/actions/RotateAroundDistance.js +++ b/src/actions/RotateAroundDistance.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MathRotateAroundDistance = require('../math/RotateAroundDistance'); - -/** - * Rotates an array of Game Objects around a point by the given angle and distance. - * - * @function Phaser.Actions.RotateAroundDistance - * @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 {object} point - Any object with public `x` and `y` properties. - * @param {number} angle - The angle to rotate by, in radians. - * @param {number} distance - The distance from the point of rotation in pixels. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var RotateAroundDistance = function (items, point, angle, distance) -{ - var x = point.x; - var y = point.y; - - // There's nothing to do - if (distance === 0) - { - return items; - } - - for (var i = 0; i < items.length; i++) - { - MathRotateAroundDistance(items[i], x, y, angle, distance); - } - - return items; -}; - -module.exports = RotateAroundDistance; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathRotateAroundDistance = require('../math/RotateAroundDistance'); + +/** + * Rotates an array of Game Objects around a point by the given angle and distance. + * + * @function Phaser.Actions.RotateAroundDistance + * @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 {object} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * @param {number} distance - The distance from the point of rotation in pixels. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var RotateAroundDistance = function (items, point, angle, distance) +{ + var x = point.x; + var y = point.y; + + // There's nothing to do + if (distance === 0) + { + return items; + } + + for (var i = 0; i < items.length; i++) + { + MathRotateAroundDistance(items[i], x, y, angle, distance); + } + + return items; +}; + +module.exports = RotateAroundDistance; diff --git a/src/actions/ScaleX.js b/src/actions/ScaleX.js index 209967ed7..2409b3c25 100644 --- a/src/actions/ScaleX.js +++ b/src/actions/ScaleX.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `scaleX` property, - * and then adds the given value to each of their `scaleX` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `ScaleX(group.getChildren(), value, step)` - * - * @function Phaser.Actions.ScaleX - * @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 {number} value - The amount to be added to the `scaleX` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var ScaleX = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'scaleX', value, step, index, direction); -}; - -module.exports = ScaleX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `scaleX` property, + * and then adds the given value to each of their `scaleX` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.ScaleX + * @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 {number} value - The amount to be added to the `scaleX` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var ScaleX = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'scaleX', value, step, index, direction); +}; + +module.exports = ScaleX; diff --git a/src/actions/ScaleXY.js b/src/actions/ScaleXY.js index 0d9182a3b..ef6aaea66 100644 --- a/src/actions/ScaleXY.js +++ b/src/actions/ScaleXY.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have public `scaleX` and `scaleY` properties, - * and then adds the given value to each of them. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `ScaleXY(group.getChildren(), scaleX, scaleY, stepX, stepY)` - * - * @function Phaser.Actions.ScaleXY - * @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 {number} scaleX - The amount to be added to the `scaleX` property. - * @param {number} [scaleY] - The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. - * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var ScaleXY = function (items, scaleX, scaleY, stepX, stepY, index, direction) -{ - if (scaleY === undefined || scaleY === null) { scaleY = scaleX; } - - PropertyValueInc(items, 'scaleX', scaleX, stepX, index, direction); - - return PropertyValueInc(items, 'scaleY', scaleY, stepY, index, direction); -}; - -module.exports = ScaleXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have public `scaleX` and `scaleY` properties, + * and then adds the given value to each of them. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleXY(group.getChildren(), scaleX, scaleY, stepX, stepY)` + * + * @function Phaser.Actions.ScaleXY + * @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 {number} scaleX - The amount to be added to the `scaleX` property. + * @param {number} [scaleY] - The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. + * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var ScaleXY = function (items, scaleX, scaleY, stepX, stepY, index, direction) +{ + if (scaleY === undefined || scaleY === null) { scaleY = scaleX; } + + PropertyValueInc(items, 'scaleX', scaleX, stepX, index, direction); + + return PropertyValueInc(items, 'scaleY', scaleY, stepY, index, direction); +}; + +module.exports = ScaleXY; diff --git a/src/actions/ScaleY.js b/src/actions/ScaleY.js index 2193165f4..5882500aa 100644 --- a/src/actions/ScaleY.js +++ b/src/actions/ScaleY.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueInc = require('./PropertyValueInc'); - -/** - * Takes an array of Game Objects, or any objects that have a public `scaleY` property, - * and then adds the given value to each of their `scaleY` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `ScaleY(group.getChildren(), value, step)` - * - * @function Phaser.Actions.ScaleY - * @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 {number} value - The amount to be added to the `scaleY` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var ScaleY = function (items, value, step, index, direction) -{ - return PropertyValueInc(items, 'scaleY', value, step, index, direction); -}; - -module.exports = ScaleY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueInc = require('./PropertyValueInc'); + +/** + * Takes an array of Game Objects, or any objects that have a public `scaleY` property, + * and then adds the given value to each of their `scaleY` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.ScaleY + * @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 {number} value - The amount to be added to the `scaleY` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var ScaleY = function (items, value, step, index, direction) +{ + return PropertyValueInc(items, 'scaleY', value, step, index, direction); +}; + +module.exports = ScaleY; diff --git a/src/actions/SetAlpha.js b/src/actions/SetAlpha.js index 0f867e084..8212843c0 100644 --- a/src/actions/SetAlpha.js +++ b/src/actions/SetAlpha.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `alpha` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetAlpha(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetAlpha - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetAlpha = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'alpha', value, step, index, direction); -}; - -module.exports = SetAlpha; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `alpha` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetAlpha(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetAlpha + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetAlpha = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'alpha', value, step, index, direction); +}; + +module.exports = SetAlpha; diff --git a/src/actions/SetBlendMode.js b/src/actions/SetBlendMode.js index bb4997732..324d425fa 100644 --- a/src/actions/SetBlendMode.js +++ b/src/actions/SetBlendMode.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `blendMode` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetBlendMode(group.getChildren(), value)` - * - * @function Phaser.Actions.SetBlendMode - * @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 {number} value - The amount to set the property to. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetBlendMode = function (items, value, index, direction) -{ - return PropertyValueSet(items, 'blendMode', value, 0, index, direction); -}; - -module.exports = SetBlendMode; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `blendMode` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetBlendMode(group.getChildren(), value)` + * + * @function Phaser.Actions.SetBlendMode + * @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 {number} value - The amount to set the property to. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetBlendMode = function (items, value, index, direction) +{ + return PropertyValueSet(items, 'blendMode', value, 0, index, direction); +}; + +module.exports = SetBlendMode; diff --git a/src/actions/SetDepth.js b/src/actions/SetDepth.js index 5d2854d1e..d78502bcc 100644 --- a/src/actions/SetDepth.js +++ b/src/actions/SetDepth.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `depth` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetDepth(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetDepth - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetDepth = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'depth', value, step, index, direction); -}; - -module.exports = SetDepth; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `depth` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetDepth(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetDepth + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetDepth = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'depth', value, step, index, direction); +}; + +module.exports = SetDepth; diff --git a/src/actions/SetHitArea.js b/src/actions/SetHitArea.js index 5024dc42f..8adb5c40f 100644 --- a/src/actions/SetHitArea.js +++ b/src/actions/SetHitArea.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Passes all provided Game Objects to the Input Manager to enable them for input with identical areas and callbacks. - * - * @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 {*} 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 - A callback to be invoked when the Game Object is interacted with. 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. - */ -var SetHitArea = function (items, hitArea, hitAreaCallback) -{ - for (var i = 0; i < items.length; i++) - { - items[i].setInteractive(hitArea, hitAreaCallback); - } - - return items; -}; - -module.exports = SetHitArea; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Passes all provided Game Objects to the Input Manager to enable them for input with identical areas and callbacks. + * + * @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 {*} 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 - A callback to be invoked when the Game Object is interacted with. 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. + */ +var SetHitArea = function (items, hitArea, hitAreaCallback) +{ + for (var i = 0; i < items.length; i++) + { + items[i].setInteractive(hitArea, hitAreaCallback); + } + + return items; +}; + +module.exports = SetHitArea; diff --git a/src/actions/SetOrigin.js b/src/actions/SetOrigin.js index 6983e4563..9b62ef94c 100644 --- a/src/actions/SetOrigin.js +++ b/src/actions/SetOrigin.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetOrigin(group.getChildren(), originX, originY, stepX, stepY)` - * - * @function Phaser.Actions.SetOrigin - * @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 {number} originX - The amount to set the `originX` property to. - * @param {number} [originY] - The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. - * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetOrigin = function (items, originX, originY, stepX, stepY, index, direction) -{ - if (originY === undefined || originY === null) { originY = originX; } - - PropertyValueSet(items, 'originX', originX, stepX, index, direction); - - return PropertyValueSet(items, 'originY', originY, stepY, index, direction); -}; - -module.exports = SetOrigin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetOrigin(group.getChildren(), originX, originY, stepX, stepY)` + * + * @function Phaser.Actions.SetOrigin + * @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 {number} originX - The amount to set the `originX` property to. + * @param {number} [originY] - The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. + * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetOrigin = function (items, originX, originY, stepX, stepY, index, direction) +{ + if (originY === undefined || originY === null) { originY = originX; } + + PropertyValueSet(items, 'originX', originX, stepX, index, direction); + + return PropertyValueSet(items, 'originY', originY, stepY, index, direction); +}; + +module.exports = SetOrigin; diff --git a/src/actions/SetRotation.js b/src/actions/SetRotation.js index d3c5b36ce..824371852 100644 --- a/src/actions/SetRotation.js +++ b/src/actions/SetRotation.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `rotation` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetRotation(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetRotation - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetRotation = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'rotation', value, step, index, direction); -}; - -module.exports = SetRotation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `rotation` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetRotation(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetRotation + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetRotation = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'rotation', value, step, index, direction); +}; + +module.exports = SetRotation; diff --git a/src/actions/SetScale.js b/src/actions/SetScale.js index 78daccd20..3768bfdfe 100644 --- a/src/actions/SetScale.js +++ b/src/actions/SetScale.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScale(group.getChildren(), scaleX, scaleY, stepX, stepY)` - * - * @function Phaser.Actions.SetScale - * @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 {number} scaleX - The amount to set the `scaleX` property to. - * @param {number} [scaleY] - The amount to set the `scaleY` property to. If `undefined` or `null` it uses the `scaleX` value. - * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetScale = function (items, scaleX, scaleY, stepX, stepY, index, direction) -{ - if (scaleY === undefined || scaleY === null) { scaleY = scaleX; } - - PropertyValueSet(items, 'scaleX', scaleX, stepX, index, direction); - - return PropertyValueSet(items, 'scaleY', scaleY, stepY, index, direction); -}; - -module.exports = SetScale; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScale(group.getChildren(), scaleX, scaleY, stepX, stepY)` + * + * @function Phaser.Actions.SetScale + * @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 {number} scaleX - The amount to set the `scaleX` property to. + * @param {number} [scaleY] - The amount to set the `scaleY` property to. If `undefined` or `null` it uses the `scaleX` value. + * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScale = function (items, scaleX, scaleY, stepX, stepY, index, direction) +{ + if (scaleY === undefined || scaleY === null) { scaleY = scaleX; } + + PropertyValueSet(items, 'scaleX', scaleX, stepX, index, direction); + + return PropertyValueSet(items, 'scaleY', scaleY, stepY, index, direction); +}; + +module.exports = SetScale; diff --git a/src/actions/SetScaleX.js b/src/actions/SetScaleX.js index ef2c40859..ff7de4cc6 100644 --- a/src/actions/SetScaleX.js +++ b/src/actions/SetScaleX.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `scaleX` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScaleX(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetScaleX - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetScaleX = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'scaleX', value, step, index, direction); -}; - -module.exports = SetScaleX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scaleX` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScaleX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScaleX + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScaleX = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scaleX', value, step, index, direction); +}; + +module.exports = SetScaleX; diff --git a/src/actions/SetScaleY.js b/src/actions/SetScaleY.js index 296ff919a..6eff271b9 100644 --- a/src/actions/SetScaleY.js +++ b/src/actions/SetScaleY.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `scaleY` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScaleY(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetScaleY - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetScaleY = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'scaleY', value, step, index, direction); -}; - -module.exports = SetScaleY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scaleY` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScaleY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScaleY + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScaleY = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scaleY', value, step, index, direction); +}; + +module.exports = SetScaleY; diff --git a/src/actions/SetScrollFactor.js b/src/actions/SetScrollFactor.js index 4598e7c40..8f594c124 100644 --- a/src/actions/SetScrollFactor.js +++ b/src/actions/SetScrollFactor.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScrollFactor(group.getChildren(), scrollFactorX, scrollFactorY, stepX, stepY)` - * - * @function Phaser.Actions.SetScrollFactor - * @since 3.21.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 {number} scrollFactorX - The amount to set the `scrollFactorX` property to. - * @param {number} [scrollFactorY] - The amount to set the `scrollFactorY` property to. If `undefined` or `null` it uses the `scrollFactorX` value. - * @param {number} [stepX=0] - This is added to the `scrollFactorX` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `scrollFactorY` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetScrollFactor = function (items, scrollFactorX, scrollFactorY, stepX, stepY, index, direction) -{ - if (scrollFactorY === undefined || scrollFactorY === null) { scrollFactorY = scrollFactorX; } - - PropertyValueSet(items, 'scrollFactorX', scrollFactorX, stepX, index, direction); - - return PropertyValueSet(items, 'scrollFactorY', scrollFactorY, stepY, index, direction); -}; - -module.exports = SetScrollFactor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactor(group.getChildren(), scrollFactorX, scrollFactorY, stepX, stepY)` + * + * @function Phaser.Actions.SetScrollFactor + * @since 3.21.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 {number} scrollFactorX - The amount to set the `scrollFactorX` property to. + * @param {number} [scrollFactorY] - The amount to set the `scrollFactorY` property to. If `undefined` or `null` it uses the `scrollFactorX` value. + * @param {number} [stepX=0] - This is added to the `scrollFactorX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scrollFactorY` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScrollFactor = function (items, scrollFactorX, scrollFactorY, stepX, stepY, index, direction) +{ + if (scrollFactorY === undefined || scrollFactorY === null) { scrollFactorY = scrollFactorX; } + + PropertyValueSet(items, 'scrollFactorX', scrollFactorX, stepX, index, direction); + + return PropertyValueSet(items, 'scrollFactorY', scrollFactorY, stepY, index, direction); +}; + +module.exports = SetScrollFactor; diff --git a/src/actions/SetScrollFactorX.js b/src/actions/SetScrollFactorX.js index e39b64dcd..88b380e8a 100644 --- a/src/actions/SetScrollFactorX.js +++ b/src/actions/SetScrollFactorX.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScrollFactorX(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetScrollFactorX - * @since 3.21.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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetScrollFactorX = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'scrollFactorX', value, step, index, direction); -}; - -module.exports = SetScrollFactorX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactorX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScrollFactorX + * @since 3.21.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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScrollFactorX = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scrollFactorX', value, step, index, direction); +}; + +module.exports = SetScrollFactorX; diff --git a/src/actions/SetScrollFactorY.js b/src/actions/SetScrollFactorY.js index fe2a9fca2..eda4f2c67 100644 --- a/src/actions/SetScrollFactorY.js +++ b/src/actions/SetScrollFactorY.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScrollFactorY(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetScrollFactorY - * @since 3.21.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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetScrollFactorY = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'scrollFactorY', value, step, index, direction); -}; - -module.exports = SetScrollFactorY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactorY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetScrollFactorY + * @since 3.21.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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetScrollFactorY = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'scrollFactorY', value, step, index, direction); +}; + +module.exports = SetScrollFactorY; diff --git a/src/actions/SetTint.js b/src/actions/SetTint.js index ce687138b..b1d8a14ae 100644 --- a/src/actions/SetTint.js +++ b/src/actions/SetTint.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects, or any objects that have the public method setTint() and then updates it to the given value(s). You can specify tint color per corner or provide only one color value for `topLeft` parameter, in which case whole item will be tinted with that color. - * - * @function Phaser.Actions.SetTint - * @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 {number} topLeft - The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. - * @param {number} [topRight] - The tint to be applied to top-right corner of item. - * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. - * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var SetTint = function (items, topLeft, topRight, bottomLeft, bottomRight) -{ - for (var i = 0; i < items.length; i++) - { - items[i].setTint(topLeft, topRight, bottomLeft, bottomRight); - } - - return items; -}; - -module.exports = SetTint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects, or any objects that have the public method setTint() and then updates it to the given value(s). You can specify tint color per corner or provide only one color value for `topLeft` parameter, in which case whole item will be tinted with that color. + * + * @function Phaser.Actions.SetTint + * @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 {number} topLeft - The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. + * @param {number} [topRight] - The tint to be applied to top-right corner of item. + * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. + * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var SetTint = function (items, topLeft, topRight, bottomLeft, bottomRight) +{ + for (var i = 0; i < items.length; i++) + { + items[i].setTint(topLeft, topRight, bottomLeft, bottomRight); + } + + return items; +}; + +module.exports = SetTint; diff --git a/src/actions/SetVisible.js b/src/actions/SetVisible.js index 9f9ad347e..aceaadd76 100644 --- a/src/actions/SetVisible.js +++ b/src/actions/SetVisible.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `visible` - * and then sets it to the given value. - * - * To use this with a Group: `SetVisible(group.getChildren(), value)` - * - * @function Phaser.Actions.SetVisible - * @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 {boolean} value - The value to set the property to. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetVisible = function (items, value, index, direction) -{ - return PropertyValueSet(items, 'visible', value, 0, index, direction); -}; - -module.exports = SetVisible; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `visible` + * and then sets it to the given value. + * + * To use this with a Group: `SetVisible(group.getChildren(), value)` + * + * @function Phaser.Actions.SetVisible + * @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 {boolean} value - The value to set the property to. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetVisible = function (items, value, index, direction) +{ + return PropertyValueSet(items, 'visible', value, 0, index, direction); +}; + +module.exports = SetVisible; diff --git a/src/actions/SetX.js b/src/actions/SetX.js index 3216a9393..687639796 100644 --- a/src/actions/SetX.js +++ b/src/actions/SetX.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `x` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetX(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetX - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetX = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'x', value, step, index, direction); -}; - -module.exports = SetX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `x` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetX(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetX + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetX = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'x', value, step, index, direction); +}; + +module.exports = SetX; diff --git a/src/actions/SetXY.js b/src/actions/SetXY.js index 3bb4f964e..b0deded50 100644 --- a/src/actions/SetXY.js +++ b/src/actions/SetXY.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetXY(group.getChildren(), x, y, stepX, stepY)` - * - * @function Phaser.Actions.SetXY - * @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 {number} x - The amount to set the `x` property to. - * @param {number} [y=x] - The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. - * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetXY = function (items, x, y, stepX, stepY, index, direction) -{ - if (y === undefined || y === null) { y = x; } - - PropertyValueSet(items, 'x', x, stepX, index, direction); - - return PropertyValueSet(items, 'y', y, stepY, index, direction); -}; - -module.exports = SetXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetXY(group.getChildren(), x, y, stepX, stepY)` + * + * @function Phaser.Actions.SetXY + * @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 {number} x - The amount to set the `x` property to. + * @param {number} [y=x] - The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetXY = function (items, x, y, stepX, stepY, index, direction) +{ + if (y === undefined || y === null) { y = x; } + + PropertyValueSet(items, 'x', x, stepX, index, direction); + + return PropertyValueSet(items, 'y', y, stepY, index, direction); +}; + +module.exports = SetXY; diff --git a/src/actions/SetY.js b/src/actions/SetY.js index 9c96b97b7..b05c0bd26 100644 --- a/src/actions/SetY.js +++ b/src/actions/SetY.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PropertyValueSet = require('./PropertyValueSet'); - -/** - * Takes an array of Game Objects, or any objects that have the public property `y` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetY(group.getChildren(), value, step)` - * - * @function Phaser.Actions.SetY - * @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 {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. - */ -var SetY = function (items, value, step, index, direction) -{ - return PropertyValueSet(items, 'y', value, step, index, direction); -}; - -module.exports = SetY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PropertyValueSet = require('./PropertyValueSet'); + +/** + * Takes an array of Game Objects, or any objects that have the public property `y` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetY(group.getChildren(), value, step)` + * + * @function Phaser.Actions.SetY + * @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 {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action. + */ +var SetY = function (items, value, step, index, direction) +{ + return PropertyValueSet(items, 'y', value, step, index, direction); +}; + +module.exports = SetY; diff --git a/src/actions/ShiftPosition.js b/src/actions/ShiftPosition.js index 9e0c16b32..19700d1cc 100644 --- a/src/actions/ShiftPosition.js +++ b/src/actions/ShiftPosition.js @@ -1,124 +1,124 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Vector2 = require('../math/Vector2'); - -/** - * Iterate through the items array changing the position of each element to be that of the element that came before - * it in the array (or after it if direction = 1) - * - * The first items position is set to x/y. - * - * The final x/y coords are returned - * - * @function Phaser.Actions.ShiftPosition - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject[]} G - [items] - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action. - * @param {number} x - The x coordinate to place the first item in the array at. - * @param {number} y - The y coordinate to place the first item in the array at. - * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. - * @param {(Phaser.Math.Vector2|object)} [output] - An optional objec to store the final objects position in. - * - * @return {Phaser.Math.Vector2} The output vector. - */ -var ShiftPosition = function (items, x, y, direction, output) -{ - if (direction === undefined) { direction = 0; } - if (output === undefined) { output = new Vector2(); } - - var px; - var py; - - if (items.length > 1) - { - var i; - var cx; - var cy; - var cur; - - if (direction === 0) - { - // Bottom to Top - - var len = items.length - 1; - - px = items[len].x; - py = items[len].y; - - for (i = len - 1; i >= 0; i--) - { - // Current item - cur = items[i]; - - // Get current item x/y, to be passed to the next item in the list - cx = cur.x; - cy = cur.y; - - // Set current item to the previous items x/y - cur.x = px; - cur.y = py; - - // Set current as previous - px = cx; - py = cy; - } - - // Update the head item to the new x/y coordinates - items[len].x = x; - items[len].y = y; - } - else - { - // Top to Bottom - - px = items[0].x; - py = items[0].y; - - for (i = 1; i < items.length; i++) - { - // Current item - cur = items[i]; - - // Get current item x/y, to be passed to the next item in the list - cx = cur.x; - cy = cur.y; - - // Set current item to the previous items x/y - cur.x = px; - cur.y = py; - - // Set current as previous - px = cx; - py = cy; - } - - // Update the head item to the new x/y coordinates - items[0].x = x; - items[0].y = y; - } - } - else - { - px = items[0].x; - py = items[0].y; - - items[0].x = x; - items[0].y = y; - } - - // Return the final set of coordinates as they're effectively lost from the shift and may be needed - - output.x = px; - output.y = py; - - return output; -}; - -module.exports = ShiftPosition; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = require('../math/Vector2'); + +/** + * Iterate through the items array changing the position of each element to be that of the element that came before + * it in the array (or after it if direction = 1) + * + * The first items position is set to x/y. + * + * The final x/y coords are returned + * + * @function Phaser.Actions.ShiftPosition + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items] + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action. + * @param {number} x - The x coordinate to place the first item in the array at. + * @param {number} y - The y coordinate to place the first item in the array at. + * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. + * @param {(Phaser.Math.Vector2|object)} [output] - An optional objec to store the final objects position in. + * + * @return {Phaser.Math.Vector2} The output vector. + */ +var ShiftPosition = function (items, x, y, direction, output) +{ + if (direction === undefined) { direction = 0; } + if (output === undefined) { output = new Vector2(); } + + var px; + var py; + + if (items.length > 1) + { + var i; + var cx; + var cy; + var cur; + + if (direction === 0) + { + // Bottom to Top + + var len = items.length - 1; + + px = items[len].x; + py = items[len].y; + + for (i = len - 1; i >= 0; i--) + { + // Current item + cur = items[i]; + + // Get current item x/y, to be passed to the next item in the list + cx = cur.x; + cy = cur.y; + + // Set current item to the previous items x/y + cur.x = px; + cur.y = py; + + // Set current as previous + px = cx; + py = cy; + } + + // Update the head item to the new x/y coordinates + items[len].x = x; + items[len].y = y; + } + else + { + // Top to Bottom + + px = items[0].x; + py = items[0].y; + + for (i = 1; i < items.length; i++) + { + // Current item + cur = items[i]; + + // Get current item x/y, to be passed to the next item in the list + cx = cur.x; + cy = cur.y; + + // Set current item to the previous items x/y + cur.x = px; + cur.y = py; + + // Set current as previous + px = cx; + py = cy; + } + + // Update the head item to the new x/y coordinates + items[0].x = x; + items[0].y = y; + } + } + else + { + px = items[0].x; + py = items[0].y; + + items[0].x = x; + items[0].y = y; + } + + // Return the final set of coordinates as they're effectively lost from the shift and may be needed + + output.x = px; + output.y = py; + + return output; +}; + +module.exports = ShiftPosition; diff --git a/src/actions/Shuffle.js b/src/actions/Shuffle.js index 933beac68..9b5bed0a3 100644 --- a/src/actions/Shuffle.js +++ b/src/actions/Shuffle.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArrayShuffle = require('../utils/array/Shuffle'); - -/** - * Shuffles the array in place. The shuffled array is both modified and returned. - * - * @function Phaser.Actions.Shuffle - * @since 3.0.0 - * @see Phaser.Utils.Array.Shuffle - * - * @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. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var Shuffle = function (items) -{ - return ArrayShuffle(items); -}; - -module.exports = Shuffle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayShuffle = require('../utils/array/Shuffle'); + +/** + * Shuffles the array in place. The shuffled array is both modified and returned. + * + * @function Phaser.Actions.Shuffle + * @since 3.0.0 + * @see Phaser.Utils.Array.Shuffle + * + * @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. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var Shuffle = function (items) +{ + return ArrayShuffle(items); +}; + +module.exports = Shuffle; diff --git a/src/actions/SmoothStep.js b/src/actions/SmoothStep.js index b97396cb5..21bc00281 100644 --- a/src/actions/SmoothStep.js +++ b/src/actions/SmoothStep.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MathSmoothStep = require('../math/SmoothStep'); - -/** - * 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 minimum interpolation value. - * @param {number} max - The maximum interpolation value. - * @param {boolean} [inc=false] - Should the values be incremented? `true` or set (`false`) - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var SmoothStep = function (items, property, min, max, inc) -{ - if (inc === undefined) { inc = false; } - - var step = Math.abs(max - min) / items.length; - var i; - - if (inc) - { - for (i = 0; i < items.length; i++) - { - items[i][property] += MathSmoothStep(i * step, min, max); - } - } - else - { - for (i = 0; i < items.length; i++) - { - items[i][property] = MathSmoothStep(i * step, min, max); - } - } - - return items; -}; - -module.exports = SmoothStep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathSmoothStep = require('../math/SmoothStep'); + +/** + * 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 minimum interpolation value. + * @param {number} max - The maximum interpolation value. + * @param {boolean} [inc=false] - Should the values be incremented? `true` or set (`false`) + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var SmoothStep = function (items, property, min, max, inc) +{ + if (inc === undefined) { inc = false; } + + var step = Math.abs(max - min) / items.length; + var i; + + if (inc) + { + for (i = 0; i < items.length; i++) + { + items[i][property] += MathSmoothStep(i * step, min, max); + } + } + else + { + for (i = 0; i < items.length; i++) + { + items[i][property] = MathSmoothStep(i * step, min, max); + } + } + + return items; +}; + +module.exports = SmoothStep; diff --git a/src/actions/SmootherStep.js b/src/actions/SmootherStep.js index 0fb21d781..3b77f3fd0 100644 --- a/src/actions/SmootherStep.js +++ b/src/actions/SmootherStep.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MathSmootherStep = require('../math/SmootherStep'); - -/** - * 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 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.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] - Should the values be incremented? `true` or set (`false`) - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var SmootherStep = function (items, property, min, max, inc) -{ - if (inc === undefined) { inc = false; } - - var step = Math.abs(max - min) / items.length; - var i; - - if (inc) - { - for (i = 0; i < items.length; i++) - { - items[i][property] += MathSmootherStep(i * step, min, max); - } - } - else - { - for (i = 0; i < items.length; i++) - { - items[i][property] = MathSmootherStep(i * step, min, max); - } - } - - return items; -}; - -module.exports = SmootherStep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathSmootherStep = require('../math/SmootherStep'); + +/** + * 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 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.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] - Should the values be incremented? `true` or set (`false`) + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var SmootherStep = function (items, property, min, max, inc) +{ + if (inc === undefined) { inc = false; } + + var step = Math.abs(max - min) / items.length; + var i; + + if (inc) + { + for (i = 0; i < items.length; i++) + { + items[i][property] += MathSmootherStep(i * step, min, max); + } + } + else + { + for (i = 0; i < items.length; i++) + { + items[i][property] = MathSmootherStep(i * step, min, max); + } + } + + return items; +}; + +module.exports = SmootherStep; diff --git a/src/actions/Spread.js b/src/actions/Spread.js index 61e87bf18..61bcfbc95 100644 --- a/src/actions/Spread.js +++ b/src/actions/Spread.js @@ -1,57 +1,57 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects and then modifies their `property` so the value equals, or is incremented, by the - * calculated spread value. - * - * The spread value is derived from the given `min` and `max` values and the total number of items in the array. - * - * For example, to cause an array of Sprites to change in alpha from 0 to 1 you could call: - * - * ```javascript - * Phaser.Actions.Spread(itemsArray, 'alpha', 0, 1); - * ``` - * - * @function Phaser.Actions.Spread - * @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 spread. - * @param {number} min - The minimum value. - * @param {number} max - The maximum value. - * @param {boolean} [inc=false] - Should the values be incremented? `true` or set (`false`) - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that were passed to this Action. - */ -var Spread = function (items, property, min, max, inc) -{ - if (inc === undefined) { inc = false; } - - var step = Math.abs(max - min) / items.length; - var i; - - if (inc) - { - for (i = 0; i < items.length; i++) - { - items[i][property] += i * step + min; - } - } - else - { - for (i = 0; i < items.length; i++) - { - items[i][property] = i * step + min; - } - } - - return items; -}; - -module.exports = Spread; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and then modifies their `property` so the value equals, or is incremented, by the + * calculated spread value. + * + * The spread value is derived from the given `min` and `max` values and the total number of items in the array. + * + * For example, to cause an array of Sprites to change in alpha from 0 to 1 you could call: + * + * ```javascript + * Phaser.Actions.Spread(itemsArray, 'alpha', 0, 1); + * ``` + * + * @function Phaser.Actions.Spread + * @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 spread. + * @param {number} min - The minimum value. + * @param {number} max - The maximum value. + * @param {boolean} [inc=false] - Should the values be incremented? `true` or set (`false`) + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that were passed to this Action. + */ +var Spread = function (items, property, min, max, inc) +{ + if (inc === undefined) { inc = false; } + + var step = Math.abs(max - min) / items.length; + var i; + + if (inc) + { + for (i = 0; i < items.length; i++) + { + items[i][property] += i * step + min; + } + } + else + { + for (i = 0; i < items.length; i++) + { + items[i][property] = i * step + min; + } + } + + return items; +}; + +module.exports = Spread; diff --git a/src/actions/ToggleVisible.js b/src/actions/ToggleVisible.js index 294013797..d1e3591bd 100644 --- a/src/actions/ToggleVisible.js +++ b/src/actions/ToggleVisible.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes an array of Game Objects and toggles the visibility of each one. - * Those previously `visible = false` will become `visible = true`, and vice versa. - * - * @function Phaser.Actions.ToggleVisible - * @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. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var ToggleVisible = function (items) -{ - for (var i = 0; i < items.length; i++) - { - items[i].visible = !items[i].visible; - } - - return items; -}; - -module.exports = ToggleVisible; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes an array of Game Objects and toggles the visibility of each one. + * Those previously `visible = false` will become `visible = true`, and vice versa. + * + * @function Phaser.Actions.ToggleVisible + * @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. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var ToggleVisible = function (items) +{ + for (var i = 0; i < items.length; i++) + { + items[i].visible = !items[i].visible; + } + + return items; +}; + +module.exports = ToggleVisible; diff --git a/src/actions/WrapInRectangle.js b/src/actions/WrapInRectangle.js index 63e74c2d7..751b573a7 100644 --- a/src/actions/WrapInRectangle.js +++ b/src/actions/WrapInRectangle.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Wrap = require('../math/Wrap'); - -/** - * Wrap each item's coordinates within a rectangle's area. - * - * @function Phaser.Actions.WrapInRectangle - * @since 3.0.0 - * @see Phaser.Math.Wrap - * - * @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.Geom.Rectangle} rect - The rectangle. - * @param {number} [padding=0] - An amount added to each side of the rectangle during the operation. - * - * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. - */ -var WrapInRectangle = function (items, rect, padding) -{ - if (padding === undefined) - { - padding = 0; - } - - for (var i = 0; i < items.length; i++) - { - var item = items[i]; - - item.x = Wrap(item.x, rect.left - padding, rect.right + padding); - item.y = Wrap(item.y, rect.top - padding, rect.bottom + padding); - } - - return items; -}; - -module.exports = WrapInRectangle; +/** + * @author Richard Davey + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Wrap = require('../math/Wrap'); + +/** + * Wrap each item's coordinates within a rectangle's area. + * + * @function Phaser.Actions.WrapInRectangle + * @since 3.0.0 + * @see Phaser.Math.Wrap + * + * @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.Geom.Rectangle} rect - The rectangle. + * @param {number} [padding=0] - An amount added to each side of the rectangle during the operation. + * + * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action. + */ +var WrapInRectangle = function (items, rect, padding) +{ + if (padding === undefined) + { + padding = 0; + } + + for (var i = 0; i < items.length; i++) + { + var item = items[i]; + + item.x = Wrap(item.x, rect.left - padding, rect.right + padding); + item.y = Wrap(item.y, rect.top - padding, rect.bottom + padding); + } + + return items; +}; + +module.exports = WrapInRectangle; diff --git a/src/actions/index.js b/src/actions/index.js index e7bc94c72..361410755 100644 --- a/src/actions/index.js +++ b/src/actions/index.js @@ -1,67 +1,67 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Actions - */ - -module.exports = { - - AlignTo: require('./AlignTo'), - Angle: require('./Angle'), - Call: require('./Call'), - GetFirst: require('./GetFirst'), - GetLast: require('./GetLast'), - GridAlign: require('./GridAlign'), - IncAlpha: require('./IncAlpha'), - IncX: require('./IncX'), - IncXY: require('./IncXY'), - IncY: require('./IncY'), - PlaceOnCircle: require('./PlaceOnCircle'), - PlaceOnEllipse: require('./PlaceOnEllipse'), - PlaceOnLine: require('./PlaceOnLine'), - PlaceOnRectangle: require('./PlaceOnRectangle'), - PlaceOnTriangle: require('./PlaceOnTriangle'), - PlayAnimation: require('./PlayAnimation'), - PropertyValueInc: require('./PropertyValueInc'), - PropertyValueSet: require('./PropertyValueSet'), - RandomCircle: require('./RandomCircle'), - RandomEllipse: require('./RandomEllipse'), - RandomLine: require('./RandomLine'), - RandomRectangle: require('./RandomRectangle'), - RandomTriangle: require('./RandomTriangle'), - Rotate: require('./Rotate'), - RotateAround: require('./RotateAround'), - RotateAroundDistance: require('./RotateAroundDistance'), - ScaleX: require('./ScaleX'), - ScaleXY: require('./ScaleXY'), - ScaleY: require('./ScaleY'), - SetAlpha: require('./SetAlpha'), - SetBlendMode: require('./SetBlendMode'), - SetDepth: require('./SetDepth'), - SetHitArea: require('./SetHitArea'), - SetOrigin: require('./SetOrigin'), - SetRotation: require('./SetRotation'), - SetScale: require('./SetScale'), - SetScaleX: require('./SetScaleX'), - SetScaleY: require('./SetScaleY'), - SetScrollFactor: require('./SetScrollFactor'), - SetScrollFactorX: require('./SetScrollFactorX'), - SetScrollFactorY: require('./SetScrollFactorY'), - SetTint: require('./SetTint'), - SetVisible: require('./SetVisible'), - SetX: require('./SetX'), - SetXY: require('./SetXY'), - SetY: require('./SetY'), - ShiftPosition: require('./ShiftPosition'), - Shuffle: require('./Shuffle'), - SmootherStep: require('./SmootherStep'), - SmoothStep: require('./SmoothStep'), - Spread: require('./Spread'), - ToggleVisible: require('./ToggleVisible'), - WrapInRectangle: require('./WrapInRectangle') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Actions + */ + +module.exports = { + + AlignTo: require('./AlignTo'), + Angle: require('./Angle'), + Call: require('./Call'), + GetFirst: require('./GetFirst'), + GetLast: require('./GetLast'), + GridAlign: require('./GridAlign'), + IncAlpha: require('./IncAlpha'), + IncX: require('./IncX'), + IncXY: require('./IncXY'), + IncY: require('./IncY'), + PlaceOnCircle: require('./PlaceOnCircle'), + PlaceOnEllipse: require('./PlaceOnEllipse'), + PlaceOnLine: require('./PlaceOnLine'), + PlaceOnRectangle: require('./PlaceOnRectangle'), + PlaceOnTriangle: require('./PlaceOnTriangle'), + PlayAnimation: require('./PlayAnimation'), + PropertyValueInc: require('./PropertyValueInc'), + PropertyValueSet: require('./PropertyValueSet'), + RandomCircle: require('./RandomCircle'), + RandomEllipse: require('./RandomEllipse'), + RandomLine: require('./RandomLine'), + RandomRectangle: require('./RandomRectangle'), + RandomTriangle: require('./RandomTriangle'), + Rotate: require('./Rotate'), + RotateAround: require('./RotateAround'), + RotateAroundDistance: require('./RotateAroundDistance'), + ScaleX: require('./ScaleX'), + ScaleXY: require('./ScaleXY'), + ScaleY: require('./ScaleY'), + SetAlpha: require('./SetAlpha'), + SetBlendMode: require('./SetBlendMode'), + SetDepth: require('./SetDepth'), + SetHitArea: require('./SetHitArea'), + SetOrigin: require('./SetOrigin'), + SetRotation: require('./SetRotation'), + SetScale: require('./SetScale'), + SetScaleX: require('./SetScaleX'), + SetScaleY: require('./SetScaleY'), + SetScrollFactor: require('./SetScrollFactor'), + SetScrollFactorX: require('./SetScrollFactorX'), + SetScrollFactorY: require('./SetScrollFactorY'), + SetTint: require('./SetTint'), + SetVisible: require('./SetVisible'), + SetX: require('./SetX'), + SetXY: require('./SetXY'), + SetY: require('./SetY'), + ShiftPosition: require('./ShiftPosition'), + Shuffle: require('./Shuffle'), + SmootherStep: require('./SmootherStep'), + SmoothStep: require('./SmoothStep'), + Spread: require('./Spread'), + ToggleVisible: require('./ToggleVisible'), + WrapInRectangle: require('./WrapInRectangle') + +}; diff --git a/src/actions/typedefs/index.js b/src/actions/typedefs/index.js index dd8bb2e75..ac74783bd 100644 --- a/src/actions/typedefs/index.js +++ b/src/actions/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Actions - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Actions + */ diff --git a/src/animations/Animation.js b/src/animations/Animation.js index 7c5c2f87b..7a8bed87b 100644 --- a/src/animations/Animation.js +++ b/src/animations/Animation.js @@ -1,954 +1,954 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../math/Clamp'); -var Class = require('../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var FindClosestInSorted = require('../utils/array/FindClosestInSorted'); -var Frame = require('./AnimationFrame'); -var GetValue = require('../utils/object/GetValue'); - -/** - * @classdesc - * A Frame based Animation. - * - * This consists of a key, some default values (like the frame rate) and a bunch of Frame objects. - * - * The Animation Manager creates these. Game Objects don't own an instance of these directly. - * Game Objects have the Animation Component, which are like playheads to global Animations (these objects) - * So multiple Game Objects can have playheads all pointing to this one Animation instance. - * - * @class Animation - * @memberof Phaser.Animations - * @extends Phaser.Events.EventEmitter - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Animations.AnimationManager} manager - A reference to the global Animation Manager - * @param {string} key - The unique identifying string for this animation. - * @param {Phaser.Types.Animations.Animation} config - The Animation configuration. - */ -var Animation = new Class({ - - Extends: EventEmitter, - - initialize: - - function Animation (manager, key, config) - { - EventEmitter.call(this); - - /** - * A reference to the global Animation Manager. - * - * @name Phaser.Animations.Animation#manager - * @type {Phaser.Animations.AnimationManager} - * @since 3.0.0 - */ - this.manager = manager; - - /** - * The unique identifying string for this animation. - * - * @name Phaser.Animations.Animation#key - * @type {string} - * @since 3.0.0 - */ - this.key = key; - - /** - * A frame based animation (as opposed to a bone based animation) - * - * @name Phaser.Animations.Animation#type - * @type {string} - * @default frame - * @since 3.0.0 - */ - this.type = 'frame'; - - /** - * Extract all the frame data into the frames array. - * - * @name Phaser.Animations.Animation#frames - * @type {Phaser.Animations.AnimationFrame[]} - * @since 3.0.0 - */ - this.frames = this.getFrames( - manager.textureManager, - GetValue(config, 'frames', []), - GetValue(config, 'defaultTextureKey', null) - ); - - /** - * The frame rate of playback in frames per second (default 24 if duration is null) - * - * @name Phaser.Animations.Animation#frameRate - * @type {integer} - * @default 24 - * @since 3.0.0 - */ - this.frameRate = GetValue(config, 'frameRate', null); - - /** - * How long the animation should play for, in milliseconds. - * If the `frameRate` property has been set then it overrides this value, - * otherwise the `frameRate` is derived from `duration`. - * - * @name Phaser.Animations.Animation#duration - * @type {integer} - * @since 3.0.0 - */ - this.duration = GetValue(config, 'duration', null); - - if (this.duration === null && this.frameRate === null) - { - // No duration or frameRate given, use default frameRate of 24fps - this.frameRate = 24; - this.duration = (this.frameRate / this.frames.length) * 1000; - } - else if (this.duration && this.frameRate === null) - { - // 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 - this.frameRate = this.frames.length / (this.duration / 1000); - } - else - { - // 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) - this.duration = (this.frames.length / this.frameRate) * 1000; - } - - /** - * How many ms per frame, not including frame specific modifiers. - * - * @name Phaser.Animations.Animation#msPerFrame - * @type {integer} - * @since 3.0.0 - */ - this.msPerFrame = 1000 / this.frameRate; - - /** - * Skip frames if the time lags, or always advanced anyway? - * - * @name Phaser.Animations.Animation#skipMissedFrames - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.skipMissedFrames = GetValue(config, 'skipMissedFrames', true); - - /** - * The delay in ms before the playback will begin. - * - * @name Phaser.Animations.Animation#delay - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.delay = GetValue(config, 'delay', 0); - - /** - * Number of times to repeat the animation. Set to -1 to repeat forever. - * - * @name Phaser.Animations.Animation#repeat - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.repeat = GetValue(config, 'repeat', 0); - - /** - * The delay in ms before the a repeat play starts. - * - * @name Phaser.Animations.Animation#repeatDelay - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.repeatDelay = GetValue(config, 'repeatDelay', 0); - - /** - * Should the animation yoyo (reverse back down to the start) before repeating? - * - * @name Phaser.Animations.Animation#yoyo - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.yoyo = GetValue(config, 'yoyo', false); - - /** - * Should the GameObject's `visible` property be set to `true` when the animation starts to play? - * - * @name Phaser.Animations.Animation#showOnStart - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.showOnStart = GetValue(config, 'showOnStart', false); - - /** - * Should the GameObject's `visible` property be set to `false` when the animation finishes? - * - * @name Phaser.Animations.Animation#hideOnComplete - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.hideOnComplete = GetValue(config, 'hideOnComplete', false); - - /** - * Global pause. All Game Objects using this Animation instance are impacted by this property. - * - * @name Phaser.Animations.Animation#paused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.paused = false; - - this.manager.on(Events.PAUSE_ALL, this.pause, this); - this.manager.on(Events.RESUME_ALL, this.resume, this); - }, - - /** - * Add frames to the end of the animation. - * - * @method Phaser.Animations.Animation#addFrame - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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. - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - addFrame: function (config) - { - return this.addFrameAt(this.frames.length, config); - }, - - /** - * Add frame/s into the animation. - * - * @method Phaser.Animations.Animation#addFrameAt - * @since 3.0.0 - * - * @param {integer} index - The index to insert the frame at within the animation. - * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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. - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - addFrameAt: function (index, config) - { - var newFrames = this.getFrames(this.manager.textureManager, config); - - if (newFrames.length > 0) - { - if (index === 0) - { - this.frames = newFrames.concat(this.frames); - } - else if (index === this.frames.length) - { - this.frames = this.frames.concat(newFrames); - } - else - { - var pre = this.frames.slice(0, index); - var post = this.frames.slice(index); - - this.frames = pre.concat(newFrames, post); - } - - this.updateFrameSequence(); - } - - return this; - }, - - /** - * Check if the given frame index is valid. - * - * @method Phaser.Animations.Animation#checkFrame - * @since 3.0.0 - * - * @param {integer} index - The index to be checked. - * - * @return {boolean} `true` if the index is valid, otherwise `false`. - */ - checkFrame: function (index) - { - return (index >= 0 && index < this.frames.length); - }, - - /** - * Called internally when this Animation completes playback. - * Optionally, hides the parent Game Object, then stops playback. - * - * @method Phaser.Animations.Animation#completeAnimation - * @protected - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - */ - completeAnimation: function (component) - { - if (this.hideOnComplete) - { - component.parent.visible = false; - } - - component.stop(); - }, - - /** - * Called internally when this Animation first starts to play. - * Sets the accumulator and nextTick properties. - * - * @method Phaser.Animations.Animation#getFirstTick - * @protected - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - * @param {boolean} [includeDelay=true] - If `true` the Animation Components delay value will be added to the `nextTick` total. - */ - getFirstTick: function (component, includeDelay) - { - if (includeDelay === undefined) { includeDelay = true; } - - // When is the first update due? - component.accumulator = 0; - component.nextTick = component.msPerFrame + component.currentFrame.duration; - - if (includeDelay) - { - component.nextTick += component._delay; - } - }, - - /** - * Returns the AnimationFrame at the provided index - * - * @method Phaser.Animations.Animation#getFrameAt - * @protected - * @since 3.0.0 - * - * @param {integer} index - The index in the AnimationFrame array - * - * @return {Phaser.Animations.AnimationFrame} The frame at the index provided from the animation sequence - */ - getFrameAt: function (index) - { - return this.frames[index]; - }, - - /** - * 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. - */ - getFrames: function (textureManager, frames, defaultTextureKey) - { - var out = []; - var prev; - var animationFrame; - var index = 1; - var i; - var textureKey; - - // if frames is a string, we'll get all the frames from the texture manager as if it's a sprite sheet - if (typeof frames === 'string') - { - textureKey = frames; - - var texture = textureManager.get(textureKey); - var frameKeys = texture.getFrameNames(); - - frames = []; - - frameKeys.forEach(function (idx, value) - { - frames.push({ key: textureKey, frame: value }); - }); - } - - if (!Array.isArray(frames) || frames.length === 0) - { - return out; - } - - for (i = 0; i < frames.length; i++) - { - var item = frames[i]; - - var key = GetValue(item, 'key', defaultTextureKey); - - if (!key) - { - continue; - } - - // Could be an integer or a string - var frame = GetValue(item, 'frame', 0); - - // The actual texture frame - var textureFrame = textureManager.getFrame(key, frame); - - animationFrame = new Frame(key, frame, index, textureFrame); - - animationFrame.duration = GetValue(item, 'duration', 0); - - animationFrame.isFirst = (!prev); - - // The previously created animationFrame - if (prev) - { - prev.nextFrame = animationFrame; - - animationFrame.prevFrame = prev; - } - - out.push(animationFrame); - - prev = animationFrame; - - index++; - } - - if (out.length > 0) - { - animationFrame.isLast = true; - - // Link them end-to-end, so they loop - animationFrame.nextFrame = out[0]; - - out[0].prevFrame = animationFrame; - - // Generate the progress data - - var slice = 1 / (out.length - 1); - - for (i = 0; i < out.length; i++) - { - out[i].progress = i * slice; - } - } - - return out; - }, - - /** - * Called internally. Sets the accumulator and nextTick values of the current Animation. - * - * @method Phaser.Animations.Animation#getNextTick - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - */ - getNextTick: function (component) - { - // accumulator += delta * _timeScale - // after a large delta surge (perf issue for example) we need to adjust for it here - - // When is the next update due? - component.accumulator -= component.nextTick; - - component.nextTick = component.msPerFrame + component.currentFrame.duration; - }, - - /** - * Loads the Animation values into the Animation Component. - * - * @method Phaser.Animations.Animation#load - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to load values into. - * @param {integer} startFrame - The start frame of the animation to load. - */ - load: function (component, startFrame) - { - if (startFrame >= this.frames.length) - { - startFrame = 0; - } - - if (component.currentAnim !== this) - { - component.currentAnim = this; - - component.frameRate = this.frameRate; - component.duration = this.duration; - component.msPerFrame = this.msPerFrame; - component.skipMissedFrames = this.skipMissedFrames; - - component._delay = this.delay; - component._repeat = this.repeat; - component._repeatDelay = this.repeatDelay; - component._yoyo = this.yoyo; - } - - var frame = this.frames[startFrame]; - - if (startFrame === 0 && !component.forward) - { - frame = this.getLastFrame(); - } - - component.updateFrame(frame); - }, - - /** - * Returns the frame closest to the given progress value between 0 and 1. - * - * @method Phaser.Animations.Animation#getFrameByProgress - * @since 3.4.0 - * - * @param {number} value - A value between 0 and 1. - * - * @return {Phaser.Animations.AnimationFrame} The frame closest to the given progress value. - */ - getFrameByProgress: function (value) - { - value = Clamp(value, 0, 1); - - return FindClosestInSorted(value, this.frames, 'progress'); - }, - - /** - * Advance the animation frame. - * - * @method Phaser.Animations.Animation#nextFrame - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to advance. - */ - nextFrame: function (component) - { - var frame = component.currentFrame; - - // TODO: Add frame skip support - - if (frame.isLast) - { - // We're at the end of the animation - - // Yoyo? (happens before repeat) - if (component._yoyo) - { - this.handleYoyoFrame(component, false); - } - else if (component.repeatCounter > 0) - { - // Repeat (happens before complete) - - if (component._reverse && component.forward) - { - component.forward = false; - } - else - { - this.repeatAnimation(component); - } - } - else - { - this.completeAnimation(component); - } - } - else - { - this.updateAndGetNextTick(component, frame.nextFrame); - } - }, - - /** - * Handle the yoyo functionality in nextFrame and previousFrame methods. - * - * @method Phaser.Animations.Animation#handleYoyoFrame - * @private - * @since 3.12.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to advance. - * @param {boolean} isReverse - Is animation in reverse mode? (Default: false) - */ - handleYoyoFrame: function (component, isReverse) - { - if (!isReverse) { isReverse = false; } - - if (component._reverse === !isReverse && component.repeatCounter > 0) - { - component.forward = isReverse; - - this.repeatAnimation(component); - - return; - } - - if (component._reverse !== isReverse && component.repeatCounter === 0) - { - this.completeAnimation(component); - - return; - } - - component.forward = isReverse; - - var frame = (isReverse) ? component.currentFrame.nextFrame : component.currentFrame.prevFrame; - - this.updateAndGetNextTick(component, frame); - }, - - /** - * Returns the animation last frame. - * - * @method Phaser.Animations.Animation#getLastFrame - * @since 3.12.0 - * - * @return {Phaser.Animations.AnimationFrame} component - The Animation Last Frame. - */ - getLastFrame: function () - { - return this.frames[this.frames.length - 1]; - }, - - /** - * Called internally when the Animation is playing backwards. - * Sets the previous frame, causing a yoyo, repeat, complete or update, accordingly. - * - * @method Phaser.Animations.Animation#previousFrame - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - */ - previousFrame: function (component) - { - var frame = component.currentFrame; - - // TODO: Add frame skip support - - if (frame.isFirst) - { - // We're at the start of the animation - - if (component._yoyo) - { - this.handleYoyoFrame(component, true); - } - else if (component.repeatCounter > 0) - { - if (component._reverse && !component.forward) - { - component.currentFrame = this.getLastFrame(); - this.repeatAnimation(component); - } - else - { - // Repeat (happens before complete) - component.forward = true; - this.repeatAnimation(component); - } - } - else - { - this.completeAnimation(component); - } - } - else - { - this.updateAndGetNextTick(component, frame.prevFrame); - } - }, - - /** - * Update Frame and Wait next tick. - * - * @method Phaser.Animations.Animation#updateAndGetNextTick - * @private - * @since 3.12.0 - * - * @param {Phaser.Animations.AnimationFrame} frame - An Animation frame. - */ - updateAndGetNextTick: function (component, frame) - { - component.updateFrame(frame); - - this.getNextTick(component); - }, - - /** - * Removes the given AnimationFrame from this Animation instance. - * This is a global action. Any Game Object using this Animation will be impacted by this change. - * - * @method Phaser.Animations.Animation#removeFrame - * @since 3.0.0 - * - * @param {Phaser.Animations.AnimationFrame} frame - The AnimationFrame to be removed. - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - removeFrame: function (frame) - { - var index = this.frames.indexOf(frame); - - if (index !== -1) - { - this.removeFrameAt(index); - } - - return this; - }, - - /** - * Removes a frame from the AnimationFrame array at the provided index - * and updates the animation accordingly. - * - * @method Phaser.Animations.Animation#removeFrameAt - * @since 3.0.0 - * - * @param {integer} index - The index in the AnimationFrame array - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - removeFrameAt: function (index) - { - this.frames.splice(index, 1); - - this.updateFrameSequence(); - - return this; - }, - - /** - * Called internally during playback. Forces the animation to repeat, providing there are enough counts left - * in the repeat counter. - * - * @method Phaser.Animations.Animation#repeatAnimation - * @fires Phaser.Animations.Events#ANIMATION_REPEAT - * @fires Phaser.Animations.Events#SPRITE_ANIMATION_REPEAT - * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - */ - repeatAnimation: function (component) - { - if (component._pendingStop === 2) - { - return this.completeAnimation(component); - } - - if (component._repeatDelay > 0 && component.pendingRepeat === false) - { - component.pendingRepeat = true; - component.accumulator -= component.nextTick; - component.nextTick += component._repeatDelay; - } - else - { - component.repeatCounter--; - - component.updateFrame(component.currentFrame[(component.forward) ? 'nextFrame' : 'prevFrame']); - - if (component.isPlaying) - { - this.getNextTick(component); - - component.pendingRepeat = false; - - var frame = component.currentFrame; - var parent = component.parent; - - this.emit(Events.ANIMATION_REPEAT, this, frame); - - parent.emit(Events.SPRITE_ANIMATION_KEY_REPEAT + this.key, this, frame, component.repeatCounter, parent); - - parent.emit(Events.SPRITE_ANIMATION_REPEAT, this, frame, component.repeatCounter, parent); - } - } - }, - - /** - * Sets the texture frame the animation uses for rendering. - * - * @method Phaser.Animations.Animation#setFrame - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. - */ - setFrame: function (component) - { - // Work out which frame should be set next on the child, and set it - if (component.forward) - { - this.nextFrame(component); - } - else - { - this.previousFrame(component); - } - }, - - /** - * Converts the animation data to JSON. - * - * @method Phaser.Animations.Animation#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Animations.JSONAnimation} The resulting JSONAnimation formatted object. - */ - toJSON: function () - { - var output = { - key: this.key, - type: this.type, - frames: [], - frameRate: this.frameRate, - duration: this.duration, - skipMissedFrames: this.skipMissedFrames, - delay: this.delay, - repeat: this.repeat, - repeatDelay: this.repeatDelay, - yoyo: this.yoyo, - showOnStart: this.showOnStart, - hideOnComplete: this.hideOnComplete - }; - - this.frames.forEach(function (frame) - { - output.frames.push(frame.toJSON()); - }); - - return output; - }, - - /** - * Called internally whenever frames are added to, or removed from, this Animation. - * - * @method Phaser.Animations.Animation#updateFrameSequence - * @since 3.0.0 - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - updateFrameSequence: function () - { - var len = this.frames.length; - var slice = 1 / (len - 1); - - var frame; - - for (var i = 0; i < len; i++) - { - frame = this.frames[i]; - - frame.index = i + 1; - frame.isFirst = false; - frame.isLast = false; - frame.progress = i * slice; - - if (i === 0) - { - frame.isFirst = true; - - if (len === 1) - { - frame.isLast = true; - frame.nextFrame = frame; - frame.prevFrame = frame; - } - else - { - frame.isLast = false; - frame.prevFrame = this.frames[len - 1]; - frame.nextFrame = this.frames[i + 1]; - } - } - else if (i === len - 1 && len > 1) - { - frame.isLast = true; - frame.prevFrame = this.frames[len - 2]; - frame.nextFrame = this.frames[0]; - } - else if (len > 1) - { - frame.prevFrame = this.frames[i - 1]; - frame.nextFrame = this.frames[i + 1]; - } - } - - return this; - }, - - /** - * Pauses playback of this Animation. The paused state is set immediately. - * - * @method Phaser.Animations.Animation#pause - * @since 3.0.0 - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - pause: function () - { - this.paused = true; - - return this; - }, - - /** - * Resumes playback of this Animation. The paused state is reset immediately. - * - * @method Phaser.Animations.Animation#resume - * @since 3.0.0 - * - * @return {Phaser.Animations.Animation} This Animation object. - */ - resume: function () - { - this.paused = false; - - return this; - }, - - /** - * Destroys this Animation instance. It will remove all event listeners, - * remove this animation and its key from the global Animation Manager, - * and then destroy all Animation Frames in turn. - * - * @method Phaser.Animations.Animation#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.removeAllListeners(); - - this.manager.off(Events.PAUSE_ALL, this.pause, this); - this.manager.off(Events.RESUME_ALL, this.resume, this); - - this.manager.remove(this.key); - - for (var i = 0; i < this.frames.length; i++) - { - this.frames[i].destroy(); - } - - this.frames = []; - - this.manager = null; - } - -}); - -module.exports = Animation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../math/Clamp'); +var Class = require('../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var FindClosestInSorted = require('../utils/array/FindClosestInSorted'); +var Frame = require('./AnimationFrame'); +var GetValue = require('../utils/object/GetValue'); + +/** + * @classdesc + * A Frame based Animation. + * + * This consists of a key, some default values (like the frame rate) and a bunch of Frame objects. + * + * The Animation Manager creates these. Game Objects don't own an instance of these directly. + * Game Objects have the Animation Component, which are like playheads to global Animations (these objects) + * So multiple Game Objects can have playheads all pointing to this one Animation instance. + * + * @class Animation + * @memberof Phaser.Animations + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationManager} manager - A reference to the global Animation Manager + * @param {string} key - The unique identifying string for this animation. + * @param {Phaser.Types.Animations.Animation} config - The Animation configuration. + */ +var Animation = new Class({ + + Extends: EventEmitter, + + initialize: + + function Animation (manager, key, config) + { + EventEmitter.call(this); + + /** + * A reference to the global Animation Manager. + * + * @name Phaser.Animations.Animation#manager + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The unique identifying string for this animation. + * + * @name Phaser.Animations.Animation#key + * @type {string} + * @since 3.0.0 + */ + this.key = key; + + /** + * A frame based animation (as opposed to a bone based animation) + * + * @name Phaser.Animations.Animation#type + * @type {string} + * @default frame + * @since 3.0.0 + */ + this.type = 'frame'; + + /** + * Extract all the frame data into the frames array. + * + * @name Phaser.Animations.Animation#frames + * @type {Phaser.Animations.AnimationFrame[]} + * @since 3.0.0 + */ + this.frames = this.getFrames( + manager.textureManager, + GetValue(config, 'frames', []), + GetValue(config, 'defaultTextureKey', null) + ); + + /** + * The frame rate of playback in frames per second (default 24 if duration is null) + * + * @name Phaser.Animations.Animation#frameRate + * @type {integer} + * @default 24 + * @since 3.0.0 + */ + this.frameRate = GetValue(config, 'frameRate', null); + + /** + * How long the animation should play for, in milliseconds. + * If the `frameRate` property has been set then it overrides this value, + * otherwise the `frameRate` is derived from `duration`. + * + * @name Phaser.Animations.Animation#duration + * @type {integer} + * @since 3.0.0 + */ + this.duration = GetValue(config, 'duration', null); + + if (this.duration === null && this.frameRate === null) + { + // No duration or frameRate given, use default frameRate of 24fps + this.frameRate = 24; + this.duration = (this.frameRate / this.frames.length) * 1000; + } + else if (this.duration && this.frameRate === null) + { + // 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 + this.frameRate = this.frames.length / (this.duration / 1000); + } + else + { + // 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) + this.duration = (this.frames.length / this.frameRate) * 1000; + } + + /** + * How many ms per frame, not including frame specific modifiers. + * + * @name Phaser.Animations.Animation#msPerFrame + * @type {integer} + * @since 3.0.0 + */ + this.msPerFrame = 1000 / this.frameRate; + + /** + * Skip frames if the time lags, or always advanced anyway? + * + * @name Phaser.Animations.Animation#skipMissedFrames + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.skipMissedFrames = GetValue(config, 'skipMissedFrames', true); + + /** + * The delay in ms before the playback will begin. + * + * @name Phaser.Animations.Animation#delay + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.delay = GetValue(config, 'delay', 0); + + /** + * Number of times to repeat the animation. Set to -1 to repeat forever. + * + * @name Phaser.Animations.Animation#repeat + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.repeat = GetValue(config, 'repeat', 0); + + /** + * The delay in ms before the a repeat play starts. + * + * @name Phaser.Animations.Animation#repeatDelay + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.repeatDelay = GetValue(config, 'repeatDelay', 0); + + /** + * Should the animation yoyo (reverse back down to the start) before repeating? + * + * @name Phaser.Animations.Animation#yoyo + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.yoyo = GetValue(config, 'yoyo', false); + + /** + * Should the GameObject's `visible` property be set to `true` when the animation starts to play? + * + * @name Phaser.Animations.Animation#showOnStart + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.showOnStart = GetValue(config, 'showOnStart', false); + + /** + * Should the GameObject's `visible` property be set to `false` when the animation finishes? + * + * @name Phaser.Animations.Animation#hideOnComplete + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.hideOnComplete = GetValue(config, 'hideOnComplete', false); + + /** + * Global pause. All Game Objects using this Animation instance are impacted by this property. + * + * @name Phaser.Animations.Animation#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + this.manager.on(Events.PAUSE_ALL, this.pause, this); + this.manager.on(Events.RESUME_ALL, this.resume, this); + }, + + /** + * Add frames to the end of the animation. + * + * @method Phaser.Animations.Animation#addFrame + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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. + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + addFrame: function (config) + { + return this.addFrameAt(this.frames.length, config); + }, + + /** + * Add frame/s into the animation. + * + * @method Phaser.Animations.Animation#addFrameAt + * @since 3.0.0 + * + * @param {integer} index - The index to insert the frame at within the animation. + * @param {(string|Phaser.Types.Animations.AnimationFrame[])} config - 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. + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + addFrameAt: function (index, config) + { + var newFrames = this.getFrames(this.manager.textureManager, config); + + if (newFrames.length > 0) + { + if (index === 0) + { + this.frames = newFrames.concat(this.frames); + } + else if (index === this.frames.length) + { + this.frames = this.frames.concat(newFrames); + } + else + { + var pre = this.frames.slice(0, index); + var post = this.frames.slice(index); + + this.frames = pre.concat(newFrames, post); + } + + this.updateFrameSequence(); + } + + return this; + }, + + /** + * Check if the given frame index is valid. + * + * @method Phaser.Animations.Animation#checkFrame + * @since 3.0.0 + * + * @param {integer} index - The index to be checked. + * + * @return {boolean} `true` if the index is valid, otherwise `false`. + */ + checkFrame: function (index) + { + return (index >= 0 && index < this.frames.length); + }, + + /** + * Called internally when this Animation completes playback. + * Optionally, hides the parent Game Object, then stops playback. + * + * @method Phaser.Animations.Animation#completeAnimation + * @protected + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + */ + completeAnimation: function (component) + { + if (this.hideOnComplete) + { + component.parent.visible = false; + } + + component.stop(); + }, + + /** + * Called internally when this Animation first starts to play. + * Sets the accumulator and nextTick properties. + * + * @method Phaser.Animations.Animation#getFirstTick + * @protected + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + * @param {boolean} [includeDelay=true] - If `true` the Animation Components delay value will be added to the `nextTick` total. + */ + getFirstTick: function (component, includeDelay) + { + if (includeDelay === undefined) { includeDelay = true; } + + // When is the first update due? + component.accumulator = 0; + component.nextTick = component.msPerFrame + component.currentFrame.duration; + + if (includeDelay) + { + component.nextTick += component._delay; + } + }, + + /** + * Returns the AnimationFrame at the provided index + * + * @method Phaser.Animations.Animation#getFrameAt + * @protected + * @since 3.0.0 + * + * @param {integer} index - The index in the AnimationFrame array + * + * @return {Phaser.Animations.AnimationFrame} The frame at the index provided from the animation sequence + */ + getFrameAt: function (index) + { + return this.frames[index]; + }, + + /** + * 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. + */ + getFrames: function (textureManager, frames, defaultTextureKey) + { + var out = []; + var prev; + var animationFrame; + var index = 1; + var i; + var textureKey; + + // if frames is a string, we'll get all the frames from the texture manager as if it's a sprite sheet + if (typeof frames === 'string') + { + textureKey = frames; + + var texture = textureManager.get(textureKey); + var frameKeys = texture.getFrameNames(); + + frames = []; + + frameKeys.forEach(function (idx, value) + { + frames.push({ key: textureKey, frame: value }); + }); + } + + if (!Array.isArray(frames) || frames.length === 0) + { + return out; + } + + for (i = 0; i < frames.length; i++) + { + var item = frames[i]; + + var key = GetValue(item, 'key', defaultTextureKey); + + if (!key) + { + continue; + } + + // Could be an integer or a string + var frame = GetValue(item, 'frame', 0); + + // The actual texture frame + var textureFrame = textureManager.getFrame(key, frame); + + animationFrame = new Frame(key, frame, index, textureFrame); + + animationFrame.duration = GetValue(item, 'duration', 0); + + animationFrame.isFirst = (!prev); + + // The previously created animationFrame + if (prev) + { + prev.nextFrame = animationFrame; + + animationFrame.prevFrame = prev; + } + + out.push(animationFrame); + + prev = animationFrame; + + index++; + } + + if (out.length > 0) + { + animationFrame.isLast = true; + + // Link them end-to-end, so they loop + animationFrame.nextFrame = out[0]; + + out[0].prevFrame = animationFrame; + + // Generate the progress data + + var slice = 1 / (out.length - 1); + + for (i = 0; i < out.length; i++) + { + out[i].progress = i * slice; + } + } + + return out; + }, + + /** + * Called internally. Sets the accumulator and nextTick values of the current Animation. + * + * @method Phaser.Animations.Animation#getNextTick + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + */ + getNextTick: function (component) + { + // accumulator += delta * _timeScale + // after a large delta surge (perf issue for example) we need to adjust for it here + + // When is the next update due? + component.accumulator -= component.nextTick; + + component.nextTick = component.msPerFrame + component.currentFrame.duration; + }, + + /** + * Loads the Animation values into the Animation Component. + * + * @method Phaser.Animations.Animation#load + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to load values into. + * @param {integer} startFrame - The start frame of the animation to load. + */ + load: function (component, startFrame) + { + if (startFrame >= this.frames.length) + { + startFrame = 0; + } + + if (component.currentAnim !== this) + { + component.currentAnim = this; + + component.frameRate = this.frameRate; + component.duration = this.duration; + component.msPerFrame = this.msPerFrame; + component.skipMissedFrames = this.skipMissedFrames; + + component._delay = this.delay; + component._repeat = this.repeat; + component._repeatDelay = this.repeatDelay; + component._yoyo = this.yoyo; + } + + var frame = this.frames[startFrame]; + + if (startFrame === 0 && !component.forward) + { + frame = this.getLastFrame(); + } + + component.updateFrame(frame); + }, + + /** + * Returns the frame closest to the given progress value between 0 and 1. + * + * @method Phaser.Animations.Animation#getFrameByProgress + * @since 3.4.0 + * + * @param {number} value - A value between 0 and 1. + * + * @return {Phaser.Animations.AnimationFrame} The frame closest to the given progress value. + */ + getFrameByProgress: function (value) + { + value = Clamp(value, 0, 1); + + return FindClosestInSorted(value, this.frames, 'progress'); + }, + + /** + * Advance the animation frame. + * + * @method Phaser.Animations.Animation#nextFrame + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to advance. + */ + nextFrame: function (component) + { + var frame = component.currentFrame; + + // TODO: Add frame skip support + + if (frame.isLast) + { + // We're at the end of the animation + + // Yoyo? (happens before repeat) + if (component._yoyo) + { + this.handleYoyoFrame(component, false); + } + else if (component.repeatCounter > 0) + { + // Repeat (happens before complete) + + if (component._reverse && component.forward) + { + component.forward = false; + } + else + { + this.repeatAnimation(component); + } + } + else + { + this.completeAnimation(component); + } + } + else + { + this.updateAndGetNextTick(component, frame.nextFrame); + } + }, + + /** + * Handle the yoyo functionality in nextFrame and previousFrame methods. + * + * @method Phaser.Animations.Animation#handleYoyoFrame + * @private + * @since 3.12.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component to advance. + * @param {boolean} isReverse - Is animation in reverse mode? (Default: false) + */ + handleYoyoFrame: function (component, isReverse) + { + if (!isReverse) { isReverse = false; } + + if (component._reverse === !isReverse && component.repeatCounter > 0) + { + component.forward = isReverse; + + this.repeatAnimation(component); + + return; + } + + if (component._reverse !== isReverse && component.repeatCounter === 0) + { + this.completeAnimation(component); + + return; + } + + component.forward = isReverse; + + var frame = (isReverse) ? component.currentFrame.nextFrame : component.currentFrame.prevFrame; + + this.updateAndGetNextTick(component, frame); + }, + + /** + * Returns the animation last frame. + * + * @method Phaser.Animations.Animation#getLastFrame + * @since 3.12.0 + * + * @return {Phaser.Animations.AnimationFrame} component - The Animation Last Frame. + */ + getLastFrame: function () + { + return this.frames[this.frames.length - 1]; + }, + + /** + * Called internally when the Animation is playing backwards. + * Sets the previous frame, causing a yoyo, repeat, complete or update, accordingly. + * + * @method Phaser.Animations.Animation#previousFrame + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + */ + previousFrame: function (component) + { + var frame = component.currentFrame; + + // TODO: Add frame skip support + + if (frame.isFirst) + { + // We're at the start of the animation + + if (component._yoyo) + { + this.handleYoyoFrame(component, true); + } + else if (component.repeatCounter > 0) + { + if (component._reverse && !component.forward) + { + component.currentFrame = this.getLastFrame(); + this.repeatAnimation(component); + } + else + { + // Repeat (happens before complete) + component.forward = true; + this.repeatAnimation(component); + } + } + else + { + this.completeAnimation(component); + } + } + else + { + this.updateAndGetNextTick(component, frame.prevFrame); + } + }, + + /** + * Update Frame and Wait next tick. + * + * @method Phaser.Animations.Animation#updateAndGetNextTick + * @private + * @since 3.12.0 + * + * @param {Phaser.Animations.AnimationFrame} frame - An Animation frame. + */ + updateAndGetNextTick: function (component, frame) + { + component.updateFrame(frame); + + this.getNextTick(component); + }, + + /** + * Removes the given AnimationFrame from this Animation instance. + * This is a global action. Any Game Object using this Animation will be impacted by this change. + * + * @method Phaser.Animations.Animation#removeFrame + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} frame - The AnimationFrame to be removed. + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + removeFrame: function (frame) + { + var index = this.frames.indexOf(frame); + + if (index !== -1) + { + this.removeFrameAt(index); + } + + return this; + }, + + /** + * Removes a frame from the AnimationFrame array at the provided index + * and updates the animation accordingly. + * + * @method Phaser.Animations.Animation#removeFrameAt + * @since 3.0.0 + * + * @param {integer} index - The index in the AnimationFrame array + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + removeFrameAt: function (index) + { + this.frames.splice(index, 1); + + this.updateFrameSequence(); + + return this; + }, + + /** + * Called internally during playback. Forces the animation to repeat, providing there are enough counts left + * in the repeat counter. + * + * @method Phaser.Animations.Animation#repeatAnimation + * @fires Phaser.Animations.Events#ANIMATION_REPEAT + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_REPEAT + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + */ + repeatAnimation: function (component) + { + if (component._pendingStop === 2) + { + return this.completeAnimation(component); + } + + if (component._repeatDelay > 0 && component.pendingRepeat === false) + { + component.pendingRepeat = true; + component.accumulator -= component.nextTick; + component.nextTick += component._repeatDelay; + } + else + { + component.repeatCounter--; + + component.updateFrame(component.currentFrame[(component.forward) ? 'nextFrame' : 'prevFrame']); + + if (component.isPlaying) + { + this.getNextTick(component); + + component.pendingRepeat = false; + + var frame = component.currentFrame; + var parent = component.parent; + + this.emit(Events.ANIMATION_REPEAT, this, frame); + + parent.emit(Events.SPRITE_ANIMATION_KEY_REPEAT + this.key, this, frame, component.repeatCounter, parent); + + parent.emit(Events.SPRITE_ANIMATION_REPEAT, this, frame, component.repeatCounter, parent); + } + } + }, + + /** + * Sets the texture frame the animation uses for rendering. + * + * @method Phaser.Animations.Animation#setFrame + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.Animation} component - The Animation Component belonging to the Game Object invoking this call. + */ + setFrame: function (component) + { + // Work out which frame should be set next on the child, and set it + if (component.forward) + { + this.nextFrame(component); + } + else + { + this.previousFrame(component); + } + }, + + /** + * Converts the animation data to JSON. + * + * @method Phaser.Animations.Animation#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Animations.JSONAnimation} The resulting JSONAnimation formatted object. + */ + toJSON: function () + { + var output = { + key: this.key, + type: this.type, + frames: [], + frameRate: this.frameRate, + duration: this.duration, + skipMissedFrames: this.skipMissedFrames, + delay: this.delay, + repeat: this.repeat, + repeatDelay: this.repeatDelay, + yoyo: this.yoyo, + showOnStart: this.showOnStart, + hideOnComplete: this.hideOnComplete + }; + + this.frames.forEach(function (frame) + { + output.frames.push(frame.toJSON()); + }); + + return output; + }, + + /** + * Called internally whenever frames are added to, or removed from, this Animation. + * + * @method Phaser.Animations.Animation#updateFrameSequence + * @since 3.0.0 + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + updateFrameSequence: function () + { + var len = this.frames.length; + var slice = 1 / (len - 1); + + var frame; + + for (var i = 0; i < len; i++) + { + frame = this.frames[i]; + + frame.index = i + 1; + frame.isFirst = false; + frame.isLast = false; + frame.progress = i * slice; + + if (i === 0) + { + frame.isFirst = true; + + if (len === 1) + { + frame.isLast = true; + frame.nextFrame = frame; + frame.prevFrame = frame; + } + else + { + frame.isLast = false; + frame.prevFrame = this.frames[len - 1]; + frame.nextFrame = this.frames[i + 1]; + } + } + else if (i === len - 1 && len > 1) + { + frame.isLast = true; + frame.prevFrame = this.frames[len - 2]; + frame.nextFrame = this.frames[0]; + } + else if (len > 1) + { + frame.prevFrame = this.frames[i - 1]; + frame.nextFrame = this.frames[i + 1]; + } + } + + return this; + }, + + /** + * Pauses playback of this Animation. The paused state is set immediately. + * + * @method Phaser.Animations.Animation#pause + * @since 3.0.0 + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + pause: function () + { + this.paused = true; + + return this; + }, + + /** + * Resumes playback of this Animation. The paused state is reset immediately. + * + * @method Phaser.Animations.Animation#resume + * @since 3.0.0 + * + * @return {Phaser.Animations.Animation} This Animation object. + */ + resume: function () + { + this.paused = false; + + return this; + }, + + /** + * Destroys this Animation instance. It will remove all event listeners, + * remove this animation and its key from the global Animation Manager, + * and then destroy all Animation Frames in turn. + * + * @method Phaser.Animations.Animation#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.manager.off(Events.PAUSE_ALL, this.pause, this); + this.manager.off(Events.RESUME_ALL, this.resume, this); + + this.manager.remove(this.key); + + for (var i = 0; i < this.frames.length; i++) + { + this.frames[i].destroy(); + } + + this.frames = []; + + this.manager = null; + } + +}); + +module.exports = Animation; diff --git a/src/animations/AnimationFrame.js b/src/animations/AnimationFrame.js index 49b4dc752..f2d7767b3 100644 --- a/src/animations/AnimationFrame.js +++ b/src/animations/AnimationFrame.js @@ -1,168 +1,168 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A single frame in an Animation sequence. - * - * An AnimationFrame consists of a reference to the Texture it uses for rendering, references to other - * frames in the animation, and index data. It also has the ability to modify the animation timing. - * - * AnimationFrames are generated automatically by the Animation class. - * - * @class AnimationFrame - * @memberof Phaser.Animations - * @constructor - * @since 3.0.0 - * - * @param {string} textureKey - The key of the Texture this AnimationFrame uses. - * @param {(string|integer)} textureFrame - The key of the Frame within the Texture that this AnimationFrame uses. - * @param {integer} index - The index of this AnimationFrame within the Animation sequence. - * @param {Phaser.Textures.Frame} frame - A reference to the Texture Frame this AnimationFrame uses for rendering. - */ -var AnimationFrame = new Class({ - - initialize: - - function AnimationFrame (textureKey, textureFrame, index, frame) - { - /** - * The key of the Texture this AnimationFrame uses. - * - * @name Phaser.Animations.AnimationFrame#textureKey - * @type {string} - * @since 3.0.0 - */ - this.textureKey = textureKey; - - /** - * The key of the Frame within the Texture that this AnimationFrame uses. - * - * @name Phaser.Animations.AnimationFrame#textureFrame - * @type {(string|integer)} - * @since 3.0.0 - */ - this.textureFrame = textureFrame; - - /** - * The index of this AnimationFrame within the Animation sequence. - * - * @name Phaser.Animations.AnimationFrame#index - * @type {integer} - * @since 3.0.0 - */ - this.index = index; - - /** - * A reference to the Texture Frame this AnimationFrame uses for rendering. - * - * @name Phaser.Animations.AnimationFrame#frame - * @type {Phaser.Textures.Frame} - * @since 3.0.0 - */ - this.frame = frame; - - /** - * Is this the first frame in an animation sequence? - * - * @name Phaser.Animations.AnimationFrame#isFirst - * @type {boolean} - * @default false - * @readonly - * @since 3.0.0 - */ - this.isFirst = false; - - /** - * Is this the last frame in an animation sequence? - * - * @name Phaser.Animations.AnimationFrame#isLast - * @type {boolean} - * @default false - * @readonly - * @since 3.0.0 - */ - this.isLast = false; - - /** - * A reference to the AnimationFrame that comes before this one in the animation, if any. - * - * @name Phaser.Animations.AnimationFrame#prevFrame - * @type {?Phaser.Animations.AnimationFrame} - * @default null - * @readonly - * @since 3.0.0 - */ - this.prevFrame = null; - - /** - * A reference to the AnimationFrame that comes after this one in the animation, if any. - * - * @name Phaser.Animations.AnimationFrame#nextFrame - * @type {?Phaser.Animations.AnimationFrame} - * @default null - * @readonly - * @since 3.0.0 - */ - this.nextFrame = null; - - /** - * Additional time (in ms) that this frame should appear for during playback. - * The value is added onto the msPerFrame set by the animation. - * - * @name Phaser.Animations.AnimationFrame#duration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.duration = 0; - - /** - * What % through the animation does this frame come? - * This value is generated when the animation is created and cached here. - * - * @name Phaser.Animations.AnimationFrame#progress - * @type {number} - * @default 0 - * @readonly - * @since 3.0.0 - */ - this.progress = 0; - }, - - /** - * Generates a JavaScript object suitable for converting to JSON. - * - * @method Phaser.Animations.AnimationFrame#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Animations.JSONAnimationFrame} The AnimationFrame data. - */ - toJSON: function () - { - return { - key: this.textureKey, - frame: this.textureFrame, - duration: this.duration - }; - }, - - /** - * Destroys this object by removing references to external resources and callbacks. - * - * @method Phaser.Animations.AnimationFrame#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.frame = undefined; - } - -}); - -module.exports = AnimationFrame; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A single frame in an Animation sequence. + * + * An AnimationFrame consists of a reference to the Texture it uses for rendering, references to other + * frames in the animation, and index data. It also has the ability to modify the animation timing. + * + * AnimationFrames are generated automatically by the Animation class. + * + * @class AnimationFrame + * @memberof Phaser.Animations + * @constructor + * @since 3.0.0 + * + * @param {string} textureKey - The key of the Texture this AnimationFrame uses. + * @param {(string|integer)} textureFrame - The key of the Frame within the Texture that this AnimationFrame uses. + * @param {integer} index - The index of this AnimationFrame within the Animation sequence. + * @param {Phaser.Textures.Frame} frame - A reference to the Texture Frame this AnimationFrame uses for rendering. + */ +var AnimationFrame = new Class({ + + initialize: + + function AnimationFrame (textureKey, textureFrame, index, frame) + { + /** + * The key of the Texture this AnimationFrame uses. + * + * @name Phaser.Animations.AnimationFrame#textureKey + * @type {string} + * @since 3.0.0 + */ + this.textureKey = textureKey; + + /** + * The key of the Frame within the Texture that this AnimationFrame uses. + * + * @name Phaser.Animations.AnimationFrame#textureFrame + * @type {(string|integer)} + * @since 3.0.0 + */ + this.textureFrame = textureFrame; + + /** + * The index of this AnimationFrame within the Animation sequence. + * + * @name Phaser.Animations.AnimationFrame#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * A reference to the Texture Frame this AnimationFrame uses for rendering. + * + * @name Phaser.Animations.AnimationFrame#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + this.frame = frame; + + /** + * Is this the first frame in an animation sequence? + * + * @name Phaser.Animations.AnimationFrame#isFirst + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isFirst = false; + + /** + * Is this the last frame in an animation sequence? + * + * @name Phaser.Animations.AnimationFrame#isLast + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isLast = false; + + /** + * A reference to the AnimationFrame that comes before this one in the animation, if any. + * + * @name Phaser.Animations.AnimationFrame#prevFrame + * @type {?Phaser.Animations.AnimationFrame} + * @default null + * @readonly + * @since 3.0.0 + */ + this.prevFrame = null; + + /** + * A reference to the AnimationFrame that comes after this one in the animation, if any. + * + * @name Phaser.Animations.AnimationFrame#nextFrame + * @type {?Phaser.Animations.AnimationFrame} + * @default null + * @readonly + * @since 3.0.0 + */ + this.nextFrame = null; + + /** + * Additional time (in ms) that this frame should appear for during playback. + * The value is added onto the msPerFrame set by the animation. + * + * @name Phaser.Animations.AnimationFrame#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * What % through the animation does this frame come? + * This value is generated when the animation is created and cached here. + * + * @name Phaser.Animations.AnimationFrame#progress + * @type {number} + * @default 0 + * @readonly + * @since 3.0.0 + */ + this.progress = 0; + }, + + /** + * Generates a JavaScript object suitable for converting to JSON. + * + * @method Phaser.Animations.AnimationFrame#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Animations.JSONAnimationFrame} The AnimationFrame data. + */ + toJSON: function () + { + return { + key: this.textureKey, + frame: this.textureFrame, + duration: this.duration + }; + }, + + /** + * Destroys this object by removing references to external resources and callbacks. + * + * @method Phaser.Animations.AnimationFrame#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.frame = undefined; + } + +}); + +module.exports = AnimationFrame; diff --git a/src/animations/AnimationManager.js b/src/animations/AnimationManager.js index 9cc54353a..15b988b29 100644 --- a/src/animations/AnimationManager.js +++ b/src/animations/AnimationManager.js @@ -1,676 +1,676 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Animation = require('./Animation'); -var Class = require('../utils/Class'); -var CustomMap = require('../structs/Map'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GameEvents = require('../core/events'); -var GetValue = require('../utils/object/GetValue'); -var Pad = require('../utils/string/Pad'); - -/** - * @classdesc - * The Animation Manager. - * - * Animations are managed by the global Animation Manager. This is a singleton class that is - * responsible for creating and delivering animations and their corresponding data to all Game Objects. - * Unlike plugins it is owned by the Game instance, not the Scene. - * - * Sprites and other Game Objects get the data they need from the AnimationManager. - * - * @class AnimationManager - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Animations - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - A reference to the Phaser.Game instance. - */ -var AnimationManager = new Class({ - - Extends: EventEmitter, - - initialize: - - function AnimationManager (game) - { - EventEmitter.call(this); - - /** - * A reference to the Phaser.Game instance. - * - * @name Phaser.Animations.AnimationManager#game - * @type {Phaser.Game} - * @protected - * @since 3.0.0 - */ - this.game = game; - - /** - * A reference to the Texture Manager. - * - * @name Phaser.Animations.AnimationManager#textureManager - * @type {Phaser.Textures.TextureManager} - * @protected - * @since 3.0.0 - */ - this.textureManager = null; - - /** - * The global time scale of the Animation Manager. - * - * This scales the time delta between two frames, thus influencing the speed of time for the Animation Manager. - * - * @name Phaser.Animations.AnimationManager#globalTimeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.globalTimeScale = 1; - - /** - * The Animations registered in the Animation Manager. - * - * This map should be modified with the {@link #add} and {@link #create} methods of the Animation Manager. - * - * @name Phaser.Animations.AnimationManager#anims - * @type {Phaser.Structs.Map.} - * @protected - * @since 3.0.0 - */ - this.anims = new CustomMap(); - - /** - * Whether the Animation Manager is paused along with all of its Animations. - * - * @name Phaser.Animations.AnimationManager#paused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.paused = false; - - /** - * The name of this Animation Manager. - * - * @name Phaser.Animations.AnimationManager#name - * @type {string} - * @since 3.0.0 - */ - this.name = 'AnimationManager'; - - game.events.once(GameEvents.BOOT, this.boot, this); - }, - - /** - * Registers event listeners after the Game boots. - * - * @method Phaser.Animations.AnimationManager#boot - * @listens Phaser.Core.Events#DESTROY - * @since 3.0.0 - */ - boot: function () - { - this.textureManager = this.game.textures; - - this.game.events.once(GameEvents.DESTROY, this.destroy, this); - }, - - /** - * Adds an existing Animation to the Animation Manager. - * - * @method Phaser.Animations.AnimationManager#add - * @fires Phaser.Animations.Events#ADD_ANIMATION - * @since 3.0.0 - * - * @param {string} key - The key under which the Animation should be added. The Animation will be updated with it. Must be unique. - * @param {Phaser.Animations.Animation} animation - The Animation which should be added to the Animation Manager. - * - * @return {Phaser.Animations.AnimationManager} This Animation Manager. - */ - add: function (key, animation) - { - if (this.anims.has(key)) - { - console.warn('Animation key exists: ' + key); - - return; - } - - animation.key = key; - - this.anims.set(key, animation); - - this.emit(Events.ADD_ANIMATION, key, animation); - - return this; - }, - - /** - * Checks to see if the given key is already in use within the Animation Manager or not. - * - * Animations are global. Keys created in one scene can be used from any other Scene in your game. They are not Scene specific. - * - * @method Phaser.Animations.AnimationManager#exists - * @since 3.16.0 - * - * @param {string} key - The key of the Animation to check. - * - * @return {boolean} `true` if the Animation already exists in the Animation Manager, or `false` if the key is available. - */ - exists: function (key) - { - return this.anims.has(key); - }, - - /** - * Creates a new Animation and adds it to the Animation Manager. - * - * Animations are global. Once created, you can use them in any Scene in your game. They are not Scene specific. - * - * If an invalid key is given this method will return `false`. - * - * If you pass the key of an animation that already exists in the Animation Manager, that animation will be returned. - * - * A brand new animation is only created if the key is valid and not already in use. - * - * If you wish to re-use an existing key, call `AnimationManager.remove` first, then this method. - * - * @method Phaser.Animations.AnimationManager#create - * @fires Phaser.Animations.Events#ADD_ANIMATION - * @since 3.0.0 - * - * @param {Phaser.Types.Animations.Animation} config - The configuration settings for the Animation. - * - * @return {(Phaser.Animations.Animation|false)} The Animation that was created, or `false` is the key is already in use. - */ - create: function (config) - { - var key = config.key; - - var anim = false; - - if (key) - { - anim = this.get(key); - - if (!anim) - { - anim = new Animation(this, key, config); - - this.anims.set(key, anim); - - this.emit(Events.ADD_ANIMATION, key, anim); - } - } - - return anim; - }, - - /** - * Loads this Animation Manager's Animations and settings from a JSON object. - * - * @method Phaser.Animations.AnimationManager#fromJSON - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Animations.JSONAnimations|Phaser.Types.Animations.JSONAnimation)} data - The JSON object to parse. - * @param {boolean} [clearCurrentAnimations=false] - If set to `true`, the current animations will be removed (`anims.clear()`). If set to `false` (default), the animations in `data` will be added. - * - * @return {Phaser.Animations.Animation[]} An array containing all of the Animation objects that were created as a result of this call. - */ - fromJSON: function (data, clearCurrentAnimations) - { - if (clearCurrentAnimations === undefined) { clearCurrentAnimations = false; } - - if (clearCurrentAnimations) - { - this.anims.clear(); - } - - // Do we have a String (i.e. from JSON, or an Object?) - if (typeof data === 'string') - { - data = JSON.parse(data); - } - - var output = []; - - // Array of animations, or a single animation? - if (data.hasOwnProperty('anims') && Array.isArray(data.anims)) - { - for (var i = 0; i < data.anims.length; i++) - { - output.push(this.create(data.anims[i])); - } - - if (data.hasOwnProperty('globalTimeScale')) - { - this.globalTimeScale = data.globalTimeScale; - } - } - else if (data.hasOwnProperty('key') && data.type === 'frame') - { - output.push(this.create(data)); - } - - return output; - }, - - /** - * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. - * - * Generates objects with string based frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNames}. - * - * It's a helper method, designed to make it easier for you to extract all of the frame names from texture atlases. - * If you're working with a sprite sheet, see the `generateFrameNumbers` method instead. - * - * Example: - * - * If you have a texture atlases loaded called `gems` and it contains 6 frames called `ruby_0001`, `ruby_0002`, and so on, - * then you can call this method using: `this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 })`. - * - * The `end` value tells it to look for 6 frames, incrementally numbered, all starting with the prefix `ruby_`. The `zeroPad` - * value tells it how many zeroes pad out the numbers. To create an animation using this method, you can do: - * - * ```javascript - * this.anims.create({ - * key: 'ruby', - * repeat: -1, - * frames: this.anims.generateFrameNames('gems', { - * prefix: 'ruby_', - * end: 6, - * zeroPad: 4 - * }) - * }); - * ``` - * - * Please see the animation examples for further details. - * - * @method Phaser.Animations.AnimationManager#generateFrameNames - * @since 3.0.0 - * - * @param {string} key - The key for the texture containing the animation frames. - * @param {Phaser.Types.Animations.GenerateFrameNames} [config] - The configuration object for the animation frame names. - * - * @return {Phaser.Types.Animations.AnimationFrame[]} The array of {@link Phaser.Types.Animations.AnimationFrame} objects. - */ - generateFrameNames: function (key, config) - { - var prefix = GetValue(config, 'prefix', ''); - var start = GetValue(config, 'start', 0); - var end = GetValue(config, 'end', 0); - var suffix = GetValue(config, 'suffix', ''); - var zeroPad = GetValue(config, 'zeroPad', 0); - var out = GetValue(config, 'outputArray', []); - var frames = GetValue(config, 'frames', false); - - var texture = this.textureManager.get(key); - - if (!texture) - { - return out; - } - - var diff = (start < end) ? 1 : -1; - - // Adjust because we use i !== end in the for loop - end += diff; - - var i; - var frame; - - if (!config) - { - // Use every frame in the atlas? - frames = texture.getFrameNames(); - - for (i = 0; i < frames.length; i++) - { - out.push({ key: key, frame: frames[i] }); - } - } - else if (Array.isArray(frames)) - { - // Have they provided their own custom frame sequence array? - for (i = 0; i < frames.length; i++) - { - frame = prefix + Pad(frames[i], zeroPad, '0', 1) + suffix; - - if (texture.has(frame)) - { - out.push({ key: key, frame: frame }); - } - } - } - else - { - for (i = start; i !== end; i += diff) - { - frame = prefix + Pad(i, zeroPad, '0', 1) + suffix; - - if (texture.has(frame)) - { - out.push({ key: key, frame: frame }); - } - } - } - - return out; - }, - - /** - * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. - * - * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. - * - * If you're working with a texture atlas, see the `generateFrameNames` method instead. - * - * @method Phaser.Animations.AnimationManager#generateFrameNumbers - * @since 3.0.0 - * - * @param {string} key - The key for the texture containing the animation frames. - * @param {Phaser.Types.Animations.GenerateFrameNumbers} config - The configuration object for the animation frames. - * - * @return {Phaser.Types.Animations.AnimationFrame[]} The array of {@link Phaser.Types.Animations.AnimationFrame} objects. - */ - generateFrameNumbers: function (key, config) - { - var startFrame = GetValue(config, 'start', 0); - var endFrame = GetValue(config, 'end', -1); - var firstFrame = GetValue(config, 'first', false); - var out = GetValue(config, 'outputArray', []); - var frames = GetValue(config, 'frames', false); - - var texture = this.textureManager.get(key); - - if (!texture) - { - return out; - } - - if (firstFrame && texture.has(firstFrame)) - { - out.push({ key: key, frame: firstFrame }); - } - - var i; - - // Have they provided their own custom frame sequence array? - if (Array.isArray(frames)) - { - for (i = 0; i < frames.length; i++) - { - if (texture.has(frames[i])) - { - out.push({ key: key, frame: frames[i] }); - } - } - } - else - { - // No endFrame then see if we can get it - if (endFrame === -1) - { - endFrame = texture.frameTotal; - } - - var diff = (startFrame < endFrame) ? 1 : -1; - - // Adjust because we use i !== end in the for loop - endFrame += diff; - - for (i = startFrame; i !== endFrame; i += diff) - { - if (texture.has(i)) - { - out.push({ key: key, frame: i }); - } - } - } - - return out; - }, - - /** - * Get an Animation. - * - * @method Phaser.Animations.AnimationManager#get - * @since 3.0.0 - * - * @param {string} key - The key of the Animation to retrieve. - * - * @return {Phaser.Animations.Animation} The Animation. - */ - get: function (key) - { - return this.anims.get(key); - }, - - /** - * Load an Animation into a Game Object's Animation Component. - * - * @method Phaser.Animations.AnimationManager#load - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to load the animation into. - * @param {string} key - The key of the animation to load. - * @param {(string|integer)} [startFrame] - The name of a start frame to set on the loaded animation. - * - * @return {Phaser.GameObjects.GameObject} The Game Object with the animation loaded into it. - */ - load: function (child, key, startFrame) - { - var anim = this.get(key); - - if (anim) - { - anim.load(child, startFrame); - } - else - { - console.warn('Missing animation: ' + key); - } - - return child; - }, - - /** - * Pause all animations. - * - * @method Phaser.Animations.AnimationManager#pauseAll - * @fires Phaser.Animations.Events#PAUSE_ALL - * @since 3.0.0 - * - * @return {Phaser.Animations.AnimationManager} This Animation Manager. - */ - pauseAll: function () - { - if (!this.paused) - { - this.paused = true; - - this.emit(Events.PAUSE_ALL); - } - - return this; - }, - - /** - * Play an animation on the given Game Objects that have an Animation Component. - * - * @method Phaser.Animations.AnimationManager#play - * @since 3.0.0 - * - * @param {string} key - The key of the animation to play on the Game Object. - * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Objects to play the animation on. - * - * @return {Phaser.Animations.AnimationManager} This Animation Manager. - */ - play: function (key, child) - { - if (!Array.isArray(child)) - { - child = [ child ]; - } - - var anim = this.get(key); - - if (!anim) - { - return; - } - - for (var i = 0; i < child.length; i++) - { - child[i].anims.play(key); - } - - return this; - }, - - /** - * 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. - */ - remove: function (key) - { - var anim = this.get(key); - - if (anim) - { - this.emit(Events.REMOVE_ANIMATION, key, anim); - - this.anims.delete(key); - } - - return anim; - }, - - /** - * Resume all paused animations. - * - * @method Phaser.Animations.AnimationManager#resumeAll - * @fires Phaser.Animations.Events#RESUME_ALL - * @since 3.0.0 - * - * @return {Phaser.Animations.AnimationManager} This Animation Manager. - */ - resumeAll: function () - { - if (this.paused) - { - this.paused = false; - - this.emit(Events.RESUME_ALL); - } - - return this; - }, - - /** - * Takes an array of Game Objects that have an Animation Component and then - * starts the given animation playing on them, each one offset by the - * `stagger` amount given to this method. - * - * @method Phaser.Animations.AnimationManager#staggerPlay - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject[]} G - [items,$return] - * - * @param {string} key - The key of the animation to play on the Game Objects. - * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} children - An array of Game Objects to play the animation on. They must have an Animation Component. - * @param {number} [stagger=0] - The amount of time, in milliseconds, to offset each play time by. - * - * @return {Phaser.Animations.AnimationManager} This Animation Manager. - */ - staggerPlay: function (key, children, stagger) - { - if (stagger === undefined) { stagger = 0; } - - if (!Array.isArray(children)) - { - children = [ children ]; - } - - var anim = this.get(key); - - if (!anim) - { - return; - } - - for (var i = 0; i < children.length; i++) - { - children[i].anims.delayedPlay(stagger * i, key); - } - - return this; - }, - - /** - * Returns the Animation data as JavaScript object based on the given key. - * Or, if not 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. - */ - toJSON: function (key) - { - var output = { - anims: [], - globalTimeScale: this.globalTimeScale - }; - - if (key !== undefined && key !== '') - { - output.anims.push(this.anims.get(key).toJSON()); - } - else - { - this.anims.each(function (animationKey, animation) - { - output.anims.push(animation.toJSON()); - }); - } - - return output; - }, - - /** - * Destroy this Animation Manager and clean up animation definitions and references to other objects. - * This method should not be called directly. It will be called automatically as a response to a `destroy` event from the Phaser.Game instance. - * - * @method Phaser.Animations.AnimationManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.anims.clear(); - - this.textureManager = null; - - this.game = null; - } - -}); - -module.exports = AnimationManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Animation = require('./Animation'); +var Class = require('../utils/Class'); +var CustomMap = require('../structs/Map'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GameEvents = require('../core/events'); +var GetValue = require('../utils/object/GetValue'); +var Pad = require('../utils/string/Pad'); + +/** + * @classdesc + * The Animation Manager. + * + * Animations are managed by the global Animation Manager. This is a singleton class that is + * responsible for creating and delivering animations and their corresponding data to all Game Objects. + * Unlike plugins it is owned by the Game instance, not the Scene. + * + * Sprites and other Game Objects get the data they need from the AnimationManager. + * + * @class AnimationManager + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Animations + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser.Game instance. + */ +var AnimationManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function AnimationManager (game) + { + EventEmitter.call(this); + + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.Animations.AnimationManager#game + * @type {Phaser.Game} + * @protected + * @since 3.0.0 + */ + this.game = game; + + /** + * A reference to the Texture Manager. + * + * @name Phaser.Animations.AnimationManager#textureManager + * @type {Phaser.Textures.TextureManager} + * @protected + * @since 3.0.0 + */ + this.textureManager = null; + + /** + * The global time scale of the Animation Manager. + * + * This scales the time delta between two frames, thus influencing the speed of time for the Animation Manager. + * + * @name Phaser.Animations.AnimationManager#globalTimeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.globalTimeScale = 1; + + /** + * The Animations registered in the Animation Manager. + * + * This map should be modified with the {@link #add} and {@link #create} methods of the Animation Manager. + * + * @name Phaser.Animations.AnimationManager#anims + * @type {Phaser.Structs.Map.} + * @protected + * @since 3.0.0 + */ + this.anims = new CustomMap(); + + /** + * Whether the Animation Manager is paused along with all of its Animations. + * + * @name Phaser.Animations.AnimationManager#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * The name of this Animation Manager. + * + * @name Phaser.Animations.AnimationManager#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'AnimationManager'; + + game.events.once(GameEvents.BOOT, this.boot, this); + }, + + /** + * Registers event listeners after the Game boots. + * + * @method Phaser.Animations.AnimationManager#boot + * @listens Phaser.Core.Events#DESTROY + * @since 3.0.0 + */ + boot: function () + { + this.textureManager = this.game.textures; + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Adds an existing Animation to the Animation Manager. + * + * @method Phaser.Animations.AnimationManager#add + * @fires Phaser.Animations.Events#ADD_ANIMATION + * @since 3.0.0 + * + * @param {string} key - The key under which the Animation should be added. The Animation will be updated with it. Must be unique. + * @param {Phaser.Animations.Animation} animation - The Animation which should be added to the Animation Manager. + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + add: function (key, animation) + { + if (this.anims.has(key)) + { + console.warn('Animation key exists: ' + key); + + return; + } + + animation.key = key; + + this.anims.set(key, animation); + + this.emit(Events.ADD_ANIMATION, key, animation); + + return this; + }, + + /** + * Checks to see if the given key is already in use within the Animation Manager or not. + * + * Animations are global. Keys created in one scene can be used from any other Scene in your game. They are not Scene specific. + * + * @method Phaser.Animations.AnimationManager#exists + * @since 3.16.0 + * + * @param {string} key - The key of the Animation to check. + * + * @return {boolean} `true` if the Animation already exists in the Animation Manager, or `false` if the key is available. + */ + exists: function (key) + { + return this.anims.has(key); + }, + + /** + * Creates a new Animation and adds it to the Animation Manager. + * + * Animations are global. Once created, you can use them in any Scene in your game. They are not Scene specific. + * + * If an invalid key is given this method will return `false`. + * + * If you pass the key of an animation that already exists in the Animation Manager, that animation will be returned. + * + * A brand new animation is only created if the key is valid and not already in use. + * + * If you wish to re-use an existing key, call `AnimationManager.remove` first, then this method. + * + * @method Phaser.Animations.AnimationManager#create + * @fires Phaser.Animations.Events#ADD_ANIMATION + * @since 3.0.0 + * + * @param {Phaser.Types.Animations.Animation} config - The configuration settings for the Animation. + * + * @return {(Phaser.Animations.Animation|false)} The Animation that was created, or `false` is the key is already in use. + */ + create: function (config) + { + var key = config.key; + + var anim = false; + + if (key) + { + anim = this.get(key); + + if (!anim) + { + anim = new Animation(this, key, config); + + this.anims.set(key, anim); + + this.emit(Events.ADD_ANIMATION, key, anim); + } + } + + return anim; + }, + + /** + * Loads this Animation Manager's Animations and settings from a JSON object. + * + * @method Phaser.Animations.AnimationManager#fromJSON + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Animations.JSONAnimations|Phaser.Types.Animations.JSONAnimation)} data - The JSON object to parse. + * @param {boolean} [clearCurrentAnimations=false] - If set to `true`, the current animations will be removed (`anims.clear()`). If set to `false` (default), the animations in `data` will be added. + * + * @return {Phaser.Animations.Animation[]} An array containing all of the Animation objects that were created as a result of this call. + */ + fromJSON: function (data, clearCurrentAnimations) + { + if (clearCurrentAnimations === undefined) { clearCurrentAnimations = false; } + + if (clearCurrentAnimations) + { + this.anims.clear(); + } + + // Do we have a String (i.e. from JSON, or an Object?) + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + var output = []; + + // Array of animations, or a single animation? + if (data.hasOwnProperty('anims') && Array.isArray(data.anims)) + { + for (var i = 0; i < data.anims.length; i++) + { + output.push(this.create(data.anims[i])); + } + + if (data.hasOwnProperty('globalTimeScale')) + { + this.globalTimeScale = data.globalTimeScale; + } + } + else if (data.hasOwnProperty('key') && data.type === 'frame') + { + output.push(this.create(data)); + } + + return output; + }, + + /** + * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. + * + * Generates objects with string based frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNames}. + * + * It's a helper method, designed to make it easier for you to extract all of the frame names from texture atlases. + * If you're working with a sprite sheet, see the `generateFrameNumbers` method instead. + * + * Example: + * + * If you have a texture atlases loaded called `gems` and it contains 6 frames called `ruby_0001`, `ruby_0002`, and so on, + * then you can call this method using: `this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 })`. + * + * The `end` value tells it to look for 6 frames, incrementally numbered, all starting with the prefix `ruby_`. The `zeroPad` + * value tells it how many zeroes pad out the numbers. To create an animation using this method, you can do: + * + * ```javascript + * this.anims.create({ + * key: 'ruby', + * repeat: -1, + * frames: this.anims.generateFrameNames('gems', { + * prefix: 'ruby_', + * end: 6, + * zeroPad: 4 + * }) + * }); + * ``` + * + * Please see the animation examples for further details. + * + * @method Phaser.Animations.AnimationManager#generateFrameNames + * @since 3.0.0 + * + * @param {string} key - The key for the texture containing the animation frames. + * @param {Phaser.Types.Animations.GenerateFrameNames} [config] - The configuration object for the animation frame names. + * + * @return {Phaser.Types.Animations.AnimationFrame[]} The array of {@link Phaser.Types.Animations.AnimationFrame} objects. + */ + generateFrameNames: function (key, config) + { + var prefix = GetValue(config, 'prefix', ''); + var start = GetValue(config, 'start', 0); + var end = GetValue(config, 'end', 0); + var suffix = GetValue(config, 'suffix', ''); + var zeroPad = GetValue(config, 'zeroPad', 0); + var out = GetValue(config, 'outputArray', []); + var frames = GetValue(config, 'frames', false); + + var texture = this.textureManager.get(key); + + if (!texture) + { + return out; + } + + var diff = (start < end) ? 1 : -1; + + // Adjust because we use i !== end in the for loop + end += diff; + + var i; + var frame; + + if (!config) + { + // Use every frame in the atlas? + frames = texture.getFrameNames(); + + for (i = 0; i < frames.length; i++) + { + out.push({ key: key, frame: frames[i] }); + } + } + else if (Array.isArray(frames)) + { + // Have they provided their own custom frame sequence array? + for (i = 0; i < frames.length; i++) + { + frame = prefix + Pad(frames[i], zeroPad, '0', 1) + suffix; + + if (texture.has(frame)) + { + out.push({ key: key, frame: frame }); + } + } + } + else + { + for (i = start; i !== end; i += diff) + { + frame = prefix + Pad(i, zeroPad, '0', 1) + suffix; + + if (texture.has(frame)) + { + out.push({ key: key, frame: frame }); + } + } + } + + return out; + }, + + /** + * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. + * + * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. + * + * If you're working with a texture atlas, see the `generateFrameNames` method instead. + * + * @method Phaser.Animations.AnimationManager#generateFrameNumbers + * @since 3.0.0 + * + * @param {string} key - The key for the texture containing the animation frames. + * @param {Phaser.Types.Animations.GenerateFrameNumbers} config - The configuration object for the animation frames. + * + * @return {Phaser.Types.Animations.AnimationFrame[]} The array of {@link Phaser.Types.Animations.AnimationFrame} objects. + */ + generateFrameNumbers: function (key, config) + { + var startFrame = GetValue(config, 'start', 0); + var endFrame = GetValue(config, 'end', -1); + var firstFrame = GetValue(config, 'first', false); + var out = GetValue(config, 'outputArray', []); + var frames = GetValue(config, 'frames', false); + + var texture = this.textureManager.get(key); + + if (!texture) + { + return out; + } + + if (firstFrame && texture.has(firstFrame)) + { + out.push({ key: key, frame: firstFrame }); + } + + var i; + + // Have they provided their own custom frame sequence array? + if (Array.isArray(frames)) + { + for (i = 0; i < frames.length; i++) + { + if (texture.has(frames[i])) + { + out.push({ key: key, frame: frames[i] }); + } + } + } + else + { + // No endFrame then see if we can get it + if (endFrame === -1) + { + endFrame = texture.frameTotal; + } + + var diff = (startFrame < endFrame) ? 1 : -1; + + // Adjust because we use i !== end in the for loop + endFrame += diff; + + for (i = startFrame; i !== endFrame; i += diff) + { + if (texture.has(i)) + { + out.push({ key: key, frame: i }); + } + } + } + + return out; + }, + + /** + * Get an Animation. + * + * @method Phaser.Animations.AnimationManager#get + * @since 3.0.0 + * + * @param {string} key - The key of the Animation to retrieve. + * + * @return {Phaser.Animations.Animation} The Animation. + */ + get: function (key) + { + return this.anims.get(key); + }, + + /** + * Load an Animation into a Game Object's Animation Component. + * + * @method Phaser.Animations.AnimationManager#load + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to load the animation into. + * @param {string} key - The key of the animation to load. + * @param {(string|integer)} [startFrame] - The name of a start frame to set on the loaded animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object with the animation loaded into it. + */ + load: function (child, key, startFrame) + { + var anim = this.get(key); + + if (anim) + { + anim.load(child, startFrame); + } + else + { + console.warn('Missing animation: ' + key); + } + + return child; + }, + + /** + * Pause all animations. + * + * @method Phaser.Animations.AnimationManager#pauseAll + * @fires Phaser.Animations.Events#PAUSE_ALL + * @since 3.0.0 + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + pauseAll: function () + { + if (!this.paused) + { + this.paused = true; + + this.emit(Events.PAUSE_ALL); + } + + return this; + }, + + /** + * Play an animation on the given Game Objects that have an Animation Component. + * + * @method Phaser.Animations.AnimationManager#play + * @since 3.0.0 + * + * @param {string} key - The key of the animation to play on the Game Object. + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Objects to play the animation on. + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + play: function (key, child) + { + if (!Array.isArray(child)) + { + child = [ child ]; + } + + var anim = this.get(key); + + if (!anim) + { + return; + } + + for (var i = 0; i < child.length; i++) + { + child[i].anims.play(key); + } + + return this; + }, + + /** + * 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. + */ + remove: function (key) + { + var anim = this.get(key); + + if (anim) + { + this.emit(Events.REMOVE_ANIMATION, key, anim); + + this.anims.delete(key); + } + + return anim; + }, + + /** + * Resume all paused animations. + * + * @method Phaser.Animations.AnimationManager#resumeAll + * @fires Phaser.Animations.Events#RESUME_ALL + * @since 3.0.0 + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + resumeAll: function () + { + if (this.paused) + { + this.paused = false; + + this.emit(Events.RESUME_ALL); + } + + return this; + }, + + /** + * Takes an array of Game Objects that have an Animation Component and then + * starts the given animation playing on them, each one offset by the + * `stagger` amount given to this method. + * + * @method Phaser.Animations.AnimationManager#staggerPlay + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [items,$return] + * + * @param {string} key - The key of the animation to play on the Game Objects. + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} children - An array of Game Objects to play the animation on. They must have an Animation Component. + * @param {number} [stagger=0] - The amount of time, in milliseconds, to offset each play time by. + * + * @return {Phaser.Animations.AnimationManager} This Animation Manager. + */ + staggerPlay: function (key, children, stagger) + { + if (stagger === undefined) { stagger = 0; } + + if (!Array.isArray(children)) + { + children = [ children ]; + } + + var anim = this.get(key); + + if (!anim) + { + return; + } + + for (var i = 0; i < children.length; i++) + { + children[i].anims.delayedPlay(stagger * i, key); + } + + return this; + }, + + /** + * Returns the Animation data as JavaScript object based on the given key. + * Or, if not 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. + */ + toJSON: function (key) + { + var output = { + anims: [], + globalTimeScale: this.globalTimeScale + }; + + if (key !== undefined && key !== '') + { + output.anims.push(this.anims.get(key).toJSON()); + } + else + { + this.anims.each(function (animationKey, animation) + { + output.anims.push(animation.toJSON()); + }); + } + + return output; + }, + + /** + * Destroy this Animation Manager and clean up animation definitions and references to other objects. + * This method should not be called directly. It will be called automatically as a response to a `destroy` event from the Phaser.Game instance. + * + * @method Phaser.Animations.AnimationManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.anims.clear(); + + this.textureManager = null; + + this.game = null; + } + +}); + +module.exports = AnimationManager; diff --git a/src/animations/events/ADD_ANIMATION_EVENT.js b/src/animations/events/ADD_ANIMATION_EVENT.js index 1c288cbfe..535d67d8a 100644 --- a/src/animations/events/ADD_ANIMATION_EVENT.js +++ b/src/animations/events/ADD_ANIMATION_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Add Animation Event. - * - * This event is dispatched when a new animation is added to the global Animation Manager. - * - * This can happen either as a result of an animation instance being added to the Animation Manager, - * or the Animation Manager creating a new animation directly. - * - * @event Phaser.Animations.Events#ADD_ANIMATION - * @since 3.0.0 - * - * @param {string} key - The key of the Animation that was added to the global Animation Manager. - * @param {Phaser.Animations.Animation} animation - An instance of the newly created Animation. - */ -module.exports = 'add'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Add Animation Event. + * + * This event is dispatched when a new animation is added to the global Animation Manager. + * + * This can happen either as a result of an animation instance being added to the Animation Manager, + * or the Animation Manager creating a new animation directly. + * + * @event Phaser.Animations.Events#ADD_ANIMATION + * @since 3.0.0 + * + * @param {string} key - The key of the Animation that was added to the global Animation Manager. + * @param {Phaser.Animations.Animation} animation - An instance of the newly created Animation. + */ +module.exports = 'add'; diff --git a/src/animations/events/ANIMATION_COMPLETE_EVENT.js b/src/animations/events/ANIMATION_COMPLETE_EVENT.js index 0c36c0d72..cb330b833 100644 --- a/src/animations/events/ANIMATION_COMPLETE_EVENT.js +++ b/src/animations/events/ANIMATION_COMPLETE_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Animation Complete Event. - * - * This event is dispatched by an Animation instance when it completes, i.e. finishes playing or is manually stopped. - * - * Be careful with the volume of events this could generate. If a group of Sprites all complete the same - * animation at the same time, this event will invoke its handler for each one of them. - * - * @event Phaser.Animations.Events#ANIMATION_COMPLETE - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. - */ -module.exports = 'complete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Complete Event. + * + * This event is dispatched by an Animation instance when it completes, i.e. finishes playing or is manually stopped. + * + * Be careful with the volume of events this could generate. If a group of Sprites all complete the same + * animation at the same time, this event will invoke its handler for each one of them. + * + * @event Phaser.Animations.Events#ANIMATION_COMPLETE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. + */ +module.exports = 'complete'; diff --git a/src/animations/events/ANIMATION_REPEAT_EVENT.js b/src/animations/events/ANIMATION_REPEAT_EVENT.js index d79dcde80..17e9929da 100644 --- a/src/animations/events/ANIMATION_REPEAT_EVENT.js +++ b/src/animations/events/ANIMATION_REPEAT_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Animation Repeat Event. - * - * This event is dispatched when a currently playing animation repeats. - * - * The event is dispatched directly from the Animation object itself. Which means that listeners - * bound to this event will be invoked every time the Animation repeats, for every Game Object that may have it. - * - * @event Phaser.Animations.Events#ANIMATION_REPEAT - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that repeated. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation was on when it repeated. - */ -module.exports = 'repeat'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Repeat Event. + * + * This event is dispatched when a currently playing animation repeats. + * + * The event is dispatched directly from the Animation object itself. Which means that listeners + * bound to this event will be invoked every time the Animation repeats, for every Game Object that may have it. + * + * @event Phaser.Animations.Events#ANIMATION_REPEAT + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that repeated. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation was on when it repeated. + */ +module.exports = 'repeat'; diff --git a/src/animations/events/ANIMATION_RESTART_EVENT.js b/src/animations/events/ANIMATION_RESTART_EVENT.js index e959a464b..ee1597cec 100644 --- a/src/animations/events/ANIMATION_RESTART_EVENT.js +++ b/src/animations/events/ANIMATION_RESTART_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Animation Restart Event. - * - * This event is dispatched by an Animation instance when it restarts. - * - * Be careful with the volume of events this could generate. If a group of Sprites all restart the same - * animation at the same time, this event will invoke its handler for each one of them. - * - * @event Phaser.Animations.Events#ANIMATION_RESTART - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that restarted playing. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. - */ -module.exports = 'restart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Restart Event. + * + * This event is dispatched by an Animation instance when it restarts. + * + * Be careful with the volume of events this could generate. If a group of Sprites all restart the same + * animation at the same time, this event will invoke its handler for each one of them. + * + * @event Phaser.Animations.Events#ANIMATION_RESTART + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that restarted playing. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. + */ +module.exports = 'restart'; diff --git a/src/animations/events/ANIMATION_START_EVENT.js b/src/animations/events/ANIMATION_START_EVENT.js index 8d65cb818..244dd39f7 100644 --- a/src/animations/events/ANIMATION_START_EVENT.js +++ b/src/animations/events/ANIMATION_START_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Animation Start Event. - * - * This event is dispatched by an Animation instance when it starts playing. - * - * Be careful with the volume of events this could generate. If a group of Sprites all play the same - * animation at the same time, this event will invoke its handler for each one of them. - * - * @event Phaser.Animations.Events#ANIMATION_START - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that started playing. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. - */ -module.exports = 'start'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Animation Start Event. + * + * This event is dispatched by an Animation instance when it starts playing. + * + * Be careful with the volume of events this could generate. If a group of Sprites all play the same + * animation at the same time, this event will invoke its handler for each one of them. + * + * @event Phaser.Animations.Events#ANIMATION_START + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that started playing. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. + */ +module.exports = 'start'; diff --git a/src/animations/events/PAUSE_ALL_EVENT.js b/src/animations/events/PAUSE_ALL_EVENT.js index b4ba939d7..925074cf5 100644 --- a/src/animations/events/PAUSE_ALL_EVENT.js +++ b/src/animations/events/PAUSE_ALL_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pause All Animations Event. - * - * This event is dispatched when the global Animation Manager is told to pause. - * - * When this happens all current animations will stop updating, although it doesn't necessarily mean - * that the game has paused as well. - * - * @event Phaser.Animations.Events#PAUSE_ALL - * @since 3.0.0 - */ -module.exports = 'pauseall'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pause All Animations Event. + * + * This event is dispatched when the global Animation Manager is told to pause. + * + * When this happens all current animations will stop updating, although it doesn't necessarily mean + * that the game has paused as well. + * + * @event Phaser.Animations.Events#PAUSE_ALL + * @since 3.0.0 + */ +module.exports = 'pauseall'; diff --git a/src/animations/events/REMOVE_ANIMATION_EVENT.js b/src/animations/events/REMOVE_ANIMATION_EVENT.js index c37de03d6..243be0f15 100644 --- a/src/animations/events/REMOVE_ANIMATION_EVENT.js +++ b/src/animations/events/REMOVE_ANIMATION_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Remove Animation Event. - * - * This event is dispatched when an animation is removed from the global Animation Manager. - * - * @event Phaser.Animations.Events#REMOVE_ANIMATION - * @since 3.0.0 - * - * @param {string} key - The key of the Animation that was removed from the global Animation Manager. - * @param {Phaser.Animations.Animation} animation - An instance of the removed Animation. - */ -module.exports = 'remove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Remove Animation Event. + * + * This event is dispatched when an animation is removed from the global Animation Manager. + * + * @event Phaser.Animations.Events#REMOVE_ANIMATION + * @since 3.0.0 + * + * @param {string} key - The key of the Animation that was removed from the global Animation Manager. + * @param {Phaser.Animations.Animation} animation - An instance of the removed Animation. + */ +module.exports = 'remove'; diff --git a/src/animations/events/RESUME_ALL_EVENT.js b/src/animations/events/RESUME_ALL_EVENT.js index c02f43028..4201a1d63 100644 --- a/src/animations/events/RESUME_ALL_EVENT.js +++ b/src/animations/events/RESUME_ALL_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Resume All Animations Event. - * - * This event is dispatched when the global Animation Manager resumes, having been previously paused. - * - * When this happens all current animations will continue updating again. - * - * @event Phaser.Animations.Events#RESUME_ALL - * @since 3.0.0 - */ -module.exports = 'resumeall'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Resume All Animations Event. + * + * This event is dispatched when the global Animation Manager resumes, having been previously paused. + * + * When this happens all current animations will continue updating again. + * + * @event Phaser.Animations.Events#RESUME_ALL + * @since 3.0.0 + */ +module.exports = 'resumeall'; diff --git a/src/animations/events/SPRITE_ANIMATION_COMPLETE_EVENT.js b/src/animations/events/SPRITE_ANIMATION_COMPLETE_EVENT.js index 20e8fdb4b..71aac0756 100644 --- a/src/animations/events/SPRITE_ANIMATION_COMPLETE_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_COMPLETE_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Complete Event. - * - * This event is dispatched by a Sprite when an animation finishes playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationcomplete', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_COMPLETE` event. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_COMPLETE - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. - */ -module.exports = 'animationcomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Complete Event. + * + * This event is dispatched by a Sprite when an animation finishes playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationcomplete', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_COMPLETE` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_COMPLETE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. + */ +module.exports = 'animationcomplete'; diff --git a/src/animations/events/SPRITE_ANIMATION_KEY_COMPLETE_EVENT.js b/src/animations/events/SPRITE_ANIMATION_KEY_COMPLETE_EVENT.js index a2ecb569c..e7ad5bf47 100644 --- a/src/animations/events/SPRITE_ANIMATION_KEY_COMPLETE_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_KEY_COMPLETE_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Key Complete Event. - * - * This event is dispatched by a Sprite when a specific animation finishes playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationcomplete-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationcomplete-explode`. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_COMPLETE - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. - */ -module.exports = 'animationcomplete-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Complete Event. + * + * This event is dispatched by a Sprite when a specific animation finishes playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationcomplete-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationcomplete-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_COMPLETE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that completed. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation completed on. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation completed. + */ +module.exports = 'animationcomplete-'; diff --git a/src/animations/events/SPRITE_ANIMATION_KEY_REPEAT_EVENT.js b/src/animations/events/SPRITE_ANIMATION_KEY_REPEAT_EVENT.js index a20169d05..02f438d6e 100644 --- a/src/animations/events/SPRITE_ANIMATION_KEY_REPEAT_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_KEY_REPEAT_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Key Repeat Event. - * - * This event is dispatched by a Sprite when a specific animation repeats playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrepeat-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrepeat-explode`. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that is repeating on the Sprite. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. - * @param {integer} repeatCount - The number of times the Animation has repeated so far. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation repeated playing. - */ -module.exports = 'animationrepeat-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Repeat Event. + * + * This event is dispatched by a Sprite when a specific animation repeats playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrepeat-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrepeat-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_REPEAT + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that is repeating on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {integer} repeatCount - The number of times the Animation has repeated so far. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation repeated playing. + */ +module.exports = 'animationrepeat-'; diff --git a/src/animations/events/SPRITE_ANIMATION_KEY_RESTART_EVENT.js b/src/animations/events/SPRITE_ANIMATION_KEY_RESTART_EVENT.js index da94d76bb..aee1f490d 100644 --- a/src/animations/events/SPRITE_ANIMATION_KEY_RESTART_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_KEY_RESTART_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Key Restart Event. - * - * This event is dispatched by a Sprite when a specific animation restarts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrestart-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrestart-explode`. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_RESTART - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was restarted on the Sprite. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. - */ -module.exports = 'animationrestart-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Restart Event. + * + * This event is dispatched by a Sprite when a specific animation restarts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrestart-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrestart-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_RESTART + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was restarted on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. + */ +module.exports = 'animationrestart-'; diff --git a/src/animations/events/SPRITE_ANIMATION_KEY_START_EVENT.js b/src/animations/events/SPRITE_ANIMATION_KEY_START_EVENT.js index 65454deea..3c0f9e0b9 100644 --- a/src/animations/events/SPRITE_ANIMATION_KEY_START_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_KEY_START_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Key Start Event. - * - * This event is dispatched by a Sprite when a specific animation starts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationstart-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationstart-explode`. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_START - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was started on the Sprite. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. - */ -module.exports = 'animationstart-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Start Event. + * + * This event is dispatched by a Sprite when a specific animation starts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationstart-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationstart-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_START + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was started on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. + */ +module.exports = 'animationstart-'; diff --git a/src/animations/events/SPRITE_ANIMATION_KEY_UPDATE_EVENT.js b/src/animations/events/SPRITE_ANIMATION_KEY_UPDATE_EVENT.js index 2b21e5804..6d6b760cc 100644 --- a/src/animations/events/SPRITE_ANIMATION_KEY_UPDATE_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_KEY_UPDATE_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Key Update Event. - * - * This event is dispatched by a Sprite when a specific animation playing on it updates. This happens when the animation changes frame, - * based on the animation frame rate and other factors like `timeScale` and `delay`. - * - * Listen for it on the Sprite using `sprite.on('animationupdate-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationupdate-explode`. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_UPDATE - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated on the Sprite. - * @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. - */ -module.exports = 'animationupdate-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Key Update Event. + * + * This event is dispatched by a Sprite when a specific animation playing on it updates. This happens when the animation changes frame, + * based on the animation frame rate and other factors like `timeScale` and `delay`. + * + * Listen for it on the Sprite using `sprite.on('animationupdate-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationupdate-explode`. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_KEY_UPDATE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated on the Sprite. + * @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. + */ +module.exports = 'animationupdate-'; diff --git a/src/animations/events/SPRITE_ANIMATION_REPEAT_EVENT.js b/src/animations/events/SPRITE_ANIMATION_REPEAT_EVENT.js index 23ca4f3eb..af6a44af9 100644 --- a/src/animations/events/SPRITE_ANIMATION_REPEAT_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_REPEAT_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Repeat Event. - * - * This event is dispatched by a Sprite when an animation repeats playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrepeat', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_REPEAT` event. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_REPEAT - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that is repeating on the Sprite. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. - * @param {integer} repeatCount - The number of times the Animation has repeated so far. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation repeated playing. - */ -module.exports = 'animationrepeat'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Repeat Event. + * + * This event is dispatched by a Sprite when an animation repeats playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrepeat', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_REPEAT` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_REPEAT + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that is repeating on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {integer} repeatCount - The number of times the Animation has repeated so far. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation repeated playing. + */ +module.exports = 'animationrepeat'; diff --git a/src/animations/events/SPRITE_ANIMATION_RESTART_EVENT.js b/src/animations/events/SPRITE_ANIMATION_RESTART_EVENT.js index 7f88df85e..0e5b9a445 100644 --- a/src/animations/events/SPRITE_ANIMATION_RESTART_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_RESTART_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Restart Event. - * - * This event is dispatched by a Sprite when an animation restarts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrestart', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_RESTART` event. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_RESTART - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was restarted on the Sprite. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. - */ -module.exports = 'animationrestart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Restart Event. + * + * This event is dispatched by a Sprite when an animation restarts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrestart', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_RESTART` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_RESTART + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was restarted on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation restarted with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation restarted playing. + */ +module.exports = 'animationrestart'; diff --git a/src/animations/events/SPRITE_ANIMATION_START_EVENT.js b/src/animations/events/SPRITE_ANIMATION_START_EVENT.js index f1e3eb390..98ee2c7fb 100644 --- a/src/animations/events/SPRITE_ANIMATION_START_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_START_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Start Event. - * - * This event is dispatched by a Sprite when an animation starts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationstart', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_START` event. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_START - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was started on the Sprite. - * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. - * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. - */ -module.exports = 'animationstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Start Event. + * + * This event is dispatched by a Sprite when an animation starts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationstart', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_START` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_START + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that was started on the Sprite. + * @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame that the Animation started with. + * @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation started playing. + */ +module.exports = 'animationstart'; diff --git a/src/animations/events/SPRITE_ANIMATION_UPDATE_EVENT.js b/src/animations/events/SPRITE_ANIMATION_UPDATE_EVENT.js index 0bf94225f..0d7102207 100644 --- a/src/animations/events/SPRITE_ANIMATION_UPDATE_EVENT.js +++ b/src/animations/events/SPRITE_ANIMATION_UPDATE_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sprite Animation Update Event. - * - * This event is dispatched by a Sprite when an animation playing on it updates. This happens when the animation changes frame, - * based on the animation frame rate and other factors like `timeScale` and `delay`. - * - * Listen for it on the Sprite using `sprite.on('animationupdate', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_UPDATE` event. - * - * @event Phaser.Animations.Events#SPRITE_ANIMATION_UPDATE - * @since 3.16.1 - * - * @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated on the Sprite. - * @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. - */ -module.exports = 'animationupdate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sprite Animation Update Event. + * + * This event is dispatched by a Sprite when an animation playing on it updates. This happens when the animation changes frame, + * based on the animation frame rate and other factors like `timeScale` and `delay`. + * + * Listen for it on the Sprite using `sprite.on('animationupdate', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_UPDATE` event. + * + * @event Phaser.Animations.Events#SPRITE_ANIMATION_UPDATE + * @since 3.16.1 + * + * @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated on the Sprite. + * @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. + */ +module.exports = 'animationupdate'; diff --git a/src/animations/events/index.js b/src/animations/events/index.js index 4882d1f66..b6af1a900 100644 --- a/src/animations/events/index.js +++ b/src/animations/events/index.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Animations.Events - */ - -module.exports = { - - ADD_ANIMATION: require('./ADD_ANIMATION_EVENT'), - ANIMATION_COMPLETE: require('./ANIMATION_COMPLETE_EVENT'), - ANIMATION_REPEAT: require('./ANIMATION_REPEAT_EVENT'), - ANIMATION_RESTART: require('./ANIMATION_RESTART_EVENT'), - ANIMATION_START: require('./ANIMATION_START_EVENT'), - PAUSE_ALL: require('./PAUSE_ALL_EVENT'), - REMOVE_ANIMATION: require('./REMOVE_ANIMATION_EVENT'), - RESUME_ALL: require('./RESUME_ALL_EVENT'), - SPRITE_ANIMATION_COMPLETE: require('./SPRITE_ANIMATION_COMPLETE_EVENT'), - SPRITE_ANIMATION_KEY_COMPLETE: require('./SPRITE_ANIMATION_KEY_COMPLETE_EVENT'), - SPRITE_ANIMATION_KEY_REPEAT: require('./SPRITE_ANIMATION_KEY_REPEAT_EVENT'), - SPRITE_ANIMATION_KEY_RESTART: require('./SPRITE_ANIMATION_KEY_RESTART_EVENT'), - SPRITE_ANIMATION_KEY_START: require('./SPRITE_ANIMATION_KEY_START_EVENT'), - SPRITE_ANIMATION_KEY_UPDATE: require('./SPRITE_ANIMATION_KEY_UPDATE_EVENT'), - SPRITE_ANIMATION_REPEAT: require('./SPRITE_ANIMATION_REPEAT_EVENT'), - SPRITE_ANIMATION_RESTART: require('./SPRITE_ANIMATION_RESTART_EVENT'), - SPRITE_ANIMATION_START: require('./SPRITE_ANIMATION_START_EVENT'), - SPRITE_ANIMATION_UPDATE: require('./SPRITE_ANIMATION_UPDATE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Animations.Events + */ + +module.exports = { + + ADD_ANIMATION: require('./ADD_ANIMATION_EVENT'), + ANIMATION_COMPLETE: require('./ANIMATION_COMPLETE_EVENT'), + ANIMATION_REPEAT: require('./ANIMATION_REPEAT_EVENT'), + ANIMATION_RESTART: require('./ANIMATION_RESTART_EVENT'), + ANIMATION_START: require('./ANIMATION_START_EVENT'), + PAUSE_ALL: require('./PAUSE_ALL_EVENT'), + REMOVE_ANIMATION: require('./REMOVE_ANIMATION_EVENT'), + RESUME_ALL: require('./RESUME_ALL_EVENT'), + SPRITE_ANIMATION_COMPLETE: require('./SPRITE_ANIMATION_COMPLETE_EVENT'), + SPRITE_ANIMATION_KEY_COMPLETE: require('./SPRITE_ANIMATION_KEY_COMPLETE_EVENT'), + SPRITE_ANIMATION_KEY_REPEAT: require('./SPRITE_ANIMATION_KEY_REPEAT_EVENT'), + SPRITE_ANIMATION_KEY_RESTART: require('./SPRITE_ANIMATION_KEY_RESTART_EVENT'), + SPRITE_ANIMATION_KEY_START: require('./SPRITE_ANIMATION_KEY_START_EVENT'), + SPRITE_ANIMATION_KEY_UPDATE: require('./SPRITE_ANIMATION_KEY_UPDATE_EVENT'), + SPRITE_ANIMATION_REPEAT: require('./SPRITE_ANIMATION_REPEAT_EVENT'), + SPRITE_ANIMATION_RESTART: require('./SPRITE_ANIMATION_RESTART_EVENT'), + SPRITE_ANIMATION_START: require('./SPRITE_ANIMATION_START_EVENT'), + SPRITE_ANIMATION_UPDATE: require('./SPRITE_ANIMATION_UPDATE_EVENT') + +}; diff --git a/src/animations/index.js b/src/animations/index.js index ec66713ec..15fac7a5a 100644 --- a/src/animations/index.js +++ b/src/animations/index.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Animations - */ - -module.exports = { - - Animation: require('./Animation'), - AnimationFrame: require('./AnimationFrame'), - AnimationManager: require('./AnimationManager'), - Events: require('./events') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Animations + */ + +module.exports = { + + Animation: require('./Animation'), + AnimationFrame: require('./AnimationFrame'), + AnimationManager: require('./AnimationManager'), + Events: require('./events') + +}; diff --git a/src/animations/typedefs/AnimationFrame.js b/src/animations/typedefs/AnimationFrame.js index 8b0126106..3f56cdfbe 100644 --- a/src/animations/typedefs/AnimationFrame.js +++ b/src/animations/typedefs/AnimationFrame.js @@ -1,9 +1,9 @@ -/** - * @typedef {object} Phaser.Types.Animations.AnimationFrame - * @since 3.0.0 - * - * @property {string} key - The key that the animation will be associated with. i.e. sprite.animations.play(key) - * @property {(string|number)} frame - The key, or index number, of the frame within the animation. - * @property {number} [duration=0] - The duration, in ms, of this frame of the animation. - * @property {boolean} [visible] - Should the parent Game Object be visible during this frame of the animation? - */ +/** + * @typedef {object} Phaser.Types.Animations.AnimationFrame + * @since 3.0.0 + * + * @property {string} key - The key that the animation will be associated with. i.e. sprite.animations.play(key) + * @property {(string|number)} frame - The key, or index number, of the frame within the animation. + * @property {number} [duration=0] - The duration, in ms, of this frame of the animation. + * @property {boolean} [visible] - Should the parent Game Object be visible during this frame of the animation? + */ diff --git a/src/animations/typedefs/GenerateFrameNames.js b/src/animations/typedefs/GenerateFrameNames.js index 2c9e28627..5ad4c2ecf 100644 --- a/src/animations/typedefs/GenerateFrameNames.js +++ b/src/animations/typedefs/GenerateFrameNames.js @@ -1,12 +1,12 @@ -/** - * @typedef {object} Phaser.Types.Animations.GenerateFrameNames - * @since 3.0.0 - * - * @property {string} [prefix=''] - The string to append to every resulting frame name if using a range or an array of `frames`. - * @property {integer} [start=0] - If `frames` is not provided, the number of the first frame to return. - * @property {integer} [end=0] - If `frames` is not provided, the number of the last frame to return. - * @property {string} [suffix=''] - The string to append to every resulting frame name if using a range or an array of `frames`. - * @property {integer} [zeroPad=0] - The minimum expected lengths of each resulting frame's number. Numbers will be left-padded with zeroes until they are this long, then prepended and appended to create the resulting frame name. - * @property {Phaser.Types.Animations.AnimationFrame[]} [outputArray=[]] - The array to append the created configuration objects to. - * @property {(boolean|integer[])} [frames=false] - If provided as an array, the range defined by `start` and `end` will be ignored and these frame numbers will be used. - */ +/** + * @typedef {object} Phaser.Types.Animations.GenerateFrameNames + * @since 3.0.0 + * + * @property {string} [prefix=''] - The string to append to every resulting frame name if using a range or an array of `frames`. + * @property {integer} [start=0] - If `frames` is not provided, the number of the first frame to return. + * @property {integer} [end=0] - If `frames` is not provided, the number of the last frame to return. + * @property {string} [suffix=''] - The string to append to every resulting frame name if using a range or an array of `frames`. + * @property {integer} [zeroPad=0] - The minimum expected lengths of each resulting frame's number. Numbers will be left-padded with zeroes until they are this long, then prepended and appended to create the resulting frame name. + * @property {Phaser.Types.Animations.AnimationFrame[]} [outputArray=[]] - The array to append the created configuration objects to. + * @property {(boolean|integer[])} [frames=false] - If provided as an array, the range defined by `start` and `end` will be ignored and these frame numbers will be used. + */ diff --git a/src/animations/typedefs/JSONAnimation.js b/src/animations/typedefs/JSONAnimation.js index 9ae13c7a3..141532652 100644 --- a/src/animations/typedefs/JSONAnimation.js +++ b/src/animations/typedefs/JSONAnimation.js @@ -1,17 +1,17 @@ -/** - * @typedef {object} Phaser.Types.Animations.JSONAnimation - * @since 3.0.0 - * - * @property {string} key - The key that the animation will be associated with. i.e. sprite.animations.play(key) - * @property {string} type - A frame based animation (as opposed to a bone based animation) - * @property {Phaser.Types.Animations.JSONAnimationFrame[]} frames - An array of the AnimationFrame objects inside this Animation. - * @property {integer} frameRate - The frame rate of playback in frames per second (default 24 if duration is null) - * @property {integer} duration - How long the animation should play for in milliseconds. If not given its derived from frameRate. - * @property {boolean} skipMissedFrames - Skip frames if the time lags, or always advanced anyway? - * @property {integer} delay - Delay before starting playback. Value given in milliseconds. - * @property {integer} repeat - Number of times to repeat the animation (-1 for infinity) - * @property {integer} repeatDelay - Delay before the animation repeats. Value given in milliseconds. - * @property {boolean} yoyo - Should the animation yoyo? (reverse back down to the start) before repeating? - * @property {boolean} showOnStart - Should sprite.visible = true when the animation starts to play? - * @property {boolean} hideOnComplete - Should sprite.visible = false when the animation finishes? - */ +/** + * @typedef {object} Phaser.Types.Animations.JSONAnimation + * @since 3.0.0 + * + * @property {string} key - The key that the animation will be associated with. i.e. sprite.animations.play(key) + * @property {string} type - A frame based animation (as opposed to a bone based animation) + * @property {Phaser.Types.Animations.JSONAnimationFrame[]} frames - An array of the AnimationFrame objects inside this Animation. + * @property {integer} frameRate - The frame rate of playback in frames per second (default 24 if duration is null) + * @property {integer} duration - How long the animation should play for in milliseconds. If not given its derived from frameRate. + * @property {boolean} skipMissedFrames - Skip frames if the time lags, or always advanced anyway? + * @property {integer} delay - Delay before starting playback. Value given in milliseconds. + * @property {integer} repeat - Number of times to repeat the animation (-1 for infinity) + * @property {integer} repeatDelay - Delay before the animation repeats. Value given in milliseconds. + * @property {boolean} yoyo - Should the animation yoyo? (reverse back down to the start) before repeating? + * @property {boolean} showOnStart - Should sprite.visible = true when the animation starts to play? + * @property {boolean} hideOnComplete - Should sprite.visible = false when the animation finishes? + */ diff --git a/src/animations/typedefs/index.js b/src/animations/typedefs/index.js index b20cd2c49..23e02f94d 100644 --- a/src/animations/typedefs/index.js +++ b/src/animations/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Animations - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Animations + */ diff --git a/src/cache/BaseCache.js b/src/cache/BaseCache.js index fa5291356..20ca62ed4 100644 --- a/src/cache/BaseCache.js +++ b/src/cache/BaseCache.js @@ -1,180 +1,180 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CustomMap = require('../structs/Map'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); - -/** - * @classdesc - * The BaseCache is a base Cache class that can be used for storing references to any kind of data. - * - * Data can be added, retrieved and removed based on the given keys. - * - * Keys are string-based. - * - * @class BaseCache - * @memberof Phaser.Cache - * @constructor - * @since 3.0.0 - */ -var BaseCache = new Class({ - - initialize: - - function BaseCache () - { - /** - * The Map in which the cache objects are stored. - * - * You can query the Map directly or use the BaseCache methods. - * - * @name Phaser.Cache.BaseCache#entries - * @type {Phaser.Structs.Map.} - * @since 3.0.0 - */ - this.entries = new CustomMap(); - - /** - * An instance of EventEmitter used by the cache to emit related events. - * - * @name Phaser.Cache.BaseCache#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events = new EventEmitter(); - }, - - /** - * Adds an item to this cache. The item is referenced by a unique string, which you are responsible - * for setting and keeping track of. The item can only be retrieved by using this string. - * - * @method Phaser.Cache.BaseCache#add - * @fires Phaser.Cache.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique key by which the data added to the cache will be referenced. - * @param {*} data - The data to be stored in the cache. - * - * @return {Phaser.Cache.BaseCache} This BaseCache object. - */ - add: function (key, data) - { - this.entries.set(key, data); - - this.events.emit(Events.ADD, this, key, data); - - return this; - }, - - /** - * Checks if this cache contains an item matching the given key. - * This performs the same action as `BaseCache.exists`. - * - * @method Phaser.Cache.BaseCache#has - * @since 3.0.0 - * - * @param {string} key - The unique key of the item to be checked in this cache. - * - * @return {boolean} Returns `true` if the cache contains an item matching the given key, otherwise `false`. - */ - has: function (key) - { - return this.entries.has(key); - }, - - /** - * Checks if this cache contains an item matching the given key. - * This performs the same action as `BaseCache.has` and is called directly by the Loader. - * - * @method Phaser.Cache.BaseCache#exists - * @since 3.7.0 - * - * @param {string} key - The unique key of the item to be checked in this cache. - * - * @return {boolean} Returns `true` if the cache contains an item matching the given key, otherwise `false`. - */ - exists: function (key) - { - return this.entries.has(key); - }, - - /** - * 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. - */ - get: function (key) - { - return this.entries.get(key); - }, - - /** - * Removes and 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 {Phaser.Cache.BaseCache} This BaseCache object. - */ - remove: function (key) - { - var entry = this.get(key); - - if (entry) - { - this.entries.delete(key); - - this.events.emit(Events.REMOVE, this, key, entry.data); - } - - return this; - }, - - /** - * Returns all keys in use in this cache. - * - * @method Phaser.Cache.BaseCache#getKeys - * @since 3.17.0 - * - * @return {string[]} Array containing all the keys. - */ - getKeys: function () - { - return this.entries.keys(); - }, - - /** - * Destroys this cache and all items within it. - * - * @method Phaser.Cache.BaseCache#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.entries.clear(); - this.events.removeAllListeners(); - - this.entries = null; - this.events = null; - } - -}); - -module.exports = BaseCache; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CustomMap = require('../structs/Map'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); + +/** + * @classdesc + * The BaseCache is a base Cache class that can be used for storing references to any kind of data. + * + * Data can be added, retrieved and removed based on the given keys. + * + * Keys are string-based. + * + * @class BaseCache + * @memberof Phaser.Cache + * @constructor + * @since 3.0.0 + */ +var BaseCache = new Class({ + + initialize: + + function BaseCache () + { + /** + * The Map in which the cache objects are stored. + * + * You can query the Map directly or use the BaseCache methods. + * + * @name Phaser.Cache.BaseCache#entries + * @type {Phaser.Structs.Map.} + * @since 3.0.0 + */ + this.entries = new CustomMap(); + + /** + * An instance of EventEmitter used by the cache to emit related events. + * + * @name Phaser.Cache.BaseCache#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = new EventEmitter(); + }, + + /** + * Adds an item to this cache. The item is referenced by a unique string, which you are responsible + * for setting and keeping track of. The item can only be retrieved by using this string. + * + * @method Phaser.Cache.BaseCache#add + * @fires Phaser.Cache.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique key by which the data added to the cache will be referenced. + * @param {*} data - The data to be stored in the cache. + * + * @return {Phaser.Cache.BaseCache} This BaseCache object. + */ + add: function (key, data) + { + this.entries.set(key, data); + + this.events.emit(Events.ADD, this, key, data); + + return this; + }, + + /** + * Checks if this cache contains an item matching the given key. + * This performs the same action as `BaseCache.exists`. + * + * @method Phaser.Cache.BaseCache#has + * @since 3.0.0 + * + * @param {string} key - The unique key of the item to be checked in this cache. + * + * @return {boolean} Returns `true` if the cache contains an item matching the given key, otherwise `false`. + */ + has: function (key) + { + return this.entries.has(key); + }, + + /** + * Checks if this cache contains an item matching the given key. + * This performs the same action as `BaseCache.has` and is called directly by the Loader. + * + * @method Phaser.Cache.BaseCache#exists + * @since 3.7.0 + * + * @param {string} key - The unique key of the item to be checked in this cache. + * + * @return {boolean} Returns `true` if the cache contains an item matching the given key, otherwise `false`. + */ + exists: function (key) + { + return this.entries.has(key); + }, + + /** + * 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. + */ + get: function (key) + { + return this.entries.get(key); + }, + + /** + * Removes and 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 {Phaser.Cache.BaseCache} This BaseCache object. + */ + remove: function (key) + { + var entry = this.get(key); + + if (entry) + { + this.entries.delete(key); + + this.events.emit(Events.REMOVE, this, key, entry.data); + } + + return this; + }, + + /** + * Returns all keys in use in this cache. + * + * @method Phaser.Cache.BaseCache#getKeys + * @since 3.17.0 + * + * @return {string[]} Array containing all the keys. + */ + getKeys: function () + { + return this.entries.keys(); + }, + + /** + * Destroys this cache and all items within it. + * + * @method Phaser.Cache.BaseCache#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.entries.clear(); + this.events.removeAllListeners(); + + this.entries = null; + this.events = null; + } + +}); + +module.exports = BaseCache; diff --git a/src/cache/CacheManager.js b/src/cache/CacheManager.js index 16f96be72..18ad0fe4b 100644 --- a/src/cache/CacheManager.js +++ b/src/cache/CacheManager.js @@ -1,228 +1,228 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseCache = require('./BaseCache'); -var Class = require('../utils/Class'); -var GameEvents = require('../core/events'); - -/** - * @classdesc - * The Cache Manager is the global cache owned and maintained by the Game instance. - * - * Various systems, such as the file Loader, rely on this cache in order to store the files - * it has loaded. The manager itself doesn't store any files, but instead owns multiple BaseCache - * instances, one per type of file. You can also add your own custom caches. - * - * @class CacheManager - * @memberof Phaser.Cache - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - A reference to the Phaser.Game instance that owns this CacheManager. - */ -var CacheManager = new Class({ - - initialize: - - function CacheManager (game) - { - /** - * A reference to the Phaser.Game instance that owns this CacheManager. - * - * @name Phaser.Cache.CacheManager#game - * @type {Phaser.Game} - * @protected - * @since 3.0.0 - */ - this.game = game; - - /** - * A Cache storing all binary files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#binary - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.binary = new BaseCache(); - - /** - * A Cache storing all bitmap font data files, typically added via the Loader. - * Only the font data is stored in this cache, the textures are part of the Texture Manager. - * - * @name Phaser.Cache.CacheManager#bitmapFont - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.bitmapFont = new BaseCache(); - - /** - * A Cache storing all JSON data files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#json - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.json = new BaseCache(); - - /** - * A Cache storing all physics data files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#physics - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.physics = new BaseCache(); - - /** - * A Cache storing all shader source files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#shader - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.shader = new BaseCache(); - - /** - * A Cache storing all non-streaming audio files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#audio - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.audio = new BaseCache(); - - /** - * A Cache storing all non-streaming video files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#video - * @type {Phaser.Cache.BaseCache} - * @since 3.20.0 - */ - this.video = new BaseCache(); - - /** - * A Cache storing all text files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#text - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.text = new BaseCache(); - - /** - * A Cache storing all html files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#html - * @type {Phaser.Cache.BaseCache} - * @since 3.12.0 - */ - this.html = new BaseCache(); - - /** - * A Cache storing all WaveFront OBJ files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#obj - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.obj = new BaseCache(); - - /** - * A Cache storing all tilemap data files, typically added via the Loader. - * Only the data is stored in this cache, the textures are part of the Texture Manager. - * - * @name Phaser.Cache.CacheManager#tilemap - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.tilemap = new BaseCache(); - - /** - * A Cache storing all xml data files, typically added via the Loader. - * - * @name Phaser.Cache.CacheManager#xml - * @type {Phaser.Cache.BaseCache} - * @since 3.0.0 - */ - this.xml = new BaseCache(); - - /** - * An object that contains your own custom BaseCache entries. - * Add to this via the `addCustom` method. - * - * @name Phaser.Cache.CacheManager#custom - * @type {Object.} - * @since 3.0.0 - */ - this.custom = {}; - - this.game.events.once(GameEvents.DESTROY, this.destroy, this); - }, - - /** - * Add your own custom Cache for storing your own files. - * The cache will be available under `Cache.custom.key`. - * The cache will only be created if the key is not already in use. - * - * @method Phaser.Cache.CacheManager#addCustom - * @since 3.0.0 - * - * @param {string} key - The unique key of your custom cache. - * - * @return {Phaser.Cache.BaseCache} A reference to the BaseCache that was created. If the key was already in use, a reference to the existing cache is returned instead. - */ - addCustom: function (key) - { - if (!this.custom.hasOwnProperty(key)) - { - this.custom[key] = new BaseCache(); - } - - return this.custom[key]; - }, - - /** - * Removes all entries from all BaseCaches and destroys all custom caches. - * - * @method Phaser.Cache.CacheManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - var keys = [ - 'binary', - 'bitmapFont', - 'json', - 'physics', - 'shader', - 'audio', - 'video', - 'text', - 'html', - 'obj', - 'tilemap', - 'xml' - ]; - - for (var i = 0; i < keys.length; i++) - { - this[keys[i]].destroy(); - this[keys[i]] = null; - } - - for (var key in this.custom) - { - this.custom[key].destroy(); - } - - this.custom = null; - - this.game = null; - } - -}); - -module.exports = CacheManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCache = require('./BaseCache'); +var Class = require('../utils/Class'); +var GameEvents = require('../core/events'); + +/** + * @classdesc + * The Cache Manager is the global cache owned and maintained by the Game instance. + * + * Various systems, such as the file Loader, rely on this cache in order to store the files + * it has loaded. The manager itself doesn't store any files, but instead owns multiple BaseCache + * instances, one per type of file. You can also add your own custom caches. + * + * @class CacheManager + * @memberof Phaser.Cache + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser.Game instance that owns this CacheManager. + */ +var CacheManager = new Class({ + + initialize: + + function CacheManager (game) + { + /** + * A reference to the Phaser.Game instance that owns this CacheManager. + * + * @name Phaser.Cache.CacheManager#game + * @type {Phaser.Game} + * @protected + * @since 3.0.0 + */ + this.game = game; + + /** + * A Cache storing all binary files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#binary + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.binary = new BaseCache(); + + /** + * A Cache storing all bitmap font data files, typically added via the Loader. + * Only the font data is stored in this cache, the textures are part of the Texture Manager. + * + * @name Phaser.Cache.CacheManager#bitmapFont + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.bitmapFont = new BaseCache(); + + /** + * A Cache storing all JSON data files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#json + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.json = new BaseCache(); + + /** + * A Cache storing all physics data files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#physics + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.physics = new BaseCache(); + + /** + * A Cache storing all shader source files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#shader + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.shader = new BaseCache(); + + /** + * A Cache storing all non-streaming audio files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#audio + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.audio = new BaseCache(); + + /** + * A Cache storing all non-streaming video files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#video + * @type {Phaser.Cache.BaseCache} + * @since 3.20.0 + */ + this.video = new BaseCache(); + + /** + * A Cache storing all text files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#text + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.text = new BaseCache(); + + /** + * A Cache storing all html files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#html + * @type {Phaser.Cache.BaseCache} + * @since 3.12.0 + */ + this.html = new BaseCache(); + + /** + * A Cache storing all WaveFront OBJ files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#obj + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.obj = new BaseCache(); + + /** + * A Cache storing all tilemap data files, typically added via the Loader. + * Only the data is stored in this cache, the textures are part of the Texture Manager. + * + * @name Phaser.Cache.CacheManager#tilemap + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.tilemap = new BaseCache(); + + /** + * A Cache storing all xml data files, typically added via the Loader. + * + * @name Phaser.Cache.CacheManager#xml + * @type {Phaser.Cache.BaseCache} + * @since 3.0.0 + */ + this.xml = new BaseCache(); + + /** + * An object that contains your own custom BaseCache entries. + * Add to this via the `addCustom` method. + * + * @name Phaser.Cache.CacheManager#custom + * @type {Object.} + * @since 3.0.0 + */ + this.custom = {}; + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Add your own custom Cache for storing your own files. + * The cache will be available under `Cache.custom.key`. + * The cache will only be created if the key is not already in use. + * + * @method Phaser.Cache.CacheManager#addCustom + * @since 3.0.0 + * + * @param {string} key - The unique key of your custom cache. + * + * @return {Phaser.Cache.BaseCache} A reference to the BaseCache that was created. If the key was already in use, a reference to the existing cache is returned instead. + */ + addCustom: function (key) + { + if (!this.custom.hasOwnProperty(key)) + { + this.custom[key] = new BaseCache(); + } + + return this.custom[key]; + }, + + /** + * Removes all entries from all BaseCaches and destroys all custom caches. + * + * @method Phaser.Cache.CacheManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + var keys = [ + 'binary', + 'bitmapFont', + 'json', + 'physics', + 'shader', + 'audio', + 'video', + 'text', + 'html', + 'obj', + 'tilemap', + 'xml' + ]; + + for (var i = 0; i < keys.length; i++) + { + this[keys[i]].destroy(); + this[keys[i]] = null; + } + + for (var key in this.custom) + { + this.custom[key].destroy(); + } + + this.custom = null; + + this.game = null; + } + +}); + +module.exports = CacheManager; diff --git a/src/cache/events/ADD_EVENT.js b/src/cache/events/ADD_EVENT.js index 78d1d0bec..cc3056aac 100644 --- a/src/cache/events/ADD_EVENT.js +++ b/src/cache/events/ADD_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Cache Add Event. - * - * This event is dispatched by any Cache that extends the BaseCache each time a new object is added to it. - * - * @event Phaser.Cache.Events#ADD - * @since 3.0.0 - * - * @param {Phaser.Cache.BaseCache} cache - The cache to which the object was added. - * @param {string} key - The key of the object added to the cache. - * @param {*} object - A reference to the object that was added to the cache. - */ -module.exports = 'add'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Cache Add Event. + * + * This event is dispatched by any Cache that extends the BaseCache each time a new object is added to it. + * + * @event Phaser.Cache.Events#ADD + * @since 3.0.0 + * + * @param {Phaser.Cache.BaseCache} cache - The cache to which the object was added. + * @param {string} key - The key of the object added to the cache. + * @param {*} object - A reference to the object that was added to the cache. + */ +module.exports = 'add'; diff --git a/src/cache/events/REMOVE_EVENT.js b/src/cache/events/REMOVE_EVENT.js index 5f57d76f4..6e38cfe3e 100644 --- a/src/cache/events/REMOVE_EVENT.js +++ b/src/cache/events/REMOVE_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Cache Remove Event. - * - * This event is dispatched by any Cache that extends the BaseCache each time an object is removed from it. - * - * @event Phaser.Cache.Events#REMOVE - * @since 3.0.0 - * - * @param {Phaser.Cache.BaseCache} cache - The cache from which the object was removed. - * @param {string} key - The key of the object removed from the cache. - * @param {*} object - A reference to the object that was removed from the cache. - */ -module.exports = 'remove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Cache Remove Event. + * + * This event is dispatched by any Cache that extends the BaseCache each time an object is removed from it. + * + * @event Phaser.Cache.Events#REMOVE + * @since 3.0.0 + * + * @param {Phaser.Cache.BaseCache} cache - The cache from which the object was removed. + * @param {string} key - The key of the object removed from the cache. + * @param {*} object - A reference to the object that was removed from the cache. + */ +module.exports = 'remove'; diff --git a/src/cache/events/index.js b/src/cache/events/index.js index 11a2b0880..95b11c4c8 100644 --- a/src/cache/events/index.js +++ b/src/cache/events/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cache.Events - */ - -module.exports = { - - ADD: require('./ADD_EVENT'), - REMOVE: require('./REMOVE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cache.Events + */ + +module.exports = { + + ADD: require('./ADD_EVENT'), + REMOVE: require('./REMOVE_EVENT') + +}; diff --git a/src/cache/index.js b/src/cache/index.js index 45db4eff9..2f908cd90 100644 --- a/src/cache/index.js +++ b/src/cache/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cache - */ - -module.exports = { - - BaseCache: require('./BaseCache'), - CacheManager: require('./CacheManager'), - Events: require('./events') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cache + */ + +module.exports = { + + BaseCache: require('./BaseCache'), + CacheManager: require('./CacheManager'), + Events: require('./events') + +}; diff --git a/src/cameras/2d/BaseCamera.js b/src/cameras/2d/BaseCamera.js index 837ab9799..0e4a7cee1 100644 --- a/src/cameras/2d/BaseCamera.js +++ b/src/cameras/2d/BaseCamera.js @@ -1,1915 +1,1915 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../../gameobjects/components'); -var DegToRad = require('../../math/DegToRad'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); -var ValueToColor = require('../../display/color/ValueToColor'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Base Camera class. - * - * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, - * and can be positioned, rotated, zoomed and scrolled accordingly. - * - * A Camera consists of two elements: The viewport and the scroll values. - * - * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are - * created the same size as your game, but their position and size can be set to anything. This means if you - * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, - * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). - * - * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this - * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the - * viewport, and changing the viewport has no impact on the scrolling. - * - * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, - * allowing you to filter Game Objects out on a per-Camera basis. - * - * The Base Camera is extended by the Camera class, which adds in special effects including Fade, - * Flash and Camera Shake, as well as the ability to follow Game Objects. - * - * The Base Camera was introduced in Phaser 3.12. It was split off from the Camera class, to allow - * you to isolate special effects as needed. Therefore the 'since' values for properties of this class relate - * to when they were added to the Camera class. - * - * @class BaseCamera - * @memberof Phaser.Cameras.Scene2D - * @constructor - * @since 3.12.0 - * - * @extends Phaser.Events.EventEmitter - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.Visible - * - * @param {number} x - The x position of the Camera, relative to the top-left of the game canvas. - * @param {number} y - The y position of the Camera, relative to the top-left of the game canvas. - * @param {number} width - The width of the Camera, in pixels. - * @param {number} height - The height of the Camera, in pixels. - */ -var BaseCamera = new Class({ - - Extends: EventEmitter, - - Mixins: [ - Components.Alpha, - Components.Visible - ], - - initialize: - - function BaseCamera (x, y, width, height) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 0; } - if (height === undefined) { height = 0; } - - EventEmitter.call(this); - - /** - * A reference to the Scene this camera belongs to. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene; - - /** - * A reference to the Game Scene Manager. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#sceneManager - * @type {Phaser.Scenes.SceneManager} - * @since 3.12.0 - */ - this.sceneManager; - - /** - * A reference to the Game Scale Manager. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#scaleManager - * @type {Phaser.Scale.ScaleManager} - * @since 3.16.0 - */ - this.scaleManager; - - /** - * A reference to the Scene's Camera Manager to which this Camera belongs. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#cameraManager - * @type {Phaser.Cameras.Scene2D.CameraManager} - * @since 3.17.0 - */ - this.cameraManager; - - /** - * The Camera ID. Assigned by the Camera Manager and used to handle camera exclusion. - * This value is a bitmask. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#id - * @type {integer} - * @readonly - * @since 3.11.0 - */ - this.id = 0; - - /** - * The name of the Camera. This is left empty for your own use. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#name - * @type {string} - * @default '' - * @since 3.0.0 - */ - this.name = ''; - - /** - * This property is un-used in v3.16. - * - * The resolution of the Game, used in most Camera calculations. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#resolution - * @type {number} - * @readonly - * @deprecated - * @since 3.12.0 - */ - this.resolution = 1; - - /** - * Should this camera round its pixel values to integers? - * - * @name Phaser.Cameras.Scene2D.BaseCamera#roundPixels - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.roundPixels = false; - - /** - * Is this Camera visible or not? - * - * A visible camera will render and perform input tests. - * An invisible camera will not render anything and will skip input tests. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#visible - * @type {boolean} - * @default true - * @since 3.10.0 - */ - - /** - * Is this Camera using a bounds to restrict scrolling movement? - * - * Set this property along with the bounds via `Camera.setBounds`. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#useBounds - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.useBounds = false; - - /** - * The World View is a Rectangle that defines the area of the 'world' the Camera is currently looking at. - * This factors in the Camera viewport size, zoom and scroll position and is updated in the Camera preRender step. - * If you have enabled Camera bounds the worldview will be clamped to those bounds accordingly. - * You can use it for culling or intersection checks. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#worldView - * @type {Phaser.Geom.Rectangle} - * @readonly - * @since 3.11.0 - */ - this.worldView = new Rectangle(); - - /** - * Is this Camera dirty? - * - * A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. - * - * This flag is cleared during the `postRenderCamera` method of the renderer. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#dirty - * @type {boolean} - * @default true - * @since 3.11.0 - */ - this.dirty = true; - - /** - * The x position of the Camera viewport, relative to the top-left of the game canvas. - * The viewport is the area into which the camera renders. - * To adjust the position the camera is looking at in the game world, see the `scrollX` value. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#x - * @type {number} - * @private - * @since 3.0.0 - */ - this._x = x; - - /** - * The y position of the Camera, relative to the top-left of the game canvas. - * The viewport is the area into which the camera renders. - * To adjust the position the camera is looking at in the game world, see the `scrollY` value. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#y - * @type {number} - * @private - * @since 3.0.0 - */ - this._y = y; - - /** - * Internal Camera X value multiplied by the resolution. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_cx - * @type {number} - * @private - * @since 3.12.0 - */ - this._cx = 0; - - /** - * Internal Camera Y value multiplied by the resolution. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_cy - * @type {number} - * @private - * @since 3.12.0 - */ - this._cy = 0; - - /** - * Internal Camera Width value multiplied by the resolution. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_cw - * @type {number} - * @private - * @since 3.12.0 - */ - this._cw = 0; - - /** - * Internal Camera Height value multiplied by the resolution. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_ch - * @type {number} - * @private - * @since 3.12.0 - */ - this._ch = 0; - - /** - * The width of the Camera viewport, in pixels. - * - * The viewport is the area into which the Camera renders. Setting the viewport does - * not restrict where the Camera can scroll to. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_width - * @type {number} - * @private - * @since 3.11.0 - */ - this._width = width; - - /** - * The height of the Camera viewport, in pixels. - * - * The viewport is the area into which the Camera renders. Setting the viewport does - * not restrict where the Camera can scroll to. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_height - * @type {number} - * @private - * @since 3.11.0 - */ - this._height = height; - - /** - * The bounds the camera is restrained to during scrolling. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_bounds - * @type {Phaser.Geom.Rectangle} - * @private - * @since 3.0.0 - */ - this._bounds = new Rectangle(); - - /** - * The horizontal scroll position of this Camera. - * - * Change this value to cause the Camera to scroll around your Scene. - * - * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, - * will automatically adjust the Camera scroll values accordingly. - * - * You can set the bounds within which the Camera can scroll via the `setBounds` method. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_scrollX - * @type {number} - * @private - * @default 0 - * @since 3.11.0 - */ - this._scrollX = 0; - - /** - * The vertical scroll position of this Camera. - * - * Change this value to cause the Camera to scroll around your Scene. - * - * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, - * will automatically adjust the Camera scroll values accordingly. - * - * You can set the bounds within which the Camera can scroll via the `setBounds` method. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_scrollY - * @type {number} - * @private - * @default 0 - * @since 3.11.0 - */ - this._scrollY = 0; - - /** - * The Camera zoom value. Change this value to zoom in, or out of, a Scene. - * - * A value of 0.5 would zoom the Camera out, so you can now see twice as much - * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel - * now takes up 2 pixels when rendered. - * - * Set to 1 to return to the default zoom level. - * - * Be careful to never set this value to zero. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_zoom - * @type {number} - * @private - * @default 1 - * @since 3.11.0 - */ - this._zoom = 1; - - /** - * 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 - */ - this._rotation = 0; - - /** - * A local transform matrix used for internal calculations. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#matrix - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @private - * @since 3.0.0 - */ - this.matrix = new TransformMatrix(); - - /** - * Does this Camera have a transparent background? - * - * @name Phaser.Cameras.Scene2D.BaseCamera#transparent - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.transparent = true; - - /** - * The background color of this Camera. Only used if `transparent` is `false`. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#backgroundColor - * @type {Phaser.Display.Color} - * @since 3.0.0 - */ - this.backgroundColor = ValueToColor('rgba(0,0,0,0)'); - - /** - * The Camera alpha value. Setting this property impacts every single object that this Camera - * renders. You can either set the property directly, i.e. via a Tween, to fade a Camera in or out, - * or via the chainable `setAlpha` method instead. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#alpha - * @type {number} - * @default 1 - * @since 3.11.0 - */ - - /** - * Should the camera cull Game Objects before checking them for input hit tests? - * In some special cases it may be beneficial to disable this. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#disableCull - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.disableCull = false; - - /** - * A temporary array of culled objects. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#culledObjects - * @type {Phaser.GameObjects.GameObject[]} - * @default [] - * @private - * @since 3.0.0 - */ - this.culledObjects = []; - - /** - * The mid-point of the Camera in 'world' coordinates. - * - * Use it to obtain exactly where in the world the center of the camera is currently looking. - * - * This value is updated in the preRender method, after the scroll values and follower - * have been processed. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#midPoint - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.11.0 - */ - this.midPoint = new Vector2(width / 2, height / 2); - - /** - * The horizontal origin of rotation for this Camera. - * - * By default the camera rotates around the center of the viewport. - * - * Changing the origin allows you to adjust the point in the viewport from which rotation happens. - * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. - * - * See `setOrigin` to set both origins in a single, chainable call. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#originX - * @type {number} - * @default 0.5 - * @since 3.11.0 - */ - this.originX = 0.5; - - /** - * The vertical origin of rotation for this Camera. - * - * By default the camera rotates around the center of the viewport. - * - * Changing the origin allows you to adjust the point in the viewport from which rotation happens. - * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. - * - * See `setOrigin` to set both origins in a single, chainable call. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#originY - * @type {number} - * @default 0.5 - * @since 3.11.0 - */ - this.originY = 0.5; - - /** - * Does this Camera have a custom viewport? - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_customViewport - * @type {boolean} - * @private - * @default false - * @since 3.12.0 - */ - this._customViewport = false; - - /** - * The Mask this Camera is using during render. - * Set the mask using the `setMask` method. Remove the mask using the `clearMask` method. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#mask - * @type {?(Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask)} - * @since 3.17.0 - */ - this.mask = null; - - /** - * The Camera that this Camera uses for translation during masking. - * - * If the mask is fixed in position this will be a reference to - * the CameraManager.default instance. Otherwise, it'll be a reference - * to itself. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#_maskCamera - * @type {?Phaser.Cameras.Scene2D.BaseCamera} - * @private - * @since 3.17.0 - */ - this._maskCamera = null; - }, - - /** - * Set the Alpha level of this Camera. The alpha controls the opacity of the Camera as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setAlpha - * @since 3.11.0 - * - * @param {number} [value=1] - The Camera alpha value. - * - * @return {this} This Camera instance. - */ - - /** - * Sets the rotation origin of this Camera. - * - * The values are given in the range 0 to 1 and are only used when calculating Camera rotation. - * - * By default the camera rotates around the center of the viewport. - * - * Changing the origin allows you to adjust the point in the viewport from which rotation happens. - * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setOrigin - * @since 3.11.0 - * - * @param {number} [x=0.5] - The horizontal origin value. - * @param {number} [y=x] - The vertical origin value. If not defined it will be set to the value of `x`. - * - * @return {this} This Camera instance. - */ - setOrigin: function (x, y) - { - if (x === undefined) { x = 0.5; } - if (y === undefined) { y = x; } - - this.originX = x; - this.originY = y; - - return this; - }, - - /** - * 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. - */ - getScroll: function (x, y, out) - { - if (out === undefined) { out = new Vector2(); } - - var originX = this.width * 0.5; - var originY = this.height * 0.5; - - out.x = x - originX; - out.y = y - originY; - - if (this.useBounds) - { - out.x = this.clampX(out.x); - out.y = this.clampY(out.y); - } - - return out; - }, - - /** - * Moves the Camera horizontally so that it is centered on the given x coordinate, bounds allowing. - * Calling this does not change the scrollY value. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#centerOnX - * @since 3.16.0 - * - * @param {number} x - The horizontal coordinate to center on. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - centerOnX: function (x) - { - var originX = this.width * 0.5; - - this.midPoint.x = x; - - this.scrollX = x - originX; - - if (this.useBounds) - { - this.scrollX = this.clampX(this.scrollX); - } - - return this; - }, - - /** - * Moves the Camera vertically so that it is centered on the given y coordinate, bounds allowing. - * Calling this does not change the scrollX value. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#centerOnY - * @since 3.16.0 - * - * @param {number} y - The vertical coordinate to center on. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - centerOnY: function (y) - { - var originY = this.height * 0.5; - - this.midPoint.y = y; - - this.scrollY = y - originY; - - if (this.useBounds) - { - this.scrollY = this.clampY(this.scrollY); - } - - return this; - }, - - /** - * Moves the Camera so that it is centered on the given coordinates, bounds allowing. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#centerOn - * @since 3.11.0 - * - * @param {number} x - The horizontal coordinate to center on. - * @param {number} y - The vertical coordinate to center on. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - centerOn: function (x, y) - { - this.centerOnX(x); - this.centerOnY(y); - - return this; - }, - - /** - * Moves the Camera so that it is looking at the center of the Camera Bounds, if enabled. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#centerToBounds - * @since 3.0.0 - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - centerToBounds: function () - { - if (this.useBounds) - { - var bounds = this._bounds; - var originX = this.width * 0.5; - var originY = this.height * 0.5; - - this.midPoint.set(bounds.centerX, bounds.centerY); - - this.scrollX = bounds.centerX - originX; - this.scrollY = bounds.centerY - originY; - } - - return this; - }, - - /** - * 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 {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - centerToSize: function () - { - this.scrollX = this.width * 0.5; - this.scrollY = this.height * 0.5; - - return this; - }, - - /** - * Takes an array of Game Objects and returns a new array featuring only those objects - * visible by this camera. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#cull - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject[]} G - [renderableObjects,$return] - * - * @param {Phaser.GameObjects.GameObject[]} renderableObjects - An array of Game Objects to cull. - * - * @return {Phaser.GameObjects.GameObject[]} An array of Game Objects visible to this Camera. - */ - cull: function (renderableObjects) - { - if (this.disableCull) - { - return renderableObjects; - } - - var cameraMatrix = this.matrix.matrix; - - var mva = cameraMatrix[0]; - var mvb = cameraMatrix[1]; - var mvc = cameraMatrix[2]; - var mvd = cameraMatrix[3]; - - /* First Invert Matrix */ - var determinant = (mva * mvd) - (mvb * mvc); - - if (!determinant) - { - return renderableObjects; - } - - var mve = cameraMatrix[4]; - var mvf = cameraMatrix[5]; - - var scrollX = this.scrollX; - var scrollY = this.scrollY; - var cameraW = this.width; - var cameraH = this.height; - var culledObjects = this.culledObjects; - var length = renderableObjects.length; - - determinant = 1 / determinant; - - culledObjects.length = 0; - - for (var index = 0; index < length; ++index) - { - var object = renderableObjects[index]; - - if (!object.hasOwnProperty('width') || object.parentContainer) - { - culledObjects.push(object); - continue; - } - - var objectW = object.width; - var objectH = object.height; - var objectX = (object.x - (scrollX * object.scrollFactorX)) - (objectW * object.originX); - var objectY = (object.y - (scrollY * object.scrollFactorY)) - (objectH * object.originY); - var tx = (objectX * mva + objectY * mvc + mve); - var ty = (objectX * mvb + objectY * mvd + mvf); - var tw = ((objectX + objectW) * mva + (objectY + objectH) * mvc + mve); - var th = ((objectX + objectW) * mvb + (objectY + objectH) * mvd + mvf); - var cullTop = this.y; - var cullBottom = cullTop + cameraH; - var cullLeft = this.x; - var cullRight = cullLeft + cameraW; - - if ((tw > cullLeft && tx < cullRight) && (th > cullTop && ty < cullBottom)) - { - culledObjects.push(object); - } - } - - return culledObjects; - }, - - /** - * 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. - */ - getWorldPoint: function (x, y, output) - { - if (output === undefined) { output = new Vector2(); } - - var cameraMatrix = this.matrix.matrix; - - var mva = cameraMatrix[0]; - var mvb = cameraMatrix[1]; - var mvc = cameraMatrix[2]; - var mvd = cameraMatrix[3]; - var mve = cameraMatrix[4]; - var mvf = cameraMatrix[5]; - - // Invert Matrix - var determinant = (mva * mvd) - (mvb * mvc); - - if (!determinant) - { - output.x = x; - output.y = y; - - return output; - } - - determinant = 1 / determinant; - - var ima = mvd * determinant; - var imb = -mvb * determinant; - var imc = -mvc * determinant; - var imd = mva * determinant; - var ime = (mvc * mvf - mvd * mve) * determinant; - var imf = (mvb * mve - mva * mvf) * determinant; - - var c = Math.cos(this.rotation); - var s = Math.sin(this.rotation); - - var zoom = this.zoom; - var res = this.resolution; - - var scrollX = this.scrollX; - var scrollY = this.scrollY; - - // Works for zoom of 1 with any resolution, but resolution > 1 and zoom !== 1 breaks - var sx = x + ((scrollX * c - scrollY * s) * zoom); - var sy = y + ((scrollX * s + scrollY * c) * zoom); - - // Apply transform to point - output.x = (sx * ima + sy * imc) * res + ime; - output.y = (sx * imb + sy * imd) * res + imf; - - return output; - }, - - /** - * Given a Game Object, or an array of Game Objects, it will update all of their camera filter settings - * so that they are ignored by this Camera. This means they will not be rendered by this Camera. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#ignore - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group)} entries - The Game Object, or array of Game Objects, to be ignored by this Camera. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - ignore: function (entries) - { - var id = this.id; - - if (!Array.isArray(entries)) - { - entries = [ entries ]; - } - - for (var i = 0; i < entries.length; i++) - { - var entry = entries[i]; - - if (Array.isArray(entry)) - { - this.ignore(entry); - } - else if (entry.isParent) - { - this.ignore(entry.getChildren()); - } - else - { - entry.cameraFilter |= id; - } - } - - return this; - }, - - /** - * Internal preRender step. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#preRender - * @protected - * @since 3.0.0 - * - * @param {number} resolution - The game resolution, as set in the Scale Manager. - */ - preRender: function (resolution) - { - var width = this.width; - var height = this.height; - - var halfWidth = width * 0.5; - var halfHeight = height * 0.5; - - var zoom = this.zoom * resolution; - var matrix = this.matrix; - - var originX = width * this.originX; - var originY = height * this.originY; - - var sx = this.scrollX; - var sy = this.scrollY; - - if (this.useBounds) - { - sx = this.clampX(sx); - sy = this.clampY(sy); - } - - if (this.roundPixels) - { - originX = Math.round(originX); - originY = Math.round(originY); - } - - // Values are in pixels and not impacted by zooming the Camera - this.scrollX = sx; - this.scrollY = sy; - - var midX = sx + halfWidth; - var midY = sy + halfHeight; - - // 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 - this.midPoint.set(midX, midY); - - var displayWidth = width / zoom; - var displayHeight = height / zoom; - - this.worldView.setTo( - midX - (displayWidth / 2), - midY - (displayHeight / 2), - displayWidth, - displayHeight - ); - - matrix.applyITRS(this.x + originX, this.y + originY, this.rotation, zoom, zoom); - matrix.translate(-originX, -originY); - }, - - /** - * Takes an x value and checks it's within the range of the Camera bounds, adjusting if required. - * Do not call this method if you are not using camera bounds. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#clampX - * @since 3.11.0 - * - * @param {number} x - The value to horizontally scroll clamp. - * - * @return {number} The adjusted value to use as scrollX. - */ - clampX: function (x) - { - var bounds = this._bounds; - - var dw = this.displayWidth; - - var bx = bounds.x + ((dw - this.width) / 2); - var bw = Math.max(bx, bx + bounds.width - dw); - - if (x < bx) - { - x = bx; - } - else if (x > bw) - { - x = bw; - } - - return x; - }, - - /** - * Takes a y value and checks it's within the range of the Camera bounds, adjusting if required. - * Do not call this method if you are not using camera bounds. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#clampY - * @since 3.11.0 - * - * @param {number} y - The value to vertically scroll clamp. - * - * @return {number} The adjusted value to use as scrollY. - */ - clampY: function (y) - { - var bounds = this._bounds; - - var dh = this.displayHeight; - - var by = bounds.y + ((dh - this.height) / 2); - var bh = Math.max(by, by + bounds.height - dh); - - if (y < by) - { - y = by; - } - else if (y > bh) - { - y = bh; - } - - return y; - }, - - /* - var gap = this._zoomInversed; - return gap * Math.round((src.x - this.scrollX * src.scrollFactorX) / gap); - */ - - /** - * If this Camera has previously had movement bounds set on it, this will remove them. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#removeBounds - * @since 3.0.0 - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - removeBounds: function () - { - this.useBounds = false; - - this.dirty = true; - - this._bounds.setEmpty(); - - return this; - }, - - /** - * Set the rotation of this Camera. This causes everything it renders to appear rotated. - * - * Rotating a camera does not rotate the viewport itself, it is applied during rendering. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setAngle - * @since 3.0.0 - * - * @param {number} [value=0] - The cameras angle of rotation, given in degrees. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setAngle: function (value) - { - if (value === undefined) { value = 0; } - - this.rotation = DegToRad(value); - - return this; - }, - - /** - * Sets the background color for this Camera. - * - * By default a Camera has a transparent background but it can be given a solid color, with any level - * of transparency, via this method. - * - * The color value can be specified using CSS color notation, hex or numbers. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setBackgroundColor - * @since 3.0.0 - * - * @param {(string|number|Phaser.Types.Display.InputColorObject)} [color='rgba(0,0,0,0)'] - The color value. In CSS, hex or numeric color notation. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setBackgroundColor: function (color) - { - if (color === undefined) { color = 'rgba(0,0,0,0)'; } - - this.backgroundColor = ValueToColor(color); - - this.transparent = (this.backgroundColor.alpha === 0); - - return this; - }, - - /** - * Set the bounds of the Camera. The bounds are an axis-aligned rectangle. - * - * The Camera bounds controls where the Camera can scroll to, stopping it from scrolling off the - * edges and into blank space. It does not limit the placement of Game Objects, or where - * the Camera viewport can be positioned. - * - * Temporarily disable the bounds by changing the boolean `Camera.useBounds`. - * - * Clear the bounds entirely by calling `Camera.removeBounds`. - * - * If you set bounds that are smaller than the viewport it will stop the Camera from being - * able to scroll. The bounds can be positioned where-ever you wish. By default they are from - * 0x0 to the canvas width x height. This means that the coordinate 0x0 is the top left of - * the Camera bounds. However, you can position them anywhere. So if you wanted a game world - * that was 2048x2048 in size, with 0x0 being the center of it, you can set the bounds x/y - * to be -1024, -1024, with a width and height of 2048. Depending on your game you may find - * it easier for 0x0 to be the top-left of the bounds, or you may wish 0x0 to be the middle. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setBounds - * @since 3.0.0 - * - * @param {integer} x - The top-left x coordinate of the bounds. - * @param {integer} y - The top-left y coordinate of the bounds. - * @param {integer} width - The width of the bounds, in pixels. - * @param {integer} height - The height of the bounds, in pixels. - * @param {boolean} [centerOn=false] - If `true` the Camera will automatically be centered on the new bounds. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setBounds: function (x, y, width, height, centerOn) - { - if (centerOn === undefined) { centerOn = false; } - - this._bounds.setTo(x, y, width, height); - - this.dirty = true; - this.useBounds = true; - - if (centerOn) - { - this.centerToBounds(); - } - else - { - this.scrollX = this.clampX(this.scrollX); - this.scrollY = this.clampY(this.scrollY); - } - - return this; - }, - - /** - * Returns a rectangle containing the bounds of the Camera. - * - * If the Camera does not have any bounds the rectangle will be empty. - * - * The rectangle is a copy of the bounds, so is safe to modify. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#getBounds - * @since 3.16.0 - * - * @param {Phaser.Geom.Rectangle} [out] - An optional Rectangle to store the bounds in. If not given, a new Rectangle will be created. - * - * @return {Phaser.Geom.Rectangle} A rectangle containing the bounds of this Camera. - */ - getBounds: function (out) - { - if (out === undefined) { out = new Rectangle(); } - - var source = this._bounds; - - out.setTo(source.x, source.y, source.width, source.height); - - return out; - }, - - /** - * Sets the name of this Camera. - * This value is for your own use and isn't used internally. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setName - * @since 3.0.0 - * - * @param {string} [value=''] - The name of the Camera. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setName: function (value) - { - if (value === undefined) { value = ''; } - - this.name = value; - - return this; - }, - - /** - * Set the position of the Camera viewport within the game. - * - * This does not change where the camera is 'looking'. See `setScroll` to control that. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setPosition - * @since 3.0.0 - * - * @param {number} x - The top-left x coordinate of the Camera viewport. - * @param {number} [y=x] - The top-left y coordinate of the Camera viewport. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setPosition: function (x, y) - { - if (y === undefined) { y = x; } - - this.x = x; - this.y = y; - - return this; - }, - - /** - * Set the rotation of this Camera. This causes everything it renders to appear rotated. - * - * Rotating a camera does not rotate the viewport itself, it is applied during rendering. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setRotation - * @since 3.0.0 - * - * @param {number} [value=0] - The rotation of the Camera, in radians. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setRotation: function (value) - { - if (value === undefined) { value = 0; } - - this.rotation = value; - - return this; - }, - - /** - * Should the Camera round pixel values to whole integers when rendering Game Objects? - * - * In some types of game, especially with pixel art, this is required to prevent sub-pixel aliasing. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setRoundPixels - * @since 3.0.0 - * - * @param {boolean} value - `true` to round Camera pixels, `false` to not. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setRoundPixels: function (value) - { - this.roundPixels = value; - - return this; - }, - - /** - * Sets the Scene the Camera is bound to. - * - * Also populates the `resolution` property and updates the internal size values. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setScene - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene the camera is bound to. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setScene: function (scene) - { - if (this.scene && this._customViewport) - { - this.sceneManager.customViewports--; - } - - this.scene = scene; - - var sys = scene.sys; - - this.sceneManager = sys.game.scene; - this.scaleManager = sys.scale; - this.cameraManager = sys.cameras; - - var res = this.scaleManager.resolution; - - this.resolution = res; - - this._cx = this._x * res; - this._cy = this._y * res; - this._cw = this._width * res; - this._ch = this._height * res; - - this.updateSystem(); - - return this; - }, - - /** - * Set the position of where the Camera is looking within the game. - * You can also modify the properties `Camera.scrollX` and `Camera.scrollY` directly. - * Use this method, or the scroll properties, to move your camera around the game world. - * - * This does not change where the camera viewport is placed. See `setPosition` to control that. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setScroll - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the Camera in the game world. - * @param {number} [y=x] - The y coordinate of the Camera in the game world. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setScroll: function (x, y) - { - if (y === undefined) { y = x; } - - this.scrollX = x; - this.scrollY = y; - - return this; - }, - - /** - * Set the size of the Camera viewport. - * - * By default a Camera is the same size as the game, but can be made smaller via this method, - * allowing you to create mini-cam style effects by creating and positioning a smaller Camera - * viewport within your game. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setSize - * @since 3.0.0 - * - * @param {integer} width - The width of the Camera viewport. - * @param {integer} [height=width] - The height of the Camera viewport. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setSize: function (width, height) - { - if (height === undefined) { height = width; } - - this.width = width; - this.height = height; - - return this; - }, - - /** - * This method sets the position and size of the Camera viewport in a single call. - * - * If you're trying to change where the Camera is looking at in your game, then see - * the method `Camera.setScroll` instead. This method is for changing the viewport - * itself, not what the camera can see. - * - * By default a Camera is the same size as the game, but can be made smaller via this method, - * allowing you to create mini-cam style effects by creating and positioning a smaller Camera - * viewport within your game. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setViewport - * @since 3.0.0 - * - * @param {number} x - The top-left x coordinate of the Camera viewport. - * @param {number} y - The top-left y coordinate of the Camera viewport. - * @param {integer} width - The width of the Camera viewport. - * @param {integer} [height=width] - The height of the Camera viewport. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setViewport: function (x, y, width, height) - { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - - return this; - }, - - /** - * Set the zoom value of the Camera. - * - * Changing to a smaller value, such as 0.5, will cause the camera to 'zoom out'. - * Changing to a larger value, such as 2, will cause the camera to 'zoom in'. - * - * A value of 1 means 'no zoom' and is the default. - * - * Changing the zoom does not impact the Camera viewport in any way, it is only applied during rendering. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setZoom - * @since 3.0.0 - * - * @param {number} [value=1] - The zoom value of the Camera. The minimum it can be is 0.001. - * - * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. - */ - setZoom: function (value) - { - if (value === undefined) { value = 1; } - - if (value === 0) - { - value = 0.001; - } - - this.zoom = value; - - return this; - }, - - /** - * Sets the mask to be applied to this Camera during rendering. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * - * Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Camera it will be immediately replaced. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * - * Note: You cannot mask a Camera that has `renderToTexture` set. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setMask - * @since 3.17.0 - * - * @param {(Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask)} mask - The mask this Camera will use when rendering. - * @param {boolean} [fixedPosition=true] - Should the mask translate along with the Camera, or be fixed in place and not impacted by the Cameras transform? - * - * @return {this} This Camera instance. - */ - setMask: function (mask, fixedPosition) - { - if (fixedPosition === undefined) { fixedPosition = true; } - - this.mask = mask; - - this._maskCamera = (fixedPosition) ? this.cameraManager.default : this; - - return this; - }, - - /** - * Clears the mask that this Camera was using. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#clearMask - * @since 3.17.0 - * - * @param {boolean} [destroyMask=false] - Destroy the mask before clearing it? - * - * @return {this} This Camera instance. - */ - clearMask: function (destroyMask) - { - if (destroyMask === undefined) { destroyMask = false; } - - if (destroyMask && this.mask) - { - this.mask.destroy(); - } - - this.mask = null; - - return this; - }, - - /** - * Sets the visibility of this Camera. - * - * An invisible Camera will skip rendering and input tests of everything it can see. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#setVisible - * @since 3.10.0 - * - * @param {boolean} value - The visible state of the Camera. - * - * @return {this} This Camera instance. - */ - - /** - * Returns an Object suitable for JSON storage containing all of the Camera viewport and rendering properties. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Cameras.Scene2D.JSONCamera} A well-formed object suitable for conversion to JSON. - */ - toJSON: function () - { - var output = { - name: this.name, - x: this.x, - y: this.y, - width: this.width, - height: this.height, - zoom: this.zoom, - rotation: this.rotation, - roundPixels: this.roundPixels, - scrollX: this.scrollX, - scrollY: this.scrollY, - backgroundColor: this.backgroundColor.rgba - }; - - if (this.useBounds) - { - output['bounds'] = { - x: this._bounds.x, - y: this._bounds.y, - width: this._bounds.width, - height: this._bounds.height - }; - } - - return output; - }, - - /** - * Internal method called automatically by the Camera Manager. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#update - * @protected - * @since 3.0.0 - * - * @param {integer} 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. - */ - update: function () - { - // NOOP - }, - - /** - * Internal method called automatically when the viewport changes. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#updateSystem - * @private - * @since 3.12.0 - */ - updateSystem: function () - { - if (!this.scaleManager) - { - return; - } - - var custom = (this._x !== 0 || this._y !== 0 || this.scaleManager.width !== this._width || this.scaleManager.height !== this._height); - - var sceneManager = this.sceneManager; - - if (custom && !this._customViewport) - { - // We need a custom viewport for this Camera - sceneManager.customViewports++; - } - else if (!custom && this._customViewport) - { - // We're turning off a custom viewport for this Camera - sceneManager.customViewports--; - } - - this.dirty = true; - this._customViewport = custom; - }, - - /** - * Destroys this Camera instance and its internal properties and references. - * Once destroyed you cannot use this Camera again, even if re-added to a Camera Manager. - * - * This method is called automatically by `CameraManager.remove` if that methods `runDestroy` argument is `true`, which is the default. - * - * Unless you have a specific reason otherwise, always use `CameraManager.remove` and allow it to handle the camera destruction, - * rather than calling this method directly. - * - * @method Phaser.Cameras.Scene2D.BaseCamera#destroy - * @fires Phaser.Cameras.Scene2D.Events#DESTROY - * @since 3.0.0 - */ - destroy: function () - { - this.emit(Events.DESTROY, this); - - this.removeAllListeners(); - - this.matrix.destroy(); - - this.culledObjects = []; - - if (this._customViewport) - { - // We're turning off a custom viewport for this Camera - this.sceneManager.customViewports--; - } - - this._bounds = null; - - this.scene = null; - this.scaleManager = null; - this.sceneManager = null; - this.cameraManager = null; - }, - - /** - * The x position of the Camera viewport, relative to the top-left of the game canvas. - * The viewport is the area into which the camera renders. - * To adjust the position the camera is looking at in the game world, see the `scrollX` value. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#x - * @type {number} - * @since 3.0.0 - */ - x: { - - get: function () - { - return this._x; - }, - - set: function (value) - { - this._x = value; - this._cx = value * this.resolution; - this.updateSystem(); - } - - }, - - /** - * The y position of the Camera viewport, relative to the top-left of the game canvas. - * The viewport is the area into which the camera renders. - * To adjust the position the camera is looking at in the game world, see the `scrollY` value. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#y - * @type {number} - * @since 3.0.0 - */ - y: { - - get: function () - { - return this._y; - }, - - set: function (value) - { - this._y = value; - this._cy = value * this.resolution; - this.updateSystem(); - } - - }, - - /** - * The width of the Camera viewport, in pixels. - * - * The viewport is the area into which the Camera renders. Setting the viewport does - * not restrict where the Camera can scroll to. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#width - * @type {number} - * @since 3.0.0 - */ - width: { - - get: function () - { - return this._width; - }, - - set: function (value) - { - this._width = value; - this._cw = value * this.resolution; - this.updateSystem(); - } - - }, - - /** - * The height of the Camera viewport, in pixels. - * - * The viewport is the area into which the Camera renders. Setting the viewport does - * not restrict where the Camera can scroll to. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#height - * @type {number} - * @since 3.0.0 - */ - height: { - - get: function () - { - return this._height; - }, - - set: function (value) - { - this._height = value; - this._ch = value * this.resolution; - this.updateSystem(); - } - - }, - - /** - * The horizontal scroll position of this Camera. - * - * Change this value to cause the Camera to scroll around your Scene. - * - * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, - * will automatically adjust the Camera scroll values accordingly. - * - * You can set the bounds within which the Camera can scroll via the `setBounds` method. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#scrollX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - scrollX: { - - get: function () - { - return this._scrollX; - }, - - set: function (value) - { - this._scrollX = value; - this.dirty = true; - } - - }, - - /** - * The vertical scroll position of this Camera. - * - * Change this value to cause the Camera to scroll around your Scene. - * - * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, - * will automatically adjust the Camera scroll values accordingly. - * - * You can set the bounds within which the Camera can scroll via the `setBounds` method. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#scrollY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - scrollY: { - - get: function () - { - return this._scrollY; - }, - - set: function (value) - { - this._scrollY = value; - this.dirty = true; - } - - }, - - /** - * The Camera zoom value. Change this value to zoom in, or out of, a Scene. - * - * A value of 0.5 would zoom the Camera out, so you can now see twice as much - * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel - * now takes up 2 pixels when rendered. - * - * Set to 1 to return to the default zoom level. - * - * Be careful to never set this value to zero. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#zoom - * @type {number} - * @default 1 - * @since 3.0.0 - */ - zoom: { - - get: function () - { - return this._zoom; - }, - - set: function (value) - { - this._zoom = value; - this.dirty = true; - } - - }, - - /** - * 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 - */ - rotation: { - - get: function () - { - return this._rotation; - }, - - set: function (value) - { - this._rotation = value; - this.dirty = true; - } - - }, - - /** - * The horizontal position of the center of the Camera's viewport, relative to the left of the game canvas. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#centerX - * @type {number} - * @readonly - * @since 3.10.0 - */ - centerX: { - - get: function () - { - return this.x + (0.5 * this.width); - } - - }, - - /** - * The vertical position of the center of the Camera's viewport, relative to the top of the game canvas. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#centerY - * @type {number} - * @readonly - * @since 3.10.0 - */ - centerY: { - - get: function () - { - return this.y + (0.5 * this.height); - } - - }, - - /** - * The displayed width of the camera viewport, factoring in the camera zoom level. - * - * If a camera has a viewport width of 800 and a zoom of 0.5 then its display width - * would be 1600, as it's displaying twice as many pixels as zoom level 1. - * - * Equally, a camera with a width of 800 and zoom of 2 would have a display width - * of 400 pixels. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#displayWidth - * @type {number} - * @readonly - * @since 3.11.0 - */ - displayWidth: { - - get: function () - { - return this.width / this.zoom; - } - - }, - - /** - * The displayed height of the camera viewport, factoring in the camera zoom level. - * - * If a camera has a viewport height of 600 and a zoom of 0.5 then its display height - * would be 1200, as it's displaying twice as many pixels as zoom level 1. - * - * Equally, a camera with a height of 600 and zoom of 2 would have a display height - * of 300 pixels. - * - * @name Phaser.Cameras.Scene2D.BaseCamera#displayHeight - * @type {number} - * @readonly - * @since 3.11.0 - */ - displayHeight: { - - get: function () - { - return this.height / this.zoom; - } - - } - -}); - -module.exports = BaseCamera; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../../gameobjects/components'); +var DegToRad = require('../../math/DegToRad'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); +var ValueToColor = require('../../display/color/ValueToColor'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Base Camera class. + * + * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, + * and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. + * + * The Base Camera is extended by the Camera class, which adds in special effects including Fade, + * Flash and Camera Shake, as well as the ability to follow Game Objects. + * + * The Base Camera was introduced in Phaser 3.12. It was split off from the Camera class, to allow + * you to isolate special effects as needed. Therefore the 'since' values for properties of this class relate + * to when they were added to the Camera class. + * + * @class BaseCamera + * @memberof Phaser.Cameras.Scene2D + * @constructor + * @since 3.12.0 + * + * @extends Phaser.Events.EventEmitter + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.Visible + * + * @param {number} x - The x position of the Camera, relative to the top-left of the game canvas. + * @param {number} y - The y position of the Camera, relative to the top-left of the game canvas. + * @param {number} width - The width of the Camera, in pixels. + * @param {number} height - The height of the Camera, in pixels. + */ +var BaseCamera = new Class({ + + Extends: EventEmitter, + + Mixins: [ + Components.Alpha, + Components.Visible + ], + + initialize: + + function BaseCamera (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + + EventEmitter.call(this); + + /** + * A reference to the Scene this camera belongs to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene; + + /** + * A reference to the Game Scene Manager. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#sceneManager + * @type {Phaser.Scenes.SceneManager} + * @since 3.12.0 + */ + this.sceneManager; + + /** + * A reference to the Game Scale Manager. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scaleManager + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.0 + */ + this.scaleManager; + + /** + * A reference to the Scene's Camera Manager to which this Camera belongs. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#cameraManager + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.17.0 + */ + this.cameraManager; + + /** + * The Camera ID. Assigned by the Camera Manager and used to handle camera exclusion. + * This value is a bitmask. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#id + * @type {integer} + * @readonly + * @since 3.11.0 + */ + this.id = 0; + + /** + * The name of the Camera. This is left empty for your own use. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * This property is un-used in v3.16. + * + * The resolution of the Game, used in most Camera calculations. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#resolution + * @type {number} + * @readonly + * @deprecated + * @since 3.12.0 + */ + this.resolution = 1; + + /** + * Should this camera round its pixel values to integers? + * + * @name Phaser.Cameras.Scene2D.BaseCamera#roundPixels + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.roundPixels = false; + + /** + * Is this Camera visible or not? + * + * A visible camera will render and perform input tests. + * An invisible camera will not render anything and will skip input tests. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#visible + * @type {boolean} + * @default true + * @since 3.10.0 + */ + + /** + * Is this Camera using a bounds to restrict scrolling movement? + * + * Set this property along with the bounds via `Camera.setBounds`. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#useBounds + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.useBounds = false; + + /** + * The World View is a Rectangle that defines the area of the 'world' the Camera is currently looking at. + * This factors in the Camera viewport size, zoom and scroll position and is updated in the Camera preRender step. + * If you have enabled Camera bounds the worldview will be clamped to those bounds accordingly. + * You can use it for culling or intersection checks. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#worldView + * @type {Phaser.Geom.Rectangle} + * @readonly + * @since 3.11.0 + */ + this.worldView = new Rectangle(); + + /** + * Is this Camera dirty? + * + * A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. + * + * This flag is cleared during the `postRenderCamera` method of the renderer. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#dirty + * @type {boolean} + * @default true + * @since 3.11.0 + */ + this.dirty = true; + + /** + * The x position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollX` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#x + * @type {number} + * @private + * @since 3.0.0 + */ + this._x = x; + + /** + * The y position of the Camera, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollY` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#y + * @type {number} + * @private + * @since 3.0.0 + */ + this._y = y; + + /** + * Internal Camera X value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_cx + * @type {number} + * @private + * @since 3.12.0 + */ + this._cx = 0; + + /** + * Internal Camera Y value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_cy + * @type {number} + * @private + * @since 3.12.0 + */ + this._cy = 0; + + /** + * Internal Camera Width value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_cw + * @type {number} + * @private + * @since 3.12.0 + */ + this._cw = 0; + + /** + * Internal Camera Height value multiplied by the resolution. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_ch + * @type {number} + * @private + * @since 3.12.0 + */ + this._ch = 0; + + /** + * The width of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_width + * @type {number} + * @private + * @since 3.11.0 + */ + this._width = width; + + /** + * The height of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_height + * @type {number} + * @private + * @since 3.11.0 + */ + this._height = height; + + /** + * The bounds the camera is restrained to during scrolling. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_bounds + * @type {Phaser.Geom.Rectangle} + * @private + * @since 3.0.0 + */ + this._bounds = new Rectangle(); + + /** + * The horizontal scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_scrollX + * @type {number} + * @private + * @default 0 + * @since 3.11.0 + */ + this._scrollX = 0; + + /** + * The vertical scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_scrollY + * @type {number} + * @private + * @default 0 + * @since 3.11.0 + */ + this._scrollY = 0; + + /** + * The Camera zoom value. Change this value to zoom in, or out of, a Scene. + * + * A value of 0.5 would zoom the Camera out, so you can now see twice as much + * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel + * now takes up 2 pixels when rendered. + * + * Set to 1 to return to the default zoom level. + * + * Be careful to never set this value to zero. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_zoom + * @type {number} + * @private + * @default 1 + * @since 3.11.0 + */ + this._zoom = 1; + + /** + * 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 + */ + this._rotation = 0; + + /** + * A local transform matrix used for internal calculations. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#matrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.0.0 + */ + this.matrix = new TransformMatrix(); + + /** + * Does this Camera have a transparent background? + * + * @name Phaser.Cameras.Scene2D.BaseCamera#transparent + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.transparent = true; + + /** + * The background color of this Camera. Only used if `transparent` is `false`. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#backgroundColor + * @type {Phaser.Display.Color} + * @since 3.0.0 + */ + this.backgroundColor = ValueToColor('rgba(0,0,0,0)'); + + /** + * The Camera alpha value. Setting this property impacts every single object that this Camera + * renders. You can either set the property directly, i.e. via a Tween, to fade a Camera in or out, + * or via the chainable `setAlpha` method instead. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#alpha + * @type {number} + * @default 1 + * @since 3.11.0 + */ + + /** + * Should the camera cull Game Objects before checking them for input hit tests? + * In some special cases it may be beneficial to disable this. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#disableCull + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.disableCull = false; + + /** + * A temporary array of culled objects. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#culledObjects + * @type {Phaser.GameObjects.GameObject[]} + * @default [] + * @private + * @since 3.0.0 + */ + this.culledObjects = []; + + /** + * The mid-point of the Camera in 'world' coordinates. + * + * Use it to obtain exactly where in the world the center of the camera is currently looking. + * + * This value is updated in the preRender method, after the scroll values and follower + * have been processed. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#midPoint + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.11.0 + */ + this.midPoint = new Vector2(width / 2, height / 2); + + /** + * The horizontal origin of rotation for this Camera. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * See `setOrigin` to set both origins in a single, chainable call. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#originX + * @type {number} + * @default 0.5 + * @since 3.11.0 + */ + this.originX = 0.5; + + /** + * The vertical origin of rotation for this Camera. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * See `setOrigin` to set both origins in a single, chainable call. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#originY + * @type {number} + * @default 0.5 + * @since 3.11.0 + */ + this.originY = 0.5; + + /** + * Does this Camera have a custom viewport? + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_customViewport + * @type {boolean} + * @private + * @default false + * @since 3.12.0 + */ + this._customViewport = false; + + /** + * The Mask this Camera is using during render. + * Set the mask using the `setMask` method. Remove the mask using the `clearMask` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#mask + * @type {?(Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask)} + * @since 3.17.0 + */ + this.mask = null; + + /** + * The Camera that this Camera uses for translation during masking. + * + * If the mask is fixed in position this will be a reference to + * the CameraManager.default instance. Otherwise, it'll be a reference + * to itself. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#_maskCamera + * @type {?Phaser.Cameras.Scene2D.BaseCamera} + * @private + * @since 3.17.0 + */ + this._maskCamera = null; + }, + + /** + * Set the Alpha level of this Camera. The alpha controls the opacity of the Camera as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setAlpha + * @since 3.11.0 + * + * @param {number} [value=1] - The Camera alpha value. + * + * @return {this} This Camera instance. + */ + + /** + * Sets the rotation origin of this Camera. + * + * The values are given in the range 0 to 1 and are only used when calculating Camera rotation. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setOrigin + * @since 3.11.0 + * + * @param {number} [x=0.5] - The horizontal origin value. + * @param {number} [y=x] - The vertical origin value. If not defined it will be set to the value of `x`. + * + * @return {this} This Camera instance. + */ + setOrigin: function (x, y) + { + if (x === undefined) { x = 0.5; } + if (y === undefined) { y = x; } + + this.originX = x; + this.originY = y; + + return this; + }, + + /** + * 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. + */ + getScroll: function (x, y, out) + { + if (out === undefined) { out = new Vector2(); } + + var originX = this.width * 0.5; + var originY = this.height * 0.5; + + out.x = x - originX; + out.y = y - originY; + + if (this.useBounds) + { + out.x = this.clampX(out.x); + out.y = this.clampY(out.y); + } + + return out; + }, + + /** + * Moves the Camera horizontally so that it is centered on the given x coordinate, bounds allowing. + * Calling this does not change the scrollY value. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerOnX + * @since 3.16.0 + * + * @param {number} x - The horizontal coordinate to center on. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerOnX: function (x) + { + var originX = this.width * 0.5; + + this.midPoint.x = x; + + this.scrollX = x - originX; + + if (this.useBounds) + { + this.scrollX = this.clampX(this.scrollX); + } + + return this; + }, + + /** + * Moves the Camera vertically so that it is centered on the given y coordinate, bounds allowing. + * Calling this does not change the scrollX value. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerOnY + * @since 3.16.0 + * + * @param {number} y - The vertical coordinate to center on. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerOnY: function (y) + { + var originY = this.height * 0.5; + + this.midPoint.y = y; + + this.scrollY = y - originY; + + if (this.useBounds) + { + this.scrollY = this.clampY(this.scrollY); + } + + return this; + }, + + /** + * Moves the Camera so that it is centered on the given coordinates, bounds allowing. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerOn + * @since 3.11.0 + * + * @param {number} x - The horizontal coordinate to center on. + * @param {number} y - The vertical coordinate to center on. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerOn: function (x, y) + { + this.centerOnX(x); + this.centerOnY(y); + + return this; + }, + + /** + * Moves the Camera so that it is looking at the center of the Camera Bounds, if enabled. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#centerToBounds + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerToBounds: function () + { + if (this.useBounds) + { + var bounds = this._bounds; + var originX = this.width * 0.5; + var originY = this.height * 0.5; + + this.midPoint.set(bounds.centerX, bounds.centerY); + + this.scrollX = bounds.centerX - originX; + this.scrollY = bounds.centerY - originY; + } + + return this; + }, + + /** + * 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 {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + centerToSize: function () + { + this.scrollX = this.width * 0.5; + this.scrollY = this.height * 0.5; + + return this; + }, + + /** + * Takes an array of Game Objects and returns a new array featuring only those objects + * visible by this camera. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#cull + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject[]} G - [renderableObjects,$return] + * + * @param {Phaser.GameObjects.GameObject[]} renderableObjects - An array of Game Objects to cull. + * + * @return {Phaser.GameObjects.GameObject[]} An array of Game Objects visible to this Camera. + */ + cull: function (renderableObjects) + { + if (this.disableCull) + { + return renderableObjects; + } + + var cameraMatrix = this.matrix.matrix; + + var mva = cameraMatrix[0]; + var mvb = cameraMatrix[1]; + var mvc = cameraMatrix[2]; + var mvd = cameraMatrix[3]; + + /* First Invert Matrix */ + var determinant = (mva * mvd) - (mvb * mvc); + + if (!determinant) + { + return renderableObjects; + } + + var mve = cameraMatrix[4]; + var mvf = cameraMatrix[5]; + + var scrollX = this.scrollX; + var scrollY = this.scrollY; + var cameraW = this.width; + var cameraH = this.height; + var culledObjects = this.culledObjects; + var length = renderableObjects.length; + + determinant = 1 / determinant; + + culledObjects.length = 0; + + for (var index = 0; index < length; ++index) + { + var object = renderableObjects[index]; + + if (!object.hasOwnProperty('width') || object.parentContainer) + { + culledObjects.push(object); + continue; + } + + var objectW = object.width; + var objectH = object.height; + var objectX = (object.x - (scrollX * object.scrollFactorX)) - (objectW * object.originX); + var objectY = (object.y - (scrollY * object.scrollFactorY)) - (objectH * object.originY); + var tx = (objectX * mva + objectY * mvc + mve); + var ty = (objectX * mvb + objectY * mvd + mvf); + var tw = ((objectX + objectW) * mva + (objectY + objectH) * mvc + mve); + var th = ((objectX + objectW) * mvb + (objectY + objectH) * mvd + mvf); + var cullTop = this.y; + var cullBottom = cullTop + cameraH; + var cullLeft = this.x; + var cullRight = cullLeft + cameraW; + + if ((tw > cullLeft && tx < cullRight) && (th > cullTop && ty < cullBottom)) + { + culledObjects.push(object); + } + } + + return culledObjects; + }, + + /** + * 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. + */ + getWorldPoint: function (x, y, output) + { + if (output === undefined) { output = new Vector2(); } + + var cameraMatrix = this.matrix.matrix; + + var mva = cameraMatrix[0]; + var mvb = cameraMatrix[1]; + var mvc = cameraMatrix[2]; + var mvd = cameraMatrix[3]; + var mve = cameraMatrix[4]; + var mvf = cameraMatrix[5]; + + // Invert Matrix + var determinant = (mva * mvd) - (mvb * mvc); + + if (!determinant) + { + output.x = x; + output.y = y; + + return output; + } + + determinant = 1 / determinant; + + var ima = mvd * determinant; + var imb = -mvb * determinant; + var imc = -mvc * determinant; + var imd = mva * determinant; + var ime = (mvc * mvf - mvd * mve) * determinant; + var imf = (mvb * mve - mva * mvf) * determinant; + + var c = Math.cos(this.rotation); + var s = Math.sin(this.rotation); + + var zoom = this.zoom; + var res = this.resolution; + + var scrollX = this.scrollX; + var scrollY = this.scrollY; + + // Works for zoom of 1 with any resolution, but resolution > 1 and zoom !== 1 breaks + var sx = x + ((scrollX * c - scrollY * s) * zoom); + var sy = y + ((scrollX * s + scrollY * c) * zoom); + + // Apply transform to point + output.x = (sx * ima + sy * imc) * res + ime; + output.y = (sx * imb + sy * imd) * res + imf; + + return output; + }, + + /** + * Given a Game Object, or an array of Game Objects, it will update all of their camera filter settings + * so that they are ignored by this Camera. This means they will not be rendered by this Camera. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#ignore + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group)} entries - The Game Object, or array of Game Objects, to be ignored by this Camera. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + ignore: function (entries) + { + var id = this.id; + + if (!Array.isArray(entries)) + { + entries = [ entries ]; + } + + for (var i = 0; i < entries.length; i++) + { + var entry = entries[i]; + + if (Array.isArray(entry)) + { + this.ignore(entry); + } + else if (entry.isParent) + { + this.ignore(entry.getChildren()); + } + else + { + entry.cameraFilter |= id; + } + } + + return this; + }, + + /** + * Internal preRender step. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#preRender + * @protected + * @since 3.0.0 + * + * @param {number} resolution - The game resolution, as set in the Scale Manager. + */ + preRender: function (resolution) + { + var width = this.width; + var height = this.height; + + var halfWidth = width * 0.5; + var halfHeight = height * 0.5; + + var zoom = this.zoom * resolution; + var matrix = this.matrix; + + var originX = width * this.originX; + var originY = height * this.originY; + + var sx = this.scrollX; + var sy = this.scrollY; + + if (this.useBounds) + { + sx = this.clampX(sx); + sy = this.clampY(sy); + } + + if (this.roundPixels) + { + originX = Math.round(originX); + originY = Math.round(originY); + } + + // Values are in pixels and not impacted by zooming the Camera + this.scrollX = sx; + this.scrollY = sy; + + var midX = sx + halfWidth; + var midY = sy + halfHeight; + + // 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 + this.midPoint.set(midX, midY); + + var displayWidth = width / zoom; + var displayHeight = height / zoom; + + this.worldView.setTo( + midX - (displayWidth / 2), + midY - (displayHeight / 2), + displayWidth, + displayHeight + ); + + matrix.applyITRS(this.x + originX, this.y + originY, this.rotation, zoom, zoom); + matrix.translate(-originX, -originY); + }, + + /** + * Takes an x value and checks it's within the range of the Camera bounds, adjusting if required. + * Do not call this method if you are not using camera bounds. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#clampX + * @since 3.11.0 + * + * @param {number} x - The value to horizontally scroll clamp. + * + * @return {number} The adjusted value to use as scrollX. + */ + clampX: function (x) + { + var bounds = this._bounds; + + var dw = this.displayWidth; + + var bx = bounds.x + ((dw - this.width) / 2); + var bw = Math.max(bx, bx + bounds.width - dw); + + if (x < bx) + { + x = bx; + } + else if (x > bw) + { + x = bw; + } + + return x; + }, + + /** + * Takes a y value and checks it's within the range of the Camera bounds, adjusting if required. + * Do not call this method if you are not using camera bounds. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#clampY + * @since 3.11.0 + * + * @param {number} y - The value to vertically scroll clamp. + * + * @return {number} The adjusted value to use as scrollY. + */ + clampY: function (y) + { + var bounds = this._bounds; + + var dh = this.displayHeight; + + var by = bounds.y + ((dh - this.height) / 2); + var bh = Math.max(by, by + bounds.height - dh); + + if (y < by) + { + y = by; + } + else if (y > bh) + { + y = bh; + } + + return y; + }, + + /* + var gap = this._zoomInversed; + return gap * Math.round((src.x - this.scrollX * src.scrollFactorX) / gap); + */ + + /** + * If this Camera has previously had movement bounds set on it, this will remove them. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#removeBounds + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + removeBounds: function () + { + this.useBounds = false; + + this.dirty = true; + + this._bounds.setEmpty(); + + return this; + }, + + /** + * Set the rotation of this Camera. This causes everything it renders to appear rotated. + * + * Rotating a camera does not rotate the viewport itself, it is applied during rendering. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setAngle + * @since 3.0.0 + * + * @param {number} [value=0] - The cameras angle of rotation, given in degrees. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setAngle: function (value) + { + if (value === undefined) { value = 0; } + + this.rotation = DegToRad(value); + + return this; + }, + + /** + * Sets the background color for this Camera. + * + * By default a Camera has a transparent background but it can be given a solid color, with any level + * of transparency, via this method. + * + * The color value can be specified using CSS color notation, hex or numbers. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setBackgroundColor + * @since 3.0.0 + * + * @param {(string|number|Phaser.Types.Display.InputColorObject)} [color='rgba(0,0,0,0)'] - The color value. In CSS, hex or numeric color notation. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setBackgroundColor: function (color) + { + if (color === undefined) { color = 'rgba(0,0,0,0)'; } + + this.backgroundColor = ValueToColor(color); + + this.transparent = (this.backgroundColor.alpha === 0); + + return this; + }, + + /** + * Set the bounds of the Camera. The bounds are an axis-aligned rectangle. + * + * The Camera bounds controls where the Camera can scroll to, stopping it from scrolling off the + * edges and into blank space. It does not limit the placement of Game Objects, or where + * the Camera viewport can be positioned. + * + * Temporarily disable the bounds by changing the boolean `Camera.useBounds`. + * + * Clear the bounds entirely by calling `Camera.removeBounds`. + * + * If you set bounds that are smaller than the viewport it will stop the Camera from being + * able to scroll. The bounds can be positioned where-ever you wish. By default they are from + * 0x0 to the canvas width x height. This means that the coordinate 0x0 is the top left of + * the Camera bounds. However, you can position them anywhere. So if you wanted a game world + * that was 2048x2048 in size, with 0x0 being the center of it, you can set the bounds x/y + * to be -1024, -1024, with a width and height of 2048. Depending on your game you may find + * it easier for 0x0 to be the top-left of the bounds, or you may wish 0x0 to be the middle. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setBounds + * @since 3.0.0 + * + * @param {integer} x - The top-left x coordinate of the bounds. + * @param {integer} y - The top-left y coordinate of the bounds. + * @param {integer} width - The width of the bounds, in pixels. + * @param {integer} height - The height of the bounds, in pixels. + * @param {boolean} [centerOn=false] - If `true` the Camera will automatically be centered on the new bounds. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setBounds: function (x, y, width, height, centerOn) + { + if (centerOn === undefined) { centerOn = false; } + + this._bounds.setTo(x, y, width, height); + + this.dirty = true; + this.useBounds = true; + + if (centerOn) + { + this.centerToBounds(); + } + else + { + this.scrollX = this.clampX(this.scrollX); + this.scrollY = this.clampY(this.scrollY); + } + + return this; + }, + + /** + * Returns a rectangle containing the bounds of the Camera. + * + * If the Camera does not have any bounds the rectangle will be empty. + * + * The rectangle is a copy of the bounds, so is safe to modify. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#getBounds + * @since 3.16.0 + * + * @param {Phaser.Geom.Rectangle} [out] - An optional Rectangle to store the bounds in. If not given, a new Rectangle will be created. + * + * @return {Phaser.Geom.Rectangle} A rectangle containing the bounds of this Camera. + */ + getBounds: function (out) + { + if (out === undefined) { out = new Rectangle(); } + + var source = this._bounds; + + out.setTo(source.x, source.y, source.width, source.height); + + return out; + }, + + /** + * Sets the name of this Camera. + * This value is for your own use and isn't used internally. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setName + * @since 3.0.0 + * + * @param {string} [value=''] - The name of the Camera. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setName: function (value) + { + if (value === undefined) { value = ''; } + + this.name = value; + + return this; + }, + + /** + * Set the position of the Camera viewport within the game. + * + * This does not change where the camera is 'looking'. See `setScroll` to control that. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setPosition + * @since 3.0.0 + * + * @param {number} x - The top-left x coordinate of the Camera viewport. + * @param {number} [y=x] - The top-left y coordinate of the Camera viewport. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Set the rotation of this Camera. This causes everything it renders to appear rotated. + * + * Rotating a camera does not rotate the viewport itself, it is applied during rendering. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setRotation + * @since 3.0.0 + * + * @param {number} [value=0] - The rotation of the Camera, in radians. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setRotation: function (value) + { + if (value === undefined) { value = 0; } + + this.rotation = value; + + return this; + }, + + /** + * Should the Camera round pixel values to whole integers when rendering Game Objects? + * + * In some types of game, especially with pixel art, this is required to prevent sub-pixel aliasing. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setRoundPixels + * @since 3.0.0 + * + * @param {boolean} value - `true` to round Camera pixels, `false` to not. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setRoundPixels: function (value) + { + this.roundPixels = value; + + return this; + }, + + /** + * Sets the Scene the Camera is bound to. + * + * Also populates the `resolution` property and updates the internal size values. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setScene + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene the camera is bound to. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setScene: function (scene) + { + if (this.scene && this._customViewport) + { + this.sceneManager.customViewports--; + } + + this.scene = scene; + + var sys = scene.sys; + + this.sceneManager = sys.game.scene; + this.scaleManager = sys.scale; + this.cameraManager = sys.cameras; + + var res = this.scaleManager.resolution; + + this.resolution = res; + + this._cx = this._x * res; + this._cy = this._y * res; + this._cw = this._width * res; + this._ch = this._height * res; + + this.updateSystem(); + + return this; + }, + + /** + * Set the position of where the Camera is looking within the game. + * You can also modify the properties `Camera.scrollX` and `Camera.scrollY` directly. + * Use this method, or the scroll properties, to move your camera around the game world. + * + * This does not change where the camera viewport is placed. See `setPosition` to control that. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setScroll + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the Camera in the game world. + * @param {number} [y=x] - The y coordinate of the Camera in the game world. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setScroll: function (x, y) + { + if (y === undefined) { y = x; } + + this.scrollX = x; + this.scrollY = y; + + return this; + }, + + /** + * Set the size of the Camera viewport. + * + * By default a Camera is the same size as the game, but can be made smaller via this method, + * allowing you to create mini-cam style effects by creating and positioning a smaller Camera + * viewport within your game. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setSize + * @since 3.0.0 + * + * @param {integer} width - The width of the Camera viewport. + * @param {integer} [height=width] - The height of the Camera viewport. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + this.width = width; + this.height = height; + + return this; + }, + + /** + * This method sets the position and size of the Camera viewport in a single call. + * + * If you're trying to change where the Camera is looking at in your game, then see + * the method `Camera.setScroll` instead. This method is for changing the viewport + * itself, not what the camera can see. + * + * By default a Camera is the same size as the game, but can be made smaller via this method, + * allowing you to create mini-cam style effects by creating and positioning a smaller Camera + * viewport within your game. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setViewport + * @since 3.0.0 + * + * @param {number} x - The top-left x coordinate of the Camera viewport. + * @param {number} y - The top-left y coordinate of the Camera viewport. + * @param {integer} width - The width of the Camera viewport. + * @param {integer} [height=width] - The height of the Camera viewport. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setViewport: function (x, y, width, height) + { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + }, + + /** + * Set the zoom value of the Camera. + * + * Changing to a smaller value, such as 0.5, will cause the camera to 'zoom out'. + * Changing to a larger value, such as 2, will cause the camera to 'zoom in'. + * + * A value of 1 means 'no zoom' and is the default. + * + * Changing the zoom does not impact the Camera viewport in any way, it is only applied during rendering. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setZoom + * @since 3.0.0 + * + * @param {number} [value=1] - The zoom value of the Camera. The minimum it can be is 0.001. + * + * @return {Phaser.Cameras.Scene2D.BaseCamera} This Camera instance. + */ + setZoom: function (value) + { + if (value === undefined) { value = 1; } + + if (value === 0) + { + value = 0.001; + } + + this.zoom = value; + + return this; + }, + + /** + * Sets the mask to be applied to this Camera during rendering. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * + * Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Camera it will be immediately replaced. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * + * Note: You cannot mask a Camera that has `renderToTexture` set. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setMask + * @since 3.17.0 + * + * @param {(Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask)} mask - The mask this Camera will use when rendering. + * @param {boolean} [fixedPosition=true] - Should the mask translate along with the Camera, or be fixed in place and not impacted by the Cameras transform? + * + * @return {this} This Camera instance. + */ + setMask: function (mask, fixedPosition) + { + if (fixedPosition === undefined) { fixedPosition = true; } + + this.mask = mask; + + this._maskCamera = (fixedPosition) ? this.cameraManager.default : this; + + return this; + }, + + /** + * Clears the mask that this Camera was using. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#clearMask + * @since 3.17.0 + * + * @param {boolean} [destroyMask=false] - Destroy the mask before clearing it? + * + * @return {this} This Camera instance. + */ + clearMask: function (destroyMask) + { + if (destroyMask === undefined) { destroyMask = false; } + + if (destroyMask && this.mask) + { + this.mask.destroy(); + } + + this.mask = null; + + return this; + }, + + /** + * Sets the visibility of this Camera. + * + * An invisible Camera will skip rendering and input tests of everything it can see. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#setVisible + * @since 3.10.0 + * + * @param {boolean} value - The visible state of the Camera. + * + * @return {this} This Camera instance. + */ + + /** + * Returns an Object suitable for JSON storage containing all of the Camera viewport and rendering properties. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Cameras.Scene2D.JSONCamera} A well-formed object suitable for conversion to JSON. + */ + toJSON: function () + { + var output = { + name: this.name, + x: this.x, + y: this.y, + width: this.width, + height: this.height, + zoom: this.zoom, + rotation: this.rotation, + roundPixels: this.roundPixels, + scrollX: this.scrollX, + scrollY: this.scrollY, + backgroundColor: this.backgroundColor.rgba + }; + + if (this.useBounds) + { + output['bounds'] = { + x: this._bounds.x, + y: this._bounds.y, + width: this._bounds.width, + height: this._bounds.height + }; + } + + return output; + }, + + /** + * Internal method called automatically by the Camera Manager. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#update + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + update: function () + { + // NOOP + }, + + /** + * Internal method called automatically when the viewport changes. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#updateSystem + * @private + * @since 3.12.0 + */ + updateSystem: function () + { + if (!this.scaleManager) + { + return; + } + + var custom = (this._x !== 0 || this._y !== 0 || this.scaleManager.width !== this._width || this.scaleManager.height !== this._height); + + var sceneManager = this.sceneManager; + + if (custom && !this._customViewport) + { + // We need a custom viewport for this Camera + sceneManager.customViewports++; + } + else if (!custom && this._customViewport) + { + // We're turning off a custom viewport for this Camera + sceneManager.customViewports--; + } + + this.dirty = true; + this._customViewport = custom; + }, + + /** + * Destroys this Camera instance and its internal properties and references. + * Once destroyed you cannot use this Camera again, even if re-added to a Camera Manager. + * + * This method is called automatically by `CameraManager.remove` if that methods `runDestroy` argument is `true`, which is the default. + * + * Unless you have a specific reason otherwise, always use `CameraManager.remove` and allow it to handle the camera destruction, + * rather than calling this method directly. + * + * @method Phaser.Cameras.Scene2D.BaseCamera#destroy + * @fires Phaser.Cameras.Scene2D.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + this.emit(Events.DESTROY, this); + + this.removeAllListeners(); + + this.matrix.destroy(); + + this.culledObjects = []; + + if (this._customViewport) + { + // We're turning off a custom viewport for this Camera + this.sceneManager.customViewports--; + } + + this._bounds = null; + + this.scene = null; + this.scaleManager = null; + this.sceneManager = null; + this.cameraManager = null; + }, + + /** + * The x position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollX` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this._x; + }, + + set: function (value) + { + this._x = value; + this._cx = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The y position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollY` value. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this._y; + }, + + set: function (value) + { + this._y = value; + this._cy = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The width of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#width + * @type {number} + * @since 3.0.0 + */ + width: { + + get: function () + { + return this._width; + }, + + set: function (value) + { + this._width = value; + this._cw = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The height of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#height + * @type {number} + * @since 3.0.0 + */ + height: { + + get: function () + { + return this._height; + }, + + set: function (value) + { + this._height = value; + this._ch = value * this.resolution; + this.updateSystem(); + } + + }, + + /** + * The horizontal scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scrollX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + scrollX: { + + get: function () + { + return this._scrollX; + }, + + set: function (value) + { + this._scrollX = value; + this.dirty = true; + } + + }, + + /** + * The vertical scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#scrollY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + scrollY: { + + get: function () + { + return this._scrollY; + }, + + set: function (value) + { + this._scrollY = value; + this.dirty = true; + } + + }, + + /** + * The Camera zoom value. Change this value to zoom in, or out of, a Scene. + * + * A value of 0.5 would zoom the Camera out, so you can now see twice as much + * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel + * now takes up 2 pixels when rendered. + * + * Set to 1 to return to the default zoom level. + * + * Be careful to never set this value to zero. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#zoom + * @type {number} + * @default 1 + * @since 3.0.0 + */ + zoom: { + + get: function () + { + return this._zoom; + }, + + set: function (value) + { + this._zoom = value; + this.dirty = true; + } + + }, + + /** + * 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 + */ + rotation: { + + get: function () + { + return this._rotation; + }, + + set: function (value) + { + this._rotation = value; + this.dirty = true; + } + + }, + + /** + * The horizontal position of the center of the Camera's viewport, relative to the left of the game canvas. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#centerX + * @type {number} + * @readonly + * @since 3.10.0 + */ + centerX: { + + get: function () + { + return this.x + (0.5 * this.width); + } + + }, + + /** + * The vertical position of the center of the Camera's viewport, relative to the top of the game canvas. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#centerY + * @type {number} + * @readonly + * @since 3.10.0 + */ + centerY: { + + get: function () + { + return this.y + (0.5 * this.height); + } + + }, + + /** + * The displayed width of the camera viewport, factoring in the camera zoom level. + * + * If a camera has a viewport width of 800 and a zoom of 0.5 then its display width + * would be 1600, as it's displaying twice as many pixels as zoom level 1. + * + * Equally, a camera with a width of 800 and zoom of 2 would have a display width + * of 400 pixels. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#displayWidth + * @type {number} + * @readonly + * @since 3.11.0 + */ + displayWidth: { + + get: function () + { + return this.width / this.zoom; + } + + }, + + /** + * The displayed height of the camera viewport, factoring in the camera zoom level. + * + * If a camera has a viewport height of 600 and a zoom of 0.5 then its display height + * would be 1200, as it's displaying twice as many pixels as zoom level 1. + * + * Equally, a camera with a height of 600 and zoom of 2 would have a display height + * of 300 pixels. + * + * @name Phaser.Cameras.Scene2D.BaseCamera#displayHeight + * @type {number} + * @readonly + * @since 3.11.0 + */ + displayHeight: { + + get: function () + { + return this.height / this.zoom; + } + + } + +}); + +module.exports = BaseCamera; diff --git a/src/cameras/2d/Camera.js b/src/cameras/2d/Camera.js index dbd69c269..478c17ebe 100644 --- a/src/cameras/2d/Camera.js +++ b/src/cameras/2d/Camera.js @@ -1,1012 +1,1012 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseCamera = require('./BaseCamera'); -var CanvasPool = require('../../display/canvas/CanvasPool'); -var CenterOn = require('../../geom/rectangle/CenterOn'); -var Clamp = require('../../math/Clamp'); -var Class = require('../../utils/Class'); -var Components = require('../../gameobjects/components'); -var Effects = require('./effects'); -var Linear = require('../../math/Linear'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Camera. - * - * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, - * and can be positioned, rotated, zoomed and scrolled accordingly. - * - * A Camera consists of two elements: The viewport and the scroll values. - * - * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are - * created the same size as your game, but their position and size can be set to anything. This means if you - * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, - * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). - * - * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this - * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the - * viewport, and changing the viewport has no impact on the scrolling. - * - * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, - * allowing you to filter Game Objects out on a per-Camera basis. - * - * A Camera also has built-in special effects including Fade, Flash and Camera Shake. - * - * @class Camera - * @memberof Phaser.Cameras.Scene2D - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Cameras.Scene2D.BaseCamera - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.Tint - * - * @param {number} x - The x position of the Camera, relative to the top-left of the game canvas. - * @param {number} y - The y position of the Camera, relative to the top-left of the game canvas. - * @param {number} width - The width of the Camera, in pixels. - * @param {number} height - The height of the Camera, in pixels. - */ -var Camera = new Class({ - - Extends: BaseCamera, - - Mixins: [ - Components.Flip, - Components.Tint - ], - - initialize: - - function Camera (x, y, width, height) - { - BaseCamera.call(this, x, y, width, height); - - /** - * Does this Camera allow the Game Objects it renders to receive input events? - * - * @name Phaser.Cameras.Scene2D.Camera#inputEnabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.inputEnabled = true; - - /** - * The Camera Fade effect handler. - * To fade this camera see the `Camera.fade` methods. - * - * @name Phaser.Cameras.Scene2D.Camera#fadeEffect - * @type {Phaser.Cameras.Scene2D.Effects.Fade} - * @since 3.5.0 - */ - this.fadeEffect = new Effects.Fade(this); - - /** - * The Camera Flash effect handler. - * To flash this camera see the `Camera.flash` method. - * - * @name Phaser.Cameras.Scene2D.Camera#flashEffect - * @type {Phaser.Cameras.Scene2D.Effects.Flash} - * @since 3.5.0 - */ - this.flashEffect = new Effects.Flash(this); - - /** - * The Camera Shake effect handler. - * To shake this camera see the `Camera.shake` method. - * - * @name Phaser.Cameras.Scene2D.Camera#shakeEffect - * @type {Phaser.Cameras.Scene2D.Effects.Shake} - * @since 3.5.0 - */ - this.shakeEffect = new Effects.Shake(this); - - /** - * The Camera Pan effect handler. - * To pan this camera see the `Camera.pan` method. - * - * @name Phaser.Cameras.Scene2D.Camera#panEffect - * @type {Phaser.Cameras.Scene2D.Effects.Pan} - * @since 3.11.0 - */ - this.panEffect = new Effects.Pan(this); - - /** - * The Camera Zoom effect handler. - * To zoom this camera see the `Camera.zoom` method. - * - * @name Phaser.Cameras.Scene2D.Camera#zoomEffect - * @type {Phaser.Cameras.Scene2D.Effects.Zoom} - * @since 3.11.0 - */ - this.zoomEffect = new Effects.Zoom(this); - - /** - * The linear interpolation value to use when following a target. - * - * Can also be set via `setLerp` or as part of the `startFollow` call. - * - * The default values of 1 means the camera will instantly snap to the target coordinates. - * A lower value, such as 0.1 means the camera will more slowly track the target, giving - * a smooth transition. You can set the horizontal and vertical values independently, and also - * adjust this value in real-time during your game. - * - * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. - * - * @name Phaser.Cameras.Scene2D.Camera#lerp - * @type {Phaser.Math.Vector2} - * @since 3.9.0 - */ - this.lerp = new Vector2(1, 1); - - /** - * The values stored in this property are subtracted from the Camera targets position, allowing you to - * offset the camera from the actual target x/y coordinates by this amount. - * Can also be set via `setFollowOffset` or as part of the `startFollow` call. - * - * @name Phaser.Cameras.Scene2D.Camera#followOffset - * @type {Phaser.Math.Vector2} - * @since 3.9.0 - */ - this.followOffset = new Vector2(); - - /** - * The Camera dead zone. - * - * The deadzone is only used when the camera is following a target. - * - * It defines a rectangular region within which if the target is present, the camera will not scroll. - * If the target moves outside of this area, the camera will begin scrolling in order to follow it. - * - * The `lerp` values that you can set for a follower target also apply when using a deadzone. - * - * You can directly set this property to be an instance of a Rectangle. Or, you can use the - * `setDeadzone` method for a chainable approach. - * - * The rectangle you provide can have its dimensions adjusted dynamically, however, please - * note that its position is updated every frame, as it is constantly re-centered on the cameras mid point. - * - * Calling `setDeadzone` with no arguments will reset an active deadzone, as will setting this property - * to `null`. - * - * @name Phaser.Cameras.Scene2D.Camera#deadzone - * @type {?Phaser.Geom.Rectangle} - * @since 3.11.0 - */ - this.deadzone = null; - - /** - * Internal follow target reference. - * - * @name Phaser.Cameras.Scene2D.Camera#_follow - * @type {?any} - * @private - * @default null - * @since 3.0.0 - */ - this._follow = null; - - /** - * Is this Camera rendering directly to the canvas or to a texture? - * - * Enable rendering to texture with the method `setRenderToTexture` (just enabling this boolean won't be enough) - * - * Once enabled you can toggle it by switching this property. - * - * To properly remove a render texture you should call the `clearRenderToTexture()` method. - * - * @name Phaser.Cameras.Scene2D.Camera#renderToTexture - * @type {boolean} - * @default false - * @since 3.13.0 - */ - this.renderToTexture = false; - - /** - * If this Camera is rendering to a texture (via `setRenderToTexture`) then you - * have the option to control if it should also render to the Game canvas as well. - * - * By default, a Camera will render both to its texture and to the Game canvas. - * - * However, if you set ths property to `false` it will only render to the texture - * and skip rendering to the Game canvas. - * - * Setting this property if the Camera isn't rendering to a texture has no effect. - * - * @name Phaser.Cameras.Scene2D.Camera#renderToGame - * @type {boolean} - * @default true - * @since 3.23.0 - */ - this.renderToGame = true; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the HTML Canvas Element that the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only populated if Phaser is running with the Canvas Renderer. - * - * @name Phaser.Cameras.Scene2D.Camera#canvas - * @type {HTMLCanvasElement} - * @since 3.13.0 - */ - this.canvas = null; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the Rendering Context belonging to the Canvas element the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only populated if Phaser is running with the Canvas Renderer. - * - * @name Phaser.Cameras.Scene2D.Camera#context - * @type {CanvasRenderingContext2D} - * @since 3.13.0 - */ - this.context = null; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the GL Texture belonging the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only set if Phaser is running with the WebGL Renderer. - * - * @name Phaser.Cameras.Scene2D.Camera#glTexture - * @type {?WebGLTexture} - * @since 3.13.0 - */ - this.glTexture = null; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the GL Frame Buffer belonging the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only set if Phaser is running with the WebGL Renderer. - * - * @name Phaser.Cameras.Scene2D.Camera#framebuffer - * @type {?WebGLFramebuffer} - * @since 3.13.0 - */ - this.framebuffer = null; - - /** - * If this Camera has been set to render to a texture and to use a custom pipeline, - * then this holds a reference to the pipeline the Camera is drawing with. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only set if Phaser is running with the WebGL Renderer. - * - * @name Phaser.Cameras.Scene2D.Camera#pipeline - * @type {any} - * @since 3.13.0 - */ - this.pipeline = null; - }, - - /** - * Sets the Camera to render to a texture instead of to the main canvas. - * - * The Camera will redirect all Game Objects it's asked to render to this texture. - * - * During the render sequence, the texture itself will then be rendered to the main canvas. - * - * Doing this gives you the ability to modify the texture before this happens, - * allowing for special effects such as Camera specific shaders, or post-processing - * on the texture. - * - * If running under Canvas the Camera will render to its `canvas` property. - * - * If running under WebGL the Camera will create a frame buffer, which is stored in its `framebuffer` and `glTexture` properties. - * - * If you set a camera to render to a texture then it will emit 2 events during the render loop: - * - * First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. - * - * Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the - * Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before - * it appears in-game. - * - * You should not enable this unless you plan on actually using the texture it creates - * somehow, otherwise you're just doubling the work required to render your game. - * - * If you only require the Camera to render to a texture, and not also to the Game, - * them set the `renderToGame` parameter to `false`. - * - * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. - * - * If you no longer require the Camera to render to a texture, call the `clearRenderToTexture` method, - * which will delete the respective textures and free-up resources. - * - * @method Phaser.Cameras.Scene2D.Camera#setRenderToTexture - * @since 3.13.0 - * - * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. - * @param {boolean} [renderToGame=true] - If you do not need the Camera to still render to the Game, set this parameter to `false`. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - setRenderToTexture: function (pipeline, renderToGame) - { - if (renderToGame === undefined) { renderToGame = true; } - - var renderer = this.scene.sys.game.renderer; - - if (renderer.gl) - { - this.glTexture = renderer.createTextureFromSource(null, this.width, this.height, 0); - this.framebuffer = renderer.createFramebuffer(this.width, this.height, this.glTexture, false); - } - else - { - this.canvas = CanvasPool.create2D(this, this.width, this.height); - this.context = this.canvas.getContext('2d'); - } - - this.renderToTexture = true; - this.renderToGame = renderToGame; - - if (pipeline) - { - this.setPipeline(pipeline); - } - - return this; - }, - - /** - * Sets the WebGL pipeline this Camera is using when rendering to a texture. - * - * You can pass either the string-based name of the pipeline, or a reference to the pipeline itself. - * - * Call this method with no arguments to clear any previously set pipeline. - * - * @method Phaser.Cameras.Scene2D.Camera#setPipeline - * @since 3.13.0 - * - * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - The WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. Or if left empty it will clear the pipeline. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - setPipeline: function (pipeline) - { - if (typeof pipeline === 'string') - { - var renderer = this.scene.sys.game.renderer; - - if (renderer.gl && renderer.hasPipeline(pipeline)) - { - this.pipeline = renderer.getPipeline(pipeline); - } - } - else - { - this.pipeline = pipeline; - } - - return this; - }, - - /** - * If this Camera was set to render to a texture, this will clear the resources it was using and - * redirect it to render back to the primary Canvas again. - * - * If you only wish to temporarily disable rendering to a texture then you can toggle the - * property `renderToTexture` instead. - * - * @method Phaser.Cameras.Scene2D.Camera#clearRenderToTexture - * @since 3.13.0 - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - clearRenderToTexture: function () - { - if (!this.scene) - { - return; - } - - var renderer = this.scene.sys.game.renderer; - - if (!renderer) - { - return; - } - - if (renderer.gl) - { - if (this.framebuffer) - { - renderer.deleteFramebuffer(this.framebuffer); - } - - if (this.glTexture) - { - renderer.deleteTexture(this.glTexture); - } - - this.framebuffer = null; - this.glTexture = null; - this.pipeline = null; - } - else - { - CanvasPool.remove(this); - - this.canvas = null; - this.context = null; - } - - this.renderToTexture = false; - - return this; - }, - - /** - * Sets the Camera dead zone. - * - * The deadzone is only used when the camera is following a target. - * - * It defines a rectangular region within which if the target is present, the camera will not scroll. - * If the target moves outside of this area, the camera will begin scrolling in order to follow it. - * - * The deadzone rectangle is re-positioned every frame so that it is centered on the mid-point - * of the camera. This allows you to use the object for additional game related checks, such as - * testing if an object is within it or not via a Rectangle.contains call. - * - * The `lerp` values that you can set for a follower target also apply when using a deadzone. - * - * Calling this method with no arguments will reset an active deadzone. - * - * @method Phaser.Cameras.Scene2D.Camera#setDeadzone - * @since 3.11.0 - * - * @param {number} [width] - The width of the deadzone rectangle in pixels. If not specified the deadzone is removed. - * @param {number} [height] - The height of the deadzone rectangle in pixels. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - setDeadzone: function (width, height) - { - if (width === undefined) - { - this.deadzone = null; - } - else - { - if (this.deadzone) - { - this.deadzone.width = width; - this.deadzone.height = height; - } - else - { - this.deadzone = new Rectangle(0, 0, width, height); - } - - if (this._follow) - { - var originX = this.width / 2; - var originY = this.height / 2; - - var fx = this._follow.x - this.followOffset.x; - var fy = this._follow.y - this.followOffset.y; - - this.midPoint.set(fx, fy); - - this.scrollX = fx - originX; - this.scrollY = fy - originY; - } - - CenterOn(this.deadzone, this.midPoint.x, this.midPoint.y); - } - - return this; - }, - - /** - * Fades the Camera in from the given color over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Camera#fadeIn - * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START - * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE - * @since 3.3.0 - * - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - fadeIn: function (duration, red, green, blue, callback, context) - { - return this.fadeEffect.start(false, duration, red, green, blue, true, callback, context); - }, - - /** - * Fades the Camera out to the given color over the duration specified. - * This is an alias for Camera.fade that forces the fade to start, regardless of existing fades. - * - * @method Phaser.Cameras.Scene2D.Camera#fadeOut - * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START - * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE - * @since 3.3.0 - * - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - fadeOut: function (duration, red, green, blue, callback, context) - { - return this.fadeEffect.start(true, duration, red, green, blue, true, callback, context); - }, - - /** - * Fades the Camera from the given color to transparent over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Camera#fadeFrom - * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START - * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE - * @since 3.5.0 - * - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. - * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - fadeFrom: function (duration, red, green, blue, force, callback, context) - { - return this.fadeEffect.start(false, duration, red, green, blue, force, callback, context); - }, - - /** - * Fades the Camera from transparent to the given color over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Camera#fade - * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START - * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE - * @since 3.0.0 - * - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. - * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - fade: function (duration, red, green, blue, force, callback, context) - { - return this.fadeEffect.start(true, duration, red, green, blue, force, callback, context); - }, - - /** - * Flashes the Camera by setting it to the given color immediately and then fading it away again quickly over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Camera#flash - * @fires Phaser.Cameras.Scene2D.Events#FLASH_START - * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE - * @since 3.0.0 - * - * @param {integer} [duration=250] - The duration of the effect in milliseconds. - * @param {integer} [red=255] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=255] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=255] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. - * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - flash: function (duration, red, green, blue, force, callback, context) - { - return this.flashEffect.start(duration, red, green, blue, force, callback, context); - }, - - /** - * Shakes the Camera by the given intensity over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Camera#shake - * @fires Phaser.Cameras.Scene2D.Events#SHAKE_START - * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE - * @since 3.0.0 - * - * @param {integer} [duration=100] - The duration of the effect in milliseconds. - * @param {(number|Phaser.Math.Vector2)} [intensity=0.05] - The intensity of the shake. - * @param {boolean} [force=false] - Force the shake effect to start immediately, even if already running. - * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - shake: function (duration, intensity, force, callback, context) - { - return this.shakeEffect.start(duration, intensity, force, callback, context); - }, - - /** - * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, - * over the duration and with the ease specified. - * - * @method Phaser.Cameras.Scene2D.Camera#pan - * @fires Phaser.Cameras.Scene2D.Events#PAN_START - * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE - * @since 3.11.0 - * - * @param {number} x - The destination x coordinate to scroll the center of the Camera viewport to. - * @param {number} y - The destination y coordinate to scroll the center of the Camera viewport to. - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. - * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * the current camera scroll x coordinate and the current camera scroll y coordinate. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - pan: function (x, y, duration, ease, force, callback, context) - { - return this.panEffect.start(x, y, duration, ease, force, callback, context); - }, - - /** - * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. - * - * @method Phaser.Cameras.Scene2D.Camera#zoomTo - * @fires Phaser.Cameras.Scene2D.Events#ZOOM_START - * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE - * @since 3.11.0 - * - * @param {number} zoom - The target Camera zoom value. - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. - * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * the current camera scroll x coordinate and the current camera scroll y coordinate. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - zoomTo: function (zoom, duration, ease, force, callback, context) - { - return this.zoomEffect.start(zoom, duration, ease, force, callback, context); - }, - - /** - * Internal preRender step. - * - * @method Phaser.Cameras.Scene2D.Camera#preRender - * @protected - * @since 3.0.0 - * - * @param {number} resolution - The game resolution, as set in the Scale Manager. - */ - preRender: function (resolution) - { - var width = this.width; - var height = this.height; - - var halfWidth = width * 0.5; - var halfHeight = height * 0.5; - - var zoom = this.zoom * resolution; - var matrix = this.matrix; - - var originX = width * this.originX; - var originY = height * this.originY; - - var follow = this._follow; - var deadzone = this.deadzone; - - var sx = this.scrollX; - var sy = this.scrollY; - - if (deadzone) - { - CenterOn(deadzone, this.midPoint.x, this.midPoint.y); - } - - if (follow && !this.panEffect.isRunning) - { - var fx = (follow.x - this.followOffset.x); - var fy = (follow.y - this.followOffset.y); - - if (deadzone) - { - if (fx < deadzone.x) - { - sx = Linear(sx, sx - (deadzone.x - fx), this.lerp.x); - } - else if (fx > deadzone.right) - { - sx = Linear(sx, sx + (fx - deadzone.right), this.lerp.x); - } - - if (fy < deadzone.y) - { - sy = Linear(sy, sy - (deadzone.y - fy), this.lerp.y); - } - else if (fy > deadzone.bottom) - { - sy = Linear(sy, sy + (fy - deadzone.bottom), this.lerp.y); - } - } - else - { - sx = Linear(sx, fx - originX, this.lerp.x); - sy = Linear(sy, fy - originY, this.lerp.y); - } - } - - if (this.useBounds) - { - sx = this.clampX(sx); - sy = this.clampY(sy); - } - - if (this.roundPixels) - { - originX = Math.round(originX); - originY = Math.round(originY); - } - - // Values are in pixels and not impacted by zooming the Camera - this.scrollX = sx; - this.scrollY = sy; - - var midX = sx + halfWidth; - var midY = sy + halfHeight; - - // 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 - this.midPoint.set(midX, midY); - - var displayWidth = width / zoom; - var displayHeight = height / zoom; - - this.worldView.setTo( - midX - (displayWidth / 2), - midY - (displayHeight / 2), - displayWidth, - displayHeight - ); - - matrix.applyITRS(this.x + originX, this.y + originY, this.rotation, zoom, zoom); - matrix.translate(-originX, -originY); - - this.shakeEffect.preRender(); - }, - - /** - * Sets the linear interpolation value to use when following a target. - * - * The default values of 1 means the camera will instantly snap to the target coordinates. - * A lower value, such as 0.1 means the camera will more slowly track the target, giving - * a smooth transition. You can set the horizontal and vertical values independently, and also - * adjust this value in real-time during your game. - * - * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. - * - * @method Phaser.Cameras.Scene2D.Camera#setLerp - * @since 3.9.0 - * - * @param {number} [x=1] - The amount added to the horizontal linear interpolation of the follow target. - * @param {number} [y=1] - The amount added to the vertical linear interpolation of the follow target. - * - * @return {this} This Camera instance. - */ - setLerp: function (x, y) - { - if (x === undefined) { x = 1; } - if (y === undefined) { y = x; } - - this.lerp.set(x, y); - - return this; - }, - - /** - * Sets the horizontal and vertical offset of the camera from its follow target. - * The values are subtracted from the targets position during the Cameras update step. - * - * @method Phaser.Cameras.Scene2D.Camera#setFollowOffset - * @since 3.9.0 - * - * @param {number} [x=0] - The horizontal offset from the camera follow target.x position. - * @param {number} [y=0] - The vertical offset from the camera follow target.y position. - * - * @return {this} This Camera instance. - */ - setFollowOffset: function (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - this.followOffset.set(x, y); - - return this; - }, - - /** - * Sets the Camera to follow a Game Object. - * - * When enabled the Camera will automatically adjust its scroll position to keep the target Game Object - * in its center. - * - * You can set the linear interpolation value used in the follow code. - * Use low lerp values (such as 0.1) to automatically smooth the camera motion. - * - * If you find you're getting a slight "jitter" effect when following an object it's probably to do with sub-pixel - * rendering of the targets position. This can be rounded by setting the `roundPixels` argument to `true` to - * force full pixel rounding rendering. Note that this can still be broken if you have specified a non-integer zoom - * value on the camera. So be sure to keep the camera zoom to integers. - * - * @method Phaser.Cameras.Scene2D.Camera#startFollow - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|object)} target - The target for the Camera to follow. - * @param {boolean} [roundPixels=false] - Round the camera position to whole integers to avoid sub-pixel rendering? - * @param {number} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. - * @param {number} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. - * @param {number} [offsetX=0] - The horizontal offset from the camera follow target.x position. - * @param {number} [offsetY=0] - The vertical offset from the camera follow target.y position. - * - * @return {this} This Camera instance. - */ - startFollow: function (target, roundPixels, lerpX, lerpY, offsetX, offsetY) - { - if (roundPixels === undefined) { roundPixels = false; } - if (lerpX === undefined) { lerpX = 1; } - if (lerpY === undefined) { lerpY = lerpX; } - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = offsetX; } - - this._follow = target; - - this.roundPixels = roundPixels; - - lerpX = Clamp(lerpX, 0, 1); - lerpY = Clamp(lerpY, 0, 1); - - this.lerp.set(lerpX, lerpY); - - this.followOffset.set(offsetX, offsetY); - - var originX = this.width / 2; - var originY = this.height / 2; - - var fx = target.x - offsetX; - var fy = target.y - offsetY; - - this.midPoint.set(fx, fy); - - this.scrollX = fx - originX; - this.scrollY = fy - originY; - - if (this.useBounds) - { - this.scrollX = this.clampX(this.scrollX); - this.scrollY = this.clampY(this.scrollY); - } - - return this; - }, - - /** - * Stops a Camera from following a Game Object, if previously set via `Camera.startFollow`. - * - * @method Phaser.Cameras.Scene2D.Camera#stopFollow - * @since 3.0.0 - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - stopFollow: function () - { - this._follow = null; - - return this; - }, - - /** - * Resets any active FX, such as a fade, flash or shake. Useful to call after a fade in order to - * remove the fade. - * - * @method Phaser.Cameras.Scene2D.Camera#resetFX - * @since 3.0.0 - * - * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. - */ - resetFX: function () - { - this.panEffect.reset(); - this.shakeEffect.reset(); - this.flashEffect.reset(); - this.fadeEffect.reset(); - - return this; - }, - - /** - * Internal method called automatically by the Camera Manager. - * - * @method Phaser.Cameras.Scene2D.Camera#update - * @protected - * @since 3.0.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - if (this.visible) - { - this.panEffect.update(time, delta); - this.zoomEffect.update(time, delta); - this.shakeEffect.update(time, delta); - this.flashEffect.update(time, delta); - this.fadeEffect.update(time, delta); - } - }, - - /** - * Destroys this Camera instance. You rarely need to call this directly. - * - * Called by the Camera Manager. If you wish to destroy a Camera please use `CameraManager.remove` as - * cameras are stored in a pool, ready for recycling later, and calling this directly will prevent that. - * - * @method Phaser.Cameras.Scene2D.Camera#destroy - * @fires Phaser.Cameras.Scene2D.Events#DESTROY - * @since 3.0.0 - */ - destroy: function () - { - this.clearRenderToTexture(); - - this.resetFX(); - - BaseCamera.prototype.destroy.call(this); - - this._follow = null; - - this.deadzone = null; - } - -}); - -module.exports = Camera; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCamera = require('./BaseCamera'); +var CanvasPool = require('../../display/canvas/CanvasPool'); +var CenterOn = require('../../geom/rectangle/CenterOn'); +var Clamp = require('../../math/Clamp'); +var Class = require('../../utils/Class'); +var Components = require('../../gameobjects/components'); +var Effects = require('./effects'); +var Linear = require('../../math/Linear'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Camera. + * + * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, + * and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. + * + * A Camera also has built-in special effects including Fade, Flash and Camera Shake. + * + * @class Camera + * @memberof Phaser.Cameras.Scene2D + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Cameras.Scene2D.BaseCamera + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Tint + * + * @param {number} x - The x position of the Camera, relative to the top-left of the game canvas. + * @param {number} y - The y position of the Camera, relative to the top-left of the game canvas. + * @param {number} width - The width of the Camera, in pixels. + * @param {number} height - The height of the Camera, in pixels. + */ +var Camera = new Class({ + + Extends: BaseCamera, + + Mixins: [ + Components.Flip, + Components.Tint + ], + + initialize: + + function Camera (x, y, width, height) + { + BaseCamera.call(this, x, y, width, height); + + /** + * Does this Camera allow the Game Objects it renders to receive input events? + * + * @name Phaser.Cameras.Scene2D.Camera#inputEnabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.inputEnabled = true; + + /** + * The Camera Fade effect handler. + * To fade this camera see the `Camera.fade` methods. + * + * @name Phaser.Cameras.Scene2D.Camera#fadeEffect + * @type {Phaser.Cameras.Scene2D.Effects.Fade} + * @since 3.5.0 + */ + this.fadeEffect = new Effects.Fade(this); + + /** + * The Camera Flash effect handler. + * To flash this camera see the `Camera.flash` method. + * + * @name Phaser.Cameras.Scene2D.Camera#flashEffect + * @type {Phaser.Cameras.Scene2D.Effects.Flash} + * @since 3.5.0 + */ + this.flashEffect = new Effects.Flash(this); + + /** + * The Camera Shake effect handler. + * To shake this camera see the `Camera.shake` method. + * + * @name Phaser.Cameras.Scene2D.Camera#shakeEffect + * @type {Phaser.Cameras.Scene2D.Effects.Shake} + * @since 3.5.0 + */ + this.shakeEffect = new Effects.Shake(this); + + /** + * The Camera Pan effect handler. + * To pan this camera see the `Camera.pan` method. + * + * @name Phaser.Cameras.Scene2D.Camera#panEffect + * @type {Phaser.Cameras.Scene2D.Effects.Pan} + * @since 3.11.0 + */ + this.panEffect = new Effects.Pan(this); + + /** + * The Camera Zoom effect handler. + * To zoom this camera see the `Camera.zoom` method. + * + * @name Phaser.Cameras.Scene2D.Camera#zoomEffect + * @type {Phaser.Cameras.Scene2D.Effects.Zoom} + * @since 3.11.0 + */ + this.zoomEffect = new Effects.Zoom(this); + + /** + * The linear interpolation value to use when following a target. + * + * Can also be set via `setLerp` or as part of the `startFollow` call. + * + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * + * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. + * + * @name Phaser.Cameras.Scene2D.Camera#lerp + * @type {Phaser.Math.Vector2} + * @since 3.9.0 + */ + this.lerp = new Vector2(1, 1); + + /** + * The values stored in this property are subtracted from the Camera targets position, allowing you to + * offset the camera from the actual target x/y coordinates by this amount. + * Can also be set via `setFollowOffset` or as part of the `startFollow` call. + * + * @name Phaser.Cameras.Scene2D.Camera#followOffset + * @type {Phaser.Math.Vector2} + * @since 3.9.0 + */ + this.followOffset = new Vector2(); + + /** + * The Camera dead zone. + * + * The deadzone is only used when the camera is following a target. + * + * It defines a rectangular region within which if the target is present, the camera will not scroll. + * If the target moves outside of this area, the camera will begin scrolling in order to follow it. + * + * The `lerp` values that you can set for a follower target also apply when using a deadzone. + * + * You can directly set this property to be an instance of a Rectangle. Or, you can use the + * `setDeadzone` method for a chainable approach. + * + * The rectangle you provide can have its dimensions adjusted dynamically, however, please + * note that its position is updated every frame, as it is constantly re-centered on the cameras mid point. + * + * Calling `setDeadzone` with no arguments will reset an active deadzone, as will setting this property + * to `null`. + * + * @name Phaser.Cameras.Scene2D.Camera#deadzone + * @type {?Phaser.Geom.Rectangle} + * @since 3.11.0 + */ + this.deadzone = null; + + /** + * Internal follow target reference. + * + * @name Phaser.Cameras.Scene2D.Camera#_follow + * @type {?any} + * @private + * @default null + * @since 3.0.0 + */ + this._follow = null; + + /** + * Is this Camera rendering directly to the canvas or to a texture? + * + * Enable rendering to texture with the method `setRenderToTexture` (just enabling this boolean won't be enough) + * + * Once enabled you can toggle it by switching this property. + * + * To properly remove a render texture you should call the `clearRenderToTexture()` method. + * + * @name Phaser.Cameras.Scene2D.Camera#renderToTexture + * @type {boolean} + * @default false + * @since 3.13.0 + */ + this.renderToTexture = false; + + /** + * If this Camera is rendering to a texture (via `setRenderToTexture`) then you + * have the option to control if it should also render to the Game canvas as well. + * + * By default, a Camera will render both to its texture and to the Game canvas. + * + * However, if you set ths property to `false` it will only render to the texture + * and skip rendering to the Game canvas. + * + * Setting this property if the Camera isn't rendering to a texture has no effect. + * + * @name Phaser.Cameras.Scene2D.Camera#renderToGame + * @type {boolean} + * @default true + * @since 3.23.0 + */ + this.renderToGame = true; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the HTML Canvas Element that the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only populated if Phaser is running with the Canvas Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#canvas + * @type {HTMLCanvasElement} + * @since 3.13.0 + */ + this.canvas = null; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the Rendering Context belonging to the Canvas element the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only populated if Phaser is running with the Canvas Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#context + * @type {CanvasRenderingContext2D} + * @since 3.13.0 + */ + this.context = null; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the GL Texture belonging the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#glTexture + * @type {?WebGLTexture} + * @since 3.13.0 + */ + this.glTexture = null; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the GL Frame Buffer belonging the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#framebuffer + * @type {?WebGLFramebuffer} + * @since 3.13.0 + */ + this.framebuffer = null; + + /** + * If this Camera has been set to render to a texture and to use a custom pipeline, + * then this holds a reference to the pipeline the Camera is drawing with. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.Cameras.Scene2D.Camera#pipeline + * @type {any} + * @since 3.13.0 + */ + this.pipeline = null; + }, + + /** + * Sets the Camera to render to a texture instead of to the main canvas. + * + * The Camera will redirect all Game Objects it's asked to render to this texture. + * + * During the render sequence, the texture itself will then be rendered to the main canvas. + * + * Doing this gives you the ability to modify the texture before this happens, + * allowing for special effects such as Camera specific shaders, or post-processing + * on the texture. + * + * If running under Canvas the Camera will render to its `canvas` property. + * + * If running under WebGL the Camera will create a frame buffer, which is stored in its `framebuffer` and `glTexture` properties. + * + * If you set a camera to render to a texture then it will emit 2 events during the render loop: + * + * First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. + * + * Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the + * Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before + * it appears in-game. + * + * You should not enable this unless you plan on actually using the texture it creates + * somehow, otherwise you're just doubling the work required to render your game. + * + * If you only require the Camera to render to a texture, and not also to the Game, + * them set the `renderToGame` parameter to `false`. + * + * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. + * + * If you no longer require the Camera to render to a texture, call the `clearRenderToTexture` method, + * which will delete the respective textures and free-up resources. + * + * @method Phaser.Cameras.Scene2D.Camera#setRenderToTexture + * @since 3.13.0 + * + * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. + * @param {boolean} [renderToGame=true] - If you do not need the Camera to still render to the Game, set this parameter to `false`. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + setRenderToTexture: function (pipeline, renderToGame) + { + if (renderToGame === undefined) { renderToGame = true; } + + var renderer = this.scene.sys.game.renderer; + + if (renderer.gl) + { + this.glTexture = renderer.createTextureFromSource(null, this.width, this.height, 0); + this.framebuffer = renderer.createFramebuffer(this.width, this.height, this.glTexture, false); + } + else + { + this.canvas = CanvasPool.create2D(this, this.width, this.height); + this.context = this.canvas.getContext('2d'); + } + + this.renderToTexture = true; + this.renderToGame = renderToGame; + + if (pipeline) + { + this.setPipeline(pipeline); + } + + return this; + }, + + /** + * Sets the WebGL pipeline this Camera is using when rendering to a texture. + * + * You can pass either the string-based name of the pipeline, or a reference to the pipeline itself. + * + * Call this method with no arguments to clear any previously set pipeline. + * + * @method Phaser.Cameras.Scene2D.Camera#setPipeline + * @since 3.13.0 + * + * @param {(string|Phaser.Renderer.WebGL.WebGLPipeline)} [pipeline] - The WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. Or if left empty it will clear the pipeline. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + setPipeline: function (pipeline) + { + if (typeof pipeline === 'string') + { + var renderer = this.scene.sys.game.renderer; + + if (renderer.gl && renderer.hasPipeline(pipeline)) + { + this.pipeline = renderer.getPipeline(pipeline); + } + } + else + { + this.pipeline = pipeline; + } + + return this; + }, + + /** + * If this Camera was set to render to a texture, this will clear the resources it was using and + * redirect it to render back to the primary Canvas again. + * + * If you only wish to temporarily disable rendering to a texture then you can toggle the + * property `renderToTexture` instead. + * + * @method Phaser.Cameras.Scene2D.Camera#clearRenderToTexture + * @since 3.13.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + clearRenderToTexture: function () + { + if (!this.scene) + { + return; + } + + var renderer = this.scene.sys.game.renderer; + + if (!renderer) + { + return; + } + + if (renderer.gl) + { + if (this.framebuffer) + { + renderer.deleteFramebuffer(this.framebuffer); + } + + if (this.glTexture) + { + renderer.deleteTexture(this.glTexture); + } + + this.framebuffer = null; + this.glTexture = null; + this.pipeline = null; + } + else + { + CanvasPool.remove(this); + + this.canvas = null; + this.context = null; + } + + this.renderToTexture = false; + + return this; + }, + + /** + * Sets the Camera dead zone. + * + * The deadzone is only used when the camera is following a target. + * + * It defines a rectangular region within which if the target is present, the camera will not scroll. + * If the target moves outside of this area, the camera will begin scrolling in order to follow it. + * + * The deadzone rectangle is re-positioned every frame so that it is centered on the mid-point + * of the camera. This allows you to use the object for additional game related checks, such as + * testing if an object is within it or not via a Rectangle.contains call. + * + * The `lerp` values that you can set for a follower target also apply when using a deadzone. + * + * Calling this method with no arguments will reset an active deadzone. + * + * @method Phaser.Cameras.Scene2D.Camera#setDeadzone + * @since 3.11.0 + * + * @param {number} [width] - The width of the deadzone rectangle in pixels. If not specified the deadzone is removed. + * @param {number} [height] - The height of the deadzone rectangle in pixels. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + setDeadzone: function (width, height) + { + if (width === undefined) + { + this.deadzone = null; + } + else + { + if (this.deadzone) + { + this.deadzone.width = width; + this.deadzone.height = height; + } + else + { + this.deadzone = new Rectangle(0, 0, width, height); + } + + if (this._follow) + { + var originX = this.width / 2; + var originY = this.height / 2; + + var fx = this._follow.x - this.followOffset.x; + var fy = this._follow.y - this.followOffset.y; + + this.midPoint.set(fx, fy); + + this.scrollX = fx - originX; + this.scrollY = fy - originY; + } + + CenterOn(this.deadzone, this.midPoint.x, this.midPoint.y); + } + + return this; + }, + + /** + * Fades the Camera in from the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#fadeIn + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @since 3.3.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fadeIn: function (duration, red, green, blue, callback, context) + { + return this.fadeEffect.start(false, duration, red, green, blue, true, callback, context); + }, + + /** + * Fades the Camera out to the given color over the duration specified. + * This is an alias for Camera.fade that forces the fade to start, regardless of existing fades. + * + * @method Phaser.Cameras.Scene2D.Camera#fadeOut + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.3.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fadeOut: function (duration, red, green, blue, callback, context) + { + return this.fadeEffect.start(true, duration, red, green, blue, true, callback, context); + }, + + /** + * Fades the Camera from the given color to transparent over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#fadeFrom + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @since 3.5.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fadeFrom: function (duration, red, green, blue, force, callback, context) + { + return this.fadeEffect.start(false, duration, red, green, blue, force, callback, context); + }, + + /** + * Fades the Camera from transparent to the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#fade + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.0.0 + * + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + fade: function (duration, red, green, blue, force, callback, context) + { + return this.fadeEffect.start(true, duration, red, green, blue, force, callback, context); + }, + + /** + * Flashes the Camera by setting it to the given color immediately and then fading it away again quickly over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#flash + * @fires Phaser.Cameras.Scene2D.Events#FLASH_START + * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.0.0 + * + * @param {integer} [duration=250] - The duration of the effect in milliseconds. + * @param {integer} [red=255] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=255] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=255] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + flash: function (duration, red, green, blue, force, callback, context) + { + return this.flashEffect.start(duration, red, green, blue, force, callback, context); + }, + + /** + * Shakes the Camera by the given intensity over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Camera#shake + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_START + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.0.0 + * + * @param {integer} [duration=100] - The duration of the effect in milliseconds. + * @param {(number|Phaser.Math.Vector2)} [intensity=0.05] - The intensity of the shake. + * @param {boolean} [force=false] - Force the shake effect to start immediately, even if already running. + * @param {function} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + shake: function (duration, intensity, force, callback, context) + { + return this.shakeEffect.start(duration, intensity, force, callback, context); + }, + + /** + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Camera#pan + * @fires Phaser.Cameras.Scene2D.Events#PAN_START + * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.11.0 + * + * @param {number} x - The destination x coordinate to scroll the center of the Camera viewport to. + * @param {number} y - The destination y coordinate to scroll the center of the Camera viewport to. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + pan: function (x, y, duration, ease, force, callback, context) + { + return this.panEffect.start(x, y, duration, ease, force, callback, context); + }, + + /** + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Camera#zoomTo + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_START + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.11.0 + * + * @param {number} zoom - The target Camera zoom value. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + zoomTo: function (zoom, duration, ease, force, callback, context) + { + return this.zoomEffect.start(zoom, duration, ease, force, callback, context); + }, + + /** + * Internal preRender step. + * + * @method Phaser.Cameras.Scene2D.Camera#preRender + * @protected + * @since 3.0.0 + * + * @param {number} resolution - The game resolution, as set in the Scale Manager. + */ + preRender: function (resolution) + { + var width = this.width; + var height = this.height; + + var halfWidth = width * 0.5; + var halfHeight = height * 0.5; + + var zoom = this.zoom * resolution; + var matrix = this.matrix; + + var originX = width * this.originX; + var originY = height * this.originY; + + var follow = this._follow; + var deadzone = this.deadzone; + + var sx = this.scrollX; + var sy = this.scrollY; + + if (deadzone) + { + CenterOn(deadzone, this.midPoint.x, this.midPoint.y); + } + + if (follow && !this.panEffect.isRunning) + { + var fx = (follow.x - this.followOffset.x); + var fy = (follow.y - this.followOffset.y); + + if (deadzone) + { + if (fx < deadzone.x) + { + sx = Linear(sx, sx - (deadzone.x - fx), this.lerp.x); + } + else if (fx > deadzone.right) + { + sx = Linear(sx, sx + (fx - deadzone.right), this.lerp.x); + } + + if (fy < deadzone.y) + { + sy = Linear(sy, sy - (deadzone.y - fy), this.lerp.y); + } + else if (fy > deadzone.bottom) + { + sy = Linear(sy, sy + (fy - deadzone.bottom), this.lerp.y); + } + } + else + { + sx = Linear(sx, fx - originX, this.lerp.x); + sy = Linear(sy, fy - originY, this.lerp.y); + } + } + + if (this.useBounds) + { + sx = this.clampX(sx); + sy = this.clampY(sy); + } + + if (this.roundPixels) + { + originX = Math.round(originX); + originY = Math.round(originY); + } + + // Values are in pixels and not impacted by zooming the Camera + this.scrollX = sx; + this.scrollY = sy; + + var midX = sx + halfWidth; + var midY = sy + halfHeight; + + // 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 + this.midPoint.set(midX, midY); + + var displayWidth = width / zoom; + var displayHeight = height / zoom; + + this.worldView.setTo( + midX - (displayWidth / 2), + midY - (displayHeight / 2), + displayWidth, + displayHeight + ); + + matrix.applyITRS(this.x + originX, this.y + originY, this.rotation, zoom, zoom); + matrix.translate(-originX, -originY); + + this.shakeEffect.preRender(); + }, + + /** + * Sets the linear interpolation value to use when following a target. + * + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * + * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. + * + * @method Phaser.Cameras.Scene2D.Camera#setLerp + * @since 3.9.0 + * + * @param {number} [x=1] - The amount added to the horizontal linear interpolation of the follow target. + * @param {number} [y=1] - The amount added to the vertical linear interpolation of the follow target. + * + * @return {this} This Camera instance. + */ + setLerp: function (x, y) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + this.lerp.set(x, y); + + return this; + }, + + /** + * Sets the horizontal and vertical offset of the camera from its follow target. + * The values are subtracted from the targets position during the Cameras update step. + * + * @method Phaser.Cameras.Scene2D.Camera#setFollowOffset + * @since 3.9.0 + * + * @param {number} [x=0] - The horizontal offset from the camera follow target.x position. + * @param {number} [y=0] - The vertical offset from the camera follow target.y position. + * + * @return {this} This Camera instance. + */ + setFollowOffset: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + this.followOffset.set(x, y); + + return this; + }, + + /** + * Sets the Camera to follow a Game Object. + * + * When enabled the Camera will automatically adjust its scroll position to keep the target Game Object + * in its center. + * + * You can set the linear interpolation value used in the follow code. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following an object it's probably to do with sub-pixel + * rendering of the targets position. This can be rounded by setting the `roundPixels` argument to `true` to + * force full pixel rounding rendering. Note that this can still be broken if you have specified a non-integer zoom + * value on the camera. So be sure to keep the camera zoom to integers. + * + * @method Phaser.Cameras.Scene2D.Camera#startFollow + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|object)} target - The target for the Camera to follow. + * @param {boolean} [roundPixels=false] - Round the camera position to whole integers to avoid sub-pixel rendering? + * @param {number} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {number} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + * @param {number} [offsetX=0] - The horizontal offset from the camera follow target.x position. + * @param {number} [offsetY=0] - The vertical offset from the camera follow target.y position. + * + * @return {this} This Camera instance. + */ + startFollow: function (target, roundPixels, lerpX, lerpY, offsetX, offsetY) + { + if (roundPixels === undefined) { roundPixels = false; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = lerpX; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = offsetX; } + + this._follow = target; + + this.roundPixels = roundPixels; + + lerpX = Clamp(lerpX, 0, 1); + lerpY = Clamp(lerpY, 0, 1); + + this.lerp.set(lerpX, lerpY); + + this.followOffset.set(offsetX, offsetY); + + var originX = this.width / 2; + var originY = this.height / 2; + + var fx = target.x - offsetX; + var fy = target.y - offsetY; + + this.midPoint.set(fx, fy); + + this.scrollX = fx - originX; + this.scrollY = fy - originY; + + if (this.useBounds) + { + this.scrollX = this.clampX(this.scrollX); + this.scrollY = this.clampY(this.scrollY); + } + + return this; + }, + + /** + * Stops a Camera from following a Game Object, if previously set via `Camera.startFollow`. + * + * @method Phaser.Cameras.Scene2D.Camera#stopFollow + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + stopFollow: function () + { + this._follow = null; + + return this; + }, + + /** + * Resets any active FX, such as a fade, flash or shake. Useful to call after a fade in order to + * remove the fade. + * + * @method Phaser.Cameras.Scene2D.Camera#resetFX + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} This Camera instance. + */ + resetFX: function () + { + this.panEffect.reset(); + this.shakeEffect.reset(); + this.flashEffect.reset(); + this.fadeEffect.reset(); + + return this; + }, + + /** + * Internal method called automatically by the Camera Manager. + * + * @method Phaser.Cameras.Scene2D.Camera#update + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (this.visible) + { + this.panEffect.update(time, delta); + this.zoomEffect.update(time, delta); + this.shakeEffect.update(time, delta); + this.flashEffect.update(time, delta); + this.fadeEffect.update(time, delta); + } + }, + + /** + * Destroys this Camera instance. You rarely need to call this directly. + * + * Called by the Camera Manager. If you wish to destroy a Camera please use `CameraManager.remove` as + * cameras are stored in a pool, ready for recycling later, and calling this directly will prevent that. + * + * @method Phaser.Cameras.Scene2D.Camera#destroy + * @fires Phaser.Cameras.Scene2D.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + this.clearRenderToTexture(); + + this.resetFX(); + + BaseCamera.prototype.destroy.call(this); + + this._follow = null; + + this.deadzone = null; + } + +}); + +module.exports = Camera; diff --git a/src/cameras/2d/CameraManager.js b/src/cameras/2d/CameraManager.js index db7ea3806..992381fab 100644 --- a/src/cameras/2d/CameraManager.js +++ b/src/cameras/2d/CameraManager.js @@ -1,742 +1,742 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Camera = require('./Camera'); -var Class = require('../../utils/Class'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var PluginCache = require('../../plugins/PluginCache'); -var RectangleContains = require('../../geom/rectangle/Contains'); -var ScaleEvents = require('../../scale/events'); -var SceneEvents = require('../../scene/events'); - -/** - * @classdesc - * The Camera Manager is a plugin that belongs to a Scene and is responsible for managing all of the Scene Cameras. - * - * By default you can access the Camera Manager from within a Scene using `this.cameras`, although this can be changed - * in your game config. - * - * Create new Cameras using the `add` method. Or extend the Camera class with your own addition code and then add - * the new Camera in using the `addExisting` method. - * - * Cameras provide a view into your game world, and can be positioned, rotated, zoomed and scrolled accordingly. - * - * A Camera consists of two elements: The viewport and the scroll values. - * - * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are - * created the same size as your game, but their position and size can be set to anything. This means if you - * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, - * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). - * - * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this - * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the - * viewport, and changing the viewport has no impact on the scrolling. - * - * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, - * allowing you to filter Game Objects out on a per-Camera basis. The Camera Manager can manage up to 31 unique - * 'Game Object ignore capable' Cameras. Any Cameras beyond 31 that you create will all be given a Camera ID of - * zero, meaning that they cannot be used for Game Object exclusion. This means if you need your Camera to ignore - * Game Objects, make sure it's one of the first 31 created. - * - * A Camera also has built-in special effects including Fade, Flash, Camera Shake, Pan and Zoom. - * - * @class CameraManager - * @memberof Phaser.Cameras.Scene2D - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that owns the Camera Manager plugin. - */ -var CameraManager = new Class({ - - initialize: - - function CameraManager (scene) - { - /** - * The Scene that owns the Camera Manager plugin. - * - * @name Phaser.Cameras.Scene2D.CameraManager#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene.Systems handler for the Scene that owns the Camera Manager. - * - * @name Phaser.Cameras.Scene2D.CameraManager#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * All Cameras created by, or added to, this Camera Manager, will have their `roundPixels` - * property set to match this value. By default it is set to match the value set in the - * game configuration, but can be changed at any point. Equally, individual cameras can - * also be changed as needed. - * - * @name Phaser.Cameras.Scene2D.CameraManager#roundPixels - * @type {boolean} - * @since 3.11.0 - */ - this.roundPixels = scene.sys.game.config.roundPixels; - - /** - * An Array of the Camera objects being managed by this Camera Manager. - * The Cameras are updated and rendered in the same order in which they appear in this array. - * Do not directly add or remove entries to this array. However, you can move the contents - * around the array should you wish to adjust the display order. - * - * @name Phaser.Cameras.Scene2D.CameraManager#cameras - * @type {Phaser.Cameras.Scene2D.Camera[]} - * @since 3.0.0 - */ - this.cameras = []; - - /** - * A handy reference to the 'main' camera. By default this is the first Camera the - * Camera Manager creates. You can also set it directly, or use the `makeMain` argument - * in the `add` and `addExisting` methods. It allows you to access it from your game: - * - * ```javascript - * var cam = this.cameras.main; - * ``` - * - * Also see the properties `camera1`, `camera2` and so on. - * - * @name Phaser.Cameras.Scene2D.CameraManager#main - * @type {Phaser.Cameras.Scene2D.Camera} - * @since 3.0.0 - */ - this.main; - - /** - * A default un-transformed Camera that doesn't exist on the camera list and doesn't - * count towards the total number of cameras being managed. It exists for other - * systems, as well as your own code, should they require a basic un-transformed - * camera instance from which to calculate a view matrix. - * - * @name Phaser.Cameras.Scene2D.CameraManager#default - * @type {Phaser.Cameras.Scene2D.Camera} - * @since 3.17.0 - */ - this.default; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Cameras.Scene2D.CameraManager#boot - * @private - * @listens Phaser.Scenes.Events#DESTROY - * @since 3.5.1 - */ - boot: function () - { - var sys = this.systems; - - if (sys.settings.cameras) - { - // We have cameras to create - this.fromJSON(sys.settings.cameras); - } - else - { - // Make one - this.add(); - } - - this.main = this.cameras[0]; - - // Create a default camera - this.default = new Camera(0, 0, sys.scale.width, sys.scale.height).setScene(this.scene); - - sys.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Cameras.Scene2D.CameraManager#start - * @private - * @listens Phaser.Scenes.Events#UPDATE - * @listens Phaser.Scenes.Events#SHUTDOWN - * @since 3.5.0 - */ - start: function () - { - if (!this.main) - { - var sys = this.systems; - - if (sys.settings.cameras) - { - // We have cameras to create - this.fromJSON(sys.settings.cameras); - } - else - { - // Make one - this.add(); - } - - this.main = this.cameras[0]; - } - - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.UPDATE, this.update, this); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * 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 {integer} [x=0] - The horizontal position of the Camera viewport. - * @param {integer} [y=0] - The vertical position of the Camera viewport. - * @param {integer} [width] - The width of the Camera viewport. If not given it'll be the game config size. - * @param {integer} [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. - */ - add: function (x, y, width, height, makeMain, name) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.scene.sys.scale.width; } - if (height === undefined) { height = this.scene.sys.scale.height; } - if (makeMain === undefined) { makeMain = false; } - if (name === undefined) { name = ''; } - - var camera = new Camera(x, y, width, height); - - camera.setName(name); - camera.setScene(this.scene); - camera.setRoundPixels(this.roundPixels); - - camera.id = this.getNextID(); - - this.cameras.push(camera); - - if (makeMain) - { - this.main = camera; - } - - return camera; - }, - - /** - * Adds an existing Camera into the Camera Manager. - * - * The Camera should either be a `Phaser.Cameras.Scene2D.Camera` instance, or a class that extends from it. - * - * The Camera will have its `roundPixels` property set to whatever `CameraManager.roundPixels` is. You can change - * it after addition if required. - * - * The Camera will be assigned an ID, which is used for Game Object exclusion and then added to the - * manager. As long as it doesn't already exist in the manager it will be added then returned. - * - * If this method returns `null` then the Camera already exists in this Camera Manager. - * - * @method Phaser.Cameras.Scene2D.CameraManager#addExisting - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to be added to the Camera Manager. - * @param {boolean} [makeMain=false] - Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. - * - * @return {?Phaser.Cameras.Scene2D.Camera} The Camera that was added to the Camera Manager, or `null` if it couldn't be added. - */ - addExisting: function (camera, makeMain) - { - if (makeMain === undefined) { makeMain = false; } - - var index = this.cameras.indexOf(camera); - - if (index === -1) - { - camera.id = this.getNextID(); - - camera.setRoundPixels(this.roundPixels); - - this.cameras.push(camera); - - if (makeMain) - { - this.main = camera; - } - - return camera; - } - - return null; - }, - - /** - * Gets the next available Camera ID number. - * - * The Camera Manager supports up to 31 unique cameras, after which the ID returned will always be zero. - * You can create additional cameras beyond 31, but they cannot be used for Game Object exclusion. - * - * @method Phaser.Cameras.Scene2D.CameraManager#getNextID - * @private - * @since 3.11.0 - * - * @return {number} The next available Camera ID, or 0 if they're all already in use. - */ - getNextID: function () - { - var cameras = this.cameras; - - var testID = 1; - - // Find the first free camera ID we can use - - for (var t = 0; t < 32; t++) - { - var found = false; - - for (var i = 0; i < cameras.length; i++) - { - var camera = cameras[i]; - - if (camera && camera.id === testID) - { - found = true; - continue; - } - } - - if (found) - { - testID = testID << 1; - } - else - { - return testID; - } - } - - return 0; - }, - - /** - * Gets the total number of Cameras in this Camera Manager. - * - * If the optional `isVisible` argument is set it will only count Cameras that are currently visible. - * - * @method Phaser.Cameras.Scene2D.CameraManager#getTotal - * @since 3.11.0 - * - * @param {boolean} [isVisible=false] - Set the `true` to only include visible Cameras in the total. - * - * @return {integer} The total number of Cameras in this Camera Manager. - */ - getTotal: function (isVisible) - { - if (isVisible === undefined) { isVisible = false; } - - var total = 0; - - var cameras = this.cameras; - - for (var i = 0; i < cameras.length; i++) - { - var camera = cameras[i]; - - if (!isVisible || (isVisible && camera.visible)) - { - total++; - } - } - - return total; - }, - - /** - * 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 {Phaser.Cameras.Scene2D.CameraManager} This Camera Manager instance. - */ - fromJSON: function (config) - { - if (!Array.isArray(config)) - { - config = [ config ]; - } - - var gameWidth = this.scene.sys.scale.width; - var gameHeight = this.scene.sys.scale.height; - - for (var i = 0; i < config.length; i++) - { - var cameraConfig = config[i]; - - var x = GetFastValue(cameraConfig, 'x', 0); - var y = GetFastValue(cameraConfig, 'y', 0); - var width = GetFastValue(cameraConfig, 'width', gameWidth); - var height = GetFastValue(cameraConfig, 'height', gameHeight); - - var camera = this.add(x, y, width, height); - - // Direct properties - camera.name = GetFastValue(cameraConfig, 'name', ''); - camera.zoom = GetFastValue(cameraConfig, 'zoom', 1); - camera.rotation = GetFastValue(cameraConfig, 'rotation', 0); - camera.scrollX = GetFastValue(cameraConfig, 'scrollX', 0); - camera.scrollY = GetFastValue(cameraConfig, 'scrollY', 0); - camera.roundPixels = GetFastValue(cameraConfig, 'roundPixels', false); - camera.visible = GetFastValue(cameraConfig, 'visible', true); - - // Background Color - - var backgroundColor = GetFastValue(cameraConfig, 'backgroundColor', false); - - if (backgroundColor) - { - camera.setBackgroundColor(backgroundColor); - } - - // Bounds - - var boundsConfig = GetFastValue(cameraConfig, 'bounds', null); - - if (boundsConfig) - { - var bx = GetFastValue(boundsConfig, 'x', 0); - var by = GetFastValue(boundsConfig, 'y', 0); - var bwidth = GetFastValue(boundsConfig, 'width', gameWidth); - var bheight = GetFastValue(boundsConfig, 'height', gameHeight); - - camera.setBounds(bx, by, bwidth, bheight); - } - } - - return this; - }, - - /** - * 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`. - */ - getCamera: function (name) - { - var cameras = this.cameras; - - for (var i = 0; i < cameras.length; i++) - { - if (cameras[i].name === name) - { - return cameras[i]; - } - } - - return null; - }, - - /** - * Returns an array of all cameras below the given Pointer. - * - * The first camera in the array is the top-most camera in the camera list. - * - * @method Phaser.Cameras.Scene2D.CameraManager#getCamerasBelowPointer - * @since 3.10.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to check against. - * - * @return {Phaser.Cameras.Scene2D.Camera[]} An array of cameras below the Pointer. - */ - getCamerasBelowPointer: function (pointer) - { - var cameras = this.cameras; - - var x = pointer.x; - var y = pointer.y; - - var output = []; - - for (var i = 0; i < cameras.length; i++) - { - var camera = cameras[i]; - - if (camera.visible && camera.inputEnabled && RectangleContains(camera, x, y)) - { - // So the top-most camera is at the top of the search array - output.unshift(camera); - } - } - - return output; - }, - - /** - * Removes the given Camera, or an array of Cameras, from this Camera Manager. - * - * If found in the Camera Manager it will be immediately removed from the local cameras array. - * If also currently the 'main' camera, 'main' will be reset to be camera 0. - * - * The removed Cameras are automatically destroyed if the `runDestroy` argument is `true`, which is the default. - * If you wish to re-use the cameras then set this to `false`, but know that they will retain their references - * and internal data until destroyed or re-added to a Camera Manager. - * - * @method Phaser.Cameras.Scene2D.CameraManager#remove - * @since 3.0.0 - * - * @param {(Phaser.Cameras.Scene2D.Camera|Phaser.Cameras.Scene2D.Camera[])} camera - The Camera, or an array of Cameras, to be removed from this Camera Manager. - * @param {boolean} [runDestroy=true] - Automatically call `Camera.destroy` on each Camera removed from this Camera Manager. - * - * @return {integer} The total number of Cameras removed. - */ - remove: function (camera, runDestroy) - { - if (runDestroy === undefined) { runDestroy = true; } - - if (!Array.isArray(camera)) - { - camera = [ camera ]; - } - - var total = 0; - var cameras = this.cameras; - - for (var i = 0; i < camera.length; i++) - { - var index = cameras.indexOf(camera[i]); - - if (index !== -1) - { - if (runDestroy) - { - cameras[index].destroy(); - } - - cameras.splice(index, 1); - - total++; - } - } - - if (!this.main && cameras[0]) - { - this.main = cameras[0]; - } - - return total; - }, - - /** - * The internal render method. This is called automatically by the Scene and should not be invoked directly. - * - * It will iterate through all local cameras and render them in turn, as long as they're visible and have - * an alpha level > 0. - * - * @method Phaser.Cameras.Scene2D.CameraManager#render - * @protected - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Renderer that will render the children to this camera. - * @param {Phaser.GameObjects.GameObject[]} children - An array of renderable Game Objects. - * @param {number} interpolation - Interpolation value. Reserved for future use. - */ - render: function (renderer, children, interpolation) - { - var scene = this.scene; - var cameras = this.cameras; - - for (var i = 0; i < this.cameras.length; i++) - { - var camera = cameras[i]; - - if (camera.visible && camera.alpha > 0) - { - // Hard-coded to 1 for now - camera.preRender(1); - - renderer.render(scene, children, interpolation, camera); - } - } - }, - - /** - * Resets this Camera Manager. - * - * This will iterate through all current Cameras, destroying them all, then it will reset the - * cameras array, reset the ID counter and create 1 new single camera using the default values. - * - * @method Phaser.Cameras.Scene2D.CameraManager#resetAll - * @since 3.0.0 - * - * @return {Phaser.Cameras.Scene2D.Camera} The freshly created main Camera. - */ - resetAll: function () - { - for (var i = 0; i < this.cameras.length; i++) - { - this.cameras[i].destroy(); - } - - this.cameras = []; - - this.main = this.add(); - - return this.main; - }, - - /** - * The main update loop. Called automatically when the Scene steps. - * - * @method Phaser.Cameras.Scene2D.CameraManager#update - * @protected - * @since 3.0.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - for (var i = 0; i < this.cameras.length; i++) - { - this.cameras[i].update(time, delta); - } - }, - - /** - * The event handler that manages the `resize` event dispatched by the Scale Manager. - * - * @method Phaser.Cameras.Scene2D.CameraManager#onResize - * @since 3.18.0 - * - * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. - * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. - */ - onResize: function (gameSize, baseSize, displaySize, resolution, previousWidth, previousHeight) - { - for (var i = 0; i < this.cameras.length; i++) - { - var cam = this.cameras[i]; - - // 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 - - if (cam._x === 0 && cam._y === 0 && cam._width === previousWidth && cam._height === previousHeight) - { - cam.setSize(baseSize.width, baseSize.height); - } - } - }, - - /** - * Resizes all cameras to the given dimensions. - * - * @method Phaser.Cameras.Scene2D.CameraManager#resize - * @since 3.2.0 - * - * @param {number} width - The new width of the camera. - * @param {number} height - The new height of the camera. - */ - resize: function (width, height) - { - for (var i = 0; i < this.cameras.length; i++) - { - this.cameras[i].setSize(width, height); - } - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Cameras.Scene2D.CameraManager#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - this.main = undefined; - - for (var i = 0; i < this.cameras.length; i++) - { - this.cameras[i].destroy(); - } - - this.cameras = []; - - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.UPDATE, this.update, this); - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Cameras.Scene2D.CameraManager#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.default.destroy(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('CameraManager', CameraManager, 'cameras'); - -module.exports = CameraManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Camera = require('./Camera'); +var Class = require('../../utils/Class'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var PluginCache = require('../../plugins/PluginCache'); +var RectangleContains = require('../../geom/rectangle/Contains'); +var ScaleEvents = require('../../scale/events'); +var SceneEvents = require('../../scene/events'); + +/** + * @classdesc + * The Camera Manager is a plugin that belongs to a Scene and is responsible for managing all of the Scene Cameras. + * + * By default you can access the Camera Manager from within a Scene using `this.cameras`, although this can be changed + * in your game config. + * + * Create new Cameras using the `add` method. Or extend the Camera class with your own addition code and then add + * the new Camera in using the `addExisting` method. + * + * Cameras provide a view into your game world, and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. The Camera Manager can manage up to 31 unique + * 'Game Object ignore capable' Cameras. Any Cameras beyond 31 that you create will all be given a Camera ID of + * zero, meaning that they cannot be used for Game Object exclusion. This means if you need your Camera to ignore + * Game Objects, make sure it's one of the first 31 created. + * + * A Camera also has built-in special effects including Fade, Flash, Camera Shake, Pan and Zoom. + * + * @class CameraManager + * @memberof Phaser.Cameras.Scene2D + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that owns the Camera Manager plugin. + */ +var CameraManager = new Class({ + + initialize: + + function CameraManager (scene) + { + /** + * The Scene that owns the Camera Manager plugin. + * + * @name Phaser.Cameras.Scene2D.CameraManager#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene.Systems handler for the Scene that owns the Camera Manager. + * + * @name Phaser.Cameras.Scene2D.CameraManager#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * All Cameras created by, or added to, this Camera Manager, will have their `roundPixels` + * property set to match this value. By default it is set to match the value set in the + * game configuration, but can be changed at any point. Equally, individual cameras can + * also be changed as needed. + * + * @name Phaser.Cameras.Scene2D.CameraManager#roundPixels + * @type {boolean} + * @since 3.11.0 + */ + this.roundPixels = scene.sys.game.config.roundPixels; + + /** + * An Array of the Camera objects being managed by this Camera Manager. + * The Cameras are updated and rendered in the same order in which they appear in this array. + * Do not directly add or remove entries to this array. However, you can move the contents + * around the array should you wish to adjust the display order. + * + * @name Phaser.Cameras.Scene2D.CameraManager#cameras + * @type {Phaser.Cameras.Scene2D.Camera[]} + * @since 3.0.0 + */ + this.cameras = []; + + /** + * A handy reference to the 'main' camera. By default this is the first Camera the + * Camera Manager creates. You can also set it directly, or use the `makeMain` argument + * in the `add` and `addExisting` methods. It allows you to access it from your game: + * + * ```javascript + * var cam = this.cameras.main; + * ``` + * + * Also see the properties `camera1`, `camera2` and so on. + * + * @name Phaser.Cameras.Scene2D.CameraManager#main + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.0.0 + */ + this.main; + + /** + * A default un-transformed Camera that doesn't exist on the camera list and doesn't + * count towards the total number of cameras being managed. It exists for other + * systems, as well as your own code, should they require a basic un-transformed + * camera instance from which to calculate a view matrix. + * + * @name Phaser.Cameras.Scene2D.CameraManager#default + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.17.0 + */ + this.default; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Cameras.Scene2D.CameraManager#boot + * @private + * @listens Phaser.Scenes.Events#DESTROY + * @since 3.5.1 + */ + boot: function () + { + var sys = this.systems; + + if (sys.settings.cameras) + { + // We have cameras to create + this.fromJSON(sys.settings.cameras); + } + else + { + // Make one + this.add(); + } + + this.main = this.cameras[0]; + + // Create a default camera + this.default = new Camera(0, 0, sys.scale.width, sys.scale.height).setScene(this.scene); + + sys.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Cameras.Scene2D.CameraManager#start + * @private + * @listens Phaser.Scenes.Events#UPDATE + * @listens Phaser.Scenes.Events#SHUTDOWN + * @since 3.5.0 + */ + start: function () + { + if (!this.main) + { + var sys = this.systems; + + if (sys.settings.cameras) + { + // We have cameras to create + this.fromJSON(sys.settings.cameras); + } + else + { + // Make one + this.add(); + } + + this.main = this.cameras[0]; + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.update, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * 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 {integer} [x=0] - The horizontal position of the Camera viewport. + * @param {integer} [y=0] - The vertical position of the Camera viewport. + * @param {integer} [width] - The width of the Camera viewport. If not given it'll be the game config size. + * @param {integer} [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. + */ + add: function (x, y, width, height, makeMain, name) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (makeMain === undefined) { makeMain = false; } + if (name === undefined) { name = ''; } + + var camera = new Camera(x, y, width, height); + + camera.setName(name); + camera.setScene(this.scene); + camera.setRoundPixels(this.roundPixels); + + camera.id = this.getNextID(); + + this.cameras.push(camera); + + if (makeMain) + { + this.main = camera; + } + + return camera; + }, + + /** + * Adds an existing Camera into the Camera Manager. + * + * The Camera should either be a `Phaser.Cameras.Scene2D.Camera` instance, or a class that extends from it. + * + * The Camera will have its `roundPixels` property set to whatever `CameraManager.roundPixels` is. You can change + * it after addition if required. + * + * The Camera will be assigned an ID, which is used for Game Object exclusion and then added to the + * manager. As long as it doesn't already exist in the manager it will be added then returned. + * + * If this method returns `null` then the Camera already exists in this Camera Manager. + * + * @method Phaser.Cameras.Scene2D.CameraManager#addExisting + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to be added to the Camera Manager. + * @param {boolean} [makeMain=false] - Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. + * + * @return {?Phaser.Cameras.Scene2D.Camera} The Camera that was added to the Camera Manager, or `null` if it couldn't be added. + */ + addExisting: function (camera, makeMain) + { + if (makeMain === undefined) { makeMain = false; } + + var index = this.cameras.indexOf(camera); + + if (index === -1) + { + camera.id = this.getNextID(); + + camera.setRoundPixels(this.roundPixels); + + this.cameras.push(camera); + + if (makeMain) + { + this.main = camera; + } + + return camera; + } + + return null; + }, + + /** + * Gets the next available Camera ID number. + * + * The Camera Manager supports up to 31 unique cameras, after which the ID returned will always be zero. + * You can create additional cameras beyond 31, but they cannot be used for Game Object exclusion. + * + * @method Phaser.Cameras.Scene2D.CameraManager#getNextID + * @private + * @since 3.11.0 + * + * @return {number} The next available Camera ID, or 0 if they're all already in use. + */ + getNextID: function () + { + var cameras = this.cameras; + + var testID = 1; + + // Find the first free camera ID we can use + + for (var t = 0; t < 32; t++) + { + var found = false; + + for (var i = 0; i < cameras.length; i++) + { + var camera = cameras[i]; + + if (camera && camera.id === testID) + { + found = true; + continue; + } + } + + if (found) + { + testID = testID << 1; + } + else + { + return testID; + } + } + + return 0; + }, + + /** + * Gets the total number of Cameras in this Camera Manager. + * + * If the optional `isVisible` argument is set it will only count Cameras that are currently visible. + * + * @method Phaser.Cameras.Scene2D.CameraManager#getTotal + * @since 3.11.0 + * + * @param {boolean} [isVisible=false] - Set the `true` to only include visible Cameras in the total. + * + * @return {integer} The total number of Cameras in this Camera Manager. + */ + getTotal: function (isVisible) + { + if (isVisible === undefined) { isVisible = false; } + + var total = 0; + + var cameras = this.cameras; + + for (var i = 0; i < cameras.length; i++) + { + var camera = cameras[i]; + + if (!isVisible || (isVisible && camera.visible)) + { + total++; + } + } + + return total; + }, + + /** + * 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 {Phaser.Cameras.Scene2D.CameraManager} This Camera Manager instance. + */ + fromJSON: function (config) + { + if (!Array.isArray(config)) + { + config = [ config ]; + } + + var gameWidth = this.scene.sys.scale.width; + var gameHeight = this.scene.sys.scale.height; + + for (var i = 0; i < config.length; i++) + { + var cameraConfig = config[i]; + + var x = GetFastValue(cameraConfig, 'x', 0); + var y = GetFastValue(cameraConfig, 'y', 0); + var width = GetFastValue(cameraConfig, 'width', gameWidth); + var height = GetFastValue(cameraConfig, 'height', gameHeight); + + var camera = this.add(x, y, width, height); + + // Direct properties + camera.name = GetFastValue(cameraConfig, 'name', ''); + camera.zoom = GetFastValue(cameraConfig, 'zoom', 1); + camera.rotation = GetFastValue(cameraConfig, 'rotation', 0); + camera.scrollX = GetFastValue(cameraConfig, 'scrollX', 0); + camera.scrollY = GetFastValue(cameraConfig, 'scrollY', 0); + camera.roundPixels = GetFastValue(cameraConfig, 'roundPixels', false); + camera.visible = GetFastValue(cameraConfig, 'visible', true); + + // Background Color + + var backgroundColor = GetFastValue(cameraConfig, 'backgroundColor', false); + + if (backgroundColor) + { + camera.setBackgroundColor(backgroundColor); + } + + // Bounds + + var boundsConfig = GetFastValue(cameraConfig, 'bounds', null); + + if (boundsConfig) + { + var bx = GetFastValue(boundsConfig, 'x', 0); + var by = GetFastValue(boundsConfig, 'y', 0); + var bwidth = GetFastValue(boundsConfig, 'width', gameWidth); + var bheight = GetFastValue(boundsConfig, 'height', gameHeight); + + camera.setBounds(bx, by, bwidth, bheight); + } + } + + return this; + }, + + /** + * 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`. + */ + getCamera: function (name) + { + var cameras = this.cameras; + + for (var i = 0; i < cameras.length; i++) + { + if (cameras[i].name === name) + { + return cameras[i]; + } + } + + return null; + }, + + /** + * Returns an array of all cameras below the given Pointer. + * + * The first camera in the array is the top-most camera in the camera list. + * + * @method Phaser.Cameras.Scene2D.CameraManager#getCamerasBelowPointer + * @since 3.10.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to check against. + * + * @return {Phaser.Cameras.Scene2D.Camera[]} An array of cameras below the Pointer. + */ + getCamerasBelowPointer: function (pointer) + { + var cameras = this.cameras; + + var x = pointer.x; + var y = pointer.y; + + var output = []; + + for (var i = 0; i < cameras.length; i++) + { + var camera = cameras[i]; + + if (camera.visible && camera.inputEnabled && RectangleContains(camera, x, y)) + { + // So the top-most camera is at the top of the search array + output.unshift(camera); + } + } + + return output; + }, + + /** + * Removes the given Camera, or an array of Cameras, from this Camera Manager. + * + * If found in the Camera Manager it will be immediately removed from the local cameras array. + * If also currently the 'main' camera, 'main' will be reset to be camera 0. + * + * The removed Cameras are automatically destroyed if the `runDestroy` argument is `true`, which is the default. + * If you wish to re-use the cameras then set this to `false`, but know that they will retain their references + * and internal data until destroyed or re-added to a Camera Manager. + * + * @method Phaser.Cameras.Scene2D.CameraManager#remove + * @since 3.0.0 + * + * @param {(Phaser.Cameras.Scene2D.Camera|Phaser.Cameras.Scene2D.Camera[])} camera - The Camera, or an array of Cameras, to be removed from this Camera Manager. + * @param {boolean} [runDestroy=true] - Automatically call `Camera.destroy` on each Camera removed from this Camera Manager. + * + * @return {integer} The total number of Cameras removed. + */ + remove: function (camera, runDestroy) + { + if (runDestroy === undefined) { runDestroy = true; } + + if (!Array.isArray(camera)) + { + camera = [ camera ]; + } + + var total = 0; + var cameras = this.cameras; + + for (var i = 0; i < camera.length; i++) + { + var index = cameras.indexOf(camera[i]); + + if (index !== -1) + { + if (runDestroy) + { + cameras[index].destroy(); + } + + cameras.splice(index, 1); + + total++; + } + } + + if (!this.main && cameras[0]) + { + this.main = cameras[0]; + } + + return total; + }, + + /** + * The internal render method. This is called automatically by the Scene and should not be invoked directly. + * + * It will iterate through all local cameras and render them in turn, as long as they're visible and have + * an alpha level > 0. + * + * @method Phaser.Cameras.Scene2D.CameraManager#render + * @protected + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Renderer that will render the children to this camera. + * @param {Phaser.GameObjects.GameObject[]} children - An array of renderable Game Objects. + * @param {number} interpolation - Interpolation value. Reserved for future use. + */ + render: function (renderer, children, interpolation) + { + var scene = this.scene; + var cameras = this.cameras; + + for (var i = 0; i < this.cameras.length; i++) + { + var camera = cameras[i]; + + if (camera.visible && camera.alpha > 0) + { + // Hard-coded to 1 for now + camera.preRender(1); + + renderer.render(scene, children, interpolation, camera); + } + } + }, + + /** + * Resets this Camera Manager. + * + * This will iterate through all current Cameras, destroying them all, then it will reset the + * cameras array, reset the ID counter and create 1 new single camera using the default values. + * + * @method Phaser.Cameras.Scene2D.CameraManager#resetAll + * @since 3.0.0 + * + * @return {Phaser.Cameras.Scene2D.Camera} The freshly created main Camera. + */ + resetAll: function () + { + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].destroy(); + } + + this.cameras = []; + + this.main = this.add(); + + return this.main; + }, + + /** + * The main update loop. Called automatically when the Scene steps. + * + * @method Phaser.Cameras.Scene2D.CameraManager#update + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].update(time, delta); + } + }, + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * + * @method Phaser.Cameras.Scene2D.CameraManager#onResize + * @since 3.18.0 + * + * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. + * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + */ + onResize: function (gameSize, baseSize, displaySize, resolution, previousWidth, previousHeight) + { + for (var i = 0; i < this.cameras.length; i++) + { + var cam = this.cameras[i]; + + // 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 + + if (cam._x === 0 && cam._y === 0 && cam._width === previousWidth && cam._height === previousHeight) + { + cam.setSize(baseSize.width, baseSize.height); + } + } + }, + + /** + * Resizes all cameras to the given dimensions. + * + * @method Phaser.Cameras.Scene2D.CameraManager#resize + * @since 3.2.0 + * + * @param {number} width - The new width of the camera. + * @param {number} height - The new height of the camera. + */ + resize: function (width, height) + { + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].setSize(width, height); + } + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Cameras.Scene2D.CameraManager#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.main = undefined; + + for (var i = 0; i < this.cameras.length; i++) + { + this.cameras[i].destroy(); + } + + this.cameras = []; + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.update, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Cameras.Scene2D.CameraManager#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.default.destroy(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('CameraManager', CameraManager, 'cameras'); + +module.exports = CameraManager; diff --git a/src/cameras/2d/effects/Fade.js b/src/cameras/2d/effects/Fade.js index 408258e18..b9969ae73 100644 --- a/src/cameras/2d/effects/Fade.js +++ b/src/cameras/2d/effects/Fade.js @@ -1,382 +1,382 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../../math/Clamp'); -var Class = require('../../../utils/Class'); -var Events = require('../events'); - -/** - * @classdesc - * A Camera Fade effect. - * - * This effect will fade the camera viewport to the given color, over the duration specified. - * - * Only the camera viewport is faded. None of the objects it is displaying are impacted, i.e. their colors 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 Fade - * @memberof Phaser.Cameras.Scene2D.Effects - * @constructor - * @since 3.5.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. - */ -var Fade = new Class({ - - initialize: - - function Fade (camera) - { - /** - * The Camera this effect belongs to. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @readonly - * @since 3.5.0 - */ - this.camera = camera; - - /** - * Is this effect actively running? - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#isRunning - * @type {boolean} - * @readonly - * @default false - * @since 3.5.0 - */ - this.isRunning = false; - - /** - * Has this effect finished running? - * - * This is different from `isRunning` because it remains set to `true` when the effect is over, - * until the effect is either reset or started again. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#isComplete - * @type {boolean} - * @readonly - * @default false - * @since 3.5.0 - */ - this.isComplete = false; - - /** - * The direction of the fade. - * `true` = fade out (transparent to color), `false` = fade in (color to transparent) - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#direction - * @type {boolean} - * @readonly - * @since 3.5.0 - */ - this.direction = true; - - /** - * The duration of the effect, in milliseconds. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#duration - * @type {integer} - * @readonly - * @default 0 - * @since 3.5.0 - */ - this.duration = 0; - - /** - * The value of the red color channel the camera will use for the fade effect. - * A value between 0 and 255. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#red - * @type {integer} - * @private - * @since 3.5.0 - */ - this.red = 0; - - /** - * The value of the green color channel the camera will use for the fade effect. - * A value between 0 and 255. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#green - * @type {integer} - * @private - * @since 3.5.0 - */ - this.green = 0; - - /** - * The value of the blue color channel the camera will use for the fade effect. - * A value between 0 and 255. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#blue - * @type {integer} - * @private - * @since 3.5.0 - */ - this.blue = 0; - - /** - * The value of the alpha channel used during the fade effect. - * A value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#alpha - * @type {number} - * @private - * @since 3.5.0 - */ - this.alpha = 0; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#progress - * @type {number} - * @since 3.5.0 - */ - this.progress = 0; - - /** - * Effect elapsed timer. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#_elapsed - * @type {number} - * @private - * @since 3.5.0 - */ - this._elapsed = 0; - - /** - * This callback is invoked every frame for the duration of the effect. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#_onUpdate - * @type {?Phaser.Types.Cameras.Scene2D.CameraFadeCallback} - * @private - * @default null - * @since 3.5.0 - */ - this._onUpdate; - - /** - * On Complete callback scope. - * - * @name Phaser.Cameras.Scene2D.Effects.Fade#_onUpdateScope - * @type {any} - * @private - * @since 3.5.0 - */ - this._onUpdateScope; - }, - - /** - * Fades the Camera to or from the given color over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#start - * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START - * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START - * @since 3.5.0 - * - * @param {boolean} [direction=true] - The direction of the fade. `true` = fade out (transparent to color), `false` = fade in (color to transparent) - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraFadeCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. - */ - start: function (direction, duration, red, green, blue, force, callback, context) - { - if (direction === undefined) { direction = true; } - if (duration === undefined) { duration = 1000; } - if (red === undefined) { red = 0; } - if (green === undefined) { green = 0; } - if (blue === undefined) { blue = 0; } - if (force === undefined) { force = false; } - if (callback === undefined) { callback = null; } - if (context === undefined) { context = this.camera.scene; } - - if (!force && this.isRunning) - { - return this.camera; - } - - this.isRunning = true; - this.isComplete = false; - this.duration = duration; - this.direction = direction; - this.progress = 0; - - this.red = red; - this.green = green; - this.blue = blue; - this.alpha = (direction) ? Number.MIN_VALUE : 1; - - this._elapsed = 0; - - this._onUpdate = callback; - this._onUpdateScope = context; - - var eventName = (direction) ? Events.FADE_OUT_START : Events.FADE_IN_START; - - this.camera.emit(eventName, this.camera, this, duration, red, green, blue); - - return this.camera; - }, - - /** - * The main update loop for this effect. Called automatically by the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#update - * @since 3.5.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - if (!this.isRunning) - { - return; - } - - this._elapsed += delta; - - this.progress = Clamp(this._elapsed / this.duration, 0, 1); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); - } - - if (this._elapsed < this.duration) - { - this.alpha = (this.direction) ? this.progress : 1 - this.progress; - } - else - { - this.alpha = (this.direction) ? 1 : 0; - this.effectComplete(); - } - }, - - /** - * Called internally by the Canvas Renderer. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#postRenderCanvas - * @since 3.5.0 - * - * @param {CanvasRenderingContext2D} ctx - The Canvas context to render to. - * - * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. - */ - postRenderCanvas: function (ctx) - { - if (!this.isRunning && !this.isComplete) - { - return false; - } - - var camera = this.camera; - - ctx.fillStyle = 'rgba(' + this.red + ',' + this.green + ',' + this.blue + ',' + this.alpha + ')'; - ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); - - return true; - }, - - /** - * Called internally by the WebGL Renderer. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#postRenderWebGL - * @since 3.5.0 - * - * @param {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} pipeline - The WebGL Pipeline to render to. - * @param {function} getTintFunction - A function that will return the gl safe tint colors. - * - * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. - */ - postRenderWebGL: function (pipeline, getTintFunction) - { - if (!this.isRunning && !this.isComplete) - { - return false; - } - - var camera = this.camera; - var red = this.red / 255; - var blue = this.blue / 255; - var green = this.green / 255; - - pipeline.drawFillRect( - camera._cx, camera._cy, camera._cw, camera._ch, - getTintFunction(red, green, blue, 1), - this.alpha - ); - - return true; - }, - - /** - * Called internally when the effect completes. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#effectComplete - * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE - * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE - * @since 3.5.0 - */ - effectComplete: function () - { - this._onUpdate = null; - this._onUpdateScope = null; - - this.isRunning = false; - this.isComplete = true; - - var eventName = (this.direction) ? Events.FADE_OUT_COMPLETE : Events.FADE_IN_COMPLETE; - - this.camera.emit(eventName, this.camera, this); - }, - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#reset - * @since 3.5.0 - */ - reset: function () - { - this.isRunning = false; - this.isComplete = false; - - this._onUpdate = null; - this._onUpdateScope = null; - }, - - /** - * Destroys this effect, releasing it from the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Fade#destroy - * @since 3.5.0 - */ - destroy: function () - { - this.reset(); - - this.camera = null; - } - -}); - -module.exports = Fade; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../../math/Clamp'); +var Class = require('../../../utils/Class'); +var Events = require('../events'); + +/** + * @classdesc + * A Camera Fade effect. + * + * This effect will fade the camera viewport to the given color, over the duration specified. + * + * Only the camera viewport is faded. None of the objects it is displaying are impacted, i.e. their colors 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 Fade + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.5.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Fade = new Class({ + + initialize: + + function Fade (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.5.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isRunning = false; + + /** + * Has this effect finished running? + * + * This is different from `isRunning` because it remains set to `true` when the effect is over, + * until the effect is either reset or started again. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#isComplete + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isComplete = false; + + /** + * The direction of the fade. + * `true` = fade out (transparent to color), `false` = fade in (color to transparent) + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#direction + * @type {boolean} + * @readonly + * @since 3.5.0 + */ + this.direction = true; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.5.0 + */ + this.duration = 0; + + /** + * The value of the red color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#red + * @type {integer} + * @private + * @since 3.5.0 + */ + this.red = 0; + + /** + * The value of the green color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#green + * @type {integer} + * @private + * @since 3.5.0 + */ + this.green = 0; + + /** + * The value of the blue color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#blue + * @type {integer} + * @private + * @since 3.5.0 + */ + this.blue = 0; + + /** + * The value of the alpha channel used during the fade effect. + * A value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#alpha + * @type {number} + * @private + * @since 3.5.0 + */ + this.alpha = 0; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#progress + * @type {number} + * @since 3.5.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#_elapsed + * @type {number} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraFadeCallback} + * @private + * @default null + * @since 3.5.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Fade#_onUpdateScope + * @type {any} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + }, + + /** + * Fades the Camera to or from the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#start + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @since 3.5.0 + * + * @param {boolean} [direction=true] - The direction of the fade. `true` = fade out (transparent to color), `false` = fade in (color to transparent) + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {integer} [red=0] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=0] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=0] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraFadeCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (direction, duration, red, green, blue, force, callback, context) + { + if (direction === undefined) { direction = true; } + if (duration === undefined) { duration = 1000; } + if (red === undefined) { red = 0; } + if (green === undefined) { green = 0; } + if (blue === undefined) { blue = 0; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + if (!force && this.isRunning) + { + return this.camera; + } + + this.isRunning = true; + this.isComplete = false; + this.duration = duration; + this.direction = direction; + this.progress = 0; + + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = (direction) ? Number.MIN_VALUE : 1; + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + var eventName = (direction) ? Events.FADE_OUT_START : Events.FADE_IN_START; + + this.camera.emit(eventName, this.camera, this, duration, red, green, blue); + + return this.camera; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#update + * @since 3.5.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); + } + + if (this._elapsed < this.duration) + { + this.alpha = (this.direction) ? this.progress : 1 - this.progress; + } + else + { + this.alpha = (this.direction) ? 1 : 0; + this.effectComplete(); + } + }, + + /** + * Called internally by the Canvas Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#postRenderCanvas + * @since 3.5.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas context to render to. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderCanvas: function (ctx) + { + if (!this.isRunning && !this.isComplete) + { + return false; + } + + var camera = this.camera; + + ctx.fillStyle = 'rgba(' + this.red + ',' + this.green + ',' + this.blue + ',' + this.alpha + ')'; + ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); + + return true; + }, + + /** + * Called internally by the WebGL Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#postRenderWebGL + * @since 3.5.0 + * + * @param {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} pipeline - The WebGL Pipeline to render to. + * @param {function} getTintFunction - A function that will return the gl safe tint colors. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderWebGL: function (pipeline, getTintFunction) + { + if (!this.isRunning && !this.isComplete) + { + return false; + } + + var camera = this.camera; + var red = this.red / 255; + var blue = this.blue / 255; + var green = this.green / 255; + + pipeline.drawFillRect( + camera._cx, camera._cy, camera._cw, camera._ch, + getTintFunction(red, green, blue, 1), + this.alpha + ); + + return true; + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @fires Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.5.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + this.isComplete = true; + + var eventName = (this.direction) ? Events.FADE_OUT_COMPLETE : Events.FADE_IN_COMPLETE; + + this.camera.emit(eventName, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#reset + * @since 3.5.0 + */ + reset: function () + { + this.isRunning = false; + this.isComplete = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Fade#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + } + +}); + +module.exports = Fade; diff --git a/src/cameras/2d/effects/Flash.js b/src/cameras/2d/effects/Flash.js index 409573547..f665c168c 100644 --- a/src/cameras/2d/effects/Flash.js +++ b/src/cameras/2d/effects/Flash.js @@ -1,345 +1,345 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../../math/Clamp'); -var Class = require('../../../utils/Class'); -var Events = require('../events'); - -/** - * @classdesc - * A Camera Flash effect. - * - * This effect will flash the camera viewport to the given color, over the duration specified. - * - * Only the camera viewport is flashed. None of the objects it is displaying are impacted, i.e. their colors 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 Flash - * @memberof Phaser.Cameras.Scene2D.Effects - * @constructor - * @since 3.5.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. - */ -var Flash = new Class({ - - initialize: - - function Flash (camera) - { - /** - * The Camera this effect belongs to. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @readonly - * @since 3.5.0 - */ - this.camera = camera; - - /** - * Is this effect actively running? - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#isRunning - * @type {boolean} - * @readonly - * @default false - * @since 3.5.0 - */ - this.isRunning = false; - - /** - * The duration of the effect, in milliseconds. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#duration - * @type {integer} - * @readonly - * @default 0 - * @since 3.5.0 - */ - this.duration = 0; - - /** - * The value of the red color channel the camera will use for the fade effect. - * A value between 0 and 255. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#red - * @type {integer} - * @private - * @since 3.5.0 - */ - this.red = 0; - - /** - * The value of the green color channel the camera will use for the fade effect. - * A value between 0 and 255. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#green - * @type {integer} - * @private - * @since 3.5.0 - */ - this.green = 0; - - /** - * The value of the blue color channel the camera will use for the fade effect. - * A value between 0 and 255. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#blue - * @type {integer} - * @private - * @since 3.5.0 - */ - this.blue = 0; - - /** - * The value of the alpha channel used during the fade effect. - * A value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#alpha - * @type {number} - * @private - * @since 3.5.0 - */ - this.alpha = 0; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#progress - * @type {number} - * @since 3.5.0 - */ - this.progress = 0; - - /** - * Effect elapsed timer. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#_elapsed - * @type {number} - * @private - * @since 3.5.0 - */ - this._elapsed = 0; - - /** - * This callback is invoked every frame for the duration of the effect. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#_onUpdate - * @type {?Phaser.Types.Cameras.Scene2D.CameraFlashCallback} - * @private - * @default null - * @since 3.5.0 - */ - this._onUpdate; - - /** - * On Complete callback scope. - * - * @name Phaser.Cameras.Scene2D.Effects.Flash#_onUpdateScope - * @type {any} - * @private - * @since 3.5.0 - */ - this._onUpdateScope; - }, - - /** - * Flashes the Camera to or from the given color over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#start - * @fires Phaser.Cameras.Scene2D.Events#FLASH_START - * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE - * @since 3.5.0 - * - * @param {integer} [duration=250] - The duration of the effect in milliseconds. - * @param {integer} [red=255] - The amount to fade the red channel towards. A value between 0 and 255. - * @param {integer} [green=255] - The amount to fade the green channel towards. A value between 0 and 255. - * @param {integer} [blue=255] - The amount to fade the blue channel towards. A value between 0 and 255. - * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraFlashCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. - */ - start: function (duration, red, green, blue, force, callback, context) - { - if (duration === undefined) { duration = 250; } - if (red === undefined) { red = 255; } - if (green === undefined) { green = 255; } - if (blue === undefined) { blue = 255; } - if (force === undefined) { force = false; } - if (callback === undefined) { callback = null; } - if (context === undefined) { context = this.camera.scene; } - - if (!force && this.isRunning) - { - return this.camera; - } - - this.isRunning = true; - this.duration = duration; - this.progress = 0; - - this.red = red; - this.green = green; - this.blue = blue; - this.alpha = 1; - - this._elapsed = 0; - - this._onUpdate = callback; - this._onUpdateScope = context; - - this.camera.emit(Events.FLASH_START, this.camera, this, duration, red, green, blue); - - return this.camera; - }, - - /** - * The main update loop for this effect. Called automatically by the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#update - * @since 3.5.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - if (!this.isRunning) - { - return; - } - - this._elapsed += delta; - - this.progress = Clamp(this._elapsed / this.duration, 0, 1); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); - } - - if (this._elapsed < this.duration) - { - this.alpha = 1 - this.progress; - } - else - { - this.effectComplete(); - } - }, - - /** - * Called internally by the Canvas Renderer. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#postRenderCanvas - * @since 3.5.0 - * - * @param {CanvasRenderingContext2D} ctx - The Canvas context to render to. - * - * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. - */ - postRenderCanvas: function (ctx) - { - if (!this.isRunning) - { - return false; - } - - var camera = this.camera; - - ctx.fillStyle = 'rgba(' + this.red + ',' + this.green + ',' + this.blue + ',' + this.alpha + ')'; - ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); - - return true; - }, - - /** - * Called internally by the WebGL Renderer. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#postRenderWebGL - * @since 3.5.0 - * - * @param {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} pipeline - The WebGL Pipeline to render to. - * @param {function} getTintFunction - A function that will return the gl safe tint colors. - * - * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. - */ - postRenderWebGL: function (pipeline, getTintFunction) - { - if (!this.isRunning) - { - return false; - } - - var camera = this.camera; - var red = this.red / 255; - var blue = this.blue / 255; - var green = this.green / 255; - - pipeline.drawFillRect( - camera._cx, camera._cy, camera._cw, camera._ch, - getTintFunction(red, green, blue, 1), - this.alpha - ); - - return true; - }, - - /** - * Called internally when the effect completes. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#effectComplete - * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE - * @since 3.5.0 - */ - effectComplete: function () - { - this._onUpdate = null; - this._onUpdateScope = null; - - this.isRunning = false; - - this.camera.emit(Events.FLASH_COMPLETE, this.camera, this); - }, - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#reset - * @since 3.5.0 - */ - reset: function () - { - this.isRunning = false; - - this._onUpdate = null; - this._onUpdateScope = null; - }, - - /** - * Destroys this effect, releasing it from the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Flash#destroy - * @since 3.5.0 - */ - destroy: function () - { - this.reset(); - - this.camera = null; - } - -}); - -module.exports = Flash; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../../math/Clamp'); +var Class = require('../../../utils/Class'); +var Events = require('../events'); + +/** + * @classdesc + * A Camera Flash effect. + * + * This effect will flash the camera viewport to the given color, over the duration specified. + * + * Only the camera viewport is flashed. None of the objects it is displaying are impacted, i.e. their colors 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 Flash + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.5.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Flash = new Class({ + + initialize: + + function Flash (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.5.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.5.0 + */ + this.duration = 0; + + /** + * The value of the red color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#red + * @type {integer} + * @private + * @since 3.5.0 + */ + this.red = 0; + + /** + * The value of the green color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#green + * @type {integer} + * @private + * @since 3.5.0 + */ + this.green = 0; + + /** + * The value of the blue color channel the camera will use for the fade effect. + * A value between 0 and 255. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#blue + * @type {integer} + * @private + * @since 3.5.0 + */ + this.blue = 0; + + /** + * The value of the alpha channel used during the fade effect. + * A value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#alpha + * @type {number} + * @private + * @since 3.5.0 + */ + this.alpha = 0; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#progress + * @type {number} + * @since 3.5.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#_elapsed + * @type {number} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraFlashCallback} + * @private + * @default null + * @since 3.5.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Flash#_onUpdateScope + * @type {any} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + }, + + /** + * Flashes the Camera to or from the given color over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#start + * @fires Phaser.Cameras.Scene2D.Events#FLASH_START + * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.5.0 + * + * @param {integer} [duration=250] - The duration of the effect in milliseconds. + * @param {integer} [red=255] - The amount to fade the red channel towards. A value between 0 and 255. + * @param {integer} [green=255] - The amount to fade the green channel towards. A value between 0 and 255. + * @param {integer} [blue=255] - The amount to fade the blue channel towards. A value between 0 and 255. + * @param {boolean} [force=false] - Force the effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraFlashCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (duration, red, green, blue, force, callback, context) + { + if (duration === undefined) { duration = 250; } + if (red === undefined) { red = 255; } + if (green === undefined) { green = 255; } + if (blue === undefined) { blue = 255; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + if (!force && this.isRunning) + { + return this.camera; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = 1; + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.FLASH_START, this.camera, this, duration, red, green, blue); + + return this.camera; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#update + * @since 3.5.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); + } + + if (this._elapsed < this.duration) + { + this.alpha = 1 - this.progress; + } + else + { + this.effectComplete(); + } + }, + + /** + * Called internally by the Canvas Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#postRenderCanvas + * @since 3.5.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas context to render to. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderCanvas: function (ctx) + { + if (!this.isRunning) + { + return false; + } + + var camera = this.camera; + + ctx.fillStyle = 'rgba(' + this.red + ',' + this.green + ',' + this.blue + ',' + this.alpha + ')'; + ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); + + return true; + }, + + /** + * Called internally by the WebGL Renderer. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#postRenderWebGL + * @since 3.5.0 + * + * @param {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} pipeline - The WebGL Pipeline to render to. + * @param {function} getTintFunction - A function that will return the gl safe tint colors. + * + * @return {boolean} `true` if the effect drew to the renderer, otherwise `false`. + */ + postRenderWebGL: function (pipeline, getTintFunction) + { + if (!this.isRunning) + { + return false; + } + + var camera = this.camera; + var red = this.red / 255; + var blue = this.blue / 255; + var green = this.green / 255; + + pipeline.drawFillRect( + camera._cx, camera._cy, camera._cw, camera._ch, + getTintFunction(red, green, blue, 1), + this.alpha + ); + + return true; + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.5.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.FLASH_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#reset + * @since 3.5.0 + */ + reset: function () + { + this.isRunning = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Flash#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + } + +}); + +module.exports = Flash; diff --git a/src/cameras/2d/effects/Pan.js b/src/cameras/2d/effects/Pan.js index 9868c4830..aeac1aa44 100644 --- a/src/cameras/2d/effects/Pan.js +++ b/src/cameras/2d/effects/Pan.js @@ -1,319 +1,319 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../../math/Clamp'); -var Class = require('../../../utils/Class'); -var EaseMap = require('../../../math/easing/EaseMap'); -var Events = require('../events'); -var Vector2 = require('../../../math/Vector2'); - -/** - * @classdesc - * A Camera Pan effect. - * - * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, - * over the duration and with the ease specified. - * - * Only the camera scroll is moved. 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 Pan - * @memberof Phaser.Cameras.Scene2D.Effects - * @constructor - * @since 3.11.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. - */ -var Pan = new Class({ - - initialize: - - function Pan (camera) - { - /** - * The Camera this effect belongs to. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @readonly - * @since 3.11.0 - */ - this.camera = camera; - - /** - * Is this effect actively running? - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#isRunning - * @type {boolean} - * @readonly - * @default false - * @since 3.11.0 - */ - this.isRunning = false; - - /** - * The duration of the effect, in milliseconds. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#duration - * @type {integer} - * @readonly - * @default 0 - * @since 3.11.0 - */ - this.duration = 0; - - /** - * The starting scroll coordinates to pan the camera from. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#source - * @type {Phaser.Math.Vector2} - * @since 3.11.0 - */ - this.source = new Vector2(); - - /** - * The constantly updated value based on zoom. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#current - * @type {Phaser.Math.Vector2} - * @since 3.11.0 - */ - this.current = new Vector2(); - - /** - * The destination scroll coordinates to pan the camera to. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#destination - * @type {Phaser.Math.Vector2} - * @since 3.11.0 - */ - this.destination = new Vector2(); - - /** - * The ease function to use during the pan. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#ease - * @type {function} - * @since 3.11.0 - */ - this.ease; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#progress - * @type {number} - * @since 3.11.0 - */ - this.progress = 0; - - /** - * Effect elapsed timer. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#_elapsed - * @type {number} - * @private - * @since 3.11.0 - */ - this._elapsed = 0; - - /** - * This callback is invoked every frame for the duration of the effect. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#_onUpdate - * @type {?Phaser.Types.Cameras.Scene2D.CameraPanCallback} - * @private - * @default null - * @since 3.11.0 - */ - this._onUpdate; - - /** - * On Complete callback scope. - * - * @name Phaser.Cameras.Scene2D.Effects.Pan#_onUpdateScope - * @type {any} - * @private - * @since 3.11.0 - */ - this._onUpdateScope; - }, - - /** - * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, - * over the duration and with the ease specified. - * - * @method Phaser.Cameras.Scene2D.Effects.Pan#start - * @fires Phaser.Cameras.Scene2D.Events#PAN_START - * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE - * @since 3.11.0 - * - * @param {number} x - The destination x coordinate to scroll the center of the Camera viewport to. - * @param {number} y - The destination y coordinate to scroll the center of the Camera viewport to. - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. - * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * the current camera scroll x coordinate and the current camera scroll y coordinate. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. - */ - start: function (x, y, duration, ease, force, callback, context) - { - if (duration === undefined) { duration = 1000; } - if (ease === undefined) { ease = EaseMap.Linear; } - if (force === undefined) { force = false; } - if (callback === undefined) { callback = null; } - if (context === undefined) { context = this.camera.scene; } - - var cam = this.camera; - - if (!force && this.isRunning) - { - return cam; - } - - this.isRunning = true; - this.duration = duration; - this.progress = 0; - - // Starting from - this.source.set(cam.scrollX, cam.scrollY); - - // Destination - this.destination.set(x, y); - - // Zoom factored version - cam.getScroll(x, y, this.current); - - // Using this ease - if (typeof ease === 'string' && EaseMap.hasOwnProperty(ease)) - { - this.ease = EaseMap[ease]; - } - else if (typeof ease === 'function') - { - this.ease = ease; - } - - this._elapsed = 0; - - this._onUpdate = callback; - this._onUpdateScope = context; - - this.camera.emit(Events.PAN_START, this.camera, this, duration, x, y); - - return cam; - }, - - /** - * The main update loop for this effect. Called automatically by the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Pan#update - * @since 3.11.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - if (!this.isRunning) - { - return; - } - - this._elapsed += delta; - - var progress = Clamp(this._elapsed / this.duration, 0, 1); - - this.progress = progress; - - var cam = this.camera; - - if (this._elapsed < this.duration) - { - var v = this.ease(progress); - - cam.getScroll(this.destination.x, this.destination.y, this.current); - - var x = this.source.x + ((this.current.x - this.source.x) * v); - var y = this.source.y + ((this.current.y - this.source.y) * v); - - cam.setScroll(x, y); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, cam, progress, x, y); - } - } - else - { - cam.centerOn(this.destination.x, this.destination.y); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, cam, progress, cam.scrollX, cam.scrollY); - } - - this.effectComplete(); - } - }, - - /** - * Called internally when the effect completes. - * - * @method Phaser.Cameras.Scene2D.Effects.Pan#effectComplete - * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE - * @since 3.11.0 - */ - effectComplete: function () - { - this._onUpdate = null; - this._onUpdateScope = null; - - this.isRunning = false; - - this.camera.emit(Events.PAN_COMPLETE, this.camera, this); - }, - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - * - * @method Phaser.Cameras.Scene2D.Effects.Pan#reset - * @since 3.11.0 - */ - reset: function () - { - this.isRunning = false; - - this._onUpdate = null; - this._onUpdateScope = null; - }, - - /** - * Destroys this effect, releasing it from the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Pan#destroy - * @since 3.11.0 - */ - destroy: function () - { - this.reset(); - - this.camera = null; - this.source = null; - this.destination = null; - } - -}); - -module.exports = Pan; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../../math/Clamp'); +var Class = require('../../../utils/Class'); +var EaseMap = require('../../../math/easing/EaseMap'); +var Events = require('../events'); +var Vector2 = require('../../../math/Vector2'); + +/** + * @classdesc + * A Camera Pan effect. + * + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * Only the camera scroll is moved. 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 Pan + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.11.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Pan = new Class({ + + initialize: + + function Pan (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.11.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.11.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.11.0 + */ + this.duration = 0; + + /** + * The starting scroll coordinates to pan the camera from. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#source + * @type {Phaser.Math.Vector2} + * @since 3.11.0 + */ + this.source = new Vector2(); + + /** + * The constantly updated value based on zoom. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#current + * @type {Phaser.Math.Vector2} + * @since 3.11.0 + */ + this.current = new Vector2(); + + /** + * The destination scroll coordinates to pan the camera to. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#destination + * @type {Phaser.Math.Vector2} + * @since 3.11.0 + */ + this.destination = new Vector2(); + + /** + * The ease function to use during the pan. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#ease + * @type {function} + * @since 3.11.0 + */ + this.ease; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#progress + * @type {number} + * @since 3.11.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#_elapsed + * @type {number} + * @private + * @since 3.11.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraPanCallback} + * @private + * @default null + * @since 3.11.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Pan#_onUpdateScope + * @type {any} + * @private + * @since 3.11.0 + */ + this._onUpdateScope; + }, + + /** + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#start + * @fires Phaser.Cameras.Scene2D.Events#PAN_START + * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.11.0 + * + * @param {number} x - The destination x coordinate to scroll the center of the Camera viewport to. + * @param {number} y - The destination y coordinate to scroll the center of the Camera viewport to. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the pan effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraPanCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (x, y, duration, ease, force, callback, context) + { + if (duration === undefined) { duration = 1000; } + if (ease === undefined) { ease = EaseMap.Linear; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + var cam = this.camera; + + if (!force && this.isRunning) + { + return cam; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + // Starting from + this.source.set(cam.scrollX, cam.scrollY); + + // Destination + this.destination.set(x, y); + + // Zoom factored version + cam.getScroll(x, y, this.current); + + // Using this ease + if (typeof ease === 'string' && EaseMap.hasOwnProperty(ease)) + { + this.ease = EaseMap[ease]; + } + else if (typeof ease === 'function') + { + this.ease = ease; + } + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.PAN_START, this.camera, this, duration, x, y); + + return cam; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#update + * @since 3.11.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + var progress = Clamp(this._elapsed / this.duration, 0, 1); + + this.progress = progress; + + var cam = this.camera; + + if (this._elapsed < this.duration) + { + var v = this.ease(progress); + + cam.getScroll(this.destination.x, this.destination.y, this.current); + + var x = this.source.x + ((this.current.x - this.source.x) * v); + var y = this.source.y + ((this.current.y - this.source.y) * v); + + cam.setScroll(x, y); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, cam, progress, x, y); + } + } + else + { + cam.centerOn(this.destination.x, this.destination.y); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, cam, progress, cam.scrollX, cam.scrollY); + } + + this.effectComplete(); + } + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.11.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.PAN_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#reset + * @since 3.11.0 + */ + reset: function () + { + this.isRunning = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Pan#destroy + * @since 3.11.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + this.source = null; + this.destination = null; + } + +}); + +module.exports = Pan; diff --git a/src/cameras/2d/effects/Shake.js b/src/cameras/2d/effects/Shake.js index e172de008..29d20f72e 100644 --- a/src/cameras/2d/effects/Shake.js +++ b/src/cameras/2d/effects/Shake.js @@ -1,313 +1,313 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../../math/Clamp'); -var Class = require('../../../utils/Class'); -var Events = require('../events'); -var Vector2 = require('../../../math/Vector2'); - -/** - * @classdesc - * A Camera Shake effect. - * - * This effect will shake the camera viewport by a random amount, bounded by the specified intensity, each frame. - * - * Only the camera viewport is moved. 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 Shake - * @memberof Phaser.Cameras.Scene2D.Effects - * @constructor - * @since 3.5.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. - */ -var Shake = new Class({ - - initialize: - - function Shake (camera) - { - /** - * The Camera this effect belongs to. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @readonly - * @since 3.5.0 - */ - this.camera = camera; - - /** - * Is this effect actively running? - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#isRunning - * @type {boolean} - * @readonly - * @default false - * @since 3.5.0 - */ - this.isRunning = false; - - /** - * The duration of the effect, in milliseconds. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#duration - * @type {integer} - * @readonly - * @default 0 - * @since 3.5.0 - */ - this.duration = 0; - - /** - * The intensity of the effect. Use small float values. The default when the effect starts is 0.05. - * This is a Vector2 object, allowing you to control the shake intensity independently across x and y. - * You can modify this value while the effect is active to create more varied shake effects. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#intensity - * @type {Phaser.Math.Vector2} - * @since 3.5.0 - */ - this.intensity = new Vector2(); - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#progress - * @type {number} - * @since 3.5.0 - */ - this.progress = 0; - - /** - * Effect elapsed timer. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#_elapsed - * @type {number} - * @private - * @since 3.5.0 - */ - this._elapsed = 0; - - /** - * How much to offset the camera by horizontally. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#_offsetX - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._offsetX = 0; - - /** - * How much to offset the camera by vertically. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#_offsetY - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._offsetY = 0; - - /** - * This callback is invoked every frame for the duration of the effect. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#_onUpdate - * @type {?Phaser.Types.Cameras.Scene2D.CameraShakeCallback} - * @private - * @default null - * @since 3.5.0 - */ - this._onUpdate; - - /** - * On Complete callback scope. - * - * @name Phaser.Cameras.Scene2D.Effects.Shake#_onUpdateScope - * @type {any} - * @private - * @since 3.5.0 - */ - this._onUpdateScope; - }, - - /** - * Shakes the Camera by the given intensity over the duration specified. - * - * @method Phaser.Cameras.Scene2D.Effects.Shake#start - * @fires Phaser.Cameras.Scene2D.Events#SHAKE_START - * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE - * @since 3.5.0 - * - * @param {integer} [duration=100] - The duration of the effect in milliseconds. - * @param {(number|Phaser.Math.Vector2)} [intensity=0.05] - The intensity of the shake. - * @param {boolean} [force=false] - Force the shake effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraShakeCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. - */ - start: function (duration, intensity, force, callback, context) - { - if (duration === undefined) { duration = 100; } - if (intensity === undefined) { intensity = 0.05; } - if (force === undefined) { force = false; } - if (callback === undefined) { callback = null; } - if (context === undefined) { context = this.camera.scene; } - - if (!force && this.isRunning) - { - return this.camera; - } - - this.isRunning = true; - this.duration = duration; - this.progress = 0; - - if (typeof intensity === 'number') - { - this.intensity.set(intensity); - } - else - { - this.intensity.set(intensity.x, intensity.y); - } - - this._elapsed = 0; - this._offsetX = 0; - this._offsetY = 0; - - this._onUpdate = callback; - this._onUpdateScope = context; - - this.camera.emit(Events.SHAKE_START, this.camera, this, duration, intensity); - - return this.camera; - }, - - /** - * The pre-render step for this effect. Called automatically by the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Shake#preRender - * @since 3.5.0 - */ - preRender: function () - { - if (this.isRunning) - { - this.camera.matrix.translate(this._offsetX, this._offsetY); - } - }, - - /** - * The main update loop for this effect. Called automatically by the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Shake#update - * @since 3.5.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - if (!this.isRunning) - { - return; - } - - this._elapsed += delta; - - this.progress = Clamp(this._elapsed / this.duration, 0, 1); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); - } - - if (this._elapsed < this.duration) - { - var intensity = this.intensity; - var width = this.camera._cw; - var height = this.camera._ch; - var zoom = this.camera.zoom; - - this._offsetX = (Math.random() * intensity.x * width * 2 - intensity.x * width) * zoom; - this._offsetY = (Math.random() * intensity.y * height * 2 - intensity.y * height) * zoom; - - if (this.camera.roundPixels) - { - this._offsetX = Math.round(this._offsetX); - this._offsetY = Math.round(this._offsetY); - } - } - else - { - this.effectComplete(); - } - }, - - /** - * Called internally when the effect completes. - * - * @method Phaser.Cameras.Scene2D.Effects.Shake#effectComplete - * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE - * @since 3.5.0 - */ - effectComplete: function () - { - this._offsetX = 0; - this._offsetY = 0; - - this._onUpdate = null; - this._onUpdateScope = null; - - this.isRunning = false; - - this.camera.emit(Events.SHAKE_COMPLETE, this.camera, this); - }, - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - * - * @method Phaser.Cameras.Scene2D.Effects.Shake#reset - * @since 3.5.0 - */ - reset: function () - { - this.isRunning = false; - - this._offsetX = 0; - this._offsetY = 0; - - this._onUpdate = null; - this._onUpdateScope = null; - }, - - /** - * Destroys this effect, releasing it from the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Shake#destroy - * @since 3.5.0 - */ - destroy: function () - { - this.reset(); - - this.camera = null; - this.intensity = null; - } - -}); - -module.exports = Shake; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../../math/Clamp'); +var Class = require('../../../utils/Class'); +var Events = require('../events'); +var Vector2 = require('../../../math/Vector2'); + +/** + * @classdesc + * A Camera Shake effect. + * + * This effect will shake the camera viewport by a random amount, bounded by the specified intensity, each frame. + * + * Only the camera viewport is moved. 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 Shake + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.5.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Shake = new Class({ + + initialize: + + function Shake (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.5.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.5.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.5.0 + */ + this.duration = 0; + + /** + * The intensity of the effect. Use small float values. The default when the effect starts is 0.05. + * This is a Vector2 object, allowing you to control the shake intensity independently across x and y. + * You can modify this value while the effect is active to create more varied shake effects. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#intensity + * @type {Phaser.Math.Vector2} + * @since 3.5.0 + */ + this.intensity = new Vector2(); + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#progress + * @type {number} + * @since 3.5.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_elapsed + * @type {number} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * How much to offset the camera by horizontally. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_offsetX + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._offsetX = 0; + + /** + * How much to offset the camera by vertically. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_offsetY + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._offsetY = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraShakeCallback} + * @private + * @default null + * @since 3.5.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Shake#_onUpdateScope + * @type {any} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + }, + + /** + * Shakes the Camera by the given intensity over the duration specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#start + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_START + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.5.0 + * + * @param {integer} [duration=100] - The duration of the effect in milliseconds. + * @param {(number|Phaser.Math.Vector2)} [intensity=0.05] - The intensity of the shake. + * @param {boolean} [force=false] - Force the shake effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraShakeCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (duration, intensity, force, callback, context) + { + if (duration === undefined) { duration = 100; } + if (intensity === undefined) { intensity = 0.05; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + if (!force && this.isRunning) + { + return this.camera; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + if (typeof intensity === 'number') + { + this.intensity.set(intensity); + } + else + { + this.intensity.set(intensity.x, intensity.y); + } + + this._elapsed = 0; + this._offsetX = 0; + this._offsetY = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.SHAKE_START, this.camera, this, duration, intensity); + + return this.camera; + }, + + /** + * The pre-render step for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#preRender + * @since 3.5.0 + */ + preRender: function () + { + if (this.isRunning) + { + this.camera.matrix.translate(this._offsetX, this._offsetY); + } + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#update + * @since 3.5.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress); + } + + if (this._elapsed < this.duration) + { + var intensity = this.intensity; + var width = this.camera._cw; + var height = this.camera._ch; + var zoom = this.camera.zoom; + + this._offsetX = (Math.random() * intensity.x * width * 2 - intensity.x * width) * zoom; + this._offsetY = (Math.random() * intensity.y * height * 2 - intensity.y * height) * zoom; + + if (this.camera.roundPixels) + { + this._offsetX = Math.round(this._offsetX); + this._offsetY = Math.round(this._offsetY); + } + } + else + { + this.effectComplete(); + } + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.5.0 + */ + effectComplete: function () + { + this._offsetX = 0; + this._offsetY = 0; + + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.SHAKE_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#reset + * @since 3.5.0 + */ + reset: function () + { + this.isRunning = false; + + this._offsetX = 0; + this._offsetY = 0; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Shake#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + this.intensity = null; + } + +}); + +module.exports = Shake; diff --git a/src/cameras/2d/effects/Zoom.js b/src/cameras/2d/effects/Zoom.js index 6d3888f0d..dc694655c 100644 --- a/src/cameras/2d/effects/Zoom.js +++ b/src/cameras/2d/effects/Zoom.js @@ -1,287 +1,287 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../../math/Clamp'); -var Class = require('../../../utils/Class'); -var EaseMap = require('../../../math/easing/EaseMap'); -var Events = require('../events'); - -/** - * @classdesc - * A Camera Zoom effect. - * - * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. - * - * 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 Zoom - * @memberof Phaser.Cameras.Scene2D.Effects - * @constructor - * @since 3.11.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. - */ -var Zoom = new Class({ - - initialize: - - function Zoom (camera) - { - /** - * The Camera this effect belongs to. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @readonly - * @since 3.11.0 - */ - this.camera = camera; - - /** - * Is this effect actively running? - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#isRunning - * @type {boolean} - * @readonly - * @default false - * @since 3.11.0 - */ - this.isRunning = false; - - /** - * The duration of the effect, in milliseconds. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#duration - * @type {integer} - * @readonly - * @default 0 - * @since 3.11.0 - */ - this.duration = 0; - - /** - * The starting zoom value; - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#source - * @type {number} - * @since 3.11.0 - */ - this.source = 1; - - /** - * The destination zoom value. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#destination - * @type {number} - * @since 3.11.0 - */ - this.destination = 1; - - /** - * The ease function to use during the zoom. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#ease - * @type {function} - * @since 3.11.0 - */ - this.ease; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#progress - * @type {number} - * @since 3.11.0 - */ - this.progress = 0; - - /** - * Effect elapsed timer. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#_elapsed - * @type {number} - * @private - * @since 3.11.0 - */ - this._elapsed = 0; - - /** - * This callback is invoked every frame for the duration of the effect. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#_onUpdate - * @type {?Phaser.Types.Cameras.Scene2D.CameraZoomCallback} - * @private - * @default null - * @since 3.11.0 - */ - this._onUpdate; - - /** - * On Complete callback scope. - * - * @name Phaser.Cameras.Scene2D.Effects.Zoom#_onUpdateScope - * @type {any} - * @private - * @since 3.11.0 - */ - this._onUpdateScope; - }, - - /** - * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. - * - * @method Phaser.Cameras.Scene2D.Effects.Zoom#start - * @fires Phaser.Cameras.Scene2D.Events#ZOOM_START - * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE - * @since 3.11.0 - * - * @param {number} zoom - The target Camera zoom value. - * @param {integer} [duration=1000] - The duration of the effect in milliseconds. - * @param {(string|function)} [ease='Linear'] - The ease to use for the Zoom. Can be any of the Phaser Easing constants or a custom function. - * @param {boolean} [force=false] - Force the zoom effect to start immediately, even if already running. - * @param {Phaser.Types.Cameras.Scene2D.CameraZoomCallback} [callback] - This callback will be invoked every frame for the duration of the effect. - * It is sent three arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * and the current camera zoom value. - * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - * - * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. - */ - start: function (zoom, duration, ease, force, callback, context) - { - if (duration === undefined) { duration = 1000; } - if (ease === undefined) { ease = EaseMap.Linear; } - if (force === undefined) { force = false; } - if (callback === undefined) { callback = null; } - if (context === undefined) { context = this.camera.scene; } - - var cam = this.camera; - - if (!force && this.isRunning) - { - return cam; - } - - this.isRunning = true; - this.duration = duration; - this.progress = 0; - - // Starting from - this.source = cam.zoom; - - // Zooming to - this.destination = zoom; - - // Using this ease - if (typeof ease === 'string' && EaseMap.hasOwnProperty(ease)) - { - this.ease = EaseMap[ease]; - } - else if (typeof ease === 'function') - { - this.ease = ease; - } - - this._elapsed = 0; - - this._onUpdate = callback; - this._onUpdateScope = context; - - this.camera.emit(Events.ZOOM_START, this.camera, this, duration, zoom); - - return cam; - }, - - /** - * The main update loop for this effect. Called automatically by the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Zoom#update - * @since 3.11.0 - * - * @param {integer} 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. - */ - update: function (time, delta) - { - if (!this.isRunning) - { - return; - } - - this._elapsed += delta; - - this.progress = Clamp(this._elapsed / this.duration, 0, 1); - - if (this._elapsed < this.duration) - { - this.camera.zoom = this.source + ((this.destination - this.source) * this.ease(this.progress)); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.camera.zoom); - } - } - else - { - this.camera.zoom = this.destination; - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.destination); - } - - this.effectComplete(); - } - }, - - /** - * Called internally when the effect completes. - * - * @method Phaser.Cameras.Scene2D.Effects.Zoom#effectComplete - * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE - * @since 3.11.0 - */ - effectComplete: function () - { - this._onUpdate = null; - this._onUpdateScope = null; - - this.isRunning = false; - - this.camera.emit(Events.ZOOM_COMPLETE, this.camera, this); - }, - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - * - * @method Phaser.Cameras.Scene2D.Effects.Zoom#reset - * @since 3.11.0 - */ - reset: function () - { - this.isRunning = false; - - this._onUpdate = null; - this._onUpdateScope = null; - }, - - /** - * Destroys this effect, releasing it from the Camera. - * - * @method Phaser.Cameras.Scene2D.Effects.Zoom#destroy - * @since 3.11.0 - */ - destroy: function () - { - this.reset(); - - this.camera = null; - } - -}); - -module.exports = Zoom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../../math/Clamp'); +var Class = require('../../../utils/Class'); +var EaseMap = require('../../../math/easing/EaseMap'); +var Events = require('../events'); + +/** + * @classdesc + * A Camera Zoom effect. + * + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * 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 Zoom + * @memberof Phaser.Cameras.Scene2D.Effects + * @constructor + * @since 3.11.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon. + */ +var Zoom = new Class({ + + initialize: + + function Zoom (camera) + { + /** + * The Camera this effect belongs to. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @readonly + * @since 3.11.0 + */ + this.camera = camera; + + /** + * Is this effect actively running? + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#isRunning + * @type {boolean} + * @readonly + * @default false + * @since 3.11.0 + */ + this.isRunning = false; + + /** + * The duration of the effect, in milliseconds. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#duration + * @type {integer} + * @readonly + * @default 0 + * @since 3.11.0 + */ + this.duration = 0; + + /** + * The starting zoom value; + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#source + * @type {number} + * @since 3.11.0 + */ + this.source = 1; + + /** + * The destination zoom value. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#destination + * @type {number} + * @since 3.11.0 + */ + this.destination = 1; + + /** + * The ease function to use during the zoom. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#ease + * @type {function} + * @since 3.11.0 + */ + this.ease; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#progress + * @type {number} + * @since 3.11.0 + */ + this.progress = 0; + + /** + * Effect elapsed timer. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#_elapsed + * @type {number} + * @private + * @since 3.11.0 + */ + this._elapsed = 0; + + /** + * This callback is invoked every frame for the duration of the effect. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#_onUpdate + * @type {?Phaser.Types.Cameras.Scene2D.CameraZoomCallback} + * @private + * @default null + * @since 3.11.0 + */ + this._onUpdate; + + /** + * On Complete callback scope. + * + * @name Phaser.Cameras.Scene2D.Effects.Zoom#_onUpdateScope + * @type {any} + * @private + * @since 3.11.0 + */ + this._onUpdateScope; + }, + + /** + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#start + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_START + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.11.0 + * + * @param {number} zoom - The target Camera zoom value. + * @param {integer} [duration=1000] - The duration of the effect in milliseconds. + * @param {(string|function)} [ease='Linear'] - The ease to use for the Zoom. Can be any of the Phaser Easing constants or a custom function. + * @param {boolean} [force=false] - Force the zoom effect to start immediately, even if already running. + * @param {Phaser.Types.Cameras.Scene2D.CameraZoomCallback} [callback] - This callback will be invoked every frame for the duration of the effect. + * It is sent three arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * and the current camera zoom value. + * @param {any} [context] - The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + * + * @return {Phaser.Cameras.Scene2D.Camera} The Camera on which the effect was started. + */ + start: function (zoom, duration, ease, force, callback, context) + { + if (duration === undefined) { duration = 1000; } + if (ease === undefined) { ease = EaseMap.Linear; } + if (force === undefined) { force = false; } + if (callback === undefined) { callback = null; } + if (context === undefined) { context = this.camera.scene; } + + var cam = this.camera; + + if (!force && this.isRunning) + { + return cam; + } + + this.isRunning = true; + this.duration = duration; + this.progress = 0; + + // Starting from + this.source = cam.zoom; + + // Zooming to + this.destination = zoom; + + // Using this ease + if (typeof ease === 'string' && EaseMap.hasOwnProperty(ease)) + { + this.ease = EaseMap[ease]; + } + else if (typeof ease === 'function') + { + this.ease = ease; + } + + this._elapsed = 0; + + this._onUpdate = callback; + this._onUpdateScope = context; + + this.camera.emit(Events.ZOOM_START, this.camera, this, duration, zoom); + + return cam; + }, + + /** + * The main update loop for this effect. Called automatically by the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#update + * @since 3.11.0 + * + * @param {integer} 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. + */ + update: function (time, delta) + { + if (!this.isRunning) + { + return; + } + + this._elapsed += delta; + + this.progress = Clamp(this._elapsed / this.duration, 0, 1); + + if (this._elapsed < this.duration) + { + this.camera.zoom = this.source + ((this.destination - this.source) * this.ease(this.progress)); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.camera.zoom); + } + } + else + { + this.camera.zoom = this.destination; + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.destination); + } + + this.effectComplete(); + } + }, + + /** + * Called internally when the effect completes. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#effectComplete + * @fires Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.11.0 + */ + effectComplete: function () + { + this._onUpdate = null; + this._onUpdateScope = null; + + this.isRunning = false; + + this.camera.emit(Events.ZOOM_COMPLETE, this.camera, this); + }, + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#reset + * @since 3.11.0 + */ + reset: function () + { + this.isRunning = false; + + this._onUpdate = null; + this._onUpdateScope = null; + }, + + /** + * Destroys this effect, releasing it from the Camera. + * + * @method Phaser.Cameras.Scene2D.Effects.Zoom#destroy + * @since 3.11.0 + */ + destroy: function () + { + this.reset(); + + this.camera = null; + } + +}); + +module.exports = Zoom; diff --git a/src/cameras/2d/effects/index.js b/src/cameras/2d/effects/index.js index 5aab10b1d..ee2bb3f43 100644 --- a/src/cameras/2d/effects/index.js +++ b/src/cameras/2d/effects/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cameras.Scene2D.Effects - */ - -module.exports = { - - Fade: require('./Fade'), - Flash: require('./Flash'), - Pan: require('./Pan'), - Shake: require('./Shake'), - Zoom: require('./Zoom') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Scene2D.Effects + */ + +module.exports = { + + Fade: require('./Fade'), + Flash: require('./Flash'), + Pan: require('./Pan'), + Shake: require('./Shake'), + Zoom: require('./Zoom') + +}; diff --git a/src/cameras/2d/events/DESTROY_EVENT.js b/src/cameras/2d/events/DESTROY_EVENT.js index 80175e07a..8cbaecc0a 100644 --- a/src/cameras/2d/events/DESTROY_EVENT.js +++ b/src/cameras/2d/events/DESTROY_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Destroy Camera Event. - * - * This event is dispatched by a Camera instance when it is destroyed by the Camera Manager. - * - * @event Phaser.Cameras.Scene2D.Events#DESTROY - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that was destroyed. - */ -module.exports = 'cameradestroy'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Destroy Camera Event. + * + * This event is dispatched by a Camera instance when it is destroyed by the Camera Manager. + * + * @event Phaser.Cameras.Scene2D.Events#DESTROY + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that was destroyed. + */ +module.exports = 'cameradestroy'; diff --git a/src/cameras/2d/events/FADE_IN_COMPLETE_EVENT.js b/src/cameras/2d/events/FADE_IN_COMPLETE_EVENT.js index 3ce221956..bd01f13c1 100644 --- a/src/cameras/2d/events/FADE_IN_COMPLETE_EVENT.js +++ b/src/cameras/2d/events/FADE_IN_COMPLETE_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Fade In Complete Event. - * - * This event is dispatched by a Camera instance when the Fade In Effect completes. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeincomplete', listener)`. - * - * @event Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. - */ -module.exports = 'camerafadeincomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade In Complete Event. + * + * This event is dispatched by a Camera instance when the Fade In Effect completes. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeincomplete', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_IN_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + */ +module.exports = 'camerafadeincomplete'; diff --git a/src/cameras/2d/events/FADE_IN_START_EVENT.js b/src/cameras/2d/events/FADE_IN_START_EVENT.js index fcf55f777..3a403c698 100644 --- a/src/cameras/2d/events/FADE_IN_START_EVENT.js +++ b/src/cameras/2d/events/FADE_IN_START_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Fade In Start Event. - * - * This event is dispatched by a Camera instance when the Fade In Effect starts. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeinstart', listener)`. - * - * @event Phaser.Cameras.Scene2D.Events#FADE_IN_START - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. - * @param {integer} duration - The duration of the effect. - * @param {integer} red - The red color channel value. - * @param {integer} green - The green color channel value. - * @param {integer} blue - The blue color channel value. - */ -module.exports = 'camerafadeinstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade In Start Event. + * + * This event is dispatched by a Camera instance when the Fade In Effect starts. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeinstart', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_IN_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {integer} red - The red color channel value. + * @param {integer} green - The green color channel value. + * @param {integer} blue - The blue color channel value. + */ +module.exports = 'camerafadeinstart'; diff --git a/src/cameras/2d/events/FADE_OUT_COMPLETE_EVENT.js b/src/cameras/2d/events/FADE_OUT_COMPLETE_EVENT.js index 1794376c8..f4ea6dfdf 100644 --- a/src/cameras/2d/events/FADE_OUT_COMPLETE_EVENT.js +++ b/src/cameras/2d/events/FADE_OUT_COMPLETE_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Fade Out Complete Event. - * - * This event is dispatched by a Camera instance when the Fade Out Effect completes. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeoutcomplete', listener)`. - * - * @event Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. - */ -module.exports = 'camerafadeoutcomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade Out Complete Event. + * + * This event is dispatched by a Camera instance when the Fade Out Effect completes. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeoutcomplete', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_OUT_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + */ +module.exports = 'camerafadeoutcomplete'; diff --git a/src/cameras/2d/events/FADE_OUT_START_EVENT.js b/src/cameras/2d/events/FADE_OUT_START_EVENT.js index 1804bf91b..77ab27082 100644 --- a/src/cameras/2d/events/FADE_OUT_START_EVENT.js +++ b/src/cameras/2d/events/FADE_OUT_START_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Fade Out Start Event. - * - * This event is dispatched by a Camera instance when the Fade Out Effect starts. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeoutstart', listener)`. - * - * @event Phaser.Cameras.Scene2D.Events#FADE_OUT_START - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. - * @param {integer} duration - The duration of the effect. - * @param {integer} red - The red color channel value. - * @param {integer} green - The green color channel value. - * @param {integer} blue - The blue color channel value. - */ -module.exports = 'camerafadeoutstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Fade Out Start Event. + * + * This event is dispatched by a Camera instance when the Fade Out Effect starts. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeoutstart', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#FADE_OUT_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Fade} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {integer} red - The red color channel value. + * @param {integer} green - The green color channel value. + * @param {integer} blue - The blue color channel value. + */ +module.exports = 'camerafadeoutstart'; diff --git a/src/cameras/2d/events/FLASH_COMPLETE_EVENT.js b/src/cameras/2d/events/FLASH_COMPLETE_EVENT.js index f4d6aaad3..d3541401e 100644 --- a/src/cameras/2d/events/FLASH_COMPLETE_EVENT.js +++ b/src/cameras/2d/events/FLASH_COMPLETE_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Flash Complete Event. - * - * This event is dispatched by a Camera instance when the Flash Effect completes. - * - * @event Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Flash} effect - A reference to the effect instance. - */ -module.exports = 'cameraflashcomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Flash Complete Event. + * + * This event is dispatched by a Camera instance when the Flash Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#FLASH_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Flash} effect - A reference to the effect instance. + */ +module.exports = 'cameraflashcomplete'; diff --git a/src/cameras/2d/events/FLASH_START_EVENT.js b/src/cameras/2d/events/FLASH_START_EVENT.js index 4934b7a03..5217021f2 100644 --- a/src/cameras/2d/events/FLASH_START_EVENT.js +++ b/src/cameras/2d/events/FLASH_START_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Flash Start Event. - * - * This event is dispatched by a Camera instance when the Flash Effect starts. - * - * @event Phaser.Cameras.Scene2D.Events#FLASH_START - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Flash} effect - A reference to the effect instance. - * @param {integer} duration - The duration of the effect. - * @param {integer} red - The red color channel value. - * @param {integer} green - The green color channel value. - * @param {integer} blue - The blue color channel value. - */ -module.exports = 'cameraflashstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Flash Start Event. + * + * This event is dispatched by a Camera instance when the Flash Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#FLASH_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Flash} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {integer} red - The red color channel value. + * @param {integer} green - The green color channel value. + * @param {integer} blue - The blue color channel value. + */ +module.exports = 'cameraflashstart'; diff --git a/src/cameras/2d/events/PAN_COMPLETE_EVENT.js b/src/cameras/2d/events/PAN_COMPLETE_EVENT.js index 7e65955fd..0f6a2b835 100644 --- a/src/cameras/2d/events/PAN_COMPLETE_EVENT.js +++ b/src/cameras/2d/events/PAN_COMPLETE_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Pan Complete Event. - * - * This event is dispatched by a Camera instance when the Pan Effect completes. - * - * @event Phaser.Cameras.Scene2D.Events#PAN_COMPLETE - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Pan} effect - A reference to the effect instance. - */ -module.exports = 'camerapancomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Pan Complete Event. + * + * This event is dispatched by a Camera instance when the Pan Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#PAN_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Pan} effect - A reference to the effect instance. + */ +module.exports = 'camerapancomplete'; diff --git a/src/cameras/2d/events/PAN_START_EVENT.js b/src/cameras/2d/events/PAN_START_EVENT.js index 60b71e691..a88666bc2 100644 --- a/src/cameras/2d/events/PAN_START_EVENT.js +++ b/src/cameras/2d/events/PAN_START_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Pan Start Event. - * - * This event is dispatched by a Camera instance when the Pan Effect starts. - * - * @event Phaser.Cameras.Scene2D.Events#PAN_START - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Pan} effect - A reference to the effect instance. - * @param {integer} duration - The duration of the effect. - * @param {number} x - The destination scroll x coordinate. - * @param {number} y - The destination scroll y coordinate. - */ -module.exports = 'camerapanstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Pan Start Event. + * + * This event is dispatched by a Camera instance when the Pan Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#PAN_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Pan} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {number} x - The destination scroll x coordinate. + * @param {number} y - The destination scroll y coordinate. + */ +module.exports = 'camerapanstart'; diff --git a/src/cameras/2d/events/POST_RENDER_EVENT.js b/src/cameras/2d/events/POST_RENDER_EVENT.js index 40fe8cb76..3ebe90ae9 100644 --- a/src/cameras/2d/events/POST_RENDER_EVENT.js +++ b/src/cameras/2d/events/POST_RENDER_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Post-Render Event. - * - * This event is dispatched by a Camera instance after is has finished rendering. - * It is only dispatched if the Camera is rendering to a texture. - * - * Listen to it from a Camera instance using: `camera.on('postrender', listener)`. - * - * @event Phaser.Cameras.Scene2D.Events#POST_RENDER - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that has finished rendering to a texture. - */ -module.exports = 'postrender'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Post-Render Event. + * + * This event is dispatched by a Camera instance after is has finished rendering. + * It is only dispatched if the Camera is rendering to a texture. + * + * Listen to it from a Camera instance using: `camera.on('postrender', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#POST_RENDER + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that has finished rendering to a texture. + */ +module.exports = 'postrender'; diff --git a/src/cameras/2d/events/PRE_RENDER_EVENT.js b/src/cameras/2d/events/PRE_RENDER_EVENT.js index 9e02ee873..d80b1172f 100644 --- a/src/cameras/2d/events/PRE_RENDER_EVENT.js +++ b/src/cameras/2d/events/PRE_RENDER_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Pre-Render Event. - * - * This event is dispatched by a Camera instance when it is about to render. - * It is only dispatched if the Camera is rendering to a texture. - * - * Listen to it from a Camera instance using: `camera.on('prerender', listener)`. - * - * @event Phaser.Cameras.Scene2D.Events#PRE_RENDER - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that is about to render to a texture. - */ -module.exports = 'prerender'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Pre-Render Event. + * + * This event is dispatched by a Camera instance when it is about to render. + * It is only dispatched if the Camera is rendering to a texture. + * + * Listen to it from a Camera instance using: `camera.on('prerender', listener)`. + * + * @event Phaser.Cameras.Scene2D.Events#PRE_RENDER + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.BaseCamera} camera - The camera that is about to render to a texture. + */ +module.exports = 'prerender'; diff --git a/src/cameras/2d/events/SHAKE_COMPLETE_EVENT.js b/src/cameras/2d/events/SHAKE_COMPLETE_EVENT.js index 188a9ed10..219d94189 100644 --- a/src/cameras/2d/events/SHAKE_COMPLETE_EVENT.js +++ b/src/cameras/2d/events/SHAKE_COMPLETE_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Shake Complete Event. - * - * This event is dispatched by a Camera instance when the Shake Effect completes. - * - * @event Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Shake} effect - A reference to the effect instance. - */ -module.exports = 'camerashakecomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Shake Complete Event. + * + * This event is dispatched by a Camera instance when the Shake Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#SHAKE_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Shake} effect - A reference to the effect instance. + */ +module.exports = 'camerashakecomplete'; diff --git a/src/cameras/2d/events/SHAKE_START_EVENT.js b/src/cameras/2d/events/SHAKE_START_EVENT.js index 08614f75f..a4af86817 100644 --- a/src/cameras/2d/events/SHAKE_START_EVENT.js +++ b/src/cameras/2d/events/SHAKE_START_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Shake Start Event. - * - * This event is dispatched by a Camera instance when the Shake Effect starts. - * - * @event Phaser.Cameras.Scene2D.Events#SHAKE_START - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Shake} effect - A reference to the effect instance. - * @param {integer} duration - The duration of the effect. - * @param {number} intensity - The intensity of the effect. - */ -module.exports = 'camerashakestart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Shake Start Event. + * + * This event is dispatched by a Camera instance when the Shake Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#SHAKE_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Shake} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {number} intensity - The intensity of the effect. + */ +module.exports = 'camerashakestart'; diff --git a/src/cameras/2d/events/ZOOM_COMPLETE_EVENT.js b/src/cameras/2d/events/ZOOM_COMPLETE_EVENT.js index 243936dc2..fb44a5af5 100644 --- a/src/cameras/2d/events/ZOOM_COMPLETE_EVENT.js +++ b/src/cameras/2d/events/ZOOM_COMPLETE_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Zoom Complete Event. - * - * This event is dispatched by a Camera instance when the Zoom Effect completes. - * - * @event Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance. - */ -module.exports = 'camerazoomcomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Zoom Complete Event. + * + * This event is dispatched by a Camera instance when the Zoom Effect completes. + * + * @event Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance. + */ +module.exports = 'camerazoomcomplete'; diff --git a/src/cameras/2d/events/ZOOM_START_EVENT.js b/src/cameras/2d/events/ZOOM_START_EVENT.js index 02cf9e0b3..27ad8a646 100644 --- a/src/cameras/2d/events/ZOOM_START_EVENT.js +++ b/src/cameras/2d/events/ZOOM_START_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Camera Zoom Start Event. - * - * This event is dispatched by a Camera instance when the Zoom Effect starts. - * - * @event Phaser.Cameras.Scene2D.Events#ZOOM_START - * @since 3.3.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. - * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance. - * @param {integer} duration - The duration of the effect. - * @param {number} zoom - The destination zoom value. - */ -module.exports = 'camerazoomstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Camera Zoom Start Event. + * + * This event is dispatched by a Camera instance when the Zoom Effect starts. + * + * @event Phaser.Cameras.Scene2D.Events#ZOOM_START + * @since 3.3.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on. + * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance. + * @param {integer} duration - The duration of the effect. + * @param {number} zoom - The destination zoom value. + */ +module.exports = 'camerazoomstart'; diff --git a/src/cameras/2d/events/index.js b/src/cameras/2d/events/index.js index a9aa5c4a4..343f8adbe 100644 --- a/src/cameras/2d/events/index.js +++ b/src/cameras/2d/events/index.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cameras.Scene2D.Events - */ - -module.exports = { - - DESTROY: require('./DESTROY_EVENT'), - FADE_IN_COMPLETE: require('./FADE_IN_COMPLETE_EVENT'), - FADE_IN_START: require('./FADE_IN_START_EVENT'), - FADE_OUT_COMPLETE: require('./FADE_OUT_COMPLETE_EVENT'), - FADE_OUT_START: require('./FADE_OUT_START_EVENT'), - FLASH_COMPLETE: require('./FLASH_COMPLETE_EVENT'), - FLASH_START: require('./FLASH_START_EVENT'), - PAN_COMPLETE: require('./PAN_COMPLETE_EVENT'), - PAN_START: require('./PAN_START_EVENT'), - POST_RENDER: require('./POST_RENDER_EVENT'), - PRE_RENDER: require('./PRE_RENDER_EVENT'), - SHAKE_COMPLETE: require('./SHAKE_COMPLETE_EVENT'), - SHAKE_START: require('./SHAKE_START_EVENT'), - ZOOM_COMPLETE: require('./ZOOM_COMPLETE_EVENT'), - ZOOM_START: require('./ZOOM_START_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Scene2D.Events + */ + +module.exports = { + + DESTROY: require('./DESTROY_EVENT'), + FADE_IN_COMPLETE: require('./FADE_IN_COMPLETE_EVENT'), + FADE_IN_START: require('./FADE_IN_START_EVENT'), + FADE_OUT_COMPLETE: require('./FADE_OUT_COMPLETE_EVENT'), + FADE_OUT_START: require('./FADE_OUT_START_EVENT'), + FLASH_COMPLETE: require('./FLASH_COMPLETE_EVENT'), + FLASH_START: require('./FLASH_START_EVENT'), + PAN_COMPLETE: require('./PAN_COMPLETE_EVENT'), + PAN_START: require('./PAN_START_EVENT'), + POST_RENDER: require('./POST_RENDER_EVENT'), + PRE_RENDER: require('./PRE_RENDER_EVENT'), + SHAKE_COMPLETE: require('./SHAKE_COMPLETE_EVENT'), + SHAKE_START: require('./SHAKE_START_EVENT'), + ZOOM_COMPLETE: require('./ZOOM_COMPLETE_EVENT'), + ZOOM_START: require('./ZOOM_START_EVENT') + +}; diff --git a/src/cameras/2d/index.js b/src/cameras/2d/index.js index 5ca74e54e..86de6473d 100644 --- a/src/cameras/2d/index.js +++ b/src/cameras/2d/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cameras.Scene2D - */ - -module.exports = { - - Camera: require('./Camera'), - BaseCamera: require('./BaseCamera'), - CameraManager: require('./CameraManager'), - Effects: require('./effects'), - Events: require('./events') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Scene2D + */ + +module.exports = { + + Camera: require('./Camera'), + BaseCamera: require('./BaseCamera'), + CameraManager: require('./CameraManager'), + Effects: require('./effects'), + Events: require('./events') + +}; diff --git a/src/cameras/2d/typedefs/index.js b/src/cameras/2d/typedefs/index.js index d5aa6d1b7..7c5daeb8e 100644 --- a/src/cameras/2d/typedefs/index.js +++ b/src/cameras/2d/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Cameras.Scene2D - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Cameras.Scene2D + */ diff --git a/src/cameras/controls/FixedKeyControl.js b/src/cameras/controls/FixedKeyControl.js index bac758e75..13dcf5d0e 100644 --- a/src/cameras/controls/FixedKeyControl.js +++ b/src/cameras/controls/FixedKeyControl.js @@ -1,300 +1,300 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetValue = require('../../utils/object/GetValue'); - -/** - * @classdesc - * A Fixed Key Camera Control. - * - * This allows you to control the movement and zoom of a camera using the defined keys. - * - * ```javascript - * var camControl = new FixedKeyControl({ - * camera: this.cameras.main, - * left: cursors.left, - * right: cursors.right, - * speed: float OR { x: 0, y: 0 } - * }); - * ``` - * - * Movement is precise and has no 'smoothing' applied to it. - * - * You must call the `update` method of this controller every frame. - * - * @class FixedKeyControl - * @memberof Phaser.Cameras.Controls - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.Cameras.Controls.FixedKeyControlConfig} config - The Fixed Key Control configuration object. - */ -var FixedKeyControl = new Class({ - - initialize: - - function FixedKeyControl (config) - { - /** - * The Camera that this Control will update. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#camera - * @type {?Phaser.Cameras.Scene2D.Camera} - * @default null - * @since 3.0.0 - */ - this.camera = GetValue(config, 'camera', null); - - /** - * The Key to be pressed that will move the Camera left. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#left - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.left = GetValue(config, 'left', null); - - /** - * The Key to be pressed that will move the Camera right. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#right - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.right = GetValue(config, 'right', null); - - /** - * The Key to be pressed that will move the Camera up. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#up - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.up = GetValue(config, 'up', null); - - /** - * The Key to be pressed that will move the Camera down. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#down - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.down = GetValue(config, 'down', null); - - /** - * The Key to be pressed that will zoom the Camera in. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#zoomIn - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.zoomIn = GetValue(config, 'zoomIn', null); - - /** - * The Key to be pressed that will zoom the Camera out. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#zoomOut - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.zoomOut = GetValue(config, 'zoomOut', null); - - /** - * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#zoomSpeed - * @type {number} - * @default 0.01 - * @since 3.0.0 - */ - this.zoomSpeed = GetValue(config, 'zoomSpeed', 0.01); - - /** - * The horizontal speed the camera will move. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#speedX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.speedX = 0; - - /** - * The vertical speed the camera will move. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#speedY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.speedY = 0; - - var speed = GetValue(config, 'speed', null); - - if (typeof speed === 'number') - { - this.speedX = speed; - this.speedY = speed; - } - else - { - this.speedX = GetValue(config, 'speed.x', 0); - this.speedY = GetValue(config, 'speed.y', 0); - } - - /** - * Internal property to track the current zoom level. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#_zoom - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._zoom = 0; - - /** - * A flag controlling if the Controls will update the Camera or not. - * - * @name Phaser.Cameras.Controls.FixedKeyControl#active - * @type {boolean} - * @since 3.0.0 - */ - this.active = (this.camera !== null); - }, - - /** - * Starts the Key Control running, providing it has been linked to a camera. - * - * @method Phaser.Cameras.Controls.FixedKeyControl#start - * @since 3.0.0 - * - * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. - */ - start: function () - { - this.active = (this.camera !== null); - - return this; - }, - - /** - * Stops this Key Control from running. Call `start` to start it again. - * - * @method Phaser.Cameras.Controls.FixedKeyControl#stop - * @since 3.0.0 - * - * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. - */ - stop: function () - { - this.active = false; - - return this; - }, - - /** - * Binds this Key Control to a camera. - * - * @method Phaser.Cameras.Controls.FixedKeyControl#setCamera - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to bind this Key Control to. - * - * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. - */ - setCamera: function (camera) - { - this.camera = camera; - - return this; - }, - - /** - * 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. - */ - update: function (delta) - { - if (!this.active) - { - return; - } - - if (delta === undefined) { delta = 1; } - - var cam = this.camera; - - if (this.up && this.up.isDown) - { - cam.scrollY -= ((this.speedY * delta) | 0); - } - else if (this.down && this.down.isDown) - { - cam.scrollY += ((this.speedY * delta) | 0); - } - - if (this.left && this.left.isDown) - { - cam.scrollX -= ((this.speedX * delta) | 0); - } - else if (this.right && this.right.isDown) - { - cam.scrollX += ((this.speedX * delta) | 0); - } - - // Camera zoom - - if (this.zoomIn && this.zoomIn.isDown) - { - cam.zoom -= this.zoomSpeed; - - if (cam.zoom < 0.1) - { - cam.zoom = 0.1; - } - } - else if (this.zoomOut && this.zoomOut.isDown) - { - cam.zoom += this.zoomSpeed; - } - }, - - /** - * Destroys this Key Control. - * - * @method Phaser.Cameras.Controls.FixedKeyControl#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.camera = null; - - this.left = null; - this.right = null; - this.up = null; - this.down = null; - - this.zoomIn = null; - this.zoomOut = null; - } - -}); - -module.exports = FixedKeyControl; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetValue = require('../../utils/object/GetValue'); + +/** + * @classdesc + * A Fixed Key Camera Control. + * + * This allows you to control the movement and zoom of a camera using the defined keys. + * + * ```javascript + * var camControl = new FixedKeyControl({ + * camera: this.cameras.main, + * left: cursors.left, + * right: cursors.right, + * speed: float OR { x: 0, y: 0 } + * }); + * ``` + * + * Movement is precise and has no 'smoothing' applied to it. + * + * You must call the `update` method of this controller every frame. + * + * @class FixedKeyControl + * @memberof Phaser.Cameras.Controls + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Cameras.Controls.FixedKeyControlConfig} config - The Fixed Key Control configuration object. + */ +var FixedKeyControl = new Class({ + + initialize: + + function FixedKeyControl (config) + { + /** + * The Camera that this Control will update. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#camera + * @type {?Phaser.Cameras.Scene2D.Camera} + * @default null + * @since 3.0.0 + */ + this.camera = GetValue(config, 'camera', null); + + /** + * The Key to be pressed that will move the Camera left. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#left + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.left = GetValue(config, 'left', null); + + /** + * The Key to be pressed that will move the Camera right. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#right + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.right = GetValue(config, 'right', null); + + /** + * The Key to be pressed that will move the Camera up. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#up + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.up = GetValue(config, 'up', null); + + /** + * The Key to be pressed that will move the Camera down. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#down + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.down = GetValue(config, 'down', null); + + /** + * The Key to be pressed that will zoom the Camera in. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#zoomIn + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomIn = GetValue(config, 'zoomIn', null); + + /** + * The Key to be pressed that will zoom the Camera out. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#zoomOut + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomOut = GetValue(config, 'zoomOut', null); + + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#zoomSpeed + * @type {number} + * @default 0.01 + * @since 3.0.0 + */ + this.zoomSpeed = GetValue(config, 'zoomSpeed', 0.01); + + /** + * The horizontal speed the camera will move. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#speedX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.speedX = 0; + + /** + * The vertical speed the camera will move. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#speedY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.speedY = 0; + + var speed = GetValue(config, 'speed', null); + + if (typeof speed === 'number') + { + this.speedX = speed; + this.speedY = speed; + } + else + { + this.speedX = GetValue(config, 'speed.x', 0); + this.speedY = GetValue(config, 'speed.y', 0); + } + + /** + * Internal property to track the current zoom level. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#_zoom + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._zoom = 0; + + /** + * A flag controlling if the Controls will update the Camera or not. + * + * @name Phaser.Cameras.Controls.FixedKeyControl#active + * @type {boolean} + * @since 3.0.0 + */ + this.active = (this.camera !== null); + }, + + /** + * Starts the Key Control running, providing it has been linked to a camera. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#start + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. + */ + start: function () + { + this.active = (this.camera !== null); + + return this; + }, + + /** + * Stops this Key Control from running. Call `start` to start it again. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#stop + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. + */ + stop: function () + { + this.active = false; + + return this; + }, + + /** + * Binds this Key Control to a camera. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#setCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to bind this Key Control to. + * + * @return {Phaser.Cameras.Controls.FixedKeyControl} This Key Control instance. + */ + setCamera: function (camera) + { + this.camera = camera; + + return this; + }, + + /** + * 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. + */ + update: function (delta) + { + if (!this.active) + { + return; + } + + if (delta === undefined) { delta = 1; } + + var cam = this.camera; + + if (this.up && this.up.isDown) + { + cam.scrollY -= ((this.speedY * delta) | 0); + } + else if (this.down && this.down.isDown) + { + cam.scrollY += ((this.speedY * delta) | 0); + } + + if (this.left && this.left.isDown) + { + cam.scrollX -= ((this.speedX * delta) | 0); + } + else if (this.right && this.right.isDown) + { + cam.scrollX += ((this.speedX * delta) | 0); + } + + // Camera zoom + + if (this.zoomIn && this.zoomIn.isDown) + { + cam.zoom -= this.zoomSpeed; + + if (cam.zoom < 0.1) + { + cam.zoom = 0.1; + } + } + else if (this.zoomOut && this.zoomOut.isDown) + { + cam.zoom += this.zoomSpeed; + } + }, + + /** + * Destroys this Key Control. + * + * @method Phaser.Cameras.Controls.FixedKeyControl#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.camera = null; + + this.left = null; + this.right = null; + this.up = null; + this.down = null; + + this.zoomIn = null; + this.zoomOut = null; + } + +}); + +module.exports = FixedKeyControl; diff --git a/src/cameras/controls/SmoothedKeyControl.js b/src/cameras/controls/SmoothedKeyControl.js index 7916e9e20..2713ec09d 100644 --- a/src/cameras/controls/SmoothedKeyControl.js +++ b/src/cameras/controls/SmoothedKeyControl.js @@ -1,477 +1,477 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetValue = require('../../utils/object/GetValue'); - -/** - * @classdesc - * A Smoothed Key Camera Control. - * - * This allows you to control the movement and zoom of a camera using the defined keys. - * Unlike the Fixed Camera Control you can also provide physics values for acceleration, drag and maxSpeed for smoothing effects. - * - * ```javascript - * var controlConfig = { - * camera: this.cameras.main, - * left: cursors.left, - * right: cursors.right, - * up: cursors.up, - * down: cursors.down, - * zoomIn: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q), - * zoomOut: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.E), - * zoomSpeed: 0.02, - * acceleration: 0.06, - * drag: 0.0005, - * maxSpeed: 1.0 - * }; - * ``` - * - * You must call the `update` method of this controller every frame. - * - * @class SmoothedKeyControl - * @memberof Phaser.Cameras.Controls - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.Cameras.Controls.SmoothedKeyControlConfig} config - The Smoothed Key Control configuration object. - */ -var SmoothedKeyControl = new Class({ - - initialize: - - function SmoothedKeyControl (config) - { - /** - * The Camera that this Control will update. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#camera - * @type {?Phaser.Cameras.Scene2D.Camera} - * @default null - * @since 3.0.0 - */ - this.camera = GetValue(config, 'camera', null); - - /** - * The Key to be pressed that will move the Camera left. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#left - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.left = GetValue(config, 'left', null); - - /** - * The Key to be pressed that will move the Camera right. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#right - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.right = GetValue(config, 'right', null); - - /** - * The Key to be pressed that will move the Camera up. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#up - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.up = GetValue(config, 'up', null); - - /** - * The Key to be pressed that will move the Camera down. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#down - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.down = GetValue(config, 'down', null); - - /** - * The Key to be pressed that will zoom the Camera in. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomIn - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.zoomIn = GetValue(config, 'zoomIn', null); - - /** - * The Key to be pressed that will zoom the Camera out. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomOut - * @type {?Phaser.Input.Keyboard.Key} - * @default null - * @since 3.0.0 - */ - this.zoomOut = GetValue(config, 'zoomOut', null); - - /** - * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomSpeed - * @type {number} - * @default 0.01 - * @since 3.0.0 - */ - this.zoomSpeed = GetValue(config, 'zoomSpeed', 0.01); - - /** - * The horizontal acceleration the camera will move. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#accelX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accelX = 0; - - /** - * The vertical acceleration the camera will move. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#accelY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accelY = 0; - - var accel = GetValue(config, 'acceleration', null); - - if (typeof accel === 'number') - { - this.accelX = accel; - this.accelY = accel; - } - else - { - this.accelX = GetValue(config, 'acceleration.x', 0); - this.accelY = GetValue(config, 'acceleration.y', 0); - } - - /** - * The horizontal drag applied to the camera when it is moving. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#dragX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.dragX = 0; - - /** - * The vertical drag applied to the camera when it is moving. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#dragY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.dragY = 0; - - var drag = GetValue(config, 'drag', null); - - if (typeof drag === 'number') - { - this.dragX = drag; - this.dragY = drag; - } - else - { - this.dragX = GetValue(config, 'drag.x', 0); - this.dragY = GetValue(config, 'drag.y', 0); - } - - /** - * The maximum horizontal speed the camera will move. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#maxSpeedX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.maxSpeedX = 0; - - /** - * The maximum vertical speed the camera will move. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#maxSpeedY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.maxSpeedY = 0; - - var maxSpeed = GetValue(config, 'maxSpeed', null); - - if (typeof maxSpeed === 'number') - { - this.maxSpeedX = maxSpeed; - this.maxSpeedY = maxSpeed; - } - else - { - this.maxSpeedX = GetValue(config, 'maxSpeed.x', 0); - this.maxSpeedY = GetValue(config, 'maxSpeed.y', 0); - } - - /** - * Internal property to track the speed of the control. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#_speedX - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._speedX = 0; - - /** - * Internal property to track the speed of the control. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#_speedY - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._speedY = 0; - - /** - * Internal property to track the zoom of the control. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#_zoom - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._zoom = 0; - - /** - * A flag controlling if the Controls will update the Camera or not. - * - * @name Phaser.Cameras.Controls.SmoothedKeyControl#active - * @type {boolean} - * @since 3.0.0 - */ - this.active = (this.camera !== null); - }, - - /** - * Starts the Key Control running, providing it has been linked to a camera. - * - * @method Phaser.Cameras.Controls.SmoothedKeyControl#start - * @since 3.0.0 - * - * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. - */ - start: function () - { - this.active = (this.camera !== null); - - return this; - }, - - /** - * Stops this Key Control from running. Call `start` to start it again. - * - * @method Phaser.Cameras.Controls.SmoothedKeyControl#stop - * @since 3.0.0 - * - * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. - */ - stop: function () - { - this.active = false; - - return this; - }, - - /** - * Binds this Key Control to a camera. - * - * @method Phaser.Cameras.Controls.SmoothedKeyControl#setCamera - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to bind this Key Control to. - * - * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. - */ - setCamera: function (camera) - { - this.camera = camera; - - return this; - }, - - /** - * 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. - */ - update: function (delta) - { - if (!this.active) - { - return; - } - - if (delta === undefined) { delta = 1; } - - var cam = this.camera; - - // Apply Deceleration - - if (this._speedX > 0) - { - this._speedX -= this.dragX * delta; - - if (this._speedX < 0) - { - this._speedX = 0; - } - } - else if (this._speedX < 0) - { - this._speedX += this.dragX * delta; - - if (this._speedX > 0) - { - this._speedX = 0; - } - } - - if (this._speedY > 0) - { - this._speedY -= this.dragY * delta; - - if (this._speedY < 0) - { - this._speedY = 0; - } - } - else if (this._speedY < 0) - { - this._speedY += this.dragY * delta; - - if (this._speedY > 0) - { - this._speedY = 0; - } - } - - // Check for keys - - if (this.up && this.up.isDown) - { - this._speedY += this.accelY; - - if (this._speedY > this.maxSpeedY) - { - this._speedY = this.maxSpeedY; - } - } - else if (this.down && this.down.isDown) - { - this._speedY -= this.accelY; - - if (this._speedY < -this.maxSpeedY) - { - this._speedY = -this.maxSpeedY; - } - } - - if (this.left && this.left.isDown) - { - this._speedX += this.accelX; - - if (this._speedX > this.maxSpeedX) - { - this._speedX = this.maxSpeedX; - } - } - else if (this.right && this.right.isDown) - { - this._speedX -= this.accelX; - - if (this._speedX < -this.maxSpeedX) - { - this._speedX = -this.maxSpeedX; - } - } - - // Camera zoom - - if (this.zoomIn && this.zoomIn.isDown) - { - this._zoom = -this.zoomSpeed; - } - else if (this.zoomOut && this.zoomOut.isDown) - { - this._zoom = this.zoomSpeed; - } - else - { - this._zoom = 0; - } - - // Apply to Camera - - if (this._speedX !== 0) - { - cam.scrollX -= ((this._speedX * delta) | 0); - } - - if (this._speedY !== 0) - { - cam.scrollY -= ((this._speedY * delta) | 0); - } - - if (this._zoom !== 0) - { - cam.zoom += this._zoom; - - if (cam.zoom < 0.001) - { - cam.zoom = 0.001; - } - } - }, - - /** - * Destroys this Key Control. - * - * @method Phaser.Cameras.Controls.SmoothedKeyControl#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.camera = null; - - this.left = null; - this.right = null; - this.up = null; - this.down = null; - - this.zoomIn = null; - this.zoomOut = null; - } - -}); - -module.exports = SmoothedKeyControl; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetValue = require('../../utils/object/GetValue'); + +/** + * @classdesc + * A Smoothed Key Camera Control. + * + * This allows you to control the movement and zoom of a camera using the defined keys. + * Unlike the Fixed Camera Control you can also provide physics values for acceleration, drag and maxSpeed for smoothing effects. + * + * ```javascript + * var controlConfig = { + * camera: this.cameras.main, + * left: cursors.left, + * right: cursors.right, + * up: cursors.up, + * down: cursors.down, + * zoomIn: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q), + * zoomOut: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.E), + * zoomSpeed: 0.02, + * acceleration: 0.06, + * drag: 0.0005, + * maxSpeed: 1.0 + * }; + * ``` + * + * You must call the `update` method of this controller every frame. + * + * @class SmoothedKeyControl + * @memberof Phaser.Cameras.Controls + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Cameras.Controls.SmoothedKeyControlConfig} config - The Smoothed Key Control configuration object. + */ +var SmoothedKeyControl = new Class({ + + initialize: + + function SmoothedKeyControl (config) + { + /** + * The Camera that this Control will update. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#camera + * @type {?Phaser.Cameras.Scene2D.Camera} + * @default null + * @since 3.0.0 + */ + this.camera = GetValue(config, 'camera', null); + + /** + * The Key to be pressed that will move the Camera left. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#left + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.left = GetValue(config, 'left', null); + + /** + * The Key to be pressed that will move the Camera right. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#right + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.right = GetValue(config, 'right', null); + + /** + * The Key to be pressed that will move the Camera up. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#up + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.up = GetValue(config, 'up', null); + + /** + * The Key to be pressed that will move the Camera down. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#down + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.down = GetValue(config, 'down', null); + + /** + * The Key to be pressed that will zoom the Camera in. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomIn + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomIn = GetValue(config, 'zoomIn', null); + + /** + * The Key to be pressed that will zoom the Camera out. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomOut + * @type {?Phaser.Input.Keyboard.Key} + * @default null + * @since 3.0.0 + */ + this.zoomOut = GetValue(config, 'zoomOut', null); + + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#zoomSpeed + * @type {number} + * @default 0.01 + * @since 3.0.0 + */ + this.zoomSpeed = GetValue(config, 'zoomSpeed', 0.01); + + /** + * The horizontal acceleration the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#accelX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelX = 0; + + /** + * The vertical acceleration the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#accelY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelY = 0; + + var accel = GetValue(config, 'acceleration', null); + + if (typeof accel === 'number') + { + this.accelX = accel; + this.accelY = accel; + } + else + { + this.accelX = GetValue(config, 'acceleration.x', 0); + this.accelY = GetValue(config, 'acceleration.y', 0); + } + + /** + * The horizontal drag applied to the camera when it is moving. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#dragX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragX = 0; + + /** + * The vertical drag applied to the camera when it is moving. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#dragY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragY = 0; + + var drag = GetValue(config, 'drag', null); + + if (typeof drag === 'number') + { + this.dragX = drag; + this.dragY = drag; + } + else + { + this.dragX = GetValue(config, 'drag.x', 0); + this.dragY = GetValue(config, 'drag.y', 0); + } + + /** + * The maximum horizontal speed the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#maxSpeedX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.maxSpeedX = 0; + + /** + * The maximum vertical speed the camera will move. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#maxSpeedY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.maxSpeedY = 0; + + var maxSpeed = GetValue(config, 'maxSpeed', null); + + if (typeof maxSpeed === 'number') + { + this.maxSpeedX = maxSpeed; + this.maxSpeedY = maxSpeed; + } + else + { + this.maxSpeedX = GetValue(config, 'maxSpeed.x', 0); + this.maxSpeedY = GetValue(config, 'maxSpeed.y', 0); + } + + /** + * Internal property to track the speed of the control. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#_speedX + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._speedX = 0; + + /** + * Internal property to track the speed of the control. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#_speedY + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._speedY = 0; + + /** + * Internal property to track the zoom of the control. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#_zoom + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._zoom = 0; + + /** + * A flag controlling if the Controls will update the Camera or not. + * + * @name Phaser.Cameras.Controls.SmoothedKeyControl#active + * @type {boolean} + * @since 3.0.0 + */ + this.active = (this.camera !== null); + }, + + /** + * Starts the Key Control running, providing it has been linked to a camera. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#start + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. + */ + start: function () + { + this.active = (this.camera !== null); + + return this; + }, + + /** + * Stops this Key Control from running. Call `start` to start it again. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#stop + * @since 3.0.0 + * + * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. + */ + stop: function () + { + this.active = false; + + return this; + }, + + /** + * Binds this Key Control to a camera. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#setCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to bind this Key Control to. + * + * @return {Phaser.Cameras.Controls.SmoothedKeyControl} This Key Control instance. + */ + setCamera: function (camera) + { + this.camera = camera; + + return this; + }, + + /** + * 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. + */ + update: function (delta) + { + if (!this.active) + { + return; + } + + if (delta === undefined) { delta = 1; } + + var cam = this.camera; + + // Apply Deceleration + + if (this._speedX > 0) + { + this._speedX -= this.dragX * delta; + + if (this._speedX < 0) + { + this._speedX = 0; + } + } + else if (this._speedX < 0) + { + this._speedX += this.dragX * delta; + + if (this._speedX > 0) + { + this._speedX = 0; + } + } + + if (this._speedY > 0) + { + this._speedY -= this.dragY * delta; + + if (this._speedY < 0) + { + this._speedY = 0; + } + } + else if (this._speedY < 0) + { + this._speedY += this.dragY * delta; + + if (this._speedY > 0) + { + this._speedY = 0; + } + } + + // Check for keys + + if (this.up && this.up.isDown) + { + this._speedY += this.accelY; + + if (this._speedY > this.maxSpeedY) + { + this._speedY = this.maxSpeedY; + } + } + else if (this.down && this.down.isDown) + { + this._speedY -= this.accelY; + + if (this._speedY < -this.maxSpeedY) + { + this._speedY = -this.maxSpeedY; + } + } + + if (this.left && this.left.isDown) + { + this._speedX += this.accelX; + + if (this._speedX > this.maxSpeedX) + { + this._speedX = this.maxSpeedX; + } + } + else if (this.right && this.right.isDown) + { + this._speedX -= this.accelX; + + if (this._speedX < -this.maxSpeedX) + { + this._speedX = -this.maxSpeedX; + } + } + + // Camera zoom + + if (this.zoomIn && this.zoomIn.isDown) + { + this._zoom = -this.zoomSpeed; + } + else if (this.zoomOut && this.zoomOut.isDown) + { + this._zoom = this.zoomSpeed; + } + else + { + this._zoom = 0; + } + + // Apply to Camera + + if (this._speedX !== 0) + { + cam.scrollX -= ((this._speedX * delta) | 0); + } + + if (this._speedY !== 0) + { + cam.scrollY -= ((this._speedY * delta) | 0); + } + + if (this._zoom !== 0) + { + cam.zoom += this._zoom; + + if (cam.zoom < 0.001) + { + cam.zoom = 0.001; + } + } + }, + + /** + * Destroys this Key Control. + * + * @method Phaser.Cameras.Controls.SmoothedKeyControl#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.camera = null; + + this.left = null; + this.right = null; + this.up = null; + this.down = null; + + this.zoomIn = null; + this.zoomOut = null; + } + +}); + +module.exports = SmoothedKeyControl; diff --git a/src/cameras/controls/index.js b/src/cameras/controls/index.js index f93ebb552..0fda9be5a 100644 --- a/src/cameras/controls/index.js +++ b/src/cameras/controls/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cameras.Controls - */ - -module.exports = { - - FixedKeyControl: require('./FixedKeyControl'), - SmoothedKeyControl: require('./SmoothedKeyControl') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras.Controls + */ + +module.exports = { + + FixedKeyControl: require('./FixedKeyControl'), + SmoothedKeyControl: require('./SmoothedKeyControl') + +}; diff --git a/src/cameras/controls/typedefs/index.js b/src/cameras/controls/typedefs/index.js index 6a28e6b28..a43052c27 100644 --- a/src/cameras/controls/typedefs/index.js +++ b/src/cameras/controls/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Cameras.Controls - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Cameras.Controls + */ diff --git a/src/cameras/index.js b/src/cameras/index.js index 5ee2b99cf..781c14e67 100644 --- a/src/cameras/index.js +++ b/src/cameras/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Cameras - */ - -/** - * @namespace Phaser.Types.Cameras - */ - -module.exports = { - - Controls: require('./controls'), - Scene2D: require('./2d') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Cameras + */ + +/** + * @namespace Phaser.Types.Cameras + */ + +module.exports = { + + Controls: require('./controls'), + Scene2D: require('./2d') + +}; diff --git a/src/const.js b/src/const.js index 86307872d..b0475236c 100644 --- a/src/const.js +++ b/src/const.js @@ -1,193 +1,193 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Global constants. - * - * @ignore - */ - -var CONST = { - - /** - * Phaser Release Version - * - * @name Phaser.VERSION - * @const - * @type {string} - * @since 3.0.0 - */ - VERSION: '3.23.0-beta1', - - BlendModes: require('./renderer/BlendModes'), - - ScaleModes: require('./renderer/ScaleModes'), - - /** - * AUTO Detect Renderer. - * - * @name Phaser.AUTO - * @const - * @type {integer} - * @since 3.0.0 - */ - AUTO: 0, - - /** - * Canvas Renderer. - * - * @name Phaser.CANVAS - * @const - * @type {integer} - * @since 3.0.0 - */ - CANVAS: 1, - - /** - * WebGL Renderer. - * - * @name Phaser.WEBGL - * @const - * @type {integer} - * @since 3.0.0 - */ - WEBGL: 2, - - /** - * Headless Renderer. - * - * @name Phaser.HEADLESS - * @const - * @type {integer} - * @since 3.0.0 - */ - HEADLESS: 3, - - /** - * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead - * to help you remember what the value is doing in your code. - * - * @name Phaser.FOREVER - * @const - * @type {integer} - * @since 3.0.0 - */ - FOREVER: -1, - - /** - * Direction constant. - * - * @name Phaser.NONE - * @const - * @type {integer} - * @since 3.0.0 - */ - NONE: 4, - - /** - * Direction constant. - * - * @name Phaser.UP - * @const - * @type {integer} - * @since 3.0.0 - */ - UP: 5, - - /** - * Direction constant. - * - * @name Phaser.DOWN - * @const - * @type {integer} - * @since 3.0.0 - */ - DOWN: 6, - - /** - * Direction constant. - * - * @name Phaser.LEFT - * @const - * @type {integer} - * @since 3.0.0 - */ - LEFT: 7, - - /** - * Direction constant. - * - * @name Phaser.RIGHT - * @const - * @type {integer} - * @since 3.0.0 - */ - RIGHT: 8, - - - /** - * Orientation constant. - * - * @name Phaser.ORTHOGONAL - * @const - * @type {integer} - * @since 3.2.2 - */ - ORTHOGONAL: 0, - - - /** - * Orientation constant. - * - * @name Phaser.ISOMETRIC - * @const - * @type {integer} - * @since 3.2.2 - */ - ISOMETRIC: 1, - - - /** - * Orientation constant. - * - * @name Phaser.STAGGERED - * @const - * @type {integer} - * @since 3.2.2 - */ - STAGGERED: 2, - - /** - * Orientation constant. - * - * @name Phaser.HEXAGONAL - * @const - * @type {integer} - * @since 3.2.2 - */ - HEXAGONAL: 3, - - fromOrientationString: function (orientation) - { - var constor = CONST.ORTHOGONAL; - - if (orientation === 'isometric') - { - constor = CONST.ISOMETRIC; - } - else if (orientation === 'staggered') - { - constor = CONST.STAGGERED; - } - else if (orientation === 'hexagonal') - { - constor = CONST.HEXAGONAL; - } - return constor; - } -}; - -module.exports = CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Global constants. + * + * @ignore + */ + +var CONST = { + + /** + * Phaser Release Version + * + * @name Phaser.VERSION + * @const + * @type {string} + * @since 3.0.0 + */ + VERSION: '3.23.0-beta1', + + BlendModes: require('./renderer/BlendModes'), + + ScaleModes: require('./renderer/ScaleModes'), + + /** + * AUTO Detect Renderer. + * + * @name Phaser.AUTO + * @const + * @type {integer} + * @since 3.0.0 + */ + AUTO: 0, + + /** + * Canvas Renderer. + * + * @name Phaser.CANVAS + * @const + * @type {integer} + * @since 3.0.0 + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * + * @name Phaser.WEBGL + * @const + * @type {integer} + * @since 3.0.0 + */ + WEBGL: 2, + + /** + * Headless Renderer. + * + * @name Phaser.HEADLESS + * @const + * @type {integer} + * @since 3.0.0 + */ + HEADLESS: 3, + + /** + * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead + * to help you remember what the value is doing in your code. + * + * @name Phaser.FOREVER + * @const + * @type {integer} + * @since 3.0.0 + */ + FOREVER: -1, + + /** + * Direction constant. + * + * @name Phaser.NONE + * @const + * @type {integer} + * @since 3.0.0 + */ + NONE: 4, + + /** + * Direction constant. + * + * @name Phaser.UP + * @const + * @type {integer} + * @since 3.0.0 + */ + UP: 5, + + /** + * Direction constant. + * + * @name Phaser.DOWN + * @const + * @type {integer} + * @since 3.0.0 + */ + DOWN: 6, + + /** + * Direction constant. + * + * @name Phaser.LEFT + * @const + * @type {integer} + * @since 3.0.0 + */ + LEFT: 7, + + /** + * Direction constant. + * + * @name Phaser.RIGHT + * @const + * @type {integer} + * @since 3.0.0 + */ + RIGHT: 8, + + + /** + * Orientation constant. + * + * @name Phaser.ORTHOGONAL + * @const + * @type {integer} + * @since 3.2.2 + */ + ORTHOGONAL: 0, + + + /** + * Orientation constant. + * + * @name Phaser.ISOMETRIC + * @const + * @type {integer} + * @since 3.2.2 + */ + ISOMETRIC: 1, + + + /** + * Orientation constant. + * + * @name Phaser.STAGGERED + * @const + * @type {integer} + * @since 3.2.2 + */ + STAGGERED: 2, + + /** + * Orientation constant. + * + * @name Phaser.HEXAGONAL + * @const + * @type {integer} + * @since 3.2.2 + */ + HEXAGONAL: 3, + + fromOrientationString: function (orientation) + { + var constor = CONST.ORTHOGONAL; + + if (orientation === 'isometric') + { + constor = CONST.ISOMETRIC; + } + else if (orientation === 'staggered') + { + constor = CONST.STAGGERED; + } + else if (orientation === 'hexagonal') + { + constor = CONST.HEXAGONAL; + } + return constor; + } +}; + +module.exports = CONST; diff --git a/src/core/Config.js b/src/core/Config.js index f5eec1ff0..3b4611cd1 100644 --- a/src/core/Config.js +++ b/src/core/Config.js @@ -1,575 +1,575 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CONST = require('../const'); -var Device = require('../device'); -var GetFastValue = require('../utils/object/GetFastValue'); -var GetValue = require('../utils/object/GetValue'); -var IsPlainObject = require('../utils/object/IsPlainObject'); -var PhaserMath = require('../math/'); -var NOOP = require('../utils/NOOP'); -var DefaultPlugins = require('../plugins/DefaultPlugins'); -var ValueToColor = require('../display/color/ValueToColor'); - -/** - * @classdesc - * The active game configuration settings, parsed from a {@link Phaser.Types.Core.GameConfig} object. - * - * @class Config - * @memberof Phaser.Core - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.Core.GameConfig} [GameConfig] - The configuration object for your Phaser Game instance. - * - * @see Phaser.Game#config - */ -var Config = new Class({ - - initialize: - - function Config (config) - { - if (config === undefined) { config = {}; } - - var defaultBannerColor = [ - '#ff0000', - '#ffff00', - '#00ff00', - '#00ffff', - '#000000' - ]; - - var defaultBannerTextColor = '#ffffff'; - - /** - * @const {(integer|string)} Phaser.Core.Config#width - The width of the underlying canvas, in pixels. - */ - this.width = GetValue(config, 'width', 1024); - - /** - * @const {(integer|string)} Phaser.Core.Config#height - The height of the underlying canvas, in pixels. - */ - this.height = GetValue(config, 'height', 768); - - /** - * @const {(Phaser.Scale.ZoomType|integer)} Phaser.Core.Config#zoom - The zoom factor, as used by the Scale Manager. - */ - this.zoom = GetValue(config, 'zoom', 1); - - /** - * @const {number} Phaser.Core.Config#resolution - The canvas device pixel resolution. Currently un-used. - */ - this.resolution = GetValue(config, 'resolution', 1); - - /** - * @const {?*} Phaser.Core.Config#parent - A parent DOM element into which the canvas created by the renderer will be injected. - */ - this.parent = GetValue(config, 'parent', undefined); - - /** - * @const {Phaser.Scale.ScaleModeType} Phaser.Core.Config#scaleMode - The scale mode as used by the Scale Manager. The default is zero, which is no scaling. - */ - this.scaleMode = GetValue(config, 'scaleMode', 0); - - /** - * @const {boolean} Phaser.Core.Config#expandParent - Is the Scale Manager allowed to adjust the CSS height property of the parent to be 100%? - */ - this.expandParent = GetValue(config, 'expandParent', true); - - /** - * @const {integer} Phaser.Core.Config#autoRound - Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. - */ - this.autoRound = GetValue(config, 'autoRound', false); - - /** - * @const {Phaser.Scale.CenterType} Phaser.Core.Config#autoCenter - Automatically center the canvas within the parent? - */ - this.autoCenter = GetValue(config, 'autoCenter', 0); - - /** - * @const {integer} Phaser.Core.Config#resizeInterval - How many ms should elapse before checking if the browser size has changed? - */ - this.resizeInterval = GetValue(config, 'resizeInterval', 500); - - /** - * @const {?(HTMLElement|string)} Phaser.Core.Config#fullscreenTarget - The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. - */ - this.fullscreenTarget = GetValue(config, 'fullscreenTarget', null); - - /** - * @const {integer} Phaser.Core.Config#minWidth - The minimum width, in pixels, the canvas will scale down to. A value of zero means no minimum. - */ - this.minWidth = GetValue(config, 'minWidth', 0); - - /** - * @const {integer} Phaser.Core.Config#maxWidth - The maximum width, in pixels, the canvas will scale up to. A value of zero means no maximum. - */ - this.maxWidth = GetValue(config, 'maxWidth', 0); - - /** - * @const {integer} Phaser.Core.Config#minHeight - The minimum height, in pixels, the canvas will scale down to. A value of zero means no minimum. - */ - this.minHeight = GetValue(config, 'minHeight', 0); - - /** - * @const {integer} Phaser.Core.Config#maxHeight - The maximum height, in pixels, the canvas will scale up to. A value of zero means no maximum. - */ - this.maxHeight = GetValue(config, 'maxHeight', 0); - - // Scale Manager - Anything set in here over-rides anything set above - - var scaleConfig = GetValue(config, 'scale', null); - - if (scaleConfig) - { - this.width = GetValue(scaleConfig, 'width', this.width); - this.height = GetValue(scaleConfig, 'height', this.height); - this.zoom = GetValue(scaleConfig, 'zoom', this.zoom); - this.resolution = GetValue(scaleConfig, 'resolution', this.resolution); - this.parent = GetValue(scaleConfig, 'parent', this.parent); - this.scaleMode = GetValue(scaleConfig, 'mode', this.scaleMode); - this.expandParent = GetValue(scaleConfig, 'expandParent', this.expandParent); - this.autoRound = GetValue(scaleConfig, 'autoRound', this.autoRound); - this.autoCenter = GetValue(scaleConfig, 'autoCenter', this.autoCenter); - this.resizeInterval = GetValue(scaleConfig, 'resizeInterval', this.resizeInterval); - this.fullscreenTarget = GetValue(scaleConfig, 'fullscreenTarget', this.fullscreenTarget); - this.minWidth = GetValue(scaleConfig, 'min.width', this.minWidth); - this.maxWidth = GetValue(scaleConfig, 'max.width', this.maxWidth); - this.minHeight = GetValue(scaleConfig, 'min.height', this.minHeight); - this.maxHeight = GetValue(scaleConfig, 'max.height', this.maxHeight); - } - - /** - * @const {number} Phaser.Core.Config#renderType - Force Phaser to use a specific renderer. Can be `CONST.CANVAS`, `CONST.WEBGL`, `CONST.HEADLESS` or `CONST.AUTO` (default) - */ - this.renderType = GetValue(config, 'type', CONST.AUTO); - - /** - * @const {?HTMLCanvasElement} Phaser.Core.Config#canvas - Force Phaser to use your own Canvas element instead of creating one. - */ - this.canvas = GetValue(config, 'canvas', null); - - /** - * @const {?(CanvasRenderingContext2D|WebGLRenderingContext)} Phaser.Core.Config#context - Force Phaser to use your own Canvas context instead of creating one. - */ - this.context = GetValue(config, 'context', null); - - /** - * @const {?string} Phaser.Core.Config#canvasStyle - Optional CSS attributes to be set on the canvas object created by the renderer. - */ - this.canvasStyle = GetValue(config, 'canvasStyle', null); - - /** - * @const {boolean} Phaser.Core.Config#customEnvironment - Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. - */ - this.customEnvironment = GetValue(config, 'customEnvironment', false); - - /** - * @const {?object} Phaser.Core.Config#sceneConfig - The default Scene configuration object. - */ - this.sceneConfig = GetValue(config, 'scene', null); - - /** - * @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. - */ - this.seed = GetValue(config, 'seed', [ (Date.now() * Math.random()).toString() ]); - - PhaserMath.RND = new PhaserMath.RandomDataGenerator(this.seed); - - /** - * @const {string} Phaser.Core.Config#gameTitle - The title of the game. - */ - this.gameTitle = GetValue(config, 'title', ''); - - /** - * @const {string} Phaser.Core.Config#gameURL - The URL of the game. - */ - this.gameURL = GetValue(config, 'url', 'https://phaser.io'); - - /** - * @const {string} Phaser.Core.Config#gameVersion - The version of the game. - */ - this.gameVersion = GetValue(config, 'version', ''); - - /** - * @const {boolean} Phaser.Core.Config#autoFocus - If `true` the window will automatically be given focus immediately and on any future mousedown event. - */ - this.autoFocus = GetValue(config, 'autoFocus', true); - - // DOM Element Container - - /** - * @const {?boolean} Phaser.Core.Config#domCreateContainer - Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. - */ - this.domCreateContainer = GetValue(config, 'dom.createContainer', false); - - /** - * @const {?boolean} Phaser.Core.Config#domBehindCanvas - Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? - */ - this.domBehindCanvas = GetValue(config, 'dom.behindCanvas', false); - - // Input - - /** - * @const {boolean} Phaser.Core.Config#inputKeyboard - Enable the Keyboard Plugin. This can be disabled in games that don't need keyboard input. - */ - this.inputKeyboard = GetValue(config, 'input.keyboard', true); - - /** - * @const {*} Phaser.Core.Config#inputKeyboardEventTarget - The DOM Target to listen for keyboard events on. Defaults to `window` if not specified. - */ - this.inputKeyboardEventTarget = GetValue(config, 'input.keyboard.target', window); - - /** - * @const {?integer[]} Phaser.Core.Config#inputKeyboardCapture - `preventDefault` will be called on every non-modified key which has a key code in this array. By default, it is empty. - */ - this.inputKeyboardCapture = GetValue(config, 'input.keyboard.capture', []); - - /** - * @const {(boolean|object)} Phaser.Core.Config#inputMouse - Enable the Mouse Plugin. This can be disabled in games that don't need mouse input. - */ - this.inputMouse = GetValue(config, 'input.mouse', true); - - /** - * @const {?*} Phaser.Core.Config#inputMouseEventTarget - The DOM Target to listen for mouse events on. Defaults to the game canvas if not specified. - */ - this.inputMouseEventTarget = GetValue(config, 'input.mouse.target', null); - - /** - * @const {boolean} Phaser.Core.Config#inputMouseCapture - Should mouse events be captured? I.e. have prevent default called on them. - */ - this.inputMouseCapture = GetValue(config, 'input.mouse.capture', true); - - /** - * @const {boolean} Phaser.Core.Config#inputTouch - Enable the Touch Plugin. This can be disabled in games that don't need touch input. - */ - this.inputTouch = GetValue(config, 'input.touch', Device.input.touch); - - /** - * @const {?*} Phaser.Core.Config#inputTouchEventTarget - The DOM Target to listen for touch events on. Defaults to the game canvas if not specified. - */ - this.inputTouchEventTarget = GetValue(config, 'input.touch.target', null); - - /** - * @const {boolean} Phaser.Core.Config#inputTouchCapture - Should touch events be captured? I.e. have prevent default called on them. - */ - this.inputTouchCapture = GetValue(config, 'input.touch.capture', true); - - /** - * @const {integer} Phaser.Core.Config#inputActivePointers - The number of Pointer objects created by default. In a mouse-only, or non-multi touch game, you can leave this as 1. - */ - this.inputActivePointers = GetValue(config, 'input.activePointers', 1); - - /** - * @const {integer} Phaser.Core.Config#inputSmoothFactor - The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. - */ - this.inputSmoothFactor = GetValue(config, 'input.smoothFactor', 0); - - /** - * @const {boolean} Phaser.Core.Config#inputWindowEvents - Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. - */ - this.inputWindowEvents = GetValue(config, 'input.windowEvents', true); - - /** - * @const {boolean} Phaser.Core.Config#inputGamepad - Enable the Gamepad Plugin. This can be disabled in games that don't need gamepad input. - */ - this.inputGamepad = GetValue(config, 'input.gamepad', false); - - /** - * @const {*} Phaser.Core.Config#inputGamepadEventTarget - The DOM Target to listen for gamepad events on. Defaults to `window` if not specified. - */ - this.inputGamepadEventTarget = GetValue(config, 'input.gamepad.target', window); - - /** - * @const {boolean} Phaser.Core.Config#disableContextMenu - Set to `true` to disable the right-click context menu. - */ - this.disableContextMenu = GetValue(config, 'disableContextMenu', false); - - /** - * @const {Phaser.Types.Core.AudioConfig} Phaser.Core.Config#audio - The Audio Configuration object. - */ - this.audio = GetValue(config, 'audio'); - - // If you do: { banner: false } it won't display any banner at all - - /** - * @const {boolean} Phaser.Core.Config#hideBanner - Don't write the banner line to the console.log. - */ - this.hideBanner = (GetValue(config, 'banner', null) === false); - - /** - * @const {boolean} Phaser.Core.Config#hidePhaser - Omit Phaser's name and version from the banner. - */ - this.hidePhaser = GetValue(config, 'banner.hidePhaser', false); - - /** - * @const {string} Phaser.Core.Config#bannerTextColor - The color of the banner text. - */ - this.bannerTextColor = GetValue(config, 'banner.text', defaultBannerTextColor); - - /** - * @const {string[]} Phaser.Core.Config#bannerBackgroundColor - The background colors of the banner. - */ - this.bannerBackgroundColor = GetValue(config, 'banner.background', defaultBannerColor); - - if (this.gameTitle === '' && this.hidePhaser) - { - this.hideBanner = true; - } - - /** - * @const {?Phaser.Types.Core.FPSConfig} Phaser.Core.Config#fps - The Frame Rate Configuration object, as parsed by the Timestep class. - */ - this.fps = GetValue(config, 'fps', null); - - // Renderer Settings - // These can either be in a `render` object within the Config, or specified on their own - - var renderConfig = GetValue(config, 'render', config); - - /** - * @const {boolean} Phaser.Core.Config#antialias - When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. - */ - this.antialias = GetValue(renderConfig, 'antialias', true); - - /** - * @const {boolean} Phaser.Core.Config#antialiasGL - Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. - */ - this.antialiasGL = GetValue(renderConfig, 'antialiasGL', true); - - /** - * @const {string} Phaser.Core.Config#mipmapFilter - Sets the `mipmapFilter` property when the WebGL renderer is created. - */ - this.mipmapFilter = GetValue(renderConfig, 'mipmapFilter', 'LINEAR'); - - /** - * @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. - */ - this.desynchronized = GetValue(renderConfig, 'desynchronized', false); - - /** - * @const {boolean} Phaser.Core.Config#roundPixels - Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. - */ - this.roundPixels = GetValue(renderConfig, 'roundPixels', false); - - /** - * @const {boolean} Phaser.Core.Config#pixelArt - Prevent pixel art from becoming blurred when scaled. It will remain crisp (tells the WebGL renderer to automatically create textures using a linear filter mode). - */ - this.pixelArt = GetValue(renderConfig, 'pixelArt', this.zoom !== 1); - - if (this.pixelArt) - { - this.antialias = false; - this.roundPixels = true; - } - - /** - * @const {boolean} Phaser.Core.Config#transparent - Whether the game canvas will have a transparent background. - */ - this.transparent = GetValue(renderConfig, 'transparent', false); - - /** - * @const {boolean} Phaser.Core.Config#clearBeforeRender - Whether the game canvas will be cleared between each rendering frame. You can disable this if you have a full-screen background image or game object. - */ - this.clearBeforeRender = GetValue(renderConfig, 'clearBeforeRender', true); - - /** - * @const {boolean} Phaser.Core.Config#premultipliedAlpha - In WebGL mode, sets the drawing buffer to contain colors with pre-multiplied alpha. - */ - this.premultipliedAlpha = GetValue(renderConfig, 'premultipliedAlpha', true); - - /** - * @const {boolean} Phaser.Core.Config#failIfMajorPerformanceCaveat - Let the browser abort creating a WebGL context if it judges performance would be unacceptable. - */ - this.failIfMajorPerformanceCaveat = GetValue(renderConfig, 'failIfMajorPerformanceCaveat', false); - - /** - * @const {string} Phaser.Core.Config#powerPreference - "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. - */ - this.powerPreference = GetValue(renderConfig, 'powerPreference', 'default'); - - /** - * @const {integer} Phaser.Core.Config#batchSize - The default WebGL Batch size. - */ - this.batchSize = GetValue(renderConfig, 'batchSize', 2000); - - /** - * @const {integer} Phaser.Core.Config#maxLights - The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. - */ - this.maxLights = GetValue(renderConfig, 'maxLights', 10); - - var bgc = GetValue(config, 'backgroundColor', 0); - - /** - * @const {Phaser.Display.Color} Phaser.Core.Config#backgroundColor - The background color of the game canvas. The default is black. This value is ignored if `transparent` is set to `true`. - */ - this.backgroundColor = ValueToColor(bgc); - - if (bgc === 0 && this.transparent) - { - this.backgroundColor.alpha = 0; - } - - /** - * @const {Phaser.Types.Core.BootCallback} Phaser.Core.Config#preBoot - Called before Phaser boots. Useful for initializing anything not related to Phaser that Phaser may require while booting. - */ - this.preBoot = GetValue(config, 'callbacks.preBoot', NOOP); - - /** - * @const {Phaser.Types.Core.BootCallback} Phaser.Core.Config#postBoot - A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. - */ - this.postBoot = GetValue(config, 'callbacks.postBoot', NOOP); - - /** - * @const {Phaser.Types.Core.PhysicsConfig} Phaser.Core.Config#physics - The Physics Configuration object. - */ - this.physics = GetValue(config, 'physics', {}); - - /** - * @const {(boolean|string)} Phaser.Core.Config#defaultPhysicsSystem - The default physics system. It will be started for each scene. Either 'arcade', 'impact' or 'matter'. - */ - this.defaultPhysicsSystem = GetValue(this.physics, 'default', false); - - /** - * @const {string} Phaser.Core.Config#loaderBaseURL - A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. - */ - this.loaderBaseURL = GetValue(config, 'loader.baseURL', ''); - - /** - * @const {string} Phaser.Core.Config#loaderPath - A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. - */ - this.loaderPath = GetValue(config, 'loader.path', ''); - - /** - * @const {integer} Phaser.Core.Config#loaderMaxParallelDownloads - Maximum parallel downloads allowed for resources (Default to 32). - */ - this.loaderMaxParallelDownloads = GetValue(config, 'loader.maxParallelDownloads', 32); - - /** - * @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}. - */ - this.loaderCrossOrigin = GetValue(config, 'loader.crossOrigin', undefined); - - /** - * @const {string} Phaser.Core.Config#loaderResponseType - The response type of the XHR request, e.g. `blob`, `text`, etc. - */ - this.loaderResponseType = GetValue(config, 'loader.responseType', ''); - - /** - * @const {boolean} Phaser.Core.Config#loaderAsync - Should the XHR request use async or not? - */ - this.loaderAsync = GetValue(config, 'loader.async', true); - - /** - * @const {string} Phaser.Core.Config#loaderUser - Optional username for all XHR requests. - */ - this.loaderUser = GetValue(config, 'loader.user', ''); - - /** - * @const {string} Phaser.Core.Config#loaderPassword - Optional password for all XHR requests. - */ - this.loaderPassword = GetValue(config, 'loader.password', ''); - - /** - * @const {integer} Phaser.Core.Config#loaderTimeout - Optional XHR timeout value, in ms. - */ - this.loaderTimeout = GetValue(config, 'loader.timeout', 0); - - /** - * @const {boolean} Phaser.Core.Config#loaderWithCredentials - Optional XHR withCredentials value. - */ - this.loaderWithCredentials = GetValue(config, 'loader.withCredentials', false); - - /* - * Allows `plugins` property to either be an array, in which case it just replaces - * the default plugins like previously, or a config object. - * - * plugins: { - * global: [ - * { key: 'TestPlugin', plugin: TestPlugin, start: true, data: { msg: 'The plugin is alive' } }, - * ], - * scene: [ - * { key: 'WireFramePlugin', plugin: WireFramePlugin, systemKey: 'wireFramePlugin', sceneKey: 'wireframe' } - * ], - * default: [], OR - * defaultMerge: [ - * 'ModPlayer' - * ] - * } - */ - - /** - * @const {any} Phaser.Core.Config#installGlobalPlugins - An array of global plugins to be installed. - */ - this.installGlobalPlugins = []; - - /** - * @const {any} Phaser.Core.Config#installScenePlugins - An array of Scene level plugins to be installed. - */ - this.installScenePlugins = []; - - var plugins = GetValue(config, 'plugins', null); - var defaultPlugins = DefaultPlugins.DefaultScene; - - if (plugins) - { - // Old 3.7 array format? - if (Array.isArray(plugins)) - { - this.defaultPlugins = plugins; - } - else if (IsPlainObject(plugins)) - { - this.installGlobalPlugins = GetFastValue(plugins, 'global', []); - this.installScenePlugins = GetFastValue(plugins, 'scene', []); - - if (Array.isArray(plugins.default)) - { - defaultPlugins = plugins.default; - } - else if (Array.isArray(plugins.defaultMerge)) - { - defaultPlugins = defaultPlugins.concat(plugins.defaultMerge); - } - } - } - - /** - * @const {any} Phaser.Core.Config#defaultPlugins - The plugins installed into every Scene (in addition to CoreScene and Global). - */ - this.defaultPlugins = defaultPlugins; - - // Default / Missing Images - var pngPrefix = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg'; - - /** - * @const {string} Phaser.Core.Config#defaultImage - A base64 encoded PNG that will be used as the default blank texture. - */ - this.defaultImage = GetValue(config, 'images.default', pngPrefix + 'AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='); - - /** - * @const {string} Phaser.Core.Config#missingImage - A base64 encoded PNG that will be used as the default texture when a texture is assigned that is missing or not loaded. - */ - this.missingImage = GetValue(config, 'images.missing', pngPrefix + 'CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='); - - if (window) - { - if (window.FORCE_WEBGL) - { - this.renderType = CONST.WEBGL; - } - else if (window.FORCE_CANVAS) - { - this.renderType = CONST.CANVAS; - } - } - } - -}); - -module.exports = Config; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CONST = require('../const'); +var Device = require('../device'); +var GetFastValue = require('../utils/object/GetFastValue'); +var GetValue = require('../utils/object/GetValue'); +var IsPlainObject = require('../utils/object/IsPlainObject'); +var PhaserMath = require('../math/'); +var NOOP = require('../utils/NOOP'); +var DefaultPlugins = require('../plugins/DefaultPlugins'); +var ValueToColor = require('../display/color/ValueToColor'); + +/** + * @classdesc + * The active game configuration settings, parsed from a {@link Phaser.Types.Core.GameConfig} object. + * + * @class Config + * @memberof Phaser.Core + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Core.GameConfig} [GameConfig] - The configuration object for your Phaser Game instance. + * + * @see Phaser.Game#config + */ +var Config = new Class({ + + initialize: + + function Config (config) + { + if (config === undefined) { config = {}; } + + var defaultBannerColor = [ + '#ff0000', + '#ffff00', + '#00ff00', + '#00ffff', + '#000000' + ]; + + var defaultBannerTextColor = '#ffffff'; + + /** + * @const {(integer|string)} Phaser.Core.Config#width - The width of the underlying canvas, in pixels. + */ + this.width = GetValue(config, 'width', 1024); + + /** + * @const {(integer|string)} Phaser.Core.Config#height - The height of the underlying canvas, in pixels. + */ + this.height = GetValue(config, 'height', 768); + + /** + * @const {(Phaser.Scale.ZoomType|integer)} Phaser.Core.Config#zoom - The zoom factor, as used by the Scale Manager. + */ + this.zoom = GetValue(config, 'zoom', 1); + + /** + * @const {number} Phaser.Core.Config#resolution - The canvas device pixel resolution. Currently un-used. + */ + this.resolution = GetValue(config, 'resolution', 1); + + /** + * @const {?*} Phaser.Core.Config#parent - A parent DOM element into which the canvas created by the renderer will be injected. + */ + this.parent = GetValue(config, 'parent', undefined); + + /** + * @const {Phaser.Scale.ScaleModeType} Phaser.Core.Config#scaleMode - The scale mode as used by the Scale Manager. The default is zero, which is no scaling. + */ + this.scaleMode = GetValue(config, 'scaleMode', 0); + + /** + * @const {boolean} Phaser.Core.Config#expandParent - Is the Scale Manager allowed to adjust the CSS height property of the parent to be 100%? + */ + this.expandParent = GetValue(config, 'expandParent', true); + + /** + * @const {integer} Phaser.Core.Config#autoRound - Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. + */ + this.autoRound = GetValue(config, 'autoRound', false); + + /** + * @const {Phaser.Scale.CenterType} Phaser.Core.Config#autoCenter - Automatically center the canvas within the parent? + */ + this.autoCenter = GetValue(config, 'autoCenter', 0); + + /** + * @const {integer} Phaser.Core.Config#resizeInterval - How many ms should elapse before checking if the browser size has changed? + */ + this.resizeInterval = GetValue(config, 'resizeInterval', 500); + + /** + * @const {?(HTMLElement|string)} Phaser.Core.Config#fullscreenTarget - The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. + */ + this.fullscreenTarget = GetValue(config, 'fullscreenTarget', null); + + /** + * @const {integer} Phaser.Core.Config#minWidth - The minimum width, in pixels, the canvas will scale down to. A value of zero means no minimum. + */ + this.minWidth = GetValue(config, 'minWidth', 0); + + /** + * @const {integer} Phaser.Core.Config#maxWidth - The maximum width, in pixels, the canvas will scale up to. A value of zero means no maximum. + */ + this.maxWidth = GetValue(config, 'maxWidth', 0); + + /** + * @const {integer} Phaser.Core.Config#minHeight - The minimum height, in pixels, the canvas will scale down to. A value of zero means no minimum. + */ + this.minHeight = GetValue(config, 'minHeight', 0); + + /** + * @const {integer} Phaser.Core.Config#maxHeight - The maximum height, in pixels, the canvas will scale up to. A value of zero means no maximum. + */ + this.maxHeight = GetValue(config, 'maxHeight', 0); + + // Scale Manager - Anything set in here over-rides anything set above + + var scaleConfig = GetValue(config, 'scale', null); + + if (scaleConfig) + { + this.width = GetValue(scaleConfig, 'width', this.width); + this.height = GetValue(scaleConfig, 'height', this.height); + this.zoom = GetValue(scaleConfig, 'zoom', this.zoom); + this.resolution = GetValue(scaleConfig, 'resolution', this.resolution); + this.parent = GetValue(scaleConfig, 'parent', this.parent); + this.scaleMode = GetValue(scaleConfig, 'mode', this.scaleMode); + this.expandParent = GetValue(scaleConfig, 'expandParent', this.expandParent); + this.autoRound = GetValue(scaleConfig, 'autoRound', this.autoRound); + this.autoCenter = GetValue(scaleConfig, 'autoCenter', this.autoCenter); + this.resizeInterval = GetValue(scaleConfig, 'resizeInterval', this.resizeInterval); + this.fullscreenTarget = GetValue(scaleConfig, 'fullscreenTarget', this.fullscreenTarget); + this.minWidth = GetValue(scaleConfig, 'min.width', this.minWidth); + this.maxWidth = GetValue(scaleConfig, 'max.width', this.maxWidth); + this.minHeight = GetValue(scaleConfig, 'min.height', this.minHeight); + this.maxHeight = GetValue(scaleConfig, 'max.height', this.maxHeight); + } + + /** + * @const {number} Phaser.Core.Config#renderType - Force Phaser to use a specific renderer. Can be `CONST.CANVAS`, `CONST.WEBGL`, `CONST.HEADLESS` or `CONST.AUTO` (default) + */ + this.renderType = GetValue(config, 'type', CONST.AUTO); + + /** + * @const {?HTMLCanvasElement} Phaser.Core.Config#canvas - Force Phaser to use your own Canvas element instead of creating one. + */ + this.canvas = GetValue(config, 'canvas', null); + + /** + * @const {?(CanvasRenderingContext2D|WebGLRenderingContext)} Phaser.Core.Config#context - Force Phaser to use your own Canvas context instead of creating one. + */ + this.context = GetValue(config, 'context', null); + + /** + * @const {?string} Phaser.Core.Config#canvasStyle - Optional CSS attributes to be set on the canvas object created by the renderer. + */ + this.canvasStyle = GetValue(config, 'canvasStyle', null); + + /** + * @const {boolean} Phaser.Core.Config#customEnvironment - Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. + */ + this.customEnvironment = GetValue(config, 'customEnvironment', false); + + /** + * @const {?object} Phaser.Core.Config#sceneConfig - The default Scene configuration object. + */ + this.sceneConfig = GetValue(config, 'scene', null); + + /** + * @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. + */ + this.seed = GetValue(config, 'seed', [ (Date.now() * Math.random()).toString() ]); + + PhaserMath.RND = new PhaserMath.RandomDataGenerator(this.seed); + + /** + * @const {string} Phaser.Core.Config#gameTitle - The title of the game. + */ + this.gameTitle = GetValue(config, 'title', ''); + + /** + * @const {string} Phaser.Core.Config#gameURL - The URL of the game. + */ + this.gameURL = GetValue(config, 'url', 'https://phaser.io'); + + /** + * @const {string} Phaser.Core.Config#gameVersion - The version of the game. + */ + this.gameVersion = GetValue(config, 'version', ''); + + /** + * @const {boolean} Phaser.Core.Config#autoFocus - If `true` the window will automatically be given focus immediately and on any future mousedown event. + */ + this.autoFocus = GetValue(config, 'autoFocus', true); + + // DOM Element Container + + /** + * @const {?boolean} Phaser.Core.Config#domCreateContainer - Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. + */ + this.domCreateContainer = GetValue(config, 'dom.createContainer', false); + + /** + * @const {?boolean} Phaser.Core.Config#domBehindCanvas - Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? + */ + this.domBehindCanvas = GetValue(config, 'dom.behindCanvas', false); + + // Input + + /** + * @const {boolean} Phaser.Core.Config#inputKeyboard - Enable the Keyboard Plugin. This can be disabled in games that don't need keyboard input. + */ + this.inputKeyboard = GetValue(config, 'input.keyboard', true); + + /** + * @const {*} Phaser.Core.Config#inputKeyboardEventTarget - The DOM Target to listen for keyboard events on. Defaults to `window` if not specified. + */ + this.inputKeyboardEventTarget = GetValue(config, 'input.keyboard.target', window); + + /** + * @const {?integer[]} Phaser.Core.Config#inputKeyboardCapture - `preventDefault` will be called on every non-modified key which has a key code in this array. By default, it is empty. + */ + this.inputKeyboardCapture = GetValue(config, 'input.keyboard.capture', []); + + /** + * @const {(boolean|object)} Phaser.Core.Config#inputMouse - Enable the Mouse Plugin. This can be disabled in games that don't need mouse input. + */ + this.inputMouse = GetValue(config, 'input.mouse', true); + + /** + * @const {?*} Phaser.Core.Config#inputMouseEventTarget - The DOM Target to listen for mouse events on. Defaults to the game canvas if not specified. + */ + this.inputMouseEventTarget = GetValue(config, 'input.mouse.target', null); + + /** + * @const {boolean} Phaser.Core.Config#inputMouseCapture - Should mouse events be captured? I.e. have prevent default called on them. + */ + this.inputMouseCapture = GetValue(config, 'input.mouse.capture', true); + + /** + * @const {boolean} Phaser.Core.Config#inputTouch - Enable the Touch Plugin. This can be disabled in games that don't need touch input. + */ + this.inputTouch = GetValue(config, 'input.touch', Device.input.touch); + + /** + * @const {?*} Phaser.Core.Config#inputTouchEventTarget - The DOM Target to listen for touch events on. Defaults to the game canvas if not specified. + */ + this.inputTouchEventTarget = GetValue(config, 'input.touch.target', null); + + /** + * @const {boolean} Phaser.Core.Config#inputTouchCapture - Should touch events be captured? I.e. have prevent default called on them. + */ + this.inputTouchCapture = GetValue(config, 'input.touch.capture', true); + + /** + * @const {integer} Phaser.Core.Config#inputActivePointers - The number of Pointer objects created by default. In a mouse-only, or non-multi touch game, you can leave this as 1. + */ + this.inputActivePointers = GetValue(config, 'input.activePointers', 1); + + /** + * @const {integer} Phaser.Core.Config#inputSmoothFactor - The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. + */ + this.inputSmoothFactor = GetValue(config, 'input.smoothFactor', 0); + + /** + * @const {boolean} Phaser.Core.Config#inputWindowEvents - Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. + */ + this.inputWindowEvents = GetValue(config, 'input.windowEvents', true); + + /** + * @const {boolean} Phaser.Core.Config#inputGamepad - Enable the Gamepad Plugin. This can be disabled in games that don't need gamepad input. + */ + this.inputGamepad = GetValue(config, 'input.gamepad', false); + + /** + * @const {*} Phaser.Core.Config#inputGamepadEventTarget - The DOM Target to listen for gamepad events on. Defaults to `window` if not specified. + */ + this.inputGamepadEventTarget = GetValue(config, 'input.gamepad.target', window); + + /** + * @const {boolean} Phaser.Core.Config#disableContextMenu - Set to `true` to disable the right-click context menu. + */ + this.disableContextMenu = GetValue(config, 'disableContextMenu', false); + + /** + * @const {Phaser.Types.Core.AudioConfig} Phaser.Core.Config#audio - The Audio Configuration object. + */ + this.audio = GetValue(config, 'audio'); + + // If you do: { banner: false } it won't display any banner at all + + /** + * @const {boolean} Phaser.Core.Config#hideBanner - Don't write the banner line to the console.log. + */ + this.hideBanner = (GetValue(config, 'banner', null) === false); + + /** + * @const {boolean} Phaser.Core.Config#hidePhaser - Omit Phaser's name and version from the banner. + */ + this.hidePhaser = GetValue(config, 'banner.hidePhaser', false); + + /** + * @const {string} Phaser.Core.Config#bannerTextColor - The color of the banner text. + */ + this.bannerTextColor = GetValue(config, 'banner.text', defaultBannerTextColor); + + /** + * @const {string[]} Phaser.Core.Config#bannerBackgroundColor - The background colors of the banner. + */ + this.bannerBackgroundColor = GetValue(config, 'banner.background', defaultBannerColor); + + if (this.gameTitle === '' && this.hidePhaser) + { + this.hideBanner = true; + } + + /** + * @const {?Phaser.Types.Core.FPSConfig} Phaser.Core.Config#fps - The Frame Rate Configuration object, as parsed by the Timestep class. + */ + this.fps = GetValue(config, 'fps', null); + + // Renderer Settings + // These can either be in a `render` object within the Config, or specified on their own + + var renderConfig = GetValue(config, 'render', config); + + /** + * @const {boolean} Phaser.Core.Config#antialias - When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. + */ + this.antialias = GetValue(renderConfig, 'antialias', true); + + /** + * @const {boolean} Phaser.Core.Config#antialiasGL - Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. + */ + this.antialiasGL = GetValue(renderConfig, 'antialiasGL', true); + + /** + * @const {string} Phaser.Core.Config#mipmapFilter - Sets the `mipmapFilter` property when the WebGL renderer is created. + */ + this.mipmapFilter = GetValue(renderConfig, 'mipmapFilter', 'LINEAR'); + + /** + * @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. + */ + this.desynchronized = GetValue(renderConfig, 'desynchronized', false); + + /** + * @const {boolean} Phaser.Core.Config#roundPixels - Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. + */ + this.roundPixels = GetValue(renderConfig, 'roundPixels', false); + + /** + * @const {boolean} Phaser.Core.Config#pixelArt - Prevent pixel art from becoming blurred when scaled. It will remain crisp (tells the WebGL renderer to automatically create textures using a linear filter mode). + */ + this.pixelArt = GetValue(renderConfig, 'pixelArt', this.zoom !== 1); + + if (this.pixelArt) + { + this.antialias = false; + this.roundPixels = true; + } + + /** + * @const {boolean} Phaser.Core.Config#transparent - Whether the game canvas will have a transparent background. + */ + this.transparent = GetValue(renderConfig, 'transparent', false); + + /** + * @const {boolean} Phaser.Core.Config#clearBeforeRender - Whether the game canvas will be cleared between each rendering frame. You can disable this if you have a full-screen background image or game object. + */ + this.clearBeforeRender = GetValue(renderConfig, 'clearBeforeRender', true); + + /** + * @const {boolean} Phaser.Core.Config#premultipliedAlpha - In WebGL mode, sets the drawing buffer to contain colors with pre-multiplied alpha. + */ + this.premultipliedAlpha = GetValue(renderConfig, 'premultipliedAlpha', true); + + /** + * @const {boolean} Phaser.Core.Config#failIfMajorPerformanceCaveat - Let the browser abort creating a WebGL context if it judges performance would be unacceptable. + */ + this.failIfMajorPerformanceCaveat = GetValue(renderConfig, 'failIfMajorPerformanceCaveat', false); + + /** + * @const {string} Phaser.Core.Config#powerPreference - "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. + */ + this.powerPreference = GetValue(renderConfig, 'powerPreference', 'default'); + + /** + * @const {integer} Phaser.Core.Config#batchSize - The default WebGL Batch size. + */ + this.batchSize = GetValue(renderConfig, 'batchSize', 2000); + + /** + * @const {integer} Phaser.Core.Config#maxLights - The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. + */ + this.maxLights = GetValue(renderConfig, 'maxLights', 10); + + var bgc = GetValue(config, 'backgroundColor', 0); + + /** + * @const {Phaser.Display.Color} Phaser.Core.Config#backgroundColor - The background color of the game canvas. The default is black. This value is ignored if `transparent` is set to `true`. + */ + this.backgroundColor = ValueToColor(bgc); + + if (bgc === 0 && this.transparent) + { + this.backgroundColor.alpha = 0; + } + + /** + * @const {Phaser.Types.Core.BootCallback} Phaser.Core.Config#preBoot - Called before Phaser boots. Useful for initializing anything not related to Phaser that Phaser may require while booting. + */ + this.preBoot = GetValue(config, 'callbacks.preBoot', NOOP); + + /** + * @const {Phaser.Types.Core.BootCallback} Phaser.Core.Config#postBoot - A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. + */ + this.postBoot = GetValue(config, 'callbacks.postBoot', NOOP); + + /** + * @const {Phaser.Types.Core.PhysicsConfig} Phaser.Core.Config#physics - The Physics Configuration object. + */ + this.physics = GetValue(config, 'physics', {}); + + /** + * @const {(boolean|string)} Phaser.Core.Config#defaultPhysicsSystem - The default physics system. It will be started for each scene. Either 'arcade', 'impact' or 'matter'. + */ + this.defaultPhysicsSystem = GetValue(this.physics, 'default', false); + + /** + * @const {string} Phaser.Core.Config#loaderBaseURL - A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. + */ + this.loaderBaseURL = GetValue(config, 'loader.baseURL', ''); + + /** + * @const {string} Phaser.Core.Config#loaderPath - A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. + */ + this.loaderPath = GetValue(config, 'loader.path', ''); + + /** + * @const {integer} Phaser.Core.Config#loaderMaxParallelDownloads - Maximum parallel downloads allowed for resources (Default to 32). + */ + this.loaderMaxParallelDownloads = GetValue(config, 'loader.maxParallelDownloads', 32); + + /** + * @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}. + */ + this.loaderCrossOrigin = GetValue(config, 'loader.crossOrigin', undefined); + + /** + * @const {string} Phaser.Core.Config#loaderResponseType - The response type of the XHR request, e.g. `blob`, `text`, etc. + */ + this.loaderResponseType = GetValue(config, 'loader.responseType', ''); + + /** + * @const {boolean} Phaser.Core.Config#loaderAsync - Should the XHR request use async or not? + */ + this.loaderAsync = GetValue(config, 'loader.async', true); + + /** + * @const {string} Phaser.Core.Config#loaderUser - Optional username for all XHR requests. + */ + this.loaderUser = GetValue(config, 'loader.user', ''); + + /** + * @const {string} Phaser.Core.Config#loaderPassword - Optional password for all XHR requests. + */ + this.loaderPassword = GetValue(config, 'loader.password', ''); + + /** + * @const {integer} Phaser.Core.Config#loaderTimeout - Optional XHR timeout value, in ms. + */ + this.loaderTimeout = GetValue(config, 'loader.timeout', 0); + + /** + * @const {boolean} Phaser.Core.Config#loaderWithCredentials - Optional XHR withCredentials value. + */ + this.loaderWithCredentials = GetValue(config, 'loader.withCredentials', false); + + /* + * Allows `plugins` property to either be an array, in which case it just replaces + * the default plugins like previously, or a config object. + * + * plugins: { + * global: [ + * { key: 'TestPlugin', plugin: TestPlugin, start: true, data: { msg: 'The plugin is alive' } }, + * ], + * scene: [ + * { key: 'WireFramePlugin', plugin: WireFramePlugin, systemKey: 'wireFramePlugin', sceneKey: 'wireframe' } + * ], + * default: [], OR + * defaultMerge: [ + * 'ModPlayer' + * ] + * } + */ + + /** + * @const {any} Phaser.Core.Config#installGlobalPlugins - An array of global plugins to be installed. + */ + this.installGlobalPlugins = []; + + /** + * @const {any} Phaser.Core.Config#installScenePlugins - An array of Scene level plugins to be installed. + */ + this.installScenePlugins = []; + + var plugins = GetValue(config, 'plugins', null); + var defaultPlugins = DefaultPlugins.DefaultScene; + + if (plugins) + { + // Old 3.7 array format? + if (Array.isArray(plugins)) + { + this.defaultPlugins = plugins; + } + else if (IsPlainObject(plugins)) + { + this.installGlobalPlugins = GetFastValue(plugins, 'global', []); + this.installScenePlugins = GetFastValue(plugins, 'scene', []); + + if (Array.isArray(plugins.default)) + { + defaultPlugins = plugins.default; + } + else if (Array.isArray(plugins.defaultMerge)) + { + defaultPlugins = defaultPlugins.concat(plugins.defaultMerge); + } + } + } + + /** + * @const {any} Phaser.Core.Config#defaultPlugins - The plugins installed into every Scene (in addition to CoreScene and Global). + */ + this.defaultPlugins = defaultPlugins; + + // Default / Missing Images + var pngPrefix = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg'; + + /** + * @const {string} Phaser.Core.Config#defaultImage - A base64 encoded PNG that will be used as the default blank texture. + */ + this.defaultImage = GetValue(config, 'images.default', pngPrefix + 'AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='); + + /** + * @const {string} Phaser.Core.Config#missingImage - A base64 encoded PNG that will be used as the default texture when a texture is assigned that is missing or not loaded. + */ + this.missingImage = GetValue(config, 'images.missing', pngPrefix + 'CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='); + + if (window) + { + if (window.FORCE_WEBGL) + { + this.renderType = CONST.WEBGL; + } + else if (window.FORCE_CANVAS) + { + this.renderType = CONST.CANVAS; + } + } + } + +}); + +module.exports = Config; diff --git a/src/core/CreateRenderer.js b/src/core/CreateRenderer.js index 29f1aed7b..98a6659a5 100644 --- a/src/core/CreateRenderer.js +++ b/src/core/CreateRenderer.js @@ -1,138 +1,138 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasInterpolation = require('../display/canvas/CanvasInterpolation'); -var CanvasPool = require('../display/canvas/CanvasPool'); -var CONST = require('../const'); -var Features = require('../device/Features'); - -/** - * Called automatically by Phaser.Game and responsible for creating the renderer it will use. - * - * Relies upon two webpack global flags to be defined: `WEBGL_RENDERER` and `CANVAS_RENDERER` during build time, but not at run-time. - * - * @function Phaser.Core.CreateRenderer - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Phaser.Game instance on which the renderer will be set. - */ -var CreateRenderer = function (game) -{ - var config = game.config; - - if ((config.customEnvironment || config.canvas) && config.renderType === CONST.AUTO) - { - throw new Error('Must set explicit renderType in custom environment'); - } - - // Not a custom environment, didn't provide their own canvas and not headless, so determine the renderer: - if (!config.customEnvironment && !config.canvas && config.renderType !== CONST.HEADLESS) - { - if (config.renderType === CONST.CANVAS || (config.renderType !== CONST.CANVAS && !Features.webGL)) - { - if (Features.canvas) - { - // They requested Canvas and their browser supports it - config.renderType = CONST.CANVAS; - } - else - { - throw new Error('Cannot create Canvas or WebGL context, aborting.'); - } - } - else - { - // Game requested WebGL and browser says it supports it - config.renderType = CONST.WEBGL; - } - } - - // Pixel Art mode? - if (!config.antialias) - { - CanvasPool.disableSmoothing(); - } - - var baseSize = game.scale.baseSize; - - var width = baseSize.width; - var height = baseSize.height; - - // Does the game config provide its own canvas element to use? - if (config.canvas) - { - game.canvas = config.canvas; - - game.canvas.width = width; - game.canvas.height = height; - } - else - { - game.canvas = CanvasPool.create(game, width, height, config.renderType); - } - - // Does the game config provide some canvas css styles to use? - if (config.canvasStyle) - { - game.canvas.style = config.canvasStyle; - } - - // Pixel Art mode? - if (!config.antialias) - { - CanvasInterpolation.setCrisp(game.canvas); - } - - if (config.renderType === CONST.HEADLESS) - { - // Nothing more to do here - return; - } - - var CanvasRenderer; - var WebGLRenderer; - - if (typeof WEBGL_RENDERER && typeof CANVAS_RENDERER) - { - CanvasRenderer = require('../renderer/canvas/CanvasRenderer'); - WebGLRenderer = require('../renderer/webgl/WebGLRenderer'); - - // Let the config pick the renderer type, as both are included - if (config.renderType === CONST.WEBGL) - { - game.renderer = new WebGLRenderer(game); - } - else - { - game.renderer = new CanvasRenderer(game); - game.context = game.renderer.gameContext; - } - } - - if (typeof WEBGL_RENDERER && !typeof CANVAS_RENDERER) - { - WebGLRenderer = require('../renderer/webgl/WebGLRenderer'); - - // Force the type to WebGL, regardless what was requested - config.renderType = CONST.WEBGL; - - game.renderer = new WebGLRenderer(game); - } - - if (!typeof WEBGL_RENDERER && typeof CANVAS_RENDERER) - { - CanvasRenderer = require('../renderer/canvas/CanvasRenderer'); - - // Force the type to Canvas, regardless what was requested - config.renderType = CONST.CANVAS; - - game.renderer = new CanvasRenderer(game); - - game.context = game.renderer.gameContext; - } -}; - -module.exports = CreateRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasInterpolation = require('../display/canvas/CanvasInterpolation'); +var CanvasPool = require('../display/canvas/CanvasPool'); +var CONST = require('../const'); +var Features = require('../device/Features'); + +/** + * Called automatically by Phaser.Game and responsible for creating the renderer it will use. + * + * Relies upon two webpack global flags to be defined: `WEBGL_RENDERER` and `CANVAS_RENDERER` during build time, but not at run-time. + * + * @function Phaser.Core.CreateRenderer + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance on which the renderer will be set. + */ +var CreateRenderer = function (game) +{ + var config = game.config; + + if ((config.customEnvironment || config.canvas) && config.renderType === CONST.AUTO) + { + throw new Error('Must set explicit renderType in custom environment'); + } + + // Not a custom environment, didn't provide their own canvas and not headless, so determine the renderer: + if (!config.customEnvironment && !config.canvas && config.renderType !== CONST.HEADLESS) + { + if (config.renderType === CONST.CANVAS || (config.renderType !== CONST.CANVAS && !Features.webGL)) + { + if (Features.canvas) + { + // They requested Canvas and their browser supports it + config.renderType = CONST.CANVAS; + } + else + { + throw new Error('Cannot create Canvas or WebGL context, aborting.'); + } + } + else + { + // Game requested WebGL and browser says it supports it + config.renderType = CONST.WEBGL; + } + } + + // Pixel Art mode? + if (!config.antialias) + { + CanvasPool.disableSmoothing(); + } + + var baseSize = game.scale.baseSize; + + var width = baseSize.width; + var height = baseSize.height; + + // Does the game config provide its own canvas element to use? + if (config.canvas) + { + game.canvas = config.canvas; + + game.canvas.width = width; + game.canvas.height = height; + } + else + { + game.canvas = CanvasPool.create(game, width, height, config.renderType); + } + + // Does the game config provide some canvas css styles to use? + if (config.canvasStyle) + { + game.canvas.style = config.canvasStyle; + } + + // Pixel Art mode? + if (!config.antialias) + { + CanvasInterpolation.setCrisp(game.canvas); + } + + if (config.renderType === CONST.HEADLESS) + { + // Nothing more to do here + return; + } + + var CanvasRenderer; + var WebGLRenderer; + + if (typeof WEBGL_RENDERER && typeof CANVAS_RENDERER) + { + CanvasRenderer = require('../renderer/canvas/CanvasRenderer'); + WebGLRenderer = require('../renderer/webgl/WebGLRenderer'); + + // Let the config pick the renderer type, as both are included + if (config.renderType === CONST.WEBGL) + { + game.renderer = new WebGLRenderer(game); + } + else + { + game.renderer = new CanvasRenderer(game); + game.context = game.renderer.gameContext; + } + } + + if (typeof WEBGL_RENDERER && !typeof CANVAS_RENDERER) + { + WebGLRenderer = require('../renderer/webgl/WebGLRenderer'); + + // Force the type to WebGL, regardless what was requested + config.renderType = CONST.WEBGL; + + game.renderer = new WebGLRenderer(game); + } + + if (!typeof WEBGL_RENDERER && typeof CANVAS_RENDERER) + { + CanvasRenderer = require('../renderer/canvas/CanvasRenderer'); + + // Force the type to Canvas, regardless what was requested + config.renderType = CONST.CANVAS; + + game.renderer = new CanvasRenderer(game); + + game.context = game.renderer.gameContext; + } +}; + +module.exports = CreateRenderer; diff --git a/src/core/DebugHeader.js b/src/core/DebugHeader.js index 6b73761c0..23ef500a5 100644 --- a/src/core/DebugHeader.js +++ b/src/core/DebugHeader.js @@ -1,124 +1,124 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../const'); - -/** - * Called automatically by Phaser.Game and responsible for creating the console.log debug header. - * - * You can customize or disable the header via the Game Config object. - * - * @function Phaser.Core.DebugHeader - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Phaser.Game instance which will output this debug header. - */ -var DebugHeader = function (game) -{ - var config = game.config; - - if (config.hideBanner) - { - return; - } - - var renderType = 'WebGL'; - - if (config.renderType === CONST.CANVAS) - { - renderType = 'Canvas'; - } - else if (config.renderType === CONST.HEADLESS) - { - renderType = 'Headless'; - } - - var audioConfig = config.audio; - var deviceAudio = game.device.audio; - - var audioType; - - if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) - { - audioType = 'Web Audio'; - } - else if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) - { - audioType = 'No Audio'; - } - else - { - audioType = 'HTML5 Audio'; - } - - if (!game.device.browser.ie) - { - var c = ''; - var args = [ c ]; - - if (Array.isArray(config.bannerBackgroundColor)) - { - var lastColor; - - config.bannerBackgroundColor.forEach(function (color) - { - c = c.concat('%c '); - - args.push('background: ' + color); - - lastColor = color; - - }); - - // inject the text color - args[args.length - 1] = 'color: ' + config.bannerTextColor + '; background: ' + lastColor; - } - else - { - c = c.concat('%c '); - - args.push('color: ' + config.bannerTextColor + '; background: ' + config.bannerBackgroundColor); - } - - // URL link background color (always white) - args.push('background: #fff'); - - if (config.gameTitle) - { - c = c.concat(config.gameTitle); - - if (config.gameVersion) - { - c = c.concat(' v' + config.gameVersion); - } - - if (!config.hidePhaser) - { - c = c.concat(' / '); - } - } - - var fb = (typeof PLUGIN_FBINSTANT) ? '-FB' : ''; - - if (!config.hidePhaser) - { - c = c.concat('Phaser v' + CONST.VERSION + fb + ' (' + renderType + ' | ' + audioType + ')'); - } - - c = c.concat(' %c ' + config.gameURL); - - // Inject the new string back into the args array - args[0] = c; - - console.log.apply(console, args); - } - else if (window['console']) - { - console.log('Phaser v' + CONST.VERSION + ' / https://phaser.io'); - } -}; - -module.exports = DebugHeader; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../const'); + +/** + * Called automatically by Phaser.Game and responsible for creating the console.log debug header. + * + * You can customize or disable the header via the Game Config object. + * + * @function Phaser.Core.DebugHeader + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance which will output this debug header. + */ +var DebugHeader = function (game) +{ + var config = game.config; + + if (config.hideBanner) + { + return; + } + + var renderType = 'WebGL'; + + if (config.renderType === CONST.CANVAS) + { + renderType = 'Canvas'; + } + else if (config.renderType === CONST.HEADLESS) + { + renderType = 'Headless'; + } + + var audioConfig = config.audio; + var deviceAudio = game.device.audio; + + var audioType; + + if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) + { + audioType = 'Web Audio'; + } + else if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + audioType = 'No Audio'; + } + else + { + audioType = 'HTML5 Audio'; + } + + if (!game.device.browser.ie) + { + var c = ''; + var args = [ c ]; + + if (Array.isArray(config.bannerBackgroundColor)) + { + var lastColor; + + config.bannerBackgroundColor.forEach(function (color) + { + c = c.concat('%c '); + + args.push('background: ' + color); + + lastColor = color; + + }); + + // inject the text color + args[args.length - 1] = 'color: ' + config.bannerTextColor + '; background: ' + lastColor; + } + else + { + c = c.concat('%c '); + + args.push('color: ' + config.bannerTextColor + '; background: ' + config.bannerBackgroundColor); + } + + // URL link background color (always white) + args.push('background: #fff'); + + if (config.gameTitle) + { + c = c.concat(config.gameTitle); + + if (config.gameVersion) + { + c = c.concat(' v' + config.gameVersion); + } + + if (!config.hidePhaser) + { + c = c.concat(' / '); + } + } + + var fb = (typeof PLUGIN_FBINSTANT) ? '-FB' : ''; + + if (!config.hidePhaser) + { + c = c.concat('Phaser v' + CONST.VERSION + fb + ' (' + renderType + ' | ' + audioType + ')'); + } + + c = c.concat(' %c ' + config.gameURL); + + // Inject the new string back into the args array + args[0] = c; + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + CONST.VERSION + ' / https://phaser.io'); + } +}; + +module.exports = DebugHeader; diff --git a/src/core/Game.js b/src/core/Game.js index be64554f2..55a871a1d 100644 --- a/src/core/Game.js +++ b/src/core/Game.js @@ -1,711 +1,711 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AddToDOM = require('../dom/AddToDOM'); -var AnimationManager = require('../animations/AnimationManager'); -var CacheManager = require('../cache/CacheManager'); -var CanvasPool = require('../display/canvas/CanvasPool'); -var Class = require('../utils/Class'); -var Config = require('./Config'); -var CreateDOMContainer = require('../dom/CreateDOMContainer'); -var CreateRenderer = require('./CreateRenderer'); -var DataManager = require('../data/DataManager'); -var DebugHeader = require('./DebugHeader'); -var Device = require('../device'); -var DOMContentLoaded = require('../dom/DOMContentLoaded'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var InputManager = require('../input/InputManager'); -var PluginCache = require('../plugins/PluginCache'); -var PluginManager = require('../plugins/PluginManager'); -var ScaleManager = require('../scale/ScaleManager'); -var SceneManager = require('../scene/SceneManager'); -var TextureEvents = require('../textures/events'); -var TextureManager = require('../textures/TextureManager'); -var TimeStep = require('./TimeStep'); -var VisibilityHandler = require('./VisibilityHandler'); - -if (typeof FEATURE_SOUND) -{ - var SoundManagerCreator = require('../sound/SoundManagerCreator'); -} - -if (typeof PLUGIN_FBINSTANT) -{ - var FacebookInstantGamesPlugin = require('../../plugins/fbinstant/src/FacebookInstantGamesPlugin'); -} - -/** - * @classdesc - * The Phaser.Game instance is the main controller for the entire Phaser game. It is responsible - * for handling the boot process, parsing the configuration values, creating the renderer, - * and setting-up all of the global Phaser systems, such as sound and input. - * Once that is complete it will start the Scene Manager and then begin the main game loop. - * - * You should generally avoid accessing any of the systems created by Game, and instead use those - * made available to you via the Phaser.Scene Systems class instead. - * - * @class Game - * @memberof Phaser - * @constructor - * @fires Phaser.Core.Events#BLUR - * @fires Phaser.Core.Events#FOCUS - * @fires Phaser.Core.Events#HIDDEN - * @fires Phaser.Core.Events#VISIBLE - * @since 3.0.0 - * - * @param {Phaser.Types.Core.GameConfig} [GameConfig] - The configuration object for your Phaser Game instance. - */ -var Game = new Class({ - - initialize: - - function Game (config) - { - /** - * The parsed Game Configuration object. - * - * The values stored within this object are read-only and should not be changed at run-time. - * - * @name Phaser.Game#config - * @type {Phaser.Core.Config} - * @readonly - * @since 3.0.0 - */ - this.config = new Config(config); - - /** - * A reference to either the Canvas or WebGL Renderer that this Game is using. - * - * @name Phaser.Game#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.0.0 - */ - this.renderer = null; - - /** - * A reference to an HTML Div Element used as the DOM Element Container. - * - * Only set if `createDOMContainer` is `true` in the game config (by default it is `false`) and - * if you provide a parent element to insert the Phaser Game inside. - * - * See the DOM Element Game Object for more details. - * - * @name Phaser.Game#domContainer - * @type {HTMLDivElement} - * @since 3.17.0 - */ - this.domContainer = null; - - /** - * A reference to the HTML Canvas Element that Phaser uses to render the game. - * This is created automatically by Phaser unless you provide a `canvas` property - * in your Game Config. - * - * @name Phaser.Game#canvas - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.canvas = null; - - /** - * A reference to the Rendering Context belonging to the Canvas Element this game is rendering to. - * If the game is running under Canvas it will be a 2d Canvas Rendering Context. - * If the game is running under WebGL it will be a WebGL Rendering Context. - * This context is created automatically by Phaser unless you provide a `context` property - * in your Game Config. - * - * @name Phaser.Game#context - * @type {(CanvasRenderingContext2D|WebGLRenderingContext)} - * @since 3.0.0 - */ - this.context = null; - - /** - * A flag indicating when this Game instance has finished its boot process. - * - * @name Phaser.Game#isBooted - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - this.isBooted = false; - - /** - * A flag indicating if this Game is currently running its game step or not. - * - * @name Phaser.Game#isRunning - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - this.isRunning = false; - - /** - * An Event Emitter which is used to broadcast game-level events from the global systems. - * - * @name Phaser.Game#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events = new EventEmitter(); - - /** - * An instance of the Animation Manager. - * - * The Animation Manager is a global system responsible for managing all animations used within your game. - * - * @name Phaser.Game#anims - * @type {Phaser.Animations.AnimationManager} - * @since 3.0.0 - */ - this.anims = new AnimationManager(this); - - /** - * An instance of the Texture Manager. - * - * The Texture Manager is a global system responsible for managing all textures being used by your game. - * - * @name Phaser.Game#textures - * @type {Phaser.Textures.TextureManager} - * @since 3.0.0 - */ - this.textures = new TextureManager(this); - - /** - * An instance of the Cache Manager. - * - * The Cache Manager is a global system responsible for caching, accessing and releasing external game assets. - * - * @name Phaser.Game#cache - * @type {Phaser.Cache.CacheManager} - * @since 3.0.0 - */ - this.cache = new CacheManager(this); - - /** - * An instance of the Data Manager - * - * @name Phaser.Game#registry - * @type {Phaser.Data.DataManager} - * @since 3.0.0 - */ - this.registry = new DataManager(this); - - /** - * An instance of the Input Manager. - * - * The Input Manager is a global system responsible for the capture of browser-level input events. - * - * @name Phaser.Game#input - * @type {Phaser.Input.InputManager} - * @since 3.0.0 - */ - this.input = new InputManager(this, this.config); - - /** - * An instance of the Scene Manager. - * - * The Scene Manager is a global system responsible for creating, modifying and updating the Scenes in your game. - * - * @name Phaser.Game#scene - * @type {Phaser.Scenes.SceneManager} - * @since 3.0.0 - */ - this.scene = new SceneManager(this, this.config.sceneConfig); - - /** - * A reference to the Device inspector. - * - * Contains information about the device running this game, such as OS, browser vendor and feature support. - * Used by various systems to determine capabilities and code paths. - * - * @name Phaser.Game#device - * @type {Phaser.DeviceConf} - * @since 3.0.0 - */ - this.device = Device; - - /** - * An instance of the Scale Manager. - * - * The Scale Manager is a global system responsible for handling scaling of the game canvas. - * - * @name Phaser.Game#scale - * @type {Phaser.Scale.ScaleManager} - * @since 3.16.0 - */ - this.scale = new ScaleManager(this, this.config); - - /** - * An instance of the base Sound Manager. - * - * The Sound Manager is a global system responsible for the playback and updating of all audio in your game. - * - * You can disable the inclusion of the Sound Manager in your build by toggling the webpack `FEATURE_SOUND` flag. - * - * @name Phaser.Game#sound - * @type {(Phaser.Sound.NoAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager)} - * @since 3.0.0 - */ - this.sound = null; - - if (typeof FEATURE_SOUND) - { - this.sound = SoundManagerCreator.create(this); - } - - /** - * An instance of the Time Step. - * - * The Time Step is a global system responsible for setting-up and responding to the browser frame events, processing - * them and calculating delta values. It then automatically calls the game step. - * - * @name Phaser.Game#loop - * @type {Phaser.Core.TimeStep} - * @since 3.0.0 - */ - this.loop = new TimeStep(this, this.config.fps); - - /** - * An instance of the Plugin Manager. - * - * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install - * those plugins into Scenes as required. - * - * @name Phaser.Game#plugins - * @type {Phaser.Plugins.PluginManager} - * @since 3.0.0 - */ - this.plugins = new PluginManager(this, this.config); - - if (typeof PLUGIN_FBINSTANT) - { - /** - * An instance of the Facebook Instant Games Plugin. - * - * This will only be available if the plugin has been built into Phaser, - * or you're using the special Facebook Instant Games custom build. - * - * @name Phaser.Game#facebook - * @type {Phaser.FacebookInstantGamesPlugin} - * @since 3.13.0 - */ - this.facebook = new FacebookInstantGamesPlugin(this); - } - - /** - * Is this Game pending destruction at the start of the next frame? - * - * @name Phaser.Game#pendingDestroy - * @type {boolean} - * @private - * @since 3.5.0 - */ - this.pendingDestroy = false; - - /** - * Remove the Canvas once the destroy is over? - * - * @name Phaser.Game#removeCanvas - * @type {boolean} - * @private - * @since 3.5.0 - */ - this.removeCanvas = false; - - /** - * Remove everything when the game is destroyed. - * You cannot create a new Phaser instance on the same web page after doing this. - * - * @name Phaser.Game#noReturn - * @type {boolean} - * @private - * @since 3.12.0 - */ - this.noReturn = false; - - /** - * Does the window the game is running in currently have focus or not? - * This is modified by the VisibilityHandler. - * - * @name Phaser.Game#hasFocus - * @type {boolean} - * @readonly - * @since 3.9.0 - */ - this.hasFocus = false; - - // Wait for the DOM Ready event, then call boot. - DOMContentLoaded(this.boot.bind(this)); - }, - - /** - * This method is called automatically when the DOM is ready. It is responsible for creating the renderer, - * displaying the Debug Header, adding the game canvas to the DOM and emitting the 'boot' event. - * It listens for a 'ready' event from the base systems and once received it will call `Game.start`. - * - * @method Phaser.Game#boot - * @protected - * @fires Phaser.Core.Events#BOOT - * @listens Phaser.Textures.Events#READY - * @since 3.0.0 - */ - boot: function () - { - if (!PluginCache.hasCore('EventEmitter')) - { - console.warn('Aborting. Core Plugins missing.'); - return; - } - - this.isBooted = true; - - this.config.preBoot(this); - - this.scale.preBoot(); - - CreateRenderer(this); - - CreateDOMContainer(this); - - DebugHeader(this); - - AddToDOM(this.canvas, this.config.parent); - - // 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: - this.textures.once(TextureEvents.READY, this.texturesReady, this); - - this.events.emit(Events.BOOT); - }, - - /** - * Called automatically when the Texture Manager has finished setting up and preparing the - * default textures. - * - * @method Phaser.Game#texturesReady - * @private - * @fires Phaser.Game#ready - * @since 3.12.0 - */ - texturesReady: function () - { - // Start all the other systems - this.events.emit(Events.READY); - - this.start(); - }, - - /** - * Called automatically by Game.boot once all of the global systems have finished setting themselves up. - * By this point the Game is now ready to start the main loop running. - * It will also enable the Visibility Handler. - * - * @method Phaser.Game#start - * @protected - * @since 3.0.0 - */ - start: function () - { - this.isRunning = true; - - this.config.postBoot(this); - - if (this.renderer) - { - this.loop.start(this.step.bind(this)); - } - else - { - this.loop.start(this.headlessStep.bind(this)); - } - - VisibilityHandler(this); - - var eventEmitter = this.events; - - eventEmitter.on(Events.HIDDEN, this.onHidden, this); - eventEmitter.on(Events.VISIBLE, this.onVisible, this); - eventEmitter.on(Events.BLUR, this.onBlur, this); - eventEmitter.on(Events.FOCUS, this.onFocus, this); - }, - - /** - * 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_EVENT - * @fires Phaser.Core.Events#STEP_EVENT - * @fires Phaser.Core.Events#POST_STEP_EVENT - * @fires Phaser.Core.Events#PRE_RENDER_EVENT - * @fires Phaser.Core.Events#POST_RENDER_EVENT - * @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. - */ - step: function (time, delta) - { - if (this.pendingDestroy) - { - return this.runDestroy(); - } - - var eventEmitter = this.events; - - // Global Managers like Input and Sound update in the prestep - - eventEmitter.emit(Events.PRE_STEP, time, delta); - - // This is mostly meant for user-land code and plugins - - eventEmitter.emit(Events.STEP, time, delta); - - // Update the Scene Manager and all active Scenes - - this.scene.update(time, delta); - - // Our final event before rendering starts - - eventEmitter.emit(Events.POST_STEP, time, delta); - - var renderer = this.renderer; - - // Run the Pre-render (clearing the canvas, setting background colors, etc) - - renderer.preRender(); - - eventEmitter.emit(Events.PRE_RENDER, renderer, time, delta); - - // The main render loop. Iterates all Scenes and all Cameras in those scenes, rendering to the renderer instance. - - this.scene.render(renderer); - - // The Post-Render call. Tidies up loose end, takes snapshots, etc. - - renderer.postRender(); - - // The final event before the step repeats. Your last chance to do anything to the canvas before it all starts again. - - eventEmitter.emit(Events.POST_RENDER, renderer, time, delta); - }, - - /** - * 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.Game#prerenderEvent - * @fires Phaser.Game#postrenderEvent - * @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. - */ - headlessStep: function (time, delta) - { - if (this.pendingDestroy) - { - return this.runDestroy(); - } - - var eventEmitter = this.events; - - // Global Managers - - eventEmitter.emit(Events.PRE_STEP, time, delta); - - eventEmitter.emit(Events.STEP, time, delta); - - // Scenes - - this.scene.update(time, delta); - - eventEmitter.emit(Events.POST_STEP, time, delta); - - // Render - - eventEmitter.emit(Events.PRE_RENDER); - - eventEmitter.emit(Events.POST_RENDER); - }, - - /** - * Called automatically by the Visibility Handler. - * This will pause the main loop and then emit a pause event. - * - * @method Phaser.Game#onHidden - * @protected - * @fires Phaser.Core.Events#PAUSE - * @since 3.0.0 - */ - onHidden: function () - { - this.loop.pause(); - - this.events.emit(Events.PAUSE); - }, - - /** - * Called automatically by the Visibility Handler. - * This will resume the main loop and then emit a resume event. - * - * @method Phaser.Game#onVisible - * @protected - * @fires Phaser.Core.Events#RESUME - * @since 3.0.0 - */ - onVisible: function () - { - this.loop.resume(); - - this.events.emit(Events.RESUME); - }, - - /** - * Called automatically by the Visibility Handler. - * This will set the main loop into a 'blurred' state, which pauses it. - * - * @method Phaser.Game#onBlur - * @protected - * @since 3.0.0 - */ - onBlur: function () - { - this.hasFocus = false; - - this.loop.blur(); - }, - - /** - * Called automatically by the Visibility Handler. - * This will set the main loop into a 'focused' state, which resumes it. - * - * @method Phaser.Game#onFocus - * @protected - * @since 3.0.0 - */ - onFocus: function () - { - this.hasFocus = true; - - this.loop.focus(); - }, - - /** - * Returns the current game frame. - * - * When the game starts running, the frame is incremented every time Request Animation Frame, or Set Timeout, fires. - * - * @method Phaser.Game#getFrame - * @since 3.16.0 - * - * @return {number} The current game frame. - */ - getFrame: function () - { - return this.loop.frame; - }, - - /** - * 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. - */ - getTime: function () - { - return this.loop.now; - }, - - /** - * Flags this Game instance as needing to be destroyed on the _next frame_, making this an asynchronous operation. - * - * It will wait until the current frame has completed and then call `runDestroy` internally. - * - * If you need to react to the games eventual destruction, listen for the `DESTROY` event. - * - * If you **do not** need to run Phaser again on the same web page you can set the `noReturn` argument to `true` and it will free-up - * memory being held by the core Phaser plugins. If you do need to create another game instance on the same page, leave this as `false`. - * - * @method Phaser.Game#destroy - * @fires Phaser.Core.Events#DESTROY - * @since 3.0.0 - * - * @param {boolean} removeCanvas - Set to `true` if you would like the parent canvas element removed from the DOM, or `false` to leave it in place. - * @param {boolean} [noReturn=false] - If `true` all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this. - */ - destroy: function (removeCanvas, noReturn) - { - if (noReturn === undefined) { noReturn = false; } - - this.pendingDestroy = true; - - this.removeCanvas = removeCanvas; - this.noReturn = noReturn; - }, - - /** - * Destroys this Phaser.Game instance, all global systems, all sub-systems and all Scenes. - * - * @method Phaser.Game#runDestroy - * @private - * @since 3.5.0 - */ - runDestroy: function () - { - this.scene.destroy(); - - this.events.emit(Events.DESTROY); - - this.events.removeAllListeners(); - - if (this.renderer) - { - this.renderer.destroy(); - } - - if (this.removeCanvas && this.canvas) - { - CanvasPool.remove(this.canvas); - - if (this.canvas.parentNode) - { - this.canvas.parentNode.removeChild(this.canvas); - } - } - - if (this.domContainer) - { - this.domContainer.parentNode.removeChild(this.domContainer); - } - - this.loop.destroy(); - - this.pendingDestroy = false; - } - -}); - -module.exports = Game; - -/** - * "Computers are good at following instructions, but not at reading your mind." - Donald Knuth - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AddToDOM = require('../dom/AddToDOM'); +var AnimationManager = require('../animations/AnimationManager'); +var CacheManager = require('../cache/CacheManager'); +var CanvasPool = require('../display/canvas/CanvasPool'); +var Class = require('../utils/Class'); +var Config = require('./Config'); +var CreateDOMContainer = require('../dom/CreateDOMContainer'); +var CreateRenderer = require('./CreateRenderer'); +var DataManager = require('../data/DataManager'); +var DebugHeader = require('./DebugHeader'); +var Device = require('../device'); +var DOMContentLoaded = require('../dom/DOMContentLoaded'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var InputManager = require('../input/InputManager'); +var PluginCache = require('../plugins/PluginCache'); +var PluginManager = require('../plugins/PluginManager'); +var ScaleManager = require('../scale/ScaleManager'); +var SceneManager = require('../scene/SceneManager'); +var TextureEvents = require('../textures/events'); +var TextureManager = require('../textures/TextureManager'); +var TimeStep = require('./TimeStep'); +var VisibilityHandler = require('./VisibilityHandler'); + +if (typeof FEATURE_SOUND) +{ + var SoundManagerCreator = require('../sound/SoundManagerCreator'); +} + +if (typeof PLUGIN_FBINSTANT) +{ + var FacebookInstantGamesPlugin = require('../../plugins/fbinstant/src/FacebookInstantGamesPlugin'); +} + +/** + * @classdesc + * The Phaser.Game instance is the main controller for the entire Phaser game. It is responsible + * for handling the boot process, parsing the configuration values, creating the renderer, + * and setting-up all of the global Phaser systems, such as sound and input. + * Once that is complete it will start the Scene Manager and then begin the main game loop. + * + * You should generally avoid accessing any of the systems created by Game, and instead use those + * made available to you via the Phaser.Scene Systems class instead. + * + * @class Game + * @memberof Phaser + * @constructor + * @fires Phaser.Core.Events#BLUR + * @fires Phaser.Core.Events#FOCUS + * @fires Phaser.Core.Events#HIDDEN + * @fires Phaser.Core.Events#VISIBLE + * @since 3.0.0 + * + * @param {Phaser.Types.Core.GameConfig} [GameConfig] - The configuration object for your Phaser Game instance. + */ +var Game = new Class({ + + initialize: + + function Game (config) + { + /** + * The parsed Game Configuration object. + * + * The values stored within this object are read-only and should not be changed at run-time. + * + * @name Phaser.Game#config + * @type {Phaser.Core.Config} + * @readonly + * @since 3.0.0 + */ + this.config = new Config(config); + + /** + * A reference to either the Canvas or WebGL Renderer that this Game is using. + * + * @name Phaser.Game#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.0.0 + */ + this.renderer = null; + + /** + * A reference to an HTML Div Element used as the DOM Element Container. + * + * Only set if `createDOMContainer` is `true` in the game config (by default it is `false`) and + * if you provide a parent element to insert the Phaser Game inside. + * + * See the DOM Element Game Object for more details. + * + * @name Phaser.Game#domContainer + * @type {HTMLDivElement} + * @since 3.17.0 + */ + this.domContainer = null; + + /** + * A reference to the HTML Canvas Element that Phaser uses to render the game. + * This is created automatically by Phaser unless you provide a `canvas` property + * in your Game Config. + * + * @name Phaser.Game#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas = null; + + /** + * A reference to the Rendering Context belonging to the Canvas Element this game is rendering to. + * If the game is running under Canvas it will be a 2d Canvas Rendering Context. + * If the game is running under WebGL it will be a WebGL Rendering Context. + * This context is created automatically by Phaser unless you provide a `context` property + * in your Game Config. + * + * @name Phaser.Game#context + * @type {(CanvasRenderingContext2D|WebGLRenderingContext)} + * @since 3.0.0 + */ + this.context = null; + + /** + * A flag indicating when this Game instance has finished its boot process. + * + * @name Phaser.Game#isBooted + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isBooted = false; + + /** + * A flag indicating if this Game is currently running its game step or not. + * + * @name Phaser.Game#isRunning + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isRunning = false; + + /** + * An Event Emitter which is used to broadcast game-level events from the global systems. + * + * @name Phaser.Game#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = new EventEmitter(); + + /** + * An instance of the Animation Manager. + * + * The Animation Manager is a global system responsible for managing all animations used within your game. + * + * @name Phaser.Game#anims + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.anims = new AnimationManager(this); + + /** + * An instance of the Texture Manager. + * + * The Texture Manager is a global system responsible for managing all textures being used by your game. + * + * @name Phaser.Game#textures + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.textures = new TextureManager(this); + + /** + * An instance of the Cache Manager. + * + * The Cache Manager is a global system responsible for caching, accessing and releasing external game assets. + * + * @name Phaser.Game#cache + * @type {Phaser.Cache.CacheManager} + * @since 3.0.0 + */ + this.cache = new CacheManager(this); + + /** + * An instance of the Data Manager + * + * @name Phaser.Game#registry + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.registry = new DataManager(this); + + /** + * An instance of the Input Manager. + * + * The Input Manager is a global system responsible for the capture of browser-level input events. + * + * @name Phaser.Game#input + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.input = new InputManager(this, this.config); + + /** + * An instance of the Scene Manager. + * + * The Scene Manager is a global system responsible for creating, modifying and updating the Scenes in your game. + * + * @name Phaser.Game#scene + * @type {Phaser.Scenes.SceneManager} + * @since 3.0.0 + */ + this.scene = new SceneManager(this, this.config.sceneConfig); + + /** + * A reference to the Device inspector. + * + * Contains information about the device running this game, such as OS, browser vendor and feature support. + * Used by various systems to determine capabilities and code paths. + * + * @name Phaser.Game#device + * @type {Phaser.DeviceConf} + * @since 3.0.0 + */ + this.device = Device; + + /** + * An instance of the Scale Manager. + * + * The Scale Manager is a global system responsible for handling scaling of the game canvas. + * + * @name Phaser.Game#scale + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.0 + */ + this.scale = new ScaleManager(this, this.config); + + /** + * An instance of the base Sound Manager. + * + * The Sound Manager is a global system responsible for the playback and updating of all audio in your game. + * + * You can disable the inclusion of the Sound Manager in your build by toggling the webpack `FEATURE_SOUND` flag. + * + * @name Phaser.Game#sound + * @type {(Phaser.Sound.NoAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager)} + * @since 3.0.0 + */ + this.sound = null; + + if (typeof FEATURE_SOUND) + { + this.sound = SoundManagerCreator.create(this); + } + + /** + * An instance of the Time Step. + * + * The Time Step is a global system responsible for setting-up and responding to the browser frame events, processing + * them and calculating delta values. It then automatically calls the game step. + * + * @name Phaser.Game#loop + * @type {Phaser.Core.TimeStep} + * @since 3.0.0 + */ + this.loop = new TimeStep(this, this.config.fps); + + /** + * An instance of the Plugin Manager. + * + * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install + * those plugins into Scenes as required. + * + * @name Phaser.Game#plugins + * @type {Phaser.Plugins.PluginManager} + * @since 3.0.0 + */ + this.plugins = new PluginManager(this, this.config); + + if (typeof PLUGIN_FBINSTANT) + { + /** + * An instance of the Facebook Instant Games Plugin. + * + * This will only be available if the plugin has been built into Phaser, + * or you're using the special Facebook Instant Games custom build. + * + * @name Phaser.Game#facebook + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.13.0 + */ + this.facebook = new FacebookInstantGamesPlugin(this); + } + + /** + * Is this Game pending destruction at the start of the next frame? + * + * @name Phaser.Game#pendingDestroy + * @type {boolean} + * @private + * @since 3.5.0 + */ + this.pendingDestroy = false; + + /** + * Remove the Canvas once the destroy is over? + * + * @name Phaser.Game#removeCanvas + * @type {boolean} + * @private + * @since 3.5.0 + */ + this.removeCanvas = false; + + /** + * Remove everything when the game is destroyed. + * You cannot create a new Phaser instance on the same web page after doing this. + * + * @name Phaser.Game#noReturn + * @type {boolean} + * @private + * @since 3.12.0 + */ + this.noReturn = false; + + /** + * Does the window the game is running in currently have focus or not? + * This is modified by the VisibilityHandler. + * + * @name Phaser.Game#hasFocus + * @type {boolean} + * @readonly + * @since 3.9.0 + */ + this.hasFocus = false; + + // Wait for the DOM Ready event, then call boot. + DOMContentLoaded(this.boot.bind(this)); + }, + + /** + * This method is called automatically when the DOM is ready. It is responsible for creating the renderer, + * displaying the Debug Header, adding the game canvas to the DOM and emitting the 'boot' event. + * It listens for a 'ready' event from the base systems and once received it will call `Game.start`. + * + * @method Phaser.Game#boot + * @protected + * @fires Phaser.Core.Events#BOOT + * @listens Phaser.Textures.Events#READY + * @since 3.0.0 + */ + boot: function () + { + if (!PluginCache.hasCore('EventEmitter')) + { + console.warn('Aborting. Core Plugins missing.'); + return; + } + + this.isBooted = true; + + this.config.preBoot(this); + + this.scale.preBoot(); + + CreateRenderer(this); + + CreateDOMContainer(this); + + DebugHeader(this); + + AddToDOM(this.canvas, this.config.parent); + + // 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: + this.textures.once(TextureEvents.READY, this.texturesReady, this); + + this.events.emit(Events.BOOT); + }, + + /** + * Called automatically when the Texture Manager has finished setting up and preparing the + * default textures. + * + * @method Phaser.Game#texturesReady + * @private + * @fires Phaser.Game#ready + * @since 3.12.0 + */ + texturesReady: function () + { + // Start all the other systems + this.events.emit(Events.READY); + + this.start(); + }, + + /** + * Called automatically by Game.boot once all of the global systems have finished setting themselves up. + * By this point the Game is now ready to start the main loop running. + * It will also enable the Visibility Handler. + * + * @method Phaser.Game#start + * @protected + * @since 3.0.0 + */ + start: function () + { + this.isRunning = true; + + this.config.postBoot(this); + + if (this.renderer) + { + this.loop.start(this.step.bind(this)); + } + else + { + this.loop.start(this.headlessStep.bind(this)); + } + + VisibilityHandler(this); + + var eventEmitter = this.events; + + eventEmitter.on(Events.HIDDEN, this.onHidden, this); + eventEmitter.on(Events.VISIBLE, this.onVisible, this); + eventEmitter.on(Events.BLUR, this.onBlur, this); + eventEmitter.on(Events.FOCUS, this.onFocus, this); + }, + + /** + * 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_EVENT + * @fires Phaser.Core.Events#STEP_EVENT + * @fires Phaser.Core.Events#POST_STEP_EVENT + * @fires Phaser.Core.Events#PRE_RENDER_EVENT + * @fires Phaser.Core.Events#POST_RENDER_EVENT + * @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. + */ + step: function (time, delta) + { + if (this.pendingDestroy) + { + return this.runDestroy(); + } + + var eventEmitter = this.events; + + // Global Managers like Input and Sound update in the prestep + + eventEmitter.emit(Events.PRE_STEP, time, delta); + + // This is mostly meant for user-land code and plugins + + eventEmitter.emit(Events.STEP, time, delta); + + // Update the Scene Manager and all active Scenes + + this.scene.update(time, delta); + + // Our final event before rendering starts + + eventEmitter.emit(Events.POST_STEP, time, delta); + + var renderer = this.renderer; + + // Run the Pre-render (clearing the canvas, setting background colors, etc) + + renderer.preRender(); + + eventEmitter.emit(Events.PRE_RENDER, renderer, time, delta); + + // The main render loop. Iterates all Scenes and all Cameras in those scenes, rendering to the renderer instance. + + this.scene.render(renderer); + + // The Post-Render call. Tidies up loose end, takes snapshots, etc. + + renderer.postRender(); + + // The final event before the step repeats. Your last chance to do anything to the canvas before it all starts again. + + eventEmitter.emit(Events.POST_RENDER, renderer, time, delta); + }, + + /** + * 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.Game#prerenderEvent + * @fires Phaser.Game#postrenderEvent + * @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. + */ + headlessStep: function (time, delta) + { + if (this.pendingDestroy) + { + return this.runDestroy(); + } + + var eventEmitter = this.events; + + // Global Managers + + eventEmitter.emit(Events.PRE_STEP, time, delta); + + eventEmitter.emit(Events.STEP, time, delta); + + // Scenes + + this.scene.update(time, delta); + + eventEmitter.emit(Events.POST_STEP, time, delta); + + // Render + + eventEmitter.emit(Events.PRE_RENDER); + + eventEmitter.emit(Events.POST_RENDER); + }, + + /** + * Called automatically by the Visibility Handler. + * This will pause the main loop and then emit a pause event. + * + * @method Phaser.Game#onHidden + * @protected + * @fires Phaser.Core.Events#PAUSE + * @since 3.0.0 + */ + onHidden: function () + { + this.loop.pause(); + + this.events.emit(Events.PAUSE); + }, + + /** + * Called automatically by the Visibility Handler. + * This will resume the main loop and then emit a resume event. + * + * @method Phaser.Game#onVisible + * @protected + * @fires Phaser.Core.Events#RESUME + * @since 3.0.0 + */ + onVisible: function () + { + this.loop.resume(); + + this.events.emit(Events.RESUME); + }, + + /** + * Called automatically by the Visibility Handler. + * This will set the main loop into a 'blurred' state, which pauses it. + * + * @method Phaser.Game#onBlur + * @protected + * @since 3.0.0 + */ + onBlur: function () + { + this.hasFocus = false; + + this.loop.blur(); + }, + + /** + * Called automatically by the Visibility Handler. + * This will set the main loop into a 'focused' state, which resumes it. + * + * @method Phaser.Game#onFocus + * @protected + * @since 3.0.0 + */ + onFocus: function () + { + this.hasFocus = true; + + this.loop.focus(); + }, + + /** + * Returns the current game frame. + * + * When the game starts running, the frame is incremented every time Request Animation Frame, or Set Timeout, fires. + * + * @method Phaser.Game#getFrame + * @since 3.16.0 + * + * @return {number} The current game frame. + */ + getFrame: function () + { + return this.loop.frame; + }, + + /** + * 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. + */ + getTime: function () + { + return this.loop.now; + }, + + /** + * Flags this Game instance as needing to be destroyed on the _next frame_, making this an asynchronous operation. + * + * It will wait until the current frame has completed and then call `runDestroy` internally. + * + * If you need to react to the games eventual destruction, listen for the `DESTROY` event. + * + * If you **do not** need to run Phaser again on the same web page you can set the `noReturn` argument to `true` and it will free-up + * memory being held by the core Phaser plugins. If you do need to create another game instance on the same page, leave this as `false`. + * + * @method Phaser.Game#destroy + * @fires Phaser.Core.Events#DESTROY + * @since 3.0.0 + * + * @param {boolean} removeCanvas - Set to `true` if you would like the parent canvas element removed from the DOM, or `false` to leave it in place. + * @param {boolean} [noReturn=false] - If `true` all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this. + */ + destroy: function (removeCanvas, noReturn) + { + if (noReturn === undefined) { noReturn = false; } + + this.pendingDestroy = true; + + this.removeCanvas = removeCanvas; + this.noReturn = noReturn; + }, + + /** + * Destroys this Phaser.Game instance, all global systems, all sub-systems and all Scenes. + * + * @method Phaser.Game#runDestroy + * @private + * @since 3.5.0 + */ + runDestroy: function () + { + this.scene.destroy(); + + this.events.emit(Events.DESTROY); + + this.events.removeAllListeners(); + + if (this.renderer) + { + this.renderer.destroy(); + } + + if (this.removeCanvas && this.canvas) + { + CanvasPool.remove(this.canvas); + + if (this.canvas.parentNode) + { + this.canvas.parentNode.removeChild(this.canvas); + } + } + + if (this.domContainer) + { + this.domContainer.parentNode.removeChild(this.domContainer); + } + + this.loop.destroy(); + + this.pendingDestroy = false; + } + +}); + +module.exports = Game; + +/** + * "Computers are good at following instructions, but not at reading your mind." - Donald Knuth + */ diff --git a/src/core/TimeStep.js b/src/core/TimeStep.js index fb2846691..b1a3c5cda 100644 --- a/src/core/TimeStep.js +++ b/src/core/TimeStep.js @@ -1,724 +1,724 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var GetValue = require('../utils/object/GetValue'); -var NOOP = require('../utils/NOOP'); -var RequestAnimationFrame = require('../dom/RequestAnimationFrame'); - -// http://www.testufo.com/#test=animation-time-graph - -/** - * @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 - */ -var TimeStep = new Class({ - - initialize: - - function TimeStep (game, config) - { - /** - * A reference to the Phaser.Game instance. - * - * @name Phaser.Core.TimeStep#game - * @type {Phaser.Game} - * @readonly - * @since 3.0.0 - */ - this.game = game; - - /** - * The Request Animation Frame DOM Event handler. - * - * @name Phaser.Core.TimeStep#raf - * @type {Phaser.DOM.RequestAnimationFrame} - * @readonly - * @since 3.0.0 - */ - this.raf = new RequestAnimationFrame(); - - /** - * A flag that is set once the TimeStep has started running and toggled when it stops. - * - * @name Phaser.Core.TimeStep#started - * @type {boolean} - * @readonly - * @default false - * @since 3.0.0 - */ - this.started = false; - - /** - * A flag that is set once the TimeStep has started running and toggled when it stops. - * The difference between this value and `started` is that `running` is toggled when - * the TimeStep is sent to sleep, where-as `started` remains `true`, only changing if - * the TimeStep is actually stopped, not just paused. - * - * @name Phaser.Core.TimeStep#running - * @type {boolean} - * @readonly - * @default false - * @since 3.0.0 - */ - this.running = false; - - /** - * The minimum fps rate you want the Time Step to run at. - * - * @name Phaser.Core.TimeStep#minFps - * @type {integer} - * @default 5 - * @since 3.0.0 - */ - this.minFps = GetValue(config, 'min', 5); - - /** - * The target fps rate for the Time Step to run at. - * - * Setting this value will not actually change the speed at which the browser runs, that is beyond - * the control of Phaser. Instead, it allows you to determine performance issues and if the Time Step - * is spiraling out of control. - * - * @name Phaser.Core.TimeStep#targetFps - * @type {integer} - * @default 60 - * @since 3.0.0 - */ - this.targetFps = GetValue(config, 'target', 60); - - /** - * The minFps value in ms. - * Defaults to 200ms between frames (i.e. super slow!) - * - * @name Phaser.Core.TimeStep#_min - * @type {number} - * @private - * @since 3.0.0 - */ - this._min = 1000 / this.minFps; - - /** - * The targetFps value in ms. - * Defaults to 16.66ms between frames (i.e. normal) - * - * @name Phaser.Core.TimeStep#_target - * @type {number} - * @private - * @since 3.0.0 - */ - this._target = 1000 / this.targetFps; - - /** - * An exponential moving average of the frames per second. - * - * @name Phaser.Core.TimeStep#actualFps - * @type {integer} - * @readonly - * @default 60 - * @since 3.0.0 - */ - this.actualFps = this.targetFps; - - /** - * The time at which the next fps rate update will take place. - * When an fps update happens, the `framesThisSecond` value is reset. - * - * @name Phaser.Core.TimeStep#nextFpsUpdate - * @type {integer} - * @readonly - * @default 0 - * @since 3.0.0 - */ - this.nextFpsUpdate = 0; - - /** - * The number of frames processed this second. - * - * @name Phaser.Core.TimeStep#framesThisSecond - * @type {integer} - * @readonly - * @default 0 - * @since 3.0.0 - */ - this.framesThisSecond = 0; - - /** - * A callback to be invoked each time the Time Step steps. - * - * @name Phaser.Core.TimeStep#callback - * @type {Phaser.Types.Core.TimeStepCallback} - * @default NOOP - * @since 3.0.0 - */ - this.callback = NOOP; - - /** - * You can force the Time Step to use Set Timeout instead of Request Animation Frame by setting - * the `forceSetTimeOut` property to `true` in the Game Configuration object. It cannot be changed at run-time. - * - * @name Phaser.Core.TimeStep#forceSetTimeOut - * @type {boolean} - * @readonly - * @default false - * @since 3.0.0 - */ - this.forceSetTimeOut = GetValue(config, 'forceSetTimeOut', false); - - /** - * The time, calculated at the start of the current step, as smoothed by the delta value. - * - * @name Phaser.Core.TimeStep#time - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.time = 0; - - /** - * The time at which the game started running. This value is adjusted if the game is then - * paused and resumes. - * - * @name Phaser.Core.TimeStep#startTime - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.startTime = 0; - - /** - * The time, as returned by `performance.now` of the previous step. - * - * @name Phaser.Core.TimeStep#lastTime - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.lastTime = 0; - - /** - * The current frame the game is on. This counter is incremented once every game step, regardless of how much - * time has passed and is unaffected by delta smoothing. - * - * @name Phaser.Core.TimeStep#frame - * @type {integer} - * @readonly - * @default 0 - * @since 3.0.0 - */ - this.frame = 0; - - /** - * Is the browser currently considered in focus by the Page Visibility API? - * This value is set in the `blur` method, which is called automatically by the Game instance. - * - * @name Phaser.Core.TimeStep#inFocus - * @type {boolean} - * @readonly - * @default true - * @since 3.0.0 - */ - this.inFocus = true; - - /** - * The timestamp at which the game became paused, as determined by the Page Visibility API. - * - * @name Phaser.Core.TimeStep#_pauseTime - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._pauseTime = 0; - - /** - * An internal counter to allow for the browser 'cooling down' after coming back into focus. - * - * @name Phaser.Core.TimeStep#_coolDown - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - this._coolDown = 0; - - /** - * The delta time, in ms, since the last game step. This is a clamped and smoothed average value. - * - * @name Phaser.Core.TimeStep#delta - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.delta = 0; - - /** - * Internal index of the delta history position. - * - * @name Phaser.Core.TimeStep#deltaIndex - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.deltaIndex = 0; - - /** - * Internal array holding the previous delta values, used for delta smoothing. - * - * @name Phaser.Core.TimeStep#deltaHistory - * @type {integer[]} - * @since 3.0.0 - */ - this.deltaHistory = []; - - /** - * The maximum number of delta values that are retained in order to calculate a smoothed moving average. - * - * This can be changed in the Game Config via the `fps.deltaHistory` property. The default is 10. - * - * @name Phaser.Core.TimeStep#deltaSmoothingMax - * @type {integer} - * @default 10 - * @since 3.0.0 - */ - this.deltaSmoothingMax = GetValue(config, 'deltaHistory', 10); - - /** - * The number of frames that the cooldown is set to after the browser panics over the FPS rate, usually - * as a result of switching tabs and regaining focus. - * - * This can be changed in the Game Config via the `fps.panicMax` property. The default is 120. - * - * @name Phaser.Core.TimeStep#panicMax - * @type {integer} - * @default 120 - * @since 3.0.0 - */ - this.panicMax = GetValue(config, 'panicMax', 120); - - /** - * The actual elapsed time in ms between one update and the next. - * - * Unlike with `delta`, no smoothing, capping, or averaging is applied to this value. - * So please be careful when using this value in math calculations. - * - * @name Phaser.Core.TimeStep#rawDelta - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.rawDelta = 0; - - /** - * The time, as returned by `performance.now` at the very start of the current step. - * 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 - */ - this.now = 0; - - /** - * Apply smoothing to the delta value used within Phasers internal calculations? - * - * This can be changed in the Game Config via the `fps.smoothStep` property. The default is `true`. - * - * Smoothing helps settle down the delta values after browser tab switches, or other situations - * which could cause significant delta spikes or dips. By default it has been enabled in Phaser 3 - * since the first version, but is now exposed under this property (and the corresponding game config - * `smoothStep` value), to allow you to easily disable it, should you require. - * - * @name Phaser.Core.TimeStep#smoothStep - * @type {boolean} - * @since 3.22.0 - */ - this.smoothStep = GetValue(config, 'smoothStep', true); - }, - - /** - * Called by the Game instance when the DOM window.onBlur event triggers. - * - * @method Phaser.Core.TimeStep#blur - * @since 3.0.0 - */ - blur: function () - { - this.inFocus = false; - }, - - /** - * Called by the Game instance when the DOM window.onFocus event triggers. - * - * @method Phaser.Core.TimeStep#focus - * @since 3.0.0 - */ - focus: function () - { - this.inFocus = true; - - this.resetDelta(); - }, - - /** - * Called when the visibility API says the game is 'hidden' (tab switch out of view, etc) - * - * @method Phaser.Core.TimeStep#pause - * @since 3.0.0 - */ - pause: function () - { - this._pauseTime = window.performance.now(); - }, - - /** - * Called when the visibility API says the game is 'visible' again (tab switch back into view, etc) - * - * @method Phaser.Core.TimeStep#resume - * @since 3.0.0 - */ - resume: function () - { - this.resetDelta(); - - this.startTime += this.time - this._pauseTime; - }, - - /** - * Resets the time, lastTime, fps averages and delta history. - * Called automatically when a browser sleeps them resumes. - * - * @method Phaser.Core.TimeStep#resetDelta - * @since 3.0.0 - */ - resetDelta: function () - { - var now = window.performance.now(); - - this.time = now; - this.lastTime = now; - this.nextFpsUpdate = now + 1000; - this.framesThisSecond = 0; - - // Pre-populate smoothing array - - for (var i = 0; i < this.deltaSmoothingMax; i++) - { - this.deltaHistory[i] = Math.min(this._target, this.deltaHistory[i]); - } - - this.delta = 0; - this.deltaIndex = 0; - - this._coolDown = this.panicMax; - }, - - /** - * Starts the Time Step running, if it is not already doing so. - * Called automatically by the Game Boot process. - * - * @method Phaser.Core.TimeStep#start - * @since 3.0.0 - * - * @param {Phaser.Types.Core.TimeStepCallback} callback - The callback to be invoked each time the Time Step steps. - */ - start: function (callback) - { - if (this.started) - { - return this; - } - - this.started = true; - this.running = true; - - for (var i = 0; i < this.deltaSmoothingMax; i++) - { - this.deltaHistory[i] = this._target; - } - - this.resetDelta(); - - this.startTime = window.performance.now(); - - this.callback = callback; - - this.raf.start(this.step.bind(this), this.forceSetTimeOut, this._target); - }, - - /** - * The main step method. This is called each time the browser updates, either by Request Animation Frame, - * or by Set Timeout. It is responsible for calculating the delta values, frame totals, cool down history and more. - * You generally should never call this method directly. - * - * @method Phaser.Core.TimeStep#step - * @since 3.0.0 - */ - step: function () - { - // Because the timestamp passed in from raf represents the beginning of the main thread frame that we’re currently in, - // not the actual time now, and as we want to compare this time value against Event timeStamps and the like, we need a - // more accurate one: - - var time = window.performance.now(); - - this.now = time; - - var before = time - this.lastTime; - - if (before < 0) - { - // Because, Chrome. - before = 0; - } - - this.rawDelta = before; - - var idx = this.deltaIndex; - var history = this.deltaHistory; - var max = this.deltaSmoothingMax; - - // delta time (time is in ms) - var dt = before; - - // Delta Average - var avg = before; - - // When a browser switches tab, then comes back again, it takes around 10 frames before - // the delta time settles down so we employ a 'cooling down' period before we start - // trusting the delta values again, to avoid spikes flooding through our delta average - - if (this.smoothStep) - { - if (this._coolDown > 0 || !this.inFocus) - { - this._coolDown--; - - dt = Math.min(dt, this._target); - } - - if (dt > this._min) - { - // Probably super bad start time or browser tab context loss, - // so use the last 'sane' dt value - - dt = history[idx]; - - // Clamp delta to min (in case history has become corrupted somehow) - dt = Math.min(dt, this._min); - } - - // Smooth out the delta over the previous X frames - - // add the delta to the smoothing array - history[idx] = dt; - - // adjusts the delta history array index based on the smoothing count - // this stops the array growing beyond the size of deltaSmoothingMax - this.deltaIndex++; - - if (this.deltaIndex > max) - { - this.deltaIndex = 0; - } - - // Loop the history array, adding the delta values together - avg = 0; - - for (var i = 0; i < max; i++) - { - avg += history[i]; - } - - // Then divide by the array length to get the average delta - avg /= max; - } - - // Set as the world delta value - this.delta = avg; - - // Real-world timer advance - this.time += this.rawDelta; - - // Update the estimate of the frame rate, `fps`. Every second, the number - // of frames that occurred in that second are included in an exponential - // moving average of all frames per second, with an alpha of 0.25. This - // means that more recent seconds affect the estimated frame rate more than - // older seconds. - // - // When a browser window is NOT minimized, but is covered up (i.e. you're using - // another app which has spawned a window over the top of the browser), then it - // will start to throttle the raf callback time. It waits for a while, and then - // starts to drop the frame rate at 1 frame per second until it's down to just over 1fps. - // So if the game was running at 60fps, and the player opens a new window, then - // after 60 seconds (+ the 'buffer time') it'll be down to 1fps, so rafin'g at 1Hz. - // - // When they make the game visible again, the frame rate is increased at a rate of - // approx. 8fps, back up to 60fps (or the max it can obtain) - // - // There is no easy way to determine if this drop in frame rate is because the - // browser is throttling raf, or because the game is struggling with performance - // because you're asking it to do too much on the device. - - if (time > this.nextFpsUpdate) - { - // Compute the new exponential moving average with an alpha of 0.25. - this.actualFps = 0.25 * this.framesThisSecond + 0.75 * this.actualFps; - this.nextFpsUpdate = time + 1000; - this.framesThisSecond = 0; - } - - this.framesThisSecond++; - - // Interpolation - how far between what is expected and where we are? - var interpolation = avg / this._target; - - this.callback(time, avg, interpolation); - - // Shift time value over - this.lastTime = time; - - this.frame++; - }, - - /** - * Manually calls `TimeStep.step`. - * - * @method Phaser.Core.TimeStep#tick - * @since 3.0.0 - */ - tick: function () - { - this.step(); - }, - - /** - * Sends the TimeStep to sleep, stopping Request Animation Frame (or SetTimeout) and toggling the `running` flag to false. - * - * @method Phaser.Core.TimeStep#sleep - * @since 3.0.0 - */ - sleep: function () - { - if (this.running) - { - this.raf.stop(); - - this.running = false; - } - }, - - /** - * 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. - */ - wake: function (seamless) - { - if (this.running) - { - this.sleep(); - } - else if (seamless) - { - this.startTime += -this.lastTime + (this.lastTime + window.performance.now()); - } - - this.raf.start(this.step.bind(this), this.useRAF); - - this.running = true; - - this.step(); - }, - - /** - * Gets the duration which the game has been running, in seconds. - * - * @method Phaser.Core.TimeStep#getDuration - * @since 3.17.0 - * - * @return {number} The duration in seconds. - */ - getDuration: function () - { - return Math.round(this.lastTime - this.startTime) / 1000; - }, - - /** - * Gets the duration which the game has been running, in ms. - * - * @method Phaser.Core.TimeStep#getDurationMS - * @since 3.17.0 - * - * @return {number} The duration in ms. - */ - getDurationMS: function () - { - return Math.round(this.lastTime - this.startTime); - }, - - /** - * Stops the TimeStep running. - * - * @method Phaser.Core.TimeStep#stop - * @since 3.0.0 - * - * @return {this} The TimeStep object. - */ - stop: function () - { - this.running = false; - this.started = false; - - this.raf.stop(); - - return this; - }, - - /** - * Destroys the TimeStep. This will stop Request Animation Frame, stop the step, clear the callbacks and null - * any objects. - * - * @method Phaser.Core.TimeStep#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.stop(); - - this.callback = NOOP; - - this.raf = null; - this.game = null; - } - -}); - -module.exports = TimeStep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var GetValue = require('../utils/object/GetValue'); +var NOOP = require('../utils/NOOP'); +var RequestAnimationFrame = require('../dom/RequestAnimationFrame'); + +// http://www.testufo.com/#test=animation-time-graph + +/** + * @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 + */ +var TimeStep = new Class({ + + initialize: + + function TimeStep (game, config) + { + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.Core.TimeStep#game + * @type {Phaser.Game} + * @readonly + * @since 3.0.0 + */ + this.game = game; + + /** + * The Request Animation Frame DOM Event handler. + * + * @name Phaser.Core.TimeStep#raf + * @type {Phaser.DOM.RequestAnimationFrame} + * @readonly + * @since 3.0.0 + */ + this.raf = new RequestAnimationFrame(); + + /** + * A flag that is set once the TimeStep has started running and toggled when it stops. + * + * @name Phaser.Core.TimeStep#started + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.started = false; + + /** + * A flag that is set once the TimeStep has started running and toggled when it stops. + * The difference between this value and `started` is that `running` is toggled when + * the TimeStep is sent to sleep, where-as `started` remains `true`, only changing if + * the TimeStep is actually stopped, not just paused. + * + * @name Phaser.Core.TimeStep#running + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.running = false; + + /** + * The minimum fps rate you want the Time Step to run at. + * + * @name Phaser.Core.TimeStep#minFps + * @type {integer} + * @default 5 + * @since 3.0.0 + */ + this.minFps = GetValue(config, 'min', 5); + + /** + * The target fps rate for the Time Step to run at. + * + * Setting this value will not actually change the speed at which the browser runs, that is beyond + * the control of Phaser. Instead, it allows you to determine performance issues and if the Time Step + * is spiraling out of control. + * + * @name Phaser.Core.TimeStep#targetFps + * @type {integer} + * @default 60 + * @since 3.0.0 + */ + this.targetFps = GetValue(config, 'target', 60); + + /** + * The minFps value in ms. + * Defaults to 200ms between frames (i.e. super slow!) + * + * @name Phaser.Core.TimeStep#_min + * @type {number} + * @private + * @since 3.0.0 + */ + this._min = 1000 / this.minFps; + + /** + * The targetFps value in ms. + * Defaults to 16.66ms between frames (i.e. normal) + * + * @name Phaser.Core.TimeStep#_target + * @type {number} + * @private + * @since 3.0.0 + */ + this._target = 1000 / this.targetFps; + + /** + * An exponential moving average of the frames per second. + * + * @name Phaser.Core.TimeStep#actualFps + * @type {integer} + * @readonly + * @default 60 + * @since 3.0.0 + */ + this.actualFps = this.targetFps; + + /** + * The time at which the next fps rate update will take place. + * When an fps update happens, the `framesThisSecond` value is reset. + * + * @name Phaser.Core.TimeStep#nextFpsUpdate + * @type {integer} + * @readonly + * @default 0 + * @since 3.0.0 + */ + this.nextFpsUpdate = 0; + + /** + * The number of frames processed this second. + * + * @name Phaser.Core.TimeStep#framesThisSecond + * @type {integer} + * @readonly + * @default 0 + * @since 3.0.0 + */ + this.framesThisSecond = 0; + + /** + * A callback to be invoked each time the Time Step steps. + * + * @name Phaser.Core.TimeStep#callback + * @type {Phaser.Types.Core.TimeStepCallback} + * @default NOOP + * @since 3.0.0 + */ + this.callback = NOOP; + + /** + * You can force the Time Step to use Set Timeout instead of Request Animation Frame by setting + * the `forceSetTimeOut` property to `true` in the Game Configuration object. It cannot be changed at run-time. + * + * @name Phaser.Core.TimeStep#forceSetTimeOut + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.forceSetTimeOut = GetValue(config, 'forceSetTimeOut', false); + + /** + * The time, calculated at the start of the current step, as smoothed by the delta value. + * + * @name Phaser.Core.TimeStep#time + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.time = 0; + + /** + * The time at which the game started running. This value is adjusted if the game is then + * paused and resumes. + * + * @name Phaser.Core.TimeStep#startTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.startTime = 0; + + /** + * The time, as returned by `performance.now` of the previous step. + * + * @name Phaser.Core.TimeStep#lastTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.lastTime = 0; + + /** + * The current frame the game is on. This counter is incremented once every game step, regardless of how much + * time has passed and is unaffected by delta smoothing. + * + * @name Phaser.Core.TimeStep#frame + * @type {integer} + * @readonly + * @default 0 + * @since 3.0.0 + */ + this.frame = 0; + + /** + * Is the browser currently considered in focus by the Page Visibility API? + * This value is set in the `blur` method, which is called automatically by the Game instance. + * + * @name Phaser.Core.TimeStep#inFocus + * @type {boolean} + * @readonly + * @default true + * @since 3.0.0 + */ + this.inFocus = true; + + /** + * The timestamp at which the game became paused, as determined by the Page Visibility API. + * + * @name Phaser.Core.TimeStep#_pauseTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._pauseTime = 0; + + /** + * An internal counter to allow for the browser 'cooling down' after coming back into focus. + * + * @name Phaser.Core.TimeStep#_coolDown + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._coolDown = 0; + + /** + * The delta time, in ms, since the last game step. This is a clamped and smoothed average value. + * + * @name Phaser.Core.TimeStep#delta + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.delta = 0; + + /** + * Internal index of the delta history position. + * + * @name Phaser.Core.TimeStep#deltaIndex + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.deltaIndex = 0; + + /** + * Internal array holding the previous delta values, used for delta smoothing. + * + * @name Phaser.Core.TimeStep#deltaHistory + * @type {integer[]} + * @since 3.0.0 + */ + this.deltaHistory = []; + + /** + * The maximum number of delta values that are retained in order to calculate a smoothed moving average. + * + * This can be changed in the Game Config via the `fps.deltaHistory` property. The default is 10. + * + * @name Phaser.Core.TimeStep#deltaSmoothingMax + * @type {integer} + * @default 10 + * @since 3.0.0 + */ + this.deltaSmoothingMax = GetValue(config, 'deltaHistory', 10); + + /** + * The number of frames that the cooldown is set to after the browser panics over the FPS rate, usually + * as a result of switching tabs and regaining focus. + * + * This can be changed in the Game Config via the `fps.panicMax` property. The default is 120. + * + * @name Phaser.Core.TimeStep#panicMax + * @type {integer} + * @default 120 + * @since 3.0.0 + */ + this.panicMax = GetValue(config, 'panicMax', 120); + + /** + * The actual elapsed time in ms between one update and the next. + * + * Unlike with `delta`, no smoothing, capping, or averaging is applied to this value. + * So please be careful when using this value in math calculations. + * + * @name Phaser.Core.TimeStep#rawDelta + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.rawDelta = 0; + + /** + * The time, as returned by `performance.now` at the very start of the current step. + * 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 + */ + this.now = 0; + + /** + * Apply smoothing to the delta value used within Phasers internal calculations? + * + * This can be changed in the Game Config via the `fps.smoothStep` property. The default is `true`. + * + * Smoothing helps settle down the delta values after browser tab switches, or other situations + * which could cause significant delta spikes or dips. By default it has been enabled in Phaser 3 + * since the first version, but is now exposed under this property (and the corresponding game config + * `smoothStep` value), to allow you to easily disable it, should you require. + * + * @name Phaser.Core.TimeStep#smoothStep + * @type {boolean} + * @since 3.22.0 + */ + this.smoothStep = GetValue(config, 'smoothStep', true); + }, + + /** + * Called by the Game instance when the DOM window.onBlur event triggers. + * + * @method Phaser.Core.TimeStep#blur + * @since 3.0.0 + */ + blur: function () + { + this.inFocus = false; + }, + + /** + * Called by the Game instance when the DOM window.onFocus event triggers. + * + * @method Phaser.Core.TimeStep#focus + * @since 3.0.0 + */ + focus: function () + { + this.inFocus = true; + + this.resetDelta(); + }, + + /** + * Called when the visibility API says the game is 'hidden' (tab switch out of view, etc) + * + * @method Phaser.Core.TimeStep#pause + * @since 3.0.0 + */ + pause: function () + { + this._pauseTime = window.performance.now(); + }, + + /** + * Called when the visibility API says the game is 'visible' again (tab switch back into view, etc) + * + * @method Phaser.Core.TimeStep#resume + * @since 3.0.0 + */ + resume: function () + { + this.resetDelta(); + + this.startTime += this.time - this._pauseTime; + }, + + /** + * Resets the time, lastTime, fps averages and delta history. + * Called automatically when a browser sleeps them resumes. + * + * @method Phaser.Core.TimeStep#resetDelta + * @since 3.0.0 + */ + resetDelta: function () + { + var now = window.performance.now(); + + this.time = now; + this.lastTime = now; + this.nextFpsUpdate = now + 1000; + this.framesThisSecond = 0; + + // Pre-populate smoothing array + + for (var i = 0; i < this.deltaSmoothingMax; i++) + { + this.deltaHistory[i] = Math.min(this._target, this.deltaHistory[i]); + } + + this.delta = 0; + this.deltaIndex = 0; + + this._coolDown = this.panicMax; + }, + + /** + * Starts the Time Step running, if it is not already doing so. + * Called automatically by the Game Boot process. + * + * @method Phaser.Core.TimeStep#start + * @since 3.0.0 + * + * @param {Phaser.Types.Core.TimeStepCallback} callback - The callback to be invoked each time the Time Step steps. + */ + start: function (callback) + { + if (this.started) + { + return this; + } + + this.started = true; + this.running = true; + + for (var i = 0; i < this.deltaSmoothingMax; i++) + { + this.deltaHistory[i] = this._target; + } + + this.resetDelta(); + + this.startTime = window.performance.now(); + + this.callback = callback; + + this.raf.start(this.step.bind(this), this.forceSetTimeOut, this._target); + }, + + /** + * The main step method. This is called each time the browser updates, either by Request Animation Frame, + * or by Set Timeout. It is responsible for calculating the delta values, frame totals, cool down history and more. + * You generally should never call this method directly. + * + * @method Phaser.Core.TimeStep#step + * @since 3.0.0 + */ + step: function () + { + // Because the timestamp passed in from raf represents the beginning of the main thread frame that we’re currently in, + // not the actual time now, and as we want to compare this time value against Event timeStamps and the like, we need a + // more accurate one: + + var time = window.performance.now(); + + this.now = time; + + var before = time - this.lastTime; + + if (before < 0) + { + // Because, Chrome. + before = 0; + } + + this.rawDelta = before; + + var idx = this.deltaIndex; + var history = this.deltaHistory; + var max = this.deltaSmoothingMax; + + // delta time (time is in ms) + var dt = before; + + // Delta Average + var avg = before; + + // When a browser switches tab, then comes back again, it takes around 10 frames before + // the delta time settles down so we employ a 'cooling down' period before we start + // trusting the delta values again, to avoid spikes flooding through our delta average + + if (this.smoothStep) + { + if (this._coolDown > 0 || !this.inFocus) + { + this._coolDown--; + + dt = Math.min(dt, this._target); + } + + if (dt > this._min) + { + // Probably super bad start time or browser tab context loss, + // so use the last 'sane' dt value + + dt = history[idx]; + + // Clamp delta to min (in case history has become corrupted somehow) + dt = Math.min(dt, this._min); + } + + // Smooth out the delta over the previous X frames + + // add the delta to the smoothing array + history[idx] = dt; + + // adjusts the delta history array index based on the smoothing count + // this stops the array growing beyond the size of deltaSmoothingMax + this.deltaIndex++; + + if (this.deltaIndex > max) + { + this.deltaIndex = 0; + } + + // Loop the history array, adding the delta values together + avg = 0; + + for (var i = 0; i < max; i++) + { + avg += history[i]; + } + + // Then divide by the array length to get the average delta + avg /= max; + } + + // Set as the world delta value + this.delta = avg; + + // Real-world timer advance + this.time += this.rawDelta; + + // Update the estimate of the frame rate, `fps`. Every second, the number + // of frames that occurred in that second are included in an exponential + // moving average of all frames per second, with an alpha of 0.25. This + // means that more recent seconds affect the estimated frame rate more than + // older seconds. + // + // When a browser window is NOT minimized, but is covered up (i.e. you're using + // another app which has spawned a window over the top of the browser), then it + // will start to throttle the raf callback time. It waits for a while, and then + // starts to drop the frame rate at 1 frame per second until it's down to just over 1fps. + // So if the game was running at 60fps, and the player opens a new window, then + // after 60 seconds (+ the 'buffer time') it'll be down to 1fps, so rafin'g at 1Hz. + // + // When they make the game visible again, the frame rate is increased at a rate of + // approx. 8fps, back up to 60fps (or the max it can obtain) + // + // There is no easy way to determine if this drop in frame rate is because the + // browser is throttling raf, or because the game is struggling with performance + // because you're asking it to do too much on the device. + + if (time > this.nextFpsUpdate) + { + // Compute the new exponential moving average with an alpha of 0.25. + this.actualFps = 0.25 * this.framesThisSecond + 0.75 * this.actualFps; + this.nextFpsUpdate = time + 1000; + this.framesThisSecond = 0; + } + + this.framesThisSecond++; + + // Interpolation - how far between what is expected and where we are? + var interpolation = avg / this._target; + + this.callback(time, avg, interpolation); + + // Shift time value over + this.lastTime = time; + + this.frame++; + }, + + /** + * Manually calls `TimeStep.step`. + * + * @method Phaser.Core.TimeStep#tick + * @since 3.0.0 + */ + tick: function () + { + this.step(); + }, + + /** + * Sends the TimeStep to sleep, stopping Request Animation Frame (or SetTimeout) and toggling the `running` flag to false. + * + * @method Phaser.Core.TimeStep#sleep + * @since 3.0.0 + */ + sleep: function () + { + if (this.running) + { + this.raf.stop(); + + this.running = false; + } + }, + + /** + * 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. + */ + wake: function (seamless) + { + if (this.running) + { + this.sleep(); + } + else if (seamless) + { + this.startTime += -this.lastTime + (this.lastTime + window.performance.now()); + } + + this.raf.start(this.step.bind(this), this.useRAF); + + this.running = true; + + this.step(); + }, + + /** + * Gets the duration which the game has been running, in seconds. + * + * @method Phaser.Core.TimeStep#getDuration + * @since 3.17.0 + * + * @return {number} The duration in seconds. + */ + getDuration: function () + { + return Math.round(this.lastTime - this.startTime) / 1000; + }, + + /** + * Gets the duration which the game has been running, in ms. + * + * @method Phaser.Core.TimeStep#getDurationMS + * @since 3.17.0 + * + * @return {number} The duration in ms. + */ + getDurationMS: function () + { + return Math.round(this.lastTime - this.startTime); + }, + + /** + * Stops the TimeStep running. + * + * @method Phaser.Core.TimeStep#stop + * @since 3.0.0 + * + * @return {this} The TimeStep object. + */ + stop: function () + { + this.running = false; + this.started = false; + + this.raf.stop(); + + return this; + }, + + /** + * Destroys the TimeStep. This will stop Request Animation Frame, stop the step, clear the callbacks and null + * any objects. + * + * @method Phaser.Core.TimeStep#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stop(); + + this.callback = NOOP; + + this.raf = null; + this.game = null; + } + +}); + +module.exports = TimeStep; diff --git a/src/core/VisibilityHandler.js b/src/core/VisibilityHandler.js index 84e92fdbf..d01aa68e5 100644 --- a/src/core/VisibilityHandler.js +++ b/src/core/VisibilityHandler.js @@ -1,85 +1,85 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Events = require('./events'); - -/** - * The Visibility Handler is responsible for listening out for document level visibility change events. - * This includes `visibilitychange` if the browser supports it, and blur and focus events. It then uses - * the provided Event Emitter and fires the related events. - * - * @function Phaser.Core.VisibilityHandler - * @fires Phaser.Core.Events#BLUR - * @fires Phaser.Core.Events#FOCUS - * @fires Phaser.Core.Events#HIDDEN - * @fires Phaser.Core.Events#VISIBLE - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Game instance this Visibility Handler is working on. - */ -var VisibilityHandler = function (game) -{ - var hiddenVar; - var eventEmitter = game.events; - - if (document.hidden !== undefined) - { - hiddenVar = 'visibilitychange'; - } - else - { - var vendors = [ 'webkit', 'moz', 'ms' ]; - - vendors.forEach(function (prefix) - { - if (document[prefix + 'Hidden'] !== undefined) - { - document.hidden = function () - { - return document[prefix + 'Hidden']; - }; - - hiddenVar = prefix + 'visibilitychange'; - } - - }); - } - - var onChange = function (event) - { - if (document.hidden || event.type === 'pause') - { - eventEmitter.emit(Events.HIDDEN); - } - else - { - eventEmitter.emit(Events.VISIBLE); - } - }; - - if (hiddenVar) - { - document.addEventListener(hiddenVar, onChange, false); - } - - window.onblur = function () - { - eventEmitter.emit(Events.BLUR); - }; - - window.onfocus = function () - { - eventEmitter.emit(Events.FOCUS); - }; - - // Automatically give the window focus unless config says otherwise - if (window.focus && game.config.autoFocus) - { - window.focus(); - } -}; - -module.exports = VisibilityHandler; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Events = require('./events'); + +/** + * The Visibility Handler is responsible for listening out for document level visibility change events. + * This includes `visibilitychange` if the browser supports it, and blur and focus events. It then uses + * the provided Event Emitter and fires the related events. + * + * @function Phaser.Core.VisibilityHandler + * @fires Phaser.Core.Events#BLUR + * @fires Phaser.Core.Events#FOCUS + * @fires Phaser.Core.Events#HIDDEN + * @fires Phaser.Core.Events#VISIBLE + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Game instance this Visibility Handler is working on. + */ +var VisibilityHandler = function (game) +{ + var hiddenVar; + var eventEmitter = game.events; + + if (document.hidden !== undefined) + { + hiddenVar = 'visibilitychange'; + } + else + { + var vendors = [ 'webkit', 'moz', 'ms' ]; + + vendors.forEach(function (prefix) + { + if (document[prefix + 'Hidden'] !== undefined) + { + document.hidden = function () + { + return document[prefix + 'Hidden']; + }; + + hiddenVar = prefix + 'visibilitychange'; + } + + }); + } + + var onChange = function (event) + { + if (document.hidden || event.type === 'pause') + { + eventEmitter.emit(Events.HIDDEN); + } + else + { + eventEmitter.emit(Events.VISIBLE); + } + }; + + if (hiddenVar) + { + document.addEventListener(hiddenVar, onChange, false); + } + + window.onblur = function () + { + eventEmitter.emit(Events.BLUR); + }; + + window.onfocus = function () + { + eventEmitter.emit(Events.FOCUS); + }; + + // Automatically give the window focus unless config says otherwise + if (window.focus && game.config.autoFocus) + { + window.focus(); + } +}; + +module.exports = VisibilityHandler; diff --git a/src/core/events/BLUR_EVENT.js b/src/core/events/BLUR_EVENT.js index 70ed78c88..f03ddce55 100644 --- a/src/core/events/BLUR_EVENT.js +++ b/src/core/events/BLUR_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Blur Event. - * - * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded - * enters a blurred state. The blur event is raised when the window loses focus. This can happen if a user swaps - * tab, or if they simply remove focus from the browser to another app. - * - * @event Phaser.Core.Events#BLUR - * @since 3.0.0 - */ -module.exports = 'blur'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Blur Event. + * + * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded + * enters a blurred state. The blur event is raised when the window loses focus. This can happen if a user swaps + * tab, or if they simply remove focus from the browser to another app. + * + * @event Phaser.Core.Events#BLUR + * @since 3.0.0 + */ +module.exports = 'blur'; diff --git a/src/core/events/BOOT_EVENT.js b/src/core/events/BOOT_EVENT.js index a0c0d98e0..4cb65f254 100644 --- a/src/core/events/BOOT_EVENT.js +++ b/src/core/events/BOOT_EVENT.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Boot Event. - * - * This event is dispatched when the Phaser Game instance has finished booting, but before it is ready to start running. - * The global systems use this event to know when to set themselves up, dispatching their own `ready` events as required. - * - * @event Phaser.Core.Events#BOOT - * @since 3.0.0 - */ -module.exports = 'boot'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Boot Event. + * + * This event is dispatched when the Phaser Game instance has finished booting, but before it is ready to start running. + * The global systems use this event to know when to set themselves up, dispatching their own `ready` events as required. + * + * @event Phaser.Core.Events#BOOT + * @since 3.0.0 + */ +module.exports = 'boot'; diff --git a/src/core/events/CONTEXT_LOST_EVENT.js b/src/core/events/CONTEXT_LOST_EVENT.js index b02b36590..e1f641c01 100644 --- a/src/core/events/CONTEXT_LOST_EVENT.js +++ b/src/core/events/CONTEXT_LOST_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Context Lost Event. - * - * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Lost event from the browser. - * - * The partner event is `CONTEXT_RESTORED`. - * - * @event Phaser.Core.Events#CONTEXT_LOST - * @since 3.19.0 - */ -module.exports = 'contextlost'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Context Lost Event. + * + * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Lost event from the browser. + * + * The partner event is `CONTEXT_RESTORED`. + * + * @event Phaser.Core.Events#CONTEXT_LOST + * @since 3.19.0 + */ +module.exports = 'contextlost'; diff --git a/src/core/events/CONTEXT_RESTORED_EVENT.js b/src/core/events/CONTEXT_RESTORED_EVENT.js index 013aafa4f..e27e4758e 100644 --- a/src/core/events/CONTEXT_RESTORED_EVENT.js +++ b/src/core/events/CONTEXT_RESTORED_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Context Restored Event. - * - * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Restored event from the browser. - * - * The partner event is `CONTEXT_LOST`. - * - * @event Phaser.Core.Events#CONTEXT_RESTORED - * @since 3.19.0 - */ -module.exports = 'contextrestored'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Context Restored Event. + * + * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Restored event from the browser. + * + * The partner event is `CONTEXT_LOST`. + * + * @event Phaser.Core.Events#CONTEXT_RESTORED + * @since 3.19.0 + */ +module.exports = 'contextrestored'; diff --git a/src/core/events/DESTROY_EVENT.js b/src/core/events/DESTROY_EVENT.js index b85a912ad..246ea627c 100644 --- a/src/core/events/DESTROY_EVENT.js +++ b/src/core/events/DESTROY_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Destroy Event. - * - * This event is dispatched when the game instance has been told to destroy itself. - * Lots of internal systems listen to this event in order to clear themselves out. - * Custom plugins and game code should also do the same. - * - * @event Phaser.Core.Events#DESTROY - * @since 3.0.0 - */ -module.exports = 'destroy'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Destroy Event. + * + * This event is dispatched when the game instance has been told to destroy itself. + * Lots of internal systems listen to this event in order to clear themselves out. + * Custom plugins and game code should also do the same. + * + * @event Phaser.Core.Events#DESTROY + * @since 3.0.0 + */ +module.exports = 'destroy'; diff --git a/src/core/events/FOCUS_EVENT.js b/src/core/events/FOCUS_EVENT.js index d8ca467a0..3b935a4e1 100644 --- a/src/core/events/FOCUS_EVENT.js +++ b/src/core/events/FOCUS_EVENT.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Focus Event. - * - * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded - * enters a focused state. The focus event is raised when the window re-gains focus, having previously lost it. - * - * @event Phaser.Core.Events#FOCUS - * @since 3.0.0 - */ -module.exports = 'focus'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Focus Event. + * + * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded + * enters a focused state. The focus event is raised when the window re-gains focus, having previously lost it. + * + * @event Phaser.Core.Events#FOCUS + * @since 3.0.0 + */ +module.exports = 'focus'; diff --git a/src/core/events/HIDDEN_EVENT.js b/src/core/events/HIDDEN_EVENT.js index 85954c80e..acd6a530e 100644 --- a/src/core/events/HIDDEN_EVENT.js +++ b/src/core/events/HIDDEN_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Hidden Event. - * - * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded - * enters a hidden state. Only browsers that support the Visibility API will cause this event to be emitted. - * - * In most modern browsers, when the document enters a hidden state, the Request Animation Frame and setTimeout, which - * control the main game loop, will automatically pause. There is no way to stop this from happening. It is something - * your game should account for in its own code, should the pause be an issue (i.e. for multiplayer games) - * - * @event Phaser.Core.Events#HIDDEN - * @since 3.0.0 - */ -module.exports = 'hidden'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Hidden Event. + * + * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded + * enters a hidden state. Only browsers that support the Visibility API will cause this event to be emitted. + * + * In most modern browsers, when the document enters a hidden state, the Request Animation Frame and setTimeout, which + * control the main game loop, will automatically pause. There is no way to stop this from happening. It is something + * your game should account for in its own code, should the pause be an issue (i.e. for multiplayer games) + * + * @event Phaser.Core.Events#HIDDEN + * @since 3.0.0 + */ +module.exports = 'hidden'; diff --git a/src/core/events/PAUSE_EVENT.js b/src/core/events/PAUSE_EVENT.js index 658c26063..4e2c8e13a 100644 --- a/src/core/events/PAUSE_EVENT.js +++ b/src/core/events/PAUSE_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Pause Event. - * - * This event is dispatched when the Game loop enters a paused state, usually as a result of the Visibility Handler. - * - * @event Phaser.Core.Events#PAUSE - * @since 3.0.0 - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Pause Event. + * + * This event is dispatched when the Game loop enters a paused state, usually as a result of the Visibility Handler. + * + * @event Phaser.Core.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; diff --git a/src/core/events/POST_RENDER_EVENT.js b/src/core/events/POST_RENDER_EVENT.js index 80ed9b758..f3f19e176 100644 --- a/src/core/events/POST_RENDER_EVENT.js +++ b/src/core/events/POST_RENDER_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Post-Render Event. - * - * This event is dispatched right at the end of the render process. - * - * Every Scene will have rendered and been drawn to the canvas by the time this event is fired. - * Use it for any last minute post-processing before the next game step begins. - * - * @event Phaser.Core.Events#POST_RENDER - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - A reference to the current renderer being used by the Game instance. - */ -module.exports = 'postrender'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Post-Render Event. + * + * This event is dispatched right at the end of the render process. + * + * Every Scene will have rendered and been drawn to the canvas by the time this event is fired. + * Use it for any last minute post-processing before the next game step begins. + * + * @event Phaser.Core.Events#POST_RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - A reference to the current renderer being used by the Game instance. + */ +module.exports = 'postrender'; diff --git a/src/core/events/POST_STEP_EVENT.js b/src/core/events/POST_STEP_EVENT.js index 2e4eb6957..912282e3e 100644 --- a/src/core/events/POST_STEP_EVENT.js +++ b/src/core/events/POST_STEP_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'poststep'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'poststep'; diff --git a/src/core/events/PRE_RENDER_EVENT.js b/src/core/events/PRE_RENDER_EVENT.js index 9f62ae71d..70c0c0e1c 100644 --- a/src/core/events/PRE_RENDER_EVENT.js +++ b/src/core/events/PRE_RENDER_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Pre-Render Event. - * - * This event is dispatched immediately before any of the Scenes have started to render. - * - * The renderer will already have been initialized this frame, clearing itself and preparing to receive the Scenes for rendering, but it won't have actually drawn anything yet. - * - * @event Phaser.Core.Events#PRE_RENDER - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - A reference to the current renderer being used by the Game instance. - */ -module.exports = 'prerender'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Pre-Render Event. + * + * This event is dispatched immediately before any of the Scenes have started to render. + * + * The renderer will already have been initialized this frame, clearing itself and preparing to receive the Scenes for rendering, but it won't have actually drawn anything yet. + * + * @event Phaser.Core.Events#PRE_RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - A reference to the current renderer being used by the Game instance. + */ +module.exports = 'prerender'; diff --git a/src/core/events/PRE_STEP_EVENT.js b/src/core/events/PRE_STEP_EVENT.js index 2c3eaafe8..1eb54eb40 100644 --- a/src/core/events/PRE_STEP_EVENT.js +++ b/src/core/events/PRE_STEP_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'prestep'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'prestep'; diff --git a/src/core/events/READY_EVENT.js b/src/core/events/READY_EVENT.js index 41ae33171..ba0839d48 100644 --- a/src/core/events/READY_EVENT.js +++ b/src/core/events/READY_EVENT.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Ready Event. - * - * This event is dispatched when the Phaser Game instance has finished booting, the Texture Manager is fully ready, - * and all local systems are now able to start. - * - * @event Phaser.Core.Events#READY - * @since 3.0.0 - */ -module.exports = 'ready'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Ready Event. + * + * This event is dispatched when the Phaser Game instance has finished booting, the Texture Manager is fully ready, + * and all local systems are now able to start. + * + * @event Phaser.Core.Events#READY + * @since 3.0.0 + */ +module.exports = 'ready'; diff --git a/src/core/events/RESUME_EVENT.js b/src/core/events/RESUME_EVENT.js index bd9b2bafe..405f551a4 100644 --- a/src/core/events/RESUME_EVENT.js +++ b/src/core/events/RESUME_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Resume Event. - * - * This event is dispatched when the game loop leaves a paused state and resumes running. - * - * @event Phaser.Core.Events#RESUME - * @since 3.0.0 - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Resume Event. + * + * This event is dispatched when the game loop leaves a paused state and resumes running. + * + * @event Phaser.Core.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; diff --git a/src/core/events/STEP_EVENT.js b/src/core/events/STEP_EVENT.js index 02a93f4ea..0fa7b1ec9 100644 --- a/src/core/events/STEP_EVENT.js +++ b/src/core/events/STEP_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'step'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'step'; diff --git a/src/core/events/VISIBLE_EVENT.js b/src/core/events/VISIBLE_EVENT.js index 1382bd9db..fea1d7607 100644 --- a/src/core/events/VISIBLE_EVENT.js +++ b/src/core/events/VISIBLE_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Visible Event. - * - * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded - * enters a visible state, previously having been hidden. - * - * Only browsers that support the Visibility API will cause this event to be emitted. - * - * @event Phaser.Core.Events#VISIBLE - * @since 3.0.0 - */ -module.exports = 'visible'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Visible Event. + * + * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded + * enters a visible state, previously having been hidden. + * + * Only browsers that support the Visibility API will cause this event to be emitted. + * + * @event Phaser.Core.Events#VISIBLE + * @since 3.0.0 + */ +module.exports = 'visible'; diff --git a/src/core/events/index.js b/src/core/events/index.js index 825dbea89..23a5be259 100644 --- a/src/core/events/index.js +++ b/src/core/events/index.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Core.Events - */ - -module.exports = { - - BLUR: require('./BLUR_EVENT'), - BOOT: require('./BOOT_EVENT'), - CONTEXT_LOST: require('./CONTEXT_LOST_EVENT'), - CONTEXT_RESTORED: require('./CONTEXT_RESTORED_EVENT'), - DESTROY: require('./DESTROY_EVENT'), - FOCUS: require('./FOCUS_EVENT'), - HIDDEN: require('./HIDDEN_EVENT'), - PAUSE: require('./PAUSE_EVENT'), - POST_RENDER: require('./POST_RENDER_EVENT'), - POST_STEP: require('./POST_STEP_EVENT'), - PRE_RENDER: require('./PRE_RENDER_EVENT'), - PRE_STEP: require('./PRE_STEP_EVENT'), - READY: require('./READY_EVENT'), - RESUME: require('./RESUME_EVENT'), - STEP: require('./STEP_EVENT'), - VISIBLE: require('./VISIBLE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Core.Events + */ + +module.exports = { + + BLUR: require('./BLUR_EVENT'), + BOOT: require('./BOOT_EVENT'), + CONTEXT_LOST: require('./CONTEXT_LOST_EVENT'), + CONTEXT_RESTORED: require('./CONTEXT_RESTORED_EVENT'), + DESTROY: require('./DESTROY_EVENT'), + FOCUS: require('./FOCUS_EVENT'), + HIDDEN: require('./HIDDEN_EVENT'), + PAUSE: require('./PAUSE_EVENT'), + POST_RENDER: require('./POST_RENDER_EVENT'), + POST_STEP: require('./POST_STEP_EVENT'), + PRE_RENDER: require('./PRE_RENDER_EVENT'), + PRE_STEP: require('./PRE_STEP_EVENT'), + READY: require('./READY_EVENT'), + RESUME: require('./RESUME_EVENT'), + STEP: require('./STEP_EVENT'), + VISIBLE: require('./VISIBLE_EVENT') + +}; diff --git a/src/core/index.js b/src/core/index.js index 1c0422af3..1fe2eb64b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Core - */ - -module.exports = { - - Config: require('./Config'), - CreateRenderer: require('./CreateRenderer'), - DebugHeader: require('./DebugHeader'), - Events: require('./events'), - TimeStep: require('./TimeStep'), - VisibilityHandler: require('./VisibilityHandler') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Core + */ + +module.exports = { + + Config: require('./Config'), + CreateRenderer: require('./CreateRenderer'), + DebugHeader: require('./DebugHeader'), + Events: require('./events'), + TimeStep: require('./TimeStep'), + VisibilityHandler: require('./VisibilityHandler') + +}; diff --git a/src/core/typedefs/PhysicsConfig.js b/src/core/typedefs/PhysicsConfig.js index 6f0c785a8..cea477cf0 100644 --- a/src/core/typedefs/PhysicsConfig.js +++ b/src/core/typedefs/PhysicsConfig.js @@ -1,8 +1,8 @@ -/** - * @typedef {object} Phaser.Types.Core.PhysicsConfig - * @since 3.0.0 - * - * @property {string} [default] - The default physics system. It will be started for each scene. Phaser provides 'arcade', 'impact', and 'matter'. - * @property {Phaser.Types.Physics.Arcade.ArcadeWorldConfig} [arcade] - Arcade Physics configuration. - * @property {Phaser.Types.Physics.Matter.MatterWorldConfig} [matter] - Matter Physics configuration. - */ +/** + * @typedef {object} Phaser.Types.Core.PhysicsConfig + * @since 3.0.0 + * + * @property {string} [default] - The default physics system. It will be started for each scene. Phaser provides 'arcade', 'impact', and 'matter'. + * @property {Phaser.Types.Physics.Arcade.ArcadeWorldConfig} [arcade] - Arcade Physics configuration. + * @property {Phaser.Types.Physics.Matter.MatterWorldConfig} [matter] - Matter Physics configuration. + */ diff --git a/src/core/typedefs/index.js b/src/core/typedefs/index.js index ebc550130..07beff4fa 100644 --- a/src/core/typedefs/index.js +++ b/src/core/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Core - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Core + */ diff --git a/src/create/GenerateTexture.js b/src/create/GenerateTexture.js index 87f682970..64308fbe5 100644 --- a/src/create/GenerateTexture.js +++ b/src/create/GenerateTexture.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Arne16 = require('./palettes/Arne16'); -var CanvasPool = require('../display/canvas/CanvasPool'); -var GetValue = require('../utils/object/GetValue'); - -/** - * Generates a texture based on the given Create configuration object. - * - * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the - * data cells map to a single color. For example, if the texture config looked like this: - * - * ```javascript - * var star = [ - * '.....828.....', - * '....72227....', - * '....82228....', - * '...7222227...', - * '2222222222222', - * '8222222222228', - * '.72222222227.', - * '..787777787..', - * '..877777778..', - * '.78778887787.', - * '.27887.78872.', - * '.787.....787.' - * ]; - * - * this.textures.generate('star', { data: star, pixelWidth: 4 }); - * ``` - * - * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array - * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color - * number 8 in the palette. If a cell contains a period character `.` then it is transparent. - * - * The default palette is Arne16, but you can specify your own using the `palette` property. - * - * @function Phaser.Create.GenerateTexture - * @since 3.0.0 - * - * @param {Phaser.Types.Create.GenerateTextureConfig} config - The Generate Texture Configuration object. - * - * @return {HTMLCanvasElement} An HTMLCanvasElement which contains the generated texture drawn to it. - */ -var GenerateTexture = function (config) -{ - var data = GetValue(config, 'data', []); - var canvas = GetValue(config, 'canvas', null); - var palette = GetValue(config, 'palette', Arne16); - var pixelWidth = GetValue(config, 'pixelWidth', 1); - var pixelHeight = GetValue(config, 'pixelHeight', pixelWidth); - var resizeCanvas = GetValue(config, 'resizeCanvas', true); - var clearCanvas = GetValue(config, 'clearCanvas', true); - var preRender = GetValue(config, 'preRender', null); - var postRender = GetValue(config, 'postRender', null); - - var width = Math.floor(Math.abs(data[0].length * pixelWidth)); - var height = Math.floor(Math.abs(data.length * pixelHeight)); - - if (!canvas) - { - canvas = CanvasPool.create2D(this, width, height); - resizeCanvas = false; - clearCanvas = false; - } - - if (resizeCanvas) - { - canvas.width = width; - canvas.height = height; - } - - var ctx = canvas.getContext('2d'); - - if (clearCanvas) - { - ctx.clearRect(0, 0, width, height); - } - - // preRender Callback? - if (preRender) - { - preRender(canvas, ctx); - } - - // Draw it - for (var y = 0; y < data.length; y++) - { - var row = data[y]; - - for (var x = 0; x < row.length; x++) - { - var d = row[x]; - - if (d !== '.' && d !== ' ') - { - ctx.fillStyle = palette[d]; - ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); - } - } - } - - // postRender Callback? - if (postRender) - { - postRender(canvas, ctx); - } - - return canvas; -}; - -module.exports = GenerateTexture; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Arne16 = require('./palettes/Arne16'); +var CanvasPool = require('../display/canvas/CanvasPool'); +var GetValue = require('../utils/object/GetValue'); + +/** + * Generates a texture based on the given Create configuration object. + * + * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the + * data cells map to a single color. For example, if the texture config looked like this: + * + * ```javascript + * var star = [ + * '.....828.....', + * '....72227....', + * '....82228....', + * '...7222227...', + * '2222222222222', + * '8222222222228', + * '.72222222227.', + * '..787777787..', + * '..877777778..', + * '.78778887787.', + * '.27887.78872.', + * '.787.....787.' + * ]; + * + * this.textures.generate('star', { data: star, pixelWidth: 4 }); + * ``` + * + * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array + * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color + * number 8 in the palette. If a cell contains a period character `.` then it is transparent. + * + * The default palette is Arne16, but you can specify your own using the `palette` property. + * + * @function Phaser.Create.GenerateTexture + * @since 3.0.0 + * + * @param {Phaser.Types.Create.GenerateTextureConfig} config - The Generate Texture Configuration object. + * + * @return {HTMLCanvasElement} An HTMLCanvasElement which contains the generated texture drawn to it. + */ +var GenerateTexture = function (config) +{ + var data = GetValue(config, 'data', []); + var canvas = GetValue(config, 'canvas', null); + var palette = GetValue(config, 'palette', Arne16); + var pixelWidth = GetValue(config, 'pixelWidth', 1); + var pixelHeight = GetValue(config, 'pixelHeight', pixelWidth); + var resizeCanvas = GetValue(config, 'resizeCanvas', true); + var clearCanvas = GetValue(config, 'clearCanvas', true); + var preRender = GetValue(config, 'preRender', null); + var postRender = GetValue(config, 'postRender', null); + + var width = Math.floor(Math.abs(data[0].length * pixelWidth)); + var height = Math.floor(Math.abs(data.length * pixelHeight)); + + if (!canvas) + { + canvas = CanvasPool.create2D(this, width, height); + resizeCanvas = false; + clearCanvas = false; + } + + if (resizeCanvas) + { + canvas.width = width; + canvas.height = height; + } + + var ctx = canvas.getContext('2d'); + + if (clearCanvas) + { + ctx.clearRect(0, 0, width, height); + } + + // preRender Callback? + if (preRender) + { + preRender(canvas, ctx); + } + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + ctx.fillStyle = palette[d]; + ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + // postRender Callback? + if (postRender) + { + postRender(canvas, ctx); + } + + return canvas; +}; + +module.exports = GenerateTexture; diff --git a/src/create/index.js b/src/create/index.js index f59f89beb..25e6cbb23 100644 --- a/src/create/index.js +++ b/src/create/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Create - */ - -module.exports = { - - GenerateTexture: require('./GenerateTexture'), - Palettes: require('./palettes') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Create + */ + +module.exports = { + + GenerateTexture: require('./GenerateTexture'), + Palettes: require('./palettes') + +}; diff --git a/src/create/palettes/Arne16.js b/src/create/palettes/Arne16.js index 2f21e8f25..291b0101f 100644 --- a/src/create/palettes/Arne16.js +++ b/src/create/palettes/Arne16.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) - * - * @name Phaser.Create.Palettes.ARNE16 - * @since 3.0.0 - * - * @type {Phaser.Types.Create.Palette} - */ -module.exports = { - 0: '#000', - 1: '#9D9D9D', - 2: '#FFF', - 3: '#BE2633', - 4: '#E06F8B', - 5: '#493C2B', - 6: '#A46422', - 7: '#EB8931', - 8: '#F7E26B', - 9: '#2F484E', - A: '#44891A', - B: '#A3CE27', - C: '#1B2632', - D: '#005784', - E: '#31A2F2', - F: '#B2DCEF' -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) + * + * @name Phaser.Create.Palettes.ARNE16 + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#9D9D9D', + 2: '#FFF', + 3: '#BE2633', + 4: '#E06F8B', + 5: '#493C2B', + 6: '#A46422', + 7: '#EB8931', + 8: '#F7E26B', + 9: '#2F484E', + A: '#44891A', + B: '#A3CE27', + C: '#1B2632', + D: '#005784', + E: '#31A2F2', + F: '#B2DCEF' +}; diff --git a/src/create/palettes/C64.js b/src/create/palettes/C64.js index 4f2fd057d..7e32164f5 100644 --- a/src/create/palettes/C64.js +++ b/src/create/palettes/C64.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A 16 color palette inspired by the Commodore 64. - * - * @name Phaser.Create.Palettes.C64 - * @since 3.0.0 - * - * @type {Phaser.Types.Create.Palette} - */ -module.exports = { - 0: '#000', - 1: '#fff', - 2: '#8b4131', - 3: '#7bbdc5', - 4: '#8b41ac', - 5: '#6aac41', - 6: '#3931a4', - 7: '#d5de73', - 8: '#945a20', - 9: '#5a4100', - A: '#bd736a', - B: '#525252', - C: '#838383', - D: '#acee8b', - E: '#7b73de', - F: '#acacac' -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color palette inspired by the Commodore 64. + * + * @name Phaser.Create.Palettes.C64 + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#fff', + 2: '#8b4131', + 3: '#7bbdc5', + 4: '#8b41ac', + 5: '#6aac41', + 6: '#3931a4', + 7: '#d5de73', + 8: '#945a20', + 9: '#5a4100', + A: '#bd736a', + B: '#525252', + C: '#838383', + D: '#acee8b', + E: '#7b73de', + F: '#acacac' +}; diff --git a/src/create/palettes/CGA.js b/src/create/palettes/CGA.js index dcdd25a42..1202d9546 100644 --- a/src/create/palettes/CGA.js +++ b/src/create/palettes/CGA.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A 16 color CGA inspired palette by [Arne](http://androidarts.com/palette/16pal.htm) - * - * @name Phaser.Create.Palettes.CGA - * @since 3.0.0 - * - * @type {Phaser.Types.Create.Palette} - */ -module.exports = { - 0: '#000', - 1: '#2234d1', - 2: '#0c7e45', - 3: '#44aacc', - 4: '#8a3622', - 5: '#5c2e78', - 6: '#aa5c3d', - 7: '#b5b5b5', - 8: '#5e606e', - 9: '#4c81fb', - A: '#6cd947', - B: '#7be2f9', - C: '#eb8a60', - D: '#e23d69', - E: '#ffd93f', - F: '#fff' -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color CGA inspired palette by [Arne](http://androidarts.com/palette/16pal.htm) + * + * @name Phaser.Create.Palettes.CGA + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#2234d1', + 2: '#0c7e45', + 3: '#44aacc', + 4: '#8a3622', + 5: '#5c2e78', + 6: '#aa5c3d', + 7: '#b5b5b5', + 8: '#5e606e', + 9: '#4c81fb', + A: '#6cd947', + B: '#7be2f9', + C: '#eb8a60', + D: '#e23d69', + E: '#ffd93f', + F: '#fff' +}; diff --git a/src/create/palettes/JMP.js b/src/create/palettes/JMP.js index 0744994c5..3d2d03e9c 100644 --- a/src/create/palettes/JMP.js +++ b/src/create/palettes/JMP.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A 16 color JMP palette by [Arne](http://androidarts.com/palette/16pal.htm) - * - * @name Phaser.Create.Palettes.JMP - * @since 3.0.0 - * - * @type {Phaser.Types.Create.Palette} - */ -module.exports = { - 0: '#000', - 1: '#191028', - 2: '#46af45', - 3: '#a1d685', - 4: '#453e78', - 5: '#7664fe', - 6: '#833129', - 7: '#9ec2e8', - 8: '#dc534b', - 9: '#e18d79', - A: '#d6b97b', - B: '#e9d8a1', - C: '#216c4b', - D: '#d365c8', - E: '#afaab9', - F: '#f5f4eb' -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color JMP palette by [Arne](http://androidarts.com/palette/16pal.htm) + * + * @name Phaser.Create.Palettes.JMP + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#191028', + 2: '#46af45', + 3: '#a1d685', + 4: '#453e78', + 5: '#7664fe', + 6: '#833129', + 7: '#9ec2e8', + 8: '#dc534b', + 9: '#e18d79', + A: '#d6b97b', + B: '#e9d8a1', + C: '#216c4b', + D: '#d365c8', + E: '#afaab9', + F: '#f5f4eb' +}; diff --git a/src/create/palettes/MSX.js b/src/create/palettes/MSX.js index a7e248bb8..c65659036 100644 --- a/src/create/palettes/MSX.js +++ b/src/create/palettes/MSX.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A 16 color palette inspired by Japanese computers like the MSX. - * - * @name Phaser.Create.Palettes.MSX - * @since 3.0.0 - * - * @type {Phaser.Types.Create.Palette} - */ -module.exports = { - 0: '#000', - 1: '#191028', - 2: '#46af45', - 3: '#a1d685', - 4: '#453e78', - 5: '#7664fe', - 6: '#833129', - 7: '#9ec2e8', - 8: '#dc534b', - 9: '#e18d79', - A: '#d6b97b', - B: '#e9d8a1', - C: '#216c4b', - D: '#d365c8', - E: '#afaab9', - F: '#fff' -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A 16 color palette inspired by Japanese computers like the MSX. + * + * @name Phaser.Create.Palettes.MSX + * @since 3.0.0 + * + * @type {Phaser.Types.Create.Palette} + */ +module.exports = { + 0: '#000', + 1: '#191028', + 2: '#46af45', + 3: '#a1d685', + 4: '#453e78', + 5: '#7664fe', + 6: '#833129', + 7: '#9ec2e8', + 8: '#dc534b', + 9: '#e18d79', + A: '#d6b97b', + B: '#e9d8a1', + C: '#216c4b', + D: '#d365c8', + E: '#afaab9', + F: '#fff' +}; diff --git a/src/create/palettes/index.js b/src/create/palettes/index.js index df1666f47..af8c7ed33 100644 --- a/src/create/palettes/index.js +++ b/src/create/palettes/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Create.Palettes - */ - -module.exports = { - - ARNE16: require('./Arne16'), - C64: require('./C64'), - CGA: require('./CGA'), - JMP: require('./JMP'), - MSX: require('./MSX') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Create.Palettes + */ + +module.exports = { + + ARNE16: require('./Arne16'), + C64: require('./C64'), + CGA: require('./CGA'), + JMP: require('./JMP'), + MSX: require('./MSX') + +}; diff --git a/src/create/typedefs/GenerateTextureConfig.js b/src/create/typedefs/GenerateTextureConfig.js index a001a9bae..12efd8b41 100644 --- a/src/create/typedefs/GenerateTextureConfig.js +++ b/src/create/typedefs/GenerateTextureConfig.js @@ -1,22 +1,22 @@ -/** - * @callback Phaser.Types.Create.GenerateTextureCallback - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The HTML Canvas element to operate on. - * @param {CanvasRenderingContext2D} context - The context of the HTML Canvas element. - */ - -/** - * @typedef {object} Phaser.Types.Create.GenerateTextureConfig - * @since 3.0.0 - * - * @property {array} [data=[]] - An array of data, where each row is a string of single values 0-9A-F, or the period character. - * @property {HTMLCanvasElement} [canvas=null] - The HTML Canvas to draw the texture to. - * @property {Phaser.Types.Create.Palette} [palette=Arne16] - The indexed palette that the data cell values map to. - * @property {number} [pixelWidth=1] - The width of each 'pixel' in the generated texture. - * @property {number} [pixelHeight=1] - The height of each 'pixel' in the generated texture. - * @property {boolean} [resizeCanvas=true] - Should the canvas be resized before the texture is drawn? - * @property {boolean} [clearCanvas=true] - Should the canvas be cleared before the texture is drawn? - * @property {Phaser.Types.Create.GenerateTextureCallback} [preRender] - A callback to send the canvas to prior to the texture being drawn. - * @property {Phaser.Types.Create.GenerateTextureCallback} [postRender] - A callback to send the canvas to after the texture has been drawn. - */ +/** + * @callback Phaser.Types.Create.GenerateTextureCallback + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The HTML Canvas element to operate on. + * @param {CanvasRenderingContext2D} context - The context of the HTML Canvas element. + */ + +/** + * @typedef {object} Phaser.Types.Create.GenerateTextureConfig + * @since 3.0.0 + * + * @property {array} [data=[]] - An array of data, where each row is a string of single values 0-9A-F, or the period character. + * @property {HTMLCanvasElement} [canvas=null] - The HTML Canvas to draw the texture to. + * @property {Phaser.Types.Create.Palette} [palette=Arne16] - The indexed palette that the data cell values map to. + * @property {number} [pixelWidth=1] - The width of each 'pixel' in the generated texture. + * @property {number} [pixelHeight=1] - The height of each 'pixel' in the generated texture. + * @property {boolean} [resizeCanvas=true] - Should the canvas be resized before the texture is drawn? + * @property {boolean} [clearCanvas=true] - Should the canvas be cleared before the texture is drawn? + * @property {Phaser.Types.Create.GenerateTextureCallback} [preRender] - A callback to send the canvas to prior to the texture being drawn. + * @property {Phaser.Types.Create.GenerateTextureCallback} [postRender] - A callback to send the canvas to after the texture has been drawn. + */ diff --git a/src/create/typedefs/index.js b/src/create/typedefs/index.js index ef13d33bd..81689d17c 100644 --- a/src/create/typedefs/index.js +++ b/src/create/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Create - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Create + */ diff --git a/src/curves/CubicBezierCurve.js b/src/curves/CubicBezierCurve.js index 231200479..470baa62c 100644 --- a/src/curves/CubicBezierCurve.js +++ b/src/curves/CubicBezierCurve.js @@ -1,221 +1,221 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) - -var Class = require('../utils/Class'); -var CubicBezier = require('../math/interpolation/CubicBezierInterpolation'); -var Curve = require('./Curve'); -var Vector2 = require('../math/Vector2'); - -/** - * @classdesc - * A higher-order Bézier curve constructed of four points. - * - * @class CubicBezier - * @extends Phaser.Curves.Curve - * @memberof Phaser.Curves - * @constructor - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector2[])} p0 - Start point, or an array of point pairs. - * @param {Phaser.Math.Vector2} p1 - Control Point 1. - * @param {Phaser.Math.Vector2} p2 - Control Point 2. - * @param {Phaser.Math.Vector2} p3 - End Point. - */ -var CubicBezierCurve = new Class({ - - Extends: Curve, - - initialize: - - function CubicBezierCurve (p0, p1, p2, p3) - { - Curve.call(this, 'CubicBezierCurve'); - - if (Array.isArray(p0)) - { - p3 = new Vector2(p0[6], p0[7]); - p2 = new Vector2(p0[4], p0[5]); - p1 = new Vector2(p0[2], p0[3]); - p0 = new Vector2(p0[0], p0[1]); - } - - /** - * The start point of this curve. - * - * @name Phaser.Curves.CubicBezier#p0 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p0 = p0; - - /** - * The first control point of this curve. - * - * @name Phaser.Curves.CubicBezier#p1 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p1 = p1; - - /** - * The second control point of this curve. - * - * @name Phaser.Curves.CubicBezier#p2 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p2 = p2; - - /** - * The end point of this curve. - * - * @name Phaser.Curves.CubicBezier#p3 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p3 = p3; - }, - - /** - * Gets the starting point on the curve. - * - * @method Phaser.Curves.CubicBezier#getStartPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return out.copy(this.p0); - }, - - /** - * Returns the resolution of this curve. - * - * @method Phaser.Curves.CubicBezier#getResolution - * @since 3.0.0 - * - * @param {number} divisions - The amount of divisions used by this curve. - * - * @return {number} The resolution of the curve. - */ - getResolution: function (divisions) - { - return divisions; - }, - - /** - * Get point at relative position in curve according to length. - * - * @method Phaser.Curves.CubicBezier#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - var p0 = this.p0; - var p1 = this.p1; - var p2 = this.p2; - var p3 = this.p3; - - return out.set(CubicBezier(t, p0.x, p1.x, p2.x, p3.x), CubicBezier(t, p0.y, p1.y, p2.y, p3.y)); - }, - - /** - * Draws this curve to the specified graphics object. - * - * @method Phaser.Curves.CubicBezier#draw - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] - * - * @param {Phaser.GameObjects.Graphics} graphics - The graphics object this curve should be drawn to. - * @param {integer} [pointsTotal=32] - The number of intermediary points that make up this curve. A higher number of points will result in a smoother curve. - * - * @return {Phaser.GameObjects.Graphics} The graphics object this curve was drawn to. Useful for method chaining. - */ - draw: function (graphics, pointsTotal) - { - if (pointsTotal === undefined) { pointsTotal = 32; } - - var points = this.getPoints(pointsTotal); - - graphics.beginPath(); - graphics.moveTo(this.p0.x, this.p0.y); - - for (var i = 1; i < points.length; i++) - { - graphics.lineTo(points[i].x, points[i].y); - } - - graphics.strokePath(); - - // So you can chain graphics calls - return graphics; - }, - - /** - * Returns a JSON object that describes this curve. - * - * @method Phaser.Curves.CubicBezier#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. - */ - toJSON: function () - { - return { - type: this.type, - points: [ - this.p0.x, this.p0.y, - this.p1.x, this.p1.y, - this.p2.x, this.p2.y, - this.p3.x, this.p3.y - ] - }; - } - -}); - -/** - * Generates a curve from a JSON object. - * - * @function Phaser.Curves.CubicBezier.fromJSON - * @since 3.0.0 - * - * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. - * - * @return {Phaser.Curves.CubicBezier} The curve generated from the JSON object. - */ -CubicBezierCurve.fromJSON = function (data) -{ - var points = data.points; - - var p0 = new Vector2(points[0], points[1]); - var p1 = new Vector2(points[2], points[3]); - var p2 = new Vector2(points[4], points[5]); - var p3 = new Vector2(points[6], points[7]); - - return new CubicBezierCurve(p0, p1, p2, p3); -}; - -module.exports = CubicBezierCurve; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = require('../utils/Class'); +var CubicBezier = require('../math/interpolation/CubicBezierInterpolation'); +var Curve = require('./Curve'); +var Vector2 = require('../math/Vector2'); + +/** + * @classdesc + * A higher-order Bézier curve constructed of four points. + * + * @class CubicBezier + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector2[])} p0 - Start point, or an array of point pairs. + * @param {Phaser.Math.Vector2} p1 - Control Point 1. + * @param {Phaser.Math.Vector2} p2 - Control Point 2. + * @param {Phaser.Math.Vector2} p3 - End Point. + */ +var CubicBezierCurve = new Class({ + + Extends: Curve, + + initialize: + + function CubicBezierCurve (p0, p1, p2, p3) + { + Curve.call(this, 'CubicBezierCurve'); + + if (Array.isArray(p0)) + { + p3 = new Vector2(p0[6], p0[7]); + p2 = new Vector2(p0[4], p0[5]); + p1 = new Vector2(p0[2], p0[3]); + p0 = new Vector2(p0[0], p0[1]); + } + + /** + * The start point of this curve. + * + * @name Phaser.Curves.CubicBezier#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = p0; + + /** + * The first control point of this curve. + * + * @name Phaser.Curves.CubicBezier#p1 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p1 = p1; + + /** + * The second control point of this curve. + * + * @name Phaser.Curves.CubicBezier#p2 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p2 = p2; + + /** + * The end point of this curve. + * + * @name Phaser.Curves.CubicBezier#p3 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p3 = p3; + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.CubicBezier#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * Returns the resolution of this curve. + * + * @method Phaser.Curves.CubicBezier#getResolution + * @since 3.0.0 + * + * @param {number} divisions - The amount of divisions used by this curve. + * + * @return {number} The resolution of the curve. + */ + getResolution: function (divisions) + { + return divisions; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.CubicBezier#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var p0 = this.p0; + var p1 = this.p1; + var p2 = this.p2; + var p3 = this.p3; + + return out.set(CubicBezier(t, p0.x, p1.x, p2.x, p3.x), CubicBezier(t, p0.y, p1.y, p2.y, p3.y)); + }, + + /** + * Draws this curve to the specified graphics object. + * + * @method Phaser.Curves.CubicBezier#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The graphics object this curve should be drawn to. + * @param {integer} [pointsTotal=32] - The number of intermediary points that make up this curve. A higher number of points will result in a smoother curve. + * + * @return {Phaser.GameObjects.Graphics} The graphics object this curve was drawn to. Useful for method chaining. + */ + draw: function (graphics, pointsTotal) + { + if (pointsTotal === undefined) { pointsTotal = 32; } + + var points = this.getPoints(pointsTotal); + + graphics.beginPath(); + graphics.moveTo(this.p0.x, this.p0.y); + + for (var i = 1; i < points.length; i++) + { + graphics.lineTo(points[i].x, points[i].y); + } + + graphics.strokePath(); + + // So you can chain graphics calls + return graphics; + }, + + /** + * Returns a JSON object that describes this curve. + * + * @method Phaser.Curves.CubicBezier#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + points: [ + this.p0.x, this.p0.y, + this.p1.x, this.p1.y, + this.p2.x, this.p2.y, + this.p3.x, this.p3.y + ] + }; + } + +}); + +/** + * Generates a curve from a JSON object. + * + * @function Phaser.Curves.CubicBezier.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.CubicBezier} The curve generated from the JSON object. + */ +CubicBezierCurve.fromJSON = function (data) +{ + var points = data.points; + + var p0 = new Vector2(points[0], points[1]); + var p1 = new Vector2(points[2], points[3]); + var p2 = new Vector2(points[4], points[5]); + var p3 = new Vector2(points[6], points[7]); + + return new CubicBezierCurve(p0, p1, p2, p3); +}; + +module.exports = CubicBezierCurve; diff --git a/src/curves/Curve.js b/src/curves/Curve.js index 8d0fe02f6..0bdf6446c 100644 --- a/src/curves/Curve.js +++ b/src/curves/Curve.js @@ -1,614 +1,614 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var FromPoints = require('../geom/rectangle/FromPoints'); -var Rectangle = require('../geom/rectangle/Rectangle'); -var Vector2 = require('../math/Vector2'); - -/** - * @classdesc - * A Base Curve class, which all other curve types extend. - * - * 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. - */ -var Curve = new Class({ - - initialize: - - function Curve (type) - { - /** - * String based identifier for the type of curve. - * - * @name Phaser.Curves.Curve#type - * @type {string} - * @since 3.0.0 - */ - this.type = type; - - /** - * The default number of divisions within the curve. - * - * @name Phaser.Curves.Curve#defaultDivisions - * @type {integer} - * @default 5 - * @since 3.0.0 - */ - this.defaultDivisions = 5; - - /** - * The quantity of arc length divisions within the curve. - * - * @name Phaser.Curves.Curve#arcLengthDivisions - * @type {integer} - * @default 100 - * @since 3.0.0 - */ - this.arcLengthDivisions = 100; - - /** - * An array of cached arc length values. - * - * @name Phaser.Curves.Curve#cacheArcLengths - * @type {number[]} - * @default [] - * @since 3.0.0 - */ - this.cacheArcLengths = []; - - /** - * Does the data of this curve need updating? - * - * @name Phaser.Curves.Curve#needsUpdate - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.needsUpdate = true; - - /** - * For a curve on a Path, `false` means the Path will ignore this curve. - * - * @name Phaser.Curves.Curve#active - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.active = true; - - /** - * A temporary calculation Vector. - * - * @name Phaser.Curves.Curve#_tmpVec2A - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tmpVec2A = new Vector2(); - - /** - * A temporary calculation Vector. - * - * @name Phaser.Curves.Curve#_tmpVec2B - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tmpVec2B = new Vector2(); - }, - - /** - * Draws this curve on the given Graphics object. - * - * The curve is drawn using `Graphics.strokePoints` so will be drawn at whatever the present Graphics stroke color is. - * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. - * - * @method Phaser.Curves.Curve#draw - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] - * - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn. - * @param {integer} [pointsTotal=32] - The resolution of the curve. The higher the value the smoother it will render, at the cost of rendering performance. - * - * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn. - */ - draw: function (graphics, pointsTotal) - { - if (pointsTotal === undefined) { pointsTotal = 32; } - - // So you can chain graphics calls - return graphics.strokePoints(this.getPoints(pointsTotal)); - }, - - /** - * Returns a Rectangle where the position and dimensions match the bounds of this Curve. - * - * You can control the accuracy of the bounds. The value given is used to work out how many points - * to plot across the curve. Higher values are more accurate at the cost of calculation speed. - * - * @method Phaser.Curves.Curve#getBounds - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the bounds in. If falsey a new object will be created. - * @param {integer} [accuracy=16] - The accuracy of the bounds calculations. - * - * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object. - */ - getBounds: function (out, accuracy) - { - if (!out) { out = new Rectangle(); } - if (accuracy === undefined) { accuracy = 16; } - - var len = this.getLength(); - - if (accuracy > len) - { - accuracy = len / 2; - } - - // The length of the curve in pixels - // So we'll have 1 spaced point per 'accuracy' pixels - - var spaced = Math.max(1, Math.round(len / accuracy)); - - return FromPoints(this.getSpacedPoints(spaced), out); - }, - - /** - * Returns an array of points, spaced out X distance pixels apart. - * The smaller the distance, the larger the array will be. - * - * @method Phaser.Curves.Curve#getDistancePoints - * @since 3.0.0 - * - * @param {integer} distance - The distance, in pixels, between each point along the curve. - * - * @return {Phaser.Geom.Point[]} An Array of Point objects. - */ - getDistancePoints: function (distance) - { - var len = this.getLength(); - - var spaced = Math.max(1, len / distance); - - return this.getSpacedPoints(spaced); - }, - - /** - * Get a point at the end of the curve. - * - * @method Phaser.Curves.Curve#getEndPoint - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} [out] - Optional Vector object to store the result in. - * - * @return {Phaser.Math.Vector2} Vector2 containing the coordinates of the curves end point. - */ - getEndPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return this.getPointAt(1, out); - }, - - /** - * Get total curve arc length - * - * @method Phaser.Curves.Curve#getLength - * @since 3.0.0 - * - * @return {number} The total length of the curve. - */ - getLength: function () - { - var lengths = this.getLengths(); - - return lengths[lengths.length - 1]; - }, - - - /** - * Get a list of cumulative segment lengths. - * - * These lengths are - * - * - [0] 0 - * - [1] The first segment - * - [2] The first and second segment - * - ... - * - [divisions] All segments - * - * @method Phaser.Curves.Curve#getLengths - * @since 3.0.0 - * - * @param {integer} [divisions] - The number of divisions or segments. - * - * @return {number[]} An array of cumulative lengths. - */ - getLengths: function (divisions) - { - if (divisions === undefined) { divisions = this.arcLengthDivisions; } - - if ((this.cacheArcLengths.length === divisions + 1) && !this.needsUpdate) - { - return this.cacheArcLengths; - } - - this.needsUpdate = false; - - var cache = []; - var current; - var last = this.getPoint(0, this._tmpVec2A); - var sum = 0; - - cache.push(0); - - for (var p = 1; p <= divisions; p++) - { - current = this.getPoint(p / divisions, this._tmpVec2B); - - sum += current.distance(last); - - cache.push(sum); - - last.copy(current); - } - - this.cacheArcLengths = cache; - - return cache; // { sums: cache, sum:sum }; Sum is in the last element. - }, - - // Get point at relative position in curve according to arc length - - // - u [0 .. 1] - - /** - * Get a point at a relative position on the curve, by arc length. - * - * @method Phaser.Curves.Curve#getPointAt - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} u - The relative position, [0..1]. - * @param {Phaser.Math.Vector2} [out] - A point to store the result in. - * - * @return {Phaser.Math.Vector2} The point. - */ - getPointAt: function (u, out) - { - var t = this.getUtoTmapping(u); - - return this.getPoint(t, out); - }, - - // Get sequence of points using getPoint( t ) - - /** - * Get a sequence of evenly spaced points from the curve. - * - * You can pass `divisions`, `stepRate`, or neither. - * - * The number of divisions will be - * - * 1. `divisions`, if `divisions` > 0; or - * 2. `this.getLength / stepRate`, if `stepRate` > 0; or - * 3. `this.defaultDivisions` - * - * `1 + divisions` points will be returned. - * - * @method Phaser.Curves.Curve#getPoints - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2[]} O - [out,$return] - * - * @param {integer} [divisions] - The number of divisions to make. - * @param {number} [stepRate] - The curve distance between points, implying `divisions`. - * @param {(array|Phaser.Math.Vector2[])} [out] - An optional array to store the points in. - * - * @return {(array|Phaser.Math.Vector2[])} An array of Points from the curve. - */ - getPoints: function (divisions, stepRate, out) - { - if (out === undefined) { out = []; } - - // If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!divisions) - { - if (!stepRate) - { - divisions = this.defaultDivisions; - } - else - { - divisions = this.getLength() / stepRate; - } - } - - for (var d = 0; d <= divisions; d++) - { - out.push(this.getPoint(d / divisions)); - } - - return out; - }, - - /** - * Get a random point from the curve. - * - * @method Phaser.Curves.Curve#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A point object to store the result in. - * - * @return {Phaser.Math.Vector2} The point. - */ - getRandomPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return this.getPoint(Math.random(), out); - }, - - // Get sequence of points using getPointAt( u ) - - /** - * Get a sequence of equally spaced points (by arc distance) from the curve. - * - * `1 + divisions` points will be returned. - * - * @method Phaser.Curves.Curve#getSpacedPoints - * @since 3.0.0 - * - * @param {integer} [divisions=this.defaultDivisions] - The number of divisions to make. - * @param {number} [stepRate] - Step between points. Used to calculate the number of points to return when divisions is falsy. Ignored if divisions is positive. - * @param {(array|Phaser.Math.Vector2[])} [out] - An optional array to store the points in. - * - * @return {Phaser.Math.Vector2[]} An array of points. - */ - getSpacedPoints: function (divisions, stepRate, out) - { - if (out === undefined) { out = []; } - - // If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!divisions) - { - if (!stepRate) - { - divisions = this.defaultDivisions; - } - else - { - divisions = this.getLength() / stepRate; - } - } - - for (var d = 0; d <= divisions; d++) - { - var t = this.getUtoTmapping(d / divisions, null, divisions); - - out.push(this.getPoint(t)); - } - - return out; - }, - - /** - * Get a point at the start of the curve. - * - * @method Phaser.Curves.Curve#getStartPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A point to store the result in. - * - * @return {Phaser.Math.Vector2} The point. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return this.getPointAt(0, out); - }, - - /** - * Get a unit vector tangent at a relative position on the curve. - * In case any sub curve does not implement its tangent derivation, - * 2 points a small delta apart will be used to find its gradient - * which seems to give a reasonable approximation - * - * @method Phaser.Curves.Curve#getTangent - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The relative position on the curve, [0..1]. - * @param {Phaser.Math.Vector2} [out] - A vector to store the result in. - * - * @return {Phaser.Math.Vector2} Vector approximating the tangent line at the point t (delta +/- 0.0001) - */ - getTangent: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; - - // Capping in case of danger - - if (t1 < 0) - { - t1 = 0; - } - - if (t2 > 1) - { - t2 = 1; - } - - this.getPoint(t1, this._tmpVec2A); - this.getPoint(t2, out); - - return out.subtract(this._tmpVec2A).normalize(); - }, - - /** - * Get a unit vector tangent at a relative position on the curve, by arc length. - * - * @method Phaser.Curves.Curve#getTangentAt - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} u - The relative position on the curve, [0..1]. - * @param {Phaser.Math.Vector2} [out] - A vector to store the result in. - * - * @return {Phaser.Math.Vector2} The tangent vector. - */ - getTangentAt: function (u, out) - { - var t = this.getUtoTmapping(u); - - return this.getTangent(t, out); - }, - - // Given a distance in pixels, get a t to find p. - /** - * [description] - * - * @method Phaser.Curves.Curve#getTFromDistance - * @since 3.0.0 - * - * @param {integer} distance - [description] - * @param {integer} [divisions] - [description] - * - * @return {number} [description] - */ - getTFromDistance: function (distance, divisions) - { - if (distance <= 0) - { - return 0; - } - - return this.getUtoTmapping(0, distance, divisions); - }, - - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - - /** - * [description] - * - * @method Phaser.Curves.Curve#getUtoTmapping - * @since 3.0.0 - * - * @param {number} u - [description] - * @param {integer} distance - [description] - * @param {integer} [divisions] - [description] - * - * @return {number} [description] - */ - getUtoTmapping: function (u, distance, divisions) - { - var arcLengths = this.getLengths(divisions); - - var i = 0; - var il = arcLengths.length; - - var targetArcLength; // The targeted u distance value to get - - if (distance) - { - // Cannot overshoot the curve - targetArcLength = Math.min(distance, arcLengths[il - 1]); - } - else - { - targetArcLength = u * arcLengths[il - 1]; - } - - // binary search for the index with largest value smaller than target u distance - - var low = 0; - var high = il - 1; - var comparison; - - while (low <= high) - { - i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - - comparison = arcLengths[i] - targetArcLength; - - if (comparison < 0) - { - low = i + 1; - } - else if (comparison > 0) - { - high = i - 1; - } - else - { - high = i; - break; - } - } - - i = high; - - if (arcLengths[i] === targetArcLength) - { - return i / (il - 1); - } - - // we could get finer grain at lengths, or use simple interpolation between two points - - var lengthBefore = arcLengths[i]; - var lengthAfter = arcLengths[i + 1]; - - var segmentLength = lengthAfter - lengthBefore; - - // determine where we are between the 'before' and 'after' points - - var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; - - // add that fractional amount to t - - return (i + segmentFraction) / (il - 1); - }, - - /** - * Calculate and cache the arc lengths. - * - * @method Phaser.Curves.Curve#updateArcLengths - * @since 3.0.0 - * - * @see Phaser.Curves.Curve#getLengths() - */ - updateArcLengths: function () - { - this.needsUpdate = true; - - this.getLengths(); - } - -}); - -module.exports = Curve; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var FromPoints = require('../geom/rectangle/FromPoints'); +var Rectangle = require('../geom/rectangle/Rectangle'); +var Vector2 = require('../math/Vector2'); + +/** + * @classdesc + * A Base Curve class, which all other curve types extend. + * + * 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. + */ +var Curve = new Class({ + + initialize: + + function Curve (type) + { + /** + * String based identifier for the type of curve. + * + * @name Phaser.Curves.Curve#type + * @type {string} + * @since 3.0.0 + */ + this.type = type; + + /** + * The default number of divisions within the curve. + * + * @name Phaser.Curves.Curve#defaultDivisions + * @type {integer} + * @default 5 + * @since 3.0.0 + */ + this.defaultDivisions = 5; + + /** + * The quantity of arc length divisions within the curve. + * + * @name Phaser.Curves.Curve#arcLengthDivisions + * @type {integer} + * @default 100 + * @since 3.0.0 + */ + this.arcLengthDivisions = 100; + + /** + * An array of cached arc length values. + * + * @name Phaser.Curves.Curve#cacheArcLengths + * @type {number[]} + * @default [] + * @since 3.0.0 + */ + this.cacheArcLengths = []; + + /** + * Does the data of this curve need updating? + * + * @name Phaser.Curves.Curve#needsUpdate + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.needsUpdate = true; + + /** + * For a curve on a Path, `false` means the Path will ignore this curve. + * + * @name Phaser.Curves.Curve#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * A temporary calculation Vector. + * + * @name Phaser.Curves.Curve#_tmpVec2A + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2A = new Vector2(); + + /** + * A temporary calculation Vector. + * + * @name Phaser.Curves.Curve#_tmpVec2B + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2B = new Vector2(); + }, + + /** + * Draws this curve on the given Graphics object. + * + * The curve is drawn using `Graphics.strokePoints` so will be drawn at whatever the present Graphics stroke color is. + * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. + * + * @method Phaser.Curves.Curve#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn. + * @param {integer} [pointsTotal=32] - The resolution of the curve. The higher the value the smoother it will render, at the cost of rendering performance. + * + * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn. + */ + draw: function (graphics, pointsTotal) + { + if (pointsTotal === undefined) { pointsTotal = 32; } + + // So you can chain graphics calls + return graphics.strokePoints(this.getPoints(pointsTotal)); + }, + + /** + * Returns a Rectangle where the position and dimensions match the bounds of this Curve. + * + * You can control the accuracy of the bounds. The value given is used to work out how many points + * to plot across the curve. Higher values are more accurate at the cost of calculation speed. + * + * @method Phaser.Curves.Curve#getBounds + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the bounds in. If falsey a new object will be created. + * @param {integer} [accuracy=16] - The accuracy of the bounds calculations. + * + * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object. + */ + getBounds: function (out, accuracy) + { + if (!out) { out = new Rectangle(); } + if (accuracy === undefined) { accuracy = 16; } + + var len = this.getLength(); + + if (accuracy > len) + { + accuracy = len / 2; + } + + // The length of the curve in pixels + // So we'll have 1 spaced point per 'accuracy' pixels + + var spaced = Math.max(1, Math.round(len / accuracy)); + + return FromPoints(this.getSpacedPoints(spaced), out); + }, + + /** + * Returns an array of points, spaced out X distance pixels apart. + * The smaller the distance, the larger the array will be. + * + * @method Phaser.Curves.Curve#getDistancePoints + * @since 3.0.0 + * + * @param {integer} distance - The distance, in pixels, between each point along the curve. + * + * @return {Phaser.Geom.Point[]} An Array of Point objects. + */ + getDistancePoints: function (distance) + { + var len = this.getLength(); + + var spaced = Math.max(1, len / distance); + + return this.getSpacedPoints(spaced); + }, + + /** + * Get a point at the end of the curve. + * + * @method Phaser.Curves.Curve#getEndPoint + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} [out] - Optional Vector object to store the result in. + * + * @return {Phaser.Math.Vector2} Vector2 containing the coordinates of the curves end point. + */ + getEndPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPointAt(1, out); + }, + + /** + * Get total curve arc length + * + * @method Phaser.Curves.Curve#getLength + * @since 3.0.0 + * + * @return {number} The total length of the curve. + */ + getLength: function () + { + var lengths = this.getLengths(); + + return lengths[lengths.length - 1]; + }, + + + /** + * Get a list of cumulative segment lengths. + * + * These lengths are + * + * - [0] 0 + * - [1] The first segment + * - [2] The first and second segment + * - ... + * - [divisions] All segments + * + * @method Phaser.Curves.Curve#getLengths + * @since 3.0.0 + * + * @param {integer} [divisions] - The number of divisions or segments. + * + * @return {number[]} An array of cumulative lengths. + */ + getLengths: function (divisions) + { + if (divisions === undefined) { divisions = this.arcLengthDivisions; } + + if ((this.cacheArcLengths.length === divisions + 1) && !this.needsUpdate) + { + return this.cacheArcLengths; + } + + this.needsUpdate = false; + + var cache = []; + var current; + var last = this.getPoint(0, this._tmpVec2A); + var sum = 0; + + cache.push(0); + + for (var p = 1; p <= divisions; p++) + { + current = this.getPoint(p / divisions, this._tmpVec2B); + + sum += current.distance(last); + + cache.push(sum); + + last.copy(current); + } + + this.cacheArcLengths = cache; + + return cache; // { sums: cache, sum:sum }; Sum is in the last element. + }, + + // Get point at relative position in curve according to arc length + + // - u [0 .. 1] + + /** + * Get a point at a relative position on the curve, by arc length. + * + * @method Phaser.Curves.Curve#getPointAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The relative position, [0..1]. + * @param {Phaser.Math.Vector2} [out] - A point to store the result in. + * + * @return {Phaser.Math.Vector2} The point. + */ + getPointAt: function (u, out) + { + var t = this.getUtoTmapping(u); + + return this.getPoint(t, out); + }, + + // Get sequence of points using getPoint( t ) + + /** + * Get a sequence of evenly spaced points from the curve. + * + * You can pass `divisions`, `stepRate`, or neither. + * + * The number of divisions will be + * + * 1. `divisions`, if `divisions` > 0; or + * 2. `this.getLength / stepRate`, if `stepRate` > 0; or + * 3. `this.defaultDivisions` + * + * `1 + divisions` points will be returned. + * + * @method Phaser.Curves.Curve#getPoints + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2[]} O - [out,$return] + * + * @param {integer} [divisions] - The number of divisions to make. + * @param {number} [stepRate] - The curve distance between points, implying `divisions`. + * @param {(array|Phaser.Math.Vector2[])} [out] - An optional array to store the points in. + * + * @return {(array|Phaser.Math.Vector2[])} An array of Points from the curve. + */ + getPoints: function (divisions, stepRate, out) + { + if (out === undefined) { out = []; } + + // If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!divisions) + { + if (!stepRate) + { + divisions = this.defaultDivisions; + } + else + { + divisions = this.getLength() / stepRate; + } + } + + for (var d = 0; d <= divisions; d++) + { + out.push(this.getPoint(d / divisions)); + } + + return out; + }, + + /** + * Get a random point from the curve. + * + * @method Phaser.Curves.Curve#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A point object to store the result in. + * + * @return {Phaser.Math.Vector2} The point. + */ + getRandomPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPoint(Math.random(), out); + }, + + // Get sequence of points using getPointAt( u ) + + /** + * Get a sequence of equally spaced points (by arc distance) from the curve. + * + * `1 + divisions` points will be returned. + * + * @method Phaser.Curves.Curve#getSpacedPoints + * @since 3.0.0 + * + * @param {integer} [divisions=this.defaultDivisions] - The number of divisions to make. + * @param {number} [stepRate] - Step between points. Used to calculate the number of points to return when divisions is falsy. Ignored if divisions is positive. + * @param {(array|Phaser.Math.Vector2[])} [out] - An optional array to store the points in. + * + * @return {Phaser.Math.Vector2[]} An array of points. + */ + getSpacedPoints: function (divisions, stepRate, out) + { + if (out === undefined) { out = []; } + + // If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!divisions) + { + if (!stepRate) + { + divisions = this.defaultDivisions; + } + else + { + divisions = this.getLength() / stepRate; + } + } + + for (var d = 0; d <= divisions; d++) + { + var t = this.getUtoTmapping(d / divisions, null, divisions); + + out.push(this.getPoint(t)); + } + + return out; + }, + + /** + * Get a point at the start of the curve. + * + * @method Phaser.Curves.Curve#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A point to store the result in. + * + * @return {Phaser.Math.Vector2} The point. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPointAt(0, out); + }, + + /** + * Get a unit vector tangent at a relative position on the curve. + * In case any sub curve does not implement its tangent derivation, + * 2 points a small delta apart will be used to find its gradient + * which seems to give a reasonable approximation + * + * @method Phaser.Curves.Curve#getTangent + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The relative position on the curve, [0..1]. + * @param {Phaser.Math.Vector2} [out] - A vector to store the result in. + * + * @return {Phaser.Math.Vector2} Vector approximating the tangent line at the point t (delta +/- 0.0001) + */ + getTangent: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; + + // Capping in case of danger + + if (t1 < 0) + { + t1 = 0; + } + + if (t2 > 1) + { + t2 = 1; + } + + this.getPoint(t1, this._tmpVec2A); + this.getPoint(t2, out); + + return out.subtract(this._tmpVec2A).normalize(); + }, + + /** + * Get a unit vector tangent at a relative position on the curve, by arc length. + * + * @method Phaser.Curves.Curve#getTangentAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The relative position on the curve, [0..1]. + * @param {Phaser.Math.Vector2} [out] - A vector to store the result in. + * + * @return {Phaser.Math.Vector2} The tangent vector. + */ + getTangentAt: function (u, out) + { + var t = this.getUtoTmapping(u); + + return this.getTangent(t, out); + }, + + // Given a distance in pixels, get a t to find p. + /** + * [description] + * + * @method Phaser.Curves.Curve#getTFromDistance + * @since 3.0.0 + * + * @param {integer} distance - [description] + * @param {integer} [divisions] - [description] + * + * @return {number} [description] + */ + getTFromDistance: function (distance, divisions) + { + if (distance <= 0) + { + return 0; + } + + return this.getUtoTmapping(0, distance, divisions); + }, + + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + + /** + * [description] + * + * @method Phaser.Curves.Curve#getUtoTmapping + * @since 3.0.0 + * + * @param {number} u - [description] + * @param {integer} distance - [description] + * @param {integer} [divisions] - [description] + * + * @return {number} [description] + */ + getUtoTmapping: function (u, distance, divisions) + { + var arcLengths = this.getLengths(divisions); + + var i = 0; + var il = arcLengths.length; + + var targetArcLength; // The targeted u distance value to get + + if (distance) + { + // Cannot overshoot the curve + targetArcLength = Math.min(distance, arcLengths[il - 1]); + } + else + { + targetArcLength = u * arcLengths[il - 1]; + } + + // binary search for the index with largest value smaller than target u distance + + var low = 0; + var high = il - 1; + var comparison; + + while (low <= high) + { + i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + + comparison = arcLengths[i] - targetArcLength; + + if (comparison < 0) + { + low = i + 1; + } + else if (comparison > 0) + { + high = i - 1; + } + else + { + high = i; + break; + } + } + + i = high; + + if (arcLengths[i] === targetArcLength) + { + return i / (il - 1); + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + var lengthBefore = arcLengths[i]; + var lengthAfter = arcLengths[i + 1]; + + var segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + + // add that fractional amount to t + + return (i + segmentFraction) / (il - 1); + }, + + /** + * Calculate and cache the arc lengths. + * + * @method Phaser.Curves.Curve#updateArcLengths + * @since 3.0.0 + * + * @see Phaser.Curves.Curve#getLengths() + */ + updateArcLengths: function () + { + this.needsUpdate = true; + + this.getLengths(); + } + +}); + +module.exports = Curve; diff --git a/src/curves/EllipseCurve.js b/src/curves/EllipseCurve.js index b0b2d3972..6b4ad3125 100644 --- a/src/curves/EllipseCurve.js +++ b/src/curves/EllipseCurve.js @@ -1,618 +1,618 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) - -var Class = require('../utils/Class'); -var Curve = require('./Curve'); -var DegToRad = require('../math/DegToRad'); -var GetValue = require('../utils/object/GetValue'); -var RadToDeg = require('../math/RadToDeg'); -var Vector2 = require('../math/Vector2'); - -/** - * @classdesc - * An Elliptical Curve derived from the Base Curve class. - * - * See https://en.wikipedia.org/wiki/Elliptic_curve 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 {integer} [startAngle=0] - The start angle of the ellipse, in degrees. - * @param {integer} [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 {integer} [rotation=0] - The rotation of the ellipse, in degrees. - */ -var EllipseCurve = new Class({ - - Extends: Curve, - - initialize: - - function EllipseCurve (x, y, xRadius, yRadius, startAngle, endAngle, clockwise, rotation) - { - if (typeof x === 'object') - { - var config = x; - - x = GetValue(config, 'x', 0); - y = GetValue(config, 'y', 0); - xRadius = GetValue(config, 'xRadius', 0); - yRadius = GetValue(config, 'yRadius', xRadius); - startAngle = GetValue(config, 'startAngle', 0); - endAngle = GetValue(config, 'endAngle', 360); - clockwise = GetValue(config, 'clockwise', false); - rotation = GetValue(config, 'rotation', 0); - } - else - { - if (yRadius === undefined) { yRadius = xRadius; } - if (startAngle === undefined) { startAngle = 0; } - if (endAngle === undefined) { endAngle = 360; } - if (clockwise === undefined) { clockwise = false; } - if (rotation === undefined) { rotation = 0; } - } - - Curve.call(this, 'EllipseCurve'); - - // Center point - - /** - * The center point of the ellipse. Used for calculating rotation. - * - * @name Phaser.Curves.Ellipse#p0 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p0 = new Vector2(x, y); - - /** - * The horizontal radius of the ellipse. - * - * @name Phaser.Curves.Ellipse#_xRadius - * @type {number} - * @private - * @since 3.0.0 - */ - this._xRadius = xRadius; - - /** - * The vertical radius of the ellipse. - * - * @name Phaser.Curves.Ellipse#_yRadius - * @type {number} - * @private - * @since 3.0.0 - */ - this._yRadius = yRadius; - - // Radians - - /** - * The starting angle of the ellipse in radians. - * - * @name Phaser.Curves.Ellipse#_startAngle - * @type {number} - * @private - * @since 3.0.0 - */ - this._startAngle = DegToRad(startAngle); - - /** - * The end angle of the ellipse in radians. - * - * @name Phaser.Curves.Ellipse#_endAngle - * @type {number} - * @private - * @since 3.0.0 - */ - this._endAngle = DegToRad(endAngle); - - /** - * Anti-clockwise direction. - * - * @name Phaser.Curves.Ellipse#_clockwise - * @type {boolean} - * @private - * @since 3.0.0 - */ - this._clockwise = clockwise; - - /** - * The rotation of the arc. - * - * @name Phaser.Curves.Ellipse#_rotation - * @type {number} - * @private - * @since 3.0.0 - */ - this._rotation = DegToRad(rotation); - }, - - /** - * Gets the starting point on the curve. - * - * @method Phaser.Curves.Ellipse#getStartPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return this.getPoint(0, out); - }, - - /** - * [description] - * - * @method Phaser.Curves.Ellipse#getResolution - * @since 3.0.0 - * - * @param {number} divisions - [description] - * - * @return {number} [description] - */ - getResolution: function (divisions) - { - return divisions * 2; - }, - - /** - * Get point at relative position in curve according to length. - * - * @method Phaser.Curves.Ellipse#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - var twoPi = Math.PI * 2; - var deltaAngle = this._endAngle - this._startAngle; - var samePoints = Math.abs(deltaAngle) < Number.EPSILON; - - // ensures that deltaAngle is 0 .. 2 PI - while (deltaAngle < 0) - { - deltaAngle += twoPi; - } - - while (deltaAngle > twoPi) - { - deltaAngle -= twoPi; - } - - if (deltaAngle < Number.EPSILON) - { - if (samePoints) - { - deltaAngle = 0; - } - else - { - deltaAngle = twoPi; - } - } - - if (this._clockwise && !samePoints) - { - if (deltaAngle === twoPi) - { - deltaAngle = - twoPi; - } - else - { - deltaAngle = deltaAngle - twoPi; - } - } - - var angle = this._startAngle + t * deltaAngle; - var x = this.p0.x + this._xRadius * Math.cos(angle); - var y = this.p0.y + this._yRadius * Math.sin(angle); - - if (this._rotation !== 0) - { - var cos = Math.cos(this._rotation); - var sin = Math.sin(this._rotation); - - var tx = x - this.p0.x; - var ty = y - this.p0.y; - - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.p0.x; - y = tx * sin + ty * cos + this.p0.y; - } - - return out.set(x, y); - }, - - /** - * Sets the horizontal radius of this curve. - * - * @method Phaser.Curves.Ellipse#setXRadius - * @since 3.0.0 - * - * @param {number} value - The horizontal radius of this curve. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setXRadius: function (value) - { - this.xRadius = value; - - return this; - }, - - /** - * Sets the vertical radius of this curve. - * - * @method Phaser.Curves.Ellipse#setYRadius - * @since 3.0.0 - * - * @param {number} value - The vertical radius of this curve. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setYRadius: function (value) - { - this.yRadius = value; - - return this; - }, - - /** - * Sets the width of this curve. - * - * @method Phaser.Curves.Ellipse#setWidth - * @since 3.0.0 - * - * @param {number} value - The width of this curve. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setWidth: function (value) - { - this.xRadius = value * 2; - - return this; - }, - - /** - * Sets the height of this curve. - * - * @method Phaser.Curves.Ellipse#setHeight - * @since 3.0.0 - * - * @param {number} value - The height of this curve. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setHeight: function (value) - { - this.yRadius = value * 2; - - return this; - }, - - /** - * Sets the start angle of this curve. - * - * @method Phaser.Curves.Ellipse#setStartAngle - * @since 3.0.0 - * - * @param {number} value - The start angle of this curve, in radians. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setStartAngle: function (value) - { - this.startAngle = value; - - return this; - }, - - /** - * Sets the end angle of this curve. - * - * @method Phaser.Curves.Ellipse#setEndAngle - * @since 3.0.0 - * - * @param {number} value - The end angle of this curve, in radians. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setEndAngle: function (value) - { - this.endAngle = value; - - return this; - }, - - /** - * Sets if this curve extends clockwise or anti-clockwise. - * - * @method Phaser.Curves.Ellipse#setClockwise - * @since 3.0.0 - * - * @param {boolean} value - The clockwise state of this curve. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setClockwise: function (value) - { - this.clockwise = value; - - return this; - }, - - /** - * Sets the rotation of this curve. - * - * @method Phaser.Curves.Ellipse#setRotation - * @since 3.0.0 - * - * @param {number} value - The rotation of this curve, in radians. - * - * @return {Phaser.Curves.Ellipse} This curve object. - */ - setRotation: function (value) - { - this.rotation = value; - - return this; - }, - - /** - * The x coordinate of the center of the ellipse. - * - * @name Phaser.Curves.Ellipse#x - * @type {number} - * @since 3.0.0 - */ - x: { - - get: function () - { - return this.p0.x; - }, - - set: function (value) - { - this.p0.x = value; - } - - }, - - /** - * The y coordinate of the center of the ellipse. - * - * @name Phaser.Curves.Ellipse#y - * @type {number} - * @since 3.0.0 - */ - y: { - - get: function () - { - return this.p0.y; - }, - - set: function (value) - { - this.p0.y = value; - } - - }, - - /** - * The horizontal radius of the ellipse. - * - * @name Phaser.Curves.Ellipse#xRadius - * @type {number} - * @since 3.0.0 - */ - xRadius: { - - get: function () - { - return this._xRadius; - }, - - set: function (value) - { - this._xRadius = value; - } - - }, - - /** - * The vertical radius of the ellipse. - * - * @name Phaser.Curves.Ellipse#yRadius - * @type {number} - * @since 3.0.0 - */ - yRadius: { - - get: function () - { - return this._yRadius; - }, - - set: function (value) - { - this._yRadius = value; - } - - }, - - /** - * The start angle of the ellipse in degrees. - * - * @name Phaser.Curves.Ellipse#startAngle - * @type {number} - * @since 3.0.0 - */ - startAngle: { - - get: function () - { - return RadToDeg(this._startAngle); - }, - - set: function (value) - { - this._startAngle = DegToRad(value); - } - - }, - - /** - * The end angle of the ellipse in degrees. - * - * @name Phaser.Curves.Ellipse#endAngle - * @type {number} - * @since 3.0.0 - */ - endAngle: { - - get: function () - { - return RadToDeg(this._endAngle); - }, - - set: function (value) - { - this._endAngle = DegToRad(value); - } - - }, - - /** - * `true` if the ellipse rotation is clockwise or `false` if anti-clockwise. - * - * @name Phaser.Curves.Ellipse#clockwise - * @type {boolean} - * @since 3.0.0 - */ - clockwise: { - - get: function () - { - return this._clockwise; - }, - - set: function (value) - { - this._clockwise = value; - } - - }, - - /** - * The rotation of the ellipse, relative to the center, in degrees. - * - * @name Phaser.Curves.Ellipse#angle - * @type {number} - * @since 3.14.0 - */ - angle: { - - get: function () - { - return RadToDeg(this._rotation); - }, - - set: function (value) - { - this._rotation = DegToRad(value); - } - - }, - - /** - * The rotation of the ellipse, relative to the center, in radians. - * - * @name Phaser.Curves.Ellipse#rotation - * @type {number} - * @since 3.0.0 - */ - rotation: { - - get: function () - { - return this._rotation; - }, - - set: function (value) - { - this._rotation = value; - } - - }, - - /** - * JSON serialization of the curve. - * - * @method Phaser.Curves.Ellipse#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Curves.JSONEllipseCurve} The JSON object containing this curve data. - */ - toJSON: function () - { - return { - type: this.type, - x: this.p0.x, - y: this.p0.y, - xRadius: this._xRadius, - yRadius: this._yRadius, - startAngle: RadToDeg(this._startAngle), - endAngle: RadToDeg(this._endAngle), - clockwise: this._clockwise, - rotation: RadToDeg(this._rotation) - }; - } - -}); - -/** - * Creates a curve from the provided Ellipse Curve Configuration object. - * - * @function Phaser.Curves.Ellipse.fromJSON - * @since 3.0.0 - * - * @param {Phaser.Types.Curves.JSONEllipseCurve} data - The JSON object containing this curve data. - * - * @return {Phaser.Curves.Ellipse} The ellipse curve constructed from the configuration object. - */ -EllipseCurve.fromJSON = function (data) -{ - return new EllipseCurve(data); -}; - -module.exports = EllipseCurve; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = require('../utils/Class'); +var Curve = require('./Curve'); +var DegToRad = require('../math/DegToRad'); +var GetValue = require('../utils/object/GetValue'); +var RadToDeg = require('../math/RadToDeg'); +var Vector2 = require('../math/Vector2'); + +/** + * @classdesc + * An Elliptical Curve derived from the Base Curve class. + * + * See https://en.wikipedia.org/wiki/Elliptic_curve 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 {integer} [startAngle=0] - The start angle of the ellipse, in degrees. + * @param {integer} [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 {integer} [rotation=0] - The rotation of the ellipse, in degrees. + */ +var EllipseCurve = new Class({ + + Extends: Curve, + + initialize: + + function EllipseCurve (x, y, xRadius, yRadius, startAngle, endAngle, clockwise, rotation) + { + if (typeof x === 'object') + { + var config = x; + + x = GetValue(config, 'x', 0); + y = GetValue(config, 'y', 0); + xRadius = GetValue(config, 'xRadius', 0); + yRadius = GetValue(config, 'yRadius', xRadius); + startAngle = GetValue(config, 'startAngle', 0); + endAngle = GetValue(config, 'endAngle', 360); + clockwise = GetValue(config, 'clockwise', false); + rotation = GetValue(config, 'rotation', 0); + } + else + { + if (yRadius === undefined) { yRadius = xRadius; } + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 360; } + if (clockwise === undefined) { clockwise = false; } + if (rotation === undefined) { rotation = 0; } + } + + Curve.call(this, 'EllipseCurve'); + + // Center point + + /** + * The center point of the ellipse. Used for calculating rotation. + * + * @name Phaser.Curves.Ellipse#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = new Vector2(x, y); + + /** + * The horizontal radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#_xRadius + * @type {number} + * @private + * @since 3.0.0 + */ + this._xRadius = xRadius; + + /** + * The vertical radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#_yRadius + * @type {number} + * @private + * @since 3.0.0 + */ + this._yRadius = yRadius; + + // Radians + + /** + * The starting angle of the ellipse in radians. + * + * @name Phaser.Curves.Ellipse#_startAngle + * @type {number} + * @private + * @since 3.0.0 + */ + this._startAngle = DegToRad(startAngle); + + /** + * The end angle of the ellipse in radians. + * + * @name Phaser.Curves.Ellipse#_endAngle + * @type {number} + * @private + * @since 3.0.0 + */ + this._endAngle = DegToRad(endAngle); + + /** + * Anti-clockwise direction. + * + * @name Phaser.Curves.Ellipse#_clockwise + * @type {boolean} + * @private + * @since 3.0.0 + */ + this._clockwise = clockwise; + + /** + * The rotation of the arc. + * + * @name Phaser.Curves.Ellipse#_rotation + * @type {number} + * @private + * @since 3.0.0 + */ + this._rotation = DegToRad(rotation); + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.Ellipse#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPoint(0, out); + }, + + /** + * [description] + * + * @method Phaser.Curves.Ellipse#getResolution + * @since 3.0.0 + * + * @param {number} divisions - [description] + * + * @return {number} [description] + */ + getResolution: function (divisions) + { + return divisions * 2; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.Ellipse#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var twoPi = Math.PI * 2; + var deltaAngle = this._endAngle - this._startAngle; + var samePoints = Math.abs(deltaAngle) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while (deltaAngle < 0) + { + deltaAngle += twoPi; + } + + while (deltaAngle > twoPi) + { + deltaAngle -= twoPi; + } + + if (deltaAngle < Number.EPSILON) + { + if (samePoints) + { + deltaAngle = 0; + } + else + { + deltaAngle = twoPi; + } + } + + if (this._clockwise && !samePoints) + { + if (deltaAngle === twoPi) + { + deltaAngle = - twoPi; + } + else + { + deltaAngle = deltaAngle - twoPi; + } + } + + var angle = this._startAngle + t * deltaAngle; + var x = this.p0.x + this._xRadius * Math.cos(angle); + var y = this.p0.y + this._yRadius * Math.sin(angle); + + if (this._rotation !== 0) + { + var cos = Math.cos(this._rotation); + var sin = Math.sin(this._rotation); + + var tx = x - this.p0.x; + var ty = y - this.p0.y; + + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.p0.x; + y = tx * sin + ty * cos + this.p0.y; + } + + return out.set(x, y); + }, + + /** + * Sets the horizontal radius of this curve. + * + * @method Phaser.Curves.Ellipse#setXRadius + * @since 3.0.0 + * + * @param {number} value - The horizontal radius of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setXRadius: function (value) + { + this.xRadius = value; + + return this; + }, + + /** + * Sets the vertical radius of this curve. + * + * @method Phaser.Curves.Ellipse#setYRadius + * @since 3.0.0 + * + * @param {number} value - The vertical radius of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setYRadius: function (value) + { + this.yRadius = value; + + return this; + }, + + /** + * Sets the width of this curve. + * + * @method Phaser.Curves.Ellipse#setWidth + * @since 3.0.0 + * + * @param {number} value - The width of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setWidth: function (value) + { + this.xRadius = value * 2; + + return this; + }, + + /** + * Sets the height of this curve. + * + * @method Phaser.Curves.Ellipse#setHeight + * @since 3.0.0 + * + * @param {number} value - The height of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setHeight: function (value) + { + this.yRadius = value * 2; + + return this; + }, + + /** + * Sets the start angle of this curve. + * + * @method Phaser.Curves.Ellipse#setStartAngle + * @since 3.0.0 + * + * @param {number} value - The start angle of this curve, in radians. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setStartAngle: function (value) + { + this.startAngle = value; + + return this; + }, + + /** + * Sets the end angle of this curve. + * + * @method Phaser.Curves.Ellipse#setEndAngle + * @since 3.0.0 + * + * @param {number} value - The end angle of this curve, in radians. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setEndAngle: function (value) + { + this.endAngle = value; + + return this; + }, + + /** + * Sets if this curve extends clockwise or anti-clockwise. + * + * @method Phaser.Curves.Ellipse#setClockwise + * @since 3.0.0 + * + * @param {boolean} value - The clockwise state of this curve. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setClockwise: function (value) + { + this.clockwise = value; + + return this; + }, + + /** + * Sets the rotation of this curve. + * + * @method Phaser.Curves.Ellipse#setRotation + * @since 3.0.0 + * + * @param {number} value - The rotation of this curve, in radians. + * + * @return {Phaser.Curves.Ellipse} This curve object. + */ + setRotation: function (value) + { + this.rotation = value; + + return this; + }, + + /** + * The x coordinate of the center of the ellipse. + * + * @name Phaser.Curves.Ellipse#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.p0.x; + }, + + set: function (value) + { + this.p0.x = value; + } + + }, + + /** + * The y coordinate of the center of the ellipse. + * + * @name Phaser.Curves.Ellipse#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.p0.y; + }, + + set: function (value) + { + this.p0.y = value; + } + + }, + + /** + * The horizontal radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#xRadius + * @type {number} + * @since 3.0.0 + */ + xRadius: { + + get: function () + { + return this._xRadius; + }, + + set: function (value) + { + this._xRadius = value; + } + + }, + + /** + * The vertical radius of the ellipse. + * + * @name Phaser.Curves.Ellipse#yRadius + * @type {number} + * @since 3.0.0 + */ + yRadius: { + + get: function () + { + return this._yRadius; + }, + + set: function (value) + { + this._yRadius = value; + } + + }, + + /** + * The start angle of the ellipse in degrees. + * + * @name Phaser.Curves.Ellipse#startAngle + * @type {number} + * @since 3.0.0 + */ + startAngle: { + + get: function () + { + return RadToDeg(this._startAngle); + }, + + set: function (value) + { + this._startAngle = DegToRad(value); + } + + }, + + /** + * The end angle of the ellipse in degrees. + * + * @name Phaser.Curves.Ellipse#endAngle + * @type {number} + * @since 3.0.0 + */ + endAngle: { + + get: function () + { + return RadToDeg(this._endAngle); + }, + + set: function (value) + { + this._endAngle = DegToRad(value); + } + + }, + + /** + * `true` if the ellipse rotation is clockwise or `false` if anti-clockwise. + * + * @name Phaser.Curves.Ellipse#clockwise + * @type {boolean} + * @since 3.0.0 + */ + clockwise: { + + get: function () + { + return this._clockwise; + }, + + set: function (value) + { + this._clockwise = value; + } + + }, + + /** + * The rotation of the ellipse, relative to the center, in degrees. + * + * @name Phaser.Curves.Ellipse#angle + * @type {number} + * @since 3.14.0 + */ + angle: { + + get: function () + { + return RadToDeg(this._rotation); + }, + + set: function (value) + { + this._rotation = DegToRad(value); + } + + }, + + /** + * The rotation of the ellipse, relative to the center, in radians. + * + * @name Phaser.Curves.Ellipse#rotation + * @type {number} + * @since 3.0.0 + */ + rotation: { + + get: function () + { + return this._rotation; + }, + + set: function (value) + { + this._rotation = value; + } + + }, + + /** + * JSON serialization of the curve. + * + * @method Phaser.Curves.Ellipse#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONEllipseCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + x: this.p0.x, + y: this.p0.y, + xRadius: this._xRadius, + yRadius: this._yRadius, + startAngle: RadToDeg(this._startAngle), + endAngle: RadToDeg(this._endAngle), + clockwise: this._clockwise, + rotation: RadToDeg(this._rotation) + }; + } + +}); + +/** + * Creates a curve from the provided Ellipse Curve Configuration object. + * + * @function Phaser.Curves.Ellipse.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONEllipseCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.Ellipse} The ellipse curve constructed from the configuration object. + */ +EllipseCurve.fromJSON = function (data) +{ + return new EllipseCurve(data); +}; + +module.exports = EllipseCurve; diff --git a/src/curves/LineCurve.js b/src/curves/LineCurve.js index 3b38d4725..768fcf810 100644 --- a/src/curves/LineCurve.js +++ b/src/curves/LineCurve.js @@ -1,299 +1,299 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) - -var Class = require('../utils/Class'); -var Curve = require('./Curve'); -var FromPoints = require('../geom/rectangle/FromPoints'); -var Rectangle = require('../geom/rectangle/Rectangle'); -var Vector2 = require('../math/Vector2'); - -var tmpVec2 = new Vector2(); - -/** - * @classdesc - * A LineCurve is a "curve" comprising exactly two points (a line segment). - * - * @class Line - * @extends Phaser.Curves.Curve - * @memberof Phaser.Curves - * @constructor - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|number[])} p0 - The first endpoint. - * @param {Phaser.Math.Vector2} [p1] - The second endpoint. - */ -var LineCurve = new Class({ - - Extends: Curve, - - initialize: - - // vec2s or array - function LineCurve (p0, p1) - { - Curve.call(this, 'LineCurve'); - - if (Array.isArray(p0)) - { - p1 = new Vector2(p0[2], p0[3]); - p0 = new Vector2(p0[0], p0[1]); - } - - /** - * The first endpoint. - * - * @name Phaser.Curves.Line#p0 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p0 = p0; - - /** - * The second endpoint. - * - * @name Phaser.Curves.Line#p1 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p1 = p1; - - // Override default Curve.arcLengthDivisions - - /** - * The quantity of arc length divisions within the curve. - * - * @name Phaser.Curves.Line#arcLengthDivisions - * @type {integer} - * @default 1 - * @since 3.0.0 - */ - this.arcLengthDivisions = 1; - }, - - /** - * Returns a Rectangle where the position and dimensions match the bounds of this Curve. - * - * @method Phaser.Curves.Line#getBounds - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the bounds in. If not given a new Rectangle will be created. - * - * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object. - */ - getBounds: function (out) - { - if (out === undefined) { out = new Rectangle(); } - - return FromPoints([ this.p0, this.p1 ], out); - }, - - /** - * Gets the starting point on the curve. - * - * @method Phaser.Curves.Line#getStartPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return out.copy(this.p0); - }, - - /** - * Gets the resolution of the line. - * - * @method Phaser.Curves.Line#getResolution - * @since 3.0.0 - * - * @param {number} [divisions=1] - The number of divisions to consider. - * - * @return {number} The resolution. Equal to the number of divisions. - */ - getResolution: function (divisions) - { - if (divisions === undefined) { divisions = 1; } - - return divisions; - }, - - /** - * Get point at relative position in curve according to length. - * - * @method Phaser.Curves.Line#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - if (t === 1) - { - return out.copy(this.p1); - } - - out.copy(this.p1).subtract(this.p0).scale(t).add(this.p0); - - return out; - }, - - // Line curve is linear, so we can overwrite default getPointAt - - /** - * Gets a point at a given position on the line. - * - * @method Phaser.Curves.Line#getPointAt - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} u - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPointAt: function (u, out) - { - return this.getPoint(u, out); - }, - - /** - * Gets the slope of the line as a unit vector. - * - * @method Phaser.Curves.Line#getTangent - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @return {Phaser.Math.Vector2} The tangent vector. - */ - getTangent: function () - { - var tangent = tmpVec2.copy(this.p1).subtract(this.p0); - - return tangent.normalize(); - }, - - // Override default Curve.getUtoTmapping - - /** - * [description] - * - * @method Phaser.Curves.Line#getUtoTmapping - * @since 3.0.0 - * - * @param {number} u - [description] - * @param {integer} distance - [description] - * @param {integer} [divisions] - [description] - * - * @return {number} [description] - */ - getUtoTmapping: function (u, distance, divisions) - { - var t; - - if (distance) - { - var arcLengths = this.getLengths(divisions); - var lineLength = arcLengths[arcLengths.length - 1]; - - // Cannot overshoot the curve - var targetLineLength = Math.min(distance, lineLength); - - t = targetLineLength / lineLength; - } - else - { - t = u; - } - - return t; - }, - - // Override default Curve.draw because this is better than calling getPoints on a line! - - /** - * Draws this curve on the given Graphics object. - * - * The curve is drawn using `Graphics.lineBetween` so will be drawn at whatever the present Graphics line color is. - * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. - * - * @method Phaser.Curves.Line#draw - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] - * - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn. - * - * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn. - */ - draw: function (graphics) - { - graphics.lineBetween(this.p0.x, this.p0.y, this.p1.x, this.p1.y); - - // So you can chain graphics calls - return graphics; - }, - - /** - * Gets a JSON representation of the line. - * - * @method Phaser.Curves.Line#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. - */ - toJSON: function () - { - return { - type: this.type, - points: [ - this.p0.x, this.p0.y, - this.p1.x, this.p1.y - ] - }; - } - -}); - -/** - * Configures this line from a JSON representation. - * - * @function Phaser.Curves.Line.fromJSON - * @since 3.0.0 - * - * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. - * - * @return {Phaser.Curves.Line} A new LineCurve object. - */ -LineCurve.fromJSON = function (data) -{ - var points = data.points; - - var p0 = new Vector2(points[0], points[1]); - var p1 = new Vector2(points[2], points[3]); - - return new LineCurve(p0, p1); -}; - -module.exports = LineCurve; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = require('../utils/Class'); +var Curve = require('./Curve'); +var FromPoints = require('../geom/rectangle/FromPoints'); +var Rectangle = require('../geom/rectangle/Rectangle'); +var Vector2 = require('../math/Vector2'); + +var tmpVec2 = new Vector2(); + +/** + * @classdesc + * A LineCurve is a "curve" comprising exactly two points (a line segment). + * + * @class Line + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|number[])} p0 - The first endpoint. + * @param {Phaser.Math.Vector2} [p1] - The second endpoint. + */ +var LineCurve = new Class({ + + Extends: Curve, + + initialize: + + // vec2s or array + function LineCurve (p0, p1) + { + Curve.call(this, 'LineCurve'); + + if (Array.isArray(p0)) + { + p1 = new Vector2(p0[2], p0[3]); + p0 = new Vector2(p0[0], p0[1]); + } + + /** + * The first endpoint. + * + * @name Phaser.Curves.Line#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = p0; + + /** + * The second endpoint. + * + * @name Phaser.Curves.Line#p1 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p1 = p1; + + // Override default Curve.arcLengthDivisions + + /** + * The quantity of arc length divisions within the curve. + * + * @name Phaser.Curves.Line#arcLengthDivisions + * @type {integer} + * @default 1 + * @since 3.0.0 + */ + this.arcLengthDivisions = 1; + }, + + /** + * Returns a Rectangle where the position and dimensions match the bounds of this Curve. + * + * @method Phaser.Curves.Line#getBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the bounds in. If not given a new Rectangle will be created. + * + * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object. + */ + getBounds: function (out) + { + if (out === undefined) { out = new Rectangle(); } + + return FromPoints([ this.p0, this.p1 ], out); + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.Line#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * Gets the resolution of the line. + * + * @method Phaser.Curves.Line#getResolution + * @since 3.0.0 + * + * @param {number} [divisions=1] - The number of divisions to consider. + * + * @return {number} The resolution. Equal to the number of divisions. + */ + getResolution: function (divisions) + { + if (divisions === undefined) { divisions = 1; } + + return divisions; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.Line#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + if (t === 1) + { + return out.copy(this.p1); + } + + out.copy(this.p1).subtract(this.p0).scale(t).add(this.p0); + + return out; + }, + + // Line curve is linear, so we can overwrite default getPointAt + + /** + * Gets a point at a given position on the line. + * + * @method Phaser.Curves.Line#getPointAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPointAt: function (u, out) + { + return this.getPoint(u, out); + }, + + /** + * Gets the slope of the line as a unit vector. + * + * @method Phaser.Curves.Line#getTangent + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @return {Phaser.Math.Vector2} The tangent vector. + */ + getTangent: function () + { + var tangent = tmpVec2.copy(this.p1).subtract(this.p0); + + return tangent.normalize(); + }, + + // Override default Curve.getUtoTmapping + + /** + * [description] + * + * @method Phaser.Curves.Line#getUtoTmapping + * @since 3.0.0 + * + * @param {number} u - [description] + * @param {integer} distance - [description] + * @param {integer} [divisions] - [description] + * + * @return {number} [description] + */ + getUtoTmapping: function (u, distance, divisions) + { + var t; + + if (distance) + { + var arcLengths = this.getLengths(divisions); + var lineLength = arcLengths[arcLengths.length - 1]; + + // Cannot overshoot the curve + var targetLineLength = Math.min(distance, lineLength); + + t = targetLineLength / lineLength; + } + else + { + t = u; + } + + return t; + }, + + // Override default Curve.draw because this is better than calling getPoints on a line! + + /** + * Draws this curve on the given Graphics object. + * + * The curve is drawn using `Graphics.lineBetween` so will be drawn at whatever the present Graphics line color is. + * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. + * + * @method Phaser.Curves.Line#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn. + * + * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn. + */ + draw: function (graphics) + { + graphics.lineBetween(this.p0.x, this.p0.y, this.p1.x, this.p1.y); + + // So you can chain graphics calls + return graphics; + }, + + /** + * Gets a JSON representation of the line. + * + * @method Phaser.Curves.Line#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + points: [ + this.p0.x, this.p0.y, + this.p1.x, this.p1.y + ] + }; + } + +}); + +/** + * Configures this line from a JSON representation. + * + * @function Phaser.Curves.Line.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.Line} A new LineCurve object. + */ +LineCurve.fromJSON = function (data) +{ + var points = data.points; + + var p0 = new Vector2(points[0], points[1]); + var p1 = new Vector2(points[2], points[3]); + + return new LineCurve(p0, p1); +}; + +module.exports = LineCurve; diff --git a/src/curves/QuadraticBezierCurve.js b/src/curves/QuadraticBezierCurve.js index 5dd513c9a..ae800d49e 100644 --- a/src/curves/QuadraticBezierCurve.js +++ b/src/curves/QuadraticBezierCurve.js @@ -1,208 +1,208 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Curve = require('./Curve'); -var QuadraticBezierInterpolation = require('../math/interpolation/QuadraticBezierInterpolation'); -var Vector2 = require('../math/Vector2'); - -/** - * @classdesc - * [description] - * - * @class QuadraticBezier - * @extends Phaser.Curves.Curve - * @memberof Phaser.Curves - * @constructor - * @since 3.2.0 - * - * @param {(Phaser.Math.Vector2|number[])} p0 - Start point, or an array of point pairs. - * @param {Phaser.Math.Vector2} p1 - Control Point 1. - * @param {Phaser.Math.Vector2} p2 - Control Point 2. - */ -var QuadraticBezier = new Class({ - - Extends: Curve, - - initialize: - - function QuadraticBezier (p0, p1, p2) - { - Curve.call(this, 'QuadraticBezier'); - - if (Array.isArray(p0)) - { - p2 = new Vector2(p0[4], p0[5]); - p1 = new Vector2(p0[2], p0[3]); - p0 = new Vector2(p0[0], p0[1]); - } - - /** - * [description] - * - * @name Phaser.Curves.QuadraticBezier#p0 - * @type {Phaser.Math.Vector2} - * @since 3.2.0 - */ - this.p0 = p0; - - /** - * [description] - * - * @name Phaser.Curves.QuadraticBezier#p1 - * @type {Phaser.Math.Vector2} - * @since 3.2.0 - */ - this.p1 = p1; - - /** - * [description] - * - * @name Phaser.Curves.QuadraticBezier#p2 - * @type {Phaser.Math.Vector2} - * @since 3.2.0 - */ - this.p2 = p2; - }, - - /** - * Gets the starting point on the curve. - * - * @method Phaser.Curves.QuadraticBezier#getStartPoint - * @since 3.2.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return out.copy(this.p0); - }, - - /** - * [description] - * - * @method Phaser.Curves.QuadraticBezier#getResolution - * @since 3.2.0 - * - * @param {number} divisions - [description] - * - * @return {number} [description] - */ - getResolution: function (divisions) - { - return divisions; - }, - - /** - * Get point at relative position in curve according to length. - * - * @method Phaser.Curves.QuadraticBezier#getPoint - * @since 3.2.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - var p0 = this.p0; - var p1 = this.p1; - var p2 = this.p2; - - return out.set( - QuadraticBezierInterpolation(t, p0.x, p1.x, p2.x), - QuadraticBezierInterpolation(t, p0.y, p1.y, p2.y) - ); - }, - - /** - * [description] - * - * @method Phaser.Curves.QuadraticBezier#draw - * @since 3.2.0 - * - * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] - * - * @param {Phaser.GameObjects.Graphics} graphics - `Graphics` object to draw onto. - * @param {integer} [pointsTotal=32] - Number of points to be used for drawing the curve. Higher numbers result in smoother curve but require more processing. - * - * @return {Phaser.GameObjects.Graphics} `Graphics` object that was drawn to. - */ - draw: function (graphics, pointsTotal) - { - if (pointsTotal === undefined) { pointsTotal = 32; } - - var points = this.getPoints(pointsTotal); - - graphics.beginPath(); - graphics.moveTo(this.p0.x, this.p0.y); - - for (var i = 1; i < points.length; i++) - { - graphics.lineTo(points[i].x, points[i].y); - } - - graphics.strokePath(); - - // So you can chain graphics calls - return graphics; - }, - - /** - * Converts the curve into a JSON compatible object. - * - * @method Phaser.Curves.QuadraticBezier#toJSON - * @since 3.2.0 - * - * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. - */ - toJSON: function () - { - return { - type: this.type, - points: [ - this.p0.x, this.p0.y, - this.p1.x, this.p1.y, - this.p2.x, this.p2.y - ] - }; - } - -}); - -/** - * Creates a curve from a JSON object, e. g. created by `toJSON`. - * - * @function Phaser.Curves.QuadraticBezier.fromJSON - * @since 3.2.0 - * - * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. - * - * @return {Phaser.Curves.QuadraticBezier} The created curve instance. - */ -QuadraticBezier.fromJSON = function (data) -{ - var points = data.points; - - var p0 = new Vector2(points[0], points[1]); - var p1 = new Vector2(points[2], points[3]); - var p2 = new Vector2(points[4], points[5]); - - return new QuadraticBezier(p0, p1, p2); -}; - -module.exports = QuadraticBezier; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Curve = require('./Curve'); +var QuadraticBezierInterpolation = require('../math/interpolation/QuadraticBezierInterpolation'); +var Vector2 = require('../math/Vector2'); + +/** + * @classdesc + * [description] + * + * @class QuadraticBezier + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.2.0 + * + * @param {(Phaser.Math.Vector2|number[])} p0 - Start point, or an array of point pairs. + * @param {Phaser.Math.Vector2} p1 - Control Point 1. + * @param {Phaser.Math.Vector2} p2 - Control Point 2. + */ +var QuadraticBezier = new Class({ + + Extends: Curve, + + initialize: + + function QuadraticBezier (p0, p1, p2) + { + Curve.call(this, 'QuadraticBezier'); + + if (Array.isArray(p0)) + { + p2 = new Vector2(p0[4], p0[5]); + p1 = new Vector2(p0[2], p0[3]); + p0 = new Vector2(p0[0], p0[1]); + } + + /** + * [description] + * + * @name Phaser.Curves.QuadraticBezier#p0 + * @type {Phaser.Math.Vector2} + * @since 3.2.0 + */ + this.p0 = p0; + + /** + * [description] + * + * @name Phaser.Curves.QuadraticBezier#p1 + * @type {Phaser.Math.Vector2} + * @since 3.2.0 + */ + this.p1 = p1; + + /** + * [description] + * + * @name Phaser.Curves.QuadraticBezier#p2 + * @type {Phaser.Math.Vector2} + * @since 3.2.0 + */ + this.p2 = p2; + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.QuadraticBezier#getStartPoint + * @since 3.2.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * [description] + * + * @method Phaser.Curves.QuadraticBezier#getResolution + * @since 3.2.0 + * + * @param {number} divisions - [description] + * + * @return {number} [description] + */ + getResolution: function (divisions) + { + return divisions; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.QuadraticBezier#getPoint + * @since 3.2.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var p0 = this.p0; + var p1 = this.p1; + var p2 = this.p2; + + return out.set( + QuadraticBezierInterpolation(t, p0.x, p1.x, p2.x), + QuadraticBezierInterpolation(t, p0.y, p1.y, p2.y) + ); + }, + + /** + * [description] + * + * @method Phaser.Curves.QuadraticBezier#draw + * @since 3.2.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - `Graphics` object to draw onto. + * @param {integer} [pointsTotal=32] - Number of points to be used for drawing the curve. Higher numbers result in smoother curve but require more processing. + * + * @return {Phaser.GameObjects.Graphics} `Graphics` object that was drawn to. + */ + draw: function (graphics, pointsTotal) + { + if (pointsTotal === undefined) { pointsTotal = 32; } + + var points = this.getPoints(pointsTotal); + + graphics.beginPath(); + graphics.moveTo(this.p0.x, this.p0.y); + + for (var i = 1; i < points.length; i++) + { + graphics.lineTo(points[i].x, points[i].y); + } + + graphics.strokePath(); + + // So you can chain graphics calls + return graphics; + }, + + /** + * Converts the curve into a JSON compatible object. + * + * @method Phaser.Curves.QuadraticBezier#toJSON + * @since 3.2.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + return { + type: this.type, + points: [ + this.p0.x, this.p0.y, + this.p1.x, this.p1.y, + this.p2.x, this.p2.y + ] + }; + } + +}); + +/** + * Creates a curve from a JSON object, e. g. created by `toJSON`. + * + * @function Phaser.Curves.QuadraticBezier.fromJSON + * @since 3.2.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.QuadraticBezier} The created curve instance. + */ +QuadraticBezier.fromJSON = function (data) +{ + var points = data.points; + + var p0 = new Vector2(points[0], points[1]); + var p1 = new Vector2(points[2], points[3]); + var p2 = new Vector2(points[4], points[5]); + + return new QuadraticBezier(p0, p1, p2); +}; + +module.exports = QuadraticBezier; diff --git a/src/curves/SplineCurve.js b/src/curves/SplineCurve.js index 0a0ad1aa9..10f66ee54 100644 --- a/src/curves/SplineCurve.js +++ b/src/curves/SplineCurve.js @@ -1,219 +1,219 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) - -var CatmullRom = require('../math/CatmullRom'); -var Class = require('../utils/Class'); -var Curve = require('./Curve'); -var Vector2 = require('../math/Vector2'); - -/** - * @classdesc - * Create a smooth 2d spline curve from a series of points. - * - * @class Spline - * @extends Phaser.Curves.Curve - * @memberof Phaser.Curves - * @constructor - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2[]|number[]|number[][])} [points] - The points that configure the curve. - */ -var SplineCurve = new Class({ - - Extends: Curve, - - initialize: - - function SplineCurve (points) - { - if (points === undefined) { points = []; } - - Curve.call(this, 'SplineCurve'); - - /** - * The Vector2 points that configure the curve. - * - * @name Phaser.Curves.Spline#points - * @type {Phaser.Math.Vector2[]} - * @default [] - * @since 3.0.0 - */ - this.points = []; - - this.addPoints(points); - }, - - /** - * Add a list of points to the current list of Vector2 points of the curve. - * - * @method Phaser.Curves.Spline#addPoints - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2[]|number[]|number[][])} points - The points that configure the curve. - * - * @return {Phaser.Curves.Spline} This curve object. - */ - addPoints: function (points) - { - for (var i = 0; i < points.length; i++) - { - var p = new Vector2(); - - if (typeof points[i] === 'number') - { - p.x = points[i]; - p.y = points[i + 1]; - i++; - } - else if (Array.isArray(points[i])) - { - // An array of arrays? - p.x = points[i][0]; - p.y = points[i][1]; - } - else - { - p.x = points[i].x; - p.y = points[i].y; - } - - this.points.push(p); - } - - return this; - }, - - /** - * Add a point to the current list of Vector2 points of the curve. - * - * @method Phaser.Curves.Spline#addPoint - * @since 3.0.0 - * - * @param {number} x - The x coordinate of this curve - * @param {number} y - The y coordinate of this curve - * - * @return {Phaser.Math.Vector2} The new Vector2 added to the curve - */ - addPoint: function (x, y) - { - var vec = new Vector2(x, y); - - this.points.push(vec); - - return vec; - }, - - /** - * Gets the starting point on the curve. - * - * @method Phaser.Curves.Spline#getStartPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return out.copy(this.points[0]); - }, - - /** - * [description] - * - * @method Phaser.Curves.Spline#getResolution - * @since 3.0.0 - * - * @param {number} divisions - [description] - * - * @return {number} [description] - */ - getResolution: function (divisions) - { - return divisions * this.points.length; - }, - - /** - * Get point at relative position in curve according to length. - * - * @method Phaser.Curves.Spline#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - var points = this.points; - - var point = (points.length - 1) * t; - - var intPoint = Math.floor(point); - - var weight = point - intPoint; - - var p0 = points[(intPoint === 0) ? intPoint : intPoint - 1]; - var p1 = points[intPoint]; - var p2 = points[(intPoint > points.length - 2) ? points.length - 1 : intPoint + 1]; - var p3 = points[(intPoint > points.length - 3) ? points.length - 1 : intPoint + 2]; - - return out.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); - }, - - /** - * Exports a JSON object containing this curve data. - * - * @method Phaser.Curves.Spline#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. - */ - toJSON: function () - { - var points = []; - - for (var i = 0; i < this.points.length; i++) - { - points.push(this.points[i].x); - points.push(this.points[i].y); - } - - return { - type: this.type, - points: points - }; - } - -}); - -/** - * Imports a JSON object containing this curve data. - * - * @function Phaser.Curves.Spline.fromJSON - * @since 3.0.0 - * - * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. - * - * @return {Phaser.Curves.Spline} The spline curve created. - */ -SplineCurve.fromJSON = function (data) -{ - return new SplineCurve(data.points); -}; - -module.exports = SplineCurve; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var CatmullRom = require('../math/CatmullRom'); +var Class = require('../utils/Class'); +var Curve = require('./Curve'); +var Vector2 = require('../math/Vector2'); + +/** + * @classdesc + * Create a smooth 2d spline curve from a series of points. + * + * @class Spline + * @extends Phaser.Curves.Curve + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2[]|number[]|number[][])} [points] - The points that configure the curve. + */ +var SplineCurve = new Class({ + + Extends: Curve, + + initialize: + + function SplineCurve (points) + { + if (points === undefined) { points = []; } + + Curve.call(this, 'SplineCurve'); + + /** + * The Vector2 points that configure the curve. + * + * @name Phaser.Curves.Spline#points + * @type {Phaser.Math.Vector2[]} + * @default [] + * @since 3.0.0 + */ + this.points = []; + + this.addPoints(points); + }, + + /** + * Add a list of points to the current list of Vector2 points of the curve. + * + * @method Phaser.Curves.Spline#addPoints + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2[]|number[]|number[][])} points - The points that configure the curve. + * + * @return {Phaser.Curves.Spline} This curve object. + */ + addPoints: function (points) + { + for (var i = 0; i < points.length; i++) + { + var p = new Vector2(); + + if (typeof points[i] === 'number') + { + p.x = points[i]; + p.y = points[i + 1]; + i++; + } + else if (Array.isArray(points[i])) + { + // An array of arrays? + p.x = points[i][0]; + p.y = points[i][1]; + } + else + { + p.x = points[i].x; + p.y = points[i].y; + } + + this.points.push(p); + } + + return this; + }, + + /** + * Add a point to the current list of Vector2 points of the curve. + * + * @method Phaser.Curves.Spline#addPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate of this curve + * @param {number} y - The y coordinate of this curve + * + * @return {Phaser.Math.Vector2} The new Vector2 added to the curve + */ + addPoint: function (x, y) + { + var vec = new Vector2(x, y); + + this.points.push(vec); + + return vec; + }, + + /** + * Gets the starting point on the curve. + * + * @method Phaser.Curves.Spline#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.points[0]); + }, + + /** + * [description] + * + * @method Phaser.Curves.Spline#getResolution + * @since 3.0.0 + * + * @param {number} divisions - [description] + * + * @return {number} [description] + */ + getResolution: function (divisions) + { + return divisions * this.points.length; + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.Spline#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var points = this.points; + + var point = (points.length - 1) * t; + + var intPoint = Math.floor(point); + + var weight = point - intPoint; + + var p0 = points[(intPoint === 0) ? intPoint : intPoint - 1]; + var p1 = points[intPoint]; + var p2 = points[(intPoint > points.length - 2) ? points.length - 1 : intPoint + 1]; + var p3 = points[(intPoint > points.length - 3) ? points.length - 1 : intPoint + 2]; + + return out.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); + }, + + /** + * Exports a JSON object containing this curve data. + * + * @method Phaser.Curves.Spline#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} The JSON object containing this curve data. + */ + toJSON: function () + { + var points = []; + + for (var i = 0; i < this.points.length; i++) + { + points.push(this.points[i].x); + points.push(this.points[i].y); + } + + return { + type: this.type, + points: points + }; + } + +}); + +/** + * Imports a JSON object containing this curve data. + * + * @function Phaser.Curves.Spline.fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONCurve} data - The JSON object containing this curve data. + * + * @return {Phaser.Curves.Spline} The spline curve created. + */ +SplineCurve.fromJSON = function (data) +{ + return new SplineCurve(data.points); +}; + +module.exports = SplineCurve; diff --git a/src/curves/index.js b/src/curves/index.js index 1b0e4ad22..0e8e9918b 100644 --- a/src/curves/index.js +++ b/src/curves/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Curves - */ - -module.exports = { - Path: require('./path/Path'), - - CubicBezier: require('./CubicBezierCurve'), - Curve: require('./Curve'), - Ellipse: require('./EllipseCurve'), - Line: require('./LineCurve'), - QuadraticBezier: require('./QuadraticBezierCurve'), - Spline: require('./SplineCurve') -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Curves + */ + +module.exports = { + Path: require('./path/Path'), + + CubicBezier: require('./CubicBezierCurve'), + Curve: require('./Curve'), + Ellipse: require('./EllipseCurve'), + Line: require('./LineCurve'), + QuadraticBezier: require('./QuadraticBezierCurve'), + Spline: require('./SplineCurve') +}; diff --git a/src/curves/path/MoveTo.js b/src/curves/path/MoveTo.js index d6e237749..6d9620bb6 100644 --- a/src/curves/path/MoveTo.js +++ b/src/curves/path/MoveTo.js @@ -1,134 +1,134 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A MoveTo Curve is a very simple curve consisting of only a single point. Its intended use is to move the ending point in a Path. - * - * @class MoveTo - * @memberof Phaser.Curves - * @constructor - * @since 3.0.0 - * - * @param {number} [x] - `x` pixel coordinate. - * @param {number} [y] - `y` pixel coordinate. - */ -var MoveTo = new Class({ - - initialize: - - function MoveTo (x, y) - { - // Skip length calcs in paths - - /** - * Denotes that this Curve does not influence the bounds, points, and drawing of its parent Path. Must be `false` or some methods in the parent Path will throw errors. - * - * @name Phaser.Curves.MoveTo#active - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.active = false; - - /** - * The lone point which this curve consists of. - * - * @name Phaser.Curves.MoveTo#p0 - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.p0 = new Vector2(x, y); - }, - - /** - * Get point at relative position in curve according to length. - * - * @method Phaser.Curves.MoveTo#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. - * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. - * - * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - return out.copy(this.p0); - }, - - /** - * Retrieves the point at given position in the curve. This will always return this curve's only point. - * - * @method Phaser.Curves.MoveTo#getPointAt - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} u - The position in the path to retrieve, between 0 and 1. Not used. - * @param {Phaser.Math.Vector2} [out] - An optional vector in which to store the point. - * - * @return {Phaser.Math.Vector2} The modified `out` vector, or a new `Vector2` if none was provided. - */ - getPointAt: function (u, out) - { - return this.getPoint(u, out); - }, - - /** - * Gets the resolution of this curve. - * - * @method Phaser.Curves.MoveTo#getResolution - * @since 3.0.0 - * - * @return {number} The resolution of this curve. For a MoveTo the value is always 1. - */ - getResolution: function () - { - return 1; - }, - - /** - * Gets the length of this curve. - * - * @method Phaser.Curves.MoveTo#getLength - * @since 3.0.0 - * - * @return {number} The length of this curve. For a MoveTo the value is always 0. - */ - getLength: function () - { - return 0; - }, - - /** - * Converts this curve into a JSON-serializable object. - * - * @method Phaser.Curves.MoveTo#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Curves.JSONCurve} A primitive object with the curve's type and only point. - */ - toJSON: function () - { - return { - type: 'MoveTo', - points: [ - this.p0.x, this.p0.y - ] - }; - } - -}); - -module.exports = MoveTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A MoveTo Curve is a very simple curve consisting of only a single point. Its intended use is to move the ending point in a Path. + * + * @class MoveTo + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - `x` pixel coordinate. + * @param {number} [y] - `y` pixel coordinate. + */ +var MoveTo = new Class({ + + initialize: + + function MoveTo (x, y) + { + // Skip length calcs in paths + + /** + * Denotes that this Curve does not influence the bounds, points, and drawing of its parent Path. Must be `false` or some methods in the parent Path will throw errors. + * + * @name Phaser.Curves.MoveTo#active + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.active = false; + + /** + * The lone point which this curve consists of. + * + * @name Phaser.Curves.MoveTo#p0 + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.p0 = new Vector2(x, y); + }, + + /** + * Get point at relative position in curve according to length. + * + * @method Phaser.Curves.MoveTo#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The position along the curve to return. Where 0 is the start and 1 is the end. + * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created. + * + * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.p0); + }, + + /** + * Retrieves the point at given position in the curve. This will always return this curve's only point. + * + * @method Phaser.Curves.MoveTo#getPointAt + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} u - The position in the path to retrieve, between 0 and 1. Not used. + * @param {Phaser.Math.Vector2} [out] - An optional vector in which to store the point. + * + * @return {Phaser.Math.Vector2} The modified `out` vector, or a new `Vector2` if none was provided. + */ + getPointAt: function (u, out) + { + return this.getPoint(u, out); + }, + + /** + * Gets the resolution of this curve. + * + * @method Phaser.Curves.MoveTo#getResolution + * @since 3.0.0 + * + * @return {number} The resolution of this curve. For a MoveTo the value is always 1. + */ + getResolution: function () + { + return 1; + }, + + /** + * Gets the length of this curve. + * + * @method Phaser.Curves.MoveTo#getLength + * @since 3.0.0 + * + * @return {number} The length of this curve. For a MoveTo the value is always 0. + */ + getLength: function () + { + return 0; + }, + + /** + * Converts this curve into a JSON-serializable object. + * + * @method Phaser.Curves.MoveTo#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONCurve} A primitive object with the curve's type and only point. + */ + toJSON: function () + { + return { + type: 'MoveTo', + points: [ + this.p0.x, this.p0.y + ] + }; + } + +}); + +module.exports = MoveTo; diff --git a/src/curves/path/Path.js b/src/curves/path/Path.js index 91d1de709..31fbb419d 100644 --- a/src/curves/path/Path.js +++ b/src/curves/path/Path.js @@ -1,843 +1,843 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) - -var Class = require('../../utils/Class'); -var CubicBezierCurve = require('../CubicBezierCurve'); -var EllipseCurve = require('../EllipseCurve'); -var GameObjectFactory = require('../../gameobjects/GameObjectFactory'); -var LineCurve = require('../LineCurve'); -var MovePathTo = require('./MoveTo'); -var QuadraticBezierCurve = require('../QuadraticBezierCurve'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var SplineCurve = require('../SplineCurve'); -var Vector2 = require('../../math/Vector2'); -var MATH_CONST = require('../../math/const'); - -/** - * @classdesc - * A Path combines multiple Curves into one continuous compound curve. - * It does not matter how many Curves are in the Path or what type they are. - * - * A Curve in a Path does not have to start where the previous Curve ends - that is to say, a Path does not - * have to be an uninterrupted curve. Only the order of the Curves influences the actual points on the Path. - * - * @class Path - * @memberof Phaser.Curves - * @constructor - * @since 3.0.0 - * - * @param {number} [x=0] - The X coordinate of the Path's starting point or a {@link Phaser.Types.Curves.JSONPath}. - * @param {number} [y=0] - The Y coordinate of the Path's starting point. - */ -var Path = new Class({ - - initialize: - - function Path (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - /** - * The name of this Path. - * Empty by default and never populated by Phaser, this is left for developers to use. - * - * @name Phaser.Curves.Path#name - * @type {string} - * @default '' - * @since 3.0.0 - */ - this.name = ''; - - /** - * The list of Curves which make up this Path. - * - * @name Phaser.Curves.Path#curves - * @type {Phaser.Curves.Curve[]} - * @default [] - * @since 3.0.0 - */ - this.curves = []; - - /** - * The cached length of each Curve in the Path. - * - * Used internally by {@link #getCurveLengths}. - * - * @name Phaser.Curves.Path#cacheLengths - * @type {number[]} - * @default [] - * @since 3.0.0 - */ - this.cacheLengths = []; - - /** - * Automatically closes the path. - * - * @name Phaser.Curves.Path#autoClose - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.autoClose = false; - - /** - * The starting point of the Path. - * - * This is not necessarily equivalent to the starting point of the first Curve in the Path. In an empty Path, it's also treated as the ending point. - * - * @name Phaser.Curves.Path#startPoint - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.startPoint = new Vector2(); - - /** - * A temporary vector used to avoid object creation when adding a Curve to the Path. - * - * @name Phaser.Curves.Path#_tmpVec2A - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tmpVec2A = new Vector2(); - - /** - * A temporary vector used to avoid object creation when adding a Curve to the Path. - * - * @name Phaser.Curves.Path#_tmpVec2B - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tmpVec2B = new Vector2(); - - if (typeof x === 'object') - { - this.fromJSON(x); - } - else - { - this.startPoint.set(x, y); - } - }, - - /** - * Appends a Curve to the end of the Path. - * - * The Curve does not have to start where the Path ends or, for an empty Path, at its defined starting point. - * - * @method Phaser.Curves.Path#add - * @since 3.0.0 - * - * @param {Phaser.Curves.Curve} curve - The Curve to append. - * - * @return {Phaser.Curves.Path} This Path object. - */ - add: function (curve) - { - this.curves.push(curve); - - return this; - }, - - /** - * Creates a circular Ellipse Curve positioned at the end of the Path. - * - * @method Phaser.Curves.Path#circleTo - * @since 3.0.0 - * - * @param {number} radius - The radius of the circle. - * @param {boolean} [clockwise=false] - `true` to create a clockwise circle as opposed to a counter-clockwise circle. - * @param {number} [rotation=0] - The rotation of the circle in degrees. - * - * @return {Phaser.Curves.Path} This Path object. - */ - circleTo: function (radius, clockwise, rotation) - { - if (clockwise === undefined) { clockwise = false; } - - return this.ellipseTo(radius, radius, 0, 360, clockwise, rotation); - }, - - /** - * Ensures that the Path is closed. - * - * A closed Path starts and ends at the same point. If the Path is not closed, a straight Line Curve will be created from the ending point directly to the starting point. During the check, the actual starting point of the Path, i.e. the starting point of the first Curve, will be used as opposed to the Path's defined {@link startPoint}, which could differ. - * - * Calling this method on an empty Path will result in an error. - * - * @method Phaser.Curves.Path#closePath - * @since 3.0.0 - * - * @return {Phaser.Curves.Path} This Path object. - */ - closePath: function () - { - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[0].getPoint(0); - var endPoint = this.curves[this.curves.length - 1].getPoint(1); - - if (!startPoint.equals(endPoint)) - { - // This will copy a reference to the vectors, which probably isn't sensible - this.curves.push(new LineCurve(endPoint, startPoint)); - } - - return this; - }, - - /** - * Creates a cubic bezier curve starting at the previous end point and ending at p3, using p1 and p2 as control points. - * - * @method Phaser.Curves.Path#cubicBezierTo - * @since 3.0.0 - * - * @param {(number|Phaser.Math.Vector2)} x - The x coordinate of the end point. Or, if a Vector2, the p1 value. - * @param {(number|Phaser.Math.Vector2)} y - The y coordinate of the end point. Or, if a Vector2, the p2 value. - * @param {(number|Phaser.Math.Vector2)} control1X - The x coordinate of the first control point. Or, if a Vector2, the p3 value. - * @param {number} [control1Y] - The y coordinate of the first control point. Not used if Vector2s are provided as the first 3 arguments. - * @param {number} [control2X] - The x coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. - * @param {number} [control2Y] - The y coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. - * - * @return {Phaser.Curves.Path} This Path object. - */ - cubicBezierTo: function (x, y, control1X, control1Y, control2X, control2Y) - { - var p0 = this.getEndPoint(); - var p1; - var p2; - var p3; - - // Assume they're all Vector2s - if (x instanceof Vector2) - { - p1 = x; - p2 = y; - p3 = control1X; - } - else - { - p1 = new Vector2(control1X, control1Y); - p2 = new Vector2(control2X, control2Y); - p3 = new Vector2(x, y); - } - - return this.add(new CubicBezierCurve(p0, p1, p2, p3)); - }, - - // Creates a quadratic bezier curve starting at the previous end point and ending at p2, using p1 as a control point - - /** - * Creates a Quadratic Bezier Curve starting at the ending point of the Path. - * - * @method Phaser.Curves.Path#quadraticBezierTo - * @since 3.2.0 - * - * @param {(number|Phaser.Math.Vector2[])} x - The X coordinate of the second control point or, if it's a `Vector2`, the first control point. - * @param {number} [y] - The Y coordinate of the second control point or, if `x` is a `Vector2`, the second control point. - * @param {number} [controlX] - If `x` is not a `Vector2`, the X coordinate of the first control point. - * @param {number} [controlY] - If `x` is not a `Vector2`, the Y coordinate of the first control point. - * - * @return {Phaser.Curves.Path} This Path object. - */ - quadraticBezierTo: function (x, y, controlX, controlY) - { - var p0 = this.getEndPoint(); - var p1; - var p2; - - // Assume they're all Vector2s - if (x instanceof Vector2) - { - p1 = x; - p2 = y; - } - else - { - p1 = new Vector2(controlX, controlY); - p2 = new Vector2(x, y); - } - - return this.add(new QuadraticBezierCurve(p0, p1, p2)); - }, - - /** - * Draws all Curves in the Path to a Graphics Game Object. - * - * @method Phaser.Curves.Path#draw - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.Graphics} G - [out,$return] - * - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics Game Object to draw to. - * @param {integer} [pointsTotal=32] - The number of points to draw for each Curve. Higher numbers result in a smoother curve but require more processing. - * - * @return {Phaser.GameObjects.Graphics} The Graphics object which was drawn to. - */ - draw: function (graphics, pointsTotal) - { - for (var i = 0; i < this.curves.length; i++) - { - var curve = this.curves[i]; - - if (!curve.active) - { - continue; - } - - curve.draw(graphics, pointsTotal); - } - - return graphics; - }, - - /** - * Creates an ellipse curve positioned at the previous end point, using the given parameters. - * - * @method Phaser.Curves.Path#ellipseTo - * @since 3.0.0 - * - * @param {number} [xRadius=0] - The horizontal radius of ellipse. - * @param {number} [yRadius=0] - The vertical radius of ellipse. - * @param {integer} [startAngle=0] - The start angle of the ellipse, in degrees. - * @param {integer} [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. - * - * @return {Phaser.Curves.Path} This Path object. - */ - ellipseTo: function (xRadius, yRadius, startAngle, endAngle, clockwise, rotation) - { - var ellipse = new EllipseCurve(0, 0, xRadius, yRadius, startAngle, endAngle, clockwise, rotation); - - var end = this.getEndPoint(this._tmpVec2A); - - // Calculate where to center the ellipse - var start = ellipse.getStartPoint(this._tmpVec2B); - - end.subtract(start); - - ellipse.x = end.x; - ellipse.y = end.y; - - return this.add(ellipse); - }, - - /** - * Creates a Path from a Path Configuration object. - * - * The provided object should be a {@link Phaser.Types.Curves.JSONPath}, as returned by {@link #toJSON}. Providing a malformed object may cause errors. - * - * @method Phaser.Curves.Path#fromJSON - * @since 3.0.0 - * - * @param {Phaser.Types.Curves.JSONPath} data - The JSON object containing the Path data. - * - * @return {Phaser.Curves.Path} This Path object. - */ - fromJSON: function (data) - { - // data should be an object matching the Path.toJSON object structure. - - this.curves = []; - this.cacheLengths = []; - - this.startPoint.set(data.x, data.y); - - this.autoClose = data.autoClose; - - for (var i = 0; i < data.curves.length; i++) - { - var curve = data.curves[i]; - - switch (curve.type) - { - case 'LineCurve': - this.add(LineCurve.fromJSON(curve)); - break; - - case 'EllipseCurve': - this.add(EllipseCurve.fromJSON(curve)); - break; - - case 'SplineCurve': - this.add(SplineCurve.fromJSON(curve)); - break; - - case 'CubicBezierCurve': - this.add(CubicBezierCurve.fromJSON(curve)); - break; - - case 'QuadraticBezierCurve': - this.add(QuadraticBezierCurve.fromJSON(curve)); - break; - } - } - - return this; - }, - - /** - * Returns a Rectangle with a position and size matching the bounds of this Path. - * - * @method Phaser.Curves.Path#getBounds - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the bounds in. - * @param {integer} [accuracy=16] - The accuracy of the bounds calculations. Higher values are more accurate at the cost of calculation speed. - * - * @return {Phaser.Geom.Rectangle} The modified `out` Rectangle, or a new Rectangle if none was provided. - */ - getBounds: function (out, accuracy) - { - if (out === undefined) { out = new Rectangle(); } - if (accuracy === undefined) { accuracy = 16; } - - out.x = Number.MAX_VALUE; - out.y = Number.MAX_VALUE; - - var bounds = new Rectangle(); - var maxRight = MATH_CONST.MIN_SAFE_INTEGER; - var maxBottom = MATH_CONST.MIN_SAFE_INTEGER; - - for (var i = 0; i < this.curves.length; i++) - { - var curve = this.curves[i]; - - if (!curve.active) - { - continue; - } - - curve.getBounds(bounds, accuracy); - - out.x = Math.min(out.x, bounds.x); - out.y = Math.min(out.y, bounds.y); - - maxRight = Math.max(maxRight, bounds.right); - maxBottom = Math.max(maxBottom, bounds.bottom); - } - - out.right = maxRight; - out.bottom = maxBottom; - - return out; - }, - - /** - * Returns an array containing the length of the Path at the end of each Curve. - * - * The result of this method will be cached to avoid recalculating it in subsequent calls. The cache is only invalidated when the {@link #curves} array changes in length, leading to potential inaccuracies if a Curve in the Path is changed, or if a Curve is removed and another is added in its place. - * - * @method Phaser.Curves.Path#getCurveLengths - * @since 3.0.0 - * - * @return {number[]} An array containing the length of the Path at the end of each one of its Curves. - */ - getCurveLengths: function () - { - // We use cache values if curves and cache array are same length - - if (this.cacheLengths.length === this.curves.length) - { - return this.cacheLengths; - } - - // Get length of sub-curve - // Push sums into cached array - - var lengths = []; - var sums = 0; - - for (var i = 0; i < this.curves.length; i++) - { - sums += this.curves[i].getLength(); - - lengths.push(sums); - } - - this.cacheLengths = lengths; - - return lengths; - }, - - /** - * Returns the ending point of the Path. - * - * A Path's ending point is equivalent to the ending point of the last Curve in the Path. For an empty Path, the ending point is at the Path's defined {@link #startPoint}. - * - * @method Phaser.Curves.Path#getEndPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - The object to store the point in. - * - * @return {Phaser.Math.Vector2} The modified `out` object, or a new Vector2 if none was provided. - */ - getEndPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - if (this.curves.length > 0) - { - this.curves[this.curves.length - 1].getPoint(1, out); - } - else - { - out.copy(this.startPoint); - } - - return out; - }, - - /** - * Returns the total length of the Path. - * - * @see {@link #getCurveLengths} - * - * @method Phaser.Curves.Path#getLength - * @since 3.0.0 - * - * @return {number} The total length of the Path. - */ - getLength: function () - { - var lens = this.getCurveLengths(); - - return lens[lens.length - 1]; - }, - - // 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') - - /** - * Calculates the coordinates of the point at the given normalized location (between 0 and 1) on the Path. - * - * The location is relative to the entire Path, not to an individual Curve. A location of 0.5 is always in the middle of the Path and is thus an equal distance away from both its starting and ending points. In a Path with one Curve, it would be in the middle of the Curve; in a Path with two Curves, it could be anywhere on either one of them depending on their lengths. - * - * @method Phaser.Curves.Path#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {number} t - The location of the point to return, between 0 and 1. - * @param {Phaser.Math.Vector2} [out] - The object in which to store the calculated point. - * - * @return {?Phaser.Math.Vector2} The modified `out` object, or a new `Vector2` if none was provided. - */ - getPoint: function (t, out) - { - if (out === undefined) { out = new Vector2(); } - - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; - - while (i < curveLengths.length) - { - if (curveLengths[i] >= d) - { - var diff = curveLengths[i] - d; - var curve = this.curves[i]; - - var segmentLength = curve.getLength(); - var u = (segmentLength === 0) ? 0 : 1 - diff / segmentLength; - - return curve.getPointAt(u, out); - } - - i++; - } - - // loop where sum != 0, sum > d , sum+1 1 && !points[points.length - 1].equals(points[0])) - { - points.push(points[0]); - } - - return points; - }, - - /** - * Returns a randomly chosen point anywhere on the path. This follows the same rules as `getPoint` in that it may return a point on any Curve inside this path. - * - * When calling this method multiple times, the points are not guaranteed to be equally spaced spatially. - * - * @method Phaser.Curves.Path#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. - * - * @return {Phaser.Math.Vector2} The modified `out` object, or a new `Vector2` if none was provided. - */ - getRandomPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return this.getPoint(Math.random(), out); - }, - - /** - * Divides this Path into a set of equally spaced points, - * - * The resulting points are equally spaced with respect to the points' position on the path, but not necessarily equally spaced spatially. - * - * @method Phaser.Curves.Path#getSpacedPoints - * @since 3.0.0 - * - * @param {integer} [divisions=40] - The amount of points to divide this Path into. - * - * @return {Phaser.Math.Vector2[]} A list of the points this path was subdivided into. - */ - getSpacedPoints: function (divisions) - { - if (divisions === undefined) { divisions = 40; } - - var points = []; - - for (var i = 0; i <= divisions; i++) - { - points.push(this.getPoint(i / divisions)); - } - - if (this.autoClose) - { - points.push(points[0]); - } - - return points; - }, - - /** - * Returns the starting point of the Path. - * - * @method Phaser.Curves.Path#getStartPoint - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [out,$return] - * - * @param {Phaser.Math.Vector2} [out] - `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. - * - * @return {Phaser.Math.Vector2} The modified `out` object, or a new Vector2 if none was provided. - */ - getStartPoint: function (out) - { - if (out === undefined) { out = new Vector2(); } - - return out.copy(this.startPoint); - }, - - /** - * Creates a line curve from the previous end point to x/y. - * - * @method Phaser.Curves.Path#lineTo - * @since 3.0.0 - * - * @param {(number|Phaser.Math.Vector2)} x - The X coordinate of the line's end point, or a `Vector2` containing the entire end point. - * @param {number} [y] - The Y coordinate of the line's end point, if a number was passed as the X parameter. - * - * @return {Phaser.Curves.Path} This Path object. - */ - lineTo: function (x, y) - { - if (x instanceof Vector2) - { - this._tmpVec2B.copy(x); - } - else - { - this._tmpVec2B.set(x, y); - } - - var end = this.getEndPoint(this._tmpVec2A); - - return this.add(new LineCurve([ end.x, end.y, this._tmpVec2B.x, this._tmpVec2B.y ])); - }, - - /** - * Creates a spline curve starting at the previous end point, using the given points on the curve. - * - * @method Phaser.Curves.Path#splineTo - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2[]} points - The points the newly created spline curve should consist of. - * - * @return {Phaser.Curves.Path} This Path object. - */ - splineTo: function (points) - { - points.unshift(this.getEndPoint()); - - return this.add(new SplineCurve(points)); - }, - - /** - * Creates a "gap" in this path from the path's current end point to the given coordinates. - * - * After calling this function, this Path's end point will be equal to the given coordinates - * - * @method Phaser.Curves.Path#moveTo - * @since 3.0.0 - * - * @param {(number|Phaser.Math.Vector2)} x - The X coordinate of the position to move the path's end point to, or a `Vector2` containing the entire new end point. - * @param {number} y - The Y coordinate of the position to move the path's end point to, if a number was passed as the X coordinate. - * - * @return {Phaser.Curves.Path} This Path object. - */ - moveTo: function (x, y) - { - if (x instanceof Vector2) - { - return this.add(new MovePathTo(x.x, x.y)); - } - else - { - return this.add(new MovePathTo(x, y)); - } - }, - - /** - * Converts this Path to a JSON object containing the path information and its constituent curves. - * - * @method Phaser.Curves.Path#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.Curves.JSONPath} The JSON object containing this path's data. - */ - toJSON: function () - { - var out = []; - - for (var i = 0; i < this.curves.length; i++) - { - out.push(this.curves[i].toJSON()); - } - - return { - type: 'Path', - x: this.startPoint.x, - y: this.startPoint.y, - autoClose: this.autoClose, - curves: out - }; - }, - - /** - * cacheLengths must be recalculated. - * - * @method Phaser.Curves.Path#updateArcLengths - * @since 3.0.0 - */ - updateArcLengths: function () - { - this.cacheLengths = []; - - this.getCurveLengths(); - }, - - /** - * Disposes of this Path, clearing its internal references to objects so they can be garbage-collected. - * - * @method Phaser.Curves.Path#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.curves.length = 0; - this.cacheLengths.length = 0; - this.startPoint = undefined; - } - -}); - -/** - * Creates a new Path Object. - * - * @method Phaser.GameObjects.GameObjectFactory#path - * @since 3.0.0 - * - * @param {number} x - The horizontal position of this Path. - * @param {number} y - The vertical position of this Path. - * - * @return {Phaser.Curves.Path} The Path Object that was created. - */ -GameObjectFactory.register('path', function (x, y) -{ - return new Path(x, y); -}); - -// 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 - -module.exports = Path; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + +var Class = require('../../utils/Class'); +var CubicBezierCurve = require('../CubicBezierCurve'); +var EllipseCurve = require('../EllipseCurve'); +var GameObjectFactory = require('../../gameobjects/GameObjectFactory'); +var LineCurve = require('../LineCurve'); +var MovePathTo = require('./MoveTo'); +var QuadraticBezierCurve = require('../QuadraticBezierCurve'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var SplineCurve = require('../SplineCurve'); +var Vector2 = require('../../math/Vector2'); +var MATH_CONST = require('../../math/const'); + +/** + * @classdesc + * A Path combines multiple Curves into one continuous compound curve. + * It does not matter how many Curves are in the Path or what type they are. + * + * A Curve in a Path does not have to start where the previous Curve ends - that is to say, a Path does not + * have to be an uninterrupted curve. Only the order of the Curves influences the actual points on the Path. + * + * @class Path + * @memberof Phaser.Curves + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The X coordinate of the Path's starting point or a {@link Phaser.Types.Curves.JSONPath}. + * @param {number} [y=0] - The Y coordinate of the Path's starting point. + */ +var Path = new Class({ + + initialize: + + function Path (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * The name of this Path. + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.Curves.Path#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * The list of Curves which make up this Path. + * + * @name Phaser.Curves.Path#curves + * @type {Phaser.Curves.Curve[]} + * @default [] + * @since 3.0.0 + */ + this.curves = []; + + /** + * The cached length of each Curve in the Path. + * + * Used internally by {@link #getCurveLengths}. + * + * @name Phaser.Curves.Path#cacheLengths + * @type {number[]} + * @default [] + * @since 3.0.0 + */ + this.cacheLengths = []; + + /** + * Automatically closes the path. + * + * @name Phaser.Curves.Path#autoClose + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.autoClose = false; + + /** + * The starting point of the Path. + * + * This is not necessarily equivalent to the starting point of the first Curve in the Path. In an empty Path, it's also treated as the ending point. + * + * @name Phaser.Curves.Path#startPoint + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.startPoint = new Vector2(); + + /** + * A temporary vector used to avoid object creation when adding a Curve to the Path. + * + * @name Phaser.Curves.Path#_tmpVec2A + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2A = new Vector2(); + + /** + * A temporary vector used to avoid object creation when adding a Curve to the Path. + * + * @name Phaser.Curves.Path#_tmpVec2B + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tmpVec2B = new Vector2(); + + if (typeof x === 'object') + { + this.fromJSON(x); + } + else + { + this.startPoint.set(x, y); + } + }, + + /** + * Appends a Curve to the end of the Path. + * + * The Curve does not have to start where the Path ends or, for an empty Path, at its defined starting point. + * + * @method Phaser.Curves.Path#add + * @since 3.0.0 + * + * @param {Phaser.Curves.Curve} curve - The Curve to append. + * + * @return {Phaser.Curves.Path} This Path object. + */ + add: function (curve) + { + this.curves.push(curve); + + return this; + }, + + /** + * Creates a circular Ellipse Curve positioned at the end of the Path. + * + * @method Phaser.Curves.Path#circleTo + * @since 3.0.0 + * + * @param {number} radius - The radius of the circle. + * @param {boolean} [clockwise=false] - `true` to create a clockwise circle as opposed to a counter-clockwise circle. + * @param {number} [rotation=0] - The rotation of the circle in degrees. + * + * @return {Phaser.Curves.Path} This Path object. + */ + circleTo: function (radius, clockwise, rotation) + { + if (clockwise === undefined) { clockwise = false; } + + return this.ellipseTo(radius, radius, 0, 360, clockwise, rotation); + }, + + /** + * Ensures that the Path is closed. + * + * A closed Path starts and ends at the same point. If the Path is not closed, a straight Line Curve will be created from the ending point directly to the starting point. During the check, the actual starting point of the Path, i.e. the starting point of the first Curve, will be used as opposed to the Path's defined {@link startPoint}, which could differ. + * + * Calling this method on an empty Path will result in an error. + * + * @method Phaser.Curves.Path#closePath + * @since 3.0.0 + * + * @return {Phaser.Curves.Path} This Path object. + */ + closePath: function () + { + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[0].getPoint(0); + var endPoint = this.curves[this.curves.length - 1].getPoint(1); + + if (!startPoint.equals(endPoint)) + { + // This will copy a reference to the vectors, which probably isn't sensible + this.curves.push(new LineCurve(endPoint, startPoint)); + } + + return this; + }, + + /** + * Creates a cubic bezier curve starting at the previous end point and ending at p3, using p1 and p2 as control points. + * + * @method Phaser.Curves.Path#cubicBezierTo + * @since 3.0.0 + * + * @param {(number|Phaser.Math.Vector2)} x - The x coordinate of the end point. Or, if a Vector2, the p1 value. + * @param {(number|Phaser.Math.Vector2)} y - The y coordinate of the end point. Or, if a Vector2, the p2 value. + * @param {(number|Phaser.Math.Vector2)} control1X - The x coordinate of the first control point. Or, if a Vector2, the p3 value. + * @param {number} [control1Y] - The y coordinate of the first control point. Not used if Vector2s are provided as the first 3 arguments. + * @param {number} [control2X] - The x coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. + * @param {number} [control2Y] - The y coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. + * + * @return {Phaser.Curves.Path} This Path object. + */ + cubicBezierTo: function (x, y, control1X, control1Y, control2X, control2Y) + { + var p0 = this.getEndPoint(); + var p1; + var p2; + var p3; + + // Assume they're all Vector2s + if (x instanceof Vector2) + { + p1 = x; + p2 = y; + p3 = control1X; + } + else + { + p1 = new Vector2(control1X, control1Y); + p2 = new Vector2(control2X, control2Y); + p3 = new Vector2(x, y); + } + + return this.add(new CubicBezierCurve(p0, p1, p2, p3)); + }, + + // Creates a quadratic bezier curve starting at the previous end point and ending at p2, using p1 as a control point + + /** + * Creates a Quadratic Bezier Curve starting at the ending point of the Path. + * + * @method Phaser.Curves.Path#quadraticBezierTo + * @since 3.2.0 + * + * @param {(number|Phaser.Math.Vector2[])} x - The X coordinate of the second control point or, if it's a `Vector2`, the first control point. + * @param {number} [y] - The Y coordinate of the second control point or, if `x` is a `Vector2`, the second control point. + * @param {number} [controlX] - If `x` is not a `Vector2`, the X coordinate of the first control point. + * @param {number} [controlY] - If `x` is not a `Vector2`, the Y coordinate of the first control point. + * + * @return {Phaser.Curves.Path} This Path object. + */ + quadraticBezierTo: function (x, y, controlX, controlY) + { + var p0 = this.getEndPoint(); + var p1; + var p2; + + // Assume they're all Vector2s + if (x instanceof Vector2) + { + p1 = x; + p2 = y; + } + else + { + p1 = new Vector2(controlX, controlY); + p2 = new Vector2(x, y); + } + + return this.add(new QuadraticBezierCurve(p0, p1, p2)); + }, + + /** + * Draws all Curves in the Path to a Graphics Game Object. + * + * @method Phaser.Curves.Path#draw + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.Graphics} G - [out,$return] + * + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics Game Object to draw to. + * @param {integer} [pointsTotal=32] - The number of points to draw for each Curve. Higher numbers result in a smoother curve but require more processing. + * + * @return {Phaser.GameObjects.Graphics} The Graphics object which was drawn to. + */ + draw: function (graphics, pointsTotal) + { + for (var i = 0; i < this.curves.length; i++) + { + var curve = this.curves[i]; + + if (!curve.active) + { + continue; + } + + curve.draw(graphics, pointsTotal); + } + + return graphics; + }, + + /** + * Creates an ellipse curve positioned at the previous end point, using the given parameters. + * + * @method Phaser.Curves.Path#ellipseTo + * @since 3.0.0 + * + * @param {number} [xRadius=0] - The horizontal radius of ellipse. + * @param {number} [yRadius=0] - The vertical radius of ellipse. + * @param {integer} [startAngle=0] - The start angle of the ellipse, in degrees. + * @param {integer} [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. + * + * @return {Phaser.Curves.Path} This Path object. + */ + ellipseTo: function (xRadius, yRadius, startAngle, endAngle, clockwise, rotation) + { + var ellipse = new EllipseCurve(0, 0, xRadius, yRadius, startAngle, endAngle, clockwise, rotation); + + var end = this.getEndPoint(this._tmpVec2A); + + // Calculate where to center the ellipse + var start = ellipse.getStartPoint(this._tmpVec2B); + + end.subtract(start); + + ellipse.x = end.x; + ellipse.y = end.y; + + return this.add(ellipse); + }, + + /** + * Creates a Path from a Path Configuration object. + * + * The provided object should be a {@link Phaser.Types.Curves.JSONPath}, as returned by {@link #toJSON}. Providing a malformed object may cause errors. + * + * @method Phaser.Curves.Path#fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.Curves.JSONPath} data - The JSON object containing the Path data. + * + * @return {Phaser.Curves.Path} This Path object. + */ + fromJSON: function (data) + { + // data should be an object matching the Path.toJSON object structure. + + this.curves = []; + this.cacheLengths = []; + + this.startPoint.set(data.x, data.y); + + this.autoClose = data.autoClose; + + for (var i = 0; i < data.curves.length; i++) + { + var curve = data.curves[i]; + + switch (curve.type) + { + case 'LineCurve': + this.add(LineCurve.fromJSON(curve)); + break; + + case 'EllipseCurve': + this.add(EllipseCurve.fromJSON(curve)); + break; + + case 'SplineCurve': + this.add(SplineCurve.fromJSON(curve)); + break; + + case 'CubicBezierCurve': + this.add(CubicBezierCurve.fromJSON(curve)); + break; + + case 'QuadraticBezierCurve': + this.add(QuadraticBezierCurve.fromJSON(curve)); + break; + } + } + + return this; + }, + + /** + * Returns a Rectangle with a position and size matching the bounds of this Path. + * + * @method Phaser.Curves.Path#getBounds + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the bounds in. + * @param {integer} [accuracy=16] - The accuracy of the bounds calculations. Higher values are more accurate at the cost of calculation speed. + * + * @return {Phaser.Geom.Rectangle} The modified `out` Rectangle, or a new Rectangle if none was provided. + */ + getBounds: function (out, accuracy) + { + if (out === undefined) { out = new Rectangle(); } + if (accuracy === undefined) { accuracy = 16; } + + out.x = Number.MAX_VALUE; + out.y = Number.MAX_VALUE; + + var bounds = new Rectangle(); + var maxRight = MATH_CONST.MIN_SAFE_INTEGER; + var maxBottom = MATH_CONST.MIN_SAFE_INTEGER; + + for (var i = 0; i < this.curves.length; i++) + { + var curve = this.curves[i]; + + if (!curve.active) + { + continue; + } + + curve.getBounds(bounds, accuracy); + + out.x = Math.min(out.x, bounds.x); + out.y = Math.min(out.y, bounds.y); + + maxRight = Math.max(maxRight, bounds.right); + maxBottom = Math.max(maxBottom, bounds.bottom); + } + + out.right = maxRight; + out.bottom = maxBottom; + + return out; + }, + + /** + * Returns an array containing the length of the Path at the end of each Curve. + * + * The result of this method will be cached to avoid recalculating it in subsequent calls. The cache is only invalidated when the {@link #curves} array changes in length, leading to potential inaccuracies if a Curve in the Path is changed, or if a Curve is removed and another is added in its place. + * + * @method Phaser.Curves.Path#getCurveLengths + * @since 3.0.0 + * + * @return {number[]} An array containing the length of the Path at the end of each one of its Curves. + */ + getCurveLengths: function () + { + // We use cache values if curves and cache array are same length + + if (this.cacheLengths.length === this.curves.length) + { + return this.cacheLengths; + } + + // Get length of sub-curve + // Push sums into cached array + + var lengths = []; + var sums = 0; + + for (var i = 0; i < this.curves.length; i++) + { + sums += this.curves[i].getLength(); + + lengths.push(sums); + } + + this.cacheLengths = lengths; + + return lengths; + }, + + /** + * Returns the ending point of the Path. + * + * A Path's ending point is equivalent to the ending point of the last Curve in the Path. For an empty Path, the ending point is at the Path's defined {@link #startPoint}. + * + * @method Phaser.Curves.Path#getEndPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - The object to store the point in. + * + * @return {Phaser.Math.Vector2} The modified `out` object, or a new Vector2 if none was provided. + */ + getEndPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + if (this.curves.length > 0) + { + this.curves[this.curves.length - 1].getPoint(1, out); + } + else + { + out.copy(this.startPoint); + } + + return out; + }, + + /** + * Returns the total length of the Path. + * + * @see {@link #getCurveLengths} + * + * @method Phaser.Curves.Path#getLength + * @since 3.0.0 + * + * @return {number} The total length of the Path. + */ + getLength: function () + { + var lens = this.getCurveLengths(); + + return lens[lens.length - 1]; + }, + + // 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') + + /** + * Calculates the coordinates of the point at the given normalized location (between 0 and 1) on the Path. + * + * The location is relative to the entire Path, not to an individual Curve. A location of 0.5 is always in the middle of the Path and is thus an equal distance away from both its starting and ending points. In a Path with one Curve, it would be in the middle of the Curve; in a Path with two Curves, it could be anywhere on either one of them depending on their lengths. + * + * @method Phaser.Curves.Path#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {number} t - The location of the point to return, between 0 and 1. + * @param {Phaser.Math.Vector2} [out] - The object in which to store the calculated point. + * + * @return {?Phaser.Math.Vector2} The modified `out` object, or a new `Vector2` if none was provided. + */ + getPoint: function (t, out) + { + if (out === undefined) { out = new Vector2(); } + + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0; + + while (i < curveLengths.length) + { + if (curveLengths[i] >= d) + { + var diff = curveLengths[i] - d; + var curve = this.curves[i]; + + var segmentLength = curve.getLength(); + var u = (segmentLength === 0) ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt(u, out); + } + + i++; + } + + // loop where sum != 0, sum > d , sum+1 1 && !points[points.length - 1].equals(points[0])) + { + points.push(points[0]); + } + + return points; + }, + + /** + * Returns a randomly chosen point anywhere on the path. This follows the same rules as `getPoint` in that it may return a point on any Curve inside this path. + * + * When calling this method multiple times, the points are not guaranteed to be equally spaced spatially. + * + * @method Phaser.Curves.Path#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. + * + * @return {Phaser.Math.Vector2} The modified `out` object, or a new `Vector2` if none was provided. + */ + getRandomPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return this.getPoint(Math.random(), out); + }, + + /** + * Divides this Path into a set of equally spaced points, + * + * The resulting points are equally spaced with respect to the points' position on the path, but not necessarily equally spaced spatially. + * + * @method Phaser.Curves.Path#getSpacedPoints + * @since 3.0.0 + * + * @param {integer} [divisions=40] - The amount of points to divide this Path into. + * + * @return {Phaser.Math.Vector2[]} A list of the points this path was subdivided into. + */ + getSpacedPoints: function (divisions) + { + if (divisions === undefined) { divisions = 40; } + + var points = []; + + for (var i = 0; i <= divisions; i++) + { + points.push(this.getPoint(i / divisions)); + } + + if (this.autoClose) + { + points.push(points[0]); + } + + return points; + }, + + /** + * Returns the starting point of the Path. + * + * @method Phaser.Curves.Path#getStartPoint + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [out,$return] + * + * @param {Phaser.Math.Vector2} [out] - `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. + * + * @return {Phaser.Math.Vector2} The modified `out` object, or a new Vector2 if none was provided. + */ + getStartPoint: function (out) + { + if (out === undefined) { out = new Vector2(); } + + return out.copy(this.startPoint); + }, + + /** + * Creates a line curve from the previous end point to x/y. + * + * @method Phaser.Curves.Path#lineTo + * @since 3.0.0 + * + * @param {(number|Phaser.Math.Vector2)} x - The X coordinate of the line's end point, or a `Vector2` containing the entire end point. + * @param {number} [y] - The Y coordinate of the line's end point, if a number was passed as the X parameter. + * + * @return {Phaser.Curves.Path} This Path object. + */ + lineTo: function (x, y) + { + if (x instanceof Vector2) + { + this._tmpVec2B.copy(x); + } + else + { + this._tmpVec2B.set(x, y); + } + + var end = this.getEndPoint(this._tmpVec2A); + + return this.add(new LineCurve([ end.x, end.y, this._tmpVec2B.x, this._tmpVec2B.y ])); + }, + + /** + * Creates a spline curve starting at the previous end point, using the given points on the curve. + * + * @method Phaser.Curves.Path#splineTo + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2[]} points - The points the newly created spline curve should consist of. + * + * @return {Phaser.Curves.Path} This Path object. + */ + splineTo: function (points) + { + points.unshift(this.getEndPoint()); + + return this.add(new SplineCurve(points)); + }, + + /** + * Creates a "gap" in this path from the path's current end point to the given coordinates. + * + * After calling this function, this Path's end point will be equal to the given coordinates + * + * @method Phaser.Curves.Path#moveTo + * @since 3.0.0 + * + * @param {(number|Phaser.Math.Vector2)} x - The X coordinate of the position to move the path's end point to, or a `Vector2` containing the entire new end point. + * @param {number} y - The Y coordinate of the position to move the path's end point to, if a number was passed as the X coordinate. + * + * @return {Phaser.Curves.Path} This Path object. + */ + moveTo: function (x, y) + { + if (x instanceof Vector2) + { + return this.add(new MovePathTo(x.x, x.y)); + } + else + { + return this.add(new MovePathTo(x, y)); + } + }, + + /** + * Converts this Path to a JSON object containing the path information and its constituent curves. + * + * @method Phaser.Curves.Path#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.Curves.JSONPath} The JSON object containing this path's data. + */ + toJSON: function () + { + var out = []; + + for (var i = 0; i < this.curves.length; i++) + { + out.push(this.curves[i].toJSON()); + } + + return { + type: 'Path', + x: this.startPoint.x, + y: this.startPoint.y, + autoClose: this.autoClose, + curves: out + }; + }, + + /** + * cacheLengths must be recalculated. + * + * @method Phaser.Curves.Path#updateArcLengths + * @since 3.0.0 + */ + updateArcLengths: function () + { + this.cacheLengths = []; + + this.getCurveLengths(); + }, + + /** + * Disposes of this Path, clearing its internal references to objects so they can be garbage-collected. + * + * @method Phaser.Curves.Path#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.curves.length = 0; + this.cacheLengths.length = 0; + this.startPoint = undefined; + } + +}); + +/** + * Creates a new Path Object. + * + * @method Phaser.GameObjects.GameObjectFactory#path + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this Path. + * @param {number} y - The vertical position of this Path. + * + * @return {Phaser.Curves.Path} The Path Object that was created. + */ +GameObjectFactory.register('path', function (x, y) +{ + return new Path(x, y); +}); + +// 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 + +module.exports = Path; diff --git a/src/curves/typedefs/index.js b/src/curves/typedefs/index.js index ed8807be1..fee798dce 100644 --- a/src/curves/typedefs/index.js +++ b/src/curves/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Curves - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Curves + */ diff --git a/src/data/DataManager.js b/src/data/DataManager.js index 5bc295e8d..298b7c982 100644 --- a/src/data/DataManager.js +++ b/src/data/DataManager.js @@ -1,635 +1,635 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Events = require('./events'); - -/** - * @callback DataEachCallback - * - * @param {*} parent - The parent object of the DataManager. - * @param {string} key - The key of the value. - * @param {*} value - The value. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the game object, key, and data. - */ - -/** - * @classdesc - * The Data Manager Component features a means to store pieces of data specific to a Game Object, System or Plugin. - * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, - * or have a property called `events` that is an instance of it. - * - * @class DataManager - * @memberof Phaser.Data - * @constructor - * @since 3.0.0 - * - * @param {object} parent - The object that this DataManager belongs to. - * @param {Phaser.Events.EventEmitter} eventEmitter - The DataManager's event emitter. - */ -var DataManager = new Class({ - - initialize: - - function DataManager (parent, eventEmitter) - { - /** - * The object that this DataManager belongs to. - * - * @name Phaser.Data.DataManager#parent - * @type {*} - * @since 3.0.0 - */ - this.parent = parent; - - /** - * The DataManager's event emitter. - * - * @name Phaser.Data.DataManager#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events = eventEmitter; - - if (!eventEmitter) - { - this.events = (parent.events) ? parent.events : parent; - } - - /** - * The data list. - * - * @name Phaser.Data.DataManager#list - * @type {Object.} - * @default {} - * @since 3.0.0 - */ - this.list = {}; - - /** - * The public values list. You can use this to access anything you have stored - * in this Data Manager. For example, if you set a value called `gold` you can - * access it via: - * - * ```javascript - * this.data.values.gold; - * ``` - * - * You can also modify it directly: - * - * ```javascript - * this.data.values.gold += 1000; - * ``` - * - * Doing so will emit a `setdata` event from the parent of this Data Manager. - * - * Do not modify this object directly. Adding properties directly to this object will not - * emit any events. Always use `DataManager.set` to create new items the first time around. - * - * @name Phaser.Data.DataManager#values - * @type {Object.} - * @default {} - * @since 3.10.0 - */ - this.values = {}; - - /** - * Whether setting data is frozen for this DataManager. - * - * @name Phaser.Data.DataManager#_frozen - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._frozen = false; - - if (!parent.hasOwnProperty('sys') && this.events) - { - this.events.once('destroy', this.destroy, this); - } - }, - - /** - * Retrieves the value for the given key, or undefined if it doesn't exist. - * - * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: - * - * ```javascript - * this.data.get('gold'); - * ``` - * - * Or access the value directly: - * - * ```javascript - * this.data.values.gold; - * ``` - * - * You can also pass in an array of keys, in which case an array of values will be returned: - * - * ```javascript - * this.data.get([ 'gold', 'armor', 'health' ]); - * ``` - * - * This approach is useful for destructuring arrays in ES6. - * - * @method Phaser.Data.DataManager#get - * @since 3.0.0 - * - * @param {(string|string[])} key - The key of the value to retrieve, or an array of keys. - * - * @return {*} The value belonging to the given key, or an array of values, the order of which will match the input array. - */ - get: function (key) - { - var list = this.list; - - if (Array.isArray(key)) - { - var output = []; - - for (var i = 0; i < key.length; i++) - { - output.push(list[key[i]]); - } - - return output; - } - else - { - return list[key]; - } - }, - - /** - * Retrieves all data values in a new object. - * - * @method Phaser.Data.DataManager#getAll - * @since 3.0.0 - * - * @return {Object.} All data values. - */ - getAll: function () - { - var results = {}; - - for (var key in this.list) - { - if (this.list.hasOwnProperty(key)) - { - results[key] = this.list[key]; - } - } - - return results; - }, - - /** - * Queries the DataManager for the values of keys matching the given regular expression. - * - * @method Phaser.Data.DataManager#query - * @since 3.0.0 - * - * @param {RegExp} search - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). - * - * @return {Object.} The values of the keys matching the search string. - */ - query: function (search) - { - var results = {}; - - for (var key in this.list) - { - if (this.list.hasOwnProperty(key) && key.match(search)) - { - results[key] = this.list[key]; - } - } - - return results; - }, - - /** - * Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created. - * - * ```javascript - * data.set('name', 'Red Gem Stone'); - * ``` - * - * You can also pass in an object of key value pairs as the first argument: - * - * ```javascript - * data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); - * ``` - * - * To get a value back again you can call `get`: - * - * ```javascript - * data.get('gold'); - * ``` - * - * Or you can access the value directly via the `values` property, where it works like any other variable: - * - * ```javascript - * data.values.gold += 50; - * ``` - * - * When the value is first set, a `setdata` event is emitted. - * - * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. - * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. - * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. - * - * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. - * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. - * - * @method Phaser.Data.DataManager#set - * @fires Phaser.Data.Events#SET_DATA - * @fires Phaser.Data.Events#CHANGE_DATA - * @fires Phaser.Data.Events#CHANGE_DATA_KEY - * @since 3.0.0 - * - * @param {(string|object)} key - The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored. - * @param {*} data - The value to set for the given key. If an object is provided as the key this argument is ignored. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - set: function (key, data) - { - if (this._frozen) - { - return this; - } - - if (typeof key === 'string') - { - return this.setValue(key, data); - } - else - { - for (var entry in key) - { - this.setValue(entry, key[entry]); - } - } - - return this; - }, - - /** - * Internal value setter, called automatically by the `set` method. - * - * @method Phaser.Data.DataManager#setValue - * @fires Phaser.Data.Events#SET_DATA - * @fires Phaser.Data.Events#CHANGE_DATA - * @fires Phaser.Data.Events#CHANGE_DATA_KEY - * @private - * @since 3.10.0 - * - * @param {string} key - The key to set the value for. - * @param {*} data - The value to set. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - setValue: function (key, data) - { - if (this._frozen) - { - return this; - } - - if (this.has(key)) - { - // Hit the key getter, which will in turn emit the events. - this.values[key] = data; - } - else - { - var _this = this; - var list = this.list; - var events = this.events; - var parent = this.parent; - - Object.defineProperty(this.values, key, { - - enumerable: true, - - configurable: true, - - get: function () - { - return list[key]; - }, - - set: function (value) - { - if (!_this._frozen) - { - var previousValue = list[key]; - list[key] = value; - - events.emit(Events.CHANGE_DATA, parent, key, value, previousValue); - events.emit(Events.CHANGE_DATA_KEY + key, parent, value, previousValue); - } - } - - }); - - list[key] = data; - - events.emit(Events.SET_DATA, parent, key, data); - } - - return this; - }, - - /** - * Passes all data entries to the given callback. - * - * @method Phaser.Data.DataManager#each - * @since 3.0.0 - * - * @param {DataEachCallback} callback - The function to call. - * @param {*} [context] - Value to use as `this` when executing callback. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the game object, key, and data. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - each: function (callback, context) - { - var args = [ this.parent, null, undefined ]; - - for (var i = 1; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (var key in this.list) - { - args[1] = key; - args[2] = this.list[key]; - - callback.apply(context, args); - } - - return this; - }, - - /** - * Merge the given object of key value pairs into this DataManager. - * - * Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument) - * will emit a `changedata` event. - * - * @method Phaser.Data.DataManager#merge - * @fires Phaser.Data.Events#SET_DATA - * @fires Phaser.Data.Events#CHANGE_DATA - * @fires Phaser.Data.Events#CHANGE_DATA_KEY - * @since 3.0.0 - * - * @param {Object.} data - The data to merge. - * @param {boolean} [overwrite=true] - Whether to overwrite existing data. Defaults to true. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - merge: function (data, overwrite) - { - if (overwrite === undefined) { overwrite = true; } - - // Merge data from another component into this one - for (var key in data) - { - if (data.hasOwnProperty(key) && (overwrite || (!overwrite && !this.has(key)))) - { - this.setValue(key, data[key]); - } - } - - return this; - }, - - /** - * Remove the value for the given key. - * - * If the key is found in this Data Manager it is removed from the internal lists and a - * `removedata` event is emitted. - * - * You can also pass in an array of keys, in which case all keys in the array will be removed: - * - * ```javascript - * this.data.remove([ 'gold', 'armor', 'health' ]); - * ``` - * - * @method Phaser.Data.DataManager#remove - * @fires Phaser.Data.Events#REMOVE_DATA - * @since 3.0.0 - * - * @param {(string|string[])} key - The key to remove, or an array of keys to remove. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - remove: function (key) - { - if (this._frozen) - { - return this; - } - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - this.removeValue(key[i]); - } - } - else - { - return this.removeValue(key); - } - - return this; - }, - - /** - * Internal value remover, called automatically by the `remove` method. - * - * @method Phaser.Data.DataManager#removeValue - * @private - * @fires Phaser.Data.Events#REMOVE_DATA - * @since 3.10.0 - * - * @param {string} key - The key to set the value for. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - removeValue: function (key) - { - if (this.has(key)) - { - var data = this.list[key]; - - delete this.list[key]; - delete this.values[key]; - - this.events.emit(Events.REMOVE_DATA, this.parent, key, data); - } - - return this; - }, - - /** - * Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it. - * - * @method Phaser.Data.DataManager#pop - * @fires Phaser.Data.Events#REMOVE_DATA - * @since 3.0.0 - * - * @param {string} key - The key of the value to retrieve and delete. - * - * @return {*} The value of the given key. - */ - pop: function (key) - { - var data = undefined; - - if (!this._frozen && this.has(key)) - { - data = this.list[key]; - - delete this.list[key]; - delete this.values[key]; - - this.events.emit(Events.REMOVE_DATA, this.parent, key, data); - } - - return data; - }, - - /** - * Determines whether the given key is set in this Data Manager. - * - * Please note that the keys are case-sensitive and must be valid JavaScript Object property strings. - * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. - * - * @method Phaser.Data.DataManager#has - * @since 3.0.0 - * - * @param {string} key - The key to check. - * - * @return {boolean} Returns `true` if the key exists, otherwise `false`. - */ - has: function (key) - { - return this.list.hasOwnProperty(key); - }, - - /** - * Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts - * to create new values or update existing ones. - * - * @method Phaser.Data.DataManager#setFreeze - * @since 3.0.0 - * - * @param {boolean} value - Whether to freeze or unfreeze the Data Manager. - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - setFreeze: function (value) - { - this._frozen = value; - - return this; - }, - - /** - * Delete all data in this Data Manager and unfreeze it. - * - * @method Phaser.Data.DataManager#reset - * @since 3.0.0 - * - * @return {Phaser.Data.DataManager} This DataManager object. - */ - reset: function () - { - for (var key in this.list) - { - delete this.list[key]; - delete this.values[key]; - } - - this._frozen = false; - - return this; - }, - - /** - * Destroy this data manager. - * - * @method Phaser.Data.DataManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.reset(); - - this.events.off(Events.CHANGE_DATA); - this.events.off(Events.SET_DATA); - this.events.off(Events.REMOVE_DATA); - - this.parent = null; - }, - - /** - * Gets or sets the frozen state of this Data Manager. - * A frozen Data Manager will block all attempts to create new values or update existing ones. - * - * @name Phaser.Data.DataManager#freeze - * @type {boolean} - * @since 3.0.0 - */ - freeze: { - - get: function () - { - return this._frozen; - }, - - set: function (value) - { - this._frozen = (value) ? true : false; - } - - }, - - /** - * Return the total number of entries in this Data Manager. - * - * @name Phaser.Data.DataManager#count - * @type {integer} - * @since 3.0.0 - */ - count: { - - get: function () - { - var i = 0; - - for (var key in this.list) - { - if (this.list[key] !== undefined) - { - i++; - } - } - - return i; - } - - } - -}); - -module.exports = DataManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Events = require('./events'); + +/** + * @callback DataEachCallback + * + * @param {*} parent - The parent object of the DataManager. + * @param {string} key - The key of the value. + * @param {*} value - The value. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the game object, key, and data. + */ + +/** + * @classdesc + * The Data Manager Component features a means to store pieces of data specific to a Game Object, System or Plugin. + * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, + * or have a property called `events` that is an instance of it. + * + * @class DataManager + * @memberof Phaser.Data + * @constructor + * @since 3.0.0 + * + * @param {object} parent - The object that this DataManager belongs to. + * @param {Phaser.Events.EventEmitter} eventEmitter - The DataManager's event emitter. + */ +var DataManager = new Class({ + + initialize: + + function DataManager (parent, eventEmitter) + { + /** + * The object that this DataManager belongs to. + * + * @name Phaser.Data.DataManager#parent + * @type {*} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * The DataManager's event emitter. + * + * @name Phaser.Data.DataManager#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = eventEmitter; + + if (!eventEmitter) + { + this.events = (parent.events) ? parent.events : parent; + } + + /** + * The data list. + * + * @name Phaser.Data.DataManager#list + * @type {Object.} + * @default {} + * @since 3.0.0 + */ + this.list = {}; + + /** + * The public values list. You can use this to access anything you have stored + * in this Data Manager. For example, if you set a value called `gold` you can + * access it via: + * + * ```javascript + * this.data.values.gold; + * ``` + * + * You can also modify it directly: + * + * ```javascript + * this.data.values.gold += 1000; + * ``` + * + * Doing so will emit a `setdata` event from the parent of this Data Manager. + * + * Do not modify this object directly. Adding properties directly to this object will not + * emit any events. Always use `DataManager.set` to create new items the first time around. + * + * @name Phaser.Data.DataManager#values + * @type {Object.} + * @default {} + * @since 3.10.0 + */ + this.values = {}; + + /** + * Whether setting data is frozen for this DataManager. + * + * @name Phaser.Data.DataManager#_frozen + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._frozen = false; + + if (!parent.hasOwnProperty('sys') && this.events) + { + this.events.once('destroy', this.destroy, this); + } + }, + + /** + * Retrieves the value for the given key, or undefined if it doesn't exist. + * + * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: + * + * ```javascript + * this.data.get('gold'); + * ``` + * + * Or access the value directly: + * + * ```javascript + * this.data.values.gold; + * ``` + * + * You can also pass in an array of keys, in which case an array of values will be returned: + * + * ```javascript + * this.data.get([ 'gold', 'armor', 'health' ]); + * ``` + * + * This approach is useful for destructuring arrays in ES6. + * + * @method Phaser.Data.DataManager#get + * @since 3.0.0 + * + * @param {(string|string[])} key - The key of the value to retrieve, or an array of keys. + * + * @return {*} The value belonging to the given key, or an array of values, the order of which will match the input array. + */ + get: function (key) + { + var list = this.list; + + if (Array.isArray(key)) + { + var output = []; + + for (var i = 0; i < key.length; i++) + { + output.push(list[key[i]]); + } + + return output; + } + else + { + return list[key]; + } + }, + + /** + * Retrieves all data values in a new object. + * + * @method Phaser.Data.DataManager#getAll + * @since 3.0.0 + * + * @return {Object.} All data values. + */ + getAll: function () + { + var results = {}; + + for (var key in this.list) + { + if (this.list.hasOwnProperty(key)) + { + results[key] = this.list[key]; + } + } + + return results; + }, + + /** + * Queries the DataManager for the values of keys matching the given regular expression. + * + * @method Phaser.Data.DataManager#query + * @since 3.0.0 + * + * @param {RegExp} search - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). + * + * @return {Object.} The values of the keys matching the search string. + */ + query: function (search) + { + var results = {}; + + for (var key in this.list) + { + if (this.list.hasOwnProperty(key) && key.match(search)) + { + results[key] = this.list[key]; + } + } + + return results; + }, + + /** + * Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created. + * + * ```javascript + * data.set('name', 'Red Gem Stone'); + * ``` + * + * You can also pass in an object of key value pairs as the first argument: + * + * ```javascript + * data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); + * ``` + * + * To get a value back again you can call `get`: + * + * ```javascript + * data.get('gold'); + * ``` + * + * Or you can access the value directly via the `values` property, where it works like any other variable: + * + * ```javascript + * data.values.gold += 50; + * ``` + * + * When the value is first set, a `setdata` event is emitted. + * + * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. + * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. + * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. + * + * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * + * @method Phaser.Data.DataManager#set + * @fires Phaser.Data.Events#SET_DATA + * @fires Phaser.Data.Events#CHANGE_DATA + * @fires Phaser.Data.Events#CHANGE_DATA_KEY + * @since 3.0.0 + * + * @param {(string|object)} key - The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored. + * @param {*} data - The value to set for the given key. If an object is provided as the key this argument is ignored. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + set: function (key, data) + { + if (this._frozen) + { + return this; + } + + if (typeof key === 'string') + { + return this.setValue(key, data); + } + else + { + for (var entry in key) + { + this.setValue(entry, key[entry]); + } + } + + return this; + }, + + /** + * Internal value setter, called automatically by the `set` method. + * + * @method Phaser.Data.DataManager#setValue + * @fires Phaser.Data.Events#SET_DATA + * @fires Phaser.Data.Events#CHANGE_DATA + * @fires Phaser.Data.Events#CHANGE_DATA_KEY + * @private + * @since 3.10.0 + * + * @param {string} key - The key to set the value for. + * @param {*} data - The value to set. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + setValue: function (key, data) + { + if (this._frozen) + { + return this; + } + + if (this.has(key)) + { + // Hit the key getter, which will in turn emit the events. + this.values[key] = data; + } + else + { + var _this = this; + var list = this.list; + var events = this.events; + var parent = this.parent; + + Object.defineProperty(this.values, key, { + + enumerable: true, + + configurable: true, + + get: function () + { + return list[key]; + }, + + set: function (value) + { + if (!_this._frozen) + { + var previousValue = list[key]; + list[key] = value; + + events.emit(Events.CHANGE_DATA, parent, key, value, previousValue); + events.emit(Events.CHANGE_DATA_KEY + key, parent, value, previousValue); + } + } + + }); + + list[key] = data; + + events.emit(Events.SET_DATA, parent, key, data); + } + + return this; + }, + + /** + * Passes all data entries to the given callback. + * + * @method Phaser.Data.DataManager#each + * @since 3.0.0 + * + * @param {DataEachCallback} callback - The function to call. + * @param {*} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the game object, key, and data. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + each: function (callback, context) + { + var args = [ this.parent, null, undefined ]; + + for (var i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var key in this.list) + { + args[1] = key; + args[2] = this.list[key]; + + callback.apply(context, args); + } + + return this; + }, + + /** + * Merge the given object of key value pairs into this DataManager. + * + * Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument) + * will emit a `changedata` event. + * + * @method Phaser.Data.DataManager#merge + * @fires Phaser.Data.Events#SET_DATA + * @fires Phaser.Data.Events#CHANGE_DATA + * @fires Phaser.Data.Events#CHANGE_DATA_KEY + * @since 3.0.0 + * + * @param {Object.} data - The data to merge. + * @param {boolean} [overwrite=true] - Whether to overwrite existing data. Defaults to true. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + merge: function (data, overwrite) + { + if (overwrite === undefined) { overwrite = true; } + + // Merge data from another component into this one + for (var key in data) + { + if (data.hasOwnProperty(key) && (overwrite || (!overwrite && !this.has(key)))) + { + this.setValue(key, data[key]); + } + } + + return this; + }, + + /** + * Remove the value for the given key. + * + * If the key is found in this Data Manager it is removed from the internal lists and a + * `removedata` event is emitted. + * + * You can also pass in an array of keys, in which case all keys in the array will be removed: + * + * ```javascript + * this.data.remove([ 'gold', 'armor', 'health' ]); + * ``` + * + * @method Phaser.Data.DataManager#remove + * @fires Phaser.Data.Events#REMOVE_DATA + * @since 3.0.0 + * + * @param {(string|string[])} key - The key to remove, or an array of keys to remove. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + remove: function (key) + { + if (this._frozen) + { + return this; + } + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + this.removeValue(key[i]); + } + } + else + { + return this.removeValue(key); + } + + return this; + }, + + /** + * Internal value remover, called automatically by the `remove` method. + * + * @method Phaser.Data.DataManager#removeValue + * @private + * @fires Phaser.Data.Events#REMOVE_DATA + * @since 3.10.0 + * + * @param {string} key - The key to set the value for. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + removeValue: function (key) + { + if (this.has(key)) + { + var data = this.list[key]; + + delete this.list[key]; + delete this.values[key]; + + this.events.emit(Events.REMOVE_DATA, this.parent, key, data); + } + + return this; + }, + + /** + * Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it. + * + * @method Phaser.Data.DataManager#pop + * @fires Phaser.Data.Events#REMOVE_DATA + * @since 3.0.0 + * + * @param {string} key - The key of the value to retrieve and delete. + * + * @return {*} The value of the given key. + */ + pop: function (key) + { + var data = undefined; + + if (!this._frozen && this.has(key)) + { + data = this.list[key]; + + delete this.list[key]; + delete this.values[key]; + + this.events.emit(Events.REMOVE_DATA, this.parent, key, data); + } + + return data; + }, + + /** + * Determines whether the given key is set in this Data Manager. + * + * Please note that the keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * + * @method Phaser.Data.DataManager#has + * @since 3.0.0 + * + * @param {string} key - The key to check. + * + * @return {boolean} Returns `true` if the key exists, otherwise `false`. + */ + has: function (key) + { + return this.list.hasOwnProperty(key); + }, + + /** + * Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts + * to create new values or update existing ones. + * + * @method Phaser.Data.DataManager#setFreeze + * @since 3.0.0 + * + * @param {boolean} value - Whether to freeze or unfreeze the Data Manager. + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + setFreeze: function (value) + { + this._frozen = value; + + return this; + }, + + /** + * Delete all data in this Data Manager and unfreeze it. + * + * @method Phaser.Data.DataManager#reset + * @since 3.0.0 + * + * @return {Phaser.Data.DataManager} This DataManager object. + */ + reset: function () + { + for (var key in this.list) + { + delete this.list[key]; + delete this.values[key]; + } + + this._frozen = false; + + return this; + }, + + /** + * Destroy this data manager. + * + * @method Phaser.Data.DataManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.reset(); + + this.events.off(Events.CHANGE_DATA); + this.events.off(Events.SET_DATA); + this.events.off(Events.REMOVE_DATA); + + this.parent = null; + }, + + /** + * Gets or sets the frozen state of this Data Manager. + * A frozen Data Manager will block all attempts to create new values or update existing ones. + * + * @name Phaser.Data.DataManager#freeze + * @type {boolean} + * @since 3.0.0 + */ + freeze: { + + get: function () + { + return this._frozen; + }, + + set: function (value) + { + this._frozen = (value) ? true : false; + } + + }, + + /** + * Return the total number of entries in this Data Manager. + * + * @name Phaser.Data.DataManager#count + * @type {integer} + * @since 3.0.0 + */ + count: { + + get: function () + { + var i = 0; + + for (var key in this.list) + { + if (this.list[key] !== undefined) + { + i++; + } + } + + return i; + } + + } + +}); + +module.exports = DataManager; diff --git a/src/data/DataManagerPlugin.js b/src/data/DataManagerPlugin.js index 3245a536d..73a71c5a2 100644 --- a/src/data/DataManagerPlugin.js +++ b/src/data/DataManagerPlugin.js @@ -1,121 +1,121 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var DataManager = require('./DataManager'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); - -/** - * @classdesc - * The Data Component features a means to store pieces of data specific to a Game Object, System or Plugin. - * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, - * or have a property called `events` that is an instance of it. - * - * @class DataManagerPlugin - * @extends Phaser.Data.DataManager - * @memberof Phaser.Data - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - A reference to the Scene that this DataManager belongs to. - */ -var DataManagerPlugin = new Class({ - - Extends: DataManager, - - initialize: - - function DataManagerPlugin (scene) - { - DataManager.call(this, scene, scene.sys.events); - - /** - * A reference to the Scene that this DataManager belongs to. - * - * @name Phaser.Data.DataManagerPlugin#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene's Systems. - * - * @name Phaser.Data.DataManagerPlugin#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Data.DataManagerPlugin#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.events = this.systems.events; - - this.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Data.DataManagerPlugin#start - * @private - * @since 3.5.0 - */ - start: function () - { - this.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Data.DataManagerPlugin#shutdown - * @private - * @since 3.5.0 - */ - shutdown: function () - { - this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Data.DataManagerPlugin#destroy - * @since 3.5.0 - */ - destroy: function () - { - DataManager.prototype.destroy.call(this); - - this.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('DataManagerPlugin', DataManagerPlugin, 'data'); - -module.exports = DataManagerPlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var DataManager = require('./DataManager'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); + +/** + * @classdesc + * The Data Component features a means to store pieces of data specific to a Game Object, System or Plugin. + * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, + * or have a property called `events` that is an instance of it. + * + * @class DataManagerPlugin + * @extends Phaser.Data.DataManager + * @memberof Phaser.Data + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that this DataManager belongs to. + */ +var DataManagerPlugin = new Class({ + + Extends: DataManager, + + initialize: + + function DataManagerPlugin (scene) + { + DataManager.call(this, scene, scene.sys.events); + + /** + * A reference to the Scene that this DataManager belongs to. + * + * @name Phaser.Data.DataManagerPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene's Systems. + * + * @name Phaser.Data.DataManagerPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Data.DataManagerPlugin#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.events = this.systems.events; + + this.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Data.DataManagerPlugin#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Data.DataManagerPlugin#shutdown + * @private + * @since 3.5.0 + */ + shutdown: function () + { + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Data.DataManagerPlugin#destroy + * @since 3.5.0 + */ + destroy: function () + { + DataManager.prototype.destroy.call(this); + + this.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('DataManagerPlugin', DataManagerPlugin, 'data'); + +module.exports = DataManagerPlugin; diff --git a/src/data/events/CHANGE_DATA_EVENT.js b/src/data/events/CHANGE_DATA_EVENT.js index ca9219315..24c11003a 100644 --- a/src/data/events/CHANGE_DATA_EVENT.js +++ b/src/data/events/CHANGE_DATA_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Change Data Event. - * - * This event is dispatched by a Data Manager when an item in the data store is changed. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * a change data event from a Game Object you would use: `sprite.data.on('changedata', listener)`. - * - * This event is dispatched for all items that change in the Data Manager. - * To listen for the change of a specific item, use the `CHANGE_DATA_KEY_EVENT` event. - * - * @event Phaser.Data.Events#CHANGE_DATA - * @since 3.0.0 - * - * @param {any} parent - A reference to the object that the Data Manager responsible for this event belongs to. - * @param {string} key - The unique key of the data item within the Data Manager. - * @param {any} value - The new value of the item in the Data Manager. - * @param {any} previousValue - The previous value of the item in the Data Manager. - */ -module.exports = 'changedata'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Change Data Event. + * + * This event is dispatched by a Data Manager when an item in the data store is changed. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * a change data event from a Game Object you would use: `sprite.data.on('changedata', listener)`. + * + * This event is dispatched for all items that change in the Data Manager. + * To listen for the change of a specific item, use the `CHANGE_DATA_KEY_EVENT` event. + * + * @event Phaser.Data.Events#CHANGE_DATA + * @since 3.0.0 + * + * @param {any} parent - A reference to the object that the Data Manager responsible for this event belongs to. + * @param {string} key - The unique key of the data item within the Data Manager. + * @param {any} value - The new value of the item in the Data Manager. + * @param {any} previousValue - The previous value of the item in the Data Manager. + */ +module.exports = 'changedata'; diff --git a/src/data/events/CHANGE_DATA_KEY_EVENT.js b/src/data/events/CHANGE_DATA_KEY_EVENT.js index 93be4bc31..d783ae338 100644 --- a/src/data/events/CHANGE_DATA_KEY_EVENT.js +++ b/src/data/events/CHANGE_DATA_KEY_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Change Data Key Event. - * - * This event is dispatched by a Data Manager when an item in the data store is changed. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * the change of a specific data item from a Game Object you would use: `sprite.data.on('changedata-key', listener)`, - * where `key` is the unique string key of the data item. For example, if you have a data item stored called `gold` - * then you can listen for `sprite.data.on('changedata-gold')`. - * - * @event Phaser.Data.Events#CHANGE_DATA_KEY - * @since 3.16.1 - * - * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. - * @param {any} value - The item that was updated in the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. - * @param {any} previousValue - The previous item that was updated in the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. - */ -module.exports = 'changedata-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Change Data Key Event. + * + * This event is dispatched by a Data Manager when an item in the data store is changed. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the change of a specific data item from a Game Object you would use: `sprite.data.on('changedata-key', listener)`, + * where `key` is the unique string key of the data item. For example, if you have a data item stored called `gold` + * then you can listen for `sprite.data.on('changedata-gold')`. + * + * @event Phaser.Data.Events#CHANGE_DATA_KEY + * @since 3.16.1 + * + * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. + * @param {any} value - The item that was updated in the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + * @param {any} previousValue - The previous item that was updated in the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + */ +module.exports = 'changedata-'; diff --git a/src/data/events/REMOVE_DATA_EVENT.js b/src/data/events/REMOVE_DATA_EVENT.js index 7e0e5c9a2..84c255837 100644 --- a/src/data/events/REMOVE_DATA_EVENT.js +++ b/src/data/events/REMOVE_DATA_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Remove Data Event. - * - * This event is dispatched by a Data Manager when an item is removed from it. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * the removal of a data item on a Game Object you would use: `sprite.data.on('removedata', listener)`. - * - * @event Phaser.Data.Events#REMOVE_DATA - * @since 3.0.0 - * - * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. - * @param {string} key - The unique key of the data item within the Data Manager. - * @param {any} data - The item that was removed from the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. - */ -module.exports = 'removedata'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Remove Data Event. + * + * This event is dispatched by a Data Manager when an item is removed from it. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the removal of a data item on a Game Object you would use: `sprite.data.on('removedata', listener)`. + * + * @event Phaser.Data.Events#REMOVE_DATA + * @since 3.0.0 + * + * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. + * @param {string} key - The unique key of the data item within the Data Manager. + * @param {any} data - The item that was removed from the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + */ +module.exports = 'removedata'; diff --git a/src/data/events/SET_DATA_EVENT.js b/src/data/events/SET_DATA_EVENT.js index aa03c6c56..e8a7d8d17 100644 --- a/src/data/events/SET_DATA_EVENT.js +++ b/src/data/events/SET_DATA_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Set Data Event. - * - * This event is dispatched by a Data Manager when a new item is added to the data store. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * the addition of a new data item on a Game Object you would use: `sprite.data.on('setdata', listener)`. - * - * @event Phaser.Data.Events#SET_DATA - * @since 3.0.0 - * - * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. - * @param {string} key - The unique key of the data item within the Data Manager. - * @param {any} data - The item that was added to the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. - */ -module.exports = 'setdata'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Set Data Event. + * + * This event is dispatched by a Data Manager when a new item is added to the data store. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the addition of a new data item on a Game Object you would use: `sprite.data.on('setdata', listener)`. + * + * @event Phaser.Data.Events#SET_DATA + * @since 3.0.0 + * + * @param {any} parent - A reference to the object that owns the instance of the Data Manager responsible for this event. + * @param {string} key - The unique key of the data item within the Data Manager. + * @param {any} data - The item that was added to the Data Manager. This can be of any data type, i.e. a string, boolean, number, object or instance. + */ +module.exports = 'setdata'; diff --git a/src/data/events/index.js b/src/data/events/index.js index 11c85b5e4..3ebdc5605 100644 --- a/src/data/events/index.js +++ b/src/data/events/index.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Data.Events - */ - -module.exports = { - - CHANGE_DATA: require('./CHANGE_DATA_EVENT'), - CHANGE_DATA_KEY: require('./CHANGE_DATA_KEY_EVENT'), - REMOVE_DATA: require('./REMOVE_DATA_EVENT'), - SET_DATA: require('./SET_DATA_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Data.Events + */ + +module.exports = { + + CHANGE_DATA: require('./CHANGE_DATA_EVENT'), + CHANGE_DATA_KEY: require('./CHANGE_DATA_KEY_EVENT'), + REMOVE_DATA: require('./REMOVE_DATA_EVENT'), + SET_DATA: require('./SET_DATA_EVENT') + +}; diff --git a/src/data/index.js b/src/data/index.js index a1406eba1..f8f0aa9f4 100644 --- a/src/data/index.js +++ b/src/data/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Data - */ - -module.exports = { - - DataManager: require('./DataManager'), - DataManagerPlugin: require('./DataManagerPlugin'), - Events: require('./events') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Data + */ + +module.exports = { + + DataManager: require('./DataManager'), + DataManagerPlugin: require('./DataManagerPlugin'), + Events: require('./events') + +}; diff --git a/src/device/Audio.js b/src/device/Audio.js index 2fbc77106..ed1a9442e 100644 --- a/src/device/Audio.js +++ b/src/device/Audio.js @@ -1,119 +1,119 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Browser = require('./Browser'); - -/** - * Determines the audio playback capabilities of the device 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.audio` from within any Scene. - * - * @typedef {object} Phaser.Device.Audio - * @since 3.0.0 - * - * @property {boolean} audioData - Can this device play HTML Audio tags? - * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? - * @property {boolean} m4a - Can this device can play m4a files. - * @property {boolean} mp3 - Can this device play mp3 files? - * @property {boolean} ogg - Can this device play ogg files? - * @property {boolean} opus - Can this device play opus files? - * @property {boolean} wav - Can this device play wav files? - * @property {boolean} webAudio - Does this device have the Web Audio API? - * @property {boolean} webm - Can this device play webm files? - */ -var Audio = { - - audioData: false, - dolby: false, - m4a: false, - mp3: false, - ogg: false, - opus: false, - wav: false, - webAudio: false, - webm: false - -}; - -function init () -{ - Audio.audioData = !!(window['Audio']); - - Audio.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); - - var audioElement = document.createElement('audio'); - - var result = !!audioElement.canPlayType; - - try - { - if (result) - { - if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) - { - Audio.ogg = true; - } - - if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) - { - Audio.opus = true; - } - - if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) - { - Audio.mp3 = true; - } - - // Mimetypes accepted: - // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements - // bit.ly/iphoneoscodecs - if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) - { - Audio.wav = true; - } - - if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) - { - Audio.m4a = true; - } - - if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) - { - Audio.webm = true; - } - - if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') - { - if (Browser.edge) - { - Audio.dolby = true; - } - else if (Browser.safari && Browser.safariVersion >= 9) - { - if ((/Mac OS X (\d+)_(\d+)/).test(navigator.userAgent)) - { - var major = parseInt(RegExp.$1, 10); - var minor = parseInt(RegExp.$2, 10); - - if ((major === 10 && minor >= 11) || major > 10) - { - Audio.dolby = true; - } - } - } - } - } - } - catch (e) - { - // Nothing to do here - } - - return Audio; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Browser = require('./Browser'); + +/** + * Determines the audio playback capabilities of the device 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.audio` from within any Scene. + * + * @typedef {object} Phaser.Device.Audio + * @since 3.0.0 + * + * @property {boolean} audioData - Can this device play HTML Audio tags? + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @property {boolean} m4a - Can this device can play m4a files. + * @property {boolean} mp3 - Can this device play mp3 files? + * @property {boolean} ogg - Can this device play ogg files? + * @property {boolean} opus - Can this device play opus files? + * @property {boolean} wav - Can this device play wav files? + * @property {boolean} webAudio - Does this device have the Web Audio API? + * @property {boolean} webm - Can this device play webm files? + */ +var Audio = { + + audioData: false, + dolby: false, + m4a: false, + mp3: false, + ogg: false, + opus: false, + wav: false, + webAudio: false, + webm: false + +}; + +function init () +{ + Audio.audioData = !!(window['Audio']); + + Audio.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + + var audioElement = document.createElement('audio'); + + var result = !!audioElement.canPlayType; + + try + { + if (result) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + Audio.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + Audio.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + Audio.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + Audio.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + Audio.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + Audio.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (Browser.edge) + { + Audio.dolby = true; + } + else if (Browser.safari && Browser.safariVersion >= 9) + { + if ((/Mac OS X (\d+)_(\d+)/).test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + Audio.dolby = true; + } + } + } + } + } + } + catch (e) + { + // Nothing to do here + } + + return Audio; +} + +module.exports = init(); diff --git a/src/device/Browser.js b/src/device/Browser.js index c0001acf8..fd7c3cf21 100644 --- a/src/device/Browser.js +++ b/src/device/Browser.js @@ -1,104 +1,104 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var OS = require('./OS'); - -/** - * 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+) - * @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} - */ -var Browser = { - - chrome: false, - chromeVersion: 0, - edge: false, - firefox: false, - firefoxVersion: 0, - ie: false, - ieVersion: 0, - mobileSafari: false, - opera: false, - safari: false, - safariVersion: 0, - silk: false, - trident: false, - tridentVersion: 0 - -}; - -function init () -{ - var ua = navigator.userAgent; - - if (/Edge\/\d+/.test(ua)) - { - Browser.edge = true; - } - else if ((/Chrome\/(\d+)/).test(ua) && !OS.windowsPhone) - { - Browser.chrome = true; - Browser.chromeVersion = parseInt(RegExp.$1, 10); - } - else if ((/Firefox\D+(\d+)/).test(ua)) - { - Browser.firefox = true; - Browser.firefoxVersion = parseInt(RegExp.$1, 10); - } - else if ((/AppleWebKit/).test(ua) && OS.iOS) - { - Browser.mobileSafari = true; - } - else if ((/MSIE (\d+\.\d+);/).test(ua)) - { - Browser.ie = true; - Browser.ieVersion = parseInt(RegExp.$1, 10); - } - else if ((/Opera/).test(ua)) - { - Browser.opera = true; - } - else if ((/Safari/).test(ua) && !OS.windowsPhone) - { - Browser.safari = true; - } - else if ((/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/).test(ua)) - { - Browser.ie = true; - Browser.trident = true; - Browser.tridentVersion = parseInt(RegExp.$1, 10); - Browser.ieVersion = parseInt(RegExp.$3, 10); - } - - // Silk gets its own if clause because its ua also contains 'Safari' - if ((/Silk/).test(ua)) - { - Browser.silk = true; - } - - return Browser; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var OS = require('./OS'); + +/** + * 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+) + * @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} + */ +var Browser = { + + chrome: false, + chromeVersion: 0, + edge: false, + firefox: false, + firefoxVersion: 0, + ie: false, + ieVersion: 0, + mobileSafari: false, + opera: false, + safari: false, + safariVersion: 0, + silk: false, + trident: false, + tridentVersion: 0 + +}; + +function init () +{ + var ua = navigator.userAgent; + + if (/Edge\/\d+/.test(ua)) + { + Browser.edge = true; + } + else if ((/Chrome\/(\d+)/).test(ua) && !OS.windowsPhone) + { + Browser.chrome = true; + Browser.chromeVersion = parseInt(RegExp.$1, 10); + } + else if ((/Firefox\D+(\d+)/).test(ua)) + { + Browser.firefox = true; + Browser.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if ((/AppleWebKit/).test(ua) && OS.iOS) + { + Browser.mobileSafari = true; + } + else if ((/MSIE (\d+\.\d+);/).test(ua)) + { + Browser.ie = true; + Browser.ieVersion = parseInt(RegExp.$1, 10); + } + else if ((/Opera/).test(ua)) + { + Browser.opera = true; + } + else if ((/Safari/).test(ua) && !OS.windowsPhone) + { + Browser.safari = true; + } + else if ((/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/).test(ua)) + { + Browser.ie = true; + Browser.trident = true; + Browser.tridentVersion = parseInt(RegExp.$1, 10); + Browser.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if ((/Silk/).test(ua)) + { + Browser.silk = true; + } + + return Browser; +} + +module.exports = init(); diff --git a/src/device/CanvasFeatures.js b/src/device/CanvasFeatures.js index bae09698b..494428cd8 100644 --- a/src/device/CanvasFeatures.js +++ b/src/device/CanvasFeatures.js @@ -1,108 +1,108 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../display/canvas/CanvasPool'); - -/** - * Determines the canvas features of the browser 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.canvasFeatures` from within any Scene. - * - * @typedef {object} Phaser.Device.CanvasFeatures - * @since 3.0.0 - * - * @property {boolean} supportInverseAlpha - Set to true if the browser supports inversed alpha. - * @property {boolean} supportNewBlendModes - Set to true if the browser supports new canvas blend modes. - */ -var CanvasFeatures = { - - supportInverseAlpha: false, - supportNewBlendModes: false - -}; - -function checkBlendMode () -{ - var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/'; - var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg=='; - - var magenta = new Image(); - - magenta.onload = function () - { - var yellow = new Image(); - - yellow.onload = function () - { - var canvas = CanvasPool.create(yellow, 6, 1); - var context = canvas.getContext('2d'); - - context.globalCompositeOperation = 'multiply'; - - context.drawImage(magenta, 0, 0); - context.drawImage(yellow, 2, 0); - - if (!context.getImageData(2, 0, 1, 1)) - { - return false; - } - - var data = context.getImageData(2, 0, 1, 1).data; - - CanvasPool.remove(yellow); - - CanvasFeatures.supportNewBlendModes = (data[0] === 255 && data[1] === 0 && data[2] === 0); - }; - - yellow.src = pngHead + '/wCKxvRF' + pngEnd; - }; - - magenta.src = pngHead + 'AP804Oa6' + pngEnd; - - return false; -} - -function checkInverseAlpha () -{ - var canvas = CanvasPool.create(this, 2, 1); - var context = canvas.getContext('2d'); - - context.fillStyle = 'rgba(10, 20, 30, 0.5)'; - - // Draw a single pixel - context.fillRect(0, 0, 1, 1); - - // Get the color values - var s1 = context.getImageData(0, 0, 1, 1); - - if (s1 === null) - { - return false; - } - - // Plot them to x2 - context.putImageData(s1, 1, 0); - - // Get those values - var s2 = context.getImageData(1, 0, 1, 1); - - // Compare and return - return (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]); -} - -function init () -{ - if (document !== undefined) - { - CanvasFeatures.supportNewBlendModes = checkBlendMode(); - CanvasFeatures.supportInverseAlpha = checkInverseAlpha(); - } - - return CanvasFeatures; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../display/canvas/CanvasPool'); + +/** + * Determines the canvas features of the browser 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.canvasFeatures` from within any Scene. + * + * @typedef {object} Phaser.Device.CanvasFeatures + * @since 3.0.0 + * + * @property {boolean} supportInverseAlpha - Set to true if the browser supports inversed alpha. + * @property {boolean} supportNewBlendModes - Set to true if the browser supports new canvas blend modes. + */ +var CanvasFeatures = { + + supportInverseAlpha: false, + supportNewBlendModes: false + +}; + +function checkBlendMode () +{ + var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/'; + var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg=='; + + var magenta = new Image(); + + magenta.onload = function () + { + var yellow = new Image(); + + yellow.onload = function () + { + var canvas = CanvasPool.create(yellow, 6, 1); + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + if (!context.getImageData(2, 0, 1, 1)) + { + return false; + } + + var data = context.getImageData(2, 0, 1, 1).data; + + CanvasPool.remove(yellow); + + CanvasFeatures.supportNewBlendModes = (data[0] === 255 && data[1] === 0 && data[2] === 0); + }; + + yellow.src = pngHead + '/wCKxvRF' + pngEnd; + }; + + magenta.src = pngHead + 'AP804Oa6' + pngEnd; + + return false; +} + +function checkInverseAlpha () +{ + var canvas = CanvasPool.create(this, 2, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1 === null) + { + return false; + } + + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and return + return (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]); +} + +function init () +{ + if (document !== undefined) + { + CanvasFeatures.supportNewBlendModes = checkBlendMode(); + CanvasFeatures.supportInverseAlpha = checkInverseAlpha(); + } + + return CanvasFeatures; +} + +module.exports = init(); diff --git a/src/device/Features.js b/src/device/Features.js index b9aa06723..a46cf2bc8 100644 --- a/src/device/Features.js +++ b/src/device/Features.js @@ -1,186 +1,186 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var OS = require('./OS'); -var Browser = require('./Browser'); -var CanvasPool = require('../display/canvas/CanvasPool'); - -/** - * Determines the features of the browser 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.features` from within any Scene. - * - * @typedef {object} Phaser.Device.Features - * @since 3.0.0 - * - * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. - * @property {boolean} canvas - Is canvas available? - * @property {boolean} file - Is file available? - * @property {boolean} fileSystem - Is fileSystem available? - * @property {boolean} getUserMedia - Does the device support the getUserMedia API? - * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) - * @property {boolean} localStorage - Is localStorage available? - * @property {boolean} pointerLock - Is Pointer Lock available? - * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? - * @property {boolean} vibration - Does the device support the Vibration API? - * @property {boolean} webGL - Is webGL available? - * @property {boolean} worker - Is worker available? - */ -var Features = { - - canvas: false, - canvasBitBltShift: null, - file: false, - fileSystem: false, - getUserMedia: true, - littleEndian: false, - localStorage: false, - pointerLock: false, - support32bit: false, - vibration: false, - webGL: false, - worker: false - -}; - -// Check Little or Big Endian system. -// @author Matt DesLauriers (@mattdesl) -function checkIsLittleEndian () -{ - var a = new ArrayBuffer(4); - var b = new Uint8Array(a); - var c = new Uint32Array(a); - - b[0] = 0xa1; - b[1] = 0xb2; - b[2] = 0xc3; - b[3] = 0xd4; - - if (c[0] === 0xd4c3b2a1) - { - return true; - } - - if (c[0] === 0xa1b2c3d4) - { - return false; - } - else - { - // Could not determine endianness - return null; - } -} - -function init () -{ - Features.canvas = !!window['CanvasRenderingContext2D']; - - try - { - Features.localStorage = !!localStorage.getItem; - } - catch (error) - { - Features.localStorage = false; - } - - Features.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; - Features.fileSystem = !!window['requestFileSystem']; - - var isUint8 = false; - - var testWebGL = function () - { - if (window['WebGLRenderingContext']) - { - try - { - var canvas = CanvasPool.createWebGL(this); - - var ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'); - - var canvas2D = CanvasPool.create2D(this); - - var ctx2D = canvas2D.getContext('2d'); - - // Can't be done on a webgl context - var image = ctx2D.createImageData(1, 1); - - // Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. - // @author Matt DesLauriers (@mattdesl) - isUint8 = image.data instanceof Uint8ClampedArray; - - CanvasPool.remove(canvas); - CanvasPool.remove(canvas2D); - - return !!ctx; - } - catch (e) - { - return false; - } - } - - return false; - }; - - Features.webGL = testWebGL(); - - Features.worker = !!window['Worker']; - - Features.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; - - navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; - - window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; - - Features.getUserMedia = Features.getUserMedia && !!navigator.getUserMedia && !!window.URL; - - // Older versions of firefox (< 21) apparently claim support but user media does not actually work - if (Browser.firefox && Browser.firefoxVersion < 21) - { - Features.getUserMedia = false; - } - - // 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. - if (!OS.iOS && (Browser.ie || Browser.firefox || Browser.chrome)) - { - Features.canvasBitBltShift = true; - } - - // Known not to work - if (Browser.safari || Browser.mobileSafari) - { - Features.canvasBitBltShift = false; - } - - navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; - - if (navigator.vibrate) - { - Features.vibration = true; - } - - if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') - { - Features.littleEndian = checkIsLittleEndian(); - } - - Features.support32bit = ( - typeof ArrayBuffer !== 'undefined' && - typeof Uint8ClampedArray !== 'undefined' && - typeof Int32Array !== 'undefined' && - Features.littleEndian !== null && - isUint8 - ); - - return Features; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var OS = require('./OS'); +var Browser = require('./Browser'); +var CanvasPool = require('../display/canvas/CanvasPool'); + +/** + * Determines the features of the browser 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.features` from within any Scene. + * + * @typedef {object} Phaser.Device.Features + * @since 3.0.0 + * + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @property {boolean} canvas - Is canvas available? + * @property {boolean} file - Is file available? + * @property {boolean} fileSystem - Is fileSystem available? + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @property {boolean} localStorage - Is localStorage available? + * @property {boolean} pointerLock - Is Pointer Lock available? + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @property {boolean} vibration - Does the device support the Vibration API? + * @property {boolean} webGL - Is webGL available? + * @property {boolean} worker - Is worker available? + */ +var Features = { + + canvas: false, + canvasBitBltShift: null, + file: false, + fileSystem: false, + getUserMedia: true, + littleEndian: false, + localStorage: false, + pointerLock: false, + support32bit: false, + vibration: false, + webGL: false, + worker: false + +}; + +// Check Little or Big Endian system. +// @author Matt DesLauriers (@mattdesl) +function checkIsLittleEndian () +{ + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } +} + +function init () +{ + Features.canvas = !!window['CanvasRenderingContext2D']; + + try + { + Features.localStorage = !!localStorage.getItem; + } + catch (error) + { + Features.localStorage = false; + } + + Features.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + Features.fileSystem = !!window['requestFileSystem']; + + var isUint8 = false; + + var testWebGL = function () + { + if (window['WebGLRenderingContext']) + { + try + { + var canvas = CanvasPool.createWebGL(this); + + var ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'); + + var canvas2D = CanvasPool.create2D(this); + + var ctx2D = canvas2D.getContext('2d'); + + // Can't be done on a webgl context + var image = ctx2D.createImageData(1, 1); + + // Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + // @author Matt DesLauriers (@mattdesl) + isUint8 = image.data instanceof Uint8ClampedArray; + + CanvasPool.remove(canvas); + CanvasPool.remove(canvas2D); + + return !!ctx; + } + catch (e) + { + return false; + } + } + + return false; + }; + + Features.webGL = testWebGL(); + + Features.worker = !!window['Worker']; + + Features.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + Features.getUserMedia = Features.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (Browser.firefox && Browser.firefoxVersion < 21) + { + Features.getUserMedia = false; + } + + // 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. + if (!OS.iOS && (Browser.ie || Browser.firefox || Browser.chrome)) + { + Features.canvasBitBltShift = true; + } + + // Known not to work + if (Browser.safari || Browser.mobileSafari) + { + Features.canvasBitBltShift = false; + } + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + Features.vibration = true; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + Features.littleEndian = checkIsLittleEndian(); + } + + Features.support32bit = ( + typeof ArrayBuffer !== 'undefined' && + typeof Uint8ClampedArray !== 'undefined' && + typeof Int32Array !== 'undefined' && + Features.littleEndian !== null && + isUint8 + ); + + return Features; +} + +module.exports = init(); diff --git a/src/device/Fullscreen.js b/src/device/Fullscreen.js index 5def34cd2..53433eeb8 100644 --- a/src/device/Fullscreen.js +++ b/src/device/Fullscreen.js @@ -1,98 +1,98 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determines the full screen support of the browser 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.fullscreen` from within any Scene. - * - * @typedef {object} Phaser.Device.Fullscreen - * @since 3.0.0 - * - * @property {boolean} available - Does the browser support the Full Screen API? - * @property {boolean} keyboard - Does the browser support access to the Keyboard during Full Screen mode? - * @property {string} cancel - If the browser supports the Full Screen API this holds the call you need to use to cancel it. - * @property {string} request - If the browser supports the Full Screen API this holds the call you need to use to activate it. - */ -var Fullscreen = { - - available: false, - cancel: '', - keyboard: false, - request: '' - -}; - -/** -* Checks for support of the Full Screen API. -* -* @ignore -*/ -function init () -{ - var i; - - var suffix1 = 'Fullscreen'; - var suffix2 = 'FullScreen'; - - var fs = [ - 'request' + suffix1, - 'request' + suffix2, - 'webkitRequest' + suffix1, - 'webkitRequest' + suffix2, - 'msRequest' + suffix1, - 'msRequest' + suffix2, - 'mozRequest' + suffix2, - 'mozRequest' + suffix1 - ]; - - for (i = 0; i < fs.length; i++) - { - if (document.documentElement[fs[i]]) - { - Fullscreen.available = true; - Fullscreen.request = fs[i]; - break; - } - } - - var cfs = [ - 'cancel' + suffix2, - 'exit' + suffix1, - 'webkitCancel' + suffix2, - 'webkitExit' + suffix1, - 'msCancel' + suffix2, - 'msExit' + suffix1, - 'mozCancel' + suffix2, - 'mozExit' + suffix1 - ]; - - if (Fullscreen.available) - { - for (i = 0; i < cfs.length; i++) - { - if (document[cfs[i]]) - { - Fullscreen.cancel = cfs[i]; - break; - } - } - } - - // Keyboard Input? - // Safari 5.1 says it supports fullscreen keyboard, but is lying. - if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'] && !(/ Version\/5\.1(?:\.\d+)? Safari\//).test(navigator.userAgent)) - { - Fullscreen.keyboard = true; - } - - Object.defineProperty(Fullscreen, 'active', { get: function () { return !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement); } }); - - return Fullscreen; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines the full screen support of the browser 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.fullscreen` from within any Scene. + * + * @typedef {object} Phaser.Device.Fullscreen + * @since 3.0.0 + * + * @property {boolean} available - Does the browser support the Full Screen API? + * @property {boolean} keyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @property {string} cancel - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @property {string} request - If the browser supports the Full Screen API this holds the call you need to use to activate it. + */ +var Fullscreen = { + + available: false, + cancel: '', + keyboard: false, + request: '' + +}; + +/** +* Checks for support of the Full Screen API. +* +* @ignore +*/ +function init () +{ + var i; + + var suffix1 = 'Fullscreen'; + var suffix2 = 'FullScreen'; + + var fs = [ + 'request' + suffix1, + 'request' + suffix2, + 'webkitRequest' + suffix1, + 'webkitRequest' + suffix2, + 'msRequest' + suffix1, + 'msRequest' + suffix2, + 'mozRequest' + suffix2, + 'mozRequest' + suffix1 + ]; + + for (i = 0; i < fs.length; i++) + { + if (document.documentElement[fs[i]]) + { + Fullscreen.available = true; + Fullscreen.request = fs[i]; + break; + } + } + + var cfs = [ + 'cancel' + suffix2, + 'exit' + suffix1, + 'webkitCancel' + suffix2, + 'webkitExit' + suffix1, + 'msCancel' + suffix2, + 'msExit' + suffix1, + 'mozCancel' + suffix2, + 'mozExit' + suffix1 + ]; + + if (Fullscreen.available) + { + for (i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + Fullscreen.cancel = cfs[i]; + break; + } + } + } + + // Keyboard Input? + // Safari 5.1 says it supports fullscreen keyboard, but is lying. + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'] && !(/ Version\/5\.1(?:\.\d+)? Safari\//).test(navigator.userAgent)) + { + Fullscreen.keyboard = true; + } + + Object.defineProperty(Fullscreen, 'active', { get: function () { return !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement); } }); + + return Fullscreen; +} + +module.exports = init(); diff --git a/src/device/Input.js b/src/device/Input.js index 986dc541c..63e825ecd 100644 --- a/src/device/Input.js +++ b/src/device/Input.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Browser = require('./Browser'); - -/** - * Determines the input support of the browser 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.input` from within any Scene. - * - * @typedef {object} Phaser.Device.Input - * @since 3.0.0 - * - * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' - * @property {boolean} gamepads - Is navigator.getGamepads available? - * @property {boolean} mspointer - Is mspointer available? - * @property {boolean} touch - Is touch available? - */ -var Input = { - - gamepads: false, - mspointer: false, - touch: false, - wheelEvent: null - -}; - -function init () -{ - if ('ontouchstart' in document.documentElement || (navigator.maxTouchPoints && navigator.maxTouchPoints >= 1)) - { - Input.touch = true; - } - - if (navigator.msPointerEnabled || navigator.pointerEnabled) - { - Input.mspointer = true; - } - - if (navigator.getGamepads) - { - Input.gamepads = true; - } - - // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel - if ('onwheel' in window || (Browser.ie && 'WheelEvent' in window)) - { - // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ - Input.wheelEvent = 'wheel'; - } - else if ('onmousewheel' in window) - { - // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. - Input.wheelEvent = 'mousewheel'; - } - else if (Browser.firefox && 'MouseScrollEvent' in window) - { - // FF prior to 17. This should probably be scrubbed. - Input.wheelEvent = 'DOMMouseScroll'; - } - - return Input; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Browser = require('./Browser'); + +/** + * Determines the input support of the browser 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.input` from within any Scene. + * + * @typedef {object} Phaser.Device.Input + * @since 3.0.0 + * + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @property {boolean} gamepads - Is navigator.getGamepads available? + * @property {boolean} mspointer - Is mspointer available? + * @property {boolean} touch - Is touch available? + */ +var Input = { + + gamepads: false, + mspointer: false, + touch: false, + wheelEvent: null + +}; + +function init () +{ + if ('ontouchstart' in document.documentElement || (navigator.maxTouchPoints && navigator.maxTouchPoints >= 1)) + { + Input.touch = true; + } + + if (navigator.msPointerEnabled || navigator.pointerEnabled) + { + Input.mspointer = true; + } + + if (navigator.getGamepads) + { + Input.gamepads = true; + } + + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (Browser.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + Input.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + Input.wheelEvent = 'mousewheel'; + } + else if (Browser.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + Input.wheelEvent = 'DOMMouseScroll'; + } + + return Input; +} + +module.exports = init(); diff --git a/src/device/OS.js b/src/device/OS.js index f672eb48a..a8c42a844 100644 --- a/src/device/OS.js +++ b/src/device/OS.js @@ -1,165 +1,165 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determines the operating system of the device 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.os` from within any Scene. - * - * @typedef {object} Phaser.Device.OS - * @since 3.0.0 - * - * @property {boolean} android - Is running on android? - * @property {boolean} chromeOS - Is running on chromeOS? - * @property {boolean} cordova - Is the game running under Apache Cordova? - * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? - * @property {boolean} desktop - Is running on a desktop? - * @property {boolean} ejecta - Is the game running under Ejecta? - * @property {boolean} electron - Is the game running under GitHub Electron? - * @property {boolean} iOS - Is running on iOS? - * @property {boolean} iPad - Is running on iPad? - * @property {boolean} iPhone - Is running on iPhone? - * @property {boolean} kindle - Is running on an Amazon Kindle? - * @property {boolean} linux - Is running on linux? - * @property {boolean} macOS - Is running on macOS? - * @property {boolean} node - Is the game running under Node.js? - * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? - * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView - * @property {boolean} windows - Is running on windows? - * @property {boolean} windowsPhone - Is running on a Windows Phone? - * @property {number} iOSVersion - If running in iOS this will contain the major version number. - * @property {number} pixelRatio - PixelRatio of the host device? - */ -var OS = { - - android: false, - chromeOS: false, - cordova: false, - crosswalk: false, - desktop: false, - ejecta: false, - electron: false, - iOS: false, - iOSVersion: 0, - iPad: false, - iPhone: false, - kindle: false, - linux: false, - macOS: false, - node: false, - nodeWebkit: false, - pixelRatio: 1, - webApp: false, - windows: false, - windowsPhone: false - -}; - -function init () -{ - var ua = navigator.userAgent; - - if (/Windows/.test(ua)) - { - OS.windows = true; - } - else if (/Mac OS/.test(ua) && !(/like Mac OS/.test(ua))) - { - OS.macOS = true; - } - else if (/Android/.test(ua)) - { - OS.android = true; - } - else if (/Linux/.test(ua)) - { - OS.linux = true; - } - else if (/iP[ao]d|iPhone/i.test(ua)) - { - OS.iOS = true; - - (navigator.appVersion).match(/OS (\d+)/); - - OS.iOSVersion = parseInt(RegExp.$1, 10); - - OS.iPhone = ua.toLowerCase().indexOf('iphone') !== -1; - OS.iPad = ua.toLowerCase().indexOf('ipad') !== -1; - } - else if (/Kindle/.test(ua) || (/\bKF[A-Z][A-Z]+/).test(ua) || (/Silk.*Mobile Safari/).test(ua)) - { - OS.kindle = true; - - // 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" - } - else if (/CrOS/.test(ua)) - { - OS.chromeOS = true; - } - - if (/Windows Phone/i.test(ua) || (/IEMobile/i).test(ua)) - { - OS.android = false; - OS.iOS = false; - OS.macOS = false; - OS.windows = true; - OS.windowsPhone = true; - } - - var silk = (/Silk/).test(ua); - - if (OS.windows || OS.macOS || (OS.linux && !silk) || OS.chromeOS) - { - OS.desktop = true; - } - - // Windows Phone / Table reset - if (OS.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) - { - OS.desktop = false; - } - - // WebApp mode in iOS - if (navigator.standalone) - { - OS.webApp = true; - } - - if (window.cordova !== undefined) - { - OS.cordova = true; - } - - if (typeof process !== 'undefined' && process.versions && process.versions.node) - { - OS.node = true; - } - - if (OS.node && typeof process.versions === 'object') - { - OS.nodeWebkit = !!process.versions['node-webkit']; - - OS.electron = !!process.versions.electron; - } - - if (window.ejecta !== undefined) - { - OS.ejecta = true; - } - - if ((/Crosswalk/).test(ua)) - { - OS.crosswalk = true; - } - - OS.pixelRatio = window['devicePixelRatio'] || 1; - - return OS; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines the operating system of the device 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.os` from within any Scene. + * + * @typedef {object} Phaser.Device.OS + * @since 3.0.0 + * + * @property {boolean} android - Is running on android? + * @property {boolean} chromeOS - Is running on chromeOS? + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @property {boolean} desktop - Is running on a desktop? + * @property {boolean} ejecta - Is the game running under Ejecta? + * @property {boolean} electron - Is the game running under GitHub Electron? + * @property {boolean} iOS - Is running on iOS? + * @property {boolean} iPad - Is running on iPad? + * @property {boolean} iPhone - Is running on iPhone? + * @property {boolean} kindle - Is running on an Amazon Kindle? + * @property {boolean} linux - Is running on linux? + * @property {boolean} macOS - Is running on macOS? + * @property {boolean} node - Is the game running under Node.js? + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @property {boolean} windows - Is running on windows? + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @property {number} pixelRatio - PixelRatio of the host device? + */ +var OS = { + + android: false, + chromeOS: false, + cordova: false, + crosswalk: false, + desktop: false, + ejecta: false, + electron: false, + iOS: false, + iOSVersion: 0, + iPad: false, + iPhone: false, + kindle: false, + linux: false, + macOS: false, + node: false, + nodeWebkit: false, + pixelRatio: 1, + webApp: false, + windows: false, + windowsPhone: false + +}; + +function init () +{ + var ua = navigator.userAgent; + + if (/Windows/.test(ua)) + { + OS.windows = true; + } + else if (/Mac OS/.test(ua) && !(/like Mac OS/.test(ua))) + { + OS.macOS = true; + } + else if (/Android/.test(ua)) + { + OS.android = true; + } + else if (/Linux/.test(ua)) + { + OS.linux = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + OS.iOS = true; + + (navigator.appVersion).match(/OS (\d+)/); + + OS.iOSVersion = parseInt(RegExp.$1, 10); + + OS.iPhone = ua.toLowerCase().indexOf('iphone') !== -1; + OS.iPad = ua.toLowerCase().indexOf('ipad') !== -1; + } + else if (/Kindle/.test(ua) || (/\bKF[A-Z][A-Z]+/).test(ua) || (/Silk.*Mobile Safari/).test(ua)) + { + OS.kindle = true; + + // 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" + } + else if (/CrOS/.test(ua)) + { + OS.chromeOS = true; + } + + if (/Windows Phone/i.test(ua) || (/IEMobile/i).test(ua)) + { + OS.android = false; + OS.iOS = false; + OS.macOS = false; + OS.windows = true; + OS.windowsPhone = true; + } + + var silk = (/Silk/).test(ua); + + if (OS.windows || OS.macOS || (OS.linux && !silk) || OS.chromeOS) + { + OS.desktop = true; + } + + // Windows Phone / Table reset + if (OS.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + OS.desktop = false; + } + + // WebApp mode in iOS + if (navigator.standalone) + { + OS.webApp = true; + } + + if (window.cordova !== undefined) + { + OS.cordova = true; + } + + if (typeof process !== 'undefined' && process.versions && process.versions.node) + { + OS.node = true; + } + + if (OS.node && typeof process.versions === 'object') + { + OS.nodeWebkit = !!process.versions['node-webkit']; + + OS.electron = !!process.versions.electron; + } + + if (window.ejecta !== undefined) + { + OS.ejecta = true; + } + + if ((/Crosswalk/).test(ua)) + { + OS.crosswalk = true; + } + + OS.pixelRatio = window['devicePixelRatio'] || 1; + + return OS; +} + +module.exports = init(); diff --git a/src/device/Video.js b/src/device/Video.js index 2bf08cb29..ed6166920 100644 --- a/src/device/Video.js +++ b/src/device/Video.js @@ -1,81 +1,81 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determines the video support of the browser 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.video` from within any Scene. - * - * In Phaser 3.20 the properties were renamed to drop the 'Video' suffix. - * - * @typedef {object} Phaser.Device.Video - * @since 3.0.0 - * - * @property {boolean} h264 - Can this device play h264 mp4 video files? - * @property {boolean} hls - Can this device play hls video files? - * @property {boolean} mp4 - Can this device play h264 mp4 video files? - * @property {boolean} ogg - Can this device play ogg video files? - * @property {boolean} vp9 - Can this device play vp9 video files? - * @property {boolean} webm - Can this device play webm video files? - */ -var Video = { - - h264: false, - hls: false, - mp4: false, - ogg: false, - vp9: false, - webm: false - -}; - -function init () -{ - var videoElement = document.createElement('video'); - var result = !!videoElement.canPlayType; - - try - { - if (result) - { - if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) - { - Video.ogg = true; - } - - if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) - { - // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 - Video.h264 = true; - Video.mp4 = true; - } - - if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) - { - Video.webm = true; - } - - if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) - { - Video.vp9 = true; - } - - if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) - { - Video.hls = true; - } - } - } - catch (e) - { - // Nothing to do - } - - return Video; -} - -module.exports = init(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines the video support of the browser 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.video` from within any Scene. + * + * In Phaser 3.20 the properties were renamed to drop the 'Video' suffix. + * + * @typedef {object} Phaser.Device.Video + * @since 3.0.0 + * + * @property {boolean} h264 - Can this device play h264 mp4 video files? + * @property {boolean} hls - Can this device play hls video files? + * @property {boolean} mp4 - Can this device play h264 mp4 video files? + * @property {boolean} ogg - Can this device play ogg video files? + * @property {boolean} vp9 - Can this device play vp9 video files? + * @property {boolean} webm - Can this device play webm video files? + */ +var Video = { + + h264: false, + hls: false, + mp4: false, + ogg: false, + vp9: false, + webm: false + +}; + +function init () +{ + var videoElement = document.createElement('video'); + var result = !!videoElement.canPlayType; + + try + { + if (result) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + Video.ogg = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + Video.h264 = true; + Video.mp4 = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + Video.webm = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + Video.vp9 = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + Video.hls = true; + } + } + } + catch (e) + { + // Nothing to do + } + + return Video; +} + +module.exports = init(); diff --git a/src/device/index.js b/src/device/index.js index 98b5af2c4..c2b41178f 100644 --- a/src/device/index.js +++ b/src/device/index.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// This singleton is instantiated as soon as Phaser loads, -// before a Phaser.Game instance has even been created. -// Which means all instances of Phaser Games can share it, -// without having to re-poll the device all over again - -/** - * @namespace Phaser.Device - * @since 3.0.0 - */ - -/** - * @typedef {object} Phaser.DeviceConf - * - * @property {Phaser.Device.OS} os - The OS Device functions. - * @property {Phaser.Device.Browser} browser - The Browser Device functions. - * @property {Phaser.Device.Features} features - The Features Device functions. - * @property {Phaser.Device.Input} input - The Input Device functions. - * @property {Phaser.Device.Audio} audio - The Audio Device functions. - * @property {Phaser.Device.Video} video - The Video Device functions. - * @property {Phaser.Device.Fullscreen} fullscreen - The Fullscreen Device functions. - * @property {Phaser.Device.CanvasFeatures} canvasFeatures - The Canvas Device functions. - */ - -module.exports = { - - os: require('./OS'), - browser: require('./Browser'), - features: require('./Features'), - input: require('./Input'), - audio: require('./Audio'), - video: require('./Video'), - fullscreen: require('./Fullscreen'), - canvasFeatures: require('./CanvasFeatures') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// This singleton is instantiated as soon as Phaser loads, +// before a Phaser.Game instance has even been created. +// Which means all instances of Phaser Games can share it, +// without having to re-poll the device all over again + +/** + * @namespace Phaser.Device + * @since 3.0.0 + */ + +/** + * @typedef {object} Phaser.DeviceConf + * + * @property {Phaser.Device.OS} os - The OS Device functions. + * @property {Phaser.Device.Browser} browser - The Browser Device functions. + * @property {Phaser.Device.Features} features - The Features Device functions. + * @property {Phaser.Device.Input} input - The Input Device functions. + * @property {Phaser.Device.Audio} audio - The Audio Device functions. + * @property {Phaser.Device.Video} video - The Video Device functions. + * @property {Phaser.Device.Fullscreen} fullscreen - The Fullscreen Device functions. + * @property {Phaser.Device.CanvasFeatures} canvasFeatures - The Canvas Device functions. + */ + +module.exports = { + + os: require('./OS'), + browser: require('./Browser'), + features: require('./Features'), + input: require('./Input'), + audio: require('./Audio'), + video: require('./Video'), + fullscreen: require('./Fullscreen'), + canvasFeatures: require('./CanvasFeatures') + +}; diff --git a/src/display/align/const.js b/src/display/align/const.js index 2c25019af..2ecf7ce55 100644 --- a/src/display/align/const.js +++ b/src/display/align/const.js @@ -1,128 +1,128 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ALIGN_CONST = { - - /** - * A constant representing a top-left alignment or position. - * @constant - * @name Phaser.Display.Align.TOP_LEFT - * @since 3.0.0 - * @type {integer} - */ - TOP_LEFT: 0, - - /** - * A constant representing a top-center alignment or position. - * @constant - * @name Phaser.Display.Align.TOP_CENTER - * @since 3.0.0 - * @type {integer} - */ - TOP_CENTER: 1, - - /** - * A constant representing a top-right alignment or position. - * @constant - * @name Phaser.Display.Align.TOP_RIGHT - * @since 3.0.0 - * @type {integer} - */ - TOP_RIGHT: 2, - - /** - * A constant representing a left-top alignment or position. - * @constant - * @name Phaser.Display.Align.LEFT_TOP - * @since 3.0.0 - * @type {integer} - */ - LEFT_TOP: 3, - - /** - * A constant representing a left-center alignment or position. - * @constant - * @name Phaser.Display.Align.LEFT_CENTER - * @since 3.0.0 - * @type {integer} - */ - LEFT_CENTER: 4, - - /** - * A constant representing a left-bottom alignment or position. - * @constant - * @name Phaser.Display.Align.LEFT_BOTTOM - * @since 3.0.0 - * @type {integer} - */ - LEFT_BOTTOM: 5, - - /** - * A constant representing a center alignment or position. - * @constant - * @name Phaser.Display.Align.CENTER - * @since 3.0.0 - * @type {integer} - */ - CENTER: 6, - - /** - * A constant representing a right-top alignment or position. - * @constant - * @name Phaser.Display.Align.RIGHT_TOP - * @since 3.0.0 - * @type {integer} - */ - RIGHT_TOP: 7, - - /** - * A constant representing a right-center alignment or position. - * @constant - * @name Phaser.Display.Align.RIGHT_CENTER - * @since 3.0.0 - * @type {integer} - */ - RIGHT_CENTER: 8, - - /** - * A constant representing a right-bottom alignment or position. - * @constant - * @name Phaser.Display.Align.RIGHT_BOTTOM - * @since 3.0.0 - * @type {integer} - */ - RIGHT_BOTTOM: 9, - - /** - * A constant representing a bottom-left alignment or position. - * @constant - * @name Phaser.Display.Align.BOTTOM_LEFT - * @since 3.0.0 - * @type {integer} - */ - BOTTOM_LEFT: 10, - - /** - * A constant representing a bottom-center alignment or position. - * @constant - * @name Phaser.Display.Align.BOTTOM_CENTER - * @since 3.0.0 - * @type {integer} - */ - BOTTOM_CENTER: 11, - - /** - * A constant representing a bottom-right alignment or position. - * @constant - * @name Phaser.Display.Align.BOTTOM_RIGHT - * @since 3.0.0 - * @type {integer} - */ - BOTTOM_RIGHT: 12 - -}; - -module.exports = ALIGN_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = { + + /** + * A constant representing a top-left alignment or position. + * @constant + * @name Phaser.Display.Align.TOP_LEFT + * @since 3.0.0 + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant + * @name Phaser.Display.Align.TOP_CENTER + * @since 3.0.0 + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant + * @name Phaser.Display.Align.TOP_RIGHT + * @since 3.0.0 + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant + * @name Phaser.Display.Align.LEFT_TOP + * @since 3.0.0 + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant + * @name Phaser.Display.Align.LEFT_CENTER + * @since 3.0.0 + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant + * @name Phaser.Display.Align.LEFT_BOTTOM + * @since 3.0.0 + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant + * @name Phaser.Display.Align.CENTER + * @since 3.0.0 + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant + * @name Phaser.Display.Align.RIGHT_TOP + * @since 3.0.0 + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant + * @name Phaser.Display.Align.RIGHT_CENTER + * @since 3.0.0 + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant + * @name Phaser.Display.Align.RIGHT_BOTTOM + * @since 3.0.0 + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant + * @name Phaser.Display.Align.BOTTOM_LEFT + * @since 3.0.0 + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant + * @name Phaser.Display.Align.BOTTOM_CENTER + * @since 3.0.0 + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant + * @name Phaser.Display.Align.BOTTOM_RIGHT + * @since 3.0.0 + * @type {integer} + */ + BOTTOM_RIGHT: 12 + +}; + +module.exports = ALIGN_CONST; diff --git a/src/display/align/in/BottomCenter.js b/src/display/align/in/BottomCenter.js index fd4271dd9..e187f417b 100644 --- a/src/display/align/in/BottomCenter.js +++ b/src/display/align/in/BottomCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetCenterX = require('../../bounds/GetCenterX'); -var SetBottom = require('../../bounds/SetBottom'); -var SetCenterX = require('../../bounds/SetCenterX'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. - * - * @function Phaser.Display.Align.In.BottomCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var BottomCenter = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); - SetBottom(gameObject, GetBottom(alignIn) + offsetY); - - return gameObject; -}; - -module.exports = BottomCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetCenterX = require('../../bounds/GetCenterX'); +var SetBottom = require('../../bounds/SetBottom'); +var SetCenterX = require('../../bounds/SetCenterX'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. + * + * @function Phaser.Display.Align.In.BottomCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var BottomCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); + SetBottom(gameObject, GetBottom(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = BottomCenter; diff --git a/src/display/align/in/BottomLeft.js b/src/display/align/in/BottomLeft.js index b0bc69953..76aff0d39 100644 --- a/src/display/align/in/BottomLeft.js +++ b/src/display/align/in/BottomLeft.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetLeft = require('../../bounds/GetLeft'); -var SetBottom = require('../../bounds/SetBottom'); -var SetLeft = require('../../bounds/SetLeft'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the bottom left of the other. - * - * @function Phaser.Display.Align.In.BottomLeft - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var BottomLeft = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetLeft(alignIn) - offsetX); - SetBottom(gameObject, GetBottom(alignIn) + offsetY); - - return gameObject; -}; - -module.exports = BottomLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetLeft = require('../../bounds/GetLeft'); +var SetBottom = require('../../bounds/SetBottom'); +var SetLeft = require('../../bounds/SetLeft'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the bottom left of the other. + * + * @function Phaser.Display.Align.In.BottomLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var BottomLeft = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignIn) - offsetX); + SetBottom(gameObject, GetBottom(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = BottomLeft; diff --git a/src/display/align/in/BottomRight.js b/src/display/align/in/BottomRight.js index d5f729e6c..1d18e8275 100644 --- a/src/display/align/in/BottomRight.js +++ b/src/display/align/in/BottomRight.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetRight = require('../../bounds/GetRight'); -var SetBottom = require('../../bounds/SetBottom'); -var SetRight = require('../../bounds/SetRight'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the bottom right of the other. - * - * @function Phaser.Display.Align.In.BottomRight - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var BottomRight = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetRight(alignIn) + offsetX); - SetBottom(gameObject, GetBottom(alignIn) + offsetY); - - return gameObject; -}; - -module.exports = BottomRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetRight = require('../../bounds/GetRight'); +var SetBottom = require('../../bounds/SetBottom'); +var SetRight = require('../../bounds/SetRight'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the bottom right of the other. + * + * @function Phaser.Display.Align.In.BottomRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var BottomRight = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignIn) + offsetX); + SetBottom(gameObject, GetBottom(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = BottomRight; diff --git a/src/display/align/in/Center.js b/src/display/align/in/Center.js index 5179e4505..97c730ed4 100644 --- a/src/display/align/in/Center.js +++ b/src/display/align/in/Center.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CenterOn = require('../../bounds/CenterOn'); -var GetCenterX = require('../../bounds/GetCenterX'); -var GetCenterY = require('../../bounds/GetCenterY'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the center of the other. - * - * @function Phaser.Display.Align.In.Center - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var Center = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - CenterOn(gameObject, GetCenterX(alignIn) + offsetX, GetCenterY(alignIn) + offsetY); - - return gameObject; -}; - -module.exports = Center; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CenterOn = require('../../bounds/CenterOn'); +var GetCenterX = require('../../bounds/GetCenterX'); +var GetCenterY = require('../../bounds/GetCenterY'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the center of the other. + * + * @function Phaser.Display.Align.In.Center + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var Center = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + CenterOn(gameObject, GetCenterX(alignIn) + offsetX, GetCenterY(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = Center; diff --git a/src/display/align/in/LeftCenter.js b/src/display/align/in/LeftCenter.js index f00bec9e8..9f646eae9 100644 --- a/src/display/align/in/LeftCenter.js +++ b/src/display/align/in/LeftCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetCenterY = require('../../bounds/GetCenterY'); -var GetLeft = require('../../bounds/GetLeft'); -var SetCenterY = require('../../bounds/SetCenterY'); -var SetLeft = require('../../bounds/SetLeft'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the left center of the other. - * - * @function Phaser.Display.Align.In.LeftCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var LeftCenter = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetLeft(alignIn) - offsetX); - SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); - - return gameObject; -}; - -module.exports = LeftCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = require('../../bounds/GetCenterY'); +var GetLeft = require('../../bounds/GetLeft'); +var SetCenterY = require('../../bounds/SetCenterY'); +var SetLeft = require('../../bounds/SetLeft'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the left center of the other. + * + * @function Phaser.Display.Align.In.LeftCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var LeftCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignIn) - offsetX); + SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = LeftCenter; diff --git a/src/display/align/in/QuickSet.js b/src/display/align/in/QuickSet.js index 8d65a4b41..f04b6030d 100644 --- a/src/display/align/in/QuickSet.js +++ b/src/display/align/in/QuickSet.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ALIGN_CONST = require('../const'); - -var AlignInMap = []; - -AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = require('./BottomCenter'); -AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = require('./BottomLeft'); -AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = require('./BottomRight'); -AlignInMap[ALIGN_CONST.CENTER] = require('./Center'); -AlignInMap[ALIGN_CONST.LEFT_CENTER] = require('./LeftCenter'); -AlignInMap[ALIGN_CONST.RIGHT_CENTER] = require('./RightCenter'); -AlignInMap[ALIGN_CONST.TOP_CENTER] = require('./TopCenter'); -AlignInMap[ALIGN_CONST.TOP_LEFT] = require('./TopLeft'); -AlignInMap[ALIGN_CONST.TOP_RIGHT] = require('./TopRight'); -AlignInMap[ALIGN_CONST.LEFT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_LEFT]; -AlignInMap[ALIGN_CONST.LEFT_TOP] = AlignInMap[ALIGN_CONST.TOP_LEFT]; -AlignInMap[ALIGN_CONST.RIGHT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_RIGHT]; -AlignInMap[ALIGN_CONST.RIGHT_TOP] = AlignInMap[ALIGN_CONST.TOP_RIGHT]; - -/** - * Takes given Game Object and aligns it so that it is positioned relative to the other. - * 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 {integer} 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. - */ -var QuickSet = function (child, alignIn, position, offsetX, offsetY) -{ - return AlignInMap[position](child, alignIn, offsetX, offsetY); -}; - -module.exports = QuickSet; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = require('../const'); + +var AlignInMap = []; + +AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = require('./BottomCenter'); +AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = require('./BottomLeft'); +AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = require('./BottomRight'); +AlignInMap[ALIGN_CONST.CENTER] = require('./Center'); +AlignInMap[ALIGN_CONST.LEFT_CENTER] = require('./LeftCenter'); +AlignInMap[ALIGN_CONST.RIGHT_CENTER] = require('./RightCenter'); +AlignInMap[ALIGN_CONST.TOP_CENTER] = require('./TopCenter'); +AlignInMap[ALIGN_CONST.TOP_LEFT] = require('./TopLeft'); +AlignInMap[ALIGN_CONST.TOP_RIGHT] = require('./TopRight'); +AlignInMap[ALIGN_CONST.LEFT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_LEFT]; +AlignInMap[ALIGN_CONST.LEFT_TOP] = AlignInMap[ALIGN_CONST.TOP_LEFT]; +AlignInMap[ALIGN_CONST.RIGHT_BOTTOM] = AlignInMap[ALIGN_CONST.BOTTOM_RIGHT]; +AlignInMap[ALIGN_CONST.RIGHT_TOP] = AlignInMap[ALIGN_CONST.TOP_RIGHT]; + +/** + * Takes given Game Object and aligns it so that it is positioned relative to the other. + * 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 {integer} 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. + */ +var QuickSet = function (child, alignIn, position, offsetX, offsetY) +{ + return AlignInMap[position](child, alignIn, offsetX, offsetY); +}; + +module.exports = QuickSet; diff --git a/src/display/align/in/RightCenter.js b/src/display/align/in/RightCenter.js index 47f2711cc..182921fc7 100644 --- a/src/display/align/in/RightCenter.js +++ b/src/display/align/in/RightCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetCenterY = require('../../bounds/GetCenterY'); -var GetRight = require('../../bounds/GetRight'); -var SetCenterY = require('../../bounds/SetCenterY'); -var SetRight = require('../../bounds/SetRight'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the right center of the other. - * - * @function Phaser.Display.Align.In.RightCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var RightCenter = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetRight(alignIn) + offsetX); - SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); - - return gameObject; -}; - -module.exports = RightCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = require('../../bounds/GetCenterY'); +var GetRight = require('../../bounds/GetRight'); +var SetCenterY = require('../../bounds/SetCenterY'); +var SetRight = require('../../bounds/SetRight'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the right center of the other. + * + * @function Phaser.Display.Align.In.RightCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var RightCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignIn) + offsetX); + SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); + + return gameObject; +}; + +module.exports = RightCenter; diff --git a/src/display/align/in/TopCenter.js b/src/display/align/in/TopCenter.js index 2d8f734e7..79651f0da 100644 --- a/src/display/align/in/TopCenter.js +++ b/src/display/align/in/TopCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetCenterX = require('../../bounds/GetCenterX'); -var GetTop = require('../../bounds/GetTop'); -var SetCenterX = require('../../bounds/SetCenterX'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the top center of the other. - * - * @function Phaser.Display.Align.In.TopCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var TopCenter = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); - SetTop(gameObject, GetTop(alignIn) - offsetY); - - return gameObject; -}; - -module.exports = TopCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterX = require('../../bounds/GetCenterX'); +var GetTop = require('../../bounds/GetTop'); +var SetCenterX = require('../../bounds/SetCenterX'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the top center of the other. + * + * @function Phaser.Display.Align.In.TopCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var TopCenter = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); + SetTop(gameObject, GetTop(alignIn) - offsetY); + + return gameObject; +}; + +module.exports = TopCenter; diff --git a/src/display/align/in/TopLeft.js b/src/display/align/in/TopLeft.js index 12246f906..9c7a22f6f 100644 --- a/src/display/align/in/TopLeft.js +++ b/src/display/align/in/TopLeft.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetLeft = require('../../bounds/GetLeft'); -var GetTop = require('../../bounds/GetTop'); -var SetLeft = require('../../bounds/SetLeft'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the top left of the other. - * - * @function Phaser.Display.Align.In.TopLeft - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var TopLeft = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetLeft(alignIn) - offsetX); - SetTop(gameObject, GetTop(alignIn) - offsetY); - - return gameObject; -}; - -module.exports = TopLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLeft = require('../../bounds/GetLeft'); +var GetTop = require('../../bounds/GetTop'); +var SetLeft = require('../../bounds/SetLeft'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the top left of the other. + * + * @function Phaser.Display.Align.In.TopLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var TopLeft = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignIn) - offsetX); + SetTop(gameObject, GetTop(alignIn) - offsetY); + + return gameObject; +}; + +module.exports = TopLeft; diff --git a/src/display/align/in/TopRight.js b/src/display/align/in/TopRight.js index c544dd9e2..deb22484d 100644 --- a/src/display/align/in/TopRight.js +++ b/src/display/align/in/TopRight.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetRight = require('../../bounds/GetRight'); -var GetTop = require('../../bounds/GetTop'); -var SetRight = require('../../bounds/SetRight'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned in the top right of the other. - * - * @function Phaser.Display.Align.In.TopRight - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. - * @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. - */ -var TopRight = function (gameObject, alignIn, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetRight(alignIn) + offsetX); - SetTop(gameObject, GetTop(alignIn) - offsetY); - - return gameObject; -}; - -module.exports = TopRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetRight = require('../../bounds/GetRight'); +var GetTop = require('../../bounds/GetTop'); +var SetRight = require('../../bounds/SetRight'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned in the top right of the other. + * + * @function Phaser.Display.Align.In.TopRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. + * @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. + */ +var TopRight = function (gameObject, alignIn, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignIn) + offsetX); + SetTop(gameObject, GetTop(alignIn) - offsetY); + + return gameObject; +}; + +module.exports = TopRight; diff --git a/src/display/align/in/index.js b/src/display/align/in/index.js index adb9a29cc..a50923be6 100644 --- a/src/display/align/in/index.js +++ b/src/display/align/in/index.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Align.In - */ - -module.exports = { - - BottomCenter: require('./BottomCenter'), - BottomLeft: require('./BottomLeft'), - BottomRight: require('./BottomRight'), - Center: require('./Center'), - LeftCenter: require('./LeftCenter'), - QuickSet: require('./QuickSet'), - RightCenter: require('./RightCenter'), - TopCenter: require('./TopCenter'), - TopLeft: require('./TopLeft'), - TopRight: require('./TopRight') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Align.In + */ + +module.exports = { + + BottomCenter: require('./BottomCenter'), + BottomLeft: require('./BottomLeft'), + BottomRight: require('./BottomRight'), + Center: require('./Center'), + LeftCenter: require('./LeftCenter'), + QuickSet: require('./QuickSet'), + RightCenter: require('./RightCenter'), + TopCenter: require('./TopCenter'), + TopLeft: require('./TopLeft'), + TopRight: require('./TopRight') + +}; diff --git a/src/display/align/index.js b/src/display/align/index.js index 61286cbe1..0470d84bd 100644 --- a/src/display/align/index.js +++ b/src/display/align/index.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../../utils/object/Extend'); - -/** - * @namespace Phaser.Display.Align - */ - -var Align = { - - In: require('./in'), - To: require('./to') - -}; - -// Merge in the consts -Align = Extend(false, Align, CONST); - -module.exports = Align; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../../utils/object/Extend'); + +/** + * @namespace Phaser.Display.Align + */ + +var Align = { + + In: require('./in'), + To: require('./to') + +}; + +// Merge in the consts +Align = Extend(false, Align, CONST); + +module.exports = Align; diff --git a/src/display/align/to/BottomCenter.js b/src/display/align/to/BottomCenter.js index 615d58b41..e90240a41 100644 --- a/src/display/align/to/BottomCenter.js +++ b/src/display/align/to/BottomCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetCenterX = require('../../bounds/GetCenterX'); -var SetCenterX = require('../../bounds/SetCenterX'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the bottom center position of the other. - * - * @function Phaser.Display.Align.To.BottomCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var BottomCenter = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); - SetTop(gameObject, GetBottom(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = BottomCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetCenterX = require('../../bounds/GetCenterX'); +var SetCenterX = require('../../bounds/SetCenterX'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the bottom center position of the other. + * + * @function Phaser.Display.Align.To.BottomCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var BottomCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); + SetTop(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = BottomCenter; diff --git a/src/display/align/to/BottomLeft.js b/src/display/align/to/BottomLeft.js index 0c8874a9b..d5e681bd5 100644 --- a/src/display/align/to/BottomLeft.js +++ b/src/display/align/to/BottomLeft.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetLeft = require('../../bounds/GetLeft'); -var SetLeft = require('../../bounds/SetLeft'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the bottom left position of the other. - * - * @function Phaser.Display.Align.To.BottomLeft - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var BottomLeft = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetLeft(alignTo) - offsetX); - SetTop(gameObject, GetBottom(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = BottomLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetLeft = require('../../bounds/GetLeft'); +var SetLeft = require('../../bounds/SetLeft'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the bottom left position of the other. + * + * @function Phaser.Display.Align.To.BottomLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var BottomLeft = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignTo) - offsetX); + SetTop(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = BottomLeft; diff --git a/src/display/align/to/BottomRight.js b/src/display/align/to/BottomRight.js index b4969dbf6..a43545d7c 100644 --- a/src/display/align/to/BottomRight.js +++ b/src/display/align/to/BottomRight.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetRight = require('../../bounds/GetRight'); -var SetRight = require('../../bounds/SetRight'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the bottom right position of the other. - * - * @function Phaser.Display.Align.To.BottomRight - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var BottomRight = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetRight(alignTo) + offsetX); - SetTop(gameObject, GetBottom(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = BottomRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetRight = require('../../bounds/GetRight'); +var SetRight = require('../../bounds/SetRight'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the bottom right position of the other. + * + * @function Phaser.Display.Align.To.BottomRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var BottomRight = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignTo) + offsetX); + SetTop(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = BottomRight; diff --git a/src/display/align/to/LeftBottom.js b/src/display/align/to/LeftBottom.js index 6991236f2..e47226b0e 100644 --- a/src/display/align/to/LeftBottom.js +++ b/src/display/align/to/LeftBottom.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetLeft = require('../../bounds/GetLeft'); -var SetBottom = require('../../bounds/SetBottom'); -var SetRight = require('../../bounds/SetRight'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the left bottom position of the other. - * - * @function Phaser.Display.Align.To.LeftBottom - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var LeftBottom = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetLeft(alignTo) - offsetX); - SetBottom(gameObject, GetBottom(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = LeftBottom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetLeft = require('../../bounds/GetLeft'); +var SetBottom = require('../../bounds/SetBottom'); +var SetRight = require('../../bounds/SetRight'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the left bottom position of the other. + * + * @function Phaser.Display.Align.To.LeftBottom + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var LeftBottom = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetLeft(alignTo) - offsetX); + SetBottom(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = LeftBottom; diff --git a/src/display/align/to/LeftCenter.js b/src/display/align/to/LeftCenter.js index 09d05a101..b3ac1d61b 100644 --- a/src/display/align/to/LeftCenter.js +++ b/src/display/align/to/LeftCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetCenterY = require('../../bounds/GetCenterY'); -var GetLeft = require('../../bounds/GetLeft'); -var SetCenterY = require('../../bounds/SetCenterY'); -var SetRight = require('../../bounds/SetRight'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the left center position of the other. - * - * @function Phaser.Display.Align.To.LeftCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var LeftCenter = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetLeft(alignTo) - offsetX); - SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = LeftCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = require('../../bounds/GetCenterY'); +var GetLeft = require('../../bounds/GetLeft'); +var SetCenterY = require('../../bounds/SetCenterY'); +var SetRight = require('../../bounds/SetRight'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the left center position of the other. + * + * @function Phaser.Display.Align.To.LeftCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var LeftCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetLeft(alignTo) - offsetX); + SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = LeftCenter; diff --git a/src/display/align/to/LeftTop.js b/src/display/align/to/LeftTop.js index 8dafc8dbf..e1e2c9fa6 100644 --- a/src/display/align/to/LeftTop.js +++ b/src/display/align/to/LeftTop.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetLeft = require('../../bounds/GetLeft'); -var GetTop = require('../../bounds/GetTop'); -var SetRight = require('../../bounds/SetRight'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the left top position of the other. - * - * @function Phaser.Display.Align.To.LeftTop - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var LeftTop = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetLeft(alignTo) - offsetX); - SetTop(gameObject, GetTop(alignTo) - offsetY); - - return gameObject; -}; - -module.exports = LeftTop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLeft = require('../../bounds/GetLeft'); +var GetTop = require('../../bounds/GetTop'); +var SetRight = require('../../bounds/SetRight'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the left top position of the other. + * + * @function Phaser.Display.Align.To.LeftTop + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var LeftTop = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetLeft(alignTo) - offsetX); + SetTop(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = LeftTop; diff --git a/src/display/align/to/QuickSet.js b/src/display/align/to/QuickSet.js index 5df6df89e..18b789de3 100644 --- a/src/display/align/to/QuickSet.js +++ b/src/display/align/to/QuickSet.js @@ -1,46 +1,46 @@ -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ALIGN_CONST = require('../const'); - -var AlignToMap = []; - -AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = require('./BottomCenter'); -AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = require('./BottomLeft'); -AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = require('./BottomRight'); -AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = require('./LeftBottom'); -AlignToMap[ALIGN_CONST.LEFT_CENTER] = require('./LeftCenter'); -AlignToMap[ALIGN_CONST.LEFT_TOP] = require('./LeftTop'); -AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = require('./RightBottom'); -AlignToMap[ALIGN_CONST.RIGHT_CENTER] = require('./RightCenter'); -AlignToMap[ALIGN_CONST.RIGHT_TOP] = require('./RightTop'); -AlignToMap[ALIGN_CONST.TOP_CENTER] = require('./TopCenter'); -AlignToMap[ALIGN_CONST.TOP_LEFT] = require('./TopLeft'); -AlignToMap[ALIGN_CONST.TOP_RIGHT] = require('./TopRight'); - -/** - * 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 {integer} 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. - * @param {number} [offsetY=0] - Optional vertical offset from the position. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was aligned. - */ -var QuickSet = function (child, alignTo, position, offsetX, offsetY) -{ - return AlignToMap[position](child, alignTo, offsetX, offsetY); -}; - -module.exports = QuickSet; +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = require('../const'); + +var AlignToMap = []; + +AlignToMap[ALIGN_CONST.BOTTOM_CENTER] = require('./BottomCenter'); +AlignToMap[ALIGN_CONST.BOTTOM_LEFT] = require('./BottomLeft'); +AlignToMap[ALIGN_CONST.BOTTOM_RIGHT] = require('./BottomRight'); +AlignToMap[ALIGN_CONST.LEFT_BOTTOM] = require('./LeftBottom'); +AlignToMap[ALIGN_CONST.LEFT_CENTER] = require('./LeftCenter'); +AlignToMap[ALIGN_CONST.LEFT_TOP] = require('./LeftTop'); +AlignToMap[ALIGN_CONST.RIGHT_BOTTOM] = require('./RightBottom'); +AlignToMap[ALIGN_CONST.RIGHT_CENTER] = require('./RightCenter'); +AlignToMap[ALIGN_CONST.RIGHT_TOP] = require('./RightTop'); +AlignToMap[ALIGN_CONST.TOP_CENTER] = require('./TopCenter'); +AlignToMap[ALIGN_CONST.TOP_LEFT] = require('./TopLeft'); +AlignToMap[ALIGN_CONST.TOP_RIGHT] = require('./TopRight'); + +/** + * 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 {integer} 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. + * @param {number} [offsetY=0] - Optional vertical offset from the position. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was aligned. + */ +var QuickSet = function (child, alignTo, position, offsetX, offsetY) +{ + return AlignToMap[position](child, alignTo, offsetX, offsetY); +}; + +module.exports = QuickSet; diff --git a/src/display/align/to/RightBottom.js b/src/display/align/to/RightBottom.js index 7c6e2e708..a5d3a6584 100644 --- a/src/display/align/to/RightBottom.js +++ b/src/display/align/to/RightBottom.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetBottom = require('../../bounds/GetBottom'); -var GetRight = require('../../bounds/GetRight'); -var SetBottom = require('../../bounds/SetBottom'); -var SetLeft = require('../../bounds/SetLeft'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the right bottom position of the other. - * - * @function Phaser.Display.Align.To.RightBottom - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var RightBottom = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetRight(alignTo) + offsetX); - SetBottom(gameObject, GetBottom(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = RightBottom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetBottom = require('../../bounds/GetBottom'); +var GetRight = require('../../bounds/GetRight'); +var SetBottom = require('../../bounds/SetBottom'); +var SetLeft = require('../../bounds/SetLeft'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the right bottom position of the other. + * + * @function Phaser.Display.Align.To.RightBottom + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var RightBottom = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetRight(alignTo) + offsetX); + SetBottom(gameObject, GetBottom(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = RightBottom; diff --git a/src/display/align/to/RightCenter.js b/src/display/align/to/RightCenter.js index 92d3babde..7a0d18558 100644 --- a/src/display/align/to/RightCenter.js +++ b/src/display/align/to/RightCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetCenterY = require('../../bounds/GetCenterY'); -var GetRight = require('../../bounds/GetRight'); -var SetCenterY = require('../../bounds/SetCenterY'); -var SetLeft = require('../../bounds/SetLeft'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the right center position of the other. - * - * @function Phaser.Display.Align.To.RightCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var RightCenter = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetRight(alignTo) + offsetX); - SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); - - return gameObject; -}; - -module.exports = RightCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterY = require('../../bounds/GetCenterY'); +var GetRight = require('../../bounds/GetRight'); +var SetCenterY = require('../../bounds/SetCenterY'); +var SetLeft = require('../../bounds/SetLeft'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the right center position of the other. + * + * @function Phaser.Display.Align.To.RightCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var RightCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetRight(alignTo) + offsetX); + SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); + + return gameObject; +}; + +module.exports = RightCenter; diff --git a/src/display/align/to/RightTop.js b/src/display/align/to/RightTop.js index 89bc01286..8e9f4dc9d 100644 --- a/src/display/align/to/RightTop.js +++ b/src/display/align/to/RightTop.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetRight = require('../../bounds/GetRight'); -var GetTop = require('../../bounds/GetTop'); -var SetLeft = require('../../bounds/SetLeft'); -var SetTop = require('../../bounds/SetTop'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the right top position of the other. - * - * @function Phaser.Display.Align.To.RightTop - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var RightTop = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetRight(alignTo) + offsetX); - SetTop(gameObject, GetTop(alignTo) - offsetY); - - return gameObject; -}; - -module.exports = RightTop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetRight = require('../../bounds/GetRight'); +var GetTop = require('../../bounds/GetTop'); +var SetLeft = require('../../bounds/SetLeft'); +var SetTop = require('../../bounds/SetTop'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the right top position of the other. + * + * @function Phaser.Display.Align.To.RightTop + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var RightTop = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetRight(alignTo) + offsetX); + SetTop(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = RightTop; diff --git a/src/display/align/to/TopCenter.js b/src/display/align/to/TopCenter.js index 5b393b0dd..78d8fe9da 100644 --- a/src/display/align/to/TopCenter.js +++ b/src/display/align/to/TopCenter.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetCenterX = require('../../bounds/GetCenterX'); -var GetTop = require('../../bounds/GetTop'); -var SetBottom = require('../../bounds/SetBottom'); -var SetCenterX = require('../../bounds/SetCenterX'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. - * - * @function Phaser.Display.Align.To.TopCenter - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var TopCenter = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); - SetBottom(gameObject, GetTop(alignTo) - offsetY); - - return gameObject; -}; - -module.exports = TopCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetCenterX = require('../../bounds/GetCenterX'); +var GetTop = require('../../bounds/GetTop'); +var SetBottom = require('../../bounds/SetBottom'); +var SetCenterX = require('../../bounds/SetCenterX'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. + * + * @function Phaser.Display.Align.To.TopCenter + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var TopCenter = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); + SetBottom(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = TopCenter; diff --git a/src/display/align/to/TopLeft.js b/src/display/align/to/TopLeft.js index 88662607e..6b2747be8 100644 --- a/src/display/align/to/TopLeft.js +++ b/src/display/align/to/TopLeft.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetLeft = require('../../bounds/GetLeft'); -var GetTop = require('../../bounds/GetTop'); -var SetBottom = require('../../bounds/SetBottom'); -var SetLeft = require('../../bounds/SetLeft'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the top left position of the other. - * - * @function Phaser.Display.Align.To.TopLeft - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var TopLeft = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetLeft(gameObject, GetLeft(alignTo) - offsetX); - SetBottom(gameObject, GetTop(alignTo) - offsetY); - - return gameObject; -}; - -module.exports = TopLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLeft = require('../../bounds/GetLeft'); +var GetTop = require('../../bounds/GetTop'); +var SetBottom = require('../../bounds/SetBottom'); +var SetLeft = require('../../bounds/SetLeft'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the top left position of the other. + * + * @function Phaser.Display.Align.To.TopLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var TopLeft = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetLeft(gameObject, GetLeft(alignTo) - offsetX); + SetBottom(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = TopLeft; diff --git a/src/display/align/to/TopRight.js b/src/display/align/to/TopRight.js index 6019165ce..a9a7a7c89 100644 --- a/src/display/align/to/TopRight.js +++ b/src/display/align/to/TopRight.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetRight = require('../../bounds/GetRight'); -var GetTop = require('../../bounds/GetTop'); -var SetBottom = require('../../bounds/SetBottom'); -var SetRight = require('../../bounds/SetRight'); - -/** - * Takes given Game Object and aligns it so that it is positioned next to the top right position of the other. - * - * @function Phaser.Display.Align.To.TopRight - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. - * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. - * @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. - */ -var TopRight = function (gameObject, alignTo, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - SetRight(gameObject, GetRight(alignTo) + offsetX); - SetBottom(gameObject, GetTop(alignTo) - offsetY); - - return gameObject; -}; - -module.exports = TopRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetRight = require('../../bounds/GetRight'); +var GetTop = require('../../bounds/GetTop'); +var SetBottom = require('../../bounds/SetBottom'); +var SetRight = require('../../bounds/SetRight'); + +/** + * Takes given Game Object and aligns it so that it is positioned next to the top right position of the other. + * + * @function Phaser.Display.Align.To.TopRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. + * @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on. + * @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. + */ +var TopRight = function (gameObject, alignTo, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + SetRight(gameObject, GetRight(alignTo) + offsetX); + SetBottom(gameObject, GetTop(alignTo) - offsetY); + + return gameObject; +}; + +module.exports = TopRight; diff --git a/src/display/align/to/index.js b/src/display/align/to/index.js index 8f7dffdc4..29907ae13 100644 --- a/src/display/align/to/index.js +++ b/src/display/align/to/index.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Align.To - */ - -module.exports = { - - BottomCenter: require('./BottomCenter'), - BottomLeft: require('./BottomLeft'), - BottomRight: require('./BottomRight'), - LeftBottom: require('./LeftBottom'), - LeftCenter: require('./LeftCenter'), - LeftTop: require('./LeftTop'), - QuickSet: require('./QuickSet'), - RightBottom: require('./RightBottom'), - RightCenter: require('./RightCenter'), - RightTop: require('./RightTop'), - TopCenter: require('./TopCenter'), - TopLeft: require('./TopLeft'), - TopRight: require('./TopRight') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Align.To + */ + +module.exports = { + + BottomCenter: require('./BottomCenter'), + BottomLeft: require('./BottomLeft'), + BottomRight: require('./BottomRight'), + LeftBottom: require('./LeftBottom'), + LeftCenter: require('./LeftCenter'), + LeftTop: require('./LeftTop'), + QuickSet: require('./QuickSet'), + RightBottom: require('./RightBottom'), + RightCenter: require('./RightCenter'), + RightTop: require('./RightTop'), + TopCenter: require('./TopCenter'), + TopLeft: require('./TopLeft'), + TopRight: require('./TopRight') + +}; diff --git a/src/display/bounds/CenterOn.js b/src/display/bounds/CenterOn.js index ea3820c75..a7fe75dd7 100644 --- a/src/display/bounds/CenterOn.js +++ b/src/display/bounds/CenterOn.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetCenterX = require('./SetCenterX'); -var SetCenterY = require('./SetCenterY'); - -/** - * Positions the Game Object so that it is centered on the given coordinates. - * - * @function Phaser.Display.Bounds.CenterOn - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} x - The horizontal coordinate to position the Game Object on. - * @param {number} y - The vertical coordinate to position the Game Object on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var CenterOn = function (gameObject, x, y) -{ - SetCenterX(gameObject, x); - - return SetCenterY(gameObject, y); -}; - -module.exports = CenterOn; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetCenterX = require('./SetCenterX'); +var SetCenterY = require('./SetCenterY'); + +/** + * Positions the Game Object so that it is centered on the given coordinates. + * + * @function Phaser.Display.Bounds.CenterOn + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} x - The horizontal coordinate to position the Game Object on. + * @param {number} y - The vertical coordinate to position the Game Object on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var CenterOn = function (gameObject, x, y) +{ + SetCenterX(gameObject, x); + + return SetCenterY(gameObject, y); +}; + +module.exports = CenterOn; diff --git a/src/display/bounds/GetBottom.js b/src/display/bounds/GetBottom.js index e404b13ca..df313a6a6 100644 --- a/src/display/bounds/GetBottom.js +++ b/src/display/bounds/GetBottom.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the bottom coordinate from the bounds of the Game Object. - * - * @function Phaser.Display.Bounds.GetBottom - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The bottom coordinate of the bounds of the Game Object. - */ -var GetBottom = function (gameObject) -{ - return (gameObject.y + gameObject.height) - (gameObject.height * gameObject.originY); -}; - -module.exports = GetBottom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the bottom coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetBottom + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The bottom coordinate of the bounds of the Game Object. + */ +var GetBottom = function (gameObject) +{ + return (gameObject.y + gameObject.height) - (gameObject.height * gameObject.originY); +}; + +module.exports = GetBottom; diff --git a/src/display/bounds/GetCenterX.js b/src/display/bounds/GetCenterX.js index 05b16d6bc..bc580071b 100644 --- a/src/display/bounds/GetCenterX.js +++ b/src/display/bounds/GetCenterX.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the center x coordinate from the bounds of the Game Object. - * - * @function Phaser.Display.Bounds.GetCenterX - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The center x coordinate of the bounds of the Game Object. - */ -var GetCenterX = function (gameObject) -{ - return gameObject.x - (gameObject.width * gameObject.originX) + (gameObject.width * 0.5); -}; - -module.exports = GetCenterX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the center x coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetCenterX + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The center x coordinate of the bounds of the Game Object. + */ +var GetCenterX = function (gameObject) +{ + return gameObject.x - (gameObject.width * gameObject.originX) + (gameObject.width * 0.5); +}; + +module.exports = GetCenterX; diff --git a/src/display/bounds/GetCenterY.js b/src/display/bounds/GetCenterY.js index 924538381..eaa0cc971 100644 --- a/src/display/bounds/GetCenterY.js +++ b/src/display/bounds/GetCenterY.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the center y coordinate from the bounds of the Game Object. - * - * @function Phaser.Display.Bounds.GetCenterY - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The center y coordinate of the bounds of the Game Object. - */ -var GetCenterY = function (gameObject) -{ - return gameObject.y - (gameObject.height * gameObject.originY) + (gameObject.height * 0.5); -}; - -module.exports = GetCenterY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the center y coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetCenterY + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The center y coordinate of the bounds of the Game Object. + */ +var GetCenterY = function (gameObject) +{ + return gameObject.y - (gameObject.height * gameObject.originY) + (gameObject.height * 0.5); +}; + +module.exports = GetCenterY; diff --git a/src/display/bounds/GetLeft.js b/src/display/bounds/GetLeft.js index c57e32766..ea739a76d 100644 --- a/src/display/bounds/GetLeft.js +++ b/src/display/bounds/GetLeft.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the left coordinate from the bounds of the Game Object. - * - * @function Phaser.Display.Bounds.GetLeft - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The left coordinate of the bounds of the Game Object. - */ -var GetLeft = function (gameObject) -{ - return gameObject.x - (gameObject.width * gameObject.originX); -}; - -module.exports = GetLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the left coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetLeft + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The left coordinate of the bounds of the Game Object. + */ +var GetLeft = function (gameObject) +{ + return gameObject.x - (gameObject.width * gameObject.originX); +}; + +module.exports = GetLeft; diff --git a/src/display/bounds/GetOffsetX.js b/src/display/bounds/GetOffsetX.js index be57b14a9..95a4238c8 100644 --- a/src/display/bounds/GetOffsetX.js +++ b/src/display/bounds/GetOffsetX.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the amount the Game Object is visually offset from its x coordinate. - * This is the same as `width * origin.x`. - * This value will only be > 0 if `origin.x` is not equal to zero. - * - * @function Phaser.Display.Bounds.GetOffsetX - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The horizontal offset of the Game Object. - */ -var GetOffsetX = function (gameObject) -{ - return gameObject.width * gameObject.originX; -}; - -module.exports = GetOffsetX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * origin.x`. + * This value will only be > 0 if `origin.x` is not equal to zero. + * + * @function Phaser.Display.Bounds.GetOffsetX + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The horizontal offset of the Game Object. + */ +var GetOffsetX = function (gameObject) +{ + return gameObject.width * gameObject.originX; +}; + +module.exports = GetOffsetX; diff --git a/src/display/bounds/GetOffsetY.js b/src/display/bounds/GetOffsetY.js index a61eced71..9955c7da4 100644 --- a/src/display/bounds/GetOffsetY.js +++ b/src/display/bounds/GetOffsetY.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the amount the Game Object is visually offset from its y coordinate. - * This is the same as `width * origin.y`. - * This value will only be > 0 if `origin.y` is not equal to zero. - * - * @function Phaser.Display.Bounds.GetOffsetY - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The vertical offset of the Game Object. - */ -var GetOffsetY = function (gameObject) -{ - return gameObject.height * gameObject.originY; -}; - -module.exports = GetOffsetY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the amount the Game Object is visually offset from its y coordinate. + * This is the same as `width * origin.y`. + * This value will only be > 0 if `origin.y` is not equal to zero. + * + * @function Phaser.Display.Bounds.GetOffsetY + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The vertical offset of the Game Object. + */ +var GetOffsetY = function (gameObject) +{ + return gameObject.height * gameObject.originY; +}; + +module.exports = GetOffsetY; diff --git a/src/display/bounds/GetRight.js b/src/display/bounds/GetRight.js index d38fcc6d6..bd4f4ebbf 100644 --- a/src/display/bounds/GetRight.js +++ b/src/display/bounds/GetRight.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the right coordinate from the bounds of the Game Object. - * - * @function Phaser.Display.Bounds.GetRight - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The right coordinate of the bounds of the Game Object. - */ -var GetRight = function (gameObject) -{ - return (gameObject.x + gameObject.width) - (gameObject.width * gameObject.originX); -}; - -module.exports = GetRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the right coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetRight + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The right coordinate of the bounds of the Game Object. + */ +var GetRight = function (gameObject) +{ + return (gameObject.x + gameObject.width) - (gameObject.width * gameObject.originX); +}; + +module.exports = GetRight; diff --git a/src/display/bounds/GetTop.js b/src/display/bounds/GetTop.js index db338d698..2027f91ee 100644 --- a/src/display/bounds/GetTop.js +++ b/src/display/bounds/GetTop.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the top coordinate from the bounds of the Game Object. - * - * @function Phaser.Display.Bounds.GetTop - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. - * - * @return {number} The top coordinate of the bounds of the Game Object. - */ -var GetTop = function (gameObject) -{ - return gameObject.y - (gameObject.height * gameObject.originY); -}; - -module.exports = GetTop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the top coordinate from the bounds of the Game Object. + * + * @function Phaser.Display.Bounds.GetTop + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. + * + * @return {number} The top coordinate of the bounds of the Game Object. + */ +var GetTop = function (gameObject) +{ + return gameObject.y - (gameObject.height * gameObject.originY); +}; + +module.exports = GetTop; diff --git a/src/display/bounds/SetBottom.js b/src/display/bounds/SetBottom.js index 643b5ad33..c8b392fdc 100644 --- a/src/display/bounds/SetBottom.js +++ b/src/display/bounds/SetBottom.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Positions the Game Object so that the bottom of its bounds aligns with the given coordinate. - * - * @function Phaser.Display.Bounds.SetBottom - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} value - The coordinate to position the Game Object bounds on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var SetBottom = function (gameObject, value) -{ - gameObject.y = (value - gameObject.height) + (gameObject.height * gameObject.originY); - - return gameObject; -}; - -module.exports = SetBottom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the bottom of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetBottom + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetBottom = function (gameObject, value) +{ + gameObject.y = (value - gameObject.height) + (gameObject.height * gameObject.originY); + + return gameObject; +}; + +module.exports = SetBottom; diff --git a/src/display/bounds/SetCenterX.js b/src/display/bounds/SetCenterX.js index 7fd454aae..af4b30421 100644 --- a/src/display/bounds/SetCenterX.js +++ b/src/display/bounds/SetCenterX.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. - * - * @function Phaser.Display.Bounds.SetCenterX - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} x - The coordinate to position the Game Object bounds on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var SetCenterX = function (gameObject, x) -{ - var offsetX = gameObject.width * gameObject.originX; - - gameObject.x = (x + offsetX) - (gameObject.width * 0.5); - - return gameObject; -}; - -module.exports = SetCenterX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetCenterX + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} x - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetCenterX = function (gameObject, x) +{ + var offsetX = gameObject.width * gameObject.originX; + + gameObject.x = (x + offsetX) - (gameObject.width * 0.5); + + return gameObject; +}; + +module.exports = SetCenterX; diff --git a/src/display/bounds/SetCenterY.js b/src/display/bounds/SetCenterY.js index 4a225ec2b..050ab6e82 100644 --- a/src/display/bounds/SetCenterY.js +++ b/src/display/bounds/SetCenterY.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. - * - * @function Phaser.Display.Bounds.SetCenterY - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} y - The coordinate to position the Game Object bounds on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var SetCenterY = function (gameObject, y) -{ - var offsetY = gameObject.height * gameObject.originY; - - gameObject.y = (y + offsetY) - (gameObject.height * 0.5); - - return gameObject; -}; - -module.exports = SetCenterY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetCenterY + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} y - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetCenterY = function (gameObject, y) +{ + var offsetY = gameObject.height * gameObject.originY; + + gameObject.y = (y + offsetY) - (gameObject.height * 0.5); + + return gameObject; +}; + +module.exports = SetCenterY; diff --git a/src/display/bounds/SetLeft.js b/src/display/bounds/SetLeft.js index 95fd46811..4bfd72181 100644 --- a/src/display/bounds/SetLeft.js +++ b/src/display/bounds/SetLeft.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Positions the Game Object so that the left of its bounds aligns with the given coordinate. - * - * @function Phaser.Display.Bounds.SetLeft - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} value - The coordinate to position the Game Object bounds on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var SetLeft = function (gameObject, value) -{ - gameObject.x = value + (gameObject.width * gameObject.originX); - - return gameObject; -}; - -module.exports = SetLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the left of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetLeft + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetLeft = function (gameObject, value) +{ + gameObject.x = value + (gameObject.width * gameObject.originX); + + return gameObject; +}; + +module.exports = SetLeft; diff --git a/src/display/bounds/SetRight.js b/src/display/bounds/SetRight.js index cfd986750..cfd9804f5 100644 --- a/src/display/bounds/SetRight.js +++ b/src/display/bounds/SetRight.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Positions the Game Object so that the left of its bounds aligns with the given coordinate. - * - * @function Phaser.Display.Bounds.SetRight - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} value - The coordinate to position the Game Object bounds on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var SetRight = function (gameObject, value) -{ - gameObject.x = (value - gameObject.width) + (gameObject.width * gameObject.originX); - - return gameObject; -}; - -module.exports = SetRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the left of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetRight + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetRight = function (gameObject, value) +{ + gameObject.x = (value - gameObject.width) + (gameObject.width * gameObject.originX); + + return gameObject; +}; + +module.exports = SetRight; diff --git a/src/display/bounds/SetTop.js b/src/display/bounds/SetTop.js index ba9a755e8..67e81a52a 100644 --- a/src/display/bounds/SetTop.js +++ b/src/display/bounds/SetTop.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Positions the Game Object so that the top of its bounds aligns with the given coordinate. - * - * @function Phaser.Display.Bounds.SetTop - * @since 3.0.0 - * - * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. - * @param {number} value - The coordinate to position the Game Object bounds on. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. - */ -var SetTop = function (gameObject, value) -{ - gameObject.y = value + (gameObject.height * gameObject.originY); - - return gameObject; -}; - -module.exports = SetTop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Positions the Game Object so that the top of its bounds aligns with the given coordinate. + * + * @function Phaser.Display.Bounds.SetTop + * @since 3.0.0 + * + * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. + * @param {number} value - The coordinate to position the Game Object bounds on. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. + */ +var SetTop = function (gameObject, value) +{ + gameObject.y = value + (gameObject.height * gameObject.originY); + + return gameObject; +}; + +module.exports = SetTop; diff --git a/src/display/bounds/index.js b/src/display/bounds/index.js index 5f82d731b..a17f2f1cb 100644 --- a/src/display/bounds/index.js +++ b/src/display/bounds/index.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Bounds - */ - -module.exports = { - - CenterOn: require('./CenterOn'), - GetBottom: require('./GetBottom'), - GetCenterX: require('./GetCenterX'), - GetCenterY: require('./GetCenterY'), - GetLeft: require('./GetLeft'), - GetOffsetX: require('./GetOffsetX'), - GetOffsetY: require('./GetOffsetY'), - GetRight: require('./GetRight'), - GetTop: require('./GetTop'), - SetBottom: require('./SetBottom'), - SetCenterX: require('./SetCenterX'), - SetCenterY: require('./SetCenterY'), - SetLeft: require('./SetLeft'), - SetRight: require('./SetRight'), - SetTop: require('./SetTop') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Bounds + */ + +module.exports = { + + CenterOn: require('./CenterOn'), + GetBottom: require('./GetBottom'), + GetCenterX: require('./GetCenterX'), + GetCenterY: require('./GetCenterY'), + GetLeft: require('./GetLeft'), + GetOffsetX: require('./GetOffsetX'), + GetOffsetY: require('./GetOffsetY'), + GetRight: require('./GetRight'), + GetTop: require('./GetTop'), + SetBottom: require('./SetBottom'), + SetCenterX: require('./SetCenterX'), + SetCenterY: require('./SetCenterY'), + SetLeft: require('./SetLeft'), + SetRight: require('./SetRight'), + SetTop: require('./SetTop') + +}; diff --git a/src/display/canvas/CanvasInterpolation.js b/src/display/canvas/CanvasInterpolation.js index d38d31cc0..0add3671a 100644 --- a/src/display/canvas/CanvasInterpolation.js +++ b/src/display/canvas/CanvasInterpolation.js @@ -1,57 +1,57 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Canvas.CanvasInterpolation - * @since 3.0.0 - */ -var CanvasInterpolation = { - - /** - * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit). - * - * @function Phaser.Display.Canvas.CanvasInterpolation.setCrisp - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The canvas object to have the style set on. - * - * @return {HTMLCanvasElement} The canvas. - */ - setCrisp: function (canvas) - { - var types = [ 'optimizeSpeed', '-moz-crisp-edges', '-o-crisp-edges', '-webkit-optimize-contrast', 'optimize-contrast', 'crisp-edges', 'pixelated' ]; - - types.forEach(function (type) - { - canvas.style['image-rendering'] = type; - }); - - canvas.style.msInterpolationMode = 'nearest-neighbor'; - - return canvas; - }, - - /** - * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). - * - * @function Phaser.Display.Canvas.CanvasInterpolation.setBicubic - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The canvas object to have the style set on. - * - * @return {HTMLCanvasElement} The canvas. - */ - setBicubic: function (canvas) - { - canvas.style['image-rendering'] = 'auto'; - canvas.style.msInterpolationMode = 'bicubic'; - - return canvas; - } - -}; - -module.exports = CanvasInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Canvas.CanvasInterpolation + * @since 3.0.0 + */ +var CanvasInterpolation = { + + /** + * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit). + * + * @function Phaser.Display.Canvas.CanvasInterpolation.setCrisp + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas object to have the style set on. + * + * @return {HTMLCanvasElement} The canvas. + */ + setCrisp: function (canvas) + { + var types = [ 'optimizeSpeed', '-moz-crisp-edges', '-o-crisp-edges', '-webkit-optimize-contrast', 'optimize-contrast', 'crisp-edges', 'pixelated' ]; + + types.forEach(function (type) + { + canvas.style['image-rendering'] = type; + }); + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * + * @function Phaser.Display.Canvas.CanvasInterpolation.setBicubic + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas object to have the style set on. + * + * @return {HTMLCanvasElement} The canvas. + */ + setBicubic: function (canvas) + { + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + } + +}; + +module.exports = CanvasInterpolation; diff --git a/src/display/canvas/CanvasPool.js b/src/display/canvas/CanvasPool.js index 2054c8216..edc913a03 100644 --- a/src/display/canvas/CanvasPool.js +++ b/src/display/canvas/CanvasPool.js @@ -1,255 +1,255 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const'); -var Smoothing = require('./Smoothing'); - -// The pool into which the canvas elements are placed. -var pool = []; - -// Automatically apply smoothing(false) to created Canvas elements -var _disableContextSmoothing = false; - -/** - * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. - * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, - * which is useless for some of the Phaser pipelines / renderer. - * - * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. - * Which means all instances of Phaser Games on the same page can share the one single pool. - * - * @namespace Phaser.Display.Canvas.CanvasPool - * @since 3.0.0 - */ -var CanvasPool = function () -{ - /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * - * @function Phaser.Display.Canvas.CanvasPool.create - * @since 3.0.0 - * - * @param {*} parent - The parent of the Canvas object. - * @param {integer} [width=1] - The width of the Canvas. - * @param {integer} [height=1] - The height of the Canvas. - * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. - * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? - * - * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool - */ - var create = function (parent, width, height, canvasType, selfParent) - { - if (width === undefined) { width = 1; } - if (height === undefined) { height = 1; } - if (canvasType === undefined) { canvasType = CONST.CANVAS; } - if (selfParent === undefined) { selfParent = false; } - - var canvas; - var container = first(canvasType); - - if (container === null) - { - container = { - parent: parent, - canvas: document.createElement('canvas'), - type: canvasType - }; - - if (canvasType === CONST.CANVAS) - { - pool.push(container); - } - - canvas = container.canvas; - } - else - { - container.parent = parent; - - canvas = container.canvas; - } - - if (selfParent) - { - container.parent = canvas; - } - - canvas.width = width; - canvas.height = height; - - if (_disableContextSmoothing && canvasType === CONST.CANVAS) - { - Smoothing.disable(canvas.getContext('2d')); - } - - return canvas; - }; - - /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * - * @function Phaser.Display.Canvas.CanvasPool.create2D - * @since 3.0.0 - * - * @param {*} parent - The parent of the Canvas object. - * @param {integer} [width=1] - The width of the Canvas. - * @param {integer} [height=1] - The height of the Canvas. - * - * @return {HTMLCanvasElement} The created canvas. - */ - var create2D = function (parent, width, height) - { - return create(parent, width, height, CONST.CANVAS); - }; - - /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * - * @function Phaser.Display.Canvas.CanvasPool.createWebGL - * @since 3.0.0 - * - * @param {*} parent - The parent of the Canvas object. - * @param {integer} [width=1] - The width of the Canvas. - * @param {integer} [height=1] - The height of the Canvas. - * - * @return {HTMLCanvasElement} The created WebGL canvas. - */ - var createWebGL = function (parent, width, height) - { - return create(parent, width, height, CONST.WEBGL); - }; - - /** - * Gets the first free canvas index from the pool. - * - * @function Phaser.Display.Canvas.CanvasPool.first - * @since 3.0.0 - * - * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. - * - * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. - */ - var first = function (canvasType) - { - if (canvasType === undefined) { canvasType = CONST.CANVAS; } - - if (canvasType === CONST.WEBGL) - { - return null; - } - - for (var i = 0; i < pool.length; i++) - { - var container = pool[i]; - - if (!container.parent && container.type === canvasType) - { - return container; - } - } - - return null; - }; - - /** - * 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. - */ - var remove = function (parent) - { - // Check to see if the parent is a canvas object - var isCanvas = parent instanceof HTMLCanvasElement; - - pool.forEach(function (container) - { - if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) - { - container.parent = null; - container.canvas.width = 1; - container.canvas.height = 1; - } - }); - }; - - /** - * Gets the total number of used canvas elements in the pool. - * - * @function Phaser.Display.Canvas.CanvasPool.total - * @since 3.0.0 - * - * @return {integer} The number of used canvases. - */ - var total = function () - { - var c = 0; - - pool.forEach(function (container) - { - if (container.parent) - { - c++; - } - }); - - return c; - }; - - /** - * Gets the total number of free canvas elements in the pool. - * - * @function Phaser.Display.Canvas.CanvasPool.free - * @since 3.0.0 - * - * @return {integer} The number of free canvases. - */ - var free = function () - { - return pool.length - total(); - }; - - /** - * Disable context smoothing on any new Canvas element created. - * - * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing - * @since 3.0.0 - */ - var disableSmoothing = function () - { - _disableContextSmoothing = true; - }; - - /** - * Enable context smoothing on any new Canvas element created. - * - * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing - * @since 3.0.0 - */ - var enableSmoothing = function () - { - _disableContextSmoothing = false; - }; - - return { - create2D: create2D, - create: create, - createWebGL: createWebGL, - disableSmoothing: disableSmoothing, - enableSmoothing: enableSmoothing, - first: first, - free: free, - pool: pool, - remove: remove, - total: total - }; -}; - -// If we export the called function here, it'll only be invoked once (not every time it's required). -module.exports = CanvasPool(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const'); +var Smoothing = require('./Smoothing'); + +// The pool into which the canvas elements are placed. +var pool = []; + +// Automatically apply smoothing(false) to created Canvas elements +var _disableContextSmoothing = false; + +/** + * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. + * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, + * which is useless for some of the Phaser pipelines / renderer. + * + * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. + * Which means all instances of Phaser Games on the same page can share the one single pool. + * + * @namespace Phaser.Display.Canvas.CanvasPool + * @since 3.0.0 + */ +var CanvasPool = function () +{ + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @function Phaser.Display.Canvas.CanvasPool.create + * @since 3.0.0 + * + * @param {*} parent - The parent of the Canvas object. + * @param {integer} [width=1] - The width of the Canvas. + * @param {integer} [height=1] - The height of the Canvas. + * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. + * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? + * + * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool + */ + var create = function (parent, width, height, canvasType, selfParent) + { + if (width === undefined) { width = 1; } + if (height === undefined) { height = 1; } + if (canvasType === undefined) { canvasType = CONST.CANVAS; } + if (selfParent === undefined) { selfParent = false; } + + var canvas; + var container = first(canvasType); + + if (container === null) + { + container = { + parent: parent, + canvas: document.createElement('canvas'), + type: canvasType + }; + + if (canvasType === CONST.CANVAS) + { + pool.push(container); + } + + canvas = container.canvas; + } + else + { + container.parent = parent; + + canvas = container.canvas; + } + + if (selfParent) + { + container.parent = canvas; + } + + canvas.width = width; + canvas.height = height; + + if (_disableContextSmoothing && canvasType === CONST.CANVAS) + { + Smoothing.disable(canvas.getContext('2d')); + } + + return canvas; + }; + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @function Phaser.Display.Canvas.CanvasPool.create2D + * @since 3.0.0 + * + * @param {*} parent - The parent of the Canvas object. + * @param {integer} [width=1] - The width of the Canvas. + * @param {integer} [height=1] - The height of the Canvas. + * + * @return {HTMLCanvasElement} The created canvas. + */ + var create2D = function (parent, width, height) + { + return create(parent, width, height, CONST.CANVAS); + }; + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @function Phaser.Display.Canvas.CanvasPool.createWebGL + * @since 3.0.0 + * + * @param {*} parent - The parent of the Canvas object. + * @param {integer} [width=1] - The width of the Canvas. + * @param {integer} [height=1] - The height of the Canvas. + * + * @return {HTMLCanvasElement} The created WebGL canvas. + */ + var createWebGL = function (parent, width, height) + { + return create(parent, width, height, CONST.WEBGL); + }; + + /** + * Gets the first free canvas index from the pool. + * + * @function Phaser.Display.Canvas.CanvasPool.first + * @since 3.0.0 + * + * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. + * + * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. + */ + var first = function (canvasType) + { + if (canvasType === undefined) { canvasType = CONST.CANVAS; } + + if (canvasType === CONST.WEBGL) + { + return null; + } + + for (var i = 0; i < pool.length; i++) + { + var container = pool[i]; + + if (!container.parent && container.type === canvasType) + { + return container; + } + } + + return null; + }; + + /** + * 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. + */ + var remove = function (parent) + { + // Check to see if the parent is a canvas object + var isCanvas = parent instanceof HTMLCanvasElement; + + pool.forEach(function (container) + { + if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) + { + container.parent = null; + container.canvas.width = 1; + container.canvas.height = 1; + } + }); + }; + + /** + * Gets the total number of used canvas elements in the pool. + * + * @function Phaser.Display.Canvas.CanvasPool.total + * @since 3.0.0 + * + * @return {integer} The number of used canvases. + */ + var total = function () + { + var c = 0; + + pool.forEach(function (container) + { + if (container.parent) + { + c++; + } + }); + + return c; + }; + + /** + * Gets the total number of free canvas elements in the pool. + * + * @function Phaser.Display.Canvas.CanvasPool.free + * @since 3.0.0 + * + * @return {integer} The number of free canvases. + */ + var free = function () + { + return pool.length - total(); + }; + + /** + * Disable context smoothing on any new Canvas element created. + * + * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing + * @since 3.0.0 + */ + var disableSmoothing = function () + { + _disableContextSmoothing = true; + }; + + /** + * Enable context smoothing on any new Canvas element created. + * + * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing + * @since 3.0.0 + */ + var enableSmoothing = function () + { + _disableContextSmoothing = false; + }; + + return { + create2D: create2D, + create: create, + createWebGL: createWebGL, + disableSmoothing: disableSmoothing, + enableSmoothing: enableSmoothing, + first: first, + free: free, + pool: pool, + remove: remove, + total: total + }; +}; + +// If we export the called function here, it'll only be invoked once (not every time it's required). +module.exports = CanvasPool(); diff --git a/src/display/canvas/Smoothing.js b/src/display/canvas/Smoothing.js index 93af63077..17b25c6b3 100644 --- a/src/display/canvas/Smoothing.js +++ b/src/display/canvas/Smoothing.js @@ -1,126 +1,126 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Browser specific prefix, so not going to change between contexts, only between browsers -var prefix = ''; - -/** - * @namespace Phaser.Display.Canvas.Smoothing - * @since 3.0.0 - */ -var Smoothing = function () -{ - /** - * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. - * - * @function Phaser.Display.Canvas.Smoothing.getPrefix - * @since 3.0.0 - * - * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The canvas context to check. - * - * @return {string} The name of the property on the context which controls image smoothing (either `imageSmoothingEnabled` or a vendor-prefixed version thereof), or `null` if not supported. - */ - var getPrefix = function (context) - { - var vendors = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; - - for (var i = 0; i < vendors.length; i++) - { - var s = vendors[i] + 'mageSmoothingEnabled'; - - if (s in context) - { - return s; - } - } - - return null; - }; - - /** - * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. - * By default browsers have image smoothing enabled, which isn't always what you visually want, especially - * when using pixel art in a game. Note that this sets the property on the context itself, so that any image - * drawn to the context will be affected. This sets the property across all current browsers but support is - * patchy on earlier browsers, especially on mobile. - * - * @function Phaser.Display.Canvas.Smoothing.enable - * @since 3.0.0 - * - * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context on which to enable smoothing. - * - * @return {(CanvasRenderingContext2D|WebGLRenderingContext)} The provided context. - */ - var enable = function (context) - { - if (prefix === '') - { - prefix = getPrefix(context); - } - - if (prefix) - { - context[prefix] = true; - } - - return context; - }; - - /** - * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. - * By default browsers have image smoothing enabled, which isn't always what you visually want, especially - * when using pixel art in a game. Note that this sets the property on the context itself, so that any image - * drawn to the context will be affected. This sets the property across all current browsers but support is - * patchy on earlier browsers, especially on mobile. - * - * @function Phaser.Display.Canvas.Smoothing.disable - * @since 3.0.0 - * - * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context on which to disable smoothing. - * - * @return {(CanvasRenderingContext2D|WebGLRenderingContext)} The provided context. - */ - var disable = function (context) - { - if (prefix === '') - { - prefix = getPrefix(context); - } - - if (prefix) - { - context[prefix] = false; - } - - return context; - }; - - /** - * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. - * Returns null if no smoothing prefix is available. - * - * @function Phaser.Display.Canvas.Smoothing.isEnabled - * @since 3.0.0 - * - * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context to check. - * - * @return {?boolean} `true` if smoothing is enabled on the context, otherwise `false`. `null` if not supported. - */ - var isEnabled = function (context) - { - return (prefix !== null) ? context[prefix] : null; - }; - - return { - disable: disable, - enable: enable, - getPrefix: getPrefix, - isEnabled: isEnabled - }; - -}; - -module.exports = Smoothing(); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Browser specific prefix, so not going to change between contexts, only between browsers +var prefix = ''; + +/** + * @namespace Phaser.Display.Canvas.Smoothing + * @since 3.0.0 + */ +var Smoothing = function () +{ + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @function Phaser.Display.Canvas.Smoothing.getPrefix + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The canvas context to check. + * + * @return {string} The name of the property on the context which controls image smoothing (either `imageSmoothingEnabled` or a vendor-prefixed version thereof), or `null` if not supported. + */ + var getPrefix = function (context) + { + var vendors = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var i = 0; i < vendors.length; i++) + { + var s = vendors[i] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + }; + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @function Phaser.Display.Canvas.Smoothing.enable + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context on which to enable smoothing. + * + * @return {(CanvasRenderingContext2D|WebGLRenderingContext)} The provided context. + */ + var enable = function (context) + { + if (prefix === '') + { + prefix = getPrefix(context); + } + + if (prefix) + { + context[prefix] = true; + } + + return context; + }; + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @function Phaser.Display.Canvas.Smoothing.disable + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context on which to disable smoothing. + * + * @return {(CanvasRenderingContext2D|WebGLRenderingContext)} The provided context. + */ + var disable = function (context) + { + if (prefix === '') + { + prefix = getPrefix(context); + } + + if (prefix) + { + context[prefix] = false; + } + + return context; + }; + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * Returns null if no smoothing prefix is available. + * + * @function Phaser.Display.Canvas.Smoothing.isEnabled + * @since 3.0.0 + * + * @param {(CanvasRenderingContext2D|WebGLRenderingContext)} context - The context to check. + * + * @return {?boolean} `true` if smoothing is enabled on the context, otherwise `false`. `null` if not supported. + */ + var isEnabled = function (context) + { + return (prefix !== null) ? context[prefix] : null; + }; + + return { + disable: disable, + enable: enable, + getPrefix: getPrefix, + isEnabled: isEnabled + }; + +}; + +module.exports = Smoothing(); diff --git a/src/display/canvas/TouchAction.js b/src/display/canvas/TouchAction.js index 24f97e86a..ca93858fa 100644 --- a/src/display/canvas/TouchAction.js +++ b/src/display/canvas/TouchAction.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. - * - * @function Phaser.Display.Canvas.TouchAction - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The canvas element to have the style applied to. - * @param {string} [value='none'] - The touch action value to set on the canvas. Set to `none` to disable touch actions. - * - * @return {HTMLCanvasElement} The canvas element. - */ -var TouchAction = function (canvas, value) -{ - if (value === undefined) { value = 'none'; } - - canvas.style['msTouchAction'] = value; - canvas.style['ms-touch-action'] = value; - canvas.style['touch-action'] = value; - - return canvas; -}; - -module.exports = TouchAction; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @function Phaser.Display.Canvas.TouchAction + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas element to have the style applied to. + * @param {string} [value='none'] - The touch action value to set on the canvas. Set to `none` to disable touch actions. + * + * @return {HTMLCanvasElement} The canvas element. + */ +var TouchAction = function (canvas, value) +{ + if (value === undefined) { value = 'none'; } + + canvas.style['msTouchAction'] = value; + canvas.style['ms-touch-action'] = value; + canvas.style['touch-action'] = value; + + return canvas; +}; + +module.exports = TouchAction; diff --git a/src/display/canvas/UserSelect.js b/src/display/canvas/UserSelect.js index 20e6a93e2..d1bf1d932 100644 --- a/src/display/canvas/UserSelect.js +++ b/src/display/canvas/UserSelect.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. - * - * @function Phaser.Display.Canvas.UserSelect - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The canvas element to have the style applied to. - * @param {string} [value='none'] - The touch callout value to set on the canvas. Set to `none` to disable touch callouts. - * - * @return {HTMLCanvasElement} The canvas element. - */ -var UserSelect = function (canvas, value) -{ - if (value === undefined) { value = 'none'; } - - var vendors = [ - '-webkit-', - '-khtml-', - '-moz-', - '-ms-', - '' - ]; - - vendors.forEach(function (vendor) - { - canvas.style[vendor + 'user-select'] = value; - }); - - canvas.style['-webkit-touch-callout'] = value; - canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)'; - - return canvas; -}; - -module.exports = UserSelect; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @function Phaser.Display.Canvas.UserSelect + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The canvas element to have the style applied to. + * @param {string} [value='none'] - The touch callout value to set on the canvas. Set to `none` to disable touch callouts. + * + * @return {HTMLCanvasElement} The canvas element. + */ +var UserSelect = function (canvas, value) +{ + if (value === undefined) { value = 'none'; } + + var vendors = [ + '-webkit-', + '-khtml-', + '-moz-', + '-ms-', + '' + ]; + + vendors.forEach(function (vendor) + { + canvas.style[vendor + 'user-select'] = value; + }); + + canvas.style['-webkit-touch-callout'] = value; + canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)'; + + return canvas; +}; + +module.exports = UserSelect; diff --git a/src/display/canvas/index.js b/src/display/canvas/index.js index eb5d57096..828f31522 100644 --- a/src/display/canvas/index.js +++ b/src/display/canvas/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Canvas - */ - -module.exports = { - - CanvasInterpolation: require('./CanvasInterpolation'), - CanvasPool: require('./CanvasPool'), - Smoothing: require('./Smoothing'), - TouchAction: require('./TouchAction'), - UserSelect: require('./UserSelect') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Canvas + */ + +module.exports = { + + CanvasInterpolation: require('./CanvasInterpolation'), + CanvasPool: require('./CanvasPool'), + Smoothing: require('./Smoothing'), + TouchAction: require('./TouchAction'), + UserSelect: require('./UserSelect') + +}; diff --git a/src/display/color/Color.js b/src/display/color/Color.js index d9301e8f3..c6c94d43f 100644 --- a/src/display/color/Color.js +++ b/src/display/color/Color.js @@ -1,857 +1,857 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetColor = require('./GetColor'); -var GetColor32 = require('./GetColor32'); -var HSVToRGB = require('./HSVToRGB'); -var RGBToHSV = require('./RGBToHSV'); - -/** - * @namespace Phaser.Display.Color - */ - -/** - * @classdesc - * The Color class holds a single color value and allows for easy modification and reading of it. - * - * @class Color - * @memberof Phaser.Display - * @constructor - * @since 3.0.0 - * - * @param {integer} [red=0] - The red color value. A number between 0 and 255. - * @param {integer} [green=0] - The green color value. A number between 0 and 255. - * @param {integer} [blue=0] - The blue color value. A number between 0 and 255. - * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. - */ -var Color = new Class({ - - initialize: - - function Color (red, green, blue, alpha) - { - if (red === undefined) { red = 0; } - if (green === undefined) { green = 0; } - if (blue === undefined) { blue = 0; } - if (alpha === undefined) { alpha = 255; } - - /** - * The internal red color value. - * - * @name Phaser.Display.Color#r - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.r = 0; - - /** - * The internal green color value. - * - * @name Phaser.Display.Color#g - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.g = 0; - - /** - * The internal blue color value. - * - * @name Phaser.Display.Color#b - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.b = 0; - - /** - * The internal alpha color value. - * - * @name Phaser.Display.Color#a - * @type {number} - * @private - * @default 255 - * @since 3.0.0 - */ - this.a = 255; - - /** - * The hue color value. A number between 0 and 1. - * This is the base color. - * - * @name Phaser.Display.Color#_h - * @type {number} - * @default 0 - * @private - * @since 3.13.0 - */ - this._h = 0; - - /** - * The saturation color value. A number between 0 and 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. - * - * @name Phaser.Display.Color#_s - * @type {number} - * @default 0 - * @private - * @since 3.13.0 - */ - this._s = 0; - - /** - * The lightness color value. A number between 0 and 1. - * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. - * - * @name Phaser.Display.Color#_v - * @type {number} - * @default 0 - * @private - * @since 3.13.0 - */ - this._v = 0; - - /** - * Is this color update locked? - * - * @name Phaser.Display.Color#_locked - * @type {boolean} - * @private - * @since 3.13.0 - */ - this._locked = false; - - /** - * An array containing the calculated color values for WebGL use. - * - * @name Phaser.Display.Color#gl - * @type {number[]} - * @since 3.0.0 - */ - this.gl = [ 0, 0, 0, 1 ]; - - /** - * Pre-calculated internal color value. - * - * @name Phaser.Display.Color#_color - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._color = 0; - - /** - * Pre-calculated internal color32 value. - * - * @name Phaser.Display.Color#_color32 - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._color32 = 0; - - /** - * Pre-calculated internal color rgb string value. - * - * @name Phaser.Display.Color#_rgba - * @type {string} - * @private - * @default '' - * @since 3.0.0 - */ - this._rgba = ''; - - this.setTo(red, green, blue, alpha); - }, - - /** - * Sets this color to be transparent. Sets all values to zero. - * - * @method Phaser.Display.Color#transparent - * @since 3.0.0 - * - * @return {Phaser.Display.Color} This Color object. - */ - transparent: function () - { - this._locked = true; - - this.red = 0; - this.green = 0; - this.blue = 0; - this.alpha = 0; - - this._locked = false; - - return this.update(true); - }, - - /** - * Sets the color of this Color component. - * - * @method Phaser.Display.Color#setTo - * @since 3.0.0 - * - * @param {integer} red - The red color value. A number between 0 and 255. - * @param {integer} green - The green color value. A number between 0 and 255. - * @param {integer} blue - The blue color value. A number between 0 and 255. - * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. - * @param {boolean} [updateHSV=true] - Update the HSV values after setting the RGB values? - * - * @return {Phaser.Display.Color} This Color object. - */ - setTo: function (red, green, blue, alpha, updateHSV) - { - if (alpha === undefined) { alpha = 255; } - if (updateHSV === undefined) { updateHSV = true; } - - this._locked = true; - - this.red = red; - this.green = green; - this.blue = blue; - this.alpha = alpha; - - this._locked = false; - - return this.update(updateHSV); - }, - - /** - * Sets the red, green, blue and alpha GL values of this Color component. - * - * @method Phaser.Display.Color#setGLTo - * @since 3.0.0 - * - * @param {number} red - The red color value. A number between 0 and 1. - * @param {number} green - The green color value. A number between 0 and 1. - * @param {number} blue - The blue color value. A number between 0 and 1. - * @param {number} [alpha=1] - The alpha value. A number between 0 and 1. - * - * @return {Phaser.Display.Color} This Color object. - */ - setGLTo: function (red, green, blue, alpha) - { - if (alpha === undefined) { alpha = 1; } - - this._locked = true; - - this.redGL = red; - this.greenGL = green; - this.blueGL = blue; - this.alphaGL = alpha; - - this._locked = false; - - return this.update(true); - }, - - /** - * 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. - */ - setFromRGB: function (color) - { - this._locked = true; - - this.red = color.r; - this.green = color.g; - this.blue = color.b; - - if (color.hasOwnProperty('a')) - { - this.alpha = color.a; - } - - this._locked = false; - - return this.update(true); - }, - - /** - * Sets the color based on the hue, saturation and lightness values 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. - */ - setFromHSV: function (h, s, v) - { - return HSVToRGB(h, s, v, this); - }, - - /** - * Updates the internal cache values. - * - * @method Phaser.Display.Color#update - * @private - * @since 3.0.0 - * - * @return {Phaser.Display.Color} This Color object. - */ - update: function (updateHSV) - { - if (updateHSV === undefined) { updateHSV = false; } - - if (this._locked) - { - return this; - } - - var r = this.r; - var g = this.g; - var b = this.b; - var a = this.a; - - this._color = GetColor(r, g, b); - this._color32 = GetColor32(r, g, b, a); - this._rgba = 'rgba(' + r + ',' + g + ',' + b + ',' + (a / 255) + ')'; - - if (updateHSV) - { - RGBToHSV(r, g, b, this); - } - - return this; - }, - - /** - * Updates the internal hsv cache values. - * - * @method Phaser.Display.Color#updateHSV - * @private - * @since 3.13.0 - * - * @return {Phaser.Display.Color} This Color object. - */ - updateHSV: function () - { - var r = this.r; - var g = this.g; - var b = this.b; - - RGBToHSV(r, g, b, this); - - return this; - }, - - /** - * Returns a new Color component using the values from this one. - * - * @method Phaser.Display.Color#clone - * @since 3.0.0 - * - * @return {Phaser.Display.Color} A new Color object. - */ - clone: function () - { - return new Color(this.r, this.g, this.b, this.a); - }, - - /** - * Sets this Color object to be grayscaled based on the shade value given. - * - * @method Phaser.Display.Color#gray - * @since 3.13.0 - * - * @param {integer} shade - A value between 0 and 255. - * - * @return {Phaser.Display.Color} This Color object. - */ - gray: function (shade) - { - return this.setTo(shade, shade, shade); - }, - - /** - * Sets this Color object to be a random color between the `min` and `max` values given. - * - * @method Phaser.Display.Color#random - * @since 3.13.0 - * - * @param {integer} [min=0] - The minimum random color value. Between 0 and 255. - * @param {integer} [max=255] - The maximum random color value. Between 0 and 255. - * - * @return {Phaser.Display.Color} This Color object. - */ - random: function (min, max) - { - if (min === undefined) { min = 0; } - if (max === undefined) { max = 255; } - - var r = Math.floor(min + Math.random() * (max - min)); - var g = Math.floor(min + Math.random() * (max - min)); - var b = Math.floor(min + Math.random() * (max - min)); - - return this.setTo(r, g, b); - }, - - /** - * Sets this Color object to be a random grayscale color between the `min` and `max` values given. - * - * @method Phaser.Display.Color#randomGray - * @since 3.13.0 - * - * @param {integer} [min=0] - The minimum random color value. Between 0 and 255. - * @param {integer} [max=255] - The maximum random color value. Between 0 and 255. - * - * @return {Phaser.Display.Color} This Color object. - */ - randomGray: function (min, max) - { - if (min === undefined) { min = 0; } - if (max === undefined) { max = 255; } - - var s = Math.floor(min + Math.random() * (max - min)); - - return this.setTo(s, s, s); - }, - - /** - * Increase the saturation of this Color by the percentage amount given. - * The saturation is the amount of the base color in the hue. - * - * @method Phaser.Display.Color#saturate - * @since 3.13.0 - * - * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. - * - * @return {Phaser.Display.Color} This Color object. - */ - saturate: function (amount) - { - this.s += amount / 100; - - return this; - }, - - /** - * Decrease the saturation of this Color by the percentage amount given. - * The saturation is the amount of the base color in the hue. - * - * @method Phaser.Display.Color#desaturate - * @since 3.13.0 - * - * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. - * - * @return {Phaser.Display.Color} This Color object. - */ - desaturate: function (amount) - { - this.s -= amount / 100; - - return this; - }, - - /** - * Increase the lightness of this Color by the percentage amount given. - * - * @method Phaser.Display.Color#lighten - * @since 3.13.0 - * - * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. - * - * @return {Phaser.Display.Color} This Color object. - */ - lighten: function (amount) - { - this.v += amount / 100; - - return this; - }, - - /** - * Decrease the lightness of this Color by the percentage amount given. - * - * @method Phaser.Display.Color#darken - * @since 3.13.0 - * - * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. - * - * @return {Phaser.Display.Color} This Color object. - */ - darken: function (amount) - { - this.v -= amount / 100; - - return this; - }, - - /** - * Brighten this Color by the percentage amount given. - * - * @method Phaser.Display.Color#brighten - * @since 3.13.0 - * - * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. - * - * @return {Phaser.Display.Color} This Color object. - */ - brighten: function (amount) - { - var r = this.r; - var g = this.g; - var b = this.b; - - r = Math.max(0, Math.min(255, r - Math.round(255 * - (amount / 100)))); - g = Math.max(0, Math.min(255, g - Math.round(255 * - (amount / 100)))); - b = Math.max(0, Math.min(255, b - Math.round(255 * - (amount / 100)))); - - return this.setTo(r, g, b); - }, - - /** - * The color of this Color component, not including the alpha channel. - * - * @name Phaser.Display.Color#color - * @type {number} - * @readonly - * @since 3.0.0 - */ - color: { - - get: function () - { - return this._color; - } - - }, - - /** - * The color of this Color component, including the alpha channel. - * - * @name Phaser.Display.Color#color32 - * @type {number} - * @readonly - * @since 3.0.0 - */ - color32: { - - get: function () - { - return this._color32; - } - - }, - - /** - * The color of this Color component as a string which can be used in CSS color values. - * - * @name Phaser.Display.Color#rgba - * @type {string} - * @readonly - * @since 3.0.0 - */ - rgba: { - - get: function () - { - return this._rgba; - } - - }, - - /** - * The red color value, normalized to the range 0 to 1. - * - * @name Phaser.Display.Color#redGL - * @type {number} - * @since 3.0.0 - */ - redGL: { - - get: function () - { - return this.gl[0]; - }, - - set: function (value) - { - this.gl[0] = Math.min(Math.abs(value), 1); - - this.r = Math.floor(this.gl[0] * 255); - - this.update(true); - } - - }, - - /** - * The green color value, normalized to the range 0 to 1. - * - * @name Phaser.Display.Color#greenGL - * @type {number} - * @since 3.0.0 - */ - greenGL: { - - get: function () - { - return this.gl[1]; - }, - - set: function (value) - { - this.gl[1] = Math.min(Math.abs(value), 1); - - this.g = Math.floor(this.gl[1] * 255); - - this.update(true); - } - - }, - - /** - * The blue color value, normalized to the range 0 to 1. - * - * @name Phaser.Display.Color#blueGL - * @type {number} - * @since 3.0.0 - */ - blueGL: { - - get: function () - { - return this.gl[2]; - }, - - set: function (value) - { - this.gl[2] = Math.min(Math.abs(value), 1); - - this.b = Math.floor(this.gl[2] * 255); - - this.update(true); - } - - }, - - /** - * The alpha color value, normalized to the range 0 to 1. - * - * @name Phaser.Display.Color#alphaGL - * @type {number} - * @since 3.0.0 - */ - alphaGL: { - - get: function () - { - return this.gl[3]; - }, - - set: function (value) - { - this.gl[3] = Math.min(Math.abs(value), 1); - - this.a = Math.floor(this.gl[3] * 255); - - this.update(); - } - - }, - - /** - * The red color value, normalized to the range 0 to 255. - * - * @name Phaser.Display.Color#red - * @type {number} - * @since 3.0.0 - */ - red: { - - get: function () - { - return this.r; - }, - - set: function (value) - { - value = Math.floor(Math.abs(value)); - - this.r = Math.min(value, 255); - - this.gl[0] = value / 255; - - this.update(true); - } - - }, - - /** - * The green color value, normalized to the range 0 to 255. - * - * @name Phaser.Display.Color#green - * @type {number} - * @since 3.0.0 - */ - green: { - - get: function () - { - return this.g; - }, - - set: function (value) - { - value = Math.floor(Math.abs(value)); - - this.g = Math.min(value, 255); - - this.gl[1] = value / 255; - - this.update(true); - } - - }, - - /** - * The blue color value, normalized to the range 0 to 255. - * - * @name Phaser.Display.Color#blue - * @type {number} - * @since 3.0.0 - */ - blue: { - - get: function () - { - return this.b; - }, - - set: function (value) - { - value = Math.floor(Math.abs(value)); - - this.b = Math.min(value, 255); - - this.gl[2] = value / 255; - - this.update(true); - } - - }, - - /** - * The alpha color value, normalized to the range 0 to 255. - * - * @name Phaser.Display.Color#alpha - * @type {number} - * @since 3.0.0 - */ - alpha: { - - get: function () - { - return this.a; - }, - - set: function (value) - { - value = Math.floor(Math.abs(value)); - - this.a = Math.min(value, 255); - - this.gl[3] = value / 255; - - this.update(); - } - - }, - - /** - * The hue color value. A number between 0 and 1. - * This is the base color. - * - * @name Phaser.Display.Color#h - * @type {number} - * @since 3.13.0 - */ - h: { - - get: function () - { - return this._h; - }, - - set: function (value) - { - this._h = value; - - HSVToRGB(value, this._s, this._v, this); - } - - }, - - /** - * The saturation color value. A number between 0 and 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. - * - * @name Phaser.Display.Color#s - * @type {number} - * @since 3.13.0 - */ - s: { - - get: function () - { - return this._s; - }, - - set: function (value) - { - this._s = value; - - HSVToRGB(this._h, value, this._v, this); - } - - }, - - /** - * The lightness color value. A number between 0 and 1. - * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. - * - * @name Phaser.Display.Color#v - * @type {number} - * @since 3.13.0 - */ - v: { - - get: function () - { - return this._v; - }, - - set: function (value) - { - this._v = value; - - HSVToRGB(this._h, this._s, value, this); - } - - } - -}); - -module.exports = Color; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetColor = require('./GetColor'); +var GetColor32 = require('./GetColor32'); +var HSVToRGB = require('./HSVToRGB'); +var RGBToHSV = require('./RGBToHSV'); + +/** + * @namespace Phaser.Display.Color + */ + +/** + * @classdesc + * The Color class holds a single color value and allows for easy modification and reading of it. + * + * @class Color + * @memberof Phaser.Display + * @constructor + * @since 3.0.0 + * + * @param {integer} [red=0] - The red color value. A number between 0 and 255. + * @param {integer} [green=0] - The green color value. A number between 0 and 255. + * @param {integer} [blue=0] - The blue color value. A number between 0 and 255. + * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. + */ +var Color = new Class({ + + initialize: + + function Color (red, green, blue, alpha) + { + if (red === undefined) { red = 0; } + if (green === undefined) { green = 0; } + if (blue === undefined) { blue = 0; } + if (alpha === undefined) { alpha = 255; } + + /** + * The internal red color value. + * + * @name Phaser.Display.Color#r + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.r = 0; + + /** + * The internal green color value. + * + * @name Phaser.Display.Color#g + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.g = 0; + + /** + * The internal blue color value. + * + * @name Phaser.Display.Color#b + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.b = 0; + + /** + * The internal alpha color value. + * + * @name Phaser.Display.Color#a + * @type {number} + * @private + * @default 255 + * @since 3.0.0 + */ + this.a = 255; + + /** + * The hue color value. A number between 0 and 1. + * This is the base color. + * + * @name Phaser.Display.Color#_h + * @type {number} + * @default 0 + * @private + * @since 3.13.0 + */ + this._h = 0; + + /** + * The saturation color value. A number between 0 and 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. + * + * @name Phaser.Display.Color#_s + * @type {number} + * @default 0 + * @private + * @since 3.13.0 + */ + this._s = 0; + + /** + * The lightness color value. A number between 0 and 1. + * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. + * + * @name Phaser.Display.Color#_v + * @type {number} + * @default 0 + * @private + * @since 3.13.0 + */ + this._v = 0; + + /** + * Is this color update locked? + * + * @name Phaser.Display.Color#_locked + * @type {boolean} + * @private + * @since 3.13.0 + */ + this._locked = false; + + /** + * An array containing the calculated color values for WebGL use. + * + * @name Phaser.Display.Color#gl + * @type {number[]} + * @since 3.0.0 + */ + this.gl = [ 0, 0, 0, 1 ]; + + /** + * Pre-calculated internal color value. + * + * @name Phaser.Display.Color#_color + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._color = 0; + + /** + * Pre-calculated internal color32 value. + * + * @name Phaser.Display.Color#_color32 + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._color32 = 0; + + /** + * Pre-calculated internal color rgb string value. + * + * @name Phaser.Display.Color#_rgba + * @type {string} + * @private + * @default '' + * @since 3.0.0 + */ + this._rgba = ''; + + this.setTo(red, green, blue, alpha); + }, + + /** + * Sets this color to be transparent. Sets all values to zero. + * + * @method Phaser.Display.Color#transparent + * @since 3.0.0 + * + * @return {Phaser.Display.Color} This Color object. + */ + transparent: function () + { + this._locked = true; + + this.red = 0; + this.green = 0; + this.blue = 0; + this.alpha = 0; + + this._locked = false; + + return this.update(true); + }, + + /** + * Sets the color of this Color component. + * + * @method Phaser.Display.Color#setTo + * @since 3.0.0 + * + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. + * @param {boolean} [updateHSV=true] - Update the HSV values after setting the RGB values? + * + * @return {Phaser.Display.Color} This Color object. + */ + setTo: function (red, green, blue, alpha, updateHSV) + { + if (alpha === undefined) { alpha = 255; } + if (updateHSV === undefined) { updateHSV = true; } + + this._locked = true; + + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + + this._locked = false; + + return this.update(updateHSV); + }, + + /** + * Sets the red, green, blue and alpha GL values of this Color component. + * + * @method Phaser.Display.Color#setGLTo + * @since 3.0.0 + * + * @param {number} red - The red color value. A number between 0 and 1. + * @param {number} green - The green color value. A number between 0 and 1. + * @param {number} blue - The blue color value. A number between 0 and 1. + * @param {number} [alpha=1] - The alpha value. A number between 0 and 1. + * + * @return {Phaser.Display.Color} This Color object. + */ + setGLTo: function (red, green, blue, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this._locked = true; + + this.redGL = red; + this.greenGL = green; + this.blueGL = blue; + this.alphaGL = alpha; + + this._locked = false; + + return this.update(true); + }, + + /** + * 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. + */ + setFromRGB: function (color) + { + this._locked = true; + + this.red = color.r; + this.green = color.g; + this.blue = color.b; + + if (color.hasOwnProperty('a')) + { + this.alpha = color.a; + } + + this._locked = false; + + return this.update(true); + }, + + /** + * Sets the color based on the hue, saturation and lightness values 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. + */ + setFromHSV: function (h, s, v) + { + return HSVToRGB(h, s, v, this); + }, + + /** + * Updates the internal cache values. + * + * @method Phaser.Display.Color#update + * @private + * @since 3.0.0 + * + * @return {Phaser.Display.Color} This Color object. + */ + update: function (updateHSV) + { + if (updateHSV === undefined) { updateHSV = false; } + + if (this._locked) + { + return this; + } + + var r = this.r; + var g = this.g; + var b = this.b; + var a = this.a; + + this._color = GetColor(r, g, b); + this._color32 = GetColor32(r, g, b, a); + this._rgba = 'rgba(' + r + ',' + g + ',' + b + ',' + (a / 255) + ')'; + + if (updateHSV) + { + RGBToHSV(r, g, b, this); + } + + return this; + }, + + /** + * Updates the internal hsv cache values. + * + * @method Phaser.Display.Color#updateHSV + * @private + * @since 3.13.0 + * + * @return {Phaser.Display.Color} This Color object. + */ + updateHSV: function () + { + var r = this.r; + var g = this.g; + var b = this.b; + + RGBToHSV(r, g, b, this); + + return this; + }, + + /** + * Returns a new Color component using the values from this one. + * + * @method Phaser.Display.Color#clone + * @since 3.0.0 + * + * @return {Phaser.Display.Color} A new Color object. + */ + clone: function () + { + return new Color(this.r, this.g, this.b, this.a); + }, + + /** + * Sets this Color object to be grayscaled based on the shade value given. + * + * @method Phaser.Display.Color#gray + * @since 3.13.0 + * + * @param {integer} shade - A value between 0 and 255. + * + * @return {Phaser.Display.Color} This Color object. + */ + gray: function (shade) + { + return this.setTo(shade, shade, shade); + }, + + /** + * Sets this Color object to be a random color between the `min` and `max` values given. + * + * @method Phaser.Display.Color#random + * @since 3.13.0 + * + * @param {integer} [min=0] - The minimum random color value. Between 0 and 255. + * @param {integer} [max=255] - The maximum random color value. Between 0 and 255. + * + * @return {Phaser.Display.Color} This Color object. + */ + random: function (min, max) + { + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + + var r = Math.floor(min + Math.random() * (max - min)); + var g = Math.floor(min + Math.random() * (max - min)); + var b = Math.floor(min + Math.random() * (max - min)); + + return this.setTo(r, g, b); + }, + + /** + * Sets this Color object to be a random grayscale color between the `min` and `max` values given. + * + * @method Phaser.Display.Color#randomGray + * @since 3.13.0 + * + * @param {integer} [min=0] - The minimum random color value. Between 0 and 255. + * @param {integer} [max=255] - The maximum random color value. Between 0 and 255. + * + * @return {Phaser.Display.Color} This Color object. + */ + randomGray: function (min, max) + { + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + + var s = Math.floor(min + Math.random() * (max - min)); + + return this.setTo(s, s, s); + }, + + /** + * Increase the saturation of this Color by the percentage amount given. + * The saturation is the amount of the base color in the hue. + * + * @method Phaser.Display.Color#saturate + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + saturate: function (amount) + { + this.s += amount / 100; + + return this; + }, + + /** + * Decrease the saturation of this Color by the percentage amount given. + * The saturation is the amount of the base color in the hue. + * + * @method Phaser.Display.Color#desaturate + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + desaturate: function (amount) + { + this.s -= amount / 100; + + return this; + }, + + /** + * Increase the lightness of this Color by the percentage amount given. + * + * @method Phaser.Display.Color#lighten + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + lighten: function (amount) + { + this.v += amount / 100; + + return this; + }, + + /** + * Decrease the lightness of this Color by the percentage amount given. + * + * @method Phaser.Display.Color#darken + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + darken: function (amount) + { + this.v -= amount / 100; + + return this; + }, + + /** + * Brighten this Color by the percentage amount given. + * + * @method Phaser.Display.Color#brighten + * @since 3.13.0 + * + * @param {integer} amount - The percentage amount to change this color by. A value between 0 and 100. + * + * @return {Phaser.Display.Color} This Color object. + */ + brighten: function (amount) + { + var r = this.r; + var g = this.g; + var b = this.b; + + r = Math.max(0, Math.min(255, r - Math.round(255 * - (amount / 100)))); + g = Math.max(0, Math.min(255, g - Math.round(255 * - (amount / 100)))); + b = Math.max(0, Math.min(255, b - Math.round(255 * - (amount / 100)))); + + return this.setTo(r, g, b); + }, + + /** + * The color of this Color component, not including the alpha channel. + * + * @name Phaser.Display.Color#color + * @type {number} + * @readonly + * @since 3.0.0 + */ + color: { + + get: function () + { + return this._color; + } + + }, + + /** + * The color of this Color component, including the alpha channel. + * + * @name Phaser.Display.Color#color32 + * @type {number} + * @readonly + * @since 3.0.0 + */ + color32: { + + get: function () + { + return this._color32; + } + + }, + + /** + * The color of this Color component as a string which can be used in CSS color values. + * + * @name Phaser.Display.Color#rgba + * @type {string} + * @readonly + * @since 3.0.0 + */ + rgba: { + + get: function () + { + return this._rgba; + } + + }, + + /** + * The red color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#redGL + * @type {number} + * @since 3.0.0 + */ + redGL: { + + get: function () + { + return this.gl[0]; + }, + + set: function (value) + { + this.gl[0] = Math.min(Math.abs(value), 1); + + this.r = Math.floor(this.gl[0] * 255); + + this.update(true); + } + + }, + + /** + * The green color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#greenGL + * @type {number} + * @since 3.0.0 + */ + greenGL: { + + get: function () + { + return this.gl[1]; + }, + + set: function (value) + { + this.gl[1] = Math.min(Math.abs(value), 1); + + this.g = Math.floor(this.gl[1] * 255); + + this.update(true); + } + + }, + + /** + * The blue color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#blueGL + * @type {number} + * @since 3.0.0 + */ + blueGL: { + + get: function () + { + return this.gl[2]; + }, + + set: function (value) + { + this.gl[2] = Math.min(Math.abs(value), 1); + + this.b = Math.floor(this.gl[2] * 255); + + this.update(true); + } + + }, + + /** + * The alpha color value, normalized to the range 0 to 1. + * + * @name Phaser.Display.Color#alphaGL + * @type {number} + * @since 3.0.0 + */ + alphaGL: { + + get: function () + { + return this.gl[3]; + }, + + set: function (value) + { + this.gl[3] = Math.min(Math.abs(value), 1); + + this.a = Math.floor(this.gl[3] * 255); + + this.update(); + } + + }, + + /** + * The red color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#red + * @type {number} + * @since 3.0.0 + */ + red: { + + get: function () + { + return this.r; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.r = Math.min(value, 255); + + this.gl[0] = value / 255; + + this.update(true); + } + + }, + + /** + * The green color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#green + * @type {number} + * @since 3.0.0 + */ + green: { + + get: function () + { + return this.g; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.g = Math.min(value, 255); + + this.gl[1] = value / 255; + + this.update(true); + } + + }, + + /** + * The blue color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#blue + * @type {number} + * @since 3.0.0 + */ + blue: { + + get: function () + { + return this.b; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.b = Math.min(value, 255); + + this.gl[2] = value / 255; + + this.update(true); + } + + }, + + /** + * The alpha color value, normalized to the range 0 to 255. + * + * @name Phaser.Display.Color#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this.a; + }, + + set: function (value) + { + value = Math.floor(Math.abs(value)); + + this.a = Math.min(value, 255); + + this.gl[3] = value / 255; + + this.update(); + } + + }, + + /** + * The hue color value. A number between 0 and 1. + * This is the base color. + * + * @name Phaser.Display.Color#h + * @type {number} + * @since 3.13.0 + */ + h: { + + get: function () + { + return this._h; + }, + + set: function (value) + { + this._h = value; + + HSVToRGB(value, this._s, this._v, this); + } + + }, + + /** + * The saturation color value. A number between 0 and 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. + * + * @name Phaser.Display.Color#s + * @type {number} + * @since 3.13.0 + */ + s: { + + get: function () + { + return this._s; + }, + + set: function (value) + { + this._s = value; + + HSVToRGB(this._h, value, this._v, this); + } + + }, + + /** + * The lightness color value. A number between 0 and 1. + * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. + * + * @name Phaser.Display.Color#v + * @type {number} + * @since 3.13.0 + */ + v: { + + get: function () + { + return this._v; + }, + + set: function (value) + { + this._v = value; + + HSVToRGB(this._h, this._s, value, this); + } + + } + +}); + +module.exports = Color; diff --git a/src/display/color/ColorToRGBA.js b/src/display/color/ColorToRGBA.js index dfc3998f8..23210c9a6 100644 --- a/src/display/color/ColorToRGBA.js +++ b/src/display/color/ColorToRGBA.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Converts the given color value into an Object containing r,g,b and a properties. - * - * @function Phaser.Display.Color.ColorToRGBA - * @since 3.0.0 - * - * @param {number} color - A color value, optionally including the alpha value. - * - * @return {Phaser.Types.Display.ColorObject} An object containing the parsed color values. - */ -var ColorToRGBA = function (color) -{ - var output = { - r: color >> 16 & 0xFF, - g: color >> 8 & 0xFF, - b: color & 0xFF, - a: 255 - }; - - if (color > 16777215) - { - output.a = color >>> 24; - } - - return output; -}; - -module.exports = ColorToRGBA; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts the given color value into an Object containing r,g,b and a properties. + * + * @function Phaser.Display.Color.ColorToRGBA + * @since 3.0.0 + * + * @param {number} color - A color value, optionally including the alpha value. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the parsed color values. + */ +var ColorToRGBA = function (color) +{ + var output = { + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF, + a: 255 + }; + + if (color > 16777215) + { + output.a = color >>> 24; + } + + return output; +}; + +module.exports = ColorToRGBA; diff --git a/src/display/color/ComponentToHex.js b/src/display/color/ComponentToHex.js index 7081c9c7f..6498304f3 100644 --- a/src/display/color/ComponentToHex.js +++ b/src/display/color/ComponentToHex.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns a string containing a hex representation of the given color component. - * - * @function Phaser.Display.Color.ComponentToHex - * @since 3.0.0 - * - * @param {integer} color - The color channel to get the hex value for, must be a value between 0 and 255. - * - * @return {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. - */ -var ComponentToHex = function (color) -{ - var hex = color.toString(16); - - return (hex.length === 1) ? '0' + hex : hex; -}; - -module.exports = ComponentToHex; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns a string containing a hex representation of the given color component. + * + * @function Phaser.Display.Color.ComponentToHex + * @since 3.0.0 + * + * @param {integer} color - The color channel to get the hex value for, must be a value between 0 and 255. + * + * @return {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ +var ComponentToHex = function (color) +{ + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; +}; + +module.exports = ComponentToHex; diff --git a/src/display/color/GetColor.js b/src/display/color/GetColor.js index e4ec84048..2bec36d5d 100644 --- a/src/display/color/GetColor.js +++ b/src/display/color/GetColor.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Given 3 separate color values this will return an integer representation of it. - * - * @function Phaser.Display.Color.GetColor - * @since 3.0.0 - * - * @param {integer} red - The red color value. A number between 0 and 255. - * @param {integer} green - The green color value. A number between 0 and 255. - * @param {integer} blue - The blue color value. A number between 0 and 255. - * - * @return {number} The combined color value. - */ -var GetColor = function (red, green, blue) -{ - return red << 16 | green << 8 | blue; -}; - -module.exports = GetColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Given 3 separate color values this will return an integer representation of it. + * + * @function Phaser.Display.Color.GetColor + * @since 3.0.0 + * + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * + * @return {number} The combined color value. + */ +var GetColor = function (red, green, blue) +{ + return red << 16 | green << 8 | blue; +}; + +module.exports = GetColor; diff --git a/src/display/color/GetColor32.js b/src/display/color/GetColor32.js index a7a9db0a2..e88e38540 100644 --- a/src/display/color/GetColor32.js +++ b/src/display/color/GetColor32.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Given an alpha and 3 color values this will return an integer representation of it. - * - * @function Phaser.Display.Color.GetColor32 - * @since 3.0.0 - * - * @param {integer} red - The red color value. A number between 0 and 255. - * @param {integer} green - The green color value. A number between 0 and 255. - * @param {integer} blue - The blue color value. A number between 0 and 255. - * @param {integer} alpha - The alpha color value. A number between 0 and 255. - * - * @return {number} The combined color value. - */ -var GetColor32 = function (red, green, blue, alpha) -{ - return alpha << 24 | red << 16 | green << 8 | blue; -}; - -module.exports = GetColor32; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @function Phaser.Display.Color.GetColor32 + * @since 3.0.0 + * + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * @param {integer} alpha - The alpha color value. A number between 0 and 255. + * + * @return {number} The combined color value. + */ +var GetColor32 = function (red, green, blue, alpha) +{ + return alpha << 24 | red << 16 | green << 8 | blue; +}; + +module.exports = GetColor32; diff --git a/src/display/color/HSLToColor.js b/src/display/color/HSLToColor.js index 1e64591ce..7809c2ccf 100644 --- a/src/display/color/HSLToColor.js +++ b/src/display/color/HSLToColor.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Color = require('./Color'); -var HueToComponent = require('./HueToComponent'); - -/** - * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. - * - * @function Phaser.Display.Color.HSLToColor - * @since 3.0.0 - * - * @param {number} h - The hue value in the range 0 to 1. - * @param {number} s - The saturation value in the range 0 to 1. - * @param {number} l - The lightness value in the range 0 to 1. - * - * @return {Phaser.Display.Color} A Color object created from the results of the h, s and l values. - */ -var HSLToColor = function (h, s, l) -{ - // achromatic by default - var r = l; - var g = l; - var b = l; - - if (s !== 0) - { - var q = (l < 0.5) ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - - r = HueToComponent(p, q, h + 1 / 3); - g = HueToComponent(p, q, h); - b = HueToComponent(p, q, h - 1 / 3); - } - - var color = new Color(); - - return color.setGLTo(r, g, b, 1); -}; - -module.exports = HSLToColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = require('./Color'); +var HueToComponent = require('./HueToComponent'); + +/** + * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. + * + * @function Phaser.Display.Color.HSLToColor + * @since 3.0.0 + * + * @param {number} h - The hue value in the range 0 to 1. + * @param {number} s - The saturation value in the range 0 to 1. + * @param {number} l - The lightness value in the range 0 to 1. + * + * @return {Phaser.Display.Color} A Color object created from the results of the h, s and l values. + */ +var HSLToColor = function (h, s, l) +{ + // achromatic by default + var r = l; + var g = l; + var b = l; + + if (s !== 0) + { + var q = (l < 0.5) ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + + r = HueToComponent(p, q, h + 1 / 3); + g = HueToComponent(p, q, h); + b = HueToComponent(p, q, h - 1 / 3); + } + + var color = new Color(); + + return color.setGLTo(r, g, b, 1); +}; + +module.exports = HSLToColor; diff --git a/src/display/color/HSVColorWheel.js b/src/display/color/HSVColorWheel.js index ca00c82b7..4c0f57116 100644 --- a/src/display/color/HSVColorWheel.js +++ b/src/display/color/HSVColorWheel.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var HSVToRGB = require('./HSVToRGB'); - -/** - * Get HSV color wheel values in an array which will be 360 elements in size. - * - * @function Phaser.Display.Color.HSVColorWheel - * @since 3.0.0 - * - * @param {number} [s=1] - The saturation, in the range 0 - 1. - * @param {number} [v=1] - The value, in the range 0 - 1. - * - * @return {Phaser.Types.Display.ColorObject[]} An array containing 360 elements, where each contains a single numeric value corresponding to the color at that point in the HSV color wheel. - */ -var HSVColorWheel = function (s, v) -{ - if (s === undefined) { s = 1; } - if (v === undefined) { v = 1; } - - var colors = []; - - for (var c = 0; c <= 359; c++) - { - colors.push(HSVToRGB(c / 359, s, v)); - } - - return colors; -}; - -module.exports = HSVColorWheel; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HSVToRGB = require('./HSVToRGB'); + +/** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @function Phaser.Display.Color.HSVColorWheel + * @since 3.0.0 + * + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * + * @return {Phaser.Types.Display.ColorObject[]} An array containing 360 elements, where each contains a single numeric value corresponding to the color at that point in the HSV color wheel. + */ +var HSVColorWheel = function (s, v) +{ + if (s === undefined) { s = 1; } + if (v === undefined) { v = 1; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(HSVToRGB(c / 359, s, v)); + } + + return colors; +}; + +module.exports = HSVColorWheel; diff --git a/src/display/color/HSVToRGB.js b/src/display/color/HSVToRGB.js index 702864ef6..9eeaaf7ec 100644 --- a/src/display/color/HSVToRGB.js +++ b/src/display/color/HSVToRGB.js @@ -1,95 +1,95 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetColor = require('./GetColor'); - -/** - * Converts an HSV (hue, saturation and value) color value to RGB. - * Conversion formula from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes HSV values are contained in the set [0, 1]. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @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 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. - * @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. - */ -var HSVToRGB = function (h, s, v, out) -{ - if (s === undefined) { s = 1; } - if (v === undefined) { v = 1; } - - var i = Math.floor(h * 6); - var f = h * 6 - i; - - var p = Math.floor((v * (1 - s)) * 255); - var q = Math.floor((v * (1 - f * s)) * 255); - var t = Math.floor((v * (1 - (1 - f) * s)) * 255); - - v = Math.floor(v *= 255); - - var r = v; - var g = v; - var b = v; - - var c = i % 6; - - if (c === 0) - { - g = t; - b = p; - } - else if (c === 1) - { - r = q; - b = p; - } - else if (c === 2) - { - r = p; - b = t; - } - else if (c === 3) - { - r = p; - g = q; - } - else if (c === 4) - { - r = t; - g = p; - } - else if (c === 5) - { - g = p; - b = q; - } - - if (!out) - { - return { r: r, g: g, b: b, color: GetColor(r, g, b) }; - } - else if (out.setTo) - { - return out.setTo(r, g, b, out.alpha, false); - } - else - { - out.r = r; - out.g = g; - out.b = b; - out.color = GetColor(r, g, b); - - return out; - } -}; - -module.exports = HSVToRGB; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetColor = require('./GetColor'); + +/** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion formula from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @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 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. + * @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. + */ +var HSVToRGB = function (h, s, v, out) +{ + if (s === undefined) { s = 1; } + if (v === undefined) { v = 1; } + + var i = Math.floor(h * 6); + var f = h * 6 - i; + + var p = Math.floor((v * (1 - s)) * 255); + var q = Math.floor((v * (1 - f * s)) * 255); + var t = Math.floor((v * (1 - (1 - f) * s)) * 255); + + v = Math.floor(v *= 255); + + var r = v; + var g = v; + var b = v; + + var c = i % 6; + + if (c === 0) + { + g = t; + b = p; + } + else if (c === 1) + { + r = q; + b = p; + } + else if (c === 2) + { + r = p; + b = t; + } + else if (c === 3) + { + r = p; + g = q; + } + else if (c === 4) + { + r = t; + g = p; + } + else if (c === 5) + { + g = p; + b = q; + } + + if (!out) + { + return { r: r, g: g, b: b, color: GetColor(r, g, b) }; + } + else if (out.setTo) + { + return out.setTo(r, g, b, out.alpha, false); + } + else + { + out.r = r; + out.g = g; + out.b = b; + out.color = GetColor(r, g, b); + + return out; + } +}; + +module.exports = HSVToRGB; diff --git a/src/display/color/HexStringToColor.js b/src/display/color/HexStringToColor.js index 0cabced5b..f02b2bbaf 100644 --- a/src/display/color/HexStringToColor.js +++ b/src/display/color/HexStringToColor.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Color = require('./Color'); - -/** - * Converts a hex string into a Phaser Color object. - * - * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. - * - * An alpha channel is _not_ supported. - * - * @function Phaser.Display.Color.HexStringToColor - * @since 3.0.0 - * - * @param {string} hex - The hex color value to convert, such as `#0033ff` or the short-hand format: `#03f`. - * - * @return {Phaser.Display.Color} A Color object populated by the values of the given string. - */ -var HexStringToColor = function (hex) -{ - var color = new Color(); - - // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") - hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function (m, r, g, b) - { - return r + r + g + g + b + b; - }); - - var result = (/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i).exec(hex); - - if (result) - { - var r = parseInt(result[1], 16); - var g = parseInt(result[2], 16); - var b = parseInt(result[3], 16); - - color.setTo(r, g, b); - } - - return color; -}; - -module.exports = HexStringToColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = require('./Color'); + +/** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @function Phaser.Display.Color.HexStringToColor + * @since 3.0.0 + * + * @param {string} hex - The hex color value to convert, such as `#0033ff` or the short-hand format: `#03f`. + * + * @return {Phaser.Display.Color} A Color object populated by the values of the given string. + */ +var HexStringToColor = function (hex) +{ + var color = new Color(); + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function (m, r, g, b) + { + return r + r + g + g + b + b; + }); + + var result = (/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i).exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + color.setTo(r, g, b); + } + + return color; +}; + +module.exports = HexStringToColor; diff --git a/src/display/color/HueToComponent.js b/src/display/color/HueToComponent.js index 0387429a2..ca81f4721 100644 --- a/src/display/color/HueToComponent.js +++ b/src/display/color/HueToComponent.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Converts a hue to an RGB color. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @function Phaser.Display.Color.HueToComponent - * @since 3.0.0 - * - * @param {number} p - * @param {number} q - * @param {number} t - * - * @return {number} The combined color value. - */ -var HueToComponent = function (p, q, t) -{ - if (t < 0) - { - t += 1; - } - - if (t > 1) - { - t -= 1; - } - - if (t < 1 / 6) - { - return p + (q - p) * 6 * t; - } - - if (t < 1 / 2) - { - return q; - } - - if (t < 2 / 3) - { - return p + (q - p) * (2 / 3 - t) * 6; - } - - return p; -}; - -module.exports = HueToComponent; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @function Phaser.Display.Color.HueToComponent + * @since 3.0.0 + * + * @param {number} p + * @param {number} q + * @param {number} t + * + * @return {number} The combined color value. + */ +var HueToComponent = function (p, q, t) +{ + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; +}; + +module.exports = HueToComponent; diff --git a/src/display/color/IntegerToColor.js b/src/display/color/IntegerToColor.js index 8a51c9fd9..9de5c49f2 100644 --- a/src/display/color/IntegerToColor.js +++ b/src/display/color/IntegerToColor.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Color = require('./Color'); -var IntegerToRGB = require('./IntegerToRGB'); - -/** - * Converts the given color value into an instance of a Color object. - * - * @function Phaser.Display.Color.IntegerToColor - * @since 3.0.0 - * - * @param {integer} input - The color value to convert into a Color object. - * - * @return {Phaser.Display.Color} A Color object. - */ -var IntegerToColor = function (input) -{ - var rgb = IntegerToRGB(input); - - return new Color(rgb.r, rgb.g, rgb.b, rgb.a); -}; - -module.exports = IntegerToColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = require('./Color'); +var IntegerToRGB = require('./IntegerToRGB'); + +/** + * Converts the given color value into an instance of a Color object. + * + * @function Phaser.Display.Color.IntegerToColor + * @since 3.0.0 + * + * @param {integer} input - The color value to convert into a Color object. + * + * @return {Phaser.Display.Color} A Color object. + */ +var IntegerToColor = function (input) +{ + var rgb = IntegerToRGB(input); + + return new Color(rgb.r, rgb.g, rgb.b, rgb.a); +}; + +module.exports = IntegerToColor; diff --git a/src/display/color/IntegerToRGB.js b/src/display/color/IntegerToRGB.js index d6943df8b..acc39d5b1 100644 --- a/src/display/color/IntegerToRGB.js +++ b/src/display/color/IntegerToRGB.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Return the component parts of a color as an Object with the properties alpha, red, green, blue. - * - * Alpha will only be set if it exists in the given color (0xAARRGGBB) - * - * @function Phaser.Display.Color.IntegerToRGB - * @since 3.0.0 - * - * @param {integer} input - The color value to convert into a Color object. - * - * @return {Phaser.Types.Display.ColorObject} An object with the red, green and blue values set in the r, g and b properties. - */ -var IntegerToRGB = function (color) -{ - if (color > 16777215) - { - // The color value has an alpha component - return { - a: color >>> 24, - r: color >> 16 & 0xFF, - g: color >> 8 & 0xFF, - b: color & 0xFF - }; - } - else - { - return { - a: 255, - r: color >> 16 & 0xFF, - g: color >> 8 & 0xFF, - b: color & 0xFF - }; - } -}; - -module.exports = IntegerToRGB; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exists in the given color (0xAARRGGBB) + * + * @function Phaser.Display.Color.IntegerToRGB + * @since 3.0.0 + * + * @param {integer} input - The color value to convert into a Color object. + * + * @return {Phaser.Types.Display.ColorObject} An object with the red, green and blue values set in the r, g and b properties. + */ +var IntegerToRGB = function (color) +{ + if (color > 16777215) + { + // The color value has an alpha component + return { + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } +}; + +module.exports = IntegerToRGB; diff --git a/src/display/color/Interpolate.js b/src/display/color/Interpolate.js index 22b4d6f25..129cb3f6f 100644 --- a/src/display/color/Interpolate.js +++ b/src/display/color/Interpolate.js @@ -1,102 +1,102 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Linear = require('../../math/Linear'); - -/** - * @namespace Phaser.Display.Color.Interpolate - * @memberof Phaser.Display.Color - * @since 3.0.0 - */ - -/** - * Interpolates between the two given color ranges over the length supplied. - * - * @function Phaser.Display.Color.Interpolate.RGBWithRGB - * @memberof Phaser.Display.Color.Interpolate - * @static - * @since 3.0.0 - * - * @param {number} r1 - Red value. - * @param {number} g1 - Blue value. - * @param {number} b1 - Green value. - * @param {number} r2 - Red value. - * @param {number} g2 - Blue value. - * @param {number} b2 - Green value. - * @param {number} [length=100] - Distance to interpolate over. - * @param {number} [index=0] - Index to start from. - * - * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. - */ -var RGBWithRGB = function (r1, g1, b1, r2, g2, b2, length, index) -{ - if (length === undefined) { length = 100; } - if (index === undefined) { index = 0; } - - var t = index / length; - - return { - r: Linear(r1, r2, t), - g: Linear(g1, g2, t), - b: Linear(b1, b2, t) - }; -}; - -/** - * Interpolates between the two given color objects over the length supplied. - * - * @function Phaser.Display.Color.Interpolate.ColorWithColor - * @memberof Phaser.Display.Color.Interpolate - * @static - * @since 3.0.0 - * - * @param {Phaser.Display.Color} color1 - The first Color object. - * @param {Phaser.Display.Color} color2 - The second Color object. - * @param {number} [length=100] - Distance to interpolate over. - * @param {number} [index=0] - Index to start from. - * - * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. - */ -var ColorWithColor = function (color1, color2, length, index) -{ - if (length === undefined) { length = 100; } - if (index === undefined) { index = 0; } - - return RGBWithRGB(color1.r, color1.g, color1.b, color2.r, color2.g, color2.b, length, index); -}; - -/** - * Interpolates between the Color object and color values over the length supplied. - * - * @function Phaser.Display.Color.Interpolate.ColorWithRGB - * @memberof Phaser.Display.Color.Interpolate - * @static - * @since 3.0.0 - * - * @param {Phaser.Display.Color} color1 - The first Color object. - * @param {number} r - Red value. - * @param {number} g - Blue value. - * @param {number} b - Green value. - * @param {number} [length=100] - Distance to interpolate over. - * @param {number} [index=0] - Index to start from. - * - * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. - */ -var ColorWithRGB = function (color, r, g, b, length, index) -{ - if (length === undefined) { length = 100; } - if (index === undefined) { index = 0; } - - return RGBWithRGB(color.r, color.g, color.b, r, g, b, length, index); -}; - -module.exports = { - - RGBWithRGB: RGBWithRGB, - ColorWithRGB: ColorWithRGB, - ColorWithColor: ColorWithColor - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Linear = require('../../math/Linear'); + +/** + * @namespace Phaser.Display.Color.Interpolate + * @memberof Phaser.Display.Color + * @since 3.0.0 + */ + +/** + * Interpolates between the two given color ranges over the length supplied. + * + * @function Phaser.Display.Color.Interpolate.RGBWithRGB + * @memberof Phaser.Display.Color.Interpolate + * @static + * @since 3.0.0 + * + * @param {number} r1 - Red value. + * @param {number} g1 - Blue value. + * @param {number} b1 - Green value. + * @param {number} r2 - Red value. + * @param {number} g2 - Blue value. + * @param {number} b2 - Green value. + * @param {number} [length=100] - Distance to interpolate over. + * @param {number} [index=0] - Index to start from. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. + */ +var RGBWithRGB = function (r1, g1, b1, r2, g2, b2, length, index) +{ + if (length === undefined) { length = 100; } + if (index === undefined) { index = 0; } + + var t = index / length; + + return { + r: Linear(r1, r2, t), + g: Linear(g1, g2, t), + b: Linear(b1, b2, t) + }; +}; + +/** + * Interpolates between the two given color objects over the length supplied. + * + * @function Phaser.Display.Color.Interpolate.ColorWithColor + * @memberof Phaser.Display.Color.Interpolate + * @static + * @since 3.0.0 + * + * @param {Phaser.Display.Color} color1 - The first Color object. + * @param {Phaser.Display.Color} color2 - The second Color object. + * @param {number} [length=100] - Distance to interpolate over. + * @param {number} [index=0] - Index to start from. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. + */ +var ColorWithColor = function (color1, color2, length, index) +{ + if (length === undefined) { length = 100; } + if (index === undefined) { index = 0; } + + return RGBWithRGB(color1.r, color1.g, color1.b, color2.r, color2.g, color2.b, length, index); +}; + +/** + * Interpolates between the Color object and color values over the length supplied. + * + * @function Phaser.Display.Color.Interpolate.ColorWithRGB + * @memberof Phaser.Display.Color.Interpolate + * @static + * @since 3.0.0 + * + * @param {Phaser.Display.Color} color1 - The first Color object. + * @param {number} r - Red value. + * @param {number} g - Blue value. + * @param {number} b - Green value. + * @param {number} [length=100] - Distance to interpolate over. + * @param {number} [index=0] - Index to start from. + * + * @return {Phaser.Types.Display.ColorObject} An object containing the interpolated color values. + */ +var ColorWithRGB = function (color, r, g, b, length, index) +{ + if (length === undefined) { length = 100; } + if (index === undefined) { index = 0; } + + return RGBWithRGB(color.r, color.g, color.b, r, g, b, length, index); +}; + +module.exports = { + + RGBWithRGB: RGBWithRGB, + ColorWithRGB: ColorWithRGB, + ColorWithColor: ColorWithColor + +}; diff --git a/src/display/color/ObjectToColor.js b/src/display/color/ObjectToColor.js index 6a4bfe5ce..1940e3821 100644 --- a/src/display/color/ObjectToColor.js +++ b/src/display/color/ObjectToColor.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Color = require('./Color'); - -/** - * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. - * - * @function Phaser.Display.Color.ObjectToColor - * @since 3.0.0 - * - * @param {Phaser.Types.Display.InputColorObject} input - An object containing `r`, `g`, `b` and `a` properties in the range 0 to 255. - * - * @return {Phaser.Display.Color} A Color object. - */ -var ObjectToColor = function (input) -{ - return new Color(input.r, input.g, input.b, input.a); -}; - -module.exports = ObjectToColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = require('./Color'); + +/** + * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. + * + * @function Phaser.Display.Color.ObjectToColor + * @since 3.0.0 + * + * @param {Phaser.Types.Display.InputColorObject} input - An object containing `r`, `g`, `b` and `a` properties in the range 0 to 255. + * + * @return {Phaser.Display.Color} A Color object. + */ +var ObjectToColor = function (input) +{ + return new Color(input.r, input.g, input.b, input.a); +}; + +module.exports = ObjectToColor; diff --git a/src/display/color/RGBStringToColor.js b/src/display/color/RGBStringToColor.js index 5ef3c7d4c..10cce1da3 100644 --- a/src/display/color/RGBStringToColor.js +++ b/src/display/color/RGBStringToColor.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Color = require('./Color'); - -/** - * Converts a CSS 'web' string into a Phaser Color object. - * - * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. - * - * @function Phaser.Display.Color.RGBStringToColor - * @since 3.0.0 - * - * @param {string} rgb - The CSS format color string, using the `rgb` or `rgba` format. - * - * @return {Phaser.Display.Color} A Color object. - */ -var RGBStringToColor = function (rgb) -{ - var color = new Color(); - - var result = (/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/).exec(rgb.toLowerCase()); - - if (result) - { - var r = parseInt(result[1], 10); - var g = parseInt(result[2], 10); - var b = parseInt(result[3], 10); - var a = (result[4] !== undefined) ? parseFloat(result[4]) : 1; - - color.setTo(r, g, b, a * 255); - } - - return color; -}; - -module.exports = RGBStringToColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = require('./Color'); + +/** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @function Phaser.Display.Color.RGBStringToColor + * @since 3.0.0 + * + * @param {string} rgb - The CSS format color string, using the `rgb` or `rgba` format. + * + * @return {Phaser.Display.Color} A Color object. + */ +var RGBStringToColor = function (rgb) +{ + var color = new Color(); + + var result = (/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/).exec(rgb.toLowerCase()); + + if (result) + { + var r = parseInt(result[1], 10); + var g = parseInt(result[2], 10); + var b = parseInt(result[3], 10); + var a = (result[4] !== undefined) ? parseFloat(result[4]) : 1; + + color.setTo(r, g, b, a * 255); + } + + return color; +}; + +module.exports = RGBStringToColor; diff --git a/src/display/color/RGBToHSV.js b/src/display/color/RGBToHSV.js index 75429fcca..7108cf093 100644 --- a/src/display/color/RGBToHSV.js +++ b/src/display/color/RGBToHSV.js @@ -1,74 +1,74 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 {integer} r - The red color value. A number between 0 and 255. - * @param {integer} g - The green color value. A number between 0 and 255. - * @param {integer} 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. - */ -var RGBToHSV = function (r, g, b, out) -{ - if (out === undefined) { out = { h: 0, s: 0, v: 0 }; } - - r /= 255; - g /= 255; - b /= 255; - - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var d = max - min; - - // achromatic by default - var h = 0; - var s = (max === 0) ? 0 : d / max; - var v = max; - - if (max !== min) - { - if (max === r) - { - h = (g - b) / d + ((g < b) ? 6 : 0); - } - else if (max === g) - { - h = (b - r) / d + 2; - } - else if (max === b) - { - h = (r - g) / d + 4; - } - - h /= 6; - } - - if (out.hasOwnProperty('_h')) - { - out._h = h; - out._s = s; - out._v = v; - } - else - { - out.h = h; - out.s = s; - out.v = v; - } - - return out; -}; - -module.exports = RGBToHSV; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} r - The red color value. A number between 0 and 255. + * @param {integer} g - The green color value. A number between 0 and 255. + * @param {integer} 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. + */ +var RGBToHSV = function (r, g, b, out) +{ + if (out === undefined) { out = { h: 0, s: 0, v: 0 }; } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + var h = 0; + var s = (max === 0) ? 0 : d / max; + var v = max; + + if (max !== min) + { + if (max === r) + { + h = (g - b) / d + ((g < b) ? 6 : 0); + } + else if (max === g) + { + h = (b - r) / d + 2; + } + else if (max === b) + { + h = (r - g) / d + 4; + } + + h /= 6; + } + + if (out.hasOwnProperty('_h')) + { + out._h = h; + out._s = s; + out._v = v; + } + else + { + out.h = h; + out.s = s; + out.v = v; + } + + return out; +}; + +module.exports = RGBToHSV; diff --git a/src/display/color/RGBToString.js b/src/display/color/RGBToString.js index b1df7931b..d2379c654 100644 --- a/src/display/color/RGBToString.js +++ b/src/display/color/RGBToString.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ComponentToHex = require('./ComponentToHex'); - -/** - * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. - * - * @function Phaser.Display.Color.RGBToString - * @since 3.0.0 - * - * @param {integer} r - The red color value. A number between 0 and 255. - * @param {integer} g - The green color value. A number between 0 and 255. - * @param {integer} b - The blue color value. A number between 0 and 255. - * @param {integer} [a=255] - The alpha value. A number between 0 and 255. - * @param {string} [prefix=#] - The prefix of the string. Either `#` or `0x`. - * - * @return {string} A string-based representation of the color values. - */ -var RGBToString = function (r, g, b, a, prefix) -{ - if (a === undefined) { a = 255; } - if (prefix === undefined) { prefix = '#'; } - - if (prefix === '#') - { - return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); - } - else - { - return '0x' + ComponentToHex(a) + ComponentToHex(r) + ComponentToHex(g) + ComponentToHex(b); - } -}; - -module.exports = RGBToString; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ComponentToHex = require('./ComponentToHex'); + +/** + * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. + * + * @function Phaser.Display.Color.RGBToString + * @since 3.0.0 + * + * @param {integer} r - The red color value. A number between 0 and 255. + * @param {integer} g - The green color value. A number between 0 and 255. + * @param {integer} b - The blue color value. A number between 0 and 255. + * @param {integer} [a=255] - The alpha value. A number between 0 and 255. + * @param {string} [prefix=#] - The prefix of the string. Either `#` or `0x`. + * + * @return {string} A string-based representation of the color values. + */ +var RGBToString = function (r, g, b, a, prefix) +{ + if (a === undefined) { a = 255; } + if (prefix === undefined) { prefix = '#'; } + + if (prefix === '#') + { + return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); + } + else + { + return '0x' + ComponentToHex(a) + ComponentToHex(r) + ComponentToHex(g) + ComponentToHex(b); + } +}; + +module.exports = RGBToString; diff --git a/src/display/color/RandomRGB.js b/src/display/color/RandomRGB.js index 00c60006f..2814ab944 100644 --- a/src/display/color/RandomRGB.js +++ b/src/display/color/RandomRGB.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Between = require('../../math/Between'); -var Color = require('./Color'); - -/** - * 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 {integer} [min=0] - The minimum value to set the random range from (between 0 and 255) - * @param {integer} [max=255] - The maximum value to set the random range from (between 0 and 255) - * - * @return {Phaser.Display.Color} A Color object. - */ -var RandomRGB = function (min, max) -{ - if (min === undefined) { min = 0; } - if (max === undefined) { max = 255; } - - return new Color(Between(min, max), Between(min, max), Between(min, max)); -}; - -module.exports = RandomRGB; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Between = require('../../math/Between'); +var Color = require('./Color'); + +/** + * 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 {integer} [min=0] - The minimum value to set the random range from (between 0 and 255) + * @param {integer} [max=255] - The maximum value to set the random range from (between 0 and 255) + * + * @return {Phaser.Display.Color} A Color object. + */ +var RandomRGB = function (min, max) +{ + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + + return new Color(Between(min, max), Between(min, max), Between(min, max)); +}; + +module.exports = RandomRGB; diff --git a/src/display/color/ValueToColor.js b/src/display/color/ValueToColor.js index 6d03b2169..12cb0fd36 100644 --- a/src/display/color/ValueToColor.js +++ b/src/display/color/ValueToColor.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var HexStringToColor = require('./HexStringToColor'); -var IntegerToColor = require('./IntegerToColor'); -var ObjectToColor = require('./ObjectToColor'); -var RGBStringToColor = require('./RGBStringToColor'); - -/** - * Converts the given source color value into an instance of a Color class. - * The value can be either a string, prefixed with `rgb` or a hex string, a number or an Object. - * - * @function Phaser.Display.Color.ValueToColor - * @since 3.0.0 - * - * @param {(string|number|Phaser.Types.Display.InputColorObject)} input - The source color value to convert. - * - * @return {Phaser.Display.Color} A Color object. - */ -var ValueToColor = function (input) -{ - var t = typeof input; - - switch (t) - { - case 'string': - - if (input.substr(0, 3).toLowerCase() === 'rgb') - { - return RGBStringToColor(input); - } - else - { - return HexStringToColor(input); - } - - case 'number': - - return IntegerToColor(input); - - case 'object': - - return ObjectToColor(input); - } -}; - -module.exports = ValueToColor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HexStringToColor = require('./HexStringToColor'); +var IntegerToColor = require('./IntegerToColor'); +var ObjectToColor = require('./ObjectToColor'); +var RGBStringToColor = require('./RGBStringToColor'); + +/** + * Converts the given source color value into an instance of a Color class. + * The value can be either a string, prefixed with `rgb` or a hex string, a number or an Object. + * + * @function Phaser.Display.Color.ValueToColor + * @since 3.0.0 + * + * @param {(string|number|Phaser.Types.Display.InputColorObject)} input - The source color value to convert. + * + * @return {Phaser.Display.Color} A Color object. + */ +var ValueToColor = function (input) +{ + var t = typeof input; + + switch (t) + { + case 'string': + + if (input.substr(0, 3).toLowerCase() === 'rgb') + { + return RGBStringToColor(input); + } + else + { + return HexStringToColor(input); + } + + case 'number': + + return IntegerToColor(input); + + case 'object': + + return ObjectToColor(input); + } +}; + +module.exports = ValueToColor; diff --git a/src/display/color/index.js b/src/display/color/index.js index b4231fe9d..444e9a9da 100644 --- a/src/display/color/index.js +++ b/src/display/color/index.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Color = require('./Color'); - -Color.ColorToRGBA = require('./ColorToRGBA'); -Color.ComponentToHex = require('./ComponentToHex'); -Color.GetColor = require('./GetColor'); -Color.GetColor32 = require('./GetColor32'); -Color.HexStringToColor = require('./HexStringToColor'); -Color.HSLToColor = require('./HSLToColor'); -Color.HSVColorWheel = require('./HSVColorWheel'); -Color.HSVToRGB = require('./HSVToRGB'); -Color.HueToComponent = require('./HueToComponent'); -Color.IntegerToColor = require('./IntegerToColor'); -Color.IntegerToRGB = require('./IntegerToRGB'); -Color.Interpolate = require('./Interpolate'); -Color.ObjectToColor = require('./ObjectToColor'); -Color.RandomRGB = require('./RandomRGB'); -Color.RGBStringToColor = require('./RGBStringToColor'); -Color.RGBToHSV = require('./RGBToHSV'); -Color.RGBToString = require('./RGBToString'); -Color.ValueToColor = require('./ValueToColor'); - -module.exports = Color; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Color = require('./Color'); + +Color.ColorToRGBA = require('./ColorToRGBA'); +Color.ComponentToHex = require('./ComponentToHex'); +Color.GetColor = require('./GetColor'); +Color.GetColor32 = require('./GetColor32'); +Color.HexStringToColor = require('./HexStringToColor'); +Color.HSLToColor = require('./HSLToColor'); +Color.HSVColorWheel = require('./HSVColorWheel'); +Color.HSVToRGB = require('./HSVToRGB'); +Color.HueToComponent = require('./HueToComponent'); +Color.IntegerToColor = require('./IntegerToColor'); +Color.IntegerToRGB = require('./IntegerToRGB'); +Color.Interpolate = require('./Interpolate'); +Color.ObjectToColor = require('./ObjectToColor'); +Color.RandomRGB = require('./RandomRGB'); +Color.RGBStringToColor = require('./RGBStringToColor'); +Color.RGBToHSV = require('./RGBToHSV'); +Color.RGBToString = require('./RGBToString'); +Color.ValueToColor = require('./ValueToColor'); + +module.exports = Color; diff --git a/src/display/index.js b/src/display/index.js index dbe567976..04cc51bad 100644 --- a/src/display/index.js +++ b/src/display/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display - */ - -module.exports = { - - Align: require('./align'), - BaseShader: require('./shader/BaseShader'), - Bounds: require('./bounds'), - Canvas: require('./canvas'), - Color: require('./color'), - Masks: require('./mask') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display + */ + +module.exports = { + + Align: require('./align'), + BaseShader: require('./shader/BaseShader'), + Bounds: require('./bounds'), + Canvas: require('./canvas'), + Color: require('./color'), + Masks: require('./mask') + +}; diff --git a/src/display/mask/BitmapMask.js b/src/display/mask/BitmapMask.js index 0e51cc8f3..95f7d4efe 100644 --- a/src/display/mask/BitmapMask.js +++ b/src/display/mask/BitmapMask.js @@ -1,287 +1,287 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GameEvents = require('../../core/events'); - -/** - * @classdesc - * A Bitmap Mask combines the alpha (opacity) of a masked pixel with the alpha of another pixel. - * Unlike the Geometry Mask, which is a clipping path, a Bitmap Mask behaves like an alpha mask, - * not a clipping path. It is only available when using the WebGL Renderer. - * - * A Bitmap Mask can use any Game Object to determine the alpha of each pixel of the masked Game Object(s). - * For any given point of a masked Game Object's texture, the pixel's alpha will be multiplied by the alpha - * of the pixel at the same position in the Bitmap Mask's Game Object. The color of the pixel from the - * Bitmap Mask doesn't matter. - * - * For example, if a pure blue pixel with an alpha of 0.95 is masked with a pure red pixel with an - * alpha of 0.5, the resulting pixel will be pure blue with an alpha of 0.475. Naturally, this means - * that a pixel in the mask with an alpha of 0 will hide the corresponding pixel in all masked Game Objects - * A pixel with an alpha of 1 in the masked Game Object will receive the same alpha as the - * corresponding pixel in the mask. - * - * The Bitmap Mask's location matches the location of its Game Object, not the location of the - * masked objects. Moving or transforming the underlying Game Object will change the mask - * (and affect the visibility of any masked objects), whereas moving or transforming a masked object - * will not affect the mask. - * - * The Bitmap Mask will not render its Game Object by itself. If the Game Object is not in a - * Scene's display list, it will only be used for the mask and its full texture will not be directly - * visible. Adding the underlying Game Object to a Scene will not cause any problems - it will - * render as a normal Game Object and will also serve as a mask. - * - * @class BitmapMask - * @memberof Phaser.Display.Masks - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene which this Bitmap Mask will be used in. - * @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite. - */ -var BitmapMask = new Class({ - - initialize: - - function BitmapMask (scene, renderable) - { - var renderer = scene.sys.game.renderer; - - /** - * A reference to either the Canvas or WebGL Renderer that this Mask is using. - * - * @name Phaser.Display.Masks.BitmapMask#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.11.0 - */ - this.renderer = renderer; - - /** - * A renderable Game Object that uses a texture, such as a Sprite. - * - * @name Phaser.Display.Masks.BitmapMask#bitmapMask - * @type {Phaser.GameObjects.GameObject} - * @since 3.0.0 - */ - this.bitmapMask = renderable; - - /** - * The texture used for the mask's framebuffer. - * - * @name Phaser.Display.Masks.BitmapMask#maskTexture - * @type {WebGLTexture} - * @default null - * @since 3.0.0 - */ - this.maskTexture = null; - - /** - * The texture used for the main framebuffer. - * - * @name Phaser.Display.Masks.BitmapMask#mainTexture - * @type {WebGLTexture} - * @default null - * @since 3.0.0 - */ - this.mainTexture = null; - - /** - * Whether the Bitmap Mask is dirty and needs to be updated. - * - * @name Phaser.Display.Masks.BitmapMask#dirty - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.dirty = true; - - /** - * The framebuffer to which a masked Game Object is rendered. - * - * @name Phaser.Display.Masks.BitmapMask#mainFramebuffer - * @type {WebGLFramebuffer} - * @since 3.0.0 - */ - this.mainFramebuffer = null; - - /** - * The framebuffer to which the Bitmap Mask's masking Game Object is rendered. - * - * @name Phaser.Display.Masks.BitmapMask#maskFramebuffer - * @type {WebGLFramebuffer} - * @since 3.0.0 - */ - this.maskFramebuffer = null; - - /** - * The previous framebuffer set in the renderer before this one was enabled. - * - * @name Phaser.Display.Masks.BitmapMask#prevFramebuffer - * @type {WebGLFramebuffer} - * @since 3.17.0 - */ - this.prevFramebuffer = null; - - /** - * Whether to invert the masks alpha. - * - * If `true`, the alpha of the masking pixel will be inverted before it's multiplied with the masked pixel. Essentially, this means that a masked area will be visible only if the corresponding area in the mask is invisible. - * - * @name Phaser.Display.Masks.BitmapMask#invertAlpha - * @type {boolean} - * @since 3.1.2 - */ - this.invertAlpha = false; - - /** - * Is this mask a stencil mask? - * - * @name Phaser.Display.Masks.BitmapMask#isStencil - * @type {boolean} - * @readonly - * @since 3.17.0 - */ - this.isStencil = false; - - if (renderer && renderer.gl) - { - var width = renderer.width; - var height = renderer.height; - var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0); - var gl = renderer.gl; - var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; - var filter = gl.LINEAR; - - this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); - this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); - this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true); - this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true); - - scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer) - { - var width = renderer.width; - var height = renderer.height; - var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0); - var gl = renderer.gl; - var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; - var filter = gl.LINEAR; - - this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); - this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); - this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true); - this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true); - - }, this); - } - }, - - /** - * Sets a new masking Game Object for the Bitmap Mask. - * - * @method Phaser.Display.Masks.BitmapMask#setBitmap - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite. - */ - setBitmap: function (renderable) - { - this.bitmapMask = renderable; - }, - - /** - * Prepares the WebGL Renderer to render a Game Object with this mask applied. - * - * This renders the masking Game Object to the mask framebuffer and switches to the main framebuffer so that the masked Game Object will be rendered to it instead of being rendered directly to the frame. - * - * @method Phaser.Display.Masks.BitmapMask#preRenderWebGL - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to prepare. - * @param {Phaser.GameObjects.GameObject} maskedObject - The masked Game Object which will be drawn. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to. - */ - preRenderWebGL: function (renderer, maskedObject, camera) - { - renderer.pipelines.BitmapMaskPipeline.beginMask(this, maskedObject, camera); - }, - - /** - * Finalizes rendering of a masked Game Object. - * - * This resets the previously bound framebuffer and switches the WebGL Renderer to the Bitmap Mask Pipeline, which uses a special fragment shader to apply the masking effect. - * - * @method Phaser.Display.Masks.BitmapMask#postRenderWebGL - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to clean up. - */ - postRenderWebGL: function (renderer, camera) - { - renderer.pipelines.BitmapMaskPipeline.endMask(this, camera); - }, - - /** - * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. - * - * @method Phaser.Display.Masks.BitmapMask#preRenderCanvas - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to. - * @param {Phaser.GameObjects.GameObject} mask - The masked Game Object which would be rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to. - */ - preRenderCanvas: function () - { - // NOOP - }, - - /** - * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. - * - * @method Phaser.Display.Masks.BitmapMask#postRenderCanvas - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to. - */ - postRenderCanvas: function () - { - // NOOP - }, - - /** - * Destroys this BitmapMask and nulls any references it holds. - * - * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, - * so be sure to call `clearMask` on any Game Object using it, before destroying it. - * - * @method Phaser.Display.Masks.BitmapMask#destroy - * @since 3.7.0 - */ - destroy: function () - { - this.bitmapMask = null; - - var renderer = this.renderer; - - if (renderer && renderer.gl) - { - renderer.deleteTexture(this.mainTexture); - renderer.deleteTexture(this.maskTexture); - renderer.deleteFramebuffer(this.mainFramebuffer); - renderer.deleteFramebuffer(this.maskFramebuffer); - } - - this.mainTexture = null; - this.maskTexture = null; - this.mainFramebuffer = null; - this.maskFramebuffer = null; - this.prevFramebuffer = null; - this.renderer = null; - } - -}); - -module.exports = BitmapMask; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GameEvents = require('../../core/events'); + +/** + * @classdesc + * A Bitmap Mask combines the alpha (opacity) of a masked pixel with the alpha of another pixel. + * Unlike the Geometry Mask, which is a clipping path, a Bitmap Mask behaves like an alpha mask, + * not a clipping path. It is only available when using the WebGL Renderer. + * + * A Bitmap Mask can use any Game Object to determine the alpha of each pixel of the masked Game Object(s). + * For any given point of a masked Game Object's texture, the pixel's alpha will be multiplied by the alpha + * of the pixel at the same position in the Bitmap Mask's Game Object. The color of the pixel from the + * Bitmap Mask doesn't matter. + * + * For example, if a pure blue pixel with an alpha of 0.95 is masked with a pure red pixel with an + * alpha of 0.5, the resulting pixel will be pure blue with an alpha of 0.475. Naturally, this means + * that a pixel in the mask with an alpha of 0 will hide the corresponding pixel in all masked Game Objects + * A pixel with an alpha of 1 in the masked Game Object will receive the same alpha as the + * corresponding pixel in the mask. + * + * The Bitmap Mask's location matches the location of its Game Object, not the location of the + * masked objects. Moving or transforming the underlying Game Object will change the mask + * (and affect the visibility of any masked objects), whereas moving or transforming a masked object + * will not affect the mask. + * + * The Bitmap Mask will not render its Game Object by itself. If the Game Object is not in a + * Scene's display list, it will only be used for the mask and its full texture will not be directly + * visible. Adding the underlying Game Object to a Scene will not cause any problems - it will + * render as a normal Game Object and will also serve as a mask. + * + * @class BitmapMask + * @memberof Phaser.Display.Masks + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which this Bitmap Mask will be used in. + * @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite. + */ +var BitmapMask = new Class({ + + initialize: + + function BitmapMask (scene, renderable) + { + var renderer = scene.sys.game.renderer; + + /** + * A reference to either the Canvas or WebGL Renderer that this Mask is using. + * + * @name Phaser.Display.Masks.BitmapMask#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.11.0 + */ + this.renderer = renderer; + + /** + * A renderable Game Object that uses a texture, such as a Sprite. + * + * @name Phaser.Display.Masks.BitmapMask#bitmapMask + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.bitmapMask = renderable; + + /** + * The texture used for the mask's framebuffer. + * + * @name Phaser.Display.Masks.BitmapMask#maskTexture + * @type {WebGLTexture} + * @default null + * @since 3.0.0 + */ + this.maskTexture = null; + + /** + * The texture used for the main framebuffer. + * + * @name Phaser.Display.Masks.BitmapMask#mainTexture + * @type {WebGLTexture} + * @default null + * @since 3.0.0 + */ + this.mainTexture = null; + + /** + * Whether the Bitmap Mask is dirty and needs to be updated. + * + * @name Phaser.Display.Masks.BitmapMask#dirty + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.dirty = true; + + /** + * The framebuffer to which a masked Game Object is rendered. + * + * @name Phaser.Display.Masks.BitmapMask#mainFramebuffer + * @type {WebGLFramebuffer} + * @since 3.0.0 + */ + this.mainFramebuffer = null; + + /** + * The framebuffer to which the Bitmap Mask's masking Game Object is rendered. + * + * @name Phaser.Display.Masks.BitmapMask#maskFramebuffer + * @type {WebGLFramebuffer} + * @since 3.0.0 + */ + this.maskFramebuffer = null; + + /** + * The previous framebuffer set in the renderer before this one was enabled. + * + * @name Phaser.Display.Masks.BitmapMask#prevFramebuffer + * @type {WebGLFramebuffer} + * @since 3.17.0 + */ + this.prevFramebuffer = null; + + /** + * Whether to invert the masks alpha. + * + * If `true`, the alpha of the masking pixel will be inverted before it's multiplied with the masked pixel. Essentially, this means that a masked area will be visible only if the corresponding area in the mask is invisible. + * + * @name Phaser.Display.Masks.BitmapMask#invertAlpha + * @type {boolean} + * @since 3.1.2 + */ + this.invertAlpha = false; + + /** + * Is this mask a stencil mask? + * + * @name Phaser.Display.Masks.BitmapMask#isStencil + * @type {boolean} + * @readonly + * @since 3.17.0 + */ + this.isStencil = false; + + if (renderer && renderer.gl) + { + var width = renderer.width; + var height = renderer.height; + var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0); + var gl = renderer.gl; + var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; + var filter = gl.LINEAR; + + this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true); + this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true); + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer) + { + var width = renderer.width; + var height = renderer.height; + var pot = ((width & (width - 1)) === 0 && (height & (height - 1)) === 0); + var gl = renderer.gl; + var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; + var filter = gl.LINEAR; + + this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); + this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, true); + this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, true); + + }, this); + } + }, + + /** + * Sets a new masking Game Object for the Bitmap Mask. + * + * @method Phaser.Display.Masks.BitmapMask#setBitmap + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} renderable - A renderable Game Object that uses a texture, such as a Sprite. + */ + setBitmap: function (renderable) + { + this.bitmapMask = renderable; + }, + + /** + * Prepares the WebGL Renderer to render a Game Object with this mask applied. + * + * This renders the masking Game Object to the mask framebuffer and switches to the main framebuffer so that the masked Game Object will be rendered to it instead of being rendered directly to the frame. + * + * @method Phaser.Display.Masks.BitmapMask#preRenderWebGL + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to prepare. + * @param {Phaser.GameObjects.GameObject} maskedObject - The masked Game Object which will be drawn. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to. + */ + preRenderWebGL: function (renderer, maskedObject, camera) + { + renderer.pipelines.BitmapMaskPipeline.beginMask(this, maskedObject, camera); + }, + + /** + * Finalizes rendering of a masked Game Object. + * + * This resets the previously bound framebuffer and switches the WebGL Renderer to the Bitmap Mask Pipeline, which uses a special fragment shader to apply the masking effect. + * + * @method Phaser.Display.Masks.BitmapMask#postRenderWebGL + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The WebGL Renderer to clean up. + */ + postRenderWebGL: function (renderer, camera) + { + renderer.pipelines.BitmapMaskPipeline.endMask(this, camera); + }, + + /** + * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. + * + * @method Phaser.Display.Masks.BitmapMask#preRenderCanvas + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to. + * @param {Phaser.GameObjects.GameObject} mask - The masked Game Object which would be rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to. + */ + preRenderCanvas: function () + { + // NOOP + }, + + /** + * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. + * + * @method Phaser.Display.Masks.BitmapMask#postRenderCanvas + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The Canvas Renderer which would be rendered to. + */ + postRenderCanvas: function () + { + // NOOP + }, + + /** + * Destroys this BitmapMask and nulls any references it holds. + * + * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, + * so be sure to call `clearMask` on any Game Object using it, before destroying it. + * + * @method Phaser.Display.Masks.BitmapMask#destroy + * @since 3.7.0 + */ + destroy: function () + { + this.bitmapMask = null; + + var renderer = this.renderer; + + if (renderer && renderer.gl) + { + renderer.deleteTexture(this.mainTexture); + renderer.deleteTexture(this.maskTexture); + renderer.deleteFramebuffer(this.mainFramebuffer); + renderer.deleteFramebuffer(this.maskFramebuffer); + } + + this.mainTexture = null; + this.maskTexture = null; + this.mainFramebuffer = null; + this.maskFramebuffer = null; + this.prevFramebuffer = null; + this.renderer = null; + } + +}); + +module.exports = BitmapMask; diff --git a/src/display/mask/GeometryMask.js b/src/display/mask/GeometryMask.js index 3281eddee..416dca480 100644 --- a/src/display/mask/GeometryMask.js +++ b/src/display/mask/GeometryMask.js @@ -1,309 +1,309 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); - -/** - * @classdesc - * A Geometry Mask can be applied to a Game Object to hide any pixels of it which don't intersect - * a visible pixel from the geometry mask. The mask is essentially a clipping path which can only - * make a masked pixel fully visible or fully invisible without changing its alpha (opacity). - * - * A Geometry Mask uses a Graphics Game Object to determine which pixels of the masked Game Object(s) - * should be clipped. For any given point of a masked Game Object's texture, the pixel will only be displayed - * if the Graphics Game Object of the Geometry Mask has a visible pixel at the same position. The color and - * alpha of the pixel from the Geometry Mask do not matter. - * - * The Geometry Mask's location matches the location of its Graphics object, not the location of the masked objects. - * Moving or transforming the underlying Graphics object will change the mask (and affect the visibility - * of any masked objects), whereas moving or transforming a masked object will not affect the mask. - * You can think of the Geometry Mask (or rather, of its Graphics object) as an invisible curtain placed - * in front of all masked objects which has its own visual properties and, naturally, respects the camera's - * visual properties, but isn't affected by and doesn't follow the masked objects by itself. - * - * @class GeometryMask - * @memberof Phaser.Display.Masks - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - This parameter is not used. - * @param {Phaser.GameObjects.Graphics} graphicsGeometry - The Graphics Game Object to use for the Geometry Mask. Doesn't have to be in the Display List. - */ -var GeometryMask = new Class({ - - initialize: - - function GeometryMask (scene, graphicsGeometry) - { - /** - * The Graphics object which describes the Geometry Mask. - * - * @name Phaser.Display.Masks.GeometryMask#geometryMask - * @type {Phaser.GameObjects.Graphics} - * @since 3.0.0 - */ - this.geometryMask = graphicsGeometry; - - /** - * Similar to the BitmapMasks invertAlpha setting this to true will then hide all pixels - * drawn to the Geometry Mask. - * - * @name Phaser.Display.Masks.GeometryMask#invertAlpha - * @type {boolean} - * @since 3.16.0 - */ - this.invertAlpha = false; - - /** - * Is this mask a stencil mask? - * - * @name Phaser.Display.Masks.GeometryMask#isStencil - * @type {boolean} - * @readonly - * @since 3.17.0 - */ - this.isStencil = true; - - /** - * The current stencil level. - * - * @name Phaser.Display.Masks.GeometryMask#level - * @type {boolean} - * @private - * @since 3.17.0 - */ - this.level = 0; - }, - - /** - * Sets a new Graphics object for the Geometry Mask. - * - * @method Phaser.Display.Masks.GeometryMask#setShape - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphicsGeometry - The Graphics object which will be used for the Geometry Mask. - * - * @return {this} This Geometry Mask - */ - setShape: function (graphicsGeometry) - { - this.geometryMask = graphicsGeometry; - - return this; - }, - - /** - * Sets the `invertAlpha` property of this Geometry Mask. - * Inverting the alpha essentially flips the way the mask works. - * - * @method Phaser.Display.Masks.GeometryMask#setInvertAlpha - * @since 3.17.0 - * - * @param {boolean} [value=true] - Invert the alpha of this mask? - * - * @return {this} This Geometry Mask - */ - setInvertAlpha: function (value) - { - if (value === undefined) { value = true; } - - this.invertAlpha = value; - - return this; - }, - - /** - * Renders the Geometry Mask's underlying Graphics object to the OpenGL stencil buffer and enables the stencil test, which clips rendered pixels according to the mask. - * - * @method Phaser.Display.Masks.GeometryMask#preRenderWebGL - * @since 3.0.0 - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw to. - * @param {Phaser.GameObjects.GameObject} child - The Game Object being rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. - */ - preRenderWebGL: function (renderer, child, camera) - { - var gl = renderer.gl; - - // Force flushing before drawing to stencil buffer - renderer.flush(); - - if (renderer.maskStack.length === 0) - { - gl.enable(gl.STENCIL_TEST); - gl.clear(gl.STENCIL_BUFFER_BIT); - - renderer.maskCount = 0; - } - - if (renderer.currentCameraMask.mask !== this) - { - renderer.currentMask.mask = this; - } - - renderer.maskStack.push({ mask: this, camera: camera }); - - this.applyStencil(renderer, camera, true); - - renderer.maskCount++; - }, - - /** - * Applies the current stencil mask to the renderer. - * - * @method Phaser.Display.Masks.GeometryMask#applyStencil - * @since 3.17.0 - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw to. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. - * @param {boolean} inc - Is this an INCR stencil or a DECR stencil? - */ - applyStencil: function (renderer, camera, inc) - { - var gl = renderer.gl; - var geometryMask = this.geometryMask; - var level = renderer.maskCount; - - gl.colorMask(false, false, false, false); - - if (inc) - { - gl.stencilFunc(gl.EQUAL, level, 0xFF); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); - } - else - { - gl.stencilFunc(gl.EQUAL, level + 1, 0xFF); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); - } - - // Write stencil buffer - geometryMask.renderWebGL(renderer, geometryMask, 0, camera); - - renderer.flush(); - - gl.colorMask(true, true, true, true); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - - if (inc) - { - if (this.invertAlpha) - { - gl.stencilFunc(gl.NOTEQUAL, level + 1, 0xFF); - } - else - { - gl.stencilFunc(gl.EQUAL, level + 1, 0xFF); - } - } - else if (this.invertAlpha) - { - gl.stencilFunc(gl.NOTEQUAL, level, 0xFF); - } - else - { - gl.stencilFunc(gl.EQUAL, level, 0xFF); - } - }, - - /** - * Flushes all rendered pixels and disables the stencil test of a WebGL context, thus disabling the mask for it. - * - * @method Phaser.Display.Masks.GeometryMask#postRenderWebGL - * @since 3.0.0 - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw flush. - */ - postRenderWebGL: function (renderer) - { - var gl = renderer.gl; - - renderer.maskStack.pop(); - - renderer.maskCount--; - - if (renderer.maskStack.length === 0) - { - // If this is the only mask in the stack, flush and disable - renderer.flush(); - - renderer.currentMask.mask = null; - - gl.disable(gl.STENCIL_TEST); - } - else - { - // Force flush before disabling stencil test - renderer.flush(); - - var prev = renderer.maskStack[renderer.maskStack.length - 1]; - - prev.mask.applyStencil(renderer, prev.camera, false); - - if (renderer.currentCameraMask.mask !== prev.mask) - { - renderer.currentMask.mask = prev.mask; - renderer.currentMask.camera = prev.camera; - } - else - { - renderer.currentMask.mask = null; - } - } - }, - - /** - * Sets the clipping path of a 2D canvas context to the Geometry Mask's underlying Graphics object. - * - * @method Phaser.Display.Masks.GeometryMask#preRenderCanvas - * @since 3.0.0 - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - The Canvas Renderer instance to set the clipping path on. - * @param {Phaser.GameObjects.GameObject} mask - The Game Object being rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. - */ - preRenderCanvas: function (renderer, mask, camera) - { - var geometryMask = this.geometryMask; - - renderer.currentContext.save(); - - geometryMask.renderCanvas(renderer, geometryMask, 0, camera, null, null, true); - - renderer.currentContext.clip(); - }, - - /** - * Restore the canvas context's previous clipping path, thus turning off the mask for it. - * - * @method Phaser.Display.Masks.GeometryMask#postRenderCanvas - * @since 3.0.0 - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - The Canvas Renderer instance being restored. - */ - postRenderCanvas: function (renderer) - { - renderer.currentContext.restore(); - }, - - /** - * Destroys this GeometryMask and nulls any references it holds. - * - * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, - * so be sure to call `clearMask` on any Game Object using it, before destroying it. - * - * @method Phaser.Display.Masks.GeometryMask#destroy - * @since 3.7.0 - */ - destroy: function () - { - this.geometryMask = null; - } - -}); - -module.exports = GeometryMask; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); + +/** + * @classdesc + * A Geometry Mask can be applied to a Game Object to hide any pixels of it which don't intersect + * a visible pixel from the geometry mask. The mask is essentially a clipping path which can only + * make a masked pixel fully visible or fully invisible without changing its alpha (opacity). + * + * A Geometry Mask uses a Graphics Game Object to determine which pixels of the masked Game Object(s) + * should be clipped. For any given point of a masked Game Object's texture, the pixel will only be displayed + * if the Graphics Game Object of the Geometry Mask has a visible pixel at the same position. The color and + * alpha of the pixel from the Geometry Mask do not matter. + * + * The Geometry Mask's location matches the location of its Graphics object, not the location of the masked objects. + * Moving or transforming the underlying Graphics object will change the mask (and affect the visibility + * of any masked objects), whereas moving or transforming a masked object will not affect the mask. + * You can think of the Geometry Mask (or rather, of its Graphics object) as an invisible curtain placed + * in front of all masked objects which has its own visual properties and, naturally, respects the camera's + * visual properties, but isn't affected by and doesn't follow the masked objects by itself. + * + * @class GeometryMask + * @memberof Phaser.Display.Masks + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - This parameter is not used. + * @param {Phaser.GameObjects.Graphics} graphicsGeometry - The Graphics Game Object to use for the Geometry Mask. Doesn't have to be in the Display List. + */ +var GeometryMask = new Class({ + + initialize: + + function GeometryMask (scene, graphicsGeometry) + { + /** + * The Graphics object which describes the Geometry Mask. + * + * @name Phaser.Display.Masks.GeometryMask#geometryMask + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.geometryMask = graphicsGeometry; + + /** + * Similar to the BitmapMasks invertAlpha setting this to true will then hide all pixels + * drawn to the Geometry Mask. + * + * @name Phaser.Display.Masks.GeometryMask#invertAlpha + * @type {boolean} + * @since 3.16.0 + */ + this.invertAlpha = false; + + /** + * Is this mask a stencil mask? + * + * @name Phaser.Display.Masks.GeometryMask#isStencil + * @type {boolean} + * @readonly + * @since 3.17.0 + */ + this.isStencil = true; + + /** + * The current stencil level. + * + * @name Phaser.Display.Masks.GeometryMask#level + * @type {boolean} + * @private + * @since 3.17.0 + */ + this.level = 0; + }, + + /** + * Sets a new Graphics object for the Geometry Mask. + * + * @method Phaser.Display.Masks.GeometryMask#setShape + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphicsGeometry - The Graphics object which will be used for the Geometry Mask. + * + * @return {this} This Geometry Mask + */ + setShape: function (graphicsGeometry) + { + this.geometryMask = graphicsGeometry; + + return this; + }, + + /** + * Sets the `invertAlpha` property of this Geometry Mask. + * Inverting the alpha essentially flips the way the mask works. + * + * @method Phaser.Display.Masks.GeometryMask#setInvertAlpha + * @since 3.17.0 + * + * @param {boolean} [value=true] - Invert the alpha of this mask? + * + * @return {this} This Geometry Mask + */ + setInvertAlpha: function (value) + { + if (value === undefined) { value = true; } + + this.invertAlpha = value; + + return this; + }, + + /** + * Renders the Geometry Mask's underlying Graphics object to the OpenGL stencil buffer and enables the stencil test, which clips rendered pixels according to the mask. + * + * @method Phaser.Display.Masks.GeometryMask#preRenderWebGL + * @since 3.0.0 + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw to. + * @param {Phaser.GameObjects.GameObject} child - The Game Object being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. + */ + preRenderWebGL: function (renderer, child, camera) + { + var gl = renderer.gl; + + // Force flushing before drawing to stencil buffer + renderer.flush(); + + if (renderer.maskStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + + renderer.maskCount = 0; + } + + if (renderer.currentCameraMask.mask !== this) + { + renderer.currentMask.mask = this; + } + + renderer.maskStack.push({ mask: this, camera: camera }); + + this.applyStencil(renderer, camera, true); + + renderer.maskCount++; + }, + + /** + * Applies the current stencil mask to the renderer. + * + * @method Phaser.Display.Masks.GeometryMask#applyStencil + * @since 3.17.0 + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw to. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. + * @param {boolean} inc - Is this an INCR stencil or a DECR stencil? + */ + applyStencil: function (renderer, camera, inc) + { + var gl = renderer.gl; + var geometryMask = this.geometryMask; + var level = renderer.maskCount; + + gl.colorMask(false, false, false, false); + + if (inc) + { + gl.stencilFunc(gl.EQUAL, level, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL, level + 1, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + } + + // Write stencil buffer + geometryMask.renderWebGL(renderer, geometryMask, 0, camera); + + renderer.flush(); + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + + if (inc) + { + if (this.invertAlpha) + { + gl.stencilFunc(gl.NOTEQUAL, level + 1, 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL, level + 1, 0xFF); + } + } + else if (this.invertAlpha) + { + gl.stencilFunc(gl.NOTEQUAL, level, 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL, level, 0xFF); + } + }, + + /** + * Flushes all rendered pixels and disables the stencil test of a WebGL context, thus disabling the mask for it. + * + * @method Phaser.Display.Masks.GeometryMask#postRenderWebGL + * @since 3.0.0 + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer instance to draw flush. + */ + postRenderWebGL: function (renderer) + { + var gl = renderer.gl; + + renderer.maskStack.pop(); + + renderer.maskCount--; + + if (renderer.maskStack.length === 0) + { + // If this is the only mask in the stack, flush and disable + renderer.flush(); + + renderer.currentMask.mask = null; + + gl.disable(gl.STENCIL_TEST); + } + else + { + // Force flush before disabling stencil test + renderer.flush(); + + var prev = renderer.maskStack[renderer.maskStack.length - 1]; + + prev.mask.applyStencil(renderer, prev.camera, false); + + if (renderer.currentCameraMask.mask !== prev.mask) + { + renderer.currentMask.mask = prev.mask; + renderer.currentMask.camera = prev.camera; + } + else + { + renderer.currentMask.mask = null; + } + } + }, + + /** + * Sets the clipping path of a 2D canvas context to the Geometry Mask's underlying Graphics object. + * + * @method Phaser.Display.Masks.GeometryMask#preRenderCanvas + * @since 3.0.0 + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - The Canvas Renderer instance to set the clipping path on. + * @param {Phaser.GameObjects.GameObject} mask - The Game Object being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the Game Object is being rendered through. + */ + preRenderCanvas: function (renderer, mask, camera) + { + var geometryMask = this.geometryMask; + + renderer.currentContext.save(); + + geometryMask.renderCanvas(renderer, geometryMask, 0, camera, null, null, true); + + renderer.currentContext.clip(); + }, + + /** + * Restore the canvas context's previous clipping path, thus turning off the mask for it. + * + * @method Phaser.Display.Masks.GeometryMask#postRenderCanvas + * @since 3.0.0 + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - The Canvas Renderer instance being restored. + */ + postRenderCanvas: function (renderer) + { + renderer.currentContext.restore(); + }, + + /** + * Destroys this GeometryMask and nulls any references it holds. + * + * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, + * so be sure to call `clearMask` on any Game Object using it, before destroying it. + * + * @method Phaser.Display.Masks.GeometryMask#destroy + * @since 3.7.0 + */ + destroy: function () + { + this.geometryMask = null; + } + +}); + +module.exports = GeometryMask; diff --git a/src/display/mask/index.js b/src/display/mask/index.js index eb3f26fd9..fdba6c2c8 100644 --- a/src/display/mask/index.js +++ b/src/display/mask/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Display.Masks - */ - -module.exports = { - - BitmapMask: require('./BitmapMask'), - GeometryMask: require('./GeometryMask') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Display.Masks + */ + +module.exports = { + + BitmapMask: require('./BitmapMask'), + GeometryMask: require('./GeometryMask') + +}; diff --git a/src/display/shader/BaseShader.js b/src/display/shader/BaseShader.js index 4a06ee495..932776de9 100644 --- a/src/display/shader/BaseShader.js +++ b/src/display/shader/BaseShader.js @@ -1,118 +1,118 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); - -/** - * @classdesc - * A BaseShader is a small resource class that contains the data required for a WebGL Shader to be created. - * - * It contains the raw source code to the fragment and vertex shader, as well as an object that defines - * the uniforms the shader requires, if any. - * - * BaseShaders are stored in the Shader Cache, available in a Scene via `this.cache.shaders` and are referenced - * by a unique key-based string. Retrieve them via `this.cache.shaders.get(key)`. - * - * BaseShaders are created automatically by the GLSL File Loader when loading an external shader resource. - * They can also be created at runtime, allowing you to use dynamically generated shader source code. - * - * Default fragment and vertex source is used if not provided in the constructor, setting-up a basic shader, - * suitable for debug rendering. - * - * @class BaseShader - * @memberof Phaser.Display - * @constructor - * @since 3.17.0 - * - * @param {string} key - The key of this shader. Must be unique within the shader cache. - * @param {string} [fragmentSrc] - The fragment source for the shader. - * @param {string} [vertexSrc] - The vertex source for the shader. - * @param {any} [uniforms] - Optional object defining the uniforms the shader uses. - */ -var BaseShader = new Class({ - - initialize: - - function BaseShader (key, fragmentSrc, vertexSrc, uniforms) - { - if (!fragmentSrc || fragmentSrc === '') - { - fragmentSrc = [ - 'precision mediump float;', - - 'uniform vec2 resolution;', - - 'varying vec2 fragCoord;', - - 'void main () {', - ' vec2 uv = fragCoord / resolution.xy;', - ' gl_FragColor = vec4(uv.xyx, 1.0);', - '}' - ].join('\n'); - } - - if (!vertexSrc || vertexSrc === '') - { - vertexSrc = [ - 'precision mediump float;', - - 'uniform mat4 uProjectionMatrix;', - 'uniform mat4 uViewMatrix;', - 'uniform vec2 uResolution;', - - 'attribute vec2 inPosition;', - - 'varying vec2 fragCoord;', - - 'void main () {', - 'gl_Position = uProjectionMatrix * uViewMatrix * vec4(inPosition, 1.0, 1.0);', - 'fragCoord = vec2(inPosition.x, uResolution.y - inPosition.y);', - '}' - ].join('\n'); - } - - if (uniforms === undefined) { uniforms = null; } - - /** - * The key of this shader, unique within the shader cache of this Phaser game instance. - * - * @name Phaser.Display.BaseShader#key - * @type {string} - * @since 3.17.0 - */ - this.key = key; - - /** - * The source code, as a string, of the fragment shader being used. - * - * @name Phaser.Display.BaseShader#fragmentSrc - * @type {string} - * @since 3.17.0 - */ - this.fragmentSrc = fragmentSrc; - - /** - * The source code, as a string, of the vertex shader being used. - * - * @name Phaser.Display.BaseShader#vertexSrc - * @type {string} - * @since 3.17.0 - */ - this.vertexSrc = vertexSrc; - - /** - * The default uniforms for this shader. - * - * @name Phaser.Display.BaseShader#uniforms - * @type {?any} - * @since 3.17.0 - */ - this.uniforms = uniforms; - } - -}); - -module.exports = BaseShader; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); + +/** + * @classdesc + * A BaseShader is a small resource class that contains the data required for a WebGL Shader to be created. + * + * It contains the raw source code to the fragment and vertex shader, as well as an object that defines + * the uniforms the shader requires, if any. + * + * BaseShaders are stored in the Shader Cache, available in a Scene via `this.cache.shaders` and are referenced + * by a unique key-based string. Retrieve them via `this.cache.shaders.get(key)`. + * + * BaseShaders are created automatically by the GLSL File Loader when loading an external shader resource. + * They can also be created at runtime, allowing you to use dynamically generated shader source code. + * + * Default fragment and vertex source is used if not provided in the constructor, setting-up a basic shader, + * suitable for debug rendering. + * + * @class BaseShader + * @memberof Phaser.Display + * @constructor + * @since 3.17.0 + * + * @param {string} key - The key of this shader. Must be unique within the shader cache. + * @param {string} [fragmentSrc] - The fragment source for the shader. + * @param {string} [vertexSrc] - The vertex source for the shader. + * @param {any} [uniforms] - Optional object defining the uniforms the shader uses. + */ +var BaseShader = new Class({ + + initialize: + + function BaseShader (key, fragmentSrc, vertexSrc, uniforms) + { + if (!fragmentSrc || fragmentSrc === '') + { + fragmentSrc = [ + 'precision mediump float;', + + 'uniform vec2 resolution;', + + 'varying vec2 fragCoord;', + + 'void main () {', + ' vec2 uv = fragCoord / resolution.xy;', + ' gl_FragColor = vec4(uv.xyx, 1.0);', + '}' + ].join('\n'); + } + + if (!vertexSrc || vertexSrc === '') + { + vertexSrc = [ + 'precision mediump float;', + + 'uniform mat4 uProjectionMatrix;', + 'uniform mat4 uViewMatrix;', + 'uniform vec2 uResolution;', + + 'attribute vec2 inPosition;', + + 'varying vec2 fragCoord;', + + 'void main () {', + 'gl_Position = uProjectionMatrix * uViewMatrix * vec4(inPosition, 1.0, 1.0);', + 'fragCoord = vec2(inPosition.x, uResolution.y - inPosition.y);', + '}' + ].join('\n'); + } + + if (uniforms === undefined) { uniforms = null; } + + /** + * The key of this shader, unique within the shader cache of this Phaser game instance. + * + * @name Phaser.Display.BaseShader#key + * @type {string} + * @since 3.17.0 + */ + this.key = key; + + /** + * The source code, as a string, of the fragment shader being used. + * + * @name Phaser.Display.BaseShader#fragmentSrc + * @type {string} + * @since 3.17.0 + */ + this.fragmentSrc = fragmentSrc; + + /** + * The source code, as a string, of the vertex shader being used. + * + * @name Phaser.Display.BaseShader#vertexSrc + * @type {string} + * @since 3.17.0 + */ + this.vertexSrc = vertexSrc; + + /** + * The default uniforms for this shader. + * + * @name Phaser.Display.BaseShader#uniforms + * @type {?any} + * @since 3.17.0 + */ + this.uniforms = uniforms; + } + +}); + +module.exports = BaseShader; diff --git a/src/dom/AddToDOM.js b/src/dom/AddToDOM.js index a201dcf7d..14150aa02 100644 --- a/src/dom/AddToDOM.js +++ b/src/dom/AddToDOM.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Adds the given element to the DOM. If a parent is provided the element is added as a child of the parent, providing it was able to access it. - * If no parent was given it falls back to using `document.body`. - * - * @function Phaser.DOM.AddToDOM - * @since 3.0.0 - * - * @param {HTMLElement} element - The element to be added to the DOM. Usually a Canvas object. - * @param {(string|HTMLElement)} [parent] - The parent in which to add the element. Can be a string which is passed to `getElementById` or an actual DOM object. - * - * @return {HTMLElement} The element that was added to the DOM. - */ -var AddToDOM = function (element, parent) -{ - var target; - - if (parent) - { - if (typeof parent === 'string') - { - // Hopefully an element ID - target = document.getElementById(parent); - } - else if (typeof parent === 'object' && parent.nodeType === 1) - { - // Quick test for a HTMLElement - target = parent; - } - } - else if (element.parentElement) - { - return element; - } - - // Fallback, covers an invalid ID and a non HTMLElement object - if (!target) - { - target = document.body; - } - - target.appendChild(element); - - return element; -}; - -module.exports = AddToDOM; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds the given element to the DOM. If a parent is provided the element is added as a child of the parent, providing it was able to access it. + * If no parent was given it falls back to using `document.body`. + * + * @function Phaser.DOM.AddToDOM + * @since 3.0.0 + * + * @param {HTMLElement} element - The element to be added to the DOM. Usually a Canvas object. + * @param {(string|HTMLElement)} [parent] - The parent in which to add the element. Can be a string which is passed to `getElementById` or an actual DOM object. + * + * @return {HTMLElement} The element that was added to the DOM. + */ +var AddToDOM = function (element, parent) +{ + var target; + + if (parent) + { + if (typeof parent === 'string') + { + // Hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // Quick test for a HTMLElement + target = parent; + } + } + else if (element.parentElement) + { + return element; + } + + // Fallback, covers an invalid ID and a non HTMLElement object + if (!target) + { + target = document.body; + } + + target.appendChild(element); + + return element; +}; + +module.exports = AddToDOM; diff --git a/src/dom/CreateDOMContainer.js b/src/dom/CreateDOMContainer.js index 67cb806fe..96ba508ed 100644 --- a/src/dom/CreateDOMContainer.js +++ b/src/dom/CreateDOMContainer.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AddToDOM = require('../dom/AddToDOM'); - -var CreateDOMContainer = function (game) -{ - var config = game.config; - - if (!config.parent || !config.domCreateContainer) - { - return; - } - - // DOM Element Container - var div = document.createElement('div'); - - div.style.cssText = [ - 'display: block;', - 'width: ' + game.scale.width + 'px;', - 'height: ' + game.scale.height + 'px;', - 'padding: 0; margin: 0;', - 'position: absolute;', - 'overflow: hidden;', - 'pointer-events: none;', - 'transform: scale(1);', - 'transform-origin: left top;' - ].join(' '); - - game.domContainer = div; - - AddToDOM(div, config.parent); -}; - -module.exports = CreateDOMContainer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AddToDOM = require('../dom/AddToDOM'); + +var CreateDOMContainer = function (game) +{ + var config = game.config; + + if (!config.parent || !config.domCreateContainer) + { + return; + } + + // DOM Element Container + var div = document.createElement('div'); + + div.style.cssText = [ + 'display: block;', + 'width: ' + game.scale.width + 'px;', + 'height: ' + game.scale.height + 'px;', + 'padding: 0; margin: 0;', + 'position: absolute;', + 'overflow: hidden;', + 'pointer-events: none;', + 'transform: scale(1);', + 'transform-origin: left top;' + ].join(' '); + + game.domContainer = div; + + AddToDOM(div, config.parent); +}; + +module.exports = CreateDOMContainer; diff --git a/src/dom/DOMContentLoaded.js b/src/dom/DOMContentLoaded.js index adb6ccf9b..9553e95a6 100644 --- a/src/dom/DOMContentLoaded.js +++ b/src/dom/DOMContentLoaded.js @@ -1,57 +1,57 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var OS = require('../device/OS'); - -/** - * @callback ContentLoadedCallback - */ - -/** - * Inspects the readyState of the document. If the document is already complete then it invokes the given callback. - * If not complete it sets up several event listeners such as `deviceready`, and once those fire, it invokes the callback. - * Called automatically by the Phaser.Game instance. Should not usually be accessed directly. - * - * @function Phaser.DOM.DOMContentLoaded - * @since 3.0.0 - * - * @param {ContentLoadedCallback} callback - The callback to be invoked when the device is ready and the DOM content is loaded. - */ -var DOMContentLoaded = function (callback) -{ - if (document.readyState === 'complete' || document.readyState === 'interactive') - { - callback(); - - return; - } - - var check = function () - { - document.removeEventListener('deviceready', check, true); - document.removeEventListener('DOMContentLoaded', check, true); - window.removeEventListener('load', check, true); - - callback(); - }; - - if (!document.body) - { - window.setTimeout(check, 20); - } - else if (OS.cordova) - { - // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready - document.addEventListener('deviceready', check, false); - } - else - { - document.addEventListener('DOMContentLoaded', check, true); - window.addEventListener('load', check, true); - } -}; - -module.exports = DOMContentLoaded; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var OS = require('../device/OS'); + +/** + * @callback ContentLoadedCallback + */ + +/** + * Inspects the readyState of the document. If the document is already complete then it invokes the given callback. + * If not complete it sets up several event listeners such as `deviceready`, and once those fire, it invokes the callback. + * Called automatically by the Phaser.Game instance. Should not usually be accessed directly. + * + * @function Phaser.DOM.DOMContentLoaded + * @since 3.0.0 + * + * @param {ContentLoadedCallback} callback - The callback to be invoked when the device is ready and the DOM content is loaded. + */ +var DOMContentLoaded = function (callback) +{ + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + callback(); + + return; + } + + var check = function () + { + document.removeEventListener('deviceready', check, true); + document.removeEventListener('DOMContentLoaded', check, true); + window.removeEventListener('load', check, true); + + callback(); + }; + + if (!document.body) + { + window.setTimeout(check, 20); + } + else if (OS.cordova) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + document.addEventListener('deviceready', check, false); + } + else + { + document.addEventListener('DOMContentLoaded', check, true); + window.addEventListener('load', check, true); + } +}; + +module.exports = DOMContentLoaded; diff --git a/src/dom/GetInnerHeight.js b/src/dom/GetInnerHeight.js index cd9992014..6fb15035a 100644 --- a/src/dom/GetInnerHeight.js +++ b/src/dom/GetInnerHeight.js @@ -1,53 +1,53 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Attempts to determine the document inner height across iOS and standard devices. - * 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 value. - */ -var GetInnerHeight = function (iOS) -{ - - if (!iOS) - { - return window.innerHeight; - } - - var axis = Math.abs(window.orientation); - - var size = { w: 0, h: 0 }; - - var ruler = document.createElement('div'); - - ruler.setAttribute('style', 'position: fixed; height: 100vh; width: 0; top: 0'); - - document.documentElement.appendChild(ruler); - - size.w = (axis === 90) ? ruler.offsetHeight : window.innerWidth; - size.h = (axis === 90) ? window.innerWidth : ruler.offsetHeight; - - document.documentElement.removeChild(ruler); - - ruler = null; - - if (Math.abs(window.orientation) !== 90) - { - return size.h; - } - else - { - return size.w; - } -}; - -module.exports = GetInnerHeight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Attempts to determine the document inner height across iOS and standard devices. + * 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 value. + */ +var GetInnerHeight = function (iOS) +{ + + if (!iOS) + { + return window.innerHeight; + } + + var axis = Math.abs(window.orientation); + + var size = { w: 0, h: 0 }; + + var ruler = document.createElement('div'); + + ruler.setAttribute('style', 'position: fixed; height: 100vh; width: 0; top: 0'); + + document.documentElement.appendChild(ruler); + + size.w = (axis === 90) ? ruler.offsetHeight : window.innerWidth; + size.h = (axis === 90) ? window.innerWidth : ruler.offsetHeight; + + document.documentElement.removeChild(ruler); + + ruler = null; + + if (Math.abs(window.orientation) !== 90) + { + return size.h; + } + else + { + return size.w; + } +}; + +module.exports = GetInnerHeight; diff --git a/src/dom/GetScreenOrientation.js b/src/dom/GetScreenOrientation.js index 08df9795e..3c98329a3 100644 --- a/src/dom/GetScreenOrientation.js +++ b/src/dom/GetScreenOrientation.js @@ -1,60 +1,60 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../scale/const'); - -/** - * Attempts to determine the screen orientation using the Orientation API. - * - * @function Phaser.DOM.GetScreenOrientation - * @since 3.16.0 - * - * @param {number} width - The width of the viewport. - * @param {number} height - The height of the viewport. - * - * @return {string} The orientation. - */ -var GetScreenOrientation = function (width, height) -{ - var screen = window.screen; - var orientation = (screen) ? screen.orientation || screen.mozOrientation || screen.msOrientation : false; - - if (orientation && typeof orientation.type === 'string') - { - // Screen Orientation API specification - return orientation.type; - } - else if (typeof orientation === 'string') - { - // moz / ms-orientation are strings - return orientation; - } - - if (screen) - { - return (screen.height > screen.width) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; - } - else if (typeof window.orientation === 'number') - { - // This may change by device based on "natural" orientation. - return (window.orientation === 0 || window.orientation === 180) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; - } - else if (window.matchMedia) - { - if (window.matchMedia('(orientation: portrait)').matches) - { - return CONST.ORIENTATION.PORTRAIT; - } - else if (window.matchMedia('(orientation: landscape)').matches) - { - return CONST.ORIENTATION.LANDSCAPE; - } - } - - return (height > width) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; -}; - -module.exports = GetScreenOrientation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../scale/const'); + +/** + * Attempts to determine the screen orientation using the Orientation API. + * + * @function Phaser.DOM.GetScreenOrientation + * @since 3.16.0 + * + * @param {number} width - The width of the viewport. + * @param {number} height - The height of the viewport. + * + * @return {string} The orientation. + */ +var GetScreenOrientation = function (width, height) +{ + var screen = window.screen; + var orientation = (screen) ? screen.orientation || screen.mozOrientation || screen.msOrientation : false; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz / ms-orientation are strings + return orientation; + } + + if (screen) + { + return (screen.height > screen.width) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; + } + else if (typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia('(orientation: portrait)').matches) + { + return CONST.ORIENTATION.PORTRAIT; + } + else if (window.matchMedia('(orientation: landscape)').matches) + { + return CONST.ORIENTATION.LANDSCAPE; + } + } + + return (height > width) ? CONST.ORIENTATION.PORTRAIT : CONST.ORIENTATION.LANDSCAPE; +}; + +module.exports = GetScreenOrientation; diff --git a/src/dom/GetTarget.js b/src/dom/GetTarget.js index 4dbeab10e..448f7f09d 100644 --- a/src/dom/GetTarget.js +++ b/src/dom/GetTarget.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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. - */ -var GetTarget = function (element) -{ - var target; - - if (element !== '') - { - if (typeof element === 'string') - { - // Hopefully an element ID - target = document.getElementById(element); - } - else if (element && element.nodeType === 1) - { - // Quick test for a HTMLElement - target = element; - } - } - - // Fallback to the document body. Covers an invalid ID and a non HTMLElement object. - if (!target) - { - // Use the full window - target = document.body; - } - - return target; -}; - -module.exports = GetTarget; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var GetTarget = function (element) +{ + var target; + + if (element !== '') + { + if (typeof element === 'string') + { + // Hopefully an element ID + target = document.getElementById(element); + } + else if (element && element.nodeType === 1) + { + // Quick test for a HTMLElement + target = element; + } + } + + // Fallback to the document body. Covers an invalid ID and a non HTMLElement object. + if (!target) + { + // Use the full window + target = document.body; + } + + return target; +}; + +module.exports = GetTarget; diff --git a/src/dom/ParseXML.js b/src/dom/ParseXML.js index 275a8c9ed..5ea9d3799 100644 --- a/src/dom/ParseXML.js +++ b/src/dom/ParseXML.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes the given data string and parses it as XML. - * First tries to use the window.DOMParser and reverts to the Microsoft.XMLDOM if that fails. - * The parsed XML object is returned, or `null` if there was an error while parsing the data. - * - * @function Phaser.DOM.ParseXML - * @since 3.0.0 - * - * @param {string} data - The XML source stored in a string. - * - * @return {?(DOMParser|ActiveXObject)} The parsed XML data, or `null` if the data could not be parsed. - */ -var ParseXML = function (data) -{ - var xml = ''; - - try - { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(data, 'text/xml'); - } - else - { - xml = new ActiveXObject('Microsoft.XMLDOM'); - xml.loadXML(data); - } - } - catch (e) - { - xml = null; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName('parsererror').length) - { - return null; - } - else - { - return xml; - } -}; - -module.exports = ParseXML; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes the given data string and parses it as XML. + * First tries to use the window.DOMParser and reverts to the Microsoft.XMLDOM if that fails. + * The parsed XML object is returned, or `null` if there was an error while parsing the data. + * + * @function Phaser.DOM.ParseXML + * @since 3.0.0 + * + * @param {string} data - The XML source stored in a string. + * + * @return {?(DOMParser|ActiveXObject)} The parsed XML data, or `null` if the data could not be parsed. + */ +var ParseXML = function (data) +{ + var xml = ''; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, 'text/xml'); + } + else + { + xml = new ActiveXObject('Microsoft.XMLDOM'); + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName('parsererror').length) + { + return null; + } + else + { + return xml; + } +}; + +module.exports = ParseXML; diff --git a/src/dom/RemoveFromDOM.js b/src/dom/RemoveFromDOM.js index 4f8534d4e..961289988 100644 --- a/src/dom/RemoveFromDOM.js +++ b/src/dom/RemoveFromDOM.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Attempts to remove the element from its parentNode in the DOM. - * - * @function Phaser.DOM.RemoveFromDOM - * @since 3.0.0 - * - * @param {HTMLElement} element - The DOM element to remove from its parent node. - */ -var RemoveFromDOM = function (element) -{ - if (element.parentNode) - { - element.parentNode.removeChild(element); - } -}; - -module.exports = RemoveFromDOM; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Attempts to remove the element from its parentNode in the DOM. + * + * @function Phaser.DOM.RemoveFromDOM + * @since 3.0.0 + * + * @param {HTMLElement} element - The DOM element to remove from its parent node. + */ +var RemoveFromDOM = function (element) +{ + if (element.parentNode) + { + element.parentNode.removeChild(element); + } +}; + +module.exports = RemoveFromDOM; diff --git a/src/dom/RequestAnimationFrame.js b/src/dom/RequestAnimationFrame.js index f6655a3af..1cee36460 100644 --- a/src/dom/RequestAnimationFrame.js +++ b/src/dom/RequestAnimationFrame.js @@ -1,208 +1,208 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var NOOP = require('../utils/NOOP'); - -/** - * @classdesc - * Abstracts away the use of RAF or setTimeOut for the core game update loop. - * This is invoked automatically by the Phaser.Game instance. - * - * @class RequestAnimationFrame - * @memberof Phaser.DOM - * @constructor - * @since 3.0.0 - */ -var RequestAnimationFrame = new Class({ - - initialize: - - function RequestAnimationFrame () - { - /** - * True if RequestAnimationFrame is running, otherwise false. - * - * @name Phaser.DOM.RequestAnimationFrame#isRunning - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isRunning = false; - - /** - * The callback to be invoked each step. - * - * @name Phaser.DOM.RequestAnimationFrame#callback - * @type {FrameRequestCallback} - * @since 3.0.0 - */ - this.callback = NOOP; - - /** - * The most recent timestamp. Either a DOMHighResTimeStamp under RAF or `Date.now` under SetTimeout. - * - * @name Phaser.DOM.RequestAnimationFrame#tick - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.tick = 0; - - /** - * True if the step is using setTimeout instead of RAF. - * - * @name Phaser.DOM.RequestAnimationFrame#isSetTimeOut - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isSetTimeOut = false; - - /** - * The setTimeout or RAF callback ID used when canceling them. - * - * @name Phaser.DOM.RequestAnimationFrame#timeOutID - * @type {?number} - * @default null - * @since 3.0.0 - */ - this.timeOutID = null; - - /** - * The previous time the step was called. - * - * @name Phaser.DOM.RequestAnimationFrame#lastTime - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.lastTime = 0; - - /** - * The target FPS rate in ms. - * Only used when setTimeout is used instead of RAF. - * - * @name Phaser.DOM.RequestAnimationFrame#target - * @type {number} - * @default 0 - * @since 3.21.0 - */ - this.target = 0; - - var _this = this; - - /** - * The RAF step function. - * Updates the local tick value, invokes the callback and schedules another call to requestAnimationFrame. - * - * @name Phaser.DOM.RequestAnimationFrame#step - * @type {FrameRequestCallback} - * @since 3.0.0 - */ - this.step = function step () - { - // Because we cannot trust the time passed to this callback from the browser and need it kept in sync with event times - var timestamp = window.performance.now(); - - // DOMHighResTimeStamp - _this.lastTime = _this.tick; - - _this.tick = timestamp; - - _this.callback(timestamp); - - _this.timeOutID = window.requestAnimationFrame(step); - }; - - /** - * The SetTimeout step function. - * Updates the local tick value, invokes the callback and schedules another call to setTimeout. - * - * @name Phaser.DOM.RequestAnimationFrame#stepTimeout - * @type {function} - * @since 3.0.0 - */ - this.stepTimeout = function stepTimeout () - { - var d = Date.now(); - - var delay = Math.min(Math.max(_this.target * 2 + _this.tick - d, 0), _this.target); - - _this.lastTime = _this.tick; - - _this.tick = d; - - _this.callback(d); - - _this.timeOutID = window.setTimeout(stepTimeout, delay); - }; - }, - - /** - * Starts the requestAnimationFrame or setTimeout process running. - * - * @method Phaser.DOM.RequestAnimationFrame#start - * @since 3.0.0 - * - * @param {FrameRequestCallback} callback - The callback to invoke each step. - * @param {boolean} forceSetTimeOut - Should it use SetTimeout, even if RAF is available? - * @param {number} targetFPS - The target fps rate (in ms). Only used when setTimeout is used. - */ - start: function (callback, forceSetTimeOut, targetFPS) - { - if (this.isRunning) - { - return; - } - - this.callback = callback; - - this.isSetTimeOut = forceSetTimeOut; - - this.target = targetFPS; - - this.isRunning = true; - - this.timeOutID = (forceSetTimeOut) ? window.setTimeout(this.stepTimeout, 0) : window.requestAnimationFrame(this.step); - }, - - /** - * Stops the requestAnimationFrame or setTimeout from running. - * - * @method Phaser.DOM.RequestAnimationFrame#stop - * @since 3.0.0 - */ - stop: function () - { - this.isRunning = false; - - if (this.isSetTimeOut) - { - clearTimeout(this.timeOutID); - } - else - { - window.cancelAnimationFrame(this.timeOutID); - } - }, - - /** - * Stops the step from running and clears the callback reference. - * - * @method Phaser.DOM.RequestAnimationFrame#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.stop(); - - this.callback = NOOP; - } - -}); - -module.exports = RequestAnimationFrame; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var NOOP = require('../utils/NOOP'); + +/** + * @classdesc + * Abstracts away the use of RAF or setTimeOut for the core game update loop. + * This is invoked automatically by the Phaser.Game instance. + * + * @class RequestAnimationFrame + * @memberof Phaser.DOM + * @constructor + * @since 3.0.0 + */ +var RequestAnimationFrame = new Class({ + + initialize: + + function RequestAnimationFrame () + { + /** + * True if RequestAnimationFrame is running, otherwise false. + * + * @name Phaser.DOM.RequestAnimationFrame#isRunning + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isRunning = false; + + /** + * The callback to be invoked each step. + * + * @name Phaser.DOM.RequestAnimationFrame#callback + * @type {FrameRequestCallback} + * @since 3.0.0 + */ + this.callback = NOOP; + + /** + * The most recent timestamp. Either a DOMHighResTimeStamp under RAF or `Date.now` under SetTimeout. + * + * @name Phaser.DOM.RequestAnimationFrame#tick + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.tick = 0; + + /** + * True if the step is using setTimeout instead of RAF. + * + * @name Phaser.DOM.RequestAnimationFrame#isSetTimeOut + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isSetTimeOut = false; + + /** + * The setTimeout or RAF callback ID used when canceling them. + * + * @name Phaser.DOM.RequestAnimationFrame#timeOutID + * @type {?number} + * @default null + * @since 3.0.0 + */ + this.timeOutID = null; + + /** + * The previous time the step was called. + * + * @name Phaser.DOM.RequestAnimationFrame#lastTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.lastTime = 0; + + /** + * The target FPS rate in ms. + * Only used when setTimeout is used instead of RAF. + * + * @name Phaser.DOM.RequestAnimationFrame#target + * @type {number} + * @default 0 + * @since 3.21.0 + */ + this.target = 0; + + var _this = this; + + /** + * The RAF step function. + * Updates the local tick value, invokes the callback and schedules another call to requestAnimationFrame. + * + * @name Phaser.DOM.RequestAnimationFrame#step + * @type {FrameRequestCallback} + * @since 3.0.0 + */ + this.step = function step () + { + // Because we cannot trust the time passed to this callback from the browser and need it kept in sync with event times + var timestamp = window.performance.now(); + + // DOMHighResTimeStamp + _this.lastTime = _this.tick; + + _this.tick = timestamp; + + _this.callback(timestamp); + + _this.timeOutID = window.requestAnimationFrame(step); + }; + + /** + * The SetTimeout step function. + * Updates the local tick value, invokes the callback and schedules another call to setTimeout. + * + * @name Phaser.DOM.RequestAnimationFrame#stepTimeout + * @type {function} + * @since 3.0.0 + */ + this.stepTimeout = function stepTimeout () + { + var d = Date.now(); + + var delay = Math.min(Math.max(_this.target * 2 + _this.tick - d, 0), _this.target); + + _this.lastTime = _this.tick; + + _this.tick = d; + + _this.callback(d); + + _this.timeOutID = window.setTimeout(stepTimeout, delay); + }; + }, + + /** + * Starts the requestAnimationFrame or setTimeout process running. + * + * @method Phaser.DOM.RequestAnimationFrame#start + * @since 3.0.0 + * + * @param {FrameRequestCallback} callback - The callback to invoke each step. + * @param {boolean} forceSetTimeOut - Should it use SetTimeout, even if RAF is available? + * @param {number} targetFPS - The target fps rate (in ms). Only used when setTimeout is used. + */ + start: function (callback, forceSetTimeOut, targetFPS) + { + if (this.isRunning) + { + return; + } + + this.callback = callback; + + this.isSetTimeOut = forceSetTimeOut; + + this.target = targetFPS; + + this.isRunning = true; + + this.timeOutID = (forceSetTimeOut) ? window.setTimeout(this.stepTimeout, 0) : window.requestAnimationFrame(this.step); + }, + + /** + * Stops the requestAnimationFrame or setTimeout from running. + * + * @method Phaser.DOM.RequestAnimationFrame#stop + * @since 3.0.0 + */ + stop: function () + { + this.isRunning = false; + + if (this.isSetTimeOut) + { + clearTimeout(this.timeOutID); + } + else + { + window.cancelAnimationFrame(this.timeOutID); + } + }, + + /** + * Stops the step from running and clears the callback reference. + * + * @method Phaser.DOM.RequestAnimationFrame#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stop(); + + this.callback = NOOP; + } + +}); + +module.exports = RequestAnimationFrame; diff --git a/src/dom/index.js b/src/dom/index.js index b7f1c7f1f..1126acc02 100644 --- a/src/dom/index.js +++ b/src/dom/index.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.DOM - */ - -var Dom = { - - AddToDOM: require('./AddToDOM'), - DOMContentLoaded: require('./DOMContentLoaded'), - GetScreenOrientation: require('./GetScreenOrientation'), - GetTarget: require('./GetTarget'), - ParseXML: require('./ParseXML'), - RemoveFromDOM: require('./RemoveFromDOM'), - RequestAnimationFrame: require('./RequestAnimationFrame') - -}; - -module.exports = Dom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.DOM + */ + +var Dom = { + + AddToDOM: require('./AddToDOM'), + DOMContentLoaded: require('./DOMContentLoaded'), + GetScreenOrientation: require('./GetScreenOrientation'), + GetTarget: require('./GetTarget'), + ParseXML: require('./ParseXML'), + RemoveFromDOM: require('./RemoveFromDOM'), + RequestAnimationFrame: require('./RequestAnimationFrame') + +}; + +module.exports = Dom; diff --git a/src/events/EventEmitter.js b/src/events/EventEmitter.js index 8e16a56e9..842d49f47 100644 --- a/src/events/EventEmitter.js +++ b/src/events/EventEmitter.js @@ -1,178 +1,178 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var EE = require('eventemitter3'); -var PluginCache = require('../plugins/PluginCache'); - -/** - * @classdesc - * EventEmitter is a Scene Systems plugin compatible version of eventemitter3. - * - * @class EventEmitter - * @memberof Phaser.Events - * @constructor - * @since 3.0.0 - */ -var EventEmitter = new Class({ - - Extends: EE, - - initialize: - - function EventEmitter () - { - EE.call(this); - }, - - /** - * Removes all listeners. - * - * @method Phaser.Events.EventEmitter#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - this.removeAllListeners(); - }, - - /** - * Removes all listeners. - * - * @method Phaser.Events.EventEmitter#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.removeAllListeners(); - } - -}); - -/** - * Return an array listing the events for which the emitter has registered listeners. - * - * @method Phaser.Events.EventEmitter#eventNames - * @since 3.0.0 - * - * @return {Array.} - */ - -/** - * Return the listeners registered for a given event. - * - * @method Phaser.Events.EventEmitter#listeners - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * - * @return {Function[]} The registered listeners. - */ - -/** - * Return the number of listeners listening to a given event. - * - * @method Phaser.Events.EventEmitter#listenerCount - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * - * @return {number} The number of listeners. - */ - -/** - * Calls each of the listeners registered for a given event. - * - * @method Phaser.Events.EventEmitter#emit - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * @param {...*} [args] - Additional arguments that will be passed to the event handler. - * - * @return {boolean} `true` if the event had listeners, else `false`. - */ - -/** - * Add a listener for a given event. - * - * @method Phaser.Events.EventEmitter#on - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * @param {function} fn - The listener function. - * @param {*} [context=this] - The context to invoke the listener with. - * - * @return {this} `this`. - */ - -/** - * Add a listener for a given event. - * - * @method Phaser.Events.EventEmitter#addListener - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * @param {function} fn - The listener function. - * @param {*} [context=this] - The context to invoke the listener with. - * - * @return {this} `this`. - */ - -/** - * Add a one-time listener for a given event. - * - * @method Phaser.Events.EventEmitter#once - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * @param {function} fn - The listener function. - * @param {*} [context=this] - The context to invoke the listener with. - * - * @return {this} `this`. - */ - -/** - * Remove the listeners of a given event. - * - * @method Phaser.Events.EventEmitter#removeListener - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * @param {function} [fn] - Only remove the listeners that match this function. - * @param {*} [context] - Only remove the listeners that have this context. - * @param {boolean} [once] - Only remove one-time listeners. - * - * @return {this} `this`. - */ - -/** - * Remove the listeners of a given event. - * - * @method Phaser.Events.EventEmitter#off - * @since 3.0.0 - * - * @param {(string|symbol)} event - The event name. - * @param {function} [fn] - Only remove the listeners that match this function. - * @param {*} [context] - Only remove the listeners that have this context. - * @param {boolean} [once] - Only remove one-time listeners. - * - * @return {this} `this`. - */ - -/** - * Remove all listeners, or those of the specified event. - * - * @method Phaser.Events.EventEmitter#removeAllListeners - * @since 3.0.0 - * - * @param {(string|symbol)} [event] - The event name. - * - * @return {this} `this`. - */ - -PluginCache.register('EventEmitter', EventEmitter, 'events'); - -module.exports = EventEmitter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var EE = require('eventemitter3'); +var PluginCache = require('../plugins/PluginCache'); + +/** + * @classdesc + * EventEmitter is a Scene Systems plugin compatible version of eventemitter3. + * + * @class EventEmitter + * @memberof Phaser.Events + * @constructor + * @since 3.0.0 + */ +var EventEmitter = new Class({ + + Extends: EE, + + initialize: + + function EventEmitter () + { + EE.call(this); + }, + + /** + * Removes all listeners. + * + * @method Phaser.Events.EventEmitter#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAllListeners(); + }, + + /** + * Removes all listeners. + * + * @method Phaser.Events.EventEmitter#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + } + +}); + +/** + * Return an array listing the events for which the emitter has registered listeners. + * + * @method Phaser.Events.EventEmitter#eventNames + * @since 3.0.0 + * + * @return {Array.} + */ + +/** + * Return the listeners registered for a given event. + * + * @method Phaser.Events.EventEmitter#listeners + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * + * @return {Function[]} The registered listeners. + */ + +/** + * Return the number of listeners listening to a given event. + * + * @method Phaser.Events.EventEmitter#listenerCount + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * + * @return {number} The number of listeners. + */ + +/** + * Calls each of the listeners registered for a given event. + * + * @method Phaser.Events.EventEmitter#emit + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {...*} [args] - Additional arguments that will be passed to the event handler. + * + * @return {boolean} `true` if the event had listeners, else `false`. + */ + +/** + * Add a listener for a given event. + * + * @method Phaser.Events.EventEmitter#on + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} fn - The listener function. + * @param {*} [context=this] - The context to invoke the listener with. + * + * @return {this} `this`. + */ + +/** + * Add a listener for a given event. + * + * @method Phaser.Events.EventEmitter#addListener + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} fn - The listener function. + * @param {*} [context=this] - The context to invoke the listener with. + * + * @return {this} `this`. + */ + +/** + * Add a one-time listener for a given event. + * + * @method Phaser.Events.EventEmitter#once + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} fn - The listener function. + * @param {*} [context=this] - The context to invoke the listener with. + * + * @return {this} `this`. + */ + +/** + * Remove the listeners of a given event. + * + * @method Phaser.Events.EventEmitter#removeListener + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} [fn] - Only remove the listeners that match this function. + * @param {*} [context] - Only remove the listeners that have this context. + * @param {boolean} [once] - Only remove one-time listeners. + * + * @return {this} `this`. + */ + +/** + * Remove the listeners of a given event. + * + * @method Phaser.Events.EventEmitter#off + * @since 3.0.0 + * + * @param {(string|symbol)} event - The event name. + * @param {function} [fn] - Only remove the listeners that match this function. + * @param {*} [context] - Only remove the listeners that have this context. + * @param {boolean} [once] - Only remove one-time listeners. + * + * @return {this} `this`. + */ + +/** + * Remove all listeners, or those of the specified event. + * + * @method Phaser.Events.EventEmitter#removeAllListeners + * @since 3.0.0 + * + * @param {(string|symbol)} [event] - The event name. + * + * @return {this} `this`. + */ + +PluginCache.register('EventEmitter', EventEmitter, 'events'); + +module.exports = EventEmitter; diff --git a/src/events/index.js b/src/events/index.js index dd19e5cdd..85c75283e 100644 --- a/src/events/index.js +++ b/src/events/index.js @@ -1,11 +1,11 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Events - */ - -module.exports = { EventEmitter: require('./EventEmitter') }; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Events + */ + +module.exports = { EventEmitter: require('./EventEmitter') }; diff --git a/src/gameobjects/BuildGameObject.js b/src/gameobjects/BuildGameObject.js index e86b6d44f..642ea3049 100644 --- a/src/gameobjects/BuildGameObject.js +++ b/src/gameobjects/BuildGameObject.js @@ -1,122 +1,122 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BlendModes = require('../renderer/BlendModes'); -var GetAdvancedValue = require('../utils/object/GetAdvancedValue'); - -/** - * Builds a Game Object using the provided configuration object. - * - * @function Phaser.GameObjects.BuildGameObject - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - A reference to the Scene. - * @param {Phaser.GameObjects.GameObject} gameObject - The initial GameObject. - * @param {Phaser.Types.GameObjects.GameObjectConfig} config - The config to build the GameObject with. - * - * @return {Phaser.GameObjects.GameObject} The built Game Object. - */ -var BuildGameObject = function (scene, gameObject, config) -{ - // Position - - gameObject.x = GetAdvancedValue(config, 'x', 0); - gameObject.y = GetAdvancedValue(config, 'y', 0); - gameObject.depth = GetAdvancedValue(config, 'depth', 0); - - // Flip - - gameObject.flipX = GetAdvancedValue(config, 'flipX', false); - gameObject.flipY = GetAdvancedValue(config, 'flipY', false); - - // Scale - // Either: { scale: 2 } or { scale: { x: 2, y: 2 }} - - var scale = GetAdvancedValue(config, 'scale', null); - - if (typeof scale === 'number') - { - gameObject.setScale(scale); - } - else if (scale !== null) - { - gameObject.scaleX = GetAdvancedValue(scale, 'x', 1); - gameObject.scaleY = GetAdvancedValue(scale, 'y', 1); - } - - // ScrollFactor - // Either: { scrollFactor: 2 } or { scrollFactor: { x: 2, y: 2 }} - - var scrollFactor = GetAdvancedValue(config, 'scrollFactor', null); - - if (typeof scrollFactor === 'number') - { - gameObject.setScrollFactor(scrollFactor); - } - else if (scrollFactor !== null) - { - gameObject.scrollFactorX = GetAdvancedValue(scrollFactor, 'x', 1); - gameObject.scrollFactorY = GetAdvancedValue(scrollFactor, 'y', 1); - } - - // Rotation - - gameObject.rotation = GetAdvancedValue(config, 'rotation', 0); - - var angle = GetAdvancedValue(config, 'angle', null); - - if (angle !== null) - { - gameObject.angle = angle; - } - - // Alpha - - gameObject.alpha = GetAdvancedValue(config, 'alpha', 1); - - // Origin - // Either: { origin: 0.5 } or { origin: { x: 0.5, y: 0.5 }} - - var origin = GetAdvancedValue(config, 'origin', null); - - if (typeof origin === 'number') - { - gameObject.setOrigin(origin); - } - else if (origin !== null) - { - var ox = GetAdvancedValue(origin, 'x', 0.5); - var oy = GetAdvancedValue(origin, 'y', 0.5); - - gameObject.setOrigin(ox, oy); - } - - // BlendMode - - gameObject.blendMode = GetAdvancedValue(config, 'blendMode', BlendModes.NORMAL); - - // Visible - - gameObject.visible = GetAdvancedValue(config, 'visible', true); - - // Add to Scene - - var add = GetAdvancedValue(config, 'add', true); - - if (add) - { - scene.sys.displayList.add(gameObject); - } - - if (gameObject.preUpdate) - { - scene.sys.updateList.add(gameObject); - } - - return gameObject; -}; - -module.exports = BuildGameObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = require('../renderer/BlendModes'); +var GetAdvancedValue = require('../utils/object/GetAdvancedValue'); + +/** + * Builds a Game Object using the provided configuration object. + * + * @function Phaser.GameObjects.BuildGameObject + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene. + * @param {Phaser.GameObjects.GameObject} gameObject - The initial GameObject. + * @param {Phaser.Types.GameObjects.GameObjectConfig} config - The config to build the GameObject with. + * + * @return {Phaser.GameObjects.GameObject} The built Game Object. + */ +var BuildGameObject = function (scene, gameObject, config) +{ + // Position + + gameObject.x = GetAdvancedValue(config, 'x', 0); + gameObject.y = GetAdvancedValue(config, 'y', 0); + gameObject.depth = GetAdvancedValue(config, 'depth', 0); + + // Flip + + gameObject.flipX = GetAdvancedValue(config, 'flipX', false); + gameObject.flipY = GetAdvancedValue(config, 'flipY', false); + + // Scale + // Either: { scale: 2 } or { scale: { x: 2, y: 2 }} + + var scale = GetAdvancedValue(config, 'scale', null); + + if (typeof scale === 'number') + { + gameObject.setScale(scale); + } + else if (scale !== null) + { + gameObject.scaleX = GetAdvancedValue(scale, 'x', 1); + gameObject.scaleY = GetAdvancedValue(scale, 'y', 1); + } + + // ScrollFactor + // Either: { scrollFactor: 2 } or { scrollFactor: { x: 2, y: 2 }} + + var scrollFactor = GetAdvancedValue(config, 'scrollFactor', null); + + if (typeof scrollFactor === 'number') + { + gameObject.setScrollFactor(scrollFactor); + } + else if (scrollFactor !== null) + { + gameObject.scrollFactorX = GetAdvancedValue(scrollFactor, 'x', 1); + gameObject.scrollFactorY = GetAdvancedValue(scrollFactor, 'y', 1); + } + + // Rotation + + gameObject.rotation = GetAdvancedValue(config, 'rotation', 0); + + var angle = GetAdvancedValue(config, 'angle', null); + + if (angle !== null) + { + gameObject.angle = angle; + } + + // Alpha + + gameObject.alpha = GetAdvancedValue(config, 'alpha', 1); + + // Origin + // Either: { origin: 0.5 } or { origin: { x: 0.5, y: 0.5 }} + + var origin = GetAdvancedValue(config, 'origin', null); + + if (typeof origin === 'number') + { + gameObject.setOrigin(origin); + } + else if (origin !== null) + { + var ox = GetAdvancedValue(origin, 'x', 0.5); + var oy = GetAdvancedValue(origin, 'y', 0.5); + + gameObject.setOrigin(ox, oy); + } + + // BlendMode + + gameObject.blendMode = GetAdvancedValue(config, 'blendMode', BlendModes.NORMAL); + + // Visible + + gameObject.visible = GetAdvancedValue(config, 'visible', true); + + // Add to Scene + + var add = GetAdvancedValue(config, 'add', true); + + if (add) + { + scene.sys.displayList.add(gameObject); + } + + if (gameObject.preUpdate) + { + scene.sys.updateList.add(gameObject); + } + + return gameObject; +}; + +module.exports = BuildGameObject; diff --git a/src/gameobjects/BuildGameObjectAnimation.js b/src/gameobjects/BuildGameObjectAnimation.js index 9ed0283ae..584aac11b 100644 --- a/src/gameobjects/BuildGameObjectAnimation.js +++ b/src/gameobjects/BuildGameObjectAnimation.js @@ -1,83 +1,83 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetAdvancedValue = require('../utils/object/GetAdvancedValue'); - -/** - * Adds an Animation component to a Sprite and populates it based on the given config. - * - * @function Phaser.GameObjects.BuildGameObjectAnimation - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Sprite} sprite - The sprite to add an Animation component to. - * @param {object} config - The animation config. - * - * @return {Phaser.GameObjects.Sprite} The updated Sprite. - */ -var BuildGameObjectAnimation = function (sprite, config) -{ - var animConfig = GetAdvancedValue(config, 'anims', null); - - if (animConfig === null) - { - return sprite; - } - - if (typeof animConfig === 'string') - { - // { anims: 'key' } - sprite.anims.play(animConfig); - } - else if (typeof animConfig === 'object') - { - // { anims: { - // key: string - // startFrame: [string|integer] - // delay: [float] - // repeat: [integer] - // repeatDelay: [float] - // yoyo: [boolean] - // play: [boolean] - // delayedPlay: [boolean] - // } - // } - - var anims = sprite.anims; - - var key = GetAdvancedValue(animConfig, 'key', undefined); - var startFrame = GetAdvancedValue(animConfig, 'startFrame', undefined); - - var delay = GetAdvancedValue(animConfig, 'delay', 0); - var repeat = GetAdvancedValue(animConfig, 'repeat', 0); - var repeatDelay = GetAdvancedValue(animConfig, 'repeatDelay', 0); - var yoyo = GetAdvancedValue(animConfig, 'yoyo', false); - - var play = GetAdvancedValue(animConfig, 'play', false); - var delayedPlay = GetAdvancedValue(animConfig, 'delayedPlay', 0); - - anims.setDelay(delay); - anims.setRepeat(repeat); - anims.setRepeatDelay(repeatDelay); - anims.setYoyo(yoyo); - - if (play) - { - anims.play(key, startFrame); - } - else if (delayedPlay > 0) - { - anims.delayedPlay(delayedPlay, key, startFrame); - } - else - { - anims.load(key); - } - } - - return sprite; -}; - -module.exports = BuildGameObjectAnimation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetAdvancedValue = require('../utils/object/GetAdvancedValue'); + +/** + * Adds an Animation component to a Sprite and populates it based on the given config. + * + * @function Phaser.GameObjects.BuildGameObjectAnimation + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Sprite} sprite - The sprite to add an Animation component to. + * @param {object} config - The animation config. + * + * @return {Phaser.GameObjects.Sprite} The updated Sprite. + */ +var BuildGameObjectAnimation = function (sprite, config) +{ + var animConfig = GetAdvancedValue(config, 'anims', null); + + if (animConfig === null) + { + return sprite; + } + + if (typeof animConfig === 'string') + { + // { anims: 'key' } + sprite.anims.play(animConfig); + } + else if (typeof animConfig === 'object') + { + // { anims: { + // key: string + // startFrame: [string|integer] + // delay: [float] + // repeat: [integer] + // repeatDelay: [float] + // yoyo: [boolean] + // play: [boolean] + // delayedPlay: [boolean] + // } + // } + + var anims = sprite.anims; + + var key = GetAdvancedValue(animConfig, 'key', undefined); + var startFrame = GetAdvancedValue(animConfig, 'startFrame', undefined); + + var delay = GetAdvancedValue(animConfig, 'delay', 0); + var repeat = GetAdvancedValue(animConfig, 'repeat', 0); + var repeatDelay = GetAdvancedValue(animConfig, 'repeatDelay', 0); + var yoyo = GetAdvancedValue(animConfig, 'yoyo', false); + + var play = GetAdvancedValue(animConfig, 'play', false); + var delayedPlay = GetAdvancedValue(animConfig, 'delayedPlay', 0); + + anims.setDelay(delay); + anims.setRepeat(repeat); + anims.setRepeatDelay(repeatDelay); + anims.setYoyo(yoyo); + + if (play) + { + anims.play(key, startFrame); + } + else if (delayedPlay > 0) + { + anims.delayedPlay(delayedPlay, key, startFrame); + } + else + { + anims.load(key); + } + } + + return sprite; +}; + +module.exports = BuildGameObjectAnimation; diff --git a/src/gameobjects/DisplayList.js b/src/gameobjects/DisplayList.js index fc4437411..125f9b4c4 100644 --- a/src/gameobjects/DisplayList.js +++ b/src/gameobjects/DisplayList.js @@ -1,199 +1,199 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var List = require('../structs/List'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); -var StableSort = require('../utils/array/StableSort'); - -/** - * @classdesc - * The Display List plugin. - * - * Display Lists belong to a Scene and maintain the list of Game Objects to render every frame. - * - * Some of these Game Objects may also be part of the Scene's [Update List]{@link Phaser.GameObjects.UpdateList}, for updating. - * - * @class DisplayList - * @extends Phaser.Structs.List. - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that this Display List belongs to. - */ -var DisplayList = new Class({ - - Extends: List, - - initialize: - - function DisplayList (scene) - { - List.call(this, scene); - - /** - * The flag the determines whether Game Objects should be sorted when `depthSort()` is called. - * - * @name Phaser.GameObjects.DisplayList#sortChildrenFlag - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.sortChildrenFlag = false; - - /** - * The Scene that this Display List belongs to. - * - * @name Phaser.GameObjects.DisplayList#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The Scene's Systems. - * - * @name Phaser.GameObjects.DisplayList#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.DisplayList#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.DisplayList#start - * @private - * @since 3.5.0 - */ - start: function () - { - this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * Force a sort of the display list on the next call to depthSort. - * - * @method Phaser.GameObjects.DisplayList#queueDepthSort - * @since 3.0.0 - */ - queueDepthSort: function () - { - this.sortChildrenFlag = true; - }, - - /** - * Immediately sorts the display list if the flag is set. - * - * @method Phaser.GameObjects.DisplayList#depthSort - * @since 3.0.0 - */ - depthSort: function () - { - if (this.sortChildrenFlag) - { - StableSort.inplace(this.list, this.sortByDepth); - - this.sortChildrenFlag = false; - } - }, - - /** - * Compare the depth of two Game Objects. - * - * @method Phaser.GameObjects.DisplayList#sortByDepth - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} childA - The first Game Object. - * @param {Phaser.GameObjects.GameObject} childB - The second Game Object. - * - * @return {integer} The difference between the depths of each Game Object. - */ - sortByDepth: function (childA, childB) - { - return childA._depth - childB._depth; - }, - - /** - * Returns an array which contains all objects currently on the Display List. - * This is a reference to the main list array, not a copy of it, so be careful not to modify it. - * - * @method Phaser.GameObjects.DisplayList#getChildren - * @since 3.12.0 - * - * @return {Phaser.GameObjects.GameObject[]} The group members. - */ - getChildren: function () - { - return this.list; - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.GameObjects.DisplayList#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - var i = this.list.length; - - while (i--) - { - this.list[i].destroy(true); - } - - this.list.length = 0; - - this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.GameObjects.DisplayList#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('DisplayList', DisplayList, 'displayList'); - -module.exports = DisplayList; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var List = require('../structs/List'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); +var StableSort = require('../utils/array/StableSort'); + +/** + * @classdesc + * The Display List plugin. + * + * Display Lists belong to a Scene and maintain the list of Game Objects to render every frame. + * + * Some of these Game Objects may also be part of the Scene's [Update List]{@link Phaser.GameObjects.UpdateList}, for updating. + * + * @class DisplayList + * @extends Phaser.Structs.List. + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this Display List belongs to. + */ +var DisplayList = new Class({ + + Extends: List, + + initialize: + + function DisplayList (scene) + { + List.call(this, scene); + + /** + * The flag the determines whether Game Objects should be sorted when `depthSort()` is called. + * + * @name Phaser.GameObjects.DisplayList#sortChildrenFlag + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.sortChildrenFlag = false; + + /** + * The Scene that this Display List belongs to. + * + * @name Phaser.GameObjects.DisplayList#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene's Systems. + * + * @name Phaser.GameObjects.DisplayList#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.DisplayList#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.DisplayList#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Force a sort of the display list on the next call to depthSort. + * + * @method Phaser.GameObjects.DisplayList#queueDepthSort + * @since 3.0.0 + */ + queueDepthSort: function () + { + this.sortChildrenFlag = true; + }, + + /** + * Immediately sorts the display list if the flag is set. + * + * @method Phaser.GameObjects.DisplayList#depthSort + * @since 3.0.0 + */ + depthSort: function () + { + if (this.sortChildrenFlag) + { + StableSort.inplace(this.list, this.sortByDepth); + + this.sortChildrenFlag = false; + } + }, + + /** + * Compare the depth of two Game Objects. + * + * @method Phaser.GameObjects.DisplayList#sortByDepth + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} childA - The first Game Object. + * @param {Phaser.GameObjects.GameObject} childB - The second Game Object. + * + * @return {integer} The difference between the depths of each Game Object. + */ + sortByDepth: function (childA, childB) + { + return childA._depth - childB._depth; + }, + + /** + * Returns an array which contains all objects currently on the Display List. + * This is a reference to the main list array, not a copy of it, so be careful not to modify it. + * + * @method Phaser.GameObjects.DisplayList#getChildren + * @since 3.12.0 + * + * @return {Phaser.GameObjects.GameObject[]} The group members. + */ + getChildren: function () + { + return this.list; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.DisplayList#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var i = this.list.length; + + while (i--) + { + this.list[i].destroy(true); + } + + this.list.length = 0; + + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.DisplayList#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('DisplayList', DisplayList, 'displayList'); + +module.exports = DisplayList; diff --git a/src/gameobjects/GameObject.js b/src/gameobjects/GameObject.js index 88e1c03ba..69b594049 100644 --- a/src/gameobjects/GameObject.js +++ b/src/gameobjects/GameObject.js @@ -1,635 +1,635 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var ComponentsToJSON = require('./components/ToJSON'); -var DataManager = require('../data/DataManager'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); - -/** - * @classdesc - * The base class that all Game Objects extend. - * You don't create GameObjects directly and they cannot be added to the display list. - * Instead, use them as the base for your own custom classes. - * - * @class GameObject - * @memberof Phaser.GameObjects - * @extends Phaser.Events.EventEmitter - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. - * @param {string} type - A textual representation of the type of Game Object, i.e. `sprite`. - */ -var GameObject = new Class({ - - Extends: EventEmitter, - - initialize: - - function GameObject (scene, type) - { - EventEmitter.call(this); - - /** - * The Scene to which this Game Object belongs. - * Game Objects can only belong to one Scene. - * - * @name Phaser.GameObjects.GameObject#scene - * @type {Phaser.Scene} - * @protected - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A textual representation of this Game Object, i.e. `sprite`. - * Used internally by Phaser but is available for your own custom classes to populate. - * - * @name Phaser.GameObjects.GameObject#type - * @type {string} - * @since 3.0.0 - */ - this.type = type; - - /** - * The current state of this Game Object. - * - * Phaser itself will never modify this value, although plugins may do so. - * - * Use this property to track the state of a Game Object during its lifetime. For example, it could change from - * a state of 'moving', to 'attacking', to 'dead'. The state value should be an integer (ideally mapped to a constant - * in your game code), or a string. These are recommended to keep it light and simple, with fast comparisons. - * If you need to store complex data about your Game Object, look at using the Data Component instead. - * - * @name Phaser.GameObjects.GameObject#state - * @type {(integer|string)} - * @since 3.16.0 - */ - this.state = 0; - - /** - * The parent Container of this Game Object, if it has one. - * - * @name Phaser.GameObjects.GameObject#parentContainer - * @type {Phaser.GameObjects.Container} - * @since 3.4.0 - */ - this.parentContainer = null; - - /** - * The name of this Game Object. - * Empty by default and never populated by Phaser, this is left for developers to use. - * - * @name Phaser.GameObjects.GameObject#name - * @type {string} - * @default '' - * @since 3.0.0 - */ - this.name = ''; - - /** - * The active state of this Game Object. - * A Game Object with an active state of `true` is processed by the Scenes UpdateList, if added to it. - * An active object is one which is having its logic and internal systems updated. - * - * @name Phaser.GameObjects.GameObject#active - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.active = true; - - /** - * The Tab Index of the Game Object. - * Reserved for future use by plugins and the Input Manager. - * - * @name Phaser.GameObjects.GameObject#tabIndex - * @type {integer} - * @default -1 - * @since 3.0.0 - */ - this.tabIndex = -1; - - /** - * A Data Manager. - * It allows you to store, query and get key/value paired information specific to this Game Object. - * `null` by default. Automatically created if you use `getData` or `setData` or `setDataEnabled`. - * - * @name Phaser.GameObjects.GameObject#data - * @type {Phaser.Data.DataManager} - * @default null - * @since 3.0.0 - */ - this.data = null; - - /** - * The flags that are compared against `RENDER_MASK` to determine if this Game Object will render or not. - * The bits are 0001 | 0010 | 0100 | 1000 set by the components Visible, Alpha, Transform and Texture respectively. - * If those components are not used by your custom class then you can use this bitmask as you wish. - * - * @name Phaser.GameObjects.GameObject#renderFlags - * @type {integer} - * @default 15 - * @since 3.0.0 - */ - this.renderFlags = 15; - - /** - * A bitmask that controls if this Game Object is drawn by a Camera or not. - * Not usually set directly, instead call `Camera.ignore`, however you can - * set this property directly using the Camera.id property: - * - * @example - * this.cameraFilter |= camera.id - * - * @name Phaser.GameObjects.GameObject#cameraFilter - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.cameraFilter = 0; - - /** - * If this Game Object is enabled for input then this property will contain an InteractiveObject instance. - * Not usually set directly. Instead call `GameObject.setInteractive()`. - * - * @name Phaser.GameObjects.GameObject#input - * @type {?Phaser.Types.Input.InteractiveObject} - * @default null - * @since 3.0.0 - */ - this.input = null; - - /** - * If this Game Object is enabled for Arcade or Matter Physics then this property will contain a reference to a Physics Body. - * - * @name Phaser.GameObjects.GameObject#body - * @type {?(object|Phaser.Physics.Arcade.Body|MatterJS.BodyType)} - * @default null - * @since 3.0.0 - */ - this.body = null; - - /** - * This Game Object will ignore all calls made to its destroy method if this flag is set to `true`. - * This includes calls that may come from a Group, Container or the Scene itself. - * While it allows you to persist a Game Object across Scenes, please understand you are entirely - * responsible for managing references to and from this Game Object. - * - * @name Phaser.GameObjects.GameObject#ignoreDestroy - * @type {boolean} - * @default false - * @since 3.5.0 - */ - this.ignoreDestroy = false; - - // Tell the Scene to re-sort the children - scene.sys.queueDepthSort(); - }, - - /** - * Sets the `active` property of this Game Object and returns this Game Object for further chaining. - * A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. - * - * @method Phaser.GameObjects.GameObject#setActive - * @since 3.0.0 - * - * @param {boolean} value - True if this Game Object should be set as active, false if not. - * - * @return {this} This GameObject. - */ - setActive: function (value) - { - this.active = value; - - return this; - }, - - /** - * Sets the `name` property of this Game Object and returns this Game Object for further chaining. - * The `name` property is not populated by Phaser and is presented for your own use. - * - * @method Phaser.GameObjects.GameObject#setName - * @since 3.0.0 - * - * @param {string} value - The name to be given to this Game Object. - * - * @return {this} This GameObject. - */ - setName: function (value) - { - this.name = value; - - return this; - }, - - /** - * Sets the current state of this Game Object. - * - * Phaser itself will never modify the State of a Game Object, although plugins may do so. - * - * For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. - * The state value should typically be an integer (ideally mapped to a constant - * in your game code), but could also be a string. It is recommended to keep it light and simple. - * If you need to store complex data about your Game Object, look at using the Data Component instead. - * - * @method Phaser.GameObjects.GameObject#setState - * @since 3.16.0 - * - * @param {(integer|string)} value - The state of the Game Object. - * - * @return {this} This GameObject. - */ - setState: function (value) - { - this.state = value; - - return this; - }, - - /** - * Adds a Data Manager component to this Game Object. - * - * @method Phaser.GameObjects.GameObject#setDataEnabled - * @since 3.0.0 - * @see Phaser.Data.DataManager - * - * @return {this} This GameObject. - */ - setDataEnabled: function () - { - if (!this.data) - { - this.data = new DataManager(this); - } - - return this; - }, - - /** - * Allows you to store a key value pair within this Game Objects Data Manager. - * - * If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled - * before setting the value. - * - * If the key doesn't already exist in the Data Manager then it is created. - * - * ```javascript - * sprite.setData('name', 'Red Gem Stone'); - * ``` - * - * You can also pass in an object of key value pairs as the first argument: - * - * ```javascript - * sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); - * ``` - * - * To get a value back again you can call `getData`: - * - * ```javascript - * sprite.getData('gold'); - * ``` - * - * Or you can access the value directly via the `values` property, where it works like any other variable: - * - * ```javascript - * sprite.data.values.gold += 50; - * ``` - * - * When the value is first set, a `setdata` event is emitted from this Game Object. - * - * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. - * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. - * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. - * - * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. - * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. - * - * @method Phaser.GameObjects.GameObject#setData - * @since 3.0.0 - * - * @param {(string|object)} key - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. - * @param {*} [data] - The value to set for the given key. If an object is provided as the key this argument is ignored. - * - * @return {this} This GameObject. - */ - setData: function (key, value) - { - if (!this.data) - { - this.data = new DataManager(this); - } - - this.data.set(key, value); - - return this; - }, - - /** - * Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. - * - * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: - * - * ```javascript - * sprite.getData('gold'); - * ``` - * - * Or access the value directly: - * - * ```javascript - * sprite.data.values.gold; - * ``` - * - * You can also pass in an array of keys, in which case an array of values will be returned: - * - * ```javascript - * sprite.getData([ 'gold', 'armor', 'health' ]); - * ``` - * - * This approach is useful for destructuring arrays in ES6. - * - * @method Phaser.GameObjects.GameObject#getData - * @since 3.0.0 - * - * @param {(string|string[])} key - The key of the value to retrieve, or an array of keys. - * - * @return {*} The value belonging to the given key, or an array of values, the order of which will match the input array. - */ - getData: function (key) - { - if (!this.data) - { - this.data = new DataManager(this); - } - - return this.data.get(key); - }, - - /** - * 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. - * - * @method Phaser.GameObjects.GameObject#setInteractive - * @since 3.0.0 - * - * @param {(Phaser.Types.Input.InputConfiguration|any)} [shape] - 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} [callback] - A callback to be invoked when the Game Object is interacted with. 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. - */ - setInteractive: function (shape, callback, dropZone) - { - this.scene.sys.input.enable(this, shape, callback, dropZone); - - return this; - }, - - /** - * If this Game Object has previously been enabled for input, this will disable it. - * - * An object that is disabled for input stops processing or being considered for - * input events, but can be turned back on again at any time by simply calling - * `setInteractive()` with no arguments provided. - * - * If want to completely remove interaction from this Game Object then use `removeInteractive` instead. - * - * @method Phaser.GameObjects.GameObject#disableInteractive - * @since 3.7.0 - * - * @return {this} This GameObject. - */ - disableInteractive: function () - { - if (this.input) - { - this.input.enabled = false; - } - - return this; - }, - - /** - * If this Game Object has previously been enabled for input, this will queue it - * for removal, causing it to no longer be interactive. The removal happens on - * the next game step, it is not immediate. - * - * The Interactive Object that was assigned to this Game Object will be destroyed, - * removed from the Input Manager and cleared from this Game Object. - * - * If you wish to re-enable this Game Object at a later date you will need to - * re-create its InteractiveObject by calling `setInteractive` again. - * - * If you wish to only temporarily stop an object from receiving input then use - * `disableInteractive` instead, as that toggles the interactive state, where-as - * this erases it completely. - * - * If you wish to resize a hit area, don't remove and then set it as being - * interactive. Instead, access the hitarea object directly and resize the shape - * being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the - * shape is a Rectangle, which it is by default.) - * - * @method Phaser.GameObjects.GameObject#removeInteractive - * @since 3.7.0 - * - * @return {this} This GameObject. - */ - removeInteractive: function () - { - this.scene.sys.input.clear(this); - - this.input = undefined; - - return this; - }, - - /** - * To be overridden by custom GameObjects. Allows base objects to be used in a Pool. - * - * @method Phaser.GameObjects.GameObject#update - * @since 3.0.0 - * - * @param {...*} [args] - args - */ - update: function () - { - }, - - /** - * Returns a JSON representation of the Game Object. - * - * @method Phaser.GameObjects.GameObject#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. - */ - toJSON: function () - { - return ComponentsToJSON(this); - }, - - /** - * Compares the renderMask with the renderFlags to see if this Game Object will render or not. - * Also checks the Game Object against the given Cameras exclusion list. - * - * @method Phaser.GameObjects.GameObject#willRender - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object. - * - * @return {boolean} True if the Game Object should be rendered, otherwise false. - */ - willRender: function (camera) - { - return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id))); - }, - - /** - * Returns an array containing the display list index of either this Game Object, or if it has one, - * its parent Container. It then iterates up through all of the parent containers until it hits the - * root of the display list (which is index 0 in the returned array). - * - * Used internally by the InputPlugin but also useful if you wish to find out the display depth of - * this Game Object and all of its ancestors. - * - * @method Phaser.GameObjects.GameObject#getIndexList - * @since 3.4.0 - * - * @return {integer[]} An array of display list position indexes. - */ - getIndexList: function () - { - // eslint-disable-next-line consistent-this - var child = this; - var parent = this.parentContainer; - - var indexes = []; - - while (parent) - { - // indexes.unshift([parent.getIndex(child), parent.name]); - indexes.unshift(parent.getIndex(child)); - - child = parent; - - if (!parent.parentContainer) - { - break; - } - else - { - parent = parent.parentContainer; - } - } - - // indexes.unshift([this.scene.sys.displayList.getIndex(child), 'root']); - indexes.unshift(this.scene.sys.displayList.getIndex(child)); - - return indexes; - }, - - /** - * Destroys this Game Object removing it from the Display List and Update List and - * severing all ties to parent resources. - * - * Also removes itself from the Input Manager and Physics Manager if previously enabled. - * - * Use this to remove a Game Object from your game if you don't ever plan to use it again. - * As long as no reference to it exists within your own code it should become free for - * garbage collection by the browser. - * - * If you just want to temporarily disable an object then look at using the - * Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. - * - * @method Phaser.GameObjects.GameObject#destroy - * @fires Phaser.GameObjects.Events#DESTROY - * @since 3.0.0 - * - * @param {boolean} [fromScene=false] - Is this Game Object being destroyed as the result of a Scene shutdown? - */ - destroy: function (fromScene) - { - if (fromScene === undefined) { fromScene = false; } - - // This Game Object has already been destroyed - if (!this.scene || this.ignoreDestroy) - { - return; - } - - if (this.preDestroy) - { - this.preDestroy.call(this); - } - - this.emit(Events.DESTROY, this); - - var sys = this.scene.sys; - - if (!fromScene) - { - sys.displayList.remove(this); - sys.updateList.remove(this); - } - - if (this.input) - { - sys.input.clear(this); - this.input = undefined; - } - - if (this.data) - { - this.data.destroy(); - - this.data = undefined; - } - - if (this.body) - { - this.body.destroy(); - this.body = undefined; - } - - // Tell the Scene to re-sort the children - if (!fromScene) - { - sys.queueDepthSort(); - } - - this.active = false; - this.visible = false; - - this.scene = undefined; - - this.parentContainer = undefined; - - this.removeAllListeners(); - } - -}); - -/** - * The bitmask that `GameObject.renderFlags` is compared against to determine if the Game Object will render or not. - * - * @constant {integer} RENDER_MASK - * @memberof Phaser.GameObjects.GameObject - * @default - */ -GameObject.RENDER_MASK = 15; - -module.exports = GameObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var ComponentsToJSON = require('./components/ToJSON'); +var DataManager = require('../data/DataManager'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); + +/** + * @classdesc + * The base class that all Game Objects extend. + * You don't create GameObjects directly and they cannot be added to the display list. + * Instead, use them as the base for your own custom classes. + * + * @class GameObject + * @memberof Phaser.GameObjects + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. + * @param {string} type - A textual representation of the type of Game Object, i.e. `sprite`. + */ +var GameObject = new Class({ + + Extends: EventEmitter, + + initialize: + + function GameObject (scene, type) + { + EventEmitter.call(this); + + /** + * The Scene to which this Game Object belongs. + * Game Objects can only belong to one Scene. + * + * @name Phaser.GameObjects.GameObject#scene + * @type {Phaser.Scene} + * @protected + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A textual representation of this Game Object, i.e. `sprite`. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.GameObjects.GameObject#type + * @type {string} + * @since 3.0.0 + */ + this.type = type; + + /** + * The current state of this Game Object. + * + * Phaser itself will never modify this value, although plugins may do so. + * + * Use this property to track the state of a Game Object during its lifetime. For example, it could change from + * a state of 'moving', to 'attacking', to 'dead'. The state value should be an integer (ideally mapped to a constant + * in your game code), or a string. These are recommended to keep it light and simple, with fast comparisons. + * If you need to store complex data about your Game Object, look at using the Data Component instead. + * + * @name Phaser.GameObjects.GameObject#state + * @type {(integer|string)} + * @since 3.16.0 + */ + this.state = 0; + + /** + * The parent Container of this Game Object, if it has one. + * + * @name Phaser.GameObjects.GameObject#parentContainer + * @type {Phaser.GameObjects.Container} + * @since 3.4.0 + */ + this.parentContainer = null; + + /** + * The name of this Game Object. + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.GameObjects.GameObject#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * The active state of this Game Object. + * A Game Object with an active state of `true` is processed by the Scenes UpdateList, if added to it. + * An active object is one which is having its logic and internal systems updated. + * + * @name Phaser.GameObjects.GameObject#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * The Tab Index of the Game Object. + * Reserved for future use by plugins and the Input Manager. + * + * @name Phaser.GameObjects.GameObject#tabIndex + * @type {integer} + * @default -1 + * @since 3.0.0 + */ + this.tabIndex = -1; + + /** + * A Data Manager. + * It allows you to store, query and get key/value paired information specific to this Game Object. + * `null` by default. Automatically created if you use `getData` or `setData` or `setDataEnabled`. + * + * @name Phaser.GameObjects.GameObject#data + * @type {Phaser.Data.DataManager} + * @default null + * @since 3.0.0 + */ + this.data = null; + + /** + * The flags that are compared against `RENDER_MASK` to determine if this Game Object will render or not. + * The bits are 0001 | 0010 | 0100 | 1000 set by the components Visible, Alpha, Transform and Texture respectively. + * If those components are not used by your custom class then you can use this bitmask as you wish. + * + * @name Phaser.GameObjects.GameObject#renderFlags + * @type {integer} + * @default 15 + * @since 3.0.0 + */ + this.renderFlags = 15; + + /** + * A bitmask that controls if this Game Object is drawn by a Camera or not. + * Not usually set directly, instead call `Camera.ignore`, however you can + * set this property directly using the Camera.id property: + * + * @example + * this.cameraFilter |= camera.id + * + * @name Phaser.GameObjects.GameObject#cameraFilter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.cameraFilter = 0; + + /** + * If this Game Object is enabled for input then this property will contain an InteractiveObject instance. + * Not usually set directly. Instead call `GameObject.setInteractive()`. + * + * @name Phaser.GameObjects.GameObject#input + * @type {?Phaser.Types.Input.InteractiveObject} + * @default null + * @since 3.0.0 + */ + this.input = null; + + /** + * If this Game Object is enabled for Arcade or Matter Physics then this property will contain a reference to a Physics Body. + * + * @name Phaser.GameObjects.GameObject#body + * @type {?(object|Phaser.Physics.Arcade.Body|MatterJS.BodyType)} + * @default null + * @since 3.0.0 + */ + this.body = null; + + /** + * This Game Object will ignore all calls made to its destroy method if this flag is set to `true`. + * This includes calls that may come from a Group, Container or the Scene itself. + * While it allows you to persist a Game Object across Scenes, please understand you are entirely + * responsible for managing references to and from this Game Object. + * + * @name Phaser.GameObjects.GameObject#ignoreDestroy + * @type {boolean} + * @default false + * @since 3.5.0 + */ + this.ignoreDestroy = false; + + // Tell the Scene to re-sort the children + scene.sys.queueDepthSort(); + }, + + /** + * Sets the `active` property of this Game Object and returns this Game Object for further chaining. + * A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. + * + * @method Phaser.GameObjects.GameObject#setActive + * @since 3.0.0 + * + * @param {boolean} value - True if this Game Object should be set as active, false if not. + * + * @return {this} This GameObject. + */ + setActive: function (value) + { + this.active = value; + + return this; + }, + + /** + * Sets the `name` property of this Game Object and returns this Game Object for further chaining. + * The `name` property is not populated by Phaser and is presented for your own use. + * + * @method Phaser.GameObjects.GameObject#setName + * @since 3.0.0 + * + * @param {string} value - The name to be given to this Game Object. + * + * @return {this} This GameObject. + */ + setName: function (value) + { + this.name = value; + + return this; + }, + + /** + * Sets the current state of this Game Object. + * + * Phaser itself will never modify the State of a Game Object, although plugins may do so. + * + * For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. + * The state value should typically be an integer (ideally mapped to a constant + * in your game code), but could also be a string. It is recommended to keep it light and simple. + * If you need to store complex data about your Game Object, look at using the Data Component instead. + * + * @method Phaser.GameObjects.GameObject#setState + * @since 3.16.0 + * + * @param {(integer|string)} value - The state of the Game Object. + * + * @return {this} This GameObject. + */ + setState: function (value) + { + this.state = value; + + return this; + }, + + /** + * Adds a Data Manager component to this Game Object. + * + * @method Phaser.GameObjects.GameObject#setDataEnabled + * @since 3.0.0 + * @see Phaser.Data.DataManager + * + * @return {this} This GameObject. + */ + setDataEnabled: function () + { + if (!this.data) + { + this.data = new DataManager(this); + } + + return this; + }, + + /** + * Allows you to store a key value pair within this Game Objects Data Manager. + * + * If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled + * before setting the value. + * + * If the key doesn't already exist in the Data Manager then it is created. + * + * ```javascript + * sprite.setData('name', 'Red Gem Stone'); + * ``` + * + * You can also pass in an object of key value pairs as the first argument: + * + * ```javascript + * sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); + * ``` + * + * To get a value back again you can call `getData`: + * + * ```javascript + * sprite.getData('gold'); + * ``` + * + * Or you can access the value directly via the `values` property, where it works like any other variable: + * + * ```javascript + * sprite.data.values.gold += 50; + * ``` + * + * When the value is first set, a `setdata` event is emitted from this Game Object. + * + * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. + * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. + * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. + * + * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * + * @method Phaser.GameObjects.GameObject#setData + * @since 3.0.0 + * + * @param {(string|object)} key - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. + * @param {*} [data] - The value to set for the given key. If an object is provided as the key this argument is ignored. + * + * @return {this} This GameObject. + */ + setData: function (key, value) + { + if (!this.data) + { + this.data = new DataManager(this); + } + + this.data.set(key, value); + + return this; + }, + + /** + * Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. + * + * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: + * + * ```javascript + * sprite.getData('gold'); + * ``` + * + * Or access the value directly: + * + * ```javascript + * sprite.data.values.gold; + * ``` + * + * You can also pass in an array of keys, in which case an array of values will be returned: + * + * ```javascript + * sprite.getData([ 'gold', 'armor', 'health' ]); + * ``` + * + * This approach is useful for destructuring arrays in ES6. + * + * @method Phaser.GameObjects.GameObject#getData + * @since 3.0.0 + * + * @param {(string|string[])} key - The key of the value to retrieve, or an array of keys. + * + * @return {*} The value belonging to the given key, or an array of values, the order of which will match the input array. + */ + getData: function (key) + { + if (!this.data) + { + this.data = new DataManager(this); + } + + return this.data.get(key); + }, + + /** + * 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. + * + * @method Phaser.GameObjects.GameObject#setInteractive + * @since 3.0.0 + * + * @param {(Phaser.Types.Input.InputConfiguration|any)} [shape] - 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} [callback] - A callback to be invoked when the Game Object is interacted with. 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. + */ + setInteractive: function (shape, callback, dropZone) + { + this.scene.sys.input.enable(this, shape, callback, dropZone); + + return this; + }, + + /** + * If this Game Object has previously been enabled for input, this will disable it. + * + * An object that is disabled for input stops processing or being considered for + * input events, but can be turned back on again at any time by simply calling + * `setInteractive()` with no arguments provided. + * + * If want to completely remove interaction from this Game Object then use `removeInteractive` instead. + * + * @method Phaser.GameObjects.GameObject#disableInteractive + * @since 3.7.0 + * + * @return {this} This GameObject. + */ + disableInteractive: function () + { + if (this.input) + { + this.input.enabled = false; + } + + return this; + }, + + /** + * If this Game Object has previously been enabled for input, this will queue it + * for removal, causing it to no longer be interactive. The removal happens on + * the next game step, it is not immediate. + * + * The Interactive Object that was assigned to this Game Object will be destroyed, + * removed from the Input Manager and cleared from this Game Object. + * + * If you wish to re-enable this Game Object at a later date you will need to + * re-create its InteractiveObject by calling `setInteractive` again. + * + * If you wish to only temporarily stop an object from receiving input then use + * `disableInteractive` instead, as that toggles the interactive state, where-as + * this erases it completely. + * + * If you wish to resize a hit area, don't remove and then set it as being + * interactive. Instead, access the hitarea object directly and resize the shape + * being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the + * shape is a Rectangle, which it is by default.) + * + * @method Phaser.GameObjects.GameObject#removeInteractive + * @since 3.7.0 + * + * @return {this} This GameObject. + */ + removeInteractive: function () + { + this.scene.sys.input.clear(this); + + this.input = undefined; + + return this; + }, + + /** + * To be overridden by custom GameObjects. Allows base objects to be used in a Pool. + * + * @method Phaser.GameObjects.GameObject#update + * @since 3.0.0 + * + * @param {...*} [args] - args + */ + update: function () + { + }, + + /** + * Returns a JSON representation of the Game Object. + * + * @method Phaser.GameObjects.GameObject#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ + toJSON: function () + { + return ComponentsToJSON(this); + }, + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * Also checks the Game Object against the given Cameras exclusion list. + * + * @method Phaser.GameObjects.GameObject#willRender + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object. + * + * @return {boolean} True if the Game Object should be rendered, otherwise false. + */ + willRender: function (camera) + { + return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id))); + }, + + /** + * Returns an array containing the display list index of either this Game Object, or if it has one, + * its parent Container. It then iterates up through all of the parent containers until it hits the + * root of the display list (which is index 0 in the returned array). + * + * Used internally by the InputPlugin but also useful if you wish to find out the display depth of + * this Game Object and all of its ancestors. + * + * @method Phaser.GameObjects.GameObject#getIndexList + * @since 3.4.0 + * + * @return {integer[]} An array of display list position indexes. + */ + getIndexList: function () + { + // eslint-disable-next-line consistent-this + var child = this; + var parent = this.parentContainer; + + var indexes = []; + + while (parent) + { + // indexes.unshift([parent.getIndex(child), parent.name]); + indexes.unshift(parent.getIndex(child)); + + child = parent; + + if (!parent.parentContainer) + { + break; + } + else + { + parent = parent.parentContainer; + } + } + + // indexes.unshift([this.scene.sys.displayList.getIndex(child), 'root']); + indexes.unshift(this.scene.sys.displayList.getIndex(child)); + + return indexes; + }, + + /** + * Destroys this Game Object removing it from the Display List and Update List and + * severing all ties to parent resources. + * + * Also removes itself from the Input Manager and Physics Manager if previously enabled. + * + * Use this to remove a Game Object from your game if you don't ever plan to use it again. + * As long as no reference to it exists within your own code it should become free for + * garbage collection by the browser. + * + * If you just want to temporarily disable an object then look at using the + * Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. + * + * @method Phaser.GameObjects.GameObject#destroy + * @fires Phaser.GameObjects.Events#DESTROY + * @since 3.0.0 + * + * @param {boolean} [fromScene=false] - Is this Game Object being destroyed as the result of a Scene shutdown? + */ + destroy: function (fromScene) + { + if (fromScene === undefined) { fromScene = false; } + + // This Game Object has already been destroyed + if (!this.scene || this.ignoreDestroy) + { + return; + } + + if (this.preDestroy) + { + this.preDestroy.call(this); + } + + this.emit(Events.DESTROY, this); + + var sys = this.scene.sys; + + if (!fromScene) + { + sys.displayList.remove(this); + sys.updateList.remove(this); + } + + if (this.input) + { + sys.input.clear(this); + this.input = undefined; + } + + if (this.data) + { + this.data.destroy(); + + this.data = undefined; + } + + if (this.body) + { + this.body.destroy(); + this.body = undefined; + } + + // Tell the Scene to re-sort the children + if (!fromScene) + { + sys.queueDepthSort(); + } + + this.active = false; + this.visible = false; + + this.scene = undefined; + + this.parentContainer = undefined; + + this.removeAllListeners(); + } + +}); + +/** + * The bitmask that `GameObject.renderFlags` is compared against to determine if the Game Object will render or not. + * + * @constant {integer} RENDER_MASK + * @memberof Phaser.GameObjects.GameObject + * @default + */ +GameObject.RENDER_MASK = 15; + +module.exports = GameObject; diff --git a/src/gameobjects/GameObjectCreator.js b/src/gameobjects/GameObjectCreator.js index 368bf3656..9a39b7063 100644 --- a/src/gameobjects/GameObjectCreator.js +++ b/src/gameobjects/GameObjectCreator.js @@ -1,162 +1,162 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); - -/** - * @classdesc - * The Game Object Creator is a Scene plugin that allows you to quickly create many common - * types of Game Objects and return them. Unlike the Game Object Factory, they are not automatically - * added to the Scene. - * - * Game Objects directly register themselves with the Creator and inject their own creation - * methods into the class. - * - * @class GameObjectCreator - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Game Object Factory belongs. - */ -var GameObjectCreator = new Class({ - - initialize: - - function GameObjectCreator (scene) - { - /** - * The Scene to which this Game Object Creator belongs. - * - * @name Phaser.GameObjects.GameObjectCreator#scene - * @type {Phaser.Scene} - * @protected - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene.Systems. - * - * @name Phaser.GameObjects.GameObjectCreator#systems - * @type {Phaser.Scenes.Systems} - * @protected - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * A reference to the Scene Display List. - * - * @name Phaser.GameObjects.GameObjectCreator#displayList - * @type {Phaser.GameObjects.DisplayList} - * @protected - * @since 3.0.0 - */ - this.displayList; - - /** - * A reference to the Scene Update List. - * - * @name Phaser.GameObjects.GameObjectCreator#updateList - * @type {Phaser.GameObjects.UpdateList} - * @protected - * @since 3.0.0 - */ - this.updateList; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.GameObjectCreator#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.displayList = this.systems.displayList; - this.updateList = this.systems.updateList; - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.GameObjectCreator#start - * @private - * @since 3.5.0 - */ - start: function () - { - this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.GameObjects.GameObjectCreator#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.GameObjects.GameObjectCreator#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - this.displayList = null; - this.updateList = null; - } - -}); - -// Static method called directly by the Game Object creator functions - -GameObjectCreator.register = function (factoryType, factoryFunction) -{ - if (!GameObjectCreator.prototype.hasOwnProperty(factoryType)) - { - GameObjectCreator.prototype[factoryType] = factoryFunction; - } -}; - -GameObjectCreator.remove = function (factoryType) -{ - if (GameObjectCreator.prototype.hasOwnProperty(factoryType)) - { - delete GameObjectCreator.prototype[factoryType]; - } -}; - -PluginCache.register('GameObjectCreator', GameObjectCreator, 'make'); - -module.exports = GameObjectCreator; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); + +/** + * @classdesc + * The Game Object Creator is a Scene plugin that allows you to quickly create many common + * types of Game Objects and return them. Unlike the Game Object Factory, they are not automatically + * added to the Scene. + * + * Game Objects directly register themselves with the Creator and inject their own creation + * methods into the class. + * + * @class GameObjectCreator + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object Factory belongs. + */ +var GameObjectCreator = new Class({ + + initialize: + + function GameObjectCreator (scene) + { + /** + * The Scene to which this Game Object Creator belongs. + * + * @name Phaser.GameObjects.GameObjectCreator#scene + * @type {Phaser.Scene} + * @protected + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene.Systems. + * + * @name Phaser.GameObjects.GameObjectCreator#systems + * @type {Phaser.Scenes.Systems} + * @protected + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the Scene Display List. + * + * @name Phaser.GameObjects.GameObjectCreator#displayList + * @type {Phaser.GameObjects.DisplayList} + * @protected + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene Update List. + * + * @name Phaser.GameObjects.GameObjectCreator#updateList + * @type {Phaser.GameObjects.UpdateList} + * @protected + * @since 3.0.0 + */ + this.updateList; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectCreator#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.displayList = this.systems.displayList; + this.updateList = this.systems.updateList; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectCreator#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.GameObjectCreator#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.GameObjectCreator#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + this.displayList = null; + this.updateList = null; + } + +}); + +// Static method called directly by the Game Object creator functions + +GameObjectCreator.register = function (factoryType, factoryFunction) +{ + if (!GameObjectCreator.prototype.hasOwnProperty(factoryType)) + { + GameObjectCreator.prototype[factoryType] = factoryFunction; + } +}; + +GameObjectCreator.remove = function (factoryType) +{ + if (GameObjectCreator.prototype.hasOwnProperty(factoryType)) + { + delete GameObjectCreator.prototype[factoryType]; + } +}; + +PluginCache.register('GameObjectCreator', GameObjectCreator, 'make'); + +module.exports = GameObjectCreator; diff --git a/src/gameobjects/GameObjectFactory.js b/src/gameobjects/GameObjectFactory.js index bcbf4c1f3..def9f15f4 100644 --- a/src/gameobjects/GameObjectFactory.js +++ b/src/gameobjects/GameObjectFactory.js @@ -1,212 +1,212 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); - -/** - * @classdesc - * The Game Object Factory is a Scene plugin that allows you to quickly create many common - * types of Game Objects and have them automatically registered with the Scene. - * - * Game Objects directly register themselves with the Factory and inject their own creation - * methods into the class. - * - * @class GameObjectFactory - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Game Object Factory belongs. - */ -var GameObjectFactory = new Class({ - - initialize: - - function GameObjectFactory (scene) - { - /** - * The Scene to which this Game Object Factory belongs. - * - * @name Phaser.GameObjects.GameObjectFactory#scene - * @type {Phaser.Scene} - * @protected - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene.Systems. - * - * @name Phaser.GameObjects.GameObjectFactory#systems - * @type {Phaser.Scenes.Systems} - * @protected - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * A reference to the Scene Display List. - * - * @name Phaser.GameObjects.GameObjectFactory#displayList - * @type {Phaser.GameObjects.DisplayList} - * @protected - * @since 3.0.0 - */ - this.displayList; - - /** - * A reference to the Scene Update List. - * - * @name Phaser.GameObjects.GameObjectFactory#updateList - * @type {Phaser.GameObjects.UpdateList} - * @protected - * @since 3.0.0 - */ - this.updateList; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.GameObjectFactory#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.displayList = this.systems.displayList; - this.updateList = this.systems.updateList; - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.GameObjectFactory#start - * @private - * @since 3.5.0 - */ - start: function () - { - this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * Adds an existing Game Object to this Scene. - * - * If the Game Object renders, it will be added to the Display List. - * If it has a `preUpdate` method, it will be added to the Update List. - * - * @method Phaser.GameObjects.GameObjectFactory#existing - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.Group)} child - The child to be added to this Scene. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was added. - */ - existing: function (child) - { - if (child.renderCanvas || child.renderWebGL) - { - this.displayList.add(child); - } - - if (child.preUpdate) - { - this.updateList.add(child); - } - - return child; - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.GameObjects.GameObjectFactory#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.GameObjects.GameObjectFactory#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - - this.displayList = null; - this.updateList = null; - } - -}); - -/** - * Static method called directly by the Game Object factory functions. - * With this method you can register a custom GameObject factory in the GameObjectFactory, - * providing a name (`factoryType`) and the constructor (`factoryFunction`) in order - * to be called when you call to Phaser.Scene.add[ factoryType ] method. - * - * @method Phaser.GameObjects.GameObjectFactory.register - * @static - * @since 3.0.0 - * - * @param {string} factoryType - The key of the factory that you will use to call to Phaser.Scene.add[ factoryType ] method. - * @param {function} factoryFunction - The constructor function to be called when you invoke to the Phaser.Scene.add method. - */ -GameObjectFactory.register = function (factoryType, factoryFunction) -{ - if (!GameObjectFactory.prototype.hasOwnProperty(factoryType)) - { - GameObjectFactory.prototype[factoryType] = factoryFunction; - } -}; - -/** - * Static method called directly by the Game Object factory functions. - * With this method you can remove a custom GameObject factory registered in the GameObjectFactory, - * providing a its `factoryType`. - * - * @method Phaser.GameObjects.GameObjectFactory.remove - * @static - * @since 3.0.0 - * - * @param {string} factoryType - The key of the factory that you want to remove from the GameObjectFactory. - */ -GameObjectFactory.remove = function (factoryType) -{ - if (GameObjectFactory.prototype.hasOwnProperty(factoryType)) - { - delete GameObjectFactory.prototype[factoryType]; - } -}; - -PluginCache.register('GameObjectFactory', GameObjectFactory, 'add'); - -module.exports = GameObjectFactory; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); + +/** + * @classdesc + * The Game Object Factory is a Scene plugin that allows you to quickly create many common + * types of Game Objects and have them automatically registered with the Scene. + * + * Game Objects directly register themselves with the Factory and inject their own creation + * methods into the class. + * + * @class GameObjectFactory + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object Factory belongs. + */ +var GameObjectFactory = new Class({ + + initialize: + + function GameObjectFactory (scene) + { + /** + * The Scene to which this Game Object Factory belongs. + * + * @name Phaser.GameObjects.GameObjectFactory#scene + * @type {Phaser.Scene} + * @protected + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene.Systems. + * + * @name Phaser.GameObjects.GameObjectFactory#systems + * @type {Phaser.Scenes.Systems} + * @protected + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the Scene Display List. + * + * @name Phaser.GameObjects.GameObjectFactory#displayList + * @type {Phaser.GameObjects.DisplayList} + * @protected + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene Update List. + * + * @name Phaser.GameObjects.GameObjectFactory#updateList + * @type {Phaser.GameObjects.UpdateList} + * @protected + * @since 3.0.0 + */ + this.updateList; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectFactory#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.displayList = this.systems.displayList; + this.updateList = this.systems.updateList; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.GameObjectFactory#start + * @private + * @since 3.5.0 + */ + start: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Adds an existing Game Object to this Scene. + * + * If the Game Object renders, it will be added to the Display List. + * If it has a `preUpdate` method, it will be added to the Update List. + * + * @method Phaser.GameObjects.GameObjectFactory#existing + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.Group)} child - The child to be added to this Scene. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was added. + */ + existing: function (child) + { + if (child.renderCanvas || child.renderWebGL) + { + this.displayList.add(child); + } + + if (child.preUpdate) + { + this.updateList.add(child); + } + + return child; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.GameObjectFactory#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.GameObjectFactory#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + + this.displayList = null; + this.updateList = null; + } + +}); + +/** + * Static method called directly by the Game Object factory functions. + * With this method you can register a custom GameObject factory in the GameObjectFactory, + * providing a name (`factoryType`) and the constructor (`factoryFunction`) in order + * to be called when you call to Phaser.Scene.add[ factoryType ] method. + * + * @method Phaser.GameObjects.GameObjectFactory.register + * @static + * @since 3.0.0 + * + * @param {string} factoryType - The key of the factory that you will use to call to Phaser.Scene.add[ factoryType ] method. + * @param {function} factoryFunction - The constructor function to be called when you invoke to the Phaser.Scene.add method. + */ +GameObjectFactory.register = function (factoryType, factoryFunction) +{ + if (!GameObjectFactory.prototype.hasOwnProperty(factoryType)) + { + GameObjectFactory.prototype[factoryType] = factoryFunction; + } +}; + +/** + * Static method called directly by the Game Object factory functions. + * With this method you can remove a custom GameObject factory registered in the GameObjectFactory, + * providing a its `factoryType`. + * + * @method Phaser.GameObjects.GameObjectFactory.remove + * @static + * @since 3.0.0 + * + * @param {string} factoryType - The key of the factory that you want to remove from the GameObjectFactory. + */ +GameObjectFactory.remove = function (factoryType) +{ + if (GameObjectFactory.prototype.hasOwnProperty(factoryType)) + { + delete GameObjectFactory.prototype[factoryType]; + } +}; + +PluginCache.register('GameObjectFactory', GameObjectFactory, 'add'); + +module.exports = GameObjectFactory; diff --git a/src/gameobjects/UpdateList.js b/src/gameobjects/UpdateList.js index f9721230f..83339c297 100644 --- a/src/gameobjects/UpdateList.js +++ b/src/gameobjects/UpdateList.js @@ -1,295 +1,295 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var ProcessQueue = require('../structs/ProcessQueue'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); - -/** - * @classdesc - * The Update List plugin. - * - * Update Lists belong to a Scene and maintain the list Game Objects to be updated every frame. - * - * Some or all of these Game Objects may also be part of the Scene's [Display List]{@link Phaser.GameObjects.DisplayList}, for Rendering. - * - * @class UpdateList - * @extends Phaser.Structs.ProcessQueue. - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that the Update List belongs to. - */ -var UpdateList = new Class({ - - Extends: ProcessQueue, - - initialize: - - function UpdateList (scene) - { - ProcessQueue.call(this); - - /** - * The Scene that the Update List belongs to. - * - * @name Phaser.GameObjects.UpdateList#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The Scene's Systems. - * - * @name Phaser.GameObjects.UpdateList#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * The `pending` list is a selection of items which are due to be made 'active' in the next update. - * - * @name Phaser.GameObjects.UpdateList#_pending - * @type {Array.<*>} - * @private - * @default [] - * @since 3.20.0 - */ - - /** - * The `active` list is a selection of items which are considered active and should be updated. - * - * @name Phaser.GameObjects.UpdateList#_active - * @type {Array.<*>} - * @private - * @default [] - * @since 3.20.0 - */ - - /** - * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. - * - * @name Phaser.GameObjects.UpdateList#_destroy - * @type {Array.<*>} - * @private - * @default [] - * @since 3.20.0 - */ - - /** - * The total number of items awaiting processing. - * - * @name Phaser.GameObjects.UpdateList#_toProcess - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.UpdateList#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.GameObjects.UpdateList#start - * @private - * @since 3.5.0 - */ - start: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.PRE_UPDATE, this.update, this); - eventEmitter.on(SceneEvents.UPDATE, this.sceneUpdate, this); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The update step. - * - * Pre-updates every active Game Object in the list. - * - * @method Phaser.GameObjects.UpdateList#sceneUpdate - * @since 3.20.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time elapsed since the last frame. - */ - sceneUpdate: function (time, delta) - { - var list = this._active; - var length = list.length; - - for (var i = 0; i < length; i++) - { - var gameObject = list[i]; - - if (gameObject.active) - { - gameObject.preUpdate.call(gameObject, time, delta); - } - } - }, - - /** - * The Scene that owns this plugin is shutting down. - * - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.GameObjects.UpdateList#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - var i = this._active.length; - - while (i--) - { - this._active[i].destroy(true); - } - - i = this._pending.length; - - while (i--) - { - this._pending[i].destroy(true); - } - - i = this._destroy.length; - - while (i--) - { - this._destroy[i].destroy(true); - } - - this._toProcess = 0; - - this._pending = []; - this._active = []; - this._destroy = []; - - this.removeAllListeners(); - - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); - eventEmitter.off(SceneEvents.UPDATE, this.sceneUpdate, this); - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * - * We need to shutdown and then kill off all external references. - * - * @method Phaser.GameObjects.UpdateList#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.systems.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - - /** - * Adds a new item to the Update List. - * - * The item is added to the pending list and made active in the next update. - * - * @method Phaser.GameObjects.UpdateList#add - * @since 3.0.0 - * - * @param {*} item - The item to add to the queue. - * - * @return {*} The item that was added. - */ - - /** - * Removes an item from the Update List. - * - * The item is added to the pending destroy and fully removed in the next update. - * - * @method Phaser.GameObjects.UpdateList#remove - * @since 3.0.0 - * - * @param {*} item - The item to be removed from the queue. - * - * @return {*} The item that was removed. - */ - - /** - * Removes all active items from this Update List. - * - * All the items are marked as 'pending destroy' and fully removed in the next update. - * - * @method Phaser.GameObjects.UpdateList#removeAll - * @since 3.20.0 - * - * @return {this} This Update List object. - */ - - /** - * Update this queue. First it will process any items awaiting destruction, and remove them. - * - * Then it will check to see if there are any items pending insertion, and move them to an - * active state. Finally, it will return a list of active items for further processing. - * - * @method Phaser.GameObjects.UpdateList#update - * @since 3.0.0 - * - * @return {Array.<*>} A list of active items. - */ - - /** - * Returns the current list of active items. - * - * This method returns a reference to the active list array, not a copy of it. - * Therefore, be careful to not modify this array outside of the ProcessQueue. - * - * @method Phaser.GameObjects.UpdateList#getActive - * @since 3.0.0 - * - * @return {Array.<*>} A list of active items. - */ - - /** - * The number of entries in the active list. - * - * @name Phaser.GameObjects.UpdateList#length - * @type {integer} - * @readonly - * @since 3.20.0 - */ -}); - -PluginCache.register('UpdateList', UpdateList, 'updateList'); - -module.exports = UpdateList; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var ProcessQueue = require('../structs/ProcessQueue'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); + +/** + * @classdesc + * The Update List plugin. + * + * Update Lists belong to a Scene and maintain the list Game Objects to be updated every frame. + * + * Some or all of these Game Objects may also be part of the Scene's [Display List]{@link Phaser.GameObjects.DisplayList}, for Rendering. + * + * @class UpdateList + * @extends Phaser.Structs.ProcessQueue. + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that the Update List belongs to. + */ +var UpdateList = new Class({ + + Extends: ProcessQueue, + + initialize: + + function UpdateList (scene) + { + ProcessQueue.call(this); + + /** + * The Scene that the Update List belongs to. + * + * @name Phaser.GameObjects.UpdateList#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene's Systems. + * + * @name Phaser.GameObjects.UpdateList#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * + * @name Phaser.GameObjects.UpdateList#_pending + * @type {Array.<*>} + * @private + * @default [] + * @since 3.20.0 + */ + + /** + * The `active` list is a selection of items which are considered active and should be updated. + * + * @name Phaser.GameObjects.UpdateList#_active + * @type {Array.<*>} + * @private + * @default [] + * @since 3.20.0 + */ + + /** + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * @name Phaser.GameObjects.UpdateList#_destroy + * @type {Array.<*>} + * @private + * @default [] + * @since 3.20.0 + */ + + /** + * The total number of items awaiting processing. + * + * @name Phaser.GameObjects.UpdateList#_toProcess + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.UpdateList#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.GameObjects.UpdateList#start + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.PRE_UPDATE, this.update, this); + eventEmitter.on(SceneEvents.UPDATE, this.sceneUpdate, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The update step. + * + * Pre-updates every active Game Object in the list. + * + * @method Phaser.GameObjects.UpdateList#sceneUpdate + * @since 3.20.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time elapsed since the last frame. + */ + sceneUpdate: function (time, delta) + { + var list = this._active; + var length = list.length; + + for (var i = 0; i < length; i++) + { + var gameObject = list[i]; + + if (gameObject.active) + { + gameObject.preUpdate.call(gameObject, time, delta); + } + } + }, + + /** + * The Scene that owns this plugin is shutting down. + * + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.GameObjects.UpdateList#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + var i = this._active.length; + + while (i--) + { + this._active[i].destroy(true); + } + + i = this._pending.length; + + while (i--) + { + this._pending[i].destroy(true); + } + + i = this._destroy.length; + + while (i--) + { + this._destroy[i].destroy(true); + } + + this._toProcess = 0; + + this._pending = []; + this._active = []; + this._destroy = []; + + this.removeAllListeners(); + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.off(SceneEvents.UPDATE, this.sceneUpdate, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * + * We need to shutdown and then kill off all external references. + * + * @method Phaser.GameObjects.UpdateList#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.systems.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + + /** + * Adds a new item to the Update List. + * + * The item is added to the pending list and made active in the next update. + * + * @method Phaser.GameObjects.UpdateList#add + * @since 3.0.0 + * + * @param {*} item - The item to add to the queue. + * + * @return {*} The item that was added. + */ + + /** + * Removes an item from the Update List. + * + * The item is added to the pending destroy and fully removed in the next update. + * + * @method Phaser.GameObjects.UpdateList#remove + * @since 3.0.0 + * + * @param {*} item - The item to be removed from the queue. + * + * @return {*} The item that was removed. + */ + + /** + * Removes all active items from this Update List. + * + * All the items are marked as 'pending destroy' and fully removed in the next update. + * + * @method Phaser.GameObjects.UpdateList#removeAll + * @since 3.20.0 + * + * @return {this} This Update List object. + */ + + /** + * Update this queue. First it will process any items awaiting destruction, and remove them. + * + * Then it will check to see if there are any items pending insertion, and move them to an + * active state. Finally, it will return a list of active items for further processing. + * + * @method Phaser.GameObjects.UpdateList#update + * @since 3.0.0 + * + * @return {Array.<*>} A list of active items. + */ + + /** + * Returns the current list of active items. + * + * This method returns a reference to the active list array, not a copy of it. + * Therefore, be careful to not modify this array outside of the ProcessQueue. + * + * @method Phaser.GameObjects.UpdateList#getActive + * @since 3.0.0 + * + * @return {Array.<*>} A list of active items. + */ + + /** + * The number of entries in the active list. + * + * @name Phaser.GameObjects.UpdateList#length + * @type {integer} + * @readonly + * @since 3.20.0 + */ +}); + +PluginCache.register('UpdateList', UpdateList, 'updateList'); + +module.exports = UpdateList; diff --git a/src/gameobjects/bitmaptext/GetBitmapTextSize.js b/src/gameobjects/bitmaptext/GetBitmapTextSize.js index 41f12c887..952e7540e 100644 --- a/src/gameobjects/bitmaptext/GetBitmapTextSize.js +++ b/src/gameobjects/bitmaptext/GetBitmapTextSize.js @@ -1,447 +1,447 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the position, width and height of a BitmapText Game Object. - * - * Returns a BitmapTextSize object that contains global and local variants of the Game Objects x and y coordinates and - * its width and height. - * - * The global position and size take into account the Game Object's position and scale. - * - * The local position and size just takes into account the font data. - * - * @function GetBitmapTextSize - * @since 3.0.0 - * @private - * - * @param {(Phaser.GameObjects.DynamicBitmapText|Phaser.GameObjects.BitmapText)} src - The BitmapText to calculate the position, width and height of. - * @param {boolean} [round] - Whether to round the results to the nearest integer. - * @param {object} [out] - Optional object to store the results in, to save constant object creation. - * - * @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} The calculated position, width and height of the BitmapText. - */ -var GetBitmapTextSize = function (src, round, out) -{ - if (out === undefined) - { - out = { - local: { - x: 0, - y: 0, - width: 0, - height: 0 - }, - global: { - x: 0, - y: 0, - width: 0, - height: 0 - }, - lines: { - shortest: 0, - longest: 0, - lengths: null, - height: 0 - }, - wrappedText: '', - words: [], - scaleX: 0, - scaleY: 0 - }; - - return out; - } - - var text = src.text; - var textLength = text.length; - var maxWidth = src.maxWidth; - var wordWrapCharCode = src.wordWrapCharCode; - - var bx = Number.MAX_VALUE; - var by = Number.MAX_VALUE; - var bw = 0; - var bh = 0; - - var chars = src.fontData.chars; - var lineHeight = src.fontData.lineHeight; - var letterSpacing = src.letterSpacing; - - var xAdvance = 0; - var yAdvance = 0; - - var charCode = 0; - - var glyph = null; - - var x = 0; - var y = 0; - - var scale = (src.fontSize / src.fontData.size); - var sx = scale * src.scaleX; - var sy = scale * src.scaleY; - - var lastGlyph = null; - var lastCharCode = 0; - var lineWidths = []; - var shortestLine = Number.MAX_VALUE; - var longestLine = 0; - var currentLine = 0; - var currentLineWidth = 0; - - var i; - var words = []; - var current = null; - - // Scan for breach of maxWidth and insert carriage-returns - if (maxWidth > 0) - { - for (i = 0; i < textLength; i++) - { - charCode = text.charCodeAt(i); - - if (charCode === 10) - { - if (current !== null) - { - words.push({ - word: current.word, - i: current.i, - x: current.x * sx, - y: current.y * sy, - w: current.w * sx, - h: current.h * sy, - cr: true - }); - - current = null; - } - - xAdvance = 0; - yAdvance += lineHeight; - lastGlyph = null; - - continue; - } - - glyph = chars[charCode]; - - if (!glyph) - { - continue; - } - - if (lastGlyph !== null) - { - var glyphKerningOffset = glyph.kerning[lastCharCode]; - } - - if (charCode === wordWrapCharCode) - { - if (current !== null) - { - words.push({ - word: current.word, - i: current.i, - x: current.x * sx, - y: current.y * sy, - w: current.w * sx, - h: current.h * sy, - cr: false - }); - - current = null; - } - } - else - { - if (current === null) - { - // We're starting a new word, recording the starting index, etc - current = { word: '', i: i, x: xAdvance, y: yAdvance, w: 0, h: lineHeight, cr: false }; - } - - current.word = current.word.concat(text[i]); - current.w += glyph.xOffset + glyph.xAdvance + ((glyphKerningOffset !== undefined) ? glyphKerningOffset : 0); - } - - xAdvance += glyph.xAdvance + letterSpacing; - lastGlyph = glyph; - lastCharCode = charCode; - } - - // Last word - if (current !== null) - { - words.push({ - word: current.word, - i: current.i, - x: current.x * sx, - y: current.y * sy, - w: current.w * sx, - h: current.h * sy, - cr: false - }); - } - - // Reset for the next loop - xAdvance = 0; - yAdvance = 0; - lastGlyph = null; - lastCharCode = 0; - - // Loop through the words array and see if we've got any > maxWidth - var prev; - var offset = 0; - var crs = []; - - for (i = 0; i < words.length; i++) - { - var entry = words[i]; - var left = entry.x; - var right = entry.x + entry.w; - - if (prev) - { - var diff = left - (prev.x + prev.w); - - offset = left - (diff + prev.w); - - prev = null; - } - - var checkLeft = left - offset; - var checkRight = right - offset; - - if (checkLeft > maxWidth || checkRight > maxWidth) - { - crs.push(entry.i - 1); - - if (entry.cr) - { - crs.push(entry.i + entry.word.length); - - offset = 0; - prev = null; - } - else - { - prev = entry; - } - } - else if (entry.cr) - { - crs.push(entry.i + entry.word.length); - - offset = 0; - prev = null; - } - } - - var stringInsert = function (str, index, value) - { - return str.substr(0, index) + value + str.substr(index + 1); - }; - - for (i = crs.length - 1; i >= 0; i--) - { - // eslint-disable-next-line quotes - text = stringInsert(text, crs[i], "\n"); - } - - out.wrappedText = text; - - textLength = text.length; - - // Recalculated in the next loop - words = []; - current = null; - } - - for (i = 0; i < textLength; i++) - { - charCode = text.charCodeAt(i); - - if (charCode === 10) - { - if (current !== null) - { - words.push({ - word: current.word, - i: current.i, - x: current.x * sx, - y: current.y * sy, - w: current.w * sx, - h: current.h * sy - }); - - current = null; - } - - xAdvance = 0; - yAdvance += lineHeight; - lastGlyph = null; - - lineWidths[currentLine] = currentLineWidth; - - if (currentLineWidth > longestLine) - { - longestLine = currentLineWidth; - } - - if (currentLineWidth < shortestLine) - { - shortestLine = currentLineWidth; - } - - currentLine++; - currentLineWidth = 0; - - continue; - } - - glyph = chars[charCode]; - - if (!glyph) - { - continue; - } - - x = xAdvance; - y = yAdvance; - - if (lastGlyph !== null) - { - var kerningOffset = glyph.kerning[lastCharCode]; - - x += (kerningOffset !== undefined) ? kerningOffset : 0; - } - - if (bx > x) - { - bx = x; - } - - if (by > y) - { - by = y; - } - - var gw = x + glyph.xAdvance; - var gh = y + lineHeight; - - if (bw < gw) - { - bw = gw; - } - - if (bh < gh) - { - bh = gh; - } - - if (charCode === wordWrapCharCode) - { - if (current !== null) - { - words.push({ - word: current.word, - i: current.i, - x: current.x * sx, - y: current.y * sy, - w: current.w * sx, - h: current.h * sy - }); - - current = null; - } - } - else - { - if (current === null) - { - // We're starting a new word, recording the starting index, etc - current = { word: '', i: i, x: xAdvance, y: yAdvance, w: 0, h: lineHeight }; - } - - current.word = current.word.concat(text[i]); - current.w += glyph.xOffset + glyph.xAdvance + ((kerningOffset !== undefined) ? kerningOffset : 0); - } - - xAdvance += glyph.xAdvance + letterSpacing; - lastGlyph = glyph; - lastCharCode = charCode; - currentLineWidth = gw * scale; - } - - // Last word - if (current !== null) - { - words.push({ - word: current.word, - i: current.i, - x: current.x * sx, - y: current.y * sy, - w: current.w * sx, - h: current.h * sy - }); - } - - lineWidths[currentLine] = currentLineWidth; - - if (currentLineWidth > longestLine) - { - longestLine = currentLineWidth; - } - - if (currentLineWidth < shortestLine) - { - shortestLine = currentLineWidth; - } - - var local = out.local; - var global = out.global; - var lines = out.lines; - - local.x = bx * scale; - local.y = by * scale; - local.width = bw * scale; - local.height = bh * scale; - - global.x = (src.x - src.displayOriginX) + (bx * sx); - global.y = (src.y - src.displayOriginY) + (by * sy); - global.width = bw * sx; - global.height = bh * sy; - - lines.shortest = shortestLine; - lines.longest = longestLine; - lines.lengths = lineWidths; - - if (round) - { - local.x = Math.round(local.x); - local.y = Math.round(local.y); - local.width = Math.round(local.width); - local.height = Math.round(local.height); - - global.x = Math.round(global.x); - global.y = Math.round(global.y); - global.width = Math.round(global.width); - global.height = Math.round(global.height); - - lines.shortest = Math.round(shortestLine); - lines.longest = Math.round(longestLine); - } - - out.words = words; - out.lines.height = lineHeight; - out.scaleX = src.scaleX; - out.scaleY = src.scaleY; - - return out; -}; - -module.exports = GetBitmapTextSize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the position, width and height of a BitmapText Game Object. + * + * Returns a BitmapTextSize object that contains global and local variants of the Game Objects x and y coordinates and + * its width and height. + * + * The global position and size take into account the Game Object's position and scale. + * + * The local position and size just takes into account the font data. + * + * @function GetBitmapTextSize + * @since 3.0.0 + * @private + * + * @param {(Phaser.GameObjects.DynamicBitmapText|Phaser.GameObjects.BitmapText)} src - The BitmapText to calculate the position, width and height of. + * @param {boolean} [round] - Whether to round the results to the nearest integer. + * @param {object} [out] - Optional object to store the results in, to save constant object creation. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} The calculated position, width and height of the BitmapText. + */ +var GetBitmapTextSize = function (src, round, out) +{ + if (out === undefined) + { + out = { + local: { + x: 0, + y: 0, + width: 0, + height: 0 + }, + global: { + x: 0, + y: 0, + width: 0, + height: 0 + }, + lines: { + shortest: 0, + longest: 0, + lengths: null, + height: 0 + }, + wrappedText: '', + words: [], + scaleX: 0, + scaleY: 0 + }; + + return out; + } + + var text = src.text; + var textLength = text.length; + var maxWidth = src.maxWidth; + var wordWrapCharCode = src.wordWrapCharCode; + + var bx = Number.MAX_VALUE; + var by = Number.MAX_VALUE; + var bw = 0; + var bh = 0; + + var chars = src.fontData.chars; + var lineHeight = src.fontData.lineHeight; + var letterSpacing = src.letterSpacing; + + var xAdvance = 0; + var yAdvance = 0; + + var charCode = 0; + + var glyph = null; + + var x = 0; + var y = 0; + + var scale = (src.fontSize / src.fontData.size); + var sx = scale * src.scaleX; + var sy = scale * src.scaleY; + + var lastGlyph = null; + var lastCharCode = 0; + var lineWidths = []; + var shortestLine = Number.MAX_VALUE; + var longestLine = 0; + var currentLine = 0; + var currentLineWidth = 0; + + var i; + var words = []; + var current = null; + + // Scan for breach of maxWidth and insert carriage-returns + if (maxWidth > 0) + { + for (i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy, + cr: true + }); + + current = null; + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + if (lastGlyph !== null) + { + var glyphKerningOffset = glyph.kerning[lastCharCode]; + } + + if (charCode === wordWrapCharCode) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy, + cr: false + }); + + current = null; + } + } + else + { + if (current === null) + { + // We're starting a new word, recording the starting index, etc + current = { word: '', i: i, x: xAdvance, y: yAdvance, w: 0, h: lineHeight, cr: false }; + } + + current.word = current.word.concat(text[i]); + current.w += glyph.xOffset + glyph.xAdvance + ((glyphKerningOffset !== undefined) ? glyphKerningOffset : 0); + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + } + + // Last word + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy, + cr: false + }); + } + + // Reset for the next loop + xAdvance = 0; + yAdvance = 0; + lastGlyph = null; + lastCharCode = 0; + + // Loop through the words array and see if we've got any > maxWidth + var prev; + var offset = 0; + var crs = []; + + for (i = 0; i < words.length; i++) + { + var entry = words[i]; + var left = entry.x; + var right = entry.x + entry.w; + + if (prev) + { + var diff = left - (prev.x + prev.w); + + offset = left - (diff + prev.w); + + prev = null; + } + + var checkLeft = left - offset; + var checkRight = right - offset; + + if (checkLeft > maxWidth || checkRight > maxWidth) + { + crs.push(entry.i - 1); + + if (entry.cr) + { + crs.push(entry.i + entry.word.length); + + offset = 0; + prev = null; + } + else + { + prev = entry; + } + } + else if (entry.cr) + { + crs.push(entry.i + entry.word.length); + + offset = 0; + prev = null; + } + } + + var stringInsert = function (str, index, value) + { + return str.substr(0, index) + value + str.substr(index + 1); + }; + + for (i = crs.length - 1; i >= 0; i--) + { + // eslint-disable-next-line quotes + text = stringInsert(text, crs[i], "\n"); + } + + out.wrappedText = text; + + textLength = text.length; + + // Recalculated in the next loop + words = []; + current = null; + } + + for (i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy + }); + + current = null; + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + lineWidths[currentLine] = currentLineWidth; + + if (currentLineWidth > longestLine) + { + longestLine = currentLineWidth; + } + + if (currentLineWidth < shortestLine) + { + shortestLine = currentLineWidth; + } + + currentLine++; + currentLineWidth = 0; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + x = xAdvance; + y = yAdvance; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + if (bx > x) + { + bx = x; + } + + if (by > y) + { + by = y; + } + + var gw = x + glyph.xAdvance; + var gh = y + lineHeight; + + if (bw < gw) + { + bw = gw; + } + + if (bh < gh) + { + bh = gh; + } + + if (charCode === wordWrapCharCode) + { + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy + }); + + current = null; + } + } + else + { + if (current === null) + { + // We're starting a new word, recording the starting index, etc + current = { word: '', i: i, x: xAdvance, y: yAdvance, w: 0, h: lineHeight }; + } + + current.word = current.word.concat(text[i]); + current.w += glyph.xOffset + glyph.xAdvance + ((kerningOffset !== undefined) ? kerningOffset : 0); + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + currentLineWidth = gw * scale; + } + + // Last word + if (current !== null) + { + words.push({ + word: current.word, + i: current.i, + x: current.x * sx, + y: current.y * sy, + w: current.w * sx, + h: current.h * sy + }); + } + + lineWidths[currentLine] = currentLineWidth; + + if (currentLineWidth > longestLine) + { + longestLine = currentLineWidth; + } + + if (currentLineWidth < shortestLine) + { + shortestLine = currentLineWidth; + } + + var local = out.local; + var global = out.global; + var lines = out.lines; + + local.x = bx * scale; + local.y = by * scale; + local.width = bw * scale; + local.height = bh * scale; + + global.x = (src.x - src.displayOriginX) + (bx * sx); + global.y = (src.y - src.displayOriginY) + (by * sy); + global.width = bw * sx; + global.height = bh * sy; + + lines.shortest = shortestLine; + lines.longest = longestLine; + lines.lengths = lineWidths; + + if (round) + { + local.x = Math.round(local.x); + local.y = Math.round(local.y); + local.width = Math.round(local.width); + local.height = Math.round(local.height); + + global.x = Math.round(global.x); + global.y = Math.round(global.y); + global.width = Math.round(global.width); + global.height = Math.round(global.height); + + lines.shortest = Math.round(shortestLine); + lines.longest = Math.round(longestLine); + } + + out.words = words; + out.lines.height = lineHeight; + out.scaleX = src.scaleX; + out.scaleY = src.scaleY; + + return out; +}; + +module.exports = GetBitmapTextSize; diff --git a/src/gameobjects/bitmaptext/ParseFromAtlas.js b/src/gameobjects/bitmaptext/ParseFromAtlas.js index e33728918..c28bcd3e0 100644 --- a/src/gameobjects/bitmaptext/ParseFromAtlas.js +++ b/src/gameobjects/bitmaptext/ParseFromAtlas.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ParseXMLBitmapFont = require('./ParseXMLBitmapFont'); - -/** - * Parse an XML Bitmap Font from an Atlas. - * - * Adds the parsed Bitmap Font data to the cache with the `fontName` key. - * - * @function ParseFromAtlas - * @since 3.0.0 - * @private - * - * @param {Phaser.Scene} scene - The Scene to parse the Bitmap Font for. - * @param {string} fontName - The key of the font to add to the Bitmap Font cache. - * @param {string} textureKey - The key of the BitmapFont's texture. - * @param {string} frameKey - The key of the BitmapFont texture's frame. - * @param {string} xmlKey - The key of the XML data of the font to parse. - * @param {integer} [xSpacing] - The x-axis spacing to add between each letter. - * @param {integer} [ySpacing] - The y-axis spacing to add to the line height. - * - * @return {boolean} Whether the parsing was successful or not. - */ -var ParseFromAtlas = function (scene, fontName, textureKey, frameKey, xmlKey, xSpacing, ySpacing) -{ - var frame = scene.sys.textures.getFrame(textureKey, frameKey); - var xml = scene.sys.cache.xml.get(xmlKey); - - if (frame && xml) - { - var data = ParseXMLBitmapFont(xml, xSpacing, ySpacing, frame); - - scene.sys.cache.bitmapFont.add(fontName, { data: data, texture: textureKey, frame: frameKey }); - - return true; - } - else - { - return false; - } -}; - -module.exports = ParseFromAtlas; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ParseXMLBitmapFont = require('./ParseXMLBitmapFont'); + +/** + * Parse an XML Bitmap Font from an Atlas. + * + * Adds the parsed Bitmap Font data to the cache with the `fontName` key. + * + * @function ParseFromAtlas + * @since 3.0.0 + * @private + * + * @param {Phaser.Scene} scene - The Scene to parse the Bitmap Font for. + * @param {string} fontName - The key of the font to add to the Bitmap Font cache. + * @param {string} textureKey - The key of the BitmapFont's texture. + * @param {string} frameKey - The key of the BitmapFont texture's frame. + * @param {string} xmlKey - The key of the XML data of the font to parse. + * @param {integer} [xSpacing] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing] - The y-axis spacing to add to the line height. + * + * @return {boolean} Whether the parsing was successful or not. + */ +var ParseFromAtlas = function (scene, fontName, textureKey, frameKey, xmlKey, xSpacing, ySpacing) +{ + var frame = scene.sys.textures.getFrame(textureKey, frameKey); + var xml = scene.sys.cache.xml.get(xmlKey); + + if (frame && xml) + { + var data = ParseXMLBitmapFont(xml, xSpacing, ySpacing, frame); + + scene.sys.cache.bitmapFont.add(fontName, { data: data, texture: textureKey, frame: frameKey }); + + return true; + } + else + { + return false; + } +}; + +module.exports = ParseFromAtlas; diff --git a/src/gameobjects/bitmaptext/ParseRetroFont.js b/src/gameobjects/bitmaptext/ParseRetroFont.js index 3234881a9..7341da39f 100644 --- a/src/gameobjects/bitmaptext/ParseRetroFont.js +++ b/src/gameobjects/bitmaptext/ParseRetroFont.js @@ -1,110 +1,110 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetValue = require('../../utils/object/GetValue'); - -/** - * Parses a Retro Font configuration object so you can pass it to the BitmapText constructor - * and create a BitmapText object using a fixed-width retro font. - * - * @function Phaser.GameObjects.RetroFont.Parse - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - A reference to the Phaser Scene. - * @param {Phaser.Types.GameObjects.BitmapText.RetroFontConfig} config - The font configuration object. - * - * @return {object} A parsed Bitmap Font data entry for the Bitmap Font cache. - */ -var ParseRetroFont = function (scene, config) -{ - var w = config.width; - var h = config.height; - var cx = Math.floor(w / 2); - var cy = Math.floor(h / 2); - var letters = GetValue(config, 'chars', ''); - - if (letters === '') - { - return; - } - - var key = GetValue(config, 'image', ''); - var offsetX = GetValue(config, 'offset.x', 0); - var offsetY = GetValue(config, 'offset.y', 0); - var spacingX = GetValue(config, 'spacing.x', 0); - var spacingY = GetValue(config, 'spacing.y', 0); - var lineSpacing = GetValue(config, 'lineSpacing', 0); - - var charsPerRow = GetValue(config, 'charsPerRow', null); - - if (charsPerRow === null) - { - charsPerRow = scene.sys.textures.getFrame(key).width / w; - - if (charsPerRow > letters.length) - { - charsPerRow = letters.length; - } - } - - var x = offsetX; - var y = offsetY; - - var data = { - retroFont: true, - font: key, - size: w, - lineHeight: h + lineSpacing, - chars: {} - }; - - var r = 0; - - for (var i = 0; i < letters.length; i++) - { - // var node = letters[i]; - - var charCode = letters.charCodeAt(i); - - data.chars[charCode] = - { - x: x, - y: y, - width: w, - height: h, - centerX: cx, - centerY: cy, - xOffset: 0, - yOffset: 0, - xAdvance: w, - data: {}, - kerning: {} - }; - - r++; - - if (r === charsPerRow) - { - r = 0; - x = offsetX; - y += h + spacingY; - } - else - { - x += w + spacingX; - } - } - - var entry = { - data: data, - frame: null, - texture: key - }; - - return entry; -}; - -module.exports = ParseRetroFont; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = require('../../utils/object/GetValue'); + +/** + * Parses a Retro Font configuration object so you can pass it to the BitmapText constructor + * and create a BitmapText object using a fixed-width retro font. + * + * @function Phaser.GameObjects.RetroFont.Parse + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Phaser Scene. + * @param {Phaser.Types.GameObjects.BitmapText.RetroFontConfig} config - The font configuration object. + * + * @return {object} A parsed Bitmap Font data entry for the Bitmap Font cache. + */ +var ParseRetroFont = function (scene, config) +{ + var w = config.width; + var h = config.height; + var cx = Math.floor(w / 2); + var cy = Math.floor(h / 2); + var letters = GetValue(config, 'chars', ''); + + if (letters === '') + { + return; + } + + var key = GetValue(config, 'image', ''); + var offsetX = GetValue(config, 'offset.x', 0); + var offsetY = GetValue(config, 'offset.y', 0); + var spacingX = GetValue(config, 'spacing.x', 0); + var spacingY = GetValue(config, 'spacing.y', 0); + var lineSpacing = GetValue(config, 'lineSpacing', 0); + + var charsPerRow = GetValue(config, 'charsPerRow', null); + + if (charsPerRow === null) + { + charsPerRow = scene.sys.textures.getFrame(key).width / w; + + if (charsPerRow > letters.length) + { + charsPerRow = letters.length; + } + } + + var x = offsetX; + var y = offsetY; + + var data = { + retroFont: true, + font: key, + size: w, + lineHeight: h + lineSpacing, + chars: {} + }; + + var r = 0; + + for (var i = 0; i < letters.length; i++) + { + // var node = letters[i]; + + var charCode = letters.charCodeAt(i); + + data.chars[charCode] = + { + x: x, + y: y, + width: w, + height: h, + centerX: cx, + centerY: cy, + xOffset: 0, + yOffset: 0, + xAdvance: w, + data: {}, + kerning: {} + }; + + r++; + + if (r === charsPerRow) + { + r = 0; + x = offsetX; + y += h + spacingY; + } + else + { + x += w + spacingX; + } + } + + var entry = { + data: data, + frame: null, + texture: key + }; + + return entry; +}; + +module.exports = ParseRetroFont; diff --git a/src/gameobjects/bitmaptext/ParseXMLBitmapFont.js b/src/gameobjects/bitmaptext/ParseXMLBitmapFont.js index b8ba6bcfb..7c8157b42 100644 --- a/src/gameobjects/bitmaptext/ParseXMLBitmapFont.js +++ b/src/gameobjects/bitmaptext/ParseXMLBitmapFont.js @@ -1,133 +1,133 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Read an integer value from an XML Node. - * - * @function getValue - * @since 3.0.0 - * @private - * - * @param {Node} node - The XML Node. - * @param {string} attribute - The attribute to read. - * - * @return {integer} The parsed value. - */ -function getValue (node, attribute) -{ - return parseInt(node.getAttribute(attribute), 10); -} - -/** - * Parse an XML font to Bitmap Font data for the Bitmap Font cache. - * - * @function ParseXMLBitmapFont - * @since 3.0.0 - * @private - * - * @param {XMLDocument} xml - The XML Document to parse the font from. - * @param {integer} [xSpacing=0] - The x-axis spacing to add between each letter. - * @param {integer} [ySpacing=0] - The y-axis spacing to add to the line height. - * @param {Phaser.Textures.Frame} [frame] - The texture frame to take into account while parsing. - * - * @return {Phaser.Types.GameObjects.BitmapText.BitmapFontData} The parsed Bitmap Font data. - */ -var ParseXMLBitmapFont = function (xml, xSpacing, ySpacing, frame) -{ - if (xSpacing === undefined) { xSpacing = 0; } - if (ySpacing === undefined) { ySpacing = 0; } - - var data = {}; - var info = xml.getElementsByTagName('info')[0]; - var common = xml.getElementsByTagName('common')[0]; - - data.font = info.getAttribute('face'); - data.size = getValue(info, 'size'); - data.lineHeight = getValue(common, 'lineHeight') + ySpacing; - data.chars = {}; - - var letters = xml.getElementsByTagName('char'); - - var adjustForTrim = (frame !== undefined && frame.trimmed); - - if (adjustForTrim) - { - var top = frame.height; - var left = frame.width; - } - - for (var i = 0; i < letters.length; i++) - { - var node = letters[i]; - - var charCode = getValue(node, 'id'); - var gx = getValue(node, 'x'); - var gy = getValue(node, 'y'); - var gw = getValue(node, 'width'); - var gh = getValue(node, 'height'); - - // Handle frame trim issues - - if (adjustForTrim) - { - if (gx < left) - { - left = gx; - } - - if (gy < top) - { - top = gy; - } - } - - data.chars[charCode] = - { - x: gx, - y: gy, - width: gw, - height: gh, - centerX: Math.floor(gw / 2), - centerY: Math.floor(gh / 2), - xOffset: getValue(node, 'xoffset'), - yOffset: getValue(node, 'yoffset'), - xAdvance: getValue(node, 'xadvance') + xSpacing, - data: {}, - kerning: {} - }; - } - - if (adjustForTrim && top !== 0 && left !== 0) - { - // Now we know the top and left coordinates of the glyphs in the original data - // so we can work out how much to adjust the glyphs by - - for (var code in data.chars) - { - var glyph = data.chars[code]; - - glyph.x -= frame.x; - glyph.y -= frame.y; - } - } - - var kernings = xml.getElementsByTagName('kerning'); - - for (i = 0; i < kernings.length; i++) - { - var kern = kernings[i]; - - var first = getValue(kern, 'first'); - var second = getValue(kern, 'second'); - var amount = getValue(kern, 'amount'); - - data.chars[second].kerning[first] = amount; - } - - return data; -}; - -module.exports = ParseXMLBitmapFont; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Read an integer value from an XML Node. + * + * @function getValue + * @since 3.0.0 + * @private + * + * @param {Node} node - The XML Node. + * @param {string} attribute - The attribute to read. + * + * @return {integer} The parsed value. + */ +function getValue (node, attribute) +{ + return parseInt(node.getAttribute(attribute), 10); +} + +/** + * Parse an XML font to Bitmap Font data for the Bitmap Font cache. + * + * @function ParseXMLBitmapFont + * @since 3.0.0 + * @private + * + * @param {XMLDocument} xml - The XML Document to parse the font from. + * @param {integer} [xSpacing=0] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing=0] - The y-axis spacing to add to the line height. + * @param {Phaser.Textures.Frame} [frame] - The texture frame to take into account while parsing. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapFontData} The parsed Bitmap Font data. + */ +var ParseXMLBitmapFont = function (xml, xSpacing, ySpacing, frame) +{ + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = getValue(info, 'size'); + data.lineHeight = getValue(common, 'lineHeight') + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var adjustForTrim = (frame !== undefined && frame.trimmed); + + if (adjustForTrim) + { + var top = frame.height; + var left = frame.width; + } + + for (var i = 0; i < letters.length; i++) + { + var node = letters[i]; + + var charCode = getValue(node, 'id'); + var gx = getValue(node, 'x'); + var gy = getValue(node, 'y'); + var gw = getValue(node, 'width'); + var gh = getValue(node, 'height'); + + // Handle frame trim issues + + if (adjustForTrim) + { + if (gx < left) + { + left = gx; + } + + if (gy < top) + { + top = gy; + } + } + + data.chars[charCode] = + { + x: gx, + y: gy, + width: gw, + height: gh, + centerX: Math.floor(gw / 2), + centerY: Math.floor(gh / 2), + xOffset: getValue(node, 'xoffset'), + yOffset: getValue(node, 'yoffset'), + xAdvance: getValue(node, 'xadvance') + xSpacing, + data: {}, + kerning: {} + }; + } + + if (adjustForTrim && top !== 0 && left !== 0) + { + // Now we know the top and left coordinates of the glyphs in the original data + // so we can work out how much to adjust the glyphs by + + for (var code in data.chars) + { + var glyph = data.chars[code]; + + glyph.x -= frame.x; + glyph.y -= frame.y; + } + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var kern = kernings[i]; + + var first = getValue(kern, 'first'); + var second = getValue(kern, 'second'); + var amount = getValue(kern, 'amount'); + + data.chars[second].kerning[first] = amount; + } + + return data; +}; + +module.exports = ParseXMLBitmapFont; diff --git a/src/gameobjects/bitmaptext/RetroFont.js b/src/gameobjects/bitmaptext/RetroFont.js index 45d2a5f75..0e8c17293 100644 --- a/src/gameobjects/bitmaptext/RetroFont.js +++ b/src/gameobjects/bitmaptext/RetroFont.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RETRO_FONT_CONST = require('./const'); -var Extend = require('../../utils/object/Extend'); - -/** - * @namespace Phaser.GameObjects.RetroFont - * @since 3.6.0 - */ - -var RetroFont = { Parse: require('./ParseRetroFont') }; - -// Merge in the consts -RetroFont = Extend(false, RetroFont, RETRO_FONT_CONST); - -module.exports = RetroFont; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RETRO_FONT_CONST = require('./const'); +var Extend = require('../../utils/object/Extend'); + +/** + * @namespace Phaser.GameObjects.RetroFont + * @since 3.6.0 + */ + +var RetroFont = { Parse: require('./ParseRetroFont') }; + +// Merge in the consts +RetroFont = Extend(false, RetroFont, RETRO_FONT_CONST); + +module.exports = RetroFont; diff --git a/src/gameobjects/bitmaptext/const.js b/src/gameobjects/bitmaptext/const.js index ce02e7731..09f6e12a2 100644 --- a/src/gameobjects/bitmaptext/const.js +++ b/src/gameobjects/bitmaptext/const.js @@ -1,110 +1,110 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RETRO_FONT_CONST = { - - /** - * Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET1 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET1: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~', - - /** - * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET2 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET2: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ', - - /** - * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET3 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET3: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ', - - /** - * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET4 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET4: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789', - - /** - * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET5 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET5: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() \'!?-*:0123456789', - - /** - * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET6 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET6: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.\' ', - - /** - * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET7 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET7: 'AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-\'39', - - /** - * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET8 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET8: '0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ', - - /** - * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET9 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET9: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,\'"?!', - - /** - * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET10 - * @type {string} - * @since 3.6.0 - */ - TEXT_SET10: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - - /** - * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 - * - * @name Phaser.GameObjects.RetroFont.TEXT_SET11 - * @since 3.6.0 - * @type {string} - */ - TEXT_SET11: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()\':;0123456789' - -}; - -module.exports = RETRO_FONT_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RETRO_FONT_CONST = { + + /** + * Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET1 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET1: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~', + + /** + * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET2 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET2: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET3 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET3: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ', + + /** + * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET4 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET4: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789', + + /** + * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET5 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET5: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() \'!?-*:0123456789', + + /** + * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET6 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET6: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.\' ', + + /** + * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET7 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET7: 'AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-\'39', + + /** + * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET8 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET8: '0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET9 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET9: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,\'"?!', + + /** + * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET10 + * @type {string} + * @since 3.6.0 + */ + TEXT_SET10: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 + * + * @name Phaser.GameObjects.RetroFont.TEXT_SET11 + * @since 3.6.0 + * @type {string} + */ + TEXT_SET11: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()\':;0123456789' + +}; + +module.exports = RETRO_FONT_CONST; diff --git a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapText.js b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapText.js index a1e99f1cc..610d5ed00 100644 --- a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapText.js +++ b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapText.js @@ -1,227 +1,227 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BitmapText = require('../static/BitmapText'); -var Class = require('../../../utils/Class'); -var Render = require('./DynamicBitmapTextRender'); - -/** - * @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. - * - * 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): 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 - * - * @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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. - */ -var DynamicBitmapText = new Class({ - - Extends: BitmapText, - - Mixins: [ - Render - ], - - initialize: - - function DynamicBitmapText (scene, x, y, font, text, size, align) - { - BitmapText.call(this, scene, x, y, font, text, size, align); - - this.type = 'DynamicBitmapText'; - - /** - * The horizontal scroll position of the Bitmap Text. - * - * @name Phaser.GameObjects.DynamicBitmapText#scrollX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.scrollX = 0; - - /** - * The vertical scroll position of the Bitmap Text. - * - * @name Phaser.GameObjects.DynamicBitmapText#scrollY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.scrollY = 0; - - /** - * The crop width of the Bitmap Text. - * - * @name Phaser.GameObjects.DynamicBitmapText#cropWidth - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.cropWidth = 0; - - /** - * The crop height of the Bitmap Text. - * - * @name Phaser.GameObjects.DynamicBitmapText#cropHeight - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.cropHeight = 0; - - /** - * A callback that alters how each character of the Bitmap Text is rendered. - * - * @name Phaser.GameObjects.DynamicBitmapText#displayCallback - * @type {Phaser.Types.GameObjects.BitmapText.DisplayCallback} - * @since 3.0.0 - */ - this.displayCallback; - - /** - * The data object that is populated during rendering, then passed to the displayCallback. - * You should modify this object then return it back from the callback. It's updated values - * will be used to render the specific glyph. - * - * Please note that if you need a reference to this object locally in your game code then you - * should shallow copy it, as it's updated and re-used for every glyph in the text. - * - * @name Phaser.GameObjects.DynamicBitmapText#callbackData - * @type {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} - * @since 3.11.0 - */ - this.callbackData = { - parent: this, - color: 0, - tint: { - topLeft: 0, - topRight: 0, - bottomLeft: 0, - bottomRight: 0 - }, - index: 0, - charCode: 0, - x: 0, - y: 0, - scale: 0, - rotation: 0, - data: 0 - }; - }, - - /** - * Set the crop size of this Bitmap Text. - * - * @method Phaser.GameObjects.DynamicBitmapText#setSize - * @since 3.0.0 - * - * @param {number} width - The width of the crop. - * @param {number} height - The height of the crop. - * - * @return {this} This Game Object. - */ - setSize: function (width, height) - { - this.cropWidth = width; - this.cropHeight = height; - - return this; - }, - - /** - * Set a callback that alters how each character of the Bitmap Text is rendered. - * - * The callback receives a {@link Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} object that contains information about the character that's - * about to be rendered. - * - * It should return an object with `x`, `y`, `scale` and `rotation` properties that will be used instead of the - * usual values when rendering. - * - * @method Phaser.GameObjects.DynamicBitmapText#setDisplayCallback - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallback} callback - The display callback to set. - * - * @return {this} This Game Object. - */ - setDisplayCallback: function (callback) - { - this.displayCallback = callback; - - return this; - }, - - /** - * Set the horizontal scroll position of this Bitmap Text. - * - * @method Phaser.GameObjects.DynamicBitmapText#setScrollX - * @since 3.0.0 - * - * @param {number} value - The horizontal scroll position to set. - * - * @return {this} This Game Object. - */ - setScrollX: function (value) - { - this.scrollX = value; - - return this; - }, - - /** - * Set the vertical scroll position of this Bitmap Text. - * - * @method Phaser.GameObjects.DynamicBitmapText#setScrollY - * @since 3.0.0 - * - * @param {number} value - The vertical scroll position to set. - * - * @return {this} This Game Object. - */ - setScrollY: function (value) - { - this.scrollY = value; - - return this; - } - -}); - -module.exports = DynamicBitmapText; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = require('../static/BitmapText'); +var Class = require('../../../utils/Class'); +var Render = require('./DynamicBitmapTextRender'); + +/** + * @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. + * + * 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): 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 + * + * @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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. + */ +var DynamicBitmapText = new Class({ + + Extends: BitmapText, + + Mixins: [ + Render + ], + + initialize: + + function DynamicBitmapText (scene, x, y, font, text, size, align) + { + BitmapText.call(this, scene, x, y, font, text, size, align); + + this.type = 'DynamicBitmapText'; + + /** + * The horizontal scroll position of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#scrollX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.scrollX = 0; + + /** + * The vertical scroll position of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#scrollY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.scrollY = 0; + + /** + * The crop width of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#cropWidth + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.cropWidth = 0; + + /** + * The crop height of the Bitmap Text. + * + * @name Phaser.GameObjects.DynamicBitmapText#cropHeight + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.cropHeight = 0; + + /** + * A callback that alters how each character of the Bitmap Text is rendered. + * + * @name Phaser.GameObjects.DynamicBitmapText#displayCallback + * @type {Phaser.Types.GameObjects.BitmapText.DisplayCallback} + * @since 3.0.0 + */ + this.displayCallback; + + /** + * The data object that is populated during rendering, then passed to the displayCallback. + * You should modify this object then return it back from the callback. It's updated values + * will be used to render the specific glyph. + * + * Please note that if you need a reference to this object locally in your game code then you + * should shallow copy it, as it's updated and re-used for every glyph in the text. + * + * @name Phaser.GameObjects.DynamicBitmapText#callbackData + * @type {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} + * @since 3.11.0 + */ + this.callbackData = { + parent: this, + color: 0, + tint: { + topLeft: 0, + topRight: 0, + bottomLeft: 0, + bottomRight: 0 + }, + index: 0, + charCode: 0, + x: 0, + y: 0, + scale: 0, + rotation: 0, + data: 0 + }; + }, + + /** + * Set the crop size of this Bitmap Text. + * + * @method Phaser.GameObjects.DynamicBitmapText#setSize + * @since 3.0.0 + * + * @param {number} width - The width of the crop. + * @param {number} height - The height of the crop. + * + * @return {this} This Game Object. + */ + setSize: function (width, height) + { + this.cropWidth = width; + this.cropHeight = height; + + return this; + }, + + /** + * Set a callback that alters how each character of the Bitmap Text is rendered. + * + * The callback receives a {@link Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} object that contains information about the character that's + * about to be rendered. + * + * It should return an object with `x`, `y`, `scale` and `rotation` properties that will be used instead of the + * usual values when rendering. + * + * @method Phaser.GameObjects.DynamicBitmapText#setDisplayCallback + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallback} callback - The display callback to set. + * + * @return {this} This Game Object. + */ + setDisplayCallback: function (callback) + { + this.displayCallback = callback; + + return this; + }, + + /** + * Set the horizontal scroll position of this Bitmap Text. + * + * @method Phaser.GameObjects.DynamicBitmapText#setScrollX + * @since 3.0.0 + * + * @param {number} value - The horizontal scroll position to set. + * + * @return {this} This Game Object. + */ + setScrollX: function (value) + { + this.scrollX = value; + + return this; + }, + + /** + * Set the vertical scroll position of this Bitmap Text. + * + * @method Phaser.GameObjects.DynamicBitmapText#setScrollY + * @since 3.0.0 + * + * @param {number} value - The vertical scroll position to set. + * + * @return {this} This Game Object. + */ + setScrollY: function (value) + { + this.scrollY = value; + + return this; + } + +}); + +module.exports = DynamicBitmapText; diff --git a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCanvasRenderer.js b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCanvasRenderer.js index c42997bd3..705c3e220 100644 --- a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCanvasRenderer.js +++ b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCanvasRenderer.js @@ -1,205 +1,205 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.DynamicBitmapText#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.DynamicBitmapText} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var DynamicBitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var text = src._text; - var textLength = text.length; - - var ctx = renderer.currentContext; - - if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - return; - } - - var textureFrame = src.frame; - - var displayCallback = src.displayCallback; - var callbackData = src.callbackData; - - var chars = src.fontData.chars; - var lineHeight = src.fontData.lineHeight; - var letterSpacing = src._letterSpacing; - - var xAdvance = 0; - var yAdvance = 0; - - var charCode = 0; - - var glyph = null; - var glyphX = 0; - var glyphY = 0; - var glyphW = 0; - var glyphH = 0; - - var x = 0; - var y = 0; - - var lastGlyph = null; - var lastCharCode = 0; - - var image = src.frame.source.image; - - var textureX = textureFrame.cutX; - var textureY = textureFrame.cutY; - - var rotation = 0; - var scale = 0; - var baseScale = (src._fontSize / src.fontData.size); - - var align = src._align; - var currentLine = 0; - var lineOffsetX = 0; - - // Update the bounds - skipped internally if not dirty - src.getTextBounds(false); - - var lineData = src._bounds.lines; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]); - } - - ctx.translate(-src.displayOriginX, -src.displayOriginY); - - var roundPixels = camera.roundPixels; - - if (src.cropWidth > 0 && src.cropHeight > 0) - { - ctx.beginPath(); - ctx.rect(0, 0, src.cropWidth, src.cropHeight); - ctx.clip(); - } - - for (var i = 0; i < textLength; i++) - { - // Reset the scale (in case the callback changed it) - scale = baseScale; - rotation = 0; - - charCode = text.charCodeAt(i); - - if (charCode === 10) - { - currentLine++; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); - } - - xAdvance = 0; - yAdvance += lineHeight; - lastGlyph = null; - - continue; - } - - glyph = chars[charCode]; - - if (!glyph) - { - continue; - } - - glyphX = textureX + glyph.x; - glyphY = textureY + glyph.y; - - glyphW = glyph.width; - glyphH = glyph.height; - - x = (glyph.xOffset + xAdvance) - src.scrollX; - y = (glyph.yOffset + yAdvance) - src.scrollY; - - if (lastGlyph !== null) - { - var kerningOffset = glyph.kerning[lastCharCode]; - x += (kerningOffset !== undefined) ? kerningOffset : 0; - } - - if (displayCallback) - { - callbackData.index = i; - callbackData.charCode = charCode; - callbackData.x = x; - callbackData.y = y; - callbackData.scale = scale; - callbackData.rotation = rotation; - callbackData.data = glyph.data; - - var output = displayCallback(callbackData); - - x = output.x; - y = output.y; - scale = output.scale; - rotation = output.rotation; - } - - x *= scale; - y *= scale; - - x += lineOffsetX; - - xAdvance += glyph.xAdvance + letterSpacing; - lastGlyph = glyph; - lastCharCode = charCode; - - // Nothing to render or a space? Then skip to the next glyph - if (glyphW === 0 || glyphH === 0 || charCode === 32) - { - continue; - } - - if (roundPixels) - { - x = Math.round(x); - y = Math.round(y); - } - - ctx.save(); - - ctx.translate(x, y); - - ctx.rotate(rotation); - - ctx.scale(scale, scale); - - ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); - - ctx.restore(); - } - - ctx.restore(); -}; - -module.exports = DynamicBitmapTextCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.DynamicBitmapText#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.DynamicBitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DynamicBitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src._text; + var textLength = text.length; + + var ctx = renderer.currentContext; + + if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + return; + } + + var textureFrame = src.frame; + + var displayCallback = src.displayCallback; + var callbackData = src.callbackData; + + var chars = src.fontData.chars; + var lineHeight = src.fontData.lineHeight; + var letterSpacing = src._letterSpacing; + + var xAdvance = 0; + var yAdvance = 0; + + var charCode = 0; + + var glyph = null; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + + var x = 0; + var y = 0; + + var lastGlyph = null; + var lastCharCode = 0; + + var image = src.frame.source.image; + + var textureX = textureFrame.cutX; + var textureY = textureFrame.cutY; + + var rotation = 0; + var scale = 0; + var baseScale = (src._fontSize / src.fontData.size); + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + src.getTextBounds(false); + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + ctx.translate(-src.displayOriginX, -src.displayOriginY); + + var roundPixels = camera.roundPixels; + + if (src.cropWidth > 0 && src.cropHeight > 0) + { + ctx.beginPath(); + ctx.rect(0, 0, src.cropWidth, src.cropHeight); + ctx.clip(); + } + + for (var i = 0; i < textLength; i++) + { + // Reset the scale (in case the callback changed it) + scale = baseScale; + rotation = 0; + + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + x = (glyph.xOffset + xAdvance) - src.scrollX; + y = (glyph.yOffset + yAdvance) - src.scrollY; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + if (displayCallback) + { + callbackData.index = i; + callbackData.charCode = charCode; + callbackData.x = x; + callbackData.y = y; + callbackData.scale = scale; + callbackData.rotation = rotation; + callbackData.data = glyph.data; + + var output = displayCallback(callbackData); + + x = output.x; + y = output.y; + scale = output.scale; + rotation = output.rotation; + } + + x *= scale; + y *= scale; + + x += lineOffsetX; + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + if (roundPixels) + { + x = Math.round(x); + y = Math.round(y); + } + + ctx.save(); + + ctx.translate(x, y); + + ctx.rotate(rotation); + + ctx.scale(scale, scale); + + ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); + + ctx.restore(); + } + + ctx.restore(); +}; + +module.exports = DynamicBitmapTextCanvasRenderer; diff --git a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCreator.js b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCreator.js index ce66f9edf..08a8a7fb5 100644 --- a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCreator.js +++ b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextCreator.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BitmapText = require('./DynamicBitmapText'); -var BuildGameObject = require('../../BuildGameObject'); -var GameObjectCreator = require('../../GameObjectCreator'); -var GetAdvancedValue = require('../../../utils/object/GetAdvancedValue'); - -/** - * Creates a new Dynamic Bitmap Text Game Object and returns it. - * - * Note: This method will only be available if the Dynamic Bitmap Text Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#dynamicBitmapText - * @since 3.0.0 - *² - * @param {Phaser.Types.GameObjects.BitmapText.BitmapTextConfig} 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.DynamicBitmapText} The Game Object that was created. - */ -GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var font = GetAdvancedValue(config, 'font', ''); - var text = GetAdvancedValue(config, 'text', ''); - var size = GetAdvancedValue(config, 'size', false); - - var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, bitmapText, config); - - return bitmapText; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = require('./DynamicBitmapText'); +var BuildGameObject = require('../../BuildGameObject'); +var GameObjectCreator = require('../../GameObjectCreator'); +var GetAdvancedValue = require('../../../utils/object/GetAdvancedValue'); + +/** + * Creates a new Dynamic Bitmap Text Game Object and returns it. + * + * Note: This method will only be available if the Dynamic Bitmap Text Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#dynamicBitmapText + * @since 3.0.0 + *² + * @param {Phaser.Types.GameObjects.BitmapText.BitmapTextConfig} 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.DynamicBitmapText} The Game Object that was created. + */ +GameObjectCreator.register('dynamicBitmapText', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var font = GetAdvancedValue(config, 'font', ''); + var text = GetAdvancedValue(config, 'text', ''); + var size = GetAdvancedValue(config, 'size', false); + + var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, bitmapText, config); + + return bitmapText; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextFactory.js b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextFactory.js index efc3083ec..4ff792f3b 100644 --- a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextFactory.js +++ b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextFactory.js @@ -1,63 +1,63 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DynamicBitmapText = require('./DynamicBitmapText'); -var GameObjectFactory = require('../../GameObjectFactory'); - -/** - * 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 for 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): 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. - */ -GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size) -{ - return this.displayList.add(new DynamicBitmapText(this.scene, x, y, font, text, size)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DynamicBitmapText = require('./DynamicBitmapText'); +var GameObjectFactory = require('../../GameObjectFactory'); + +/** + * 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 for 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): 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. + */ +GameObjectFactory.register('dynamicBitmapText', function (x, y, font, text, size) +{ + return this.displayList.add(new DynamicBitmapText(this.scene, x, y, font, text, size)); +}); + +// 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 diff --git a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextRender.js b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextRender.js index 498350a92..32a3afa32 100644 --- a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextRender.js +++ b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./DynamicBitmapTextWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./DynamicBitmapTextCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./DynamicBitmapTextWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./DynamicBitmapTextCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextWebGLRenderer.js b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextWebGLRenderer.js index ee4595094..51a254348 100644 --- a/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextWebGLRenderer.js +++ b/src/gameobjects/bitmaptext/dynamic/DynamicBitmapTextWebGLRenderer.js @@ -1,300 +1,300 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.DynamicBitmapText#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.DynamicBitmapText} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var DynamicBitmapTextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var text = src.text; - var textLength = text.length; - - if (textLength === 0) - { - return; - } - - var pipeline = this.pipeline; - - renderer.setPipeline(pipeline, src); - - var crop = (src.cropWidth > 0 || src.cropHeight > 0); - - if (crop) - { - pipeline.flush(); - - renderer.pushScissor( - src.x, - src.y, - src.cropWidth * src.scaleX, - src.cropHeight * src.scaleY - ); - } - - var camMatrix = pipeline._tempMatrix1; - var spriteMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - var fontMatrix = pipeline._tempMatrix4; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var frame = src.frame; - var texture = frame.glTexture; - var textureX = frame.cutX; - var textureY = frame.cutY; - var textureWidth = texture.width; - var textureHeight = texture.height; - - var tintEffect = (src._isTinted && src.tintFill); - var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); - var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); - var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); - var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); - - pipeline.setTexture2D(texture, 0); - - var xAdvance = 0; - var yAdvance = 0; - var charCode = 0; - var lastCharCode = 0; - var letterSpacing = src.letterSpacing; - var glyph; - var glyphX = 0; - var glyphY = 0; - var glyphW = 0; - var glyphH = 0; - var lastGlyph; - var scrollX = src.scrollX; - var scrollY = src.scrollY; - - var fontData = src.fontData; - var chars = fontData.chars; - var lineHeight = fontData.lineHeight; - var scale = (src.fontSize / fontData.size); - var rotation = 0; - - var align = src._align; - var currentLine = 0; - var lineOffsetX = 0; - - // Update the bounds - skipped internally if not dirty - src.getTextBounds(false); - - var lineData = src._bounds.lines; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]); - } - - var roundPixels = camera.roundPixels; - var displayCallback = src.displayCallback; - var callbackData = src.callbackData; - - for (var i = 0; i < textLength; i++) - { - charCode = text.charCodeAt(i); - - // Carriage-return - if (charCode === 10) - { - currentLine++; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); - } - - xAdvance = 0; - yAdvance += lineHeight; - lastGlyph = null; - - continue; - } - - glyph = chars[charCode]; - - if (!glyph) - { - continue; - } - - glyphX = textureX + glyph.x; - glyphY = textureY + glyph.y; - - glyphW = glyph.width; - glyphH = glyph.height; - - var x = (glyph.xOffset + xAdvance) - scrollX; - var y = (glyph.yOffset + yAdvance) - scrollY; - - if (lastGlyph !== null) - { - var kerningOffset = glyph.kerning[lastCharCode]; - x += (kerningOffset !== undefined) ? kerningOffset : 0; - } - - xAdvance += glyph.xAdvance + letterSpacing; - lastGlyph = glyph; - lastCharCode = charCode; - - // Nothing to render or a space? Then skip to the next glyph - if (glyphW === 0 || glyphH === 0 || charCode === 32) - { - continue; - } - - scale = (src.fontSize / src.fontData.size); - rotation = 0; - - if (displayCallback) - { - callbackData.color = 0; - callbackData.tint.topLeft = tintTL; - callbackData.tint.topRight = tintTR; - callbackData.tint.bottomLeft = tintBL; - callbackData.tint.bottomRight = tintBR; - callbackData.index = i; - callbackData.charCode = charCode; - callbackData.x = x; - callbackData.y = y; - callbackData.scale = scale; - callbackData.rotation = rotation; - callbackData.data = glyph.data; - - var output = displayCallback(callbackData); - - x = output.x; - y = output.y; - scale = output.scale; - rotation = output.rotation; - - if (output.color) - { - tintTL = output.color; - tintTR = output.color; - tintBL = output.color; - tintBR = output.color; - } - else - { - tintTL = output.tint.topLeft; - tintTR = output.tint.topRight; - tintBL = output.tint.bottomLeft; - tintBR = output.tint.bottomRight; - } - - tintTL = Utils.getTintAppendFloatAlpha(tintTL, camera.alpha * src._alphaTL); - tintTR = Utils.getTintAppendFloatAlpha(tintTR, camera.alpha * src._alphaTR); - tintBL = Utils.getTintAppendFloatAlpha(tintBL, camera.alpha * src._alphaBL); - tintBR = Utils.getTintAppendFloatAlpha(tintBR, camera.alpha * src._alphaBR); - } - - x *= scale; - y *= scale; - - x -= src.displayOriginX; - y -= src.displayOriginY; - - x += lineOffsetX; - - fontMatrix.applyITRS(x, y, rotation, scale, scale); - - calcMatrix.multiply(fontMatrix, spriteMatrix); - - var u0 = glyphX / textureWidth; - var v0 = glyphY / textureHeight; - var u1 = (glyphX + glyphW) / textureWidth; - var v1 = (glyphY + glyphH) / textureHeight; - - var xw = glyphW; - var yh = glyphH; - - var tx0 = spriteMatrix.e; - var ty0 = spriteMatrix.f; - - var tx1 = yh * spriteMatrix.c + spriteMatrix.e; - var ty1 = yh * spriteMatrix.d + spriteMatrix.f; - - var tx2 = xw * spriteMatrix.a + yh * spriteMatrix.c + spriteMatrix.e; - var ty2 = xw * spriteMatrix.b + yh * spriteMatrix.d + spriteMatrix.f; - - var tx3 = xw * spriteMatrix.a + spriteMatrix.e; - var ty3 = xw * spriteMatrix.b + spriteMatrix.f; - - if (roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); - } - - if (crop) - { - pipeline.flush(); - - renderer.popScissor(); - } -}; - -module.exports = DynamicBitmapTextWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.DynamicBitmapText#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.DynamicBitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DynamicBitmapTextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src.text; + var textLength = text.length; + + if (textLength === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var crop = (src.cropWidth > 0 || src.cropHeight > 0); + + if (crop) + { + pipeline.flush(); + + renderer.pushScissor( + src.x, + src.y, + src.cropWidth * src.scaleX, + src.cropHeight * src.scaleY + ); + } + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + var fontMatrix = pipeline._tempMatrix4; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + var textureX = frame.cutX; + var textureY = frame.cutY; + var textureWidth = texture.width; + var textureHeight = texture.height; + + var tintEffect = (src._isTinted && src.tintFill); + var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); + var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); + var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); + var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); + + pipeline.setTexture2D(texture, 0); + + var xAdvance = 0; + var yAdvance = 0; + var charCode = 0; + var lastCharCode = 0; + var letterSpacing = src.letterSpacing; + var glyph; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + var lastGlyph; + var scrollX = src.scrollX; + var scrollY = src.scrollY; + + var fontData = src.fontData; + var chars = fontData.chars; + var lineHeight = fontData.lineHeight; + var scale = (src.fontSize / fontData.size); + var rotation = 0; + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + src.getTextBounds(false); + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + var roundPixels = camera.roundPixels; + var displayCallback = src.displayCallback; + var callbackData = src.callbackData; + + for (var i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + // Carriage-return + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + var x = (glyph.xOffset + xAdvance) - scrollX; + var y = (glyph.yOffset + yAdvance) - scrollY; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + scale = (src.fontSize / src.fontData.size); + rotation = 0; + + if (displayCallback) + { + callbackData.color = 0; + callbackData.tint.topLeft = tintTL; + callbackData.tint.topRight = tintTR; + callbackData.tint.bottomLeft = tintBL; + callbackData.tint.bottomRight = tintBR; + callbackData.index = i; + callbackData.charCode = charCode; + callbackData.x = x; + callbackData.y = y; + callbackData.scale = scale; + callbackData.rotation = rotation; + callbackData.data = glyph.data; + + var output = displayCallback(callbackData); + + x = output.x; + y = output.y; + scale = output.scale; + rotation = output.rotation; + + if (output.color) + { + tintTL = output.color; + tintTR = output.color; + tintBL = output.color; + tintBR = output.color; + } + else + { + tintTL = output.tint.topLeft; + tintTR = output.tint.topRight; + tintBL = output.tint.bottomLeft; + tintBR = output.tint.bottomRight; + } + + tintTL = Utils.getTintAppendFloatAlpha(tintTL, camera.alpha * src._alphaTL); + tintTR = Utils.getTintAppendFloatAlpha(tintTR, camera.alpha * src._alphaTR); + tintBL = Utils.getTintAppendFloatAlpha(tintBL, camera.alpha * src._alphaBL); + tintBR = Utils.getTintAppendFloatAlpha(tintBR, camera.alpha * src._alphaBR); + } + + x *= scale; + y *= scale; + + x -= src.displayOriginX; + y -= src.displayOriginY; + + x += lineOffsetX; + + fontMatrix.applyITRS(x, y, rotation, scale, scale); + + calcMatrix.multiply(fontMatrix, spriteMatrix); + + var u0 = glyphX / textureWidth; + var v0 = glyphY / textureHeight; + var u1 = (glyphX + glyphW) / textureWidth; + var v1 = (glyphY + glyphH) / textureHeight; + + var xw = glyphW; + var yh = glyphH; + + var tx0 = spriteMatrix.e; + var ty0 = spriteMatrix.f; + + var tx1 = yh * spriteMatrix.c + spriteMatrix.e; + var ty1 = yh * spriteMatrix.d + spriteMatrix.f; + + var tx2 = xw * spriteMatrix.a + yh * spriteMatrix.c + spriteMatrix.e; + var ty2 = xw * spriteMatrix.b + yh * spriteMatrix.d + spriteMatrix.f; + + var tx3 = xw * spriteMatrix.a + spriteMatrix.e; + var ty3 = xw * spriteMatrix.b + spriteMatrix.f; + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + } + + if (crop) + { + pipeline.flush(); + + renderer.popScissor(); + } +}; + +module.exports = DynamicBitmapTextWebGLRenderer; diff --git a/src/gameobjects/bitmaptext/static/BitmapText.js b/src/gameobjects/bitmaptext/static/BitmapText.js index 7ade82888..e11462f0c 100644 --- a/src/gameobjects/bitmaptext/static/BitmapText.js +++ b/src/gameobjects/bitmaptext/static/BitmapText.js @@ -1,723 +1,723 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Components = require('../../components'); -var GameObject = require('../../GameObject'); -var GetBitmapTextSize = require('../GetBitmapTextSize'); -var ParseFromAtlas = require('../ParseFromAtlas'); -var ParseXMLBitmapFont = require('../ParseXMLBitmapFont'); -var Render = require('./BitmapTextRender'); - -/** - * @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} - * Littera (Web-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.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. - */ -var BitmapText = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Texture, - Components.Tint, - Components.Transform, - Components.Visible, - Render - ], - - initialize: - - function BitmapText (scene, x, y, font, text, size, align) - { - if (text === undefined) { text = ''; } - if (align === undefined) { align = 0; } - - GameObject.call(this, scene, 'BitmapText'); - - /** - * The key of the Bitmap Font used by this Bitmap Text. - * To change the font after creation please use `setFont`. - * - * @name Phaser.GameObjects.BitmapText#font - * @type {string} - * @readonly - * @since 3.0.0 - */ - this.font = font; - - var entry = this.scene.sys.cache.bitmapFont.get(font); - - /** - * The data of the Bitmap Font used by this Bitmap Text. - * - * @name Phaser.GameObjects.BitmapText#fontData - * @type {Phaser.Types.GameObjects.BitmapText.BitmapFontData} - * @readonly - * @since 3.0.0 - */ - this.fontData = entry.data; - - /** - * The text that this Bitmap Text object displays. - * - * @name Phaser.GameObjects.BitmapText#_text - * @type {string} - * @private - * @since 3.0.0 - */ - this._text = ''; - - /** - * The font size of this Bitmap Text. - * - * @name Phaser.GameObjects.BitmapText#_fontSize - * @type {number} - * @private - * @since 3.0.0 - */ - this._fontSize = size || this.fontData.size; - - /** - * Adds / Removes spacing between characters. - * - * Can be a negative or positive number. - * - * @name Phaser.GameObjects.BitmapText#_letterSpacing - * @type {number} - * @private - * @since 3.4.0 - */ - this._letterSpacing = 0; - - /** - * 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 {integer} - * @private - * @since 3.11.0 - */ - this._align = align; - - /** - * An object that describes the size of this Bitmap Text. - * - * @name Phaser.GameObjects.BitmapText#_bounds - * @type {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} - * @private - * @since 3.0.0 - */ - this._bounds = GetBitmapTextSize(); - - /** - * An internal dirty flag for bounds calculation. - * - * @name Phaser.GameObjects.BitmapText#_dirty - * @type {boolean} - * @private - * @since 3.11.0 - */ - this._dirty = true; - - /** - * Internal cache var holding the maxWidth. - * - * @name Phaser.GameObjects.BitmapText#_maxWidth - * @type {number} - * @private - * @since 3.21.0 - */ - this._maxWidth = 0; - - /** - * The character code used to detect for word wrapping. - * Defaults to 32 (a space character). - * - * @name Phaser.GameObjects.BitmapText#wordWrapCharCode - * @type {number} - * @since 3.21.0 - */ - this.wordWrapCharCode = 32; - - this.setTexture(entry.texture, entry.frame); - this.setPosition(x, y); - this.setOrigin(0, 0); - this.initPipeline(); - - this.setText(text); - }, - - /** - * Set the lines of text in this BitmapText to be left-aligned. - * This only has any effect if this BitmapText contains more than one line of text. - * - * @method Phaser.GameObjects.BitmapText#setLeftAlign - * @since 3.11.0 - * - * @return {this} This BitmapText Object. - */ - setLeftAlign: function () - { - this._align = BitmapText.ALIGN_LEFT; - - this._dirty = true; - - return this; - }, - - /** - * Set the lines of text in this BitmapText to be center-aligned. - * This only has any effect if this BitmapText contains more than one line of text. - * - * @method Phaser.GameObjects.BitmapText#setCenterAlign - * @since 3.11.0 - * - * @return {this} This BitmapText Object. - */ - setCenterAlign: function () - { - this._align = BitmapText.ALIGN_CENTER; - - this._dirty = true; - - return this; - }, - - /** - * Set the lines of text in this BitmapText to be right-aligned. - * This only has any effect if this BitmapText contains more than one line of text. - * - * @method Phaser.GameObjects.BitmapText#setRightAlign - * @since 3.11.0 - * - * @return {this} This BitmapText Object. - */ - setRightAlign: function () - { - this._align = BitmapText.ALIGN_RIGHT; - - this._dirty = true; - - return this; - }, - - /** - * Set the font size of this Bitmap Text. - * - * @method Phaser.GameObjects.BitmapText#setFontSize - * @since 3.0.0 - * - * @param {number} size - The font size to set. - * - * @return {this} This BitmapText Object. - */ - setFontSize: function (size) - { - this._fontSize = size; - - this._dirty = true; - - return this; - }, - - /** - * Sets the letter spacing between each character of this Bitmap Text. - * Can be a positive value to increase the space, or negative to reduce it. - * Spacing is applied after the kerning values have been set. - * - * @method Phaser.GameObjects.BitmapText#setLetterSpacing - * @since 3.4.0 - * - * @param {number} [spacing=0] - The amount of horizontal space to add between each character. - * - * @return {this} This BitmapText Object. - */ - setLetterSpacing: function (spacing) - { - if (spacing === undefined) { spacing = 0; } - - this._letterSpacing = spacing; - - this._dirty = true; - - return this; - }, - - /** - * Set the textual content of this BitmapText. - * - * An array of strings will be converted into multi-line text. Use the align methods to change multi-line alignment. - * - * @method Phaser.GameObjects.BitmapText#setText - * @since 3.0.0 - * - * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this BitmapText. - * - * @return {this} This BitmapText Object. - */ - setText: function (value) - { - if (!value && value !== 0) - { - value = ''; - } - - if (Array.isArray(value)) - { - value = value.join('\n'); - } - - if (value !== this.text) - { - this._text = value.toString(); - - this._dirty = true; - - this.updateDisplayOrigin(); - } - - return this; - }, - - /** - * 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] - Whether to round the results to the nearest integer. - * - * @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} An object that describes the size of this Bitmap Text. - */ - getTextBounds: function (round) - { - // local = The BitmapText based on fontSize and 0x0 coords - // global = The BitmapText, taking into account scale and world position - // lines = The BitmapText line data - - var bounds = this._bounds; - - if (this._dirty || this.scaleX !== bounds.scaleX || this.scaleY !== bounds.scaleY) - { - GetBitmapTextSize(this, round, bounds); - - this._dirty = false; - - this.updateDisplayOrigin(); - } - - return bounds; - }, - - /** - * Changes the font this BitmapText is using to render. - * - * The new texture is loaded and applied to the BitmapText. The existing test, size and alignment are preserved, - * unless overridden via the arguments. - * - * @method Phaser.GameObjects.BitmapText#setFont - * @since 3.11.0 - * - * @param {string} font - The key of the font to use from the Bitmap Font cache. - * @param {number} [size] - The font size of this Bitmap Text. If not specified the current size will be used. - * @param {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. If not specified the current alignment will be used. - * - * @return {this} This BitmapText Object. - */ - setFont: function (key, size, align) - { - if (size === undefined) { size = this._fontSize; } - if (align === undefined) { align = this._align; } - - if (key !== this.font) - { - var entry = this.scene.sys.cache.bitmapFont.get(key); - - if (entry) - { - this.font = key; - this.fontData = entry.data; - this._fontSize = size; - this._align = align; - - this.setTexture(entry.texture, entry.frame); - - GetBitmapTextSize(this, false, this._bounds); - } - } - - return this; - }, - - /** - * 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. - */ - setMaxWidth: function (value, wordWrapCharCode) - { - this._maxWidth = value; - - this._dirty = true; - - if (wordWrapCharCode !== undefined) - { - this.wordWrapCharCode = wordWrapCharCode; - } - - return this; - }, - - /** - * 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 {integer} - * @since 3.11.0 - */ - align: { - - set: function (value) - { - this._align = value; - this._dirty = true; - }, - - get: function () - { - return this._align; - } - - }, - - /** - * The text that this Bitmap Text object displays. - * - * You can also use the method `setText` if you want a chainable way to change the text content. - * - * @name Phaser.GameObjects.BitmapText#text - * @type {string} - * @since 3.0.0 - */ - text: { - - set: function (value) - { - this.setText(value); - }, - - get: function () - { - return this._text; - } - - }, - - /** - * The font size of this Bitmap Text. - * - * You can also use the method `setFontSize` if you want a chainable way to change the font size. - * - * @name Phaser.GameObjects.BitmapText#fontSize - * @type {number} - * @since 3.0.0 - */ - fontSize: { - - set: function (value) - { - this._fontSize = value; - this._dirty = true; - }, - - get: function () - { - return this._fontSize; - } - - }, - - /** - * Adds / Removes spacing between characters. - * - * Can be a negative or positive number. - * - * You can also use the method `setLetterSpacing` if you want a chainable way to change the letter spacing. - * - * @name Phaser.GameObjects.BitmapText#letterSpacing - * @type {number} - * @since 3.0.0 - */ - letterSpacing: { - - set: function (value) - { - this._letterSpacing = value; - this._dirty = true; - }, - - get: function () - { - return this._letterSpacing; - } - - }, - - /** - * 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 - */ - maxWidth: { - - set: function (value) - { - this._maxWidth = value; - this._dirty = true; - }, - - get: function () - { - return this._maxWidth; - } - - }, - - /** - * The width of this Bitmap Text. - * - * @name Phaser.GameObjects.BitmapText#width - * @type {number} - * @readonly - * @since 3.0.0 - */ - width: { - - get: function () - { - this.getTextBounds(false); - - return this._bounds.global.width; - } - - }, - - /** - * The height of this bitmap text. - * - * @name Phaser.GameObjects.BitmapText#height - * @type {number} - * @readonly - * @since 3.0.0 - */ - height: { - - get: function () - { - this.getTextBounds(false); - - return this._bounds.global.height; - } - - }, - - /** - * Build a JSON representation of this Bitmap Text. - * - * @method Phaser.GameObjects.BitmapText#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.BitmapText.JSONBitmapText} A JSON representation of this Bitmap Text. - */ - toJSON: function () - { - var out = Components.ToJSON(this); - - // Extra data is added here - - var data = { - font: this.font, - text: this.text, - fontSize: this.fontSize, - letterSpacing: this.letterSpacing, - align: this.align - }; - - out.data = data; - - return out; - } - -}); - -/** - * Left align the text characters in a multi-line BitmapText object. - * - * @name Phaser.GameObjects.BitmapText.ALIGN_LEFT - * @type {integer} - * @since 3.11.0 - */ -BitmapText.ALIGN_LEFT = 0; - -/** - * Center align the text characters in a multi-line BitmapText object. - * - * @name Phaser.GameObjects.BitmapText.ALIGN_CENTER - * @type {integer} - * @since 3.11.0 - */ -BitmapText.ALIGN_CENTER = 1; - -/** - * Right align the text characters in a multi-line BitmapText object. - * - * @name Phaser.GameObjects.BitmapText.ALIGN_RIGHT - * @type {integer} - * @since 3.11.0 - */ -BitmapText.ALIGN_RIGHT = 2; - -/** - * Parse an XML Bitmap Font from an Atlas. - * - * Adds the parsed Bitmap Font data to the cache with the `fontName` key. - * - * @method Phaser.GameObjects.BitmapText.ParseFromAtlas - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to parse the Bitmap Font for. - * @param {string} fontName - The key of the font to add to the Bitmap Font cache. - * @param {string} textureKey - The key of the BitmapFont's texture. - * @param {string} frameKey - The key of the BitmapFont texture's frame. - * @param {string} xmlKey - The key of the XML data of the font to parse. - * @param {integer} [xSpacing] - The x-axis spacing to add between each letter. - * @param {integer} [ySpacing] - The y-axis spacing to add to the line height. - * - * @return {boolean} Whether the parsing was successful or not. - */ -BitmapText.ParseFromAtlas = ParseFromAtlas; - -/** - * Parse an XML font to Bitmap Font data for the Bitmap Font cache. - * - * @method Phaser.GameObjects.BitmapText.ParseXMLBitmapFont - * @since 3.17.0 - * - * @param {XMLDocument} xml - The XML Document to parse the font from. - * @param {integer} [xSpacing=0] - The x-axis spacing to add between each letter. - * @param {integer} [ySpacing=0] - The y-axis spacing to add to the line height. - * @param {Phaser.Textures.Frame} [frame] - The texture frame to take into account while parsing. - * - * @return {Phaser.Types.GameObjects.BitmapText.BitmapFontData} The parsed Bitmap Font data. - */ -BitmapText.ParseXMLBitmapFont = ParseXMLBitmapFont; - -module.exports = BitmapText; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Components = require('../../components'); +var GameObject = require('../../GameObject'); +var GetBitmapTextSize = require('../GetBitmapTextSize'); +var ParseFromAtlas = require('../ParseFromAtlas'); +var ParseXMLBitmapFont = require('../ParseXMLBitmapFont'); +var Render = require('./BitmapTextRender'); + +/** + * @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} + * Littera (Web-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.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. + */ +var BitmapText = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Texture, + Components.Tint, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + function BitmapText (scene, x, y, font, text, size, align) + { + if (text === undefined) { text = ''; } + if (align === undefined) { align = 0; } + + GameObject.call(this, scene, 'BitmapText'); + + /** + * The key of the Bitmap Font used by this Bitmap Text. + * To change the font after creation please use `setFont`. + * + * @name Phaser.GameObjects.BitmapText#font + * @type {string} + * @readonly + * @since 3.0.0 + */ + this.font = font; + + var entry = this.scene.sys.cache.bitmapFont.get(font); + + /** + * The data of the Bitmap Font used by this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#fontData + * @type {Phaser.Types.GameObjects.BitmapText.BitmapFontData} + * @readonly + * @since 3.0.0 + */ + this.fontData = entry.data; + + /** + * The text that this Bitmap Text object displays. + * + * @name Phaser.GameObjects.BitmapText#_text + * @type {string} + * @private + * @since 3.0.0 + */ + this._text = ''; + + /** + * The font size of this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#_fontSize + * @type {number} + * @private + * @since 3.0.0 + */ + this._fontSize = size || this.fontData.size; + + /** + * Adds / Removes spacing between characters. + * + * Can be a negative or positive number. + * + * @name Phaser.GameObjects.BitmapText#_letterSpacing + * @type {number} + * @private + * @since 3.4.0 + */ + this._letterSpacing = 0; + + /** + * 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 {integer} + * @private + * @since 3.11.0 + */ + this._align = align; + + /** + * An object that describes the size of this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#_bounds + * @type {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} + * @private + * @since 3.0.0 + */ + this._bounds = GetBitmapTextSize(); + + /** + * An internal dirty flag for bounds calculation. + * + * @name Phaser.GameObjects.BitmapText#_dirty + * @type {boolean} + * @private + * @since 3.11.0 + */ + this._dirty = true; + + /** + * Internal cache var holding the maxWidth. + * + * @name Phaser.GameObjects.BitmapText#_maxWidth + * @type {number} + * @private + * @since 3.21.0 + */ + this._maxWidth = 0; + + /** + * The character code used to detect for word wrapping. + * Defaults to 32 (a space character). + * + * @name Phaser.GameObjects.BitmapText#wordWrapCharCode + * @type {number} + * @since 3.21.0 + */ + this.wordWrapCharCode = 32; + + this.setTexture(entry.texture, entry.frame); + this.setPosition(x, y); + this.setOrigin(0, 0); + this.initPipeline(); + + this.setText(text); + }, + + /** + * Set the lines of text in this BitmapText to be left-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + * + * @method Phaser.GameObjects.BitmapText#setLeftAlign + * @since 3.11.0 + * + * @return {this} This BitmapText Object. + */ + setLeftAlign: function () + { + this._align = BitmapText.ALIGN_LEFT; + + this._dirty = true; + + return this; + }, + + /** + * Set the lines of text in this BitmapText to be center-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + * + * @method Phaser.GameObjects.BitmapText#setCenterAlign + * @since 3.11.0 + * + * @return {this} This BitmapText Object. + */ + setCenterAlign: function () + { + this._align = BitmapText.ALIGN_CENTER; + + this._dirty = true; + + return this; + }, + + /** + * Set the lines of text in this BitmapText to be right-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + * + * @method Phaser.GameObjects.BitmapText#setRightAlign + * @since 3.11.0 + * + * @return {this} This BitmapText Object. + */ + setRightAlign: function () + { + this._align = BitmapText.ALIGN_RIGHT; + + this._dirty = true; + + return this; + }, + + /** + * Set the font size of this Bitmap Text. + * + * @method Phaser.GameObjects.BitmapText#setFontSize + * @since 3.0.0 + * + * @param {number} size - The font size to set. + * + * @return {this} This BitmapText Object. + */ + setFontSize: function (size) + { + this._fontSize = size; + + this._dirty = true; + + return this; + }, + + /** + * Sets the letter spacing between each character of this Bitmap Text. + * Can be a positive value to increase the space, or negative to reduce it. + * Spacing is applied after the kerning values have been set. + * + * @method Phaser.GameObjects.BitmapText#setLetterSpacing + * @since 3.4.0 + * + * @param {number} [spacing=0] - The amount of horizontal space to add between each character. + * + * @return {this} This BitmapText Object. + */ + setLetterSpacing: function (spacing) + { + if (spacing === undefined) { spacing = 0; } + + this._letterSpacing = spacing; + + this._dirty = true; + + return this; + }, + + /** + * Set the textual content of this BitmapText. + * + * An array of strings will be converted into multi-line text. Use the align methods to change multi-line alignment. + * + * @method Phaser.GameObjects.BitmapText#setText + * @since 3.0.0 + * + * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this BitmapText. + * + * @return {this} This BitmapText Object. + */ + setText: function (value) + { + if (!value && value !== 0) + { + value = ''; + } + + if (Array.isArray(value)) + { + value = value.join('\n'); + } + + if (value !== this.text) + { + this._text = value.toString(); + + this._dirty = true; + + this.updateDisplayOrigin(); + } + + return this; + }, + + /** + * 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] - Whether to round the results to the nearest integer. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} An object that describes the size of this Bitmap Text. + */ + getTextBounds: function (round) + { + // local = The BitmapText based on fontSize and 0x0 coords + // global = The BitmapText, taking into account scale and world position + // lines = The BitmapText line data + + var bounds = this._bounds; + + if (this._dirty || this.scaleX !== bounds.scaleX || this.scaleY !== bounds.scaleY) + { + GetBitmapTextSize(this, round, bounds); + + this._dirty = false; + + this.updateDisplayOrigin(); + } + + return bounds; + }, + + /** + * Changes the font this BitmapText is using to render. + * + * The new texture is loaded and applied to the BitmapText. The existing test, size and alignment are preserved, + * unless overridden via the arguments. + * + * @method Phaser.GameObjects.BitmapText#setFont + * @since 3.11.0 + * + * @param {string} font - The key of the font to use from the Bitmap Font cache. + * @param {number} [size] - The font size of this Bitmap Text. If not specified the current size will be used. + * @param {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. If not specified the current alignment will be used. + * + * @return {this} This BitmapText Object. + */ + setFont: function (key, size, align) + { + if (size === undefined) { size = this._fontSize; } + if (align === undefined) { align = this._align; } + + if (key !== this.font) + { + var entry = this.scene.sys.cache.bitmapFont.get(key); + + if (entry) + { + this.font = key; + this.fontData = entry.data; + this._fontSize = size; + this._align = align; + + this.setTexture(entry.texture, entry.frame); + + GetBitmapTextSize(this, false, this._bounds); + } + } + + return this; + }, + + /** + * 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. + */ + setMaxWidth: function (value, wordWrapCharCode) + { + this._maxWidth = value; + + this._dirty = true; + + if (wordWrapCharCode !== undefined) + { + this.wordWrapCharCode = wordWrapCharCode; + } + + return this; + }, + + /** + * 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 {integer} + * @since 3.11.0 + */ + align: { + + set: function (value) + { + this._align = value; + this._dirty = true; + }, + + get: function () + { + return this._align; + } + + }, + + /** + * The text that this Bitmap Text object displays. + * + * You can also use the method `setText` if you want a chainable way to change the text content. + * + * @name Phaser.GameObjects.BitmapText#text + * @type {string} + * @since 3.0.0 + */ + text: { + + set: function (value) + { + this.setText(value); + }, + + get: function () + { + return this._text; + } + + }, + + /** + * The font size of this Bitmap Text. + * + * You can also use the method `setFontSize` if you want a chainable way to change the font size. + * + * @name Phaser.GameObjects.BitmapText#fontSize + * @type {number} + * @since 3.0.0 + */ + fontSize: { + + set: function (value) + { + this._fontSize = value; + this._dirty = true; + }, + + get: function () + { + return this._fontSize; + } + + }, + + /** + * Adds / Removes spacing between characters. + * + * Can be a negative or positive number. + * + * You can also use the method `setLetterSpacing` if you want a chainable way to change the letter spacing. + * + * @name Phaser.GameObjects.BitmapText#letterSpacing + * @type {number} + * @since 3.0.0 + */ + letterSpacing: { + + set: function (value) + { + this._letterSpacing = value; + this._dirty = true; + }, + + get: function () + { + return this._letterSpacing; + } + + }, + + /** + * 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 + */ + maxWidth: { + + set: function (value) + { + this._maxWidth = value; + this._dirty = true; + }, + + get: function () + { + return this._maxWidth; + } + + }, + + /** + * The width of this Bitmap Text. + * + * @name Phaser.GameObjects.BitmapText#width + * @type {number} + * @readonly + * @since 3.0.0 + */ + width: { + + get: function () + { + this.getTextBounds(false); + + return this._bounds.global.width; + } + + }, + + /** + * The height of this bitmap text. + * + * @name Phaser.GameObjects.BitmapText#height + * @type {number} + * @readonly + * @since 3.0.0 + */ + height: { + + get: function () + { + this.getTextBounds(false); + + return this._bounds.global.height; + } + + }, + + /** + * Build a JSON representation of this Bitmap Text. + * + * @method Phaser.GameObjects.BitmapText#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.BitmapText.JSONBitmapText} A JSON representation of this Bitmap Text. + */ + toJSON: function () + { + var out = Components.ToJSON(this); + + // Extra data is added here + + var data = { + font: this.font, + text: this.text, + fontSize: this.fontSize, + letterSpacing: this.letterSpacing, + align: this.align + }; + + out.data = data; + + return out; + } + +}); + +/** + * Left align the text characters in a multi-line BitmapText object. + * + * @name Phaser.GameObjects.BitmapText.ALIGN_LEFT + * @type {integer} + * @since 3.11.0 + */ +BitmapText.ALIGN_LEFT = 0; + +/** + * Center align the text characters in a multi-line BitmapText object. + * + * @name Phaser.GameObjects.BitmapText.ALIGN_CENTER + * @type {integer} + * @since 3.11.0 + */ +BitmapText.ALIGN_CENTER = 1; + +/** + * Right align the text characters in a multi-line BitmapText object. + * + * @name Phaser.GameObjects.BitmapText.ALIGN_RIGHT + * @type {integer} + * @since 3.11.0 + */ +BitmapText.ALIGN_RIGHT = 2; + +/** + * Parse an XML Bitmap Font from an Atlas. + * + * Adds the parsed Bitmap Font data to the cache with the `fontName` key. + * + * @method Phaser.GameObjects.BitmapText.ParseFromAtlas + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to parse the Bitmap Font for. + * @param {string} fontName - The key of the font to add to the Bitmap Font cache. + * @param {string} textureKey - The key of the BitmapFont's texture. + * @param {string} frameKey - The key of the BitmapFont texture's frame. + * @param {string} xmlKey - The key of the XML data of the font to parse. + * @param {integer} [xSpacing] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing] - The y-axis spacing to add to the line height. + * + * @return {boolean} Whether the parsing was successful or not. + */ +BitmapText.ParseFromAtlas = ParseFromAtlas; + +/** + * Parse an XML font to Bitmap Font data for the Bitmap Font cache. + * + * @method Phaser.GameObjects.BitmapText.ParseXMLBitmapFont + * @since 3.17.0 + * + * @param {XMLDocument} xml - The XML Document to parse the font from. + * @param {integer} [xSpacing=0] - The x-axis spacing to add between each letter. + * @param {integer} [ySpacing=0] - The y-axis spacing to add to the line height. + * @param {Phaser.Textures.Frame} [frame] - The texture frame to take into account while parsing. + * + * @return {Phaser.Types.GameObjects.BitmapText.BitmapFontData} The parsed Bitmap Font data. + */ +BitmapText.ParseXMLBitmapFont = ParseXMLBitmapFont; + +module.exports = BitmapText; diff --git a/src/gameobjects/bitmaptext/static/BitmapTextCanvasRenderer.js b/src/gameobjects/bitmaptext/static/BitmapTextCanvasRenderer.js index 571203019..88d71c03f 100644 --- a/src/gameobjects/bitmaptext/static/BitmapTextCanvasRenderer.js +++ b/src/gameobjects/bitmaptext/static/BitmapTextCanvasRenderer.js @@ -1,176 +1,176 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.BitmapText#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.BitmapText} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var BitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var text = src._text; - var textLength = text.length; - - var ctx = renderer.currentContext; - - if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - return; - } - - var textureFrame = src.frame; - - var chars = src.fontData.chars; - var lineHeight = src.fontData.lineHeight; - var letterSpacing = src._letterSpacing; - - var xAdvance = 0; - var yAdvance = 0; - - var charCode = 0; - - var glyph = null; - var glyphX = 0; - var glyphY = 0; - var glyphW = 0; - var glyphH = 0; - - var x = 0; - var y = 0; - - var lastGlyph = null; - var lastCharCode = 0; - - var image = src.frame.source.image; - - var textureX = textureFrame.cutX; - var textureY = textureFrame.cutY; - - var scale = (src._fontSize / src.fontData.size); - - var align = src._align; - var currentLine = 0; - var lineOffsetX = 0; - - // Update the bounds - skipped internally if not dirty - var bounds = src.getTextBounds(false); - - // In case the method above changed it (word wrapping) - if (src.maxWidth > 0) - { - text = bounds.wrappedText; - textLength = text.length; - } - - var lineData = src._bounds.lines; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]); - } - - ctx.translate(-src.displayOriginX, -src.displayOriginY); - - var roundPixels = camera.roundPixels; - - for (var i = 0; i < textLength; i++) - { - charCode = text.charCodeAt(i); - - if (charCode === 10) - { - currentLine++; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); - } - - xAdvance = 0; - yAdvance += lineHeight; - lastGlyph = null; - - continue; - } - - glyph = chars[charCode]; - - if (!glyph) - { - continue; - } - - glyphX = textureX + glyph.x; - glyphY = textureY + glyph.y; - - glyphW = glyph.width; - glyphH = glyph.height; - - x = glyph.xOffset + xAdvance; - y = glyph.yOffset + yAdvance; - - if (lastGlyph !== null) - { - var kerningOffset = glyph.kerning[lastCharCode]; - x += (kerningOffset !== undefined) ? kerningOffset : 0; - } - - x *= scale; - y *= scale; - - x += lineOffsetX; - - xAdvance += glyph.xAdvance + letterSpacing; - lastGlyph = glyph; - lastCharCode = charCode; - - // Nothing to render or a space? Then skip to the next glyph - if (glyphW === 0 || glyphH === 0 || charCode === 32) - { - continue; - } - - if (roundPixels) - { - x = Math.round(x); - y = Math.round(y); - } - - ctx.save(); - - ctx.translate(x, y); - - ctx.scale(scale, scale); - - ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); - - ctx.restore(); - } - - ctx.restore(); -}; - -module.exports = BitmapTextCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.BitmapText#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.BitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BitmapTextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src._text; + var textLength = text.length; + + var ctx = renderer.currentContext; + + if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + return; + } + + var textureFrame = src.frame; + + var chars = src.fontData.chars; + var lineHeight = src.fontData.lineHeight; + var letterSpacing = src._letterSpacing; + + var xAdvance = 0; + var yAdvance = 0; + + var charCode = 0; + + var glyph = null; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + + var x = 0; + var y = 0; + + var lastGlyph = null; + var lastCharCode = 0; + + var image = src.frame.source.image; + + var textureX = textureFrame.cutX; + var textureY = textureFrame.cutY; + + var scale = (src._fontSize / src.fontData.size); + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + var bounds = src.getTextBounds(false); + + // In case the method above changed it (word wrapping) + if (src.maxWidth > 0) + { + text = bounds.wrappedText; + textLength = text.length; + } + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + ctx.translate(-src.displayOriginX, -src.displayOriginY); + + var roundPixels = camera.roundPixels; + + for (var i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + x = glyph.xOffset + xAdvance; + y = glyph.yOffset + yAdvance; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + x *= scale; + y *= scale; + + x += lineOffsetX; + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + if (roundPixels) + { + x = Math.round(x); + y = Math.round(y); + } + + ctx.save(); + + ctx.translate(x, y); + + ctx.scale(scale, scale); + + ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); + + ctx.restore(); + } + + ctx.restore(); +}; + +module.exports = BitmapTextCanvasRenderer; diff --git a/src/gameobjects/bitmaptext/static/BitmapTextCreator.js b/src/gameobjects/bitmaptext/static/BitmapTextCreator.js index 79ce10c85..290a2b48b 100644 --- a/src/gameobjects/bitmaptext/static/BitmapTextCreator.js +++ b/src/gameobjects/bitmaptext/static/BitmapTextCreator.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BitmapText = require('./BitmapText'); -var BuildGameObject = require('../../BuildGameObject'); -var GameObjectCreator = require('../../GameObjectCreator'); -var GetAdvancedValue = require('../../../utils/object/GetAdvancedValue'); -var GetValue = require('../../../utils/object/GetValue'); - -/** - * Creates a new Bitmap Text Game Object and returns it. - * - * Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#bitmapText - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.BitmapText.BitmapTextConfig} 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.BitmapText} The Game Object that was created. - */ -GameObjectCreator.register('bitmapText', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var font = GetValue(config, 'font', ''); - var text = GetAdvancedValue(config, 'text', ''); - var size = GetAdvancedValue(config, 'size', false); - var align = GetValue(config, 'align', 0); - - var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size, align); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, bitmapText, config); - - return bitmapText; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = require('./BitmapText'); +var BuildGameObject = require('../../BuildGameObject'); +var GameObjectCreator = require('../../GameObjectCreator'); +var GetAdvancedValue = require('../../../utils/object/GetAdvancedValue'); +var GetValue = require('../../../utils/object/GetValue'); + +/** + * Creates a new Bitmap Text Game Object and returns it. + * + * Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#bitmapText + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.BitmapText.BitmapTextConfig} 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.BitmapText} The Game Object that was created. + */ +GameObjectCreator.register('bitmapText', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var font = GetValue(config, 'font', ''); + var text = GetAdvancedValue(config, 'text', ''); + var size = GetAdvancedValue(config, 'size', false); + var align = GetValue(config, 'align', 0); + + var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size, align); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, bitmapText, config); + + return bitmapText; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/bitmaptext/static/BitmapTextFactory.js b/src/gameobjects/bitmaptext/static/BitmapTextFactory.js index bcbf72455..4d8bf1a91 100644 --- a/src/gameobjects/bitmaptext/static/BitmapTextFactory.js +++ b/src/gameobjects/bitmaptext/static/BitmapTextFactory.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BitmapText = require('./BitmapText'); -var GameObjectFactory = require('../../GameObjectFactory'); - -/** - * 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 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): 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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. - * - * @return {Phaser.GameObjects.BitmapText} The Game Object that was created. - */ -GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align) -{ - return this.displayList.add(new BitmapText(this.scene, x, y, font, text, size, align)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapText = require('./BitmapText'); +var GameObjectFactory = require('../../GameObjectFactory'); + +/** + * 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 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): 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 {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. + * + * @return {Phaser.GameObjects.BitmapText} The Game Object that was created. + */ +GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align) +{ + return this.displayList.add(new BitmapText(this.scene, x, y, font, text, size, align)); +}); + +// 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 diff --git a/src/gameobjects/bitmaptext/static/BitmapTextRender.js b/src/gameobjects/bitmaptext/static/BitmapTextRender.js index 01daa7969..ccfc53f72 100644 --- a/src/gameobjects/bitmaptext/static/BitmapTextRender.js +++ b/src/gameobjects/bitmaptext/static/BitmapTextRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./BitmapTextWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./BitmapTextCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./BitmapTextWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./BitmapTextCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/bitmaptext/static/BitmapTextWebGLRenderer.js b/src/gameobjects/bitmaptext/static/BitmapTextWebGLRenderer.js index 8b38ab5df..0e0d81191 100644 --- a/src/gameobjects/bitmaptext/static/BitmapTextWebGLRenderer.js +++ b/src/gameobjects/bitmaptext/static/BitmapTextWebGLRenderer.js @@ -1,230 +1,230 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.BitmapText#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.BitmapText} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var BitmapTextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var text = src._text; - var textLength = text.length; - - if (textLength === 0) - { - return; - } - - var pipeline = this.pipeline; - - renderer.setPipeline(pipeline, src); - - var camMatrix = pipeline._tempMatrix1; - var spriteMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var frame = src.frame; - var texture = frame.glTexture; - var textureX = frame.cutX; - var textureY = frame.cutY; - var textureWidth = texture.width; - var textureHeight = texture.height; - - var tintEffect = (src._isTinted && src.tintFill); - var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); - var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); - var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); - var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); - - pipeline.setTexture2D(texture, 0); - - var xAdvance = 0; - var yAdvance = 0; - var charCode = 0; - var lastCharCode = 0; - var letterSpacing = src._letterSpacing; - var glyph; - var glyphX = 0; - var glyphY = 0; - var glyphW = 0; - var glyphH = 0; - var lastGlyph; - - var fontData = src.fontData; - var chars = fontData.chars; - var lineHeight = fontData.lineHeight; - var scale = (src._fontSize / fontData.size); - - var align = src._align; - var currentLine = 0; - var lineOffsetX = 0; - - // Update the bounds - skipped internally if not dirty - var bounds = src.getTextBounds(false); - - // In case the method above changed it (word wrapping) - if (src.maxWidth > 0) - { - text = bounds.wrappedText; - textLength = text.length; - } - - var lineData = src._bounds.lines; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[0]); - } - - var roundPixels = camera.roundPixels; - - for (var i = 0; i < textLength; i++) - { - charCode = text.charCodeAt(i); - - // Carriage-return - if (charCode === 10) - { - currentLine++; - - if (align === 1) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; - } - else if (align === 2) - { - lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); - } - - xAdvance = 0; - yAdvance += lineHeight; - lastGlyph = null; - - continue; - } - - glyph = chars[charCode]; - - if (!glyph) - { - continue; - } - - glyphX = textureX + glyph.x; - glyphY = textureY + glyph.y; - - glyphW = glyph.width; - glyphH = glyph.height; - - var x = glyph.xOffset + xAdvance; - var y = glyph.yOffset + yAdvance; - - if (lastGlyph !== null) - { - var kerningOffset = glyph.kerning[lastCharCode]; - x += (kerningOffset !== undefined) ? kerningOffset : 0; - } - - xAdvance += glyph.xAdvance + letterSpacing; - lastGlyph = glyph; - lastCharCode = charCode; - - // Nothing to render or a space? Then skip to the next glyph - if (glyphW === 0 || glyphH === 0 || charCode === 32) - { - continue; - } - - x *= scale; - y *= scale; - - x -= src.displayOriginX; - y -= src.displayOriginY; - - x += lineOffsetX; - - var u0 = glyphX / textureWidth; - var v0 = glyphY / textureHeight; - var u1 = (glyphX + glyphW) / textureWidth; - var v1 = (glyphY + glyphH) / textureHeight; - - var xw = x + (glyphW * scale); - var yh = y + (glyphH * scale); - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(x, yh); - var ty1 = calcMatrix.getY(x, yh); - - var tx2 = calcMatrix.getX(xw, yh); - var ty2 = calcMatrix.getY(xw, yh); - - var tx3 = calcMatrix.getX(xw, y); - var ty3 = calcMatrix.getY(xw, y); - - if (roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); - } -}; - -module.exports = BitmapTextWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.BitmapText#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.BitmapText} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BitmapTextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var text = src._text; + var textLength = text.length; + + if (textLength === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + var textureX = frame.cutX; + var textureY = frame.cutY; + var textureWidth = texture.width; + var textureHeight = texture.height; + + var tintEffect = (src._isTinted && src.tintFill); + var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); + var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); + var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); + var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); + + pipeline.setTexture2D(texture, 0); + + var xAdvance = 0; + var yAdvance = 0; + var charCode = 0; + var lastCharCode = 0; + var letterSpacing = src._letterSpacing; + var glyph; + var glyphX = 0; + var glyphY = 0; + var glyphW = 0; + var glyphH = 0; + var lastGlyph; + + var fontData = src.fontData; + var chars = fontData.chars; + var lineHeight = fontData.lineHeight; + var scale = (src._fontSize / fontData.size); + + var align = src._align; + var currentLine = 0; + var lineOffsetX = 0; + + // Update the bounds - skipped internally if not dirty + var bounds = src.getTextBounds(false); + + // In case the method above changed it (word wrapping) + if (src.maxWidth > 0) + { + text = bounds.wrappedText; + textLength = text.length; + } + + var lineData = src._bounds.lines; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[0]); + } + + var roundPixels = camera.roundPixels; + + for (var i = 0; i < textLength; i++) + { + charCode = text.charCodeAt(i); + + // Carriage-return + if (charCode === 10) + { + currentLine++; + + if (align === 1) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2; + } + else if (align === 2) + { + lineOffsetX = (lineData.longest - lineData.lengths[currentLine]); + } + + xAdvance = 0; + yAdvance += lineHeight; + lastGlyph = null; + + continue; + } + + glyph = chars[charCode]; + + if (!glyph) + { + continue; + } + + glyphX = textureX + glyph.x; + glyphY = textureY + glyph.y; + + glyphW = glyph.width; + glyphH = glyph.height; + + var x = glyph.xOffset + xAdvance; + var y = glyph.yOffset + yAdvance; + + if (lastGlyph !== null) + { + var kerningOffset = glyph.kerning[lastCharCode]; + x += (kerningOffset !== undefined) ? kerningOffset : 0; + } + + xAdvance += glyph.xAdvance + letterSpacing; + lastGlyph = glyph; + lastCharCode = charCode; + + // Nothing to render or a space? Then skip to the next glyph + if (glyphW === 0 || glyphH === 0 || charCode === 32) + { + continue; + } + + x *= scale; + y *= scale; + + x -= src.displayOriginX; + y -= src.displayOriginY; + + x += lineOffsetX; + + var u0 = glyphX / textureWidth; + var v0 = glyphY / textureHeight; + var u1 = (glyphX + glyphW) / textureWidth; + var v1 = (glyphY + glyphH) / textureHeight; + + var xw = x + (glyphW * scale); + var yh = y + (glyphH * scale); + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + } +}; + +module.exports = BitmapTextWebGLRenderer; diff --git a/src/gameobjects/bitmaptext/typedefs/index.js b/src/gameobjects/bitmaptext/typedefs/index.js index b45c35b32..116995f26 100644 --- a/src/gameobjects/bitmaptext/typedefs/index.js +++ b/src/gameobjects/bitmaptext/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.BitmapText - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.BitmapText + */ diff --git a/src/gameobjects/blitter/Blitter.js b/src/gameobjects/blitter/Blitter.js index 9ec7966a9..1765f1aa6 100644 --- a/src/gameobjects/blitter/Blitter.js +++ b/src/gameobjects/blitter/Blitter.js @@ -1,293 +1,293 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BlitterRender = require('./BlitterRender'); -var Bob = require('./Bob'); -var Class = require('../../utils/Class'); -var Components = require('../components'); -var Frame = require('../../textures/Frame'); -var GameObject = require('../GameObject'); -var List = require('../../structs/List'); - -/** - * @callback CreateCallback - * - * @param {Phaser.GameObjects.Bob} bob - The Bob that was created by the Blitter. - * @param {integer} index - The position of the Bob within the Blitter display list. - */ - -/** - * @classdesc - * A Blitter Game Object. - * - * The Blitter Game Object is a special kind of container that creates, updates and manages Bob objects. - * Bobs are designed for rendering speed rather than flexibility. They consist of a texture, or frame from a texture, - * a position and an alpha value. You cannot scale or rotate them. They use a batched drawing method for speed - * during rendering. - * - * A Blitter Game Object has one texture bound to it. Bobs created by the Blitter can use any Frame from this - * Texture to render with, but they cannot use any other Texture. It is this single texture-bind that allows - * them their speed. - * - * If you have a need to blast a large volume of frames around the screen then Blitter objects are well worth - * investigating. They are especially useful for using as a base for your own special effects systems. - * - * @class Blitter - * @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.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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. It can only belong to one Scene at any given time. - * @param {number} [x=0] - The x coordinate of this Game Object in world space. - * @param {number} [y=0] - The y coordinate of this Game Object in world space. - * @param {string} [texture='__DEFAULT'] - The key of the texture this Game Object will use for rendering. The Texture must already exist in the Texture Manager. - * @param {(string|integer)} [frame=0] - The Frame of the Texture that this Game Object will use. Only set if the Texture has multiple frames, such as a Texture Atlas or Sprite Sheet. - */ -var Blitter = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Mask, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.Texture, - Components.Transform, - Components.Visible, - BlitterRender - ], - - initialize: - - function Blitter (scene, x, y, texture, frame) - { - GameObject.call(this, scene, 'Blitter'); - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.initPipeline(); - - /** - * The children of this Blitter. - * This List contains all of the Bob objects created by the Blitter. - * - * @name Phaser.GameObjects.Blitter#children - * @type {Phaser.Structs.List.} - * @since 3.0.0 - */ - this.children = new List(); - - /** - * A transient array that holds all of the Bobs that will be rendered this frame. - * The array is re-populated whenever the dirty flag is set. - * - * @name Phaser.GameObjects.Blitter#renderList - * @type {Phaser.GameObjects.Bob[]} - * @default [] - * @private - * @since 3.0.0 - */ - this.renderList = []; - - /** - * Is the Blitter considered dirty? - * A 'dirty' Blitter has had its child count changed since the last frame. - * - * @name Phaser.GameObjects.Blitter#dirty - * @type {boolean} - * @since 3.0.0 - */ - this.dirty = false; - }, - - /** - * Creates a new Bob in this Blitter. - * - * The Bob is created at the given coordinates, relative to the Blitter and uses the given frame. - * A Bob can use any frame belonging to the texture bound to the Blitter. - * - * @method Phaser.GameObjects.Blitter#create - * @since 3.0.0 - * - * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. - * @param {boolean} [visible=true] - Should the created Bob render or not? - * @param {integer} [index] - The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list. - * - * @return {Phaser.GameObjects.Bob} The newly created Bob object. - */ - create: function (x, y, frame, visible, index) - { - if (visible === undefined) { visible = true; } - if (index === undefined) { index = this.children.length; } - - if (frame === undefined) - { - frame = this.frame; - } - else if (!(frame instanceof Frame)) - { - frame = this.texture.get(frame); - } - - var bob = new Bob(this, x, y, frame, visible); - - this.children.addAt(bob, index, false); - - this.dirty = true; - - return bob; - }, - - /** - * Creates multiple Bob objects within this Blitter and then passes each of them to the specified callback. - * - * @method Phaser.GameObjects.Blitter#createFromCallback - * @since 3.0.0 - * - * @param {CreateCallback} callback - The callback to invoke after creating a bob. It will be sent two arguments: The Bob and the index of the Bob. - * @param {integer} quantity - The quantity of Bob objects to create. - * @param {(string|integer|Phaser.Textures.Frame|string[]|integer[]|Phaser.Textures.Frame[])} [frame] - The Frame the Bobs will use. It must be part of the Blitter Texture. - * @param {boolean} [visible=true] - Should the created Bob render or not? - * - * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that were created. - */ - createFromCallback: function (callback, quantity, frame, visible) - { - var bobs = this.createMultiple(quantity, frame, visible); - - for (var i = 0; i < bobs.length; i++) - { - var bob = bobs[i]; - - callback.call(this, bob, i); - } - - return bobs; - }, - - /** - * Creates multiple Bobs in one call. - * - * The amount created is controlled by a combination of the `quantity` argument and the number of frames provided. - * - * If the quantity is set to 10 and you provide 2 frames, then 20 Bobs will be created. 10 with the first - * frame and 10 with the second. - * - * @method Phaser.GameObjects.Blitter#createMultiple - * @since 3.0.0 - * - * @param {integer} quantity - The quantity of Bob objects to create. - * @param {(string|integer|Phaser.Textures.Frame|string[]|integer[]|Phaser.Textures.Frame[])} [frame] - The Frame the Bobs will use. It must be part of the Blitter Texture. - * @param {boolean} [visible=true] - Should the created Bob render or not? - * - * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that were created. - */ - createMultiple: function (quantity, frame, visible) - { - if (frame === undefined) { frame = this.frame.name; } - if (visible === undefined) { visible = true; } - - if (!Array.isArray(frame)) - { - frame = [ frame ]; - } - - var bobs = []; - var _this = this; - - frame.forEach(function (singleFrame) - { - for (var i = 0; i < quantity; i++) - { - bobs.push(_this.create(0, 0, singleFrame, visible)); - } - }); - - return bobs; - }, - - /** - * Checks if the given child can render or not, by checking its `visible` and `alpha` values. - * - * @method Phaser.GameObjects.Blitter#childCanRender - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Bob} child - The Bob to check for rendering. - * - * @return {boolean} Returns `true` if the given child can render, otherwise `false`. - */ - childCanRender: function (child) - { - return (child.visible && child.alpha > 0); - }, - - /** - * Returns an array of Bobs to be rendered. - * If the Blitter is dirty then a new list is generated and stored in `renderList`. - * - * @method Phaser.GameObjects.Blitter#getRenderList - * @since 3.0.0 - * - * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that will be rendered this frame. - */ - getRenderList: function () - { - if (this.dirty) - { - this.renderList = this.children.list.filter(this.childCanRender, this); - this.dirty = false; - } - - return this.renderList; - }, - - /** - * Removes all Bobs from the children List and clears the dirty flag. - * - * @method Phaser.GameObjects.Blitter#clear - * @since 3.0.0 - */ - clear: function () - { - this.children.removeAll(); - this.dirty = true; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Blitter#preDestroy - * @protected - * @since 3.9.0 - */ - preDestroy: function () - { - this.children.destroy(); - - this.renderList = []; - } - -}); - -module.exports = Blitter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlitterRender = require('./BlitterRender'); +var Bob = require('./Bob'); +var Class = require('../../utils/Class'); +var Components = require('../components'); +var Frame = require('../../textures/Frame'); +var GameObject = require('../GameObject'); +var List = require('../../structs/List'); + +/** + * @callback CreateCallback + * + * @param {Phaser.GameObjects.Bob} bob - The Bob that was created by the Blitter. + * @param {integer} index - The position of the Bob within the Blitter display list. + */ + +/** + * @classdesc + * A Blitter Game Object. + * + * The Blitter Game Object is a special kind of container that creates, updates and manages Bob objects. + * Bobs are designed for rendering speed rather than flexibility. They consist of a texture, or frame from a texture, + * a position and an alpha value. You cannot scale or rotate them. They use a batched drawing method for speed + * during rendering. + * + * A Blitter Game Object has one texture bound to it. Bobs created by the Blitter can use any Frame from this + * Texture to render with, but they cannot use any other Texture. It is this single texture-bind that allows + * them their speed. + * + * If you have a need to blast a large volume of frames around the screen then Blitter objects are well worth + * investigating. They are especially useful for using as a base for your own special effects systems. + * + * @class Blitter + * @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.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. It can only belong to one Scene at any given time. + * @param {number} [x=0] - The x coordinate of this Game Object in world space. + * @param {number} [y=0] - The y coordinate of this Game Object in world space. + * @param {string} [texture='__DEFAULT'] - The key of the texture this Game Object will use for rendering. The Texture must already exist in the Texture Manager. + * @param {(string|integer)} [frame=0] - The Frame of the Texture that this Game Object will use. Only set if the Texture has multiple frames, such as a Texture Atlas or Sprite Sheet. + */ +var Blitter = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Mask, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.Texture, + Components.Transform, + Components.Visible, + BlitterRender + ], + + initialize: + + function Blitter (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Blitter'); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.initPipeline(); + + /** + * The children of this Blitter. + * This List contains all of the Bob objects created by the Blitter. + * + * @name Phaser.GameObjects.Blitter#children + * @type {Phaser.Structs.List.} + * @since 3.0.0 + */ + this.children = new List(); + + /** + * A transient array that holds all of the Bobs that will be rendered this frame. + * The array is re-populated whenever the dirty flag is set. + * + * @name Phaser.GameObjects.Blitter#renderList + * @type {Phaser.GameObjects.Bob[]} + * @default [] + * @private + * @since 3.0.0 + */ + this.renderList = []; + + /** + * Is the Blitter considered dirty? + * A 'dirty' Blitter has had its child count changed since the last frame. + * + * @name Phaser.GameObjects.Blitter#dirty + * @type {boolean} + * @since 3.0.0 + */ + this.dirty = false; + }, + + /** + * Creates a new Bob in this Blitter. + * + * The Bob is created at the given coordinates, relative to the Blitter and uses the given frame. + * A Bob can use any frame belonging to the texture bound to the Blitter. + * + * @method Phaser.GameObjects.Blitter#create + * @since 3.0.0 + * + * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. + * @param {boolean} [visible=true] - Should the created Bob render or not? + * @param {integer} [index] - The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list. + * + * @return {Phaser.GameObjects.Bob} The newly created Bob object. + */ + create: function (x, y, frame, visible, index) + { + if (visible === undefined) { visible = true; } + if (index === undefined) { index = this.children.length; } + + if (frame === undefined) + { + frame = this.frame; + } + else if (!(frame instanceof Frame)) + { + frame = this.texture.get(frame); + } + + var bob = new Bob(this, x, y, frame, visible); + + this.children.addAt(bob, index, false); + + this.dirty = true; + + return bob; + }, + + /** + * Creates multiple Bob objects within this Blitter and then passes each of them to the specified callback. + * + * @method Phaser.GameObjects.Blitter#createFromCallback + * @since 3.0.0 + * + * @param {CreateCallback} callback - The callback to invoke after creating a bob. It will be sent two arguments: The Bob and the index of the Bob. + * @param {integer} quantity - The quantity of Bob objects to create. + * @param {(string|integer|Phaser.Textures.Frame|string[]|integer[]|Phaser.Textures.Frame[])} [frame] - The Frame the Bobs will use. It must be part of the Blitter Texture. + * @param {boolean} [visible=true] - Should the created Bob render or not? + * + * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that were created. + */ + createFromCallback: function (callback, quantity, frame, visible) + { + var bobs = this.createMultiple(quantity, frame, visible); + + for (var i = 0; i < bobs.length; i++) + { + var bob = bobs[i]; + + callback.call(this, bob, i); + } + + return bobs; + }, + + /** + * Creates multiple Bobs in one call. + * + * The amount created is controlled by a combination of the `quantity` argument and the number of frames provided. + * + * If the quantity is set to 10 and you provide 2 frames, then 20 Bobs will be created. 10 with the first + * frame and 10 with the second. + * + * @method Phaser.GameObjects.Blitter#createMultiple + * @since 3.0.0 + * + * @param {integer} quantity - The quantity of Bob objects to create. + * @param {(string|integer|Phaser.Textures.Frame|string[]|integer[]|Phaser.Textures.Frame[])} [frame] - The Frame the Bobs will use. It must be part of the Blitter Texture. + * @param {boolean} [visible=true] - Should the created Bob render or not? + * + * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that were created. + */ + createMultiple: function (quantity, frame, visible) + { + if (frame === undefined) { frame = this.frame.name; } + if (visible === undefined) { visible = true; } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var bobs = []; + var _this = this; + + frame.forEach(function (singleFrame) + { + for (var i = 0; i < quantity; i++) + { + bobs.push(_this.create(0, 0, singleFrame, visible)); + } + }); + + return bobs; + }, + + /** + * Checks if the given child can render or not, by checking its `visible` and `alpha` values. + * + * @method Phaser.GameObjects.Blitter#childCanRender + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Bob} child - The Bob to check for rendering. + * + * @return {boolean} Returns `true` if the given child can render, otherwise `false`. + */ + childCanRender: function (child) + { + return (child.visible && child.alpha > 0); + }, + + /** + * Returns an array of Bobs to be rendered. + * If the Blitter is dirty then a new list is generated and stored in `renderList`. + * + * @method Phaser.GameObjects.Blitter#getRenderList + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Bob[]} An array of Bob objects that will be rendered this frame. + */ + getRenderList: function () + { + if (this.dirty) + { + this.renderList = this.children.list.filter(this.childCanRender, this); + this.dirty = false; + } + + return this.renderList; + }, + + /** + * Removes all Bobs from the children List and clears the dirty flag. + * + * @method Phaser.GameObjects.Blitter#clear + * @since 3.0.0 + */ + clear: function () + { + this.children.removeAll(); + this.dirty = true; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Blitter#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + this.children.destroy(); + + this.renderList = []; + } + +}); + +module.exports = Blitter; diff --git a/src/gameobjects/blitter/BlitterCanvasRenderer.js b/src/gameobjects/blitter/BlitterCanvasRenderer.js index 029f747fe..3408b48eb 100644 --- a/src/gameobjects/blitter/BlitterCanvasRenderer.js +++ b/src/gameobjects/blitter/BlitterCanvasRenderer.js @@ -1,124 +1,124 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Blitter#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Blitter} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var BlitterCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var list = src.getRenderList(); - - if (list.length === 0) - { - return; - } - - var ctx = renderer.currentContext; - - var alpha = camera.alpha * src.alpha; - - if (alpha === 0) - { - // Nothing to see, so abort early - return; - } - - // Blend Mode + Scale Mode - ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; - - ctx.imageSmoothingEnabled = !(!renderer.antialias || src.frame.source.scaleMode); - - var cameraScrollX = src.x - camera.scrollX * src.scrollFactorX; - var cameraScrollY = src.y - camera.scrollY * src.scrollFactorY; - - ctx.save(); - - if (parentMatrix) - { - parentMatrix.copyToContext(ctx); - } - - var roundPixels = camera.roundPixels; - - // Render bobs - for (var i = 0; i < list.length; i++) - { - var bob = list[i]; - var flip = (bob.flipX || bob.flipY); - var frame = bob.frame; - var cd = frame.canvasData; - var dx = frame.x; - var dy = frame.y; - var fx = 1; - var fy = 1; - - var bobAlpha = bob.alpha * alpha; - - if (bobAlpha === 0) - { - continue; - } - - ctx.globalAlpha = bobAlpha; - - if (!flip) - { - if (roundPixels) - { - dx = Math.round(dx); - dy = Math.round(dy); - } - - ctx.drawImage( - frame.source.image, - cd.x, - cd.y, - cd.width, - cd.height, - dx + bob.x + cameraScrollX, - dy + bob.y + cameraScrollY, - cd.width, - cd.height - ); - } - else - { - if (bob.flipX) - { - fx = -1; - dx -= cd.width; - } - - if (bob.flipY) - { - fy = -1; - dy -= cd.height; - } - - ctx.save(); - ctx.translate(bob.x + cameraScrollX, bob.y + cameraScrollY); - ctx.scale(fx, fy); - ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, dx, dy, cd.width, cd.height); - ctx.restore(); - } - } - - ctx.restore(); -}; - -module.exports = BlitterCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Blitter#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Blitter} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BlitterCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var list = src.getRenderList(); + + if (list.length === 0) + { + return; + } + + var ctx = renderer.currentContext; + + var alpha = camera.alpha * src.alpha; + + if (alpha === 0) + { + // Nothing to see, so abort early + return; + } + + // Blend Mode + Scale Mode + ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + + ctx.imageSmoothingEnabled = !(!renderer.antialias || src.frame.source.scaleMode); + + var cameraScrollX = src.x - camera.scrollX * src.scrollFactorX; + var cameraScrollY = src.y - camera.scrollY * src.scrollFactorY; + + ctx.save(); + + if (parentMatrix) + { + parentMatrix.copyToContext(ctx); + } + + var roundPixels = camera.roundPixels; + + // Render bobs + for (var i = 0; i < list.length; i++) + { + var bob = list[i]; + var flip = (bob.flipX || bob.flipY); + var frame = bob.frame; + var cd = frame.canvasData; + var dx = frame.x; + var dy = frame.y; + var fx = 1; + var fy = 1; + + var bobAlpha = bob.alpha * alpha; + + if (bobAlpha === 0) + { + continue; + } + + ctx.globalAlpha = bobAlpha; + + if (!flip) + { + if (roundPixels) + { + dx = Math.round(dx); + dy = Math.round(dy); + } + + ctx.drawImage( + frame.source.image, + cd.x, + cd.y, + cd.width, + cd.height, + dx + bob.x + cameraScrollX, + dy + bob.y + cameraScrollY, + cd.width, + cd.height + ); + } + else + { + if (bob.flipX) + { + fx = -1; + dx -= cd.width; + } + + if (bob.flipY) + { + fy = -1; + dy -= cd.height; + } + + ctx.save(); + ctx.translate(bob.x + cameraScrollX, bob.y + cameraScrollY); + ctx.scale(fx, fy); + ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, dx, dy, cd.width, cd.height); + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = BlitterCanvasRenderer; diff --git a/src/gameobjects/blitter/BlitterCreator.js b/src/gameobjects/blitter/BlitterCreator.js index f7ed4a09e..e25cef398 100644 --- a/src/gameobjects/blitter/BlitterCreator.js +++ b/src/gameobjects/blitter/BlitterCreator.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Blitter = require('./Blitter'); -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); - -/** - * Creates a new Blitter Game Object and returns it. - * - * Note: This method will only be available if the Blitter Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#blitter - * @since 3.0.0 - * - * @param {object} 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.Blitter} The Game Object that was created. - */ -GameObjectCreator.register('blitter', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - - var blitter = new Blitter(this.scene, 0, 0, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, blitter, config); - - return blitter; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Blitter = require('./Blitter'); +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); + +/** + * Creates a new Blitter Game Object and returns it. + * + * Note: This method will only be available if the Blitter Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#blitter + * @since 3.0.0 + * + * @param {object} 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.Blitter} The Game Object that was created. + */ +GameObjectCreator.register('blitter', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var blitter = new Blitter(this.scene, 0, 0, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, blitter, config); + + return blitter; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/blitter/BlitterFactory.js b/src/gameobjects/blitter/BlitterFactory.js index d7f70b114..dfa2fb79a 100644 --- a/src/gameobjects/blitter/BlitterFactory.js +++ b/src/gameobjects/blitter/BlitterFactory.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Blitter = require('./Blitter'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Blitter Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Blitter Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#blitter - * @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} key - The key of the Texture the Blitter object will use. - * @param {(string|integer)} [frame] - The default Frame children of the Blitter will use. - * - * @return {Phaser.GameObjects.Blitter} The Game Object that was created. - */ -GameObjectFactory.register('blitter', function (x, y, key, frame) -{ - return this.displayList.add(new Blitter(this.scene, x, y, key, frame)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Blitter = require('./Blitter'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Blitter Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Blitter Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#blitter + * @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} key - The key of the Texture the Blitter object will use. + * @param {(string|integer)} [frame] - The default Frame children of the Blitter will use. + * + * @return {Phaser.GameObjects.Blitter} The Game Object that was created. + */ +GameObjectFactory.register('blitter', function (x, y, key, frame) +{ + return this.displayList.add(new Blitter(this.scene, x, y, key, frame)); +}); + +// 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 diff --git a/src/gameobjects/blitter/BlitterRender.js b/src/gameobjects/blitter/BlitterRender.js index 7e8e0ace9..d47b580c2 100644 --- a/src/gameobjects/blitter/BlitterRender.js +++ b/src/gameobjects/blitter/BlitterRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./BlitterWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./BlitterCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./BlitterWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./BlitterCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/blitter/BlitterWebGLRenderer.js b/src/gameobjects/blitter/BlitterWebGLRenderer.js index a3538914b..7d5cb58fa 100644 --- a/src/gameobjects/blitter/BlitterWebGLRenderer.js +++ b/src/gameobjects/blitter/BlitterWebGLRenderer.js @@ -1,124 +1,124 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Blitter#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Blitter} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var BlitterWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var list = src.getRenderList(); - - if (list.length === 0) - { - return; - } - - var pipeline = this.pipeline; - - renderer.setPipeline(pipeline, src); - - var cameraScrollX = camera.scrollX * src.scrollFactorX; - var cameraScrollY = camera.scrollY * src.scrollFactorY; - - var calcMatrix = pipeline._tempMatrix1; - - calcMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - calcMatrix.multiplyWithOffset(parentMatrix, -cameraScrollX, -cameraScrollY); - - cameraScrollX = 0; - cameraScrollY = 0; - } - - var blitterX = src.x - cameraScrollX; - var blitterY = src.y - cameraScrollY; - var prevTextureSourceIndex = -1; - var tintEffect = false; - var alpha = camera.alpha * src.alpha; - var roundPixels = camera.roundPixels; - - for (var index = 0; index < list.length; index++) - { - var bob = list[index]; - var frame = bob.frame; - var bobAlpha = bob.alpha * alpha; - - if (bobAlpha === 0) - { - continue; - } - - var width = frame.width; - var height = frame.height; - - var x = blitterX + bob.x + frame.x; - var y = blitterY + bob.y + frame.y; - - if (bob.flipX) - { - width *= -1; - x += frame.width; - } - - if (bob.flipY) - { - height *= -1; - y += frame.height; - } - - var xw = x + width; - var yh = y + height; - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(xw, yh); - var ty1 = calcMatrix.getY(xw, yh); - - var tint = Utils.getTintAppendFloatAlpha(bob.tint, bobAlpha); - - // Bind texture only if the Texture Source is different from before - if (frame.sourceIndex !== prevTextureSourceIndex) - { - pipeline.setTexture2D(frame.glTexture, 0); - - prevTextureSourceIndex = frame.sourceIndex; - } - - if (roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - } - - // TL x/y, BL x/y, BR x/y, TR x/y - if (pipeline.batchQuad(tx0, ty0, tx0, ty1, tx1, ty1, tx1, ty0, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect, frame.glTexture, 0)) - { - prevTextureSourceIndex = -1; - } - } -}; - -module.exports = BlitterWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Blitter#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Blitter} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var BlitterWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var list = src.getRenderList(); + + if (list.length === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var cameraScrollX = camera.scrollX * src.scrollFactorX; + var cameraScrollY = camera.scrollY * src.scrollFactorY; + + var calcMatrix = pipeline._tempMatrix1; + + calcMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + calcMatrix.multiplyWithOffset(parentMatrix, -cameraScrollX, -cameraScrollY); + + cameraScrollX = 0; + cameraScrollY = 0; + } + + var blitterX = src.x - cameraScrollX; + var blitterY = src.y - cameraScrollY; + var prevTextureSourceIndex = -1; + var tintEffect = false; + var alpha = camera.alpha * src.alpha; + var roundPixels = camera.roundPixels; + + for (var index = 0; index < list.length; index++) + { + var bob = list[index]; + var frame = bob.frame; + var bobAlpha = bob.alpha * alpha; + + if (bobAlpha === 0) + { + continue; + } + + var width = frame.width; + var height = frame.height; + + var x = blitterX + bob.x + frame.x; + var y = blitterY + bob.y + frame.y; + + if (bob.flipX) + { + width *= -1; + x += frame.width; + } + + if (bob.flipY) + { + height *= -1; + y += frame.height; + } + + var xw = x + width; + var yh = y + height; + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(xw, yh); + var ty1 = calcMatrix.getY(xw, yh); + + var tint = Utils.getTintAppendFloatAlpha(bob.tint, bobAlpha); + + // Bind texture only if the Texture Source is different from before + if (frame.sourceIndex !== prevTextureSourceIndex) + { + pipeline.setTexture2D(frame.glTexture, 0); + + prevTextureSourceIndex = frame.sourceIndex; + } + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + } + + // TL x/y, BL x/y, BR x/y, TR x/y + if (pipeline.batchQuad(tx0, ty0, tx0, ty1, tx1, ty1, tx1, ty0, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect, frame.glTexture, 0)) + { + prevTextureSourceIndex = -1; + } + } +}; + +module.exports = BlitterWebGLRenderer; diff --git a/src/gameobjects/blitter/Bob.js b/src/gameobjects/blitter/Bob.js index 5c8941a05..d5a53c7b7 100644 --- a/src/gameobjects/blitter/Bob.js +++ b/src/gameobjects/blitter/Bob.js @@ -1,424 +1,424 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Frame = require('../../textures/Frame'); - -/** - * @classdesc - * A Bob Game Object. - * - * A Bob belongs to a Blitter Game Object. The Blitter is responsible for managing and rendering this object. - * - * A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle - * the flipped and visible state of the Bob. The Frame the Bob uses to render can be changed dynamically, but it - * must be a Frame within the Texture used by the parent Blitter. - * - * Bob positions are relative to the Blitter parent. So if you move the Blitter parent, all Bob children will - * have their positions impacted by this change as well. - * - * You can manipulate Bob objects directly from your game code, but the creation and destruction of them should be - * handled via the Blitter parent. - * - * @class Bob - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Blitter} blitter - The parent Blitter object is responsible for updating this Bob. - * @param {number} x - The horizontal position of this Game Object in the world, relative to the parent Blitter position. - * @param {number} y - The vertical position of this Game Object in the world, relative to the parent Blitter position. - * @param {(string|integer)} frame - The Frame this Bob will render with, as defined in the Texture the parent Blitter is using. - * @param {boolean} visible - Should the Bob render visible or not to start with? - */ -var Bob = new Class({ - - initialize: - - function Bob (blitter, x, y, frame, visible) - { - /** - * The Blitter object that this Bob belongs to. - * - * @name Phaser.GameObjects.Bob#parent - * @type {Phaser.GameObjects.Blitter} - * @since 3.0.0 - */ - this.parent = blitter; - - /** - * The x position of this Bob, relative to the x position of the Blitter. - * - * @name Phaser.GameObjects.Bob#x - * @type {number} - * @since 3.0.0 - */ - this.x = x; - - /** - * The y position of this Bob, relative to the y position of the Blitter. - * - * @name Phaser.GameObjects.Bob#y - * @type {number} - * @since 3.0.0 - */ - this.y = y; - - /** - * The frame that the Bob uses to render with. - * To change the frame use the `Bob.setFrame` method. - * - * @name Phaser.GameObjects.Bob#frame - * @type {Phaser.Textures.Frame} - * @protected - * @since 3.0.0 - */ - this.frame = frame; - - /** - * A blank object which can be used to store data related to this Bob in. - * - * @name Phaser.GameObjects.Bob#data - * @type {object} - * @default {} - * @since 3.0.0 - */ - this.data = {}; - - /** - * The tint value of this Bob. - * - * @name Phaser.GameObjects.Bob#tint - * @type {number} - * @default 0xffffff - * @since 3.20.0 - */ - this.tint = 0xffffff; - - /** - * The visible state of this Bob. - * - * @name Phaser.GameObjects.Bob#_visible - * @type {boolean} - * @private - * @since 3.0.0 - */ - this._visible = visible; - - /** - * The alpha value of this Bob. - * - * @name Phaser.GameObjects.Bob#_alpha - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - this._alpha = 1; - - /** - * The horizontally flipped state of the Bob. - * A Bob that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture. - * - * @name Phaser.GameObjects.Bob#flipX - * @type {boolean} - * @since 3.0.0 - */ - this.flipX = false; - - /** - * The vertically flipped state of the Bob. - * A Bob that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture. - * - * @name Phaser.GameObjects.Bob#flipY - * @type {boolean} - * @since 3.0.0 - */ - this.flipY = false; - }, - - /** - * Changes the Texture Frame being used by this Bob. - * The frame must be part of the Texture the parent Blitter is using. - * If no value is given it will use the default frame of the Blitter parent. - * - * @method Phaser.GameObjects.Bob#setFrame - * @since 3.0.0 - * - * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The frame to be used during rendering. - * - * @return {this} This Bob Game Object. - */ - setFrame: function (frame) - { - if (frame === undefined) - { - this.frame = this.parent.frame; - } - else if (frame instanceof Frame && frame.texture === this.parent.texture) - { - this.frame = frame; - } - else - { - this.frame = this.parent.texture.get(frame); - } - - return this; - }, - - /** - * Resets the horizontal and vertical flipped state of this Bob back to their default un-flipped state. - * - * @method Phaser.GameObjects.Bob#resetFlip - * @since 3.0.0 - * - * @return {this} This Bob Game Object. - */ - resetFlip: function () - { - this.flipX = false; - this.flipY = false; - - return this; - }, - - /** - * Resets this Bob. - * - * Changes the position to the values given, and optionally changes the frame. - * - * Also resets the flipX and flipY values, sets alpha back to 1 and visible to true. - * - * @method Phaser.GameObjects.Bob#reset - * @since 3.0.0 - * - * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. - * - * @return {this} This Bob Game Object. - */ - reset: function (x, y, frame) - { - this.x = x; - this.y = y; - - this.flipX = false; - this.flipY = false; - - this._alpha = 1; - this._visible = true; - - this.parent.dirty = true; - - if (frame) - { - this.setFrame(frame); - } - - return this; - }, - - /** - * Changes the position of this Bob to the values given. - * - * @method Phaser.GameObjects.Bob#setPosition - * @since 3.20.0 - * - * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * - * @return {this} This Bob Game Object. - */ - setPosition: function (x, y) - { - this.x = x; - this.y = y; - - return this; - }, - - /** - * Sets the horizontal flipped state of this Bob. - * - * @method Phaser.GameObjects.Bob#setFlipX - * @since 3.0.0 - * - * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. - * - * @return {this} This Bob Game Object. - */ - setFlipX: function (value) - { - this.flipX = value; - - return this; - }, - - /** - * Sets the vertical flipped state of this Bob. - * - * @method Phaser.GameObjects.Bob#setFlipY - * @since 3.0.0 - * - * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. - * - * @return {this} This Bob Game Object. - */ - setFlipY: function (value) - { - this.flipY = value; - - return this; - }, - - /** - * Sets the horizontal and vertical flipped state of this Bob. - * - * @method Phaser.GameObjects.Bob#setFlip - * @since 3.0.0 - * - * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * - * @return {this} This Bob Game Object. - */ - setFlip: function (x, y) - { - this.flipX = x; - this.flipY = y; - - return this; - }, - - /** - * Sets the visibility of this Bob. - * - * An invisible Bob will skip rendering. - * - * @method Phaser.GameObjects.Bob#setVisible - * @since 3.0.0 - * - * @param {boolean} value - The visible state of the Game Object. - * - * @return {this} This Bob Game Object. - */ - setVisible: function (value) - { - this.visible = value; - - return this; - }, - - /** - * Set the Alpha level of this Bob. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * A Bob with alpha 0 will skip rendering. - * - * @method Phaser.GameObjects.Bob#setAlpha - * @since 3.0.0 - * - * @param {number} value - The alpha value used for this Bob. Between 0 and 1. - * - * @return {this} This Bob Game Object. - */ - setAlpha: function (value) - { - this.alpha = value; - - return this; - }, - - /** - * Sets the tint of this Bob. - * - * @method Phaser.GameObjects.Bob#setTint - * @since 3.20.0 - * - * @param {number} value - The tint value used for this Bob. Between 0 and 0xffffff. - * - * @return {this} This Bob Game Object. - */ - setTint: function (value) - { - this.tint = value; - - return this; - }, - - /** - * Destroys this Bob instance. - * Removes itself from the Blitter and clears the parent, frame and data properties. - * - * @method Phaser.GameObjects.Bob#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.parent.dirty = true; - - this.parent.children.remove(this); - - this.parent = undefined; - this.frame = undefined; - this.data = undefined; - }, - - /** - * The visible state of the Bob. - * - * An invisible Bob will skip rendering. - * - * @name Phaser.GameObjects.Bob#visible - * @type {boolean} - * @since 3.0.0 - */ - visible: { - - get: function () - { - return this._visible; - }, - - set: function (value) - { - this.parent.dirty |= (this._visible !== value); - this._visible = value; - } - - }, - - /** - * The alpha value of the Bob, between 0 and 1. - * - * A Bob with alpha 0 will skip rendering. - * - * @name Phaser.GameObjects.Bob#alpha - * @type {number} - * @since 3.0.0 - */ - alpha: { - - get: function () - { - return this._alpha; - }, - - set: function (value) - { - this.parent.dirty |= ((this._alpha > 0) !== (value > 0)); - this._alpha = value; - } - - } - -}); - -module.exports = Bob; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Frame = require('../../textures/Frame'); + +/** + * @classdesc + * A Bob Game Object. + * + * A Bob belongs to a Blitter Game Object. The Blitter is responsible for managing and rendering this object. + * + * A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle + * the flipped and visible state of the Bob. The Frame the Bob uses to render can be changed dynamically, but it + * must be a Frame within the Texture used by the parent Blitter. + * + * Bob positions are relative to the Blitter parent. So if you move the Blitter parent, all Bob children will + * have their positions impacted by this change as well. + * + * You can manipulate Bob objects directly from your game code, but the creation and destruction of them should be + * handled via the Blitter parent. + * + * @class Bob + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Blitter} blitter - The parent Blitter object is responsible for updating this Bob. + * @param {number} x - The horizontal position of this Game Object in the world, relative to the parent Blitter position. + * @param {number} y - The vertical position of this Game Object in the world, relative to the parent Blitter position. + * @param {(string|integer)} frame - The Frame this Bob will render with, as defined in the Texture the parent Blitter is using. + * @param {boolean} visible - Should the Bob render visible or not to start with? + */ +var Bob = new Class({ + + initialize: + + function Bob (blitter, x, y, frame, visible) + { + /** + * The Blitter object that this Bob belongs to. + * + * @name Phaser.GameObjects.Bob#parent + * @type {Phaser.GameObjects.Blitter} + * @since 3.0.0 + */ + this.parent = blitter; + + /** + * The x position of this Bob, relative to the x position of the Blitter. + * + * @name Phaser.GameObjects.Bob#x + * @type {number} + * @since 3.0.0 + */ + this.x = x; + + /** + * The y position of this Bob, relative to the y position of the Blitter. + * + * @name Phaser.GameObjects.Bob#y + * @type {number} + * @since 3.0.0 + */ + this.y = y; + + /** + * The frame that the Bob uses to render with. + * To change the frame use the `Bob.setFrame` method. + * + * @name Phaser.GameObjects.Bob#frame + * @type {Phaser.Textures.Frame} + * @protected + * @since 3.0.0 + */ + this.frame = frame; + + /** + * A blank object which can be used to store data related to this Bob in. + * + * @name Phaser.GameObjects.Bob#data + * @type {object} + * @default {} + * @since 3.0.0 + */ + this.data = {}; + + /** + * The tint value of this Bob. + * + * @name Phaser.GameObjects.Bob#tint + * @type {number} + * @default 0xffffff + * @since 3.20.0 + */ + this.tint = 0xffffff; + + /** + * The visible state of this Bob. + * + * @name Phaser.GameObjects.Bob#_visible + * @type {boolean} + * @private + * @since 3.0.0 + */ + this._visible = visible; + + /** + * The alpha value of this Bob. + * + * @name Phaser.GameObjects.Bob#_alpha + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + this._alpha = 1; + + /** + * The horizontally flipped state of the Bob. + * A Bob that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture. + * + * @name Phaser.GameObjects.Bob#flipX + * @type {boolean} + * @since 3.0.0 + */ + this.flipX = false; + + /** + * The vertically flipped state of the Bob. + * A Bob that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture. + * + * @name Phaser.GameObjects.Bob#flipY + * @type {boolean} + * @since 3.0.0 + */ + this.flipY = false; + }, + + /** + * Changes the Texture Frame being used by this Bob. + * The frame must be part of the Texture the parent Blitter is using. + * If no value is given it will use the default frame of the Blitter parent. + * + * @method Phaser.GameObjects.Bob#setFrame + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The frame to be used during rendering. + * + * @return {this} This Bob Game Object. + */ + setFrame: function (frame) + { + if (frame === undefined) + { + this.frame = this.parent.frame; + } + else if (frame instanceof Frame && frame.texture === this.parent.texture) + { + this.frame = frame; + } + else + { + this.frame = this.parent.texture.get(frame); + } + + return this; + }, + + /** + * Resets the horizontal and vertical flipped state of this Bob back to their default un-flipped state. + * + * @method Phaser.GameObjects.Bob#resetFlip + * @since 3.0.0 + * + * @return {this} This Bob Game Object. + */ + resetFlip: function () + { + this.flipX = false; + this.flipY = false; + + return this; + }, + + /** + * Resets this Bob. + * + * Changes the position to the values given, and optionally changes the frame. + * + * Also resets the flipX and flipY values, sets alpha back to 1 and visible to true. + * + * @method Phaser.GameObjects.Bob#reset + * @since 3.0.0 + * + * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {(string|integer|Phaser.Textures.Frame)} [frame] - The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. + * + * @return {this} This Bob Game Object. + */ + reset: function (x, y, frame) + { + this.x = x; + this.y = y; + + this.flipX = false; + this.flipY = false; + + this._alpha = 1; + this._visible = true; + + this.parent.dirty = true; + + if (frame) + { + this.setFrame(frame); + } + + return this; + }, + + /** + * Changes the position of this Bob to the values given. + * + * @method Phaser.GameObjects.Bob#setPosition + * @since 3.20.0 + * + * @param {number} x - The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param {number} y - The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * + * @return {this} This Bob Game Object. + */ + setPosition: function (x, y) + { + this.x = x; + this.y = y; + + return this; + }, + + /** + * Sets the horizontal flipped state of this Bob. + * + * @method Phaser.GameObjects.Bob#setFlipX + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Bob Game Object. + */ + setFlipX: function (value) + { + this.flipX = value; + + return this; + }, + + /** + * Sets the vertical flipped state of this Bob. + * + * @method Phaser.GameObjects.Bob#setFlipY + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Bob Game Object. + */ + setFlipY: function (value) + { + this.flipY = value; + + return this; + }, + + /** + * Sets the horizontal and vertical flipped state of this Bob. + * + * @method Phaser.GameObjects.Bob#setFlip + * @since 3.0.0 + * + * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Bob Game Object. + */ + setFlip: function (x, y) + { + this.flipX = x; + this.flipY = y; + + return this; + }, + + /** + * Sets the visibility of this Bob. + * + * An invisible Bob will skip rendering. + * + * @method Phaser.GameObjects.Bob#setVisible + * @since 3.0.0 + * + * @param {boolean} value - The visible state of the Game Object. + * + * @return {this} This Bob Game Object. + */ + setVisible: function (value) + { + this.visible = value; + + return this; + }, + + /** + * Set the Alpha level of this Bob. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * A Bob with alpha 0 will skip rendering. + * + * @method Phaser.GameObjects.Bob#setAlpha + * @since 3.0.0 + * + * @param {number} value - The alpha value used for this Bob. Between 0 and 1. + * + * @return {this} This Bob Game Object. + */ + setAlpha: function (value) + { + this.alpha = value; + + return this; + }, + + /** + * Sets the tint of this Bob. + * + * @method Phaser.GameObjects.Bob#setTint + * @since 3.20.0 + * + * @param {number} value - The tint value used for this Bob. Between 0 and 0xffffff. + * + * @return {this} This Bob Game Object. + */ + setTint: function (value) + { + this.tint = value; + + return this; + }, + + /** + * Destroys this Bob instance. + * Removes itself from the Blitter and clears the parent, frame and data properties. + * + * @method Phaser.GameObjects.Bob#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.parent.dirty = true; + + this.parent.children.remove(this); + + this.parent = undefined; + this.frame = undefined; + this.data = undefined; + }, + + /** + * The visible state of the Bob. + * + * An invisible Bob will skip rendering. + * + * @name Phaser.GameObjects.Bob#visible + * @type {boolean} + * @since 3.0.0 + */ + visible: { + + get: function () + { + return this._visible; + }, + + set: function (value) + { + this.parent.dirty |= (this._visible !== value); + this._visible = value; + } + + }, + + /** + * The alpha value of the Bob, between 0 and 1. + * + * A Bob with alpha 0 will skip rendering. + * + * @name Phaser.GameObjects.Bob#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this._alpha; + }, + + set: function (value) + { + this.parent.dirty |= ((this._alpha > 0) !== (value > 0)); + this._alpha = value; + } + + } + +}); + +module.exports = Bob; diff --git a/src/gameobjects/components/Alpha.js b/src/gameobjects/components/Alpha.js index 6c48edcdb..6fb5d78a2 100644 --- a/src/gameobjects/components/Alpha.js +++ b/src/gameobjects/components/Alpha.js @@ -1,289 +1,289 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../math/Clamp'); - -// bitmask flag for GameObject.renderMask -var _FLAG = 2; // 0010 - -/** - * Provides methods used for setting the alpha properties of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.Alpha - * @since 3.0.0 - */ - -var Alpha = { - - /** - * Private internal value. Holds the global alpha value. - * - * @name Phaser.GameObjects.Components.Alpha#_alpha - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _alpha: 1, - - /** - * Private internal value. Holds the top-left alpha value. - * - * @name Phaser.GameObjects.Components.Alpha#_alphaTL - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _alphaTL: 1, - - /** - * Private internal value. Holds the top-right alpha value. - * - * @name Phaser.GameObjects.Components.Alpha#_alphaTR - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _alphaTR: 1, - - /** - * Private internal value. Holds the bottom-left alpha value. - * - * @name Phaser.GameObjects.Components.Alpha#_alphaBL - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _alphaBL: 1, - - /** - * Private internal value. Holds the bottom-right alpha value. - * - * @name Phaser.GameObjects.Components.Alpha#_alphaBR - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _alphaBR: 1, - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - * - * @method Phaser.GameObjects.Components.Alpha#clearAlpha - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - clearAlpha: function () - { - return this.setAlpha(1); - }, - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * - * @method Phaser.GameObjects.Components.Alpha#setAlpha - * @since 3.0.0 - * - * @param {number} [topLeft=1] - The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. - * @param {number} [topRight] - The alpha value used for the top-right of the Game Object. WebGL only. - * @param {number} [bottomLeft] - The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param {number} [bottomRight] - The alpha value used for the bottom-right of the Game Object. WebGL only. - * - * @return {this} This Game Object instance. - */ - setAlpha: function (topLeft, topRight, bottomLeft, bottomRight) - { - if (topLeft === undefined) { topLeft = 1; } - - // Treat as if there is only one alpha value for the whole Game Object - if (topRight === undefined) - { - this.alpha = topLeft; - } - else - { - this._alphaTL = Clamp(topLeft, 0, 1); - this._alphaTR = Clamp(topRight, 0, 1); - this._alphaBL = Clamp(bottomLeft, 0, 1); - this._alphaBR = Clamp(bottomRight, 0, 1); - } - - return this; - }, - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - * - * @name Phaser.GameObjects.Components.Alpha#alpha - * @type {number} - * @since 3.0.0 - */ - alpha: { - - get: function () - { - return this._alpha; - }, - - set: function (value) - { - var v = Clamp(value, 0, 1); - - this._alpha = v; - this._alphaTL = v; - this._alphaTR = v; - this._alphaBL = v; - this._alphaBR = v; - - if (v === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Alpha#alphaTopLeft - * @type {number} - * @webglOnly - * @since 3.0.0 - */ - alphaTopLeft: { - - get: function () - { - return this._alphaTL; - }, - - set: function (value) - { - var v = Clamp(value, 0, 1); - - this._alphaTL = v; - - if (v !== 0) - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Alpha#alphaTopRight - * @type {number} - * @webglOnly - * @since 3.0.0 - */ - alphaTopRight: { - - get: function () - { - return this._alphaTR; - }, - - set: function (value) - { - var v = Clamp(value, 0, 1); - - this._alphaTR = v; - - if (v !== 0) - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Alpha#alphaBottomLeft - * @type {number} - * @webglOnly - * @since 3.0.0 - */ - alphaBottomLeft: { - - get: function () - { - return this._alphaBL; - }, - - set: function (value) - { - var v = Clamp(value, 0, 1); - - this._alphaBL = v; - - if (v !== 0) - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Alpha#alphaBottomRight - * @type {number} - * @webglOnly - * @since 3.0.0 - */ - alphaBottomRight: { - - get: function () - { - return this._alphaBR; - }, - - set: function (value) - { - var v = Clamp(value, 0, 1); - - this._alphaBR = v; - - if (v !== 0) - { - this.renderFlags |= _FLAG; - } - } - - } - -}; - -module.exports = Alpha; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../math/Clamp'); + +// bitmask flag for GameObject.renderMask +var _FLAG = 2; // 0010 + +/** + * Provides methods used for setting the alpha properties of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Alpha + * @since 3.0.0 + */ + +var Alpha = { + + /** + * Private internal value. Holds the global alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alpha + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alpha: 1, + + /** + * Private internal value. Holds the top-left alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaTL + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaTL: 1, + + /** + * Private internal value. Holds the top-right alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaTR + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaTR: 1, + + /** + * Private internal value. Holds the bottom-left alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaBL + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaBL: 1, + + /** + * Private internal value. Holds the bottom-right alpha value. + * + * @name Phaser.GameObjects.Components.Alpha#_alphaBR + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alphaBR: 1, + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + * + * @method Phaser.GameObjects.Components.Alpha#clearAlpha + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + clearAlpha: function () + { + return this.setAlpha(1); + }, + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * + * @method Phaser.GameObjects.Components.Alpha#setAlpha + * @since 3.0.0 + * + * @param {number} [topLeft=1] - The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. + * @param {number} [topRight] - The alpha value used for the top-right of the Game Object. WebGL only. + * @param {number} [bottomLeft] - The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param {number} [bottomRight] - The alpha value used for the bottom-right of the Game Object. WebGL only. + * + * @return {this} This Game Object instance. + */ + setAlpha: function (topLeft, topRight, bottomLeft, bottomRight) + { + if (topLeft === undefined) { topLeft = 1; } + + // Treat as if there is only one alpha value for the whole Game Object + if (topRight === undefined) + { + this.alpha = topLeft; + } + else + { + this._alphaTL = Clamp(topLeft, 0, 1); + this._alphaTR = Clamp(topRight, 0, 1); + this._alphaBL = Clamp(bottomLeft, 0, 1); + this._alphaBR = Clamp(bottomRight, 0, 1); + } + + return this; + }, + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + * + * @name Phaser.GameObjects.Components.Alpha#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this._alpha; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alpha = v; + this._alphaTL = v; + this._alphaTR = v; + this._alphaBL = v; + this._alphaBR = v; + + if (v === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaTopLeft + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaTopLeft: { + + get: function () + { + return this._alphaTL; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaTL = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaTopRight + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaTopRight: { + + get: function () + { + return this._alphaTR; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaTR = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaBottomLeft + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaBottomLeft: { + + get: function () + { + return this._alphaBL; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaBL = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Alpha#alphaBottomRight + * @type {number} + * @webglOnly + * @since 3.0.0 + */ + alphaBottomRight: { + + get: function () + { + return this._alphaBR; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alphaBR = v; + + if (v !== 0) + { + this.renderFlags |= _FLAG; + } + } + + } + +}; + +module.exports = Alpha; diff --git a/src/gameobjects/components/AlphaSingle.js b/src/gameobjects/components/AlphaSingle.js index 8aaac608b..50dce2950 100644 --- a/src/gameobjects/components/AlphaSingle.js +++ b/src/gameobjects/components/AlphaSingle.js @@ -1,104 +1,104 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../../math/Clamp'); - -// bitmask flag for GameObject.renderMask -var _FLAG = 2; // 0010 - -/** - * Provides methods used for setting the alpha property of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.AlphaSingle - * @since 3.22.0 - */ - -var AlphaSingle = { - - /** - * Private internal value. Holds the global alpha value. - * - * @name Phaser.GameObjects.Components.AlphaSingle#_alpha - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _alpha: 1, - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - * - * @method Phaser.GameObjects.Components.AlphaSingle#clearAlpha - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - clearAlpha: function () - { - return this.setAlpha(1); - }, - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * @method Phaser.GameObjects.Components.AlphaSingle#setAlpha - * @since 3.0.0 - * - * @param {number} [value=1] - The alpha value applied across the whole Game Object. - * - * @return {this} This Game Object instance. - */ - setAlpha: function (value) - { - if (value === undefined) { value = 1; } - - this.alpha = value; - - return this; - }, - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - * - * @name Phaser.GameObjects.Components.AlphaSingle#alpha - * @type {number} - * @since 3.0.0 - */ - alpha: { - - get: function () - { - return this._alpha; - }, - - set: function (value) - { - var v = Clamp(value, 0, 1); - - this._alpha = v; - - if (v === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - } - - } - -}; - -module.exports = AlphaSingle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../../math/Clamp'); + +// bitmask flag for GameObject.renderMask +var _FLAG = 2; // 0010 + +/** + * Provides methods used for setting the alpha property of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.AlphaSingle + * @since 3.22.0 + */ + +var AlphaSingle = { + + /** + * Private internal value. Holds the global alpha value. + * + * @name Phaser.GameObjects.Components.AlphaSingle#_alpha + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _alpha: 1, + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + * + * @method Phaser.GameObjects.Components.AlphaSingle#clearAlpha + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + clearAlpha: function () + { + return this.setAlpha(1); + }, + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * @method Phaser.GameObjects.Components.AlphaSingle#setAlpha + * @since 3.0.0 + * + * @param {number} [value=1] - The alpha value applied across the whole Game Object. + * + * @return {this} This Game Object instance. + */ + setAlpha: function (value) + { + if (value === undefined) { value = 1; } + + this.alpha = value; + + return this; + }, + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + * + * @name Phaser.GameObjects.Components.AlphaSingle#alpha + * @type {number} + * @since 3.0.0 + */ + alpha: { + + get: function () + { + return this._alpha; + }, + + set: function (value) + { + var v = Clamp(value, 0, 1); + + this._alpha = v; + + if (v === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + } + +}; + +module.exports = AlphaSingle; diff --git a/src/gameobjects/components/Animation.js b/src/gameobjects/components/Animation.js index a21a1b752..bb5ae4718 100644 --- a/src/gameobjects/components/Animation.js +++ b/src/gameobjects/components/Animation.js @@ -1,1172 +1,1172 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseAnimation = require('../../animations/Animation'); -var Class = require('../../utils/Class'); -var Events = require('../../animations/events'); - -/** - * @classdesc - * A Game Object Animation Controller. - * - * This controller lives as an instance within a Game Object, accessible as `sprite.anims`. - * - * @class Animation - * @memberof Phaser.GameObjects.Components - * @constructor - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} parent - The Game Object to which this animation controller belongs. - */ -var Animation = new Class({ - - initialize: - - function Animation (parent) - { - /** - * The Game Object to which this animation controller belongs. - * - * @name Phaser.GameObjects.Components.Animation#parent - * @type {Phaser.GameObjects.GameObject} - * @since 3.0.0 - */ - this.parent = parent; - - /** - * A reference to the global Animation Manager. - * - * @name Phaser.GameObjects.Components.Animation#animationManager - * @type {Phaser.Animations.AnimationManager} - * @since 3.0.0 - */ - this.animationManager = parent.scene.sys.anims; - - this.animationManager.once(Events.REMOVE_ANIMATION, this.remove, this); - - /** - * Is an animation currently playing or not? - * - * @name Phaser.GameObjects.Components.Animation#isPlaying - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isPlaying = false; - - /** - * The current Animation loaded into this Animation Controller. - * - * @name Phaser.GameObjects.Components.Animation#currentAnim - * @type {?Phaser.Animations.Animation} - * @default null - * @since 3.0.0 - */ - this.currentAnim = null; - - /** - * The current AnimationFrame being displayed by this Animation Controller. - * - * @name Phaser.GameObjects.Components.Animation#currentFrame - * @type {?Phaser.Animations.AnimationFrame} - * @default null - * @since 3.0.0 - */ - this.currentFrame = null; - - /** - * The key of the next Animation to be loaded into this Animation Controller when the current animation completes. - * - * @name Phaser.GameObjects.Components.Animation#nextAnim - * @type {?string} - * @default null - * @since 3.16.0 - */ - this.nextAnim = null; - - /** - * Time scale factor. - * - * @name Phaser.GameObjects.Components.Animation#_timeScale - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - this._timeScale = 1; - - /** - * The frame rate of playback in frames per second. - * The default is 24 if the `duration` property is `null`. - * - * @name Phaser.GameObjects.Components.Animation#frameRate - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.frameRate = 0; - - /** - * How long the animation should play for, in milliseconds. - * If the `frameRate` property has been set then it overrides this value, - * otherwise the `frameRate` is derived from `duration`. - * - * @name Phaser.GameObjects.Components.Animation#duration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.duration = 0; - - /** - * ms per frame, not including frame specific modifiers that may be present in the Animation data. - * - * @name Phaser.GameObjects.Components.Animation#msPerFrame - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.msPerFrame = 0; - - /** - * Skip frames if the time lags, or always advanced anyway? - * - * @name Phaser.GameObjects.Components.Animation#skipMissedFrames - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.skipMissedFrames = true; - - /** - * A delay before starting playback, in milliseconds. - * - * @name Phaser.GameObjects.Components.Animation#_delay - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._delay = 0; - - /** - * Number of times to repeat the animation (-1 for infinity) - * - * @name Phaser.GameObjects.Components.Animation#_repeat - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._repeat = 0; - - /** - * Delay before the repeat starts, in milliseconds. - * - * @name Phaser.GameObjects.Components.Animation#_repeatDelay - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._repeatDelay = 0; - - /** - * Should the animation yoyo? (reverse back down to the start) before repeating? - * - * @name Phaser.GameObjects.Components.Animation#_yoyo - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._yoyo = false; - - /** - * Will the playhead move forwards (`true`) or in reverse (`false`). - * - * @name Phaser.GameObjects.Components.Animation#forward - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.forward = true; - - /** - * An Internal trigger that's play the animation in reverse mode ('true') or not ('false'), - * needed because forward can be changed by yoyo feature. - * - * @name Phaser.GameObjects.Components.Animation#_reverse - * @type {boolean} - * @default false - * @private - * @since 3.12.0 - */ - this._reverse = false; - - /** - * Internal time overflow accumulator. - * - * @name Phaser.GameObjects.Components.Animation#accumulator - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accumulator = 0; - - /** - * The time point at which the next animation frame will change. - * - * @name Phaser.GameObjects.Components.Animation#nextTick - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.nextTick = 0; - - /** - * An internal counter keeping track of how many repeats are left to play. - * - * @name Phaser.GameObjects.Components.Animation#repeatCounter - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.repeatCounter = 0; - - /** - * An internal flag keeping track of pending repeats. - * - * @name Phaser.GameObjects.Components.Animation#pendingRepeat - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.pendingRepeat = false; - - /** - * Is the Animation paused? - * - * @name Phaser.GameObjects.Components.Animation#_paused - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._paused = false; - - /** - * Was the animation previously playing before being paused? - * - * @name Phaser.GameObjects.Components.Animation#_wasPlaying - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._wasPlaying = false; - - /** - * Internal property tracking if this Animation is waiting to stop. - * - * 0 = No - * 1 = Waiting for ms to pass - * 2 = Waiting for repeat - * 3 = Waiting for specific frame - * - * @name Phaser.GameObjects.Components.Animation#_pendingStop - * @type {integer} - * @private - * @since 3.4.0 - */ - this._pendingStop = 0; - - /** - * Internal property used by _pendingStop. - * - * @name Phaser.GameObjects.Components.Animation#_pendingStopValue - * @type {any} - * @private - * @since 3.4.0 - */ - this._pendingStopValue; - }, - - /** - * Sets an animation to be played immediately after the current one completes. - * - * The current animation must enter a 'completed' state for this to happen, i.e. finish all of its repeats, delays, etc, or have the `stop` method called directly on it. - * - * An animation set to repeat forever will never enter a completed state. - * - * You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). - * Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. - * - * Call this method with no arguments to reset the chained animation. - * - * @method Phaser.GameObjects.Components.Animation#chain - * @since 3.16.0 - * - * @param {(string|Phaser.Animations.Animation)} [key] - The string-based key of the animation to play next, as defined previously in the Animation Manager. Or an Animation instance. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - chain: function (key) - { - if (key instanceof BaseAnimation) - { - key = key.key; - } - - this.nextAnim = key; - - return this.parent; - }, - - /** - * Sets the amount of time, in milliseconds, that the animation will be delayed before starting playback. - * - * @method Phaser.GameObjects.Components.Animation#setDelay - * @since 3.4.0 - * - * @param {integer} [value=0] - The amount of time, in milliseconds, to wait before starting playback. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - setDelay: function (value) - { - if (value === undefined) { value = 0; } - - this._delay = value; - - return this.parent; - }, - - /** - * Gets the amount of time, in milliseconds that the animation will be delayed before starting playback. - * - * @method Phaser.GameObjects.Components.Animation#getDelay - * @since 3.4.0 - * - * @return {integer} The amount of time, in milliseconds, the Animation will wait before starting playback. - */ - getDelay: function () - { - return this._delay; - }, - - /** - * Waits for the specified delay, in milliseconds, then starts playback of the requested animation. - * - * @method Phaser.GameObjects.Components.Animation#delayedPlay - * @since 3.0.0 - * - * @param {integer} delay - The delay, in milliseconds, to wait before starting the animation playing. - * @param {string} key - The key of the animation to play. - * @param {integer} [startFrame=0] - The frame of the animation to start from. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - delayedPlay: function (delay, key, startFrame) - { - this.play(key, true, startFrame); - - this.nextTick += delay; - - return this.parent; - }, - - /** - * Returns the key of the animation currently loaded into this component. - * - * @method Phaser.GameObjects.Components.Animation#getCurrentKey - * @since 3.0.0 - * - * @return {string} The key of the Animation loaded into this component. - */ - getCurrentKey: function () - { - if (this.currentAnim) - { - return this.currentAnim.key; - } - }, - - /** - * Internal method used to load an animation into this component. - * - * @method Phaser.GameObjects.Components.Animation#load - * @protected - * @since 3.0.0 - * - * @param {string} key - The key of the animation to load. - * @param {integer} [startFrame=0] - The start frame of the animation to load. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - load: function (key, startFrame) - { - if (startFrame === undefined) { startFrame = 0; } - - if (this.isPlaying) - { - this.stop(); - } - - // Load the new animation in - this.animationManager.load(this, key, startFrame); - - return this.parent; - }, - - /** - * Pause the current animation and set the `isPlaying` property to `false`. - * You can optionally pause it at a specific frame. - * - * @method Phaser.GameObjects.Components.Animation#pause - * @since 3.0.0 - * - * @param {Phaser.Animations.AnimationFrame} [atFrame] - An optional frame to set after pausing the animation. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - pause: function (atFrame) - { - if (!this._paused) - { - this._paused = true; - this._wasPlaying = this.isPlaying; - this.isPlaying = false; - } - - if (atFrame !== undefined) - { - this.updateFrame(atFrame); - } - - return this.parent; - }, - - /** - * Resumes playback of a paused animation and sets the `isPlaying` property to `true`. - * You can optionally tell it to start playback from a specific frame. - * - * @method Phaser.GameObjects.Components.Animation#resume - * @since 3.0.0 - * - * @param {Phaser.Animations.AnimationFrame} [fromFrame] - An optional frame to set before restarting playback. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - resume: function (fromFrame) - { - if (this._paused) - { - this._paused = false; - this.isPlaying = this._wasPlaying; - } - - if (fromFrame !== undefined) - { - this.updateFrame(fromFrame); - } - - return this.parent; - }, - - /** - * `true` if the current animation is paused, otherwise `false`. - * - * @name Phaser.GameObjects.Components.Animation#isPaused - * @readonly - * @type {boolean} - * @since 3.4.0 - */ - isPaused: { - - get: function () - { - return this._paused; - } - - }, - - /** - * Plays an Animation on a Game Object that has the Animation component, such as a Sprite. - * - * Animations are stored in the global Animation Manager and are referenced by a unique string-based key. - * - * @method Phaser.GameObjects.Components.Animation#play - * @fires Phaser.GameObjects.Components.Animation#onStartEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Animations.Animation)} key - The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. - * @param {boolean} [ignoreIfPlaying=false] - If this animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false; } - if (startFrame === undefined) { startFrame = 0; } - - if (key instanceof BaseAnimation) - { - key = key.key; - } - - if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) - { - return this.parent; - } - - this.forward = true; - this._reverse = false; - this._paused = false; - this._wasPlaying = true; - - return this._startAnimation(key, startFrame); - }, - - /** - * Plays an Animation (in reverse mode) on the Game Object that owns this Animation Component. - * - * @method Phaser.GameObjects.Components.Animation#playReverse - * @fires Phaser.GameObjects.Components.Animation#onStartEvent - * @since 3.12.0 - * - * @param {(string|Phaser.Animations.Animation)} key - The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - playReverse: function (key, ignoreIfPlaying, startFrame) - { - if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false; } - if (startFrame === undefined) { startFrame = 0; } - - if (key instanceof BaseAnimation) - { - key = key.key; - } - - if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) - { - return this.parent; - } - - this.forward = false; - this._reverse = true; - - return this._startAnimation(key, startFrame); - }, - - /** - * Load an Animation and fires 'onStartEvent' event, extracted from 'play' method. - * - * @method Phaser.GameObjects.Components.Animation#_startAnimation - * @fires Phaser.Animations.Events#START_ANIMATION_EVENT - * @fires Phaser.Animations.Events#SPRITE_START_ANIMATION_EVENT - * @fires Phaser.Animations.Events#SPRITE_START_KEY_ANIMATION_EVENT - * @since 3.12.0 - * - * @param {string} key - The string-based key of the animation to play, as defined previously in the Animation Manager. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - _startAnimation: function (key, startFrame) - { - this.load(key, startFrame); - - var anim = this.currentAnim; - var gameObject = this.parent; - - if (!anim) - { - return gameObject; - } - - // Should give us 9,007,199,254,740,991 safe repeats - this.repeatCounter = (this._repeat === -1) ? Number.MAX_VALUE : this._repeat; - - anim.getFirstTick(this); - - this.isPlaying = true; - this.pendingRepeat = false; - - if (anim.showOnStart) - { - gameObject.visible = true; - } - - var frame = this.currentFrame; - - anim.emit(Events.ANIMATION_START, anim, frame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_KEY_START + key, anim, frame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_START, anim, frame, gameObject); - - return gameObject; - }, - - /** - * Reverse the Animation that is already playing on the Game Object. - * - * @method Phaser.GameObjects.Components.Animation#reverse - * @since 3.12.0 - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - reverse: function () - { - if (this.isPlaying) - { - this._reverse = !this._reverse; - - this.forward = !this.forward; - } - - return this.parent; - }, - - /** - * Returns a value between 0 and 1 indicating how far this animation is through, ignoring repeats and yoyos. - * If the animation has a non-zero repeat defined, `getProgress` and `getTotalProgress` will be different - * because `getProgress` doesn't include any repeats or repeat delays, whereas `getTotalProgress` does. - * - * @method Phaser.GameObjects.Components.Animation#getProgress - * @since 3.4.0 - * - * @return {number} The progress of the current animation, between 0 and 1. - */ - getProgress: function () - { - var p = this.currentFrame.progress; - - if (!this.forward) - { - p = 1 - p; - } - - return p; - }, - - /** - * 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. - * - * @method Phaser.GameObjects.Components.Animation#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. - */ - setProgress: function (value) - { - if (!this.forward) - { - value = 1 - value; - } - - this.setCurrentFrame(this.currentAnim.getFrameByProgress(value)); - - return this.parent; - }, - - /** - * Handle the removal of an animation from the Animation Manager. - * - * @method Phaser.GameObjects.Components.Animation#remove - * @since 3.0.0 - * - * @param {string} [key] - The key of the removed Animation. - * @param {Phaser.Animations.Animation} [animation] - The removed Animation. - */ - remove: function (key, animation) - { - if (animation === undefined) { animation = this.currentAnim; } - - if (this.isPlaying && animation.key === this.currentAnim.key) - { - this.stop(); - - this.setCurrentFrame(this.currentAnim.frames[0]); - } - }, - - /** - * Gets the number of times that the animation will repeat - * after its first iteration. For example, if returns 1, the animation will - * play a total of twice (the initial play plus 1 repeat). - * A value of -1 means the animation will repeat indefinitely. - * - * @method Phaser.GameObjects.Components.Animation#getRepeat - * @since 3.4.0 - * - * @return {integer} The number of times that the animation will repeat. - */ - getRepeat: function () - { - return this._repeat; - }, - - /** - * Sets the number of times that the animation should repeat - * after its first iteration. For example, if repeat is 1, the animation will - * play a total of twice (the initial play plus 1 repeat). - * To repeat indefinitely, use -1. repeat should always be an integer. - * - * @method Phaser.GameObjects.Components.Animation#setRepeat - * @since 3.4.0 - * - * @param {integer} value - The number of times that the animation should repeat. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - setRepeat: function (value) - { - this._repeat = value; - - this.repeatCounter = (value === -1) ? Number.MAX_VALUE : value; - - return this.parent; - }, - - /** - * Gets the amount of delay between repeats, if any. - * - * @method Phaser.GameObjects.Components.Animation#getRepeatDelay - * @since 3.4.0 - * - * @return {number} The delay between repeats. - */ - getRepeatDelay: function () - { - return this._repeatDelay; - }, - - /** - * Sets the amount of time in seconds between repeats. - * For example, if `repeat` is 2 and `repeatDelay` is 10, the animation will play initially, - * then wait for 10 seconds before repeating, then play again, then wait another 10 seconds - * before doing its final repeat. - * - * @method Phaser.GameObjects.Components.Animation#setRepeatDelay - * @since 3.4.0 - * - * @param {number} value - The delay to wait between repeats, in seconds. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - setRepeatDelay: function (value) - { - this._repeatDelay = value; - - return this.parent; - }, - - /** - * Restarts the current animation from its beginning, optionally including its delay value. - * - * @method Phaser.GameObjects.Components.Animation#restart - * @fires Phaser.Animations.Events#RESTART_ANIMATION_EVENT - * @fires Phaser.Animations.Events#SPRITE_RESTART_ANIMATION_EVENT - * @fires Phaser.Animations.Events#SPRITE_RESTART_KEY_ANIMATION_EVENT - * @since 3.0.0 - * - * @param {boolean} [includeDelay=false] - Whether to include the delay value of the animation when restarting. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - restart: function (includeDelay) - { - if (includeDelay === undefined) { includeDelay = false; } - - var anim = this.currentAnim; - - anim.getFirstTick(this, includeDelay); - - this.forward = true; - this.isPlaying = true; - this.pendingRepeat = false; - this._paused = false; - - // Set frame - this.updateFrame(anim.frames[0]); - - var gameObject = this.parent; - var frame = this.currentFrame; - - anim.emit(Events.ANIMATION_RESTART, anim, frame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_KEY_RESTART + anim.key, anim, frame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_RESTART, anim, frame, gameObject); - - return this.parent; - }, - - /** - * Immediately stops the current animation from playing and dispatches the `animationcomplete` event. - * - * If no animation is set, no event will be dispatched. - * - * If there is another animation queued (via the `chain` method) then it will start playing immediately. - * - * @method Phaser.GameObjects.Components.Animation#stop - * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - stop: function () - { - this._pendingStop = 0; - - this.isPlaying = false; - - var gameObject = this.parent; - var anim = this.currentAnim; - var frame = this.currentFrame; - - if (anim) - { - anim.emit(Events.ANIMATION_COMPLETE, anim, frame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_KEY_COMPLETE + anim.key, anim, frame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_COMPLETE, anim, frame, gameObject); - } - - if (this.nextAnim) - { - var key = this.nextAnim; - - this.nextAnim = null; - - this.play(key); - } - - return gameObject; - }, - - /** - * Stops the current animation from playing after the specified time delay, given in milliseconds. - * - * @method Phaser.GameObjects.Components.Animation#stopAfterDelay - * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent - * @since 3.4.0 - * - * @param {integer} delay - The number of milliseconds to wait before stopping this animation. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - stopAfterDelay: function (delay) - { - this._pendingStop = 1; - this._pendingStopValue = delay; - - return this.parent; - }, - - /** - * Stops the current animation from playing when it next repeats. - * - * @method Phaser.GameObjects.Components.Animation#stopOnRepeat - * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent - * @since 3.4.0 - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - stopOnRepeat: function () - { - this._pendingStop = 2; - - return this.parent; - }, - - /** - * Stops the current animation from playing when it next sets the given frame. - * If this frame doesn't exist within the animation it will not stop it from playing. - * - * @method Phaser.GameObjects.Components.Animation#stopOnFrame - * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent - * @since 3.4.0 - * - * @param {Phaser.Animations.AnimationFrame} frame - The frame to check before stopping this animation. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - stopOnFrame: function (frame) - { - this._pendingStop = 3; - this._pendingStopValue = frame; - - return this.parent; - }, - - /** - * Sets the Time Scale factor, allowing you to make the animation go go faster or slower than default. - * Where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. - * - * @method Phaser.GameObjects.Components.Animation#setTimeScale - * @since 3.4.0 - * - * @param {number} [value=1] - The time scale factor, where 1 is no change, 0.5 is half speed, etc. - * - * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. - */ - setTimeScale: function (value) - { - if (value === undefined) { value = 1; } - - this._timeScale = value; - - return this.parent; - }, - - /** - * Gets the Time Scale factor. - * - * @method Phaser.GameObjects.Components.Animation#getTimeScale - * @since 3.4.0 - * - * @return {number} The Time Scale value. - */ - getTimeScale: function () - { - return this._timeScale; - }, - - /** - * Returns the total number of frames in this animation. - * - * @method Phaser.GameObjects.Components.Animation#getTotalFrames - * @since 3.4.0 - * - * @return {integer} The total number of frames in this animation. - */ - getTotalFrames: function () - { - return this.currentAnim.frames.length; - }, - - /** - * The internal update loop for the Animation Component. - * - * @method Phaser.GameObjects.Components.Animation#update - * @since 3.0.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - update: function (time, delta) - { - if (!this.currentAnim || !this.isPlaying || this.currentAnim.paused) - { - return; - } - - this.accumulator += delta * this._timeScale; - - if (this._pendingStop === 1) - { - this._pendingStopValue -= delta; - - if (this._pendingStopValue <= 0) - { - return this.currentAnim.completeAnimation(this); - } - } - - if (this.accumulator >= this.nextTick) - { - this.currentAnim.setFrame(this); - } - }, - - /** - * Sets the given Animation Frame as being the current frame - * and applies it to the parent Game Object, adjusting its size and origin as needed. - * - * @method Phaser.GameObjects.Components.Animation#setCurrentFrame - * @since 3.4.0 - * - * @param {Phaser.Animations.AnimationFrame} animationFrame - The Animation Frame to set as being current. - * - * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. - */ - setCurrentFrame: function (animationFrame) - { - var gameObject = this.parent; - - this.currentFrame = animationFrame; - - gameObject.texture = animationFrame.frame.texture; - gameObject.frame = animationFrame.frame; - - if (gameObject.isCropped) - { - gameObject.frame.updateCropUVs(gameObject._crop, gameObject.flipX, gameObject.flipY); - } - - gameObject.setSizeToFrame(); - - if (gameObject._originComponent) - { - if (animationFrame.frame.customPivot) - { - gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); - } - else - { - gameObject.updateDisplayOrigin(); - } - } - - return gameObject; - }, - - /** - * Internal frame change handler. - * - * @method Phaser.GameObjects.Components.Animation#updateFrame - * @fires Phaser.Animations.Events#SPRITE_ANIMATION_UPDATE_EVENT - * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_UPDATE_EVENT - * @private - * @since 3.0.0 - * - * @param {Phaser.Animations.AnimationFrame} animationFrame - The animation frame to change to. - */ - updateFrame: function (animationFrame) - { - var gameObject = this.setCurrentFrame(animationFrame); - - if (this.isPlaying) - { - if (animationFrame.setAlpha) - { - gameObject.alpha = animationFrame.alpha; - } - - var anim = this.currentAnim; - - gameObject.emit(Events.SPRITE_ANIMATION_KEY_UPDATE + anim.key, anim, animationFrame, gameObject); - - gameObject.emit(Events.SPRITE_ANIMATION_UPDATE, anim, animationFrame, gameObject); - - if (this._pendingStop === 3 && this._pendingStopValue === animationFrame) - { - this.currentAnim.completeAnimation(this); - } - } - }, - - /** - * Advances the animation to the next frame, regardless of the time or animation state. - * If the animation is set to repeat, or yoyo, this will still take effect. - * - * Calling this does not change the direction of the animation. I.e. if it was currently - * playing in reverse, calling this method doesn't then change the direction to forwards. - * - * @method Phaser.GameObjects.Components.Animation#nextFrame - * @since 3.16.0 - * - * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. - */ - nextFrame: function () - { - if (this.currentAnim) - { - this.currentAnim.nextFrame(this); - } - - return this.parent; - }, - - /** - * Advances the animation to the previous frame, regardless of the time or animation state. - * If the animation is set to repeat, or yoyo, this will still take effect. - * - * Calling this does not change the direction of the animation. I.e. if it was currently - * playing in forwards, calling this method doesn't then change the direction to backwards. - * - * @method Phaser.GameObjects.Components.Animation#previousFrame - * @since 3.16.0 - * - * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. - */ - previousFrame: function () - { - if (this.currentAnim) - { - this.currentAnim.previousFrame(this); - } - - return this.parent; - }, - - /** - * Sets if the current Animation will yoyo when it reaches the end. - * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. - * - * @method Phaser.GameObjects.Components.Animation#setYoyo - * @since 3.4.0 - * - * @param {boolean} [value=false] - `true` if the animation should yoyo, `false` to not. - * - * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. - */ - setYoyo: function (value) - { - if (value === undefined) { value = false; } - - this._yoyo = value; - - return this.parent; - }, - - /** - * Gets if the current Animation will yoyo when it reaches the end. - * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. - * - * @method Phaser.GameObjects.Components.Animation#getYoyo - * @since 3.4.0 - * - * @return {boolean} `true` if the animation is set to yoyo, `false` if not. - */ - getYoyo: function () - { - return this._yoyo; - }, - - /** - * Destroy this Animation component. - * - * Unregisters event listeners and cleans up its references. - * - * @method Phaser.GameObjects.Components.Animation#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.animationManager.off(Events.REMOVE_ANIMATION, this.remove, this); - - this.animationManager = null; - this.parent = null; - - this.currentAnim = null; - this.currentFrame = null; - } - -}); - -module.exports = Animation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseAnimation = require('../../animations/Animation'); +var Class = require('../../utils/Class'); +var Events = require('../../animations/events'); + +/** + * @classdesc + * A Game Object Animation Controller. + * + * This controller lives as an instance within a Game Object, accessible as `sprite.anims`. + * + * @class Animation + * @memberof Phaser.GameObjects.Components + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} parent - The Game Object to which this animation controller belongs. + */ +var Animation = new Class({ + + initialize: + + function Animation (parent) + { + /** + * The Game Object to which this animation controller belongs. + * + * @name Phaser.GameObjects.Components.Animation#parent + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * A reference to the global Animation Manager. + * + * @name Phaser.GameObjects.Components.Animation#animationManager + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.animationManager = parent.scene.sys.anims; + + this.animationManager.once(Events.REMOVE_ANIMATION, this.remove, this); + + /** + * Is an animation currently playing or not? + * + * @name Phaser.GameObjects.Components.Animation#isPlaying + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isPlaying = false; + + /** + * The current Animation loaded into this Animation Controller. + * + * @name Phaser.GameObjects.Components.Animation#currentAnim + * @type {?Phaser.Animations.Animation} + * @default null + * @since 3.0.0 + */ + this.currentAnim = null; + + /** + * The current AnimationFrame being displayed by this Animation Controller. + * + * @name Phaser.GameObjects.Components.Animation#currentFrame + * @type {?Phaser.Animations.AnimationFrame} + * @default null + * @since 3.0.0 + */ + this.currentFrame = null; + + /** + * The key of the next Animation to be loaded into this Animation Controller when the current animation completes. + * + * @name Phaser.GameObjects.Components.Animation#nextAnim + * @type {?string} + * @default null + * @since 3.16.0 + */ + this.nextAnim = null; + + /** + * Time scale factor. + * + * @name Phaser.GameObjects.Components.Animation#_timeScale + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + this._timeScale = 1; + + /** + * The frame rate of playback in frames per second. + * The default is 24 if the `duration` property is `null`. + * + * @name Phaser.GameObjects.Components.Animation#frameRate + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.frameRate = 0; + + /** + * How long the animation should play for, in milliseconds. + * If the `frameRate` property has been set then it overrides this value, + * otherwise the `frameRate` is derived from `duration`. + * + * @name Phaser.GameObjects.Components.Animation#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * ms per frame, not including frame specific modifiers that may be present in the Animation data. + * + * @name Phaser.GameObjects.Components.Animation#msPerFrame + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.msPerFrame = 0; + + /** + * Skip frames if the time lags, or always advanced anyway? + * + * @name Phaser.GameObjects.Components.Animation#skipMissedFrames + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.skipMissedFrames = true; + + /** + * A delay before starting playback, in milliseconds. + * + * @name Phaser.GameObjects.Components.Animation#_delay + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._delay = 0; + + /** + * Number of times to repeat the animation (-1 for infinity) + * + * @name Phaser.GameObjects.Components.Animation#_repeat + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._repeat = 0; + + /** + * Delay before the repeat starts, in milliseconds. + * + * @name Phaser.GameObjects.Components.Animation#_repeatDelay + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._repeatDelay = 0; + + /** + * Should the animation yoyo? (reverse back down to the start) before repeating? + * + * @name Phaser.GameObjects.Components.Animation#_yoyo + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._yoyo = false; + + /** + * Will the playhead move forwards (`true`) or in reverse (`false`). + * + * @name Phaser.GameObjects.Components.Animation#forward + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.forward = true; + + /** + * An Internal trigger that's play the animation in reverse mode ('true') or not ('false'), + * needed because forward can be changed by yoyo feature. + * + * @name Phaser.GameObjects.Components.Animation#_reverse + * @type {boolean} + * @default false + * @private + * @since 3.12.0 + */ + this._reverse = false; + + /** + * Internal time overflow accumulator. + * + * @name Phaser.GameObjects.Components.Animation#accumulator + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accumulator = 0; + + /** + * The time point at which the next animation frame will change. + * + * @name Phaser.GameObjects.Components.Animation#nextTick + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.nextTick = 0; + + /** + * An internal counter keeping track of how many repeats are left to play. + * + * @name Phaser.GameObjects.Components.Animation#repeatCounter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.repeatCounter = 0; + + /** + * An internal flag keeping track of pending repeats. + * + * @name Phaser.GameObjects.Components.Animation#pendingRepeat + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.pendingRepeat = false; + + /** + * Is the Animation paused? + * + * @name Phaser.GameObjects.Components.Animation#_paused + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._paused = false; + + /** + * Was the animation previously playing before being paused? + * + * @name Phaser.GameObjects.Components.Animation#_wasPlaying + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._wasPlaying = false; + + /** + * Internal property tracking if this Animation is waiting to stop. + * + * 0 = No + * 1 = Waiting for ms to pass + * 2 = Waiting for repeat + * 3 = Waiting for specific frame + * + * @name Phaser.GameObjects.Components.Animation#_pendingStop + * @type {integer} + * @private + * @since 3.4.0 + */ + this._pendingStop = 0; + + /** + * Internal property used by _pendingStop. + * + * @name Phaser.GameObjects.Components.Animation#_pendingStopValue + * @type {any} + * @private + * @since 3.4.0 + */ + this._pendingStopValue; + }, + + /** + * Sets an animation to be played immediately after the current one completes. + * + * The current animation must enter a 'completed' state for this to happen, i.e. finish all of its repeats, delays, etc, or have the `stop` method called directly on it. + * + * An animation set to repeat forever will never enter a completed state. + * + * You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). + * Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. + * + * Call this method with no arguments to reset the chained animation. + * + * @method Phaser.GameObjects.Components.Animation#chain + * @since 3.16.0 + * + * @param {(string|Phaser.Animations.Animation)} [key] - The string-based key of the animation to play next, as defined previously in the Animation Manager. Or an Animation instance. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + chain: function (key) + { + if (key instanceof BaseAnimation) + { + key = key.key; + } + + this.nextAnim = key; + + return this.parent; + }, + + /** + * Sets the amount of time, in milliseconds, that the animation will be delayed before starting playback. + * + * @method Phaser.GameObjects.Components.Animation#setDelay + * @since 3.4.0 + * + * @param {integer} [value=0] - The amount of time, in milliseconds, to wait before starting playback. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setDelay: function (value) + { + if (value === undefined) { value = 0; } + + this._delay = value; + + return this.parent; + }, + + /** + * Gets the amount of time, in milliseconds that the animation will be delayed before starting playback. + * + * @method Phaser.GameObjects.Components.Animation#getDelay + * @since 3.4.0 + * + * @return {integer} The amount of time, in milliseconds, the Animation will wait before starting playback. + */ + getDelay: function () + { + return this._delay; + }, + + /** + * Waits for the specified delay, in milliseconds, then starts playback of the requested animation. + * + * @method Phaser.GameObjects.Components.Animation#delayedPlay + * @since 3.0.0 + * + * @param {integer} delay - The delay, in milliseconds, to wait before starting the animation playing. + * @param {string} key - The key of the animation to play. + * @param {integer} [startFrame=0] - The frame of the animation to start from. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + delayedPlay: function (delay, key, startFrame) + { + this.play(key, true, startFrame); + + this.nextTick += delay; + + return this.parent; + }, + + /** + * Returns the key of the animation currently loaded into this component. + * + * @method Phaser.GameObjects.Components.Animation#getCurrentKey + * @since 3.0.0 + * + * @return {string} The key of the Animation loaded into this component. + */ + getCurrentKey: function () + { + if (this.currentAnim) + { + return this.currentAnim.key; + } + }, + + /** + * Internal method used to load an animation into this component. + * + * @method Phaser.GameObjects.Components.Animation#load + * @protected + * @since 3.0.0 + * + * @param {string} key - The key of the animation to load. + * @param {integer} [startFrame=0] - The start frame of the animation to load. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + load: function (key, startFrame) + { + if (startFrame === undefined) { startFrame = 0; } + + if (this.isPlaying) + { + this.stop(); + } + + // Load the new animation in + this.animationManager.load(this, key, startFrame); + + return this.parent; + }, + + /** + * Pause the current animation and set the `isPlaying` property to `false`. + * You can optionally pause it at a specific frame. + * + * @method Phaser.GameObjects.Components.Animation#pause + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} [atFrame] - An optional frame to set after pausing the animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + pause: function (atFrame) + { + if (!this._paused) + { + this._paused = true; + this._wasPlaying = this.isPlaying; + this.isPlaying = false; + } + + if (atFrame !== undefined) + { + this.updateFrame(atFrame); + } + + return this.parent; + }, + + /** + * Resumes playback of a paused animation and sets the `isPlaying` property to `true`. + * You can optionally tell it to start playback from a specific frame. + * + * @method Phaser.GameObjects.Components.Animation#resume + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} [fromFrame] - An optional frame to set before restarting playback. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + resume: function (fromFrame) + { + if (this._paused) + { + this._paused = false; + this.isPlaying = this._wasPlaying; + } + + if (fromFrame !== undefined) + { + this.updateFrame(fromFrame); + } + + return this.parent; + }, + + /** + * `true` if the current animation is paused, otherwise `false`. + * + * @name Phaser.GameObjects.Components.Animation#isPaused + * @readonly + * @type {boolean} + * @since 3.4.0 + */ + isPaused: { + + get: function () + { + return this._paused; + } + + }, + + /** + * Plays an Animation on a Game Object that has the Animation component, such as a Sprite. + * + * Animations are stored in the global Animation Manager and are referenced by a unique string-based key. + * + * @method Phaser.GameObjects.Components.Animation#play + * @fires Phaser.GameObjects.Components.Animation#onStartEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Animations.Animation)} key - The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. + * @param {boolean} [ignoreIfPlaying=false] - If this animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + play: function (key, ignoreIfPlaying, startFrame) + { + if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false; } + if (startFrame === undefined) { startFrame = 0; } + + if (key instanceof BaseAnimation) + { + key = key.key; + } + + if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) + { + return this.parent; + } + + this.forward = true; + this._reverse = false; + this._paused = false; + this._wasPlaying = true; + + return this._startAnimation(key, startFrame); + }, + + /** + * Plays an Animation (in reverse mode) on the Game Object that owns this Animation Component. + * + * @method Phaser.GameObjects.Components.Animation#playReverse + * @fires Phaser.GameObjects.Components.Animation#onStartEvent + * @since 3.12.0 + * + * @param {(string|Phaser.Animations.Animation)} key - The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + playReverse: function (key, ignoreIfPlaying, startFrame) + { + if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false; } + if (startFrame === undefined) { startFrame = 0; } + + if (key instanceof BaseAnimation) + { + key = key.key; + } + + if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) + { + return this.parent; + } + + this.forward = false; + this._reverse = true; + + return this._startAnimation(key, startFrame); + }, + + /** + * Load an Animation and fires 'onStartEvent' event, extracted from 'play' method. + * + * @method Phaser.GameObjects.Components.Animation#_startAnimation + * @fires Phaser.Animations.Events#START_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_START_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_START_KEY_ANIMATION_EVENT + * @since 3.12.0 + * + * @param {string} key - The string-based key of the animation to play, as defined previously in the Animation Manager. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + _startAnimation: function (key, startFrame) + { + this.load(key, startFrame); + + var anim = this.currentAnim; + var gameObject = this.parent; + + if (!anim) + { + return gameObject; + } + + // Should give us 9,007,199,254,740,991 safe repeats + this.repeatCounter = (this._repeat === -1) ? Number.MAX_VALUE : this._repeat; + + anim.getFirstTick(this); + + this.isPlaying = true; + this.pendingRepeat = false; + + if (anim.showOnStart) + { + gameObject.visible = true; + } + + var frame = this.currentFrame; + + anim.emit(Events.ANIMATION_START, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_START + key, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_START, anim, frame, gameObject); + + return gameObject; + }, + + /** + * Reverse the Animation that is already playing on the Game Object. + * + * @method Phaser.GameObjects.Components.Animation#reverse + * @since 3.12.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + reverse: function () + { + if (this.isPlaying) + { + this._reverse = !this._reverse; + + this.forward = !this.forward; + } + + return this.parent; + }, + + /** + * Returns a value between 0 and 1 indicating how far this animation is through, ignoring repeats and yoyos. + * If the animation has a non-zero repeat defined, `getProgress` and `getTotalProgress` will be different + * because `getProgress` doesn't include any repeats or repeat delays, whereas `getTotalProgress` does. + * + * @method Phaser.GameObjects.Components.Animation#getProgress + * @since 3.4.0 + * + * @return {number} The progress of the current animation, between 0 and 1. + */ + getProgress: function () + { + var p = this.currentFrame.progress; + + if (!this.forward) + { + p = 1 - p; + } + + return p; + }, + + /** + * 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. + * + * @method Phaser.GameObjects.Components.Animation#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. + */ + setProgress: function (value) + { + if (!this.forward) + { + value = 1 - value; + } + + this.setCurrentFrame(this.currentAnim.getFrameByProgress(value)); + + return this.parent; + }, + + /** + * Handle the removal of an animation from the Animation Manager. + * + * @method Phaser.GameObjects.Components.Animation#remove + * @since 3.0.0 + * + * @param {string} [key] - The key of the removed Animation. + * @param {Phaser.Animations.Animation} [animation] - The removed Animation. + */ + remove: function (key, animation) + { + if (animation === undefined) { animation = this.currentAnim; } + + if (this.isPlaying && animation.key === this.currentAnim.key) + { + this.stop(); + + this.setCurrentFrame(this.currentAnim.frames[0]); + } + }, + + /** + * Gets the number of times that the animation will repeat + * after its first iteration. For example, if returns 1, the animation will + * play a total of twice (the initial play plus 1 repeat). + * A value of -1 means the animation will repeat indefinitely. + * + * @method Phaser.GameObjects.Components.Animation#getRepeat + * @since 3.4.0 + * + * @return {integer} The number of times that the animation will repeat. + */ + getRepeat: function () + { + return this._repeat; + }, + + /** + * Sets the number of times that the animation should repeat + * after its first iteration. For example, if repeat is 1, the animation will + * play a total of twice (the initial play plus 1 repeat). + * To repeat indefinitely, use -1. repeat should always be an integer. + * + * @method Phaser.GameObjects.Components.Animation#setRepeat + * @since 3.4.0 + * + * @param {integer} value - The number of times that the animation should repeat. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setRepeat: function (value) + { + this._repeat = value; + + this.repeatCounter = (value === -1) ? Number.MAX_VALUE : value; + + return this.parent; + }, + + /** + * Gets the amount of delay between repeats, if any. + * + * @method Phaser.GameObjects.Components.Animation#getRepeatDelay + * @since 3.4.0 + * + * @return {number} The delay between repeats. + */ + getRepeatDelay: function () + { + return this._repeatDelay; + }, + + /** + * Sets the amount of time in seconds between repeats. + * For example, if `repeat` is 2 and `repeatDelay` is 10, the animation will play initially, + * then wait for 10 seconds before repeating, then play again, then wait another 10 seconds + * before doing its final repeat. + * + * @method Phaser.GameObjects.Components.Animation#setRepeatDelay + * @since 3.4.0 + * + * @param {number} value - The delay to wait between repeats, in seconds. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setRepeatDelay: function (value) + { + this._repeatDelay = value; + + return this.parent; + }, + + /** + * Restarts the current animation from its beginning, optionally including its delay value. + * + * @method Phaser.GameObjects.Components.Animation#restart + * @fires Phaser.Animations.Events#RESTART_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_RESTART_ANIMATION_EVENT + * @fires Phaser.Animations.Events#SPRITE_RESTART_KEY_ANIMATION_EVENT + * @since 3.0.0 + * + * @param {boolean} [includeDelay=false] - Whether to include the delay value of the animation when restarting. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + restart: function (includeDelay) + { + if (includeDelay === undefined) { includeDelay = false; } + + var anim = this.currentAnim; + + anim.getFirstTick(this, includeDelay); + + this.forward = true; + this.isPlaying = true; + this.pendingRepeat = false; + this._paused = false; + + // Set frame + this.updateFrame(anim.frames[0]); + + var gameObject = this.parent; + var frame = this.currentFrame; + + anim.emit(Events.ANIMATION_RESTART, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_RESTART + anim.key, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_RESTART, anim, frame, gameObject); + + return this.parent; + }, + + /** + * Immediately stops the current animation from playing and dispatches the `animationcomplete` event. + * + * If no animation is set, no event will be dispatched. + * + * If there is another animation queued (via the `chain` method) then it will start playing immediately. + * + * @method Phaser.GameObjects.Components.Animation#stop + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stop: function () + { + this._pendingStop = 0; + + this.isPlaying = false; + + var gameObject = this.parent; + var anim = this.currentAnim; + var frame = this.currentFrame; + + if (anim) + { + anim.emit(Events.ANIMATION_COMPLETE, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_COMPLETE + anim.key, anim, frame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_COMPLETE, anim, frame, gameObject); + } + + if (this.nextAnim) + { + var key = this.nextAnim; + + this.nextAnim = null; + + this.play(key); + } + + return gameObject; + }, + + /** + * Stops the current animation from playing after the specified time delay, given in milliseconds. + * + * @method Phaser.GameObjects.Components.Animation#stopAfterDelay + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.4.0 + * + * @param {integer} delay - The number of milliseconds to wait before stopping this animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stopAfterDelay: function (delay) + { + this._pendingStop = 1; + this._pendingStopValue = delay; + + return this.parent; + }, + + /** + * Stops the current animation from playing when it next repeats. + * + * @method Phaser.GameObjects.Components.Animation#stopOnRepeat + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.4.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stopOnRepeat: function () + { + this._pendingStop = 2; + + return this.parent; + }, + + /** + * Stops the current animation from playing when it next sets the given frame. + * If this frame doesn't exist within the animation it will not stop it from playing. + * + * @method Phaser.GameObjects.Components.Animation#stopOnFrame + * @fires Phaser.GameObjects.Components.Animation#onCompleteEvent + * @since 3.4.0 + * + * @param {Phaser.Animations.AnimationFrame} frame - The frame to check before stopping this animation. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + stopOnFrame: function (frame) + { + this._pendingStop = 3; + this._pendingStopValue = frame; + + return this.parent; + }, + + /** + * Sets the Time Scale factor, allowing you to make the animation go go faster or slower than default. + * Where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. + * + * @method Phaser.GameObjects.Components.Animation#setTimeScale + * @since 3.4.0 + * + * @param {number} [value=1] - The time scale factor, where 1 is no change, 0.5 is half speed, etc. + * + * @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component. + */ + setTimeScale: function (value) + { + if (value === undefined) { value = 1; } + + this._timeScale = value; + + return this.parent; + }, + + /** + * Gets the Time Scale factor. + * + * @method Phaser.GameObjects.Components.Animation#getTimeScale + * @since 3.4.0 + * + * @return {number} The Time Scale value. + */ + getTimeScale: function () + { + return this._timeScale; + }, + + /** + * Returns the total number of frames in this animation. + * + * @method Phaser.GameObjects.Components.Animation#getTotalFrames + * @since 3.4.0 + * + * @return {integer} The total number of frames in this animation. + */ + getTotalFrames: function () + { + return this.currentAnim.frames.length; + }, + + /** + * The internal update loop for the Animation Component. + * + * @method Phaser.GameObjects.Components.Animation#update + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + update: function (time, delta) + { + if (!this.currentAnim || !this.isPlaying || this.currentAnim.paused) + { + return; + } + + this.accumulator += delta * this._timeScale; + + if (this._pendingStop === 1) + { + this._pendingStopValue -= delta; + + if (this._pendingStopValue <= 0) + { + return this.currentAnim.completeAnimation(this); + } + } + + if (this.accumulator >= this.nextTick) + { + this.currentAnim.setFrame(this); + } + }, + + /** + * Sets the given Animation Frame as being the current frame + * and applies it to the parent Game Object, adjusting its size and origin as needed. + * + * @method Phaser.GameObjects.Components.Animation#setCurrentFrame + * @since 3.4.0 + * + * @param {Phaser.Animations.AnimationFrame} animationFrame - The Animation Frame to set as being current. + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + setCurrentFrame: function (animationFrame) + { + var gameObject = this.parent; + + this.currentFrame = animationFrame; + + gameObject.texture = animationFrame.frame.texture; + gameObject.frame = animationFrame.frame; + + if (gameObject.isCropped) + { + gameObject.frame.updateCropUVs(gameObject._crop, gameObject.flipX, gameObject.flipY); + } + + gameObject.setSizeToFrame(); + + if (gameObject._originComponent) + { + if (animationFrame.frame.customPivot) + { + gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY); + } + else + { + gameObject.updateDisplayOrigin(); + } + } + + return gameObject; + }, + + /** + * Internal frame change handler. + * + * @method Phaser.GameObjects.Components.Animation#updateFrame + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_UPDATE_EVENT + * @fires Phaser.Animations.Events#SPRITE_ANIMATION_KEY_UPDATE_EVENT + * @private + * @since 3.0.0 + * + * @param {Phaser.Animations.AnimationFrame} animationFrame - The animation frame to change to. + */ + updateFrame: function (animationFrame) + { + var gameObject = this.setCurrentFrame(animationFrame); + + if (this.isPlaying) + { + if (animationFrame.setAlpha) + { + gameObject.alpha = animationFrame.alpha; + } + + var anim = this.currentAnim; + + gameObject.emit(Events.SPRITE_ANIMATION_KEY_UPDATE + anim.key, anim, animationFrame, gameObject); + + gameObject.emit(Events.SPRITE_ANIMATION_UPDATE, anim, animationFrame, gameObject); + + if (this._pendingStop === 3 && this._pendingStopValue === animationFrame) + { + this.currentAnim.completeAnimation(this); + } + } + }, + + /** + * Advances the animation to the next frame, regardless of the time or animation state. + * If the animation is set to repeat, or yoyo, this will still take effect. + * + * Calling this does not change the direction of the animation. I.e. if it was currently + * playing in reverse, calling this method doesn't then change the direction to forwards. + * + * @method Phaser.GameObjects.Components.Animation#nextFrame + * @since 3.16.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + nextFrame: function () + { + if (this.currentAnim) + { + this.currentAnim.nextFrame(this); + } + + return this.parent; + }, + + /** + * Advances the animation to the previous frame, regardless of the time or animation state. + * If the animation is set to repeat, or yoyo, this will still take effect. + * + * Calling this does not change the direction of the animation. I.e. if it was currently + * playing in forwards, calling this method doesn't then change the direction to backwards. + * + * @method Phaser.GameObjects.Components.Animation#previousFrame + * @since 3.16.0 + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + previousFrame: function () + { + if (this.currentAnim) + { + this.currentAnim.previousFrame(this); + } + + return this.parent; + }, + + /** + * Sets if the current Animation will yoyo when it reaches the end. + * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. + * + * @method Phaser.GameObjects.Components.Animation#setYoyo + * @since 3.4.0 + * + * @param {boolean} [value=false] - `true` if the animation should yoyo, `false` to not. + * + * @return {Phaser.GameObjects.GameObject} The Game Object this Animation Component belongs to. + */ + setYoyo: function (value) + { + if (value === undefined) { value = false; } + + this._yoyo = value; + + return this.parent; + }, + + /** + * Gets if the current Animation will yoyo when it reaches the end. + * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. + * + * @method Phaser.GameObjects.Components.Animation#getYoyo + * @since 3.4.0 + * + * @return {boolean} `true` if the animation is set to yoyo, `false` if not. + */ + getYoyo: function () + { + return this._yoyo; + }, + + /** + * Destroy this Animation component. + * + * Unregisters event listeners and cleans up its references. + * + * @method Phaser.GameObjects.Components.Animation#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.animationManager.off(Events.REMOVE_ANIMATION, this.remove, this); + + this.animationManager = null; + this.parent = null; + + this.currentAnim = null; + this.currentFrame = null; + } + +}); + +module.exports = Animation; diff --git a/src/gameobjects/components/BlendMode.js b/src/gameobjects/components/BlendMode.js index f868f6bb0..8d21ef609 100644 --- a/src/gameobjects/components/BlendMode.js +++ b/src/gameobjects/components/BlendMode.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BlendModes = require('../../renderer/BlendModes'); - -/** - * Provides methods used for setting the blend mode of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.BlendMode - * @since 3.0.0 - */ - -var BlendMode = { - - /** - * Private internal value. Holds the current blend mode. - * - * @name Phaser.GameObjects.Components.BlendMode#_blendMode - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - _blendMode: BlendModes.NORMAL, - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - * - * @name Phaser.GameObjects.Components.BlendMode#blendMode - * @type {(Phaser.BlendModes|string)} - * @since 3.0.0 - */ - blendMode: { - - get: function () - { - return this._blendMode; - }, - - set: function (value) - { - if (typeof value === 'string') - { - value = BlendModes[value]; - } - - value |= 0; - - if (value >= -1) - { - this._blendMode = value; - } - } - - }, - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * - * @method Phaser.GameObjects.Components.BlendMode#setBlendMode - * @since 3.0.0 - * - * @param {(string|Phaser.BlendModes)} value - The BlendMode value. Either a string or a CONST. - * - * @return {this} This Game Object instance. - */ - setBlendMode: function (value) - { - this.blendMode = value; - - return this; - } - -}; - -module.exports = BlendMode; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = require('../../renderer/BlendModes'); + +/** + * Provides methods used for setting the blend mode of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.BlendMode + * @since 3.0.0 + */ + +var BlendMode = { + + /** + * Private internal value. Holds the current blend mode. + * + * @name Phaser.GameObjects.Components.BlendMode#_blendMode + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + _blendMode: BlendModes.NORMAL, + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + * + * @name Phaser.GameObjects.Components.BlendMode#blendMode + * @type {(Phaser.BlendModes|string)} + * @since 3.0.0 + */ + blendMode: { + + get: function () + { + return this._blendMode; + }, + + set: function (value) + { + if (typeof value === 'string') + { + value = BlendModes[value]; + } + + value |= 0; + + if (value >= -1) + { + this._blendMode = value; + } + } + + }, + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * + * @method Phaser.GameObjects.Components.BlendMode#setBlendMode + * @since 3.0.0 + * + * @param {(string|Phaser.BlendModes)} value - The BlendMode value. Either a string or a CONST. + * + * @return {this} This Game Object instance. + */ + setBlendMode: function (value) + { + this.blendMode = value; + + return this; + } + +}; + +module.exports = BlendMode; diff --git a/src/gameobjects/components/ComputedSize.js b/src/gameobjects/components/ComputedSize.js index 909bffd29..d262787c3 100644 --- a/src/gameobjects/components/ComputedSize.js +++ b/src/gameobjects/components/ComputedSize.js @@ -1,143 +1,143 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for calculating and setting the size of a non-Frame based Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.ComputedSize - * @since 3.0.0 - */ - -var ComputedSize = { - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - * - * @name Phaser.GameObjects.Components.ComputedSize#width - * @type {number} - * @since 3.0.0 - */ - width: 0, - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - * - * @name Phaser.GameObjects.Components.ComputedSize#height - * @type {number} - * @since 3.0.0 - */ - height: 0, - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - * - * @name Phaser.GameObjects.Components.ComputedSize#displayWidth - * @type {number} - * @since 3.0.0 - */ - displayWidth: { - - get: function () - { - return this.scaleX * this.width; - }, - - set: function (value) - { - this.scaleX = value / this.width; - } - - }, - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - * - * @name Phaser.GameObjects.Components.ComputedSize#displayHeight - * @type {number} - * @since 3.0.0 - */ - displayHeight: { - - get: function () - { - return this.scaleY * this.height; - }, - - set: function (value) - { - this.scaleY = value / this.height; - } - - }, - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * - * @method Phaser.GameObjects.Components.ComputedSize#setSize - * @since 3.4.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * - * @return {this} This Game Object instance. - */ - setSize: function (width, height) - { - this.width = width; - this.height = height; - - return this; - }, - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * - * @method Phaser.GameObjects.Components.ComputedSize#setDisplaySize - * @since 3.4.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * - * @return {this} This Game Object instance. - */ - setDisplaySize: function (width, height) - { - this.displayWidth = width; - this.displayHeight = height; - - return this; - } - -}; - -module.exports = ComputedSize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for calculating and setting the size of a non-Frame based Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.ComputedSize + * @since 3.0.0 + */ + +var ComputedSize = { + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + * + * @name Phaser.GameObjects.Components.ComputedSize#width + * @type {number} + * @since 3.0.0 + */ + width: 0, + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + * + * @name Phaser.GameObjects.Components.ComputedSize#height + * @type {number} + * @since 3.0.0 + */ + height: 0, + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.ComputedSize#displayWidth + * @type {number} + * @since 3.0.0 + */ + displayWidth: { + + get: function () + { + return this.scaleX * this.width; + }, + + set: function (value) + { + this.scaleX = value / this.width; + } + + }, + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.ComputedSize#displayHeight + * @type {number} + * @since 3.0.0 + */ + displayHeight: { + + get: function () + { + return this.scaleY * this.height; + }, + + set: function (value) + { + this.scaleY = value / this.height; + } + + }, + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * + * @method Phaser.GameObjects.Components.ComputedSize#setSize + * @since 3.4.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + this.width = width; + this.height = height; + + return this; + }, + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * + * @method Phaser.GameObjects.Components.ComputedSize#setDisplaySize + * @since 3.4.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setDisplaySize: function (width, height) + { + this.displayWidth = width; + this.displayHeight = height; + + return this; + } + +}; + +module.exports = ComputedSize; diff --git a/src/gameobjects/components/Crop.js b/src/gameobjects/components/Crop.js index 18d858aab..c9c9482bd 100644 --- a/src/gameobjects/components/Crop.js +++ b/src/gameobjects/components/Crop.js @@ -1,119 +1,119 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for getting and setting the texture of a Game Object. - * - * @namespace Phaser.GameObjects.Components.Crop - * @since 3.12.0 - */ - -var Crop = { - - /** - * The Texture this Game Object is using to render with. - * - * @name Phaser.GameObjects.Components.Crop#texture - * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} - * @since 3.0.0 - */ - texture: null, - - /** - * The Texture Frame this Game Object is using to render with. - * - * @name Phaser.GameObjects.Components.Crop#frame - * @type {Phaser.Textures.Frame} - * @since 3.0.0 - */ - frame: null, - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - * - * @name Phaser.GameObjects.Components.Crop#isCropped - * @type {boolean} - * @since 3.11.0 - */ - isCropped: false, - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * - * @method Phaser.GameObjects.Components.Crop#setCrop - * @since 3.11.0 - * - * @param {(number|Phaser.Geom.Rectangle)} [x] - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param {number} [y] - The y coordinate to start the crop from. - * @param {number} [width] - The width of the crop rectangle in pixels. - * @param {number} [height] - The height of the crop rectangle in pixels. - * - * @return {this} This Game Object instance. - */ - setCrop: function (x, y, width, height) - { - if (x === undefined) - { - this.isCropped = false; - } - else if (this.frame) - { - if (typeof x === 'number') - { - this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY); - } - else - { - var rect = x; - - this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY); - } - - this.isCropped = true; - } - - return this; - }, - - /** - * Internal method that returns a blank, well-formed crop object for use by a Game Object. - * - * @method Phaser.GameObjects.Components.Crop#resetCropObject - * @private - * @since 3.12.0 - * - * @return {object} The crop object. - */ - resetCropObject: function () - { - return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 }; - } - -}; - -module.exports = Crop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the texture of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Crop + * @since 3.12.0 + */ + +var Crop = { + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Crop#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + texture: null, + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Crop#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + frame: null, + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + * + * @name Phaser.GameObjects.Components.Crop#isCropped + * @type {boolean} + * @since 3.11.0 + */ + isCropped: false, + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * + * @method Phaser.GameObjects.Components.Crop#setCrop + * @since 3.11.0 + * + * @param {(number|Phaser.Geom.Rectangle)} [x] - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param {number} [y] - The y coordinate to start the crop from. + * @param {number} [width] - The width of the crop rectangle in pixels. + * @param {number} [height] - The height of the crop rectangle in pixels. + * + * @return {this} This Game Object instance. + */ + setCrop: function (x, y, width, height) + { + if (x === undefined) + { + this.isCropped = false; + } + else if (this.frame) + { + if (typeof x === 'number') + { + this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY); + } + else + { + var rect = x; + + this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY); + } + + this.isCropped = true; + } + + return this; + }, + + /** + * Internal method that returns a blank, well-formed crop object for use by a Game Object. + * + * @method Phaser.GameObjects.Components.Crop#resetCropObject + * @private + * @since 3.12.0 + * + * @return {object} The crop object. + */ + resetCropObject: function () + { + return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 }; + } + +}; + +module.exports = Crop; diff --git a/src/gameobjects/components/Depth.js b/src/gameobjects/components/Depth.js index ec47d257b..c85583b45 100644 --- a/src/gameobjects/components/Depth.js +++ b/src/gameobjects/components/Depth.js @@ -1,87 +1,87 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the depth of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.Depth - * @since 3.0.0 - */ - -var Depth = { - - /** - * Private internal value. Holds the depth of the Game Object. - * - * @name Phaser.GameObjects.Components.Depth#_depth - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - _depth: 0, - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * - * @name Phaser.GameObjects.Components.Depth#depth - * @type {number} - * @since 3.0.0 - */ - depth: { - - get: function () - { - return this._depth; - }, - - set: function (value) - { - this.scene.sys.queueDepthSort(); - this._depth = value; - } - - }, - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * - * @method Phaser.GameObjects.Components.Depth#setDepth - * @since 3.0.0 - * - * @param {integer} value - The depth of this Game Object. - * - * @return {this} This Game Object instance. - */ - setDepth: function (value) - { - if (value === undefined) { value = 0; } - - this.depth = value; - - return this; - } - -}; - -module.exports = Depth; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the depth of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Depth + * @since 3.0.0 + */ + +var Depth = { + + /** + * Private internal value. Holds the depth of the Game Object. + * + * @name Phaser.GameObjects.Components.Depth#_depth + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + _depth: 0, + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * + * @name Phaser.GameObjects.Components.Depth#depth + * @type {number} + * @since 3.0.0 + */ + depth: { + + get: function () + { + return this._depth; + }, + + set: function (value) + { + this.scene.sys.queueDepthSort(); + this._depth = value; + } + + }, + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * + * @method Phaser.GameObjects.Components.Depth#setDepth + * @since 3.0.0 + * + * @param {integer} value - The depth of this Game Object. + * + * @return {this} This Game Object instance. + */ + setDepth: function (value) + { + if (value === undefined) { value = 0; } + + this.depth = value; + + return this; + } + +}; + +module.exports = Depth; diff --git a/src/gameobjects/components/Flip.js b/src/gameobjects/components/Flip.js index 14441493d..58e01feeb 100644 --- a/src/gameobjects/components/Flip.js +++ b/src/gameobjects/components/Flip.js @@ -1,158 +1,158 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for visually flipping a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.Flip - * @since 3.0.0 - */ - -var Flip = { - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Components.Flip#flipX - * @type {boolean} - * @default false - * @since 3.0.0 - */ - flipX: false, - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Components.Flip#flipY - * @type {boolean} - * @default false - * @since 3.0.0 - */ - flipY: false, - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @method Phaser.GameObjects.Components.Flip#toggleFlipX - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - toggleFlipX: function () - { - this.flipX = !this.flipX; - - return this; - }, - - /** - * Toggles the vertical flipped state of this Game Object. - * - * @method Phaser.GameObjects.Components.Flip#toggleFlipY - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - toggleFlipY: function () - { - this.flipY = !this.flipY; - - return this; - }, - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @method Phaser.GameObjects.Components.Flip#setFlipX - * @since 3.0.0 - * - * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. - * - * @return {this} This Game Object instance. - */ - setFlipX: function (value) - { - this.flipX = value; - - return this; - }, - - /** - * Sets the vertical flipped state of this Game Object. - * - * @method Phaser.GameObjects.Components.Flip#setFlipY - * @since 3.0.0 - * - * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. - * - * @return {this} This Game Object instance. - */ - setFlipY: function (value) - { - this.flipY = value; - - return this; - }, - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @method Phaser.GameObjects.Components.Flip#setFlip - * @since 3.0.0 - * - * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * - * @return {this} This Game Object instance. - */ - setFlip: function (x, y) - { - this.flipX = x; - this.flipY = y; - - return this; - }, - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - * - * @method Phaser.GameObjects.Components.Flip#resetFlip - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - resetFlip: function () - { - this.flipX = false; - this.flipY = false; - - return this; - } - -}; - -module.exports = Flip; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for visually flipping a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Flip + * @since 3.0.0 + */ + +var Flip = { + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Components.Flip#flipX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + flipX: false, + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Components.Flip#flipY + * @type {boolean} + * @default false + * @since 3.0.0 + */ + flipY: false, + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @method Phaser.GameObjects.Components.Flip#toggleFlipX + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + toggleFlipX: function () + { + this.flipX = !this.flipX; + + return this; + }, + + /** + * Toggles the vertical flipped state of this Game Object. + * + * @method Phaser.GameObjects.Components.Flip#toggleFlipY + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + toggleFlipY: function () + { + this.flipY = !this.flipY; + + return this; + }, + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @method Phaser.GameObjects.Components.Flip#setFlipX + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Game Object instance. + */ + setFlipX: function (value) + { + this.flipX = value; + + return this; + }, + + /** + * Sets the vertical flipped state of this Game Object. + * + * @method Phaser.GameObjects.Components.Flip#setFlipY + * @since 3.0.0 + * + * @param {boolean} value - The flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Game Object instance. + */ + setFlipY: function (value) + { + this.flipY = value; + + return this; + }, + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @method Phaser.GameObjects.Components.Flip#setFlip + * @since 3.0.0 + * + * @param {boolean} x - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param {boolean} y - The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * + * @return {this} This Game Object instance. + */ + setFlip: function (x, y) + { + this.flipX = x; + this.flipY = y; + + return this; + }, + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + * + * @method Phaser.GameObjects.Components.Flip#resetFlip + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + resetFlip: function () + { + this.flipX = false; + this.flipY = false; + + return this; + } + +}; + +module.exports = Flip; diff --git a/src/gameobjects/components/GetBounds.js b/src/gameobjects/components/GetBounds.js index 89bbc3661..94e20988f 100644 --- a/src/gameobjects/components/GetBounds.js +++ b/src/gameobjects/components/GetBounds.js @@ -1,353 +1,353 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('../../geom/rectangle/Rectangle'); -var RotateAround = require('../../math/RotateAround'); -var Vector2 = require('../../math/Vector2'); - -/** - * Provides methods used for obtaining the bounds of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.GetBounds - * @since 3.0.0 - */ - -var GetBounds = { - - /** - * Processes the bounds output vector before returning it. - * - * @method Phaser.GameObjects.Components.GetBounds#prepareBoundsOutput - * @private - * @since 3.18.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} output - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - prepareBoundsOutput: function (output, includeParent) - { - if (includeParent === undefined) { includeParent = false; } - - if (this.rotation !== 0) - { - RotateAround(output, this.x, this.y, this.rotation); - } - - if (includeParent && this.parentContainer) - { - var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); - - parentMatrix.transformPoint(output.x, output.y, output); - } - - return output; - }, - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getCenter - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getCenter: function (output) - { - if (output === undefined) { output = new Vector2(); } - - output.x = this.x - (this.displayWidth * this.originX) + (this.displayWidth / 2); - output.y = this.y - (this.displayHeight * this.originY) + (this.displayHeight / 2); - - return output; - }, - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getTopLeft - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getTopLeft: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = this.x - (this.displayWidth * this.originX); - output.y = this.y - (this.displayHeight * this.originY); - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getTopCenter - * @since 3.18.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getTopCenter: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = (this.x - (this.displayWidth * this.originX)) + (this.displayWidth / 2); - output.y = this.y - (this.displayHeight * this.originY); - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getTopRight - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getTopRight: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; - output.y = this.y - (this.displayHeight * this.originY); - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getLeftCenter - * @since 3.18.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getLeftCenter: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = this.x - (this.displayWidth * this.originX); - output.y = (this.y - (this.displayHeight * this.originY)) + (this.displayHeight / 2); - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getRightCenter - * @since 3.18.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getRightCenter: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; - output.y = (this.y - (this.displayHeight * this.originY)) + (this.displayHeight / 2); - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getBottomLeft - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getBottomLeft: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = this.x - (this.displayWidth * this.originX); - output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getBottomCenter - * @since 3.18.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getBottomCenter: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = (this.x - (this.displayWidth * this.originX)) + (this.displayWidth / 2); - output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * - * @method Phaser.GameObjects.Components.GetBounds#getBottomRight - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [output,$return] - * - * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. - * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? - * - * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. - */ - getBottomRight: function (output, includeParent) - { - if (!output) { output = new Vector2(); } - - output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; - output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; - - return this.prepareBoundsOutput(output, includeParent); - }, - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * - * @method Phaser.GameObjects.Components.GetBounds#getBounds - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [output,$return] - * - * @param {(Phaser.Geom.Rectangle|object)} [output] - An object to store the values in. If not provided a new Rectangle will be created. - * - * @return {(Phaser.Geom.Rectangle|object)} The values stored in the output object. - */ - getBounds: function (output) - { - if (output === undefined) { output = new Rectangle(); } - - // We can use the output object to temporarily store the x/y coords in: - - var TLx, TLy, TRx, TRy, BLx, BLy, BRx, BRy; - - // Instead of doing a check if parent container is - // defined per corner we only do it once. - if (this.parentContainer) - { - var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); - - this.getTopLeft(output); - parentMatrix.transformPoint(output.x, output.y, output); - - TLx = output.x; - TLy = output.y; - - this.getTopRight(output); - parentMatrix.transformPoint(output.x, output.y, output); - - TRx = output.x; - TRy = output.y; - - this.getBottomLeft(output); - parentMatrix.transformPoint(output.x, output.y, output); - - BLx = output.x; - BLy = output.y; - - this.getBottomRight(output); - parentMatrix.transformPoint(output.x, output.y, output); - - BRx = output.x; - BRy = output.y; - } - else - { - this.getTopLeft(output); - - TLx = output.x; - TLy = output.y; - - this.getTopRight(output); - - TRx = output.x; - TRy = output.y; - - this.getBottomLeft(output); - - BLx = output.x; - BLy = output.y; - - this.getBottomRight(output); - - BRx = output.x; - BRy = output.y; - } - - output.x = Math.min(TLx, TRx, BLx, BRx); - output.y = Math.min(TLy, TRy, BLy, BRy); - output.width = Math.max(TLx, TRx, BLx, BRx) - output.x; - output.height = Math.max(TLy, TRy, BLy, BRy) - output.y; - - return output; - } - -}; - -module.exports = GetBounds; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('../../geom/rectangle/Rectangle'); +var RotateAround = require('../../math/RotateAround'); +var Vector2 = require('../../math/Vector2'); + +/** + * Provides methods used for obtaining the bounds of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.GetBounds + * @since 3.0.0 + */ + +var GetBounds = { + + /** + * Processes the bounds output vector before returning it. + * + * @method Phaser.GameObjects.Components.GetBounds#prepareBoundsOutput + * @private + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} output - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + prepareBoundsOutput: function (output, includeParent) + { + if (includeParent === undefined) { includeParent = false; } + + if (this.rotation !== 0) + { + RotateAround(output, this.x, this.y, this.rotation); + } + + if (includeParent && this.parentContainer) + { + var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); + + parentMatrix.transformPoint(output.x, output.y, output); + } + + return output; + }, + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getCenter + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getCenter: function (output) + { + if (output === undefined) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX) + (this.displayWidth / 2); + output.y = this.y - (this.displayHeight * this.originY) + (this.displayHeight / 2); + + return output; + }, + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getTopLeft + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getTopLeft: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX); + output.y = this.y - (this.displayHeight * this.originY); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getTopCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getTopCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + (this.displayWidth / 2); + output.y = this.y - (this.displayHeight * this.originY); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getTopRight + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getTopRight: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; + output.y = this.y - (this.displayHeight * this.originY); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getLeftCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getLeftCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX); + output.y = (this.y - (this.displayHeight * this.originY)) + (this.displayHeight / 2); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getRightCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getRightCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; + output.y = (this.y - (this.displayHeight * this.originY)) + (this.displayHeight / 2); + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getBottomLeft + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getBottomLeft: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = this.x - (this.displayWidth * this.originX); + output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getBottomCenter + * @since 3.18.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getBottomCenter: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + (this.displayWidth / 2); + output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * + * @method Phaser.GameObjects.Components.GetBounds#getBottomRight + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [output,$return] + * + * @param {(Phaser.Math.Vector2|object)} [output] - An object to store the values in. If not provided a new Vector2 will be created. + * @param {boolean} [includeParent=false] - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? + * + * @return {(Phaser.Math.Vector2|object)} The values stored in the output object. + */ + getBottomRight: function (output, includeParent) + { + if (!output) { output = new Vector2(); } + + output.x = (this.x - (this.displayWidth * this.originX)) + this.displayWidth; + output.y = (this.y - (this.displayHeight * this.originY)) + this.displayHeight; + + return this.prepareBoundsOutput(output, includeParent); + }, + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * + * @method Phaser.GameObjects.Components.GetBounds#getBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [output,$return] + * + * @param {(Phaser.Geom.Rectangle|object)} [output] - An object to store the values in. If not provided a new Rectangle will be created. + * + * @return {(Phaser.Geom.Rectangle|object)} The values stored in the output object. + */ + getBounds: function (output) + { + if (output === undefined) { output = new Rectangle(); } + + // We can use the output object to temporarily store the x/y coords in: + + var TLx, TLy, TRx, TRy, BLx, BLy, BRx, BRy; + + // Instead of doing a check if parent container is + // defined per corner we only do it once. + if (this.parentContainer) + { + var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); + + this.getTopLeft(output); + parentMatrix.transformPoint(output.x, output.y, output); + + TLx = output.x; + TLy = output.y; + + this.getTopRight(output); + parentMatrix.transformPoint(output.x, output.y, output); + + TRx = output.x; + TRy = output.y; + + this.getBottomLeft(output); + parentMatrix.transformPoint(output.x, output.y, output); + + BLx = output.x; + BLy = output.y; + + this.getBottomRight(output); + parentMatrix.transformPoint(output.x, output.y, output); + + BRx = output.x; + BRy = output.y; + } + else + { + this.getTopLeft(output); + + TLx = output.x; + TLy = output.y; + + this.getTopRight(output); + + TRx = output.x; + TRy = output.y; + + this.getBottomLeft(output); + + BLx = output.x; + BLy = output.y; + + this.getBottomRight(output); + + BRx = output.x; + BRy = output.y; + } + + output.x = Math.min(TLx, TRx, BLx, BRx); + output.y = Math.min(TLy, TRy, BLy, BRy); + output.width = Math.max(TLx, TRx, BLx, BRx) - output.x; + output.height = Math.max(TLy, TRy, BLy, BRy) - output.y; + + return output; + } + +}; + +module.exports = GetBounds; diff --git a/src/gameobjects/components/Mask.js b/src/gameobjects/components/Mask.js index 790dc521d..320019d86 100644 --- a/src/gameobjects/components/Mask.js +++ b/src/gameobjects/components/Mask.js @@ -1,141 +1,141 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BitmapMask = require('../../display/mask/BitmapMask'); -var GeometryMask = require('../../display/mask/GeometryMask'); - -/** - * Provides methods used for getting and setting the mask of a Game Object. - * - * @namespace Phaser.GameObjects.Components.Mask - * @since 3.0.0 - */ - -var Mask = { - - /** - * The Mask this Game Object is using during render. - * - * @name Phaser.GameObjects.Components.Mask#mask - * @type {Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask} - * @since 3.0.0 - */ - mask: null, - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * - * @method Phaser.GameObjects.Components.Mask#setMask - * @since 3.6.2 - * - * @param {Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask} mask - The mask this Game Object will use when rendering. - * - * @return {this} This Game Object instance. - */ - setMask: function (mask) - { - this.mask = mask; - - return this; - }, - - /** - * Clears the mask that this Game Object was using. - * - * @method Phaser.GameObjects.Components.Mask#clearMask - * @since 3.6.2 - * - * @param {boolean} [destroyMask=false] - Destroy the mask before clearing it? - * - * @return {this} This Game Object instance. - */ - clearMask: function (destroyMask) - { - if (destroyMask === undefined) { destroyMask = false; } - - if (destroyMask && this.mask) - { - this.mask.destroy(); - } - - this.mask = null; - - return this; - }, - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * - * @method Phaser.GameObjects.Components.Mask#createBitmapMask - * @since 3.6.2 - * - * @param {Phaser.GameObjects.GameObject} [renderable] - A renderable Game Object that uses a texture, such as a Sprite. - * - * @return {Phaser.Display.Masks.BitmapMask} This Bitmap Mask that was created. - */ - createBitmapMask: function (renderable) - { - if (renderable === undefined && (this.texture || this.shader)) - { - // eslint-disable-next-line consistent-this - renderable = this; - } - - return new BitmapMask(this.scene, renderable); - }, - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * - * @method Phaser.GameObjects.Components.Mask#createGeometryMask - * @since 3.6.2 - * - * @param {Phaser.GameObjects.Graphics} [graphics] - A Graphics Game Object. The geometry within it will be used as the mask. - * - * @return {Phaser.Display.Masks.GeometryMask} This Geometry Mask that was created. - */ - createGeometryMask: function (graphics) - { - if (graphics === undefined && this.type === 'Graphics') - { - // eslint-disable-next-line consistent-this - graphics = this; - } - - return new GeometryMask(this.scene, graphics); - } - -}; - -module.exports = Mask; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BitmapMask = require('../../display/mask/BitmapMask'); +var GeometryMask = require('../../display/mask/GeometryMask'); + +/** + * Provides methods used for getting and setting the mask of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Mask + * @since 3.0.0 + */ + +var Mask = { + + /** + * The Mask this Game Object is using during render. + * + * @name Phaser.GameObjects.Components.Mask#mask + * @type {Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask} + * @since 3.0.0 + */ + mask: null, + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * + * @method Phaser.GameObjects.Components.Mask#setMask + * @since 3.6.2 + * + * @param {Phaser.Display.Masks.BitmapMask|Phaser.Display.Masks.GeometryMask} mask - The mask this Game Object will use when rendering. + * + * @return {this} This Game Object instance. + */ + setMask: function (mask) + { + this.mask = mask; + + return this; + }, + + /** + * Clears the mask that this Game Object was using. + * + * @method Phaser.GameObjects.Components.Mask#clearMask + * @since 3.6.2 + * + * @param {boolean} [destroyMask=false] - Destroy the mask before clearing it? + * + * @return {this} This Game Object instance. + */ + clearMask: function (destroyMask) + { + if (destroyMask === undefined) { destroyMask = false; } + + if (destroyMask && this.mask) + { + this.mask.destroy(); + } + + this.mask = null; + + return this; + }, + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * + * @method Phaser.GameObjects.Components.Mask#createBitmapMask + * @since 3.6.2 + * + * @param {Phaser.GameObjects.GameObject} [renderable] - A renderable Game Object that uses a texture, such as a Sprite. + * + * @return {Phaser.Display.Masks.BitmapMask} This Bitmap Mask that was created. + */ + createBitmapMask: function (renderable) + { + if (renderable === undefined && (this.texture || this.shader)) + { + // eslint-disable-next-line consistent-this + renderable = this; + } + + return new BitmapMask(this.scene, renderable); + }, + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * + * @method Phaser.GameObjects.Components.Mask#createGeometryMask + * @since 3.6.2 + * + * @param {Phaser.GameObjects.Graphics} [graphics] - A Graphics Game Object. The geometry within it will be used as the mask. + * + * @return {Phaser.Display.Masks.GeometryMask} This Geometry Mask that was created. + */ + createGeometryMask: function (graphics) + { + if (graphics === undefined && this.type === 'Graphics') + { + // eslint-disable-next-line consistent-this + graphics = this; + } + + return new GeometryMask(this.scene, graphics); + } + +}; + +module.exports = Mask; diff --git a/src/gameobjects/components/Origin.js b/src/gameobjects/components/Origin.js index 6f724ca91..9631c78ac 100644 --- a/src/gameobjects/components/Origin.js +++ b/src/gameobjects/components/Origin.js @@ -1,197 +1,197 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for getting and setting the origin of a Game Object. - * Values are normalized, given in the range 0 to 1. - * Display values contain the calculated pixel values. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.Origin - * @since 3.0.0 - */ - -var Origin = { - - /** - * A property indicating that a Game Object has this component. - * - * @name Phaser.GameObjects.Components.Origin#_originComponent - * @type {boolean} - * @private - * @default true - * @since 3.2.0 - */ - _originComponent: true, - - /** - * 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.Components.Origin#originX - * @type {number} - * @default 0.5 - * @since 3.0.0 - */ - originX: 0.5, - - /** - * 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.Components.Origin#originY - * @type {number} - * @default 0.5 - * @since 3.0.0 - */ - originY: 0.5, - - // private + read only - _displayOriginX: 0, - _displayOriginY: 0, - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - * - * @name Phaser.GameObjects.Components.Origin#displayOriginX - * @type {number} - * @since 3.0.0 - */ - displayOriginX: { - - get: function () - { - return this._displayOriginX; - }, - - set: function (value) - { - this._displayOriginX = value; - this.originX = value / this.width; - } - - }, - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - * - * @name Phaser.GameObjects.Components.Origin#displayOriginY - * @type {number} - * @since 3.0.0 - */ - displayOriginY: { - - get: function () - { - return this._displayOriginY; - }, - - set: function (value) - { - this._displayOriginY = value; - this.originY = value / this.height; - } - - }, - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * - * @method Phaser.GameObjects.Components.Origin#setOrigin - * @since 3.0.0 - * - * @param {number} [x=0.5] - The horizontal origin value. - * @param {number} [y=x] - The vertical origin value. If not defined it will be set to the value of `x`. - * - * @return {this} This Game Object instance. - */ - setOrigin: function (x, y) - { - if (x === undefined) { x = 0.5; } - if (y === undefined) { y = x; } - - this.originX = x; - this.originY = y; - - return this.updateDisplayOrigin(); - }, - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - * - * @method Phaser.GameObjects.Components.Origin#setOriginFromFrame - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - setOriginFromFrame: function () - { - if (!this.frame || !this.frame.customPivot) - { - return this.setOrigin(); - } - else - { - this.originX = this.frame.pivotX; - this.originY = this.frame.pivotY; - } - - return this.updateDisplayOrigin(); - }, - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * - * @method Phaser.GameObjects.Components.Origin#setDisplayOrigin - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal display origin value. - * @param {number} [y=x] - The vertical display origin value. If not defined it will be set to the value of `x`. - * - * @return {this} This Game Object instance. - */ - setDisplayOrigin: function (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - - this.displayOriginX = x; - this.displayOriginY = y; - - return this; - }, - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - * - * @method Phaser.GameObjects.Components.Origin#updateDisplayOrigin - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - updateDisplayOrigin: function () - { - this._displayOriginX = this.originX * this.width; - this._displayOriginY = this.originY * this.height; - - return this; - } - -}; - -module.exports = Origin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the origin of a Game Object. + * Values are normalized, given in the range 0 to 1. + * Display values contain the calculated pixel values. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Origin + * @since 3.0.0 + */ + +var Origin = { + + /** + * A property indicating that a Game Object has this component. + * + * @name Phaser.GameObjects.Components.Origin#_originComponent + * @type {boolean} + * @private + * @default true + * @since 3.2.0 + */ + _originComponent: true, + + /** + * 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.Components.Origin#originX + * @type {number} + * @default 0.5 + * @since 3.0.0 + */ + originX: 0.5, + + /** + * 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.Components.Origin#originY + * @type {number} + * @default 0.5 + * @since 3.0.0 + */ + originY: 0.5, + + // private + read only + _displayOriginX: 0, + _displayOriginY: 0, + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + * + * @name Phaser.GameObjects.Components.Origin#displayOriginX + * @type {number} + * @since 3.0.0 + */ + displayOriginX: { + + get: function () + { + return this._displayOriginX; + }, + + set: function (value) + { + this._displayOriginX = value; + this.originX = value / this.width; + } + + }, + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + * + * @name Phaser.GameObjects.Components.Origin#displayOriginY + * @type {number} + * @since 3.0.0 + */ + displayOriginY: { + + get: function () + { + return this._displayOriginY; + }, + + set: function (value) + { + this._displayOriginY = value; + this.originY = value / this.height; + } + + }, + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * + * @method Phaser.GameObjects.Components.Origin#setOrigin + * @since 3.0.0 + * + * @param {number} [x=0.5] - The horizontal origin value. + * @param {number} [y=x] - The vertical origin value. If not defined it will be set to the value of `x`. + * + * @return {this} This Game Object instance. + */ + setOrigin: function (x, y) + { + if (x === undefined) { x = 0.5; } + if (y === undefined) { y = x; } + + this.originX = x; + this.originY = y; + + return this.updateDisplayOrigin(); + }, + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + * + * @method Phaser.GameObjects.Components.Origin#setOriginFromFrame + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + setOriginFromFrame: function () + { + if (!this.frame || !this.frame.customPivot) + { + return this.setOrigin(); + } + else + { + this.originX = this.frame.pivotX; + this.originY = this.frame.pivotY; + } + + return this.updateDisplayOrigin(); + }, + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * + * @method Phaser.GameObjects.Components.Origin#setDisplayOrigin + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal display origin value. + * @param {number} [y=x] - The vertical display origin value. If not defined it will be set to the value of `x`. + * + * @return {this} This Game Object instance. + */ + setDisplayOrigin: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.displayOriginX = x; + this.displayOriginY = y; + + return this; + }, + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + * + * @method Phaser.GameObjects.Components.Origin#updateDisplayOrigin + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + updateDisplayOrigin: function () + { + this._displayOriginX = this.originX * this.width; + this._displayOriginY = this.originY * this.height; + + return this; + } + +}; + +module.exports = Origin; diff --git a/src/gameobjects/components/PathFollower.js b/src/gameobjects/components/PathFollower.js index 0172a36e0..f5fdc1e8c 100644 --- a/src/gameobjects/components/PathFollower.js +++ b/src/gameobjects/components/PathFollower.js @@ -1,400 +1,400 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DegToRad = require('../../math/DegToRad'); -var GetBoolean = require('../../tweens/builders/GetBoolean'); -var GetValue = require('../../utils/object/GetValue'); -var TWEEN_CONST = require('../../tweens/tween/const'); -var Vector2 = require('../../math/Vector2'); - -/** - * Provides methods used for managing a Game Object following a Path. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.PathFollower - * @since 3.17.0 - */ - -var PathFollower = { - - /** - * The Path this PathFollower is following. It can only follow one Path at a time. - * - * @name Phaser.GameObjects.Components.PathFollower#path - * @type {Phaser.Curves.Path} - * @since 3.0.0 - */ - path: null, - - /** - * Should the PathFollower automatically rotate to point in the direction of the Path? - * - * @name Phaser.GameObjects.Components.PathFollower#rotateToPath - * @type {boolean} - * @default false - * @since 3.0.0 - */ - rotateToPath: false, - - /** - * If the PathFollower is rotating to match the Path (@see Phaser.GameObjects.PathFollower#rotateToPath) - * this value is added to the rotation value. This allows you to rotate objects to a path but control - * the angle of the rotation as well. - * - * @name Phaser.GameObjects.PathFollower#pathRotationOffset - * @type {number} - * @default 0 - * @since 3.0.0 - */ - pathRotationOffset: 0, - - /** - * An additional vector to add to the PathFollowers position, allowing you to offset it from the - * Path coordinates. - * - * @name Phaser.GameObjects.PathFollower#pathOffset - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - pathOffset: null, - - /** - * A Vector2 that stores the current point of the path the follower is on. - * - * @name Phaser.GameObjects.PathFollower#pathVector - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - pathVector: null, - - /** - * The Tween used for following the Path. - * - * @name Phaser.GameObjects.PathFollower#pathTween - * @type {Phaser.Tweens.Tween} - * @since 3.0.0 - */ - pathTween: null, - - /** - * Settings for the PathFollower. - * - * @name Phaser.GameObjects.PathFollower#pathConfig - * @type {?Phaser.Types.GameObjects.PathFollower.PathConfig} - * @default null - * @since 3.0.0 - */ - pathConfig: null, - - /** - * Records the direction of the follower so it can change direction. - * - * @name Phaser.GameObjects.PathFollower#_prevDirection - * @type {integer} - * @private - * @since 3.0.0 - */ - _prevDirection: TWEEN_CONST.PLAYING_FORWARD, - - /** - * Set the Path that this PathFollower should follow. - * - * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. - * - * @method Phaser.GameObjects.Components.PathFollower#setPath - * @since 3.0.0 - * - * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path at a time. - * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config] - Settings for the PathFollower. - * - * @return {this} This Game Object. - */ - setPath: function (path, config) - { - if (config === undefined) { config = this.pathConfig; } - - var tween = this.pathTween; - - if (tween && tween.isPlaying()) - { - tween.stop(); - } - - this.path = path; - - if (config) - { - this.startFollow(config); - } - - return this; - }, - - /** - * Set whether the PathFollower should automatically rotate to point in the direction of the Path. - * - * @method Phaser.GameObjects.Components.PathFollower#setRotateToPath - * @since 3.0.0 - * - * @param {boolean} value - Whether the PathFollower should automatically rotate to point in the direction of the Path. - * @param {number} [offset=0] - Rotation offset in degrees. - * - * @return {this} This Game Object. - */ - setRotateToPath: function (value, offset) - { - if (offset === undefined) { offset = 0; } - - this.rotateToPath = value; - - this.pathRotationOffset = offset; - - return this; - }, - - /** - * Is this PathFollower actively following a Path or not? - * - * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. - * - * @method Phaser.GameObjects.Components.PathFollower#isFollowing - * @since 3.0.0 - * - * @return {boolean} `true` is this PathFollower is actively following a Path, otherwise `false`. - */ - isFollowing: function () - { - var tween = this.pathTween; - - return (tween && tween.isPlaying()); - }, - - /** - * Starts this PathFollower following its given Path. - * - * @method Phaser.GameObjects.Components.PathFollower#startFollow - * @since 3.3.0 - * - * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config={}] - The duration of the follow, or a PathFollower config object. - * @param {number} [startAt=0] - Optional start position of the follow, between 0 and 1. - * - * @return {this} This Game Object. - */ - startFollow: function (config, startAt) - { - if (config === undefined) { config = {}; } - if (startAt === undefined) { startAt = 0; } - - var tween = this.pathTween; - - if (tween && tween.isPlaying()) - { - tween.stop(); - } - - if (typeof config === 'number') - { - config = { duration: config }; - } - - // Override in case they've been specified in the config - config.from = GetValue(config, 'from', 0); - config.to = GetValue(config, 'to', 1); - - var positionOnPath = GetBoolean(config, 'positionOnPath', false); - - this.rotateToPath = GetBoolean(config, 'rotateToPath', false); - this.pathRotationOffset = GetValue(config, 'rotationOffset', 0); - - // This works, but it's not an ideal way of doing it as the follower jumps position - var seek = GetValue(config, 'startAt', startAt); - - if (seek) - { - config.onStart = function (tween) - { - var tweenData = tween.data[0]; - tweenData.progress = seek; - tweenData.elapsed = tweenData.duration * seek; - var v = tweenData.ease(tweenData.progress); - tweenData.current = tweenData.start + ((tweenData.end - tweenData.start) * v); - tweenData.target[tweenData.key] = tweenData.current; - }; - } - - if (!this.pathOffset) - { - this.pathOffset = new Vector2(this.x, this.y); - } - - if (!this.pathVector) - { - this.pathVector = new Vector2(); - } - - this.pathTween = this.scene.sys.tweens.addCounter(config); - - // The starting point of the path, relative to this follower - this.path.getStartPoint(this.pathOffset); - - if (positionOnPath) - { - this.x = this.pathOffset.x; - this.y = this.pathOffset.y; - } - - this.pathOffset.x = this.x - this.pathOffset.x; - this.pathOffset.y = this.y - this.pathOffset.y; - - this._prevDirection = TWEEN_CONST.PLAYING_FORWARD; - - if (this.rotateToPath) - { - // Set the rotation now (in case the tween has a delay on it, etc) - var nextPoint = this.path.getPoint(0.1); - - this.rotation = Math.atan2(nextPoint.y - this.y, nextPoint.x - this.x) + DegToRad(this.pathRotationOffset); - } - - this.pathConfig = config; - - return this; - }, - - /** - * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the - * point on the Path at which you paused it. - * - * @method Phaser.GameObjects.Components.PathFollower#pauseFollow - * @since 3.3.0 - * - * @return {this} This Game Object. - */ - pauseFollow: function () - { - var tween = this.pathTween; - - if (tween && tween.isPlaying()) - { - tween.pause(); - } - - return this; - }, - - /** - * Resumes a previously paused PathFollower. - * - * If the PathFollower was not paused this has no effect. - * - * @method Phaser.GameObjects.Components.PathFollower#resumeFollow - * @since 3.3.0 - * - * @return {this} This Game Object. - */ - resumeFollow: function () - { - var tween = this.pathTween; - - if (tween && tween.isPaused()) - { - tween.resume(); - } - - return this; - }, - - /** - * Stops this PathFollower from following the path any longer. - * - * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. - * - * @method Phaser.GameObjects.Components.PathFollower#stopFollow - * @since 3.3.0 - * - * @return {this} This Game Object. - */ - stopFollow: function () - { - var tween = this.pathTween; - - if (tween && tween.isPlaying()) - { - tween.stop(); - } - - return this; - }, - - /** - * Internal update handler that advances this PathFollower along the path. - * - * Called automatically by the Scene step, should not typically be called directly. - * - * @method Phaser.GameObjects.Components.PathFollower#pathUpdate - * @since 3.17.0 - */ - pathUpdate: function () - { - var tween = this.pathTween; - - if (tween) - { - var tweenData = tween.data[0]; - var pathVector = this.pathVector; - - if (tweenData.state === TWEEN_CONST.COMPLETE) - { - this.path.getPoint(1, pathVector); - - pathVector.add(this.pathOffset); - - this.setPosition(pathVector.x, pathVector.y); - - return; - } - else if (tweenData.state !== TWEEN_CONST.PLAYING_FORWARD && tweenData.state !== TWEEN_CONST.PLAYING_BACKWARD) - { - // If delayed, etc then bail out - return; - } - - this.path.getPoint(tween.getValue(), pathVector); - - pathVector.add(this.pathOffset); - - var oldX = this.x; - var oldY = this.y; - - this.setPosition(pathVector.x, pathVector.y); - - var speedX = this.x - oldX; - var speedY = this.y - oldY; - - if (speedX === 0 && speedY === 0) - { - // Bail out early - return; - } - - if (tweenData.state !== this._prevDirection) - { - // We've changed direction, so don't do a rotate this frame - this._prevDirection = tweenData.state; - - return; - } - - if (this.rotateToPath) - { - this.rotation = Math.atan2(speedY, speedX) + DegToRad(this.pathRotationOffset); - } - } - } - -}; - -module.exports = PathFollower; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DegToRad = require('../../math/DegToRad'); +var GetBoolean = require('../../tweens/builders/GetBoolean'); +var GetValue = require('../../utils/object/GetValue'); +var TWEEN_CONST = require('../../tweens/tween/const'); +var Vector2 = require('../../math/Vector2'); + +/** + * Provides methods used for managing a Game Object following a Path. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.PathFollower + * @since 3.17.0 + */ + +var PathFollower = { + + /** + * The Path this PathFollower is following. It can only follow one Path at a time. + * + * @name Phaser.GameObjects.Components.PathFollower#path + * @type {Phaser.Curves.Path} + * @since 3.0.0 + */ + path: null, + + /** + * Should the PathFollower automatically rotate to point in the direction of the Path? + * + * @name Phaser.GameObjects.Components.PathFollower#rotateToPath + * @type {boolean} + * @default false + * @since 3.0.0 + */ + rotateToPath: false, + + /** + * If the PathFollower is rotating to match the Path (@see Phaser.GameObjects.PathFollower#rotateToPath) + * this value is added to the rotation value. This allows you to rotate objects to a path but control + * the angle of the rotation as well. + * + * @name Phaser.GameObjects.PathFollower#pathRotationOffset + * @type {number} + * @default 0 + * @since 3.0.0 + */ + pathRotationOffset: 0, + + /** + * An additional vector to add to the PathFollowers position, allowing you to offset it from the + * Path coordinates. + * + * @name Phaser.GameObjects.PathFollower#pathOffset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + pathOffset: null, + + /** + * A Vector2 that stores the current point of the path the follower is on. + * + * @name Phaser.GameObjects.PathFollower#pathVector + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + pathVector: null, + + /** + * The Tween used for following the Path. + * + * @name Phaser.GameObjects.PathFollower#pathTween + * @type {Phaser.Tweens.Tween} + * @since 3.0.0 + */ + pathTween: null, + + /** + * Settings for the PathFollower. + * + * @name Phaser.GameObjects.PathFollower#pathConfig + * @type {?Phaser.Types.GameObjects.PathFollower.PathConfig} + * @default null + * @since 3.0.0 + */ + pathConfig: null, + + /** + * Records the direction of the follower so it can change direction. + * + * @name Phaser.GameObjects.PathFollower#_prevDirection + * @type {integer} + * @private + * @since 3.0.0 + */ + _prevDirection: TWEEN_CONST.PLAYING_FORWARD, + + /** + * Set the Path that this PathFollower should follow. + * + * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. + * + * @method Phaser.GameObjects.Components.PathFollower#setPath + * @since 3.0.0 + * + * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path at a time. + * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config] - Settings for the PathFollower. + * + * @return {this} This Game Object. + */ + setPath: function (path, config) + { + if (config === undefined) { config = this.pathConfig; } + + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.stop(); + } + + this.path = path; + + if (config) + { + this.startFollow(config); + } + + return this; + }, + + /** + * Set whether the PathFollower should automatically rotate to point in the direction of the Path. + * + * @method Phaser.GameObjects.Components.PathFollower#setRotateToPath + * @since 3.0.0 + * + * @param {boolean} value - Whether the PathFollower should automatically rotate to point in the direction of the Path. + * @param {number} [offset=0] - Rotation offset in degrees. + * + * @return {this} This Game Object. + */ + setRotateToPath: function (value, offset) + { + if (offset === undefined) { offset = 0; } + + this.rotateToPath = value; + + this.pathRotationOffset = offset; + + return this; + }, + + /** + * Is this PathFollower actively following a Path or not? + * + * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. + * + * @method Phaser.GameObjects.Components.PathFollower#isFollowing + * @since 3.0.0 + * + * @return {boolean} `true` is this PathFollower is actively following a Path, otherwise `false`. + */ + isFollowing: function () + { + var tween = this.pathTween; + + return (tween && tween.isPlaying()); + }, + + /** + * Starts this PathFollower following its given Path. + * + * @method Phaser.GameObjects.Components.PathFollower#startFollow + * @since 3.3.0 + * + * @param {(number|Phaser.Types.GameObjects.PathFollower.PathConfig|Phaser.Types.Tweens.NumberTweenBuilderConfig)} [config={}] - The duration of the follow, or a PathFollower config object. + * @param {number} [startAt=0] - Optional start position of the follow, between 0 and 1. + * + * @return {this} This Game Object. + */ + startFollow: function (config, startAt) + { + if (config === undefined) { config = {}; } + if (startAt === undefined) { startAt = 0; } + + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.stop(); + } + + if (typeof config === 'number') + { + config = { duration: config }; + } + + // Override in case they've been specified in the config + config.from = GetValue(config, 'from', 0); + config.to = GetValue(config, 'to', 1); + + var positionOnPath = GetBoolean(config, 'positionOnPath', false); + + this.rotateToPath = GetBoolean(config, 'rotateToPath', false); + this.pathRotationOffset = GetValue(config, 'rotationOffset', 0); + + // This works, but it's not an ideal way of doing it as the follower jumps position + var seek = GetValue(config, 'startAt', startAt); + + if (seek) + { + config.onStart = function (tween) + { + var tweenData = tween.data[0]; + tweenData.progress = seek; + tweenData.elapsed = tweenData.duration * seek; + var v = tweenData.ease(tweenData.progress); + tweenData.current = tweenData.start + ((tweenData.end - tweenData.start) * v); + tweenData.target[tweenData.key] = tweenData.current; + }; + } + + if (!this.pathOffset) + { + this.pathOffset = new Vector2(this.x, this.y); + } + + if (!this.pathVector) + { + this.pathVector = new Vector2(); + } + + this.pathTween = this.scene.sys.tweens.addCounter(config); + + // The starting point of the path, relative to this follower + this.path.getStartPoint(this.pathOffset); + + if (positionOnPath) + { + this.x = this.pathOffset.x; + this.y = this.pathOffset.y; + } + + this.pathOffset.x = this.x - this.pathOffset.x; + this.pathOffset.y = this.y - this.pathOffset.y; + + this._prevDirection = TWEEN_CONST.PLAYING_FORWARD; + + if (this.rotateToPath) + { + // Set the rotation now (in case the tween has a delay on it, etc) + var nextPoint = this.path.getPoint(0.1); + + this.rotation = Math.atan2(nextPoint.y - this.y, nextPoint.x - this.x) + DegToRad(this.pathRotationOffset); + } + + this.pathConfig = config; + + return this; + }, + + /** + * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the + * point on the Path at which you paused it. + * + * @method Phaser.GameObjects.Components.PathFollower#pauseFollow + * @since 3.3.0 + * + * @return {this} This Game Object. + */ + pauseFollow: function () + { + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.pause(); + } + + return this; + }, + + /** + * Resumes a previously paused PathFollower. + * + * If the PathFollower was not paused this has no effect. + * + * @method Phaser.GameObjects.Components.PathFollower#resumeFollow + * @since 3.3.0 + * + * @return {this} This Game Object. + */ + resumeFollow: function () + { + var tween = this.pathTween; + + if (tween && tween.isPaused()) + { + tween.resume(); + } + + return this; + }, + + /** + * Stops this PathFollower from following the path any longer. + * + * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. + * + * @method Phaser.GameObjects.Components.PathFollower#stopFollow + * @since 3.3.0 + * + * @return {this} This Game Object. + */ + stopFollow: function () + { + var tween = this.pathTween; + + if (tween && tween.isPlaying()) + { + tween.stop(); + } + + return this; + }, + + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + * + * @method Phaser.GameObjects.Components.PathFollower#pathUpdate + * @since 3.17.0 + */ + pathUpdate: function () + { + var tween = this.pathTween; + + if (tween) + { + var tweenData = tween.data[0]; + var pathVector = this.pathVector; + + if (tweenData.state === TWEEN_CONST.COMPLETE) + { + this.path.getPoint(1, pathVector); + + pathVector.add(this.pathOffset); + + this.setPosition(pathVector.x, pathVector.y); + + return; + } + else if (tweenData.state !== TWEEN_CONST.PLAYING_FORWARD && tweenData.state !== TWEEN_CONST.PLAYING_BACKWARD) + { + // If delayed, etc then bail out + return; + } + + this.path.getPoint(tween.getValue(), pathVector); + + pathVector.add(this.pathOffset); + + var oldX = this.x; + var oldY = this.y; + + this.setPosition(pathVector.x, pathVector.y); + + var speedX = this.x - oldX; + var speedY = this.y - oldY; + + if (speedX === 0 && speedY === 0) + { + // Bail out early + return; + } + + if (tweenData.state !== this._prevDirection) + { + // We've changed direction, so don't do a rotate this frame + this._prevDirection = tweenData.state; + + return; + } + + if (this.rotateToPath) + { + this.rotation = Math.atan2(speedY, speedX) + DegToRad(this.pathRotationOffset); + } + } + } + +}; + +module.exports = PathFollower; diff --git a/src/gameobjects/components/Pipeline.js b/src/gameobjects/components/Pipeline.js index 4b58cd98e..fb72aab72 100644 --- a/src/gameobjects/components/Pipeline.js +++ b/src/gameobjects/components/Pipeline.js @@ -1,123 +1,123 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the WebGL rendering pipeline of a Game Object. - * - * @namespace Phaser.GameObjects.Components.Pipeline - * @webglOnly - * @since 3.0.0 - */ - -var Pipeline = { - - /** - * The initial WebGL pipeline of this Game Object. - * - * @name Phaser.GameObjects.Components.Pipeline#defaultPipeline - * @type {Phaser.Renderer.WebGL.WebGLPipeline} - * @default null - * @webglOnly - * @since 3.0.0 - */ - defaultPipeline: null, - - /** - * The current WebGL pipeline of this Game Object. - * - * @name Phaser.GameObjects.Components.Pipeline#pipeline - * @type {Phaser.Renderer.WebGL.WebGLPipeline} - * @default null - * @webglOnly - * @since 3.0.0 - */ - pipeline: null, - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * - * @method Phaser.GameObjects.Components.Pipeline#initPipeline - * @webglOnly - * @since 3.0.0 - * - * @param {string} [pipelineName=TextureTintPipeline] - The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. - * - * @return {boolean} `true` if the pipeline was set successfully, otherwise `false`. - */ - initPipeline: function (pipelineName) - { - if (pipelineName === undefined) { pipelineName = 'TextureTintPipeline'; } - - var renderer = this.scene.sys.game.renderer; - - if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) - { - this.defaultPipeline = renderer.getPipeline(pipelineName); - this.pipeline = this.defaultPipeline; - - return true; - } - - return false; - }, - - /** - * Sets the active WebGL Pipeline of this Game Object. - * - * @method Phaser.GameObjects.Components.Pipeline#setPipeline - * @webglOnly - * @since 3.0.0 - * - * @param {string} pipelineName - The name of the pipeline to set on this Game Object. - * - * @return {this} This Game Object instance. - */ - setPipeline: function (pipelineName) - { - var renderer = this.scene.sys.game.renderer; - - if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) - { - this.pipeline = renderer.getPipeline(pipelineName); - } - - return this; - }, - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - * - * @method Phaser.GameObjects.Components.Pipeline#resetPipeline - * @webglOnly - * @since 3.0.0 - * - * @return {boolean} `true` if the pipeline was set successfully, otherwise `false`. - */ - resetPipeline: function () - { - this.pipeline = this.defaultPipeline; - - return (this.pipeline !== null); - }, - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - * - * @method Phaser.GameObjects.Components.Pipeline#getPipelineName - * @webglOnly - * @since 3.0.0 - * - * @return {string} The string-based name of the pipeline being used by this Game Object. - */ - getPipelineName: function () - { - return this.pipeline.name; - } - -}; - -module.exports = Pipeline; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the WebGL rendering pipeline of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Pipeline + * @webglOnly + * @since 3.0.0 + */ + +var Pipeline = { + + /** + * The initial WebGL pipeline of this Game Object. + * + * @name Phaser.GameObjects.Components.Pipeline#defaultPipeline + * @type {Phaser.Renderer.WebGL.WebGLPipeline} + * @default null + * @webglOnly + * @since 3.0.0 + */ + defaultPipeline: null, + + /** + * The current WebGL pipeline of this Game Object. + * + * @name Phaser.GameObjects.Components.Pipeline#pipeline + * @type {Phaser.Renderer.WebGL.WebGLPipeline} + * @default null + * @webglOnly + * @since 3.0.0 + */ + pipeline: null, + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * + * @method Phaser.GameObjects.Components.Pipeline#initPipeline + * @webglOnly + * @since 3.0.0 + * + * @param {string} [pipelineName=TextureTintPipeline] - The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. + * + * @return {boolean} `true` if the pipeline was set successfully, otherwise `false`. + */ + initPipeline: function (pipelineName) + { + if (pipelineName === undefined) { pipelineName = 'TextureTintPipeline'; } + + var renderer = this.scene.sys.game.renderer; + + if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) + { + this.defaultPipeline = renderer.getPipeline(pipelineName); + this.pipeline = this.defaultPipeline; + + return true; + } + + return false; + }, + + /** + * Sets the active WebGL Pipeline of this Game Object. + * + * @method Phaser.GameObjects.Components.Pipeline#setPipeline + * @webglOnly + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline to set on this Game Object. + * + * @return {this} This Game Object instance. + */ + setPipeline: function (pipelineName) + { + var renderer = this.scene.sys.game.renderer; + + if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) + { + this.pipeline = renderer.getPipeline(pipelineName); + } + + return this; + }, + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + * + * @method Phaser.GameObjects.Components.Pipeline#resetPipeline + * @webglOnly + * @since 3.0.0 + * + * @return {boolean} `true` if the pipeline was set successfully, otherwise `false`. + */ + resetPipeline: function () + { + this.pipeline = this.defaultPipeline; + + return (this.pipeline !== null); + }, + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + * + * @method Phaser.GameObjects.Components.Pipeline#getPipelineName + * @webglOnly + * @since 3.0.0 + * + * @return {string} The string-based name of the pipeline being used by this Game Object. + */ + getPipelineName: function () + { + return this.pipeline.name; + } + +}; + +module.exports = Pipeline; diff --git a/src/gameobjects/components/ScrollFactor.js b/src/gameobjects/components/ScrollFactor.js index 396862727..a6a3bd145 100644 --- a/src/gameobjects/components/ScrollFactor.js +++ b/src/gameobjects/components/ScrollFactor.js @@ -1,101 +1,101 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for getting and setting the Scroll Factor of a Game Object. - * - * @namespace Phaser.GameObjects.Components.ScrollFactor - * @since 3.0.0 - */ - -var ScrollFactor = { - - /** - * 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 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.Components.ScrollFactor#scrollFactorX - * @type {number} - * @default 1 - * @since 3.0.0 - */ - scrollFactorX: 1, - - /** - * 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 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.Components.ScrollFactor#scrollFactorY - * @type {number} - * @default 1 - * @since 3.0.0 - */ - scrollFactorY: 1, - - /** - * Sets the 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 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.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. - */ - setScrollFactor: function (x, y) - { - if (y === undefined) { y = x; } - - this.scrollFactorX = x; - this.scrollFactorY = y; - - return this; - } - -}; - -module.exports = ScrollFactor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the Scroll Factor of a Game Object. + * + * @namespace Phaser.GameObjects.Components.ScrollFactor + * @since 3.0.0 + */ + +var ScrollFactor = { + + /** + * 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 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.Components.ScrollFactor#scrollFactorX + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scrollFactorX: 1, + + /** + * 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 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.Components.ScrollFactor#scrollFactorY + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scrollFactorY: 1, + + /** + * Sets the 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 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.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. + */ + setScrollFactor: function (x, y) + { + if (y === undefined) { y = x; } + + this.scrollFactorX = x; + this.scrollFactorY = y; + + return this; + } + +}; + +module.exports = ScrollFactor; diff --git a/src/gameobjects/components/Size.js b/src/gameobjects/components/Size.js index 3f8aefb56..d2d5c463d 100644 --- a/src/gameobjects/components/Size.js +++ b/src/gameobjects/components/Size.js @@ -1,181 +1,181 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for getting and setting the size of a Game Object. - * - * @namespace Phaser.GameObjects.Components.Size - * @since 3.0.0 - */ - -var Size = { - - /** - * A property indicating that a Game Object has this component. - * - * @name Phaser.GameObjects.Components.Size#_sizeComponent - * @type {boolean} - * @private - * @default true - * @since 3.2.0 - */ - _sizeComponent: true, - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - * - * @name Phaser.GameObjects.Components.Size#width - * @type {number} - * @since 3.0.0 - */ - width: 0, - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - * - * @name Phaser.GameObjects.Components.Size#height - * @type {number} - * @since 3.0.0 - */ - height: 0, - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - * - * @name Phaser.GameObjects.Components.Size#displayWidth - * @type {number} - * @since 3.0.0 - */ - displayWidth: { - - get: function () - { - return Math.abs(this.scaleX * this.frame.realWidth); - }, - - set: function (value) - { - this.scaleX = value / this.frame.realWidth; - } - - }, - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - * - * @name Phaser.GameObjects.Components.Size#displayHeight - * @type {number} - * @since 3.0.0 - */ - displayHeight: { - - get: function () - { - return Math.abs(this.scaleY * this.frame.realHeight); - }, - - set: function (value) - { - this.scaleY = value / this.frame.realHeight; - } - - }, - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * - * @method Phaser.GameObjects.Components.Size#setSizeToFrame - * @since 3.0.0 - * - * @param {Phaser.Textures.Frame} frame - The frame to base the size of this Game Object on. - * - * @return {this} This Game Object instance. - */ - setSizeToFrame: function (frame) - { - if (frame === undefined) { frame = this.frame; } - - this.width = frame.realWidth; - this.height = frame.realHeight; - - return this; - }, - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * - * @method Phaser.GameObjects.Components.Size#setSize - * @since 3.0.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * - * @return {this} This Game Object instance. - */ - setSize: function (width, height) - { - this.width = width; - this.height = height; - - return this; - }, - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * - * @method Phaser.GameObjects.Components.Size#setDisplaySize - * @since 3.0.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * - * @return {this} This Game Object instance. - */ - setDisplaySize: function (width, height) - { - this.displayWidth = width; - this.displayHeight = height; - - return this; - } - -}; - -module.exports = Size; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for getting and setting the size of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Size + * @since 3.0.0 + */ + +var Size = { + + /** + * A property indicating that a Game Object has this component. + * + * @name Phaser.GameObjects.Components.Size#_sizeComponent + * @type {boolean} + * @private + * @default true + * @since 3.2.0 + */ + _sizeComponent: true, + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + * + * @name Phaser.GameObjects.Components.Size#width + * @type {number} + * @since 3.0.0 + */ + width: 0, + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + * + * @name Phaser.GameObjects.Components.Size#height + * @type {number} + * @since 3.0.0 + */ + height: 0, + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.Size#displayWidth + * @type {number} + * @since 3.0.0 + */ + displayWidth: { + + get: function () + { + return Math.abs(this.scaleX * this.frame.realWidth); + }, + + set: function (value) + { + this.scaleX = value / this.frame.realWidth; + } + + }, + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + * + * @name Phaser.GameObjects.Components.Size#displayHeight + * @type {number} + * @since 3.0.0 + */ + displayHeight: { + + get: function () + { + return Math.abs(this.scaleY * this.frame.realHeight); + }, + + set: function (value) + { + this.scaleY = value / this.frame.realHeight; + } + + }, + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * + * @method Phaser.GameObjects.Components.Size#setSizeToFrame + * @since 3.0.0 + * + * @param {Phaser.Textures.Frame} frame - The frame to base the size of this Game Object on. + * + * @return {this} This Game Object instance. + */ + setSizeToFrame: function (frame) + { + if (frame === undefined) { frame = this.frame; } + + this.width = frame.realWidth; + this.height = frame.realHeight; + + return this; + }, + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * + * @method Phaser.GameObjects.Components.Size#setSize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + this.width = width; + this.height = height; + + return this; + }, + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * + * @method Phaser.GameObjects.Components.Size#setDisplaySize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setDisplaySize: function (width, height) + { + this.displayWidth = width; + this.displayHeight = height; + + return this; + } + +}; + +module.exports = Size; diff --git a/src/gameobjects/components/Texture.js b/src/gameobjects/components/Texture.js index b0978a2fb..29a280ae7 100644 --- a/src/gameobjects/components/Texture.js +++ b/src/gameobjects/components/Texture.js @@ -1,124 +1,124 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// bitmask flag for GameObject.renderMask -var _FLAG = 8; // 1000 - -/** - * Provides methods used for getting and setting the texture of a Game Object. - * - * @namespace Phaser.GameObjects.Components.Texture - * @since 3.0.0 - */ - -var Texture = { - - /** - * The Texture this Game Object is using to render with. - * - * @name Phaser.GameObjects.Components.Texture#texture - * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} - * @since 3.0.0 - */ - texture: null, - - /** - * The Texture Frame this Game Object is using to render with. - * - * @name Phaser.GameObjects.Components.Texture#frame - * @type {Phaser.Textures.Frame} - * @since 3.0.0 - */ - frame: null, - - /** - * Internal flag. Not to be set by this Game Object. - * - * @name Phaser.GameObjects.Components.Texture#isCropped - * @type {boolean} - * @private - * @since 3.11.0 - */ - isCropped: false, - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * @method Phaser.GameObjects.Components.Texture#setTexture - * @since 3.0.0 - * - * @param {(string|Phaser.Textures.Texture)} key - The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * - * @return {this} This Game Object instance. - */ - setTexture: function (key, frame) - { - this.texture = this.scene.sys.textures.get(key); - - return this.setFrame(frame); - }, - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * - * @method Phaser.GameObjects.Components.Texture#setFrame - * @since 3.0.0 - * - * @param {(string|integer)} frame - The name or index of the frame within the Texture. - * @param {boolean} [updateSize=true] - Should this call adjust the size of the Game Object? - * @param {boolean} [updateOrigin=true] - Should this call adjust the origin of the Game Object? - * - * @return {this} This Game Object instance. - */ - setFrame: function (frame, updateSize, updateOrigin) - { - if (updateSize === undefined) { updateSize = true; } - if (updateOrigin === undefined) { updateOrigin = true; } - - this.frame = this.texture.get(frame); - - if (!this.frame.cutWidth || !this.frame.cutHeight) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - - if (this._sizeComponent && updateSize) - { - this.setSizeToFrame(); - } - - if (this._originComponent && updateOrigin) - { - if (this.frame.customPivot) - { - this.setOrigin(this.frame.pivotX, this.frame.pivotY); - } - else - { - this.updateDisplayOrigin(); - } - } - - return this; - } - -}; - -module.exports = Texture; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// bitmask flag for GameObject.renderMask +var _FLAG = 8; // 1000 + +/** + * Provides methods used for getting and setting the texture of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Texture + * @since 3.0.0 + */ + +var Texture = { + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Texture#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + texture: null, + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.Texture#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + frame: null, + + /** + * Internal flag. Not to be set by this Game Object. + * + * @name Phaser.GameObjects.Components.Texture#isCropped + * @type {boolean} + * @private + * @since 3.11.0 + */ + isCropped: false, + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.Components.Texture#setTexture + * @since 3.0.0 + * + * @param {(string|Phaser.Textures.Texture)} key - The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setTexture: function (key, frame) + { + this.texture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * + * @method Phaser.GameObjects.Components.Texture#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * @param {boolean} [updateSize=true] - Should this call adjust the size of the Game Object? + * @param {boolean} [updateOrigin=true] - Should this call adjust the origin of the Game Object? + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame, updateSize, updateOrigin) + { + if (updateSize === undefined) { updateSize = true; } + if (updateOrigin === undefined) { updateOrigin = true; } + + this.frame = this.texture.get(frame); + + if (!this.frame.cutWidth || !this.frame.cutHeight) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + if (this._sizeComponent && updateSize) + { + this.setSizeToFrame(); + } + + if (this._originComponent && updateOrigin) + { + if (this.frame.customPivot) + { + this.setOrigin(this.frame.pivotX, this.frame.pivotY); + } + else + { + this.updateDisplayOrigin(); + } + } + + return this; + } + +}; + +module.exports = Texture; diff --git a/src/gameobjects/components/TextureCrop.js b/src/gameobjects/components/TextureCrop.js index ba7361786..96cc87c77 100644 --- a/src/gameobjects/components/TextureCrop.js +++ b/src/gameobjects/components/TextureCrop.js @@ -1,202 +1,202 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// bitmask flag for GameObject.renderMask -var _FLAG = 8; // 1000 - -/** - * Provides methods used for getting and setting the texture of a Game Object. - * - * @namespace Phaser.GameObjects.Components.TextureCrop - * @since 3.0.0 - */ - -var TextureCrop = { - - /** - * The Texture this Game Object is using to render with. - * - * @name Phaser.GameObjects.Components.TextureCrop#texture - * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} - * @since 3.0.0 - */ - texture: null, - - /** - * The Texture Frame this Game Object is using to render with. - * - * @name Phaser.GameObjects.Components.TextureCrop#frame - * @type {Phaser.Textures.Frame} - * @since 3.0.0 - */ - frame: null, - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - * - * @name Phaser.GameObjects.Components.TextureCrop#isCropped - * @type {boolean} - * @since 3.11.0 - */ - isCropped: false, - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * - * @method Phaser.GameObjects.Components.TextureCrop#setCrop - * @since 3.11.0 - * - * @param {(number|Phaser.Geom.Rectangle)} [x] - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param {number} [y] - The y coordinate to start the crop from. - * @param {number} [width] - The width of the crop rectangle in pixels. - * @param {number} [height] - The height of the crop rectangle in pixels. - * - * @return {this} This Game Object instance. - */ - setCrop: function (x, y, width, height) - { - if (x === undefined) - { - this.isCropped = false; - } - else if (this.frame) - { - if (typeof x === 'number') - { - this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY); - } - else - { - var rect = x; - - this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY); - } - - this.isCropped = true; - } - - return this; - }, - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * @method Phaser.GameObjects.Components.TextureCrop#setTexture - * @since 3.0.0 - * - * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * - * @return {this} This Game Object instance. - */ - setTexture: function (key, frame) - { - this.texture = this.scene.sys.textures.get(key); - - return this.setFrame(frame); - }, - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * - * @method Phaser.GameObjects.Components.TextureCrop#setFrame - * @since 3.0.0 - * - * @param {(string|integer)} frame - The name or index of the frame within the Texture. - * @param {boolean} [updateSize=true] - Should this call adjust the size of the Game Object? - * @param {boolean} [updateOrigin=true] - Should this call adjust the origin of the Game Object? - * - * @return {this} This Game Object instance. - */ - setFrame: function (frame, updateSize, updateOrigin) - { - if (updateSize === undefined) { updateSize = true; } - if (updateOrigin === undefined) { updateOrigin = true; } - - this.frame = this.texture.get(frame); - - if (!this.frame.cutWidth || !this.frame.cutHeight) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - - if (this._sizeComponent && updateSize) - { - this.setSizeToFrame(); - } - - if (this._originComponent && updateOrigin) - { - if (this.frame.customPivot) - { - this.setOrigin(this.frame.pivotX, this.frame.pivotY); - } - else - { - this.updateDisplayOrigin(); - } - } - - if (this.isCropped) - { - this.frame.updateCropUVs(this._crop, this.flipX, this.flipY); - } - - return this; - }, - - /** - * Internal method that returns a blank, well-formed crop object for use by a Game Object. - * - * @method Phaser.GameObjects.Components.TextureCrop#resetCropObject - * @private - * @since 3.12.0 - * - * @return {object} The crop object. - */ - resetCropObject: function () - { - return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 }; - } - -}; - -module.exports = TextureCrop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// bitmask flag for GameObject.renderMask +var _FLAG = 8; // 1000 + +/** + * Provides methods used for getting and setting the texture of a Game Object. + * + * @namespace Phaser.GameObjects.Components.TextureCrop + * @since 3.0.0 + */ + +var TextureCrop = { + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.TextureCrop#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + texture: null, + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.Components.TextureCrop#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + frame: null, + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + * + * @name Phaser.GameObjects.Components.TextureCrop#isCropped + * @type {boolean} + * @since 3.11.0 + */ + isCropped: false, + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * + * @method Phaser.GameObjects.Components.TextureCrop#setCrop + * @since 3.11.0 + * + * @param {(number|Phaser.Geom.Rectangle)} [x] - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param {number} [y] - The y coordinate to start the crop from. + * @param {number} [width] - The width of the crop rectangle in pixels. + * @param {number} [height] - The height of the crop rectangle in pixels. + * + * @return {this} This Game Object instance. + */ + setCrop: function (x, y, width, height) + { + if (x === undefined) + { + this.isCropped = false; + } + else if (this.frame) + { + if (typeof x === 'number') + { + this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY); + } + else + { + var rect = x; + + this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY); + } + + this.isCropped = true; + } + + return this; + }, + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.Components.TextureCrop#setTexture + * @since 3.0.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setTexture: function (key, frame) + { + this.texture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * + * @method Phaser.GameObjects.Components.TextureCrop#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * @param {boolean} [updateSize=true] - Should this call adjust the size of the Game Object? + * @param {boolean} [updateOrigin=true] - Should this call adjust the origin of the Game Object? + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame, updateSize, updateOrigin) + { + if (updateSize === undefined) { updateSize = true; } + if (updateOrigin === undefined) { updateOrigin = true; } + + this.frame = this.texture.get(frame); + + if (!this.frame.cutWidth || !this.frame.cutHeight) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + if (this._sizeComponent && updateSize) + { + this.setSizeToFrame(); + } + + if (this._originComponent && updateOrigin) + { + if (this.frame.customPivot) + { + this.setOrigin(this.frame.pivotX, this.frame.pivotY); + } + else + { + this.updateDisplayOrigin(); + } + } + + if (this.isCropped) + { + this.frame.updateCropUVs(this._crop, this.flipX, this.flipY); + } + + return this; + }, + + /** + * Internal method that returns a blank, well-formed crop object for use by a Game Object. + * + * @method Phaser.GameObjects.Components.TextureCrop#resetCropObject + * @private + * @since 3.12.0 + * + * @return {object} The crop object. + */ + resetCropObject: function () + { + return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 }; + } + +}; + +module.exports = TextureCrop; diff --git a/src/gameobjects/components/Tint.js b/src/gameobjects/components/Tint.js index f790064bc..27ac35304 100644 --- a/src/gameobjects/components/Tint.js +++ b/src/gameobjects/components/Tint.js @@ -1,334 +1,334 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @function GetColor - * @since 3.0.0 - * @private - */ -var GetColor = function (value) -{ - return (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); -}; - -/** - * Provides methods used for setting the tint of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.Tint - * @webglOnly - * @since 3.0.0 - */ - -var Tint = { - - /** - * Private internal value. Holds the top-left tint value. - * - * @name Phaser.GameObjects.Components.Tint#_tintTL - * @type {number} - * @private - * @default 16777215 - * @since 3.0.0 - */ - _tintTL: 16777215, - - /** - * Private internal value. Holds the top-right tint value. - * - * @name Phaser.GameObjects.Components.Tint#_tintTR - * @type {number} - * @private - * @default 16777215 - * @since 3.0.0 - */ - _tintTR: 16777215, - - /** - * Private internal value. Holds the bottom-left tint value. - * - * @name Phaser.GameObjects.Components.Tint#_tintBL - * @type {number} - * @private - * @default 16777215 - * @since 3.0.0 - */ - _tintBL: 16777215, - - /** - * Private internal value. Holds the bottom-right tint value. - * - * @name Phaser.GameObjects.Components.Tint#_tintBR - * @type {number} - * @private - * @default 16777215 - * @since 3.0.0 - */ - _tintBR: 16777215, - - /** - * Private internal value. Holds if the Game Object is tinted or not. - * - * @name Phaser.GameObjects.Components.Tint#_isTinted - * @type {boolean} - * @private - * @default false - * @since 3.11.0 - */ - _isTinted: false, - - /** - * Fill or additive? - * - * @name Phaser.GameObjects.Components.Tint#tintFill - * @type {boolean} - * @default false - * @since 3.11.0 - */ - tintFill: false, - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - * - * @method Phaser.GameObjects.Components.Tint#clearTint - * @webglOnly - * @since 3.0.0 - * - * @return {this} This Game Object instance. - */ - clearTint: function () - { - this.setTint(0xffffff); - - this._isTinted = false; - - return this; - }, - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * - * @method Phaser.GameObjects.Components.Tint#setTint - * @webglOnly - * @since 3.0.0 - * - * @param {integer} [topLeft=0xffffff] - The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. - * @param {integer} [topRight] - The tint being applied to the top-right of the Game Object. - * @param {integer} [bottomLeft] - The tint being applied to the bottom-left of the Game Object. - * @param {integer} [bottomRight] - The tint being applied to the bottom-right of the Game Object. - * - * @return {this} This Game Object instance. - */ - setTint: function (topLeft, topRight, bottomLeft, bottomRight) - { - if (topLeft === undefined) { topLeft = 0xffffff; } - - if (topRight === undefined) - { - topRight = topLeft; - bottomLeft = topLeft; - bottomRight = topLeft; - } - - this._tintTL = GetColor(topLeft); - this._tintTR = GetColor(topRight); - this._tintBL = GetColor(bottomLeft); - this._tintBR = GetColor(bottomRight); - - this._isTinted = true; - - this.tintFill = false; - - return this; - }, - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * - * @method Phaser.GameObjects.Components.Tint#setTintFill - * @webglOnly - * @since 3.11.0 - * - * @param {integer} [topLeft=0xffffff] - The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. - * @param {integer} [topRight] - The tint being applied to the top-right of the Game Object. - * @param {integer} [bottomLeft] - The tint being applied to the bottom-left of the Game Object. - * @param {integer} [bottomRight] - The tint being applied to the bottom-right of the Game Object. - * - * @return {this} This Game Object instance. - */ - setTintFill: function (topLeft, topRight, bottomLeft, bottomRight) - { - this.setTint(topLeft, topRight, bottomLeft, bottomRight); - - this.tintFill = true; - - return this; - }, - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Tint#tintTopLeft - * @type {integer} - * @webglOnly - * @since 3.0.0 - */ - tintTopLeft: { - - get: function () - { - return this._tintTL; - }, - - set: function (value) - { - this._tintTL = GetColor(value); - this._isTinted = true; - } - - }, - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Tint#tintTopRight - * @type {integer} - * @webglOnly - * @since 3.0.0 - */ - tintTopRight: { - - get: function () - { - return this._tintTR; - }, - - set: function (value) - { - this._tintTR = GetColor(value); - this._isTinted = true; - } - - }, - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Tint#tintBottomLeft - * @type {integer} - * @webglOnly - * @since 3.0.0 - */ - tintBottomLeft: { - - get: function () - { - return this._tintBL; - }, - - set: function (value) - { - this._tintBL = GetColor(value); - this._isTinted = true; - } - - }, - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - * - * @name Phaser.GameObjects.Components.Tint#tintBottomRight - * @type {integer} - * @webglOnly - * @since 3.0.0 - */ - tintBottomRight: { - - get: function () - { - return this._tintBR; - }, - - set: function (value) - { - this._tintBR = GetColor(value); - this._isTinted = true; - } - - }, - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - * - * @name Phaser.GameObjects.Components.Tint#tint - * @type {integer} - * @webglOnly - * @since 3.0.0 - */ - tint: { - - set: function (value) - { - this.setTint(value, value, value, value); - } - }, - - /** - * Does this Game Object have a tint applied to it or not? - * - * @name Phaser.GameObjects.Components.Tint#isTinted - * @type {boolean} - * @webglOnly - * @readonly - * @since 3.11.0 - */ - isTinted: { - - get: function () - { - return this._isTinted; - } - - } - -}; - -module.exports = Tint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @function GetColor + * @since 3.0.0 + * @private + */ +var GetColor = function (value) +{ + return (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); +}; + +/** + * Provides methods used for setting the tint of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Tint + * @webglOnly + * @since 3.0.0 + */ + +var Tint = { + + /** + * Private internal value. Holds the top-left tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintTL + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintTL: 16777215, + + /** + * Private internal value. Holds the top-right tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintTR + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintTR: 16777215, + + /** + * Private internal value. Holds the bottom-left tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintBL + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintBL: 16777215, + + /** + * Private internal value. Holds the bottom-right tint value. + * + * @name Phaser.GameObjects.Components.Tint#_tintBR + * @type {number} + * @private + * @default 16777215 + * @since 3.0.0 + */ + _tintBR: 16777215, + + /** + * Private internal value. Holds if the Game Object is tinted or not. + * + * @name Phaser.GameObjects.Components.Tint#_isTinted + * @type {boolean} + * @private + * @default false + * @since 3.11.0 + */ + _isTinted: false, + + /** + * Fill or additive? + * + * @name Phaser.GameObjects.Components.Tint#tintFill + * @type {boolean} + * @default false + * @since 3.11.0 + */ + tintFill: false, + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + * + * @method Phaser.GameObjects.Components.Tint#clearTint + * @webglOnly + * @since 3.0.0 + * + * @return {this} This Game Object instance. + */ + clearTint: function () + { + this.setTint(0xffffff); + + this._isTinted = false; + + return this; + }, + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * + * @method Phaser.GameObjects.Components.Tint#setTint + * @webglOnly + * @since 3.0.0 + * + * @param {integer} [topLeft=0xffffff] - The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. + * @param {integer} [topRight] - The tint being applied to the top-right of the Game Object. + * @param {integer} [bottomLeft] - The tint being applied to the bottom-left of the Game Object. + * @param {integer} [bottomRight] - The tint being applied to the bottom-right of the Game Object. + * + * @return {this} This Game Object instance. + */ + setTint: function (topLeft, topRight, bottomLeft, bottomRight) + { + if (topLeft === undefined) { topLeft = 0xffffff; } + + if (topRight === undefined) + { + topRight = topLeft; + bottomLeft = topLeft; + bottomRight = topLeft; + } + + this._tintTL = GetColor(topLeft); + this._tintTR = GetColor(topRight); + this._tintBL = GetColor(bottomLeft); + this._tintBR = GetColor(bottomRight); + + this._isTinted = true; + + this.tintFill = false; + + return this; + }, + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * + * @method Phaser.GameObjects.Components.Tint#setTintFill + * @webglOnly + * @since 3.11.0 + * + * @param {integer} [topLeft=0xffffff] - The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. + * @param {integer} [topRight] - The tint being applied to the top-right of the Game Object. + * @param {integer} [bottomLeft] - The tint being applied to the bottom-left of the Game Object. + * @param {integer} [bottomRight] - The tint being applied to the bottom-right of the Game Object. + * + * @return {this} This Game Object instance. + */ + setTintFill: function (topLeft, topRight, bottomLeft, bottomRight) + { + this.setTint(topLeft, topRight, bottomLeft, bottomRight); + + this.tintFill = true; + + return this; + }, + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintTopLeft + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintTopLeft: { + + get: function () + { + return this._tintTL; + }, + + set: function (value) + { + this._tintTL = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintTopRight + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintTopRight: { + + get: function () + { + return this._tintTR; + }, + + set: function (value) + { + this._tintTR = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintBottomLeft + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintBottomLeft: { + + get: function () + { + return this._tintBL; + }, + + set: function (value) + { + this._tintBL = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + * + * @name Phaser.GameObjects.Components.Tint#tintBottomRight + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tintBottomRight: { + + get: function () + { + return this._tintBR; + }, + + set: function (value) + { + this._tintBR = GetColor(value); + this._isTinted = true; + } + + }, + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + * + * @name Phaser.GameObjects.Components.Tint#tint + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + tint: { + + set: function (value) + { + this.setTint(value, value, value, value); + } + }, + + /** + * Does this Game Object have a tint applied to it or not? + * + * @name Phaser.GameObjects.Components.Tint#isTinted + * @type {boolean} + * @webglOnly + * @readonly + * @since 3.11.0 + */ + isTinted: { + + get: function () + { + return this._isTinted; + } + + } + +}; + +module.exports = Tint; diff --git a/src/gameobjects/components/ToJSON.js b/src/gameobjects/components/ToJSON.js index 3081afff0..83d708b83 100644 --- a/src/gameobjects/components/ToJSON.js +++ b/src/gameobjects/components/ToJSON.js @@ -1,55 +1,55 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Build a JSON representation of the given Game Object. - * - * This is typically extended further by Game Object specific implementations. - * - * @method Phaser.GameObjects.Components.ToJSON - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to export as JSON. - * - * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. - */ -var ToJSON = function (gameObject) -{ - var out = { - name: gameObject.name, - type: gameObject.type, - x: gameObject.x, - y: gameObject.y, - depth: gameObject.depth, - scale: { - x: gameObject.scaleX, - y: gameObject.scaleY - }, - origin: { - x: gameObject.originX, - y: gameObject.originY - }, - flipX: gameObject.flipX, - flipY: gameObject.flipY, - rotation: gameObject.rotation, - alpha: gameObject.alpha, - visible: gameObject.visible, - blendMode: gameObject.blendMode, - textureKey: '', - frameKey: '', - data: {} - }; - - if (gameObject.texture) - { - out.textureKey = gameObject.texture.key; - out.frameKey = gameObject.frame.name; - } - - return out; -}; - -module.exports = ToJSON; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Build a JSON representation of the given Game Object. + * + * This is typically extended further by Game Object specific implementations. + * + * @method Phaser.GameObjects.Components.ToJSON + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to export as JSON. + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ +var ToJSON = function (gameObject) +{ + var out = { + name: gameObject.name, + type: gameObject.type, + x: gameObject.x, + y: gameObject.y, + depth: gameObject.depth, + scale: { + x: gameObject.scaleX, + y: gameObject.scaleY + }, + origin: { + x: gameObject.originX, + y: gameObject.originY + }, + flipX: gameObject.flipX, + flipY: gameObject.flipY, + rotation: gameObject.rotation, + alpha: gameObject.alpha, + visible: gameObject.visible, + blendMode: gameObject.blendMode, + textureKey: '', + frameKey: '', + data: {} + }; + + if (gameObject.texture) + { + out.textureKey = gameObject.texture.key; + out.frameKey = gameObject.frame.name; + } + + return out; +}; + +module.exports = ToJSON; diff --git a/src/gameobjects/components/Transform.js b/src/gameobjects/components/Transform.js index 0ed851b59..4dd598821 100644 --- a/src/gameobjects/components/Transform.js +++ b/src/gameobjects/components/Transform.js @@ -1,533 +1,533 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = require('../../math/const'); -var TransformMatrix = require('./TransformMatrix'); -var WrapAngle = require('../../math/angle/Wrap'); -var WrapAngleDegrees = require('../../math/angle/WrapDegrees'); - -// global bitmask flag for GameObject.renderMask (used by Scale) -var _FLAG = 4; // 0100 - -/** - * Provides methods used for getting and setting the position, scale and rotation of a Game Object. - * - * @namespace Phaser.GameObjects.Components.Transform - * @since 3.0.0 - */ - -var Transform = { - - /** - * Private internal value. Holds the horizontal scale value. - * - * @name Phaser.GameObjects.Components.Transform#_scaleX - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _scaleX: 1, - - /** - * Private internal value. Holds the vertical scale value. - * - * @name Phaser.GameObjects.Components.Transform#_scaleY - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - _scaleY: 1, - - /** - * Private internal value. Holds the rotation value in radians. - * - * @name Phaser.GameObjects.Components.Transform#_rotation - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - _rotation: 0, - - /** - * The x position of this Game Object. - * - * @name Phaser.GameObjects.Components.Transform#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - x: 0, - - /** - * The y position of this Game Object. - * - * @name Phaser.GameObjects.Components.Transform#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - y: 0, - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - * - * @name Phaser.GameObjects.Components.Transform#z - * @type {number} - * @default 0 - * @since 3.0.0 - */ - z: 0, - - /** - * The w position of this Game Object. - * - * @name Phaser.GameObjects.Components.Transform#w - * @type {number} - * @default 0 - * @since 3.0.0 - */ - w: 0, - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - * - * @name Phaser.GameObjects.Components.Transform#scale - * @type {number} - * @default 1 - * @since 3.18.0 - */ - scale: { - - get: function () - { - return (this._scaleX + this._scaleY) / 2; - }, - - set: function (value) - { - this._scaleX = value; - this._scaleY = value; - - if (value === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The horizontal scale of this Game Object. - * - * @name Phaser.GameObjects.Components.Transform#scaleX - * @type {number} - * @default 1 - * @since 3.0.0 - */ - scaleX: { - - get: function () - { - return this._scaleX; - }, - - set: function (value) - { - this._scaleX = value; - - if (value === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The vertical scale of this Game Object. - * - * @name Phaser.GameObjects.Components.Transform#scaleY - * @type {number} - * @default 1 - * @since 3.0.0 - */ - scaleY: { - - get: function () - { - return this._scaleY; - }, - - set: function (value) - { - this._scaleY = value; - - if (value === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - } - - }, - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - * - * @name Phaser.GameObjects.Components.Transform#angle - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - angle: { - - get: function () - { - return WrapAngleDegrees(this._rotation * MATH_CONST.RAD_TO_DEG); - }, - - set: function (value) - { - // value is in degrees - this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD; - } - }, - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - * - * @name Phaser.GameObjects.Components.Transform#rotation - * @type {number} - * @default 1 - * @since 3.0.0 - */ - rotation: { - - get: function () - { - return this._rotation; - }, - - set: function (value) - { - // value is in radians - this._rotation = WrapAngle(value); - } - }, - - /** - * Sets the position of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setPosition - * @since 3.0.0 - * - * @param {number} [x=0] - The x position of this Game Object. - * @param {number} [y=x] - The y position of this Game Object. If not set it will use the `x` value. - * @param {number} [z=0] - The z position of this Game Object. - * @param {number} [w=0] - The w position of this Game Object. - * - * @return {this} This Game Object instance. - */ - setPosition: function (x, y, z, w) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - if (z === undefined) { z = 0; } - if (w === undefined) { w = 0; } - - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - return this; - }, - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * - * @method Phaser.GameObjects.Components.Transform#setRandomPosition - * @since 3.8.0 - * - * @param {number} [x=0] - The x position of the top-left of the random area. - * @param {number} [y=0] - The y position of the top-left of the random area. - * @param {number} [width] - The width of the random area. - * @param {number} [height] - The height of the random area. - * - * @return {this} This Game Object instance. - */ - setRandomPosition: function (x, y, width, height) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.scene.sys.scale.width; } - if (height === undefined) { height = this.scene.sys.scale.height; } - - this.x = x + (Math.random() * width); - this.y = y + (Math.random() * height); - - return this; - }, - - /** - * Sets the rotation of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setRotation - * @since 3.0.0 - * - * @param {number} [radians=0] - The rotation of this Game Object, in radians. - * - * @return {this} This Game Object instance. - */ - setRotation: function (radians) - { - if (radians === undefined) { radians = 0; } - - this.rotation = radians; - - return this; - }, - - /** - * Sets the angle of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setAngle - * @since 3.0.0 - * - * @param {number} [degrees=0] - The rotation of this Game Object, in degrees. - * - * @return {this} This Game Object instance. - */ - setAngle: function (degrees) - { - if (degrees === undefined) { degrees = 0; } - - this.angle = degrees; - - return this; - }, - - /** - * Sets the scale of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setScale - * @since 3.0.0 - * - * @param {number} x - The horizontal scale of this Game Object. - * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the `x` value. - * - * @return {this} This Game Object instance. - */ - setScale: function (x, y) - { - if (x === undefined) { x = 1; } - if (y === undefined) { y = x; } - - this.scaleX = x; - this.scaleY = y; - - return this; - }, - - /** - * Sets the x position of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setX - * @since 3.0.0 - * - * @param {number} [value=0] - The x position of this Game Object. - * - * @return {this} This Game Object instance. - */ - setX: function (value) - { - if (value === undefined) { value = 0; } - - this.x = value; - - return this; - }, - - /** - * Sets the y position of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setY - * @since 3.0.0 - * - * @param {number} [value=0] - The y position of this Game Object. - * - * @return {this} This Game Object instance. - */ - setY: function (value) - { - if (value === undefined) { value = 0; } - - this.y = value; - - return this; - }, - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * - * @method Phaser.GameObjects.Components.Transform#setZ - * @since 3.0.0 - * - * @param {number} [value=0] - The z position of this Game Object. - * - * @return {this} This Game Object instance. - */ - setZ: function (value) - { - if (value === undefined) { value = 0; } - - this.z = value; - - return this; - }, - - /** - * Sets the w position of this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#setW - * @since 3.0.0 - * - * @param {number} [value=0] - The w position of this Game Object. - * - * @return {this} This Game Object instance. - */ - setW: function (value) - { - if (value === undefined) { value = 0; } - - this.w = value; - - return this; - }, - - /** - * Gets the local transform matrix for this Game Object. - * - * @method Phaser.GameObjects.Components.Transform#getLocalTransformMatrix - * @since 3.4.0 - * - * @param {Phaser.GameObjects.Components.TransformMatrix} [tempMatrix] - The matrix to populate with the values from this Game Object. - * - * @return {Phaser.GameObjects.Components.TransformMatrix} The populated Transform Matrix. - */ - getLocalTransformMatrix: function (tempMatrix) - { - if (tempMatrix === undefined) { tempMatrix = new TransformMatrix(); } - - return tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); - }, - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * - * @method Phaser.GameObjects.Components.Transform#getWorldTransformMatrix - * @since 3.4.0 - * - * @param {Phaser.GameObjects.Components.TransformMatrix} [tempMatrix] - The matrix to populate with the values from this Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} [parentMatrix] - A temporary matrix to hold parent values during the calculations. - * - * @return {Phaser.GameObjects.Components.TransformMatrix} The populated Transform Matrix. - */ - getWorldTransformMatrix: function (tempMatrix, parentMatrix) - { - if (tempMatrix === undefined) { tempMatrix = new TransformMatrix(); } - if (parentMatrix === undefined) { parentMatrix = new TransformMatrix(); } - - var parent = this.parentContainer; - - if (!parent) - { - return this.getLocalTransformMatrix(tempMatrix); - } - - tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); - - while (parent) - { - parentMatrix.applyITRS(parent.x, parent.y, parent._rotation, parent._scaleX, parent._scaleY); - - parentMatrix.multiply(tempMatrix, tempMatrix); - - parent = parent.parentContainer; - } - - return tempMatrix; - }, - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - * - * @method Phaser.GameObjects.Components.Transform#getParentRotation - * @since 3.18.0 - * - * @return {number} The sum total rotation, in radians, of all parent containers of this Game Object. - */ - getParentRotation: function () - { - var rotation = 0; - - var parent = this.parentContainer; - - while (parent) - { - rotation += parent.rotation; - - parent = parent.parentContainer; - } - - return rotation; - } - -}; - -module.exports = Transform; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = require('../../math/const'); +var TransformMatrix = require('./TransformMatrix'); +var WrapAngle = require('../../math/angle/Wrap'); +var WrapAngleDegrees = require('../../math/angle/WrapDegrees'); + +// global bitmask flag for GameObject.renderMask (used by Scale) +var _FLAG = 4; // 0100 + +/** + * Provides methods used for getting and setting the position, scale and rotation of a Game Object. + * + * @namespace Phaser.GameObjects.Components.Transform + * @since 3.0.0 + */ + +var Transform = { + + /** + * Private internal value. Holds the horizontal scale value. + * + * @name Phaser.GameObjects.Components.Transform#_scaleX + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _scaleX: 1, + + /** + * Private internal value. Holds the vertical scale value. + * + * @name Phaser.GameObjects.Components.Transform#_scaleY + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + _scaleY: 1, + + /** + * Private internal value. Holds the rotation value in radians. + * + * @name Phaser.GameObjects.Components.Transform#_rotation + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + _rotation: 0, + + /** + * The x position of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + x: 0, + + /** + * The y position of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + y: 0, + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + * + * @name Phaser.GameObjects.Components.Transform#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + z: 0, + + /** + * The w position of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#w + * @type {number} + * @default 0 + * @since 3.0.0 + */ + w: 0, + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + * + * @name Phaser.GameObjects.Components.Transform#scale + * @type {number} + * @default 1 + * @since 3.18.0 + */ + scale: { + + get: function () + { + return (this._scaleX + this._scaleY) / 2; + }, + + set: function (value) + { + this._scaleX = value; + this._scaleY = value; + + if (value === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The horizontal scale of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#scaleX + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scaleX: { + + get: function () + { + return this._scaleX; + }, + + set: function (value) + { + this._scaleX = value; + + if (value === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The vertical scale of this Game Object. + * + * @name Phaser.GameObjects.Components.Transform#scaleY + * @type {number} + * @default 1 + * @since 3.0.0 + */ + scaleY: { + + get: function () + { + return this._scaleY; + }, + + set: function (value) + { + this._scaleY = value; + + if (value === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + } + + }, + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + * + * @name Phaser.GameObjects.Components.Transform#angle + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + angle: { + + get: function () + { + return WrapAngleDegrees(this._rotation * MATH_CONST.RAD_TO_DEG); + }, + + set: function (value) + { + // value is in degrees + this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD; + } + }, + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + * + * @name Phaser.GameObjects.Components.Transform#rotation + * @type {number} + * @default 1 + * @since 3.0.0 + */ + rotation: { + + get: function () + { + return this._rotation; + }, + + set: function (value) + { + // value is in radians + this._rotation = WrapAngle(value); + } + }, + + /** + * Sets the position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setPosition + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of this Game Object. + * @param {number} [y=x] - The y position of this Game Object. If not set it will use the `x` value. + * @param {number} [z=0] - The z position of this Game Object. + * @param {number} [w=0] - The w position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setPosition: function (x, y, z, w) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + if (z === undefined) { z = 0; } + if (w === undefined) { w = 0; } + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + return this; + }, + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * + * @method Phaser.GameObjects.Components.Transform#setRandomPosition + * @since 3.8.0 + * + * @param {number} [x=0] - The x position of the top-left of the random area. + * @param {number} [y=0] - The y position of the top-left of the random area. + * @param {number} [width] - The width of the random area. + * @param {number} [height] - The height of the random area. + * + * @return {this} This Game Object instance. + */ + setRandomPosition: function (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + + this.x = x + (Math.random() * width); + this.y = y + (Math.random() * height); + + return this; + }, + + /** + * Sets the rotation of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setRotation + * @since 3.0.0 + * + * @param {number} [radians=0] - The rotation of this Game Object, in radians. + * + * @return {this} This Game Object instance. + */ + setRotation: function (radians) + { + if (radians === undefined) { radians = 0; } + + this.rotation = radians; + + return this; + }, + + /** + * Sets the angle of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setAngle + * @since 3.0.0 + * + * @param {number} [degrees=0] - The rotation of this Game Object, in degrees. + * + * @return {this} This Game Object instance. + */ + setAngle: function (degrees) + { + if (degrees === undefined) { degrees = 0; } + + this.angle = degrees; + + return this; + }, + + /** + * Sets the scale of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setScale + * @since 3.0.0 + * + * @param {number} x - The horizontal scale of this Game Object. + * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the `x` value. + * + * @return {this} This Game Object instance. + */ + setScale: function (x, y) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + this.scaleX = x; + this.scaleY = y; + + return this; + }, + + /** + * Sets the x position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setX + * @since 3.0.0 + * + * @param {number} [value=0] - The x position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setX: function (value) + { + if (value === undefined) { value = 0; } + + this.x = value; + + return this; + }, + + /** + * Sets the y position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setY + * @since 3.0.0 + * + * @param {number} [value=0] - The y position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setY: function (value) + { + if (value === undefined) { value = 0; } + + this.y = value; + + return this; + }, + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * + * @method Phaser.GameObjects.Components.Transform#setZ + * @since 3.0.0 + * + * @param {number} [value=0] - The z position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setZ: function (value) + { + if (value === undefined) { value = 0; } + + this.z = value; + + return this; + }, + + /** + * Sets the w position of this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#setW + * @since 3.0.0 + * + * @param {number} [value=0] - The w position of this Game Object. + * + * @return {this} This Game Object instance. + */ + setW: function (value) + { + if (value === undefined) { value = 0; } + + this.w = value; + + return this; + }, + + /** + * Gets the local transform matrix for this Game Object. + * + * @method Phaser.GameObjects.Components.Transform#getLocalTransformMatrix + * @since 3.4.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} [tempMatrix] - The matrix to populate with the values from this Game Object. + * + * @return {Phaser.GameObjects.Components.TransformMatrix} The populated Transform Matrix. + */ + getLocalTransformMatrix: function (tempMatrix) + { + if (tempMatrix === undefined) { tempMatrix = new TransformMatrix(); } + + return tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); + }, + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * + * @method Phaser.GameObjects.Components.Transform#getWorldTransformMatrix + * @since 3.4.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} [tempMatrix] - The matrix to populate with the values from this Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentMatrix] - A temporary matrix to hold parent values during the calculations. + * + * @return {Phaser.GameObjects.Components.TransformMatrix} The populated Transform Matrix. + */ + getWorldTransformMatrix: function (tempMatrix, parentMatrix) + { + if (tempMatrix === undefined) { tempMatrix = new TransformMatrix(); } + if (parentMatrix === undefined) { parentMatrix = new TransformMatrix(); } + + var parent = this.parentContainer; + + if (!parent) + { + return this.getLocalTransformMatrix(tempMatrix); + } + + tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); + + while (parent) + { + parentMatrix.applyITRS(parent.x, parent.y, parent._rotation, parent._scaleX, parent._scaleY); + + parentMatrix.multiply(tempMatrix, tempMatrix); + + parent = parent.parentContainer; + } + + return tempMatrix; + }, + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + * + * @method Phaser.GameObjects.Components.Transform#getParentRotation + * @since 3.18.0 + * + * @return {number} The sum total rotation, in radians, of all parent containers of this Game Object. + */ + getParentRotation: function () + { + var rotation = 0; + + var parent = this.parentContainer; + + while (parent) + { + rotation += parent.rotation; + + parent = parent.parentContainer; + } + + return rotation; + } + +}; + +module.exports = Transform; diff --git a/src/gameobjects/components/TransformMatrix.js b/src/gameobjects/components/TransformMatrix.js index 101afaf90..4c10c5a26 100644 --- a/src/gameobjects/components/TransformMatrix.js +++ b/src/gameobjects/components/TransformMatrix.js @@ -1,962 +1,962 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var MATH_CONST = require('../../math/const'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Matrix used for display transformations for rendering. - * - * It is represented like so: - * - * ``` - * | a | c | tx | - * | b | d | ty | - * | 0 | 0 | 1 | - * ``` - * - * @class TransformMatrix - * @memberof Phaser.GameObjects.Components - * @constructor - * @since 3.0.0 - * - * @param {number} [a=1] - The Scale X value. - * @param {number} [b=0] - The Skew Y value. - * @param {number} [c=0] - The Skew X value. - * @param {number} [d=1] - The Scale Y value. - * @param {number} [tx=0] - The Translate X value. - * @param {number} [ty=0] - The Translate Y value. - */ -var TransformMatrix = new Class({ - - initialize: - - function TransformMatrix (a, b, c, d, tx, ty) - { - if (a === undefined) { a = 1; } - if (b === undefined) { b = 0; } - if (c === undefined) { c = 0; } - if (d === undefined) { d = 1; } - if (tx === undefined) { tx = 0; } - if (ty === undefined) { ty = 0; } - - /** - * The matrix values. - * - * @name Phaser.GameObjects.Components.TransformMatrix#matrix - * @type {Float32Array} - * @since 3.0.0 - */ - this.matrix = new Float32Array([ a, b, c, d, tx, ty, 0, 0, 1 ]); - - /** - * The decomposed matrix. - * - * @name Phaser.GameObjects.Components.TransformMatrix#decomposedMatrix - * @type {object} - * @since 3.0.0 - */ - this.decomposedMatrix = { - translateX: 0, - translateY: 0, - scaleX: 1, - scaleY: 1, - rotation: 0 - }; - }, - - /** - * The Scale X value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#a - * @type {number} - * @since 3.4.0 - */ - a: { - - get: function () - { - return this.matrix[0]; - }, - - set: function (value) - { - this.matrix[0] = value; - } - - }, - - /** - * The Skew Y value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#b - * @type {number} - * @since 3.4.0 - */ - b: { - - get: function () - { - return this.matrix[1]; - }, - - set: function (value) - { - this.matrix[1] = value; - } - - }, - - /** - * The Skew X value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#c - * @type {number} - * @since 3.4.0 - */ - c: { - - get: function () - { - return this.matrix[2]; - }, - - set: function (value) - { - this.matrix[2] = value; - } - - }, - - /** - * The Scale Y value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#d - * @type {number} - * @since 3.4.0 - */ - d: { - - get: function () - { - return this.matrix[3]; - }, - - set: function (value) - { - this.matrix[3] = value; - } - - }, - - /** - * The Translate X value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#e - * @type {number} - * @since 3.11.0 - */ - e: { - - get: function () - { - return this.matrix[4]; - }, - - set: function (value) - { - this.matrix[4] = value; - } - - }, - - /** - * The Translate Y value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#f - * @type {number} - * @since 3.11.0 - */ - f: { - - get: function () - { - return this.matrix[5]; - }, - - set: function (value) - { - this.matrix[5] = value; - } - - }, - - /** - * The Translate X value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#tx - * @type {number} - * @since 3.4.0 - */ - tx: { - - get: function () - { - return this.matrix[4]; - }, - - set: function (value) - { - this.matrix[4] = value; - } - - }, - - /** - * The Translate Y value. - * - * @name Phaser.GameObjects.Components.TransformMatrix#ty - * @type {number} - * @since 3.4.0 - */ - ty: { - - get: function () - { - return this.matrix[5]; - }, - - set: function (value) - { - this.matrix[5] = value; - } - - }, - - /** - * The rotation of the Matrix. Value is in radians. - * - * @name Phaser.GameObjects.Components.TransformMatrix#rotation - * @type {number} - * @readonly - * @since 3.4.0 - */ - rotation: { - - get: function () - { - return Math.acos(this.a / this.scaleX) * ((Math.atan(-this.c / this.a) < 0) ? -1 : 1); - } - - }, - - /** - * The rotation of the Matrix, normalized to be within the Phaser right-handed - * clockwise rotation space. Value is in radians. - * - * @name Phaser.GameObjects.Components.TransformMatrix#rotationNormalized - * @type {number} - * @readonly - * @since 3.19.0 - */ - rotationNormalized: { - - get: function () - { - var matrix = this.matrix; - - var a = matrix[0]; - var b = matrix[1]; - var c = matrix[2]; - var d = matrix[3]; - - if (a || b) - { - // var r = Math.sqrt(a * a + b * b); - - return (b > 0) ? Math.acos(a / this.scaleX) : -Math.acos(a / this.scaleX); - } - else if (c || d) - { - // var s = Math.sqrt(c * c + d * d); - - return MATH_CONST.TAU - ((d > 0) ? Math.acos(-c / this.scaleY) : -Math.acos(c / this.scaleY)); - } - else - { - return 0; - } - } - - }, - - /** - * The decomposed horizontal scale of the Matrix. This value is always positive. - * - * @name Phaser.GameObjects.Components.TransformMatrix#scaleX - * @type {number} - * @readonly - * @since 3.4.0 - */ - scaleX: { - - get: function () - { - return Math.sqrt((this.a * this.a) + (this.b * this.b)); - } - - }, - - /** - * The decomposed vertical scale of the Matrix. This value is always positive. - * - * @name Phaser.GameObjects.Components.TransformMatrix#scaleY - * @type {number} - * @readonly - * @since 3.4.0 - */ - scaleY: { - - get: function () - { - return Math.sqrt((this.c * this.c) + (this.d * this.d)); - } - - }, - - /** - * Reset the Matrix to an identity matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#loadIdentity - * @since 3.0.0 - * - * @return {this} This TransformMatrix. - */ - loadIdentity: function () - { - var matrix = this.matrix; - - matrix[0] = 1; - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 1; - matrix[4] = 0; - matrix[5] = 0; - - return this; - }, - - /** - * Translate the Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#translate - * @since 3.0.0 - * - * @param {number} x - The horizontal translation value. - * @param {number} y - The vertical translation value. - * - * @return {this} This TransformMatrix. - */ - translate: function (x, y) - { - var matrix = this.matrix; - - matrix[4] = matrix[0] * x + matrix[2] * y + matrix[4]; - matrix[5] = matrix[1] * x + matrix[3] * y + matrix[5]; - - return this; - }, - - /** - * Scale the Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#scale - * @since 3.0.0 - * - * @param {number} x - The horizontal scale value. - * @param {number} y - The vertical scale value. - * - * @return {this} This TransformMatrix. - */ - scale: function (x, y) - { - var matrix = this.matrix; - - matrix[0] *= x; - matrix[1] *= x; - matrix[2] *= y; - matrix[3] *= y; - - return this; - }, - - /** - * Rotate the Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#rotate - * @since 3.0.0 - * - * @param {number} angle - The angle of rotation in radians. - * - * @return {this} This TransformMatrix. - */ - rotate: function (angle) - { - var sin = Math.sin(angle); - var cos = Math.cos(angle); - - var matrix = this.matrix; - - var a = matrix[0]; - var b = matrix[1]; - var c = matrix[2]; - var d = matrix[3]; - - matrix[0] = a * cos + c * sin; - matrix[1] = b * cos + d * sin; - matrix[2] = a * -sin + c * cos; - matrix[3] = b * -sin + d * cos; - - return this; - }, - - /** - * Multiply this Matrix by the given Matrix. - * - * If an `out` Matrix is given then the results will be stored in it. - * If it is not given, this matrix will be updated in place instead. - * Use an `out` Matrix if you do not wish to mutate this matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#multiply - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Components.TransformMatrix} rhs - The Matrix to multiply by. - * @param {Phaser.GameObjects.Components.TransformMatrix} [out] - An optional Matrix to store the results in. - * - * @return {(this|Phaser.GameObjects.Components.TransformMatrix)} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. - */ - multiply: function (rhs, out) - { - var matrix = this.matrix; - var source = rhs.matrix; - - var localA = matrix[0]; - var localB = matrix[1]; - var localC = matrix[2]; - var localD = matrix[3]; - var localE = matrix[4]; - var localF = matrix[5]; - - var sourceA = source[0]; - var sourceB = source[1]; - var sourceC = source[2]; - var sourceD = source[3]; - var sourceE = source[4]; - var sourceF = source[5]; - - var destinationMatrix = (out === undefined) ? this : out; - - destinationMatrix.a = (sourceA * localA) + (sourceB * localC); - destinationMatrix.b = (sourceA * localB) + (sourceB * localD); - destinationMatrix.c = (sourceC * localA) + (sourceD * localC); - destinationMatrix.d = (sourceC * localB) + (sourceD * localD); - destinationMatrix.e = (sourceE * localA) + (sourceF * localC) + localE; - destinationMatrix.f = (sourceE * localB) + (sourceF * localD) + localF; - - return destinationMatrix; - }, - - /** - * Multiply this Matrix by the matrix given, including the offset. - * - * The offsetX is added to the tx value: `offsetX * a + offsetY * c + tx`. - * The offsetY is added to the ty value: `offsetY * b + offsetY * d + ty`. - * - * @method Phaser.GameObjects.Components.TransformMatrix#multiplyWithOffset - * @since 3.11.0 - * - * @param {Phaser.GameObjects.Components.TransformMatrix} src - The source Matrix to copy from. - * @param {number} offsetX - Horizontal offset to factor in to the multiplication. - * @param {number} offsetY - Vertical offset to factor in to the multiplication. - * - * @return {this} This TransformMatrix. - */ - multiplyWithOffset: function (src, offsetX, offsetY) - { - var matrix = this.matrix; - var otherMatrix = src.matrix; - - var a0 = matrix[0]; - var b0 = matrix[1]; - var c0 = matrix[2]; - var d0 = matrix[3]; - var tx0 = matrix[4]; - var ty0 = matrix[5]; - - var pse = offsetX * a0 + offsetY * c0 + tx0; - var psf = offsetX * b0 + offsetY * d0 + ty0; - - var a1 = otherMatrix[0]; - var b1 = otherMatrix[1]; - var c1 = otherMatrix[2]; - var d1 = otherMatrix[3]; - var tx1 = otherMatrix[4]; - var ty1 = otherMatrix[5]; - - matrix[0] = a1 * a0 + b1 * c0; - matrix[1] = a1 * b0 + b1 * d0; - matrix[2] = c1 * a0 + d1 * c0; - matrix[3] = c1 * b0 + d1 * d0; - matrix[4] = tx1 * a0 + ty1 * c0 + pse; - matrix[5] = tx1 * b0 + ty1 * d0 + psf; - - return this; - }, - - /** - * Transform the Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#transform - * @since 3.0.0 - * - * @param {number} a - The Scale X value. - * @param {number} b - The Shear Y value. - * @param {number} c - The Shear X value. - * @param {number} d - The Scale Y value. - * @param {number} tx - The Translate X value. - * @param {number} ty - The Translate Y value. - * - * @return {this} This TransformMatrix. - */ - transform: function (a, b, c, d, tx, ty) - { - var matrix = this.matrix; - - var a0 = matrix[0]; - var b0 = matrix[1]; - var c0 = matrix[2]; - var d0 = matrix[3]; - var tx0 = matrix[4]; - var ty0 = matrix[5]; - - matrix[0] = a * a0 + b * c0; - matrix[1] = a * b0 + b * d0; - matrix[2] = c * a0 + d * c0; - matrix[3] = c * b0 + d * d0; - matrix[4] = tx * a0 + ty * c0 + tx0; - matrix[5] = tx * b0 + ty * d0 + ty0; - - return this; - }, - - /** - * Transform a point using this Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#transformPoint - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the point to transform. - * @param {number} y - The y coordinate of the point to transform. - * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The Point object to store the transformed coordinates. - * - * @return {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} The Point containing the transformed coordinates. - */ - transformPoint: function (x, y, point) - { - if (point === undefined) { point = { x: 0, y: 0 }; } - - var matrix = this.matrix; - - var a = matrix[0]; - var b = matrix[1]; - var c = matrix[2]; - var d = matrix[3]; - var tx = matrix[4]; - var ty = matrix[5]; - - point.x = x * a + y * c + tx; - point.y = x * b + y * d + ty; - - return point; - }, - - /** - * Invert the Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#invert - * @since 3.0.0 - * - * @return {this} This TransformMatrix. - */ - invert: function () - { - var matrix = this.matrix; - - var a = matrix[0]; - var b = matrix[1]; - var c = matrix[2]; - var d = matrix[3]; - var tx = matrix[4]; - var ty = matrix[5]; - - var n = a * d - b * c; - - matrix[0] = d / n; - matrix[1] = -b / n; - matrix[2] = -c / n; - matrix[3] = a / n; - matrix[4] = (c * ty - d * tx) / n; - matrix[5] = -(a * ty - b * tx) / n; - - return this; - }, - - /** - * Set the values of this Matrix to copy those of the matrix given. - * - * @method Phaser.GameObjects.Components.TransformMatrix#copyFrom - * @since 3.11.0 - * - * @param {Phaser.GameObjects.Components.TransformMatrix} src - The source Matrix to copy from. - * - * @return {this} This TransformMatrix. - */ - copyFrom: function (src) - { - var matrix = this.matrix; - - matrix[0] = src.a; - matrix[1] = src.b; - matrix[2] = src.c; - matrix[3] = src.d; - matrix[4] = src.e; - matrix[5] = src.f; - - return this; - }, - - /** - * Set the values of this Matrix to copy those of the array given. - * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. - * - * @method Phaser.GameObjects.Components.TransformMatrix#copyFromArray - * @since 3.11.0 - * - * @param {array} src - The array of values to set into this matrix. - * - * @return {this} This TransformMatrix. - */ - copyFromArray: function (src) - { - var matrix = this.matrix; - - matrix[0] = src[0]; - matrix[1] = src[1]; - matrix[2] = src[2]; - matrix[3] = src[3]; - matrix[4] = src[4]; - matrix[5] = src[5]; - - return this; - }, - - /** - * Copy the values from this Matrix to the given Canvas Rendering Context. - * This will use the Context.transform method. - * - * @method Phaser.GameObjects.Components.TransformMatrix#copyToContext - * @since 3.12.0 - * - * @param {CanvasRenderingContext2D} ctx - The Canvas Rendering Context to copy the matrix values to. - * - * @return {CanvasRenderingContext2D} The Canvas Rendering Context. - */ - copyToContext: function (ctx) - { - var matrix = this.matrix; - - ctx.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); - - return ctx; - }, - - /** - * Copy the values from this Matrix to the given Canvas Rendering Context. - * This will use the Context.setTransform method. - * - * @method Phaser.GameObjects.Components.TransformMatrix#setToContext - * @since 3.12.0 - * - * @param {CanvasRenderingContext2D} ctx - The Canvas Rendering Context to copy the matrix values to. - * - * @return {CanvasRenderingContext2D} The Canvas Rendering Context. - */ - setToContext: function (ctx) - { - var matrix = this.matrix; - - ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); - - return ctx; - }, - - /** - * Copy the values in this Matrix to the array given. - * - * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. - * - * @method Phaser.GameObjects.Components.TransformMatrix#copyToArray - * @since 3.12.0 - * - * @param {array} [out] - The array to copy the matrix values in to. - * - * @return {array} An array where elements 0 to 5 contain the values from this matrix. - */ - copyToArray: function (out) - { - var matrix = this.matrix; - - if (out === undefined) - { - out = [ matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5] ]; - } - else - { - out[0] = matrix[0]; - out[1] = matrix[1]; - out[2] = matrix[2]; - out[3] = matrix[3]; - out[4] = matrix[4]; - out[5] = matrix[5]; - } - - return out; - }, - - /** - * Set the values of this Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#setTransform - * @since 3.0.0 - * - * @param {number} a - The Scale X value. - * @param {number} b - The Shear Y value. - * @param {number} c - The Shear X value. - * @param {number} d - The Scale Y value. - * @param {number} tx - The Translate X value. - * @param {number} ty - The Translate Y value. - * - * @return {this} This TransformMatrix. - */ - setTransform: function (a, b, c, d, tx, ty) - { - var matrix = this.matrix; - - matrix[0] = a; - matrix[1] = b; - matrix[2] = c; - matrix[3] = d; - matrix[4] = tx; - matrix[5] = ty; - - return this; - }, - - /** - * Decompose this Matrix into its translation, scale and rotation values using QR decomposition. - * - * The result must be applied in the following order to reproduce the current matrix: - * - * translate -> rotate -> scale - * - * @method Phaser.GameObjects.Components.TransformMatrix#decomposeMatrix - * @since 3.0.0 - * - * @return {object} The decomposed Matrix. - */ - decomposeMatrix: function () - { - var decomposedMatrix = this.decomposedMatrix; - - var matrix = this.matrix; - - // a = scale X (1) - // b = shear Y (0) - // c = shear X (0) - // d = scale Y (1) - - var a = matrix[0]; - var b = matrix[1]; - var c = matrix[2]; - var d = matrix[3]; - - var determ = a * d - b * c; - - decomposedMatrix.translateX = matrix[4]; - decomposedMatrix.translateY = matrix[5]; - - if (a || b) - { - var r = Math.sqrt(a * a + b * b); - - decomposedMatrix.rotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); - decomposedMatrix.scaleX = r; - decomposedMatrix.scaleY = determ / r; - } - else if (c || d) - { - var s = Math.sqrt(c * c + d * d); - - decomposedMatrix.rotation = Math.PI * 0.5 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s)); - decomposedMatrix.scaleX = determ / s; - decomposedMatrix.scaleY = s; - } - else - { - decomposedMatrix.rotation = 0; - decomposedMatrix.scaleX = 0; - decomposedMatrix.scaleY = 0; - } - - return decomposedMatrix; - }, - - /** - * Apply the identity, translate, rotate and scale operations on the Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#applyITRS - * @since 3.0.0 - * - * @param {number} x - The horizontal translation. - * @param {number} y - The vertical translation. - * @param {number} rotation - The angle of rotation in radians. - * @param {number} scaleX - The horizontal scale. - * @param {number} scaleY - The vertical scale. - * - * @return {this} This TransformMatrix. - */ - applyITRS: function (x, y, rotation, scaleX, scaleY) - { - var matrix = this.matrix; - - var radianSin = Math.sin(rotation); - var radianCos = Math.cos(rotation); - - // Translate - matrix[4] = x; - matrix[5] = y; - - // Rotate and Scale - matrix[0] = radianCos * scaleX; - matrix[1] = radianSin * scaleX; - matrix[2] = -radianSin * scaleY; - matrix[3] = radianCos * scaleY; - - return this; - }, - - /** - * Takes the `x` and `y` values and returns a new position in the `output` vector that is the inverse of - * the current matrix with its transformation applied. - * - * Can be used to translate points from world to local space. - * - * @method Phaser.GameObjects.Components.TransformMatrix#applyInverse - * @since 3.12.0 - * - * @param {number} x - The x position to translate. - * @param {number} y - The y position to translate. - * @param {Phaser.Math.Vector2} [output] - A Vector2, or point-like object, to store the results in. - * - * @return {Phaser.Math.Vector2} The coordinates, inverse-transformed through this matrix. - */ - applyInverse: function (x, y, output) - { - if (output === undefined) { output = new Vector2(); } - - var matrix = this.matrix; - - var a = matrix[0]; - var b = matrix[1]; - var c = matrix[2]; - var d = matrix[3]; - var tx = matrix[4]; - var ty = matrix[5]; - - var id = 1 / ((a * d) + (c * -b)); - - output.x = (d * id * x) + (-c * id * y) + (((ty * c) - (tx * d)) * id); - output.y = (a * id * y) + (-b * id * x) + (((-ty * a) + (tx * b)) * id); - - return output; - }, - - /** - * Returns the X component of this matrix multiplied by the given values. - * This is the same as `x * a + y * c + e`. - * - * @method Phaser.GameObjects.Components.TransformMatrix#getX - * @since 3.12.0 - * - * @param {number} x - The x value. - * @param {number} y - The y value. - * - * @return {number} The calculated x value. - */ - getX: function (x, y) - { - return x * this.a + y * this.c + this.e; - }, - - /** - * Returns the Y component of this matrix multiplied by the given values. - * This is the same as `x * b + y * d + f`. - * - * @method Phaser.GameObjects.Components.TransformMatrix#getY - * @since 3.12.0 - * - * @param {number} x - The x value. - * @param {number} y - The y value. - * - * @return {number} The calculated y value. - */ - getY: function (x, y) - { - return x * this.b + y * this.d + this.f; - }, - - /** - * Returns a string that can be used in a CSS Transform call as a `matrix` property. - * - * @method Phaser.GameObjects.Components.TransformMatrix#getCSSMatrix - * @since 3.12.0 - * - * @return {string} A string containing the CSS Transform matrix values. - */ - getCSSMatrix: function () - { - var m = this.matrix; - - return 'matrix(' + m[0] + ',' + m[1] + ',' + m[2] + ',' + m[3] + ',' + m[4] + ',' + m[5] + ')'; - }, - - /** - * Destroys this Transform Matrix. - * - * @method Phaser.GameObjects.Components.TransformMatrix#destroy - * @since 3.4.0 - */ - destroy: function () - { - this.matrix = null; - this.decomposedMatrix = null; - } - -}); - -module.exports = TransformMatrix; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var MATH_CONST = require('../../math/const'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Matrix used for display transformations for rendering. + * + * It is represented like so: + * + * ``` + * | a | c | tx | + * | b | d | ty | + * | 0 | 0 | 1 | + * ``` + * + * @class TransformMatrix + * @memberof Phaser.GameObjects.Components + * @constructor + * @since 3.0.0 + * + * @param {number} [a=1] - The Scale X value. + * @param {number} [b=0] - The Skew Y value. + * @param {number} [c=0] - The Skew X value. + * @param {number} [d=1] - The Scale Y value. + * @param {number} [tx=0] - The Translate X value. + * @param {number} [ty=0] - The Translate Y value. + */ +var TransformMatrix = new Class({ + + initialize: + + function TransformMatrix (a, b, c, d, tx, ty) + { + if (a === undefined) { a = 1; } + if (b === undefined) { b = 0; } + if (c === undefined) { c = 0; } + if (d === undefined) { d = 1; } + if (tx === undefined) { tx = 0; } + if (ty === undefined) { ty = 0; } + + /** + * The matrix values. + * + * @name Phaser.GameObjects.Components.TransformMatrix#matrix + * @type {Float32Array} + * @since 3.0.0 + */ + this.matrix = new Float32Array([ a, b, c, d, tx, ty, 0, 0, 1 ]); + + /** + * The decomposed matrix. + * + * @name Phaser.GameObjects.Components.TransformMatrix#decomposedMatrix + * @type {object} + * @since 3.0.0 + */ + this.decomposedMatrix = { + translateX: 0, + translateY: 0, + scaleX: 1, + scaleY: 1, + rotation: 0 + }; + }, + + /** + * The Scale X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#a + * @type {number} + * @since 3.4.0 + */ + a: { + + get: function () + { + return this.matrix[0]; + }, + + set: function (value) + { + this.matrix[0] = value; + } + + }, + + /** + * The Skew Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#b + * @type {number} + * @since 3.4.0 + */ + b: { + + get: function () + { + return this.matrix[1]; + }, + + set: function (value) + { + this.matrix[1] = value; + } + + }, + + /** + * The Skew X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#c + * @type {number} + * @since 3.4.0 + */ + c: { + + get: function () + { + return this.matrix[2]; + }, + + set: function (value) + { + this.matrix[2] = value; + } + + }, + + /** + * The Scale Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#d + * @type {number} + * @since 3.4.0 + */ + d: { + + get: function () + { + return this.matrix[3]; + }, + + set: function (value) + { + this.matrix[3] = value; + } + + }, + + /** + * The Translate X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#e + * @type {number} + * @since 3.11.0 + */ + e: { + + get: function () + { + return this.matrix[4]; + }, + + set: function (value) + { + this.matrix[4] = value; + } + + }, + + /** + * The Translate Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#f + * @type {number} + * @since 3.11.0 + */ + f: { + + get: function () + { + return this.matrix[5]; + }, + + set: function (value) + { + this.matrix[5] = value; + } + + }, + + /** + * The Translate X value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#tx + * @type {number} + * @since 3.4.0 + */ + tx: { + + get: function () + { + return this.matrix[4]; + }, + + set: function (value) + { + this.matrix[4] = value; + } + + }, + + /** + * The Translate Y value. + * + * @name Phaser.GameObjects.Components.TransformMatrix#ty + * @type {number} + * @since 3.4.0 + */ + ty: { + + get: function () + { + return this.matrix[5]; + }, + + set: function (value) + { + this.matrix[5] = value; + } + + }, + + /** + * The rotation of the Matrix. Value is in radians. + * + * @name Phaser.GameObjects.Components.TransformMatrix#rotation + * @type {number} + * @readonly + * @since 3.4.0 + */ + rotation: { + + get: function () + { + return Math.acos(this.a / this.scaleX) * ((Math.atan(-this.c / this.a) < 0) ? -1 : 1); + } + + }, + + /** + * The rotation of the Matrix, normalized to be within the Phaser right-handed + * clockwise rotation space. Value is in radians. + * + * @name Phaser.GameObjects.Components.TransformMatrix#rotationNormalized + * @type {number} + * @readonly + * @since 3.19.0 + */ + rotationNormalized: { + + get: function () + { + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + + if (a || b) + { + // var r = Math.sqrt(a * a + b * b); + + return (b > 0) ? Math.acos(a / this.scaleX) : -Math.acos(a / this.scaleX); + } + else if (c || d) + { + // var s = Math.sqrt(c * c + d * d); + + return MATH_CONST.TAU - ((d > 0) ? Math.acos(-c / this.scaleY) : -Math.acos(c / this.scaleY)); + } + else + { + return 0; + } + } + + }, + + /** + * The decomposed horizontal scale of the Matrix. This value is always positive. + * + * @name Phaser.GameObjects.Components.TransformMatrix#scaleX + * @type {number} + * @readonly + * @since 3.4.0 + */ + scaleX: { + + get: function () + { + return Math.sqrt((this.a * this.a) + (this.b * this.b)); + } + + }, + + /** + * The decomposed vertical scale of the Matrix. This value is always positive. + * + * @name Phaser.GameObjects.Components.TransformMatrix#scaleY + * @type {number} + * @readonly + * @since 3.4.0 + */ + scaleY: { + + get: function () + { + return Math.sqrt((this.c * this.c) + (this.d * this.d)); + } + + }, + + /** + * Reset the Matrix to an identity matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#loadIdentity + * @since 3.0.0 + * + * @return {this} This TransformMatrix. + */ + loadIdentity: function () + { + var matrix = this.matrix; + + matrix[0] = 1; + matrix[1] = 0; + matrix[2] = 0; + matrix[3] = 1; + matrix[4] = 0; + matrix[5] = 0; + + return this; + }, + + /** + * Translate the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#translate + * @since 3.0.0 + * + * @param {number} x - The horizontal translation value. + * @param {number} y - The vertical translation value. + * + * @return {this} This TransformMatrix. + */ + translate: function (x, y) + { + var matrix = this.matrix; + + matrix[4] = matrix[0] * x + matrix[2] * y + matrix[4]; + matrix[5] = matrix[1] * x + matrix[3] * y + matrix[5]; + + return this; + }, + + /** + * Scale the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#scale + * @since 3.0.0 + * + * @param {number} x - The horizontal scale value. + * @param {number} y - The vertical scale value. + * + * @return {this} This TransformMatrix. + */ + scale: function (x, y) + { + var matrix = this.matrix; + + matrix[0] *= x; + matrix[1] *= x; + matrix[2] *= y; + matrix[3] *= y; + + return this; + }, + + /** + * Rotate the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#rotate + * @since 3.0.0 + * + * @param {number} angle - The angle of rotation in radians. + * + * @return {this} This TransformMatrix. + */ + rotate: function (angle) + { + var sin = Math.sin(angle); + var cos = Math.cos(angle); + + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + + matrix[0] = a * cos + c * sin; + matrix[1] = b * cos + d * sin; + matrix[2] = a * -sin + c * cos; + matrix[3] = b * -sin + d * cos; + + return this; + }, + + /** + * Multiply this Matrix by the given Matrix. + * + * If an `out` Matrix is given then the results will be stored in it. + * If it is not given, this matrix will be updated in place instead. + * Use an `out` Matrix if you do not wish to mutate this matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#multiply + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} rhs - The Matrix to multiply by. + * @param {Phaser.GameObjects.Components.TransformMatrix} [out] - An optional Matrix to store the results in. + * + * @return {(this|Phaser.GameObjects.Components.TransformMatrix)} Either this TransformMatrix, or the `out` Matrix, if given in the arguments. + */ + multiply: function (rhs, out) + { + var matrix = this.matrix; + var source = rhs.matrix; + + var localA = matrix[0]; + var localB = matrix[1]; + var localC = matrix[2]; + var localD = matrix[3]; + var localE = matrix[4]; + var localF = matrix[5]; + + var sourceA = source[0]; + var sourceB = source[1]; + var sourceC = source[2]; + var sourceD = source[3]; + var sourceE = source[4]; + var sourceF = source[5]; + + var destinationMatrix = (out === undefined) ? this : out; + + destinationMatrix.a = (sourceA * localA) + (sourceB * localC); + destinationMatrix.b = (sourceA * localB) + (sourceB * localD); + destinationMatrix.c = (sourceC * localA) + (sourceD * localC); + destinationMatrix.d = (sourceC * localB) + (sourceD * localD); + destinationMatrix.e = (sourceE * localA) + (sourceF * localC) + localE; + destinationMatrix.f = (sourceE * localB) + (sourceF * localD) + localF; + + return destinationMatrix; + }, + + /** + * Multiply this Matrix by the matrix given, including the offset. + * + * The offsetX is added to the tx value: `offsetX * a + offsetY * c + tx`. + * The offsetY is added to the ty value: `offsetY * b + offsetY * d + ty`. + * + * @method Phaser.GameObjects.Components.TransformMatrix#multiplyWithOffset + * @since 3.11.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} src - The source Matrix to copy from. + * @param {number} offsetX - Horizontal offset to factor in to the multiplication. + * @param {number} offsetY - Vertical offset to factor in to the multiplication. + * + * @return {this} This TransformMatrix. + */ + multiplyWithOffset: function (src, offsetX, offsetY) + { + var matrix = this.matrix; + var otherMatrix = src.matrix; + + var a0 = matrix[0]; + var b0 = matrix[1]; + var c0 = matrix[2]; + var d0 = matrix[3]; + var tx0 = matrix[4]; + var ty0 = matrix[5]; + + var pse = offsetX * a0 + offsetY * c0 + tx0; + var psf = offsetX * b0 + offsetY * d0 + ty0; + + var a1 = otherMatrix[0]; + var b1 = otherMatrix[1]; + var c1 = otherMatrix[2]; + var d1 = otherMatrix[3]; + var tx1 = otherMatrix[4]; + var ty1 = otherMatrix[5]; + + matrix[0] = a1 * a0 + b1 * c0; + matrix[1] = a1 * b0 + b1 * d0; + matrix[2] = c1 * a0 + d1 * c0; + matrix[3] = c1 * b0 + d1 * d0; + matrix[4] = tx1 * a0 + ty1 * c0 + pse; + matrix[5] = tx1 * b0 + ty1 * d0 + psf; + + return this; + }, + + /** + * Transform the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#transform + * @since 3.0.0 + * + * @param {number} a - The Scale X value. + * @param {number} b - The Shear Y value. + * @param {number} c - The Shear X value. + * @param {number} d - The Scale Y value. + * @param {number} tx - The Translate X value. + * @param {number} ty - The Translate Y value. + * + * @return {this} This TransformMatrix. + */ + transform: function (a, b, c, d, tx, ty) + { + var matrix = this.matrix; + + var a0 = matrix[0]; + var b0 = matrix[1]; + var c0 = matrix[2]; + var d0 = matrix[3]; + var tx0 = matrix[4]; + var ty0 = matrix[5]; + + matrix[0] = a * a0 + b * c0; + matrix[1] = a * b0 + b * d0; + matrix[2] = c * a0 + d * c0; + matrix[3] = c * b0 + d * d0; + matrix[4] = tx * a0 + ty * c0 + tx0; + matrix[5] = tx * b0 + ty * d0 + ty0; + + return this; + }, + + /** + * Transform a point using this Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#transformPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the point to transform. + * @param {number} y - The y coordinate of the point to transform. + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The Point object to store the transformed coordinates. + * + * @return {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} The Point containing the transformed coordinates. + */ + transformPoint: function (x, y, point) + { + if (point === undefined) { point = { x: 0, y: 0 }; } + + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + var tx = matrix[4]; + var ty = matrix[5]; + + point.x = x * a + y * c + tx; + point.y = x * b + y * d + ty; + + return point; + }, + + /** + * Invert the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#invert + * @since 3.0.0 + * + * @return {this} This TransformMatrix. + */ + invert: function () + { + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + var tx = matrix[4]; + var ty = matrix[5]; + + var n = a * d - b * c; + + matrix[0] = d / n; + matrix[1] = -b / n; + matrix[2] = -c / n; + matrix[3] = a / n; + matrix[4] = (c * ty - d * tx) / n; + matrix[5] = -(a * ty - b * tx) / n; + + return this; + }, + + /** + * Set the values of this Matrix to copy those of the matrix given. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyFrom + * @since 3.11.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} src - The source Matrix to copy from. + * + * @return {this} This TransformMatrix. + */ + copyFrom: function (src) + { + var matrix = this.matrix; + + matrix[0] = src.a; + matrix[1] = src.b; + matrix[2] = src.c; + matrix[3] = src.d; + matrix[4] = src.e; + matrix[5] = src.f; + + return this; + }, + + /** + * Set the values of this Matrix to copy those of the array given. + * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyFromArray + * @since 3.11.0 + * + * @param {array} src - The array of values to set into this matrix. + * + * @return {this} This TransformMatrix. + */ + copyFromArray: function (src) + { + var matrix = this.matrix; + + matrix[0] = src[0]; + matrix[1] = src[1]; + matrix[2] = src[2]; + matrix[3] = src[3]; + matrix[4] = src[4]; + matrix[5] = src[5]; + + return this; + }, + + /** + * Copy the values from this Matrix to the given Canvas Rendering Context. + * This will use the Context.transform method. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyToContext + * @since 3.12.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas Rendering Context to copy the matrix values to. + * + * @return {CanvasRenderingContext2D} The Canvas Rendering Context. + */ + copyToContext: function (ctx) + { + var matrix = this.matrix; + + ctx.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + return ctx; + }, + + /** + * Copy the values from this Matrix to the given Canvas Rendering Context. + * This will use the Context.setTransform method. + * + * @method Phaser.GameObjects.Components.TransformMatrix#setToContext + * @since 3.12.0 + * + * @param {CanvasRenderingContext2D} ctx - The Canvas Rendering Context to copy the matrix values to. + * + * @return {CanvasRenderingContext2D} The Canvas Rendering Context. + */ + setToContext: function (ctx) + { + var matrix = this.matrix; + + ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + return ctx; + }, + + /** + * Copy the values in this Matrix to the array given. + * + * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. + * + * @method Phaser.GameObjects.Components.TransformMatrix#copyToArray + * @since 3.12.0 + * + * @param {array} [out] - The array to copy the matrix values in to. + * + * @return {array} An array where elements 0 to 5 contain the values from this matrix. + */ + copyToArray: function (out) + { + var matrix = this.matrix; + + if (out === undefined) + { + out = [ matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5] ]; + } + else + { + out[0] = matrix[0]; + out[1] = matrix[1]; + out[2] = matrix[2]; + out[3] = matrix[3]; + out[4] = matrix[4]; + out[5] = matrix[5]; + } + + return out; + }, + + /** + * Set the values of this Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#setTransform + * @since 3.0.0 + * + * @param {number} a - The Scale X value. + * @param {number} b - The Shear Y value. + * @param {number} c - The Shear X value. + * @param {number} d - The Scale Y value. + * @param {number} tx - The Translate X value. + * @param {number} ty - The Translate Y value. + * + * @return {this} This TransformMatrix. + */ + setTransform: function (a, b, c, d, tx, ty) + { + var matrix = this.matrix; + + matrix[0] = a; + matrix[1] = b; + matrix[2] = c; + matrix[3] = d; + matrix[4] = tx; + matrix[5] = ty; + + return this; + }, + + /** + * Decompose this Matrix into its translation, scale and rotation values using QR decomposition. + * + * The result must be applied in the following order to reproduce the current matrix: + * + * translate -> rotate -> scale + * + * @method Phaser.GameObjects.Components.TransformMatrix#decomposeMatrix + * @since 3.0.0 + * + * @return {object} The decomposed Matrix. + */ + decomposeMatrix: function () + { + var decomposedMatrix = this.decomposedMatrix; + + var matrix = this.matrix; + + // a = scale X (1) + // b = shear Y (0) + // c = shear X (0) + // d = scale Y (1) + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + + var determ = a * d - b * c; + + decomposedMatrix.translateX = matrix[4]; + decomposedMatrix.translateY = matrix[5]; + + if (a || b) + { + var r = Math.sqrt(a * a + b * b); + + decomposedMatrix.rotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + decomposedMatrix.scaleX = r; + decomposedMatrix.scaleY = determ / r; + } + else if (c || d) + { + var s = Math.sqrt(c * c + d * d); + + decomposedMatrix.rotation = Math.PI * 0.5 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s)); + decomposedMatrix.scaleX = determ / s; + decomposedMatrix.scaleY = s; + } + else + { + decomposedMatrix.rotation = 0; + decomposedMatrix.scaleX = 0; + decomposedMatrix.scaleY = 0; + } + + return decomposedMatrix; + }, + + /** + * Apply the identity, translate, rotate and scale operations on the Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#applyITRS + * @since 3.0.0 + * + * @param {number} x - The horizontal translation. + * @param {number} y - The vertical translation. + * @param {number} rotation - The angle of rotation in radians. + * @param {number} scaleX - The horizontal scale. + * @param {number} scaleY - The vertical scale. + * + * @return {this} This TransformMatrix. + */ + applyITRS: function (x, y, rotation, scaleX, scaleY) + { + var matrix = this.matrix; + + var radianSin = Math.sin(rotation); + var radianCos = Math.cos(rotation); + + // Translate + matrix[4] = x; + matrix[5] = y; + + // Rotate and Scale + matrix[0] = radianCos * scaleX; + matrix[1] = radianSin * scaleX; + matrix[2] = -radianSin * scaleY; + matrix[3] = radianCos * scaleY; + + return this; + }, + + /** + * Takes the `x` and `y` values and returns a new position in the `output` vector that is the inverse of + * the current matrix with its transformation applied. + * + * Can be used to translate points from world to local space. + * + * @method Phaser.GameObjects.Components.TransformMatrix#applyInverse + * @since 3.12.0 + * + * @param {number} x - The x position to translate. + * @param {number} y - The y position to translate. + * @param {Phaser.Math.Vector2} [output] - A Vector2, or point-like object, to store the results in. + * + * @return {Phaser.Math.Vector2} The coordinates, inverse-transformed through this matrix. + */ + applyInverse: function (x, y, output) + { + if (output === undefined) { output = new Vector2(); } + + var matrix = this.matrix; + + var a = matrix[0]; + var b = matrix[1]; + var c = matrix[2]; + var d = matrix[3]; + var tx = matrix[4]; + var ty = matrix[5]; + + var id = 1 / ((a * d) + (c * -b)); + + output.x = (d * id * x) + (-c * id * y) + (((ty * c) - (tx * d)) * id); + output.y = (a * id * y) + (-b * id * x) + (((-ty * a) + (tx * b)) * id); + + return output; + }, + + /** + * Returns the X component of this matrix multiplied by the given values. + * This is the same as `x * a + y * c + e`. + * + * @method Phaser.GameObjects.Components.TransformMatrix#getX + * @since 3.12.0 + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * + * @return {number} The calculated x value. + */ + getX: function (x, y) + { + return x * this.a + y * this.c + this.e; + }, + + /** + * Returns the Y component of this matrix multiplied by the given values. + * This is the same as `x * b + y * d + f`. + * + * @method Phaser.GameObjects.Components.TransformMatrix#getY + * @since 3.12.0 + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * + * @return {number} The calculated y value. + */ + getY: function (x, y) + { + return x * this.b + y * this.d + this.f; + }, + + /** + * Returns a string that can be used in a CSS Transform call as a `matrix` property. + * + * @method Phaser.GameObjects.Components.TransformMatrix#getCSSMatrix + * @since 3.12.0 + * + * @return {string} A string containing the CSS Transform matrix values. + */ + getCSSMatrix: function () + { + var m = this.matrix; + + return 'matrix(' + m[0] + ',' + m[1] + ',' + m[2] + ',' + m[3] + ',' + m[4] + ',' + m[5] + ')'; + }, + + /** + * Destroys this Transform Matrix. + * + * @method Phaser.GameObjects.Components.TransformMatrix#destroy + * @since 3.4.0 + */ + destroy: function () + { + this.matrix = null; + this.decomposedMatrix = null; + } + +}); + +module.exports = TransformMatrix; diff --git a/src/gameobjects/components/Visible.js b/src/gameobjects/components/Visible.js index 6ee626d00..30afebcdf 100644 --- a/src/gameobjects/components/Visible.js +++ b/src/gameobjects/components/Visible.js @@ -1,83 +1,83 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// bitmask flag for GameObject.renderMask -var _FLAG = 1; // 0001 - -/** - * Provides methods used for setting the visibility of a Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.GameObjects.Components.Visible - * @since 3.0.0 - */ - -var Visible = { - - /** - * Private internal value. Holds the visible value. - * - * @name Phaser.GameObjects.Components.Visible#_visible - * @type {boolean} - * @private - * @default true - * @since 3.0.0 - */ - _visible: true, - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * - * @name Phaser.GameObjects.Components.Visible#visible - * @type {boolean} - * @since 3.0.0 - */ - visible: { - - get: function () - { - return this._visible; - }, - - set: function (value) - { - if (value) - { - this._visible = true; - this.renderFlags |= _FLAG; - } - else - { - this._visible = false; - this.renderFlags &= ~_FLAG; - } - } - - }, - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * - * @method Phaser.GameObjects.Components.Visible#setVisible - * @since 3.0.0 - * - * @param {boolean} value - The visible state of the Game Object. - * - * @return {this} This Game Object instance. - */ - setVisible: function (value) - { - this.visible = value; - - return this; - } -}; - -module.exports = Visible; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// bitmask flag for GameObject.renderMask +var _FLAG = 1; // 0001 + +/** + * Provides methods used for setting the visibility of a Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.GameObjects.Components.Visible + * @since 3.0.0 + */ + +var Visible = { + + /** + * Private internal value. Holds the visible value. + * + * @name Phaser.GameObjects.Components.Visible#_visible + * @type {boolean} + * @private + * @default true + * @since 3.0.0 + */ + _visible: true, + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * + * @name Phaser.GameObjects.Components.Visible#visible + * @type {boolean} + * @since 3.0.0 + */ + visible: { + + get: function () + { + return this._visible; + }, + + set: function (value) + { + if (value) + { + this._visible = true; + this.renderFlags |= _FLAG; + } + else + { + this._visible = false; + this.renderFlags &= ~_FLAG; + } + } + + }, + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * + * @method Phaser.GameObjects.Components.Visible#setVisible + * @since 3.0.0 + * + * @param {boolean} value - The visible state of the Game Object. + * + * @return {this} This Game Object instance. + */ + setVisible: function (value) + { + this.visible = value; + + return this; + } +}; + +module.exports = Visible; diff --git a/src/gameobjects/components/index.js b/src/gameobjects/components/index.js index 1a04d2eee..f02cc0927 100644 --- a/src/gameobjects/components/index.js +++ b/src/gameobjects/components/index.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.GameObjects.Components - */ - -module.exports = { - - Alpha: require('./Alpha'), - AlphaSingle: require('./AlphaSingle'), - Animation: require('./Animation'), - BlendMode: require('./BlendMode'), - ComputedSize: require('./ComputedSize'), - Crop: require('./Crop'), - Depth: require('./Depth'), - Flip: require('./Flip'), - GetBounds: require('./GetBounds'), - Mask: require('./Mask'), - Origin: require('./Origin'), - PathFollower: require('./PathFollower'), - Pipeline: require('./Pipeline'), - ScrollFactor: require('./ScrollFactor'), - Size: require('./Size'), - Texture: require('./Texture'), - TextureCrop: require('./TextureCrop'), - Tint: require('./Tint'), - ToJSON: require('./ToJSON'), - Transform: require('./Transform'), - TransformMatrix: require('./TransformMatrix'), - Visible: require('./Visible') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Components + */ + +module.exports = { + + Alpha: require('./Alpha'), + AlphaSingle: require('./AlphaSingle'), + Animation: require('./Animation'), + BlendMode: require('./BlendMode'), + ComputedSize: require('./ComputedSize'), + Crop: require('./Crop'), + Depth: require('./Depth'), + Flip: require('./Flip'), + GetBounds: require('./GetBounds'), + Mask: require('./Mask'), + Origin: require('./Origin'), + PathFollower: require('./PathFollower'), + Pipeline: require('./Pipeline'), + ScrollFactor: require('./ScrollFactor'), + Size: require('./Size'), + Texture: require('./Texture'), + TextureCrop: require('./TextureCrop'), + Tint: require('./Tint'), + ToJSON: require('./ToJSON'), + Transform: require('./Transform'), + TransformMatrix: require('./TransformMatrix'), + Visible: require('./Visible') + +}; diff --git a/src/gameobjects/container/Container.js b/src/gameobjects/container/Container.js index 71479926e..75d503001 100644 --- a/src/gameobjects/container/Container.js +++ b/src/gameobjects/container/Container.js @@ -1,1319 +1,1319 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArrayUtils = require('../../utils/array'); -var BlendModes = require('../../renderer/BlendModes'); -var Class = require('../../utils/Class'); -var Components = require('../components'); -var Events = require('../events'); -var GameObject = require('../GameObject'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var Render = require('./ContainerRender'); -var Union = require('../../geom/rectangle/Union'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Container Game Object. - * - * A Container, as the name implies, can 'contain' other types of Game Object. - * When a Game Object is added to a Container, the Container becomes responsible for the rendering of it. - * By default it will be removed from the Display List and instead added to the Containers own internal list. - * - * The position of the Game Object automatically becomes relative to the position of the Container. - * - * When the Container is rendered, all of its children are rendered as well, in the order in which they exist - * within the Container. Container children can be repositioned using methods such as `MoveUp`, `MoveDown` and `SendToBack`. - * - * If you modify a transform property of the Container, such as `Container.x` or `Container.rotation` then it will - * automatically influence all children as well. - * - * Containers can include other Containers for deeply nested transforms. - * - * Containers can have masks set on them and can be used as a mask too. However, Container children cannot be masked. - * The masks do not 'stack up'. Only a Container on the root of the display list will use its mask. - * - * Containers can be enabled for input. Because they do not have a texture you need to provide a shape for them - * to use as their hit area. Container children can also be enabled for input, independent of the Container. - * - * Containers can be given a physics body for either Arcade Physics, Impact Physics or Matter Physics. However, - * if Container _children_ are enabled for physics you may get unexpected results, such as offset bodies, - * if the Container itself, or any of its ancestors, is positioned anywhere other than at 0 x 0. Container children - * with physics do not factor in the Container due to the excessive extra calculations needed. Please structure - * your game to work around this. - * - * It's important to understand the impact of using Containers. They add additional processing overhead into - * every one of their children. The deeper you nest them, the more the cost escalates. This is especially true - * for input events. You also loose the ability to set the display depth of Container children in the same - * flexible manner as those not within them. In short, don't use them for the sake of it. You pay a small cost - * every time you create one, try to structure your game around avoiding that where possible. - * - * @class Container - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.4.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.ComputedSize - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Mask - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to this Container. - */ -var Container = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.ComputedSize, - Components.Depth, - Components.Mask, - Components.Transform, - Components.Visible, - Render - ], - - initialize: - - function Container (scene, x, y, children) - { - GameObject.call(this, scene, 'Container'); - - /** - * An array holding the children of this Container. - * - * @name Phaser.GameObjects.Container#list - * @type {Phaser.GameObjects.GameObject[]} - * @since 3.4.0 - */ - this.list = []; - - /** - * Does this Container exclusively manage its children? - * - * The default is `true` which means a child added to this Container cannot - * belong in another Container, which includes the Scene display list. - * - * If you disable this then this Container will no longer exclusively manage its children. - * This allows you to create all kinds of interesting graphical effects, such as replicating - * Game Objects without reparenting them all over the Scene. - * However, doing so will prevent children from receiving any kind of input event or have - * their physics bodies work by default, as they're no longer a single entity on the - * display list, but are being replicated where-ever this Container is. - * - * @name Phaser.GameObjects.Container#exclusive - * @type {boolean} - * @default true - * @since 3.4.0 - */ - this.exclusive = true; - - /** - * Containers can have an optional maximum size. If set to anything above 0 it - * will constrict the addition of new Game Objects into the Container, capping off - * the maximum limit the Container can grow in size to. - * - * @name Phaser.GameObjects.Container#maxSize - * @type {integer} - * @default -1 - * @since 3.4.0 - */ - this.maxSize = -1; - - /** - * The cursor position. - * - * @name Phaser.GameObjects.Container#position - * @type {integer} - * @since 3.4.0 - */ - this.position = 0; - - /** - * Internal Transform Matrix used for local space conversion. - * - * @name Phaser.GameObjects.Container#localTransform - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.4.0 - */ - this.localTransform = new Components.TransformMatrix(); - - /** - * Internal temporary Transform Matrix used to avoid object creation. - * - * @name Phaser.GameObjects.Container#tempTransformMatrix - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @private - * @since 3.4.0 - */ - this.tempTransformMatrix = new Components.TransformMatrix(); - - /** - * A reference to the Scene Display List. - * - * @name Phaser.GameObjects.Container#_displayList - * @type {Phaser.GameObjects.DisplayList} - * @private - * @since 3.4.0 - */ - this._displayList = scene.sys.displayList; - - /** - * The property key to sort by. - * - * @name Phaser.GameObjects.Container#_sortKey - * @type {string} - * @private - * @since 3.4.0 - */ - this._sortKey = ''; - - /** - * A reference to the Scene Systems Event Emitter. - * - * @name Phaser.GameObjects.Container#_sysEvents - * @type {Phaser.Events.EventEmitter} - * @private - * @since 3.9.0 - */ - this._sysEvents = scene.sys.events; - - /** - * 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.0.0 - */ - this.scrollFactorX = 1; - - /** - * 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.0.0 - */ - this.scrollFactorY = 1; - - this.setPosition(x, y); - - this.clearAlpha(); - - this.setBlendMode(BlendModes.SKIP_CHECK); - - if (children) - { - this.add(children); - } - }, - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - * - * @name Phaser.GameObjects.Container#originX - * @type {number} - * @readonly - * @since 3.4.0 - */ - originX: { - - get: function () - { - return 0.5; - } - - }, - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - * - * @name Phaser.GameObjects.Container#originY - * @type {number} - * @readonly - * @since 3.4.0 - */ - originY: { - - get: function () - { - return 0.5; - } - - }, - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - * - * @name Phaser.GameObjects.Container#displayOriginX - * @type {number} - * @readonly - * @since 3.4.0 - */ - displayOriginX: { - - get: function () - { - return this.width * 0.5; - } - - }, - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - * - * @name Phaser.GameObjects.Container#displayOriginY - * @type {number} - * @readonly - * @since 3.4.0 - */ - displayOriginY: { - - get: function () - { - return this.height * 0.5; - } - - }, - - /** - * Does this Container exclusively manage its children? - * - * The default is `true` which means a child added to this Container cannot - * belong in another Container, which includes the Scene display list. - * - * If you disable this then this Container will no longer exclusively manage its children. - * This allows you to create all kinds of interesting graphical effects, such as replicating - * Game Objects without reparenting them all over the Scene. - * However, doing so will prevent children from receiving any kind of input event or have - * their physics bodies work by default, as they're no longer a single entity on the - * display list, but are being replicated where-ever this Container is. - * - * @method Phaser.GameObjects.Container#setExclusive - * @since 3.4.0 - * - * @param {boolean} [value=true] - The exclusive state of this Container. - * - * @return {this} This Container. - */ - setExclusive: function (value) - { - if (value === undefined) { value = true; } - - this.exclusive = value; - - return this; - }, - - /** - * Gets the bounds of this Container. It works by iterating all children of the Container, - * getting their respective bounds, and then working out a min-max rectangle from that. - * It does not factor in if the children render or not, all are included. - * - * Some children are unable to return their bounds, such as Graphics objects, in which case - * they are skipped. - * - * Depending on the quantity of children in this Container it could be a really expensive call, - * so cache it and only poll it as needed. - * - * The values are stored and returned in a Rectangle object. - * - * @method Phaser.GameObjects.Container#getBounds - * @since 3.4.0 - * - * @param {Phaser.Geom.Rectangle} [output] - A Geom.Rectangle object to store the values in. If not provided a new Rectangle will be created. - * - * @return {Phaser.Geom.Rectangle} The values stored in the output object. - */ - getBounds: function (output) - { - if (output === undefined) { output = new Rectangle(); } - - output.setTo(this.x, this.y, 0, 0); - - if (this.list.length > 0) - { - var children = this.list; - var tempRect = new Rectangle(); - - for (var i = 0; i < children.length; i++) - { - var entry = children[i]; - - if (entry.getBounds) - { - entry.getBounds(tempRect); - - Union(tempRect, output, output); - } - } - } - - return output; - }, - - /** - * Internal add handler. - * - * @method Phaser.GameObjects.Container#addHandler - * @private - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that was just added to this Container. - */ - addHandler: function (gameObject) - { - gameObject.once(Events.DESTROY, this.remove, this); - - if (this.exclusive) - { - this._displayList.remove(gameObject); - - if (gameObject.parentContainer) - { - gameObject.parentContainer.remove(gameObject); - } - - gameObject.parentContainer = this; - } - }, - - /** - * Internal remove handler. - * - * @method Phaser.GameObjects.Container#removeHandler - * @private - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that was just removed from this Container. - */ - removeHandler: function (gameObject) - { - gameObject.off(Events.DESTROY, this.remove); - - if (this.exclusive) - { - gameObject.parentContainer = null; - } - }, - - /** - * Takes a Point-like object, such as a Vector2, Geom.Point or object with public x and y properties, - * and transforms it into the space of this Container, then returns it in the output object. - * - * @method Phaser.GameObjects.Container#pointToContainer - * @since 3.4.0 - * - * @param {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} source - The Source Point to be transformed. - * @param {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} [output] - A destination object to store the transformed point in. If none given a Vector2 will be created and returned. - * - * @return {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} The transformed point. - */ - pointToContainer: function (source, output) - { - if (output === undefined) { output = new Vector2(); } - - if (this.parentContainer) - { - return this.parentContainer.pointToContainer(source, output); - } - - var tempMatrix = this.tempTransformMatrix; - - // No need to loadIdentity because applyITRS overwrites every value anyway - tempMatrix.applyITRS(this.x, this.y, this.rotation, this.scaleX, this.scaleY); - - tempMatrix.invert(); - - tempMatrix.transformPoint(source.x, source.y, output); - - return output; - }, - - /** - * Returns the world transform matrix as used for Bounds checks. - * - * The returned matrix is temporal and shouldn't be stored. - * - * @method Phaser.GameObjects.Container#getBoundsTransformMatrix - * @since 3.4.0 - * - * @return {Phaser.GameObjects.Components.TransformMatrix} The world transform matrix. - */ - getBoundsTransformMatrix: function () - { - return this.getWorldTransformMatrix(this.tempTransformMatrix, this.localTransform); - }, - - /** - * Adds the given Game Object, or array of Game Objects, to this Container. - * - * Each Game Object must be unique within the Container. - * - * @method Phaser.GameObjects.Container#add - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. - * - * @return {this} This Container instance. - */ - add: function (child) - { - ArrayUtils.Add(this.list, child, this.maxSize, this.addHandler, this); - - return this; - }, - - /** - * Adds the given Game Object, or array of Game Objects, to this Container at the specified position. - * - * Existing Game Objects in the Container are shifted up. - * - * Each Game Object must be unique within the Container. - * - * @method Phaser.GameObjects.Container#addAt - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. - * @param {integer} [index=0] - The position to insert the Game Object/s at. - * - * @return {this} This Container instance. - */ - addAt: function (child, index) - { - ArrayUtils.AddAt(this.list, child, index, this.maxSize, this.addHandler, this); - - return this; - }, - - /** - * Returns the Game Object at the given position in this Container. - * - * @method Phaser.GameObjects.Container#getAt - * @since 3.4.0 - * - * @param {integer} index - The position to get the Game Object from. - * - * @return {?Phaser.GameObjects.GameObject} The Game Object at the specified index, or `null` if none found. - */ - getAt: function (index) - { - return this.list[index]; - }, - - /** - * Returns the index of the given Game Object in this Container. - * - * @method Phaser.GameObjects.Container#getIndex - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to search for in this Container. - * - * @return {integer} The index of the Game Object in this Container, or -1 if not found. - */ - getIndex: function (child) - { - return this.list.indexOf(child); - }, - - /** - * 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 boolean. - * - * @return {this} This Container instance. - */ - sort: function (property, handler) - { - if (!property) - { - return this; - } - - if (handler === undefined) - { - handler = function (childA, childB) - { - return childA[property] - childB[property]; - }; - } - - ArrayUtils.StableSort.inplace(this.list, handler); - - return this; - }, - - /** - * Searches for the first instance of a child with its `name` property matching the given argument. - * Should more than one child have the same name only the first is returned. - * - * @method Phaser.GameObjects.Container#getByName - * @since 3.4.0 - * - * @param {string} name - The name to search for. - * - * @return {?Phaser.GameObjects.GameObject} The first child with a matching name, or `null` if none were found. - */ - getByName: function (name) - { - return ArrayUtils.GetFirst(this.list, 'name', name); - }, - - /** - * Returns a random Game Object from this Container. - * - * @method Phaser.GameObjects.Container#getRandom - * @since 3.4.0 - * - * @param {integer} [startIndex=0] - An optional start index. - * @param {integer} [length] - An optional length, the total number of elements (from the startIndex) to choose from. - * - * @return {?Phaser.GameObjects.GameObject} A random child from the Container, or `null` if the Container is empty. - */ - getRandom: function (startIndex, length) - { - return ArrayUtils.GetRandom(this.list, startIndex, length); - }, - - /** - * Gets the first Game Object in this Container. - * - * You can also specify a property and value to search for, in which case it will return the first - * Game Object in this Container with a matching property and / or value. - * - * For example: `getFirst('visible', true)` would return the first Game Object that had its `visible` property set. - * - * You can limit the search to the `startIndex` - `endIndex` range. - * - * @method Phaser.GameObjects.Container#getFirst - * @since 3.4.0 - * - * @param {string} property - The property to test on each Game Object in the Container. - * @param {*} value - The value to test the property against. Must pass a strict (`===`) comparison check. - * @param {integer} [startIndex=0] - An optional start index to search from. - * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) - * - * @return {?Phaser.GameObjects.GameObject} The first matching Game Object, or `null` if none was found. - */ - getFirst: function (property, value, startIndex, endIndex) - { - return ArrayUtils.GetFirst(this.list, property, value, startIndex, endIndex); - }, - - /** - * Returns all Game Objects in this Container. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('body')` would return only Game Objects that have a body property. - * - * You can also specify a value to compare the property to: - * - * `getAll('visible', true)` would return only Game Objects that have their visible property set to `true`. - * - * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 Game Objects. - * - * @method Phaser.GameObjects.Container#getAll - * @since 3.4.0 - * - * @param {string} [property] - The property to test on each Game Object in the Container. - * @param {any} [value] - If property is set then the `property` must strictly equal this value to be included in the results. - * @param {integer} [startIndex=0] - An optional start index to search from. - * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) - * - * @return {Phaser.GameObjects.GameObject[]} An array of matching Game Objects from this Container. - */ - getAll: function (property, value, startIndex, endIndex) - { - return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex); - }, - - /** - * Returns the total number of Game Objects in this Container that have a property - * matching the given value. - * - * For example: `count('visible', true)` would count all the elements that have their visible property set. - * - * You can optionally limit the operation to the `startIndex` - `endIndex` range. - * - * @method Phaser.GameObjects.Container#count - * @since 3.4.0 - * - * @param {string} property - The property to check. - * @param {any} value - The value to check. - * @param {integer} [startIndex=0] - An optional start index to search from. - * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) - * - * @return {integer} The total number of Game Objects in this Container with a property matching the given value. - */ - count: function (property, value, startIndex, endIndex) - { - return ArrayUtils.CountAllMatching(this.list, property, value, startIndex, endIndex); - }, - - /** - * Swaps the position of two Game Objects in this Container. - * Both Game Objects must belong to this Container. - * - * @method Phaser.GameObjects.Container#swap - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child1 - The first Game Object to swap. - * @param {Phaser.GameObjects.GameObject} child2 - The second Game Object to swap. - * - * @return {this} This Container instance. - */ - swap: function (child1, child2) - { - ArrayUtils.Swap(this.list, child1, child2); - - return this; - }, - - /** - * Moves a Game Object to a new position within this Container. - * - * The Game Object must already be a child of this Container. - * - * The Game Object is removed from its old position and inserted into the new one. - * Therefore the Container size does not change. Other children will change position accordingly. - * - * @method Phaser.GameObjects.Container#moveTo - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to move. - * @param {integer} index - The new position of the Game Object in this Container. - * - * @return {this} This Container instance. - */ - moveTo: function (child, index) - { - ArrayUtils.MoveTo(this.list, child, index); - - return this; - }, - - /** - * Removes the given Game Object, or array of Game Objects, from this Container. - * - * The Game Objects must already be children of this Container. - * - * You can also optionally call `destroy` on each Game Object that is removed from the Container. - * - * @method Phaser.GameObjects.Container#remove - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to be removed from the Container. - * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each child successfully removed from this Container. - * - * @return {this} This Container instance. - */ - remove: function (child, destroyChild) - { - var removed = ArrayUtils.Remove(this.list, child, this.removeHandler, this); - - if (destroyChild && removed) - { - if (!Array.isArray(removed)) - { - removed = [ removed ]; - } - - for (var i = 0; i < removed.length; i++) - { - removed[i].destroy(); - } - } - - return this; - }, - - /** - * Removes the Game Object at the given position in this Container. - * - * You can also optionally call `destroy` on the Game Object, if one is found. - * - * @method Phaser.GameObjects.Container#removeAt - * @since 3.4.0 - * - * @param {integer} index - The index of the Game Object to be removed. - * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. - * - * @return {this} This Container instance. - */ - removeAt: function (index, destroyChild) - { - var removed = ArrayUtils.RemoveAt(this.list, index, this.removeHandler, this); - - if (destroyChild && removed) - { - removed.destroy(); - } - - return this; - }, - - /** - * Removes the Game Objects between the given positions in this Container. - * - * You can also optionally call `destroy` on each Game Object that is removed from the Container. - * - * @method Phaser.GameObjects.Container#removeBetween - * @since 3.4.0 - * - * @param {integer} [startIndex=0] - An optional start index to search from. - * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) - * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. - * - * @return {this} This Container instance. - */ - removeBetween: function (startIndex, endIndex, destroyChild) - { - var removed = ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeHandler, this); - - if (destroyChild) - { - for (var i = 0; i < removed.length; i++) - { - removed[i].destroy(); - } - } - - return this; - }, - - /** - * Removes all Game Objects from this Container. - * - * You can also optionally call `destroy` on each Game Object that is removed from the Container. - * - * @method Phaser.GameObjects.Container#removeAll - * @since 3.4.0 - * - * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. - * - * @return {this} This Container instance. - */ - removeAll: function (destroyChild) - { - var removed = ArrayUtils.RemoveBetween(this.list, 0, this.list.length, this.removeHandler, this); - - if (destroyChild) - { - for (var i = 0; i < removed.length; i++) - { - removed[i].destroy(); - } - } - - return this; - }, - - /** - * Brings the given Game Object to the top of this Container. - * This will cause it to render on-top of any other objects in the Container. - * - * @method Phaser.GameObjects.Container#bringToTop - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to bring to the top of the Container. - * - * @return {this} This Container instance. - */ - bringToTop: function (child) - { - ArrayUtils.BringToTop(this.list, child); - - return this; - }, - - /** - * Sends the given Game Object to the bottom of this Container. - * This will cause it to render below any other objects in the Container. - * - * @method Phaser.GameObjects.Container#sendToBack - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to send to the bottom of the Container. - * - * @return {this} This Container instance. - */ - sendToBack: function (child) - { - ArrayUtils.SendToBack(this.list, child); - - return this; - }, - - /** - * Moves the given Game Object up one place in this Container, unless it's already at the top. - * - * @method Phaser.GameObjects.Container#moveUp - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. - * - * @return {this} This Container instance. - */ - moveUp: function (child) - { - ArrayUtils.MoveUp(this.list, child); - - return this; - }, - - /** - * Moves the given Game Object down one place in this Container, unless it's already at the bottom. - * - * @method Phaser.GameObjects.Container#moveDown - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. - * - * @return {this} This Container instance. - */ - moveDown: function (child) - { - ArrayUtils.MoveDown(this.list, child); - - return this; - }, - - /** - * Reverses the order of all Game Objects in this Container. - * - * @method Phaser.GameObjects.Container#reverse - * @since 3.4.0 - * - * @return {this} This Container instance. - */ - reverse: function () - { - this.list.reverse(); - - return this; - }, - - /** - * Shuffles the all Game Objects in this Container using the Fisher-Yates implementation. - * - * @method Phaser.GameObjects.Container#shuffle - * @since 3.4.0 - * - * @return {this} This Container instance. - */ - shuffle: function () - { - ArrayUtils.Shuffle(this.list); - - return this; - }, - - /** - * Replaces a Game Object in this Container with the new Game Object. - * The new Game Object cannot already be a child of this Container. - * - * @method Phaser.GameObjects.Container#replace - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} oldChild - The Game Object in this Container that will be replaced. - * @param {Phaser.GameObjects.GameObject} newChild - The Game Object to be added to this Container. - * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. - * - * @return {this} This Container instance. - */ - replace: function (oldChild, newChild, destroyChild) - { - var moved = ArrayUtils.Replace(this.list, oldChild, newChild); - - if (moved) - { - this.addHandler(newChild); - this.removeHandler(oldChild); - - if (destroyChild) - { - oldChild.destroy(); - } - } - - return this; - }, - - /** - * Returns `true` if the given Game Object is a direct child of this Container. - * - * This check does not scan nested Containers. - * - * @method Phaser.GameObjects.Container#exists - * @since 3.4.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to check for within this Container. - * - * @return {boolean} True if the Game Object is an immediate child of this Container, otherwise false. - */ - exists: function (child) - { - return (this.list.indexOf(child) > -1); - }, - - /** - * Sets the property to the given value on all Game Objects in this Container. - * - * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 Game Objects. - * - * @method Phaser.GameObjects.Container#setAll - * @since 3.4.0 - * - * @param {string} property - The property that must exist on the Game Object. - * @param {any} value - The value to get the property to. - * @param {integer} [startIndex=0] - An optional start index to search from. - * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) - * - * @return {this} This Container instance. - */ - setAll: function (property, value, startIndex, endIndex) - { - ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); - - return this; - }, - - /** - * @callback EachContainerCallback - * @generic I - [item] - * - * @param {*} item - The child Game Object of the Container. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - */ - - /** - * Passes all Game Objects in this Container to the given callback. - * - * A copy of the Container is made before passing each entry to your callback. - * This protects against the callback itself modifying the Container. - * - * If you know for sure that the callback will not change the size of this Container - * then you can use the more performant `Container.iterate` method instead. - * - * @method Phaser.GameObjects.Container#each - * @since 3.4.0 - * - * @param {function} callback - The function to call. - * @param {object} [context] - Value to use as `this` when executing callback. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - * - * @return {this} This Container instance. - */ - each: function (callback, context) - { - var args = [ null ]; - var i; - var temp = this.list.slice(); - var len = temp.length; - - for (i = 2; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (i = 0; i < len; i++) - { - args[0] = temp[i]; - - callback.apply(context, args); - } - - return this; - }, - - /** - * Passes all Game Objects in this Container to the given callback. - * - * Only use this method when you absolutely know that the Container will not be modified during - * the iteration, i.e. by removing or adding to its contents. - * - * @method Phaser.GameObjects.Container#iterate - * @since 3.4.0 - * - * @param {function} callback - The function to call. - * @param {object} [context] - Value to use as `this` when executing callback. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - * - * @return {this} This Container instance. - */ - iterate: function (callback, context) - { - var args = [ null ]; - var i; - - for (i = 2; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (i = 0; i < this.list.length; i++) - { - args[0] = this.list[i]; - - callback.apply(context, args); - } - - return this; - }, - - /** - * 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.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. - * @param {boolean} [updateChildren=false] - Apply this scrollFactor to all Container children as well? - * - * @return {this} This Game Object instance. - */ - setScrollFactor: function (x, y, updateChildren) - { - if (y === undefined) { y = x; } - if (updateChildren === undefined) { updateChildren = false; } - - this.scrollFactorX = x; - this.scrollFactorY = y; - - if (updateChildren) - { - ArrayUtils.SetAll(this.list, 'scrollFactorX', x); - ArrayUtils.SetAll(this.list, 'scrollFactorY', y); - } - - return this; - }, - - /** - * The number of Game Objects inside this Container. - * - * @name Phaser.GameObjects.Container#length - * @type {integer} - * @readonly - * @since 3.4.0 - */ - length: { - - get: function () - { - return this.list.length; - } - - }, - - /** - * Returns the first Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - * - * @name Phaser.GameObjects.Container#first - * @type {?Phaser.GameObjects.GameObject} - * @readonly - * @since 3.4.0 - */ - first: { - - get: function () - { - this.position = 0; - - if (this.list.length > 0) - { - return this.list[0]; - } - else - { - return null; - } - } - - }, - - /** - * Returns the last Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - * - * @name Phaser.GameObjects.Container#last - * @type {?Phaser.GameObjects.GameObject} - * @readonly - * @since 3.4.0 - */ - last: { - - get: function () - { - if (this.list.length > 0) - { - this.position = this.list.length - 1; - - return this.list[this.position]; - } - else - { - return null; - } - } - - }, - - /** - * Returns the next Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - * - * @name Phaser.GameObjects.Container#next - * @type {?Phaser.GameObjects.GameObject} - * @readonly - * @since 3.4.0 - */ - next: { - - get: function () - { - if (this.position < this.list.length) - { - this.position++; - - return this.list[this.position]; - } - else - { - return null; - } - } - - }, - - /** - * Returns the previous Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - * - * @name Phaser.GameObjects.Container#previous - * @type {?Phaser.GameObjects.GameObject} - * @readonly - * @since 3.4.0 - */ - previous: { - - get: function () - { - if (this.position > 0) - { - this.position--; - - return this.list[this.position]; - } - else - { - return null; - } - } - - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Container#preDestroy - * @protected - * @since 3.9.0 - */ - preDestroy: function () - { - this.removeAll(!!this.exclusive); - - this.localTransform.destroy(); - this.tempTransformMatrix.destroy(); - - this.list = []; - this._displayList = null; - } - -}); - -module.exports = Container; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayUtils = require('../../utils/array'); +var BlendModes = require('../../renderer/BlendModes'); +var Class = require('../../utils/Class'); +var Components = require('../components'); +var Events = require('../events'); +var GameObject = require('../GameObject'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var Render = require('./ContainerRender'); +var Union = require('../../geom/rectangle/Union'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Container Game Object. + * + * A Container, as the name implies, can 'contain' other types of Game Object. + * When a Game Object is added to a Container, the Container becomes responsible for the rendering of it. + * By default it will be removed from the Display List and instead added to the Containers own internal list. + * + * The position of the Game Object automatically becomes relative to the position of the Container. + * + * When the Container is rendered, all of its children are rendered as well, in the order in which they exist + * within the Container. Container children can be repositioned using methods such as `MoveUp`, `MoveDown` and `SendToBack`. + * + * If you modify a transform property of the Container, such as `Container.x` or `Container.rotation` then it will + * automatically influence all children as well. + * + * Containers can include other Containers for deeply nested transforms. + * + * Containers can have masks set on them and can be used as a mask too. However, Container children cannot be masked. + * The masks do not 'stack up'. Only a Container on the root of the display list will use its mask. + * + * Containers can be enabled for input. Because they do not have a texture you need to provide a shape for them + * to use as their hit area. Container children can also be enabled for input, independent of the Container. + * + * Containers can be given a physics body for either Arcade Physics, Impact Physics or Matter Physics. However, + * if Container _children_ are enabled for physics you may get unexpected results, such as offset bodies, + * if the Container itself, or any of its ancestors, is positioned anywhere other than at 0 x 0. Container children + * with physics do not factor in the Container due to the excessive extra calculations needed. Please structure + * your game to work around this. + * + * It's important to understand the impact of using Containers. They add additional processing overhead into + * every one of their children. The deeper you nest them, the more the cost escalates. This is especially true + * for input events. You also loose the ability to set the display depth of Container children in the same + * flexible manner as those not within them. In short, don't use them for the sake of it. You pay a small cost + * every time you create one, try to structure your game around avoiding that where possible. + * + * @class Container + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.4.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Mask + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to this Container. + */ +var Container = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.Mask, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + function Container (scene, x, y, children) + { + GameObject.call(this, scene, 'Container'); + + /** + * An array holding the children of this Container. + * + * @name Phaser.GameObjects.Container#list + * @type {Phaser.GameObjects.GameObject[]} + * @since 3.4.0 + */ + this.list = []; + + /** + * Does this Container exclusively manage its children? + * + * The default is `true` which means a child added to this Container cannot + * belong in another Container, which includes the Scene display list. + * + * If you disable this then this Container will no longer exclusively manage its children. + * This allows you to create all kinds of interesting graphical effects, such as replicating + * Game Objects without reparenting them all over the Scene. + * However, doing so will prevent children from receiving any kind of input event or have + * their physics bodies work by default, as they're no longer a single entity on the + * display list, but are being replicated where-ever this Container is. + * + * @name Phaser.GameObjects.Container#exclusive + * @type {boolean} + * @default true + * @since 3.4.0 + */ + this.exclusive = true; + + /** + * Containers can have an optional maximum size. If set to anything above 0 it + * will constrict the addition of new Game Objects into the Container, capping off + * the maximum limit the Container can grow in size to. + * + * @name Phaser.GameObjects.Container#maxSize + * @type {integer} + * @default -1 + * @since 3.4.0 + */ + this.maxSize = -1; + + /** + * The cursor position. + * + * @name Phaser.GameObjects.Container#position + * @type {integer} + * @since 3.4.0 + */ + this.position = 0; + + /** + * Internal Transform Matrix used for local space conversion. + * + * @name Phaser.GameObjects.Container#localTransform + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.4.0 + */ + this.localTransform = new Components.TransformMatrix(); + + /** + * Internal temporary Transform Matrix used to avoid object creation. + * + * @name Phaser.GameObjects.Container#tempTransformMatrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.4.0 + */ + this.tempTransformMatrix = new Components.TransformMatrix(); + + /** + * A reference to the Scene Display List. + * + * @name Phaser.GameObjects.Container#_displayList + * @type {Phaser.GameObjects.DisplayList} + * @private + * @since 3.4.0 + */ + this._displayList = scene.sys.displayList; + + /** + * The property key to sort by. + * + * @name Phaser.GameObjects.Container#_sortKey + * @type {string} + * @private + * @since 3.4.0 + */ + this._sortKey = ''; + + /** + * A reference to the Scene Systems Event Emitter. + * + * @name Phaser.GameObjects.Container#_sysEvents + * @type {Phaser.Events.EventEmitter} + * @private + * @since 3.9.0 + */ + this._sysEvents = scene.sys.events; + + /** + * 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.0.0 + */ + this.scrollFactorX = 1; + + /** + * 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.0.0 + */ + this.scrollFactorY = 1; + + this.setPosition(x, y); + + this.clearAlpha(); + + this.setBlendMode(BlendModes.SKIP_CHECK); + + if (children) + { + this.add(children); + } + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#originX + * @type {number} + * @readonly + * @since 3.4.0 + */ + originX: { + + get: function () + { + return 0.5; + } + + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#originY + * @type {number} + * @readonly + * @since 3.4.0 + */ + originY: { + + get: function () + { + return 0.5; + } + + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#displayOriginX + * @type {number} + * @readonly + * @since 3.4.0 + */ + displayOriginX: { + + get: function () + { + return this.width * 0.5; + } + + }, + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + * + * @name Phaser.GameObjects.Container#displayOriginY + * @type {number} + * @readonly + * @since 3.4.0 + */ + displayOriginY: { + + get: function () + { + return this.height * 0.5; + } + + }, + + /** + * Does this Container exclusively manage its children? + * + * The default is `true` which means a child added to this Container cannot + * belong in another Container, which includes the Scene display list. + * + * If you disable this then this Container will no longer exclusively manage its children. + * This allows you to create all kinds of interesting graphical effects, such as replicating + * Game Objects without reparenting them all over the Scene. + * However, doing so will prevent children from receiving any kind of input event or have + * their physics bodies work by default, as they're no longer a single entity on the + * display list, but are being replicated where-ever this Container is. + * + * @method Phaser.GameObjects.Container#setExclusive + * @since 3.4.0 + * + * @param {boolean} [value=true] - The exclusive state of this Container. + * + * @return {this} This Container. + */ + setExclusive: function (value) + { + if (value === undefined) { value = true; } + + this.exclusive = value; + + return this; + }, + + /** + * Gets the bounds of this Container. It works by iterating all children of the Container, + * getting their respective bounds, and then working out a min-max rectangle from that. + * It does not factor in if the children render or not, all are included. + * + * Some children are unable to return their bounds, such as Graphics objects, in which case + * they are skipped. + * + * Depending on the quantity of children in this Container it could be a really expensive call, + * so cache it and only poll it as needed. + * + * The values are stored and returned in a Rectangle object. + * + * @method Phaser.GameObjects.Container#getBounds + * @since 3.4.0 + * + * @param {Phaser.Geom.Rectangle} [output] - A Geom.Rectangle object to store the values in. If not provided a new Rectangle will be created. + * + * @return {Phaser.Geom.Rectangle} The values stored in the output object. + */ + getBounds: function (output) + { + if (output === undefined) { output = new Rectangle(); } + + output.setTo(this.x, this.y, 0, 0); + + if (this.list.length > 0) + { + var children = this.list; + var tempRect = new Rectangle(); + + for (var i = 0; i < children.length; i++) + { + var entry = children[i]; + + if (entry.getBounds) + { + entry.getBounds(tempRect); + + Union(tempRect, output, output); + } + } + } + + return output; + }, + + /** + * Internal add handler. + * + * @method Phaser.GameObjects.Container#addHandler + * @private + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that was just added to this Container. + */ + addHandler: function (gameObject) + { + gameObject.once(Events.DESTROY, this.remove, this); + + if (this.exclusive) + { + this._displayList.remove(gameObject); + + if (gameObject.parentContainer) + { + gameObject.parentContainer.remove(gameObject); + } + + gameObject.parentContainer = this; + } + }, + + /** + * Internal remove handler. + * + * @method Phaser.GameObjects.Container#removeHandler + * @private + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that was just removed from this Container. + */ + removeHandler: function (gameObject) + { + gameObject.off(Events.DESTROY, this.remove); + + if (this.exclusive) + { + gameObject.parentContainer = null; + } + }, + + /** + * Takes a Point-like object, such as a Vector2, Geom.Point or object with public x and y properties, + * and transforms it into the space of this Container, then returns it in the output object. + * + * @method Phaser.GameObjects.Container#pointToContainer + * @since 3.4.0 + * + * @param {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} source - The Source Point to be transformed. + * @param {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} [output] - A destination object to store the transformed point in. If none given a Vector2 will be created and returned. + * + * @return {(object|Phaser.Geom.Point|Phaser.Math.Vector2)} The transformed point. + */ + pointToContainer: function (source, output) + { + if (output === undefined) { output = new Vector2(); } + + if (this.parentContainer) + { + return this.parentContainer.pointToContainer(source, output); + } + + var tempMatrix = this.tempTransformMatrix; + + // No need to loadIdentity because applyITRS overwrites every value anyway + tempMatrix.applyITRS(this.x, this.y, this.rotation, this.scaleX, this.scaleY); + + tempMatrix.invert(); + + tempMatrix.transformPoint(source.x, source.y, output); + + return output; + }, + + /** + * Returns the world transform matrix as used for Bounds checks. + * + * The returned matrix is temporal and shouldn't be stored. + * + * @method Phaser.GameObjects.Container#getBoundsTransformMatrix + * @since 3.4.0 + * + * @return {Phaser.GameObjects.Components.TransformMatrix} The world transform matrix. + */ + getBoundsTransformMatrix: function () + { + return this.getWorldTransformMatrix(this.tempTransformMatrix, this.localTransform); + }, + + /** + * Adds the given Game Object, or array of Game Objects, to this Container. + * + * Each Game Object must be unique within the Container. + * + * @method Phaser.GameObjects.Container#add + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. + * + * @return {this} This Container instance. + */ + add: function (child) + { + ArrayUtils.Add(this.list, child, this.maxSize, this.addHandler, this); + + return this; + }, + + /** + * Adds the given Game Object, or array of Game Objects, to this Container at the specified position. + * + * Existing Game Objects in the Container are shifted up. + * + * Each Game Object must be unique within the Container. + * + * @method Phaser.GameObjects.Container#addAt + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to add to the Container. + * @param {integer} [index=0] - The position to insert the Game Object/s at. + * + * @return {this} This Container instance. + */ + addAt: function (child, index) + { + ArrayUtils.AddAt(this.list, child, index, this.maxSize, this.addHandler, this); + + return this; + }, + + /** + * Returns the Game Object at the given position in this Container. + * + * @method Phaser.GameObjects.Container#getAt + * @since 3.4.0 + * + * @param {integer} index - The position to get the Game Object from. + * + * @return {?Phaser.GameObjects.GameObject} The Game Object at the specified index, or `null` if none found. + */ + getAt: function (index) + { + return this.list[index]; + }, + + /** + * Returns the index of the given Game Object in this Container. + * + * @method Phaser.GameObjects.Container#getIndex + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to search for in this Container. + * + * @return {integer} The index of the Game Object in this Container, or -1 if not found. + */ + getIndex: function (child) + { + return this.list.indexOf(child); + }, + + /** + * 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 boolean. + * + * @return {this} This Container instance. + */ + sort: function (property, handler) + { + if (!property) + { + return this; + } + + if (handler === undefined) + { + handler = function (childA, childB) + { + return childA[property] - childB[property]; + }; + } + + ArrayUtils.StableSort.inplace(this.list, handler); + + return this; + }, + + /** + * Searches for the first instance of a child with its `name` property matching the given argument. + * Should more than one child have the same name only the first is returned. + * + * @method Phaser.GameObjects.Container#getByName + * @since 3.4.0 + * + * @param {string} name - The name to search for. + * + * @return {?Phaser.GameObjects.GameObject} The first child with a matching name, or `null` if none were found. + */ + getByName: function (name) + { + return ArrayUtils.GetFirst(this.list, 'name', name); + }, + + /** + * Returns a random Game Object from this Container. + * + * @method Phaser.GameObjects.Container#getRandom + * @since 3.4.0 + * + * @param {integer} [startIndex=0] - An optional start index. + * @param {integer} [length] - An optional length, the total number of elements (from the startIndex) to choose from. + * + * @return {?Phaser.GameObjects.GameObject} A random child from the Container, or `null` if the Container is empty. + */ + getRandom: function (startIndex, length) + { + return ArrayUtils.GetRandom(this.list, startIndex, length); + }, + + /** + * Gets the first Game Object in this Container. + * + * You can also specify a property and value to search for, in which case it will return the first + * Game Object in this Container with a matching property and / or value. + * + * For example: `getFirst('visible', true)` would return the first Game Object that had its `visible` property set. + * + * You can limit the search to the `startIndex` - `endIndex` range. + * + * @method Phaser.GameObjects.Container#getFirst + * @since 3.4.0 + * + * @param {string} property - The property to test on each Game Object in the Container. + * @param {*} value - The value to test the property against. Must pass a strict (`===`) comparison check. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {?Phaser.GameObjects.GameObject} The first matching Game Object, or `null` if none was found. + */ + getFirst: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetFirst(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns all Game Objects in this Container. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('body')` would return only Game Objects that have a body property. + * + * You can also specify a value to compare the property to: + * + * `getAll('visible', true)` would return only Game Objects that have their visible property set to `true`. + * + * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 Game Objects. + * + * @method Phaser.GameObjects.Container#getAll + * @since 3.4.0 + * + * @param {string} [property] - The property to test on each Game Object in the Container. + * @param {any} [value] - If property is set then the `property` must strictly equal this value to be included in the results. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {Phaser.GameObjects.GameObject[]} An array of matching Game Objects from this Container. + */ + getAll: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns the total number of Game Objects in this Container that have a property + * matching the given value. + * + * For example: `count('visible', true)` would count all the elements that have their visible property set. + * + * You can optionally limit the operation to the `startIndex` - `endIndex` range. + * + * @method Phaser.GameObjects.Container#count + * @since 3.4.0 + * + * @param {string} property - The property to check. + * @param {any} value - The value to check. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {integer} The total number of Game Objects in this Container with a property matching the given value. + */ + count: function (property, value, startIndex, endIndex) + { + return ArrayUtils.CountAllMatching(this.list, property, value, startIndex, endIndex); + }, + + /** + * Swaps the position of two Game Objects in this Container. + * Both Game Objects must belong to this Container. + * + * @method Phaser.GameObjects.Container#swap + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child1 - The first Game Object to swap. + * @param {Phaser.GameObjects.GameObject} child2 - The second Game Object to swap. + * + * @return {this} This Container instance. + */ + swap: function (child1, child2) + { + ArrayUtils.Swap(this.list, child1, child2); + + return this; + }, + + /** + * Moves a Game Object to a new position within this Container. + * + * The Game Object must already be a child of this Container. + * + * The Game Object is removed from its old position and inserted into the new one. + * Therefore the Container size does not change. Other children will change position accordingly. + * + * @method Phaser.GameObjects.Container#moveTo + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to move. + * @param {integer} index - The new position of the Game Object in this Container. + * + * @return {this} This Container instance. + */ + moveTo: function (child, index) + { + ArrayUtils.MoveTo(this.list, child, index); + + return this; + }, + + /** + * Removes the given Game Object, or array of Game Objects, from this Container. + * + * The Game Objects must already be children of this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * + * @method Phaser.GameObjects.Container#remove + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} child - The Game Object, or array of Game Objects, to be removed from the Container. + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each child successfully removed from this Container. + * + * @return {this} This Container instance. + */ + remove: function (child, destroyChild) + { + var removed = ArrayUtils.Remove(this.list, child, this.removeHandler, this); + + if (destroyChild && removed) + { + if (!Array.isArray(removed)) + { + removed = [ removed ]; + } + + for (var i = 0; i < removed.length; i++) + { + removed[i].destroy(); + } + } + + return this; + }, + + /** + * Removes the Game Object at the given position in this Container. + * + * You can also optionally call `destroy` on the Game Object, if one is found. + * + * @method Phaser.GameObjects.Container#removeAt + * @since 3.4.0 + * + * @param {integer} index - The index of the Game Object to be removed. + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. + * + * @return {this} This Container instance. + */ + removeAt: function (index, destroyChild) + { + var removed = ArrayUtils.RemoveAt(this.list, index, this.removeHandler, this); + + if (destroyChild && removed) + { + removed.destroy(); + } + + return this; + }, + + /** + * Removes the Game Objects between the given positions in this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * + * @method Phaser.GameObjects.Container#removeBetween + * @since 3.4.0 + * + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. + * + * @return {this} This Container instance. + */ + removeBetween: function (startIndex, endIndex, destroyChild) + { + var removed = ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeHandler, this); + + if (destroyChild) + { + for (var i = 0; i < removed.length; i++) + { + removed[i].destroy(); + } + } + + return this; + }, + + /** + * Removes all Game Objects from this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * + * @method Phaser.GameObjects.Container#removeAll + * @since 3.4.0 + * + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on each Game Object successfully removed from this Container. + * + * @return {this} This Container instance. + */ + removeAll: function (destroyChild) + { + var removed = ArrayUtils.RemoveBetween(this.list, 0, this.list.length, this.removeHandler, this); + + if (destroyChild) + { + for (var i = 0; i < removed.length; i++) + { + removed[i].destroy(); + } + } + + return this; + }, + + /** + * Brings the given Game Object to the top of this Container. + * This will cause it to render on-top of any other objects in the Container. + * + * @method Phaser.GameObjects.Container#bringToTop + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to bring to the top of the Container. + * + * @return {this} This Container instance. + */ + bringToTop: function (child) + { + ArrayUtils.BringToTop(this.list, child); + + return this; + }, + + /** + * Sends the given Game Object to the bottom of this Container. + * This will cause it to render below any other objects in the Container. + * + * @method Phaser.GameObjects.Container#sendToBack + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to send to the bottom of the Container. + * + * @return {this} This Container instance. + */ + sendToBack: function (child) + { + ArrayUtils.SendToBack(this.list, child); + + return this; + }, + + /** + * Moves the given Game Object up one place in this Container, unless it's already at the top. + * + * @method Phaser.GameObjects.Container#moveUp + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. + * + * @return {this} This Container instance. + */ + moveUp: function (child) + { + ArrayUtils.MoveUp(this.list, child); + + return this; + }, + + /** + * Moves the given Game Object down one place in this Container, unless it's already at the bottom. + * + * @method Phaser.GameObjects.Container#moveDown + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to be moved in the Container. + * + * @return {this} This Container instance. + */ + moveDown: function (child) + { + ArrayUtils.MoveDown(this.list, child); + + return this; + }, + + /** + * Reverses the order of all Game Objects in this Container. + * + * @method Phaser.GameObjects.Container#reverse + * @since 3.4.0 + * + * @return {this} This Container instance. + */ + reverse: function () + { + this.list.reverse(); + + return this; + }, + + /** + * Shuffles the all Game Objects in this Container using the Fisher-Yates implementation. + * + * @method Phaser.GameObjects.Container#shuffle + * @since 3.4.0 + * + * @return {this} This Container instance. + */ + shuffle: function () + { + ArrayUtils.Shuffle(this.list); + + return this; + }, + + /** + * Replaces a Game Object in this Container with the new Game Object. + * The new Game Object cannot already be a child of this Container. + * + * @method Phaser.GameObjects.Container#replace + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} oldChild - The Game Object in this Container that will be replaced. + * @param {Phaser.GameObjects.GameObject} newChild - The Game Object to be added to this Container. + * @param {boolean} [destroyChild=false] - Optionally call `destroy` on the Game Object if successfully removed from this Container. + * + * @return {this} This Container instance. + */ + replace: function (oldChild, newChild, destroyChild) + { + var moved = ArrayUtils.Replace(this.list, oldChild, newChild); + + if (moved) + { + this.addHandler(newChild); + this.removeHandler(oldChild); + + if (destroyChild) + { + oldChild.destroy(); + } + } + + return this; + }, + + /** + * Returns `true` if the given Game Object is a direct child of this Container. + * + * This check does not scan nested Containers. + * + * @method Phaser.GameObjects.Container#exists + * @since 3.4.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to check for within this Container. + * + * @return {boolean} True if the Game Object is an immediate child of this Container, otherwise false. + */ + exists: function (child) + { + return (this.list.indexOf(child) > -1); + }, + + /** + * Sets the property to the given value on all Game Objects in this Container. + * + * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 Game Objects. + * + * @method Phaser.GameObjects.Container#setAll + * @since 3.4.0 + * + * @param {string} property - The property that must exist on the Game Object. + * @param {any} value - The value to get the property to. + * @param {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=Container.length] - An optional end index to search up to (but not included) + * + * @return {this} This Container instance. + */ + setAll: function (property, value, startIndex, endIndex) + { + ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); + + return this; + }, + + /** + * @callback EachContainerCallback + * @generic I - [item] + * + * @param {*} item - The child Game Object of the Container. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + + /** + * Passes all Game Objects in this Container to the given callback. + * + * A copy of the Container is made before passing each entry to your callback. + * This protects against the callback itself modifying the Container. + * + * If you know for sure that the callback will not change the size of this Container + * then you can use the more performant `Container.iterate` method instead. + * + * @method Phaser.GameObjects.Container#each + * @since 3.4.0 + * + * @param {function} callback - The function to call. + * @param {object} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {this} This Container instance. + */ + each: function (callback, context) + { + var args = [ null ]; + var i; + var temp = this.list.slice(); + var len = temp.length; + + for (i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < len; i++) + { + args[0] = temp[i]; + + callback.apply(context, args); + } + + return this; + }, + + /** + * Passes all Game Objects in this Container to the given callback. + * + * Only use this method when you absolutely know that the Container will not be modified during + * the iteration, i.e. by removing or adding to its contents. + * + * @method Phaser.GameObjects.Container#iterate + * @since 3.4.0 + * + * @param {function} callback - The function to call. + * @param {object} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {this} This Container instance. + */ + iterate: function (callback, context) + { + var args = [ null ]; + var i; + + for (i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < this.list.length; i++) + { + args[0] = this.list[i]; + + callback.apply(context, args); + } + + return this; + }, + + /** + * 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.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. + * @param {boolean} [updateChildren=false] - Apply this scrollFactor to all Container children as well? + * + * @return {this} This Game Object instance. + */ + setScrollFactor: function (x, y, updateChildren) + { + if (y === undefined) { y = x; } + if (updateChildren === undefined) { updateChildren = false; } + + this.scrollFactorX = x; + this.scrollFactorY = y; + + if (updateChildren) + { + ArrayUtils.SetAll(this.list, 'scrollFactorX', x); + ArrayUtils.SetAll(this.list, 'scrollFactorY', y); + } + + return this; + }, + + /** + * The number of Game Objects inside this Container. + * + * @name Phaser.GameObjects.Container#length + * @type {integer} + * @readonly + * @since 3.4.0 + */ + length: { + + get: function () + { + return this.list.length; + } + + }, + + /** + * Returns the first Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#first + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + first: { + + get: function () + { + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + } + + }, + + /** + * Returns the last Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#last + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + last: { + + get: function () + { + if (this.list.length > 0) + { + this.position = this.list.length - 1; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * Returns the next Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#next + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + next: { + + get: function () + { + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * Returns the previous Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + * + * @name Phaser.GameObjects.Container#previous + * @type {?Phaser.GameObjects.GameObject} + * @readonly + * @since 3.4.0 + */ + previous: { + + get: function () + { + if (this.position > 0) + { + this.position--; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Container#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + this.removeAll(!!this.exclusive); + + this.localTransform.destroy(); + this.tempTransformMatrix.destroy(); + + this.list = []; + this._displayList = null; + } + +}); + +module.exports = Container; diff --git a/src/gameobjects/container/ContainerCanvasRenderer.js b/src/gameobjects/container/ContainerCanvasRenderer.js index 88bfbef87..f4ecb9a82 100644 --- a/src/gameobjects/container/ContainerCanvasRenderer.js +++ b/src/gameobjects/container/ContainerCanvasRenderer.js @@ -1,91 +1,91 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Container#renderCanvas - * @since 3.4.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Container} container - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ContainerCanvasRenderer = function (renderer, container, interpolationPercentage, camera, parentMatrix) -{ - var children = container.list; - - if (children.length === 0) - { - return; - } - - var transformMatrix = container.localTransform; - - if (parentMatrix) - { - transformMatrix.loadIdentity(); - transformMatrix.multiply(parentMatrix); - transformMatrix.translate(container.x, container.y); - transformMatrix.rotate(container.rotation); - transformMatrix.scale(container.scaleX, container.scaleY); - } - else - { - transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY); - } - - var containerHasBlendMode = (container.blendMode !== -1); - - if (!containerHasBlendMode) - { - // If Container is SKIP_TEST then set blend mode to be Normal - renderer.setBlendMode(0); - } - - var alpha = container._alpha; - var scrollFactorX = container.scrollFactorX; - var scrollFactorY = container.scrollFactorY; - - for (var i = 0; i < children.length; i++) - { - var child = children[i]; - - if (!child.willRender(camera)) - { - continue; - } - - var childAlpha = child.alpha; - var childScrollFactorX = child.scrollFactorX; - var childScrollFactorY = child.scrollFactorY; - - if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) - { - // If Container doesn't have its own blend mode, then a child can have one - renderer.setBlendMode(child.blendMode); - } - - // Set parent values - child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); - child.setAlpha(childAlpha * alpha); - - // Render - child.renderCanvas(renderer, child, interpolationPercentage, camera, transformMatrix); - - // Restore original values - child.setAlpha(childAlpha); - child.setScrollFactor(childScrollFactorX, childScrollFactorY); - } -}; - -module.exports = ContainerCanvasRenderer; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Container#renderCanvas + * @since 3.4.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Container} container - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ContainerCanvasRenderer = function (renderer, container, interpolationPercentage, camera, parentMatrix) +{ + var children = container.list; + + if (children.length === 0) + { + return; + } + + var transformMatrix = container.localTransform; + + if (parentMatrix) + { + transformMatrix.loadIdentity(); + transformMatrix.multiply(parentMatrix); + transformMatrix.translate(container.x, container.y); + transformMatrix.rotate(container.rotation); + transformMatrix.scale(container.scaleX, container.scaleY); + } + else + { + transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY); + } + + var containerHasBlendMode = (container.blendMode !== -1); + + if (!containerHasBlendMode) + { + // If Container is SKIP_TEST then set blend mode to be Normal + renderer.setBlendMode(0); + } + + var alpha = container._alpha; + var scrollFactorX = container.scrollFactorX; + var scrollFactorY = container.scrollFactorY; + + for (var i = 0; i < children.length; i++) + { + var child = children[i]; + + if (!child.willRender(camera)) + { + continue; + } + + var childAlpha = child.alpha; + var childScrollFactorX = child.scrollFactorX; + var childScrollFactorY = child.scrollFactorY; + + if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) + { + // If Container doesn't have its own blend mode, then a child can have one + renderer.setBlendMode(child.blendMode); + } + + // Set parent values + child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); + child.setAlpha(childAlpha * alpha); + + // Render + child.renderCanvas(renderer, child, interpolationPercentage, camera, transformMatrix); + + // Restore original values + child.setAlpha(childAlpha); + child.setScrollFactor(childScrollFactorX, childScrollFactorY); + } +}; + +module.exports = ContainerCanvasRenderer; diff --git a/src/gameobjects/container/ContainerCreator.js b/src/gameobjects/container/ContainerCreator.js index 21b2f5fb2..37d394b16 100644 --- a/src/gameobjects/container/ContainerCreator.js +++ b/src/gameobjects/container/ContainerCreator.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var Container = require('./Container'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); - -/** - * Creates a new Container Game Object and returns it. - * - * Note: This method will only be available if the Container Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#container - * @since 3.4.0 - * - * @param {object} 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.Container} The Game Object that was created. - */ -GameObjectCreator.register('container', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var x = GetAdvancedValue(config, 'x', 0); - var y = GetAdvancedValue(config, 'y', 0); - - var container = new Container(this.scene, x, y); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, container, config); - - return container; -}); +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var Container = require('./Container'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); + +/** + * Creates a new Container Game Object and returns it. + * + * Note: This method will only be available if the Container Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#container + * @since 3.4.0 + * + * @param {object} 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.Container} The Game Object that was created. + */ +GameObjectCreator.register('container', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + + var container = new Container(this.scene, x, y); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, container, config); + + return container; +}); diff --git a/src/gameobjects/container/ContainerFactory.js b/src/gameobjects/container/ContainerFactory.js index d50d870d8..8e35f139c 100644 --- a/src/gameobjects/container/ContainerFactory.js +++ b/src/gameobjects/container/ContainerFactory.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Container = require('./Container'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Container Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Container Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#container - * @since 3.4.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 {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to this Container. - * - * @return {Phaser.GameObjects.Container} The Game Object that was created. - */ -GameObjectFactory.register('container', function (x, y, children) -{ - return this.displayList.add(new Container(this.scene, x, y, children)); -}); +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Container = require('./Container'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Container Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Container Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#container + * @since 3.4.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 {Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to this Container. + * + * @return {Phaser.GameObjects.Container} The Game Object that was created. + */ +GameObjectFactory.register('container', function (x, y, children) +{ + return this.displayList.add(new Container(this.scene, x, y, children)); +}); diff --git a/src/gameobjects/container/ContainerRender.js b/src/gameobjects/container/ContainerRender.js index 2d6709041..1660a514b 100644 --- a/src/gameobjects/container/ContainerRender.js +++ b/src/gameobjects/container/ContainerRender.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./ContainerWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./ContainerCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./ContainerWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./ContainerCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/container/ContainerWebGLRenderer.js b/src/gameobjects/container/ContainerWebGLRenderer.js index 6e41ffb19..46d60b0d5 100644 --- a/src/gameobjects/container/ContainerWebGLRenderer.js +++ b/src/gameobjects/container/ContainerWebGLRenderer.js @@ -1,143 +1,143 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Container#renderWebGL - * @since 3.4.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Container} container - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ContainerWebGLRenderer = function (renderer, container, interpolationPercentage, camera, parentMatrix) -{ - var children = container.list; - - if (children.length === 0) - { - return; - } - - var transformMatrix = container.localTransform; - - if (parentMatrix) - { - transformMatrix.loadIdentity(); - transformMatrix.multiply(parentMatrix); - transformMatrix.translate(container.x, container.y); - transformMatrix.rotate(container.rotation); - transformMatrix.scale(container.scaleX, container.scaleY); - } - else - { - transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY); - } - - var containerHasBlendMode = (container.blendMode !== -1); - - if (!containerHasBlendMode) - { - // If Container is SKIP_TEST then set blend mode to be Normal - renderer.setBlendMode(0); - } - - var alpha = container.alpha; - - var scrollFactorX = container.scrollFactorX; - var scrollFactorY = container.scrollFactorY; - - var list = children; - var childCount = children.length; - - for (var i = 0; i < childCount; i++) - { - var child = children[i]; - - if (!child.willRender(camera)) - { - continue; - } - - var childAlphaTopLeft; - var childAlphaTopRight; - var childAlphaBottomLeft; - var childAlphaBottomRight; - - if (child.alphaTopLeft !== undefined) - { - childAlphaTopLeft = child.alphaTopLeft; - childAlphaTopRight = child.alphaTopRight; - childAlphaBottomLeft = child.alphaBottomLeft; - childAlphaBottomRight = child.alphaBottomRight; - } - else - { - var childAlpha = child.alpha; - - childAlphaTopLeft = childAlpha; - childAlphaTopRight = childAlpha; - childAlphaBottomLeft = childAlpha; - childAlphaBottomRight = childAlpha; - } - - var childScrollFactorX = child.scrollFactorX; - var childScrollFactorY = child.scrollFactorY; - - if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) - { - // If Container doesn't have its own blend mode, then a child can have one - renderer.setBlendMode(child.blendMode); - } - - var mask = child.mask; - - if (mask) - { - mask.preRenderWebGL(renderer, child, camera); - } - - var type = child.type; - - if (type !== renderer.currentType) - { - renderer.newType = true; - renderer.currentType = type; - } - - renderer.nextTypeMatch = (i < childCount - 1) ? (list[i + 1].type === renderer.currentType) : false; - - // Set parent values - child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); - - child.setAlpha(childAlphaTopLeft * alpha, childAlphaTopRight * alpha, childAlphaBottomLeft * alpha, childAlphaBottomRight * alpha); - - // Render - child.renderWebGL(renderer, child, interpolationPercentage, camera, transformMatrix); - - // Restore original values - - child.setAlpha(childAlphaTopLeft, childAlphaTopRight, childAlphaBottomLeft, childAlphaBottomRight); - - child.setScrollFactor(childScrollFactorX, childScrollFactorY); - - if (mask) - { - mask.postRenderWebGL(renderer, camera); - } - - renderer.newType = false; - } -}; - -module.exports = ContainerWebGLRenderer; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Container#renderWebGL + * @since 3.4.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Container} container - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ContainerWebGLRenderer = function (renderer, container, interpolationPercentage, camera, parentMatrix) +{ + var children = container.list; + + if (children.length === 0) + { + return; + } + + var transformMatrix = container.localTransform; + + if (parentMatrix) + { + transformMatrix.loadIdentity(); + transformMatrix.multiply(parentMatrix); + transformMatrix.translate(container.x, container.y); + transformMatrix.rotate(container.rotation); + transformMatrix.scale(container.scaleX, container.scaleY); + } + else + { + transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY); + } + + var containerHasBlendMode = (container.blendMode !== -1); + + if (!containerHasBlendMode) + { + // If Container is SKIP_TEST then set blend mode to be Normal + renderer.setBlendMode(0); + } + + var alpha = container.alpha; + + var scrollFactorX = container.scrollFactorX; + var scrollFactorY = container.scrollFactorY; + + var list = children; + var childCount = children.length; + + for (var i = 0; i < childCount; i++) + { + var child = children[i]; + + if (!child.willRender(camera)) + { + continue; + } + + var childAlphaTopLeft; + var childAlphaTopRight; + var childAlphaBottomLeft; + var childAlphaBottomRight; + + if (child.alphaTopLeft !== undefined) + { + childAlphaTopLeft = child.alphaTopLeft; + childAlphaTopRight = child.alphaTopRight; + childAlphaBottomLeft = child.alphaBottomLeft; + childAlphaBottomRight = child.alphaBottomRight; + } + else + { + var childAlpha = child.alpha; + + childAlphaTopLeft = childAlpha; + childAlphaTopRight = childAlpha; + childAlphaBottomLeft = childAlpha; + childAlphaBottomRight = childAlpha; + } + + var childScrollFactorX = child.scrollFactorX; + var childScrollFactorY = child.scrollFactorY; + + if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) + { + // If Container doesn't have its own blend mode, then a child can have one + renderer.setBlendMode(child.blendMode); + } + + var mask = child.mask; + + if (mask) + { + mask.preRenderWebGL(renderer, child, camera); + } + + var type = child.type; + + if (type !== renderer.currentType) + { + renderer.newType = true; + renderer.currentType = type; + } + + renderer.nextTypeMatch = (i < childCount - 1) ? (list[i + 1].type === renderer.currentType) : false; + + // Set parent values + child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); + + child.setAlpha(childAlphaTopLeft * alpha, childAlphaTopRight * alpha, childAlphaBottomLeft * alpha, childAlphaBottomRight * alpha); + + // Render + child.renderWebGL(renderer, child, interpolationPercentage, camera, transformMatrix); + + // Restore original values + + child.setAlpha(childAlphaTopLeft, childAlphaTopRight, childAlphaBottomLeft, childAlphaBottomRight); + + child.setScrollFactor(childScrollFactorX, childScrollFactorY); + + if (mask) + { + mask.postRenderWebGL(renderer, camera); + } + + renderer.newType = false; + } +}; + +module.exports = ContainerWebGLRenderer; diff --git a/src/gameobjects/domelement/CSSBlendModes.js b/src/gameobjects/domelement/CSSBlendModes.js index 88610d428..27cf827f3 100644 --- a/src/gameobjects/domelement/CSSBlendModes.js +++ b/src/gameobjects/domelement/CSSBlendModes.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Blend Modes to CSS Blend Modes Map. - * - * @name Phaser.CSSBlendModes - * @enum {string} - * @memberof Phaser - * @readonly - * @since 3.12.0 - */ - -module.exports = [ - 'normal', - 'multiply', - 'multiply', - 'screen', - 'overlay', - 'darken', - 'lighten', - 'color-dodge', - 'color-burn', - 'hard-light', - 'soft-light', - 'difference', - 'exclusion', - 'hue', - 'saturation', - 'color', - 'luminosity' -]; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Blend Modes to CSS Blend Modes Map. + * + * @name Phaser.CSSBlendModes + * @enum {string} + * @memberof Phaser + * @readonly + * @since 3.12.0 + */ + +module.exports = [ + 'normal', + 'multiply', + 'multiply', + 'screen', + 'overlay', + 'darken', + 'lighten', + 'color-dodge', + 'color-burn', + 'hard-light', + 'soft-light', + 'difference', + 'exclusion', + 'hue', + 'saturation', + 'color', + 'luminosity' +]; diff --git a/src/gameobjects/domelement/DOMElement.js b/src/gameobjects/domelement/DOMElement.js index 414946a17..d241493bb 100644 --- a/src/gameobjects/domelement/DOMElement.js +++ b/src/gameobjects/domelement/DOMElement.js @@ -1,968 +1,968 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var DOMElementRender = require('./DOMElementRender'); -var GameObject = require('../GameObject'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var RemoveFromDOM = require('../../dom/RemoveFromDOM'); -var SCENE_EVENTS = require('../../scene/events'); -var Vector4 = require('../../math/Vector4'); - -/** - * @classdesc - * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. - * - * In order for DOM Elements to display you have to enable them by adding the following to your game - * configuration object: - * - * ```javascript - * dom { - * createContainer: true - * } - * ``` - * - * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top - * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of - * settings within the Scale Manager, the dom container is resized accordingly. - * - * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing - * Element that you wish to be placed under the control of Phaser. For example: - * - * ```javascript - * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); - * ``` - * - * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in - * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, - * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. - * - * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control - * alignment and positioning of the elements next to regular game content. - * - * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the - * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other - * methods available in this class to help construct your elements. - * - * Once the element has been created you can then control it like you would any other Game Object. You can set its - * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped - * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that - * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have - * a DOM Element, then a Sprite, then another DOM Element behind it. - * - * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event - * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas - * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you - * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. - * - * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. - * - * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert - * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. - * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and - * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top - * of your game, and should treat it accordingly. - * - * @class DOMElement - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.17.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.ScrollFactor - * @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=0] - The horizontal position of this DOM Element in the world. - * @param {number} [y=0] - The vertical position of this DOM Element in the world. - * @param {(Element|string)} [element] - An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. - * @param {(string|any)} [style] - If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. - * @param {string} [innerText] - If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. - */ -var DOMElement = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.Depth, - Components.Origin, - Components.ScrollFactor, - Components.Transform, - Components.Visible, - DOMElementRender - ], - - initialize: - - function DOMElement (scene, x, y, element, style, innerText) - { - GameObject.call(this, scene, 'DOMElement'); - - /** - * A reference to the parent DOM Container that the Game instance created when it started. - * - * @name Phaser.GameObjects.DOMElement#parent - * @type {Element} - * @since 3.17.0 - */ - this.parent = scene.sys.game.domContainer; - - /** - * A reference to the HTML Cache. - * - * @name Phaser.GameObjects.DOMElement#cache - * @type {Phaser.Cache.BaseCache} - * @since 3.17.0 - */ - this.cache = scene.sys.cache.html; - - /** - * The actual DOM Element that this Game Object is bound to. For example, if you've created a `
` - * then this property is a direct reference to that element within the dom. - * - * @name Phaser.GameObjects.DOMElement#node - * @type {Element} - * @since 3.17.0 - */ - this.node; - - /** - * By default a DOM Element will have its transform, display, opacity, zIndex and blend mode properties - * updated when its rendered. If, for some reason, you don't want any of these changed other than the - * CSS transform, then set this flag to `true`. When `true` only the CSS Transform is applied and it's - * up to you to keep track of and set the other properties as required. - * - * This can be handy if, for example, you've a nested DOM Element and you don't want the opacity to be - * picked-up by any of its children. - * - * @name Phaser.GameObjects.DOMElement#transformOnly - * @type {boolean} - * @since 3.17.0 - */ - this.transformOnly = false; - - /** - * 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 - */ - this.skewX = 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 - */ - this.skewY = 0; - - /** - * A Vector4 that contains the 3D rotation of this DOM Element around a fixed axis in 3D space. - * - * All values in the Vector4 are treated as degrees, unless the `rotate3dAngle` property is changed. - * - * 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 - */ - this.rotate3d = new Vector4(); - - /** - * 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 - */ - this.rotate3dAngle = 'deg'; - - /** - * The native (un-scaled) width of this Game Object. - * - * For a DOM Element this property is read-only. - * - * The property `displayWidth` holds the computed bounds of this DOM Element, factoring in scaling. - * - * @name Phaser.GameObjects.DOMElement#width - * @type {number} - * @readonly - * @since 3.17.0 - */ - this.width = 0; - - /** - * The native (un-scaled) height of this Game Object. - * - * For a DOM Element this property is read-only. - * - * The property `displayHeight` holds the computed bounds of this DOM Element, factoring in scaling. - * - * @name Phaser.GameObjects.DOMElement#height - * @type {number} - * @readonly - * @since 3.17.0 - */ - this.height = 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 - */ - this.displayWidth = 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 - */ - this.displayHeight = 0; - - /** - * Internal native event handler. - * - * @name Phaser.GameObjects.DOMElement#handler - * @type {number} - * @private - * @since 3.17.0 - */ - this.handler = this.dispatchNativeEvent.bind(this); - - this.setPosition(x, y); - - if (typeof element === 'string') - { - // hash? - if (element[0] === '#') - { - this.setElement(element.substr(1), style, innerText); - } - else - { - this.createElement(element, style, innerText); - } - } - else if (element) - { - this.setElement(element, style, innerText); - } - - scene.sys.events.on(SCENE_EVENTS.SLEEP, this.handleSceneEvent, this); - scene.sys.events.on(SCENE_EVENTS.WAKE, this.handleSceneEvent, this); - }, - - /** - * Handles a Scene Sleep and Wake event. - * - * @method Phaser.GameObjects.DOMElement#handleSceneEvent - * @private - * @since 3.22.0 - * - * @param {Phaser.Scenes.Systems} sys - The Scene Systems. - */ - handleSceneEvent: function (sys) - { - var node = this.node; - var style = node.style; - - if (node) - { - style.display = (sys.settings.visible) ? 'block' : 'none'; - } - }, - - /** - * 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. - */ - setSkew: function (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - - this.skewX = x; - this.skewY = y; - - return this; - }, - - /** - * 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. - */ - setPerspective: function (value) - { - this.parent.style.perspective = value + 'px'; - - return this; - }, - - /** - * 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 - */ - perspective: { - - get: function () - { - return parseFloat(this.parent.style.perspective); - }, - - set: function (value) - { - this.parent.style.perspective = value + 'px'; - } - - }, - - /** - * Adds one or more native DOM event listeners onto the underlying Element of this Game Object. - * The event is then dispatched via this Game Objects standard event emitter. - * - * For example: - * - * ```javascript - * var div = this.add.dom(x, y, element); - * - * div.addListener('click'); - * - * div.on('click', handler); - * ``` - * - * @method Phaser.GameObjects.DOMElement#addListener - * @since 3.17.0 - * - * @param {string} events - The DOM event/s to listen for. You can specify multiple events by separating them with spaces. - * - * @return {this} This DOM Element instance. - */ - addListener: function (events) - { - if (this.node) - { - events = events.split(' '); - - for (var i = 0; i < events.length; i++) - { - this.node.addEventListener(events[i], this.handler, false); - } - } - - return this; - }, - - /** - * Removes one or more native DOM event listeners from the underlying Element of this Game Object. - * - * @method Phaser.GameObjects.DOMElement#removeListener - * @since 3.17.0 - * - * @param {string} events - The DOM event/s to stop listening for. You can specify multiple events by separating them with spaces. - * - * @return {this} This DOM Element instance. - */ - removeListener: function (events) - { - if (this.node) - { - events = events.split(' '); - - for (var i = 0; i < events.length; i++) - { - this.node.removeEventListener(events[i], this.handler); - } - } - - return this; - }, - - /** - * Internal event proxy to dispatch native DOM Events via this Game Object. - * - * @method Phaser.GameObjects.DOMElement#dispatchNativeEvent - * @private - * @since 3.17.0 - * - * @param {any} event - The native DOM event. - */ - dispatchNativeEvent: function (event) - { - this.emit(event.type, event); - }, - - /** - * 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 ready 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. - */ - createElement: function (tagName, style, innerText) - { - return this.setElement(document.createElement(tagName), style, innerText); - }, - - /** - * Binds a new DOM Element to this Game Object. 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 on the new element. - * - * The `element` argument you pass to this method can be either a string tagName: - * - * ```javascript - *

Phaser

- * - * this.add.dom().setElement('heading'); - * ``` - * - * Or a reference to an Element instance: - * - * ```javascript - *

Phaser

- * - * var h1 = document.getElementById('heading'); - * - * this.add.dom().setElement(h1); - * ``` - * - * 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().setElement(h1, '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().setElement(h1, style, 'Phaser'); - * ``` - * - * @method Phaser.GameObjects.DOMElement#setElement - * @since 3.17.0 - * - * @param {(string|Element)} element - If a string it is passed to `getElementById()`, or it should be a reference to an existing Element. - * @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 ready 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. - */ - setElement: function (element, style, innerText) - { - // Already got an element? Remove it first - this.removeElement(); - - var target; - - if (typeof element === 'string') - { - // hash? - if (element[0] === '#') - { - element = element.substr(1); - } - - target = document.getElementById(element); - } - else if (typeof element === 'object' && element.nodeType === 1) - { - target = element; - } - - if (!target) - { - return this; - } - - this.node = target; - - // style can be empty, a string or a plain object - if (style && IsPlainObject(style)) - { - for (var key in style) - { - target.style[key] = style[key]; - } - } - else if (typeof style === 'string') - { - target.style = style; - } - - // Add / Override the values we need - - target.style.zIndex = '0'; - target.style.display = 'inline'; - target.style.position = 'absolute'; - - // Node handler - - target.phaser = this; - - if (this.parent) - { - this.parent.appendChild(target); - } - - // InnerText - - if (innerText) - { - target.innerText = innerText; - } - - return this.updateSize(); - }, - - /** - * Takes a block of html from the HTML Cache, that has previously been preloaded into the game, and then - * creates a DOM Element from it. The loaded HTML is set as the `innerHTML` property of the created - * element. - * - * Assume the following html is stored in a file called `loginform.html`: - * - * ```html - * - * - * ``` - * - * Which is loaded into your game using the cache key 'login': - * - * ```javascript - * this.load.html('login', 'assets/loginform.html'); - * ``` - * - * You can create a DOM Element from it using the cache key: - * - * ```javascript - * this.add.dom().createFromCache('login'); - * ``` - * - * The optional `elementType` argument controls the container that is created, into which the loaded html is inserted. - * The default is a plain `div` object, but any valid tagName can be given. - * - * 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#createFromCache - * @since 3.17.0 - * - * @param {string} The key of the html cache entry to use for this DOM Element. - * @param {string} [tagName='div'] - The tag name of the element into which all of the loaded html will be inserted. Defaults to a plain div tag. - * - * @return {this} This DOM Element instance. - */ - createFromCache: function (key, tagName) - { - var html = this.cache.get(key); - - if (html) - { - this.createFromHTML(html, tagName); - } - - return this; - }, - - /** - * Takes a string of html and then creates a DOM Element from it. The HTML is set as the `innerHTML` - * property of the created element. - * - * ```javascript - * let form = ` - * - * - * `; - * ``` - * - * You can create a DOM Element from it using the string: - * - * ```javascript - * this.add.dom().createFromHTML(form); - * ``` - * - * The optional `elementType` argument controls the type of container that is created, into which the html is inserted. - * The default is a plain `div` object, but any valid tagName can be given. - * - * 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#createFromHTML - * @since 3.17.0 - * - * @param {string} A string of html to be set as the `innerHTML` property of the created element. - * @param {string} [tagName='div'] - The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag. - * - * @return {this} This DOM Element instance. - */ - createFromHTML: function (html, tagName) - { - if (tagName === undefined) { tagName = 'div'; } - - // Already got an element? Remove it first - this.removeElement(); - - var element = document.createElement(tagName); - - this.node = element; - - element.style.zIndex = '0'; - element.style.display = 'inline'; - element.style.position = 'absolute'; - - // Node handler - - element.phaser = this; - - if (this.parent) - { - this.parent.appendChild(element); - } - - element.innerHTML = html; - - return this.updateSize(); - }, - - /** - * Removes the current DOM Element bound to this Game Object from the DOM entirely and resets the - * `node` property of this Game Object to be `null`. - * - * @method Phaser.GameObjects.DOMElement#removeElement - * @since 3.17.0 - * - * @return {this} This DOM Element instance. - */ - removeElement: function () - { - if (this.node) - { - RemoveFromDOM(this.node); - - this.node = null; - } - - return this; - }, - - /** - * Internal method that calls `getBoundingClientRect` on the `node` and then sets the bounds width - * and height into the `displayWidth` and `displayHeight` properties, and the `clientWidth` and `clientHeight` - * values into the `width` and `height` properties respectively. - * - * This is called automatically whenever a new element is created or set. - * - * @method Phaser.GameObjects.DOMElement#updateSize - * @since 3.17.0 - * - * @return {this} This DOM Element instance. - */ - updateSize: function () - { - var node = this.node; - - var nodeBounds = node.getBoundingClientRect(); - - this.width = node.clientWidth; - this.height = node.clientHeight; - - this.displayWidth = nodeBounds.width || 0; - this.displayHeight = nodeBounds.height || 0; - - return this; - }, - - /** - * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through - * them, looking for the first one that has a property matching the given key and value. It then returns this child - * if found, or `null` if not. - * - * @method Phaser.GameObjects.DOMElement#getChildByProperty - * @since 3.17.0 - * - * @param {string} property - The property to search the children for. - * @param {string} value - The value the property must strictly equal. - * - * @return {?Element} The first matching child DOM Element, or `null` if not found. - */ - getChildByProperty: function (property, value) - { - if (this.node) - { - var children = this.node.querySelectorAll('*'); - - for (var i = 0; i < children.length; i++) - { - if (children[i][property] === value) - { - return children[i]; - } - } - } - - return null; - }, - - /** - * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through - * them, looking for the first one that has a matching id. It then returns this child if found, or `null` if not. - * - * Be aware that class and id names are case-sensitive. - * - * @method Phaser.GameObjects.DOMElement#getChildByID - * @since 3.17.0 - * - * @param {string} id - The id to search the children for. - * - * @return {?Element} The first matching child DOM Element, or `null` if not found. - */ - getChildByID: function (id) - { - return this.getChildByProperty('id', id); - }, - - /** - * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through - * them, looking for the first one that has a matching name. It then returns this child if found, or `null` if not. - * - * Be aware that class and id names are case-sensitive. - * - * @method Phaser.GameObjects.DOMElement#getChildByName - * @since 3.17.0 - * - * @param {string} name - The name to search the children for. - * - * @return {?Element} The first matching child DOM Element, or `null` if not found. - */ - getChildByName: function (name) - { - return this.getChildByProperty('name', name); - }, - - /** - * Sets the `className` property of the DOM Element node and updates the internal sizes. - * - * @method Phaser.GameObjects.DOMElement#setClassName - * @since 3.17.0 - * - * @param {string} className - A string representing the class or space-separated classes of the element. - * - * @return {this} This DOM Element instance. - */ - setClassName: function (className) - { - if (this.node) - { - this.node.className = className; - - this.updateSize(); - } - - return this; - }, - - /** - * Sets the `innerText` property of the DOM Element node and updates the internal sizes. - * - * Note that only certain types of Elements can have `innerText` set on them. - * - * @method Phaser.GameObjects.DOMElement#setText - * @since 3.17.0 - * - * @param {string} text - A DOMString representing the rendered text content of the element. - * - * @return {this} This DOM Element instance. - */ - setText: function (text) - { - if (this.node) - { - this.node.innerText = text; - - this.updateSize(); - } - - return this; - }, - - /** - * Sets the `innerHTML` property of the DOM Element node and updates the internal sizes. - * - * @method Phaser.GameObjects.DOMElement#setHTML - * @since 3.17.0 - * - * @param {string} html - A DOMString of html to be set as the `innerHTML` property of the element. - * - * @return {this} This DOM Element instance. - */ - setHTML: function (html) - { - if (this.node) - { - this.node.innerHTML = html; - - this.updateSize(); - } - - return this; - }, - - /** - * Runs internal update tasks. - * - * @method Phaser.GameObjects.DOMElement#preUpdate - * @private - * @since 3.17.0 - */ - preUpdate: function () - { - var parent = this.parentContainer; - var node = this.node; - - if (node && parent && !parent.willRender()) - { - node.style.display = 'none'; - } - }, - - /** - * Compares the renderMask with the renderFlags to see if this Game Object will render or not. - * - * DOMElements always return `true` as they need to still set values during the render pass, even if not visible. - * - * @method Phaser.GameObjects.DOMElement#willRender - * @since 3.17.0 - * - * @return {boolean} `true` if the Game Object should be rendered, otherwise `false`. - */ - willRender: function () - { - return true; - }, - - /** - * Handles the pre-destroy step for the DOM Element, which removes the underlying node from the DOM. - * - * @method Phaser.GameObjects.DOMElement#preDestroy - * @private - * @since 3.17.0 - */ - preDestroy: function () - { - this.removeElement(); - - this.scene.sys.events.off(SCENE_EVENTS.SLEEP, this.handleSceneEvent, this); - this.scene.sys.events.off(SCENE_EVENTS.WAKE, this.handleSceneEvent, this); - } - -}); - -module.exports = DOMElement; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var DOMElementRender = require('./DOMElementRender'); +var GameObject = require('../GameObject'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var RemoveFromDOM = require('../../dom/RemoveFromDOM'); +var SCENE_EVENTS = require('../../scene/events'); +var Vector4 = require('../../math/Vector4'); + +/** + * @classdesc + * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. + * + * In order for DOM Elements to display you have to enable them by adding the following to your game + * configuration object: + * + * ```javascript + * dom { + * createContainer: true + * } + * ``` + * + * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top + * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of + * settings within the Scale Manager, the dom container is resized accordingly. + * + * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing + * Element that you wish to be placed under the control of Phaser. For example: + * + * ```javascript + * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); + * ``` + * + * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in + * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, + * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + * + * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control + * alignment and positioning of the elements next to regular game content. + * + * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the + * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other + * methods available in this class to help construct your elements. + * + * Once the element has been created you can then control it like you would any other Game Object. You can set its + * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped + * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that + * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have + * a DOM Element, then a Sprite, then another DOM Element behind it. + * + * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event + * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas + * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you + * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. + * + * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. + * + * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert + * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. + * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and + * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top + * of your game, and should treat it accordingly. + * + * @class DOMElement + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.17.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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=0] - The horizontal position of this DOM Element in the world. + * @param {number} [y=0] - The vertical position of this DOM Element in the world. + * @param {(Element|string)} [element] - An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. + * @param {(string|any)} [style] - If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. + * @param {string} [innerText] - If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. + */ +var DOMElement = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.Depth, + Components.Origin, + Components.ScrollFactor, + Components.Transform, + Components.Visible, + DOMElementRender + ], + + initialize: + + function DOMElement (scene, x, y, element, style, innerText) + { + GameObject.call(this, scene, 'DOMElement'); + + /** + * A reference to the parent DOM Container that the Game instance created when it started. + * + * @name Phaser.GameObjects.DOMElement#parent + * @type {Element} + * @since 3.17.0 + */ + this.parent = scene.sys.game.domContainer; + + /** + * A reference to the HTML Cache. + * + * @name Phaser.GameObjects.DOMElement#cache + * @type {Phaser.Cache.BaseCache} + * @since 3.17.0 + */ + this.cache = scene.sys.cache.html; + + /** + * The actual DOM Element that this Game Object is bound to. For example, if you've created a `
` + * then this property is a direct reference to that element within the dom. + * + * @name Phaser.GameObjects.DOMElement#node + * @type {Element} + * @since 3.17.0 + */ + this.node; + + /** + * By default a DOM Element will have its transform, display, opacity, zIndex and blend mode properties + * updated when its rendered. If, for some reason, you don't want any of these changed other than the + * CSS transform, then set this flag to `true`. When `true` only the CSS Transform is applied and it's + * up to you to keep track of and set the other properties as required. + * + * This can be handy if, for example, you've a nested DOM Element and you don't want the opacity to be + * picked-up by any of its children. + * + * @name Phaser.GameObjects.DOMElement#transformOnly + * @type {boolean} + * @since 3.17.0 + */ + this.transformOnly = false; + + /** + * 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 + */ + this.skewX = 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 + */ + this.skewY = 0; + + /** + * A Vector4 that contains the 3D rotation of this DOM Element around a fixed axis in 3D space. + * + * All values in the Vector4 are treated as degrees, unless the `rotate3dAngle` property is changed. + * + * 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 + */ + this.rotate3d = new Vector4(); + + /** + * 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 + */ + this.rotate3dAngle = 'deg'; + + /** + * The native (un-scaled) width of this Game Object. + * + * For a DOM Element this property is read-only. + * + * The property `displayWidth` holds the computed bounds of this DOM Element, factoring in scaling. + * + * @name Phaser.GameObjects.DOMElement#width + * @type {number} + * @readonly + * @since 3.17.0 + */ + this.width = 0; + + /** + * The native (un-scaled) height of this Game Object. + * + * For a DOM Element this property is read-only. + * + * The property `displayHeight` holds the computed bounds of this DOM Element, factoring in scaling. + * + * @name Phaser.GameObjects.DOMElement#height + * @type {number} + * @readonly + * @since 3.17.0 + */ + this.height = 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 + */ + this.displayWidth = 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 + */ + this.displayHeight = 0; + + /** + * Internal native event handler. + * + * @name Phaser.GameObjects.DOMElement#handler + * @type {number} + * @private + * @since 3.17.0 + */ + this.handler = this.dispatchNativeEvent.bind(this); + + this.setPosition(x, y); + + if (typeof element === 'string') + { + // hash? + if (element[0] === '#') + { + this.setElement(element.substr(1), style, innerText); + } + else + { + this.createElement(element, style, innerText); + } + } + else if (element) + { + this.setElement(element, style, innerText); + } + + scene.sys.events.on(SCENE_EVENTS.SLEEP, this.handleSceneEvent, this); + scene.sys.events.on(SCENE_EVENTS.WAKE, this.handleSceneEvent, this); + }, + + /** + * Handles a Scene Sleep and Wake event. + * + * @method Phaser.GameObjects.DOMElement#handleSceneEvent + * @private + * @since 3.22.0 + * + * @param {Phaser.Scenes.Systems} sys - The Scene Systems. + */ + handleSceneEvent: function (sys) + { + var node = this.node; + var style = node.style; + + if (node) + { + style.display = (sys.settings.visible) ? 'block' : 'none'; + } + }, + + /** + * 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. + */ + setSkew: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.skewX = x; + this.skewY = y; + + return this; + }, + + /** + * 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. + */ + setPerspective: function (value) + { + this.parent.style.perspective = value + 'px'; + + return this; + }, + + /** + * 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 + */ + perspective: { + + get: function () + { + return parseFloat(this.parent.style.perspective); + }, + + set: function (value) + { + this.parent.style.perspective = value + 'px'; + } + + }, + + /** + * Adds one or more native DOM event listeners onto the underlying Element of this Game Object. + * The event is then dispatched via this Game Objects standard event emitter. + * + * For example: + * + * ```javascript + * var div = this.add.dom(x, y, element); + * + * div.addListener('click'); + * + * div.on('click', handler); + * ``` + * + * @method Phaser.GameObjects.DOMElement#addListener + * @since 3.17.0 + * + * @param {string} events - The DOM event/s to listen for. You can specify multiple events by separating them with spaces. + * + * @return {this} This DOM Element instance. + */ + addListener: function (events) + { + if (this.node) + { + events = events.split(' '); + + for (var i = 0; i < events.length; i++) + { + this.node.addEventListener(events[i], this.handler, false); + } + } + + return this; + }, + + /** + * Removes one or more native DOM event listeners from the underlying Element of this Game Object. + * + * @method Phaser.GameObjects.DOMElement#removeListener + * @since 3.17.0 + * + * @param {string} events - The DOM event/s to stop listening for. You can specify multiple events by separating them with spaces. + * + * @return {this} This DOM Element instance. + */ + removeListener: function (events) + { + if (this.node) + { + events = events.split(' '); + + for (var i = 0; i < events.length; i++) + { + this.node.removeEventListener(events[i], this.handler); + } + } + + return this; + }, + + /** + * Internal event proxy to dispatch native DOM Events via this Game Object. + * + * @method Phaser.GameObjects.DOMElement#dispatchNativeEvent + * @private + * @since 3.17.0 + * + * @param {any} event - The native DOM event. + */ + dispatchNativeEvent: function (event) + { + this.emit(event.type, event); + }, + + /** + * 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 ready 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. + */ + createElement: function (tagName, style, innerText) + { + return this.setElement(document.createElement(tagName), style, innerText); + }, + + /** + * Binds a new DOM Element to this Game Object. 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 on the new element. + * + * The `element` argument you pass to this method can be either a string tagName: + * + * ```javascript + *

Phaser

+ * + * this.add.dom().setElement('heading'); + * ``` + * + * Or a reference to an Element instance: + * + * ```javascript + *

Phaser

+ * + * var h1 = document.getElementById('heading'); + * + * this.add.dom().setElement(h1); + * ``` + * + * 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().setElement(h1, '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().setElement(h1, style, 'Phaser'); + * ``` + * + * @method Phaser.GameObjects.DOMElement#setElement + * @since 3.17.0 + * + * @param {(string|Element)} element - If a string it is passed to `getElementById()`, or it should be a reference to an existing Element. + * @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 ready 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. + */ + setElement: function (element, style, innerText) + { + // Already got an element? Remove it first + this.removeElement(); + + var target; + + if (typeof element === 'string') + { + // hash? + if (element[0] === '#') + { + element = element.substr(1); + } + + target = document.getElementById(element); + } + else if (typeof element === 'object' && element.nodeType === 1) + { + target = element; + } + + if (!target) + { + return this; + } + + this.node = target; + + // style can be empty, a string or a plain object + if (style && IsPlainObject(style)) + { + for (var key in style) + { + target.style[key] = style[key]; + } + } + else if (typeof style === 'string') + { + target.style = style; + } + + // Add / Override the values we need + + target.style.zIndex = '0'; + target.style.display = 'inline'; + target.style.position = 'absolute'; + + // Node handler + + target.phaser = this; + + if (this.parent) + { + this.parent.appendChild(target); + } + + // InnerText + + if (innerText) + { + target.innerText = innerText; + } + + return this.updateSize(); + }, + + /** + * Takes a block of html from the HTML Cache, that has previously been preloaded into the game, and then + * creates a DOM Element from it. The loaded HTML is set as the `innerHTML` property of the created + * element. + * + * Assume the following html is stored in a file called `loginform.html`: + * + * ```html + * + * + * ``` + * + * Which is loaded into your game using the cache key 'login': + * + * ```javascript + * this.load.html('login', 'assets/loginform.html'); + * ``` + * + * You can create a DOM Element from it using the cache key: + * + * ```javascript + * this.add.dom().createFromCache('login'); + * ``` + * + * The optional `elementType` argument controls the container that is created, into which the loaded html is inserted. + * The default is a plain `div` object, but any valid tagName can be given. + * + * 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#createFromCache + * @since 3.17.0 + * + * @param {string} The key of the html cache entry to use for this DOM Element. + * @param {string} [tagName='div'] - The tag name of the element into which all of the loaded html will be inserted. Defaults to a plain div tag. + * + * @return {this} This DOM Element instance. + */ + createFromCache: function (key, tagName) + { + var html = this.cache.get(key); + + if (html) + { + this.createFromHTML(html, tagName); + } + + return this; + }, + + /** + * Takes a string of html and then creates a DOM Element from it. The HTML is set as the `innerHTML` + * property of the created element. + * + * ```javascript + * let form = ` + * + * + * `; + * ``` + * + * You can create a DOM Element from it using the string: + * + * ```javascript + * this.add.dom().createFromHTML(form); + * ``` + * + * The optional `elementType` argument controls the type of container that is created, into which the html is inserted. + * The default is a plain `div` object, but any valid tagName can be given. + * + * 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#createFromHTML + * @since 3.17.0 + * + * @param {string} A string of html to be set as the `innerHTML` property of the created element. + * @param {string} [tagName='div'] - The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag. + * + * @return {this} This DOM Element instance. + */ + createFromHTML: function (html, tagName) + { + if (tagName === undefined) { tagName = 'div'; } + + // Already got an element? Remove it first + this.removeElement(); + + var element = document.createElement(tagName); + + this.node = element; + + element.style.zIndex = '0'; + element.style.display = 'inline'; + element.style.position = 'absolute'; + + // Node handler + + element.phaser = this; + + if (this.parent) + { + this.parent.appendChild(element); + } + + element.innerHTML = html; + + return this.updateSize(); + }, + + /** + * Removes the current DOM Element bound to this Game Object from the DOM entirely and resets the + * `node` property of this Game Object to be `null`. + * + * @method Phaser.GameObjects.DOMElement#removeElement + * @since 3.17.0 + * + * @return {this} This DOM Element instance. + */ + removeElement: function () + { + if (this.node) + { + RemoveFromDOM(this.node); + + this.node = null; + } + + return this; + }, + + /** + * Internal method that calls `getBoundingClientRect` on the `node` and then sets the bounds width + * and height into the `displayWidth` and `displayHeight` properties, and the `clientWidth` and `clientHeight` + * values into the `width` and `height` properties respectively. + * + * This is called automatically whenever a new element is created or set. + * + * @method Phaser.GameObjects.DOMElement#updateSize + * @since 3.17.0 + * + * @return {this} This DOM Element instance. + */ + updateSize: function () + { + var node = this.node; + + var nodeBounds = node.getBoundingClientRect(); + + this.width = node.clientWidth; + this.height = node.clientHeight; + + this.displayWidth = nodeBounds.width || 0; + this.displayHeight = nodeBounds.height || 0; + + return this; + }, + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a property matching the given key and value. It then returns this child + * if found, or `null` if not. + * + * @method Phaser.GameObjects.DOMElement#getChildByProperty + * @since 3.17.0 + * + * @param {string} property - The property to search the children for. + * @param {string} value - The value the property must strictly equal. + * + * @return {?Element} The first matching child DOM Element, or `null` if not found. + */ + getChildByProperty: function (property, value) + { + if (this.node) + { + var children = this.node.querySelectorAll('*'); + + for (var i = 0; i < children.length; i++) + { + if (children[i][property] === value) + { + return children[i]; + } + } + } + + return null; + }, + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a matching id. It then returns this child if found, or `null` if not. + * + * Be aware that class and id names are case-sensitive. + * + * @method Phaser.GameObjects.DOMElement#getChildByID + * @since 3.17.0 + * + * @param {string} id - The id to search the children for. + * + * @return {?Element} The first matching child DOM Element, or `null` if not found. + */ + getChildByID: function (id) + { + return this.getChildByProperty('id', id); + }, + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a matching name. It then returns this child if found, or `null` if not. + * + * Be aware that class and id names are case-sensitive. + * + * @method Phaser.GameObjects.DOMElement#getChildByName + * @since 3.17.0 + * + * @param {string} name - The name to search the children for. + * + * @return {?Element} The first matching child DOM Element, or `null` if not found. + */ + getChildByName: function (name) + { + return this.getChildByProperty('name', name); + }, + + /** + * Sets the `className` property of the DOM Element node and updates the internal sizes. + * + * @method Phaser.GameObjects.DOMElement#setClassName + * @since 3.17.0 + * + * @param {string} className - A string representing the class or space-separated classes of the element. + * + * @return {this} This DOM Element instance. + */ + setClassName: function (className) + { + if (this.node) + { + this.node.className = className; + + this.updateSize(); + } + + return this; + }, + + /** + * Sets the `innerText` property of the DOM Element node and updates the internal sizes. + * + * Note that only certain types of Elements can have `innerText` set on them. + * + * @method Phaser.GameObjects.DOMElement#setText + * @since 3.17.0 + * + * @param {string} text - A DOMString representing the rendered text content of the element. + * + * @return {this} This DOM Element instance. + */ + setText: function (text) + { + if (this.node) + { + this.node.innerText = text; + + this.updateSize(); + } + + return this; + }, + + /** + * Sets the `innerHTML` property of the DOM Element node and updates the internal sizes. + * + * @method Phaser.GameObjects.DOMElement#setHTML + * @since 3.17.0 + * + * @param {string} html - A DOMString of html to be set as the `innerHTML` property of the element. + * + * @return {this} This DOM Element instance. + */ + setHTML: function (html) + { + if (this.node) + { + this.node.innerHTML = html; + + this.updateSize(); + } + + return this; + }, + + /** + * Runs internal update tasks. + * + * @method Phaser.GameObjects.DOMElement#preUpdate + * @private + * @since 3.17.0 + */ + preUpdate: function () + { + var parent = this.parentContainer; + var node = this.node; + + if (node && parent && !parent.willRender()) + { + node.style.display = 'none'; + } + }, + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * + * DOMElements always return `true` as they need to still set values during the render pass, even if not visible. + * + * @method Phaser.GameObjects.DOMElement#willRender + * @since 3.17.0 + * + * @return {boolean} `true` if the Game Object should be rendered, otherwise `false`. + */ + willRender: function () + { + return true; + }, + + /** + * Handles the pre-destroy step for the DOM Element, which removes the underlying node from the DOM. + * + * @method Phaser.GameObjects.DOMElement#preDestroy + * @private + * @since 3.17.0 + */ + preDestroy: function () + { + this.removeElement(); + + this.scene.sys.events.off(SCENE_EVENTS.SLEEP, this.handleSceneEvent, this); + this.scene.sys.events.off(SCENE_EVENTS.WAKE, this.handleSceneEvent, this); + } + +}); + +module.exports = DOMElement; diff --git a/src/gameobjects/domelement/DOMElementCSSRenderer.js b/src/gameobjects/domelement/DOMElementCSSRenderer.js index b229ce187..3366d14f8 100644 --- a/src/gameobjects/domelement/DOMElementCSSRenderer.js +++ b/src/gameobjects/domelement/DOMElementCSSRenderer.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CSSBlendModes = require('./CSSBlendModes'); -var GameObject = require('../GameObject'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.DOMElement#renderWebGL - * @since 3.17.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active renderer. - * @param {Phaser.GameObjects.DOMElement} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var DOMElementCSSRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var node = src.node; - var style = node.style; - var settings = src.scene.sys.settings; - - if (!node || !style || !settings.visible || GameObject.RENDER_MASK !== src.renderFlags || (src.cameraFilter !== 0 && (src.cameraFilter & camera.id)) || (src.parentContainer && !src.parentContainer.willRender())) - { - if (node) - { - style.display = 'none'; - } - - return; - } - - var parent = src.parentContainer; - var alpha = camera.alpha * src.alpha; - - if (parent) - { - alpha *= parent.alpha; - } - - var camMatrix = renderer._tempMatrix1; - var srcMatrix = renderer._tempMatrix2; - var calcMatrix = renderer._tempMatrix3; - - var dx = 0; - var dy = 0; - - var tx = '0%'; - var ty = '0%'; - - if (parentMatrix) - { - dx = (src.width * src.scaleX) * src.originX; - dy = (src.height * src.scaleY) * src.originY; - - srcMatrix.applyITRS(src.x - dx, src.y - dy, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - srcMatrix.e = src.x - dx; - srcMatrix.f = src.y - dy; - - // Multiply by the src matrix, store result in calcMatrix - camMatrix.multiply(srcMatrix, calcMatrix); - } - else - { - dx = (src.width) * src.originX; - dy = (src.height) * src.originY; - - srcMatrix.applyITRS(src.x - dx, src.y - dy, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - tx = (100 * src.originX) + '%'; - ty = (100 * src.originY) + '%'; - - srcMatrix.e -= camera.scrollX * src.scrollFactorX; - srcMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the src matrix, store result in calcMatrix - camMatrix.multiply(srcMatrix, calcMatrix); - } - - if (!src.transformOnly) - { - style.display = 'block'; - style.opacity = alpha; - style.zIndex = src._depth; - style.pointerEvents = 'auto'; - style.mixBlendMode = CSSBlendModes[src._blendMode]; - } - - // https://developer.mozilla.org/en-US/docs/Web/CSS/transform - - style.transform = - calcMatrix.getCSSMatrix() + - ' skew(' + src.skewX + 'rad, ' + src.skewY + 'rad)' + - ' rotate3d(' + src.rotate3d.x + ',' + src.rotate3d.y + ',' + src.rotate3d.z + ',' + src.rotate3d.w + src.rotate3dAngle + ')'; - - style.transformOrigin = tx + ' ' + ty; -}; - -module.exports = DOMElementCSSRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CSSBlendModes = require('./CSSBlendModes'); +var GameObject = require('../GameObject'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.DOMElement#renderWebGL + * @since 3.17.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active renderer. + * @param {Phaser.GameObjects.DOMElement} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DOMElementCSSRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var node = src.node; + var style = node.style; + var settings = src.scene.sys.settings; + + if (!node || !style || !settings.visible || GameObject.RENDER_MASK !== src.renderFlags || (src.cameraFilter !== 0 && (src.cameraFilter & camera.id)) || (src.parentContainer && !src.parentContainer.willRender())) + { + if (node) + { + style.display = 'none'; + } + + return; + } + + var parent = src.parentContainer; + var alpha = camera.alpha * src.alpha; + + if (parent) + { + alpha *= parent.alpha; + } + + var camMatrix = renderer._tempMatrix1; + var srcMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + var dx = 0; + var dy = 0; + + var tx = '0%'; + var ty = '0%'; + + if (parentMatrix) + { + dx = (src.width * src.scaleX) * src.originX; + dy = (src.height * src.scaleY) * src.originY; + + srcMatrix.applyITRS(src.x - dx, src.y - dy, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + srcMatrix.e = src.x - dx; + srcMatrix.f = src.y - dy; + + // Multiply by the src matrix, store result in calcMatrix + camMatrix.multiply(srcMatrix, calcMatrix); + } + else + { + dx = (src.width) * src.originX; + dy = (src.height) * src.originY; + + srcMatrix.applyITRS(src.x - dx, src.y - dy, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + tx = (100 * src.originX) + '%'; + ty = (100 * src.originY) + '%'; + + srcMatrix.e -= camera.scrollX * src.scrollFactorX; + srcMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the src matrix, store result in calcMatrix + camMatrix.multiply(srcMatrix, calcMatrix); + } + + if (!src.transformOnly) + { + style.display = 'block'; + style.opacity = alpha; + style.zIndex = src._depth; + style.pointerEvents = 'auto'; + style.mixBlendMode = CSSBlendModes[src._blendMode]; + } + + // https://developer.mozilla.org/en-US/docs/Web/CSS/transform + + style.transform = + calcMatrix.getCSSMatrix() + + ' skew(' + src.skewX + 'rad, ' + src.skewY + 'rad)' + + ' rotate3d(' + src.rotate3d.x + ',' + src.rotate3d.y + ',' + src.rotate3d.z + ',' + src.rotate3d.w + src.rotate3dAngle + ')'; + + style.transformOrigin = tx + ' ' + ty; +}; + +module.exports = DOMElementCSSRenderer; diff --git a/src/gameobjects/domelement/DOMElementFactory.js b/src/gameobjects/domelement/DOMElementFactory.js index e4fc9fe23..ac70a9c76 100644 --- a/src/gameobjects/domelement/DOMElementFactory.js +++ b/src/gameobjects/domelement/DOMElementFactory.js @@ -1,84 +1,84 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DOMElement = require('./DOMElement'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. - * - * In order for DOM Elements to display you have to enable them by adding the following to your game - * configuration object: - * - * ```javascript - * dom { - * createContainer: true - * } - * ``` - * - * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top - * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of - * settings within the Scale Manager, the dom container is resized accordingly. - * - * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing - * Element that you wish to be placed under the control of Phaser. For example: - * - * ```javascript - * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); - * ``` - * - * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in - * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, - * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. - * - * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control - * alignment and positioning of the elements next to regular game content. - * - * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the - * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other - * methods available in this class to help construct your elements. - * - * Once the element has been created you can then control it like you would any other Game Object. You can set its - * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped - * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that - * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have - * a DOM Element, then a Sprite, then another DOM Element behind it. - * - * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event - * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas - * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you - * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. - * - * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. - * - * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert - * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. - * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and - * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top - * of your game, and should treat it accordingly. - * - * Note: This method will only be available if the DOM Element Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#dom - * @since 3.17.0 - * - * @param {number} x - The horizontal position of this DOM Element in the world. - * @param {number} y - The vertical position of this DOM Element in the world. - * @param {(HTMLElement|string)} [element] - An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. - * @param {(string|any)} [style] - If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. - * @param {string} [innerText] - If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. - * - * @return {Phaser.GameObjects.DOMElement} The Game Object that was created. - */ -GameObjectFactory.register('dom', function (x, y, element, style, innerText) -{ - var gameObject = new DOMElement(this.scene, x, y, element, style, innerText); - - this.displayList.add(gameObject); - this.updateList.add(gameObject); - - return gameObject; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DOMElement = require('./DOMElement'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. + * + * In order for DOM Elements to display you have to enable them by adding the following to your game + * configuration object: + * + * ```javascript + * dom { + * createContainer: true + * } + * ``` + * + * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top + * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of + * settings within the Scale Manager, the dom container is resized accordingly. + * + * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing + * Element that you wish to be placed under the control of Phaser. For example: + * + * ```javascript + * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); + * ``` + * + * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in + * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, + * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + * + * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control + * alignment and positioning of the elements next to regular game content. + * + * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the + * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other + * methods available in this class to help construct your elements. + * + * Once the element has been created you can then control it like you would any other Game Object. You can set its + * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped + * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that + * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have + * a DOM Element, then a Sprite, then another DOM Element behind it. + * + * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event + * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas + * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you + * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. + * + * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. + * + * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert + * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. + * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and + * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top + * of your game, and should treat it accordingly. + * + * Note: This method will only be available if the DOM Element Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#dom + * @since 3.17.0 + * + * @param {number} x - The horizontal position of this DOM Element in the world. + * @param {number} y - The vertical position of this DOM Element in the world. + * @param {(HTMLElement|string)} [element] - An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. + * @param {(string|any)} [style] - If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. + * @param {string} [innerText] - If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. + * + * @return {Phaser.GameObjects.DOMElement} The Game Object that was created. + */ +GameObjectFactory.register('dom', function (x, y, element, style, innerText) +{ + var gameObject = new DOMElement(this.scene, x, y, element, style, innerText); + + this.displayList.add(gameObject); + this.updateList.add(gameObject); + + return gameObject; +}); diff --git a/src/gameobjects/domelement/DOMElementRender.js b/src/gameobjects/domelement/DOMElementRender.js index 0c2bfd4d7..7736f0bd3 100644 --- a/src/gameobjects/domelement/DOMElementRender.js +++ b/src/gameobjects/domelement/DOMElementRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./DOMElementCSSRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./DOMElementCSSRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./DOMElementCSSRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./DOMElementCSSRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/events/DESTROY_EVENT.js b/src/gameobjects/events/DESTROY_EVENT.js index a86bfcd30..f1126f3de 100644 --- a/src/gameobjects/events/DESTROY_EVENT.js +++ b/src/gameobjects/events/DESTROY_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Destroy Event. - * - * This event is dispatched when a Game Object instance is being destroyed. - * - * Listen for it on a Game Object instance using `GameObject.on('destroy', listener)`. - * - * @event Phaser.GameObjects.Events#DESTROY - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object which is being destroyed. - */ -module.exports = 'destroy'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Destroy Event. + * + * This event is dispatched when a Game Object instance is being destroyed. + * + * Listen for it on a Game Object instance using `GameObject.on('destroy', listener)`. + * + * @event Phaser.GameObjects.Events#DESTROY + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object which is being destroyed. + */ +module.exports = 'destroy'; diff --git a/src/gameobjects/events/VIDEO_COMPLETE_EVENT.js b/src/gameobjects/events/VIDEO_COMPLETE_EVENT.js index 13ac38f59..67baa0fe1 100644 --- a/src/gameobjects/events/VIDEO_COMPLETE_EVENT.js +++ b/src/gameobjects/events/VIDEO_COMPLETE_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Complete Event. - * - * This event is dispatched when a Video finishes playback by reaching the end of its duration. It - * is also dispatched if a video marker sequence is being played and reaches the end. - * - * Note that not all videos can fire this event. Live streams, for example, have no fixed duration, - * so never technically 'complete'. - * - * If a video is stopped from playback, via the `Video.stop` method, it will emit the - * `VIDEO_STOP` event instead of this one. - * - * Listen for it from a Video Game Object instance using `Video.on('complete', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_COMPLETE - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which completed playback. - */ -module.exports = 'complete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Complete Event. + * + * This event is dispatched when a Video finishes playback by reaching the end of its duration. It + * is also dispatched if a video marker sequence is being played and reaches the end. + * + * Note that not all videos can fire this event. Live streams, for example, have no fixed duration, + * so never technically 'complete'. + * + * If a video is stopped from playback, via the `Video.stop` method, it will emit the + * `VIDEO_STOP` event instead of this one. + * + * Listen for it from a Video Game Object instance using `Video.on('complete', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_COMPLETE + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which completed playback. + */ +module.exports = 'complete'; diff --git a/src/gameobjects/events/VIDEO_CREATED_EVENT.js b/src/gameobjects/events/VIDEO_CREATED_EVENT.js index cf9890446..84f64189f 100644 --- a/src/gameobjects/events/VIDEO_CREATED_EVENT.js +++ b/src/gameobjects/events/VIDEO_CREATED_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Created Event. - * - * This event is dispatched when the texture for a Video has been created. This happens - * when enough of the video source has been loaded that the browser is able to render a - * frame from it. - * - * Listen for it from a Video Game Object instance using `Video.on('created', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_CREATED - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which raised the event. - * @param {integer} width - The width of the video. - * @param {integer} height - The height of the video. - */ -module.exports = 'created'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Created Event. + * + * This event is dispatched when the texture for a Video has been created. This happens + * when enough of the video source has been loaded that the browser is able to render a + * frame from it. + * + * Listen for it from a Video Game Object instance using `Video.on('created', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_CREATED + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which raised the event. + * @param {integer} width - The width of the video. + * @param {integer} height - The height of the video. + */ +module.exports = 'created'; diff --git a/src/gameobjects/events/VIDEO_ERROR_EVENT.js b/src/gameobjects/events/VIDEO_ERROR_EVENT.js index 934a844b3..b16be60ec 100644 --- a/src/gameobjects/events/VIDEO_ERROR_EVENT.js +++ b/src/gameobjects/events/VIDEO_ERROR_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Error Event. - * - * This event is dispatched when a Video tries to play a source that does not exist, or is the wrong file type. - * - * Listen for it from a Video Game Object instance using `Video.on('error', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_ERROR - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which threw the error. - * @param {Event} event - The native DOM event the browser raised during playback. - */ -module.exports = 'error'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Error Event. + * + * This event is dispatched when a Video tries to play a source that does not exist, or is the wrong file type. + * + * Listen for it from a Video Game Object instance using `Video.on('error', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_ERROR + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which threw the error. + * @param {Event} event - The native DOM event the browser raised during playback. + */ +module.exports = 'error'; diff --git a/src/gameobjects/events/VIDEO_LOOP_EVENT.js b/src/gameobjects/events/VIDEO_LOOP_EVENT.js index 0609e75b5..840c772ff 100644 --- a/src/gameobjects/events/VIDEO_LOOP_EVENT.js +++ b/src/gameobjects/events/VIDEO_LOOP_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which has looped. - */ -module.exports = 'loop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which has looped. + */ +module.exports = 'loop'; diff --git a/src/gameobjects/events/VIDEO_PLAY_EVENT.js b/src/gameobjects/events/VIDEO_PLAY_EVENT.js index 3a251b3b8..dead4ad1e 100644 --- a/src/gameobjects/events/VIDEO_PLAY_EVENT.js +++ b/src/gameobjects/events/VIDEO_PLAY_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Play Event. - * - * This event is dispatched when a Video begins playback. For videos that do not require - * interaction unlocking, this is usually as soon as the `Video.play` method is called. - * However, for videos that require unlocking, it is fired once playback begins after - * they've been unlocked. - * - * Listen for it from a Video Game Object instance using `Video.on('play', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_PLAY - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which started playback. - */ -module.exports = 'play'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Play Event. + * + * This event is dispatched when a Video begins playback. For videos that do not require + * interaction unlocking, this is usually as soon as the `Video.play` method is called. + * However, for videos that require unlocking, it is fired once playback begins after + * they've been unlocked. + * + * Listen for it from a Video Game Object instance using `Video.on('play', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_PLAY + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which started playback. + */ +module.exports = 'play'; diff --git a/src/gameobjects/events/VIDEO_SEEKED_EVENT.js b/src/gameobjects/events/VIDEO_SEEKED_EVENT.js index bf440c2bb..72f65a2a5 100644 --- a/src/gameobjects/events/VIDEO_SEEKED_EVENT.js +++ b/src/gameobjects/events/VIDEO_SEEKED_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Seeked Event. - * - * This event is dispatched when a Video completes seeking to a new point in its timeline. - * - * Listen for it from a Video Game Object instance using `Video.on('seeked', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_SEEKED - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which completed seeking. - */ -module.exports = 'seeked'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Seeked Event. + * + * This event is dispatched when a Video completes seeking to a new point in its timeline. + * + * Listen for it from a Video Game Object instance using `Video.on('seeked', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_SEEKED + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which completed seeking. + */ +module.exports = 'seeked'; diff --git a/src/gameobjects/events/VIDEO_SEEKING_EVENT.js b/src/gameobjects/events/VIDEO_SEEKING_EVENT.js index d31f8ccb0..ad114ff88 100644 --- a/src/gameobjects/events/VIDEO_SEEKING_EVENT.js +++ b/src/gameobjects/events/VIDEO_SEEKING_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Seeking Event. - * - * This event is dispatched when a Video _begins_ seeking to a new point in its timeline. - * When the seek is complete, it will dispatch the `VIDEO_SEEKED` event to conclude. - * - * Listen for it from a Video Game Object instance using `Video.on('seeking', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_SEEKING - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which started seeking. - */ -module.exports = 'seeking'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Seeking Event. + * + * This event is dispatched when a Video _begins_ seeking to a new point in its timeline. + * When the seek is complete, it will dispatch the `VIDEO_SEEKED` event to conclude. + * + * Listen for it from a Video Game Object instance using `Video.on('seeking', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_SEEKING + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which started seeking. + */ +module.exports = 'seeking'; diff --git a/src/gameobjects/events/VIDEO_STOP_EVENT.js b/src/gameobjects/events/VIDEO_STOP_EVENT.js index 1db3c8275..80acd3c03 100644 --- a/src/gameobjects/events/VIDEO_STOP_EVENT.js +++ b/src/gameobjects/events/VIDEO_STOP_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Stopped Event. - * - * This event is dispatched when a Video is stopped from playback via a call to the `Video.stop` method, - * either directly via game code, or indirectly as the result of changing a video source or destroying it. - * - * Listen for it from a Video Game Object instance using `Video.on('stop', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_STOP - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which stopped playback. - */ -module.exports = 'stop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Stopped Event. + * + * This event is dispatched when a Video is stopped from playback via a call to the `Video.stop` method, + * either directly via game code, or indirectly as the result of changing a video source or destroying it. + * + * Listen for it from a Video Game Object instance using `Video.on('stop', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_STOP + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which stopped playback. + */ +module.exports = 'stop'; diff --git a/src/gameobjects/events/VIDEO_TIMEOUT_EVENT.js b/src/gameobjects/events/VIDEO_TIMEOUT_EVENT.js index de97a3213..69421245d 100644 --- a/src/gameobjects/events/VIDEO_TIMEOUT_EVENT.js +++ b/src/gameobjects/events/VIDEO_TIMEOUT_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Timeout Event. - * - * This event is dispatched when a Video has exhausted its allocated time while trying to connect to a video - * source to start playback. - * - * Listen for it from a Video Game Object instance using `Video.on('timeout', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_TIMEOUT - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which timed out. - */ -module.exports = 'timeout'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Timeout Event. + * + * This event is dispatched when a Video has exhausted its allocated time while trying to connect to a video + * source to start playback. + * + * Listen for it from a Video Game Object instance using `Video.on('timeout', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_TIMEOUT + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which timed out. + */ +module.exports = 'timeout'; diff --git a/src/gameobjects/events/VIDEO_UNLOCKED_EVENT.js b/src/gameobjects/events/VIDEO_UNLOCKED_EVENT.js index 11e221b13..b2238d2da 100644 --- a/src/gameobjects/events/VIDEO_UNLOCKED_EVENT.js +++ b/src/gameobjects/events/VIDEO_UNLOCKED_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Video Game Object Unlocked Event. - * - * This event is dispatched when a Video that was prevented from playback due to the browsers - * Media Engagement Interaction policy, is unlocked by a user gesture. - * - * Listen for it from a Video Game Object instance using `Video.on('unlocked', listener)`. - * - * @event Phaser.GameObjects.Events#VIDEO_UNLOCKED - * @since 3.20.0 - * - * @param {Phaser.GameObjects.Video} video - The Video Game Object which raised the event. - */ -module.exports = 'unlocked'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Video Game Object Unlocked Event. + * + * This event is dispatched when a Video that was prevented from playback due to the browsers + * Media Engagement Interaction policy, is unlocked by a user gesture. + * + * Listen for it from a Video Game Object instance using `Video.on('unlocked', listener)`. + * + * @event Phaser.GameObjects.Events#VIDEO_UNLOCKED + * @since 3.20.0 + * + * @param {Phaser.GameObjects.Video} video - The Video Game Object which raised the event. + */ +module.exports = 'unlocked'; diff --git a/src/gameobjects/events/index.js b/src/gameobjects/events/index.js index 7a237c690..6885ac7f3 100644 --- a/src/gameobjects/events/index.js +++ b/src/gameobjects/events/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.GameObjects.Events - */ - -module.exports = { - - DESTROY: require('./DESTROY_EVENT'), - VIDEO_COMPLETE: require('./VIDEO_COMPLETE_EVENT'), - VIDEO_CREATED: require('./VIDEO_CREATED_EVENT'), - VIDEO_ERROR: require('./VIDEO_ERROR_EVENT'), - VIDEO_LOOP: require('./VIDEO_LOOP_EVENT'), - VIDEO_PLAY: require('./VIDEO_PLAY_EVENT'), - VIDEO_SEEKED: require('./VIDEO_SEEKED_EVENT'), - VIDEO_SEEKING: require('./VIDEO_SEEKING_EVENT'), - VIDEO_STOP: require('./VIDEO_STOP_EVENT'), - VIDEO_TIMEOUT: require('./VIDEO_TIMEOUT_EVENT'), - VIDEO_UNLOCKED: require('./VIDEO_UNLOCKED_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Events + */ + +module.exports = { + + DESTROY: require('./DESTROY_EVENT'), + VIDEO_COMPLETE: require('./VIDEO_COMPLETE_EVENT'), + VIDEO_CREATED: require('./VIDEO_CREATED_EVENT'), + VIDEO_ERROR: require('./VIDEO_ERROR_EVENT'), + VIDEO_LOOP: require('./VIDEO_LOOP_EVENT'), + VIDEO_PLAY: require('./VIDEO_PLAY_EVENT'), + VIDEO_SEEKED: require('./VIDEO_SEEKED_EVENT'), + VIDEO_SEEKING: require('./VIDEO_SEEKING_EVENT'), + VIDEO_STOP: require('./VIDEO_STOP_EVENT'), + VIDEO_TIMEOUT: require('./VIDEO_TIMEOUT_EVENT'), + VIDEO_UNLOCKED: require('./VIDEO_UNLOCKED_EVENT') + +}; diff --git a/src/gameobjects/extern/Extern.js b/src/gameobjects/extern/Extern.js index 1fceab854..75966c719 100644 --- a/src/gameobjects/extern/Extern.js +++ b/src/gameobjects/extern/Extern.js @@ -1,90 +1,90 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var ExternRender = require('./ExternRender'); - -/** - * @classdesc - * An Extern Game Object is a special type of Game Object that allows you to pass - * rendering off to a 3rd party. - * - * When you create an Extern and place it in the display list of a Scene, the renderer will - * process the list as usual. When it finds an Extern it will flush the current batch, - * clear down the pipeline and prepare a transform matrix which your render function can - * take advantage of, if required. - * - * The WebGL context is then left is a 'clean' state, ready for you to bind your own shaders, - * or draw to it, whatever you wish to do. Once you've finished, you should free-up any - * of your resources. The Extern will then rebind the Phaser pipeline and carry on - * rendering the display list. - * - * Although this object has lots of properties such as Alpha, Blend Mode and Tint, none of - * them are used during rendering unless you take advantage of them in your own render code. - * - * @class Extern - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.16.0 - * - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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. A Game Object can only belong to one Scene at a time. - */ -var Extern = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.Origin, - Components.ScrollFactor, - Components.Size, - Components.Texture, - Components.Tint, - Components.Transform, - Components.Visible, - ExternRender - ], - - initialize: - - function Extern (scene) - { - GameObject.call(this, scene, 'Extern'); - }, - - preUpdate: function () - { - // override this! - // Arguments: time, delta - }, - - render: function () - { - // override this! - // Arguments: renderer, camera, calcMatrix - } - -}); - -module.exports = Extern; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var ExternRender = require('./ExternRender'); + +/** + * @classdesc + * An Extern Game Object is a special type of Game Object that allows you to pass + * rendering off to a 3rd party. + * + * When you create an Extern and place it in the display list of a Scene, the renderer will + * process the list as usual. When it finds an Extern it will flush the current batch, + * clear down the pipeline and prepare a transform matrix which your render function can + * take advantage of, if required. + * + * The WebGL context is then left is a 'clean' state, ready for you to bind your own shaders, + * or draw to it, whatever you wish to do. Once you've finished, you should free-up any + * of your resources. The Extern will then rebind the Phaser pipeline and carry on + * rendering the display list. + * + * Although this object has lots of properties such as Alpha, Blend Mode and Tint, none of + * them are used during rendering unless you take advantage of them in your own render code. + * + * @class Extern + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.16.0 + * + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. A Game Object can only belong to one Scene at a time. + */ +var Extern = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.Origin, + Components.ScrollFactor, + Components.Size, + Components.Texture, + Components.Tint, + Components.Transform, + Components.Visible, + ExternRender + ], + + initialize: + + function Extern (scene) + { + GameObject.call(this, scene, 'Extern'); + }, + + preUpdate: function () + { + // override this! + // Arguments: time, delta + }, + + render: function () + { + // override this! + // Arguments: renderer, camera, calcMatrix + } + +}); + +module.exports = Extern; diff --git a/src/gameobjects/extern/ExternFactory.js b/src/gameobjects/extern/ExternFactory.js index 269e5b968..c6d3476ba 100644 --- a/src/gameobjects/extern/ExternFactory.js +++ b/src/gameobjects/extern/ExternFactory.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Extern = require('./Extern'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Extern Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Extern Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#extern - * @since 3.16.0 - * - * @return {Phaser.GameObjects.Extern} The Game Object that was created. - */ -GameObjectFactory.register('extern', function () -{ - var extern = new Extern(this.scene); - - this.displayList.add(extern); - this.updateList.add(extern); - - return extern; -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extern = require('./Extern'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Extern Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Extern Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#extern + * @since 3.16.0 + * + * @return {Phaser.GameObjects.Extern} The Game Object that was created. + */ +GameObjectFactory.register('extern', function () +{ + var extern = new Extern(this.scene); + + this.displayList.add(extern); + this.updateList.add(extern); + + return extern; +}); + +// 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 diff --git a/src/gameobjects/extern/ExternRender.js b/src/gameobjects/extern/ExternRender.js index a9dd107c8..fbfe6f8f9 100644 --- a/src/gameobjects/extern/ExternRender.js +++ b/src/gameobjects/extern/ExternRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./ExternWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./ExternCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./ExternWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./ExternCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/extern/ExternWebGLRenderer.js b/src/gameobjects/extern/ExternWebGLRenderer.js index a4ebb4b95..6aa35b044 100644 --- a/src/gameobjects/extern/ExternWebGLRenderer.js +++ b/src/gameobjects/extern/ExternWebGLRenderer.js @@ -1,63 +1,63 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Extern#renderWebGL - * @since 3.16.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Extern} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ExternWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = renderer.currentPipeline; - - renderer.clearPipeline(); - - var camMatrix = renderer._tempMatrix1; - var spriteMatrix = renderer._tempMatrix2; - var calcMatrix = renderer._tempMatrix3; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - // Callback - src.render.call(src, renderer, camera, calcMatrix); - - renderer.rebindPipeline(pipeline); -}; - -module.exports = ExternWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Extern#renderWebGL + * @since 3.16.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Extern} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ExternWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = renderer.currentPipeline; + + renderer.clearPipeline(); + + var camMatrix = renderer._tempMatrix1; + var spriteMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + // Callback + src.render.call(src, renderer, camera, calcMatrix); + + renderer.rebindPipeline(pipeline); +}; + +module.exports = ExternWebGLRenderer; diff --git a/src/gameobjects/graphics/Commands.js b/src/gameobjects/graphics/Commands.js index 494156f70..7adc38bd2 100644 --- a/src/gameobjects/graphics/Commands.js +++ b/src/gameobjects/graphics/Commands.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -module.exports = { - - ARC: 0, - BEGIN_PATH: 1, - CLOSE_PATH: 2, - FILL_RECT: 3, - LINE_TO: 4, - MOVE_TO: 5, - LINE_STYLE: 6, - FILL_STYLE: 7, - FILL_PATH: 8, - STROKE_PATH: 9, - FILL_TRIANGLE: 10, - STROKE_TRIANGLE: 11, - SAVE: 14, - RESTORE: 15, - TRANSLATE: 16, - SCALE: 17, - ROTATE: 18, - SET_TEXTURE: 19, - CLEAR_TEXTURE: 20, - GRADIENT_FILL_STYLE: 21, - GRADIENT_LINE_STYLE: 22 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +module.exports = { + + ARC: 0, + BEGIN_PATH: 1, + CLOSE_PATH: 2, + FILL_RECT: 3, + LINE_TO: 4, + MOVE_TO: 5, + LINE_STYLE: 6, + FILL_STYLE: 7, + FILL_PATH: 8, + STROKE_PATH: 9, + FILL_TRIANGLE: 10, + STROKE_TRIANGLE: 11, + SAVE: 14, + RESTORE: 15, + TRANSLATE: 16, + SCALE: 17, + ROTATE: 18, + SET_TEXTURE: 19, + CLEAR_TEXTURE: 20, + GRADIENT_FILL_STYLE: 21, + GRADIENT_LINE_STYLE: 22 + +}; diff --git a/src/gameobjects/graphics/Graphics.js b/src/gameobjects/graphics/Graphics.js index 0cfd61bab..0a7ad7e89 100644 --- a/src/gameobjects/graphics/Graphics.js +++ b/src/gameobjects/graphics/Graphics.js @@ -1,1544 +1,1544 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseCamera = require('../../cameras/2d/BaseCamera.js'); -var Class = require('../../utils/Class'); -var Commands = require('./Commands'); -var ComponentsAlpha = require('../components/AlphaSingle'); -var ComponentsBlendMode = require('../components/BlendMode'); -var ComponentsDepth = require('../components/Depth'); -var ComponentsMask = require('../components/Mask'); -var ComponentsPipeline = require('../components/Pipeline'); -var ComponentsTransform = require('../components/Transform'); -var ComponentsVisible = require('../components/Visible'); -var ComponentsScrollFactor = require('../components/ScrollFactor'); - -var TransformMatrix = require('../components/TransformMatrix'); - -var Ellipse = require('../../geom/ellipse/Ellipse'); -var GameObject = require('../GameObject'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetValue = require('../../utils/object/GetValue'); -var MATH_CONST = require('../../math/const'); -var Render = require('./GraphicsRender'); - -/** - * @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. - * - * 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.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @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. - */ -var Graphics = new Class({ - - Extends: GameObject, - - Mixins: [ - ComponentsAlpha, - ComponentsBlendMode, - ComponentsDepth, - ComponentsMask, - ComponentsPipeline, - ComponentsTransform, - ComponentsVisible, - ComponentsScrollFactor, - Render - ], - - initialize: - - function Graphics (scene, options) - { - var x = GetValue(options, 'x', 0); - var y = GetValue(options, 'y', 0); - - GameObject.call(this, scene, 'Graphics'); - - this.setPosition(x, y); - this.initPipeline(); - - /** - * The horizontal display origin of the Graphics. - * - * @name Phaser.GameObjects.Graphics#displayOriginX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.displayOriginX = 0; - - /** - * The vertical display origin of the Graphics. - * - * @name Phaser.GameObjects.Graphics#displayOriginY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.displayOriginY = 0; - - /** - * The array of commands used to render the Graphics. - * - * @name Phaser.GameObjects.Graphics#commandBuffer - * @type {array} - * @default [] - * @since 3.0.0 - */ - this.commandBuffer = []; - - /** - * The default fill color for shapes rendered by this Graphics object. - * - * @name Phaser.GameObjects.Graphics#defaultFillColor - * @type {number} - * @default -1 - * @since 3.0.0 - */ - this.defaultFillColor = -1; - - /** - * The default fill alpha for shapes rendered by this Graphics object. - * - * @name Phaser.GameObjects.Graphics#defaultFillAlpha - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.defaultFillAlpha = 1; - - /** - * The default stroke width for shapes rendered by this Graphics object. - * - * @name Phaser.GameObjects.Graphics#defaultStrokeWidth - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.defaultStrokeWidth = 1; - - /** - * The default stroke color for shapes rendered by this Graphics object. - * - * @name Phaser.GameObjects.Graphics#defaultStrokeColor - * @type {number} - * @default -1 - * @since 3.0.0 - */ - this.defaultStrokeColor = -1; - - /** - * The default stroke alpha for shapes rendered by this Graphics object. - * - * @name Phaser.GameObjects.Graphics#defaultStrokeAlpha - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.defaultStrokeAlpha = 1; - - /** - * Internal property that keeps track of the line width style setting. - * - * @name Phaser.GameObjects.Graphics#_lineWidth - * @type {number} - * @private - * @since 3.0.0 - */ - this._lineWidth = 1.0; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.GameObjects.Graphics#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.17.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.GameObjects.Graphics#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.17.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.GameObjects.Graphics#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.17.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - this.setDefaultStyles(options); - }, - - /** - * Set the default style settings for this Graphics object. - * - * @method Phaser.GameObjects.Graphics#setDefaultStyles - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Graphics.Styles} options - The styles to set as defaults. - * - * @return {this} This Game Object. - */ - setDefaultStyles: function (options) - { - if (GetValue(options, 'lineStyle', null)) - { - this.defaultStrokeWidth = GetValue(options, 'lineStyle.width', 1); - this.defaultStrokeColor = GetValue(options, 'lineStyle.color', 0xffffff); - this.defaultStrokeAlpha = GetValue(options, 'lineStyle.alpha', 1); - - this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha); - } - - if (GetValue(options, 'fillStyle', null)) - { - this.defaultFillColor = GetValue(options, 'fillStyle.color', 0xffffff); - this.defaultFillAlpha = GetValue(options, 'fillStyle.alpha', 1); - - this.fillStyle(this.defaultFillColor, this.defaultFillAlpha); - } - - return this; - }, - - /** - * Set the current line style. - * - * @method Phaser.GameObjects.Graphics#lineStyle - * @since 3.0.0 - * - * @param {number} lineWidth - The stroke width. - * @param {number} color - The stroke color. - * @param {number} [alpha=1] - The stroke alpha. - * - * @return {this} This Game Object. - */ - lineStyle: function (lineWidth, color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - this.commandBuffer.push( - Commands.LINE_STYLE, - lineWidth, color, alpha - ); - - this._lineWidth = lineWidth; - - return this; - }, - - /** - * Set the current fill style. - * - * @method Phaser.GameObjects.Graphics#fillStyle - * @since 3.0.0 - * - * @param {number} color - The fill color. - * @param {number} [alpha=1] - The fill alpha. - * - * @return {this} This Game Object. - */ - fillStyle: function (color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - this.commandBuffer.push( - Commands.FILL_STYLE, - color, alpha - ); - - return this; - }, - - /** - * Sets a gradient fill style. This is a WebGL only feature. - * - * The gradient color values represent the 4 corners of an untransformed rectangle. - * The gradient is used to color all filled shapes and paths drawn after calling this method. - * If you wish to turn a gradient off, call `fillStyle` and provide a new single fill color. - * - * When filling a triangle only the first 3 color values provided are used for the 3 points of a triangle. - * - * This feature is best used only on rectangles and triangles. All other shapes will give strange results. - * - * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used - * will be filled with a gradient on its own. There is no ability to gradient fill a shape or path as a single - * entity at this time. - * - * @method Phaser.GameObjects.Graphics#fillGradientStyle - * @webglOnly - * @since 3.12.0 - * - * @param {integer} topLeft - The tint being applied to the top-left of the Game Object. - * @param {integer} topRight - The tint being applied to the top-right of the Game Object. - * @param {integer} bottomLeft - The tint being applied to the bottom-left of the Game Object. - * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. - * @param {number} [alpha=1] - The fill alpha. - * - * @return {this} This Game Object. - */ - fillGradientStyle: function (topLeft, topRight, bottomLeft, bottomRight, alpha) - { - if (alpha === undefined) { alpha = 1; } - - this.commandBuffer.push( - Commands.GRADIENT_FILL_STYLE, - alpha, topLeft, topRight, bottomLeft, bottomRight - ); - - return this; - }, - - /** - * Sets a gradient line style. This is a WebGL only feature. - * - * The gradient color values represent the 4 corners of an untransformed rectangle. - * The gradient is used to color all stroked shapes and paths drawn after calling this method. - * If you wish to turn a gradient off, call `lineStyle` and provide a new single line color. - * - * This feature is best used only on single lines. All other shapes will give strange results. - * - * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used - * will be filled with a gradient on its own. There is no ability to gradient stroke a shape or path as a single - * entity at this time. - * - * @method Phaser.GameObjects.Graphics#lineGradientStyle - * @webglOnly - * @since 3.12.0 - * - * @param {number} lineWidth - The stroke width. - * @param {integer} topLeft - The tint being applied to the top-left of the Game Object. - * @param {integer} topRight - The tint being applied to the top-right of the Game Object. - * @param {integer} bottomLeft - The tint being applied to the bottom-left of the Game Object. - * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. - * @param {number} [alpha=1] - The fill alpha. - * - * @return {this} This Game Object. - */ - lineGradientStyle: function (lineWidth, topLeft, topRight, bottomLeft, bottomRight, alpha) - { - if (alpha === undefined) { alpha = 1; } - - this.commandBuffer.push( - Commands.GRADIENT_LINE_STYLE, - lineWidth, alpha, topLeft, topRight, bottomLeft, bottomRight - ); - - return this; - }, - - /** - * Sets the texture frame this Graphics Object will use when drawing all shapes defined after calling this. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * Once set, all shapes will use this texture. Call this method with no arguments to clear it. - * - * The textures are not tiled. They are stretched to the dimensions of the shapes being rendered. For this reason, - * it works best with seamless / tileable textures. - * - * The mode argument controls how the textures are combined with the fill colors. The default value (0) will - * multiply the texture by the fill color. A value of 1 will use just the fill color, but the alpha data from the texture, - * and a value of 2 will use just the texture and no fill color at all. - * - * @method Phaser.GameObjects.Graphics#setTexture - * @since 3.12.0 - * @webglOnly - * - * @param {string} [key] - The key of the texture to be used, as stored in the Texture Manager. Leave blank to clear a previously set texture. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * @param {number} [mode=0] - The texture tint mode. 0 is multiply, 1 is alpha only and 2 is texture only. - * - * @return {this} This Game Object. - */ - setTexture: function (key, frame, mode) - { - if (mode === undefined) { mode = 0; } - - if (key === undefined) - { - this.commandBuffer.push( - Commands.CLEAR_TEXTURE - ); - } - else - { - var textureFrame = this.scene.sys.textures.getFrame(key, frame); - - if (textureFrame) - { - if (mode === 2) - { - mode = 3; - } - - this.commandBuffer.push( - Commands.SET_TEXTURE, - textureFrame, - mode - ); - } - } - - return this; - }, - - /** - * Start a new shape path. - * - * @method Phaser.GameObjects.Graphics#beginPath - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - beginPath: function () - { - this.commandBuffer.push( - Commands.BEGIN_PATH - ); - - return this; - }, - - /** - * Close the current path. - * - * @method Phaser.GameObjects.Graphics#closePath - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - closePath: function () - { - this.commandBuffer.push( - Commands.CLOSE_PATH - ); - - return this; - }, - - /** - * Fill the current path. - * - * @method Phaser.GameObjects.Graphics#fillPath - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - fillPath: function () - { - this.commandBuffer.push( - Commands.FILL_PATH - ); - - return this; - }, - - /** - * Fill the current path. - * - * This is an alias for `Graphics.fillPath` and does the same thing. - * It was added to match the CanvasRenderingContext 2D API. - * - * @method Phaser.GameObjects.Graphics#fill - * @since 3.16.0 - * - * @return {this} This Game Object. - */ - fill: function () - { - this.commandBuffer.push( - Commands.FILL_PATH - ); - - return this; - }, - - /** - * Stroke the current path. - * - * @method Phaser.GameObjects.Graphics#strokePath - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - strokePath: function () - { - this.commandBuffer.push( - Commands.STROKE_PATH - ); - - return this; - }, - - /** - * Stroke the current path. - * - * This is an alias for `Graphics.strokePath` and does the same thing. - * It was added to match the CanvasRenderingContext 2D API. - * - * @method Phaser.GameObjects.Graphics#stroke - * @since 3.16.0 - * - * @return {this} This Game Object. - */ - stroke: function () - { - this.commandBuffer.push( - Commands.STROKE_PATH - ); - - return this; - }, - - /** - * Fill the given circle. - * - * @method Phaser.GameObjects.Graphics#fillCircleShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The circle to fill. - * - * @return {this} This Game Object. - */ - fillCircleShape: function (circle) - { - return this.fillCircle(circle.x, circle.y, circle.radius); - }, - - /** - * Stroke the given circle. - * - * @method Phaser.GameObjects.Graphics#strokeCircleShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The circle to stroke. - * - * @return {this} This Game Object. - */ - strokeCircleShape: function (circle) - { - return this.strokeCircle(circle.x, circle.y, circle.radius); - }, - - /** - * Fill a circle with the given position and radius. - * - * @method Phaser.GameObjects.Graphics#fillCircle - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the center of the circle. - * @param {number} y - The y coordinate of the center of the circle. - * @param {number} radius - The radius of the circle. - * - * @return {this} This Game Object. - */ - fillCircle: function (x, y, radius) - { - this.beginPath(); - this.arc(x, y, radius, 0, MATH_CONST.PI2); - this.fillPath(); - - return this; - }, - - /** - * Stroke a circle with the given position and radius. - * - * @method Phaser.GameObjects.Graphics#strokeCircle - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the center of the circle. - * @param {number} y - The y coordinate of the center of the circle. - * @param {number} radius - The radius of the circle. - * - * @return {this} This Game Object. - */ - strokeCircle: function (x, y, radius) - { - this.beginPath(); - this.arc(x, y, radius, 0, MATH_CONST.PI2); - this.strokePath(); - - return this; - }, - - /** - * Fill the given rectangle. - * - * @method Phaser.GameObjects.Graphics#fillRectShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The rectangle to fill. - * - * @return {this} This Game Object. - */ - fillRectShape: function (rect) - { - return this.fillRect(rect.x, rect.y, rect.width, rect.height); - }, - - /** - * Stroke the given rectangle. - * - * @method Phaser.GameObjects.Graphics#strokeRectShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The rectangle to stroke. - * - * @return {this} This Game Object. - */ - strokeRectShape: function (rect) - { - return this.strokeRect(rect.x, rect.y, rect.width, rect.height); - }, - - /** - * Fill a rectangle with the given position and size. - * - * @method Phaser.GameObjects.Graphics#fillRect - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the top-left of the rectangle. - * @param {number} y - The y coordinate of the top-left of the rectangle. - * @param {number} width - The width of the rectangle. - * @param {number} height - The height of the rectangle. - * - * @return {this} This Game Object. - */ - fillRect: function (x, y, width, height) - { - this.commandBuffer.push( - Commands.FILL_RECT, - x, y, width, height - ); - - return this; - }, - - /** - * Stroke a rectangle with the given position and size. - * - * @method Phaser.GameObjects.Graphics#strokeRect - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the top-left of the rectangle. - * @param {number} y - The y coordinate of the top-left of the rectangle. - * @param {number} width - The width of the rectangle. - * @param {number} height - The height of the rectangle. - * - * @return {this} This Game Object. - */ - strokeRect: function (x, y, width, height) - { - var lineWidthHalf = this._lineWidth / 2; - var minx = x - lineWidthHalf; - var maxx = x + lineWidthHalf; - - this.beginPath(); - this.moveTo(x, y); - this.lineTo(x, y + height); - this.strokePath(); - - this.beginPath(); - this.moveTo(x + width, y); - this.lineTo(x + width, y + height); - this.strokePath(); - - this.beginPath(); - this.moveTo(minx, y); - this.lineTo(maxx + width, y); - this.strokePath(); - - this.beginPath(); - this.moveTo(minx, y + height); - this.lineTo(maxx + width, y + height); - this.strokePath(); - - return this; - }, - - /** - * Fill a rounded rectangle with the given position, size and radius. - * - * @method Phaser.GameObjects.Graphics#fillRoundedRect - * @since 3.11.0 - * - * @param {number} x - The x coordinate of the top-left of the rectangle. - * @param {number} y - The y coordinate of the top-left of the rectangle. - * @param {number} width - The width of the rectangle. - * @param {number} height - The height of the rectangle. - * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. - * - * @return {this} This Game Object. - */ - fillRoundedRect: function (x, y, width, height, radius) - { - if (radius === undefined) { radius = 20; } - - var tl = radius; - var tr = radius; - var bl = radius; - var br = radius; - - if (typeof radius !== 'number') - { - tl = GetFastValue(radius, 'tl', 20); - tr = GetFastValue(radius, 'tr', 20); - bl = GetFastValue(radius, 'bl', 20); - br = GetFastValue(radius, 'br', 20); - } - - this.beginPath(); - this.moveTo(x + tl, y); - this.lineTo(x + width - tr, y); - this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); - this.lineTo(x + width, y + height - br); - this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); - this.lineTo(x + bl, y + height); - this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); - this.lineTo(x, y + tl); - this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); - this.fillPath(); - - return this; - }, - - /** - * Stroke a rounded rectangle with the given position, size and radius. - * - * @method Phaser.GameObjects.Graphics#strokeRoundedRect - * @since 3.11.0 - * - * @param {number} x - The x coordinate of the top-left of the rectangle. - * @param {number} y - The y coordinate of the top-left of the rectangle. - * @param {number} width - The width of the rectangle. - * @param {number} height - The height of the rectangle. - * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. - * - * @return {this} This Game Object. - */ - strokeRoundedRect: function (x, y, width, height, radius) - { - if (radius === undefined) { radius = 20; } - - var tl = radius; - var tr = radius; - var bl = radius; - var br = radius; - - if (typeof radius !== 'number') - { - tl = GetFastValue(radius, 'tl', 20); - tr = GetFastValue(radius, 'tr', 20); - bl = GetFastValue(radius, 'bl', 20); - br = GetFastValue(radius, 'br', 20); - } - - this.beginPath(); - this.moveTo(x + tl, y); - this.lineTo(x + width - tr, y); - this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); - this.lineTo(x + width, y + height - br); - this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); - this.lineTo(x + bl, y + height); - this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); - this.lineTo(x, y + tl); - this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); - this.strokePath(); - - return this; - }, - - /** - * Fill the given point. - * - * Draws a square at the given position, 1 pixel in size by default. - * - * @method Phaser.GameObjects.Graphics#fillPointShape - * @since 3.0.0 - * - * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The point to fill. - * @param {number} [size=1] - The size of the square to draw. - * - * @return {this} This Game Object. - */ - fillPointShape: function (point, size) - { - return this.fillPoint(point.x, point.y, size); - }, - - /** - * Fill a point at the given position. - * - * Draws a square at the given position, 1 pixel in size by default. - * - * @method Phaser.GameObjects.Graphics#fillPoint - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the point. - * @param {number} y - The y coordinate of the point. - * @param {number} [size=1] - The size of the square to draw. - * - * @return {this} This Game Object. - */ - fillPoint: function (x, y, size) - { - if (!size || size < 1) - { - size = 1; - } - else - { - x -= (size / 2); - y -= (size / 2); - } - - this.commandBuffer.push( - Commands.FILL_RECT, - x, y, size, size - ); - - return this; - }, - - /** - * Fill the given triangle. - * - * @method Phaser.GameObjects.Graphics#fillTriangleShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The triangle to fill. - * - * @return {this} This Game Object. - */ - fillTriangleShape: function (triangle) - { - return this.fillTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3); - }, - - /** - * Stroke the given triangle. - * - * @method Phaser.GameObjects.Graphics#strokeTriangleShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The triangle to stroke. - * - * @return {this} This Game Object. - */ - strokeTriangleShape: function (triangle) - { - return this.strokeTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3); - }, - - /** - * Fill a triangle with the given points. - * - * @method Phaser.GameObjects.Graphics#fillTriangle - * @since 3.0.0 - * - * @param {number} x0 - The x coordinate of the first point. - * @param {number} y0 - The y coordinate of the first point. - * @param {number} x1 - The x coordinate of the second point. - * @param {number} y1 - The y coordinate of the second point. - * @param {number} x2 - The x coordinate of the third point. - * @param {number} y2 - The y coordinate of the third point. - * - * @return {this} This Game Object. - */ - fillTriangle: function (x0, y0, x1, y1, x2, y2) - { - this.commandBuffer.push( - Commands.FILL_TRIANGLE, - x0, y0, x1, y1, x2, y2 - ); - - return this; - }, - - /** - * Stroke a triangle with the given points. - * - * @method Phaser.GameObjects.Graphics#strokeTriangle - * @since 3.0.0 - * - * @param {number} x0 - The x coordinate of the first point. - * @param {number} y0 - The y coordinate of the first point. - * @param {number} x1 - The x coordinate of the second point. - * @param {number} y1 - The y coordinate of the second point. - * @param {number} x2 - The x coordinate of the third point. - * @param {number} y2 - The y coordinate of the third point. - * - * @return {this} This Game Object. - */ - strokeTriangle: function (x0, y0, x1, y1, x2, y2) - { - this.commandBuffer.push( - Commands.STROKE_TRIANGLE, - x0, y0, x1, y1, x2, y2 - ); - - return this; - }, - - /** - * Draw the given line. - * - * @method Phaser.GameObjects.Graphics#strokeLineShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to stroke. - * - * @return {this} This Game Object. - */ - strokeLineShape: function (line) - { - return this.lineBetween(line.x1, line.y1, line.x2, line.y2); - }, - - /** - * Draw a line between the given points. - * - * @method Phaser.GameObjects.Graphics#lineBetween - * @since 3.0.0 - * - * @param {number} x1 - The x coordinate of the start point of the line. - * @param {number} y1 - The y coordinate of the start point of the line. - * @param {number} x2 - The x coordinate of the end point of the line. - * @param {number} y2 - The y coordinate of the end point of the line. - * - * @return {this} This Game Object. - */ - lineBetween: function (x1, y1, x2, y2) - { - this.beginPath(); - this.moveTo(x1, y1); - this.lineTo(x2, y2); - this.strokePath(); - - return this; - }, - - /** - * Draw a line from the current drawing position to the given position. - * - * Moves the current drawing position to the given position. - * - * @method Phaser.GameObjects.Graphics#lineTo - * @since 3.0.0 - * - * @param {number} x - The x coordinate to draw the line to. - * @param {number} y - The y coordinate to draw the line to. - * - * @return {this} This Game Object. - */ - lineTo: function (x, y) - { - this.commandBuffer.push( - Commands.LINE_TO, - x, y - ); - - return this; - }, - - /** - * Move the current drawing position to the given position. - * - * @method Phaser.GameObjects.Graphics#moveTo - * @since 3.0.0 - * - * @param {number} x - The x coordinate to move to. - * @param {number} y - The y coordinate to move to. - * - * @return {this} This Game Object. - */ - moveTo: function (x, y) - { - this.commandBuffer.push( - Commands.MOVE_TO, - x, y - ); - - return this; - }, - - /** - * Stroke the shape represented by the given array of points. - * - * Pass `closeShape` to automatically close the shape by joining the last to the first point. - * - * Pass `closePath` to automatically close the path before it is stroked. - * - * @method Phaser.GameObjects.Graphics#strokePoints - * @since 3.0.0 - * - * @param {(array|Phaser.Geom.Point[])} points - The points to stroke. - * @param {boolean} [closeShape=false] - When `true`, the shape is closed by joining the last point to the first point. - * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. - * @param {integer} [endIndex] - The index of `points` to stop drawing at. Defaults to `points.length`. - * - * @return {this} This Game Object. - */ - strokePoints: function (points, closeShape, closePath, endIndex) - { - if (closeShape === undefined) { closeShape = false; } - if (closePath === undefined) { closePath = false; } - if (endIndex === undefined) { endIndex = points.length; } - - this.beginPath(); - - this.moveTo(points[0].x, points[0].y); - - for (var i = 1; i < endIndex; i++) - { - this.lineTo(points[i].x, points[i].y); - } - - if (closeShape) - { - this.lineTo(points[0].x, points[0].y); - } - - if (closePath) - { - this.closePath(); - } - - this.strokePath(); - - return this; - }, - - /** - * Fill the shape represented by the given array of points. - * - * Pass `closeShape` to automatically close the shape by joining the last to the first point. - * - * Pass `closePath` to automatically close the path before it is filled. - * - * @method Phaser.GameObjects.Graphics#fillPoints - * @since 3.0.0 - * - * @param {(array|Phaser.Geom.Point[])} points - The points to fill. - * @param {boolean} [closeShape=false] - When `true`, the shape is closed by joining the last point to the first point. - * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. - * @param {integer} [endIndex] - The index of `points` to stop at. Defaults to `points.length`. - * - * @return {this} This Game Object. - */ - fillPoints: function (points, closeShape, closePath, endIndex) - { - if (closeShape === undefined) { closeShape = false; } - if (closePath === undefined) { closePath = false; } - if (endIndex === undefined) { endIndex = points.length; } - - this.beginPath(); - - this.moveTo(points[0].x, points[0].y); - - for (var i = 1; i < endIndex; i++) - { - this.lineTo(points[i].x, points[i].y); - } - - if (closeShape) - { - this.lineTo(points[0].x, points[0].y); - } - - if (closePath) - { - this.closePath(); - } - - this.fillPath(); - - return this; - }, - - /** - * Stroke the given ellipse. - * - * @method Phaser.GameObjects.Graphics#strokeEllipseShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to stroke. - * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. - * - * @return {this} This Game Object. - */ - strokeEllipseShape: function (ellipse, smoothness) - { - if (smoothness === undefined) { smoothness = 32; } - - var points = ellipse.getPoints(smoothness); - - return this.strokePoints(points, true); - }, - - /** - * Stroke an ellipse with the given position and size. - * - * @method Phaser.GameObjects.Graphics#strokeEllipse - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the center of the ellipse. - * @param {number} y - The y coordinate of the center of the ellipse. - * @param {number} width - The width of the ellipse. - * @param {number} height - The height of the ellipse. - * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. - * - * @return {this} This Game Object. - */ - strokeEllipse: function (x, y, width, height, smoothness) - { - if (smoothness === undefined) { smoothness = 32; } - - var ellipse = new Ellipse(x, y, width, height); - - var points = ellipse.getPoints(smoothness); - - return this.strokePoints(points, true); - }, - - /** - * Fill the given ellipse. - * - * @method Phaser.GameObjects.Graphics#fillEllipseShape - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to fill. - * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. - * - * @return {this} This Game Object. - */ - fillEllipseShape: function (ellipse, smoothness) - { - if (smoothness === undefined) { smoothness = 32; } - - var points = ellipse.getPoints(smoothness); - - return this.fillPoints(points, true); - }, - - /** - * Fill an ellipse with the given position and size. - * - * @method Phaser.GameObjects.Graphics#fillEllipse - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the center of the ellipse. - * @param {number} y - The y coordinate of the center of the ellipse. - * @param {number} width - The width of the ellipse. - * @param {number} height - The height of the ellipse. - * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. - * - * @return {this} This Game Object. - */ - fillEllipse: function (x, y, width, height, smoothness) - { - if (smoothness === undefined) { smoothness = 32; } - - var ellipse = new Ellipse(x, y, width, height); - - var points = ellipse.getPoints(smoothness); - - return this.fillPoints(points, true); - }, - - /** - * Draw an arc. - * - * This method can be used to create circles, or parts of circles. - * - * Make sure you call `beginPath` before starting the arc unless you wish for the arc to automatically - * close when filled or stroked. - * - * Use the optional `overshoot` argument increase the number of iterations that take place when - * the arc is rendered in WebGL. This is useful if you're drawing an arc with an especially thick line, - * as it will allow the arc to fully join-up. Try small values at first, i.e. 0.01. - * - * Call {@link Phaser.GameObjects.Graphics#fillPath} or {@link Phaser.GameObjects.Graphics#strokePath} after calling - * this method to draw the arc. - * - * @method Phaser.GameObjects.Graphics#arc - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the center of the circle. - * @param {number} y - The y coordinate of the center of the circle. - * @param {number} radius - The radius of the circle. - * @param {number} startAngle - The starting angle, in radians. - * @param {number} endAngle - The ending angle, in radians. - * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. - * @param {number} [overshoot=0] - This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. - * - * @return {this} This Game Object. - */ - arc: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) - { - if (anticlockwise === undefined) { anticlockwise = false; } - if (overshoot === undefined) { overshoot = 0; } - - this.commandBuffer.push( - Commands.ARC, - x, y, radius, startAngle, endAngle, anticlockwise, overshoot - ); - - return this; - }, - - /** - * Creates a pie-chart slice shape centered at `x`, `y` with the given radius. - * You must define the start and end angle of the slice. - * - * Setting the `anticlockwise` argument to `true` creates a shape similar to Pacman. - * Setting it to `false` creates a shape like a slice of pie. - * - * This method will begin a new path and close the path at the end of it. - * To display the actual slice you need to call either `strokePath` or `fillPath` after it. - * - * @method Phaser.GameObjects.Graphics#slice - * @since 3.4.0 - * - * @param {number} x - The horizontal center of the slice. - * @param {number} y - The vertical center of the slice. - * @param {number} radius - The radius of the slice. - * @param {number} startAngle - The start angle of the slice, given in radians. - * @param {number} endAngle - The end angle of the slice, given in radians. - * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. - * @param {number} [overshoot=0] - This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. - * - * @return {this} This Game Object. - */ - slice: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) - { - if (anticlockwise === undefined) { anticlockwise = false; } - if (overshoot === undefined) { overshoot = 0; } - - this.commandBuffer.push(Commands.BEGIN_PATH); - - this.commandBuffer.push(Commands.MOVE_TO, x, y); - - this.commandBuffer.push(Commands.ARC, x, y, radius, startAngle, endAngle, anticlockwise, overshoot); - - this.commandBuffer.push(Commands.CLOSE_PATH); - - return this; - }, - - /** - * Saves the state of the Graphics by pushing the current state onto a stack. - * - * The most recently saved state can then be restored with {@link Phaser.GameObjects.Graphics#restore}. - * - * @method Phaser.GameObjects.Graphics#save - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - save: function () - { - this.commandBuffer.push( - Commands.SAVE - ); - - return this; - }, - - /** - * Restores the most recently saved state of the Graphics by popping from the state stack. - * - * Use {@link Phaser.GameObjects.Graphics#save} to save the current state, and call this afterwards to restore that state. - * - * If there is no saved state, this command does nothing. - * - * @method Phaser.GameObjects.Graphics#restore - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - restore: function () - { - this.commandBuffer.push( - Commands.RESTORE - ); - - return this; - }, - - /** - * Inserts a translation command into this Graphics objects command buffer. - * - * All objects drawn _after_ calling this method will be translated - * by the given amount. - * - * This does not change the position of the Graphics object itself, - * only of the objects drawn by it after calling this method. - * - * @method Phaser.GameObjects.Graphics#translateCanvas - * @since 3.0.0 - * - * @param {number} x - The horizontal translation to apply. - * @param {number} y - The vertical translation to apply. - * - * @return {this} This Game Object. - */ - translateCanvas: function (x, y) - { - this.commandBuffer.push( - Commands.TRANSLATE, - x, y - ); - - return this; - }, - - /** - * Inserts a scale command into this Graphics objects command buffer. - * - * All objects drawn _after_ calling this method will be scaled - * by the given amount. - * - * This does not change the scale of the Graphics object itself, - * only of the objects drawn by it after calling this method. - * - * @method Phaser.GameObjects.Graphics#scaleCanvas - * @since 3.0.0 - * - * @param {number} x - The horizontal scale to apply. - * @param {number} y - The vertical scale to apply. - * - * @return {this} This Game Object. - */ - scaleCanvas: function (x, y) - { - this.commandBuffer.push( - Commands.SCALE, - x, y - ); - - return this; - }, - - /** - * Inserts a rotation command into this Graphics objects command buffer. - * - * All objects drawn _after_ calling this method will be rotated - * by the given amount. - * - * This does not change the rotation of the Graphics object itself, - * only of the objects drawn by it after calling this method. - * - * @method Phaser.GameObjects.Graphics#rotateCanvas - * @since 3.0.0 - * - * @param {number} radians - The rotation angle, in radians. - * - * @return {this} This Game Object. - */ - rotateCanvas: function (radians) - { - this.commandBuffer.push( - Commands.ROTATE, - radians - ); - - return this; - }, - - /** - * Clear the command buffer and reset the fill style and line style to their defaults. - * - * @method Phaser.GameObjects.Graphics#clear - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - clear: function () - { - this.commandBuffer.length = 0; - - if (this.defaultFillColor > -1) - { - this.fillStyle(this.defaultFillColor, this.defaultFillAlpha); - } - - if (this.defaultStrokeColor > -1) - { - this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha); - } - - return this; - }, - - /** - * Generate a texture from this Graphics object. - * - * If `key` is a string it'll generate a new texture using it and add it into the - * Texture Manager (assuming no key conflict happens). - * - * If `key` is a Canvas it will draw the texture to that canvas context. Note that it will NOT - * automatically upload it to the GPU in WebGL mode. - * - * @method Phaser.GameObjects.Graphics#generateTexture - * @since 3.0.0 - * - * @param {(string|HTMLCanvasElement)} key - The key to store the texture with in the Texture Manager, or a Canvas to draw to. - * @param {integer} [width] - The width of the graphics to generate. - * @param {integer} [height] - The height of the graphics to generate. - * - * @return {this} This Game Object. - */ - generateTexture: function (key, width, height) - { - var sys = this.scene.sys; - var renderer = sys.game.renderer; - - if (width === undefined) { width = sys.scale.width; } - if (height === undefined) { height = sys.scale.height; } - - Graphics.TargetCamera.setScene(this.scene); - Graphics.TargetCamera.setViewport(0, 0, width, height); - Graphics.TargetCamera.scrollX = this.x; - Graphics.TargetCamera.scrollY = this.y; - - var texture; - var ctx; - - if (typeof key === 'string') - { - if (sys.textures.exists(key)) - { - // Key is a string, it DOES exist in the Texture Manager AND is a canvas, so draw to it - - texture = sys.textures.get(key); - - var src = texture.getSourceImage(); - - if (src instanceof HTMLCanvasElement) - { - ctx = src.getContext('2d'); - } - } - else - { - // Key is a string and doesn't exist in the Texture Manager, so generate and save it - - texture = sys.textures.createCanvas(key, width, height); - - ctx = texture.getSourceImage().getContext('2d'); - } - } - else if (key instanceof HTMLCanvasElement) - { - // Key is a Canvas, so draw to it - - ctx = key.getContext('2d'); - } - - if (ctx) - { - // var GraphicsCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) - this.renderCanvas(renderer, this, 0, Graphics.TargetCamera, null, ctx, false); - - if (texture) - { - texture.refresh(); - } - } - - return this; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Graphics#preDestroy - * @protected - * @since 3.9.0 - */ - preDestroy: function () - { - this.commandBuffer = []; - } - -}); - -/** - * A Camera used specifically by the Graphics system for rendering to textures. - * - * @name Phaser.GameObjects.Graphics.TargetCamera - * @type {Phaser.Cameras.Scene2D.Camera} - * @since 3.1.0 - */ -Graphics.TargetCamera = new BaseCamera(); - -module.exports = Graphics; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCamera = require('../../cameras/2d/BaseCamera.js'); +var Class = require('../../utils/Class'); +var Commands = require('./Commands'); +var ComponentsAlpha = require('../components/AlphaSingle'); +var ComponentsBlendMode = require('../components/BlendMode'); +var ComponentsDepth = require('../components/Depth'); +var ComponentsMask = require('../components/Mask'); +var ComponentsPipeline = require('../components/Pipeline'); +var ComponentsTransform = require('../components/Transform'); +var ComponentsVisible = require('../components/Visible'); +var ComponentsScrollFactor = require('../components/ScrollFactor'); + +var TransformMatrix = require('../components/TransformMatrix'); + +var Ellipse = require('../../geom/ellipse/Ellipse'); +var GameObject = require('../GameObject'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetValue = require('../../utils/object/GetValue'); +var MATH_CONST = require('../../math/const'); +var Render = require('./GraphicsRender'); + +/** + * @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. + * + * 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.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @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. + */ +var Graphics = new Class({ + + Extends: GameObject, + + Mixins: [ + ComponentsAlpha, + ComponentsBlendMode, + ComponentsDepth, + ComponentsMask, + ComponentsPipeline, + ComponentsTransform, + ComponentsVisible, + ComponentsScrollFactor, + Render + ], + + initialize: + + function Graphics (scene, options) + { + var x = GetValue(options, 'x', 0); + var y = GetValue(options, 'y', 0); + + GameObject.call(this, scene, 'Graphics'); + + this.setPosition(x, y); + this.initPipeline(); + + /** + * The horizontal display origin of the Graphics. + * + * @name Phaser.GameObjects.Graphics#displayOriginX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.displayOriginX = 0; + + /** + * The vertical display origin of the Graphics. + * + * @name Phaser.GameObjects.Graphics#displayOriginY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.displayOriginY = 0; + + /** + * The array of commands used to render the Graphics. + * + * @name Phaser.GameObjects.Graphics#commandBuffer + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.commandBuffer = []; + + /** + * The default fill color for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultFillColor + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.defaultFillColor = -1; + + /** + * The default fill alpha for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultFillAlpha + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.defaultFillAlpha = 1; + + /** + * The default stroke width for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultStrokeWidth + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.defaultStrokeWidth = 1; + + /** + * The default stroke color for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultStrokeColor + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.defaultStrokeColor = -1; + + /** + * The default stroke alpha for shapes rendered by this Graphics object. + * + * @name Phaser.GameObjects.Graphics#defaultStrokeAlpha + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.defaultStrokeAlpha = 1; + + /** + * Internal property that keeps track of the line width style setting. + * + * @name Phaser.GameObjects.Graphics#_lineWidth + * @type {number} + * @private + * @since 3.0.0 + */ + this._lineWidth = 1.0; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Graphics#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Graphics#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Graphics#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + this.setDefaultStyles(options); + }, + + /** + * Set the default style settings for this Graphics object. + * + * @method Phaser.GameObjects.Graphics#setDefaultStyles + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Graphics.Styles} options - The styles to set as defaults. + * + * @return {this} This Game Object. + */ + setDefaultStyles: function (options) + { + if (GetValue(options, 'lineStyle', null)) + { + this.defaultStrokeWidth = GetValue(options, 'lineStyle.width', 1); + this.defaultStrokeColor = GetValue(options, 'lineStyle.color', 0xffffff); + this.defaultStrokeAlpha = GetValue(options, 'lineStyle.alpha', 1); + + this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha); + } + + if (GetValue(options, 'fillStyle', null)) + { + this.defaultFillColor = GetValue(options, 'fillStyle.color', 0xffffff); + this.defaultFillAlpha = GetValue(options, 'fillStyle.alpha', 1); + + this.fillStyle(this.defaultFillColor, this.defaultFillAlpha); + } + + return this; + }, + + /** + * Set the current line style. + * + * @method Phaser.GameObjects.Graphics#lineStyle + * @since 3.0.0 + * + * @param {number} lineWidth - The stroke width. + * @param {number} color - The stroke color. + * @param {number} [alpha=1] - The stroke alpha. + * + * @return {this} This Game Object. + */ + lineStyle: function (lineWidth, color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.LINE_STYLE, + lineWidth, color, alpha + ); + + this._lineWidth = lineWidth; + + return this; + }, + + /** + * Set the current fill style. + * + * @method Phaser.GameObjects.Graphics#fillStyle + * @since 3.0.0 + * + * @param {number} color - The fill color. + * @param {number} [alpha=1] - The fill alpha. + * + * @return {this} This Game Object. + */ + fillStyle: function (color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.FILL_STYLE, + color, alpha + ); + + return this; + }, + + /** + * Sets a gradient fill style. This is a WebGL only feature. + * + * The gradient color values represent the 4 corners of an untransformed rectangle. + * The gradient is used to color all filled shapes and paths drawn after calling this method. + * If you wish to turn a gradient off, call `fillStyle` and provide a new single fill color. + * + * When filling a triangle only the first 3 color values provided are used for the 3 points of a triangle. + * + * This feature is best used only on rectangles and triangles. All other shapes will give strange results. + * + * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used + * will be filled with a gradient on its own. There is no ability to gradient fill a shape or path as a single + * entity at this time. + * + * @method Phaser.GameObjects.Graphics#fillGradientStyle + * @webglOnly + * @since 3.12.0 + * + * @param {integer} topLeft - The tint being applied to the top-left of the Game Object. + * @param {integer} topRight - The tint being applied to the top-right of the Game Object. + * @param {integer} bottomLeft - The tint being applied to the bottom-left of the Game Object. + * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. + * @param {number} [alpha=1] - The fill alpha. + * + * @return {this} This Game Object. + */ + fillGradientStyle: function (topLeft, topRight, bottomLeft, bottomRight, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.GRADIENT_FILL_STYLE, + alpha, topLeft, topRight, bottomLeft, bottomRight + ); + + return this; + }, + + /** + * Sets a gradient line style. This is a WebGL only feature. + * + * The gradient color values represent the 4 corners of an untransformed rectangle. + * The gradient is used to color all stroked shapes and paths drawn after calling this method. + * If you wish to turn a gradient off, call `lineStyle` and provide a new single line color. + * + * This feature is best used only on single lines. All other shapes will give strange results. + * + * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used + * will be filled with a gradient on its own. There is no ability to gradient stroke a shape or path as a single + * entity at this time. + * + * @method Phaser.GameObjects.Graphics#lineGradientStyle + * @webglOnly + * @since 3.12.0 + * + * @param {number} lineWidth - The stroke width. + * @param {integer} topLeft - The tint being applied to the top-left of the Game Object. + * @param {integer} topRight - The tint being applied to the top-right of the Game Object. + * @param {integer} bottomLeft - The tint being applied to the bottom-left of the Game Object. + * @param {integer} bottomRight - The tint being applied to the bottom-right of the Game Object. + * @param {number} [alpha=1] - The fill alpha. + * + * @return {this} This Game Object. + */ + lineGradientStyle: function (lineWidth, topLeft, topRight, bottomLeft, bottomRight, alpha) + { + if (alpha === undefined) { alpha = 1; } + + this.commandBuffer.push( + Commands.GRADIENT_LINE_STYLE, + lineWidth, alpha, topLeft, topRight, bottomLeft, bottomRight + ); + + return this; + }, + + /** + * Sets the texture frame this Graphics Object will use when drawing all shapes defined after calling this. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * Once set, all shapes will use this texture. Call this method with no arguments to clear it. + * + * The textures are not tiled. They are stretched to the dimensions of the shapes being rendered. For this reason, + * it works best with seamless / tileable textures. + * + * The mode argument controls how the textures are combined with the fill colors. The default value (0) will + * multiply the texture by the fill color. A value of 1 will use just the fill color, but the alpha data from the texture, + * and a value of 2 will use just the texture and no fill color at all. + * + * @method Phaser.GameObjects.Graphics#setTexture + * @since 3.12.0 + * @webglOnly + * + * @param {string} [key] - The key of the texture to be used, as stored in the Texture Manager. Leave blank to clear a previously set texture. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * @param {number} [mode=0] - The texture tint mode. 0 is multiply, 1 is alpha only and 2 is texture only. + * + * @return {this} This Game Object. + */ + setTexture: function (key, frame, mode) + { + if (mode === undefined) { mode = 0; } + + if (key === undefined) + { + this.commandBuffer.push( + Commands.CLEAR_TEXTURE + ); + } + else + { + var textureFrame = this.scene.sys.textures.getFrame(key, frame); + + if (textureFrame) + { + if (mode === 2) + { + mode = 3; + } + + this.commandBuffer.push( + Commands.SET_TEXTURE, + textureFrame, + mode + ); + } + } + + return this; + }, + + /** + * Start a new shape path. + * + * @method Phaser.GameObjects.Graphics#beginPath + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + beginPath: function () + { + this.commandBuffer.push( + Commands.BEGIN_PATH + ); + + return this; + }, + + /** + * Close the current path. + * + * @method Phaser.GameObjects.Graphics#closePath + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + closePath: function () + { + this.commandBuffer.push( + Commands.CLOSE_PATH + ); + + return this; + }, + + /** + * Fill the current path. + * + * @method Phaser.GameObjects.Graphics#fillPath + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + fillPath: function () + { + this.commandBuffer.push( + Commands.FILL_PATH + ); + + return this; + }, + + /** + * Fill the current path. + * + * This is an alias for `Graphics.fillPath` and does the same thing. + * It was added to match the CanvasRenderingContext 2D API. + * + * @method Phaser.GameObjects.Graphics#fill + * @since 3.16.0 + * + * @return {this} This Game Object. + */ + fill: function () + { + this.commandBuffer.push( + Commands.FILL_PATH + ); + + return this; + }, + + /** + * Stroke the current path. + * + * @method Phaser.GameObjects.Graphics#strokePath + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + strokePath: function () + { + this.commandBuffer.push( + Commands.STROKE_PATH + ); + + return this; + }, + + /** + * Stroke the current path. + * + * This is an alias for `Graphics.strokePath` and does the same thing. + * It was added to match the CanvasRenderingContext 2D API. + * + * @method Phaser.GameObjects.Graphics#stroke + * @since 3.16.0 + * + * @return {this} This Game Object. + */ + stroke: function () + { + this.commandBuffer.push( + Commands.STROKE_PATH + ); + + return this; + }, + + /** + * Fill the given circle. + * + * @method Phaser.GameObjects.Graphics#fillCircleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to fill. + * + * @return {this} This Game Object. + */ + fillCircleShape: function (circle) + { + return this.fillCircle(circle.x, circle.y, circle.radius); + }, + + /** + * Stroke the given circle. + * + * @method Phaser.GameObjects.Graphics#strokeCircleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to stroke. + * + * @return {this} This Game Object. + */ + strokeCircleShape: function (circle) + { + return this.strokeCircle(circle.x, circle.y, circle.radius); + }, + + /** + * Fill a circle with the given position and radius. + * + * @method Phaser.GameObjects.Graphics#fillCircle + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} radius - The radius of the circle. + * + * @return {this} This Game Object. + */ + fillCircle: function (x, y, radius) + { + this.beginPath(); + this.arc(x, y, radius, 0, MATH_CONST.PI2); + this.fillPath(); + + return this; + }, + + /** + * Stroke a circle with the given position and radius. + * + * @method Phaser.GameObjects.Graphics#strokeCircle + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} radius - The radius of the circle. + * + * @return {this} This Game Object. + */ + strokeCircle: function (x, y, radius) + { + this.beginPath(); + this.arc(x, y, radius, 0, MATH_CONST.PI2); + this.strokePath(); + + return this; + }, + + /** + * Fill the given rectangle. + * + * @method Phaser.GameObjects.Graphics#fillRectShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to fill. + * + * @return {this} This Game Object. + */ + fillRectShape: function (rect) + { + return this.fillRect(rect.x, rect.y, rect.width, rect.height); + }, + + /** + * Stroke the given rectangle. + * + * @method Phaser.GameObjects.Graphics#strokeRectShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to stroke. + * + * @return {this} This Game Object. + */ + strokeRectShape: function (rect) + { + return this.strokeRect(rect.x, rect.y, rect.width, rect.height); + }, + + /** + * Fill a rectangle with the given position and size. + * + * @method Phaser.GameObjects.Graphics#fillRect + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * + * @return {this} This Game Object. + */ + fillRect: function (x, y, width, height) + { + this.commandBuffer.push( + Commands.FILL_RECT, + x, y, width, height + ); + + return this; + }, + + /** + * Stroke a rectangle with the given position and size. + * + * @method Phaser.GameObjects.Graphics#strokeRect + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * + * @return {this} This Game Object. + */ + strokeRect: function (x, y, width, height) + { + var lineWidthHalf = this._lineWidth / 2; + var minx = x - lineWidthHalf; + var maxx = x + lineWidthHalf; + + this.beginPath(); + this.moveTo(x, y); + this.lineTo(x, y + height); + this.strokePath(); + + this.beginPath(); + this.moveTo(x + width, y); + this.lineTo(x + width, y + height); + this.strokePath(); + + this.beginPath(); + this.moveTo(minx, y); + this.lineTo(maxx + width, y); + this.strokePath(); + + this.beginPath(); + this.moveTo(minx, y + height); + this.lineTo(maxx + width, y + height); + this.strokePath(); + + return this; + }, + + /** + * Fill a rounded rectangle with the given position, size and radius. + * + * @method Phaser.GameObjects.Graphics#fillRoundedRect + * @since 3.11.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. + * + * @return {this} This Game Object. + */ + fillRoundedRect: function (x, y, width, height, radius) + { + if (radius === undefined) { radius = 20; } + + var tl = radius; + var tr = radius; + var bl = radius; + var br = radius; + + if (typeof radius !== 'number') + { + tl = GetFastValue(radius, 'tl', 20); + tr = GetFastValue(radius, 'tr', 20); + bl = GetFastValue(radius, 'bl', 20); + br = GetFastValue(radius, 'br', 20); + } + + this.beginPath(); + this.moveTo(x + tl, y); + this.lineTo(x + width - tr, y); + this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); + this.lineTo(x + width, y + height - br); + this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); + this.lineTo(x + bl, y + height); + this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); + this.lineTo(x, y + tl); + this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); + this.fillPath(); + + return this; + }, + + /** + * Stroke a rounded rectangle with the given position, size and radius. + * + * @method Phaser.GameObjects.Graphics#strokeRoundedRect + * @since 3.11.0 + * + * @param {number} x - The x coordinate of the top-left of the rectangle. + * @param {number} y - The y coordinate of the top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * @param {(Phaser.Types.GameObjects.Graphics.RoundedRectRadius|number)} [radius=20] - The corner radius; It can also be an object to specify different radii for corners. + * + * @return {this} This Game Object. + */ + strokeRoundedRect: function (x, y, width, height, radius) + { + if (radius === undefined) { radius = 20; } + + var tl = radius; + var tr = radius; + var bl = radius; + var br = radius; + + if (typeof radius !== 'number') + { + tl = GetFastValue(radius, 'tl', 20); + tr = GetFastValue(radius, 'tr', 20); + bl = GetFastValue(radius, 'bl', 20); + br = GetFastValue(radius, 'br', 20); + } + + this.beginPath(); + this.moveTo(x + tl, y); + this.lineTo(x + width - tr, y); + this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); + this.lineTo(x + width, y + height - br); + this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); + this.lineTo(x + bl, y + height); + this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); + this.lineTo(x, y + tl); + this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); + this.strokePath(); + + return this; + }, + + /** + * Fill the given point. + * + * Draws a square at the given position, 1 pixel in size by default. + * + * @method Phaser.GameObjects.Graphics#fillPointShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|object)} point - The point to fill. + * @param {number} [size=1] - The size of the square to draw. + * + * @return {this} This Game Object. + */ + fillPointShape: function (point, size) + { + return this.fillPoint(point.x, point.y, size); + }, + + /** + * Fill a point at the given position. + * + * Draws a square at the given position, 1 pixel in size by default. + * + * @method Phaser.GameObjects.Graphics#fillPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the point. + * @param {number} y - The y coordinate of the point. + * @param {number} [size=1] - The size of the square to draw. + * + * @return {this} This Game Object. + */ + fillPoint: function (x, y, size) + { + if (!size || size < 1) + { + size = 1; + } + else + { + x -= (size / 2); + y -= (size / 2); + } + + this.commandBuffer.push( + Commands.FILL_RECT, + x, y, size, size + ); + + return this; + }, + + /** + * Fill the given triangle. + * + * @method Phaser.GameObjects.Graphics#fillTriangleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle to fill. + * + * @return {this} This Game Object. + */ + fillTriangleShape: function (triangle) + { + return this.fillTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3); + }, + + /** + * Stroke the given triangle. + * + * @method Phaser.GameObjects.Graphics#strokeTriangleShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle to stroke. + * + * @return {this} This Game Object. + */ + strokeTriangleShape: function (triangle) + { + return this.strokeTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3); + }, + + /** + * Fill a triangle with the given points. + * + * @method Phaser.GameObjects.Graphics#fillTriangle + * @since 3.0.0 + * + * @param {number} x0 - The x coordinate of the first point. + * @param {number} y0 - The y coordinate of the first point. + * @param {number} x1 - The x coordinate of the second point. + * @param {number} y1 - The y coordinate of the second point. + * @param {number} x2 - The x coordinate of the third point. + * @param {number} y2 - The y coordinate of the third point. + * + * @return {this} This Game Object. + */ + fillTriangle: function (x0, y0, x1, y1, x2, y2) + { + this.commandBuffer.push( + Commands.FILL_TRIANGLE, + x0, y0, x1, y1, x2, y2 + ); + + return this; + }, + + /** + * Stroke a triangle with the given points. + * + * @method Phaser.GameObjects.Graphics#strokeTriangle + * @since 3.0.0 + * + * @param {number} x0 - The x coordinate of the first point. + * @param {number} y0 - The y coordinate of the first point. + * @param {number} x1 - The x coordinate of the second point. + * @param {number} y1 - The y coordinate of the second point. + * @param {number} x2 - The x coordinate of the third point. + * @param {number} y2 - The y coordinate of the third point. + * + * @return {this} This Game Object. + */ + strokeTriangle: function (x0, y0, x1, y1, x2, y2) + { + this.commandBuffer.push( + Commands.STROKE_TRIANGLE, + x0, y0, x1, y1, x2, y2 + ); + + return this; + }, + + /** + * Draw the given line. + * + * @method Phaser.GameObjects.Graphics#strokeLineShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to stroke. + * + * @return {this} This Game Object. + */ + strokeLineShape: function (line) + { + return this.lineBetween(line.x1, line.y1, line.x2, line.y2); + }, + + /** + * Draw a line between the given points. + * + * @method Phaser.GameObjects.Graphics#lineBetween + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the start point of the line. + * @param {number} y1 - The y coordinate of the start point of the line. + * @param {number} x2 - The x coordinate of the end point of the line. + * @param {number} y2 - The y coordinate of the end point of the line. + * + * @return {this} This Game Object. + */ + lineBetween: function (x1, y1, x2, y2) + { + this.beginPath(); + this.moveTo(x1, y1); + this.lineTo(x2, y2); + this.strokePath(); + + return this; + }, + + /** + * Draw a line from the current drawing position to the given position. + * + * Moves the current drawing position to the given position. + * + * @method Phaser.GameObjects.Graphics#lineTo + * @since 3.0.0 + * + * @param {number} x - The x coordinate to draw the line to. + * @param {number} y - The y coordinate to draw the line to. + * + * @return {this} This Game Object. + */ + lineTo: function (x, y) + { + this.commandBuffer.push( + Commands.LINE_TO, + x, y + ); + + return this; + }, + + /** + * Move the current drawing position to the given position. + * + * @method Phaser.GameObjects.Graphics#moveTo + * @since 3.0.0 + * + * @param {number} x - The x coordinate to move to. + * @param {number} y - The y coordinate to move to. + * + * @return {this} This Game Object. + */ + moveTo: function (x, y) + { + this.commandBuffer.push( + Commands.MOVE_TO, + x, y + ); + + return this; + }, + + /** + * Stroke the shape represented by the given array of points. + * + * Pass `closeShape` to automatically close the shape by joining the last to the first point. + * + * Pass `closePath` to automatically close the path before it is stroked. + * + * @method Phaser.GameObjects.Graphics#strokePoints + * @since 3.0.0 + * + * @param {(array|Phaser.Geom.Point[])} points - The points to stroke. + * @param {boolean} [closeShape=false] - When `true`, the shape is closed by joining the last point to the first point. + * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. + * @param {integer} [endIndex] - The index of `points` to stop drawing at. Defaults to `points.length`. + * + * @return {this} This Game Object. + */ + strokePoints: function (points, closeShape, closePath, endIndex) + { + if (closeShape === undefined) { closeShape = false; } + if (closePath === undefined) { closePath = false; } + if (endIndex === undefined) { endIndex = points.length; } + + this.beginPath(); + + this.moveTo(points[0].x, points[0].y); + + for (var i = 1; i < endIndex; i++) + { + this.lineTo(points[i].x, points[i].y); + } + + if (closeShape) + { + this.lineTo(points[0].x, points[0].y); + } + + if (closePath) + { + this.closePath(); + } + + this.strokePath(); + + return this; + }, + + /** + * Fill the shape represented by the given array of points. + * + * Pass `closeShape` to automatically close the shape by joining the last to the first point. + * + * Pass `closePath` to automatically close the path before it is filled. + * + * @method Phaser.GameObjects.Graphics#fillPoints + * @since 3.0.0 + * + * @param {(array|Phaser.Geom.Point[])} points - The points to fill. + * @param {boolean} [closeShape=false] - When `true`, the shape is closed by joining the last point to the first point. + * @param {boolean} [closePath=false] - When `true`, the path is closed before being stroked. + * @param {integer} [endIndex] - The index of `points` to stop at. Defaults to `points.length`. + * + * @return {this} This Game Object. + */ + fillPoints: function (points, closeShape, closePath, endIndex) + { + if (closeShape === undefined) { closeShape = false; } + if (closePath === undefined) { closePath = false; } + if (endIndex === undefined) { endIndex = points.length; } + + this.beginPath(); + + this.moveTo(points[0].x, points[0].y); + + for (var i = 1; i < endIndex; i++) + { + this.lineTo(points[i].x, points[i].y); + } + + if (closeShape) + { + this.lineTo(points[0].x, points[0].y); + } + + if (closePath) + { + this.closePath(); + } + + this.fillPath(); + + return this; + }, + + /** + * Stroke the given ellipse. + * + * @method Phaser.GameObjects.Graphics#strokeEllipseShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to stroke. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {this} This Game Object. + */ + strokeEllipseShape: function (ellipse, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var points = ellipse.getPoints(smoothness); + + return this.strokePoints(points, true); + }, + + /** + * Stroke an ellipse with the given position and size. + * + * @method Phaser.GameObjects.Graphics#strokeEllipse + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the ellipse. + * @param {number} y - The y coordinate of the center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {this} This Game Object. + */ + strokeEllipse: function (x, y, width, height, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var ellipse = new Ellipse(x, y, width, height); + + var points = ellipse.getPoints(smoothness); + + return this.strokePoints(points, true); + }, + + /** + * Fill the given ellipse. + * + * @method Phaser.GameObjects.Graphics#fillEllipseShape + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The ellipse to fill. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {this} This Game Object. + */ + fillEllipseShape: function (ellipse, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var points = ellipse.getPoints(smoothness); + + return this.fillPoints(points, true); + }, + + /** + * Fill an ellipse with the given position and size. + * + * @method Phaser.GameObjects.Graphics#fillEllipse + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the ellipse. + * @param {number} y - The y coordinate of the center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * @param {integer} [smoothness=32] - The number of points to draw the ellipse with. + * + * @return {this} This Game Object. + */ + fillEllipse: function (x, y, width, height, smoothness) + { + if (smoothness === undefined) { smoothness = 32; } + + var ellipse = new Ellipse(x, y, width, height); + + var points = ellipse.getPoints(smoothness); + + return this.fillPoints(points, true); + }, + + /** + * Draw an arc. + * + * This method can be used to create circles, or parts of circles. + * + * Make sure you call `beginPath` before starting the arc unless you wish for the arc to automatically + * close when filled or stroked. + * + * Use the optional `overshoot` argument increase the number of iterations that take place when + * the arc is rendered in WebGL. This is useful if you're drawing an arc with an especially thick line, + * as it will allow the arc to fully join-up. Try small values at first, i.e. 0.01. + * + * Call {@link Phaser.GameObjects.Graphics#fillPath} or {@link Phaser.GameObjects.Graphics#strokePath} after calling + * this method to draw the arc. + * + * @method Phaser.GameObjects.Graphics#arc + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} radius - The radius of the circle. + * @param {number} startAngle - The starting angle, in radians. + * @param {number} endAngle - The ending angle, in radians. + * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. + * @param {number} [overshoot=0] - This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. + * + * @return {this} This Game Object. + */ + arc: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) + { + if (anticlockwise === undefined) { anticlockwise = false; } + if (overshoot === undefined) { overshoot = 0; } + + this.commandBuffer.push( + Commands.ARC, + x, y, radius, startAngle, endAngle, anticlockwise, overshoot + ); + + return this; + }, + + /** + * Creates a pie-chart slice shape centered at `x`, `y` with the given radius. + * You must define the start and end angle of the slice. + * + * Setting the `anticlockwise` argument to `true` creates a shape similar to Pacman. + * Setting it to `false` creates a shape like a slice of pie. + * + * This method will begin a new path and close the path at the end of it. + * To display the actual slice you need to call either `strokePath` or `fillPath` after it. + * + * @method Phaser.GameObjects.Graphics#slice + * @since 3.4.0 + * + * @param {number} x - The horizontal center of the slice. + * @param {number} y - The vertical center of the slice. + * @param {number} radius - The radius of the slice. + * @param {number} startAngle - The start angle of the slice, given in radians. + * @param {number} endAngle - The end angle of the slice, given in radians. + * @param {boolean} [anticlockwise=false] - Whether the drawing should be anticlockwise or clockwise. + * @param {number} [overshoot=0] - This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. + * + * @return {this} This Game Object. + */ + slice: function (x, y, radius, startAngle, endAngle, anticlockwise, overshoot) + { + if (anticlockwise === undefined) { anticlockwise = false; } + if (overshoot === undefined) { overshoot = 0; } + + this.commandBuffer.push(Commands.BEGIN_PATH); + + this.commandBuffer.push(Commands.MOVE_TO, x, y); + + this.commandBuffer.push(Commands.ARC, x, y, radius, startAngle, endAngle, anticlockwise, overshoot); + + this.commandBuffer.push(Commands.CLOSE_PATH); + + return this; + }, + + /** + * Saves the state of the Graphics by pushing the current state onto a stack. + * + * The most recently saved state can then be restored with {@link Phaser.GameObjects.Graphics#restore}. + * + * @method Phaser.GameObjects.Graphics#save + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + save: function () + { + this.commandBuffer.push( + Commands.SAVE + ); + + return this; + }, + + /** + * Restores the most recently saved state of the Graphics by popping from the state stack. + * + * Use {@link Phaser.GameObjects.Graphics#save} to save the current state, and call this afterwards to restore that state. + * + * If there is no saved state, this command does nothing. + * + * @method Phaser.GameObjects.Graphics#restore + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + restore: function () + { + this.commandBuffer.push( + Commands.RESTORE + ); + + return this; + }, + + /** + * Inserts a translation command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be translated + * by the given amount. + * + * This does not change the position of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * + * @method Phaser.GameObjects.Graphics#translateCanvas + * @since 3.0.0 + * + * @param {number} x - The horizontal translation to apply. + * @param {number} y - The vertical translation to apply. + * + * @return {this} This Game Object. + */ + translateCanvas: function (x, y) + { + this.commandBuffer.push( + Commands.TRANSLATE, + x, y + ); + + return this; + }, + + /** + * Inserts a scale command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be scaled + * by the given amount. + * + * This does not change the scale of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * + * @method Phaser.GameObjects.Graphics#scaleCanvas + * @since 3.0.0 + * + * @param {number} x - The horizontal scale to apply. + * @param {number} y - The vertical scale to apply. + * + * @return {this} This Game Object. + */ + scaleCanvas: function (x, y) + { + this.commandBuffer.push( + Commands.SCALE, + x, y + ); + + return this; + }, + + /** + * Inserts a rotation command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be rotated + * by the given amount. + * + * This does not change the rotation of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * + * @method Phaser.GameObjects.Graphics#rotateCanvas + * @since 3.0.0 + * + * @param {number} radians - The rotation angle, in radians. + * + * @return {this} This Game Object. + */ + rotateCanvas: function (radians) + { + this.commandBuffer.push( + Commands.ROTATE, + radians + ); + + return this; + }, + + /** + * Clear the command buffer and reset the fill style and line style to their defaults. + * + * @method Phaser.GameObjects.Graphics#clear + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + clear: function () + { + this.commandBuffer.length = 0; + + if (this.defaultFillColor > -1) + { + this.fillStyle(this.defaultFillColor, this.defaultFillAlpha); + } + + if (this.defaultStrokeColor > -1) + { + this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha); + } + + return this; + }, + + /** + * Generate a texture from this Graphics object. + * + * If `key` is a string it'll generate a new texture using it and add it into the + * Texture Manager (assuming no key conflict happens). + * + * If `key` is a Canvas it will draw the texture to that canvas context. Note that it will NOT + * automatically upload it to the GPU in WebGL mode. + * + * @method Phaser.GameObjects.Graphics#generateTexture + * @since 3.0.0 + * + * @param {(string|HTMLCanvasElement)} key - The key to store the texture with in the Texture Manager, or a Canvas to draw to. + * @param {integer} [width] - The width of the graphics to generate. + * @param {integer} [height] - The height of the graphics to generate. + * + * @return {this} This Game Object. + */ + generateTexture: function (key, width, height) + { + var sys = this.scene.sys; + var renderer = sys.game.renderer; + + if (width === undefined) { width = sys.scale.width; } + if (height === undefined) { height = sys.scale.height; } + + Graphics.TargetCamera.setScene(this.scene); + Graphics.TargetCamera.setViewport(0, 0, width, height); + Graphics.TargetCamera.scrollX = this.x; + Graphics.TargetCamera.scrollY = this.y; + + var texture; + var ctx; + + if (typeof key === 'string') + { + if (sys.textures.exists(key)) + { + // Key is a string, it DOES exist in the Texture Manager AND is a canvas, so draw to it + + texture = sys.textures.get(key); + + var src = texture.getSourceImage(); + + if (src instanceof HTMLCanvasElement) + { + ctx = src.getContext('2d'); + } + } + else + { + // Key is a string and doesn't exist in the Texture Manager, so generate and save it + + texture = sys.textures.createCanvas(key, width, height); + + ctx = texture.getSourceImage().getContext('2d'); + } + } + else if (key instanceof HTMLCanvasElement) + { + // Key is a Canvas, so draw to it + + ctx = key.getContext('2d'); + } + + if (ctx) + { + // var GraphicsCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) + this.renderCanvas(renderer, this, 0, Graphics.TargetCamera, null, ctx, false); + + if (texture) + { + texture.refresh(); + } + } + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Graphics#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + this.commandBuffer = []; + } + +}); + +/** + * A Camera used specifically by the Graphics system for rendering to textures. + * + * @name Phaser.GameObjects.Graphics.TargetCamera + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.1.0 + */ +Graphics.TargetCamera = new BaseCamera(); + +module.exports = Graphics; diff --git a/src/gameobjects/graphics/GraphicsCanvasRenderer.js b/src/gameobjects/graphics/GraphicsCanvasRenderer.js index fad524de4..f683cc941 100644 --- a/src/gameobjects/graphics/GraphicsCanvasRenderer.js +++ b/src/gameobjects/graphics/GraphicsCanvasRenderer.js @@ -1,244 +1,244 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Commands = require('./Commands'); -var SetTransform = require('../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Graphics#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Graphics} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - * @param {CanvasRenderingContext2D} [renderTargetCtx] - The target rendering context. - * @param {boolean} allowClip - If `true` then path operations will be used instead of fill operations. - */ -var GraphicsCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) -{ - var commandBuffer = src.commandBuffer; - var commandBufferLength = commandBuffer.length; - - var ctx = renderTargetCtx || renderer.currentContext; - - if (commandBufferLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - return; - } - - var lineAlpha = 1; - var fillAlpha = 1; - var lineColor = 0; - var fillColor = 0; - var lineWidth = 1; - var red = 0; - var green = 0; - var blue = 0; - - // Reset any currently active paths - ctx.beginPath(); - - for (var index = 0; index < commandBufferLength; ++index) - { - var commandID = commandBuffer[index]; - - switch (commandID) - { - case Commands.ARC: - ctx.arc( - commandBuffer[index + 1], - commandBuffer[index + 2], - commandBuffer[index + 3], - commandBuffer[index + 4], - commandBuffer[index + 5], - commandBuffer[index + 6] - ); - - // +7 because overshoot is the 7th value, not used in Canvas - index += 7; - break; - - case Commands.LINE_STYLE: - lineWidth = commandBuffer[index + 1]; - lineColor = commandBuffer[index + 2]; - lineAlpha = commandBuffer[index + 3]; - red = ((lineColor & 0xFF0000) >>> 16); - green = ((lineColor & 0xFF00) >>> 8); - blue = (lineColor & 0xFF); - ctx.strokeStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + lineAlpha + ')'; - ctx.lineWidth = lineWidth; - index += 3; - break; - - case Commands.FILL_STYLE: - fillColor = commandBuffer[index + 1]; - fillAlpha = commandBuffer[index + 2]; - red = ((fillColor & 0xFF0000) >>> 16); - green = ((fillColor & 0xFF00) >>> 8); - blue = (fillColor & 0xFF); - ctx.fillStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + fillAlpha + ')'; - index += 2; - break; - - case Commands.BEGIN_PATH: - ctx.beginPath(); - break; - - case Commands.CLOSE_PATH: - ctx.closePath(); - break; - - case Commands.FILL_PATH: - if (!allowClip) - { - ctx.fill(); - } - break; - - case Commands.STROKE_PATH: - if (!allowClip) - { - ctx.stroke(); - } - break; - - case Commands.FILL_RECT: - if (!allowClip) - { - ctx.fillRect( - commandBuffer[index + 1], - commandBuffer[index + 2], - commandBuffer[index + 3], - commandBuffer[index + 4] - ); - } - else - { - ctx.rect( - commandBuffer[index + 1], - commandBuffer[index + 2], - commandBuffer[index + 3], - commandBuffer[index + 4] - ); - } - index += 4; - break; - - case Commands.FILL_TRIANGLE: - ctx.beginPath(); - ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); - ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); - ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); - ctx.closePath(); - if (!allowClip) - { - ctx.fill(); - } - index += 6; - break; - - case Commands.STROKE_TRIANGLE: - ctx.beginPath(); - ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); - ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); - ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); - ctx.closePath(); - if (!allowClip) - { - ctx.stroke(); - } - index += 6; - break; - - case Commands.LINE_TO: - ctx.lineTo( - commandBuffer[index + 1], - commandBuffer[index + 2] - ); - index += 2; - break; - - case Commands.MOVE_TO: - ctx.moveTo( - commandBuffer[index + 1], - commandBuffer[index + 2] - ); - index += 2; - break; - - case Commands.LINE_FX_TO: - ctx.lineTo( - commandBuffer[index + 1], - commandBuffer[index + 2] - ); - index += 5; - break; - - case Commands.MOVE_FX_TO: - ctx.moveTo( - commandBuffer[index + 1], - commandBuffer[index + 2] - ); - index += 5; - break; - - case Commands.SAVE: - ctx.save(); - break; - - case Commands.RESTORE: - ctx.restore(); - break; - - case Commands.TRANSLATE: - ctx.translate( - commandBuffer[index + 1], - commandBuffer[index + 2] - ); - index += 2; - break; - - case Commands.SCALE: - ctx.scale( - commandBuffer[index + 1], - commandBuffer[index + 2] - ); - index += 2; - break; - - case Commands.ROTATE: - ctx.rotate( - commandBuffer[index + 1] - ); - index += 1; - break; - - case Commands.GRADIENT_FILL_STYLE: - index += 5; - break; - - case Commands.GRADIENT_LINE_STYLE: - index += 6; - break; - - case Commands.SET_TEXTURE: - index += 2; - break; - } - } - - // Restore the context saved in SetTransform - ctx.restore(); -}; - -module.exports = GraphicsCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Commands = require('./Commands'); +var SetTransform = require('../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Graphics#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Graphics} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + * @param {CanvasRenderingContext2D} [renderTargetCtx] - The target rendering context. + * @param {boolean} allowClip - If `true` then path operations will be used instead of fill operations. + */ +var GraphicsCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) +{ + var commandBuffer = src.commandBuffer; + var commandBufferLength = commandBuffer.length; + + var ctx = renderTargetCtx || renderer.currentContext; + + if (commandBufferLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + return; + } + + var lineAlpha = 1; + var fillAlpha = 1; + var lineColor = 0; + var fillColor = 0; + var lineWidth = 1; + var red = 0; + var green = 0; + var blue = 0; + + // Reset any currently active paths + ctx.beginPath(); + + for (var index = 0; index < commandBufferLength; ++index) + { + var commandID = commandBuffer[index]; + + switch (commandID) + { + case Commands.ARC: + ctx.arc( + commandBuffer[index + 1], + commandBuffer[index + 2], + commandBuffer[index + 3], + commandBuffer[index + 4], + commandBuffer[index + 5], + commandBuffer[index + 6] + ); + + // +7 because overshoot is the 7th value, not used in Canvas + index += 7; + break; + + case Commands.LINE_STYLE: + lineWidth = commandBuffer[index + 1]; + lineColor = commandBuffer[index + 2]; + lineAlpha = commandBuffer[index + 3]; + red = ((lineColor & 0xFF0000) >>> 16); + green = ((lineColor & 0xFF00) >>> 8); + blue = (lineColor & 0xFF); + ctx.strokeStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + lineAlpha + ')'; + ctx.lineWidth = lineWidth; + index += 3; + break; + + case Commands.FILL_STYLE: + fillColor = commandBuffer[index + 1]; + fillAlpha = commandBuffer[index + 2]; + red = ((fillColor & 0xFF0000) >>> 16); + green = ((fillColor & 0xFF00) >>> 8); + blue = (fillColor & 0xFF); + ctx.fillStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + fillAlpha + ')'; + index += 2; + break; + + case Commands.BEGIN_PATH: + ctx.beginPath(); + break; + + case Commands.CLOSE_PATH: + ctx.closePath(); + break; + + case Commands.FILL_PATH: + if (!allowClip) + { + ctx.fill(); + } + break; + + case Commands.STROKE_PATH: + if (!allowClip) + { + ctx.stroke(); + } + break; + + case Commands.FILL_RECT: + if (!allowClip) + { + ctx.fillRect( + commandBuffer[index + 1], + commandBuffer[index + 2], + commandBuffer[index + 3], + commandBuffer[index + 4] + ); + } + else + { + ctx.rect( + commandBuffer[index + 1], + commandBuffer[index + 2], + commandBuffer[index + 3], + commandBuffer[index + 4] + ); + } + index += 4; + break; + + case Commands.FILL_TRIANGLE: + ctx.beginPath(); + ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); + ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); + ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); + ctx.closePath(); + if (!allowClip) + { + ctx.fill(); + } + index += 6; + break; + + case Commands.STROKE_TRIANGLE: + ctx.beginPath(); + ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); + ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); + ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); + ctx.closePath(); + if (!allowClip) + { + ctx.stroke(); + } + index += 6; + break; + + case Commands.LINE_TO: + ctx.lineTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.MOVE_TO: + ctx.moveTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.LINE_FX_TO: + ctx.lineTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 5; + break; + + case Commands.MOVE_FX_TO: + ctx.moveTo( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 5; + break; + + case Commands.SAVE: + ctx.save(); + break; + + case Commands.RESTORE: + ctx.restore(); + break; + + case Commands.TRANSLATE: + ctx.translate( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.SCALE: + ctx.scale( + commandBuffer[index + 1], + commandBuffer[index + 2] + ); + index += 2; + break; + + case Commands.ROTATE: + ctx.rotate( + commandBuffer[index + 1] + ); + index += 1; + break; + + case Commands.GRADIENT_FILL_STYLE: + index += 5; + break; + + case Commands.GRADIENT_LINE_STYLE: + index += 6; + break; + + case Commands.SET_TEXTURE: + index += 2; + break; + } + } + + // Restore the context saved in SetTransform + ctx.restore(); +}; + +module.exports = GraphicsCanvasRenderer; diff --git a/src/gameobjects/graphics/GraphicsCreator.js b/src/gameobjects/graphics/GraphicsCreator.js index 0437ba08c..2744f6a5b 100644 --- a/src/gameobjects/graphics/GraphicsCreator.js +++ b/src/gameobjects/graphics/GraphicsCreator.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectCreator = require('../GameObjectCreator'); -var Graphics = require('./Graphics'); - -/** - * Creates a new Graphics Game Object and returns it. - * - * Note: This method will only be available if the Graphics Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#graphics - * @since 3.0.0 - * - * @param {object} 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.Graphics} The Game Object that was created. - */ -GameObjectCreator.register('graphics', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - var graphics = new Graphics(this.scene, config); - - if (config.add) - { - this.scene.sys.displayList.add(graphics); - } - - return graphics; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = require('../GameObjectCreator'); +var Graphics = require('./Graphics'); + +/** + * Creates a new Graphics Game Object and returns it. + * + * Note: This method will only be available if the Graphics Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#graphics + * @since 3.0.0 + * + * @param {object} 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.Graphics} The Game Object that was created. + */ +GameObjectCreator.register('graphics', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + var graphics = new Graphics(this.scene, config); + + if (config.add) + { + this.scene.sys.displayList.add(graphics); + } + + return graphics; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/graphics/GraphicsFactory.js b/src/gameobjects/graphics/GraphicsFactory.js index ad19b5fbb..abe9b016f 100644 --- a/src/gameobjects/graphics/GraphicsFactory.js +++ b/src/gameobjects/graphics/GraphicsFactory.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Graphics = require('./Graphics'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Graphics Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Graphics Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#graphics - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Graphics.Options} [config] - The Graphics configuration. - * - * @return {Phaser.GameObjects.Graphics} The Game Object that was created. - */ -GameObjectFactory.register('graphics', function (config) -{ - return this.displayList.add(new Graphics(this.scene, config)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Graphics = require('./Graphics'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Graphics Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Graphics Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#graphics + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Graphics.Options} [config] - The Graphics configuration. + * + * @return {Phaser.GameObjects.Graphics} The Game Object that was created. + */ +GameObjectFactory.register('graphics', function (config) +{ + return this.displayList.add(new Graphics(this.scene, config)); +}); + +// 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 diff --git a/src/gameobjects/graphics/GraphicsRender.js b/src/gameobjects/graphics/GraphicsRender.js index 08e845a4c..4a4bccad0 100644 --- a/src/gameobjects/graphics/GraphicsRender.js +++ b/src/gameobjects/graphics/GraphicsRender.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./GraphicsWebGLRenderer'); - - // Needed for Graphics.generateTexture - renderCanvas = require('./GraphicsCanvasRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./GraphicsCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./GraphicsWebGLRenderer'); + + // Needed for Graphics.generateTexture + renderCanvas = require('./GraphicsCanvasRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./GraphicsCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/graphics/GraphicsWebGLRenderer.js b/src/gameobjects/graphics/GraphicsWebGLRenderer.js index b0e8217a8..b478fda81 100644 --- a/src/gameobjects/graphics/GraphicsWebGLRenderer.js +++ b/src/gameobjects/graphics/GraphicsWebGLRenderer.js @@ -1,359 +1,359 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Commands = require('./Commands'); -var Utils = require('../../renderer/webgl/Utils'); - -// TODO: Remove the use of this -var Point = function (x, y, width) -{ - this.x = x; - this.y = y; - this.width = width; -}; - -// TODO: Remove the use of this -var Path = function (x, y, width) -{ - this.points = []; - this.pointsLength = 1; - this.points[0] = new Point(x, y, width); -}; - -var matrixStack = []; - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Graphics#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Graphics} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var GraphicsWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - if (src.commandBuffer.length === 0) - { - return; - } - - var pipeline = this.pipeline; - - renderer.setPipeline(pipeline, src); - - var camMatrix = src._tempMatrix1; - var graphicsMatrix = src._tempMatrix2; - var currentMatrix = src._tempMatrix3; - - currentMatrix.loadIdentity(); - - graphicsMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - graphicsMatrix.e = src.x; - graphicsMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(graphicsMatrix); - } - else - { - graphicsMatrix.e -= camera.scrollX * src.scrollFactorX; - graphicsMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(graphicsMatrix); - } - - var commands = src.commandBuffer; - var alpha = camera.alpha * src.alpha; - - var lineWidth = 1; - var fillTint = pipeline.fillTint; - var strokeTint = pipeline.strokeTint; - - var tx = 0; - var ty = 0; - var ta = 0; - var iterStep = 0.01; - var PI2 = Math.PI * 2; - - var cmd; - - var path = []; - var pathIndex = 0; - var pathOpen = false; - var lastPath = null; - - var getTint = Utils.getTintAppendFloatAlphaAndSwap; - - var currentTexture = renderer.blankTexture.glTexture; - - for (var cmdIndex = 0; cmdIndex < commands.length; cmdIndex++) - { - cmd = commands[cmdIndex]; - - switch (cmd) - { - case Commands.BEGIN_PATH: - - path.length = 0; - lastPath = null; - pathOpen = true; - break; - - case Commands.CLOSE_PATH: - - pathOpen = false; - - if (lastPath && lastPath.points.length) - { - lastPath.points.push(lastPath.points[0]); - } - break; - - case Commands.FILL_PATH: - for (pathIndex = 0; pathIndex < path.length; pathIndex++) - { - pipeline.setTexture2D(currentTexture); - - pipeline.batchFillPath( - path[pathIndex].points, - currentMatrix, - camMatrix - ); - } - break; - - case Commands.STROKE_PATH: - for (pathIndex = 0; pathIndex < path.length; pathIndex++) - { - pipeline.setTexture2D(currentTexture); - - pipeline.batchStrokePath( - path[pathIndex].points, - lineWidth, - pathOpen, - currentMatrix, - camMatrix - ); - } - break; - - case Commands.LINE_STYLE: - lineWidth = commands[++cmdIndex]; - var strokeColor = commands[++cmdIndex]; - var strokeAlpha = commands[++cmdIndex] * alpha; - var strokeTintColor = getTint(strokeColor, strokeAlpha); - strokeTint.TL = strokeTintColor; - strokeTint.TR = strokeTintColor; - strokeTint.BL = strokeTintColor; - strokeTint.BR = strokeTintColor; - break; - - case Commands.FILL_STYLE: - var fillColor = commands[++cmdIndex]; - var fillAlpha = commands[++cmdIndex] * alpha; - var fillTintColor = getTint(fillColor, fillAlpha); - fillTint.TL = fillTintColor; - fillTint.TR = fillTintColor; - fillTint.BL = fillTintColor; - fillTint.BR = fillTintColor; - break; - - case Commands.GRADIENT_FILL_STYLE: - var gradientFillAlpha = commands[++cmdIndex] * alpha; - fillTint.TL = getTint(commands[++cmdIndex], gradientFillAlpha); - fillTint.TR = getTint(commands[++cmdIndex], gradientFillAlpha); - fillTint.BL = getTint(commands[++cmdIndex], gradientFillAlpha); - fillTint.BR = getTint(commands[++cmdIndex], gradientFillAlpha); - break; - - case Commands.GRADIENT_LINE_STYLE: - lineWidth = commands[++cmdIndex]; - var gradientLineAlpha = commands[++cmdIndex] * alpha; - strokeTint.TL = getTint(commands[++cmdIndex], gradientLineAlpha); - strokeTint.TR = getTint(commands[++cmdIndex], gradientLineAlpha); - strokeTint.BL = getTint(commands[++cmdIndex], gradientLineAlpha); - strokeTint.BR = getTint(commands[++cmdIndex], gradientLineAlpha); - break; - - case Commands.ARC: - var iteration = 0; - var x = commands[++cmdIndex]; - var y = commands[++cmdIndex]; - var radius = commands[++cmdIndex]; - var startAngle = commands[++cmdIndex]; - var endAngle = commands[++cmdIndex]; - var anticlockwise = commands[++cmdIndex]; - var overshoot = commands[++cmdIndex]; - - endAngle -= startAngle; - - if (anticlockwise) - { - if (endAngle < -PI2) - { - endAngle = -PI2; - } - else if (endAngle > 0) - { - endAngle = -PI2 + endAngle % PI2; - } - } - else if (endAngle > PI2) - { - endAngle = PI2; - } - else if (endAngle < 0) - { - endAngle = PI2 + endAngle % PI2; - } - - if (lastPath === null) - { - lastPath = new Path(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius, lineWidth); - path.push(lastPath); - iteration += iterStep; - } - - while (iteration < 1 + overshoot) - { - ta = endAngle * iteration + startAngle; - tx = x + Math.cos(ta) * radius; - ty = y + Math.sin(ta) * radius; - - lastPath.points.push(new Point(tx, ty, lineWidth)); - - iteration += iterStep; - } - - ta = endAngle + startAngle; - tx = x + Math.cos(ta) * radius; - ty = y + Math.sin(ta) * radius; - - lastPath.points.push(new Point(tx, ty, lineWidth)); - - break; - - case Commands.FILL_RECT: - pipeline.setTexture2D(currentTexture); - pipeline.batchFillRect( - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - currentMatrix, - camMatrix - ); - break; - - case Commands.FILL_TRIANGLE: - pipeline.setTexture2D(currentTexture); - pipeline.batchFillTriangle( - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - currentMatrix, - camMatrix - ); - break; - - case Commands.STROKE_TRIANGLE: - pipeline.setTexture2D(currentTexture); - pipeline.batchStrokeTriangle( - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - commands[++cmdIndex], - lineWidth, - currentMatrix, - camMatrix - ); - break; - - case Commands.LINE_TO: - if (lastPath !== null) - { - lastPath.points.push(new Point(commands[++cmdIndex], commands[++cmdIndex], lineWidth)); - } - else - { - lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); - path.push(lastPath); - } - break; - - case Commands.MOVE_TO: - lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); - path.push(lastPath); - break; - - case Commands.SAVE: - matrixStack.push(currentMatrix.copyToArray()); - break; - - case Commands.RESTORE: - currentMatrix.copyFromArray(matrixStack.pop()); - break; - - case Commands.TRANSLATE: - x = commands[++cmdIndex]; - y = commands[++cmdIndex]; - currentMatrix.translate(x, y); - break; - - case Commands.SCALE: - x = commands[++cmdIndex]; - y = commands[++cmdIndex]; - currentMatrix.scale(x, y); - break; - - case Commands.ROTATE: - currentMatrix.rotate(commands[++cmdIndex]); - break; - - case Commands.SET_TEXTURE: - var frame = commands[++cmdIndex]; - var mode = commands[++cmdIndex]; - - pipeline.currentFrame = frame; - pipeline.setTexture2D(frame.glTexture, 0); - pipeline.tintEffect = mode; - - currentTexture = frame.glTexture; - - break; - - case Commands.CLEAR_TEXTURE: - pipeline.currentFrame = renderer.blankTexture; - pipeline.tintEffect = 2; - currentTexture = renderer.blankTexture.glTexture; - break; - } - } -}; - -module.exports = GraphicsWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Commands = require('./Commands'); +var Utils = require('../../renderer/webgl/Utils'); + +// TODO: Remove the use of this +var Point = function (x, y, width) +{ + this.x = x; + this.y = y; + this.width = width; +}; + +// TODO: Remove the use of this +var Path = function (x, y, width) +{ + this.points = []; + this.pointsLength = 1; + this.points[0] = new Point(x, y, width); +}; + +var matrixStack = []; + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Graphics#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Graphics} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var GraphicsWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (src.commandBuffer.length === 0) + { + return; + } + + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = src._tempMatrix1; + var graphicsMatrix = src._tempMatrix2; + var currentMatrix = src._tempMatrix3; + + currentMatrix.loadIdentity(); + + graphicsMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + graphicsMatrix.e = src.x; + graphicsMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(graphicsMatrix); + } + else + { + graphicsMatrix.e -= camera.scrollX * src.scrollFactorX; + graphicsMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(graphicsMatrix); + } + + var commands = src.commandBuffer; + var alpha = camera.alpha * src.alpha; + + var lineWidth = 1; + var fillTint = pipeline.fillTint; + var strokeTint = pipeline.strokeTint; + + var tx = 0; + var ty = 0; + var ta = 0; + var iterStep = 0.01; + var PI2 = Math.PI * 2; + + var cmd; + + var path = []; + var pathIndex = 0; + var pathOpen = false; + var lastPath = null; + + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + + var currentTexture = renderer.blankTexture.glTexture; + + for (var cmdIndex = 0; cmdIndex < commands.length; cmdIndex++) + { + cmd = commands[cmdIndex]; + + switch (cmd) + { + case Commands.BEGIN_PATH: + + path.length = 0; + lastPath = null; + pathOpen = true; + break; + + case Commands.CLOSE_PATH: + + pathOpen = false; + + if (lastPath && lastPath.points.length) + { + lastPath.points.push(lastPath.points[0]); + } + break; + + case Commands.FILL_PATH: + for (pathIndex = 0; pathIndex < path.length; pathIndex++) + { + pipeline.setTexture2D(currentTexture); + + pipeline.batchFillPath( + path[pathIndex].points, + currentMatrix, + camMatrix + ); + } + break; + + case Commands.STROKE_PATH: + for (pathIndex = 0; pathIndex < path.length; pathIndex++) + { + pipeline.setTexture2D(currentTexture); + + pipeline.batchStrokePath( + path[pathIndex].points, + lineWidth, + pathOpen, + currentMatrix, + camMatrix + ); + } + break; + + case Commands.LINE_STYLE: + lineWidth = commands[++cmdIndex]; + var strokeColor = commands[++cmdIndex]; + var strokeAlpha = commands[++cmdIndex] * alpha; + var strokeTintColor = getTint(strokeColor, strokeAlpha); + strokeTint.TL = strokeTintColor; + strokeTint.TR = strokeTintColor; + strokeTint.BL = strokeTintColor; + strokeTint.BR = strokeTintColor; + break; + + case Commands.FILL_STYLE: + var fillColor = commands[++cmdIndex]; + var fillAlpha = commands[++cmdIndex] * alpha; + var fillTintColor = getTint(fillColor, fillAlpha); + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + break; + + case Commands.GRADIENT_FILL_STYLE: + var gradientFillAlpha = commands[++cmdIndex] * alpha; + fillTint.TL = getTint(commands[++cmdIndex], gradientFillAlpha); + fillTint.TR = getTint(commands[++cmdIndex], gradientFillAlpha); + fillTint.BL = getTint(commands[++cmdIndex], gradientFillAlpha); + fillTint.BR = getTint(commands[++cmdIndex], gradientFillAlpha); + break; + + case Commands.GRADIENT_LINE_STYLE: + lineWidth = commands[++cmdIndex]; + var gradientLineAlpha = commands[++cmdIndex] * alpha; + strokeTint.TL = getTint(commands[++cmdIndex], gradientLineAlpha); + strokeTint.TR = getTint(commands[++cmdIndex], gradientLineAlpha); + strokeTint.BL = getTint(commands[++cmdIndex], gradientLineAlpha); + strokeTint.BR = getTint(commands[++cmdIndex], gradientLineAlpha); + break; + + case Commands.ARC: + var iteration = 0; + var x = commands[++cmdIndex]; + var y = commands[++cmdIndex]; + var radius = commands[++cmdIndex]; + var startAngle = commands[++cmdIndex]; + var endAngle = commands[++cmdIndex]; + var anticlockwise = commands[++cmdIndex]; + var overshoot = commands[++cmdIndex]; + + endAngle -= startAngle; + + if (anticlockwise) + { + if (endAngle < -PI2) + { + endAngle = -PI2; + } + else if (endAngle > 0) + { + endAngle = -PI2 + endAngle % PI2; + } + } + else if (endAngle > PI2) + { + endAngle = PI2; + } + else if (endAngle < 0) + { + endAngle = PI2 + endAngle % PI2; + } + + if (lastPath === null) + { + lastPath = new Path(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius, lineWidth); + path.push(lastPath); + iteration += iterStep; + } + + while (iteration < 1 + overshoot) + { + ta = endAngle * iteration + startAngle; + tx = x + Math.cos(ta) * radius; + ty = y + Math.sin(ta) * radius; + + lastPath.points.push(new Point(tx, ty, lineWidth)); + + iteration += iterStep; + } + + ta = endAngle + startAngle; + tx = x + Math.cos(ta) * radius; + ty = y + Math.sin(ta) * radius; + + lastPath.points.push(new Point(tx, ty, lineWidth)); + + break; + + case Commands.FILL_RECT: + pipeline.setTexture2D(currentTexture); + pipeline.batchFillRect( + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + currentMatrix, + camMatrix + ); + break; + + case Commands.FILL_TRIANGLE: + pipeline.setTexture2D(currentTexture); + pipeline.batchFillTriangle( + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + currentMatrix, + camMatrix + ); + break; + + case Commands.STROKE_TRIANGLE: + pipeline.setTexture2D(currentTexture); + pipeline.batchStrokeTriangle( + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + commands[++cmdIndex], + lineWidth, + currentMatrix, + camMatrix + ); + break; + + case Commands.LINE_TO: + if (lastPath !== null) + { + lastPath.points.push(new Point(commands[++cmdIndex], commands[++cmdIndex], lineWidth)); + } + else + { + lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); + path.push(lastPath); + } + break; + + case Commands.MOVE_TO: + lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); + path.push(lastPath); + break; + + case Commands.SAVE: + matrixStack.push(currentMatrix.copyToArray()); + break; + + case Commands.RESTORE: + currentMatrix.copyFromArray(matrixStack.pop()); + break; + + case Commands.TRANSLATE: + x = commands[++cmdIndex]; + y = commands[++cmdIndex]; + currentMatrix.translate(x, y); + break; + + case Commands.SCALE: + x = commands[++cmdIndex]; + y = commands[++cmdIndex]; + currentMatrix.scale(x, y); + break; + + case Commands.ROTATE: + currentMatrix.rotate(commands[++cmdIndex]); + break; + + case Commands.SET_TEXTURE: + var frame = commands[++cmdIndex]; + var mode = commands[++cmdIndex]; + + pipeline.currentFrame = frame; + pipeline.setTexture2D(frame.glTexture, 0); + pipeline.tintEffect = mode; + + currentTexture = frame.glTexture; + + break; + + case Commands.CLEAR_TEXTURE: + pipeline.currentFrame = renderer.blankTexture; + pipeline.tintEffect = 2; + currentTexture = renderer.blankTexture.glTexture; + break; + } + } +}; + +module.exports = GraphicsWebGLRenderer; diff --git a/src/gameobjects/graphics/typedefs/index.js b/src/gameobjects/graphics/typedefs/index.js index 618f783bb..e1142871c 100644 --- a/src/gameobjects/graphics/typedefs/index.js +++ b/src/gameobjects/graphics/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.Graphics - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.Graphics + */ diff --git a/src/gameobjects/group/Group.js b/src/gameobjects/group/Group.js index 07e520c46..11fd57266 100644 --- a/src/gameobjects/group/Group.js +++ b/src/gameobjects/group/Group.js @@ -1,1632 +1,1632 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Actions = require('../../actions/'); -var Class = require('../../utils/Class'); -var Events = require('../events'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetValue = require('../../utils/object/GetValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var Range = require('../../utils/array/Range'); -var Set = require('../../structs/Set'); -var Sprite = require('../sprite/Sprite'); - -/** - * @classdesc - * A Group is a way for you to create, manipulate, or recycle similar Game Objects. - * - * Group membership is non-exclusive. A Game Object can belong to several groups, one group, or none. - * - * Groups themselves aren't displayable, and can't be positioned, rotated, scaled, or hidden. - * - * @class Group - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * @param {Phaser.Scene} scene - The scene this group belongs to. - * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. - * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. If `key` is set, Phaser.GameObjects.Group#createMultiple is also called with these settings. - * - * @see Phaser.Physics.Arcade.Group - * @see Phaser.Physics.Arcade.StaticGroup - */ -var Group = new Class({ - - initialize: - - function Group (scene, children, config) - { - // 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 - - if (config) - { - // config has been set, are the children an array? - - if (children && !Array.isArray(children)) - { - children = [ children ]; - } - } - else if (Array.isArray(children)) - { - // No config, so let's check the children argument - - if (IsPlainObject(children[0])) - { - // It's an array of plain config objects - config = children; - children = null; - } - } - else if (IsPlainObject(children)) - { - // Children isn't an array. Is it a config object though? - config = children; - children = null; - } - - /** - * This scene this group belongs to. - * - * @name Phaser.GameObjects.Group#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * Members of this group. - * - * @name Phaser.GameObjects.Group#children - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.children = new Set(children); - - /** - * A flag identifying this object as a group. - * - * @name Phaser.GameObjects.Group#isParent - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.isParent = true; - - /** - * A textual representation of this Game Object. - * Used internally by Phaser but is available for your own custom classes to populate. - * - * @name Phaser.GameObjects.Group#type - * @type {string} - * @default 'Group' - * @since 3.21.0 - */ - this.type = 'Group'; - - /** - * The class to create new group members from. - * - * @name Phaser.GameObjects.Group#classType - * @type {Function} - * @since 3.0.0 - * @default Phaser.GameObjects.Sprite - */ - this.classType = GetFastValue(config, 'classType', Sprite); - - /** - * The name of this group. - * Empty by default and never populated by Phaser, this is left for developers to use. - * - * @name Phaser.GameObjects.Group#name - * @type {string} - * @default '' - * @since 3.18.0 - */ - this.name = GetFastValue(config, 'name', ''); - - /** - * Whether this group runs its {@link Phaser.GameObjects.Group#preUpdate} method - * (which may update any members). - * - * @name Phaser.GameObjects.Group#active - * @type {boolean} - * @since 3.0.0 - */ - this.active = GetFastValue(config, 'active', true); - - /** - * The maximum size of this group, if used as a pool. -1 is no limit. - * - * @name Phaser.GameObjects.Group#maxSize - * @type {integer} - * @since 3.0.0 - * @default -1 - */ - this.maxSize = GetFastValue(config, 'maxSize', -1); - - /** - * A default texture key to use when creating new group members. - * - * This is used in {@link Phaser.GameObjects.Group#create} - * but not in {@link Phaser.GameObjects.Group#createMultiple}. - * - * @name Phaser.GameObjects.Group#defaultKey - * @type {string} - * @since 3.0.0 - */ - this.defaultKey = GetFastValue(config, 'defaultKey', null); - - /** - * A default texture frame to use when creating new group members. - * - * @name Phaser.GameObjects.Group#defaultFrame - * @type {(string|integer)} - * @since 3.0.0 - */ - this.defaultFrame = GetFastValue(config, 'defaultFrame', null); - - /** - * Whether to call the update method of any members. - * - * @name Phaser.GameObjects.Group#runChildUpdate - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.GameObjects.Group#preUpdate - */ - this.runChildUpdate = GetFastValue(config, 'runChildUpdate', false); - - /** - * A function to be called when adding or creating group members. - * - * @name Phaser.GameObjects.Group#createCallback - * @type {?Phaser.Types.GameObjects.Group.GroupCallback} - * @since 3.0.0 - */ - this.createCallback = GetFastValue(config, 'createCallback', null); - - /** - * A function to be called when removing group members. - * - * @name Phaser.GameObjects.Group#removeCallback - * @type {?Phaser.Types.GameObjects.Group.GroupCallback} - * @since 3.0.0 - */ - this.removeCallback = GetFastValue(config, 'removeCallback', null); - - /** - * A function to be called when creating several group members at once. - * - * @name Phaser.GameObjects.Group#createMultipleCallback - * @type {?Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback} - * @since 3.0.0 - */ - this.createMultipleCallback = GetFastValue(config, 'createMultipleCallback', null); - - /** - * A function to be called when adding or creating group members. - * For internal use only by a Group, or any class that extends it. - * - * @name Phaser.GameObjects.Group#internalCreateCallback - * @type {?Phaser.Types.GameObjects.Group.GroupCallback} - * @private - * @since 3.22.0 - */ - this.internalCreateCallback = GetFastValue(config, 'internalCreateCallback', null); - - /** - * A function to be called when removing group members. - * For internal use only by a Group, or any class that extends it. - * - * @name Phaser.GameObjects.Group#internalRemoveCallback - * @type {?Phaser.Types.GameObjects.Group.GroupCallback} - * @private - * @since 3.22.0 - */ - this.internalRemoveCallback = GetFastValue(config, 'internalRemoveCallback', null); - - if (config) - { - this.createMultiple(config); - } - }, - - /** - * Creates a new Game Object and adds it to this group, unless the group {@link Phaser.GameObjects.Group#isFull is full}. - * - * Calls {@link Phaser.GameObjects.Group#createCallback}. - * - * @method Phaser.GameObjects.Group#create - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal position of the new Game Object in the world. - * @param {number} [y=0] - The vertical position of the new Game Object in the world. - * @param {string} [key=defaultKey] - The texture key of the new Game Object. - * @param {(string|integer)} [frame=defaultFrame] - The texture frame of the new Game Object. - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of the new Game Object. - * @param {boolean} [active=true] - The {@link Phaser.GameObjects.GameObject#active} state of the new Game Object. - * - * @return {any} The new Game Object (usually a Sprite, etc.). - */ - create: function (x, y, key, frame, visible, active) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (key === undefined) { key = this.defaultKey; } - if (frame === undefined) { frame = this.defaultFrame; } - if (visible === undefined) { visible = true; } - if (active === undefined) { active = true; } - - // Pool? - if (this.isFull()) - { - return null; - } - - var child = new this.classType(this.scene, x, y, key, frame); - - this.scene.sys.displayList.add(child); - - if (child.preUpdate) - { - this.scene.sys.updateList.add(child); - } - - child.visible = visible; - child.setActive(active); - - this.add(child); - - return child; - }, - - /** - * Creates several Game Objects and adds them to this group. - * - * If the group becomes {@link Phaser.GameObjects.Group#isFull}, no further Game Objects are created. - * - * Calls {@link Phaser.GameObjects.Group#createMultipleCallback} and {@link Phaser.GameObjects.Group#createCallback}. - * - * @method Phaser.GameObjects.Group#createMultiple - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Group.GroupCreateConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig[]} config - Creation settings. This can be a single configuration object or an array of such objects, which will be applied in turn. - * - * @return {any[]} The newly created Game Objects. - */ - createMultiple: function (config) - { - if (this.isFull()) - { - return []; - } - - if (!Array.isArray(config)) - { - config = [ config ]; - } - - var output = []; - - if (config[0].key) - { - for (var i = 0; i < config.length; i++) - { - var entries = this.createFromConfig(config[i]); - - output = output.concat(entries); - } - } - - return output; - }, - - /** - * A helper for {@link Phaser.GameObjects.Group#createMultiple}. - * - * @method Phaser.GameObjects.Group#createFromConfig - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Group.GroupCreateConfig} options - Creation settings. - * - * @return {any[]} The newly created Game Objects. - */ - createFromConfig: function (options) - { - if (this.isFull()) - { - return []; - } - - this.classType = GetFastValue(options, 'classType', this.classType); - - var key = GetFastValue(options, 'key', undefined); - var frame = GetFastValue(options, 'frame', null); - var visible = GetFastValue(options, 'visible', true); - var active = GetFastValue(options, 'active', true); - - var entries = []; - - // Can't do anything without at least a key - if (key === undefined) - { - return entries; - } - else - { - if (!Array.isArray(key)) - { - key = [ key ]; - } - - if (!Array.isArray(frame)) - { - frame = [ frame ]; - } - } - - // Build an array of key frame pairs to loop through - - var repeat = GetFastValue(options, 'repeat', 0); - var randomKey = GetFastValue(options, 'randomKey', false); - var randomFrame = GetFastValue(options, 'randomFrame', false); - var yoyo = GetFastValue(options, 'yoyo', false); - var quantity = GetFastValue(options, 'quantity', false); - var frameQuantity = GetFastValue(options, 'frameQuantity', 1); - var max = GetFastValue(options, 'max', 0); - - // If a quantity value is set we use that to override the frameQuantity - - var range = Range(key, frame, { - max: max, - qty: (quantity) ? quantity : frameQuantity, - random: randomKey, - randomB: randomFrame, - repeat: repeat, - yoyo: yoyo - }); - - if (options.createCallback) - { - this.createCallback = options.createCallback; - } - - if (options.removeCallback) - { - this.removeCallback = options.removeCallback; - } - - for (var c = 0; c < range.length; c++) - { - var created = this.create(0, 0, range[c].a, range[c].b, visible, active); - - if (!created) - { - break; - } - - entries.push(created); - } - - // Post-creation options (applied only to those items created in this call): - - var x = GetValue(options, 'setXY.x', 0); - var y = GetValue(options, 'setXY.y', 0); - var stepX = GetValue(options, 'setXY.stepX', 0); - var stepY = GetValue(options, 'setXY.stepY', 0); - - Actions.SetXY(entries, x, y, stepX, stepY); - - var rotation = GetValue(options, 'setRotation.value', 0); - var stepRotation = GetValue(options, 'setRotation.step', 0); - - Actions.SetRotation(entries, rotation, stepRotation); - - var scaleX = GetValue(options, 'setScale.x', 1); - var scaleY = GetValue(options, 'setScale.y', scaleX); - var stepScaleX = GetValue(options, 'setScale.stepX', 0); - var stepScaleY = GetValue(options, 'setScale.stepY', 0); - - Actions.SetScale(entries, scaleX, scaleY, stepScaleX, stepScaleY); - - var alpha = GetValue(options, 'setAlpha.value', 1); - var stepAlpha = GetValue(options, 'setAlpha.step', 0); - - Actions.SetAlpha(entries, alpha, stepAlpha); - - var depth = GetValue(options, 'setDepth.value', 0); - var stepDepth = GetValue(options, 'setDepth.step', 0); - - Actions.SetDepth(entries, depth, stepDepth); - - var scrollFactorX = GetValue(options, 'setScrollFactor.x', 1); - var scrollFactorY = GetValue(options, 'setScrollFactor.y', scrollFactorX); - var stepScrollFactorX = GetValue(options, 'setScrollFactor.stepX', 0); - var stepScrollFactorY = GetValue(options, 'setScrollFactor.stepY', 0); - - Actions.SetScrollFactor(entries, scrollFactorX, scrollFactorY, stepScrollFactorX, stepScrollFactorY); - - var hitArea = GetFastValue(options, 'hitArea', null); - var hitAreaCallback = GetFastValue(options, 'hitAreaCallback', null); - - if (hitArea) - { - Actions.SetHitArea(entries, hitArea, hitAreaCallback); - } - - var grid = GetFastValue(options, 'gridAlign', false); - - if (grid) - { - Actions.GridAlign(entries, grid); - } - - if (this.createMultipleCallback) - { - this.createMultipleCallback.call(this, entries); - } - - return entries; - }, - - /** - * Updates any group members, if {@link Phaser.GameObjects.Group#runChildUpdate} is enabled. - * - * @method Phaser.GameObjects.Group#preUpdate - * @since 3.0.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - if (!this.runChildUpdate || this.children.size === 0) - { - return; - } - - // Because a Group child may mess with the length of the Group during its update - var temp = this.children.entries.slice(); - - for (var i = 0; i < temp.length; i++) - { - var item = temp[i]; - - if (item.active) - { - item.update(time, delta); - } - } - }, - - /** - * Adds a Game Object to this group. - * - * Calls {@link Phaser.GameObjects.Group#createCallback}. - * - * @method Phaser.GameObjects.Group#add - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. - * @param {boolean} [addToScene=false] - Also add the Game Object to the scene. - * - * @return {this} This Group object. - */ - add: function (child, addToScene) - { - if (addToScene === undefined) { addToScene = false; } - - if (this.isFull()) - { - return this; - } - - this.children.set(child); - - if (this.internalCreateCallback) - { - this.internalCreateCallback.call(this, child); - } - - if (this.createCallback) - { - this.createCallback.call(this, child); - } - - if (addToScene) - { - this.scene.sys.displayList.add(child); - - if (child.preUpdate) - { - this.scene.sys.updateList.add(child); - } - } - - child.on(Events.DESTROY, this.remove, this); - - return this; - }, - - /** - * Adds several Game Objects to this group. - * - * Calls {@link Phaser.GameObjects.Group#createCallback}. - * - * @method Phaser.GameObjects.Group#addMultiple - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject[]} children - The Game Objects to add. - * @param {boolean} [addToScene=false] - Also add the Game Objects to the scene. - * - * @return {this} This group. - */ - addMultiple: function (children, addToScene) - { - if (addToScene === undefined) { addToScene = false; } - - if (Array.isArray(children)) - { - for (var i = 0; i < children.length; i++) - { - this.add(children[i], addToScene); - } - } - - return this; - }, - - /** - * Removes a member of this Group and optionally removes it from the Scene and / or destroys it. - * - * Calls {@link Phaser.GameObjects.Group#removeCallback}. - * - * @method Phaser.GameObjects.Group#remove - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to remove. - * @param {boolean} [removeFromScene=false] - Optionally remove the Group member from the Scene it belongs to. - * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group member. - * - * @return {this} This Group object. - */ - remove: function (child, removeFromScene, destroyChild) - { - if (removeFromScene === undefined) { removeFromScene = false; } - if (destroyChild === undefined) { destroyChild = false; } - - if (!this.children.contains(child)) - { - return this; - } - - this.children.delete(child); - - if (this.internalRemoveCallback) - { - this.internalRemoveCallback.call(this, child); - } - - if (this.removeCallback) - { - this.removeCallback.call(this, child); - } - - child.off(Events.DESTROY, this.remove, this); - - if (destroyChild) - { - child.destroy(); - } - else if (removeFromScene) - { - child.scene.sys.displayList.remove(child); - - if (child.preUpdate) - { - child.scene.sys.updateList.remove(child); - } - } - - return this; - }, - - /** - * Removes all members of this Group and optionally removes them from the Scene and / or destroys them. - * - * Does not call {@link Phaser.GameObjects.Group#removeCallback}. - * - * @method Phaser.GameObjects.Group#clear - * @since 3.0.0 - * - * @param {boolean} [removeFromScene=false] - Optionally remove each Group member from the Scene. - * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group members. - * - * @return {this} This group. - */ - clear: function (removeFromScene, destroyChild) - { - if (removeFromScene === undefined) { removeFromScene = false; } - if (destroyChild === undefined) { destroyChild = false; } - - var children = this.children; - - for (var i = 0; i < children.size; i++) - { - var gameObject = children.entries[i]; - - gameObject.off(Events.DESTROY, this.remove, this); - - if (destroyChild) - { - gameObject.destroy(); - } - else if (removeFromScene) - { - gameObject.scene.sys.displayList.remove(gameObject); - - if (gameObject.preUpdate) - { - gameObject.scene.sys.updateList.remove(gameObject); - } - } - } - - this.children.clear(); - - return this; - }, - - /** - * Tests if a Game Object is a member of this group. - * - * @method Phaser.GameObjects.Group#contains - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - A Game Object. - * - * @return {boolean} True if the Game Object is a member of this group. - */ - contains: function (child) - { - return this.children.contains(child); - }, - - /** - * All members of the group. - * - * @method Phaser.GameObjects.Group#getChildren - * @since 3.0.0 - * - * @return {Phaser.GameObjects.GameObject[]} The group members. - */ - getChildren: function () - { - return this.children.entries; - }, - - /** - * The number of members of the group. - * - * @method Phaser.GameObjects.Group#getLength - * @since 3.0.0 - * - * @return {integer} - */ - getLength: function () - { - return this.children.size; - }, - - /** - * Scans the Group, from top to bottom, for the first member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getFirst - * @since 3.0.0 - * - * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {?any} The first matching group member, or a newly created member, or null. - */ - getFirst: function (state, createIfNull, x, y, key, frame, visible) - { - return this.getHandler(true, 1, state, createIfNull, x, y, key, frame, visible); - }, - - /** - * Scans the Group, from top to bottom, for the nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getFirstNth - * @since 3.6.0 - * - * @param {integer} nth - The nth matching Group member to search for. - * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {?any} The first matching group member, or a newly created member, or null. - */ - getFirstNth: function (nth, state, createIfNull, x, y, key, frame, visible) - { - return this.getHandler(true, nth, state, createIfNull, x, y, key, frame, visible); - }, - - /** - * Scans the Group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getLast - * @since 3.6.0 - * - * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {?any} The first matching group member, or a newly created member, or null. - */ - getLast: function (state, createIfNull, x, y, key, frame, visible) - { - return this.getHandler(false, 1, state, createIfNull, x, y, key, frame, visible); - }, - - /** - * Scans the Group for the last nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getLastNth - * @since 3.6.0 - * - * @param {integer} nth - The nth matching Group member to search for. - * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {?any} The first matching group member, or a newly created member, or null. - */ - getLastNth: function (nth, state, createIfNull, x, y, key, frame, visible) - { - return this.getHandler(false, nth, state, createIfNull, x, y, key, frame, visible); - }, - - /** - * Scans the group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getHandler - * @private - * @since 3.6.0 - * - * @param {boolean} forwards - Search front to back or back to front? - * @param {integer} nth - Stop matching after nth successful matches. - * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {?any} The first matching group member, or a newly created member, or null. - */ - getHandler: function (forwards, nth, state, createIfNull, x, y, key, frame, visible) - { - if (state === undefined) { state = false; } - if (createIfNull === undefined) { createIfNull = false; } - - var gameObject; - - var i; - var total = 0; - var children = this.children.entries; - - if (forwards) - { - for (i = 0; i < children.length; i++) - { - gameObject = children[i]; - - if (gameObject.active === state) - { - total++; - - if (total === nth) - { - break; - } - } - else - { - gameObject = null; - } - } - } - else - { - for (i = children.length - 1; i >= 0; i--) - { - gameObject = children[i]; - - if (gameObject.active === state) - { - total++; - - if (total === nth) - { - break; - } - } - else - { - gameObject = null; - } - } - } - - if (gameObject) - { - if (typeof(x) === 'number') - { - gameObject.x = x; - } - - if (typeof(y) === 'number') - { - gameObject.y = y; - } - - return gameObject; - } - - // Got this far? We need to create or bail - if (createIfNull) - { - return this.create(x, y, key, frame, visible); - } - else - { - return null; - } - }, - - /** - * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, - * assigns `x` and `y`, and returns the member. - * - * If no inactive member is found and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * The new Game Object will have its active state set to `true`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#get - * @since 3.0.0 - * - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {?any} The first inactive group member, or a newly created member, or null. - */ - get: function (x, y, key, frame, visible) - { - return this.getFirst(false, true, x, y, key, frame, visible); - }, - - /** - * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `true`, - * assigns `x` and `y`, and returns the member. - * - * If no active member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getFirstAlive - * @since 3.0.0 - * - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {any} The first active group member, or a newly created member, or null. - */ - getFirstAlive: function (createIfNull, x, y, key, frame, visible) - { - return this.getFirst(true, createIfNull, x, y, key, frame, visible); - }, - - /** - * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, - * assigns `x` and `y`, and returns the member. - * - * If no inactive member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. - * The new Game Object will have an active state set to `true`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * - * @method Phaser.GameObjects.Group#getFirstDead - * @since 3.0.0 - * - * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. - * @param {number} [x] - The horizontal position of the Game Object in the world. - * @param {number} [y] - The vertical position of the Game Object in the world. - * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). - * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). - * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). - * - * @return {any} The first inactive group member, or a newly created member, or null. - */ - getFirstDead: function (createIfNull, x, y, key, frame, visible) - { - return this.getFirst(false, createIfNull, x, y, key, frame, visible); - }, - - /** - * {@link Phaser.GameObjects.Components.Animation#play Plays} an animation for all members of this group. - * - * @method Phaser.GameObjects.Group#playAnimation - * @since 3.0.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {string} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Group object. - */ - playAnimation: function (key, startFrame) - { - Actions.PlayAnimation(this.children.entries, key, startFrame); - - return this; - }, - - /** - * Whether this group's size at its {@link Phaser.GameObjects.Group#maxSize maximum}. - * - * @method Phaser.GameObjects.Group#isFull - * @since 3.0.0 - * - * @return {boolean} True if the number of members equals {@link Phaser.GameObjects.Group#maxSize}. - */ - isFull: function () - { - if (this.maxSize === -1) - { - return false; - } - else - { - return (this.children.size >= this.maxSize); - } - }, - - /** - * Counts the number of active (or inactive) group members. - * - * @method Phaser.GameObjects.Group#countActive - * @since 3.0.0 - * - * @param {boolean} [value=true] - Count active (true) or inactive (false) group members. - * - * @return {integer} The number of group members with an active state matching the `active` argument. - */ - countActive: function (value) - { - if (value === undefined) { value = true; } - - var total = 0; - - for (var i = 0; i < this.children.size; i++) - { - if (this.children.entries[i].active === value) - { - total++; - } - } - - return total; - }, - - /** - * Counts the number of in-use (active) group members. - * - * @method Phaser.GameObjects.Group#getTotalUsed - * @since 3.0.0 - * - * @return {integer} The number of group members with an active state of true. - */ - getTotalUsed: function () - { - return this.countActive(); - }, - - /** - * The difference of {@link Phaser.GameObjects.Group#maxSize} and the number of active group members. - * - * This represents the number of group members that could be created or reactivated before reaching the size limit. - * - * @method Phaser.GameObjects.Group#getTotalFree - * @since 3.0.0 - * - * @return {integer} maxSize minus the number of active group numbers; or a large number (if maxSize is -1). - */ - getTotalFree: function () - { - var used = this.getTotalUsed(); - var capacity = (this.maxSize === -1) ? 999999999999 : this.maxSize; - - return (capacity - used); - }, - - /** - * Sets the property as defined in `key` of each group member to the given value. - * - * @method Phaser.GameObjects.Group#propertyValueSet - * @since 3.21.0 - * - * @param {string} key - The property to be updated. - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {this} This Group object. - */ - propertyValueSet: function (key, value, step, index, direction) - { - Actions.PropertyValueSet(this.children.entries, key, value, step, index, direction); - - return this; - }, - - /** - * Adds the given value to the property as defined in `key` of each group member. - * - * @method Phaser.GameObjects.Group#propertyValueInc - * @since 3.21.0 - * - * @param {string} key - The property to be updated. - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {this} This Group object. - */ - propertyValueInc: function (key, value, step, index, direction) - { - Actions.PropertyValueInc(this.children.entries, key, value, step, index, direction); - - return this; - }, - - /** - * Sets the x of each group member. - * - * @method Phaser.GameObjects.Group#setX - * @since 3.21.0 - * - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - setX: function (value, step) - { - Actions.SetX(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the y of each group member. - * - * @method Phaser.GameObjects.Group#setY - * @since 3.21.0 - * - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - setY: function (value, step) - { - Actions.SetY(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the x, y of each group member. - * - * @method Phaser.GameObjects.Group#setXY - * @since 3.21.0 - * - * @param {number} x - The amount to set the `x` property to. - * @param {number} [y=x] - The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. - * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - setXY: function (x, y, stepX, stepY) - { - Actions.SetXY(this.children.entries, x, y, stepX, stepY); - - return this; - }, - - /** - * Adds the given value to the x of each group member. - * - * @method Phaser.GameObjects.Group#incX - * @since 3.21.0 - * - * @param {number} value - The amount to be added to the `x` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - incX: function (value, step) - { - Actions.IncX(this.children.entries, value, step); - - return this; - }, - - /** - * Adds the given value to the y of each group member. - * - * @method Phaser.GameObjects.Group#incY - * @since 3.21.0 - * - * @param {number} value - The amount to be added to the `y` property. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - incY: function (value, step) - { - Actions.IncY(this.children.entries, value, step); - - return this; - }, - - /** - * Adds the given value to the x, y of each group member. - * - * @method Phaser.GameObjects.Group#incXY - * @since 3.21.0 - * - * @param {number} x - The amount to be added to the `x` property. - * @param {number} [y=x] - The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. - * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - incXY: function (x, y, stepX, stepY) - { - Actions.IncXY(this.children.entries, x, y, stepX, stepY); - - return this; - }, - - /** - * Iterate through the group members changing the position of each element to be that of the element that came before - * it in the array (or after it if direction = 1) - * - * The first group member position is set to x/y. - * - * @method Phaser.GameObjects.Group#shiftPosition - * @since 3.21.0 - * - * @param {number} x - The x coordinate to place the first item in the array at. - * @param {number} y - The y coordinate to place the first item in the array at. - * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. - * - * @return {this} This Group object. - */ - shiftPosition: function (x, y, direction) - { - Actions.ShiftPosition(this.children.entries, x, y, direction); - - return this; - }, - - /** - * Sets the angle of each group member. - * - * @method Phaser.GameObjects.Group#angle - * @since 3.21.0 - * - * @param {number} value - The amount to set the angle to, in degrees. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - angle: function (value, step) - { - Actions.Angle(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the rotation of each group member. - * - * @method Phaser.GameObjects.Group#rotate - * @since 3.21.0 - * - * @param {number} value - The amount to set the rotation to, in radians. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - rotate: function (value, step) - { - Actions.Rotate(this.children.entries, value, step); - - return this; - }, - - /** - * Rotates each group member around the given point by the given angle. - * - * @method Phaser.GameObjects.Group#rotateAround - * @since 3.21.0 - * - * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. - * @param {number} angle - The angle to rotate by, in radians. - * - * @return {this} This Group object. - */ - rotateAround: function (point, angle) - { - Actions.RotateAround(this.children.entries, point, angle); - - return this; - }, - - /** - * Rotates each group member around the given point by the given angle and distance. - * - * @method Phaser.GameObjects.Group#rotateAroundDistance - * @since 3.21.0 - * - * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. - * @param {number} angle - The angle to rotate by, in radians. - * @param {number} distance - The distance from the point of rotation in pixels. - * - * @return {this} This Group object. - */ - rotateAroundDistance: function (point, angle, distance) - { - Actions.RotateAroundDistance(this.children.entries, point, angle, distance); - - return this; - }, - - /** - * Sets the alpha of each group member. - * - * @method Phaser.GameObjects.Group#setAlpha - * @since 3.21.0 - * - * @param {number} value - The amount to set the alpha to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - setAlpha: function (value, step) - { - Actions.SetAlpha(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the tint of each group member. - * - * @method Phaser.GameObjects.Group#setTint - * @since 3.21.0 - * - * @param {number} topLeft - The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. - * @param {number} [topRight] - The tint to be applied to top-right corner of item. - * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. - * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. - * - * @return {this} This Group object. - */ - setTint: function (topLeft, topRight, bottomLeft, bottomRight) - { - Actions.SetTint(this.children.entries, topLeft, topRight, bottomLeft, bottomRight); - - return this; - }, - - /** - * Sets the originX, originY of each group member. - * - * @method Phaser.GameObjects.Group#setOrigin - * @since 3.21.0 - * - * @param {number} originX - The amount to set the `originX` property to. - * @param {number} [originY] - The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. - * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - setOrigin: function (originX, originY, stepX, stepY) - { - Actions.SetOrigin(this.children.entries, originX, originY, stepX, stepY); - - return this; - }, - - /** - * Sets the scaleX of each group member. - * - * @method Phaser.GameObjects.Group#scaleX - * @since 3.21.0 - * - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - scaleX: function (value, step) - { - Actions.ScaleX(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the scaleY of each group member. - * - * @method Phaser.GameObjects.Group#scaleY - * @since 3.21.0 - * - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - scaleY: function (value, step) - { - Actions.ScaleY(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the scaleX, scaleY of each group member. - * - * @method Phaser.GameObjects.Group#scaleXY - * @since 3.21.0 - * - * @param {number} scaleX - The amount to be added to the `scaleX` property. - * @param {number} [scaleY] - The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. - * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. - * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - scaleXY: function (scaleX, scaleY, stepX, stepY) - { - Actions.ScaleXY(this.children.entries, scaleX, scaleY, stepX, stepY); - - return this; - }, - - /** - * Sets the depth of each group member. - * - * @method Phaser.GameObjects.Group#setDepth - * @since 3.0.0 - * - * @param {number} value - The amount to set the property to. - * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. - * - * @return {this} This Group object. - */ - setDepth: function (value, step) - { - Actions.SetDepth(this.children.entries, value, step); - - return this; - }, - - /** - * Sets the blendMode of each group member. - * - * @method Phaser.GameObjects.Group#setBlendMode - * @since 3.21.0 - * - * @param {number} value - The amount to set the property to. - * - * @return {this} This Group object. - */ - setBlendMode: function (value) - { - Actions.SetBlendMode(this.children.entries, value); - - return this; - }, - - /** - * Passes all group members to the Input Manager to enable them for input with identical areas and callbacks. - * - * @method Phaser.GameObjects.Group#setHitArea - * @since 3.21.0 - * - * @param {*} 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 - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. - * - * @return {this} This Group object. - */ - setHitArea: function (hitArea, hitAreaCallback) - { - Actions.SetHitArea(this.children.entries, hitArea, hitAreaCallback); - - return this; - }, - - /** - * Shuffles the group members in place. - * - * @method Phaser.GameObjects.Group#shuffle - * @since 3.21.0 - * - * @return {this} This Group object. - */ - shuffle: function () - { - Actions.Shuffle(this.children.entries); - - return this; - }, - - /** - * Deactivates a member of this group. - * - * @method Phaser.GameObjects.Group#kill - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - A member of this group. - */ - kill: function (gameObject) - { - if (this.children.contains(gameObject)) - { - gameObject.setActive(false); - } - }, - - /** - * Deactivates and hides a member of this group. - * - * @method Phaser.GameObjects.Group#killAndHide - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - A member of this group. - */ - killAndHide: function (gameObject) - { - if (this.children.contains(gameObject)) - { - gameObject.setActive(false); - gameObject.setVisible(false); - } - }, - - /** - * Sets the visible of each group member. - * - * @method Phaser.GameObjects.Group#setVisible - * @since 3.21.0 - * - * @param {boolean} value - The value to set the property to. - * @param {integer} [index=0] - An optional offset to start searching from within the items array. - * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. - * - * @return {this} This Group object. - */ - setVisible: function (value, index, direction) - { - Actions.SetVisible(this.children.entries, value, index, direction); - - return this; - }, - - /** - * Toggles (flips) the visible state of each member of this group. - * - * @method Phaser.GameObjects.Group#toggleVisible - * @since 3.0.0 - * - * @return {this} This Group object. - */ - toggleVisible: function () - { - Actions.ToggleVisible(this.children.entries); - - return this; - }, - - /** - * Empties this group and removes it from the Scene. - * - * Does not call {@link Phaser.GameObjects.Group#removeCallback}. - * - * @method Phaser.GameObjects.Group#destroy - * @since 3.0.0 - * - * @param {boolean} [destroyChildren=false] - Also {@link Phaser.GameObjects.GameObject#destroy} each group member. - */ - destroy: function (destroyChildren) - { - if (destroyChildren === undefined) { destroyChildren = false; } - - // This Game Object had already been destroyed - if (!this.scene || this.ignoreDestroy) - { - return; - } - - this.clear(false, destroyChildren); - - this.scene = undefined; - this.children = undefined; - } - -}); - -module.exports = Group; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Actions = require('../../actions/'); +var Class = require('../../utils/Class'); +var Events = require('../events'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetValue = require('../../utils/object/GetValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var Range = require('../../utils/array/Range'); +var Set = require('../../structs/Set'); +var Sprite = require('../sprite/Sprite'); + +/** + * @classdesc + * A Group is a way for you to create, manipulate, or recycle similar Game Objects. + * + * Group membership is non-exclusive. A Game Object can belong to several groups, one group, or none. + * + * Groups themselves aren't displayable, and can't be positioned, rotated, scaled, or hidden. + * + * @class Group + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * @param {Phaser.Scene} scene - The scene this group belongs to. + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. If `key` is set, Phaser.GameObjects.Group#createMultiple is also called with these settings. + * + * @see Phaser.Physics.Arcade.Group + * @see Phaser.Physics.Arcade.StaticGroup + */ +var Group = new Class({ + + initialize: + + function Group (scene, children, config) + { + // 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 + + if (config) + { + // config has been set, are the children an array? + + if (children && !Array.isArray(children)) + { + children = [ children ]; + } + } + else if (Array.isArray(children)) + { + // No config, so let's check the children argument + + if (IsPlainObject(children[0])) + { + // It's an array of plain config objects + config = children; + children = null; + } + } + else if (IsPlainObject(children)) + { + // Children isn't an array. Is it a config object though? + config = children; + children = null; + } + + /** + * This scene this group belongs to. + * + * @name Phaser.GameObjects.Group#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * Members of this group. + * + * @name Phaser.GameObjects.Group#children + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.children = new Set(children); + + /** + * A flag identifying this object as a group. + * + * @name Phaser.GameObjects.Group#isParent + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.isParent = true; + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.GameObjects.Group#type + * @type {string} + * @default 'Group' + * @since 3.21.0 + */ + this.type = 'Group'; + + /** + * The class to create new group members from. + * + * @name Phaser.GameObjects.Group#classType + * @type {Function} + * @since 3.0.0 + * @default Phaser.GameObjects.Sprite + */ + this.classType = GetFastValue(config, 'classType', Sprite); + + /** + * The name of this group. + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.GameObjects.Group#name + * @type {string} + * @default '' + * @since 3.18.0 + */ + this.name = GetFastValue(config, 'name', ''); + + /** + * Whether this group runs its {@link Phaser.GameObjects.Group#preUpdate} method + * (which may update any members). + * + * @name Phaser.GameObjects.Group#active + * @type {boolean} + * @since 3.0.0 + */ + this.active = GetFastValue(config, 'active', true); + + /** + * The maximum size of this group, if used as a pool. -1 is no limit. + * + * @name Phaser.GameObjects.Group#maxSize + * @type {integer} + * @since 3.0.0 + * @default -1 + */ + this.maxSize = GetFastValue(config, 'maxSize', -1); + + /** + * A default texture key to use when creating new group members. + * + * This is used in {@link Phaser.GameObjects.Group#create} + * but not in {@link Phaser.GameObjects.Group#createMultiple}. + * + * @name Phaser.GameObjects.Group#defaultKey + * @type {string} + * @since 3.0.0 + */ + this.defaultKey = GetFastValue(config, 'defaultKey', null); + + /** + * A default texture frame to use when creating new group members. + * + * @name Phaser.GameObjects.Group#defaultFrame + * @type {(string|integer)} + * @since 3.0.0 + */ + this.defaultFrame = GetFastValue(config, 'defaultFrame', null); + + /** + * Whether to call the update method of any members. + * + * @name Phaser.GameObjects.Group#runChildUpdate + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.GameObjects.Group#preUpdate + */ + this.runChildUpdate = GetFastValue(config, 'runChildUpdate', false); + + /** + * A function to be called when adding or creating group members. + * + * @name Phaser.GameObjects.Group#createCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @since 3.0.0 + */ + this.createCallback = GetFastValue(config, 'createCallback', null); + + /** + * A function to be called when removing group members. + * + * @name Phaser.GameObjects.Group#removeCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @since 3.0.0 + */ + this.removeCallback = GetFastValue(config, 'removeCallback', null); + + /** + * A function to be called when creating several group members at once. + * + * @name Phaser.GameObjects.Group#createMultipleCallback + * @type {?Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback} + * @since 3.0.0 + */ + this.createMultipleCallback = GetFastValue(config, 'createMultipleCallback', null); + + /** + * A function to be called when adding or creating group members. + * For internal use only by a Group, or any class that extends it. + * + * @name Phaser.GameObjects.Group#internalCreateCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @private + * @since 3.22.0 + */ + this.internalCreateCallback = GetFastValue(config, 'internalCreateCallback', null); + + /** + * A function to be called when removing group members. + * For internal use only by a Group, or any class that extends it. + * + * @name Phaser.GameObjects.Group#internalRemoveCallback + * @type {?Phaser.Types.GameObjects.Group.GroupCallback} + * @private + * @since 3.22.0 + */ + this.internalRemoveCallback = GetFastValue(config, 'internalRemoveCallback', null); + + if (config) + { + this.createMultiple(config); + } + }, + + /** + * Creates a new Game Object and adds it to this group, unless the group {@link Phaser.GameObjects.Group#isFull is full}. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#create + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal position of the new Game Object in the world. + * @param {number} [y=0] - The vertical position of the new Game Object in the world. + * @param {string} [key=defaultKey] - The texture key of the new Game Object. + * @param {(string|integer)} [frame=defaultFrame] - The texture frame of the new Game Object. + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of the new Game Object. + * @param {boolean} [active=true] - The {@link Phaser.GameObjects.GameObject#active} state of the new Game Object. + * + * @return {any} The new Game Object (usually a Sprite, etc.). + */ + create: function (x, y, key, frame, visible, active) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (key === undefined) { key = this.defaultKey; } + if (frame === undefined) { frame = this.defaultFrame; } + if (visible === undefined) { visible = true; } + if (active === undefined) { active = true; } + + // Pool? + if (this.isFull()) + { + return null; + } + + var child = new this.classType(this.scene, x, y, key, frame); + + this.scene.sys.displayList.add(child); + + if (child.preUpdate) + { + this.scene.sys.updateList.add(child); + } + + child.visible = visible; + child.setActive(active); + + this.add(child); + + return child; + }, + + /** + * Creates several Game Objects and adds them to this group. + * + * If the group becomes {@link Phaser.GameObjects.Group#isFull}, no further Game Objects are created. + * + * Calls {@link Phaser.GameObjects.Group#createMultipleCallback} and {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#createMultiple + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Group.GroupCreateConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig[]} config - Creation settings. This can be a single configuration object or an array of such objects, which will be applied in turn. + * + * @return {any[]} The newly created Game Objects. + */ + createMultiple: function (config) + { + if (this.isFull()) + { + return []; + } + + if (!Array.isArray(config)) + { + config = [ config ]; + } + + var output = []; + + if (config[0].key) + { + for (var i = 0; i < config.length; i++) + { + var entries = this.createFromConfig(config[i]); + + output = output.concat(entries); + } + } + + return output; + }, + + /** + * A helper for {@link Phaser.GameObjects.Group#createMultiple}. + * + * @method Phaser.GameObjects.Group#createFromConfig + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Group.GroupCreateConfig} options - Creation settings. + * + * @return {any[]} The newly created Game Objects. + */ + createFromConfig: function (options) + { + if (this.isFull()) + { + return []; + } + + this.classType = GetFastValue(options, 'classType', this.classType); + + var key = GetFastValue(options, 'key', undefined); + var frame = GetFastValue(options, 'frame', null); + var visible = GetFastValue(options, 'visible', true); + var active = GetFastValue(options, 'active', true); + + var entries = []; + + // Can't do anything without at least a key + if (key === undefined) + { + return entries; + } + else + { + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + } + + // Build an array of key frame pairs to loop through + + var repeat = GetFastValue(options, 'repeat', 0); + var randomKey = GetFastValue(options, 'randomKey', false); + var randomFrame = GetFastValue(options, 'randomFrame', false); + var yoyo = GetFastValue(options, 'yoyo', false); + var quantity = GetFastValue(options, 'quantity', false); + var frameQuantity = GetFastValue(options, 'frameQuantity', 1); + var max = GetFastValue(options, 'max', 0); + + // If a quantity value is set we use that to override the frameQuantity + + var range = Range(key, frame, { + max: max, + qty: (quantity) ? quantity : frameQuantity, + random: randomKey, + randomB: randomFrame, + repeat: repeat, + yoyo: yoyo + }); + + if (options.createCallback) + { + this.createCallback = options.createCallback; + } + + if (options.removeCallback) + { + this.removeCallback = options.removeCallback; + } + + for (var c = 0; c < range.length; c++) + { + var created = this.create(0, 0, range[c].a, range[c].b, visible, active); + + if (!created) + { + break; + } + + entries.push(created); + } + + // Post-creation options (applied only to those items created in this call): + + var x = GetValue(options, 'setXY.x', 0); + var y = GetValue(options, 'setXY.y', 0); + var stepX = GetValue(options, 'setXY.stepX', 0); + var stepY = GetValue(options, 'setXY.stepY', 0); + + Actions.SetXY(entries, x, y, stepX, stepY); + + var rotation = GetValue(options, 'setRotation.value', 0); + var stepRotation = GetValue(options, 'setRotation.step', 0); + + Actions.SetRotation(entries, rotation, stepRotation); + + var scaleX = GetValue(options, 'setScale.x', 1); + var scaleY = GetValue(options, 'setScale.y', scaleX); + var stepScaleX = GetValue(options, 'setScale.stepX', 0); + var stepScaleY = GetValue(options, 'setScale.stepY', 0); + + Actions.SetScale(entries, scaleX, scaleY, stepScaleX, stepScaleY); + + var alpha = GetValue(options, 'setAlpha.value', 1); + var stepAlpha = GetValue(options, 'setAlpha.step', 0); + + Actions.SetAlpha(entries, alpha, stepAlpha); + + var depth = GetValue(options, 'setDepth.value', 0); + var stepDepth = GetValue(options, 'setDepth.step', 0); + + Actions.SetDepth(entries, depth, stepDepth); + + var scrollFactorX = GetValue(options, 'setScrollFactor.x', 1); + var scrollFactorY = GetValue(options, 'setScrollFactor.y', scrollFactorX); + var stepScrollFactorX = GetValue(options, 'setScrollFactor.stepX', 0); + var stepScrollFactorY = GetValue(options, 'setScrollFactor.stepY', 0); + + Actions.SetScrollFactor(entries, scrollFactorX, scrollFactorY, stepScrollFactorX, stepScrollFactorY); + + var hitArea = GetFastValue(options, 'hitArea', null); + var hitAreaCallback = GetFastValue(options, 'hitAreaCallback', null); + + if (hitArea) + { + Actions.SetHitArea(entries, hitArea, hitAreaCallback); + } + + var grid = GetFastValue(options, 'gridAlign', false); + + if (grid) + { + Actions.GridAlign(entries, grid); + } + + if (this.createMultipleCallback) + { + this.createMultipleCallback.call(this, entries); + } + + return entries; + }, + + /** + * Updates any group members, if {@link Phaser.GameObjects.Group#runChildUpdate} is enabled. + * + * @method Phaser.GameObjects.Group#preUpdate + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time elapsed since the last frame. + */ + preUpdate: function (time, delta) + { + if (!this.runChildUpdate || this.children.size === 0) + { + return; + } + + // Because a Group child may mess with the length of the Group during its update + var temp = this.children.entries.slice(); + + for (var i = 0; i < temp.length; i++) + { + var item = temp[i]; + + if (item.active) + { + item.update(time, delta); + } + } + }, + + /** + * Adds a Game Object to this group. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#add + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. + * @param {boolean} [addToScene=false] - Also add the Game Object to the scene. + * + * @return {this} This Group object. + */ + add: function (child, addToScene) + { + if (addToScene === undefined) { addToScene = false; } + + if (this.isFull()) + { + return this; + } + + this.children.set(child); + + if (this.internalCreateCallback) + { + this.internalCreateCallback.call(this, child); + } + + if (this.createCallback) + { + this.createCallback.call(this, child); + } + + if (addToScene) + { + this.scene.sys.displayList.add(child); + + if (child.preUpdate) + { + this.scene.sys.updateList.add(child); + } + } + + child.on(Events.DESTROY, this.remove, this); + + return this; + }, + + /** + * Adds several Game Objects to this group. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * + * @method Phaser.GameObjects.Group#addMultiple + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject[]} children - The Game Objects to add. + * @param {boolean} [addToScene=false] - Also add the Game Objects to the scene. + * + * @return {this} This group. + */ + addMultiple: function (children, addToScene) + { + if (addToScene === undefined) { addToScene = false; } + + if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], addToScene); + } + } + + return this; + }, + + /** + * Removes a member of this Group and optionally removes it from the Scene and / or destroys it. + * + * Calls {@link Phaser.GameObjects.Group#removeCallback}. + * + * @method Phaser.GameObjects.Group#remove + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to remove. + * @param {boolean} [removeFromScene=false] - Optionally remove the Group member from the Scene it belongs to. + * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group member. + * + * @return {this} This Group object. + */ + remove: function (child, removeFromScene, destroyChild) + { + if (removeFromScene === undefined) { removeFromScene = false; } + if (destroyChild === undefined) { destroyChild = false; } + + if (!this.children.contains(child)) + { + return this; + } + + this.children.delete(child); + + if (this.internalRemoveCallback) + { + this.internalRemoveCallback.call(this, child); + } + + if (this.removeCallback) + { + this.removeCallback.call(this, child); + } + + child.off(Events.DESTROY, this.remove, this); + + if (destroyChild) + { + child.destroy(); + } + else if (removeFromScene) + { + child.scene.sys.displayList.remove(child); + + if (child.preUpdate) + { + child.scene.sys.updateList.remove(child); + } + } + + return this; + }, + + /** + * Removes all members of this Group and optionally removes them from the Scene and / or destroys them. + * + * Does not call {@link Phaser.GameObjects.Group#removeCallback}. + * + * @method Phaser.GameObjects.Group#clear + * @since 3.0.0 + * + * @param {boolean} [removeFromScene=false] - Optionally remove each Group member from the Scene. + * @param {boolean} [destroyChild=false] - Optionally call destroy on the removed Group members. + * + * @return {this} This group. + */ + clear: function (removeFromScene, destroyChild) + { + if (removeFromScene === undefined) { removeFromScene = false; } + if (destroyChild === undefined) { destroyChild = false; } + + var children = this.children; + + for (var i = 0; i < children.size; i++) + { + var gameObject = children.entries[i]; + + gameObject.off(Events.DESTROY, this.remove, this); + + if (destroyChild) + { + gameObject.destroy(); + } + else if (removeFromScene) + { + gameObject.scene.sys.displayList.remove(gameObject); + + if (gameObject.preUpdate) + { + gameObject.scene.sys.updateList.remove(gameObject); + } + } + } + + this.children.clear(); + + return this; + }, + + /** + * Tests if a Game Object is a member of this group. + * + * @method Phaser.GameObjects.Group#contains + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - A Game Object. + * + * @return {boolean} True if the Game Object is a member of this group. + */ + contains: function (child) + { + return this.children.contains(child); + }, + + /** + * All members of the group. + * + * @method Phaser.GameObjects.Group#getChildren + * @since 3.0.0 + * + * @return {Phaser.GameObjects.GameObject[]} The group members. + */ + getChildren: function () + { + return this.children.entries; + }, + + /** + * The number of members of the group. + * + * @method Phaser.GameObjects.Group#getLength + * @since 3.0.0 + * + * @return {integer} + */ + getLength: function () + { + return this.children.size; + }, + + /** + * Scans the Group, from top to bottom, for the first member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirst + * @since 3.0.0 + * + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getFirst: function (state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(true, 1, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the Group, from top to bottom, for the nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirstNth + * @since 3.6.0 + * + * @param {integer} nth - The nth matching Group member to search for. + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getFirstNth: function (nth, state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(true, nth, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the Group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getLast + * @since 3.6.0 + * + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getLast: function (state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(false, 1, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the Group for the last nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getLastNth + * @since 3.6.0 + * + * @param {integer} nth - The nth matching Group member to search for. + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getLastNth: function (nth, state, createIfNull, x, y, key, frame, visible) + { + return this.getHandler(false, nth, state, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getHandler + * @private + * @since 3.6.0 + * + * @param {boolean} forwards - Search front to back or back to front? + * @param {integer} nth - Stop matching after nth successful matches. + * @param {boolean} [state=false] - The {@link Phaser.GameObjects.GameObject#active} value to match. + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first matching group member, or a newly created member, or null. + */ + getHandler: function (forwards, nth, state, createIfNull, x, y, key, frame, visible) + { + if (state === undefined) { state = false; } + if (createIfNull === undefined) { createIfNull = false; } + + var gameObject; + + var i; + var total = 0; + var children = this.children.entries; + + if (forwards) + { + for (i = 0; i < children.length; i++) + { + gameObject = children[i]; + + if (gameObject.active === state) + { + total++; + + if (total === nth) + { + break; + } + } + else + { + gameObject = null; + } + } + } + else + { + for (i = children.length - 1; i >= 0; i--) + { + gameObject = children[i]; + + if (gameObject.active === state) + { + total++; + + if (total === nth) + { + break; + } + } + else + { + gameObject = null; + } + } + } + + if (gameObject) + { + if (typeof(x) === 'number') + { + gameObject.x = x; + } + + if (typeof(y) === 'number') + { + gameObject.y = y; + } + + return gameObject; + } + + // Got this far? We need to create or bail + if (createIfNull) + { + return this.create(x, y, key, frame, visible); + } + else + { + return null; + } + }, + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, + * assigns `x` and `y`, and returns the member. + * + * If no inactive member is found and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * The new Game Object will have its active state set to `true`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#get + * @since 3.0.0 + * + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {?any} The first inactive group member, or a newly created member, or null. + */ + get: function (x, y, key, frame, visible) + { + return this.getFirst(false, true, x, y, key, frame, visible); + }, + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `true`, + * assigns `x` and `y`, and returns the member. + * + * If no active member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirstAlive + * @since 3.0.0 + * + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {any} The first active group member, or a newly created member, or null. + */ + getFirstAlive: function (createIfNull, x, y, key, frame, visible) + { + return this.getFirst(true, createIfNull, x, y, key, frame, visible); + }, + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, + * assigns `x` and `y`, and returns the member. + * + * If no inactive member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. + * The new Game Object will have an active state set to `true`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * + * @method Phaser.GameObjects.Group#getFirstDead + * @since 3.0.0 + * + * @param {boolean} [createIfNull=false] - Create a new Game Object if no matching members are found, using the following arguments. + * @param {number} [x] - The horizontal position of the Game Object in the world. + * @param {number} [y] - The vertical position of the Game Object in the world. + * @param {string} [key=defaultKey] - The texture key assigned to a new Game Object (if one is created). + * @param {(string|integer)} [frame=defaultFrame] - A texture frame assigned to a new Game Object (if one is created). + * @param {boolean} [visible=true] - The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). + * + * @return {any} The first inactive group member, or a newly created member, or null. + */ + getFirstDead: function (createIfNull, x, y, key, frame, visible) + { + return this.getFirst(false, createIfNull, x, y, key, frame, visible); + }, + + /** + * {@link Phaser.GameObjects.Components.Animation#play Plays} an animation for all members of this group. + * + * @method Phaser.GameObjects.Group#playAnimation + * @since 3.0.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {string} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {this} This Group object. + */ + playAnimation: function (key, startFrame) + { + Actions.PlayAnimation(this.children.entries, key, startFrame); + + return this; + }, + + /** + * Whether this group's size at its {@link Phaser.GameObjects.Group#maxSize maximum}. + * + * @method Phaser.GameObjects.Group#isFull + * @since 3.0.0 + * + * @return {boolean} True if the number of members equals {@link Phaser.GameObjects.Group#maxSize}. + */ + isFull: function () + { + if (this.maxSize === -1) + { + return false; + } + else + { + return (this.children.size >= this.maxSize); + } + }, + + /** + * Counts the number of active (or inactive) group members. + * + * @method Phaser.GameObjects.Group#countActive + * @since 3.0.0 + * + * @param {boolean} [value=true] - Count active (true) or inactive (false) group members. + * + * @return {integer} The number of group members with an active state matching the `active` argument. + */ + countActive: function (value) + { + if (value === undefined) { value = true; } + + var total = 0; + + for (var i = 0; i < this.children.size; i++) + { + if (this.children.entries[i].active === value) + { + total++; + } + } + + return total; + }, + + /** + * Counts the number of in-use (active) group members. + * + * @method Phaser.GameObjects.Group#getTotalUsed + * @since 3.0.0 + * + * @return {integer} The number of group members with an active state of true. + */ + getTotalUsed: function () + { + return this.countActive(); + }, + + /** + * The difference of {@link Phaser.GameObjects.Group#maxSize} and the number of active group members. + * + * This represents the number of group members that could be created or reactivated before reaching the size limit. + * + * @method Phaser.GameObjects.Group#getTotalFree + * @since 3.0.0 + * + * @return {integer} maxSize minus the number of active group numbers; or a large number (if maxSize is -1). + */ + getTotalFree: function () + { + var used = this.getTotalUsed(); + var capacity = (this.maxSize === -1) ? 999999999999 : this.maxSize; + + return (capacity - used); + }, + + /** + * Sets the property as defined in `key` of each group member to the given value. + * + * @method Phaser.GameObjects.Group#propertyValueSet + * @since 3.21.0 + * + * @param {string} key - The property to be updated. + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {this} This Group object. + */ + propertyValueSet: function (key, value, step, index, direction) + { + Actions.PropertyValueSet(this.children.entries, key, value, step, index, direction); + + return this; + }, + + /** + * Adds the given value to the property as defined in `key` of each group member. + * + * @method Phaser.GameObjects.Group#propertyValueInc + * @since 3.21.0 + * + * @param {string} key - The property to be updated. + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {this} This Group object. + */ + propertyValueInc: function (key, value, step, index, direction) + { + Actions.PropertyValueInc(this.children.entries, key, value, step, index, direction); + + return this; + }, + + /** + * Sets the x of each group member. + * + * @method Phaser.GameObjects.Group#setX + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + setX: function (value, step) + { + Actions.SetX(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the y of each group member. + * + * @method Phaser.GameObjects.Group#setY + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + setY: function (value, step) + { + Actions.SetY(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the x, y of each group member. + * + * @method Phaser.GameObjects.Group#setXY + * @since 3.21.0 + * + * @param {number} x - The amount to set the `x` property to. + * @param {number} [y=x] - The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + setXY: function (x, y, stepX, stepY) + { + Actions.SetXY(this.children.entries, x, y, stepX, stepY); + + return this; + }, + + /** + * Adds the given value to the x of each group member. + * + * @method Phaser.GameObjects.Group#incX + * @since 3.21.0 + * + * @param {number} value - The amount to be added to the `x` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + incX: function (value, step) + { + Actions.IncX(this.children.entries, value, step); + + return this; + }, + + /** + * Adds the given value to the y of each group member. + * + * @method Phaser.GameObjects.Group#incY + * @since 3.21.0 + * + * @param {number} value - The amount to be added to the `y` property. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + incY: function (value, step) + { + Actions.IncY(this.children.entries, value, step); + + return this; + }, + + /** + * Adds the given value to the x, y of each group member. + * + * @method Phaser.GameObjects.Group#incXY + * @since 3.21.0 + * + * @param {number} x - The amount to be added to the `x` property. + * @param {number} [y=x] - The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. + * @param {number} [stepX=0] - This is added to the `x` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `y` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + incXY: function (x, y, stepX, stepY) + { + Actions.IncXY(this.children.entries, x, y, stepX, stepY); + + return this; + }, + + /** + * Iterate through the group members changing the position of each element to be that of the element that came before + * it in the array (or after it if direction = 1) + * + * The first group member position is set to x/y. + * + * @method Phaser.GameObjects.Group#shiftPosition + * @since 3.21.0 + * + * @param {number} x - The x coordinate to place the first item in the array at. + * @param {number} y - The y coordinate to place the first item in the array at. + * @param {integer} [direction=0] - The iteration direction. 0 = first to last and 1 = last to first. + * + * @return {this} This Group object. + */ + shiftPosition: function (x, y, direction) + { + Actions.ShiftPosition(this.children.entries, x, y, direction); + + return this; + }, + + /** + * Sets the angle of each group member. + * + * @method Phaser.GameObjects.Group#angle + * @since 3.21.0 + * + * @param {number} value - The amount to set the angle to, in degrees. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + angle: function (value, step) + { + Actions.Angle(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the rotation of each group member. + * + * @method Phaser.GameObjects.Group#rotate + * @since 3.21.0 + * + * @param {number} value - The amount to set the rotation to, in radians. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + rotate: function (value, step) + { + Actions.Rotate(this.children.entries, value, step); + + return this; + }, + + /** + * Rotates each group member around the given point by the given angle. + * + * @method Phaser.GameObjects.Group#rotateAround + * @since 3.21.0 + * + * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * + * @return {this} This Group object. + */ + rotateAround: function (point, angle) + { + Actions.RotateAround(this.children.entries, point, angle); + + return this; + }, + + /** + * Rotates each group member around the given point by the given angle and distance. + * + * @method Phaser.GameObjects.Group#rotateAroundDistance + * @since 3.21.0 + * + * @param {Phaser.Types.Math.Vector2Like} point - Any object with public `x` and `y` properties. + * @param {number} angle - The angle to rotate by, in radians. + * @param {number} distance - The distance from the point of rotation in pixels. + * + * @return {this} This Group object. + */ + rotateAroundDistance: function (point, angle, distance) + { + Actions.RotateAroundDistance(this.children.entries, point, angle, distance); + + return this; + }, + + /** + * Sets the alpha of each group member. + * + * @method Phaser.GameObjects.Group#setAlpha + * @since 3.21.0 + * + * @param {number} value - The amount to set the alpha to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + setAlpha: function (value, step) + { + Actions.SetAlpha(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the tint of each group member. + * + * @method Phaser.GameObjects.Group#setTint + * @since 3.21.0 + * + * @param {number} topLeft - The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. + * @param {number} [topRight] - The tint to be applied to top-right corner of item. + * @param {number} [bottomLeft] - The tint to be applied to the bottom-left corner of item. + * @param {number} [bottomRight] - The tint to be applied to the bottom-right corner of item. + * + * @return {this} This Group object. + */ + setTint: function (topLeft, topRight, bottomLeft, bottomRight) + { + Actions.SetTint(this.children.entries, topLeft, topRight, bottomLeft, bottomRight); + + return this; + }, + + /** + * Sets the originX, originY of each group member. + * + * @method Phaser.GameObjects.Group#setOrigin + * @since 3.21.0 + * + * @param {number} originX - The amount to set the `originX` property to. + * @param {number} [originY] - The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. + * @param {number} [stepX=0] - This is added to the `originX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `originY` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + setOrigin: function (originX, originY, stepX, stepY) + { + Actions.SetOrigin(this.children.entries, originX, originY, stepX, stepY); + + return this; + }, + + /** + * Sets the scaleX of each group member. + * + * @method Phaser.GameObjects.Group#scaleX + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + scaleX: function (value, step) + { + Actions.ScaleX(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the scaleY of each group member. + * + * @method Phaser.GameObjects.Group#scaleY + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + scaleY: function (value, step) + { + Actions.ScaleY(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the scaleX, scaleY of each group member. + * + * @method Phaser.GameObjects.Group#scaleXY + * @since 3.21.0 + * + * @param {number} scaleX - The amount to be added to the `scaleX` property. + * @param {number} [scaleY] - The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. + * @param {number} [stepX=0] - This is added to the `scaleX` amount, multiplied by the iteration counter. + * @param {number} [stepY=0] - This is added to the `scaleY` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + scaleXY: function (scaleX, scaleY, stepX, stepY) + { + Actions.ScaleXY(this.children.entries, scaleX, scaleY, stepX, stepY); + + return this; + }, + + /** + * Sets the depth of each group member. + * + * @method Phaser.GameObjects.Group#setDepth + * @since 3.0.0 + * + * @param {number} value - The amount to set the property to. + * @param {number} [step=0] - This is added to the `value` amount, multiplied by the iteration counter. + * + * @return {this} This Group object. + */ + setDepth: function (value, step) + { + Actions.SetDepth(this.children.entries, value, step); + + return this; + }, + + /** + * Sets the blendMode of each group member. + * + * @method Phaser.GameObjects.Group#setBlendMode + * @since 3.21.0 + * + * @param {number} value - The amount to set the property to. + * + * @return {this} This Group object. + */ + setBlendMode: function (value) + { + Actions.SetBlendMode(this.children.entries, value); + + return this; + }, + + /** + * Passes all group members to the Input Manager to enable them for input with identical areas and callbacks. + * + * @method Phaser.GameObjects.Group#setHitArea + * @since 3.21.0 + * + * @param {*} 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 - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. + * + * @return {this} This Group object. + */ + setHitArea: function (hitArea, hitAreaCallback) + { + Actions.SetHitArea(this.children.entries, hitArea, hitAreaCallback); + + return this; + }, + + /** + * Shuffles the group members in place. + * + * @method Phaser.GameObjects.Group#shuffle + * @since 3.21.0 + * + * @return {this} This Group object. + */ + shuffle: function () + { + Actions.Shuffle(this.children.entries); + + return this; + }, + + /** + * Deactivates a member of this group. + * + * @method Phaser.GameObjects.Group#kill + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - A member of this group. + */ + kill: function (gameObject) + { + if (this.children.contains(gameObject)) + { + gameObject.setActive(false); + } + }, + + /** + * Deactivates and hides a member of this group. + * + * @method Phaser.GameObjects.Group#killAndHide + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - A member of this group. + */ + killAndHide: function (gameObject) + { + if (this.children.contains(gameObject)) + { + gameObject.setActive(false); + gameObject.setVisible(false); + } + }, + + /** + * Sets the visible of each group member. + * + * @method Phaser.GameObjects.Group#setVisible + * @since 3.21.0 + * + * @param {boolean} value - The value to set the property to. + * @param {integer} [index=0] - An optional offset to start searching from within the items array. + * @param {integer} [direction=1] - The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. + * + * @return {this} This Group object. + */ + setVisible: function (value, index, direction) + { + Actions.SetVisible(this.children.entries, value, index, direction); + + return this; + }, + + /** + * Toggles (flips) the visible state of each member of this group. + * + * @method Phaser.GameObjects.Group#toggleVisible + * @since 3.0.0 + * + * @return {this} This Group object. + */ + toggleVisible: function () + { + Actions.ToggleVisible(this.children.entries); + + return this; + }, + + /** + * Empties this group and removes it from the Scene. + * + * Does not call {@link Phaser.GameObjects.Group#removeCallback}. + * + * @method Phaser.GameObjects.Group#destroy + * @since 3.0.0 + * + * @param {boolean} [destroyChildren=false] - Also {@link Phaser.GameObjects.GameObject#destroy} each group member. + */ + destroy: function (destroyChildren) + { + if (destroyChildren === undefined) { destroyChildren = false; } + + // This Game Object had already been destroyed + if (!this.scene || this.ignoreDestroy) + { + return; + } + + this.clear(false, destroyChildren); + + this.scene = undefined; + this.children = undefined; + } + +}); + +module.exports = Group; diff --git a/src/gameobjects/group/GroupCreator.js b/src/gameobjects/group/GroupCreator.js index 7e3046e81..b8c7c196c 100644 --- a/src/gameobjects/group/GroupCreator.js +++ b/src/gameobjects/group/GroupCreator.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectCreator = require('../GameObjectCreator'); -var Group = require('./Group'); - -/** - * Creates a new Group Game Object and returns it. - * - * Note: This method will only be available if the Group Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#group - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} config - The configuration object this Game Object will use to create itself. - * - * @return {Phaser.GameObjects.Group} The Game Object that was created. - */ -GameObjectCreator.register('group', function (config) -{ - return new Group(this.scene, null, config); -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = require('../GameObjectCreator'); +var Group = require('./Group'); + +/** + * Creates a new Group Game Object and returns it. + * + * Note: This method will only be available if the Group Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#group + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} config - The configuration object this Game Object will use to create itself. + * + * @return {Phaser.GameObjects.Group} The Game Object that was created. + */ +GameObjectCreator.register('group', function (config) +{ + return new Group(this.scene, null, config); +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/group/GroupFactory.js b/src/gameobjects/group/GroupFactory.js index 9abcf6ccd..05c47a683 100644 --- a/src/gameobjects/group/GroupFactory.js +++ b/src/gameobjects/group/GroupFactory.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Group = require('./Group'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Group Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Group Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#group - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupConfig[])} [children] - Game Objects to add to this Group; or the `config` argument. - * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - A Group Configuration object. - * - * @return {Phaser.GameObjects.Group} The Game Object that was created. - */ -GameObjectFactory.register('group', function (children, config) -{ - return this.updateList.add(new Group(this.scene, children, config)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Group = require('./Group'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Group Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Group Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#group + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupConfig[])} [children] - Game Objects to add to this Group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - A Group Configuration object. + * + * @return {Phaser.GameObjects.Group} The Game Object that was created. + */ +GameObjectFactory.register('group', function (children, config) +{ + return this.updateList.add(new Group(this.scene, children, config)); +}); diff --git a/src/gameobjects/group/typedefs/index.js b/src/gameobjects/group/typedefs/index.js index 1b10eea4b..8861b3c4f 100644 --- a/src/gameobjects/group/typedefs/index.js +++ b/src/gameobjects/group/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.Group - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.Group + */ diff --git a/src/gameobjects/image/Image.js b/src/gameobjects/image/Image.js index f87a6e1f5..6269a4d11 100644 --- a/src/gameobjects/image/Image.js +++ b/src/gameobjects/image/Image.js @@ -1,95 +1,95 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var ImageRender = require('./ImageRender'); - -/** - * @classdesc - * An Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * - * @class Image - * @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.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var Image = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - ImageRender - ], - - initialize: - - function Image (scene, x, y, texture, frame) - { - GameObject.call(this, scene, 'Image'); - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.Image#_crop - * @type {object} - * @private - * @since 3.11.0 - */ - this._crop = this.resetCropObject(); - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.setOriginFromFrame(); - this.initPipeline(); - } - -}); - -module.exports = Image; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var ImageRender = require('./ImageRender'); + +/** + * @classdesc + * An Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class Image + * @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.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Image = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + ImageRender + ], + + initialize: + + function Image (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Image'); + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Image#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + } + +}); + +module.exports = Image; diff --git a/src/gameobjects/image/ImageCanvasRenderer.js b/src/gameobjects/image/ImageCanvasRenderer.js index 1c044bded..6f6da02e2 100644 --- a/src/gameobjects/image/ImageCanvasRenderer.js +++ b/src/gameobjects/image/ImageCanvasRenderer.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Image#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Image} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ImageCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - renderer.batchSprite(src, src.frame, camera, parentMatrix); -}; - -module.exports = ImageCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Image#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Image} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ImageCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = ImageCanvasRenderer; diff --git a/src/gameobjects/image/ImageCreator.js b/src/gameobjects/image/ImageCreator.js index a9487f96e..ce4b8736c 100644 --- a/src/gameobjects/image/ImageCreator.js +++ b/src/gameobjects/image/ImageCreator.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var Image = require('./Image'); - -/** - * Creates a new Image Game Object and returns it. - * - * Note: This method will only be available if the Image Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#image - * @since 3.0.0 - * - * @param {object} 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.Image} The Game Object that was created. - */ -GameObjectCreator.register('image', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - - var image = new Image(this.scene, 0, 0, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, image, config); - - return image; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var Image = require('./Image'); + +/** + * Creates a new Image Game Object and returns it. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#image + * @since 3.0.0 + * + * @param {object} 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.Image} The Game Object that was created. + */ +GameObjectCreator.register('image', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var image = new Image(this.scene, 0, 0, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, image, config); + + return image; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/image/ImageFactory.js b/src/gameobjects/image/ImageFactory.js index 8335defa5..a9e388d93 100644 --- a/src/gameobjects/image/ImageFactory.js +++ b/src/gameobjects/image/ImageFactory.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Image = require('./Image'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Image Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Image Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#image - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.Image} The Game Object that was created. - */ -GameObjectFactory.register('image', function (x, y, key, frame) -{ - return this.displayList.add(new Image(this.scene, x, y, key, frame)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Image = require('./Image'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Image Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#image + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Image} The Game Object that was created. + */ +GameObjectFactory.register('image', function (x, y, key, frame) +{ + return this.displayList.add(new Image(this.scene, x, y, key, frame)); +}); + +// 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 diff --git a/src/gameobjects/image/ImageRender.js b/src/gameobjects/image/ImageRender.js index e42de7c5d..0e086e49a 100644 --- a/src/gameobjects/image/ImageRender.js +++ b/src/gameobjects/image/ImageRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./ImageWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./ImageCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./ImageWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./ImageCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/image/ImageWebGLRenderer.js b/src/gameobjects/image/ImageWebGLRenderer.js index 95170b109..0d8c9dd3f 100644 --- a/src/gameobjects/image/ImageWebGLRenderer.js +++ b/src/gameobjects/image/ImageWebGLRenderer.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Image#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Image} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ImageWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - this.pipeline.batchSprite(src, camera, parentMatrix); -}; - -module.exports = ImageWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Image#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Image} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ImageWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + this.pipeline.batchSprite(src, camera, parentMatrix); +}; + +module.exports = ImageWebGLRenderer; diff --git a/src/gameobjects/index.js b/src/gameobjects/index.js index cd6c90019..7db1d006d 100644 --- a/src/gameobjects/index.js +++ b/src/gameobjects/index.js @@ -1,137 +1,137 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.GameObjects - */ - -var GameObjects = { - - Events: require('./events'), - - DisplayList: require('./DisplayList'), - GameObjectCreator: require('./GameObjectCreator'), - GameObjectFactory: require('./GameObjectFactory'), - UpdateList: require('./UpdateList'), - - Components: require('./components'), - - BuildGameObject: require('./BuildGameObject'), - BuildGameObjectAnimation: require('./BuildGameObjectAnimation'), - GameObject: require('./GameObject'), - BitmapText: require('./bitmaptext/static/BitmapText'), - Blitter: require('./blitter/Blitter'), - Container: require('./container/Container'), - DOMElement: require('./domelement/DOMElement'), - DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapText'), - Extern: require('./extern/Extern.js'), - Graphics: require('./graphics/Graphics.js'), - Group: require('./group/Group'), - Image: require('./image/Image'), - Particles: require('./particles'), - PathFollower: require('./pathfollower/PathFollower'), - RenderTexture: require('./rendertexture/RenderTexture'), - RetroFont: require('./bitmaptext/RetroFont'), - Rope: require('./rope/Rope'), - Sprite: require('./sprite/Sprite'), - Text: require('./text/static/Text'), - TileSprite: require('./tilesprite/TileSprite'), - Zone: require('./zone/Zone'), - Video: require('./video/Video'), - - // Shapes - - Shape: require('./shape/Shape'), - Arc: require('./shape/arc/Arc'), - Curve: require('./shape/curve/Curve'), - Ellipse: require('./shape/ellipse/Ellipse'), - Grid: require('./shape/grid/Grid'), - IsoBox: require('./shape/isobox/IsoBox'), - IsoTriangle: require('./shape/isotriangle/IsoTriangle'), - Line: require('./shape/line/Line'), - Polygon: require('./shape/polygon/Polygon'), - Rectangle: require('./shape/rectangle/Rectangle'), - Star: require('./shape/star/Star'), - Triangle: require('./shape/triangle/Triangle'), - - // Game Object Factories - - Factories: { - Blitter: require('./blitter/BlitterFactory'), - Container: require('./container/ContainerFactory'), - DOMElement: require('./domelement/DOMElementFactory'), - DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapTextFactory'), - Extern: require('./extern/ExternFactory'), - Graphics: require('./graphics/GraphicsFactory'), - Group: require('./group/GroupFactory'), - Image: require('./image/ImageFactory'), - Particles: require('./particles/ParticleManagerFactory'), - PathFollower: require('./pathfollower/PathFollowerFactory'), - RenderTexture: require('./rendertexture/RenderTextureFactory'), - Rope: require('./rope/RopeFactory'), - Sprite: require('./sprite/SpriteFactory'), - StaticBitmapText: require('./bitmaptext/static/BitmapTextFactory'), - Text: require('./text/static/TextFactory'), - TileSprite: require('./tilesprite/TileSpriteFactory'), - Zone: require('./zone/ZoneFactory'), - Video: require('./video/VideoFactory'), - - // Shapes - Arc: require('./shape/arc/ArcFactory'), - Curve: require('./shape/curve/CurveFactory'), - Ellipse: require('./shape/ellipse/EllipseFactory'), - Grid: require('./shape/grid/GridFactory'), - IsoBox: require('./shape/isobox/IsoBoxFactory'), - IsoTriangle: require('./shape/isotriangle/IsoTriangleFactory'), - Line: require('./shape/line/LineFactory'), - Polygon: require('./shape/polygon/PolygonFactory'), - Rectangle: require('./shape/rectangle/RectangleFactory'), - Star: require('./shape/star/StarFactory'), - Triangle: require('./shape/triangle/TriangleFactory') - }, - - Creators: { - Blitter: require('./blitter/BlitterCreator'), - Container: require('./container/ContainerCreator'), - DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapTextCreator'), - Graphics: require('./graphics/GraphicsCreator'), - Group: require('./group/GroupCreator'), - Image: require('./image/ImageCreator'), - Particles: require('./particles/ParticleManagerCreator'), - RenderTexture: require('./rendertexture/RenderTextureCreator'), - Rope: require('./rope/RopeCreator'), - Sprite: require('./sprite/SpriteCreator'), - StaticBitmapText: require('./bitmaptext/static/BitmapTextCreator'), - Text: require('./text/static/TextCreator'), - TileSprite: require('./tilesprite/TileSpriteCreator'), - Zone: require('./zone/ZoneCreator'), - Video: require('./video/VideoCreator') - } - -}; - -if (typeof WEBGL_RENDERER) -{ - // WebGL only Game Objects - GameObjects.Mesh = require('./mesh/Mesh'); - GameObjects.Quad = require('./quad/Quad'); - GameObjects.Shader = require('./shader/Shader'); - - GameObjects.Factories.Mesh = require('./mesh/MeshFactory'); - GameObjects.Factories.Quad = require('./quad/QuadFactory'); - GameObjects.Factories.Shader = require('./shader/ShaderFactory'); - - GameObjects.Creators.Mesh = require('./mesh/MeshCreator'); - GameObjects.Creators.Quad = require('./quad/QuadCreator'); - GameObjects.Creators.Shader = require('./shader/ShaderCreator'); - - GameObjects.Light = require('./lights/Light'); - - require('./lights/LightsManager'); - require('./lights/LightsPlugin'); -} - -module.exports = GameObjects; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects + */ + +var GameObjects = { + + Events: require('./events'), + + DisplayList: require('./DisplayList'), + GameObjectCreator: require('./GameObjectCreator'), + GameObjectFactory: require('./GameObjectFactory'), + UpdateList: require('./UpdateList'), + + Components: require('./components'), + + BuildGameObject: require('./BuildGameObject'), + BuildGameObjectAnimation: require('./BuildGameObjectAnimation'), + GameObject: require('./GameObject'), + BitmapText: require('./bitmaptext/static/BitmapText'), + Blitter: require('./blitter/Blitter'), + Container: require('./container/Container'), + DOMElement: require('./domelement/DOMElement'), + DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapText'), + Extern: require('./extern/Extern.js'), + Graphics: require('./graphics/Graphics.js'), + Group: require('./group/Group'), + Image: require('./image/Image'), + Particles: require('./particles'), + PathFollower: require('./pathfollower/PathFollower'), + RenderTexture: require('./rendertexture/RenderTexture'), + RetroFont: require('./bitmaptext/RetroFont'), + Rope: require('./rope/Rope'), + Sprite: require('./sprite/Sprite'), + Text: require('./text/static/Text'), + TileSprite: require('./tilesprite/TileSprite'), + Zone: require('./zone/Zone'), + Video: require('./video/Video'), + + // Shapes + + Shape: require('./shape/Shape'), + Arc: require('./shape/arc/Arc'), + Curve: require('./shape/curve/Curve'), + Ellipse: require('./shape/ellipse/Ellipse'), + Grid: require('./shape/grid/Grid'), + IsoBox: require('./shape/isobox/IsoBox'), + IsoTriangle: require('./shape/isotriangle/IsoTriangle'), + Line: require('./shape/line/Line'), + Polygon: require('./shape/polygon/Polygon'), + Rectangle: require('./shape/rectangle/Rectangle'), + Star: require('./shape/star/Star'), + Triangle: require('./shape/triangle/Triangle'), + + // Game Object Factories + + Factories: { + Blitter: require('./blitter/BlitterFactory'), + Container: require('./container/ContainerFactory'), + DOMElement: require('./domelement/DOMElementFactory'), + DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapTextFactory'), + Extern: require('./extern/ExternFactory'), + Graphics: require('./graphics/GraphicsFactory'), + Group: require('./group/GroupFactory'), + Image: require('./image/ImageFactory'), + Particles: require('./particles/ParticleManagerFactory'), + PathFollower: require('./pathfollower/PathFollowerFactory'), + RenderTexture: require('./rendertexture/RenderTextureFactory'), + Rope: require('./rope/RopeFactory'), + Sprite: require('./sprite/SpriteFactory'), + StaticBitmapText: require('./bitmaptext/static/BitmapTextFactory'), + Text: require('./text/static/TextFactory'), + TileSprite: require('./tilesprite/TileSpriteFactory'), + Zone: require('./zone/ZoneFactory'), + Video: require('./video/VideoFactory'), + + // Shapes + Arc: require('./shape/arc/ArcFactory'), + Curve: require('./shape/curve/CurveFactory'), + Ellipse: require('./shape/ellipse/EllipseFactory'), + Grid: require('./shape/grid/GridFactory'), + IsoBox: require('./shape/isobox/IsoBoxFactory'), + IsoTriangle: require('./shape/isotriangle/IsoTriangleFactory'), + Line: require('./shape/line/LineFactory'), + Polygon: require('./shape/polygon/PolygonFactory'), + Rectangle: require('./shape/rectangle/RectangleFactory'), + Star: require('./shape/star/StarFactory'), + Triangle: require('./shape/triangle/TriangleFactory') + }, + + Creators: { + Blitter: require('./blitter/BlitterCreator'), + Container: require('./container/ContainerCreator'), + DynamicBitmapText: require('./bitmaptext/dynamic/DynamicBitmapTextCreator'), + Graphics: require('./graphics/GraphicsCreator'), + Group: require('./group/GroupCreator'), + Image: require('./image/ImageCreator'), + Particles: require('./particles/ParticleManagerCreator'), + RenderTexture: require('./rendertexture/RenderTextureCreator'), + Rope: require('./rope/RopeCreator'), + Sprite: require('./sprite/SpriteCreator'), + StaticBitmapText: require('./bitmaptext/static/BitmapTextCreator'), + Text: require('./text/static/TextCreator'), + TileSprite: require('./tilesprite/TileSpriteCreator'), + Zone: require('./zone/ZoneCreator'), + Video: require('./video/VideoCreator') + } + +}; + +if (typeof WEBGL_RENDERER) +{ + // WebGL only Game Objects + GameObjects.Mesh = require('./mesh/Mesh'); + GameObjects.Quad = require('./quad/Quad'); + GameObjects.Shader = require('./shader/Shader'); + + GameObjects.Factories.Mesh = require('./mesh/MeshFactory'); + GameObjects.Factories.Quad = require('./quad/QuadFactory'); + GameObjects.Factories.Shader = require('./shader/ShaderFactory'); + + GameObjects.Creators.Mesh = require('./mesh/MeshCreator'); + GameObjects.Creators.Quad = require('./quad/QuadCreator'); + GameObjects.Creators.Shader = require('./shader/ShaderCreator'); + + GameObjects.Light = require('./lights/Light'); + + require('./lights/LightsManager'); + require('./lights/LightsPlugin'); +} + +module.exports = GameObjects; diff --git a/src/gameobjects/lights/Light.js b/src/gameobjects/lights/Light.js index 57128d907..cb6b7beb8 100644 --- a/src/gameobjects/lights/Light.js +++ b/src/gameobjects/lights/Light.js @@ -1,257 +1,257 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Utils = require('../../renderer/webgl/Utils'); - -/** - * @classdesc - * A 2D point light. - * - * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`. - * - * Any Game Objects using the Light2D pipeline will then be affected by these Lights. - * - * They can also simply be used to represent a point light for your own purposes. - * - * @class Light - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the light. - * @param {number} y - The vertical position of the light. - * @param {number} radius - The radius of the light. - * @param {number} r - The red color of the light. A value between 0 and 1. - * @param {number} g - The green color of the light. A value between 0 and 1. - * @param {number} b - The blue color of the light. A value between 0 and 1. - * @param {number} intensity - The intensity of the light. - */ -var Light = new Class({ - - initialize: - - function Light (x, y, radius, r, g, b, intensity) - { - /** - * The horizontal position of the light. - * - * @name Phaser.GameObjects.Light#x - * @type {number} - * @since 3.0.0 - */ - this.x = x; - - /** - * The vertical position of the light. - * - * @name Phaser.GameObjects.Light#y - * @type {number} - * @since 3.0.0 - */ - this.y = y; - - /** - * The radius of the light. - * - * @name Phaser.GameObjects.Light#radius - * @type {number} - * @since 3.0.0 - */ - this.radius = radius; - - /** - * The red color of the light. A value between 0 and 1. - * - * @name Phaser.GameObjects.Light#r - * @type {number} - * @since 3.0.0 - */ - this.r = r; - - /** - * The green color of the light. A value between 0 and 1. - * - * @name Phaser.GameObjects.Light#g - * @type {number} - * @since 3.0.0 - */ - this.g = g; - - /** - * The blue color of the light. A value between 0 and 1. - * - * @name Phaser.GameObjects.Light#b - * @type {number} - * @since 3.0.0 - */ - this.b = b; - - /** - * The intensity of the light. - * - * @name Phaser.GameObjects.Light#intensity - * @type {number} - * @since 3.0.0 - */ - this.intensity = intensity; - - /** - * The horizontal scroll factor of the light. - * - * @name Phaser.GameObjects.Light#scrollFactorX - * @type {number} - * @since 3.0.0 - */ - this.scrollFactorX = 1.0; - - /** - * The vertical scroll factor of the light. - * - * @name Phaser.GameObjects.Light#scrollFactorY - * @type {number} - * @since 3.0.0 - */ - this.scrollFactorY = 1.0; - }, - - /** - * Set the properties of the light. - * - * Sets both horizontal and vertical scroll factor to 1. Use {@link Phaser.GameObjects.Light#setScrollFactor} to set - * the scroll factor. - * - * @method Phaser.GameObjects.Light#set - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the light. - * @param {number} y - The vertical position of the light. - * @param {number} radius - The radius of the light. - * @param {number} r - The red color. A value between 0 and 1. - * @param {number} g - The green color. A value between 0 and 1. - * @param {number} b - The blue color. A value between 0 and 1. - * @param {number} intensity - The intensity of the light. - * - * @return {this} This Light object. - */ - set: function (x, y, radius, r, g, b, intensity) - { - this.x = x; - this.y = y; - - this.radius = radius; - - this.r = r; - this.g = g; - this.b = b; - - this.intensity = intensity; - - this.scrollFactorX = 1; - this.scrollFactorY = 1; - - return this; - }, - - /** - * Set the scroll factor of the light. - * - * @method Phaser.GameObjects.Light#setScrollFactor - * @since 3.0.0 - * - * @param {number} x - The horizontal scroll factor of the light. - * @param {number} y - The vertical scroll factor of the light. - * - * @return {this} This Light object. - */ - setScrollFactor: function (x, y) - { - if (x === undefined) { x = 1; } - if (y === undefined) { y = x; } - - this.scrollFactorX = x; - this.scrollFactorY = y; - - return this; - }, - - /** - * Set the color of the light from a single integer RGB value. - * - * @method Phaser.GameObjects.Light#setColor - * @since 3.0.0 - * - * @param {number} rgb - The integer RGB color of the light. - * - * @return {this} This Light object. - */ - setColor: function (rgb) - { - var color = Utils.getFloatsFromUintRGB(rgb); - - this.r = color[0]; - this.g = color[1]; - this.b = color[2]; - - return this; - }, - - /** - * Set the intensity of the light. - * - * @method Phaser.GameObjects.Light#setIntensity - * @since 3.0.0 - * - * @param {number} intensity - The intensity of the light. - * - * @return {this} This Light object. - */ - setIntensity: function (intensity) - { - this.intensity = intensity; - - return this; - }, - - /** - * Set the position of the light. - * - * @method Phaser.GameObjects.Light#setPosition - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the light. - * @param {number} y - The vertical position of the light. - * - * @return {this} This Light object. - */ - setPosition: function (x, y) - { - this.x = x; - this.y = y; - - return this; - }, - - /** - * Set the radius of the light. - * - * @method Phaser.GameObjects.Light#setRadius - * @since 3.0.0 - * - * @param {number} radius - The radius of the light. - * - * @return {this} This Light object. - */ - setRadius: function (radius) - { - this.radius = radius; - - return this; - } - -}); - -module.exports = Light; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Utils = require('../../renderer/webgl/Utils'); + +/** + * @classdesc + * A 2D point light. + * + * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`. + * + * Any Game Objects using the Light2D pipeline will then be affected by these Lights. + * + * They can also simply be used to represent a point light for your own purposes. + * + * @class Light + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the light. + * @param {number} y - The vertical position of the light. + * @param {number} radius - The radius of the light. + * @param {number} r - The red color of the light. A value between 0 and 1. + * @param {number} g - The green color of the light. A value between 0 and 1. + * @param {number} b - The blue color of the light. A value between 0 and 1. + * @param {number} intensity - The intensity of the light. + */ +var Light = new Class({ + + initialize: + + function Light (x, y, radius, r, g, b, intensity) + { + /** + * The horizontal position of the light. + * + * @name Phaser.GameObjects.Light#x + * @type {number} + * @since 3.0.0 + */ + this.x = x; + + /** + * The vertical position of the light. + * + * @name Phaser.GameObjects.Light#y + * @type {number} + * @since 3.0.0 + */ + this.y = y; + + /** + * The radius of the light. + * + * @name Phaser.GameObjects.Light#radius + * @type {number} + * @since 3.0.0 + */ + this.radius = radius; + + /** + * The red color of the light. A value between 0 and 1. + * + * @name Phaser.GameObjects.Light#r + * @type {number} + * @since 3.0.0 + */ + this.r = r; + + /** + * The green color of the light. A value between 0 and 1. + * + * @name Phaser.GameObjects.Light#g + * @type {number} + * @since 3.0.0 + */ + this.g = g; + + /** + * The blue color of the light. A value between 0 and 1. + * + * @name Phaser.GameObjects.Light#b + * @type {number} + * @since 3.0.0 + */ + this.b = b; + + /** + * The intensity of the light. + * + * @name Phaser.GameObjects.Light#intensity + * @type {number} + * @since 3.0.0 + */ + this.intensity = intensity; + + /** + * The horizontal scroll factor of the light. + * + * @name Phaser.GameObjects.Light#scrollFactorX + * @type {number} + * @since 3.0.0 + */ + this.scrollFactorX = 1.0; + + /** + * The vertical scroll factor of the light. + * + * @name Phaser.GameObjects.Light#scrollFactorY + * @type {number} + * @since 3.0.0 + */ + this.scrollFactorY = 1.0; + }, + + /** + * Set the properties of the light. + * + * Sets both horizontal and vertical scroll factor to 1. Use {@link Phaser.GameObjects.Light#setScrollFactor} to set + * the scroll factor. + * + * @method Phaser.GameObjects.Light#set + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the light. + * @param {number} y - The vertical position of the light. + * @param {number} radius - The radius of the light. + * @param {number} r - The red color. A value between 0 and 1. + * @param {number} g - The green color. A value between 0 and 1. + * @param {number} b - The blue color. A value between 0 and 1. + * @param {number} intensity - The intensity of the light. + * + * @return {this} This Light object. + */ + set: function (x, y, radius, r, g, b, intensity) + { + this.x = x; + this.y = y; + + this.radius = radius; + + this.r = r; + this.g = g; + this.b = b; + + this.intensity = intensity; + + this.scrollFactorX = 1; + this.scrollFactorY = 1; + + return this; + }, + + /** + * Set the scroll factor of the light. + * + * @method Phaser.GameObjects.Light#setScrollFactor + * @since 3.0.0 + * + * @param {number} x - The horizontal scroll factor of the light. + * @param {number} y - The vertical scroll factor of the light. + * + * @return {this} This Light object. + */ + setScrollFactor: function (x, y) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + this.scrollFactorX = x; + this.scrollFactorY = y; + + return this; + }, + + /** + * Set the color of the light from a single integer RGB value. + * + * @method Phaser.GameObjects.Light#setColor + * @since 3.0.0 + * + * @param {number} rgb - The integer RGB color of the light. + * + * @return {this} This Light object. + */ + setColor: function (rgb) + { + var color = Utils.getFloatsFromUintRGB(rgb); + + this.r = color[0]; + this.g = color[1]; + this.b = color[2]; + + return this; + }, + + /** + * Set the intensity of the light. + * + * @method Phaser.GameObjects.Light#setIntensity + * @since 3.0.0 + * + * @param {number} intensity - The intensity of the light. + * + * @return {this} This Light object. + */ + setIntensity: function (intensity) + { + this.intensity = intensity; + + return this; + }, + + /** + * Set the position of the light. + * + * @method Phaser.GameObjects.Light#setPosition + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the light. + * @param {number} y - The vertical position of the light. + * + * @return {this} This Light object. + */ + setPosition: function (x, y) + { + this.x = x; + this.y = y; + + return this; + }, + + /** + * Set the radius of the light. + * + * @method Phaser.GameObjects.Light#setRadius + * @since 3.0.0 + * + * @param {number} radius - The radius of the light. + * + * @return {this} This Light object. + */ + setRadius: function (radius) + { + this.radius = radius; + + return this; + } + +}); + +module.exports = Light; diff --git a/src/gameobjects/lights/LightsManager.js b/src/gameobjects/lights/LightsManager.js index cedd23787..7d59734ce 100644 --- a/src/gameobjects/lights/LightsManager.js +++ b/src/gameobjects/lights/LightsManager.js @@ -1,357 +1,357 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Light = require('./Light'); -var Utils = require('../../renderer/webgl/Utils'); - -/** - * @callback LightForEach - * - * @param {Phaser.GameObjects.Light} light - The Light. - */ - -/** - * @classdesc - * Manages Lights for a Scene. - * - * Affects the rendering of Game Objects using the `Light2D` pipeline. - * - * @class LightsManager - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - */ -var LightsManager = new Class({ - - initialize: - - function LightsManager () - { - /** - * The pool of Lights. - * - * Used to recycle removed Lights for a more efficient use of memory. - * - * @name Phaser.GameObjects.LightsManager#lightPool - * @type {Phaser.GameObjects.Light[]} - * @default [] - * @since 3.0.0 - */ - this.lightPool = []; - - /** - * The Lights in the Scene. - * - * @name Phaser.GameObjects.LightsManager#lights - * @type {Phaser.GameObjects.Light[]} - * @default [] - * @since 3.0.0 - */ - this.lights = []; - - /** - * Lights that have been culled from a Camera's viewport. - * - * Lights in this list will not be rendered. - * - * @name Phaser.GameObjects.LightsManager#culledLights - * @type {Phaser.GameObjects.Light[]} - * @default [] - * @since 3.0.0 - */ - this.culledLights = []; - - /** - * The ambient color. - * - * @name Phaser.GameObjects.LightsManager#ambientColor - * @type {{ r: number, g: number, b: number }} - * @since 3.0.0 - */ - this.ambientColor = { r: 0.1, g: 0.1, b: 0.1 }; - - /** - * Whether the Lights Manager is enabled. - * - * @name Phaser.GameObjects.LightsManager#active - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.active = false; - - /** - * The maximum number of lights that a single Camera and the lights shader can process. - * Change this via the `maxLights` property in your game config, as it cannot be changed at runtime. - * - * @name Phaser.GameObjects.LightsManager#maxLights - * @type {integer} - * @readonly - * @since 3.15.0 - */ - this.maxLights = -1; - }, - - /** - * Enable the Lights Manager. - * - * @method Phaser.GameObjects.LightsManager#enable - * @since 3.0.0 - * - * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. - */ - enable: function () - { - if (this.maxLights === -1) - { - this.maxLights = this.scene.sys.game.renderer.config.maxLights; - } - - this.active = true; - - return this; - }, - - /** - * Disable the Lights Manager. - * - * @method Phaser.GameObjects.LightsManager#disable - * @since 3.0.0 - * - * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. - */ - disable: function () - { - this.active = false; - - return this; - }, - - /** - * Cull any Lights that aren't visible to the given Camera. - * - * Culling Lights improves performance by ensuring that only Lights within a Camera's viewport are rendered. - * - * @method Phaser.GameObjects.LightsManager#cull - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to cull Lights for. - * - * @return {Phaser.GameObjects.Light[]} The culled Lights. - */ - cull: function (camera) - { - var lights = this.lights; - var culledLights = this.culledLights; - var length = lights.length; - var cameraCenterX = camera.x + camera.width / 2.0; - var cameraCenterY = camera.y + camera.height / 2.0; - var cameraRadius = (camera.width + camera.height) / 2.0; - var point = { x: 0, y: 0 }; - var cameraMatrix = camera.matrix; - var viewportHeight = this.systems.game.config.height; - - culledLights.length = 0; - - for (var index = 0; index < length && culledLights.length < this.maxLights; index++) - { - var light = lights[index]; - - cameraMatrix.transformPoint(light.x, light.y, point); - - // We'll just use bounding spheres to test if lights should be rendered - var dx = cameraCenterX - (point.x - (camera.scrollX * light.scrollFactorX * camera.zoom)); - var dy = cameraCenterY - (viewportHeight - (point.y - (camera.scrollY * light.scrollFactorY) * camera.zoom)); - var distance = Math.sqrt(dx * dx + dy * dy); - - if (distance < light.radius + cameraRadius) - { - culledLights.push(lights[index]); - } - } - - return culledLights; - }, - - /** - * Iterate over each Light with a callback. - * - * @method Phaser.GameObjects.LightsManager#forEachLight - * @since 3.0.0 - * - * @param {LightForEach} callback - The callback that is called with each Light. - * - * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. - */ - forEachLight: function (callback) - { - if (!callback) - { - return; - } - - var lights = this.lights; - var length = lights.length; - - for (var index = 0; index < length; ++index) - { - callback(lights[index]); - } - - return this; - }, - - /** - * Set the ambient light color. - * - * @method Phaser.GameObjects.LightsManager#setAmbientColor - * @since 3.0.0 - * - * @param {number} rgb - The integer RGB color of the ambient light. - * - * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. - */ - setAmbientColor: function (rgb) - { - var color = Utils.getFloatsFromUintRGB(rgb); - - this.ambientColor.r = color[0]; - this.ambientColor.g = color[1]; - this.ambientColor.b = color[2]; - - return this; - }, - - /** - * Returns the maximum number of Lights allowed to appear at once. - * - * @method Phaser.GameObjects.LightsManager#getMaxVisibleLights - * @since 3.0.0 - * - * @return {integer} The maximum number of Lights allowed to appear at once. - */ - getMaxVisibleLights: function () - { - return 10; - }, - - /** - * Get the number of Lights managed by this Lights Manager. - * - * @method Phaser.GameObjects.LightsManager#getLightCount - * @since 3.0.0 - * - * @return {integer} The number of Lights managed by this Lights Manager. - */ - getLightCount: function () - { - return this.lights.length; - }, - - /** - * Add a Light. - * - * @method Phaser.GameObjects.LightsManager#addLight - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal position of the Light. - * @param {number} [y=0] - The vertical position of the Light. - * @param {number} [radius=100] - The radius of the Light. - * @param {number} [rgb=0xffffff] - The integer RGB color of the light. - * @param {number} [intensity=1] - The intensity of the Light. - * - * @return {Phaser.GameObjects.Light} The Light that was added. - */ - addLight: function (x, y, radius, rgb, intensity) - { - var color = null; - var light = null; - - x = (x === undefined) ? 0.0 : x; - y = (y === undefined) ? 0.0 : y; - rgb = (rgb === undefined) ? 0xffffff : rgb; - radius = (radius === undefined) ? 100.0 : radius; - intensity = (intensity === undefined) ? 1.0 : intensity; - - color = Utils.getFloatsFromUintRGB(rgb); - light = null; - - if (this.lightPool.length > 0) - { - light = this.lightPool.pop(); - light.set(x, y, radius, color[0], color[1], color[2], intensity); - } - else - { - light = new Light(x, y, radius, color[0], color[1], color[2], intensity); - } - - this.lights.push(light); - - return light; - }, - - /** - * Remove a Light. - * - * @method Phaser.GameObjects.LightsManager#removeLight - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Light} light - The Light to remove. - * - * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. - */ - removeLight: function (light) - { - var index = this.lights.indexOf(light); - - if (index >= 0) - { - this.lightPool.push(light); - this.lights.splice(index, 1); - } - - return this; - }, - - /** - * Shut down the Lights Manager. - * - * Recycles all active Lights into the Light pool, resets ambient light color and clears the lists of Lights and - * culled Lights. - * - * @method Phaser.GameObjects.LightsManager#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - while (this.lights.length > 0) - { - this.lightPool.push(this.lights.pop()); - } - - this.ambientColor = { r: 0.1, g: 0.1, b: 0.1 }; - this.culledLights.length = 0; - this.lights.length = 0; - }, - - /** - * Destroy the Lights Manager. - * - * Cleans up all references by calling {@link Phaser.GameObjects.LightsManager#shutdown}. - * - * @method Phaser.GameObjects.LightsManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - } - -}); - -module.exports = LightsManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Light = require('./Light'); +var Utils = require('../../renderer/webgl/Utils'); + +/** + * @callback LightForEach + * + * @param {Phaser.GameObjects.Light} light - The Light. + */ + +/** + * @classdesc + * Manages Lights for a Scene. + * + * Affects the rendering of Game Objects using the `Light2D` pipeline. + * + * @class LightsManager + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + */ +var LightsManager = new Class({ + + initialize: + + function LightsManager () + { + /** + * The pool of Lights. + * + * Used to recycle removed Lights for a more efficient use of memory. + * + * @name Phaser.GameObjects.LightsManager#lightPool + * @type {Phaser.GameObjects.Light[]} + * @default [] + * @since 3.0.0 + */ + this.lightPool = []; + + /** + * The Lights in the Scene. + * + * @name Phaser.GameObjects.LightsManager#lights + * @type {Phaser.GameObjects.Light[]} + * @default [] + * @since 3.0.0 + */ + this.lights = []; + + /** + * Lights that have been culled from a Camera's viewport. + * + * Lights in this list will not be rendered. + * + * @name Phaser.GameObjects.LightsManager#culledLights + * @type {Phaser.GameObjects.Light[]} + * @default [] + * @since 3.0.0 + */ + this.culledLights = []; + + /** + * The ambient color. + * + * @name Phaser.GameObjects.LightsManager#ambientColor + * @type {{ r: number, g: number, b: number }} + * @since 3.0.0 + */ + this.ambientColor = { r: 0.1, g: 0.1, b: 0.1 }; + + /** + * Whether the Lights Manager is enabled. + * + * @name Phaser.GameObjects.LightsManager#active + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.active = false; + + /** + * The maximum number of lights that a single Camera and the lights shader can process. + * Change this via the `maxLights` property in your game config, as it cannot be changed at runtime. + * + * @name Phaser.GameObjects.LightsManager#maxLights + * @type {integer} + * @readonly + * @since 3.15.0 + */ + this.maxLights = -1; + }, + + /** + * Enable the Lights Manager. + * + * @method Phaser.GameObjects.LightsManager#enable + * @since 3.0.0 + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + enable: function () + { + if (this.maxLights === -1) + { + this.maxLights = this.scene.sys.game.renderer.config.maxLights; + } + + this.active = true; + + return this; + }, + + /** + * Disable the Lights Manager. + * + * @method Phaser.GameObjects.LightsManager#disable + * @since 3.0.0 + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + disable: function () + { + this.active = false; + + return this; + }, + + /** + * Cull any Lights that aren't visible to the given Camera. + * + * Culling Lights improves performance by ensuring that only Lights within a Camera's viewport are rendered. + * + * @method Phaser.GameObjects.LightsManager#cull + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to cull Lights for. + * + * @return {Phaser.GameObjects.Light[]} The culled Lights. + */ + cull: function (camera) + { + var lights = this.lights; + var culledLights = this.culledLights; + var length = lights.length; + var cameraCenterX = camera.x + camera.width / 2.0; + var cameraCenterY = camera.y + camera.height / 2.0; + var cameraRadius = (camera.width + camera.height) / 2.0; + var point = { x: 0, y: 0 }; + var cameraMatrix = camera.matrix; + var viewportHeight = this.systems.game.config.height; + + culledLights.length = 0; + + for (var index = 0; index < length && culledLights.length < this.maxLights; index++) + { + var light = lights[index]; + + cameraMatrix.transformPoint(light.x, light.y, point); + + // We'll just use bounding spheres to test if lights should be rendered + var dx = cameraCenterX - (point.x - (camera.scrollX * light.scrollFactorX * camera.zoom)); + var dy = cameraCenterY - (viewportHeight - (point.y - (camera.scrollY * light.scrollFactorY) * camera.zoom)); + var distance = Math.sqrt(dx * dx + dy * dy); + + if (distance < light.radius + cameraRadius) + { + culledLights.push(lights[index]); + } + } + + return culledLights; + }, + + /** + * Iterate over each Light with a callback. + * + * @method Phaser.GameObjects.LightsManager#forEachLight + * @since 3.0.0 + * + * @param {LightForEach} callback - The callback that is called with each Light. + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + forEachLight: function (callback) + { + if (!callback) + { + return; + } + + var lights = this.lights; + var length = lights.length; + + for (var index = 0; index < length; ++index) + { + callback(lights[index]); + } + + return this; + }, + + /** + * Set the ambient light color. + * + * @method Phaser.GameObjects.LightsManager#setAmbientColor + * @since 3.0.0 + * + * @param {number} rgb - The integer RGB color of the ambient light. + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + setAmbientColor: function (rgb) + { + var color = Utils.getFloatsFromUintRGB(rgb); + + this.ambientColor.r = color[0]; + this.ambientColor.g = color[1]; + this.ambientColor.b = color[2]; + + return this; + }, + + /** + * Returns the maximum number of Lights allowed to appear at once. + * + * @method Phaser.GameObjects.LightsManager#getMaxVisibleLights + * @since 3.0.0 + * + * @return {integer} The maximum number of Lights allowed to appear at once. + */ + getMaxVisibleLights: function () + { + return 10; + }, + + /** + * Get the number of Lights managed by this Lights Manager. + * + * @method Phaser.GameObjects.LightsManager#getLightCount + * @since 3.0.0 + * + * @return {integer} The number of Lights managed by this Lights Manager. + */ + getLightCount: function () + { + return this.lights.length; + }, + + /** + * Add a Light. + * + * @method Phaser.GameObjects.LightsManager#addLight + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal position of the Light. + * @param {number} [y=0] - The vertical position of the Light. + * @param {number} [radius=100] - The radius of the Light. + * @param {number} [rgb=0xffffff] - The integer RGB color of the light. + * @param {number} [intensity=1] - The intensity of the Light. + * + * @return {Phaser.GameObjects.Light} The Light that was added. + */ + addLight: function (x, y, radius, rgb, intensity) + { + var color = null; + var light = null; + + x = (x === undefined) ? 0.0 : x; + y = (y === undefined) ? 0.0 : y; + rgb = (rgb === undefined) ? 0xffffff : rgb; + radius = (radius === undefined) ? 100.0 : radius; + intensity = (intensity === undefined) ? 1.0 : intensity; + + color = Utils.getFloatsFromUintRGB(rgb); + light = null; + + if (this.lightPool.length > 0) + { + light = this.lightPool.pop(); + light.set(x, y, radius, color[0], color[1], color[2], intensity); + } + else + { + light = new Light(x, y, radius, color[0], color[1], color[2], intensity); + } + + this.lights.push(light); + + return light; + }, + + /** + * Remove a Light. + * + * @method Phaser.GameObjects.LightsManager#removeLight + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Light} light - The Light to remove. + * + * @return {Phaser.GameObjects.LightsManager} This Lights Manager object. + */ + removeLight: function (light) + { + var index = this.lights.indexOf(light); + + if (index >= 0) + { + this.lightPool.push(light); + this.lights.splice(index, 1); + } + + return this; + }, + + /** + * Shut down the Lights Manager. + * + * Recycles all active Lights into the Light pool, resets ambient light color and clears the lists of Lights and + * culled Lights. + * + * @method Phaser.GameObjects.LightsManager#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + while (this.lights.length > 0) + { + this.lightPool.push(this.lights.pop()); + } + + this.ambientColor = { r: 0.1, g: 0.1, b: 0.1 }; + this.culledLights.length = 0; + this.lights.length = 0; + }, + + /** + * Destroy the Lights Manager. + * + * Cleans up all references by calling {@link Phaser.GameObjects.LightsManager#shutdown}. + * + * @method Phaser.GameObjects.LightsManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + } + +}); + +module.exports = LightsManager; diff --git a/src/gameobjects/lights/LightsPlugin.js b/src/gameobjects/lights/LightsPlugin.js index 3ef48403e..f39609b74 100644 --- a/src/gameobjects/lights/LightsPlugin.js +++ b/src/gameobjects/lights/LightsPlugin.js @@ -1,110 +1,110 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var LightsManager = require('./LightsManager'); -var PluginCache = require('../../plugins/PluginCache'); -var SceneEvents = require('../../scene/events'); - -/** - * @classdesc - * A Scene plugin that provides a {@link Phaser.GameObjects.LightsManager} for the Light2D pipeline. - * - * Available from within a Scene via `this.lights`. - * - * Add Lights using the {@link Phaser.GameObjects.LightsManager#addLight} method: - * - * ```javascript - * // Enable the Lights Manager because it is disabled by default - * this.lights.enable(); - * - * // Create a Light at [400, 300] with a radius of 200 - * this.lights.addLight(400, 300, 200); - * ``` - * - * For Game Objects to be affected by the Lights when rendered, you will need to set them to use the `Light2D` pipeline like so: - * - * ```javascript - * sprite.setPipeline('Light2D'); - * ``` - * - * @class LightsPlugin - * @extends Phaser.GameObjects.LightsManager - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that this Lights Plugin belongs to. - */ -var LightsPlugin = new Class({ - - Extends: LightsManager, - - initialize: - - function LightsPlugin (scene) - { - /** - * A reference to the Scene that this Lights Plugin belongs to. - * - * @name Phaser.GameObjects.LightsPlugin#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene's systems. - * - * @name Phaser.GameObjects.LightsPlugin#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - if (!scene.sys.settings.isBooted) - { - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - } - - LightsManager.call(this); - }, - - /** - * Boot the Lights Plugin. - * - * @method Phaser.GameObjects.LightsPlugin#boot - * @since 3.0.0 - */ - boot: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.SHUTDOWN, this.shutdown, this); - eventEmitter.on(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * Destroy the Lights Plugin. - * - * Cleans up all references. - * - * @method Phaser.GameObjects.LightsPlugin#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene = undefined; - this.systems = undefined; - } - -}); - -PluginCache.register('LightsPlugin', LightsPlugin, 'lights'); - -module.exports = LightsPlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var LightsManager = require('./LightsManager'); +var PluginCache = require('../../plugins/PluginCache'); +var SceneEvents = require('../../scene/events'); + +/** + * @classdesc + * A Scene plugin that provides a {@link Phaser.GameObjects.LightsManager} for the Light2D pipeline. + * + * Available from within a Scene via `this.lights`. + * + * Add Lights using the {@link Phaser.GameObjects.LightsManager#addLight} method: + * + * ```javascript + * // Enable the Lights Manager because it is disabled by default + * this.lights.enable(); + * + * // Create a Light at [400, 300] with a radius of 200 + * this.lights.addLight(400, 300, 200); + * ``` + * + * For Game Objects to be affected by the Lights when rendered, you will need to set them to use the `Light2D` pipeline like so: + * + * ```javascript + * sprite.setPipeline('Light2D'); + * ``` + * + * @class LightsPlugin + * @extends Phaser.GameObjects.LightsManager + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this Lights Plugin belongs to. + */ +var LightsPlugin = new Class({ + + Extends: LightsManager, + + initialize: + + function LightsPlugin (scene) + { + /** + * A reference to the Scene that this Lights Plugin belongs to. + * + * @name Phaser.GameObjects.LightsPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene's systems. + * + * @name Phaser.GameObjects.LightsPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + if (!scene.sys.settings.isBooted) + { + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + } + + LightsManager.call(this); + }, + + /** + * Boot the Lights Plugin. + * + * @method Phaser.GameObjects.LightsPlugin#boot + * @since 3.0.0 + */ + boot: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.SHUTDOWN, this.shutdown, this); + eventEmitter.on(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * Destroy the Lights Plugin. + * + * Cleans up all references. + * + * @method Phaser.GameObjects.LightsPlugin#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene = undefined; + this.systems = undefined; + } + +}); + +PluginCache.register('LightsPlugin', LightsPlugin, 'lights'); + +module.exports = LightsPlugin; diff --git a/src/gameobjects/mesh/Mesh.js b/src/gameobjects/mesh/Mesh.js index 302328849..28a9ecb6f 100644 --- a/src/gameobjects/mesh/Mesh.js +++ b/src/gameobjects/mesh/Mesh.js @@ -1,165 +1,165 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var MeshRender = require('./MeshRender'); -var NOOP = require('../../utils/NOOP'); - -/** - * @classdesc - * A Mesh Game Object. - * - * @class Mesh - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @webglOnly - * @since 3.0.0 - * - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * @extends Phaser.GameObjects.Components.ScrollFactor - * - * @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 {number[]} vertices - An array containing the vertices data for this Mesh. - * @param {number[]} uv - An array containing the uv data for this Mesh. - * @param {number[]} colors - An array containing the color data for this Mesh. - * @param {number[]} alphas - An array containing the alpha data for this Mesh. - * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var Mesh = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.BlendMode, - Components.Depth, - Components.Mask, - Components.Pipeline, - Components.Size, - Components.Texture, - Components.Transform, - Components.Visible, - Components.ScrollFactor, - MeshRender - ], - - initialize: - - function Mesh (scene, x, y, vertices, uv, colors, alphas, texture, frame) - { - GameObject.call(this, scene, 'Mesh'); - - if (vertices.length !== uv.length) - { - throw new Error('Mesh Vertex count must match UV count'); - } - - var verticesUB = (vertices.length / 2) | 0; - - if (colors.length > 0 && colors.length < verticesUB) - { - throw new Error('Mesh Color count must match Vertex count'); - } - - if (alphas.length > 0 && alphas.length < verticesUB) - { - throw new Error('Mesh Alpha count must match Vertex count'); - } - - var i; - - if (colors.length === 0) - { - for (i = 0; i < verticesUB; ++i) - { - colors[i] = 0xFFFFFF; - } - } - - if (alphas.length === 0) - { - for (i = 0; i < verticesUB; ++i) - { - alphas[i] = 1.0; - } - } - - /** - * An array containing the vertices data for this Mesh. - * - * @name Phaser.GameObjects.Mesh#vertices - * @type {Float32Array} - * @since 3.0.0 - */ - this.vertices = new Float32Array(vertices); - - /** - * An array containing the uv data for this Mesh. - * - * @name Phaser.GameObjects.Mesh#uv - * @type {Float32Array} - * @since 3.0.0 - */ - this.uv = new Float32Array(uv); - - /** - * An array containing the color data for this Mesh. - * - * @name Phaser.GameObjects.Mesh#colors - * @type {Uint32Array} - * @since 3.0.0 - */ - this.colors = new Uint32Array(colors); - - /** - * An array containing the alpha data for this Mesh. - * - * @name Phaser.GameObjects.Mesh#alphas - * @type {Float32Array} - * @since 3.0.0 - */ - this.alphas = new Float32Array(alphas); - - /** - * Fill or additive mode used when blending the color values? - * - * @name Phaser.GameObjects.Mesh#tintFill - * @type {boolean} - * @default false - * @since 3.11.0 - */ - this.tintFill = false; - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.initPipeline(); - }, - - /** - * This method is left intentionally empty and does not do anything. - * It is retained to allow a Mesh or Quad to be added to a Container. - * - * @method Phaser.GameObjects.Mesh#setAlpha - * @since 3.17.0 - */ - setAlpha: NOOP - -}); - -module.exports = Mesh; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var MeshRender = require('./MeshRender'); +var NOOP = require('../../utils/NOOP'); + +/** + * @classdesc + * A Mesh Game Object. + * + * @class Mesh + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * @extends Phaser.GameObjects.Components.ScrollFactor + * + * @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 {number[]} vertices - An array containing the vertices data for this Mesh. + * @param {number[]} uv - An array containing the uv data for this Mesh. + * @param {number[]} colors - An array containing the color data for this Mesh. + * @param {number[]} alphas - An array containing the alpha data for this Mesh. + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Mesh = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.BlendMode, + Components.Depth, + Components.Mask, + Components.Pipeline, + Components.Size, + Components.Texture, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + MeshRender + ], + + initialize: + + function Mesh (scene, x, y, vertices, uv, colors, alphas, texture, frame) + { + GameObject.call(this, scene, 'Mesh'); + + if (vertices.length !== uv.length) + { + throw new Error('Mesh Vertex count must match UV count'); + } + + var verticesUB = (vertices.length / 2) | 0; + + if (colors.length > 0 && colors.length < verticesUB) + { + throw new Error('Mesh Color count must match Vertex count'); + } + + if (alphas.length > 0 && alphas.length < verticesUB) + { + throw new Error('Mesh Alpha count must match Vertex count'); + } + + var i; + + if (colors.length === 0) + { + for (i = 0; i < verticesUB; ++i) + { + colors[i] = 0xFFFFFF; + } + } + + if (alphas.length === 0) + { + for (i = 0; i < verticesUB; ++i) + { + alphas[i] = 1.0; + } + } + + /** + * An array containing the vertices data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#vertices + * @type {Float32Array} + * @since 3.0.0 + */ + this.vertices = new Float32Array(vertices); + + /** + * An array containing the uv data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#uv + * @type {Float32Array} + * @since 3.0.0 + */ + this.uv = new Float32Array(uv); + + /** + * An array containing the color data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#colors + * @type {Uint32Array} + * @since 3.0.0 + */ + this.colors = new Uint32Array(colors); + + /** + * An array containing the alpha data for this Mesh. + * + * @name Phaser.GameObjects.Mesh#alphas + * @type {Float32Array} + * @since 3.0.0 + */ + this.alphas = new Float32Array(alphas); + + /** + * Fill or additive mode used when blending the color values? + * + * @name Phaser.GameObjects.Mesh#tintFill + * @type {boolean} + * @default false + * @since 3.11.0 + */ + this.tintFill = false; + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.initPipeline(); + }, + + /** + * This method is left intentionally empty and does not do anything. + * It is retained to allow a Mesh or Quad to be added to a Container. + * + * @method Phaser.GameObjects.Mesh#setAlpha + * @since 3.17.0 + */ + setAlpha: NOOP + +}); + +module.exports = Mesh; diff --git a/src/gameobjects/mesh/MeshCanvasRenderer.js b/src/gameobjects/mesh/MeshCanvasRenderer.js index 09cf824f5..e231c02f3 100644 --- a/src/gameobjects/mesh/MeshCanvasRenderer.js +++ b/src/gameobjects/mesh/MeshCanvasRenderer.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This is a stub function for Mesh.Render. There is no Canvas renderer for Mesh objects. - * - * @method Phaser.GameObjects.Mesh#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Mesh} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var MeshCanvasRenderer = function () -{ -}; - -module.exports = MeshCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a stub function for Mesh.Render. There is no Canvas renderer for Mesh objects. + * + * @method Phaser.GameObjects.Mesh#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Mesh} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var MeshCanvasRenderer = function () +{ +}; + +module.exports = MeshCanvasRenderer; diff --git a/src/gameobjects/mesh/MeshCreator.js b/src/gameobjects/mesh/MeshCreator.js index 43b6d5ab1..31aeae256 100644 --- a/src/gameobjects/mesh/MeshCreator.js +++ b/src/gameobjects/mesh/MeshCreator.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetValue = require('../../utils/object/GetValue'); -var Mesh = require('./Mesh'); - -/** - * Creates a new Mesh Game Object and returns it. - * - * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#mesh - * @since 3.0.0 - * - * @param {object} 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.Mesh} The Game Object that was created. - */ -GameObjectCreator.register('mesh', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - var vertices = GetValue(config, 'vertices', []); - var colors = GetValue(config, 'colors', []); - var alphas = GetValue(config, 'alphas', []); - var uv = GetValue(config, 'uv', []); - - var mesh = new Mesh(this.scene, 0, 0, vertices, uv, colors, alphas, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, mesh, config); - - return mesh; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetValue = require('../../utils/object/GetValue'); +var Mesh = require('./Mesh'); + +/** + * Creates a new Mesh Game Object and returns it. + * + * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#mesh + * @since 3.0.0 + * + * @param {object} 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.Mesh} The Game Object that was created. + */ +GameObjectCreator.register('mesh', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + var vertices = GetValue(config, 'vertices', []); + var colors = GetValue(config, 'colors', []); + var alphas = GetValue(config, 'alphas', []); + var uv = GetValue(config, 'uv', []); + + var mesh = new Mesh(this.scene, 0, 0, vertices, uv, colors, alphas, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, mesh, config); + + return mesh; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/mesh/MeshFactory.js b/src/gameobjects/mesh/MeshFactory.js index c83e1da44..a9befc460 100644 --- a/src/gameobjects/mesh/MeshFactory.js +++ b/src/gameobjects/mesh/MeshFactory.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Mesh = require('./Mesh'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Mesh Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#mesh - * @webglOnly - * @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 {number[]} vertices - An array containing the vertices data for this Mesh. - * @param {number[]} uv - An array containing the uv data for this Mesh. - * @param {number[]} colors - An array containing the color data for this Mesh. - * @param {number[]} alphas - An array containing the alpha data for this Mesh. - * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.Mesh} The Game Object that was created. - */ -if (typeof WEBGL_RENDERER) -{ - GameObjectFactory.register('mesh', function (x, y, vertices, uv, colors, alphas, texture, frame) - { - return this.displayList.add(new Mesh(this.scene, x, y, vertices, uv, colors, alphas, texture, frame)); - }); -} - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Mesh = require('./Mesh'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Mesh Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#mesh + * @webglOnly + * @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 {number[]} vertices - An array containing the vertices data for this Mesh. + * @param {number[]} uv - An array containing the uv data for this Mesh. + * @param {number[]} colors - An array containing the color data for this Mesh. + * @param {number[]} alphas - An array containing the alpha data for this Mesh. + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Mesh} The Game Object that was created. + */ +if (typeof WEBGL_RENDERER) +{ + GameObjectFactory.register('mesh', function (x, y, vertices, uv, colors, alphas, texture, frame) + { + return this.displayList.add(new Mesh(this.scene, x, y, vertices, uv, colors, alphas, texture, frame)); + }); +} + +// 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 diff --git a/src/gameobjects/mesh/MeshRender.js b/src/gameobjects/mesh/MeshRender.js index de2a7c04c..994eb85b4 100644 --- a/src/gameobjects/mesh/MeshRender.js +++ b/src/gameobjects/mesh/MeshRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./MeshWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./MeshCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./MeshWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./MeshCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/mesh/MeshWebGLRenderer.js b/src/gameobjects/mesh/MeshWebGLRenderer.js index 7c374633d..52c8e6731 100644 --- a/src/gameobjects/mesh/MeshWebGLRenderer.js +++ b/src/gameobjects/mesh/MeshWebGLRenderer.js @@ -1,112 +1,112 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Mesh#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Mesh} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var MeshWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - renderer.setPipeline(pipeline, src); - - var camMatrix = pipeline._tempMatrix1; - var spriteMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var frame = src.frame; - var texture = frame.glTexture; - - var vertices = src.vertices; - var uvs = src.uv; - var colors = src.colors; - var alphas = src.alphas; - - var meshVerticesLength = vertices.length; - var vertexCount = Math.floor(meshVerticesLength * 0.5); - - if (pipeline.vertexCount + vertexCount > pipeline.vertexCapacity) - { - pipeline.flush(); - } - - pipeline.setTexture2D(texture, 0); - - var vertexViewF32 = pipeline.vertexViewF32; - var vertexViewU32 = pipeline.vertexViewU32; - - var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; - - var colorIndex = 0; - var tintEffect = src.tintFill; - - for (var i = 0; i < meshVerticesLength; i += 2) - { - var x = vertices[i + 0]; - var y = vertices[i + 1]; - - var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; - var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; - - if (camera.roundPixels) - { - tx = Math.round(tx); - ty = Math.round(ty); - } - - vertexViewF32[++vertexOffset] = tx; - vertexViewF32[++vertexOffset] = ty; - vertexViewF32[++vertexOffset] = uvs[i + 0]; - vertexViewF32[++vertexOffset] = uvs[i + 1]; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = Utils.getTintAppendFloatAlpha(colors[colorIndex], camera.alpha * alphas[colorIndex]); - - colorIndex++; - } - - pipeline.vertexCount += vertexCount; -}; - -module.exports = MeshWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Mesh#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Mesh} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var MeshWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + + var vertices = src.vertices; + var uvs = src.uv; + var colors = src.colors; + var alphas = src.alphas; + + var meshVerticesLength = vertices.length; + var vertexCount = Math.floor(meshVerticesLength * 0.5); + + if (pipeline.vertexCount + vertexCount > pipeline.vertexCapacity) + { + pipeline.flush(); + } + + pipeline.setTexture2D(texture, 0); + + var vertexViewF32 = pipeline.vertexViewF32; + var vertexViewU32 = pipeline.vertexViewU32; + + var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; + + var colorIndex = 0; + var tintEffect = src.tintFill; + + for (var i = 0; i < meshVerticesLength; i += 2) + { + var x = vertices[i + 0]; + var y = vertices[i + 1]; + + var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; + var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; + + if (camera.roundPixels) + { + tx = Math.round(tx); + ty = Math.round(ty); + } + + vertexViewF32[++vertexOffset] = tx; + vertexViewF32[++vertexOffset] = ty; + vertexViewF32[++vertexOffset] = uvs[i + 0]; + vertexViewF32[++vertexOffset] = uvs[i + 1]; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = Utils.getTintAppendFloatAlpha(colors[colorIndex], camera.alpha * alphas[colorIndex]); + + colorIndex++; + } + + pipeline.vertexCount += vertexCount; +}; + +module.exports = MeshWebGLRenderer; diff --git a/src/gameobjects/particles/EmitterOp.js b/src/gameobjects/particles/EmitterOp.js index 64d217831..19f726d8b 100644 --- a/src/gameobjects/particles/EmitterOp.js +++ b/src/gameobjects/particles/EmitterOp.js @@ -1,585 +1,585 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FloatBetween = require('../../math/FloatBetween'); -var GetEaseFunction = require('../../tweens/builders/GetEaseFunction'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Wrap = require('../../math/Wrap'); - -/** - * @classdesc - * A Particle Emitter property. - * - * Facilitates changing Particle properties as they are emitted and throughout their lifetime. - * - * @class EmitterOp - * @memberof Phaser.GameObjects.Particles - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for the Particle Emitter that owns this property. - * @param {string} key - The name of the property. - * @param {number} defaultValue - The default value of the property. - * @param {boolean} [emitOnly=false] - Whether the property can only be modified when a Particle is emitted. - */ -var EmitterOp = new Class({ - - initialize: - - function EmitterOp (config, key, defaultValue, emitOnly) - { - if (emitOnly === undefined) - { - emitOnly = false; - } - - /** - * The name of this property. - * - * @name Phaser.GameObjects.Particles.EmitterOp#propertyKey - * @type {string} - * @since 3.0.0 - */ - this.propertyKey = key; - - /** - * The value of this property. - * - * @name Phaser.GameObjects.Particles.EmitterOp#propertyValue - * @type {number} - * @since 3.0.0 - */ - this.propertyValue = defaultValue; - - /** - * The default value of this property. - * - * @name Phaser.GameObjects.Particles.EmitterOp#defaultValue - * @type {number} - * @since 3.0.0 - */ - this.defaultValue = defaultValue; - - /** - * The number of steps for stepped easing between {@link Phaser.GameObjects.Particles.EmitterOp#start} and - * {@link Phaser.GameObjects.Particles.EmitterOp#end} values, per emit. - * - * @name Phaser.GameObjects.Particles.EmitterOp#steps - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.steps = 0; - - /** - * The step counter for stepped easing, per emit. - * - * @name Phaser.GameObjects.Particles.EmitterOp#counter - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.counter = 0; - - /** - * The start value for this property to ease between. - * - * @name Phaser.GameObjects.Particles.EmitterOp#start - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.start = 0; - - /** - * The end value for this property to ease between. - * - * @name Phaser.GameObjects.Particles.EmitterOp#end - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.end = 0; - - /** - * The easing function to use for updating this property. - * - * @name Phaser.GameObjects.Particles.EmitterOp#ease - * @type {?function} - * @since 3.0.0 - */ - this.ease; - - /** - * Whether this property can only be modified when a Particle is emitted. - * - * Set to `true` to allow only {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} callbacks to be set and - * affect this property. - * - * Set to `false` to allow both {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and - * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks to be set and affect this property. - * - * @name Phaser.GameObjects.Particles.EmitterOp#emitOnly - * @type {boolean} - * @since 3.0.0 - */ - this.emitOnly = emitOnly; - - /** - * The callback to run for Particles when they are emitted from the Particle Emitter. - * - * @name Phaser.GameObjects.Particles.EmitterOp#onEmit - * @type {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback} - * @since 3.0.0 - */ - this.onEmit = this.defaultEmit; - - /** - * The callback to run for Particles when they are updated. - * - * @name Phaser.GameObjects.Particles.EmitterOp#onUpdate - * @type {Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback} - * @since 3.0.0 - */ - this.onUpdate = this.defaultUpdate; - - this.loadConfig(config); - }, - - /** - * Load the property from a Particle Emitter configuration object. - * - * Optionally accepts a new property key to use, replacing the current one. - * - * @method Phaser.GameObjects.Particles.EmitterOp#loadConfig - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} [config] - Settings for the Particle Emitter that owns this property. - * @param {string} [newKey] - The new key to use for this property, if any. - */ - loadConfig: function (config, newKey) - { - if (config === undefined) - { - config = {}; - } - - if (newKey) - { - this.propertyKey = newKey; - } - - this.propertyValue = GetFastValue( - config, - this.propertyKey, - this.defaultValue - ); - - this.setMethods(); - - if (this.emitOnly) - { - // Reset it back again - this.onUpdate = this.defaultUpdate; - } - }, - - /** - * Build a JSON representation of this Particle Emitter property. - * - * @method Phaser.GameObjects.Particles.EmitterOp#toJSON - * @since 3.0.0 - * - * @return {object} A JSON representation of this Particle Emitter property. - */ - toJSON: function () - { - return this.propertyValue; - }, - - /** - * Change the current value of the property and update its callback methods. - * - * @method Phaser.GameObjects.Particles.EmitterOp#onChange - * @since 3.0.0 - * - * @param {number} value - The value of the property. - * - * @return {this} This Emitter Op object. - */ - onChange: function (value) - { - this.propertyValue = value; - - return this.setMethods(); - }, - - /** - * Update the {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and - * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks based on the type of the current - * {@link Phaser.GameObjects.Particles.EmitterOp#propertyValue}. - * - * @method Phaser.GameObjects.Particles.EmitterOp#setMethods - * @since 3.0.0 - * - * @return {this} This Emitter Op object. - */ - setMethods: function () - { - var value = this.propertyValue; - - var t = typeof value; - - if (t === 'number') - { - // Explicit static value: - // x: 400 - - this.onEmit = this.staticValueEmit; - this.onUpdate = this.staticValueUpdate; // How? - } - else if (Array.isArray(value)) - { - // Picks a random element from the array: - // x: [ 100, 200, 300, 400 ] - - this.onEmit = this.randomStaticValueEmit; - } - else if (t === 'function') - { - // The same as setting just the onUpdate function and no onEmit (unless this op is an emitOnly one) - // Custom callback, must return a value: - - /* - x: function (particle, key, t, value) - { - return value + 50; - } - */ - - if (this.emitOnly) - { - this.onEmit = value; - } - else - { - this.onUpdate = value; - } - } - else if (t === 'object' && (this.has(value, 'random') || this.hasBoth(value, 'start', 'end') || this.hasBoth(value, 'min', 'max'))) - { - this.start = this.has(value, 'start') ? value.start : value.min; - this.end = this.has(value, 'end') ? value.end : value.max; - - var isRandom = (this.hasBoth(value, 'min', 'max') || !!value.random); - - // A random starting value (using 'min | max' instead of 'start | end' automatically implies a random value) - - // x: { start: 100, end: 400, random: true } OR { min: 100, max: 400 } OR { random: [ 100, 400 ] } - - if (isRandom) - { - var rnd = value.random; - - // x: { random: [ 100, 400 ] } = the same as doing: x: { start: 100, end: 400, random: true } - if (Array.isArray(rnd)) - { - this.start = rnd[0]; - this.end = rnd[1]; - } - - this.onEmit = this.randomRangedValueEmit; - } - - if (this.has(value, 'steps')) - { - // A stepped (per emit) range - - // x: { start: 100, end: 400, steps: 64 } - - // Increments a value stored in the emitter - - this.steps = value.steps; - this.counter = this.start; - - this.onEmit = this.steppedEmit; - } - else - { - // An eased range (defaults to Linear if not specified) - - // x: { start: 100, end: 400, [ ease: 'Linear' ] } - - var easeType = this.has(value, 'ease') ? value.ease : 'Linear'; - - this.ease = GetEaseFunction(easeType); - - if (!isRandom) - { - this.onEmit = this.easedValueEmit; - } - - // BUG: alpha, rotate, scaleX, scaleY, or tint are eased here if {min, max} is given. - // Probably this branch should exclude isRandom entirely. - - this.onUpdate = this.easeValueUpdate; - } - } - else if (t === 'object' && this.hasEither(value, 'onEmit', 'onUpdate')) - { - // Custom onEmit and onUpdate callbacks - - /* - x: { - // Called at the start of the particles life, when it is being created - onEmit: function (particle, key, t, value) - { - return value; - }, - - // Called during the particles life on each update - onUpdate: function (particle, key, t, value) - { - return value; - } - } - */ - - if (this.has(value, 'onEmit')) - { - this.onEmit = value.onEmit; - } - - if (this.has(value, 'onUpdate')) - { - this.onUpdate = value.onUpdate; - } - } - - return this; - }, - - /** - * Check whether an object has the given property. - * - * @method Phaser.GameObjects.Particles.EmitterOp#has - * @since 3.0.0 - * - * @param {object} object - The object to check. - * @param {string} key - The key of the property to look for in the object. - * - * @return {boolean} `true` if the property exists in the object, `false` otherwise. - */ - has: function (object, key) - { - return object.hasOwnProperty(key); - }, - - /** - * Check whether an object has both of the given properties. - * - * @method Phaser.GameObjects.Particles.EmitterOp#hasBoth - * @since 3.0.0 - * - * @param {object} object - The object to check. - * @param {string} key1 - The key of the first property to check the object for. - * @param {string} key2 - The key of the second property to check the object for. - * - * @return {boolean} `true` if both properties exist in the object, `false` otherwise. - */ - hasBoth: function (object, key1, key2) - { - return object.hasOwnProperty(key1) && object.hasOwnProperty(key2); - }, - - /** - * Check whether an object has at least one of the given properties. - * - * @method Phaser.GameObjects.Particles.EmitterOp#hasEither - * @since 3.0.0 - * - * @param {object} object - The object to check. - * @param {string} key1 - The key of the first property to check the object for. - * @param {string} key2 - The key of the second property to check the object for. - * - * @return {boolean} `true` if at least one of the properties exists in the object, `false` if neither exist. - */ - hasEither: function (object, key1, key2) - { - return object.hasOwnProperty(key1) || object.hasOwnProperty(key2); - }, - - /** - * The returned value sets what the property will be at the START of the particles life, on emit. - * - * @method Phaser.GameObjects.Particles.EmitterOp#defaultEmit - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. - * @param {string} key - The name of the property. - * @param {number} [value] - The current value of the property. - * - * @return {number} The new value of the property. - */ - defaultEmit: function (particle, key, value) - { - return value; - }, - - /** - * The returned value updates the property for the duration of the particles life. - * - * @method Phaser.GameObjects.Particles.EmitterOp#defaultUpdate - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. - * @param {string} key - The name of the property. - * @param {number} t - The T value (between 0 and 1) - * @param {number} value - The current value of the property. - * - * @return {number} The new value of the property. - */ - defaultUpdate: function (particle, key, t, value) - { - return value; - }, - - /** - * An `onEmit` callback that returns the current value of the property. - * - * @method Phaser.GameObjects.Particles.EmitterOp#staticValueEmit - * @since 3.0.0 - * - * @return {number} The current value of the property. - */ - staticValueEmit: function () - { - return this.propertyValue; - }, - - /** - * An `onUpdate` callback that returns the current value of the property. - * - * @method Phaser.GameObjects.Particles.EmitterOp#staticValueUpdate - * @since 3.0.0 - * - * @return {number} The current value of the property. - */ - staticValueUpdate: function () - { - return this.propertyValue; - }, - - /** - * An `onEmit` callback that returns a random value from the current value array. - * - * @method Phaser.GameObjects.Particles.EmitterOp#randomStaticValueEmit - * @since 3.0.0 - * - * @return {number} The new value of the property. - */ - randomStaticValueEmit: function () - { - var randomIndex = Math.floor(Math.random() * this.propertyValue.length); - - return this.propertyValue[randomIndex]; - }, - - /** - * An `onEmit` callback that returns a value between the {@link Phaser.GameObjects.Particles.EmitterOp#start} and - * {@link Phaser.GameObjects.Particles.EmitterOp#end} range. - * - * @method Phaser.GameObjects.Particles.EmitterOp#randomRangedValueEmit - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. - * @param {string} key - The key of the property. - * - * @return {number} The new value of the property. - */ - randomRangedValueEmit: function (particle, key) - { - var value = FloatBetween(this.start, this.end); - - if (particle && particle.data[key]) - { - particle.data[key].min = value; - } - - return value; - }, - - /** - * An `onEmit` callback that returns a stepped value between the - * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} - * range. - * - * @method Phaser.GameObjects.Particles.EmitterOp#steppedEmit - * @since 3.0.0 - * - * @return {number} The new value of the property. - */ - steppedEmit: function () - { - var current = this.counter; - - var next = this.counter + (this.end - this.start) / this.steps; - - this.counter = Wrap(next, this.start, this.end); - - return current; - }, - - /** - * An `onEmit` callback for an eased property. - * - * It prepares the particle for easing by {@link Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate}. - * - * @method Phaser.GameObjects.Particles.EmitterOp#easedValueEmit - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. - * @param {string} key - The name of the property. - * - * @return {number} {@link Phaser.GameObjects.Particles.EmitterOp#start}, as the new value of the property. - */ - easedValueEmit: function (particle, key) - { - if (particle && particle.data[key]) - { - var data = particle.data[key]; - - data.min = this.start; - data.max = this.end; - } - - return this.start; - }, - - /** - * An `onUpdate` callback that returns an eased value between the - * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} - * range. - * - * @method Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. - * @param {string} key - The name of the property. - * @param {number} t - The T value (between 0 and 1) - * - * @return {number} The new value of the property. - */ - easeValueUpdate: function (particle, key, t) - { - var data = particle.data[key]; - - return (data.max - data.min) * this.ease(t) + data.min; - } -}); - -module.exports = EmitterOp; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FloatBetween = require('../../math/FloatBetween'); +var GetEaseFunction = require('../../tweens/builders/GetEaseFunction'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Wrap = require('../../math/Wrap'); + +/** + * @classdesc + * A Particle Emitter property. + * + * Facilitates changing Particle properties as they are emitted and throughout their lifetime. + * + * @class EmitterOp + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for the Particle Emitter that owns this property. + * @param {string} key - The name of the property. + * @param {number} defaultValue - The default value of the property. + * @param {boolean} [emitOnly=false] - Whether the property can only be modified when a Particle is emitted. + */ +var EmitterOp = new Class({ + + initialize: + + function EmitterOp (config, key, defaultValue, emitOnly) + { + if (emitOnly === undefined) + { + emitOnly = false; + } + + /** + * The name of this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#propertyKey + * @type {string} + * @since 3.0.0 + */ + this.propertyKey = key; + + /** + * The value of this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#propertyValue + * @type {number} + * @since 3.0.0 + */ + this.propertyValue = defaultValue; + + /** + * The default value of this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#defaultValue + * @type {number} + * @since 3.0.0 + */ + this.defaultValue = defaultValue; + + /** + * The number of steps for stepped easing between {@link Phaser.GameObjects.Particles.EmitterOp#start} and + * {@link Phaser.GameObjects.Particles.EmitterOp#end} values, per emit. + * + * @name Phaser.GameObjects.Particles.EmitterOp#steps + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.steps = 0; + + /** + * The step counter for stepped easing, per emit. + * + * @name Phaser.GameObjects.Particles.EmitterOp#counter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.counter = 0; + + /** + * The start value for this property to ease between. + * + * @name Phaser.GameObjects.Particles.EmitterOp#start + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.start = 0; + + /** + * The end value for this property to ease between. + * + * @name Phaser.GameObjects.Particles.EmitterOp#end + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.end = 0; + + /** + * The easing function to use for updating this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#ease + * @type {?function} + * @since 3.0.0 + */ + this.ease; + + /** + * Whether this property can only be modified when a Particle is emitted. + * + * Set to `true` to allow only {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} callbacks to be set and + * affect this property. + * + * Set to `false` to allow both {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and + * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks to be set and affect this property. + * + * @name Phaser.GameObjects.Particles.EmitterOp#emitOnly + * @type {boolean} + * @since 3.0.0 + */ + this.emitOnly = emitOnly; + + /** + * The callback to run for Particles when they are emitted from the Particle Emitter. + * + * @name Phaser.GameObjects.Particles.EmitterOp#onEmit + * @type {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback} + * @since 3.0.0 + */ + this.onEmit = this.defaultEmit; + + /** + * The callback to run for Particles when they are updated. + * + * @name Phaser.GameObjects.Particles.EmitterOp#onUpdate + * @type {Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback} + * @since 3.0.0 + */ + this.onUpdate = this.defaultUpdate; + + this.loadConfig(config); + }, + + /** + * Load the property from a Particle Emitter configuration object. + * + * Optionally accepts a new property key to use, replacing the current one. + * + * @method Phaser.GameObjects.Particles.EmitterOp#loadConfig + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} [config] - Settings for the Particle Emitter that owns this property. + * @param {string} [newKey] - The new key to use for this property, if any. + */ + loadConfig: function (config, newKey) + { + if (config === undefined) + { + config = {}; + } + + if (newKey) + { + this.propertyKey = newKey; + } + + this.propertyValue = GetFastValue( + config, + this.propertyKey, + this.defaultValue + ); + + this.setMethods(); + + if (this.emitOnly) + { + // Reset it back again + this.onUpdate = this.defaultUpdate; + } + }, + + /** + * Build a JSON representation of this Particle Emitter property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#toJSON + * @since 3.0.0 + * + * @return {object} A JSON representation of this Particle Emitter property. + */ + toJSON: function () + { + return this.propertyValue; + }, + + /** + * Change the current value of the property and update its callback methods. + * + * @method Phaser.GameObjects.Particles.EmitterOp#onChange + * @since 3.0.0 + * + * @param {number} value - The value of the property. + * + * @return {this} This Emitter Op object. + */ + onChange: function (value) + { + this.propertyValue = value; + + return this.setMethods(); + }, + + /** + * Update the {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and + * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks based on the type of the current + * {@link Phaser.GameObjects.Particles.EmitterOp#propertyValue}. + * + * @method Phaser.GameObjects.Particles.EmitterOp#setMethods + * @since 3.0.0 + * + * @return {this} This Emitter Op object. + */ + setMethods: function () + { + var value = this.propertyValue; + + var t = typeof value; + + if (t === 'number') + { + // Explicit static value: + // x: 400 + + this.onEmit = this.staticValueEmit; + this.onUpdate = this.staticValueUpdate; // How? + } + else if (Array.isArray(value)) + { + // Picks a random element from the array: + // x: [ 100, 200, 300, 400 ] + + this.onEmit = this.randomStaticValueEmit; + } + else if (t === 'function') + { + // The same as setting just the onUpdate function and no onEmit (unless this op is an emitOnly one) + // Custom callback, must return a value: + + /* + x: function (particle, key, t, value) + { + return value + 50; + } + */ + + if (this.emitOnly) + { + this.onEmit = value; + } + else + { + this.onUpdate = value; + } + } + else if (t === 'object' && (this.has(value, 'random') || this.hasBoth(value, 'start', 'end') || this.hasBoth(value, 'min', 'max'))) + { + this.start = this.has(value, 'start') ? value.start : value.min; + this.end = this.has(value, 'end') ? value.end : value.max; + + var isRandom = (this.hasBoth(value, 'min', 'max') || !!value.random); + + // A random starting value (using 'min | max' instead of 'start | end' automatically implies a random value) + + // x: { start: 100, end: 400, random: true } OR { min: 100, max: 400 } OR { random: [ 100, 400 ] } + + if (isRandom) + { + var rnd = value.random; + + // x: { random: [ 100, 400 ] } = the same as doing: x: { start: 100, end: 400, random: true } + if (Array.isArray(rnd)) + { + this.start = rnd[0]; + this.end = rnd[1]; + } + + this.onEmit = this.randomRangedValueEmit; + } + + if (this.has(value, 'steps')) + { + // A stepped (per emit) range + + // x: { start: 100, end: 400, steps: 64 } + + // Increments a value stored in the emitter + + this.steps = value.steps; + this.counter = this.start; + + this.onEmit = this.steppedEmit; + } + else + { + // An eased range (defaults to Linear if not specified) + + // x: { start: 100, end: 400, [ ease: 'Linear' ] } + + var easeType = this.has(value, 'ease') ? value.ease : 'Linear'; + + this.ease = GetEaseFunction(easeType); + + if (!isRandom) + { + this.onEmit = this.easedValueEmit; + } + + // BUG: alpha, rotate, scaleX, scaleY, or tint are eased here if {min, max} is given. + // Probably this branch should exclude isRandom entirely. + + this.onUpdate = this.easeValueUpdate; + } + } + else if (t === 'object' && this.hasEither(value, 'onEmit', 'onUpdate')) + { + // Custom onEmit and onUpdate callbacks + + /* + x: { + // Called at the start of the particles life, when it is being created + onEmit: function (particle, key, t, value) + { + return value; + }, + + // Called during the particles life on each update + onUpdate: function (particle, key, t, value) + { + return value; + } + } + */ + + if (this.has(value, 'onEmit')) + { + this.onEmit = value.onEmit; + } + + if (this.has(value, 'onUpdate')) + { + this.onUpdate = value.onUpdate; + } + } + + return this; + }, + + /** + * Check whether an object has the given property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#has + * @since 3.0.0 + * + * @param {object} object - The object to check. + * @param {string} key - The key of the property to look for in the object. + * + * @return {boolean} `true` if the property exists in the object, `false` otherwise. + */ + has: function (object, key) + { + return object.hasOwnProperty(key); + }, + + /** + * Check whether an object has both of the given properties. + * + * @method Phaser.GameObjects.Particles.EmitterOp#hasBoth + * @since 3.0.0 + * + * @param {object} object - The object to check. + * @param {string} key1 - The key of the first property to check the object for. + * @param {string} key2 - The key of the second property to check the object for. + * + * @return {boolean} `true` if both properties exist in the object, `false` otherwise. + */ + hasBoth: function (object, key1, key2) + { + return object.hasOwnProperty(key1) && object.hasOwnProperty(key2); + }, + + /** + * Check whether an object has at least one of the given properties. + * + * @method Phaser.GameObjects.Particles.EmitterOp#hasEither + * @since 3.0.0 + * + * @param {object} object - The object to check. + * @param {string} key1 - The key of the first property to check the object for. + * @param {string} key2 - The key of the second property to check the object for. + * + * @return {boolean} `true` if at least one of the properties exists in the object, `false` if neither exist. + */ + hasEither: function (object, key1, key2) + { + return object.hasOwnProperty(key1) || object.hasOwnProperty(key2); + }, + + /** + * The returned value sets what the property will be at the START of the particles life, on emit. + * + * @method Phaser.GameObjects.Particles.EmitterOp#defaultEmit + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * @param {number} [value] - The current value of the property. + * + * @return {number} The new value of the property. + */ + defaultEmit: function (particle, key, value) + { + return value; + }, + + /** + * The returned value updates the property for the duration of the particles life. + * + * @method Phaser.GameObjects.Particles.EmitterOp#defaultUpdate + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * @param {number} t - The T value (between 0 and 1) + * @param {number} value - The current value of the property. + * + * @return {number} The new value of the property. + */ + defaultUpdate: function (particle, key, t, value) + { + return value; + }, + + /** + * An `onEmit` callback that returns the current value of the property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#staticValueEmit + * @since 3.0.0 + * + * @return {number} The current value of the property. + */ + staticValueEmit: function () + { + return this.propertyValue; + }, + + /** + * An `onUpdate` callback that returns the current value of the property. + * + * @method Phaser.GameObjects.Particles.EmitterOp#staticValueUpdate + * @since 3.0.0 + * + * @return {number} The current value of the property. + */ + staticValueUpdate: function () + { + return this.propertyValue; + }, + + /** + * An `onEmit` callback that returns a random value from the current value array. + * + * @method Phaser.GameObjects.Particles.EmitterOp#randomStaticValueEmit + * @since 3.0.0 + * + * @return {number} The new value of the property. + */ + randomStaticValueEmit: function () + { + var randomIndex = Math.floor(Math.random() * this.propertyValue.length); + + return this.propertyValue[randomIndex]; + }, + + /** + * An `onEmit` callback that returns a value between the {@link Phaser.GameObjects.Particles.EmitterOp#start} and + * {@link Phaser.GameObjects.Particles.EmitterOp#end} range. + * + * @method Phaser.GameObjects.Particles.EmitterOp#randomRangedValueEmit + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The key of the property. + * + * @return {number} The new value of the property. + */ + randomRangedValueEmit: function (particle, key) + { + var value = FloatBetween(this.start, this.end); + + if (particle && particle.data[key]) + { + particle.data[key].min = value; + } + + return value; + }, + + /** + * An `onEmit` callback that returns a stepped value between the + * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} + * range. + * + * @method Phaser.GameObjects.Particles.EmitterOp#steppedEmit + * @since 3.0.0 + * + * @return {number} The new value of the property. + */ + steppedEmit: function () + { + var current = this.counter; + + var next = this.counter + (this.end - this.start) / this.steps; + + this.counter = Wrap(next, this.start, this.end); + + return current; + }, + + /** + * An `onEmit` callback for an eased property. + * + * It prepares the particle for easing by {@link Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate}. + * + * @method Phaser.GameObjects.Particles.EmitterOp#easedValueEmit + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * + * @return {number} {@link Phaser.GameObjects.Particles.EmitterOp#start}, as the new value of the property. + */ + easedValueEmit: function (particle, key) + { + if (particle && particle.data[key]) + { + var data = particle.data[key]; + + data.min = this.start; + data.max = this.end; + } + + return this.start; + }, + + /** + * An `onUpdate` callback that returns an eased value between the + * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} + * range. + * + * @method Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The particle. + * @param {string} key - The name of the property. + * @param {number} t - The T value (between 0 and 1) + * + * @return {number} The new value of the property. + */ + easeValueUpdate: function (particle, key, t) + { + var data = particle.data[key]; + + return (data.max - data.min) * this.ease(t) + data.min; + } +}); + +module.exports = EmitterOp; diff --git a/src/gameobjects/particles/GravityWell.js b/src/gameobjects/particles/GravityWell.js index 6b69fbc15..6861963de 100644 --- a/src/gameobjects/particles/GravityWell.js +++ b/src/gameobjects/particles/GravityWell.js @@ -1,213 +1,213 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * @classdesc - * The GravityWell action applies a force on the particle to draw it towards, or repel it from, a single point. - * - * The force applied is inversely proportional to the square of the distance from the particle to the point, in accordance with Newton's law of gravity. - * - * This simulates the effect of gravity over large distances (as between planets, for example). - * - * @class GravityWell - * @memberof Phaser.GameObjects.Particles - * @constructor - * @since 3.0.0 - * - * @param {(number|Phaser.Types.GameObjects.Particles.GravityWellConfig)} [x=0] - The x coordinate of the Gravity Well, in world space. - * @param {number} [y=0] - The y coordinate of the Gravity Well, in world space. - * @param {number} [power=0] - The strength of the gravity force - larger numbers produce a stronger force. - * @param {number} [epsilon=100] - The minimum distance for which the gravity force is calculated. - * @param {number} [gravity=50] - The gravitational force of this Gravity Well. - */ -var GravityWell = new Class({ - - initialize: - - function GravityWell (x, y, power, epsilon, gravity) - { - if (typeof x === 'object') - { - var config = x; - - x = GetFastValue(config, 'x', 0); - y = GetFastValue(config, 'y', 0); - power = GetFastValue(config, 'power', 0); - epsilon = GetFastValue(config, 'epsilon', 100); - gravity = GetFastValue(config, 'gravity', 50); - } - else - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (power === undefined) { power = 0; } - if (epsilon === undefined) { epsilon = 100; } - if (gravity === undefined) { gravity = 50; } - } - - /** - * The x coordinate of the Gravity Well, in world space. - * - * @name Phaser.GameObjects.Particles.GravityWell#x - * @type {number} - * @since 3.0.0 - */ - this.x = x; - - /** - * The y coordinate of the Gravity Well, in world space. - * - * @name Phaser.GameObjects.Particles.GravityWell#y - * @type {number} - * @since 3.0.0 - */ - this.y = y; - - /** - * The active state of the Gravity Well. An inactive Gravity Well will not influence any particles. - * - * @name Phaser.GameObjects.Particles.GravityWell#active - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.active = true; - - /** - * Internal gravity value. - * - * @name Phaser.GameObjects.Particles.GravityWell#_gravity - * @type {number} - * @private - * @since 3.0.0 - */ - this._gravity = gravity; - - /** - * Internal power value. - * - * @name Phaser.GameObjects.Particles.GravityWell#_power - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._power = 0; - - /** - * Internal epsilon value. - * - * @name Phaser.GameObjects.Particles.GravityWell#_epsilon - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._epsilon = 0; - - /** - * The strength of the gravity force - larger numbers produce a stronger force. - * - * @name Phaser.GameObjects.Particles.GravityWell#power - * @type {number} - * @since 3.0.0 - */ - this.power = power; - - /** - * The minimum distance for which the gravity force is calculated. - * - * @name Phaser.GameObjects.Particles.GravityWell#epsilon - * @type {number} - * @since 3.0.0 - */ - this.epsilon = epsilon; - }, - - /** - * Takes a Particle and updates it based on the properties of this Gravity Well. - * - * @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. - */ - update: function (particle, delta) - { - var x = this.x - particle.x; - var y = this.y - particle.y; - var dSq = x * x + y * y; - - if (dSq === 0) - { - return; - } - - var d = Math.sqrt(dSq); - - if (dSq < this._epsilon) - { - dSq = this._epsilon; - } - - var factor = ((this._power * delta) / (dSq * d)) * 100; - - particle.velocityX += x * factor; - particle.velocityY += y * factor; - }, - - epsilon: { - - get: function () - { - return Math.sqrt(this._epsilon); - }, - - set: function (value) - { - this._epsilon = value * value; - } - - }, - - power: { - - get: function () - { - return this._power / this._gravity; - }, - - set: function (value) - { - this._power = value * this._gravity; - } - - }, - - gravity: { - - get: function () - { - return this._gravity; - }, - - set: function (value) - { - var pwr = this.power; - this._gravity = value; - this.power = pwr; - } - - } - -}); - -module.exports = GravityWell; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * @classdesc + * The GravityWell action applies a force on the particle to draw it towards, or repel it from, a single point. + * + * The force applied is inversely proportional to the square of the distance from the particle to the point, in accordance with Newton's law of gravity. + * + * This simulates the effect of gravity over large distances (as between planets, for example). + * + * @class GravityWell + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @param {(number|Phaser.Types.GameObjects.Particles.GravityWellConfig)} [x=0] - The x coordinate of the Gravity Well, in world space. + * @param {number} [y=0] - The y coordinate of the Gravity Well, in world space. + * @param {number} [power=0] - The strength of the gravity force - larger numbers produce a stronger force. + * @param {number} [epsilon=100] - The minimum distance for which the gravity force is calculated. + * @param {number} [gravity=50] - The gravitational force of this Gravity Well. + */ +var GravityWell = new Class({ + + initialize: + + function GravityWell (x, y, power, epsilon, gravity) + { + if (typeof x === 'object') + { + var config = x; + + x = GetFastValue(config, 'x', 0); + y = GetFastValue(config, 'y', 0); + power = GetFastValue(config, 'power', 0); + epsilon = GetFastValue(config, 'epsilon', 100); + gravity = GetFastValue(config, 'gravity', 50); + } + else + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (power === undefined) { power = 0; } + if (epsilon === undefined) { epsilon = 100; } + if (gravity === undefined) { gravity = 50; } + } + + /** + * The x coordinate of the Gravity Well, in world space. + * + * @name Phaser.GameObjects.Particles.GravityWell#x + * @type {number} + * @since 3.0.0 + */ + this.x = x; + + /** + * The y coordinate of the Gravity Well, in world space. + * + * @name Phaser.GameObjects.Particles.GravityWell#y + * @type {number} + * @since 3.0.0 + */ + this.y = y; + + /** + * The active state of the Gravity Well. An inactive Gravity Well will not influence any particles. + * + * @name Phaser.GameObjects.Particles.GravityWell#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * Internal gravity value. + * + * @name Phaser.GameObjects.Particles.GravityWell#_gravity + * @type {number} + * @private + * @since 3.0.0 + */ + this._gravity = gravity; + + /** + * Internal power value. + * + * @name Phaser.GameObjects.Particles.GravityWell#_power + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._power = 0; + + /** + * Internal epsilon value. + * + * @name Phaser.GameObjects.Particles.GravityWell#_epsilon + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._epsilon = 0; + + /** + * The strength of the gravity force - larger numbers produce a stronger force. + * + * @name Phaser.GameObjects.Particles.GravityWell#power + * @type {number} + * @since 3.0.0 + */ + this.power = power; + + /** + * The minimum distance for which the gravity force is calculated. + * + * @name Phaser.GameObjects.Particles.GravityWell#epsilon + * @type {number} + * @since 3.0.0 + */ + this.epsilon = epsilon; + }, + + /** + * Takes a Particle and updates it based on the properties of this Gravity Well. + * + * @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. + */ + update: function (particle, delta) + { + var x = this.x - particle.x; + var y = this.y - particle.y; + var dSq = x * x + y * y; + + if (dSq === 0) + { + return; + } + + var d = Math.sqrt(dSq); + + if (dSq < this._epsilon) + { + dSq = this._epsilon; + } + + var factor = ((this._power * delta) / (dSq * d)) * 100; + + particle.velocityX += x * factor; + particle.velocityY += y * factor; + }, + + epsilon: { + + get: function () + { + return Math.sqrt(this._epsilon); + }, + + set: function (value) + { + this._epsilon = value * value; + } + + }, + + power: { + + get: function () + { + return this._power / this._gravity; + }, + + set: function (value) + { + this._power = value * this._gravity; + } + + }, + + gravity: { + + get: function () + { + return this._gravity; + }, + + set: function (value) + { + var pwr = this.power; + this._gravity = value; + this.power = pwr; + } + + } + +}); + +module.exports = GravityWell; diff --git a/src/gameobjects/particles/Particle.js b/src/gameobjects/particles/Particle.js index 0ba4dd268..f0862e047 100644 --- a/src/gameobjects/particles/Particle.js +++ b/src/gameobjects/particles/Particle.js @@ -1,563 +1,563 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var DegToRad = require('../../math/DegToRad'); -var DistanceBetween = require('../../math/distance/DistanceBetween'); - -/** - * @classdesc - * A Particle is a simple Game Object controlled by a Particle Emitter and Manager, and rendered by the Manager. - * It uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. - * - * @class Particle - * @memberof Phaser.GameObjects.Particles - * @constructor - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter to which this Particle belongs. - */ -var Particle = new Class({ - - initialize: - - function Particle (emitter) - { - /** - * The Emitter to which this Particle belongs. - * - * A Particle can only belong to a single Emitter and is created, updated and destroyed via it. - * - * @name Phaser.GameObjects.Particles.Particle#emitter - * @type {Phaser.GameObjects.Particles.ParticleEmitter} - * @since 3.0.0 - */ - this.emitter = emitter; - - /** - * The texture frame used to render this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#frame - * @type {Phaser.Textures.Frame} - * @default null - * @since 3.0.0 - */ - this.frame = null; - - /** - * The x coordinate of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = 0; - - /** - * The y coordinate of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = 0; - - /** - * The x velocity of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#velocityX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.velocityX = 0; - - /** - * The y velocity of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#velocityY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.velocityY = 0; - - /** - * The x acceleration of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#accelerationX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accelerationX = 0; - - /** - * The y acceleration of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#accelerationY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.accelerationY = 0; - - /** - * The maximum horizontal velocity this Particle can travel at. - * - * @name Phaser.GameObjects.Particles.Particle#maxVelocityX - * @type {number} - * @default 10000 - * @since 3.0.0 - */ - this.maxVelocityX = 10000; - - /** - * The maximum vertical velocity this Particle can travel at. - * - * @name Phaser.GameObjects.Particles.Particle#maxVelocityY - * @type {number} - * @default 10000 - * @since 3.0.0 - */ - this.maxVelocityY = 10000; - - /** - * The bounciness, or restitution, of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#bounce - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.bounce = 0; - - /** - * The horizontal scale of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#scaleX - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.scaleX = 1; - - /** - * The vertical scale of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#scaleY - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.scaleY = 1; - - /** - * The alpha value of this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#alpha - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.alpha = 1; - - /** - * The angle of this Particle in degrees. - * - * @name Phaser.GameObjects.Particles.Particle#angle - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.angle = 0; - - /** - * The angle of this Particle in radians. - * - * @name Phaser.GameObjects.Particles.Particle#rotation - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.rotation = 0; - - /** - * The tint applied to this Particle. - * - * @name Phaser.GameObjects.Particles.Particle#tint - * @type {integer} - * @webglOnly - * @since 3.0.0 - */ - this.tint = 0xffffff; - - /** - * The lifespan of this Particle in ms. - * - * @name Phaser.GameObjects.Particles.Particle#life - * @type {number} - * @default 1000 - * @since 3.0.0 - */ - this.life = 1000; - - /** - * The current life of this Particle in ms. - * - * @name Phaser.GameObjects.Particles.Particle#lifeCurrent - * @type {number} - * @default 1000 - * @since 3.0.0 - */ - this.lifeCurrent = 1000; - - /** - * The delay applied to this Particle upon emission, in ms. - * - * @name Phaser.GameObjects.Particles.Particle#delayCurrent - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.delayCurrent = 0; - - /** - * The normalized lifespan T value, where 0 is the start and 1 is the end. - * - * @name Phaser.GameObjects.Particles.Particle#lifeT - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.lifeT = 0; - - /** - * The data used by the ease equation. - * - * @name Phaser.GameObjects.Particles.Particle#data - * @type {object} - * @since 3.0.0 - */ - this.data = { - tint: { min: 0xffffff, max: 0xffffff, current: 0xffffff }, - alpha: { min: 1, max: 1 }, - rotate: { min: 0, max: 0 }, - scaleX: { min: 1, max: 1 }, - scaleY: { min: 1, max: 1 } - }; - }, - - /** - * Checks to see if this Particle is alive and updating. - * - * @method Phaser.GameObjects.Particles.Particle#isAlive - * @since 3.0.0 - * - * @return {boolean} `true` if this Particle is alive and updating, otherwise `false`. - */ - isAlive: function () - { - return (this.lifeCurrent > 0); - }, - - /** - * Resets the position of this particle back to zero. - * - * @method Phaser.GameObjects.Particles.Particle#resetPosition - * @since 3.16.0 - */ - resetPosition: function () - { - this.x = 0; - this.y = 0; - }, - - /** - * Starts this Particle from the given coordinates. - * - * @method Phaser.GameObjects.Particles.Particle#fire - * @since 3.0.0 - * - * @param {number} x - The x coordinate to launch this Particle from. - * @param {number} y - The y coordinate to launch this Particle from. - */ - fire: function (x, y) - { - var emitter = this.emitter; - - this.frame = emitter.getFrame(); - - if (emitter.emitZone) - { - // Updates particle.x and particle.y during this call - emitter.emitZone.getPoint(this); - } - - if (x === undefined) - { - if (emitter.follow) - { - this.x += emitter.follow.x + emitter.followOffset.x; - } - - this.x += emitter.x.onEmit(this, 'x'); - } - else - { - this.x += x; - } - - if (y === undefined) - { - if (emitter.follow) - { - this.y += emitter.follow.y + emitter.followOffset.y; - } - - this.y += emitter.y.onEmit(this, 'y'); - } - else - { - this.y += y; - } - - this.life = emitter.lifespan.onEmit(this, 'lifespan'); - this.lifeCurrent = this.life; - this.lifeT = 0; - - var sx = emitter.speedX.onEmit(this, 'speedX'); - var sy = (emitter.speedY) ? emitter.speedY.onEmit(this, 'speedY') : sx; - - if (emitter.radial) - { - var rad = DegToRad(emitter.angle.onEmit(this, 'angle')); - - this.velocityX = Math.cos(rad) * Math.abs(sx); - this.velocityY = Math.sin(rad) * Math.abs(sy); - } - else if (emitter.moveTo) - { - var mx = emitter.moveToX.onEmit(this, 'moveToX'); - var my = (emitter.moveToY) ? emitter.moveToY.onEmit(this, 'moveToY') : mx; - - var angle = Math.atan2(my - this.y, mx - this.x); - - var speed = DistanceBetween(this.x, this.y, mx, my) / (this.life / 1000); - - // We know how many pixels we need to move, but how fast? - // var speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); - - this.velocityX = Math.cos(angle) * speed; - this.velocityY = Math.sin(angle) * speed; - } - else - { - this.velocityX = sx; - this.velocityY = sy; - } - - if (emitter.acceleration) - { - this.accelerationX = emitter.accelerationX.onEmit(this, 'accelerationX'); - this.accelerationY = emitter.accelerationY.onEmit(this, 'accelerationY'); - } - - this.maxVelocityX = emitter.maxVelocityX.onEmit(this, 'maxVelocityX'); - this.maxVelocityY = emitter.maxVelocityY.onEmit(this, 'maxVelocityY'); - - this.delayCurrent = emitter.delay.onEmit(this, 'delay'); - - this.scaleX = emitter.scaleX.onEmit(this, 'scaleX'); - this.scaleY = (emitter.scaleY) ? emitter.scaleY.onEmit(this, 'scaleY') : this.scaleX; - - this.angle = emitter.rotate.onEmit(this, 'rotate'); - this.rotation = DegToRad(this.angle); - - this.bounce = emitter.bounce.onEmit(this, 'bounce'); - - this.alpha = emitter.alpha.onEmit(this, 'alpha'); - - this.tint = emitter.tint.onEmit(this, 'tint'); - }, - - /** - * An internal method that calculates the velocity of the Particle. - * - * @method Phaser.GameObjects.Particles.Particle#computeVelocity - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter that is updating this Particle. - * @param {number} delta - The delta time in ms. - * @param {number} step - The delta value divided by 1000. - * @param {array} processors - Particle processors (gravity wells). - */ - computeVelocity: function (emitter, delta, step, processors) - { - var vx = this.velocityX; - var vy = this.velocityY; - - var ax = this.accelerationX; - var ay = this.accelerationY; - - var mx = this.maxVelocityX; - var my = this.maxVelocityY; - - vx += (emitter.gravityX * step); - vy += (emitter.gravityY * step); - - if (ax) - { - vx += (ax * step); - } - - if (ay) - { - vy += (ay * step); - } - - if (vx > mx) - { - vx = mx; - } - else if (vx < -mx) - { - vx = -mx; - } - - if (vy > my) - { - vy = my; - } - else if (vy < -my) - { - vy = -my; - } - - this.velocityX = vx; - this.velocityY = vy; - - // Apply any additional processors - for (var i = 0; i < processors.length; i++) - { - processors[i].update(this, delta, step); - } - }, - - /** - * Checks if this Particle is still within the bounds defined by the given Emitter. - * - * If not, and depending on the Emitter collision flags, the Particle may either stop or rebound. - * - * @method Phaser.GameObjects.Particles.Particle#checkBounds - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter to check the bounds against. - */ - checkBounds: function (emitter) - { - var bounds = emitter.bounds; - var bounce = -this.bounce; - - if (this.x < bounds.x && emitter.collideLeft) - { - this.x = bounds.x; - this.velocityX *= bounce; - } - else if (this.x > bounds.right && emitter.collideRight) - { - this.x = bounds.right; - this.velocityX *= bounce; - } - - if (this.y < bounds.y && emitter.collideTop) - { - this.y = bounds.y; - this.velocityY *= bounce; - } - else if (this.y > bounds.bottom && emitter.collideBottom) - { - this.y = bounds.bottom; - this.velocityY *= bounce; - } - }, - - /** - * The main update method for this Particle. - * - * Updates its life values, computes the velocity and repositions the Particle. - * - * @method Phaser.GameObjects.Particles.Particle#update - * @since 3.0.0 - * - * @param {number} delta - The delta time in ms. - * @param {number} step - The delta value divided by 1000. - * @param {array} processors - An optional array of update processors. - * - * @return {boolean} Returns `true` if this Particle has now expired and should be removed, otherwise `false` if still active. - */ - update: function (delta, step, processors) - { - if (this.delayCurrent > 0) - { - this.delayCurrent -= delta; - - return false; - } - - var emitter = this.emitter; - - // How far along in life is this particle? (t = 0 to 1) - var t = 1 - (this.lifeCurrent / this.life); - - this.lifeT = t; - - this.computeVelocity(emitter, delta, step, processors); - - this.x += this.velocityX * step; - this.y += this.velocityY * step; - - if (emitter.bounds) - { - this.checkBounds(emitter); - } - - if (emitter.deathZone && emitter.deathZone.willKill(this)) - { - this.lifeCurrent = 0; - - // No need to go any further, particle has been killed - return true; - } - - this.scaleX = emitter.scaleX.onUpdate(this, 'scaleX', t, this.scaleX); - - if (emitter.scaleY) - { - this.scaleY = emitter.scaleY.onUpdate(this, 'scaleY', t, this.scaleY); - } - else - { - this.scaleY = this.scaleX; - } - - this.angle = emitter.rotate.onUpdate(this, 'rotate', t, this.angle); - this.rotation = DegToRad(this.angle); - - this.alpha = emitter.alpha.onUpdate(this, 'alpha', t, this.alpha); - - this.tint = emitter.tint.onUpdate(this, 'tint', t, this.tint); - - this.lifeCurrent -= delta; - - return (this.lifeCurrent <= 0); - } - -}); - -module.exports = Particle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var DegToRad = require('../../math/DegToRad'); +var DistanceBetween = require('../../math/distance/DistanceBetween'); + +/** + * @classdesc + * A Particle is a simple Game Object controlled by a Particle Emitter and Manager, and rendered by the Manager. + * It uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. + * + * @class Particle + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter to which this Particle belongs. + */ +var Particle = new Class({ + + initialize: + + function Particle (emitter) + { + /** + * The Emitter to which this Particle belongs. + * + * A Particle can only belong to a single Emitter and is created, updated and destroyed via it. + * + * @name Phaser.GameObjects.Particles.Particle#emitter + * @type {Phaser.GameObjects.Particles.ParticleEmitter} + * @since 3.0.0 + */ + this.emitter = emitter; + + /** + * The texture frame used to render this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#frame + * @type {Phaser.Textures.Frame} + * @default null + * @since 3.0.0 + */ + this.frame = null; + + /** + * The x coordinate of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y coordinate of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The x velocity of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#velocityX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.velocityX = 0; + + /** + * The y velocity of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#velocityY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.velocityY = 0; + + /** + * The x acceleration of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#accelerationX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelerationX = 0; + + /** + * The y acceleration of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#accelerationY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.accelerationY = 0; + + /** + * The maximum horizontal velocity this Particle can travel at. + * + * @name Phaser.GameObjects.Particles.Particle#maxVelocityX + * @type {number} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityX = 10000; + + /** + * The maximum vertical velocity this Particle can travel at. + * + * @name Phaser.GameObjects.Particles.Particle#maxVelocityY + * @type {number} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityY = 10000; + + /** + * The bounciness, or restitution, of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#bounce + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.bounce = 0; + + /** + * The horizontal scale of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#scaleX + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.scaleX = 1; + + /** + * The vertical scale of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#scaleY + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.scaleY = 1; + + /** + * The alpha value of this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#alpha + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.alpha = 1; + + /** + * The angle of this Particle in degrees. + * + * @name Phaser.GameObjects.Particles.Particle#angle + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angle = 0; + + /** + * The angle of this Particle in radians. + * + * @name Phaser.GameObjects.Particles.Particle#rotation + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.rotation = 0; + + /** + * The tint applied to this Particle. + * + * @name Phaser.GameObjects.Particles.Particle#tint + * @type {integer} + * @webglOnly + * @since 3.0.0 + */ + this.tint = 0xffffff; + + /** + * The lifespan of this Particle in ms. + * + * @name Phaser.GameObjects.Particles.Particle#life + * @type {number} + * @default 1000 + * @since 3.0.0 + */ + this.life = 1000; + + /** + * The current life of this Particle in ms. + * + * @name Phaser.GameObjects.Particles.Particle#lifeCurrent + * @type {number} + * @default 1000 + * @since 3.0.0 + */ + this.lifeCurrent = 1000; + + /** + * The delay applied to this Particle upon emission, in ms. + * + * @name Phaser.GameObjects.Particles.Particle#delayCurrent + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.delayCurrent = 0; + + /** + * The normalized lifespan T value, where 0 is the start and 1 is the end. + * + * @name Phaser.GameObjects.Particles.Particle#lifeT + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.lifeT = 0; + + /** + * The data used by the ease equation. + * + * @name Phaser.GameObjects.Particles.Particle#data + * @type {object} + * @since 3.0.0 + */ + this.data = { + tint: { min: 0xffffff, max: 0xffffff, current: 0xffffff }, + alpha: { min: 1, max: 1 }, + rotate: { min: 0, max: 0 }, + scaleX: { min: 1, max: 1 }, + scaleY: { min: 1, max: 1 } + }; + }, + + /** + * Checks to see if this Particle is alive and updating. + * + * @method Phaser.GameObjects.Particles.Particle#isAlive + * @since 3.0.0 + * + * @return {boolean} `true` if this Particle is alive and updating, otherwise `false`. + */ + isAlive: function () + { + return (this.lifeCurrent > 0); + }, + + /** + * Resets the position of this particle back to zero. + * + * @method Phaser.GameObjects.Particles.Particle#resetPosition + * @since 3.16.0 + */ + resetPosition: function () + { + this.x = 0; + this.y = 0; + }, + + /** + * Starts this Particle from the given coordinates. + * + * @method Phaser.GameObjects.Particles.Particle#fire + * @since 3.0.0 + * + * @param {number} x - The x coordinate to launch this Particle from. + * @param {number} y - The y coordinate to launch this Particle from. + */ + fire: function (x, y) + { + var emitter = this.emitter; + + this.frame = emitter.getFrame(); + + if (emitter.emitZone) + { + // Updates particle.x and particle.y during this call + emitter.emitZone.getPoint(this); + } + + if (x === undefined) + { + if (emitter.follow) + { + this.x += emitter.follow.x + emitter.followOffset.x; + } + + this.x += emitter.x.onEmit(this, 'x'); + } + else + { + this.x += x; + } + + if (y === undefined) + { + if (emitter.follow) + { + this.y += emitter.follow.y + emitter.followOffset.y; + } + + this.y += emitter.y.onEmit(this, 'y'); + } + else + { + this.y += y; + } + + this.life = emitter.lifespan.onEmit(this, 'lifespan'); + this.lifeCurrent = this.life; + this.lifeT = 0; + + var sx = emitter.speedX.onEmit(this, 'speedX'); + var sy = (emitter.speedY) ? emitter.speedY.onEmit(this, 'speedY') : sx; + + if (emitter.radial) + { + var rad = DegToRad(emitter.angle.onEmit(this, 'angle')); + + this.velocityX = Math.cos(rad) * Math.abs(sx); + this.velocityY = Math.sin(rad) * Math.abs(sy); + } + else if (emitter.moveTo) + { + var mx = emitter.moveToX.onEmit(this, 'moveToX'); + var my = (emitter.moveToY) ? emitter.moveToY.onEmit(this, 'moveToY') : mx; + + var angle = Math.atan2(my - this.y, mx - this.x); + + var speed = DistanceBetween(this.x, this.y, mx, my) / (this.life / 1000); + + // We know how many pixels we need to move, but how fast? + // var speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + + this.velocityX = Math.cos(angle) * speed; + this.velocityY = Math.sin(angle) * speed; + } + else + { + this.velocityX = sx; + this.velocityY = sy; + } + + if (emitter.acceleration) + { + this.accelerationX = emitter.accelerationX.onEmit(this, 'accelerationX'); + this.accelerationY = emitter.accelerationY.onEmit(this, 'accelerationY'); + } + + this.maxVelocityX = emitter.maxVelocityX.onEmit(this, 'maxVelocityX'); + this.maxVelocityY = emitter.maxVelocityY.onEmit(this, 'maxVelocityY'); + + this.delayCurrent = emitter.delay.onEmit(this, 'delay'); + + this.scaleX = emitter.scaleX.onEmit(this, 'scaleX'); + this.scaleY = (emitter.scaleY) ? emitter.scaleY.onEmit(this, 'scaleY') : this.scaleX; + + this.angle = emitter.rotate.onEmit(this, 'rotate'); + this.rotation = DegToRad(this.angle); + + this.bounce = emitter.bounce.onEmit(this, 'bounce'); + + this.alpha = emitter.alpha.onEmit(this, 'alpha'); + + this.tint = emitter.tint.onEmit(this, 'tint'); + }, + + /** + * An internal method that calculates the velocity of the Particle. + * + * @method Phaser.GameObjects.Particles.Particle#computeVelocity + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter that is updating this Particle. + * @param {number} delta - The delta time in ms. + * @param {number} step - The delta value divided by 1000. + * @param {array} processors - Particle processors (gravity wells). + */ + computeVelocity: function (emitter, delta, step, processors) + { + var vx = this.velocityX; + var vy = this.velocityY; + + var ax = this.accelerationX; + var ay = this.accelerationY; + + var mx = this.maxVelocityX; + var my = this.maxVelocityY; + + vx += (emitter.gravityX * step); + vy += (emitter.gravityY * step); + + if (ax) + { + vx += (ax * step); + } + + if (ay) + { + vy += (ay * step); + } + + if (vx > mx) + { + vx = mx; + } + else if (vx < -mx) + { + vx = -mx; + } + + if (vy > my) + { + vy = my; + } + else if (vy < -my) + { + vy = -my; + } + + this.velocityX = vx; + this.velocityY = vy; + + // Apply any additional processors + for (var i = 0; i < processors.length; i++) + { + processors[i].update(this, delta, step); + } + }, + + /** + * Checks if this Particle is still within the bounds defined by the given Emitter. + * + * If not, and depending on the Emitter collision flags, the Particle may either stop or rebound. + * + * @method Phaser.GameObjects.Particles.Particle#checkBounds + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Emitter to check the bounds against. + */ + checkBounds: function (emitter) + { + var bounds = emitter.bounds; + var bounce = -this.bounce; + + if (this.x < bounds.x && emitter.collideLeft) + { + this.x = bounds.x; + this.velocityX *= bounce; + } + else if (this.x > bounds.right && emitter.collideRight) + { + this.x = bounds.right; + this.velocityX *= bounce; + } + + if (this.y < bounds.y && emitter.collideTop) + { + this.y = bounds.y; + this.velocityY *= bounce; + } + else if (this.y > bounds.bottom && emitter.collideBottom) + { + this.y = bounds.bottom; + this.velocityY *= bounce; + } + }, + + /** + * The main update method for this Particle. + * + * Updates its life values, computes the velocity and repositions the Particle. + * + * @method Phaser.GameObjects.Particles.Particle#update + * @since 3.0.0 + * + * @param {number} delta - The delta time in ms. + * @param {number} step - The delta value divided by 1000. + * @param {array} processors - An optional array of update processors. + * + * @return {boolean} Returns `true` if this Particle has now expired and should be removed, otherwise `false` if still active. + */ + update: function (delta, step, processors) + { + if (this.delayCurrent > 0) + { + this.delayCurrent -= delta; + + return false; + } + + var emitter = this.emitter; + + // How far along in life is this particle? (t = 0 to 1) + var t = 1 - (this.lifeCurrent / this.life); + + this.lifeT = t; + + this.computeVelocity(emitter, delta, step, processors); + + this.x += this.velocityX * step; + this.y += this.velocityY * step; + + if (emitter.bounds) + { + this.checkBounds(emitter); + } + + if (emitter.deathZone && emitter.deathZone.willKill(this)) + { + this.lifeCurrent = 0; + + // No need to go any further, particle has been killed + return true; + } + + this.scaleX = emitter.scaleX.onUpdate(this, 'scaleX', t, this.scaleX); + + if (emitter.scaleY) + { + this.scaleY = emitter.scaleY.onUpdate(this, 'scaleY', t, this.scaleY); + } + else + { + this.scaleY = this.scaleX; + } + + this.angle = emitter.rotate.onUpdate(this, 'rotate', t, this.angle); + this.rotation = DegToRad(this.angle); + + this.alpha = emitter.alpha.onUpdate(this, 'alpha', t, this.alpha); + + this.tint = emitter.tint.onUpdate(this, 'tint', t, this.tint); + + this.lifeCurrent -= delta; + + return (this.lifeCurrent <= 0); + } + +}); + +module.exports = Particle; diff --git a/src/gameobjects/particles/ParticleEmitter.js b/src/gameobjects/particles/ParticleEmitter.js index d346474a3..247012422 100644 --- a/src/gameobjects/particles/ParticleEmitter.js +++ b/src/gameobjects/particles/ParticleEmitter.js @@ -1,2065 +1,2065 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BlendModes = require('../../renderer/BlendModes'); -var Class = require('../../utils/Class'); -var Components = require('../components'); -var DeathZone = require('./zones/DeathZone'); -var EdgeZone = require('./zones/EdgeZone'); -var EmitterOp = require('./EmitterOp'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetRandom = require('../../utils/array/GetRandom'); -var HasAny = require('../../utils/object/HasAny'); -var HasValue = require('../../utils/object/HasValue'); -var Particle = require('./Particle'); -var RandomZone = require('./zones/RandomZone'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var StableSort = require('../../utils/array/StableSort'); -var Vector2 = require('../../math/Vector2'); -var Wrap = require('../../math/Wrap'); - -/** - * @classdesc - * A particle emitter represents a single particle stream. - * It controls a pool of {@link Phaser.GameObjects.Particles.Particle Particles} and is controlled by a {@link Phaser.GameObjects.Particles.ParticleEmitterManager Particle Emitter Manager}. - * - * @class ParticleEmitter - * @memberof Phaser.GameObjects.Particles - * @constructor - * @since 3.0.0 - * - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} manager - The Emitter Manager this Emitter belongs to. - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. - */ -var ParticleEmitter = new Class({ - - Mixins: [ - Components.BlendMode, - Components.Mask, - Components.ScrollFactor, - Components.Visible - ], - - initialize: - - function ParticleEmitter (manager, config) - { - /** - * The Emitter Manager this Emitter belongs to. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#manager - * @type {Phaser.GameObjects.Particles.ParticleEmitterManager} - * @since 3.0.0 - */ - this.manager = manager; - - /** - * The texture assigned to particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#texture - * @type {Phaser.Textures.Texture} - * @since 3.0.0 - */ - this.texture = manager.texture; - - /** - * The texture frames assigned to particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#frames - * @type {Phaser.Textures.Frame[]} - * @since 3.0.0 - */ - this.frames = [ manager.defaultFrame ]; - - /** - * The default texture frame assigned to particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#defaultFrame - * @type {Phaser.Textures.Frame} - * @since 3.0.0 - */ - this.defaultFrame = manager.defaultFrame; - - /** - * Names of simple configuration properties. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#configFastMap - * @type {object} - * @since 3.0.0 - */ - this.configFastMap = [ - 'active', - 'blendMode', - 'collideBottom', - 'collideLeft', - 'collideRight', - 'collideTop', - 'deathCallback', - 'deathCallbackScope', - 'emitCallback', - 'emitCallbackScope', - 'follow', - 'frequency', - 'gravityX', - 'gravityY', - 'maxParticles', - 'name', - 'on', - 'particleBringToTop', - 'particleClass', - 'radial', - 'timeScale', - 'trackVisible', - 'visible' - ]; - - /** - * Names of complex configuration properties. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#configOpMap - * @type {object} - * @since 3.0.0 - */ - this.configOpMap = [ - 'accelerationX', - 'accelerationY', - 'angle', - 'alpha', - 'bounce', - 'delay', - 'lifespan', - 'maxVelocityX', - 'maxVelocityY', - 'moveToX', - 'moveToY', - 'quantity', - 'rotate', - 'scaleX', - 'scaleY', - 'speedX', - 'speedY', - 'tint', - 'x', - 'y' - ]; - - /** - * The name of this Particle Emitter. - * - * Empty by default and never populated by Phaser, this is left for developers to use. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#name - * @type {string} - * @default '' - * @since 3.0.0 - */ - this.name = ''; - - /** - * The Particle Class which will be emitted by this Emitter. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#particleClass - * @type {Phaser.GameObjects.Particles.Particle} - * @default Phaser.GameObjects.Particles.Particle - * @since 3.0.0 - */ - this.particleClass = Particle; - - /** - * The x-coordinate of the particle origin (where particles will be emitted). - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#x - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition - */ - this.x = new EmitterOp(config, 'x', 0, true); - - /** - * The y-coordinate of the particle origin (where particles will be emitted). - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#y - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition - */ - this.y = new EmitterOp(config, 'y', 0, true); - - /** - * A radial emitter will emit particles in all directions between angle min and max, - * using {@link Phaser.GameObjects.Particles.ParticleEmitter#speed} as the value. If set to false then this acts as a point Emitter. - * A point emitter will emit particles only in the direction derived from the speedX and speedY values. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#radial - * @type {boolean} - * @default true - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setRadial - */ - this.radial = true; - - /** - * Horizontal acceleration applied to emitted particles, in pixels per second squared. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#gravityX - * @type {number} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity - */ - this.gravityX = 0; - - /** - * Vertical acceleration applied to emitted particles, in pixels per second squared. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#gravityY - * @type {number} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity - */ - this.gravityY = 0; - - /** - * Whether accelerationX and accelerationY are non-zero. Set automatically during configuration. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#acceleration - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.acceleration = false; - - /** - * Horizontal acceleration applied to emitted particles, in pixels per second squared. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationX - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.accelerationX = new EmitterOp(config, 'accelerationX', 0, true); - - /** - * Vertical acceleration applied to emitted particles, in pixels per second squared. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationY - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.accelerationY = new EmitterOp(config, 'accelerationY', 0, true); - - /** - * The maximum horizontal velocity of emitted particles, in pixels per second squared. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityX - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 10000 - * @since 3.0.0 - */ - this.maxVelocityX = new EmitterOp(config, 'maxVelocityX', 10000, true); - - /** - * The maximum vertical velocity of emitted particles, in pixels per second squared. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityY - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 10000 - * @since 3.0.0 - */ - this.maxVelocityY = new EmitterOp(config, 'maxVelocityY', 10000, true); - - /** - * The initial horizontal speed of emitted particles, in pixels per second. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#speedX - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX - */ - this.speedX = new EmitterOp(config, 'speedX', 0, true); - - /** - * The initial vertical speed of emitted particles, in pixels per second. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#speedY - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY - */ - this.speedY = new EmitterOp(config, 'speedY', 0, true); - - /** - * Whether moveToX and moveToY are nonzero. Set automatically during configuration. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#moveTo - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.moveTo = false; - - /** - * The x-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#moveToX - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.moveToX = new EmitterOp(config, 'moveToX', 0, true); - - /** - * The y-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#moveToY - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.moveToY = new EmitterOp(config, 'moveToY', 0, true); - - /** - * Whether particles will rebound when they meet the emitter bounds. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#bounce - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.bounce = new EmitterOp(config, 'bounce', 0, true); - - /** - * The horizontal scale of emitted particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#scaleX - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 1 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setScale - * @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleX - */ - this.scaleX = new EmitterOp(config, 'scaleX', 1); - - /** - * The vertical scale of emitted particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#scaleY - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 1 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setScale - * @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleY - */ - this.scaleY = new EmitterOp(config, 'scaleY', 1); - - /** - * Color tint applied to emitted particles. Any alpha component (0xAA000000) is ignored. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#tint - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0xffffffff - * @since 3.0.0 - */ - this.tint = new EmitterOp(config, 'tint', 0xffffffff); - - /** - * The alpha (transparency) of emitted particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#alpha - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 1 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setAlpha - */ - this.alpha = new EmitterOp(config, 'alpha', 1); - - /** - * The lifespan of emitted particles, in ms. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#lifespan - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 1000 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setLifespan - */ - this.lifespan = new EmitterOp(config, 'lifespan', 1000, true); - - /** - * The angle of the initial velocity of emitted particles, in degrees. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#angle - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default { min: 0, max: 360 } - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setAngle - */ - this.angle = new EmitterOp(config, 'angle', { min: 0, max: 360 }, true); - - /** - * The rotation of emitted particles, in degrees. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#rotate - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.rotate = new EmitterOp(config, 'rotate', 0); - - /** - * A function to call when a particle is emitted. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallback - * @type {?Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} - * @default null - * @since 3.0.0 - */ - this.emitCallback = null; - - /** - * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope - * @type {?*} - * @default null - * @since 3.0.0 - */ - this.emitCallbackScope = null; - - /** - * A function to call when a particle dies. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallback - * @type {?Phaser.Types.GameObjects.Particles.ParticleDeathCallback} - * @default null - * @since 3.0.0 - */ - this.deathCallback = null; - - /** - * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope - * @type {?*} - * @default null - * @since 3.0.0 - */ - this.deathCallbackScope = null; - - /** - * Set to hard limit the amount of particle objects this emitter is allowed to create. - * 0 means unlimited. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#maxParticles - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.maxParticles = 0; - - /** - * How many particles are emitted each time particles are emitted (one explosion or one flow cycle). - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#quantity - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 1 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency - * @see Phaser.GameObjects.Particles.ParticleEmitter#setQuantity - */ - this.quantity = new EmitterOp(config, 'quantity', 1, true); - - /** - * How many ms to wait after emission before the particles start updating. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#delay - * @type {Phaser.GameObjects.Particles.EmitterOp} - * @default 0 - * @since 3.0.0 - */ - this.delay = new EmitterOp(config, 'delay', 0, true); - - /** - * For a flow emitter, the time interval (>= 0) between particle flow cycles in ms. - * A value of 0 means there is one particle flow cycle for each logic update (the maximum flow frequency). This is the default setting. - * For an exploding emitter, this value will be -1. - * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} also puts the emitter in flow mode (frequency >= 0). - * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} also puts the emitter in explode mode (frequency = -1). - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#frequency - * @type {number} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency - */ - this.frequency = 0; - - /** - * Controls if the emitter is currently emitting a particle flow (when frequency >= 0). - * Already alive particles will continue to update until they expire. - * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#start} and {@link Phaser.GameObjects.Particles.ParticleEmitter#stop}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#on - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.on = true; - - /** - * Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. - * Set to false to send them to the back. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#particleBringToTop - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.particleBringToTop = true; - - /** - * The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * An object describing a shape to emit particles from. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#emitZone - * @type {?Phaser.GameObjects.Particles.Zones.EdgeZone|Phaser.GameObjects.Particles.Zones.RandomZone} - * @default null - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone - */ - this.emitZone = null; - - /** - * An object describing a shape that deactivates particles when they interact with it. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#deathZone - * @type {?Phaser.GameObjects.Particles.Zones.DeathZone} - * @default null - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone - */ - this.deathZone = null; - - /** - * A rectangular boundary constraining particle movement. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#bounds - * @type {?Phaser.Geom.Rectangle} - * @default null - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setBounds - */ - this.bounds = null; - - /** - * Whether particles interact with the left edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#collideLeft - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.collideLeft = true; - - /** - * Whether particles interact with the right edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#collideRight - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.collideRight = true; - - /** - * Whether particles interact with the top edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#collideTop - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.collideTop = true; - - /** - * Whether particles interact with the bottom edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#collideBottom - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.collideBottom = true; - - /** - * Whether this emitter updates itself and its particles. - * - * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#pause} - * and {@link Phaser.GameObjects.Particles.ParticleEmitter#resume}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#active - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.active = true; - - /** - * Set this to false to hide any active particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#visible - * @type {boolean} - * @default true - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setVisible - */ - this.visible = true; - - /** - * The blend mode of this emitter's particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#blendMode - * @type {integer} - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setBlendMode - */ - this.blendMode = BlendModes.NORMAL; - - /** - * A Game Object whose position is used as the particle origin. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#follow - * @type {?Phaser.GameObjects.GameObject} - * @default null - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow - * @see Phaser.GameObjects.Particles.ParticleEmitter#stopFollow - */ - this.follow = null; - - /** - * The offset of the particle origin from the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#followOffset - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow - */ - this.followOffset = new Vector2(); - - /** - * Whether the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#visible} state will track - * the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target's visibility state. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#trackVisible - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow - */ - this.trackVisible = false; - - /** - * The current texture frame, as an index of {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#currentFrame - * @type {integer} - * @default 0 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame - */ - this.currentFrame = 0; - - /** - * Whether texture {@link Phaser.GameObjects.Particles.ParticleEmitter#frames} are selected at random. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#randomFrame - * @type {boolean} - * @default true - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame - */ - this.randomFrame = true; - - /** - * The number of consecutive particles that receive a single texture frame (per frame cycle). - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity - * @type {integer} - * @default 1 - * @since 3.0.0 - * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame - */ - this.frameQuantity = 1; - - /** - * Inactive particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#dead - * @type {Phaser.GameObjects.Particles.Particle[]} - * @private - * @since 3.0.0 - */ - this.dead = []; - - /** - * Active particles - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#alive - * @type {Phaser.GameObjects.Particles.Particle[]} - * @private - * @since 3.0.0 - */ - this.alive = []; - - /** - * The time until the next flow cycle. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#_counter - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._counter = 0; - - /** - * Counts up to {@link Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity}. - * - * @name Phaser.GameObjects.Particles.ParticleEmitter#_frameCounter - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - this._frameCounter = 0; - - if (config) - { - this.fromJSON(config); - } - }, - - /** - * Merges configuration settings into the emitter's current settings. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#fromJSON - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. - * - * @return {this} This Particle Emitter. - */ - fromJSON: function (config) - { - if (!config) - { - return this; - } - - // Only update properties from their current state if they exist in the given config - - var i = 0; - var key = ''; - - for (i = 0; i < this.configFastMap.length; i++) - { - key = this.configFastMap[i]; - - if (HasValue(config, key)) - { - this[key] = GetFastValue(config, key); - } - } - - for (i = 0; i < this.configOpMap.length; i++) - { - key = this.configOpMap[i]; - - if (HasValue(config, key)) - { - this[key].loadConfig(config); - } - } - - this.acceleration = (this.accelerationX.propertyValue !== 0 || this.accelerationY.propertyValue !== 0); - - this.moveTo = (this.moveToX.propertyValue !== 0 || this.moveToY.propertyValue !== 0); - - // Special 'speed' override - - if (HasValue(config, 'speed')) - { - this.speedX.loadConfig(config, 'speed'); - this.speedY = null; - } - - // If you specify speedX, speedY or moveTo then it changes the emitter from radial to a point emitter - if (HasAny(config, [ 'speedX', 'speedY' ]) || this.moveTo) - { - this.radial = false; - } - - // Special 'scale' override - - if (HasValue(config, 'scale')) - { - this.scaleX.loadConfig(config, 'scale'); - this.scaleY = null; - } - - if (HasValue(config, 'callbackScope')) - { - var callbackScope = GetFastValue(config, 'callbackScope', null); - - this.emitCallbackScope = callbackScope; - this.deathCallbackScope = callbackScope; - } - - if (HasValue(config, 'emitZone')) - { - this.setEmitZone(config.emitZone); - } - - if (HasValue(config, 'deathZone')) - { - this.setDeathZone(config.deathZone); - } - - if (HasValue(config, 'bounds')) - { - this.setBounds(config.bounds); - } - - if (HasValue(config, 'followOffset')) - { - this.followOffset.setFromObject(GetFastValue(config, 'followOffset', 0)); - } - - if (HasValue(config, 'frame')) - { - this.setFrame(config.frame); - } - - return this; - }, - - /** - * Creates a description of this emitter suitable for JSON serialization. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#toJSON - * @since 3.0.0 - * - * @param {object} [output] - An object to copy output into. - * - * @return {object} - The output object. - */ - toJSON: function (output) - { - if (output === undefined) { output = {}; } - - var i = 0; - var key = ''; - - for (i = 0; i < this.configFastMap.length; i++) - { - key = this.configFastMap[i]; - - output[key] = this[key]; - } - - for (i = 0; i < this.configOpMap.length; i++) - { - key = this.configOpMap[i]; - - if (this[key]) - { - output[key] = this[key].toJSON(); - } - } - - // special handlers - if (!this.speedY) - { - delete output.speedX; - output.speed = this.speedX.toJSON(); - } - - if (!this.scaleY) - { - delete output.scaleX; - output.scale = this.scaleX.toJSON(); - } - - return output; - }, - - /** - * Continuously moves the particle origin to follow a Game Object's position. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#startFollow - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} target - The Game Object to follow. - * @param {number} [offsetX=0] - Horizontal offset of the particle origin from the Game Object. - * @param {number} [offsetY=0] - Vertical offset of the particle origin from the Game Object. - * @param {boolean} [trackVisible=false] - Whether the emitter's visible state will track the target's visible state. - * - * @return {this} This Particle Emitter. - */ - startFollow: function (target, offsetX, offsetY, trackVisible) - { - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - if (trackVisible === undefined) { trackVisible = false; } - - this.follow = target; - this.followOffset.set(offsetX, offsetY); - this.trackVisible = trackVisible; - - return this; - }, - - /** - * Stops following a Game Object. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#stopFollow - * @since 3.0.0 - * - * @return {this} This Particle Emitter. - */ - stopFollow: function () - { - this.follow = null; - this.followOffset.set(0, 0); - this.trackVisible = false; - - return this; - }, - - /** - * Chooses a texture frame from {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#getFrame - * @since 3.0.0 - * - * @return {Phaser.Textures.Frame} The texture frame. - */ - getFrame: function () - { - if (this.frames.length === 1) - { - return this.defaultFrame; - } - else if (this.randomFrame) - { - return GetRandom(this.frames); - } - else - { - var frame = this.frames[this.currentFrame]; - - this._frameCounter++; - - if (this._frameCounter === this.frameQuantity) - { - this._frameCounter = 0; - this.currentFrame = Wrap(this.currentFrame + 1, 0, this._frameLength); - } - - return frame; - } - }, - - // frame: 0 - // frame: 'red' - // frame: [ 0, 1, 2, 3 ] - // frame: [ 'red', 'green', 'blue', 'pink', 'white' ] - // frame: { frames: [ 'red', 'green', 'blue', 'pink', 'white' ], [cycle: bool], [quantity: int] } - - /** - * Sets a pattern for assigning texture frames to emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setFrame - * @since 3.0.0 - * - * @param {(array|string|integer|Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig)} frames - One or more texture frames, or a configuration object. - * @param {boolean} [pickRandom=true] - Whether frames should be assigned at random from `frames`. - * @param {integer} [quantity=1] - The number of consecutive particles that will receive each frame. - * - * @return {this} This Particle Emitter. - */ - setFrame: function (frames, pickRandom, quantity) - { - if (pickRandom === undefined) { pickRandom = true; } - if (quantity === undefined) { quantity = 1; } - - this.randomFrame = pickRandom; - this.frameQuantity = quantity; - this.currentFrame = 0; - this._frameCounter = 0; - - var t = typeof (frames); - - if (Array.isArray(frames) || t === 'string' || t === 'number') - { - this.manager.setEmitterFrames(frames, this); - } - else if (t === 'object') - { - var frameConfig = frames; - - frames = GetFastValue(frameConfig, 'frames', null); - - if (frames) - { - this.manager.setEmitterFrames(frames, this); - } - - var isCycle = GetFastValue(frameConfig, 'cycle', false); - - this.randomFrame = (isCycle) ? false : true; - - this.frameQuantity = GetFastValue(frameConfig, 'quantity', quantity); - } - - this._frameLength = this.frames.length; - - if (this._frameLength === 1) - { - this.frameQuantity = 1; - this.randomFrame = false; - } - - return this; - }, - - /** - * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle movement on or off. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setRadial - * @since 3.0.0 - * - * @param {boolean} [value=true] - Radial mode (true) or point mode (true). - * - * @return {this} This Particle Emitter. - */ - setRadial: function (value) - { - if (value === undefined) { value = true; } - - this.radial = value; - - return this; - }, - - /** - * Sets the position of the emitter's particle origin. - * New particles will be emitted here. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setPosition - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} x - The x-coordinate of the particle origin. - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} y - The y-coordinate of the particle origin. - * - * @return {this} This Particle Emitter. - */ - setPosition: function (x, y) - { - this.x.onChange(x); - this.y.onChange(y); - - return this; - }, - - /** - * Sets or modifies a rectangular boundary constraining the particles. - * - * To remove the boundary, set {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds} to null. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setBounds - * @since 3.0.0 - * - * @param {(number|Phaser.Types.GameObjects.Particles.ParticleEmitterBounds|Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt)} x - The x-coordinate of the left edge of the boundary, or an object representing a rectangle. - * @param {number} y - The y-coordinate of the top edge of the boundary. - * @param {number} width - The width of the boundary. - * @param {number} height - The height of the boundary. - * - * @return {this} This Particle Emitter. - */ - setBounds: function (x, y, width, height) - { - if (typeof x === 'object') - { - var obj = x; - - x = obj.x; - y = obj.y; - width = (HasValue(obj, 'w')) ? obj.w : obj.width; - height = (HasValue(obj, 'h')) ? obj.h : obj.height; - } - - if (this.bounds) - { - this.bounds.setTo(x, y, width, height); - } - else - { - this.bounds = new Rectangle(x, y, width, height); - } - - return this; - }, - - /** - * Sets the initial horizontal speed of emitted particles. - * Changes the emitter to point mode. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. - * - * @return {this} This Particle Emitter. - */ - setSpeedX: function (value) - { - this.speedX.onChange(value); - - // If you specify speedX and Y then it changes the emitter from radial to a point emitter - this.radial = false; - - return this; - }, - - /** - * Sets the initial vertical speed of emitted particles. - * Changes the emitter to point mode. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. - * - * @return {this} This Particle Emitter. - */ - setSpeedY: function (value) - { - if (this.speedY) - { - this.speedY.onChange(value); - - // If you specify speedX and Y then it changes the emitter from radial to a point emitter - this.radial = false; - } - - return this; - }, - - /** - * Sets the initial radial speed of emitted particles. - * Changes the emitter to radial mode. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeed - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. - * - * @return {this} This Particle Emitter. - */ - setSpeed: function (value) - { - this.speedX.onChange(value); - this.speedY = null; - - // If you specify speedX and Y then it changes the emitter from radial to a point emitter - this.radial = true; - - return this; - }, - - /** - * Sets the horizontal scale of emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleX - * @since 3.0.0 - * - * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. - * - * @return {this} This Particle Emitter. - */ - setScaleX: function (value) - { - this.scaleX.onChange(value); - - return this; - }, - - /** - * Sets the vertical scale of emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleY - * @since 3.0.0 - * - * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. - * - * @return {this} This Particle Emitter. - */ - setScaleY: function (value) - { - this.scaleY.onChange(value); - - return this; - }, - - /** - * Sets the scale of emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setScale - * @since 3.0.0 - * - * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. - * - * @return {this} This Particle Emitter. - */ - setScale: function (value) - { - this.scaleX.onChange(value); - this.scaleY = null; - - return this; - }, - - /** - * Sets the horizontal gravity applied to emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityX - * @since 3.0.0 - * - * @param {number} value - Acceleration due to gravity, in pixels per second squared. - * - * @return {this} This Particle Emitter. - */ - setGravityX: function (value) - { - this.gravityX = value; - - return this; - }, - - /** - * Sets the vertical gravity applied to emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityY - * @since 3.0.0 - * - * @param {number} value - Acceleration due to gravity, in pixels per second squared. - * - * @return {this} This Particle Emitter. - */ - setGravityY: function (value) - { - this.gravityY = value; - - return this; - }, - - /** - * Sets the gravity applied to emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravity - * @since 3.0.0 - * - * @param {number} x - Horizontal acceleration due to gravity, in pixels per second squared. - * @param {number} y - Vertical acceleration due to gravity, in pixels per second squared. - * - * @return {this} This Particle Emitter. - */ - setGravity: function (x, y) - { - this.gravityX = x; - this.gravityY = y; - - return this; - }, - - /** - * Sets the opacity of emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setAlpha - * @since 3.0.0 - * - * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 (transparent) and 1 (opaque). - * - * @return {this} This Particle Emitter. - */ - setAlpha: function (value) - { - this.alpha.onChange(value); - - return this; - }, - - /** - * Sets the color tint of emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setTint - * @since 3.22.0 - * - * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 and 0xffffff. - * - * @return {this} This Particle Emitter. - */ - setTint: function (value) - { - this.tint.onChange(value); - - return this; - }, - - /** - * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitterAngle - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. - * - * @return {this} This Particle Emitter. - */ - setEmitterAngle: function (value) - { - this.angle.onChange(value); - - return this; - }, - - /** - * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setAngle - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. - * - * @return {this} This Particle Emitter. - */ - setAngle: function (value) - { - this.angle.onChange(value); - - return this; - }, - - /** - * Sets the lifespan of newly emitted particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setLifespan - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The particle lifespan, in ms. - * - * @return {this} This Particle Emitter. - */ - setLifespan: function (value) - { - this.lifespan.onChange(value); - - return this; - }, - - /** - * Sets the number of particles released at each flow cycle or explosion. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setQuantity - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} quantity - The number of particles to release at each flow cycle or explosion. - * - * @return {this} This Particle Emitter. - */ - setQuantity: function (quantity) - { - this.quantity.onChange(quantity); - - return this; - }, - - /** - * Sets the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency} - * and {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setFrequency - * @since 3.0.0 - * - * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [quantity] - The number of particles to release at each flow cycle or explosion. - * - * @return {this} This Particle Emitter. - */ - setFrequency: function (frequency, quantity) - { - this.frequency = frequency; - - this._counter = 0; - - if (quantity) - { - this.quantity.onChange(quantity); - } - - return this; - }, - - /** - * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#emitZone}. - * - * An {@link Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig EdgeZone} places particles on its edges. Its {@link Phaser.Types.GameObjects.Particles.EdgeZoneSource source} can be a Curve, Path, Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback getPoints} method. - * - * A {@link Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig RandomZone} places randomly within its interior. Its {@link RandomZoneSource source} can be a Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback getRandomPoint} method. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current emit zone. - * - * @return {this} This Particle Emitter. - */ - setEmitZone: function (zoneConfig) - { - if (zoneConfig === undefined) - { - this.emitZone = null; - } - else - { - // 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] } - - var type = GetFastValue(zoneConfig, 'type', 'random'); - var source = GetFastValue(zoneConfig, 'source', null); - - switch (type) - { - case 'random': - - this.emitZone = new RandomZone(source); - - break; - - case 'edge': - - var quantity = GetFastValue(zoneConfig, 'quantity', 1); - var stepRate = GetFastValue(zoneConfig, 'stepRate', 0); - var yoyo = GetFastValue(zoneConfig, 'yoyo', false); - var seamless = GetFastValue(zoneConfig, 'seamless', true); - - this.emitZone = new EdgeZone(source, quantity, stepRate, yoyo, seamless); - - break; - } - } - - return this; - }, - - /** - * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#deathZone}. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current death zone. - * - * @return {this} This Particle Emitter. - */ - setDeathZone: function (zoneConfig) - { - if (zoneConfig === undefined) - { - this.deathZone = null; - } - else - { - // Where source = Geom like Circle or Rect that supports a 'contains' function - // deathZone: { type: 'onEnter', source: X } - // deathZone: { type: 'onLeave', source: X } - - var type = GetFastValue(zoneConfig, 'type', 'onEnter'); - var source = GetFastValue(zoneConfig, 'source', null); - - if (source && typeof source.contains === 'function') - { - var killOnEnter = (type === 'onEnter') ? true : false; - - this.deathZone = new DeathZone(source, killOnEnter); - } - } - - return this; - }, - - /** - * Creates inactive particles and adds them to this emitter's pool. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#reserve - * @since 3.0.0 - * - * @param {integer} particleCount - The number of particles to create. - * - * @return {this} This Particle Emitter. - */ - reserve: function (particleCount) - { - var dead = this.dead; - - for (var i = 0; i < particleCount; i++) - { - dead.push(new this.particleClass(this)); - } - - return this; - }, - - /** - * Gets the number of active (in-use) particles in this emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#getAliveParticleCount - * @since 3.0.0 - * - * @return {integer} The number of particles with `active=true`. - */ - getAliveParticleCount: function () - { - return this.alive.length; - }, - - /** - * Gets the number of inactive (available) particles in this emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#getDeadParticleCount - * @since 3.0.0 - * - * @return {integer} The number of particles with `active=false`. - */ - getDeadParticleCount: function () - { - return this.dead.length; - }, - - /** - * Gets the total number of particles in this emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#getParticleCount - * @since 3.0.0 - * - * @return {integer} The number of particles, including both alive and dead. - */ - getParticleCount: function () - { - return this.getAliveParticleCount() + this.getDeadParticleCount(); - }, - - /** - * Whether this emitter is at its limit (if set). - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#atLimit - * @since 3.0.0 - * - * @return {boolean} Returns `true` if this Emitter is at its limit, or `false` if no limit, or below the `maxParticles` level. - */ - atLimit: function () - { - return (this.maxParticles > 0 && this.getParticleCount() === this.maxParticles); - }, - - /** - * Sets a function to call for each newly emitted particle. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleEmit - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. - * @param {*} [context] - The calling context. - * - * @return {this} This Particle Emitter. - */ - onParticleEmit: function (callback, context) - { - if (callback === undefined) - { - // Clear any previously set callback - this.emitCallback = null; - this.emitCallbackScope = null; - } - else if (typeof callback === 'function') - { - this.emitCallback = callback; - - if (context) - { - this.emitCallbackScope = context; - } - } - - return this; - }, - - /** - * Sets a function to call for each particle death. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleDeath - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleDeathCallback} callback - The function. - * @param {*} [context] - The function's calling context. - * - * @return {this} This Particle Emitter. - */ - onParticleDeath: function (callback, context) - { - if (callback === undefined) - { - // Clear any previously set callback - this.deathCallback = null; - this.deathCallbackScope = null; - } - else if (typeof callback === 'function') - { - this.deathCallback = callback; - - if (context) - { - this.deathCallbackScope = context; - } - } - - return this; - }, - - /** - * Deactivates every particle in this emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#killAll - * @since 3.0.0 - * - * @return {this} This Particle Emitter. - */ - killAll: function () - { - var dead = this.dead; - var alive = this.alive; - - while (alive.length > 0) - { - dead.push(alive.pop()); - } - - return this; - }, - - /** - * Calls a function for each active particle in this emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#forEachAlive - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. - * @param {*} context - The function's calling context. - * - * @return {this} This Particle Emitter. - */ - forEachAlive: function (callback, context) - { - var alive = this.alive; - var length = alive.length; - - for (var index = 0; index < length; ++index) - { - // Sends the Particle and the Emitter - callback.call(context, alive[index], this); - } - - return this; - }, - - /** - * Calls a function for each inactive particle in this emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#forEachDead - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. - * @param {*} context - The function's calling context. - * - * @return {this} This Particle Emitter. - */ - forEachDead: function (callback, context) - { - var dead = this.dead; - var length = dead.length; - - for (var index = 0; index < length; ++index) - { - // Sends the Particle and the Emitter - callback.call(context, dead[index], this); - } - - return this; - }, - - /** - * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on} the emitter and resets the flow counter. - * - * If this emitter is in flow mode (frequency >= 0; the default), the particle flow will start (or restart). - * - * If this emitter is in explode mode (frequency = -1), nothing will happen. - * Use {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} or {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} instead. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#start - * @since 3.0.0 - * - * @return {this} This Particle Emitter. - */ - start: function () - { - this.on = true; - - this._counter = 0; - - return this; - }, - - /** - * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on off} the emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#stop - * @since 3.11.0 - * - * @return {this} This Particle Emitter. - */ - stop: function () - { - this.on = false; - - return this; - }, - - /** - * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Deactivates} the emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#pause - * @since 3.0.0 - * - * @return {this} This Particle Emitter. - */ - pause: function () - { - this.active = false; - - return this; - }, - - /** - * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Activates} the emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#resume - * @since 3.0.0 - * - * @return {this} This Particle Emitter. - */ - resume: function () - { - this.active = true; - - return this; - }, - - /** - * Removes the emitter from its manager and the scene. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#remove - * @since 3.22.0 - * - * @return {this} This Particle Emitter. - */ - remove: function () - { - this.manager.removeEmitter(this); - - return this; - }, - - /** - * Sorts active particles with {@link Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback}. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSort - * @since 3.0.0 - * - * @return {this} This Particle Emitter. - */ - depthSort: function () - { - StableSort.inplace(this.alive, this.depthSortCallback); - - return this; - }, - - /** - * Puts the emitter in flow mode (frequency >= 0) and starts (or restarts) a particle flow. - * - * To resume a flow at the current frequency and quantity, use {@link Phaser.GameObjects.Particles.ParticleEmitter#start} instead. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#flow - * @since 3.0.0 - * - * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms. - * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [count=1] - The number of particles to emit at each flow cycle. - * - * @return {this} This Particle Emitter. - */ - flow: function (frequency, count) - { - if (count === undefined) { count = 1; } - - this.frequency = frequency; - - this.quantity.onChange(count); - - return this.start(); - }, - - /** - * Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#explode - * @since 3.0.0 - * - * @param {integer} count - The amount of Particles to emit. - * @param {number} x - The x coordinate to emit the Particles from. - * @param {number} y - The y coordinate to emit the Particles from. - * - * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. - */ - explode: function (count, x, y) - { - this.frequency = -1; - - return this.emitParticle(count, x, y); - }, - - /** - * Emits particles at a given position (or the emitter's current position). - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticleAt - * @since 3.0.0 - * - * @param {number} [x=this.x] - The x coordinate to emit the Particles from. - * @param {number} [y=this.x] - The y coordinate to emit the Particles from. - * @param {integer} [count=this.quantity] - The number of Particles to emit. - * - * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. - */ - emitParticleAt: function (x, y, count) - { - return this.emitParticle(count, x, y); - }, - - /** - * Emits particles at a given position (or the emitter's current position). - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticle - * @since 3.0.0 - * - * @param {integer} [count=this.quantity] - The number of Particles to emit. - * @param {number} [x=this.x] - The x coordinate to emit the Particles from. - * @param {number} [y=this.x] - The y coordinate to emit the Particles from. - * - * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. - * - * @see Phaser.GameObjects.Particles.Particle#fire - */ - emitParticle: function (count, x, y) - { - if (this.atLimit()) - { - return; - } - - if (count === undefined) - { - count = this.quantity.onEmit(); - } - - var dead = this.dead; - - for (var i = 0; i < count; i++) - { - var particle = dead.pop(); - - if (!particle) - { - particle = new this.particleClass(this); - } - - particle.fire(x, y); - - if (this.particleBringToTop) - { - this.alive.push(particle); - } - else - { - this.alive.unshift(particle); - } - - if (this.emitCallback) - { - this.emitCallback.call(this.emitCallbackScope, particle, this); - } - - if (this.atLimit()) - { - break; - } - } - - return particle; - }, - - /** - * Updates this emitter and its particles. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#preUpdate - * @since 3.0.0 - * - * @param {integer} 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. - */ - preUpdate: function (time, delta) - { - // Scale the delta - delta *= this.timeScale; - - var step = (delta / 1000); - - if (this.trackVisible) - { - this.visible = this.follow.visible; - } - - // Any particle processors? - var processors = this.manager.getProcessors(); - - var particles = this.alive; - var dead = this.dead; - - var i = 0; - var rip = []; - var length = particles.length; - - for (i = 0; i < length; i++) - { - var particle = particles[i]; - - // update returns `true` if the particle is now dead (lifeCurrent <= 0) - if (particle.update(delta, step, processors)) - { - rip.push({ index: i, particle: particle }); - } - } - - // Move dead particles to the dead array - length = rip.length; - - if (length > 0) - { - var deathCallback = this.deathCallback; - var deathCallbackScope = this.deathCallbackScope; - - for (i = length - 1; i >= 0; i--) - { - var entry = rip[i]; - - // Remove from particles array - particles.splice(entry.index, 1); - - // Add to dead array - dead.push(entry.particle); - - // Callback - if (deathCallback) - { - deathCallback.call(deathCallbackScope, entry.particle); - } - - entry.particle.resetPosition(); - } - } - - if (!this.on) - { - return; - } - - if (this.frequency === 0) - { - this.emitParticle(); - } - else if (this.frequency > 0) - { - this._counter -= delta; - - if (this._counter <= 0) - { - this.emitParticle(); - - // counter = frequency - remained from previous delta - this._counter = (this.frequency - Math.abs(this._counter)); - } - } - }, - - /** - * Calculates the difference of two particles, for sorting them by depth. - * - * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback - * @since 3.0.0 - * - * @param {object} a - The first particle. - * @param {object} b - The second particle. - * - * @return {integer} The difference of a and b's y coordinates. - */ - depthSortCallback: function (a, b) - { - return a.y - b.y; - } - -}); - -module.exports = ParticleEmitter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = require('../../renderer/BlendModes'); +var Class = require('../../utils/Class'); +var Components = require('../components'); +var DeathZone = require('./zones/DeathZone'); +var EdgeZone = require('./zones/EdgeZone'); +var EmitterOp = require('./EmitterOp'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetRandom = require('../../utils/array/GetRandom'); +var HasAny = require('../../utils/object/HasAny'); +var HasValue = require('../../utils/object/HasValue'); +var Particle = require('./Particle'); +var RandomZone = require('./zones/RandomZone'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var StableSort = require('../../utils/array/StableSort'); +var Vector2 = require('../../math/Vector2'); +var Wrap = require('../../math/Wrap'); + +/** + * @classdesc + * A particle emitter represents a single particle stream. + * It controls a pool of {@link Phaser.GameObjects.Particles.Particle Particles} and is controlled by a {@link Phaser.GameObjects.Particles.ParticleEmitterManager Particle Emitter Manager}. + * + * @class ParticleEmitter + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} manager - The Emitter Manager this Emitter belongs to. + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. + */ +var ParticleEmitter = new Class({ + + Mixins: [ + Components.BlendMode, + Components.Mask, + Components.ScrollFactor, + Components.Visible + ], + + initialize: + + function ParticleEmitter (manager, config) + { + /** + * The Emitter Manager this Emitter belongs to. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#manager + * @type {Phaser.GameObjects.Particles.ParticleEmitterManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The texture assigned to particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#texture + * @type {Phaser.Textures.Texture} + * @since 3.0.0 + */ + this.texture = manager.texture; + + /** + * The texture frames assigned to particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#frames + * @type {Phaser.Textures.Frame[]} + * @since 3.0.0 + */ + this.frames = [ manager.defaultFrame ]; + + /** + * The default texture frame assigned to particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#defaultFrame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + this.defaultFrame = manager.defaultFrame; + + /** + * Names of simple configuration properties. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#configFastMap + * @type {object} + * @since 3.0.0 + */ + this.configFastMap = [ + 'active', + 'blendMode', + 'collideBottom', + 'collideLeft', + 'collideRight', + 'collideTop', + 'deathCallback', + 'deathCallbackScope', + 'emitCallback', + 'emitCallbackScope', + 'follow', + 'frequency', + 'gravityX', + 'gravityY', + 'maxParticles', + 'name', + 'on', + 'particleBringToTop', + 'particleClass', + 'radial', + 'timeScale', + 'trackVisible', + 'visible' + ]; + + /** + * Names of complex configuration properties. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#configOpMap + * @type {object} + * @since 3.0.0 + */ + this.configOpMap = [ + 'accelerationX', + 'accelerationY', + 'angle', + 'alpha', + 'bounce', + 'delay', + 'lifespan', + 'maxVelocityX', + 'maxVelocityY', + 'moveToX', + 'moveToY', + 'quantity', + 'rotate', + 'scaleX', + 'scaleY', + 'speedX', + 'speedY', + 'tint', + 'x', + 'y' + ]; + + /** + * The name of this Particle Emitter. + * + * Empty by default and never populated by Phaser, this is left for developers to use. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#name + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.name = ''; + + /** + * The Particle Class which will be emitted by this Emitter. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#particleClass + * @type {Phaser.GameObjects.Particles.Particle} + * @default Phaser.GameObjects.Particles.Particle + * @since 3.0.0 + */ + this.particleClass = Particle; + + /** + * The x-coordinate of the particle origin (where particles will be emitted). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#x + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition + */ + this.x = new EmitterOp(config, 'x', 0, true); + + /** + * The y-coordinate of the particle origin (where particles will be emitted). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#y + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition + */ + this.y = new EmitterOp(config, 'y', 0, true); + + /** + * A radial emitter will emit particles in all directions between angle min and max, + * using {@link Phaser.GameObjects.Particles.ParticleEmitter#speed} as the value. If set to false then this acts as a point Emitter. + * A point emitter will emit particles only in the direction derived from the speedX and speedY values. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#radial + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setRadial + */ + this.radial = true; + + /** + * Horizontal acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#gravityX + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity + */ + this.gravityX = 0; + + /** + * Vertical acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#gravityY + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity + */ + this.gravityY = 0; + + /** + * Whether accelerationX and accelerationY are non-zero. Set automatically during configuration. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#acceleration + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.acceleration = false; + + /** + * Horizontal acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.accelerationX = new EmitterOp(config, 'accelerationX', 0, true); + + /** + * Vertical acceleration applied to emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.accelerationY = new EmitterOp(config, 'accelerationY', 0, true); + + /** + * The maximum horizontal velocity of emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityX = new EmitterOp(config, 'maxVelocityX', 10000, true); + + /** + * The maximum vertical velocity of emitted particles, in pixels per second squared. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 10000 + * @since 3.0.0 + */ + this.maxVelocityY = new EmitterOp(config, 'maxVelocityY', 10000, true); + + /** + * The initial horizontal speed of emitted particles, in pixels per second. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#speedX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX + */ + this.speedX = new EmitterOp(config, 'speedX', 0, true); + + /** + * The initial vertical speed of emitted particles, in pixels per second. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#speedY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY + */ + this.speedY = new EmitterOp(config, 'speedY', 0, true); + + /** + * Whether moveToX and moveToY are nonzero. Set automatically during configuration. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#moveTo + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.moveTo = false; + + /** + * The x-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#moveToX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.moveToX = new EmitterOp(config, 'moveToX', 0, true); + + /** + * The y-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#moveToY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.moveToY = new EmitterOp(config, 'moveToY', 0, true); + + /** + * Whether particles will rebound when they meet the emitter bounds. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#bounce + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.bounce = new EmitterOp(config, 'bounce', 0, true); + + /** + * The horizontal scale of emitted particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#scaleX + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScale + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleX + */ + this.scaleX = new EmitterOp(config, 'scaleX', 1); + + /** + * The vertical scale of emitted particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#scaleY + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScale + * @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleY + */ + this.scaleY = new EmitterOp(config, 'scaleY', 1); + + /** + * Color tint applied to emitted particles. Any alpha component (0xAA000000) is ignored. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#tint + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0xffffffff + * @since 3.0.0 + */ + this.tint = new EmitterOp(config, 'tint', 0xffffffff); + + /** + * The alpha (transparency) of emitted particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#alpha + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setAlpha + */ + this.alpha = new EmitterOp(config, 'alpha', 1); + + /** + * The lifespan of emitted particles, in ms. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#lifespan + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1000 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setLifespan + */ + this.lifespan = new EmitterOp(config, 'lifespan', 1000, true); + + /** + * The angle of the initial velocity of emitted particles, in degrees. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#angle + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default { min: 0, max: 360 } + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setAngle + */ + this.angle = new EmitterOp(config, 'angle', { min: 0, max: 360 }, true); + + /** + * The rotation of emitted particles, in degrees. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#rotate + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.rotate = new EmitterOp(config, 'rotate', 0); + + /** + * A function to call when a particle is emitted. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallback + * @type {?Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} + * @default null + * @since 3.0.0 + */ + this.emitCallback = null; + + /** + * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope + * @type {?*} + * @default null + * @since 3.0.0 + */ + this.emitCallbackScope = null; + + /** + * A function to call when a particle dies. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallback + * @type {?Phaser.Types.GameObjects.Particles.ParticleDeathCallback} + * @default null + * @since 3.0.0 + */ + this.deathCallback = null; + + /** + * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope + * @type {?*} + * @default null + * @since 3.0.0 + */ + this.deathCallbackScope = null; + + /** + * Set to hard limit the amount of particle objects this emitter is allowed to create. + * 0 means unlimited. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#maxParticles + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.maxParticles = 0; + + /** + * How many particles are emitted each time particles are emitted (one explosion or one flow cycle). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#quantity + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency + * @see Phaser.GameObjects.Particles.ParticleEmitter#setQuantity + */ + this.quantity = new EmitterOp(config, 'quantity', 1, true); + + /** + * How many ms to wait after emission before the particles start updating. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#delay + * @type {Phaser.GameObjects.Particles.EmitterOp} + * @default 0 + * @since 3.0.0 + */ + this.delay = new EmitterOp(config, 'delay', 0, true); + + /** + * For a flow emitter, the time interval (>= 0) between particle flow cycles in ms. + * A value of 0 means there is one particle flow cycle for each logic update (the maximum flow frequency). This is the default setting. + * For an exploding emitter, this value will be -1. + * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} also puts the emitter in flow mode (frequency >= 0). + * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} also puts the emitter in explode mode (frequency = -1). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#frequency + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency + */ + this.frequency = 0; + + /** + * Controls if the emitter is currently emitting a particle flow (when frequency >= 0). + * Already alive particles will continue to update until they expire. + * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#start} and {@link Phaser.GameObjects.Particles.ParticleEmitter#stop}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#on + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.on = true; + + /** + * Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. + * Set to false to send them to the back. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#particleBringToTop + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.particleBringToTop = true; + + /** + * The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * An object describing a shape to emit particles from. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#emitZone + * @type {?Phaser.GameObjects.Particles.Zones.EdgeZone|Phaser.GameObjects.Particles.Zones.RandomZone} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone + */ + this.emitZone = null; + + /** + * An object describing a shape that deactivates particles when they interact with it. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#deathZone + * @type {?Phaser.GameObjects.Particles.Zones.DeathZone} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone + */ + this.deathZone = null; + + /** + * A rectangular boundary constraining particle movement. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#bounds + * @type {?Phaser.Geom.Rectangle} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setBounds + */ + this.bounds = null; + + /** + * Whether particles interact with the left edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideLeft + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideLeft = true; + + /** + * Whether particles interact with the right edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideRight + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideRight = true; + + /** + * Whether particles interact with the top edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideTop + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideTop = true; + + /** + * Whether particles interact with the bottom edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#collideBottom + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.collideBottom = true; + + /** + * Whether this emitter updates itself and its particles. + * + * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#pause} + * and {@link Phaser.GameObjects.Particles.ParticleEmitter#resume}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * Set this to false to hide any active particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#visible + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setVisible + */ + this.visible = true; + + /** + * The blend mode of this emitter's particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#blendMode + * @type {integer} + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setBlendMode + */ + this.blendMode = BlendModes.NORMAL; + + /** + * A Game Object whose position is used as the particle origin. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#follow + * @type {?Phaser.GameObjects.GameObject} + * @default null + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow + * @see Phaser.GameObjects.Particles.ParticleEmitter#stopFollow + */ + this.follow = null; + + /** + * The offset of the particle origin from the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#followOffset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow + */ + this.followOffset = new Vector2(); + + /** + * Whether the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#visible} state will track + * the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target's visibility state. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#trackVisible + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow + */ + this.trackVisible = false; + + /** + * The current texture frame, as an index of {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#currentFrame + * @type {integer} + * @default 0 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame + */ + this.currentFrame = 0; + + /** + * Whether texture {@link Phaser.GameObjects.Particles.ParticleEmitter#frames} are selected at random. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#randomFrame + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame + */ + this.randomFrame = true; + + /** + * The number of consecutive particles that receive a single texture frame (per frame cycle). + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity + * @type {integer} + * @default 1 + * @since 3.0.0 + * @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame + */ + this.frameQuantity = 1; + + /** + * Inactive particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#dead + * @type {Phaser.GameObjects.Particles.Particle[]} + * @private + * @since 3.0.0 + */ + this.dead = []; + + /** + * Active particles + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#alive + * @type {Phaser.GameObjects.Particles.Particle[]} + * @private + * @since 3.0.0 + */ + this.alive = []; + + /** + * The time until the next flow cycle. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#_counter + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._counter = 0; + + /** + * Counts up to {@link Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity}. + * + * @name Phaser.GameObjects.Particles.ParticleEmitter#_frameCounter + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._frameCounter = 0; + + if (config) + { + this.fromJSON(config); + } + }, + + /** + * Merges configuration settings into the emitter's current settings. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#fromJSON + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter. + * + * @return {this} This Particle Emitter. + */ + fromJSON: function (config) + { + if (!config) + { + return this; + } + + // Only update properties from their current state if they exist in the given config + + var i = 0; + var key = ''; + + for (i = 0; i < this.configFastMap.length; i++) + { + key = this.configFastMap[i]; + + if (HasValue(config, key)) + { + this[key] = GetFastValue(config, key); + } + } + + for (i = 0; i < this.configOpMap.length; i++) + { + key = this.configOpMap[i]; + + if (HasValue(config, key)) + { + this[key].loadConfig(config); + } + } + + this.acceleration = (this.accelerationX.propertyValue !== 0 || this.accelerationY.propertyValue !== 0); + + this.moveTo = (this.moveToX.propertyValue !== 0 || this.moveToY.propertyValue !== 0); + + // Special 'speed' override + + if (HasValue(config, 'speed')) + { + this.speedX.loadConfig(config, 'speed'); + this.speedY = null; + } + + // If you specify speedX, speedY or moveTo then it changes the emitter from radial to a point emitter + if (HasAny(config, [ 'speedX', 'speedY' ]) || this.moveTo) + { + this.radial = false; + } + + // Special 'scale' override + + if (HasValue(config, 'scale')) + { + this.scaleX.loadConfig(config, 'scale'); + this.scaleY = null; + } + + if (HasValue(config, 'callbackScope')) + { + var callbackScope = GetFastValue(config, 'callbackScope', null); + + this.emitCallbackScope = callbackScope; + this.deathCallbackScope = callbackScope; + } + + if (HasValue(config, 'emitZone')) + { + this.setEmitZone(config.emitZone); + } + + if (HasValue(config, 'deathZone')) + { + this.setDeathZone(config.deathZone); + } + + if (HasValue(config, 'bounds')) + { + this.setBounds(config.bounds); + } + + if (HasValue(config, 'followOffset')) + { + this.followOffset.setFromObject(GetFastValue(config, 'followOffset', 0)); + } + + if (HasValue(config, 'frame')) + { + this.setFrame(config.frame); + } + + return this; + }, + + /** + * Creates a description of this emitter suitable for JSON serialization. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#toJSON + * @since 3.0.0 + * + * @param {object} [output] - An object to copy output into. + * + * @return {object} - The output object. + */ + toJSON: function (output) + { + if (output === undefined) { output = {}; } + + var i = 0; + var key = ''; + + for (i = 0; i < this.configFastMap.length; i++) + { + key = this.configFastMap[i]; + + output[key] = this[key]; + } + + for (i = 0; i < this.configOpMap.length; i++) + { + key = this.configOpMap[i]; + + if (this[key]) + { + output[key] = this[key].toJSON(); + } + } + + // special handlers + if (!this.speedY) + { + delete output.speedX; + output.speed = this.speedX.toJSON(); + } + + if (!this.scaleY) + { + delete output.scaleX; + output.scale = this.scaleX.toJSON(); + } + + return output; + }, + + /** + * Continuously moves the particle origin to follow a Game Object's position. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#startFollow + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} target - The Game Object to follow. + * @param {number} [offsetX=0] - Horizontal offset of the particle origin from the Game Object. + * @param {number} [offsetY=0] - Vertical offset of the particle origin from the Game Object. + * @param {boolean} [trackVisible=false] - Whether the emitter's visible state will track the target's visible state. + * + * @return {this} This Particle Emitter. + */ + startFollow: function (target, offsetX, offsetY, trackVisible) + { + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackVisible === undefined) { trackVisible = false; } + + this.follow = target; + this.followOffset.set(offsetX, offsetY); + this.trackVisible = trackVisible; + + return this; + }, + + /** + * Stops following a Game Object. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#stopFollow + * @since 3.0.0 + * + * @return {this} This Particle Emitter. + */ + stopFollow: function () + { + this.follow = null; + this.followOffset.set(0, 0); + this.trackVisible = false; + + return this; + }, + + /** + * Chooses a texture frame from {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getFrame + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} The texture frame. + */ + getFrame: function () + { + if (this.frames.length === 1) + { + return this.defaultFrame; + } + else if (this.randomFrame) + { + return GetRandom(this.frames); + } + else + { + var frame = this.frames[this.currentFrame]; + + this._frameCounter++; + + if (this._frameCounter === this.frameQuantity) + { + this._frameCounter = 0; + this.currentFrame = Wrap(this.currentFrame + 1, 0, this._frameLength); + } + + return frame; + } + }, + + // frame: 0 + // frame: 'red' + // frame: [ 0, 1, 2, 3 ] + // frame: [ 'red', 'green', 'blue', 'pink', 'white' ] + // frame: { frames: [ 'red', 'green', 'blue', 'pink', 'white' ], [cycle: bool], [quantity: int] } + + /** + * Sets a pattern for assigning texture frames to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setFrame + * @since 3.0.0 + * + * @param {(array|string|integer|Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig)} frames - One or more texture frames, or a configuration object. + * @param {boolean} [pickRandom=true] - Whether frames should be assigned at random from `frames`. + * @param {integer} [quantity=1] - The number of consecutive particles that will receive each frame. + * + * @return {this} This Particle Emitter. + */ + setFrame: function (frames, pickRandom, quantity) + { + if (pickRandom === undefined) { pickRandom = true; } + if (quantity === undefined) { quantity = 1; } + + this.randomFrame = pickRandom; + this.frameQuantity = quantity; + this.currentFrame = 0; + this._frameCounter = 0; + + var t = typeof (frames); + + if (Array.isArray(frames) || t === 'string' || t === 'number') + { + this.manager.setEmitterFrames(frames, this); + } + else if (t === 'object') + { + var frameConfig = frames; + + frames = GetFastValue(frameConfig, 'frames', null); + + if (frames) + { + this.manager.setEmitterFrames(frames, this); + } + + var isCycle = GetFastValue(frameConfig, 'cycle', false); + + this.randomFrame = (isCycle) ? false : true; + + this.frameQuantity = GetFastValue(frameConfig, 'quantity', quantity); + } + + this._frameLength = this.frames.length; + + if (this._frameLength === 1) + { + this.frameQuantity = 1; + this.randomFrame = false; + } + + return this; + }, + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle movement on or off. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setRadial + * @since 3.0.0 + * + * @param {boolean} [value=true] - Radial mode (true) or point mode (true). + * + * @return {this} This Particle Emitter. + */ + setRadial: function (value) + { + if (value === undefined) { value = true; } + + this.radial = value; + + return this; + }, + + /** + * Sets the position of the emitter's particle origin. + * New particles will be emitted here. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setPosition + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} x - The x-coordinate of the particle origin. + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} y - The y-coordinate of the particle origin. + * + * @return {this} This Particle Emitter. + */ + setPosition: function (x, y) + { + this.x.onChange(x); + this.y.onChange(y); + + return this; + }, + + /** + * Sets or modifies a rectangular boundary constraining the particles. + * + * To remove the boundary, set {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds} to null. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setBounds + * @since 3.0.0 + * + * @param {(number|Phaser.Types.GameObjects.Particles.ParticleEmitterBounds|Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt)} x - The x-coordinate of the left edge of the boundary, or an object representing a rectangle. + * @param {number} y - The y-coordinate of the top edge of the boundary. + * @param {number} width - The width of the boundary. + * @param {number} height - The height of the boundary. + * + * @return {this} This Particle Emitter. + */ + setBounds: function (x, y, width, height) + { + if (typeof x === 'object') + { + var obj = x; + + x = obj.x; + y = obj.y; + width = (HasValue(obj, 'w')) ? obj.w : obj.width; + height = (HasValue(obj, 'h')) ? obj.h : obj.height; + } + + if (this.bounds) + { + this.bounds.setTo(x, y, width, height); + } + else + { + this.bounds = new Rectangle(x, y, width, height); + } + + return this; + }, + + /** + * Sets the initial horizontal speed of emitted particles. + * Changes the emitter to point mode. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. + * + * @return {this} This Particle Emitter. + */ + setSpeedX: function (value) + { + this.speedX.onChange(value); + + // If you specify speedX and Y then it changes the emitter from radial to a point emitter + this.radial = false; + + return this; + }, + + /** + * Sets the initial vertical speed of emitted particles. + * Changes the emitter to point mode. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. + * + * @return {this} This Particle Emitter. + */ + setSpeedY: function (value) + { + if (this.speedY) + { + this.speedY.onChange(value); + + // If you specify speedX and Y then it changes the emitter from radial to a point emitter + this.radial = false; + } + + return this; + }, + + /** + * Sets the initial radial speed of emitted particles. + * Changes the emitter to radial mode. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeed + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second. + * + * @return {this} This Particle Emitter. + */ + setSpeed: function (value) + { + this.speedX.onChange(value); + this.speedY = null; + + // If you specify speedX and Y then it changes the emitter from radial to a point emitter + this.radial = true; + + return this; + }, + + /** + * Sets the horizontal scale of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleX + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. + * + * @return {this} This Particle Emitter. + */ + setScaleX: function (value) + { + this.scaleX.onChange(value); + + return this; + }, + + /** + * Sets the vertical scale of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleY + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. + * + * @return {this} This Particle Emitter. + */ + setScaleY: function (value) + { + this.scaleY.onChange(value); + + return this; + }, + + /** + * Sets the scale of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setScale + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1. + * + * @return {this} This Particle Emitter. + */ + setScale: function (value) + { + this.scaleX.onChange(value); + this.scaleY = null; + + return this; + }, + + /** + * Sets the horizontal gravity applied to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityX + * @since 3.0.0 + * + * @param {number} value - Acceleration due to gravity, in pixels per second squared. + * + * @return {this} This Particle Emitter. + */ + setGravityX: function (value) + { + this.gravityX = value; + + return this; + }, + + /** + * Sets the vertical gravity applied to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityY + * @since 3.0.0 + * + * @param {number} value - Acceleration due to gravity, in pixels per second squared. + * + * @return {this} This Particle Emitter. + */ + setGravityY: function (value) + { + this.gravityY = value; + + return this; + }, + + /** + * Sets the gravity applied to emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setGravity + * @since 3.0.0 + * + * @param {number} x - Horizontal acceleration due to gravity, in pixels per second squared. + * @param {number} y - Vertical acceleration due to gravity, in pixels per second squared. + * + * @return {this} This Particle Emitter. + */ + setGravity: function (x, y) + { + this.gravityX = x; + this.gravityY = y; + + return this; + }, + + /** + * Sets the opacity of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setAlpha + * @since 3.0.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 (transparent) and 1 (opaque). + * + * @return {this} This Particle Emitter. + */ + setAlpha: function (value) + { + this.alpha.onChange(value); + + return this; + }, + + /** + * Sets the color tint of emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setTint + * @since 3.22.0 + * + * @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 and 0xffffff. + * + * @return {this} This Particle Emitter. + */ + setTint: function (value) + { + this.tint.onChange(value); + + return this; + }, + + /** + * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitterAngle + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. + * + * @return {this} This Particle Emitter. + */ + setEmitterAngle: function (value) + { + this.angle.onChange(value); + + return this; + }, + + /** + * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setAngle + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles. + * + * @return {this} This Particle Emitter. + */ + setAngle: function (value) + { + this.angle.onChange(value); + + return this; + }, + + /** + * Sets the lifespan of newly emitted particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setLifespan + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The particle lifespan, in ms. + * + * @return {this} This Particle Emitter. + */ + setLifespan: function (value) + { + this.lifespan.onChange(value); + + return this; + }, + + /** + * Sets the number of particles released at each flow cycle or explosion. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setQuantity + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} quantity - The number of particles to release at each flow cycle or explosion. + * + * @return {this} This Particle Emitter. + */ + setQuantity: function (quantity) + { + this.quantity.onChange(quantity); + + return this; + }, + + /** + * Sets the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency} + * and {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setFrequency + * @since 3.0.0 + * + * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [quantity] - The number of particles to release at each flow cycle or explosion. + * + * @return {this} This Particle Emitter. + */ + setFrequency: function (frequency, quantity) + { + this.frequency = frequency; + + this._counter = 0; + + if (quantity) + { + this.quantity.onChange(quantity); + } + + return this; + }, + + /** + * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#emitZone}. + * + * An {@link Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig EdgeZone} places particles on its edges. Its {@link Phaser.Types.GameObjects.Particles.EdgeZoneSource source} can be a Curve, Path, Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback getPoints} method. + * + * A {@link Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig RandomZone} places randomly within its interior. Its {@link RandomZoneSource source} can be a Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback getRandomPoint} method. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current emit zone. + * + * @return {this} This Particle Emitter. + */ + setEmitZone: function (zoneConfig) + { + if (zoneConfig === undefined) + { + this.emitZone = null; + } + else + { + // 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] } + + var type = GetFastValue(zoneConfig, 'type', 'random'); + var source = GetFastValue(zoneConfig, 'source', null); + + switch (type) + { + case 'random': + + this.emitZone = new RandomZone(source); + + break; + + case 'edge': + + var quantity = GetFastValue(zoneConfig, 'quantity', 1); + var stepRate = GetFastValue(zoneConfig, 'stepRate', 0); + var yoyo = GetFastValue(zoneConfig, 'yoyo', false); + var seamless = GetFastValue(zoneConfig, 'seamless', true); + + this.emitZone = new EdgeZone(source, quantity, stepRate, yoyo, seamless); + + break; + } + } + + return this; + }, + + /** + * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#deathZone}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current death zone. + * + * @return {this} This Particle Emitter. + */ + setDeathZone: function (zoneConfig) + { + if (zoneConfig === undefined) + { + this.deathZone = null; + } + else + { + // Where source = Geom like Circle or Rect that supports a 'contains' function + // deathZone: { type: 'onEnter', source: X } + // deathZone: { type: 'onLeave', source: X } + + var type = GetFastValue(zoneConfig, 'type', 'onEnter'); + var source = GetFastValue(zoneConfig, 'source', null); + + if (source && typeof source.contains === 'function') + { + var killOnEnter = (type === 'onEnter') ? true : false; + + this.deathZone = new DeathZone(source, killOnEnter); + } + } + + return this; + }, + + /** + * Creates inactive particles and adds them to this emitter's pool. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#reserve + * @since 3.0.0 + * + * @param {integer} particleCount - The number of particles to create. + * + * @return {this} This Particle Emitter. + */ + reserve: function (particleCount) + { + var dead = this.dead; + + for (var i = 0; i < particleCount; i++) + { + dead.push(new this.particleClass(this)); + } + + return this; + }, + + /** + * Gets the number of active (in-use) particles in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getAliveParticleCount + * @since 3.0.0 + * + * @return {integer} The number of particles with `active=true`. + */ + getAliveParticleCount: function () + { + return this.alive.length; + }, + + /** + * Gets the number of inactive (available) particles in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getDeadParticleCount + * @since 3.0.0 + * + * @return {integer} The number of particles with `active=false`. + */ + getDeadParticleCount: function () + { + return this.dead.length; + }, + + /** + * Gets the total number of particles in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#getParticleCount + * @since 3.0.0 + * + * @return {integer} The number of particles, including both alive and dead. + */ + getParticleCount: function () + { + return this.getAliveParticleCount() + this.getDeadParticleCount(); + }, + + /** + * Whether this emitter is at its limit (if set). + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#atLimit + * @since 3.0.0 + * + * @return {boolean} Returns `true` if this Emitter is at its limit, or `false` if no limit, or below the `maxParticles` level. + */ + atLimit: function () + { + return (this.maxParticles > 0 && this.getParticleCount() === this.maxParticles); + }, + + /** + * Sets a function to call for each newly emitted particle. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleEmit + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. + * @param {*} [context] - The calling context. + * + * @return {this} This Particle Emitter. + */ + onParticleEmit: function (callback, context) + { + if (callback === undefined) + { + // Clear any previously set callback + this.emitCallback = null; + this.emitCallbackScope = null; + } + else if (typeof callback === 'function') + { + this.emitCallback = callback; + + if (context) + { + this.emitCallbackScope = context; + } + } + + return this; + }, + + /** + * Sets a function to call for each particle death. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleDeath + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleDeathCallback} callback - The function. + * @param {*} [context] - The function's calling context. + * + * @return {this} This Particle Emitter. + */ + onParticleDeath: function (callback, context) + { + if (callback === undefined) + { + // Clear any previously set callback + this.deathCallback = null; + this.deathCallbackScope = null; + } + else if (typeof callback === 'function') + { + this.deathCallback = callback; + + if (context) + { + this.deathCallbackScope = context; + } + } + + return this; + }, + + /** + * Deactivates every particle in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#killAll + * @since 3.0.0 + * + * @return {this} This Particle Emitter. + */ + killAll: function () + { + var dead = this.dead; + var alive = this.alive; + + while (alive.length > 0) + { + dead.push(alive.pop()); + } + + return this; + }, + + /** + * Calls a function for each active particle in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#forEachAlive + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. + * @param {*} context - The function's calling context. + * + * @return {this} This Particle Emitter. + */ + forEachAlive: function (callback, context) + { + var alive = this.alive; + var length = alive.length; + + for (var index = 0; index < length; ++index) + { + // Sends the Particle and the Emitter + callback.call(context, alive[index], this); + } + + return this; + }, + + /** + * Calls a function for each inactive particle in this emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#forEachDead + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function. + * @param {*} context - The function's calling context. + * + * @return {this} This Particle Emitter. + */ + forEachDead: function (callback, context) + { + var dead = this.dead; + var length = dead.length; + + for (var index = 0; index < length; ++index) + { + // Sends the Particle and the Emitter + callback.call(context, dead[index], this); + } + + return this; + }, + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on} the emitter and resets the flow counter. + * + * If this emitter is in flow mode (frequency >= 0; the default), the particle flow will start (or restart). + * + * If this emitter is in explode mode (frequency = -1), nothing will happen. + * Use {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} or {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} instead. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#start + * @since 3.0.0 + * + * @return {this} This Particle Emitter. + */ + start: function () + { + this.on = true; + + this._counter = 0; + + return this; + }, + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on off} the emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#stop + * @since 3.11.0 + * + * @return {this} This Particle Emitter. + */ + stop: function () + { + this.on = false; + + return this; + }, + + /** + * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Deactivates} the emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#pause + * @since 3.0.0 + * + * @return {this} This Particle Emitter. + */ + pause: function () + { + this.active = false; + + return this; + }, + + /** + * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Activates} the emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#resume + * @since 3.0.0 + * + * @return {this} This Particle Emitter. + */ + resume: function () + { + this.active = true; + + return this; + }, + + /** + * Removes the emitter from its manager and the scene. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#remove + * @since 3.22.0 + * + * @return {this} This Particle Emitter. + */ + remove: function () + { + this.manager.removeEmitter(this); + + return this; + }, + + /** + * Sorts active particles with {@link Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback}. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSort + * @since 3.0.0 + * + * @return {this} This Particle Emitter. + */ + depthSort: function () + { + StableSort.inplace(this.alive, this.depthSortCallback); + + return this; + }, + + /** + * Puts the emitter in flow mode (frequency >= 0) and starts (or restarts) a particle flow. + * + * To resume a flow at the current frequency and quantity, use {@link Phaser.GameObjects.Particles.ParticleEmitter#start} instead. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#flow + * @since 3.0.0 + * + * @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms. + * @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [count=1] - The number of particles to emit at each flow cycle. + * + * @return {this} This Particle Emitter. + */ + flow: function (frequency, count) + { + if (count === undefined) { count = 1; } + + this.frequency = frequency; + + this.quantity.onChange(count); + + return this.start(); + }, + + /** + * Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#explode + * @since 3.0.0 + * + * @param {integer} count - The amount of Particles to emit. + * @param {number} x - The x coordinate to emit the Particles from. + * @param {number} y - The y coordinate to emit the Particles from. + * + * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. + */ + explode: function (count, x, y) + { + this.frequency = -1; + + return this.emitParticle(count, x, y); + }, + + /** + * Emits particles at a given position (or the emitter's current position). + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticleAt + * @since 3.0.0 + * + * @param {number} [x=this.x] - The x coordinate to emit the Particles from. + * @param {number} [y=this.x] - The y coordinate to emit the Particles from. + * @param {integer} [count=this.quantity] - The number of Particles to emit. + * + * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. + */ + emitParticleAt: function (x, y, count) + { + return this.emitParticle(count, x, y); + }, + + /** + * Emits particles at a given position (or the emitter's current position). + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticle + * @since 3.0.0 + * + * @param {integer} [count=this.quantity] - The number of Particles to emit. + * @param {number} [x=this.x] - The x coordinate to emit the Particles from. + * @param {number} [y=this.x] - The y coordinate to emit the Particles from. + * + * @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle. + * + * @see Phaser.GameObjects.Particles.Particle#fire + */ + emitParticle: function (count, x, y) + { + if (this.atLimit()) + { + return; + } + + if (count === undefined) + { + count = this.quantity.onEmit(); + } + + var dead = this.dead; + + for (var i = 0; i < count; i++) + { + var particle = dead.pop(); + + if (!particle) + { + particle = new this.particleClass(this); + } + + particle.fire(x, y); + + if (this.particleBringToTop) + { + this.alive.push(particle); + } + else + { + this.alive.unshift(particle); + } + + if (this.emitCallback) + { + this.emitCallback.call(this.emitCallbackScope, particle, this); + } + + if (this.atLimit()) + { + break; + } + } + + return particle; + }, + + /** + * Updates this emitter and its particles. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#preUpdate + * @since 3.0.0 + * + * @param {integer} 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. + */ + preUpdate: function (time, delta) + { + // Scale the delta + delta *= this.timeScale; + + var step = (delta / 1000); + + if (this.trackVisible) + { + this.visible = this.follow.visible; + } + + // Any particle processors? + var processors = this.manager.getProcessors(); + + var particles = this.alive; + var dead = this.dead; + + var i = 0; + var rip = []; + var length = particles.length; + + for (i = 0; i < length; i++) + { + var particle = particles[i]; + + // update returns `true` if the particle is now dead (lifeCurrent <= 0) + if (particle.update(delta, step, processors)) + { + rip.push({ index: i, particle: particle }); + } + } + + // Move dead particles to the dead array + length = rip.length; + + if (length > 0) + { + var deathCallback = this.deathCallback; + var deathCallbackScope = this.deathCallbackScope; + + for (i = length - 1; i >= 0; i--) + { + var entry = rip[i]; + + // Remove from particles array + particles.splice(entry.index, 1); + + // Add to dead array + dead.push(entry.particle); + + // Callback + if (deathCallback) + { + deathCallback.call(deathCallbackScope, entry.particle); + } + + entry.particle.resetPosition(); + } + } + + if (!this.on) + { + return; + } + + if (this.frequency === 0) + { + this.emitParticle(); + } + else if (this.frequency > 0) + { + this._counter -= delta; + + if (this._counter <= 0) + { + this.emitParticle(); + + // counter = frequency - remained from previous delta + this._counter = (this.frequency - Math.abs(this._counter)); + } + } + }, + + /** + * Calculates the difference of two particles, for sorting them by depth. + * + * @method Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback + * @since 3.0.0 + * + * @param {object} a - The first particle. + * @param {object} b - The second particle. + * + * @return {integer} The difference of a and b's y coordinates. + */ + depthSortCallback: function (a, b) + { + return a.y - b.y; + } + +}); + +module.exports = ParticleEmitter; diff --git a/src/gameobjects/particles/ParticleEmitterManager.js b/src/gameobjects/particles/ParticleEmitterManager.js index a4aa00b9a..995b64e11 100644 --- a/src/gameobjects/particles/ParticleEmitterManager.js +++ b/src/gameobjects/particles/ParticleEmitterManager.js @@ -1,483 +1,483 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var GravityWell = require('./GravityWell'); -var List = require('../../structs/List'); -var ParticleEmitter = require('./ParticleEmitter'); -var Render = require('./ParticleManagerRender'); - -/** - * @classdesc - * A Particle Emitter Manager creates and controls {@link Phaser.GameObjects.Particles.ParticleEmitter Particle Emitters} and {@link Phaser.GameObjects.Particles.GravityWell Gravity Wells}. - * - * @class ParticleEmitterManager - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects.Particles - * @constructor - * @since 3.0.0 - * - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Scene} scene - The Scene to which this Emitter Manager belongs. - * @param {string} texture - The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Emitter Manager will use to render particles. - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create. - */ -var ParticleEmitterManager = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Depth, - Components.Mask, - Components.Pipeline, - Components.Transform, - Components.Visible, - Render - ], - - initialize: - - // frame is optional and can contain the emitters array or object if skipped - function ParticleEmitterManager (scene, texture, frame, emitters) - { - GameObject.call(this, scene, 'ParticleEmitterManager'); - - /** - * The blend mode applied to all emitters and particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#blendMode - * @type {integer} - * @default -1 - * @private - * @since 3.0.0 - */ - this.blendMode = -1; - - /** - * The time scale applied to all emitters and particles, affecting flow rate, lifespan, and movement. - * Values larger than 1 are faster than normal. - * This is multiplied with any timeScale set on each individual emitter. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * The texture used to render this Emitter Manager's particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#texture - * @type {Phaser.Textures.Texture} - * @default null - * @since 3.0.0 - */ - this.texture = null; - - /** - * The texture frame used to render this Emitter Manager's particles. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#frame - * @type {Phaser.Textures.Frame} - * @default null - * @since 3.0.0 - */ - this.frame = null; - - /** - * Names of this Emitter Manager's texture frames. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#frameNames - * @type {string[]} - * @since 3.0.0 - */ - this.frameNames = []; - - // frame is optional and can contain the emitters array or object if skipped - if (frame !== null && (typeof frame === 'object' || Array.isArray(frame))) - { - emitters = frame; - frame = null; - } - - this.setTexture(texture, frame); - - this.initPipeline(); - - /** - * A list of Emitters being managed by this Emitter Manager. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#emitters - * @type {Phaser.Structs.List.} - * @since 3.0.0 - */ - this.emitters = new List(this); - - /** - * A list of Gravity Wells being managed by this Emitter Manager. - * - * @name Phaser.GameObjects.Particles.ParticleEmitterManager#wells - * @type {Phaser.Structs.List.} - * @since 3.0.0 - */ - this.wells = new List(this); - - if (emitters) - { - // An array of emitter configs? - if (!Array.isArray(emitters)) - { - emitters = [ emitters ]; - } - - for (var i = 0; i < emitters.length; i++) - { - this.createEmitter(emitters[i]); - } - } - }, - - /** - * Sets the texture and frame this Emitter Manager will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setTexture - * @since 3.0.0 - * - * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * - * @return {this} This Emitter Manager. - */ - setTexture: function (key, frame) - { - this.texture = this.scene.sys.textures.get(key); - - return this.setFrame(frame); - }, - - /** - * Sets the frame this Emitter Manager will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setFrame - * @since 3.0.0 - * - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * - * @return {this} This Emitter Manager. - */ - setFrame: function (frame) - { - this.frame = this.texture.get(frame); - - var frames = this.texture.getFramesFromTextureSource(this.frame.sourceIndex); - - var names = []; - - frames.forEach(function (sourceFrame) - { - names.push(sourceFrame.name); - }); - - this.frameNames = names; - - this.defaultFrame = this.frame; - - return this; - }, - - /** - * Assigns texture frames to an emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setEmitterFrames - * @since 3.0.0 - * - * @param {(Phaser.Textures.Frame|Phaser.Textures.Frame[])} frames - The texture frames. - * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The particle emitter to modify. - * - * @return {this} This Emitter Manager. - */ - setEmitterFrames: function (frames, emitter) - { - if (!Array.isArray(frames)) - { - frames = [ frames ]; - } - - var out = emitter.frames; - - out.length = 0; - - for (var i = 0; i < frames.length; i++) - { - var frame = frames[i]; - - if (this.frameNames.indexOf(frame) !== -1) - { - out.push(this.texture.get(frame)); - } - } - - if (out.length > 0) - { - emitter.defaultFrame = out[0]; - } - else - { - emitter.defaultFrame = this.defaultFrame; - } - - return this; - }, - - /** - * Adds an existing Particle Emitter to this Emitter Manager. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#addEmitter - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Particle Emitter to add to this Emitter Manager. - * - * @return {Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter that was added to this Emitter Manager. - */ - addEmitter: function (emitter) - { - return this.emitters.add(emitter); - }, - - /** - * Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#createEmitter - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Configuration settings for the Particle Emitter to create. - * - * @return {Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter that was created. - */ - createEmitter: function (config) - { - return this.addEmitter(new ParticleEmitter(this, config)); - }, - - /** - * Removes a Particle Emitter from this Emitter Manager, if the Emitter belongs to this Manager. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#removeEmitter - * @since 3.22.0 - * - * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - * - * @return {?Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter if it was removed or null if it was not. - */ - removeEmitter: function (emitter) - { - return this.emitters.remove(emitter, true); - }, - - /** - * Adds an existing Gravity Well object to this Emitter Manager. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#addGravityWell - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.GravityWell} well - The Gravity Well to add to this Emitter Manager. - * - * @return {Phaser.GameObjects.Particles.GravityWell} The Gravity Well that was added to this Emitter Manager. - */ - addGravityWell: function (well) - { - return this.wells.add(well); - }, - - /** - * Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#createGravityWell - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.GravityWellConfig} config - Configuration settings for the Gravity Well to create. - * - * @return {Phaser.GameObjects.Particles.GravityWell} The Gravity Well that was created. - */ - createGravityWell: function (config) - { - return this.addGravityWell(new GravityWell(config)); - }, - - /** - * Emits particles from each active emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#emitParticle - * @since 3.0.0 - * - * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. - * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. - * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. - * - * @return {this} This Emitter Manager. - */ - emitParticle: function (count, x, y) - { - var emitters = this.emitters.list; - - for (var i = 0; i < emitters.length; i++) - { - var emitter = emitters[i]; - - if (emitter.active) - { - emitter.emitParticle(count, x, y); - } - } - - return this; - }, - - /** - * Emits particles from each active emitter. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#emitParticleAt - * @since 3.0.0 - * - * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. - * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. - * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. - * - * @return {this} This Emitter Manager. - */ - emitParticleAt: function (x, y, count) - { - return this.emitParticle(count, x, y); - }, - - /** - * Pauses this Emitter Manager. - * - * This has the effect of pausing all emitters, and all particles of those emitters, currently under its control. - * - * The particles will still render, but they will not have any of their logic updated. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#pause - * @since 3.0.0 - * - * @return {this} This Emitter Manager. - */ - pause: function () - { - this.active = false; - - return this; - }, - - /** - * Resumes this Emitter Manager, should it have been previously paused. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#resume - * @since 3.0.0 - * - * @return {this} This Emitter Manager. - */ - resume: function () - { - this.active = true; - - return this; - }, - - /** - * Gets all active particle processors (gravity wells). - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#getProcessors - * @since 3.0.0 - * - * @return {Phaser.GameObjects.Particles.GravityWell[]} - The active gravity wells. - */ - getProcessors: function () - { - return this.wells.getAll('active', true); - }, - - /** - * Updates all active emitters. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#preUpdate - * @since 3.0.0 - * - * @param {integer} 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. - */ - preUpdate: function (time, delta) - { - // Scale the delta - delta *= this.timeScale; - - var emitters = this.emitters.list; - - for (var i = 0; i < emitters.length; i++) - { - var emitter = emitters[i]; - - if (emitter.active) - { - emitter.preUpdate(time, delta); - } - } - }, - - /** - * A NOOP method so you can pass an EmitterManager to a Container. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setAlpha - * @private - * @since 3.10.0 - */ - setAlpha: function () - { - }, - - /** - * A NOOP method so you can pass an EmitterManager to a Container. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setScrollFactor - * @private - * @since 3.10.0 - */ - setScrollFactor: function () - { - }, - - /** - * A NOOP method so you can pass an EmitterManager to a Container. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setBlendMode - * @private - * @since 3.15.0 - */ - setBlendMode: function () - { - } - -}); - -module.exports = ParticleEmitterManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var GravityWell = require('./GravityWell'); +var List = require('../../structs/List'); +var ParticleEmitter = require('./ParticleEmitter'); +var Render = require('./ParticleManagerRender'); + +/** + * @classdesc + * A Particle Emitter Manager creates and controls {@link Phaser.GameObjects.Particles.ParticleEmitter Particle Emitters} and {@link Phaser.GameObjects.Particles.GravityWell Gravity Wells}. + * + * @class ParticleEmitterManager + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects.Particles + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Scene} scene - The Scene to which this Emitter Manager belongs. + * @param {string} texture - The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Emitter Manager will use to render particles. + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create. + */ +var ParticleEmitterManager = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Depth, + Components.Mask, + Components.Pipeline, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + // frame is optional and can contain the emitters array or object if skipped + function ParticleEmitterManager (scene, texture, frame, emitters) + { + GameObject.call(this, scene, 'ParticleEmitterManager'); + + /** + * The blend mode applied to all emitters and particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#blendMode + * @type {integer} + * @default -1 + * @private + * @since 3.0.0 + */ + this.blendMode = -1; + + /** + * The time scale applied to all emitters and particles, affecting flow rate, lifespan, and movement. + * Values larger than 1 are faster than normal. + * This is multiplied with any timeScale set on each individual emitter. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * The texture used to render this Emitter Manager's particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#texture + * @type {Phaser.Textures.Texture} + * @default null + * @since 3.0.0 + */ + this.texture = null; + + /** + * The texture frame used to render this Emitter Manager's particles. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#frame + * @type {Phaser.Textures.Frame} + * @default null + * @since 3.0.0 + */ + this.frame = null; + + /** + * Names of this Emitter Manager's texture frames. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#frameNames + * @type {string[]} + * @since 3.0.0 + */ + this.frameNames = []; + + // frame is optional and can contain the emitters array or object if skipped + if (frame !== null && (typeof frame === 'object' || Array.isArray(frame))) + { + emitters = frame; + frame = null; + } + + this.setTexture(texture, frame); + + this.initPipeline(); + + /** + * A list of Emitters being managed by this Emitter Manager. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#emitters + * @type {Phaser.Structs.List.} + * @since 3.0.0 + */ + this.emitters = new List(this); + + /** + * A list of Gravity Wells being managed by this Emitter Manager. + * + * @name Phaser.GameObjects.Particles.ParticleEmitterManager#wells + * @type {Phaser.Structs.List.} + * @since 3.0.0 + */ + this.wells = new List(this); + + if (emitters) + { + // An array of emitter configs? + if (!Array.isArray(emitters)) + { + emitters = [ emitters ]; + } + + for (var i = 0; i < emitters.length; i++) + { + this.createEmitter(emitters[i]); + } + } + }, + + /** + * Sets the texture and frame this Emitter Manager will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setTexture + * @since 3.0.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Emitter Manager. + */ + setTexture: function (key, frame) + { + this.texture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Emitter Manager will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Emitter Manager. + */ + setFrame: function (frame) + { + this.frame = this.texture.get(frame); + + var frames = this.texture.getFramesFromTextureSource(this.frame.sourceIndex); + + var names = []; + + frames.forEach(function (sourceFrame) + { + names.push(sourceFrame.name); + }); + + this.frameNames = names; + + this.defaultFrame = this.frame; + + return this; + }, + + /** + * Assigns texture frames to an emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setEmitterFrames + * @since 3.0.0 + * + * @param {(Phaser.Textures.Frame|Phaser.Textures.Frame[])} frames - The texture frames. + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The particle emitter to modify. + * + * @return {this} This Emitter Manager. + */ + setEmitterFrames: function (frames, emitter) + { + if (!Array.isArray(frames)) + { + frames = [ frames ]; + } + + var out = emitter.frames; + + out.length = 0; + + for (var i = 0; i < frames.length; i++) + { + var frame = frames[i]; + + if (this.frameNames.indexOf(frame) !== -1) + { + out.push(this.texture.get(frame)); + } + } + + if (out.length > 0) + { + emitter.defaultFrame = out[0]; + } + else + { + emitter.defaultFrame = this.defaultFrame; + } + + return this; + }, + + /** + * Adds an existing Particle Emitter to this Emitter Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#addEmitter + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter - The Particle Emitter to add to this Emitter Manager. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter that was added to this Emitter Manager. + */ + addEmitter: function (emitter) + { + return this.emitters.add(emitter); + }, + + /** + * Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#createEmitter + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Configuration settings for the Particle Emitter to create. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter that was created. + */ + createEmitter: function (config) + { + return this.addEmitter(new ParticleEmitter(this, config)); + }, + + /** + * Removes a Particle Emitter from this Emitter Manager, if the Emitter belongs to this Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#removeEmitter + * @since 3.22.0 + * + * @param {Phaser.GameObjects.Particles.ParticleEmitter} emitter + * + * @return {?Phaser.GameObjects.Particles.ParticleEmitter} The Particle Emitter if it was removed or null if it was not. + */ + removeEmitter: function (emitter) + { + return this.emitters.remove(emitter, true); + }, + + /** + * Adds an existing Gravity Well object to this Emitter Manager. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#addGravityWell + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.GravityWell} well - The Gravity Well to add to this Emitter Manager. + * + * @return {Phaser.GameObjects.Particles.GravityWell} The Gravity Well that was added to this Emitter Manager. + */ + addGravityWell: function (well) + { + return this.wells.add(well); + }, + + /** + * Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#createGravityWell + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.GravityWellConfig} config - Configuration settings for the Gravity Well to create. + * + * @return {Phaser.GameObjects.Particles.GravityWell} The Gravity Well that was created. + */ + createGravityWell: function (config) + { + return this.addGravityWell(new GravityWell(config)); + }, + + /** + * Emits particles from each active emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#emitParticle + * @since 3.0.0 + * + * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. + * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. + * + * @return {this} This Emitter Manager. + */ + emitParticle: function (count, x, y) + { + var emitters = this.emitters.list; + + for (var i = 0; i < emitters.length; i++) + { + var emitter = emitters[i]; + + if (emitter.active) + { + emitter.emitParticle(count, x, y); + } + } + + return this; + }, + + /** + * Emits particles from each active emitter. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#emitParticleAt + * @since 3.0.0 + * + * @param {number} [x] - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. + * @param {number} [y] - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. + * @param {integer} [count] - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * + * @return {this} This Emitter Manager. + */ + emitParticleAt: function (x, y, count) + { + return this.emitParticle(count, x, y); + }, + + /** + * Pauses this Emitter Manager. + * + * This has the effect of pausing all emitters, and all particles of those emitters, currently under its control. + * + * The particles will still render, but they will not have any of their logic updated. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#pause + * @since 3.0.0 + * + * @return {this} This Emitter Manager. + */ + pause: function () + { + this.active = false; + + return this; + }, + + /** + * Resumes this Emitter Manager, should it have been previously paused. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#resume + * @since 3.0.0 + * + * @return {this} This Emitter Manager. + */ + resume: function () + { + this.active = true; + + return this; + }, + + /** + * Gets all active particle processors (gravity wells). + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#getProcessors + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Particles.GravityWell[]} - The active gravity wells. + */ + getProcessors: function () + { + return this.wells.getAll('active', true); + }, + + /** + * Updates all active emitters. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#preUpdate + * @since 3.0.0 + * + * @param {integer} 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. + */ + preUpdate: function (time, delta) + { + // Scale the delta + delta *= this.timeScale; + + var emitters = this.emitters.list; + + for (var i = 0; i < emitters.length; i++) + { + var emitter = emitters[i]; + + if (emitter.active) + { + emitter.preUpdate(time, delta); + } + } + }, + + /** + * A NOOP method so you can pass an EmitterManager to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setAlpha + * @private + * @since 3.10.0 + */ + setAlpha: function () + { + }, + + /** + * A NOOP method so you can pass an EmitterManager to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setScrollFactor + * @private + * @since 3.10.0 + */ + setScrollFactor: function () + { + }, + + /** + * A NOOP method so you can pass an EmitterManager to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Particles.ParticleEmitterManager#setBlendMode + * @private + * @since 3.15.0 + */ + setBlendMode: function () + { + } + +}); + +module.exports = ParticleEmitterManager; diff --git a/src/gameobjects/particles/ParticleManagerCanvasRenderer.js b/src/gameobjects/particles/ParticleManagerCanvasRenderer.js index 8ff328033..a8df16e6b 100644 --- a/src/gameobjects/particles/ParticleManagerCanvasRenderer.js +++ b/src/gameobjects/particles/ParticleManagerCanvasRenderer.js @@ -1,117 +1,117 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Particles.EmitterManager#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} emitterManager - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ParticleManagerCanvasRenderer = function (renderer, emitterManager, interpolationPercentage, camera, parentMatrix) -{ - var emitters = emitterManager.emitters.list; - var emittersLength = emitters.length; - - if (emittersLength === 0) - { - return; - } - - var camMatrix = renderer._tempMatrix1.copyFrom(camera.matrix); - var calcMatrix = renderer._tempMatrix2; - var particleMatrix = renderer._tempMatrix3; - var managerMatrix = renderer._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); - - camMatrix.multiply(managerMatrix); - - var roundPixels = camera.roundPixels; - - var ctx = renderer.currentContext; - - ctx.save(); - - for (var e = 0; e < emittersLength; e++) - { - var emitter = emitters[e]; - var particles = emitter.alive; - var particleCount = particles.length; - - if (!emitter.visible || particleCount === 0) - { - continue; - } - - var scrollX = camera.scrollX * emitter.scrollFactorX; - var scrollY = camera.scrollY * emitter.scrollFactorY; - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); - - scrollX = 0; - scrollY = 0; - } - - ctx.globalCompositeOperation = renderer.blendModes[emitter.blendMode]; - - for (var i = 0; i < particleCount; i++) - { - var particle = particles[i]; - - var alpha = particle.alpha * camera.alpha; - - if (alpha <= 0) - { - continue; - } - - var frame = particle.frame; - var cd = frame.canvasData; - - var x = -(frame.halfWidth); - var y = -(frame.halfHeight); - - particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); - - particleMatrix.e = particle.x - scrollX; - particleMatrix.f = particle.y - scrollY; - - camMatrix.multiply(particleMatrix, calcMatrix); - - ctx.globalAlpha = alpha; - - ctx.save(); - - calcMatrix.copyToContext(ctx); - - if (roundPixels) - { - x = Math.round(x); - y = Math.round(y); - } - - ctx.imageSmoothingEnabled = !(!renderer.antialias || frame.source.scaleMode); - - ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); - - ctx.restore(); - } - } - - ctx.restore(); -}; - -module.exports = ParticleManagerCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Particles.EmitterManager#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} emitterManager - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ParticleManagerCanvasRenderer = function (renderer, emitterManager, interpolationPercentage, camera, parentMatrix) +{ + var emitters = emitterManager.emitters.list; + var emittersLength = emitters.length; + + if (emittersLength === 0) + { + return; + } + + var camMatrix = renderer._tempMatrix1.copyFrom(camera.matrix); + var calcMatrix = renderer._tempMatrix2; + var particleMatrix = renderer._tempMatrix3; + var managerMatrix = renderer._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); + + camMatrix.multiply(managerMatrix); + + var roundPixels = camera.roundPixels; + + var ctx = renderer.currentContext; + + ctx.save(); + + for (var e = 0; e < emittersLength; e++) + { + var emitter = emitters[e]; + var particles = emitter.alive; + var particleCount = particles.length; + + if (!emitter.visible || particleCount === 0) + { + continue; + } + + var scrollX = camera.scrollX * emitter.scrollFactorX; + var scrollY = camera.scrollY * emitter.scrollFactorY; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); + + scrollX = 0; + scrollY = 0; + } + + ctx.globalCompositeOperation = renderer.blendModes[emitter.blendMode]; + + for (var i = 0; i < particleCount; i++) + { + var particle = particles[i]; + + var alpha = particle.alpha * camera.alpha; + + if (alpha <= 0) + { + continue; + } + + var frame = particle.frame; + var cd = frame.canvasData; + + var x = -(frame.halfWidth); + var y = -(frame.halfHeight); + + particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); + + particleMatrix.e = particle.x - scrollX; + particleMatrix.f = particle.y - scrollY; + + camMatrix.multiply(particleMatrix, calcMatrix); + + ctx.globalAlpha = alpha; + + ctx.save(); + + calcMatrix.copyToContext(ctx); + + if (roundPixels) + { + x = Math.round(x); + y = Math.round(y); + } + + ctx.imageSmoothingEnabled = !(!renderer.antialias || frame.source.scaleMode); + + ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); + + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = ParticleManagerCanvasRenderer; diff --git a/src/gameobjects/particles/ParticleManagerCreator.js b/src/gameobjects/particles/ParticleManagerCreator.js index 38272f7f8..f1177dd47 100644 --- a/src/gameobjects/particles/ParticleManagerCreator.js +++ b/src/gameobjects/particles/ParticleManagerCreator.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var ParticleEmitterManager = require('./ParticleEmitterManager'); - -/** - * Creates a new Particle Emitter Manager Game Object and returns it. - * - * 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 {object} 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.ParticleEmitterManager} The Game Object that was created. - */ -GameObjectCreator.register('particles', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - var emitters = GetFastValue(config, 'emitters', null); - - // frame is optional and can contain the emitters array or object if skipped - var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - var add = GetFastValue(config, 'add', false); - - if (add) - { - this.displayList.add(manager); - } - - this.updateList.add(manager); - - return manager; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var ParticleEmitterManager = require('./ParticleEmitterManager'); + +/** + * Creates a new Particle Emitter Manager Game Object and returns it. + * + * 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 {object} 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.ParticleEmitterManager} The Game Object that was created. + */ +GameObjectCreator.register('particles', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + var emitters = GetFastValue(config, 'emitters', null); + + // frame is optional and can contain the emitters array or object if skipped + var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + var add = GetFastValue(config, 'add', false); + + if (add) + { + this.displayList.add(manager); + } + + this.updateList.add(manager); + + return manager; +}); diff --git a/src/gameobjects/particles/ParticleManagerFactory.js b/src/gameobjects/particles/ParticleManagerFactory.js index 0781f2258..1a49b3ff4 100644 --- a/src/gameobjects/particles/ParticleManagerFactory.js +++ b/src/gameobjects/particles/ParticleManagerFactory.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../GameObjectFactory'); -var ParticleEmitterManager = require('./ParticleEmitterManager'); - -/** - * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Particles Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#particles - * @since 3.0.0 - * - * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer|object)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create. - * - * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} The Game Object that was created. - */ -GameObjectFactory.register('particles', function (key, frame, emitters) -{ - var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); - - this.displayList.add(manager); - this.updateList.add(manager); - - return manager; -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../GameObjectFactory'); +var ParticleEmitterManager = require('./ParticleEmitterManager'); + +/** + * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Particles Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#particles + * @since 3.0.0 + * + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer|object)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create. + * + * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} The Game Object that was created. + */ +GameObjectFactory.register('particles', function (key, frame, emitters) +{ + var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); + + this.displayList.add(manager); + this.updateList.add(manager); + + return manager; +}); + +// 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 diff --git a/src/gameobjects/particles/ParticleManagerRender.js b/src/gameobjects/particles/ParticleManagerRender.js index defbc212f..a351ac1c5 100644 --- a/src/gameobjects/particles/ParticleManagerRender.js +++ b/src/gameobjects/particles/ParticleManagerRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./ParticleManagerWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./ParticleManagerCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./ParticleManagerWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./ParticleManagerCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/particles/ParticleManagerWebGLRenderer.js b/src/gameobjects/particles/ParticleManagerWebGLRenderer.js index 036f8103e..914336b93 100644 --- a/src/gameobjects/particles/ParticleManagerWebGLRenderer.js +++ b/src/gameobjects/particles/ParticleManagerWebGLRenderer.js @@ -1,153 +1,153 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Particles.EmitterManager#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} emitterManager - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ParticleManagerWebGLRenderer = function (renderer, emitterManager, interpolationPercentage, camera, parentMatrix) -{ - var emitters = emitterManager.emitters.list; - var emittersLength = emitters.length; - - if (emittersLength === 0) - { - return; - } - - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1.copyFrom(camera.matrix); - var calcMatrix = pipeline._tempMatrix2; - var particleMatrix = pipeline._tempMatrix3; - var managerMatrix = pipeline._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); - - camMatrix.multiply(managerMatrix); - - renderer.setPipeline(pipeline); - - var roundPixels = camera.roundPixels; - var texture = emitterManager.defaultFrame.glTexture; - var getTint = Utils.getTintAppendFloatAlphaAndSwap; - - pipeline.setTexture2D(texture, 0); - - for (var e = 0; e < emittersLength; e++) - { - var emitter = emitters[e]; - var particles = emitter.alive; - var particleCount = particles.length; - - if (!emitter.visible || particleCount === 0) - { - continue; - } - - var scrollX = camera.scrollX * emitter.scrollFactorX; - var scrollY = camera.scrollY * emitter.scrollFactorY; - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); - - scrollX = 0; - scrollY = 0; - } - - if (renderer.setBlendMode(emitter.blendMode)) - { - // Rebind the texture if we've flushed - pipeline.setTexture2D(texture, 0); - } - - if (emitter.mask) - { - emitter.mask.preRenderWebGL(renderer, emitter, camera); - pipeline.setTexture2D(texture, 0); - } - - var tintEffect = 0; - - for (var i = 0; i < particleCount; i++) - { - var particle = particles[i]; - - var alpha = particle.alpha * camera.alpha; - - if (alpha <= 0) - { - continue; - } - - var frame = particle.frame; - - var x = -(frame.halfWidth); - var y = -(frame.halfHeight); - var xw = x + frame.width; - var yh = y + frame.height; - - particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); - - particleMatrix.e = particle.x - scrollX; - particleMatrix.f = particle.y - scrollY; - - camMatrix.multiply(particleMatrix, calcMatrix); - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(x, yh); - var ty1 = calcMatrix.getY(x, yh); - - var tx2 = calcMatrix.getX(xw, yh); - var ty2 = calcMatrix.getY(xw, yh); - - var tx3 = calcMatrix.getX(xw, y); - var ty3 = calcMatrix.getY(xw, y); - - if (roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - var tint = getTint(particle.tint, alpha); - - pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect, texture, 0); - } - - if (emitter.mask) - { - emitter.mask.postRenderWebGL(renderer, camera); - pipeline.setTexture2D(texture, 0); - } - } -}; - -module.exports = ParticleManagerWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Particles.EmitterManager#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Particles.ParticleEmitterManager} emitterManager - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ParticleManagerWebGLRenderer = function (renderer, emitterManager, interpolationPercentage, camera, parentMatrix) +{ + var emitters = emitterManager.emitters.list; + var emittersLength = emitters.length; + + if (emittersLength === 0) + { + return; + } + + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1.copyFrom(camera.matrix); + var calcMatrix = pipeline._tempMatrix2; + var particleMatrix = pipeline._tempMatrix3; + var managerMatrix = pipeline._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); + + camMatrix.multiply(managerMatrix); + + renderer.setPipeline(pipeline); + + var roundPixels = camera.roundPixels; + var texture = emitterManager.defaultFrame.glTexture; + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + + pipeline.setTexture2D(texture, 0); + + for (var e = 0; e < emittersLength; e++) + { + var emitter = emitters[e]; + var particles = emitter.alive; + var particleCount = particles.length; + + if (!emitter.visible || particleCount === 0) + { + continue; + } + + var scrollX = camera.scrollX * emitter.scrollFactorX; + var scrollY = camera.scrollY * emitter.scrollFactorY; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); + + scrollX = 0; + scrollY = 0; + } + + if (renderer.setBlendMode(emitter.blendMode)) + { + // Rebind the texture if we've flushed + pipeline.setTexture2D(texture, 0); + } + + if (emitter.mask) + { + emitter.mask.preRenderWebGL(renderer, emitter, camera); + pipeline.setTexture2D(texture, 0); + } + + var tintEffect = 0; + + for (var i = 0; i < particleCount; i++) + { + var particle = particles[i]; + + var alpha = particle.alpha * camera.alpha; + + if (alpha <= 0) + { + continue; + } + + var frame = particle.frame; + + var x = -(frame.halfWidth); + var y = -(frame.halfHeight); + var xw = x + frame.width; + var yh = y + frame.height; + + particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); + + particleMatrix.e = particle.x - scrollX; + particleMatrix.f = particle.y - scrollY; + + camMatrix.multiply(particleMatrix, calcMatrix); + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + var tint = getTint(particle.tint, alpha); + + pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect, texture, 0); + } + + if (emitter.mask) + { + emitter.mask.postRenderWebGL(renderer, camera); + pipeline.setTexture2D(texture, 0); + } + } +}; + +module.exports = ParticleManagerWebGLRenderer; diff --git a/src/gameobjects/particles/index.js b/src/gameobjects/particles/index.js index 1e25f1cc9..9be0876a7 100644 --- a/src/gameobjects/particles/index.js +++ b/src/gameobjects/particles/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.GameObjects.Particles - */ - -module.exports = { - - GravityWell: require('./GravityWell'), - Particle: require('./Particle'), - ParticleEmitter: require('./ParticleEmitter'), - ParticleEmitterManager: require('./ParticleEmitterManager'), - Zones: require('./zones') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Particles + */ + +module.exports = { + + GravityWell: require('./GravityWell'), + Particle: require('./Particle'), + ParticleEmitter: require('./ParticleEmitter'), + ParticleEmitterManager: require('./ParticleEmitterManager'), + Zones: require('./zones') + +}; diff --git a/src/gameobjects/particles/typedefs/index.js b/src/gameobjects/particles/typedefs/index.js index a476a464e..fa8c4df05 100644 --- a/src/gameobjects/particles/typedefs/index.js +++ b/src/gameobjects/particles/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.Particles - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.Particles + */ diff --git a/src/gameobjects/particles/zones/DeathZone.js b/src/gameobjects/particles/zones/DeathZone.js index 81fb9675e..b26977e94 100644 --- a/src/gameobjects/particles/zones/DeathZone.js +++ b/src/gameobjects/particles/zones/DeathZone.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); - -/** - * @classdesc - * A Death Zone. - * - * A Death Zone is a special type of zone that will kill a Particle as soon as it either enters, or leaves, the zone. - * - * The zone consists of a `source` which could be a Geometric shape, such as a Rectangle or Ellipse, or your own - * object as long as it includes a `contains` method for which the Particles can be tested against. - * - * @class DeathZone - * @memberof Phaser.GameObjects.Particles.Zones - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.DeathZoneSource} source - An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. - * @param {boolean} killOnEnter - Should the Particle be killed when it enters the zone? `true` or leaves it? `false` - */ -var DeathZone = new Class({ - - initialize: - - function DeathZone (source, killOnEnter) - { - /** - * An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. - * This could be a Geometry shape, such as `Phaser.Geom.Circle`, or your own custom object. - * - * @name Phaser.GameObjects.Particles.Zones.DeathZone#source - * @type {Phaser.Types.GameObjects.Particles.DeathZoneSource} - * @since 3.0.0 - */ - this.source = source; - - /** - * Set to `true` if the Particle should be killed if it enters this zone. - * Set to `false` to kill the Particle if it leaves this zone. - * - * @name Phaser.GameObjects.Particles.Zones.DeathZone#killOnEnter - * @type {boolean} - * @since 3.0.0 - */ - this.killOnEnter = killOnEnter; - }, - - /** - * Checks if the given Particle will be killed or not by this zone. - * - * @method Phaser.GameObjects.Particles.Zones.DeathZone#willKill - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle to be checked against this zone. - * - * @return {boolean} Return `true` if the Particle is to be killed, otherwise return `false`. - */ - willKill: function (particle) - { - var withinZone = this.source.contains(particle.x, particle.y); - - return (withinZone && this.killOnEnter || !withinZone && !this.killOnEnter); - } - -}); - -module.exports = DeathZone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); + +/** + * @classdesc + * A Death Zone. + * + * A Death Zone is a special type of zone that will kill a Particle as soon as it either enters, or leaves, the zone. + * + * The zone consists of a `source` which could be a Geometric shape, such as a Rectangle or Ellipse, or your own + * object as long as it includes a `contains` method for which the Particles can be tested against. + * + * @class DeathZone + * @memberof Phaser.GameObjects.Particles.Zones + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.DeathZoneSource} source - An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. + * @param {boolean} killOnEnter - Should the Particle be killed when it enters the zone? `true` or leaves it? `false` + */ +var DeathZone = new Class({ + + initialize: + + function DeathZone (source, killOnEnter) + { + /** + * An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. + * This could be a Geometry shape, such as `Phaser.Geom.Circle`, or your own custom object. + * + * @name Phaser.GameObjects.Particles.Zones.DeathZone#source + * @type {Phaser.Types.GameObjects.Particles.DeathZoneSource} + * @since 3.0.0 + */ + this.source = source; + + /** + * Set to `true` if the Particle should be killed if it enters this zone. + * Set to `false` to kill the Particle if it leaves this zone. + * + * @name Phaser.GameObjects.Particles.Zones.DeathZone#killOnEnter + * @type {boolean} + * @since 3.0.0 + */ + this.killOnEnter = killOnEnter; + }, + + /** + * Checks if the given Particle will be killed or not by this zone. + * + * @method Phaser.GameObjects.Particles.Zones.DeathZone#willKill + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle to be checked against this zone. + * + * @return {boolean} Return `true` if the Particle is to be killed, otherwise return `false`. + */ + willKill: function (particle) + { + var withinZone = this.source.contains(particle.x, particle.y); + + return (withinZone && this.killOnEnter || !withinZone && !this.killOnEnter); + } + +}); + +module.exports = DeathZone; diff --git a/src/gameobjects/particles/zones/EdgeZone.js b/src/gameobjects/particles/zones/EdgeZone.js index 43f321490..c8efbaeba 100644 --- a/src/gameobjects/particles/zones/EdgeZone.js +++ b/src/gameobjects/particles/zones/EdgeZone.js @@ -1,238 +1,238 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); - -/** - * @classdesc - * A zone that places particles on a shape's edges. - * - * @class EdgeZone - * @memberof Phaser.GameObjects.Particles.Zones - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. - * @param {integer} quantity - The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. - * @param {number} stepRate - The distance between each particle. When set, `quantity` is implied and should be set to 0. - * @param {boolean} [yoyo=false] - Whether particles are placed from start to end and then end to start. - * @param {boolean} [seamless=true] - Whether one endpoint will be removed if it's identical to the other. - */ -var EdgeZone = new Class({ - - initialize: - - function EdgeZone (source, quantity, stepRate, yoyo, seamless) - { - if (yoyo === undefined) { yoyo = false; } - if (seamless === undefined) { seamless = true; } - - /** - * An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#source - * @type {Phaser.Types.GameObjects.Particles.EdgeZoneSource|Phaser.Types.GameObjects.Particles.RandomZoneSource} - * @since 3.0.0 - */ - this.source = source; - - /** - * The points placed on the source edge. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#points - * @type {Phaser.Geom.Point[]} - * @default [] - * @since 3.0.0 - */ - this.points = []; - - /** - * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#quantity - * @type {integer} - * @since 3.0.0 - */ - this.quantity = quantity; - - /** - * The distance between each particle. When set, `quantity` is implied and should be set to 0. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#stepRate - * @type {number} - * @since 3.0.0 - */ - this.stepRate = stepRate; - - /** - * Whether particles are placed from start to end and then end to start. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#yoyo - * @type {boolean} - * @since 3.0.0 - */ - this.yoyo = yoyo; - - /** - * The counter used for iterating the EdgeZone's points. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#counter - * @type {number} - * @default -1 - * @since 3.0.0 - */ - this.counter = -1; - - /** - * Whether one endpoint will be removed if it's identical to the other. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#seamless - * @type {boolean} - * @since 3.0.0 - */ - this.seamless = seamless; - - /** - * An internal count of the points belonging to this EdgeZone. - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#_length - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._length = 0; - - /** - * An internal value used to keep track of the current iteration direction for the EdgeZone's points. - * - * 0 = forwards, 1 = backwards - * - * @name Phaser.GameObjects.Particles.Zones.EdgeZone#_direction - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._direction = 0; - - this.updateSource(); - }, - - /** - * Update the {@link Phaser.GameObjects.Particles.Zones.EdgeZone#points} from the EdgeZone's - * {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. - * - * Also updates internal properties. - * - * @method Phaser.GameObjects.Particles.Zones.EdgeZone#updateSource - * @since 3.0.0 - * - * @return {this} This Edge Zone. - */ - updateSource: function () - { - this.points = this.source.getPoints(this.quantity, this.stepRate); - - // Remove ends? - if (this.seamless) - { - var a = this.points[0]; - var b = this.points[this.points.length - 1]; - - if (a.x === b.x && a.y === b.y) - { - this.points.pop(); - } - } - - var oldLength = this._length; - - this._length = this.points.length; - - // Adjust counter if we now have less points than before - if (this._length < oldLength && this.counter > this._length) - { - this.counter = this._length - 1; - } - - return this; - }, - - /** - * Change the source of the EdgeZone. - * - * @method Phaser.GameObjects.Particles.Zones.EdgeZone#changeSource - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. - * - * @return {this} This Edge Zone. - */ - changeSource: function (source) - { - this.source = source; - - return this.updateSource(); - }, - - /** - * Get the next point in the Zone and set its coordinates on the given Particle. - * - * @method Phaser.GameObjects.Particles.Zones.EdgeZone#getPoint - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle. - */ - getPoint: function (particle) - { - if (this._direction === 0) - { - this.counter++; - - if (this.counter >= this._length) - { - if (this.yoyo) - { - this._direction = 1; - this.counter = this._length - 1; - } - else - { - this.counter = 0; - } - } - } - else - { - this.counter--; - - if (this.counter === -1) - { - if (this.yoyo) - { - this._direction = 0; - this.counter = 0; - } - else - { - this.counter = this._length - 1; - } - } - } - - var point = this.points[this.counter]; - - if (point) - { - particle.x = point.x; - particle.y = point.y; - } - } - -}); - -module.exports = EdgeZone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); + +/** + * @classdesc + * A zone that places particles on a shape's edges. + * + * @class EdgeZone + * @memberof Phaser.GameObjects.Particles.Zones + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * @param {integer} quantity - The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + * @param {number} stepRate - The distance between each particle. When set, `quantity` is implied and should be set to 0. + * @param {boolean} [yoyo=false] - Whether particles are placed from start to end and then end to start. + * @param {boolean} [seamless=true] - Whether one endpoint will be removed if it's identical to the other. + */ +var EdgeZone = new Class({ + + initialize: + + function EdgeZone (source, quantity, stepRate, yoyo, seamless) + { + if (yoyo === undefined) { yoyo = false; } + if (seamless === undefined) { seamless = true; } + + /** + * An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#source + * @type {Phaser.Types.GameObjects.Particles.EdgeZoneSource|Phaser.Types.GameObjects.Particles.RandomZoneSource} + * @since 3.0.0 + */ + this.source = source; + + /** + * The points placed on the source edge. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#points + * @type {Phaser.Geom.Point[]} + * @default [] + * @since 3.0.0 + */ + this.points = []; + + /** + * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#quantity + * @type {integer} + * @since 3.0.0 + */ + this.quantity = quantity; + + /** + * The distance between each particle. When set, `quantity` is implied and should be set to 0. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#stepRate + * @type {number} + * @since 3.0.0 + */ + this.stepRate = stepRate; + + /** + * Whether particles are placed from start to end and then end to start. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#yoyo + * @type {boolean} + * @since 3.0.0 + */ + this.yoyo = yoyo; + + /** + * The counter used for iterating the EdgeZone's points. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#counter + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.counter = -1; + + /** + * Whether one endpoint will be removed if it's identical to the other. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#seamless + * @type {boolean} + * @since 3.0.0 + */ + this.seamless = seamless; + + /** + * An internal count of the points belonging to this EdgeZone. + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#_length + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._length = 0; + + /** + * An internal value used to keep track of the current iteration direction for the EdgeZone's points. + * + * 0 = forwards, 1 = backwards + * + * @name Phaser.GameObjects.Particles.Zones.EdgeZone#_direction + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._direction = 0; + + this.updateSource(); + }, + + /** + * Update the {@link Phaser.GameObjects.Particles.Zones.EdgeZone#points} from the EdgeZone's + * {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. + * + * Also updates internal properties. + * + * @method Phaser.GameObjects.Particles.Zones.EdgeZone#updateSource + * @since 3.0.0 + * + * @return {this} This Edge Zone. + */ + updateSource: function () + { + this.points = this.source.getPoints(this.quantity, this.stepRate); + + // Remove ends? + if (this.seamless) + { + var a = this.points[0]; + var b = this.points[this.points.length - 1]; + + if (a.x === b.x && a.y === b.y) + { + this.points.pop(); + } + } + + var oldLength = this._length; + + this._length = this.points.length; + + // Adjust counter if we now have less points than before + if (this._length < oldLength && this.counter > this._length) + { + this.counter = this._length - 1; + } + + return this; + }, + + /** + * Change the source of the EdgeZone. + * + * @method Phaser.GameObjects.Particles.Zones.EdgeZone#changeSource + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.EdgeZoneSource} source - An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * + * @return {this} This Edge Zone. + */ + changeSource: function (source) + { + this.source = source; + + return this.updateSource(); + }, + + /** + * Get the next point in the Zone and set its coordinates on the given Particle. + * + * @method Phaser.GameObjects.Particles.Zones.EdgeZone#getPoint + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle. + */ + getPoint: function (particle) + { + if (this._direction === 0) + { + this.counter++; + + if (this.counter >= this._length) + { + if (this.yoyo) + { + this._direction = 1; + this.counter = this._length - 1; + } + else + { + this.counter = 0; + } + } + } + else + { + this.counter--; + + if (this.counter === -1) + { + if (this.yoyo) + { + this._direction = 0; + this.counter = 0; + } + else + { + this.counter = this._length - 1; + } + } + } + + var point = this.points[this.counter]; + + if (point) + { + particle.x = point.x; + particle.y = point.y; + } + } + +}); + +module.exports = EdgeZone; diff --git a/src/gameobjects/particles/zones/RandomZone.js b/src/gameobjects/particles/zones/RandomZone.js index 72fd05e4f..5876a2285 100644 --- a/src/gameobjects/particles/zones/RandomZone.js +++ b/src/gameobjects/particles/zones/RandomZone.js @@ -1,67 +1,67 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Vector2 = require('../../../math/Vector2'); - -/** - * @classdesc - * A zone that places particles randomly within a shape's area. - * - * @class RandomZone - * @memberof Phaser.GameObjects.Particles.Zones - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Particles.RandomZoneSource} source - An object instance with a `getRandomPoint(point)` method. - */ -var RandomZone = new Class({ - - initialize: - - function RandomZone (source) - { - /** - * An object instance with a `getRandomPoint(point)` method. - * - * @name Phaser.GameObjects.Particles.Zones.RandomZone#source - * @type {Phaser.Types.GameObjects.Particles.RandomZoneSource} - * @since 3.0.0 - */ - this.source = source; - - /** - * Internal calculation vector. - * - * @name Phaser.GameObjects.Particles.Zones.RandomZone#_tempVec - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tempVec = new Vector2(); - }, - - /** - * Get the next point in the Zone and set its coordinates on the given Particle. - * - * @method Phaser.GameObjects.Particles.Zones.RandomZone#getPoint - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle. - */ - getPoint: function (particle) - { - var vec = this._tempVec; - - this.source.getRandomPoint(vec); - - particle.x = vec.x; - particle.y = vec.y; - } - -}); - -module.exports = RandomZone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Vector2 = require('../../../math/Vector2'); + +/** + * @classdesc + * A zone that places particles randomly within a shape's area. + * + * @class RandomZone + * @memberof Phaser.GameObjects.Particles.Zones + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Particles.RandomZoneSource} source - An object instance with a `getRandomPoint(point)` method. + */ +var RandomZone = new Class({ + + initialize: + + function RandomZone (source) + { + /** + * An object instance with a `getRandomPoint(point)` method. + * + * @name Phaser.GameObjects.Particles.Zones.RandomZone#source + * @type {Phaser.Types.GameObjects.Particles.RandomZoneSource} + * @since 3.0.0 + */ + this.source = source; + + /** + * Internal calculation vector. + * + * @name Phaser.GameObjects.Particles.Zones.RandomZone#_tempVec + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tempVec = new Vector2(); + }, + + /** + * Get the next point in the Zone and set its coordinates on the given Particle. + * + * @method Phaser.GameObjects.Particles.Zones.RandomZone#getPoint + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Particles.Particle} particle - The Particle. + */ + getPoint: function (particle) + { + var vec = this._tempVec; + + this.source.getRandomPoint(vec); + + particle.x = vec.x; + particle.y = vec.y; + } + +}); + +module.exports = RandomZone; diff --git a/src/gameobjects/particles/zones/index.js b/src/gameobjects/particles/zones/index.js index 890dbdaf5..3650c441c 100644 --- a/src/gameobjects/particles/zones/index.js +++ b/src/gameobjects/particles/zones/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.GameObjects.Particles.Zones - */ - -module.exports = { - - DeathZone: require('./DeathZone'), - EdgeZone: require('./EdgeZone'), - RandomZone: require('./RandomZone') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.GameObjects.Particles.Zones + */ + +module.exports = { + + DeathZone: require('./DeathZone'), + EdgeZone: require('./EdgeZone'), + RandomZone: require('./RandomZone') + +}; diff --git a/src/gameobjects/pathfollower/PathFollower.js b/src/gameobjects/pathfollower/PathFollower.js index 677344ddd..c762b3522 100644 --- a/src/gameobjects/pathfollower/PathFollower.js +++ b/src/gameobjects/pathfollower/PathFollower.js @@ -1,76 +1,76 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var Sprite = require('../sprite/Sprite'); - -/** - * @classdesc - * A PathFollower Game Object. - * - * A PathFollower is a Sprite Game Object with some extra helpers to allow it to follow a Path automatically. - * - * Anything you can do with a standard Sprite can be done with this PathFollower, such as animate it, tint it, - * scale it and so on. - * - * PathFollowers are bound to a single Path at any one time and can traverse the length of the Path, from start - * to finish, forwards or backwards, or from any given point on the Path to its end. They can optionally rotate - * to face the direction of the path, be offset from the path coordinates or rotate independently of the Path. - * - * @class PathFollower - * @extends Phaser.GameObjects.Sprite - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @extends Phaser.GameObjects.Components.PathFollower - * - * @param {Phaser.Scene} scene - The Scene to which this PathFollower belongs. - * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var PathFollower = new Class({ - - Extends: Sprite, - - Mixins: [ - Components.PathFollower - ], - - initialize: - - function PathFollower (scene, path, x, y, texture, frame) - { - Sprite.call(this, scene, x, y, texture, frame); - - this.path = path; - }, - - /** - * Internal update handler that advances this PathFollower along the path. - * - * Called automatically by the Scene step, should not typically be called directly. - * - * @method Phaser.GameObjects.PathFollower#preUpdate - * @protected - * @since 3.0.0 - * - * @param {integer} 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. - */ - preUpdate: function (time, delta) - { - this.anims.update(time, delta); - this.pathUpdate(time); - } - -}); - -module.exports = PathFollower; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var Sprite = require('../sprite/Sprite'); + +/** + * @classdesc + * A PathFollower Game Object. + * + * A PathFollower is a Sprite Game Object with some extra helpers to allow it to follow a Path automatically. + * + * Anything you can do with a standard Sprite can be done with this PathFollower, such as animate it, tint it, + * scale it and so on. + * + * PathFollowers are bound to a single Path at any one time and can traverse the length of the Path, from start + * to finish, forwards or backwards, or from any given point on the Path to its end. They can optionally rotate + * to face the direction of the path, be offset from the path coordinates or rotate independently of the Path. + * + * @class PathFollower + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.PathFollower + * + * @param {Phaser.Scene} scene - The Scene to which this PathFollower belongs. + * @param {Phaser.Curves.Path} path - The Path this PathFollower is following. It can only follow one Path 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var PathFollower = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.PathFollower + ], + + initialize: + + function PathFollower (scene, path, x, y, texture, frame) + { + Sprite.call(this, scene, x, y, texture, frame); + + this.path = path; + }, + + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + * + * @method Phaser.GameObjects.PathFollower#preUpdate + * @protected + * @since 3.0.0 + * + * @param {integer} 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. + */ + preUpdate: function (time, delta) + { + this.anims.update(time, delta); + this.pathUpdate(time); + } + +}); + +module.exports = PathFollower; diff --git a/src/gameobjects/pathfollower/PathFollowerFactory.js b/src/gameobjects/pathfollower/PathFollowerFactory.js index b3f389217..51c11f393 100644 --- a/src/gameobjects/pathfollower/PathFollowerFactory.js +++ b/src/gameobjects/pathfollower/PathFollowerFactory.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../GameObjectFactory'); -var PathFollower = require('./PathFollower'); - -/** - * Creates a new PathFollower Game Object and adds it to the Scene. - * - * Note: This method will only be available if the PathFollower Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#follower - * @since 3.0.0 - * - * @param {Phaser.Curves.Path} path - The Path this PathFollower is connected to. - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.PathFollower} The Game Object that was created. - */ -GameObjectFactory.register('follower', function (path, x, y, key, frame) -{ - var sprite = new PathFollower(this.scene, path, x, y, key, frame); - - this.displayList.add(sprite); - this.updateList.add(sprite); - - return sprite; -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../GameObjectFactory'); +var PathFollower = require('./PathFollower'); + +/** + * Creates a new PathFollower Game Object and adds it to the Scene. + * + * Note: This method will only be available if the PathFollower Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#follower + * @since 3.0.0 + * + * @param {Phaser.Curves.Path} path - The Path this PathFollower is connected to. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.PathFollower} The Game Object that was created. + */ +GameObjectFactory.register('follower', function (path, x, y, key, frame) +{ + var sprite = new PathFollower(this.scene, path, x, y, key, frame); + + this.displayList.add(sprite); + this.updateList.add(sprite); + + return sprite; +}); + +// 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 diff --git a/src/gameobjects/pathfollower/typedefs/index.js b/src/gameobjects/pathfollower/typedefs/index.js index 191dd49ae..a03fdca4e 100644 --- a/src/gameobjects/pathfollower/typedefs/index.js +++ b/src/gameobjects/pathfollower/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.PathFollower - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.PathFollower + */ diff --git a/src/gameobjects/quad/Quad.js b/src/gameobjects/quad/Quad.js index 517a6cb48..5205f0439 100644 --- a/src/gameobjects/quad/Quad.js +++ b/src/gameobjects/quad/Quad.js @@ -1,655 +1,655 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Mesh = require('../mesh/Mesh'); - -/** - * @classdesc - * A Quad Game Object. - * - * A Quad is a Mesh Game Object pre-configured with two triangles arranged into a rectangle, with a single - * texture spread across them. - * - * You can manipulate the corner points of the quad via the getters and setters such as `topLeftX`, and also - * change their alpha and color values. The quad itself can be moved by adjusting the `x` and `y` properties. - * - * @class Quad - * @extends Phaser.GameObjects.Mesh - * @memberof Phaser.GameObjects - * @constructor - * @webglOnly - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Quad 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 {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var Quad = new Class({ - - Extends: Mesh, - - initialize: - - function Quad (scene, x, y, texture, frame) - { - // 0----3 - // |\ B| - // | \ | - // | \ | - // | A \| - // | \ - // 1----2 - - var vertices = [ - 0, 0, // tl - 0, 0, // bl - 0, 0, // br - 0, 0, // tl - 0, 0, // br - 0, 0 // tr - ]; - - var uv = [ - 0, 0, // tl - 0, 1, // bl - 1, 1, // br - 0, 0, // tl - 1, 1, // br - 1, 0 // tr - ]; - - var colors = [ - 0xffffff, // tl - 0xffffff, // bl - 0xffffff, // br - 0xffffff, // tl - 0xffffff, // br - 0xffffff // tr - ]; - - var alphas = [ - 1, // tl - 1, // bl - 1, // br - 1, // tl - 1, // br - 1 // tr - ]; - - Mesh.call(this, scene, x, y, vertices, uv, colors, alphas, texture, frame); - - this.resetPosition(); - }, - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * - * @method Phaser.GameObjects.Quad#setFrame - * @since 3.11.0 - * - * @param {(string|integer)} frame - The name or index of the frame within the Texture. - * - * @return {this} This Game Object instance. - */ - setFrame: function (frame) - { - this.frame = this.texture.get(frame); - - if (!this.frame.cutWidth || !this.frame.cutHeight) - { - this.renderFlags &= ~8; - } - else - { - this.renderFlags |= 8; - } - - frame = this.frame; - - // TL - this.uv[0] = frame.u0; - this.uv[1] = frame.v0; - - // BL - this.uv[2] = frame.u0; - this.uv[3] = frame.v1; - - // BR - this.uv[4] = frame.u1; - this.uv[5] = frame.v1; - - // TL - this.uv[6] = frame.u0; - this.uv[7] = frame.v0; - - // BR - this.uv[8] = frame.u1; - this.uv[9] = frame.v1; - - // TR - this.uv[10] = frame.u1; - this.uv[11] = frame.v0; - - return this; - }, - - /** - * The top-left x vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#topLeftX - * @type {number} - * @since 3.0.0 - */ - topLeftX: { - - get: function () - { - return this.x + this.vertices[0]; - }, - - set: function (value) - { - this.vertices[0] = value - this.x; - this.vertices[6] = value - this.x; - } - - }, - - /** - * The top-left y vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#topLeftY - * @type {number} - * @since 3.0.0 - */ - topLeftY: { - - get: function () - { - return this.y + this.vertices[1]; - }, - - set: function (value) - { - this.vertices[1] = value - this.y; - this.vertices[7] = value - this.y; - } - - }, - - /** - * The top-right x vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#topRightX - * @type {number} - * @since 3.0.0 - */ - topRightX: { - - get: function () - { - return this.x + this.vertices[10]; - }, - - set: function (value) - { - this.vertices[10] = value - this.x; - } - - }, - - /** - * The top-right y vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#topRightY - * @type {number} - * @since 3.0.0 - */ - topRightY: { - - get: function () - { - return this.y + this.vertices[11]; - }, - - set: function (value) - { - this.vertices[11] = value - this.y; - } - - }, - - /** - * The bottom-left x vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomLeftX - * @type {number} - * @since 3.0.0 - */ - bottomLeftX: { - - get: function () - { - return this.x + this.vertices[2]; - }, - - set: function (value) - { - this.vertices[2] = value - this.x; - } - - }, - - /** - * The bottom-left y vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomLeftY - * @type {number} - * @since 3.0.0 - */ - bottomLeftY: { - - get: function () - { - return this.y + this.vertices[3]; - }, - - set: function (value) - { - this.vertices[3] = value - this.y; - } - - }, - - /** - * The bottom-right x vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomRightX - * @type {number} - * @since 3.0.0 - */ - bottomRightX: { - - get: function () - { - return this.x + this.vertices[4]; - }, - - set: function (value) - { - this.vertices[4] = value - this.x; - this.vertices[8] = value - this.x; - } - - }, - - /** - * The bottom-right y vertex of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomRightY - * @type {number} - * @since 3.0.0 - */ - bottomRightY: { - - get: function () - { - return this.y + this.vertices[5]; - }, - - set: function (value) - { - this.vertices[5] = value - this.y; - this.vertices[9] = value - this.y; - } - - }, - - /** - * The top-left alpha value of this Quad. - * - * @name Phaser.GameObjects.Quad#topLeftAlpha - * @type {number} - * @since 3.0.0 - */ - topLeftAlpha: { - - get: function () - { - return this.alphas[0]; - }, - - set: function (value) - { - this.alphas[0] = value; - this.alphas[3] = value; - } - - }, - - /** - * The top-right alpha value of this Quad. - * - * @name Phaser.GameObjects.Quad#topRightAlpha - * @type {number} - * @since 3.0.0 - */ - topRightAlpha: { - - get: function () - { - return this.alphas[5]; - }, - - set: function (value) - { - this.alphas[5] = value; - } - - }, - - /** - * The bottom-left alpha value of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomLeftAlpha - * @type {number} - * @since 3.0.0 - */ - bottomLeftAlpha: { - - get: function () - { - return this.alphas[1]; - }, - - set: function (value) - { - this.alphas[1] = value; - } - - }, - - /** - * The bottom-right alpha value of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomRightAlpha - * @type {number} - * @since 3.0.0 - */ - bottomRightAlpha: { - - get: function () - { - return this.alphas[2]; - }, - - set: function (value) - { - this.alphas[2] = value; - this.alphas[4] = value; - } - - }, - - /** - * The top-left color value of this Quad. - * - * @name Phaser.GameObjects.Quad#topLeftColor - * @type {number} - * @since 3.0.0 - */ - topLeftColor: { - - get: function () - { - return this.colors[0]; - }, - - set: function (value) - { - this.colors[0] = value; - this.colors[3] = value; - } - - }, - - /** - * The top-right color value of this Quad. - * - * @name Phaser.GameObjects.Quad#topRightColor - * @type {number} - * @since 3.0.0 - */ - topRightColor: { - - get: function () - { - return this.colors[5]; - }, - - set: function (value) - { - this.colors[5] = value; - } - - }, - - /** - * The bottom-left color value of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomLeftColor - * @type {number} - * @since 3.0.0 - */ - bottomLeftColor: { - - get: function () - { - return this.colors[1]; - }, - - set: function (value) - { - this.colors[1] = value; - } - - }, - - /** - * The bottom-right color value of this Quad. - * - * @name Phaser.GameObjects.Quad#bottomRightColor - * @type {number} - * @since 3.0.0 - */ - bottomRightColor: { - - get: function () - { - return this.colors[2]; - }, - - set: function (value) - { - this.colors[2] = value; - this.colors[4] = value; - } - - }, - - /** - * Sets the top-left vertex position of this Quad. - * - * @method Phaser.GameObjects.Quad#setTopLeft - * @since 3.0.0 - * - * @param {number} x - The horizontal coordinate of the vertex. - * @param {number} y - The vertical coordinate of the vertex. - * - * @return {this} This Game Object. - */ - setTopLeft: function (x, y) - { - this.topLeftX = x; - this.topLeftY = y; - - return this; - }, - - /** - * Sets the top-right vertex position of this Quad. - * - * @method Phaser.GameObjects.Quad#setTopRight - * @since 3.0.0 - * - * @param {number} x - The horizontal coordinate of the vertex. - * @param {number} y - The vertical coordinate of the vertex. - * - * @return {this} This Game Object. - */ - setTopRight: function (x, y) - { - this.topRightX = x; - this.topRightY = y; - - return this; - }, - - /** - * Sets the bottom-left vertex position of this Quad. - * - * @method Phaser.GameObjects.Quad#setBottomLeft - * @since 3.0.0 - * - * @param {number} x - The horizontal coordinate of the vertex. - * @param {number} y - The vertical coordinate of the vertex. - * - * @return {this} This Game Object. - */ - setBottomLeft: function (x, y) - { - this.bottomLeftX = x; - this.bottomLeftY = y; - - return this; - }, - - /** - * Sets the bottom-right vertex position of this Quad. - * - * @method Phaser.GameObjects.Quad#setBottomRight - * @since 3.0.0 - * - * @param {number} x - The horizontal coordinate of the vertex. - * @param {number} y - The vertical coordinate of the vertex. - * - * @return {this} This Game Object. - */ - setBottomRight: function (x, y) - { - this.bottomRightX = x; - this.bottomRightY = y; - - return this; - }, - - /** - * Resets the positions of the four corner vertices of this Quad. - * - * @method Phaser.GameObjects.Quad#resetPosition - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - resetPosition: function () - { - var x = this.x; - var y = this.y; - var halfWidth = Math.floor(this.width / 2); - var halfHeight = Math.floor(this.height / 2); - - this.setTopLeft(x - halfWidth, y - halfHeight); - this.setTopRight(x + halfWidth, y - halfHeight); - this.setBottomLeft(x - halfWidth, y + halfHeight); - this.setBottomRight(x + halfWidth, y + halfHeight); - - return this; - }, - - /** - * Resets the alpha values used by this Quad back to 1. - * - * @method Phaser.GameObjects.Quad#resetAlpha - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - resetAlpha: function () - { - var alphas = this.alphas; - - alphas[0] = 1; - alphas[1] = 1; - alphas[2] = 1; - alphas[3] = 1; - alphas[4] = 1; - alphas[5] = 1; - - return this; - }, - - /** - * Resets the color values used by this Quad back to 0xffffff. - * - * @method Phaser.GameObjects.Quad#resetColors - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - resetColors: function () - { - var colors = this.colors; - - colors[0] = 0xffffff; - colors[1] = 0xffffff; - colors[2] = 0xffffff; - colors[3] = 0xffffff; - colors[4] = 0xffffff; - colors[5] = 0xffffff; - - return this; - }, - - /** - * Resets the position, alpha and color values used by this Quad. - * - * @method Phaser.GameObjects.Quad#reset - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - reset: function () - { - this.resetPosition(); - - this.resetAlpha(); - - return this.resetColors(); - } - -}); - -module.exports = Quad; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Mesh = require('../mesh/Mesh'); + +/** + * @classdesc + * A Quad Game Object. + * + * A Quad is a Mesh Game Object pre-configured with two triangles arranged into a rectangle, with a single + * texture spread across them. + * + * You can manipulate the corner points of the quad via the getters and setters such as `topLeftX`, and also + * change their alpha and color values. The quad itself can be moved by adjusting the `x` and `y` properties. + * + * @class Quad + * @extends Phaser.GameObjects.Mesh + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Quad 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 {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Quad = new Class({ + + Extends: Mesh, + + initialize: + + function Quad (scene, x, y, texture, frame) + { + // 0----3 + // |\ B| + // | \ | + // | \ | + // | A \| + // | \ + // 1----2 + + var vertices = [ + 0, 0, // tl + 0, 0, // bl + 0, 0, // br + 0, 0, // tl + 0, 0, // br + 0, 0 // tr + ]; + + var uv = [ + 0, 0, // tl + 0, 1, // bl + 1, 1, // br + 0, 0, // tl + 1, 1, // br + 1, 0 // tr + ]; + + var colors = [ + 0xffffff, // tl + 0xffffff, // bl + 0xffffff, // br + 0xffffff, // tl + 0xffffff, // br + 0xffffff // tr + ]; + + var alphas = [ + 1, // tl + 1, // bl + 1, // br + 1, // tl + 1, // br + 1 // tr + ]; + + Mesh.call(this, scene, x, y, vertices, uv, colors, alphas, texture, frame); + + this.resetPosition(); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * + * @method Phaser.GameObjects.Quad#setFrame + * @since 3.11.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame) + { + this.frame = this.texture.get(frame); + + if (!this.frame.cutWidth || !this.frame.cutHeight) + { + this.renderFlags &= ~8; + } + else + { + this.renderFlags |= 8; + } + + frame = this.frame; + + // TL + this.uv[0] = frame.u0; + this.uv[1] = frame.v0; + + // BL + this.uv[2] = frame.u0; + this.uv[3] = frame.v1; + + // BR + this.uv[4] = frame.u1; + this.uv[5] = frame.v1; + + // TL + this.uv[6] = frame.u0; + this.uv[7] = frame.v0; + + // BR + this.uv[8] = frame.u1; + this.uv[9] = frame.v1; + + // TR + this.uv[10] = frame.u1; + this.uv[11] = frame.v0; + + return this; + }, + + /** + * The top-left x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftX + * @type {number} + * @since 3.0.0 + */ + topLeftX: { + + get: function () + { + return this.x + this.vertices[0]; + }, + + set: function (value) + { + this.vertices[0] = value - this.x; + this.vertices[6] = value - this.x; + } + + }, + + /** + * The top-left y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftY + * @type {number} + * @since 3.0.0 + */ + topLeftY: { + + get: function () + { + return this.y + this.vertices[1]; + }, + + set: function (value) + { + this.vertices[1] = value - this.y; + this.vertices[7] = value - this.y; + } + + }, + + /** + * The top-right x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightX + * @type {number} + * @since 3.0.0 + */ + topRightX: { + + get: function () + { + return this.x + this.vertices[10]; + }, + + set: function (value) + { + this.vertices[10] = value - this.x; + } + + }, + + /** + * The top-right y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightY + * @type {number} + * @since 3.0.0 + */ + topRightY: { + + get: function () + { + return this.y + this.vertices[11]; + }, + + set: function (value) + { + this.vertices[11] = value - this.y; + } + + }, + + /** + * The bottom-left x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftX + * @type {number} + * @since 3.0.0 + */ + bottomLeftX: { + + get: function () + { + return this.x + this.vertices[2]; + }, + + set: function (value) + { + this.vertices[2] = value - this.x; + } + + }, + + /** + * The bottom-left y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftY + * @type {number} + * @since 3.0.0 + */ + bottomLeftY: { + + get: function () + { + return this.y + this.vertices[3]; + }, + + set: function (value) + { + this.vertices[3] = value - this.y; + } + + }, + + /** + * The bottom-right x vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightX + * @type {number} + * @since 3.0.0 + */ + bottomRightX: { + + get: function () + { + return this.x + this.vertices[4]; + }, + + set: function (value) + { + this.vertices[4] = value - this.x; + this.vertices[8] = value - this.x; + } + + }, + + /** + * The bottom-right y vertex of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightY + * @type {number} + * @since 3.0.0 + */ + bottomRightY: { + + get: function () + { + return this.y + this.vertices[5]; + }, + + set: function (value) + { + this.vertices[5] = value - this.y; + this.vertices[9] = value - this.y; + } + + }, + + /** + * The top-left alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftAlpha + * @type {number} + * @since 3.0.0 + */ + topLeftAlpha: { + + get: function () + { + return this.alphas[0]; + }, + + set: function (value) + { + this.alphas[0] = value; + this.alphas[3] = value; + } + + }, + + /** + * The top-right alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightAlpha + * @type {number} + * @since 3.0.0 + */ + topRightAlpha: { + + get: function () + { + return this.alphas[5]; + }, + + set: function (value) + { + this.alphas[5] = value; + } + + }, + + /** + * The bottom-left alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftAlpha + * @type {number} + * @since 3.0.0 + */ + bottomLeftAlpha: { + + get: function () + { + return this.alphas[1]; + }, + + set: function (value) + { + this.alphas[1] = value; + } + + }, + + /** + * The bottom-right alpha value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightAlpha + * @type {number} + * @since 3.0.0 + */ + bottomRightAlpha: { + + get: function () + { + return this.alphas[2]; + }, + + set: function (value) + { + this.alphas[2] = value; + this.alphas[4] = value; + } + + }, + + /** + * The top-left color value of this Quad. + * + * @name Phaser.GameObjects.Quad#topLeftColor + * @type {number} + * @since 3.0.0 + */ + topLeftColor: { + + get: function () + { + return this.colors[0]; + }, + + set: function (value) + { + this.colors[0] = value; + this.colors[3] = value; + } + + }, + + /** + * The top-right color value of this Quad. + * + * @name Phaser.GameObjects.Quad#topRightColor + * @type {number} + * @since 3.0.0 + */ + topRightColor: { + + get: function () + { + return this.colors[5]; + }, + + set: function (value) + { + this.colors[5] = value; + } + + }, + + /** + * The bottom-left color value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomLeftColor + * @type {number} + * @since 3.0.0 + */ + bottomLeftColor: { + + get: function () + { + return this.colors[1]; + }, + + set: function (value) + { + this.colors[1] = value; + } + + }, + + /** + * The bottom-right color value of this Quad. + * + * @name Phaser.GameObjects.Quad#bottomRightColor + * @type {number} + * @since 3.0.0 + */ + bottomRightColor: { + + get: function () + { + return this.colors[2]; + }, + + set: function (value) + { + this.colors[2] = value; + this.colors[4] = value; + } + + }, + + /** + * Sets the top-left vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setTopLeft + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {this} This Game Object. + */ + setTopLeft: function (x, y) + { + this.topLeftX = x; + this.topLeftY = y; + + return this; + }, + + /** + * Sets the top-right vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setTopRight + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {this} This Game Object. + */ + setTopRight: function (x, y) + { + this.topRightX = x; + this.topRightY = y; + + return this; + }, + + /** + * Sets the bottom-left vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setBottomLeft + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {this} This Game Object. + */ + setBottomLeft: function (x, y) + { + this.bottomLeftX = x; + this.bottomLeftY = y; + + return this; + }, + + /** + * Sets the bottom-right vertex position of this Quad. + * + * @method Phaser.GameObjects.Quad#setBottomRight + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate of the vertex. + * @param {number} y - The vertical coordinate of the vertex. + * + * @return {this} This Game Object. + */ + setBottomRight: function (x, y) + { + this.bottomRightX = x; + this.bottomRightY = y; + + return this; + }, + + /** + * Resets the positions of the four corner vertices of this Quad. + * + * @method Phaser.GameObjects.Quad#resetPosition + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + resetPosition: function () + { + var x = this.x; + var y = this.y; + var halfWidth = Math.floor(this.width / 2); + var halfHeight = Math.floor(this.height / 2); + + this.setTopLeft(x - halfWidth, y - halfHeight); + this.setTopRight(x + halfWidth, y - halfHeight); + this.setBottomLeft(x - halfWidth, y + halfHeight); + this.setBottomRight(x + halfWidth, y + halfHeight); + + return this; + }, + + /** + * Resets the alpha values used by this Quad back to 1. + * + * @method Phaser.GameObjects.Quad#resetAlpha + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + resetAlpha: function () + { + var alphas = this.alphas; + + alphas[0] = 1; + alphas[1] = 1; + alphas[2] = 1; + alphas[3] = 1; + alphas[4] = 1; + alphas[5] = 1; + + return this; + }, + + /** + * Resets the color values used by this Quad back to 0xffffff. + * + * @method Phaser.GameObjects.Quad#resetColors + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + resetColors: function () + { + var colors = this.colors; + + colors[0] = 0xffffff; + colors[1] = 0xffffff; + colors[2] = 0xffffff; + colors[3] = 0xffffff; + colors[4] = 0xffffff; + colors[5] = 0xffffff; + + return this; + }, + + /** + * Resets the position, alpha and color values used by this Quad. + * + * @method Phaser.GameObjects.Quad#reset + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + reset: function () + { + this.resetPosition(); + + this.resetAlpha(); + + return this.resetColors(); + } + +}); + +module.exports = Quad; diff --git a/src/gameobjects/quad/QuadCreator.js b/src/gameobjects/quad/QuadCreator.js index df7d56e99..4cb4e162e 100644 --- a/src/gameobjects/quad/QuadCreator.js +++ b/src/gameobjects/quad/QuadCreator.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var Quad = require('./Quad'); - -/** - * Creates a new Quad Game Object and returns it. - * - * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#quad - * @since 3.0.0 - * - * @param {object} 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.Quad} The Game Object that was created. - */ -GameObjectCreator.register('quad', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var x = GetAdvancedValue(config, 'x', 0); - var y = GetAdvancedValue(config, 'y', 0); - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - - var quad = new Quad(this.scene, x, y, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, quad, config); - - return quad; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var Quad = require('./Quad'); + +/** + * Creates a new Quad Game Object and returns it. + * + * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#quad + * @since 3.0.0 + * + * @param {object} 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.Quad} The Game Object that was created. + */ +GameObjectCreator.register('quad', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var quad = new Quad(this.scene, x, y, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, quad, config); + + return quad; +}); diff --git a/src/gameobjects/quad/QuadFactory.js b/src/gameobjects/quad/QuadFactory.js index 42c1dd32e..efa81cd48 100644 --- a/src/gameobjects/quad/QuadFactory.js +++ b/src/gameobjects/quad/QuadFactory.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Quad = require('./Quad'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Quad Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#quad - * @webglOnly - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.Quad} The Game Object that was created. - */ -if (typeof WEBGL_RENDERER) -{ - GameObjectFactory.register('quad', function (x, y, key, frame) - { - return this.displayList.add(new Quad(this.scene, x, y, key, frame)); - }); -} - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Quad = require('./Quad'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Quad Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#quad + * @webglOnly + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Quad} The Game Object that was created. + */ +if (typeof WEBGL_RENDERER) +{ + GameObjectFactory.register('quad', function (x, y, key, frame) + { + return this.displayList.add(new Quad(this.scene, x, y, key, frame)); + }); +} + +// 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 diff --git a/src/gameobjects/rendertexture/RenderTexture.js b/src/gameobjects/rendertexture/RenderTexture.js index 60fc85c46..89d1b122f 100644 --- a/src/gameobjects/rendertexture/RenderTexture.js +++ b/src/gameobjects/rendertexture/RenderTexture.js @@ -1,1233 +1,1233 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BlendModes = require('../../renderer/BlendModes'); -var Camera = require('../../cameras/2d/BaseCamera'); -var CanvasPool = require('../../display/canvas/CanvasPool'); -var Class = require('../../utils/Class'); -var Components = require('../components'); -var CONST = require('../../const'); -var Frame = require('../../textures/Frame'); -var GameObject = require('../GameObject'); -var Render = require('./RenderTextureRender'); -var Utils = require('../../renderer/webgl/Utils'); -var UUID = require('../../utils/string/UUID'); - -/** - * @classdesc - * A Render Texture. - * - * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and - * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic - * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. - * - * Note that under WebGL a FrameBuffer, which is what the Render Texture uses internally, cannot be anti-aliased. This means - * that when drawing objects such as Shapes to a Render Texture they will appear to be drawn with no aliasing, however this - * is a technical limitation of WebGL. To get around it, create your shape as a texture in an art package, then draw that - * to the Render Texture. - * - * @class RenderTexture - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.2.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.Pipeline - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {integer} [width=32] - The width of the Render Texture. - * @param {integer} [height=32] - The height of the Render Texture. - * @property {string} [key] - The texture key to make the RenderTexture from. - * @property {string} [frame] - the frame to make the RenderTexture from. - */ -var RenderTexture = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.ComputedSize, - Components.Crop, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Tint, - Components.Transform, - Components.Visible, - Render - ], - - initialize: - - function RenderTexture (scene, x, y, width, height, key, frame) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 32; } - if (height === undefined) { height = 32; } - - GameObject.call(this, scene, 'RenderTexture'); - - /** - * A reference to either the Canvas or WebGL Renderer that the Game instance is using. - * - * @name Phaser.GameObjects.RenderTexture#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.2.0 - */ - this.renderer = scene.sys.game.renderer; - - /** - * A reference to the Texture Manager. - * - * @name Phaser.GameObjects.RenderTexture#textureManager - * @type {Phaser.Textures.TextureManager} - * @since 3.12.0 - */ - this.textureManager = scene.sys.textures; - - /** - * The tint of the Render Texture when rendered. - * - * @name Phaser.GameObjects.RenderTexture#globalTint - * @type {number} - * @default 0xffffff - * @since 3.2.0 - */ - this.globalTint = 0xffffff; - - /** - * The alpha of the Render Texture when rendered. - * - * @name Phaser.GameObjects.RenderTexture#globalAlpha - * @type {number} - * @default 1 - * @since 3.2.0 - */ - this.globalAlpha = 1; - - /** - * The HTML Canvas Element that the Render Texture is drawing to when using the Canvas Renderer. - * - * @name Phaser.GameObjects.RenderTexture#canvas - * @type {HTMLCanvasElement} - * @since 3.2.0 - */ - this.canvas = null; - - /** - * A reference to the GL Frame Buffer this Render Texture is drawing to. - * This is only set if Phaser is running with the WebGL Renderer. - * - * @name Phaser.GameObjects.RenderTexture#framebuffer - * @type {?WebGLFramebuffer} - * @since 3.2.0 - */ - this.framebuffer = null; - - /** - * Is this Render Texture dirty or not? If not it won't spend time clearing or filling itself. - * - * @name Phaser.GameObjects.RenderTexture#dirty - * @type {boolean} - * @since 3.12.0 - */ - this.dirty = false; - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.RenderTexture#_crop - * @type {object} - * @private - * @since 3.12.0 - */ - this._crop = this.resetCropObject(); - - /** - * The Texture corresponding to this Render Texture. - * - * @name Phaser.GameObjects.RenderTexture#texture - * @type {Phaser.Textures.Texture} - * @since 3.12.0 - */ - this.texture = null; - - /** - * The Frame corresponding to this Render Texture. - * - * @name Phaser.GameObjects.RenderTexture#frame - * @type {Phaser.Textures.Frame} - * @since 3.12.0 - */ - this.frame = null; - - /** - * Internal saved texture flag. - * - * @name Phaser.GameObjects.RenderTexture#_saved - * @type {boolean} - * @private - * @since 3.12.0 - */ - this._saved = false; - - if (key === undefined) - { - this.canvas = CanvasPool.create2D(this, width, height); - - // Create a new Texture for this Text object - this.texture = scene.sys.textures.addCanvas(UUID(), this.canvas); - - // Get the frame - this.frame = this.texture.get(); - } - else - { - this.texture = scene.sys.textures.get(key); - - // Get the frame - this.frame = this.texture.get(frame); - - this.canvas = this.frame.source.image; - this._saved = true; - - this.dirty = true; - - this.width = this.frame.cutWidth; - this.height = this.frame.cutHeight; - } - - /** - * A reference to the Rendering Context belonging to the Canvas Element this Render Texture is drawing to. - * - * @name Phaser.GameObjects.RenderTexture#context - * @type {CanvasRenderingContext2D} - * @since 3.2.0 - */ - this.context = this.canvas.getContext('2d'); - - /** - * Internal erase mode flag. - * - * @name Phaser.GameObjects.RenderTexture#_eraseMode - * @type {boolean} - * @private - * @since 3.16.0 - */ - this._eraseMode = false; - - /** - * An internal Camera that can be used to move around the Render Texture. - * Control it just like you would any Scene Camera. The difference is that it only impacts the placement of what - * is drawn to the Render Texture. You can scroll, zoom and rotate this Camera. - * - * @name Phaser.GameObjects.RenderTexture#camera - * @type {Phaser.Cameras.Scene2D.BaseCamera} - * @since 3.12.0 - */ - this.camera = new Camera(0, 0, width, height); - - /** - * A reference to the WebGL Rendering Context. - * - * @name Phaser.GameObjects.RenderTexture#gl - * @type {WebGLRenderingContext} - * @default null - * @since 3.0.0 - */ - this.gl = null; - - /** - * A reference to the WebGLTexture that is being rendered to in a WebGL Context. - * - * @name Phaser.GameObjects.RenderTexture#glTexture - * @type {WebGLTexture} - * @default null - * @readonly - * @since 3.19.0 - */ - this.glTexture = null; - - var renderer = this.renderer; - - if (renderer.type === CONST.WEBGL) - { - var gl = renderer.gl; - - this.gl = gl; - this.glTexture = this.frame.source.glTexture; - this.drawGameObject = this.batchGameObjectWebGL; - this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false); - } - else if (renderer.type === CONST.CANVAS) - { - this.drawGameObject = this.batchGameObjectCanvas; - } - - this.camera.setScene(scene); - - this.setPosition(x, y); - - if (key === undefined) - { - this.setSize(width, height); - } - - this.setOrigin(0, 0); - this.initPipeline(); - }, - - /** - * Sets the size of this Game Object. - * - * @method Phaser.GameObjects.RenderTexture#setSize - * @since 3.0.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * - * @return {this} This Game Object instance. - */ - setSize: function (width, height) - { - return this.resize(width, height); - }, - - /** - * Resizes the Render Texture to the new dimensions given. - * - * If Render Texture was created from specific frame, only the size of the frame will be changed. The size of the source - * texture will not change. - * - * If Render Texture was not created from specific frame, the following will happen: - * In WebGL it will destroy and then re-create the frame buffer being used by the Render Texture. - * In Canvas it will resize the underlying canvas element. - * Both approaches will erase everything currently drawn to the Render Texture. - * - * If the dimensions given are the same as those already being used, calling this method will do nothing. - * - * @method Phaser.GameObjects.RenderTexture#resize - * @since 3.10.0 - * - * @param {number} width - The new width of the Render Texture. - * @param {number} [height=width] - The new height of the Render Texture. If not specified, will be set the same as the `width`. - * - * @return {this} This Render Texture. - */ - resize: function (width, height) - { - if (height === undefined) { height = width; } - - if (width !== this.width || height !== this.height) - { - if (this.frame.name === '__BASE') - { - // Resize the texture - - this.canvas.width = width; - this.canvas.height = height; - - this.texture.width = width; - this.texture.height = height; - - if (this.gl) - { - var gl = this.gl; - - this.renderer.deleteTexture(this.frame.source.glTexture); - this.renderer.deleteFramebuffer(this.framebuffer); - - var glTexture = this.renderer.createTexture2D(0, gl.NEAREST, gl.NEAREST, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, gl.RGBA, null, width, height, false); - - this.framebuffer = this.renderer.createFramebuffer(width, height, glTexture, false); - - this.frame.source.isRenderTexture = true; - - this.frame.glTexture = glTexture; - this.glTexture = glTexture; - } - - this.frame.source.width = width; - this.frame.source.height = height; - - this.camera.setSize(width, height); - - this.frame.setSize(width, height); - - this.width = width; - this.height = height; - } - } - else - { - // Resize the frame - - var baseFrame = this.texture.getSourceImage(); - - if (this.frame.cutX + width > baseFrame.width) - { - width = baseFrame.width - this.frame.cutX; - } - - if (this.frame.cutY + height > baseFrame.height) - { - height = baseFrame.height - this.frame.cutY; - } - - this.frame.setSize(width, height, this.frame.cutX, this.frame.cutY); - } - - this.updateDisplayOrigin(); - - var input = this.input; - - if (input && !input.customHitArea) - { - input.hitArea.width = width; - input.hitArea.height = height; - } - - return this; - }, - - /** - * Set the tint to use when rendering this Render Texture. - * - * @method Phaser.GameObjects.RenderTexture#setGlobalTint - * @since 3.2.0 - * - * @param {integer} tint - The tint value. - * - * @return {this} This Render Texture. - */ - setGlobalTint: function (tint) - { - this.globalTint = tint; - - return this; - }, - - /** - * Set the alpha to use when rendering this Render Texture. - * - * @method Phaser.GameObjects.RenderTexture#setGlobalAlpha - * @since 3.2.0 - * - * @param {number} alpha - The alpha value. - * - * @return {this} This Render Texture. - */ - setGlobalAlpha: function (alpha) - { - this.globalAlpha = alpha; - - return this; - }, - - /** - * Stores a copy of this Render Texture in the Texture Manager using the given key. - * - * After doing this, any texture based Game Object, such as a Sprite, can use the contents of this - * Render Texture by using the texture key: - * - * ```javascript - * var rt = this.add.renderTexture(0, 0, 128, 128); - * - * // Draw something to the Render Texture - * - * rt.saveTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * Updating the contents of this Render Texture will automatically update _any_ Game Object - * that is using it as a texture. Calling `saveTexture` again will not save another copy - * of the same texture, it will just rename the key of the existing copy. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame from a Render Texture. - * - * @method Phaser.GameObjects.RenderTexture#saveTexture - * @since 3.12.0 - * - * @param {string} key - The unique key to store the texture as within the global Texture Manager. - * - * @return {Phaser.Textures.Texture} The Texture that was saved. - */ - saveTexture: function (key) - { - this.textureManager.renameTexture(this.texture.key, key); - - this._saved = true; - - return this.texture; - }, - - /** - * Fills the Render Texture with the given color. - * - * @method Phaser.GameObjects.RenderTexture#fill - * @since 3.2.0 - * - * @param {number} rgb - The color to fill the Render Texture with. - * @param {number} [alpha=1] - The alpha value used by the fill. - * @param {number} [x=0] - The left coordinate of the fill rectangle. - * @param {number} [y=0] - The top coordinate of the fill rectangle. - * @param {number} [width=this.frame.cutWidth] - The width of the fill rectangle. - * @param {number} [height=this.frame.cutHeight] - The height of the fill rectangle. - * - * @return {this} This Render Texture instance. - */ - fill: function (rgb, alpha, x, y, width, height) - { - if (alpha === undefined) { alpha = 1; } - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.frame.cutWidth; } - if (height === undefined) { height = this.frame.cutHeight; } - - var r = ((rgb >> 16) | 0) & 0xff; - var g = ((rgb >> 8) | 0) & 0xff; - var b = (rgb | 0) & 0xff; - - var gl = this.gl; - var frame = this.frame; - - this.camera.preRender(1, 1); - - if (gl) - { - var cx = this.camera._cx; - var cy = this.camera._cy; - var cw = this.camera._cw; - var ch = this.camera._ch; - - this.renderer.setFramebuffer(this.framebuffer, false); - - this.renderer.pushScissor(cx, cy, cw, ch, ch); - - var pipeline = this.pipeline; - - pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); - - pipeline.drawFillRect( - x, y, width, height, - Utils.getTintFromFloats(r / 255, g / 255, b / 255, 1), - alpha - ); - - this.renderer.setFramebuffer(null, false); - - this.renderer.popScissor(); - - pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); - } - else - { - this.renderer.setContext(this.context); - - this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'; - this.context.fillRect(x + frame.cutX, y + frame.cutY, width, height); - - this.renderer.setContext(); - } - - this.dirty = true; - - return this; - }, - - /** - * Clears the Render Texture. - * - * @method Phaser.GameObjects.RenderTexture#clear - * @since 3.2.0 - * - * @return {this} This Render Texture instance. - */ - clear: function () - { - if (this.dirty) - { - var gl = this.gl; - - if (gl) - { - var renderer = this.renderer; - - renderer.setFramebuffer(this.framebuffer, true); - - if (this.frame.cutWidth !== this.canvas.width || this.frame.cutHeight !== this.canvas.height) - { - gl.scissor(this.frame.cutX, this.frame.cutY, this.frame.cutWidth, this.frame.cutHeight); - } - - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - - renderer.setFramebuffer(null, true); - } - else - { - var ctx = this.context; - - ctx.save(); - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.clearRect(this.frame.cutX, this.frame.cutY, this.frame.cutWidth, this.frame.cutHeight); - ctx.restore(); - } - - this.dirty = false; - } - - return this; - }, - - /** - * Draws the given object, or an array of objects, to this Render Texture using a blend mode of ERASE. - * This has the effect of erasing any filled pixels in the objects from this Render Texture. - * - * It can accept any of the following: - * - * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. - * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. - * * Another Render Texture. - * * A Texture Frame instance. - * * A string. This is used to look-up a texture from the Texture Manager. - * - * Note: You cannot erase a Render Texture from itself. - * - * 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. - * - * 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. - * - * Calling this method causes the WebGL batch to flush, so it can write the texture - * data to the framebuffer being used internally. The batch is flushed at the end, - * after the entries have been iterated. So if you've a bunch of objects to draw, - * try and pass them in an array in one single call, rather than making lots of - * separate calls. - * - * @method Phaser.GameObjects.RenderTexture#erase - * @since 3.16.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] - The x position to draw the Frame at, or the offset applied to the object. - * @param {number} [y] - The y position to draw the Frame at, or the offset applied to the object. - * - * @return {this} This Render Texture instance. - */ - erase: function (entries, x, y) - { - this._eraseMode = true; - - var blendMode = this.renderer.currentBlendMode; - - this.renderer.setBlendMode(BlendModes.ERASE); - - this.draw(entries, x, y, 1, 16777215); - - this.renderer.setBlendMode(blendMode); - - this._eraseMode = false; - - return this; - }, - - /** - * Draws the given object, or an array of objects, to this Render Texture. - * - * It can accept any of the following: - * - * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. - * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. - * * Another Render Texture. - * * A Texture Frame instance. - * * A string. This is used to look-up a texture from the Texture Manager. - * - * Note: You cannot draw a Render Texture to itself. - * - * 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. - * - * The `alpha` and `tint` values are only used by Texture Frames. - * Game Objects use their own alpha and tint values when being drawn. - * - * Calling this method causes the WebGL batch to flush, so it can write the texture - * data to the framebuffer being used internally. The batch is flushed at the end, - * after the entries have been iterated. So if you've a bunch of objects to draw, - * try and pass them in an array in one single call, rather than making lots of - * separate calls. - * - * @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] - The x position to draw the Frame at, or the offset applied to the object. - * @param {number} [y] - The y position to draw the Frame at, or the offset applied to the object. - * @param {number} [alpha] - The alpha value. Only used for Texture Frames and if not specified defaults to the `globalAlpha` property. Game Objects use their own current alpha value. - * @param {number} [tint] - WebGL only. The tint color value. Only used for Texture Frames and if not specified defaults to the `globalTint` property. Game Objects use their own current tint value. - * - * @return {this} This Render Texture instance. - */ - draw: function (entries, x, y, alpha, tint) - { - if (alpha === undefined) { alpha = this.globalAlpha; } - - if (tint === undefined) - { - tint = (this.globalTint >> 16) + (this.globalTint & 0xff00) + ((this.globalTint & 0xff) << 16); - } - else - { - tint = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16); - } - - if (!Array.isArray(entries)) - { - entries = [ entries ]; - } - - var gl = this.gl; - - this.camera.preRender(1, 1); - - if (gl) - { - var cx = this.camera._cx; - var cy = this.camera._cy; - var cw = this.camera._cw; - var ch = this.camera._ch; - - this.renderer.setFramebuffer(this.framebuffer, false); - - this.renderer.pushScissor(cx, cy, cw, ch, ch); - - var pipeline = this.pipeline; - - pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); - - this.batchList(entries, x, y, alpha, tint); - - pipeline.flush(); - - this.renderer.setFramebuffer(null, false); - - this.renderer.popScissor(); - - pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); - } - else - { - this.renderer.setContext(this.context); - - this.batchList(entries, x, y, alpha, tint); - - this.renderer.setContext(); - } - - this.dirty = true; - - return this; - }, - - /** - * Draws the Texture Frame to the Render Texture at the given position. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * ```javascript - * var rt = this.add.renderTexture(0, 0, 800, 600); - * rt.drawFrame(key, frame); - * ``` - * - * You can optionally provide a position, alpha and tint value to apply to the frame - * before it is drawn. - * - * Calling this method will cause a batch flush, so if you've got a stack of things to draw - * in a tight loop, try using the `draw` method instead. - * - * If you need to draw a Sprite to this Render Texture, use the `draw` method instead. - * - * @method Phaser.GameObjects.RenderTexture#drawFrame - * @since 3.12.0 - * - * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * @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 {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. - * @param {number} [tint] - WebGL only. The tint color to use. If not specified it uses the `globalTint` property. - * - * @return {this} This Render Texture instance. - */ - drawFrame: function (key, frame, x, y, alpha, tint) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (alpha === undefined) { alpha = this.globalAlpha; } - - if (tint === undefined) - { - tint = (this.globalTint >> 16) + (this.globalTint & 0xff00) + ((this.globalTint & 0xff) << 16); - } - else - { - tint = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16); - } - - var gl = this.gl; - var textureFrame = this.textureManager.getFrame(key, frame); - - if (textureFrame) - { - this.camera.preRender(1, 1); - - if (gl) - { - var cx = this.camera._cx; - var cy = this.camera._cy; - var cw = this.camera._cw; - var ch = this.camera._ch; - - this.renderer.setFramebuffer(this.framebuffer, false); - - this.renderer.pushScissor(cx, cy, cw, ch, ch); - - var pipeline = this.pipeline; - - pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); - - pipeline.batchTextureFrame(textureFrame, x + this.frame.cutX, y + this.frame.cutY, tint, alpha, this.camera.matrix, null); - - pipeline.flush(); - - this.renderer.setFramebuffer(null, false); - - this.renderer.popScissor(); - - pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); - } - else - { - this.batchTextureFrame(textureFrame, x + this.frame.cutX, y + this.frame.cutY, alpha, tint); - } - - this.dirty = true; - } - - return this; - }, - - /** - * Internal method that handles the drawing of an array of children. - * - * @method Phaser.GameObjects.RenderTexture#batchList - * @private - * @since 3.12.0 - * - * @param {array} children - The array of Game Objects to draw. - * @param {number} [x] - The x position to offset the Game Object by. - * @param {number} [y] - The y position to offset the Game Object by. - * @param {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. - * @param {number} [tint] - The tint color to use. If not specified it uses the `globalTint` property. - */ - batchList: function (children, x, y, alpha, tint) - { - for (var i = 0; i < children.length; i++) - { - var entry = children[i]; - - if (!entry || entry === this) - { - continue; - } - - if (entry.renderWebGL || entry.renderCanvas) - { - // Game Objects - this.drawGameObject(entry, x, y); - } - else if (entry.isParent || entry.list) - { - // Groups / Display Lists - this.batchGroup(entry.getChildren(), x, y); - } - else if (typeof entry === 'string') - { - // Texture key - this.batchTextureFrameKey(entry, null, x, y, alpha, tint); - } - else if (entry instanceof Frame) - { - // Texture Frame instance - this.batchTextureFrame(entry, x, y, alpha, tint); - } - else if (Array.isArray(entry)) - { - // Another Array - this.batchList(entry, x, y, alpha, tint); - } - } - }, - - /** - * Internal method that handles the drawing a Phaser Group contents. - * - * @method Phaser.GameObjects.RenderTexture#batchGroup - * @private - * @since 3.12.0 - * - * @param {array} children - The array of Game Objects to draw. - * @param {number} [x=0] - The x position to offset the Game Object by. - * @param {number} [y=0] - The y position to offset the Game Object by. - */ - batchGroup: function (children, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - x += this.frame.cutX; - y += this.frame.cutY; - - for (var i = 0; i < children.length; i++) - { - var entry = children[i]; - - if (entry.willRender()) - { - var tx = entry.x + x; - var ty = entry.y + y; - - this.drawGameObject(entry, tx, ty); - } - } - }, - - /** - * Internal method that handles drawing a single Phaser Game Object to this Render Texture using WebGL. - * - * @method Phaser.GameObjects.RenderTexture#batchGameObjectWebGL - * @private - * @since 3.12.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to draw. - * @param {number} [x] - The x position to draw the Game Object at. - * @param {number} [y] - The y position to draw the Game Object at. - */ - batchGameObjectWebGL: function (gameObject, x, y) - { - if (x === undefined) { x = gameObject.x; } - if (y === undefined) { y = gameObject.y; } - - var prevX = gameObject.x; - var prevY = gameObject.y; - - if (!this._eraseMode) - { - this.renderer.setBlendMode(gameObject.blendMode); - } - - gameObject.setPosition(x + this.frame.cutX, y + this.frame.cutY); - - gameObject.renderWebGL(this.renderer, gameObject, 0, this.camera, null); - - gameObject.setPosition(prevX, prevY); - }, - - /** - * Internal method that handles drawing a single Phaser Game Object to this Render Texture using Canvas. - * - * @method Phaser.GameObjects.RenderTexture#batchGameObjectCanvas - * @private - * @since 3.12.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to draw. - * @param {number} [x] - The x position to draw the Game Object at. - * @param {number} [y] - The y position to draw the Game Object at. - */ - batchGameObjectCanvas: function (gameObject, x, y) - { - if (x === undefined) { x = gameObject.x; } - if (y === undefined) { y = gameObject.y; } - - var prevX = gameObject.x; - var prevY = gameObject.y; - - if (this._eraseMode) - { - var blendMode = gameObject.blendMode; - - gameObject.blendMode = BlendModes.ERASE; - } - - gameObject.setPosition(x + this.frame.cutX, y + this.frame.cutY); - - gameObject.renderCanvas(this.renderer, gameObject, 0, this.camera, null); - - gameObject.setPosition(prevX, prevY); - - if (this._eraseMode) - { - gameObject.blendMode = blendMode; - } - }, - - /** - * Internal method that handles the drawing of an array of children. - * - * @method Phaser.GameObjects.RenderTexture#batchTextureFrameKey - * @private - * @since 3.12.0 - * - * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * @param {number} [x=0] - The x position to offset the Game Object by. - * @param {number} [y=0] - The y position to offset the Game Object by. - * @param {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. - * @param {number} [tint] - The tint color to use. If not specified it uses the `globalTint` property. - */ - batchTextureFrameKey: function (key, frame, x, y, alpha, tint) - { - var textureFrame = this.textureManager.getFrame(key, frame); - - if (textureFrame) - { - this.batchTextureFrame(textureFrame, x, y, alpha, tint); - } - }, - - /** - * Internal method that handles the drawing of a Texture Frame to this Render Texture. - * - * @method Phaser.GameObjects.RenderTexture#batchTextureFrame - * @private - * @since 3.12.0 - * - * @param {Phaser.Textures.Frame} textureFrame - The Texture Frame to draw. - * @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 {number} [tint] - A tint color to be applied to the frame drawn to the Render Texture. - */ - batchTextureFrame: function (textureFrame, x, y, alpha, tint) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - x += this.frame.cutX; - y += this.frame.cutY; - - if (this.gl) - { - this.pipeline.batchTextureFrame(textureFrame, x, y, tint, alpha, this.camera.matrix, null); - } - else - { - var ctx = this.context; - var cd = textureFrame.canvasData; - var source = textureFrame.source.image; - - var matrix = this.camera.matrix; - - ctx.globalAlpha = this.globalAlpha; - - ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); - - ctx.drawImage(source, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); - } - }, - - /** - * Takes a snapshot of the given area of this Render Texture. - * - * The snapshot is taken immediately. - * - * To capture the whole Render Texture see the `snapshot` method. To capture a specific pixel, see `snapshotPixel`. - * - * 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.GameObjects.RenderTexture#snapshotArea - * @since 3.19.0 - * - * @param {integer} x - The x coordinate to grab from. - * @param {integer} y - The y coordinate to grab from. - * @param {integer} width - The width of the area to grab. - * @param {integer} 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 Render Texture instance. - */ - snapshotArea: function (x, y, width, height, callback, type, encoderOptions) - { - if (this.gl) - { - this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, false, x, y, width, height, type, encoderOptions); - } - else - { - this.renderer.snapshotCanvas(this.canvas, callback, false, x, y, width, height, type, encoderOptions); - } - - return this; - }, - - /** - * Takes a snapshot of the whole of this Render Texture. - * - * The snapshot is taken immediately. - * - * To capture just a portion of the Render Texture see the `snapshotArea` method. To capture a specific pixel, see `snapshotPixel`. - * - * 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.GameObjects.RenderTexture#snapshot - * @since 3.19.0 - * - * @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 Render Texture instance. - */ - snapshot: function (callback, type, encoderOptions) - { - if (this.gl) - { - this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, false, 0, 0, this.width, this.height, type, encoderOptions); - } - else - { - this.renderer.snapshotCanvas(this.canvas, callback, false, 0, 0, this.width, this.height, type, encoderOptions); - } - - return this; - }, - - /** - * Takes a snapshot of the given pixel from this Render Texture. - * - * The snapshot is taken immediately. - * - * To capture the whole Render Texture see the `snapshot` method. To capture a specific portion, see `snapshotArea`. - * - * Unlike the other two snapshot methods, this one will send your callback 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, than the other snapshot methods. - * - * @method Phaser.GameObjects.RenderTexture#snapshotPixel - * @since 3.19.0 - * - * @param {integer} x - The x coordinate of the pixel to get. - * @param {integer} y - The y coordinate of the pixel to get. - * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. - * - * @return {this} This Render Texture instance. - */ - snapshotPixel: function (x, y, callback) - { - if (this.gl) - { - this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, true, x, y); - } - else - { - this.renderer.snapshotCanvas(this.canvas, callback, true, x, y); - } - - return this; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.RenderTexture#preDestroy - * @protected - * @since 3.9.0 - */ - preDestroy: function () - { - if (!this._saved) - { - CanvasPool.remove(this.canvas); - - if (this.gl) - { - this.renderer.deleteFramebuffer(this.framebuffer); - } - - this.texture.destroy(); - this.camera.destroy(); - - this.canvas = null; - this.context = null; - this.framebuffer = null; - this.texture = null; - this.glTexture = null; - } - } - -}); - -module.exports = RenderTexture; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = require('../../renderer/BlendModes'); +var Camera = require('../../cameras/2d/BaseCamera'); +var CanvasPool = require('../../display/canvas/CanvasPool'); +var Class = require('../../utils/Class'); +var Components = require('../components'); +var CONST = require('../../const'); +var Frame = require('../../textures/Frame'); +var GameObject = require('../GameObject'); +var Render = require('./RenderTextureRender'); +var Utils = require('../../renderer/webgl/Utils'); +var UUID = require('../../utils/string/UUID'); + +/** + * @classdesc + * A Render Texture. + * + * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and + * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic + * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. + * + * Note that under WebGL a FrameBuffer, which is what the Render Texture uses internally, cannot be anti-aliased. This means + * that when drawing objects such as Shapes to a Render Texture they will appear to be drawn with no aliasing, however this + * is a technical limitation of WebGL. To get around it, create your shape as a texture in an art package, then draw that + * to the Render Texture. + * + * @class RenderTexture + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.2.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.Pipeline + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {integer} [width=32] - The width of the Render Texture. + * @param {integer} [height=32] - The height of the Render Texture. + * @property {string} [key] - The texture key to make the RenderTexture from. + * @property {string} [frame] - the frame to make the RenderTexture from. + */ +var RenderTexture = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Crop, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Tint, + Components.Transform, + Components.Visible, + Render + ], + + initialize: + + function RenderTexture (scene, x, y, width, height, key, frame) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 32; } + if (height === undefined) { height = 32; } + + GameObject.call(this, scene, 'RenderTexture'); + + /** + * A reference to either the Canvas or WebGL Renderer that the Game instance is using. + * + * @name Phaser.GameObjects.RenderTexture#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.2.0 + */ + this.renderer = scene.sys.game.renderer; + + /** + * A reference to the Texture Manager. + * + * @name Phaser.GameObjects.RenderTexture#textureManager + * @type {Phaser.Textures.TextureManager} + * @since 3.12.0 + */ + this.textureManager = scene.sys.textures; + + /** + * The tint of the Render Texture when rendered. + * + * @name Phaser.GameObjects.RenderTexture#globalTint + * @type {number} + * @default 0xffffff + * @since 3.2.0 + */ + this.globalTint = 0xffffff; + + /** + * The alpha of the Render Texture when rendered. + * + * @name Phaser.GameObjects.RenderTexture#globalAlpha + * @type {number} + * @default 1 + * @since 3.2.0 + */ + this.globalAlpha = 1; + + /** + * The HTML Canvas Element that the Render Texture is drawing to when using the Canvas Renderer. + * + * @name Phaser.GameObjects.RenderTexture#canvas + * @type {HTMLCanvasElement} + * @since 3.2.0 + */ + this.canvas = null; + + /** + * A reference to the GL Frame Buffer this Render Texture is drawing to. + * This is only set if Phaser is running with the WebGL Renderer. + * + * @name Phaser.GameObjects.RenderTexture#framebuffer + * @type {?WebGLFramebuffer} + * @since 3.2.0 + */ + this.framebuffer = null; + + /** + * Is this Render Texture dirty or not? If not it won't spend time clearing or filling itself. + * + * @name Phaser.GameObjects.RenderTexture#dirty + * @type {boolean} + * @since 3.12.0 + */ + this.dirty = false; + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.RenderTexture#_crop + * @type {object} + * @private + * @since 3.12.0 + */ + this._crop = this.resetCropObject(); + + /** + * The Texture corresponding to this Render Texture. + * + * @name Phaser.GameObjects.RenderTexture#texture + * @type {Phaser.Textures.Texture} + * @since 3.12.0 + */ + this.texture = null; + + /** + * The Frame corresponding to this Render Texture. + * + * @name Phaser.GameObjects.RenderTexture#frame + * @type {Phaser.Textures.Frame} + * @since 3.12.0 + */ + this.frame = null; + + /** + * Internal saved texture flag. + * + * @name Phaser.GameObjects.RenderTexture#_saved + * @type {boolean} + * @private + * @since 3.12.0 + */ + this._saved = false; + + if (key === undefined) + { + this.canvas = CanvasPool.create2D(this, width, height); + + // Create a new Texture for this Text object + this.texture = scene.sys.textures.addCanvas(UUID(), this.canvas); + + // Get the frame + this.frame = this.texture.get(); + } + else + { + this.texture = scene.sys.textures.get(key); + + // Get the frame + this.frame = this.texture.get(frame); + + this.canvas = this.frame.source.image; + this._saved = true; + + this.dirty = true; + + this.width = this.frame.cutWidth; + this.height = this.frame.cutHeight; + } + + /** + * A reference to the Rendering Context belonging to the Canvas Element this Render Texture is drawing to. + * + * @name Phaser.GameObjects.RenderTexture#context + * @type {CanvasRenderingContext2D} + * @since 3.2.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * Internal erase mode flag. + * + * @name Phaser.GameObjects.RenderTexture#_eraseMode + * @type {boolean} + * @private + * @since 3.16.0 + */ + this._eraseMode = false; + + /** + * An internal Camera that can be used to move around the Render Texture. + * Control it just like you would any Scene Camera. The difference is that it only impacts the placement of what + * is drawn to the Render Texture. You can scroll, zoom and rotate this Camera. + * + * @name Phaser.GameObjects.RenderTexture#camera + * @type {Phaser.Cameras.Scene2D.BaseCamera} + * @since 3.12.0 + */ + this.camera = new Camera(0, 0, width, height); + + /** + * A reference to the WebGL Rendering Context. + * + * @name Phaser.GameObjects.RenderTexture#gl + * @type {WebGLRenderingContext} + * @default null + * @since 3.0.0 + */ + this.gl = null; + + /** + * A reference to the WebGLTexture that is being rendered to in a WebGL Context. + * + * @name Phaser.GameObjects.RenderTexture#glTexture + * @type {WebGLTexture} + * @default null + * @readonly + * @since 3.19.0 + */ + this.glTexture = null; + + var renderer = this.renderer; + + if (renderer.type === CONST.WEBGL) + { + var gl = renderer.gl; + + this.gl = gl; + this.glTexture = this.frame.source.glTexture; + this.drawGameObject = this.batchGameObjectWebGL; + this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false); + } + else if (renderer.type === CONST.CANVAS) + { + this.drawGameObject = this.batchGameObjectCanvas; + } + + this.camera.setScene(scene); + + this.setPosition(x, y); + + if (key === undefined) + { + this.setSize(width, height); + } + + this.setOrigin(0, 0); + this.initPipeline(); + }, + + /** + * Sets the size of this Game Object. + * + * @method Phaser.GameObjects.RenderTexture#setSize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + return this.resize(width, height); + }, + + /** + * Resizes the Render Texture to the new dimensions given. + * + * If Render Texture was created from specific frame, only the size of the frame will be changed. The size of the source + * texture will not change. + * + * If Render Texture was not created from specific frame, the following will happen: + * In WebGL it will destroy and then re-create the frame buffer being used by the Render Texture. + * In Canvas it will resize the underlying canvas element. + * Both approaches will erase everything currently drawn to the Render Texture. + * + * If the dimensions given are the same as those already being used, calling this method will do nothing. + * + * @method Phaser.GameObjects.RenderTexture#resize + * @since 3.10.0 + * + * @param {number} width - The new width of the Render Texture. + * @param {number} [height=width] - The new height of the Render Texture. If not specified, will be set the same as the `width`. + * + * @return {this} This Render Texture. + */ + resize: function (width, height) + { + if (height === undefined) { height = width; } + + if (width !== this.width || height !== this.height) + { + if (this.frame.name === '__BASE') + { + // Resize the texture + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.width = width; + this.texture.height = height; + + if (this.gl) + { + var gl = this.gl; + + this.renderer.deleteTexture(this.frame.source.glTexture); + this.renderer.deleteFramebuffer(this.framebuffer); + + var glTexture = this.renderer.createTexture2D(0, gl.NEAREST, gl.NEAREST, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, gl.RGBA, null, width, height, false); + + this.framebuffer = this.renderer.createFramebuffer(width, height, glTexture, false); + + this.frame.source.isRenderTexture = true; + + this.frame.glTexture = glTexture; + this.glTexture = glTexture; + } + + this.frame.source.width = width; + this.frame.source.height = height; + + this.camera.setSize(width, height); + + this.frame.setSize(width, height); + + this.width = width; + this.height = height; + } + } + else + { + // Resize the frame + + var baseFrame = this.texture.getSourceImage(); + + if (this.frame.cutX + width > baseFrame.width) + { + width = baseFrame.width - this.frame.cutX; + } + + if (this.frame.cutY + height > baseFrame.height) + { + height = baseFrame.height - this.frame.cutY; + } + + this.frame.setSize(width, height, this.frame.cutX, this.frame.cutY); + } + + this.updateDisplayOrigin(); + + var input = this.input; + + if (input && !input.customHitArea) + { + input.hitArea.width = width; + input.hitArea.height = height; + } + + return this; + }, + + /** + * Set the tint to use when rendering this Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#setGlobalTint + * @since 3.2.0 + * + * @param {integer} tint - The tint value. + * + * @return {this} This Render Texture. + */ + setGlobalTint: function (tint) + { + this.globalTint = tint; + + return this; + }, + + /** + * Set the alpha to use when rendering this Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#setGlobalAlpha + * @since 3.2.0 + * + * @param {number} alpha - The alpha value. + * + * @return {this} This Render Texture. + */ + setGlobalAlpha: function (alpha) + { + this.globalAlpha = alpha; + + return this; + }, + + /** + * Stores a copy of this Render Texture in the Texture Manager using the given key. + * + * After doing this, any texture based Game Object, such as a Sprite, can use the contents of this + * Render Texture by using the texture key: + * + * ```javascript + * var rt = this.add.renderTexture(0, 0, 128, 128); + * + * // Draw something to the Render Texture + * + * rt.saveTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Updating the contents of this Render Texture will automatically update _any_ Game Object + * that is using it as a texture. Calling `saveTexture` again will not save another copy + * of the same texture, it will just rename the key of the existing copy. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame from a Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#saveTexture + * @since 3.12.0 + * + * @param {string} key - The unique key to store the texture as within the global Texture Manager. + * + * @return {Phaser.Textures.Texture} The Texture that was saved. + */ + saveTexture: function (key) + { + this.textureManager.renameTexture(this.texture.key, key); + + this._saved = true; + + return this.texture; + }, + + /** + * Fills the Render Texture with the given color. + * + * @method Phaser.GameObjects.RenderTexture#fill + * @since 3.2.0 + * + * @param {number} rgb - The color to fill the Render Texture with. + * @param {number} [alpha=1] - The alpha value used by the fill. + * @param {number} [x=0] - The left coordinate of the fill rectangle. + * @param {number} [y=0] - The top coordinate of the fill rectangle. + * @param {number} [width=this.frame.cutWidth] - The width of the fill rectangle. + * @param {number} [height=this.frame.cutHeight] - The height of the fill rectangle. + * + * @return {this} This Render Texture instance. + */ + fill: function (rgb, alpha, x, y, width, height) + { + if (alpha === undefined) { alpha = 1; } + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.frame.cutWidth; } + if (height === undefined) { height = this.frame.cutHeight; } + + var r = ((rgb >> 16) | 0) & 0xff; + var g = ((rgb >> 8) | 0) & 0xff; + var b = (rgb | 0) & 0xff; + + var gl = this.gl; + var frame = this.frame; + + this.camera.preRender(1, 1); + + if (gl) + { + var cx = this.camera._cx; + var cy = this.camera._cy; + var cw = this.camera._cw; + var ch = this.camera._ch; + + this.renderer.setFramebuffer(this.framebuffer, false); + + this.renderer.pushScissor(cx, cy, cw, ch, ch); + + var pipeline = this.pipeline; + + pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); + + pipeline.drawFillRect( + x, y, width, height, + Utils.getTintFromFloats(r / 255, g / 255, b / 255, 1), + alpha + ); + + this.renderer.setFramebuffer(null, false); + + this.renderer.popScissor(); + + pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); + } + else + { + this.renderer.setContext(this.context); + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'; + this.context.fillRect(x + frame.cutX, y + frame.cutY, width, height); + + this.renderer.setContext(); + } + + this.dirty = true; + + return this; + }, + + /** + * Clears the Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#clear + * @since 3.2.0 + * + * @return {this} This Render Texture instance. + */ + clear: function () + { + if (this.dirty) + { + var gl = this.gl; + + if (gl) + { + var renderer = this.renderer; + + renderer.setFramebuffer(this.framebuffer, true); + + if (this.frame.cutWidth !== this.canvas.width || this.frame.cutHeight !== this.canvas.height) + { + gl.scissor(this.frame.cutX, this.frame.cutY, this.frame.cutWidth, this.frame.cutHeight); + } + + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + + renderer.setFramebuffer(null, true); + } + else + { + var ctx = this.context; + + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(this.frame.cutX, this.frame.cutY, this.frame.cutWidth, this.frame.cutHeight); + ctx.restore(); + } + + this.dirty = false; + } + + return this; + }, + + /** + * Draws the given object, or an array of objects, to this Render Texture using a blend mode of ERASE. + * This has the effect of erasing any filled pixels in the objects from this Render Texture. + * + * It can accept any of the following: + * + * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. + * * Another Render Texture. + * * A Texture Frame instance. + * * A string. This is used to look-up a texture from the Texture Manager. + * + * Note: You cannot erase a Render Texture from itself. + * + * 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. + * + * 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. + * + * Calling this method causes the WebGL batch to flush, so it can write the texture + * data to the framebuffer being used internally. The batch is flushed at the end, + * after the entries have been iterated. So if you've a bunch of objects to draw, + * try and pass them in an array in one single call, rather than making lots of + * separate calls. + * + * @method Phaser.GameObjects.RenderTexture#erase + * @since 3.16.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] - The x position to draw the Frame at, or the offset applied to the object. + * @param {number} [y] - The y position to draw the Frame at, or the offset applied to the object. + * + * @return {this} This Render Texture instance. + */ + erase: function (entries, x, y) + { + this._eraseMode = true; + + var blendMode = this.renderer.currentBlendMode; + + this.renderer.setBlendMode(BlendModes.ERASE); + + this.draw(entries, x, y, 1, 16777215); + + this.renderer.setBlendMode(blendMode); + + this._eraseMode = false; + + return this; + }, + + /** + * Draws the given object, or an array of objects, to this Render Texture. + * + * It can accept any of the following: + * + * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. + * * Another Render Texture. + * * A Texture Frame instance. + * * A string. This is used to look-up a texture from the Texture Manager. + * + * Note: You cannot draw a Render Texture to itself. + * + * 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. + * + * The `alpha` and `tint` values are only used by Texture Frames. + * Game Objects use their own alpha and tint values when being drawn. + * + * Calling this method causes the WebGL batch to flush, so it can write the texture + * data to the framebuffer being used internally. The batch is flushed at the end, + * after the entries have been iterated. So if you've a bunch of objects to draw, + * try and pass them in an array in one single call, rather than making lots of + * separate calls. + * + * @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] - The x position to draw the Frame at, or the offset applied to the object. + * @param {number} [y] - The y position to draw the Frame at, or the offset applied to the object. + * @param {number} [alpha] - The alpha value. Only used for Texture Frames and if not specified defaults to the `globalAlpha` property. Game Objects use their own current alpha value. + * @param {number} [tint] - WebGL only. The tint color value. Only used for Texture Frames and if not specified defaults to the `globalTint` property. Game Objects use their own current tint value. + * + * @return {this} This Render Texture instance. + */ + draw: function (entries, x, y, alpha, tint) + { + if (alpha === undefined) { alpha = this.globalAlpha; } + + if (tint === undefined) + { + tint = (this.globalTint >> 16) + (this.globalTint & 0xff00) + ((this.globalTint & 0xff) << 16); + } + else + { + tint = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16); + } + + if (!Array.isArray(entries)) + { + entries = [ entries ]; + } + + var gl = this.gl; + + this.camera.preRender(1, 1); + + if (gl) + { + var cx = this.camera._cx; + var cy = this.camera._cy; + var cw = this.camera._cw; + var ch = this.camera._ch; + + this.renderer.setFramebuffer(this.framebuffer, false); + + this.renderer.pushScissor(cx, cy, cw, ch, ch); + + var pipeline = this.pipeline; + + pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); + + this.batchList(entries, x, y, alpha, tint); + + pipeline.flush(); + + this.renderer.setFramebuffer(null, false); + + this.renderer.popScissor(); + + pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); + } + else + { + this.renderer.setContext(this.context); + + this.batchList(entries, x, y, alpha, tint); + + this.renderer.setContext(); + } + + this.dirty = true; + + return this; + }, + + /** + * Draws the Texture Frame to the Render Texture at the given position. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * ```javascript + * var rt = this.add.renderTexture(0, 0, 800, 600); + * rt.drawFrame(key, frame); + * ``` + * + * You can optionally provide a position, alpha and tint value to apply to the frame + * before it is drawn. + * + * Calling this method will cause a batch flush, so if you've got a stack of things to draw + * in a tight loop, try using the `draw` method instead. + * + * If you need to draw a Sprite to this Render Texture, use the `draw` method instead. + * + * @method Phaser.GameObjects.RenderTexture#drawFrame + * @since 3.12.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * @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 {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. + * @param {number} [tint] - WebGL only. The tint color to use. If not specified it uses the `globalTint` property. + * + * @return {this} This Render Texture instance. + */ + drawFrame: function (key, frame, x, y, alpha, tint) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (alpha === undefined) { alpha = this.globalAlpha; } + + if (tint === undefined) + { + tint = (this.globalTint >> 16) + (this.globalTint & 0xff00) + ((this.globalTint & 0xff) << 16); + } + else + { + tint = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16); + } + + var gl = this.gl; + var textureFrame = this.textureManager.getFrame(key, frame); + + if (textureFrame) + { + this.camera.preRender(1, 1); + + if (gl) + { + var cx = this.camera._cx; + var cy = this.camera._cy; + var cw = this.camera._cw; + var ch = this.camera._ch; + + this.renderer.setFramebuffer(this.framebuffer, false); + + this.renderer.pushScissor(cx, cy, cw, ch, ch); + + var pipeline = this.pipeline; + + pipeline.projOrtho(0, this.texture.width, 0, this.texture.height, -1000.0, 1000.0); + + pipeline.batchTextureFrame(textureFrame, x + this.frame.cutX, y + this.frame.cutY, tint, alpha, this.camera.matrix, null); + + pipeline.flush(); + + this.renderer.setFramebuffer(null, false); + + this.renderer.popScissor(); + + pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1000.0, 1000.0); + } + else + { + this.batchTextureFrame(textureFrame, x + this.frame.cutX, y + this.frame.cutY, alpha, tint); + } + + this.dirty = true; + } + + return this; + }, + + /** + * Internal method that handles the drawing of an array of children. + * + * @method Phaser.GameObjects.RenderTexture#batchList + * @private + * @since 3.12.0 + * + * @param {array} children - The array of Game Objects to draw. + * @param {number} [x] - The x position to offset the Game Object by. + * @param {number} [y] - The y position to offset the Game Object by. + * @param {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. + * @param {number} [tint] - The tint color to use. If not specified it uses the `globalTint` property. + */ + batchList: function (children, x, y, alpha, tint) + { + for (var i = 0; i < children.length; i++) + { + var entry = children[i]; + + if (!entry || entry === this) + { + continue; + } + + if (entry.renderWebGL || entry.renderCanvas) + { + // Game Objects + this.drawGameObject(entry, x, y); + } + else if (entry.isParent || entry.list) + { + // Groups / Display Lists + this.batchGroup(entry.getChildren(), x, y); + } + else if (typeof entry === 'string') + { + // Texture key + this.batchTextureFrameKey(entry, null, x, y, alpha, tint); + } + else if (entry instanceof Frame) + { + // Texture Frame instance + this.batchTextureFrame(entry, x, y, alpha, tint); + } + else if (Array.isArray(entry)) + { + // Another Array + this.batchList(entry, x, y, alpha, tint); + } + } + }, + + /** + * Internal method that handles the drawing a Phaser Group contents. + * + * @method Phaser.GameObjects.RenderTexture#batchGroup + * @private + * @since 3.12.0 + * + * @param {array} children - The array of Game Objects to draw. + * @param {number} [x=0] - The x position to offset the Game Object by. + * @param {number} [y=0] - The y position to offset the Game Object by. + */ + batchGroup: function (children, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + x += this.frame.cutX; + y += this.frame.cutY; + + for (var i = 0; i < children.length; i++) + { + var entry = children[i]; + + if (entry.willRender()) + { + var tx = entry.x + x; + var ty = entry.y + y; + + this.drawGameObject(entry, tx, ty); + } + } + }, + + /** + * Internal method that handles drawing a single Phaser Game Object to this Render Texture using WebGL. + * + * @method Phaser.GameObjects.RenderTexture#batchGameObjectWebGL + * @private + * @since 3.12.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to draw. + * @param {number} [x] - The x position to draw the Game Object at. + * @param {number} [y] - The y position to draw the Game Object at. + */ + batchGameObjectWebGL: function (gameObject, x, y) + { + if (x === undefined) { x = gameObject.x; } + if (y === undefined) { y = gameObject.y; } + + var prevX = gameObject.x; + var prevY = gameObject.y; + + if (!this._eraseMode) + { + this.renderer.setBlendMode(gameObject.blendMode); + } + + gameObject.setPosition(x + this.frame.cutX, y + this.frame.cutY); + + gameObject.renderWebGL(this.renderer, gameObject, 0, this.camera, null); + + gameObject.setPosition(prevX, prevY); + }, + + /** + * Internal method that handles drawing a single Phaser Game Object to this Render Texture using Canvas. + * + * @method Phaser.GameObjects.RenderTexture#batchGameObjectCanvas + * @private + * @since 3.12.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to draw. + * @param {number} [x] - The x position to draw the Game Object at. + * @param {number} [y] - The y position to draw the Game Object at. + */ + batchGameObjectCanvas: function (gameObject, x, y) + { + if (x === undefined) { x = gameObject.x; } + if (y === undefined) { y = gameObject.y; } + + var prevX = gameObject.x; + var prevY = gameObject.y; + + if (this._eraseMode) + { + var blendMode = gameObject.blendMode; + + gameObject.blendMode = BlendModes.ERASE; + } + + gameObject.setPosition(x + this.frame.cutX, y + this.frame.cutY); + + gameObject.renderCanvas(this.renderer, gameObject, 0, this.camera, null); + + gameObject.setPosition(prevX, prevY); + + if (this._eraseMode) + { + gameObject.blendMode = blendMode; + } + }, + + /** + * Internal method that handles the drawing of an array of children. + * + * @method Phaser.GameObjects.RenderTexture#batchTextureFrameKey + * @private + * @since 3.12.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * @param {number} [x=0] - The x position to offset the Game Object by. + * @param {number} [y=0] - The y position to offset the Game Object by. + * @param {number} [alpha] - The alpha to use. If not specified it uses the `globalAlpha` property. + * @param {number} [tint] - The tint color to use. If not specified it uses the `globalTint` property. + */ + batchTextureFrameKey: function (key, frame, x, y, alpha, tint) + { + var textureFrame = this.textureManager.getFrame(key, frame); + + if (textureFrame) + { + this.batchTextureFrame(textureFrame, x, y, alpha, tint); + } + }, + + /** + * Internal method that handles the drawing of a Texture Frame to this Render Texture. + * + * @method Phaser.GameObjects.RenderTexture#batchTextureFrame + * @private + * @since 3.12.0 + * + * @param {Phaser.Textures.Frame} textureFrame - The Texture Frame to draw. + * @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 {number} [tint] - A tint color to be applied to the frame drawn to the Render Texture. + */ + batchTextureFrame: function (textureFrame, x, y, alpha, tint) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + x += this.frame.cutX; + y += this.frame.cutY; + + if (this.gl) + { + this.pipeline.batchTextureFrame(textureFrame, x, y, tint, alpha, this.camera.matrix, null); + } + else + { + var ctx = this.context; + var cd = textureFrame.canvasData; + var source = textureFrame.source.image; + + var matrix = this.camera.matrix; + + ctx.globalAlpha = this.globalAlpha; + + ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); + + ctx.drawImage(source, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); + } + }, + + /** + * Takes a snapshot of the given area of this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture the whole Render Texture see the `snapshot` method. To capture a specific pixel, see `snapshotPixel`. + * + * 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.GameObjects.RenderTexture#snapshotArea + * @since 3.19.0 + * + * @param {integer} x - The x coordinate to grab from. + * @param {integer} y - The y coordinate to grab from. + * @param {integer} width - The width of the area to grab. + * @param {integer} 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 Render Texture instance. + */ + snapshotArea: function (x, y, width, height, callback, type, encoderOptions) + { + if (this.gl) + { + this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, false, x, y, width, height, type, encoderOptions); + } + else + { + this.renderer.snapshotCanvas(this.canvas, callback, false, x, y, width, height, type, encoderOptions); + } + + return this; + }, + + /** + * Takes a snapshot of the whole of this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture just a portion of the Render Texture see the `snapshotArea` method. To capture a specific pixel, see `snapshotPixel`. + * + * 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.GameObjects.RenderTexture#snapshot + * @since 3.19.0 + * + * @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 Render Texture instance. + */ + snapshot: function (callback, type, encoderOptions) + { + if (this.gl) + { + this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, false, 0, 0, this.width, this.height, type, encoderOptions); + } + else + { + this.renderer.snapshotCanvas(this.canvas, callback, false, 0, 0, this.width, this.height, type, encoderOptions); + } + + return this; + }, + + /** + * Takes a snapshot of the given pixel from this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture the whole Render Texture see the `snapshot` method. To capture a specific portion, see `snapshotArea`. + * + * Unlike the other two snapshot methods, this one will send your callback 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, than the other snapshot methods. + * + * @method Phaser.GameObjects.RenderTexture#snapshotPixel + * @since 3.19.0 + * + * @param {integer} x - The x coordinate of the pixel to get. + * @param {integer} y - The y coordinate of the pixel to get. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. + * + * @return {this} This Render Texture instance. + */ + snapshotPixel: function (x, y, callback) + { + if (this.gl) + { + this.renderer.snapshotFramebuffer(this.framebuffer, this.width, this.height, callback, true, x, y); + } + else + { + this.renderer.snapshotCanvas(this.canvas, callback, true, x, y); + } + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.RenderTexture#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + if (!this._saved) + { + CanvasPool.remove(this.canvas); + + if (this.gl) + { + this.renderer.deleteFramebuffer(this.framebuffer); + } + + this.texture.destroy(); + this.camera.destroy(); + + this.canvas = null; + this.context = null; + this.framebuffer = null; + this.texture = null; + this.glTexture = null; + } + } + +}); + +module.exports = RenderTexture; diff --git a/src/gameobjects/rendertexture/RenderTextureCanvasRenderer.js b/src/gameobjects/rendertexture/RenderTextureCanvasRenderer.js index 19a93466e..29d3c0799 100644 --- a/src/gameobjects/rendertexture/RenderTextureCanvasRenderer.js +++ b/src/gameobjects/rendertexture/RenderTextureCanvasRenderer.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.RenderTexture#renderCanvas - * @since 3.2.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.RenderTexture} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RenderTextureCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - renderer.batchSprite(src, src.frame, camera, parentMatrix); -}; - -module.exports = RenderTextureCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.RenderTexture#renderCanvas + * @since 3.2.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.RenderTexture} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RenderTextureCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = RenderTextureCanvasRenderer; diff --git a/src/gameobjects/rendertexture/RenderTextureCreator.js b/src/gameobjects/rendertexture/RenderTextureCreator.js index 71d5ce953..f4dd9eee3 100644 --- a/src/gameobjects/rendertexture/RenderTextureCreator.js +++ b/src/gameobjects/rendertexture/RenderTextureCreator.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var RenderTexture = require('./RenderTexture'); - -/** - * Creates a new Render Texture Game Object and returns it. - * - * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#renderTexture - * @since 3.2.0 - * - * @param {Phaser.Types.GameObjects.RenderTexture.RenderTextureConfig} 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.RenderTexture} The Game Object that was created. - */ -GameObjectCreator.register('renderTexture', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var x = GetAdvancedValue(config, 'x', 0); - var y = GetAdvancedValue(config, 'y', 0); - var width = GetAdvancedValue(config, 'width', 32); - var height = GetAdvancedValue(config, 'height', 32); - var key = GetAdvancedValue(config, 'key', undefined); - var frame = GetAdvancedValue(config, 'frame', undefined); - - var renderTexture = new RenderTexture(this.scene, x, y, width, height, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, renderTexture, config); - - return renderTexture; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var RenderTexture = require('./RenderTexture'); + +/** + * Creates a new Render Texture Game Object and returns it. + * + * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#renderTexture + * @since 3.2.0 + * + * @param {Phaser.Types.GameObjects.RenderTexture.RenderTextureConfig} 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.RenderTexture} The Game Object that was created. + */ +GameObjectCreator.register('renderTexture', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 32); + var height = GetAdvancedValue(config, 'height', 32); + var key = GetAdvancedValue(config, 'key', undefined); + var frame = GetAdvancedValue(config, 'frame', undefined); + + var renderTexture = new RenderTexture(this.scene, x, y, width, height, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, renderTexture, config); + + return renderTexture; +}); diff --git a/src/gameobjects/rendertexture/RenderTextureFactory.js b/src/gameobjects/rendertexture/RenderTextureFactory.js index 5b58e80d3..ae675bdb6 100644 --- a/src/gameobjects/rendertexture/RenderTextureFactory.js +++ b/src/gameobjects/rendertexture/RenderTextureFactory.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../GameObjectFactory'); -var RenderTexture = require('./RenderTexture'); - -/** - * Creates a new Render Texture Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. - * - * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and - * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic - * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. - * - * @method Phaser.GameObjects.GameObjectFactory#renderTexture - * @since 3.2.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 {integer} [width=32] - The width of the Render Texture. - * @param {integer} [height=32] - The height of the Render Texture. - * @property {string} [key] - The texture key to make the RenderTexture from. - * @property {string} [frame] - the frame to make the RenderTexture from. - * - * @return {Phaser.GameObjects.RenderTexture} The Game Object that was created. - */ -GameObjectFactory.register('renderTexture', function (x, y, width, height, key, frame) -{ - return this.displayList.add(new RenderTexture(this.scene, x, y, width, height, key, frame)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../GameObjectFactory'); +var RenderTexture = require('./RenderTexture'); + +/** + * Creates a new Render Texture Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. + * + * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and + * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic + * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. + * + * @method Phaser.GameObjects.GameObjectFactory#renderTexture + * @since 3.2.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 {integer} [width=32] - The width of the Render Texture. + * @param {integer} [height=32] - The height of the Render Texture. + * @property {string} [key] - The texture key to make the RenderTexture from. + * @property {string} [frame] - the frame to make the RenderTexture from. + * + * @return {Phaser.GameObjects.RenderTexture} The Game Object that was created. + */ +GameObjectFactory.register('renderTexture', function (x, y, width, height, key, frame) +{ + return this.displayList.add(new RenderTexture(this.scene, x, y, width, height, key, frame)); +}); diff --git a/src/gameobjects/rendertexture/RenderTextureRender.js b/src/gameobjects/rendertexture/RenderTextureRender.js index dad7fe392..89230a315 100644 --- a/src/gameobjects/rendertexture/RenderTextureRender.js +++ b/src/gameobjects/rendertexture/RenderTextureRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./RenderTextureWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./RenderTextureCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./RenderTextureWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./RenderTextureCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/rendertexture/RenderTextureWebGLRenderer.js b/src/gameobjects/rendertexture/RenderTextureWebGLRenderer.js index e0119f60f..a3925f050 100644 --- a/src/gameobjects/rendertexture/RenderTextureWebGLRenderer.js +++ b/src/gameobjects/rendertexture/RenderTextureWebGLRenderer.js @@ -1,57 +1,57 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.RenderTexture#renderWebGL - * @since 3.2.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.RenderTexture} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RenderTextureWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var frame = src.frame; - var width = frame.width; - var height = frame.height; - var getTint = Utils.getTintAppendFloatAlpha; - - this.pipeline.batchTexture( - src, - frame.glTexture, - width, height, - src.x, src.y, - width, height, - src.scaleX, src.scaleY, - src.rotation, - src.flipX, !src.flipY, - src.scrollFactorX, src.scrollFactorY, - src.displayOriginX, src.displayOriginY, - 0, 0, width, height, - getTint(src._tintTL, camera.alpha * src._alphaTL), - getTint(src._tintTR, camera.alpha * src._alphaTR), - getTint(src._tintBL, camera.alpha * src._alphaBL), - getTint(src._tintBR, camera.alpha * src._alphaBR), - (src._isTinted && src.tintFill), - 0, 0, - camera, - parentMatrix - ); - - // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it - renderer.setBlankTexture(true); -}; - -module.exports = RenderTextureWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.RenderTexture#renderWebGL + * @since 3.2.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.RenderTexture} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RenderTextureWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var frame = src.frame; + var width = frame.width; + var height = frame.height; + var getTint = Utils.getTintAppendFloatAlpha; + + this.pipeline.batchTexture( + src, + frame.glTexture, + width, height, + src.x, src.y, + width, height, + src.scaleX, src.scaleY, + src.rotation, + src.flipX, !src.flipY, + src.scrollFactorX, src.scrollFactorY, + src.displayOriginX, src.displayOriginY, + 0, 0, width, height, + getTint(src._tintTL, camera.alpha * src._alphaTL), + getTint(src._tintTR, camera.alpha * src._alphaTR), + getTint(src._tintBL, camera.alpha * src._alphaBL), + getTint(src._tintBR, camera.alpha * src._alphaBR), + (src._isTinted && src.tintFill), + 0, 0, + camera, + parentMatrix + ); + + // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it + renderer.setBlankTexture(true); +}; + +module.exports = RenderTextureWebGLRenderer; diff --git a/src/gameobjects/rendertexture/typedefs/index.js b/src/gameobjects/rendertexture/typedefs/index.js index 9f907b444..56aeb0e05 100644 --- a/src/gameobjects/rendertexture/typedefs/index.js +++ b/src/gameobjects/rendertexture/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.RenderTexture - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.RenderTexture + */ diff --git a/src/gameobjects/rope/Rope.js b/src/gameobjects/rope/Rope.js index 5f1c809df..ad193696f 100644 --- a/src/gameobjects/rope/Rope.js +++ b/src/gameobjects/rope/Rope.js @@ -1,1100 +1,1100 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var RopeRender = require('./RopeRender'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Rope Game Object. - * - * A Ropes origin is always 0.5 x 0.5 and cannot be changed. - * - * @class Rope - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @webglOnly - * @since 3.23.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * @extends Phaser.GameObjects.Components.ScrollFactor - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {string} [texture] - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. If not given, `__DEFAULT` is used. - * @param {(string|integer|null)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {(integer|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. See `setPoints` to set this post-creation. - * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? - * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. - * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. - */ -var Rope = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.Mask, - Components.Pipeline, - Components.Size, - Components.Texture, - Components.Transform, - Components.Visible, - Components.ScrollFactor, - RopeRender - ], - - initialize: - - function Rope (scene, x, y, texture, frame, points, horizontal, colors, alphas) - { - if (texture === undefined) { texture = '__DEFAULT'; } - if (points === undefined) { points = 2; } - if (horizontal === undefined) { horizontal = true; } - - GameObject.call(this, scene, 'Rope'); - - /** - * The Animation Controller of this Rope. - * - * @name Phaser.GameObjects.Rope#anims - * @type {Phaser.GameObjects.Components.Animation} - * @since 3.23.0 - */ - this.anims = new Components.Animation(this); - - /** - * An array containing the points data for this Rope. - * - * Each point should be given as a Vector2Like object (i.e. a Vector2, Geom.Point or object with public x/y properties). - * - * The point coordinates are given in local space, where 0 x 0 is the start of the Rope strip. - * - * You can modify the contents of this array directly in real-time to create interesting effects. - * If you do so, be sure to call `setDirty` _after_ modifying this array, so that the vertices data is - * updated before the next render. Alternatively, you can use the `setPoints` method instead. - * - * Should you need to change the _size_ of this array, then you should always use the `setPoints` method. - * - * @name Phaser.GameObjects.Rope#points - * @type {Phaser.Math.Types.Vector2Like[]} - * @since 3.23.0 - */ - this.points = points; - - /** - * 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 - */ - this.vertices; - - /** - * 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 - */ - this.uv; - - /** - * An array containing the color data for this Rope. - * - * Colors should be given as numeric RGB values, such as 0xff0000. - * You should provide _two_ color values for every point in the Rope, one for the top and one for the bottom of each quad. - * - * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ - * of the array, then you should use the `setColors` method instead. - * - * @name Phaser.GameObjects.Rope#colors - * @type {Uint32Array} - * @since 3.23.0 - */ - this.colors; - - /** - * An array containing the alpha data for this Rope. - * - * Alphas should be given as float values, such as 0.5. - * You should provide _two_ alpha values for every point in the Rope, one for the top and one for the bottom of each quad. - * - * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ - * of the array, then you should use the `setAlphas` method instead. - * - * @name Phaser.GameObjects.Rope#alphas - * @type {Float32Array} - * @since 3.23.0 - */ - this.alphas; - - /** - * The tint fill mode. - * - * 0 = An additive tint (the default), where vertices colors are blended with the texture. - * 1 = A fill tint, where the vertices colors replace the texture, but respects texture alpha. - * 2 = A complete tint, where the vertices colors replace the texture, including alpha, entirely. - * - * @name Phaser.GameObjects.Rope#tintFill - * @type {integer} - * @since 3.23.0 - */ - this.tintFill = (texture === '__DEFAULT') ? 2 : 0; - - /** - * If the Rope is marked as `dirty` it will automatically recalculate its vertices - * the next time it renders. You can also force this by calling `updateVertices`. - * - * @name Phaser.GameObjects.Rope#dirty - * @type {boolean} - * @since 3.23.0 - */ - this.dirty = false; - - /** - * Are the Rope vertices aligned horizontally, in a strip, or vertically, in a column? - * - * This property is set during instantiation and cannot be changed directly. - * See the `setVertical` and `setHorizontal` methods. - * - * @name Phaser.GameObjects.Rope#horizontal - * @type {boolean} - * @readonly - * @since 3.23.0 - */ - this.horizontal = horizontal; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#_flipX - * @type {boolean} - * @default false - * @private - * @since 3.23.0 - */ - this._flipX = false; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipY - * @type {boolean} - * @default false - * @private - * @since 3.23.0 - */ - this._flipY = false; - - /** - * Internal Vector2 used for vertices updates. - * - * @name Phaser.GameObjects.Rope#_perp - * @type {Phaser.Math.Vector2} - * @private - * @since 3.23.0 - */ - this._perp = new Vector2(); - - /** - * You can optionally choose to render the vertices of this Rope to a Graphics instance. - * - * Achieve this by setting the `debugCallback` and the `debugGraphic` properties. - * - * You can do this in a single call via the `Rope.setDebug` method, which will use the - * built-in debug function. You can also set it to your own callback. The callback - * will be invoked _once per render_ and sent the following parameters: - * - * `debugCallback(src, meshLength, verts)` - * - * `src` is the Rope instance being debugged. - * `meshLength` is the number of mesh vertices in total. - * `verts` is an array of the translated vertex coordinates. - * - * To disable rendering, set this property back to `null`. - * - * @name Phaser.GameObjects.Rope#debugCallback - * @type {function} - * @since 3.23.0 - */ - this.debugCallback = null; - - /** - * The Graphics instance that the debug vertices will be drawn to, if `setDebug` has - * been called. - * - * @name Phaser.GameObjects.Rope#debugGraphic - * @type {Phaser.GameObjects.Graphics} - * @since 3.23.0 - */ - this.debugGraphic = null; - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.initPipeline('TextureTintStripPipeline'); - - if (Array.isArray(points)) - { - this.resizeArrays(points.length); - } - - this.setPoints(points, colors, alphas); - - this.updateVertices(); - }, - - /** - * The Rope update loop. - * - * @method Phaser.GameObjects.Rope#preUpdate - * @protected - * @since 3.23.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - var prevFrame = this.anims.currentFrame; - - this.anims.update(time, delta); - - if (this.anims.currentFrame !== prevFrame) - { - this.updateUVs(); - this.updateVertices(); - } - }, - - /** - * Start playing the given animation. - * - * @method Phaser.GameObjects.Rope#play - * @since 3.23.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Game Object. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - this.anims.play(key, ignoreIfPlaying, startFrame); - - return this; - }, - - /** - * Flags this Rope as being dirty. A dirty rope will recalculate all of its vertices data - * the _next_ time it renders. You should set this rope as dirty if you update the points - * array directly. - * - * @method Phaser.GameObjects.Rope#setDirty - * @since 3.23.0 - * - * @return {this} This Game Object instance. - */ - setDirty: function () - { - this.dirty = true; - - return this; - }, - - /** - * Sets the alignment of the points in this Rope to be horizontal, in a strip format. - * - * Calling this method will reset this Rope. The current points, vertices, colors and alpha - * values will be reset to thoes values given as parameters. - * - * @method Phaser.GameObjects.Rope#setHorizontal - * @since 3.23.0 - * - * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. - * @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. - */ - setHorizontal: function (points, colors, alphas) - { - if (points === undefined) { points = this.points.length; } - - if (this.horizontal) - { - return this; - } - - this.horizontal = true; - - return this.setPoints(points, colors, alphas); - }, - - /** - * Sets the alignment of the points in this Rope to be vertical, in a column format. - * - * Calling this method will reset this Rope. The current points, vertices, colors and alpha - * values will be reset to thoes values given as parameters. - * - * @method Phaser.GameObjects.Rope#setVertical - * @since 3.23.0 - * - * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. - * @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. - */ - setVertical: function (points, colors, alphas) - { - if (points === undefined) { points = this.points.length; } - - if (!this.horizontal) - { - return this; - } - - this.horizontal = false; - - return this.setPoints(points, colors, alphas); - }, - - /** - * Sets the tint fill mode. - * - * Mode 0 is an additive tint, the default, which blends the vertices colors with the texture. - * This mode respects the texture alpha. - * - * Mode 1 is a fill tint. Unlike an additive tint, a fill-tint literally replaces the pixel colors - * from the texture with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. This mode respects the texture alpha. - * - * Mode 2 is a complete tint. The texture colors and alpha are replaced entirely by the vertices colors. - * - * See the `setColors` method for details of how to color each of the vertices. - * - * @method Phaser.GameObjects.Rope#setTintFill - * @webglOnly - * @since 3.23.0 - * - * @param {integer} [value=0] - Set to 0 for an Additive tint, 1 for a fill tint with alpha, or 2 for a fill tint without alpha. - * - * @return {this} This Game Object instance. - */ - setTintFill: function (value) - { - if (value === undefined) { value = 0; } - - this.tintFill = value; - - return this; - }, - - /** - * Set the alpha values used by the Rope during rendering. - * - * You can provide the values in a number of ways: - * - * 1) One single numeric value: `setAlphas(0.5)` - This will set a single alpha for the whole Rope. - * 2) Two numeric value: `setAlphas(1, 0.5)` - This will set a 'top' and 'bottom' alpha value across the whole Rope. - * 3) An array of values: `setAlphas([ 1, 0.5, 0.2 ])` - * - * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it - * will use each alpha value per rope segment. - * - * If the provided array has a different number of values than `points` then it will use the values in order, from - * the first Rope segment and on, until it runs out of values. This allows you to control the alpha values at all - * vertices in the Rope. - * - * Note this method is called `setAlphas` (plural) and not `setAlpha`. - * - * @method Phaser.GameObjects.Rope#setAlphas - * @since 3.23.0 - * - * @param {(number|number[])} [alphas] - Either a single alpha value, or an array of values. If nothing is provided alpha is reset to 1. - * @param {number} [bottomAlpha] - An optional bottom alpha value. See the method description for details. - * - * @return {this} This Game Object instance. - */ - setAlphas: function (alphas, bottomAlpha) - { - var total = this.points.length; - - if (total < 1) - { - return this; - } - - var currentAlphas = this.alphas; - - if (alphas === undefined) - { - alphas = [ 1 ]; - } - else if (!Array.isArray(alphas) && bottomAlpha === undefined) - { - alphas = [ alphas ]; - } - - var i; - var index = 0; - - if (bottomAlpha !== undefined) - { - // Top / Bottom alpha pair - for (i = 0; i < total; i++) - { - index = i * 2; - - currentAlphas[index] = alphas; - currentAlphas[index + 1] = bottomAlpha; - } - } - else if (alphas.length === total) - { - // If there are exactly the same number of alphas as points, we'll combine the alphas - for (i = 0; i < total; i++) - { - index = i * 2; - - currentAlphas[index] = alphas[i]; - currentAlphas[index + 1] = alphas[i]; - } - } - else - { - var prevAlpha = alphas[0]; - - for (i = 0; i < total; i++) - { - index = i * 2; - - if (alphas.length > index) - { - prevAlpha = alphas[index]; - } - - currentAlphas[index] = prevAlpha; - - if (alphas.length > index + 1) - { - prevAlpha = alphas[index + 1]; - } - - currentAlphas[index + 1] = prevAlpha; - } - } - - return this; - - }, - - /** - * Set the color values used by the Rope during rendering. - * - * Colors are used to control the level of tint applied across the Rope texture. - * - * You can provide the values in a number of ways: - * - * * One single numeric value: `setColors(0xff0000)` - This will set a single color tint for the whole Rope. - * * An array of values: `setColors([ 0xff0000, 0x00ff00, 0x0000ff ])` - * - * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it - * will use each color per rope segment. - * - * If the provided array has a different number of values than `points` then it will use the values in order, from - * the first Rope segment and on, until it runs out of values. This allows you to control the color values at all - * vertices in the Rope. - * - * @method Phaser.GameObjects.Rope#setColors - * @since 3.23.0 - * - * @param {(number|number[])} [colors] - Either a single color value, or an array of values. If nothing is provided color is reset to 0xffffff. - * - * @return {this} This Game Object instance. - */ - setColors: function (colors) - { - var total = this.points.length; - - if (total < 1) - { - return this; - } - - var currentColors = this.colors; - - if (colors === undefined) - { - colors = [ 0xffffff ]; - } - else if (!Array.isArray(colors)) - { - colors = [ colors ]; - } - - var i; - var index = 0; - - if (colors.length === total) - { - // If there are exactly the same number of colors as points, we'll combine the colors - for (i = 0; i < total; i++) - { - index = i * 2; - - currentColors[index] = colors[i]; - currentColors[index + 1] = colors[i]; - } - } - else - { - var prevColor = colors[0]; - - for (i = 0; i < total; i++) - { - index = i * 2; - - if (colors.length > index) - { - prevColor = colors[index]; - } - - currentColors[index] = prevColor; - - if (colors.length > index + 1) - { - prevColor = colors[index + 1]; - } - - currentColors[index + 1] = prevColor; - } - } - - return this; - }, - - /** - * 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 {(integer|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. - */ - setPoints: function (points, colors, alphas) - { - if (points === undefined) { points = 2; } - - if (typeof points === 'number') - { - // Generate an array based on the points - var segments = points; - - if (segments < 2) - { - segments = 2; - } - - points = []; - - var s; - var frameSegment; - var offset; - - if (this.horizontal) - { - offset = -(this.frame.halfWidth); - frameSegment = this.frame.width / (segments - 1); - - for (s = 0; s < segments; s++) - { - points.push({ x: offset + s * frameSegment, y: 0 }); - } - } - else - { - offset = -(this.frame.halfHeight); - frameSegment = this.frame.height / (segments - 1); - - for (s = 0; s < segments; s++) - { - points.push({ x: 0, y: offset + s * frameSegment }); - } - } - } - - var total = points.length; - var currentTotal = this.points.length; - - if (total < 1) - { - console.warn('Rope: Not enough points given'); - - return this; - } - else if (total === 1) - { - points.unshift({ x: 0, y: 0 }); - total++; - } - - if (currentTotal !== total) - { - this.resizeArrays(total); - } - - this.points = points; - - this.updateUVs(); - - if (colors !== undefined && colors !== null) - { - this.setColors(colors); - } - - if (alphas !== undefined && alphas !== null) - { - this.setAlphas(alphas); - } - - return this; - }, - - /** - * 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. - */ - updateUVs: function () - { - var currentUVs = this.uv; - var total = this.points.length; - - var u0 = this.frame.u0; - var v0 = this.frame.v0; - var u1 = this.frame.u1; - var v1 = this.frame.v1; - - var partH = (u1 - u0) / (total - 1); - var partV = (v1 - v0) / (total - 1); - - for (var i = 0; i < total; i++) - { - var index = i * 4; - - var uv0; - var uv1; - var uv2; - var uv3; - - if (this.horizontal) - { - if (this._flipX) - { - uv0 = u1 - (i * partH); - uv2 = u1 - (i * partH); - } - else - { - uv0 = u0 + (i * partH); - uv2 = u0 + (i * partH); - } - - if (this._flipY) - { - uv1 = v1; - uv3 = v0; - } - else - { - uv1 = v0; - uv3 = v1; - } - } - else - { - if (this._flipX) - { - uv0 = u0; - uv2 = u1; - } - else - { - uv0 = u1; - uv2 = u0; - } - - if (this._flipY) - { - uv1 = v1 - (i * partV); - uv3 = v1 - (i * partV); - } - else - { - uv1 = v0 + (i * partV); - uv3 = v0 + (i * partV); - } - } - - currentUVs[index + 0] = uv0; - currentUVs[index + 1] = uv1; - currentUVs[index + 2] = uv2; - currentUVs[index + 3] = uv3; - } - - return this; - }, - - /** - * Resizes all of the internal arrays: `vertices`, `uv`, `colors` and `alphas` to the new - * given Rope segment total. - * - * @method Phaser.GameObjects.Rope#resizeArrays - * @since 3.23.0 - * - * @param {integer} newSize - The amount of segments to split the Rope in to. - * - * @return {this} This Game Object instance. - */ - resizeArrays: function (newSize) - { - var colors = this.colors; - var alphas = this.alphas; - - this.vertices = new Float32Array(newSize * 4); - this.uv = new Float32Array(newSize * 4); - - colors = new Uint32Array(newSize * 2); - alphas = new Float32Array(newSize * 2); - - for (var i = 0; i < newSize * 2; i++) - { - colors[i] = 0xffffff; - alphas[i] = 1; - } - - this.colors = colors; - this.alphas = alphas; - - // updateVertices during next render - this.dirty = true; - - return this; - }, - - /** - * 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. - */ - updateVertices: function () - { - var perp = this._perp; - var points = this.points; - var vertices = this.vertices; - - var total = points.length; - - this.dirty = false; - - if (total < 1) - { - return; - } - - var nextPoint; - var lastPoint = points[0]; - - var frameSize = (this.horizontal) ? this.frame.halfHeight : this.frame.halfWidth; - - for (var i = 0; i < total; i++) - { - var point = points[i]; - var index = i * 4; - - if (i < total - 1) - { - nextPoint = points[i + 1]; - } - else - { - nextPoint = point; - } - - perp.x = nextPoint.y - lastPoint.y; - perp.y = -(nextPoint.x - lastPoint.x); - - var perpLength = perp.length(); - - perp.x /= perpLength; - perp.y /= perpLength; - - perp.x *= frameSize; - perp.y *= frameSize; - - vertices[index] = point.x + perp.x; - vertices[index + 1] = point.y + perp.y; - vertices[index + 2] = point.x - perp.x; - vertices[index + 3] = point.y - perp.y; - - lastPoint = point; - } - - return this; - }, - - /** - * This method enables rendering of the Rope vertices to the given Graphics instance. - * - * If you enable this feature, you must call `Graphics.clear()` in your Scene `update`, - * otherwise the Graphics instance will fill-in with draw calls. This is not done automatically - * to allow for you to debug render multiple Rope objects to a single Graphics instance. - * - * The Rope class has a built-in debug rendering callback `Rope.renderDebugVerts`, however - * you can also provide your own callback to be used instead. Do this by setting the `callback` parameter. - * - * The callback is invoked _once per render_ and sent the following parameters: - * - * `callback(src, meshLength, verts)` - * - * `src` is the Rope instance being debugged. - * `meshLength` is the number of mesh vertices in total. - * `verts` is an array of the translated vertex coordinates. - * - * If using your own callback you do not have to provide a Graphics instance to this method. - * - * To disable debug rendering, to either your own callback or the built-in one, call this method - * with no arguments. - * - * @method Phaser.GameObjects.Rope#setDebug - * @since 3.23.0 - * - * @param {Phaser.GameObjects.Graphics} [graphic] - The Graphic instance to render to if using the built-in callback. - * @param {function} [callback] - The callback to invoke during debug render. Leave as undefined to use the built-in callback. - * - * @return {this} This Game Object instance. - */ - setDebug: function (graphic, callback) - { - this.debugGraphic = graphic; - - if (!graphic && !callback) - { - this.debugCallback = null; - } - else if (!callback) - { - this.debugCallback = this.renderDebugVerts; - } - else - { - this.debugCallback = callback; - } - - return this; - }, - - /** - * The built-in Rope vertices debug rendering method. - * - * See `Rope.setDebug` for more details. - * - * @method Phaser.GameObjects.Rope#renderDebugVerts - * @since 3.23.0 - * - * @param {Phaser.GameObjects.Rope} src - The Rope object being rendered. - * @param {integer} meshLength - The number of vertices in the mesh. - * @param {number[]} verts - An array of translated vertex coordinates. - */ - renderDebugVerts: function (src, meshLength, verts) - { - var graphic = src.debugGraphic; - - var px0 = verts[0]; - var py0 = verts[1]; - var px1 = verts[2]; - var py1 = verts[3]; - - graphic.lineBetween(px0, py0, px1, py1); - - for (var i = 4; i < meshLength; i += 4) - { - var x0 = verts[i + 0]; - var y0 = verts[i + 1]; - var x1 = verts[i + 2]; - var y1 = verts[i + 3]; - - graphic.lineBetween(px0, py0, x0, y0); - graphic.lineBetween(px1, py1, x1, y1); - graphic.lineBetween(px1, py1, x0, y0); - graphic.lineBetween(x0, y0, x1, y1); - - px0 = x0; - py0 = y0; - px1 = x1; - py1 = y1; - } - }, - - /** - * Handles the pre-destroy step for the Rope, which removes the Animation component and typed arrays. - * - * @method Phaser.GameObjects.Rope#preDestroy - * @private - * @since 3.23.0 - */ - preDestroy: function () - { - this.anims.destroy(); - - this.anims = undefined; - - this.points = null; - this.vertices = null; - this.uv = null; - this.colors = null; - this.alphas = null; - - this.debugCallback = null; - this.debugGraphic = null; - }, - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipX - * @type {boolean} - * @default false - * @since 3.23.0 - */ - flipX: { - - get: function () - { - return this._flipX; - }, - - set: function (value) - { - this._flipX = value; - - return this.updateUVs(); - } - - }, - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * - * @name Phaser.GameObjects.Rope#flipY - * @type {boolean} - * @default false - * @since 3.23.0 - */ - flipY: { - - get: function () - { - return this._flipY; - }, - - set: function (value) - { - this._flipY = value; - - return this.updateUVs(); - } - - } - -}); - -module.exports = Rope; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var RopeRender = require('./RopeRender'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Rope Game Object. + * + * A Ropes origin is always 0.5 x 0.5 and cannot be changed. + * + * @class Rope + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.23.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * @extends Phaser.GameObjects.Components.ScrollFactor + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {string} [texture] - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. If not given, `__DEFAULT` is used. + * @param {(string|integer|null)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {(integer|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. See `setPoints` to set this post-creation. + * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? + * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. + * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. + */ +var Rope = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.Mask, + Components.Pipeline, + Components.Size, + Components.Texture, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + RopeRender + ], + + initialize: + + function Rope (scene, x, y, texture, frame, points, horizontal, colors, alphas) + { + if (texture === undefined) { texture = '__DEFAULT'; } + if (points === undefined) { points = 2; } + if (horizontal === undefined) { horizontal = true; } + + GameObject.call(this, scene, 'Rope'); + + /** + * The Animation Controller of this Rope. + * + * @name Phaser.GameObjects.Rope#anims + * @type {Phaser.GameObjects.Components.Animation} + * @since 3.23.0 + */ + this.anims = new Components.Animation(this); + + /** + * An array containing the points data for this Rope. + * + * Each point should be given as a Vector2Like object (i.e. a Vector2, Geom.Point or object with public x/y properties). + * + * The point coordinates are given in local space, where 0 x 0 is the start of the Rope strip. + * + * You can modify the contents of this array directly in real-time to create interesting effects. + * If you do so, be sure to call `setDirty` _after_ modifying this array, so that the vertices data is + * updated before the next render. Alternatively, you can use the `setPoints` method instead. + * + * Should you need to change the _size_ of this array, then you should always use the `setPoints` method. + * + * @name Phaser.GameObjects.Rope#points + * @type {Phaser.Math.Types.Vector2Like[]} + * @since 3.23.0 + */ + this.points = points; + + /** + * 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 + */ + this.vertices; + + /** + * 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 + */ + this.uv; + + /** + * An array containing the color data for this Rope. + * + * Colors should be given as numeric RGB values, such as 0xff0000. + * You should provide _two_ color values for every point in the Rope, one for the top and one for the bottom of each quad. + * + * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ + * of the array, then you should use the `setColors` method instead. + * + * @name Phaser.GameObjects.Rope#colors + * @type {Uint32Array} + * @since 3.23.0 + */ + this.colors; + + /** + * An array containing the alpha data for this Rope. + * + * Alphas should be given as float values, such as 0.5. + * You should provide _two_ alpha values for every point in the Rope, one for the top and one for the bottom of each quad. + * + * You can modify the contents of this array directly in real-time, however, should you need to change the _size_ + * of the array, then you should use the `setAlphas` method instead. + * + * @name Phaser.GameObjects.Rope#alphas + * @type {Float32Array} + * @since 3.23.0 + */ + this.alphas; + + /** + * The tint fill mode. + * + * 0 = An additive tint (the default), where vertices colors are blended with the texture. + * 1 = A fill tint, where the vertices colors replace the texture, but respects texture alpha. + * 2 = A complete tint, where the vertices colors replace the texture, including alpha, entirely. + * + * @name Phaser.GameObjects.Rope#tintFill + * @type {integer} + * @since 3.23.0 + */ + this.tintFill = (texture === '__DEFAULT') ? 2 : 0; + + /** + * If the Rope is marked as `dirty` it will automatically recalculate its vertices + * the next time it renders. You can also force this by calling `updateVertices`. + * + * @name Phaser.GameObjects.Rope#dirty + * @type {boolean} + * @since 3.23.0 + */ + this.dirty = false; + + /** + * Are the Rope vertices aligned horizontally, in a strip, or vertically, in a column? + * + * This property is set during instantiation and cannot be changed directly. + * See the `setVertical` and `setHorizontal` methods. + * + * @name Phaser.GameObjects.Rope#horizontal + * @type {boolean} + * @readonly + * @since 3.23.0 + */ + this.horizontal = horizontal; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Rope#_flipX + * @type {boolean} + * @default false + * @private + * @since 3.23.0 + */ + this._flipX = false; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Rope#flipY + * @type {boolean} + * @default false + * @private + * @since 3.23.0 + */ + this._flipY = false; + + /** + * Internal Vector2 used for vertices updates. + * + * @name Phaser.GameObjects.Rope#_perp + * @type {Phaser.Math.Vector2} + * @private + * @since 3.23.0 + */ + this._perp = new Vector2(); + + /** + * You can optionally choose to render the vertices of this Rope to a Graphics instance. + * + * Achieve this by setting the `debugCallback` and the `debugGraphic` properties. + * + * You can do this in a single call via the `Rope.setDebug` method, which will use the + * built-in debug function. You can also set it to your own callback. The callback + * will be invoked _once per render_ and sent the following parameters: + * + * `debugCallback(src, meshLength, verts)` + * + * `src` is the Rope instance being debugged. + * `meshLength` is the number of mesh vertices in total. + * `verts` is an array of the translated vertex coordinates. + * + * To disable rendering, set this property back to `null`. + * + * @name Phaser.GameObjects.Rope#debugCallback + * @type {function} + * @since 3.23.0 + */ + this.debugCallback = null; + + /** + * The Graphics instance that the debug vertices will be drawn to, if `setDebug` has + * been called. + * + * @name Phaser.GameObjects.Rope#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.23.0 + */ + this.debugGraphic = null; + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.initPipeline('TextureTintStripPipeline'); + + if (Array.isArray(points)) + { + this.resizeArrays(points.length); + } + + this.setPoints(points, colors, alphas); + + this.updateVertices(); + }, + + /** + * The Rope update loop. + * + * @method Phaser.GameObjects.Rope#preUpdate + * @protected + * @since 3.23.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + preUpdate: function (time, delta) + { + var prevFrame = this.anims.currentFrame; + + this.anims.update(time, delta); + + if (this.anims.currentFrame !== prevFrame) + { + this.updateUVs(); + this.updateVertices(); + } + }, + + /** + * Start playing the given animation. + * + * @method Phaser.GameObjects.Rope#play + * @since 3.23.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {this} This Game Object. + */ + play: function (key, ignoreIfPlaying, startFrame) + { + this.anims.play(key, ignoreIfPlaying, startFrame); + + return this; + }, + + /** + * Flags this Rope as being dirty. A dirty rope will recalculate all of its vertices data + * the _next_ time it renders. You should set this rope as dirty if you update the points + * array directly. + * + * @method Phaser.GameObjects.Rope#setDirty + * @since 3.23.0 + * + * @return {this} This Game Object instance. + */ + setDirty: function () + { + this.dirty = true; + + return this; + }, + + /** + * Sets the alignment of the points in this Rope to be horizontal, in a strip format. + * + * Calling this method will reset this Rope. The current points, vertices, colors and alpha + * values will be reset to thoes values given as parameters. + * + * @method Phaser.GameObjects.Rope#setHorizontal + * @since 3.23.0 + * + * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. + * @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. + */ + setHorizontal: function (points, colors, alphas) + { + if (points === undefined) { points = this.points.length; } + + if (this.horizontal) + { + return this; + } + + this.horizontal = true; + + return this.setPoints(points, colors, alphas); + }, + + /** + * Sets the alignment of the points in this Rope to be vertical, in a column format. + * + * Calling this method will reset this Rope. The current points, vertices, colors and alpha + * values will be reset to thoes values given as parameters. + * + * @method Phaser.GameObjects.Rope#setVertical + * @since 3.23.0 + * + * @param {(integer|Phaser.Types.Math.Vector2Like[])} [points] - 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 the current points length is used. + * @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. + */ + setVertical: function (points, colors, alphas) + { + if (points === undefined) { points = this.points.length; } + + if (!this.horizontal) + { + return this; + } + + this.horizontal = false; + + return this.setPoints(points, colors, alphas); + }, + + /** + * Sets the tint fill mode. + * + * Mode 0 is an additive tint, the default, which blends the vertices colors with the texture. + * This mode respects the texture alpha. + * + * Mode 1 is a fill tint. Unlike an additive tint, a fill-tint literally replaces the pixel colors + * from the texture with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. This mode respects the texture alpha. + * + * Mode 2 is a complete tint. The texture colors and alpha are replaced entirely by the vertices colors. + * + * See the `setColors` method for details of how to color each of the vertices. + * + * @method Phaser.GameObjects.Rope#setTintFill + * @webglOnly + * @since 3.23.0 + * + * @param {integer} [value=0] - Set to 0 for an Additive tint, 1 for a fill tint with alpha, or 2 for a fill tint without alpha. + * + * @return {this} This Game Object instance. + */ + setTintFill: function (value) + { + if (value === undefined) { value = 0; } + + this.tintFill = value; + + return this; + }, + + /** + * Set the alpha values used by the Rope during rendering. + * + * You can provide the values in a number of ways: + * + * 1) One single numeric value: `setAlphas(0.5)` - This will set a single alpha for the whole Rope. + * 2) Two numeric value: `setAlphas(1, 0.5)` - This will set a 'top' and 'bottom' alpha value across the whole Rope. + * 3) An array of values: `setAlphas([ 1, 0.5, 0.2 ])` + * + * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it + * will use each alpha value per rope segment. + * + * If the provided array has a different number of values than `points` then it will use the values in order, from + * the first Rope segment and on, until it runs out of values. This allows you to control the alpha values at all + * vertices in the Rope. + * + * Note this method is called `setAlphas` (plural) and not `setAlpha`. + * + * @method Phaser.GameObjects.Rope#setAlphas + * @since 3.23.0 + * + * @param {(number|number[])} [alphas] - Either a single alpha value, or an array of values. If nothing is provided alpha is reset to 1. + * @param {number} [bottomAlpha] - An optional bottom alpha value. See the method description for details. + * + * @return {this} This Game Object instance. + */ + setAlphas: function (alphas, bottomAlpha) + { + var total = this.points.length; + + if (total < 1) + { + return this; + } + + var currentAlphas = this.alphas; + + if (alphas === undefined) + { + alphas = [ 1 ]; + } + else if (!Array.isArray(alphas) && bottomAlpha === undefined) + { + alphas = [ alphas ]; + } + + var i; + var index = 0; + + if (bottomAlpha !== undefined) + { + // Top / Bottom alpha pair + for (i = 0; i < total; i++) + { + index = i * 2; + + currentAlphas[index] = alphas; + currentAlphas[index + 1] = bottomAlpha; + } + } + else if (alphas.length === total) + { + // If there are exactly the same number of alphas as points, we'll combine the alphas + for (i = 0; i < total; i++) + { + index = i * 2; + + currentAlphas[index] = alphas[i]; + currentAlphas[index + 1] = alphas[i]; + } + } + else + { + var prevAlpha = alphas[0]; + + for (i = 0; i < total; i++) + { + index = i * 2; + + if (alphas.length > index) + { + prevAlpha = alphas[index]; + } + + currentAlphas[index] = prevAlpha; + + if (alphas.length > index + 1) + { + prevAlpha = alphas[index + 1]; + } + + currentAlphas[index + 1] = prevAlpha; + } + } + + return this; + + }, + + /** + * Set the color values used by the Rope during rendering. + * + * Colors are used to control the level of tint applied across the Rope texture. + * + * You can provide the values in a number of ways: + * + * * One single numeric value: `setColors(0xff0000)` - This will set a single color tint for the whole Rope. + * * An array of values: `setColors([ 0xff0000, 0x00ff00, 0x0000ff ])` + * + * If you provide an array of values and the array has exactly the same number of values as `points` in the Rope, it + * will use each color per rope segment. + * + * If the provided array has a different number of values than `points` then it will use the values in order, from + * the first Rope segment and on, until it runs out of values. This allows you to control the color values at all + * vertices in the Rope. + * + * @method Phaser.GameObjects.Rope#setColors + * @since 3.23.0 + * + * @param {(number|number[])} [colors] - Either a single color value, or an array of values. If nothing is provided color is reset to 0xffffff. + * + * @return {this} This Game Object instance. + */ + setColors: function (colors) + { + var total = this.points.length; + + if (total < 1) + { + return this; + } + + var currentColors = this.colors; + + if (colors === undefined) + { + colors = [ 0xffffff ]; + } + else if (!Array.isArray(colors)) + { + colors = [ colors ]; + } + + var i; + var index = 0; + + if (colors.length === total) + { + // If there are exactly the same number of colors as points, we'll combine the colors + for (i = 0; i < total; i++) + { + index = i * 2; + + currentColors[index] = colors[i]; + currentColors[index + 1] = colors[i]; + } + } + else + { + var prevColor = colors[0]; + + for (i = 0; i < total; i++) + { + index = i * 2; + + if (colors.length > index) + { + prevColor = colors[index]; + } + + currentColors[index] = prevColor; + + if (colors.length > index + 1) + { + prevColor = colors[index + 1]; + } + + currentColors[index + 1] = prevColor; + } + } + + return this; + }, + + /** + * 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 {(integer|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. + */ + setPoints: function (points, colors, alphas) + { + if (points === undefined) { points = 2; } + + if (typeof points === 'number') + { + // Generate an array based on the points + var segments = points; + + if (segments < 2) + { + segments = 2; + } + + points = []; + + var s; + var frameSegment; + var offset; + + if (this.horizontal) + { + offset = -(this.frame.halfWidth); + frameSegment = this.frame.width / (segments - 1); + + for (s = 0; s < segments; s++) + { + points.push({ x: offset + s * frameSegment, y: 0 }); + } + } + else + { + offset = -(this.frame.halfHeight); + frameSegment = this.frame.height / (segments - 1); + + for (s = 0; s < segments; s++) + { + points.push({ x: 0, y: offset + s * frameSegment }); + } + } + } + + var total = points.length; + var currentTotal = this.points.length; + + if (total < 1) + { + console.warn('Rope: Not enough points given'); + + return this; + } + else if (total === 1) + { + points.unshift({ x: 0, y: 0 }); + total++; + } + + if (currentTotal !== total) + { + this.resizeArrays(total); + } + + this.points = points; + + this.updateUVs(); + + if (colors !== undefined && colors !== null) + { + this.setColors(colors); + } + + if (alphas !== undefined && alphas !== null) + { + this.setAlphas(alphas); + } + + return this; + }, + + /** + * 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. + */ + updateUVs: function () + { + var currentUVs = this.uv; + var total = this.points.length; + + var u0 = this.frame.u0; + var v0 = this.frame.v0; + var u1 = this.frame.u1; + var v1 = this.frame.v1; + + var partH = (u1 - u0) / (total - 1); + var partV = (v1 - v0) / (total - 1); + + for (var i = 0; i < total; i++) + { + var index = i * 4; + + var uv0; + var uv1; + var uv2; + var uv3; + + if (this.horizontal) + { + if (this._flipX) + { + uv0 = u1 - (i * partH); + uv2 = u1 - (i * partH); + } + else + { + uv0 = u0 + (i * partH); + uv2 = u0 + (i * partH); + } + + if (this._flipY) + { + uv1 = v1; + uv3 = v0; + } + else + { + uv1 = v0; + uv3 = v1; + } + } + else + { + if (this._flipX) + { + uv0 = u0; + uv2 = u1; + } + else + { + uv0 = u1; + uv2 = u0; + } + + if (this._flipY) + { + uv1 = v1 - (i * partV); + uv3 = v1 - (i * partV); + } + else + { + uv1 = v0 + (i * partV); + uv3 = v0 + (i * partV); + } + } + + currentUVs[index + 0] = uv0; + currentUVs[index + 1] = uv1; + currentUVs[index + 2] = uv2; + currentUVs[index + 3] = uv3; + } + + return this; + }, + + /** + * Resizes all of the internal arrays: `vertices`, `uv`, `colors` and `alphas` to the new + * given Rope segment total. + * + * @method Phaser.GameObjects.Rope#resizeArrays + * @since 3.23.0 + * + * @param {integer} newSize - The amount of segments to split the Rope in to. + * + * @return {this} This Game Object instance. + */ + resizeArrays: function (newSize) + { + var colors = this.colors; + var alphas = this.alphas; + + this.vertices = new Float32Array(newSize * 4); + this.uv = new Float32Array(newSize * 4); + + colors = new Uint32Array(newSize * 2); + alphas = new Float32Array(newSize * 2); + + for (var i = 0; i < newSize * 2; i++) + { + colors[i] = 0xffffff; + alphas[i] = 1; + } + + this.colors = colors; + this.alphas = alphas; + + // updateVertices during next render + this.dirty = true; + + return this; + }, + + /** + * 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. + */ + updateVertices: function () + { + var perp = this._perp; + var points = this.points; + var vertices = this.vertices; + + var total = points.length; + + this.dirty = false; + + if (total < 1) + { + return; + } + + var nextPoint; + var lastPoint = points[0]; + + var frameSize = (this.horizontal) ? this.frame.halfHeight : this.frame.halfWidth; + + for (var i = 0; i < total; i++) + { + var point = points[i]; + var index = i * 4; + + if (i < total - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.x = nextPoint.y - lastPoint.y; + perp.y = -(nextPoint.x - lastPoint.x); + + var perpLength = perp.length(); + + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= frameSize; + perp.y *= frameSize; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + return this; + }, + + /** + * This method enables rendering of the Rope vertices to the given Graphics instance. + * + * If you enable this feature, you must call `Graphics.clear()` in your Scene `update`, + * otherwise the Graphics instance will fill-in with draw calls. This is not done automatically + * to allow for you to debug render multiple Rope objects to a single Graphics instance. + * + * The Rope class has a built-in debug rendering callback `Rope.renderDebugVerts`, however + * you can also provide your own callback to be used instead. Do this by setting the `callback` parameter. + * + * The callback is invoked _once per render_ and sent the following parameters: + * + * `callback(src, meshLength, verts)` + * + * `src` is the Rope instance being debugged. + * `meshLength` is the number of mesh vertices in total. + * `verts` is an array of the translated vertex coordinates. + * + * If using your own callback you do not have to provide a Graphics instance to this method. + * + * To disable debug rendering, to either your own callback or the built-in one, call this method + * with no arguments. + * + * @method Phaser.GameObjects.Rope#setDebug + * @since 3.23.0 + * + * @param {Phaser.GameObjects.Graphics} [graphic] - The Graphic instance to render to if using the built-in callback. + * @param {function} [callback] - The callback to invoke during debug render. Leave as undefined to use the built-in callback. + * + * @return {this} This Game Object instance. + */ + setDebug: function (graphic, callback) + { + this.debugGraphic = graphic; + + if (!graphic && !callback) + { + this.debugCallback = null; + } + else if (!callback) + { + this.debugCallback = this.renderDebugVerts; + } + else + { + this.debugCallback = callback; + } + + return this; + }, + + /** + * The built-in Rope vertices debug rendering method. + * + * See `Rope.setDebug` for more details. + * + * @method Phaser.GameObjects.Rope#renderDebugVerts + * @since 3.23.0 + * + * @param {Phaser.GameObjects.Rope} src - The Rope object being rendered. + * @param {integer} meshLength - The number of vertices in the mesh. + * @param {number[]} verts - An array of translated vertex coordinates. + */ + renderDebugVerts: function (src, meshLength, verts) + { + var graphic = src.debugGraphic; + + var px0 = verts[0]; + var py0 = verts[1]; + var px1 = verts[2]; + var py1 = verts[3]; + + graphic.lineBetween(px0, py0, px1, py1); + + for (var i = 4; i < meshLength; i += 4) + { + var x0 = verts[i + 0]; + var y0 = verts[i + 1]; + var x1 = verts[i + 2]; + var y1 = verts[i + 3]; + + graphic.lineBetween(px0, py0, x0, y0); + graphic.lineBetween(px1, py1, x1, y1); + graphic.lineBetween(px1, py1, x0, y0); + graphic.lineBetween(x0, y0, x1, y1); + + px0 = x0; + py0 = y0; + px1 = x1; + py1 = y1; + } + }, + + /** + * Handles the pre-destroy step for the Rope, which removes the Animation component and typed arrays. + * + * @method Phaser.GameObjects.Rope#preDestroy + * @private + * @since 3.23.0 + */ + preDestroy: function () + { + this.anims.destroy(); + + this.anims = undefined; + + this.points = null; + this.vertices = null; + this.uv = null; + this.colors = null; + this.alphas = null; + + this.debugCallback = null; + this.debugGraphic = null; + }, + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Rope#flipX + * @type {boolean} + * @default false + * @since 3.23.0 + */ + flipX: { + + get: function () + { + return this._flipX; + }, + + set: function (value) + { + this._flipX = value; + + return this.updateUVs(); + } + + }, + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * + * @name Phaser.GameObjects.Rope#flipY + * @type {boolean} + * @default false + * @since 3.23.0 + */ + flipY: { + + get: function () + { + return this._flipY; + }, + + set: function (value) + { + this._flipY = value; + + return this.updateUVs(); + } + + } + +}); + +module.exports = Rope; diff --git a/src/gameobjects/rope/RopeCanvasRenderer.js b/src/gameobjects/rope/RopeCanvasRenderer.js index 509a7b9d3..d56503279 100644 --- a/src/gameobjects/rope/RopeCanvasRenderer.js +++ b/src/gameobjects/rope/RopeCanvasRenderer.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This is a stub function for Rope.Render. There is no Canvas renderer for Rope objects. - * - * @method Phaser.GameObjects.Rope#renderCanvas - * @since 3.23.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var RopeCanvasRenderer = function () -{ -}; - -module.exports = RopeCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a stub function for Rope.Render. There is no Canvas renderer for Rope objects. + * + * @method Phaser.GameObjects.Rope#renderCanvas + * @since 3.23.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var RopeCanvasRenderer = function () +{ +}; + +module.exports = RopeCanvasRenderer; diff --git a/src/gameobjects/rope/RopeCreator.js b/src/gameobjects/rope/RopeCreator.js index b677017d2..3154534a3 100644 --- a/src/gameobjects/rope/RopeCreator.js +++ b/src/gameobjects/rope/RopeCreator.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetValue = require('../../utils/object/GetValue'); -var Rope = require('./Rope'); - -/** - * Creates a new Rope Game Object and returns it. - * - * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#rope - * @since 3.23.0 - * - * @param {object} 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.Rope} The Game Object that was created. - */ -GameObjectCreator.register('rope', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - var horizontal = GetAdvancedValue(config, 'horizontal', true); - var points = GetValue(config, 'points', undefined); - var colors = GetValue(config, 'colors', undefined); - var alphas = GetValue(config, 'alphas', undefined); - - var rope = new Rope(this.scene, 0, 0, key, frame, points, horizontal, colors, alphas); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, rope, config); - - return rope; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetValue = require('../../utils/object/GetValue'); +var Rope = require('./Rope'); + +/** + * Creates a new Rope Game Object and returns it. + * + * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#rope + * @since 3.23.0 + * + * @param {object} 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.Rope} The Game Object that was created. + */ +GameObjectCreator.register('rope', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + var horizontal = GetAdvancedValue(config, 'horizontal', true); + var points = GetValue(config, 'points', undefined); + var colors = GetValue(config, 'colors', undefined); + var alphas = GetValue(config, 'alphas', undefined); + + var rope = new Rope(this.scene, 0, 0, key, frame, points, horizontal, colors, alphas); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, rope, config); + + return rope; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/rope/RopeFactory.js b/src/gameobjects/rope/RopeFactory.js index 67e75b9fa..f55cec70e 100644 --- a/src/gameobjects/rope/RopeFactory.js +++ b/src/gameobjects/rope/RopeFactory.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rope = require('./Rope'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Rope Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#mesh - * @webglOnly - * @since 3.23.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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {Phaser.Types.Math.Vector2Like[]} [points] - An array containing the vertices data for this Rope. If none is provided a simple quad is created. See `setPoints` to set this post-creation. - * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? - * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. - * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. - * - * @return {Phaser.GameObjects.Rope} The Game Object that was created. - */ -if (typeof WEBGL_RENDERER) -{ - GameObjectFactory.register('rope', function (x, y, texture, frame, points, horizontal, colors, alphas) - { - var rope = new Rope(this.scene, x, y, texture, frame, points, horizontal, colors, alphas); - - this.displayList.add(rope); - - return this.updateList.add(rope); - }); -} - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rope = require('./Rope'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Rope Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Rope Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#mesh + * @webglOnly + * @since 3.23.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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.Math.Vector2Like[]} [points] - An array containing the vertices data for this Rope. If none is provided a simple quad is created. See `setPoints` to set this post-creation. + * @param {boolean} [horizontal=true] - Should the vertices of this Rope be aligned horizontally (`true`), or vertically (`false`)? + * @param {number[]} [colors] - An optional array containing the color data for this Rope. You should provide one color value per pair of vertices. + * @param {number[]} [alphas] - An optional array containing the alpha data for this Rope. You should provide one alpha value per pair of vertices. + * + * @return {Phaser.GameObjects.Rope} The Game Object that was created. + */ +if (typeof WEBGL_RENDERER) +{ + GameObjectFactory.register('rope', function (x, y, texture, frame, points, horizontal, colors, alphas) + { + var rope = new Rope(this.scene, x, y, texture, frame, points, horizontal, colors, alphas); + + this.displayList.add(rope); + + return this.updateList.add(rope); + }); +} + +// 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 diff --git a/src/gameobjects/rope/RopeRender.js b/src/gameobjects/rope/RopeRender.js index b2ea4a41c..a87df825f 100644 --- a/src/gameobjects/rope/RopeRender.js +++ b/src/gameobjects/rope/RopeRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./RopeWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./RopeCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./RopeWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./RopeCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/rope/RopeWebGLRenderer.js b/src/gameobjects/rope/RopeWebGLRenderer.js index 23398e06b..ce54ece39 100644 --- a/src/gameobjects/rope/RopeWebGLRenderer.js +++ b/src/gameobjects/rope/RopeWebGLRenderer.js @@ -1,133 +1,133 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Rope#renderWebGL - * @since 3.23.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RopeWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = src.pipeline; - - renderer.setPipeline(pipeline, src); - - var camMatrix = pipeline._tempMatrix1; - var spriteMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = src.x; - spriteMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * src.scrollFactorX; - spriteMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var frame = src.frame; - var texture = frame.glTexture; - - var vertices = src.vertices; - var uvs = src.uv; - var colors = src.colors; - var alphas = src.alphas; - var alpha = src.alpha; - var getTint = Utils.getTintAppendFloatAlphaAndSwap; - var roundPixels = camera.roundPixels; - - var meshVerticesLength = vertices.length; - var vertexCount = Math.floor(meshVerticesLength * 0.5); - - // Because it's a triangle strip and we don't want lots of degenerate triangles joining things up - pipeline.flush(); - - pipeline.setTexture2D(texture, 0); - - var vertexViewF32 = pipeline.vertexViewF32; - var vertexViewU32 = pipeline.vertexViewU32; - - var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; - - var colorIndex = 0; - - var tintEffect = src.tintFill; - - if (src.dirty) - { - src.updateVertices(); - } - - var debugCallback = src.debugCallback; - var debugVerts = []; - - for (var i = 0; i < meshVerticesLength; i += 2) - { - var x = vertices[i + 0]; - var y = vertices[i + 1]; - - var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; - var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; - - if (roundPixels) - { - tx = Math.round(tx); - ty = Math.round(ty); - } - - vertexViewF32[++vertexOffset] = tx; - vertexViewF32[++vertexOffset] = ty; - vertexViewF32[++vertexOffset] = uvs[i + 0]; - vertexViewF32[++vertexOffset] = uvs[i + 1]; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = getTint(colors[colorIndex], camera.alpha * (alphas[colorIndex] * alpha)); - - colorIndex++; - - if (debugCallback) - { - debugVerts[i + 0] = tx; - debugVerts[i + 1] = ty; - } - } - - if (debugCallback) - { - debugCallback.call(src, src, meshVerticesLength, debugVerts); - } - - pipeline.vertexCount += vertexCount; -}; - -module.exports = RopeWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Rope#renderWebGL + * @since 3.23.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Rope} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RopeWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = src.pipeline; + + renderer.setPipeline(pipeline, src); + + var camMatrix = pipeline._tempMatrix1; + var spriteMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = src.x; + spriteMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * src.scrollFactorX; + spriteMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var frame = src.frame; + var texture = frame.glTexture; + + var vertices = src.vertices; + var uvs = src.uv; + var colors = src.colors; + var alphas = src.alphas; + var alpha = src.alpha; + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + var roundPixels = camera.roundPixels; + + var meshVerticesLength = vertices.length; + var vertexCount = Math.floor(meshVerticesLength * 0.5); + + // Because it's a triangle strip and we don't want lots of degenerate triangles joining things up + pipeline.flush(); + + pipeline.setTexture2D(texture, 0); + + var vertexViewF32 = pipeline.vertexViewF32; + var vertexViewU32 = pipeline.vertexViewU32; + + var vertexOffset = (pipeline.vertexCount * pipeline.vertexComponentCount) - 1; + + var colorIndex = 0; + + var tintEffect = src.tintFill; + + if (src.dirty) + { + src.updateVertices(); + } + + var debugCallback = src.debugCallback; + var debugVerts = []; + + for (var i = 0; i < meshVerticesLength; i += 2) + { + var x = vertices[i + 0]; + var y = vertices[i + 1]; + + var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; + var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; + + if (roundPixels) + { + tx = Math.round(tx); + ty = Math.round(ty); + } + + vertexViewF32[++vertexOffset] = tx; + vertexViewF32[++vertexOffset] = ty; + vertexViewF32[++vertexOffset] = uvs[i + 0]; + vertexViewF32[++vertexOffset] = uvs[i + 1]; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = getTint(colors[colorIndex], camera.alpha * (alphas[colorIndex] * alpha)); + + colorIndex++; + + if (debugCallback) + { + debugVerts[i + 0] = tx; + debugVerts[i + 1] = ty; + } + } + + if (debugCallback) + { + debugCallback.call(src, src, meshVerticesLength, debugVerts); + } + + pipeline.vertexCount += vertexCount; +}; + +module.exports = RopeWebGLRenderer; diff --git a/src/gameobjects/shader/Shader.js b/src/gameobjects/shader/Shader.js index c969d788c..fce78e4ab 100644 --- a/src/gameobjects/shader/Shader.js +++ b/src/gameobjects/shader/Shader.js @@ -1,1217 +1,1217 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Extend = require('../../utils/object/Extend'); -var SetValue = require('../../utils/object/SetValue'); -var ShaderRender = require('./ShaderRender'); -var TransformMatrix = require('../components/TransformMatrix'); - -/** - * @classdesc - * A Shader Game Object. - * - * This Game Object allows you to easily add a quad with its own shader into the display list, and manipulate it - * as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders - * can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other - * Game Object. They can also be made interactive and used for input events. - * - * It works by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can - * be created dynamically at runtime, or loaded in via the GLSL File Loader: - * - * ```javascript - * function preload () - * { - * this.load.glsl('fire', 'shaders/fire.glsl.js'); - * } - * - * function create () - * { - * this.add.shader('fire', 400, 300, 512, 512); - * } - * ``` - * - * Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. - * - * Due to the way in which they work, you cannot directly change the alpha or blend mode of a Shader. This should - * be handled via exposed uniforms in the shader code itself. - * - * By default a Shader will be created with a standard set of uniforms. These were added to match those - * found on sites such as ShaderToy or GLSLSandbox, and provide common functionality a shader may need, - * such as the timestamp, resolution or pointer position. You can replace them by specifying your own uniforms - * in the Base Shader. - * - * These Shaders work by halting the current pipeline during rendering, creating a viewport matched to the - * size of this Game Object and then renders a quad using the bound shader. At the end, the pipeline is restored. - * - * Because it blocks the pipeline it means it will interrupt any batching that is currently going on, so you should - * use these Game Objects sparingly. If you need to have a fully batched custom shader, then please look at using - * a custom pipeline instead. However, for background or special masking effects, they are extremely effective. - * - * @class Shader - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @webglOnly - * @since 3.17.0 - * - * @extends Phaser.GameObjects.Components.ComputedSize - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.ScrollFactor - * @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 {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the Game Object. - * @param {number} [height=128] - The height of the Game Object. - * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. - * @param {any} [textureData] - Additional texture data if you want to create shader with none NPOT textures. - */ -var Shader = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.ComputedSize, - Components.Depth, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.ScrollFactor, - Components.Transform, - Components.Visible, - ShaderRender - ], - - initialize: - - function Shader (scene, key, x, y, width, height, textures, textureData) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 128; } - if (height === undefined) { height = 128; } - - GameObject.call(this, scene, 'Shader'); - - /** - * This Game Object cannot have a blend mode, so skip all checks. - * - * @name Phaser.GameObjects.Shader#blendMode - * @type {integer} - * @private - * @since 3.17.0 - */ - this.blendMode = -1; - - /** - * The underlying shader object being used. - * Empty by default and set during a call to the `setShader` method. - * - * @name Phaser.GameObjects.Shader#shader - * @type {Phaser.Display.BaseShader} - * @since 3.17.0 - */ - this.shader; - - var renderer = scene.sys.renderer; - - /** - * A reference to the current renderer. - * Shaders only work with the WebGL Renderer. - * - * @name Phaser.GameObjects.Shader#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.17.0 - */ - this.renderer = renderer; - - /** - * The WebGL context belonging to the renderer. - * - * @name Phaser.GameObjects.Shader#gl - * @type {WebGLRenderingContext} - * @since 3.17.0 - */ - this.gl = renderer.gl; - - /** - * Raw byte buffer of vertices this Shader uses. - * - * @name Phaser.GameObjects.Shader#vertexData - * @type {ArrayBuffer} - * @since 3.17.0 - */ - this.vertexData = new ArrayBuffer(6 * (Float32Array.BYTES_PER_ELEMENT * 2)); - - /** - * The WebGL vertex buffer object this shader uses. - * - * @name Phaser.GameObjects.Shader#vertexBuffer - * @type {WebGLBuffer} - * @since 3.17.0 - */ - this.vertexBuffer = renderer.createVertexBuffer(this.vertexData.byteLength, this.gl.STREAM_DRAW); - - /** - * The WebGL shader program this shader uses. - * - * @name Phaser.GameObjects.Shader#program - * @type {WebGLProgram} - * @since 3.17.0 - */ - this.program = null; - - /** - * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources to the GPU. - * - * @name Phaser.GameObjects.Shader#bytes - * @type {Uint8Array} - * @since 3.17.0 - */ - this.bytes = new Uint8Array(this.vertexData); - - /** - * Float32 view of the array buffer containing the shaders vertices. - * - * @name Phaser.GameObjects.Shader#vertexViewF32 - * @type {Float32Array} - * @since 3.17.0 - */ - this.vertexViewF32 = new Float32Array(this.vertexData); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.GameObjects.Shader#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.17.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.GameObjects.Shader#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.17.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.GameObjects.Shader#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.17.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - /** - * The view matrix the shader uses during rendering. - * - * @name Phaser.GameObjects.Shader#viewMatrix - * @type {Float32Array} - * @readonly - * @since 3.17.0 - */ - this.viewMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); - - /** - * The projection matrix the shader uses during rendering. - * - * @name Phaser.GameObjects.Shader#projectionMatrix - * @type {Float32Array} - * @readonly - * @since 3.17.0 - */ - this.projectionMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); - - /** - * The default uniform mappings. These can be added to (or replaced) by specifying your own uniforms when - * creating this shader game object. The uniforms are updated automatically during the render step. - * - * The defaults are: - * - * `resolution` (2f) - Set to the size of this shader. - * `time` (1f) - The elapsed game time, in seconds. - * `mouse` (2f) - If a pointer has been bound (with `setPointer`), this uniform contains its position each frame. - * `date` (4fv) - A vec4 containing the year, month, day and time in seconds. - * `sampleRate` (1f) - Sound sample rate. 44100 by default. - * `iChannel0...3` (sampler2D) - Input channels 0 to 3. `null` by default. - * - * @name Phaser.GameObjects.Shader#uniforms - * @type {any} - * @since 3.17.0 - */ - this.uniforms = {}; - - /** - * The pointer bound to this shader, if any. - * Set via the chainable `setPointer` method, or by modifying this property directly. - * - * @name Phaser.GameObjects.Shader#pointer - * @type {Phaser.Input.Pointer} - * @since 3.17.0 - */ - this.pointer = null; - - /** - * The cached width of the renderer. - * - * @name Phaser.GameObjects.Shader#_rendererWidth - * @type {number} - * @private - * @since 3.17.0 - */ - this._rendererWidth = renderer.width; - - /** - * The cached height of the renderer. - * - * @name Phaser.GameObjects.Shader#_rendererHeight - * @type {number} - * @private - * @since 3.17.0 - */ - this._rendererHeight = renderer.height; - - /** - * Internal texture count tracker. - * - * @name Phaser.GameObjects.Shader#_textureCount - * @type {number} - * @private - * @since 3.17.0 - */ - this._textureCount = 0; - - /** - * A reference to the GL Frame Buffer this Shader is drawing to. - * This property is only set if you have called `Shader.setRenderToTexture`. - * - * @name Phaser.GameObjects.Shader#framebuffer - * @type {?WebGLFramebuffer} - * @since 3.19.0 - */ - this.framebuffer = null; - - /** - * A reference to the WebGLTexture this Shader is rendering to. - * This property is only set if you have called `Shader.setRenderToTexture`. - * - * @name Phaser.GameObjects.Shader#glTexture - * @type {?WebGLTexture} - * @since 3.19.0 - */ - this.glTexture = null; - - /** - * A flag that indicates if this Shader has been set to render to a texture instead of the display list. - * - * This property is `true` if you have called `Shader.setRenderToTexture`, otherwise it's `false`. - * - * A Shader that is rendering to a texture _does not_ appear on the display list. - * - * @name Phaser.GameObjects.Shader#renderToTexture - * @type {boolean} - * @readonly - * @since 3.19.0 - */ - this.renderToTexture = false; - - /** - * A reference to the Phaser.Textures.Texture that has been stored in the Texture Manager for this Shader. - * - * This property is only set if you have called `Shader.setRenderToTexture`, otherwise it is `null`. - * - * @name Phaser.GameObjects.Shader#texture - * @type {Phaser.Textures.Texture} - * @since 3.19.0 - */ - this.texture = null; - - this.setPosition(x, y); - this.setSize(width, height); - this.setOrigin(0.5, 0.5); - this.setShader(key, textures, textureData); - }, - - /** - * Compares the renderMask with the renderFlags to see if this Game Object will render or not. - * Also checks the Game Object against the given Cameras exclusion list. - * - * @method Phaser.GameObjects.Shader#willRender - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object. - * - * @return {boolean} True if the Game Object should be rendered, otherwise false. - */ - willRender: function (camera) - { - if (this.renderToTexture) - { - return true; - } - else - { - return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id))); - } - }, - - /** - * Changes this Shader so instead of rendering to the display list it renders to a - * WebGL Framebuffer and WebGL Texture instead. This allows you to use the output - * of this shader as an input for another shader, by mapping a sampler2D uniform - * to it. - * - * After calling this method the `Shader.framebuffer` and `Shader.glTexture` properties - * are populated. - * - * Additionally, you can provide a key to this method. Doing so will create a Phaser Texture - * from this Shader and save it into the Texture Manager, allowing you to then use it for - * any texture-based Game Object, such as a Sprite or Image: - * - * ```javascript - * var shader = this.add.shader('myShader', x, y, width, height); - * - * shader.setRenderToTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * Note that it stores an active reference to this Shader. That means as this shader updates, - * so does the texture and any object using it to render with. Also, if you destroy this - * shader, be sure to clear any objects that may have been using it as a texture too. - * - * You can access the Phaser Texture that is created via the `Shader.texture` property. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame from a Render Texture. - * - * @method Phaser.GameObjects.Shader#setRenderToTexture - * @since 3.19.0 - * - * @param {string} [key] - The unique key to store the texture as within the global Texture Manager. - * @param {boolean} [flipY=false] - Does this texture need vertically flipping before rendering? This should usually be set to `true` if being fed from a buffer. - * - * @return {this} This Shader instance. - */ - setRenderToTexture: function (key, flipY) - { - if (flipY === undefined) { flipY = false; } - - if (!this.renderToTexture) - { - var width = this.width; - var height = this.height; - var renderer = this.renderer; - - this.glTexture = renderer.createTextureFromSource(null, width, height, 0); - - this.glTexture.flipY = flipY; - - this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false); - - this._rendererWidth = width; - this._rendererHeight = height; - - this.renderToTexture = true; - - this.projOrtho(0, this.width, this.height, 0); - - if (key) - { - this.texture = this.scene.sys.textures.addGLTexture(key, this.glTexture, width, height); - } - } - - // And now render at least once, so our texture isn't blank on the first update - - if (this.shader) - { - var pipeline = renderer.currentPipeline; - - renderer.clearPipeline(); - - this.load(); - this.flush(); - - renderer.rebindPipeline(pipeline); - } - - return this; - }, - - /** - * Sets the fragment and, optionally, the vertex shader source code that this Shader will use. - * This will immediately delete the active shader program, if set, and then create a new one - * with the given source. Finally, the shader uniforms are initialized. - * - * @method Phaser.GameObjects.Shader#setShader - * @since 3.17.0 - * - * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. - * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setShader: function (key, textures, textureData) - { - if (textures === undefined) { textures = []; } - - if (typeof key === 'string') - { - var cache = this.scene.sys.cache.shader; - - if (!cache.has(key)) - { - console.warn('Shader missing: ' + key); - return this; - } - - this.shader = cache.get(key); - } - else - { - this.shader = key; - } - - var gl = this.gl; - var renderer = this.renderer; - - if (this.program) - { - gl.deleteProgram(this.program); - } - - var program = renderer.createProgram(this.shader.vertexSrc, this.shader.fragmentSrc); - - // The default uniforms available within the vertex shader - renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); - renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); - renderer.setFloat2(program, 'uResolution', this.width, this.height); - - this.program = program; - - var d = new Date(); - - // The default uniforms available within the fragment shader - var defaultUniforms = { - resolution: { type: '2f', value: { x: this.width, y: this.height } }, - time: { type: '1f', value: 0 }, - mouse: { type: '2f', value: { x: this.width / 2, y: this.height / 2 } }, - date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() * 60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, - sampleRate: { type: '1f', value: 44100.0 }, - iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, - iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, - iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, - iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } - }; - - if (this.shader.uniforms) - { - this.uniforms = Extend(true, {}, this.shader.uniforms, defaultUniforms); - } - else - { - this.uniforms = defaultUniforms; - } - - for (var i = 0; i < 4; i++) - { - if (textures[i]) - { - this.setSampler2D('iChannel' + i, textures[i], i, textureData); - } - } - - this.initUniforms(); - - this.projOrtho(0, this._rendererWidth, this._rendererHeight, 0); - - return this; - }, - - /** - * Binds a Phaser Pointer object to this Shader. - * - * The screen position of the pointer will be set in to the shaders `mouse` uniform - * automatically every frame. Call this method with no arguments to unbind the pointer. - * - * @method Phaser.GameObjects.Shader#setPointer - * @since 3.17.0 - * - * @param {Phaser.Input.Pointer} [pointer] - The Pointer to bind to this shader. - * - * @return {this} This Shader instance. - */ - setPointer: function (pointer) - { - this.pointer = pointer; - - return this; - }, - - /** - * Sets this shader to use an orthographic projection matrix. - * This matrix is stored locally in the `projectionMatrix` property, - * as well as being bound to the `uProjectionMatrix` uniform. - * - * @method Phaser.GameObjects.Shader#projOrtho - * @since 3.17.0 - * - * @param {number} left - The left value. - * @param {number} right - The right value. - * @param {number} bottom - The bottom value. - * @param {number} top - The top value. - */ - projOrtho: function (left, right, bottom, top) - { - var near = -1000; - var far = 1000; - - var leftRight = 1 / (left - right); - var bottomTop = 1 / (bottom - top); - var nearFar = 1 / (near - far); - - var pm = this.projectionMatrix; - - pm[0] = -2 * leftRight; - pm[5] = -2 * bottomTop; - pm[10] = 2 * nearFar; - pm[12] = (left + right) * leftRight; - pm[13] = (top + bottom) * bottomTop; - pm[14] = (far + near) * nearFar; - - var program = this.program; - - this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); - - this._rendererWidth = right; - this._rendererHeight = bottom; - }, - - // Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ - // http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf - - /** - * Initializes all of the uniforms this shader uses. - * - * @method Phaser.GameObjects.Shader#initUniforms - * @private - * @since 3.17.0 - */ - initUniforms: function () - { - var gl = this.gl; - var map = this.renderer.glFuncMap; - var program = this.program; - - this._textureCount = 0; - - for (var key in this.uniforms) - { - var uniform = this.uniforms[key]; - - var type = uniform.type; - var data = map[type]; - - uniform.uniformLocation = gl.getUniformLocation(program, key); - - if (type !== 'sampler2D') - { - uniform.glMatrix = data.matrix; - uniform.glValueLength = data.length; - uniform.glFunc = data.func; - } - } - }, - - /** - * Sets a sampler2D uniform on this shader where the source texture is a WebGLTexture. - * - * This allows you to feed the output from one Shader into another: - * - * ```javascript - * let shader1 = this.add.shader(baseShader1, 0, 0, 512, 512).setRenderToTexture(); - * let shader2 = this.add.shader(baseShader2, 0, 0, 512, 512).setRenderToTexture('output'); - * - * shader1.setSampler2DBuffer('iChannel0', shader2.glTexture, 512, 512); - * shader2.setSampler2DBuffer('iChannel0', shader1.glTexture, 512, 512); - * ``` - * - * In the above code, the result of baseShader1 is fed into Shader2 as the `iChannel0` sampler2D uniform. - * The result of baseShader2 is then fed back into shader1 again, creating a feedback loop. - * - * If you wish to use an image from the Texture Manager as a sampler2D input for this shader, - * see the `Shader.setSampler2D` method. - * - * @method Phaser.GameObjects.Shader#setSampler2DBuffer - * @since 3.19.0 - * - * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`. - * @param {WebGLTexture} texture - A WebGLTexture reference. - * @param {integer} width - The width of the texture. - * @param {integer} height - The height of the texture. - * @param {integer} [textureIndex=0] - The texture index. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setSampler2DBuffer: function (uniformKey, texture, width, height, textureIndex, textureData) - { - if (textureIndex === undefined) { textureIndex = 0; } - if (textureData === undefined) { textureData = {}; } - - var uniform = this.uniforms[uniformKey]; - - uniform.value = texture; - - textureData.width = width; - textureData.height = height; - - uniform.textureData = textureData; - - this._textureCount = textureIndex; - - this.initSampler2D(uniform); - - return this; - }, - - /** - * Sets a sampler2D uniform on this shader. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * - * If you wish to use another Shader as a sampler2D input for this shader, see the `Shader.setSampler2DBuffer` method. - * - * @method Phaser.GameObjects.Shader#setSampler2D - * @since 3.17.0 - * - * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`. - * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param {integer} [textureIndex=0] - The texture index. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setSampler2D: function (uniformKey, textureKey, textureIndex, textureData) - { - if (textureIndex === undefined) { textureIndex = 0; } - - var textureManager = this.scene.sys.textures; - - if (textureManager.exists(textureKey)) - { - var frame = textureManager.getFrame(textureKey); - var uniform = this.uniforms[uniformKey]; - var source = frame.source; - - uniform.textureKey = textureKey; - uniform.source = source.image; - uniform.value = frame.glTexture; - - if (source.isGLTexture) - { - if (!textureData) - { - textureData = {}; - } - - textureData.width = source.width; - textureData.height = source.height; - } - - if (textureData) - { - uniform.textureData = textureData; - } - - this._textureCount = textureIndex; - - this.initSampler2D(uniform); - } - - return this; - }, - - /** - * Sets a property of a uniform already present on this shader. - * - * To modify the value of a uniform such as a 1f or 1i use the `value` property directly: - * - * ```javascript - * shader.setUniform('size.value', 16); - * ``` - * - * You can use dot notation to access deeper values, for example: - * - * ```javascript - * shader.setUniform('resolution.value.x', 512); - * ``` - * - * The change to the uniform will take effect the next time the shader is rendered. - * - * @method Phaser.GameObjects.Shader#setUniform - * @since 3.17.0 - * - * @param {string} key - The key of the uniform to modify. Use dots for deep properties, i.e. `resolution.value.x`. - * @param {any} value - The value to set into the uniform. - * - * @return {this} This Shader instance. - */ - setUniform: function (key, value) - { - SetValue(this.uniforms, key, value); - - return this; - }, - - /** - * Returns the uniform object for the given key, or `null` if the uniform couldn't be found. - * - * @method Phaser.GameObjects.Shader#getUniform - * @since 3.17.0 - * - * @param {string} key - The key of the uniform to return the value for. - * - * @return {any} A reference to the uniform object. This is not a copy, so modifying it will update the original object also. - */ - getUniform: function (key) - { - return GetFastValue(this.uniforms, key, null); - }, - - /** - * A short-cut method that will directly set the texture being used by the `iChannel0` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * - * @method Phaser.GameObjects.Shader#setChannel0 - * @since 3.17.0 - * - * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setChannel0: function (textureKey, textureData) - { - return this.setSampler2D('iChannel0', textureKey, 0, textureData); - }, - - /** - * A short-cut method that will directly set the texture being used by the `iChannel1` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * - * @method Phaser.GameObjects.Shader#setChannel1 - * @since 3.17.0 - * - * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setChannel1: function (textureKey, textureData) - { - return this.setSampler2D('iChannel1', textureKey, 1, textureData); - }, - - /** - * A short-cut method that will directly set the texture being used by the `iChannel2` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * - * @method Phaser.GameObjects.Shader#setChannel2 - * @since 3.17.0 - * - * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setChannel2: function (textureKey, textureData) - { - return this.setSampler2D('iChannel2', textureKey, 2, textureData); - }, - - /** - * A short-cut method that will directly set the texture being used by the `iChannel3` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * - * @method Phaser.GameObjects.Shader#setChannel3 - * @since 3.17.0 - * - * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param {any} [textureData] - Additional texture data. - * - * @return {this} This Shader instance. - */ - setChannel3: function (textureKey, textureData) - { - return this.setSampler2D('iChannel3', textureKey, 3, textureData); - }, - - /** - * Internal method that takes a sampler2D uniform and prepares it for use by setting the - * gl texture parameters. - * - * @method Phaser.GameObjects.Shader#initSampler2D - * @private - * @since 3.17.0 - * - * @param {any} uniform - The sampler2D uniform to process. - */ - initSampler2D: function (uniform) - { - if (!uniform.value) - { - return; - } - - var gl = this.gl; - - gl.activeTexture(gl.TEXTURE0 + this._textureCount); - gl.bindTexture(gl.TEXTURE_2D, uniform.value); - - // Extended texture data - - var data = uniform.textureData; - - if (data) - { - // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D - - // mag / minFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST - // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT - // format can be: gl.LUMINANCE or gl.RGBA - - var magFilter = gl[GetFastValue(data, 'magFilter', 'linear').toUpperCase()]; - var minFilter = gl[GetFastValue(data, 'minFilter', 'linear').toUpperCase()]; - var wrapS = gl[GetFastValue(data, 'wrapS', 'repeat').toUpperCase()]; - var wrapT = gl[GetFastValue(data, 'wrapT', 'repeat').toUpperCase()]; - var format = gl[GetFastValue(data, 'format', 'rgba').toUpperCase()]; - - if (data.repeat) - { - wrapS = gl.REPEAT; - wrapT = gl.REPEAT; - } - - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - - if (data.width) - { - var width = GetFastValue(data, 'width', 512); - var height = GetFastValue(data, 'height', 2); - var border = GetFastValue(data, 'border', 0); - - // texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels) - gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); - } - else - { - // texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels) - gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.source); - } - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); - } - - this.renderer.setProgram(this.program); - - gl.uniform1i(uniform.uniformLocation, this._textureCount); - - this._textureCount++; - }, - - /** - * Synchronizes all of the uniforms this shader uses. - * Each uniforms gl function is called in turn. - * - * @method Phaser.GameObjects.Shader#syncUniforms - * @private - * @since 3.17.0 - */ - syncUniforms: function () - { - var gl = this.gl; - - var uniforms = this.uniforms; - var uniform; - var length; - var glFunc; - var location; - var value; - var textureCount = 0; - - for (var key in uniforms) - { - uniform = uniforms[key]; - - glFunc = uniform.glFunc; - length = uniform.glValueLength; - location = uniform.uniformLocation; - value = uniform.value; - - if (value === null) - { - continue; - } - - if (length === 1) - { - if (uniform.glMatrix) - { - glFunc.call(gl, location, uniform.transpose, value); - } - else - { - glFunc.call(gl, location, value); - } - } - else if (length === 2) - { - glFunc.call(gl, location, value.x, value.y); - } - else if (length === 3) - { - glFunc.call(gl, location, value.x, value.y, value.z); - } - else if (length === 4) - { - glFunc.call(gl, location, value.x, value.y, value.z, value.w); - } - else if (uniform.type === 'sampler2D') - { - gl.activeTexture(gl['TEXTURE' + textureCount]); - - gl.bindTexture(gl.TEXTURE_2D, value); - - gl.uniform1i(location, textureCount); - - textureCount++; - } - } - }, - - /** - * Called automatically during render. - * - * This method performs matrix ITRS and then stores the resulting value in the `uViewMatrix` uniform. - * It then sets up the vertex buffer and shader, updates and syncs the uniforms ready - * for flush to be called. - * - * @method Phaser.GameObjects.Shader#load - * @since 3.17.0 - * - * @param {Phaser.GameObjects.Components.TransformMatrix} [matrix2D] - The transform matrix to use during rendering. - */ - load: function (matrix2D) - { - // ITRS - - var gl = this.gl; - var width = this.width; - var height = this.height; - var renderer = this.renderer; - var program = this.program; - var vm = this.viewMatrix; - - if (!this.renderToTexture) - { - var x = -this._displayOriginX; - var y = -this._displayOriginY; - - vm[0] = matrix2D[0]; - vm[1] = matrix2D[1]; - vm[4] = matrix2D[2]; - vm[5] = matrix2D[3]; - vm[8] = matrix2D[4]; - vm[9] = matrix2D[5]; - vm[12] = vm[0] * x + vm[4] * y; - vm[13] = vm[1] * x + vm[5] * y; - } - - // Update vertex shader uniforms - - gl.useProgram(program); - - gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uViewMatrix'), false, vm); - gl.uniform2f(gl.getUniformLocation(program, 'uResolution'), this.width, this.height); - - // Update fragment shader uniforms - - var uniforms = this.uniforms; - var res = uniforms.resolution; - - res.value.x = width; - res.value.y = height; - - uniforms.time.value = renderer.game.loop.getDuration(); - - var pointer = this.pointer; - - if (pointer) - { - var mouse = uniforms.mouse; - - var px = pointer.x / width; - var py = 1 - pointer.y / height; - - mouse.value.x = px.toFixed(2); - mouse.value.y = py.toFixed(2); - } - - this.syncUniforms(); - }, - - /** - * Called automatically during render. - * - * Sets the active shader, loads the vertex buffer and then draws. - * - * @method Phaser.GameObjects.Shader#flush - * @since 3.17.0 - */ - flush: function () - { - // Bind - - var width = this.width; - var height = this.height; - var program = this.program; - - var gl = this.gl; - var vertexBuffer = this.vertexBuffer; - var renderer = this.renderer; - var vertexSize = Float32Array.BYTES_PER_ELEMENT * 2; - - if (this.renderToTexture) - { - renderer.setFramebuffer(this.framebuffer); - - gl.clearColor(0, 0, 0, 0); - - gl.clear(gl.COLOR_BUFFER_BIT); - } - - gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); - - var location = gl.getAttribLocation(program, 'inPosition'); - - if (location !== -1) - { - gl.enableVertexAttribArray(location); - - gl.vertexAttribPointer(location, 2, gl.FLOAT, false, vertexSize, 0); - } - - // Draw - - var vf = this.vertexViewF32; - - vf[3] = height; - vf[4] = width; - vf[5] = height; - vf[8] = width; - vf[9] = height; - vf[10] = width; - - // Flush - - var vertexCount = 6; - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); - - gl.drawArrays(gl.TRIANGLES, 0, vertexCount); - - if (this.renderToTexture) - { - renderer.setFramebuffer(null, false); - } - }, - - /** - * A NOOP method so you can pass a Shader to a Container. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Shader#setAlpha - * @private - * @since 3.17.0 - */ - setAlpha: function () - { - }, - - /** - * A NOOP method so you can pass a Shader to a Container. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Shader#setBlendMode - * @private - * @since 3.17.0 - */ - setBlendMode: function () - { - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Shader#preDestroy - * @protected - * @since 3.17.0 - */ - preDestroy: function () - { - var gl = this.gl; - - gl.deleteProgram(this.program); - gl.deleteBuffer(this.vertexBuffer); - - if (this.renderToTexture) - { - this.renderer.deleteFramebuffer(this.framebuffer); - - this.texture.destroy(); - - this.framebuffer = null; - this.glTexture = null; - this.texture = null; - } - } - -}); - -module.exports = Shader; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Extend = require('../../utils/object/Extend'); +var SetValue = require('../../utils/object/SetValue'); +var ShaderRender = require('./ShaderRender'); +var TransformMatrix = require('../components/TransformMatrix'); + +/** + * @classdesc + * A Shader Game Object. + * + * This Game Object allows you to easily add a quad with its own shader into the display list, and manipulate it + * as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders + * can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other + * Game Object. They can also be made interactive and used for input events. + * + * It works by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can + * be created dynamically at runtime, or loaded in via the GLSL File Loader: + * + * ```javascript + * function preload () + * { + * this.load.glsl('fire', 'shaders/fire.glsl.js'); + * } + * + * function create () + * { + * this.add.shader('fire', 400, 300, 512, 512); + * } + * ``` + * + * Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. + * + * Due to the way in which they work, you cannot directly change the alpha or blend mode of a Shader. This should + * be handled via exposed uniforms in the shader code itself. + * + * By default a Shader will be created with a standard set of uniforms. These were added to match those + * found on sites such as ShaderToy or GLSLSandbox, and provide common functionality a shader may need, + * such as the timestamp, resolution or pointer position. You can replace them by specifying your own uniforms + * in the Base Shader. + * + * These Shaders work by halting the current pipeline during rendering, creating a viewport matched to the + * size of this Game Object and then renders a quad using the bound shader. At the end, the pipeline is restored. + * + * Because it blocks the pipeline it means it will interrupt any batching that is currently going on, so you should + * use these Game Objects sparingly. If you need to have a fully batched custom shader, then please look at using + * a custom pipeline instead. However, for background or special masking effects, they are extremely effective. + * + * @class Shader + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @webglOnly + * @since 3.17.0 + * + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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 {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the Game Object. + * @param {number} [height=128] - The height of the Game Object. + * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param {any} [textureData] - Additional texture data if you want to create shader with none NPOT textures. + */ +var Shader = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.ComputedSize, + Components.Depth, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.ScrollFactor, + Components.Transform, + Components.Visible, + ShaderRender + ], + + initialize: + + function Shader (scene, key, x, y, width, height, textures, textureData) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + + GameObject.call(this, scene, 'Shader'); + + /** + * This Game Object cannot have a blend mode, so skip all checks. + * + * @name Phaser.GameObjects.Shader#blendMode + * @type {integer} + * @private + * @since 3.17.0 + */ + this.blendMode = -1; + + /** + * The underlying shader object being used. + * Empty by default and set during a call to the `setShader` method. + * + * @name Phaser.GameObjects.Shader#shader + * @type {Phaser.Display.BaseShader} + * @since 3.17.0 + */ + this.shader; + + var renderer = scene.sys.renderer; + + /** + * A reference to the current renderer. + * Shaders only work with the WebGL Renderer. + * + * @name Phaser.GameObjects.Shader#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.17.0 + */ + this.renderer = renderer; + + /** + * The WebGL context belonging to the renderer. + * + * @name Phaser.GameObjects.Shader#gl + * @type {WebGLRenderingContext} + * @since 3.17.0 + */ + this.gl = renderer.gl; + + /** + * Raw byte buffer of vertices this Shader uses. + * + * @name Phaser.GameObjects.Shader#vertexData + * @type {ArrayBuffer} + * @since 3.17.0 + */ + this.vertexData = new ArrayBuffer(6 * (Float32Array.BYTES_PER_ELEMENT * 2)); + + /** + * The WebGL vertex buffer object this shader uses. + * + * @name Phaser.GameObjects.Shader#vertexBuffer + * @type {WebGLBuffer} + * @since 3.17.0 + */ + this.vertexBuffer = renderer.createVertexBuffer(this.vertexData.byteLength, this.gl.STREAM_DRAW); + + /** + * The WebGL shader program this shader uses. + * + * @name Phaser.GameObjects.Shader#program + * @type {WebGLProgram} + * @since 3.17.0 + */ + this.program = null; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources to the GPU. + * + * @name Phaser.GameObjects.Shader#bytes + * @type {Uint8Array} + * @since 3.17.0 + */ + this.bytes = new Uint8Array(this.vertexData); + + /** + * Float32 view of the array buffer containing the shaders vertices. + * + * @name Phaser.GameObjects.Shader#vertexViewF32 + * @type {Float32Array} + * @since 3.17.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Shader#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Shader#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.GameObjects.Shader#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.17.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * The view matrix the shader uses during rendering. + * + * @name Phaser.GameObjects.Shader#viewMatrix + * @type {Float32Array} + * @readonly + * @since 3.17.0 + */ + this.viewMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); + + /** + * The projection matrix the shader uses during rendering. + * + * @name Phaser.GameObjects.Shader#projectionMatrix + * @type {Float32Array} + * @readonly + * @since 3.17.0 + */ + this.projectionMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); + + /** + * The default uniform mappings. These can be added to (or replaced) by specifying your own uniforms when + * creating this shader game object. The uniforms are updated automatically during the render step. + * + * The defaults are: + * + * `resolution` (2f) - Set to the size of this shader. + * `time` (1f) - The elapsed game time, in seconds. + * `mouse` (2f) - If a pointer has been bound (with `setPointer`), this uniform contains its position each frame. + * `date` (4fv) - A vec4 containing the year, month, day and time in seconds. + * `sampleRate` (1f) - Sound sample rate. 44100 by default. + * `iChannel0...3` (sampler2D) - Input channels 0 to 3. `null` by default. + * + * @name Phaser.GameObjects.Shader#uniforms + * @type {any} + * @since 3.17.0 + */ + this.uniforms = {}; + + /** + * The pointer bound to this shader, if any. + * Set via the chainable `setPointer` method, or by modifying this property directly. + * + * @name Phaser.GameObjects.Shader#pointer + * @type {Phaser.Input.Pointer} + * @since 3.17.0 + */ + this.pointer = null; + + /** + * The cached width of the renderer. + * + * @name Phaser.GameObjects.Shader#_rendererWidth + * @type {number} + * @private + * @since 3.17.0 + */ + this._rendererWidth = renderer.width; + + /** + * The cached height of the renderer. + * + * @name Phaser.GameObjects.Shader#_rendererHeight + * @type {number} + * @private + * @since 3.17.0 + */ + this._rendererHeight = renderer.height; + + /** + * Internal texture count tracker. + * + * @name Phaser.GameObjects.Shader#_textureCount + * @type {number} + * @private + * @since 3.17.0 + */ + this._textureCount = 0; + + /** + * A reference to the GL Frame Buffer this Shader is drawing to. + * This property is only set if you have called `Shader.setRenderToTexture`. + * + * @name Phaser.GameObjects.Shader#framebuffer + * @type {?WebGLFramebuffer} + * @since 3.19.0 + */ + this.framebuffer = null; + + /** + * A reference to the WebGLTexture this Shader is rendering to. + * This property is only set if you have called `Shader.setRenderToTexture`. + * + * @name Phaser.GameObjects.Shader#glTexture + * @type {?WebGLTexture} + * @since 3.19.0 + */ + this.glTexture = null; + + /** + * A flag that indicates if this Shader has been set to render to a texture instead of the display list. + * + * This property is `true` if you have called `Shader.setRenderToTexture`, otherwise it's `false`. + * + * A Shader that is rendering to a texture _does not_ appear on the display list. + * + * @name Phaser.GameObjects.Shader#renderToTexture + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this.renderToTexture = false; + + /** + * A reference to the Phaser.Textures.Texture that has been stored in the Texture Manager for this Shader. + * + * This property is only set if you have called `Shader.setRenderToTexture`, otherwise it is `null`. + * + * @name Phaser.GameObjects.Shader#texture + * @type {Phaser.Textures.Texture} + * @since 3.19.0 + */ + this.texture = null; + + this.setPosition(x, y); + this.setSize(width, height); + this.setOrigin(0.5, 0.5); + this.setShader(key, textures, textureData); + }, + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * Also checks the Game Object against the given Cameras exclusion list. + * + * @method Phaser.GameObjects.Shader#willRender + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object. + * + * @return {boolean} True if the Game Object should be rendered, otherwise false. + */ + willRender: function (camera) + { + if (this.renderToTexture) + { + return true; + } + else + { + return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id))); + } + }, + + /** + * Changes this Shader so instead of rendering to the display list it renders to a + * WebGL Framebuffer and WebGL Texture instead. This allows you to use the output + * of this shader as an input for another shader, by mapping a sampler2D uniform + * to it. + * + * After calling this method the `Shader.framebuffer` and `Shader.glTexture` properties + * are populated. + * + * Additionally, you can provide a key to this method. Doing so will create a Phaser Texture + * from this Shader and save it into the Texture Manager, allowing you to then use it for + * any texture-based Game Object, such as a Sprite or Image: + * + * ```javascript + * var shader = this.add.shader('myShader', x, y, width, height); + * + * shader.setRenderToTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Note that it stores an active reference to this Shader. That means as this shader updates, + * so does the texture and any object using it to render with. Also, if you destroy this + * shader, be sure to clear any objects that may have been using it as a texture too. + * + * You can access the Phaser Texture that is created via the `Shader.texture` property. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame from a Render Texture. + * + * @method Phaser.GameObjects.Shader#setRenderToTexture + * @since 3.19.0 + * + * @param {string} [key] - The unique key to store the texture as within the global Texture Manager. + * @param {boolean} [flipY=false] - Does this texture need vertically flipping before rendering? This should usually be set to `true` if being fed from a buffer. + * + * @return {this} This Shader instance. + */ + setRenderToTexture: function (key, flipY) + { + if (flipY === undefined) { flipY = false; } + + if (!this.renderToTexture) + { + var width = this.width; + var height = this.height; + var renderer = this.renderer; + + this.glTexture = renderer.createTextureFromSource(null, width, height, 0); + + this.glTexture.flipY = flipY; + + this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false); + + this._rendererWidth = width; + this._rendererHeight = height; + + this.renderToTexture = true; + + this.projOrtho(0, this.width, this.height, 0); + + if (key) + { + this.texture = this.scene.sys.textures.addGLTexture(key, this.glTexture, width, height); + } + } + + // And now render at least once, so our texture isn't blank on the first update + + if (this.shader) + { + var pipeline = renderer.currentPipeline; + + renderer.clearPipeline(); + + this.load(); + this.flush(); + + renderer.rebindPipeline(pipeline); + } + + return this; + }, + + /** + * Sets the fragment and, optionally, the vertex shader source code that this Shader will use. + * This will immediately delete the active shader program, if set, and then create a new one + * with the given source. Finally, the shader uniforms are initialized. + * + * @method Phaser.GameObjects.Shader#setShader + * @since 3.17.0 + * + * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. + * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setShader: function (key, textures, textureData) + { + if (textures === undefined) { textures = []; } + + if (typeof key === 'string') + { + var cache = this.scene.sys.cache.shader; + + if (!cache.has(key)) + { + console.warn('Shader missing: ' + key); + return this; + } + + this.shader = cache.get(key); + } + else + { + this.shader = key; + } + + var gl = this.gl; + var renderer = this.renderer; + + if (this.program) + { + gl.deleteProgram(this.program); + } + + var program = renderer.createProgram(this.shader.vertexSrc, this.shader.fragmentSrc); + + // The default uniforms available within the vertex shader + renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); + renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + renderer.setFloat2(program, 'uResolution', this.width, this.height); + + this.program = program; + + var d = new Date(); + + // The default uniforms available within the fragment shader + var defaultUniforms = { + resolution: { type: '2f', value: { x: this.width, y: this.height } }, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: this.width / 2, y: this.height / 2 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() * 60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + }; + + if (this.shader.uniforms) + { + this.uniforms = Extend(true, {}, this.shader.uniforms, defaultUniforms); + } + else + { + this.uniforms = defaultUniforms; + } + + for (var i = 0; i < 4; i++) + { + if (textures[i]) + { + this.setSampler2D('iChannel' + i, textures[i], i, textureData); + } + } + + this.initUniforms(); + + this.projOrtho(0, this._rendererWidth, this._rendererHeight, 0); + + return this; + }, + + /** + * Binds a Phaser Pointer object to this Shader. + * + * The screen position of the pointer will be set in to the shaders `mouse` uniform + * automatically every frame. Call this method with no arguments to unbind the pointer. + * + * @method Phaser.GameObjects.Shader#setPointer + * @since 3.17.0 + * + * @param {Phaser.Input.Pointer} [pointer] - The Pointer to bind to this shader. + * + * @return {this} This Shader instance. + */ + setPointer: function (pointer) + { + this.pointer = pointer; + + return this; + }, + + /** + * Sets this shader to use an orthographic projection matrix. + * This matrix is stored locally in the `projectionMatrix` property, + * as well as being bound to the `uProjectionMatrix` uniform. + * + * @method Phaser.GameObjects.Shader#projOrtho + * @since 3.17.0 + * + * @param {number} left - The left value. + * @param {number} right - The right value. + * @param {number} bottom - The bottom value. + * @param {number} top - The top value. + */ + projOrtho: function (left, right, bottom, top) + { + var near = -1000; + var far = 1000; + + var leftRight = 1 / (left - right); + var bottomTop = 1 / (bottom - top); + var nearFar = 1 / (near - far); + + var pm = this.projectionMatrix; + + pm[0] = -2 * leftRight; + pm[5] = -2 * bottomTop; + pm[10] = 2 * nearFar; + pm[12] = (left + right) * leftRight; + pm[13] = (top + bottom) * bottomTop; + pm[14] = (far + near) * nearFar; + + var program = this.program; + + this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + + this._rendererWidth = right; + this._rendererHeight = bottom; + }, + + // Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ + // http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf + + /** + * Initializes all of the uniforms this shader uses. + * + * @method Phaser.GameObjects.Shader#initUniforms + * @private + * @since 3.17.0 + */ + initUniforms: function () + { + var gl = this.gl; + var map = this.renderer.glFuncMap; + var program = this.program; + + this._textureCount = 0; + + for (var key in this.uniforms) + { + var uniform = this.uniforms[key]; + + var type = uniform.type; + var data = map[type]; + + uniform.uniformLocation = gl.getUniformLocation(program, key); + + if (type !== 'sampler2D') + { + uniform.glMatrix = data.matrix; + uniform.glValueLength = data.length; + uniform.glFunc = data.func; + } + } + }, + + /** + * Sets a sampler2D uniform on this shader where the source texture is a WebGLTexture. + * + * This allows you to feed the output from one Shader into another: + * + * ```javascript + * let shader1 = this.add.shader(baseShader1, 0, 0, 512, 512).setRenderToTexture(); + * let shader2 = this.add.shader(baseShader2, 0, 0, 512, 512).setRenderToTexture('output'); + * + * shader1.setSampler2DBuffer('iChannel0', shader2.glTexture, 512, 512); + * shader2.setSampler2DBuffer('iChannel0', shader1.glTexture, 512, 512); + * ``` + * + * In the above code, the result of baseShader1 is fed into Shader2 as the `iChannel0` sampler2D uniform. + * The result of baseShader2 is then fed back into shader1 again, creating a feedback loop. + * + * If you wish to use an image from the Texture Manager as a sampler2D input for this shader, + * see the `Shader.setSampler2D` method. + * + * @method Phaser.GameObjects.Shader#setSampler2DBuffer + * @since 3.19.0 + * + * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`. + * @param {WebGLTexture} texture - A WebGLTexture reference. + * @param {integer} width - The width of the texture. + * @param {integer} height - The height of the texture. + * @param {integer} [textureIndex=0] - The texture index. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setSampler2DBuffer: function (uniformKey, texture, width, height, textureIndex, textureData) + { + if (textureIndex === undefined) { textureIndex = 0; } + if (textureData === undefined) { textureData = {}; } + + var uniform = this.uniforms[uniformKey]; + + uniform.value = texture; + + textureData.width = width; + textureData.height = height; + + uniform.textureData = textureData; + + this._textureCount = textureIndex; + + this.initSampler2D(uniform); + + return this; + }, + + /** + * Sets a sampler2D uniform on this shader. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * If you wish to use another Shader as a sampler2D input for this shader, see the `Shader.setSampler2DBuffer` method. + * + * @method Phaser.GameObjects.Shader#setSampler2D + * @since 3.17.0 + * + * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`. + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {integer} [textureIndex=0] - The texture index. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setSampler2D: function (uniformKey, textureKey, textureIndex, textureData) + { + if (textureIndex === undefined) { textureIndex = 0; } + + var textureManager = this.scene.sys.textures; + + if (textureManager.exists(textureKey)) + { + var frame = textureManager.getFrame(textureKey); + var uniform = this.uniforms[uniformKey]; + var source = frame.source; + + uniform.textureKey = textureKey; + uniform.source = source.image; + uniform.value = frame.glTexture; + + if (source.isGLTexture) + { + if (!textureData) + { + textureData = {}; + } + + textureData.width = source.width; + textureData.height = source.height; + } + + if (textureData) + { + uniform.textureData = textureData; + } + + this._textureCount = textureIndex; + + this.initSampler2D(uniform); + } + + return this; + }, + + /** + * Sets a property of a uniform already present on this shader. + * + * To modify the value of a uniform such as a 1f or 1i use the `value` property directly: + * + * ```javascript + * shader.setUniform('size.value', 16); + * ``` + * + * You can use dot notation to access deeper values, for example: + * + * ```javascript + * shader.setUniform('resolution.value.x', 512); + * ``` + * + * The change to the uniform will take effect the next time the shader is rendered. + * + * @method Phaser.GameObjects.Shader#setUniform + * @since 3.17.0 + * + * @param {string} key - The key of the uniform to modify. Use dots for deep properties, i.e. `resolution.value.x`. + * @param {any} value - The value to set into the uniform. + * + * @return {this} This Shader instance. + */ + setUniform: function (key, value) + { + SetValue(this.uniforms, key, value); + + return this; + }, + + /** + * Returns the uniform object for the given key, or `null` if the uniform couldn't be found. + * + * @method Phaser.GameObjects.Shader#getUniform + * @since 3.17.0 + * + * @param {string} key - The key of the uniform to return the value for. + * + * @return {any} A reference to the uniform object. This is not a copy, so modifying it will update the original object also. + */ + getUniform: function (key) + { + return GetFastValue(this.uniforms, key, null); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel0` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel0 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel0: function (textureKey, textureData) + { + return this.setSampler2D('iChannel0', textureKey, 0, textureData); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel1` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel1 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel1: function (textureKey, textureData) + { + return this.setSampler2D('iChannel1', textureKey, 1, textureData); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel2` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel2 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel2: function (textureKey, textureData) + { + return this.setSampler2D('iChannel2', textureKey, 2, textureData); + }, + + /** + * A short-cut method that will directly set the texture being used by the `iChannel3` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * @method Phaser.GameObjects.Shader#setChannel3 + * @since 3.17.0 + * + * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param {any} [textureData] - Additional texture data. + * + * @return {this} This Shader instance. + */ + setChannel3: function (textureKey, textureData) + { + return this.setSampler2D('iChannel3', textureKey, 3, textureData); + }, + + /** + * Internal method that takes a sampler2D uniform and prepares it for use by setting the + * gl texture parameters. + * + * @method Phaser.GameObjects.Shader#initSampler2D + * @private + * @since 3.17.0 + * + * @param {any} uniform - The sampler2D uniform to process. + */ + initSampler2D: function (uniform) + { + if (!uniform.value) + { + return; + } + + var gl = this.gl; + + gl.activeTexture(gl.TEXTURE0 + this._textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value); + + // Extended texture data + + var data = uniform.textureData; + + if (data) + { + // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D + + // mag / minFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + // format can be: gl.LUMINANCE or gl.RGBA + + var magFilter = gl[GetFastValue(data, 'magFilter', 'linear').toUpperCase()]; + var minFilter = gl[GetFastValue(data, 'minFilter', 'linear').toUpperCase()]; + var wrapS = gl[GetFastValue(data, 'wrapS', 'repeat').toUpperCase()]; + var wrapT = gl[GetFastValue(data, 'wrapT', 'repeat').toUpperCase()]; + var format = gl[GetFastValue(data, 'format', 'rgba').toUpperCase()]; + + if (data.repeat) + { + wrapS = gl.REPEAT; + wrapT = gl.REPEAT; + } + + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); + + if (data.width) + { + var width = GetFastValue(data, 'width', 512); + var height = GetFastValue(data, 'height', 2); + var border = GetFastValue(data, 'border', 0); + + // texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels) + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels) + gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.source); + } + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); + } + + this.renderer.setProgram(this.program); + + gl.uniform1i(uniform.uniformLocation, this._textureCount); + + this._textureCount++; + }, + + /** + * Synchronizes all of the uniforms this shader uses. + * Each uniforms gl function is called in turn. + * + * @method Phaser.GameObjects.Shader#syncUniforms + * @private + * @since 3.17.0 + */ + syncUniforms: function () + { + var gl = this.gl; + + var uniforms = this.uniforms; + var uniform; + var length; + var glFunc; + var location; + var value; + var textureCount = 0; + + for (var key in uniforms) + { + uniform = uniforms[key]; + + glFunc = uniform.glFunc; + length = uniform.glValueLength; + location = uniform.uniformLocation; + value = uniform.value; + + if (value === null) + { + continue; + } + + if (length === 1) + { + if (uniform.glMatrix) + { + glFunc.call(gl, location, uniform.transpose, value); + } + else + { + glFunc.call(gl, location, value); + } + } + else if (length === 2) + { + glFunc.call(gl, location, value.x, value.y); + } + else if (length === 3) + { + glFunc.call(gl, location, value.x, value.y, value.z); + } + else if (length === 4) + { + glFunc.call(gl, location, value.x, value.y, value.z, value.w); + } + else if (uniform.type === 'sampler2D') + { + gl.activeTexture(gl['TEXTURE' + textureCount]); + + gl.bindTexture(gl.TEXTURE_2D, value); + + gl.uniform1i(location, textureCount); + + textureCount++; + } + } + }, + + /** + * Called automatically during render. + * + * This method performs matrix ITRS and then stores the resulting value in the `uViewMatrix` uniform. + * It then sets up the vertex buffer and shader, updates and syncs the uniforms ready + * for flush to be called. + * + * @method Phaser.GameObjects.Shader#load + * @since 3.17.0 + * + * @param {Phaser.GameObjects.Components.TransformMatrix} [matrix2D] - The transform matrix to use during rendering. + */ + load: function (matrix2D) + { + // ITRS + + var gl = this.gl; + var width = this.width; + var height = this.height; + var renderer = this.renderer; + var program = this.program; + var vm = this.viewMatrix; + + if (!this.renderToTexture) + { + var x = -this._displayOriginX; + var y = -this._displayOriginY; + + vm[0] = matrix2D[0]; + vm[1] = matrix2D[1]; + vm[4] = matrix2D[2]; + vm[5] = matrix2D[3]; + vm[8] = matrix2D[4]; + vm[9] = matrix2D[5]; + vm[12] = vm[0] * x + vm[4] * y; + vm[13] = vm[1] * x + vm[5] * y; + } + + // Update vertex shader uniforms + + gl.useProgram(program); + + gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uViewMatrix'), false, vm); + gl.uniform2f(gl.getUniformLocation(program, 'uResolution'), this.width, this.height); + + // Update fragment shader uniforms + + var uniforms = this.uniforms; + var res = uniforms.resolution; + + res.value.x = width; + res.value.y = height; + + uniforms.time.value = renderer.game.loop.getDuration(); + + var pointer = this.pointer; + + if (pointer) + { + var mouse = uniforms.mouse; + + var px = pointer.x / width; + var py = 1 - pointer.y / height; + + mouse.value.x = px.toFixed(2); + mouse.value.y = py.toFixed(2); + } + + this.syncUniforms(); + }, + + /** + * Called automatically during render. + * + * Sets the active shader, loads the vertex buffer and then draws. + * + * @method Phaser.GameObjects.Shader#flush + * @since 3.17.0 + */ + flush: function () + { + // Bind + + var width = this.width; + var height = this.height; + var program = this.program; + + var gl = this.gl; + var vertexBuffer = this.vertexBuffer; + var renderer = this.renderer; + var vertexSize = Float32Array.BYTES_PER_ELEMENT * 2; + + if (this.renderToTexture) + { + renderer.setFramebuffer(this.framebuffer); + + gl.clearColor(0, 0, 0, 0); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); + + var location = gl.getAttribLocation(program, 'inPosition'); + + if (location !== -1) + { + gl.enableVertexAttribArray(location); + + gl.vertexAttribPointer(location, 2, gl.FLOAT, false, vertexSize, 0); + } + + // Draw + + var vf = this.vertexViewF32; + + vf[3] = height; + vf[4] = width; + vf[5] = height; + vf[8] = width; + vf[9] = height; + vf[10] = width; + + // Flush + + var vertexCount = 6; + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + + gl.drawArrays(gl.TRIANGLES, 0, vertexCount); + + if (this.renderToTexture) + { + renderer.setFramebuffer(null, false); + } + }, + + /** + * A NOOP method so you can pass a Shader to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Shader#setAlpha + * @private + * @since 3.17.0 + */ + setAlpha: function () + { + }, + + /** + * A NOOP method so you can pass a Shader to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Shader#setBlendMode + * @private + * @since 3.17.0 + */ + setBlendMode: function () + { + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Shader#preDestroy + * @protected + * @since 3.17.0 + */ + preDestroy: function () + { + var gl = this.gl; + + gl.deleteProgram(this.program); + gl.deleteBuffer(this.vertexBuffer); + + if (this.renderToTexture) + { + this.renderer.deleteFramebuffer(this.framebuffer); + + this.texture.destroy(); + + this.framebuffer = null; + this.glTexture = null; + this.texture = null; + } + } + +}); + +module.exports = Shader; diff --git a/src/gameobjects/shader/ShaderCanvasRenderer.js b/src/gameobjects/shader/ShaderCanvasRenderer.js index 8dc97d372..7625e0b21 100644 --- a/src/gameobjects/shader/ShaderCanvasRenderer.js +++ b/src/gameobjects/shader/ShaderCanvasRenderer.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This is a stub function for Shader.Render. There is no Canvas renderer for Shader objects. - * - * @method Phaser.GameObjects.Shader#renderCanvas - * @since 3.17.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Shader} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var ShaderCanvasRenderer = function () -{ -}; - -module.exports = ShaderCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a stub function for Shader.Render. There is no Canvas renderer for Shader objects. + * + * @method Phaser.GameObjects.Shader#renderCanvas + * @since 3.17.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Shader} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var ShaderCanvasRenderer = function () +{ +}; + +module.exports = ShaderCanvasRenderer; diff --git a/src/gameobjects/shader/ShaderCreator.js b/src/gameobjects/shader/ShaderCreator.js index f9a80950a..c18458845 100644 --- a/src/gameobjects/shader/ShaderCreator.js +++ b/src/gameobjects/shader/ShaderCreator.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var Shader = require('./Shader'); - -/** - * Creates a new Shader Game Object and returns it. - * - * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#shader - * @since 3.17.0 - * - * @param {object} 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.Shader} The Game Object that was created. - */ -GameObjectCreator.register('shader', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var x = GetAdvancedValue(config, 'x', 0); - var y = GetAdvancedValue(config, 'y', 0); - var width = GetAdvancedValue(config, 'width', 128); - var height = GetAdvancedValue(config, 'height', 128); - - var shader = new Shader(this.scene, key, x, y, width, height); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, shader, config); - - return shader; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var Shader = require('./Shader'); + +/** + * Creates a new Shader Game Object and returns it. + * + * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#shader + * @since 3.17.0 + * + * @param {object} 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.Shader} The Game Object that was created. + */ +GameObjectCreator.register('shader', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 128); + var height = GetAdvancedValue(config, 'height', 128); + + var shader = new Shader(this.scene, key, x, y, width, height); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, shader, config); + + return shader; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/shader/ShaderFactory.js b/src/gameobjects/shader/ShaderFactory.js index ab7497726..4f248b18c 100644 --- a/src/gameobjects/shader/ShaderFactory.js +++ b/src/gameobjects/shader/ShaderFactory.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Shader = require('./Shader'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Shader Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#shader - * @webglOnly - * @since 3.17.0 - * - * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the Game Object. - * @param {number} [height=128] - The height of the Game Object. - * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. - * @param {object} [textureData] - Optional additional texture data. - * - * @return {Phaser.GameObjects.Shader} The Game Object that was created. - */ -if (typeof WEBGL_RENDERER) -{ - GameObjectFactory.register('shader', function (key, x, y, width, height, textures, textureData) - { - return this.displayList.add(new Shader(this.scene, key, x, y, width, height, textures, textureData)); - }); -} +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Shader = require('./Shader'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Shader Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#shader + * @webglOnly + * @since 3.17.0 + * + * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance. + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the Game Object. + * @param {number} [height=128] - The height of the Game Object. + * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param {object} [textureData] - Optional additional texture data. + * + * @return {Phaser.GameObjects.Shader} The Game Object that was created. + */ +if (typeof WEBGL_RENDERER) +{ + GameObjectFactory.register('shader', function (key, x, y, width, height, textures, textureData) + { + return this.displayList.add(new Shader(this.scene, key, x, y, width, height, textures, textureData)); + }); +} diff --git a/src/gameobjects/shader/ShaderRender.js b/src/gameobjects/shader/ShaderRender.js index df6389671..c16f55077 100644 --- a/src/gameobjects/shader/ShaderRender.js +++ b/src/gameobjects/shader/ShaderRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./ShaderWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./ShaderCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./ShaderWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./ShaderCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shader/ShaderWebGLRenderer.js b/src/gameobjects/shader/ShaderWebGLRenderer.js index f1103b64e..00467bb18 100644 --- a/src/gameobjects/shader/ShaderWebGLRenderer.js +++ b/src/gameobjects/shader/ShaderWebGLRenderer.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Shader#renderWebGL - * @since 3.17.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Shader} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ShaderWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - if (!src.shader) - { - return; - } - - var pipeline = renderer.currentPipeline; - - renderer.clearPipeline(); - - if (src.renderToTexture) - { - src.load(); - src.flush(); - } - else - { - var camMatrix = src._tempMatrix1; - var shapeMatrix = src._tempMatrix2; - var calcMatrix = src._tempMatrix3; - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - // Renderer size changed? - if (renderer.width !== src._rendererWidth || renderer.height !== src._rendererHeight) - { - src.projOrtho(0, renderer.width, renderer.height, 0); - } - - src.load(calcMatrix.matrix); - src.flush(); - } - - renderer.rebindPipeline(pipeline); -}; - -module.exports = ShaderWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Shader#renderWebGL + * @since 3.17.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Shader} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ShaderWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (!src.shader) + { + return; + } + + var pipeline = renderer.currentPipeline; + + renderer.clearPipeline(); + + if (src.renderToTexture) + { + src.load(); + src.flush(); + } + else + { + var camMatrix = src._tempMatrix1; + var shapeMatrix = src._tempMatrix2; + var calcMatrix = src._tempMatrix3; + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + // Renderer size changed? + if (renderer.width !== src._rendererWidth || renderer.height !== src._rendererHeight) + { + src.projOrtho(0, renderer.width, renderer.height, 0); + } + + src.load(calcMatrix.matrix); + src.flush(); + } + + renderer.rebindPipeline(pipeline); +}; + +module.exports = ShaderWebGLRenderer; diff --git a/src/gameobjects/shape/FillPathWebGL.js b/src/gameobjects/shape/FillPathWebGL.js index 12f72c2e0..0479fcb59 100644 --- a/src/gameobjects/shape/FillPathWebGL.js +++ b/src/gameobjects/shape/FillPathWebGL.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders a filled path for the given Shape. - * - * @method Phaser.GameObjects.Shape#FillPathWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipeline - The WebGL Pipeline used to render this Shape. - * @param {Phaser.GameObjects.Components.TransformMatrix} calcMatrix - The transform matrix used to get the position values. - * @param {Phaser.GameObjects.Shape} src - The Game Object shape being rendered in this call. - * @param {number} alpha - The base alpha value. - * @param {number} dx - The source displayOriginX. - * @param {number} dy - The source displayOriginY. - */ -var FillPathWebGL = function (pipeline, calcMatrix, src, alpha, dx, dy) -{ - var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); - - var path = src.pathData; - var pathIndexes = src.pathIndexes; - - for (var i = 0; i < pathIndexes.length; i += 3) - { - var p0 = pathIndexes[i] * 2; - var p1 = pathIndexes[i + 1] * 2; - var p2 = pathIndexes[i + 2] * 2; - - var x0 = path[p0 + 0] - dx; - var y0 = path[p0 + 1] - dy; - var x1 = path[p1 + 0] - dx; - var y1 = path[p1 + 1] - dy; - var x2 = path[p2 + 0] - dx; - var y2 = path[p2 + 1] - dy; - - var tx0 = calcMatrix.getX(x0, y0); - var ty0 = calcMatrix.getY(x0, y0); - - var tx1 = calcMatrix.getX(x1, y1); - var ty1 = calcMatrix.getY(x1, y1); - - var tx2 = calcMatrix.getX(x2, y2); - var ty2 = calcMatrix.getY(x2, y2); - - pipeline.setTexture2D(); - - pipeline.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, 0, 0, 1, 1, fillTintColor, fillTintColor, fillTintColor, pipeline.tintEffect); - } -}; - -module.exports = FillPathWebGL; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders a filled path for the given Shape. + * + * @method Phaser.GameObjects.Shape#FillPathWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipeline - The WebGL Pipeline used to render this Shape. + * @param {Phaser.GameObjects.Components.TransformMatrix} calcMatrix - The transform matrix used to get the position values. + * @param {Phaser.GameObjects.Shape} src - The Game Object shape being rendered in this call. + * @param {number} alpha - The base alpha value. + * @param {number} dx - The source displayOriginX. + * @param {number} dy - The source displayOriginY. + */ +var FillPathWebGL = function (pipeline, calcMatrix, src, alpha, dx, dy) +{ + var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + var path = src.pathData; + var pathIndexes = src.pathIndexes; + + for (var i = 0; i < pathIndexes.length; i += 3) + { + var p0 = pathIndexes[i] * 2; + var p1 = pathIndexes[i + 1] * 2; + var p2 = pathIndexes[i + 2] * 2; + + var x0 = path[p0 + 0] - dx; + var y0 = path[p0 + 1] - dy; + var x1 = path[p1 + 0] - dx; + var y1 = path[p1 + 1] - dy; + var x2 = path[p2 + 0] - dx; + var y2 = path[p2 + 1] - dy; + + var tx0 = calcMatrix.getX(x0, y0); + var ty0 = calcMatrix.getY(x0, y0); + + var tx1 = calcMatrix.getX(x1, y1); + var ty1 = calcMatrix.getY(x1, y1); + + var tx2 = calcMatrix.getX(x2, y2); + var ty2 = calcMatrix.getY(x2, y2); + + pipeline.setTexture2D(); + + pipeline.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, 0, 0, 1, 1, fillTintColor, fillTintColor, fillTintColor, pipeline.tintEffect); + } +}; + +module.exports = FillPathWebGL; diff --git a/src/gameobjects/shape/FillStyleCanvas.js b/src/gameobjects/shape/FillStyleCanvas.js index ad89cbf7a..18aa8be34 100644 --- a/src/gameobjects/shape/FillStyleCanvas.js +++ b/src/gameobjects/shape/FillStyleCanvas.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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. - */ -var FillStyleCanvas = function (ctx, src, altColor, altAlpha) -{ - var fillColor = (altColor) ? altColor : src.fillColor; - var fillAlpha = (altAlpha) ? altAlpha : src.fillAlpha; - - var red = ((fillColor & 0xFF0000) >>> 16); - var green = ((fillColor & 0xFF00) >>> 8); - var blue = (fillColor & 0xFF); - - ctx.fillStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + fillAlpha + ')'; -}; - -module.exports = FillStyleCanvas; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var FillStyleCanvas = function (ctx, src, altColor, altAlpha) +{ + var fillColor = (altColor) ? altColor : src.fillColor; + var fillAlpha = (altAlpha) ? altAlpha : src.fillAlpha; + + var red = ((fillColor & 0xFF0000) >>> 16); + var green = ((fillColor & 0xFF00) >>> 8); + var blue = (fillColor & 0xFF); + + ctx.fillStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + fillAlpha + ')'; +}; + +module.exports = FillStyleCanvas; diff --git a/src/gameobjects/shape/LineStyleCanvas.js b/src/gameobjects/shape/LineStyleCanvas.js index e8b801bcf..dd2ecb7e1 100644 --- a/src/gameobjects/shape/LineStyleCanvas.js +++ b/src/gameobjects/shape/LineStyleCanvas.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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. - */ -var LineStyleCanvas = function (ctx, src, altColor, altAlpha) -{ - var strokeColor = (altColor) ? altColor : src.strokeColor; - var strokeAlpha = (altAlpha) ? altAlpha : src.strokeAlpha; - - var red = ((strokeColor & 0xFF0000) >>> 16); - var green = ((strokeColor & 0xFF00) >>> 8); - var blue = (strokeColor & 0xFF); - - ctx.strokeStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + strokeAlpha + ')'; - ctx.lineWidth = src.lineWidth; -}; - -module.exports = LineStyleCanvas; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var LineStyleCanvas = function (ctx, src, altColor, altAlpha) +{ + var strokeColor = (altColor) ? altColor : src.strokeColor; + var strokeAlpha = (altAlpha) ? altAlpha : src.strokeAlpha; + + var red = ((strokeColor & 0xFF0000) >>> 16); + var green = ((strokeColor & 0xFF00) >>> 8); + var blue = (strokeColor & 0xFF); + + ctx.strokeStyle = 'rgba(' + red + ',' + green + ',' + blue + ',' + strokeAlpha + ')'; + ctx.lineWidth = src.lineWidth; +}; + +module.exports = LineStyleCanvas; diff --git a/src/gameobjects/shape/Shape.js b/src/gameobjects/shape/Shape.js index 82c452a0b..44246110e 100644 --- a/src/gameobjects/shape/Shape.js +++ b/src/gameobjects/shape/Shape.js @@ -1,294 +1,294 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var Line = require('../../geom/line/Line'); - -/** - * @classdesc - * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. - * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. - * - * @class Shape - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @extends Phaser.GameObjects.Components.AlphaSingle - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.ComputedSize - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @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 {string} [type] - The internal type of the Shape. - * @param {any} [data] - The data of the source shape geometry, if any. - */ -var Shape = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.AlphaSingle, - Components.BlendMode, - Components.ComputedSize, - Components.Depth, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Transform, - Components.Visible - ], - - initialize: - - function Shape (scene, type, data) - { - if (type === undefined) { type = 'Shape'; } - - GameObject.call(this, scene, type); - - /** - * The source Shape data. Typically a geometry object. - * You should not manipulate this directly. - * - * @name Phaser.GameObjects.Shape#data - * @type {any} - * @readonly - * @since 3.13.0 - */ - this.geom = data; - - /** - * Holds the polygon path data for filled rendering. - * - * @name Phaser.GameObjects.Shape#pathData - * @type {number[]} - * @readonly - * @since 3.13.0 - */ - this.pathData = []; - - /** - * Holds the earcut polygon path index data for filled rendering. - * - * @name Phaser.GameObjects.Shape#pathIndexes - * @type {integer[]} - * @readonly - * @since 3.13.0 - */ - this.pathIndexes = []; - - /** - * The fill color used by this Shape. - * - * @name Phaser.GameObjects.Shape#fillColor - * @type {number} - * @since 3.13.0 - */ - this.fillColor = 0xffffff; - - /** - * The fill alpha value used by this Shape. - * - * @name Phaser.GameObjects.Shape#fillAlpha - * @type {number} - * @since 3.13.0 - */ - this.fillAlpha = 1; - - /** - * The stroke color used by this Shape. - * - * @name Phaser.GameObjects.Shape#strokeColor - * @type {number} - * @since 3.13.0 - */ - this.strokeColor = 0xffffff; - - /** - * The stroke alpha value used by this Shape. - * - * @name Phaser.GameObjects.Shape#strokeAlpha - * @type {number} - * @since 3.13.0 - */ - this.strokeAlpha = 1; - - /** - * The stroke line width used by this Shape. - * - * @name Phaser.GameObjects.Shape#lineWidth - * @type {number} - * @since 3.13.0 - */ - this.lineWidth = 1; - - /** - * Controls if this Shape is filled or not. - * Note that some Shapes do not support being filled (such as Line shapes) - * - * @name Phaser.GameObjects.Shape#isFilled - * @type {boolean} - * @since 3.13.0 - */ - this.isFilled = false; - - /** - * Controls if this Shape is stroked or not. - * Note that some Shapes do not support being stroked (such as Iso Box shapes) - * - * @name Phaser.GameObjects.Shape#isStroked - * @type {boolean} - * @since 3.13.0 - */ - this.isStroked = false; - - /** - * Controls if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * @name Phaser.GameObjects.Shape#closePath - * @type {boolean} - * @since 3.13.0 - */ - this.closePath = true; - - /** - * Private internal value. - * A Line used when parsing internal path data to avoid constant object re-creation. - * - * @name Phaser.GameObjects.Curve#_tempLine - * @type {Phaser.Geom.Line} - * @private - * @since 3.13.0 - */ - this._tempLine = new Line(); - - this.initPipeline(); - }, - - /** - * Sets the fill color and alpha for this Shape. - * - * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. - * - * Note that some Shapes do not support fill colors, such as the Line shape. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setFillStyle - * @since 3.13.0 - * - * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. - * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. - * - * @return {this} This Game Object instance. - */ - setFillStyle: function (color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - if (color === undefined) - { - this.isFilled = false; - } - else - { - this.fillColor = color; - this.fillAlpha = alpha; - this.isFilled = true; - } - - return this; - }, - - /** - * Sets the stroke color and alpha for this Shape. - * - * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. - * - * Note that some Shapes do not support being stroked, such as the Iso Box shape. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setStrokeStyle - * @since 3.13.0 - * - * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. - * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. - * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. - * - * @return {this} This Game Object instance. - */ - setStrokeStyle: function (lineWidth, color, alpha) - { - if (alpha === undefined) { alpha = 1; } - - if (lineWidth === undefined) - { - this.isStroked = false; - } - else - { - this.lineWidth = lineWidth; - this.strokeColor = color; - this.strokeAlpha = alpha; - this.isStroked = true; - } - - return this; - }, - - /** - * Sets if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * This call can be chained. - * - * @method Phaser.GameObjects.Shape#setClosePath - * @since 3.13.0 - * - * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. - * - * @return {this} This Game Object instance. - */ - setClosePath: function (value) - { - this.closePath = value; - - return this; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Shape#preDestroy - * @protected - * @since 3.13.0 - */ - preDestroy: function () - { - this.geom = null; - this._tempLine = null; - this.pathData = []; - this.pathIndexes = []; - } - -}); - -module.exports = Shape; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var Line = require('../../geom/line/Line'); + +/** + * @classdesc + * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. + * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. + * + * @class Shape + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @extends Phaser.GameObjects.Components.AlphaSingle + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.ComputedSize + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @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 {string} [type] - The internal type of the Shape. + * @param {any} [data] - The data of the source shape geometry, if any. + */ +var Shape = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.AlphaSingle, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Transform, + Components.Visible + ], + + initialize: + + function Shape (scene, type, data) + { + if (type === undefined) { type = 'Shape'; } + + GameObject.call(this, scene, type); + + /** + * The source Shape data. Typically a geometry object. + * You should not manipulate this directly. + * + * @name Phaser.GameObjects.Shape#data + * @type {any} + * @readonly + * @since 3.13.0 + */ + this.geom = data; + + /** + * Holds the polygon path data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathData + * @type {number[]} + * @readonly + * @since 3.13.0 + */ + this.pathData = []; + + /** + * Holds the earcut polygon path index data for filled rendering. + * + * @name Phaser.GameObjects.Shape#pathIndexes + * @type {integer[]} + * @readonly + * @since 3.13.0 + */ + this.pathIndexes = []; + + /** + * The fill color used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillColor + * @type {number} + * @since 3.13.0 + */ + this.fillColor = 0xffffff; + + /** + * The fill alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#fillAlpha + * @type {number} + * @since 3.13.0 + */ + this.fillAlpha = 1; + + /** + * The stroke color used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeColor + * @type {number} + * @since 3.13.0 + */ + this.strokeColor = 0xffffff; + + /** + * The stroke alpha value used by this Shape. + * + * @name Phaser.GameObjects.Shape#strokeAlpha + * @type {number} + * @since 3.13.0 + */ + this.strokeAlpha = 1; + + /** + * The stroke line width used by this Shape. + * + * @name Phaser.GameObjects.Shape#lineWidth + * @type {number} + * @since 3.13.0 + */ + this.lineWidth = 1; + + /** + * Controls if this Shape is filled or not. + * Note that some Shapes do not support being filled (such as Line shapes) + * + * @name Phaser.GameObjects.Shape#isFilled + * @type {boolean} + * @since 3.13.0 + */ + this.isFilled = false; + + /** + * Controls if this Shape is stroked or not. + * Note that some Shapes do not support being stroked (such as Iso Box shapes) + * + * @name Phaser.GameObjects.Shape#isStroked + * @type {boolean} + * @since 3.13.0 + */ + this.isStroked = false; + + /** + * Controls if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * @name Phaser.GameObjects.Shape#closePath + * @type {boolean} + * @since 3.13.0 + */ + this.closePath = true; + + /** + * Private internal value. + * A Line used when parsing internal path data to avoid constant object re-creation. + * + * @name Phaser.GameObjects.Curve#_tempLine + * @type {Phaser.Geom.Line} + * @private + * @since 3.13.0 + */ + this._tempLine = new Line(); + + this.initPipeline(); + }, + + /** + * Sets the fill color and alpha for this Shape. + * + * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. + * + * Note that some Shapes do not support fill colors, such as the Line shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setFillStyle + * @since 3.13.0 + * + * @param {number} [color] - The color used to fill this shape. If not provided the Shape will not be filled. + * @param {number} [alpha=1] - The alpha value used when filling this shape, if a fill color is given. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (color === undefined) + { + this.isFilled = false; + } + else + { + this.fillColor = color; + this.fillAlpha = alpha; + this.isFilled = true; + } + + return this; + }, + + /** + * Sets the stroke color and alpha for this Shape. + * + * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. + * + * Note that some Shapes do not support being stroked, such as the Iso Box shape. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setStrokeStyle + * @since 3.13.0 + * + * @param {number} [lineWidth] - The width of line to stroke with. If not provided or undefined the Shape will not be stroked. + * @param {number} [color] - The color used to stroke this shape. If not provided the Shape will not be stroked. + * @param {number} [alpha=1] - The alpha value used when stroking this shape, if a stroke color is given. + * + * @return {this} This Game Object instance. + */ + setStrokeStyle: function (lineWidth, color, alpha) + { + if (alpha === undefined) { alpha = 1; } + + if (lineWidth === undefined) + { + this.isStroked = false; + } + else + { + this.lineWidth = lineWidth; + this.strokeColor = color; + this.strokeAlpha = alpha; + this.isStroked = true; + } + + return this; + }, + + /** + * Sets if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * This call can be chained. + * + * @method Phaser.GameObjects.Shape#setClosePath + * @since 3.13.0 + * + * @param {boolean} value - Set to `true` if the Shape should be closed when stroked, otherwise `false`. + * + * @return {this} This Game Object instance. + */ + setClosePath: function (value) + { + this.closePath = value; + + return this; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Shape#preDestroy + * @protected + * @since 3.13.0 + */ + preDestroy: function () + { + this.geom = null; + this._tempLine = null; + this.pathData = []; + this.pathIndexes = []; + } + +}); + +module.exports = Shape; diff --git a/src/gameobjects/shape/StrokePathWebGL.js b/src/gameobjects/shape/StrokePathWebGL.js index 88c12f546..b7e9b314f 100644 --- a/src/gameobjects/shape/StrokePathWebGL.js +++ b/src/gameobjects/shape/StrokePathWebGL.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders a stroke outline around the given Shape. - * - * @method Phaser.GameObjects.Shape#StrokePathWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipeline - The WebGL Pipeline used to render this Shape. - * @param {Phaser.GameObjects.Shape} src - The Game Object shape being rendered in this call. - * @param {number} alpha - The base alpha value. - * @param {number} dx - The source displayOriginX. - * @param {number} dy - The source displayOriginY. - */ -var StrokePathWebGL = function (pipeline, src, alpha, dx, dy) -{ - var strokeTint = pipeline.strokeTint; - var strokeTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); - - strokeTint.TL = strokeTintColor; - strokeTint.TR = strokeTintColor; - strokeTint.BL = strokeTintColor; - strokeTint.BR = strokeTintColor; - - var path = src.pathData; - var pathLength = path.length - 1; - var lineWidth = src.lineWidth; - var halfLineWidth = lineWidth / 2; - - var px1 = path[0] - dx; - var py1 = path[1] - dy; - - if (!src.closePath) - { - pathLength -= 2; - } - - for (var i = 2; i < pathLength; i += 2) - { - var px2 = path[i] - dx; - var py2 = path[i + 1] - dy; - - pipeline.setTexture2D(); - - pipeline.batchLine( - px1, - py1, - px2, - py2, - halfLineWidth, - halfLineWidth, - lineWidth, - i - 2, - (src.closePath) ? (i === pathLength - 1) : false - ); - - px1 = px2; - py1 = py2; - } -}; - -module.exports = StrokePathWebGL; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders a stroke outline around the given Shape. + * + * @method Phaser.GameObjects.Shape#StrokePathWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipeline - The WebGL Pipeline used to render this Shape. + * @param {Phaser.GameObjects.Shape} src - The Game Object shape being rendered in this call. + * @param {number} alpha - The base alpha value. + * @param {number} dx - The source displayOriginX. + * @param {number} dy - The source displayOriginY. + */ +var StrokePathWebGL = function (pipeline, src, alpha, dx, dy) +{ + var strokeTint = pipeline.strokeTint; + var strokeTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); + + strokeTint.TL = strokeTintColor; + strokeTint.TR = strokeTintColor; + strokeTint.BL = strokeTintColor; + strokeTint.BR = strokeTintColor; + + var path = src.pathData; + var pathLength = path.length - 1; + var lineWidth = src.lineWidth; + var halfLineWidth = lineWidth / 2; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + pipeline.setTexture2D(); + + pipeline.batchLine( + px1, + py1, + px2, + py2, + halfLineWidth, + halfLineWidth, + lineWidth, + i - 2, + (src.closePath) ? (i === pathLength - 1) : false + ); + + px1 = px2; + py1 = py2; + } +}; + +module.exports = StrokePathWebGL; diff --git a/src/gameobjects/shape/arc/Arc.js b/src/gameobjects/shape/arc/Arc.js index ee80e43a7..3f04d018a 100644 --- a/src/gameobjects/shape/arc/Arc.js +++ b/src/gameobjects/shape/arc/Arc.js @@ -1,403 +1,403 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArcRender = require('./ArcRender'); -var Class = require('../../../utils/Class'); -var DegToRad = require('../../../math/DegToRad'); -var Earcut = require('../../../geom/polygon/Earcut'); -var GeomCircle = require('../../../geom/circle/Circle'); -var MATH_CONST = require('../../../math/const'); -var Shape = require('../Shape'); - -/** - * @classdesc - * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an arc shape. You can control the start and end angles of the arc, - * as well as if the angles are winding clockwise or anti-clockwise. With the default settings - * it renders as a complete circle. By changing the angles you can create other arc shapes, - * such as half-circles. - * - * Arcs also have an `iterations` property and corresponding `setIterations` method. This allows - * you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. - * - * @class Arc - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [radius=128] - The radius of the arc. - * @param {integer} [startAngle=0] - The start angle of the arc, in degrees. - * @param {integer} [endAngle=360] - The end angle of the arc, in degrees. - * @param {boolean} [anticlockwise=false] - The winding order of the start and end angles. - * @param {number} [fillColor] - The color the arc will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Arc = new Class({ - - Extends: Shape, - - Mixins: [ - ArcRender - ], - - initialize: - - function Arc (scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (radius === undefined) { radius = 128; } - if (startAngle === undefined) { startAngle = 0; } - if (endAngle === undefined) { endAngle = 360; } - if (anticlockwise === undefined) { anticlockwise = false; } - - Shape.call(this, scene, 'Arc', new GeomCircle(0, 0, radius)); - - /** - * Private internal value. Holds the start angle in degrees. - * - * @name Phaser.GameObjects.Arc#_startAngle - * @type {integer} - * @private - * @since 3.13.0 - */ - this._startAngle = startAngle; - - /** - * Private internal value. Holds the end angle in degrees. - * - * @name Phaser.GameObjects.Arc#_endAngle - * @type {integer} - * @private - * @since 3.13.0 - */ - this._endAngle = endAngle; - - /** - * Private internal value. Holds the winding order of the start and end angles. - * - * @name Phaser.GameObjects.Arc#_anticlockwise - * @type {boolean} - * @private - * @since 3.13.0 - */ - this._anticlockwise = anticlockwise; - - /** - * Private internal value. Holds the number of iterations used when drawing the arc. - * - * @name Phaser.GameObjects.Arc#_iterations - * @type {number} - * @default 0.01 - * @private - * @since 3.13.0 - */ - this._iterations = 0.01; - - this.setPosition(x, y); - - var diameter = this.geom.radius * 2; - this.setSize(diameter, diameter); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateDisplayOrigin(); - this.updateData(); - }, - - /** - * The number of iterations used when drawing the arc. - * Increase this value for smoother arcs, at the cost of more polygons being rendered. - * Modify this value by small amounts, such as 0.01. - * - * @name Phaser.GameObjects.Arc#iterations - * @type {number} - * @default 0.01 - * @since 3.13.0 - */ - iterations: { - - get: function () - { - return this._iterations; - }, - - set: function (value) - { - this._iterations = value; - - this.updateData(); - } - - }, - - /** - * The radius of the arc. - * - * @name Phaser.GameObjects.Arc#radius - * @type {number} - * @since 3.13.0 - */ - radius: { - - get: function () - { - return this.geom.radius; - }, - - set: function (value) - { - this.geom.radius = value; - - var diameter = value * 2; - this.setSize(diameter, diameter); - this.updateDisplayOrigin(); - this.updateData(); - } - - }, - - /** - * The start angle of the arc, in degrees. - * - * @name Phaser.GameObjects.Arc#startAngle - * @type {integer} - * @since 3.13.0 - */ - startAngle: { - - get: function () - { - return this._startAngle; - }, - - set: function (value) - { - this._startAngle = value; - - this.updateData(); - } - - }, - - /** - * The end angle of the arc, in degrees. - * - * @name Phaser.GameObjects.Arc#endAngle - * @type {integer} - * @since 3.13.0 - */ - endAngle: { - - get: function () - { - return this._endAngle; - }, - - set: function (value) - { - this._endAngle = value; - - this.updateData(); - } - - }, - - /** - * The winding order of the start and end angles. - * - * @name Phaser.GameObjects.Arc#anticlockwise - * @type {boolean} - * @since 3.13.0 - */ - anticlockwise: { - - get: function () - { - return this._anticlockwise; - }, - - set: function (value) - { - this._anticlockwise = value; - - this.updateData(); - } - - }, - - /** - * Sets the radius of the arc. - * This call can be chained. - * - * @method Phaser.GameObjects.Arc#setRadius - * @since 3.13.0 - * - * @param {number} value - The value to set the radius to. - * - * @return {this} This Game Object instance. - */ - setRadius: function (value) - { - this.radius = value; - - return this; - }, - - /** - * Sets the number of iterations used when drawing the arc. - * Increase this value for smoother arcs, at the cost of more polygons being rendered. - * Modify this value by small amounts, such as 0.01. - * This call can be chained. - * - * @method Phaser.GameObjects.Arc#setIterations - * @since 3.13.0 - * - * @param {number} value - The value to set the iterations to. - * - * @return {this} This Game Object instance. - */ - setIterations: function (value) - { - if (value === undefined) { value = 0.01; } - - this.iterations = value; - - return this; - }, - - /** - * Sets the starting angle of the arc, in degrees. - * This call can be chained. - * - * @method Phaser.GameObjects.Arc#setStartAngle - * @since 3.13.0 - * - * @param {integer} value - The value to set the starting angle to. - * - * @return {this} This Game Object instance. - */ - setStartAngle: function (angle, anticlockwise) - { - this._startAngle = angle; - - if (anticlockwise !== undefined) - { - this._anticlockwise = anticlockwise; - } - - return this.updateData(); - }, - - /** - * Sets the ending angle of the arc, in degrees. - * This call can be chained. - * - * @method Phaser.GameObjects.Arc#setEndAngle - * @since 3.13.0 - * - * @param {integer} value - The value to set the ending angle to. - * - * @return {this} This Game Object instance. - */ - setEndAngle: function (angle, anticlockwise) - { - this._endAngle = angle; - - if (anticlockwise !== undefined) - { - this._anticlockwise = anticlockwise; - } - - return this.updateData(); - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Arc#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var step = this._iterations; - var iteration = step; - - var radius = this.geom.radius; - var startAngle = DegToRad(this._startAngle); - var endAngle = DegToRad(this._endAngle); - var anticlockwise = this._anticlockwise; - - var x = radius; - var y = radius; - - endAngle -= startAngle; - - if (anticlockwise) - { - if (endAngle < -MATH_CONST.PI2) - { - endAngle = -MATH_CONST.PI2; - } - else if (endAngle > 0) - { - endAngle = -MATH_CONST.PI2 + endAngle % MATH_CONST.PI2; - } - } - else if (endAngle > MATH_CONST.PI2) - { - endAngle = MATH_CONST.PI2; - } - else if (endAngle < 0) - { - endAngle = MATH_CONST.PI2 + endAngle % MATH_CONST.PI2; - } - - var path = [ x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius ]; - - var ta; - - while (iteration < 1) - { - ta = endAngle * iteration + startAngle; - - path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); - - iteration += step; - } - - ta = endAngle + startAngle; - - path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); - - path.push(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius); - - this.pathIndexes = Earcut(path); - this.pathData = path; - - return this; - } - -}); - -module.exports = Arc; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcRender = require('./ArcRender'); +var Class = require('../../../utils/Class'); +var DegToRad = require('../../../math/DegToRad'); +var Earcut = require('../../../geom/polygon/Earcut'); +var GeomCircle = require('../../../geom/circle/Circle'); +var MATH_CONST = require('../../../math/const'); +var Shape = require('../Shape'); + +/** + * @classdesc + * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an arc shape. You can control the start and end angles of the arc, + * as well as if the angles are winding clockwise or anti-clockwise. With the default settings + * it renders as a complete circle. By changing the angles you can create other arc shapes, + * such as half-circles. + * + * Arcs also have an `iterations` property and corresponding `setIterations` method. This allows + * you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. + * + * @class Arc + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [radius=128] - The radius of the arc. + * @param {integer} [startAngle=0] - The start angle of the arc, in degrees. + * @param {integer} [endAngle=360] - The end angle of the arc, in degrees. + * @param {boolean} [anticlockwise=false] - The winding order of the start and end angles. + * @param {number} [fillColor] - The color the arc will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Arc = new Class({ + + Extends: Shape, + + Mixins: [ + ArcRender + ], + + initialize: + + function Arc (scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (radius === undefined) { radius = 128; } + if (startAngle === undefined) { startAngle = 0; } + if (endAngle === undefined) { endAngle = 360; } + if (anticlockwise === undefined) { anticlockwise = false; } + + Shape.call(this, scene, 'Arc', new GeomCircle(0, 0, radius)); + + /** + * Private internal value. Holds the start angle in degrees. + * + * @name Phaser.GameObjects.Arc#_startAngle + * @type {integer} + * @private + * @since 3.13.0 + */ + this._startAngle = startAngle; + + /** + * Private internal value. Holds the end angle in degrees. + * + * @name Phaser.GameObjects.Arc#_endAngle + * @type {integer} + * @private + * @since 3.13.0 + */ + this._endAngle = endAngle; + + /** + * Private internal value. Holds the winding order of the start and end angles. + * + * @name Phaser.GameObjects.Arc#_anticlockwise + * @type {boolean} + * @private + * @since 3.13.0 + */ + this._anticlockwise = anticlockwise; + + /** + * Private internal value. Holds the number of iterations used when drawing the arc. + * + * @name Phaser.GameObjects.Arc#_iterations + * @type {number} + * @default 0.01 + * @private + * @since 3.13.0 + */ + this._iterations = 0.01; + + this.setPosition(x, y); + + var diameter = this.geom.radius * 2; + this.setSize(diameter, diameter); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * The number of iterations used when drawing the arc. + * Increase this value for smoother arcs, at the cost of more polygons being rendered. + * Modify this value by small amounts, such as 0.01. + * + * @name Phaser.GameObjects.Arc#iterations + * @type {number} + * @default 0.01 + * @since 3.13.0 + */ + iterations: { + + get: function () + { + return this._iterations; + }, + + set: function (value) + { + this._iterations = value; + + this.updateData(); + } + + }, + + /** + * The radius of the arc. + * + * @name Phaser.GameObjects.Arc#radius + * @type {number} + * @since 3.13.0 + */ + radius: { + + get: function () + { + return this.geom.radius; + }, + + set: function (value) + { + this.geom.radius = value; + + var diameter = value * 2; + this.setSize(diameter, diameter); + this.updateDisplayOrigin(); + this.updateData(); + } + + }, + + /** + * The start angle of the arc, in degrees. + * + * @name Phaser.GameObjects.Arc#startAngle + * @type {integer} + * @since 3.13.0 + */ + startAngle: { + + get: function () + { + return this._startAngle; + }, + + set: function (value) + { + this._startAngle = value; + + this.updateData(); + } + + }, + + /** + * The end angle of the arc, in degrees. + * + * @name Phaser.GameObjects.Arc#endAngle + * @type {integer} + * @since 3.13.0 + */ + endAngle: { + + get: function () + { + return this._endAngle; + }, + + set: function (value) + { + this._endAngle = value; + + this.updateData(); + } + + }, + + /** + * The winding order of the start and end angles. + * + * @name Phaser.GameObjects.Arc#anticlockwise + * @type {boolean} + * @since 3.13.0 + */ + anticlockwise: { + + get: function () + { + return this._anticlockwise; + }, + + set: function (value) + { + this._anticlockwise = value; + + this.updateData(); + } + + }, + + /** + * Sets the radius of the arc. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setRadius + * @since 3.13.0 + * + * @param {number} value - The value to set the radius to. + * + * @return {this} This Game Object instance. + */ + setRadius: function (value) + { + this.radius = value; + + return this; + }, + + /** + * Sets the number of iterations used when drawing the arc. + * Increase this value for smoother arcs, at the cost of more polygons being rendered. + * Modify this value by small amounts, such as 0.01. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setIterations + * @since 3.13.0 + * + * @param {number} value - The value to set the iterations to. + * + * @return {this} This Game Object instance. + */ + setIterations: function (value) + { + if (value === undefined) { value = 0.01; } + + this.iterations = value; + + return this; + }, + + /** + * Sets the starting angle of the arc, in degrees. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setStartAngle + * @since 3.13.0 + * + * @param {integer} value - The value to set the starting angle to. + * + * @return {this} This Game Object instance. + */ + setStartAngle: function (angle, anticlockwise) + { + this._startAngle = angle; + + if (anticlockwise !== undefined) + { + this._anticlockwise = anticlockwise; + } + + return this.updateData(); + }, + + /** + * Sets the ending angle of the arc, in degrees. + * This call can be chained. + * + * @method Phaser.GameObjects.Arc#setEndAngle + * @since 3.13.0 + * + * @param {integer} value - The value to set the ending angle to. + * + * @return {this} This Game Object instance. + */ + setEndAngle: function (angle, anticlockwise) + { + this._endAngle = angle; + + if (anticlockwise !== undefined) + { + this._anticlockwise = anticlockwise; + } + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Arc#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var step = this._iterations; + var iteration = step; + + var radius = this.geom.radius; + var startAngle = DegToRad(this._startAngle); + var endAngle = DegToRad(this._endAngle); + var anticlockwise = this._anticlockwise; + + var x = radius; + var y = radius; + + endAngle -= startAngle; + + if (anticlockwise) + { + if (endAngle < -MATH_CONST.PI2) + { + endAngle = -MATH_CONST.PI2; + } + else if (endAngle > 0) + { + endAngle = -MATH_CONST.PI2 + endAngle % MATH_CONST.PI2; + } + } + else if (endAngle > MATH_CONST.PI2) + { + endAngle = MATH_CONST.PI2; + } + else if (endAngle < 0) + { + endAngle = MATH_CONST.PI2 + endAngle % MATH_CONST.PI2; + } + + var path = [ x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius ]; + + var ta; + + while (iteration < 1) + { + ta = endAngle * iteration + startAngle; + + path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); + + iteration += step; + } + + ta = endAngle + startAngle; + + path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); + + path.push(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Arc; diff --git a/src/gameobjects/shape/arc/ArcCanvasRenderer.js b/src/gameobjects/shape/arc/ArcCanvasRenderer.js index 4048fae88..5499977ec 100644 --- a/src/gameobjects/shape/arc/ArcCanvasRenderer.js +++ b/src/gameobjects/shape/arc/ArcCanvasRenderer.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DegToRad = require('../../../math/DegToRad'); -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Arc#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Arc} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ArcCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var radius = src.radius; - - ctx.beginPath(); - - ctx.arc( - (radius) - src.originX * (radius * 2), - (radius) - src.originY * (radius * 2), - radius, - DegToRad(src._startAngle), - DegToRad(src._endAngle), - src.anticlockwise - ); - - if (src.closePath) - { - ctx.closePath(); - } - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fill(); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = ArcCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DegToRad = require('../../../math/DegToRad'); +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Arc#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Arc} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ArcCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var radius = src.radius; + + ctx.beginPath(); + + ctx.arc( + (radius) - src.originX * (radius * 2), + (radius) - src.originY * (radius * 2), + radius, + DegToRad(src._startAngle), + DegToRad(src._endAngle), + src.anticlockwise + ); + + if (src.closePath) + { + ctx.closePath(); + } + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = ArcCanvasRenderer; diff --git a/src/gameobjects/shape/arc/ArcFactory.js b/src/gameobjects/shape/arc/ArcFactory.js index aa760a132..604297d04 100644 --- a/src/gameobjects/shape/arc/ArcFactory.js +++ b/src/gameobjects/shape/arc/ArcFactory.js @@ -1,67 +1,67 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Arc = require('./Arc'); -var GameObjectFactory = require('../../GameObjectFactory'); - -/** - * Creates a new Arc Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Arc Game Object has been built into Phaser. - * - * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an arc shape. You can control the start and end angles of the arc, - * as well as if the angles are winding clockwise or anti-clockwise. With the default settings - * it renders as a complete circle. By changing the angles you can create other arc shapes, - * such as half-circles. - * - * @method Phaser.GameObjects.GameObjectFactory#arc - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [radius=128] - The radius of the arc. - * @param {integer} [startAngle=0] - The start angle of the arc, in degrees. - * @param {integer} [endAngle=360] - The end angle of the arc, in degrees. - * @param {boolean} [anticlockwise=false] - The winding order of the start and end angles. - * @param {number} [fillColor] - The color the arc will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Arc} The Game Object that was created. - */ -GameObjectFactory.register('arc', function (x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) -{ - return this.displayList.add(new Arc(this.scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha)); -}); - -/** - * Creates a new Circle Shape Game Object and adds it to the Scene. - * - * A Circle is an Arc with no defined start and end angle, making it render as a complete circle. - * - * Note: This method will only be available if the Arc Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#circle - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [radius=128] - The radius of the circle. - * @param {number} [fillColor] - The color the circle will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the circle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Arc} The Game Object that was created. - */ -GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlpha) -{ - return this.displayList.add(new Arc(this.scene, x, y, radius, 0, 360, false, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Arc = require('./Arc'); +var GameObjectFactory = require('../../GameObjectFactory'); + +/** + * Creates a new Arc Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Arc Game Object has been built into Phaser. + * + * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an arc shape. You can control the start and end angles of the arc, + * as well as if the angles are winding clockwise or anti-clockwise. With the default settings + * it renders as a complete circle. By changing the angles you can create other arc shapes, + * such as half-circles. + * + * @method Phaser.GameObjects.GameObjectFactory#arc + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [radius=128] - The radius of the arc. + * @param {integer} [startAngle=0] - The start angle of the arc, in degrees. + * @param {integer} [endAngle=360] - The end angle of the arc, in degrees. + * @param {boolean} [anticlockwise=false] - The winding order of the start and end angles. + * @param {number} [fillColor] - The color the arc will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Arc} The Game Object that was created. + */ +GameObjectFactory.register('arc', function (x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) +{ + return this.displayList.add(new Arc(this.scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha)); +}); + +/** + * Creates a new Circle Shape Game Object and adds it to the Scene. + * + * A Circle is an Arc with no defined start and end angle, making it render as a complete circle. + * + * Note: This method will only be available if the Arc Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#circle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [radius=128] - The radius of the circle. + * @param {number} [fillColor] - The color the circle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the circle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Arc} The Game Object that was created. + */ +GameObjectFactory.register('circle', function (x, y, radius, fillColor, fillAlpha) +{ + return this.displayList.add(new Arc(this.scene, x, y, radius, 0, 360, false, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/arc/ArcRender.js b/src/gameobjects/shape/arc/ArcRender.js index 35989616e..3667e94ff 100644 --- a/src/gameobjects/shape/arc/ArcRender.js +++ b/src/gameobjects/shape/arc/ArcRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./ArcWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./ArcCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./ArcWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./ArcCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/arc/ArcWebGLRenderer.js b/src/gameobjects/shape/arc/ArcWebGLRenderer.js index 48c61034f..ad9273d4d 100644 --- a/src/gameobjects/shape/arc/ArcWebGLRenderer.js +++ b/src/gameobjects/shape/arc/ArcWebGLRenderer.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillPathWebGL = require('../FillPathWebGL'); -var StrokePathWebGL = require('../StrokePathWebGL'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Arc#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Arc} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var ArcWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = ArcWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = require('../FillPathWebGL'); +var StrokePathWebGL = require('../StrokePathWebGL'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Arc#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Arc} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var ArcWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = ArcWebGLRenderer; diff --git a/src/gameobjects/shape/curve/Curve.js b/src/gameobjects/shape/curve/Curve.js index b4c7342bd..a0437f347 100644 --- a/src/gameobjects/shape/curve/Curve.js +++ b/src/gameobjects/shape/curve/Curve.js @@ -1,176 +1,176 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var CurveRender = require('./CurveRender'); -var Earcut = require('../../../geom/polygon/Earcut'); -var Rectangle = require('../../../geom/rectangle/Rectangle'); -var Shape = require('../Shape'); - -/** - * @classdesc - * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to - * the Curve Shape in the constructor. - * - * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - * - * @class Curve - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {Phaser.Curves.Curve} [curve] - The Curve object to use to create the Shape. - * @param {number} [fillColor] - The color the curve will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Curve = new Class({ - - Extends: Shape, - - Mixins: [ - CurveRender - ], - - initialize: - - function Curve (scene, x, y, curve, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - Shape.call(this, scene, 'Curve', curve); - - /** - * Private internal value. - * The number of points used to draw the curve. Higher values create smoother renders at the cost of more triangles being drawn. - * - * @name Phaser.GameObjects.Curve#_smoothness - * @type {integer} - * @private - * @since 3.13.0 - */ - this._smoothness = 32; - - /** - * Private internal value. - * The Curve bounds rectangle. - * - * @name Phaser.GameObjects.Curve#_curveBounds - * @type {Phaser.Geom.Rectangle} - * @private - * @since 3.13.0 - */ - this._curveBounds = new Rectangle(); - - this.closePath = false; - - this.setPosition(x, y); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateData(); - }, - - /** - * The smoothness of the curve. The number of points used when rendering it. - * Increase this value for smoother curves, at the cost of more polygons being rendered. - * - * @name Phaser.GameObjects.Curve#smoothness - * @type {integer} - * @default 32 - * @since 3.13.0 - */ - smoothness: { - - get: function () - { - return this._smoothness; - }, - - set: function (value) - { - this._smoothness = value; - - this.updateData(); - } - - }, - - /** - * Sets the smoothness of the curve. The number of points used when rendering it. - * Increase this value for smoother curves, at the cost of more polygons being rendered. - * This call can be chained. - * - * @method Phaser.GameObjects.Curve#setSmoothness - * @since 3.13.0 - * - * @param {integer} value - The value to set the smoothness to. - * - * @return {this} This Game Object instance. - */ - setSmoothness: function (value) - { - this._smoothness = value; - - return this.updateData(); - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Curve#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var bounds = this._curveBounds; - var smoothness = this._smoothness; - - // Update the bounds in case the underlying data has changed - this.geom.getBounds(bounds, smoothness); - - this.setSize(bounds.width, bounds.height); - this.updateDisplayOrigin(); - - var path = []; - var points = this.geom.getPoints(smoothness); - - for (var i = 0; i < points.length; i++) - { - path.push(points[i].x, points[i].y); - } - - path.push(points[0].x, points[0].y); - - this.pathIndexes = Earcut(path); - this.pathData = path; - - return this; - } - -}); - -module.exports = Curve; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var CurveRender = require('./CurveRender'); +var Earcut = require('../../../geom/polygon/Earcut'); +var Rectangle = require('../../../geom/rectangle/Rectangle'); +var Shape = require('../Shape'); + +/** + * @classdesc + * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to + * the Curve Shape in the constructor. + * + * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @class Curve + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {Phaser.Curves.Curve} [curve] - The Curve object to use to create the Shape. + * @param {number} [fillColor] - The color the curve will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Curve = new Class({ + + Extends: Shape, + + Mixins: [ + CurveRender + ], + + initialize: + + function Curve (scene, x, y, curve, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + Shape.call(this, scene, 'Curve', curve); + + /** + * Private internal value. + * The number of points used to draw the curve. Higher values create smoother renders at the cost of more triangles being drawn. + * + * @name Phaser.GameObjects.Curve#_smoothness + * @type {integer} + * @private + * @since 3.13.0 + */ + this._smoothness = 32; + + /** + * Private internal value. + * The Curve bounds rectangle. + * + * @name Phaser.GameObjects.Curve#_curveBounds + * @type {Phaser.Geom.Rectangle} + * @private + * @since 3.13.0 + */ + this._curveBounds = new Rectangle(); + + this.closePath = false; + + this.setPosition(x, y); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateData(); + }, + + /** + * The smoothness of the curve. The number of points used when rendering it. + * Increase this value for smoother curves, at the cost of more polygons being rendered. + * + * @name Phaser.GameObjects.Curve#smoothness + * @type {integer} + * @default 32 + * @since 3.13.0 + */ + smoothness: { + + get: function () + { + return this._smoothness; + }, + + set: function (value) + { + this._smoothness = value; + + this.updateData(); + } + + }, + + /** + * Sets the smoothness of the curve. The number of points used when rendering it. + * Increase this value for smoother curves, at the cost of more polygons being rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.Curve#setSmoothness + * @since 3.13.0 + * + * @param {integer} value - The value to set the smoothness to. + * + * @return {this} This Game Object instance. + */ + setSmoothness: function (value) + { + this._smoothness = value; + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Curve#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var bounds = this._curveBounds; + var smoothness = this._smoothness; + + // Update the bounds in case the underlying data has changed + this.geom.getBounds(bounds, smoothness); + + this.setSize(bounds.width, bounds.height); + this.updateDisplayOrigin(); + + var path = []; + var points = this.geom.getPoints(smoothness); + + for (var i = 0; i < points.length; i++) + { + path.push(points[i].x, points[i].y); + } + + path.push(points[0].x, points[0].y); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Curve; diff --git a/src/gameobjects/shape/curve/CurveCanvasRenderer.js b/src/gameobjects/shape/curve/CurveCanvasRenderer.js index 639c85b63..c5377a490 100644 --- a/src/gameobjects/shape/curve/CurveCanvasRenderer.js +++ b/src/gameobjects/shape/curve/CurveCanvasRenderer.js @@ -1,82 +1,82 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Curve#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Curve} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var CurveCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX + src._curveBounds.x; - var dy = src._displayOriginY + src._curveBounds.y; - - var path = src.pathData; - var pathLength = path.length - 1; - - var px1 = path[0] - dx; - var py1 = path[1] - dy; - - ctx.beginPath(); - - ctx.moveTo(px1, py1); - - if (!src.closePath) - { - pathLength -= 2; - } - - for (var i = 2; i < pathLength; i += 2) - { - var px2 = path[i] - dx; - var py2 = path[i + 1] - dy; - - ctx.lineTo(px2, py2); - } - - if (src.closePath) - { - ctx.closePath(); - } - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fill(); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = CurveCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Curve#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Curve} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var CurveCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX + src._curveBounds.x; + var dy = src._displayOriginY + src._curveBounds.y; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + if (src.closePath) + { + ctx.closePath(); + } + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = CurveCanvasRenderer; diff --git a/src/gameobjects/shape/curve/CurveFactory.js b/src/gameobjects/shape/curve/CurveFactory.js index 2b8ff9572..8e4ff4019 100644 --- a/src/gameobjects/shape/curve/CurveFactory.js +++ b/src/gameobjects/shape/curve/CurveFactory.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var Curve = require('./Curve'); - -/** - * Creates a new Curve Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Curve Game Object has been built into Phaser. - * - * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to - * the Curve Shape in the constructor. - * - * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - * - * @method Phaser.GameObjects.GameObjectFactory#curve - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {Phaser.Curves.Curve} [curve] - The Curve object to use to create the Shape. - * @param {number} [fillColor] - The color the curve will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Curve} The Game Object that was created. - */ -GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) -{ - return this.displayList.add(new Curve(this.scene, x, y, curve, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var Curve = require('./Curve'); + +/** + * Creates a new Curve Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Curve Game Object has been built into Phaser. + * + * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to + * the Curve Shape in the constructor. + * + * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @method Phaser.GameObjects.GameObjectFactory#curve + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {Phaser.Curves.Curve} [curve] - The Curve object to use to create the Shape. + * @param {number} [fillColor] - The color the curve will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Curve} The Game Object that was created. + */ +GameObjectFactory.register('curve', function (x, y, curve, fillColor, fillAlpha) +{ + return this.displayList.add(new Curve(this.scene, x, y, curve, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/curve/CurveRender.js b/src/gameobjects/shape/curve/CurveRender.js index 5d4334faf..4b916b561 100644 --- a/src/gameobjects/shape/curve/CurveRender.js +++ b/src/gameobjects/shape/curve/CurveRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./CurveWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./CurveCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./CurveWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./CurveCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/curve/CurveWebGLRenderer.js b/src/gameobjects/shape/curve/CurveWebGLRenderer.js index 228b62f14..b64b02572 100644 --- a/src/gameobjects/shape/curve/CurveWebGLRenderer.js +++ b/src/gameobjects/shape/curve/CurveWebGLRenderer.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillPathWebGL = require('../FillPathWebGL'); -var StrokePathWebGL = require('../StrokePathWebGL'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Curve#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Curve} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var CurveWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX + src._curveBounds.x; - var dy = src._displayOriginY + src._curveBounds.y; - - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = CurveWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = require('../FillPathWebGL'); +var StrokePathWebGL = require('../StrokePathWebGL'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Curve#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Curve} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var CurveWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX + src._curveBounds.x; + var dy = src._displayOriginY + src._curveBounds.y; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = CurveWebGLRenderer; diff --git a/src/gameobjects/shape/ellipse/Ellipse.js b/src/gameobjects/shape/ellipse/Ellipse.js index 793fefdef..b94de2359 100644 --- a/src/gameobjects/shape/ellipse/Ellipse.js +++ b/src/gameobjects/shape/ellipse/Ellipse.js @@ -1,181 +1,181 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Earcut = require('../../../geom/polygon/Earcut'); -var EllipseRender = require('./EllipseRender'); -var GeomEllipse = require('../../../geom/ellipse/Ellipse'); -var Shape = require('../Shape'); - -/** - * @classdesc - * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. - * If the width and height match it will render as a circle. If the width is less than the height, - * it will look more like an egg shape. - * - * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - * - * @class Ellipse - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the ellipse. An ellipse with equal width and height renders as a circle. - * @param {number} [height=128] - The height of the ellipse. An ellipse with equal width and height renders as a circle. - * @param {number} [fillColor] - The color the ellipse will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Ellipse = new Class({ - - Extends: Shape, - - Mixins: [ - EllipseRender - ], - - initialize: - - function Ellipse (scene, x, y, width, height, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 128; } - if (height === undefined) { height = 128; } - - Shape.call(this, scene, 'Ellipse', new GeomEllipse(width / 2, height / 2, width, height)); - - /** - * Private internal value. - * The number of points used to draw the curve. Higher values create smoother renders at the cost of more triangles being drawn. - * - * @name Phaser.GameObjects.Ellipse#_smoothness - * @type {integer} - * @private - * @since 3.13.0 - */ - this._smoothness = 64; - - this.setPosition(x, y); - - this.width = width; - this.height = height; - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateDisplayOrigin(); - this.updateData(); - }, - - /** - * The smoothness of the ellipse. The number of points used when rendering it. - * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. - * - * @name Phaser.GameObjects.Ellipse#smoothness - * @type {integer} - * @default 64 - * @since 3.13.0 - */ - smoothness: { - - get: function () - { - return this._smoothness; - }, - - set: function (value) - { - this._smoothness = value; - - this.updateData(); - } - - }, - - /** - * Sets the size of the ellipse by changing the underlying geometry data, rather than scaling the object. - * This call can be chained. - * - * @method Phaser.GameObjects.Ellipse#setSize - * @since 3.13.0 - * - * @param {number} width - The width of the ellipse. - * @param {number} height - The height of the ellipse. - * - * @return {this} This Game Object instance. - */ - setSize: function (width, height) - { - this.geom.setSize(width, height); - - return this.updateData(); - }, - - /** - * Sets the smoothness of the ellipse. The number of points used when rendering it. - * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. - * This call can be chained. - * - * @method Phaser.GameObjects.Ellipse#setSmoothness - * @since 3.13.0 - * - * @param {integer} value - The value to set the smoothness to. - * - * @return {this} This Game Object instance. - */ - setSmoothness: function (value) - { - this._smoothness = value; - - return this.updateData(); - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Ellipse#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var path = []; - var points = this.geom.getPoints(this._smoothness); - - for (var i = 0; i < points.length; i++) - { - path.push(points[i].x, points[i].y); - } - - path.push(points[0].x, points[0].y); - - this.pathIndexes = Earcut(path); - this.pathData = path; - - return this; - } - -}); - -module.exports = Ellipse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Earcut = require('../../../geom/polygon/Earcut'); +var EllipseRender = require('./EllipseRender'); +var GeomEllipse = require('../../../geom/ellipse/Ellipse'); +var Shape = require('../Shape'); + +/** + * @classdesc + * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. + * If the width and height match it will render as a circle. If the width is less than the height, + * it will look more like an egg shape. + * + * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @class Ellipse + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [height=128] - The height of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [fillColor] - The color the ellipse will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Ellipse = new Class({ + + Extends: Shape, + + Mixins: [ + EllipseRender + ], + + initialize: + + function Ellipse (scene, x, y, width, height, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + + Shape.call(this, scene, 'Ellipse', new GeomEllipse(width / 2, height / 2, width, height)); + + /** + * Private internal value. + * The number of points used to draw the curve. Higher values create smoother renders at the cost of more triangles being drawn. + * + * @name Phaser.GameObjects.Ellipse#_smoothness + * @type {integer} + * @private + * @since 3.13.0 + */ + this._smoothness = 64; + + this.setPosition(x, y); + + this.width = width; + this.height = height; + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * The smoothness of the ellipse. The number of points used when rendering it. + * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. + * + * @name Phaser.GameObjects.Ellipse#smoothness + * @type {integer} + * @default 64 + * @since 3.13.0 + */ + smoothness: { + + get: function () + { + return this._smoothness; + }, + + set: function (value) + { + this._smoothness = value; + + this.updateData(); + } + + }, + + /** + * Sets the size of the ellipse by changing the underlying geometry data, rather than scaling the object. + * This call can be chained. + * + * @method Phaser.GameObjects.Ellipse#setSize + * @since 3.13.0 + * + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * + * @return {this} This Game Object instance. + */ + setSize: function (width, height) + { + this.geom.setSize(width, height); + + return this.updateData(); + }, + + /** + * Sets the smoothness of the ellipse. The number of points used when rendering it. + * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.Ellipse#setSmoothness + * @since 3.13.0 + * + * @param {integer} value - The value to set the smoothness to. + * + * @return {this} This Game Object instance. + */ + setSmoothness: function (value) + { + this._smoothness = value; + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Ellipse#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var points = this.geom.getPoints(this._smoothness); + + for (var i = 0; i < points.length; i++) + { + path.push(points[i].x, points[i].y); + } + + path.push(points[0].x, points[0].y); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Ellipse; diff --git a/src/gameobjects/shape/ellipse/EllipseCanvasRenderer.js b/src/gameobjects/shape/ellipse/EllipseCanvasRenderer.js index c8b8487fa..4d110ff6f 100644 --- a/src/gameobjects/shape/ellipse/EllipseCanvasRenderer.js +++ b/src/gameobjects/shape/ellipse/EllipseCanvasRenderer.js @@ -1,79 +1,79 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Ellipse#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Ellipse} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var EllipseCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var path = src.pathData; - var pathLength = path.length - 1; - - var px1 = path[0] - dx; - var py1 = path[1] - dy; - - ctx.beginPath(); - - ctx.moveTo(px1, py1); - - if (!src.closePath) - { - pathLength -= 2; - } - - for (var i = 2; i < pathLength; i += 2) - { - var px2 = path[i] - dx; - var py2 = path[i + 1] - dy; - - ctx.lineTo(px2, py2); - } - - ctx.closePath(); - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fill(); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = EllipseCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Ellipse#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Ellipse} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var EllipseCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = EllipseCanvasRenderer; diff --git a/src/gameobjects/shape/ellipse/EllipseFactory.js b/src/gameobjects/shape/ellipse/EllipseFactory.js index 1bb925288..2fb4922ef 100644 --- a/src/gameobjects/shape/ellipse/EllipseFactory.js +++ b/src/gameobjects/shape/ellipse/EllipseFactory.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Ellipse = require('./Ellipse'); -var GameObjectFactory = require('../../GameObjectFactory'); - -/** - * Creates a new Ellipse Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Ellipse Game Object has been built into Phaser. - * - * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. - * If the width and height match it will render as a circle. If the width is less than the height, - * it will look more like an egg shape. - * - * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - * - * @method Phaser.GameObjects.GameObjectFactory#ellipse - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the ellipse. An ellipse with equal width and height renders as a circle. - * @param {number} [height=128] - The height of the ellipse. An ellipse with equal width and height renders as a circle. - * @param {number} [fillColor] - The color the ellipse will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Ellipse} The Game Object that was created. - */ -GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, fillAlpha) -{ - return this.displayList.add(new Ellipse(this.scene, x, y, width, height, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Ellipse = require('./Ellipse'); +var GameObjectFactory = require('../../GameObjectFactory'); + +/** + * Creates a new Ellipse Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Ellipse Game Object has been built into Phaser. + * + * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. + * If the width and height match it will render as a circle. If the width is less than the height, + * it will look more like an egg shape. + * + * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * + * @method Phaser.GameObjects.GameObjectFactory#ellipse + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [height=128] - The height of the ellipse. An ellipse with equal width and height renders as a circle. + * @param {number} [fillColor] - The color the ellipse will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Ellipse} The Game Object that was created. + */ +GameObjectFactory.register('ellipse', function (x, y, width, height, fillColor, fillAlpha) +{ + return this.displayList.add(new Ellipse(this.scene, x, y, width, height, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/ellipse/EllipseRender.js b/src/gameobjects/shape/ellipse/EllipseRender.js index 4dccf0998..431ee1d01 100644 --- a/src/gameobjects/shape/ellipse/EllipseRender.js +++ b/src/gameobjects/shape/ellipse/EllipseRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./EllipseWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./EllipseCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./EllipseWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./EllipseCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/ellipse/EllipseWebGLRenderer.js b/src/gameobjects/shape/ellipse/EllipseWebGLRenderer.js index df8b51272..2e3cabab5 100644 --- a/src/gameobjects/shape/ellipse/EllipseWebGLRenderer.js +++ b/src/gameobjects/shape/ellipse/EllipseWebGLRenderer.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillPathWebGL = require('../FillPathWebGL'); -var StrokePathWebGL = require('../StrokePathWebGL'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Ellipse#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Ellipse} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var EllipseWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = EllipseWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = require('../FillPathWebGL'); +var StrokePathWebGL = require('../StrokePathWebGL'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Ellipse#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Ellipse} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var EllipseWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = EllipseWebGLRenderer; diff --git a/src/gameobjects/shape/grid/Grid.js b/src/gameobjects/shape/grid/Grid.js index f4f1cfd5d..a858eb3a2 100644 --- a/src/gameobjects/shape/grid/Grid.js +++ b/src/gameobjects/shape/grid/Grid.js @@ -1,276 +1,276 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Shape = require('../Shape'); -var GridRender = require('./GridRender'); - -/** - * @classdesc - * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * A Grid Shape allows you to display a grid in your game, where you can control the size of the - * grid as well as the width and height of the grid cells. You can set a fill color for each grid - * cell as well as an alternate fill color. When the alternate fill color is set then the grid - * cells will alternate the fill colors as they render, creating a chess-board effect. You can - * also optionally have an outline fill color. If set, this draws lines between the grid cells - * in the given color. If you specify an outline color with an alpha of zero, then it will draw - * the cells spaced out, but without the lines between them. - * - * @class Grid - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the grid. - * @param {number} [height=128] - The height of the grid. - * @param {number} [cellWidth=32] - The width of one cell in the grid. - * @param {number} [cellHeight=32] - The height of one cell in the grid. - * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * @param {number} [outlineFillColor] - The color of the lines between the grid cells. See the `setOutline` method. - * @param {number} [outlineFillAlpha] - The alpha of the lines between the grid cells. - */ -var Grid = new Class({ - - Extends: Shape, - - Mixins: [ - GridRender - ], - - initialize: - - function Grid (scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 128; } - if (height === undefined) { height = 128; } - if (cellWidth === undefined) { cellWidth = 32; } - if (cellHeight === undefined) { cellHeight = 32; } - - Shape.call(this, scene, 'Grid', null); - - /** - * The width of each grid cell. - * Must be a positive value. - * - * @name Phaser.GameObjects.Grid#cellWidth - * @type {number} - * @since 3.13.0 - */ - this.cellWidth = cellWidth; - - /** - * The height of each grid cell. - * Must be a positive value. - * - * @name Phaser.GameObjects.Grid#cellHeight - * @type {number} - * @since 3.13.0 - */ - this.cellHeight = cellHeight; - - /** - * Will the grid render its cells in the `fillColor`? - * - * @name Phaser.GameObjects.Grid#showCells - * @type {boolean} - * @since 3.13.0 - */ - this.showCells = true; - - /** - * The color of the lines between each grid cell. - * - * @name Phaser.GameObjects.Grid#outlineFillColor - * @type {number} - * @since 3.13.0 - */ - this.outlineFillColor = 0; - - /** - * The alpha value for the color of the lines between each grid cell. - * - * @name Phaser.GameObjects.Grid#outlineFillAlpha - * @type {number} - * @since 3.13.0 - */ - this.outlineFillAlpha = 0; - - /** - * Will the grid display the lines between each cell when it renders? - * - * @name Phaser.GameObjects.Grid#showOutline - * @type {boolean} - * @since 3.13.0 - */ - this.showOutline = true; - - /** - * Will the grid render the alternating cells in the `altFillColor`? - * - * @name Phaser.GameObjects.Grid#showAltCells - * @type {boolean} - * @since 3.13.0 - */ - this.showAltCells = false; - - /** - * The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. - * - * @name Phaser.GameObjects.Grid#altFillColor - * @type {number} - * @since 3.13.0 - */ - this.altFillColor; - - /** - * The alpha the alternating grid cells will be filled with. - * You can also set the alpha of the overall Shape using its `alpha` property. - * - * @name Phaser.GameObjects.Grid#altFillAlpha - * @type {number} - * @since 3.13.0 - */ - this.altFillAlpha; - - this.setPosition(x, y); - this.setSize(width, height); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - if (outlineFillColor !== undefined) - { - this.setOutlineStyle(outlineFillColor, outlineFillAlpha); - } - - this.updateDisplayOrigin(); - }, - - /** - * Sets the fill color and alpha level the grid cells will use when rendering. - * - * If this method is called with no values then the grid cells will not be rendered, - * however the grid lines and alternating cells may still be. - * - * Also see the `setOutlineStyle` and `setAltFillStyle` methods. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Grid#setFillStyle - * @since 3.13.0 - * - * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha=1] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {this} This Game Object instance. - */ - setFillStyle: function (fillColor, fillAlpha) - { - if (fillAlpha === undefined) { fillAlpha = 1; } - - if (fillColor === undefined) - { - this.showCells = false; - } - else - { - this.fillColor = fillColor; - this.fillAlpha = fillAlpha; - this.showCells = true; - } - - return this; - }, - - /** - * Sets the fill color and alpha level that the alternating grid cells will use. - * - * If this method is called with no values then alternating grid cells will not be rendered in a different color. - * - * Also see the `setOutlineStyle` and `setFillStyle` methods. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Grid#setAltFillStyle - * @since 3.13.0 - * - * @param {number} [fillColor] - The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha=1] - The alpha the alternating grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {this} This Game Object instance. - */ - setAltFillStyle: function (fillColor, fillAlpha) - { - if (fillAlpha === undefined) { fillAlpha = 1; } - - if (fillColor === undefined) - { - this.showAltCells = false; - } - else - { - this.altFillColor = fillColor; - this.altFillAlpha = fillAlpha; - this.showAltCells = true; - } - - return this; - }, - - /** - * Sets the fill color and alpha level that the lines between each grid cell will use. - * - * If this method is called with no values then the grid lines will not be rendered at all, however - * the cells themselves may still be if they have colors set. - * - * Also see the `setFillStyle` and `setAltFillStyle` methods. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Grid#setOutlineStyle - * @since 3.13.0 - * - * @param {number} [fillColor] - The color the lines between the grid cells will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha=1] - The alpha the lines between the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {this} This Game Object instance. - */ - setOutlineStyle: function (fillColor, fillAlpha) - { - if (fillAlpha === undefined) { fillAlpha = 1; } - - if (fillColor === undefined) - { - this.showOutline = false; - } - else - { - this.outlineFillColor = fillColor; - this.outlineFillAlpha = fillAlpha; - this.showOutline = true; - } - - return this; - } - -}); - -module.exports = Grid; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Shape = require('../Shape'); +var GridRender = require('./GridRender'); + +/** + * @classdesc + * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * A Grid Shape allows you to display a grid in your game, where you can control the size of the + * grid as well as the width and height of the grid cells. You can set a fill color for each grid + * cell as well as an alternate fill color. When the alternate fill color is set then the grid + * cells will alternate the fill colors as they render, creating a chess-board effect. You can + * also optionally have an outline fill color. If set, this draws lines between the grid cells + * in the given color. If you specify an outline color with an alpha of zero, then it will draw + * the cells spaced out, but without the lines between them. + * + * @class Grid + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the grid. + * @param {number} [height=128] - The height of the grid. + * @param {number} [cellWidth=32] - The width of one cell in the grid. + * @param {number} [cellHeight=32] - The height of one cell in the grid. + * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * @param {number} [outlineFillColor] - The color of the lines between the grid cells. See the `setOutline` method. + * @param {number} [outlineFillAlpha] - The alpha of the lines between the grid cells. + */ +var Grid = new Class({ + + Extends: Shape, + + Mixins: [ + GridRender + ], + + initialize: + + function Grid (scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + if (cellWidth === undefined) { cellWidth = 32; } + if (cellHeight === undefined) { cellHeight = 32; } + + Shape.call(this, scene, 'Grid', null); + + /** + * The width of each grid cell. + * Must be a positive value. + * + * @name Phaser.GameObjects.Grid#cellWidth + * @type {number} + * @since 3.13.0 + */ + this.cellWidth = cellWidth; + + /** + * The height of each grid cell. + * Must be a positive value. + * + * @name Phaser.GameObjects.Grid#cellHeight + * @type {number} + * @since 3.13.0 + */ + this.cellHeight = cellHeight; + + /** + * Will the grid render its cells in the `fillColor`? + * + * @name Phaser.GameObjects.Grid#showCells + * @type {boolean} + * @since 3.13.0 + */ + this.showCells = true; + + /** + * The color of the lines between each grid cell. + * + * @name Phaser.GameObjects.Grid#outlineFillColor + * @type {number} + * @since 3.13.0 + */ + this.outlineFillColor = 0; + + /** + * The alpha value for the color of the lines between each grid cell. + * + * @name Phaser.GameObjects.Grid#outlineFillAlpha + * @type {number} + * @since 3.13.0 + */ + this.outlineFillAlpha = 0; + + /** + * Will the grid display the lines between each cell when it renders? + * + * @name Phaser.GameObjects.Grid#showOutline + * @type {boolean} + * @since 3.13.0 + */ + this.showOutline = true; + + /** + * Will the grid render the alternating cells in the `altFillColor`? + * + * @name Phaser.GameObjects.Grid#showAltCells + * @type {boolean} + * @since 3.13.0 + */ + this.showAltCells = false; + + /** + * The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. + * + * @name Phaser.GameObjects.Grid#altFillColor + * @type {number} + * @since 3.13.0 + */ + this.altFillColor; + + /** + * The alpha the alternating grid cells will be filled with. + * You can also set the alpha of the overall Shape using its `alpha` property. + * + * @name Phaser.GameObjects.Grid#altFillAlpha + * @type {number} + * @since 3.13.0 + */ + this.altFillAlpha; + + this.setPosition(x, y); + this.setSize(width, height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + if (outlineFillColor !== undefined) + { + this.setOutlineStyle(outlineFillColor, outlineFillAlpha); + } + + this.updateDisplayOrigin(); + }, + + /** + * Sets the fill color and alpha level the grid cells will use when rendering. + * + * If this method is called with no values then the grid cells will not be rendered, + * however the grid lines and alternating cells may still be. + * + * Also see the `setOutlineStyle` and `setAltFillStyle` methods. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Grid#setFillStyle + * @since 3.13.0 + * + * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha=1] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (fillColor, fillAlpha) + { + if (fillAlpha === undefined) { fillAlpha = 1; } + + if (fillColor === undefined) + { + this.showCells = false; + } + else + { + this.fillColor = fillColor; + this.fillAlpha = fillAlpha; + this.showCells = true; + } + + return this; + }, + + /** + * Sets the fill color and alpha level that the alternating grid cells will use. + * + * If this method is called with no values then alternating grid cells will not be rendered in a different color. + * + * Also see the `setOutlineStyle` and `setFillStyle` methods. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Grid#setAltFillStyle + * @since 3.13.0 + * + * @param {number} [fillColor] - The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha=1] - The alpha the alternating grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {this} This Game Object instance. + */ + setAltFillStyle: function (fillColor, fillAlpha) + { + if (fillAlpha === undefined) { fillAlpha = 1; } + + if (fillColor === undefined) + { + this.showAltCells = false; + } + else + { + this.altFillColor = fillColor; + this.altFillAlpha = fillAlpha; + this.showAltCells = true; + } + + return this; + }, + + /** + * Sets the fill color and alpha level that the lines between each grid cell will use. + * + * If this method is called with no values then the grid lines will not be rendered at all, however + * the cells themselves may still be if they have colors set. + * + * Also see the `setFillStyle` and `setAltFillStyle` methods. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Grid#setOutlineStyle + * @since 3.13.0 + * + * @param {number} [fillColor] - The color the lines between the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha=1] - The alpha the lines between the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {this} This Game Object instance. + */ + setOutlineStyle: function (fillColor, fillAlpha) + { + if (fillAlpha === undefined) { fillAlpha = 1; } + + if (fillColor === undefined) + { + this.showOutline = false; + } + else + { + this.outlineFillColor = fillColor; + this.outlineFillAlpha = fillAlpha; + this.showOutline = true; + } + + return this; + } + +}); + +module.exports = Grid; diff --git a/src/gameobjects/shape/grid/GridCanvasRenderer.js b/src/gameobjects/shape/grid/GridCanvasRenderer.js index c797aebd7..768aab741 100644 --- a/src/gameobjects/shape/grid/GridCanvasRenderer.js +++ b/src/gameobjects/shape/grid/GridCanvasRenderer.js @@ -1,183 +1,183 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Grid#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Grid} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var GridCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = -src._displayOriginX; - var dy = -src._displayOriginY; - - var alpha = camera.alpha * src.alpha; - - // Work out the grid size - - var width = src.width; - var height = src.height; - - var cellWidth = src.cellWidth; - var cellHeight = src.cellHeight; - - var gridWidth = Math.ceil(width / cellWidth); - var gridHeight = Math.ceil(height / cellHeight); - - var cellWidthA = cellWidth; - var cellHeightA = cellHeight; - - var cellWidthB = cellWidth - ((gridWidth * cellWidth) - width); - var cellHeightB = cellHeight - ((gridHeight * cellHeight) - height); - - var showCells = src.showCells; - var showAltCells = src.showAltCells; - var showOutline = src.showOutline; - - var x = 0; - var y = 0; - var r = 0; - var cw = 0; - var ch = 0; - - if (showOutline) - { - // To make room for the grid lines (in case alpha < 1) - cellWidthA--; - cellHeightA--; - - if (cellWidthB === cellWidth) - { - cellWidthB--; - } - - if (cellHeightB === cellHeight) - { - cellHeightB--; - } - } - - if (showCells && src.fillAlpha > 0) - { - FillStyleCanvas(ctx, src); - - for (y = 0; y < gridHeight; y++) - { - if (showAltCells) - { - r = y % 2; - } - - for (x = 0; x < gridWidth; x++) - { - if (showAltCells && r) - { - r = 0; - continue; - } - - r++; - - cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; - ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; - - ctx.fillRect( - dx + x * cellWidth, - dy + y * cellHeight, - cw, - ch - ); - } - } - } - - if (showAltCells && src.altFillAlpha > 0) - { - FillStyleCanvas(ctx, src, src.altFillColor, src.altFillAlpha * alpha); - - for (y = 0; y < gridHeight; y++) - { - if (showAltCells) - { - r = y % 2; - } - - for (x = 0; x < gridWidth; x++) - { - if (showAltCells && !r) - { - r = 1; - continue; - } - - r = 0; - - cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; - ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; - - ctx.fillRect( - dx + x * cellWidth, - dy + y * cellHeight, - cw, - ch - ); - } - } - } - - if (showOutline && src.outlineFillAlpha > 0) - { - LineStyleCanvas(ctx, src, src.outlineFillColor, src.outlineFillAlpha * alpha); - - for (x = 1; x < gridWidth; x++) - { - var x1 = x * cellWidth; - - ctx.beginPath(); - - ctx.moveTo(x1 + dx, dy); - ctx.lineTo(x1 + dx, height + dy); - - ctx.stroke(); - } - - for (y = 1; y < gridHeight; y++) - { - var y1 = y * cellHeight; - - ctx.beginPath(); - - ctx.moveTo(dx, y1 + dy); - ctx.lineTo(dx + width, y1 + dy); - - ctx.stroke(); - } - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = GridCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Grid#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Grid} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var GridCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = -src._displayOriginX; + var dy = -src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + // Work out the grid size + + var width = src.width; + var height = src.height; + + var cellWidth = src.cellWidth; + var cellHeight = src.cellHeight; + + var gridWidth = Math.ceil(width / cellWidth); + var gridHeight = Math.ceil(height / cellHeight); + + var cellWidthA = cellWidth; + var cellHeightA = cellHeight; + + var cellWidthB = cellWidth - ((gridWidth * cellWidth) - width); + var cellHeightB = cellHeight - ((gridHeight * cellHeight) - height); + + var showCells = src.showCells; + var showAltCells = src.showAltCells; + var showOutline = src.showOutline; + + var x = 0; + var y = 0; + var r = 0; + var cw = 0; + var ch = 0; + + if (showOutline) + { + // To make room for the grid lines (in case alpha < 1) + cellWidthA--; + cellHeightA--; + + if (cellWidthB === cellWidth) + { + cellWidthB--; + } + + if (cellHeightB === cellHeight) + { + cellHeightB--; + } + } + + if (showCells && src.fillAlpha > 0) + { + FillStyleCanvas(ctx, src); + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && r) + { + r = 0; + continue; + } + + r++; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + ctx.fillRect( + dx + x * cellWidth, + dy + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showAltCells && src.altFillAlpha > 0) + { + FillStyleCanvas(ctx, src, src.altFillColor, src.altFillAlpha * alpha); + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && !r) + { + r = 1; + continue; + } + + r = 0; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + ctx.fillRect( + dx + x * cellWidth, + dy + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showOutline && src.outlineFillAlpha > 0) + { + LineStyleCanvas(ctx, src, src.outlineFillColor, src.outlineFillAlpha * alpha); + + for (x = 1; x < gridWidth; x++) + { + var x1 = x * cellWidth; + + ctx.beginPath(); + + ctx.moveTo(x1 + dx, dy); + ctx.lineTo(x1 + dx, height + dy); + + ctx.stroke(); + } + + for (y = 1; y < gridHeight; y++) + { + var y1 = y * cellHeight; + + ctx.beginPath(); + + ctx.moveTo(dx, y1 + dy); + ctx.lineTo(dx + width, y1 + dy); + + ctx.stroke(); + } + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = GridCanvasRenderer; diff --git a/src/gameobjects/shape/grid/GridFactory.js b/src/gameobjects/shape/grid/GridFactory.js index 45932f6b6..2fc28cccb 100644 --- a/src/gameobjects/shape/grid/GridFactory.js +++ b/src/gameobjects/shape/grid/GridFactory.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var Grid = require('./Grid'); - -/** - * Creates a new Grid Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Grid Game Object has been built into Phaser. - * - * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * A Grid Shape allows you to display a grid in your game, where you can control the size of the - * grid as well as the width and height of the grid cells. You can set a fill color for each grid - * cell as well as an alternate fill color. When the alternate fill color is set then the grid - * cells will alternate the fill colors as they render, creating a chess-board effect. You can - * also optionally have an outline fill color. If set, this draws lines between the grid cells - * in the given color. If you specify an outline color with an alpha of zero, then it will draw - * the cells spaced out, but without the lines between them. - * - * @method Phaser.GameObjects.GameObjectFactory#grid - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the grid. - * @param {number} [height=128] - The height of the grid. - * @param {number} [cellWidth=32] - The width of one cell in the grid. - * @param {number} [cellHeight=32] - The height of one cell in the grid. - * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * @param {number} [outlineFillColor] - The color of the lines between the grid cells. - * @param {number} [outlineFillAlpha] - The alpha of the lines between the grid cells. - * - * @return {Phaser.GameObjects.Grid} The Game Object that was created. - */ -GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) -{ - return this.displayList.add(new Grid(this.scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var Grid = require('./Grid'); + +/** + * Creates a new Grid Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Grid Game Object has been built into Phaser. + * + * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * A Grid Shape allows you to display a grid in your game, where you can control the size of the + * grid as well as the width and height of the grid cells. You can set a fill color for each grid + * cell as well as an alternate fill color. When the alternate fill color is set then the grid + * cells will alternate the fill colors as they render, creating a chess-board effect. You can + * also optionally have an outline fill color. If set, this draws lines between the grid cells + * in the given color. If you specify an outline color with an alpha of zero, then it will draw + * the cells spaced out, but without the lines between them. + * + * @method Phaser.GameObjects.GameObjectFactory#grid + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the grid. + * @param {number} [height=128] - The height of the grid. + * @param {number} [cellWidth=32] - The width of one cell in the grid. + * @param {number} [cellHeight=32] - The height of one cell in the grid. + * @param {number} [fillColor] - The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * @param {number} [outlineFillColor] - The color of the lines between the grid cells. + * @param {number} [outlineFillAlpha] - The alpha of the lines between the grid cells. + * + * @return {Phaser.GameObjects.Grid} The Game Object that was created. + */ +GameObjectFactory.register('grid', function (x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) +{ + return this.displayList.add(new Grid(this.scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha)); +}); diff --git a/src/gameobjects/shape/grid/GridRender.js b/src/gameobjects/shape/grid/GridRender.js index a66a60549..b418df046 100644 --- a/src/gameobjects/shape/grid/GridRender.js +++ b/src/gameobjects/shape/grid/GridRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./GridWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./GridCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./GridWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./GridCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/grid/GridWebGLRenderer.js b/src/gameobjects/shape/grid/GridWebGLRenderer.js index ed26fa305..0d595f532 100644 --- a/src/gameobjects/shape/grid/GridWebGLRenderer.js +++ b/src/gameobjects/shape/grid/GridWebGLRenderer.js @@ -1,220 +1,220 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Grid#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Grid} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var GridWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - calcMatrix.translate(-src._displayOriginX, -src._displayOriginY); - - var alpha = camera.alpha * src.alpha; - - // Work out the grid size - - var width = src.width; - var height = src.height; - - var cellWidth = src.cellWidth; - var cellHeight = src.cellHeight; - - var gridWidth = Math.ceil(width / cellWidth); - var gridHeight = Math.ceil(height / cellHeight); - - var cellWidthA = cellWidth; - var cellHeightA = cellHeight; - - var cellWidthB = cellWidth - ((gridWidth * cellWidth) - width); - var cellHeightB = cellHeight - ((gridHeight * cellHeight) - height); - - var fillTint; - var fillTintColor; - - var showCells = src.showCells; - var showAltCells = src.showAltCells; - var showOutline = src.showOutline; - - var x = 0; - var y = 0; - var r = 0; - var cw = 0; - var ch = 0; - - if (showOutline) - { - // To make room for the grid lines (in case alpha < 1) - cellWidthA--; - cellHeightA--; - - if (cellWidthB === cellWidth) - { - cellWidthB--; - } - - if (cellHeightB === cellHeight) - { - cellHeightB--; - } - } - - if (showCells && src.fillAlpha > 0) - { - fillTint = pipeline.fillTint; - fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); - - fillTint.TL = fillTintColor; - fillTint.TR = fillTintColor; - fillTint.BL = fillTintColor; - fillTint.BR = fillTintColor; - - for (y = 0; y < gridHeight; y++) - { - if (showAltCells) - { - r = y % 2; - } - - for (x = 0; x < gridWidth; x++) - { - if (showAltCells && r) - { - r = 0; - continue; - } - - r++; - - cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; - ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; - - pipeline.setTexture2D(); - - pipeline.batchFillRect( - x * cellWidth, - y * cellHeight, - cw, - ch - ); - } - } - } - - if (showAltCells && src.altFillAlpha > 0) - { - fillTint = pipeline.fillTint; - fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.altFillColor, src.altFillAlpha * alpha); - - fillTint.TL = fillTintColor; - fillTint.TR = fillTintColor; - fillTint.BL = fillTintColor; - fillTint.BR = fillTintColor; - - for (y = 0; y < gridHeight; y++) - { - if (showAltCells) - { - r = y % 2; - } - - for (x = 0; x < gridWidth; x++) - { - if (showAltCells && !r) - { - r = 1; - continue; - } - - r = 0; - - cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; - ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; - - pipeline.setTexture2D(); - - pipeline.batchFillRect( - x * cellWidth, - y * cellHeight, - cw, - ch - ); - } - } - } - - if (showOutline && src.outlineFillAlpha > 0) - { - var strokeTint = pipeline.strokeTint; - var color = Utils.getTintAppendFloatAlphaAndSwap(src.outlineFillColor, src.outlineFillAlpha * alpha); - - strokeTint.TL = color; - strokeTint.TR = color; - strokeTint.BL = color; - strokeTint.BR = color; - - for (x = 1; x < gridWidth; x++) - { - var x1 = x * cellWidth; - - pipeline.setTexture2D(); - - pipeline.batchLine(x1, 0, x1, height, 1, 1, 1, 0, false); - } - - for (y = 1; y < gridHeight; y++) - { - var y1 = y * cellHeight; - - pipeline.setTexture2D(); - - pipeline.batchLine(0, y1, width, y1, 1, 1, 1, 0, false); - } - } -}; - -module.exports = GridWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Grid#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Grid} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var GridWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + calcMatrix.translate(-src._displayOriginX, -src._displayOriginY); + + var alpha = camera.alpha * src.alpha; + + // Work out the grid size + + var width = src.width; + var height = src.height; + + var cellWidth = src.cellWidth; + var cellHeight = src.cellHeight; + + var gridWidth = Math.ceil(width / cellWidth); + var gridHeight = Math.ceil(height / cellHeight); + + var cellWidthA = cellWidth; + var cellHeightA = cellHeight; + + var cellWidthB = cellWidth - ((gridWidth * cellWidth) - width); + var cellHeightB = cellHeight - ((gridHeight * cellHeight) - height); + + var fillTint; + var fillTintColor; + + var showCells = src.showCells; + var showAltCells = src.showAltCells; + var showOutline = src.showOutline; + + var x = 0; + var y = 0; + var r = 0; + var cw = 0; + var ch = 0; + + if (showOutline) + { + // To make room for the grid lines (in case alpha < 1) + cellWidthA--; + cellHeightA--; + + if (cellWidthB === cellWidth) + { + cellWidthB--; + } + + if (cellHeightB === cellHeight) + { + cellHeightB--; + } + } + + if (showCells && src.fillAlpha > 0) + { + fillTint = pipeline.fillTint; + fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && r) + { + r = 0; + continue; + } + + r++; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + pipeline.setTexture2D(); + + pipeline.batchFillRect( + x * cellWidth, + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showAltCells && src.altFillAlpha > 0) + { + fillTint = pipeline.fillTint; + fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.altFillColor, src.altFillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + for (y = 0; y < gridHeight; y++) + { + if (showAltCells) + { + r = y % 2; + } + + for (x = 0; x < gridWidth; x++) + { + if (showAltCells && !r) + { + r = 1; + continue; + } + + r = 0; + + cw = (x < gridWidth - 1) ? cellWidthA : cellWidthB; + ch = (y < gridHeight - 1) ? cellHeightA : cellHeightB; + + pipeline.setTexture2D(); + + pipeline.batchFillRect( + x * cellWidth, + y * cellHeight, + cw, + ch + ); + } + } + } + + if (showOutline && src.outlineFillAlpha > 0) + { + var strokeTint = pipeline.strokeTint; + var color = Utils.getTintAppendFloatAlphaAndSwap(src.outlineFillColor, src.outlineFillAlpha * alpha); + + strokeTint.TL = color; + strokeTint.TR = color; + strokeTint.BL = color; + strokeTint.BR = color; + + for (x = 1; x < gridWidth; x++) + { + var x1 = x * cellWidth; + + pipeline.setTexture2D(); + + pipeline.batchLine(x1, 0, x1, height, 1, 1, 1, 0, false); + } + + for (y = 1; y < gridHeight; y++) + { + var y1 = y * cellHeight; + + pipeline.setTexture2D(); + + pipeline.batchLine(0, y1, width, y1, 1, 1, 1, 0, false); + } + } +}; + +module.exports = GridWebGLRenderer; diff --git a/src/gameobjects/shape/isobox/IsoBox.js b/src/gameobjects/shape/isobox/IsoBox.js index 8e6bd80e3..014dffcab 100644 --- a/src/gameobjects/shape/isobox/IsoBox.js +++ b/src/gameobjects/shape/isobox/IsoBox.js @@ -1,209 +1,209 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var IsoBoxRender = require('./IsoBoxRender'); -var Class = require('../../../utils/Class'); -var Shape = require('../Shape'); - -/** - * @classdesc - * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set - * the color of the top, left and right faces of the rectangle respectively. You can also choose - * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting - * the `projection` property. - * - * @class IsoBox - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [size=48] - The width of the iso box in pixels. The left and right faces will be exactly half this value. - * @param {number} [height=32] - The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. - * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso box. - * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso box. - * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso box. - */ -var IsoBox = new Class({ - - Extends: Shape, - - Mixins: [ - IsoBoxRender - ], - - initialize: - - function IsoBox (scene, x, y, size, height, fillTop, fillLeft, fillRight) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (size === undefined) { size = 48; } - if (height === undefined) { height = 32; } - if (fillTop === undefined) { fillTop = 0xeeeeee; } - if (fillLeft === undefined) { fillLeft = 0x999999; } - if (fillRight === undefined) { fillRight = 0xcccccc; } - - Shape.call(this, scene, 'IsoBox', null); - - /** - * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. - * - * @name Phaser.GameObjects.IsoBox#projection - * @type {integer} - * @default 4 - * @since 3.13.0 - */ - this.projection = 4; - - /** - * The color used to fill in the top of the iso box. - * - * @name Phaser.GameObjects.IsoBox#fillTop - * @type {number} - * @since 3.13.0 - */ - this.fillTop = fillTop; - - /** - * The color used to fill in the left-facing side of the iso box. - * - * @name Phaser.GameObjects.IsoBox#fillLeft - * @type {number} - * @since 3.13.0 - */ - this.fillLeft = fillLeft; - - /** - * The color used to fill in the right-facing side of the iso box. - * - * @name Phaser.GameObjects.IsoBox#fillRight - * @type {number} - * @since 3.13.0 - */ - this.fillRight = fillRight; - - /** - * Controls if the top-face of the iso box be rendered. - * - * @name Phaser.GameObjects.IsoBox#showTop - * @type {boolean} - * @default true - * @since 3.13.0 - */ - this.showTop = true; - - /** - * Controls if the left-face of the iso box be rendered. - * - * @name Phaser.GameObjects.IsoBox#showLeft - * @type {boolean} - * @default true - * @since 3.13.0 - */ - this.showLeft = true; - - /** - * Controls if the right-face of the iso box be rendered. - * - * @name Phaser.GameObjects.IsoBox#showRight - * @type {boolean} - * @default true - * @since 3.13.0 - */ - this.showRight = true; - - this.isFilled = true; - - this.setPosition(x, y); - this.setSize(size, height); - - this.updateDisplayOrigin(); - }, - - /** - * Sets the projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoBox#setProjection - * @since 3.13.0 - * - * @param {integer} value - The value to set the projection to. - * - * @return {this} This Game Object instance. - */ - setProjection: function (value) - { - this.projection = value; - - return this; - }, - - /** - * Sets which faces of the iso box will be rendered. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoBox#setFaces - * @since 3.13.0 - * - * @param {boolean} [showTop=true] - Show the top-face of the iso box. - * @param {boolean} [showLeft=true] - Show the left-face of the iso box. - * @param {boolean} [showRight=true] - Show the right-face of the iso box. - * - * @return {this} This Game Object instance. - */ - setFaces: function (showTop, showLeft, showRight) - { - if (showTop === undefined) { showTop = true; } - if (showLeft === undefined) { showLeft = true; } - if (showRight === undefined) { showRight = true; } - - this.showTop = showTop; - this.showLeft = showLeft; - this.showRight = showRight; - - return this; - }, - - /** - * Sets the fill colors for each face of the iso box. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoBox#setFillStyle - * @since 3.13.0 - * - * @param {number} [fillTop] - The color used to fill the top of the iso box. - * @param {number} [fillLeft] - The color used to fill in the left-facing side of the iso box. - * @param {number} [fillRight] - The color used to fill in the right-facing side of the iso box. - * - * @return {this} This Game Object instance. - */ - setFillStyle: function (fillTop, fillLeft, fillRight) - { - this.fillTop = fillTop; - this.fillLeft = fillLeft; - this.fillRight = fillRight; - - this.isFilled = true; - - return this; - } - -}); - -module.exports = IsoBox; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsoBoxRender = require('./IsoBoxRender'); +var Class = require('../../../utils/Class'); +var Shape = require('../Shape'); + +/** + * @classdesc + * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set + * the color of the top, left and right faces of the rectangle respectively. You can also choose + * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting + * the `projection` property. + * + * @class IsoBox + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso box in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso box. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso box. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso box. + */ +var IsoBox = new Class({ + + Extends: Shape, + + Mixins: [ + IsoBoxRender + ], + + initialize: + + function IsoBox (scene, x, y, size, height, fillTop, fillLeft, fillRight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (size === undefined) { size = 48; } + if (height === undefined) { height = 32; } + if (fillTop === undefined) { fillTop = 0xeeeeee; } + if (fillLeft === undefined) { fillLeft = 0x999999; } + if (fillRight === undefined) { fillRight = 0xcccccc; } + + Shape.call(this, scene, 'IsoBox', null); + + /** + * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * + * @name Phaser.GameObjects.IsoBox#projection + * @type {integer} + * @default 4 + * @since 3.13.0 + */ + this.projection = 4; + + /** + * The color used to fill in the top of the iso box. + * + * @name Phaser.GameObjects.IsoBox#fillTop + * @type {number} + * @since 3.13.0 + */ + this.fillTop = fillTop; + + /** + * The color used to fill in the left-facing side of the iso box. + * + * @name Phaser.GameObjects.IsoBox#fillLeft + * @type {number} + * @since 3.13.0 + */ + this.fillLeft = fillLeft; + + /** + * The color used to fill in the right-facing side of the iso box. + * + * @name Phaser.GameObjects.IsoBox#fillRight + * @type {number} + * @since 3.13.0 + */ + this.fillRight = fillRight; + + /** + * Controls if the top-face of the iso box be rendered. + * + * @name Phaser.GameObjects.IsoBox#showTop + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showTop = true; + + /** + * Controls if the left-face of the iso box be rendered. + * + * @name Phaser.GameObjects.IsoBox#showLeft + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showLeft = true; + + /** + * Controls if the right-face of the iso box be rendered. + * + * @name Phaser.GameObjects.IsoBox#showRight + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showRight = true; + + this.isFilled = true; + + this.setPosition(x, y); + this.setSize(size, height); + + this.updateDisplayOrigin(); + }, + + /** + * Sets the projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoBox#setProjection + * @since 3.13.0 + * + * @param {integer} value - The value to set the projection to. + * + * @return {this} This Game Object instance. + */ + setProjection: function (value) + { + this.projection = value; + + return this; + }, + + /** + * Sets which faces of the iso box will be rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoBox#setFaces + * @since 3.13.0 + * + * @param {boolean} [showTop=true] - Show the top-face of the iso box. + * @param {boolean} [showLeft=true] - Show the left-face of the iso box. + * @param {boolean} [showRight=true] - Show the right-face of the iso box. + * + * @return {this} This Game Object instance. + */ + setFaces: function (showTop, showLeft, showRight) + { + if (showTop === undefined) { showTop = true; } + if (showLeft === undefined) { showLeft = true; } + if (showRight === undefined) { showRight = true; } + + this.showTop = showTop; + this.showLeft = showLeft; + this.showRight = showRight; + + return this; + }, + + /** + * Sets the fill colors for each face of the iso box. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoBox#setFillStyle + * @since 3.13.0 + * + * @param {number} [fillTop] - The color used to fill the top of the iso box. + * @param {number} [fillLeft] - The color used to fill in the left-facing side of the iso box. + * @param {number} [fillRight] - The color used to fill in the right-facing side of the iso box. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (fillTop, fillLeft, fillRight) + { + this.fillTop = fillTop; + this.fillLeft = fillLeft; + this.fillRight = fillRight; + + this.isFilled = true; + + return this; + } + +}); + +module.exports = IsoBox; diff --git a/src/gameobjects/shape/isobox/IsoBoxCanvasRenderer.js b/src/gameobjects/shape/isobox/IsoBoxCanvasRenderer.js index 651da129e..0ecc3de81 100644 --- a/src/gameobjects/shape/isobox/IsoBoxCanvasRenderer.js +++ b/src/gameobjects/shape/isobox/IsoBoxCanvasRenderer.js @@ -1,95 +1,95 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.IsoBox#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.IsoBox} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var IsoBoxCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) - { - var size = src.width; - var height = src.height; - - var sizeA = size / 2; - var sizeB = size / src.projection; - - // Top Face - - if (src.showTop) - { - FillStyleCanvas(ctx, src, src.fillTop); - - ctx.beginPath(); - - ctx.moveTo(-sizeA, -height); - ctx.lineTo(0, -sizeB - height); - ctx.lineTo(sizeA, -height); - ctx.lineTo(sizeA, -1); - ctx.lineTo(0, sizeB - 1); - ctx.lineTo(-sizeA, -1); - ctx.lineTo(-sizeA, -height); - - ctx.fill(); - } - - // Left Face - - if (src.showLeft) - { - FillStyleCanvas(ctx, src, src.fillLeft); - - ctx.beginPath(); - - ctx.moveTo(-sizeA, 0); - ctx.lineTo(0, sizeB); - ctx.lineTo(0, sizeB - height); - ctx.lineTo(-sizeA, -height); - ctx.lineTo(-sizeA, 0); - - ctx.fill(); - } - - // Right Face - - if (src.showRight) - { - FillStyleCanvas(ctx, src, src.fillRight); - - ctx.beginPath(); - - ctx.moveTo(sizeA, 0); - ctx.lineTo(0, sizeB); - ctx.lineTo(0, sizeB - height); - ctx.lineTo(sizeA, -height); - ctx.lineTo(sizeA, 0); - - ctx.fill(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = IsoBoxCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoBox#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.IsoBox} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoBoxCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) + { + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + // Top Face + + if (src.showTop) + { + FillStyleCanvas(ctx, src, src.fillTop); + + ctx.beginPath(); + + ctx.moveTo(-sizeA, -height); + ctx.lineTo(0, -sizeB - height); + ctx.lineTo(sizeA, -height); + ctx.lineTo(sizeA, -1); + ctx.lineTo(0, sizeB - 1); + ctx.lineTo(-sizeA, -1); + ctx.lineTo(-sizeA, -height); + + ctx.fill(); + } + + // Left Face + + if (src.showLeft) + { + FillStyleCanvas(ctx, src, src.fillLeft); + + ctx.beginPath(); + + ctx.moveTo(-sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + ctx.lineTo(-sizeA, -height); + ctx.lineTo(-sizeA, 0); + + ctx.fill(); + } + + // Right Face + + if (src.showRight) + { + FillStyleCanvas(ctx, src, src.fillRight); + + ctx.beginPath(); + + ctx.moveTo(sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + ctx.lineTo(sizeA, -height); + ctx.lineTo(sizeA, 0); + + ctx.fill(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = IsoBoxCanvasRenderer; diff --git a/src/gameobjects/shape/isobox/IsoBoxFactory.js b/src/gameobjects/shape/isobox/IsoBoxFactory.js index 00a670b59..7dd8c9bfa 100644 --- a/src/gameobjects/shape/isobox/IsoBoxFactory.js +++ b/src/gameobjects/shape/isobox/IsoBoxFactory.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var IsoBox = require('./IsoBox'); - -/** - * Creates a new IsoBox Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the IsoBox Game Object has been built into Phaser. - * - * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set - * the color of the top, left and right faces of the rectangle respectively. You can also choose - * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting - * the `projection` property. - * - * @method Phaser.GameObjects.GameObjectFactory#isobox - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [size=48] - The width of the iso box in pixels. The left and right faces will be exactly half this value. - * @param {number} [height=32] - The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. - * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso box. - * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso box. - * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso box. - * - * @return {Phaser.GameObjects.IsoBox} The Game Object that was created. - */ -GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fillLeft, fillRight) -{ - return this.displayList.add(new IsoBox(this.scene, x, y, size, height, fillTop, fillLeft, fillRight)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var IsoBox = require('./IsoBox'); + +/** + * Creates a new IsoBox Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the IsoBox Game Object has been built into Phaser. + * + * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set + * the color of the top, left and right faces of the rectangle respectively. You can also choose + * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting + * the `projection` property. + * + * @method Phaser.GameObjects.GameObjectFactory#isobox + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso box in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso box. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso box. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso box. + * + * @return {Phaser.GameObjects.IsoBox} The Game Object that was created. + */ +GameObjectFactory.register('isobox', function (x, y, size, height, fillTop, fillLeft, fillRight) +{ + return this.displayList.add(new IsoBox(this.scene, x, y, size, height, fillTop, fillLeft, fillRight)); +}); diff --git a/src/gameobjects/shape/isobox/IsoBoxRender.js b/src/gameobjects/shape/isobox/IsoBoxRender.js index e057bb1c1..e051fe448 100644 --- a/src/gameobjects/shape/isobox/IsoBoxRender.js +++ b/src/gameobjects/shape/isobox/IsoBoxRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./IsoBoxWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./IsoBoxCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./IsoBoxWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./IsoBoxCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/isobox/IsoBoxWebGLRenderer.js b/src/gameobjects/shape/isobox/IsoBoxWebGLRenderer.js index 91ca1b749..03450072e 100644 --- a/src/gameobjects/shape/isobox/IsoBoxWebGLRenderer.js +++ b/src/gameobjects/shape/isobox/IsoBoxWebGLRenderer.js @@ -1,152 +1,152 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.IsoBox#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.IsoBox} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var IsoBoxWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var size = src.width; - var height = src.height; - - var sizeA = size / 2; - var sizeB = size / src.projection; - - var alpha = camera.alpha * src.alpha; - - if (!src.isFilled) - { - return; - } - - var tint; - - var x0; - var y0; - - var x1; - var y1; - - var x2; - var y2; - - var x3; - var y3; - - // Top Face - - if (src.showTop) - { - tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); - - x0 = calcMatrix.getX(-sizeA, -height); - y0 = calcMatrix.getY(-sizeA, -height); - - x1 = calcMatrix.getX(0, -sizeB - height); - y1 = calcMatrix.getY(0, -sizeB - height); - - x2 = calcMatrix.getX(sizeA, -height); - y2 = calcMatrix.getY(sizeA, -height); - - x3 = calcMatrix.getX(0, sizeB - height); - y3 = calcMatrix.getY(0, sizeB - height); - - pipeline.setTexture2D(); - - pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); - } - - // Left Face - - if (src.showLeft) - { - tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); - - x0 = calcMatrix.getX(-sizeA, 0); - y0 = calcMatrix.getY(-sizeA, 0); - - x1 = calcMatrix.getX(0, sizeB); - y1 = calcMatrix.getY(0, sizeB); - - x2 = calcMatrix.getX(0, sizeB - height); - y2 = calcMatrix.getY(0, sizeB - height); - - x3 = calcMatrix.getX(-sizeA, -height); - y3 = calcMatrix.getY(-sizeA, -height); - - pipeline.setTexture2D(); - - pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); - } - - // Right Face - - if (src.showRight) - { - tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); - - x0 = calcMatrix.getX(sizeA, 0); - y0 = calcMatrix.getY(sizeA, 0); - - x1 = calcMatrix.getX(0, sizeB); - y1 = calcMatrix.getY(0, sizeB); - - x2 = calcMatrix.getX(0, sizeB - height); - y2 = calcMatrix.getY(0, sizeB - height); - - x3 = calcMatrix.getX(sizeA, -height); - y3 = calcMatrix.getY(sizeA, -height); - - pipeline.setTexture2D(); - - pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); - } -}; - -module.exports = IsoBoxWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoBox#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.IsoBox} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoBoxWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + var alpha = camera.alpha * src.alpha; + + if (!src.isFilled) + { + return; + } + + var tint; + + var x0; + var y0; + + var x1; + var y1; + + var x2; + var y2; + + var x3; + var y3; + + // Top Face + + if (src.showTop) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); + + x0 = calcMatrix.getX(-sizeA, -height); + y0 = calcMatrix.getY(-sizeA, -height); + + x1 = calcMatrix.getX(0, -sizeB - height); + y1 = calcMatrix.getY(0, -sizeB - height); + + x2 = calcMatrix.getX(sizeA, -height); + y2 = calcMatrix.getY(sizeA, -height); + + x3 = calcMatrix.getX(0, sizeB - height); + y3 = calcMatrix.getY(0, sizeB - height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } + + // Left Face + + if (src.showLeft) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); + + x0 = calcMatrix.getX(-sizeA, 0); + y0 = calcMatrix.getY(-sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + + x3 = calcMatrix.getX(-sizeA, -height); + y3 = calcMatrix.getY(-sizeA, -height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } + + // Right Face + + if (src.showRight) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); + + x0 = calcMatrix.getX(sizeA, 0); + y0 = calcMatrix.getY(sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + + x3 = calcMatrix.getX(sizeA, -height); + y3 = calcMatrix.getY(sizeA, -height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } +}; + +module.exports = IsoBoxWebGLRenderer; diff --git a/src/gameobjects/shape/isotriangle/IsoTriangle.js b/src/gameobjects/shape/isotriangle/IsoTriangle.js index 8df8346dd..7dd937602 100644 --- a/src/gameobjects/shape/isotriangle/IsoTriangle.js +++ b/src/gameobjects/shape/isotriangle/IsoTriangle.js @@ -1,240 +1,240 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var IsoTriangleRender = require('./IsoTriangleRender'); -var Shape = require('../Shape'); - -/** - * @classdesc - * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different - * fill color. You can set the color of the top, left and right faces of the triangle respectively - * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting - * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside - * down or not. - * - * @class IsoTriangle - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value. - * @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. - * @param {boolean} [reversed=false] - Is the iso triangle upside down? - * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle. - * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle. - * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle. - */ -var IsoTriangle = new Class({ - - Extends: Shape, - - Mixins: [ - IsoTriangleRender - ], - - initialize: - - function IsoTriangle (scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (size === undefined) { size = 48; } - if (height === undefined) { height = 32; } - if (reversed === undefined) { reversed = false; } - if (fillTop === undefined) { fillTop = 0xeeeeee; } - if (fillLeft === undefined) { fillLeft = 0x999999; } - if (fillRight === undefined) { fillRight = 0xcccccc; } - - Shape.call(this, scene, 'IsoTriangle', null); - - /** - * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. - * - * @name Phaser.GameObjects.IsoTriangle#projection - * @type {integer} - * @default 4 - * @since 3.13.0 - */ - this.projection = 4; - - /** - * The color used to fill in the top of the iso triangle. This is only used if the triangle is reversed. - * - * @name Phaser.GameObjects.IsoTriangle#fillTop - * @type {number} - * @since 3.13.0 - */ - this.fillTop = fillTop; - - /** - * The color used to fill in the left-facing side of the iso triangle. - * - * @name Phaser.GameObjects.IsoTriangle#fillLeft - * @type {number} - * @since 3.13.0 - */ - this.fillLeft = fillLeft; - - /** - * The color used to fill in the right-facing side of the iso triangle. - * - * @name Phaser.GameObjects.IsoTriangle#fillRight - * @type {number} - * @since 3.13.0 - */ - this.fillRight = fillRight; - - /** - * Controls if the top-face of the iso triangle be rendered. - * - * @name Phaser.GameObjects.IsoTriangle#showTop - * @type {boolean} - * @default true - * @since 3.13.0 - */ - this.showTop = true; - - /** - * Controls if the left-face of the iso triangle be rendered. - * - * @name Phaser.GameObjects.IsoTriangle#showLeft - * @type {boolean} - * @default true - * @since 3.13.0 - */ - this.showLeft = true; - - /** - * Controls if the right-face of the iso triangle be rendered. - * - * @name Phaser.GameObjects.IsoTriangle#showRight - * @type {boolean} - * @default true - * @since 3.13.0 - */ - this.showRight = true; - - /** - * Sets if the iso triangle will be rendered upside down or not. - * - * @name Phaser.GameObjects.IsoTriangle#isReversed - * @type {boolean} - * @default false - * @since 3.13.0 - */ - this.isReversed = reversed; - - this.isFilled = true; - - this.setPosition(x, y); - this.setSize(size, height); - - this.updateDisplayOrigin(); - }, - - /** - * Sets the projection level of the iso triangle. Change this to change the 'angle' at which you are looking at the pyramid. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoTriangle#setProjection - * @since 3.13.0 - * - * @param {integer} value - The value to set the projection to. - * - * @return {this} This Game Object instance. - */ - setProjection: function (value) - { - this.projection = value; - - return this; - }, - - /** - * Sets if the iso triangle will be rendered upside down or not. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoTriangle#setReversed - * @since 3.13.0 - * - * @param {boolean} reversed - Sets if the iso triangle will be rendered upside down or not. - * - * @return {this} This Game Object instance. - */ - setReversed: function (reversed) - { - this.isReversed = reversed; - - return this; - }, - - /** - * Sets which faces of the iso triangle will be rendered. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoTriangle#setFaces - * @since 3.13.0 - * - * @param {boolean} [showTop=true] - Show the top-face of the iso triangle (only if `reversed` is true) - * @param {boolean} [showLeft=true] - Show the left-face of the iso triangle. - * @param {boolean} [showRight=true] - Show the right-face of the iso triangle. - * - * @return {this} This Game Object instance. - */ - setFaces: function (showTop, showLeft, showRight) - { - if (showTop === undefined) { showTop = true; } - if (showLeft === undefined) { showLeft = true; } - if (showRight === undefined) { showRight = true; } - - this.showTop = showTop; - this.showLeft = showLeft; - this.showRight = showRight; - - return this; - }, - - /** - * Sets the fill colors for each face of the iso triangle. - * This call can be chained. - * - * @method Phaser.GameObjects.IsoTriangle#setFillStyle - * @since 3.13.0 - * - * @param {number} [fillTop] - The color used to fill the top of the iso triangle. - * @param {number} [fillLeft] - The color used to fill in the left-facing side of the iso triangle. - * @param {number} [fillRight] - The color used to fill in the right-facing side of the iso triangle. - * - * @return {this} This Game Object instance. - */ - setFillStyle: function (fillTop, fillLeft, fillRight) - { - this.fillTop = fillTop; - this.fillLeft = fillLeft; - this.fillRight = fillRight; - - this.isFilled = true; - - return this; - } - -}); - -module.exports = IsoTriangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var IsoTriangleRender = require('./IsoTriangleRender'); +var Shape = require('../Shape'); + +/** + * @classdesc + * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different + * fill color. You can set the color of the top, left and right faces of the triangle respectively + * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting + * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside + * down or not. + * + * @class IsoTriangle + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. + * @param {boolean} [reversed=false] - Is the iso triangle upside down? + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle. + */ +var IsoTriangle = new Class({ + + Extends: Shape, + + Mixins: [ + IsoTriangleRender + ], + + initialize: + + function IsoTriangle (scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (size === undefined) { size = 48; } + if (height === undefined) { height = 32; } + if (reversed === undefined) { reversed = false; } + if (fillTop === undefined) { fillTop = 0xeeeeee; } + if (fillLeft === undefined) { fillLeft = 0x999999; } + if (fillRight === undefined) { fillRight = 0xcccccc; } + + Shape.call(this, scene, 'IsoTriangle', null); + + /** + * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * + * @name Phaser.GameObjects.IsoTriangle#projection + * @type {integer} + * @default 4 + * @since 3.13.0 + */ + this.projection = 4; + + /** + * The color used to fill in the top of the iso triangle. This is only used if the triangle is reversed. + * + * @name Phaser.GameObjects.IsoTriangle#fillTop + * @type {number} + * @since 3.13.0 + */ + this.fillTop = fillTop; + + /** + * The color used to fill in the left-facing side of the iso triangle. + * + * @name Phaser.GameObjects.IsoTriangle#fillLeft + * @type {number} + * @since 3.13.0 + */ + this.fillLeft = fillLeft; + + /** + * The color used to fill in the right-facing side of the iso triangle. + * + * @name Phaser.GameObjects.IsoTriangle#fillRight + * @type {number} + * @since 3.13.0 + */ + this.fillRight = fillRight; + + /** + * Controls if the top-face of the iso triangle be rendered. + * + * @name Phaser.GameObjects.IsoTriangle#showTop + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showTop = true; + + /** + * Controls if the left-face of the iso triangle be rendered. + * + * @name Phaser.GameObjects.IsoTriangle#showLeft + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showLeft = true; + + /** + * Controls if the right-face of the iso triangle be rendered. + * + * @name Phaser.GameObjects.IsoTriangle#showRight + * @type {boolean} + * @default true + * @since 3.13.0 + */ + this.showRight = true; + + /** + * Sets if the iso triangle will be rendered upside down or not. + * + * @name Phaser.GameObjects.IsoTriangle#isReversed + * @type {boolean} + * @default false + * @since 3.13.0 + */ + this.isReversed = reversed; + + this.isFilled = true; + + this.setPosition(x, y); + this.setSize(size, height); + + this.updateDisplayOrigin(); + }, + + /** + * Sets the projection level of the iso triangle. Change this to change the 'angle' at which you are looking at the pyramid. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setProjection + * @since 3.13.0 + * + * @param {integer} value - The value to set the projection to. + * + * @return {this} This Game Object instance. + */ + setProjection: function (value) + { + this.projection = value; + + return this; + }, + + /** + * Sets if the iso triangle will be rendered upside down or not. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setReversed + * @since 3.13.0 + * + * @param {boolean} reversed - Sets if the iso triangle will be rendered upside down or not. + * + * @return {this} This Game Object instance. + */ + setReversed: function (reversed) + { + this.isReversed = reversed; + + return this; + }, + + /** + * Sets which faces of the iso triangle will be rendered. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setFaces + * @since 3.13.0 + * + * @param {boolean} [showTop=true] - Show the top-face of the iso triangle (only if `reversed` is true) + * @param {boolean} [showLeft=true] - Show the left-face of the iso triangle. + * @param {boolean} [showRight=true] - Show the right-face of the iso triangle. + * + * @return {this} This Game Object instance. + */ + setFaces: function (showTop, showLeft, showRight) + { + if (showTop === undefined) { showTop = true; } + if (showLeft === undefined) { showLeft = true; } + if (showRight === undefined) { showRight = true; } + + this.showTop = showTop; + this.showLeft = showLeft; + this.showRight = showRight; + + return this; + }, + + /** + * Sets the fill colors for each face of the iso triangle. + * This call can be chained. + * + * @method Phaser.GameObjects.IsoTriangle#setFillStyle + * @since 3.13.0 + * + * @param {number} [fillTop] - The color used to fill the top of the iso triangle. + * @param {number} [fillLeft] - The color used to fill in the left-facing side of the iso triangle. + * @param {number} [fillRight] - The color used to fill in the right-facing side of the iso triangle. + * + * @return {this} This Game Object instance. + */ + setFillStyle: function (fillTop, fillLeft, fillRight) + { + this.fillTop = fillTop; + this.fillLeft = fillLeft; + this.fillRight = fillRight; + + this.isFilled = true; + + return this; + } + +}); + +module.exports = IsoTriangle; diff --git a/src/gameobjects/shape/isotriangle/IsoTriangleCanvasRenderer.js b/src/gameobjects/shape/isotriangle/IsoTriangleCanvasRenderer.js index 866b28ae8..27fc06384 100644 --- a/src/gameobjects/shape/isotriangle/IsoTriangleCanvasRenderer.js +++ b/src/gameobjects/shape/isotriangle/IsoTriangleCanvasRenderer.js @@ -1,108 +1,108 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.IsoTriangle#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.IsoTriangle} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var IsoTriangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) - { - var size = src.width; - var height = src.height; - - var sizeA = size / 2; - var sizeB = size / src.projection; - - var reversed = src.isReversed; - - // Top Face - - if (src.showTop && reversed) - { - FillStyleCanvas(ctx, src, src.fillTop); - - ctx.beginPath(); - - ctx.moveTo(-sizeA, -height); - ctx.lineTo(0, -sizeB - height); - ctx.lineTo(sizeA, -height); - ctx.lineTo(0, sizeB - height); - - ctx.fill(); - } - - // Left Face - - if (src.showLeft) - { - FillStyleCanvas(ctx, src, src.fillLeft); - - ctx.beginPath(); - - if (reversed) - { - ctx.moveTo(-sizeA, -height); - ctx.lineTo(0, sizeB); - ctx.lineTo(0, sizeB - height); - } - else - { - ctx.moveTo(-sizeA, 0); - ctx.lineTo(0, sizeB); - ctx.lineTo(0, sizeB - height); - } - - ctx.fill(); - } - - // Right Face - - if (src.showRight) - { - FillStyleCanvas(ctx, src, src.fillRight); - - ctx.beginPath(); - - if (reversed) - { - ctx.moveTo(sizeA, -height); - ctx.lineTo(0, sizeB); - ctx.lineTo(0, sizeB - height); - } - else - { - ctx.moveTo(sizeA, 0); - ctx.lineTo(0, sizeB); - ctx.lineTo(0, sizeB - height); - } - - ctx.fill(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = IsoTriangleCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoTriangle#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.IsoTriangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoTriangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) + { + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + var reversed = src.isReversed; + + // Top Face + + if (src.showTop && reversed) + { + FillStyleCanvas(ctx, src, src.fillTop); + + ctx.beginPath(); + + ctx.moveTo(-sizeA, -height); + ctx.lineTo(0, -sizeB - height); + ctx.lineTo(sizeA, -height); + ctx.lineTo(0, sizeB - height); + + ctx.fill(); + } + + // Left Face + + if (src.showLeft) + { + FillStyleCanvas(ctx, src, src.fillLeft); + + ctx.beginPath(); + + if (reversed) + { + ctx.moveTo(-sizeA, -height); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + else + { + ctx.moveTo(-sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + + ctx.fill(); + } + + // Right Face + + if (src.showRight) + { + FillStyleCanvas(ctx, src, src.fillRight); + + ctx.beginPath(); + + if (reversed) + { + ctx.moveTo(sizeA, -height); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + else + { + ctx.moveTo(sizeA, 0); + ctx.lineTo(0, sizeB); + ctx.lineTo(0, sizeB - height); + } + + ctx.fill(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = IsoTriangleCanvasRenderer; diff --git a/src/gameobjects/shape/isotriangle/IsoTriangleFactory.js b/src/gameobjects/shape/isotriangle/IsoTriangleFactory.js index 5fc16bbaa..2e8761f57 100644 --- a/src/gameobjects/shape/isotriangle/IsoTriangleFactory.js +++ b/src/gameobjects/shape/isotriangle/IsoTriangleFactory.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var IsoTriangle = require('./IsoTriangle'); - -/** - * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser. - * - * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different - * fill color. You can set the color of the top, left and right faces of the triangle respectively - * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting - * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside - * down or not. - * - * @method Phaser.GameObjects.GameObjectFactory#isotriangle - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value. - * @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. - * @param {boolean} [reversed=false] - Is the iso triangle upside down? - * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle. - * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle. - * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle. - * - * @return {Phaser.GameObjects.IsoTriangle} The Game Object that was created. - */ -GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed, fillTop, fillLeft, fillRight) -{ - return this.displayList.add(new IsoTriangle(this.scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var IsoTriangle = require('./IsoTriangle'); + +/** + * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser. + * + * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different + * fill color. You can set the color of the top, left and right faces of the triangle respectively + * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting + * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside + * down or not. + * + * @method Phaser.GameObjects.GameObjectFactory#isotriangle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value. + * @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. + * @param {boolean} [reversed=false] - Is the iso triangle upside down? + * @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle. + * @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle. + * @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle. + * + * @return {Phaser.GameObjects.IsoTriangle} The Game Object that was created. + */ +GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed, fillTop, fillLeft, fillRight) +{ + return this.displayList.add(new IsoTriangle(this.scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight)); +}); diff --git a/src/gameobjects/shape/isotriangle/IsoTriangleRender.js b/src/gameobjects/shape/isotriangle/IsoTriangleRender.js index 494738ced..1b71f45e0 100644 --- a/src/gameobjects/shape/isotriangle/IsoTriangleRender.js +++ b/src/gameobjects/shape/isotriangle/IsoTriangleRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./IsoTriangleWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./IsoTriangleCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./IsoTriangleWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./IsoTriangleCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/isotriangle/IsoTriangleWebGLRenderer.js b/src/gameobjects/shape/isotriangle/IsoTriangleWebGLRenderer.js index 1c7e5e884..b431a520e 100644 --- a/src/gameobjects/shape/isotriangle/IsoTriangleWebGLRenderer.js +++ b/src/gameobjects/shape/isotriangle/IsoTriangleWebGLRenderer.js @@ -1,171 +1,171 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.IsoTriangle#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.IsoTriangle} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var IsoTriangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var size = src.width; - var height = src.height; - - var sizeA = size / 2; - var sizeB = size / src.projection; - - var reversed = src.isReversed; - - var alpha = camera.alpha * src.alpha; - - if (!src.isFilled) - { - return; - } - - var tint; - - var x0; - var y0; - - var x1; - var y1; - - var x2; - var y2; - - // Top Face - - if (src.showTop && reversed) - { - tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); - - x0 = calcMatrix.getX(-sizeA, -height); - y0 = calcMatrix.getY(-sizeA, -height); - - x1 = calcMatrix.getX(0, -sizeB - height); - y1 = calcMatrix.getY(0, -sizeB - height); - - x2 = calcMatrix.getX(sizeA, -height); - y2 = calcMatrix.getY(sizeA, -height); - - var x3 = calcMatrix.getX(0, sizeB - height); - var y3 = calcMatrix.getY(0, sizeB - height); - - pipeline.setTexture2D(); - - pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); - } - - // Left Face - - if (src.showLeft) - { - tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); - - if (reversed) - { - x0 = calcMatrix.getX(-sizeA, -height); - y0 = calcMatrix.getY(-sizeA, -height); - - x1 = calcMatrix.getX(0, sizeB); - y1 = calcMatrix.getY(0, sizeB); - - x2 = calcMatrix.getX(0, sizeB - height); - y2 = calcMatrix.getY(0, sizeB - height); - } - else - { - x0 = calcMatrix.getX(-sizeA, 0); - y0 = calcMatrix.getY(-sizeA, 0); - - x1 = calcMatrix.getX(0, sizeB); - y1 = calcMatrix.getY(0, sizeB); - - x2 = calcMatrix.getX(0, sizeB - height); - y2 = calcMatrix.getY(0, sizeB - height); - } - - pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2); - } - - // Right Face - - if (src.showRight) - { - tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); - - if (reversed) - { - x0 = calcMatrix.getX(sizeA, -height); - y0 = calcMatrix.getY(sizeA, -height); - - x1 = calcMatrix.getX(0, sizeB); - y1 = calcMatrix.getY(0, sizeB); - - x2 = calcMatrix.getX(0, sizeB - height); - y2 = calcMatrix.getY(0, sizeB - height); - } - else - { - x0 = calcMatrix.getX(sizeA, 0); - y0 = calcMatrix.getY(sizeA, 0); - - x1 = calcMatrix.getX(0, sizeB); - y1 = calcMatrix.getY(0, sizeB); - - x2 = calcMatrix.getX(0, sizeB - height); - y2 = calcMatrix.getY(0, sizeB - height); - } - - pipeline.setTexture2D(); - - pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2); - } -}; - -module.exports = IsoTriangleWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.IsoTriangle#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.IsoTriangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var IsoTriangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var size = src.width; + var height = src.height; + + var sizeA = size / 2; + var sizeB = size / src.projection; + + var reversed = src.isReversed; + + var alpha = camera.alpha * src.alpha; + + if (!src.isFilled) + { + return; + } + + var tint; + + var x0; + var y0; + + var x1; + var y1; + + var x2; + var y2; + + // Top Face + + if (src.showTop && reversed) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); + + x0 = calcMatrix.getX(-sizeA, -height); + y0 = calcMatrix.getY(-sizeA, -height); + + x1 = calcMatrix.getX(0, -sizeB - height); + y1 = calcMatrix.getY(0, -sizeB - height); + + x2 = calcMatrix.getX(sizeA, -height); + y2 = calcMatrix.getY(sizeA, -height); + + var x3 = calcMatrix.getX(0, sizeB - height); + var y3 = calcMatrix.getY(0, sizeB - height); + + pipeline.setTexture2D(); + + pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2); + } + + // Left Face + + if (src.showLeft) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); + + if (reversed) + { + x0 = calcMatrix.getX(-sizeA, -height); + y0 = calcMatrix.getY(-sizeA, -height); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + else + { + x0 = calcMatrix.getX(-sizeA, 0); + y0 = calcMatrix.getY(-sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + + pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2); + } + + // Right Face + + if (src.showRight) + { + tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); + + if (reversed) + { + x0 = calcMatrix.getX(sizeA, -height); + y0 = calcMatrix.getY(sizeA, -height); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + else + { + x0 = calcMatrix.getX(sizeA, 0); + y0 = calcMatrix.getY(sizeA, 0); + + x1 = calcMatrix.getX(0, sizeB); + y1 = calcMatrix.getY(0, sizeB); + + x2 = calcMatrix.getX(0, sizeB - height); + y2 = calcMatrix.getY(0, sizeB - height); + } + + pipeline.setTexture2D(); + + pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2); + } +}; + +module.exports = IsoTriangleWebGLRenderer; diff --git a/src/gameobjects/shape/line/Line.js b/src/gameobjects/shape/line/Line.js index 38296113d..19ae5f4fe 100644 --- a/src/gameobjects/shape/line/Line.js +++ b/src/gameobjects/shape/line/Line.js @@ -1,161 +1,161 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Shape = require('../Shape'); -var GeomLine = require('../../../geom/line/Line'); -var LineRender = require('./LineRender'); - -/** - * @classdesc - * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only stroke colors and cannot be filled. - * - * A Line Shape allows you to draw a line between two points in your game. You can control the - * stroke color and thickness of the line. In WebGL only you can also specify a different - * thickness for the start and end of the line, allowing you to render lines that taper-off. - * - * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. - * - * Be aware that as with all Game Objects the default origin is 0.5. If you need to draw a Line - * between two points and want the x1/y1 values to match the x/y values, then set the origin to 0. - * - * @class Line - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [x1=0] - The horizontal position of the start of the line. - * @param {number} [y1=0] - The vertical position of the start of the line. - * @param {number} [x2=128] - The horizontal position of the end of the line. - * @param {number} [y2=0] - The vertical position of the end of the line. - * @param {number} [strokeColor] - The color the line will be drawn in, i.e. 0xff0000 for red. - * @param {number} [strokeAlpha] - The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Line = new Class({ - - Extends: Shape, - - Mixins: [ - LineRender - ], - - initialize: - - function Line (scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (x1 === undefined) { x1 = 0; } - if (y1 === undefined) { y1 = 0; } - if (x2 === undefined) { x2 = 128; } - if (y2 === undefined) { y2 = 0; } - - Shape.call(this, scene, 'Line', new GeomLine(x1, y1, x2, y2)); - - var width = this.geom.right - this.geom.left; - var height = this.geom.bottom - this.geom.top; - - /** - * The width (or thickness) of the line. - * See the setLineWidth method for extra details on changing this on WebGL. - * - * @name Phaser.GameObjects.Line#lineWidth - * @type {number} - * @since 3.13.0 - */ - this.lineWidth = 1; - - /** - * Private internal value. Holds the start width of the line. - * - * @name Phaser.GameObjects.Line#_startWidth - * @type {number} - * @private - * @since 3.13.0 - */ - this._startWidth = 1; - - /** - * Private internal value. Holds the end width of the line. - * - * @name Phaser.GameObjects.Line#_endWidth - * @type {number} - * @private - * @since 3.13.0 - */ - this._endWidth = 1; - - this.setPosition(x, y); - this.setSize(width, height); - - if (strokeColor !== undefined) - { - this.setStrokeStyle(1, strokeColor, strokeAlpha); - } - - this.updateDisplayOrigin(); - }, - - /** - * Sets the width of the line. - * - * When using the WebGL renderer you can have different start and end widths. - * When using the Canvas renderer only the `startWidth` value is used. The `endWidth` is ignored. - * - * This call can be chained. - * - * @method Phaser.GameObjects.Line#setLineWidth - * @since 3.13.0 - * - * @param {number} startWidth - The start width of the line. - * @param {number} [endWidth] - The end width of the line. Only used in WebGL. - * - * @return {this} This Game Object instance. - */ - setLineWidth: function (startWidth, endWidth) - { - if (endWidth === undefined) { endWidth = startWidth; } - - this._startWidth = startWidth; - this._endWidth = endWidth; - - this.lineWidth = startWidth; - - return this; - }, - - /** - * Sets the start and end coordinates of this Line. - * - * @method Phaser.GameObjects.Line#setTo - * @since 3.13.0 - * - * @param {number} [x1=0] - The horizontal position of the start of the line. - * @param {number} [y1=0] - The vertical position of the start of the line. - * @param {number} [x2=0] - The horizontal position of the end of the line. - * @param {number} [y2=0] - The vertical position of the end of the line. - * - * @return {this} This Line object. - */ - setTo: function (x1, y1, x2, y2) - { - this.geom.setTo(x1, y1, x2, y2); - - return this; - } - -}); - -module.exports = Line; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Shape = require('../Shape'); +var GeomLine = require('../../../geom/line/Line'); +var LineRender = require('./LineRender'); + +/** + * @classdesc + * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only stroke colors and cannot be filled. + * + * A Line Shape allows you to draw a line between two points in your game. You can control the + * stroke color and thickness of the line. In WebGL only you can also specify a different + * thickness for the start and end of the line, allowing you to render lines that taper-off. + * + * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. + * + * Be aware that as with all Game Objects the default origin is 0.5. If you need to draw a Line + * between two points and want the x1/y1 values to match the x/y values, then set the origin to 0. + * + * @class Line + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the start of the line. + * @param {number} [y1=0] - The vertical position of the start of the line. + * @param {number} [x2=128] - The horizontal position of the end of the line. + * @param {number} [y2=0] - The vertical position of the end of the line. + * @param {number} [strokeColor] - The color the line will be drawn in, i.e. 0xff0000 for red. + * @param {number} [strokeAlpha] - The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Line = new Class({ + + Extends: Shape, + + Mixins: [ + LineRender + ], + + initialize: + + function Line (scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 128; } + if (y2 === undefined) { y2 = 0; } + + Shape.call(this, scene, 'Line', new GeomLine(x1, y1, x2, y2)); + + var width = this.geom.right - this.geom.left; + var height = this.geom.bottom - this.geom.top; + + /** + * The width (or thickness) of the line. + * See the setLineWidth method for extra details on changing this on WebGL. + * + * @name Phaser.GameObjects.Line#lineWidth + * @type {number} + * @since 3.13.0 + */ + this.lineWidth = 1; + + /** + * Private internal value. Holds the start width of the line. + * + * @name Phaser.GameObjects.Line#_startWidth + * @type {number} + * @private + * @since 3.13.0 + */ + this._startWidth = 1; + + /** + * Private internal value. Holds the end width of the line. + * + * @name Phaser.GameObjects.Line#_endWidth + * @type {number} + * @private + * @since 3.13.0 + */ + this._endWidth = 1; + + this.setPosition(x, y); + this.setSize(width, height); + + if (strokeColor !== undefined) + { + this.setStrokeStyle(1, strokeColor, strokeAlpha); + } + + this.updateDisplayOrigin(); + }, + + /** + * Sets the width of the line. + * + * When using the WebGL renderer you can have different start and end widths. + * When using the Canvas renderer only the `startWidth` value is used. The `endWidth` is ignored. + * + * This call can be chained. + * + * @method Phaser.GameObjects.Line#setLineWidth + * @since 3.13.0 + * + * @param {number} startWidth - The start width of the line. + * @param {number} [endWidth] - The end width of the line. Only used in WebGL. + * + * @return {this} This Game Object instance. + */ + setLineWidth: function (startWidth, endWidth) + { + if (endWidth === undefined) { endWidth = startWidth; } + + this._startWidth = startWidth; + this._endWidth = endWidth; + + this.lineWidth = startWidth; + + return this; + }, + + /** + * Sets the start and end coordinates of this Line. + * + * @method Phaser.GameObjects.Line#setTo + * @since 3.13.0 + * + * @param {number} [x1=0] - The horizontal position of the start of the line. + * @param {number} [y1=0] - The vertical position of the start of the line. + * @param {number} [x2=0] - The horizontal position of the end of the line. + * @param {number} [y2=0] - The vertical position of the end of the line. + * + * @return {this} This Line object. + */ + setTo: function (x1, y1, x2, y2) + { + this.geom.setTo(x1, y1, x2, y2); + + return this; + } + +}); + +module.exports = Line; diff --git a/src/gameobjects/shape/line/LineCanvasRenderer.js b/src/gameobjects/shape/line/LineCanvasRenderer.js index 01a504f74..bd4a9fc52 100644 --- a/src/gameobjects/shape/line/LineCanvasRenderer.js +++ b/src/gameobjects/shape/line/LineCanvasRenderer.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Line#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var LineCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.beginPath(); - - ctx.moveTo(src.geom.x1 - dx, src.geom.y1 - dy); - ctx.lineTo(src.geom.x2 - dx, src.geom.y2 - dy); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = LineCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Line#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var LineCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.beginPath(); + + ctx.moveTo(src.geom.x1 - dx, src.geom.y1 - dy); + ctx.lineTo(src.geom.x2 - dx, src.geom.y2 - dy); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = LineCanvasRenderer; diff --git a/src/gameobjects/shape/line/LineFactory.js b/src/gameobjects/shape/line/LineFactory.js index 0f2da4aef..d1ed59e10 100644 --- a/src/gameobjects/shape/line/LineFactory.js +++ b/src/gameobjects/shape/line/LineFactory.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var Line = require('./Line'); - -/** - * Creates a new Line Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Line Game Object has been built into Phaser. - * - * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only stroke colors and cannot be filled. - * - * A Line Shape allows you to draw a line between two points in your game. You can control the - * stroke color and thickness of the line. In WebGL only you can also specify a different - * thickness for the start and end of the line, allowing you to render lines that taper-off. - * - * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. - * - * @method Phaser.GameObjects.GameObjectFactory#line - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [x1=0] - The horizontal position of the start of the line. - * @param {number} [y1=0] - The vertical position of the start of the line. - * @param {number} [x2=128] - The horizontal position of the end of the line. - * @param {number} [y2=0] - The vertical position of the end of the line. - * @param {number} [strokeColor] - The color the line will be drawn in, i.e. 0xff0000 for red. - * @param {number} [strokeAlpha] - The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Line} The Game Object that was created. - */ -GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) -{ - return this.displayList.add(new Line(this.scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var Line = require('./Line'); + +/** + * Creates a new Line Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Line Game Object has been built into Phaser. + * + * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only stroke colors and cannot be filled. + * + * A Line Shape allows you to draw a line between two points in your game. You can control the + * stroke color and thickness of the line. In WebGL only you can also specify a different + * thickness for the start and end of the line, allowing you to render lines that taper-off. + * + * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. + * + * @method Phaser.GameObjects.GameObjectFactory#line + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the start of the line. + * @param {number} [y1=0] - The vertical position of the start of the line. + * @param {number} [x2=128] - The horizontal position of the end of the line. + * @param {number} [y2=0] - The vertical position of the end of the line. + * @param {number} [strokeColor] - The color the line will be drawn in, i.e. 0xff0000 for red. + * @param {number} [strokeAlpha] - The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Line} The Game Object that was created. + */ +GameObjectFactory.register('line', function (x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) +{ + return this.displayList.add(new Line(this.scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha)); +}); diff --git a/src/gameobjects/shape/line/LineRender.js b/src/gameobjects/shape/line/LineRender.js index 8a8e2a83e..3f7970259 100644 --- a/src/gameobjects/shape/line/LineRender.js +++ b/src/gameobjects/shape/line/LineRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./LineWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./LineCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./LineWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./LineCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/line/LineWebGLRenderer.js b/src/gameobjects/shape/line/LineWebGLRenderer.js index a8b26536d..f56c43777 100644 --- a/src/gameobjects/shape/line/LineWebGLRenderer.js +++ b/src/gameobjects/shape/line/LineWebGLRenderer.js @@ -1,87 +1,87 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Line#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var LineWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - var alpha = camera.alpha * src.alpha; - - if (src.isStroked) - { - var strokeTint = pipeline.strokeTint; - var color = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); - - strokeTint.TL = color; - strokeTint.TR = color; - strokeTint.BL = color; - strokeTint.BR = color; - - var startWidth = src._startWidth; - var endWidth = src._endWidth; - - pipeline.setTexture2D(); - - pipeline.batchLine( - src.geom.x1 - dx, - src.geom.y1 - dy, - src.geom.x2 - dx, - src.geom.y2 - dy, - startWidth, - endWidth, - 1, - 0, - false, - shapeMatrix, - camMatrix - ); - } -}; - -module.exports = LineWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Line#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var LineWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + var alpha = camera.alpha * src.alpha; + + if (src.isStroked) + { + var strokeTint = pipeline.strokeTint; + var color = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); + + strokeTint.TL = color; + strokeTint.TR = color; + strokeTint.BL = color; + strokeTint.BR = color; + + var startWidth = src._startWidth; + var endWidth = src._endWidth; + + pipeline.setTexture2D(); + + pipeline.batchLine( + src.geom.x1 - dx, + src.geom.y1 - dy, + src.geom.x2 - dx, + src.geom.y2 - dy, + startWidth, + endWidth, + 1, + 0, + false, + shapeMatrix, + camMatrix + ); + } +}; + +module.exports = LineWebGLRenderer; diff --git a/src/gameobjects/shape/polygon/Polygon.js b/src/gameobjects/shape/polygon/Polygon.js index 971ead967..fb6d089f9 100644 --- a/src/gameobjects/shape/polygon/Polygon.js +++ b/src/gameobjects/shape/polygon/Polygon.js @@ -1,133 +1,133 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PolygonRender = require('./PolygonRender'); -var Class = require('../../../utils/Class'); -var Earcut = require('../../../geom/polygon/Earcut'); -var GetAABB = require('../../../geom/polygon/GetAABB'); -var GeomPolygon = require('../../../geom/polygon/Polygon'); -var Shape = require('../Shape'); -var Smooth = require('../../../geom/polygon/Smooth'); - -/** - * @classdesc - * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Polygon Shape is created by providing a list of points, which are then used to create an - * internal Polygon geometry object. The points can be set from a variety of formats: - * - * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` - * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` - * - An array of objects with public x/y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - * - * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending - * on the coordinates of the points provided, the final shape may be rendered offset from its origin. - * - * @class Polygon - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {any} [points] - The points that make up the polygon. - * @param {number} [fillColor] - The color the polygon will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Polygon = new Class({ - - Extends: Shape, - - Mixins: [ - PolygonRender - ], - - initialize: - - function Polygon (scene, x, y, points, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - Shape.call(this, scene, 'Polygon', new GeomPolygon(points)); - - var bounds = GetAABB(this.geom); - - this.setPosition(x, y); - this.setSize(bounds.width, bounds.height); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateDisplayOrigin(); - this.updateData(); - }, - - /** - * Smooths the polygon over the number of iterations specified. - * The base polygon data will be updated and replaced with the smoothed values. - * This call can be chained. - * - * @method Phaser.GameObjects.Polygon#smooth - * @since 3.13.0 - * - * @param {integer} [iterations=1] - The number of times to apply the polygon smoothing. - * - * @return {this} This Game Object instance. - */ - smooth: function (iterations) - { - if (iterations === undefined) { iterations = 1; } - - for (var i = 0; i < iterations; i++) - { - Smooth(this.geom); - } - - return this.updateData(); - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Polygon#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var path = []; - var points = this.geom.points; - - for (var i = 0; i < points.length; i++) - { - path.push(points[i].x, points[i].y); - } - - path.push(points[0].x, points[0].y); - - this.pathIndexes = Earcut(path); - this.pathData = path; - - return this; - } - -}); - -module.exports = Polygon; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PolygonRender = require('./PolygonRender'); +var Class = require('../../../utils/Class'); +var Earcut = require('../../../geom/polygon/Earcut'); +var GetAABB = require('../../../geom/polygon/GetAABB'); +var GeomPolygon = require('../../../geom/polygon/Polygon'); +var Shape = require('../Shape'); +var Smooth = require('../../../geom/polygon/Smooth'); + +/** + * @classdesc + * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Polygon Shape is created by providing a list of points, which are then used to create an + * internal Polygon geometry object. The points can be set from a variety of formats: + * + * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending + * on the coordinates of the points provided, the final shape may be rendered offset from its origin. + * + * @class Polygon + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {any} [points] - The points that make up the polygon. + * @param {number} [fillColor] - The color the polygon will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Polygon = new Class({ + + Extends: Shape, + + Mixins: [ + PolygonRender + ], + + initialize: + + function Polygon (scene, x, y, points, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + Shape.call(this, scene, 'Polygon', new GeomPolygon(points)); + + var bounds = GetAABB(this.geom); + + this.setPosition(x, y); + this.setSize(bounds.width, bounds.height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Smooths the polygon over the number of iterations specified. + * The base polygon data will be updated and replaced with the smoothed values. + * This call can be chained. + * + * @method Phaser.GameObjects.Polygon#smooth + * @since 3.13.0 + * + * @param {integer} [iterations=1] - The number of times to apply the polygon smoothing. + * + * @return {this} This Game Object instance. + */ + smooth: function (iterations) + { + if (iterations === undefined) { iterations = 1; } + + for (var i = 0; i < iterations; i++) + { + Smooth(this.geom); + } + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Polygon#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var points = this.geom.points; + + for (var i = 0; i < points.length; i++) + { + path.push(points[i].x, points[i].y); + } + + path.push(points[0].x, points[0].y); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Polygon; diff --git a/src/gameobjects/shape/polygon/PolygonCanvasRenderer.js b/src/gameobjects/shape/polygon/PolygonCanvasRenderer.js index 2662b4fa7..5c2af4eea 100644 --- a/src/gameobjects/shape/polygon/PolygonCanvasRenderer.js +++ b/src/gameobjects/shape/polygon/PolygonCanvasRenderer.js @@ -1,79 +1,79 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Polygon#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Polygon} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var PolygonCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var path = src.pathData; - var pathLength = path.length - 1; - - var px1 = path[0] - dx; - var py1 = path[1] - dy; - - ctx.beginPath(); - - ctx.moveTo(px1, py1); - - if (!src.closePath) - { - pathLength -= 2; - } - - for (var i = 2; i < pathLength; i += 2) - { - var px2 = path[i] - dx; - var py2 = path[i + 1] - dy; - - ctx.lineTo(px2, py2); - } - - ctx.closePath(); - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fill(); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = PolygonCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Polygon#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Polygon} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var PolygonCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = PolygonCanvasRenderer; diff --git a/src/gameobjects/shape/polygon/PolygonFactory.js b/src/gameobjects/shape/polygon/PolygonFactory.js index d0c03aac6..03d5be950 100644 --- a/src/gameobjects/shape/polygon/PolygonFactory.js +++ b/src/gameobjects/shape/polygon/PolygonFactory.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var Polygon = require('./Polygon'); - -/** - * Creates a new Polygon Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Polygon Game Object has been built into Phaser. - * - * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Polygon Shape is created by providing a list of points, which are then used to create an - * internal Polygon geometry object. The points can be set from a variety of formats: - * - * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` - * - An array of objects with public x/y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - * - * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending - * on the coordinates of the points provided, the final shape may be rendered offset from its origin. - * - * @method Phaser.GameObjects.GameObjectFactory#polygon - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {any} [points] - The points that make up the polygon. - * @param {number} [fillColor] - The color the polygon will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Polygon} The Game Object that was created. - */ -GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlpha) -{ - return this.displayList.add(new Polygon(this.scene, x, y, points, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var Polygon = require('./Polygon'); + +/** + * Creates a new Polygon Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Polygon Game Object has been built into Phaser. + * + * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Polygon Shape is created by providing a list of points, which are then used to create an + * internal Polygon geometry object. The points can be set from a variety of formats: + * + * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending + * on the coordinates of the points provided, the final shape may be rendered offset from its origin. + * + * @method Phaser.GameObjects.GameObjectFactory#polygon + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {any} [points] - The points that make up the polygon. + * @param {number} [fillColor] - The color the polygon will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Polygon} The Game Object that was created. + */ +GameObjectFactory.register('polygon', function (x, y, points, fillColor, fillAlpha) +{ + return this.displayList.add(new Polygon(this.scene, x, y, points, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/polygon/PolygonRender.js b/src/gameobjects/shape/polygon/PolygonRender.js index 5e4897f1c..0669050d8 100644 --- a/src/gameobjects/shape/polygon/PolygonRender.js +++ b/src/gameobjects/shape/polygon/PolygonRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./PolygonWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./PolygonCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./PolygonWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./PolygonCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/polygon/PolygonWebGLRenderer.js b/src/gameobjects/shape/polygon/PolygonWebGLRenderer.js index cd41ef81f..1a5b480b8 100644 --- a/src/gameobjects/shape/polygon/PolygonWebGLRenderer.js +++ b/src/gameobjects/shape/polygon/PolygonWebGLRenderer.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillPathWebGL = require('../FillPathWebGL'); -var StrokePathWebGL = require('../StrokePathWebGL'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Polygon#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Polygon} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var PolygonWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = PolygonWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = require('../FillPathWebGL'); +var StrokePathWebGL = require('../StrokePathWebGL'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Polygon#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Polygon} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var PolygonWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = PolygonWebGLRenderer; diff --git a/src/gameobjects/shape/rectangle/Rectangle.js b/src/gameobjects/shape/rectangle/Rectangle.js index f4e6b815e..31bc736d2 100644 --- a/src/gameobjects/shape/rectangle/Rectangle.js +++ b/src/gameobjects/shape/rectangle/Rectangle.js @@ -1,106 +1,106 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var GeomRectangle = require('../../../geom/rectangle/Rectangle'); -var Shape = require('../Shape'); -var RectangleRender = require('./RectangleRender'); - -/** - * @classdesc - * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * You can change the size of the rectangle by changing the `width` and `height` properties. - * - * @class Rectangle - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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 {number} [width=128] - The width of the rectangle. - * @param {number} [height=128] - The height of the rectangle. - * @param {number} [fillColor] - The color the rectangle will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Rectangle = new Class({ - - Extends: Shape, - - Mixins: [ - RectangleRender - ], - - initialize: - - function Rectangle (scene, x, y, width, height, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 128; } - if (height === undefined) { height = 128; } - - Shape.call(this, scene, 'Rectangle', new GeomRectangle(0, 0, width, height)); - - this.setPosition(x, y); - this.setSize(width, height); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateDisplayOrigin(); - this.updateData(); - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Rectangle#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var path = []; - var rect = this.geom; - var line = this._tempLine; - - rect.getLineA(line); - - path.push(line.x1, line.y1, line.x2, line.y2); - - rect.getLineB(line); - - path.push(line.x2, line.y2); - - rect.getLineC(line); - - path.push(line.x2, line.y2); - - rect.getLineD(line); - - path.push(line.x2, line.y2); - - this.pathData = path; - - return this; - } - -}); - -module.exports = Rectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var GeomRectangle = require('../../../geom/rectangle/Rectangle'); +var Shape = require('../Shape'); +var RectangleRender = require('./RectangleRender'); + +/** + * @classdesc + * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * You can change the size of the rectangle by changing the `width` and `height` properties. + * + * @class Rectangle + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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 {number} [width=128] - The width of the rectangle. + * @param {number} [height=128] - The height of the rectangle. + * @param {number} [fillColor] - The color the rectangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Rectangle = new Class({ + + Extends: Shape, + + Mixins: [ + RectangleRender + ], + + initialize: + + function Rectangle (scene, x, y, width, height, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 128; } + if (height === undefined) { height = 128; } + + Shape.call(this, scene, 'Rectangle', new GeomRectangle(0, 0, width, height)); + + this.setPosition(x, y); + this.setSize(width, height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Rectangle#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var rect = this.geom; + var line = this._tempLine; + + rect.getLineA(line); + + path.push(line.x1, line.y1, line.x2, line.y2); + + rect.getLineB(line); + + path.push(line.x2, line.y2); + + rect.getLineC(line); + + path.push(line.x2, line.y2); + + rect.getLineD(line); + + path.push(line.x2, line.y2); + + this.pathData = path; + + return this; + } + +}); + +module.exports = Rectangle; diff --git a/src/gameobjects/shape/rectangle/RectangleCanvasRenderer.js b/src/gameobjects/shape/rectangle/RectangleCanvasRenderer.js index 02a3e52d4..e212433cc 100644 --- a/src/gameobjects/shape/rectangle/RectangleCanvasRenderer.js +++ b/src/gameobjects/shape/rectangle/RectangleCanvasRenderer.js @@ -1,68 +1,68 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Rectangle#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Rectangle} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RectangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fillRect( - -dx, - -dy, - src.width, - src.height - ); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.beginPath(); - - ctx.rect( - -dx, - -dy, - src.width, - src.height - ); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = RectangleCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Rectangle#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Rectangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RectangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fillRect( + -dx, + -dy, + src.width, + src.height + ); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.beginPath(); + + ctx.rect( + -dx, + -dy, + src.width, + src.height + ); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = RectangleCanvasRenderer; diff --git a/src/gameobjects/shape/rectangle/RectangleFactory.js b/src/gameobjects/shape/rectangle/RectangleFactory.js index 41ffb1b6c..6f16e8064 100644 --- a/src/gameobjects/shape/rectangle/RectangleFactory.js +++ b/src/gameobjects/shape/rectangle/RectangleFactory.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var Rectangle = require('./Rectangle'); - -/** - * Creates a new Rectangle Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Rectangle Game Object has been built into Phaser. - * - * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * You can change the size of the rectangle by changing the `width` and `height` properties. - * - * @method Phaser.GameObjects.GameObjectFactory#rectangle - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [width=128] - The width of the rectangle. - * @param {number} [height=128] - The height of the rectangle. - * @param {number} [fillColor] - The color the rectangle will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Rectangle} The Game Object that was created. - */ -GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor, fillAlpha) -{ - return this.displayList.add(new Rectangle(this.scene, x, y, width, height, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var Rectangle = require('./Rectangle'); + +/** + * Creates a new Rectangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Rectangle Game Object has been built into Phaser. + * + * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * You can change the size of the rectangle by changing the `width` and `height` properties. + * + * @method Phaser.GameObjects.GameObjectFactory#rectangle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [width=128] - The width of the rectangle. + * @param {number} [height=128] - The height of the rectangle. + * @param {number} [fillColor] - The color the rectangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Rectangle} The Game Object that was created. + */ +GameObjectFactory.register('rectangle', function (x, y, width, height, fillColor, fillAlpha) +{ + return this.displayList.add(new Rectangle(this.scene, x, y, width, height, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/rectangle/RectangleRender.js b/src/gameobjects/shape/rectangle/RectangleRender.js index 188fa6632..6246c7e8d 100644 --- a/src/gameobjects/shape/rectangle/RectangleRender.js +++ b/src/gameobjects/shape/rectangle/RectangleRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./RectangleWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./RectangleCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./RectangleWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./RectangleCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/rectangle/RectangleWebGLRenderer.js b/src/gameobjects/shape/rectangle/RectangleWebGLRenderer.js index 1773dc3e7..bd3e2f945 100644 --- a/src/gameobjects/shape/rectangle/RectangleWebGLRenderer.js +++ b/src/gameobjects/shape/rectangle/RectangleWebGLRenderer.js @@ -1,86 +1,86 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var StrokePathWebGL = require('../StrokePathWebGL'); -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Rectangle#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Rectangle} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var RectangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - var fillTint = pipeline.fillTint; - var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); - - fillTint.TL = fillTintColor; - fillTint.TR = fillTintColor; - fillTint.BL = fillTintColor; - fillTint.BR = fillTintColor; - - pipeline.setTexture2D(); - - pipeline.batchFillRect( - -dx, - -dy, - src.width, - src.height - ); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = RectangleWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var StrokePathWebGL = require('../StrokePathWebGL'); +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Rectangle#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Rectangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var RectangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + var fillTint = pipeline.fillTint; + var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + pipeline.setTexture2D(); + + pipeline.batchFillRect( + -dx, + -dy, + src.width, + src.height + ); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = RectangleWebGLRenderer; diff --git a/src/gameobjects/shape/star/Star.js b/src/gameobjects/shape/star/Star.js index a0bd489b6..320bfa689 100644 --- a/src/gameobjects/shape/star/Star.js +++ b/src/gameobjects/shape/star/Star.js @@ -1,282 +1,282 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var StarRender = require('./StarRender'); -var Class = require('../../../utils/Class'); -var Earcut = require('../../../geom/polygon/Earcut'); -var Shape = require('../Shape'); - -/** - * @classdesc - * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * As the name implies, the Star shape will display a star in your game. You can control several - * aspects of it including the number of points that constitute the star. The default is 5. If - * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky - * star shape. - * - * You can also control the inner and outer radius, which is how 'long' each point of the star is. - * Modify these values to create more interesting shapes. - * - * @class Star - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [points=5] - The number of points on the star. - * @param {number} [innerRadius=32] - The inner radius of the star. - * @param {number} [outerRadius=64] - The outer radius of the star. - * @param {number} [fillColor] - The color the star will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Star = new Class({ - - Extends: Shape, - - Mixins: [ - StarRender - ], - - initialize: - - function Star (scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (points === undefined) { points = 5; } - if (innerRadius === undefined) { innerRadius = 32; } - if (outerRadius === undefined) { outerRadius = 64; } - - Shape.call(this, scene, 'Star', null); - - /** - * Private internal value. - * The number of points in the star. - * - * @name Phaser.GameObjects.Star#_points - * @type {integer} - * @private - * @since 3.13.0 - */ - this._points = points; - - /** - * Private internal value. - * The inner radius of the star. - * - * @name Phaser.GameObjects.Star#_innerRadius - * @type {number} - * @private - * @since 3.13.0 - */ - this._innerRadius = innerRadius; - - /** - * Private internal value. - * The outer radius of the star. - * - * @name Phaser.GameObjects.Star#_outerRadius - * @type {number} - * @private - * @since 3.13.0 - */ - this._outerRadius = outerRadius; - - this.setPosition(x, y); - this.setSize(outerRadius * 2, outerRadius * 2); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateDisplayOrigin(); - this.updateData(); - }, - - /** - * Sets the number of points that make up the Star shape. - * This call can be chained. - * - * @method Phaser.GameObjects.Star#setPoints - * @since 3.13.0 - * - * @param {integer} value - The amount of points the Star will have. - * - * @return {this} This Game Object instance. - */ - setPoints: function (value) - { - this._points = value; - - return this.updateData(); - }, - - /** - * Sets the inner radius of the Star shape. - * This call can be chained. - * - * @method Phaser.GameObjects.Star#setInnerRadius - * @since 3.13.0 - * - * @param {number} value - The amount to set the inner radius to. - * - * @return {this} This Game Object instance. - */ - setInnerRadius: function (value) - { - this._innerRadius = value; - - return this.updateData(); - }, - - /** - * Sets the outer radius of the Star shape. - * This call can be chained. - * - * @method Phaser.GameObjects.Star#setOuterRadius - * @since 3.13.0 - * - * @param {number} value - The amount to set the outer radius to. - * - * @return {this} This Game Object instance. - */ - setOuterRadius: function (value) - { - this._outerRadius = value; - - return this.updateData(); - }, - - /** - * The number of points that make up the Star shape. - * - * @name Phaser.GameObjects.Star#points - * @type {integer} - * @default 5 - * @since 3.13.0 - */ - points: { - - get: function () - { - return this._points; - }, - - set: function (value) - { - this._points = value; - - this.updateData(); - } - - }, - - /** - * The inner radius of the Star shape. - * - * @name Phaser.GameObjects.Star#innerRadius - * @type {number} - * @default 32 - * @since 3.13.0 - */ - innerRadius: { - - get: function () - { - return this._innerRadius; - }, - - set: function (value) - { - this._innerRadius = value; - - this.updateData(); - } - - }, - - /** - * The outer radius of the Star shape. - * - * @name Phaser.GameObjects.Star#outerRadius - * @type {number} - * @default 64 - * @since 3.13.0 - */ - outerRadius: { - - get: function () - { - return this._outerRadius; - }, - - set: function (value) - { - this._outerRadius = value; - - this.updateData(); - } - - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Star#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var path = []; - - var points = this._points; - var innerRadius = this._innerRadius; - var outerRadius = this._outerRadius; - - var rot = Math.PI / 2 * 3; - var step = Math.PI / points; - - // So origin 0.5 = the center of the star - var x = outerRadius; - var y = outerRadius; - - path.push(x, y + -outerRadius); - - for (var i = 0; i < points; i++) - { - path.push(x + Math.cos(rot) * outerRadius, y + Math.sin(rot) * outerRadius); - - rot += step; - - path.push(x + Math.cos(rot) * innerRadius, y + Math.sin(rot) * innerRadius); - - rot += step; - } - - path.push(x, y + -outerRadius); - - this.pathIndexes = Earcut(path); - this.pathData = path; - - return this; - } - -}); - -module.exports = Star; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var StarRender = require('./StarRender'); +var Class = require('../../../utils/Class'); +var Earcut = require('../../../geom/polygon/Earcut'); +var Shape = require('../Shape'); + +/** + * @classdesc + * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * As the name implies, the Star shape will display a star in your game. You can control several + * aspects of it including the number of points that constitute the star. The default is 5. If + * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky + * star shape. + * + * You can also control the inner and outer radius, which is how 'long' each point of the star is. + * Modify these values to create more interesting shapes. + * + * @class Star + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [points=5] - The number of points on the star. + * @param {number} [innerRadius=32] - The inner radius of the star. + * @param {number} [outerRadius=64] - The outer radius of the star. + * @param {number} [fillColor] - The color the star will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Star = new Class({ + + Extends: Shape, + + Mixins: [ + StarRender + ], + + initialize: + + function Star (scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (points === undefined) { points = 5; } + if (innerRadius === undefined) { innerRadius = 32; } + if (outerRadius === undefined) { outerRadius = 64; } + + Shape.call(this, scene, 'Star', null); + + /** + * Private internal value. + * The number of points in the star. + * + * @name Phaser.GameObjects.Star#_points + * @type {integer} + * @private + * @since 3.13.0 + */ + this._points = points; + + /** + * Private internal value. + * The inner radius of the star. + * + * @name Phaser.GameObjects.Star#_innerRadius + * @type {number} + * @private + * @since 3.13.0 + */ + this._innerRadius = innerRadius; + + /** + * Private internal value. + * The outer radius of the star. + * + * @name Phaser.GameObjects.Star#_outerRadius + * @type {number} + * @private + * @since 3.13.0 + */ + this._outerRadius = outerRadius; + + this.setPosition(x, y); + this.setSize(outerRadius * 2, outerRadius * 2); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Sets the number of points that make up the Star shape. + * This call can be chained. + * + * @method Phaser.GameObjects.Star#setPoints + * @since 3.13.0 + * + * @param {integer} value - The amount of points the Star will have. + * + * @return {this} This Game Object instance. + */ + setPoints: function (value) + { + this._points = value; + + return this.updateData(); + }, + + /** + * Sets the inner radius of the Star shape. + * This call can be chained. + * + * @method Phaser.GameObjects.Star#setInnerRadius + * @since 3.13.0 + * + * @param {number} value - The amount to set the inner radius to. + * + * @return {this} This Game Object instance. + */ + setInnerRadius: function (value) + { + this._innerRadius = value; + + return this.updateData(); + }, + + /** + * Sets the outer radius of the Star shape. + * This call can be chained. + * + * @method Phaser.GameObjects.Star#setOuterRadius + * @since 3.13.0 + * + * @param {number} value - The amount to set the outer radius to. + * + * @return {this} This Game Object instance. + */ + setOuterRadius: function (value) + { + this._outerRadius = value; + + return this.updateData(); + }, + + /** + * The number of points that make up the Star shape. + * + * @name Phaser.GameObjects.Star#points + * @type {integer} + * @default 5 + * @since 3.13.0 + */ + points: { + + get: function () + { + return this._points; + }, + + set: function (value) + { + this._points = value; + + this.updateData(); + } + + }, + + /** + * The inner radius of the Star shape. + * + * @name Phaser.GameObjects.Star#innerRadius + * @type {number} + * @default 32 + * @since 3.13.0 + */ + innerRadius: { + + get: function () + { + return this._innerRadius; + }, + + set: function (value) + { + this._innerRadius = value; + + this.updateData(); + } + + }, + + /** + * The outer radius of the Star shape. + * + * @name Phaser.GameObjects.Star#outerRadius + * @type {number} + * @default 64 + * @since 3.13.0 + */ + outerRadius: { + + get: function () + { + return this._outerRadius; + }, + + set: function (value) + { + this._outerRadius = value; + + this.updateData(); + } + + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Star#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + + var points = this._points; + var innerRadius = this._innerRadius; + var outerRadius = this._outerRadius; + + var rot = Math.PI / 2 * 3; + var step = Math.PI / points; + + // So origin 0.5 = the center of the star + var x = outerRadius; + var y = outerRadius; + + path.push(x, y + -outerRadius); + + for (var i = 0; i < points; i++) + { + path.push(x + Math.cos(rot) * outerRadius, y + Math.sin(rot) * outerRadius); + + rot += step; + + path.push(x + Math.cos(rot) * innerRadius, y + Math.sin(rot) * innerRadius); + + rot += step; + } + + path.push(x, y + -outerRadius); + + this.pathIndexes = Earcut(path); + this.pathData = path; + + return this; + } + +}); + +module.exports = Star; diff --git a/src/gameobjects/shape/star/StarCanvasRenderer.js b/src/gameobjects/shape/star/StarCanvasRenderer.js index 834be1bab..cda8b89ff 100644 --- a/src/gameobjects/shape/star/StarCanvasRenderer.js +++ b/src/gameobjects/shape/star/StarCanvasRenderer.js @@ -1,79 +1,79 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Star#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Star} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var StarCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var path = src.pathData; - var pathLength = path.length - 1; - - var px1 = path[0] - dx; - var py1 = path[1] - dy; - - ctx.beginPath(); - - ctx.moveTo(px1, py1); - - if (!src.closePath) - { - pathLength -= 2; - } - - for (var i = 2; i < pathLength; i += 2) - { - var px2 = path[i] - dx; - var py2 = path[i + 1] - dy; - - ctx.lineTo(px2, py2); - } - - ctx.closePath(); - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fill(); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = StarCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Star#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Star} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var StarCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var path = src.pathData; + var pathLength = path.length - 1; + + var px1 = path[0] - dx; + var py1 = path[1] - dy; + + ctx.beginPath(); + + ctx.moveTo(px1, py1); + + if (!src.closePath) + { + pathLength -= 2; + } + + for (var i = 2; i < pathLength; i += 2) + { + var px2 = path[i] - dx; + var py2 = path[i + 1] - dy; + + ctx.lineTo(px2, py2); + } + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = StarCanvasRenderer; diff --git a/src/gameobjects/shape/star/StarFactory.js b/src/gameobjects/shape/star/StarFactory.js index 5d621acf4..fd9e8675a 100644 --- a/src/gameobjects/shape/star/StarFactory.js +++ b/src/gameobjects/shape/star/StarFactory.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Star = require('./Star'); -var GameObjectFactory = require('../../GameObjectFactory'); - -/** - * Creates a new Star Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Star Game Object has been built into Phaser. - * - * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * As the name implies, the Star shape will display a star in your game. You can control several - * aspects of it including the number of points that constitute the star. The default is 5. If - * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky - * star shape. - * - * You can also control the inner and outer radius, which is how 'long' each point of the star is. - * Modify these values to create more interesting shapes. - * - * @method Phaser.GameObjects.GameObjectFactory#star - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [points=5] - The number of points on the star. - * @param {number} [innerRadius=32] - The inner radius of the star. - * @param {number} [outerRadius=64] - The outer radius of the star. - * @param {number} [fillColor] - The color the star will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Star} The Game Object that was created. - */ -GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) -{ - return this.displayList.add(new Star(this.scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Star = require('./Star'); +var GameObjectFactory = require('../../GameObjectFactory'); + +/** + * Creates a new Star Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Star Game Object has been built into Phaser. + * + * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * As the name implies, the Star shape will display a star in your game. You can control several + * aspects of it including the number of points that constitute the star. The default is 5. If + * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky + * star shape. + * + * You can also control the inner and outer radius, which is how 'long' each point of the star is. + * Modify these values to create more interesting shapes. + * + * @method Phaser.GameObjects.GameObjectFactory#star + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [points=5] - The number of points on the star. + * @param {number} [innerRadius=32] - The inner radius of the star. + * @param {number} [outerRadius=64] - The outer radius of the star. + * @param {number} [fillColor] - The color the star will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Star} The Game Object that was created. + */ +GameObjectFactory.register('star', function (x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) +{ + return this.displayList.add(new Star(this.scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/star/StarRender.js b/src/gameobjects/shape/star/StarRender.js index 966db1331..82760766b 100644 --- a/src/gameobjects/shape/star/StarRender.js +++ b/src/gameobjects/shape/star/StarRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./StarWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./StarCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./StarWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./StarCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/star/StarWebGLRenderer.js b/src/gameobjects/shape/star/StarWebGLRenderer.js index 054fd6cc5..b3bb70913 100644 --- a/src/gameobjects/shape/star/StarWebGLRenderer.js +++ b/src/gameobjects/shape/star/StarWebGLRenderer.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillPathWebGL = require('../FillPathWebGL'); -var StrokePathWebGL = require('../StrokePathWebGL'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Star#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Star} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var StarWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = StarWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillPathWebGL = require('../FillPathWebGL'); +var StrokePathWebGL = require('../StrokePathWebGL'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Star#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Star} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var StarWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = StarWebGLRenderer; diff --git a/src/gameobjects/shape/triangle/Triangle.js b/src/gameobjects/shape/triangle/Triangle.js index d4446df6f..7dc4b3b57 100644 --- a/src/gameobjects/shape/triangle/Triangle.js +++ b/src/gameobjects/shape/triangle/Triangle.js @@ -1,137 +1,137 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Shape = require('../Shape'); -var GeomTriangle = require('../../../geom/triangle/Triangle'); -var TriangleRender = require('./TriangleRender'); - -/** - * @classdesc - * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the - * position of each point of these lines. The triangle is always closed and cannot have an open - * face. If you require that, consider using a Polygon instead. - * - * @class Triangle - * @extends Phaser.GameObjects.Shape - * @memberof Phaser.GameObjects - * @constructor - * @since 3.13.0 - * - * @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=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [x1=0] - The horizontal position of the first point in the triangle. - * @param {number} [y1=128] - The vertical position of the first point in the triangle. - * @param {number} [x2=64] - The horizontal position of the second point in the triangle. - * @param {number} [y2=0] - The vertical position of the second point in the triangle. - * @param {number} [x3=128] - The horizontal position of the third point in the triangle. - * @param {number} [y3=128] - The vertical position of the third point in the triangle. - * @param {number} [fillColor] - The color the triangle will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ -var Triangle = new Class({ - - Extends: Shape, - - Mixins: [ - TriangleRender - ], - - initialize: - - function Triangle (scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (x1 === undefined) { x1 = 0; } - if (y1 === undefined) { y1 = 128; } - if (x2 === undefined) { x2 = 64; } - if (y2 === undefined) { y2 = 0; } - if (x3 === undefined) { x3 = 128; } - if (y3 === undefined) { y3 = 128; } - - Shape.call(this, scene, 'Triangle', new GeomTriangle(x1, y1, x2, y2, x3, y3)); - - var width = this.geom.right - this.geom.left; - var height = this.geom.bottom - this.geom.top; - - this.setPosition(x, y); - this.setSize(width, height); - - if (fillColor !== undefined) - { - this.setFillStyle(fillColor, fillAlpha); - } - - this.updateDisplayOrigin(); - this.updateData(); - }, - - /** - * Sets the data for the lines that make up this Triangle shape. - * - * @method Phaser.GameObjects.Triangle#setTo - * @since 3.13.0 - * - * @param {number} [x1=0] - The horizontal position of the first point in the triangle. - * @param {number} [y1=0] - The vertical position of the first point in the triangle. - * @param {number} [x2=0] - The horizontal position of the second point in the triangle. - * @param {number} [y2=0] - The vertical position of the second point in the triangle. - * @param {number} [x3=0] - The horizontal position of the third point in the triangle. - * @param {number} [y3=0] - The vertical position of the third point in the triangle. - * - * @return {this} This Game Object instance. - */ - setTo: function (x1, y1, x2, y2, x3, y3) - { - this.geom.setTo(x1, y1, x2, y2, x3, y3); - - return this.updateData(); - }, - - /** - * Internal method that updates the data and path values. - * - * @method Phaser.GameObjects.Triangle#updateData - * @private - * @since 3.13.0 - * - * @return {this} This Game Object instance. - */ - updateData: function () - { - var path = []; - var tri = this.geom; - var line = this._tempLine; - - tri.getLineA(line); - - path.push(line.x1, line.y1, line.x2, line.y2); - - tri.getLineB(line); - - path.push(line.x2, line.y2); - - tri.getLineC(line); - - path.push(line.x2, line.y2); - - this.pathData = path; - - return this; - } - -}); - -module.exports = Triangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Shape = require('../Shape'); +var GeomTriangle = require('../../../geom/triangle/Triangle'); +var TriangleRender = require('./TriangleRender'); + +/** + * @classdesc + * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the + * position of each point of these lines. The triangle is always closed and cannot have an open + * face. If you require that, consider using a Polygon instead. + * + * @class Triangle + * @extends Phaser.GameObjects.Shape + * @memberof Phaser.GameObjects + * @constructor + * @since 3.13.0 + * + * @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=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the first point in the triangle. + * @param {number} [y1=128] - The vertical position of the first point in the triangle. + * @param {number} [x2=64] - The horizontal position of the second point in the triangle. + * @param {number} [y2=0] - The vertical position of the second point in the triangle. + * @param {number} [x3=128] - The horizontal position of the third point in the triangle. + * @param {number} [y3=128] - The vertical position of the third point in the triangle. + * @param {number} [fillColor] - The color the triangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ +var Triangle = new Class({ + + Extends: Shape, + + Mixins: [ + TriangleRender + ], + + initialize: + + function Triangle (scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 128; } + if (x2 === undefined) { x2 = 64; } + if (y2 === undefined) { y2 = 0; } + if (x3 === undefined) { x3 = 128; } + if (y3 === undefined) { y3 = 128; } + + Shape.call(this, scene, 'Triangle', new GeomTriangle(x1, y1, x2, y2, x3, y3)); + + var width = this.geom.right - this.geom.left; + var height = this.geom.bottom - this.geom.top; + + this.setPosition(x, y); + this.setSize(width, height); + + if (fillColor !== undefined) + { + this.setFillStyle(fillColor, fillAlpha); + } + + this.updateDisplayOrigin(); + this.updateData(); + }, + + /** + * Sets the data for the lines that make up this Triangle shape. + * + * @method Phaser.GameObjects.Triangle#setTo + * @since 3.13.0 + * + * @param {number} [x1=0] - The horizontal position of the first point in the triangle. + * @param {number} [y1=0] - The vertical position of the first point in the triangle. + * @param {number} [x2=0] - The horizontal position of the second point in the triangle. + * @param {number} [y2=0] - The vertical position of the second point in the triangle. + * @param {number} [x3=0] - The horizontal position of the third point in the triangle. + * @param {number} [y3=0] - The vertical position of the third point in the triangle. + * + * @return {this} This Game Object instance. + */ + setTo: function (x1, y1, x2, y2, x3, y3) + { + this.geom.setTo(x1, y1, x2, y2, x3, y3); + + return this.updateData(); + }, + + /** + * Internal method that updates the data and path values. + * + * @method Phaser.GameObjects.Triangle#updateData + * @private + * @since 3.13.0 + * + * @return {this} This Game Object instance. + */ + updateData: function () + { + var path = []; + var tri = this.geom; + var line = this._tempLine; + + tri.getLineA(line); + + path.push(line.x1, line.y1, line.x2, line.y2); + + tri.getLineB(line); + + path.push(line.x2, line.y2); + + tri.getLineC(line); + + path.push(line.x2, line.y2); + + this.pathData = path; + + return this; + } + +}); + +module.exports = Triangle; diff --git a/src/gameobjects/shape/triangle/TriangleCanvasRenderer.js b/src/gameobjects/shape/triangle/TriangleCanvasRenderer.js index dd577aafa..a01392096 100644 --- a/src/gameobjects/shape/triangle/TriangleCanvasRenderer.js +++ b/src/gameobjects/shape/triangle/TriangleCanvasRenderer.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FillStyleCanvas = require('../FillStyleCanvas'); -var LineStyleCanvas = require('../LineStyleCanvas'); -var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Triangle#renderCanvas - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Triangle} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var TriangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var ctx = renderer.currentContext; - - if (SetTransform(renderer, ctx, src, camera, parentMatrix)) - { - var dx = src._displayOriginX; - var dy = src._displayOriginY; - - var x1 = src.geom.x1 - dx; - var y1 = src.geom.y1 - dy; - var x2 = src.geom.x2 - dx; - var y2 = src.geom.y2 - dy; - var x3 = src.geom.x3 - dx; - var y3 = src.geom.y3 - dy; - - ctx.beginPath(); - - ctx.moveTo(x1, y1); - ctx.lineTo(x2, y2); - ctx.lineTo(x3, y3); - - ctx.closePath(); - - if (src.isFilled) - { - FillStyleCanvas(ctx, src); - - ctx.fill(); - } - - if (src.isStroked) - { - LineStyleCanvas(ctx, src); - - ctx.stroke(); - } - - // Restore the context saved in SetTransform - ctx.restore(); - } -}; - -module.exports = TriangleCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FillStyleCanvas = require('../FillStyleCanvas'); +var LineStyleCanvas = require('../LineStyleCanvas'); +var SetTransform = require('../../../renderer/canvas/utils/SetTransform'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Triangle#renderCanvas + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Triangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TriangleCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var ctx = renderer.currentContext; + + if (SetTransform(renderer, ctx, src, camera, parentMatrix)) + { + var dx = src._displayOriginX; + var dy = src._displayOriginY; + + var x1 = src.geom.x1 - dx; + var y1 = src.geom.y1 - dy; + var x2 = src.geom.x2 - dx; + var y2 = src.geom.y2 - dy; + var x3 = src.geom.x3 - dx; + var y3 = src.geom.y3 - dy; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.lineTo(x3, y3); + + ctx.closePath(); + + if (src.isFilled) + { + FillStyleCanvas(ctx, src); + + ctx.fill(); + } + + if (src.isStroked) + { + LineStyleCanvas(ctx, src); + + ctx.stroke(); + } + + // Restore the context saved in SetTransform + ctx.restore(); + } +}; + +module.exports = TriangleCanvasRenderer; diff --git a/src/gameobjects/shape/triangle/TriangleFactory.js b/src/gameobjects/shape/triangle/TriangleFactory.js index c5505a15c..0b30d5c40 100644 --- a/src/gameobjects/shape/triangle/TriangleFactory.js +++ b/src/gameobjects/shape/triangle/TriangleFactory.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../../GameObjectFactory'); -var Triangle = require('./Triangle'); - -/** - * Creates a new Triangle Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Triangle Game Object has been built into Phaser. - * - * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the - * position of each point of these lines. The triangle is always closed and cannot have an open - * face. If you require that, consider using a Polygon instead. - * - * @method Phaser.GameObjects.GameObjectFactory#triangle - * @since 3.13.0 - * - * @param {number} [x=0] - The horizontal position of this Game Object in the world. - * @param {number} [y=0] - The vertical position of this Game Object in the world. - * @param {number} [x1=0] - The horizontal position of the first point in the triangle. - * @param {number} [y1=128] - The vertical position of the first point in the triangle. - * @param {number} [x2=64] - The horizontal position of the second point in the triangle. - * @param {number} [y2=0] - The vertical position of the second point in the triangle. - * @param {number} [x3=128] - The horizontal position of the third point in the triangle. - * @param {number} [y3=128] - The vertical position of the third point in the triangle. - * @param {number} [fillColor] - The color the triangle will be filled with, i.e. 0xff0000 for red. - * @param {number} [fillAlpha] - The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * - * @return {Phaser.GameObjects.Triangle} The Game Object that was created. - */ -GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) -{ - return this.displayList.add(new Triangle(this.scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha)); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../../GameObjectFactory'); +var Triangle = require('./Triangle'); + +/** + * Creates a new Triangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Triangle Game Object has been built into Phaser. + * + * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the + * position of each point of these lines. The triangle is always closed and cannot have an open + * face. If you require that, consider using a Polygon instead. + * + * @method Phaser.GameObjects.GameObjectFactory#triangle + * @since 3.13.0 + * + * @param {number} [x=0] - The horizontal position of this Game Object in the world. + * @param {number} [y=0] - The vertical position of this Game Object in the world. + * @param {number} [x1=0] - The horizontal position of the first point in the triangle. + * @param {number} [y1=128] - The vertical position of the first point in the triangle. + * @param {number} [x2=64] - The horizontal position of the second point in the triangle. + * @param {number} [y2=0] - The vertical position of the second point in the triangle. + * @param {number} [x3=128] - The horizontal position of the third point in the triangle. + * @param {number} [y3=128] - The vertical position of the third point in the triangle. + * @param {number} [fillColor] - The color the triangle will be filled with, i.e. 0xff0000 for red. + * @param {number} [fillAlpha] - The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * + * @return {Phaser.GameObjects.Triangle} The Game Object that was created. + */ +GameObjectFactory.register('triangle', function (x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) +{ + return this.displayList.add(new Triangle(this.scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha)); +}); diff --git a/src/gameobjects/shape/triangle/TriangleRender.js b/src/gameobjects/shape/triangle/TriangleRender.js index d92eba5cd..4b48ff34d 100644 --- a/src/gameobjects/shape/triangle/TriangleRender.js +++ b/src/gameobjects/shape/triangle/TriangleRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./TriangleWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./TriangleCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./TriangleWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./TriangleCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/shape/triangle/TriangleWebGLRenderer.js b/src/gameobjects/shape/triangle/TriangleWebGLRenderer.js index 9b6a1a1c6..461844fb7 100644 --- a/src/gameobjects/shape/triangle/TriangleWebGLRenderer.js +++ b/src/gameobjects/shape/triangle/TriangleWebGLRenderer.js @@ -1,97 +1,97 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var StrokePathWebGL = require('../StrokePathWebGL'); -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Triangle#renderWebGL - * @since 3.13.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Triangle} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var TriangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - var pipeline = this.pipeline; - - var camMatrix = pipeline._tempMatrix1; - var shapeMatrix = pipeline._tempMatrix2; - var calcMatrix = pipeline._tempMatrix3; - - renderer.setPipeline(pipeline); - - shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - shapeMatrix.e = src.x; - shapeMatrix.f = src.y; - } - else - { - shapeMatrix.e -= camera.scrollX * src.scrollFactorX; - shapeMatrix.f -= camera.scrollY * src.scrollFactorY; - } - - camMatrix.multiply(shapeMatrix, calcMatrix); - - var dx = src._displayOriginX; - var dy = src._displayOriginY; - var alpha = camera.alpha * src.alpha; - - if (src.isFilled) - { - var fillTint = pipeline.fillTint; - var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); - - fillTint.TL = fillTintColor; - fillTint.TR = fillTintColor; - fillTint.BL = fillTintColor; - fillTint.BR = fillTintColor; - - var x1 = src.geom.x1 - dx; - var y1 = src.geom.y1 - dy; - var x2 = src.geom.x2 - dx; - var y2 = src.geom.y2 - dy; - var x3 = src.geom.x3 - dx; - var y3 = src.geom.y3 - dy; - - pipeline.setTexture2D(); - - pipeline.batchFillTriangle( - x1, - y1, - x2, - y2, - x3, - y3, - shapeMatrix, - camMatrix - ); - } - - if (src.isStroked) - { - StrokePathWebGL(pipeline, src, alpha, dx, dy); - } -}; - -module.exports = TriangleWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var StrokePathWebGL = require('../StrokePathWebGL'); +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Triangle#renderWebGL + * @since 3.13.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Triangle} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TriangleWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + var pipeline = this.pipeline; + + var camMatrix = pipeline._tempMatrix1; + var shapeMatrix = pipeline._tempMatrix2; + var calcMatrix = pipeline._tempMatrix3; + + renderer.setPipeline(pipeline); + + shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + shapeMatrix.e = src.x; + shapeMatrix.f = src.y; + } + else + { + shapeMatrix.e -= camera.scrollX * src.scrollFactorX; + shapeMatrix.f -= camera.scrollY * src.scrollFactorY; + } + + camMatrix.multiply(shapeMatrix, calcMatrix); + + var dx = src._displayOriginX; + var dy = src._displayOriginY; + var alpha = camera.alpha * src.alpha; + + if (src.isFilled) + { + var fillTint = pipeline.fillTint; + var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); + + fillTint.TL = fillTintColor; + fillTint.TR = fillTintColor; + fillTint.BL = fillTintColor; + fillTint.BR = fillTintColor; + + var x1 = src.geom.x1 - dx; + var y1 = src.geom.y1 - dy; + var x2 = src.geom.x2 - dx; + var y2 = src.geom.y2 - dy; + var x3 = src.geom.x3 - dx; + var y3 = src.geom.y3 - dy; + + pipeline.setTexture2D(); + + pipeline.batchFillTriangle( + x1, + y1, + x2, + y2, + x3, + y3, + shapeMatrix, + camMatrix + ); + } + + if (src.isStroked) + { + StrokePathWebGL(pipeline, src, alpha, dx, dy); + } +}; + +module.exports = TriangleWebGLRenderer; diff --git a/src/gameobjects/sprite/Sprite.js b/src/gameobjects/sprite/Sprite.js index 0035eabd9..970140078 100644 --- a/src/gameobjects/sprite/Sprite.js +++ b/src/gameobjects/sprite/Sprite.js @@ -1,172 +1,172 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var SpriteRender = require('./SpriteRender'); - -/** - * @classdesc - * A Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * - * @class Sprite - * @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.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Mask - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var Sprite = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - SpriteRender - ], - - initialize: - - function Sprite (scene, x, y, texture, frame) - { - GameObject.call(this, scene, 'Sprite'); - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.Sprite#_crop - * @type {object} - * @private - * @since 3.11.0 - */ - this._crop = this.resetCropObject(); - - /** - * The Animation Controller of this Sprite. - * - * @name Phaser.GameObjects.Sprite#anims - * @type {Phaser.GameObjects.Components.Animation} - * @since 3.0.0 - */ - this.anims = new Components.Animation(this); - - this.setTexture(texture, frame); - this.setPosition(x, y); - this.setSizeToFrame(); - this.setOriginFromFrame(); - this.initPipeline(); - }, - - /** - * Update this Sprite's animations. - * - * @method Phaser.GameObjects.Sprite#preUpdate - * @protected - * @since 3.0.0 - * - * @param {number} time - The current timestamp. - * @param {number} delta - The delta time, in ms, elapsed since the last frame. - */ - preUpdate: function (time, delta) - { - this.anims.update(time, delta); - }, - - /** - * Start playing the given animation. - * - * @method Phaser.GameObjects.Sprite#play - * @since 3.0.0 - * - * @param {string} key - The string-based key of the animation to play. - * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. - * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. - * - * @return {this} This Game Object. - */ - play: function (key, ignoreIfPlaying, startFrame) - { - this.anims.play(key, ignoreIfPlaying, startFrame); - - return this; - }, - - /** - * Build a JSON representation of this Sprite. - * - * @method Phaser.GameObjects.Sprite#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. - */ - toJSON: function () - { - var data = Components.ToJSON(this); - - // Extra Sprite data is added here - - return data; - }, - - /** - * Handles the pre-destroy step for the Sprite, which removes the Animation component. - * - * @method Phaser.GameObjects.Sprite#preDestroy - * @private - * @since 3.14.0 - */ - preDestroy: function () - { - this.anims.destroy(); - - this.anims = undefined; - } - -}); - -module.exports = Sprite; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var SpriteRender = require('./SpriteRender'); + +/** + * @classdesc + * A Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class Sprite + * @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.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Mask + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var Sprite = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + SpriteRender + ], + + initialize: + + function Sprite (scene, x, y, texture, frame) + { + GameObject.call(this, scene, 'Sprite'); + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Sprite#_crop + * @type {object} + * @private + * @since 3.11.0 + */ + this._crop = this.resetCropObject(); + + /** + * The Animation Controller of this Sprite. + * + * @name Phaser.GameObjects.Sprite#anims + * @type {Phaser.GameObjects.Components.Animation} + * @since 3.0.0 + */ + this.anims = new Components.Animation(this); + + this.setTexture(texture, frame); + this.setPosition(x, y); + this.setSizeToFrame(); + this.setOriginFromFrame(); + this.initPipeline(); + }, + + /** + * Update this Sprite's animations. + * + * @method Phaser.GameObjects.Sprite#preUpdate + * @protected + * @since 3.0.0 + * + * @param {number} time - The current timestamp. + * @param {number} delta - The delta time, in ms, elapsed since the last frame. + */ + preUpdate: function (time, delta) + { + this.anims.update(time, delta); + }, + + /** + * Start playing the given animation. + * + * @method Phaser.GameObjects.Sprite#play + * @since 3.0.0 + * + * @param {string} key - The string-based key of the animation to play. + * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call. + * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index. + * + * @return {this} This Game Object. + */ + play: function (key, ignoreIfPlaying, startFrame) + { + this.anims.play(key, ignoreIfPlaying, startFrame); + + return this; + }, + + /** + * Build a JSON representation of this Sprite. + * + * @method Phaser.GameObjects.Sprite#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object. + */ + toJSON: function () + { + var data = Components.ToJSON(this); + + // Extra Sprite data is added here + + return data; + }, + + /** + * Handles the pre-destroy step for the Sprite, which removes the Animation component. + * + * @method Phaser.GameObjects.Sprite#preDestroy + * @private + * @since 3.14.0 + */ + preDestroy: function () + { + this.anims.destroy(); + + this.anims = undefined; + } + +}); + +module.exports = Sprite; diff --git a/src/gameobjects/sprite/SpriteCanvasRenderer.js b/src/gameobjects/sprite/SpriteCanvasRenderer.js index 39d8f05c7..bc3757660 100644 --- a/src/gameobjects/sprite/SpriteCanvasRenderer.js +++ b/src/gameobjects/sprite/SpriteCanvasRenderer.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Sprite#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var SpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - renderer.batchSprite(src, src.frame, camera, parentMatrix); -}; - -module.exports = SpriteCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Sprite#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var SpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = SpriteCanvasRenderer; diff --git a/src/gameobjects/sprite/SpriteCreator.js b/src/gameobjects/sprite/SpriteCreator.js index 1129522d4..54c7763e7 100644 --- a/src/gameobjects/sprite/SpriteCreator.js +++ b/src/gameobjects/sprite/SpriteCreator.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var BuildGameObjectAnimation = require('../BuildGameObjectAnimation'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var Sprite = require('./Sprite'); - -/** - * Creates a new Sprite Game Object and returns it. - * - * Note: This method will only be available if the Sprite Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#sprite - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} 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.Sprite} The Game Object that was created. - */ -GameObjectCreator.register('sprite', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - var frame = GetAdvancedValue(config, 'frame', null); - - var sprite = new Sprite(this.scene, 0, 0, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, sprite, config); - - // Sprite specific config options: - - BuildGameObjectAnimation(sprite, config); - - return sprite; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var BuildGameObjectAnimation = require('../BuildGameObjectAnimation'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var Sprite = require('./Sprite'); + +/** + * Creates a new Sprite Game Object and returns it. + * + * Note: This method will only be available if the Sprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#sprite + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} 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.Sprite} The Game Object that was created. + */ +GameObjectCreator.register('sprite', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + var frame = GetAdvancedValue(config, 'frame', null); + + var sprite = new Sprite(this.scene, 0, 0, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, sprite, config); + + // Sprite specific config options: + + BuildGameObjectAnimation(sprite, config); + + return sprite; +}); diff --git a/src/gameobjects/sprite/SpriteFactory.js b/src/gameobjects/sprite/SpriteFactory.js index 1db62f293..66028ad37 100644 --- a/src/gameobjects/sprite/SpriteFactory.js +++ b/src/gameobjects/sprite/SpriteFactory.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../GameObjectFactory'); -var Sprite = require('./Sprite'); - -/** - * Creates a new Sprite Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Sprite Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#sprite - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.Sprite} The Game Object that was created. - */ -GameObjectFactory.register('sprite', function (x, y, key, frame) -{ - var sprite = new Sprite(this.scene, x, y, key, frame); - - this.displayList.add(sprite); - this.updateList.add(sprite); - - return sprite; -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../GameObjectFactory'); +var Sprite = require('./Sprite'); + +/** + * Creates a new Sprite Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Sprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#sprite + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Sprite} The Game Object that was created. + */ +GameObjectFactory.register('sprite', function (x, y, key, frame) +{ + var sprite = new Sprite(this.scene, x, y, key, frame); + + this.displayList.add(sprite); + this.updateList.add(sprite); + + return sprite; +}); + +// 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 diff --git a/src/gameobjects/sprite/SpriteRender.js b/src/gameobjects/sprite/SpriteRender.js index 5a4fcbeca..620173aff 100644 --- a/src/gameobjects/sprite/SpriteRender.js +++ b/src/gameobjects/sprite/SpriteRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./SpriteWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./SpriteCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./SpriteWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./SpriteCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/sprite/SpriteWebGLRenderer.js b/src/gameobjects/sprite/SpriteWebGLRenderer.js index 93ed5ee9d..cf6bf4462 100644 --- a/src/gameobjects/sprite/SpriteWebGLRenderer.js +++ b/src/gameobjects/sprite/SpriteWebGLRenderer.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Sprite#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var SpriteWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - this.pipeline.batchSprite(src, camera, parentMatrix); -}; - -module.exports = SpriteWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Sprite#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var SpriteWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + this.pipeline.batchSprite(src, camera, parentMatrix); +}; + +module.exports = SpriteWebGLRenderer; diff --git a/src/gameobjects/sprite/typedefs/index.js b/src/gameobjects/sprite/typedefs/index.js index 21cbeda72..74b066a15 100644 --- a/src/gameobjects/sprite/typedefs/index.js +++ b/src/gameobjects/sprite/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.Sprite - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.Sprite + */ diff --git a/src/gameobjects/text/GetTextSize.js b/src/gameobjects/text/GetTextSize.js index af1626b8c..a43d08d59 100644 --- a/src/gameobjects/text/GetTextSize.js +++ b/src/gameobjects/text/GetTextSize.js @@ -1,76 +1,76 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns an object containing dimensions of the Text object. - * - * @function Phaser.GameObjects.Text.GetTextSize - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Text} text - The Text object to calculate the size from. - * @param {Phaser.Types.GameObjects.Text.TextMetrics} size - The Text metrics to use when calculating the size. - * @param {array} lines - The lines of text to calculate the size from. - * - * @return {object} An object containing dimensions of the Text object. - */ -var GetTextSize = function (text, size, lines) -{ - var canvas = text.canvas; - var context = text.context; - var style = text.style; - - var lineWidths = []; - var maxLineWidth = 0; - var drawnLines = lines.length; - - if (style.maxLines > 0 && style.maxLines < lines.length) - { - drawnLines = style.maxLines; - } - - style.syncFont(canvas, context); - - // Text Width - - for (var i = 0; i < drawnLines; i++) - { - var lineWidth = style.strokeThickness; - - lineWidth += context.measureText(lines[i]).width; - - // Adjust for wrapped text - if (style.wordWrap) - { - lineWidth -= context.measureText(' ').width; - } - - lineWidths[i] = Math.ceil(lineWidth); - maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); - } - - // Text Height - - var lineHeight = size.fontSize + style.strokeThickness; - var height = lineHeight * drawnLines; - var lineSpacing = text.lineSpacing; - - // Adjust for line spacing - if (drawnLines > 1) - { - height += lineSpacing * (drawnLines - 1); - } - - return { - width: maxLineWidth, - height: height, - lines: drawnLines, - lineWidths: lineWidths, - lineSpacing: lineSpacing, - lineHeight: lineHeight - }; -}; - -module.exports = GetTextSize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns an object containing dimensions of the Text object. + * + * @function Phaser.GameObjects.Text.GetTextSize + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Text} text - The Text object to calculate the size from. + * @param {Phaser.Types.GameObjects.Text.TextMetrics} size - The Text metrics to use when calculating the size. + * @param {array} lines - The lines of text to calculate the size from. + * + * @return {object} An object containing dimensions of the Text object. + */ +var GetTextSize = function (text, size, lines) +{ + var canvas = text.canvas; + var context = text.context; + var style = text.style; + + var lineWidths = []; + var maxLineWidth = 0; + var drawnLines = lines.length; + + if (style.maxLines > 0 && style.maxLines < lines.length) + { + drawnLines = style.maxLines; + } + + style.syncFont(canvas, context); + + // Text Width + + for (var i = 0; i < drawnLines; i++) + { + var lineWidth = style.strokeThickness; + + lineWidth += context.measureText(lines[i]).width; + + // Adjust for wrapped text + if (style.wordWrap) + { + lineWidth -= context.measureText(' ').width; + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + // Text Height + + var lineHeight = size.fontSize + style.strokeThickness; + var height = lineHeight * drawnLines; + var lineSpacing = text.lineSpacing; + + // Adjust for line spacing + if (drawnLines > 1) + { + height += lineSpacing * (drawnLines - 1); + } + + return { + width: maxLineWidth, + height: height, + lines: drawnLines, + lineWidths: lineWidths, + lineSpacing: lineSpacing, + lineHeight: lineHeight + }; +}; + +module.exports = GetTextSize; diff --git a/src/gameobjects/text/MeasureText.js b/src/gameobjects/text/MeasureText.js index 331542861..f215e2d36 100644 --- a/src/gameobjects/text/MeasureText.js +++ b/src/gameobjects/text/MeasureText.js @@ -1,129 +1,129 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../../display/canvas/CanvasPool'); - -/** - * Calculates the ascent, descent and fontSize of a given font style. - * - * @function Phaser.GameObjects.Text.MeasureText - * @since 3.0.0 - * - * @param {Phaser.GameObjects.TextStyle} textStyle - The TextStyle object to measure. - * - * @return {Phaser.Types.GameObjects.Text.TextMetrics} An object containing the ascent, descent and fontSize of the TextStyle. - */ -var MeasureText = function (textStyle) -{ - // @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. - var canvas = CanvasPool.create(this); - - // @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. - var context = canvas.getContext('2d'); - - textStyle.syncFont(canvas, context); - - var width = Math.ceil(context.measureText(textStyle.testString).width * textStyle.baselineX); - var baseline = width; - var height = 2 * baseline; - - baseline = baseline * textStyle.baselineY | 0; - - canvas.width = width; - canvas.height = height; - - context.fillStyle = '#f00'; - context.fillRect(0, 0, width, height); - - context.font = textStyle._font; - - context.textBaseline = 'alphabetic'; - context.fillStyle = '#000'; - context.fillText(textStyle.testString, 0, baseline); - - var output = { - ascent: 0, - descent: 0, - fontSize: 0 - }; - - if (!context.getImageData(0, 0, width, height)) - { - output.ascent = baseline; - output.descent = baseline + 6; - output.fontSize = output.ascent + output.descent; - - CanvasPool.remove(canvas); - - return output; - } - - var imagedata = context.getImageData(0, 0, width, height).data; - var pixels = imagedata.length; - var line = width * 4; - var i; - var j; - var idx = 0; - var stop = false; - - // ascent. scan from top to bottom until we find a non red pixel - for (i = 0; i < baseline; i++) - { - for (j = 0; j < line; j += 4) - { - if (imagedata[idx + j] !== 255) - { - stop = true; - break; - } - } - - if (!stop) - { - idx += line; - } - else - { - break; - } - } - - output.ascent = baseline - i; - - idx = pixels - line; - stop = false; - - // descent. scan from bottom to top until we find a non red pixel - for (i = height; i > baseline; i--) - { - for (j = 0; j < line; j += 4) - { - if (imagedata[idx + j] !== 255) - { - stop = true; - break; - } - } - - if (!stop) - { - idx -= line; - } - else - { - break; - } - } - - output.descent = (i - baseline); - output.fontSize = output.ascent + output.descent; - - CanvasPool.remove(canvas); - - return output; -}; - -module.exports = MeasureText; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../../display/canvas/CanvasPool'); + +/** + * Calculates the ascent, descent and fontSize of a given font style. + * + * @function Phaser.GameObjects.Text.MeasureText + * @since 3.0.0 + * + * @param {Phaser.GameObjects.TextStyle} textStyle - The TextStyle object to measure. + * + * @return {Phaser.Types.GameObjects.Text.TextMetrics} An object containing the ascent, descent and fontSize of the TextStyle. + */ +var MeasureText = function (textStyle) +{ + // @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + var canvas = CanvasPool.create(this); + + // @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + var context = canvas.getContext('2d'); + + textStyle.syncFont(canvas, context); + + var width = Math.ceil(context.measureText(textStyle.testString).width * textStyle.baselineX); + var baseline = width; + var height = 2 * baseline; + + baseline = baseline * textStyle.baselineY | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = textStyle._font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(textStyle.testString, 0, baseline); + + var output = { + ascent: 0, + descent: 0, + fontSize: 0 + }; + + if (!context.getImageData(0, 0, width, height)) + { + output.ascent = baseline; + output.descent = baseline + 6; + output.fontSize = output.ascent + output.descent; + + CanvasPool.remove(canvas); + + return output; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + var i; + var j; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + output.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + output.descent = (i - baseline); + output.fontSize = output.ascent + output.descent; + + CanvasPool.remove(canvas); + + return output; +}; + +module.exports = MeasureText; diff --git a/src/gameobjects/text/TextStyle.js b/src/gameobjects/text/TextStyle.js index 18336afc8..55d898b1b 100644 --- a/src/gameobjects/text/TextStyle.js +++ b/src/gameobjects/text/TextStyle.js @@ -1,1047 +1,1047 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetValue = require('../../utils/object/GetValue'); -var MeasureText = require('./MeasureText'); - -// Key: [ Object Key, Default Value ] - -var propertyMap = { - fontFamily: [ 'fontFamily', 'Courier' ], - fontSize: [ 'fontSize', '16px' ], - fontStyle: [ 'fontStyle', '' ], - backgroundColor: [ 'backgroundColor', null ], - color: [ 'color', '#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', 0 ], - fixedHeight: [ 'fixedHeight', 0 ], - resolution: [ 'resolution', 0 ], - rtl: [ 'rtl', false ], - testString: [ 'testString', '|MÉqgy' ], - baselineX: [ 'baselineX', 1.2 ], - baselineY: [ 'baselineY', 1.4 ], - wordWrapWidth: [ 'wordWrap.width', null ], - wordWrapCallback: [ 'wordWrap.callback', null ], - wordWrapCallbackScope: [ 'wordWrap.callbackScope', null ], - wordWrapUseAdvanced: [ 'wordWrap.useAdvancedWrap', false ] -}; - -/** - * @classdesc - * A TextStyle class manages all of the style settings for a Text object. - * - * Text Game Objects create a TextStyle instance automatically, which is - * accessed via the `Text.style` property. You do not normally need to - * instantiate one yourself. - * - * @class TextStyle - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Text} text - The Text object that this TextStyle is styling. - * @param {Phaser.Types.GameObjects.Text.TextStyle} style - The style settings to set. - */ -var TextStyle = new Class({ - - initialize: - - function TextStyle (text, style) - { - /** - * The Text object that this TextStyle is styling. - * - * @name Phaser.GameObjects.TextStyle#parent - * @type {Phaser.GameObjects.Text} - * @since 3.0.0 - */ - this.parent = text; - - /** - * The font family. - * - * @name Phaser.GameObjects.TextStyle#fontFamily - * @type {string} - * @default 'Courier' - * @since 3.0.0 - */ - this.fontFamily; - - /** - * The font size. - * - * @name Phaser.GameObjects.TextStyle#fontSize - * @type {string} - * @default '16px' - * @since 3.0.0 - */ - this.fontSize; - - /** - * The font style. - * - * @name Phaser.GameObjects.TextStyle#fontStyle - * @type {string} - * @since 3.0.0 - */ - this.fontStyle; - - /** - * The background color. - * - * @name Phaser.GameObjects.TextStyle#backgroundColor - * @type {string} - * @since 3.0.0 - */ - this.backgroundColor; - - /** - * The text fill color. - * - * @name Phaser.GameObjects.TextStyle#color - * @type {string} - * @default '#fff' - * @since 3.0.0 - */ - this.color; - - /** - * The text stroke color. - * - * @name Phaser.GameObjects.TextStyle#stroke - * @type {string} - * @default '#fff' - * @since 3.0.0 - */ - this.stroke; - - /** - * The text stroke thickness. - * - * @name Phaser.GameObjects.TextStyle#strokeThickness - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.strokeThickness; - - /** - * The horizontal shadow offset. - * - * @name Phaser.GameObjects.TextStyle#shadowOffsetX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.shadowOffsetX; - - /** - * The vertical shadow offset. - * - * @name Phaser.GameObjects.TextStyle#shadowOffsetY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.shadowOffsetY; - - /** - * The shadow color. - * - * @name Phaser.GameObjects.TextStyle#shadowColor - * @type {string} - * @default '#000' - * @since 3.0.0 - */ - this.shadowColor; - - /** - * The shadow blur radius. - * - * @name Phaser.GameObjects.TextStyle#shadowBlur - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.shadowBlur; - - /** - * Whether shadow stroke is enabled or not. - * - * @name Phaser.GameObjects.TextStyle#shadowStroke - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.shadowStroke; - - /** - * Whether shadow fill is enabled or not. - * - * @name Phaser.GameObjects.TextStyle#shadowFill - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.shadowFill; - - /** - * The text alignment. - * - * @name Phaser.GameObjects.TextStyle#align - * @type {string} - * @default 'left' - * @since 3.0.0 - */ - this.align; - - /** - * The maximum number of lines to draw. - * - * @name Phaser.GameObjects.TextStyle#maxLines - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.maxLines; - - /** - * The fixed width of the text. - * - * `0` means no fixed with. - * - * @name Phaser.GameObjects.TextStyle#fixedWidth - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.fixedWidth; - - /** - * The fixed height of the text. - * - * `0` means no fixed height. - * - * @name Phaser.GameObjects.TextStyle#fixedHeight - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.fixedHeight; - - /** - * The resolution the text is rendered to its internal canvas at. - * The default is 0, which means it will use the resolution set in the Game Config. - * - * @name Phaser.GameObjects.TextStyle#resolution - * @type {number} - * @default 0 - * @since 3.12.0 - */ - this.resolution; - - /** - * Whether the text should render right to left. - * - * @name Phaser.GameObjects.TextStyle#rtl - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.rtl; - - /** - * The test string to use when measuring the font. - * - * @name Phaser.GameObjects.TextStyle#testString - * @type {string} - * @default '|MÉqgy' - * @since 3.0.0 - */ - this.testString; - - /** - * The amount of horizontal padding added to the width of the text when calculating the font metrics. - * - * @name Phaser.GameObjects.TextStyle#baselineX - * @type {number} - * @default 1.2 - * @since 3.3.0 - */ - this.baselineX; - - /** - * The amount of vertical padding added to the height of the text when calculating the font metrics. - * - * @name Phaser.GameObjects.TextStyle#baselineY - * @type {number} - * @default 1.4 - * @since 3.3.0 - */ - this.baselineY; - - /** - * The font style, size and family. - * - * @name Phaser.GameObjects.TextStyle#_font - * @type {string} - * @private - * @since 3.0.0 - */ - this._font; - - // Set to defaults + user style - this.setStyle(style, false, true); - - var metrics = GetValue(style, 'metrics', false); - - // 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 - if (metrics) - { - this.metrics = { - ascent: GetValue(metrics, 'ascent', 0), - descent: GetValue(metrics, 'descent', 0), - fontSize: GetValue(metrics, 'fontSize', 0) - }; - } - else - { - this.metrics = MeasureText(this); - } - }, - - /** - * Set the text style. - * - * @example - * text.setStyle({ - * fontSize: '64px', - * fontFamily: 'Arial', - * color: '#ffffff', - * align: 'center', - * backgroundColor: '#ff00ff' - * }); - * - * @method Phaser.GameObjects.TextStyle#setStyle - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.Text.TextStyle} style - The style settings to set. - * @param {boolean} [updateText=true] - Whether to update the text immediately. - * @param {boolean} [setDefaults=false] - Use the default values is not set, or the local values. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setStyle: function (style, updateText, setDefaults) - { - if (updateText === undefined) { updateText = true; } - if (setDefaults === undefined) { setDefaults = false; } - - // Avoid type mutation - if (style && style.hasOwnProperty('fontSize') && typeof style.fontSize === 'number') - { - style.fontSize = style.fontSize.toString() + 'px'; - } - - for (var key in propertyMap) - { - var value = (setDefaults) ? propertyMap[key][1] : this[key]; - - if (key === 'wordWrapCallback' || key === 'wordWrapCallbackScope') - { - // Callback & scope should be set without processing the values - this[key] = GetValue(style, propertyMap[key][0], value); - } - else - { - this[key] = GetAdvancedValue(style, propertyMap[key][0], value); - } - } - - // Allow for 'font' override - var font = GetValue(style, 'font', null); - - if (font !== null) - { - this.setFont(font, false); - } - - this._font = [ this.fontStyle, this.fontSize, this.fontFamily ].join(' ').trim(); - - // Allow for 'fill' to be used in place of 'color' - var fill = GetValue(style, 'fill', null); - - if (fill !== null) - { - this.color = fill; - } - - if (updateText) - { - return this.update(true); - } - else - { - return this.parent; - } - }, - - /** - * Synchronize the font settings to the given Canvas Rendering Context. - * - * @method Phaser.GameObjects.TextStyle#syncFont - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The Canvas Element. - * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. - */ - syncFont: function (canvas, context) - { - context.font = this._font; - }, - - /** - * Synchronize the text style settings to the given Canvas Rendering Context. - * - * @method Phaser.GameObjects.TextStyle#syncStyle - * @since 3.0.0 - * - * @param {HTMLCanvasElement} canvas - The Canvas Element. - * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. - */ - syncStyle: function (canvas, context) - { - context.textBaseline = 'alphabetic'; - - context.fillStyle = this.color; - context.strokeStyle = this.stroke; - - context.lineWidth = this.strokeThickness; - context.lineCap = 'round'; - context.lineJoin = 'round'; - }, - - /** - * Synchronize the shadow settings to the given Canvas Rendering Context. - * - * @method Phaser.GameObjects.TextStyle#syncShadow - * @since 3.0.0 - * - * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. - * @param {boolean} enabled - Whether shadows are enabled or not. - */ - syncShadow: function (context, enabled) - { - if (enabled) - { - context.shadowOffsetX = this.shadowOffsetX; - context.shadowOffsetY = this.shadowOffsetY; - context.shadowColor = this.shadowColor; - context.shadowBlur = this.shadowBlur; - } - else - { - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - context.shadowColor = 0; - context.shadowBlur = 0; - } - }, - - /** - * Update the style settings for the parent Text object. - * - * @method Phaser.GameObjects.TextStyle#update - * @since 3.0.0 - * - * @param {boolean} recalculateMetrics - Whether to recalculate font and text metrics. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - update: function (recalculateMetrics) - { - if (recalculateMetrics) - { - this._font = [ this.fontStyle, this.fontSize, this.fontFamily ].join(' ').trim(); - - this.metrics = MeasureText(this); - } - - return this.parent.updateText(); - }, - - /** - * 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. - * - * @method Phaser.GameObjects.TextStyle#setFont - * @since 3.0.0 - * - * @param {(string|object)} font - The font family or font settings to set. - * @param {boolean} [updateText=true] - Whether to update the text immediately. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setFont: function (font, updateText) - { - if (updateText === undefined) { updateText = true; } - - var fontFamily = font; - var fontSize = ''; - var fontStyle = ''; - - if (typeof font !== 'string') - { - fontFamily = GetValue(font, 'fontFamily', 'Courier'); - fontSize = GetValue(font, 'fontSize', '16px'); - fontStyle = GetValue(font, 'fontStyle', ''); - } - else - { - var fontSplit = font.split(' '); - - var i = 0; - - fontStyle = (fontSplit.length > 2) ? fontSplit[i++] : ''; - fontSize = fontSplit[i++] || '16px'; - fontFamily = fontSplit[i++] || 'Courier'; - } - - if (fontFamily !== this.fontFamily || fontSize !== this.fontSize || fontStyle !== this.fontStyle) - { - this.fontFamily = fontFamily; - this.fontSize = fontSize; - this.fontStyle = fontStyle; - - if (updateText) - { - this.update(true); - } - } - - return this.parent; - }, - - /** - * Set the font family. - * - * @method Phaser.GameObjects.TextStyle#setFontFamily - * @since 3.0.0 - * - * @param {string} family - The font family. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setFontFamily: function (family) - { - if (this.fontFamily !== family) - { - this.fontFamily = family; - - this.update(true); - } - - return this.parent; - }, - - /** - * Set the font style. - * - * @method Phaser.GameObjects.TextStyle#setFontStyle - * @since 3.0.0 - * - * @param {string} style - The font style. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setFontStyle: function (style) - { - if (this.fontStyle !== style) - { - this.fontStyle = style; - - this.update(true); - } - - return this.parent; - }, - - /** - * Set the font size. - * - * @method Phaser.GameObjects.TextStyle#setFontSize - * @since 3.0.0 - * - * @param {(number|string)} size - The font size. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setFontSize: function (size) - { - if (typeof size === 'number') - { - size = size.toString() + 'px'; - } - - if (this.fontSize !== size) - { - this.fontSize = size; - - this.update(true); - } - - return this.parent; - }, - - /** - * Set the test string to use when measuring the font. - * - * @method Phaser.GameObjects.TextStyle#setTestString - * @since 3.0.0 - * - * @param {string} string - The test string to use when measuring the font. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setTestString: function (string) - { - this.testString = string; - - return this.update(true); - }, - - /** - * Set a fixed width and height for the text. - * - * Pass in `0` for either of these parameters to disable fixed width or height respectively. - * - * @method Phaser.GameObjects.TextStyle#setFixedSize - * @since 3.0.0 - * - * @param {number} width - The fixed width to set. - * @param {number} height - The fixed height to set. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setFixedSize: function (width, height) - { - this.fixedWidth = width; - this.fixedHeight = height; - - if (width) - { - this.parent.width = width; - } - - if (height) - { - this.parent.height = height; - } - - return this.update(false); - }, - - /** - * Set the background color. - * - * @method Phaser.GameObjects.TextStyle#setBackgroundColor - * @since 3.0.0 - * - * @param {string} color - The background color. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setBackgroundColor: function (color) - { - this.backgroundColor = color; - - return this.update(false); - }, - - /** - * Set the text fill color. - * - * @method Phaser.GameObjects.TextStyle#setFill - * @since 3.0.0 - * - * @param {string} color - The text fill color. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setFill: function (color) - { - this.color = color; - - return this.update(false); - }, - - /** - * Set the text fill color. - * - * @method Phaser.GameObjects.TextStyle#setColor - * @since 3.0.0 - * - * @param {string} color - The text fill color. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setColor: function (color) - { - this.color = color; - - return this.update(false); - }, - - /** - * Set the resolution used by the Text object. - * - * By default it will be set to match the resolution set in the Game Config, - * but you can override it via this method. It allows for much clearer text on High DPI devices, - * at the cost of memory because it uses larger internal Canvas textures for the Text. - * - * Please use with caution, as the more high res Text you have, the more memory it uses up. - * - * @method Phaser.GameObjects.TextStyle#setResolution - * @since 3.12.0 - * - * @param {number} value - The resolution for this Text object to use. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setResolution: function (value) - { - this.resolution = value; - - return this.update(false); - }, - - /** - * Set the stroke settings. - * - * @method Phaser.GameObjects.TextStyle#setStroke - * @since 3.0.0 - * - * @param {string} color - The stroke color. - * @param {number} thickness - The stroke thickness. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setStroke: function (color, thickness) - { - if (thickness === undefined) { thickness = this.strokeThickness; } - - if (color === undefined && this.strokeThickness !== 0) - { - // Reset the stroke to zero (disabling it) - this.strokeThickness = 0; - - this.update(true); - } - else if (this.stroke !== color || this.strokeThickness !== thickness) - { - this.stroke = color; - this.strokeThickness = thickness; - - this.update(true); - } - - return this.parent; - }, - - /** - * Set the shadow settings. - * - * Calling this method always re-measures the parent Text object, - * so only call it when you actually change the shadow settings. - * - * @method Phaser.GameObjects.TextStyle#setShadow - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal shadow offset. - * @param {number} [y=0] - The vertical shadow offset. - * @param {string} [color='#000'] - The shadow color. - * @param {number} [blur=0] - The shadow blur radius. - * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. - * @param {boolean} [shadowFill=true] - Whether to fill the shadow. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setShadow: function (x, y, color, blur, shadowStroke, shadowFill) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (color === undefined) { color = '#000'; } - if (blur === undefined) { blur = 0; } - if (shadowStroke === undefined) { shadowStroke = false; } - if (shadowFill === undefined) { shadowFill = true; } - - this.shadowOffsetX = x; - this.shadowOffsetY = y; - this.shadowColor = color; - this.shadowBlur = blur; - this.shadowStroke = shadowStroke; - this.shadowFill = shadowFill; - - return this.update(false); - }, - - /** - * Set the shadow offset. - * - * @method Phaser.GameObjects.TextStyle#setShadowOffset - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal shadow offset. - * @param {number} [y=0] - The vertical shadow offset. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setShadowOffset: function (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - - this.shadowOffsetX = x; - this.shadowOffsetY = y; - - return this.update(false); - }, - - /** - * Set the shadow color. - * - * @method Phaser.GameObjects.TextStyle#setShadowColor - * @since 3.0.0 - * - * @param {string} [color='#000'] - The shadow color. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setShadowColor: function (color) - { - if (color === undefined) { color = '#000'; } - - this.shadowColor = color; - - return this.update(false); - }, - - /** - * Set the shadow blur radius. - * - * @method Phaser.GameObjects.TextStyle#setShadowBlur - * @since 3.0.0 - * - * @param {number} [blur=0] - The shadow blur radius. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setShadowBlur: function (blur) - { - if (blur === undefined) { blur = 0; } - - this.shadowBlur = blur; - - return this.update(false); - }, - - /** - * Enable or disable shadow stroke. - * - * @method Phaser.GameObjects.TextStyle#setShadowStroke - * @since 3.0.0 - * - * @param {boolean} enabled - Whether shadow stroke is enabled or not. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setShadowStroke: function (enabled) - { - this.shadowStroke = enabled; - - return this.update(false); - }, - - /** - * Enable or disable shadow fill. - * - * @method Phaser.GameObjects.TextStyle#setShadowFill - * @since 3.0.0 - * - * @param {boolean} enabled - Whether shadow fill is enabled or not. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setShadowFill: function (enabled) - { - this.shadowFill = enabled; - - return this.update(false); - }, - - /** - * Set the width (in pixels) to use for wrapping lines. - * - * Pass in null to remove wrapping by width. - * - * @method Phaser.GameObjects.TextStyle#setWordWrapWidth - * @since 3.0.0 - * - * @param {number} width - The maximum width of a line in pixels. Set to null to remove wrapping. - * @param {boolean} [useAdvancedWrap=false] - Whether or not to use the advanced wrapping - * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, - * spaces and whitespace are left as is. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setWordWrapWidth: function (width, useAdvancedWrap) - { - if (useAdvancedWrap === undefined) { useAdvancedWrap = false; } - - this.wordWrapWidth = width; - this.wordWrapUseAdvanced = useAdvancedWrap; - - return this.update(false); - }, - - /** - * Set a custom callback for wrapping lines. - * - * Pass in null to remove wrapping by callback. - * - * @method Phaser.GameObjects.TextStyle#setWordWrapCallback - * @since 3.0.0 - * - * @param {TextStyleWordWrapCallback} callback - A custom function that will be responsible for wrapping the - * text. It will receive two arguments: text (the string to wrap), textObject (this Text - * instance). It should return the wrapped lines either as an array of lines or as a string with - * newline characters in place to indicate where breaks should happen. - * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setWordWrapCallback: function (callback, scope) - { - if (scope === undefined) { scope = null; } - - this.wordWrapCallback = callback; - this.wordWrapCallbackScope = scope; - - return this.update(false); - }, - - /** - * Set the alignment of the text in this Text object. - * - * The argument can be one of: `left`, `right`, `center` or `justify`. - * - * Alignment only works if the Text object has more than one line of text. - * - * @method Phaser.GameObjects.TextStyle#setAlign - * @since 3.0.0 - * - * @param {string} [align='left'] - The text alignment for multi-line text. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setAlign: function (align) - { - if (align === undefined) { align = 'left'; } - - this.align = align; - - return this.update(false); - }, - - /** - * Set the maximum number of lines to draw. - * - * @method Phaser.GameObjects.TextStyle#setMaxLines - * @since 3.0.0 - * - * @param {integer} [max=0] - The maximum number of lines to draw. - * - * @return {Phaser.GameObjects.Text} The parent Text object. - */ - setMaxLines: function (max) - { - if (max === undefined) { max = 0; } - - this.maxLines = max; - - return this.update(false); - }, - - /** - * Get the current text metrics. - * - * @method Phaser.GameObjects.TextStyle#getTextMetrics - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.Text.TextMetrics} The text metrics. - */ - getTextMetrics: function () - { - var metrics = this.metrics; - - return { - ascent: metrics.ascent, - descent: metrics.descent, - fontSize: metrics.fontSize - }; - }, - - /** - * Build a JSON representation of this Text Style. - * - * @method Phaser.GameObjects.TextStyle#toJSON - * @since 3.0.0 - * - * @return {object} A JSON representation of this Text Style. - */ - toJSON: function () - { - var output = {}; - - for (var key in propertyMap) - { - output[key] = this[key]; - } - - output.metrics = this.getTextMetrics(); - - return output; - }, - - /** - * Destroy this Text Style. - * - * @method Phaser.GameObjects.TextStyle#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.parent = undefined; - } - -}); - -module.exports = TextStyle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetValue = require('../../utils/object/GetValue'); +var MeasureText = require('./MeasureText'); + +// Key: [ Object Key, Default Value ] + +var propertyMap = { + fontFamily: [ 'fontFamily', 'Courier' ], + fontSize: [ 'fontSize', '16px' ], + fontStyle: [ 'fontStyle', '' ], + backgroundColor: [ 'backgroundColor', null ], + color: [ 'color', '#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', 0 ], + fixedHeight: [ 'fixedHeight', 0 ], + resolution: [ 'resolution', 0 ], + rtl: [ 'rtl', false ], + testString: [ 'testString', '|MÉqgy' ], + baselineX: [ 'baselineX', 1.2 ], + baselineY: [ 'baselineY', 1.4 ], + wordWrapWidth: [ 'wordWrap.width', null ], + wordWrapCallback: [ 'wordWrap.callback', null ], + wordWrapCallbackScope: [ 'wordWrap.callbackScope', null ], + wordWrapUseAdvanced: [ 'wordWrap.useAdvancedWrap', false ] +}; + +/** + * @classdesc + * A TextStyle class manages all of the style settings for a Text object. + * + * Text Game Objects create a TextStyle instance automatically, which is + * accessed via the `Text.style` property. You do not normally need to + * instantiate one yourself. + * + * @class TextStyle + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Text} text - The Text object that this TextStyle is styling. + * @param {Phaser.Types.GameObjects.Text.TextStyle} style - The style settings to set. + */ +var TextStyle = new Class({ + + initialize: + + function TextStyle (text, style) + { + /** + * The Text object that this TextStyle is styling. + * + * @name Phaser.GameObjects.TextStyle#parent + * @type {Phaser.GameObjects.Text} + * @since 3.0.0 + */ + this.parent = text; + + /** + * The font family. + * + * @name Phaser.GameObjects.TextStyle#fontFamily + * @type {string} + * @default 'Courier' + * @since 3.0.0 + */ + this.fontFamily; + + /** + * The font size. + * + * @name Phaser.GameObjects.TextStyle#fontSize + * @type {string} + * @default '16px' + * @since 3.0.0 + */ + this.fontSize; + + /** + * The font style. + * + * @name Phaser.GameObjects.TextStyle#fontStyle + * @type {string} + * @since 3.0.0 + */ + this.fontStyle; + + /** + * The background color. + * + * @name Phaser.GameObjects.TextStyle#backgroundColor + * @type {string} + * @since 3.0.0 + */ + this.backgroundColor; + + /** + * The text fill color. + * + * @name Phaser.GameObjects.TextStyle#color + * @type {string} + * @default '#fff' + * @since 3.0.0 + */ + this.color; + + /** + * The text stroke color. + * + * @name Phaser.GameObjects.TextStyle#stroke + * @type {string} + * @default '#fff' + * @since 3.0.0 + */ + this.stroke; + + /** + * The text stroke thickness. + * + * @name Phaser.GameObjects.TextStyle#strokeThickness + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.strokeThickness; + + /** + * The horizontal shadow offset. + * + * @name Phaser.GameObjects.TextStyle#shadowOffsetX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.shadowOffsetX; + + /** + * The vertical shadow offset. + * + * @name Phaser.GameObjects.TextStyle#shadowOffsetY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.shadowOffsetY; + + /** + * The shadow color. + * + * @name Phaser.GameObjects.TextStyle#shadowColor + * @type {string} + * @default '#000' + * @since 3.0.0 + */ + this.shadowColor; + + /** + * The shadow blur radius. + * + * @name Phaser.GameObjects.TextStyle#shadowBlur + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.shadowBlur; + + /** + * Whether shadow stroke is enabled or not. + * + * @name Phaser.GameObjects.TextStyle#shadowStroke + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.shadowStroke; + + /** + * Whether shadow fill is enabled or not. + * + * @name Phaser.GameObjects.TextStyle#shadowFill + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.shadowFill; + + /** + * The text alignment. + * + * @name Phaser.GameObjects.TextStyle#align + * @type {string} + * @default 'left' + * @since 3.0.0 + */ + this.align; + + /** + * The maximum number of lines to draw. + * + * @name Phaser.GameObjects.TextStyle#maxLines + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.maxLines; + + /** + * The fixed width of the text. + * + * `0` means no fixed with. + * + * @name Phaser.GameObjects.TextStyle#fixedWidth + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.fixedWidth; + + /** + * The fixed height of the text. + * + * `0` means no fixed height. + * + * @name Phaser.GameObjects.TextStyle#fixedHeight + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.fixedHeight; + + /** + * The resolution the text is rendered to its internal canvas at. + * The default is 0, which means it will use the resolution set in the Game Config. + * + * @name Phaser.GameObjects.TextStyle#resolution + * @type {number} + * @default 0 + * @since 3.12.0 + */ + this.resolution; + + /** + * Whether the text should render right to left. + * + * @name Phaser.GameObjects.TextStyle#rtl + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.rtl; + + /** + * The test string to use when measuring the font. + * + * @name Phaser.GameObjects.TextStyle#testString + * @type {string} + * @default '|MÉqgy' + * @since 3.0.0 + */ + this.testString; + + /** + * The amount of horizontal padding added to the width of the text when calculating the font metrics. + * + * @name Phaser.GameObjects.TextStyle#baselineX + * @type {number} + * @default 1.2 + * @since 3.3.0 + */ + this.baselineX; + + /** + * The amount of vertical padding added to the height of the text when calculating the font metrics. + * + * @name Phaser.GameObjects.TextStyle#baselineY + * @type {number} + * @default 1.4 + * @since 3.3.0 + */ + this.baselineY; + + /** + * The font style, size and family. + * + * @name Phaser.GameObjects.TextStyle#_font + * @type {string} + * @private + * @since 3.0.0 + */ + this._font; + + // Set to defaults + user style + this.setStyle(style, false, true); + + var metrics = GetValue(style, 'metrics', false); + + // 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 + if (metrics) + { + this.metrics = { + ascent: GetValue(metrics, 'ascent', 0), + descent: GetValue(metrics, 'descent', 0), + fontSize: GetValue(metrics, 'fontSize', 0) + }; + } + else + { + this.metrics = MeasureText(this); + } + }, + + /** + * Set the text style. + * + * @example + * text.setStyle({ + * fontSize: '64px', + * fontFamily: 'Arial', + * color: '#ffffff', + * align: 'center', + * backgroundColor: '#ff00ff' + * }); + * + * @method Phaser.GameObjects.TextStyle#setStyle + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.Text.TextStyle} style - The style settings to set. + * @param {boolean} [updateText=true] - Whether to update the text immediately. + * @param {boolean} [setDefaults=false] - Use the default values is not set, or the local values. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setStyle: function (style, updateText, setDefaults) + { + if (updateText === undefined) { updateText = true; } + if (setDefaults === undefined) { setDefaults = false; } + + // Avoid type mutation + if (style && style.hasOwnProperty('fontSize') && typeof style.fontSize === 'number') + { + style.fontSize = style.fontSize.toString() + 'px'; + } + + for (var key in propertyMap) + { + var value = (setDefaults) ? propertyMap[key][1] : this[key]; + + if (key === 'wordWrapCallback' || key === 'wordWrapCallbackScope') + { + // Callback & scope should be set without processing the values + this[key] = GetValue(style, propertyMap[key][0], value); + } + else + { + this[key] = GetAdvancedValue(style, propertyMap[key][0], value); + } + } + + // Allow for 'font' override + var font = GetValue(style, 'font', null); + + if (font !== null) + { + this.setFont(font, false); + } + + this._font = [ this.fontStyle, this.fontSize, this.fontFamily ].join(' ').trim(); + + // Allow for 'fill' to be used in place of 'color' + var fill = GetValue(style, 'fill', null); + + if (fill !== null) + { + this.color = fill; + } + + if (updateText) + { + return this.update(true); + } + else + { + return this.parent; + } + }, + + /** + * Synchronize the font settings to the given Canvas Rendering Context. + * + * @method Phaser.GameObjects.TextStyle#syncFont + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The Canvas Element. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + */ + syncFont: function (canvas, context) + { + context.font = this._font; + }, + + /** + * Synchronize the text style settings to the given Canvas Rendering Context. + * + * @method Phaser.GameObjects.TextStyle#syncStyle + * @since 3.0.0 + * + * @param {HTMLCanvasElement} canvas - The Canvas Element. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + */ + syncStyle: function (canvas, context) + { + context.textBaseline = 'alphabetic'; + + context.fillStyle = this.color; + context.strokeStyle = this.stroke; + + context.lineWidth = this.strokeThickness; + context.lineCap = 'round'; + context.lineJoin = 'round'; + }, + + /** + * Synchronize the shadow settings to the given Canvas Rendering Context. + * + * @method Phaser.GameObjects.TextStyle#syncShadow + * @since 3.0.0 + * + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + * @param {boolean} enabled - Whether shadows are enabled or not. + */ + syncShadow: function (context, enabled) + { + if (enabled) + { + context.shadowOffsetX = this.shadowOffsetX; + context.shadowOffsetY = this.shadowOffsetY; + context.shadowColor = this.shadowColor; + context.shadowBlur = this.shadowBlur; + } + else + { + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + context.shadowColor = 0; + context.shadowBlur = 0; + } + }, + + /** + * Update the style settings for the parent Text object. + * + * @method Phaser.GameObjects.TextStyle#update + * @since 3.0.0 + * + * @param {boolean} recalculateMetrics - Whether to recalculate font and text metrics. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + update: function (recalculateMetrics) + { + if (recalculateMetrics) + { + this._font = [ this.fontStyle, this.fontSize, this.fontFamily ].join(' ').trim(); + + this.metrics = MeasureText(this); + } + + return this.parent.updateText(); + }, + + /** + * 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. + * + * @method Phaser.GameObjects.TextStyle#setFont + * @since 3.0.0 + * + * @param {(string|object)} font - The font family or font settings to set. + * @param {boolean} [updateText=true] - Whether to update the text immediately. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFont: function (font, updateText) + { + if (updateText === undefined) { updateText = true; } + + var fontFamily = font; + var fontSize = ''; + var fontStyle = ''; + + if (typeof font !== 'string') + { + fontFamily = GetValue(font, 'fontFamily', 'Courier'); + fontSize = GetValue(font, 'fontSize', '16px'); + fontStyle = GetValue(font, 'fontStyle', ''); + } + else + { + var fontSplit = font.split(' '); + + var i = 0; + + fontStyle = (fontSplit.length > 2) ? fontSplit[i++] : ''; + fontSize = fontSplit[i++] || '16px'; + fontFamily = fontSplit[i++] || 'Courier'; + } + + if (fontFamily !== this.fontFamily || fontSize !== this.fontSize || fontStyle !== this.fontStyle) + { + this.fontFamily = fontFamily; + this.fontSize = fontSize; + this.fontStyle = fontStyle; + + if (updateText) + { + this.update(true); + } + } + + return this.parent; + }, + + /** + * Set the font family. + * + * @method Phaser.GameObjects.TextStyle#setFontFamily + * @since 3.0.0 + * + * @param {string} family - The font family. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFontFamily: function (family) + { + if (this.fontFamily !== family) + { + this.fontFamily = family; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the font style. + * + * @method Phaser.GameObjects.TextStyle#setFontStyle + * @since 3.0.0 + * + * @param {string} style - The font style. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFontStyle: function (style) + { + if (this.fontStyle !== style) + { + this.fontStyle = style; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the font size. + * + * @method Phaser.GameObjects.TextStyle#setFontSize + * @since 3.0.0 + * + * @param {(number|string)} size - The font size. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFontSize: function (size) + { + if (typeof size === 'number') + { + size = size.toString() + 'px'; + } + + if (this.fontSize !== size) + { + this.fontSize = size; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the test string to use when measuring the font. + * + * @method Phaser.GameObjects.TextStyle#setTestString + * @since 3.0.0 + * + * @param {string} string - The test string to use when measuring the font. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setTestString: function (string) + { + this.testString = string; + + return this.update(true); + }, + + /** + * Set a fixed width and height for the text. + * + * Pass in `0` for either of these parameters to disable fixed width or height respectively. + * + * @method Phaser.GameObjects.TextStyle#setFixedSize + * @since 3.0.0 + * + * @param {number} width - The fixed width to set. + * @param {number} height - The fixed height to set. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFixedSize: function (width, height) + { + this.fixedWidth = width; + this.fixedHeight = height; + + if (width) + { + this.parent.width = width; + } + + if (height) + { + this.parent.height = height; + } + + return this.update(false); + }, + + /** + * Set the background color. + * + * @method Phaser.GameObjects.TextStyle#setBackgroundColor + * @since 3.0.0 + * + * @param {string} color - The background color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setBackgroundColor: function (color) + { + this.backgroundColor = color; + + return this.update(false); + }, + + /** + * Set the text fill color. + * + * @method Phaser.GameObjects.TextStyle#setFill + * @since 3.0.0 + * + * @param {string} color - The text fill color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setFill: function (color) + { + this.color = color; + + return this.update(false); + }, + + /** + * Set the text fill color. + * + * @method Phaser.GameObjects.TextStyle#setColor + * @since 3.0.0 + * + * @param {string} color - The text fill color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setColor: function (color) + { + this.color = color; + + return this.update(false); + }, + + /** + * Set the resolution used by the Text object. + * + * By default it will be set to match the resolution set in the Game Config, + * but you can override it via this method. It allows for much clearer text on High DPI devices, + * at the cost of memory because it uses larger internal Canvas textures for the Text. + * + * Please use with caution, as the more high res Text you have, the more memory it uses up. + * + * @method Phaser.GameObjects.TextStyle#setResolution + * @since 3.12.0 + * + * @param {number} value - The resolution for this Text object to use. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setResolution: function (value) + { + this.resolution = value; + + return this.update(false); + }, + + /** + * Set the stroke settings. + * + * @method Phaser.GameObjects.TextStyle#setStroke + * @since 3.0.0 + * + * @param {string} color - The stroke color. + * @param {number} thickness - The stroke thickness. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setStroke: function (color, thickness) + { + if (thickness === undefined) { thickness = this.strokeThickness; } + + if (color === undefined && this.strokeThickness !== 0) + { + // Reset the stroke to zero (disabling it) + this.strokeThickness = 0; + + this.update(true); + } + else if (this.stroke !== color || this.strokeThickness !== thickness) + { + this.stroke = color; + this.strokeThickness = thickness; + + this.update(true); + } + + return this.parent; + }, + + /** + * Set the shadow settings. + * + * Calling this method always re-measures the parent Text object, + * so only call it when you actually change the shadow settings. + * + * @method Phaser.GameObjects.TextStyle#setShadow + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal shadow offset. + * @param {number} [y=0] - The vertical shadow offset. + * @param {string} [color='#000'] - The shadow color. + * @param {number} [blur=0] - The shadow blur radius. + * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. + * @param {boolean} [shadowFill=true] - Whether to fill the shadow. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadow: function (x, y, color, blur, shadowStroke, shadowFill) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = '#000'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = false; } + if (shadowFill === undefined) { shadowFill = true; } + + this.shadowOffsetX = x; + this.shadowOffsetY = y; + this.shadowColor = color; + this.shadowBlur = blur; + this.shadowStroke = shadowStroke; + this.shadowFill = shadowFill; + + return this.update(false); + }, + + /** + * Set the shadow offset. + * + * @method Phaser.GameObjects.TextStyle#setShadowOffset + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal shadow offset. + * @param {number} [y=0] - The vertical shadow offset. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowOffset: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.shadowOffsetX = x; + this.shadowOffsetY = y; + + return this.update(false); + }, + + /** + * Set the shadow color. + * + * @method Phaser.GameObjects.TextStyle#setShadowColor + * @since 3.0.0 + * + * @param {string} [color='#000'] - The shadow color. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowColor: function (color) + { + if (color === undefined) { color = '#000'; } + + this.shadowColor = color; + + return this.update(false); + }, + + /** + * Set the shadow blur radius. + * + * @method Phaser.GameObjects.TextStyle#setShadowBlur + * @since 3.0.0 + * + * @param {number} [blur=0] - The shadow blur radius. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowBlur: function (blur) + { + if (blur === undefined) { blur = 0; } + + this.shadowBlur = blur; + + return this.update(false); + }, + + /** + * Enable or disable shadow stroke. + * + * @method Phaser.GameObjects.TextStyle#setShadowStroke + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow stroke is enabled or not. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowStroke: function (enabled) + { + this.shadowStroke = enabled; + + return this.update(false); + }, + + /** + * Enable or disable shadow fill. + * + * @method Phaser.GameObjects.TextStyle#setShadowFill + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow fill is enabled or not. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setShadowFill: function (enabled) + { + this.shadowFill = enabled; + + return this.update(false); + }, + + /** + * Set the width (in pixels) to use for wrapping lines. + * + * Pass in null to remove wrapping by width. + * + * @method Phaser.GameObjects.TextStyle#setWordWrapWidth + * @since 3.0.0 + * + * @param {number} width - The maximum width of a line in pixels. Set to null to remove wrapping. + * @param {boolean} [useAdvancedWrap=false] - Whether or not to use the advanced wrapping + * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, + * spaces and whitespace are left as is. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setWordWrapWidth: function (width, useAdvancedWrap) + { + if (useAdvancedWrap === undefined) { useAdvancedWrap = false; } + + this.wordWrapWidth = width; + this.wordWrapUseAdvanced = useAdvancedWrap; + + return this.update(false); + }, + + /** + * Set a custom callback for wrapping lines. + * + * Pass in null to remove wrapping by callback. + * + * @method Phaser.GameObjects.TextStyle#setWordWrapCallback + * @since 3.0.0 + * + * @param {TextStyleWordWrapCallback} callback - A custom function that will be responsible for wrapping the + * text. It will receive two arguments: text (the string to wrap), textObject (this Text + * instance). It should return the wrapped lines either as an array of lines or as a string with + * newline characters in place to indicate where breaks should happen. + * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setWordWrapCallback: function (callback, scope) + { + if (scope === undefined) { scope = null; } + + this.wordWrapCallback = callback; + this.wordWrapCallbackScope = scope; + + return this.update(false); + }, + + /** + * Set the alignment of the text in this Text object. + * + * The argument can be one of: `left`, `right`, `center` or `justify`. + * + * Alignment only works if the Text object has more than one line of text. + * + * @method Phaser.GameObjects.TextStyle#setAlign + * @since 3.0.0 + * + * @param {string} [align='left'] - The text alignment for multi-line text. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setAlign: function (align) + { + if (align === undefined) { align = 'left'; } + + this.align = align; + + return this.update(false); + }, + + /** + * Set the maximum number of lines to draw. + * + * @method Phaser.GameObjects.TextStyle#setMaxLines + * @since 3.0.0 + * + * @param {integer} [max=0] - The maximum number of lines to draw. + * + * @return {Phaser.GameObjects.Text} The parent Text object. + */ + setMaxLines: function (max) + { + if (max === undefined) { max = 0; } + + this.maxLines = max; + + return this.update(false); + }, + + /** + * Get the current text metrics. + * + * @method Phaser.GameObjects.TextStyle#getTextMetrics + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.Text.TextMetrics} The text metrics. + */ + getTextMetrics: function () + { + var metrics = this.metrics; + + return { + ascent: metrics.ascent, + descent: metrics.descent, + fontSize: metrics.fontSize + }; + }, + + /** + * Build a JSON representation of this Text Style. + * + * @method Phaser.GameObjects.TextStyle#toJSON + * @since 3.0.0 + * + * @return {object} A JSON representation of this Text Style. + */ + toJSON: function () + { + var output = {}; + + for (var key in propertyMap) + { + output[key] = this[key]; + } + + output.metrics = this.getTextMetrics(); + + return output; + }, + + /** + * Destroy this Text Style. + * + * @method Phaser.GameObjects.TextStyle#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.parent = undefined; + } + +}); + +module.exports = TextStyle; diff --git a/src/gameobjects/text/static/Text.js b/src/gameobjects/text/static/Text.js index 4d39c5f7b..557d4ab12 100644 --- a/src/gameobjects/text/static/Text.js +++ b/src/gameobjects/text/static/Text.js @@ -1,1403 +1,1403 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AddToDOM = require('../../../dom/AddToDOM'); -var CanvasPool = require('../../../display/canvas/CanvasPool'); -var Class = require('../../../utils/Class'); -var Components = require('../../components'); -var GameEvents = require('../../../core/events'); -var GameObject = require('../../GameObject'); -var GetTextSize = require('../GetTextSize'); -var GetValue = require('../../../utils/object/GetValue'); -var RemoveFromDOM = require('../../../dom/RemoveFromDOM'); -var TextRender = require('./TextRender'); -var TextStyle = require('../TextStyle'); - -/** - * @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:** If the font you wish to use has a space or digit in its name, such as - * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes, either - * when creating the Text object, or when setting the font via `setFont` or `setFontFamily`. I.e.: - * - * ```javascript - * this.add.text(0, 0, 'Hello World', { fontFamily: '"Roboto Condensed"' }); - * ``` - * - * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all - * quoted properly, too: - * - * ```javascript - * this.add.text(0, 0, 'Hello World', { fontFamily: 'Verdana, "Times New Roman", Tahoma, serif' }); - * ``` - * - * You can only display fonts that are currently loaded and available to the browser: therefore fonts must - * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, - * or have the fonts ready 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.Pipeline - * @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. - */ -var Text = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.ComputedSize, - Components.Crop, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Tint, - Components.Transform, - Components.Visible, - TextRender - ], - - initialize: - - function Text (scene, x, y, text, style) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - GameObject.call(this, scene, 'Text'); - - /** - * The renderer in use by this Text object. - * - * @name Phaser.GameObjects.Text#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.12.0 - */ - this.renderer = scene.sys.game.renderer; - - this.setPosition(x, y); - this.setOrigin(0, 0); - this.initPipeline(); - - /** - * The canvas element that the text is rendered to. - * - * @name Phaser.GameObjects.Text#canvas - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.canvas = CanvasPool.create(this); - - /** - * The context of the canvas element that the text is rendered to. - * - * @name Phaser.GameObjects.Text#context - * @type {CanvasRenderingContext2D} - * @since 3.0.0 - */ - this.context = this.canvas.getContext('2d'); - - /** - * The Text Style object. - * - * Manages the style of this Text object. - * - * @name Phaser.GameObjects.Text#style - * @type {Phaser.GameObjects.TextStyle} - * @since 3.0.0 - */ - this.style = new TextStyle(this, style); - - /** - * Whether to automatically round line positions. - * - * @name Phaser.GameObjects.Text#autoRound - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.autoRound = true; - - /** - * The Regular Expression that is used to split the text up into lines, in - * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. - * You can change this RegExp to be anything else that you may need. - * - * @name Phaser.GameObjects.Text#splitRegExp - * @type {object} - * @since 3.0.0 - */ - this.splitRegExp = /(?:\r\n|\r|\n)/; - - /** - * The text to display. - * - * @name Phaser.GameObjects.Text#_text - * @type {string} - * @private - * @since 3.12.0 - */ - this._text = undefined; - - /** - * Specify a padding value which is added to the line width and height when calculating the Text size. - * Allows you to add extra spacing if the browser is unable to accurately determine the true font dimensions. - * - * @name Phaser.GameObjects.Text#padding - * @type {{left:number,right:number,top:number,bottom:number}} - * @since 3.0.0 - */ - this.padding = { left: 0, right: 0, top: 0, bottom: 0 }; - - /** - * The width of this Text object. - * - * @name Phaser.GameObjects.Text#width - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.width = 1; - - /** - * The height of this Text object. - * - * @name Phaser.GameObjects.Text#height - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.height = 1; - - /** - * The line spacing value. - * This value is added to the font height to calculate the overall line height. - * Only has an effect if this Text object contains multiple lines of text. - * - * If you update this property directly, instead of using the `setLineSpacing` method, then - * be sure to call `updateText` after, or you won't see the change reflected in the Text object. - * - * @name Phaser.GameObjects.Text#lineSpacing - * @type {number} - * @since 3.13.0 - */ - this.lineSpacing = 0; - - /** - * Whether the text or its settings have changed and need updating. - * - * @name Phaser.GameObjects.Text#dirty - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.dirty = false; - - // If resolution wasn't set, then we get it from the game config - if (this.style.resolution === 0) - { - this.style.resolution = scene.sys.game.config.resolution; - } - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.Text#_crop - * @type {object} - * @private - * @since 3.12.0 - */ - this._crop = this.resetCropObject(); - - // Create a Texture for this Text object - this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); - - // Get the frame - this.frame = this.texture.get(); - - // Set the resolution - this.frame.source.resolution = this.style.resolution; - - if (this.renderer && this.renderer.gl) - { - // Clear the default 1x1 glTexture, as we override it later - this.renderer.deleteTexture(this.frame.source.glTexture); - - this.frame.source.glTexture = null; - } - - this.initRTL(); - - this.setText(text); - - if (style && style.padding) - { - this.setPadding(style.padding); - } - - if (style && style.lineSpacing) - { - this.setLineSpacing(style.lineSpacing); - } - - scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function () - { - this.dirty = true; - }, this); - }, - - /** - * Initialize right to left text. - * - * @method Phaser.GameObjects.Text#initRTL - * @since 3.0.0 - */ - initRTL: function () - { - if (!this.style.rtl) - { - return; - } - - // 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. - - this.canvas.dir = 'rtl'; - - // Experimental atm, but one day ... - this.context.direction = 'rtl'; - - // Add it to the DOM, but hidden within the parent canvas. - this.canvas.style.display = 'none'; - - AddToDOM(this.canvas, this.scene.sys.canvas); - - // And finally we set the x origin - this.originX = 1; - }, - - /** - * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal - * bounds. - * - * @method Phaser.GameObjects.Text#runWordWrap - * @since 3.0.0 - * - * @param {string} text - The text to perform word wrap detection against. - * - * @return {string} The text after wrapping has been applied. - */ - runWordWrap: function (text) - { - var style = this.style; - - if (style.wordWrapCallback) - { - var wrappedLines = style.wordWrapCallback.call(style.wordWrapCallbackScope, text, this); - - if (Array.isArray(wrappedLines)) - { - wrappedLines = wrappedLines.join('\n'); - } - - return wrappedLines; - } - else if (style.wordWrapWidth) - { - if (style.wordWrapUseAdvanced) - { - return this.advancedWordWrap(text, this.context, this.style.wordWrapWidth); - } - else - { - return this.basicWordWrap(text, this.context, this.style.wordWrapWidth); - } - } - else - { - return text; - } - }, - - /** - * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal - * bounds. Consecutive spaces will be collapsed and replaced with a single space. Lines will be - * trimmed of white space before processing. Throws an error if wordWrapWidth is less than a - * single character. - * - * @method Phaser.GameObjects.Text#advancedWordWrap - * @since 3.0.0 - * - * @param {string} text - The text to perform word wrap detection against. - * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. - * @param {number} wordWrapWidth - The word wrap width. - * - * @return {string} The wrapped text. - */ - advancedWordWrap: function (text, context, wordWrapWidth) - { - var output = ''; - - // Condense consecutive spaces and split into lines - var lines = text - .replace(/ +/gi, ' ') - .split(this.splitRegExp); - - var linesCount = lines.length; - - for (var i = 0; i < linesCount; i++) - { - var line = lines[i]; - var out = ''; - - // Trim whitespace - line = line.replace(/^ *|\s*$/gi, ''); - - // If entire line is less than wordWrapWidth append the entire line and exit early - var lineWidth = context.measureText(line).width; - - if (lineWidth < wordWrapWidth) - { - output += line + '\n'; - continue; - } - - // Otherwise, calculate new lines - var currentLineWidth = wordWrapWidth; - - // Split into words - var words = line.split(' '); - - for (var j = 0; j < words.length; j++) - { - var word = words[j]; - var wordWithSpace = word + ' '; - var wordWidth = context.measureText(wordWithSpace).width; - - if (wordWidth > currentLineWidth) - { - // Break word - if (j === 0) - { - // Shave off letters from word until it's small enough - var newWord = wordWithSpace; - - while (newWord.length) - { - newWord = newWord.slice(0, -1); - wordWidth = context.measureText(newWord).width; - - if (wordWidth <= currentLineWidth) - { - break; - } - } - - // If wordWrapWidth is too small for even a single letter, shame user - // failure with a fatal error - if (!newWord.length) - { - throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); - } - - // Replace current word in array with remainder - var secondPart = word.substr(newWord.length); - - words[j] = secondPart; - - // Append first piece to output - out += newWord; - } - - // If existing word length is 0, don't include it - var offset = (words[j].length) ? j : j + 1; - - // Collapse rest of sentence and remove any trailing white space - var remainder = words.slice(offset).join(' ') - .replace(/[ \n]*$/gi, ''); - - // Prepend remainder to next line - lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); - linesCount = lines.length; - - break; // Processing on this line - - // Append word with space to output - } - else - { - out += wordWithSpace; - currentLineWidth -= wordWidth; - } - } - - // Append processed line to output - output += out.replace(/[ \n]*$/gi, '') + '\n'; - } - - // Trim the end of the string - output = output.replace(/[\s|\n]*$/gi, ''); - - return output; - }, - - /** - * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal - * bounds. Spaces are not collapsed and whitespace is not trimmed. - * - * @method Phaser.GameObjects.Text#basicWordWrap - * @since 3.0.0 - * - * @param {string} text - The text to perform word wrap detection against. - * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. - * @param {number} wordWrapWidth - The word wrap width. - * - * @return {string} The wrapped text. - */ - basicWordWrap: function (text, context, wordWrapWidth) - { - var result = ''; - var lines = text.split(this.splitRegExp); - var lastLineIndex = lines.length - 1; - var whiteSpaceWidth = context.measureText(' ').width; - - for (var i = 0; i <= lastLineIndex; i++) - { - var spaceLeft = wordWrapWidth; - var words = lines[i].split(' '); - var lastWordIndex = words.length - 1; - - for (var j = 0; j <= lastWordIndex; j++) - { - var word = words[j]; - var wordWidth = context.measureText(word).width; - var wordWidthWithSpace = wordWidth + whiteSpaceWidth; - - if (wordWidthWithSpace > spaceLeft) - { - // Skip printing the newline if it's the first word of the line that is greater - // than the word wrap width. - if (j > 0) - { - result += '\n'; - spaceLeft = wordWrapWidth; - } - } - - result += word; - - if (j < lastWordIndex) - { - result += ' '; - spaceLeft -= wordWidthWithSpace; - } - else - { - spaceLeft -= wordWidth; - } - } - - if (i < lastLineIndex) - { - result += '\n'; - } - } - - return result; - }, - - /** - * Runs the given text through this Text objects word wrapping and returns the results as an - * array, where each element of the array corresponds to a wrapped line of text. - * - * @method Phaser.GameObjects.Text#getWrappedText - * @since 3.0.0 - * - * @param {string} text - The text for which the wrapping will be calculated. If unspecified, the Text objects current text will be used. - * - * @return {string[]} An array of strings with the pieces of wrapped text. - */ - getWrappedText: function (text) - { - if (text === undefined) { text = this._text; } - - this.style.syncFont(this.canvas, this.context); - - var wrappedLines = this.runWordWrap(text); - - return wrappedLines.split(this.splitRegExp); - }, - - /** - * Set the text to display. - * - * An array of strings will be joined with `\n` line breaks. - * - * @method Phaser.GameObjects.Text#setText - * @since 3.0.0 - * - * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this Text object. - * - * @return {this} This Text object. - */ - setText: function (value) - { - if (!value && value !== 0) - { - value = ''; - } - - if (Array.isArray(value)) - { - value = value.join('\n'); - } - - if (value !== this._text) - { - this._text = value.toString(); - - this.updateText(); - } - - return this; - }, - - /** - * Set the text style. - * - * @example - * text.setStyle({ - * fontSize: '64px', - * fontFamily: 'Arial', - * color: '#ffffff', - * align: 'center', - * backgroundColor: '#ff00ff' - * }); - * - * @method Phaser.GameObjects.Text#setStyle - * @since 3.0.0 - * - * @param {object} style - The style settings to set. - * - * @return {this} This Text object. - */ - setStyle: function (style) - { - return this.style.setStyle(style); - }, - - /** - * 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:** If the font you wish to use has a space or digit in its name, such as - * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: - * - * ```javascript - * Text.setFont('"Roboto Condensed"'); - * ``` - * - * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all - * quoted properly, too: - * - * ```javascript - * Text.setFont('Verdana, "Times New Roman", Tahoma, 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. - */ - setFont: function (font) - { - return this.style.setFont(font); - }, - - /** - * Set the font family. - * - * **Important:** If the font you wish to use has a space or digit in its name, such as - * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: - * - * ```javascript - * Text.setFont('"Roboto Condensed"'); - * ``` - * - * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all - * quoted properly, too: - * - * ```javascript - * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); - * ``` - * - * @method Phaser.GameObjects.Text#setFontFamily - * @since 3.0.0 - * - * @param {string} family - The font family. - * - * @return {this} This Text object. - */ - setFontFamily: function (family) - { - return this.style.setFontFamily(family); - }, - - /** - * Set the font size. - * - * @method Phaser.GameObjects.Text#setFontSize - * @since 3.0.0 - * - * @param {number} size - The font size. - * - * @return {this} This Text object. - */ - setFontSize: function (size) - { - return this.style.setFontSize(size); - }, - - /** - * Set the font style. - * - * @method Phaser.GameObjects.Text#setFontStyle - * @since 3.0.0 - * - * @param {string} style - The font style. - * - * @return {this} This Text object. - */ - setFontStyle: function (style) - { - return this.style.setFontStyle(style); - }, - - /** - * Set a fixed width and height for the text. - * - * Pass in `0` for either of these parameters to disable fixed width or height respectively. - * - * @method Phaser.GameObjects.Text#setFixedSize - * @since 3.0.0 - * - * @param {number} width - The fixed width to set. `0` disables fixed width. - * @param {number} height - The fixed height to set. `0` disables fixed height. - * - * @return {this} This Text object. - */ - setFixedSize: function (width, height) - { - return this.style.setFixedSize(width, height); - }, - - /** - * Set the background color. - * - * @method Phaser.GameObjects.Text#setBackgroundColor - * @since 3.0.0 - * - * @param {string} color - The background color. - * - * @return {this} This Text object. - */ - setBackgroundColor: function (color) - { - return this.style.setBackgroundColor(color); - }, - - /** - * 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|any)} color - The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. - * - * @return {this} This Text object. - */ - setFill: function (fillStyle) - { - return this.style.setFill(fillStyle); - }, - - /** - * Set the text fill color. - * - * @method Phaser.GameObjects.Text#setColor - * @since 3.0.0 - * - * @param {string} color - The text fill color. - * - * @return {this} This Text object. - */ - setColor: function (color) - { - return this.style.setColor(color); - }, - - /** - * Set the stroke settings. - * - * @method Phaser.GameObjects.Text#setStroke - * @since 3.0.0 - * - * @param {string} color - The stroke color. - * @param {number} thickness - The stroke thickness. - * - * @return {this} This Text object. - */ - setStroke: function (color, thickness) - { - return this.style.setStroke(color, thickness); - }, - - /** - * Set the shadow settings. - * - * @method Phaser.GameObjects.Text#setShadow - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal shadow offset. - * @param {number} [y=0] - The vertical shadow offset. - * @param {string} [color='#000'] - The shadow color. - * @param {number} [blur=0] - The shadow blur radius. - * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. - * @param {boolean} [shadowFill=true] - Whether to fill the shadow. - * - * @return {this} This Text object. - */ - setShadow: function (x, y, color, blur, shadowStroke, shadowFill) - { - return this.style.setShadow(x, y, color, blur, shadowStroke, shadowFill); - }, - - /** - * Set the shadow offset. - * - * @method Phaser.GameObjects.Text#setShadowOffset - * @since 3.0.0 - * - * @param {number} x - The horizontal shadow offset. - * @param {number} y - The vertical shadow offset. - * - * @return {this} This Text object. - */ - setShadowOffset: function (x, y) - { - return this.style.setShadowOffset(x, y); - }, - - /** - * Set the shadow color. - * - * @method Phaser.GameObjects.Text#setShadowColor - * @since 3.0.0 - * - * @param {string} color - The shadow color. - * - * @return {this} This Text object. - */ - setShadowColor: function (color) - { - return this.style.setShadowColor(color); - }, - - /** - * Set the shadow blur radius. - * - * @method Phaser.GameObjects.Text#setShadowBlur - * @since 3.0.0 - * - * @param {number} blur - The shadow blur radius. - * - * @return {this} This Text object. - */ - setShadowBlur: function (blur) - { - return this.style.setShadowBlur(blur); - }, - - /** - * Enable or disable shadow stroke. - * - * @method Phaser.GameObjects.Text#setShadowStroke - * @since 3.0.0 - * - * @param {boolean} enabled - Whether shadow stroke is enabled or not. - * - * @return {this} This Text object. - */ - setShadowStroke: function (enabled) - { - return this.style.setShadowStroke(enabled); - }, - - /** - * Enable or disable shadow fill. - * - * @method Phaser.GameObjects.Text#setShadowFill - * @since 3.0.0 - * - * @param {boolean} enabled - Whether shadow fill is enabled or not. - * - * @return {this} This Text object. - */ - setShadowFill: function (enabled) - { - return this.style.setShadowFill(enabled); - }, - - /** - * Set the width (in pixels) to use for wrapping lines. Pass in null to remove wrapping by width. - * - * @method Phaser.GameObjects.Text#setWordWrapWidth - * @since 3.0.0 - * - * @param {?number} width - The maximum width of a line in pixels. Set to null to remove wrapping. - * @param {boolean} [useAdvancedWrap=false] - Whether or not to use the advanced wrapping - * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, - * spaces and whitespace are left as is. - * - * @return {this} This Text object. - */ - setWordWrapWidth: function (width, useAdvancedWrap) - { - return this.style.setWordWrapWidth(width, useAdvancedWrap); - }, - - /** - * Set a custom callback for wrapping lines. Pass in null to remove wrapping by callback. - * - * @method Phaser.GameObjects.Text#setWordWrapCallback - * @since 3.0.0 - * - * @param {TextStyleWordWrapCallback} callback - A custom function that will be responsible for wrapping the - * text. It will receive two arguments: text (the string to wrap), textObject (this Text - * instance). It should return the wrapped lines either as an array of lines or as a string with - * newline characters in place to indicate where breaks should happen. - * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. - * - * @return {this} This Text object. - */ - setWordWrapCallback: function (callback, scope) - { - return this.style.setWordWrapCallback(callback, scope); - }, - - /** - * Set the alignment of the text in this Text object. - * - * The argument can be one of: `left`, `right`, `center` or `justify`. - * - * Alignment only works if the Text object has more than one line of text. - * - * @method Phaser.GameObjects.Text#setAlign - * @since 3.0.0 - * - * @param {string} [align='left'] - The text alignment for multi-line text. - * - * @return {this} This Text object. - */ - setAlign: function (align) - { - return this.style.setAlign(align); - }, - - /** - * Set the resolution used by this Text object. - * - * By default it will be set to match the resolution set in the Game Config, - * but you can override it via this method, or by specifying it in the Text style configuration object. - * - * It allows for much clearer text on High DPI devices, at the cost of memory because it uses larger - * internal Canvas textures for the Text. - * - * Therefore, please use with caution, as the more high res Text you have, the more memory it uses. - * - * @method Phaser.GameObjects.Text#setResolution - * @since 3.12.0 - * - * @param {number} value - The resolution for this Text object to use. - * - * @return {this} This Text object. - */ - setResolution: function (value) - { - return this.style.setResolution(value); - }, - - /** - * Sets the line spacing value. - * - * This value is _added_ to the height of the font when calculating the overall line height. - * This only has an effect if this Text object consists of multiple lines of text. - * - * @method Phaser.GameObjects.Text#setLineSpacing - * @since 3.13.0 - * - * @param {number} value - The amount to add to the font height to achieve the overall line height. - * - * @return {this} This Text object. - */ - setLineSpacing: function (value) - { - this.lineSpacing = value; - - return this.updateText(); - }, - - /** - * Set the text padding. - * - * 'left' can be an object. - * - * If only 'left' and 'top' are given they are treated as 'x' and 'y'. - * - * @method Phaser.GameObjects.Text#setPadding - * @since 3.0.0 - * - * @param {(number|Phaser.Types.GameObjects.Text.TextPadding)} left - The left padding value, or a padding config object. - * @param {number} top - The top padding value. - * @param {number} right - The right padding value. - * @param {number} bottom - The bottom padding value. - * - * @return {this} This Text object. - */ - setPadding: function (left, top, right, bottom) - { - if (typeof left === 'object') - { - var config = left; - - // If they specify x and/or y this applies to all - var x = GetValue(config, 'x', null); - - if (x !== null) - { - left = x; - right = x; - } - else - { - left = GetValue(config, 'left', 0); - right = GetValue(config, 'right', left); - } - - var y = GetValue(config, 'y', null); - - if (y !== null) - { - top = y; - bottom = y; - } - else - { - top = GetValue(config, 'top', 0); - bottom = GetValue(config, 'bottom', top); - } - } - else - { - if (left === undefined) { left = 0; } - if (top === undefined) { top = left; } - if (right === undefined) { right = left; } - if (bottom === undefined) { bottom = top; } - } - - this.padding.left = left; - this.padding.top = top; - this.padding.right = right; - this.padding.bottom = bottom; - - return this.updateText(); - }, - - /** - * Set the maximum number of lines to draw. - * - * @method Phaser.GameObjects.Text#setMaxLines - * @since 3.0.0 - * - * @param {integer} [max=0] - The maximum number of lines to draw. - * - * @return {this} This Text object. - */ - setMaxLines: function (max) - { - return this.style.setMaxLines(max); - }, - - /** - * Update the displayed text. - * - * @method Phaser.GameObjects.Text#updateText - * @since 3.0.0 - * - * @return {this} This Text object. - */ - updateText: function () - { - var canvas = this.canvas; - var context = this.context; - var style = this.style; - var resolution = style.resolution; - var size = style.metrics; - - style.syncFont(canvas, context); - - var outputText = this._text; - - if (style.wordWrapWidth || style.wordWrapCallback) - { - outputText = this.runWordWrap(this._text); - } - - // Split text into lines - var lines = outputText.split(this.splitRegExp); - - var textSize = GetTextSize(this, size, lines); - - var padding = this.padding; - - var textWidth; - - if (style.fixedWidth === 0) - { - this.width = textSize.width + padding.left + padding.right; - - textWidth = textSize.width; - } - else - { - this.width = style.fixedWidth; - - textWidth = this.width - padding.left - padding.right; - - if (textWidth < textSize.width) - { - textWidth = textSize.width; - } - } - - if (style.fixedHeight === 0) - { - this.height = textSize.height + padding.top + padding.bottom; - } - else - { - this.height = style.fixedHeight; - } - - var w = this.width; - var h = this.height; - - this.updateDisplayOrigin(); - - w *= resolution; - h *= resolution; - - w = Math.max(w, 1); - h = Math.max(h, 1); - - if (canvas.width !== w || canvas.height !== h) - { - canvas.width = w; - canvas.height = h; - - this.frame.setSize(w, h); - - // Because resizing the canvas resets the context - style.syncFont(canvas, context); - } - else - { - context.clearRect(0, 0, w, h); - } - - context.save(); - - context.scale(resolution, resolution); - - if (style.backgroundColor) - { - context.fillStyle = style.backgroundColor; - context.fillRect(0, 0, w, h); - } - - style.syncStyle(canvas, context); - - context.textBaseline = 'alphabetic'; - - // Apply padding - context.translate(padding.left, padding.top); - - var linePositionX; - var linePositionY; - - // Draw text line by line - for (var i = 0; i < textSize.lines; i++) - { - linePositionX = style.strokeThickness / 2; - linePositionY = (style.strokeThickness / 2 + i * textSize.lineHeight) + size.ascent; - - if (i > 0) - { - linePositionY += (textSize.lineSpacing * i); - } - - if (style.rtl) - { - linePositionX = w - linePositionX; - } - else if (style.align === 'right') - { - linePositionX += textWidth - textSize.lineWidths[i]; - } - else if (style.align === 'center') - { - linePositionX += (textWidth - textSize.lineWidths[i]) / 2; - } - else if (style.align === 'justify') - { - // To justify text line its width must be no less than 85% of defined width - var minimumLengthToApplyJustification = 0.85; - - if (textSize.lineWidths[i] / textSize.width >= minimumLengthToApplyJustification) - { - var extraSpace = textSize.width - textSize.lineWidths[i]; - var spaceSize = context.measureText(' ').width; - var trimmedLine = lines[i].trim(); - var array = trimmedLine.split(' '); - - extraSpace += (lines[i].length - trimmedLine.length) * spaceSize; - - var extraSpaceCharacters = Math.floor(extraSpace / spaceSize); - var idx = 0; - - while (extraSpaceCharacters > 0) - { - array[idx] += ' '; - idx = (idx + 1) % (array.length - 1 || 1); - --extraSpaceCharacters; - } - - lines[i] = array.join(' '); - } - } - - if (this.autoRound) - { - linePositionX = Math.round(linePositionX); - linePositionY = Math.round(linePositionY); - } - - if (style.strokeThickness) - { - this.style.syncShadow(context, style.shadowStroke); - - context.strokeText(lines[i], linePositionX, linePositionY); - } - - if (style.color) - { - this.style.syncShadow(context, style.shadowFill); - - context.fillText(lines[i], linePositionX, linePositionY); - } - } - - context.restore(); - - if (this.renderer.gl) - { - this.frame.source.glTexture = this.renderer.canvasToTexture(canvas, this.frame.source.glTexture, true); - - this.frame.glTexture = this.frame.source.glTexture; - } - - this.dirty = true; - - var input = this.input; - - if (input && !input.customHitArea) - { - input.hitArea.width = this.width; - input.hitArea.height = this.height; - } - - return this; - }, - - /** - * Get the current text metrics. - * - * @method Phaser.GameObjects.Text#getTextMetrics - * @since 3.0.0 - * - * @return {object} The text metrics. - */ - getTextMetrics: function () - { - return this.style.getTextMetrics(); - }, - - /** - * The text string being rendered by this Text Game Object. - * - * @name Phaser.GameObjects.Text#text - * @type {string} - * @since 3.0.0 - */ - text: { - - get: function () - { - return this._text; - }, - - set: function (value) - { - this.setText(value); - } - - }, - - /** - * Build a JSON representation of the Text object. - * - * @method Phaser.GameObjects.Text#toJSON - * @since 3.0.0 - * - * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Text object. - */ - toJSON: function () - { - var out = Components.ToJSON(this); - - // Extra Text data is added here - - var data = { - autoRound: this.autoRound, - text: this._text, - style: this.style.toJSON(), - padding: { - left: this.padding.left, - right: this.padding.right, - top: this.padding.top, - bottom: this.padding.bottom - } - }; - - out.data = data; - - return out; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.Text#preDestroy - * @protected - * @since 3.0.0 - */ - preDestroy: function () - { - if (this.style.rtl) - { - RemoveFromDOM(this.canvas); - } - - CanvasPool.remove(this.canvas); - - this.texture.destroy(); - } - - /** - * 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 - */ - -}); - -module.exports = Text; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AddToDOM = require('../../../dom/AddToDOM'); +var CanvasPool = require('../../../display/canvas/CanvasPool'); +var Class = require('../../../utils/Class'); +var Components = require('../../components'); +var GameEvents = require('../../../core/events'); +var GameObject = require('../../GameObject'); +var GetTextSize = require('../GetTextSize'); +var GetValue = require('../../../utils/object/GetValue'); +var RemoveFromDOM = require('../../../dom/RemoveFromDOM'); +var TextRender = require('./TextRender'); +var TextStyle = require('../TextStyle'); + +/** + * @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:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes, either + * when creating the Text object, or when setting the font via `setFont` or `setFontFamily`. I.e.: + * + * ```javascript + * this.add.text(0, 0, 'Hello World', { fontFamily: '"Roboto Condensed"' }); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * this.add.text(0, 0, 'Hello World', { fontFamily: 'Verdana, "Times New Roman", Tahoma, serif' }); + * ``` + * + * You can only display fonts that are currently loaded and available to the browser: therefore fonts must + * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, + * or have the fonts ready 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.Pipeline + * @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. + */ +var Text = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Crop, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Tint, + Components.Transform, + Components.Visible, + TextRender + ], + + initialize: + + function Text (scene, x, y, text, style) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + GameObject.call(this, scene, 'Text'); + + /** + * The renderer in use by this Text object. + * + * @name Phaser.GameObjects.Text#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.12.0 + */ + this.renderer = scene.sys.game.renderer; + + this.setPosition(x, y); + this.setOrigin(0, 0); + this.initPipeline(); + + /** + * The canvas element that the text is rendered to. + * + * @name Phaser.GameObjects.Text#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas = CanvasPool.create(this); + + /** + * The context of the canvas element that the text is rendered to. + * + * @name Phaser.GameObjects.Text#context + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * The Text Style object. + * + * Manages the style of this Text object. + * + * @name Phaser.GameObjects.Text#style + * @type {Phaser.GameObjects.TextStyle} + * @since 3.0.0 + */ + this.style = new TextStyle(this, style); + + /** + * Whether to automatically round line positions. + * + * @name Phaser.GameObjects.Text#autoRound + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.autoRound = true; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * + * @name Phaser.GameObjects.Text#splitRegExp + * @type {object} + * @since 3.0.0 + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + /** + * The text to display. + * + * @name Phaser.GameObjects.Text#_text + * @type {string} + * @private + * @since 3.12.0 + */ + this._text = undefined; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * Allows you to add extra spacing if the browser is unable to accurately determine the true font dimensions. + * + * @name Phaser.GameObjects.Text#padding + * @type {{left:number,right:number,top:number,bottom:number}} + * @since 3.0.0 + */ + this.padding = { left: 0, right: 0, top: 0, bottom: 0 }; + + /** + * The width of this Text object. + * + * @name Phaser.GameObjects.Text#width + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.width = 1; + + /** + * The height of this Text object. + * + * @name Phaser.GameObjects.Text#height + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.height = 1; + + /** + * The line spacing value. + * This value is added to the font height to calculate the overall line height. + * Only has an effect if this Text object contains multiple lines of text. + * + * If you update this property directly, instead of using the `setLineSpacing` method, then + * be sure to call `updateText` after, or you won't see the change reflected in the Text object. + * + * @name Phaser.GameObjects.Text#lineSpacing + * @type {number} + * @since 3.13.0 + */ + this.lineSpacing = 0; + + /** + * Whether the text or its settings have changed and need updating. + * + * @name Phaser.GameObjects.Text#dirty + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.dirty = false; + + // If resolution wasn't set, then we get it from the game config + if (this.style.resolution === 0) + { + this.style.resolution = scene.sys.game.config.resolution; + } + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Text#_crop + * @type {object} + * @private + * @since 3.12.0 + */ + this._crop = this.resetCropObject(); + + // Create a Texture for this Text object + this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); + + // Get the frame + this.frame = this.texture.get(); + + // Set the resolution + this.frame.source.resolution = this.style.resolution; + + if (this.renderer && this.renderer.gl) + { + // Clear the default 1x1 glTexture, as we override it later + this.renderer.deleteTexture(this.frame.source.glTexture); + + this.frame.source.glTexture = null; + } + + this.initRTL(); + + this.setText(text); + + if (style && style.padding) + { + this.setPadding(style.padding); + } + + if (style && style.lineSpacing) + { + this.setLineSpacing(style.lineSpacing); + } + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function () + { + this.dirty = true; + }, this); + }, + + /** + * Initialize right to left text. + * + * @method Phaser.GameObjects.Text#initRTL + * @since 3.0.0 + */ + initRTL: function () + { + if (!this.style.rtl) + { + return; + } + + // 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. + + this.canvas.dir = 'rtl'; + + // Experimental atm, but one day ... + this.context.direction = 'rtl'; + + // Add it to the DOM, but hidden within the parent canvas. + this.canvas.style.display = 'none'; + + AddToDOM(this.canvas, this.scene.sys.canvas); + + // And finally we set the x origin + this.originX = 1; + }, + + /** + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. + * + * @method Phaser.GameObjects.Text#runWordWrap + * @since 3.0.0 + * + * @param {string} text - The text to perform word wrap detection against. + * + * @return {string} The text after wrapping has been applied. + */ + runWordWrap: function (text) + { + var style = this.style; + + if (style.wordWrapCallback) + { + var wrappedLines = style.wordWrapCallback.call(style.wordWrapCallbackScope, text, this); + + if (Array.isArray(wrappedLines)) + { + wrappedLines = wrappedLines.join('\n'); + } + + return wrappedLines; + } + else if (style.wordWrapWidth) + { + if (style.wordWrapUseAdvanced) + { + return this.advancedWordWrap(text, this.context, this.style.wordWrapWidth); + } + else + { + return this.basicWordWrap(text, this.context, this.style.wordWrapWidth); + } + } + else + { + return text; + } + }, + + /** + * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. Consecutive spaces will be collapsed and replaced with a single space. Lines will be + * trimmed of white space before processing. Throws an error if wordWrapWidth is less than a + * single character. + * + * @method Phaser.GameObjects.Text#advancedWordWrap + * @since 3.0.0 + * + * @param {string} text - The text to perform word wrap detection against. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + * @param {number} wordWrapWidth - The word wrap width. + * + * @return {string} The wrapped text. + */ + advancedWordWrap: function (text, context, wordWrapWidth) + { + var output = ''; + + // Condense consecutive spaces and split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(this.splitRegExp); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // Trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // If entire line is less than wordWrapWidth append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // Otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // Split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // Break word + if (j === 0) + { + // Shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // If wordWrapWidth is too small for even a single letter, shame user + // failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // Replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // Append first piece to output + out += newWord; + } + + // If existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // Collapse rest of sentence and remove any trailing white space + var remainder = words.slice(offset).join(' ') + .replace(/[ \n]*$/gi, ''); + + // Prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // Processing on this line + + // Append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // Append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // Trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + }, + + /** + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. Spaces are not collapsed and whitespace is not trimmed. + * + * @method Phaser.GameObjects.Text#basicWordWrap + * @since 3.0.0 + * + * @param {string} text - The text to perform word wrap detection against. + * @param {CanvasRenderingContext2D} context - The Canvas Rendering Context. + * @param {number} wordWrapWidth - The word wrap width. + * + * @return {string} The wrapped text. + */ + basicWordWrap: function (text, context, wordWrapWidth) + { + var result = ''; + var lines = text.split(this.splitRegExp); + var lastLineIndex = lines.length - 1; + var whiteSpaceWidth = context.measureText(' ').width; + + for (var i = 0; i <= lastLineIndex; i++) + { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + var lastWordIndex = words.length - 1; + + for (var j = 0; j <= lastWordIndex; j++) + { + var word = words[j]; + var wordWidth = context.measureText(word).width; + var wordWidthWithSpace = wordWidth + whiteSpaceWidth; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater + // than the word wrap width. + if (j > 0) + { + result += '\n'; + spaceLeft = wordWrapWidth; + } + } + + result += word; + + if (j < lastWordIndex) + { + result += ' '; + spaceLeft -= wordWidthWithSpace; + } + else + { + spaceLeft -= wordWidth; + } + } + + if (i < lastLineIndex) + { + result += '\n'; + } + } + + return result; + }, + + /** + * Runs the given text through this Text objects word wrapping and returns the results as an + * array, where each element of the array corresponds to a wrapped line of text. + * + * @method Phaser.GameObjects.Text#getWrappedText + * @since 3.0.0 + * + * @param {string} text - The text for which the wrapping will be calculated. If unspecified, the Text objects current text will be used. + * + * @return {string[]} An array of strings with the pieces of wrapped text. + */ + getWrappedText: function (text) + { + if (text === undefined) { text = this._text; } + + this.style.syncFont(this.canvas, this.context); + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(this.splitRegExp); + }, + + /** + * Set the text to display. + * + * An array of strings will be joined with `\n` line breaks. + * + * @method Phaser.GameObjects.Text#setText + * @since 3.0.0 + * + * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this Text object. + * + * @return {this} This Text object. + */ + setText: function (value) + { + if (!value && value !== 0) + { + value = ''; + } + + if (Array.isArray(value)) + { + value = value.join('\n'); + } + + if (value !== this._text) + { + this._text = value.toString(); + + this.updateText(); + } + + return this; + }, + + /** + * Set the text style. + * + * @example + * text.setStyle({ + * fontSize: '64px', + * fontFamily: 'Arial', + * color: '#ffffff', + * align: 'center', + * backgroundColor: '#ff00ff' + * }); + * + * @method Phaser.GameObjects.Text#setStyle + * @since 3.0.0 + * + * @param {object} style - The style settings to set. + * + * @return {this} This Text object. + */ + setStyle: function (style) + { + return this.style.setStyle(style); + }, + + /** + * 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:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: + * + * ```javascript + * Text.setFont('"Roboto Condensed"'); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * Text.setFont('Verdana, "Times New Roman", Tahoma, 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. + */ + setFont: function (font) + { + return this.style.setFont(font); + }, + + /** + * Set the font family. + * + * **Important:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: + * + * ```javascript + * Text.setFont('"Roboto Condensed"'); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); + * ``` + * + * @method Phaser.GameObjects.Text#setFontFamily + * @since 3.0.0 + * + * @param {string} family - The font family. + * + * @return {this} This Text object. + */ + setFontFamily: function (family) + { + return this.style.setFontFamily(family); + }, + + /** + * Set the font size. + * + * @method Phaser.GameObjects.Text#setFontSize + * @since 3.0.0 + * + * @param {number} size - The font size. + * + * @return {this} This Text object. + */ + setFontSize: function (size) + { + return this.style.setFontSize(size); + }, + + /** + * Set the font style. + * + * @method Phaser.GameObjects.Text#setFontStyle + * @since 3.0.0 + * + * @param {string} style - The font style. + * + * @return {this} This Text object. + */ + setFontStyle: function (style) + { + return this.style.setFontStyle(style); + }, + + /** + * Set a fixed width and height for the text. + * + * Pass in `0` for either of these parameters to disable fixed width or height respectively. + * + * @method Phaser.GameObjects.Text#setFixedSize + * @since 3.0.0 + * + * @param {number} width - The fixed width to set. `0` disables fixed width. + * @param {number} height - The fixed height to set. `0` disables fixed height. + * + * @return {this} This Text object. + */ + setFixedSize: function (width, height) + { + return this.style.setFixedSize(width, height); + }, + + /** + * Set the background color. + * + * @method Phaser.GameObjects.Text#setBackgroundColor + * @since 3.0.0 + * + * @param {string} color - The background color. + * + * @return {this} This Text object. + */ + setBackgroundColor: function (color) + { + return this.style.setBackgroundColor(color); + }, + + /** + * 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|any)} color - The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. + * + * @return {this} This Text object. + */ + setFill: function (fillStyle) + { + return this.style.setFill(fillStyle); + }, + + /** + * Set the text fill color. + * + * @method Phaser.GameObjects.Text#setColor + * @since 3.0.0 + * + * @param {string} color - The text fill color. + * + * @return {this} This Text object. + */ + setColor: function (color) + { + return this.style.setColor(color); + }, + + /** + * Set the stroke settings. + * + * @method Phaser.GameObjects.Text#setStroke + * @since 3.0.0 + * + * @param {string} color - The stroke color. + * @param {number} thickness - The stroke thickness. + * + * @return {this} This Text object. + */ + setStroke: function (color, thickness) + { + return this.style.setStroke(color, thickness); + }, + + /** + * Set the shadow settings. + * + * @method Phaser.GameObjects.Text#setShadow + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal shadow offset. + * @param {number} [y=0] - The vertical shadow offset. + * @param {string} [color='#000'] - The shadow color. + * @param {number} [blur=0] - The shadow blur radius. + * @param {boolean} [shadowStroke=false] - Whether to stroke the shadow. + * @param {boolean} [shadowFill=true] - Whether to fill the shadow. + * + * @return {this} This Text object. + */ + setShadow: function (x, y, color, blur, shadowStroke, shadowFill) + { + return this.style.setShadow(x, y, color, blur, shadowStroke, shadowFill); + }, + + /** + * Set the shadow offset. + * + * @method Phaser.GameObjects.Text#setShadowOffset + * @since 3.0.0 + * + * @param {number} x - The horizontal shadow offset. + * @param {number} y - The vertical shadow offset. + * + * @return {this} This Text object. + */ + setShadowOffset: function (x, y) + { + return this.style.setShadowOffset(x, y); + }, + + /** + * Set the shadow color. + * + * @method Phaser.GameObjects.Text#setShadowColor + * @since 3.0.0 + * + * @param {string} color - The shadow color. + * + * @return {this} This Text object. + */ + setShadowColor: function (color) + { + return this.style.setShadowColor(color); + }, + + /** + * Set the shadow blur radius. + * + * @method Phaser.GameObjects.Text#setShadowBlur + * @since 3.0.0 + * + * @param {number} blur - The shadow blur radius. + * + * @return {this} This Text object. + */ + setShadowBlur: function (blur) + { + return this.style.setShadowBlur(blur); + }, + + /** + * Enable or disable shadow stroke. + * + * @method Phaser.GameObjects.Text#setShadowStroke + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow stroke is enabled or not. + * + * @return {this} This Text object. + */ + setShadowStroke: function (enabled) + { + return this.style.setShadowStroke(enabled); + }, + + /** + * Enable or disable shadow fill. + * + * @method Phaser.GameObjects.Text#setShadowFill + * @since 3.0.0 + * + * @param {boolean} enabled - Whether shadow fill is enabled or not. + * + * @return {this} This Text object. + */ + setShadowFill: function (enabled) + { + return this.style.setShadowFill(enabled); + }, + + /** + * Set the width (in pixels) to use for wrapping lines. Pass in null to remove wrapping by width. + * + * @method Phaser.GameObjects.Text#setWordWrapWidth + * @since 3.0.0 + * + * @param {?number} width - The maximum width of a line in pixels. Set to null to remove wrapping. + * @param {boolean} [useAdvancedWrap=false] - Whether or not to use the advanced wrapping + * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, + * spaces and whitespace are left as is. + * + * @return {this} This Text object. + */ + setWordWrapWidth: function (width, useAdvancedWrap) + { + return this.style.setWordWrapWidth(width, useAdvancedWrap); + }, + + /** + * Set a custom callback for wrapping lines. Pass in null to remove wrapping by callback. + * + * @method Phaser.GameObjects.Text#setWordWrapCallback + * @since 3.0.0 + * + * @param {TextStyleWordWrapCallback} callback - A custom function that will be responsible for wrapping the + * text. It will receive two arguments: text (the string to wrap), textObject (this Text + * instance). It should return the wrapped lines either as an array of lines or as a string with + * newline characters in place to indicate where breaks should happen. + * @param {object} [scope=null] - The scope that will be applied when the callback is invoked. + * + * @return {this} This Text object. + */ + setWordWrapCallback: function (callback, scope) + { + return this.style.setWordWrapCallback(callback, scope); + }, + + /** + * Set the alignment of the text in this Text object. + * + * The argument can be one of: `left`, `right`, `center` or `justify`. + * + * Alignment only works if the Text object has more than one line of text. + * + * @method Phaser.GameObjects.Text#setAlign + * @since 3.0.0 + * + * @param {string} [align='left'] - The text alignment for multi-line text. + * + * @return {this} This Text object. + */ + setAlign: function (align) + { + return this.style.setAlign(align); + }, + + /** + * Set the resolution used by this Text object. + * + * By default it will be set to match the resolution set in the Game Config, + * but you can override it via this method, or by specifying it in the Text style configuration object. + * + * It allows for much clearer text on High DPI devices, at the cost of memory because it uses larger + * internal Canvas textures for the Text. + * + * Therefore, please use with caution, as the more high res Text you have, the more memory it uses. + * + * @method Phaser.GameObjects.Text#setResolution + * @since 3.12.0 + * + * @param {number} value - The resolution for this Text object to use. + * + * @return {this} This Text object. + */ + setResolution: function (value) + { + return this.style.setResolution(value); + }, + + /** + * Sets the line spacing value. + * + * This value is _added_ to the height of the font when calculating the overall line height. + * This only has an effect if this Text object consists of multiple lines of text. + * + * @method Phaser.GameObjects.Text#setLineSpacing + * @since 3.13.0 + * + * @param {number} value - The amount to add to the font height to achieve the overall line height. + * + * @return {this} This Text object. + */ + setLineSpacing: function (value) + { + this.lineSpacing = value; + + return this.updateText(); + }, + + /** + * Set the text padding. + * + * 'left' can be an object. + * + * If only 'left' and 'top' are given they are treated as 'x' and 'y'. + * + * @method Phaser.GameObjects.Text#setPadding + * @since 3.0.0 + * + * @param {(number|Phaser.Types.GameObjects.Text.TextPadding)} left - The left padding value, or a padding config object. + * @param {number} top - The top padding value. + * @param {number} right - The right padding value. + * @param {number} bottom - The bottom padding value. + * + * @return {this} This Text object. + */ + setPadding: function (left, top, right, bottom) + { + if (typeof left === 'object') + { + var config = left; + + // If they specify x and/or y this applies to all + var x = GetValue(config, 'x', null); + + if (x !== null) + { + left = x; + right = x; + } + else + { + left = GetValue(config, 'left', 0); + right = GetValue(config, 'right', left); + } + + var y = GetValue(config, 'y', null); + + if (y !== null) + { + top = y; + bottom = y; + } + else + { + top = GetValue(config, 'top', 0); + bottom = GetValue(config, 'bottom', top); + } + } + else + { + if (left === undefined) { left = 0; } + if (top === undefined) { top = left; } + if (right === undefined) { right = left; } + if (bottom === undefined) { bottom = top; } + } + + this.padding.left = left; + this.padding.top = top; + this.padding.right = right; + this.padding.bottom = bottom; + + return this.updateText(); + }, + + /** + * Set the maximum number of lines to draw. + * + * @method Phaser.GameObjects.Text#setMaxLines + * @since 3.0.0 + * + * @param {integer} [max=0] - The maximum number of lines to draw. + * + * @return {this} This Text object. + */ + setMaxLines: function (max) + { + return this.style.setMaxLines(max); + }, + + /** + * Update the displayed text. + * + * @method Phaser.GameObjects.Text#updateText + * @since 3.0.0 + * + * @return {this} This Text object. + */ + updateText: function () + { + var canvas = this.canvas; + var context = this.context; + var style = this.style; + var resolution = style.resolution; + var size = style.metrics; + + style.syncFont(canvas, context); + + var outputText = this._text; + + if (style.wordWrapWidth || style.wordWrapCallback) + { + outputText = this.runWordWrap(this._text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + var textSize = GetTextSize(this, size, lines); + + var padding = this.padding; + + var textWidth; + + if (style.fixedWidth === 0) + { + this.width = textSize.width + padding.left + padding.right; + + textWidth = textSize.width; + } + else + { + this.width = style.fixedWidth; + + textWidth = this.width - padding.left - padding.right; + + if (textWidth < textSize.width) + { + textWidth = textSize.width; + } + } + + if (style.fixedHeight === 0) + { + this.height = textSize.height + padding.top + padding.bottom; + } + else + { + this.height = style.fixedHeight; + } + + var w = this.width; + var h = this.height; + + this.updateDisplayOrigin(); + + w *= resolution; + h *= resolution; + + w = Math.max(w, 1); + h = Math.max(h, 1); + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + + this.frame.setSize(w, h); + + // Because resizing the canvas resets the context + style.syncFont(canvas, context); + } + else + { + context.clearRect(0, 0, w, h); + } + + context.save(); + + context.scale(resolution, resolution); + + if (style.backgroundColor) + { + context.fillStyle = style.backgroundColor; + context.fillRect(0, 0, w, h); + } + + style.syncStyle(canvas, context); + + context.textBaseline = 'alphabetic'; + + // Apply padding + context.translate(padding.left, padding.top); + + var linePositionX; + var linePositionY; + + // Draw text line by line + for (var i = 0; i < textSize.lines; i++) + { + linePositionX = style.strokeThickness / 2; + linePositionY = (style.strokeThickness / 2 + i * textSize.lineHeight) + size.ascent; + + if (i > 0) + { + linePositionY += (textSize.lineSpacing * i); + } + + if (style.rtl) + { + linePositionX = w - linePositionX; + } + else if (style.align === 'right') + { + linePositionX += textWidth - textSize.lineWidths[i]; + } + else if (style.align === 'center') + { + linePositionX += (textWidth - textSize.lineWidths[i]) / 2; + } + else if (style.align === 'justify') + { + // To justify text line its width must be no less than 85% of defined width + var minimumLengthToApplyJustification = 0.85; + + if (textSize.lineWidths[i] / textSize.width >= minimumLengthToApplyJustification) + { + var extraSpace = textSize.width - textSize.lineWidths[i]; + var spaceSize = context.measureText(' ').width; + var trimmedLine = lines[i].trim(); + var array = trimmedLine.split(' '); + + extraSpace += (lines[i].length - trimmedLine.length) * spaceSize; + + var extraSpaceCharacters = Math.floor(extraSpace / spaceSize); + var idx = 0; + + while (extraSpaceCharacters > 0) + { + array[idx] += ' '; + idx = (idx + 1) % (array.length - 1 || 1); + --extraSpaceCharacters; + } + + lines[i] = array.join(' '); + } + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (style.strokeThickness) + { + this.style.syncShadow(context, style.shadowStroke); + + context.strokeText(lines[i], linePositionX, linePositionY); + } + + if (style.color) + { + this.style.syncShadow(context, style.shadowFill); + + context.fillText(lines[i], linePositionX, linePositionY); + } + } + + context.restore(); + + if (this.renderer.gl) + { + this.frame.source.glTexture = this.renderer.canvasToTexture(canvas, this.frame.source.glTexture, true); + + this.frame.glTexture = this.frame.source.glTexture; + } + + this.dirty = true; + + var input = this.input; + + if (input && !input.customHitArea) + { + input.hitArea.width = this.width; + input.hitArea.height = this.height; + } + + return this; + }, + + /** + * Get the current text metrics. + * + * @method Phaser.GameObjects.Text#getTextMetrics + * @since 3.0.0 + * + * @return {object} The text metrics. + */ + getTextMetrics: function () + { + return this.style.getTextMetrics(); + }, + + /** + * The text string being rendered by this Text Game Object. + * + * @name Phaser.GameObjects.Text#text + * @type {string} + * @since 3.0.0 + */ + text: { + + get: function () + { + return this._text; + }, + + set: function (value) + { + this.setText(value); + } + + }, + + /** + * Build a JSON representation of the Text object. + * + * @method Phaser.GameObjects.Text#toJSON + * @since 3.0.0 + * + * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Text object. + */ + toJSON: function () + { + var out = Components.ToJSON(this); + + // Extra Text data is added here + + var data = { + autoRound: this.autoRound, + text: this._text, + style: this.style.toJSON(), + padding: { + left: this.padding.left, + right: this.padding.right, + top: this.padding.top, + bottom: this.padding.bottom + } + }; + + out.data = data; + + return out; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.Text#preDestroy + * @protected + * @since 3.0.0 + */ + preDestroy: function () + { + if (this.style.rtl) + { + RemoveFromDOM(this.canvas); + } + + CanvasPool.remove(this.canvas); + + this.texture.destroy(); + } + + /** + * 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 + */ + +}); + +module.exports = Text; diff --git a/src/gameobjects/text/static/TextCanvasRenderer.js b/src/gameobjects/text/static/TextCanvasRenderer.js index 87cb99856..e795adc1e 100644 --- a/src/gameobjects/text/static/TextCanvasRenderer.js +++ b/src/gameobjects/text/static/TextCanvasRenderer.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Text#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Text} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var TextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - if ((src.width === 0) || (src.height === 0)) - { - return; - } - - renderer.batchSprite(src, src.frame, camera, parentMatrix); -}; - -module.exports = TextCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Text#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Text} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TextCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if ((src.width === 0) || (src.height === 0)) + { + return; + } + + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = TextCanvasRenderer; diff --git a/src/gameobjects/text/static/TextCreator.js b/src/gameobjects/text/static/TextCreator.js index 2baedc2ca..d62778617 100644 --- a/src/gameobjects/text/static/TextCreator.js +++ b/src/gameobjects/text/static/TextCreator.js @@ -1,81 +1,81 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../../BuildGameObject'); -var GameObjectCreator = require('../../GameObjectCreator'); -var GetAdvancedValue = require('../../../utils/object/GetAdvancedValue'); -var Text = require('./Text'); - -/** - * Creates a new Text Game Object and returns it. - * - * Note: This method will only be available if the Text Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#text - * @since 3.0.0 - * - * @param {object} 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.Text} The Game Object that was created. - */ -GameObjectCreator.register('text', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - // 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 ] - // } - - var content = GetAdvancedValue(config, 'text', ''); - var style = GetAdvancedValue(config, 'style', null); - - // Padding - // { padding: 2 } - // { padding: { x: , y: }} - // { padding: { left: , top: }} - // { padding: { left: , right: , top: , bottom: }} - - var padding = GetAdvancedValue(config, 'padding', null); - - if (padding !== null) - { - style.padding = padding; - } - - var text = new Text(this.scene, 0, 0, content, style); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, text, config); - - // Text specific config options: - - text.autoRound = GetAdvancedValue(config, 'autoRound', true); - text.resolution = GetAdvancedValue(config, 'resolution', 1); - - return text; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../../BuildGameObject'); +var GameObjectCreator = require('../../GameObjectCreator'); +var GetAdvancedValue = require('../../../utils/object/GetAdvancedValue'); +var Text = require('./Text'); + +/** + * Creates a new Text Game Object and returns it. + * + * Note: This method will only be available if the Text Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#text + * @since 3.0.0 + * + * @param {object} 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.Text} The Game Object that was created. + */ +GameObjectCreator.register('text', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + // 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 ] + // } + + var content = GetAdvancedValue(config, 'text', ''); + var style = GetAdvancedValue(config, 'style', null); + + // Padding + // { padding: 2 } + // { padding: { x: , y: }} + // { padding: { left: , top: }} + // { padding: { left: , right: , top: , bottom: }} + + var padding = GetAdvancedValue(config, 'padding', null); + + if (padding !== null) + { + style.padding = padding; + } + + var text = new Text(this.scene, 0, 0, content, style); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, text, config); + + // Text specific config options: + + text.autoRound = GetAdvancedValue(config, 'autoRound', true); + text.resolution = GetAdvancedValue(config, 'resolution', 1); + + return text; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/text/static/TextFactory.js b/src/gameobjects/text/static/TextFactory.js index d639aae23..f8e88023e 100644 --- a/src/gameobjects/text/static/TextFactory.js +++ b/src/gameobjects/text/static/TextFactory.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Text = require('./Text'); -var GameObjectFactory = require('../../GameObjectFactory'); - -/** - * Creates a new Text Game Object and adds it to the Scene. - * - * 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. - * - * You can only display fonts that are currently loaded and available to the browser: therefore fonts must - * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, - * or have the fonts ready 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 {object} [style] - The Text style configuration object. - * - * @return {Phaser.GameObjects.Text} The Game Object that was created. - */ -GameObjectFactory.register('text', function (x, y, text, style) -{ - return this.displayList.add(new Text(this.scene, x, y, text, style)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Text = require('./Text'); +var GameObjectFactory = require('../../GameObjectFactory'); + +/** + * Creates a new Text Game Object and adds it to the Scene. + * + * 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. + * + * You can only display fonts that are currently loaded and available to the browser: therefore fonts must + * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, + * or have the fonts ready 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 {object} [style] - The Text style configuration object. + * + * @return {Phaser.GameObjects.Text} The Game Object that was created. + */ +GameObjectFactory.register('text', function (x, y, text, style) +{ + return this.displayList.add(new Text(this.scene, x, y, text, style)); +}); + +// 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 diff --git a/src/gameobjects/text/static/TextRender.js b/src/gameobjects/text/static/TextRender.js index a48d3935f..9a4288276 100644 --- a/src/gameobjects/text/static/TextRender.js +++ b/src/gameobjects/text/static/TextRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../../utils/NOOP'); -var renderCanvas = require('../../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./TextWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./TextCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../../utils/NOOP'); +var renderCanvas = require('../../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./TextWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./TextCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/text/static/TextWebGLRenderer.js b/src/gameobjects/text/static/TextWebGLRenderer.js index 70d379422..4a2478383 100644 --- a/src/gameobjects/text/static/TextWebGLRenderer.js +++ b/src/gameobjects/text/static/TextWebGLRenderer.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Text#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Text} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var TextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - if ((src.width === 0) || (src.height === 0)) - { - return; - } - - var frame = src.frame; - var width = frame.width; - var height = frame.height; - var getTint = Utils.getTintAppendFloatAlpha; - - this.pipeline.batchTexture( - src, - frame.glTexture, - width, height, - src.x, src.y, - width / src.style.resolution, height / src.style.resolution, - src.scaleX, src.scaleY, - src.rotation, - src.flipX, src.flipY, - src.scrollFactorX, src.scrollFactorY, - src.displayOriginX, src.displayOriginY, - 0, 0, width, height, - getTint(src._tintTL, camera.alpha * src._alphaTL), - getTint(src._tintTR, camera.alpha * src._alphaTR), - getTint(src._tintBL, camera.alpha * src._alphaBL), - getTint(src._tintBR, camera.alpha * src._alphaBR), - (src._isTinted && src.tintFill), - 0, 0, - camera, - parentMatrix - ); -}; - -module.exports = TextWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Text#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Text} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TextWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if ((src.width === 0) || (src.height === 0)) + { + return; + } + + var frame = src.frame; + var width = frame.width; + var height = frame.height; + var getTint = Utils.getTintAppendFloatAlpha; + + this.pipeline.batchTexture( + src, + frame.glTexture, + width, height, + src.x, src.y, + width / src.style.resolution, height / src.style.resolution, + src.scaleX, src.scaleY, + src.rotation, + src.flipX, src.flipY, + src.scrollFactorX, src.scrollFactorY, + src.displayOriginX, src.displayOriginY, + 0, 0, width, height, + getTint(src._tintTL, camera.alpha * src._alphaTL), + getTint(src._tintTR, camera.alpha * src._alphaTR), + getTint(src._tintBL, camera.alpha * src._alphaBL), + getTint(src._tintBR, camera.alpha * src._alphaBR), + (src._isTinted && src.tintFill), + 0, 0, + camera, + parentMatrix + ); +}; + +module.exports = TextWebGLRenderer; diff --git a/src/gameobjects/text/typedefs/index.js b/src/gameobjects/text/typedefs/index.js index 70c06926c..cfb2e8d57 100644 --- a/src/gameobjects/text/typedefs/index.js +++ b/src/gameobjects/text/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.Text - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.Text + */ diff --git a/src/gameobjects/tilesprite/TileSprite.js b/src/gameobjects/tilesprite/TileSprite.js index d58fd5a90..f226aec5e 100644 --- a/src/gameobjects/tilesprite/TileSprite.js +++ b/src/gameobjects/tilesprite/TileSprite.js @@ -1,646 +1,646 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../../display/canvas/CanvasPool'); -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameEvents = require('../../core/events'); -var GameObject = require('../GameObject'); -var GetPowerOfTwo = require('../../math/pow2/GetPowerOfTwo'); -var Smoothing = require('../../display/canvas/Smoothing'); -var TileSpriteRender = require('./TileSpriteRender'); -var Vector2 = require('../../math/Vector2'); - -// bitmask flag for GameObject.renderMask -var _FLAG = 8; // 1000 - -/** - * @classdesc - * A TileSprite is a Sprite that has a repeating texture. - * - * The texture can be scrolled and scaled independently of the TileSprite itself. Textures will automatically wrap and - * are designed so that you can create game backdrops using seamless textures as a source. - * - * You shouldn't ever create a TileSprite any larger than your actual canvas size. If you want to create a large repeating background - * that scrolls across the whole map of your game, then you create a TileSprite that fits the canvas size and then use the `tilePosition` - * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will - * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to - * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. - * - * An important note about Tile Sprites and NPOT textures: Internally, TileSprite textures use GL_REPEAT to provide - * seamless repeating of the textures. This, combined with the way in which the textures are handled in WebGL, means - * they need to be POT (power-of-two) sizes in order to wrap. If you provide a NPOT (non power-of-two) texture to a - * TileSprite it will generate a POT sized canvas and draw your texture to it, scaled up to the POT size. It's then - * scaled back down again during rendering to the original dimensions. While this works, in that it allows you to use - * any size texture for a Tile Sprite, it does mean that NPOT textures are going to appear anti-aliased when rendered, - * due to the interpolation that took place when it was resized into a POT texture. This is especially visible in - * pixel art graphics. If you notice it and it becomes an issue, the only way to avoid it is to ensure that you - * provide POT textures for Tile Sprites. - * - * @class TileSprite - * @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.Pipeline - * @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 {integer} width - The width of the Game Object. If zero it will use the size of the texture frame. - * @param {integer} height - The height of the Game Object. If zero it will use the size of the texture frame. - * @param {string} textureKey - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frameKey] - An optional frame from the Texture this Game Object is rendering with. - */ -var TileSprite = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.ComputedSize, - Components.Crop, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Tint, - Components.Transform, - Components.Visible, - TileSpriteRender - ], - - initialize: - - function TileSprite (scene, x, y, width, height, textureKey, frameKey) - { - var renderer = scene.sys.game.renderer; - - GameObject.call(this, scene, 'TileSprite'); - - var displayTexture = scene.sys.textures.get(textureKey); - var displayFrame = displayTexture.get(frameKey); - - if (!width || !height) - { - width = displayFrame.width; - height = displayFrame.height; - } - else - { - width = Math.floor(width); - height = Math.floor(height); - } - - /** - * Internal tile position vector. - * - * @name Phaser.GameObjects.TileSprite#_tilePosition - * @type {Phaser.Math.Vector2} - * @private - * @since 3.12.0 - */ - this._tilePosition = new Vector2(); - - /** - * Internal tile scale vector. - * - * @name Phaser.GameObjects.TileSprite#_tileScale - * @type {Phaser.Math.Vector2} - * @private - * @since 3.12.0 - */ - this._tileScale = new Vector2(1, 1); - - /** - * Whether the Tile Sprite has changed in some way, requiring an re-render of its tile texture. - * - * Such changes include the texture frame and scroll position of the Tile Sprite. - * - * @name Phaser.GameObjects.TileSprite#dirty - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.dirty = false; - - /** - * The renderer in use by this Tile Sprite. - * - * @name Phaser.GameObjects.TileSprite#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.0.0 - */ - this.renderer = renderer; - - /** - * The Canvas element that the TileSprite renders its fill pattern in to. - * Only used in Canvas mode. - * - * @name Phaser.GameObjects.TileSprite#canvas - * @type {?HTMLCanvasElement} - * @since 3.12.0 - */ - this.canvas = CanvasPool.create(this, width, height); - - /** - * The Context of the Canvas element that the TileSprite renders its fill pattern in to. - * Only used in Canvas mode. - * - * @name Phaser.GameObjects.TileSprite#context - * @type {CanvasRenderingContext2D} - * @since 3.12.0 - */ - this.context = this.canvas.getContext('2d'); - - /** - * The Texture the TileSprite is using as its fill pattern. - * - * @name Phaser.GameObjects.TileSprite#displayTexture - * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} - * @private - * @since 3.12.0 - */ - this.displayTexture = displayTexture; - - /** - * The Frame the TileSprite is using as its fill pattern. - * - * @name Phaser.GameObjects.TileSprite#displayFrame - * @type {Phaser.Textures.Frame} - * @private - * @since 3.12.0 - */ - this.displayFrame = displayFrame; - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.TileSprite#_crop - * @type {object} - * @private - * @since 3.12.0 - */ - this._crop = this.resetCropObject(); - - /** - * The Texture this Game Object is using to render with. - * - * @name Phaser.GameObjects.TileSprite#texture - * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} - * @since 3.0.0 - */ - this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); - - /** - * The Texture Frame this Game Object is using to render with. - * - * @name Phaser.GameObjects.TileSprite#frame - * @type {Phaser.Textures.Frame} - * @since 3.0.0 - */ - this.frame = this.texture.get(); - - /** - * The next power of two value from the width of the Fill Pattern frame. - * - * @name Phaser.GameObjects.TileSprite#potWidth - * @type {integer} - * @since 3.0.0 - */ - this.potWidth = GetPowerOfTwo(displayFrame.width); - - /** - * The next power of two value from the height of the Fill Pattern frame. - * - * @name Phaser.GameObjects.TileSprite#potHeight - * @type {integer} - * @since 3.0.0 - */ - this.potHeight = GetPowerOfTwo(displayFrame.height); - - /** - * The Canvas that the TileSprites texture is rendered to. - * This is used to create a WebGL texture from. - * - * @name Phaser.GameObjects.TileSprite#fillCanvas - * @type {HTMLCanvasElement} - * @since 3.12.0 - */ - this.fillCanvas = CanvasPool.create2D(this, this.potWidth, this.potHeight); - - /** - * The Canvas Context used to render the TileSprites texture. - * - * @name Phaser.GameObjects.TileSprite#fillContext - * @type {CanvasRenderingContext2D} - * @since 3.12.0 - */ - this.fillContext = this.fillCanvas.getContext('2d'); - - /** - * The texture that the Tile Sprite is rendered to, which is then rendered to a Scene. - * In WebGL this is a WebGLTexture. In Canvas it's a Canvas Fill Pattern. - * - * @name Phaser.GameObjects.TileSprite#fillPattern - * @type {?(WebGLTexture|CanvasPattern)} - * @since 3.12.0 - */ - this.fillPattern = null; - - this.setPosition(x, y); - this.setSize(width, height); - this.setFrame(frameKey); - this.setOriginFromFrame(); - this.initPipeline(); - - scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer) - { - var gl = renderer.gl; - - this.dirty = true; - this.fillPattern = null; - this.fillPattern = renderer.createTexture2D(0, gl.LINEAR, gl.LINEAR, gl.REPEAT, gl.REPEAT, gl.RGBA, this.fillCanvas, this.potWidth, this.potHeight); - - }, this); - }, - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * @method Phaser.GameObjects.TileSprite#setTexture - * @since 3.0.0 - * - * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. - * - * @return {this} This Game Object instance. - */ - setTexture: function (key, frame) - { - this.displayTexture = this.scene.sys.textures.get(key); - - return this.setFrame(frame); - }, - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * @method Phaser.GameObjects.TileSprite#setFrame - * @since 3.0.0 - * - * @param {(string|integer)} frame - The name or index of the frame within the Texture. - * - * @return {this} This Game Object instance. - */ - setFrame: function (frame) - { - var newFrame = this.displayTexture.get(frame); - - this.potWidth = GetPowerOfTwo(newFrame.width); - this.potHeight = GetPowerOfTwo(newFrame.height); - - // So updateCanvas is triggered - this.canvas.width = 0; - - if (!newFrame.cutWidth || !newFrame.cutHeight) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - - this.displayFrame = newFrame; - - this.dirty = true; - - this.updateTileTexture(); - - return this; - }, - - /** - * Sets {@link Phaser.GameObjects.TileSprite#tilePositionX} and {@link Phaser.GameObjects.TileSprite#tilePositionY}. - * - * @method Phaser.GameObjects.TileSprite#setTilePosition - * @since 3.3.0 - * - * @param {number} [x] - The x position of this sprite's tiling texture. - * @param {number} [y] - The y position of this sprite's tiling texture. - * - * @return {this} This Tile Sprite instance. - */ - setTilePosition: function (x, y) - { - if (x !== undefined) - { - this.tilePositionX = x; - } - - if (y !== undefined) - { - this.tilePositionY = y; - } - - return this; - }, - - /** - * Sets {@link Phaser.GameObjects.TileSprite#tileScaleX} and {@link Phaser.GameObjects.TileSprite#tileScaleY}. - * - * @method Phaser.GameObjects.TileSprite#setTileScale - * @since 3.12.0 - * - * @param {number} [x] - The horizontal scale of the tiling texture. If not given it will use the current `tileScaleX` value. - * @param {number} [y=x] - The vertical scale of the tiling texture. If not given it will use the `x` value. - * - * @return {this} This Tile Sprite instance. - */ - setTileScale: function (x, y) - { - if (x === undefined) { x = this.tileScaleX; } - if (y === undefined) { y = x; } - - this.tileScaleX = x; - this.tileScaleY = y; - - return this; - }, - - /** - * Render the tile texture if it is dirty, or if the frame has changed. - * - * @method Phaser.GameObjects.TileSprite#updateTileTexture - * @private - * @since 3.0.0 - */ - updateTileTexture: function () - { - if (!this.dirty || !this.renderer) - { - return; - } - - // Draw the displayTexture to our fillCanvas - - var frame = this.displayFrame; - - if (frame.source.isRenderTexture || frame.source.isGLTexture) - { - console.warn('TileSprites can only use Image or Canvas based textures'); - - this.dirty = false; - - return; - } - - var ctx = this.fillContext; - var canvas = this.fillCanvas; - - var fw = this.potWidth; - var fh = this.potHeight; - - if (!this.renderer.gl) - { - fw = frame.cutWidth; - fh = frame.cutHeight; - } - - ctx.clearRect(0, 0, fw, fh); - - canvas.width = fw; - canvas.height = fh; - - ctx.drawImage( - frame.source.image, - frame.cutX, frame.cutY, - frame.cutWidth, frame.cutHeight, - 0, 0, - fw, fh - ); - - if (this.renderer.gl) - { - this.fillPattern = this.renderer.canvasToTexture(canvas, this.fillPattern); - } - else - { - this.fillPattern = ctx.createPattern(canvas, 'repeat'); - } - - this.updateCanvas(); - - this.dirty = false; - }, - - /** - * Draw the fill pattern to the internal canvas. - * - * @method Phaser.GameObjects.TileSprite#updateCanvas - * @private - * @since 3.12.0 - */ - updateCanvas: function () - { - var canvas = this.canvas; - - if (canvas.width !== this.width || canvas.height !== this.height) - { - canvas.width = this.width; - canvas.height = this.height; - - this.frame.setSize(this.width, this.height); - this.updateDisplayOrigin(); - - this.dirty = true; - } - - if (!this.dirty || this.renderer && this.renderer.gl) - { - this.dirty = false; - return; - } - - var ctx = this.context; - - if (!this.scene.sys.game.config.antialias) - { - Smoothing.disable(ctx); - } - - var scaleX = this._tileScale.x; - var scaleY = this._tileScale.y; - - var positionX = this._tilePosition.x; - var positionY = this._tilePosition.y; - - ctx.clearRect(0, 0, this.width, this.height); - - ctx.save(); - - ctx.scale(scaleX, scaleY); - - ctx.translate(-positionX, -positionY); - - ctx.fillStyle = this.fillPattern; - - ctx.fillRect(positionX, positionY, this.width / scaleX, this.height / scaleY); - - ctx.restore(); - - this.dirty = false; - }, - - /** - * Internal destroy handler, called as part of the destroy process. - * - * @method Phaser.GameObjects.TileSprite#preDestroy - * @protected - * @since 3.9.0 - */ - preDestroy: function () - { - if (this.renderer && this.renderer.gl) - { - this.renderer.deleteTexture(this.fillPattern); - } - - CanvasPool.remove(this.canvas); - CanvasPool.remove(this.fillCanvas); - - this.fillPattern = null; - this.fillContext = null; - this.fillCanvas = null; - - this.displayTexture = null; - this.displayFrame = null; - - this.texture.destroy(); - - this.renderer = null; - }, - - /** - * The horizontal scroll position of the Tile Sprite. - * - * @name Phaser.GameObjects.TileSprite#tilePositionX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - tilePositionX: { - - get: function () - { - return this._tilePosition.x; - }, - - set: function (value) - { - this._tilePosition.x = value; - this.dirty = true; - } - - }, - - /** - * The vertical scroll position of the Tile Sprite. - * - * @name Phaser.GameObjects.TileSprite#tilePositionY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - tilePositionY: { - - get: function () - { - return this._tilePosition.y; - }, - - set: function (value) - { - this._tilePosition.y = value; - this.dirty = true; - } - - }, - - /** - * The horizontal scale of the Tile Sprite texture. - * - * @name Phaser.GameObjects.TileSprite#tileScaleX - * @type {number} - * @default 1 - * @since 3.11.0 - */ - tileScaleX: { - - get: function () - { - return this._tileScale.x; - }, - - set: function (value) - { - this._tileScale.x = value; - this.dirty = true; - } - - }, - - /** - * The vertical scale of the Tile Sprite texture. - * - * @name Phaser.GameObjects.TileSprite#tileScaleY - * @type {number} - * @default 1 - * @since 3.11.0 - */ - tileScaleY: { - - get: function () - { - return this._tileScale.y; - }, - - set: function (value) - { - this._tileScale.y = value; - this.dirty = true; - } - - } - -}); - -module.exports = TileSprite; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../../display/canvas/CanvasPool'); +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameEvents = require('../../core/events'); +var GameObject = require('../GameObject'); +var GetPowerOfTwo = require('../../math/pow2/GetPowerOfTwo'); +var Smoothing = require('../../display/canvas/Smoothing'); +var TileSpriteRender = require('./TileSpriteRender'); +var Vector2 = require('../../math/Vector2'); + +// bitmask flag for GameObject.renderMask +var _FLAG = 8; // 1000 + +/** + * @classdesc + * A TileSprite is a Sprite that has a repeating texture. + * + * The texture can be scrolled and scaled independently of the TileSprite itself. Textures will automatically wrap and + * are designed so that you can create game backdrops using seamless textures as a source. + * + * You shouldn't ever create a TileSprite any larger than your actual canvas size. If you want to create a large repeating background + * that scrolls across the whole map of your game, then you create a TileSprite that fits the canvas size and then use the `tilePosition` + * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will + * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to + * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. + * + * An important note about Tile Sprites and NPOT textures: Internally, TileSprite textures use GL_REPEAT to provide + * seamless repeating of the textures. This, combined with the way in which the textures are handled in WebGL, means + * they need to be POT (power-of-two) sizes in order to wrap. If you provide a NPOT (non power-of-two) texture to a + * TileSprite it will generate a POT sized canvas and draw your texture to it, scaled up to the POT size. It's then + * scaled back down again during rendering to the original dimensions. While this works, in that it allows you to use + * any size texture for a Tile Sprite, it does mean that NPOT textures are going to appear anti-aliased when rendered, + * due to the interpolation that took place when it was resized into a POT texture. This is especially visible in + * pixel art graphics. If you notice it and it becomes an issue, the only way to avoid it is to ensure that you + * provide POT textures for Tile Sprites. + * + * @class TileSprite + * @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.Pipeline + * @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 {integer} width - The width of the Game Object. If zero it will use the size of the texture frame. + * @param {integer} height - The height of the Game Object. If zero it will use the size of the texture frame. + * @param {string} textureKey - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frameKey] - An optional frame from the Texture this Game Object is rendering with. + */ +var TileSprite = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Crop, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Tint, + Components.Transform, + Components.Visible, + TileSpriteRender + ], + + initialize: + + function TileSprite (scene, x, y, width, height, textureKey, frameKey) + { + var renderer = scene.sys.game.renderer; + + GameObject.call(this, scene, 'TileSprite'); + + var displayTexture = scene.sys.textures.get(textureKey); + var displayFrame = displayTexture.get(frameKey); + + if (!width || !height) + { + width = displayFrame.width; + height = displayFrame.height; + } + else + { + width = Math.floor(width); + height = Math.floor(height); + } + + /** + * Internal tile position vector. + * + * @name Phaser.GameObjects.TileSprite#_tilePosition + * @type {Phaser.Math.Vector2} + * @private + * @since 3.12.0 + */ + this._tilePosition = new Vector2(); + + /** + * Internal tile scale vector. + * + * @name Phaser.GameObjects.TileSprite#_tileScale + * @type {Phaser.Math.Vector2} + * @private + * @since 3.12.0 + */ + this._tileScale = new Vector2(1, 1); + + /** + * Whether the Tile Sprite has changed in some way, requiring an re-render of its tile texture. + * + * Such changes include the texture frame and scroll position of the Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#dirty + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.dirty = false; + + /** + * The renderer in use by this Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.0.0 + */ + this.renderer = renderer; + + /** + * The Canvas element that the TileSprite renders its fill pattern in to. + * Only used in Canvas mode. + * + * @name Phaser.GameObjects.TileSprite#canvas + * @type {?HTMLCanvasElement} + * @since 3.12.0 + */ + this.canvas = CanvasPool.create(this, width, height); + + /** + * The Context of the Canvas element that the TileSprite renders its fill pattern in to. + * Only used in Canvas mode. + * + * @name Phaser.GameObjects.TileSprite#context + * @type {CanvasRenderingContext2D} + * @since 3.12.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * The Texture the TileSprite is using as its fill pattern. + * + * @name Phaser.GameObjects.TileSprite#displayTexture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @private + * @since 3.12.0 + */ + this.displayTexture = displayTexture; + + /** + * The Frame the TileSprite is using as its fill pattern. + * + * @name Phaser.GameObjects.TileSprite#displayFrame + * @type {Phaser.Textures.Frame} + * @private + * @since 3.12.0 + */ + this.displayFrame = displayFrame; + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.TileSprite#_crop + * @type {object} + * @private + * @since 3.12.0 + */ + this._crop = this.resetCropObject(); + + /** + * The Texture this Game Object is using to render with. + * + * @name Phaser.GameObjects.TileSprite#texture + * @type {Phaser.Textures.Texture|Phaser.Textures.CanvasTexture} + * @since 3.0.0 + */ + this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); + + /** + * The Texture Frame this Game Object is using to render with. + * + * @name Phaser.GameObjects.TileSprite#frame + * @type {Phaser.Textures.Frame} + * @since 3.0.0 + */ + this.frame = this.texture.get(); + + /** + * The next power of two value from the width of the Fill Pattern frame. + * + * @name Phaser.GameObjects.TileSprite#potWidth + * @type {integer} + * @since 3.0.0 + */ + this.potWidth = GetPowerOfTwo(displayFrame.width); + + /** + * The next power of two value from the height of the Fill Pattern frame. + * + * @name Phaser.GameObjects.TileSprite#potHeight + * @type {integer} + * @since 3.0.0 + */ + this.potHeight = GetPowerOfTwo(displayFrame.height); + + /** + * The Canvas that the TileSprites texture is rendered to. + * This is used to create a WebGL texture from. + * + * @name Phaser.GameObjects.TileSprite#fillCanvas + * @type {HTMLCanvasElement} + * @since 3.12.0 + */ + this.fillCanvas = CanvasPool.create2D(this, this.potWidth, this.potHeight); + + /** + * The Canvas Context used to render the TileSprites texture. + * + * @name Phaser.GameObjects.TileSprite#fillContext + * @type {CanvasRenderingContext2D} + * @since 3.12.0 + */ + this.fillContext = this.fillCanvas.getContext('2d'); + + /** + * The texture that the Tile Sprite is rendered to, which is then rendered to a Scene. + * In WebGL this is a WebGLTexture. In Canvas it's a Canvas Fill Pattern. + * + * @name Phaser.GameObjects.TileSprite#fillPattern + * @type {?(WebGLTexture|CanvasPattern)} + * @since 3.12.0 + */ + this.fillPattern = null; + + this.setPosition(x, y); + this.setSize(width, height); + this.setFrame(frameKey); + this.setOriginFromFrame(); + this.initPipeline(); + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function (renderer) + { + var gl = renderer.gl; + + this.dirty = true; + this.fillPattern = null; + this.fillPattern = renderer.createTexture2D(0, gl.LINEAR, gl.LINEAR, gl.REPEAT, gl.REPEAT, gl.RGBA, this.fillCanvas, this.potWidth, this.potHeight); + + }, this); + }, + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * @method Phaser.GameObjects.TileSprite#setTexture + * @since 3.0.0 + * + * @param {string} key - The key of the texture to be used, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setTexture: function (key, frame) + { + this.displayTexture = this.scene.sys.textures.get(key); + + return this.setFrame(frame); + }, + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * @method Phaser.GameObjects.TileSprite#setFrame + * @since 3.0.0 + * + * @param {(string|integer)} frame - The name or index of the frame within the Texture. + * + * @return {this} This Game Object instance. + */ + setFrame: function (frame) + { + var newFrame = this.displayTexture.get(frame); + + this.potWidth = GetPowerOfTwo(newFrame.width); + this.potHeight = GetPowerOfTwo(newFrame.height); + + // So updateCanvas is triggered + this.canvas.width = 0; + + if (!newFrame.cutWidth || !newFrame.cutHeight) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + this.displayFrame = newFrame; + + this.dirty = true; + + this.updateTileTexture(); + + return this; + }, + + /** + * Sets {@link Phaser.GameObjects.TileSprite#tilePositionX} and {@link Phaser.GameObjects.TileSprite#tilePositionY}. + * + * @method Phaser.GameObjects.TileSprite#setTilePosition + * @since 3.3.0 + * + * @param {number} [x] - The x position of this sprite's tiling texture. + * @param {number} [y] - The y position of this sprite's tiling texture. + * + * @return {this} This Tile Sprite instance. + */ + setTilePosition: function (x, y) + { + if (x !== undefined) + { + this.tilePositionX = x; + } + + if (y !== undefined) + { + this.tilePositionY = y; + } + + return this; + }, + + /** + * Sets {@link Phaser.GameObjects.TileSprite#tileScaleX} and {@link Phaser.GameObjects.TileSprite#tileScaleY}. + * + * @method Phaser.GameObjects.TileSprite#setTileScale + * @since 3.12.0 + * + * @param {number} [x] - The horizontal scale of the tiling texture. If not given it will use the current `tileScaleX` value. + * @param {number} [y=x] - The vertical scale of the tiling texture. If not given it will use the `x` value. + * + * @return {this} This Tile Sprite instance. + */ + setTileScale: function (x, y) + { + if (x === undefined) { x = this.tileScaleX; } + if (y === undefined) { y = x; } + + this.tileScaleX = x; + this.tileScaleY = y; + + return this; + }, + + /** + * Render the tile texture if it is dirty, or if the frame has changed. + * + * @method Phaser.GameObjects.TileSprite#updateTileTexture + * @private + * @since 3.0.0 + */ + updateTileTexture: function () + { + if (!this.dirty || !this.renderer) + { + return; + } + + // Draw the displayTexture to our fillCanvas + + var frame = this.displayFrame; + + if (frame.source.isRenderTexture || frame.source.isGLTexture) + { + console.warn('TileSprites can only use Image or Canvas based textures'); + + this.dirty = false; + + return; + } + + var ctx = this.fillContext; + var canvas = this.fillCanvas; + + var fw = this.potWidth; + var fh = this.potHeight; + + if (!this.renderer.gl) + { + fw = frame.cutWidth; + fh = frame.cutHeight; + } + + ctx.clearRect(0, 0, fw, fh); + + canvas.width = fw; + canvas.height = fh; + + ctx.drawImage( + frame.source.image, + frame.cutX, frame.cutY, + frame.cutWidth, frame.cutHeight, + 0, 0, + fw, fh + ); + + if (this.renderer.gl) + { + this.fillPattern = this.renderer.canvasToTexture(canvas, this.fillPattern); + } + else + { + this.fillPattern = ctx.createPattern(canvas, 'repeat'); + } + + this.updateCanvas(); + + this.dirty = false; + }, + + /** + * Draw the fill pattern to the internal canvas. + * + * @method Phaser.GameObjects.TileSprite#updateCanvas + * @private + * @since 3.12.0 + */ + updateCanvas: function () + { + var canvas = this.canvas; + + if (canvas.width !== this.width || canvas.height !== this.height) + { + canvas.width = this.width; + canvas.height = this.height; + + this.frame.setSize(this.width, this.height); + this.updateDisplayOrigin(); + + this.dirty = true; + } + + if (!this.dirty || this.renderer && this.renderer.gl) + { + this.dirty = false; + return; + } + + var ctx = this.context; + + if (!this.scene.sys.game.config.antialias) + { + Smoothing.disable(ctx); + } + + var scaleX = this._tileScale.x; + var scaleY = this._tileScale.y; + + var positionX = this._tilePosition.x; + var positionY = this._tilePosition.y; + + ctx.clearRect(0, 0, this.width, this.height); + + ctx.save(); + + ctx.scale(scaleX, scaleY); + + ctx.translate(-positionX, -positionY); + + ctx.fillStyle = this.fillPattern; + + ctx.fillRect(positionX, positionY, this.width / scaleX, this.height / scaleY); + + ctx.restore(); + + this.dirty = false; + }, + + /** + * Internal destroy handler, called as part of the destroy process. + * + * @method Phaser.GameObjects.TileSprite#preDestroy + * @protected + * @since 3.9.0 + */ + preDestroy: function () + { + if (this.renderer && this.renderer.gl) + { + this.renderer.deleteTexture(this.fillPattern); + } + + CanvasPool.remove(this.canvas); + CanvasPool.remove(this.fillCanvas); + + this.fillPattern = null; + this.fillContext = null; + this.fillCanvas = null; + + this.displayTexture = null; + this.displayFrame = null; + + this.texture.destroy(); + + this.renderer = null; + }, + + /** + * The horizontal scroll position of the Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#tilePositionX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + tilePositionX: { + + get: function () + { + return this._tilePosition.x; + }, + + set: function (value) + { + this._tilePosition.x = value; + this.dirty = true; + } + + }, + + /** + * The vertical scroll position of the Tile Sprite. + * + * @name Phaser.GameObjects.TileSprite#tilePositionY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + tilePositionY: { + + get: function () + { + return this._tilePosition.y; + }, + + set: function (value) + { + this._tilePosition.y = value; + this.dirty = true; + } + + }, + + /** + * The horizontal scale of the Tile Sprite texture. + * + * @name Phaser.GameObjects.TileSprite#tileScaleX + * @type {number} + * @default 1 + * @since 3.11.0 + */ + tileScaleX: { + + get: function () + { + return this._tileScale.x; + }, + + set: function (value) + { + this._tileScale.x = value; + this.dirty = true; + } + + }, + + /** + * The vertical scale of the Tile Sprite texture. + * + * @name Phaser.GameObjects.TileSprite#tileScaleY + * @type {number} + * @default 1 + * @since 3.11.0 + */ + tileScaleY: { + + get: function () + { + return this._tileScale.y; + }, + + set: function (value) + { + this._tileScale.y = value; + this.dirty = true; + } + + } + +}); + +module.exports = TileSprite; diff --git a/src/gameobjects/tilesprite/TileSpriteCanvasRenderer.js b/src/gameobjects/tilesprite/TileSpriteCanvasRenderer.js index cf5012867..a531ded86 100644 --- a/src/gameobjects/tilesprite/TileSpriteCanvasRenderer.js +++ b/src/gameobjects/tilesprite/TileSpriteCanvasRenderer.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.TileSprite#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.TileSprite} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var TileSpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - src.updateCanvas(); - - renderer.batchSprite(src, src.frame, camera, parentMatrix); -}; - -module.exports = TileSpriteCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.TileSprite#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.TileSprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TileSpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.updateCanvas(); + + renderer.batchSprite(src, src.frame, camera, parentMatrix); +}; + +module.exports = TileSpriteCanvasRenderer; diff --git a/src/gameobjects/tilesprite/TileSpriteCreator.js b/src/gameobjects/tilesprite/TileSpriteCreator.js index 2407f1b9a..d2bded771 100644 --- a/src/gameobjects/tilesprite/TileSpriteCreator.js +++ b/src/gameobjects/tilesprite/TileSpriteCreator.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var TileSprite = require('./TileSprite'); - -/** - * Creates a new TileSprite Game Object and returns it. - * - * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#tileSprite - * @since 3.0.0 - * - * @param {Phaser.Types.GameObjects.TileSprite.TileSpriteConfig} 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.TileSprite} The Game Object that was created. - */ -GameObjectCreator.register('tileSprite', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var x = GetAdvancedValue(config, 'x', 0); - var y = GetAdvancedValue(config, 'y', 0); - var width = GetAdvancedValue(config, 'width', 512); - var height = GetAdvancedValue(config, 'height', 512); - var key = GetAdvancedValue(config, 'key', ''); - var frame = GetAdvancedValue(config, 'frame', ''); - - var tile = new TileSprite(this.scene, x, y, width, height, key, frame); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, tile, config); - - return tile; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var TileSprite = require('./TileSprite'); + +/** + * Creates a new TileSprite Game Object and returns it. + * + * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#tileSprite + * @since 3.0.0 + * + * @param {Phaser.Types.GameObjects.TileSprite.TileSpriteConfig} 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.TileSprite} The Game Object that was created. + */ +GameObjectCreator.register('tileSprite', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 512); + var height = GetAdvancedValue(config, 'height', 512); + var key = GetAdvancedValue(config, 'key', ''); + var frame = GetAdvancedValue(config, 'frame', ''); + + var tile = new TileSprite(this.scene, x, y, width, height, key, frame); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, tile, config); + + return tile; +}); diff --git a/src/gameobjects/tilesprite/TileSpriteFactory.js b/src/gameobjects/tilesprite/TileSpriteFactory.js index 679897ac8..a4e01a665 100644 --- a/src/gameobjects/tilesprite/TileSpriteFactory.js +++ b/src/gameobjects/tilesprite/TileSpriteFactory.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var TileSprite = require('./TileSprite'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new TileSprite Game Object and adds it to the Scene. - * - * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#tileSprite - * @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 {integer} width - The width of the Game Object. If zero it will use the size of the texture frame. - * @param {integer} height - The height of the Game Object. If zero it will use the size of the texture frame. - * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.TileSprite} The Game Object that was created. - */ -GameObjectFactory.register('tileSprite', function (x, y, width, height, key, frame) -{ - return this.displayList.add(new TileSprite(this.scene, x, y, width, height, key, frame)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TileSprite = require('./TileSprite'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new TileSprite Game Object and adds it to the Scene. + * + * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#tileSprite + * @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 {integer} width - The width of the Game Object. If zero it will use the size of the texture frame. + * @param {integer} height - The height of the Game Object. If zero it will use the size of the texture frame. + * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.TileSprite} The Game Object that was created. + */ +GameObjectFactory.register('tileSprite', function (x, y, width, height, key, frame) +{ + return this.displayList.add(new TileSprite(this.scene, x, y, width, height, key, frame)); +}); + +// 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 diff --git a/src/gameobjects/tilesprite/TileSpriteRender.js b/src/gameobjects/tilesprite/TileSpriteRender.js index 7960eaf21..37e0aeaeb 100644 --- a/src/gameobjects/tilesprite/TileSpriteRender.js +++ b/src/gameobjects/tilesprite/TileSpriteRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./TileSpriteWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./TileSpriteCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./TileSpriteWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./TileSpriteCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/tilesprite/TileSpriteWebGLRenderer.js b/src/gameobjects/tilesprite/TileSpriteWebGLRenderer.js index 5d9545633..748c9c048 100644 --- a/src/gameobjects/tilesprite/TileSpriteWebGLRenderer.js +++ b/src/gameobjects/tilesprite/TileSpriteWebGLRenderer.js @@ -1,54 +1,54 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Utils = require('../../renderer/webgl/Utils'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.TileSprite#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.TileSprite} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var TileSpriteWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - src.updateCanvas(); - - var getTint = Utils.getTintAppendFloatAlpha; - - this.pipeline.batchTexture( - src, - src.fillPattern, - src.displayFrame.width * src.tileScaleX, src.displayFrame.height * src.tileScaleY, - src.x, src.y, - src.width, src.height, - src.scaleX, src.scaleY, - src.rotation, - src.flipX, src.flipY, - src.scrollFactorX, src.scrollFactorY, - src.originX * src.width, src.originY * src.height, - 0, 0, src.width, src.height, - getTint(src._tintTL, camera.alpha * src._alphaTL), - getTint(src._tintTR, camera.alpha * src._alphaTR), - getTint(src._tintBL, camera.alpha * src._alphaBL), - getTint(src._tintBR, camera.alpha * src._alphaBR), - (src._isTinted && src.tintFill), - (src.tilePositionX % src.displayFrame.width) / src.displayFrame.width, - (src.tilePositionY % src.displayFrame.height) / src.displayFrame.height, - camera, - parentMatrix - ); -}; - -module.exports = TileSpriteWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Utils = require('../../renderer/webgl/Utils'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.TileSprite#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.TileSprite} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var TileSpriteWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.updateCanvas(); + + var getTint = Utils.getTintAppendFloatAlpha; + + this.pipeline.batchTexture( + src, + src.fillPattern, + src.displayFrame.width * src.tileScaleX, src.displayFrame.height * src.tileScaleY, + src.x, src.y, + src.width, src.height, + src.scaleX, src.scaleY, + src.rotation, + src.flipX, src.flipY, + src.scrollFactorX, src.scrollFactorY, + src.originX * src.width, src.originY * src.height, + 0, 0, src.width, src.height, + getTint(src._tintTL, camera.alpha * src._alphaTL), + getTint(src._tintTR, camera.alpha * src._alphaTR), + getTint(src._tintBL, camera.alpha * src._alphaBL), + getTint(src._tintBR, camera.alpha * src._alphaBR), + (src._isTinted && src.tintFill), + (src.tilePositionX % src.displayFrame.width) / src.displayFrame.width, + (src.tilePositionY % src.displayFrame.height) / src.displayFrame.height, + camera, + parentMatrix + ); +}; + +module.exports = TileSpriteWebGLRenderer; diff --git a/src/gameobjects/tilesprite/typedefs/index.js b/src/gameobjects/tilesprite/typedefs/index.js index 906ba37cb..d5aedbbfa 100644 --- a/src/gameobjects/tilesprite/typedefs/index.js +++ b/src/gameobjects/tilesprite/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects.TileSprite - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects.TileSprite + */ diff --git a/src/gameobjects/typedefs/index.js b/src/gameobjects/typedefs/index.js index 081574801..7ccb1c61b 100644 --- a/src/gameobjects/typedefs/index.js +++ b/src/gameobjects/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.GameObjects - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.GameObjects + */ diff --git a/src/gameobjects/video/Video.js b/src/gameobjects/video/Video.js index 82ae064cb..776bb6793 100644 --- a/src/gameobjects/video/Video.js +++ b/src/gameobjects/video/Video.js @@ -1,1763 +1,1763 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Clamp = require('../../math/Clamp'); -var Components = require('../components'); -var Events = require('../events'); -var GameEvents = require('../../core/events/'); -var GameObject = require('../GameObject'); -var SoundEvents = require('../../sound/events/'); -var UUID = require('../../utils/string/UUID'); -var VideoRender = require('./VideoRender'); -var MATH_CONST = require('../../math/const'); - -/** - * @classdesc - * A Video Game Object. - * - * This Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, - * or playing a video based on a given URL. Videos can be either local, or streamed. - * - * ```javascript - * preload () { - * this.load.video('pixar', 'nemo.mp4'); - * } - * - * create () { - * this.add.video(400, 300, 'pixar'); - * } - * ``` - * - * 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. - * - * ### 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, ahd 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', 'loadeddata', false, true); - * } - * ``` - * - * The 5th 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. - * - * Note that due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. - * - * 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.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.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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. - */ -var Video = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Mask, - Components.Origin, - Components.Pipeline, - Components.ScrollFactor, - Components.Size, - Components.TextureCrop, - Components.Tint, - Components.Transform, - Components.Visible, - VideoRender - ], - - initialize: - - function Video (scene, x, y, key) - { - GameObject.call(this, scene, 'Video'); - - /** - * A reference to the HTML Video Element this Video Game Object is playing. - * Will be `null` until a video is loaded for playback. - * - * @name Phaser.GameObjects.Video#video - * @type {?HTMLVideoElement} - * @since 3.20.0 - */ - this.video = null; - - /** - * The Phaser Texture this Game Object is using to render the video to. - * Will be `null` until a video is loaded for playback. - * - * @name Phaser.GameObjects.Video#videoTexture - * @type {?Phaser.Textures.Texture} - * @since 3.20.0 - */ - this.videoTexture = null; - - /** - * A reference to the TextureSource belong to the `videoTexture` Texture object. - * Will be `null` until a video is loaded for playback. - * - * @name Phaser.GameObjects.Video#videoTextureSource - * @type {?Phaser.Textures.TextureSource} - * @since 3.20.0 - */ - this.videoTextureSource = null; - - /** - * A Phaser CanvasTexture instance that holds the most recent snapshot taken from the video. - * This will only be set if `snapshot` or `snapshotArea` have been called, and will be `null` until that point. - * - * @name Phaser.GameObjects.Video#snapshotTexture - * @type {?Phaser.Textures.CanvasTexture} - * @since 3.20.0 - */ - this.snapshotTexture = null; - - /** - * If you have saved this video to a texture via the `saveTexture` method, this controls if the video - * is rendered with `flipY` in WebGL or not. You often need to set this if you wish to use the video texture - * as the input source for a shader. If you find your video is appearing upside down within a shader or - * custom pipeline, flip this property. - * - * @name Phaser.GameObjects.Video#flipY - * @type {boolean} - * @since 3.20.0 - */ - this.flipY = false; - - /** - * The key used by the texture as stored in the Texture Manager. - * - * @name Phaser.GameObjects.Video#_key - * @type {string} - * @private - * @since 3.20.0 - */ - this._key = UUID(); - - /** - * An internal flag holding the current state of the video lock, should document interaction be required - * before playback can begin. - * - * @name Phaser.GameObjects.Video#touchLocked - * @type {boolean} - * @since 3.20.0 - */ - this.touchLocked = true; - - /** - * Should the video auto play when document interaction is required and happens? - * - * @name Phaser.GameObjects.Video#playWhenUnlocked - * @type {boolean} - * @since 3.20.0 - */ - this.playWhenUnlocked = false; - - /** - * When starting playback of a video Phaser will monitor its `readyState` using a `setTimeout` call. - * The `setTimeout` happens once every `Video.retryInterval` ms. It will carry on monitoring the video - * state in this manner until the `retryLimit` is reached and then abort. - * - * @name Phaser.GameObjects.Video#retryLimit - * @type {integer} - * @since 3.20.0 - */ - this.retryLimit = 20; - - /** - * The current retry attempt. - * - * @name Phaser.GameObjects.Video#retry - * @type {integer} - * @since 3.20.0 - */ - this.retry = 0; - - /** - * The number of ms between each retry while monitoring the ready state of a downloading video. - * - * @name Phaser.GameObjects.Video#retryInterval - * @type {integer} - * @since 3.20.0 - */ - this.retryInterval = 500; - - /** - * The setTimeout callback ID. - * - * @name Phaser.GameObjects.Video#_retryID - * @type {integer} - * @private - * @since 3.20.0 - */ - this._retryID = null; - - /** - * The video was muted due to a system event, such as the game losing focus. - * - * @name Phaser.GameObjects.Video#_systemMuted - * @type {boolean} - * @private - * @since 3.20.0 - */ - this._systemMuted = false; - - /** - * The video was muted due to game code, not a system event. - * - * @name Phaser.GameObjects.Video#_codeMuted - * @type {boolean} - * @private - * @since 3.20.0 - */ - this._codeMuted = false; - - /** - * The video was paused due to a system event, such as the game losing focus. - * - * @name Phaser.GameObjects.Video#_systemPaused - * @type {boolean} - * @private - * @since 3.20.0 - */ - this._systemPaused = false; - - /** - * The video was paused due to game code, not a system event. - * - * @name Phaser.GameObjects.Video#_codePaused - * @type {boolean} - * @private - * @since 3.20.0 - */ - this._codePaused = false; - - /** - * The locally bound event callback handlers. - * - * @name Phaser.GameObjects.Video#_callbacks - * @type {any} - * @private - * @since 3.20.0 - */ - this._callbacks = { - play: this.playHandler.bind(this), - error: this.loadErrorHandler.bind(this), - end: this.completeHandler.bind(this), - time: this.timeUpdateHandler.bind(this), - seeking: this.seekingHandler.bind(this), - seeked: this.seekedHandler.bind(this) - }; - - /** - * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. - * - * @name Phaser.GameObjects.Video#_crop - * @type {object} - * @private - * @since 3.20.0 - */ - this._crop = this.resetCropObject(); - - /** - * An object containing in and out markers for sequence playback. - * - * @name Phaser.GameObjects.Video#markers - * @type {any} - * @since 3.20.0 - */ - this.markers = {}; - - /** - * The in marker. - * - * @name Phaser.GameObjects.Video#_markerIn - * @type {integer} - * @private - * @since 3.20.0 - */ - this._markerIn = -1; - - /** - * The out marker. - * - * @name Phaser.GameObjects.Video#_markerOut - * @type {integer} - * @private - * @since 3.20.0 - */ - this._markerOut = MATH_CONST.MAX_SAFE_INTEGER; - - /** - * The last time the TextureSource was updated. - * - * @name Phaser.GameObjects.Video#_lastUpdate - * @type {integer} - * @private - * @since 3.20.0 - */ - this._lastUpdate = 0; - - /** - * The key of the video being played from the Video cache, if any. - * - * @name Phaser.GameObjects.Video#_cacheKey - * @type {string} - * @private - * @since 3.20.0 - */ - this._cacheKey = ''; - - /** - * Is the video currently seeking? - * - * @name Phaser.GameObjects.Video#_isSeeking - * @type {boolean} - * @private - * @since 3.20.0 - */ - this._isSeeking = false; - - /** - * Should the Video element that this Video is using, be removed from the DOM - * when this Video is destroyed? - * - * @name Phaser.GameObjects.Video#removeVideoElementOnDestroy - * @type {boolean} - * @since 3.21.0 - */ - this.removeVideoElementOnDestroy = false; - - this.setPosition(x, y); - this.initPipeline(); - - if (key) - { - this.changeSource(key, false); - } - - var game = scene.sys.game.events; - - game.on(GameEvents.PAUSE, this.globalPause, this); - game.on(GameEvents.RESUME, this.globalResume, this); - - var sound = scene.sys.sound; - - if (sound) - { - sound.on(SoundEvents.GLOBAL_MUTE, this.globalMute, this); - } - }, - - /** - * 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', 'loadeddata', false, true); - * } - * ``` - * - * The 5th 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 {integer} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video. - * @param {integer} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video. - * - * @return {this} This Video Game Object for method chaining. - */ - play: function (loop, markerIn, markerOut) - { - if ((this.touchLocked && this.playWhenUnlocked) || this.isPlaying()) - { - return this; - } - - var video = this.video; - - if (!video) - { - console.warn('Video not loaded'); - - return this; - } - - if (loop === undefined) { loop = video.loop; } - - var sound = this.scene.sys.sound; - - if (sound && sound.mute) - { - // Mute will be set based on the global mute state of the Sound Manager (if there is one) - this.setMute(true); - } - - if (!isNaN(markerIn)) - { - this._markerIn = markerIn; - } - - if (!isNaN(markerOut) && markerOut > markerIn) - { - this._markerOut = markerOut; - } - - video.loop = loop; - - var callbacks = this._callbacks; - - var playPromise = video.play(); - - if (playPromise !== undefined) - { - playPromise.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)); - } - else - { - // Old-school browsers with no Promises - video.addEventListener('playing', callbacks.play, true); - - // If video hasn't downloaded properly yet ... - if (video.readyState < 2) - { - this.retry = this.retryLimit; - - this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); - } - } - - // Set these _after_ calling `play` or they don't fire (useful, thanks browsers) - video.addEventListener('ended', callbacks.end, true); - video.addEventListener('timeupdate', callbacks.time, true); - video.addEventListener('seeking', callbacks.seeking, true); - video.addEventListener('seeked', callbacks.seeked, true); - - return this; - }, - - /** - * This method allows you to change the source of the current video element. It works by first stopping the - * current video, if playing. Then deleting the video texture, if one has been created. Finally, it makes a - * new video texture and starts playback of the new source through the existing video element. - * - * The reason you may wish to do this is because videos that require interaction to unlock, remain in an unlocked - * state, even if you change the source of the video. By changing the source to a new video you avoid having to - * go through the unlock process again. - * - * @method Phaser.GameObjects.Video#changeSource - * @since 3.20.0 - * - * @param {string} key - The key of the Video this Game Object will swap to playing, as stored in the Video Cache. - * @param {boolean} [autoplay=true] - Should the video start playing immediately, once the swap is complete? - * @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 {integer} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video. - * @param {integer} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video. - * - * @return {this} This Video Game Object for method chaining. - */ - changeSource: function (key, autoplay, loop, markerIn, markerOut) - { - if (autoplay === undefined) { autoplay = true; } - - var currentVideo = this.video; - - if (currentVideo) - { - this.stop(); - } - - var newVideo = this.scene.sys.cache.video.get(key); - - if (newVideo) - { - this.video = newVideo; - - this._cacheKey = key; - - this._codePaused = newVideo.paused; - this._codeMuted = newVideo.muted; - - if (this.videoTexture) - { - this.scene.sys.textures.remove(this._key); - - this.videoTexture = this.scene.sys.textures.create(this._key, newVideo, newVideo.videoWidth, newVideo.videoHeight); - this.videoTextureSource = this.videoTexture.source[0]; - this.videoTexture.add('__BASE', 0, 0, 0, newVideo.videoWidth, newVideo.videoHeight); - - this.setTexture(this.videoTexture); - this.setSizeToFrame(); - this.updateDisplayOrigin(); - - this.emit(Events.VIDEO_CREATED, this, newVideo.videoWidth, newVideo.videoHeight); - } - else - { - this.updateTexture(); - } - - newVideo.currentTime = 0; - - this._lastUpdate = 0; - - if (autoplay) - { - this.play(loop, markerIn, markerOut); - } - } - else - { - this.video = null; - } - - return this; - }, - - /** - * 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 {integer} markerIn - The time, in seconds, representing the start of this marker. - * @param {integer} markerOut - The time, in seconds, representing the end of this marker. - * - * @return {this} This Video Game Object for method chaining. - */ - addMarker: function (key, markerIn, markerOut) - { - if (!isNaN(markerIn) && markerIn >= 0 && !isNaN(markerOut)) - { - this.markers[key] = [ markerIn, markerOut ]; - } - - return this; - }, - - /** - * 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. - */ - playMarker: function (key, loop) - { - var marker = this.markers[key]; - - if (marker) - { - this.play(loop, marker[0], marker[1]); - } - - return this; - }, - - /** - * Removes a previously set marker from this video. - * - * If the marker is currently playing it will _not_ stop playback. - * - * @method Phaser.GameObjects.Video#removeMarker - * @since 3.20.0 - * - * @param {string} key - The name of the marker to remove. - * - * @return {this} This Video Game Object for method chaining. - */ - removeMarker: function (key) - { - delete this.markers[key]; - - return this; - }, - - /** - * Takes a snapshot of the current frame of the video and renders it to a CanvasTexture object, - * which is then returned. You can optionally resize the grab by passing a width and height. - * - * This method returns a reference to the `Video.snapshotTexture` object. Calling this method - * multiple times will overwrite the previous snapshot with the most recent one. - * - * @method Phaser.GameObjects.Video#snapshot - * @since 3.20.0 - * - * @param {integer} [width] - The width of the resulting CanvasTexture. - * @param {integer} [height] - The height of the resulting CanvasTexture. - * - * @return {Phaser.Textures.CanvasTexture} - */ - snapshot: function (width, height) - { - if (width === undefined) { width = this.width; } - if (height === undefined) { height = this.height; } - - return this.snapshotArea(0, 0, this.width, this.height, width, height); - }, - - /** - * Takes a snapshot of the specified area of the current frame of the video and renders it to a CanvasTexture object, - * which is then returned. You can optionally resize the grab by passing a different `destWidth` and `destHeight`. - * - * This method returns a reference to the `Video.snapshotTexture` object. Calling this method - * multiple times will overwrite the previous snapshot with the most recent one. - * - * @method Phaser.GameObjects.Video#snapshotArea - * @since 3.20.0 - * - * @param {integer} [x=0] - The horizontal location of the top-left of the area to grab from. - * @param {integer} [y=0] - The vertical location of the top-left of the area to grab from. - * @param {integer} [srcWidth] - The width of area to grab from the video. If not given it will grab the full video dimensions. - * @param {integer} [srcHeight] - The height of area to grab from the video. If not given it will grab the full video dimensions. - * @param {integer} [destWidth] - The destination width of the grab, allowing you to resize it. - * @param {integer} [destHeight] - The destination height of the grab, allowing you to resize it. - * - * @return {Phaser.Textures.CanvasTexture} - */ - snapshotArea: function (x, y, srcWidth, srcHeight, destWidth, destHeight) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (srcWidth === undefined) { srcWidth = this.width; } - if (srcHeight === undefined) { srcHeight = this.height; } - if (destWidth === undefined) { destWidth = srcWidth; } - if (destHeight === undefined) { destHeight = srcHeight; } - - var video = this.video; - var snap = this.snapshotTexture; - - if (!snap) - { - snap = this.scene.sys.textures.createCanvas(UUID(), destWidth, destHeight); - - this.snapshotTexture = snap; - - if (video) - { - snap.context.drawImage(video, x, y, srcWidth, srcHeight, 0, 0, destWidth, destHeight); - } - } - else - { - snap.setSize(destWidth, destHeight); - - if (video) - { - snap.context.drawImage(video, x, y, srcWidth, srcHeight, 0, 0, destWidth, destHeight); - } - } - - return snap.update(); - }, - - /** - * Stores a copy of this Videos `snapshotTexture` in the Texture Manager using the given key. - * - * This texture is created when the `snapshot` or `snapshotArea` methods are called. - * - * After doing this, any texture based Game Object, such as a Sprite, can use the contents of the - * snapshot by using the texture key: - * - * ```javascript - * var vid = this.add.video(0, 0, 'intro'); - * - * vid.snapshot(); - * - * vid.saveSnapshotTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * Updating the contents of the `snapshotTexture`, for example by calling `snapshot` again, - * will automatically update _any_ Game Object that is using it as a texture. - * Calling `saveSnapshotTexture` again will not save another copy of the same texture, - * it will just rename the existing one. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame. - * - * @method Phaser.GameObjects.Video#saveSnapshotTexture - * @since 3.20.0 - * - * @param {string} key - The unique key to store the texture as within the global Texture Manager. - * - * @return {Phaser.Textures.CanvasTexture} The Texture that was saved. - */ - saveSnapshotTexture: function (key) - { - if (this.snapshotTexture) - { - this.scene.sys.textures.renameTexture(this.snapshotTexture.key, key); - } - else - { - this.snapshotTexture = this.scene.sys.textures.createCanvas(key, this.width, this.height); - } - - return this.snapshotTexture; - }, - - /** - * Loads a Video from the given URL, ready for playback with the `Video.play` method. - * - * You can control at what point the browser determines the video as being ready for playback via - * the `loadEvent` parameter. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement - * for more details. - * - * @method Phaser.GameObjects.Video#loadURL - * @since 3.20.0 - * - * @param {string} url - The URL of the video to load or be streamed. - * @param {string} [loadEvent='loadeddata'] - The load event to listen for. Either `loadeddata`, `canplay` or `canplaythrough`. - * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. - * - * @return {this} This Video Game Object for method chaining. - */ - loadURL: function (url, loadEvent, noAudio) - { - if (loadEvent === undefined) { loadEvent = 'loadeddata'; } - if (noAudio === undefined) { noAudio = false; } - - if (this.video) - { - this.stop(); - } - - if (this.videoTexture) - { - this.scene.sys.textures.remove(this._key); - } - - var video = document.createElement('video'); - - video.controls = false; - - if (noAudio) - { - video.muted = true; - video.defaultMuted = true; - - video.setAttribute('autoplay', 'autoplay'); - } - - video.setAttribute('playsinline', 'playsinline'); - video.setAttribute('preload', 'auto'); - - video.addEventListener('error', this._callbacks.error, true); - - video.src = url; - - video.load(); - - this.video = video; - - return this; - }, - - /** - * This internal method is called automatically if the playback Promise resolves successfully. - * - * @method Phaser.GameObjects.Video#playPromiseSuccessHandler - * @fires Phaser.GameObjects.Events#VIDEO_PLAY - * @private - * @since 3.20.0 - */ - playPromiseSuccessHandler: function () - { - this.touchLocked = false; - - this.emit(Events.VIDEO_PLAY, this); - - if (this._markerIn > -1) - { - this.video.currentTime = this._markerIn; - } - }, - - /** - * This internal method is called automatically if the playback Promise fails to resolve. - * - * @method Phaser.GameObjects.Video#playPromiseErrorHandler - * @fires Phaser.GameObjects.Events#VIDEO_ERROR - * @private - * @since 3.20.0 - * - * @param {any} error - The Promise resolution error. - */ - playPromiseErrorHandler: function (error) - { - this.scene.sys.input.once('pointerdown', this.unlockHandler, this); - - this.touchLocked = true; - this.playWhenUnlocked = true; - - this.emit(Events.VIDEO_ERROR, this, error); - }, - - /** - * Called when the video emits a `playing` event during load. - * - * This is only listened for if the browser doesn't support Promises. - * - * @method Phaser.GameObjects.Video#playHandler - * @fires Phaser.GameObjects.Events#VIDEO_PLAY - * @since 3.20.0 - */ - playHandler: function () - { - this.touchLocked = false; - - this.emit(Events.VIDEO_PLAY, this); - - this.video.removeEventListener('playing', this._callbacks.play, true); - }, - - /** - * This internal method is called automatically if the video fails to load. - * - * @method Phaser.GameObjects.Video#loadErrorHandler - * @fires Phaser.GameObjects.Events#VIDEO_ERROR - * @private - * @since 3.20.0 - * - * @param {Event} event - The error Event. - */ - loadErrorHandler: function (event) - { - this.stop(); - - this.emit(Events.VIDEO_ERROR, this, event); - }, - - /** - * This internal method is called if the video couldn't be played because it was interaction locked - * by the browser, but an input event has since been received. - * - * @method Phaser.GameObjects.Video#unlockHandler - * @fires Phaser.GameObjects.Events#VIDEO_UNLOCKED - * @fires Phaser.GameObjects.Events#VIDEO_PLAY - * @private - * @since 3.20.0 - * - * @param {any} error - The Promise resolution error. - */ - unlockHandler: function () - { - this.touchLocked = false; - this.playWhenUnlocked = false; - - this.emit(Events.VIDEO_UNLOCKED, this); - - if (this._markerIn > -1) - { - this.video.currentTime = this._markerIn; - } - - this.video.play(); - - this.emit(Events.VIDEO_PLAY, this); - }, - - /** - * Called when the video completes playback, i.e. reaches an `ended` state. - * - * This will never happen if the video is coming from a live stream, where the duration is `Infinity`. - * - * @method Phaser.GameObjects.Video#completeHandler - * @fires Phaser.GameObjects.Events#VIDEO_COMPLETE - * @since 3.20.0 - */ - completeHandler: function () - { - this.emit(Events.VIDEO_COMPLETE, this); - }, - - /** - * Called when the video emits a `timeUpdate` event during playback. - * - * This event is too slow and irregular to be used for actual video timing or texture updating, - * but we can use it to determine if a video has looped. - * - * @method Phaser.GameObjects.Video#timeUpdateHandler - * @fires Phaser.GameObjects.Events#VIDEO_LOOP - * @since 3.20.0 - */ - timeUpdateHandler: function () - { - if (this.video && this.video.currentTime < this._lastUpdate) - { - this.emit(Events.VIDEO_LOOP, this); - - this._lastUpdate = 0; - } - }, - - /** - * The internal update step. - * - * @method Phaser.GameObjects.Video#preUpdate - * @private - * @since 3.20.0 - */ - preUpdate: function () - { - var video = this.video; - - if (video) - { - var currentTime = video.currentTime; - - // Don't render a new frame unless the video has actually changed time - if (currentTime !== this._lastUpdate) - { - this._lastUpdate = currentTime; - - this.updateTexture(); - - if (currentTime >= this._markerOut) - { - if (video.loop) - { - video.currentTime = this._markerIn; - - this.updateTexture(); - - this._lastUpdate = currentTime; - - this.emit(Events.VIDEO_LOOP, this); - } - else - { - this.emit(Events.VIDEO_COMPLETE, this); - - this.stop(); - } - } - } - } - }, - - /** - * Internal callback that monitors the download progress of a video after changing its source. - * - * @method Phaser.GameObjects.Video#checkVideoProgress - * @fires Phaser.GameObjects.Events#VIDEO_TIMEOUT - * @private - * @since 3.20.0 - */ - checkVideoProgress: function () - { - if (this.video.readyState >= 2) - { - // We've got enough data to update the texture for playback - this.updateTexture(); - } - else - { - this.retry--; - - if (this.retry > 0) - { - this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); - } - else - { - this.emit(Events.VIDEO_TIMEOUT, this); - } - } - }, - - /** - * Internal method that is called when enough video data has been received in order to create a texture - * from it. The texture is assigned to the `Video.videoTexture` property and given a base frame that - * encompases the whole video size. - * - * @method Phaser.GameObjects.Video#updateTexture - * @since 3.20.0 - */ - updateTexture: function () - { - var video = this.video; - - var width = video.videoWidth; - var height = video.videoHeight; - - if (!this.videoTexture) - { - this.videoTexture = this.scene.sys.textures.create(this._key, video, width, height); - this.videoTextureSource = this.videoTexture.source[0]; - this.videoTexture.add('__BASE', 0, 0, 0, width, height); - - this.setTexture(this.videoTexture); - this.setSizeToFrame(); - this.updateDisplayOrigin(); - - this.emit(Events.VIDEO_CREATED, this, width, height); - } - else - { - var textureSource = this.videoTextureSource; - - if (textureSource.source !== video) - { - textureSource.source = video; - textureSource.width = width; - textureSource.height = height; - } - - textureSource.update(); - } - }, - - /** - * Returns the key of the currently played video, as stored in the Video Cache. - * If the video did not come from the cache this will return an empty string. - * - * @method Phaser.GameObjects.Video#getVideoKey - * @since 3.20.0 - * - * @return {string} The key of the video being played from the Video Cache, if any. - */ - getVideoKey: function () - { - return this._cacheKey; - }, - - /** - * 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. - * - * @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. - */ - seekTo: function (value) - { - var video = this.video; - - if (video) - { - var duration = video.duration; - - if (duration !== Infinity && !isNaN(duration)) - { - var seekTime = duration * value; - - this.setCurrentTime(seekTime); - } - } - - return this; - }, - - /** - * A double-precision floating-point value indicating the current playback time in seconds. - * If the media has not started to play and has not been seeked, this value is the media's initial playback time. - * - * @method Phaser.GameObjects.Video#getCurrentTime - * @since 3.20.0 - * - * @return {number} A double-precision floating-point value indicating the current playback time in seconds. - */ - getCurrentTime: function () - { - return (this.video) ? this.video.currentTime : 0; - }, - - /** - * 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. - */ - setCurrentTime: function (value) - { - var video = this.video; - - if (video) - { - if (typeof value === 'string') - { - var op = value[0]; - var num = parseFloat(value.substr(1)); - - if (op === '+') - { - value = video.currentTime + num; - } - else if (op === '-') - { - value = video.currentTime - num; - } - } - - video.currentTime = value; - - this._lastUpdate = value; - } - - return this; - }, - - /** - * Returns a boolean indicating if this Video is currently seeking, or not. - * - * @method Phaser.GameObjects.Video#isSeeking - * @since 3.20.0 - * - * @return {boolean} A boolean indicating if this Video is currently seeking, or not. - */ - isSeeking: function () - { - return this._isSeeking; - }, - - /** - * Internal seeking handler. - * - * @method Phaser.GameObjects.Video#seekingHandler - * @fires Phaser.GameObjects.Events#VIDEO_SEEKING - * @private - * @since 3.20.0 - */ - seekingHandler: function () - { - this._isSeeking = true; - - this.emit(Events.VIDEO_SEEKING, this); - }, - - /** - * Internal seeked handler. - * - * @method Phaser.GameObjects.Video#seekedHandler - * @fires Phaser.GameObjects.Events#VIDEO_SEEKED - * @private - * @since 3.20.0 - */ - seekedHandler: function () - { - this._isSeeking = false; - - this.emit(Events.VIDEO_SEEKED, this); - - var video = this.video; - - if (video) - { - this.updateTexture(); - } - }, - - /** - * Returns the current progress of the video. Progress is defined as a value between 0 (the start) - * and 1 (the end). - * - * Progress can only be returned if the video has a duration, otherwise it will always return zero. - * - * @method Phaser.GameObjects.Video#getProgress - * @since 3.20.0 - * - * @return {number} The current progress of playback. If the video has no duration, will always return zero. - */ - getProgress: function () - { - var video = this.video; - - if (video) - { - var now = video.currentTime; - var duration = video.duration; - - if (duration !== Infinity && !isNaN(duration)) - { - return now / duration; - } - } - - return 0; - }, - - /** - * A double-precision floating-point value which indicates the duration (total length) of the media in seconds, - * on the media's timeline. If no media is present on the element, or the media is not valid, the returned value is NaN. - * - * If the media has no known end (such as for live streams of unknown duration, web radio, media incoming from WebRTC, - * and so forth), this value is +Infinity. - * - * @method Phaser.GameObjects.Video#getDuration - * @since 3.20.0 - * - * @return {number} A double-precision floating-point value indicating the duration of the media in seconds. - */ - getDuration: function () - { - return (this.video) ? this.video.duration : 0; - }, - - /** - * Sets the muted state of the currently playing video, if one is loaded. - * - * @method Phaser.GameObjects.Video#setMute - * @since 3.20.0 - * - * @param {boolean} [value=true] - The mute value. `true` if the video should be muted, otherwise `false`. - * - * @return {this} This Video Game Object for method chaining. - */ - setMute: function (value) - { - if (value === undefined) { value = true; } - - this._codeMuted = value; - - var video = this.video; - - if (video) - { - video.muted = (this._systemMuted) ? true : value; - } - - return this; - }, - - /** - * Returns a boolean indicating if this Video is currently muted. - * - * @method Phaser.GameObjects.Video#isMuted - * @since 3.20.0 - * - * @return {boolean} A boolean indicating if this Video is currently muted, or not. - */ - isMuted: function () - { - return this._codeMuted; - }, - - /** - * Internal global mute handler. Will mute the video, if playing, if the global sound system mutes. - * - * @method Phaser.GameObjects.Video#globalMute - * @private - * @since 3.20.0 - * - * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the Sound Manager that emitted the event. - * @param {boolean} mute - The mute value. `true` if the Sound Manager is now muted, otherwise `false`. - */ - globalMute: function (soundManager, value) - { - this._systemMuted = value; - - var video = this.video; - - if (video) - { - video.muted = (this._codeMuted) ? true : value; - } - }, - - /** - * Internal global pause handler. Will pause the video if the Game itself pauses. - * - * @method Phaser.GameObjects.Video#globalPause - * @private - * @since 3.20.0 - */ - globalPause: function () - { - this._systemPaused = true; - - if (this.video) - { - this.video.pause(); - } - }, - - /** - * Internal global resume handler. Will resume a paused video if the Game itself resumes. - * - * @method Phaser.GameObjects.Video#globalResume - * @private - * @since 3.20.0 - */ - globalResume: function () - { - this._systemPaused = false; - - if (this.video && !this._codePaused) - { - this.video.play(); - } - }, - - /** - * Sets the paused state of the currently loaded video. - * - * If the video is playing, calling this method with `true` will pause playback. - * If the video is paused, calling this method with `false` will resume playback. - * - * If no video is loaded, this method does nothing. - * - * @method Phaser.GameObjects.Video#setPaused - * @since 3.20.0 - * - * @param {boolean} [value=true] - The paused value. `true` if the video should be paused, `false` to resume it. - * - * @return {this} This Video Game Object for method chaining. - */ - setPaused: function (value) - { - if (value === undefined) { value = true; } - - var video = this.video; - - this._codePaused = value; - - if (video) - { - if (value) - { - if (!video.paused) - { - video.pause(); - } - } - else if (!value) - { - if (video.paused && !this._systemPaused) - { - video.play(); - } - } - } - - return this; - }, - - /** - * Returns a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). - * - * @method Phaser.GameObjects.Video#getVolume - * @since 3.20.0 - * - * @return {number} A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). - */ - getVolume: function () - { - return (this.video) ? this.video.volume : 1; - }, - - /** - * Sets the volume of the currently playing video. - * - * The value given is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). - * - * @method Phaser.GameObjects.Video#setVolume - * @since 3.20.0 - * - * @param {number} [value=1] - A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). - * - * @return {this} This Video Game Object for method chaining. - */ - setVolume: function (value) - { - if (value === undefined) { value = 1; } - - if (this.video) - { - this.video.volume = Clamp(value, 0, 1); - } - - return this; - }, - - /** - * Returns a double that indicates the rate at which the media is being played back. - * - * @method Phaser.GameObjects.Video#getPlaybackRate - * @since 3.20.0 - * - * @return {number} A double that indicates the rate at which the media is being played back. - */ - getPlaybackRate: function () - { - return (this.video) ? this.video.playbackRate : 1; - }, - - /** - * Sets the playback rate of the current video. - * - * The value given is a double that indicates the rate at which the media is being played back. - * - * @method Phaser.GameObjects.Video#setPlaybackRate - * @since 3.20.0 - * - * @param {number} [rate] - A double that indicates the rate at which the media is being played back. - * - * @return {this} This Video Game Object for method chaining. - */ - setPlaybackRate: function (rate) - { - if (this.video) - { - this.video.playbackRate = rate; - } - - return this; - }, - - /** - * Returns a boolean which indicates whether the media element should start over when it reaches the end. - * - * @method Phaser.GameObjects.Video#getLoop - * @since 3.20.0 - * - * @return {boolean} A boolean which indicates whether the media element will start over when it reaches the end. - */ - getLoop: function () - { - return (this.video) ? this.video.loop : false; - }, - - /** - * Sets the loop state of the current video. - * - * The value given is a boolean which indicates whether the media element will start over when it reaches the end. - * - * Not all videos can loop, for example live streams. - * - * Please note that not all browsers support _seamless_ video looping for all encoding formats. - * - * @method Phaser.GameObjects.Video#setLoop - * @since 3.20.0 - * - * @param {boolean} [value=true] - A boolean which indicates whether the media element will start over when it reaches the end. - * - * @return {this} This Video Game Object for method chaining. - */ - setLoop: function (value) - { - if (value === undefined) { value = true; } - - if (this.video) - { - this.video.loop = value; - } - - return this; - }, - - /** - * Returns a boolean which indicates whether the video is currently playing. - * - * @method Phaser.GameObjects.Video#isPlaying - * @since 3.20.0 - * - * @return {boolean} A boolean which indicates whether the video is playing, or not. - */ - isPlaying: function () - { - return (this.video) ? !(this.video.paused || this.video.ended) : false; - }, - - /** - * Returns a boolean which indicates whether the video is currently paused. - * - * @method Phaser.GameObjects.Video#isPaused - * @since 3.20.0 - * - * @return {boolean} A boolean which indicates whether the video is paused, or not. - */ - isPaused: function () - { - return ((this.video && this.video.paused) || this._codePaused || this._systemPaused); - }, - - /** - * Stores this Video in the Texture Manager using the given key as a dynamic texture, - * which any texture-based Game Object, such as a Sprite, can use as its texture: - * - * ```javascript - * var vid = this.add.video(0, 0, 'intro'); - * - * vid.play(); - * - * vid.saveTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * The saved texture is automatically updated as the video plays. If you pause this video, - * or change its source, then the saved texture updates instantly. - * - * Calling `saveTexture` again will not save another copy of the same texture, it will just rename the existing one. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame. - * - * If you intend to save the texture so you can use it as the input for a Shader, you may need to set the - * `flipY` parameter to `true` if you find the video renders upside down in your shader. - * - * @method Phaser.GameObjects.Video#saveTexture - * @since 3.20.0 - * - * @param {string} key - The unique key to store the texture as within the global Texture Manager. - * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y` during upload? - * - * @return {Phaser.Textures.Texture} The Texture that was saved. - */ - saveTexture: function (key, flipY) - { - if (flipY === undefined) { flipY = false; } - - if (this.videoTexture) - { - this.scene.sys.textures.renameTexture(this._key, key); - } - - this._key = key; - - this.flipY = flipY; - - if (this.videoTextureSource) - { - this.videoTextureSource.setFlipY(flipY); - } - - return this.videoTexture; - }, - - /** - * Stops the video playing and clears all internal event listeners. - * - * If you only wish to pause playback of the video, and resume it a later time, use the `Video.pause` method instead. - * - * If the video hasn't finished downloading, calling this method will not abort the download. To do that you need to - * call `destroy` instead. - * - * @method Phaser.GameObjects.Video#stop - * @fires Phaser.GameObjects.Events#VIDEO_STOP - * @since 3.20.0 - * - * @return {this} This Video Game Object for method chaining. - */ - stop: function () - { - var video = this.video; - - if (video) - { - var callbacks = this._callbacks; - - for (var callback in callbacks) - { - video.removeEventListener(callback, callbacks[callback], true); - } - - video.pause(); - } - - if (this._retryID) - { - window.clearTimeout(this._retryID); - } - - this.emit(Events.VIDEO_STOP, this); - - return this; - }, - - /** - * Removes the Video element from the DOM by calling parentNode.removeChild on itself. - * - * Also removes the autoplay and src attributes and nulls the Video reference. - * - * You should not call this method if you were playing a video from the Video Cache that - * you wish to play again in your game, or if another Video object is also using the same - * video. - * - * If you loaded an external video via `Video.loadURL` then you should call this function - * to clear up once you are done with the instance. - * - * @method Phaser.GameObjects.Video#removeVideoElement - * @since 3.20.0 - */ - removeVideoElement: function () - { - var video = this.video; - - if (!video) - { - return; - } - - if (video.parentNode) - { - video.parentNode.removeChild(video); - } - - while (video.hasChildNodes()) - { - video.removeChild(video.firstChild); - } - - video.removeAttribute('autoplay'); - video.removeAttribute('src'); - - this.video = null; - }, - - /** - * Handles the pre-destroy step for the Video object. - * - * This calls `Video.stop` and optionally `Video.removeVideoElement`. - * - * If any Sprites are using this Video as their texture it is up to you to manage those. - * - * @method Phaser.GameObjects.Video#preDestroy - * @private - * @since 3.21.0 - */ - preDestroy: function () - { - this.stop(); - - if (this.removeVideoElementOnDestroy) - { - this.removeVideoElement(); - } - - var game = this.scene.sys.game.events; - - game.off(GameEvents.PAUSE, this.globalPause, this); - game.off(GameEvents.RESUME, this.globalResume, this); - - var sound = this.scene.sys.sound; - - if (sound) - { - sound.off(SoundEvents.GLOBAL_MUTE, this.globalMute, this); - } - - if (this._retryID) - { - window.clearTimeout(this._retryID); - } - } - -}); - -module.exports = Video; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Clamp = require('../../math/Clamp'); +var Components = require('../components'); +var Events = require('../events'); +var GameEvents = require('../../core/events/'); +var GameObject = require('../GameObject'); +var SoundEvents = require('../../sound/events/'); +var UUID = require('../../utils/string/UUID'); +var VideoRender = require('./VideoRender'); +var MATH_CONST = require('../../math/const'); + +/** + * @classdesc + * A Video Game Object. + * + * This Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, + * or playing a video based on a given URL. Videos can be either local, or streamed. + * + * ```javascript + * preload () { + * this.load.video('pixar', 'nemo.mp4'); + * } + * + * create () { + * this.add.video(400, 300, 'pixar'); + * } + * ``` + * + * 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. + * + * ### 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, ahd 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', 'loadeddata', false, true); + * } + * ``` + * + * The 5th 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. + * + * Note that due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. + * + * 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.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.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. + */ +var Video = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Mask, + Components.Origin, + Components.Pipeline, + Components.ScrollFactor, + Components.Size, + Components.TextureCrop, + Components.Tint, + Components.Transform, + Components.Visible, + VideoRender + ], + + initialize: + + function Video (scene, x, y, key) + { + GameObject.call(this, scene, 'Video'); + + /** + * A reference to the HTML Video Element this Video Game Object is playing. + * Will be `null` until a video is loaded for playback. + * + * @name Phaser.GameObjects.Video#video + * @type {?HTMLVideoElement} + * @since 3.20.0 + */ + this.video = null; + + /** + * The Phaser Texture this Game Object is using to render the video to. + * Will be `null` until a video is loaded for playback. + * + * @name Phaser.GameObjects.Video#videoTexture + * @type {?Phaser.Textures.Texture} + * @since 3.20.0 + */ + this.videoTexture = null; + + /** + * A reference to the TextureSource belong to the `videoTexture` Texture object. + * Will be `null` until a video is loaded for playback. + * + * @name Phaser.GameObjects.Video#videoTextureSource + * @type {?Phaser.Textures.TextureSource} + * @since 3.20.0 + */ + this.videoTextureSource = null; + + /** + * A Phaser CanvasTexture instance that holds the most recent snapshot taken from the video. + * This will only be set if `snapshot` or `snapshotArea` have been called, and will be `null` until that point. + * + * @name Phaser.GameObjects.Video#snapshotTexture + * @type {?Phaser.Textures.CanvasTexture} + * @since 3.20.0 + */ + this.snapshotTexture = null; + + /** + * If you have saved this video to a texture via the `saveTexture` method, this controls if the video + * is rendered with `flipY` in WebGL or not. You often need to set this if you wish to use the video texture + * as the input source for a shader. If you find your video is appearing upside down within a shader or + * custom pipeline, flip this property. + * + * @name Phaser.GameObjects.Video#flipY + * @type {boolean} + * @since 3.20.0 + */ + this.flipY = false; + + /** + * The key used by the texture as stored in the Texture Manager. + * + * @name Phaser.GameObjects.Video#_key + * @type {string} + * @private + * @since 3.20.0 + */ + this._key = UUID(); + + /** + * An internal flag holding the current state of the video lock, should document interaction be required + * before playback can begin. + * + * @name Phaser.GameObjects.Video#touchLocked + * @type {boolean} + * @since 3.20.0 + */ + this.touchLocked = true; + + /** + * Should the video auto play when document interaction is required and happens? + * + * @name Phaser.GameObjects.Video#playWhenUnlocked + * @type {boolean} + * @since 3.20.0 + */ + this.playWhenUnlocked = false; + + /** + * When starting playback of a video Phaser will monitor its `readyState` using a `setTimeout` call. + * The `setTimeout` happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * + * @name Phaser.GameObjects.Video#retryLimit + * @type {integer} + * @since 3.20.0 + */ + this.retryLimit = 20; + + /** + * The current retry attempt. + * + * @name Phaser.GameObjects.Video#retry + * @type {integer} + * @since 3.20.0 + */ + this.retry = 0; + + /** + * The number of ms between each retry while monitoring the ready state of a downloading video. + * + * @name Phaser.GameObjects.Video#retryInterval + * @type {integer} + * @since 3.20.0 + */ + this.retryInterval = 500; + + /** + * The setTimeout callback ID. + * + * @name Phaser.GameObjects.Video#_retryID + * @type {integer} + * @private + * @since 3.20.0 + */ + this._retryID = null; + + /** + * The video was muted due to a system event, such as the game losing focus. + * + * @name Phaser.GameObjects.Video#_systemMuted + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._systemMuted = false; + + /** + * The video was muted due to game code, not a system event. + * + * @name Phaser.GameObjects.Video#_codeMuted + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._codeMuted = false; + + /** + * The video was paused due to a system event, such as the game losing focus. + * + * @name Phaser.GameObjects.Video#_systemPaused + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._systemPaused = false; + + /** + * The video was paused due to game code, not a system event. + * + * @name Phaser.GameObjects.Video#_codePaused + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._codePaused = false; + + /** + * The locally bound event callback handlers. + * + * @name Phaser.GameObjects.Video#_callbacks + * @type {any} + * @private + * @since 3.20.0 + */ + this._callbacks = { + play: this.playHandler.bind(this), + error: this.loadErrorHandler.bind(this), + end: this.completeHandler.bind(this), + time: this.timeUpdateHandler.bind(this), + seeking: this.seekingHandler.bind(this), + seeked: this.seekedHandler.bind(this) + }; + + /** + * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method. + * + * @name Phaser.GameObjects.Video#_crop + * @type {object} + * @private + * @since 3.20.0 + */ + this._crop = this.resetCropObject(); + + /** + * An object containing in and out markers for sequence playback. + * + * @name Phaser.GameObjects.Video#markers + * @type {any} + * @since 3.20.0 + */ + this.markers = {}; + + /** + * The in marker. + * + * @name Phaser.GameObjects.Video#_markerIn + * @type {integer} + * @private + * @since 3.20.0 + */ + this._markerIn = -1; + + /** + * The out marker. + * + * @name Phaser.GameObjects.Video#_markerOut + * @type {integer} + * @private + * @since 3.20.0 + */ + this._markerOut = MATH_CONST.MAX_SAFE_INTEGER; + + /** + * The last time the TextureSource was updated. + * + * @name Phaser.GameObjects.Video#_lastUpdate + * @type {integer} + * @private + * @since 3.20.0 + */ + this._lastUpdate = 0; + + /** + * The key of the video being played from the Video cache, if any. + * + * @name Phaser.GameObjects.Video#_cacheKey + * @type {string} + * @private + * @since 3.20.0 + */ + this._cacheKey = ''; + + /** + * Is the video currently seeking? + * + * @name Phaser.GameObjects.Video#_isSeeking + * @type {boolean} + * @private + * @since 3.20.0 + */ + this._isSeeking = false; + + /** + * Should the Video element that this Video is using, be removed from the DOM + * when this Video is destroyed? + * + * @name Phaser.GameObjects.Video#removeVideoElementOnDestroy + * @type {boolean} + * @since 3.21.0 + */ + this.removeVideoElementOnDestroy = false; + + this.setPosition(x, y); + this.initPipeline(); + + if (key) + { + this.changeSource(key, false); + } + + var game = scene.sys.game.events; + + game.on(GameEvents.PAUSE, this.globalPause, this); + game.on(GameEvents.RESUME, this.globalResume, this); + + var sound = scene.sys.sound; + + if (sound) + { + sound.on(SoundEvents.GLOBAL_MUTE, this.globalMute, this); + } + }, + + /** + * 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', 'loadeddata', false, true); + * } + * ``` + * + * The 5th 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 {integer} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video. + * @param {integer} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video. + * + * @return {this} This Video Game Object for method chaining. + */ + play: function (loop, markerIn, markerOut) + { + if ((this.touchLocked && this.playWhenUnlocked) || this.isPlaying()) + { + return this; + } + + var video = this.video; + + if (!video) + { + console.warn('Video not loaded'); + + return this; + } + + if (loop === undefined) { loop = video.loop; } + + var sound = this.scene.sys.sound; + + if (sound && sound.mute) + { + // Mute will be set based on the global mute state of the Sound Manager (if there is one) + this.setMute(true); + } + + if (!isNaN(markerIn)) + { + this._markerIn = markerIn; + } + + if (!isNaN(markerOut) && markerOut > markerIn) + { + this._markerOut = markerOut; + } + + video.loop = loop; + + var callbacks = this._callbacks; + + var playPromise = video.play(); + + if (playPromise !== undefined) + { + playPromise.then(this.playPromiseSuccessHandler.bind(this)).catch(this.playPromiseErrorHandler.bind(this)); + } + else + { + // Old-school browsers with no Promises + video.addEventListener('playing', callbacks.play, true); + + // If video hasn't downloaded properly yet ... + if (video.readyState < 2) + { + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + } + + // Set these _after_ calling `play` or they don't fire (useful, thanks browsers) + video.addEventListener('ended', callbacks.end, true); + video.addEventListener('timeupdate', callbacks.time, true); + video.addEventListener('seeking', callbacks.seeking, true); + video.addEventListener('seeked', callbacks.seeked, true); + + return this; + }, + + /** + * This method allows you to change the source of the current video element. It works by first stopping the + * current video, if playing. Then deleting the video texture, if one has been created. Finally, it makes a + * new video texture and starts playback of the new source through the existing video element. + * + * The reason you may wish to do this is because videos that require interaction to unlock, remain in an unlocked + * state, even if you change the source of the video. By changing the source to a new video you avoid having to + * go through the unlock process again. + * + * @method Phaser.GameObjects.Video#changeSource + * @since 3.20.0 + * + * @param {string} key - The key of the Video this Game Object will swap to playing, as stored in the Video Cache. + * @param {boolean} [autoplay=true] - Should the video start playing immediately, once the swap is complete? + * @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 {integer} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video. + * @param {integer} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video. + * + * @return {this} This Video Game Object for method chaining. + */ + changeSource: function (key, autoplay, loop, markerIn, markerOut) + { + if (autoplay === undefined) { autoplay = true; } + + var currentVideo = this.video; + + if (currentVideo) + { + this.stop(); + } + + var newVideo = this.scene.sys.cache.video.get(key); + + if (newVideo) + { + this.video = newVideo; + + this._cacheKey = key; + + this._codePaused = newVideo.paused; + this._codeMuted = newVideo.muted; + + if (this.videoTexture) + { + this.scene.sys.textures.remove(this._key); + + this.videoTexture = this.scene.sys.textures.create(this._key, newVideo, newVideo.videoWidth, newVideo.videoHeight); + this.videoTextureSource = this.videoTexture.source[0]; + this.videoTexture.add('__BASE', 0, 0, 0, newVideo.videoWidth, newVideo.videoHeight); + + this.setTexture(this.videoTexture); + this.setSizeToFrame(); + this.updateDisplayOrigin(); + + this.emit(Events.VIDEO_CREATED, this, newVideo.videoWidth, newVideo.videoHeight); + } + else + { + this.updateTexture(); + } + + newVideo.currentTime = 0; + + this._lastUpdate = 0; + + if (autoplay) + { + this.play(loop, markerIn, markerOut); + } + } + else + { + this.video = null; + } + + return this; + }, + + /** + * 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 {integer} markerIn - The time, in seconds, representing the start of this marker. + * @param {integer} markerOut - The time, in seconds, representing the end of this marker. + * + * @return {this} This Video Game Object for method chaining. + */ + addMarker: function (key, markerIn, markerOut) + { + if (!isNaN(markerIn) && markerIn >= 0 && !isNaN(markerOut)) + { + this.markers[key] = [ markerIn, markerOut ]; + } + + return this; + }, + + /** + * 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. + */ + playMarker: function (key, loop) + { + var marker = this.markers[key]; + + if (marker) + { + this.play(loop, marker[0], marker[1]); + } + + return this; + }, + + /** + * Removes a previously set marker from this video. + * + * If the marker is currently playing it will _not_ stop playback. + * + * @method Phaser.GameObjects.Video#removeMarker + * @since 3.20.0 + * + * @param {string} key - The name of the marker to remove. + * + * @return {this} This Video Game Object for method chaining. + */ + removeMarker: function (key) + { + delete this.markers[key]; + + return this; + }, + + /** + * Takes a snapshot of the current frame of the video and renders it to a CanvasTexture object, + * which is then returned. You can optionally resize the grab by passing a width and height. + * + * This method returns a reference to the `Video.snapshotTexture` object. Calling this method + * multiple times will overwrite the previous snapshot with the most recent one. + * + * @method Phaser.GameObjects.Video#snapshot + * @since 3.20.0 + * + * @param {integer} [width] - The width of the resulting CanvasTexture. + * @param {integer} [height] - The height of the resulting CanvasTexture. + * + * @return {Phaser.Textures.CanvasTexture} + */ + snapshot: function (width, height) + { + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + return this.snapshotArea(0, 0, this.width, this.height, width, height); + }, + + /** + * Takes a snapshot of the specified area of the current frame of the video and renders it to a CanvasTexture object, + * which is then returned. You can optionally resize the grab by passing a different `destWidth` and `destHeight`. + * + * This method returns a reference to the `Video.snapshotTexture` object. Calling this method + * multiple times will overwrite the previous snapshot with the most recent one. + * + * @method Phaser.GameObjects.Video#snapshotArea + * @since 3.20.0 + * + * @param {integer} [x=0] - The horizontal location of the top-left of the area to grab from. + * @param {integer} [y=0] - The vertical location of the top-left of the area to grab from. + * @param {integer} [srcWidth] - The width of area to grab from the video. If not given it will grab the full video dimensions. + * @param {integer} [srcHeight] - The height of area to grab from the video. If not given it will grab the full video dimensions. + * @param {integer} [destWidth] - The destination width of the grab, allowing you to resize it. + * @param {integer} [destHeight] - The destination height of the grab, allowing you to resize it. + * + * @return {Phaser.Textures.CanvasTexture} + */ + snapshotArea: function (x, y, srcWidth, srcHeight, destWidth, destHeight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (srcWidth === undefined) { srcWidth = this.width; } + if (srcHeight === undefined) { srcHeight = this.height; } + if (destWidth === undefined) { destWidth = srcWidth; } + if (destHeight === undefined) { destHeight = srcHeight; } + + var video = this.video; + var snap = this.snapshotTexture; + + if (!snap) + { + snap = this.scene.sys.textures.createCanvas(UUID(), destWidth, destHeight); + + this.snapshotTexture = snap; + + if (video) + { + snap.context.drawImage(video, x, y, srcWidth, srcHeight, 0, 0, destWidth, destHeight); + } + } + else + { + snap.setSize(destWidth, destHeight); + + if (video) + { + snap.context.drawImage(video, x, y, srcWidth, srcHeight, 0, 0, destWidth, destHeight); + } + } + + return snap.update(); + }, + + /** + * Stores a copy of this Videos `snapshotTexture` in the Texture Manager using the given key. + * + * This texture is created when the `snapshot` or `snapshotArea` methods are called. + * + * After doing this, any texture based Game Object, such as a Sprite, can use the contents of the + * snapshot by using the texture key: + * + * ```javascript + * var vid = this.add.video(0, 0, 'intro'); + * + * vid.snapshot(); + * + * vid.saveSnapshotTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Updating the contents of the `snapshotTexture`, for example by calling `snapshot` again, + * will automatically update _any_ Game Object that is using it as a texture. + * Calling `saveSnapshotTexture` again will not save another copy of the same texture, + * it will just rename the existing one. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame. + * + * @method Phaser.GameObjects.Video#saveSnapshotTexture + * @since 3.20.0 + * + * @param {string} key - The unique key to store the texture as within the global Texture Manager. + * + * @return {Phaser.Textures.CanvasTexture} The Texture that was saved. + */ + saveSnapshotTexture: function (key) + { + if (this.snapshotTexture) + { + this.scene.sys.textures.renameTexture(this.snapshotTexture.key, key); + } + else + { + this.snapshotTexture = this.scene.sys.textures.createCanvas(key, this.width, this.height); + } + + return this.snapshotTexture; + }, + + /** + * Loads a Video from the given URL, ready for playback with the `Video.play` method. + * + * You can control at what point the browser determines the video as being ready for playback via + * the `loadEvent` parameter. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement + * for more details. + * + * @method Phaser.GameObjects.Video#loadURL + * @since 3.20.0 + * + * @param {string} url - The URL of the video to load or be streamed. + * @param {string} [loadEvent='loadeddata'] - The load event to listen for. Either `loadeddata`, `canplay` or `canplaythrough`. + * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. + * + * @return {this} This Video Game Object for method chaining. + */ + loadURL: function (url, loadEvent, noAudio) + { + if (loadEvent === undefined) { loadEvent = 'loadeddata'; } + if (noAudio === undefined) { noAudio = false; } + + if (this.video) + { + this.stop(); + } + + if (this.videoTexture) + { + this.scene.sys.textures.remove(this._key); + } + + var video = document.createElement('video'); + + video.controls = false; + + if (noAudio) + { + video.muted = true; + video.defaultMuted = true; + + video.setAttribute('autoplay', 'autoplay'); + } + + video.setAttribute('playsinline', 'playsinline'); + video.setAttribute('preload', 'auto'); + + video.addEventListener('error', this._callbacks.error, true); + + video.src = url; + + video.load(); + + this.video = video; + + return this; + }, + + /** + * This internal method is called automatically if the playback Promise resolves successfully. + * + * @method Phaser.GameObjects.Video#playPromiseSuccessHandler + * @fires Phaser.GameObjects.Events#VIDEO_PLAY + * @private + * @since 3.20.0 + */ + playPromiseSuccessHandler: function () + { + this.touchLocked = false; + + this.emit(Events.VIDEO_PLAY, this); + + if (this._markerIn > -1) + { + this.video.currentTime = this._markerIn; + } + }, + + /** + * This internal method is called automatically if the playback Promise fails to resolve. + * + * @method Phaser.GameObjects.Video#playPromiseErrorHandler + * @fires Phaser.GameObjects.Events#VIDEO_ERROR + * @private + * @since 3.20.0 + * + * @param {any} error - The Promise resolution error. + */ + playPromiseErrorHandler: function (error) + { + this.scene.sys.input.once('pointerdown', this.unlockHandler, this); + + this.touchLocked = true; + this.playWhenUnlocked = true; + + this.emit(Events.VIDEO_ERROR, this, error); + }, + + /** + * Called when the video emits a `playing` event during load. + * + * This is only listened for if the browser doesn't support Promises. + * + * @method Phaser.GameObjects.Video#playHandler + * @fires Phaser.GameObjects.Events#VIDEO_PLAY + * @since 3.20.0 + */ + playHandler: function () + { + this.touchLocked = false; + + this.emit(Events.VIDEO_PLAY, this); + + this.video.removeEventListener('playing', this._callbacks.play, true); + }, + + /** + * This internal method is called automatically if the video fails to load. + * + * @method Phaser.GameObjects.Video#loadErrorHandler + * @fires Phaser.GameObjects.Events#VIDEO_ERROR + * @private + * @since 3.20.0 + * + * @param {Event} event - The error Event. + */ + loadErrorHandler: function (event) + { + this.stop(); + + this.emit(Events.VIDEO_ERROR, this, event); + }, + + /** + * This internal method is called if the video couldn't be played because it was interaction locked + * by the browser, but an input event has since been received. + * + * @method Phaser.GameObjects.Video#unlockHandler + * @fires Phaser.GameObjects.Events#VIDEO_UNLOCKED + * @fires Phaser.GameObjects.Events#VIDEO_PLAY + * @private + * @since 3.20.0 + * + * @param {any} error - The Promise resolution error. + */ + unlockHandler: function () + { + this.touchLocked = false; + this.playWhenUnlocked = false; + + this.emit(Events.VIDEO_UNLOCKED, this); + + if (this._markerIn > -1) + { + this.video.currentTime = this._markerIn; + } + + this.video.play(); + + this.emit(Events.VIDEO_PLAY, this); + }, + + /** + * Called when the video completes playback, i.e. reaches an `ended` state. + * + * This will never happen if the video is coming from a live stream, where the duration is `Infinity`. + * + * @method Phaser.GameObjects.Video#completeHandler + * @fires Phaser.GameObjects.Events#VIDEO_COMPLETE + * @since 3.20.0 + */ + completeHandler: function () + { + this.emit(Events.VIDEO_COMPLETE, this); + }, + + /** + * Called when the video emits a `timeUpdate` event during playback. + * + * This event is too slow and irregular to be used for actual video timing or texture updating, + * but we can use it to determine if a video has looped. + * + * @method Phaser.GameObjects.Video#timeUpdateHandler + * @fires Phaser.GameObjects.Events#VIDEO_LOOP + * @since 3.20.0 + */ + timeUpdateHandler: function () + { + if (this.video && this.video.currentTime < this._lastUpdate) + { + this.emit(Events.VIDEO_LOOP, this); + + this._lastUpdate = 0; + } + }, + + /** + * The internal update step. + * + * @method Phaser.GameObjects.Video#preUpdate + * @private + * @since 3.20.0 + */ + preUpdate: function () + { + var video = this.video; + + if (video) + { + var currentTime = video.currentTime; + + // Don't render a new frame unless the video has actually changed time + if (currentTime !== this._lastUpdate) + { + this._lastUpdate = currentTime; + + this.updateTexture(); + + if (currentTime >= this._markerOut) + { + if (video.loop) + { + video.currentTime = this._markerIn; + + this.updateTexture(); + + this._lastUpdate = currentTime; + + this.emit(Events.VIDEO_LOOP, this); + } + else + { + this.emit(Events.VIDEO_COMPLETE, this); + + this.stop(); + } + } + } + } + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.GameObjects.Video#checkVideoProgress + * @fires Phaser.GameObjects.Events#VIDEO_TIMEOUT + * @private + * @since 3.20.0 + */ + checkVideoProgress: function () + { + if (this.video.readyState >= 2) + { + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this.emit(Events.VIDEO_TIMEOUT, this); + } + } + }, + + /** + * Internal method that is called when enough video data has been received in order to create a texture + * from it. The texture is assigned to the `Video.videoTexture` property and given a base frame that + * encompases the whole video size. + * + * @method Phaser.GameObjects.Video#updateTexture + * @since 3.20.0 + */ + updateTexture: function () + { + var video = this.video; + + var width = video.videoWidth; + var height = video.videoHeight; + + if (!this.videoTexture) + { + this.videoTexture = this.scene.sys.textures.create(this._key, video, width, height); + this.videoTextureSource = this.videoTexture.source[0]; + this.videoTexture.add('__BASE', 0, 0, 0, width, height); + + this.setTexture(this.videoTexture); + this.setSizeToFrame(); + this.updateDisplayOrigin(); + + this.emit(Events.VIDEO_CREATED, this, width, height); + } + else + { + var textureSource = this.videoTextureSource; + + if (textureSource.source !== video) + { + textureSource.source = video; + textureSource.width = width; + textureSource.height = height; + } + + textureSource.update(); + } + }, + + /** + * Returns the key of the currently played video, as stored in the Video Cache. + * If the video did not come from the cache this will return an empty string. + * + * @method Phaser.GameObjects.Video#getVideoKey + * @since 3.20.0 + * + * @return {string} The key of the video being played from the Video Cache, if any. + */ + getVideoKey: function () + { + return this._cacheKey; + }, + + /** + * 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. + * + * @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. + */ + seekTo: function (value) + { + var video = this.video; + + if (video) + { + var duration = video.duration; + + if (duration !== Infinity && !isNaN(duration)) + { + var seekTime = duration * value; + + this.setCurrentTime(seekTime); + } + } + + return this; + }, + + /** + * A double-precision floating-point value indicating the current playback time in seconds. + * If the media has not started to play and has not been seeked, this value is the media's initial playback time. + * + * @method Phaser.GameObjects.Video#getCurrentTime + * @since 3.20.0 + * + * @return {number} A double-precision floating-point value indicating the current playback time in seconds. + */ + getCurrentTime: function () + { + return (this.video) ? this.video.currentTime : 0; + }, + + /** + * 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. + */ + setCurrentTime: function (value) + { + var video = this.video; + + if (video) + { + if (typeof value === 'string') + { + var op = value[0]; + var num = parseFloat(value.substr(1)); + + if (op === '+') + { + value = video.currentTime + num; + } + else if (op === '-') + { + value = video.currentTime - num; + } + } + + video.currentTime = value; + + this._lastUpdate = value; + } + + return this; + }, + + /** + * Returns a boolean indicating if this Video is currently seeking, or not. + * + * @method Phaser.GameObjects.Video#isSeeking + * @since 3.20.0 + * + * @return {boolean} A boolean indicating if this Video is currently seeking, or not. + */ + isSeeking: function () + { + return this._isSeeking; + }, + + /** + * Internal seeking handler. + * + * @method Phaser.GameObjects.Video#seekingHandler + * @fires Phaser.GameObjects.Events#VIDEO_SEEKING + * @private + * @since 3.20.0 + */ + seekingHandler: function () + { + this._isSeeking = true; + + this.emit(Events.VIDEO_SEEKING, this); + }, + + /** + * Internal seeked handler. + * + * @method Phaser.GameObjects.Video#seekedHandler + * @fires Phaser.GameObjects.Events#VIDEO_SEEKED + * @private + * @since 3.20.0 + */ + seekedHandler: function () + { + this._isSeeking = false; + + this.emit(Events.VIDEO_SEEKED, this); + + var video = this.video; + + if (video) + { + this.updateTexture(); + } + }, + + /** + * Returns the current progress of the video. Progress is defined as a value between 0 (the start) + * and 1 (the end). + * + * Progress can only be returned if the video has a duration, otherwise it will always return zero. + * + * @method Phaser.GameObjects.Video#getProgress + * @since 3.20.0 + * + * @return {number} The current progress of playback. If the video has no duration, will always return zero. + */ + getProgress: function () + { + var video = this.video; + + if (video) + { + var now = video.currentTime; + var duration = video.duration; + + if (duration !== Infinity && !isNaN(duration)) + { + return now / duration; + } + } + + return 0; + }, + + /** + * A double-precision floating-point value which indicates the duration (total length) of the media in seconds, + * on the media's timeline. If no media is present on the element, or the media is not valid, the returned value is NaN. + * + * If the media has no known end (such as for live streams of unknown duration, web radio, media incoming from WebRTC, + * and so forth), this value is +Infinity. + * + * @method Phaser.GameObjects.Video#getDuration + * @since 3.20.0 + * + * @return {number} A double-precision floating-point value indicating the duration of the media in seconds. + */ + getDuration: function () + { + return (this.video) ? this.video.duration : 0; + }, + + /** + * Sets the muted state of the currently playing video, if one is loaded. + * + * @method Phaser.GameObjects.Video#setMute + * @since 3.20.0 + * + * @param {boolean} [value=true] - The mute value. `true` if the video should be muted, otherwise `false`. + * + * @return {this} This Video Game Object for method chaining. + */ + setMute: function (value) + { + if (value === undefined) { value = true; } + + this._codeMuted = value; + + var video = this.video; + + if (video) + { + video.muted = (this._systemMuted) ? true : value; + } + + return this; + }, + + /** + * Returns a boolean indicating if this Video is currently muted. + * + * @method Phaser.GameObjects.Video#isMuted + * @since 3.20.0 + * + * @return {boolean} A boolean indicating if this Video is currently muted, or not. + */ + isMuted: function () + { + return this._codeMuted; + }, + + /** + * Internal global mute handler. Will mute the video, if playing, if the global sound system mutes. + * + * @method Phaser.GameObjects.Video#globalMute + * @private + * @since 3.20.0 + * + * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the Sound Manager that emitted the event. + * @param {boolean} mute - The mute value. `true` if the Sound Manager is now muted, otherwise `false`. + */ + globalMute: function (soundManager, value) + { + this._systemMuted = value; + + var video = this.video; + + if (video) + { + video.muted = (this._codeMuted) ? true : value; + } + }, + + /** + * Internal global pause handler. Will pause the video if the Game itself pauses. + * + * @method Phaser.GameObjects.Video#globalPause + * @private + * @since 3.20.0 + */ + globalPause: function () + { + this._systemPaused = true; + + if (this.video) + { + this.video.pause(); + } + }, + + /** + * Internal global resume handler. Will resume a paused video if the Game itself resumes. + * + * @method Phaser.GameObjects.Video#globalResume + * @private + * @since 3.20.0 + */ + globalResume: function () + { + this._systemPaused = false; + + if (this.video && !this._codePaused) + { + this.video.play(); + } + }, + + /** + * Sets the paused state of the currently loaded video. + * + * If the video is playing, calling this method with `true` will pause playback. + * If the video is paused, calling this method with `false` will resume playback. + * + * If no video is loaded, this method does nothing. + * + * @method Phaser.GameObjects.Video#setPaused + * @since 3.20.0 + * + * @param {boolean} [value=true] - The paused value. `true` if the video should be paused, `false` to resume it. + * + * @return {this} This Video Game Object for method chaining. + */ + setPaused: function (value) + { + if (value === undefined) { value = true; } + + var video = this.video; + + this._codePaused = value; + + if (video) + { + if (value) + { + if (!video.paused) + { + video.pause(); + } + } + else if (!value) + { + if (video.paused && !this._systemPaused) + { + video.play(); + } + } + } + + return this; + }, + + /** + * Returns a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * + * @method Phaser.GameObjects.Video#getVolume + * @since 3.20.0 + * + * @return {number} A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + */ + getVolume: function () + { + return (this.video) ? this.video.volume : 1; + }, + + /** + * Sets the volume of the currently playing video. + * + * The value given is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * + * @method Phaser.GameObjects.Video#setVolume + * @since 3.20.0 + * + * @param {number} [value=1] - A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * + * @return {this} This Video Game Object for method chaining. + */ + setVolume: function (value) + { + if (value === undefined) { value = 1; } + + if (this.video) + { + this.video.volume = Clamp(value, 0, 1); + } + + return this; + }, + + /** + * Returns a double that indicates the rate at which the media is being played back. + * + * @method Phaser.GameObjects.Video#getPlaybackRate + * @since 3.20.0 + * + * @return {number} A double that indicates the rate at which the media is being played back. + */ + getPlaybackRate: function () + { + return (this.video) ? this.video.playbackRate : 1; + }, + + /** + * Sets the playback rate of the current video. + * + * The value given is a double that indicates the rate at which the media is being played back. + * + * @method Phaser.GameObjects.Video#setPlaybackRate + * @since 3.20.0 + * + * @param {number} [rate] - A double that indicates the rate at which the media is being played back. + * + * @return {this} This Video Game Object for method chaining. + */ + setPlaybackRate: function (rate) + { + if (this.video) + { + this.video.playbackRate = rate; + } + + return this; + }, + + /** + * Returns a boolean which indicates whether the media element should start over when it reaches the end. + * + * @method Phaser.GameObjects.Video#getLoop + * @since 3.20.0 + * + * @return {boolean} A boolean which indicates whether the media element will start over when it reaches the end. + */ + getLoop: function () + { + return (this.video) ? this.video.loop : false; + }, + + /** + * Sets the loop state of the current video. + * + * The value given is a boolean which indicates whether the media element will start over when it reaches the end. + * + * Not all videos can loop, for example live streams. + * + * Please note that not all browsers support _seamless_ video looping for all encoding formats. + * + * @method Phaser.GameObjects.Video#setLoop + * @since 3.20.0 + * + * @param {boolean} [value=true] - A boolean which indicates whether the media element will start over when it reaches the end. + * + * @return {this} This Video Game Object for method chaining. + */ + setLoop: function (value) + { + if (value === undefined) { value = true; } + + if (this.video) + { + this.video.loop = value; + } + + return this; + }, + + /** + * Returns a boolean which indicates whether the video is currently playing. + * + * @method Phaser.GameObjects.Video#isPlaying + * @since 3.20.0 + * + * @return {boolean} A boolean which indicates whether the video is playing, or not. + */ + isPlaying: function () + { + return (this.video) ? !(this.video.paused || this.video.ended) : false; + }, + + /** + * Returns a boolean which indicates whether the video is currently paused. + * + * @method Phaser.GameObjects.Video#isPaused + * @since 3.20.0 + * + * @return {boolean} A boolean which indicates whether the video is paused, or not. + */ + isPaused: function () + { + return ((this.video && this.video.paused) || this._codePaused || this._systemPaused); + }, + + /** + * Stores this Video in the Texture Manager using the given key as a dynamic texture, + * which any texture-based Game Object, such as a Sprite, can use as its texture: + * + * ```javascript + * var vid = this.add.video(0, 0, 'intro'); + * + * vid.play(); + * + * vid.saveTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * The saved texture is automatically updated as the video plays. If you pause this video, + * or change its source, then the saved texture updates instantly. + * + * Calling `saveTexture` again will not save another copy of the same texture, it will just rename the existing one. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame. + * + * If you intend to save the texture so you can use it as the input for a Shader, you may need to set the + * `flipY` parameter to `true` if you find the video renders upside down in your shader. + * + * @method Phaser.GameObjects.Video#saveTexture + * @since 3.20.0 + * + * @param {string} key - The unique key to store the texture as within the global Texture Manager. + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y` during upload? + * + * @return {Phaser.Textures.Texture} The Texture that was saved. + */ + saveTexture: function (key, flipY) + { + if (flipY === undefined) { flipY = false; } + + if (this.videoTexture) + { + this.scene.sys.textures.renameTexture(this._key, key); + } + + this._key = key; + + this.flipY = flipY; + + if (this.videoTextureSource) + { + this.videoTextureSource.setFlipY(flipY); + } + + return this.videoTexture; + }, + + /** + * Stops the video playing and clears all internal event listeners. + * + * If you only wish to pause playback of the video, and resume it a later time, use the `Video.pause` method instead. + * + * If the video hasn't finished downloading, calling this method will not abort the download. To do that you need to + * call `destroy` instead. + * + * @method Phaser.GameObjects.Video#stop + * @fires Phaser.GameObjects.Events#VIDEO_STOP + * @since 3.20.0 + * + * @return {this} This Video Game Object for method chaining. + */ + stop: function () + { + var video = this.video; + + if (video) + { + var callbacks = this._callbacks; + + for (var callback in callbacks) + { + video.removeEventListener(callback, callbacks[callback], true); + } + + video.pause(); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + this.emit(Events.VIDEO_STOP, this); + + return this; + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * + * Also removes the autoplay and src attributes and nulls the Video reference. + * + * You should not call this method if you were playing a video from the Video Cache that + * you wish to play again in your game, or if another Video object is also using the same + * video. + * + * If you loaded an external video via `Video.loadURL` then you should call this function + * to clear up once you are done with the instance. + * + * @method Phaser.GameObjects.Video#removeVideoElement + * @since 3.20.0 + */ + removeVideoElement: function () + { + var video = this.video; + + if (!video) + { + return; + } + + if (video.parentNode) + { + video.parentNode.removeChild(video); + } + + while (video.hasChildNodes()) + { + video.removeChild(video.firstChild); + } + + video.removeAttribute('autoplay'); + video.removeAttribute('src'); + + this.video = null; + }, + + /** + * Handles the pre-destroy step for the Video object. + * + * This calls `Video.stop` and optionally `Video.removeVideoElement`. + * + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.GameObjects.Video#preDestroy + * @private + * @since 3.21.0 + */ + preDestroy: function () + { + this.stop(); + + if (this.removeVideoElementOnDestroy) + { + this.removeVideoElement(); + } + + var game = this.scene.sys.game.events; + + game.off(GameEvents.PAUSE, this.globalPause, this); + game.off(GameEvents.RESUME, this.globalResume, this); + + var sound = this.scene.sys.sound; + + if (sound) + { + sound.off(SoundEvents.GLOBAL_MUTE, this.globalMute, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + } + +}); + +module.exports = Video; diff --git a/src/gameobjects/video/VideoCanvasRenderer.js b/src/gameobjects/video/VideoCanvasRenderer.js index d5b1e979d..5e28ad7e0 100644 --- a/src/gameobjects/video/VideoCanvasRenderer.js +++ b/src/gameobjects/video/VideoCanvasRenderer.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Video#renderCanvas - * @since 3.20.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.GameObjects.Video} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var VideoCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - if (src.videoTexture) - { - renderer.batchSprite(src, src.frame, camera, parentMatrix); - } -}; - -module.exports = VideoCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Video#renderCanvas + * @since 3.20.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.GameObjects.Video} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var VideoCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (src.videoTexture) + { + renderer.batchSprite(src, src.frame, camera, parentMatrix); + } +}; + +module.exports = VideoCanvasRenderer; diff --git a/src/gameobjects/video/VideoCreator.js b/src/gameobjects/video/VideoCreator.js index d30bd1c51..0c5b230c5 100644 --- a/src/gameobjects/video/VideoCreator.js +++ b/src/gameobjects/video/VideoCreator.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BuildGameObject = require('../BuildGameObject'); -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var Video = require('./Video'); - -/** - * Creates a new Video Game Object and returns it. - * - * Note: This method will only be available if the Video Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#video - * @since 3.20.0 - * - * @param {object} 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.Video} The Game Object that was created. - */ -GameObjectCreator.register('video', function (config, addToScene) -{ - if (config === undefined) { config = {}; } - - var key = GetAdvancedValue(config, 'key', null); - - var video = new Video(this.scene, 0, 0, key); - - if (addToScene !== undefined) - { - config.add = addToScene; - } - - BuildGameObject(this.scene, video, config); - - return video; -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BuildGameObject = require('../BuildGameObject'); +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var Video = require('./Video'); + +/** + * Creates a new Video Game Object and returns it. + * + * Note: This method will only be available if the Video Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#video + * @since 3.20.0 + * + * @param {object} 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.Video} The Game Object that was created. + */ +GameObjectCreator.register('video', function (config, addToScene) +{ + if (config === undefined) { config = {}; } + + var key = GetAdvancedValue(config, 'key', null); + + var video = new Video(this.scene, 0, 0, key); + + if (addToScene !== undefined) + { + config.add = addToScene; + } + + BuildGameObject(this.scene, video, config); + + return video; +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/video/VideoFactory.js b/src/gameobjects/video/VideoFactory.js index 98d7b7999..f69349cb9 100644 --- a/src/gameobjects/video/VideoFactory.js +++ b/src/gameobjects/video/VideoFactory.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Video = require('./Video'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Image Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Image 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.GameObjects.Image} The Game Object that was created. - */ -GameObjectFactory.register('video', function (x, y, key) -{ - var video = new Video(this.scene, x, y, key); - - this.displayList.add(video); - this.updateList.add(video); - - return video; -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Video = require('./Video'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Image Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Image 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.GameObjects.Image} The Game Object that was created. + */ +GameObjectFactory.register('video', function (x, y, key) +{ + var video = new Video(this.scene, x, y, key); + + this.displayList.add(video); + this.updateList.add(video); + + return video; +}); + +// 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 diff --git a/src/gameobjects/video/VideoRender.js b/src/gameobjects/video/VideoRender.js index 129a17ba7..5286a3d28 100644 --- a/src/gameobjects/video/VideoRender.js +++ b/src/gameobjects/video/VideoRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./VideoWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./VideoCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./VideoWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./VideoCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/gameobjects/video/VideoWebGLRenderer.js b/src/gameobjects/video/VideoWebGLRenderer.js index 5b13e5fd7..ef3919a80 100644 --- a/src/gameobjects/video/VideoWebGLRenderer.js +++ b/src/gameobjects/video/VideoWebGLRenderer.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.GameObjects.Video#renderWebGL - * @since 3.20.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.GameObjects.Video} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var VideoWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - if (src.videoTexture) - { - this.pipeline.batchSprite(src, camera, parentMatrix); - } -}; - -module.exports = VideoWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.GameObjects.Video#renderWebGL + * @since 3.20.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.GameObjects.Video} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var VideoWebGLRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + if (src.videoTexture) + { + this.pipeline.batchSprite(src, camera, parentMatrix); + } +}; + +module.exports = VideoWebGLRenderer; diff --git a/src/gameobjects/zone/Zone.js b/src/gameobjects/zone/Zone.js index a80110592..a20850a3f 100644 --- a/src/gameobjects/zone/Zone.js +++ b/src/gameobjects/zone/Zone.js @@ -1,307 +1,307 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BlendModes = require('../../renderer/BlendModes'); -var Circle = require('../../geom/circle/Circle'); -var CircleContains = require('../../geom/circle/Contains'); -var Class = require('../../utils/Class'); -var Components = require('../components'); -var GameObject = require('../GameObject'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var RectangleContains = require('../../geom/rectangle/Contains'); - -/** - * @classdesc - * A Zone Game Object. - * - * A Zone is a non-rendering rectangular Game Object that has a position and size. - * It has no texture and never displays, but does live on the display list and - * can be moved, scaled and rotated like any other Game Object. - * - * Its primary use is for creating Drop Zones and Input Hit Areas and it has a couple of helper methods - * specifically for this. It is also useful for object overlap checks, or as a base for your own - * non-displaying Game Objects. - - * The default origin is 0.5, the center of the Zone, the same as with Game Objects. - * - * @class Zone - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.GameObjects - * @constructor - * @since 3.0.0 - * - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Visible - * - * @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 {number} [width=1] - The width of the Game Object. - * @param {number} [height=1] - The height of the Game Object. - */ -var Zone = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Depth, - Components.GetBounds, - Components.Origin, - Components.Transform, - Components.ScrollFactor, - Components.Visible - ], - - initialize: - - function Zone (scene, x, y, width, height) - { - if (width === undefined) { width = 1; } - if (height === undefined) { height = width; } - - GameObject.call(this, scene, 'Zone'); - - this.setPosition(x, y); - - /** - * The native (un-scaled) width of this Game Object. - * - * @name Phaser.GameObjects.Zone#width - * @type {number} - * @since 3.0.0 - */ - this.width = width; - - /** - * The native (un-scaled) height of this Game Object. - * - * @name Phaser.GameObjects.Zone#height - * @type {number} - * @since 3.0.0 - */ - this.height = height; - - /** - * The Blend Mode of the Game Object. - * Although a Zone never renders, it still has a blend mode to allow it to fit seamlessly into - * display lists without causing a batch flush. - * - * @name Phaser.GameObjects.Zone#blendMode - * @type {integer} - * @since 3.0.0 - */ - this.blendMode = BlendModes.NORMAL; - - this.updateDisplayOrigin(); - }, - - /** - * The displayed width of this Game Object. - * This value takes into account the scale factor. - * - * @name Phaser.GameObjects.Zone#displayWidth - * @type {number} - * @since 3.0.0 - */ - displayWidth: { - - get: function () - { - return this.scaleX * this.width; - }, - - set: function (value) - { - this.scaleX = value / this.width; - } - - }, - - /** - * The displayed height of this Game Object. - * This value takes into account the scale factor. - * - * @name Phaser.GameObjects.Zone#displayHeight - * @type {number} - * @since 3.0.0 - */ - displayHeight: { - - get: function () - { - return this.scaleY * this.height; - }, - - set: function (value) - { - this.scaleY = value / this.height; - } - - }, - - /** - * Sets the size of this Game Object. - * - * @method Phaser.GameObjects.Zone#setSize - * @since 3.0.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * @param {boolean} [resizeInput=true] - If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. - * - * @return {this} This Game Object. - */ - setSize: function (width, height, resizeInput) - { - if (resizeInput === undefined) { resizeInput = true; } - - this.width = width; - this.height = height; - - this.updateDisplayOrigin(); - - var input = this.input; - - if (resizeInput && input && !input.customHitArea) - { - input.hitArea.width = width; - input.hitArea.height = height; - } - - return this; - }, - - /** - * Sets the display size of this Game Object. - * Calling this will adjust the scale. - * - * @method Phaser.GameObjects.Zone#setDisplaySize - * @since 3.0.0 - * - * @param {number} width - The width of this Game Object. - * @param {number} height - The height of this Game Object. - * - * @return {this} This Game Object. - */ - setDisplaySize: function (width, height) - { - this.displayWidth = width; - this.displayHeight = height; - - return this; - }, - - /** - * Sets this Zone to be a Circular Drop Zone. - * The circle is centered on this Zones `x` and `y` coordinates. - * - * @method Phaser.GameObjects.Zone#setCircleDropZone - * @since 3.0.0 - * - * @param {number} radius - The radius of the Circle that will form the Drop Zone. - * - * @return {this} This Game Object. - */ - setCircleDropZone: function (radius) - { - return this.setDropZone(new Circle(0, 0, radius), CircleContains); - }, - - /** - * Sets this Zone to be a Rectangle Drop Zone. - * The rectangle is centered on this Zones `x` and `y` coordinates. - * - * @method Phaser.GameObjects.Zone#setRectangleDropZone - * @since 3.0.0 - * - * @param {number} width - The width of the rectangle drop zone. - * @param {number} height - The height of the rectangle drop zone. - * - * @return {this} This Game Object. - */ - setRectangleDropZone: function (width, height) - { - return this.setDropZone(new Rectangle(0, 0, width, height), RectangleContains); - }, - - /** - * Allows you to define your own Geometry shape to be used as a Drop Zone. - * - * @method Phaser.GameObjects.Zone#setDropZone - * @since 3.0.0 - * - * @param {object} shape - A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. - * @param {Phaser.Types.Input.HitAreaCallback} callback - A function that will return `true` if the given x/y coords it is sent are within the shape. - * - * @return {this} This Game Object. - */ - setDropZone: function (shape, callback) - { - if (shape === undefined) - { - this.setRectangleDropZone(this.width, this.height); - } - else if (!this.input) - { - this.setInteractive(shape, callback, true); - } - - return this; - }, - - /** - * A NOOP method so you can pass a Zone to a Container. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Zone#setAlpha - * @private - * @since 3.11.0 - */ - setAlpha: function () - { - }, - - /** - * A NOOP method so you can pass a Zone to a Container in Canvas. - * Calling this method will do nothing. It is intentionally empty. - * - * @method Phaser.GameObjects.Zone#setBlendMode - * @private - * @since 3.16.2 - */ - setBlendMode: function () - { - }, - - /** - * A Zone does not render. - * - * @method Phaser.GameObjects.Zone#renderCanvas - * @private - * @since 3.0.0 - */ - renderCanvas: function () - { - }, - - /** - * A Zone does not render. - * - * @method Phaser.GameObjects.Zone#renderWebGL - * @private - * @since 3.0.0 - */ - renderWebGL: function () - { - } - -}); - -module.exports = Zone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BlendModes = require('../../renderer/BlendModes'); +var Circle = require('../../geom/circle/Circle'); +var CircleContains = require('../../geom/circle/Contains'); +var Class = require('../../utils/Class'); +var Components = require('../components'); +var GameObject = require('../GameObject'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var RectangleContains = require('../../geom/rectangle/Contains'); + +/** + * @classdesc + * A Zone Game Object. + * + * A Zone is a non-rendering rectangular Game Object that has a position and size. + * It has no texture and never displays, but does live on the display list and + * can be moved, scaled and rotated like any other Game Object. + * + * Its primary use is for creating Drop Zones and Input Hit Areas and it has a couple of helper methods + * specifically for this. It is also useful for object overlap checks, or as a base for your own + * non-displaying Game Objects. + + * The default origin is 0.5, the center of the Zone, the same as with Game Objects. + * + * @class Zone + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.GameObjects + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Visible + * + * @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 {number} [width=1] - The width of the Game Object. + * @param {number} [height=1] - The height of the Game Object. + */ +var Zone = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Depth, + Components.GetBounds, + Components.Origin, + Components.Transform, + Components.ScrollFactor, + Components.Visible + ], + + initialize: + + function Zone (scene, x, y, width, height) + { + if (width === undefined) { width = 1; } + if (height === undefined) { height = width; } + + GameObject.call(this, scene, 'Zone'); + + this.setPosition(x, y); + + /** + * The native (un-scaled) width of this Game Object. + * + * @name Phaser.GameObjects.Zone#width + * @type {number} + * @since 3.0.0 + */ + this.width = width; + + /** + * The native (un-scaled) height of this Game Object. + * + * @name Phaser.GameObjects.Zone#height + * @type {number} + * @since 3.0.0 + */ + this.height = height; + + /** + * The Blend Mode of the Game Object. + * Although a Zone never renders, it still has a blend mode to allow it to fit seamlessly into + * display lists without causing a batch flush. + * + * @name Phaser.GameObjects.Zone#blendMode + * @type {integer} + * @since 3.0.0 + */ + this.blendMode = BlendModes.NORMAL; + + this.updateDisplayOrigin(); + }, + + /** + * The displayed width of this Game Object. + * This value takes into account the scale factor. + * + * @name Phaser.GameObjects.Zone#displayWidth + * @type {number} + * @since 3.0.0 + */ + displayWidth: { + + get: function () + { + return this.scaleX * this.width; + }, + + set: function (value) + { + this.scaleX = value / this.width; + } + + }, + + /** + * The displayed height of this Game Object. + * This value takes into account the scale factor. + * + * @name Phaser.GameObjects.Zone#displayHeight + * @type {number} + * @since 3.0.0 + */ + displayHeight: { + + get: function () + { + return this.scaleY * this.height; + }, + + set: function (value) + { + this.scaleY = value / this.height; + } + + }, + + /** + * Sets the size of this Game Object. + * + * @method Phaser.GameObjects.Zone#setSize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * @param {boolean} [resizeInput=true] - If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. + * + * @return {this} This Game Object. + */ + setSize: function (width, height, resizeInput) + { + if (resizeInput === undefined) { resizeInput = true; } + + this.width = width; + this.height = height; + + this.updateDisplayOrigin(); + + var input = this.input; + + if (resizeInput && input && !input.customHitArea) + { + input.hitArea.width = width; + input.hitArea.height = height; + } + + return this; + }, + + /** + * Sets the display size of this Game Object. + * Calling this will adjust the scale. + * + * @method Phaser.GameObjects.Zone#setDisplaySize + * @since 3.0.0 + * + * @param {number} width - The width of this Game Object. + * @param {number} height - The height of this Game Object. + * + * @return {this} This Game Object. + */ + setDisplaySize: function (width, height) + { + this.displayWidth = width; + this.displayHeight = height; + + return this; + }, + + /** + * Sets this Zone to be a Circular Drop Zone. + * The circle is centered on this Zones `x` and `y` coordinates. + * + * @method Phaser.GameObjects.Zone#setCircleDropZone + * @since 3.0.0 + * + * @param {number} radius - The radius of the Circle that will form the Drop Zone. + * + * @return {this} This Game Object. + */ + setCircleDropZone: function (radius) + { + return this.setDropZone(new Circle(0, 0, radius), CircleContains); + }, + + /** + * Sets this Zone to be a Rectangle Drop Zone. + * The rectangle is centered on this Zones `x` and `y` coordinates. + * + * @method Phaser.GameObjects.Zone#setRectangleDropZone + * @since 3.0.0 + * + * @param {number} width - The width of the rectangle drop zone. + * @param {number} height - The height of the rectangle drop zone. + * + * @return {this} This Game Object. + */ + setRectangleDropZone: function (width, height) + { + return this.setDropZone(new Rectangle(0, 0, width, height), RectangleContains); + }, + + /** + * Allows you to define your own Geometry shape to be used as a Drop Zone. + * + * @method Phaser.GameObjects.Zone#setDropZone + * @since 3.0.0 + * + * @param {object} shape - A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. + * @param {Phaser.Types.Input.HitAreaCallback} callback - A function that will return `true` if the given x/y coords it is sent are within the shape. + * + * @return {this} This Game Object. + */ + setDropZone: function (shape, callback) + { + if (shape === undefined) + { + this.setRectangleDropZone(this.width, this.height); + } + else if (!this.input) + { + this.setInteractive(shape, callback, true); + } + + return this; + }, + + /** + * A NOOP method so you can pass a Zone to a Container. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Zone#setAlpha + * @private + * @since 3.11.0 + */ + setAlpha: function () + { + }, + + /** + * A NOOP method so you can pass a Zone to a Container in Canvas. + * Calling this method will do nothing. It is intentionally empty. + * + * @method Phaser.GameObjects.Zone#setBlendMode + * @private + * @since 3.16.2 + */ + setBlendMode: function () + { + }, + + /** + * A Zone does not render. + * + * @method Phaser.GameObjects.Zone#renderCanvas + * @private + * @since 3.0.0 + */ + renderCanvas: function () + { + }, + + /** + * A Zone does not render. + * + * @method Phaser.GameObjects.Zone#renderWebGL + * @private + * @since 3.0.0 + */ + renderWebGL: function () + { + } + +}); + +module.exports = Zone; diff --git a/src/gameobjects/zone/ZoneCreator.js b/src/gameobjects/zone/ZoneCreator.js index 2b2ba09da..a1ede8712 100644 --- a/src/gameobjects/zone/ZoneCreator.js +++ b/src/gameobjects/zone/ZoneCreator.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectCreator = require('../GameObjectCreator'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var Zone = require('./Zone'); - -/** - * Creates a new Zone Game Object and returns it. - * - * Note: This method will only be available if the Zone Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#zone - * @since 3.0.0 - * - * @param {object} config - The configuration object this Game Object will use to create itself. - * - * @return {Phaser.GameObjects.Zone} The Game Object that was created. - */ -GameObjectCreator.register('zone', function (config) -{ - var x = GetAdvancedValue(config, 'x', 0); - var y = GetAdvancedValue(config, 'y', 0); - var width = GetAdvancedValue(config, 'width', 1); - var height = GetAdvancedValue(config, 'height', width); - - return new Zone(this.scene, x, y, width, height); -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = require('../GameObjectCreator'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var Zone = require('./Zone'); + +/** + * Creates a new Zone Game Object and returns it. + * + * Note: This method will only be available if the Zone Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#zone + * @since 3.0.0 + * + * @param {object} config - The configuration object this Game Object will use to create itself. + * + * @return {Phaser.GameObjects.Zone} The Game Object that was created. + */ +GameObjectCreator.register('zone', function (config) +{ + var x = GetAdvancedValue(config, 'x', 0); + var y = GetAdvancedValue(config, 'y', 0); + var width = GetAdvancedValue(config, 'width', 1); + var height = GetAdvancedValue(config, 'height', width); + + return new Zone(this.scene, x, y, width, height); +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. diff --git a/src/gameobjects/zone/ZoneFactory.js b/src/gameobjects/zone/ZoneFactory.js index b8b6d5d24..2339650b9 100644 --- a/src/gameobjects/zone/ZoneFactory.js +++ b/src/gameobjects/zone/ZoneFactory.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Zone = require('./Zone'); -var GameObjectFactory = require('../GameObjectFactory'); - -/** - * Creates a new Zone Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Zone Game Object has been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#zone - * @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 {number} width - The width of the Game Object. - * @param {number} height - The height of the Game Object. - * - * @return {Phaser.GameObjects.Zone} The Game Object that was created. - */ -GameObjectFactory.register('zone', function (x, y, width, height) -{ - return this.displayList.add(new Zone(this.scene, x, y, width, height)); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Zone = require('./Zone'); +var GameObjectFactory = require('../GameObjectFactory'); + +/** + * Creates a new Zone Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Zone Game Object has been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#zone + * @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 {number} width - The width of the Game Object. + * @param {number} height - The height of the Game Object. + * + * @return {Phaser.GameObjects.Zone} The Game Object that was created. + */ +GameObjectFactory.register('zone', function (x, y, width, height) +{ + return this.displayList.add(new Zone(this.scene, x, y, width, height)); +}); + +// 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 diff --git a/src/geom/circle/Area.js b/src/geom/circle/Area.js index be2d4887c..dc7997b72 100644 --- a/src/geom/circle/Area.js +++ b/src/geom/circle/Area.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the area of the circle. - * - * @function Phaser.Geom.Circle.Area - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The Circle to get the area of. - * - * @return {number} The area of the Circle. - */ -var Area = function (circle) -{ - return (circle.radius > 0) ? Math.PI * circle.radius * circle.radius : 0; -}; - -module.exports = Area; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the area of the circle. + * + * @function Phaser.Geom.Circle.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the area of. + * + * @return {number} The area of the Circle. + */ +var Area = function (circle) +{ + return (circle.radius > 0) ? Math.PI * circle.radius * circle.radius : 0; +}; + +module.exports = Area; diff --git a/src/geom/circle/Circle.js b/src/geom/circle/Circle.js index 34ca17847..0205e24b5 100644 --- a/src/geom/circle/Circle.js +++ b/src/geom/circle/Circle.js @@ -1,369 +1,369 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Contains = require('./Contains'); -var GetPoint = require('./GetPoint'); -var GetPoints = require('./GetPoints'); -var GEOM_CONST = require('../const'); -var Random = require('./Random'); - -/** - * @classdesc - * A Circle object. - * - * This is a geometry object, containing numerical values and related methods to inspect and modify them. - * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. - * To render a Circle you should look at the capabilities of the Graphics class. - * - * @class Circle - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {number} [x=0] - The x position of the center of the circle. - * @param {number} [y=0] - The y position of the center of the circle. - * @param {number} [radius=0] - The radius of the circle. - */ -var Circle = new Class({ - - initialize: - - function Circle (x, y, radius) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (radius === undefined) { radius = 0; } - - /** - * The geometry constant type of this object: `GEOM_CONST.CIRCLE`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Circle#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.CIRCLE; - - /** - * The x position of the center of the circle. - * - * @name Phaser.Geom.Circle#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = x; - - /** - * The y position of the center of the circle. - * - * @name Phaser.Geom.Circle#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = y; - - /** - * The internal radius of the circle. - * - * @name Phaser.Geom.Circle#_radius - * @type {number} - * @private - * @since 3.0.0 - */ - this._radius = radius; - - /** - * The internal diameter of the circle. - * - * @name Phaser.Geom.Circle#_diameter - * @type {number} - * @private - * @since 3.0.0 - */ - this._diameter = radius * 2; - }, - - /** - * Check to see if the Circle contains the given x / y coordinates. - * - * @method Phaser.Geom.Circle#contains - * @since 3.0.0 - * - * @param {number} x - The x coordinate to check within the circle. - * @param {number} y - The y coordinate to check within the circle. - * - * @return {boolean} True if the coordinates are within the circle, otherwise false. - */ - contains: function (x, y) - { - return Contains(this, x, y); - }, - - /** - * 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.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle. - */ - getPoint: function (position, point) - { - return GetPoint(this, position, point); - }, - - /** - * 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.Geom.Point[]} O - [output,$return] - * - * @param {integer} 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 circle and dividing it by the stepRate. - * @param {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. - * - * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the circle. - */ - getPoints: function (quantity, stepRate, output) - { - return GetPoints(this, quantity, stepRate, output); - }, - - /** - * Returns a uniformly distributed random point from anywhere within the Circle. - * - * @method Phaser.Geom.Circle#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {(Phaser.Geom.Point|object)} [point] - A Point or point-like object to set the random `x` and `y` values in. - * - * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. - */ - getRandomPoint: function (point) - { - return Random(this, point); - }, - - /** - * Sets the x, y and radius of this circle. - * - * @method Phaser.Geom.Circle#setTo - * @since 3.0.0 - * - * @param {number} [x=0] - The x position of the center of the circle. - * @param {number} [y=0] - The y position of the center of the circle. - * @param {number} [radius=0] - The radius of the circle. - * - * @return {Phaser.Geom.Circle} This Circle object. - */ - setTo: function (x, y, radius) - { - this.x = x; - this.y = y; - this._radius = radius; - this._diameter = radius * 2; - - return this; - }, - - /** - * Sets this Circle to be empty with a radius of zero. - * Does not change its position. - * - * @method Phaser.Geom.Circle#setEmpty - * @since 3.0.0 - * - * @return {Phaser.Geom.Circle} This Circle object. - */ - setEmpty: function () - { - this._radius = 0; - this._diameter = 0; - - return this; - }, - - /** - * Sets the position of this Circle. - * - * @method Phaser.Geom.Circle#setPosition - * @since 3.0.0 - * - * @param {number} [x=0] - The x position of the center of the circle. - * @param {number} [y=0] - The y position of the center of the circle. - * - * @return {Phaser.Geom.Circle} This Circle object. - */ - setPosition: function (x, y) - { - if (y === undefined) { y = x; } - - this.x = x; - this.y = y; - - return this; - }, - - /** - * Checks to see if the Circle is empty: has a radius of zero. - * - * @method Phaser.Geom.Circle#isEmpty - * @since 3.0.0 - * - * @return {boolean} True if the Circle is empty, otherwise false. - */ - isEmpty: function () - { - return (this._radius <= 0); - }, - - /** - * The radius of the Circle. - * - * @name Phaser.Geom.Circle#radius - * @type {number} - * @since 3.0.0 - */ - radius: { - - get: function () - { - return this._radius; - }, - - set: function (value) - { - this._radius = value; - this._diameter = value * 2; - } - - }, - - /** - * The diameter of the Circle. - * - * @name Phaser.Geom.Circle#diameter - * @type {number} - * @since 3.0.0 - */ - diameter: { - - get: function () - { - return this._diameter; - }, - - set: function (value) - { - this._diameter = value; - this._radius = value * 0.5; - } - - }, - - /** - * The left position of the Circle. - * - * @name Phaser.Geom.Circle#left - * @type {number} - * @since 3.0.0 - */ - left: { - - get: function () - { - return this.x - this._radius; - }, - - set: function (value) - { - this.x = value + this._radius; - } - - }, - - /** - * The right position of the Circle. - * - * @name Phaser.Geom.Circle#right - * @type {number} - * @since 3.0.0 - */ - right: { - - get: function () - { - return this.x + this._radius; - }, - - set: function (value) - { - this.x = value - this._radius; - } - - }, - - /** - * The top position of the Circle. - * - * @name Phaser.Geom.Circle#top - * @type {number} - * @since 3.0.0 - */ - top: { - - get: function () - { - return this.y - this._radius; - }, - - set: function (value) - { - this.y = value + this._radius; - } - - }, - - /** - * The bottom position of the Circle. - * - * @name Phaser.Geom.Circle#bottom - * @type {number} - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return this.y + this._radius; - }, - - set: function (value) - { - this.y = value - this._radius; - } - - } - -}); - -module.exports = Circle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Contains = require('./Contains'); +var GetPoint = require('./GetPoint'); +var GetPoints = require('./GetPoints'); +var GEOM_CONST = require('../const'); +var Random = require('./Random'); + +/** + * @classdesc + * A Circle object. + * + * This is a geometry object, containing numerical values and related methods to inspect and modify them. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render a Circle you should look at the capabilities of the Graphics class. + * + * @class Circle + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the circle. + * @param {number} [y=0] - The y position of the center of the circle. + * @param {number} [radius=0] - The radius of the circle. + */ +var Circle = new Class({ + + initialize: + + function Circle (x, y, radius) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (radius === undefined) { radius = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.CIRCLE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Circle#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.CIRCLE; + + /** + * The x position of the center of the circle. + * + * @name Phaser.Geom.Circle#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The y position of the center of the circle. + * + * @name Phaser.Geom.Circle#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + + /** + * The internal radius of the circle. + * + * @name Phaser.Geom.Circle#_radius + * @type {number} + * @private + * @since 3.0.0 + */ + this._radius = radius; + + /** + * The internal diameter of the circle. + * + * @name Phaser.Geom.Circle#_diameter + * @type {number} + * @private + * @since 3.0.0 + */ + this._diameter = radius * 2; + }, + + /** + * Check to see if the Circle contains the given x / y coordinates. + * + * @method Phaser.Geom.Circle#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check within the circle. + * @param {number} y - The y coordinate to check within the circle. + * + * @return {boolean} True if the coordinates are within the circle, otherwise false. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * 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.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle. + */ + getPoint: function (position, point) + { + return GetPoint(this, position, point); + }, + + /** + * 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 circle and dividing it by the stepRate. + * @param {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the circle. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a uniformly distributed random point from anywhere within the Circle. + * + * @method Phaser.Geom.Circle#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {(Phaser.Geom.Point|object)} [point] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets the x, y and radius of this circle. + * + * @method Phaser.Geom.Circle#setTo + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the circle. + * @param {number} [y=0] - The y position of the center of the circle. + * @param {number} [radius=0] - The radius of the circle. + * + * @return {Phaser.Geom.Circle} This Circle object. + */ + setTo: function (x, y, radius) + { + this.x = x; + this.y = y; + this._radius = radius; + this._diameter = radius * 2; + + return this; + }, + + /** + * Sets this Circle to be empty with a radius of zero. + * Does not change its position. + * + * @method Phaser.Geom.Circle#setEmpty + * @since 3.0.0 + * + * @return {Phaser.Geom.Circle} This Circle object. + */ + setEmpty: function () + { + this._radius = 0; + this._diameter = 0; + + return this; + }, + + /** + * Sets the position of this Circle. + * + * @method Phaser.Geom.Circle#setPosition + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the circle. + * @param {number} [y=0] - The y position of the center of the circle. + * + * @return {Phaser.Geom.Circle} This Circle object. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Checks to see if the Circle is empty: has a radius of zero. + * + * @method Phaser.Geom.Circle#isEmpty + * @since 3.0.0 + * + * @return {boolean} True if the Circle is empty, otherwise false. + */ + isEmpty: function () + { + return (this._radius <= 0); + }, + + /** + * The radius of the Circle. + * + * @name Phaser.Geom.Circle#radius + * @type {number} + * @since 3.0.0 + */ + radius: { + + get: function () + { + return this._radius; + }, + + set: function (value) + { + this._radius = value; + this._diameter = value * 2; + } + + }, + + /** + * The diameter of the Circle. + * + * @name Phaser.Geom.Circle#diameter + * @type {number} + * @since 3.0.0 + */ + diameter: { + + get: function () + { + return this._diameter; + }, + + set: function (value) + { + this._diameter = value; + this._radius = value * 0.5; + } + + }, + + /** + * The left position of the Circle. + * + * @name Phaser.Geom.Circle#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.x - this._radius; + }, + + set: function (value) + { + this.x = value + this._radius; + } + + }, + + /** + * The right position of the Circle. + * + * @name Phaser.Geom.Circle#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.x + this._radius; + }, + + set: function (value) + { + this.x = value - this._radius; + } + + }, + + /** + * The top position of the Circle. + * + * @name Phaser.Geom.Circle#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.y - this._radius; + }, + + set: function (value) + { + this.y = value + this._radius; + } + + }, + + /** + * The bottom position of the Circle. + * + * @name Phaser.Geom.Circle#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.y + this._radius; + }, + + set: function (value) + { + this.y = value - this._radius; + } + + } + +}); + +module.exports = Circle; diff --git a/src/geom/circle/Circumference.js b/src/geom/circle/Circumference.js index 73044976d..18caba664 100644 --- a/src/geom/circle/Circumference.js +++ b/src/geom/circle/Circumference.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the circumference of the given Circle. - * - * @function Phaser.Geom.Circle.Circumference - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The Circle to get the circumference of. - * - * @return {number} The circumference of the Circle. - */ -var Circumference = function (circle) -{ - return 2 * (Math.PI * circle.radius); -}; - -module.exports = Circumference; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the circumference of the given Circle. + * + * @function Phaser.Geom.Circle.Circumference + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the circumference of. + * + * @return {number} The circumference of the Circle. + */ +var Circumference = function (circle) +{ + return 2 * (Math.PI * circle.radius); +}; + +module.exports = Circumference; diff --git a/src/geom/circle/CircumferencePoint.js b/src/geom/circle/CircumferencePoint.js index 8866ceaa0..11785f1d4 100644 --- a/src/geom/circle/CircumferencePoint.js +++ b/src/geom/circle/CircumferencePoint.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a Point 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.Geom.Point} 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.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference. - */ -var CircumferencePoint = function (circle, angle, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = circle.x + (circle.radius * Math.cos(angle)); - out.y = circle.y + (circle.radius * Math.sin(angle)); - - return out; -}; - -module.exports = CircumferencePoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a Point 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.Geom.Point} 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.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference. + */ +var CircumferencePoint = function (circle, angle, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = circle.x + (circle.radius * Math.cos(angle)); + out.y = circle.y + (circle.radius * Math.sin(angle)); + + return out; +}; + +module.exports = CircumferencePoint; diff --git a/src/geom/circle/Clone.js b/src/geom/circle/Clone.js index c2a010f99..172ea00fb 100644 --- a/src/geom/circle/Clone.js +++ b/src/geom/circle/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Circle = require('./Circle'); - -/** - * 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. - */ -var Clone = function (source) -{ - return new Circle(source.x, source.y, source.radius); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = require('./Circle'); + +/** + * 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. + */ +var Clone = function (source) +{ + return new Circle(source.x, source.y, source.radius); +}; + +module.exports = Clone; diff --git a/src/geom/circle/Contains.js b/src/geom/circle/Contains.js index 18ea913c9..5cb6e53de 100644 --- a/src/geom/circle/Contains.js +++ b/src/geom/circle/Contains.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check to see if the Circle contains the given x / y coordinates. - * - * @function Phaser.Geom.Circle.Contains - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The Circle to check. - * @param {number} x - The x coordinate to check within the circle. - * @param {number} y - The y coordinate to check within the circle. - * - * @return {boolean} True if the coordinates are within the circle, otherwise false. - */ -var Contains = function (circle, x, y) -{ - // Check if x/y are within the bounds first - if (circle.radius > 0 && x >= circle.left && x <= circle.right && y >= circle.top && y <= circle.bottom) - { - var dx = (circle.x - x) * (circle.x - x); - var dy = (circle.y - y) * (circle.y - y); - - return (dx + dy) <= (circle.radius * circle.radius); - } - else - { - return false; - } -}; - -module.exports = Contains; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check to see if the Circle contains the given x / y coordinates. + * + * @function Phaser.Geom.Circle.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to check. + * @param {number} x - The x coordinate to check within the circle. + * @param {number} y - The y coordinate to check within the circle. + * + * @return {boolean} True if the coordinates are within the circle, otherwise false. + */ +var Contains = function (circle, x, y) +{ + // Check if x/y are within the bounds first + if (circle.radius > 0 && x >= circle.left && x <= circle.right && y >= circle.top && y <= circle.bottom) + { + var dx = (circle.x - x) * (circle.x - x); + var dy = (circle.y - y) * (circle.y - y); + + return (dx + dy) <= (circle.radius * circle.radius); + } + else + { + return false; + } +}; + +module.exports = Contains; diff --git a/src/geom/circle/ContainsPoint.js b/src/geom/circle/ContainsPoint.js index 940c86f14..4a82a1ef6 100644 --- a/src/geom/circle/ContainsPoint.js +++ b/src/geom/circle/ContainsPoint.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Check to see if the Circle contains the given Point object. - * - * @function Phaser.Geom.Circle.ContainsPoint - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The Circle to check. - * @param {(Phaser.Geom.Point|object)} point - The Point object to check if it's within the Circle or not. - * - * @return {boolean} True if the Point coordinates are within the circle, otherwise false. - */ -var ContainsPoint = function (circle, point) -{ - return Contains(circle, point.x, point.y); -}; - -module.exports = ContainsPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Check to see if the Circle contains the given Point object. + * + * @function Phaser.Geom.Circle.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to check. + * @param {(Phaser.Geom.Point|object)} point - The Point object to check if it's within the Circle or not. + * + * @return {boolean} True if the Point coordinates are within the circle, otherwise false. + */ +var ContainsPoint = function (circle, point) +{ + return Contains(circle, point.x, point.y); +}; + +module.exports = ContainsPoint; diff --git a/src/geom/circle/ContainsRect.js b/src/geom/circle/ContainsRect.js index f428c2b54..41c9e059c 100644 --- a/src/geom/circle/ContainsRect.js +++ b/src/geom/circle/ContainsRect.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Check to see if the Circle contains all four points of the given Rectangle object. - * - * @function Phaser.Geom.Circle.ContainsRect - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The Circle to check. - * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle object to check if it's within the Circle or not. - * - * @return {boolean} True if all of the Rectangle coordinates are within the circle, otherwise false. - */ -var ContainsRect = function (circle, rect) -{ - return ( - Contains(circle, rect.x, rect.y) && - Contains(circle, rect.right, rect.y) && - Contains(circle, rect.x, rect.bottom) && - Contains(circle, rect.right, rect.bottom) - ); -}; - -module.exports = ContainsRect; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Check to see if the Circle contains all four points of the given Rectangle object. + * + * @function Phaser.Geom.Circle.ContainsRect + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to check. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle object to check if it's within the Circle or not. + * + * @return {boolean} True if all of the Rectangle coordinates are within the circle, otherwise false. + */ +var ContainsRect = function (circle, rect) +{ + return ( + Contains(circle, rect.x, rect.y) && + Contains(circle, rect.right, rect.y) && + Contains(circle, rect.x, rect.bottom) && + Contains(circle, rect.right, rect.bottom) + ); +}; + +module.exports = ContainsRect; diff --git a/src/geom/circle/CopyFrom.js b/src/geom/circle/CopyFrom.js index fad7c223e..3417cc2eb 100644 --- a/src/geom/circle/CopyFrom.js +++ b/src/geom/circle/CopyFrom.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Copies the `x`, `y` and `radius` properties from the `source` Circle - * into the given `dest` Circle, then returns the `dest` Circle. - * - * @function Phaser.Geom.Circle.CopyFrom - * @since 3.0.0 - * - * @generic {Phaser.Geom.Circle} O - [dest,$return] - * - * @param {Phaser.Geom.Circle} source - The source Circle to copy the values from. - * @param {Phaser.Geom.Circle} dest - The destination Circle to copy the values to. - * - * @return {Phaser.Geom.Circle} The destination Circle. - */ -var CopyFrom = function (source, dest) -{ - return dest.setTo(source.x, source.y, source.radius); -}; - -module.exports = CopyFrom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copies the `x`, `y` and `radius` properties from the `source` Circle + * into the given `dest` Circle, then returns the `dest` Circle. + * + * @function Phaser.Geom.Circle.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Circle} O - [dest,$return] + * + * @param {Phaser.Geom.Circle} source - The source Circle to copy the values from. + * @param {Phaser.Geom.Circle} dest - The destination Circle to copy the values to. + * + * @return {Phaser.Geom.Circle} The destination Circle. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y, source.radius); +}; + +module.exports = CopyFrom; diff --git a/src/geom/circle/Equals.js b/src/geom/circle/Equals.js index bac237bad..e41f9677d 100644 --- a/src/geom/circle/Equals.js +++ b/src/geom/circle/Equals.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compares the `x`, `y` and `radius` properties of the two given Circles. - * Returns `true` if they all match, otherwise returns `false`. - * - * @function Phaser.Geom.Circle.Equals - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The first Circle to compare. - * @param {Phaser.Geom.Circle} toCompare - The second Circle to compare. - * - * @return {boolean} `true` if the two Circles equal each other, otherwise `false`. - */ -var Equals = function (circle, toCompare) -{ - return ( - circle.x === toCompare.x && - circle.y === toCompare.y && - circle.radius === toCompare.radius - ); -}; - -module.exports = Equals; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compares the `x`, `y` and `radius` properties of the two given Circles. + * Returns `true` if they all match, otherwise returns `false`. + * + * @function Phaser.Geom.Circle.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The first Circle to compare. + * @param {Phaser.Geom.Circle} toCompare - The second Circle to compare. + * + * @return {boolean} `true` if the two Circles equal each other, otherwise `false`. + */ +var Equals = function (circle, toCompare) +{ + return ( + circle.x === toCompare.x && + circle.y === toCompare.y && + circle.radius === toCompare.radius + ); +}; + +module.exports = Equals; diff --git a/src/geom/circle/GetBounds.js b/src/geom/circle/GetBounds.js index c234217bf..f0d24931c 100644 --- a/src/geom/circle/GetBounds.js +++ b/src/geom/circle/GetBounds.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('../rectangle/Rectangle'); - -/** - * Returns the bounds of the Circle object. - * - * @function Phaser.Geom.Circle.GetBounds - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {Phaser.Geom.Circle} circle - The Circle to get the bounds from. - * @param {(Phaser.Geom.Rectangle|object)} [out] - A Rectangle, or rectangle-like object, to store the circle bounds in. If not given a new Rectangle will be created. - * - * @return {(Phaser.Geom.Rectangle|object)} The Rectangle object containing the Circles bounds. - */ -var GetBounds = function (circle, out) -{ - if (out === undefined) { out = new Rectangle(); } - - out.x = circle.left; - out.y = circle.top; - out.width = circle.diameter; - out.height = circle.diameter; - - return out; -}; - -module.exports = GetBounds; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('../rectangle/Rectangle'); + +/** + * Returns the bounds of the Circle object. + * + * @function Phaser.Geom.Circle.GetBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the bounds from. + * @param {(Phaser.Geom.Rectangle|object)} [out] - A Rectangle, or rectangle-like object, to store the circle bounds in. If not given a new Rectangle will be created. + * + * @return {(Phaser.Geom.Rectangle|object)} The Rectangle object containing the Circles bounds. + */ +var GetBounds = function (circle, out) +{ + if (out === undefined) { out = new Rectangle(); } + + out.x = circle.left; + out.y = circle.top; + out.width = circle.diameter; + out.height = circle.diameter; + + return out; +}; + +module.exports = GetBounds; diff --git a/src/geom/circle/GetPoint.js b/src/geom/circle/GetPoint.js index 698db939a..cd4ff0028 100644 --- a/src/geom/circle/GetPoint.js +++ b/src/geom/circle/GetPoint.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CircumferencePoint = require('./CircumferencePoint'); -var FromPercent = require('../../math/FromPercent'); -var MATH_CONST = require('../../math/const'); -var Point = require('../point/Point'); - -/** - * 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. - * - * @function Phaser.Geom.Circle.GetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle. - */ -var GetPoint = function (circle, position, out) -{ - if (out === undefined) { out = new Point(); } - - var angle = FromPercent(position, 0, MATH_CONST.PI2); - - return CircumferencePoint(circle, angle, out); -}; - -module.exports = GetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CircumferencePoint = require('./CircumferencePoint'); +var FromPercent = require('../../math/FromPercent'); +var MATH_CONST = require('../../math/const'); +var Point = require('../point/Point'); + +/** + * 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. + * + * @function Phaser.Geom.Circle.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle. + */ +var GetPoint = function (circle, position, out) +{ + if (out === undefined) { out = new Point(); } + + var angle = FromPercent(position, 0, MATH_CONST.PI2); + + return CircumferencePoint(circle, angle, out); +}; + +module.exports = GetPoint; diff --git a/src/geom/circle/GetPoints.js b/src/geom/circle/GetPoints.js index 34974cbbb..8cebabf32 100644 --- a/src/geom/circle/GetPoints.js +++ b/src/geom/circle/GetPoints.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Circumference = require('./Circumference'); -var CircumferencePoint = require('./CircumferencePoint'); -var FromPercent = require('../../math/FromPercent'); -var MATH_CONST = require('../../math/const'); - -/** - * 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. - * - * @function Phaser.Geom.Circle.GetPoints - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The Circle to get the points from. - * @param {integer} 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 circle 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.Geom.Point[]} An array of Point objects pertaining to the points around the circumference of the circle. - */ -var GetPoints = function (circle, quantity, stepRate, out) -{ - if (out === undefined) { out = []; } - - // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!quantity) - { - quantity = Circumference(circle) / stepRate; - } - - for (var i = 0; i < quantity; i++) - { - var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); - - out.push(CircumferencePoint(circle, angle)); - } - - return out; -}; - -module.exports = GetPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circumference = require('./Circumference'); +var CircumferencePoint = require('./CircumferencePoint'); +var FromPercent = require('../../math/FromPercent'); +var MATH_CONST = require('../../math/const'); + +/** + * 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. + * + * @function Phaser.Geom.Circle.GetPoints + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The Circle to get the points from. + * @param {integer} 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 circle 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.Geom.Point[]} An array of Point objects pertaining to the points around the circumference of the circle. + */ +var GetPoints = function (circle, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Circumference(circle) / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); + + out.push(CircumferencePoint(circle, angle)); + } + + return out; +}; + +module.exports = GetPoints; diff --git a/src/geom/circle/Offset.js b/src/geom/circle/Offset.js index 8bc4175d5..0c25f9740 100644 --- a/src/geom/circle/Offset.js +++ b/src/geom/circle/Offset.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Offsets the Circle by the values given. - * - * @function Phaser.Geom.Circle.Offset - * @since 3.0.0 - * - * @generic {Phaser.Geom.Circle} O - [circle,$return] - * - * @param {Phaser.Geom.Circle} circle - The Circle to be offset (translated.) - * @param {number} x - The amount to horizontally offset the Circle by. - * @param {number} y - The amount to vertically offset the Circle by. - * - * @return {Phaser.Geom.Circle} The Circle that was offset. - */ -var Offset = function (circle, x, y) -{ - circle.x += x; - circle.y += y; - - return circle; -}; - -module.exports = Offset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Circle by the values given. + * + * @function Phaser.Geom.Circle.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Circle} O - [circle,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to be offset (translated.) + * @param {number} x - The amount to horizontally offset the Circle by. + * @param {number} y - The amount to vertically offset the Circle by. + * + * @return {Phaser.Geom.Circle} The Circle that was offset. + */ +var Offset = function (circle, x, y) +{ + circle.x += x; + circle.y += y; + + return circle; +}; + +module.exports = Offset; diff --git a/src/geom/circle/OffsetPoint.js b/src/geom/circle/OffsetPoint.js index de9938859..72430c9fd 100644 --- a/src/geom/circle/OffsetPoint.js +++ b/src/geom/circle/OffsetPoint.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Offsets the Circle by the values given in the `x` and `y` properties of the Point object. - * - * @function Phaser.Geom.Circle.OffsetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Circle} O - [circle,$return] - * - * @param {Phaser.Geom.Circle} circle - The Circle to be offset (translated.) - * @param {(Phaser.Geom.Point|object)} point - The Point object containing the values to offset the Circle by. - * - * @return {Phaser.Geom.Circle} The Circle that was offset. - */ -var OffsetPoint = function (circle, point) -{ - circle.x += point.x; - circle.y += point.y; - - return circle; -}; - -module.exports = OffsetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Circle by the values given in the `x` and `y` properties of the Point object. + * + * @function Phaser.Geom.Circle.OffsetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Circle} O - [circle,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to be offset (translated.) + * @param {(Phaser.Geom.Point|object)} point - The Point object containing the values to offset the Circle by. + * + * @return {Phaser.Geom.Circle} The Circle that was offset. + */ +var OffsetPoint = function (circle, point) +{ + circle.x += point.x; + circle.y += point.y; + + return circle; +}; + +module.exports = OffsetPoint; diff --git a/src/geom/circle/Random.js b/src/geom/circle/Random.js index e75218779..379aaadf0 100644 --- a/src/geom/circle/Random.js +++ b/src/geom/circle/Random.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a uniformly distributed random point from anywhere within the given Circle. - * - * @function Phaser.Geom.Circle.Random - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Circle} circle - The Circle to get a random point from. - * @param {(Phaser.Geom.Point|object)} [out] - A Point or point-like object to set the random `x` and `y` values in. - * - * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. - */ -var Random = function (circle, out) -{ - if (out === undefined) { out = new Point(); } - - var t = 2 * Math.PI * Math.random(); - var u = Math.random() + Math.random(); - var r = (u > 1) ? 2 - u : u; - var x = r * Math.cos(t); - var y = r * Math.sin(t); - - out.x = circle.x + (x * circle.radius); - out.y = circle.y + (y * circle.radius); - - return out; -}; - -module.exports = Random; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a uniformly distributed random point from anywhere within the given Circle. + * + * @function Phaser.Geom.Circle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Circle} circle - The Circle to get a random point from. + * @param {(Phaser.Geom.Point|object)} [out] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ +var Random = function (circle, out) +{ + if (out === undefined) { out = new Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = circle.x + (x * circle.radius); + out.y = circle.y + (y * circle.radius); + + return out; +}; + +module.exports = Random; diff --git a/src/geom/circle/index.js b/src/geom/circle/index.js index 2c47dc3a0..68305f177 100644 --- a/src/geom/circle/index.js +++ b/src/geom/circle/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Circle = require('./Circle'); - -Circle.Area = require('./Area'); -Circle.Circumference = require('./Circumference'); -Circle.CircumferencePoint = require('./CircumferencePoint'); -Circle.Clone = require('./Clone'); -Circle.Contains = require('./Contains'); -Circle.ContainsPoint = require('./ContainsPoint'); -Circle.ContainsRect = require('./ContainsRect'); -Circle.CopyFrom = require('./CopyFrom'); -Circle.Equals = require('./Equals'); -Circle.GetBounds = require('./GetBounds'); -Circle.GetPoint = require('./GetPoint'); -Circle.GetPoints = require('./GetPoints'); -Circle.Offset = require('./Offset'); -Circle.OffsetPoint = require('./OffsetPoint'); -Circle.Random = require('./Random'); - -module.exports = Circle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = require('./Circle'); + +Circle.Area = require('./Area'); +Circle.Circumference = require('./Circumference'); +Circle.CircumferencePoint = require('./CircumferencePoint'); +Circle.Clone = require('./Clone'); +Circle.Contains = require('./Contains'); +Circle.ContainsPoint = require('./ContainsPoint'); +Circle.ContainsRect = require('./ContainsRect'); +Circle.CopyFrom = require('./CopyFrom'); +Circle.Equals = require('./Equals'); +Circle.GetBounds = require('./GetBounds'); +Circle.GetPoint = require('./GetPoint'); +Circle.GetPoints = require('./GetPoints'); +Circle.Offset = require('./Offset'); +Circle.OffsetPoint = require('./OffsetPoint'); +Circle.Random = require('./Random'); + +module.exports = Circle; diff --git a/src/geom/const.js b/src/geom/const.js index 5988b0db2..a38d40829 100644 --- a/src/geom/const.js +++ b/src/geom/const.js @@ -1,74 +1,74 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GEOM_CONST = { - - /** - * A Circle Geometry object type. - * - * @name Phaser.Geom.CIRCLE - * @type {integer} - * @since 3.19.0 - */ - CIRCLE: 0, - - /** - * An Ellipse Geometry object type. - * - * @name Phaser.Geom.ELLIPSE - * @type {integer} - * @since 3.19.0 - */ - ELLIPSE: 1, - - /** - * A Line Geometry object type. - * - * @name Phaser.Geom.LINE - * @type {integer} - * @since 3.19.0 - */ - LINE: 2, - - /** - * A Point Geometry object type. - * - * @name Phaser.Geom.POINT - * @type {integer} - * @since 3.19.0 - */ - POINT: 3, - - /** - * A Polygon Geometry object type. - * - * @name Phaser.Geom.POLYGON - * @type {integer} - * @since 3.19.0 - */ - POLYGON: 4, - - /** - * A Rectangle Geometry object type. - * - * @name Phaser.Geom.RECTANGLE - * @type {integer} - * @since 3.19.0 - */ - RECTANGLE: 5, - - /** - * A Triangle Geometry object type. - * - * @name Phaser.Geom.TRIANGLE - * @type {integer} - * @since 3.19.0 - */ - TRIANGLE: 6 - -}; - -module.exports = GEOM_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GEOM_CONST = { + + /** + * A Circle Geometry object type. + * + * @name Phaser.Geom.CIRCLE + * @type {integer} + * @since 3.19.0 + */ + CIRCLE: 0, + + /** + * An Ellipse Geometry object type. + * + * @name Phaser.Geom.ELLIPSE + * @type {integer} + * @since 3.19.0 + */ + ELLIPSE: 1, + + /** + * A Line Geometry object type. + * + * @name Phaser.Geom.LINE + * @type {integer} + * @since 3.19.0 + */ + LINE: 2, + + /** + * A Point Geometry object type. + * + * @name Phaser.Geom.POINT + * @type {integer} + * @since 3.19.0 + */ + POINT: 3, + + /** + * A Polygon Geometry object type. + * + * @name Phaser.Geom.POLYGON + * @type {integer} + * @since 3.19.0 + */ + POLYGON: 4, + + /** + * A Rectangle Geometry object type. + * + * @name Phaser.Geom.RECTANGLE + * @type {integer} + * @since 3.19.0 + */ + RECTANGLE: 5, + + /** + * A Triangle Geometry object type. + * + * @name Phaser.Geom.TRIANGLE + * @type {integer} + * @since 3.19.0 + */ + TRIANGLE: 6 + +}; + +module.exports = GEOM_CONST; diff --git a/src/geom/ellipse/Area.js b/src/geom/ellipse/Area.js index bb5cb15b2..dcd5e46c4 100644 --- a/src/geom/ellipse/Area.js +++ b/src/geom/ellipse/Area.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the area of the Ellipse. - * - * @function Phaser.Geom.Ellipse.Area - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the area of. - * - * @return {number} The area of the Ellipse. - */ -var Area = function (ellipse) -{ - if (ellipse.isEmpty()) - { - return 0; - } - - // units squared - return (ellipse.getMajorRadius() * ellipse.getMinorRadius() * Math.PI); -}; - -module.exports = Area; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the area of the Ellipse. + * + * @function Phaser.Geom.Ellipse.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the area of. + * + * @return {number} The area of the Ellipse. + */ +var Area = function (ellipse) +{ + if (ellipse.isEmpty()) + { + return 0; + } + + // units squared + return (ellipse.getMajorRadius() * ellipse.getMinorRadius() * Math.PI); +}; + +module.exports = Area; diff --git a/src/geom/ellipse/Circumference.js b/src/geom/ellipse/Circumference.js index 75fe314c6..d865c0b79 100644 --- a/src/geom/ellipse/Circumference.js +++ b/src/geom/ellipse/Circumference.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the circumference of the given Ellipse. - * - * @function Phaser.Geom.Ellipse.Circumference - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the circumference of. - * - * @return {number} The circumference of th Ellipse. - */ -var Circumference = function (ellipse) -{ - var rx = ellipse.width / 2; - var ry = ellipse.height / 2; - var h = Math.pow((rx - ry), 2) / Math.pow((rx + ry), 2); - - return (Math.PI * (rx + ry)) * (1 + ((3 * h) / (10 + Math.sqrt(4 - (3 * h))))); -}; - -module.exports = Circumference; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the circumference of the given Ellipse. + * + * @function Phaser.Geom.Ellipse.Circumference + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the circumference of. + * + * @return {number} The circumference of th Ellipse. + */ +var Circumference = function (ellipse) +{ + var rx = ellipse.width / 2; + var ry = ellipse.height / 2; + var h = Math.pow((rx - ry), 2) / Math.pow((rx + ry), 2); + + return (Math.PI * (rx + ry)) * (1 + ((3 * h) / (10 + Math.sqrt(4 - (3 * h))))); +}; + +module.exports = Circumference; diff --git a/src/geom/ellipse/CircumferencePoint.js b/src/geom/ellipse/CircumferencePoint.js index a3ce6df65..1bf0344ec 100644 --- a/src/geom/ellipse/CircumferencePoint.js +++ b/src/geom/ellipse/CircumferencePoint.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a Point object 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.Geom.Point} 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.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference. - */ -var CircumferencePoint = function (ellipse, angle, out) -{ - if (out === undefined) { out = new Point(); } - - var halfWidth = ellipse.width / 2; - var halfHeight = ellipse.height / 2; - - out.x = ellipse.x + halfWidth * Math.cos(angle); - out.y = ellipse.y + halfHeight * Math.sin(angle); - - return out; -}; - -module.exports = CircumferencePoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a Point object 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.Geom.Point} 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.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference. + */ +var CircumferencePoint = function (ellipse, angle, out) +{ + if (out === undefined) { out = new Point(); } + + var halfWidth = ellipse.width / 2; + var halfHeight = ellipse.height / 2; + + out.x = ellipse.x + halfWidth * Math.cos(angle); + out.y = ellipse.y + halfHeight * Math.sin(angle); + + return out; +}; + +module.exports = CircumferencePoint; diff --git a/src/geom/ellipse/Clone.js b/src/geom/ellipse/Clone.js index 17657fd4f..d20e208c0 100644 --- a/src/geom/ellipse/Clone.js +++ b/src/geom/ellipse/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Ellipse = require('./Ellipse'); - -/** - * 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 a ellipse-like object, with x, y, width and height properties. - * - * @return {Phaser.Geom.Ellipse} A clone of the source Ellipse. - */ -var Clone = function (source) -{ - return new Ellipse(source.x, source.y, source.width, source.height); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Ellipse = require('./Ellipse'); + +/** + * 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 a ellipse-like object, with x, y, width and height properties. + * + * @return {Phaser.Geom.Ellipse} A clone of the source Ellipse. + */ +var Clone = function (source) +{ + return new Ellipse(source.x, source.y, source.width, source.height); +}; + +module.exports = Clone; diff --git a/src/geom/ellipse/Contains.js b/src/geom/ellipse/Contains.js index e0ace630d..632aeba63 100644 --- a/src/geom/ellipse/Contains.js +++ b/src/geom/ellipse/Contains.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check to see if the Ellipse contains the given x / y coordinates. - * - * @function Phaser.Geom.Ellipse.Contains - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. - * @param {number} x - The x coordinate to check within the ellipse. - * @param {number} y - The y coordinate to check within the ellipse. - * - * @return {boolean} True if the coordinates are within the ellipse, otherwise false. - */ -var Contains = function (ellipse, x, y) -{ - if (ellipse.width <= 0 || ellipse.height <= 0) - { - return false; - } - - // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 - var normx = ((x - ellipse.x) / ellipse.width); - var normy = ((y - ellipse.y) / ellipse.height); - - normx *= normx; - normy *= normy; - - return (normx + normy < 0.25); -}; - -module.exports = Contains; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check to see if the Ellipse contains the given x / y coordinates. + * + * @function Phaser.Geom.Ellipse.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. + * @param {number} x - The x coordinate to check within the ellipse. + * @param {number} y - The y coordinate to check within the ellipse. + * + * @return {boolean} True if the coordinates are within the ellipse, otherwise false. + */ +var Contains = function (ellipse, x, y) +{ + if (ellipse.width <= 0 || ellipse.height <= 0) + { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - ellipse.x) / ellipse.width); + var normy = ((y - ellipse.y) / ellipse.height); + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); +}; + +module.exports = Contains; diff --git a/src/geom/ellipse/ContainsPoint.js b/src/geom/ellipse/ContainsPoint.js index 4260d0ebb..859d00733 100644 --- a/src/geom/ellipse/ContainsPoint.js +++ b/src/geom/ellipse/ContainsPoint.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Check to see if the Ellipse contains the given Point object. - * - * @function Phaser.Geom.Ellipse.ContainsPoint - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. - * @param {(Phaser.Geom.Point|object)} point - The Point object to check if it's within the Circle or not. - * - * @return {boolean} True if the Point coordinates are within the circle, otherwise false. - */ -var ContainsPoint = function (ellipse, point) -{ - return Contains(ellipse, point.x, point.y); -}; - -module.exports = ContainsPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Check to see if the Ellipse contains the given Point object. + * + * @function Phaser.Geom.Ellipse.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. + * @param {(Phaser.Geom.Point|object)} point - The Point object to check if it's within the Circle or not. + * + * @return {boolean} True if the Point coordinates are within the circle, otherwise false. + */ +var ContainsPoint = function (ellipse, point) +{ + return Contains(ellipse, point.x, point.y); +}; + +module.exports = ContainsPoint; diff --git a/src/geom/ellipse/ContainsRect.js b/src/geom/ellipse/ContainsRect.js index f3427889a..a0533bd67 100644 --- a/src/geom/ellipse/ContainsRect.js +++ b/src/geom/ellipse/ContainsRect.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Check to see if the Ellipse contains all four points of the given Rectangle object. - * - * @function Phaser.Geom.Ellipse.ContainsRect - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. - * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle object to check if it's within the Ellipse or not. - * - * @return {boolean} True if all of the Rectangle coordinates are within the ellipse, otherwise false. - */ -var ContainsRect = function (ellipse, rect) -{ - return ( - Contains(ellipse, rect.x, rect.y) && - Contains(ellipse, rect.right, rect.y) && - Contains(ellipse, rect.x, rect.bottom) && - Contains(ellipse, rect.right, rect.bottom) - ); -}; - -module.exports = ContainsRect; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Check to see if the Ellipse contains all four points of the given Rectangle object. + * + * @function Phaser.Geom.Ellipse.ContainsRect + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to check. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle object to check if it's within the Ellipse or not. + * + * @return {boolean} True if all of the Rectangle coordinates are within the ellipse, otherwise false. + */ +var ContainsRect = function (ellipse, rect) +{ + return ( + Contains(ellipse, rect.x, rect.y) && + Contains(ellipse, rect.right, rect.y) && + Contains(ellipse, rect.x, rect.bottom) && + Contains(ellipse, rect.right, rect.bottom) + ); +}; + +module.exports = ContainsRect; diff --git a/src/geom/ellipse/CopyFrom.js b/src/geom/ellipse/CopyFrom.js index 6e0374235..bcc77bd0a 100644 --- a/src/geom/ellipse/CopyFrom.js +++ b/src/geom/ellipse/CopyFrom.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Copies the `x`, `y`, `width` and `height` properties from the `source` Ellipse - * into the given `dest` Ellipse, then returns the `dest` Ellipse. - * - * @function Phaser.Geom.Ellipse.CopyFrom - * @since 3.0.0 - * - * @generic {Phaser.Geom.Ellipse} O - [dest,$return] - * - * @param {Phaser.Geom.Ellipse} source - The source Ellipse to copy the values from. - * @param {Phaser.Geom.Ellipse} dest - The destination Ellipse to copy the values to. - * - * @return {Phaser.Geom.Ellipse} The destination Ellipse. - */ -var CopyFrom = function (source, dest) -{ - return dest.setTo(source.x, source.y, source.width, source.height); -}; - -module.exports = CopyFrom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copies the `x`, `y`, `width` and `height` properties from the `source` Ellipse + * into the given `dest` Ellipse, then returns the `dest` Ellipse. + * + * @function Phaser.Geom.Ellipse.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Ellipse} O - [dest,$return] + * + * @param {Phaser.Geom.Ellipse} source - The source Ellipse to copy the values from. + * @param {Phaser.Geom.Ellipse} dest - The destination Ellipse to copy the values to. + * + * @return {Phaser.Geom.Ellipse} The destination Ellipse. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y, source.width, source.height); +}; + +module.exports = CopyFrom; diff --git a/src/geom/ellipse/Ellipse.js b/src/geom/ellipse/Ellipse.js index ff6ec4fc5..a34525dbe 100644 --- a/src/geom/ellipse/Ellipse.js +++ b/src/geom/ellipse/Ellipse.js @@ -1,376 +1,376 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Contains = require('./Contains'); -var GetPoint = require('./GetPoint'); -var GetPoints = require('./GetPoints'); -var GEOM_CONST = require('../const'); -var Random = require('./Random'); - -/** - * @classdesc - * An Ellipse object. - * - * This is a geometry object, containing numerical values and related methods to inspect and modify them. - * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. - * To render an Ellipse you should look at the capabilities of the Graphics class. - * - * @class Ellipse - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {number} [x=0] - The x position of the center of the ellipse. - * @param {number} [y=0] - The y position of the center of the ellipse. - * @param {number} [width=0] - The width of the ellipse. - * @param {number} [height=0] - The height of the ellipse. - */ -var Ellipse = new Class({ - - initialize: - - function Ellipse (x, y, width, height) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 0; } - if (height === undefined) { height = 0; } - - /** - * The geometry constant type of this object: `GEOM_CONST.ELLIPSE`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Ellipse#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.ELLIPSE; - - /** - * The x position of the center of the ellipse. - * - * @name Phaser.Geom.Ellipse#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = x; - - /** - * The y position of the center of the ellipse. - * - * @name Phaser.Geom.Ellipse#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = y; - - /** - * The width of the ellipse. - * - * @name Phaser.Geom.Ellipse#width - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.width = width; - - /** - * The height of the ellipse. - * - * @name Phaser.Geom.Ellipse#height - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.height = height; - }, - - /** - * Check to see if the Ellipse contains the given x / y coordinates. - * - * @method Phaser.Geom.Ellipse#contains - * @since 3.0.0 - * - * @param {number} x - The x coordinate to check within the ellipse. - * @param {number} y - The y coordinate to check within the ellipse. - * - * @return {boolean} True if the coordinates are within the ellipse, otherwise false. - */ - contains: function (x, y) - { - return Contains(this, x, y); - }, - - /** - * Returns a Point 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 circle. - * - * @method Phaser.Geom.Ellipse#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the ellipse. - */ - getPoint: function (position, point) - { - return GetPoint(this, position, point); - }, - - /** - * Returns an array of Point 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.Geom.Point[]} O - [output,$return] - * - * @param {integer} 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 {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. - * - * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the ellipse. - */ - getPoints: function (quantity, stepRate, output) - { - return GetPoints(this, quantity, stepRate, output); - }, - - /** - * Returns a uniformly distributed random point from anywhere within the given Ellipse. - * - * @method Phaser.Geom.Ellipse#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {(Phaser.Geom.Point|object)} [point] - A Point or point-like object to set the random `x` and `y` values in. - * - * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. - */ - getRandomPoint: function (point) - { - return Random(this, point); - }, - - /** - * Sets the x, y, width and height of this ellipse. - * - * @method Phaser.Geom.Ellipse#setTo - * @since 3.0.0 - * - * @param {number} x - The x position of the center of the ellipse. - * @param {number} y - The y position of the center of the ellipse. - * @param {number} width - The width of the ellipse. - * @param {number} height - The height of the ellipse. - * - * @return {Phaser.Geom.Ellipse} This Ellipse object. - */ - setTo: function (x, y, width, height) - { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - - return this; - }, - - /** - * Sets this Ellipse to be empty with a width and height of zero. - * Does not change its position. - * - * @method Phaser.Geom.Ellipse#setEmpty - * @since 3.0.0 - * - * @return {Phaser.Geom.Ellipse} This Ellipse object. - */ - setEmpty: function () - { - this.width = 0; - this.height = 0; - - return this; - }, - - /** - * Sets the position of this Ellipse. - * - * @method Phaser.Geom.Ellipse#setPosition - * @since 3.0.0 - * - * @param {number} x - The x position of the center of the ellipse. - * @param {number} y - The y position of the center of the ellipse. - * - * @return {Phaser.Geom.Ellipse} This Ellipse object. - */ - setPosition: function (x, y) - { - if (y === undefined) { y = x; } - - this.x = x; - this.y = y; - - return this; - }, - - /** - * Sets the size of this Ellipse. - * Does not change its position. - * - * @method Phaser.Geom.Ellipse#setSize - * @since 3.0.0 - * - * @param {number} width - The width of the ellipse. - * @param {number} [height=width] - The height of the ellipse. - * - * @return {Phaser.Geom.Ellipse} This Ellipse object. - */ - setSize: function (width, height) - { - if (height === undefined) { height = width; } - - this.width = width; - this.height = height; - - return this; - }, - - /** - * Checks to see if the Ellipse is empty: has a width or height equal to zero. - * - * @method Phaser.Geom.Ellipse#isEmpty - * @since 3.0.0 - * - * @return {boolean} True if the Ellipse is empty, otherwise false. - */ - isEmpty: function () - { - return (this.width <= 0 || this.height <= 0); - }, - - /** - * Returns the minor radius of the ellipse. Also known as the Semi Minor Axis. - * - * @method Phaser.Geom.Ellipse#getMinorRadius - * @since 3.0.0 - * - * @return {number} The minor radius. - */ - getMinorRadius: function () - { - return Math.min(this.width, this.height) / 2; - }, - - /** - * Returns the major radius of the ellipse. Also known as the Semi Major Axis. - * - * @method Phaser.Geom.Ellipse#getMajorRadius - * @since 3.0.0 - * - * @return {number} The major radius. - */ - getMajorRadius: function () - { - return Math.max(this.width, this.height) / 2; - }, - - /** - * The left position of the Ellipse. - * - * @name Phaser.Geom.Ellipse#left - * @type {number} - * @since 3.0.0 - */ - left: { - - get: function () - { - return this.x - (this.width / 2); - }, - - set: function (value) - { - this.x = value + (this.width / 2); - } - - }, - - /** - * The right position of the Ellipse. - * - * @name Phaser.Geom.Ellipse#right - * @type {number} - * @since 3.0.0 - */ - right: { - - get: function () - { - return this.x + (this.width / 2); - }, - - set: function (value) - { - this.x = value - (this.width / 2); - } - - }, - - /** - * The top position of the Ellipse. - * - * @name Phaser.Geom.Ellipse#top - * @type {number} - * @since 3.0.0 - */ - top: { - - get: function () - { - return this.y - (this.height / 2); - }, - - set: function (value) - { - this.y = value + (this.height / 2); - } - - }, - - /** - * The bottom position of the Ellipse. - * - * @name Phaser.Geom.Ellipse#bottom - * @type {number} - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return this.y + (this.height / 2); - }, - - set: function (value) - { - this.y = value - (this.height / 2); - } - - } - -}); - -module.exports = Ellipse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Contains = require('./Contains'); +var GetPoint = require('./GetPoint'); +var GetPoints = require('./GetPoints'); +var GEOM_CONST = require('../const'); +var Random = require('./Random'); + +/** + * @classdesc + * An Ellipse object. + * + * This is a geometry object, containing numerical values and related methods to inspect and modify them. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render an Ellipse you should look at the capabilities of the Graphics class. + * + * @class Ellipse + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The x position of the center of the ellipse. + * @param {number} [y=0] - The y position of the center of the ellipse. + * @param {number} [width=0] - The width of the ellipse. + * @param {number} [height=0] - The height of the ellipse. + */ +var Ellipse = new Class({ + + initialize: + + function Ellipse (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.ELLIPSE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Ellipse#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.ELLIPSE; + + /** + * The x position of the center of the ellipse. + * + * @name Phaser.Geom.Ellipse#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The y position of the center of the ellipse. + * + * @name Phaser.Geom.Ellipse#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + + /** + * The width of the ellipse. + * + * @name Phaser.Geom.Ellipse#width + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the ellipse. + * + * @name Phaser.Geom.Ellipse#height + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.height = height; + }, + + /** + * Check to see if the Ellipse contains the given x / y coordinates. + * + * @method Phaser.Geom.Ellipse#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check within the ellipse. + * @param {number} y - The y coordinate to check within the ellipse. + * + * @return {boolean} True if the coordinates are within the ellipse, otherwise false. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Returns a Point 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 circle. + * + * @method Phaser.Geom.Ellipse#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} 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.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the ellipse. + */ + getPoint: function (position, point) + { + return GetPoint(this, position, point); + }, + + /** + * Returns an array of Point 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the ellipse. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a uniformly distributed random point from anywhere within the given Ellipse. + * + * @method Phaser.Geom.Ellipse#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {(Phaser.Geom.Point|object)} [point] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets the x, y, width and height of this ellipse. + * + * @method Phaser.Geom.Ellipse#setTo + * @since 3.0.0 + * + * @param {number} x - The x position of the center of the ellipse. + * @param {number} y - The y position of the center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) + { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + }, + + /** + * Sets this Ellipse to be empty with a width and height of zero. + * Does not change its position. + * + * @method Phaser.Geom.Ellipse#setEmpty + * @since 3.0.0 + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setEmpty: function () + { + this.width = 0; + this.height = 0; + + return this; + }, + + /** + * Sets the position of this Ellipse. + * + * @method Phaser.Geom.Ellipse#setPosition + * @since 3.0.0 + * + * @param {number} x - The x position of the center of the ellipse. + * @param {number} y - The y position of the center of the ellipse. + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Sets the size of this Ellipse. + * Does not change its position. + * + * @method Phaser.Geom.Ellipse#setSize + * @since 3.0.0 + * + * @param {number} width - The width of the ellipse. + * @param {number} [height=width] - The height of the ellipse. + * + * @return {Phaser.Geom.Ellipse} This Ellipse object. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + this.width = width; + this.height = height; + + return this; + }, + + /** + * Checks to see if the Ellipse is empty: has a width or height equal to zero. + * + * @method Phaser.Geom.Ellipse#isEmpty + * @since 3.0.0 + * + * @return {boolean} True if the Ellipse is empty, otherwise false. + */ + isEmpty: function () + { + return (this.width <= 0 || this.height <= 0); + }, + + /** + * Returns the minor radius of the ellipse. Also known as the Semi Minor Axis. + * + * @method Phaser.Geom.Ellipse#getMinorRadius + * @since 3.0.0 + * + * @return {number} The minor radius. + */ + getMinorRadius: function () + { + return Math.min(this.width, this.height) / 2; + }, + + /** + * Returns the major radius of the ellipse. Also known as the Semi Major Axis. + * + * @method Phaser.Geom.Ellipse#getMajorRadius + * @since 3.0.0 + * + * @return {number} The major radius. + */ + getMajorRadius: function () + { + return Math.max(this.width, this.height) / 2; + }, + + /** + * The left position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.x - (this.width / 2); + }, + + set: function (value) + { + this.x = value + (this.width / 2); + } + + }, + + /** + * The right position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.x + (this.width / 2); + }, + + set: function (value) + { + this.x = value - (this.width / 2); + } + + }, + + /** + * The top position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.y - (this.height / 2); + }, + + set: function (value) + { + this.y = value + (this.height / 2); + } + + }, + + /** + * The bottom position of the Ellipse. + * + * @name Phaser.Geom.Ellipse#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.y + (this.height / 2); + }, + + set: function (value) + { + this.y = value - (this.height / 2); + } + + } + +}); + +module.exports = Ellipse; diff --git a/src/geom/ellipse/Equals.js b/src/geom/ellipse/Equals.js index 6395d9daa..a60f8da1b 100644 --- a/src/geom/ellipse/Equals.js +++ b/src/geom/ellipse/Equals.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compares the `x`, `y`, `width` and `height` properties of the two given Ellipses. - * Returns `true` if they all match, otherwise returns `false`. - * - * @function Phaser.Geom.Ellipse.Equals - * @since 3.0.0 - * - * @param {Phaser.Geom.Ellipse} ellipse - The first Ellipse to compare. - * @param {Phaser.Geom.Ellipse} toCompare - The second Ellipse to compare. - * - * @return {boolean} `true` if the two Ellipse equal each other, otherwise `false`. - */ -var Equals = function (ellipse, toCompare) -{ - return ( - ellipse.x === toCompare.x && - ellipse.y === toCompare.y && - ellipse.width === toCompare.width && - ellipse.height === toCompare.height - ); -}; - -module.exports = Equals; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compares the `x`, `y`, `width` and `height` properties of the two given Ellipses. + * Returns `true` if they all match, otherwise returns `false`. + * + * @function Phaser.Geom.Ellipse.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Ellipse} ellipse - The first Ellipse to compare. + * @param {Phaser.Geom.Ellipse} toCompare - The second Ellipse to compare. + * + * @return {boolean} `true` if the two Ellipse equal each other, otherwise `false`. + */ +var Equals = function (ellipse, toCompare) +{ + return ( + ellipse.x === toCompare.x && + ellipse.y === toCompare.y && + ellipse.width === toCompare.width && + ellipse.height === toCompare.height + ); +}; + +module.exports = Equals; diff --git a/src/geom/ellipse/GetBounds.js b/src/geom/ellipse/GetBounds.js index 141ce5c8a..516f3c9ae 100644 --- a/src/geom/ellipse/GetBounds.js +++ b/src/geom/ellipse/GetBounds.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('../rectangle/Rectangle'); - -/** - * Returns the bounds of the Ellipse object. - * - * @function Phaser.Geom.Ellipse.GetBounds - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the bounds from. - * @param {(Phaser.Geom.Rectangle|object)} [out] - A Rectangle, or rectangle-like object, to store the ellipse bounds in. If not given a new Rectangle will be created. - * - * @return {(Phaser.Geom.Rectangle|object)} The Rectangle object containing the Ellipse bounds. - */ -var GetBounds = function (ellipse, out) -{ - if (out === undefined) { out = new Rectangle(); } - - out.x = ellipse.left; - out.y = ellipse.top; - out.width = ellipse.width; - out.height = ellipse.height; - - return out; -}; - -module.exports = GetBounds; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('../rectangle/Rectangle'); + +/** + * Returns the bounds of the Ellipse object. + * + * @function Phaser.Geom.Ellipse.GetBounds + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the bounds from. + * @param {(Phaser.Geom.Rectangle|object)} [out] - A Rectangle, or rectangle-like object, to store the ellipse bounds in. If not given a new Rectangle will be created. + * + * @return {(Phaser.Geom.Rectangle|object)} The Rectangle object containing the Ellipse bounds. + */ +var GetBounds = function (ellipse, out) +{ + if (out === undefined) { out = new Rectangle(); } + + out.x = ellipse.left; + out.y = ellipse.top; + out.width = ellipse.width; + out.height = ellipse.height; + + return out; +}; + +module.exports = GetBounds; diff --git a/src/geom/ellipse/GetPoint.js b/src/geom/ellipse/GetPoint.js index 7a1242600..7a4cfbeb1 100644 --- a/src/geom/ellipse/GetPoint.js +++ b/src/geom/ellipse/GetPoint.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CircumferencePoint = require('./CircumferencePoint'); -var FromPercent = require('../../math/FromPercent'); -var MATH_CONST = require('../../math/const'); -var Point = require('../point/Point'); - -/** - * Returns a Point 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 circle. - * - * @function Phaser.Geom.Ellipse.GetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} 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 around the ellipse. - * @param {(Phaser.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the ellipse. - */ -var GetPoint = function (ellipse, position, out) -{ - if (out === undefined) { out = new Point(); } - - var angle = FromPercent(position, 0, MATH_CONST.PI2); - - return CircumferencePoint(ellipse, angle, out); -}; - -module.exports = GetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CircumferencePoint = require('./CircumferencePoint'); +var FromPercent = require('../../math/FromPercent'); +var MATH_CONST = require('../../math/const'); +var Point = require('../point/Point'); + +/** + * Returns a Point 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 circle. + * + * @function Phaser.Geom.Ellipse.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} 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 around the ellipse. + * @param {(Phaser.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the ellipse. + */ +var GetPoint = function (ellipse, position, out) +{ + if (out === undefined) { out = new Point(); } + + var angle = FromPercent(position, 0, MATH_CONST.PI2); + + return CircumferencePoint(ellipse, angle, out); +}; + +module.exports = GetPoint; diff --git a/src/geom/ellipse/GetPoints.js b/src/geom/ellipse/GetPoints.js index ebe1cb435..47f4c0e74 100644 --- a/src/geom/ellipse/GetPoints.js +++ b/src/geom/ellipse/GetPoints.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Circumference = require('./Circumference'); -var CircumferencePoint = require('./CircumferencePoint'); -var FromPercent = require('../../math/FromPercent'); -var MATH_CONST = require('../../math/const'); - -/** - * Returns an array of Point 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.Geom.Point[]} O - [out,$return] - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the points from. - * @param {integer} 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 {(array|Phaser.Geom.Point[])} [out] - An array to insert the points in to. If not provided a new array will be created. - * - * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the ellipse. - */ -var GetPoints = function (ellipse, quantity, stepRate, out) -{ - if (out === undefined) { out = []; } - - // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!quantity) - { - quantity = Circumference(ellipse) / stepRate; - } - - for (var i = 0; i < quantity; i++) - { - var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); - - out.push(CircumferencePoint(ellipse, angle)); - } - - return out; -}; - -module.exports = GetPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circumference = require('./Circumference'); +var CircumferencePoint = require('./CircumferencePoint'); +var FromPercent = require('../../math/FromPercent'); +var MATH_CONST = require('../../math/const'); + +/** + * Returns an array of Point 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.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the points from. + * @param {integer} 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 {(array|Phaser.Geom.Point[])} [out] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the circumference of the ellipse. + */ +var GetPoints = function (ellipse, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Circumference(ellipse) / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); + + out.push(CircumferencePoint(ellipse, angle)); + } + + return out; +}; + +module.exports = GetPoints; diff --git a/src/geom/ellipse/Offset.js b/src/geom/ellipse/Offset.js index a2089241e..2a6a79ec8 100644 --- a/src/geom/ellipse/Offset.js +++ b/src/geom/ellipse/Offset.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Offsets the Ellipse by the values given. - * - * @function Phaser.Geom.Ellipse.Offset - * @since 3.0.0 - * - * @generic {Phaser.Geom.Ellipse} O - [ellipse,$return] - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to be offset (translated.) - * @param {number} x - The amount to horizontally offset the Ellipse by. - * @param {number} y - The amount to vertically offset the Ellipse by. - * - * @return {Phaser.Geom.Ellipse} The Ellipse that was offset. - */ -var Offset = function (ellipse, x, y) -{ - ellipse.x += x; - ellipse.y += y; - - return ellipse; -}; - -module.exports = Offset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Ellipse by the values given. + * + * @function Phaser.Geom.Ellipse.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Ellipse} O - [ellipse,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to be offset (translated.) + * @param {number} x - The amount to horizontally offset the Ellipse by. + * @param {number} y - The amount to vertically offset the Ellipse by. + * + * @return {Phaser.Geom.Ellipse} The Ellipse that was offset. + */ +var Offset = function (ellipse, x, y) +{ + ellipse.x += x; + ellipse.y += y; + + return ellipse; +}; + +module.exports = Offset; diff --git a/src/geom/ellipse/OffsetPoint.js b/src/geom/ellipse/OffsetPoint.js index 2309cc0f5..c119ad1ee 100644 --- a/src/geom/ellipse/OffsetPoint.js +++ b/src/geom/ellipse/OffsetPoint.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Offsets the Ellipse by the values given in the `x` and `y` properties of the Point object. - * - * @function Phaser.Geom.Ellipse.OffsetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Ellipse} O - [ellipse,$return] - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to be offset (translated.) - * @param {(Phaser.Geom.Point|object)} point - The Point object containing the values to offset the Ellipse by. - * - * @return {Phaser.Geom.Ellipse} The Ellipse that was offset. - */ -var OffsetPoint = function (ellipse, point) -{ - ellipse.x += point.x; - ellipse.y += point.y; - - return ellipse; -}; - -module.exports = OffsetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offsets the Ellipse by the values given in the `x` and `y` properties of the Point object. + * + * @function Phaser.Geom.Ellipse.OffsetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Ellipse} O - [ellipse,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to be offset (translated.) + * @param {(Phaser.Geom.Point|object)} point - The Point object containing the values to offset the Ellipse by. + * + * @return {Phaser.Geom.Ellipse} The Ellipse that was offset. + */ +var OffsetPoint = function (ellipse, point) +{ + ellipse.x += point.x; + ellipse.y += point.y; + + return ellipse; +}; + +module.exports = OffsetPoint; diff --git a/src/geom/ellipse/Random.js b/src/geom/ellipse/Random.js index 0008fc7ed..26d1d2984 100644 --- a/src/geom/ellipse/Random.js +++ b/src/geom/ellipse/Random.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a uniformly distributed random point from anywhere within the given Ellipse. - * - * @function Phaser.Geom.Ellipse.Random - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get a random point from. - * @param {(Phaser.Geom.Point|object)} [out] - A Point or point-like object to set the random `x` and `y` values in. - * - * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. - */ -var Random = function (ellipse, out) -{ - if (out === undefined) { out = new Point(); } - - var p = Math.random() * Math.PI * 2; - var s = Math.sqrt(Math.random()); - - out.x = ellipse.x + ((s * Math.cos(p)) * ellipse.width / 2); - out.y = ellipse.y + ((s * Math.sin(p)) * ellipse.height / 2); - - return out; -}; - -module.exports = Random; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a uniformly distributed random point from anywhere within the given Ellipse. + * + * @function Phaser.Geom.Ellipse.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get a random point from. + * @param {(Phaser.Geom.Point|object)} [out] - A Point or point-like object to set the random `x` and `y` values in. + * + * @return {(Phaser.Geom.Point|object)} A Point object with the random values set in the `x` and `y` properties. + */ +var Random = function (ellipse, out) +{ + if (out === undefined) { out = new Point(); } + + var p = Math.random() * Math.PI * 2; + var s = Math.sqrt(Math.random()); + + out.x = ellipse.x + ((s * Math.cos(p)) * ellipse.width / 2); + out.y = ellipse.y + ((s * Math.sin(p)) * ellipse.height / 2); + + return out; +}; + +module.exports = Random; diff --git a/src/geom/ellipse/index.js b/src/geom/ellipse/index.js index be7226eaa..78994d5ea 100644 --- a/src/geom/ellipse/index.js +++ b/src/geom/ellipse/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Ellipse = require('./Ellipse'); - -Ellipse.Area = require('./Area'); -Ellipse.Circumference = require('./Circumference'); -Ellipse.CircumferencePoint = require('./CircumferencePoint'); -Ellipse.Clone = require('./Clone'); -Ellipse.Contains = require('./Contains'); -Ellipse.ContainsPoint = require('./ContainsPoint'); -Ellipse.ContainsRect = require('./ContainsRect'); -Ellipse.CopyFrom = require('./CopyFrom'); -Ellipse.Equals = require('./Equals'); -Ellipse.GetBounds = require('./GetBounds'); -Ellipse.GetPoint = require('./GetPoint'); -Ellipse.GetPoints = require('./GetPoints'); -Ellipse.Offset = require('./Offset'); -Ellipse.OffsetPoint = require('./OffsetPoint'); -Ellipse.Random = require('./Random'); - -module.exports = Ellipse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Ellipse = require('./Ellipse'); + +Ellipse.Area = require('./Area'); +Ellipse.Circumference = require('./Circumference'); +Ellipse.CircumferencePoint = require('./CircumferencePoint'); +Ellipse.Clone = require('./Clone'); +Ellipse.Contains = require('./Contains'); +Ellipse.ContainsPoint = require('./ContainsPoint'); +Ellipse.ContainsRect = require('./ContainsRect'); +Ellipse.CopyFrom = require('./CopyFrom'); +Ellipse.Equals = require('./Equals'); +Ellipse.GetBounds = require('./GetBounds'); +Ellipse.GetPoint = require('./GetPoint'); +Ellipse.GetPoints = require('./GetPoints'); +Ellipse.Offset = require('./Offset'); +Ellipse.OffsetPoint = require('./OffsetPoint'); +Ellipse.Random = require('./Random'); + +module.exports = Ellipse; diff --git a/src/geom/index.js b/src/geom/index.js index 2208184af..c40856e85 100644 --- a/src/geom/index.js +++ b/src/geom/index.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../utils/object/Extend'); - -/** - * @namespace Phaser.Geom - */ - -var Geom = { - - Circle: require('./circle'), - Ellipse: require('./ellipse'), - Intersects: require('./intersects'), - Line: require('./line'), - Point: require('./point'), - Polygon: require('./polygon'), - Rectangle: require('./rectangle'), - Triangle: require('./triangle') - -}; - -// Merge in the consts -Geom = Extend(false, Geom, CONST); - -module.exports = Geom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../utils/object/Extend'); + +/** + * @namespace Phaser.Geom + */ + +var Geom = { + + Circle: require('./circle'), + Ellipse: require('./ellipse'), + Intersects: require('./intersects'), + Line: require('./line'), + Point: require('./point'), + Polygon: require('./polygon'), + Rectangle: require('./rectangle'), + Triangle: require('./triangle') + +}; + +// Merge in the consts +Geom = Extend(false, Geom, CONST); + +module.exports = Geom; diff --git a/src/geom/intersects/CircleToCircle.js b/src/geom/intersects/CircleToCircle.js index 567abb25d..513806ff3 100644 --- a/src/geom/intersects/CircleToCircle.js +++ b/src/geom/intersects/CircleToCircle.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DistanceBetween = require('../../math/distance/DistanceBetween'); - -/** - * Checks if two Circles intersect. - * - * @function Phaser.Geom.Intersects.CircleToCircle - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circleA - The first Circle to check for intersection. - * @param {Phaser.Geom.Circle} circleB - The second Circle to check for intersection. - * - * @return {boolean} `true` if the two Circles intersect, otherwise `false`. - */ -var CircleToCircle = function (circleA, circleB) -{ - return (DistanceBetween(circleA.x, circleA.y, circleB.x, circleB.y) <= (circleA.radius + circleB.radius)); -}; - -module.exports = CircleToCircle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DistanceBetween = require('../../math/distance/DistanceBetween'); + +/** + * Checks if two Circles intersect. + * + * @function Phaser.Geom.Intersects.CircleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circleA - The first Circle to check for intersection. + * @param {Phaser.Geom.Circle} circleB - The second Circle to check for intersection. + * + * @return {boolean} `true` if the two Circles intersect, otherwise `false`. + */ +var CircleToCircle = function (circleA, circleB) +{ + return (DistanceBetween(circleA.x, circleA.y, circleB.x, circleB.y) <= (circleA.radius + circleB.radius)); +}; + +module.exports = CircleToCircle; diff --git a/src/geom/intersects/CircleToRectangle.js b/src/geom/intersects/CircleToRectangle.js index 3afd9f2a9..ae756952c 100644 --- a/src/geom/intersects/CircleToRectangle.js +++ b/src/geom/intersects/CircleToRectangle.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks for intersection between a circle and a rectangle. - * - * @function Phaser.Geom.Intersects.CircleToRectangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The circle to be checked. - * @param {Phaser.Geom.Rectangle} rect - The rectangle to be checked. - * - * @return {boolean} `true` if the two objects intersect, otherwise `false`. - */ -var CircleToRectangle = function (circle, rect) -{ - var halfWidth = rect.width / 2; - var halfHeight = rect.height / 2; - - var cx = Math.abs(circle.x - rect.x - halfWidth); - var cy = Math.abs(circle.y - rect.y - halfHeight); - var xDist = halfWidth + circle.radius; - var yDist = halfHeight + circle.radius; - - if (cx > xDist || cy > yDist) - { - return false; - } - else if (cx <= halfWidth || cy <= halfHeight) - { - return true; - } - else - { - var xCornerDist = cx - halfWidth; - var yCornerDist = cy - halfHeight; - var xCornerDistSq = xCornerDist * xCornerDist; - var yCornerDistSq = yCornerDist * yCornerDist; - var maxCornerDistSq = circle.radius * circle.radius; - - return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq); - } -}; - -module.exports = CircleToRectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks for intersection between a circle and a rectangle. + * + * @function Phaser.Geom.Intersects.CircleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to be checked. + * @param {Phaser.Geom.Rectangle} rect - The rectangle to be checked. + * + * @return {boolean} `true` if the two objects intersect, otherwise `false`. + */ +var CircleToRectangle = function (circle, rect) +{ + var halfWidth = rect.width / 2; + var halfHeight = rect.height / 2; + + var cx = Math.abs(circle.x - rect.x - halfWidth); + var cy = Math.abs(circle.y - rect.y - halfHeight); + var xDist = halfWidth + circle.radius; + var yDist = halfHeight + circle.radius; + + if (cx > xDist || cy > yDist) + { + return false; + } + else if (cx <= halfWidth || cy <= halfHeight) + { + return true; + } + else + { + var xCornerDist = cx - halfWidth; + var yCornerDist = cy - halfHeight; + var xCornerDistSq = xCornerDist * xCornerDist; + var yCornerDistSq = yCornerDist * yCornerDist; + var maxCornerDistSq = circle.radius * circle.radius; + + return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq); + } +}; + +module.exports = CircleToRectangle; diff --git a/src/geom/intersects/GetCircleToCircle.js b/src/geom/intersects/GetCircleToCircle.js index b241a908d..e15831df7 100644 --- a/src/geom/intersects/GetCircleToCircle.js +++ b/src/geom/intersects/GetCircleToCircle.js @@ -1,88 +1,88 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); -var CircleToCircle = require('./CircleToCircle'); - -/** - * Checks if two Circles intersect and returns the intersection points as a Point object array. - * - * @function Phaser.Geom.Intersects.GetCircleToCircle - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circleA - The first Circle to check for intersection. - * @param {Phaser.Geom.Circle} circleB - The second Circle to check for intersection. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetCircleToCircle = function (circleA, circleB, out) -{ - if (out === undefined) { out = []; } - - if (CircleToCircle(circleA, circleB)) - { - var x0 = circleA.x; - var y0 = circleA.y; - var r0 = circleA.radius; - - var x1 = circleB.x; - var y1 = circleB.y; - var r1 = circleB.radius; - - var coefficientA, coefficientB, coefficientC, lambda, x; - - if (y0 === y1) - { - x = ((r1 * r1) - (r0 * r0) - (x1 * x1) + (x0 * x0)) / (2 * (x0 - x1)); - - coefficientA = 1; - coefficientB = -2 * y1; - coefficientC = (x1 * x1) + (x * x) - (2 * x1 * x) + (y1 * y1) - (r1 * r1); - - lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); - - if (lambda === 0) - { - out.push(new Point(x, (-coefficientB / (2 * coefficientA)))); - } - else if (lambda > 0) - { - out.push(new Point(x, (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA))); - out.push(new Point(x, (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA))); - } - } - else - { - var v1 = (x0 - x1) / (y0 - y1); - var n = (r1 * r1 - r0 * r0 - x1 * x1 + x0 * x0 - y1 * y1 + y0 * y0) / (2 * (y0 - y1)); - - coefficientA = (v1 * v1) + 1; - coefficientB = (2 * y0 * v1) - (2 * n * v1) - (2 * x0); - coefficientC = (x0 * x0) + (y0 * y0) + (n * n) - (r0 * r0) - (2 * y0 * n); - - lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); - - if (lambda === 0) - { - x = (-coefficientB / (2 * coefficientA)); - out.push(new Point(x, (n - (x * v1)))); - } - else if (lambda > 0) - { - x = (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA); - out.push(new Point(x, (n - (x * v1)))); - x = (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA); - out.push(new Point(x, (n - (x * v1)))); - } - } - } - - return out; -}; - -module.exports = GetCircleToCircle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); +var CircleToCircle = require('./CircleToCircle'); + +/** + * Checks if two Circles intersect and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetCircleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circleA - The first Circle to check for intersection. + * @param {Phaser.Geom.Circle} circleB - The second Circle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetCircleToCircle = function (circleA, circleB, out) +{ + if (out === undefined) { out = []; } + + if (CircleToCircle(circleA, circleB)) + { + var x0 = circleA.x; + var y0 = circleA.y; + var r0 = circleA.radius; + + var x1 = circleB.x; + var y1 = circleB.y; + var r1 = circleB.radius; + + var coefficientA, coefficientB, coefficientC, lambda, x; + + if (y0 === y1) + { + x = ((r1 * r1) - (r0 * r0) - (x1 * x1) + (x0 * x0)) / (2 * (x0 - x1)); + + coefficientA = 1; + coefficientB = -2 * y1; + coefficientC = (x1 * x1) + (x * x) - (2 * x1 * x) + (y1 * y1) - (r1 * r1); + + lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); + + if (lambda === 0) + { + out.push(new Point(x, (-coefficientB / (2 * coefficientA)))); + } + else if (lambda > 0) + { + out.push(new Point(x, (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA))); + out.push(new Point(x, (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA))); + } + } + else + { + var v1 = (x0 - x1) / (y0 - y1); + var n = (r1 * r1 - r0 * r0 - x1 * x1 + x0 * x0 - y1 * y1 + y0 * y0) / (2 * (y0 - y1)); + + coefficientA = (v1 * v1) + 1; + coefficientB = (2 * y0 * v1) - (2 * n * v1) - (2 * x0); + coefficientC = (x0 * x0) + (y0 * y0) + (n * n) - (r0 * r0) - (2 * y0 * n); + + lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); + + if (lambda === 0) + { + x = (-coefficientB / (2 * coefficientA)); + out.push(new Point(x, (n - (x * v1)))); + } + else if (lambda > 0) + { + x = (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA); + out.push(new Point(x, (n - (x * v1)))); + x = (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA); + out.push(new Point(x, (n - (x * v1)))); + } + } + } + + return out; +}; + +module.exports = GetCircleToCircle; diff --git a/src/geom/intersects/GetCircleToRectangle.js b/src/geom/intersects/GetCircleToRectangle.js index edd7fc59e..35b676953 100644 --- a/src/geom/intersects/GetCircleToRectangle.js +++ b/src/geom/intersects/GetCircleToRectangle.js @@ -1,44 +1,44 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetLineToCircle = require('./GetLineToCircle'); -var CircleToRectangle = require('./CircleToRectangle'); - -/** - * Checks for intersection between a circle and a rectangle, - * and returns the intersection points as a Point object array. - * - * @function Phaser.Geom.Intersects.GetCircleToRectangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Circle} circle - The circle to be checked. - * @param {Phaser.Geom.Rectangle} rect - The rectangle to be checked. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetCircleToRectangle = function (circle, rect, out) -{ - if (out === undefined) { out = []; } - - if (CircleToRectangle(circle, rect)) - { - var lineA = rect.getLineA(); - var lineB = rect.getLineB(); - var lineC = rect.getLineC(); - var lineD = rect.getLineD(); - - GetLineToCircle(lineA, circle, out); - GetLineToCircle(lineB, circle, out); - GetLineToCircle(lineC, circle, out); - GetLineToCircle(lineD, circle, out); - } - - return out; -}; - -module.exports = GetCircleToRectangle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLineToCircle = require('./GetLineToCircle'); +var CircleToRectangle = require('./CircleToRectangle'); + +/** + * Checks for intersection between a circle and a rectangle, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetCircleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Circle} circle - The circle to be checked. + * @param {Phaser.Geom.Rectangle} rect - The rectangle to be checked. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetCircleToRectangle = function (circle, rect, out) +{ + if (out === undefined) { out = []; } + + if (CircleToRectangle(circle, rect)) + { + var lineA = rect.getLineA(); + var lineB = rect.getLineB(); + var lineC = rect.getLineC(); + var lineD = rect.getLineD(); + + GetLineToCircle(lineA, circle, out); + GetLineToCircle(lineB, circle, out); + GetLineToCircle(lineC, circle, out); + GetLineToCircle(lineD, circle, out); + } + + return out; +}; + +module.exports = GetCircleToRectangle; diff --git a/src/geom/intersects/GetLineToCircle.js b/src/geom/intersects/GetLineToCircle.js index fa59407e3..dc435579c 100644 --- a/src/geom/intersects/GetLineToCircle.js +++ b/src/geom/intersects/GetLineToCircle.js @@ -1,86 +1,86 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); -var LineToCircle = require('./LineToCircle'); - -/** - * Checks for intersection between the line segment and circle, - * and returns the intersection points as a Point object array. - * - * @function Phaser.Geom.Intersects.GetLineToCircle - * @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 {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetLineToCircle = function (line, circle, out) -{ - if (out === undefined) { out = []; } - - if (LineToCircle(line, circle)) - { - var lx1 = line.x1; - var ly1 = line.y1; - - var lx2 = line.x2; - var ly2 = line.y2; - - var cx = circle.x; - var cy = circle.y; - var cr = circle.radius; - - var lDirX = lx2 - lx1; - var lDirY = ly2 - ly1; - var oDirX = lx1 - cx; - var oDirY = ly1 - cy; - - var coefficientA = lDirX * lDirX + lDirY * lDirY; - var coefficientB = 2 * (lDirX * oDirX + lDirY * oDirY); - var coefficientC = oDirX * oDirX + oDirY * oDirY - cr * cr; - - var lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); - - var x, y; - - if (lambda === 0) - { - var root = -coefficientB / (2 * coefficientA); - x = lx1 + root * lDirX; - y = ly1 + root * lDirY; - if (root >= 0 && root <= 1) - { - out.push(new Point(x, y)); - } - } - else if (lambda > 0) - { - var root1 = (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA); - x = lx1 + root1 * lDirX; - y = ly1 + root1 * lDirY; - if (root1 >= 0 && root1 <= 1) - { - out.push(new Point(x, y)); - } - - var root2 = (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA); - x = lx1 + root2 * lDirX; - y = ly1 + root2 * lDirY; - if (root2 >= 0 && root2 <= 1) - { - out.push(new Point(x, y)); - } - } - } - - return out; -}; - -module.exports = GetLineToCircle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); +var LineToCircle = require('./LineToCircle'); + +/** + * Checks for intersection between the line segment and circle, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetLineToCircle + * @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 {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetLineToCircle = function (line, circle, out) +{ + if (out === undefined) { out = []; } + + if (LineToCircle(line, circle)) + { + var lx1 = line.x1; + var ly1 = line.y1; + + var lx2 = line.x2; + var ly2 = line.y2; + + var cx = circle.x; + var cy = circle.y; + var cr = circle.radius; + + var lDirX = lx2 - lx1; + var lDirY = ly2 - ly1; + var oDirX = lx1 - cx; + var oDirY = ly1 - cy; + + var coefficientA = lDirX * lDirX + lDirY * lDirY; + var coefficientB = 2 * (lDirX * oDirX + lDirY * oDirY); + var coefficientC = oDirX * oDirX + oDirY * oDirY - cr * cr; + + var lambda = (coefficientB * coefficientB) - (4 * coefficientA * coefficientC); + + var x, y; + + if (lambda === 0) + { + var root = -coefficientB / (2 * coefficientA); + x = lx1 + root * lDirX; + y = ly1 + root * lDirY; + if (root >= 0 && root <= 1) + { + out.push(new Point(x, y)); + } + } + else if (lambda > 0) + { + var root1 = (-coefficientB - Math.sqrt(lambda)) / (2 * coefficientA); + x = lx1 + root1 * lDirX; + y = ly1 + root1 * lDirY; + if (root1 >= 0 && root1 <= 1) + { + out.push(new Point(x, y)); + } + + var root2 = (-coefficientB + Math.sqrt(lambda)) / (2 * coefficientA); + x = lx1 + root2 * lDirX; + y = ly1 + root2 * lDirY; + if (root2 >= 0 && root2 <= 1) + { + out.push(new Point(x, y)); + } + } + } + + return out; +}; + +module.exports = GetLineToCircle; diff --git a/src/geom/intersects/GetLineToRectangle.js b/src/geom/intersects/GetLineToRectangle.js index 859866b29..f7d32bace 100644 --- a/src/geom/intersects/GetLineToRectangle.js +++ b/src/geom/intersects/GetLineToRectangle.js @@ -1,54 +1,54 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); -var LineToLine = require('./LineToLine'); -var LineToRectangle = require('./LineToRectangle'); - -/** - * Checks for intersection between the Line and a Rectangle shape, - * and returns the intersection points as a Point object array. - * - * @function Phaser.Geom.Intersects.GetLineToRectangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The Line to check for intersection. - * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle to check for intersection. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetLineToRectangle = function (line, rect, out) -{ - if (out === undefined) { out = []; } - - if (LineToRectangle(line, rect)) - { - var lineA = rect.getLineA(); - var lineB = rect.getLineB(); - var lineC = rect.getLineC(); - var lineD = rect.getLineD(); - - var output = [ new Point(), new Point(), new Point(), new Point() ]; - - var result = [ - LineToLine(lineA, line, output[0]), - LineToLine(lineB, line, output[1]), - LineToLine(lineC, line, output[2]), - LineToLine(lineD, line, output[3]) - ]; - - for (var i = 0; i < 4; i++) - { - if (result[i]) { out.push(output[i]); } - } - } - - return out; -}; - -module.exports = GetLineToRectangle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); +var LineToLine = require('./LineToLine'); +var LineToRectangle = require('./LineToRectangle'); + +/** + * Checks for intersection between the Line and a Rectangle shape, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetLineToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The Line to check for intersection. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetLineToRectangle = function (line, rect, out) +{ + if (out === undefined) { out = []; } + + if (LineToRectangle(line, rect)) + { + var lineA = rect.getLineA(); + var lineB = rect.getLineB(); + var lineC = rect.getLineC(); + var lineD = rect.getLineD(); + + var output = [ new Point(), new Point(), new Point(), new Point() ]; + + var result = [ + LineToLine(lineA, line, output[0]), + LineToLine(lineB, line, output[1]), + LineToLine(lineC, line, output[2]), + LineToLine(lineD, line, output[3]) + ]; + + for (var i = 0; i < 4; i++) + { + if (result[i]) { out.push(output[i]); } + } + } + + return out; +}; + +module.exports = GetLineToRectangle; diff --git a/src/geom/intersects/GetRectangleIntersection.js b/src/geom/intersects/GetRectangleIntersection.js index 9949b8143..a20c22857 100644 --- a/src/geom/intersects/GetRectangleIntersection.js +++ b/src/geom/intersects/GetRectangleIntersection.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('../rectangle/Rectangle'); -var RectangleToRectangle = require('./RectangleToRectangle'); - -/** - * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. - * - * If optional `output` parameter is omitted, new Rectangle object is created and returned. If there is intersection, it will contain intersection area. If there is no intersection, it wil be empty Rectangle (all values set to zero). - * - * If Rectangle object is passed as `output` and there is intersection, then intersection area data will be loaded into it and it will be returned. If there is no intersection, it will be returned without any change. - * - * @function Phaser.Geom.Intersects.GetRectangleIntersection - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [output,$return] - * - * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle object. - * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle object. - * @param {Phaser.Geom.Rectangle} [output] - Optional Rectangle object. If given, the intersection data will be loaded into it (in case of no intersection, it will be left unchanged). Otherwise, new Rectangle object will be created and returned with either intersection data or empty (all values set to zero), if there is no intersection. - * - * @return {Phaser.Geom.Rectangle} A rectangle object with intersection data. - */ -var GetRectangleIntersection = function (rectA, rectB, output) -{ - if (output === undefined) { output = new Rectangle(); } - - if (RectangleToRectangle(rectA, rectB)) - { - output.x = Math.max(rectA.x, rectB.x); - output.y = Math.max(rectA.y, rectB.y); - output.width = Math.min(rectA.right, rectB.right) - output.x; - output.height = Math.min(rectA.bottom, rectB.bottom) - output.y; - } - - return output; -}; - -module.exports = GetRectangleIntersection; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('../rectangle/Rectangle'); +var RectangleToRectangle = require('./RectangleToRectangle'); + +/** + * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. + * + * If optional `output` parameter is omitted, new Rectangle object is created and returned. If there is intersection, it will contain intersection area. If there is no intersection, it wil be empty Rectangle (all values set to zero). + * + * If Rectangle object is passed as `output` and there is intersection, then intersection area data will be loaded into it and it will be returned. If there is no intersection, it will be returned without any change. + * + * @function Phaser.Geom.Intersects.GetRectangleIntersection + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [output,$return] + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle object. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle object. + * @param {Phaser.Geom.Rectangle} [output] - Optional Rectangle object. If given, the intersection data will be loaded into it (in case of no intersection, it will be left unchanged). Otherwise, new Rectangle object will be created and returned with either intersection data or empty (all values set to zero), if there is no intersection. + * + * @return {Phaser.Geom.Rectangle} A rectangle object with intersection data. + */ +var GetRectangleIntersection = function (rectA, rectB, output) +{ + if (output === undefined) { output = new Rectangle(); } + + if (RectangleToRectangle(rectA, rectB)) + { + output.x = Math.max(rectA.x, rectB.x); + output.y = Math.max(rectA.y, rectB.y); + output.width = Math.min(rectA.right, rectB.right) - output.x; + output.height = Math.min(rectA.bottom, rectB.bottom) - output.y; + } + + return output; +}; + +module.exports = GetRectangleIntersection; diff --git a/src/geom/intersects/GetRectangleToRectangle.js b/src/geom/intersects/GetRectangleToRectangle.js index 28f0808d9..6710dc877 100644 --- a/src/geom/intersects/GetRectangleToRectangle.js +++ b/src/geom/intersects/GetRectangleToRectangle.js @@ -1,45 +1,45 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetLineToRectangle = require('./GetLineToRectangle'); -var RectangleToRectangle = require('./RectangleToRectangle'); - -/** - * Checks if two Rectangles intersect and returns the intersection points as a Point object array. - * - * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. As such, the two Rectangles are considered "solid". A Rectangle with no width or no height will never intersect another Rectangle. - * - * @function Phaser.Geom.Intersects.GetRectangleToRectangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. - * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetRectangleToRectangle = function (rectA, rectB, out) -{ - if (out === undefined) { out = []; } - - if (RectangleToRectangle(rectA, rectB)) - { - var lineA = rectA.getLineA(); - var lineB = rectA.getLineB(); - var lineC = rectA.getLineC(); - var lineD = rectA.getLineD(); - - GetLineToRectangle(lineA, rectB, out); - GetLineToRectangle(lineB, rectB, out); - GetLineToRectangle(lineC, rectB, out); - GetLineToRectangle(lineD, rectB, out); - } - - return out; -}; - -module.exports = GetRectangleToRectangle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLineToRectangle = require('./GetLineToRectangle'); +var RectangleToRectangle = require('./RectangleToRectangle'); + +/** + * Checks if two Rectangles intersect and returns the intersection points as a Point object array. + * + * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. As such, the two Rectangles are considered "solid". A Rectangle with no width or no height will never intersect another Rectangle. + * + * @function Phaser.Geom.Intersects.GetRectangleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetRectangleToRectangle = function (rectA, rectB, out) +{ + if (out === undefined) { out = []; } + + if (RectangleToRectangle(rectA, rectB)) + { + var lineA = rectA.getLineA(); + var lineB = rectA.getLineB(); + var lineC = rectA.getLineC(); + var lineD = rectA.getLineD(); + + GetLineToRectangle(lineA, rectB, out); + GetLineToRectangle(lineB, rectB, out); + GetLineToRectangle(lineC, rectB, out); + GetLineToRectangle(lineD, rectB, out); + } + + return out; +}; + +module.exports = GetRectangleToRectangle; diff --git a/src/geom/intersects/GetRectangleToTriangle.js b/src/geom/intersects/GetRectangleToTriangle.js index e574f7d44..4e04c797d 100644 --- a/src/geom/intersects/GetRectangleToTriangle.js +++ b/src/geom/intersects/GetRectangleToTriangle.js @@ -1,42 +1,42 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RectangleToTriangle = require('./RectangleToTriangle'); -var GetLineToRectangle = require('./GetLineToRectangle'); - -/** - * Checks for intersection between Rectangle shape and Triangle shape, - * and returns the intersection points as a Point object array. - * - * @function Phaser.Geom.Intersects.GetRectangleToTriangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - Rectangle object to test. - * @param {Phaser.Geom.Triangle} triangle - Triangle object to test. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetRectangleToTriangle = function (rect, triangle, out) -{ - if (out === undefined) { out = []; } - - if (RectangleToTriangle(rect, triangle)) - { - var lineA = triangle.getLineA(); - var lineB = triangle.getLineB(); - var lineC = triangle.getLineC(); - - GetLineToRectangle(lineA, rect, out); - GetLineToRectangle(lineB, rect, out); - GetLineToRectangle(lineC, rect, out); - } - - return out; -}; - -module.exports = GetRectangleToTriangle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RectangleToTriangle = require('./RectangleToTriangle'); +var GetLineToRectangle = require('./GetLineToRectangle'); + +/** + * Checks for intersection between Rectangle shape and Triangle shape, + * and returns the intersection points as a Point object array. + * + * @function Phaser.Geom.Intersects.GetRectangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - Rectangle object to test. + * @param {Phaser.Geom.Triangle} triangle - Triangle object to test. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetRectangleToTriangle = function (rect, triangle, out) +{ + if (out === undefined) { out = []; } + + if (RectangleToTriangle(rect, triangle)) + { + var lineA = triangle.getLineA(); + var lineB = triangle.getLineB(); + var lineC = triangle.getLineC(); + + GetLineToRectangle(lineA, rect, out); + GetLineToRectangle(lineB, rect, out); + GetLineToRectangle(lineC, rect, out); + } + + return out; +}; + +module.exports = GetRectangleToTriangle; diff --git a/src/geom/intersects/GetTriangleToCircle.js b/src/geom/intersects/GetTriangleToCircle.js index bf7877342..98f6cd2be 100644 --- a/src/geom/intersects/GetTriangleToCircle.js +++ b/src/geom/intersects/GetTriangleToCircle.js @@ -1,43 +1,43 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetLineToCircle = require('./GetLineToCircle'); -var TriangleToCircle = require('./TriangleToCircle'); - -/** - * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. - * - * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. - * - * @function Phaser.Geom.Intersects.GetTriangleToCircle - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to check for intersection. - * @param {Phaser.Geom.Circle} circle - The Circle to check for intersection. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetTriangleToCircle = function (triangle, circle, out) -{ - if (out === undefined) { out = []; } - - if (TriangleToCircle(triangle, circle)) - { - var lineA = triangle.getLineA(); - var lineB = triangle.getLineB(); - var lineC = triangle.getLineC(); - - GetLineToCircle(lineA, circle, out); - GetLineToCircle(lineB, circle, out); - GetLineToCircle(lineC, circle, out); - } - - return out; -}; - -module.exports = GetTriangleToCircle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetLineToCircle = require('./GetLineToCircle'); +var TriangleToCircle = require('./TriangleToCircle'); + +/** + * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. + * + * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. + * + * @function Phaser.Geom.Intersects.GetTriangleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check for intersection. + * @param {Phaser.Geom.Circle} circle - The Circle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetTriangleToCircle = function (triangle, circle, out) +{ + if (out === undefined) { out = []; } + + if (TriangleToCircle(triangle, circle)) + { + var lineA = triangle.getLineA(); + var lineB = triangle.getLineB(); + var lineC = triangle.getLineC(); + + GetLineToCircle(lineA, circle, out); + GetLineToCircle(lineB, circle, out); + GetLineToCircle(lineC, circle, out); + } + + return out; +}; + +module.exports = GetTriangleToCircle; diff --git a/src/geom/intersects/GetTriangleToLine.js b/src/geom/intersects/GetTriangleToLine.js index 1490c1b7d..42ae85d59 100644 --- a/src/geom/intersects/GetTriangleToLine.js +++ b/src/geom/intersects/GetTriangleToLine.js @@ -1,53 +1,53 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); -var TriangleToLine = require('./TriangleToLine'); -var LineToLine = require('./LineToLine'); - -/** - * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. - * - * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". - * - * @function Phaser.Geom.Intersects.GetTriangleToLine - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to check with. - * @param {Phaser.Geom.Line} line - The Line to check with. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetTriangleToLine = function (triangle, line, out) -{ - if (out === undefined) { out = []; } - - if (TriangleToLine(triangle, line)) - { - var lineA = triangle.getLineA(); - var lineB = triangle.getLineB(); - var lineC = triangle.getLineC(); - - var output = [ new Point(), new Point(), new Point() ]; - - var result = [ - LineToLine(lineA, line, output[0]), - LineToLine(lineB, line, output[1]), - LineToLine(lineC, line, output[2]) - ]; - - for (var i = 0; i < 3; i++) - { - if (result[i]) { out.push(output[i]); } - } - } - - return out; -}; - -module.exports = GetTriangleToLine; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); +var TriangleToLine = require('./TriangleToLine'); +var LineToLine = require('./LineToLine'); + +/** + * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. + * + * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". + * + * @function Phaser.Geom.Intersects.GetTriangleToLine + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check with. + * @param {Phaser.Geom.Line} line - The Line to check with. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetTriangleToLine = function (triangle, line, out) +{ + if (out === undefined) { out = []; } + + if (TriangleToLine(triangle, line)) + { + var lineA = triangle.getLineA(); + var lineB = triangle.getLineB(); + var lineC = triangle.getLineC(); + + var output = [ new Point(), new Point(), new Point() ]; + + var result = [ + LineToLine(lineA, line, output[0]), + LineToLine(lineB, line, output[1]), + LineToLine(lineC, line, output[2]) + ]; + + for (var i = 0; i < 3; i++) + { + if (result[i]) { out.push(output[i]); } + } + } + + return out; +}; + +module.exports = GetTriangleToLine; diff --git a/src/geom/intersects/GetTriangleToTriangle.js b/src/geom/intersects/GetTriangleToTriangle.js index 01e759ba9..0e0a735f8 100644 --- a/src/geom/intersects/GetTriangleToTriangle.js +++ b/src/geom/intersects/GetTriangleToTriangle.js @@ -1,43 +1,43 @@ -/** - * @author Florian Vazelle - * @author Geoffrey Glaive - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var TriangleToTriangle = require('./TriangleToTriangle'); -var GetTriangleToLine = require('./GetTriangleToLine'); - -/** - * Checks if two Triangles intersect, and returns the intersection points as a Point object array. - * - * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". - * - * @function Phaser.Geom.Intersects.GetTriangleToTriangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangleA - The first Triangle to check for intersection. - * @param {Phaser.Geom.Triangle} triangleB - The second Triangle to check for intersection. - * @param {array} [out] - An optional array in which to store the points of intersection. - * - * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. - */ -var GetTriangleToTriangle = function (triangleA, triangleB, out) -{ - if (out === undefined) { out = []; } - - if (TriangleToTriangle(triangleA, triangleB)) - { - var lineA = triangleB.getLineA(); - var lineB = triangleB.getLineB(); - var lineC = triangleB.getLineC(); - - GetTriangleToLine(triangleA, lineA, out); - GetTriangleToLine(triangleA, lineB, out); - GetTriangleToLine(triangleA, lineC, out); - } - - return out; -}; - -module.exports = GetTriangleToTriangle; +/** + * @author Florian Vazelle + * @author Geoffrey Glaive + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TriangleToTriangle = require('./TriangleToTriangle'); +var GetTriangleToLine = require('./GetTriangleToLine'); + +/** + * Checks if two Triangles intersect, and returns the intersection points as a Point object array. + * + * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". + * + * @function Phaser.Geom.Intersects.GetTriangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangleA - The first Triangle to check for intersection. + * @param {Phaser.Geom.Triangle} triangleB - The second Triangle to check for intersection. + * @param {array} [out] - An optional array in which to store the points of intersection. + * + * @return {array} An array with the points of intersection if objects intersect, otherwise an empty array. + */ +var GetTriangleToTriangle = function (triangleA, triangleB, out) +{ + if (out === undefined) { out = []; } + + if (TriangleToTriangle(triangleA, triangleB)) + { + var lineA = triangleB.getLineA(); + var lineB = triangleB.getLineB(); + var lineC = triangleB.getLineC(); + + GetTriangleToLine(triangleA, lineA, out); + GetTriangleToLine(triangleA, lineB, out); + GetTriangleToLine(triangleA, lineC, out); + } + + return out; +}; + +module.exports = GetTriangleToTriangle; diff --git a/src/geom/intersects/LineToCircle.js b/src/geom/intersects/LineToCircle.js index 5c31b3cb7..39687215e 100644 --- a/src/geom/intersects/LineToCircle.js +++ b/src/geom/intersects/LineToCircle.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('../circle/Contains'); -var Point = require('../point/Point'); - -var tmp = new Point(); - -/** - * 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.Geom.Point|any)} [nearest] - An optional Point-like 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`. - */ -var LineToCircle = function (line, circle, nearest) -{ - if (nearest === undefined) { nearest = tmp; } - - if (Contains(circle, line.x1, line.y1)) - { - nearest.x = line.x1; - nearest.y = line.y1; - - return true; - } - - if (Contains(circle, line.x2, line.y2)) - { - nearest.x = line.x2; - nearest.y = line.y2; - - return true; - } - - var dx = line.x2 - line.x1; - var dy = line.y2 - line.y1; - - var lcx = circle.x - line.x1; - var lcy = circle.y - line.y1; - - // project lc onto d, resulting in vector p - var dLen2 = (dx * dx) + (dy * dy); - var px = dx; - var py = dy; - - if (dLen2 > 0) - { - var dp = ((lcx * dx) + (lcy * dy)) / dLen2; - - px *= dp; - py *= dp; - } - - nearest.x = line.x1 + px; - nearest.y = line.y1 + py; - - // len2 of p - var pLen2 = (px * px) + (py * py); - - return ( - pLen2 <= dLen2 && - ((px * dx) + (py * dy)) >= 0 && - Contains(circle, nearest.x, nearest.y) - ); -}; - -module.exports = LineToCircle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('../circle/Contains'); +var Point = require('../point/Point'); + +var tmp = new Point(); + +/** + * 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.Geom.Point|any)} [nearest] - An optional Point-like 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`. + */ +var LineToCircle = function (line, circle, nearest) +{ + if (nearest === undefined) { nearest = tmp; } + + if (Contains(circle, line.x1, line.y1)) + { + nearest.x = line.x1; + nearest.y = line.y1; + + return true; + } + + if (Contains(circle, line.x2, line.y2)) + { + nearest.x = line.x2; + nearest.y = line.y2; + + return true; + } + + var dx = line.x2 - line.x1; + var dy = line.y2 - line.y1; + + var lcx = circle.x - line.x1; + var lcy = circle.y - line.y1; + + // project lc onto d, resulting in vector p + var dLen2 = (dx * dx) + (dy * dy); + var px = dx; + var py = dy; + + if (dLen2 > 0) + { + var dp = ((lcx * dx) + (lcy * dy)) / dLen2; + + px *= dp; + py *= dp; + } + + nearest.x = line.x1 + px; + nearest.y = line.y1 + py; + + // len2 of p + var pLen2 = (px * px) + (py * py); + + return ( + pLen2 <= dLen2 && + ((px * dx) + (py * dy)) >= 0 && + Contains(circle, nearest.x, nearest.y) + ); +}; + +module.exports = LineToCircle; diff --git a/src/geom/intersects/LineToLine.js b/src/geom/intersects/LineToLine.js index 5a7a60a3e..61da2369c 100644 --- a/src/geom/intersects/LineToLine.js +++ b/src/geom/intersects/LineToLine.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -// This is based off an explanation and expanded math presented by Paul Bourke: -// See http:'local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ - -/** - * Checks if two Lines intersect. If the Lines are identical, they will be treated as parallel and thus non-intersecting. - * - * @function Phaser.Geom.Intersects.LineToLine - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line1 - The first Line to check. - * @param {Phaser.Geom.Line} line2 - The second Line to check. - * @param {Phaser.Geom.Point} [out] - A Point in which to optionally store the point of intersection. - * - * @return {boolean} `true` if the two Lines intersect, and the `out` object will be populated, if given. Otherwise, `false`. - */ -var LineToLine = function (line1, line2, out) -{ - if (out === undefined) { out = new Point(); } - - var x1 = line1.x1; - var y1 = line1.y1; - var x2 = line1.x2; - var y2 = line1.y2; - - var x3 = line2.x1; - var y3 = line2.y1; - var x4 = line2.x2; - var y4 = line2.y2; - - var numA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); - var numB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); - var deNom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); - - // 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). - - if (deNom === 0) - { - return false; - } - - // Calculate the intermediate fractional point that the lines potentially intersect. - - var uA = numA / deNom; - var uB = numB / deNom; - - // 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 (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) - { - out.x = x1 + (uA * (x2 - x1)); - out.y = y1 + (uA * (y2 - y1)); - - return true; - } - - return false; -}; - -module.exports = LineToLine; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +// This is based off an explanation and expanded math presented by Paul Bourke: +// See http:'local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ + +/** + * Checks if two Lines intersect. If the Lines are identical, they will be treated as parallel and thus non-intersecting. + * + * @function Phaser.Geom.Intersects.LineToLine + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line1 - The first Line to check. + * @param {Phaser.Geom.Line} line2 - The second Line to check. + * @param {Phaser.Geom.Point} [out] - A Point in which to optionally store the point of intersection. + * + * @return {boolean} `true` if the two Lines intersect, and the `out` object will be populated, if given. Otherwise, `false`. + */ +var LineToLine = function (line1, line2, out) +{ + if (out === undefined) { out = new Point(); } + + var x1 = line1.x1; + var y1 = line1.y1; + var x2 = line1.x2; + var y2 = line1.y2; + + var x3 = line2.x1; + var y3 = line2.y1; + var x4 = line2.x2; + var y4 = line2.y2; + + var numA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); + var numB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); + var deNom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + + // 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). + + if (deNom === 0) + { + return false; + } + + // Calculate the intermediate fractional point that the lines potentially intersect. + + var uA = numA / deNom; + var uB = numB / deNom; + + // 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 (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) + { + out.x = x1 + (uA * (x2 - x1)); + out.y = y1 + (uA * (y2 - y1)); + + return true; + } + + return false; +}; + +module.exports = LineToLine; diff --git a/src/geom/intersects/LineToRectangle.js b/src/geom/intersects/LineToRectangle.js index dd483f23b..ab9031bb2 100644 --- a/src/geom/intersects/LineToRectangle.js +++ b/src/geom/intersects/LineToRectangle.js @@ -1,95 +1,95 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like - * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. - * - * An intersection is considered valid if: - * - * The line starts within, or ends within, the Rectangle. - * The line segment intersects one of the 4 rectangle edges. - * - * The for the purposes of this function rectangles are considered 'solid'. - * - * @function Phaser.Geom.Intersects.LineToRectangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The Line to check for intersection. - * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle to check for intersection. - * - * @return {boolean} `true` if the Line and the Rectangle intersect, `false` otherwise. - */ -var LineToRectangle = function (line, rect) -{ - var x1 = line.x1; - var y1 = line.y1; - - var x2 = line.x2; - var y2 = line.y2; - - var bx1 = rect.x; - var by1 = rect.y; - var bx2 = rect.right; - var by2 = rect.bottom; - - var t = 0; - - // If the start or end of the line is inside the rect then we assume - // collision, as rects are solid for our use-case. - - if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || - (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) - { - return true; - } - - if (x1 < bx1 && x2 >= bx1) - { - // Left edge - t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); - - if (t > by1 && t <= by2) - { - return true; - } - } - else if (x1 > bx2 && x2 <= bx2) - { - // Right edge - t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); - - if (t >= by1 && t <= by2) - { - return true; - } - } - - if (y1 < by1 && y2 >= by1) - { - // Top edge - t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); - - if (t >= bx1 && t <= bx2) - { - return true; - } - } - else if (y1 > by2 && y2 <= by2) - { - // Bottom edge - t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); - - if (t >= bx1 && t <= bx2) - { - return true; - } - } - - return false; -}; - -module.exports = LineToRectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like + * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. + * + * An intersection is considered valid if: + * + * The line starts within, or ends within, the Rectangle. + * The line segment intersects one of the 4 rectangle edges. + * + * The for the purposes of this function rectangles are considered 'solid'. + * + * @function Phaser.Geom.Intersects.LineToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The Line to check for intersection. + * @param {(Phaser.Geom.Rectangle|object)} rect - The Rectangle to check for intersection. + * + * @return {boolean} `true` if the Line and the Rectangle intersect, `false` otherwise. + */ +var LineToRectangle = function (line, rect) +{ + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; +}; + +module.exports = LineToRectangle; diff --git a/src/geom/intersects/PointToLine.js b/src/geom/intersects/PointToLine.js index e783fe496..5a26be6ea 100644 --- a/src/geom/intersects/PointToLine.js +++ b/src/geom/intersects/PointToLine.js @@ -1,64 +1,64 @@ -/** - * @author Richard Davey - * @author Florian Mertens - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if the 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.Geom.Point|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`. - */ -var PointToLine = function (point, line, lineThickness) -{ - if (lineThickness === undefined) { lineThickness = 1; } - - var x1 = line.x1; - var y1 = line.y1; - - var x2 = line.x2; - var y2 = line.y2; - - var px = point.x; - var py = point.y; - - var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); - - if (L2 === 0) - { - return false; - } - - var r = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))) / L2; - - // Assume line thickness is circular - if (r < 0) - { - // Outside line1 - return (Math.sqrt(((x1 - px) * (x1 - px)) + ((y1 - py) * (y1 - py))) <= lineThickness); - } - else if ((r >= 0) && (r <= 1)) - { - // On the line segment - var s = (((y1 - py) * (x2 - x1)) - ((x1 - px) * (y2 - y1))) / L2; - - return (Math.abs(s) * Math.sqrt(L2) <= lineThickness); - } - else - { - // Outside line2 - return (Math.sqrt(((x2 - px) * (x2 - px)) + ((y2 - py) * (y2 - py))) <= lineThickness); - } -}; - -module.exports = PointToLine; +/** + * @author Richard Davey + * @author Florian Mertens + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the 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.Geom.Point|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`. + */ +var PointToLine = function (point, line, lineThickness) +{ + if (lineThickness === undefined) { lineThickness = 1; } + + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var px = point.x; + var py = point.y; + + var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); + + if (L2 === 0) + { + return false; + } + + var r = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))) / L2; + + // Assume line thickness is circular + if (r < 0) + { + // Outside line1 + return (Math.sqrt(((x1 - px) * (x1 - px)) + ((y1 - py) * (y1 - py))) <= lineThickness); + } + else if ((r >= 0) && (r <= 1)) + { + // On the line segment + var s = (((y1 - py) * (x2 - x1)) - ((x1 - px) * (y2 - y1))) / L2; + + return (Math.abs(s) * Math.sqrt(L2) <= lineThickness); + } + else + { + // Outside line2 + return (Math.sqrt(((x2 - px) * (x2 - px)) + ((y2 - py) * (y2 - py))) <= lineThickness); + } +}; + +module.exports = PointToLine; diff --git a/src/geom/intersects/PointToLineSegment.js b/src/geom/intersects/PointToLineSegment.js index bda719df1..d5b7b71b1 100644 --- a/src/geom/intersects/PointToLineSegment.js +++ b/src/geom/intersects/PointToLineSegment.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PointToLine = require('./PointToLine'); - -/** - * Checks if a Point is located on the given line segment. - * - * @function Phaser.Geom.Intersects.PointToLineSegment - * @since 3.0.0 - * - * @param {Phaser.Geom.Point} point - The Point to check for intersection. - * @param {Phaser.Geom.Line} line - The line segment to check for intersection. - * - * @return {boolean} `true` if the Point is on the given line segment, otherwise `false`. - */ -var PointToLineSegment = function (point, line) -{ - if (!PointToLine(point, line)) - { - return false; - } - - var xMin = Math.min(line.x1, line.x2); - var xMax = Math.max(line.x1, line.x2); - var yMin = Math.min(line.y1, line.y2); - var yMax = Math.max(line.y1, line.y2); - - return ((point.x >= xMin && point.x <= xMax) && (point.y >= yMin && point.y <= yMax)); -}; - -module.exports = PointToLineSegment; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PointToLine = require('./PointToLine'); + +/** + * Checks if a Point is located on the given line segment. + * + * @function Phaser.Geom.Intersects.PointToLineSegment + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - The Point to check for intersection. + * @param {Phaser.Geom.Line} line - The line segment to check for intersection. + * + * @return {boolean} `true` if the Point is on the given line segment, otherwise `false`. + */ +var PointToLineSegment = function (point, line) +{ + if (!PointToLine(point, line)) + { + return false; + } + + var xMin = Math.min(line.x1, line.x2); + var xMax = Math.max(line.x1, line.x2); + var yMin = Math.min(line.y1, line.y2); + var yMax = Math.max(line.y1, line.y2); + + return ((point.x >= xMin && point.x <= xMax) && (point.y >= yMin && point.y <= yMax)); +}; + +module.exports = PointToLineSegment; diff --git a/src/geom/intersects/RectangleToRectangle.js b/src/geom/intersects/RectangleToRectangle.js index 6f7a04620..37766feb5 100644 --- a/src/geom/intersects/RectangleToRectangle.js +++ b/src/geom/intersects/RectangleToRectangle.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if two Rectangles intersect. - * - * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. - * As such, the two Rectangles are considered "solid". - * A Rectangle with no width or no height will never intersect another Rectangle. - * - * @function Phaser.Geom.Intersects.RectangleToRectangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. - * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. - * - * @return {boolean} `true` if the two Rectangles intersect, otherwise `false`. - */ -var RectangleToRectangle = function (rectA, rectB) -{ - if (rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) - { - return false; - } - - return !(rectA.right < rectB.x || rectA.bottom < rectB.y || rectA.x > rectB.right || rectA.y > rectB.bottom); -}; - -module.exports = RectangleToRectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if two Rectangles intersect. + * + * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. + * As such, the two Rectangles are considered "solid". + * A Rectangle with no width or no height will never intersect another Rectangle. + * + * @function Phaser.Geom.Intersects.RectangleToRectangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. + * + * @return {boolean} `true` if the two Rectangles intersect, otherwise `false`. + */ +var RectangleToRectangle = function (rectA, rectB) +{ + if (rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) + { + return false; + } + + return !(rectA.right < rectB.x || rectA.bottom < rectB.y || rectA.x > rectB.right || rectA.y > rectB.bottom); +}; + +module.exports = RectangleToRectangle; diff --git a/src/geom/intersects/RectangleToTriangle.js b/src/geom/intersects/RectangleToTriangle.js index 7ddfb5a1b..8644733cf 100644 --- a/src/geom/intersects/RectangleToTriangle.js +++ b/src/geom/intersects/RectangleToTriangle.js @@ -1,87 +1,87 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var LineToLine = require('./LineToLine'); -var Contains = require('../rectangle/Contains'); -var ContainsArray = require('../triangle/ContainsArray'); -var Decompose = require('../rectangle/Decompose'); - -/** - * Checks for intersection between Rectangle shape and Triangle shape. - * - * @function Phaser.Geom.Intersects.RectangleToTriangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - Rectangle object to test. - * @param {Phaser.Geom.Triangle} triangle - Triangle object to test. - * - * @return {boolean} A value of `true` if objects intersect; otherwise `false`. - */ -var RectangleToTriangle = function (rect, triangle) -{ - // First the cheapest ones: - - if ( - triangle.left > rect.right || - triangle.right < rect.left || - triangle.top > rect.bottom || - triangle.bottom < rect.top) - { - return false; - } - - var triA = triangle.getLineA(); - var triB = triangle.getLineB(); - var triC = triangle.getLineC(); - - // Are any of the triangle points within the rectangle? - - if (Contains(rect, triA.x1, triA.y1) || Contains(rect, triA.x2, triA.y2)) - { - return true; - } - - if (Contains(rect, triB.x1, triB.y1) || Contains(rect, triB.x2, triB.y2)) - { - return true; - } - - if (Contains(rect, triC.x1, triC.y1) || Contains(rect, triC.x2, triC.y2)) - { - return true; - } - - // Cheap tests over, now to see if any of the lines intersect ... - - var rectA = rect.getLineA(); - var rectB = rect.getLineB(); - var rectC = rect.getLineC(); - var rectD = rect.getLineD(); - - if (LineToLine(triA, rectA) || LineToLine(triA, rectB) || LineToLine(triA, rectC) || LineToLine(triA, rectD)) - { - return true; - } - - if (LineToLine(triB, rectA) || LineToLine(triB, rectB) || LineToLine(triB, rectC) || LineToLine(triB, rectD)) - { - return true; - } - - if (LineToLine(triC, rectA) || LineToLine(triC, rectB) || LineToLine(triC, rectC) || LineToLine(triC, rectD)) - { - return true; - } - - // None of the lines intersect, so are any rectangle points within the triangle? - - var points = Decompose(rect); - var within = ContainsArray(triangle, points, true); - - return (within.length > 0); -}; - -module.exports = RectangleToTriangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LineToLine = require('./LineToLine'); +var Contains = require('../rectangle/Contains'); +var ContainsArray = require('../triangle/ContainsArray'); +var Decompose = require('../rectangle/Decompose'); + +/** + * Checks for intersection between Rectangle shape and Triangle shape. + * + * @function Phaser.Geom.Intersects.RectangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - Rectangle object to test. + * @param {Phaser.Geom.Triangle} triangle - Triangle object to test. + * + * @return {boolean} A value of `true` if objects intersect; otherwise `false`. + */ +var RectangleToTriangle = function (rect, triangle) +{ + // First the cheapest ones: + + if ( + triangle.left > rect.right || + triangle.right < rect.left || + triangle.top > rect.bottom || + triangle.bottom < rect.top) + { + return false; + } + + var triA = triangle.getLineA(); + var triB = triangle.getLineB(); + var triC = triangle.getLineC(); + + // Are any of the triangle points within the rectangle? + + if (Contains(rect, triA.x1, triA.y1) || Contains(rect, triA.x2, triA.y2)) + { + return true; + } + + if (Contains(rect, triB.x1, triB.y1) || Contains(rect, triB.x2, triB.y2)) + { + return true; + } + + if (Contains(rect, triC.x1, triC.y1) || Contains(rect, triC.x2, triC.y2)) + { + return true; + } + + // Cheap tests over, now to see if any of the lines intersect ... + + var rectA = rect.getLineA(); + var rectB = rect.getLineB(); + var rectC = rect.getLineC(); + var rectD = rect.getLineD(); + + if (LineToLine(triA, rectA) || LineToLine(triA, rectB) || LineToLine(triA, rectC) || LineToLine(triA, rectD)) + { + return true; + } + + if (LineToLine(triB, rectA) || LineToLine(triB, rectB) || LineToLine(triB, rectC) || LineToLine(triB, rectD)) + { + return true; + } + + if (LineToLine(triC, rectA) || LineToLine(triC, rectB) || LineToLine(triC, rectC) || LineToLine(triC, rectD)) + { + return true; + } + + // None of the lines intersect, so are any rectangle points within the triangle? + + var points = Decompose(rect); + var within = ContainsArray(triangle, points, true); + + return (within.length > 0); +}; + +module.exports = RectangleToTriangle; diff --git a/src/geom/intersects/RectangleToValues.js b/src/geom/intersects/RectangleToValues.js index e6668c906..b3ab43c6b 100644 --- a/src/geom/intersects/RectangleToValues.js +++ b/src/geom/intersects/RectangleToValues.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check if rectangle intersects with values. - * - * @function Phaser.Geom.Intersects.RectangleToValues - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The rectangle object - * @param {number} left - The x coordinate of the left of the Rectangle. - * @param {number} right - The x coordinate of the right of the Rectangle. - * @param {number} top - The y coordinate of the top of the Rectangle. - * @param {number} bottom - The y coordinate of the bottom of the Rectangle. - * @param {number} [tolerance=0] - Tolerance allowed in the calculation, expressed in pixels. - * - * @return {boolean} Returns true if there is an intersection. - */ -var RectangleToValues = function (rect, left, right, top, bottom, tolerance) -{ - if (tolerance === undefined) { tolerance = 0; } - - return !( - left > rect.right + tolerance || - right < rect.left - tolerance || - top > rect.bottom + tolerance || - bottom < rect.top - tolerance - ); -}; - -module.exports = RectangleToValues; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check if rectangle intersects with values. + * + * @function Phaser.Geom.Intersects.RectangleToValues + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle object + * @param {number} left - The x coordinate of the left of the Rectangle. + * @param {number} right - The x coordinate of the right of the Rectangle. + * @param {number} top - The y coordinate of the top of the Rectangle. + * @param {number} bottom - The y coordinate of the bottom of the Rectangle. + * @param {number} [tolerance=0] - Tolerance allowed in the calculation, expressed in pixels. + * + * @return {boolean} Returns true if there is an intersection. + */ +var RectangleToValues = function (rect, left, right, top, bottom, tolerance) +{ + if (tolerance === undefined) { tolerance = 0; } + + return !( + left > rect.right + tolerance || + right < rect.left - tolerance || + top > rect.bottom + tolerance || + bottom < rect.top - tolerance + ); +}; + +module.exports = RectangleToValues; diff --git a/src/geom/intersects/TriangleToCircle.js b/src/geom/intersects/TriangleToCircle.js index 7a8e6f271..a187c7a03 100644 --- a/src/geom/intersects/TriangleToCircle.js +++ b/src/geom/intersects/TriangleToCircle.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var LineToCircle = require('./LineToCircle'); -var Contains = require('../triangle/Contains'); - -/** - * Checks if a Triangle and a Circle intersect. - * - * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. - * - * @function Phaser.Geom.Intersects.TriangleToCircle - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to check for intersection. - * @param {Phaser.Geom.Circle} circle - The Circle to check for intersection. - * - * @return {boolean} `true` if the Triangle and the `Circle` intersect, otherwise `false`. - */ -var TriangleToCircle = function (triangle, circle) -{ - // First the cheapest ones: - - if ( - triangle.left > circle.right || - triangle.right < circle.left || - triangle.top > circle.bottom || - triangle.bottom < circle.top) - { - return false; - } - - if (Contains(triangle, circle.x, circle.y)) - { - return true; - } - - if (LineToCircle(triangle.getLineA(), circle)) - { - return true; - } - - if (LineToCircle(triangle.getLineB(), circle)) - { - return true; - } - - if (LineToCircle(triangle.getLineC(), circle)) - { - return true; - } - - return false; -}; - -module.exports = TriangleToCircle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LineToCircle = require('./LineToCircle'); +var Contains = require('../triangle/Contains'); + +/** + * Checks if a Triangle and a Circle intersect. + * + * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. + * + * @function Phaser.Geom.Intersects.TriangleToCircle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check for intersection. + * @param {Phaser.Geom.Circle} circle - The Circle to check for intersection. + * + * @return {boolean} `true` if the Triangle and the `Circle` intersect, otherwise `false`. + */ +var TriangleToCircle = function (triangle, circle) +{ + // First the cheapest ones: + + if ( + triangle.left > circle.right || + triangle.right < circle.left || + triangle.top > circle.bottom || + triangle.bottom < circle.top) + { + return false; + } + + if (Contains(triangle, circle.x, circle.y)) + { + return true; + } + + if (LineToCircle(triangle.getLineA(), circle)) + { + return true; + } + + if (LineToCircle(triangle.getLineB(), circle)) + { + return true; + } + + if (LineToCircle(triangle.getLineC(), circle)) + { + return true; + } + + return false; +}; + +module.exports = TriangleToCircle; diff --git a/src/geom/intersects/TriangleToLine.js b/src/geom/intersects/TriangleToLine.js index ea15569d8..be4762359 100644 --- a/src/geom/intersects/TriangleToLine.js +++ b/src/geom/intersects/TriangleToLine.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('../triangle/Contains'); -var LineToLine = require('./LineToLine'); - -/** - * Checks if a Triangle and a Line intersect. - * - * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". - * - * @function Phaser.Geom.Intersects.TriangleToLine - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to check with. - * @param {Phaser.Geom.Line} line - The Line to check with. - * - * @return {boolean} `true` if the Triangle and the Line intersect, otherwise `false`. - */ -var TriangleToLine = function (triangle, line) -{ - // If the Triangle contains either the start or end point of the line, it intersects - if (Contains(triangle, line.getPointA()) || Contains(triangle, line.getPointB())) - { - return true; - } - - // Now check the line against each line of the Triangle - if (LineToLine(triangle.getLineA(), line)) - { - return true; - } - - if (LineToLine(triangle.getLineB(), line)) - { - return true; - } - - if (LineToLine(triangle.getLineC(), line)) - { - return true; - } - - return false; -}; - -module.exports = TriangleToLine; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('../triangle/Contains'); +var LineToLine = require('./LineToLine'); + +/** + * Checks if a Triangle and a Line intersect. + * + * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". + * + * @function Phaser.Geom.Intersects.TriangleToLine + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check with. + * @param {Phaser.Geom.Line} line - The Line to check with. + * + * @return {boolean} `true` if the Triangle and the Line intersect, otherwise `false`. + */ +var TriangleToLine = function (triangle, line) +{ + // If the Triangle contains either the start or end point of the line, it intersects + if (Contains(triangle, line.getPointA()) || Contains(triangle, line.getPointB())) + { + return true; + } + + // Now check the line against each line of the Triangle + if (LineToLine(triangle.getLineA(), line)) + { + return true; + } + + if (LineToLine(triangle.getLineB(), line)) + { + return true; + } + + if (LineToLine(triangle.getLineC(), line)) + { + return true; + } + + return false; +}; + +module.exports = TriangleToLine; diff --git a/src/geom/intersects/TriangleToTriangle.js b/src/geom/intersects/TriangleToTriangle.js index 69ae8421a..38dff806b 100644 --- a/src/geom/intersects/TriangleToTriangle.js +++ b/src/geom/intersects/TriangleToTriangle.js @@ -1,84 +1,84 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ContainsArray = require('../triangle/ContainsArray'); -var Decompose = require('../triangle/Decompose'); -var LineToLine = require('./LineToLine'); - -/** - * Checks if two Triangles intersect. - * - * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". - * - * @function Phaser.Geom.Intersects.TriangleToTriangle - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangleA - The first Triangle to check for intersection. - * @param {Phaser.Geom.Triangle} triangleB - The second Triangle to check for intersection. - * - * @return {boolean} `true` if the Triangles intersect, otherwise `false`. - */ -var TriangleToTriangle = function (triangleA, triangleB) -{ - // First the cheapest ones: - - if ( - triangleA.left > triangleB.right || - triangleA.right < triangleB.left || - triangleA.top > triangleB.bottom || - triangleA.bottom < triangleB.top) - { - return false; - } - - var lineAA = triangleA.getLineA(); - var lineAB = triangleA.getLineB(); - var lineAC = triangleA.getLineC(); - - var lineBA = triangleB.getLineA(); - var lineBB = triangleB.getLineB(); - var lineBC = triangleB.getLineC(); - - // Now check the lines against each line of TriangleB - if (LineToLine(lineAA, lineBA) || LineToLine(lineAA, lineBB) || LineToLine(lineAA, lineBC)) - { - return true; - } - - if (LineToLine(lineAB, lineBA) || LineToLine(lineAB, lineBB) || LineToLine(lineAB, lineBC)) - { - return true; - } - - if (LineToLine(lineAC, lineBA) || LineToLine(lineAC, lineBB) || LineToLine(lineAC, lineBC)) - { - return true; - } - - // Nope, so check to see if any of the points of triangleA are within triangleB - - var points = Decompose(triangleA); - var within = ContainsArray(triangleB, points, true); - - if (within.length > 0) - { - return true; - } - - // Finally check to see if any of the points of triangleB are within triangleA - - points = Decompose(triangleB); - within = ContainsArray(triangleA, points, true); - - if (within.length > 0) - { - return true; - } - - return false; -}; - -module.exports = TriangleToTriangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ContainsArray = require('../triangle/ContainsArray'); +var Decompose = require('../triangle/Decompose'); +var LineToLine = require('./LineToLine'); + +/** + * Checks if two Triangles intersect. + * + * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". + * + * @function Phaser.Geom.Intersects.TriangleToTriangle + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangleA - The first Triangle to check for intersection. + * @param {Phaser.Geom.Triangle} triangleB - The second Triangle to check for intersection. + * + * @return {boolean} `true` if the Triangles intersect, otherwise `false`. + */ +var TriangleToTriangle = function (triangleA, triangleB) +{ + // First the cheapest ones: + + if ( + triangleA.left > triangleB.right || + triangleA.right < triangleB.left || + triangleA.top > triangleB.bottom || + triangleA.bottom < triangleB.top) + { + return false; + } + + var lineAA = triangleA.getLineA(); + var lineAB = triangleA.getLineB(); + var lineAC = triangleA.getLineC(); + + var lineBA = triangleB.getLineA(); + var lineBB = triangleB.getLineB(); + var lineBC = triangleB.getLineC(); + + // Now check the lines against each line of TriangleB + if (LineToLine(lineAA, lineBA) || LineToLine(lineAA, lineBB) || LineToLine(lineAA, lineBC)) + { + return true; + } + + if (LineToLine(lineAB, lineBA) || LineToLine(lineAB, lineBB) || LineToLine(lineAB, lineBC)) + { + return true; + } + + if (LineToLine(lineAC, lineBA) || LineToLine(lineAC, lineBB) || LineToLine(lineAC, lineBC)) + { + return true; + } + + // Nope, so check to see if any of the points of triangleA are within triangleB + + var points = Decompose(triangleA); + var within = ContainsArray(triangleB, points, true); + + if (within.length > 0) + { + return true; + } + + // Finally check to see if any of the points of triangleB are within triangleA + + points = Decompose(triangleB); + within = ContainsArray(triangleA, points, true); + + if (within.length > 0) + { + return true; + } + + return false; +}; + +module.exports = TriangleToTriangle; diff --git a/src/geom/intersects/index.js b/src/geom/intersects/index.js index e5e9c656b..39d945c91 100644 --- a/src/geom/intersects/index.js +++ b/src/geom/intersects/index.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Geom.Intersects - */ - -module.exports = { - - CircleToCircle: require('./CircleToCircle'), - CircleToRectangle: require('./CircleToRectangle'), - GetCircleToCircle: require('./GetCircleToCircle'), - GetCircleToRectangle: require('./GetCircleToRectangle'), - GetLineToCircle: require('./GetLineToCircle'), - GetLineToRectangle: require('./GetLineToRectangle'), - GetRectangleIntersection: require('./GetRectangleIntersection'), - GetRectangleToRectangle: require('./GetRectangleToRectangle'), - GetRectangleToTriangle: require('./GetRectangleToTriangle'), - GetTriangleToCircle: require('./GetTriangleToCircle'), - GetTriangleToLine: require('./GetTriangleToLine'), - GetTriangleToTriangle: require('./GetTriangleToTriangle'), - LineToCircle: require('./LineToCircle'), - LineToLine: require('./LineToLine'), - LineToRectangle: require('./LineToRectangle'), - PointToLine: require('./PointToLine'), - PointToLineSegment: require('./PointToLineSegment'), - RectangleToRectangle: require('./RectangleToRectangle'), - RectangleToTriangle: require('./RectangleToTriangle'), - RectangleToValues: require('./RectangleToValues'), - TriangleToCircle: require('./TriangleToCircle'), - TriangleToLine: require('./TriangleToLine'), - TriangleToTriangle: require('./TriangleToTriangle') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Geom.Intersects + */ + +module.exports = { + + CircleToCircle: require('./CircleToCircle'), + CircleToRectangle: require('./CircleToRectangle'), + GetCircleToCircle: require('./GetCircleToCircle'), + GetCircleToRectangle: require('./GetCircleToRectangle'), + GetLineToCircle: require('./GetLineToCircle'), + GetLineToRectangle: require('./GetLineToRectangle'), + GetRectangleIntersection: require('./GetRectangleIntersection'), + GetRectangleToRectangle: require('./GetRectangleToRectangle'), + GetRectangleToTriangle: require('./GetRectangleToTriangle'), + GetTriangleToCircle: require('./GetTriangleToCircle'), + GetTriangleToLine: require('./GetTriangleToLine'), + GetTriangleToTriangle: require('./GetTriangleToTriangle'), + LineToCircle: require('./LineToCircle'), + LineToLine: require('./LineToLine'), + LineToRectangle: require('./LineToRectangle'), + PointToLine: require('./PointToLine'), + PointToLineSegment: require('./PointToLineSegment'), + RectangleToRectangle: require('./RectangleToRectangle'), + RectangleToTriangle: require('./RectangleToTriangle'), + RectangleToValues: require('./RectangleToValues'), + TriangleToCircle: require('./TriangleToCircle'), + TriangleToLine: require('./TriangleToLine'), + TriangleToTriangle: require('./TriangleToTriangle') + +}; diff --git a/src/geom/line/Angle.js b/src/geom/line/Angle.js index 772fb79de..ecc4bcc16 100644 --- a/src/geom/line/Angle.js +++ b/src/geom/line/Angle.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the angle of the line in radians. - * - * @function Phaser.Geom.Line.Angle - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the angle of. - * - * @return {number} The angle of the line, in radians. - */ -var Angle = function (line) -{ - return Math.atan2(line.y2 - line.y1, line.x2 - line.x1); -}; - -module.exports = Angle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the angle of the line in radians. + * + * @function Phaser.Geom.Line.Angle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the angle of. + * + * @return {number} The angle of the line, in radians. + */ +var Angle = function (line) +{ + return Math.atan2(line.y2 - line.y1, line.x2 - line.x1); +}; + +module.exports = Angle; diff --git a/src/geom/line/BresenhamPoints.js b/src/geom/line/BresenhamPoints.js index 5192320b0..89e13b9a1 100644 --- a/src/geom/line/BresenhamPoints.js +++ b/src/geom/line/BresenhamPoints.js @@ -1,68 +1,68 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Using Bresenham's line algorithm this will return an array of all coordinates on this line. - * - * The `start` and `end` points are rounded before this runs as the algorithm works on integers. - * - * @function Phaser.Geom.Line.BresenhamPoints - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line. - * @param {integer} [stepRate=1] - The optional step rate for the points on the line. - * @param {Phaser.Types.Math.Vector2Like[]} [results] - An optional array to push the resulting coordinates into. - * - * @return {Phaser.Types.Math.Vector2Like[]} The array of coordinates on the line. - */ -var BresenhamPoints = function (line, stepRate, results) -{ - if (stepRate === undefined) { stepRate = 1; } - if (results === undefined) { results = []; } - - var x1 = Math.round(line.x1); - var y1 = Math.round(line.y1); - var x2 = Math.round(line.x2); - var y2 = Math.round(line.y2); - - var dx = Math.abs(x2 - x1); - var dy = Math.abs(y2 - y1); - var sx = (x1 < x2) ? 1 : -1; - var sy = (y1 < y2) ? 1 : -1; - var err = dx - dy; - - results.push({ x: x1, y: y1 }); - - var i = 1; - - while (!((x1 === x2) && (y1 === y2))) - { - var e2 = err << 1; - - if (e2 > -dy) - { - err -= dy; - x1 += sx; - } - - if (e2 < dx) - { - err += dx; - y1 += sy; - } - - if (i % stepRate === 0) - { - results.push({ x: x1, y: y1 }); - } - - i++; - } - - return results; -}; - -module.exports = BresenhamPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * + * The `start` and `end` points are rounded before this runs as the algorithm works on integers. + * + * @function Phaser.Geom.Line.BresenhamPoints + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line. + * @param {integer} [stepRate=1] - The optional step rate for the points on the line. + * @param {Phaser.Types.Math.Vector2Like[]} [results] - An optional array to push the resulting coordinates into. + * + * @return {Phaser.Types.Math.Vector2Like[]} The array of coordinates on the line. + */ +var BresenhamPoints = function (line, stepRate, results) +{ + if (stepRate === undefined) { stepRate = 1; } + if (results === undefined) { results = []; } + + var x1 = Math.round(line.x1); + var y1 = Math.round(line.y1); + var x2 = Math.round(line.x2); + var y2 = Math.round(line.y2); + + var dx = Math.abs(x2 - x1); + var dy = Math.abs(y2 - y1); + var sx = (x1 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push({ x: x1, y: y1 }); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push({ x: x1, y: y1 }); + } + + i++; + } + + return results; +}; + +module.exports = BresenhamPoints; diff --git a/src/geom/line/CenterOn.js b/src/geom/line/CenterOn.js index d425336bd..6634fc4c1 100644 --- a/src/geom/line/CenterOn.js +++ b/src/geom/line/CenterOn.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - - -/** - * Center a line on the given coordinates. - * - * @function Phaser.Geom.Line.CenterOn - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to center. - * @param {number} x - The horizontal coordinate to center the line on. - * @param {number} y - The vertical coordinate to center the line on. - * - * @return {Phaser.Geom.Line} The centered line. - */ -var CenterOn = function (line, x, y) -{ - var tx = x - ((line.x1 + line.x2) / 2); - var ty = y - ((line.y1 + line.y2) / 2); - - line.x1 += tx; - line.y1 += ty; - - line.x2 += tx; - line.y2 += ty; - - return line; -}; - -module.exports = CenterOn; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + + +/** + * Center a line on the given coordinates. + * + * @function Phaser.Geom.Line.CenterOn + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to center. + * @param {number} x - The horizontal coordinate to center the line on. + * @param {number} y - The vertical coordinate to center the line on. + * + * @return {Phaser.Geom.Line} The centered line. + */ +var CenterOn = function (line, x, y) +{ + var tx = x - ((line.x1 + line.x2) / 2); + var ty = y - ((line.y1 + line.y2) / 2); + + line.x1 += tx; + line.y1 += ty; + + line.x2 += tx; + line.y2 += ty; + + return line; +}; + +module.exports = CenterOn; diff --git a/src/geom/line/Clone.js b/src/geom/line/Clone.js index 993648c14..9122294fa 100644 --- a/src/geom/line/Clone.js +++ b/src/geom/line/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Line = require('./Line'); - -/** - * Clone the given line. - * - * @function Phaser.Geom.Line.Clone - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} source - The source line to clone. - * - * @return {Phaser.Geom.Line} The cloned line. - */ -var Clone = function (source) -{ - return new Line(source.x1, source.y1, source.x2, source.y2); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Line = require('./Line'); + +/** + * Clone the given line. + * + * @function Phaser.Geom.Line.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} source - The source line to clone. + * + * @return {Phaser.Geom.Line} The cloned line. + */ +var Clone = function (source) +{ + return new Line(source.x1, source.y1, source.x2, source.y2); +}; + +module.exports = Clone; diff --git a/src/geom/line/CopyFrom.js b/src/geom/line/CopyFrom.js index 382e37803..2e2e4f89f 100644 --- a/src/geom/line/CopyFrom.js +++ b/src/geom/line/CopyFrom.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Copy the values of one line to a destination line. - * - * @function Phaser.Geom.Line.CopyFrom - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [dest,$return] - * - * @param {Phaser.Geom.Line} source - The source line to copy the values from. - * @param {Phaser.Geom.Line} dest - The destination line to copy the values to. - * - * @return {Phaser.Geom.Line} The destination line. - */ -var CopyFrom = function (source, dest) -{ - return dest.setTo(source.x1, source.y1, source.x2, source.y2); -}; - -module.exports = CopyFrom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one line to a destination line. + * + * @function Phaser.Geom.Line.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [dest,$return] + * + * @param {Phaser.Geom.Line} source - The source line to copy the values from. + * @param {Phaser.Geom.Line} dest - The destination line to copy the values to. + * + * @return {Phaser.Geom.Line} The destination line. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x1, source.y1, source.x2, source.y2); +}; + +module.exports = CopyFrom; diff --git a/src/geom/line/Equals.js b/src/geom/line/Equals.js index 1f596ba45..b2c88e6a8 100644 --- a/src/geom/line/Equals.js +++ b/src/geom/line/Equals.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compare two lines for strict equality. - * - * @function Phaser.Geom.Line.Equals - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The first line to compare. - * @param {Phaser.Geom.Line} toCompare - The second line to compare. - * - * @return {boolean} Whether the two lines are equal. - */ -var Equals = function (line, toCompare) -{ - return ( - line.x1 === toCompare.x1 && - line.y1 === toCompare.y1 && - line.x2 === toCompare.x2 && - line.y2 === toCompare.y2 - ); -}; - -module.exports = Equals; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compare two lines for strict equality. + * + * @function Phaser.Geom.Line.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The first line to compare. + * @param {Phaser.Geom.Line} toCompare - The second line to compare. + * + * @return {boolean} Whether the two lines are equal. + */ +var Equals = function (line, toCompare) +{ + return ( + line.x1 === toCompare.x1 && + line.y1 === toCompare.y1 && + line.x2 === toCompare.x2 && + line.y2 === toCompare.y2 + ); +}; + +module.exports = Equals; diff --git a/src/geom/line/Extend.js b/src/geom/line/Extend.js index a2634967e..92c05e2fd 100644 --- a/src/geom/line/Extend.js +++ b/src/geom/line/Extend.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Length = require('./Length'); - -/** - * Extends the start and end points of a Line by the given amounts. - * - * The amounts can be positive or negative. Positive points will increase the length of the line, - * while negative ones will decrease it. - * - * If no `right` value is provided it will extend the length of the line equally in both directions. - * - * Pass a value of zero to leave the start or end point unchanged. - * - * @function Phaser.Geom.Line.Extend - * @since 3.16.0 - * - * @param {Phaser.Geom.Line} line - The line instance to extend. - * @param {number} left - The amount to extend the start of the line by. - * @param {number} [right] - The amount to extend the end of the line by. If not given it will be set to the `left` value. - * - * @return {Phaser.Geom.Line} The modified Line instance. - */ -var Extend = function (line, left, right) -{ - if (right === undefined) { right = left; } - - var length = Length(line); - - var slopX = line.x2 - line.x1; - var slopY = line.y2 - line.y1; - - if (left) - { - line.x1 = line.x1 - slopX / length * left; - line.y1 = line.y1 - slopY / length * left; - } - - if (right) - { - line.x2 = line.x2 + slopX / length * right; - line.y2 = line.y2 + slopY / length * right; - } - - return line; -}; - -module.exports = Extend; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = require('./Length'); + +/** + * Extends the start and end points of a Line by the given amounts. + * + * The amounts can be positive or negative. Positive points will increase the length of the line, + * while negative ones will decrease it. + * + * If no `right` value is provided it will extend the length of the line equally in both directions. + * + * Pass a value of zero to leave the start or end point unchanged. + * + * @function Phaser.Geom.Line.Extend + * @since 3.16.0 + * + * @param {Phaser.Geom.Line} line - The line instance to extend. + * @param {number} left - The amount to extend the start of the line by. + * @param {number} [right] - The amount to extend the end of the line by. If not given it will be set to the `left` value. + * + * @return {Phaser.Geom.Line} The modified Line instance. + */ +var Extend = function (line, left, right) +{ + if (right === undefined) { right = left; } + + var length = Length(line); + + var slopX = line.x2 - line.x1; + var slopY = line.y2 - line.y1; + + if (left) + { + line.x1 = line.x1 - slopX / length * left; + line.y1 = line.y1 - slopY / length * left; + } + + if (right) + { + line.x2 = line.x2 + slopX / length * right; + line.y2 = line.y2 + slopY / length * right; + } + + return line; +}; + +module.exports = Extend; diff --git a/src/geom/line/GetEasedPoints.js b/src/geom/line/GetEasedPoints.js index f8b82d357..05c8fcf4a 100644 --- a/src/geom/line/GetEasedPoints.js +++ b/src/geom/line/GetEasedPoints.js @@ -1,114 +1,114 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var DistanceBetweenPoints = require('../../math/distance/DistanceBetweenPoints'); -var GetEaseFunction = require('../../tweens/builders/GetEaseFunction'); -var Point = require('../point/Point'); - -/** - * 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.Geom.Point[]} 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 {integer} 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 noisey eases. - * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. - * - * @return {Phaser.Geom.Point[]} An array of Geom.Points containing the coordinates of the points on the line. - */ -var GetEasedPoints = function (line, ease, quantity, collinearThreshold, easeParams) -{ - if (collinearThreshold === undefined) { collinearThreshold = 0; } - if (easeParams === undefined) { easeParams = []; } - - var results = []; - - var x1 = line.x1; - var y1 = line.y1; - - var spaceX = line.x2 - x1; - var spaceY = line.y2 - y1; - - var easeFunc = GetEaseFunction(ease, easeParams); - - var i; - var v; - var q = quantity - 1; - - for (i = 0; i < q; i++) - { - v = easeFunc(i / q); - - results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); - } - - // Always include the end of the line - v = easeFunc(1); - - results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); - - // Remove collinear parts - if (collinearThreshold > 0) - { - var prevPoint = results[0]; - - // Store the new results here - var sortedResults = [ prevPoint ]; - - for (i = 1; i < results.length - 1; i++) - { - var point = results[i]; - - if (DistanceBetweenPoints(prevPoint, point) >= collinearThreshold) - { - sortedResults.push(point); - prevPoint = point; - } - } - - // Top and tail - var endPoint = results[results.length - 1]; - - if (DistanceBetweenPoints(prevPoint, endPoint) < collinearThreshold) - { - sortedResults.pop(); - } - - sortedResults.push(endPoint); - - return sortedResults; - } - else - { - return results; - } -}; - -module.exports = GetEasedPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var DistanceBetweenPoints = require('../../math/distance/DistanceBetweenPoints'); +var GetEaseFunction = require('../../tweens/builders/GetEaseFunction'); +var Point = require('../point/Point'); + +/** + * 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.Geom.Point[]} 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 {integer} 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 noisey eases. + * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * + * @return {Phaser.Geom.Point[]} An array of Geom.Points containing the coordinates of the points on the line. + */ +var GetEasedPoints = function (line, ease, quantity, collinearThreshold, easeParams) +{ + if (collinearThreshold === undefined) { collinearThreshold = 0; } + if (easeParams === undefined) { easeParams = []; } + + var results = []; + + var x1 = line.x1; + var y1 = line.y1; + + var spaceX = line.x2 - x1; + var spaceY = line.y2 - y1; + + var easeFunc = GetEaseFunction(ease, easeParams); + + var i; + var v; + var q = quantity - 1; + + for (i = 0; i < q; i++) + { + v = easeFunc(i / q); + + results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); + } + + // Always include the end of the line + v = easeFunc(1); + + results.push(new Point(x1 + (spaceX * v), y1 + (spaceY * v))); + + // Remove collinear parts + if (collinearThreshold > 0) + { + var prevPoint = results[0]; + + // Store the new results here + var sortedResults = [ prevPoint ]; + + for (i = 1; i < results.length - 1; i++) + { + var point = results[i]; + + if (DistanceBetweenPoints(prevPoint, point) >= collinearThreshold) + { + sortedResults.push(point); + prevPoint = point; + } + } + + // Top and tail + var endPoint = results[results.length - 1]; + + if (DistanceBetweenPoints(prevPoint, endPoint) < collinearThreshold) + { + sortedResults.pop(); + } + + sortedResults.push(endPoint); + + return sortedResults; + } + else + { + return results; + } +}; + +module.exports = GetEasedPoints; diff --git a/src/geom/line/GetMidPoint.js b/src/geom/line/GetMidPoint.js index 87e802778..5638a9ac1 100644 --- a/src/geom/line/GetMidPoint.js +++ b/src/geom/line/GetMidPoint.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Get the midpoint of the given line. - * - * @function Phaser.Geom.Line.GetMidPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The line to get the midpoint of. - * @param {(Phaser.Geom.Point|object)} [out] - An optional point object to store the midpoint in. - * - * @return {(Phaser.Geom.Point|object)} The midpoint of the Line. - */ -var GetMidPoint = function (line, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = (line.x1 + line.x2) / 2; - out.y = (line.y1 + line.y2) / 2; - - return out; -}; - -module.exports = GetMidPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Get the midpoint of the given line. + * + * @function Phaser.Geom.Line.GetMidPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to get the midpoint of. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point object to store the midpoint in. + * + * @return {(Phaser.Geom.Point|object)} The midpoint of the Line. + */ +var GetMidPoint = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = (line.x1 + line.x2) / 2; + out.y = (line.y1 + line.y2) / 2; + + return out; +}; + +module.exports = GetMidPoint; diff --git a/src/geom/line/GetNearestPoint.js b/src/geom/line/GetNearestPoint.js index 0bf695059..416709ade 100644 --- a/src/geom/line/GetNearestPoint.js +++ b/src/geom/line/GetNearestPoint.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @author Florian Mertens - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Get the nearest point on a line perpendicular to the given point. - * - * @function Phaser.Geom.Line.GetNearestPoint - * @since 3.16.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The line to get the nearest point on. - * @param {(Phaser.Geom.Point|object)} point - The point to get the nearest point to. - * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the nearest point on the line. - * - * @return {(Phaser.Geom.Point|object)} The nearest point on the line. - */ -var GetNearestPoint = function (line, point, out) -{ - if (out === undefined) { out = new Point(); } - - var x1 = line.x1; - var y1 = line.y1; - - var x2 = line.x2; - var y2 = line.y2; - - var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); - - if (L2 === 0) - { - return out; - } - - var r = (((point.x - x1) * (x2 - x1)) + ((point.y - y1) * (y2 - y1))) / L2; - - out.x = x1 + (r * (x2 - x1)); - out.y = y1 + (r * (y2 - y1)); - - return out; -}; - -module.exports = GetNearestPoint; +/** + * @author Richard Davey + * @author Florian Mertens + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Get the nearest point on a line perpendicular to the given point. + * + * @function Phaser.Geom.Line.GetNearestPoint + * @since 3.16.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to get the nearest point on. + * @param {(Phaser.Geom.Point|object)} point - The point to get the nearest point to. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the nearest point on the line. + * + * @return {(Phaser.Geom.Point|object)} The nearest point on the line. + */ +var GetNearestPoint = function (line, point, out) +{ + if (out === undefined) { out = new Point(); } + + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); + + if (L2 === 0) + { + return out; + } + + var r = (((point.x - x1) * (x2 - x1)) + ((point.y - y1) * (y2 - y1))) / L2; + + out.x = x1 + (r * (x2 - x1)); + out.y = y1 + (r * (y2 - y1)); + + return out; +}; + +module.exports = GetNearestPoint; diff --git a/src/geom/line/GetNormal.js b/src/geom/line/GetNormal.js index ce62b7b02..fc61e382a 100644 --- a/src/geom/line/GetNormal.js +++ b/src/geom/line/GetNormal.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = require('../../math/const'); -var Angle = require('./Angle'); -var Point = require('../point/Point'); - -/** - * Calculate the normal of the given line. - * - * The normal of a line is a vector that points perpendicular from it. - * - * @function Phaser.Geom.Line.GetNormal - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The line to calculate the normal of. - * @param {(Phaser.Geom.Point|object)} [out] - An optional point object to store the normal in. - * - * @return {(Phaser.Geom.Point|object)} The normal of the Line. - */ -var GetNormal = function (line, out) -{ - if (out === undefined) { out = new Point(); } - - var a = Angle(line) - MATH_CONST.TAU; - - out.x = Math.cos(a); - out.y = Math.sin(a); - - return out; -}; - -module.exports = GetNormal; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = require('../../math/const'); +var Angle = require('./Angle'); +var Point = require('../point/Point'); + +/** + * Calculate the normal of the given line. + * + * The normal of a line is a vector that points perpendicular from it. + * + * @function Phaser.Geom.Line.GetNormal + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to calculate the normal of. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point object to store the normal in. + * + * @return {(Phaser.Geom.Point|object)} The normal of the Line. + */ +var GetNormal = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + var a = Angle(line) - MATH_CONST.TAU; + + out.x = Math.cos(a); + out.y = Math.sin(a); + + return out; +}; + +module.exports = GetNormal; diff --git a/src/geom/line/GetPoint.js b/src/geom/line/GetPoint.js index c66cfbb76..7a8fec968 100644 --- a/src/geom/line/GetPoint.js +++ b/src/geom/line/GetPoint.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Get a point on a line that's a given percentage along its length. - * - * @function Phaser.Geom.Line.GetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The line. - * @param {number} position - A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. - * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the point on the line. - * - * @return {(Phaser.Geom.Point|object)} The point on the line. - */ -var GetPoint = function (line, position, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = line.x1 + (line.x2 - line.x1) * position; - out.y = line.y1 + (line.y2 - line.y1) * position; - - return out; -}; - -module.exports = GetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Get a point on a line that's a given percentage along its length. + * + * @function Phaser.Geom.Line.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line. + * @param {number} position - A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. + * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the point on the line. + * + * @return {(Phaser.Geom.Point|object)} The point on the line. + */ +var GetPoint = function (line, position, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = line.x1 + (line.x2 - line.x1) * position; + out.y = line.y1 + (line.y2 - line.y1) * position; + + return out; +}; + +module.exports = GetPoint; diff --git a/src/geom/line/GetPoints.js b/src/geom/line/GetPoints.js index a7cbb5952..9a181f694 100644 --- a/src/geom/line/GetPoints.js +++ b/src/geom/line/GetPoints.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Length = require('./Length'); -var Point = require('../point/Point'); - -/** - * Get a number of points along a line's length. - * - * Provide a `quantity` to get an exact number of points along the line. - * - * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when - * providing a `stepRate`. - * - * @function Phaser.Geom.Line.GetPoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point[]} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The line. - * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. - * @param {number} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. - * @param {(array|Phaser.Geom.Point[])} [out] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. - * - * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. - */ -var GetPoints = function (line, quantity, stepRate, out) -{ - if (out === undefined) { out = []; } - - // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!quantity) - { - quantity = Length(line) / stepRate; - } - - var x1 = line.x1; - var y1 = line.y1; - - var x2 = line.x2; - var y2 = line.y2; - - for (var i = 0; i < quantity; i++) - { - var position = i / quantity; - - var x = x1 + (x2 - x1) * position; - var y = y1 + (y2 - y1) * position; - - out.push(new Point(x, y)); - } - - return out; -}; - -module.exports = GetPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = require('./Length'); +var Point = require('../point/Point'); + +/** + * Get a number of points along a line's length. + * + * Provide a `quantity` to get an exact number of points along the line. + * + * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when + * providing a `stepRate`. + * + * @function Phaser.Geom.Line.GetPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line. + * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. + * @param {number} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. + * @param {(array|Phaser.Geom.Point[])} [out] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. + * + * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. + */ +var GetPoints = function (line, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Length(line) / stepRate; + } + + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + for (var i = 0; i < quantity; i++) + { + var position = i / quantity; + + var x = x1 + (x2 - x1) * position; + var y = y1 + (y2 - y1) * position; + + out.push(new Point(x, y)); + } + + return out; +}; + +module.exports = GetPoints; diff --git a/src/geom/line/GetShortestDistance.js b/src/geom/line/GetShortestDistance.js index 0087bcc6b..620f50301 100644 --- a/src/geom/line/GetShortestDistance.js +++ b/src/geom/line/GetShortestDistance.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @author Florian Mertens - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Get the shortest distance from a Line to the given Point. - * - * @function Phaser.Geom.Line.GetShortestDistance - * @since 3.16.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The line to get the distance from. - * @param {(Phaser.Geom.Point|object)} point - The point to get the shortest distance to. - * - * @return {number} The shortest distance from the line to the point. - */ -var GetShortestDistance = function (line, point) -{ - var x1 = line.x1; - var y1 = line.y1; - - var x2 = line.x2; - var y2 = line.y2; - - var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); - - if (L2 === 0) - { - return false; - } - - var s = (((y1 - point.y) * (x2 - x1)) - ((x1 - point.x) * (y2 - y1))) / L2; - - return Math.abs(s) * Math.sqrt(L2); -}; - -module.exports = GetShortestDistance; +/** + * @author Richard Davey + * @author Florian Mertens + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Get the shortest distance from a Line to the given Point. + * + * @function Phaser.Geom.Line.GetShortestDistance + * @since 3.16.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The line to get the distance from. + * @param {(Phaser.Geom.Point|object)} point - The point to get the shortest distance to. + * + * @return {number} The shortest distance from the line to the point. + */ +var GetShortestDistance = function (line, point) +{ + var x1 = line.x1; + var y1 = line.y1; + + var x2 = line.x2; + var y2 = line.y2; + + var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); + + if (L2 === 0) + { + return false; + } + + var s = (((y1 - point.y) * (x2 - x1)) - ((x1 - point.x) * (y2 - y1))) / L2; + + return Math.abs(s) * Math.sqrt(L2); +}; + +module.exports = GetShortestDistance; diff --git a/src/geom/line/Height.js b/src/geom/line/Height.js index f35bdd09e..b1110e309 100644 --- a/src/geom/line/Height.js +++ b/src/geom/line/Height.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the height of the given line. - * - * @function Phaser.Geom.Line.Height - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the height of. - * - * @return {number} The height of the line. - */ -var Height = function (line) -{ - return Math.abs(line.y1 - line.y2); -}; - -module.exports = Height; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the height of the given line. + * + * @function Phaser.Geom.Line.Height + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the height of. + * + * @return {number} The height of the line. + */ +var Height = function (line) +{ + return Math.abs(line.y1 - line.y2); +}; + +module.exports = Height; diff --git a/src/geom/line/Length.js b/src/geom/line/Length.js index 116623f47..200a2f9a3 100644 --- a/src/geom/line/Length.js +++ b/src/geom/line/Length.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the length of the given line. - * - * @function Phaser.Geom.Line.Length - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the length of. - * - * @return {number} The length of the line. - */ -var Length = function (line) -{ - return Math.sqrt((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1)); -}; - -module.exports = Length; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the length of the given line. + * + * @function Phaser.Geom.Line.Length + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the length of. + * + * @return {number} The length of the line. + */ +var Length = function (line) +{ + return Math.sqrt((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1)); +}; + +module.exports = Length; diff --git a/src/geom/line/Line.js b/src/geom/line/Line.js index 4114e5e38..7a33a9080 100644 --- a/src/geom/line/Line.js +++ b/src/geom/line/Line.js @@ -1,331 +1,331 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetPoint = require('./GetPoint'); -var GetPoints = require('./GetPoints'); -var GEOM_CONST = require('../const'); -var Random = require('./Random'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * Defines a Line segment, a part of a line between two endpoints. - * - * @class Line - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {number} [x1=0] - The x coordinate of the lines starting point. - * @param {number} [y1=0] - The y coordinate of the lines starting point. - * @param {number} [x2=0] - The x coordinate of the lines ending point. - * @param {number} [y2=0] - The y coordinate of the lines ending point. - */ -var Line = new Class({ - - initialize: - - function Line (x1, y1, x2, y2) - { - if (x1 === undefined) { x1 = 0; } - if (y1 === undefined) { y1 = 0; } - if (x2 === undefined) { x2 = 0; } - if (y2 === undefined) { y2 = 0; } - - /** - * The geometry constant type of this object: `GEOM_CONST.LINE`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Line#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.LINE; - - /** - * The x coordinate of the lines starting point. - * - * @name Phaser.Geom.Line#x1 - * @type {number} - * @since 3.0.0 - */ - this.x1 = x1; - - /** - * The y coordinate of the lines starting point. - * - * @name Phaser.Geom.Line#y1 - * @type {number} - * @since 3.0.0 - */ - this.y1 = y1; - - /** - * The x coordinate of the lines ending point. - * - * @name Phaser.Geom.Line#x2 - * @type {number} - * @since 3.0.0 - */ - this.x2 = x2; - - /** - * The y coordinate of the lines ending point. - * - * @name Phaser.Geom.Line#y2 - * @type {number} - * @since 3.0.0 - */ - this.y2 = y2; - }, - - /** - * Get a point on a line that's a given percentage along its length. - * - * @method Phaser.Geom.Line#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [output,$return] - * - * @param {number} position - A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. - * @param {(Phaser.Geom.Point|object)} [output] - An optional point, or point-like object, to store the coordinates of the point on the line. - * - * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point on the line. - */ - getPoint: function (position, output) - { - return GetPoint(this, position, output); - }, - - /** - * Get a number of points along a line's length. - * - * Provide a `quantity` to get an exact number of points along the line. - * - * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when - * providing a `stepRate`. - * - * @method Phaser.Geom.Line#getPoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point[]} O - [output,$return] - * - * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. - * @param {integer} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. - * @param {(array|Phaser.Geom.Point[])} [output] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. - * - * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. - */ - getPoints: function (quantity, stepRate, output) - { - return GetPoints(this, quantity, stepRate, output); - }, - - /** - * Get a random Point on the Line. - * - * @method Phaser.Geom.Line#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {(Phaser.Geom.Point|object)} [point] - An instance of a Point to be modified. - * - * @return {Phaser.Geom.Point} A random Point on the Line. - */ - getRandomPoint: function (point) - { - return Random(this, point); - }, - - /** - * Set new coordinates for the line endpoints. - * - * @method Phaser.Geom.Line#setTo - * @since 3.0.0 - * - * @param {number} [x1=0] - The x coordinate of the lines starting point. - * @param {number} [y1=0] - The y coordinate of the lines starting point. - * @param {number} [x2=0] - The x coordinate of the lines ending point. - * @param {number} [y2=0] - The y coordinate of the lines ending point. - * - * @return {Phaser.Geom.Line} This Line object. - */ - setTo: function (x1, y1, x2, y2) - { - if (x1 === undefined) { x1 = 0; } - if (y1 === undefined) { y1 = 0; } - if (x2 === undefined) { x2 = 0; } - if (y2 === undefined) { y2 = 0; } - - this.x1 = x1; - this.y1 = y1; - - this.x2 = x2; - this.y2 = y2; - - return this; - }, - - /** - * Returns a Vector2 object that corresponds to the start of this Line. - * - * @method Phaser.Geom.Line#getPointA - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [vec2,$return] - * - * @param {Phaser.Math.Vector2} [vec2] - A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. - * - * @return {Phaser.Math.Vector2} A Vector2 object that corresponds to the start of this Line. - */ - getPointA: function (vec2) - { - if (vec2 === undefined) { vec2 = new Vector2(); } - - vec2.set(this.x1, this.y1); - - return vec2; - }, - - /** - * Returns a Vector2 object that corresponds to the end of this Line. - * - * @method Phaser.Geom.Line#getPointB - * @since 3.0.0 - * - * @generic {Phaser.Math.Vector2} O - [vec2,$return] - * - * @param {Phaser.Math.Vector2} [vec2] - A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. - * - * @return {Phaser.Math.Vector2} A Vector2 object that corresponds to the end of this Line. - */ - getPointB: function (vec2) - { - if (vec2 === undefined) { vec2 = new Vector2(); } - - vec2.set(this.x2, this.y2); - - return vec2; - }, - - /** - * The left position of the Line. - * - * @name Phaser.Geom.Line#left - * @type {number} - * @since 3.0.0 - */ - left: { - - get: function () - { - return Math.min(this.x1, this.x2); - }, - - set: function (value) - { - if (this.x1 <= this.x2) - { - this.x1 = value; - } - else - { - this.x2 = value; - } - } - - }, - - /** - * The right position of the Line. - * - * @name Phaser.Geom.Line#right - * @type {number} - * @since 3.0.0 - */ - right: { - - get: function () - { - return Math.max(this.x1, this.x2); - }, - - set: function (value) - { - if (this.x1 > this.x2) - { - this.x1 = value; - } - else - { - this.x2 = value; - } - } - - }, - - /** - * The top position of the Line. - * - * @name Phaser.Geom.Line#top - * @type {number} - * @since 3.0.0 - */ - top: { - - get: function () - { - return Math.min(this.y1, this.y2); - }, - - set: function (value) - { - if (this.y1 <= this.y2) - { - this.y1 = value; - } - else - { - this.y2 = value; - } - } - - }, - - /** - * The bottom position of the Line. - * - * @name Phaser.Geom.Line#bottom - * @type {number} - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return Math.max(this.y1, this.y2); - }, - - set: function (value) - { - if (this.y1 > this.y2) - { - this.y1 = value; - } - else - { - this.y2 = value; - } - } - - } - -}); - -module.exports = Line; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetPoint = require('./GetPoint'); +var GetPoints = require('./GetPoints'); +var GEOM_CONST = require('../const'); +var Random = require('./Random'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * Defines a Line segment, a part of a line between two endpoints. + * + * @class Line + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x1=0] - The x coordinate of the lines starting point. + * @param {number} [y1=0] - The y coordinate of the lines starting point. + * @param {number} [x2=0] - The x coordinate of the lines ending point. + * @param {number} [y2=0] - The y coordinate of the lines ending point. + */ +var Line = new Class({ + + initialize: + + function Line (x1, y1, x2, y2) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.LINE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Line#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.LINE; + + /** + * The x coordinate of the lines starting point. + * + * @name Phaser.Geom.Line#x1 + * @type {number} + * @since 3.0.0 + */ + this.x1 = x1; + + /** + * The y coordinate of the lines starting point. + * + * @name Phaser.Geom.Line#y1 + * @type {number} + * @since 3.0.0 + */ + this.y1 = y1; + + /** + * The x coordinate of the lines ending point. + * + * @name Phaser.Geom.Line#x2 + * @type {number} + * @since 3.0.0 + */ + this.x2 = x2; + + /** + * The y coordinate of the lines ending point. + * + * @name Phaser.Geom.Line#y2 + * @type {number} + * @since 3.0.0 + */ + this.y2 = y2; + }, + + /** + * Get a point on a line that's a given percentage along its length. + * + * @method Phaser.Geom.Line#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [output,$return] + * + * @param {number} position - A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. + * @param {(Phaser.Geom.Point|object)} [output] - An optional point, or point-like object, to store the coordinates of the point on the line. + * + * @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point on the line. + */ + getPoint: function (position, output) + { + return GetPoint(this, position, output); + }, + + /** + * Get a number of points along a line's length. + * + * Provide a `quantity` to get an exact number of points along the line. + * + * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when + * providing a `stepRate`. + * + * @method Phaser.Geom.Line#getPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [output,$return] + * + * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. + * @param {integer} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. + * @param {(array|Phaser.Geom.Point[])} [output] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. + * + * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Get a random Point on the Line. + * + * @method Phaser.Geom.Line#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {(Phaser.Geom.Point|object)} [point] - An instance of a Point to be modified. + * + * @return {Phaser.Geom.Point} A random Point on the Line. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Set new coordinates for the line endpoints. + * + * @method Phaser.Geom.Line#setTo + * @since 3.0.0 + * + * @param {number} [x1=0] - The x coordinate of the lines starting point. + * @param {number} [y1=0] - The y coordinate of the lines starting point. + * @param {number} [x2=0] - The x coordinate of the lines ending point. + * @param {number} [y2=0] - The y coordinate of the lines ending point. + * + * @return {Phaser.Geom.Line} This Line object. + */ + setTo: function (x1, y1, x2, y2) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + + this.x1 = x1; + this.y1 = y1; + + this.x2 = x2; + this.y2 = y2; + + return this; + }, + + /** + * Returns a Vector2 object that corresponds to the start of this Line. + * + * @method Phaser.Geom.Line#getPointA + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [vec2,$return] + * + * @param {Phaser.Math.Vector2} [vec2] - A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. + * + * @return {Phaser.Math.Vector2} A Vector2 object that corresponds to the start of this Line. + */ + getPointA: function (vec2) + { + if (vec2 === undefined) { vec2 = new Vector2(); } + + vec2.set(this.x1, this.y1); + + return vec2; + }, + + /** + * Returns a Vector2 object that corresponds to the end of this Line. + * + * @method Phaser.Geom.Line#getPointB + * @since 3.0.0 + * + * @generic {Phaser.Math.Vector2} O - [vec2,$return] + * + * @param {Phaser.Math.Vector2} [vec2] - A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. + * + * @return {Phaser.Math.Vector2} A Vector2 object that corresponds to the end of this Line. + */ + getPointB: function (vec2) + { + if (vec2 === undefined) { vec2 = new Vector2(); } + + vec2.set(this.x2, this.y2); + + return vec2; + }, + + /** + * The left position of the Line. + * + * @name Phaser.Geom.Line#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return Math.min(this.x1, this.x2); + }, + + set: function (value) + { + if (this.x1 <= this.x2) + { + this.x1 = value; + } + else + { + this.x2 = value; + } + } + + }, + + /** + * The right position of the Line. + * + * @name Phaser.Geom.Line#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return Math.max(this.x1, this.x2); + }, + + set: function (value) + { + if (this.x1 > this.x2) + { + this.x1 = value; + } + else + { + this.x2 = value; + } + } + + }, + + /** + * The top position of the Line. + * + * @name Phaser.Geom.Line#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return Math.min(this.y1, this.y2); + }, + + set: function (value) + { + if (this.y1 <= this.y2) + { + this.y1 = value; + } + else + { + this.y2 = value; + } + } + + }, + + /** + * The bottom position of the Line. + * + * @name Phaser.Geom.Line#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return Math.max(this.y1, this.y2); + }, + + set: function (value) + { + if (this.y1 > this.y2) + { + this.y1 = value; + } + else + { + this.y2 = value; + } + } + + } + +}); + +module.exports = Line; diff --git a/src/geom/line/NormalAngle.js b/src/geom/line/NormalAngle.js index 80eda7992..eee6ea812 100644 --- a/src/geom/line/NormalAngle.js +++ b/src/geom/line/NormalAngle.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = require('../../math/const'); -var Wrap = require('../../math/Wrap'); -var Angle = require('./Angle'); - -/** - * Get the angle of the normal of the given line in radians. - * - * @function Phaser.Geom.Line.NormalAngle - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the angle of the normal of. - * - * @return {number} The angle of the normal of the line in radians. - */ -var NormalAngle = function (line) -{ - var angle = Angle(line) - MATH_CONST.TAU; - - return Wrap(angle, -Math.PI, Math.PI); -}; - -module.exports = NormalAngle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = require('../../math/const'); +var Wrap = require('../../math/Wrap'); +var Angle = require('./Angle'); + +/** + * Get the angle of the normal of the given line in radians. + * + * @function Phaser.Geom.Line.NormalAngle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the angle of the normal of. + * + * @return {number} The angle of the normal of the line in radians. + */ +var NormalAngle = function (line) +{ + var angle = Angle(line) - MATH_CONST.TAU; + + return Wrap(angle, -Math.PI, Math.PI); +}; + +module.exports = NormalAngle; diff --git a/src/geom/line/NormalX.js b/src/geom/line/NormalX.js index 8cb0a3d84..5cc86b8bd 100644 --- a/src/geom/line/NormalX.js +++ b/src/geom/line/NormalX.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = require('../../math/const'); -var Angle = require('./Angle'); - -/** - * Returns the x component of the normal vector of the given line. - * - * @function Phaser.Geom.Line.NormalX - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The Line object to get the normal value from. - * - * @return {number} The x component of the normal vector of the line. - */ -var NormalX = function (line) -{ - return Math.cos(Angle(line) - MATH_CONST.TAU); -}; - -module.exports = NormalX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = require('../../math/const'); +var Angle = require('./Angle'); + +/** + * Returns the x component of the normal vector of the given line. + * + * @function Phaser.Geom.Line.NormalX + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The Line object to get the normal value from. + * + * @return {number} The x component of the normal vector of the line. + */ +var NormalX = function (line) +{ + return Math.cos(Angle(line) - MATH_CONST.TAU); +}; + +module.exports = NormalX; diff --git a/src/geom/line/NormalY.js b/src/geom/line/NormalY.js index 23e5fea92..b807e9542 100644 --- a/src/geom/line/NormalY.js +++ b/src/geom/line/NormalY.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = require('../../math/const'); -var Angle = require('./Angle'); - -/** - * The Y value of the normal of the given line. - * The normal of a line is a vector that points perpendicular from it. - * - * @function Phaser.Geom.Line.NormalY - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the normal of. - * - * @return {number} The Y value of the normal of the Line. - */ -var NormalY = function (line) -{ - return Math.sin(Angle(line) - MATH_CONST.TAU); -}; - -module.exports = NormalY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = require('../../math/const'); +var Angle = require('./Angle'); + +/** + * The Y value of the normal of the given line. + * The normal of a line is a vector that points perpendicular from it. + * + * @function Phaser.Geom.Line.NormalY + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the normal of. + * + * @return {number} The Y value of the normal of the Line. + */ +var NormalY = function (line) +{ + return Math.sin(Angle(line) - MATH_CONST.TAU); +}; + +module.exports = NormalY; diff --git a/src/geom/line/Offset.js b/src/geom/line/Offset.js index f38f1d443..79198ea80 100644 --- a/src/geom/line/Offset.js +++ b/src/geom/line/Offset.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Offset a line by the given amount. - * - * @function Phaser.Geom.Line.Offset - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} line - The line to offset. - * @param {number} x - The horizontal offset to add to the line. - * @param {number} y - The vertical offset to add to the line. - * - * @return {Phaser.Geom.Line} The offset line. - */ -var Offset = function (line, x, y) -{ - line.x1 += x; - line.y1 += y; - - line.x2 += x; - line.y2 += y; - - return line; -}; - -module.exports = Offset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Offset a line by the given amount. + * + * @function Phaser.Geom.Line.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to offset. + * @param {number} x - The horizontal offset to add to the line. + * @param {number} y - The vertical offset to add to the line. + * + * @return {Phaser.Geom.Line} The offset line. + */ +var Offset = function (line, x, y) +{ + line.x1 += x; + line.y1 += y; + + line.x2 += x; + line.y2 += y; + + return line; +}; + +module.exports = Offset; diff --git a/src/geom/line/PerpSlope.js b/src/geom/line/PerpSlope.js index 8a82aadec..098eeb9f5 100644 --- a/src/geom/line/PerpSlope.js +++ b/src/geom/line/PerpSlope.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the perpendicular slope of the given line. - * - * @function Phaser.Geom.Line.PerpSlope - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the perpendicular slope of. - * - * @return {number} The perpendicular slope of the line. - */ -var PerpSlope = function (line) -{ - return -((line.x2 - line.x1) / (line.y2 - line.y1)); -}; - -module.exports = PerpSlope; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the perpendicular slope of the given line. + * + * @function Phaser.Geom.Line.PerpSlope + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the perpendicular slope of. + * + * @return {number} The perpendicular slope of the line. + */ +var PerpSlope = function (line) +{ + return -((line.x2 - line.x1) / (line.y2 - line.y1)); +}; + +module.exports = PerpSlope; diff --git a/src/geom/line/Random.js b/src/geom/line/Random.js index f56db0223..fa4ad2dae 100644 --- a/src/geom/line/Random.js +++ b/src/geom/line/Random.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a random point on a given Line. - * - * @function Phaser.Geom.Line.Random - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Line} line - The Line to calculate the random Point on. - * @param {(Phaser.Geom.Point|object)} [out] - An instance of a Point to be modified. - * - * @return {(Phaser.Geom.Point|object)} A random Point on the Line. - */ -var Random = function (line, out) -{ - if (out === undefined) { out = new Point(); } - - var t = Math.random(); - - out.x = line.x1 + t * (line.x2 - line.x1); - out.y = line.y1 + t * (line.y2 - line.y1); - - return out; -}; - -module.exports = Random; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a random point on a given Line. + * + * @function Phaser.Geom.Line.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The Line to calculate the random Point on. + * @param {(Phaser.Geom.Point|object)} [out] - An instance of a Point to be modified. + * + * @return {(Phaser.Geom.Point|object)} A random Point on the Line. + */ +var Random = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + var t = Math.random(); + + out.x = line.x1 + t * (line.x2 - line.x1); + out.y = line.y1 + t * (line.y2 - line.y1); + + return out; +}; + +module.exports = Random; diff --git a/src/geom/line/ReflectAngle.js b/src/geom/line/ReflectAngle.js index af90f37d7..1c5060589 100644 --- a/src/geom/line/ReflectAngle.js +++ b/src/geom/line/ReflectAngle.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Angle = require('./Angle'); -var NormalAngle = require('./NormalAngle'); - -/** - * Calculate the reflected angle between two lines. - * - * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. - * - * @function Phaser.Geom.Line.ReflectAngle - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} lineA - The first line. - * @param {Phaser.Geom.Line} lineB - The second line. - * - * @return {number} The reflected angle between each line. - */ -var ReflectAngle = function (lineA, lineB) -{ - return (2 * NormalAngle(lineB) - Math.PI - Angle(lineA)); -}; - -module.exports = ReflectAngle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Angle = require('./Angle'); +var NormalAngle = require('./NormalAngle'); + +/** + * Calculate the reflected angle between two lines. + * + * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. + * + * @function Phaser.Geom.Line.ReflectAngle + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} lineA - The first line. + * @param {Phaser.Geom.Line} lineB - The second line. + * + * @return {number} The reflected angle between each line. + */ +var ReflectAngle = function (lineA, lineB) +{ + return (2 * NormalAngle(lineB) - Math.PI - Angle(lineA)); +}; + +module.exports = ReflectAngle; diff --git a/src/geom/line/Rotate.js b/src/geom/line/Rotate.js index 7afcb30f5..8c772eaaf 100644 --- a/src/geom/line/Rotate.js +++ b/src/geom/line/Rotate.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateAroundXY = require('./RotateAroundXY'); - -/** - * Rotate a line around its midpoint by the given angle in radians. - * - * @function Phaser.Geom.Line.Rotate - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} line - The line to rotate. - * @param {number} angle - The angle of rotation in radians. - * - * @return {Phaser.Geom.Line} The rotated line. - */ -var Rotate = function (line, angle) -{ - var x = (line.x1 + line.x2) / 2; - var y = (line.y1 + line.y2) / 2; - - return RotateAroundXY(line, x, y, angle); -}; - -module.exports = Rotate; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = require('./RotateAroundXY'); + +/** + * Rotate a line around its midpoint by the given angle in radians. + * + * @function Phaser.Geom.Line.Rotate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to rotate. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Line} The rotated line. + */ +var Rotate = function (line, angle) +{ + var x = (line.x1 + line.x2) / 2; + var y = (line.y1 + line.y2) / 2; + + return RotateAroundXY(line, x, y, angle); +}; + +module.exports = Rotate; diff --git a/src/geom/line/RotateAroundPoint.js b/src/geom/line/RotateAroundPoint.js index 894355bf2..16cd34e84 100644 --- a/src/geom/line/RotateAroundPoint.js +++ b/src/geom/line/RotateAroundPoint.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateAroundXY = require('./RotateAroundXY'); - -/** - * Rotate a line around a point by the given angle in radians. - * - * @function Phaser.Geom.Line.RotateAroundPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} line - The line to rotate. - * @param {(Phaser.Geom.Point|object)} point - The point to rotate the line around. - * @param {number} angle - The angle of rotation in radians. - * - * @return {Phaser.Geom.Line} The rotated line. - */ -var RotateAroundPoint = function (line, point, angle) -{ - return RotateAroundXY(line, point.x, point.y, angle); -}; - -module.exports = RotateAroundPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = require('./RotateAroundXY'); + +/** + * Rotate a line around a point by the given angle in radians. + * + * @function Phaser.Geom.Line.RotateAroundPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to rotate. + * @param {(Phaser.Geom.Point|object)} point - The point to rotate the line around. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Line} The rotated line. + */ +var RotateAroundPoint = function (line, point, angle) +{ + return RotateAroundXY(line, point.x, point.y, angle); +}; + +module.exports = RotateAroundPoint; diff --git a/src/geom/line/RotateAroundXY.js b/src/geom/line/RotateAroundXY.js index 63669f6b3..fdeb55fac 100644 --- a/src/geom/line/RotateAroundXY.js +++ b/src/geom/line/RotateAroundXY.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rotate a line around the given coordinates by the given angle in radians. - * - * @function Phaser.Geom.Line.RotateAroundXY - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} line - The line to rotate. - * @param {number} x - The horizontal coordinate to rotate the line around. - * @param {number} y - The vertical coordinate to rotate the line around. - * @param {number} angle - The angle of rotation in radians. - * - * @return {Phaser.Geom.Line} The rotated line. - */ -var RotateAroundXY = function (line, x, y, angle) -{ - var c = Math.cos(angle); - var s = Math.sin(angle); - - var tx = line.x1 - x; - var ty = line.y1 - y; - - line.x1 = tx * c - ty * s + x; - line.y1 = tx * s + ty * c + y; - - tx = line.x2 - x; - ty = line.y2 - y; - - line.x2 = tx * c - ty * s + x; - line.y2 = tx * s + ty * c + y; - - return line; -}; - -module.exports = RotateAroundXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a line around the given coordinates by the given angle in radians. + * + * @function Phaser.Geom.Line.RotateAroundXY + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to rotate. + * @param {number} x - The horizontal coordinate to rotate the line around. + * @param {number} y - The vertical coordinate to rotate the line around. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Line} The rotated line. + */ +var RotateAroundXY = function (line, x, y, angle) +{ + var c = Math.cos(angle); + var s = Math.sin(angle); + + var tx = line.x1 - x; + var ty = line.y1 - y; + + line.x1 = tx * c - ty * s + x; + line.y1 = tx * s + ty * c + y; + + tx = line.x2 - x; + ty = line.y2 - y; + + line.x2 = tx * c - ty * s + x; + line.y2 = tx * s + ty * c + y; + + return line; +}; + +module.exports = RotateAroundXY; diff --git a/src/geom/line/SetToAngle.js b/src/geom/line/SetToAngle.js index cc061a1df..cf41af872 100644 --- a/src/geom/line/SetToAngle.js +++ b/src/geom/line/SetToAngle.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Set a line to a given position, angle and length. - * - * @function Phaser.Geom.Line.SetToAngle - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} line - The line to set. - * @param {number} x - The horizontal start position of the line. - * @param {number} y - The vertical start position of the line. - * @param {number} angle - The angle of the line in radians. - * @param {number} length - The length of the line. - * - * @return {Phaser.Geom.Line} The updated line. - */ -var SetToAngle = function (line, x, y, angle, length) -{ - line.x1 = x; - line.y1 = y; - - line.x2 = x + (Math.cos(angle) * length); - line.y2 = y + (Math.sin(angle) * length); - - return line; -}; - -module.exports = SetToAngle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Set a line to a given position, angle and length. + * + * @function Phaser.Geom.Line.SetToAngle + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} line - The line to set. + * @param {number} x - The horizontal start position of the line. + * @param {number} y - The vertical start position of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line. + * + * @return {Phaser.Geom.Line} The updated line. + */ +var SetToAngle = function (line, x, y, angle, length) +{ + line.x1 = x; + line.y1 = y; + + line.x2 = x + (Math.cos(angle) * length); + line.y2 = y + (Math.sin(angle) * length); + + return line; +}; + +module.exports = SetToAngle; diff --git a/src/geom/line/Slope.js b/src/geom/line/Slope.js index 8b0b77278..974639bcf 100644 --- a/src/geom/line/Slope.js +++ b/src/geom/line/Slope.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the slope of the given line. - * - * @function Phaser.Geom.Line.Slope - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the slope of. - * - * @return {number} The slope of the line. - */ -var Slope = function (line) -{ - return (line.y2 - line.y1) / (line.x2 - line.x1); -}; - -module.exports = Slope; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the slope of the given line. + * + * @function Phaser.Geom.Line.Slope + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the slope of. + * + * @return {number} The slope of the line. + */ +var Slope = function (line) +{ + return (line.y2 - line.y1) / (line.x2 - line.x1); +}; + +module.exports = Slope; diff --git a/src/geom/line/Width.js b/src/geom/line/Width.js index 83d78b6ee..4de51fcf0 100644 --- a/src/geom/line/Width.js +++ b/src/geom/line/Width.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the width of the given line. - * - * @function Phaser.Geom.Line.Width - * @since 3.0.0 - * - * @param {Phaser.Geom.Line} line - The line to calculate the width of. - * - * @return {number} The width of the line. - */ -var Width = function (line) -{ - return Math.abs(line.x1 - line.x2); -}; - -module.exports = Width; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the width of the given line. + * + * @function Phaser.Geom.Line.Width + * @since 3.0.0 + * + * @param {Phaser.Geom.Line} line - The line to calculate the width of. + * + * @return {number} The width of the line. + */ +var Width = function (line) +{ + return Math.abs(line.x1 - line.x2); +}; + +module.exports = Width; diff --git a/src/geom/line/index.js b/src/geom/line/index.js index 60a5c26f9..90301e7d4 100644 --- a/src/geom/line/index.js +++ b/src/geom/line/index.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Line = require('./Line'); - -Line.Angle = require('./Angle'); -Line.BresenhamPoints = require('./BresenhamPoints'); -Line.CenterOn = require('./CenterOn'); -Line.Clone = require('./Clone'); -Line.CopyFrom = require('./CopyFrom'); -Line.Equals = require('./Equals'); -Line.Extend = require('./Extend'); -Line.GetEasedPoints = require('./GetEasedPoints'); -Line.GetMidPoint = require('./GetMidPoint'); -Line.GetNearestPoint = require('./GetNearestPoint'); -Line.GetNormal = require('./GetNormal'); -Line.GetPoint = require('./GetPoint'); -Line.GetPoints = require('./GetPoints'); -Line.GetShortestDistance = require('./GetShortestDistance'); -Line.Height = require('./Height'); -Line.Length = require('./Length'); -Line.NormalAngle = require('./NormalAngle'); -Line.NormalX = require('./NormalX'); -Line.NormalY = require('./NormalY'); -Line.Offset = require('./Offset'); -Line.PerpSlope = require('./PerpSlope'); -Line.Random = require('./Random'); -Line.ReflectAngle = require('./ReflectAngle'); -Line.Rotate = require('./Rotate'); -Line.RotateAroundPoint = require('./RotateAroundPoint'); -Line.RotateAroundXY = require('./RotateAroundXY'); -Line.SetToAngle = require('./SetToAngle'); -Line.Slope = require('./Slope'); -Line.Width = require('./Width'); - -module.exports = Line; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Line = require('./Line'); + +Line.Angle = require('./Angle'); +Line.BresenhamPoints = require('./BresenhamPoints'); +Line.CenterOn = require('./CenterOn'); +Line.Clone = require('./Clone'); +Line.CopyFrom = require('./CopyFrom'); +Line.Equals = require('./Equals'); +Line.Extend = require('./Extend'); +Line.GetEasedPoints = require('./GetEasedPoints'); +Line.GetMidPoint = require('./GetMidPoint'); +Line.GetNearestPoint = require('./GetNearestPoint'); +Line.GetNormal = require('./GetNormal'); +Line.GetPoint = require('./GetPoint'); +Line.GetPoints = require('./GetPoints'); +Line.GetShortestDistance = require('./GetShortestDistance'); +Line.Height = require('./Height'); +Line.Length = require('./Length'); +Line.NormalAngle = require('./NormalAngle'); +Line.NormalX = require('./NormalX'); +Line.NormalY = require('./NormalY'); +Line.Offset = require('./Offset'); +Line.PerpSlope = require('./PerpSlope'); +Line.Random = require('./Random'); +Line.ReflectAngle = require('./ReflectAngle'); +Line.Rotate = require('./Rotate'); +Line.RotateAroundPoint = require('./RotateAroundPoint'); +Line.RotateAroundXY = require('./RotateAroundXY'); +Line.SetToAngle = require('./SetToAngle'); +Line.Slope = require('./Slope'); +Line.Width = require('./Width'); + +module.exports = Line; diff --git a/src/geom/point/Ceil.js b/src/geom/point/Ceil.js index a39101e68..5800185ab 100644 --- a/src/geom/point/Ceil.js +++ b/src/geom/point/Ceil.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Apply `Math.ceil()` to each coordinate of the given Point. - * - * @function Phaser.Geom.Point.Ceil - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {Phaser.Geom.Point} point - The Point to ceil. - * - * @return {Phaser.Geom.Point} The Point with `Math.ceil()` applied to its coordinates. - */ -var Ceil = function (point) -{ - return point.setTo(Math.ceil(point.x), Math.ceil(point.y)); -}; - -module.exports = Ceil; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Apply `Math.ceil()` to each coordinate of the given Point. + * + * @function Phaser.Geom.Point.Ceil + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to ceil. + * + * @return {Phaser.Geom.Point} The Point with `Math.ceil()` applied to its coordinates. + */ +var Ceil = function (point) +{ + return point.setTo(Math.ceil(point.x), Math.ceil(point.y)); +}; + +module.exports = Ceil; diff --git a/src/geom/point/Clone.js b/src/geom/point/Clone.js index 9d7249fc0..14a3f7cd6 100644 --- a/src/geom/point/Clone.js +++ b/src/geom/point/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); - -/** - * Clone the given Point. - * - * @function Phaser.Geom.Point.Clone - * @since 3.0.0 - * - * @param {Phaser.Geom.Point} source - The source Point to clone. - * - * @return {Phaser.Geom.Point} The cloned Point. - */ -var Clone = function (source) -{ - return new Point(source.x, source.y); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); + +/** + * Clone the given Point. + * + * @function Phaser.Geom.Point.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} source - The source Point to clone. + * + * @return {Phaser.Geom.Point} The cloned Point. + */ +var Clone = function (source) +{ + return new Point(source.x, source.y); +}; + +module.exports = Clone; diff --git a/src/geom/point/CopyFrom.js b/src/geom/point/CopyFrom.js index e71112e39..2a7935219 100644 --- a/src/geom/point/CopyFrom.js +++ b/src/geom/point/CopyFrom.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Copy the values of one Point to a destination Point. - * - * @function Phaser.Geom.Point.CopyFrom - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [dest,$return] - * - * @param {Phaser.Geom.Point} source - The source Point to copy the values from. - * @param {Phaser.Geom.Point} dest - The destination Point to copy the values to. - * - * @return {Phaser.Geom.Point} The destination Point. - */ -var CopyFrom = function (source, dest) -{ - return dest.setTo(source.x, source.y); -}; - -module.exports = CopyFrom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one Point to a destination Point. + * + * @function Phaser.Geom.Point.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [dest,$return] + * + * @param {Phaser.Geom.Point} source - The source Point to copy the values from. + * @param {Phaser.Geom.Point} dest - The destination Point to copy the values to. + * + * @return {Phaser.Geom.Point} The destination Point. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y); +}; + +module.exports = CopyFrom; diff --git a/src/geom/point/Equals.js b/src/geom/point/Equals.js index 3084664ae..d319e1053 100644 --- a/src/geom/point/Equals.js +++ b/src/geom/point/Equals.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A comparison of two `Point` objects to see if they are equal. - * - * @function Phaser.Geom.Point.Equals - * @since 3.0.0 - * - * @param {Phaser.Geom.Point} point - The original `Point` to compare against. - * @param {Phaser.Geom.Point} toCompare - The second `Point` to compare. - * - * @return {boolean} Returns true if the both `Point` objects are equal. - */ -var Equals = function (point, toCompare) -{ - return (point.x === toCompare.x && point.y === toCompare.y); -}; - -module.exports = Equals; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A comparison of two `Point` objects to see if they are equal. + * + * @function Phaser.Geom.Point.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - The original `Point` to compare against. + * @param {Phaser.Geom.Point} toCompare - The second `Point` to compare. + * + * @return {boolean} Returns true if the both `Point` objects are equal. + */ +var Equals = function (point, toCompare) +{ + return (point.x === toCompare.x && point.y === toCompare.y); +}; + +module.exports = Equals; diff --git a/src/geom/point/Floor.js b/src/geom/point/Floor.js index d158f17a0..f54480e71 100644 --- a/src/geom/point/Floor.js +++ b/src/geom/point/Floor.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Apply `Math.ceil()` to each coordinate of the given Point. - * - * @function Phaser.Geom.Point.Floor - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {Phaser.Geom.Point} point - The Point to floor. - * - * @return {Phaser.Geom.Point} The Point with `Math.floor()` applied to its coordinates. - */ -var Floor = function (point) -{ - return point.setTo(Math.floor(point.x), Math.floor(point.y)); -}; - -module.exports = Floor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Apply `Math.ceil()` to each coordinate of the given Point. + * + * @function Phaser.Geom.Point.Floor + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to floor. + * + * @return {Phaser.Geom.Point} The Point with `Math.floor()` applied to its coordinates. + */ +var Floor = function (point) +{ + return point.setTo(Math.floor(point.x), Math.floor(point.y)); +}; + +module.exports = Floor; diff --git a/src/geom/point/GetCentroid.js b/src/geom/point/GetCentroid.js index c081fe4f8..cd676afa3 100644 --- a/src/geom/point/GetCentroid.js +++ b/src/geom/point/GetCentroid.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); - -/** - * Get the centroid or geometric center of a plane figure (the arithmetic mean position of all the points in the figure). - * Informally, it is the point at which a cutout of the shape could be perfectly balanced on the tip of a pin. - * - * @function Phaser.Geom.Point.GetCentroid - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the geometric center of. - * @param {Phaser.Geom.Point} [out] - A Point object to store the output coordinates in. If not given, a new Point instance is created. - * - * @return {Phaser.Geom.Point} A Point object representing the geometric center of the given points. - */ -var GetCentroid = function (points, out) -{ - if (out === undefined) { out = new Point(); } - - if (!Array.isArray(points)) - { - throw new Error('GetCentroid points argument must be an array'); - } - - var len = points.length; - - if (len < 1) - { - throw new Error('GetCentroid points array must not be empty'); - } - else if (len === 1) - { - out.x = points[0].x; - out.y = points[0].y; - } - else - { - for (var i = 0; i < len; i++) - { - out.x += points[i].x; - out.y += points[i].y; - } - - out.x /= len; - out.y /= len; - } - - return out; -}; - -module.exports = GetCentroid; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); + +/** + * Get the centroid or geometric center of a plane figure (the arithmetic mean position of all the points in the figure). + * Informally, it is the point at which a cutout of the shape could be perfectly balanced on the tip of a pin. + * + * @function Phaser.Geom.Point.GetCentroid + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the geometric center of. + * @param {Phaser.Geom.Point} [out] - A Point object to store the output coordinates in. If not given, a new Point instance is created. + * + * @return {Phaser.Geom.Point} A Point object representing the geometric center of the given points. + */ +var GetCentroid = function (points, out) +{ + if (out === undefined) { out = new Point(); } + + if (!Array.isArray(points)) + { + throw new Error('GetCentroid points argument must be an array'); + } + + var len = points.length; + + if (len < 1) + { + throw new Error('GetCentroid points array must not be empty'); + } + else if (len === 1) + { + out.x = points[0].x; + out.y = points[0].y; + } + else + { + for (var i = 0; i < len; i++) + { + out.x += points[i].x; + out.y += points[i].y; + } + + out.x /= len; + out.y /= len; + } + + return out; +}; + +module.exports = GetCentroid; diff --git a/src/geom/point/GetMagnitude.js b/src/geom/point/GetMagnitude.js index 07fae43fc..3fe0bb10b 100644 --- a/src/geom/point/GetMagnitude.js +++ b/src/geom/point/GetMagnitude.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the magnitude of the point, which equivalent to the length of the line from the origin to this point. - * - * @function Phaser.Geom.Point.GetMagnitude - * @since 3.0.0 - * - * @param {Phaser.Geom.Point} point - The point to calculate the magnitude for - * - * @return {number} The resulting magnitude - */ -var GetMagnitude = function (point) -{ - return Math.sqrt((point.x * point.x) + (point.y * point.y)); -}; - -module.exports = GetMagnitude; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the magnitude of the point, which equivalent to the length of the line from the origin to this point. + * + * @function Phaser.Geom.Point.GetMagnitude + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - The point to calculate the magnitude for + * + * @return {number} The resulting magnitude + */ +var GetMagnitude = function (point) +{ + return Math.sqrt((point.x * point.x) + (point.y * point.y)); +}; + +module.exports = GetMagnitude; diff --git a/src/geom/point/GetMagnitudeSq.js b/src/geom/point/GetMagnitudeSq.js index dd80db75b..442073ae0 100644 --- a/src/geom/point/GetMagnitudeSq.js +++ b/src/geom/point/GetMagnitudeSq.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the square of magnitude of given point.(Can be used for fast magnitude calculation of point) - * - * @function Phaser.Geom.Point.GetMagnitudeSq - * @since 3.0.0 - * - * @param {Phaser.Geom.Point} point - Returns square of the magnitude/length of given point. - * - * @return {number} Returns square of the magnitude of given point. - */ -var GetMagnitudeSq = function (point) -{ - return (point.x * point.x) + (point.y * point.y); -}; - -module.exports = GetMagnitudeSq; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the square of magnitude of given point.(Can be used for fast magnitude calculation of point) + * + * @function Phaser.Geom.Point.GetMagnitudeSq + * @since 3.0.0 + * + * @param {Phaser.Geom.Point} point - Returns square of the magnitude/length of given point. + * + * @return {number} Returns square of the magnitude of given point. + */ +var GetMagnitudeSq = function (point) +{ + return (point.x * point.x) + (point.y * point.y); +}; + +module.exports = GetMagnitudeSq; diff --git a/src/geom/point/GetRectangleFromPoints.js b/src/geom/point/GetRectangleFromPoints.js index 3927bbadf..2b64d5381 100644 --- a/src/geom/point/GetRectangleFromPoints.js +++ b/src/geom/point/GetRectangleFromPoints.js @@ -1,64 +1,64 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('../rectangle/Rectangle'); - -/** - * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. - * - * @function Phaser.Geom.Point.GetRectangleFromPoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the AABB from. - * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the results in. If not given, a new Rectangle instance is created. - * - * @return {Phaser.Geom.Rectangle} A Rectangle object holding the AABB values for the given points. - */ -var GetRectangleFromPoints = function (points, out) -{ - if (out === undefined) { out = new Rectangle(); } - - var xMax = Number.NEGATIVE_INFINITY; - var xMin = Number.POSITIVE_INFINITY; - var yMax = Number.NEGATIVE_INFINITY; - var yMin = Number.POSITIVE_INFINITY; - - for (var i = 0; i < points.length; i++) - { - var point = points[i]; - - if (point.x > xMax) - { - xMax = point.x; - } - - if (point.x < xMin) - { - xMin = point.x; - } - - if (point.y > yMax) - { - yMax = point.y; - } - - if (point.y < yMin) - { - yMin = point.y; - } - } - - out.x = xMin; - out.y = yMin; - out.width = xMax - xMin; - out.height = yMax - yMin; - - return out; -}; - -module.exports = GetRectangleFromPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('../rectangle/Rectangle'); + +/** + * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. + * + * @function Phaser.Geom.Point.GetRectangleFromPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the AABB from. + * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the results in. If not given, a new Rectangle instance is created. + * + * @return {Phaser.Geom.Rectangle} A Rectangle object holding the AABB values for the given points. + */ +var GetRectangleFromPoints = function (points, out) +{ + if (out === undefined) { out = new Rectangle(); } + + var xMax = Number.NEGATIVE_INFINITY; + var xMin = Number.POSITIVE_INFINITY; + var yMax = Number.NEGATIVE_INFINITY; + var yMin = Number.POSITIVE_INFINITY; + + for (var i = 0; i < points.length; i++) + { + var point = points[i]; + + if (point.x > xMax) + { + xMax = point.x; + } + + if (point.x < xMin) + { + xMin = point.x; + } + + if (point.y > yMax) + { + yMax = point.y; + } + + if (point.y < yMin) + { + yMin = point.y; + } + } + + out.x = xMin; + out.y = yMin; + out.width = xMax - xMin; + out.height = yMax - yMin; + + return out; +}; + +module.exports = GetRectangleFromPoints; diff --git a/src/geom/point/Interpolate.js b/src/geom/point/Interpolate.js index fcd4e1a90..af3c37027 100644 --- a/src/geom/point/Interpolate.js +++ b/src/geom/point/Interpolate.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); - -/** - * Returns the linear interpolation point between the two given points, based on `t`. - * - * @function Phaser.Geom.Point.Interpolate - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Point} pointA - The starting `Point` for the interpolation. - * @param {Phaser.Geom.Point} pointB - The target `Point` for the interpolation. - * @param {number} [t=0] - The amount to interpolate between the two points. Generally, a value between 0 (returns the starting `Point`) and 1 (returns the target `Point`). If omitted, 0 is used. - * @param {(Phaser.Geom.Point|object)} [out] - An optional `Point` object whose `x` and `y` values will be set to the result of the interpolation (can also be any object with `x` and `y` properties). If omitted, a new `Point` created and returned. - * - * @return {(Phaser.Geom.Point|object)} Either the object from the `out` argument with the properties `x` and `y` set to the result of the interpolation or a newly created `Point` object. - */ -var Interpolate = function (pointA, pointB, t, out) -{ - if (t === undefined) { t = 0; } - if (out === undefined) { out = new Point(); } - - out.x = pointA.x + ((pointB.x - pointA.x) * t); - out.y = pointA.y + ((pointB.y - pointA.y) * t); - - return out; -}; - -module.exports = Interpolate; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); + +/** + * Returns the linear interpolation point between the two given points, based on `t`. + * + * @function Phaser.Geom.Point.Interpolate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} pointA - The starting `Point` for the interpolation. + * @param {Phaser.Geom.Point} pointB - The target `Point` for the interpolation. + * @param {number} [t=0] - The amount to interpolate between the two points. Generally, a value between 0 (returns the starting `Point`) and 1 (returns the target `Point`). If omitted, 0 is used. + * @param {(Phaser.Geom.Point|object)} [out] - An optional `Point` object whose `x` and `y` values will be set to the result of the interpolation (can also be any object with `x` and `y` properties). If omitted, a new `Point` created and returned. + * + * @return {(Phaser.Geom.Point|object)} Either the object from the `out` argument with the properties `x` and `y` set to the result of the interpolation or a newly created `Point` object. + */ +var Interpolate = function (pointA, pointB, t, out) +{ + if (t === undefined) { t = 0; } + if (out === undefined) { out = new Point(); } + + out.x = pointA.x + ((pointB.x - pointA.x) * t); + out.y = pointA.y + ((pointB.y - pointA.y) * t); + + return out; +}; + +module.exports = Interpolate; diff --git a/src/geom/point/Invert.js b/src/geom/point/Invert.js index 698dcdcc4..9ffe901e2 100644 --- a/src/geom/point/Invert.js +++ b/src/geom/point/Invert.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Swaps the X and the Y coordinate of a point. - * - * @function Phaser.Geom.Point.Invert - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {Phaser.Geom.Point} point - The Point to modify. - * - * @return {Phaser.Geom.Point} The modified `point`. - */ -var Invert = function (point) -{ - return point.setTo(point.y, point.x); -}; - -module.exports = Invert; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Swaps the X and the Y coordinate of a point. + * + * @function Phaser.Geom.Point.Invert + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to modify. + * + * @return {Phaser.Geom.Point} The modified `point`. + */ +var Invert = function (point) +{ + return point.setTo(point.y, point.x); +}; + +module.exports = Invert; diff --git a/src/geom/point/Negative.js b/src/geom/point/Negative.js index a013d869f..acb06f6a9 100644 --- a/src/geom/point/Negative.js +++ b/src/geom/point/Negative.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); - -/** - * Inverts a Point's coordinates. - * - * @function Phaser.Geom.Point.Negative - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Point} point - The Point to invert. - * @param {Phaser.Geom.Point} [out] - The Point to return the inverted coordinates in. - * - * @return {Phaser.Geom.Point} The modified `out` Point, or a new Point if none was provided. - */ -var Negative = function (point, out) -{ - if (out === undefined) { out = new Point(); } - - return out.setTo(-point.x, -point.y); -}; - -module.exports = Negative; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); + +/** + * Inverts a Point's coordinates. + * + * @function Phaser.Geom.Point.Negative + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} point - The Point to invert. + * @param {Phaser.Geom.Point} [out] - The Point to return the inverted coordinates in. + * + * @return {Phaser.Geom.Point} The modified `out` Point, or a new Point if none was provided. + */ +var Negative = function (point, out) +{ + if (out === undefined) { out = new Point(); } + + return out.setTo(-point.x, -point.y); +}; + +module.exports = Negative; diff --git a/src/geom/point/Point.js b/src/geom/point/Point.js index 43d0aaea1..00707df56 100644 --- a/src/geom/point/Point.js +++ b/src/geom/point/Point.js @@ -1,87 +1,87 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GEOM_CONST = require('../const'); - -/** - * @classdesc - * Defines a Point in 2D space, with an x and y component. - * - * @class Point - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {number} [x=0] - The x coordinate of this Point. - * @param {number} [y=x] - The y coordinate of this Point. - */ -var Point = new Class({ - - initialize: - - function Point (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - - /** - * The geometry constant type of this object: `GEOM_CONST.POINT`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Point#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.POINT; - - /** - * The x coordinate of this Point. - * - * @name Phaser.Geom.Point#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = x; - - /** - * The y coordinate of this Point. - * - * @name Phaser.Geom.Point#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = y; - }, - - /** - * Set the x and y coordinates of the point to the given values. - * - * @method Phaser.Geom.Point#setTo - * @since 3.0.0 - * - * @param {number} [x=0] - The x coordinate of this Point. - * @param {number} [y=x] - The y coordinate of this Point. - * - * @return {Phaser.Geom.Point} This Point object. - */ - setTo: function (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - - this.x = x; - this.y = y; - - return this; - } - -}); - -module.exports = Point; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GEOM_CONST = require('../const'); + +/** + * @classdesc + * Defines a Point in 2D space, with an x and y component. + * + * @class Point + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The x coordinate of this Point. + * @param {number} [y=x] - The y coordinate of this Point. + */ +var Point = new Class({ + + initialize: + + function Point (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + /** + * The geometry constant type of this object: `GEOM_CONST.POINT`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Point#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.POINT; + + /** + * The x coordinate of this Point. + * + * @name Phaser.Geom.Point#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The y coordinate of this Point. + * + * @name Phaser.Geom.Point#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + }, + + /** + * Set the x and y coordinates of the point to the given values. + * + * @method Phaser.Geom.Point#setTo + * @since 3.0.0 + * + * @param {number} [x=0] - The x coordinate of this Point. + * @param {number} [y=x] - The y coordinate of this Point. + * + * @return {Phaser.Geom.Point} This Point object. + */ + setTo: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + } + +}); + +module.exports = Point; diff --git a/src/geom/point/Project.js b/src/geom/point/Project.js index 219b80f6c..c8cdb269b 100644 --- a/src/geom/point/Project.js +++ b/src/geom/point/Project.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); -var GetMagnitudeSq = require('./GetMagnitudeSq'); - -/** - * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the - * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. - * - * @function Phaser.Geom.Point.Project - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. - * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. - * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. - */ -var Project = function (pointA, pointB, out) -{ - if (out === undefined) { out = new Point(); } - - var dot = ((pointA.x * pointB.x) + (pointA.y * pointB.y)); - var amt = dot / GetMagnitudeSq(pointB); - - if (amt !== 0) - { - out.x = amt * pointB.x; - out.y = amt * pointB.y; - } - - return out; -}; - -module.exports = Project; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); +var GetMagnitudeSq = require('./GetMagnitudeSq'); + +/** + * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the + * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. + * + * @function Phaser.Geom.Point.Project + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. + * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. + * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * + * @return {Phaser.Geom.Point} A Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. + */ +var Project = function (pointA, pointB, out) +{ + if (out === undefined) { out = new Point(); } + + var dot = ((pointA.x * pointB.x) + (pointA.y * pointB.y)); + var amt = dot / GetMagnitudeSq(pointB); + + if (amt !== 0) + { + out.x = amt * pointB.x; + out.y = amt * pointB.y; + } + + return out; +}; + +module.exports = Project; diff --git a/src/geom/point/ProjectUnit.js b/src/geom/point/ProjectUnit.js index 236d2a2db..3378d0071 100644 --- a/src/geom/point/ProjectUnit.js +++ b/src/geom/point/ProjectUnit.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); - -/** - * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the - * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. - * - * @function Phaser.Geom.Point.ProjectUnit - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. Must be a normalized point with a magnitude of 1. - * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. - * - * @return {Phaser.Geom.Point} A unit Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. - */ -var ProjectUnit = function (pointA, pointB, out) -{ - if (out === undefined) { out = new Point(); } - - var amt = ((pointA.x * pointB.x) + (pointA.y * pointB.y)); - - if (amt !== 0) - { - out.x = amt * pointB.x; - out.y = amt * pointB.y; - } - - return out; -}; - -module.exports = ProjectUnit; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); + +/** + * Calculates the vector projection of `pointA` onto the nonzero `pointB`. This is the + * orthogonal projection of `pointA` onto a straight line paralle to `pointB`. + * + * @function Phaser.Geom.Point.ProjectUnit + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Point} pointA - Point A, to be projected onto Point B. Must be a normalized point with a magnitude of 1. + * @param {Phaser.Geom.Point} pointB - Point B, to have Point A projected upon it. + * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * + * @return {Phaser.Geom.Point} A unit Point object holding the coordinates of the vector projection of `pointA` onto `pointB`. + */ +var ProjectUnit = function (pointA, pointB, out) +{ + if (out === undefined) { out = new Point(); } + + var amt = ((pointA.x * pointB.x) + (pointA.y * pointB.y)); + + if (amt !== 0) + { + out.x = amt * pointB.x; + out.y = amt * pointB.y; + } + + return out; +}; + +module.exports = ProjectUnit; diff --git a/src/geom/point/SetMagnitude.js b/src/geom/point/SetMagnitude.js index ef4f907b3..6f8d563f8 100644 --- a/src/geom/point/SetMagnitude.js +++ b/src/geom/point/SetMagnitude.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetMagnitude = require('./GetMagnitude'); - -/** - * Changes the magnitude (length) of a two-dimensional vector without changing its direction. - * - * @function Phaser.Geom.Point.SetMagnitude - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {Phaser.Geom.Point} point - The Point to treat as the end point of the vector. - * @param {number} magnitude - The new magnitude of the vector. - * - * @return {Phaser.Geom.Point} The modified Point. - */ -var SetMagnitude = function (point, magnitude) -{ - if (point.x !== 0 || point.y !== 0) - { - var m = GetMagnitude(point); - - point.x /= m; - point.y /= m; - } - - point.x *= magnitude; - point.y *= magnitude; - - return point; -}; - -module.exports = SetMagnitude; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetMagnitude = require('./GetMagnitude'); + +/** + * Changes the magnitude (length) of a two-dimensional vector without changing its direction. + * + * @function Phaser.Geom.Point.SetMagnitude + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} point - The Point to treat as the end point of the vector. + * @param {number} magnitude - The new magnitude of the vector. + * + * @return {Phaser.Geom.Point} The modified Point. + */ +var SetMagnitude = function (point, magnitude) +{ + if (point.x !== 0 || point.y !== 0) + { + var m = GetMagnitude(point); + + point.x /= m; + point.y /= m; + } + + point.x *= magnitude; + point.y *= magnitude; + + return point; +}; + +module.exports = SetMagnitude; diff --git a/src/geom/point/index.js b/src/geom/point/index.js index 53c1cd950..eb9b480aa 100644 --- a/src/geom/point/index.js +++ b/src/geom/point/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('./Point'); - -Point.Ceil = require('./Ceil'); -Point.Clone = require('./Clone'); -Point.CopyFrom = require('./CopyFrom'); -Point.Equals = require('./Equals'); -Point.Floor = require('./Floor'); -Point.GetCentroid = require('./GetCentroid'); -Point.GetMagnitude = require('./GetMagnitude'); -Point.GetMagnitudeSq = require('./GetMagnitudeSq'); -Point.GetRectangleFromPoints = require('./GetRectangleFromPoints'); -Point.Interpolate = require('./Interpolate'); -Point.Invert = require('./Invert'); -Point.Negative = require('./Negative'); -Point.Project = require('./Project'); -Point.ProjectUnit = require('./ProjectUnit'); -Point.SetMagnitude = require('./SetMagnitude'); - -module.exports = Point; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('./Point'); + +Point.Ceil = require('./Ceil'); +Point.Clone = require('./Clone'); +Point.CopyFrom = require('./CopyFrom'); +Point.Equals = require('./Equals'); +Point.Floor = require('./Floor'); +Point.GetCentroid = require('./GetCentroid'); +Point.GetMagnitude = require('./GetMagnitude'); +Point.GetMagnitudeSq = require('./GetMagnitudeSq'); +Point.GetRectangleFromPoints = require('./GetRectangleFromPoints'); +Point.Interpolate = require('./Interpolate'); +Point.Invert = require('./Invert'); +Point.Negative = require('./Negative'); +Point.Project = require('./Project'); +Point.ProjectUnit = require('./ProjectUnit'); +Point.SetMagnitude = require('./SetMagnitude'); + +module.exports = Point; diff --git a/src/geom/polygon/Clone.js b/src/geom/polygon/Clone.js index 5d314dac4..d7f17c2a4 100644 --- a/src/geom/polygon/Clone.js +++ b/src/geom/polygon/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Polygon = require('./Polygon'); - -/** - * 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. - */ -var Clone = function (polygon) -{ - return new Polygon(polygon.points); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Polygon = require('./Polygon'); + +/** + * 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. + */ +var Clone = function (polygon) +{ + return new Polygon(polygon.points); +}; + +module.exports = Clone; diff --git a/src/geom/polygon/Contains.js b/src/geom/polygon/Contains.js index fada1a347..6ea9df721 100644 --- a/src/geom/polygon/Contains.js +++ b/src/geom/polygon/Contains.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// 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 - -/** - * Checks if a point is within the bounds of a Polygon. - * - * @function Phaser.Geom.Polygon.Contains - * @since 3.0.0 - * - * @param {Phaser.Geom.Polygon} polygon - The Polygon to check against. - * @param {number} x - The X coordinate of the point to check. - * @param {number} y - The Y coordinate of the point to check. - * - * @return {boolean} `true` if the point is within the bounds of the Polygon, otherwise `false`. - */ -var Contains = function (polygon, x, y) -{ - var inside = false; - - for (var i = -1, j = polygon.points.length - 1; ++i < polygon.points.length; j = i) - { - var ix = polygon.points[i].x; - var iy = polygon.points[i].y; - - var jx = polygon.points[j].x; - var jy = polygon.points[j].y; - - if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) - { - inside = !inside; - } - } - - return inside; -}; - -module.exports = Contains; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// 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 + +/** + * Checks if a point is within the bounds of a Polygon. + * + * @function Phaser.Geom.Polygon.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to check against. + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is within the bounds of the Polygon, otherwise `false`. + */ +var Contains = function (polygon, x, y) +{ + var inside = false; + + for (var i = -1, j = polygon.points.length - 1; ++i < polygon.points.length; j = i) + { + var ix = polygon.points[i].x; + var iy = polygon.points[i].y; + + var jx = polygon.points[j].x; + var jy = polygon.points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + return inside; +}; + +module.exports = Contains; diff --git a/src/geom/polygon/ContainsPoint.js b/src/geom/polygon/ContainsPoint.js index 09e52a7c2..8b97c8f42 100644 --- a/src/geom/polygon/ContainsPoint.js +++ b/src/geom/polygon/ContainsPoint.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Checks the given Point again the Polygon to see if the Point lays within its vertices. - * - * @function Phaser.Geom.Polygon.ContainsPoint - * @since 3.0.0 - * - * @param {Phaser.Geom.Polygon} polygon - The Polygon to check. - * @param {Phaser.Geom.Point} point - The Point to check if it's within the Polygon. - * - * @return {boolean} `true` if the Point is within the Polygon, otherwise `false`. - */ -var ContainsPoint = function (polygon, point) -{ - return Contains(polygon, point.x, point.y); -}; - -module.exports = ContainsPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Checks the given Point again the Polygon to see if the Point lays within its vertices. + * + * @function Phaser.Geom.Polygon.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to check. + * @param {Phaser.Geom.Point} point - The Point to check if it's within the Polygon. + * + * @return {boolean} `true` if the Point is within the Polygon, otherwise `false`. + */ +var ContainsPoint = function (polygon, point) +{ + return Contains(polygon, point.x, point.y); +}; + +module.exports = ContainsPoint; diff --git a/src/geom/polygon/Earcut.js b/src/geom/polygon/Earcut.js index e4babbf1e..df0e07721 100644 --- a/src/geom/polygon/Earcut.js +++ b/src/geom/polygon/Earcut.js @@ -1,675 +1,675 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Earcut 2.1.4 (December 4th 2018) - -/* - * 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. - */ - -'use strict'; - -module.exports = earcut; - -function earcut(data, holeIndices, dim) { - - dim = dim || 2; - - var hasHoles = holeIndices && holeIndices.length, - outerLen = hasHoles ? holeIndices[0] * dim : data.length, - outerNode = linkedList(data, 0, outerLen, dim, true), - triangles = []; - - if (!outerNode || outerNode.next === outerNode.prev) return triangles; - - var minX, minY, maxX, maxY, x, y, invSize; - - if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); - - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY = data[1]; - - for (var i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - } - - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max(maxX - minX, maxY - minY); - invSize = invSize !== 0 ? 1 / invSize : 0; - } - - earcutLinked(outerNode, triangles, dim, minX, minY, invSize); - - return triangles; -} - -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList(data, start, end, dim, clockwise) { - var i, last; - - if (clockwise === (signedArea(data, start, end, dim) > 0)) { - for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); - } else { - for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); - } - - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - - return last; -} - -// eliminate collinear or duplicate points -function filterPoints(start, end) { - if (!start) return start; - if (!end) end = start; - - var p = start, - again; - do { - again = false; - - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) break; - again = true; - - } else { - p = p.next; - } - } while (again || p !== end); - - return end; -} - -// main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { - if (!ear) return; - - // interlink polygon nodes in z-order - if (!pass && invSize) indexCurve(ear, minX, minY, invSize); - - var stop = ear, - prev, next; - - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - - if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { - // cut off the triangle - triangles.push(prev.i / dim); - triangles.push(ear.i / dim); - triangles.push(next.i / dim); - - removeNode(ear); - - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; - - continue; - } - - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if (ear === stop) { - // try filtering points and slicing again - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - - // if this didn't work, try curing all small self-intersections locally - } else if (pass === 1) { - ear = cureLocalIntersections(ear, triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); - - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, invSize); - } - - break; - } - } -} - -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar(ear) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - - // now make sure we don't have other points inside the potential ear - var p = ear.next.next; - - while (p !== ear.prev) { - if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.next; - } - - return true; -} - -function isEarHashed(ear, minX, minY, invSize) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - - // triangle bbox; min & max are calculated like this for speed - var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), - minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), - maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), - maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); - - // z-order range for the current triangle bbox; - var minZ = zOrder(minTX, minTY, minX, minY, invSize), - maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); - - var p = ear.prevZ, - n = ear.nextZ; - - // look for points inside the triangle in both directions - while (p && p.z >= minZ && n && n.z <= maxZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - - if (n !== ear.prev && n !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && - area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - - // look for remaining points in decreasing z-order - while (p && p.z >= minZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - } - - // look for remaining points in increasing z-order - while (n && n.z <= maxZ) { - if (n !== ear.prev && n !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && - area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - - return true; -} - -// go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections(start, triangles, dim) { - var p = start; - do { - var a = p.prev, - b = p.next.next; - - if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - - triangles.push(a.i / dim); - triangles.push(p.i / dim); - triangles.push(b.i / dim); - - // remove two nodes involved - removeNode(p); - removeNode(p.next); - - p = start = b; - } - p = p.next; - } while (p !== start); - - return p; -} - -// try splitting polygon into two and triangulate them independently -function splitEarcut(start, triangles, dim, minX, minY, invSize) { - // look for a valid diagonal that divides the polygon into two - var a = start; - do { - var b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - // split the polygon in two by the diagonal - var c = splitPolygon(a, b); - - // filter collinear points around the cuts - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); - - // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, invSize); - earcutLinked(c, triangles, dim, minX, minY, invSize); - return; - } - b = b.next; - } - a = a.next; - } while (a !== start); -} - -// link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles(data, holeIndices, outerNode, dim) { - var queue = [], - i, len, start, end, list; - - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) list.steiner = true; - queue.push(getLeftmost(list)); - } - - queue.sort(compareX); - - // process holes from left to right - for (i = 0; i < queue.length; i++) { - eliminateHole(queue[i], outerNode); - outerNode = filterPoints(outerNode, outerNode.next); - } - - return outerNode; -} - -function compareX(a, b) { - return a.x - b.x; -} - -// find a bridge between vertices that connects hole with an outer ring and and link it -function eliminateHole(hole, outerNode) { - outerNode = findHoleBridge(hole, outerNode); - if (outerNode) { - var b = splitPolygon(outerNode, hole); - filterPoints(b, b.next); - } -} - -// David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge(hole, outerNode) { - var p = outerNode, - hx = hole.x, - hy = hole.y, - qx = -Infinity, - m; - - // 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 - do { - if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { - var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - if (x === hx) { - if (hy === p.y) return p; - if (hy === p.next.y) return p.next; - } - m = p.x < p.next.x ? p : p.next; - } - } - p = p.next; - } while (p !== outerNode); - - if (!m) return null; - - if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint - - // 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 - - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; - - p = m.next; - - while (p !== stop) { - if (hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential - - if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { - m = p; - tanMin = tan; - } - } - - p = p.next; - } - - return m; -} - -// interlink polygon nodes in z-order -function indexCurve(start, minX, minY, invSize) { - var p = start; - do { - if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - - p.prevZ.nextZ = null; - p.prevZ = null; - - sortLinked(p); -} - -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked(list) { - var i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; - - do { - p = list; - list = null; - tail = null; - numMerges = 0; - - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) break; - } - qSize = inSize; - - while (pSize > 0 || (qSize > 0 && q)) { - - if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } - - if (tail) tail.nextZ = e; - else list = e; - - e.prevZ = tail; - tail = e; - } - - p = q; - } - - tail.nextZ = null; - inSize *= 2; - - } while (numMerges > 1); - - return list; -} - -// z-order of a point given coords and inverse of the longer side of data bbox -function zOrder(x, y, minX, minY, invSize) { - // coords are transformed into non-negative 15-bit integer range - x = 32767 * (x - minX) * invSize; - y = 32767 * (y - minY) * invSize; - - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); -} - -// find the leftmost node of a polygon ring -function getLeftmost(start) { - var p = start, - leftmost = start; - do { - if (p.x < leftmost.x) leftmost = p; - p = p.next; - } while (p !== start); - - return leftmost; -} - -// check if a point lies within a convex triangle -function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { - return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && - (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && - (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; -} - -// check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && - locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); -} - -// signed area of a triangle -function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); -} - -// check if two points are equal -function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; -} - -// check if two segments intersect -function intersects(p1, q1, p2, q2) { - if ((equals(p1, q1) && equals(p2, q2)) || - (equals(p1, q2) && equals(p2, q1))) return true; - return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && - area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; -} - -// check if a polygon diagonal intersects any polygon segments -function intersectsPolygon(a, b) { - var p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects(p, p.next, a, b)) return true; - p = p.next; - } while (p !== a); - - return false; -} - -// check if a polygon diagonal is locally inside the polygon -function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? - area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : - area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; -} - -// check if the middle point of a polygon diagonal is inside the polygon -function middleInside(a, b) { - var p = a, - inside = false, - px = (a.x + b.x) / 2, - py = (a.y + b.y) / 2; - do { - if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && - (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) - inside = !inside; - p = p.next; - } while (p !== a); - - return inside; -} - -// 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 -function splitPolygon(a, b) { - var a2 = new Node(a.i, a.x, a.y), - b2 = new Node(b.i, b.x, b.y), - an = a.next, - bp = b.prev; - - a.next = b; - b.prev = a; - - a2.next = an; - an.prev = a2; - - b2.next = a2; - a2.prev = b2; - - bp.next = b2; - b2.prev = bp; - - return b2; -} - -// create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode(i, x, y, last) { - var p = new Node(i, x, y); - - if (!last) { - p.prev = p; - p.next = p; - - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} - -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} - -function Node(i, x, y) { - // vertex index in coordinates array - this.i = i; - - // vertex coordinates - this.x = x; - this.y = y; - - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; - - // z-order curve value - this.z = null; - - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; - - // indicates whether this is a steiner point - this.steiner = false; -} - -// return a percentage difference between the polygon area and its triangulation area; -// used to verify correctness of triangulation -earcut.deviation = function (data, holeIndices, dim, triangles) { - var hasHoles = holeIndices && holeIndices.length; - var outerLen = hasHoles ? holeIndices[0] * dim : data.length; - - var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); - if (hasHoles) { - for (var i = 0, len = holeIndices.length; i < len; i++) { - var start = holeIndices[i] * dim; - var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - polygonArea -= Math.abs(signedArea(data, start, end, dim)); - } - } - - var trianglesArea = 0; - for (i = 0; i < triangles.length; i += 3) { - var a = triangles[i] * dim; - var b = triangles[i + 1] * dim; - var c = triangles[i + 2] * dim; - trianglesArea += Math.abs( - (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); - } - - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); -}; - -function signedArea(data, start, end, dim) { - var sum = 0; - for (var i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; -} - -// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts -earcut.flatten = function (data) { - var dim = data[0][0].length, - result = {vertices: [], holes: [], dimensions: dim}, - holeIndex = 0; - - for (var i = 0; i < data.length; i++) { - for (var j = 0; j < data[i].length; j++) { - for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); - } - if (i > 0) { - holeIndex += data[i - 1].length; - result.holes.push(holeIndex); - } - } - return result; -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Earcut 2.1.4 (December 4th 2018) + +/* + * 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. + */ + +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate collinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter collinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // 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 + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // 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 + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// 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 +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; diff --git a/src/geom/polygon/GetAABB.js b/src/geom/polygon/GetAABB.js index 36a93f799..4e524b3ff 100644 --- a/src/geom/polygon/GetAABB.js +++ b/src/geom/polygon/GetAABB.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('../rectangle/Rectangle'); - -/** - * Calculates the bounding AABB rectangle of a polygon. - * - * @function Phaser.Geom.Polygon.GetAABB - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {Phaser.Geom.Polygon} polygon - The polygon that should be calculated. - * @param {(Phaser.Geom.Rectangle|object)} [out] - The rectangle or object that has x, y, width, and height properties to store the result. Optional. - * - * @return {(Phaser.Geom.Rectangle|object)} The resulting rectangle or object that is passed in with position and dimensions of the polygon's AABB. - */ -var GetAABB = function (polygon, out) -{ - if (out === undefined) { out = new Rectangle(); } - - var minX = Infinity; - var minY = Infinity; - var maxX = -minX; - var maxY = -minY; - var p; - - for (var i = 0; i < polygon.points.length; i++) - { - p = polygon.points[i]; - - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - - out.x = minX; - out.y = minY; - out.width = maxX - minX; - out.height = maxY - minY; - - return out; -}; - -module.exports = GetAABB; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('../rectangle/Rectangle'); + +/** + * Calculates the bounding AABB rectangle of a polygon. + * + * @function Phaser.Geom.Polygon.GetAABB + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The polygon that should be calculated. + * @param {(Phaser.Geom.Rectangle|object)} [out] - The rectangle or object that has x, y, width, and height properties to store the result. Optional. + * + * @return {(Phaser.Geom.Rectangle|object)} The resulting rectangle or object that is passed in with position and dimensions of the polygon's AABB. + */ +var GetAABB = function (polygon, out) +{ + if (out === undefined) { out = new Rectangle(); } + + var minX = Infinity; + var minY = Infinity; + var maxX = -minX; + var maxY = -minY; + var p; + + for (var i = 0; i < polygon.points.length; i++) + { + p = polygon.points[i]; + + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + + out.x = minX; + out.y = minY; + out.width = maxX - minX; + out.height = maxY - minY; + + return out; +}; + +module.exports = GetAABB; diff --git a/src/geom/polygon/GetNumberArray.js b/src/geom/polygon/GetNumberArray.js index b039b05b8..d90211412 100644 --- a/src/geom/polygon/GetNumberArray.js +++ b/src/geom/polygon/GetNumberArray.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] - -/** - * Stores all of the points of a Polygon into a flat array of numbers following the sequence [ x,y, x,y, x,y ], - * i.e. each point of the Polygon, in the order it's defined, corresponds to two elements of the resultant - * array for the point's X and Y coordinate. - * - * @function Phaser.Geom.Polygon.GetNumberArray - * @since 3.0.0 - * - * @generic {number[]} O - [output,$return] - * - * @param {Phaser.Geom.Polygon} polygon - The Polygon whose points to export. - * @param {(array|number[])} [output] - An array to which the points' coordinates should be appended. - * - * @return {(array|number[])} The modified `output` array, or a new array if none was given. - */ -var GetNumberArray = function (polygon, output) -{ - if (output === undefined) { output = []; } - - for (var i = 0; i < polygon.points.length; i++) - { - output.push(polygon.points[i].x); - output.push(polygon.points[i].y); - } - - return output; -}; - -module.exports = GetNumberArray; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + +/** + * Stores all of the points of a Polygon into a flat array of numbers following the sequence [ x,y, x,y, x,y ], + * i.e. each point of the Polygon, in the order it's defined, corresponds to two elements of the resultant + * array for the point's X and Y coordinate. + * + * @function Phaser.Geom.Polygon.GetNumberArray + * @since 3.0.0 + * + * @generic {number[]} O - [output,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon whose points to export. + * @param {(array|number[])} [output] - An array to which the points' coordinates should be appended. + * + * @return {(array|number[])} The modified `output` array, or a new array if none was given. + */ +var GetNumberArray = function (polygon, output) +{ + if (output === undefined) { output = []; } + + for (var i = 0; i < polygon.points.length; i++) + { + output.push(polygon.points[i].x); + output.push(polygon.points[i].y); + } + + return output; +}; + +module.exports = GetNumberArray; diff --git a/src/geom/polygon/GetPoints.js b/src/geom/polygon/GetPoints.js index 2a0310496..e703eab82 100644 --- a/src/geom/polygon/GetPoints.js +++ b/src/geom/polygon/GetPoints.js @@ -1,71 +1,71 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Length = require('../line/Length'); -var Line = require('../line/Line'); -var Perimeter = require('./Perimeter'); - -/** - * Returns an array of Point 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 {integer} 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 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.Geom.Point[]} An array of Point objects pertaining to the points around the perimeter of the Polygon. - */ -var GetPoints = function (polygon, quantity, stepRate, out) -{ - if (out === undefined) { out = []; } - - var points = polygon.points; - var perimeter = Perimeter(polygon); - - // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!quantity) - { - quantity = perimeter / stepRate; - } - - for (var i = 0; i < quantity; i++) - { - var position = perimeter * (i / quantity); - var accumulatedPerimeter = 0; - - for (var j = 0; j < points.length; j++) - { - var pointA = points[j]; - var pointB = points[(j + 1) % points.length]; - var line = new Line( - pointA.x, - pointA.y, - pointB.x, - pointB.y - ); - var length = Length(line); - - if (position < accumulatedPerimeter || position > accumulatedPerimeter + length) - { - accumulatedPerimeter += length; - continue; - } - - var point = line.getPoint((position - accumulatedPerimeter) / length); - out.push(point); - - break; - } - } - - return out; -}; - -module.exports = GetPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = require('../line/Length'); +var Line = require('../line/Line'); +var Perimeter = require('./Perimeter'); + +/** + * Returns an array of Point 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 {integer} 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 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.Geom.Point[]} An array of Point objects pertaining to the points around the perimeter of the Polygon. + */ +var GetPoints = function (polygon, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + var points = polygon.points; + var perimeter = Perimeter(polygon); + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = perimeter / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var position = perimeter * (i / quantity); + var accumulatedPerimeter = 0; + + for (var j = 0; j < points.length; j++) + { + var pointA = points[j]; + var pointB = points[(j + 1) % points.length]; + var line = new Line( + pointA.x, + pointA.y, + pointB.x, + pointB.y + ); + var length = Length(line); + + if (position < accumulatedPerimeter || position > accumulatedPerimeter + length) + { + accumulatedPerimeter += length; + continue; + } + + var point = line.getPoint((position - accumulatedPerimeter) / length); + out.push(point); + + break; + } + } + + return out; +}; + +module.exports = GetPoints; diff --git a/src/geom/polygon/Perimeter.js b/src/geom/polygon/Perimeter.js index bd6d5587f..46fde0e73 100644 --- a/src/geom/polygon/Perimeter.js +++ b/src/geom/polygon/Perimeter.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Length = require('../line/Length'); -var Line = require('../line/Line'); - -/** - * Returns the perimeter of the given Polygon. - * - * @function Phaser.Geom.Polygon.Perimeter - * @since 3.12.0 - * - * @param {Phaser.Geom.Polygon} polygon - The Polygon to get the perimeter of. - * - * @return {number} The perimeter of the Polygon. - */ -var Perimeter = function (polygon) -{ - var points = polygon.points; - var perimeter = 0; - - for (var i = 0; i < points.length; i++) - { - var pointA = points[i]; - var pointB = points[(i + 1) % points.length]; - var line = new Line( - pointA.x, - pointA.y, - pointB.x, - pointB.y - ); - - perimeter += Length(line); - } - - return perimeter; -}; - -module.exports = Perimeter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = require('../line/Length'); +var Line = require('../line/Line'); + +/** + * Returns the perimeter of the given Polygon. + * + * @function Phaser.Geom.Polygon.Perimeter + * @since 3.12.0 + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to get the perimeter of. + * + * @return {number} The perimeter of the Polygon. + */ +var Perimeter = function (polygon) +{ + var points = polygon.points; + var perimeter = 0; + + for (var i = 0; i < points.length; i++) + { + var pointA = points[i]; + var pointB = points[(i + 1) % points.length]; + var line = new Line( + pointA.x, + pointA.y, + pointB.x, + pointB.y + ); + + perimeter += Length(line); + } + + return perimeter; +}; + +module.exports = Perimeter; diff --git a/src/geom/polygon/Polygon.js b/src/geom/polygon/Polygon.js index 72568bd0f..c3113e085 100644 --- a/src/geom/polygon/Polygon.js +++ b/src/geom/polygon/Polygon.js @@ -1,228 +1,228 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Contains = require('./Contains'); -var GetPoints = require('./GetPoints'); -var GEOM_CONST = require('../const'); - -/** - * @classdesc - * A Polygon object - * - * The polygon is a closed shape consists of a series of connected straight lines defined by list of ordered points. - * Several formats are supported to define the list of points, check the setTo method for details. - * This is a geometry object allowing you to define and inspect the shape. - * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. - * To render a Polygon you should look at the capabilities of the Graphics class. - * - * @class Polygon - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Geom.Point[]} [points] - List of points defining the perimeter of this Polygon. Several formats are supported: - * - A string containing paired x y values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` - * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` - * - An array of objects with public x y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - */ -var Polygon = new Class({ - - initialize: - - function Polygon (points) - { - /** - * The geometry constant type of this object: `GEOM_CONST.POLYGON`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Polygon#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.POLYGON; - - /** - * The area of this Polygon. - * - * @name Phaser.Geom.Polygon#area - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.area = 0; - - /** - * An array of number pair objects that make up this polygon. I.e. [ {x,y}, {x,y}, {x,y} ] - * - * @name Phaser.Geom.Polygon#points - * @type {Phaser.Geom.Point[]} - * @since 3.0.0 - */ - this.points = []; - - if (points) - { - this.setTo(points); - } - }, - - /** - * Check to see if the Polygon contains the given x / y coordinates. - * - * @method Phaser.Geom.Polygon#contains - * @since 3.0.0 - * - * @param {number} x - The x coordinate to check within the polygon. - * @param {number} y - The y coordinate to check within the polygon. - * - * @return {boolean} `true` if the coordinates are within the polygon, otherwise `false`. - */ - contains: function (x, y) - { - return Contains(this, x, y); - }, - - /** - * Sets this Polygon to the given points. - * - * The points can be set from a variety of formats: - * - * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` - * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` - * - An array of objects with public x/y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - * - * `setTo` may also be called without any arguments to remove all points. - * - * @method Phaser.Geom.Polygon#setTo - * @since 3.0.0 - * - * @param {array} points - Points defining the perimeter of this polygon. Please check function description above for the different supported formats. - * - * @return {Phaser.Geom.Polygon} This Polygon object. - */ - setTo: function (points) - { - this.area = 0; - this.points = []; - - if (typeof points === 'string') - { - points = points.split(' '); - } - - if (!Array.isArray(points)) - { - return this; - } - - var p; - var y0 = Number.MAX_VALUE; - - // The points argument is an array, so iterate through it - for (var i = 0; i < points.length; i++) - { - p = { x: 0, y: 0 }; - - if (typeof points[i] === 'number' || typeof points[i] === 'string') - { - p.x = parseFloat(points[i]); - p.y = parseFloat(points[i + 1]); - i++; - } - else if (Array.isArray(points[i])) - { - // An array of arrays? - p.x = points[i][0]; - p.y = points[i][1]; - } - else - { - p.x = points[i].x; - p.y = points[i].y; - } - - this.points.push(p); - - // Lowest boundary - if (p.y < y0) - { - y0 = p.y; - } - } - - this.calculateArea(y0); - - return this; - }, - - /** - * Calculates the area of the Polygon. This is available in the property Polygon.area - * - * @method Phaser.Geom.Polygon#calculateArea - * @since 3.0.0 - * - * @return {number} The area of the polygon. - */ - calculateArea: function () - { - if (this.points.length < 3) - { - this.area = 0; - - return this.area; - } - - var sum = 0; - var p1; - var p2; - - for (var i = 0; i < this.points.length - 1; i++) - { - p1 = this.points[i]; - p2 = this.points[i + 1]; - - sum += (p2.x - p1.x) * (p1.y + p2.y); - } - - p1 = this.points[0]; - p2 = this.points[this.points.length - 1]; - - sum += (p1.x - p2.x) * (p2.y + p1.y); - - this.area = -sum * 0.5; - - return this.area; - }, - - /** - * Returns an array of Point 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.Geom.Point[]} O - [output,$return] - * - * @param {integer} 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 perimeter of the Polygon and dividing it by the stepRate. - * @param {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. - * - * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the perimeter of the Polygon. - */ - getPoints: function (quantity, step, output) - { - return GetPoints(this, quantity, step, output); - } - -}); - -module.exports = Polygon; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Contains = require('./Contains'); +var GetPoints = require('./GetPoints'); +var GEOM_CONST = require('../const'); + +/** + * @classdesc + * A Polygon object + * + * The polygon is a closed shape consists of a series of connected straight lines defined by list of ordered points. + * Several formats are supported to define the list of points, check the setTo method for details. + * This is a geometry object allowing you to define and inspect the shape. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render a Polygon you should look at the capabilities of the Graphics class. + * + * @class Polygon + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Geom.Point[]} [points] - List of points defining the perimeter of this Polygon. Several formats are supported: + * - A string containing paired x y values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + */ +var Polygon = new Class({ + + initialize: + + function Polygon (points) + { + /** + * The geometry constant type of this object: `GEOM_CONST.POLYGON`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Polygon#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.POLYGON; + + /** + * The area of this Polygon. + * + * @name Phaser.Geom.Polygon#area + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.area = 0; + + /** + * An array of number pair objects that make up this polygon. I.e. [ {x,y}, {x,y}, {x,y} ] + * + * @name Phaser.Geom.Polygon#points + * @type {Phaser.Geom.Point[]} + * @since 3.0.0 + */ + this.points = []; + + if (points) + { + this.setTo(points); + } + }, + + /** + * Check to see if the Polygon contains the given x / y coordinates. + * + * @method Phaser.Geom.Polygon#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check within the polygon. + * @param {number} y - The y coordinate to check within the polygon. + * + * @return {boolean} `true` if the coordinates are within the polygon, otherwise `false`. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Geom.Polygon#setTo + * @since 3.0.0 + * + * @param {array} points - Points defining the perimeter of this polygon. Please check function description above for the different supported formats. + * + * @return {Phaser.Geom.Polygon} This Polygon object. + */ + setTo: function (points) + { + this.area = 0; + this.points = []; + + if (typeof points === 'string') + { + points = points.split(' '); + } + + if (!Array.isArray(points)) + { + return this; + } + + var p; + var y0 = Number.MAX_VALUE; + + // The points argument is an array, so iterate through it + for (var i = 0; i < points.length; i++) + { + p = { x: 0, y: 0 }; + + if (typeof points[i] === 'number' || typeof points[i] === 'string') + { + p.x = parseFloat(points[i]); + p.y = parseFloat(points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + // An array of arrays? + p.x = points[i][0]; + p.y = points[i][1]; + } + else + { + p.x = points[i].x; + p.y = points[i].y; + } + + this.points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + + return this; + }, + + /** + * Calculates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Geom.Polygon#calculateArea + * @since 3.0.0 + * + * @return {number} The area of the polygon. + */ + calculateArea: function () + { + if (this.points.length < 3) + { + this.area = 0; + + return this.area; + } + + var sum = 0; + var p1; + var p2; + + for (var i = 0; i < this.points.length - 1; i++) + { + p1 = this.points[i]; + p2 = this.points[i + 1]; + + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + + p1 = this.points[0]; + p2 = this.points[this.points.length - 1]; + + sum += (p1.x - p2.x) * (p2.y + p1.y); + + this.area = -sum * 0.5; + + return this.area; + }, + + /** + * Returns an array of Point 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 perimeter of the Polygon and dividing it by the stepRate. + * @param {(array|Phaser.Geom.Point[])} [output] - An array to insert the points in to. If not provided a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} An array of Point objects pertaining to the points around the perimeter of the Polygon. + */ + getPoints: function (quantity, step, output) + { + return GetPoints(this, quantity, step, output); + } + +}); + +module.exports = Polygon; diff --git a/src/geom/polygon/Reverse.js b/src/geom/polygon/Reverse.js index 354e133a6..bfacfeecd 100644 --- a/src/geom/polygon/Reverse.js +++ b/src/geom/polygon/Reverse.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Reverses the order of the points of a Polygon. - * - * @function Phaser.Geom.Polygon.Reverse - * @since 3.0.0 - * - * @generic {Phaser.Geom.Polygon} O - [polygon,$return] - * - * @param {Phaser.Geom.Polygon} polygon - The Polygon to modify. - * - * @return {Phaser.Geom.Polygon} The modified Polygon. - */ -var Reverse = function (polygon) -{ - polygon.points.reverse(); - - return polygon; -}; - -module.exports = Reverse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Reverses the order of the points of a Polygon. + * + * @function Phaser.Geom.Polygon.Reverse + * @since 3.0.0 + * + * @generic {Phaser.Geom.Polygon} O - [polygon,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The Polygon to modify. + * + * @return {Phaser.Geom.Polygon} The modified Polygon. + */ +var Reverse = function (polygon) +{ + polygon.points.reverse(); + + return polygon; +}; + +module.exports = Reverse; diff --git a/src/geom/polygon/Smooth.js b/src/geom/polygon/Smooth.js index 3e77d9889..3dc16c594 100644 --- a/src/geom/polygon/Smooth.js +++ b/src/geom/polygon/Smooth.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @author Igor Ognichenko - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @ignore - */ -var copy = function (out, a) -{ - out[0] = a[0]; - out[1] = a[1]; - - return out; -}; - -/** - * Takes a Polygon object and applies Chaikin's smoothing algorithm on its points. - * - * @function Phaser.Geom.Polygon.Smooth - * @since 3.13.0 - * - * @generic {Phaser.Geom.Polygon} O - [polygon,$return] - * - * @param {Phaser.Geom.Polygon} polygon - The polygon to be smoothed. The polygon will be modified in-place and returned. - * - * @return {Phaser.Geom.Polygon} The input polygon. - */ -var Smooth = function (polygon) -{ - var i; - var points = []; - var data = polygon.points; - - for (i = 0; i < data.length; i++) - { - points.push([ data[i].x, data[i].y ]); - } - - var output = []; - - if (points.length > 0) - { - output.push(copy([ 0, 0 ], points[0])); - } - - for (i = 0; i < points.length - 1; i++) - { - var p0 = points[i]; - var p1 = points[i + 1]; - var p0x = p0[0]; - var p0y = p0[1]; - var p1x = p1[0]; - var p1y = p1[1]; - - output.push([ 0.85 * p0x + 0.15 * p1x, 0.85 * p0y + 0.15 * p1y ]); - output.push([ 0.15 * p0x + 0.85 * p1x, 0.15 * p0y + 0.85 * p1y ]); - } - - if (points.length > 1) - { - output.push(copy([ 0, 0 ], points[points.length - 1])); - } - - return polygon.setTo(output); -}; - -module.exports = Smooth; +/** + * @author Richard Davey + * @author Igor Ognichenko + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +var copy = function (out, a) +{ + out[0] = a[0]; + out[1] = a[1]; + + return out; +}; + +/** + * Takes a Polygon object and applies Chaikin's smoothing algorithm on its points. + * + * @function Phaser.Geom.Polygon.Smooth + * @since 3.13.0 + * + * @generic {Phaser.Geom.Polygon} O - [polygon,$return] + * + * @param {Phaser.Geom.Polygon} polygon - The polygon to be smoothed. The polygon will be modified in-place and returned. + * + * @return {Phaser.Geom.Polygon} The input polygon. + */ +var Smooth = function (polygon) +{ + var i; + var points = []; + var data = polygon.points; + + for (i = 0; i < data.length; i++) + { + points.push([ data[i].x, data[i].y ]); + } + + var output = []; + + if (points.length > 0) + { + output.push(copy([ 0, 0 ], points[0])); + } + + for (i = 0; i < points.length - 1; i++) + { + var p0 = points[i]; + var p1 = points[i + 1]; + var p0x = p0[0]; + var p0y = p0[1]; + var p1x = p1[0]; + var p1y = p1[1]; + + output.push([ 0.85 * p0x + 0.15 * p1x, 0.85 * p0y + 0.15 * p1y ]); + output.push([ 0.15 * p0x + 0.85 * p1x, 0.15 * p0y + 0.85 * p1y ]); + } + + if (points.length > 1) + { + output.push(copy([ 0, 0 ], points[points.length - 1])); + } + + return polygon.setTo(output); +}; + +module.exports = Smooth; diff --git a/src/geom/polygon/index.js b/src/geom/polygon/index.js index a928bccef..c43fa861b 100644 --- a/src/geom/polygon/index.js +++ b/src/geom/polygon/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Polygon = require('./Polygon'); - -Polygon.Clone = require('./Clone'); -Polygon.Contains = require('./Contains'); -Polygon.ContainsPoint = require('./ContainsPoint'); -Polygon.GetAABB = require('./GetAABB'); -Polygon.GetNumberArray = require('./GetNumberArray'); -Polygon.GetPoints = require('./GetPoints'); -Polygon.Perimeter = require('./Perimeter'); -Polygon.Reverse = require('./Reverse'); -Polygon.Smooth = require('./Smooth'); - -module.exports = Polygon; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Polygon = require('./Polygon'); + +Polygon.Clone = require('./Clone'); +Polygon.Contains = require('./Contains'); +Polygon.ContainsPoint = require('./ContainsPoint'); +Polygon.GetAABB = require('./GetAABB'); +Polygon.GetNumberArray = require('./GetNumberArray'); +Polygon.GetPoints = require('./GetPoints'); +Polygon.Perimeter = require('./Perimeter'); +Polygon.Reverse = require('./Reverse'); +Polygon.Smooth = require('./Smooth'); + +module.exports = Polygon; diff --git a/src/geom/rectangle/Area.js b/src/geom/rectangle/Area.js index fb13b7c29..9030460fc 100644 --- a/src/geom/rectangle/Area.js +++ b/src/geom/rectangle/Area.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the area of the given Rectangle object. - * - * @function Phaser.Geom.Rectangle.Area - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The rectangle to calculate the area of. - * - * @return {number} The area of the Rectangle object. - */ -var Area = function (rect) -{ - return rect.width * rect.height; -}; - -module.exports = Area; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the area of the given Rectangle object. + * + * @function Phaser.Geom.Rectangle.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to calculate the area of. + * + * @return {number} The area of the Rectangle object. + */ +var Area = function (rect) +{ + return rect.width * rect.height; +}; + +module.exports = Area; diff --git a/src/geom/rectangle/Ceil.js b/src/geom/rectangle/Ceil.js index dd6ad15f3..3e20cce4d 100644 --- a/src/geom/rectangle/Ceil.js +++ b/src/geom/rectangle/Ceil.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rounds a Rectangle's position up to the smallest integer greater than or equal to each current coordinate. - * - * @function Phaser.Geom.Rectangle.Ceil - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. - * - * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. - */ -var Ceil = function (rect) -{ - rect.x = Math.ceil(rect.x); - rect.y = Math.ceil(rect.y); - - return rect; -}; - -module.exports = Ceil; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds a Rectangle's position up to the smallest integer greater than or equal to each current coordinate. + * + * @function Phaser.Geom.Rectangle.Ceil + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var Ceil = function (rect) +{ + rect.x = Math.ceil(rect.x); + rect.y = Math.ceil(rect.y); + + return rect; +}; + +module.exports = Ceil; diff --git a/src/geom/rectangle/CeilAll.js b/src/geom/rectangle/CeilAll.js index 3b65d994e..ed6c641a6 100644 --- a/src/geom/rectangle/CeilAll.js +++ b/src/geom/rectangle/CeilAll.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rounds a Rectangle's position and size up to the smallest integer greater than or equal to each respective value. - * - * @function Phaser.Geom.Rectangle.CeilAll - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to modify. - * - * @return {Phaser.Geom.Rectangle} The modified Rectangle. - */ -var CeilAll = function (rect) -{ - rect.x = Math.ceil(rect.x); - rect.y = Math.ceil(rect.y); - rect.width = Math.ceil(rect.width); - rect.height = Math.ceil(rect.height); - - return rect; -}; - -module.exports = CeilAll; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds a Rectangle's position and size up to the smallest integer greater than or equal to each respective value. + * + * @function Phaser.Geom.Rectangle.CeilAll + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to modify. + * + * @return {Phaser.Geom.Rectangle} The modified Rectangle. + */ +var CeilAll = function (rect) +{ + rect.x = Math.ceil(rect.x); + rect.y = Math.ceil(rect.y); + rect.width = Math.ceil(rect.width); + rect.height = Math.ceil(rect.height); + + return rect; +}; + +module.exports = CeilAll; diff --git a/src/geom/rectangle/CenterOn.js b/src/geom/rectangle/CenterOn.js index f1bb3298e..808965029 100644 --- a/src/geom/rectangle/CenterOn.js +++ b/src/geom/rectangle/CenterOn.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Centers this Rectangle so that the center coordinates match the given x and y values. - -/** - * Moves the top-left corner of a Rectangle so that its center is at the given coordinates. - * - * @function Phaser.Geom.Rectangle.CenterOn - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to be centered. - * @param {number} x - The X coordinate of the Rectangle's center. - * @param {number} y - The Y coordinate of the Rectangle's center. - * - * @return {Phaser.Geom.Rectangle} The centered rectangle. - */ -var CenterOn = function (rect, x, y) -{ - rect.x = x - (rect.width / 2); - rect.y = y - (rect.height / 2); - - return rect; -}; - -module.exports = CenterOn; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Centers this Rectangle so that the center coordinates match the given x and y values. + +/** + * Moves the top-left corner of a Rectangle so that its center is at the given coordinates. + * + * @function Phaser.Geom.Rectangle.CenterOn + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to be centered. + * @param {number} x - The X coordinate of the Rectangle's center. + * @param {number} y - The Y coordinate of the Rectangle's center. + * + * @return {Phaser.Geom.Rectangle} The centered rectangle. + */ +var CenterOn = function (rect, x, y) +{ + rect.x = x - (rect.width / 2); + rect.y = y - (rect.height / 2); + + return rect; +}; + +module.exports = CenterOn; diff --git a/src/geom/rectangle/Clone.js b/src/geom/rectangle/Clone.js index a7d50a4e4..6cbc0f2ff 100644 --- a/src/geom/rectangle/Clone.js +++ b/src/geom/rectangle/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('./Rectangle'); - -/** - * Creates a new Rectangle which is identical to the given one. - * - * @function Phaser.Geom.Rectangle.Clone - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} source - The Rectangle to clone. - * - * @return {Phaser.Geom.Rectangle} The newly created Rectangle, which is separate from the given one. - */ -var Clone = function (source) -{ - return new Rectangle(source.x, source.y, source.width, source.height); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('./Rectangle'); + +/** + * Creates a new Rectangle which is identical to the given one. + * + * @function Phaser.Geom.Rectangle.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} source - The Rectangle to clone. + * + * @return {Phaser.Geom.Rectangle} The newly created Rectangle, which is separate from the given one. + */ +var Clone = function (source) +{ + return new Rectangle(source.x, source.y, source.width, source.height); +}; + +module.exports = Clone; diff --git a/src/geom/rectangle/Contains.js b/src/geom/rectangle/Contains.js index 382a8d2f4..f291f5a9a 100644 --- a/src/geom/rectangle/Contains.js +++ b/src/geom/rectangle/Contains.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if a given point is inside a Rectangle's bounds. - * - * @function Phaser.Geom.Rectangle.Contains - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to check. - * @param {number} x - The X coordinate of the point to check. - * @param {number} y - The Y coordinate of the point to check. - * - * @return {boolean} `true` if the point is within the Rectangle's bounds, otherwise `false`. - */ -var Contains = function (rect, x, y) -{ - if (rect.width <= 0 || rect.height <= 0) - { - return false; - } - - return (rect.x <= x && rect.x + rect.width >= x && rect.y <= y && rect.y + rect.height >= y); -}; - -module.exports = Contains; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if a given point is inside a Rectangle's bounds. + * + * @function Phaser.Geom.Rectangle.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to check. + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is within the Rectangle's bounds, otherwise `false`. + */ +var Contains = function (rect, x, y) +{ + if (rect.width <= 0 || rect.height <= 0) + { + return false; + } + + return (rect.x <= x && rect.x + rect.width >= x && rect.y <= y && rect.y + rect.height >= y); +}; + +module.exports = Contains; diff --git a/src/geom/rectangle/ContainsPoint.js b/src/geom/rectangle/ContainsPoint.js index fe3761578..d0d7053bb 100644 --- a/src/geom/rectangle/ContainsPoint.js +++ b/src/geom/rectangle/ContainsPoint.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. - * - * @function Phaser.Geom.Rectangle.ContainsPoint - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle object. - * @param {Phaser.Geom.Point} point - The point object to be checked. Can be a Phaser Point object or any object with x and y values. - * - * @return {boolean} A value of true if the Rectangle object contains the specified point, otherwise false. - */ -var ContainsPoint = function (rect, point) -{ - return Contains(rect, point.x, point.y); -}; - -module.exports = ContainsPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. + * + * @function Phaser.Geom.Rectangle.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle object. + * @param {Phaser.Geom.Point} point - The point object to be checked. Can be a Phaser Point object or any object with x and y values. + * + * @return {boolean} A value of true if the Rectangle object contains the specified point, otherwise false. + */ +var ContainsPoint = function (rect, point) +{ + return Contains(rect, point.x, point.y); +}; + +module.exports = ContainsPoint; diff --git a/src/geom/rectangle/ContainsRect.js b/src/geom/rectangle/ContainsRect.js index 979a2ee07..e500d3354 100644 --- a/src/geom/rectangle/ContainsRect.js +++ b/src/geom/rectangle/ContainsRect.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Tests if one rectangle fully contains another. - * - * @function Phaser.Geom.Rectangle.ContainsRect - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rectA - The first rectangle. - * @param {Phaser.Geom.Rectangle} rectB - The second rectangle. - * - * @return {boolean} True only if rectA fully contains rectB. - */ -var ContainsRect = function (rectA, rectB) -{ - // Volume check (if rectB volume > rectA then rectA cannot contain it) - if ((rectB.width * rectB.height) > (rectA.width * rectA.height)) - { - return false; - } - - return ( - (rectB.x > rectA.x && rectB.x < rectA.right) && - (rectB.right > rectA.x && rectB.right < rectA.right) && - (rectB.y > rectA.y && rectB.y < rectA.bottom) && - (rectB.bottom > rectA.y && rectB.bottom < rectA.bottom) - ); -}; - -module.exports = ContainsRect; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tests if one rectangle fully contains another. + * + * @function Phaser.Geom.Rectangle.ContainsRect + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first rectangle. + * @param {Phaser.Geom.Rectangle} rectB - The second rectangle. + * + * @return {boolean} True only if rectA fully contains rectB. + */ +var ContainsRect = function (rectA, rectB) +{ + // Volume check (if rectB volume > rectA then rectA cannot contain it) + if ((rectB.width * rectB.height) > (rectA.width * rectA.height)) + { + return false; + } + + return ( + (rectB.x > rectA.x && rectB.x < rectA.right) && + (rectB.right > rectA.x && rectB.right < rectA.right) && + (rectB.y > rectA.y && rectB.y < rectA.bottom) && + (rectB.bottom > rectA.y && rectB.bottom < rectA.bottom) + ); +}; + +module.exports = ContainsRect; diff --git a/src/geom/rectangle/CopyFrom.js b/src/geom/rectangle/CopyFrom.js index 2db18a759..b457b1bf5 100644 --- a/src/geom/rectangle/CopyFrom.js +++ b/src/geom/rectangle/CopyFrom.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Copy the values of one Rectangle to a destination Rectangle. - * - * @function Phaser.Geom.Rectangle.CopyFrom - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [dest,$return] - * - * @param {Phaser.Geom.Rectangle} source - The source Rectangle to copy the values from. - * @param {Phaser.Geom.Rectangle} dest - The destination Rectangle to copy the values to. - * - * @return {Phaser.Geom.Rectangle} The destination Rectangle. - */ -var CopyFrom = function (source, dest) -{ - return dest.setTo(source.x, source.y, source.width, source.height); -}; - -module.exports = CopyFrom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one Rectangle to a destination Rectangle. + * + * @function Phaser.Geom.Rectangle.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [dest,$return] + * + * @param {Phaser.Geom.Rectangle} source - The source Rectangle to copy the values from. + * @param {Phaser.Geom.Rectangle} dest - The destination Rectangle to copy the values to. + * + * @return {Phaser.Geom.Rectangle} The destination Rectangle. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x, source.y, source.width, source.height); +}; + +module.exports = CopyFrom; diff --git a/src/geom/rectangle/Decompose.js b/src/geom/rectangle/Decompose.js index ad331ff98..e178260b0 100644 --- a/src/geom/rectangle/Decompose.js +++ b/src/geom/rectangle/Decompose.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Create an array of points for each corner of a Rectangle - * If an array is specified, each point object will be added to the end of the array, otherwise a new array will be created. - * - * @function Phaser.Geom.Rectangle.Decompose - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle object to be decomposed. - * @param {array} [out] - If provided, each point will be added to this array. - * - * @return {array} Will return the array you specified or a new array containing the points of the Rectangle. - */ -var Decompose = function (rect, out) -{ - if (out === undefined) { out = []; } - - out.push({ x: rect.x, y: rect.y }); - out.push({ x: rect.right, y: rect.y }); - out.push({ x: rect.right, y: rect.bottom }); - out.push({ x: rect.x, y: rect.bottom }); - - return out; -}; - -module.exports = Decompose; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Create an array of points for each corner of a Rectangle + * If an array is specified, each point object will be added to the end of the array, otherwise a new array will be created. + * + * @function Phaser.Geom.Rectangle.Decompose + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle object to be decomposed. + * @param {array} [out] - If provided, each point will be added to this array. + * + * @return {array} Will return the array you specified or a new array containing the points of the Rectangle. + */ +var Decompose = function (rect, out) +{ + if (out === undefined) { out = []; } + + out.push({ x: rect.x, y: rect.y }); + out.push({ x: rect.right, y: rect.y }); + out.push({ x: rect.right, y: rect.bottom }); + out.push({ x: rect.x, y: rect.bottom }); + + return out; +}; + +module.exports = Decompose; diff --git a/src/geom/rectangle/Equals.js b/src/geom/rectangle/Equals.js index a8a7c037e..e45611c0a 100644 --- a/src/geom/rectangle/Equals.js +++ b/src/geom/rectangle/Equals.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compares the `x`, `y`, `width` and `height` properties of two rectangles. - * - * @function Phaser.Geom.Rectangle.Equals - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - Rectangle A - * @param {Phaser.Geom.Rectangle} toCompare - Rectangle B - * - * @return {boolean} `true` if the rectangles' properties are an exact match, otherwise `false`. - */ -var Equals = function (rect, toCompare) -{ - return ( - rect.x === toCompare.x && - rect.y === toCompare.y && - rect.width === toCompare.width && - rect.height === toCompare.height - ); -}; - -module.exports = Equals; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compares the `x`, `y`, `width` and `height` properties of two rectangles. + * + * @function Phaser.Geom.Rectangle.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - Rectangle A + * @param {Phaser.Geom.Rectangle} toCompare - Rectangle B + * + * @return {boolean} `true` if the rectangles' properties are an exact match, otherwise `false`. + */ +var Equals = function (rect, toCompare) +{ + return ( + rect.x === toCompare.x && + rect.y === toCompare.y && + rect.width === toCompare.width && + rect.height === toCompare.height + ); +}; + +module.exports = Equals; diff --git a/src/geom/rectangle/FitInside.js b/src/geom/rectangle/FitInside.js index cc4c5a3c5..caa659999 100644 --- a/src/geom/rectangle/FitInside.js +++ b/src/geom/rectangle/FitInside.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetAspectRatio = require('./GetAspectRatio'); - -/** - * Adjusts the target rectangle, changing its width, height and position, - * so that it fits inside the area of the source rectangle, while maintaining its original - * aspect ratio. - * - * Unlike the `FitOutside` function, there may be some space inside the source area not covered. - * - * @function Phaser.Geom.Rectangle.FitInside - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [target,$return] - * - * @param {Phaser.Geom.Rectangle} target - The target rectangle to adjust. - * @param {Phaser.Geom.Rectangle} source - The source rectangle to envelop the target in. - * - * @return {Phaser.Geom.Rectangle} The modified target rectangle instance. - */ -var FitInside = function (target, source) -{ - var ratio = GetAspectRatio(target); - - if (ratio < GetAspectRatio(source)) - { - // Taller than Wide - target.setSize(source.height * ratio, source.height); - } - else - { - // Wider than Tall - target.setSize(source.width, source.width / ratio); - } - - return target.setPosition( - source.centerX - (target.width / 2), - source.centerY - (target.height / 2) - ); -}; - -module.exports = FitInside; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetAspectRatio = require('./GetAspectRatio'); + +/** + * Adjusts the target rectangle, changing its width, height and position, + * so that it fits inside the area of the source rectangle, while maintaining its original + * aspect ratio. + * + * Unlike the `FitOutside` function, there may be some space inside the source area not covered. + * + * @function Phaser.Geom.Rectangle.FitInside + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The target rectangle to adjust. + * @param {Phaser.Geom.Rectangle} source - The source rectangle to envelop the target in. + * + * @return {Phaser.Geom.Rectangle} The modified target rectangle instance. + */ +var FitInside = function (target, source) +{ + var ratio = GetAspectRatio(target); + + if (ratio < GetAspectRatio(source)) + { + // Taller than Wide + target.setSize(source.height * ratio, source.height); + } + else + { + // Wider than Tall + target.setSize(source.width, source.width / ratio); + } + + return target.setPosition( + source.centerX - (target.width / 2), + source.centerY - (target.height / 2) + ); +}; + +module.exports = FitInside; diff --git a/src/geom/rectangle/FitOutside.js b/src/geom/rectangle/FitOutside.js index 4bc148c01..2b7e9db2c 100644 --- a/src/geom/rectangle/FitOutside.js +++ b/src/geom/rectangle/FitOutside.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetAspectRatio = require('./GetAspectRatio'); - -/** - * Adjusts the target rectangle, changing its width, height and position, - * so that it fully covers the area of the source rectangle, while maintaining its original - * aspect ratio. - * - * Unlike the `FitInside` function, the target rectangle may extend further out than the source. - * - * @function Phaser.Geom.Rectangle.FitOutside - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [target,$return] - * - * @param {Phaser.Geom.Rectangle} target - The target rectangle to adjust. - * @param {Phaser.Geom.Rectangle} source - The source rectangle to envelope the target in. - * - * @return {Phaser.Geom.Rectangle} The modified target rectangle instance. - */ -var FitOutside = function (target, source) -{ - var ratio = GetAspectRatio(target); - - if (ratio > GetAspectRatio(source)) - { - // Wider than Tall - target.setSize(source.height * ratio, source.height); - } - else - { - // Taller than Wide - target.setSize(source.width, source.width / ratio); - } - - return target.setPosition( - source.centerX - target.width / 2, - source.centerY - target.height / 2 - ); -}; - -module.exports = FitOutside; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetAspectRatio = require('./GetAspectRatio'); + +/** + * Adjusts the target rectangle, changing its width, height and position, + * so that it fully covers the area of the source rectangle, while maintaining its original + * aspect ratio. + * + * Unlike the `FitInside` function, the target rectangle may extend further out than the source. + * + * @function Phaser.Geom.Rectangle.FitOutside + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The target rectangle to adjust. + * @param {Phaser.Geom.Rectangle} source - The source rectangle to envelope the target in. + * + * @return {Phaser.Geom.Rectangle} The modified target rectangle instance. + */ +var FitOutside = function (target, source) +{ + var ratio = GetAspectRatio(target); + + if (ratio > GetAspectRatio(source)) + { + // Wider than Tall + target.setSize(source.height * ratio, source.height); + } + else + { + // Taller than Wide + target.setSize(source.width, source.width / ratio); + } + + return target.setPosition( + source.centerX - target.width / 2, + source.centerY - target.height / 2 + ); +}; + +module.exports = FitOutside; diff --git a/src/geom/rectangle/Floor.js b/src/geom/rectangle/Floor.js index 8f79186cb..fe76d2954 100644 --- a/src/geom/rectangle/Floor.js +++ b/src/geom/rectangle/Floor.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rounds down (floors) the top left X and Y coordinates of the given Rectangle to the largest integer less than or equal to them - * - * @function Phaser.Geom.Rectangle.Floor - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The rectangle to floor the top left X and Y coordinates of - * - * @return {Phaser.Geom.Rectangle} The rectangle that was passed to this function with its coordinates floored. - */ -var Floor = function (rect) -{ - rect.x = Math.floor(rect.x); - rect.y = Math.floor(rect.y); - - return rect; -}; - -module.exports = Floor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds down (floors) the top left X and Y coordinates of the given Rectangle to the largest integer less than or equal to them + * + * @function Phaser.Geom.Rectangle.Floor + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle to floor the top left X and Y coordinates of + * + * @return {Phaser.Geom.Rectangle} The rectangle that was passed to this function with its coordinates floored. + */ +var Floor = function (rect) +{ + rect.x = Math.floor(rect.x); + rect.y = Math.floor(rect.y); + + return rect; +}; + +module.exports = Floor; diff --git a/src/geom/rectangle/FloorAll.js b/src/geom/rectangle/FloorAll.js index c5c48fcb2..e80deacba 100644 --- a/src/geom/rectangle/FloorAll.js +++ b/src/geom/rectangle/FloorAll.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rounds a Rectangle's position and size down to the largest integer less than or equal to each current coordinate or dimension. - * - * @function Phaser.Geom.Rectangle.FloorAll - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. - * - * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. - */ -var FloorAll = function (rect) -{ - rect.x = Math.floor(rect.x); - rect.y = Math.floor(rect.y); - rect.width = Math.floor(rect.width); - rect.height = Math.floor(rect.height); - - return rect; -}; - -module.exports = FloorAll; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rounds a Rectangle's position and size down to the largest integer less than or equal to each current coordinate or dimension. + * + * @function Phaser.Geom.Rectangle.FloorAll + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var FloorAll = function (rect) +{ + rect.x = Math.floor(rect.x); + rect.y = Math.floor(rect.y); + rect.width = Math.floor(rect.width); + rect.height = Math.floor(rect.height); + + return rect; +}; + +module.exports = FloorAll; diff --git a/src/geom/rectangle/FromPoints.js b/src/geom/rectangle/FromPoints.js index 4cf816736..cb603fdf5 100644 --- a/src/geom/rectangle/FromPoints.js +++ b/src/geom/rectangle/FromPoints.js @@ -1,80 +1,80 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('./Rectangle'); -var MATH_CONST = require('../../math/const'); - -// points is an array of Point-like objects, -// either 2 dimensional arrays, or objects with public x/y properties: -// var points = [ -// [100, 200], -// [200, 400], -// { x: 30, y: 60 } -// ] - -/** - * Constructs new Rectangle or repositions and resizes an existing Rectangle so that all of the given points are on or within its bounds. - * - * @function Phaser.Geom.Rectangle.FromPoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {array} points - An array of points (either arrays with two elements corresponding to the X and Y coordinate or an object with public `x` and `y` properties) which should be surrounded by the Rectangle. - * @param {Phaser.Geom.Rectangle} [out] - Optional Rectangle to adjust. - * - * @return {Phaser.Geom.Rectangle} The adjusted `out` Rectangle, or a new Rectangle if none was provided. - */ -var FromPoints = function (points, out) -{ - if (out === undefined) { out = new Rectangle(); } - - if (points.length === 0) - { - return out; - } - - var minX = Number.MAX_VALUE; - var minY = Number.MAX_VALUE; - - var maxX = MATH_CONST.MIN_SAFE_INTEGER; - var maxY = MATH_CONST.MIN_SAFE_INTEGER; - - var p; - var px; - var py; - - for (var i = 0; i < points.length; i++) - { - p = points[i]; - - if (Array.isArray(p)) - { - px = p[0]; - py = p[1]; - } - else - { - px = p.x; - py = p.y; - } - - minX = Math.min(minX, px); - minY = Math.min(minY, py); - - maxX = Math.max(maxX, px); - maxY = Math.max(maxY, py); - } - - out.x = minX; - out.y = minY; - out.width = maxX - minX; - out.height = maxY - minY; - - return out; -}; - -module.exports = FromPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('./Rectangle'); +var MATH_CONST = require('../../math/const'); + +// points is an array of Point-like objects, +// either 2 dimensional arrays, or objects with public x/y properties: +// var points = [ +// [100, 200], +// [200, 400], +// { x: 30, y: 60 } +// ] + +/** + * Constructs new Rectangle or repositions and resizes an existing Rectangle so that all of the given points are on or within its bounds. + * + * @function Phaser.Geom.Rectangle.FromPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {array} points - An array of points (either arrays with two elements corresponding to the X and Y coordinate or an object with public `x` and `y` properties) which should be surrounded by the Rectangle. + * @param {Phaser.Geom.Rectangle} [out] - Optional Rectangle to adjust. + * + * @return {Phaser.Geom.Rectangle} The adjusted `out` Rectangle, or a new Rectangle if none was provided. + */ +var FromPoints = function (points, out) +{ + if (out === undefined) { out = new Rectangle(); } + + if (points.length === 0) + { + return out; + } + + var minX = Number.MAX_VALUE; + var minY = Number.MAX_VALUE; + + var maxX = MATH_CONST.MIN_SAFE_INTEGER; + var maxY = MATH_CONST.MIN_SAFE_INTEGER; + + var p; + var px; + var py; + + for (var i = 0; i < points.length; i++) + { + p = points[i]; + + if (Array.isArray(p)) + { + px = p[0]; + py = p[1]; + } + else + { + px = p.x; + py = p.y; + } + + minX = Math.min(minX, px); + minY = Math.min(minY, py); + + maxX = Math.max(maxX, px); + maxY = Math.max(maxY, py); + } + + out.x = minX; + out.y = minY; + out.width = maxX - minX; + out.height = maxY - minY; + + return out; +}; + +module.exports = FromPoints; diff --git a/src/geom/rectangle/GetAspectRatio.js b/src/geom/rectangle/GetAspectRatio.js index 155023155..595d56bbb 100644 --- a/src/geom/rectangle/GetAspectRatio.js +++ b/src/geom/rectangle/GetAspectRatio.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the width/height ratio of a rectangle. - * - * @function Phaser.Geom.Rectangle.GetAspectRatio - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The rectangle. - * - * @return {number} The width/height ratio of the rectangle. - */ -var GetAspectRatio = function (rect) -{ - return (rect.height === 0) ? NaN : rect.width / rect.height; -}; - -module.exports = GetAspectRatio; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the width/height ratio of a rectangle. + * + * @function Phaser.Geom.Rectangle.GetAspectRatio + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The rectangle. + * + * @return {number} The width/height ratio of the rectangle. + */ +var GetAspectRatio = function (rect) +{ + return (rect.height === 0) ? NaN : rect.width / rect.height; +}; + +module.exports = GetAspectRatio; diff --git a/src/geom/rectangle/GetCenter.js b/src/geom/rectangle/GetCenter.js index af8d98793..c5a5b4864 100644 --- a/src/geom/rectangle/GetCenter.js +++ b/src/geom/rectangle/GetCenter.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns the center of a Rectangle as a Point. - * - * @function Phaser.Geom.Rectangle.GetCenter - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the center of. - * @param {(Phaser.Geom.Point|object)} [out] - Optional point-like object to update with the center coordinates. - * - * @return {(Phaser.Geom.Point|object)} The modified `out` object, or a new Point if none was provided. - */ -var GetCenter = function (rect, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = rect.centerX; - out.y = rect.centerY; - - return out; -}; - -module.exports = GetCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns the center of a Rectangle as a Point. + * + * @function Phaser.Geom.Rectangle.GetCenter + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the center of. + * @param {(Phaser.Geom.Point|object)} [out] - Optional point-like object to update with the center coordinates. + * + * @return {(Phaser.Geom.Point|object)} The modified `out` object, or a new Point if none was provided. + */ +var GetCenter = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.centerX; + out.y = rect.centerY; + + return out; +}; + +module.exports = GetCenter; diff --git a/src/geom/rectangle/GetPoint.js b/src/geom/rectangle/GetPoint.js index 3a4f4dfcf..88192781c 100644 --- a/src/geom/rectangle/GetPoint.js +++ b/src/geom/rectangle/GetPoint.js @@ -1,75 +1,75 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Perimeter = require('./Perimeter'); -var Point = require('../point/Point'); - -/** - * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. - * - * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. - * - * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. - * - * @function Phaser.Geom.Rectangle.GetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. - * @param {number} position - The normalized distance into the Rectangle's perimeter to return. - * @param {(Phaser.Geom.Point|object)} [out] - An object to update with the `x` and `y` coordinates of the point. - * - * @return {Phaser.Geom.Point} The updated `output` object, or a new Point if no `output` object was given. - */ -var GetPoint = function (rectangle, position, out) -{ - if (out === undefined) { out = new Point(); } - - if (position <= 0 || position >= 1) - { - out.x = rectangle.x; - out.y = rectangle.y; - - return out; - } - - var p = Perimeter(rectangle) * position; - - if (position > 0.5) - { - p -= (rectangle.width + rectangle.height); - - if (p <= rectangle.width) - { - // Face 3 - out.x = rectangle.right - p; - out.y = rectangle.bottom; - } - else - { - // Face 4 - out.x = rectangle.x; - out.y = rectangle.bottom - (p - rectangle.width); - } - } - else if (p <= rectangle.width) - { - // Face 1 - out.x = rectangle.x + p; - out.y = rectangle.y; - } - else - { - // Face 2 - out.x = rectangle.right; - out.y = rectangle.y + (p - rectangle.width); - } - - return out; -}; - -module.exports = GetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Perimeter = require('./Perimeter'); +var Point = require('../point/Point'); + +/** + * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. + * + * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. + * + * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. + * + * @function Phaser.Geom.Rectangle.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. + * @param {number} position - The normalized distance into the Rectangle's perimeter to return. + * @param {(Phaser.Geom.Point|object)} [out] - An object to update with the `x` and `y` coordinates of the point. + * + * @return {Phaser.Geom.Point} The updated `output` object, or a new Point if no `output` object was given. + */ +var GetPoint = function (rectangle, position, out) +{ + if (out === undefined) { out = new Point(); } + + if (position <= 0 || position >= 1) + { + out.x = rectangle.x; + out.y = rectangle.y; + + return out; + } + + var p = Perimeter(rectangle) * position; + + if (position > 0.5) + { + p -= (rectangle.width + rectangle.height); + + if (p <= rectangle.width) + { + // Face 3 + out.x = rectangle.right - p; + out.y = rectangle.bottom; + } + else + { + // Face 4 + out.x = rectangle.x; + out.y = rectangle.bottom - (p - rectangle.width); + } + } + else if (p <= rectangle.width) + { + // Face 1 + out.x = rectangle.x + p; + out.y = rectangle.y; + } + else + { + // Face 2 + out.x = rectangle.right; + out.y = rectangle.y + (p - rectangle.width); + } + + return out; +}; + +module.exports = GetPoint; diff --git a/src/geom/rectangle/GetPoints.js b/src/geom/rectangle/GetPoints.js index 942d3fa1c..9cce24d71 100644 --- a/src/geom/rectangle/GetPoints.js +++ b/src/geom/rectangle/GetPoints.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetPoint = require('./GetPoint'); -var Perimeter = require('./Perimeter'); - -// Return an array of points from the perimeter of the rectangle -// each spaced out based on the quantity or step required - -/** - * Return an array of 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.Geom.Point[]} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle object to get the points from. - * @param {number} step - Step between points. Used to calculate the number of points to return when quantity is falsey. Ignored if quantity is positive. - * @param {integer} quantity - The number of evenly spaced points from the rectangles perimeter to return. If falsey, step param will be used to calculate the number of points. - * @param {(array|Phaser.Geom.Point[])} [out] - An optional array to store the points in. - * - * @return {(array|Phaser.Geom.Point[])} An array of Points from the perimeter of the rectangle. - */ -var GetPoints = function (rectangle, quantity, stepRate, out) -{ - if (out === undefined) { out = []; } - - // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!quantity) - { - quantity = Perimeter(rectangle) / stepRate; - } - - for (var i = 0; i < quantity; i++) - { - var position = i / quantity; - - out.push(GetPoint(rectangle, position)); - } - - return out; -}; - -module.exports = GetPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetPoint = require('./GetPoint'); +var Perimeter = require('./Perimeter'); + +// Return an array of points from the perimeter of the rectangle +// each spaced out based on the quantity or step required + +/** + * Return an array of 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.Geom.Point[]} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle object to get the points from. + * @param {number} step - Step between points. Used to calculate the number of points to return when quantity is falsey. Ignored if quantity is positive. + * @param {integer} quantity - The number of evenly spaced points from the rectangles perimeter to return. If falsey, step param will be used to calculate the number of points. + * @param {(array|Phaser.Geom.Point[])} [out] - An optional array to store the points in. + * + * @return {(array|Phaser.Geom.Point[])} An array of Points from the perimeter of the rectangle. + */ +var GetPoints = function (rectangle, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = Perimeter(rectangle) / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var position = i / quantity; + + out.push(GetPoint(rectangle, position)); + } + + return out; +}; + +module.exports = GetPoints; diff --git a/src/geom/rectangle/GetSize.js b/src/geom/rectangle/GetSize.js index d8f8f5fd7..483aa52e9 100644 --- a/src/geom/rectangle/GetSize.js +++ b/src/geom/rectangle/GetSize.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - - -/** - * Returns the size of the Rectangle, expressed as a Point object. - * With the value of the `width` as the `x` property and the `height` as the `y` property. - * - * @function Phaser.Geom.Rectangle.GetSize - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the size from. - * @param {(Phaser.Geom.Point|object)} [out] - The Point object to store the size in. If not given, a new Point instance is created. - * - * @return {(Phaser.Geom.Point|object)} A Point object where `x` holds the width and `y` holds the height of the Rectangle. - */ -var GetSize = function (rect, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = rect.width; - out.y = rect.height; - - return out; -}; - -module.exports = GetSize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + + +/** + * Returns the size of the Rectangle, expressed as a Point object. + * With the value of the `width` as the `x` property and the `height` as the `y` property. + * + * @function Phaser.Geom.Rectangle.GetSize + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the size from. + * @param {(Phaser.Geom.Point|object)} [out] - The Point object to store the size in. If not given, a new Point instance is created. + * + * @return {(Phaser.Geom.Point|object)} A Point object where `x` holds the width and `y` holds the height of the Rectangle. + */ +var GetSize = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.width; + out.y = rect.height; + + return out; +}; + +module.exports = GetSize; diff --git a/src/geom/rectangle/Inflate.js b/src/geom/rectangle/Inflate.js index cbf12e200..ee6b31497 100644 --- a/src/geom/rectangle/Inflate.js +++ b/src/geom/rectangle/Inflate.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CenterOn = require('./CenterOn'); - - -/** - * Increases the size of a Rectangle by a specified amount. - * - * The center of the Rectangle stays the same. The amounts are added to each side, so the actual increase in width or height is two times bigger than the respective argument. - * - * @function Phaser.Geom.Rectangle.Inflate - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to inflate. - * @param {number} x - How many pixels the left and the right side should be moved by horizontally. - * @param {number} y - How many pixels the top and the bottom side should be moved by vertically. - * - * @return {Phaser.Geom.Rectangle} The inflated Rectangle. - */ -var Inflate = function (rect, x, y) -{ - var cx = rect.centerX; - var cy = rect.centerY; - - rect.setSize(rect.width + (x * 2), rect.height + (y * 2)); - - return CenterOn(rect, cx, cy); -}; - -module.exports = Inflate; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CenterOn = require('./CenterOn'); + + +/** + * Increases the size of a Rectangle by a specified amount. + * + * The center of the Rectangle stays the same. The amounts are added to each side, so the actual increase in width or height is two times bigger than the respective argument. + * + * @function Phaser.Geom.Rectangle.Inflate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to inflate. + * @param {number} x - How many pixels the left and the right side should be moved by horizontally. + * @param {number} y - How many pixels the top and the bottom side should be moved by vertically. + * + * @return {Phaser.Geom.Rectangle} The inflated Rectangle. + */ +var Inflate = function (rect, x, y) +{ + var cx = rect.centerX; + var cy = rect.centerY; + + rect.setSize(rect.width + (x * 2), rect.height + (y * 2)); + + return CenterOn(rect, cx, cy); +}; + +module.exports = Inflate; diff --git a/src/geom/rectangle/Intersection.js b/src/geom/rectangle/Intersection.js index fc7357163..2c6d86831 100644 --- a/src/geom/rectangle/Intersection.js +++ b/src/geom/rectangle/Intersection.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('./Rectangle'); -var Intersects = require('../intersects/RectangleToRectangle'); - -/** - * Takes two Rectangles and first checks to see if they intersect. - * If they intersect it will return the area of intersection in the `out` Rectangle. - * If they do not intersect, the `out` Rectangle will have a width and height of zero. - * - * @function Phaser.Geom.Rectangle.Intersection - * @since 3.11.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to get the intersection from. - * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to get the intersection from. - * @param {Phaser.Geom.Rectangle} [out] - A Rectangle to store the intersection results in. - * - * @return {Phaser.Geom.Rectangle} The intersection result. If the width and height are zero, no intersection occurred. - */ -var Intersection = function (rectA, rectB, out) -{ - if (out === undefined) { out = new Rectangle(); } - - if (Intersects(rectA, rectB)) - { - out.x = Math.max(rectA.x, rectB.x); - out.y = Math.max(rectA.y, rectB.y); - out.width = Math.min(rectA.right, rectB.right) - out.x; - out.height = Math.min(rectA.bottom, rectB.bottom) - out.y; - } - else - { - out.setEmpty(); - } - - return out; -}; - -module.exports = Intersection; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('./Rectangle'); +var Intersects = require('../intersects/RectangleToRectangle'); + +/** + * Takes two Rectangles and first checks to see if they intersect. + * If they intersect it will return the area of intersection in the `out` Rectangle. + * If they do not intersect, the `out` Rectangle will have a width and height of zero. + * + * @function Phaser.Geom.Rectangle.Intersection + * @since 3.11.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to get the intersection from. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to get the intersection from. + * @param {Phaser.Geom.Rectangle} [out] - A Rectangle to store the intersection results in. + * + * @return {Phaser.Geom.Rectangle} The intersection result. If the width and height are zero, no intersection occurred. + */ +var Intersection = function (rectA, rectB, out) +{ + if (out === undefined) { out = new Rectangle(); } + + if (Intersects(rectA, rectB)) + { + out.x = Math.max(rectA.x, rectB.x); + out.y = Math.max(rectA.y, rectB.y); + out.width = Math.min(rectA.right, rectB.right) - out.x; + out.height = Math.min(rectA.bottom, rectB.bottom) - out.y; + } + else + { + out.setEmpty(); + } + + return out; +}; + +module.exports = Intersection; diff --git a/src/geom/rectangle/MarchingAnts.js b/src/geom/rectangle/MarchingAnts.js index c0c452cea..0e4f11a25 100644 --- a/src/geom/rectangle/MarchingAnts.js +++ b/src/geom/rectangle/MarchingAnts.js @@ -1,113 +1,113 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Perimeter = require('./Perimeter'); -var Point = require('../point/Point'); - - -/** - * Returns an array of points from the perimeter of the Rectangle, where each point is spaced out based - * on either the `step` value, or the `quantity`. - * - * @function Phaser.Geom.Rectangle.MarchingAnts - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point[]} 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 {integer} [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 {(array|Phaser.Geom.Point[])} [out] - An array in which the perimeter points will be stored. If not given, a new array instance is created. - * - * @return {(array|Phaser.Geom.Point[])} An array containing the perimeter points from the Rectangle. - */ -var MarchingAnts = function (rect, step, quantity, out) -{ - if (out === undefined) { out = []; } - - if (!step && !quantity) - { - // Bail out - return 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 - if (!step) - { - step = Perimeter(rect) / quantity; - } - else - { - quantity = Math.round(Perimeter(rect) / step); - } - - var x = rect.x; - var y = rect.y; - var face = 0; - - // Loop across each face of the rectangle - - for (var i = 0; i < quantity; i++) - { - out.push(new Point(x, y)); - - switch (face) - { - - // Top face - case 0: - x += step; - - if (x >= rect.right) - { - face = 1; - y += (x - rect.right); - x = rect.right; - } - break; - - // Right face - case 1: - y += step; - - if (y >= rect.bottom) - { - face = 2; - x -= (y - rect.bottom); - y = rect.bottom; - } - break; - - // Bottom face - case 2: - x -= step; - - if (x <= rect.left) - { - face = 3; - y -= (rect.left - x); - x = rect.left; - } - break; - - // Left face - case 3: - y -= step; - - if (y <= rect.top) - { - face = 0; - y = rect.top; - } - break; - } - } - - return out; -}; - -module.exports = MarchingAnts; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Perimeter = require('./Perimeter'); +var Point = require('../point/Point'); + + +/** + * Returns an array of points from the perimeter of the Rectangle, where each point is spaced out based + * on either the `step` value, or the `quantity`. + * + * @function Phaser.Geom.Rectangle.MarchingAnts + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} 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 {integer} [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 {(array|Phaser.Geom.Point[])} [out] - An array in which the perimeter points will be stored. If not given, a new array instance is created. + * + * @return {(array|Phaser.Geom.Point[])} An array containing the perimeter points from the Rectangle. + */ +var MarchingAnts = function (rect, step, quantity, out) +{ + if (out === undefined) { out = []; } + + if (!step && !quantity) + { + // Bail out + return 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 + if (!step) + { + step = Perimeter(rect) / quantity; + } + else + { + quantity = Math.round(Perimeter(rect) / step); + } + + var x = rect.x; + var y = rect.y; + var face = 0; + + // Loop across each face of the rectangle + + for (var i = 0; i < quantity; i++) + { + out.push(new Point(x, y)); + + switch (face) + { + + // Top face + case 0: + x += step; + + if (x >= rect.right) + { + face = 1; + y += (x - rect.right); + x = rect.right; + } + break; + + // Right face + case 1: + y += step; + + if (y >= rect.bottom) + { + face = 2; + x -= (y - rect.bottom); + y = rect.bottom; + } + break; + + // Bottom face + case 2: + x -= step; + + if (x <= rect.left) + { + face = 3; + y -= (rect.left - x); + x = rect.left; + } + break; + + // Left face + case 3: + y -= step; + + if (y <= rect.top) + { + face = 0; + y = rect.top; + } + break; + } + } + + return out; +}; + +module.exports = MarchingAnts; diff --git a/src/geom/rectangle/MergePoints.js b/src/geom/rectangle/MergePoints.js index d3544cc3b..78ff02b0c 100644 --- a/src/geom/rectangle/MergePoints.js +++ b/src/geom/rectangle/MergePoints.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Merges a Rectangle with a list of points by repositioning and/or resizing it such that all points are located on or within its bounds. - * - * @function Phaser.Geom.Rectangle.MergePoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [target,$return] - * - * @param {Phaser.Geom.Rectangle} target - The Rectangle which should be merged. - * @param {Phaser.Geom.Point[]} points - An array of Points (or any object with public `x` and `y` properties) which should be merged with the Rectangle. - * - * @return {Phaser.Geom.Rectangle} The modified Rectangle. - */ -var MergePoints = function (target, points) -{ - var minX = target.x; - var maxX = target.right; - var minY = target.y; - var maxY = target.bottom; - - for (var i = 0; i < points.length; i++) - { - minX = Math.min(minX, points[i].x); - maxX = Math.max(maxX, points[i].x); - minY = Math.min(minY, points[i].y); - maxY = Math.max(maxY, points[i].y); - } - - target.x = minX; - target.y = minY; - target.width = maxX - minX; - target.height = maxY - minY; - - return target; -}; - -module.exports = MergePoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Merges a Rectangle with a list of points by repositioning and/or resizing it such that all points are located on or within its bounds. + * + * @function Phaser.Geom.Rectangle.MergePoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The Rectangle which should be merged. + * @param {Phaser.Geom.Point[]} points - An array of Points (or any object with public `x` and `y` properties) which should be merged with the Rectangle. + * + * @return {Phaser.Geom.Rectangle} The modified Rectangle. + */ +var MergePoints = function (target, points) +{ + var minX = target.x; + var maxX = target.right; + var minY = target.y; + var maxY = target.bottom; + + for (var i = 0; i < points.length; i++) + { + minX = Math.min(minX, points[i].x); + maxX = Math.max(maxX, points[i].x); + minY = Math.min(minY, points[i].y); + maxY = Math.max(maxY, points[i].y); + } + + target.x = minX; + target.y = minY; + target.width = maxX - minX; + target.height = maxY - minY; + + return target; +}; + +module.exports = MergePoints; diff --git a/src/geom/rectangle/MergeRect.js b/src/geom/rectangle/MergeRect.js index 448a77ab4..1bc7bf732 100644 --- a/src/geom/rectangle/MergeRect.js +++ b/src/geom/rectangle/MergeRect.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Merges source rectangle into target rectangle and returns target -// Neither rect should have negative widths or heights - -/** - * Merges the source rectangle into the target rectangle and returns the target. - * Neither rectangle should have a negative width or height. - * - * @function Phaser.Geom.Rectangle.MergeRect - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [target,$return] - * - * @param {Phaser.Geom.Rectangle} target - Target rectangle. Will be modified to include source rectangle. - * @param {Phaser.Geom.Rectangle} source - Rectangle that will be merged into target rectangle. - * - * @return {Phaser.Geom.Rectangle} Modified target rectangle that contains source rectangle. - */ -var MergeRect = function (target, source) -{ - var minX = Math.min(target.x, source.x); - var maxX = Math.max(target.right, source.right); - - target.x = minX; - target.width = maxX - minX; - - var minY = Math.min(target.y, source.y); - var maxY = Math.max(target.bottom, source.bottom); - - target.y = minY; - target.height = maxY - minY; - - return target; -}; - -module.exports = MergeRect; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Merges source rectangle into target rectangle and returns target +// Neither rect should have negative widths or heights + +/** + * Merges the source rectangle into the target rectangle and returns the target. + * Neither rectangle should have a negative width or height. + * + * @function Phaser.Geom.Rectangle.MergeRect + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - Target rectangle. Will be modified to include source rectangle. + * @param {Phaser.Geom.Rectangle} source - Rectangle that will be merged into target rectangle. + * + * @return {Phaser.Geom.Rectangle} Modified target rectangle that contains source rectangle. + */ +var MergeRect = function (target, source) +{ + var minX = Math.min(target.x, source.x); + var maxX = Math.max(target.right, source.right); + + target.x = minX; + target.width = maxX - minX; + + var minY = Math.min(target.y, source.y); + var maxY = Math.max(target.bottom, source.bottom); + + target.y = minY; + target.height = maxY - minY; + + return target; +}; + +module.exports = MergeRect; diff --git a/src/geom/rectangle/MergeXY.js b/src/geom/rectangle/MergeXY.js index 1f4f51d0c..a69a1eb84 100644 --- a/src/geom/rectangle/MergeXY.js +++ b/src/geom/rectangle/MergeXY.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Merges a Rectangle with a point by repositioning and/or resizing it so that the point is on or within its bounds. - * - * @function Phaser.Geom.Rectangle.MergeXY - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [target,$return] - * - * @param {Phaser.Geom.Rectangle} target - The Rectangle which should be merged and modified. - * @param {number} x - The X coordinate of the point which should be merged. - * @param {number} y - The Y coordinate of the point which should be merged. - * - * @return {Phaser.Geom.Rectangle} The modified `target` Rectangle. - */ -var MergeXY = function (target, x, y) -{ - var minX = Math.min(target.x, x); - var maxX = Math.max(target.right, x); - - target.x = minX; - target.width = maxX - minX; - - var minY = Math.min(target.y, y); - var maxY = Math.max(target.bottom, y); - - target.y = minY; - target.height = maxY - minY; - - return target; -}; - -module.exports = MergeXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Merges a Rectangle with a point by repositioning and/or resizing it so that the point is on or within its bounds. + * + * @function Phaser.Geom.Rectangle.MergeXY + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [target,$return] + * + * @param {Phaser.Geom.Rectangle} target - The Rectangle which should be merged and modified. + * @param {number} x - The X coordinate of the point which should be merged. + * @param {number} y - The Y coordinate of the point which should be merged. + * + * @return {Phaser.Geom.Rectangle} The modified `target` Rectangle. + */ +var MergeXY = function (target, x, y) +{ + var minX = Math.min(target.x, x); + var maxX = Math.max(target.right, x); + + target.x = minX; + target.width = maxX - minX; + + var minY = Math.min(target.y, y); + var maxY = Math.max(target.bottom, y); + + target.y = minY; + target.height = maxY - minY; + + return target; +}; + +module.exports = MergeXY; diff --git a/src/geom/rectangle/Offset.js b/src/geom/rectangle/Offset.js index f70882059..bed4763b7 100644 --- a/src/geom/rectangle/Offset.js +++ b/src/geom/rectangle/Offset.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Nudges (translates) the top left corner of a Rectangle by a given offset. - * - * @function Phaser.Geom.Rectangle.Offset - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. - * @param {number} x - The distance to move the Rectangle horizontally. - * @param {number} y - The distance to move the Rectangle vertically. - * - * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. - */ -var Offset = function (rect, x, y) -{ - rect.x += x; - rect.y += y; - - return rect; -}; - -module.exports = Offset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Nudges (translates) the top left corner of a Rectangle by a given offset. + * + * @function Phaser.Geom.Rectangle.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * @param {number} x - The distance to move the Rectangle horizontally. + * @param {number} y - The distance to move the Rectangle vertically. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var Offset = function (rect, x, y) +{ + rect.x += x; + rect.y += y; + + return rect; +}; + +module.exports = Offset; diff --git a/src/geom/rectangle/OffsetPoint.js b/src/geom/rectangle/OffsetPoint.js index b06e8965f..596999216 100644 --- a/src/geom/rectangle/OffsetPoint.js +++ b/src/geom/rectangle/OffsetPoint.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Nudges (translates) the top-left corner of a Rectangle by the coordinates of a point (translation vector). - * - * @function Phaser.Geom.Rectangle.OffsetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. - * @param {(Phaser.Geom.Point|Phaser.Math.Vector2)} point - The point whose coordinates should be used as an offset. - * - * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. - */ -var OffsetPoint = function (rect, point) -{ - rect.x += point.x; - rect.y += point.y; - - return rect; -}; - -module.exports = OffsetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Nudges (translates) the top-left corner of a Rectangle by the coordinates of a point (translation vector). + * + * @function Phaser.Geom.Rectangle.OffsetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to adjust. + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2)} point - The point whose coordinates should be used as an offset. + * + * @return {Phaser.Geom.Rectangle} The adjusted Rectangle. + */ +var OffsetPoint = function (rect, point) +{ + rect.x += point.x; + rect.y += point.y; + + return rect; +}; + +module.exports = OffsetPoint; diff --git a/src/geom/rectangle/Overlaps.js b/src/geom/rectangle/Overlaps.js index b595d6521..40855e1f9 100644 --- a/src/geom/rectangle/Overlaps.js +++ b/src/geom/rectangle/Overlaps.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if two Rectangles overlap. If a Rectangle is within another Rectangle, the two will be considered overlapping. Thus, the Rectangles are treated as "solid". - * - * @function Phaser.Geom.Rectangle.Overlaps - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check. - * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check. - * - * @return {boolean} `true` if the two Rectangles overlap, `false` otherwise. - */ -var Overlaps = function (rectA, rectB) -{ - return ( - rectA.x < rectB.right && - rectA.right > rectB.x && - rectA.y < rectB.bottom && - rectA.bottom > rectB.y - ); -}; - -module.exports = Overlaps; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if two Rectangles overlap. If a Rectangle is within another Rectangle, the two will be considered overlapping. Thus, the Rectangles are treated as "solid". + * + * @function Phaser.Geom.Rectangle.Overlaps + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check. + * + * @return {boolean} `true` if the two Rectangles overlap, `false` otherwise. + */ +var Overlaps = function (rectA, rectB) +{ + return ( + rectA.x < rectB.right && + rectA.right > rectB.x && + rectA.y < rectB.bottom && + rectA.bottom > rectB.y + ); +}; + +module.exports = Overlaps; diff --git a/src/geom/rectangle/Perimeter.js b/src/geom/rectangle/Perimeter.js index 68eaf0d4b..0b9f0934a 100644 --- a/src/geom/rectangle/Perimeter.js +++ b/src/geom/rectangle/Perimeter.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the perimeter of a Rectangle. - * - * @function Phaser.Geom.Rectangle.Perimeter - * @since 3.0.0 - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to use. - * - * @return {number} The perimeter of the Rectangle, equal to `(width * 2) + (height * 2)`. - */ -var Perimeter = function (rect) -{ - return 2 * (rect.width + rect.height); -}; - -module.exports = Perimeter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the perimeter of a Rectangle. + * + * @function Phaser.Geom.Rectangle.Perimeter + * @since 3.0.0 + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to use. + * + * @return {number} The perimeter of the Rectangle, equal to `(width * 2) + (height * 2)`. + */ +var Perimeter = function (rect) +{ + return 2 * (rect.width + rect.height); +}; + +module.exports = Perimeter; diff --git a/src/geom/rectangle/PerimeterPoint.js b/src/geom/rectangle/PerimeterPoint.js index e76b79702..442f6f85e 100644 --- a/src/geom/rectangle/PerimeterPoint.js +++ b/src/geom/rectangle/PerimeterPoint.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); -var DegToRad = require('../../math/DegToRad'); - -/** - * Returns a Point from the perimeter of a Rectangle based on the given angle. - * - * @function Phaser.Geom.Rectangle.PerimeterPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. - * @param {integer} angle - The angle of the point, in degrees. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. - * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of the Rectangle perimeter. - */ -var PerimeterPoint = function (rectangle, angle, out) -{ - if (out === undefined) { out = new Point(); } - - angle = DegToRad(angle); - - var s = Math.sin(angle); - var c = Math.cos(angle); - - var dx = (c > 0) ? rectangle.width / 2 : rectangle.width / -2; - var dy = (s > 0) ? rectangle.height / 2 : rectangle.height / -2; - - if (Math.abs(dx * s) < Math.abs(dy * c)) - { - dy = (dx * s) / c; - } - else - { - dx = (dy * c) / s; - } - - out.x = dx + rectangle.centerX; - out.y = dy + rectangle.centerY; - - return out; -}; - -module.exports = PerimeterPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); +var DegToRad = require('../../math/DegToRad'); + +/** + * Returns a Point from the perimeter of a Rectangle based on the given angle. + * + * @function Phaser.Geom.Rectangle.PerimeterPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from. + * @param {integer} angle - The angle of the point, in degrees. + * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * + * @return {Phaser.Geom.Point} A Point object holding the coordinates of the Rectangle perimeter. + */ +var PerimeterPoint = function (rectangle, angle, out) +{ + if (out === undefined) { out = new Point(); } + + angle = DegToRad(angle); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var dx = (c > 0) ? rectangle.width / 2 : rectangle.width / -2; + var dy = (s > 0) ? rectangle.height / 2 : rectangle.height / -2; + + if (Math.abs(dx * s) < Math.abs(dy * c)) + { + dy = (dx * s) / c; + } + else + { + dx = (dy * c) / s; + } + + out.x = dx + rectangle.centerX; + out.y = dy + rectangle.centerY; + + return out; +}; + +module.exports = PerimeterPoint; diff --git a/src/geom/rectangle/Random.js b/src/geom/rectangle/Random.js index 713956116..a8bad7b92 100644 --- a/src/geom/rectangle/Random.js +++ b/src/geom/rectangle/Random.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a random point within a Rectangle. - * - * @function Phaser.Geom.Rectangle.Random - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The Rectangle to return a point from. - * @param {Phaser.Geom.Point} out - The object to update with the point's coordinates. - * - * @return {Phaser.Geom.Point} The modified `out` object, or a new Point if none was provided. - */ -var Random = function (rect, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = rect.x + (Math.random() * rect.width); - out.y = rect.y + (Math.random() * rect.height); - - return out; -}; - -module.exports = Random; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a random point within a Rectangle. + * + * @function Phaser.Geom.Rectangle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to return a point from. + * @param {Phaser.Geom.Point} out - The object to update with the point's coordinates. + * + * @return {Phaser.Geom.Point} The modified `out` object, or a new Point if none was provided. + */ +var Random = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.x + (Math.random() * rect.width); + out.y = rect.y + (Math.random() * rect.height); + + return out; +}; + +module.exports = Random; diff --git a/src/geom/rectangle/RandomOutside.js b/src/geom/rectangle/RandomOutside.js index 19682f4d1..708af0cc5 100644 --- a/src/geom/rectangle/RandomOutside.js +++ b/src/geom/rectangle/RandomOutside.js @@ -1,65 +1,65 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Between = require('../../math/Between'); -var ContainsRect = require('./ContainsRect'); -var Point = require('../point/Point'); - -/** - * Calculates a random point that lies within the `outer` Rectangle, but outside of the `inner` Rectangle. - * The inner Rectangle must be fully contained within the outer rectangle. - * - * @function Phaser.Geom.Rectangle.RandomOutside - * @since 3.10.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} outer - The outer Rectangle to get the random point within. - * @param {Phaser.Geom.Rectangle} inner - The inner Rectangle to exclude from the returned point. - * @param {Phaser.Geom.Point} [out] - A Point, or Point-like object to store the result in. If not specified, a new Point will be created. - * - * @return {Phaser.Geom.Point} A Point object containing the random values in its `x` and `y` properties. - */ -var RandomOutside = function (outer, inner, out) -{ - if (out === undefined) { out = new Point(); } - - if (ContainsRect(outer, inner)) - { - // 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 - - switch (Between(0, 3)) - { - case 0: // Top - out.x = outer.x + (Math.random() * (inner.right - outer.x)); - out.y = outer.y + (Math.random() * (inner.top - outer.y)); - break; - - case 1: // Bottom - out.x = inner.x + (Math.random() * (outer.right - inner.x)); - out.y = inner.bottom + (Math.random() * (outer.bottom - inner.bottom)); - break; - - case 2: // Left - out.x = outer.x + (Math.random() * (inner.x - outer.x)); - out.y = inner.y + (Math.random() * (outer.bottom - inner.y)); - break; - - case 3: // Right - out.x = inner.right + (Math.random() * (outer.right - inner.right)); - out.y = outer.y + (Math.random() * (inner.bottom - outer.y)); - break; - } - } - - return out; -}; - -module.exports = RandomOutside; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Between = require('../../math/Between'); +var ContainsRect = require('./ContainsRect'); +var Point = require('../point/Point'); + +/** + * Calculates a random point that lies within the `outer` Rectangle, but outside of the `inner` Rectangle. + * The inner Rectangle must be fully contained within the outer rectangle. + * + * @function Phaser.Geom.Rectangle.RandomOutside + * @since 3.10.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} outer - The outer Rectangle to get the random point within. + * @param {Phaser.Geom.Rectangle} inner - The inner Rectangle to exclude from the returned point. + * @param {Phaser.Geom.Point} [out] - A Point, or Point-like object to store the result in. If not specified, a new Point will be created. + * + * @return {Phaser.Geom.Point} A Point object containing the random values in its `x` and `y` properties. + */ +var RandomOutside = function (outer, inner, out) +{ + if (out === undefined) { out = new Point(); } + + if (ContainsRect(outer, inner)) + { + // 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 + + switch (Between(0, 3)) + { + case 0: // Top + out.x = outer.x + (Math.random() * (inner.right - outer.x)); + out.y = outer.y + (Math.random() * (inner.top - outer.y)); + break; + + case 1: // Bottom + out.x = inner.x + (Math.random() * (outer.right - inner.x)); + out.y = inner.bottom + (Math.random() * (outer.bottom - inner.bottom)); + break; + + case 2: // Left + out.x = outer.x + (Math.random() * (inner.x - outer.x)); + out.y = inner.y + (Math.random() * (outer.bottom - inner.y)); + break; + + case 3: // Right + out.x = inner.right + (Math.random() * (outer.right - inner.right)); + out.y = outer.y + (Math.random() * (inner.bottom - outer.y)); + break; + } + } + + return out; +}; + +module.exports = RandomOutside; diff --git a/src/geom/rectangle/Rectangle.js b/src/geom/rectangle/Rectangle.js index 3b5fd7d61..cd26662dc 100644 --- a/src/geom/rectangle/Rectangle.js +++ b/src/geom/rectangle/Rectangle.js @@ -1,505 +1,505 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Contains = require('./Contains'); -var GetPoint = require('./GetPoint'); -var GetPoints = require('./GetPoints'); -var GEOM_CONST = require('../const'); -var Line = require('../line/Line'); -var Random = require('./Random'); - -/** - * @classdesc - * Encapsulates a 2D rectangle defined by its corner point in the top-left and its extends in x (width) and y (height) - * - * @class Rectangle - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {number} [x=0] - The X coordinate of the top left corner of the Rectangle. - * @param {number} [y=0] - The Y coordinate of the top left corner of the Rectangle. - * @param {number} [width=0] - The width of the Rectangle. - * @param {number} [height=0] - The height of the Rectangle. - */ -var Rectangle = new Class({ - - initialize: - - function Rectangle (x, y, width, height) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = 0; } - if (height === undefined) { height = 0; } - - /** - * The geometry constant type of this object: `GEOM_CONST.RECTANGLE`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Rectangle#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.RECTANGLE; - - /** - * The X coordinate of the top left corner of the Rectangle. - * - * @name Phaser.Geom.Rectangle#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = x; - - /** - * The Y coordinate of the top left corner of the Rectangle. - * - * @name Phaser.Geom.Rectangle#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = y; - - /** - * The width of the Rectangle, i.e. the distance between its left side (defined by `x`) and its right side. - * - * @name Phaser.Geom.Rectangle#width - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.width = width; - - /** - * The height of the Rectangle, i.e. the distance between its top side (defined by `y`) and its bottom side. - * - * @name Phaser.Geom.Rectangle#height - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.height = height; - }, - - /** - * Checks if the given point is inside the Rectangle's bounds. - * - * @method Phaser.Geom.Rectangle#contains - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the point to check. - * @param {number} y - The Y coordinate of the point to check. - * - * @return {boolean} `true` if the point is within the Rectangle's bounds, otherwise `false`. - */ - contains: function (x, y) - { - return Contains(this, x, y); - }, - - /** - * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. - * - * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. - * - * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. - * - * @method Phaser.Geom.Rectangle#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [output,$return] - * - * @param {number} position - The normalized distance into the Rectangle's perimeter to return. - * @param {(Phaser.Geom.Point|object)} [output] - An object to update with the `x` and `y` coordinates of the point. - * - * @return {(Phaser.Geom.Point|object)} The updated `output` object, or a new Point if no `output` object was given. - */ - getPoint: function (position, output) - { - return GetPoint(this, position, output); - }, - - /** - * 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.Geom.Point[]} O - [output,$return] - * - * @param {integer} 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 {(array|Phaser.Geom.Point[])} [output] - An array to which to append the points. - * - * @return {(array|Phaser.Geom.Point[])} The modified `output` array, or a new array if none was provided. - */ - getPoints: function (quantity, stepRate, output) - { - return GetPoints(this, quantity, stepRate, output); - }, - - /** - * Returns a random point within the Rectangle's bounds. - * - * @method Phaser.Geom.Rectangle#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {Phaser.Geom.Point} [point] - The object in which to store the `x` and `y` coordinates of the point. - * - * @return {Phaser.Geom.Point} The updated `point`, or a new Point if none was provided. - */ - getRandomPoint: function (point) - { - return Random(this, point); - }, - - /** - * Sets the position, width, and height of the Rectangle. - * - * @method Phaser.Geom.Rectangle#setTo - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the top left corner of the Rectangle. - * @param {number} y - The Y coordinate of the top left corner of the Rectangle. - * @param {number} width - The width of the Rectangle. - * @param {number} height - The height of the Rectangle. - * - * @return {Phaser.Geom.Rectangle} This Rectangle object. - */ - setTo: function (x, y, width, height) - { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - - return this; - }, - - /** - * Resets the position, width, and height of the Rectangle to 0. - * - * @method Phaser.Geom.Rectangle#setEmpty - * @since 3.0.0 - * - * @return {Phaser.Geom.Rectangle} This Rectangle object. - */ - setEmpty: function () - { - return this.setTo(0, 0, 0, 0); - }, - - /** - * Sets the position of the Rectangle. - * - * @method Phaser.Geom.Rectangle#setPosition - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the top left corner of the Rectangle. - * @param {number} [y=x] - The Y coordinate of the top left corner of the Rectangle. - * - * @return {Phaser.Geom.Rectangle} This Rectangle object. - */ - setPosition: function (x, y) - { - if (y === undefined) { y = x; } - - this.x = x; - this.y = y; - - return this; - }, - - /** - * Sets the width and height of the Rectangle. - * - * @method Phaser.Geom.Rectangle#setSize - * @since 3.0.0 - * - * @param {number} width - The width to set the Rectangle to. - * @param {number} [height=width] - The height to set the Rectangle to. - * - * @return {Phaser.Geom.Rectangle} This Rectangle object. - */ - setSize: function (width, height) - { - if (height === undefined) { height = width; } - - this.width = width; - this.height = height; - - return this; - }, - - /** - * Determines if the Rectangle is empty. A Rectangle is empty if its width or height is less than or equal to 0. - * - * @method Phaser.Geom.Rectangle#isEmpty - * @since 3.0.0 - * - * @return {boolean} `true` if the Rectangle is empty. A Rectangle object is empty if its width or height is less than or equal to 0. - */ - isEmpty: function () - { - return (this.width <= 0 || this.height <= 0); - }, - - /** - * Returns a Line object that corresponds to the top of this Rectangle. - * - * @method Phaser.Geom.Rectangle#getLineA - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to the top of this Rectangle. - */ - getLineA: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.x, this.y, this.right, this.y); - - return line; - }, - - /** - * Returns a Line object that corresponds to the right of this Rectangle. - * - * @method Phaser.Geom.Rectangle#getLineB - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to the right of this Rectangle. - */ - getLineB: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.right, this.y, this.right, this.bottom); - - return line; - }, - - /** - * Returns a Line object that corresponds to the bottom of this Rectangle. - * - * @method Phaser.Geom.Rectangle#getLineC - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to the bottom of this Rectangle. - */ - getLineC: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.right, this.bottom, this.x, this.bottom); - - return line; - }, - - /** - * Returns a Line object that corresponds to the left of this Rectangle. - * - * @method Phaser.Geom.Rectangle#getLineD - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to the left of this Rectangle. - */ - getLineD: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.x, this.bottom, this.x, this.y); - - return line; - }, - - /** - * The x coordinate of the left of the Rectangle. - * Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. - * - * @name Phaser.Geom.Rectangle#left - * @type {number} - * @since 3.0.0 - */ - left: { - - get: function () - { - return this.x; - }, - - set: function (value) - { - if (value >= this.right) - { - this.width = 0; - } - else - { - this.width = this.right - value; - } - - this.x = value; - } - - }, - - /** - * The sum of the x and width properties. - * Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. - * - * @name Phaser.Geom.Rectangle#right - * @type {number} - * @since 3.0.0 - */ - right: { - - get: function () - { - return this.x + this.width; - }, - - set: function (value) - { - if (value <= this.x) - { - this.width = 0; - } - else - { - this.width = value - this.x; - } - } - - }, - - /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * - * @name Phaser.Geom.Rectangle#top - * @type {number} - * @since 3.0.0 - */ - top: { - - get: function () - { - return this.y; - }, - - set: function (value) - { - if (value >= this.bottom) - { - this.height = 0; - } - else - { - this.height = (this.bottom - value); - } - - this.y = value; - } - - }, - - /** - * The sum of the y and height properties. - * Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * - * @name Phaser.Geom.Rectangle#bottom - * @type {number} - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return this.y + this.height; - }, - - set: function (value) - { - if (value <= this.y) - { - this.height = 0; - } - else - { - this.height = value - this.y; - } - } - - }, - - /** - * The x coordinate of the center of the Rectangle. - * - * @name Phaser.Geom.Rectangle#centerX - * @type {number} - * @since 3.0.0 - */ - centerX: { - - get: function () - { - return this.x + (this.width / 2); - }, - - set: function (value) - { - this.x = value - (this.width / 2); - } - - }, - - /** - * The y coordinate of the center of the Rectangle. - * - * @name Phaser.Geom.Rectangle#centerY - * @type {number} - * @since 3.0.0 - */ - centerY: { - - get: function () - { - return this.y + (this.height / 2); - }, - - set: function (value) - { - this.y = value - (this.height / 2); - } - - } - -}); - -module.exports = Rectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Contains = require('./Contains'); +var GetPoint = require('./GetPoint'); +var GetPoints = require('./GetPoints'); +var GEOM_CONST = require('../const'); +var Line = require('../line/Line'); +var Random = require('./Random'); + +/** + * @classdesc + * Encapsulates a 2D rectangle defined by its corner point in the top-left and its extends in x (width) and y (height) + * + * @class Rectangle + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x=0] - The X coordinate of the top left corner of the Rectangle. + * @param {number} [y=0] - The Y coordinate of the top left corner of the Rectangle. + * @param {number} [width=0] - The width of the Rectangle. + * @param {number} [height=0] - The height of the Rectangle. + */ +var Rectangle = new Class({ + + initialize: + + function Rectangle (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.RECTANGLE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Rectangle#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.RECTANGLE; + + /** + * The X coordinate of the top left corner of the Rectangle. + * + * @name Phaser.Geom.Rectangle#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = x; + + /** + * The Y coordinate of the top left corner of the Rectangle. + * + * @name Phaser.Geom.Rectangle#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = y; + + /** + * The width of the Rectangle, i.e. the distance between its left side (defined by `x`) and its right side. + * + * @name Phaser.Geom.Rectangle#width + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the Rectangle, i.e. the distance between its top side (defined by `y`) and its bottom side. + * + * @name Phaser.Geom.Rectangle#height + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.height = height; + }, + + /** + * Checks if the given point is inside the Rectangle's bounds. + * + * @method Phaser.Geom.Rectangle#contains + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is within the Rectangle's bounds, otherwise `false`. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. + * + * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. + * + * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. + * + * @method Phaser.Geom.Rectangle#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [output,$return] + * + * @param {number} position - The normalized distance into the Rectangle's perimeter to return. + * @param {(Phaser.Geom.Point|object)} [output] - An object to update with the `x` and `y` coordinates of the point. + * + * @return {(Phaser.Geom.Point|object)} The updated `output` object, or a new Point if no `output` object was given. + */ + getPoint: function (position, output) + { + return GetPoint(this, position, output); + }, + + /** + * 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.Geom.Point[]} O - [output,$return] + * + * @param {integer} 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 {(array|Phaser.Geom.Point[])} [output] - An array to which to append the points. + * + * @return {(array|Phaser.Geom.Point[])} The modified `output` array, or a new array if none was provided. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a random point within the Rectangle's bounds. + * + * @method Phaser.Geom.Rectangle#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} [point] - The object in which to store the `x` and `y` coordinates of the point. + * + * @return {Phaser.Geom.Point} The updated `point`, or a new Point if none was provided. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets the position, width, and height of the Rectangle. + * + * @method Phaser.Geom.Rectangle#setTo + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the top left corner of the Rectangle. + * @param {number} y - The Y coordinate of the top left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setTo: function (x, y, width, height) + { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + }, + + /** + * Resets the position, width, and height of the Rectangle to 0. + * + * @method Phaser.Geom.Rectangle#setEmpty + * @since 3.0.0 + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setEmpty: function () + { + return this.setTo(0, 0, 0, 0); + }, + + /** + * Sets the position of the Rectangle. + * + * @method Phaser.Geom.Rectangle#setPosition + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the top left corner of the Rectangle. + * @param {number} [y=x] - The Y coordinate of the top left corner of the Rectangle. + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setPosition: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * Sets the width and height of the Rectangle. + * + * @method Phaser.Geom.Rectangle#setSize + * @since 3.0.0 + * + * @param {number} width - The width to set the Rectangle to. + * @param {number} [height=width] - The height to set the Rectangle to. + * + * @return {Phaser.Geom.Rectangle} This Rectangle object. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + this.width = width; + this.height = height; + + return this; + }, + + /** + * Determines if the Rectangle is empty. A Rectangle is empty if its width or height is less than or equal to 0. + * + * @method Phaser.Geom.Rectangle#isEmpty + * @since 3.0.0 + * + * @return {boolean} `true` if the Rectangle is empty. A Rectangle object is empty if its width or height is less than or equal to 0. + */ + isEmpty: function () + { + return (this.width <= 0 || this.height <= 0); + }, + + /** + * Returns a Line object that corresponds to the top of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineA + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the top of this Rectangle. + */ + getLineA: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x, this.y, this.right, this.y); + + return line; + }, + + /** + * Returns a Line object that corresponds to the right of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineB + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the right of this Rectangle. + */ + getLineB: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.right, this.y, this.right, this.bottom); + + return line; + }, + + /** + * Returns a Line object that corresponds to the bottom of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineC + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the bottom of this Rectangle. + */ + getLineC: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.right, this.bottom, this.x, this.bottom); + + return line; + }, + + /** + * Returns a Line object that corresponds to the left of this Rectangle. + * + * @method Phaser.Geom.Rectangle#getLineD + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to the left of this Rectangle. + */ + getLineD: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x, this.bottom, this.x, this.y); + + return line; + }, + + /** + * The x coordinate of the left of the Rectangle. + * Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * + * @name Phaser.Geom.Rectangle#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.x; + }, + + set: function (value) + { + if (value >= this.right) + { + this.width = 0; + } + else + { + this.width = this.right - value; + } + + this.x = value; + } + + }, + + /** + * The sum of the x and width properties. + * Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. + * + * @name Phaser.Geom.Rectangle#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.x + this.width; + }, + + set: function (value) + { + if (value <= this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + + }, + + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * + * @name Phaser.Geom.Rectangle#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.y; + }, + + set: function (value) + { + if (value >= this.bottom) + { + this.height = 0; + } + else + { + this.height = (this.bottom - value); + } + + this.y = value; + } + + }, + + /** + * The sum of the y and height properties. + * Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * + * @name Phaser.Geom.Rectangle#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.y + this.height; + }, + + set: function (value) + { + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + + }, + + /** + * The x coordinate of the center of the Rectangle. + * + * @name Phaser.Geom.Rectangle#centerX + * @type {number} + * @since 3.0.0 + */ + centerX: { + + get: function () + { + return this.x + (this.width / 2); + }, + + set: function (value) + { + this.x = value - (this.width / 2); + } + + }, + + /** + * The y coordinate of the center of the Rectangle. + * + * @name Phaser.Geom.Rectangle#centerY + * @type {number} + * @since 3.0.0 + */ + centerY: { + + get: function () + { + return this.y + (this.height / 2); + }, + + set: function (value) + { + this.y = value - (this.height / 2); + } + + } + +}); + +module.exports = Rectangle; diff --git a/src/geom/rectangle/SameDimensions.js b/src/geom/rectangle/SameDimensions.js index 64fc94659..9a564ce52 100644 --- a/src/geom/rectangle/SameDimensions.js +++ b/src/geom/rectangle/SameDimensions.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. - * - * @function Phaser.Geom.Rectangle.SameDimensions - * @since 3.15.0 - * - * @param {Phaser.Geom.Rectangle} rect - The first Rectangle object. - * @param {Phaser.Geom.Rectangle} toCompare - The second Rectangle object. - * - * @return {boolean} `true` if the objects have equivalent values for the `width` and `height` properties, otherwise `false`. - */ -var SameDimensions = function (rect, toCompare) -{ - return (rect.width === toCompare.width && rect.height === toCompare.height); -}; - -module.exports = SameDimensions; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. + * + * @function Phaser.Geom.Rectangle.SameDimensions + * @since 3.15.0 + * + * @param {Phaser.Geom.Rectangle} rect - The first Rectangle object. + * @param {Phaser.Geom.Rectangle} toCompare - The second Rectangle object. + * + * @return {boolean} `true` if the objects have equivalent values for the `width` and `height` properties, otherwise `false`. + */ +var SameDimensions = function (rect, toCompare) +{ + return (rect.width === toCompare.width && rect.height === toCompare.height); +}; + +module.exports = SameDimensions; diff --git a/src/geom/rectangle/Scale.js b/src/geom/rectangle/Scale.js index efbbcc174..97cf965e8 100644 --- a/src/geom/rectangle/Scale.js +++ b/src/geom/rectangle/Scale.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Scales the width and height of this Rectangle by the given amounts. - -/** - * Scales the width and height of this Rectangle by the given amounts. - * - * @function Phaser.Geom.Rectangle.Scale - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [rect,$return] - * - * @param {Phaser.Geom.Rectangle} rect - The `Rectangle` object that will be scaled by the specified amount(s). - * @param {number} x - The factor by which to scale the rectangle horizontally. - * @param {number} y - The amount by which to scale the rectangle vertically. If this is not specified, the rectangle will be scaled by the factor `x` in both directions. - * - * @return {Phaser.Geom.Rectangle} The rectangle object with updated `width` and `height` properties as calculated from the scaling factor(s). - */ -var Scale = function (rect, x, y) -{ - if (y === undefined) { y = x; } - - rect.width *= x; - rect.height *= y; - - return rect; -}; - -module.exports = Scale; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Scales the width and height of this Rectangle by the given amounts. + +/** + * Scales the width and height of this Rectangle by the given amounts. + * + * @function Phaser.Geom.Rectangle.Scale + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [rect,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The `Rectangle` object that will be scaled by the specified amount(s). + * @param {number} x - The factor by which to scale the rectangle horizontally. + * @param {number} y - The amount by which to scale the rectangle vertically. If this is not specified, the rectangle will be scaled by the factor `x` in both directions. + * + * @return {Phaser.Geom.Rectangle} The rectangle object with updated `width` and `height` properties as calculated from the scaling factor(s). + */ +var Scale = function (rect, x, y) +{ + if (y === undefined) { y = x; } + + rect.width *= x; + rect.height *= y; + + return rect; +}; + +module.exports = Scale; diff --git a/src/geom/rectangle/Union.js b/src/geom/rectangle/Union.js index 6ac609c91..032792b31 100644 --- a/src/geom/rectangle/Union.js +++ b/src/geom/rectangle/Union.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('./Rectangle'); - -/** - * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. - * - * @function Phaser.Geom.Rectangle.Union - * @since 3.0.0 - * - * @generic {Phaser.Geom.Rectangle} O - [out,$return] - * - * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to use. - * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to use. - * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the union in. - * - * @return {Phaser.Geom.Rectangle} The modified `out` Rectangle, or a new Rectangle if none was provided. - */ -var Union = function (rectA, rectB, out) -{ - if (out === undefined) { out = new Rectangle(); } - - // Cache vars so we can use one of the input rects as the output rect - var x = Math.min(rectA.x, rectB.x); - var y = Math.min(rectA.y, rectB.y); - var w = Math.max(rectA.right, rectB.right) - x; - var h = Math.max(rectA.bottom, rectB.bottom) - y; - - return out.setTo(x, y, w, h); -}; - -module.exports = Union; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('./Rectangle'); + +/** + * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. + * + * @function Phaser.Geom.Rectangle.Union + * @since 3.0.0 + * + * @generic {Phaser.Geom.Rectangle} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to use. + * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to use. + * @param {Phaser.Geom.Rectangle} [out] - The Rectangle to store the union in. + * + * @return {Phaser.Geom.Rectangle} The modified `out` Rectangle, or a new Rectangle if none was provided. + */ +var Union = function (rectA, rectB, out) +{ + if (out === undefined) { out = new Rectangle(); } + + // Cache vars so we can use one of the input rects as the output rect + var x = Math.min(rectA.x, rectB.x); + var y = Math.min(rectA.y, rectB.y); + var w = Math.max(rectA.right, rectB.right) - x; + var h = Math.max(rectA.bottom, rectB.bottom) - y; + + return out.setTo(x, y, w, h); +}; + +module.exports = Union; diff --git a/src/geom/rectangle/index.js b/src/geom/rectangle/index.js index 35c9e1a22..de710a00f 100644 --- a/src/geom/rectangle/index.js +++ b/src/geom/rectangle/index.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Rectangle = require('./Rectangle'); - -Rectangle.Area = require('./Area'); -Rectangle.Ceil = require('./Ceil'); -Rectangle.CeilAll = require('./CeilAll'); -Rectangle.CenterOn = require('./CenterOn'); -Rectangle.Clone = require('./Clone'); -Rectangle.Contains = require('./Contains'); -Rectangle.ContainsPoint = require('./ContainsPoint'); -Rectangle.ContainsRect = require('./ContainsRect'); -Rectangle.CopyFrom = require('./CopyFrom'); -Rectangle.Decompose = require('./Decompose'); -Rectangle.Equals = require('./Equals'); -Rectangle.FitInside = require('./FitInside'); -Rectangle.FitOutside = require('./FitOutside'); -Rectangle.Floor = require('./Floor'); -Rectangle.FloorAll = require('./FloorAll'); -Rectangle.FromPoints = require('./FromPoints'); -Rectangle.GetAspectRatio = require('./GetAspectRatio'); -Rectangle.GetCenter = require('./GetCenter'); -Rectangle.GetPoint = require('./GetPoint'); -Rectangle.GetPoints = require('./GetPoints'); -Rectangle.GetSize = require('./GetSize'); -Rectangle.Inflate = require('./Inflate'); -Rectangle.Intersection = require('./Intersection'); -Rectangle.MarchingAnts = require('./MarchingAnts'); -Rectangle.MergePoints = require('./MergePoints'); -Rectangle.MergeRect = require('./MergeRect'); -Rectangle.MergeXY = require('./MergeXY'); -Rectangle.Offset = require('./Offset'); -Rectangle.OffsetPoint = require('./OffsetPoint'); -Rectangle.Overlaps = require('./Overlaps'); -Rectangle.Perimeter = require('./Perimeter'); -Rectangle.PerimeterPoint = require('./PerimeterPoint'); -Rectangle.Random = require('./Random'); -Rectangle.RandomOutside = require('./RandomOutside'); -Rectangle.SameDimensions = require('./SameDimensions'); -Rectangle.Scale = require('./Scale'); -Rectangle.Union = require('./Union'); - -module.exports = Rectangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Rectangle = require('./Rectangle'); + +Rectangle.Area = require('./Area'); +Rectangle.Ceil = require('./Ceil'); +Rectangle.CeilAll = require('./CeilAll'); +Rectangle.CenterOn = require('./CenterOn'); +Rectangle.Clone = require('./Clone'); +Rectangle.Contains = require('./Contains'); +Rectangle.ContainsPoint = require('./ContainsPoint'); +Rectangle.ContainsRect = require('./ContainsRect'); +Rectangle.CopyFrom = require('./CopyFrom'); +Rectangle.Decompose = require('./Decompose'); +Rectangle.Equals = require('./Equals'); +Rectangle.FitInside = require('./FitInside'); +Rectangle.FitOutside = require('./FitOutside'); +Rectangle.Floor = require('./Floor'); +Rectangle.FloorAll = require('./FloorAll'); +Rectangle.FromPoints = require('./FromPoints'); +Rectangle.GetAspectRatio = require('./GetAspectRatio'); +Rectangle.GetCenter = require('./GetCenter'); +Rectangle.GetPoint = require('./GetPoint'); +Rectangle.GetPoints = require('./GetPoints'); +Rectangle.GetSize = require('./GetSize'); +Rectangle.Inflate = require('./Inflate'); +Rectangle.Intersection = require('./Intersection'); +Rectangle.MarchingAnts = require('./MarchingAnts'); +Rectangle.MergePoints = require('./MergePoints'); +Rectangle.MergeRect = require('./MergeRect'); +Rectangle.MergeXY = require('./MergeXY'); +Rectangle.Offset = require('./Offset'); +Rectangle.OffsetPoint = require('./OffsetPoint'); +Rectangle.Overlaps = require('./Overlaps'); +Rectangle.Perimeter = require('./Perimeter'); +Rectangle.PerimeterPoint = require('./PerimeterPoint'); +Rectangle.Random = require('./Random'); +Rectangle.RandomOutside = require('./RandomOutside'); +Rectangle.SameDimensions = require('./SameDimensions'); +Rectangle.Scale = require('./Scale'); +Rectangle.Union = require('./Union'); + +module.exports = Rectangle; diff --git a/src/geom/triangle/Area.js b/src/geom/triangle/Area.js index bf06dad21..6e72c0b91 100644 --- a/src/geom/triangle/Area.js +++ b/src/geom/triangle/Area.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// The 2D area of a triangle. The area value is always non-negative. - -/** - * Returns the area of a Triangle. - * - * @function Phaser.Geom.Triangle.Area - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to use. - * - * @return {number} The area of the Triangle, always non-negative. - */ -var Area = function (triangle) -{ - var x1 = triangle.x1; - var y1 = triangle.y1; - - var x2 = triangle.x2; - var y2 = triangle.y2; - - var x3 = triangle.x3; - var y3 = triangle.y3; - - return Math.abs(((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1)) / 2); -}; - -module.exports = Area; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// The 2D area of a triangle. The area value is always non-negative. + +/** + * Returns the area of a Triangle. + * + * @function Phaser.Geom.Triangle.Area + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to use. + * + * @return {number} The area of the Triangle, always non-negative. + */ +var Area = function (triangle) +{ + var x1 = triangle.x1; + var y1 = triangle.y1; + + var x2 = triangle.x2; + var y2 = triangle.y2; + + var x3 = triangle.x3; + var y3 = triangle.y3; + + return Math.abs(((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1)) / 2); +}; + +module.exports = Area; diff --git a/src/geom/triangle/BuildEquilateral.js b/src/geom/triangle/BuildEquilateral.js index 1e8563052..92f8344f7 100644 --- a/src/geom/triangle/BuildEquilateral.js +++ b/src/geom/triangle/BuildEquilateral.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Triangle = require('./Triangle'); - -/** - * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). - * The x/y specifies the top-middle of the triangle (x1/y1) and length is the length of each side. - * - * @function Phaser.Geom.Triangle.BuildEquilateral - * @since 3.0.0 - * - * @param {number} x - x coordinate of the top point of the triangle. - * @param {number} y - y coordinate of the top point of the triangle. - * @param {number} length - Length of each side of the triangle. - * - * @return {Phaser.Geom.Triangle} The Triangle object of the given size. - */ -var BuildEquilateral = function (x, y, length) -{ - var height = length * (Math.sqrt(3) / 2); - - var x1 = x; - var y1 = y; - - var x2 = x + (length / 2); - var y2 = y + height; - - var x3 = x - (length / 2); - var y3 = y + height; - - return new Triangle(x1, y1, x2, y2, x3, y3); -}; - -module.exports = BuildEquilateral; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = require('./Triangle'); + +/** + * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). + * The x/y specifies the top-middle of the triangle (x1/y1) and length is the length of each side. + * + * @function Phaser.Geom.Triangle.BuildEquilateral + * @since 3.0.0 + * + * @param {number} x - x coordinate of the top point of the triangle. + * @param {number} y - y coordinate of the top point of the triangle. + * @param {number} length - Length of each side of the triangle. + * + * @return {Phaser.Geom.Triangle} The Triangle object of the given size. + */ +var BuildEquilateral = function (x, y, length) +{ + var height = length * (Math.sqrt(3) / 2); + + var x1 = x; + var y1 = y; + + var x2 = x + (length / 2); + var y2 = y + height; + + var x3 = x - (length / 2); + var y3 = y + height; + + return new Triangle(x1, y1, x2, y2, x3, y3); +}; + +module.exports = BuildEquilateral; diff --git a/src/geom/triangle/BuildFromPolygon.js b/src/geom/triangle/BuildFromPolygon.js index f8a1096fc..5e6acf368 100644 --- a/src/geom/triangle/BuildFromPolygon.js +++ b/src/geom/triangle/BuildFromPolygon.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var EarCut = require('../polygon/Earcut'); -var Triangle = require('./Triangle'); - -/** - * 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. - */ -var BuildFromPolygon = function (data, holes, scaleX, scaleY, out) -{ - if (holes === undefined) { holes = null; } - if (scaleX === undefined) { scaleX = 1; } - if (scaleY === undefined) { scaleY = 1; } - if (out === undefined) { out = []; } - - var tris = EarCut(data, holes); - - var a; - var b; - var c; - - var x1; - var y1; - - var x2; - var y2; - - var x3; - var y3; - - for (var i = 0; i < tris.length; i += 3) - { - a = tris[i]; - b = tris[i + 1]; - c = tris[i + 2]; - - x1 = data[a * 2] * scaleX; - y1 = data[(a * 2) + 1] * scaleY; - - x2 = data[b * 2] * scaleX; - y2 = data[(b * 2) + 1] * scaleY; - - x3 = data[c * 2] * scaleX; - y3 = data[(c * 2) + 1] * scaleY; - - out.push(new Triangle(x1, y1, x2, y2, x3, y3)); - } - - return out; -}; - -module.exports = BuildFromPolygon; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var EarCut = require('../polygon/Earcut'); +var Triangle = require('./Triangle'); + +/** + * 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. + */ +var BuildFromPolygon = function (data, holes, scaleX, scaleY, out) +{ + if (holes === undefined) { holes = null; } + if (scaleX === undefined) { scaleX = 1; } + if (scaleY === undefined) { scaleY = 1; } + if (out === undefined) { out = []; } + + var tris = EarCut(data, holes); + + var a; + var b; + var c; + + var x1; + var y1; + + var x2; + var y2; + + var x3; + var y3; + + for (var i = 0; i < tris.length; i += 3) + { + a = tris[i]; + b = tris[i + 1]; + c = tris[i + 2]; + + x1 = data[a * 2] * scaleX; + y1 = data[(a * 2) + 1] * scaleY; + + x2 = data[b * 2] * scaleX; + y2 = data[(b * 2) + 1] * scaleY; + + x3 = data[c * 2] * scaleX; + y3 = data[(c * 2) + 1] * scaleY; + + out.push(new Triangle(x1, y1, x2, y2, x3, y3)); + } + + return out; +}; + +module.exports = BuildFromPolygon; diff --git a/src/geom/triangle/BuildRight.js b/src/geom/triangle/BuildRight.js index 5d7578fb9..de29cee2a 100644 --- a/src/geom/triangle/BuildRight.js +++ b/src/geom/triangle/BuildRight.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Triangle = require('./Triangle'); - -// 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 - -/** - * Builds a right triangle, i.e. one which has a 90-degree angle and two acute angles. - * - * @function Phaser.Geom.Triangle.BuildRight - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the right angle, which will also be the first X coordinate of the constructed Triangle. - * @param {number} y - The Y coordinate of the right angle, which will also be the first Y coordinate of the constructed Triangle. - * @param {number} width - The length of the side which is to the left or to the right of the right angle. - * @param {number} height - The length of the side which is above or below the right angle. - * - * @return {Phaser.Geom.Triangle} The constructed right Triangle. - */ -var BuildRight = function (x, y, width, height) -{ - if (height === undefined) { height = width; } - - // 90 degree angle - var x1 = x; - var y1 = y; - - var x2 = x; - var y2 = y - height; - - var x3 = x + width; - var y3 = y; - - return new Triangle(x1, y1, x2, y2, x3, y3); -}; - -module.exports = BuildRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = require('./Triangle'); + +// 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 + +/** + * Builds a right triangle, i.e. one which has a 90-degree angle and two acute angles. + * + * @function Phaser.Geom.Triangle.BuildRight + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the right angle, which will also be the first X coordinate of the constructed Triangle. + * @param {number} y - The Y coordinate of the right angle, which will also be the first Y coordinate of the constructed Triangle. + * @param {number} width - The length of the side which is to the left or to the right of the right angle. + * @param {number} height - The length of the side which is above or below the right angle. + * + * @return {Phaser.Geom.Triangle} The constructed right Triangle. + */ +var BuildRight = function (x, y, width, height) +{ + if (height === undefined) { height = width; } + + // 90 degree angle + var x1 = x; + var y1 = y; + + var x2 = x; + var y2 = y - height; + + var x3 = x + width; + var y3 = y; + + return new Triangle(x1, y1, x2, y2, x3, y3); +}; + +module.exports = BuildRight; diff --git a/src/geom/triangle/CenterOn.js b/src/geom/triangle/CenterOn.js index 53b6d7a97..6984f6130 100644 --- a/src/geom/triangle/CenterOn.js +++ b/src/geom/triangle/CenterOn.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Centroid = require('./Centroid'); -var Offset = require('./Offset'); - -/** - * @callback CenterFunction - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to return the center coordinates of. - * - * @return {Phaser.Math.Vector2} The center point of the Triangle according to the function. - */ - -/** - * Positions the Triangle so that it is centered on the given coordinates. - * - * @function Phaser.Geom.Triangle.CenterOn - * @since 3.0.0 - * - * @generic {Phaser.Geom.Triangle} O - [triangle,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The triangle to be positioned. - * @param {number} x - The horizontal coordinate to center on. - * @param {number} y - The vertical coordinate to center on. - * @param {CenterFunction} [centerFunc] - The function used to center the triangle. Defaults to Centroid centering. - * - * @return {Phaser.Geom.Triangle} The Triangle that was centered. - */ -var CenterOn = function (triangle, x, y, centerFunc) -{ - if (centerFunc === undefined) { centerFunc = Centroid; } - - // Get the center of the triangle - var center = centerFunc(triangle); - - // Difference - var diffX = x - center.x; - var diffY = y - center.y; - - return Offset(triangle, diffX, diffY); -}; - -module.exports = CenterOn; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Centroid = require('./Centroid'); +var Offset = require('./Offset'); + +/** + * @callback CenterFunction + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to return the center coordinates of. + * + * @return {Phaser.Math.Vector2} The center point of the Triangle according to the function. + */ + +/** + * Positions the Triangle so that it is centered on the given coordinates. + * + * @function Phaser.Geom.Triangle.CenterOn + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The triangle to be positioned. + * @param {number} x - The horizontal coordinate to center on. + * @param {number} y - The vertical coordinate to center on. + * @param {CenterFunction} [centerFunc] - The function used to center the triangle. Defaults to Centroid centering. + * + * @return {Phaser.Geom.Triangle} The Triangle that was centered. + */ +var CenterOn = function (triangle, x, y, centerFunc) +{ + if (centerFunc === undefined) { centerFunc = Centroid; } + + // Get the center of the triangle + var center = centerFunc(triangle); + + // Difference + var diffX = x - center.x; + var diffY = y - center.y; + + return Offset(triangle, diffX, diffY); +}; + +module.exports = CenterOn; diff --git a/src/geom/triangle/Centroid.js b/src/geom/triangle/Centroid.js index 3cec6d16c..1e269e165 100644 --- a/src/geom/triangle/Centroid.js +++ b/src/geom/triangle/Centroid.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -// The three medians (the lines drawn from the vertices to the bisectors of the opposite sides) -// meet in the centroid or center of mass (center of gravity). -// The centroid divides each median in a ratio of 2:1 - -/** - * Calculates the position of a Triangle's centroid, which is also its center of mass (center of gravity). - * - * The centroid is the point in a Triangle at which its three medians (the lines drawn from the vertices to the bisectors of the opposite sides) meet. It divides each one in a 2:1 ratio. - * - * @function Phaser.Geom.Triangle.Centroid - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to use. - * @param {(Phaser.Geom.Point|object)} [out] - An object to store the coordinates in. - * - * @return {(Phaser.Geom.Point|object)} The `out` object with modified `x` and `y` properties, or a new Point if none was provided. - */ -var Centroid = function (triangle, out) -{ - if (out === undefined) { out = new Point(); } - - out.x = (triangle.x1 + triangle.x2 + triangle.x3) / 3; - out.y = (triangle.y1 + triangle.y2 + triangle.y3) / 3; - - return out; -}; - -module.exports = Centroid; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +// The three medians (the lines drawn from the vertices to the bisectors of the opposite sides) +// meet in the centroid or center of mass (center of gravity). +// The centroid divides each median in a ratio of 2:1 + +/** + * Calculates the position of a Triangle's centroid, which is also its center of mass (center of gravity). + * + * The centroid is the point in a Triangle at which its three medians (the lines drawn from the vertices to the bisectors of the opposite sides) meet. It divides each one in a 2:1 ratio. + * + * @function Phaser.Geom.Triangle.Centroid + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to use. + * @param {(Phaser.Geom.Point|object)} [out] - An object to store the coordinates in. + * + * @return {(Phaser.Geom.Point|object)} The `out` object with modified `x` and `y` properties, or a new Point if none was provided. + */ +var Centroid = function (triangle, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = (triangle.x1 + triangle.x2 + triangle.x3) / 3; + out.y = (triangle.y1 + triangle.y2 + triangle.y3) / 3; + + return out; +}; + +module.exports = Centroid; diff --git a/src/geom/triangle/CircumCenter.js b/src/geom/triangle/CircumCenter.js index a8bae4ffa..0ce77e852 100644 --- a/src/geom/triangle/CircumCenter.js +++ b/src/geom/triangle/CircumCenter.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Vector2 = require('../../math/Vector2'); - -// Adapted from http://bjornharrtell.github.io/jsts/doc/api/jsts_geom_Triangle.js.html - -/** - * Computes the determinant of a 2x2 matrix. Uses standard double-precision arithmetic, so is susceptible to round-off error. - * - * @function det - * @private - * @since 3.0.0 - * - * @param {number} m00 - The [0,0] entry of the matrix. - * @param {number} m01 - The [0,1] entry of the matrix. - * @param {number} m10 - The [1,0] entry of the matrix. - * @param {number} m11 - The [1,1] entry of the matrix. - * - * @return {number} the determinant. - */ -function det (m00, m01, m10, m11) -{ - return (m00 * m11) - (m01 * m10); -} - -/** - * Computes the circumcentre of a triangle. The circumcentre is the centre of - * the circumcircle, the smallest circle which encloses 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. - * - * @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. - */ -var CircumCenter = function (triangle, out) -{ - if (out === undefined) { out = new Vector2(); } - - var cx = triangle.x3; - var cy = triangle.y3; - - var ax = triangle.x1 - cx; - var ay = triangle.y1 - cy; - - var bx = triangle.x2 - cx; - var by = triangle.y2 - cy; - - var denom = 2 * det(ax, ay, bx, by); - var numx = det(ay, ax * ax + ay * ay, by, bx * bx + by * by); - var numy = det(ax, ax * ax + ay * ay, bx, bx * bx + by * by); - - out.x = cx - numx / denom; - out.y = cy + numy / denom; - - return out; -}; - -module.exports = CircumCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = require('../../math/Vector2'); + +// Adapted from http://bjornharrtell.github.io/jsts/doc/api/jsts_geom_Triangle.js.html + +/** + * Computes the determinant of a 2x2 matrix. Uses standard double-precision arithmetic, so is susceptible to round-off error. + * + * @function det + * @private + * @since 3.0.0 + * + * @param {number} m00 - The [0,0] entry of the matrix. + * @param {number} m01 - The [0,1] entry of the matrix. + * @param {number} m10 - The [1,0] entry of the matrix. + * @param {number} m11 - The [1,1] entry of the matrix. + * + * @return {number} the determinant. + */ +function det (m00, m01, m10, m11) +{ + return (m00 * m11) - (m01 * m10); +} + +/** + * Computes the circumcentre of a triangle. The circumcentre is the centre of + * the circumcircle, the smallest circle which encloses 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. + * + * @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. + */ +var CircumCenter = function (triangle, out) +{ + if (out === undefined) { out = new Vector2(); } + + var cx = triangle.x3; + var cy = triangle.y3; + + var ax = triangle.x1 - cx; + var ay = triangle.y1 - cy; + + var bx = triangle.x2 - cx; + var by = triangle.y2 - cy; + + var denom = 2 * det(ax, ay, bx, by); + var numx = det(ay, ax * ax + ay * ay, by, bx * bx + by * by); + var numy = det(ax, ax * ax + ay * ay, bx, bx * bx + by * by); + + out.x = cx - numx / denom; + out.y = cy + numy / denom; + + return out; +}; + +module.exports = CircumCenter; diff --git a/src/geom/triangle/CircumCircle.js b/src/geom/triangle/CircumCircle.js index b98ca0d15..4b6b2ed2e 100644 --- a/src/geom/triangle/CircumCircle.js +++ b/src/geom/triangle/CircumCircle.js @@ -1,77 +1,77 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Circle = require('../circle/Circle'); - -// Adapted from https://gist.github.com/mutoo/5617691 - -/** - * Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices. - * - * @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. - */ -var CircumCircle = function (triangle, out) -{ - if (out === undefined) { out = new Circle(); } - - // A - var x1 = triangle.x1; - var y1 = triangle.y1; - - // B - var x2 = triangle.x2; - var y2 = triangle.y2; - - // C - var x3 = triangle.x3; - var y3 = triangle.y3; - - var A = x2 - x1; - var B = y2 - y1; - var C = x3 - x1; - var D = y3 - y1; - var E = A * (x1 + x2) + B * (y1 + y2); - var F = C * (x1 + x3) + D * (y1 + y3); - var G = 2 * (A * (y3 - y2) - B * (x3 - x2)); - - var dx; - var dy; - - // If the points of the triangle are collinear, then just find the - // extremes and use the midpoint as the center of the circumcircle. - - if (Math.abs(G) < 0.000001) - { - var minX = Math.min(x1, x2, x3); - var minY = Math.min(y1, y2, y3); - dx = (Math.max(x1, x2, x3) - minX) * 0.5; - dy = (Math.max(y1, y2, y3) - minY) * 0.5; - - out.x = minX + dx; - out.y = minY + dy; - out.radius = Math.sqrt(dx * dx + dy * dy); - } - else - { - out.x = (D * E - B * F) / G; - out.y = (A * F - C * E) / G; - dx = out.x - x1; - dy = out.y - y1; - out.radius = Math.sqrt(dx * dx + dy * dy); - } - - return out; -}; - -module.exports = CircumCircle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = require('../circle/Circle'); + +// Adapted from https://gist.github.com/mutoo/5617691 + +/** + * Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices. + * + * @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. + */ +var CircumCircle = function (triangle, out) +{ + if (out === undefined) { out = new Circle(); } + + // A + var x1 = triangle.x1; + var y1 = triangle.y1; + + // B + var x2 = triangle.x2; + var y2 = triangle.y2; + + // C + var x3 = triangle.x3; + var y3 = triangle.y3; + + var A = x2 - x1; + var B = y2 - y1; + var C = x3 - x1; + var D = y3 - y1; + var E = A * (x1 + x2) + B * (y1 + y2); + var F = C * (x1 + x3) + D * (y1 + y3); + var G = 2 * (A * (y3 - y2) - B * (x3 - x2)); + + var dx; + var dy; + + // If the points of the triangle are collinear, then just find the + // extremes and use the midpoint as the center of the circumcircle. + + if (Math.abs(G) < 0.000001) + { + var minX = Math.min(x1, x2, x3); + var minY = Math.min(y1, y2, y3); + dx = (Math.max(x1, x2, x3) - minX) * 0.5; + dy = (Math.max(y1, y2, y3) - minY) * 0.5; + + out.x = minX + dx; + out.y = minY + dy; + out.radius = Math.sqrt(dx * dx + dy * dy); + } + else + { + out.x = (D * E - B * F) / G; + out.y = (A * F - C * E) / G; + dx = out.x - x1; + dy = out.y - y1; + out.radius = Math.sqrt(dx * dx + dy * dy); + } + + return out; +}; + +module.exports = CircumCircle; diff --git a/src/geom/triangle/Clone.js b/src/geom/triangle/Clone.js index a7e6f553e..6128eb808 100644 --- a/src/geom/triangle/Clone.js +++ b/src/geom/triangle/Clone.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Triangle = require('./Triangle'); - -/** - * Clones a Triangle object. - * - * @function Phaser.Geom.Triangle.Clone - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} source - The Triangle to clone. - * - * @return {Phaser.Geom.Triangle} A new Triangle identical to the given one but separate from it. - */ -var Clone = function (source) -{ - return new Triangle(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3); -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = require('./Triangle'); + +/** + * Clones a Triangle object. + * + * @function Phaser.Geom.Triangle.Clone + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} source - The Triangle to clone. + * + * @return {Phaser.Geom.Triangle} A new Triangle identical to the given one but separate from it. + */ +var Clone = function (source) +{ + return new Triangle(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3); +}; + +module.exports = Clone; diff --git a/src/geom/triangle/Contains.js b/src/geom/triangle/Contains.js index 236795d6f..1ecb3f3b3 100644 --- a/src/geom/triangle/Contains.js +++ b/src/geom/triangle/Contains.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// http://www.blackpawn.com/texts/pointinpoly/ - -/** - * Checks if a point (as a pair of coordinates) is inside a Triangle's bounds. - * - * @function Phaser.Geom.Triangle.Contains - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to check. - * @param {number} x - The X coordinate of the point to check. - * @param {number} y - The Y coordinate of the point to check. - * - * @return {boolean} `true` if the point is inside the Triangle, otherwise `false`. - */ -var Contains = function (triangle, x, y) -{ - var v0x = triangle.x3 - triangle.x1; - var v0y = triangle.y3 - triangle.y1; - - var v1x = triangle.x2 - triangle.x1; - var v1y = triangle.y2 - triangle.y1; - - var v2x = x - triangle.x1; - var v2y = y - triangle.y1; - - var dot00 = (v0x * v0x) + (v0y * v0y); - var dot01 = (v0x * v1x) + (v0y * v1y); - var dot02 = (v0x * v2x) + (v0y * v2y); - var dot11 = (v1x * v1x) + (v1y * v1y); - var dot12 = (v1x * v2x) + (v1y * v2y); - - // Compute barycentric coordinates - var b = ((dot00 * dot11) - (dot01 * dot01)); - var inv = (b === 0) ? 0 : (1 / b); - var u = ((dot11 * dot02) - (dot01 * dot12)) * inv; - var v = ((dot00 * dot12) - (dot01 * dot02)) * inv; - - return (u >= 0 && v >= 0 && (u + v < 1)); -}; - -module.exports = Contains; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// http://www.blackpawn.com/texts/pointinpoly/ + +/** + * Checks if a point (as a pair of coordinates) is inside a Triangle's bounds. + * + * @function Phaser.Geom.Triangle.Contains + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to check. + * @param {number} x - The X coordinate of the point to check. + * @param {number} y - The Y coordinate of the point to check. + * + * @return {boolean} `true` if the point is inside the Triangle, otherwise `false`. + */ +var Contains = function (triangle, x, y) +{ + var v0x = triangle.x3 - triangle.x1; + var v0y = triangle.y3 - triangle.y1; + + var v1x = triangle.x2 - triangle.x1; + var v1y = triangle.y2 - triangle.y1; + + var v2x = x - triangle.x1; + var v2y = y - triangle.y1; + + var dot00 = (v0x * v0x) + (v0y * v0y); + var dot01 = (v0x * v1x) + (v0y * v1y); + var dot02 = (v0x * v2x) + (v0y * v2y); + var dot11 = (v1x * v1x) + (v1y * v1y); + var dot12 = (v1x * v2x) + (v1y * v2y); + + // Compute barycentric coordinates + var b = ((dot00 * dot11) - (dot01 * dot01)); + var inv = (b === 0) ? 0 : (1 / b); + var u = ((dot11 * dot02) - (dot01 * dot12)) * inv; + var v = ((dot00 * dot12) - (dot01 * dot02)) * inv; + + return (u >= 0 && v >= 0 && (u + v < 1)); +}; + +module.exports = Contains; diff --git a/src/geom/triangle/ContainsArray.js b/src/geom/triangle/ContainsArray.js index e8df0fde7..ce7e67a7c 100644 --- a/src/geom/triangle/ContainsArray.js +++ b/src/geom/triangle/ContainsArray.js @@ -1,81 +1,81 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// http://www.blackpawn.com/texts/pointinpoly/ - -// points is an array of Point-like objects with public x/y properties -// returns an array containing all points that are within the triangle, or an empty array if none -// if 'returnFirst' is true it will return after the first point within the triangle is found - -/** - * Filters an array of point-like objects to only those contained within a triangle. - * If `returnFirst` is true, will return an array containing only the first point in the provided array that is within the triangle (or an empty array if there are no such points). - * - * @function Phaser.Geom.Triangle.ContainsArray - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The triangle that the points are being checked in. - * @param {Phaser.Geom.Point[]} points - An array of point-like objects (objects that have an `x` and `y` property) - * @param {boolean} [returnFirst=false] - If `true`, return an array containing only the first point found that is within the triangle. - * @param {array} [out] - If provided, the points that are within the triangle will be appended to this array instead of being added to a new array. If `returnFirst` is true, only the first point found within the triangle will be appended. This array will also be returned by this function. - * - * @return {Phaser.Geom.Point[]} An array containing all the points from `points` that are within the triangle, if an array was provided as `out`, points will be appended to that array and it will also be returned here. - */ -var ContainsArray = function (triangle, points, returnFirst, out) -{ - if (returnFirst === undefined) { returnFirst = false; } - if (out === undefined) { out = []; } - - var v0x = triangle.x3 - triangle.x1; - var v0y = triangle.y3 - triangle.y1; - - var v1x = triangle.x2 - triangle.x1; - var v1y = triangle.y2 - triangle.y1; - - var dot00 = (v0x * v0x) + (v0y * v0y); - var dot01 = (v0x * v1x) + (v0y * v1y); - var dot11 = (v1x * v1x) + (v1y * v1y); - - // Compute barycentric coordinates - var b = ((dot00 * dot11) - (dot01 * dot01)); - var inv = (b === 0) ? 0 : (1 / b); - - var u; - var v; - var v2x; - var v2y; - var dot02; - var dot12; - - var x1 = triangle.x1; - var y1 = triangle.y1; - - for (var i = 0; i < points.length; i++) - { - v2x = points[i].x - x1; - v2y = points[i].y - y1; - - dot02 = (v0x * v2x) + (v0y * v2y); - dot12 = (v1x * v2x) + (v1y * v2y); - - u = ((dot11 * dot02) - (dot01 * dot12)) * inv; - v = ((dot00 * dot12) - (dot01 * dot02)) * inv; - - if (u >= 0 && v >= 0 && (u + v < 1)) - { - out.push({ x: points[i].x, y: points[i].y }); - - if (returnFirst) - { - break; - } - } - } - - return out; -}; - -module.exports = ContainsArray; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// http://www.blackpawn.com/texts/pointinpoly/ + +// points is an array of Point-like objects with public x/y properties +// returns an array containing all points that are within the triangle, or an empty array if none +// if 'returnFirst' is true it will return after the first point within the triangle is found + +/** + * Filters an array of point-like objects to only those contained within a triangle. + * If `returnFirst` is true, will return an array containing only the first point in the provided array that is within the triangle (or an empty array if there are no such points). + * + * @function Phaser.Geom.Triangle.ContainsArray + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle that the points are being checked in. + * @param {Phaser.Geom.Point[]} points - An array of point-like objects (objects that have an `x` and `y` property) + * @param {boolean} [returnFirst=false] - If `true`, return an array containing only the first point found that is within the triangle. + * @param {array} [out] - If provided, the points that are within the triangle will be appended to this array instead of being added to a new array. If `returnFirst` is true, only the first point found within the triangle will be appended. This array will also be returned by this function. + * + * @return {Phaser.Geom.Point[]} An array containing all the points from `points` that are within the triangle, if an array was provided as `out`, points will be appended to that array and it will also be returned here. + */ +var ContainsArray = function (triangle, points, returnFirst, out) +{ + if (returnFirst === undefined) { returnFirst = false; } + if (out === undefined) { out = []; } + + var v0x = triangle.x3 - triangle.x1; + var v0y = triangle.y3 - triangle.y1; + + var v1x = triangle.x2 - triangle.x1; + var v1y = triangle.y2 - triangle.y1; + + var dot00 = (v0x * v0x) + (v0y * v0y); + var dot01 = (v0x * v1x) + (v0y * v1y); + var dot11 = (v1x * v1x) + (v1y * v1y); + + // Compute barycentric coordinates + var b = ((dot00 * dot11) - (dot01 * dot01)); + var inv = (b === 0) ? 0 : (1 / b); + + var u; + var v; + var v2x; + var v2y; + var dot02; + var dot12; + + var x1 = triangle.x1; + var y1 = triangle.y1; + + for (var i = 0; i < points.length; i++) + { + v2x = points[i].x - x1; + v2y = points[i].y - y1; + + dot02 = (v0x * v2x) + (v0y * v2y); + dot12 = (v1x * v2x) + (v1y * v2y); + + u = ((dot11 * dot02) - (dot01 * dot12)) * inv; + v = ((dot00 * dot12) - (dot01 * dot02)) * inv; + + if (u >= 0 && v >= 0 && (u + v < 1)) + { + out.push({ x: points[i].x, y: points[i].y }); + + if (returnFirst) + { + break; + } + } + } + + return out; +}; + +module.exports = ContainsArray; diff --git a/src/geom/triangle/ContainsPoint.js b/src/geom/triangle/ContainsPoint.js index d641ac4f6..0b8cf491f 100644 --- a/src/geom/triangle/ContainsPoint.js +++ b/src/geom/triangle/ContainsPoint.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Contains = require('./Contains'); - -/** - * Tests if a triangle contains a point. - * - * @function Phaser.Geom.Triangle.ContainsPoint - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The triangle. - * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|any)} point - The point to test, or any point-like object with public `x` and `y` properties. - * - * @return {boolean} `true` if the point is within the triangle, otherwise `false`. - */ -var ContainsPoint = function (triangle, point) -{ - return Contains(triangle, point.x, point.y); -}; - -module.exports = ContainsPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Contains = require('./Contains'); + +/** + * Tests if a triangle contains a point. + * + * @function Phaser.Geom.Triangle.ContainsPoint + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The triangle. + * @param {(Phaser.Geom.Point|Phaser.Math.Vector2|any)} point - The point to test, or any point-like object with public `x` and `y` properties. + * + * @return {boolean} `true` if the point is within the triangle, otherwise `false`. + */ +var ContainsPoint = function (triangle, point) +{ + return Contains(triangle, point.x, point.y); +}; + +module.exports = ContainsPoint; diff --git a/src/geom/triangle/CopyFrom.js b/src/geom/triangle/CopyFrom.js index a42a24432..e62debbc9 100644 --- a/src/geom/triangle/CopyFrom.js +++ b/src/geom/triangle/CopyFrom.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Copy the values of one Triangle to a destination Triangle. - * - * @function Phaser.Geom.Triangle.CopyFrom - * @since 3.0.0 - * - * @generic {Phaser.Geom.Triangle} O - [dest,$return] - * - * @param {Phaser.Geom.Triangle} source - The source Triangle to copy the values from. - * @param {Phaser.Geom.Triangle} dest - The destination Triangle to copy the values to. - * - * @return {Phaser.Geom.Triangle} The destination Triangle. - */ -var CopyFrom = function (source, dest) -{ - return dest.setTo(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3); -}; - -module.exports = CopyFrom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Copy the values of one Triangle to a destination Triangle. + * + * @function Phaser.Geom.Triangle.CopyFrom + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [dest,$return] + * + * @param {Phaser.Geom.Triangle} source - The source Triangle to copy the values from. + * @param {Phaser.Geom.Triangle} dest - The destination Triangle to copy the values to. + * + * @return {Phaser.Geom.Triangle} The destination Triangle. + */ +var CopyFrom = function (source, dest) +{ + return dest.setTo(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3); +}; + +module.exports = CopyFrom; diff --git a/src/geom/triangle/Decompose.js b/src/geom/triangle/Decompose.js index 5114cbe50..ae909c0d0 100644 --- a/src/geom/triangle/Decompose.js +++ b/src/geom/triangle/Decompose.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Decomposes a Triangle into an array of its points. - * - * @function Phaser.Geom.Triangle.Decompose - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to decompose. - * @param {array} [out] - An array to store the points into. - * - * @return {array} The provided `out` array, or a new array if none was provided, with three objects with `x` and `y` properties representing each point of the Triangle appended to it. - */ -var Decompose = function (triangle, out) -{ - if (out === undefined) { out = []; } - - out.push({ x: triangle.x1, y: triangle.y1 }); - out.push({ x: triangle.x2, y: triangle.y2 }); - out.push({ x: triangle.x3, y: triangle.y3 }); - - return out; -}; - -module.exports = Decompose; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Decomposes a Triangle into an array of its points. + * + * @function Phaser.Geom.Triangle.Decompose + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to decompose. + * @param {array} [out] - An array to store the points into. + * + * @return {array} The provided `out` array, or a new array if none was provided, with three objects with `x` and `y` properties representing each point of the Triangle appended to it. + */ +var Decompose = function (triangle, out) +{ + if (out === undefined) { out = []; } + + out.push({ x: triangle.x1, y: triangle.y1 }); + out.push({ x: triangle.x2, y: triangle.y2 }); + out.push({ x: triangle.x3, y: triangle.y3 }); + + return out; +}; + +module.exports = Decompose; diff --git a/src/geom/triangle/Equals.js b/src/geom/triangle/Equals.js index 98a6ef408..b79ccf8f3 100644 --- a/src/geom/triangle/Equals.js +++ b/src/geom/triangle/Equals.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns true if two triangles have the same coordinates. - * - * @function Phaser.Geom.Triangle.Equals - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The first triangle to check. - * @param {Phaser.Geom.Triangle} toCompare - The second triangle to check. - * - * @return {boolean} `true` if the two given triangles have the exact same coordinates, otherwise `false`. - */ -var Equals = function (triangle, toCompare) -{ - return ( - triangle.x1 === toCompare.x1 && - triangle.y1 === toCompare.y1 && - triangle.x2 === toCompare.x2 && - triangle.y2 === toCompare.y2 && - triangle.x3 === toCompare.x3 && - triangle.y3 === toCompare.y3 - ); -}; - -module.exports = Equals; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns true if two triangles have the same coordinates. + * + * @function Phaser.Geom.Triangle.Equals + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The first triangle to check. + * @param {Phaser.Geom.Triangle} toCompare - The second triangle to check. + * + * @return {boolean} `true` if the two given triangles have the exact same coordinates, otherwise `false`. + */ +var Equals = function (triangle, toCompare) +{ + return ( + triangle.x1 === toCompare.x1 && + triangle.y1 === toCompare.y1 && + triangle.x2 === toCompare.x2 && + triangle.y2 === toCompare.y2 && + triangle.x3 === toCompare.x3 && + triangle.y3 === toCompare.y3 + ); +}; + +module.exports = Equals; diff --git a/src/geom/triangle/GetPoint.js b/src/geom/triangle/GetPoint.js index 546ea200a..f0e3be069 100644 --- a/src/geom/triangle/GetPoint.js +++ b/src/geom/triangle/GetPoint.js @@ -1,81 +1,81 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); -var Length = require('../line/Length'); - -/** - * Returns a Point from around the perimeter of a Triangle. - * - * @function Phaser.Geom.Triangle.GetPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the point on its perimeter from. - * @param {number} position - The position along the perimeter of the triangle. A value between 0 and 1. - * @param {(Phaser.Geom.Point|object)} [out] - An option Point, or Point-like object to store the value in. If not given a new Point will be created. - * - * @return {(Phaser.Geom.Point|object)} A Point object containing the given position from the perimeter of the triangle. - */ -var GetPoint = function (triangle, position, out) -{ - if (out === undefined) { out = new Point(); } - - var line1 = triangle.getLineA(); - var line2 = triangle.getLineB(); - var line3 = triangle.getLineC(); - - if (position <= 0 || position >= 1) - { - out.x = line1.x1; - out.y = line1.y1; - - return out; - } - - var length1 = Length(line1); - var length2 = Length(line2); - var length3 = Length(line3); - - var perimeter = length1 + length2 + length3; - - var p = perimeter * position; - var localPosition = 0; - - // Which line is it on? - - if (p < length1) - { - // Line 1 - localPosition = p / length1; - - out.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; - out.y = line1.y1 + (line1.y2 - line1.y1) * localPosition; - } - else if (p > length1 + length2) - { - // Line 3 - p -= length1 + length2; - localPosition = p / length3; - - out.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; - out.y = line3.y1 + (line3.y2 - line3.y1) * localPosition; - } - else - { - // Line 2 - p -= length1; - localPosition = p / length2; - - out.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; - out.y = line2.y1 + (line2.y2 - line2.y1) * localPosition; - } - - return out; -}; - -module.exports = GetPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); +var Length = require('../line/Length'); + +/** + * Returns a Point from around the perimeter of a Triangle. + * + * @function Phaser.Geom.Triangle.GetPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the point on its perimeter from. + * @param {number} position - The position along the perimeter of the triangle. A value between 0 and 1. + * @param {(Phaser.Geom.Point|object)} [out] - An option Point, or Point-like object to store the value in. If not given a new Point will be created. + * + * @return {(Phaser.Geom.Point|object)} A Point object containing the given position from the perimeter of the triangle. + */ +var GetPoint = function (triangle, position, out) +{ + if (out === undefined) { out = new Point(); } + + var line1 = triangle.getLineA(); + var line2 = triangle.getLineB(); + var line3 = triangle.getLineC(); + + if (position <= 0 || position >= 1) + { + out.x = line1.x1; + out.y = line1.y1; + + return out; + } + + var length1 = Length(line1); + var length2 = Length(line2); + var length3 = Length(line3); + + var perimeter = length1 + length2 + length3; + + var p = perimeter * position; + var localPosition = 0; + + // Which line is it on? + + if (p < length1) + { + // Line 1 + localPosition = p / length1; + + out.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; + out.y = line1.y1 + (line1.y2 - line1.y1) * localPosition; + } + else if (p > length1 + length2) + { + // Line 3 + p -= length1 + length2; + localPosition = p / length3; + + out.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; + out.y = line3.y1 + (line3.y2 - line3.y1) * localPosition; + } + else + { + // Line 2 + p -= length1; + localPosition = p / length2; + + out.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; + out.y = line2.y1 + (line2.y2 - line2.y1) * localPosition; + } + + return out; +}; + +module.exports = GetPoint; diff --git a/src/geom/triangle/GetPoints.js b/src/geom/triangle/GetPoints.js index 373b1234b..fb0b58fce 100644 --- a/src/geom/triangle/GetPoints.js +++ b/src/geom/triangle/GetPoints.js @@ -1,87 +1,87 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Length = require('../line/Length'); -var Point = require('../point/Point'); - -/** - * Returns an array of evenly spaced points on the perimeter of a Triangle. - * - * @function Phaser.Geom.Triangle.GetPoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the points from. - * @param {integer} 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 between each returned point. - * @param {(array|Phaser.Geom.Point[])} [out] - An array to which the points should be appended. - * - * @return {(array|Phaser.Geom.Point[])} The modified `out` array, or a new array if none was provided. - */ -var GetPoints = function (triangle, quantity, stepRate, out) -{ - if (out === undefined) { out = []; } - - var line1 = triangle.getLineA(); - var line2 = triangle.getLineB(); - var line3 = triangle.getLineC(); - - var length1 = Length(line1); - var length2 = Length(line2); - var length3 = Length(line3); - - var perimeter = length1 + length2 + length3; - - // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. - if (!quantity) - { - quantity = perimeter / stepRate; - } - - for (var i = 0; i < quantity; i++) - { - var p = perimeter * (i / quantity); - var localPosition = 0; - - var point = new Point(); - - // Which line is it on? - - if (p < length1) - { - // Line 1 - localPosition = p / length1; - - point.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; - point.y = line1.y1 + (line1.y2 - line1.y1) * localPosition; - } - else if (p > length1 + length2) - { - // Line 3 - p -= length1 + length2; - localPosition = p / length3; - - point.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; - point.y = line3.y1 + (line3.y2 - line3.y1) * localPosition; - } - else - { - // Line 2 - p -= length1; - localPosition = p / length2; - - point.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; - point.y = line2.y1 + (line2.y2 - line2.y1) * localPosition; - } - - out.push(point); - } - - return out; -}; - -module.exports = GetPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = require('../line/Length'); +var Point = require('../point/Point'); + +/** + * Returns an array of evenly spaced points on the perimeter of a Triangle. + * + * @function Phaser.Geom.Triangle.GetPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the points from. + * @param {integer} 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 between each returned point. + * @param {(array|Phaser.Geom.Point[])} [out] - An array to which the points should be appended. + * + * @return {(array|Phaser.Geom.Point[])} The modified `out` array, or a new array if none was provided. + */ +var GetPoints = function (triangle, quantity, stepRate, out) +{ + if (out === undefined) { out = []; } + + var line1 = triangle.getLineA(); + var line2 = triangle.getLineB(); + var line3 = triangle.getLineC(); + + var length1 = Length(line1); + var length2 = Length(line2); + var length3 = Length(line3); + + var perimeter = length1 + length2 + length3; + + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. + if (!quantity) + { + quantity = perimeter / stepRate; + } + + for (var i = 0; i < quantity; i++) + { + var p = perimeter * (i / quantity); + var localPosition = 0; + + var point = new Point(); + + // Which line is it on? + + if (p < length1) + { + // Line 1 + localPosition = p / length1; + + point.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; + point.y = line1.y1 + (line1.y2 - line1.y1) * localPosition; + } + else if (p > length1 + length2) + { + // Line 3 + p -= length1 + length2; + localPosition = p / length3; + + point.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; + point.y = line3.y1 + (line3.y2 - line3.y1) * localPosition; + } + else + { + // Line 2 + p -= length1; + localPosition = p / length2; + + point.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; + point.y = line2.y1 + (line2.y2 - line2.y1) * localPosition; + } + + out.push(point); + } + + return out; +}; + +module.exports = GetPoints; diff --git a/src/geom/triangle/InCenter.js b/src/geom/triangle/InCenter.js index 154cc80c1..561e8fd2d 100644 --- a/src/geom/triangle/InCenter.js +++ b/src/geom/triangle/InCenter.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -// 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. - -function getLength (x1, y1, x2, y2) -{ - var x = x1 - x2; - var y = y1 - y2; - var magnitude = (x * x) + (y * y); - - return Math.sqrt(magnitude); -} - -/** - * Calculates the position of the incenter of a Triangle object. This is the point where its three angle bisectors meet and it's also the center of the incircle, which is the circle inscribed in the triangle. - * - * @function Phaser.Geom.Triangle.InCenter - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to find the incenter of. - * @param {Phaser.Geom.Point} [out] - An optional Point in which to store the coordinates. - * - * @return {Phaser.Geom.Point} Point (x, y) of the center pixel of the triangle. - */ -var InCenter = function (triangle, out) -{ - if (out === undefined) { out = new Point(); } - - var x1 = triangle.x1; - var y1 = triangle.y1; - - var x2 = triangle.x2; - var y2 = triangle.y2; - - var x3 = triangle.x3; - var y3 = triangle.y3; - - var d1 = getLength(x3, y3, x2, y2); - var d2 = getLength(x1, y1, x3, y3); - var d3 = getLength(x2, y2, x1, y1); - - var p = d1 + d2 + d3; - - out.x = (x1 * d1 + x2 * d2 + x3 * d3) / p; - out.y = (y1 * d1 + y2 * d2 + y3 * d3) / p; - - return out; -}; - -module.exports = InCenter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +// 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. + +function getLength (x1, y1, x2, y2) +{ + var x = x1 - x2; + var y = y1 - y2; + var magnitude = (x * x) + (y * y); + + return Math.sqrt(magnitude); +} + +/** + * Calculates the position of the incenter of a Triangle object. This is the point where its three angle bisectors meet and it's also the center of the incircle, which is the circle inscribed in the triangle. + * + * @function Phaser.Geom.Triangle.InCenter + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to find the incenter of. + * @param {Phaser.Geom.Point} [out] - An optional Point in which to store the coordinates. + * + * @return {Phaser.Geom.Point} Point (x, y) of the center pixel of the triangle. + */ +var InCenter = function (triangle, out) +{ + if (out === undefined) { out = new Point(); } + + var x1 = triangle.x1; + var y1 = triangle.y1; + + var x2 = triangle.x2; + var y2 = triangle.y2; + + var x3 = triangle.x3; + var y3 = triangle.y3; + + var d1 = getLength(x3, y3, x2, y2); + var d2 = getLength(x1, y1, x3, y3); + var d3 = getLength(x2, y2, x1, y1); + + var p = d1 + d2 + d3; + + out.x = (x1 * d1 + x2 * d2 + x3 * d3) / p; + out.y = (y1 * d1 + y2 * d2 + y3 * d3) / p; + + return out; +}; + +module.exports = InCenter; diff --git a/src/geom/triangle/Offset.js b/src/geom/triangle/Offset.js index b774a255d..8f42b3f81 100644 --- a/src/geom/triangle/Offset.js +++ b/src/geom/triangle/Offset.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves each point (vertex) of a Triangle by a given offset, thus moving the entire Triangle by that offset. - * - * @function Phaser.Geom.Triangle.Offset - * @since 3.0.0 - * - * @generic {Phaser.Geom.Triangle} O - [triangle,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to move. - * @param {number} x - The horizontal offset (distance) by which to move each point. Can be positive or negative. - * @param {number} y - The vertical offset (distance) by which to move each point. Can be positive or negative. - * - * @return {Phaser.Geom.Triangle} The modified Triangle. - */ -var Offset = function (triangle, x, y) -{ - triangle.x1 += x; - triangle.y1 += y; - - triangle.x2 += x; - triangle.y2 += y; - - triangle.x3 += x; - triangle.y3 += y; - - return triangle; -}; - -module.exports = Offset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves each point (vertex) of a Triangle by a given offset, thus moving the entire Triangle by that offset. + * + * @function Phaser.Geom.Triangle.Offset + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to move. + * @param {number} x - The horizontal offset (distance) by which to move each point. Can be positive or negative. + * @param {number} y - The vertical offset (distance) by which to move each point. Can be positive or negative. + * + * @return {Phaser.Geom.Triangle} The modified Triangle. + */ +var Offset = function (triangle, x, y) +{ + triangle.x1 += x; + triangle.y1 += y; + + triangle.x2 += x; + triangle.y2 += y; + + triangle.x3 += x; + triangle.y3 += y; + + return triangle; +}; + +module.exports = Offset; diff --git a/src/geom/triangle/Perimeter.js b/src/geom/triangle/Perimeter.js index 65cb3b32e..1c710b7e7 100644 --- a/src/geom/triangle/Perimeter.js +++ b/src/geom/triangle/Perimeter.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Length = require('../line/Length'); - -/** - * Gets the length of the perimeter of the given triangle. - * Calculated by adding together the length of each of the three sides. - * - * @function Phaser.Geom.Triangle.Perimeter - * @since 3.0.0 - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the length from. - * - * @return {number} The length of the Triangle. - */ -var Perimeter = function (triangle) -{ - var line1 = triangle.getLineA(); - var line2 = triangle.getLineB(); - var line3 = triangle.getLineC(); - - return (Length(line1) + Length(line2) + Length(line3)); -}; - -module.exports = Perimeter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Length = require('../line/Length'); + +/** + * Gets the length of the perimeter of the given triangle. + * Calculated by adding together the length of each of the three sides. + * + * @function Phaser.Geom.Triangle.Perimeter + * @since 3.0.0 + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to get the length from. + * + * @return {number} The length of the Triangle. + */ +var Perimeter = function (triangle) +{ + var line1 = triangle.getLineA(); + var line2 = triangle.getLineB(); + var line3 = triangle.getLineC(); + + return (Length(line1) + Length(line2) + Length(line3)); +}; + +module.exports = Perimeter; diff --git a/src/geom/triangle/Random.js b/src/geom/triangle/Random.js index 92687c15c..4c803257b 100644 --- a/src/geom/triangle/Random.js +++ b/src/geom/triangle/Random.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Point = require('../point/Point'); - -/** - * Returns a random Point from within the area of the given Triangle. - * - * @function Phaser.Geom.Triangle.Random - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [out,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to get a random point from. - * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. - * - * @return {Phaser.Geom.Point} A Point object holding the coordinates of a random position within the Triangle. - */ -var Random = function (triangle, out) -{ - if (out === undefined) { out = new Point(); } - - // Basis vectors - var ux = triangle.x2 - triangle.x1; - var uy = triangle.y2 - triangle.y1; - - var vx = triangle.x3 - triangle.x1; - var vy = triangle.y3 - triangle.y1; - - // Random point within the unit square - var r = Math.random(); - var s = Math.random(); - - // Point outside the triangle? Remap it. - if (r + s >= 1) - { - r = 1 - r; - s = 1 - s; - } - - out.x = triangle.x1 + ((ux * r) + (vx * s)); - out.y = triangle.y1 + ((uy * r) + (vy * s)); - - return out; -}; - -module.exports = Random; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a random Point from within the area of the given Triangle. + * + * @function Phaser.Geom.Triangle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to get a random point from. + * @param {Phaser.Geom.Point} [out] - The Point object to store the position in. If not given, a new Point instance is created. + * + * @return {Phaser.Geom.Point} A Point object holding the coordinates of a random position within the Triangle. + */ +var Random = function (triangle, out) +{ + if (out === undefined) { out = new Point(); } + + // Basis vectors + var ux = triangle.x2 - triangle.x1; + var uy = triangle.y2 - triangle.y1; + + var vx = triangle.x3 - triangle.x1; + var vy = triangle.y3 - triangle.y1; + + // Random point within the unit square + var r = Math.random(); + var s = Math.random(); + + // Point outside the triangle? Remap it. + if (r + s >= 1) + { + r = 1 - r; + s = 1 - s; + } + + out.x = triangle.x1 + ((ux * r) + (vx * s)); + out.y = triangle.y1 + ((uy * r) + (vy * s)); + + return out; +}; + +module.exports = Random; diff --git a/src/geom/triangle/Rotate.js b/src/geom/triangle/Rotate.js index 820c4afd2..9b5cee05a 100644 --- a/src/geom/triangle/Rotate.js +++ b/src/geom/triangle/Rotate.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateAroundXY = require('./RotateAroundXY'); -var InCenter = require('./InCenter'); - -/** - * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. - * - * @function Phaser.Geom.Triangle.Rotate - * @since 3.0.0 - * - * @generic {Phaser.Geom.Triangle} O - [triangle,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. - * @param {number} angle - The angle by which to rotate the Triangle, in radians. - * - * @return {Phaser.Geom.Triangle} The rotated Triangle. - */ -var Rotate = function (triangle, angle) -{ - var point = InCenter(triangle); - - return RotateAroundXY(triangle, point.x, point.y, angle); -}; - -module.exports = Rotate; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = require('./RotateAroundXY'); +var InCenter = require('./InCenter'); + +/** + * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. + * + * @function Phaser.Geom.Triangle.Rotate + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. + * @param {number} angle - The angle by which to rotate the Triangle, in radians. + * + * @return {Phaser.Geom.Triangle} The rotated Triangle. + */ +var Rotate = function (triangle, angle) +{ + var point = InCenter(triangle); + + return RotateAroundXY(triangle, point.x, point.y, angle); +}; + +module.exports = Rotate; diff --git a/src/geom/triangle/RotateAroundPoint.js b/src/geom/triangle/RotateAroundPoint.js index c440469c8..8e41a5311 100644 --- a/src/geom/triangle/RotateAroundPoint.js +++ b/src/geom/triangle/RotateAroundPoint.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateAroundXY = require('./RotateAroundXY'); - -/** - * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. - * - * @function Phaser.Geom.Triangle.RotateAroundPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Triangle} O - [triangle,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. - * @param {Phaser.Geom.Point} point - The Point to rotate the Triangle about. - * @param {number} angle - The angle by which to rotate the Triangle, in radians. - * - * @return {Phaser.Geom.Triangle} The rotated Triangle. - */ -var RotateAroundPoint = function (triangle, point, angle) -{ - return RotateAroundXY(triangle, point.x, point.y, angle); -}; - -module.exports = RotateAroundPoint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateAroundXY = require('./RotateAroundXY'); + +/** + * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. + * + * @function Phaser.Geom.Triangle.RotateAroundPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. + * @param {Phaser.Geom.Point} point - The Point to rotate the Triangle about. + * @param {number} angle - The angle by which to rotate the Triangle, in radians. + * + * @return {Phaser.Geom.Triangle} The rotated Triangle. + */ +var RotateAroundPoint = function (triangle, point, angle) +{ + return RotateAroundXY(triangle, point.x, point.y, angle); +}; + +module.exports = RotateAroundPoint; diff --git a/src/geom/triangle/RotateAroundXY.js b/src/geom/triangle/RotateAroundXY.js index 515a7e5a9..05fb87ae7 100644 --- a/src/geom/triangle/RotateAroundXY.js +++ b/src/geom/triangle/RotateAroundXY.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rotates an entire Triangle at a given angle about a specific point. - * - * @function Phaser.Geom.Triangle.RotateAroundXY - * @since 3.0.0 - * - * @generic {Phaser.Geom.Triangle} O - [triangle,$return] - * - * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. - * @param {number} x - The X coordinate of the point to rotate the Triangle about. - * @param {number} y - The Y coordinate of the point to rotate the Triangle about. - * @param {number} angle - The angle by which to rotate the Triangle, in radians. - * - * @return {Phaser.Geom.Triangle} The rotated Triangle. - */ -var RotateAroundXY = function (triangle, x, y, angle) -{ - var c = Math.cos(angle); - var s = Math.sin(angle); - - var tx = triangle.x1 - x; - var ty = triangle.y1 - y; - - triangle.x1 = tx * c - ty * s + x; - triangle.y1 = tx * s + ty * c + y; - - tx = triangle.x2 - x; - ty = triangle.y2 - y; - - triangle.x2 = tx * c - ty * s + x; - triangle.y2 = tx * s + ty * c + y; - - tx = triangle.x3 - x; - ty = triangle.y3 - y; - - triangle.x3 = tx * c - ty * s + x; - triangle.y3 = tx * s + ty * c + y; - - return triangle; -}; - -module.exports = RotateAroundXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotates an entire Triangle at a given angle about a specific point. + * + * @function Phaser.Geom.Triangle.RotateAroundXY + * @since 3.0.0 + * + * @generic {Phaser.Geom.Triangle} O - [triangle,$return] + * + * @param {Phaser.Geom.Triangle} triangle - The Triangle to rotate. + * @param {number} x - The X coordinate of the point to rotate the Triangle about. + * @param {number} y - The Y coordinate of the point to rotate the Triangle about. + * @param {number} angle - The angle by which to rotate the Triangle, in radians. + * + * @return {Phaser.Geom.Triangle} The rotated Triangle. + */ +var RotateAroundXY = function (triangle, x, y, angle) +{ + var c = Math.cos(angle); + var s = Math.sin(angle); + + var tx = triangle.x1 - x; + var ty = triangle.y1 - y; + + triangle.x1 = tx * c - ty * s + x; + triangle.y1 = tx * s + ty * c + y; + + tx = triangle.x2 - x; + ty = triangle.y2 - y; + + triangle.x2 = tx * c - ty * s + x; + triangle.y2 = tx * s + ty * c + y; + + tx = triangle.x3 - x; + ty = triangle.y3 - y; + + triangle.x3 = tx * c - ty * s + x; + triangle.y3 = tx * s + ty * c + y; + + return triangle; +}; + +module.exports = RotateAroundXY; diff --git a/src/geom/triangle/Triangle.js b/src/geom/triangle/Triangle.js index 769663820..c42144084 100644 --- a/src/geom/triangle/Triangle.js +++ b/src/geom/triangle/Triangle.js @@ -1,441 +1,441 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Contains = require('./Contains'); -var GetPoint = require('./GetPoint'); -var GetPoints = require('./GetPoints'); -var GEOM_CONST = require('../const'); -var Line = require('../line/Line'); -var Random = require('./Random'); - -/** - * @classdesc - * A triangle is a plane created by connecting three points. - * The first two arguments specify the first point, the middle two arguments - * specify the second point, and the last two arguments specify the third point. - * - * @class Triangle - * @memberof Phaser.Geom - * @constructor - * @since 3.0.0 - * - * @param {number} [x1=0] - `x` coordinate of the first point. - * @param {number} [y1=0] - `y` coordinate of the first point. - * @param {number} [x2=0] - `x` coordinate of the second point. - * @param {number} [y2=0] - `y` coordinate of the second point. - * @param {number} [x3=0] - `x` coordinate of the third point. - * @param {number} [y3=0] - `y` coordinate of the third point. - */ -var Triangle = new Class({ - - initialize: - - function Triangle (x1, y1, x2, y2, x3, y3) - { - if (x1 === undefined) { x1 = 0; } - if (y1 === undefined) { y1 = 0; } - if (x2 === undefined) { x2 = 0; } - if (y2 === undefined) { y2 = 0; } - if (x3 === undefined) { x3 = 0; } - if (y3 === undefined) { y3 = 0; } - - /** - * The geometry constant type of this object: `GEOM_CONST.TRIANGLE`. - * Used for fast type comparisons. - * - * @name Phaser.Geom.Triangle#type - * @type {integer} - * @readonly - * @since 3.19.0 - */ - this.type = GEOM_CONST.TRIANGLE; - - /** - * `x` coordinate of the first point. - * - * @name Phaser.Geom.Triangle#x1 - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x1 = x1; - - /** - * `y` coordinate of the first point. - * - * @name Phaser.Geom.Triangle#y1 - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y1 = y1; - - /** - * `x` coordinate of the second point. - * - * @name Phaser.Geom.Triangle#x2 - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x2 = x2; - - /** - * `y` coordinate of the second point. - * - * @name Phaser.Geom.Triangle#y2 - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y2 = y2; - - /** - * `x` coordinate of the third point. - * - * @name Phaser.Geom.Triangle#x3 - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x3 = x3; - - /** - * `y` coordinate of the third point. - * - * @name Phaser.Geom.Triangle#y3 - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y3 = y3; - }, - - /** - * Checks whether a given points lies within the triangle. - * - * @method Phaser.Geom.Triangle#contains - * @since 3.0.0 - * - * @param {number} x - The x coordinate of the point to check. - * @param {number} y - The y coordinate of the point to check. - * - * @return {boolean} `true` if the coordinate pair is within the triangle, otherwise `false`. - */ - contains: function (x, y) - { - return Contains(this, x, y); - }, - - /** - * Returns a specific point on the triangle. - * - * @method Phaser.Geom.Triangle#getPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [output,$return] - * - * @param {number} position - Position as float within `0` and `1`. `0` equals the first point. - * @param {(Phaser.Geom.Point|object)} [output] - Optional Point, or point-like object, that the calculated point will be written to. - * - * @return {(Phaser.Geom.Point|object)} Calculated `Point` that represents the requested position. It is the same as `output` when this parameter has been given. - */ - getPoint: function (position, output) - { - return GetPoint(this, position, output); - }, - - /** - * Calculates a list of evenly distributed points on the triangle. It is either possible to pass an amount of points to be generated (`quantity`) or the distance between two points (`stepRate`). - * - * @method Phaser.Geom.Triangle#getPoints - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point[]} O - [output,$return] - * - * @param {integer} quantity - Number of points to be generated. Can be falsey when `stepRate` should be used. All points have the same distance along the triangle. - * @param {number} [stepRate] - Distance between two points. Will only be used when `quantity` is falsey. - * @param {(array|Phaser.Geom.Point[])} [output] - Optional Array for writing the calculated points into. Otherwise a new array will be created. - * - * @return {(array|Phaser.Geom.Point[])} Returns a list of calculated `Point` instances or the filled array passed as parameter `output`. - */ - getPoints: function (quantity, stepRate, output) - { - return GetPoints(this, quantity, stepRate, output); - }, - - /** - * Returns a random point along the triangle. - * - * @method Phaser.Geom.Triangle#getRandomPoint - * @since 3.0.0 - * - * @generic {Phaser.Geom.Point} O - [point,$return] - * - * @param {Phaser.Geom.Point} [point] - Optional `Point` that should be modified. Otherwise a new one will be created. - * - * @return {Phaser.Geom.Point} Random `Point`. When parameter `point` has been provided it will be returned. - */ - getRandomPoint: function (point) - { - return Random(this, point); - }, - - /** - * Sets all three points of the triangle. Leaving out any coordinate sets it to be `0`. - * - * @method Phaser.Geom.Triangle#setTo - * @since 3.0.0 - * - * @param {number} [x1=0] - `x` coordinate of the first point. - * @param {number} [y1=0] - `y` coordinate of the first point. - * @param {number} [x2=0] - `x` coordinate of the second point. - * @param {number} [y2=0] - `y` coordinate of the second point. - * @param {number} [x3=0] - `x` coordinate of the third point. - * @param {number} [y3=0] - `y` coordinate of the third point. - * - * @return {Phaser.Geom.Triangle} This Triangle object. - */ - setTo: function (x1, y1, x2, y2, x3, y3) - { - if (x1 === undefined) { x1 = 0; } - if (y1 === undefined) { y1 = 0; } - if (x2 === undefined) { x2 = 0; } - if (y2 === undefined) { y2 = 0; } - if (x3 === undefined) { x3 = 0; } - if (y3 === undefined) { y3 = 0; } - - this.x1 = x1; - this.y1 = y1; - - this.x2 = x2; - this.y2 = y2; - - this.x3 = x3; - this.y3 = y3; - - return this; - }, - - /** - * Returns a Line object that corresponds to Line A of this Triangle. - * - * @method Phaser.Geom.Triangle#getLineA - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to line A of this Triangle. - */ - getLineA: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.x1, this.y1, this.x2, this.y2); - - return line; - }, - - /** - * Returns a Line object that corresponds to Line B of this Triangle. - * - * @method Phaser.Geom.Triangle#getLineB - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to line B of this Triangle. - */ - getLineB: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.x2, this.y2, this.x3, this.y3); - - return line; - }, - - /** - * Returns a Line object that corresponds to Line C of this Triangle. - * - * @method Phaser.Geom.Triangle#getLineC - * @since 3.0.0 - * - * @generic {Phaser.Geom.Line} O - [line,$return] - * - * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. - * - * @return {Phaser.Geom.Line} A Line object that corresponds to line C of this Triangle. - */ - getLineC: function (line) - { - if (line === undefined) { line = new Line(); } - - line.setTo(this.x3, this.y3, this.x1, this.y1); - - return line; - }, - - /** - * Left most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. - * - * @name Phaser.Geom.Triangle#left - * @type {number} - * @since 3.0.0 - */ - left: { - - get: function () - { - return Math.min(this.x1, this.x2, this.x3); - }, - - set: function (value) - { - var diff = 0; - - if (this.x1 <= this.x2 && this.x1 <= this.x3) - { - diff = this.x1 - value; - } - else if (this.x2 <= this.x1 && this.x2 <= this.x3) - { - diff = this.x2 - value; - } - else - { - diff = this.x3 - value; - } - - this.x1 -= diff; - this.x2 -= diff; - this.x3 -= diff; - } - - }, - - /** - * Right most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. - * - * @name Phaser.Geom.Triangle#right - * @type {number} - * @since 3.0.0 - */ - right: { - - get: function () - { - return Math.max(this.x1, this.x2, this.x3); - }, - - set: function (value) - { - var diff = 0; - - if (this.x1 >= this.x2 && this.x1 >= this.x3) - { - diff = this.x1 - value; - } - else if (this.x2 >= this.x1 && this.x2 >= this.x3) - { - diff = this.x2 - value; - } - else - { - diff = this.x3 - value; - } - - this.x1 -= diff; - this.x2 -= diff; - this.x3 -= diff; - } - - }, - - /** - * Top most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. - * - * @name Phaser.Geom.Triangle#top - * @type {number} - * @since 3.0.0 - */ - top: { - - get: function () - { - return Math.min(this.y1, this.y2, this.y3); - }, - - set: function (value) - { - var diff = 0; - - if (this.y1 <= this.y2 && this.y1 <= this.y3) - { - diff = this.y1 - value; - } - else if (this.y2 <= this.y1 && this.y2 <= this.y3) - { - diff = this.y2 - value; - } - else - { - diff = this.y3 - value; - } - - this.y1 -= diff; - this.y2 -= diff; - this.y3 -= diff; - } - - }, - - /** - * Bottom most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. - * - * @name Phaser.Geom.Triangle#bottom - * @type {number} - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return Math.max(this.y1, this.y2, this.y3); - }, - - set: function (value) - { - var diff = 0; - - if (this.y1 >= this.y2 && this.y1 >= this.y3) - { - diff = this.y1 - value; - } - else if (this.y2 >= this.y1 && this.y2 >= this.y3) - { - diff = this.y2 - value; - } - else - { - diff = this.y3 - value; - } - - this.y1 -= diff; - this.y2 -= diff; - this.y3 -= diff; - } - - } - -}); - -module.exports = Triangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Contains = require('./Contains'); +var GetPoint = require('./GetPoint'); +var GetPoints = require('./GetPoints'); +var GEOM_CONST = require('../const'); +var Line = require('../line/Line'); +var Random = require('./Random'); + +/** + * @classdesc + * A triangle is a plane created by connecting three points. + * The first two arguments specify the first point, the middle two arguments + * specify the second point, and the last two arguments specify the third point. + * + * @class Triangle + * @memberof Phaser.Geom + * @constructor + * @since 3.0.0 + * + * @param {number} [x1=0] - `x` coordinate of the first point. + * @param {number} [y1=0] - `y` coordinate of the first point. + * @param {number} [x2=0] - `x` coordinate of the second point. + * @param {number} [y2=0] - `y` coordinate of the second point. + * @param {number} [x3=0] - `x` coordinate of the third point. + * @param {number} [y3=0] - `y` coordinate of the third point. + */ +var Triangle = new Class({ + + initialize: + + function Triangle (x1, y1, x2, y2, x3, y3) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + if (x3 === undefined) { x3 = 0; } + if (y3 === undefined) { y3 = 0; } + + /** + * The geometry constant type of this object: `GEOM_CONST.TRIANGLE`. + * Used for fast type comparisons. + * + * @name Phaser.Geom.Triangle#type + * @type {integer} + * @readonly + * @since 3.19.0 + */ + this.type = GEOM_CONST.TRIANGLE; + + /** + * `x` coordinate of the first point. + * + * @name Phaser.Geom.Triangle#x1 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x1 = x1; + + /** + * `y` coordinate of the first point. + * + * @name Phaser.Geom.Triangle#y1 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y1 = y1; + + /** + * `x` coordinate of the second point. + * + * @name Phaser.Geom.Triangle#x2 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x2 = x2; + + /** + * `y` coordinate of the second point. + * + * @name Phaser.Geom.Triangle#y2 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y2 = y2; + + /** + * `x` coordinate of the third point. + * + * @name Phaser.Geom.Triangle#x3 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x3 = x3; + + /** + * `y` coordinate of the third point. + * + * @name Phaser.Geom.Triangle#y3 + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y3 = y3; + }, + + /** + * Checks whether a given points lies within the triangle. + * + * @method Phaser.Geom.Triangle#contains + * @since 3.0.0 + * + * @param {number} x - The x coordinate of the point to check. + * @param {number} y - The y coordinate of the point to check. + * + * @return {boolean} `true` if the coordinate pair is within the triangle, otherwise `false`. + */ + contains: function (x, y) + { + return Contains(this, x, y); + }, + + /** + * Returns a specific point on the triangle. + * + * @method Phaser.Geom.Triangle#getPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [output,$return] + * + * @param {number} position - Position as float within `0` and `1`. `0` equals the first point. + * @param {(Phaser.Geom.Point|object)} [output] - Optional Point, or point-like object, that the calculated point will be written to. + * + * @return {(Phaser.Geom.Point|object)} Calculated `Point` that represents the requested position. It is the same as `output` when this parameter has been given. + */ + getPoint: function (position, output) + { + return GetPoint(this, position, output); + }, + + /** + * Calculates a list of evenly distributed points on the triangle. It is either possible to pass an amount of points to be generated (`quantity`) or the distance between two points (`stepRate`). + * + * @method Phaser.Geom.Triangle#getPoints + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point[]} O - [output,$return] + * + * @param {integer} quantity - Number of points to be generated. Can be falsey when `stepRate` should be used. All points have the same distance along the triangle. + * @param {number} [stepRate] - Distance between two points. Will only be used when `quantity` is falsey. + * @param {(array|Phaser.Geom.Point[])} [output] - Optional Array for writing the calculated points into. Otherwise a new array will be created. + * + * @return {(array|Phaser.Geom.Point[])} Returns a list of calculated `Point` instances or the filled array passed as parameter `output`. + */ + getPoints: function (quantity, stepRate, output) + { + return GetPoints(this, quantity, stepRate, output); + }, + + /** + * Returns a random point along the triangle. + * + * @method Phaser.Geom.Triangle#getRandomPoint + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [point,$return] + * + * @param {Phaser.Geom.Point} [point] - Optional `Point` that should be modified. Otherwise a new one will be created. + * + * @return {Phaser.Geom.Point} Random `Point`. When parameter `point` has been provided it will be returned. + */ + getRandomPoint: function (point) + { + return Random(this, point); + }, + + /** + * Sets all three points of the triangle. Leaving out any coordinate sets it to be `0`. + * + * @method Phaser.Geom.Triangle#setTo + * @since 3.0.0 + * + * @param {number} [x1=0] - `x` coordinate of the first point. + * @param {number} [y1=0] - `y` coordinate of the first point. + * @param {number} [x2=0] - `x` coordinate of the second point. + * @param {number} [y2=0] - `y` coordinate of the second point. + * @param {number} [x3=0] - `x` coordinate of the third point. + * @param {number} [y3=0] - `y` coordinate of the third point. + * + * @return {Phaser.Geom.Triangle} This Triangle object. + */ + setTo: function (x1, y1, x2, y2, x3, y3) + { + if (x1 === undefined) { x1 = 0; } + if (y1 === undefined) { y1 = 0; } + if (x2 === undefined) { x2 = 0; } + if (y2 === undefined) { y2 = 0; } + if (x3 === undefined) { x3 = 0; } + if (y3 === undefined) { y3 = 0; } + + this.x1 = x1; + this.y1 = y1; + + this.x2 = x2; + this.y2 = y2; + + this.x3 = x3; + this.y3 = y3; + + return this; + }, + + /** + * Returns a Line object that corresponds to Line A of this Triangle. + * + * @method Phaser.Geom.Triangle#getLineA + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to line A of this Triangle. + */ + getLineA: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x1, this.y1, this.x2, this.y2); + + return line; + }, + + /** + * Returns a Line object that corresponds to Line B of this Triangle. + * + * @method Phaser.Geom.Triangle#getLineB + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to line B of this Triangle. + */ + getLineB: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x2, this.y2, this.x3, this.y3); + + return line; + }, + + /** + * Returns a Line object that corresponds to Line C of this Triangle. + * + * @method Phaser.Geom.Triangle#getLineC + * @since 3.0.0 + * + * @generic {Phaser.Geom.Line} O - [line,$return] + * + * @param {Phaser.Geom.Line} [line] - A Line object to set the results in. If `undefined` a new Line will be created. + * + * @return {Phaser.Geom.Line} A Line object that corresponds to line C of this Triangle. + */ + getLineC: function (line) + { + if (line === undefined) { line = new Line(); } + + line.setTo(this.x3, this.y3, this.x1, this.y1); + + return line; + }, + + /** + * Left most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. + * + * @name Phaser.Geom.Triangle#left + * @type {number} + * @since 3.0.0 + */ + left: { + + get: function () + { + return Math.min(this.x1, this.x2, this.x3); + }, + + set: function (value) + { + var diff = 0; + + if (this.x1 <= this.x2 && this.x1 <= this.x3) + { + diff = this.x1 - value; + } + else if (this.x2 <= this.x1 && this.x2 <= this.x3) + { + diff = this.x2 - value; + } + else + { + diff = this.x3 - value; + } + + this.x1 -= diff; + this.x2 -= diff; + this.x3 -= diff; + } + + }, + + /** + * Right most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. + * + * @name Phaser.Geom.Triangle#right + * @type {number} + * @since 3.0.0 + */ + right: { + + get: function () + { + return Math.max(this.x1, this.x2, this.x3); + }, + + set: function (value) + { + var diff = 0; + + if (this.x1 >= this.x2 && this.x1 >= this.x3) + { + diff = this.x1 - value; + } + else if (this.x2 >= this.x1 && this.x2 >= this.x3) + { + diff = this.x2 - value; + } + else + { + diff = this.x3 - value; + } + + this.x1 -= diff; + this.x2 -= diff; + this.x3 -= diff; + } + + }, + + /** + * Top most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. + * + * @name Phaser.Geom.Triangle#top + * @type {number} + * @since 3.0.0 + */ + top: { + + get: function () + { + return Math.min(this.y1, this.y2, this.y3); + }, + + set: function (value) + { + var diff = 0; + + if (this.y1 <= this.y2 && this.y1 <= this.y3) + { + diff = this.y1 - value; + } + else if (this.y2 <= this.y1 && this.y2 <= this.y3) + { + diff = this.y2 - value; + } + else + { + diff = this.y3 - value; + } + + this.y1 -= diff; + this.y2 -= diff; + this.y3 -= diff; + } + + }, + + /** + * Bottom most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. + * + * @name Phaser.Geom.Triangle#bottom + * @type {number} + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return Math.max(this.y1, this.y2, this.y3); + }, + + set: function (value) + { + var diff = 0; + + if (this.y1 >= this.y2 && this.y1 >= this.y3) + { + diff = this.y1 - value; + } + else if (this.y2 >= this.y1 && this.y2 >= this.y3) + { + diff = this.y2 - value; + } + else + { + diff = this.y3 - value; + } + + this.y1 -= diff; + this.y2 -= diff; + this.y3 -= diff; + } + + } + +}); + +module.exports = Triangle; diff --git a/src/geom/triangle/index.js b/src/geom/triangle/index.js index 050f8a177..3cb2f3159 100644 --- a/src/geom/triangle/index.js +++ b/src/geom/triangle/index.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Triangle = require('./Triangle'); - -Triangle.Area = require('./Area'); -Triangle.BuildEquilateral = require('./BuildEquilateral'); -Triangle.BuildFromPolygon = require('./BuildFromPolygon'); -Triangle.BuildRight = require('./BuildRight'); -Triangle.CenterOn = require('./CenterOn'); -Triangle.Centroid = require('./Centroid'); -Triangle.CircumCenter = require('./CircumCenter'); -Triangle.CircumCircle = require('./CircumCircle'); -Triangle.Clone = require('./Clone'); -Triangle.Contains = require('./Contains'); -Triangle.ContainsArray = require('./ContainsArray'); -Triangle.ContainsPoint = require('./ContainsPoint'); -Triangle.CopyFrom = require('./CopyFrom'); -Triangle.Decompose = require('./Decompose'); -Triangle.Equals = require('./Equals'); -Triangle.GetPoint = require('./GetPoint'); -Triangle.GetPoints = require('./GetPoints'); -Triangle.InCenter = require('./InCenter'); -Triangle.Perimeter = require('./Perimeter'); -Triangle.Offset = require('./Offset'); -Triangle.Random = require('./Random'); -Triangle.Rotate = require('./Rotate'); -Triangle.RotateAroundPoint = require('./RotateAroundPoint'); -Triangle.RotateAroundXY = require('./RotateAroundXY'); - -module.exports = Triangle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Triangle = require('./Triangle'); + +Triangle.Area = require('./Area'); +Triangle.BuildEquilateral = require('./BuildEquilateral'); +Triangle.BuildFromPolygon = require('./BuildFromPolygon'); +Triangle.BuildRight = require('./BuildRight'); +Triangle.CenterOn = require('./CenterOn'); +Triangle.Centroid = require('./Centroid'); +Triangle.CircumCenter = require('./CircumCenter'); +Triangle.CircumCircle = require('./CircumCircle'); +Triangle.Clone = require('./Clone'); +Triangle.Contains = require('./Contains'); +Triangle.ContainsArray = require('./ContainsArray'); +Triangle.ContainsPoint = require('./ContainsPoint'); +Triangle.CopyFrom = require('./CopyFrom'); +Triangle.Decompose = require('./Decompose'); +Triangle.Equals = require('./Equals'); +Triangle.GetPoint = require('./GetPoint'); +Triangle.GetPoints = require('./GetPoints'); +Triangle.InCenter = require('./InCenter'); +Triangle.Perimeter = require('./Perimeter'); +Triangle.Offset = require('./Offset'); +Triangle.Random = require('./Random'); +Triangle.Rotate = require('./Rotate'); +Triangle.RotateAroundPoint = require('./RotateAroundPoint'); +Triangle.RotateAroundXY = require('./RotateAroundXY'); + +module.exports = Triangle; diff --git a/src/input/CreateInteractiveObject.js b/src/input/CreateInteractiveObject.js index 2c9df433e..dbe1eccff 100644 --- a/src/input/CreateInteractiveObject.js +++ b/src/input/CreateInteractiveObject.js @@ -1,65 +1,65 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Creates a new Interactive Object. - * - * This is called automatically by the Input Manager when you enable a Game Object for input. - * - * The resulting Interactive Object is mapped to the Game Object's `input` property. - * - * @function Phaser.Input.CreateInteractiveObject - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to which this Interactive Object is bound. - * @param {any} hitArea - The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. - * @param {Phaser.Types.Input.HitAreaCallback} hitAreaCallback - The 'contains' check callback that the hit area shape will use for all hit tests. - * - * @return {Phaser.Types.Input.InteractiveObject} The new Interactive Object. - */ -var CreateInteractiveObject = function (gameObject, hitArea, hitAreaCallback) -{ - return { - - gameObject: gameObject, - - enabled: true, - alwaysEnabled: false, - draggable: false, - dropZone: false, - cursor: false, - - target: null, - - camera: null, - - hitArea: hitArea, - hitAreaCallback: hitAreaCallback, - hitAreaDebug: null, - - // Has the dev specified their own shape, or is this bound to the texture size? - customHitArea: false, - - localX: 0, - localY: 0, - - // 0 = Not being dragged - // 1 = Being checked for dragging - // 2 = Being dragged - dragState: 0, - - dragStartX: 0, - dragStartY: 0, - dragStartXGlobal: 0, - dragStartYGlobal: 0, - - dragX: 0, - dragY: 0 - - }; -}; - -module.exports = CreateInteractiveObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates a new Interactive Object. + * + * This is called automatically by the Input Manager when you enable a Game Object for input. + * + * The resulting Interactive Object is mapped to the Game Object's `input` property. + * + * @function Phaser.Input.CreateInteractiveObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to which this Interactive Object is bound. + * @param {any} hitArea - The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. + * @param {Phaser.Types.Input.HitAreaCallback} hitAreaCallback - The 'contains' check callback that the hit area shape will use for all hit tests. + * + * @return {Phaser.Types.Input.InteractiveObject} The new Interactive Object. + */ +var CreateInteractiveObject = function (gameObject, hitArea, hitAreaCallback) +{ + return { + + gameObject: gameObject, + + enabled: true, + alwaysEnabled: false, + draggable: false, + dropZone: false, + cursor: false, + + target: null, + + camera: null, + + hitArea: hitArea, + hitAreaCallback: hitAreaCallback, + hitAreaDebug: null, + + // Has the dev specified their own shape, or is this bound to the texture size? + customHitArea: false, + + localX: 0, + localY: 0, + + // 0 = Not being dragged + // 1 = Being checked for dragging + // 2 = Being dragged + dragState: 0, + + dragStartX: 0, + dragStartY: 0, + dragStartXGlobal: 0, + dragStartYGlobal: 0, + + dragX: 0, + dragY: 0 + + }; +}; + +module.exports = CreateInteractiveObject; diff --git a/src/input/CreatePixelPerfectHandler.js b/src/input/CreatePixelPerfectHandler.js index d975d6d36..2b8f27db6 100644 --- a/src/input/CreatePixelPerfectHandler.js +++ b/src/input/CreatePixelPerfectHandler.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Creates a new Pixel Perfect Handler function. - * - * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. - * - * @function Phaser.Input.CreatePixelPerfectHandler - * @since 3.10.0 - * - * @param {Phaser.Textures.TextureManager} textureManager - A reference to the Texture Manager. - * @param {integer} alphaTolerance - The alpha level that the pixel should be above to be included as a successful interaction. - * - * @return {function} The new Pixel Perfect Handler function. - */ -var CreatePixelPerfectHandler = function (textureManager, alphaTolerance) -{ - return function (hitArea, x, y, gameObject) - { - var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.name); - - return (alpha && alpha >= alphaTolerance); - }; -}; - -module.exports = CreatePixelPerfectHandler; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates a new Pixel Perfect Handler function. + * + * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. + * + * @function Phaser.Input.CreatePixelPerfectHandler + * @since 3.10.0 + * + * @param {Phaser.Textures.TextureManager} textureManager - A reference to the Texture Manager. + * @param {integer} alphaTolerance - The alpha level that the pixel should be above to be included as a successful interaction. + * + * @return {function} The new Pixel Perfect Handler function. + */ +var CreatePixelPerfectHandler = function (textureManager, alphaTolerance) +{ + return function (hitArea, x, y, gameObject) + { + var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.name); + + return (alpha && alpha >= alphaTolerance); + }; +}; + +module.exports = CreatePixelPerfectHandler; diff --git a/src/input/InputManager.js b/src/input/InputManager.js index 3dbaceeac..ca89708a4 100644 --- a/src/input/InputManager.js +++ b/src/input/InputManager.js @@ -1,1076 +1,1076 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CONST = require('./const'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GameEvents = require('../core/events'); -var Keyboard = require('./keyboard/KeyboardManager'); -var Mouse = require('./mouse/MouseManager'); -var Pointer = require('./Pointer'); -var Touch = require('./touch/TouchManager'); -var TransformMatrix = require('../gameobjects/components/TransformMatrix'); -var TransformXY = require('../math/TransformXY'); - -/** - * @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. - */ -var InputManager = new Class({ - - initialize: - - function InputManager (game, config) - { - /** - * The Game instance that owns the Input Manager. - * A Game only maintains on instance of the Input Manager at any time. - * - * @name Phaser.Input.InputManager#game - * @type {Phaser.Game} - * @readonly - * @since 3.0.0 - */ - this.game = game; - - /** - * A reference to the global Game Scale Manager. - * Used for all bounds checks and pointer scaling. - * - * @name Phaser.Input.InputManager#scaleManager - * @type {Phaser.Scale.ScaleManager} - * @since 3.16.0 - */ - this.scaleManager; - - /** - * The Canvas that is used for all DOM event input listeners. - * - * @name Phaser.Input.InputManager#canvas - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.canvas; - - /** - * The Game Configuration object, as set during the game boot. - * - * @name Phaser.Input.InputManager#config - * @type {Phaser.Core.Config} - * @since 3.0.0 - */ - this.config = config; - - /** - * If set, the Input Manager will run its update loop every frame. - * - * @name Phaser.Input.InputManager#enabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enabled = true; - - /** - * The Event Emitter instance that the Input Manager uses to emit events from. - * - * @name Phaser.Input.InputManager#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events = new EventEmitter(); - - /** - * Are any mouse or touch pointers currently over the game canvas? - * This is updated automatically by the canvas over and out handlers. - * - * @name Phaser.Input.InputManager#isOver - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - this.isOver = true; - - /** - * The default CSS cursor to be used when interacting with your game. - * - * See the `setDefaultCursor` method for more details. - * - * @name Phaser.Input.InputManager#defaultCursor - * @type {string} - * @since 3.10.0 - */ - this.defaultCursor = ''; - - /** - * A reference to the Keyboard Manager class, if enabled via the `input.keyboard` Game Config property. - * - * @name Phaser.Input.InputManager#keyboard - * @type {?Phaser.Input.Keyboard.KeyboardManager} - * @since 3.16.0 - */ - this.keyboard = (config.inputKeyboard) ? new Keyboard(this) : null; - - /** - * A reference to the Mouse Manager class, if enabled via the `input.mouse` Game Config property. - * - * @name Phaser.Input.InputManager#mouse - * @type {?Phaser.Input.Mouse.MouseManager} - * @since 3.0.0 - */ - this.mouse = (config.inputMouse) ? new Mouse(this) : null; - - /** - * A reference to the Touch Manager class, if enabled via the `input.touch` Game Config property. - * - * @name Phaser.Input.InputManager#touch - * @type {Phaser.Input.Touch.TouchManager} - * @since 3.0.0 - */ - this.touch = (config.inputTouch) ? new Touch(this) : null; - - /** - * An array of Pointers that have been added to the game. - * The first entry is reserved for the Mouse Pointer, the rest are Touch Pointers. - * - * By default there is 1 touch pointer enabled. If you need more use the `addPointer` method to start them, - * or set the `input.activePointers` property in the Game Config. - * - * @name Phaser.Input.InputManager#pointers - * @type {Phaser.Input.Pointer[]} - * @since 3.10.0 - */ - this.pointers = []; - - /** - * The number of touch objects activated and being processed each update. - * - * You can change this by either calling `addPointer` at run-time, or by - * setting the `input.activePointers` property in the Game Config. - * - * @name Phaser.Input.InputManager#pointersTotal - * @type {integer} - * @readonly - * @since 3.10.0 - */ - this.pointersTotal = config.inputActivePointers; - - if (config.inputTouch && this.pointersTotal === 1) - { - this.pointersTotal = 2; - } - - for (var i = 0; i <= this.pointersTotal; i++) - { - var pointer = new Pointer(this, i); - - pointer.smoothFactor = config.inputSmoothFactor; - - this.pointers.push(pointer); - } - - /** - * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. - * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` - * which will always map to the most recently interacted pointer. - * - * @name Phaser.Input.InputManager#mousePointer - * @type {?Phaser.Input.Pointer} - * @since 3.10.0 - */ - this.mousePointer = (config.inputMouse) ? this.pointers[0] : null; - - /** - * 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 - */ - this.activePointer = this.pointers[0]; - - /** - * If the top-most Scene in the Scene List receives an input it will stop input from - * propagating any lower down the scene list, i.e. if you have a UI Scene at the top - * and click something on it, that click will not then be passed down to any other - * Scene below. Disable this to have input events passed through all Scenes, all the time. - * - * @name Phaser.Input.InputManager#globalTopOnly - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.globalTopOnly = true; - - /** - * The time this Input Manager was last updated. - * This value is populated by the Game Step each frame. - * - * @name Phaser.Input.InputManager#time - * @type {number} - * @readonly - * @since 3.16.2 - */ - this.time = 0; - - /** - * A re-cycled point-like object to store hit test values in. - * - * @name Phaser.Input.InputManager#_tempPoint - * @type {{x:number, y:number}} - * @private - * @since 3.0.0 - */ - this._tempPoint = { x: 0, y: 0 }; - - /** - * A re-cycled array to store hit results in. - * - * @name Phaser.Input.InputManager#_tempHitTest - * @type {array} - * @private - * @default [] - * @since 3.0.0 - */ - this._tempHitTest = []; - - /** - * A re-cycled matrix used in hit test calculations. - * - * @name Phaser.Input.InputManager#_tempMatrix - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @private - * @since 3.4.0 - */ - this._tempMatrix = new TransformMatrix(); - - /** - * A re-cycled matrix used in hit test calculations. - * - * @name Phaser.Input.InputManager#_tempMatrix2 - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @private - * @since 3.12.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * An internal private var that records Scenes aborting event processing. - * - * @name Phaser.Input.InputManager#_tempSkip - * @type {boolean} - * @private - * @since 3.18.0 - */ - this._tempSkip = false; - - /** - * An internal private array that avoids needing to create a new array on every DOM mouse event. - * - * @name Phaser.Input.InputManager#mousePointerContainer - * @type {Phaser.Input.Pointer[]} - * @private - * @since 3.18.0 - */ - this.mousePointerContainer = [ this.mousePointer ]; - - game.events.once(GameEvents.BOOT, this.boot, this); - }, - - /** - * The Boot handler is called by Phaser.Game when it first starts up. - * The renderer is available by now. - * - * @method Phaser.Input.InputManager#boot - * @protected - * @fires Phaser.Input.Events#MANAGER_BOOT - * @since 3.0.0 - */ - boot: function () - { - this.canvas = this.game.canvas; - - this.scaleManager = this.game.scale; - - this.events.emit(Events.MANAGER_BOOT); - - this.game.events.on(GameEvents.PRE_RENDER, this.preRender, this); - - this.game.events.once(GameEvents.DESTROY, this.destroy, this); - }, - - /** - * Internal canvas state change, called automatically by the Mouse Manager. - * - * @method Phaser.Input.InputManager#setCanvasOver - * @fires Phaser.Input.Events#GAME_OVER - * @private - * @since 3.16.0 - * - * @param {(MouseEvent|TouchEvent)} event - The DOM Event. - */ - setCanvasOver: function (event) - { - this.isOver = true; - - this.events.emit(Events.GAME_OVER, event); - }, - - /** - * Internal canvas state change, called automatically by the Mouse Manager. - * - * @method Phaser.Input.InputManager#setCanvasOut - * @fires Phaser.Input.Events#GAME_OUT - * @private - * @since 3.16.0 - * - * @param {(MouseEvent|TouchEvent)} event - The DOM Event. - */ - setCanvasOut: function (event) - { - this.isOver = false; - - this.events.emit(Events.GAME_OUT, event); - }, - - /** - * Internal update, called automatically by the Game Step right at the start. - * - * @method Phaser.Input.InputManager#preRender - * @private - * @since 3.18.0 - */ - preRender: function () - { - var time = this.game.loop.now; - var delta = this.game.loop.delta; - var scenes = this.game.scene.getScenes(true, true); - - this.time = time; - - this.events.emit(Events.MANAGER_UPDATE); - - for (var i = 0; i < scenes.length; i++) - { - var scene = scenes[i]; - - if (scene.sys.input && scene.sys.input.updatePoll(time, delta) && this.globalTopOnly) - { - // If the Scene returns true, it means it captured some input that no other Scene should get, so we bail out - return; - } - } - }, - - /** - * 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. - */ - setDefaultCursor: function (cursor) - { - this.defaultCursor = cursor; - - if (this.canvas.style.cursor !== cursor) - { - this.canvas.style.cursor = 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. - */ - setCursor: function (interactiveObject) - { - if (interactiveObject.cursor) - { - this.canvas.style.cursor = interactiveObject.cursor; - } - }, - - /** - * Called by the InputPlugin when processing over and out events. - * - * Tells the Input Manager to clear the hand cursor, if set, during its postUpdate step. - * - * @method Phaser.Input.InputManager#resetCursor - * @private - * @since 3.10.0 - * - * @param {Phaser.Types.Input.InteractiveObject} interactiveObject - The Interactive Object that called this method. - */ - resetCursor: function (interactiveObject) - { - if (interactiveObject.cursor && this.canvas) - { - this.canvas.style.cursor = this.defaultCursor; - } - }, - - /** - * Adds new Pointer objects to the Input Manager. - * - * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. - * - * You can create more either by calling this method, or by setting the `input.activePointers` property - * in the Game Config, up to a maximum of 10 pointers. - * - * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added - * via this method. - * - * @method Phaser.Input.InputManager#addPointer - * @since 3.10.0 - * - * @param {integer} [quantity=1] The number of new Pointers to create. A maximum of 10 is allowed in total. - * - * @return {Phaser.Input.Pointer[]} An array containing all of the new Pointer objects that were created. - */ - addPointer: function (quantity) - { - if (quantity === undefined) { quantity = 1; } - - var output = []; - - if (this.pointersTotal + quantity > 10) - { - quantity = 10 - this.pointersTotal; - } - - for (var i = 0; i < quantity; i++) - { - var id = this.pointers.length; - - var pointer = new Pointer(this, id); - - pointer.smoothFactor = this.config.inputSmoothFactor; - - this.pointers.push(pointer); - - this.pointersTotal++; - - output.push(pointer); - } - - return output; - }, - - /** - * Internal method that gets a list of all the active Input Plugins in the game - * and updates each of them in turn, in reverse order (top to bottom), to allow - * for DOM top-level event handling simulation. - * - * @method Phaser.Input.InputManager#updateInputPlugins - * @since 3.16.0 - * - * @param {integer} type - The type of event to process. - * @param {Phaser.Input.Pointer[]} pointers - An array of Pointers on which the event occurred. - */ - updateInputPlugins: function (type, pointers) - { - var scenes = this.game.scene.getScenes(true, true); - - this._tempSkip = false; - - for (var i = 0; i < scenes.length; i++) - { - var scene = scenes[i]; - - if (scene.sys.input) - { - var capture = scene.sys.input.update(type, pointers); - - if ((capture && this.globalTopOnly) || this._tempSkip) - { - // If the Scene returns true, or called stopPropagation, it means it captured some input that no other Scene should get, so we bail out - return; - } - } - } - }, - - // 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 - - /** - * Processes a touch start event, as passed in by the TouchManager. - * - * @method Phaser.Input.InputManager#onTouchStart - * @private - * @since 3.18.0 - * - * @param {TouchEvent} event - The native DOM Touch event. - */ - onTouchStart: function (event) - { - var pointers = this.pointers; - var changed = []; - - for (var c = 0; c < event.changedTouches.length; c++) - { - var changedTouch = event.changedTouches[c]; - - for (var i = 1; i < this.pointersTotal; i++) - { - var pointer = pointers[i]; - - if (!pointer.active) - { - pointer.touchstart(changedTouch, event); - - this.activePointer = pointer; - - changed.push(pointer); - - break; - } - } - } - - this.updateInputPlugins(CONST.TOUCH_START, changed); - }, - - /** - * Processes a touch move event, as passed in by the TouchManager. - * - * @method Phaser.Input.InputManager#onTouchMove - * @private - * @since 3.18.0 - * - * @param {TouchEvent} event - The native DOM Touch event. - */ - onTouchMove: function (event) - { - var pointers = this.pointers; - var changed = []; - - for (var c = 0; c < event.changedTouches.length; c++) - { - var changedTouch = event.changedTouches[c]; - - for (var i = 1; i < this.pointersTotal; i++) - { - var pointer = pointers[i]; - - if (pointer.active && pointer.identifier === changedTouch.identifier) - { - pointer.touchmove(changedTouch, event); - - this.activePointer = pointer; - - changed.push(pointer); - - break; - } - } - } - - this.updateInputPlugins(CONST.TOUCH_MOVE, changed); - }, - - // 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 - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - - /** - * Processes a touch end event, as passed in by the TouchManager. - * - * @method Phaser.Input.InputManager#onTouchEnd - * @private - * @since 3.18.0 - * - * @param {TouchEvent} event - The native DOM Touch event. - */ - onTouchEnd: function (event) - { - var pointers = this.pointers; - var changed = []; - - for (var c = 0; c < event.changedTouches.length; c++) - { - var changedTouch = event.changedTouches[c]; - - for (var i = 1; i < this.pointersTotal; i++) - { - var pointer = pointers[i]; - - if (pointer.active && pointer.identifier === changedTouch.identifier) - { - pointer.touchend(changedTouch, event); - - changed.push(pointer); - - break; - } - } - } - - this.updateInputPlugins(CONST.TOUCH_END, changed); - }, - - /** - * Processes a touch cancel event, as passed in by the TouchManager. - * - * @method Phaser.Input.InputManager#onTouchCancel - * @private - * @since 3.18.0 - * - * @param {TouchEvent} event - The native DOM Touch event. - */ - onTouchCancel: function (event) - { - var pointers = this.pointers; - var changed = []; - - for (var c = 0; c < event.changedTouches.length; c++) - { - var changedTouch = event.changedTouches[c]; - - for (var i = 1; i < this.pointersTotal; i++) - { - var pointer = pointers[i]; - - if (pointer.active && pointer.identifier === changedTouch.identifier) - { - pointer.touchcancel(changedTouch, event); - - changed.push(pointer); - - break; - } - } - } - - this.updateInputPlugins(CONST.TOUCH_CANCEL, changed); - }, - - /** - * Processes a mouse down event, as passed in by the MouseManager. - * - * @method Phaser.Input.InputManager#onMouseDown - * @private - * @since 3.18.0 - * - * @param {MouseEvent} event - The native DOM Mouse event. - */ - onMouseDown: function (event) - { - this.mousePointer.down(event); - - this.mousePointer.updateMotion(); - - this.updateInputPlugins(CONST.MOUSE_DOWN, this.mousePointerContainer); - }, - - /** - * Processes a mouse move event, as passed in by the MouseManager. - * - * @method Phaser.Input.InputManager#onMouseMove - * @private - * @since 3.18.0 - * - * @param {MouseEvent} event - The native DOM Mouse event. - */ - onMouseMove: function (event) - { - this.mousePointer.move(event); - - this.mousePointer.updateMotion(); - - this.updateInputPlugins(CONST.MOUSE_MOVE, this.mousePointerContainer); - }, - - /** - * Processes a mouse up event, as passed in by the MouseManager. - * - * @method Phaser.Input.InputManager#onMouseUp - * @private - * @since 3.18.0 - * - * @param {MouseEvent} event - The native DOM Mouse event. - */ - onMouseUp: function (event) - { - this.mousePointer.up(event); - - this.mousePointer.updateMotion(); - - this.updateInputPlugins(CONST.MOUSE_UP, this.mousePointerContainer); - }, - - /** - * Processes a mouse wheel event, as passed in by the MouseManager. - * - * @method Phaser.Input.InputManager#onMouseWheel - * @private - * @since 3.18.0 - * - * @param {WheelEvent} event - The native DOM Wheel event. - */ - onMouseWheel: function (event) - { - this.mousePointer.wheel(event); - - this.updateInputPlugins(CONST.MOUSE_WHEEL, this.mousePointerContainer); - }, - - /** - * Processes a pointer lock change event, as passed in by the MouseManager. - * - * @method Phaser.Input.InputManager#onPointerLockChange - * @fires Phaser.Input.Events#POINTERLOCK_CHANGE - * @private - * @since 3.19.0 - * - * @param {MouseEvent} event - The native DOM Mouse event. - */ - onPointerLockChange: function (event) - { - var isLocked = this.mouse.locked; - - this.mousePointer.locked = isLocked; - - this.events.emit(Events.POINTERLOCK_CHANGE, event, isLocked); - }, - - /** - * Checks if the given Game Object should be considered as a candidate for input or not. - * - * Checks if the Game Object has an input component that is enabled, that it will render, - * and finally, if it has a parent, that the parent parent, or any ancestor, is visible or not. - * - * @method Phaser.Input.InputManager#inputCandidate - * @private - * @since 3.10.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to test. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. - * - * @return {boolean} `true` if the Game Object should be considered for input, otherwise `false`. - */ - inputCandidate: function (gameObject, camera) - { - var input = gameObject.input; - - if (!input || !input.enabled || (!input.alwaysEnabled && !gameObject.willRender(camera))) - { - return false; - } - - var visible = true; - var parent = gameObject.parentContainer; - - if (parent) - { - do - { - if (!parent.willRender(camera)) - { - visible = false; - break; - } - - parent = parent.parentContainer; - - } while (parent); - } - - return visible; - }, - - /** - * Performs a hit test using the given Pointer and camera, against an array of interactive Game Objects. - * - * The Game Objects are culled against the camera, and then the coordinates are translated into the local camera space - * and used to determine if they fall within the remaining Game Objects hit areas or not. - * - * If nothing is matched an empty array is returned. - * - * This method is called automatically by InputPlugin.hitTestPointer and doesn't usually need to be invoked directly. - * - * @method Phaser.Input.InputManager#hitTest - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to test against. - * @param {array} gameObjects - An array of interactive Game Objects to check. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. - * @param {array} [output] - An array to store the results in. If not given, a new empty array is created. - * - * @return {array} An array of the Game Objects that were hit during this hit test. - */ - hitTest: function (pointer, gameObjects, camera, output) - { - if (output === undefined) { output = this._tempHitTest; } - - var tempPoint = this._tempPoint; - - var csx = camera.scrollX; - var csy = camera.scrollY; - - output.length = 0; - - var x = pointer.x; - var y = pointer.y; - - if (camera.resolution !== 1) - { - x += camera._x; - y += camera._y; - } - - // Stores the world point inside of tempPoint - camera.getWorldPoint(x, y, tempPoint); - - pointer.worldX = tempPoint.x; - pointer.worldY = tempPoint.y; - - var point = { x: 0, y: 0 }; - - var matrix = this._tempMatrix; - var parentMatrix = this._tempMatrix2; - - for (var i = 0; i < gameObjects.length; i++) - { - var gameObject = gameObjects[i]; - - // 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 - if (!this.inputCandidate(gameObject, camera)) - { - continue; - } - - var px = tempPoint.x + (csx * gameObject.scrollFactorX) - csx; - var py = tempPoint.y + (csy * gameObject.scrollFactorY) - csy; - - if (gameObject.parentContainer) - { - gameObject.getWorldTransformMatrix(matrix, parentMatrix); - - matrix.applyInverse(px, py, point); - } - else - { - TransformXY(px, py, gameObject.x, gameObject.y, gameObject.rotation, gameObject.scaleX, gameObject.scaleY, point); - } - - if (this.pointWithinHitArea(gameObject, point.x, point.y)) - { - output.push(gameObject); - } - } - - return output; - }, - - /** - * Checks if the given x and y coordinate are within the hit area of the Game Object. - * - * This method assumes that the coordinate values have already been translated into the space of the Game Object. - * - * If the coordinates are within the hit area they are set into the Game Objects Input `localX` and `localY` properties. - * - * @method Phaser.Input.InputManager#pointWithinHitArea - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object to check against. - * @param {number} x - The translated x coordinate for the hit test. - * @param {number} y - The translated y coordinate for the hit test. - * - * @return {boolean} `true` if the coordinates were inside the Game Objects hit area, otherwise `false`. - */ - pointWithinHitArea: function (gameObject, x, y) - { - // Normalize the origin - x += gameObject.displayOriginX; - y += gameObject.displayOriginY; - - var input = gameObject.input; - - if (input && input.hitAreaCallback(input.hitArea, x, y, gameObject)) - { - input.localX = x; - input.localY = y; - - return true; - } - else - { - return false; - } - }, - - /** - * Checks if the given x and y coordinate are within the hit area of the Interactive Object. - * - * This method assumes that the coordinate values have already been translated into the space of the Interactive Object. - * - * If the coordinates are within the hit area they are set into the Interactive Objects Input `localX` and `localY` properties. - * - * @method Phaser.Input.InputManager#pointWithinInteractiveObject - * @since 3.0.0 - * - * @param {Phaser.Types.Input.InteractiveObject} object - The Interactive Object to check against. - * @param {number} x - The translated x coordinate for the hit test. - * @param {number} y - The translated y coordinate for the hit test. - * - * @return {boolean} `true` if the coordinates were inside the Game Objects hit area, otherwise `false`. - */ - pointWithinInteractiveObject: function (object, x, y) - { - if (!object.hitArea) - { - return false; - } - - // Normalize the origin - x += object.gameObject.displayOriginX; - y += object.gameObject.displayOriginY; - - object.localX = x; - object.localY = y; - - return object.hitAreaCallback(object.hitArea, x, y, object); - }, - - /** - * Transforms the pageX and pageY values of a Pointer into the scaled coordinate space of the Input Manager. - * - * @method Phaser.Input.InputManager#transformPointer - * @since 3.10.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to transform the values for. - * @param {number} pageX - The Page X value. - * @param {number} pageY - The Page Y value. - * @param {boolean} wasMove - Are we transforming the Pointer from a move event, or an up / down event? - */ - transformPointer: function (pointer, pageX, pageY, wasMove) - { - var p0 = pointer.position; - var p1 = pointer.prevPosition; - - // Store previous position - p1.x = p0.x; - p1.y = p0.y; - - // Translate coordinates - var x = this.scaleManager.transformX(pageX); - var y = this.scaleManager.transformY(pageY); - - var a = pointer.smoothFactor; - - if (!wasMove || a === 0) - { - // Set immediately - p0.x = x; - p0.y = y; - } - else - { - // Apply smoothing - p0.x = x * a + p1.x * (1 - a); - p0.y = y * a + p1.y * (1 - a); - } - }, - - /** - * Destroys the Input Manager and all of its systems. - * - * There is no way to recover from doing this. - * - * @method Phaser.Input.InputManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.events.removeAllListeners(); - - this.game.events.off(GameEvents.PRE_RENDER); - - if (this.keyboard) - { - this.keyboard.destroy(); - } - - if (this.mouse) - { - this.mouse.destroy(); - } - - if (this.touch) - { - this.touch.destroy(); - } - - for (var i = 0; i < this.pointers.length; i++) - { - this.pointers[i].destroy(); - } - - this.pointers = []; - this._tempHitTest = []; - this._tempMatrix.destroy(); - this.canvas = null; - this.game = null; - } - -}); - -module.exports = InputManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CONST = require('./const'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GameEvents = require('../core/events'); +var Keyboard = require('./keyboard/KeyboardManager'); +var Mouse = require('./mouse/MouseManager'); +var Pointer = require('./Pointer'); +var Touch = require('./touch/TouchManager'); +var TransformMatrix = require('../gameobjects/components/TransformMatrix'); +var TransformXY = require('../math/TransformXY'); + +/** + * @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. + */ +var InputManager = new Class({ + + initialize: + + function InputManager (game, config) + { + /** + * The Game instance that owns the Input Manager. + * A Game only maintains on instance of the Input Manager at any time. + * + * @name Phaser.Input.InputManager#game + * @type {Phaser.Game} + * @readonly + * @since 3.0.0 + */ + this.game = game; + + /** + * A reference to the global Game Scale Manager. + * Used for all bounds checks and pointer scaling. + * + * @name Phaser.Input.InputManager#scaleManager + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.0 + */ + this.scaleManager; + + /** + * The Canvas that is used for all DOM event input listeners. + * + * @name Phaser.Input.InputManager#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas; + + /** + * The Game Configuration object, as set during the game boot. + * + * @name Phaser.Input.InputManager#config + * @type {Phaser.Core.Config} + * @since 3.0.0 + */ + this.config = config; + + /** + * If set, the Input Manager will run its update loop every frame. + * + * @name Phaser.Input.InputManager#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The Event Emitter instance that the Input Manager uses to emit events from. + * + * @name Phaser.Input.InputManager#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = new EventEmitter(); + + /** + * Are any mouse or touch pointers currently over the game canvas? + * This is updated automatically by the canvas over and out handlers. + * + * @name Phaser.Input.InputManager#isOver + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + this.isOver = true; + + /** + * The default CSS cursor to be used when interacting with your game. + * + * See the `setDefaultCursor` method for more details. + * + * @name Phaser.Input.InputManager#defaultCursor + * @type {string} + * @since 3.10.0 + */ + this.defaultCursor = ''; + + /** + * A reference to the Keyboard Manager class, if enabled via the `input.keyboard` Game Config property. + * + * @name Phaser.Input.InputManager#keyboard + * @type {?Phaser.Input.Keyboard.KeyboardManager} + * @since 3.16.0 + */ + this.keyboard = (config.inputKeyboard) ? new Keyboard(this) : null; + + /** + * A reference to the Mouse Manager class, if enabled via the `input.mouse` Game Config property. + * + * @name Phaser.Input.InputManager#mouse + * @type {?Phaser.Input.Mouse.MouseManager} + * @since 3.0.0 + */ + this.mouse = (config.inputMouse) ? new Mouse(this) : null; + + /** + * A reference to the Touch Manager class, if enabled via the `input.touch` Game Config property. + * + * @name Phaser.Input.InputManager#touch + * @type {Phaser.Input.Touch.TouchManager} + * @since 3.0.0 + */ + this.touch = (config.inputTouch) ? new Touch(this) : null; + + /** + * An array of Pointers that have been added to the game. + * The first entry is reserved for the Mouse Pointer, the rest are Touch Pointers. + * + * By default there is 1 touch pointer enabled. If you need more use the `addPointer` method to start them, + * or set the `input.activePointers` property in the Game Config. + * + * @name Phaser.Input.InputManager#pointers + * @type {Phaser.Input.Pointer[]} + * @since 3.10.0 + */ + this.pointers = []; + + /** + * The number of touch objects activated and being processed each update. + * + * You can change this by either calling `addPointer` at run-time, or by + * setting the `input.activePointers` property in the Game Config. + * + * @name Phaser.Input.InputManager#pointersTotal + * @type {integer} + * @readonly + * @since 3.10.0 + */ + this.pointersTotal = config.inputActivePointers; + + if (config.inputTouch && this.pointersTotal === 1) + { + this.pointersTotal = 2; + } + + for (var i = 0; i <= this.pointersTotal; i++) + { + var pointer = new Pointer(this, i); + + pointer.smoothFactor = config.inputSmoothFactor; + + this.pointers.push(pointer); + } + + /** + * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. + * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` + * which will always map to the most recently interacted pointer. + * + * @name Phaser.Input.InputManager#mousePointer + * @type {?Phaser.Input.Pointer} + * @since 3.10.0 + */ + this.mousePointer = (config.inputMouse) ? this.pointers[0] : null; + + /** + * 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 + */ + this.activePointer = this.pointers[0]; + + /** + * If the top-most Scene in the Scene List receives an input it will stop input from + * propagating any lower down the scene list, i.e. if you have a UI Scene at the top + * and click something on it, that click will not then be passed down to any other + * Scene below. Disable this to have input events passed through all Scenes, all the time. + * + * @name Phaser.Input.InputManager#globalTopOnly + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.globalTopOnly = true; + + /** + * The time this Input Manager was last updated. + * This value is populated by the Game Step each frame. + * + * @name Phaser.Input.InputManager#time + * @type {number} + * @readonly + * @since 3.16.2 + */ + this.time = 0; + + /** + * A re-cycled point-like object to store hit test values in. + * + * @name Phaser.Input.InputManager#_tempPoint + * @type {{x:number, y:number}} + * @private + * @since 3.0.0 + */ + this._tempPoint = { x: 0, y: 0 }; + + /** + * A re-cycled array to store hit results in. + * + * @name Phaser.Input.InputManager#_tempHitTest + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this._tempHitTest = []; + + /** + * A re-cycled matrix used in hit test calculations. + * + * @name Phaser.Input.InputManager#_tempMatrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.4.0 + */ + this._tempMatrix = new TransformMatrix(); + + /** + * A re-cycled matrix used in hit test calculations. + * + * @name Phaser.Input.InputManager#_tempMatrix2 + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * An internal private var that records Scenes aborting event processing. + * + * @name Phaser.Input.InputManager#_tempSkip + * @type {boolean} + * @private + * @since 3.18.0 + */ + this._tempSkip = false; + + /** + * An internal private array that avoids needing to create a new array on every DOM mouse event. + * + * @name Phaser.Input.InputManager#mousePointerContainer + * @type {Phaser.Input.Pointer[]} + * @private + * @since 3.18.0 + */ + this.mousePointerContainer = [ this.mousePointer ]; + + game.events.once(GameEvents.BOOT, this.boot, this); + }, + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * The renderer is available by now. + * + * @method Phaser.Input.InputManager#boot + * @protected + * @fires Phaser.Input.Events#MANAGER_BOOT + * @since 3.0.0 + */ + boot: function () + { + this.canvas = this.game.canvas; + + this.scaleManager = this.game.scale; + + this.events.emit(Events.MANAGER_BOOT); + + this.game.events.on(GameEvents.PRE_RENDER, this.preRender, this); + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Internal canvas state change, called automatically by the Mouse Manager. + * + * @method Phaser.Input.InputManager#setCanvasOver + * @fires Phaser.Input.Events#GAME_OVER + * @private + * @since 3.16.0 + * + * @param {(MouseEvent|TouchEvent)} event - The DOM Event. + */ + setCanvasOver: function (event) + { + this.isOver = true; + + this.events.emit(Events.GAME_OVER, event); + }, + + /** + * Internal canvas state change, called automatically by the Mouse Manager. + * + * @method Phaser.Input.InputManager#setCanvasOut + * @fires Phaser.Input.Events#GAME_OUT + * @private + * @since 3.16.0 + * + * @param {(MouseEvent|TouchEvent)} event - The DOM Event. + */ + setCanvasOut: function (event) + { + this.isOver = false; + + this.events.emit(Events.GAME_OUT, event); + }, + + /** + * Internal update, called automatically by the Game Step right at the start. + * + * @method Phaser.Input.InputManager#preRender + * @private + * @since 3.18.0 + */ + preRender: function () + { + var time = this.game.loop.now; + var delta = this.game.loop.delta; + var scenes = this.game.scene.getScenes(true, true); + + this.time = time; + + this.events.emit(Events.MANAGER_UPDATE); + + for (var i = 0; i < scenes.length; i++) + { + var scene = scenes[i]; + + if (scene.sys.input && scene.sys.input.updatePoll(time, delta) && this.globalTopOnly) + { + // If the Scene returns true, it means it captured some input that no other Scene should get, so we bail out + return; + } + } + }, + + /** + * 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. + */ + setDefaultCursor: function (cursor) + { + this.defaultCursor = cursor; + + if (this.canvas.style.cursor !== cursor) + { + this.canvas.style.cursor = 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. + */ + setCursor: function (interactiveObject) + { + if (interactiveObject.cursor) + { + this.canvas.style.cursor = interactiveObject.cursor; + } + }, + + /** + * Called by the InputPlugin when processing over and out events. + * + * Tells the Input Manager to clear the hand cursor, if set, during its postUpdate step. + * + * @method Phaser.Input.InputManager#resetCursor + * @private + * @since 3.10.0 + * + * @param {Phaser.Types.Input.InteractiveObject} interactiveObject - The Interactive Object that called this method. + */ + resetCursor: function (interactiveObject) + { + if (interactiveObject.cursor && this.canvas) + { + this.canvas.style.cursor = this.defaultCursor; + } + }, + + /** + * Adds new Pointer objects to the Input Manager. + * + * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. + * + * You can create more either by calling this method, or by setting the `input.activePointers` property + * in the Game Config, up to a maximum of 10 pointers. + * + * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added + * via this method. + * + * @method Phaser.Input.InputManager#addPointer + * @since 3.10.0 + * + * @param {integer} [quantity=1] The number of new Pointers to create. A maximum of 10 is allowed in total. + * + * @return {Phaser.Input.Pointer[]} An array containing all of the new Pointer objects that were created. + */ + addPointer: function (quantity) + { + if (quantity === undefined) { quantity = 1; } + + var output = []; + + if (this.pointersTotal + quantity > 10) + { + quantity = 10 - this.pointersTotal; + } + + for (var i = 0; i < quantity; i++) + { + var id = this.pointers.length; + + var pointer = new Pointer(this, id); + + pointer.smoothFactor = this.config.inputSmoothFactor; + + this.pointers.push(pointer); + + this.pointersTotal++; + + output.push(pointer); + } + + return output; + }, + + /** + * Internal method that gets a list of all the active Input Plugins in the game + * and updates each of them in turn, in reverse order (top to bottom), to allow + * for DOM top-level event handling simulation. + * + * @method Phaser.Input.InputManager#updateInputPlugins + * @since 3.16.0 + * + * @param {integer} type - The type of event to process. + * @param {Phaser.Input.Pointer[]} pointers - An array of Pointers on which the event occurred. + */ + updateInputPlugins: function (type, pointers) + { + var scenes = this.game.scene.getScenes(true, true); + + this._tempSkip = false; + + for (var i = 0; i < scenes.length; i++) + { + var scene = scenes[i]; + + if (scene.sys.input) + { + var capture = scene.sys.input.update(type, pointers); + + if ((capture && this.globalTopOnly) || this._tempSkip) + { + // If the Scene returns true, or called stopPropagation, it means it captured some input that no other Scene should get, so we bail out + return; + } + } + } + }, + + // 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 + + /** + * Processes a touch start event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchStart + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchStart: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (!pointer.active) + { + pointer.touchstart(changedTouch, event); + + this.activePointer = pointer; + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_START, changed); + }, + + /** + * Processes a touch move event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchMove + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchMove: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (pointer.active && pointer.identifier === changedTouch.identifier) + { + pointer.touchmove(changedTouch, event); + + this.activePointer = pointer; + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_MOVE, changed); + }, + + // 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 + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + + /** + * Processes a touch end event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchEnd + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchEnd: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (pointer.active && pointer.identifier === changedTouch.identifier) + { + pointer.touchend(changedTouch, event); + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_END, changed); + }, + + /** + * Processes a touch cancel event, as passed in by the TouchManager. + * + * @method Phaser.Input.InputManager#onTouchCancel + * @private + * @since 3.18.0 + * + * @param {TouchEvent} event - The native DOM Touch event. + */ + onTouchCancel: function (event) + { + var pointers = this.pointers; + var changed = []; + + for (var c = 0; c < event.changedTouches.length; c++) + { + var changedTouch = event.changedTouches[c]; + + for (var i = 1; i < this.pointersTotal; i++) + { + var pointer = pointers[i]; + + if (pointer.active && pointer.identifier === changedTouch.identifier) + { + pointer.touchcancel(changedTouch, event); + + changed.push(pointer); + + break; + } + } + } + + this.updateInputPlugins(CONST.TOUCH_CANCEL, changed); + }, + + /** + * Processes a mouse down event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseDown + * @private + * @since 3.18.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onMouseDown: function (event) + { + this.mousePointer.down(event); + + this.mousePointer.updateMotion(); + + this.updateInputPlugins(CONST.MOUSE_DOWN, this.mousePointerContainer); + }, + + /** + * Processes a mouse move event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseMove + * @private + * @since 3.18.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onMouseMove: function (event) + { + this.mousePointer.move(event); + + this.mousePointer.updateMotion(); + + this.updateInputPlugins(CONST.MOUSE_MOVE, this.mousePointerContainer); + }, + + /** + * Processes a mouse up event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseUp + * @private + * @since 3.18.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onMouseUp: function (event) + { + this.mousePointer.up(event); + + this.mousePointer.updateMotion(); + + this.updateInputPlugins(CONST.MOUSE_UP, this.mousePointerContainer); + }, + + /** + * Processes a mouse wheel event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onMouseWheel + * @private + * @since 3.18.0 + * + * @param {WheelEvent} event - The native DOM Wheel event. + */ + onMouseWheel: function (event) + { + this.mousePointer.wheel(event); + + this.updateInputPlugins(CONST.MOUSE_WHEEL, this.mousePointerContainer); + }, + + /** + * Processes a pointer lock change event, as passed in by the MouseManager. + * + * @method Phaser.Input.InputManager#onPointerLockChange + * @fires Phaser.Input.Events#POINTERLOCK_CHANGE + * @private + * @since 3.19.0 + * + * @param {MouseEvent} event - The native DOM Mouse event. + */ + onPointerLockChange: function (event) + { + var isLocked = this.mouse.locked; + + this.mousePointer.locked = isLocked; + + this.events.emit(Events.POINTERLOCK_CHANGE, event, isLocked); + }, + + /** + * Checks if the given Game Object should be considered as a candidate for input or not. + * + * Checks if the Game Object has an input component that is enabled, that it will render, + * and finally, if it has a parent, that the parent parent, or any ancestor, is visible or not. + * + * @method Phaser.Input.InputManager#inputCandidate + * @private + * @since 3.10.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to test. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. + * + * @return {boolean} `true` if the Game Object should be considered for input, otherwise `false`. + */ + inputCandidate: function (gameObject, camera) + { + var input = gameObject.input; + + if (!input || !input.enabled || (!input.alwaysEnabled && !gameObject.willRender(camera))) + { + return false; + } + + var visible = true; + var parent = gameObject.parentContainer; + + if (parent) + { + do + { + if (!parent.willRender(camera)) + { + visible = false; + break; + } + + parent = parent.parentContainer; + + } while (parent); + } + + return visible; + }, + + /** + * Performs a hit test using the given Pointer and camera, against an array of interactive Game Objects. + * + * The Game Objects are culled against the camera, and then the coordinates are translated into the local camera space + * and used to determine if they fall within the remaining Game Objects hit areas or not. + * + * If nothing is matched an empty array is returned. + * + * This method is called automatically by InputPlugin.hitTestPointer and doesn't usually need to be invoked directly. + * + * @method Phaser.Input.InputManager#hitTest + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to test against. + * @param {array} gameObjects - An array of interactive Game Objects to check. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. + * @param {array} [output] - An array to store the results in. If not given, a new empty array is created. + * + * @return {array} An array of the Game Objects that were hit during this hit test. + */ + hitTest: function (pointer, gameObjects, camera, output) + { + if (output === undefined) { output = this._tempHitTest; } + + var tempPoint = this._tempPoint; + + var csx = camera.scrollX; + var csy = camera.scrollY; + + output.length = 0; + + var x = pointer.x; + var y = pointer.y; + + if (camera.resolution !== 1) + { + x += camera._x; + y += camera._y; + } + + // Stores the world point inside of tempPoint + camera.getWorldPoint(x, y, tempPoint); + + pointer.worldX = tempPoint.x; + pointer.worldY = tempPoint.y; + + var point = { x: 0, y: 0 }; + + var matrix = this._tempMatrix; + var parentMatrix = this._tempMatrix2; + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + // 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 + if (!this.inputCandidate(gameObject, camera)) + { + continue; + } + + var px = tempPoint.x + (csx * gameObject.scrollFactorX) - csx; + var py = tempPoint.y + (csy * gameObject.scrollFactorY) - csy; + + if (gameObject.parentContainer) + { + gameObject.getWorldTransformMatrix(matrix, parentMatrix); + + matrix.applyInverse(px, py, point); + } + else + { + TransformXY(px, py, gameObject.x, gameObject.y, gameObject.rotation, gameObject.scaleX, gameObject.scaleY, point); + } + + if (this.pointWithinHitArea(gameObject, point.x, point.y)) + { + output.push(gameObject); + } + } + + return output; + }, + + /** + * Checks if the given x and y coordinate are within the hit area of the Game Object. + * + * This method assumes that the coordinate values have already been translated into the space of the Game Object. + * + * If the coordinates are within the hit area they are set into the Game Objects Input `localX` and `localY` properties. + * + * @method Phaser.Input.InputManager#pointWithinHitArea + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object to check against. + * @param {number} x - The translated x coordinate for the hit test. + * @param {number} y - The translated y coordinate for the hit test. + * + * @return {boolean} `true` if the coordinates were inside the Game Objects hit area, otherwise `false`. + */ + pointWithinHitArea: function (gameObject, x, y) + { + // Normalize the origin + x += gameObject.displayOriginX; + y += gameObject.displayOriginY; + + var input = gameObject.input; + + if (input && input.hitAreaCallback(input.hitArea, x, y, gameObject)) + { + input.localX = x; + input.localY = y; + + return true; + } + else + { + return false; + } + }, + + /** + * Checks if the given x and y coordinate are within the hit area of the Interactive Object. + * + * This method assumes that the coordinate values have already been translated into the space of the Interactive Object. + * + * If the coordinates are within the hit area they are set into the Interactive Objects Input `localX` and `localY` properties. + * + * @method Phaser.Input.InputManager#pointWithinInteractiveObject + * @since 3.0.0 + * + * @param {Phaser.Types.Input.InteractiveObject} object - The Interactive Object to check against. + * @param {number} x - The translated x coordinate for the hit test. + * @param {number} y - The translated y coordinate for the hit test. + * + * @return {boolean} `true` if the coordinates were inside the Game Objects hit area, otherwise `false`. + */ + pointWithinInteractiveObject: function (object, x, y) + { + if (!object.hitArea) + { + return false; + } + + // Normalize the origin + x += object.gameObject.displayOriginX; + y += object.gameObject.displayOriginY; + + object.localX = x; + object.localY = y; + + return object.hitAreaCallback(object.hitArea, x, y, object); + }, + + /** + * Transforms the pageX and pageY values of a Pointer into the scaled coordinate space of the Input Manager. + * + * @method Phaser.Input.InputManager#transformPointer + * @since 3.10.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to transform the values for. + * @param {number} pageX - The Page X value. + * @param {number} pageY - The Page Y value. + * @param {boolean} wasMove - Are we transforming the Pointer from a move event, or an up / down event? + */ + transformPointer: function (pointer, pageX, pageY, wasMove) + { + var p0 = pointer.position; + var p1 = pointer.prevPosition; + + // Store previous position + p1.x = p0.x; + p1.y = p0.y; + + // Translate coordinates + var x = this.scaleManager.transformX(pageX); + var y = this.scaleManager.transformY(pageY); + + var a = pointer.smoothFactor; + + if (!wasMove || a === 0) + { + // Set immediately + p0.x = x; + p0.y = y; + } + else + { + // Apply smoothing + p0.x = x * a + p1.x * (1 - a); + p0.y = y * a + p1.y * (1 - a); + } + }, + + /** + * Destroys the Input Manager and all of its systems. + * + * There is no way to recover from doing this. + * + * @method Phaser.Input.InputManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.events.removeAllListeners(); + + this.game.events.off(GameEvents.PRE_RENDER); + + if (this.keyboard) + { + this.keyboard.destroy(); + } + + if (this.mouse) + { + this.mouse.destroy(); + } + + if (this.touch) + { + this.touch.destroy(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].destroy(); + } + + this.pointers = []; + this._tempHitTest = []; + this._tempMatrix.destroy(); + this.canvas = null; + this.game = null; + } + +}); + +module.exports = InputManager; diff --git a/src/input/InputPlugin.js b/src/input/InputPlugin.js index 4764d6411..33fa7920b 100644 --- a/src/input/InputPlugin.js +++ b/src/input/InputPlugin.js @@ -1,3146 +1,3146 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Circle = require('../geom/circle/Circle'); -var CircleContains = require('../geom/circle/Contains'); -var Class = require('../utils/Class'); -var CONST = require('./const'); -var CreateInteractiveObject = require('./CreateInteractiveObject'); -var CreatePixelPerfectHandler = require('./CreatePixelPerfectHandler'); -var DistanceBetween = require('../math/distance/DistanceBetween'); -var Ellipse = require('../geom/ellipse/Ellipse'); -var EllipseContains = require('../geom/ellipse/Contains'); -var Events = require('./events'); -var EventEmitter = require('eventemitter3'); -var GetFastValue = require('../utils/object/GetFastValue'); -var GEOM_CONST = require('../geom/const'); -var InputPluginCache = require('./InputPluginCache'); -var IsPlainObject = require('../utils/object/IsPlainObject'); -var PluginCache = require('../plugins/PluginCache'); -var Rectangle = require('../geom/rectangle/Rectangle'); -var RectangleContains = require('../geom/rectangle/Contains'); -var SceneEvents = require('../scene/events'); -var Triangle = require('../geom/triangle/Triangle'); -var TriangleContains = require('../geom/triangle/Contains'); - -/** - * @classdesc - * The Input Plugin belongs to a Scene and handles all input related events and operations for it. - * - * You can access it from within a Scene using `this.input`. - * - * It emits events directly. For example, you can do: - * - * ```javascript - * this.input.on('pointerdown', callback, context); - * ``` - * - * To listen for a pointer down event anywhere on the game canvas. - * - * Game Objects can be enabled for input by calling their `setInteractive` method. After which they - * will directly emit input events: - * - * ```javascript - * var sprite = this.add.sprite(x, y, texture); - * sprite.setInteractive(); - * sprite.on('pointerdown', callback, context); - * ``` - * - * There are lots of game configuration options available relating to input. - * See the [Input Config object]{@linkcode Phaser.Types.Core.InputConfig} for more details, including how to deal with Phaser - * listening for input events outside of the canvas, how to set a default number of pointers, input - * capture settings and more. - * - * Please also see the Input examples and tutorials for further information. - * - * @class InputPlugin - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Input - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - A reference to the Scene that this Input Plugin is responsible for. - */ -var InputPlugin = new Class({ - - Extends: EventEmitter, - - initialize: - - function InputPlugin (scene) - { - EventEmitter.call(this); - - /** - * A reference to the Scene that this Input Plugin is responsible for. - * - * @name Phaser.Input.InputPlugin#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene Systems class. - * - * @name Phaser.Input.InputPlugin#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * A reference to the Scene Systems Settings. - * - * @name Phaser.Input.InputPlugin#settings - * @type {Phaser.Types.Scenes.SettingsObject} - * @since 3.5.0 - */ - this.settings = scene.sys.settings; - - /** - * A reference to the Game Input Manager. - * - * @name Phaser.Input.InputPlugin#manager - * @type {Phaser.Input.InputManager} - * @since 3.0.0 - */ - this.manager = scene.sys.game.input; - - /** - * Internal event queue used for plugins only. - * - * @name Phaser.Input.InputPlugin#pluginEvents - * @type {Phaser.Events.EventEmitter} - * @private - * @since 3.10.0 - */ - this.pluginEvents = new EventEmitter(); - - /** - * If `true` this Input Plugin will process DOM input events. - * - * @name Phaser.Input.InputPlugin#enabled - * @type {boolean} - * @default true - * @since 3.5.0 - */ - this.enabled = true; - - /** - * A reference to the Scene Display List. This property is set during the `boot` method. - * - * @name Phaser.Input.InputPlugin#displayList - * @type {Phaser.GameObjects.DisplayList} - * @since 3.0.0 - */ - this.displayList; - - /** - * A reference to the Scene Cameras Manager. This property is set during the `boot` method. - * - * @name Phaser.Input.InputPlugin#cameras - * @type {Phaser.Cameras.Scene2D.CameraManager} - * @since 3.0.0 - */ - this.cameras; - - // Inject the available input plugins into this class - InputPluginCache.install(this); - - /** - * A reference to the Mouse Manager. - * - * This property is only set if Mouse support has been enabled in your Game Configuration file. - * - * If you just wish to get access to the mouse pointer, use the `mousePointer` property instead. - * - * @name Phaser.Input.InputPlugin#mouse - * @type {?Phaser.Input.Mouse.MouseManager} - * @since 3.0.0 - */ - this.mouse = this.manager.mouse; - - /** - * When set to `true` (the default) the Input Plugin will emulate DOM behavior by only emitting events from - * the top-most Game Objects in the Display List. - * - * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. - * - * @name Phaser.Input.InputPlugin#topOnly - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.topOnly = true; - - /** - * How often should the Pointers be checked? - * - * The value is a time, given in ms, and is the time that must have elapsed between game steps before - * the Pointers will be polled again. When a pointer is polled it runs a hit test to see which Game - * Objects are currently below it, or being interacted with it. - * - * Pointers will *always* be checked if they have been moved by the user, or press or released. - * - * This property only controls how often they will be polled if they have not been updated. - * You should set this if you want to have Game Objects constantly check against the pointers, even - * if the pointer didn't itself move. - * - * Set to 0 to poll constantly. Set to -1 to only poll on user movement. - * - * @name Phaser.Input.InputPlugin#pollRate - * @type {integer} - * @default -1 - * @since 3.0.0 - */ - this.pollRate = -1; - - /** - * Internal poll timer value. - * - * @name Phaser.Input.InputPlugin#_pollTimer - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._pollTimer = 0; - - var _eventData = { cancelled: false }; - - /** - * Internal event propagation callback container. - * - * @name Phaser.Input.InputPlugin#_eventContainer - * @type {Phaser.Types.Input.EventData} - * @private - * @since 3.13.0 - */ - this._eventContainer = { - stopPropagation: function () - { - _eventData.cancelled = true; - } - }; - - /** - * Internal event propagation data object. - * - * @name Phaser.Input.InputPlugin#_eventData - * @type {object} - * @private - * @since 3.13.0 - */ - this._eventData = _eventData; - - /** - * The distance, in pixels, a pointer has to move while being held down, before it thinks it is being dragged. - * - * @name Phaser.Input.InputPlugin#dragDistanceThreshold - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.dragDistanceThreshold = 0; - - /** - * The amount of time, in ms, a pointer has to be held down before it thinks it is dragging. - * - * The default polling rate is to poll only on move so once the time threshold is reached the - * drag event will not start until you move the mouse. If you want it to start immediately - * when the time threshold is reached, you must increase the polling rate by calling - * [setPollAlways]{@linkcode Phaser.Input.InputPlugin#setPollAlways} or - * [setPollRate]{@linkcode Phaser.Input.InputPlugin#setPollRate}. - * - * @name Phaser.Input.InputPlugin#dragTimeThreshold - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.dragTimeThreshold = 0; - - /** - * Used to temporarily store the results of the Hit Test - * - * @name Phaser.Input.InputPlugin#_temp - * @type {array} - * @private - * @default [] - * @since 3.0.0 - */ - this._temp = []; - - /** - * Used to temporarily store the results of the Hit Test dropZones - * - * @name Phaser.Input.InputPlugin#_tempZones - * @type {array} - * @private - * @default [] - * @since 3.0.0 - */ - this._tempZones = []; - - /** - * A list of all Game Objects that have been set to be interactive in the Scene this Input Plugin is managing. - * - * @name Phaser.Input.InputPlugin#_list - * @type {Phaser.GameObjects.GameObject[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._list = []; - - /** - * Objects waiting to be inserted to the list on the next call to 'begin'. - * - * @name Phaser.Input.InputPlugin#_pendingInsertion - * @type {Phaser.GameObjects.GameObject[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._pendingInsertion = []; - - /** - * Objects waiting to be removed from the list on the next call to 'begin'. - * - * @name Phaser.Input.InputPlugin#_pendingRemoval - * @type {Phaser.GameObjects.GameObject[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._pendingRemoval = []; - - /** - * A list of all Game Objects that have been enabled for dragging. - * - * @name Phaser.Input.InputPlugin#_draggable - * @type {Phaser.GameObjects.GameObject[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._draggable = []; - - /** - * A list of all Interactive Objects currently considered as being 'draggable' by any pointer, indexed by pointer ID. - * - * @name Phaser.Input.InputPlugin#_drag - * @type {{0:Array,1:Array,2:Array,3:Array,4:Array,5:Array,6:Array,7:Array,8:Array,9:Array,10:Array}} - * @private - * @since 3.0.0 - */ - this._drag = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; - - /** - * A array containing the dragStates, for this Scene, index by the Pointer ID. - * - * @name Phaser.Input.InputPlugin#_dragState - * @type {integer[]} - * @private - * @since 3.16.0 - */ - this._dragState = []; - - /** - * A list of all Interactive Objects currently considered as being 'over' by any pointer, indexed by pointer ID. - * - * @name Phaser.Input.InputPlugin#_over - * @type {{0:Array,1:Array,2:Array,3:Array,4:Array,5:Array,6:Array,7:Array,8:Array,9:Array,10:Array}} - * @private - * @since 3.0.0 - */ - this._over = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; - - /** - * A list of valid DOM event types. - * - * @name Phaser.Input.InputPlugin#_validTypes - * @type {string[]} - * @private - * @since 3.0.0 - */ - this._validTypes = [ 'onDown', 'onUp', 'onOver', 'onOut', 'onMove', 'onDragStart', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragLeave', 'onDragOver', 'onDrop' ]; - - /** - * Internal property that tracks frame event state. - * - * @name Phaser.Input.InputPlugin#_updatedThisFrame - * @type {boolean} - * @private - * @since 3.18.0 - */ - this._updatedThisFrame = false; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Input.InputPlugin#boot - * @fires Phaser.Input.Events#BOOT - * @private - * @since 3.5.1 - */ - boot: function () - { - this.cameras = this.systems.cameras; - - this.displayList = this.systems.displayList; - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - - // Registered input plugins listen for this - this.pluginEvents.emit(Events.BOOT); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Input.InputPlugin#start - * @fires Phaser.Input.Events#START - * @private - * @since 3.5.0 - */ - start: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.TRANSITION_START, this.transitionIn, this); - eventEmitter.on(SceneEvents.TRANSITION_OUT, this.transitionOut, this); - eventEmitter.on(SceneEvents.TRANSITION_COMPLETE, this.transitionComplete, this); - eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - - this.manager.events.on(Events.GAME_OUT, this.onGameOut, this); - this.manager.events.on(Events.GAME_OVER, this.onGameOver, this); - - this.enabled = true; - - // Populate the pointer drag states - this._dragState = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; - - // Registered input plugins listen for this - this.pluginEvents.emit(Events.START); - }, - - /** - * Game Over handler. - * - * @method Phaser.Input.InputPlugin#onGameOver - * @fires Phaser.Input.Events#GAME_OVER - * @private - * @since 3.16.2 - */ - onGameOver: function (event) - { - if (this.isActive()) - { - this.emit(Events.GAME_OVER, event.timeStamp, event); - } - }, - - /** - * Game Out handler. - * - * @method Phaser.Input.InputPlugin#onGameOut - * @fires Phaser.Input.Events#GAME_OUT - * @private - * @since 3.16.2 - */ - onGameOut: function (event) - { - if (this.isActive()) - { - this.emit(Events.GAME_OUT, event.timeStamp, event); - } - }, - - /** - * The pre-update handler is responsible for checking the pending removal and insertion lists and - * deleting old Game Objects. - * - * @method Phaser.Input.InputPlugin#preUpdate - * @private - * @fires Phaser.Input.Events#PRE_UPDATE - * @since 3.0.0 - */ - preUpdate: function () - { - // Registered input plugins listen for this - this.pluginEvents.emit(Events.PRE_UPDATE); - - var removeList = this._pendingRemoval; - var insertList = this._pendingInsertion; - - var toRemove = removeList.length; - var toInsert = insertList.length; - - if (toRemove === 0 && toInsert === 0) - { - // Quick bail - return; - } - - var current = this._list; - - // Delete old gameObjects - for (var i = 0; i < toRemove; i++) - { - var gameObject = removeList[i]; - - var index = current.indexOf(gameObject); - - if (index > -1) - { - current.splice(index, 1); - - this.clear(gameObject, true); - } - } - - // Clear the removal list - removeList.length = 0; - this._pendingRemoval.length = 0; - - // Move pendingInsertion to list (also clears pendingInsertion at the same time) - this._list = current.concat(insertList.splice(0)); - }, - - /** - * Checks to see if both this plugin and the Scene to which it belongs is active. - * - * @method Phaser.Input.InputPlugin#isActive - * @since 3.10.0 - * - * @return {boolean} `true` if the plugin and the Scene it belongs to is active. - */ - isActive: function () - { - return (this.enabled && this.scene.sys.isActive()); - }, - - /** - * 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. - */ - updatePoll: function (time, delta) - { - if (!this.isActive()) - { - return false; - } - - // The plugins should update every frame, regardless if there has been - // any DOM input events or not (such as the Gamepad and Keyboard) - this.pluginEvents.emit(Events.UPDATE, time, delta); - - // We can leave now if we've already updated once this frame via the immediate DOM event handlers - if (this._updatedThisFrame) - { - this._updatedThisFrame = false; - - return false; - } - - var i; - var manager = this.manager; - - var pointers = manager.pointers; - var pointersTotal = manager.pointersTotal; - - for (i = 0; i < pointersTotal; i++) - { - pointers[i].updateMotion(); - } - - // No point going any further if there aren't any interactive objects - if (this._list.length === 0) - { - return false; - } - - var rate = this.pollRate; - - if (rate === -1) - { - return false; - } - else if (rate > 0) - { - this._pollTimer -= delta; - - if (this._pollTimer < 0) - { - // Discard timer diff, we're ready to poll again - this._pollTimer = this.pollRate; - } - else - { - // Not enough time has elapsed since the last poll, so abort now - return false; - } - } - - // We got this far? Then we should poll for movement - var captured = false; - - for (i = 0; i < pointersTotal; i++) - { - var total = 0; - - var pointer = pointers[i]; - - // Always reset this array - this._tempZones = []; - - // _temp contains a hit tested and camera culled list of IO objects - this._temp = this.hitTestPointer(pointer); - - this.sortGameObjects(this._temp); - this.sortGameObjects(this._tempZones); - - if (this.topOnly) - { - // Only the top-most one counts now, so safely ignore the rest - if (this._temp.length) - { - this._temp.splice(1); - } - - if (this._tempZones.length) - { - this._tempZones.splice(1); - } - } - - total += this.processOverOutEvents(pointer); - - if (this.getDragState(pointer) === 2) - { - this.processDragThresholdEvent(pointer, time); - } - - if (total > 0) - { - // We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame - captured = true; - } - } - - return captured; - }, - - /** - * This method is called when a DOM Event is received by the Input Manager. It handles dispatching the events - * to relevant input enabled Game Objects in this scene. - * - * @method Phaser.Input.InputPlugin#update - * @private - * @fires Phaser.Input.Events#UPDATE - * @since 3.0.0 - * - * @param {integer} type - The type of event to process. - * @param {Phaser.Input.Pointer[]} pointers - An array of Pointers on which the event occurred. - * - * @return {boolean} `true` if this Scene has captured the input events from all other Scenes, otherwise `false`. - */ - update: function (type, pointers) - { - if (!this.isActive()) - { - return false; - } - - var pointersTotal = pointers.length; - var captured = false; - - for (var i = 0; i < pointersTotal; i++) - { - var total = 0; - var pointer = pointers[i]; - - // Always reset this array - this._tempZones = []; - - // _temp contains a hit tested and camera culled list of IO objects - this._temp = this.hitTestPointer(pointer); - - this.sortGameObjects(this._temp); - this.sortGameObjects(this._tempZones); - - if (this.topOnly) - { - // Only the top-most one counts now, so safely ignore the rest - if (this._temp.length) - { - this._temp.splice(1); - } - - if (this._tempZones.length) - { - this._tempZones.splice(1); - } - } - - switch (type) - { - case CONST.MOUSE_DOWN: - total += this.processDragDownEvent(pointer); - total += this.processDownEvents(pointer); - total += this.processOverOutEvents(pointer); - break; - - case CONST.MOUSE_UP: - total += this.processDragUpEvent(pointer); - total += this.processUpEvents(pointer); - total += this.processOverOutEvents(pointer); - break; - - case CONST.TOUCH_START: - total += this.processDragDownEvent(pointer); - total += this.processDownEvents(pointer); - total += this.processOverEvents(pointer); - break; - - case CONST.TOUCH_END: - case CONST.TOUCH_CANCEL: - total += this.processDragUpEvent(pointer); - total += this.processUpEvents(pointer); - total += this.processOutEvents(pointer); - break; - - case CONST.MOUSE_MOVE: - case CONST.TOUCH_MOVE: - total += this.processDragMoveEvent(pointer); - total += this.processMoveEvents(pointer); - total += this.processOverOutEvents(pointer); - break; - - case CONST.MOUSE_WHEEL: - total += this.processWheelEvent(pointer); - break; - } - - if (total > 0) - { - // We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame - captured = true; - } - } - - this._updatedThisFrame = true; - - return captured; - }, - - /** - * Clears a Game Object so it no longer has an Interactive Object associated with it. - * The Game Object is then queued for removal from the Input Plugin on the next update. - * - * @method Phaser.Input.InputPlugin#clear - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will have its Interactive Object removed. - * @param {boolean} [skipQueue=false] - Skip adding this Game Object into the removal queue? - * - * @return {Phaser.GameObjects.GameObject} The Game Object that had its Interactive Object removed. - */ - clear: function (gameObject, skipQueue) - { - if (skipQueue === undefined) { skipQueue = false; } - - var input = gameObject.input; - - // If GameObject.input already cleared from higher class - if (!input) - { - return; - } - - if (!skipQueue) - { - this.queueForRemoval(gameObject); - } - - input.gameObject = undefined; - input.target = undefined; - input.hitArea = undefined; - input.hitAreaCallback = undefined; - input.callbackContext = undefined; - - this.manager.resetCursor(input); - - gameObject.input = null; - - // Clear from _draggable, _drag and _over - var index = this._draggable.indexOf(gameObject); - - if (index > -1) - { - this._draggable.splice(index, 1); - } - - index = this._drag[0].indexOf(gameObject); - - if (index > -1) - { - this._drag[0].splice(index, 1); - } - - index = this._over[0].indexOf(gameObject); - - if (index > -1) - { - this._over[0].splice(index, 1); - } - - return gameObject; - }, - - /** - * Disables Input on a single Game Object. - * - * An input disabled Game Object still retains its Interactive Object component and can be re-enabled - * at any time, by passing it to `InputPlugin.enable`. - * - * @method Phaser.Input.InputPlugin#disable - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to have its input system disabled. - */ - disable: function (gameObject) - { - gameObject.input.enabled = false; - }, - - /** - * 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)} [shape] - 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} [callback] - 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 {Phaser.Input.InputPlugin} This Input Plugin. - */ - enable: function (gameObject, shape, callback, dropZone) - { - if (dropZone === undefined) { dropZone = false; } - - if (gameObject.input) - { - // If it is already has an InteractiveObject then just enable it and return - gameObject.input.enabled = true; - } - else - { - // Create an InteractiveObject and enable it - this.setHitArea(gameObject, shape, callback); - } - - if (gameObject.input && dropZone && !gameObject.input.dropZone) - { - gameObject.input.dropZone = dropZone; - } - - return this; - }, - - /** - * Takes the given Pointer and performs a hit test against it, to see which interactive Game Objects - * it is currently above. - * - * The hit test is performed against which-ever Camera the Pointer is over. If it is over multiple - * cameras, it starts checking the camera at the top of the camera list, and if nothing is found, iterates down the list. - * - * @method Phaser.Input.InputPlugin#hitTestPointer - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to check against the Game Objects. - * - * @return {Phaser.GameObjects.GameObject[]} An array of all the interactive Game Objects the Pointer was above. - */ - hitTestPointer: function (pointer) - { - var cameras = this.cameras.getCamerasBelowPointer(pointer); - - for (var c = 0; c < cameras.length; c++) - { - var camera = cameras[c]; - - // 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. - var over = this.manager.hitTest(pointer, this._list, camera); - - // Filter out the drop zones - for (var i = 0; i < over.length; i++) - { - var obj = over[i]; - - if (obj.input.dropZone) - { - this._tempZones.push(obj); - } - } - - if (over.length > 0) - { - pointer.camera = camera; - - return over; - } - } - - // 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 - - pointer.camera = cameras[0]; - - return []; - }, - - /** - * An internal method that handles the Pointer down event. - * - * @method Phaser.Input.InputPlugin#processDownEvents - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_DOWN - * @fires Phaser.Input.Events#GAMEOBJECT_DOWN - * @fires Phaser.Input.Events#POINTER_DOWN - * @fires Phaser.Input.Events#POINTER_DOWN_OUTSIDE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer being tested. - * - * @return {integer} The total number of objects interacted with. - */ - processDownEvents: function (pointer) - { - var total = 0; - var currentlyOver = this._temp; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - // Go through all objects the pointer was over and fire their events / callbacks - for (var i = 0; i < currentlyOver.length; i++) - { - var gameObject = currentlyOver[i]; - - if (!gameObject.input) - { - continue; - } - - total++; - - gameObject.emit(Events.GAMEOBJECT_POINTER_DOWN, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_DOWN, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - // If they released outside the canvas, but pressed down inside it, we'll still dispatch the event. - if (!aborted && this.manager) - { - if (pointer.downElement === this.manager.game.canvas) - { - this.emit(Events.POINTER_DOWN, pointer, currentlyOver); - } - else - { - this.emit(Events.POINTER_DOWN_OUTSIDE, pointer); - } - } - - return total; - }, - - /** - * Returns the drag state of the given Pointer for this Input Plugin. - * - * The state will be one of the following: - * - * 0 = Not dragging anything - * 1 = Primary button down and objects below, so collect a draglist - * 2 = Pointer being checked if meets drag criteria - * 3 = Pointer meets criteria, notify the draglist - * 4 = Pointer actively dragging the draglist and has moved - * 5 = Pointer actively dragging but has been released, notify draglist - * - * @method Phaser.Input.InputPlugin#getDragState - * @since 3.16.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to get the drag state for. - * - * @return {integer} The drag state of the given Pointer. - */ - getDragState: function (pointer) - { - return this._dragState[pointer.id]; - }, - - /** - * Sets the drag state of the given Pointer for this Input Plugin. - * - * The state must be one of the following values: - * - * 0 = Not dragging anything - * 1 = Primary button down and objects below, so collect a draglist - * 2 = Pointer being checked if meets drag criteria - * 3 = Pointer meets criteria, notify the draglist - * 4 = Pointer actively dragging the draglist and has moved - * 5 = Pointer actively dragging but has been released, notify draglist - * - * @method Phaser.Input.InputPlugin#setDragState - * @since 3.16.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to set the drag state for. - * @param {integer} state - The drag state value. An integer between 0 and 5. - */ - setDragState: function (pointer, state) - { - this._dragState[pointer.id] = state; - }, - - /** - * 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. - */ - processDragThresholdEvent: function (pointer, time) - { - var passed = false; - var timeThreshold = this.dragTimeThreshold; - var distanceThreshold = this.dragDistanceThreshold; - - if (distanceThreshold > 0 && DistanceBetween(pointer.x, pointer.y, pointer.downX, pointer.downY) >= distanceThreshold) - { - // It has moved far enough to be considered a drag - passed = true; - } - else if (timeThreshold > 0 && (time >= pointer.downTime + timeThreshold)) - { - // It has been held down long enough to be considered a drag - passed = true; - } - - if (passed) - { - this.setDragState(pointer, 3); - - return this.processDragStartList(pointer); - } - }, - - /** - * Processes the drag list for the given pointer and dispatches the start events for each object on it. - * - * @method Phaser.Input.InputPlugin#processDragStartList - * @private - * @fires Phaser.Input.Events#DRAG_START - * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_START - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. - * - * @return {integer} The number of items that DRAG_START was called on. - */ - processDragStartList: function (pointer) - { - // 3 = Pointer meets criteria and is freshly down, notify the draglist - if (this.getDragState(pointer) !== 3) - { - return 0; - } - - var list = this._drag[pointer.id]; - - for (var i = 0; i < list.length; i++) - { - var gameObject = list[i]; - - var input = gameObject.input; - - input.dragState = 2; - - input.dragStartX = gameObject.x; - input.dragStartY = gameObject.y; - - input.dragStartXGlobal = pointer.x; - input.dragStartYGlobal = pointer.y; - - input.dragX = input.dragStartXGlobal - input.dragStartX; - input.dragY = input.dragStartYGlobal - input.dragStartY; - - gameObject.emit(Events.GAMEOBJECT_DRAG_START, pointer, input.dragX, input.dragY); - - this.emit(Events.DRAG_START, pointer, gameObject); - } - - this.setDragState(pointer, 4); - - return list.length; - }, - - /** - * Processes a 'drag down' event for the given pointer. Checks the pointer state, builds-up the drag list - * and prepares them all for interaction. - * - * @method Phaser.Input.InputPlugin#processDragDownEvent - * @private - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. - * - * @return {integer} The number of items that were collected on the drag list. - */ - processDragDownEvent: function (pointer) - { - var currentlyOver = this._temp; - - if (this._draggable.length === 0 || currentlyOver.length === 0 || !pointer.primaryDown || this.getDragState(pointer) !== 0) - { - // There are no draggable items, no over items or the pointer isn't down, so let's not even bother going further - return 0; - } - - // 1 = Primary button down and objects below, so collect a draglist - this.setDragState(pointer, 1); - - // Get draggable objects, sort them, pick the top (or all) and store them somewhere - var draglist = []; - - for (var i = 0; i < currentlyOver.length; i++) - { - var gameObject = currentlyOver[i]; - - if (gameObject.input.draggable && (gameObject.input.dragState === 0)) - { - draglist.push(gameObject); - } - } - - if (draglist.length === 0) - { - this.setDragState(pointer, 0); - - return 0; - } - else if (draglist.length > 1) - { - this.sortGameObjects(draglist); - - if (this.topOnly) - { - draglist.splice(1); - } - } - - // draglist now contains all potential candidates for dragging - this._drag[pointer.id] = draglist; - - if (this.dragDistanceThreshold === 0 && this.dragTimeThreshold === 0) - { - // No drag criteria, so snap immediately to mode 3 - this.setDragState(pointer, 3); - - return this.processDragStartList(pointer); - } - else - { - // Check the distance / time on the next event - this.setDragState(pointer, 2); - - return 0; - } - }, - - /** - * Processes a 'drag move' event for the given pointer. - * - * @method Phaser.Input.InputPlugin#processDragMoveEvent - * @private - * @fires Phaser.Input.Events#DRAG_ENTER - * @fires Phaser.Input.Events#DRAG - * @fires Phaser.Input.Events#DRAG_LEAVE - * @fires Phaser.Input.Events#DRAG_OVER - * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_ENTER - * @fires Phaser.Input.Events#GAMEOBJECT_DRAG - * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_LEAVE - * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_OVER - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. - * - * @return {integer} The number of items that were updated by this drag event. - */ - processDragMoveEvent: function (pointer) - { - // 2 = Pointer being checked if meets drag criteria - if (this.getDragState(pointer) === 2) - { - this.processDragThresholdEvent(pointer, this.manager.game.loop.now); - } - - if (this.getDragState(pointer) !== 4) - { - return 0; - } - - // 4 = Pointer actively dragging the draglist and has moved - var dropZones = this._tempZones; - - var list = this._drag[pointer.id]; - - for (var i = 0; i < list.length; i++) - { - var gameObject = list[i]; - - var input = gameObject.input; - - var target = input.target; - - // If this GO has a target then let's check it - if (target) - { - var index = dropZones.indexOf(target); - - // Got a target, are we still over it? - if (index === 0) - { - // We're still over it, and it's still the top of the display list, phew ... - gameObject.emit(Events.GAMEOBJECT_DRAG_OVER, pointer, target); - - this.emit(Events.DRAG_OVER, pointer, gameObject, target); - } - else if (index > 0) - { - // Still over it but it's no longer top of the display list (targets must always be at the top) - gameObject.emit(Events.GAMEOBJECT_DRAG_LEAVE, pointer, target); - - this.emit(Events.DRAG_LEAVE, pointer, gameObject, target); - - input.target = dropZones[0]; - - target = input.target; - - gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); - - this.emit(Events.DRAG_ENTER, pointer, gameObject, target); - } - else - { - // Nope, we've moved on (or the target has!), leave the old target - gameObject.emit(Events.GAMEOBJECT_DRAG_LEAVE, pointer, target); - - this.emit(Events.DRAG_LEAVE, pointer, gameObject, target); - - // Anything new to replace it? - // Yup! - if (dropZones[0]) - { - input.target = dropZones[0]; - - target = input.target; - - gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); - - this.emit(Events.DRAG_ENTER, pointer, gameObject, target); - } - else - { - // Nope - input.target = null; - } - } - } - else if (!target && dropZones[0]) - { - input.target = dropZones[0]; - - target = input.target; - - gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); - - this.emit(Events.DRAG_ENTER, pointer, gameObject, target); - } - - var dragX; - var dragY; - - if (!gameObject.parentContainer) - { - dragX = pointer.x - input.dragX; - dragY = pointer.y - input.dragY; - } - else - { - var dx = pointer.x - input.dragStartXGlobal; - var dy = pointer.y - input.dragStartYGlobal; - - var rotation = gameObject.getParentRotation(); - - var dxRotated = dx * Math.cos(rotation) + dy * Math.sin(rotation); - var dyRotated = dy * Math.cos(rotation) - dx * Math.sin(rotation); - - dxRotated *= (1 / gameObject.parentContainer.scaleX); - dyRotated *= (1 / gameObject.parentContainer.scaleY); - - dragX = dxRotated + input.dragStartX; - dragY = dyRotated + input.dragStartY; - } - - gameObject.emit(Events.GAMEOBJECT_DRAG, pointer, dragX, dragY); - - this.emit(Events.DRAG, pointer, gameObject, dragX, dragY); - } - - return list.length; - }, - - /** - * Processes a 'drag down' event for the given pointer. Checks the pointer state, builds-up the drag list - * and prepares them all for interaction. - * - * @method Phaser.Input.InputPlugin#processDragUpEvent - * @fires Phaser.Input.Events#DRAG_END - * @fires Phaser.Input.Events#DROP - * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_END - * @fires Phaser.Input.Events#GAMEOBJECT_DROP - * @private - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. - * - * @return {integer} The number of items that were updated by this drag event. - */ - processDragUpEvent: function (pointer) - { - // 5 = Pointer was actively dragging but has been released, notify draglist - var list = this._drag[pointer.id]; - - for (var i = 0; i < list.length; i++) - { - var gameObject = list[i]; - - var input = gameObject.input; - - if (input && input.dragState === 2) - { - input.dragState = 0; - - input.dragX = input.localX - gameObject.displayOriginX; - input.dragY = input.localY - gameObject.displayOriginY; - - var dropped = false; - - var target = input.target; - - if (target) - { - gameObject.emit(Events.GAMEOBJECT_DROP, pointer, target); - - this.emit(Events.DROP, pointer, gameObject, target); - - input.target = null; - - dropped = true; - } - - // And finally the dragend event - - if (gameObject.input) - { - gameObject.emit(Events.GAMEOBJECT_DRAG_END, pointer, input.dragX, input.dragY, dropped); - - this.emit(Events.DRAG_END, pointer, gameObject, dropped); - } - } - } - - this.setDragState(pointer, 0); - - list.splice(0); - - return 0; - }, - - /** - * An internal method that handles the Pointer movement event. - * - * @method Phaser.Input.InputPlugin#processMoveEvents - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_MOVE - * @fires Phaser.Input.Events#GAMEOBJECT_MOVE - * @fires Phaser.Input.Events#POINTER_MOVE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. - * - * @return {integer} The total number of objects interacted with. - */ - processMoveEvents: function (pointer) - { - var total = 0; - var currentlyOver = this._temp; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - // Go through all objects the pointer was over and fire their events / callbacks - for (var i = 0; i < currentlyOver.length; i++) - { - var gameObject = currentlyOver[i]; - - if (!gameObject.input) - { - continue; - } - - total++; - - gameObject.emit(Events.GAMEOBJECT_POINTER_MOVE, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_MOVE, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - if (this.topOnly) - { - break; - } - } - - if (!aborted) - { - this.emit(Events.POINTER_MOVE, pointer, currentlyOver); - } - - return total; - }, - - /** - * An internal method that handles a mouse wheel event. - * - * @method Phaser.Input.InputPlugin#processWheelEvent - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_WHEEL - * @fires Phaser.Input.Events#GAMEOBJECT_WHEEL - * @fires Phaser.Input.Events#POINTER_WHEEL - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. - * - * @return {integer} The total number of objects interacted with. - */ - processWheelEvent: function (pointer) - { - var total = 0; - var currentlyOver = this._temp; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - var dx = pointer.deltaX; - var dy = pointer.deltaY; - var dz = pointer.deltaZ; - - // Go through all objects the pointer was over and fire their events / callbacks - for (var i = 0; i < currentlyOver.length; i++) - { - var gameObject = currentlyOver[i]; - - if (!gameObject.input) - { - continue; - } - - total++; - - gameObject.emit(Events.GAMEOBJECT_POINTER_WHEEL, pointer, dx, dy, dz, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_WHEEL, pointer, gameObject, dx, dy, dz, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - if (!aborted) - { - this.emit(Events.POINTER_WHEEL, pointer, currentlyOver, dx, dy, dz); - } - - return total; - }, - - /** - * An internal method that handles the Pointer over events. - * This is called when a touch input hits the canvas, having previously been off of it. - * - * @method Phaser.Input.InputPlugin#processOverEvents - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OVER - * @fires Phaser.Input.Events#GAMEOBJECT_OVER - * @fires Phaser.Input.Events#POINTER_OVER - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. - * - * @return {integer} The total number of objects interacted with. - */ - processOverEvents: function (pointer) - { - var currentlyOver = this._temp; - - var totalInteracted = 0; - - var total = currentlyOver.length; - - var justOver = []; - - if (total > 0) - { - var manager = this.manager; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - for (var i = 0; i < total; i++) - { - var gameObject = currentlyOver[i]; - - if (!gameObject.input) - { - continue; - } - - justOver.push(gameObject); - - manager.setCursor(gameObject.input); - - gameObject.emit(Events.GAMEOBJECT_POINTER_OVER, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); - - totalInteracted++; - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_OVER, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - if (!aborted) - { - this.emit(Events.POINTER_OVER, pointer, justOver); - } - } - - // Then sort it into display list order - this._over[pointer.id] = justOver; - - return totalInteracted; - }, - - /** - * An internal method that handles the Pointer out events. - * This is called when a touch input leaves the canvas, as it can never be 'over' in this case. - * - * @method Phaser.Input.InputPlugin#processOutEvents - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OUT - * @fires Phaser.Input.Events#GAMEOBJECT_OUT - * @fires Phaser.Input.Events#POINTER_OUT - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. - * - * @return {integer} The total number of objects interacted with. - */ - processOutEvents: function (pointer) - { - var previouslyOver = this._over[pointer.id]; - - var totalInteracted = 0; - - var total = previouslyOver.length; - - if (total > 0) - { - var manager = this.manager; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - this.sortGameObjects(previouslyOver); - - for (var i = 0; i < total; i++) - { - var gameObject = previouslyOver[i]; - - // Call onOut for everything in the previouslyOver array - for (i = 0; i < total; i++) - { - gameObject = previouslyOver[i]; - - if (!gameObject.input) - { - continue; - } - - manager.resetCursor(gameObject.input); - - gameObject.emit(Events.GAMEOBJECT_POINTER_OUT, pointer, _eventContainer); - - totalInteracted++; - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_OUT, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - if (!aborted) - { - this.emit(Events.POINTER_OUT, pointer, previouslyOver); - } - } - - this._over[pointer.id] = []; - } - - return totalInteracted; - }, - - /** - * An internal method that handles the Pointer over and out events. - * - * @method Phaser.Input.InputPlugin#processOverOutEvents - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OVER - * @fires Phaser.Input.Events#GAMEOBJECT_OVER - * @fires Phaser.Input.Events#POINTER_OVER - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OUT - * @fires Phaser.Input.Events#GAMEOBJECT_OUT - * @fires Phaser.Input.Events#POINTER_OUT - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. - * - * @return {integer} The total number of objects interacted with. - */ - processOverOutEvents: function (pointer) - { - var currentlyOver = this._temp; - - var i; - var gameObject; - var justOut = []; - var justOver = []; - var stillOver = []; - var previouslyOver = this._over[pointer.id]; - var currentlyDragging = this._drag[pointer.id]; - - var manager = this.manager; - - // 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 - - for (i = 0; i < previouslyOver.length; i++) - { - gameObject = previouslyOver[i]; - - if (currentlyOver.indexOf(gameObject) === -1 && currentlyDragging.indexOf(gameObject) === -1) - { - // Not in the currentlyOver array, so must be outside of this object now - justOut.push(gameObject); - } - else - { - // In the currentlyOver array - stillOver.push(gameObject); - } - } - - // 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 - for (i = 0; i < currentlyOver.length; i++) - { - gameObject = currentlyOver[i]; - - // Is this newly over? - - if (previouslyOver.indexOf(gameObject) === -1) - { - justOver.push(gameObject); - } - } - - // By this point the arrays are filled, so now we can process what happened... - - // Process the Just Out objects - var total = justOut.length; - - var totalInteracted = 0; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - if (total > 0) - { - this.sortGameObjects(justOut); - - // Call onOut for everything in the justOut array - for (i = 0; i < total; i++) - { - gameObject = justOut[i]; - - if (!gameObject.input) - { - continue; - } - - // Reset cursor before we emit the event, in case they want to change it during the event - manager.resetCursor(gameObject.input); - - gameObject.emit(Events.GAMEOBJECT_POINTER_OUT, pointer, _eventContainer); - - totalInteracted++; - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_OUT, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - if (!aborted) - { - this.emit(Events.POINTER_OUT, pointer, justOut); - } - } - - // Process the Just Over objects - total = justOver.length; - - _eventData.cancelled = false; - - aborted = false; - - if (total > 0) - { - this.sortGameObjects(justOver); - - // Call onOver for everything in the justOver array - for (i = 0; i < total; i++) - { - gameObject = justOver[i]; - - if (!gameObject.input) - { - continue; - } - - // Set cursor before we emit the event, in case they want to change it during the event - manager.setCursor(gameObject.input); - - gameObject.emit(Events.GAMEOBJECT_POINTER_OVER, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); - - totalInteracted++; - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_OVER, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - if (!aborted) - { - this.emit(Events.POINTER_OVER, pointer, justOver); - } - } - - // Add the contents of justOver to the previously over array - previouslyOver = stillOver.concat(justOver); - - // Then sort it into display list order - this._over[pointer.id] = this.sortGameObjects(previouslyOver); - - return totalInteracted; - }, - - /** - * An internal method that handles the Pointer up events. - * - * @method Phaser.Input.InputPlugin#processUpEvents - * @private - * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_UP - * @fires Phaser.Input.Events#GAMEOBJECT_UP - * @fires Phaser.Input.Events#POINTER_UP - * @fires Phaser.Input.Events#POINTER_UP_OUTSIDE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. - * - * @return {integer} The total number of objects interacted with. - */ - processUpEvents: function (pointer) - { - var currentlyOver = this._temp; - - var _eventData = this._eventData; - var _eventContainer = this._eventContainer; - - _eventData.cancelled = false; - - var aborted = false; - - // Go through all objects the pointer was over and fire their events / callbacks - for (var i = 0; i < currentlyOver.length; i++) - { - var gameObject = currentlyOver[i]; - - if (!gameObject.input) - { - continue; - } - - gameObject.emit(Events.GAMEOBJECT_POINTER_UP, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - - this.emit(Events.GAMEOBJECT_UP, pointer, gameObject, _eventContainer); - - if (_eventData.cancelled || !gameObject.input) - { - aborted = true; - break; - } - } - - // If they released outside the canvas, but pressed down inside it, we'll still dispatch the event. - if (!aborted && this.manager) - { - if (pointer.upElement === this.manager.game.canvas) - { - this.emit(Events.POINTER_UP, pointer, currentlyOver); - } - else - { - this.emit(Events.POINTER_UP_OUTSIDE, pointer); - } - } - - return currentlyOver.length; - }, - - /** - * Queues a Game Object for insertion into this Input Plugin on the next update. - * - * @method Phaser.Input.InputPlugin#queueForInsertion - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - queueForInsertion: function (child) - { - if (this._pendingInsertion.indexOf(child) === -1 && this._list.indexOf(child) === -1) - { - this._pendingInsertion.push(child); - } - - return this; - }, - - /** - * Queues a Game Object for removal from this Input Plugin on the next update. - * - * @method Phaser.Input.InputPlugin#queueForRemoval - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object to remove. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - queueForRemoval: function (child) - { - this._pendingRemoval.push(child); - - return this; - }, - - /** - * Sets the draggable state of the given array of Game Objects. - * - * They can either be set to be draggable, or can have their draggable state removed by passing `false`. - * - * A Game Object will not fire drag events unless it has been specifically enabled for drag. - * - * @method Phaser.Input.InputPlugin#setDraggable - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to change the draggable state on. - * @param {boolean} [value=true] - Set to `true` if the Game Objects should be made draggable, `false` if they should be unset. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setDraggable: function (gameObjects, value) - { - if (value === undefined) { value = true; } - - if (!Array.isArray(gameObjects)) - { - gameObjects = [ gameObjects ]; - } - - for (var i = 0; i < gameObjects.length; i++) - { - var gameObject = gameObjects[i]; - - gameObject.input.draggable = value; - - var index = this._draggable.indexOf(gameObject); - - if (value && index === -1) - { - this._draggable.push(gameObject); - } - else if (!value && index > -1) - { - this._draggable.splice(index, 1); - } - } - - return this; - }, - - /** - * Creates a function that can be passed to `setInteractive`, `enable` or `setHitArea` that will handle - * pixel-perfect input detection on an Image or Sprite based Game Object, or any custom class that extends them. - * - * The following will create a sprite that is clickable on any pixel that has an alpha value >= 1. - * - * ```javascript - * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect()); - * ``` - * - * The following will create a sprite that is clickable on any pixel that has an alpha value >= 150. - * - * ```javascript - * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect(150)); - * ``` - * - * Once you have made an Interactive Object pixel perfect it impacts all input related events for it: down, up, - * dragstart, drag, etc. - * - * As a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from - * the given coordinates and checking its color values. This is an expensive process, so should only be enabled on - * Game Objects that really need it. - * - * You cannot make non-texture based Game Objects pixel perfect. So this will not work on Graphics, BitmapText, - * Render Textures, Text, Tilemaps, Containers or Particles. - * - * @method Phaser.Input.InputPlugin#makePixelPerfect - * @since 3.10.0 - * - * @param {integer} [alphaTolerance=1] - The alpha level that the pixel should be above to be included as a successful interaction. - * - * @return {function} A Pixel Perfect Handler for use as a hitArea shape callback. - */ - makePixelPerfect: function (alphaTolerance) - { - if (alphaTolerance === undefined) { alphaTolerance = 1; } - - var textureManager = this.systems.textures; - - return CreatePixelPerfectHandler(textureManager, alphaTolerance); - }, - - /** - * 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`. - * - * @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|any)} [shape] - 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} [callback] - The 'contains' function to invoke to check if the pointer is within the hit area. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setHitArea: function (gameObjects, shape, callback) - { - if (shape === undefined) - { - return this.setHitAreaFromTexture(gameObjects); - } - - if (!Array.isArray(gameObjects)) - { - gameObjects = [ gameObjects ]; - } - - var draggable = false; - var dropZone = false; - var cursor = false; - var useHandCursor = false; - var pixelPerfect = false; - var customHitArea = true; - - // Config object? - if (IsPlainObject(shape)) - { - var config = shape; - - shape = GetFastValue(config, 'hitArea', null); - callback = GetFastValue(config, 'hitAreaCallback', null); - draggable = GetFastValue(config, 'draggable', false); - dropZone = GetFastValue(config, 'dropZone', false); - cursor = GetFastValue(config, 'cursor', false); - useHandCursor = GetFastValue(config, 'useHandCursor', false); - - pixelPerfect = GetFastValue(config, 'pixelPerfect', false); - var alphaTolerance = GetFastValue(config, 'alphaTolerance', 1); - - if (pixelPerfect) - { - shape = {}; - callback = this.makePixelPerfect(alphaTolerance); - } - - // Still no hitArea or callback? - if (!shape || !callback) - { - this.setHitAreaFromTexture(gameObjects); - customHitArea = false; - } - } - else if (typeof shape === 'function' && !callback) - { - callback = shape; - shape = {}; - } - - for (var i = 0; i < gameObjects.length; i++) - { - var gameObject = gameObjects[i]; - - if (pixelPerfect && gameObject.type === 'Container') - { - console.warn('Cannot pixelPerfect test a Container. Use a custom callback.'); - continue; - } - - var io = (!gameObject.input) ? CreateInteractiveObject(gameObject, shape, callback) : gameObject.input; - - io.customHitArea = customHitArea; - io.dropZone = dropZone; - io.cursor = (useHandCursor) ? 'pointer' : cursor; - - gameObject.input = io; - - if (draggable) - { - this.setDraggable(gameObject); - } - - this.queueForInsertion(gameObject); - } - - return this; - }, - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Circle` shape, using - * the given coordinates and radius to control its position and size. - * - * @method Phaser.Input.InputPlugin#setHitAreaCircle - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a circle hit area. - * @param {number} x - The center of the circle. - * @param {number} y - The center of the circle. - * @param {number} radius - The radius of the circle. - * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Circle.Contains. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setHitAreaCircle: function (gameObjects, x, y, radius, callback) - { - if (callback === undefined) { callback = CircleContains; } - - var shape = new Circle(x, y, radius); - - return this.setHitArea(gameObjects, shape, callback); - }, - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Ellipse` shape, using - * the given coordinates and dimensions to control its position and size. - * - * @method Phaser.Input.InputPlugin#setHitAreaEllipse - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having an ellipse hit area. - * @param {number} x - The center of the ellipse. - * @param {number} y - The center of the ellipse. - * @param {number} width - The width of the ellipse. - * @param {number} height - The height of the ellipse. - * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Ellipse.Contains. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setHitAreaEllipse: function (gameObjects, x, y, width, height, callback) - { - if (callback === undefined) { callback = EllipseContains; } - - var shape = new Ellipse(x, y, width, height); - - return this.setHitArea(gameObjects, shape, callback); - }, - - /** - * 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 an ellipse hit area. - * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setHitAreaFromTexture: function (gameObjects, callback) - { - if (callback === undefined) { callback = RectangleContains; } - - if (!Array.isArray(gameObjects)) - { - gameObjects = [ gameObjects ]; - } - - for (var i = 0; i < gameObjects.length; i++) - { - var gameObject = gameObjects[i]; - - var frame = gameObject.frame; - - var width = 0; - var height = 0; - - if (gameObject.width) - { - width = gameObject.width; - height = gameObject.height; - } - else if (frame) - { - width = frame.realWidth; - height = frame.realHeight; - } - - if (gameObject.type === 'Container' && (width === 0 || height === 0)) - { - console.warn('Container.setInteractive must specify a Shape or call setSize() first'); - continue; - } - - if (width !== 0 && height !== 0) - { - gameObject.input = CreateInteractiveObject(gameObject, new Rectangle(0, 0, width, height), callback); - - this.queueForInsertion(gameObject); - } - } - - return this; - }, - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Rectangle` shape, using - * the given coordinates and dimensions to control its position and size. - * - * @method Phaser.Input.InputPlugin#setHitAreaRectangle - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a rectangular hit area. - * @param {number} x - The top-left of the rectangle. - * @param {number} y - The top-left of the rectangle. - * @param {number} width - The width of the rectangle. - * @param {number} height - The height of the rectangle. - * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setHitAreaRectangle: function (gameObjects, x, y, width, height, callback) - { - if (callback === undefined) { callback = RectangleContains; } - - var shape = new Rectangle(x, y, width, height); - - return this.setHitArea(gameObjects, shape, callback); - }, - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Triangle` shape, using - * the given coordinates to control the position of its points. - * - * @method Phaser.Input.InputPlugin#setHitAreaTriangle - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a triangular hit area. - * @param {number} x1 - The x coordinate of the first point of the triangle. - * @param {number} y1 - The y coordinate of the first point of the triangle. - * @param {number} x2 - The x coordinate of the second point of the triangle. - * @param {number} y2 - The y coordinate of the second point of the triangle. - * @param {number} x3 - The x coordinate of the third point of the triangle. - * @param {number} y3 - The y coordinate of the third point of the triangle. - * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Triangle.Contains. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setHitAreaTriangle: function (gameObjects, x1, y1, x2, y2, x3, y3, callback) - { - if (callback === undefined) { callback = TriangleContains; } - - var shape = new Triangle(x1, y1, x2, y2, x3, y3); - - return this.setHitArea(gameObjects, shape, callback); - }, - - /** - * Creates an Input Debug Shape for the given Game Object. - * - * The Game Object must have _already_ been enabled for input prior to calling this method. - * - * This is intended to assist you during development and debugging. - * - * Debug Shapes can only be created for Game Objects that are using standard Phaser Geometry for input, - * including: Circle, Ellipse, Line, Polygon, Rectangle and Triangle. - * - * Game Objects that are using their automatic hit areas are using Rectangles by default, so will also work. - * - * The Debug Shape is created and added to the display list and is then kept in sync with the Game Object - * it is connected with. Should you need to modify it yourself, such as to hide it, you can access it via - * the Game Object property: `GameObject.input.hitAreaDebug`. - * - * Calling this method on a Game Object that already has a Debug Shape will first destroy the old shape, - * before creating a new one. If you wish to remove the Debug Shape entirely, you should call the - * method `InputPlugin.removeDebug`. - * - * Note that the debug shape will only show the outline of the input area. If the input test is using a - * pixel perfect check, for example, then this is not displayed. If you are using a custom shape, that - * doesn't extend one of the base Phaser Geometry objects, as your hit area, then this method will not - * work. - * - * @method Phaser.Input.InputPlugin#enableDebug - * @since 3.19.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to create the input debug shape for. - * @param {number} [color=0x00ff00] - The outline color of the debug shape. - * - * @return {Phaser.Input.InputPlugin} This Input Plugin. - */ - enableDebug: function (gameObject, color) - { - if (color === undefined) { color = 0x00ff00; } - - var input = gameObject.input; - - if (!input || !input.hitArea) - { - return this; - } - - var shape = input.hitArea; - var shapeType = shape.type; - var debug = input.hitAreaDebug; - var factory = this.systems.add; - var updateList = this.systems.updateList; - - if (debug) - { - updateList.remove(debug); - - debug.destroy(); - - debug = null; - } - - var offsetx = 0; - var offsety = 0; - switch (shapeType) - { - case GEOM_CONST.CIRCLE: - debug = factory.arc(0, 0, shape.radius); - offsetx = shape.x - shape.radius; - offsety = shape.y - shape.radius; - break; - - case GEOM_CONST.ELLIPSE: - debug = factory.ellipse(0, 0, shape.width, shape.height); - offsetx = shape.x - shape.width / 2; - offsety = shape.y - shape.height / 2; - break; - - case GEOM_CONST.LINE: - debug = factory.line(0, 0, shape.x1, shape.y1, shape.x2, shape.y2); - break; - - case GEOM_CONST.POLYGON: - debug = factory.polygon(0, 0, shape.points); - break; - - case GEOM_CONST.RECTANGLE: - debug = factory.rectangle(0, 0, shape.width, shape.height); - offsetx = shape.x; - offsety = shape.y; - break; - - case GEOM_CONST.TRIANGLE: - debug = factory.triangle(0, 0, shape.x1, shape.y1, shape.x2, shape.y2, shape.x3, shape.y3); - break; - } - - if (debug) - { - debug.isFilled = false; - - debug.preUpdate = function () - { - debug.setStrokeStyle(1 / gameObject.scale, color); - - debug.setDisplayOrigin(gameObject.displayOriginX, gameObject.displayOriginY); - debug.setRotation(gameObject.rotation); - debug.setScale(gameObject.scaleX, gameObject.scaleY); - debug.setPosition(gameObject.x + offsetx, gameObject.y + offsety); - debug.setScrollFactor(gameObject.scrollFactorX, gameObject.scrollFactorY); - }; - - updateList.add(debug); - - input.hitAreaDebug = debug; - } - - return this; - }, - - /** - * Removes an Input Debug Shape from the given Game Object. - * - * The shape is destroyed immediately and the `hitAreaDebug` property is set to `null`. - * - * @method Phaser.Input.InputPlugin#removeDebug - * @since 3.19.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to remove the input debug shape from. - * - * @return {Phaser.Input.InputPlugin} This Input Plugin. - */ - removeDebug: function (gameObject) - { - var input = gameObject.input; - - if (input && input.hitAreaDebug) - { - var debug = input.hitAreaDebug; - - this.systems.updateList.remove(debug); - - debug.destroy(); - - input.hitAreaDebug = null; - } - - return this; - }, - - /** - * Sets the Pointers to always poll. - * - * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, - * or being interacted with it, regardless if the Pointer has actually moved or not. - * - * You should enable this if you want objects in your game to fire over / out events, and the objects - * are constantly moving, but the pointer may not have. Polling every frame has additional computation - * costs, especially if there are a large number of interactive objects in your game. - * - * @method Phaser.Input.InputPlugin#setPollAlways - * @since 3.0.0 - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setPollAlways: function () - { - return this.setPollRate(0); - }, - - /** - * Sets the Pointers to only poll when they are moved or updated. - * - * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, - * or being interacted with it. - * - * @method Phaser.Input.InputPlugin#setPollOnMove - * @since 3.0.0 - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setPollOnMove: function () - { - return this.setPollRate(-1); - }, - - /** - * Sets the poll rate value. This is the amount of time that should have elapsed before a pointer - * will be polled again. See the `setPollAlways` and `setPollOnMove` methods. - * - * @method Phaser.Input.InputPlugin#setPollRate - * @since 3.0.0 - * - * @param {number} value - The amount of time, in ms, that should elapsed before re-polling the pointers. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setPollRate: function (value) - { - this.pollRate = value; - this._pollTimer = 0; - - return this; - }, - - /** - * When set to `true` the global Input Manager will emulate DOM behavior by only emitting events from - * the top-most Scene in the Scene List. By default, if a Scene receives an input event it will then stop the event - * from flowing down to any Scenes below it in the Scene list. To disable this behavior call this method with `false`. - * - * @method Phaser.Input.InputPlugin#setGlobalTopOnly - * @since 3.0.0 - * - * @param {boolean} value - Set to `true` to stop processing input events on the Scene that receives it, or `false` to let the event continue down the Scene list. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setGlobalTopOnly: function (value) - { - this.manager.globalTopOnly = value; - - return this; - }, - - /** - * When set to `true` this Input Plugin will emulate DOM behavior by only emitting events from - * the top-most Game Objects in the Display List. - * - * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. - * - * @method Phaser.Input.InputPlugin#setTopOnly - * @since 3.0.0 - * - * @param {boolean} value - `true` to only include the top-most Game Object, or `false` to include all Game Objects in a hit test. - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - setTopOnly: function (value) - { - this.topOnly = value; - - return this; - }, - - /** - * Given an array of Game Objects, sort the array and return it, so that the objects are in depth index order - * with the lowest at the bottom. - * - * @method Phaser.Input.InputPlugin#sortGameObjects - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject[]} gameObjects - An array of Game Objects to be sorted. - * - * @return {Phaser.GameObjects.GameObject[]} The sorted array of Game Objects. - */ - sortGameObjects: function (gameObjects) - { - if (gameObjects.length < 2) - { - return gameObjects; - } - - this.scene.sys.depthSort(); - - return gameObjects.sort(this.sortHandlerGO.bind(this)); - }, - - /** - * Return the child lowest down the display list (with the smallest index) - * Will iterate through all parent containers, if present. - * - * @method Phaser.Input.InputPlugin#sortHandlerGO - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} childA - The first Game Object to compare. - * @param {Phaser.GameObjects.GameObject} childB - The second Game Object to compare. - * - * @return {integer} Returns either a negative or positive integer, or zero if they match. - */ - sortHandlerGO: function (childA, childB) - { - if (!childA.parentContainer && !childB.parentContainer) - { - // Quick bail out when neither child has a container - return this.displayList.getIndex(childB) - this.displayList.getIndex(childA); - } - else if (childA.parentContainer === childB.parentContainer) - { - // Quick bail out when both children have the same container - return childB.parentContainer.getIndex(childB) - childA.parentContainer.getIndex(childA); - } - else if (childA.parentContainer === childB) - { - // Quick bail out when childA is a child of childB - return -1; - } - else if (childB.parentContainer === childA) - { - // Quick bail out when childA is a child of childB - return 1; - } - else - { - // Container index check - var listA = childA.getIndexList(); - var listB = childB.getIndexList(); - var len = Math.min(listA.length, listB.length); - - for (var i = 0; i < len; i++) - { - var indexA = listA[i]; - var indexB = listB[i]; - - if (indexA === indexB) - { - // Go to the next level down - continue; - } - else - { - // Non-matching parents, so return - return indexB - indexA; - } - } - } - - // Technically this shouldn't happen, but ... - return 0; - }, - - /** - * This method should be called from within an input event handler, such as `pointerdown`. - * - * When called, it stops the Input Manager from allowing _this specific event_ to be processed by any other Scene - * not yet handled in the scene list. - * - * @method Phaser.Input.InputPlugin#stopPropagation - * @since 3.0.0 - * - * @return {Phaser.Input.InputPlugin} This InputPlugin object. - */ - stopPropagation: function () - { - this.manager._tempSkip = true; - - return this; - }, - - /** - * Adds new Pointer objects to the Input Manager. - * - * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. - * - * You can create more either by calling this method, or by setting the `input.activePointers` property - * in the Game Config, up to a maximum of 10 pointers. - * - * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added - * via this method. - * - * @method Phaser.Input.InputPlugin#addPointer - * @since 3.10.0 - * - * @param {integer} [quantity=1] The number of new Pointers to create. A maximum of 10 is allowed in total. - * - * @return {Phaser.Input.Pointer[]} An array containing all of the new Pointer objects that were created. - */ - addPointer: function (quantity) - { - return this.manager.addPointer(quantity); - }, - - /** - * 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 {Phaser.Input.InputPlugin} This Input instance. - */ - setDefaultCursor: function (cursor) - { - this.manager.setDefaultCursor(cursor); - - return this; - }, - - /** - * The Scene that owns this plugin is transitioning in. - * - * @method Phaser.Input.InputPlugin#transitionIn - * @private - * @since 3.5.0 - */ - transitionIn: function () - { - this.enabled = this.settings.transitionAllowInput; - }, - - /** - * The Scene that owns this plugin has finished transitioning in. - * - * @method Phaser.Input.InputPlugin#transitionComplete - * @private - * @since 3.5.0 - */ - transitionComplete: function () - { - if (!this.settings.transitionAllowInput) - { - this.enabled = true; - } - }, - - /** - * The Scene that owns this plugin is transitioning out. - * - * @method Phaser.Input.InputPlugin#transitionOut - * @private - * @since 3.5.0 - */ - transitionOut: function () - { - this.enabled = this.settings.transitionAllowInput; - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Input.InputPlugin#shutdown - * @fires Phaser.Input.Events#SHUTDOWN - * @private - * @since 3.0.0 - */ - shutdown: function () - { - // Registered input plugins listen for this - this.pluginEvents.emit(Events.SHUTDOWN); - - this._temp.length = 0; - this._list.length = 0; - this._draggable.length = 0; - this._pendingRemoval.length = 0; - this._pendingInsertion.length = 0; - this._dragState.length = 0; - - for (var i = 0; i < 10; i++) - { - this._drag[i] = []; - this._over[i] = []; - } - - this.removeAllListeners(); - - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.TRANSITION_START, this.transitionIn, this); - eventEmitter.off(SceneEvents.TRANSITION_OUT, this.transitionOut, this); - eventEmitter.off(SceneEvents.TRANSITION_COMPLETE, this.transitionComplete, this); - eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); - - this.manager.events.off(Events.GAME_OUT, this.onGameOut, this); - this.manager.events.off(Events.GAME_OVER, this.onGameOver, this); - - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Input.InputPlugin#destroy - * @fires Phaser.Input.Events#DESTROY - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - // Registered input plugins listen for this - this.pluginEvents.emit(Events.DESTROY); - - this.pluginEvents.removeAllListeners(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.cameras = null; - this.manager = null; - this.events = null; - this.mouse = null; - }, - - /** - * The x coordinates 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 - */ - x: { - - get: function () - { - return this.manager.activePointer.x; - } - - }, - - /** - * The y coordinates 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 - */ - y: { - - get: function () - { - return this.manager.activePointer.y; - } - - }, - - /** - * Are any mouse or touch pointers currently over the game canvas? - * - * @name Phaser.Input.InputPlugin#isOver - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - isOver: { - - get: function () - { - return this.manager.isOver; - } - - }, - - /** - * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. - * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` - * which will always map to the most recently interacted pointer. - * - * @name Phaser.Input.InputPlugin#mousePointer - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - mousePointer: { - - get: function () - { - return this.manager.mousePointer; - } - - }, - - /** - * The current active input Pointer. - * - * @name Phaser.Input.InputPlugin#activePointer - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.0.0 - */ - activePointer: { - - get: function () - { - return this.manager.activePointer; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer1 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer1: { - - get: function () - { - return this.manager.pointers[1]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer2 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer2: { - - get: function () - { - return this.manager.pointers[2]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer3 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer3: { - - get: function () - { - return this.manager.pointers[3]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer4 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer4: { - - get: function () - { - return this.manager.pointers[4]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer5 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer5: { - - get: function () - { - return this.manager.pointers[5]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer6 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer6: { - - get: function () - { - return this.manager.pointers[6]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer7 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer7: { - - get: function () - { - return this.manager.pointers[7]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer8 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer8: { - - get: function () - { - return this.manager.pointers[8]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer9 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer9: { - - get: function () - { - return this.manager.pointers[9]; - } - - }, - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - * - * @name Phaser.Input.InputPlugin#pointer10 - * @type {Phaser.Input.Pointer} - * @readonly - * @since 3.10.0 - */ - pointer10: { - - get: function () - { - return this.manager.pointers[10]; - } - - } - -}); - -PluginCache.register('InputPlugin', InputPlugin, 'input'); - -module.exports = InputPlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Circle = require('../geom/circle/Circle'); +var CircleContains = require('../geom/circle/Contains'); +var Class = require('../utils/Class'); +var CONST = require('./const'); +var CreateInteractiveObject = require('./CreateInteractiveObject'); +var CreatePixelPerfectHandler = require('./CreatePixelPerfectHandler'); +var DistanceBetween = require('../math/distance/DistanceBetween'); +var Ellipse = require('../geom/ellipse/Ellipse'); +var EllipseContains = require('../geom/ellipse/Contains'); +var Events = require('./events'); +var EventEmitter = require('eventemitter3'); +var GetFastValue = require('../utils/object/GetFastValue'); +var GEOM_CONST = require('../geom/const'); +var InputPluginCache = require('./InputPluginCache'); +var IsPlainObject = require('../utils/object/IsPlainObject'); +var PluginCache = require('../plugins/PluginCache'); +var Rectangle = require('../geom/rectangle/Rectangle'); +var RectangleContains = require('../geom/rectangle/Contains'); +var SceneEvents = require('../scene/events'); +var Triangle = require('../geom/triangle/Triangle'); +var TriangleContains = require('../geom/triangle/Contains'); + +/** + * @classdesc + * The Input Plugin belongs to a Scene and handles all input related events and operations for it. + * + * You can access it from within a Scene using `this.input`. + * + * It emits events directly. For example, you can do: + * + * ```javascript + * this.input.on('pointerdown', callback, context); + * ``` + * + * To listen for a pointer down event anywhere on the game canvas. + * + * Game Objects can be enabled for input by calling their `setInteractive` method. After which they + * will directly emit input events: + * + * ```javascript + * var sprite = this.add.sprite(x, y, texture); + * sprite.setInteractive(); + * sprite.on('pointerdown', callback, context); + * ``` + * + * There are lots of game configuration options available relating to input. + * See the [Input Config object]{@linkcode Phaser.Types.Core.InputConfig} for more details, including how to deal with Phaser + * listening for input events outside of the canvas, how to set a default number of pointers, input + * capture settings and more. + * + * Please also see the Input examples and tutorials for further information. + * + * @class InputPlugin + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Input + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that this Input Plugin is responsible for. + */ +var InputPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function InputPlugin (scene) + { + EventEmitter.call(this); + + /** + * A reference to the Scene that this Input Plugin is responsible for. + * + * @name Phaser.Input.InputPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems class. + * + * @name Phaser.Input.InputPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the Scene Systems Settings. + * + * @name Phaser.Input.InputPlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.5.0 + */ + this.settings = scene.sys.settings; + + /** + * A reference to the Game Input Manager. + * + * @name Phaser.Input.InputPlugin#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = scene.sys.game.input; + + /** + * Internal event queue used for plugins only. + * + * @name Phaser.Input.InputPlugin#pluginEvents + * @type {Phaser.Events.EventEmitter} + * @private + * @since 3.10.0 + */ + this.pluginEvents = new EventEmitter(); + + /** + * If `true` this Input Plugin will process DOM input events. + * + * @name Phaser.Input.InputPlugin#enabled + * @type {boolean} + * @default true + * @since 3.5.0 + */ + this.enabled = true; + + /** + * A reference to the Scene Display List. This property is set during the `boot` method. + * + * @name Phaser.Input.InputPlugin#displayList + * @type {Phaser.GameObjects.DisplayList} + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene Cameras Manager. This property is set during the `boot` method. + * + * @name Phaser.Input.InputPlugin#cameras + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.0.0 + */ + this.cameras; + + // Inject the available input plugins into this class + InputPluginCache.install(this); + + /** + * A reference to the Mouse Manager. + * + * This property is only set if Mouse support has been enabled in your Game Configuration file. + * + * If you just wish to get access to the mouse pointer, use the `mousePointer` property instead. + * + * @name Phaser.Input.InputPlugin#mouse + * @type {?Phaser.Input.Mouse.MouseManager} + * @since 3.0.0 + */ + this.mouse = this.manager.mouse; + + /** + * When set to `true` (the default) the Input Plugin will emulate DOM behavior by only emitting events from + * the top-most Game Objects in the Display List. + * + * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. + * + * @name Phaser.Input.InputPlugin#topOnly + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.topOnly = true; + + /** + * How often should the Pointers be checked? + * + * The value is a time, given in ms, and is the time that must have elapsed between game steps before + * the Pointers will be polled again. When a pointer is polled it runs a hit test to see which Game + * Objects are currently below it, or being interacted with it. + * + * Pointers will *always* be checked if they have been moved by the user, or press or released. + * + * This property only controls how often they will be polled if they have not been updated. + * You should set this if you want to have Game Objects constantly check against the pointers, even + * if the pointer didn't itself move. + * + * Set to 0 to poll constantly. Set to -1 to only poll on user movement. + * + * @name Phaser.Input.InputPlugin#pollRate + * @type {integer} + * @default -1 + * @since 3.0.0 + */ + this.pollRate = -1; + + /** + * Internal poll timer value. + * + * @name Phaser.Input.InputPlugin#_pollTimer + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._pollTimer = 0; + + var _eventData = { cancelled: false }; + + /** + * Internal event propagation callback container. + * + * @name Phaser.Input.InputPlugin#_eventContainer + * @type {Phaser.Types.Input.EventData} + * @private + * @since 3.13.0 + */ + this._eventContainer = { + stopPropagation: function () + { + _eventData.cancelled = true; + } + }; + + /** + * Internal event propagation data object. + * + * @name Phaser.Input.InputPlugin#_eventData + * @type {object} + * @private + * @since 3.13.0 + */ + this._eventData = _eventData; + + /** + * The distance, in pixels, a pointer has to move while being held down, before it thinks it is being dragged. + * + * @name Phaser.Input.InputPlugin#dragDistanceThreshold + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragDistanceThreshold = 0; + + /** + * The amount of time, in ms, a pointer has to be held down before it thinks it is dragging. + * + * The default polling rate is to poll only on move so once the time threshold is reached the + * drag event will not start until you move the mouse. If you want it to start immediately + * when the time threshold is reached, you must increase the polling rate by calling + * [setPollAlways]{@linkcode Phaser.Input.InputPlugin#setPollAlways} or + * [setPollRate]{@linkcode Phaser.Input.InputPlugin#setPollRate}. + * + * @name Phaser.Input.InputPlugin#dragTimeThreshold + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.dragTimeThreshold = 0; + + /** + * Used to temporarily store the results of the Hit Test + * + * @name Phaser.Input.InputPlugin#_temp + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this._temp = []; + + /** + * Used to temporarily store the results of the Hit Test dropZones + * + * @name Phaser.Input.InputPlugin#_tempZones + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this._tempZones = []; + + /** + * A list of all Game Objects that have been set to be interactive in the Scene this Input Plugin is managing. + * + * @name Phaser.Input.InputPlugin#_list + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._list = []; + + /** + * Objects waiting to be inserted to the list on the next call to 'begin'. + * + * @name Phaser.Input.InputPlugin#_pendingInsertion + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingInsertion = []; + + /** + * Objects waiting to be removed from the list on the next call to 'begin'. + * + * @name Phaser.Input.InputPlugin#_pendingRemoval + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingRemoval = []; + + /** + * A list of all Game Objects that have been enabled for dragging. + * + * @name Phaser.Input.InputPlugin#_draggable + * @type {Phaser.GameObjects.GameObject[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._draggable = []; + + /** + * A list of all Interactive Objects currently considered as being 'draggable' by any pointer, indexed by pointer ID. + * + * @name Phaser.Input.InputPlugin#_drag + * @type {{0:Array,1:Array,2:Array,3:Array,4:Array,5:Array,6:Array,7:Array,8:Array,9:Array,10:Array}} + * @private + * @since 3.0.0 + */ + this._drag = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; + + /** + * A array containing the dragStates, for this Scene, index by the Pointer ID. + * + * @name Phaser.Input.InputPlugin#_dragState + * @type {integer[]} + * @private + * @since 3.16.0 + */ + this._dragState = []; + + /** + * A list of all Interactive Objects currently considered as being 'over' by any pointer, indexed by pointer ID. + * + * @name Phaser.Input.InputPlugin#_over + * @type {{0:Array,1:Array,2:Array,3:Array,4:Array,5:Array,6:Array,7:Array,8:Array,9:Array,10:Array}} + * @private + * @since 3.0.0 + */ + this._over = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; + + /** + * A list of valid DOM event types. + * + * @name Phaser.Input.InputPlugin#_validTypes + * @type {string[]} + * @private + * @since 3.0.0 + */ + this._validTypes = [ 'onDown', 'onUp', 'onOver', 'onOut', 'onMove', 'onDragStart', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragLeave', 'onDragOver', 'onDrop' ]; + + /** + * Internal property that tracks frame event state. + * + * @name Phaser.Input.InputPlugin#_updatedThisFrame + * @type {boolean} + * @private + * @since 3.18.0 + */ + this._updatedThisFrame = false; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Input.InputPlugin#boot + * @fires Phaser.Input.Events#BOOT + * @private + * @since 3.5.1 + */ + boot: function () + { + this.cameras = this.systems.cameras; + + this.displayList = this.systems.displayList; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + + // Registered input plugins listen for this + this.pluginEvents.emit(Events.BOOT); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Input.InputPlugin#start + * @fires Phaser.Input.Events#START + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.TRANSITION_START, this.transitionIn, this); + eventEmitter.on(SceneEvents.TRANSITION_OUT, this.transitionOut, this); + eventEmitter.on(SceneEvents.TRANSITION_COMPLETE, this.transitionComplete, this); + eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.manager.events.on(Events.GAME_OUT, this.onGameOut, this); + this.manager.events.on(Events.GAME_OVER, this.onGameOver, this); + + this.enabled = true; + + // Populate the pointer drag states + this._dragState = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; + + // Registered input plugins listen for this + this.pluginEvents.emit(Events.START); + }, + + /** + * Game Over handler. + * + * @method Phaser.Input.InputPlugin#onGameOver + * @fires Phaser.Input.Events#GAME_OVER + * @private + * @since 3.16.2 + */ + onGameOver: function (event) + { + if (this.isActive()) + { + this.emit(Events.GAME_OVER, event.timeStamp, event); + } + }, + + /** + * Game Out handler. + * + * @method Phaser.Input.InputPlugin#onGameOut + * @fires Phaser.Input.Events#GAME_OUT + * @private + * @since 3.16.2 + */ + onGameOut: function (event) + { + if (this.isActive()) + { + this.emit(Events.GAME_OUT, event.timeStamp, event); + } + }, + + /** + * The pre-update handler is responsible for checking the pending removal and insertion lists and + * deleting old Game Objects. + * + * @method Phaser.Input.InputPlugin#preUpdate + * @private + * @fires Phaser.Input.Events#PRE_UPDATE + * @since 3.0.0 + */ + preUpdate: function () + { + // Registered input plugins listen for this + this.pluginEvents.emit(Events.PRE_UPDATE); + + var removeList = this._pendingRemoval; + var insertList = this._pendingInsertion; + + var toRemove = removeList.length; + var toInsert = insertList.length; + + if (toRemove === 0 && toInsert === 0) + { + // Quick bail + return; + } + + var current = this._list; + + // Delete old gameObjects + for (var i = 0; i < toRemove; i++) + { + var gameObject = removeList[i]; + + var index = current.indexOf(gameObject); + + if (index > -1) + { + current.splice(index, 1); + + this.clear(gameObject, true); + } + } + + // Clear the removal list + removeList.length = 0; + this._pendingRemoval.length = 0; + + // Move pendingInsertion to list (also clears pendingInsertion at the same time) + this._list = current.concat(insertList.splice(0)); + }, + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + * + * @method Phaser.Input.InputPlugin#isActive + * @since 3.10.0 + * + * @return {boolean} `true` if the plugin and the Scene it belongs to is active. + */ + isActive: function () + { + return (this.enabled && this.scene.sys.isActive()); + }, + + /** + * 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. + */ + updatePoll: function (time, delta) + { + if (!this.isActive()) + { + return false; + } + + // The plugins should update every frame, regardless if there has been + // any DOM input events or not (such as the Gamepad and Keyboard) + this.pluginEvents.emit(Events.UPDATE, time, delta); + + // We can leave now if we've already updated once this frame via the immediate DOM event handlers + if (this._updatedThisFrame) + { + this._updatedThisFrame = false; + + return false; + } + + var i; + var manager = this.manager; + + var pointers = manager.pointers; + var pointersTotal = manager.pointersTotal; + + for (i = 0; i < pointersTotal; i++) + { + pointers[i].updateMotion(); + } + + // No point going any further if there aren't any interactive objects + if (this._list.length === 0) + { + return false; + } + + var rate = this.pollRate; + + if (rate === -1) + { + return false; + } + else if (rate > 0) + { + this._pollTimer -= delta; + + if (this._pollTimer < 0) + { + // Discard timer diff, we're ready to poll again + this._pollTimer = this.pollRate; + } + else + { + // Not enough time has elapsed since the last poll, so abort now + return false; + } + } + + // We got this far? Then we should poll for movement + var captured = false; + + for (i = 0; i < pointersTotal; i++) + { + var total = 0; + + var pointer = pointers[i]; + + // Always reset this array + this._tempZones = []; + + // _temp contains a hit tested and camera culled list of IO objects + this._temp = this.hitTestPointer(pointer); + + this.sortGameObjects(this._temp); + this.sortGameObjects(this._tempZones); + + if (this.topOnly) + { + // Only the top-most one counts now, so safely ignore the rest + if (this._temp.length) + { + this._temp.splice(1); + } + + if (this._tempZones.length) + { + this._tempZones.splice(1); + } + } + + total += this.processOverOutEvents(pointer); + + if (this.getDragState(pointer) === 2) + { + this.processDragThresholdEvent(pointer, time); + } + + if (total > 0) + { + // We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame + captured = true; + } + } + + return captured; + }, + + /** + * This method is called when a DOM Event is received by the Input Manager. It handles dispatching the events + * to relevant input enabled Game Objects in this scene. + * + * @method Phaser.Input.InputPlugin#update + * @private + * @fires Phaser.Input.Events#UPDATE + * @since 3.0.0 + * + * @param {integer} type - The type of event to process. + * @param {Phaser.Input.Pointer[]} pointers - An array of Pointers on which the event occurred. + * + * @return {boolean} `true` if this Scene has captured the input events from all other Scenes, otherwise `false`. + */ + update: function (type, pointers) + { + if (!this.isActive()) + { + return false; + } + + var pointersTotal = pointers.length; + var captured = false; + + for (var i = 0; i < pointersTotal; i++) + { + var total = 0; + var pointer = pointers[i]; + + // Always reset this array + this._tempZones = []; + + // _temp contains a hit tested and camera culled list of IO objects + this._temp = this.hitTestPointer(pointer); + + this.sortGameObjects(this._temp); + this.sortGameObjects(this._tempZones); + + if (this.topOnly) + { + // Only the top-most one counts now, so safely ignore the rest + if (this._temp.length) + { + this._temp.splice(1); + } + + if (this._tempZones.length) + { + this._tempZones.splice(1); + } + } + + switch (type) + { + case CONST.MOUSE_DOWN: + total += this.processDragDownEvent(pointer); + total += this.processDownEvents(pointer); + total += this.processOverOutEvents(pointer); + break; + + case CONST.MOUSE_UP: + total += this.processDragUpEvent(pointer); + total += this.processUpEvents(pointer); + total += this.processOverOutEvents(pointer); + break; + + case CONST.TOUCH_START: + total += this.processDragDownEvent(pointer); + total += this.processDownEvents(pointer); + total += this.processOverEvents(pointer); + break; + + case CONST.TOUCH_END: + case CONST.TOUCH_CANCEL: + total += this.processDragUpEvent(pointer); + total += this.processUpEvents(pointer); + total += this.processOutEvents(pointer); + break; + + case CONST.MOUSE_MOVE: + case CONST.TOUCH_MOVE: + total += this.processDragMoveEvent(pointer); + total += this.processMoveEvents(pointer); + total += this.processOverOutEvents(pointer); + break; + + case CONST.MOUSE_WHEEL: + total += this.processWheelEvent(pointer); + break; + } + + if (total > 0) + { + // We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame + captured = true; + } + } + + this._updatedThisFrame = true; + + return captured; + }, + + /** + * Clears a Game Object so it no longer has an Interactive Object associated with it. + * The Game Object is then queued for removal from the Input Plugin on the next update. + * + * @method Phaser.Input.InputPlugin#clear + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will have its Interactive Object removed. + * @param {boolean} [skipQueue=false] - Skip adding this Game Object into the removal queue? + * + * @return {Phaser.GameObjects.GameObject} The Game Object that had its Interactive Object removed. + */ + clear: function (gameObject, skipQueue) + { + if (skipQueue === undefined) { skipQueue = false; } + + var input = gameObject.input; + + // If GameObject.input already cleared from higher class + if (!input) + { + return; + } + + if (!skipQueue) + { + this.queueForRemoval(gameObject); + } + + input.gameObject = undefined; + input.target = undefined; + input.hitArea = undefined; + input.hitAreaCallback = undefined; + input.callbackContext = undefined; + + this.manager.resetCursor(input); + + gameObject.input = null; + + // Clear from _draggable, _drag and _over + var index = this._draggable.indexOf(gameObject); + + if (index > -1) + { + this._draggable.splice(index, 1); + } + + index = this._drag[0].indexOf(gameObject); + + if (index > -1) + { + this._drag[0].splice(index, 1); + } + + index = this._over[0].indexOf(gameObject); + + if (index > -1) + { + this._over[0].splice(index, 1); + } + + return gameObject; + }, + + /** + * Disables Input on a single Game Object. + * + * An input disabled Game Object still retains its Interactive Object component and can be re-enabled + * at any time, by passing it to `InputPlugin.enable`. + * + * @method Phaser.Input.InputPlugin#disable + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to have its input system disabled. + */ + disable: function (gameObject) + { + gameObject.input.enabled = false; + }, + + /** + * 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)} [shape] - 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} [callback] - 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 {Phaser.Input.InputPlugin} This Input Plugin. + */ + enable: function (gameObject, shape, callback, dropZone) + { + if (dropZone === undefined) { dropZone = false; } + + if (gameObject.input) + { + // If it is already has an InteractiveObject then just enable it and return + gameObject.input.enabled = true; + } + else + { + // Create an InteractiveObject and enable it + this.setHitArea(gameObject, shape, callback); + } + + if (gameObject.input && dropZone && !gameObject.input.dropZone) + { + gameObject.input.dropZone = dropZone; + } + + return this; + }, + + /** + * Takes the given Pointer and performs a hit test against it, to see which interactive Game Objects + * it is currently above. + * + * The hit test is performed against which-ever Camera the Pointer is over. If it is over multiple + * cameras, it starts checking the camera at the top of the camera list, and if nothing is found, iterates down the list. + * + * @method Phaser.Input.InputPlugin#hitTestPointer + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to check against the Game Objects. + * + * @return {Phaser.GameObjects.GameObject[]} An array of all the interactive Game Objects the Pointer was above. + */ + hitTestPointer: function (pointer) + { + var cameras = this.cameras.getCamerasBelowPointer(pointer); + + for (var c = 0; c < cameras.length; c++) + { + var camera = cameras[c]; + + // 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. + var over = this.manager.hitTest(pointer, this._list, camera); + + // Filter out the drop zones + for (var i = 0; i < over.length; i++) + { + var obj = over[i]; + + if (obj.input.dropZone) + { + this._tempZones.push(obj); + } + } + + if (over.length > 0) + { + pointer.camera = camera; + + return over; + } + } + + // 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 + + pointer.camera = cameras[0]; + + return []; + }, + + /** + * An internal method that handles the Pointer down event. + * + * @method Phaser.Input.InputPlugin#processDownEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_DOWN + * @fires Phaser.Input.Events#GAMEOBJECT_DOWN + * @fires Phaser.Input.Events#POINTER_DOWN + * @fires Phaser.Input.Events#POINTER_DOWN_OUTSIDE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer being tested. + * + * @return {integer} The total number of objects interacted with. + */ + processDownEvents: function (pointer) + { + var total = 0; + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + total++; + + gameObject.emit(Events.GAMEOBJECT_POINTER_DOWN, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_DOWN, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + // If they released outside the canvas, but pressed down inside it, we'll still dispatch the event. + if (!aborted && this.manager) + { + if (pointer.downElement === this.manager.game.canvas) + { + this.emit(Events.POINTER_DOWN, pointer, currentlyOver); + } + else + { + this.emit(Events.POINTER_DOWN_OUTSIDE, pointer); + } + } + + return total; + }, + + /** + * Returns the drag state of the given Pointer for this Input Plugin. + * + * The state will be one of the following: + * + * 0 = Not dragging anything + * 1 = Primary button down and objects below, so collect a draglist + * 2 = Pointer being checked if meets drag criteria + * 3 = Pointer meets criteria, notify the draglist + * 4 = Pointer actively dragging the draglist and has moved + * 5 = Pointer actively dragging but has been released, notify draglist + * + * @method Phaser.Input.InputPlugin#getDragState + * @since 3.16.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to get the drag state for. + * + * @return {integer} The drag state of the given Pointer. + */ + getDragState: function (pointer) + { + return this._dragState[pointer.id]; + }, + + /** + * Sets the drag state of the given Pointer for this Input Plugin. + * + * The state must be one of the following values: + * + * 0 = Not dragging anything + * 1 = Primary button down and objects below, so collect a draglist + * 2 = Pointer being checked if meets drag criteria + * 3 = Pointer meets criteria, notify the draglist + * 4 = Pointer actively dragging the draglist and has moved + * 5 = Pointer actively dragging but has been released, notify draglist + * + * @method Phaser.Input.InputPlugin#setDragState + * @since 3.16.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to set the drag state for. + * @param {integer} state - The drag state value. An integer between 0 and 5. + */ + setDragState: function (pointer, state) + { + this._dragState[pointer.id] = state; + }, + + /** + * 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. + */ + processDragThresholdEvent: function (pointer, time) + { + var passed = false; + var timeThreshold = this.dragTimeThreshold; + var distanceThreshold = this.dragDistanceThreshold; + + if (distanceThreshold > 0 && DistanceBetween(pointer.x, pointer.y, pointer.downX, pointer.downY) >= distanceThreshold) + { + // It has moved far enough to be considered a drag + passed = true; + } + else if (timeThreshold > 0 && (time >= pointer.downTime + timeThreshold)) + { + // It has been held down long enough to be considered a drag + passed = true; + } + + if (passed) + { + this.setDragState(pointer, 3); + + return this.processDragStartList(pointer); + } + }, + + /** + * Processes the drag list for the given pointer and dispatches the start events for each object on it. + * + * @method Phaser.Input.InputPlugin#processDragStartList + * @private + * @fires Phaser.Input.Events#DRAG_START + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_START + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that DRAG_START was called on. + */ + processDragStartList: function (pointer) + { + // 3 = Pointer meets criteria and is freshly down, notify the draglist + if (this.getDragState(pointer) !== 3) + { + return 0; + } + + var list = this._drag[pointer.id]; + + for (var i = 0; i < list.length; i++) + { + var gameObject = list[i]; + + var input = gameObject.input; + + input.dragState = 2; + + input.dragStartX = gameObject.x; + input.dragStartY = gameObject.y; + + input.dragStartXGlobal = pointer.x; + input.dragStartYGlobal = pointer.y; + + input.dragX = input.dragStartXGlobal - input.dragStartX; + input.dragY = input.dragStartYGlobal - input.dragStartY; + + gameObject.emit(Events.GAMEOBJECT_DRAG_START, pointer, input.dragX, input.dragY); + + this.emit(Events.DRAG_START, pointer, gameObject); + } + + this.setDragState(pointer, 4); + + return list.length; + }, + + /** + * Processes a 'drag down' event for the given pointer. Checks the pointer state, builds-up the drag list + * and prepares them all for interaction. + * + * @method Phaser.Input.InputPlugin#processDragDownEvent + * @private + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that were collected on the drag list. + */ + processDragDownEvent: function (pointer) + { + var currentlyOver = this._temp; + + if (this._draggable.length === 0 || currentlyOver.length === 0 || !pointer.primaryDown || this.getDragState(pointer) !== 0) + { + // There are no draggable items, no over items or the pointer isn't down, so let's not even bother going further + return 0; + } + + // 1 = Primary button down and objects below, so collect a draglist + this.setDragState(pointer, 1); + + // Get draggable objects, sort them, pick the top (or all) and store them somewhere + var draglist = []; + + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (gameObject.input.draggable && (gameObject.input.dragState === 0)) + { + draglist.push(gameObject); + } + } + + if (draglist.length === 0) + { + this.setDragState(pointer, 0); + + return 0; + } + else if (draglist.length > 1) + { + this.sortGameObjects(draglist); + + if (this.topOnly) + { + draglist.splice(1); + } + } + + // draglist now contains all potential candidates for dragging + this._drag[pointer.id] = draglist; + + if (this.dragDistanceThreshold === 0 && this.dragTimeThreshold === 0) + { + // No drag criteria, so snap immediately to mode 3 + this.setDragState(pointer, 3); + + return this.processDragStartList(pointer); + } + else + { + // Check the distance / time on the next event + this.setDragState(pointer, 2); + + return 0; + } + }, + + /** + * Processes a 'drag move' event for the given pointer. + * + * @method Phaser.Input.InputPlugin#processDragMoveEvent + * @private + * @fires Phaser.Input.Events#DRAG_ENTER + * @fires Phaser.Input.Events#DRAG + * @fires Phaser.Input.Events#DRAG_LEAVE + * @fires Phaser.Input.Events#DRAG_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_ENTER + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_LEAVE + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_OVER + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that were updated by this drag event. + */ + processDragMoveEvent: function (pointer) + { + // 2 = Pointer being checked if meets drag criteria + if (this.getDragState(pointer) === 2) + { + this.processDragThresholdEvent(pointer, this.manager.game.loop.now); + } + + if (this.getDragState(pointer) !== 4) + { + return 0; + } + + // 4 = Pointer actively dragging the draglist and has moved + var dropZones = this._tempZones; + + var list = this._drag[pointer.id]; + + for (var i = 0; i < list.length; i++) + { + var gameObject = list[i]; + + var input = gameObject.input; + + var target = input.target; + + // If this GO has a target then let's check it + if (target) + { + var index = dropZones.indexOf(target); + + // Got a target, are we still over it? + if (index === 0) + { + // We're still over it, and it's still the top of the display list, phew ... + gameObject.emit(Events.GAMEOBJECT_DRAG_OVER, pointer, target); + + this.emit(Events.DRAG_OVER, pointer, gameObject, target); + } + else if (index > 0) + { + // Still over it but it's no longer top of the display list (targets must always be at the top) + gameObject.emit(Events.GAMEOBJECT_DRAG_LEAVE, pointer, target); + + this.emit(Events.DRAG_LEAVE, pointer, gameObject, target); + + input.target = dropZones[0]; + + target = input.target; + + gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); + + this.emit(Events.DRAG_ENTER, pointer, gameObject, target); + } + else + { + // Nope, we've moved on (or the target has!), leave the old target + gameObject.emit(Events.GAMEOBJECT_DRAG_LEAVE, pointer, target); + + this.emit(Events.DRAG_LEAVE, pointer, gameObject, target); + + // Anything new to replace it? + // Yup! + if (dropZones[0]) + { + input.target = dropZones[0]; + + target = input.target; + + gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); + + this.emit(Events.DRAG_ENTER, pointer, gameObject, target); + } + else + { + // Nope + input.target = null; + } + } + } + else if (!target && dropZones[0]) + { + input.target = dropZones[0]; + + target = input.target; + + gameObject.emit(Events.GAMEOBJECT_DRAG_ENTER, pointer, target); + + this.emit(Events.DRAG_ENTER, pointer, gameObject, target); + } + + var dragX; + var dragY; + + if (!gameObject.parentContainer) + { + dragX = pointer.x - input.dragX; + dragY = pointer.y - input.dragY; + } + else + { + var dx = pointer.x - input.dragStartXGlobal; + var dy = pointer.y - input.dragStartYGlobal; + + var rotation = gameObject.getParentRotation(); + + var dxRotated = dx * Math.cos(rotation) + dy * Math.sin(rotation); + var dyRotated = dy * Math.cos(rotation) - dx * Math.sin(rotation); + + dxRotated *= (1 / gameObject.parentContainer.scaleX); + dyRotated *= (1 / gameObject.parentContainer.scaleY); + + dragX = dxRotated + input.dragStartX; + dragY = dyRotated + input.dragStartY; + } + + gameObject.emit(Events.GAMEOBJECT_DRAG, pointer, dragX, dragY); + + this.emit(Events.DRAG, pointer, gameObject, dragX, dragY); + } + + return list.length; + }, + + /** + * Processes a 'drag down' event for the given pointer. Checks the pointer state, builds-up the drag list + * and prepares them all for interaction. + * + * @method Phaser.Input.InputPlugin#processDragUpEvent + * @fires Phaser.Input.Events#DRAG_END + * @fires Phaser.Input.Events#DROP + * @fires Phaser.Input.Events#GAMEOBJECT_DRAG_END + * @fires Phaser.Input.Events#GAMEOBJECT_DROP + * @private + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer to process the drag event on. + * + * @return {integer} The number of items that were updated by this drag event. + */ + processDragUpEvent: function (pointer) + { + // 5 = Pointer was actively dragging but has been released, notify draglist + var list = this._drag[pointer.id]; + + for (var i = 0; i < list.length; i++) + { + var gameObject = list[i]; + + var input = gameObject.input; + + if (input && input.dragState === 2) + { + input.dragState = 0; + + input.dragX = input.localX - gameObject.displayOriginX; + input.dragY = input.localY - gameObject.displayOriginY; + + var dropped = false; + + var target = input.target; + + if (target) + { + gameObject.emit(Events.GAMEOBJECT_DROP, pointer, target); + + this.emit(Events.DROP, pointer, gameObject, target); + + input.target = null; + + dropped = true; + } + + // And finally the dragend event + + if (gameObject.input) + { + gameObject.emit(Events.GAMEOBJECT_DRAG_END, pointer, input.dragX, input.dragY, dropped); + + this.emit(Events.DRAG_END, pointer, gameObject, dropped); + } + } + } + + this.setDragState(pointer, 0); + + list.splice(0); + + return 0; + }, + + /** + * An internal method that handles the Pointer movement event. + * + * @method Phaser.Input.InputPlugin#processMoveEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_MOVE + * @fires Phaser.Input.Events#GAMEOBJECT_MOVE + * @fires Phaser.Input.Events#POINTER_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processMoveEvents: function (pointer) + { + var total = 0; + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + total++; + + gameObject.emit(Events.GAMEOBJECT_POINTER_MOVE, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_MOVE, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + if (this.topOnly) + { + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_MOVE, pointer, currentlyOver); + } + + return total; + }, + + /** + * An internal method that handles a mouse wheel event. + * + * @method Phaser.Input.InputPlugin#processWheelEvent + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_WHEEL + * @fires Phaser.Input.Events#GAMEOBJECT_WHEEL + * @fires Phaser.Input.Events#POINTER_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processWheelEvent: function (pointer) + { + var total = 0; + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + var dx = pointer.deltaX; + var dy = pointer.deltaY; + var dz = pointer.deltaZ; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + total++; + + gameObject.emit(Events.GAMEOBJECT_POINTER_WHEEL, pointer, dx, dy, dz, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_WHEEL, pointer, gameObject, dx, dy, dz, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_WHEEL, pointer, currentlyOver, dx, dy, dz); + } + + return total; + }, + + /** + * An internal method that handles the Pointer over events. + * This is called when a touch input hits the canvas, having previously been off of it. + * + * @method Phaser.Input.InputPlugin#processOverEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_OVER + * @fires Phaser.Input.Events#POINTER_OVER + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processOverEvents: function (pointer) + { + var currentlyOver = this._temp; + + var totalInteracted = 0; + + var total = currentlyOver.length; + + var justOver = []; + + if (total > 0) + { + var manager = this.manager; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + for (var i = 0; i < total; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + justOver.push(gameObject); + + manager.setCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OVER, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OVER, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OVER, pointer, justOver); + } + } + + // Then sort it into display list order + this._over[pointer.id] = justOver; + + return totalInteracted; + }, + + /** + * An internal method that handles the Pointer out events. + * This is called when a touch input leaves the canvas, as it can never be 'over' in this case. + * + * @method Phaser.Input.InputPlugin#processOutEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OUT + * @fires Phaser.Input.Events#GAMEOBJECT_OUT + * @fires Phaser.Input.Events#POINTER_OUT + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processOutEvents: function (pointer) + { + var previouslyOver = this._over[pointer.id]; + + var totalInteracted = 0; + + var total = previouslyOver.length; + + if (total > 0) + { + var manager = this.manager; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + this.sortGameObjects(previouslyOver); + + for (var i = 0; i < total; i++) + { + var gameObject = previouslyOver[i]; + + // Call onOut for everything in the previouslyOver array + for (i = 0; i < total; i++) + { + gameObject = previouslyOver[i]; + + if (!gameObject.input) + { + continue; + } + + manager.resetCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OUT, pointer, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OUT, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OUT, pointer, previouslyOver); + } + } + + this._over[pointer.id] = []; + } + + return totalInteracted; + }, + + /** + * An internal method that handles the Pointer over and out events. + * + * @method Phaser.Input.InputPlugin#processOverOutEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_OVER + * @fires Phaser.Input.Events#POINTER_OVER + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_OUT + * @fires Phaser.Input.Events#GAMEOBJECT_OUT + * @fires Phaser.Input.Events#POINTER_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processOverOutEvents: function (pointer) + { + var currentlyOver = this._temp; + + var i; + var gameObject; + var justOut = []; + var justOver = []; + var stillOver = []; + var previouslyOver = this._over[pointer.id]; + var currentlyDragging = this._drag[pointer.id]; + + var manager = this.manager; + + // 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 + + for (i = 0; i < previouslyOver.length; i++) + { + gameObject = previouslyOver[i]; + + if (currentlyOver.indexOf(gameObject) === -1 && currentlyDragging.indexOf(gameObject) === -1) + { + // Not in the currentlyOver array, so must be outside of this object now + justOut.push(gameObject); + } + else + { + // In the currentlyOver array + stillOver.push(gameObject); + } + } + + // 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 + for (i = 0; i < currentlyOver.length; i++) + { + gameObject = currentlyOver[i]; + + // Is this newly over? + + if (previouslyOver.indexOf(gameObject) === -1) + { + justOver.push(gameObject); + } + } + + // By this point the arrays are filled, so now we can process what happened... + + // Process the Just Out objects + var total = justOut.length; + + var totalInteracted = 0; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + if (total > 0) + { + this.sortGameObjects(justOut); + + // Call onOut for everything in the justOut array + for (i = 0; i < total; i++) + { + gameObject = justOut[i]; + + if (!gameObject.input) + { + continue; + } + + // Reset cursor before we emit the event, in case they want to change it during the event + manager.resetCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OUT, pointer, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OUT, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OUT, pointer, justOut); + } + } + + // Process the Just Over objects + total = justOver.length; + + _eventData.cancelled = false; + + aborted = false; + + if (total > 0) + { + this.sortGameObjects(justOver); + + // Call onOver for everything in the justOver array + for (i = 0; i < total; i++) + { + gameObject = justOver[i]; + + if (!gameObject.input) + { + continue; + } + + // Set cursor before we emit the event, in case they want to change it during the event + manager.setCursor(gameObject.input); + + gameObject.emit(Events.GAMEOBJECT_POINTER_OVER, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + totalInteracted++; + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_OVER, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + if (!aborted) + { + this.emit(Events.POINTER_OVER, pointer, justOver); + } + } + + // Add the contents of justOver to the previously over array + previouslyOver = stillOver.concat(justOver); + + // Then sort it into display list order + this._over[pointer.id] = this.sortGameObjects(previouslyOver); + + return totalInteracted; + }, + + /** + * An internal method that handles the Pointer up events. + * + * @method Phaser.Input.InputPlugin#processUpEvents + * @private + * @fires Phaser.Input.Events#GAMEOBJECT_POINTER_UP + * @fires Phaser.Input.Events#GAMEOBJECT_UP + * @fires Phaser.Input.Events#POINTER_UP + * @fires Phaser.Input.Events#POINTER_UP_OUTSIDE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The pointer to check for events against. + * + * @return {integer} The total number of objects interacted with. + */ + processUpEvents: function (pointer) + { + var currentlyOver = this._temp; + + var _eventData = this._eventData; + var _eventContainer = this._eventContainer; + + _eventData.cancelled = false; + + var aborted = false; + + // Go through all objects the pointer was over and fire their events / callbacks + for (var i = 0; i < currentlyOver.length; i++) + { + var gameObject = currentlyOver[i]; + + if (!gameObject.input) + { + continue; + } + + gameObject.emit(Events.GAMEOBJECT_POINTER_UP, pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + + this.emit(Events.GAMEOBJECT_UP, pointer, gameObject, _eventContainer); + + if (_eventData.cancelled || !gameObject.input) + { + aborted = true; + break; + } + } + + // If they released outside the canvas, but pressed down inside it, we'll still dispatch the event. + if (!aborted && this.manager) + { + if (pointer.upElement === this.manager.game.canvas) + { + this.emit(Events.POINTER_UP, pointer, currentlyOver); + } + else + { + this.emit(Events.POINTER_UP_OUTSIDE, pointer); + } + } + + return currentlyOver.length; + }, + + /** + * Queues a Game Object for insertion into this Input Plugin on the next update. + * + * @method Phaser.Input.InputPlugin#queueForInsertion + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to add. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + queueForInsertion: function (child) + { + if (this._pendingInsertion.indexOf(child) === -1 && this._list.indexOf(child) === -1) + { + this._pendingInsertion.push(child); + } + + return this; + }, + + /** + * Queues a Game Object for removal from this Input Plugin on the next update. + * + * @method Phaser.Input.InputPlugin#queueForRemoval + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object to remove. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + queueForRemoval: function (child) + { + this._pendingRemoval.push(child); + + return this; + }, + + /** + * Sets the draggable state of the given array of Game Objects. + * + * They can either be set to be draggable, or can have their draggable state removed by passing `false`. + * + * A Game Object will not fire drag events unless it has been specifically enabled for drag. + * + * @method Phaser.Input.InputPlugin#setDraggable + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to change the draggable state on. + * @param {boolean} [value=true] - Set to `true` if the Game Objects should be made draggable, `false` if they should be unset. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setDraggable: function (gameObjects, value) + { + if (value === undefined) { value = true; } + + if (!Array.isArray(gameObjects)) + { + gameObjects = [ gameObjects ]; + } + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + gameObject.input.draggable = value; + + var index = this._draggable.indexOf(gameObject); + + if (value && index === -1) + { + this._draggable.push(gameObject); + } + else if (!value && index > -1) + { + this._draggable.splice(index, 1); + } + } + + return this; + }, + + /** + * Creates a function that can be passed to `setInteractive`, `enable` or `setHitArea` that will handle + * pixel-perfect input detection on an Image or Sprite based Game Object, or any custom class that extends them. + * + * The following will create a sprite that is clickable on any pixel that has an alpha value >= 1. + * + * ```javascript + * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect()); + * ``` + * + * The following will create a sprite that is clickable on any pixel that has an alpha value >= 150. + * + * ```javascript + * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect(150)); + * ``` + * + * Once you have made an Interactive Object pixel perfect it impacts all input related events for it: down, up, + * dragstart, drag, etc. + * + * As a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from + * the given coordinates and checking its color values. This is an expensive process, so should only be enabled on + * Game Objects that really need it. + * + * You cannot make non-texture based Game Objects pixel perfect. So this will not work on Graphics, BitmapText, + * Render Textures, Text, Tilemaps, Containers or Particles. + * + * @method Phaser.Input.InputPlugin#makePixelPerfect + * @since 3.10.0 + * + * @param {integer} [alphaTolerance=1] - The alpha level that the pixel should be above to be included as a successful interaction. + * + * @return {function} A Pixel Perfect Handler for use as a hitArea shape callback. + */ + makePixelPerfect: function (alphaTolerance) + { + if (alphaTolerance === undefined) { alphaTolerance = 1; } + + var textureManager = this.systems.textures; + + return CreatePixelPerfectHandler(textureManager, alphaTolerance); + }, + + /** + * 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`. + * + * @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|any)} [shape] - 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} [callback] - The 'contains' function to invoke to check if the pointer is within the hit area. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitArea: function (gameObjects, shape, callback) + { + if (shape === undefined) + { + return this.setHitAreaFromTexture(gameObjects); + } + + if (!Array.isArray(gameObjects)) + { + gameObjects = [ gameObjects ]; + } + + var draggable = false; + var dropZone = false; + var cursor = false; + var useHandCursor = false; + var pixelPerfect = false; + var customHitArea = true; + + // Config object? + if (IsPlainObject(shape)) + { + var config = shape; + + shape = GetFastValue(config, 'hitArea', null); + callback = GetFastValue(config, 'hitAreaCallback', null); + draggable = GetFastValue(config, 'draggable', false); + dropZone = GetFastValue(config, 'dropZone', false); + cursor = GetFastValue(config, 'cursor', false); + useHandCursor = GetFastValue(config, 'useHandCursor', false); + + pixelPerfect = GetFastValue(config, 'pixelPerfect', false); + var alphaTolerance = GetFastValue(config, 'alphaTolerance', 1); + + if (pixelPerfect) + { + shape = {}; + callback = this.makePixelPerfect(alphaTolerance); + } + + // Still no hitArea or callback? + if (!shape || !callback) + { + this.setHitAreaFromTexture(gameObjects); + customHitArea = false; + } + } + else if (typeof shape === 'function' && !callback) + { + callback = shape; + shape = {}; + } + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + if (pixelPerfect && gameObject.type === 'Container') + { + console.warn('Cannot pixelPerfect test a Container. Use a custom callback.'); + continue; + } + + var io = (!gameObject.input) ? CreateInteractiveObject(gameObject, shape, callback) : gameObject.input; + + io.customHitArea = customHitArea; + io.dropZone = dropZone; + io.cursor = (useHandCursor) ? 'pointer' : cursor; + + gameObject.input = io; + + if (draggable) + { + this.setDraggable(gameObject); + } + + this.queueForInsertion(gameObject); + } + + return this; + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Circle` shape, using + * the given coordinates and radius to control its position and size. + * + * @method Phaser.Input.InputPlugin#setHitAreaCircle + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a circle hit area. + * @param {number} x - The center of the circle. + * @param {number} y - The center of the circle. + * @param {number} radius - The radius of the circle. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Circle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaCircle: function (gameObjects, x, y, radius, callback) + { + if (callback === undefined) { callback = CircleContains; } + + var shape = new Circle(x, y, radius); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Ellipse` shape, using + * the given coordinates and dimensions to control its position and size. + * + * @method Phaser.Input.InputPlugin#setHitAreaEllipse + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having an ellipse hit area. + * @param {number} x - The center of the ellipse. + * @param {number} y - The center of the ellipse. + * @param {number} width - The width of the ellipse. + * @param {number} height - The height of the ellipse. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Ellipse.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaEllipse: function (gameObjects, x, y, width, height, callback) + { + if (callback === undefined) { callback = EllipseContains; } + + var shape = new Ellipse(x, y, width, height); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * 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 an ellipse hit area. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaFromTexture: function (gameObjects, callback) + { + if (callback === undefined) { callback = RectangleContains; } + + if (!Array.isArray(gameObjects)) + { + gameObjects = [ gameObjects ]; + } + + for (var i = 0; i < gameObjects.length; i++) + { + var gameObject = gameObjects[i]; + + var frame = gameObject.frame; + + var width = 0; + var height = 0; + + if (gameObject.width) + { + width = gameObject.width; + height = gameObject.height; + } + else if (frame) + { + width = frame.realWidth; + height = frame.realHeight; + } + + if (gameObject.type === 'Container' && (width === 0 || height === 0)) + { + console.warn('Container.setInteractive must specify a Shape or call setSize() first'); + continue; + } + + if (width !== 0 && height !== 0) + { + gameObject.input = CreateInteractiveObject(gameObject, new Rectangle(0, 0, width, height), callback); + + this.queueForInsertion(gameObject); + } + } + + return this; + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Rectangle` shape, using + * the given coordinates and dimensions to control its position and size. + * + * @method Phaser.Input.InputPlugin#setHitAreaRectangle + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a rectangular hit area. + * @param {number} x - The top-left of the rectangle. + * @param {number} y - The top-left of the rectangle. + * @param {number} width - The width of the rectangle. + * @param {number} height - The height of the rectangle. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaRectangle: function (gameObjects, x, y, width, height, callback) + { + if (callback === undefined) { callback = RectangleContains; } + + var shape = new Rectangle(x, y, width, height); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Triangle` shape, using + * the given coordinates to control the position of its points. + * + * @method Phaser.Input.InputPlugin#setHitAreaTriangle + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a triangular hit area. + * @param {number} x1 - The x coordinate of the first point of the triangle. + * @param {number} y1 - The y coordinate of the first point of the triangle. + * @param {number} x2 - The x coordinate of the second point of the triangle. + * @param {number} y2 - The y coordinate of the second point of the triangle. + * @param {number} x3 - The x coordinate of the third point of the triangle. + * @param {number} y3 - The y coordinate of the third point of the triangle. + * @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Triangle.Contains. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setHitAreaTriangle: function (gameObjects, x1, y1, x2, y2, x3, y3, callback) + { + if (callback === undefined) { callback = TriangleContains; } + + var shape = new Triangle(x1, y1, x2, y2, x3, y3); + + return this.setHitArea(gameObjects, shape, callback); + }, + + /** + * Creates an Input Debug Shape for the given Game Object. + * + * The Game Object must have _already_ been enabled for input prior to calling this method. + * + * This is intended to assist you during development and debugging. + * + * Debug Shapes can only be created for Game Objects that are using standard Phaser Geometry for input, + * including: Circle, Ellipse, Line, Polygon, Rectangle and Triangle. + * + * Game Objects that are using their automatic hit areas are using Rectangles by default, so will also work. + * + * The Debug Shape is created and added to the display list and is then kept in sync with the Game Object + * it is connected with. Should you need to modify it yourself, such as to hide it, you can access it via + * the Game Object property: `GameObject.input.hitAreaDebug`. + * + * Calling this method on a Game Object that already has a Debug Shape will first destroy the old shape, + * before creating a new one. If you wish to remove the Debug Shape entirely, you should call the + * method `InputPlugin.removeDebug`. + * + * Note that the debug shape will only show the outline of the input area. If the input test is using a + * pixel perfect check, for example, then this is not displayed. If you are using a custom shape, that + * doesn't extend one of the base Phaser Geometry objects, as your hit area, then this method will not + * work. + * + * @method Phaser.Input.InputPlugin#enableDebug + * @since 3.19.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to create the input debug shape for. + * @param {number} [color=0x00ff00] - The outline color of the debug shape. + * + * @return {Phaser.Input.InputPlugin} This Input Plugin. + */ + enableDebug: function (gameObject, color) + { + if (color === undefined) { color = 0x00ff00; } + + var input = gameObject.input; + + if (!input || !input.hitArea) + { + return this; + } + + var shape = input.hitArea; + var shapeType = shape.type; + var debug = input.hitAreaDebug; + var factory = this.systems.add; + var updateList = this.systems.updateList; + + if (debug) + { + updateList.remove(debug); + + debug.destroy(); + + debug = null; + } + + var offsetx = 0; + var offsety = 0; + switch (shapeType) + { + case GEOM_CONST.CIRCLE: + debug = factory.arc(0, 0, shape.radius); + offsetx = shape.x - shape.radius; + offsety = shape.y - shape.radius; + break; + + case GEOM_CONST.ELLIPSE: + debug = factory.ellipse(0, 0, shape.width, shape.height); + offsetx = shape.x - shape.width / 2; + offsety = shape.y - shape.height / 2; + break; + + case GEOM_CONST.LINE: + debug = factory.line(0, 0, shape.x1, shape.y1, shape.x2, shape.y2); + break; + + case GEOM_CONST.POLYGON: + debug = factory.polygon(0, 0, shape.points); + break; + + case GEOM_CONST.RECTANGLE: + debug = factory.rectangle(0, 0, shape.width, shape.height); + offsetx = shape.x; + offsety = shape.y; + break; + + case GEOM_CONST.TRIANGLE: + debug = factory.triangle(0, 0, shape.x1, shape.y1, shape.x2, shape.y2, shape.x3, shape.y3); + break; + } + + if (debug) + { + debug.isFilled = false; + + debug.preUpdate = function () + { + debug.setStrokeStyle(1 / gameObject.scale, color); + + debug.setDisplayOrigin(gameObject.displayOriginX, gameObject.displayOriginY); + debug.setRotation(gameObject.rotation); + debug.setScale(gameObject.scaleX, gameObject.scaleY); + debug.setPosition(gameObject.x + offsetx, gameObject.y + offsety); + debug.setScrollFactor(gameObject.scrollFactorX, gameObject.scrollFactorY); + }; + + updateList.add(debug); + + input.hitAreaDebug = debug; + } + + return this; + }, + + /** + * Removes an Input Debug Shape from the given Game Object. + * + * The shape is destroyed immediately and the `hitAreaDebug` property is set to `null`. + * + * @method Phaser.Input.InputPlugin#removeDebug + * @since 3.19.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to remove the input debug shape from. + * + * @return {Phaser.Input.InputPlugin} This Input Plugin. + */ + removeDebug: function (gameObject) + { + var input = gameObject.input; + + if (input && input.hitAreaDebug) + { + var debug = input.hitAreaDebug; + + this.systems.updateList.remove(debug); + + debug.destroy(); + + input.hitAreaDebug = null; + } + + return this; + }, + + /** + * Sets the Pointers to always poll. + * + * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, + * or being interacted with it, regardless if the Pointer has actually moved or not. + * + * You should enable this if you want objects in your game to fire over / out events, and the objects + * are constantly moving, but the pointer may not have. Polling every frame has additional computation + * costs, especially if there are a large number of interactive objects in your game. + * + * @method Phaser.Input.InputPlugin#setPollAlways + * @since 3.0.0 + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setPollAlways: function () + { + return this.setPollRate(0); + }, + + /** + * Sets the Pointers to only poll when they are moved or updated. + * + * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, + * or being interacted with it. + * + * @method Phaser.Input.InputPlugin#setPollOnMove + * @since 3.0.0 + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setPollOnMove: function () + { + return this.setPollRate(-1); + }, + + /** + * Sets the poll rate value. This is the amount of time that should have elapsed before a pointer + * will be polled again. See the `setPollAlways` and `setPollOnMove` methods. + * + * @method Phaser.Input.InputPlugin#setPollRate + * @since 3.0.0 + * + * @param {number} value - The amount of time, in ms, that should elapsed before re-polling the pointers. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setPollRate: function (value) + { + this.pollRate = value; + this._pollTimer = 0; + + return this; + }, + + /** + * When set to `true` the global Input Manager will emulate DOM behavior by only emitting events from + * the top-most Scene in the Scene List. By default, if a Scene receives an input event it will then stop the event + * from flowing down to any Scenes below it in the Scene list. To disable this behavior call this method with `false`. + * + * @method Phaser.Input.InputPlugin#setGlobalTopOnly + * @since 3.0.0 + * + * @param {boolean} value - Set to `true` to stop processing input events on the Scene that receives it, or `false` to let the event continue down the Scene list. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setGlobalTopOnly: function (value) + { + this.manager.globalTopOnly = value; + + return this; + }, + + /** + * When set to `true` this Input Plugin will emulate DOM behavior by only emitting events from + * the top-most Game Objects in the Display List. + * + * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. + * + * @method Phaser.Input.InputPlugin#setTopOnly + * @since 3.0.0 + * + * @param {boolean} value - `true` to only include the top-most Game Object, or `false` to include all Game Objects in a hit test. + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + setTopOnly: function (value) + { + this.topOnly = value; + + return this; + }, + + /** + * Given an array of Game Objects, sort the array and return it, so that the objects are in depth index order + * with the lowest at the bottom. + * + * @method Phaser.Input.InputPlugin#sortGameObjects + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject[]} gameObjects - An array of Game Objects to be sorted. + * + * @return {Phaser.GameObjects.GameObject[]} The sorted array of Game Objects. + */ + sortGameObjects: function (gameObjects) + { + if (gameObjects.length < 2) + { + return gameObjects; + } + + this.scene.sys.depthSort(); + + return gameObjects.sort(this.sortHandlerGO.bind(this)); + }, + + /** + * Return the child lowest down the display list (with the smallest index) + * Will iterate through all parent containers, if present. + * + * @method Phaser.Input.InputPlugin#sortHandlerGO + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} childA - The first Game Object to compare. + * @param {Phaser.GameObjects.GameObject} childB - The second Game Object to compare. + * + * @return {integer} Returns either a negative or positive integer, or zero if they match. + */ + sortHandlerGO: function (childA, childB) + { + if (!childA.parentContainer && !childB.parentContainer) + { + // Quick bail out when neither child has a container + return this.displayList.getIndex(childB) - this.displayList.getIndex(childA); + } + else if (childA.parentContainer === childB.parentContainer) + { + // Quick bail out when both children have the same container + return childB.parentContainer.getIndex(childB) - childA.parentContainer.getIndex(childA); + } + else if (childA.parentContainer === childB) + { + // Quick bail out when childA is a child of childB + return -1; + } + else if (childB.parentContainer === childA) + { + // Quick bail out when childA is a child of childB + return 1; + } + else + { + // Container index check + var listA = childA.getIndexList(); + var listB = childB.getIndexList(); + var len = Math.min(listA.length, listB.length); + + for (var i = 0; i < len; i++) + { + var indexA = listA[i]; + var indexB = listB[i]; + + if (indexA === indexB) + { + // Go to the next level down + continue; + } + else + { + // Non-matching parents, so return + return indexB - indexA; + } + } + } + + // Technically this shouldn't happen, but ... + return 0; + }, + + /** + * This method should be called from within an input event handler, such as `pointerdown`. + * + * When called, it stops the Input Manager from allowing _this specific event_ to be processed by any other Scene + * not yet handled in the scene list. + * + * @method Phaser.Input.InputPlugin#stopPropagation + * @since 3.0.0 + * + * @return {Phaser.Input.InputPlugin} This InputPlugin object. + */ + stopPropagation: function () + { + this.manager._tempSkip = true; + + return this; + }, + + /** + * Adds new Pointer objects to the Input Manager. + * + * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. + * + * You can create more either by calling this method, or by setting the `input.activePointers` property + * in the Game Config, up to a maximum of 10 pointers. + * + * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added + * via this method. + * + * @method Phaser.Input.InputPlugin#addPointer + * @since 3.10.0 + * + * @param {integer} [quantity=1] The number of new Pointers to create. A maximum of 10 is allowed in total. + * + * @return {Phaser.Input.Pointer[]} An array containing all of the new Pointer objects that were created. + */ + addPointer: function (quantity) + { + return this.manager.addPointer(quantity); + }, + + /** + * 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 {Phaser.Input.InputPlugin} This Input instance. + */ + setDefaultCursor: function (cursor) + { + this.manager.setDefaultCursor(cursor); + + return this; + }, + + /** + * The Scene that owns this plugin is transitioning in. + * + * @method Phaser.Input.InputPlugin#transitionIn + * @private + * @since 3.5.0 + */ + transitionIn: function () + { + this.enabled = this.settings.transitionAllowInput; + }, + + /** + * The Scene that owns this plugin has finished transitioning in. + * + * @method Phaser.Input.InputPlugin#transitionComplete + * @private + * @since 3.5.0 + */ + transitionComplete: function () + { + if (!this.settings.transitionAllowInput) + { + this.enabled = true; + } + }, + + /** + * The Scene that owns this plugin is transitioning out. + * + * @method Phaser.Input.InputPlugin#transitionOut + * @private + * @since 3.5.0 + */ + transitionOut: function () + { + this.enabled = this.settings.transitionAllowInput; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Input.InputPlugin#shutdown + * @fires Phaser.Input.Events#SHUTDOWN + * @private + * @since 3.0.0 + */ + shutdown: function () + { + // Registered input plugins listen for this + this.pluginEvents.emit(Events.SHUTDOWN); + + this._temp.length = 0; + this._list.length = 0; + this._draggable.length = 0; + this._pendingRemoval.length = 0; + this._pendingInsertion.length = 0; + this._dragState.length = 0; + + for (var i = 0; i < 10; i++) + { + this._drag[i] = []; + this._over[i] = []; + } + + this.removeAllListeners(); + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.TRANSITION_START, this.transitionIn, this); + eventEmitter.off(SceneEvents.TRANSITION_OUT, this.transitionOut, this); + eventEmitter.off(SceneEvents.TRANSITION_COMPLETE, this.transitionComplete, this); + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + + this.manager.events.off(Events.GAME_OUT, this.onGameOut, this); + this.manager.events.off(Events.GAME_OVER, this.onGameOver, this); + + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Input.InputPlugin#destroy + * @fires Phaser.Input.Events#DESTROY + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + // Registered input plugins listen for this + this.pluginEvents.emit(Events.DESTROY); + + this.pluginEvents.removeAllListeners(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.cameras = null; + this.manager = null; + this.events = null; + this.mouse = null; + }, + + /** + * The x coordinates 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 + */ + x: { + + get: function () + { + return this.manager.activePointer.x; + } + + }, + + /** + * The y coordinates 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 + */ + y: { + + get: function () + { + return this.manager.activePointer.y; + } + + }, + + /** + * Are any mouse or touch pointers currently over the game canvas? + * + * @name Phaser.Input.InputPlugin#isOver + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isOver: { + + get: function () + { + return this.manager.isOver; + } + + }, + + /** + * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. + * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` + * which will always map to the most recently interacted pointer. + * + * @name Phaser.Input.InputPlugin#mousePointer + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + mousePointer: { + + get: function () + { + return this.manager.mousePointer; + } + + }, + + /** + * The current active input Pointer. + * + * @name Phaser.Input.InputPlugin#activePointer + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.0.0 + */ + activePointer: { + + get: function () + { + return this.manager.activePointer; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer1 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer1: { + + get: function () + { + return this.manager.pointers[1]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer2 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer2: { + + get: function () + { + return this.manager.pointers[2]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer3 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer3: { + + get: function () + { + return this.manager.pointers[3]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer4 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer4: { + + get: function () + { + return this.manager.pointers[4]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer5 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer5: { + + get: function () + { + return this.manager.pointers[5]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer6 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer6: { + + get: function () + { + return this.manager.pointers[6]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer7 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer7: { + + get: function () + { + return this.manager.pointers[7]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer8 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer8: { + + get: function () + { + return this.manager.pointers[8]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer9 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer9: { + + get: function () + { + return this.manager.pointers[9]; + } + + }, + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + * + * @name Phaser.Input.InputPlugin#pointer10 + * @type {Phaser.Input.Pointer} + * @readonly + * @since 3.10.0 + */ + pointer10: { + + get: function () + { + return this.manager.pointers[10]; + } + + } + +}); + +PluginCache.register('InputPlugin', InputPlugin, 'input'); + +module.exports = InputPlugin; diff --git a/src/input/InputPluginCache.js b/src/input/InputPluginCache.js index 37a2f1c15..a3ec8e824 100644 --- a/src/input/InputPluginCache.js +++ b/src/input/InputPluginCache.js @@ -1,102 +1,102 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetValue = require('../utils/object/GetValue'); - -// Contains the plugins that Phaser uses globally and locally. -// These are the source objects, not instantiated. -var inputPlugins = {}; - -/** - * @namespace Phaser.Input.InputPluginCache - */ - -var InputPluginCache = {}; - -/** - * Static method called directly by the Core internal Plugins. - * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) - * Plugin is the object to instantiate to create the plugin - * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) - * - * @function Phaser.Input.InputPluginCache.register - * @static - * @since 3.10.0 - * - * @param {string} key - A reference used to get this plugin from the plugin cache. - * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. - * @param {string} mapping - If this plugin is to be injected into the Input Plugin, this is the property key used. - * @param {string} settingsKey - The key in the Scene Settings to check to see if this plugin should install or not. - * @param {string} configKey - The key in the Game Config to check to see if this plugin should install or not. - */ -InputPluginCache.register = function (key, plugin, mapping, settingsKey, configKey) -{ - inputPlugins[key] = { plugin: plugin, mapping: mapping, settingsKey: settingsKey, configKey: configKey }; -}; - -/** - * Returns the input plugin object from the cache based on the given key. - * - * @function Phaser.Input.InputPluginCache.getCore - * @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. - */ -InputPluginCache.getPlugin = function (key) -{ - return inputPlugins[key]; -}; - -/** - * Installs all of the registered Input Plugins into the given target. - * - * @function Phaser.Input.InputPluginCache.install - * @static - * @since 3.10.0 - * - * @param {Phaser.Input.InputPlugin} target - The target InputPlugin to install the plugins into. - */ -InputPluginCache.install = function (target) -{ - var sys = target.scene.sys; - var settings = sys.settings.input; - var config = sys.game.config; - - for (var key in inputPlugins) - { - var source = inputPlugins[key].plugin; - var mapping = inputPlugins[key].mapping; - var settingsKey = inputPlugins[key].settingsKey; - var configKey = inputPlugins[key].configKey; - - if (GetValue(settings, settingsKey, config[configKey])) - { - target[mapping] = new source(target); - } - } -}; - -/** - * 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. - */ -InputPluginCache.remove = function (key) -{ - if (inputPlugins.hasOwnProperty(key)) - { - delete inputPlugins[key]; - } -}; - -module.exports = InputPluginCache; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = require('../utils/object/GetValue'); + +// Contains the plugins that Phaser uses globally and locally. +// These are the source objects, not instantiated. +var inputPlugins = {}; + +/** + * @namespace Phaser.Input.InputPluginCache + */ + +var InputPluginCache = {}; + +/** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * + * @function Phaser.Input.InputPluginCache.register + * @static + * @since 3.10.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Input Plugin, this is the property key used. + * @param {string} settingsKey - The key in the Scene Settings to check to see if this plugin should install or not. + * @param {string} configKey - The key in the Game Config to check to see if this plugin should install or not. + */ +InputPluginCache.register = function (key, plugin, mapping, settingsKey, configKey) +{ + inputPlugins[key] = { plugin: plugin, mapping: mapping, settingsKey: settingsKey, configKey: configKey }; +}; + +/** + * Returns the input plugin object from the cache based on the given key. + * + * @function Phaser.Input.InputPluginCache.getCore + * @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. + */ +InputPluginCache.getPlugin = function (key) +{ + return inputPlugins[key]; +}; + +/** + * Installs all of the registered Input Plugins into the given target. + * + * @function Phaser.Input.InputPluginCache.install + * @static + * @since 3.10.0 + * + * @param {Phaser.Input.InputPlugin} target - The target InputPlugin to install the plugins into. + */ +InputPluginCache.install = function (target) +{ + var sys = target.scene.sys; + var settings = sys.settings.input; + var config = sys.game.config; + + for (var key in inputPlugins) + { + var source = inputPlugins[key].plugin; + var mapping = inputPlugins[key].mapping; + var settingsKey = inputPlugins[key].settingsKey; + var configKey = inputPlugins[key].configKey; + + if (GetValue(settings, settingsKey, config[configKey])) + { + target[mapping] = new source(target); + } + } +}; + +/** + * 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. + */ +InputPluginCache.remove = function (key) +{ + if (inputPlugins.hasOwnProperty(key)) + { + delete inputPlugins[key]; + } +}; + +module.exports = InputPluginCache; diff --git a/src/input/Pointer.js b/src/input/Pointer.js index 3c2ee6fa7..38f61d671 100644 --- a/src/input/Pointer.js +++ b/src/input/Pointer.js @@ -1,1272 +1,1272 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Angle = require('../math/angle/Between'); -var Class = require('../utils/Class'); -var Distance = require('../math/distance/DistanceBetween'); -var FuzzyEqual = require('../math/fuzzy/Equal'); -var SmoothStepInterpolation = require('../math/interpolation/SmoothStepInterpolation'); -var Vector2 = require('../math/Vector2'); - -/** - * @classdesc - * A Pointer object encapsulates both mouse and touch input within Phaser. - * - * By default, Phaser will create 2 pointers for your game to use. If you require more, i.e. for a multi-touch - * game, then use the `InputPlugin.addPointer` method to do so, rather than instantiating this class directly, - * otherwise it won't be managed by the input system. - * - * You can reference the current active pointer via `InputPlugin.activePointer`. You can also use the properties - * `InputPlugin.pointer1` through to `pointer10`, for each pointer you have enabled in your game. - * - * The properties of this object are set by the Input Plugin during processing. This object is then sent in all - * input related events that the Input Plugin emits, so you can reference properties from it directly in your - * callbacks. - * - * @class Pointer - * @memberof Phaser.Input - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.InputManager} manager - A reference to the Input Manager. - * @param {integer} id - The internal ID of this Pointer. - */ -var Pointer = new Class({ - - initialize: - - function Pointer (manager, id) - { - /** - * A reference to the Input Manager. - * - * @name Phaser.Input.Pointer#manager - * @type {Phaser.Input.InputManager} - * @since 3.0.0 - */ - this.manager = manager; - - /** - * The internal ID of this Pointer. - * - * @name Phaser.Input.Pointer#id - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.id = id; - - /** - * The most recent native DOM Event this Pointer has processed. - * - * @name Phaser.Input.Pointer#event - * @type {(TouchEvent|MouseEvent)} - * @since 3.0.0 - */ - this.event; - - /** - * 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 - */ - this.downElement; - - /** - * 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 - */ - this.upElement; - - /** - * The camera the Pointer interacted with during its last update. - * - * A Pointer can only ever interact with one camera at once, which will be the top-most camera - * in the list should multiple cameras be positioned on-top of each other. - * - * @name Phaser.Input.Pointer#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @default null - * @since 3.0.0 - */ - this.camera = null; - - /** - * A read-only property that indicates which button was pressed, or released, on the pointer - * during the most recent event. It is only set during `up` and `down` events. - * - * On Touch devices the value is always 0. - * - * Users may change the configuration of buttons on their pointing device so that if an event's button property - * is zero, it may not have been caused by the button that is physically left–most on the pointing device; - * however, it should behave as if the left button was clicked in the standard button layout. - * - * @name Phaser.Input.Pointer#button - * @type {integer} - * @readonly - * @default 0 - * @since 3.18.0 - */ - this.button = 0; - - /** - * 0: No button or un-initialized - * 1: Left button - * 2: Right button - * 4: Wheel button or middle button - * 8: 4th button (typically the "Browser Back" button) - * 16: 5th button (typically the "Browser Forward" button) - * - * For a mouse configured for left-handed use, the button actions are reversed. - * In this case, the values are read from right to left. - * - * @name Phaser.Input.Pointer#buttons - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.buttons = 0; - - /** - * The position of the Pointer in screen space. - * - * @name Phaser.Input.Pointer#position - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.0.0 - */ - this.position = new Vector2(); - - /** - * The previous position of the Pointer in screen space. - * - * The old x and y values are stored in here during the InputManager.transformPointer call. - * - * Use the properties `velocity`, `angle` and `distance` to create your own gesture recognition. - * - * @name Phaser.Input.Pointer#prevPosition - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.11.0 - */ - this.prevPosition = new Vector2(); - - /** - * An internal vector used for calculations of the pointer speed and angle. - * - * @name Phaser.Input.Pointer#midPoint - * @type {Phaser.Math.Vector2} - * @private - * @since 3.16.0 - */ - this.midPoint = new Vector2(-1, -1); - - /** - * 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 - */ - this.velocity = new Vector2(); - - /** - * 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 - */ - this.angle = 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 buttons was pressed down, - * then use the `Pointer.getDistance` method. - * - * @name Phaser.Input.Pointer#distance - * @type {number} - * @readonly - * @since 3.16.0 - */ - this.distance = 0; - - /** - * The smoothing factor to apply to the Pointer position. - * - * Due to their nature, pointer positions are inherently noisy. While this is fine for lots of games, if you need cleaner positions - * then you can set this value to apply an automatic smoothing to the positions as they are recorded. - * - * The default value of zero means 'no smoothing'. - * Set to a small value, such as 0.2, to apply an average level of smoothing between positions. You can do this by changing this - * value directly, or by setting the `input.smoothFactor` property in the Game Config. - * - * Positions are only smoothed when the pointer moves. If the primary button on this Pointer enters an Up or Down state, then the position - * is always precise, and not smoothed. - * - * @name Phaser.Input.Pointer#smoothFactor - * @type {number} - * @default 0 - * @since 3.16.0 - */ - this.smoothFactor = 0; - - /** - * The factor applied to the motion smoothing each frame. - * - * This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, - * angle and distance of the Pointer. It's applied every frame, until the midPoint reaches the current - * position of the Pointer. 0.2 provides a good average but can be increased if you need a - * quicker update and are working in a high performance environment. Never set this value to - * zero. - * - * @name Phaser.Input.Pointer#motionFactor - * @type {number} - * @default 0.2 - * @since 3.16.0 - */ - this.motionFactor = 0.2; - - /** - * The x position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. - * - * If you wish to use this value _outside_ of an input event handler then you should update it first by calling - * the `Pointer.updateWorldPoint` method. - * - * @name Phaser.Input.Pointer#worldX - * @type {number} - * @default 0 - * @since 3.10.0 - */ - this.worldX = 0; - - /** - * The y position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. - * - * If you wish to use this value _outside_ of an input event handler then you should update it first by calling - * the `Pointer.updateWorldPoint` method. - * - * @name Phaser.Input.Pointer#worldY - * @type {number} - * @default 0 - * @since 3.10.0 - */ - this.worldY = 0; - - /** - * Time when this Pointer was most recently moved (regardless of the state of its buttons, if any) - * - * @name Phaser.Input.Pointer#moveTime - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.moveTime = 0; - - /** - * X coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. - * - * @name Phaser.Input.Pointer#downX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.downX = 0; - - /** - * Y coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. - * - * @name Phaser.Input.Pointer#downY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.downY = 0; - - /** - * Time when Button 1 (left button), or Touch, was pressed, used for dragging objects. - * - * @name Phaser.Input.Pointer#downTime - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.downTime = 0; - - /** - * X coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. - * - * @name Phaser.Input.Pointer#upX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.upX = 0; - - /** - * Y coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. - * - * @name Phaser.Input.Pointer#upY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.upY = 0; - - /** - * Time when Button 1 (left button), or Touch, was released, used for dragging objects. - * - * @name Phaser.Input.Pointer#upTime - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.upTime = 0; - - /** - * Is the primary button down? (usually button 0, the left mouse button) - * - * @name Phaser.Input.Pointer#primaryDown - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.primaryDown = false; - - /** - * Is _any_ button on this pointer considered as being down? - * - * @name Phaser.Input.Pointer#isDown - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isDown = false; - - /** - * Did the previous input event come from a Touch input (true) or Mouse? (false) - * - * @name Phaser.Input.Pointer#wasTouch - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.wasTouch = false; - - /** - * Did this Pointer get canceled by a touchcancel event? - * - * Note: "canceled" is the American-English spelling of "cancelled". Please don't submit PRs correcting it! - * - * @name Phaser.Input.Pointer#wasCanceled - * @type {boolean} - * @default false - * @since 3.15.0 - */ - this.wasCanceled = false; - - /** - * If the mouse is locked, the horizontal relative movement of the Pointer in pixels since last frame. - * - * @name Phaser.Input.Pointer#movementX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.movementX = 0; - - /** - * If the mouse is locked, the vertical relative movement of the Pointer in pixels since last frame. - * - * @name Phaser.Input.Pointer#movementY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.movementY = 0; - - /** - * The identifier property of the Pointer as set by the DOM event when this Pointer is started. - * - * @name Phaser.Input.Pointer#identifier - * @type {number} - * @since 3.10.0 - */ - this.identifier = 0; - - /** - * The pointerId property of the Pointer as set by the DOM event when this Pointer is started. - * The browser can and will recycle this value. - * - * @name Phaser.Input.Pointer#pointerId - * @type {number} - * @since 3.10.0 - */ - this.pointerId = null; - - /** - * An active Pointer is one that is currently pressed down on the display. - * A Mouse is always considered as active. - * - * @name Phaser.Input.Pointer#active - * @type {boolean} - * @since 3.10.0 - */ - this.active = (id === 0) ? true : false; - - /** - * Is this pointer Pointer Locked? - * - * Only a mouse pointer can be locked and it only becomes locked when requested via - * the browsers Pointer Lock API. - * - * You can request this by calling the `this.input.mouse.requestPointerLock()` method from - * a `pointerdown` or `pointerup` event handler. - * - * @name Phaser.Input.Pointer#locked - * @readonly - * @type {boolean} - * @since 3.19.0 - */ - this.locked = false; - - /** - * The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * - * @name Phaser.Input.Pointer#deltaX - * @type {number} - * @default 0 - * @since 3.18.0 - */ - this.deltaX = 0; - - /** - * The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. - * - * @name Phaser.Input.Pointer#deltaY - * @type {number} - * @default 0 - * @since 3.18.0 - */ - this.deltaY = 0; - - /** - * The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * - * @name Phaser.Input.Pointer#deltaZ - * @type {number} - * @default 0 - * @since 3.18.0 - */ - this.deltaZ = 0; - }, - - /** - * Takes a Camera and updates this Pointer's `worldX` and `worldY` values so they are - * the result of a translation through the given Camera. - * - * Note that the values will be automatically replaced the moment the Pointer is - * updated by an input event, such as a mouse move, so should be used immediately. - * - * @method Phaser.Input.Pointer#updateWorldPoint - * @since 3.19.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. - * - * @return {this} This Pointer object. - */ - updateWorldPoint: function (camera) - { - var x = this.x; - var y = this.y; - - if (camera.resolution !== 1) - { - x += camera._x; - y += camera._y; - } - - // Stores the world point inside of tempPoint - var temp = camera.getWorldPoint(x, y); - - this.worldX = temp.x; - this.worldY = temp.y; - - return this; - }, - - /** - * 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. - */ - positionToCamera: function (camera, output) - { - return camera.getWorldPoint(this.x, this.y, output); - }, - - /** - * Calculates the motion of this Pointer, including its velocity and angle of movement. - * This method is called automatically each frame by the Input Manager. - * - * @method Phaser.Input.Pointer#updateMotion - * @private - * @since 3.16.0 - */ - updateMotion: function () - { - var cx = this.position.x; - var cy = this.position.y; - - var mx = this.midPoint.x; - var my = this.midPoint.y; - - if (cx === mx && cy === my) - { - // Nothing to do here - return; - } - - // Moving towards our goal ... - var vx = SmoothStepInterpolation(this.motionFactor, mx, cx); - var vy = SmoothStepInterpolation(this.motionFactor, my, cy); - - if (FuzzyEqual(vx, cx, 0.1)) - { - vx = cx; - } - - if (FuzzyEqual(vy, cy, 0.1)) - { - vy = cy; - } - - this.midPoint.set(vx, vy); - - var dx = cx - vx; - var dy = cy - vy; - - this.velocity.set(dx, dy); - - this.angle = Angle(vx, vy, cx, cy); - - this.distance = Math.sqrt(dx * dx + dy * dy); - }, - - /** - * Internal method to handle a Mouse Up Event. - * - * @method Phaser.Input.Pointer#up - * @private - * @since 3.0.0 - * - * @param {MouseEvent} event - The Mouse Event to process. - */ - up: function (event) - { - if ('buttons' in event) - { - this.buttons = event.buttons; - } - - this.event = event; - - this.button = event.button; - - this.upElement = event.target; - - // Sets the local x/y properties - this.manager.transformPointer(this, event.pageX, event.pageY, false); - - // 0: Main button pressed, usually the left button or the un-initialized state - if (event.button === 0) - { - this.primaryDown = false; - this.upX = this.x; - this.upY = this.y; - this.upTime = event.timeStamp; - } - - this.isDown = false; - - this.wasTouch = false; - }, - - /** - * Internal method to handle a Mouse Down Event. - * - * @method Phaser.Input.Pointer#down - * @private - * @since 3.0.0 - * - * @param {MouseEvent} event - The Mouse Event to process. - */ - down: function (event) - { - if ('buttons' in event) - { - this.buttons = event.buttons; - } - - this.event = event; - - this.button = event.button; - - this.downElement = event.target; - - // Sets the local x/y properties - this.manager.transformPointer(this, event.pageX, event.pageY, false); - - // 0: Main button pressed, usually the left button or the un-initialized state - if (event.button === 0) - { - this.primaryDown = true; - this.downX = this.x; - this.downY = this.y; - this.downTime = event.timeStamp; - } - - this.isDown = true; - - this.wasTouch = false; - }, - - /** - * Internal method to handle a Mouse Move Event. - * - * @method Phaser.Input.Pointer#move - * @private - * @since 3.0.0 - * - * @param {MouseEvent} event - The Mouse Event to process. - */ - move: function (event) - { - if ('buttons' in event) - { - this.buttons = event.buttons; - } - - this.event = event; - - // Sets the local x/y properties - this.manager.transformPointer(this, event.pageX, event.pageY, true); - - if (this.locked) - { - // Multiple DOM events may occur within one frame, but only one Phaser event will fire - this.movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; - this.movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; - } - - this.moveTime = event.timeStamp; - - this.wasTouch = false; - }, - - /** - * Internal method to handle a Mouse Wheel Event. - * - * @method Phaser.Input.Pointer#wheel - * @private - * @since 3.18.0 - * - * @param {WheelEvent} event - The Wheel Event to process. - */ - wheel: function (event) - { - if ('buttons' in event) - { - this.buttons = event.buttons; - } - - this.event = event; - - // Sets the local x/y properties - this.manager.transformPointer(this, event.pageX, event.pageY, false); - - this.deltaX = event.deltaX; - this.deltaY = event.deltaY; - this.deltaZ = event.deltaZ; - - this.wasTouch = false; - }, - - /** - * Internal method to handle a Touch Start Event. - * - * @method Phaser.Input.Pointer#touchstart - * @private - * @since 3.0.0 - * - * @param {Touch} touch - The Changed Touch from the Touch Event. - * @param {TouchEvent} event - The full Touch Event. - */ - touchstart: function (touch, event) - { - if (touch['pointerId']) - { - this.pointerId = touch.pointerId; - } - - this.identifier = touch.identifier; - this.target = touch.target; - this.active = true; - - this.buttons = 1; - - this.event = event; - - this.downElement = touch.target; - - // Sets the local x/y properties - this.manager.transformPointer(this, touch.pageX, touch.pageY, false); - - this.primaryDown = true; - this.downX = this.x; - this.downY = this.y; - this.downTime = event.timeStamp; - - this.isDown = true; - - this.wasTouch = true; - this.wasCanceled = false; - - this.updateMotion(); - }, - - /** - * Internal method to handle a Touch Move Event. - * - * @method Phaser.Input.Pointer#touchmove - * @private - * @since 3.0.0 - * - * @param {Touch} touch - The Changed Touch from the Touch Event. - * @param {TouchEvent} event - The full Touch Event. - */ - touchmove: function (touch, event) - { - this.event = event; - - // Sets the local x/y properties - this.manager.transformPointer(this, touch.pageX, touch.pageY, true); - - this.moveTime = event.timeStamp; - - this.wasTouch = true; - - this.updateMotion(); - }, - - /** - * Internal method to handle a Touch End Event. - * - * @method Phaser.Input.Pointer#touchend - * @private - * @since 3.0.0 - * - * @param {Touch} touch - The Changed Touch from the Touch Event. - * @param {TouchEvent} event - The full Touch Event. - */ - touchend: function (touch, event) - { - this.buttons = 0; - - this.event = event; - - this.upElement = touch.target; - - // Sets the local x/y properties - this.manager.transformPointer(this, touch.pageX, touch.pageY, false); - - this.primaryDown = false; - this.upX = this.x; - this.upY = this.y; - this.upTime = event.timeStamp; - - this.isDown = false; - - this.wasTouch = true; - this.wasCanceled = false; - - this.active = false; - - this.updateMotion(); - }, - - /** - * Internal method to handle a Touch Cancel Event. - * - * @method Phaser.Input.Pointer#touchcancel - * @private - * @since 3.15.0 - * - * @param {Touch} touch - The Changed Touch from the Touch Event. - * @param {TouchEvent} event - The full Touch Event. - */ - touchcancel: function (touch, event) - { - this.buttons = 0; - - this.event = event; - - this.upElement = touch.target; - - // Sets the local x/y properties - this.manager.transformPointer(this, touch.pageX, touch.pageY, false); - - this.primaryDown = false; - this.upX = this.x; - this.upY = this.y; - this.upTime = event.timeStamp; - - this.isDown = false; - - this.wasTouch = true; - this.wasCanceled = true; - - this.active = false; - }, - - /** - * Checks to see if any buttons are being held down on this Pointer. - * - * @method Phaser.Input.Pointer#noButtonDown - * @since 3.0.0 - * - * @return {boolean} `true` if no buttons are being held down. - */ - noButtonDown: function () - { - return (this.buttons === 0); - }, - - /** - * Checks to see if the left button is being held down on this Pointer. - * - * @method Phaser.Input.Pointer#leftButtonDown - * @since 3.0.0 - * - * @return {boolean} `true` if the left button is being held down. - */ - leftButtonDown: function () - { - return (this.buttons & 1) ? true : false; - }, - - /** - * Checks to see if the right button is being held down on this Pointer. - * - * @method Phaser.Input.Pointer#rightButtonDown - * @since 3.0.0 - * - * @return {boolean} `true` if the right button is being held down. - */ - rightButtonDown: function () - { - return (this.buttons & 2) ? true : false; - }, - - /** - * Checks to see if the middle button is being held down on this Pointer. - * - * @method Phaser.Input.Pointer#middleButtonDown - * @since 3.0.0 - * - * @return {boolean} `true` if the middle button is being held down. - */ - middleButtonDown: function () - { - return (this.buttons & 4) ? true : false; - }, - - /** - * Checks to see if the back button is being held down on this Pointer. - * - * @method Phaser.Input.Pointer#backButtonDown - * @since 3.0.0 - * - * @return {boolean} `true` if the back button is being held down. - */ - backButtonDown: function () - { - return (this.buttons & 8) ? true : false; - }, - - /** - * Checks to see if the forward button is being held down on this Pointer. - * - * @method Phaser.Input.Pointer#forwardButtonDown - * @since 3.0.0 - * - * @return {boolean} `true` if the forward button is being held down. - */ - forwardButtonDown: function () - { - return (this.buttons & 16) ? true : false; - }, - - /** - * Checks to see if the left button was just released on this Pointer. - * - * @method Phaser.Input.Pointer#leftButtonReleased - * @since 3.18.0 - * - * @return {boolean} `true` if the left button was just released. - */ - leftButtonReleased: function () - { - return (this.button === 0 && !this.isDown); - }, - - /** - * Checks to see if the right button was just released on this Pointer. - * - * @method Phaser.Input.Pointer#rightButtonReleased - * @since 3.18.0 - * - * @return {boolean} `true` if the right button was just released. - */ - rightButtonReleased: function () - { - return (this.button === 2 && !this.isDown); - }, - - /** - * Checks to see if the middle button was just released on this Pointer. - * - * @method Phaser.Input.Pointer#middleButtonReleased - * @since 3.18.0 - * - * @return {boolean} `true` if the middle button was just released. - */ - middleButtonReleased: function () - { - return (this.button === 1 && !this.isDown); - }, - - /** - * Checks to see if the back button was just released on this Pointer. - * - * @method Phaser.Input.Pointer#backButtonReleased - * @since 3.18.0 - * - * @return {boolean} `true` if the back button was just released. - */ - backButtonReleased: function () - { - return (this.button === 3 && !this.isDown); - }, - - /** - * Checks to see if the forward button was just released on this Pointer. - * - * @method Phaser.Input.Pointer#forwardButtonReleased - * @since 3.18.0 - * - * @return {boolean} `true` if the forward button was just released. - */ - forwardButtonReleased: function () - { - return (this.button === 4 && !this.isDown); - }, - - /** - * 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. - */ - getDistance: function () - { - if (this.isDown) - { - return Distance(this.downX, this.downY, this.x, this.y); - } - else - { - return Distance(this.downX, this.downY, this.upX, this.upY); - } - }, - - /** - * 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` and `downY` values and the current 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. - */ - getDistanceX: function () - { - if (this.isDown) - { - return Math.abs(this.downX - this.x); - } - else - { - return Math.abs(this.downX - this.upX); - } - }, - - /** - * 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 `downX` and `downY` values and the current 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. - */ - getDistanceY: function () - { - if (this.isDown) - { - return Math.abs(this.downY - this.y); - } - else - { - return Math.abs(this.downY - this.upY); - } - }, - - /** - * 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 Pointer button was released. - * - * @method Phaser.Input.Pointer#getDuration - * @since 3.16.0 - * - * @return {number} The duration the Pointer was held down for in milliseconds. - */ - getDuration: function () - { - if (this.isDown) - { - return (this.manager.time - this.downTime); - } - else - { - return (this.upTime - this.downTime); - } - }, - - /** - * 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. - */ - getAngle: function () - { - if (this.isDown) - { - return Angle(this.downX, this.downY, this.x, this.y); - } - else - { - return Angle(this.downX, this.downY, this.upX, this.upY); - } - }, - - /** - * Takes the previous and current Pointer positions and then generates an array of interpolated values between - * the two. The array will be populated up to the size of the `steps` argument. - * - * ```javaScript - * var points = pointer.getInterpolatedPosition(4); - * - * // points[0] = { x: 0, y: 0 } - * // points[1] = { x: 2, y: 1 } - * // points[2] = { x: 3, y: 2 } - * // points[3] = { x: 6, y: 3 } - * ``` - * - * Use this if you need to get smoothed values between the previous and current pointer positions. DOM pointer - * events can often fire faster than the main browser loop, and this will help you avoid janky movement - * especially if you have an object following a Pointer. - * - * Note that if you provide an output array it will only be populated up to the number of steps provided. - * It will not clear any previous data that may have existed beyond the range of the steps count. - * - * Internally it uses the Smooth Step interpolation calculation. - * - * @method Phaser.Input.Pointer#getInterpolatedPosition - * @since 3.11.0 - * - * @param {integer} [steps=10] - The number of interpolation steps to use. - * @param {array} [out] - An array to store the results in. If not provided a new one will be created. - * - * @return {array} An array of interpolated values. - */ - getInterpolatedPosition: function (steps, out) - { - if (steps === undefined) { steps = 10; } - if (out === undefined) { out = []; } - - var prevX = this.prevPosition.x; - var prevY = this.prevPosition.y; - - var curX = this.position.x; - var curY = this.position.y; - - for (var i = 0; i < steps; i++) - { - var t = (1 / steps) * i; - - out[i] = { x: SmoothStepInterpolation(t, prevX, curX), y: SmoothStepInterpolation(t, prevY, curY) }; - } - - return out; - }, - - /** - * Destroys this Pointer instance and resets its external references. - * - * @method Phaser.Input.Pointer#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.camera = null; - this.manager = null; - this.position = null; - }, - - /** - * The x position of this Pointer. - * The value is in screen space. - * See `worldX` to get a camera converted position. - * - * @name Phaser.Input.Pointer#x - * @type {number} - * @since 3.0.0 - */ - x: { - - get: function () - { - return this.position.x; - }, - - set: function (value) - { - this.position.x = value; - } - - }, - - /** - * The y position of this Pointer. - * The value is in screen space. - * See `worldY` to get a camera converted position. - * - * @name Phaser.Input.Pointer#y - * @type {number} - * @since 3.0.0 - */ - y: { - - get: function () - { - return this.position.y; - }, - - set: function (value) - { - this.position.y = value; - } - - }, - - /** - * Time when this Pointer was most recently updated by a DOM Event. - * This comes directly from the `event.timeStamp` property. - * If no event has yet taken place, it will return zero. - * - * @name Phaser.Input.Pointer#time - * @type {number} - * @readonly - * @since 3.16.0 - */ - time: { - - get: function () - { - return (this.event) ? this.event.timeStamp : 0; - } - - } - -}); - -module.exports = Pointer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Angle = require('../math/angle/Between'); +var Class = require('../utils/Class'); +var Distance = require('../math/distance/DistanceBetween'); +var FuzzyEqual = require('../math/fuzzy/Equal'); +var SmoothStepInterpolation = require('../math/interpolation/SmoothStepInterpolation'); +var Vector2 = require('../math/Vector2'); + +/** + * @classdesc + * A Pointer object encapsulates both mouse and touch input within Phaser. + * + * By default, Phaser will create 2 pointers for your game to use. If you require more, i.e. for a multi-touch + * game, then use the `InputPlugin.addPointer` method to do so, rather than instantiating this class directly, + * otherwise it won't be managed by the input system. + * + * You can reference the current active pointer via `InputPlugin.activePointer`. You can also use the properties + * `InputPlugin.pointer1` through to `pointer10`, for each pointer you have enabled in your game. + * + * The properties of this object are set by the Input Plugin during processing. This object is then sent in all + * input related events that the Input Plugin emits, so you can reference properties from it directly in your + * callbacks. + * + * @class Pointer + * @memberof Phaser.Input + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.InputManager} manager - A reference to the Input Manager. + * @param {integer} id - The internal ID of this Pointer. + */ +var Pointer = new Class({ + + initialize: + + function Pointer (manager, id) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Pointer#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The internal ID of this Pointer. + * + * @name Phaser.Input.Pointer#id + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.id = id; + + /** + * The most recent native DOM Event this Pointer has processed. + * + * @name Phaser.Input.Pointer#event + * @type {(TouchEvent|MouseEvent)} + * @since 3.0.0 + */ + this.event; + + /** + * 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 + */ + this.downElement; + + /** + * 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 + */ + this.upElement; + + /** + * The camera the Pointer interacted with during its last update. + * + * A Pointer can only ever interact with one camera at once, which will be the top-most camera + * in the list should multiple cameras be positioned on-top of each other. + * + * @name Phaser.Input.Pointer#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @default null + * @since 3.0.0 + */ + this.camera = null; + + /** + * A read-only property that indicates which button was pressed, or released, on the pointer + * during the most recent event. It is only set during `up` and `down` events. + * + * On Touch devices the value is always 0. + * + * Users may change the configuration of buttons on their pointing device so that if an event's button property + * is zero, it may not have been caused by the button that is physically left–most on the pointing device; + * however, it should behave as if the left button was clicked in the standard button layout. + * + * @name Phaser.Input.Pointer#button + * @type {integer} + * @readonly + * @default 0 + * @since 3.18.0 + */ + this.button = 0; + + /** + * 0: No button or un-initialized + * 1: Left button + * 2: Right button + * 4: Wheel button or middle button + * 8: 4th button (typically the "Browser Back" button) + * 16: 5th button (typically the "Browser Forward" button) + * + * For a mouse configured for left-handed use, the button actions are reversed. + * In this case, the values are read from right to left. + * + * @name Phaser.Input.Pointer#buttons + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.buttons = 0; + + /** + * The position of the Pointer in screen space. + * + * @name Phaser.Input.Pointer#position + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.position = new Vector2(); + + /** + * The previous position of the Pointer in screen space. + * + * The old x and y values are stored in here during the InputManager.transformPointer call. + * + * Use the properties `velocity`, `angle` and `distance` to create your own gesture recognition. + * + * @name Phaser.Input.Pointer#prevPosition + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.11.0 + */ + this.prevPosition = new Vector2(); + + /** + * An internal vector used for calculations of the pointer speed and angle. + * + * @name Phaser.Input.Pointer#midPoint + * @type {Phaser.Math.Vector2} + * @private + * @since 3.16.0 + */ + this.midPoint = new Vector2(-1, -1); + + /** + * 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 + */ + this.velocity = new Vector2(); + + /** + * 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 + */ + this.angle = 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 buttons was pressed down, + * then use the `Pointer.getDistance` method. + * + * @name Phaser.Input.Pointer#distance + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.distance = 0; + + /** + * The smoothing factor to apply to the Pointer position. + * + * Due to their nature, pointer positions are inherently noisy. While this is fine for lots of games, if you need cleaner positions + * then you can set this value to apply an automatic smoothing to the positions as they are recorded. + * + * The default value of zero means 'no smoothing'. + * Set to a small value, such as 0.2, to apply an average level of smoothing between positions. You can do this by changing this + * value directly, or by setting the `input.smoothFactor` property in the Game Config. + * + * Positions are only smoothed when the pointer moves. If the primary button on this Pointer enters an Up or Down state, then the position + * is always precise, and not smoothed. + * + * @name Phaser.Input.Pointer#smoothFactor + * @type {number} + * @default 0 + * @since 3.16.0 + */ + this.smoothFactor = 0; + + /** + * The factor applied to the motion smoothing each frame. + * + * This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, + * angle and distance of the Pointer. It's applied every frame, until the midPoint reaches the current + * position of the Pointer. 0.2 provides a good average but can be increased if you need a + * quicker update and are working in a high performance environment. Never set this value to + * zero. + * + * @name Phaser.Input.Pointer#motionFactor + * @type {number} + * @default 0.2 + * @since 3.16.0 + */ + this.motionFactor = 0.2; + + /** + * The x position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. + * + * If you wish to use this value _outside_ of an input event handler then you should update it first by calling + * the `Pointer.updateWorldPoint` method. + * + * @name Phaser.Input.Pointer#worldX + * @type {number} + * @default 0 + * @since 3.10.0 + */ + this.worldX = 0; + + /** + * The y position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. + * + * If you wish to use this value _outside_ of an input event handler then you should update it first by calling + * the `Pointer.updateWorldPoint` method. + * + * @name Phaser.Input.Pointer#worldY + * @type {number} + * @default 0 + * @since 3.10.0 + */ + this.worldY = 0; + + /** + * Time when this Pointer was most recently moved (regardless of the state of its buttons, if any) + * + * @name Phaser.Input.Pointer#moveTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.moveTime = 0; + + /** + * X coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. + * + * @name Phaser.Input.Pointer#downX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.downX = 0; + + /** + * Y coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. + * + * @name Phaser.Input.Pointer#downY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.downY = 0; + + /** + * Time when Button 1 (left button), or Touch, was pressed, used for dragging objects. + * + * @name Phaser.Input.Pointer#downTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.downTime = 0; + + /** + * X coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. + * + * @name Phaser.Input.Pointer#upX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.upX = 0; + + /** + * Y coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. + * + * @name Phaser.Input.Pointer#upY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.upY = 0; + + /** + * Time when Button 1 (left button), or Touch, was released, used for dragging objects. + * + * @name Phaser.Input.Pointer#upTime + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.upTime = 0; + + /** + * Is the primary button down? (usually button 0, the left mouse button) + * + * @name Phaser.Input.Pointer#primaryDown + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.primaryDown = false; + + /** + * Is _any_ button on this pointer considered as being down? + * + * @name Phaser.Input.Pointer#isDown + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isDown = false; + + /** + * Did the previous input event come from a Touch input (true) or Mouse? (false) + * + * @name Phaser.Input.Pointer#wasTouch + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.wasTouch = false; + + /** + * Did this Pointer get canceled by a touchcancel event? + * + * Note: "canceled" is the American-English spelling of "cancelled". Please don't submit PRs correcting it! + * + * @name Phaser.Input.Pointer#wasCanceled + * @type {boolean} + * @default false + * @since 3.15.0 + */ + this.wasCanceled = false; + + /** + * If the mouse is locked, the horizontal relative movement of the Pointer in pixels since last frame. + * + * @name Phaser.Input.Pointer#movementX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.movementX = 0; + + /** + * If the mouse is locked, the vertical relative movement of the Pointer in pixels since last frame. + * + * @name Phaser.Input.Pointer#movementY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.movementY = 0; + + /** + * The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * + * @name Phaser.Input.Pointer#identifier + * @type {number} + * @since 3.10.0 + */ + this.identifier = 0; + + /** + * The pointerId property of the Pointer as set by the DOM event when this Pointer is started. + * The browser can and will recycle this value. + * + * @name Phaser.Input.Pointer#pointerId + * @type {number} + * @since 3.10.0 + */ + this.pointerId = null; + + /** + * An active Pointer is one that is currently pressed down on the display. + * A Mouse is always considered as active. + * + * @name Phaser.Input.Pointer#active + * @type {boolean} + * @since 3.10.0 + */ + this.active = (id === 0) ? true : false; + + /** + * Is this pointer Pointer Locked? + * + * Only a mouse pointer can be locked and it only becomes locked when requested via + * the browsers Pointer Lock API. + * + * You can request this by calling the `this.input.mouse.requestPointerLock()` method from + * a `pointerdown` or `pointerup` event handler. + * + * @name Phaser.Input.Pointer#locked + * @readonly + * @type {boolean} + * @since 3.19.0 + */ + this.locked = false; + + /** + * The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * + * @name Phaser.Input.Pointer#deltaX + * @type {number} + * @default 0 + * @since 3.18.0 + */ + this.deltaX = 0; + + /** + * The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * + * @name Phaser.Input.Pointer#deltaY + * @type {number} + * @default 0 + * @since 3.18.0 + */ + this.deltaY = 0; + + /** + * The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * + * @name Phaser.Input.Pointer#deltaZ + * @type {number} + * @default 0 + * @since 3.18.0 + */ + this.deltaZ = 0; + }, + + /** + * Takes a Camera and updates this Pointer's `worldX` and `worldY` values so they are + * the result of a translation through the given Camera. + * + * Note that the values will be automatically replaced the moment the Pointer is + * updated by an input event, such as a mouse move, so should be used immediately. + * + * @method Phaser.Input.Pointer#updateWorldPoint + * @since 3.19.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera which is being tested against. + * + * @return {this} This Pointer object. + */ + updateWorldPoint: function (camera) + { + var x = this.x; + var y = this.y; + + if (camera.resolution !== 1) + { + x += camera._x; + y += camera._y; + } + + // Stores the world point inside of tempPoint + var temp = camera.getWorldPoint(x, y); + + this.worldX = temp.x; + this.worldY = temp.y; + + return this; + }, + + /** + * 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. + */ + positionToCamera: function (camera, output) + { + return camera.getWorldPoint(this.x, this.y, output); + }, + + /** + * Calculates the motion of this Pointer, including its velocity and angle of movement. + * This method is called automatically each frame by the Input Manager. + * + * @method Phaser.Input.Pointer#updateMotion + * @private + * @since 3.16.0 + */ + updateMotion: function () + { + var cx = this.position.x; + var cy = this.position.y; + + var mx = this.midPoint.x; + var my = this.midPoint.y; + + if (cx === mx && cy === my) + { + // Nothing to do here + return; + } + + // Moving towards our goal ... + var vx = SmoothStepInterpolation(this.motionFactor, mx, cx); + var vy = SmoothStepInterpolation(this.motionFactor, my, cy); + + if (FuzzyEqual(vx, cx, 0.1)) + { + vx = cx; + } + + if (FuzzyEqual(vy, cy, 0.1)) + { + vy = cy; + } + + this.midPoint.set(vx, vy); + + var dx = cx - vx; + var dy = cy - vy; + + this.velocity.set(dx, dy); + + this.angle = Angle(vx, vy, cx, cy); + + this.distance = Math.sqrt(dx * dx + dy * dy); + }, + + /** + * Internal method to handle a Mouse Up Event. + * + * @method Phaser.Input.Pointer#up + * @private + * @since 3.0.0 + * + * @param {MouseEvent} event - The Mouse Event to process. + */ + up: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + this.button = event.button; + + this.upElement = event.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, false); + + // 0: Main button pressed, usually the left button or the un-initialized state + if (event.button === 0) + { + this.primaryDown = false; + this.upX = this.x; + this.upY = this.y; + this.upTime = event.timeStamp; + } + + this.isDown = false; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Mouse Down Event. + * + * @method Phaser.Input.Pointer#down + * @private + * @since 3.0.0 + * + * @param {MouseEvent} event - The Mouse Event to process. + */ + down: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + this.button = event.button; + + this.downElement = event.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, false); + + // 0: Main button pressed, usually the left button or the un-initialized state + if (event.button === 0) + { + this.primaryDown = true; + this.downX = this.x; + this.downY = this.y; + this.downTime = event.timeStamp; + } + + this.isDown = true; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Mouse Move Event. + * + * @method Phaser.Input.Pointer#move + * @private + * @since 3.0.0 + * + * @param {MouseEvent} event - The Mouse Event to process. + */ + move: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, true); + + if (this.locked) + { + // Multiple DOM events may occur within one frame, but only one Phaser event will fire + this.movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; + this.movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; + } + + this.moveTime = event.timeStamp; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Mouse Wheel Event. + * + * @method Phaser.Input.Pointer#wheel + * @private + * @since 3.18.0 + * + * @param {WheelEvent} event - The Wheel Event to process. + */ + wheel: function (event) + { + if ('buttons' in event) + { + this.buttons = event.buttons; + } + + this.event = event; + + // Sets the local x/y properties + this.manager.transformPointer(this, event.pageX, event.pageY, false); + + this.deltaX = event.deltaX; + this.deltaY = event.deltaY; + this.deltaZ = event.deltaZ; + + this.wasTouch = false; + }, + + /** + * Internal method to handle a Touch Start Event. + * + * @method Phaser.Input.Pointer#touchstart + * @private + * @since 3.0.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchstart: function (touch, event) + { + if (touch['pointerId']) + { + this.pointerId = touch.pointerId; + } + + this.identifier = touch.identifier; + this.target = touch.target; + this.active = true; + + this.buttons = 1; + + this.event = event; + + this.downElement = touch.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, false); + + this.primaryDown = true; + this.downX = this.x; + this.downY = this.y; + this.downTime = event.timeStamp; + + this.isDown = true; + + this.wasTouch = true; + this.wasCanceled = false; + + this.updateMotion(); + }, + + /** + * Internal method to handle a Touch Move Event. + * + * @method Phaser.Input.Pointer#touchmove + * @private + * @since 3.0.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchmove: function (touch, event) + { + this.event = event; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, true); + + this.moveTime = event.timeStamp; + + this.wasTouch = true; + + this.updateMotion(); + }, + + /** + * Internal method to handle a Touch End Event. + * + * @method Phaser.Input.Pointer#touchend + * @private + * @since 3.0.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchend: function (touch, event) + { + this.buttons = 0; + + this.event = event; + + this.upElement = touch.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, false); + + this.primaryDown = false; + this.upX = this.x; + this.upY = this.y; + this.upTime = event.timeStamp; + + this.isDown = false; + + this.wasTouch = true; + this.wasCanceled = false; + + this.active = false; + + this.updateMotion(); + }, + + /** + * Internal method to handle a Touch Cancel Event. + * + * @method Phaser.Input.Pointer#touchcancel + * @private + * @since 3.15.0 + * + * @param {Touch} touch - The Changed Touch from the Touch Event. + * @param {TouchEvent} event - The full Touch Event. + */ + touchcancel: function (touch, event) + { + this.buttons = 0; + + this.event = event; + + this.upElement = touch.target; + + // Sets the local x/y properties + this.manager.transformPointer(this, touch.pageX, touch.pageY, false); + + this.primaryDown = false; + this.upX = this.x; + this.upY = this.y; + this.upTime = event.timeStamp; + + this.isDown = false; + + this.wasTouch = true; + this.wasCanceled = true; + + this.active = false; + }, + + /** + * Checks to see if any buttons are being held down on this Pointer. + * + * @method Phaser.Input.Pointer#noButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if no buttons are being held down. + */ + noButtonDown: function () + { + return (this.buttons === 0); + }, + + /** + * Checks to see if the left button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#leftButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the left button is being held down. + */ + leftButtonDown: function () + { + return (this.buttons & 1) ? true : false; + }, + + /** + * Checks to see if the right button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#rightButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the right button is being held down. + */ + rightButtonDown: function () + { + return (this.buttons & 2) ? true : false; + }, + + /** + * Checks to see if the middle button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#middleButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the middle button is being held down. + */ + middleButtonDown: function () + { + return (this.buttons & 4) ? true : false; + }, + + /** + * Checks to see if the back button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#backButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the back button is being held down. + */ + backButtonDown: function () + { + return (this.buttons & 8) ? true : false; + }, + + /** + * Checks to see if the forward button is being held down on this Pointer. + * + * @method Phaser.Input.Pointer#forwardButtonDown + * @since 3.0.0 + * + * @return {boolean} `true` if the forward button is being held down. + */ + forwardButtonDown: function () + { + return (this.buttons & 16) ? true : false; + }, + + /** + * Checks to see if the left button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#leftButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the left button was just released. + */ + leftButtonReleased: function () + { + return (this.button === 0 && !this.isDown); + }, + + /** + * Checks to see if the right button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#rightButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the right button was just released. + */ + rightButtonReleased: function () + { + return (this.button === 2 && !this.isDown); + }, + + /** + * Checks to see if the middle button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#middleButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the middle button was just released. + */ + middleButtonReleased: function () + { + return (this.button === 1 && !this.isDown); + }, + + /** + * Checks to see if the back button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#backButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the back button was just released. + */ + backButtonReleased: function () + { + return (this.button === 3 && !this.isDown); + }, + + /** + * Checks to see if the forward button was just released on this Pointer. + * + * @method Phaser.Input.Pointer#forwardButtonReleased + * @since 3.18.0 + * + * @return {boolean} `true` if the forward button was just released. + */ + forwardButtonReleased: function () + { + return (this.button === 4 && !this.isDown); + }, + + /** + * 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. + */ + getDistance: function () + { + if (this.isDown) + { + return Distance(this.downX, this.downY, this.x, this.y); + } + else + { + return Distance(this.downX, this.downY, this.upX, this.upY); + } + }, + + /** + * 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` and `downY` values and the current 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. + */ + getDistanceX: function () + { + if (this.isDown) + { + return Math.abs(this.downX - this.x); + } + else + { + return Math.abs(this.downX - this.upX); + } + }, + + /** + * 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 `downX` and `downY` values and the current 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. + */ + getDistanceY: function () + { + if (this.isDown) + { + return Math.abs(this.downY - this.y); + } + else + { + return Math.abs(this.downY - this.upY); + } + }, + + /** + * 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 Pointer button was released. + * + * @method Phaser.Input.Pointer#getDuration + * @since 3.16.0 + * + * @return {number} The duration the Pointer was held down for in milliseconds. + */ + getDuration: function () + { + if (this.isDown) + { + return (this.manager.time - this.downTime); + } + else + { + return (this.upTime - this.downTime); + } + }, + + /** + * 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. + */ + getAngle: function () + { + if (this.isDown) + { + return Angle(this.downX, this.downY, this.x, this.y); + } + else + { + return Angle(this.downX, this.downY, this.upX, this.upY); + } + }, + + /** + * Takes the previous and current Pointer positions and then generates an array of interpolated values between + * the two. The array will be populated up to the size of the `steps` argument. + * + * ```javaScript + * var points = pointer.getInterpolatedPosition(4); + * + * // points[0] = { x: 0, y: 0 } + * // points[1] = { x: 2, y: 1 } + * // points[2] = { x: 3, y: 2 } + * // points[3] = { x: 6, y: 3 } + * ``` + * + * Use this if you need to get smoothed values between the previous and current pointer positions. DOM pointer + * events can often fire faster than the main browser loop, and this will help you avoid janky movement + * especially if you have an object following a Pointer. + * + * Note that if you provide an output array it will only be populated up to the number of steps provided. + * It will not clear any previous data that may have existed beyond the range of the steps count. + * + * Internally it uses the Smooth Step interpolation calculation. + * + * @method Phaser.Input.Pointer#getInterpolatedPosition + * @since 3.11.0 + * + * @param {integer} [steps=10] - The number of interpolation steps to use. + * @param {array} [out] - An array to store the results in. If not provided a new one will be created. + * + * @return {array} An array of interpolated values. + */ + getInterpolatedPosition: function (steps, out) + { + if (steps === undefined) { steps = 10; } + if (out === undefined) { out = []; } + + var prevX = this.prevPosition.x; + var prevY = this.prevPosition.y; + + var curX = this.position.x; + var curY = this.position.y; + + for (var i = 0; i < steps; i++) + { + var t = (1 / steps) * i; + + out[i] = { x: SmoothStepInterpolation(t, prevX, curX), y: SmoothStepInterpolation(t, prevY, curY) }; + } + + return out; + }, + + /** + * Destroys this Pointer instance and resets its external references. + * + * @method Phaser.Input.Pointer#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.camera = null; + this.manager = null; + this.position = null; + }, + + /** + * The x position of this Pointer. + * The value is in screen space. + * See `worldX` to get a camera converted position. + * + * @name Phaser.Input.Pointer#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.position.x; + }, + + set: function (value) + { + this.position.x = value; + } + + }, + + /** + * The y position of this Pointer. + * The value is in screen space. + * See `worldY` to get a camera converted position. + * + * @name Phaser.Input.Pointer#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.position.y; + }, + + set: function (value) + { + this.position.y = value; + } + + }, + + /** + * Time when this Pointer was most recently updated by a DOM Event. + * This comes directly from the `event.timeStamp` property. + * If no event has yet taken place, it will return zero. + * + * @name Phaser.Input.Pointer#time + * @type {number} + * @readonly + * @since 3.16.0 + */ + time: { + + get: function () + { + return (this.event) ? this.event.timeStamp : 0; + } + + } + +}); + +module.exports = Pointer; diff --git a/src/input/const.js b/src/input/const.js index 757b4c2a8..d2bb00019 100644 --- a/src/input/const.js +++ b/src/input/const.js @@ -1,92 +1,92 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var INPUT_CONST = { - - /** - * The mouse pointer is being held down. - * - * @name Phaser.Input.MOUSE_DOWN - * @type {integer} - * @since 3.10.0 - */ - MOUSE_DOWN: 0, - - /** - * The mouse pointer is being moved. - * - * @name Phaser.Input.MOUSE_MOVE - * @type {integer} - * @since 3.10.0 - */ - MOUSE_MOVE: 1, - - /** - * The mouse pointer is released. - * - * @name Phaser.Input.MOUSE_UP - * @type {integer} - * @since 3.10.0 - */ - MOUSE_UP: 2, - - /** - * A touch pointer has been started. - * - * @name Phaser.Input.TOUCH_START - * @type {integer} - * @since 3.10.0 - */ - TOUCH_START: 3, - - /** - * A touch pointer has been started. - * - * @name Phaser.Input.TOUCH_MOVE - * @type {integer} - * @since 3.10.0 - */ - TOUCH_MOVE: 4, - - /** - * A touch pointer has been started. - * - * @name Phaser.Input.TOUCH_END - * @type {integer} - * @since 3.10.0 - */ - TOUCH_END: 5, - - /** - * The pointer lock has changed. - * - * @name Phaser.Input.POINTER_LOCK_CHANGE - * @type {integer} - * @since 3.10.0 - */ - POINTER_LOCK_CHANGE: 6, - - /** - * A touch pointer has been been cancelled by the browser. - * - * @name Phaser.Input.TOUCH_CANCEL - * @type {integer} - * @since 3.15.0 - */ - TOUCH_CANCEL: 7, - - /** - * The mouse wheel changes. - * - * @name Phaser.Input.MOUSE_WHEEL - * @type {integer} - * @since 3.18.0 - */ - MOUSE_WHEEL: 8 - -}; - -module.exports = INPUT_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var INPUT_CONST = { + + /** + * The mouse pointer is being held down. + * + * @name Phaser.Input.MOUSE_DOWN + * @type {integer} + * @since 3.10.0 + */ + MOUSE_DOWN: 0, + + /** + * The mouse pointer is being moved. + * + * @name Phaser.Input.MOUSE_MOVE + * @type {integer} + * @since 3.10.0 + */ + MOUSE_MOVE: 1, + + /** + * The mouse pointer is released. + * + * @name Phaser.Input.MOUSE_UP + * @type {integer} + * @since 3.10.0 + */ + MOUSE_UP: 2, + + /** + * A touch pointer has been started. + * + * @name Phaser.Input.TOUCH_START + * @type {integer} + * @since 3.10.0 + */ + TOUCH_START: 3, + + /** + * A touch pointer has been started. + * + * @name Phaser.Input.TOUCH_MOVE + * @type {integer} + * @since 3.10.0 + */ + TOUCH_MOVE: 4, + + /** + * A touch pointer has been started. + * + * @name Phaser.Input.TOUCH_END + * @type {integer} + * @since 3.10.0 + */ + TOUCH_END: 5, + + /** + * The pointer lock has changed. + * + * @name Phaser.Input.POINTER_LOCK_CHANGE + * @type {integer} + * @since 3.10.0 + */ + POINTER_LOCK_CHANGE: 6, + + /** + * A touch pointer has been been cancelled by the browser. + * + * @name Phaser.Input.TOUCH_CANCEL + * @type {integer} + * @since 3.15.0 + */ + TOUCH_CANCEL: 7, + + /** + * The mouse wheel changes. + * + * @name Phaser.Input.MOUSE_WHEEL + * @type {integer} + * @since 3.18.0 + */ + MOUSE_WHEEL: 8 + +}; + +module.exports = INPUT_CONST; diff --git a/src/input/events/BOOT_EVENT.js b/src/input/events/BOOT_EVENT.js index 7988d335a..fa9ffdc1a 100644 --- a/src/input/events/BOOT_EVENT.js +++ b/src/input/events/BOOT_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Boot Event. - * - * This internal event is dispatched by the Input Plugin when it boots, signalling to all of its systems to create themselves. - * - * @event Phaser.Input.Events#BOOT - * @since 3.0.0 - */ -module.exports = 'boot'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Boot Event. + * + * This internal event is dispatched by the Input Plugin when it boots, signalling to all of its systems to create themselves. + * + * @event Phaser.Input.Events#BOOT + * @since 3.0.0 + */ +module.exports = 'boot'; diff --git a/src/input/events/DESTROY_EVENT.js b/src/input/events/DESTROY_EVENT.js index 9c6dc29c7..8b08ad968 100644 --- a/src/input/events/DESTROY_EVENT.js +++ b/src/input/events/DESTROY_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Destroy Event. - * - * This internal event is dispatched by the Input Plugin when it is destroyed, signalling to all of its systems to destroy themselves. - * - * @event Phaser.Input.Events#DESTROY - * @since 3.0.0 - */ -module.exports = 'destroy'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Destroy Event. + * + * This internal event is dispatched by the Input Plugin when it is destroyed, signalling to all of its systems to destroy themselves. + * + * @event Phaser.Input.Events#DESTROY + * @since 3.0.0 + */ +module.exports = 'destroy'; diff --git a/src/input/events/DRAG_END_EVENT.js b/src/input/events/DRAG_END_EVENT.js index 421e27d73..eae96affd 100644 --- a/src/input/events/DRAG_END_EVENT.js +++ b/src/input/events/DRAG_END_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drag End Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer stops dragging a Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('dragend', listener)`. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_END]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_END} event instead. - * - * @event Phaser.Input.Events#DRAG_END - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer stopped dragging. - */ -module.exports = 'dragend'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag End Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer stops dragging a Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('dragend', listener)`. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_END]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_END} event instead. + * + * @event Phaser.Input.Events#DRAG_END + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer stopped dragging. + */ +module.exports = 'dragend'; diff --git a/src/input/events/DRAG_ENTER_EVENT.js b/src/input/events/DRAG_ENTER_EVENT.js index bb956571c..d2b8c4c9d 100644 --- a/src/input/events/DRAG_ENTER_EVENT.js +++ b/src/input/events/DRAG_ENTER_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drag Enter Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object into a Drag Target. - * - * Listen to this event from within a Scene using: `this.input.on('dragenter', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_ENTER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_ENTER} event instead. - * - * @event Phaser.Input.Events#DRAG_ENTER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. - * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved into. - */ -module.exports = 'dragenter'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Enter Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object into a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('dragenter', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_ENTER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_ENTER} event instead. + * + * @event Phaser.Input.Events#DRAG_ENTER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved into. + */ +module.exports = 'dragenter'; diff --git a/src/input/events/DRAG_EVENT.js b/src/input/events/DRAG_EVENT.js index 730d725d2..9ffa0b4a0 100644 --- a/src/input/events/DRAG_EVENT.js +++ b/src/input/events/DRAG_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drag Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves while dragging a Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('drag', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG} event instead. - * - * @event Phaser.Input.Events#DRAG - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. - * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. - * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. - */ -module.exports = 'drag'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves while dragging a Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('drag', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG} event instead. + * + * @event Phaser.Input.Events#DRAG + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. + */ +module.exports = 'drag'; diff --git a/src/input/events/DRAG_LEAVE_EVENT.js b/src/input/events/DRAG_LEAVE_EVENT.js index 29c8c3de7..78404a96d 100644 --- a/src/input/events/DRAG_LEAVE_EVENT.js +++ b/src/input/events/DRAG_LEAVE_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drag Leave Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object out of a Drag Target. - * - * Listen to this event from within a Scene using: `this.input.on('dragleave', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_LEAVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_LEAVE} event instead. - * - * @event Phaser.Input.Events#DRAG_LEAVE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. - * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has left. - */ -module.exports = 'dragleave'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Leave Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object out of a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('dragleave', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_LEAVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_LEAVE} event instead. + * + * @event Phaser.Input.Events#DRAG_LEAVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has left. + */ +module.exports = 'dragleave'; diff --git a/src/input/events/DRAG_OVER_EVENT.js b/src/input/events/DRAG_OVER_EVENT.js index 915e89ee0..10b94b134 100644 --- a/src/input/events/DRAG_OVER_EVENT.js +++ b/src/input/events/DRAG_OVER_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drag Over Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object over a Drag Target. - * - * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within - * the drag target, it will emit this event instead. - * - * Listen to this event from within a Scene using: `this.input.on('dragover', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_OVER} event instead. - * - * @event Phaser.Input.Events#DRAG_OVER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. - * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved over. - */ -module.exports = 'dragover'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object over a Drag Target. + * + * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within + * the drag target, it will emit this event instead. + * + * Listen to this event from within a Scene using: `this.input.on('dragover', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_OVER} event instead. + * + * @event Phaser.Input.Events#DRAG_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved over. + */ +module.exports = 'dragover'; diff --git a/src/input/events/DRAG_START_EVENT.js b/src/input/events/DRAG_START_EVENT.js index 36f8bd812..1e3c1a70b 100644 --- a/src/input/events/DRAG_START_EVENT.js +++ b/src/input/events/DRAG_START_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drag Start Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer starts to drag any Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('dragstart', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_START]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_START} event instead. - * - * @event Phaser.Input.Events#DRAG_START - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. - */ -module.exports = 'dragstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drag Start Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer starts to drag any Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('dragstart', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_START]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_START} event instead. + * + * @event Phaser.Input.Events#DRAG_START + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer is dragging. + */ +module.exports = 'dragstart'; diff --git a/src/input/events/DROP_EVENT.js b/src/input/events/DROP_EVENT.js index 92569eeaa..a401ab36e 100644 --- a/src/input/events/DROP_EVENT.js +++ b/src/input/events/DROP_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Drop Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drops a Game Object on a Drag Target. - * - * Listen to this event from within a Scene using: `this.input.on('drop', listener)`. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DROP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DROP} event instead. - * - * @event Phaser.Input.Events#DROP - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer was dragging. - * @param {Phaser.GameObjects.GameObject} target - The Drag Target the `gameObject` has been dropped on. - */ -module.exports = 'drop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Drop Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drops a Game Object on a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('drop', listener)`. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DROP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DROP} event instead. + * + * @event Phaser.Input.Events#DROP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The interactive Game Object that this pointer was dragging. + * @param {Phaser.GameObjects.GameObject} target - The Drag Target the `gameObject` has been dropped on. + */ +module.exports = 'drop'; diff --git a/src/input/events/GAMEOBJECT_DOWN_EVENT.js b/src/input/events/GAMEOBJECT_DOWN_EVENT.js index 0a1bec816..af07462b4 100644 --- a/src/input/events/GAMEOBJECT_DOWN_EVENT.js +++ b/src/input/events/GAMEOBJECT_DOWN_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Down Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down on _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectdown', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_DOWN - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was pressed down on. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'gameobjectdown'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Down Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down on _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectdown', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was pressed down on. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectdown'; diff --git a/src/input/events/GAMEOBJECT_DRAG_END_EVENT.js b/src/input/events/GAMEOBJECT_DRAG_END_EVENT.js index fffc52d17..32729732a 100644 --- a/src/input/events/GAMEOBJECT_DRAG_END_EVENT.js +++ b/src/input/events/GAMEOBJECT_DRAG_END_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drag End Event. - * - * This event is dispatched by an interactive Game Object if a pointer stops dragging it. - * - * Listen to this event from a Game Object using: `gameObject.on('dragend', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive](Phaser.GameObjects.GameObject#setInteractive) for more details. - * - * @event Phaser.Input.Events#GAMEOBJECT_DRAG_END - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} dragX - The x coordinate where the Pointer stopped dragging the Game Object, in world space. - * @param {number} dragY - The y coordinate where the Pointer stopped dragging the Game Object, in world space. - */ -module.exports = 'dragend'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag End Event. + * + * This event is dispatched by an interactive Game Object if a pointer stops dragging it. + * + * Listen to this event from a Game Object using: `gameObject.on('dragend', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive](Phaser.GameObjects.GameObject#setInteractive) for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_END + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} dragX - The x coordinate where the Pointer stopped dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer stopped dragging the Game Object, in world space. + */ +module.exports = 'dragend'; diff --git a/src/input/events/GAMEOBJECT_DRAG_ENTER_EVENT.js b/src/input/events/GAMEOBJECT_DRAG_ENTER_EVENT.js index 437becdab..2c4382485 100644 --- a/src/input/events/GAMEOBJECT_DRAG_ENTER_EVENT.js +++ b/src/input/events/GAMEOBJECT_DRAG_ENTER_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drag Enter Event. - * - * This event is dispatched by an interactive Game Object if a pointer drags it into a drag target. - * - * Listen to this event from a Game Object using: `gameObject.on('dragenter', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * @event Phaser.Input.Events#GAMEOBJECT_DRAG_ENTER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved into. - */ -module.exports = 'dragenter'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Enter Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it into a drag target. + * + * Listen to this event from a Game Object using: `gameObject.on('dragenter', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_ENTER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved into. + */ +module.exports = 'dragenter'; diff --git a/src/input/events/GAMEOBJECT_DRAG_EVENT.js b/src/input/events/GAMEOBJECT_DRAG_EVENT.js index 47f44de4a..3a5e9356c 100644 --- a/src/input/events/GAMEOBJECT_DRAG_EVENT.js +++ b/src/input/events/GAMEOBJECT_DRAG_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drag Event. - * - * This event is dispatched by an interactive Game Object if a pointer moves while dragging it. - * - * Listen to this event from a Game Object using: `gameObject.on('drag', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * @event Phaser.Input.Events#GAMEOBJECT_DRAG - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. - * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. - */ -module.exports = 'drag'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves while dragging it. + * + * Listen to this event from a Game Object using: `gameObject.on('drag', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. + */ +module.exports = 'drag'; diff --git a/src/input/events/GAMEOBJECT_DRAG_LEAVE_EVENT.js b/src/input/events/GAMEOBJECT_DRAG_LEAVE_EVENT.js index e20f718df..9f1516035 100644 --- a/src/input/events/GAMEOBJECT_DRAG_LEAVE_EVENT.js +++ b/src/input/events/GAMEOBJECT_DRAG_LEAVE_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drag Leave Event. - * - * This event is dispatched by an interactive Game Object if a pointer drags it out of a drag target. - * - * Listen to this event from a Game Object using: `gameObject.on('dragleave', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * @event Phaser.Input.Events#GAMEOBJECT_DRAG_LEAVE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has left. - */ -module.exports = 'dragleave'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Leave Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it out of a drag target. + * + * Listen to this event from a Game Object using: `gameObject.on('dragleave', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_LEAVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has left. + */ +module.exports = 'dragleave'; diff --git a/src/input/events/GAMEOBJECT_DRAG_OVER_EVENT.js b/src/input/events/GAMEOBJECT_DRAG_OVER_EVENT.js index 8a1a0df39..34cdadbd5 100644 --- a/src/input/events/GAMEOBJECT_DRAG_OVER_EVENT.js +++ b/src/input/events/GAMEOBJECT_DRAG_OVER_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drag Over Event. - * - * This event is dispatched by an interactive Game Object if a pointer drags it over a drag target. - * - * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within - * the drag target, it will emit this event instead. - * - * Listen to this event from a Game Object using: `gameObject.on('dragover', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * @event Phaser.Input.Events#GAMEOBJECT_DRAG_OVER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved over. - */ -module.exports = 'dragover'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Over Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it over a drag target. + * + * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within + * the drag target, it will emit this event instead. + * + * Listen to this event from a Game Object using: `gameObject.on('dragover', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The drag target that this pointer has moved over. + */ +module.exports = 'dragover'; diff --git a/src/input/events/GAMEOBJECT_DRAG_START_EVENT.js b/src/input/events/GAMEOBJECT_DRAG_START_EVENT.js index 1032e427a..17f6d5869 100644 --- a/src/input/events/GAMEOBJECT_DRAG_START_EVENT.js +++ b/src/input/events/GAMEOBJECT_DRAG_START_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drag Start Event. - * - * This event is dispatched by an interactive Game Object if a pointer starts to drag it. - * - * Listen to this event from a Game Object using: `gameObject.on('dragstart', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * There are lots of useful drag related properties that are set within the Game Object when dragging occurs. - * For example, `gameObject.input.dragStartX`, `dragStartY` and so on. - * - * @event Phaser.Input.Events#GAMEOBJECT_DRAG_START - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. - * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. - */ -module.exports = 'dragstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drag Start Event. + * + * This event is dispatched by an interactive Game Object if a pointer starts to drag it. + * + * Listen to this event from a Game Object using: `gameObject.on('dragstart', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * There are lots of useful drag related properties that are set within the Game Object when dragging occurs. + * For example, `gameObject.input.dragStartX`, `dragStartY` and so on. + * + * @event Phaser.Input.Events#GAMEOBJECT_DRAG_START + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} dragX - The x coordinate where the Pointer is currently dragging the Game Object, in world space. + * @param {number} dragY - The y coordinate where the Pointer is currently dragging the Game Object, in world space. + */ +module.exports = 'dragstart'; diff --git a/src/input/events/GAMEOBJECT_DROP_EVENT.js b/src/input/events/GAMEOBJECT_DROP_EVENT.js index 6b1df4ff1..d9486199f 100644 --- a/src/input/events/GAMEOBJECT_DROP_EVENT.js +++ b/src/input/events/GAMEOBJECT_DROP_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Drop Event. - * - * This event is dispatched by an interactive Game Object if a pointer drops it on a Drag Target. - * - * Listen to this event from a Game Object using: `gameObject.on('drop', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * @event Phaser.Input.Events#GAMEOBJECT_DROP - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} target - The Drag Target the `gameObject` has been dropped on. - */ -module.exports = 'drop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Drop Event. + * + * This event is dispatched by an interactive Game Object if a pointer drops it on a Drag Target. + * + * Listen to this event from a Game Object using: `gameObject.on('drop', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * @event Phaser.Input.Events#GAMEOBJECT_DROP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} target - The Drag Target the `gameObject` has been dropped on. + */ +module.exports = 'drop'; diff --git a/src/input/events/GAMEOBJECT_MOVE_EVENT.js b/src/input/events/GAMEOBJECT_MOVE_EVENT.js index f1f017ad8..8028dac55 100644 --- a/src/input/events/GAMEOBJECT_MOVE_EVENT.js +++ b/src/input/events/GAMEOBJECT_MOVE_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Move Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved across _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectmove', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} - * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} - * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_MOVE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was moved on. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'gameobjectmove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Move Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved across _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectmove', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was moved on. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectmove'; diff --git a/src/input/events/GAMEOBJECT_OUT_EVENT.js b/src/input/events/GAMEOBJECT_OUT_EVENT.js index c12279211..2a88bbe9b 100644 --- a/src/input/events/GAMEOBJECT_OUT_EVENT.js +++ b/src/input/events/GAMEOBJECT_OUT_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Out Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectout', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} - * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} - * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_OUT - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer moved out of. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'gameobjectout'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Out Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectout', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer moved out of. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectout'; diff --git a/src/input/events/GAMEOBJECT_OVER_EVENT.js b/src/input/events/GAMEOBJECT_OVER_EVENT.js index 0e9e16054..4f9ee5a5f 100644 --- a/src/input/events/GAMEOBJECT_OVER_EVENT.js +++ b/src/input/events/GAMEOBJECT_OVER_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Over Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectover', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} - * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} - * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_OVER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer moved over. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'gameobjectover'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectover', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer moved over. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectover'; diff --git a/src/input/events/GAMEOBJECT_POINTER_DOWN_EVENT.js b/src/input/events/GAMEOBJECT_POINTER_DOWN_EVENT.js index 475942944..3df5322cd 100644 --- a/src/input/events/GAMEOBJECT_POINTER_DOWN_EVENT.js +++ b/src/input/events/GAMEOBJECT_POINTER_DOWN_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Pointer Down Event. - * - * This event is dispatched by an interactive Game Object if a pointer is pressed down on it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerdown', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_POINTER_DOWN - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'pointerdown'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Down Event. + * + * This event is dispatched by an interactive Game Object if a pointer is pressed down on it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerdown', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerdown'; diff --git a/src/input/events/GAMEOBJECT_POINTER_MOVE_EVENT.js b/src/input/events/GAMEOBJECT_POINTER_MOVE_EVENT.js index d8afbd534..e43584bf6 100644 --- a/src/input/events/GAMEOBJECT_POINTER_MOVE_EVENT.js +++ b/src/input/events/GAMEOBJECT_POINTER_MOVE_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Pointer Move Event. - * - * This event is dispatched by an interactive Game Object if a pointer is moved while over it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointermove', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} - * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} - * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_POINTER_MOVE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'pointermove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Move Event. + * + * This event is dispatched by an interactive Game Object if a pointer is moved while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointermove', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointermove'; diff --git a/src/input/events/GAMEOBJECT_POINTER_OUT_EVENT.js b/src/input/events/GAMEOBJECT_POINTER_OUT_EVENT.js index 7be5150c9..8ce6cd4a6 100644 --- a/src/input/events/GAMEOBJECT_POINTER_OUT_EVENT.js +++ b/src/input/events/GAMEOBJECT_POINTER_OUT_EVENT.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Pointer Out Event. - * - * This event is dispatched by an interactive Game Object if a pointer moves out of it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerout', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} - * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} - * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_POINTER_OUT - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'pointerout'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Out Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves out of it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerout', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerout'; diff --git a/src/input/events/GAMEOBJECT_POINTER_OVER_EVENT.js b/src/input/events/GAMEOBJECT_POINTER_OVER_EVENT.js index 6e4c837f8..50702967d 100644 --- a/src/input/events/GAMEOBJECT_POINTER_OVER_EVENT.js +++ b/src/input/events/GAMEOBJECT_POINTER_OVER_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Pointer Over Event. - * - * This event is dispatched by an interactive Game Object if a pointer moves over it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerover', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} - * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} - * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_POINTER_OVER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'pointerover'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Over Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerover', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerover'; diff --git a/src/input/events/GAMEOBJECT_POINTER_UP_EVENT.js b/src/input/events/GAMEOBJECT_POINTER_UP_EVENT.js index 6f3098518..40f6d411e 100644 --- a/src/input/events/GAMEOBJECT_POINTER_UP_EVENT.js +++ b/src/input/events/GAMEOBJECT_POINTER_UP_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Pointer Up Event. - * - * This event is dispatched by an interactive Game Object if a pointer is released while over it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerup', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_POINTER_UP - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'pointerup'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Up Event. + * + * This event is dispatched by an interactive Game Object if a pointer is released while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerup', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_UP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} localX - The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {number} localY - The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'pointerup'; diff --git a/src/input/events/GAMEOBJECT_POINTER_WHEEL_EVENT.js b/src/input/events/GAMEOBJECT_POINTER_WHEEL_EVENT.js index 6c4b6b8fe..a0ec39b19 100644 --- a/src/input/events/GAMEOBJECT_POINTER_WHEEL_EVENT.js +++ b/src/input/events/GAMEOBJECT_POINTER_WHEEL_EVENT.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Pointer Wheel Event. - * - * This event is dispatched by an interactive Game Object if a pointer has its wheel moved while over it. - * - * Listen to this event from a Game Object using: `gameObject.on('wheel', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} - * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} - * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_POINTER_WHEEL - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. - * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'wheel'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Pointer Wheel Event. + * + * This event is dispatched by an interactive Game Object if a pointer has its wheel moved while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('wheel', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_POINTER_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'wheel'; diff --git a/src/input/events/GAMEOBJECT_UP_EVENT.js b/src/input/events/GAMEOBJECT_UP_EVENT.js index e8f473b41..d816ad33f 100644 --- a/src/input/events/GAMEOBJECT_UP_EVENT.js +++ b/src/input/events/GAMEOBJECT_UP_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Up Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released while over _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectup', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_UP - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was over when released. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'gameobjectup'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Up Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released while over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectup', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_UP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was over when released. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectup'; diff --git a/src/input/events/GAMEOBJECT_WHEEL_EVENT.js b/src/input/events/GAMEOBJECT_WHEEL_EVENT.js index d4297da0a..3977dad98 100644 --- a/src/input/events/GAMEOBJECT_WHEEL_EVENT.js +++ b/src/input/events/GAMEOBJECT_WHEEL_EVENT.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Game Object Wheel Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel moved while over _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectwheel', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} - * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} - * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#GAMEOBJECT_WHEEL - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was over when the wheel changed. - * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. - * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. - */ -module.exports = 'gameobjectwheel'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Game Object Wheel Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel moved while over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectwheel', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#GAMEOBJECT_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the pointer was over when the wheel changed. + * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {Phaser.Types.Input.EventData} event - The Phaser input event. You can call `stopPropagation()` to halt it from going any further in the event flow. + */ +module.exports = 'gameobjectwheel'; diff --git a/src/input/events/GAME_OUT_EVENT.js b/src/input/events/GAME_OUT_EVENT.js index 539742ff8..c684eacf8 100644 --- a/src/input/events/GAME_OUT_EVENT.js +++ b/src/input/events/GAME_OUT_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Game Out Event. - * - * This event is dispatched by the Input Plugin if the active pointer leaves the game canvas and is now - * outside of it, elsewhere on the web page. - * - * Listen to this event from within a Scene using: `this.input.on('gameout', listener)`. - * - * @event Phaser.Input.Events#GAME_OUT - * @since 3.16.1 - * - * @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 {(MouseEvent|TouchEvent)} event - The DOM Event that triggered the canvas out. - */ -module.exports = 'gameout'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Game Out Event. + * + * This event is dispatched by the Input Plugin if the active pointer leaves the game canvas and is now + * outside of it, elsewhere on the web page. + * + * Listen to this event from within a Scene using: `this.input.on('gameout', listener)`. + * + * @event Phaser.Input.Events#GAME_OUT + * @since 3.16.1 + * + * @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 {(MouseEvent|TouchEvent)} event - The DOM Event that triggered the canvas out. + */ +module.exports = 'gameout'; diff --git a/src/input/events/GAME_OVER_EVENT.js b/src/input/events/GAME_OVER_EVENT.js index bb76e00b3..703093202 100644 --- a/src/input/events/GAME_OVER_EVENT.js +++ b/src/input/events/GAME_OVER_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Game Over Event. - * - * This event is dispatched by the Input Plugin if the active pointer enters the game canvas and is now - * over of it, having previously been elsewhere on the web page. - * - * Listen to this event from within a Scene using: `this.input.on('gameover', listener)`. - * - * @event Phaser.Input.Events#GAME_OVER - * @since 3.16.1 - * - * @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 {(MouseEvent|TouchEvent)} event - The DOM Event that triggered the canvas over. - */ -module.exports = 'gameover'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Game Over Event. + * + * This event is dispatched by the Input Plugin if the active pointer enters the game canvas and is now + * over of it, having previously been elsewhere on the web page. + * + * Listen to this event from within a Scene using: `this.input.on('gameover', listener)`. + * + * @event Phaser.Input.Events#GAME_OVER + * @since 3.16.1 + * + * @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 {(MouseEvent|TouchEvent)} event - The DOM Event that triggered the canvas over. + */ +module.exports = 'gameover'; diff --git a/src/input/events/MANAGER_BOOT_EVENT.js b/src/input/events/MANAGER_BOOT_EVENT.js index da42a8749..76d663330 100644 --- a/src/input/events/MANAGER_BOOT_EVENT.js +++ b/src/input/events/MANAGER_BOOT_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Manager Boot Event. - * - * This internal event is dispatched by the Input Manager when it boots. - * - * @event Phaser.Input.Events#MANAGER_BOOT - * @since 3.0.0 - */ -module.exports = 'boot'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Manager Boot Event. + * + * This internal event is dispatched by the Input Manager when it boots. + * + * @event Phaser.Input.Events#MANAGER_BOOT + * @since 3.0.0 + */ +module.exports = 'boot'; diff --git a/src/input/events/MANAGER_PROCESS_EVENT.js b/src/input/events/MANAGER_PROCESS_EVENT.js index aa2c8b422..02dec2355 100644 --- a/src/input/events/MANAGER_PROCESS_EVENT.js +++ b/src/input/events/MANAGER_PROCESS_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'process'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'process'; diff --git a/src/input/events/MANAGER_UPDATE_EVENT.js b/src/input/events/MANAGER_UPDATE_EVENT.js index f58acc77b..c5b922c8c 100644 --- a/src/input/events/MANAGER_UPDATE_EVENT.js +++ b/src/input/events/MANAGER_UPDATE_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Manager Update Event. - * - * This internal event is dispatched by the Input Manager as part of its update step. - * - * @event Phaser.Input.Events#MANAGER_UPDATE - * @since 3.0.0 - */ -module.exports = 'update'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Manager Update Event. + * + * This internal event is dispatched by the Input Manager as part of its update step. + * + * @event Phaser.Input.Events#MANAGER_UPDATE + * @since 3.0.0 + */ +module.exports = 'update'; diff --git a/src/input/events/POINTERLOCK_CHANGE_EVENT.js b/src/input/events/POINTERLOCK_CHANGE_EVENT.js index 90a5926d3..e9cd6a1c2 100644 --- a/src/input/events/POINTERLOCK_CHANGE_EVENT.js +++ b/src/input/events/POINTERLOCK_CHANGE_EVENT.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Manager Pointer Lock Change Event. - * - * This event is dispatched by the Input Manager when it is processing a native Pointer Lock Change DOM Event. - * - * @event Phaser.Input.Events#POINTERLOCK_CHANGE - * @since 3.0.0 - * - * @param {Event} event - The native DOM Event. - * @param {boolean} locked - The locked state of the Mouse Pointer. - */ -module.exports = 'pointerlockchange'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Manager Pointer Lock Change Event. + * + * This event is dispatched by the Input Manager when it is processing a native Pointer Lock Change DOM Event. + * + * @event Phaser.Input.Events#POINTERLOCK_CHANGE + * @since 3.0.0 + * + * @param {Event} event - The native DOM Event. + * @param {boolean} locked - The locked state of the Mouse Pointer. + */ +module.exports = 'pointerlockchange'; diff --git a/src/input/events/POINTER_DOWN_EVENT.js b/src/input/events/POINTER_DOWN_EVENT.js index e9116d427..047a2a047 100644 --- a/src/input/events/POINTER_DOWN_EVENT.js +++ b/src/input/events/POINTER_DOWN_EVENT.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Down Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere. - * - * Listen to this event from within a Scene using: `this.input.on('pointerdown', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_DOWN - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. - */ -module.exports = 'pointerdown'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Down Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointerdown', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + */ +module.exports = 'pointerdown'; diff --git a/src/input/events/POINTER_DOWN_OUTSIDE_EVENT.js b/src/input/events/POINTER_DOWN_OUTSIDE_EVENT.js index 5290c45a9..92caa7dde 100644 --- a/src/input/events/POINTER_DOWN_OUTSIDE_EVENT.js +++ b/src/input/events/POINTER_DOWN_OUTSIDE_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Down Outside Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere outside of the game canvas. - * - * Listen to this event from within a Scene using: `this.input.on('pointerdownoutside', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_DOWN_OUTSIDE - * @since 3.16.1 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - */ -module.exports = 'pointerdownoutside'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Down Outside Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere outside of the game canvas. + * + * Listen to this event from within a Scene using: `this.input.on('pointerdownoutside', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_DOWN_OUTSIDE + * @since 3.16.1 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + */ +module.exports = 'pointerdownoutside'; diff --git a/src/input/events/POINTER_MOVE_EVENT.js b/src/input/events/POINTER_MOVE_EVENT.js index 3ae600009..3c518e1c6 100644 --- a/src/input/events/POINTER_MOVE_EVENT.js +++ b/src/input/events/POINTER_MOVE_EVENT.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Move Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved anywhere. - * - * Listen to this event from within a Scene using: `this.input.on('pointermove', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} - * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} - * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_MOVE - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. - */ -module.exports = 'pointermove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Move Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointermove', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_MOVE + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + */ +module.exports = 'pointermove'; diff --git a/src/input/events/POINTER_OUT_EVENT.js b/src/input/events/POINTER_OUT_EVENT.js index 9dbd61e05..32025f433 100644 --- a/src/input/events/POINTER_OUT_EVENT.js +++ b/src/input/events/POINTER_OUT_EVENT.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Out Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of any interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('pointerout', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} - * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} - * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_OUT - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject[]} justOut - An array containing all interactive Game Objects that the pointer moved out of when the event was created. - */ -module.exports = 'pointerout'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Out Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of any interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('pointerout', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_OUT + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} justOut - An array containing all interactive Game Objects that the pointer moved out of when the event was created. + */ +module.exports = 'pointerout'; diff --git a/src/input/events/POINTER_OVER_EVENT.js b/src/input/events/POINTER_OVER_EVENT.js index 1304784f5..3dfb1808d 100644 --- a/src/input/events/POINTER_OVER_EVENT.js +++ b/src/input/events/POINTER_OVER_EVENT.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Over Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over any interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('pointerover', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} - * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} - * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_OVER - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject[]} justOver - An array containing all interactive Game Objects that the pointer moved over when the event was created. - */ -module.exports = 'pointerover'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over any interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('pointerover', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_OVER + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} justOver - An array containing all interactive Game Objects that the pointer moved over when the event was created. + */ +module.exports = 'pointerover'; diff --git a/src/input/events/POINTER_UP_EVENT.js b/src/input/events/POINTER_UP_EVENT.js index 05ce8fe49..769085437 100644 --- a/src/input/events/POINTER_UP_EVENT.js +++ b/src/input/events/POINTER_UP_EVENT.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Up Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere. - * - * Listen to this event from within a Scene using: `this.input.on('pointerup', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_UP - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. - */ -module.exports = 'pointerup'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Up Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointerup', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_UP + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + */ +module.exports = 'pointerup'; diff --git a/src/input/events/POINTER_UP_OUTSIDE_EVENT.js b/src/input/events/POINTER_UP_OUTSIDE_EVENT.js index c0dece412..b655a2d37 100644 --- a/src/input/events/POINTER_UP_OUTSIDE_EVENT.js +++ b/src/input/events/POINTER_UP_OUTSIDE_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Up Outside Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere outside of the game canvas. - * - * Listen to this event from within a Scene using: `this.input.on('pointerupoutside', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_UP_OUTSIDE - * @since 3.16.1 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - */ -module.exports = 'pointerupoutside'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Up Outside Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere outside of the game canvas. + * + * Listen to this event from within a Scene using: `this.input.on('pointerupoutside', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_UP_OUTSIDE + * @since 3.16.1 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + */ +module.exports = 'pointerupoutside'; diff --git a/src/input/events/POINTER_WHEEL_EVENT.js b/src/input/events/POINTER_WHEEL_EVENT.js index c902588ee..4d79642d8 100644 --- a/src/input/events/POINTER_WHEEL_EVENT.js +++ b/src/input/events/POINTER_WHEEL_EVENT.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pointer Wheel Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel updated. - * - * Listen to this event from within a Scene using: `this.input.on('wheel', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} - * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} - * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - * - * @event Phaser.Input.Events#POINTER_WHEEL - * @since 3.18.0 - * - * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. - * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. - * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. - * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. - */ -module.exports = 'wheel'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pointer Wheel Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel updated. + * + * Listen to this event from within a Scene using: `this.input.on('wheel', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + * + * @event Phaser.Input.Events#POINTER_WHEEL + * @since 3.18.0 + * + * @param {Phaser.Input.Pointer} pointer - The Pointer responsible for triggering this event. + * @param {Phaser.GameObjects.GameObject[]} currentlyOver - An array containing all interactive Game Objects that the pointer was over when the event was created. + * @param {number} deltaX - The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * @param {number} deltaY - The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + * @param {number} deltaZ - The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + */ +module.exports = 'wheel'; diff --git a/src/input/events/PRE_UPDATE_EVENT.js b/src/input/events/PRE_UPDATE_EVENT.js index 9c37ccba4..20e093206 100644 --- a/src/input/events/PRE_UPDATE_EVENT.js +++ b/src/input/events/PRE_UPDATE_EVENT.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Pre-Update Event. - * - * This internal event is dispatched by the Input Plugin at the start of its `preUpdate` method. - * This hook is designed specifically for input plugins, but can also be listened to from user-land code. - * - * @event Phaser.Input.Events#PRE_UPDATE - * @since 3.0.0 - */ -module.exports = 'preupdate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Pre-Update Event. + * + * This internal event is dispatched by the Input Plugin at the start of its `preUpdate` method. + * This hook is designed specifically for input plugins, but can also be listened to from user-land code. + * + * @event Phaser.Input.Events#PRE_UPDATE + * @since 3.0.0 + */ +module.exports = 'preupdate'; diff --git a/src/input/events/SHUTDOWN_EVENT.js b/src/input/events/SHUTDOWN_EVENT.js index 8ed7b30a3..98d872af8 100644 --- a/src/input/events/SHUTDOWN_EVENT.js +++ b/src/input/events/SHUTDOWN_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Shutdown Event. - * - * This internal event is dispatched by the Input Plugin when it shuts down, signalling to all of its systems to shut themselves down. - * - * @event Phaser.Input.Events#SHUTDOWN - * @since 3.0.0 - */ -module.exports = 'shutdown'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Shutdown Event. + * + * This internal event is dispatched by the Input Plugin when it shuts down, signalling to all of its systems to shut themselves down. + * + * @event Phaser.Input.Events#SHUTDOWN + * @since 3.0.0 + */ +module.exports = 'shutdown'; diff --git a/src/input/events/START_EVENT.js b/src/input/events/START_EVENT.js index 1395adb41..349b48b05 100644 --- a/src/input/events/START_EVENT.js +++ b/src/input/events/START_EVENT.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Input Plugin Start Event. - * - * This internal event is dispatched by the Input Plugin when it has finished setting-up, - * signalling to all of its internal systems to start. - * - * @event Phaser.Input.Events#START - * @since 3.0.0 - */ -module.exports = 'start'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Input Plugin Start Event. + * + * This internal event is dispatched by the Input Plugin when it has finished setting-up, + * signalling to all of its internal systems to start. + * + * @event Phaser.Input.Events#START + * @since 3.0.0 + */ +module.exports = 'start'; diff --git a/src/input/events/UPDATE_EVENT.js b/src/input/events/UPDATE_EVENT.js index a95fc9b21..ea2839ad8 100644 --- a/src/input/events/UPDATE_EVENT.js +++ b/src/input/events/UPDATE_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'update'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'update'; diff --git a/src/input/events/index.js b/src/input/events/index.js index d1e19bfb4..b5deb4862 100644 --- a/src/input/events/index.js +++ b/src/input/events/index.js @@ -1,60 +1,60 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Events - */ - -module.exports = { - - BOOT: require('./BOOT_EVENT'), - DESTROY: require('./DESTROY_EVENT'), - DRAG_END: require('./DRAG_END_EVENT'), - DRAG_ENTER: require('./DRAG_ENTER_EVENT'), - DRAG: require('./DRAG_EVENT'), - DRAG_LEAVE: require('./DRAG_LEAVE_EVENT'), - DRAG_OVER: require('./DRAG_OVER_EVENT'), - DRAG_START: require('./DRAG_START_EVENT'), - DROP: require('./DROP_EVENT'), - GAME_OUT: require('./GAME_OUT_EVENT'), - GAME_OVER: require('./GAME_OVER_EVENT'), - GAMEOBJECT_DOWN: require('./GAMEOBJECT_DOWN_EVENT'), - GAMEOBJECT_DRAG_END: require('./GAMEOBJECT_DRAG_END_EVENT'), - GAMEOBJECT_DRAG_ENTER: require('./GAMEOBJECT_DRAG_ENTER_EVENT'), - GAMEOBJECT_DRAG: require('./GAMEOBJECT_DRAG_EVENT'), - GAMEOBJECT_DRAG_LEAVE: require('./GAMEOBJECT_DRAG_LEAVE_EVENT'), - GAMEOBJECT_DRAG_OVER: require('./GAMEOBJECT_DRAG_OVER_EVENT'), - GAMEOBJECT_DRAG_START: require('./GAMEOBJECT_DRAG_START_EVENT'), - GAMEOBJECT_DROP: require('./GAMEOBJECT_DROP_EVENT'), - GAMEOBJECT_MOVE: require('./GAMEOBJECT_MOVE_EVENT'), - GAMEOBJECT_OUT: require('./GAMEOBJECT_OUT_EVENT'), - GAMEOBJECT_OVER: require('./GAMEOBJECT_OVER_EVENT'), - GAMEOBJECT_POINTER_DOWN: require('./GAMEOBJECT_POINTER_DOWN_EVENT'), - GAMEOBJECT_POINTER_MOVE: require('./GAMEOBJECT_POINTER_MOVE_EVENT'), - GAMEOBJECT_POINTER_OUT: require('./GAMEOBJECT_POINTER_OUT_EVENT'), - GAMEOBJECT_POINTER_OVER: require('./GAMEOBJECT_POINTER_OVER_EVENT'), - GAMEOBJECT_POINTER_UP: require('./GAMEOBJECT_POINTER_UP_EVENT'), - GAMEOBJECT_POINTER_WHEEL: require('./GAMEOBJECT_POINTER_WHEEL_EVENT'), - GAMEOBJECT_UP: require('./GAMEOBJECT_UP_EVENT'), - GAMEOBJECT_WHEEL: require('./GAMEOBJECT_WHEEL_EVENT'), - MANAGER_BOOT: require('./MANAGER_BOOT_EVENT'), - MANAGER_PROCESS: require('./MANAGER_PROCESS_EVENT'), - MANAGER_UPDATE: require('./MANAGER_UPDATE_EVENT'), - POINTER_DOWN: require('./POINTER_DOWN_EVENT'), - POINTER_DOWN_OUTSIDE: require('./POINTER_DOWN_OUTSIDE_EVENT'), - POINTER_MOVE: require('./POINTER_MOVE_EVENT'), - POINTER_OUT: require('./POINTER_OUT_EVENT'), - POINTER_OVER: require('./POINTER_OVER_EVENT'), - POINTER_UP: require('./POINTER_UP_EVENT'), - POINTER_UP_OUTSIDE: require('./POINTER_UP_OUTSIDE_EVENT'), - POINTER_WHEEL: require('./POINTER_WHEEL_EVENT'), - POINTERLOCK_CHANGE: require('./POINTERLOCK_CHANGE_EVENT'), - PRE_UPDATE: require('./PRE_UPDATE_EVENT'), - SHUTDOWN: require('./SHUTDOWN_EVENT'), - START: require('./START_EVENT'), - UPDATE: require('./UPDATE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Events + */ + +module.exports = { + + BOOT: require('./BOOT_EVENT'), + DESTROY: require('./DESTROY_EVENT'), + DRAG_END: require('./DRAG_END_EVENT'), + DRAG_ENTER: require('./DRAG_ENTER_EVENT'), + DRAG: require('./DRAG_EVENT'), + DRAG_LEAVE: require('./DRAG_LEAVE_EVENT'), + DRAG_OVER: require('./DRAG_OVER_EVENT'), + DRAG_START: require('./DRAG_START_EVENT'), + DROP: require('./DROP_EVENT'), + GAME_OUT: require('./GAME_OUT_EVENT'), + GAME_OVER: require('./GAME_OVER_EVENT'), + GAMEOBJECT_DOWN: require('./GAMEOBJECT_DOWN_EVENT'), + GAMEOBJECT_DRAG_END: require('./GAMEOBJECT_DRAG_END_EVENT'), + GAMEOBJECT_DRAG_ENTER: require('./GAMEOBJECT_DRAG_ENTER_EVENT'), + GAMEOBJECT_DRAG: require('./GAMEOBJECT_DRAG_EVENT'), + GAMEOBJECT_DRAG_LEAVE: require('./GAMEOBJECT_DRAG_LEAVE_EVENT'), + GAMEOBJECT_DRAG_OVER: require('./GAMEOBJECT_DRAG_OVER_EVENT'), + GAMEOBJECT_DRAG_START: require('./GAMEOBJECT_DRAG_START_EVENT'), + GAMEOBJECT_DROP: require('./GAMEOBJECT_DROP_EVENT'), + GAMEOBJECT_MOVE: require('./GAMEOBJECT_MOVE_EVENT'), + GAMEOBJECT_OUT: require('./GAMEOBJECT_OUT_EVENT'), + GAMEOBJECT_OVER: require('./GAMEOBJECT_OVER_EVENT'), + GAMEOBJECT_POINTER_DOWN: require('./GAMEOBJECT_POINTER_DOWN_EVENT'), + GAMEOBJECT_POINTER_MOVE: require('./GAMEOBJECT_POINTER_MOVE_EVENT'), + GAMEOBJECT_POINTER_OUT: require('./GAMEOBJECT_POINTER_OUT_EVENT'), + GAMEOBJECT_POINTER_OVER: require('./GAMEOBJECT_POINTER_OVER_EVENT'), + GAMEOBJECT_POINTER_UP: require('./GAMEOBJECT_POINTER_UP_EVENT'), + GAMEOBJECT_POINTER_WHEEL: require('./GAMEOBJECT_POINTER_WHEEL_EVENT'), + GAMEOBJECT_UP: require('./GAMEOBJECT_UP_EVENT'), + GAMEOBJECT_WHEEL: require('./GAMEOBJECT_WHEEL_EVENT'), + MANAGER_BOOT: require('./MANAGER_BOOT_EVENT'), + MANAGER_PROCESS: require('./MANAGER_PROCESS_EVENT'), + MANAGER_UPDATE: require('./MANAGER_UPDATE_EVENT'), + POINTER_DOWN: require('./POINTER_DOWN_EVENT'), + POINTER_DOWN_OUTSIDE: require('./POINTER_DOWN_OUTSIDE_EVENT'), + POINTER_MOVE: require('./POINTER_MOVE_EVENT'), + POINTER_OUT: require('./POINTER_OUT_EVENT'), + POINTER_OVER: require('./POINTER_OVER_EVENT'), + POINTER_UP: require('./POINTER_UP_EVENT'), + POINTER_UP_OUTSIDE: require('./POINTER_UP_OUTSIDE_EVENT'), + POINTER_WHEEL: require('./POINTER_WHEEL_EVENT'), + POINTERLOCK_CHANGE: require('./POINTERLOCK_CHANGE_EVENT'), + PRE_UPDATE: require('./PRE_UPDATE_EVENT'), + SHUTDOWN: require('./SHUTDOWN_EVENT'), + START: require('./START_EVENT'), + UPDATE: require('./UPDATE_EVENT') + +}; diff --git a/src/input/gamepad/Axis.js b/src/input/gamepad/Axis.js index c56db03e5..e062b329b 100644 --- a/src/input/gamepad/Axis.js +++ b/src/input/gamepad/Axis.js @@ -1,119 +1,119 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); - -/** - * @classdesc - * Contains information about a specific Gamepad Axis. - * Axis objects are created automatically by the Gamepad as they are needed. - * - * @class Axis - * @memberof Phaser.Input.Gamepad - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Axis belongs to. - * @param {integer} index - The index of this Axis. - */ -var Axis = new Class({ - - initialize: - - function Axis (pad, index) - { - /** - * A reference to the Gamepad that this Axis belongs to. - * - * @name Phaser.Input.Gamepad.Axis#pad - * @type {Phaser.Input.Gamepad.Gamepad} - * @since 3.0.0 - */ - this.pad = pad; - - /** - * An event emitter to use to emit the axis events. - * - * @name Phaser.Input.Gamepad.Axis#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events = pad.events; - - /** - * The index of this Axis. - * - * @name Phaser.Input.Gamepad.Axis#index - * @type {integer} - * @since 3.0.0 - */ - this.index = index; - - /** - * The raw axis value, between -1 and 1 with 0 being dead center. - * Use the method `getValue` to get a normalized value with the threshold applied. - * - * @name Phaser.Input.Gamepad.Axis#value - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.value = 0; - - /** - * Movement tolerance threshold below which axis values are ignored in `getValue`. - * - * @name Phaser.Input.Gamepad.Axis#threshold - * @type {number} - * @default 0.1 - * @since 3.0.0 - */ - this.threshold = 0.1; - }, - - /** - * Internal update handler for this Axis. - * Called automatically by the Gamepad as part of its update. - * - * @method Phaser.Input.Gamepad.Axis#update - * @private - * @since 3.0.0 - * - * @param {number} value - The value of the axis movement. - */ - update: function (value) - { - this.value = value; - }, - - /** - * Applies the `threshold` value to the axis and returns it. - * - * @method Phaser.Input.Gamepad.Axis#getValue - * @since 3.0.0 - * - * @return {number} The axis value, adjusted for the movement threshold. - */ - getValue: function () - { - return (Math.abs(this.value) < this.threshold) ? 0 : this.value; - }, - - /** - * Destroys this Axis instance and releases external references it holds. - * - * @method Phaser.Input.Gamepad.Axis#destroy - * @since 3.10.0 - */ - destroy: function () - { - this.pad = null; - this.events = null; - } - -}); - -module.exports = Axis; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); + +/** + * @classdesc + * Contains information about a specific Gamepad Axis. + * Axis objects are created automatically by the Gamepad as they are needed. + * + * @class Axis + * @memberof Phaser.Input.Gamepad + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Axis belongs to. + * @param {integer} index - The index of this Axis. + */ +var Axis = new Class({ + + initialize: + + function Axis (pad, index) + { + /** + * A reference to the Gamepad that this Axis belongs to. + * + * @name Phaser.Input.Gamepad.Axis#pad + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.0.0 + */ + this.pad = pad; + + /** + * An event emitter to use to emit the axis events. + * + * @name Phaser.Input.Gamepad.Axis#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = pad.events; + + /** + * The index of this Axis. + * + * @name Phaser.Input.Gamepad.Axis#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * The raw axis value, between -1 and 1 with 0 being dead center. + * Use the method `getValue` to get a normalized value with the threshold applied. + * + * @name Phaser.Input.Gamepad.Axis#value + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.value = 0; + + /** + * Movement tolerance threshold below which axis values are ignored in `getValue`. + * + * @name Phaser.Input.Gamepad.Axis#threshold + * @type {number} + * @default 0.1 + * @since 3.0.0 + */ + this.threshold = 0.1; + }, + + /** + * Internal update handler for this Axis. + * Called automatically by the Gamepad as part of its update. + * + * @method Phaser.Input.Gamepad.Axis#update + * @private + * @since 3.0.0 + * + * @param {number} value - The value of the axis movement. + */ + update: function (value) + { + this.value = value; + }, + + /** + * Applies the `threshold` value to the axis and returns it. + * + * @method Phaser.Input.Gamepad.Axis#getValue + * @since 3.0.0 + * + * @return {number} The axis value, adjusted for the movement threshold. + */ + getValue: function () + { + return (Math.abs(this.value) < this.threshold) ? 0 : this.value; + }, + + /** + * Destroys this Axis instance and releases external references it holds. + * + * @method Phaser.Input.Gamepad.Axis#destroy + * @since 3.10.0 + */ + destroy: function () + { + this.pad = null; + this.events = null; + } + +}); + +module.exports = Axis; diff --git a/src/input/gamepad/Button.js b/src/input/gamepad/Button.js index 734a39e41..670591632 100644 --- a/src/input/gamepad/Button.js +++ b/src/input/gamepad/Button.js @@ -1,140 +1,140 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Events = require('./events'); - -/** - * @classdesc - * Contains information about a specific button on a Gamepad. - * Button objects are created automatically by the Gamepad as they are needed. - * - * @class Button - * @memberof Phaser.Input.Gamepad - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Button belongs to. - * @param {integer} index - The index of this Button. - */ -var Button = new Class({ - - initialize: - - function Button (pad, index) - { - /** - * A reference to the Gamepad that this Button belongs to. - * - * @name Phaser.Input.Gamepad.Button#pad - * @type {Phaser.Input.Gamepad.Gamepad} - * @since 3.0.0 - */ - this.pad = pad; - - /** - * An event emitter to use to emit the button events. - * - * @name Phaser.Input.Gamepad.Button#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events = pad.manager; - - /** - * The index of this Button. - * - * @name Phaser.Input.Gamepad.Button#index - * @type {integer} - * @since 3.0.0 - */ - this.index = index; - - /** - * Between 0 and 1. - * - * @name Phaser.Input.Gamepad.Button#value - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.value = 0; - - /** - * Can be set for analogue buttons to enable a 'pressure' threshold, - * before a button is considered as being 'pressed'. - * - * @name Phaser.Input.Gamepad.Button#threshold - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.threshold = 1; - - /** - * Is the Button being pressed down or not? - * - * @name Phaser.Input.Gamepad.Button#pressed - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.pressed = false; - }, - - /** - * Internal update handler for this Button. - * Called automatically by the Gamepad as part of its update. - * - * @method Phaser.Input.Gamepad.Button#update - * @fires Phaser.Input.Gamepad.Events#BUTTON_DOWN - * @fires Phaser.Input.Gamepad.Events#BUTTON_UP - * @fires Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_DOWN - * @fires Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_UP - * @private - * @since 3.0.0 - * - * @param {number} value - The value of the button. Between 0 and 1. - */ - update: function (value) - { - this.value = value; - - var pad = this.pad; - var index = this.index; - - if (value >= this.threshold) - { - if (!this.pressed) - { - this.pressed = true; - this.events.emit(Events.BUTTON_DOWN, pad, this, value); - this.pad.emit(Events.GAMEPAD_BUTTON_DOWN, index, value, this); - } - } - else if (this.pressed) - { - this.pressed = false; - this.events.emit(Events.BUTTON_UP, pad, this, value); - this.pad.emit(Events.GAMEPAD_BUTTON_UP, index, value, this); - } - }, - - /** - * Destroys this Button instance and releases external references it holds. - * - * @method Phaser.Input.Gamepad.Button#destroy - * @since 3.10.0 - */ - destroy: function () - { - this.pad = null; - this.events = null; - } - -}); - -module.exports = Button; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Events = require('./events'); + +/** + * @classdesc + * Contains information about a specific button on a Gamepad. + * Button objects are created automatically by the Gamepad as they are needed. + * + * @class Button + * @memberof Phaser.Input.Gamepad + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Button belongs to. + * @param {integer} index - The index of this Button. + */ +var Button = new Class({ + + initialize: + + function Button (pad, index) + { + /** + * A reference to the Gamepad that this Button belongs to. + * + * @name Phaser.Input.Gamepad.Button#pad + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.0.0 + */ + this.pad = pad; + + /** + * An event emitter to use to emit the button events. + * + * @name Phaser.Input.Gamepad.Button#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events = pad.manager; + + /** + * The index of this Button. + * + * @name Phaser.Input.Gamepad.Button#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * Between 0 and 1. + * + * @name Phaser.Input.Gamepad.Button#value + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.value = 0; + + /** + * Can be set for analogue buttons to enable a 'pressure' threshold, + * before a button is considered as being 'pressed'. + * + * @name Phaser.Input.Gamepad.Button#threshold + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.threshold = 1; + + /** + * Is the Button being pressed down or not? + * + * @name Phaser.Input.Gamepad.Button#pressed + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.pressed = false; + }, + + /** + * Internal update handler for this Button. + * Called automatically by the Gamepad as part of its update. + * + * @method Phaser.Input.Gamepad.Button#update + * @fires Phaser.Input.Gamepad.Events#BUTTON_DOWN + * @fires Phaser.Input.Gamepad.Events#BUTTON_UP + * @fires Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_DOWN + * @fires Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_UP + * @private + * @since 3.0.0 + * + * @param {number} value - The value of the button. Between 0 and 1. + */ + update: function (value) + { + this.value = value; + + var pad = this.pad; + var index = this.index; + + if (value >= this.threshold) + { + if (!this.pressed) + { + this.pressed = true; + this.events.emit(Events.BUTTON_DOWN, pad, this, value); + this.pad.emit(Events.GAMEPAD_BUTTON_DOWN, index, value, this); + } + } + else if (this.pressed) + { + this.pressed = false; + this.events.emit(Events.BUTTON_UP, pad, this, value); + this.pad.emit(Events.GAMEPAD_BUTTON_UP, index, value, this); + } + }, + + /** + * Destroys this Button instance and releases external references it holds. + * + * @method Phaser.Input.Gamepad.Button#destroy + * @since 3.10.0 + */ + destroy: function () + { + this.pad = null; + this.events = null; + } + +}); + +module.exports = Button; diff --git a/src/input/gamepad/Gamepad.js b/src/input/gamepad/Gamepad.js index 52e8ae57c..754654079 100644 --- a/src/input/gamepad/Gamepad.js +++ b/src/input/gamepad/Gamepad.js @@ -1,752 +1,752 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Axis = require('./Axis'); -var Button = require('./Button'); -var Class = require('../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A single Gamepad. - * - * These are created, updated and managed by the Gamepad Plugin. - * - * @class Gamepad - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Input.Gamepad - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.Gamepad.GamepadPlugin} manager - A reference to the Gamepad Plugin. - * @param {Phaser.Types.Input.Gamepad.Pad} pad - The Gamepad object, as extracted from GamepadEvent. - */ -var Gamepad = new Class({ - - Extends: EventEmitter, - - initialize: - - function Gamepad (manager, pad) - { - EventEmitter.call(this); - - /** - * A reference to the Gamepad Plugin. - * - * @name Phaser.Input.Gamepad.Gamepad#manager - * @type {Phaser.Input.Gamepad.GamepadPlugin} - * @since 3.0.0 - */ - this.manager = manager; - - /** - * A reference to the native Gamepad object that is connected to the browser. - * - * @name Phaser.Input.Gamepad.Gamepad#pad - * @type {any} - * @since 3.10.0 - */ - this.pad = pad; - - /** - * A string containing some information about the controller. - * - * This is not strictly specified, but in Firefox it will contain three pieces of information - * separated by dashes (-): two 4-digit hexadecimal strings containing the USB vendor and - * product id of the controller, and the name of the controller as provided by the driver. - * In Chrome it will contain the name of the controller as provided by the driver, - * followed by vendor and product 4-digit hexadecimal strings. - * - * @name Phaser.Input.Gamepad.Gamepad#id - * @type {string} - * @since 3.0.0 - */ - this.id = pad.id; - - /** - * An integer that is unique for each Gamepad currently connected to the system. - * This can be used to distinguish multiple controllers. - * Note that disconnecting a device and then connecting a new device may reuse the previous index. - * - * @name Phaser.Input.Gamepad.Gamepad#index - * @type {number} - * @since 3.0.0 - */ - this.index = pad.index; - - var buttons = []; - - for (var i = 0; i < pad.buttons.length; i++) - { - buttons.push(new Button(this, i)); - } - - /** - * An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad. - * - * @name Phaser.Input.Gamepad.Gamepad#buttons - * @type {Phaser.Input.Gamepad.Button[]} - * @since 3.0.0 - */ - this.buttons = buttons; - - var axes = []; - - for (i = 0; i < pad.axes.length; i++) - { - axes.push(new Axis(this, i)); - } - - /** - * An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any. - * - * @name Phaser.Input.Gamepad.Gamepad#axes - * @type {Phaser.Input.Gamepad.Axis[]} - * @since 3.0.0 - */ - this.axes = axes; - - /** - * The Gamepad's Haptic Actuator (Vibration / Rumble support). - * This is highly experimental and only set if both present on the device, - * and exposed by both the hardware and browser. - * - * @name Phaser.Input.Gamepad.Gamepad#vibration - * @type {GamepadHapticActuator} - * @since 3.10.0 - */ - this.vibration = pad.vibrationActuator; - - // https://w3c.github.io/gamepad/#remapping - - var _noButton = { value: 0, pressed: false }; - - /** - * A reference to the Left Button in the Left Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_LCLeft - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._LCLeft = (buttons[14]) ? buttons[14] : _noButton; - - /** - * A reference to the Right Button in the Left Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_LCRight - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._LCRight = (buttons[15]) ? buttons[15] : _noButton; - - /** - * A reference to the Top Button in the Left Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_LCTop - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._LCTop = (buttons[12]) ? buttons[12] : _noButton; - - /** - * A reference to the Bottom Button in the Left Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_LCBottom - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._LCBottom = (buttons[13]) ? buttons[13] : _noButton; - - /** - * A reference to the Left Button in the Right Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_RCLeft - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._RCLeft = (buttons[2]) ? buttons[2] : _noButton; - - /** - * A reference to the Right Button in the Right Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_RCRight - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._RCRight = (buttons[1]) ? buttons[1] : _noButton; - - /** - * A reference to the Top Button in the Right Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_RCTop - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._RCTop = (buttons[3]) ? buttons[3] : _noButton; - - /** - * A reference to the Bottom Button in the Right Cluster. - * - * @name Phaser.Input.Gamepad.Gamepad#_RCBottom - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._RCBottom = (buttons[0]) ? buttons[0] : _noButton; - - /** - * A reference to the Top Left Front Button (L1 Shoulder Button) - * - * @name Phaser.Input.Gamepad.Gamepad#_FBLeftTop - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._FBLeftTop = (buttons[4]) ? buttons[4] : _noButton; - - /** - * A reference to the Bottom Left Front Button (L2 Shoulder Button) - * - * @name Phaser.Input.Gamepad.Gamepad#_FBLeftBottom - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._FBLeftBottom = (buttons[6]) ? buttons[6] : _noButton; - - /** - * A reference to the Top Right Front Button (R1 Shoulder Button) - * - * @name Phaser.Input.Gamepad.Gamepad#_FBRightTop - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._FBRightTop = (buttons[5]) ? buttons[5] : _noButton; - - /** - * A reference to the Bottom Right Front Button (R2 Shoulder Button) - * - * @name Phaser.Input.Gamepad.Gamepad#_FBRightBottom - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._FBRightBottom = (buttons[7]) ? buttons[7] : _noButton; - - var _noAxis = { value: 0 }; - - /** - * A reference to the Horizontal Axis for the Left Stick. - * - * @name Phaser.Input.Gamepad.Gamepad#_HAxisLeft - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._HAxisLeft = (axes[0]) ? axes[0] : _noAxis; - - /** - * A reference to the Vertical Axis for the Left Stick. - * - * @name Phaser.Input.Gamepad.Gamepad#_VAxisLeft - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._VAxisLeft = (axes[1]) ? axes[1] : _noAxis; - - /** - * A reference to the Horizontal Axis for the Right Stick. - * - * @name Phaser.Input.Gamepad.Gamepad#_HAxisRight - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._HAxisRight = (axes[2]) ? axes[2] : _noAxis; - - /** - * A reference to the Vertical Axis for the Right Stick. - * - * @name Phaser.Input.Gamepad.Gamepad#_VAxisRight - * @type {Phaser.Input.Gamepad.Button} - * @private - * @since 3.10.0 - */ - this._VAxisRight = (axes[3]) ? axes[3] : _noAxis; - - /** - * 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 - */ - this.leftStick = new Vector2(); - - /** - * 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 - */ - this.rightStick = new Vector2(); - }, - - /** - * Gets the total number of axis this Gamepad claims to support. - * - * @method Phaser.Input.Gamepad.Gamepad#getAxisTotal - * @since 3.10.0 - * - * @return {integer} The total number of axes this Gamepad claims to support. - */ - getAxisTotal: function () - { - return this.axes.length; - }, - - /** - * 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 0 and 1. - * - * @method Phaser.Input.Gamepad.Gamepad#getAxisValue - * @since 3.10.0 - * - * @param {integer} index - The index of the axes to get the value for. - * - * @return {number} The value of the axis, between 0 and 1. - */ - getAxisValue: function (index) - { - return this.axes[index].getValue(); - }, - - /** - * Sets the threshold value of all axis on this Gamepad. - * The value is a float between 0 and 1 and is the amount below which the axis is considered as not having been moved. - * - * @method Phaser.Input.Gamepad.Gamepad#setAxisThreshold - * @since 3.10.0 - * - * @param {number} value - A value between 0 and 1. - */ - setAxisThreshold: function (value) - { - for (var i = 0; i < this.axes.length; i++) - { - this.axes[i].threshold = value; - } - }, - - /** - * Gets the total number of buttons this Gamepad claims to have. - * - * @method Phaser.Input.Gamepad.Gamepad#getButtonTotal - * @since 3.10.0 - * - * @return {integer} The total number of buttons this Gamepad claims to have. - */ - getButtonTotal: function () - { - return this.buttons.length; - }, - - /** - * 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 an analogue button, or a float between 0 and 1 - * for a pressure-sensitive digital button, such as the shoulder buttons on a Dual Shock. - * - * @method Phaser.Input.Gamepad.Gamepad#getButtonValue - * @since 3.10.0 - * - * @param {integer} index - The index of the button to get the value for. - * - * @return {number} The value of the button, between 0 and 1. - */ - getButtonValue: function (index) - { - return this.buttons[index].value; - }, - - /** - * Returns if the button is pressed down or not. - * The index must be valid within the range of buttons supported by this Gamepad. - * - * @method Phaser.Input.Gamepad.Gamepad#isButtonDown - * @since 3.10.0 - * - * @param {integer} index - The index of the button to get the value for. - * - * @return {boolean} `true` if the button is considered as being pressed down, otherwise `false`. - */ - isButtonDown: function (index) - { - return this.buttons[index].pressed; - }, - - /** - * Internal update handler for this Gamepad. - * Called automatically by the Gamepad Manager as part of its update. - * - * @method Phaser.Input.Gamepad.Gamepad#update - * @private - * @since 3.0.0 - */ - update: function (pad) - { - var i; - - // Sync the button values - - var localButtons = this.buttons; - var gamepadButtons = pad.buttons; - - var len = localButtons.length; - - for (i = 0; i < len; i++) - { - localButtons[i].update(gamepadButtons[i].value); - } - - // Sync the axis values - - var localAxes = this.axes; - var gamepadAxes = pad.axes; - - len = localAxes.length; - - for (i = 0; i < len; i++) - { - localAxes[i].update(gamepadAxes[i]); - } - - if (len >= 2) - { - this.leftStick.set(localAxes[0].getValue(), localAxes[1].getValue()); - - if (len >= 4) - { - this.rightStick.set(localAxes[2].getValue(), localAxes[3].getValue()); - } - } - }, - - /** - * Destroys this Gamepad instance, its buttons and axes, and releases external references it holds. - * - * @method Phaser.Input.Gamepad.Gamepad#destroy - * @since 3.10.0 - */ - destroy: function () - { - this.removeAllListeners(); - - this.manager = null; - this.pad = null; - - var i; - - for (i = 0; i < this.buttons.length; i++) - { - this.buttons[i].destroy(); - } - - for (i = 0; i < this.axes.length; i++) - { - this.axes[i].destroy(); - } - - this.buttons = []; - this.axes = []; - }, - - /** - * Is this Gamepad currently connected or not? - * - * @name Phaser.Input.Gamepad.Gamepad#connected - * @type {boolean} - * @default true - * @since 3.0.0 - */ - connected: { - - get: function () - { - return this.pad.connected; - } - - }, - - /** - * A timestamp containing the most recent time this Gamepad was updated. - * - * @name Phaser.Input.Gamepad.Gamepad#timestamp - * @type {number} - * @since 3.0.0 - */ - timestamp: { - - get: function () - { - return this.pad.timestamp; - } - - }, - - /** - * Is the Gamepad's Left button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad left button under standard Gamepad mapping. - * - * @name Phaser.Input.Gamepad.Gamepad#left - * @type {boolean} - * @since 3.10.0 - */ - left: { - - get: function () - { - return this._LCLeft.pressed; - } - - }, - - /** - * Is the Gamepad's Right button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad right button under standard Gamepad mapping. - * - * @name Phaser.Input.Gamepad.Gamepad#right - * @type {boolean} - * @since 3.10.0 - */ - right: { - - get: function () - { - return this._LCRight.pressed; - } - - }, - - /** - * Is the Gamepad's Up button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad up button under standard Gamepad mapping. - * - * @name Phaser.Input.Gamepad.Gamepad#up - * @type {boolean} - * @since 3.10.0 - */ - up: { - - get: function () - { - return this._LCTop.pressed; - } - - }, - - /** - * Is the Gamepad's Down button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad down button under standard Gamepad mapping. - * - * @name Phaser.Input.Gamepad.Gamepad#down - * @type {boolean} - * @since 3.10.0 - */ - down: { - - get: function () - { - return this._LCBottom.pressed; - } - - }, - - /** - * Is the Gamepad's bottom button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the X button. - * On an XBox controller it's the A button. - * - * @name Phaser.Input.Gamepad.Gamepad#A - * @type {boolean} - * @since 3.10.0 - */ - A: { - - get: function () - { - return this._RCBottom.pressed; - } - - }, - - /** - * Is the Gamepad's top button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the Triangle button. - * On an XBox controller it's the Y button. - * - * @name Phaser.Input.Gamepad.Gamepad#Y - * @type {boolean} - * @since 3.10.0 - */ - Y: { - - get: function () - { - return this._RCTop.pressed; - } - - }, - - /** - * Is the Gamepad's left button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the Square button. - * On an XBox controller it's the X button. - * - * @name Phaser.Input.Gamepad.Gamepad#X - * @type {boolean} - * @since 3.10.0 - */ - X: { - - get: function () - { - return this._RCLeft.pressed; - } - - }, - - /** - * Is the Gamepad's right button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the Circle button. - * On an XBox controller it's the B button. - * - * @name Phaser.Input.Gamepad.Gamepad#B - * @type {boolean} - * @since 3.10.0 - */ - B: { - - get: function () - { - return this._RCRight.pressed; - } - - }, - - /** - * Returns the value of the Gamepad's top left shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the L1 button. - * On an XBox controller it's the LB button. - * - * @name Phaser.Input.Gamepad.Gamepad#L1 - * @type {number} - * @since 3.10.0 - */ - L1: { - - get: function () - { - return this._FBLeftTop.value; - } - - }, - - /** - * Returns the value of the Gamepad's bottom left shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the L2 button. - * On an XBox controller it's the LT button. - * - * @name Phaser.Input.Gamepad.Gamepad#L2 - * @type {number} - * @since 3.10.0 - */ - L2: { - - get: function () - { - return this._FBLeftBottom.value; - } - - }, - - /** - * Returns the value of the Gamepad's top right shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the R1 button. - * On an XBox controller it's the RB button. - * - * @name Phaser.Input.Gamepad.Gamepad#R1 - * @type {number} - * @since 3.10.0 - */ - R1: { - - get: function () - { - return this._FBRightTop.value; - } - - }, - - /** - * Returns the value of the Gamepad's bottom right shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the R2 button. - * On an XBox controller it's the RT button. - * - * @name Phaser.Input.Gamepad.Gamepad#R2 - * @type {number} - * @since 3.10.0 - */ - R2: { - - get: function () - { - return this._FBRightBottom.value; - } - - } - -}); - -module.exports = Gamepad; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Axis = require('./Axis'); +var Button = require('./Button'); +var Class = require('../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A single Gamepad. + * + * These are created, updated and managed by the Gamepad Plugin. + * + * @class Gamepad + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Input.Gamepad + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad.GamepadPlugin} manager - A reference to the Gamepad Plugin. + * @param {Phaser.Types.Input.Gamepad.Pad} pad - The Gamepad object, as extracted from GamepadEvent. + */ +var Gamepad = new Class({ + + Extends: EventEmitter, + + initialize: + + function Gamepad (manager, pad) + { + EventEmitter.call(this); + + /** + * A reference to the Gamepad Plugin. + * + * @name Phaser.Input.Gamepad.Gamepad#manager + * @type {Phaser.Input.Gamepad.GamepadPlugin} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * A reference to the native Gamepad object that is connected to the browser. + * + * @name Phaser.Input.Gamepad.Gamepad#pad + * @type {any} + * @since 3.10.0 + */ + this.pad = pad; + + /** + * A string containing some information about the controller. + * + * This is not strictly specified, but in Firefox it will contain three pieces of information + * separated by dashes (-): two 4-digit hexadecimal strings containing the USB vendor and + * product id of the controller, and the name of the controller as provided by the driver. + * In Chrome it will contain the name of the controller as provided by the driver, + * followed by vendor and product 4-digit hexadecimal strings. + * + * @name Phaser.Input.Gamepad.Gamepad#id + * @type {string} + * @since 3.0.0 + */ + this.id = pad.id; + + /** + * An integer that is unique for each Gamepad currently connected to the system. + * This can be used to distinguish multiple controllers. + * Note that disconnecting a device and then connecting a new device may reuse the previous index. + * + * @name Phaser.Input.Gamepad.Gamepad#index + * @type {number} + * @since 3.0.0 + */ + this.index = pad.index; + + var buttons = []; + + for (var i = 0; i < pad.buttons.length; i++) + { + buttons.push(new Button(this, i)); + } + + /** + * An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad. + * + * @name Phaser.Input.Gamepad.Gamepad#buttons + * @type {Phaser.Input.Gamepad.Button[]} + * @since 3.0.0 + */ + this.buttons = buttons; + + var axes = []; + + for (i = 0; i < pad.axes.length; i++) + { + axes.push(new Axis(this, i)); + } + + /** + * An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any. + * + * @name Phaser.Input.Gamepad.Gamepad#axes + * @type {Phaser.Input.Gamepad.Axis[]} + * @since 3.0.0 + */ + this.axes = axes; + + /** + * The Gamepad's Haptic Actuator (Vibration / Rumble support). + * This is highly experimental and only set if both present on the device, + * and exposed by both the hardware and browser. + * + * @name Phaser.Input.Gamepad.Gamepad#vibration + * @type {GamepadHapticActuator} + * @since 3.10.0 + */ + this.vibration = pad.vibrationActuator; + + // https://w3c.github.io/gamepad/#remapping + + var _noButton = { value: 0, pressed: false }; + + /** + * A reference to the Left Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCLeft = (buttons[14]) ? buttons[14] : _noButton; + + /** + * A reference to the Right Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCRight = (buttons[15]) ? buttons[15] : _noButton; + + /** + * A reference to the Top Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCTop = (buttons[12]) ? buttons[12] : _noButton; + + /** + * A reference to the Bottom Button in the Left Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_LCBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._LCBottom = (buttons[13]) ? buttons[13] : _noButton; + + /** + * A reference to the Left Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCLeft = (buttons[2]) ? buttons[2] : _noButton; + + /** + * A reference to the Right Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCRight = (buttons[1]) ? buttons[1] : _noButton; + + /** + * A reference to the Top Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCTop = (buttons[3]) ? buttons[3] : _noButton; + + /** + * A reference to the Bottom Button in the Right Cluster. + * + * @name Phaser.Input.Gamepad.Gamepad#_RCBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._RCBottom = (buttons[0]) ? buttons[0] : _noButton; + + /** + * A reference to the Top Left Front Button (L1 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBLeftTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBLeftTop = (buttons[4]) ? buttons[4] : _noButton; + + /** + * A reference to the Bottom Left Front Button (L2 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBLeftBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBLeftBottom = (buttons[6]) ? buttons[6] : _noButton; + + /** + * A reference to the Top Right Front Button (R1 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBRightTop + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBRightTop = (buttons[5]) ? buttons[5] : _noButton; + + /** + * A reference to the Bottom Right Front Button (R2 Shoulder Button) + * + * @name Phaser.Input.Gamepad.Gamepad#_FBRightBottom + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._FBRightBottom = (buttons[7]) ? buttons[7] : _noButton; + + var _noAxis = { value: 0 }; + + /** + * A reference to the Horizontal Axis for the Left Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_HAxisLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._HAxisLeft = (axes[0]) ? axes[0] : _noAxis; + + /** + * A reference to the Vertical Axis for the Left Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_VAxisLeft + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._VAxisLeft = (axes[1]) ? axes[1] : _noAxis; + + /** + * A reference to the Horizontal Axis for the Right Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_HAxisRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._HAxisRight = (axes[2]) ? axes[2] : _noAxis; + + /** + * A reference to the Vertical Axis for the Right Stick. + * + * @name Phaser.Input.Gamepad.Gamepad#_VAxisRight + * @type {Phaser.Input.Gamepad.Button} + * @private + * @since 3.10.0 + */ + this._VAxisRight = (axes[3]) ? axes[3] : _noAxis; + + /** + * 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 + */ + this.leftStick = new Vector2(); + + /** + * 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 + */ + this.rightStick = new Vector2(); + }, + + /** + * Gets the total number of axis this Gamepad claims to support. + * + * @method Phaser.Input.Gamepad.Gamepad#getAxisTotal + * @since 3.10.0 + * + * @return {integer} The total number of axes this Gamepad claims to support. + */ + getAxisTotal: function () + { + return this.axes.length; + }, + + /** + * 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 0 and 1. + * + * @method Phaser.Input.Gamepad.Gamepad#getAxisValue + * @since 3.10.0 + * + * @param {integer} index - The index of the axes to get the value for. + * + * @return {number} The value of the axis, between 0 and 1. + */ + getAxisValue: function (index) + { + return this.axes[index].getValue(); + }, + + /** + * Sets the threshold value of all axis on this Gamepad. + * The value is a float between 0 and 1 and is the amount below which the axis is considered as not having been moved. + * + * @method Phaser.Input.Gamepad.Gamepad#setAxisThreshold + * @since 3.10.0 + * + * @param {number} value - A value between 0 and 1. + */ + setAxisThreshold: function (value) + { + for (var i = 0; i < this.axes.length; i++) + { + this.axes[i].threshold = value; + } + }, + + /** + * Gets the total number of buttons this Gamepad claims to have. + * + * @method Phaser.Input.Gamepad.Gamepad#getButtonTotal + * @since 3.10.0 + * + * @return {integer} The total number of buttons this Gamepad claims to have. + */ + getButtonTotal: function () + { + return this.buttons.length; + }, + + /** + * 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 an analogue button, or a float between 0 and 1 + * for a pressure-sensitive digital button, such as the shoulder buttons on a Dual Shock. + * + * @method Phaser.Input.Gamepad.Gamepad#getButtonValue + * @since 3.10.0 + * + * @param {integer} index - The index of the button to get the value for. + * + * @return {number} The value of the button, between 0 and 1. + */ + getButtonValue: function (index) + { + return this.buttons[index].value; + }, + + /** + * Returns if the button is pressed down or not. + * The index must be valid within the range of buttons supported by this Gamepad. + * + * @method Phaser.Input.Gamepad.Gamepad#isButtonDown + * @since 3.10.0 + * + * @param {integer} index - The index of the button to get the value for. + * + * @return {boolean} `true` if the button is considered as being pressed down, otherwise `false`. + */ + isButtonDown: function (index) + { + return this.buttons[index].pressed; + }, + + /** + * Internal update handler for this Gamepad. + * Called automatically by the Gamepad Manager as part of its update. + * + * @method Phaser.Input.Gamepad.Gamepad#update + * @private + * @since 3.0.0 + */ + update: function (pad) + { + var i; + + // Sync the button values + + var localButtons = this.buttons; + var gamepadButtons = pad.buttons; + + var len = localButtons.length; + + for (i = 0; i < len; i++) + { + localButtons[i].update(gamepadButtons[i].value); + } + + // Sync the axis values + + var localAxes = this.axes; + var gamepadAxes = pad.axes; + + len = localAxes.length; + + for (i = 0; i < len; i++) + { + localAxes[i].update(gamepadAxes[i]); + } + + if (len >= 2) + { + this.leftStick.set(localAxes[0].getValue(), localAxes[1].getValue()); + + if (len >= 4) + { + this.rightStick.set(localAxes[2].getValue(), localAxes[3].getValue()); + } + } + }, + + /** + * Destroys this Gamepad instance, its buttons and axes, and releases external references it holds. + * + * @method Phaser.Input.Gamepad.Gamepad#destroy + * @since 3.10.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.manager = null; + this.pad = null; + + var i; + + for (i = 0; i < this.buttons.length; i++) + { + this.buttons[i].destroy(); + } + + for (i = 0; i < this.axes.length; i++) + { + this.axes[i].destroy(); + } + + this.buttons = []; + this.axes = []; + }, + + /** + * Is this Gamepad currently connected or not? + * + * @name Phaser.Input.Gamepad.Gamepad#connected + * @type {boolean} + * @default true + * @since 3.0.0 + */ + connected: { + + get: function () + { + return this.pad.connected; + } + + }, + + /** + * A timestamp containing the most recent time this Gamepad was updated. + * + * @name Phaser.Input.Gamepad.Gamepad#timestamp + * @type {number} + * @since 3.0.0 + */ + timestamp: { + + get: function () + { + return this.pad.timestamp; + } + + }, + + /** + * Is the Gamepad's Left button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad left button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#left + * @type {boolean} + * @since 3.10.0 + */ + left: { + + get: function () + { + return this._LCLeft.pressed; + } + + }, + + /** + * Is the Gamepad's Right button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad right button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#right + * @type {boolean} + * @since 3.10.0 + */ + right: { + + get: function () + { + return this._LCRight.pressed; + } + + }, + + /** + * Is the Gamepad's Up button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad up button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#up + * @type {boolean} + * @since 3.10.0 + */ + up: { + + get: function () + { + return this._LCTop.pressed; + } + + }, + + /** + * Is the Gamepad's Down button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad down button under standard Gamepad mapping. + * + * @name Phaser.Input.Gamepad.Gamepad#down + * @type {boolean} + * @since 3.10.0 + */ + down: { + + get: function () + { + return this._LCBottom.pressed; + } + + }, + + /** + * Is the Gamepad's bottom button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the X button. + * On an XBox controller it's the A button. + * + * @name Phaser.Input.Gamepad.Gamepad#A + * @type {boolean} + * @since 3.10.0 + */ + A: { + + get: function () + { + return this._RCBottom.pressed; + } + + }, + + /** + * Is the Gamepad's top button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Triangle button. + * On an XBox controller it's the Y button. + * + * @name Phaser.Input.Gamepad.Gamepad#Y + * @type {boolean} + * @since 3.10.0 + */ + Y: { + + get: function () + { + return this._RCTop.pressed; + } + + }, + + /** + * Is the Gamepad's left button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Square button. + * On an XBox controller it's the X button. + * + * @name Phaser.Input.Gamepad.Gamepad#X + * @type {boolean} + * @since 3.10.0 + */ + X: { + + get: function () + { + return this._RCLeft.pressed; + } + + }, + + /** + * Is the Gamepad's right button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Circle button. + * On an XBox controller it's the B button. + * + * @name Phaser.Input.Gamepad.Gamepad#B + * @type {boolean} + * @since 3.10.0 + */ + B: { + + get: function () + { + return this._RCRight.pressed; + } + + }, + + /** + * Returns the value of the Gamepad's top left shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the L1 button. + * On an XBox controller it's the LB button. + * + * @name Phaser.Input.Gamepad.Gamepad#L1 + * @type {number} + * @since 3.10.0 + */ + L1: { + + get: function () + { + return this._FBLeftTop.value; + } + + }, + + /** + * Returns the value of the Gamepad's bottom left shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the L2 button. + * On an XBox controller it's the LT button. + * + * @name Phaser.Input.Gamepad.Gamepad#L2 + * @type {number} + * @since 3.10.0 + */ + L2: { + + get: function () + { + return this._FBLeftBottom.value; + } + + }, + + /** + * Returns the value of the Gamepad's top right shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the R1 button. + * On an XBox controller it's the RB button. + * + * @name Phaser.Input.Gamepad.Gamepad#R1 + * @type {number} + * @since 3.10.0 + */ + R1: { + + get: function () + { + return this._FBRightTop.value; + } + + }, + + /** + * Returns the value of the Gamepad's bottom right shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the R2 button. + * On an XBox controller it's the RT button. + * + * @name Phaser.Input.Gamepad.Gamepad#R2 + * @type {number} + * @since 3.10.0 + */ + R2: { + + get: function () + { + return this._FBRightBottom.value; + } + + } + +}); + +module.exports = Gamepad; diff --git a/src/input/gamepad/GamepadPlugin.js b/src/input/gamepad/GamepadPlugin.js index 50c72a5d1..ed3d6a3cc 100644 --- a/src/input/gamepad/GamepadPlugin.js +++ b/src/input/gamepad/GamepadPlugin.js @@ -1,632 +1,632 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var Gamepad = require('./Gamepad'); -var GetValue = require('../../utils/object/GetValue'); -var InputPluginCache = require('../InputPluginCache'); -var InputEvents = require('../events'); - -/** - * @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. - * - * 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 KeyboardPlugin belongs to. - */ -var GamepadPlugin = new Class({ - - Extends: EventEmitter, - - initialize: - - function GamepadPlugin (sceneInputPlugin) - { - EventEmitter.call(this); - - /** - * A reference to the Scene that this Input Plugin is responsible for. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#scene - * @type {Phaser.Scene} - * @since 3.10.0 - */ - this.scene = sceneInputPlugin.scene; - - /** - * A reference to the Scene Systems Settings. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#settings - * @type {Phaser.Types.Scenes.SettingsObject} - * @since 3.10.0 - */ - this.settings = this.scene.sys.settings; - - /** - * A reference to the Scene Input Plugin that created this Keyboard Plugin. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#sceneInputPlugin - * @type {Phaser.Input.InputPlugin} - * @since 3.10.0 - */ - this.sceneInputPlugin = sceneInputPlugin; - - /** - * A boolean that controls if the Gamepad Manager is enabled or not. - * Can be toggled on the fly. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#enabled - * @type {boolean} - * @default true - * @since 3.10.0 - */ - this.enabled = true; - - /** - * The Gamepad Event target, as defined in the Game Config. - * Typically the browser window, but can be any interactive DOM element. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#target - * @type {any} - * @since 3.10.0 - */ - this.target; - - /** - * An array of the connected Gamepads. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#gamepads - * @type {Phaser.Input.Gamepad.Gamepad[]} - * @default [] - * @since 3.10.0 - */ - this.gamepads = []; - - /** - * An internal event queue. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#queue - * @type {GamepadEvent[]} - * @private - * @since 3.10.0 - */ - this.queue = []; - - /** - * Internal event handler. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#onGamepadHandler - * @type {function} - * @private - * @since 3.10.0 - */ - this.onGamepadHandler; - - /** - * Internal Gamepad reference. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#_pad1 - * @type {Phaser.Input.Gamepad.Gamepad} - * @private - * @since 3.10.0 - */ - this._pad1; - - /** - * Internal Gamepad reference. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#_pad2 - * @type {Phaser.Input.Gamepad.Gamepad} - * @private - * @since 3.10.0 - */ - this._pad2; - - /** - * Internal Gamepad reference. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#_pad3 - * @type {Phaser.Input.Gamepad.Gamepad} - * @private - * @since 3.10.0 - */ - this._pad3; - - /** - * Internal Gamepad reference. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#_pad4 - * @type {Phaser.Input.Gamepad.Gamepad} - * @private - * @since 3.10.0 - */ - this._pad4; - - sceneInputPlugin.pluginEvents.once(InputEvents.BOOT, this.boot, this); - sceneInputPlugin.pluginEvents.on(InputEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#boot - * @private - * @since 3.10.0 - */ - boot: function () - { - var game = this.scene.sys.game; - var settings = this.settings.input; - var config = game.config; - - this.enabled = GetValue(settings, 'gamepad', config.inputGamepad) && game.device.input.gamepads; - this.target = GetValue(settings, 'gamepad.target', config.inputGamepadEventTarget); - - this.sceneInputPlugin.pluginEvents.once(InputEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#start - * @private - * @since 3.10.0 - */ - start: function () - { - if (this.enabled) - { - this.startListeners(); - } - - this.sceneInputPlugin.pluginEvents.once(InputEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * Checks to see if both this plugin and the Scene to which it belongs is active. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#isActive - * @since 3.10.0 - * - * @return {boolean} `true` if the plugin and the Scene it belongs to is active. - */ - isActive: function () - { - return (this.enabled && this.scene.sys.isActive()); - }, - - /** - * Starts the Gamepad Event listeners running. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#startListeners - * @private - * @since 3.10.0 - */ - startListeners: function () - { - var _this = this; - var target = this.target; - - var handler = function (event) - { - if (event.defaultPrevented || !_this.isActive()) - { - // Do nothing if event already handled - return; - } - - _this.refreshPads(); - - _this.queue.push(event); - }; - - this.onGamepadHandler = handler; - - target.addEventListener('gamepadconnected', handler, false); - target.addEventListener('gamepaddisconnected', handler, false); - - // 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 - this.sceneInputPlugin.pluginEvents.on(InputEvents.UPDATE, this.update, this); - }, - - /** - * Stops the Gamepad Event listeners. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#stopListeners - * @private - * @since 3.10.0 - */ - stopListeners: function () - { - this.target.removeEventListener('gamepadconnected', this.onGamepadHandler); - this.target.removeEventListener('gamepaddisconnected', this.onGamepadHandler); - - this.sceneInputPlugin.pluginEvents.off(InputEvents.UPDATE, this.update); - }, - - /** - * Disconnects all current Gamepads. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#disconnectAll - * @since 3.10.0 - */ - disconnectAll: function () - { - for (var i = 0; i < this.gamepads.length; i++) - { - this.gamepads.connected = false; - } - }, - - /** - * Refreshes the list of connected Gamepads. - * - * This is called automatically when a gamepad is connected or disconnected, - * and during the update loop. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#refreshPads - * @private - * @since 3.10.0 - */ - refreshPads: function () - { - var connectedPads = navigator.getGamepads(); - - if (!connectedPads) - { - this.disconnectAll(); - } - else - { - var currentPads = this.gamepads; - - for (var i = 0; i < connectedPads.length; i++) - { - var livePad = connectedPads[i]; - - // Because sometimes they're null (yes, really) - if (!livePad) - { - continue; - } - - var id = livePad.id; - var index = livePad.index; - var currentPad = currentPads[index]; - - if (!currentPad) - { - // A new Gamepad, not currently stored locally - var newPad = new Gamepad(this, livePad); - - currentPads[index] = newPad; - - if (!this._pad1) - { - this._pad1 = newPad; - } - else if (!this._pad2) - { - this._pad2 = newPad; - } - else if (!this._pad3) - { - this._pad3 = newPad; - } - else if (!this._pad4) - { - this._pad4 = newPad; - } - } - else if (currentPad.id !== id) - { - // A new Gamepad with a different vendor string, but it has got the same index as an old one - currentPad.destroy(); - - currentPads[index] = new Gamepad(this, livePad); - } - else - { - // If neither of these, it's a pad we've already got, so update it - currentPad.update(livePad); - } - } - } - }, - - /** - * Returns an array of all currently connected Gamepads. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#getAll - * @since 3.10.0 - * - * @return {Phaser.Input.Gamepad.Gamepad[]} An array of all currently connected Gamepads. - */ - getAll: function () - { - var out = []; - var pads = this.gamepads; - - for (var i = 0; i < pads.length; i++) - { - if (pads[i]) - { - out.push(pads[i]); - } - } - - return out; - }, - - /** - * 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. - */ - getPad: function (index) - { - var pads = this.gamepads; - - for (var i = 0; i < pads.length; i++) - { - if (pads[i] && pads[i].index === index) - { - return pads[i]; - } - } - }, - - /** - * The internal update loop. Refreshes all connected gamepads and processes their events. - * - * Called automatically by the Input Manager, invoked from the Game step. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#update - * @private - * @fires Phaser.Input.Gamepad.Events#CONNECTED - * @fires Phaser.Input.Gamepad.Events#DISCONNECTED - * @since 3.10.0 - */ - update: function () - { - if (!this.enabled) - { - return; - } - - this.refreshPads(); - - var len = this.queue.length; - - if (len === 0) - { - return; - } - - var queue = this.queue.splice(0, len); - - // Process the event queue, dispatching all of the events that have stored up - for (var i = 0; i < len; i++) - { - var event = queue[i]; - var pad = this.getPad(event.gamepad.index); - - if (event.type === 'gamepadconnected') - { - this.emit(Events.CONNECTED, pad, event); - } - else if (event.type === 'gamepaddisconnected') - { - this.emit(Events.DISCONNECTED, pad, event); - } - } - }, - - /** - * Shuts the Gamepad Plugin down. - * All this does is remove any listeners bound to it. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#shutdown - * @private - * @since 3.10.0 - */ - shutdown: function () - { - this.stopListeners(); - - this.disconnectAll(); - - this.removeAllListeners(); - }, - - /** - * Destroys this Gamepad Plugin, disconnecting all Gamepads and releasing internal references. - * - * @method Phaser.Input.Gamepad.GamepadPlugin#destroy - * @private - * @since 3.10.0 - */ - destroy: function () - { - this.shutdown(); - - for (var i = 0; i < this.gamepads.length; i++) - { - if (this.gamepads[i]) - { - this.gamepads[i].destroy(); - } - } - - this.gamepads = []; - - this.scene = null; - this.settings = null; - this.sceneInputPlugin = null; - this.target = null; - }, - - /** - * The total number of connected game pads. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#total - * @type {integer} - * @since 3.10.0 - */ - total: { - - get: function () - { - return this.gamepads.length; - } - - }, - - /** - * A reference to the first connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#pad1 - * @type {Phaser.Input.Gamepad.Gamepad} - * @since 3.10.0 - */ - pad1: { - - get: function () - { - return this._pad1; - } - - }, - - /** - * A reference to the second connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#pad2 - * @type {Phaser.Input.Gamepad.Gamepad} - * @since 3.10.0 - */ - pad2: { - - get: function () - { - return this._pad2; - } - - }, - - /** - * A reference to the third connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#pad3 - * @type {Phaser.Input.Gamepad.Gamepad} - * @since 3.10.0 - */ - pad3: { - - get: function () - { - return this._pad3; - } - - }, - - /** - * A reference to the fourth connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - * - * @name Phaser.Input.Gamepad.GamepadPlugin#pad4 - * @type {Phaser.Input.Gamepad.Gamepad} - * @since 3.10.0 - */ - pad4: { - - get: function () - { - return this._pad4; - } - - } - -}); - -/** - * An instance of the Gamepad Plugin class, if enabled via the `input.gamepad` Scene or Game Config property. - * Use this to create access Gamepads connected to the browser and respond to gamepad buttons. - * - * @name Phaser.Input.InputPlugin#gamepad - * @type {?Phaser.Input.Gamepad.GamepadPlugin} - * @since 3.10.0 - */ -InputPluginCache.register('GamepadPlugin', GamepadPlugin, 'gamepad', 'gamepad', 'inputGamepad'); - -module.exports = GamepadPlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var Gamepad = require('./Gamepad'); +var GetValue = require('../../utils/object/GetValue'); +var InputPluginCache = require('../InputPluginCache'); +var InputEvents = require('../events'); + +/** + * @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. + * + * 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 KeyboardPlugin belongs to. + */ +var GamepadPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function GamepadPlugin (sceneInputPlugin) + { + EventEmitter.call(this); + + /** + * A reference to the Scene that this Input Plugin is responsible for. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#scene + * @type {Phaser.Scene} + * @since 3.10.0 + */ + this.scene = sceneInputPlugin.scene; + + /** + * A reference to the Scene Systems Settings. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.10.0 + */ + this.settings = this.scene.sys.settings; + + /** + * A reference to the Scene Input Plugin that created this Keyboard Plugin. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#sceneInputPlugin + * @type {Phaser.Input.InputPlugin} + * @since 3.10.0 + */ + this.sceneInputPlugin = sceneInputPlugin; + + /** + * A boolean that controls if the Gamepad Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#enabled + * @type {boolean} + * @default true + * @since 3.10.0 + */ + this.enabled = true; + + /** + * The Gamepad Event target, as defined in the Game Config. + * Typically the browser window, but can be any interactive DOM element. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#target + * @type {any} + * @since 3.10.0 + */ + this.target; + + /** + * An array of the connected Gamepads. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#gamepads + * @type {Phaser.Input.Gamepad.Gamepad[]} + * @default [] + * @since 3.10.0 + */ + this.gamepads = []; + + /** + * An internal event queue. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#queue + * @type {GamepadEvent[]} + * @private + * @since 3.10.0 + */ + this.queue = []; + + /** + * Internal event handler. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#onGamepadHandler + * @type {function} + * @private + * @since 3.10.0 + */ + this.onGamepadHandler; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad1 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad1; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad2 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad2; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad3 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad3; + + /** + * Internal Gamepad reference. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#_pad4 + * @type {Phaser.Input.Gamepad.Gamepad} + * @private + * @since 3.10.0 + */ + this._pad4; + + sceneInputPlugin.pluginEvents.once(InputEvents.BOOT, this.boot, this); + sceneInputPlugin.pluginEvents.on(InputEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#boot + * @private + * @since 3.10.0 + */ + boot: function () + { + var game = this.scene.sys.game; + var settings = this.settings.input; + var config = game.config; + + this.enabled = GetValue(settings, 'gamepad', config.inputGamepad) && game.device.input.gamepads; + this.target = GetValue(settings, 'gamepad.target', config.inputGamepadEventTarget); + + this.sceneInputPlugin.pluginEvents.once(InputEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#start + * @private + * @since 3.10.0 + */ + start: function () + { + if (this.enabled) + { + this.startListeners(); + } + + this.sceneInputPlugin.pluginEvents.once(InputEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#isActive + * @since 3.10.0 + * + * @return {boolean} `true` if the plugin and the Scene it belongs to is active. + */ + isActive: function () + { + return (this.enabled && this.scene.sys.isActive()); + }, + + /** + * Starts the Gamepad Event listeners running. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#startListeners + * @private + * @since 3.10.0 + */ + startListeners: function () + { + var _this = this; + var target = this.target; + + var handler = function (event) + { + if (event.defaultPrevented || !_this.isActive()) + { + // Do nothing if event already handled + return; + } + + _this.refreshPads(); + + _this.queue.push(event); + }; + + this.onGamepadHandler = handler; + + target.addEventListener('gamepadconnected', handler, false); + target.addEventListener('gamepaddisconnected', handler, false); + + // 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 + this.sceneInputPlugin.pluginEvents.on(InputEvents.UPDATE, this.update, this); + }, + + /** + * Stops the Gamepad Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#stopListeners + * @private + * @since 3.10.0 + */ + stopListeners: function () + { + this.target.removeEventListener('gamepadconnected', this.onGamepadHandler); + this.target.removeEventListener('gamepaddisconnected', this.onGamepadHandler); + + this.sceneInputPlugin.pluginEvents.off(InputEvents.UPDATE, this.update); + }, + + /** + * Disconnects all current Gamepads. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#disconnectAll + * @since 3.10.0 + */ + disconnectAll: function () + { + for (var i = 0; i < this.gamepads.length; i++) + { + this.gamepads.connected = false; + } + }, + + /** + * Refreshes the list of connected Gamepads. + * + * This is called automatically when a gamepad is connected or disconnected, + * and during the update loop. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#refreshPads + * @private + * @since 3.10.0 + */ + refreshPads: function () + { + var connectedPads = navigator.getGamepads(); + + if (!connectedPads) + { + this.disconnectAll(); + } + else + { + var currentPads = this.gamepads; + + for (var i = 0; i < connectedPads.length; i++) + { + var livePad = connectedPads[i]; + + // Because sometimes they're null (yes, really) + if (!livePad) + { + continue; + } + + var id = livePad.id; + var index = livePad.index; + var currentPad = currentPads[index]; + + if (!currentPad) + { + // A new Gamepad, not currently stored locally + var newPad = new Gamepad(this, livePad); + + currentPads[index] = newPad; + + if (!this._pad1) + { + this._pad1 = newPad; + } + else if (!this._pad2) + { + this._pad2 = newPad; + } + else if (!this._pad3) + { + this._pad3 = newPad; + } + else if (!this._pad4) + { + this._pad4 = newPad; + } + } + else if (currentPad.id !== id) + { + // A new Gamepad with a different vendor string, but it has got the same index as an old one + currentPad.destroy(); + + currentPads[index] = new Gamepad(this, livePad); + } + else + { + // If neither of these, it's a pad we've already got, so update it + currentPad.update(livePad); + } + } + } + }, + + /** + * Returns an array of all currently connected Gamepads. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#getAll + * @since 3.10.0 + * + * @return {Phaser.Input.Gamepad.Gamepad[]} An array of all currently connected Gamepads. + */ + getAll: function () + { + var out = []; + var pads = this.gamepads; + + for (var i = 0; i < pads.length; i++) + { + if (pads[i]) + { + out.push(pads[i]); + } + } + + return out; + }, + + /** + * 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. + */ + getPad: function (index) + { + var pads = this.gamepads; + + for (var i = 0; i < pads.length; i++) + { + if (pads[i] && pads[i].index === index) + { + return pads[i]; + } + } + }, + + /** + * The internal update loop. Refreshes all connected gamepads and processes their events. + * + * Called automatically by the Input Manager, invoked from the Game step. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#update + * @private + * @fires Phaser.Input.Gamepad.Events#CONNECTED + * @fires Phaser.Input.Gamepad.Events#DISCONNECTED + * @since 3.10.0 + */ + update: function () + { + if (!this.enabled) + { + return; + } + + this.refreshPads(); + + var len = this.queue.length; + + if (len === 0) + { + return; + } + + var queue = this.queue.splice(0, len); + + // Process the event queue, dispatching all of the events that have stored up + for (var i = 0; i < len; i++) + { + var event = queue[i]; + var pad = this.getPad(event.gamepad.index); + + if (event.type === 'gamepadconnected') + { + this.emit(Events.CONNECTED, pad, event); + } + else if (event.type === 'gamepaddisconnected') + { + this.emit(Events.DISCONNECTED, pad, event); + } + } + }, + + /** + * Shuts the Gamepad Plugin down. + * All this does is remove any listeners bound to it. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#shutdown + * @private + * @since 3.10.0 + */ + shutdown: function () + { + this.stopListeners(); + + this.disconnectAll(); + + this.removeAllListeners(); + }, + + /** + * Destroys this Gamepad Plugin, disconnecting all Gamepads and releasing internal references. + * + * @method Phaser.Input.Gamepad.GamepadPlugin#destroy + * @private + * @since 3.10.0 + */ + destroy: function () + { + this.shutdown(); + + for (var i = 0; i < this.gamepads.length; i++) + { + if (this.gamepads[i]) + { + this.gamepads[i].destroy(); + } + } + + this.gamepads = []; + + this.scene = null; + this.settings = null; + this.sceneInputPlugin = null; + this.target = null; + }, + + /** + * The total number of connected game pads. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#total + * @type {integer} + * @since 3.10.0 + */ + total: { + + get: function () + { + return this.gamepads.length; + } + + }, + + /** + * A reference to the first connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad1 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad1: { + + get: function () + { + return this._pad1; + } + + }, + + /** + * A reference to the second connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad2 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad2: { + + get: function () + { + return this._pad2; + } + + }, + + /** + * A reference to the third connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad3 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad3: { + + get: function () + { + return this._pad3; + } + + }, + + /** + * A reference to the fourth connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + * + * @name Phaser.Input.Gamepad.GamepadPlugin#pad4 + * @type {Phaser.Input.Gamepad.Gamepad} + * @since 3.10.0 + */ + pad4: { + + get: function () + { + return this._pad4; + } + + } + +}); + +/** + * An instance of the Gamepad Plugin class, if enabled via the `input.gamepad` Scene or Game Config property. + * Use this to create access Gamepads connected to the browser and respond to gamepad buttons. + * + * @name Phaser.Input.InputPlugin#gamepad + * @type {?Phaser.Input.Gamepad.GamepadPlugin} + * @since 3.10.0 + */ +InputPluginCache.register('GamepadPlugin', GamepadPlugin, 'gamepad', 'gamepad', 'inputGamepad'); + +module.exports = GamepadPlugin; diff --git a/src/input/gamepad/configs/SNES_USB_Controller.js b/src/input/gamepad/configs/SNES_USB_Controller.js index bb13dae70..aea159568 100644 --- a/src/input/gamepad/configs/SNES_USB_Controller.js +++ b/src/input/gamepad/configs/SNES_USB_Controller.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Tatar SNES USB Controller Gamepad Configuration. - * USB Gamepad (STANDARD GAMEPAD Vendor: 0079 Product: 0011) - * - * @name Phaser.Input.Gamepad.Configs.SNES_USB - * @type {object} - * @since 3.0.0 - */ -module.exports = { - - UP: 12, - DOWN: 13, - LEFT: 14, - RIGHT: 15, - - SELECT: 8, - START: 9, - - B: 0, - A: 1, - Y: 2, - X: 3, - - LEFT_SHOULDER: 4, - RIGHT_SHOULDER: 5 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tatar SNES USB Controller Gamepad Configuration. + * USB Gamepad (STANDARD GAMEPAD Vendor: 0079 Product: 0011) + * + * @name Phaser.Input.Gamepad.Configs.SNES_USB + * @type {object} + * @since 3.0.0 + */ +module.exports = { + + UP: 12, + DOWN: 13, + LEFT: 14, + RIGHT: 15, + + SELECT: 8, + START: 9, + + B: 0, + A: 1, + Y: 2, + X: 3, + + LEFT_SHOULDER: 4, + RIGHT_SHOULDER: 5 + +}; diff --git a/src/input/gamepad/configs/Sony_PlayStation_DualShock_4.js b/src/input/gamepad/configs/Sony_PlayStation_DualShock_4.js index 3ce9d5aa0..1be701dca 100644 --- a/src/input/gamepad/configs/Sony_PlayStation_DualShock_4.js +++ b/src/input/gamepad/configs/Sony_PlayStation_DualShock_4.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * PlayStation DualShock 4 Gamepad Configuration. - * Sony PlayStation DualShock 4 (v2) wireless controller - * - * @name Phaser.Input.Gamepad.Configs.DUALSHOCK_4 - * @type {object} - * @since 3.0.0 - */ -module.exports = { - - UP: 12, - DOWN: 13, - LEFT: 14, - RIGHT: 15, - - SHARE: 8, - OPTIONS: 9, - PS: 16, - TOUCHBAR: 17, - - X: 0, - CIRCLE: 1, - SQUARE: 2, - TRIANGLE: 3, - - L1: 4, - R1: 5, - L2: 6, - R2: 7, - L3: 10, - R3: 11, - - LEFT_STICK_H: 0, - LEFT_STICK_V: 1, - RIGHT_STICK_H: 2, - RIGHT_STICK_V: 3 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * PlayStation DualShock 4 Gamepad Configuration. + * Sony PlayStation DualShock 4 (v2) wireless controller + * + * @name Phaser.Input.Gamepad.Configs.DUALSHOCK_4 + * @type {object} + * @since 3.0.0 + */ +module.exports = { + + UP: 12, + DOWN: 13, + LEFT: 14, + RIGHT: 15, + + SHARE: 8, + OPTIONS: 9, + PS: 16, + TOUCHBAR: 17, + + X: 0, + CIRCLE: 1, + SQUARE: 2, + TRIANGLE: 3, + + L1: 4, + R1: 5, + L2: 6, + R2: 7, + L3: 10, + R3: 11, + + LEFT_STICK_H: 0, + LEFT_STICK_V: 1, + RIGHT_STICK_H: 2, + RIGHT_STICK_V: 3 + +}; diff --git a/src/input/gamepad/configs/XBox360_Controller.js b/src/input/gamepad/configs/XBox360_Controller.js index 271e1c7be..a501d56c8 100644 --- a/src/input/gamepad/configs/XBox360_Controller.js +++ b/src/input/gamepad/configs/XBox360_Controller.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * XBox 360 Gamepad Configuration. - * - * @name Phaser.Input.Gamepad.Configs.XBOX_360 - * @type {object} - * @since 3.0.0 - */ -module.exports = { - - UP: 12, - DOWN: 13, - LEFT: 14, - RIGHT: 15, - - MENU: 16, - - A: 0, - B: 1, - X: 2, - Y: 3, - - LB: 4, - RB: 5, - - LT: 6, - RT: 7, - - BACK: 8, - START: 9, - - LS: 10, - RS: 11, - - LEFT_STICK_H: 0, - LEFT_STICK_V: 1, - RIGHT_STICK_H: 2, - RIGHT_STICK_V: 3 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * XBox 360 Gamepad Configuration. + * + * @name Phaser.Input.Gamepad.Configs.XBOX_360 + * @type {object} + * @since 3.0.0 + */ +module.exports = { + + UP: 12, + DOWN: 13, + LEFT: 14, + RIGHT: 15, + + MENU: 16, + + A: 0, + B: 1, + X: 2, + Y: 3, + + LB: 4, + RB: 5, + + LT: 6, + RT: 7, + + BACK: 8, + START: 9, + + LS: 10, + RS: 11, + + LEFT_STICK_H: 0, + LEFT_STICK_V: 1, + RIGHT_STICK_H: 2, + RIGHT_STICK_V: 3 + +}; diff --git a/src/input/gamepad/configs/index.js b/src/input/gamepad/configs/index.js index 4f5e763aa..fa5d46a1d 100644 --- a/src/input/gamepad/configs/index.js +++ b/src/input/gamepad/configs/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Gamepad.Configs - */ - -module.exports = { - - DUALSHOCK_4: require('./Sony_PlayStation_DualShock_4'), - SNES_USB: require('./SNES_USB_Controller'), - XBOX_360: require('./XBox360_Controller') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Gamepad.Configs + */ + +module.exports = { + + DUALSHOCK_4: require('./Sony_PlayStation_DualShock_4'), + SNES_USB: require('./SNES_USB_Controller'), + XBOX_360: require('./XBox360_Controller') + +}; diff --git a/src/input/gamepad/events/BUTTON_DOWN_EVENT.js b/src/input/gamepad/events/BUTTON_DOWN_EVENT.js index 64a9a543e..01993c398 100644 --- a/src/input/gamepad/events/BUTTON_DOWN_EVENT.js +++ b/src/input/gamepad/events/BUTTON_DOWN_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Gamepad Button Down Event. - * - * This event is dispatched by the Gamepad Plugin when a button has been pressed on any active Gamepad. - * - * Listen to this event from within a Scene using: `this.input.gamepad.on('down', listener)`. - * - * You can also listen for a DOWN event from a Gamepad instance. See the [GAMEPAD_BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_DOWN} event for details. - * - * @event Phaser.Input.Gamepad.Events#BUTTON_DOWN - * @since 3.10.0 - * - * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad on which the button was pressed. - * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was pressed. - * @param {number} value - The value of the button at the time it was pressed. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. - */ -module.exports = 'down'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Down Event. + * + * This event is dispatched by the Gamepad Plugin when a button has been pressed on any active Gamepad. + * + * Listen to this event from within a Scene using: `this.input.gamepad.on('down', listener)`. + * + * You can also listen for a DOWN event from a Gamepad instance. See the [GAMEPAD_BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_DOWN} event for details. + * + * @event Phaser.Input.Gamepad.Events#BUTTON_DOWN + * @since 3.10.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad on which the button was pressed. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was pressed. + * @param {number} value - The value of the button at the time it was pressed. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + */ +module.exports = 'down'; diff --git a/src/input/gamepad/events/BUTTON_UP_EVENT.js b/src/input/gamepad/events/BUTTON_UP_EVENT.js index 7993a40f0..5e52d0375 100644 --- a/src/input/gamepad/events/BUTTON_UP_EVENT.js +++ b/src/input/gamepad/events/BUTTON_UP_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Gamepad Button Up Event. - * - * This event is dispatched by the Gamepad Plugin when a button has been released on any active Gamepad. - * - * Listen to this event from within a Scene using: `this.input.gamepad.on('up', listener)`. - * - * You can also listen for an UP event from a Gamepad instance. See the [GAMEPAD_BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_UP} event for details. - * - * @event Phaser.Input.Gamepad.Events#BUTTON_UP - * @since 3.10.0 - * - * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad on which the button was released. - * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was released. - * @param {number} value - The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. - */ -module.exports = 'up'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Up Event. + * + * This event is dispatched by the Gamepad Plugin when a button has been released on any active Gamepad. + * + * Listen to this event from within a Scene using: `this.input.gamepad.on('up', listener)`. + * + * You can also listen for an UP event from a Gamepad instance. See the [GAMEPAD_BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_UP} event for details. + * + * @event Phaser.Input.Gamepad.Events#BUTTON_UP + * @since 3.10.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad on which the button was released. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was released. + * @param {number} value - The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + */ +module.exports = 'up'; diff --git a/src/input/gamepad/events/CONNECTED_EVENT.js b/src/input/gamepad/events/CONNECTED_EVENT.js index c39ba4a15..b82be8fec 100644 --- a/src/input/gamepad/events/CONNECTED_EVENT.js +++ b/src/input/gamepad/events/CONNECTED_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Gamepad Connected Event. - * - * This event is dispatched by the Gamepad Plugin when a Gamepad has been connected. - * - * Listen to this event from within a Scene using: `this.input.gamepad.once('connected', listener)`. - * - * 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. - * - * @event Phaser.Input.Gamepad.Events#CONNECTED - * @since 3.0.0 - * - * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad which was connected. - * @param {Event} event - The native DOM Event that triggered the connection. - */ -module.exports = 'connected'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Connected Event. + * + * This event is dispatched by the Gamepad Plugin when a Gamepad has been connected. + * + * Listen to this event from within a Scene using: `this.input.gamepad.once('connected', listener)`. + * + * 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. + * + * @event Phaser.Input.Gamepad.Events#CONNECTED + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad which was connected. + * @param {Event} event - The native DOM Event that triggered the connection. + */ +module.exports = 'connected'; diff --git a/src/input/gamepad/events/DISCONNECTED_EVENT.js b/src/input/gamepad/events/DISCONNECTED_EVENT.js index 7b67d621c..4d845c57d 100644 --- a/src/input/gamepad/events/DISCONNECTED_EVENT.js +++ b/src/input/gamepad/events/DISCONNECTED_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Gamepad Disconnected Event. - * - * This event is dispatched by the Gamepad Plugin when a Gamepad has been disconnected. - * - * Listen to this event from within a Scene using: `this.input.gamepad.once('disconnected', listener)`. - * - * @event Phaser.Input.Gamepad.Events#DISCONNECTED - * @since 3.0.0 - * - * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad which was disconnected. - * @param {Event} event - The native DOM Event that triggered the disconnection. - */ -module.exports = 'disconnected'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Disconnected Event. + * + * This event is dispatched by the Gamepad Plugin when a Gamepad has been disconnected. + * + * Listen to this event from within a Scene using: `this.input.gamepad.once('disconnected', listener)`. + * + * @event Phaser.Input.Gamepad.Events#DISCONNECTED + * @since 3.0.0 + * + * @param {Phaser.Input.Gamepad} pad - A reference to the Gamepad which was disconnected. + * @param {Event} event - The native DOM Event that triggered the disconnection. + */ +module.exports = 'disconnected'; diff --git a/src/input/gamepad/events/GAMEPAD_BUTTON_DOWN_EVENT.js b/src/input/gamepad/events/GAMEPAD_BUTTON_DOWN_EVENT.js index 47336c46d..4c28b65b1 100644 --- a/src/input/gamepad/events/GAMEPAD_BUTTON_DOWN_EVENT.js +++ b/src/input/gamepad/events/GAMEPAD_BUTTON_DOWN_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Gamepad Button Down Event. - * - * This event is dispatched by a Gamepad instance when a button has been pressed on it. - * - * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: - * `this.input.gamepad.pad1.on('down', listener)`. - * - * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. - * - * You can also listen for a DOWN event from the Gamepad Plugin. See the [BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_DOWN} event for details. - * - * @event Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_DOWN - * @since 3.10.0 - * - * @param {integer} index - The index of the button that was pressed. - * @param {number} value - The value of the button at the time it was pressed. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. - * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was pressed. - */ -module.exports = 'down'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Down Event. + * + * This event is dispatched by a Gamepad instance when a button has been pressed on it. + * + * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: + * `this.input.gamepad.pad1.on('down', listener)`. + * + * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. + * + * You can also listen for a DOWN event from the Gamepad Plugin. See the [BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_DOWN} event for details. + * + * @event Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_DOWN + * @since 3.10.0 + * + * @param {integer} index - The index of the button that was pressed. + * @param {number} value - The value of the button at the time it was pressed. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was pressed. + */ +module.exports = 'down'; diff --git a/src/input/gamepad/events/GAMEPAD_BUTTON_UP_EVENT.js b/src/input/gamepad/events/GAMEPAD_BUTTON_UP_EVENT.js index 5db6a16bb..a5c65797a 100644 --- a/src/input/gamepad/events/GAMEPAD_BUTTON_UP_EVENT.js +++ b/src/input/gamepad/events/GAMEPAD_BUTTON_UP_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Gamepad Button Up Event. - * - * This event is dispatched by a Gamepad instance when a button has been released on it. - * - * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: - * `this.input.gamepad.pad1.on('up', listener)`. - * - * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. - * - * You can also listen for an UP event from the Gamepad Plugin. See the [BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_UP} event for details. - * - * @event Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_UP - * @since 3.10.0 - * - * @param {integer} index - The index of the button that was released. - * @param {number} value - The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. - * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was released. - */ -module.exports = 'up'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Gamepad Button Up Event. + * + * This event is dispatched by a Gamepad instance when a button has been released on it. + * + * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: + * `this.input.gamepad.pad1.on('up', listener)`. + * + * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. + * + * You can also listen for an UP event from the Gamepad Plugin. See the [BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_UP} event for details. + * + * @event Phaser.Input.Gamepad.Events#GAMEPAD_BUTTON_UP + * @since 3.10.0 + * + * @param {integer} index - The index of the button that was released. + * @param {number} value - The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons. + * @param {Phaser.Input.Gamepad.Button} button - A reference to the Button which was released. + */ +module.exports = 'up'; diff --git a/src/input/gamepad/events/index.js b/src/input/gamepad/events/index.js index ba8fdbf09..1c097c517 100644 --- a/src/input/gamepad/events/index.js +++ b/src/input/gamepad/events/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Gamepad.Events - */ - -module.exports = { - - BUTTON_DOWN: require('./BUTTON_DOWN_EVENT'), - BUTTON_UP: require('./BUTTON_UP_EVENT'), - CONNECTED: require('./CONNECTED_EVENT'), - DISCONNECTED: require('./DISCONNECTED_EVENT'), - GAMEPAD_BUTTON_DOWN: require('./GAMEPAD_BUTTON_DOWN_EVENT'), - GAMEPAD_BUTTON_UP: require('./GAMEPAD_BUTTON_UP_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Gamepad.Events + */ + +module.exports = { + + BUTTON_DOWN: require('./BUTTON_DOWN_EVENT'), + BUTTON_UP: require('./BUTTON_UP_EVENT'), + CONNECTED: require('./CONNECTED_EVENT'), + DISCONNECTED: require('./DISCONNECTED_EVENT'), + GAMEPAD_BUTTON_DOWN: require('./GAMEPAD_BUTTON_DOWN_EVENT'), + GAMEPAD_BUTTON_UP: require('./GAMEPAD_BUTTON_UP_EVENT') + +}; diff --git a/src/input/gamepad/index.js b/src/input/gamepad/index.js index c9f0b2b1a..8b0b021ff 100644 --- a/src/input/gamepad/index.js +++ b/src/input/gamepad/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Gamepad - */ - -module.exports = { - - Axis: require('./Axis'), - Button: require('./Button'), - Events: require('./events'), - Gamepad: require('./Gamepad'), - GamepadPlugin: require('./GamepadPlugin'), - - Configs: require('./configs/') -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Gamepad + */ + +module.exports = { + + Axis: require('./Axis'), + Button: require('./Button'), + Events: require('./events'), + Gamepad: require('./Gamepad'), + GamepadPlugin: require('./GamepadPlugin'), + + Configs: require('./configs/') +}; diff --git a/src/input/gamepad/typedefs/index.js b/src/input/gamepad/typedefs/index.js index d95114b58..f375d209d 100644 --- a/src/input/gamepad/typedefs/index.js +++ b/src/input/gamepad/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Input.Gamepad - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Input.Gamepad + */ diff --git a/src/input/index.js b/src/input/index.js index 144fa8f86..2052972f0 100644 --- a/src/input/index.js +++ b/src/input/index.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../utils/object/Extend'); - -/** - * @namespace Phaser.Input - */ - -var Input = { - - CreateInteractiveObject: require('./CreateInteractiveObject'), - Events: require('./events'), - Gamepad: require('./gamepad'), - InputManager: require('./InputManager'), - InputPlugin: require('./InputPlugin'), - InputPluginCache: require('./InputPluginCache'), - Keyboard: require('./keyboard'), - Mouse: require('./mouse'), - Pointer: require('./Pointer'), - Touch: require('./touch') - -}; - -// Merge in the consts -Input = Extend(false, Input, CONST); - -module.exports = Input; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../utils/object/Extend'); + +/** + * @namespace Phaser.Input + */ + +var Input = { + + CreateInteractiveObject: require('./CreateInteractiveObject'), + Events: require('./events'), + Gamepad: require('./gamepad'), + InputManager: require('./InputManager'), + InputPlugin: require('./InputPlugin'), + InputPluginCache: require('./InputPluginCache'), + Keyboard: require('./keyboard'), + Mouse: require('./mouse'), + Pointer: require('./Pointer'), + Touch: require('./touch') + +}; + +// Merge in the consts +Input = Extend(false, Input, CONST); + +module.exports = Input; diff --git a/src/input/keyboard/KeyboardManager.js b/src/input/keyboard/KeyboardManager.js index 063743e5f..530545f1c 100644 --- a/src/input/keyboard/KeyboardManager.js +++ b/src/input/keyboard/KeyboardManager.js @@ -1,444 +1,444 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArrayRemove = require('../../utils/array/Remove'); -var Class = require('../../utils/Class'); -var GameEvents = require('../../core/events'); -var InputEvents = require('../events'); -var KeyCodes = require('../../input/keyboard/keys/KeyCodes'); -var NOOP = require('../../utils/Class'); - -/** - * @classdesc - * The Keyboard Manager is a helper class that belongs to the global Input Manager. - * - * Its role is to listen for native DOM Keyboard Events and then store them for further processing by the Keyboard Plugin. - * - * You do not need to create this class directly, the Input Manager will create an instance of it automatically if keyboard - * input has been enabled in the Game Config. - * - * @class KeyboardManager - * @memberof Phaser.Input.Keyboard - * @constructor - * @since 3.16.0 - * - * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. - */ -var KeyboardManager = new Class({ - - initialize: - - function KeyboardManager (inputManager) - { - /** - * A reference to the Input Manager. - * - * @name Phaser.Input.Keyboard.KeyboardManager#manager - * @type {Phaser.Input.InputManager} - * @since 3.16.0 - */ - this.manager = inputManager; - - /** - * An internal event queue. - * - * @name Phaser.Input.Keyboard.KeyboardManager#queue - * @type {KeyboardEvent[]} - * @private - * @since 3.16.0 - */ - this.queue = []; - - /** - * A flag that controls if the non-modified keys, matching those stored in the `captures` array, - * have `preventDefault` called on them or not. - * - * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are - * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). - * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. - * However, if the user presses just the r key on its own, it will have its event prevented. - * - * If you wish to stop capturing the keys, for example switching out to a DOM based element, then - * you can toggle this property at run-time. - * - * @name Phaser.Input.Keyboard.KeyboardManager#preventDefault - * @type {boolean} - * @since 3.16.0 - */ - this.preventDefault = true; - - /** - * An array of Key Code values that will automatically have `preventDefault` called on them, - * as long as the `KeyboardManager.preventDefault` boolean is set to `true`. - * - * By default the array is empty. - * - * The key must be non-modified when pressed in order to be captured. - * - * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are - * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). - * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. - * However, if the user presses just the r key on its own, it will have its event prevented. - * - * If you wish to stop capturing the keys, for example switching out to a DOM based element, then - * you can toggle the `KeyboardManager.preventDefault` boolean at run-time. - * - * If you need more specific control, you can create Key objects and set the flag on each of those instead. - * - * This array can be populated via the Game Config by setting the `input.keyboard.capture` array, or you - * can call the `addCapture` method. See also `removeCapture` and `clearCaptures`. - * - * @name Phaser.Input.Keyboard.KeyboardManager#captures - * @type {integer[]} - * @since 3.16.0 - */ - this.captures = []; - - /** - * A boolean that controls if the Keyboard Manager is enabled or not. - * Can be toggled on the fly. - * - * @name Phaser.Input.Keyboard.KeyboardManager#enabled - * @type {boolean} - * @default false - * @since 3.16.0 - */ - this.enabled = false; - - /** - * The Keyboard Event target, as defined in the Game Config. - * Typically the window in which the game is rendering, but can be any interactive DOM element. - * - * @name Phaser.Input.Keyboard.KeyboardManager#target - * @type {any} - * @since 3.16.0 - */ - this.target; - - /** - * The Key Down Event handler. - * This function is sent the native DOM KeyEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Keyboard.KeyboardManager#onKeyDown - * @type {function} - * @since 3.16.00 - */ - this.onKeyDown = NOOP; - - /** - * The Key Up Event handler. - * This function is sent the native DOM KeyEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Keyboard.KeyboardManager#onKeyUp - * @type {function} - * @since 3.16.00 - */ - this.onKeyUp = NOOP; - - inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); - }, - - /** - * The Keyboard Manager boot process. - * - * @method Phaser.Input.Keyboard.KeyboardManager#boot - * @private - * @since 3.16.0 - */ - boot: function () - { - var config = this.manager.config; - - this.enabled = config.inputKeyboard; - this.target = config.inputKeyboardEventTarget; - - this.addCapture(config.inputKeyboardCapture); - - if (!this.target && window) - { - this.target = window; - } - - if (this.enabled && this.target) - { - this.startListeners(); - } - - this.manager.game.events.on(GameEvents.POST_STEP, this.postUpdate, this); - }, - - /** - * Starts the Keyboard Event listeners running. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Keyboard.KeyboardManager#startListeners - * @since 3.16.0 - */ - startListeners: function () - { - var _this = this; - - this.onKeyDown = function (event) - { - if (event.defaultPrevented || !_this.enabled || !_this.manager) - { - // Do nothing if event already handled - return; - } - - _this.queue.push(event); - - if (!_this.manager.useQueue) - { - _this.manager.events.emit(InputEvents.MANAGER_PROCESS); - } - - var modified = (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey); - - if (_this.preventDefault && !modified && _this.captures.indexOf(event.keyCode) > -1) - { - event.preventDefault(); - } - }; - - this.onKeyUp = function (event) - { - if (event.defaultPrevented || !_this.enabled || !_this.manager) - { - // Do nothing if event already handled - return; - } - - _this.queue.push(event); - - if (!_this.manager.useQueue) - { - _this.manager.events.emit(InputEvents.MANAGER_PROCESS); - } - - var modified = (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey); - - if (_this.preventDefault && !modified && _this.captures.indexOf(event.keyCode) > -1) - { - event.preventDefault(); - } - }; - - var target = this.target; - - if (target) - { - target.addEventListener('keydown', this.onKeyDown, false); - target.addEventListener('keyup', this.onKeyUp, false); - - this.enabled = true; - } - }, - - /** - * Stops the Key Event listeners. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Keyboard.KeyboardManager#stopListeners - * @since 3.16.0 - */ - stopListeners: function () - { - var target = this.target; - - target.removeEventListener('keydown', this.onKeyDown, false); - target.removeEventListener('keyup', this.onKeyUp, false); - - this.enabled = false; - }, - - /** - * Clears the event queue. - * Called automatically by the Input Manager. - * - * @method Phaser.Input.Keyboard.KeyboardManager#postUpdate - * @private - * @since 3.16.0 - */ - postUpdate: function () - { - this.queue = []; - }, - - /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * - * This `addCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser - * and cause the default browser behavior. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent - * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. - * - * You can pass in a single key code value, or an array of key codes, or a string: - * - * ```javascript - * this.input.keyboard.addCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.addCapture([ 62, 63, 64 ]); - * ``` - * - * Or a string: - * - * ```javascript - * this.input.keyboard.addCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * - * If there are active captures after calling this method, the `preventDefault` property is set to `true`. - * - * @method Phaser.Input.Keyboard.KeyboardManager#addCapture - * @since 3.16.0 - * - * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to enable capture for, preventing them reaching the browser. - */ - addCapture: function (keycode) - { - if (typeof keycode === 'string') - { - keycode = keycode.split(','); - } - - if (!Array.isArray(keycode)) - { - keycode = [ keycode ]; - } - - var captures = this.captures; - - for (var i = 0; i < keycode.length; i++) - { - var code = keycode[i]; - - if (typeof code === 'string') - { - code = KeyCodes[code.trim().toUpperCase()]; - } - - if (captures.indexOf(code) === -1) - { - captures.push(code); - } - } - - this.preventDefault = captures.length > 0; - }, - - /** - * Removes an existing key capture. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove - * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. - * - * You can pass in a single key code value, or an array of key codes, or a string: - * - * ```javascript - * this.input.keyboard.removeCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.removeCapture([ 62, 63, 64 ]); - * ``` - * - * Or a string: - * - * ```javascript - * this.input.keyboard.removeCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * - * If there are no captures left after calling this method, the `preventDefault` property is set to `false`. - * - * @method Phaser.Input.Keyboard.KeyboardManager#removeCapture - * @since 3.16.0 - * - * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to disable capture for, allowing them reaching the browser again. - */ - removeCapture: function (keycode) - { - if (typeof keycode === 'string') - { - keycode = keycode.split(','); - } - - if (!Array.isArray(keycode)) - { - keycode = [ keycode ]; - } - - var captures = this.captures; - - for (var i = 0; i < keycode.length; i++) - { - var code = keycode[i]; - - if (typeof code === 'string') - { - code = KeyCodes[code.toUpperCase()]; - } - - ArrayRemove(captures, code); - } - - this.preventDefault = captures.length > 0; - }, - - /** - * Removes all keyboard captures and sets the `preventDefault` property to `false`. - * - * @method Phaser.Input.Keyboard.KeyboardManager#clearCaptures - * @since 3.16.0 - */ - clearCaptures: function () - { - this.captures = []; - - this.preventDefault = false; - }, - - /** - * Destroys this Keyboard Manager instance. - * - * @method Phaser.Input.Keyboard.KeyboardManager#destroy - * @since 3.16.0 - */ - destroy: function () - { - this.stopListeners(); - - this.clearCaptures(); - - this.queue = []; - - this.manager.game.events.off(GameEvents.POST_RENDER, this.postUpdate, this); - - this.target = null; - this.enabled = false; - this.manager = null; - } - -}); - -module.exports = KeyboardManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayRemove = require('../../utils/array/Remove'); +var Class = require('../../utils/Class'); +var GameEvents = require('../../core/events'); +var InputEvents = require('../events'); +var KeyCodes = require('../../input/keyboard/keys/KeyCodes'); +var NOOP = require('../../utils/Class'); + +/** + * @classdesc + * The Keyboard Manager is a helper class that belongs to the global Input Manager. + * + * Its role is to listen for native DOM Keyboard Events and then store them for further processing by the Keyboard Plugin. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically if keyboard + * input has been enabled in the Game Config. + * + * @class KeyboardManager + * @memberof Phaser.Input.Keyboard + * @constructor + * @since 3.16.0 + * + * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. + */ +var KeyboardManager = new Class({ + + initialize: + + function KeyboardManager (inputManager) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Keyboard.KeyboardManager#manager + * @type {Phaser.Input.InputManager} + * @since 3.16.0 + */ + this.manager = inputManager; + + /** + * An internal event queue. + * + * @name Phaser.Input.Keyboard.KeyboardManager#queue + * @type {KeyboardEvent[]} + * @private + * @since 3.16.0 + */ + this.queue = []; + + /** + * A flag that controls if the non-modified keys, matching those stored in the `captures` array, + * have `preventDefault` called on them or not. + * + * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are + * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). + * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. + * However, if the user presses just the r key on its own, it will have its event prevented. + * + * If you wish to stop capturing the keys, for example switching out to a DOM based element, then + * you can toggle this property at run-time. + * + * @name Phaser.Input.Keyboard.KeyboardManager#preventDefault + * @type {boolean} + * @since 3.16.0 + */ + this.preventDefault = true; + + /** + * An array of Key Code values that will automatically have `preventDefault` called on them, + * as long as the `KeyboardManager.preventDefault` boolean is set to `true`. + * + * By default the array is empty. + * + * The key must be non-modified when pressed in order to be captured. + * + * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are + * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). + * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. + * However, if the user presses just the r key on its own, it will have its event prevented. + * + * If you wish to stop capturing the keys, for example switching out to a DOM based element, then + * you can toggle the `KeyboardManager.preventDefault` boolean at run-time. + * + * If you need more specific control, you can create Key objects and set the flag on each of those instead. + * + * This array can be populated via the Game Config by setting the `input.keyboard.capture` array, or you + * can call the `addCapture` method. See also `removeCapture` and `clearCaptures`. + * + * @name Phaser.Input.Keyboard.KeyboardManager#captures + * @type {integer[]} + * @since 3.16.0 + */ + this.captures = []; + + /** + * A boolean that controls if the Keyboard Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Keyboard.KeyboardManager#enabled + * @type {boolean} + * @default false + * @since 3.16.0 + */ + this.enabled = false; + + /** + * The Keyboard Event target, as defined in the Game Config. + * Typically the window in which the game is rendering, but can be any interactive DOM element. + * + * @name Phaser.Input.Keyboard.KeyboardManager#target + * @type {any} + * @since 3.16.0 + */ + this.target; + + /** + * The Key Down Event handler. + * This function is sent the native DOM KeyEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Keyboard.KeyboardManager#onKeyDown + * @type {function} + * @since 3.16.00 + */ + this.onKeyDown = NOOP; + + /** + * The Key Up Event handler. + * This function is sent the native DOM KeyEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Keyboard.KeyboardManager#onKeyUp + * @type {function} + * @since 3.16.00 + */ + this.onKeyUp = NOOP; + + inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); + }, + + /** + * The Keyboard Manager boot process. + * + * @method Phaser.Input.Keyboard.KeyboardManager#boot + * @private + * @since 3.16.0 + */ + boot: function () + { + var config = this.manager.config; + + this.enabled = config.inputKeyboard; + this.target = config.inputKeyboardEventTarget; + + this.addCapture(config.inputKeyboardCapture); + + if (!this.target && window) + { + this.target = window; + } + + if (this.enabled && this.target) + { + this.startListeners(); + } + + this.manager.game.events.on(GameEvents.POST_STEP, this.postUpdate, this); + }, + + /** + * Starts the Keyboard Event listeners running. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Keyboard.KeyboardManager#startListeners + * @since 3.16.0 + */ + startListeners: function () + { + var _this = this; + + this.onKeyDown = function (event) + { + if (event.defaultPrevented || !_this.enabled || !_this.manager) + { + // Do nothing if event already handled + return; + } + + _this.queue.push(event); + + if (!_this.manager.useQueue) + { + _this.manager.events.emit(InputEvents.MANAGER_PROCESS); + } + + var modified = (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey); + + if (_this.preventDefault && !modified && _this.captures.indexOf(event.keyCode) > -1) + { + event.preventDefault(); + } + }; + + this.onKeyUp = function (event) + { + if (event.defaultPrevented || !_this.enabled || !_this.manager) + { + // Do nothing if event already handled + return; + } + + _this.queue.push(event); + + if (!_this.manager.useQueue) + { + _this.manager.events.emit(InputEvents.MANAGER_PROCESS); + } + + var modified = (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey); + + if (_this.preventDefault && !modified && _this.captures.indexOf(event.keyCode) > -1) + { + event.preventDefault(); + } + }; + + var target = this.target; + + if (target) + { + target.addEventListener('keydown', this.onKeyDown, false); + target.addEventListener('keyup', this.onKeyUp, false); + + this.enabled = true; + } + }, + + /** + * Stops the Key Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Keyboard.KeyboardManager#stopListeners + * @since 3.16.0 + */ + stopListeners: function () + { + var target = this.target; + + target.removeEventListener('keydown', this.onKeyDown, false); + target.removeEventListener('keyup', this.onKeyUp, false); + + this.enabled = false; + }, + + /** + * Clears the event queue. + * Called automatically by the Input Manager. + * + * @method Phaser.Input.Keyboard.KeyboardManager#postUpdate + * @private + * @since 3.16.0 + */ + postUpdate: function () + { + this.queue = []; + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * This `addCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent + * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. + * + * You can pass in a single key code value, or an array of key codes, or a string: + * + * ```javascript + * this.input.keyboard.addCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.addCapture([ 62, 63, 64 ]); + * ``` + * + * Or a string: + * + * ```javascript + * this.input.keyboard.addCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * If there are active captures after calling this method, the `preventDefault` property is set to `true`. + * + * @method Phaser.Input.Keyboard.KeyboardManager#addCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to enable capture for, preventing them reaching the browser. + */ + addCapture: function (keycode) + { + if (typeof keycode === 'string') + { + keycode = keycode.split(','); + } + + if (!Array.isArray(keycode)) + { + keycode = [ keycode ]; + } + + var captures = this.captures; + + for (var i = 0; i < keycode.length; i++) + { + var code = keycode[i]; + + if (typeof code === 'string') + { + code = KeyCodes[code.trim().toUpperCase()]; + } + + if (captures.indexOf(code) === -1) + { + captures.push(code); + } + } + + this.preventDefault = captures.length > 0; + }, + + /** + * Removes an existing key capture. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove + * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. + * + * You can pass in a single key code value, or an array of key codes, or a string: + * + * ```javascript + * this.input.keyboard.removeCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.removeCapture([ 62, 63, 64 ]); + * ``` + * + * Or a string: + * + * ```javascript + * this.input.keyboard.removeCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * If there are no captures left after calling this method, the `preventDefault` property is set to `false`. + * + * @method Phaser.Input.Keyboard.KeyboardManager#removeCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to disable capture for, allowing them reaching the browser again. + */ + removeCapture: function (keycode) + { + if (typeof keycode === 'string') + { + keycode = keycode.split(','); + } + + if (!Array.isArray(keycode)) + { + keycode = [ keycode ]; + } + + var captures = this.captures; + + for (var i = 0; i < keycode.length; i++) + { + var code = keycode[i]; + + if (typeof code === 'string') + { + code = KeyCodes[code.toUpperCase()]; + } + + ArrayRemove(captures, code); + } + + this.preventDefault = captures.length > 0; + }, + + /** + * Removes all keyboard captures and sets the `preventDefault` property to `false`. + * + * @method Phaser.Input.Keyboard.KeyboardManager#clearCaptures + * @since 3.16.0 + */ + clearCaptures: function () + { + this.captures = []; + + this.preventDefault = false; + }, + + /** + * Destroys this Keyboard Manager instance. + * + * @method Phaser.Input.Keyboard.KeyboardManager#destroy + * @since 3.16.0 + */ + destroy: function () + { + this.stopListeners(); + + this.clearCaptures(); + + this.queue = []; + + this.manager.game.events.off(GameEvents.POST_RENDER, this.postUpdate, this); + + this.target = null; + this.enabled = false; + this.manager = null; + } + +}); + +module.exports = KeyboardManager; diff --git a/src/input/keyboard/KeyboardPlugin.js b/src/input/keyboard/KeyboardPlugin.js index ab5bc5d91..d84d005f4 100644 --- a/src/input/keyboard/KeyboardPlugin.js +++ b/src/input/keyboard/KeyboardPlugin.js @@ -1,880 +1,880 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GameEvents = require('../../core/events'); -var GetValue = require('../../utils/object/GetValue'); -var InputEvents = require('../events'); -var InputPluginCache = require('../InputPluginCache'); -var Key = require('./keys/Key'); -var KeyCodes = require('./keys/KeyCodes'); -var KeyCombo = require('./combo/KeyCombo'); -var KeyMap = require('./keys/KeyMap'); -var SnapFloor = require('../../math/snap/SnapFloor'); - -/** - * @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. - * - * 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. - */ -var KeyboardPlugin = new Class({ - - Extends: EventEmitter, - - initialize: - - function KeyboardPlugin (sceneInputPlugin) - { - EventEmitter.call(this); - - /** - * A reference to the core game, so we can listen for visibility events. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#game - * @type {Phaser.Game} - * @since 3.16.0 - */ - this.game = sceneInputPlugin.systems.game; - - /** - * A reference to the Scene that this Input Plugin is responsible for. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#scene - * @type {Phaser.Scene} - * @since 3.10.0 - */ - this.scene = sceneInputPlugin.scene; - - /** - * A reference to the Scene Systems Settings. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#settings - * @type {Phaser.Types.Scenes.SettingsObject} - * @since 3.10.0 - */ - this.settings = this.scene.sys.settings; - - /** - * A reference to the Scene Input Plugin that created this Keyboard Plugin. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#sceneInputPlugin - * @type {Phaser.Input.InputPlugin} - * @since 3.10.0 - */ - this.sceneInputPlugin = sceneInputPlugin; - - /** - * A reference to the global Keyboard Manager. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#manager - * @type {Phaser.Input.InputPlugin} - * @since 3.16.0 - */ - this.manager = sceneInputPlugin.manager.keyboard; - - /** - * A boolean that controls if this Keyboard Plugin is enabled or not. - * Can be toggled on the fly. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#enabled - * @type {boolean} - * @default true - * @since 3.10.0 - */ - this.enabled = true; - - /** - * An array of Key objects to process. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#keys - * @type {Phaser.Input.Keyboard.Key[]} - * @since 3.10.0 - */ - this.keys = []; - - /** - * An array of KeyCombo objects to process. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#combos - * @type {Phaser.Input.Keyboard.KeyCombo[]} - * @since 3.10.0 - */ - this.combos = []; - - sceneInputPlugin.pluginEvents.once(InputEvents.BOOT, this.boot, this); - sceneInputPlugin.pluginEvents.on(InputEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#boot - * @private - * @since 3.10.0 - */ - boot: function () - { - var settings = this.settings.input; - - this.enabled = GetValue(settings, 'keyboard', true); - - var captures = GetValue(settings, 'keyboard.capture', null); - - if (captures) - { - this.addCaptures(captures); - } - - this.sceneInputPlugin.pluginEvents.once(InputEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#start - * @private - * @since 3.10.0 - */ - start: function () - { - if (this.sceneInputPlugin.manager.useQueue) - { - this.sceneInputPlugin.pluginEvents.on(InputEvents.UPDATE, this.update, this); - } - else - { - this.sceneInputPlugin.manager.events.on(InputEvents.MANAGER_PROCESS, this.update, this); - } - - this.sceneInputPlugin.pluginEvents.once(InputEvents.SHUTDOWN, this.shutdown, this); - - this.game.events.on(GameEvents.BLUR, this.resetKeys, this); - }, - - /** - * Checks to see if both this plugin and the Scene to which it belongs is active. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#isActive - * @since 3.10.0 - * - * @return {boolean} `true` if the plugin and the Scene it belongs to is active. - */ - isActive: function () - { - return (this.enabled && this.scene.sys.isActive()); - }, - - /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * - * This `addCapture` method enables consuming keyboard events for specific keys, so they don't bubble up the browser - * and cause the default behaviors. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent - * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. - * - * You can pass a single key code value: - * - * ```javascript - * this.input.keyboard.addCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.addCapture([ 62, 63, 64 ]); - * ``` - * - * Or, a comma-delimited string: - * - * ```javascript - * this.input.keyboard.addCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#addCapture - * @since 3.16.0 - * - * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to enable event capture for. - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - addCapture: function (keycode) - { - this.manager.addCapture(keycode); - - return this; - }, - - /** - * Removes an existing key capture. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove - * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. - * - * You can pass a single key code value: - * - * ```javascript - * this.input.keyboard.removeCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.removeCapture([ 62, 63, 64 ]); - * ``` - * - * Or, a comma-delimited string: - * - * ```javascript - * this.input.keyboard.removeCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#removeCapture - * @since 3.16.0 - * - * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to disable event capture for. - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - removeCapture: function (keycode) - { - this.manager.removeCapture(keycode); - - return this; - }, - - /** - * Returns an array that contains all of the keyboard captures currently enabled. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#getCaptures - * @since 3.16.0 - * - * @return {integer[]} An array of all the currently capturing key codes. - */ - getCaptures: function () - { - return this.manager.captures; - }, - - /** - * Allows Phaser to prevent any key captures you may have defined from bubbling up the browser. - * You can use this to re-enable event capturing if you had paused it via `disableGlobalCapture`. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#enableGlobalCapture - * @since 3.16.0 - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - enableGlobalCapture: function () - { - this.manager.preventDefault = true; - - return this; - }, - - /** - * Disables Phaser from preventing any key captures you may have defined, without actually removing them. - * You can use this to temporarily disable event capturing if, for example, you swap to a DOM element. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#disableGlobalCapture - * @since 3.16.0 - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - disableGlobalCapture: function () - { - this.manager.preventDefault = false; - - return this; - }, - - /** - * Removes all keyboard captures. - * - * Note that this is a global change. It will clear all event captures across your game, not just for this specific Scene. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#clearCaptures - * @since 3.16.0 - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - clearCaptures: function () - { - this.manager.clearCaptures(); - - return this; - }, - - /** - * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right, and also Space Bar and shift. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#createCursorKeys - * @since 3.10.0 - * - * @return {Phaser.Types.Input.Keyboard.CursorKeys} An object containing the properties: `up`, `down`, `left`, `right`, `space` and `shift`. - */ - createCursorKeys: function () - { - return this.addKeys({ - up: KeyCodes.UP, - down: KeyCodes.DOWN, - left: KeyCodes.LEFT, - right: KeyCodes.RIGHT, - space: KeyCodes.SPACE, - shift: KeyCodes.SHIFT - }); - }, - - /** - * A practical way to create an object containing user selected hotkeys. - * - * For example: - * - * ```javascript - * this.input.keyboard.addKeys({ 'up': Phaser.Input.Keyboard.KeyCodes.W, 'down': Phaser.Input.Keyboard.KeyCodes.S }); - * ``` - * - * would return an object containing the properties (`up` and `down`) mapped to W and S {@link Phaser.Input.Keyboard.Key} objects. - * - * You can also pass in a comma-separated string: - * - * ```javascript - * this.input.keyboard.addKeys('W,S,A,D'); - * ``` - * - * Which will return an object with the properties W, S, A and D mapped to the relevant Key objects. - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#addKeys - * @since 3.10.0 - * - * @param {(object|string)} keys - An object containing Key Codes, or a comma-separated string. - * @param {boolean} [enableCapture=true] - Automatically call `preventDefault` on the native DOM browser event for the key codes being added. - * @param {boolean} [emitOnRepeat=false] - Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). - * - * @return {object} An object containing Key objects mapped to the input properties. - */ - addKeys: function (keys, enableCapture, emitOnRepeat) - { - if (enableCapture === undefined) { enableCapture = true; } - if (emitOnRepeat === undefined) { emitOnRepeat = false; } - - var output = {}; - - if (typeof keys === 'string') - { - keys = keys.split(','); - - for (var i = 0; i < keys.length; i++) - { - var currentKey = keys[i].trim(); - - if (currentKey) - { - output[currentKey] = this.addKey(currentKey, enableCapture, emitOnRepeat); - } - } - } - else - { - for (var key in keys) - { - output[key] = this.addKey(keys[key], enableCapture, emitOnRepeat); - } - } - - return output; - }, - - /** - * Adds a Key object to this Keyboard Plugin. - * - * The given argument can be either an existing Key object, a string, such as `A` or `SPACE`, or a key code value. - * - * If a Key object is given, and one already exists matching the same key code, the existing one is replaced with the new one. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#addKey - * @since 3.10.0 - * - * @param {(Phaser.Input.Keyboard.Key|string|integer)} key - Either a Key object, a string, such as `A` or `SPACE`, or a key code value. - * @param {boolean} [enableCapture=true] - Automatically call `preventDefault` on the native DOM browser event for the key codes being added. - * @param {boolean} [emitOnRepeat=false] - Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). - * - * @return {Phaser.Input.Keyboard.Key} The newly created Key object, or a reference to it if it already existed in the keys array. - */ - addKey: function (key, enableCapture, emitOnRepeat) - { - if (enableCapture === undefined) { enableCapture = true; } - if (emitOnRepeat === undefined) { emitOnRepeat = false; } - - var keys = this.keys; - - if (key instanceof Key) - { - var idx = keys.indexOf(key); - - if (idx > -1) - { - keys[idx] = key; - } - else - { - keys[key.keyCode] = key; - } - - if (enableCapture) - { - this.addCapture(key.keyCode); - } - - key.setEmitOnRepeat(emitOnRepeat); - - return key; - } - - if (typeof key === 'string') - { - key = KeyCodes[key.toUpperCase()]; - } - - if (!keys[key]) - { - keys[key] = new Key(this, key); - - if (enableCapture) - { - this.addCapture(key); - } - - keys[key].setEmitOnRepeat(emitOnRepeat); - } - - return keys[key]; - }, - - /** - * Removes a Key object from this Keyboard Plugin. - * - * The given argument can be either a Key object, a string, such as `A` or `SPACE`, or a key code value. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#removeKey - * @since 3.10.0 - * - * @param {(Phaser.Input.Keyboard.Key|string|integer)} key - Either a Key object, a string, such as `A` or `SPACE`, or a key code value. - * @param {boolean} [destroy=false] - Call `Key.destroy` on the removed Key object? - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - removeKey: function (key, destroy) - { - if (destroy === undefined) { destroy = false; } - - var keys = this.keys; - var ref; - - if (key instanceof Key) - { - var idx = keys.indexOf(key); - - if (idx > -1) - { - ref = this.keys[idx]; - - this.keys[idx] = undefined; - } - } - else if (typeof key === 'string') - { - key = KeyCodes[key.toUpperCase()]; - } - - if (keys[key]) - { - ref = keys[key]; - - keys[key] = undefined; - } - - if (ref) - { - ref.plugin = null; - - if (destroy) - { - ref.destroy(); - } - } - - return this; - }, - - /** - * Creates a new KeyCombo. - * - * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them - * it will emit a `keycombomatch` event from this Keyboard Plugin. - * - * The keys to be listened for can be defined as: - * - * A string (i.e. 'ATARI') - * An array of either integers (key codes) or strings, or a mixture of both - * An array of objects (such as Key objects) with a public 'keyCode' property - * - * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) - * you could pass the following array of key codes: - * - * ```javascript - * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); - * - * this.input.keyboard.on('keycombomatch', function (event) { - * console.log('Konami Code entered!'); - * }); - * ``` - * - * Or, to listen for the user entering the word PHASER: - * - * ```javascript - * this.input.keyboard.createCombo('PHASER'); - * ``` - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#createCombo - * @since 3.10.0 - * - * @param {(string|integer[]|object[])} keys - The keys that comprise this combo. - * @param {Phaser.Types.Input.Keyboard.KeyComboConfig} [config] - A Key Combo configuration object. - * - * @return {Phaser.Input.Keyboard.KeyCombo} The new KeyCombo object. - */ - createCombo: function (keys, config) - { - return new KeyCombo(this, keys, config); - }, - - /** - * Checks if the given Key object is currently being held down. - * - * The difference between this method and checking the `Key.isDown` property directly is that you can provide - * a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted - * it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it - * will only return `true` every 100ms. - * - * If the Keyboard Plugin has been disabled, this method will always return `false`. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#checkDown - * @since 3.11.0 - * - * @param {Phaser.Input.Keyboard.Key} key - A Key object. - * @param {number} [duration=0] - The duration which must have elapsed before this Key is considered as being down. - * - * @return {boolean} `true` if the Key is down within the duration specified, otherwise `false`. - */ - checkDown: function (key, duration) - { - if (this.enabled && key.isDown) - { - var t = SnapFloor(this.time - key.timeDown, duration); - - if (t > key._tick) - { - key._tick = t; - - return true; - } - } - - return false; - }, - - /** - * Internal update handler called by the Input Plugin, which is in turn invoked by the Game step. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#update - * @private - * @since 3.10.0 - */ - update: function () - { - var queue = this.manager.queue; - var len = queue.length; - - if (!this.isActive() || len === 0) - { - return; - } - - var keys = this.keys; - - // Process the event queue, dispatching all of the events that have stored up - for (var i = 0; i < len; i++) - { - var event = queue[i]; - var code = event.keyCode; - var key = keys[code]; - var repeat = false; - - // Override the default functions (it's too late for the browser to use them anyway, so we may as well) - if (event.cancelled === undefined) - { - // Event allowed to flow across all handlers in this Scene, and any other Scene in the Scene list - event.cancelled = 0; - - // Won't reach any more local (Scene level) handlers - event.stopImmediatePropagation = function () - { - event.cancelled = 1; - }; - - // Won't reach any more handlers in any Scene further down the Scene list - event.stopPropagation = function () - { - event.cancelled = -1; - }; - } - - if (event.cancelled === -1) - { - // This event has been stopped from broadcasting to any other Scene, so abort. - continue; - } - - if (event.type === 'keydown') - { - // Key specific callback first - if (key) - { - repeat = key.isDown; - - key.onDown(event); - } - - if (!event.cancelled && (!key || !repeat)) - { - if (KeyMap[code]) - { - this.emit(Events.KEY_DOWN + KeyMap[code], event); - - // Deprecated, kept in for compatibility with 3.15 - // To be removed by 3.20. - this.emit('keydown_' + KeyMap[code], event); - } - - if (!event.cancelled) - { - this.emit(Events.ANY_KEY_DOWN, event); - } - } - } - else - { - // Key specific callback first - if (key) - { - key.onUp(event); - } - - if (!event.cancelled) - { - if (KeyMap[code]) - { - this.emit(Events.KEY_UP + KeyMap[code], event); - - // Deprecated, kept in for compatibility with 3.15 - // To be removed by 3.20. - this.emit('keyup_' + KeyMap[code], event); - } - - if (!event.cancelled) - { - this.emit(Events.ANY_KEY_UP, event); - } - } - } - - // Reset the cancel state for other Scenes to use - if (event.cancelled === 1) - { - event.cancelled = 0; - } - } - }, - - /** - * Resets all Key objects created by _this_ Keyboard Plugin back to their default un-pressed states. - * This can only reset keys created via the `addKey`, `addKeys` or `createCursorKeys` methods. - * If you have created a Key object directly you'll need to reset it yourself. - * - * This method is called automatically when the Keyboard Plugin shuts down, but can be - * invoked directly at any time you require. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#resetKeys - * @since 3.15.0 - * - * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. - */ - resetKeys: function () - { - var keys = this.keys; - - for (var i = 0; i < keys.length; i++) - { - // Because it's a sparsely populated array - if (keys[i]) - { - keys[i].reset(); - } - } - - return this; - }, - - /** - * Shuts this Keyboard Plugin down. This performs the following tasks: - * - * 1 - Resets all keys created by this Keyboard plugin. - * 2 - Stops and removes the keyboard event listeners. - * 3 - Clears out any pending requests in the queue, without processing them. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#shutdown - * @private - * @since 3.10.0 - */ - shutdown: function () - { - this.resetKeys(); - - if (this.sceneInputPlugin.manager.useQueue) - { - this.sceneInputPlugin.pluginEvents.off(InputEvents.UPDATE, this.update, this); - } - else - { - this.sceneInputPlugin.manager.events.off(InputEvents.MANAGER_PROCESS, this.update, this); - } - - this.game.events.off(GameEvents.BLUR, this.resetKeys); - - this.removeAllListeners(); - - this.queue = []; - }, - - /** - * Destroys this Keyboard Plugin instance and all references it holds, plus clears out local arrays. - * - * @method Phaser.Input.Keyboard.KeyboardPlugin#destroy - * @private - * @since 3.10.0 - */ - destroy: function () - { - this.shutdown(); - - var keys = this.keys; - - for (var i = 0; i < keys.length; i++) - { - // Because it's a sparsely populated array - if (keys[i]) - { - keys[i].destroy(); - } - } - - this.keys = []; - this.combos = []; - this.queue = []; - - this.scene = null; - this.settings = null; - this.sceneInputPlugin = null; - this.manager = null; - }, - - /** - * Internal time value. - * - * @name Phaser.Input.Keyboard.KeyboardPlugin#time - * @type {number} - * @private - * @since 3.11.0 - */ - time: { - - get: function () - { - return this.sceneInputPlugin.manager.time; - } - - } - -}); - -/** - * An instance of the Keyboard Plugin class, if enabled via the `input.keyboard` Scene or Game Config property. - * Use this to create Key objects and listen for keyboard specific events. - * - * @name Phaser.Input.InputPlugin#keyboard - * @type {?Phaser.Input.Keyboard.KeyboardPlugin} - * @since 3.10.0 - */ -InputPluginCache.register('KeyboardPlugin', KeyboardPlugin, 'keyboard', 'keyboard', 'inputKeyboard'); - -module.exports = KeyboardPlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GameEvents = require('../../core/events'); +var GetValue = require('../../utils/object/GetValue'); +var InputEvents = require('../events'); +var InputPluginCache = require('../InputPluginCache'); +var Key = require('./keys/Key'); +var KeyCodes = require('./keys/KeyCodes'); +var KeyCombo = require('./combo/KeyCombo'); +var KeyMap = require('./keys/KeyMap'); +var SnapFloor = require('../../math/snap/SnapFloor'); + +/** + * @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. + * + * 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. + */ +var KeyboardPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function KeyboardPlugin (sceneInputPlugin) + { + EventEmitter.call(this); + + /** + * A reference to the core game, so we can listen for visibility events. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#game + * @type {Phaser.Game} + * @since 3.16.0 + */ + this.game = sceneInputPlugin.systems.game; + + /** + * A reference to the Scene that this Input Plugin is responsible for. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#scene + * @type {Phaser.Scene} + * @since 3.10.0 + */ + this.scene = sceneInputPlugin.scene; + + /** + * A reference to the Scene Systems Settings. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.10.0 + */ + this.settings = this.scene.sys.settings; + + /** + * A reference to the Scene Input Plugin that created this Keyboard Plugin. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#sceneInputPlugin + * @type {Phaser.Input.InputPlugin} + * @since 3.10.0 + */ + this.sceneInputPlugin = sceneInputPlugin; + + /** + * A reference to the global Keyboard Manager. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#manager + * @type {Phaser.Input.InputPlugin} + * @since 3.16.0 + */ + this.manager = sceneInputPlugin.manager.keyboard; + + /** + * A boolean that controls if this Keyboard Plugin is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#enabled + * @type {boolean} + * @default true + * @since 3.10.0 + */ + this.enabled = true; + + /** + * An array of Key objects to process. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#keys + * @type {Phaser.Input.Keyboard.Key[]} + * @since 3.10.0 + */ + this.keys = []; + + /** + * An array of KeyCombo objects to process. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#combos + * @type {Phaser.Input.Keyboard.KeyCombo[]} + * @since 3.10.0 + */ + this.combos = []; + + sceneInputPlugin.pluginEvents.once(InputEvents.BOOT, this.boot, this); + sceneInputPlugin.pluginEvents.on(InputEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#boot + * @private + * @since 3.10.0 + */ + boot: function () + { + var settings = this.settings.input; + + this.enabled = GetValue(settings, 'keyboard', true); + + var captures = GetValue(settings, 'keyboard.capture', null); + + if (captures) + { + this.addCaptures(captures); + } + + this.sceneInputPlugin.pluginEvents.once(InputEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#start + * @private + * @since 3.10.0 + */ + start: function () + { + if (this.sceneInputPlugin.manager.useQueue) + { + this.sceneInputPlugin.pluginEvents.on(InputEvents.UPDATE, this.update, this); + } + else + { + this.sceneInputPlugin.manager.events.on(InputEvents.MANAGER_PROCESS, this.update, this); + } + + this.sceneInputPlugin.pluginEvents.once(InputEvents.SHUTDOWN, this.shutdown, this); + + this.game.events.on(GameEvents.BLUR, this.resetKeys, this); + }, + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#isActive + * @since 3.10.0 + * + * @return {boolean} `true` if the plugin and the Scene it belongs to is active. + */ + isActive: function () + { + return (this.enabled && this.scene.sys.isActive()); + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * This `addCapture` method enables consuming keyboard events for specific keys, so they don't bubble up the browser + * and cause the default behaviors. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent + * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. + * + * You can pass a single key code value: + * + * ```javascript + * this.input.keyboard.addCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.addCapture([ 62, 63, 64 ]); + * ``` + * + * Or, a comma-delimited string: + * + * ```javascript + * this.input.keyboard.addCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#addCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to enable event capture for. + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + addCapture: function (keycode) + { + this.manager.addCapture(keycode); + + return this; + }, + + /** + * Removes an existing key capture. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove + * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. + * + * You can pass a single key code value: + * + * ```javascript + * this.input.keyboard.removeCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.removeCapture([ 62, 63, 64 ]); + * ``` + * + * Or, a comma-delimited string: + * + * ```javascript + * this.input.keyboard.removeCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#removeCapture + * @since 3.16.0 + * + * @param {(string|integer|integer[]|any[])} keycode - The Key Codes to disable event capture for. + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + removeCapture: function (keycode) + { + this.manager.removeCapture(keycode); + + return this; + }, + + /** + * Returns an array that contains all of the keyboard captures currently enabled. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#getCaptures + * @since 3.16.0 + * + * @return {integer[]} An array of all the currently capturing key codes. + */ + getCaptures: function () + { + return this.manager.captures; + }, + + /** + * Allows Phaser to prevent any key captures you may have defined from bubbling up the browser. + * You can use this to re-enable event capturing if you had paused it via `disableGlobalCapture`. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#enableGlobalCapture + * @since 3.16.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + enableGlobalCapture: function () + { + this.manager.preventDefault = true; + + return this; + }, + + /** + * Disables Phaser from preventing any key captures you may have defined, without actually removing them. + * You can use this to temporarily disable event capturing if, for example, you swap to a DOM element. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#disableGlobalCapture + * @since 3.16.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + disableGlobalCapture: function () + { + this.manager.preventDefault = false; + + return this; + }, + + /** + * Removes all keyboard captures. + * + * Note that this is a global change. It will clear all event captures across your game, not just for this specific Scene. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#clearCaptures + * @since 3.16.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + clearCaptures: function () + { + this.manager.clearCaptures(); + + return this; + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right, and also Space Bar and shift. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#createCursorKeys + * @since 3.10.0 + * + * @return {Phaser.Types.Input.Keyboard.CursorKeys} An object containing the properties: `up`, `down`, `left`, `right`, `space` and `shift`. + */ + createCursorKeys: function () + { + return this.addKeys({ + up: KeyCodes.UP, + down: KeyCodes.DOWN, + left: KeyCodes.LEFT, + right: KeyCodes.RIGHT, + space: KeyCodes.SPACE, + shift: KeyCodes.SHIFT + }); + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example: + * + * ```javascript + * this.input.keyboard.addKeys({ 'up': Phaser.Input.Keyboard.KeyCodes.W, 'down': Phaser.Input.Keyboard.KeyCodes.S }); + * ``` + * + * would return an object containing the properties (`up` and `down`) mapped to W and S {@link Phaser.Input.Keyboard.Key} objects. + * + * You can also pass in a comma-separated string: + * + * ```javascript + * this.input.keyboard.addKeys('W,S,A,D'); + * ``` + * + * Which will return an object with the properties W, S, A and D mapped to the relevant Key objects. + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#addKeys + * @since 3.10.0 + * + * @param {(object|string)} keys - An object containing Key Codes, or a comma-separated string. + * @param {boolean} [enableCapture=true] - Automatically call `preventDefault` on the native DOM browser event for the key codes being added. + * @param {boolean} [emitOnRepeat=false] - Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). + * + * @return {object} An object containing Key objects mapped to the input properties. + */ + addKeys: function (keys, enableCapture, emitOnRepeat) + { + if (enableCapture === undefined) { enableCapture = true; } + if (emitOnRepeat === undefined) { emitOnRepeat = false; } + + var output = {}; + + if (typeof keys === 'string') + { + keys = keys.split(','); + + for (var i = 0; i < keys.length; i++) + { + var currentKey = keys[i].trim(); + + if (currentKey) + { + output[currentKey] = this.addKey(currentKey, enableCapture, emitOnRepeat); + } + } + } + else + { + for (var key in keys) + { + output[key] = this.addKey(keys[key], enableCapture, emitOnRepeat); + } + } + + return output; + }, + + /** + * Adds a Key object to this Keyboard Plugin. + * + * The given argument can be either an existing Key object, a string, such as `A` or `SPACE`, or a key code value. + * + * If a Key object is given, and one already exists matching the same key code, the existing one is replaced with the new one. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#addKey + * @since 3.10.0 + * + * @param {(Phaser.Input.Keyboard.Key|string|integer)} key - Either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param {boolean} [enableCapture=true] - Automatically call `preventDefault` on the native DOM browser event for the key codes being added. + * @param {boolean} [emitOnRepeat=false] - Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). + * + * @return {Phaser.Input.Keyboard.Key} The newly created Key object, or a reference to it if it already existed in the keys array. + */ + addKey: function (key, enableCapture, emitOnRepeat) + { + if (enableCapture === undefined) { enableCapture = true; } + if (emitOnRepeat === undefined) { emitOnRepeat = false; } + + var keys = this.keys; + + if (key instanceof Key) + { + var idx = keys.indexOf(key); + + if (idx > -1) + { + keys[idx] = key; + } + else + { + keys[key.keyCode] = key; + } + + if (enableCapture) + { + this.addCapture(key.keyCode); + } + + key.setEmitOnRepeat(emitOnRepeat); + + return key; + } + + if (typeof key === 'string') + { + key = KeyCodes[key.toUpperCase()]; + } + + if (!keys[key]) + { + keys[key] = new Key(this, key); + + if (enableCapture) + { + this.addCapture(key); + } + + keys[key].setEmitOnRepeat(emitOnRepeat); + } + + return keys[key]; + }, + + /** + * Removes a Key object from this Keyboard Plugin. + * + * The given argument can be either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#removeKey + * @since 3.10.0 + * + * @param {(Phaser.Input.Keyboard.Key|string|integer)} key - Either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param {boolean} [destroy=false] - Call `Key.destroy` on the removed Key object? + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + removeKey: function (key, destroy) + { + if (destroy === undefined) { destroy = false; } + + var keys = this.keys; + var ref; + + if (key instanceof Key) + { + var idx = keys.indexOf(key); + + if (idx > -1) + { + ref = this.keys[idx]; + + this.keys[idx] = undefined; + } + } + else if (typeof key === 'string') + { + key = KeyCodes[key.toUpperCase()]; + } + + if (keys[key]) + { + ref = keys[key]; + + keys[key] = undefined; + } + + if (ref) + { + ref.plugin = null; + + if (destroy) + { + ref.destroy(); + } + } + + return this; + }, + + /** + * Creates a new KeyCombo. + * + * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them + * it will emit a `keycombomatch` event from this Keyboard Plugin. + * + * The keys to be listened for can be defined as: + * + * A string (i.e. 'ATARI') + * An array of either integers (key codes) or strings, or a mixture of both + * An array of objects (such as Key objects) with a public 'keyCode' property + * + * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) + * you could pass the following array of key codes: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * Or, to listen for the user entering the word PHASER: + * + * ```javascript + * this.input.keyboard.createCombo('PHASER'); + * ``` + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#createCombo + * @since 3.10.0 + * + * @param {(string|integer[]|object[])} keys - The keys that comprise this combo. + * @param {Phaser.Types.Input.Keyboard.KeyComboConfig} [config] - A Key Combo configuration object. + * + * @return {Phaser.Input.Keyboard.KeyCombo} The new KeyCombo object. + */ + createCombo: function (keys, config) + { + return new KeyCombo(this, keys, config); + }, + + /** + * Checks if the given Key object is currently being held down. + * + * The difference between this method and checking the `Key.isDown` property directly is that you can provide + * a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted + * it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it + * will only return `true` every 100ms. + * + * If the Keyboard Plugin has been disabled, this method will always return `false`. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#checkDown + * @since 3.11.0 + * + * @param {Phaser.Input.Keyboard.Key} key - A Key object. + * @param {number} [duration=0] - The duration which must have elapsed before this Key is considered as being down. + * + * @return {boolean} `true` if the Key is down within the duration specified, otherwise `false`. + */ + checkDown: function (key, duration) + { + if (this.enabled && key.isDown) + { + var t = SnapFloor(this.time - key.timeDown, duration); + + if (t > key._tick) + { + key._tick = t; + + return true; + } + } + + return false; + }, + + /** + * Internal update handler called by the Input Plugin, which is in turn invoked by the Game step. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#update + * @private + * @since 3.10.0 + */ + update: function () + { + var queue = this.manager.queue; + var len = queue.length; + + if (!this.isActive() || len === 0) + { + return; + } + + var keys = this.keys; + + // Process the event queue, dispatching all of the events that have stored up + for (var i = 0; i < len; i++) + { + var event = queue[i]; + var code = event.keyCode; + var key = keys[code]; + var repeat = false; + + // Override the default functions (it's too late for the browser to use them anyway, so we may as well) + if (event.cancelled === undefined) + { + // Event allowed to flow across all handlers in this Scene, and any other Scene in the Scene list + event.cancelled = 0; + + // Won't reach any more local (Scene level) handlers + event.stopImmediatePropagation = function () + { + event.cancelled = 1; + }; + + // Won't reach any more handlers in any Scene further down the Scene list + event.stopPropagation = function () + { + event.cancelled = -1; + }; + } + + if (event.cancelled === -1) + { + // This event has been stopped from broadcasting to any other Scene, so abort. + continue; + } + + if (event.type === 'keydown') + { + // Key specific callback first + if (key) + { + repeat = key.isDown; + + key.onDown(event); + } + + if (!event.cancelled && (!key || !repeat)) + { + if (KeyMap[code]) + { + this.emit(Events.KEY_DOWN + KeyMap[code], event); + + // Deprecated, kept in for compatibility with 3.15 + // To be removed by 3.20. + this.emit('keydown_' + KeyMap[code], event); + } + + if (!event.cancelled) + { + this.emit(Events.ANY_KEY_DOWN, event); + } + } + } + else + { + // Key specific callback first + if (key) + { + key.onUp(event); + } + + if (!event.cancelled) + { + if (KeyMap[code]) + { + this.emit(Events.KEY_UP + KeyMap[code], event); + + // Deprecated, kept in for compatibility with 3.15 + // To be removed by 3.20. + this.emit('keyup_' + KeyMap[code], event); + } + + if (!event.cancelled) + { + this.emit(Events.ANY_KEY_UP, event); + } + } + } + + // Reset the cancel state for other Scenes to use + if (event.cancelled === 1) + { + event.cancelled = 0; + } + } + }, + + /** + * Resets all Key objects created by _this_ Keyboard Plugin back to their default un-pressed states. + * This can only reset keys created via the `addKey`, `addKeys` or `createCursorKeys` methods. + * If you have created a Key object directly you'll need to reset it yourself. + * + * This method is called automatically when the Keyboard Plugin shuts down, but can be + * invoked directly at any time you require. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#resetKeys + * @since 3.15.0 + * + * @return {Phaser.Input.Keyboard.KeyboardPlugin} This KeyboardPlugin object. + */ + resetKeys: function () + { + var keys = this.keys; + + for (var i = 0; i < keys.length; i++) + { + // Because it's a sparsely populated array + if (keys[i]) + { + keys[i].reset(); + } + } + + return this; + }, + + /** + * Shuts this Keyboard Plugin down. This performs the following tasks: + * + * 1 - Resets all keys created by this Keyboard plugin. + * 2 - Stops and removes the keyboard event listeners. + * 3 - Clears out any pending requests in the queue, without processing them. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#shutdown + * @private + * @since 3.10.0 + */ + shutdown: function () + { + this.resetKeys(); + + if (this.sceneInputPlugin.manager.useQueue) + { + this.sceneInputPlugin.pluginEvents.off(InputEvents.UPDATE, this.update, this); + } + else + { + this.sceneInputPlugin.manager.events.off(InputEvents.MANAGER_PROCESS, this.update, this); + } + + this.game.events.off(GameEvents.BLUR, this.resetKeys); + + this.removeAllListeners(); + + this.queue = []; + }, + + /** + * Destroys this Keyboard Plugin instance and all references it holds, plus clears out local arrays. + * + * @method Phaser.Input.Keyboard.KeyboardPlugin#destroy + * @private + * @since 3.10.0 + */ + destroy: function () + { + this.shutdown(); + + var keys = this.keys; + + for (var i = 0; i < keys.length; i++) + { + // Because it's a sparsely populated array + if (keys[i]) + { + keys[i].destroy(); + } + } + + this.keys = []; + this.combos = []; + this.queue = []; + + this.scene = null; + this.settings = null; + this.sceneInputPlugin = null; + this.manager = null; + }, + + /** + * Internal time value. + * + * @name Phaser.Input.Keyboard.KeyboardPlugin#time + * @type {number} + * @private + * @since 3.11.0 + */ + time: { + + get: function () + { + return this.sceneInputPlugin.manager.time; + } + + } + +}); + +/** + * An instance of the Keyboard Plugin class, if enabled via the `input.keyboard` Scene or Game Config property. + * Use this to create Key objects and listen for keyboard specific events. + * + * @name Phaser.Input.InputPlugin#keyboard + * @type {?Phaser.Input.Keyboard.KeyboardPlugin} + * @since 3.10.0 + */ +InputPluginCache.register('KeyboardPlugin', KeyboardPlugin, 'keyboard', 'keyboard', 'inputKeyboard'); + +module.exports = KeyboardPlugin; diff --git a/src/input/keyboard/combo/AdvanceKeyCombo.js b/src/input/keyboard/combo/AdvanceKeyCombo.js index b60b4d0bd..9725c17aa 100644 --- a/src/input/keyboard/combo/AdvanceKeyCombo.js +++ b/src/input/keyboard/combo/AdvanceKeyCombo.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Used internally by the KeyCombo class. - * Return `true` if it reached the end of the combo, `false` if not. - * - * @function Phaser.Input.Keyboard.KeyCombo.AdvanceKeyCombo - * @private - * @since 3.0.0 - * - * @param {KeyboardEvent} event - The native Keyboard Event. - * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo object to advance. - * - * @return {boolean} `true` if it reached the end of the combo, `false` if not. - */ -var AdvanceKeyCombo = function (event, combo) -{ - combo.timeLastMatched = event.timeStamp; - combo.index++; - - if (combo.index === combo.size) - { - return true; - } - else - { - combo.current = combo.keyCodes[combo.index]; - return false; - } -}; - -module.exports = AdvanceKeyCombo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Used internally by the KeyCombo class. + * Return `true` if it reached the end of the combo, `false` if not. + * + * @function Phaser.Input.Keyboard.KeyCombo.AdvanceKeyCombo + * @private + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native Keyboard Event. + * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo object to advance. + * + * @return {boolean} `true` if it reached the end of the combo, `false` if not. + */ +var AdvanceKeyCombo = function (event, combo) +{ + combo.timeLastMatched = event.timeStamp; + combo.index++; + + if (combo.index === combo.size) + { + return true; + } + else + { + combo.current = combo.keyCodes[combo.index]; + return false; + } +}; + +module.exports = AdvanceKeyCombo; diff --git a/src/input/keyboard/combo/KeyCombo.js b/src/input/keyboard/combo/KeyCombo.js index 8ad1b5d61..00f81401e 100644 --- a/src/input/keyboard/combo/KeyCombo.js +++ b/src/input/keyboard/combo/KeyCombo.js @@ -1,287 +1,287 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Events = require('../events'); -var GetFastValue = require('../../../utils/object/GetFastValue'); -var ProcessKeyCombo = require('./ProcessKeyCombo'); -var ResetKeyCombo = require('./ResetKeyCombo'); - -/** - * @classdesc - * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them - * it will emit a `keycombomatch` event from the Keyboard Manager. - * - * The keys to be listened for can be defined as: - * - * A string (i.e. 'ATARI') - * An array of either integers (key codes) or strings, or a mixture of both - * An array of objects (such as Key objects) with a public 'keyCode' property - * - * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) - * you could pass the following array of key codes: - * - * ```javascript - * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); - * - * this.input.keyboard.on('keycombomatch', function (event) { - * console.log('Konami Code entered!'); - * }); - * ``` - * - * Or, to listen for the user entering the word PHASER: - * - * ```javascript - * this.input.keyboard.createCombo('PHASER'); - * ``` - * - * @class KeyCombo - * @memberof Phaser.Input.Keyboard - * @constructor - * @listens Phaser.Input.Keyboard.Events#ANY_KEY_DOWN - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.KeyboardPlugin} keyboardPlugin - A reference to the Keyboard Plugin. - * @param {(string|integer[]|object[])} keys - The keys that comprise this combo. - * @param {Phaser.Types.Input.Keyboard.KeyComboConfig} [config] - A Key Combo configuration object. - */ -var KeyCombo = new Class({ - - initialize: - - function KeyCombo (keyboardPlugin, keys, config) - { - if (config === undefined) { config = {}; } - - // Can't have a zero or single length combo (string or array based) - if (keys.length < 2) - { - return false; - } - - /** - * A reference to the Keyboard Manager - * - * @name Phaser.Input.Keyboard.KeyCombo#manager - * @type {Phaser.Input.Keyboard.KeyboardPlugin} - * @since 3.0.0 - */ - this.manager = keyboardPlugin; - - /** - * A flag that controls if this Key Combo is actively processing keys or not. - * - * @name Phaser.Input.Keyboard.KeyCombo#enabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enabled = true; - - /** - * An array of the keycodes that comprise this combo. - * - * @name Phaser.Input.Keyboard.KeyCombo#keyCodes - * @type {array} - * @default [] - * @since 3.0.0 - */ - this.keyCodes = []; - - // if 'keys' is a string we need to get the keycode of each character in it - - for (var i = 0; i < keys.length; i++) - { - var char = keys[i]; - - if (typeof char === 'string') - { - this.keyCodes.push(char.toUpperCase().charCodeAt(0)); - } - else if (typeof char === 'number') - { - this.keyCodes.push(char); - } - else if (char.hasOwnProperty('keyCode')) - { - this.keyCodes.push(char.keyCode); - } - } - - /** - * The current keyCode the combo is waiting for. - * - * @name Phaser.Input.Keyboard.KeyCombo#current - * @type {integer} - * @since 3.0.0 - */ - this.current = this.keyCodes[0]; - - /** - * The current index of the key being waited for in the 'keys' string. - * - * @name Phaser.Input.Keyboard.KeyCombo#index - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.index = 0; - - /** - * The length of this combo (in keycodes) - * - * @name Phaser.Input.Keyboard.KeyCombo#size - * @type {number} - * @since 3.0.0 - */ - this.size = this.keyCodes.length; - - /** - * The time the previous key in the combo was matched. - * - * @name Phaser.Input.Keyboard.KeyCombo#timeLastMatched - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.timeLastMatched = 0; - - /** - * Has this Key Combo been matched yet? - * - * @name Phaser.Input.Keyboard.KeyCombo#matched - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.matched = false; - - /** - * The time the entire combo was matched. - * - * @name Phaser.Input.Keyboard.KeyCombo#timeMatched - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.timeMatched = 0; - - /** - * If they press the wrong key do we reset the combo? - * - * @name Phaser.Input.Keyboard.KeyCombo#resetOnWrongKey - * @type {boolean} - * @default 0 - * @since 3.0.0 - */ - this.resetOnWrongKey = GetFastValue(config, 'resetOnWrongKey', true); - - /** - * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. - * - * @name Phaser.Input.Keyboard.KeyCombo#maxKeyDelay - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.maxKeyDelay = GetFastValue(config, 'maxKeyDelay', 0); - - /** - * If previously matched and they press the first key of the combo again, will it reset? - * - * @name Phaser.Input.Keyboard.KeyCombo#resetOnMatch - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.resetOnMatch = GetFastValue(config, 'resetOnMatch', false); - - /** - * If the combo matches, will it delete itself? - * - * @name Phaser.Input.Keyboard.KeyCombo#deleteOnMatch - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.deleteOnMatch = GetFastValue(config, 'deleteOnMatch', false); - - var _this = this; - - var onKeyDownHandler = function (event) - { - if (_this.matched || !_this.enabled) - { - return; - } - - var matched = ProcessKeyCombo(event, _this); - - if (matched) - { - _this.manager.emit(Events.COMBO_MATCH, _this, event); - - if (_this.resetOnMatch) - { - ResetKeyCombo(_this); - } - else if (_this.deleteOnMatch) - { - _this.destroy(); - } - } - }; - - /** - * The internal Key Down handler. - * - * @name Phaser.Input.Keyboard.KeyCombo#onKeyDown - * @private - * @type {KeyboardKeydownCallback} - * @fires Phaser.Input.Keyboard.Events#COMBO_MATCH - * @since 3.0.0 - */ - this.onKeyDown = onKeyDownHandler; - - this.manager.on(Events.ANY_KEY_DOWN, this.onKeyDown); - }, - - /** - * How far complete is this combo? A value between 0 and 1. - * - * @name Phaser.Input.Keyboard.KeyCombo#progress - * @type {number} - * @readonly - * @since 3.0.0 - */ - progress: { - - get: function () - { - return this.index / this.size; - } - - }, - - /** - * Destroys this Key Combo and all of its references. - * - * @method Phaser.Input.Keyboard.KeyCombo#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.enabled = false; - this.keyCodes = []; - - this.manager.off(Events.ANY_KEY_DOWN, this.onKeyDown); - - this.manager = null; - } - -}); - -module.exports = KeyCombo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Events = require('../events'); +var GetFastValue = require('../../../utils/object/GetFastValue'); +var ProcessKeyCombo = require('./ProcessKeyCombo'); +var ResetKeyCombo = require('./ResetKeyCombo'); + +/** + * @classdesc + * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them + * it will emit a `keycombomatch` event from the Keyboard Manager. + * + * The keys to be listened for can be defined as: + * + * A string (i.e. 'ATARI') + * An array of either integers (key codes) or strings, or a mixture of both + * An array of objects (such as Key objects) with a public 'keyCode' property + * + * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) + * you could pass the following array of key codes: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * Or, to listen for the user entering the word PHASER: + * + * ```javascript + * this.input.keyboard.createCombo('PHASER'); + * ``` + * + * @class KeyCombo + * @memberof Phaser.Input.Keyboard + * @constructor + * @listens Phaser.Input.Keyboard.Events#ANY_KEY_DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyboardPlugin} keyboardPlugin - A reference to the Keyboard Plugin. + * @param {(string|integer[]|object[])} keys - The keys that comprise this combo. + * @param {Phaser.Types.Input.Keyboard.KeyComboConfig} [config] - A Key Combo configuration object. + */ +var KeyCombo = new Class({ + + initialize: + + function KeyCombo (keyboardPlugin, keys, config) + { + if (config === undefined) { config = {}; } + + // Can't have a zero or single length combo (string or array based) + if (keys.length < 2) + { + return false; + } + + /** + * A reference to the Keyboard Manager + * + * @name Phaser.Input.Keyboard.KeyCombo#manager + * @type {Phaser.Input.Keyboard.KeyboardPlugin} + * @since 3.0.0 + */ + this.manager = keyboardPlugin; + + /** + * A flag that controls if this Key Combo is actively processing keys or not. + * + * @name Phaser.Input.Keyboard.KeyCombo#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * An array of the keycodes that comprise this combo. + * + * @name Phaser.Input.Keyboard.KeyCombo#keyCodes + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.keyCodes = []; + + // if 'keys' is a string we need to get the keycode of each character in it + + for (var i = 0; i < keys.length; i++) + { + var char = keys[i]; + + if (typeof char === 'string') + { + this.keyCodes.push(char.toUpperCase().charCodeAt(0)); + } + else if (typeof char === 'number') + { + this.keyCodes.push(char); + } + else if (char.hasOwnProperty('keyCode')) + { + this.keyCodes.push(char.keyCode); + } + } + + /** + * The current keyCode the combo is waiting for. + * + * @name Phaser.Input.Keyboard.KeyCombo#current + * @type {integer} + * @since 3.0.0 + */ + this.current = this.keyCodes[0]; + + /** + * The current index of the key being waited for in the 'keys' string. + * + * @name Phaser.Input.Keyboard.KeyCombo#index + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.index = 0; + + /** + * The length of this combo (in keycodes) + * + * @name Phaser.Input.Keyboard.KeyCombo#size + * @type {number} + * @since 3.0.0 + */ + this.size = this.keyCodes.length; + + /** + * The time the previous key in the combo was matched. + * + * @name Phaser.Input.Keyboard.KeyCombo#timeLastMatched + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeLastMatched = 0; + + /** + * Has this Key Combo been matched yet? + * + * @name Phaser.Input.Keyboard.KeyCombo#matched + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.matched = false; + + /** + * The time the entire combo was matched. + * + * @name Phaser.Input.Keyboard.KeyCombo#timeMatched + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeMatched = 0; + + /** + * If they press the wrong key do we reset the combo? + * + * @name Phaser.Input.Keyboard.KeyCombo#resetOnWrongKey + * @type {boolean} + * @default 0 + * @since 3.0.0 + */ + this.resetOnWrongKey = GetFastValue(config, 'resetOnWrongKey', true); + + /** + * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. + * + * @name Phaser.Input.Keyboard.KeyCombo#maxKeyDelay + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.maxKeyDelay = GetFastValue(config, 'maxKeyDelay', 0); + + /** + * If previously matched and they press the first key of the combo again, will it reset? + * + * @name Phaser.Input.Keyboard.KeyCombo#resetOnMatch + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.resetOnMatch = GetFastValue(config, 'resetOnMatch', false); + + /** + * If the combo matches, will it delete itself? + * + * @name Phaser.Input.Keyboard.KeyCombo#deleteOnMatch + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.deleteOnMatch = GetFastValue(config, 'deleteOnMatch', false); + + var _this = this; + + var onKeyDownHandler = function (event) + { + if (_this.matched || !_this.enabled) + { + return; + } + + var matched = ProcessKeyCombo(event, _this); + + if (matched) + { + _this.manager.emit(Events.COMBO_MATCH, _this, event); + + if (_this.resetOnMatch) + { + ResetKeyCombo(_this); + } + else if (_this.deleteOnMatch) + { + _this.destroy(); + } + } + }; + + /** + * The internal Key Down handler. + * + * @name Phaser.Input.Keyboard.KeyCombo#onKeyDown + * @private + * @type {KeyboardKeydownCallback} + * @fires Phaser.Input.Keyboard.Events#COMBO_MATCH + * @since 3.0.0 + */ + this.onKeyDown = onKeyDownHandler; + + this.manager.on(Events.ANY_KEY_DOWN, this.onKeyDown); + }, + + /** + * How far complete is this combo? A value between 0 and 1. + * + * @name Phaser.Input.Keyboard.KeyCombo#progress + * @type {number} + * @readonly + * @since 3.0.0 + */ + progress: { + + get: function () + { + return this.index / this.size; + } + + }, + + /** + * Destroys this Key Combo and all of its references. + * + * @method Phaser.Input.Keyboard.KeyCombo#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.enabled = false; + this.keyCodes = []; + + this.manager.off(Events.ANY_KEY_DOWN, this.onKeyDown); + + this.manager = null; + } + +}); + +module.exports = KeyCombo; diff --git a/src/input/keyboard/combo/ProcessKeyCombo.js b/src/input/keyboard/combo/ProcessKeyCombo.js index bb5fe93d3..9bd744957 100644 --- a/src/input/keyboard/combo/ProcessKeyCombo.js +++ b/src/input/keyboard/combo/ProcessKeyCombo.js @@ -1,75 +1,75 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AdvanceKeyCombo = require('./AdvanceKeyCombo'); - -/** - * Used internally by the KeyCombo class. - * - * @function Phaser.Input.Keyboard.KeyCombo.ProcessKeyCombo - * @private - * @since 3.0.0 - * - * @param {KeyboardEvent} event - The native Keyboard Event. - * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo object to be processed. - * - * @return {boolean} `true` if the combo was matched, otherwise `false`. - */ -var ProcessKeyCombo = function (event, combo) -{ - if (combo.matched) - { - return true; - } - - var comboMatched = false; - var keyMatched = false; - - if (event.keyCode === combo.current) - { - // Key was correct - - if (combo.index > 0 && combo.maxKeyDelay > 0) - { - // We have to check to see if the delay between - // the new key and the old one was too long (if enabled) - - var timeLimit = combo.timeLastMatched + combo.maxKeyDelay; - - // Check if they pressed it in time or not - if (event.timeStamp <= timeLimit) - { - keyMatched = true; - comboMatched = AdvanceKeyCombo(event, combo); - } - } - else - { - keyMatched = true; - - // We don't check the time for the first key pressed, so just advance it - comboMatched = AdvanceKeyCombo(event, combo); - } - } - - if (!keyMatched && combo.resetOnWrongKey) - { - // Wrong key was pressed - combo.index = 0; - combo.current = combo.keyCodes[0]; - } - - if (comboMatched) - { - combo.timeLastMatched = event.timeStamp; - combo.matched = true; - combo.timeMatched = event.timeStamp; - } - - return comboMatched; -}; - -module.exports = ProcessKeyCombo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AdvanceKeyCombo = require('./AdvanceKeyCombo'); + +/** + * Used internally by the KeyCombo class. + * + * @function Phaser.Input.Keyboard.KeyCombo.ProcessKeyCombo + * @private + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native Keyboard Event. + * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo object to be processed. + * + * @return {boolean} `true` if the combo was matched, otherwise `false`. + */ +var ProcessKeyCombo = function (event, combo) +{ + if (combo.matched) + { + return true; + } + + var comboMatched = false; + var keyMatched = false; + + if (event.keyCode === combo.current) + { + // Key was correct + + if (combo.index > 0 && combo.maxKeyDelay > 0) + { + // We have to check to see if the delay between + // the new key and the old one was too long (if enabled) + + var timeLimit = combo.timeLastMatched + combo.maxKeyDelay; + + // Check if they pressed it in time or not + if (event.timeStamp <= timeLimit) + { + keyMatched = true; + comboMatched = AdvanceKeyCombo(event, combo); + } + } + else + { + keyMatched = true; + + // We don't check the time for the first key pressed, so just advance it + comboMatched = AdvanceKeyCombo(event, combo); + } + } + + if (!keyMatched && combo.resetOnWrongKey) + { + // Wrong key was pressed + combo.index = 0; + combo.current = combo.keyCodes[0]; + } + + if (comboMatched) + { + combo.timeLastMatched = event.timeStamp; + combo.matched = true; + combo.timeMatched = event.timeStamp; + } + + return comboMatched; +}; + +module.exports = ProcessKeyCombo; diff --git a/src/input/keyboard/combo/ResetKeyCombo.js b/src/input/keyboard/combo/ResetKeyCombo.js index 72088e238..b1c5182de 100644 --- a/src/input/keyboard/combo/ResetKeyCombo.js +++ b/src/input/keyboard/combo/ResetKeyCombo.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Used internally by the KeyCombo class. - * - * @function Phaser.Input.Keyboard.KeyCombo.ResetKeyCombo - * @private - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo to reset. - * - * @return {Phaser.Input.Keyboard.KeyCombo} The KeyCombo. - */ -var ResetKeyCombo = function (combo) -{ - combo.current = combo.keyCodes[0]; - combo.index = 0; - combo.timeLastMatched = 0; - combo.matched = false; - combo.timeMatched = 0; - - return combo; -}; - -module.exports = ResetKeyCombo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Used internally by the KeyCombo class. + * + * @function Phaser.Input.Keyboard.KeyCombo.ResetKeyCombo + * @private + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyCombo} combo - The KeyCombo to reset. + * + * @return {Phaser.Input.Keyboard.KeyCombo} The KeyCombo. + */ +var ResetKeyCombo = function (combo) +{ + combo.current = combo.keyCodes[0]; + combo.index = 0; + combo.timeLastMatched = 0; + combo.matched = false; + combo.timeMatched = 0; + + return combo; +}; + +module.exports = ResetKeyCombo; diff --git a/src/input/keyboard/events/ANY_KEY_DOWN_EVENT.js b/src/input/keyboard/events/ANY_KEY_DOWN_EVENT.js index 68a27620a..db8465422 100644 --- a/src/input/keyboard/events/ANY_KEY_DOWN_EVENT.js +++ b/src/input/keyboard/events/ANY_KEY_DOWN_EVENT.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'keydown'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'keydown'; diff --git a/src/input/keyboard/events/ANY_KEY_UP_EVENT.js b/src/input/keyboard/events/ANY_KEY_UP_EVENT.js index c3a38b3e9..6e74cbfe4 100644 --- a/src/input/keyboard/events/ANY_KEY_UP_EVENT.js +++ b/src/input/keyboard/events/ANY_KEY_UP_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Global Key Up Event. - * - * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. - * - * Listen to this event from within a Scene using: `this.input.keyboard.on('keyup', listener)`. - * - * You can also listen for a specific key being released. See [Keyboard.Events.KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:KEY_UP} for details. - * - * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. - * - * @event Phaser.Input.Keyboard.Events#ANY_KEY_UP - * @since 3.0.0 - * - * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was released, any modifiers, etc. - */ -module.exports = 'keyup'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Global Key Up Event. + * + * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. + * + * Listen to this event from within a Scene using: `this.input.keyboard.on('keyup', listener)`. + * + * You can also listen for a specific key being released. See [Keyboard.Events.KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:KEY_UP} for details. + * + * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. + * + * @event Phaser.Input.Keyboard.Events#ANY_KEY_UP + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was released, any modifiers, etc. + */ +module.exports = 'keyup'; diff --git a/src/input/keyboard/events/COMBO_MATCH_EVENT.js b/src/input/keyboard/events/COMBO_MATCH_EVENT.js index 8d3199f7f..0c5ec4e68 100644 --- a/src/input/keyboard/events/COMBO_MATCH_EVENT.js +++ b/src/input/keyboard/events/COMBO_MATCH_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Key Combo Match Event. - * - * This event is dispatched by the Keyboard Plugin when a [Key Combo]{@link Phaser.Input.Keyboard.KeyCombo} is matched. - * - * Listen for this event from the Key Plugin after a combo has been created: - * - * ```javascript - * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); - * - * this.input.keyboard.on('keycombomatch', function (event) { - * console.log('Konami Code entered!'); - * }); - * ``` - * - * @event Phaser.Input.Keyboard.Events#COMBO_MATCH - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.KeyCombo} keycombo - The Key Combo object that was matched. - * @param {KeyboardEvent} event - The native DOM Keyboard Event of the final key in the combo. You can inspect this to learn more about any modifiers, etc. - */ -module.exports = 'keycombomatch'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Combo Match Event. + * + * This event is dispatched by the Keyboard Plugin when a [Key Combo]{@link Phaser.Input.Keyboard.KeyCombo} is matched. + * + * Listen for this event from the Key Plugin after a combo has been created: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * @event Phaser.Input.Keyboard.Events#COMBO_MATCH + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyCombo} keycombo - The Key Combo object that was matched. + * @param {KeyboardEvent} event - The native DOM Keyboard Event of the final key in the combo. You can inspect this to learn more about any modifiers, etc. + */ +module.exports = 'keycombomatch'; diff --git a/src/input/keyboard/events/DOWN_EVENT.js b/src/input/keyboard/events/DOWN_EVENT.js index 24d9b7b1d..b83dda3f7 100644 --- a/src/input/keyboard/events/DOWN_EVENT.js +++ b/src/input/keyboard/events/DOWN_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Key Down Event. - * - * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is pressed. - * - * Listen for this event from the Key object instance directly: - * - * ```javascript - * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); - * - * spaceBar.on('down', 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. - * - * @event Phaser.Input.Keyboard.Events#DOWN - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.Key} key - The Key object that was pressed. - * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about any modifiers, etc. - */ -module.exports = 'down'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Down Event. + * + * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is pressed. + * + * Listen for this event from the Key object instance directly: + * + * ```javascript + * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); + * + * spaceBar.on('down', 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. + * + * @event Phaser.Input.Keyboard.Events#DOWN + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key object that was pressed. + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about any modifiers, etc. + */ +module.exports = 'down'; diff --git a/src/input/keyboard/events/KEY_DOWN_EVENT.js b/src/input/keyboard/events/KEY_DOWN_EVENT.js index 911a6c402..2658ceca2 100644 --- a/src/input/keyboard/events/KEY_DOWN_EVENT.js +++ b/src/input/keyboard/events/KEY_DOWN_EVENT.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * @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. - */ -module.exports = 'keydown-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * @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. + */ +module.exports = 'keydown-'; diff --git a/src/input/keyboard/events/KEY_UP_EVENT.js b/src/input/keyboard/events/KEY_UP_EVENT.js index 55065f213..9c959a3d9 100644 --- a/src/input/keyboard/events/KEY_UP_EVENT.js +++ b/src/input/keyboard/events/KEY_UP_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Key Up Event. - * - * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. - * - * Unlike the `ANY_KEY_UP` event, this one has a special dynamic event name. For example, to listen for the `A` key being released - * use the following from within a Scene: `this.input.keyboard.on('keyup-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('keyup-SPACE', listener)`. - * - * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. - * - * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. - * - * @event Phaser.Input.Keyboard.Events#KEY_UP - * @since 3.0.0 - * - * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was released, any modifiers, etc. - */ -module.exports = 'keyup-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Up Event. + * + * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. + * + * Unlike the `ANY_KEY_UP` event, this one has a special dynamic event name. For example, to listen for the `A` key being released + * use the following from within a Scene: `this.input.keyboard.on('keyup-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('keyup-SPACE', listener)`. + * + * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. + * + * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. + * + * @event Phaser.Input.Keyboard.Events#KEY_UP + * @since 3.0.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was released, any modifiers, etc. + */ +module.exports = 'keyup-'; diff --git a/src/input/keyboard/events/UP_EVENT.js b/src/input/keyboard/events/UP_EVENT.js index 126d916e7..4d347fc93 100644 --- a/src/input/keyboard/events/UP_EVENT.js +++ b/src/input/keyboard/events/UP_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Key Up Event. - * - * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is released. - * - * Listen for this event from the Key object instance directly: - * - * ```javascript - * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); - * - * spaceBar.on('up', listener) - * ``` - * - * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. - * - * @event Phaser.Input.Keyboard.Events#UP - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.Key} key - The Key object that was released. - * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about any modifiers, etc. - */ -module.exports = 'up'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Key Up Event. + * + * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is released. + * + * Listen for this event from the Key object instance directly: + * + * ```javascript + * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); + * + * spaceBar.on('up', listener) + * ``` + * + * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. + * + * @event Phaser.Input.Keyboard.Events#UP + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key object that was released. + * @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about any modifiers, etc. + */ +module.exports = 'up'; diff --git a/src/input/keyboard/events/index.js b/src/input/keyboard/events/index.js index 3eca6a61e..462348930 100644 --- a/src/input/keyboard/events/index.js +++ b/src/input/keyboard/events/index.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Keyboard.Events - */ - -module.exports = { - - ANY_KEY_DOWN: require('./ANY_KEY_DOWN_EVENT'), - ANY_KEY_UP: require('./ANY_KEY_UP_EVENT'), - COMBO_MATCH: require('./COMBO_MATCH_EVENT'), - DOWN: require('./DOWN_EVENT'), - KEY_DOWN: require('./KEY_DOWN_EVENT'), - KEY_UP: require('./KEY_UP_EVENT'), - UP: require('./UP_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Keyboard.Events + */ + +module.exports = { + + ANY_KEY_DOWN: require('./ANY_KEY_DOWN_EVENT'), + ANY_KEY_UP: require('./ANY_KEY_UP_EVENT'), + COMBO_MATCH: require('./COMBO_MATCH_EVENT'), + DOWN: require('./DOWN_EVENT'), + KEY_DOWN: require('./KEY_DOWN_EVENT'), + KEY_UP: require('./KEY_UP_EVENT'), + UP: require('./UP_EVENT') + +}; diff --git a/src/input/keyboard/index.js b/src/input/keyboard/index.js index 67225ba20..2e2fd37c3 100644 --- a/src/input/keyboard/index.js +++ b/src/input/keyboard/index.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Keyboard - */ - -module.exports = { - - Events: require('./events'), - - KeyboardManager: require('./KeyboardManager'), - KeyboardPlugin: require('./KeyboardPlugin'), - - Key: require('./keys/Key'), - KeyCodes: require('./keys/KeyCodes'), - - KeyCombo: require('./combo/KeyCombo'), - - JustDown: require('./keys/JustDown'), - JustUp: require('./keys/JustUp'), - DownDuration: require('./keys/DownDuration'), - UpDuration: require('./keys/UpDuration') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Keyboard + */ + +module.exports = { + + Events: require('./events'), + + KeyboardManager: require('./KeyboardManager'), + KeyboardPlugin: require('./KeyboardPlugin'), + + Key: require('./keys/Key'), + KeyCodes: require('./keys/KeyCodes'), + + KeyCombo: require('./combo/KeyCombo'), + + JustDown: require('./keys/JustDown'), + JustUp: require('./keys/JustUp'), + DownDuration: require('./keys/DownDuration'), + UpDuration: require('./keys/UpDuration') + +}; diff --git a/src/input/keyboard/keys/DownDuration.js b/src/input/keyboard/keys/DownDuration.js index 84d55ae73..7d37a8f42 100644 --- a/src/input/keyboard/keys/DownDuration.js +++ b/src/input/keyboard/keys/DownDuration.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 {integer} [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`. - */ -var DownDuration = function (key, duration) -{ - if (duration === undefined) { duration = 50; } - - var current = key.plugin.game.loop.time - key.timeDown; - - return (key.isDown && current < duration); -}; - -module.exports = DownDuration; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} [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`. + */ +var DownDuration = function (key, duration) +{ + if (duration === undefined) { duration = 50; } + + var current = key.plugin.game.loop.time - key.timeDown; + + return (key.isDown && current < duration); +}; + +module.exports = DownDuration; diff --git a/src/input/keyboard/keys/JustDown.js b/src/input/keyboard/keys/JustDown.js index 89f34fe99..81f8730b3 100644 --- a/src/input/keyboard/keys/JustDown.js +++ b/src/input/keyboard/keys/JustDown.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The justDown value allows you to test if this Key has just been pressed down or not. - * - * When you check this value it will return `true` if the Key is down, otherwise `false`. - * - * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. - * This allows you to use it in situations where you want to check if this key is down without using an event, such as in a core game loop. - * - * @function Phaser.Input.Keyboard.JustDown - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.Key} key - The Key to check to see if it's just down or not. - * - * @return {boolean} `true` if the Key was just pressed, otherwise `false`. - */ -var JustDown = function (key) -{ - if (key._justDown) - { - key._justDown = false; - - return true; - } - else - { - return false; - } -}; - -module.exports = JustDown; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The justDown value allows you to test if this Key has just been pressed down or not. + * + * When you check this value it will return `true` if the Key is down, otherwise `false`. + * + * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. + * This allows you to use it in situations where you want to check if this key is down without using an event, such as in a core game loop. + * + * @function Phaser.Input.Keyboard.JustDown + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key to check to see if it's just down or not. + * + * @return {boolean} `true` if the Key was just pressed, otherwise `false`. + */ +var JustDown = function (key) +{ + if (key._justDown) + { + key._justDown = false; + + return true; + } + else + { + return false; + } +}; + +module.exports = JustDown; diff --git a/src/input/keyboard/keys/JustUp.js b/src/input/keyboard/keys/JustUp.js index 97bc3b894..9780972e8 100644 --- a/src/input/keyboard/keys/JustUp.js +++ b/src/input/keyboard/keys/JustUp.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The justUp value allows you to test if this Key has just been released or not. - * - * When you check this value it will return `true` if the Key is up, otherwise `false`. - * - * You can only call JustUp once per key release. It will only return `true` once, until the Key is pressed down and released again. - * This allows you to use it in situations where you want to check if this key is up without using an event, such as in a core game loop. - * - * @function Phaser.Input.Keyboard.JustUp - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.Key} key - The Key to check to see if it's just up or not. - * - * @return {boolean} `true` if the Key was just released, otherwise `false`. - */ -var JustUp = function (key) -{ - if (key._justUp) - { - key._justUp = false; - - return true; - } - else - { - return false; - } -}; - -module.exports = JustUp; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The justUp value allows you to test if this Key has just been released or not. + * + * When you check this value it will return `true` if the Key is up, otherwise `false`. + * + * You can only call JustUp once per key release. It will only return `true` once, until the Key is pressed down and released again. + * This allows you to use it in situations where you want to check if this key is up without using an event, such as in a core game loop. + * + * @function Phaser.Input.Keyboard.JustUp + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.Key} key - The Key to check to see if it's just up or not. + * + * @return {boolean} `true` if the Key was just released, otherwise `false`. + */ +var JustUp = function (key) +{ + if (key._justUp) + { + key._justUp = false; + + return true; + } + else + { + return false; + } +}; + +module.exports = JustUp; diff --git a/src/input/keyboard/keys/Key.js b/src/input/keyboard/keys/Key.js index cceed0d1c..e31565960 100644 --- a/src/input/keyboard/keys/Key.js +++ b/src/input/keyboard/keys/Key.js @@ -1,396 +1,396 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('../events'); - -/** - * @classdesc - * A generic Key object which can be passed to the Process functions (and so on) - * keycode must be an integer - * - * @class Key - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Input.Keyboard - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.Keyboard.KeyboardPlugin} plugin - The Keyboard Plugin instance that owns this Key object. - * @param {integer} keyCode - The keycode of this key. - */ -var Key = new Class({ - - Extends: EventEmitter, - - initialize: - - function Key (plugin, keyCode) - { - EventEmitter.call(this); - - /** - * The Keyboard Plugin instance that owns this Key object. - * - * @name Phaser.Input.Keyboard.Key#plugin - * @type {Phaser.Input.Keyboard.KeyboardPlugin} - * @since 3.17.0 - */ - this.plugin = plugin; - - /** - * The keycode of this key. - * - * @name Phaser.Input.Keyboard.Key#keyCode - * @type {integer} - * @since 3.0.0 - */ - this.keyCode = keyCode; - - /** - * The original DOM event. - * - * @name Phaser.Input.Keyboard.Key#originalEvent - * @type {KeyboardEvent} - * @since 3.0.0 - */ - this.originalEvent = undefined; - - /** - * Can this Key be processed? - * - * @name Phaser.Input.Keyboard.Key#enabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enabled = true; - - /** - * The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. - * - * @name Phaser.Input.Keyboard.Key#isDown - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isDown = false; - - /** - * The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. - * - * @name Phaser.Input.Keyboard.Key#isUp - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.isUp = true; - - /** - * The down state of the ALT key, if pressed at the same time as this key. - * - * @name Phaser.Input.Keyboard.Key#altKey - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.altKey = false; - - /** - * The down state of the CTRL key, if pressed at the same time as this key. - * - * @name Phaser.Input.Keyboard.Key#ctrlKey - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.ctrlKey = false; - - /** - * The down state of the SHIFT key, if pressed at the same time as this key. - * - * @name Phaser.Input.Keyboard.Key#shiftKey - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.shiftKey = false; - - /** - * The down state of the Meta key, if pressed at the same time as this key. - * On a Mac the Meta Key is the Command key. On Windows keyboards, it's the Windows key. - * - * @name Phaser.Input.Keyboard.Key#metaKey - * @type {boolean} - * @default false - * @since 3.16.0 - */ - this.metaKey = false; - - /** - * The location of the modifier key. 0 for standard (or unknown), 1 for left, 2 for right, 3 for numpad. - * - * @name Phaser.Input.Keyboard.Key#location - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.location = 0; - - /** - * The timestamp when the key was last pressed down. - * - * @name Phaser.Input.Keyboard.Key#timeDown - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.timeDown = 0; - - /** - * The number of milliseconds this key was held down for in the previous down - up sequence. - * This value isn't updated every game step, only when the Key changes state. - * To get the current duration use the `getDuration` method. - * - * @name Phaser.Input.Keyboard.Key#duration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.duration = 0; - - /** - * The timestamp when the key was last released. - * - * @name Phaser.Input.Keyboard.Key#timeUp - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.timeUp = 0; - - /** - * When a key is held down should it continuously fire the `down` event each time it repeats? - * - * By default it will emit the `down` event just once, but if you wish to receive the event - * for each repeat as well, enable this property. - * - * @name Phaser.Input.Keyboard.Key#emitOnRepeat - * @type {boolean} - * @default false - * @since 3.16.0 - */ - this.emitOnRepeat = false; - - /** - * If a key is held down this holds down the number of times the key has 'repeated'. - * - * @name Phaser.Input.Keyboard.Key#repeats - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.repeats = 0; - - /** - * True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) - * - * @name Phaser.Input.Keyboard.Key#_justDown - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._justDown = false; - - /** - * True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) - * - * @name Phaser.Input.Keyboard.Key#_justUp - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._justUp = false; - - /** - * Internal tick counter. - * - * @name Phaser.Input.Keyboard.Key#_tick - * @type {number} - * @private - * @since 3.11.0 - */ - this._tick = -1; - }, - - /** - * Controls if this Key will continuously emit a `down` event while being held down (true), - * or emit the event just once, on first press, and then skip future events (false). - * - * @method Phaser.Input.Keyboard.Key#setEmitOnRepeat - * @since 3.16.0 - * - * @param {boolean} value - Emit `down` events on repeated key down actions, or just once? - * - * @return {Phaser.Input.Keyboard.Key} This Key instance. - */ - setEmitOnRepeat: function (value) - { - this.emitOnRepeat = value; - - return this; - }, - - /** - * Processes the Key Down action for this Key. - * Called automatically by the Keyboard Plugin. - * - * @method Phaser.Input.Keyboard.Key#onDown - * @fires Phaser.Input.Keyboard.Events#DOWN - * @since 3.16.0 - * - * @param {KeyboardEvent} event - The native DOM Keyboard event. - */ - onDown: function (event) - { - this.originalEvent = event; - - if (!this.enabled) - { - return; - } - - this.altKey = event.altKey; - this.ctrlKey = event.ctrlKey; - this.shiftKey = event.shiftKey; - this.metaKey = event.metaKey; - this.location = event.location; - - this.repeats++; - - if (!this.isDown) - { - this.isDown = true; - this.isUp = false; - this.timeDown = event.timeStamp; - this.duration = 0; - this._justDown = true; - this._justUp = false; - - this.emit(Events.DOWN, this, event); - } - else if (this.emitOnRepeat) - { - this.emit(Events.DOWN, this, event); - } - }, - - /** - * Processes the Key Up action for this Key. - * Called automatically by the Keyboard Plugin. - * - * @method Phaser.Input.Keyboard.Key#onUp - * @fires Phaser.Input.Keyboard.Events#UP - * @since 3.16.0 - * - * @param {KeyboardEvent} event - The native DOM Keyboard event. - */ - onUp: function (event) - { - this.originalEvent = event; - - if (!this.enabled) - { - return; - } - - this.isDown = false; - this.isUp = true; - this.timeUp = event.timeStamp; - this.duration = this.timeUp - this.timeDown; - this.repeats = 0; - - this._justDown = false; - this._justUp = true; - this._tick = -1; - - this.emit(Events.UP, this, event); - }, - - /** - * Resets this Key object back to its default un-pressed state. - * - * @method Phaser.Input.Keyboard.Key#reset - * @since 3.6.0 - * - * @return {Phaser.Input.Keyboard.Key} This Key instance. - */ - reset: function () - { - this.preventDefault = true; - this.enabled = true; - this.isDown = false; - this.isUp = true; - this.altKey = false; - this.ctrlKey = false; - this.shiftKey = false; - this.metaKey = false; - this.timeDown = 0; - this.duration = 0; - this.timeUp = 0; - this.repeats = 0; - this._justDown = false; - this._justUp = false; - this._tick = -1; - - return this; - }, - - /** - * Returns the duration, in ms, that the Key has been held down for. - * - * If the key is not currently down it will return zero. - * - * The get the duration the Key was held down for in the previous up-down cycle, - * use the `Key.duration` property value instead. - * - * @method Phaser.Input.Keyboard.Key#getDuration - * @since 3.17.0 - * - * @return {number} The duration, in ms, that the Key has been held down for if currently down. - */ - getDuration: function () - { - if (this.isDown) - { - return (this.plugin.game.loop.time - this.timeDown); - } - else - { - return 0; - } - }, - - /** - * Removes any bound event handlers and removes local references. - * - * @method Phaser.Input.Keyboard.Key#destroy - * @since 3.16.0 - */ - destroy: function () - { - this.removeAllListeners(); - - this.originalEvent = null; - - this.plugin = null; - } - -}); - -module.exports = Key; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('../events'); + +/** + * @classdesc + * A generic Key object which can be passed to the Process functions (and so on) + * keycode must be an integer + * + * @class Key + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Input.Keyboard + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.Keyboard.KeyboardPlugin} plugin - The Keyboard Plugin instance that owns this Key object. + * @param {integer} keyCode - The keycode of this key. + */ +var Key = new Class({ + + Extends: EventEmitter, + + initialize: + + function Key (plugin, keyCode) + { + EventEmitter.call(this); + + /** + * The Keyboard Plugin instance that owns this Key object. + * + * @name Phaser.Input.Keyboard.Key#plugin + * @type {Phaser.Input.Keyboard.KeyboardPlugin} + * @since 3.17.0 + */ + this.plugin = plugin; + + /** + * The keycode of this key. + * + * @name Phaser.Input.Keyboard.Key#keyCode + * @type {integer} + * @since 3.0.0 + */ + this.keyCode = keyCode; + + /** + * The original DOM event. + * + * @name Phaser.Input.Keyboard.Key#originalEvent + * @type {KeyboardEvent} + * @since 3.0.0 + */ + this.originalEvent = undefined; + + /** + * Can this Key be processed? + * + * @name Phaser.Input.Keyboard.Key#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = true; + + /** + * The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * + * @name Phaser.Input.Keyboard.Key#isDown + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isDown = false; + + /** + * The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * + * @name Phaser.Input.Keyboard.Key#isUp + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.isUp = true; + + /** + * The down state of the ALT key, if pressed at the same time as this key. + * + * @name Phaser.Input.Keyboard.Key#altKey + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.altKey = false; + + /** + * The down state of the CTRL key, if pressed at the same time as this key. + * + * @name Phaser.Input.Keyboard.Key#ctrlKey + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.ctrlKey = false; + + /** + * The down state of the SHIFT key, if pressed at the same time as this key. + * + * @name Phaser.Input.Keyboard.Key#shiftKey + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.shiftKey = false; + + /** + * The down state of the Meta key, if pressed at the same time as this key. + * On a Mac the Meta Key is the Command key. On Windows keyboards, it's the Windows key. + * + * @name Phaser.Input.Keyboard.Key#metaKey + * @type {boolean} + * @default false + * @since 3.16.0 + */ + this.metaKey = false; + + /** + * The location of the modifier key. 0 for standard (or unknown), 1 for left, 2 for right, 3 for numpad. + * + * @name Phaser.Input.Keyboard.Key#location + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.location = 0; + + /** + * The timestamp when the key was last pressed down. + * + * @name Phaser.Input.Keyboard.Key#timeDown + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeDown = 0; + + /** + * The number of milliseconds this key was held down for in the previous down - up sequence. + * This value isn't updated every game step, only when the Key changes state. + * To get the current duration use the `getDuration` method. + * + * @name Phaser.Input.Keyboard.Key#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * The timestamp when the key was last released. + * + * @name Phaser.Input.Keyboard.Key#timeUp + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.timeUp = 0; + + /** + * When a key is held down should it continuously fire the `down` event each time it repeats? + * + * By default it will emit the `down` event just once, but if you wish to receive the event + * for each repeat as well, enable this property. + * + * @name Phaser.Input.Keyboard.Key#emitOnRepeat + * @type {boolean} + * @default false + * @since 3.16.0 + */ + this.emitOnRepeat = false; + + /** + * If a key is held down this holds down the number of times the key has 'repeated'. + * + * @name Phaser.Input.Keyboard.Key#repeats + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.repeats = 0; + + /** + * True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * + * @name Phaser.Input.Keyboard.Key#_justDown + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._justDown = false; + + /** + * True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * + * @name Phaser.Input.Keyboard.Key#_justUp + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._justUp = false; + + /** + * Internal tick counter. + * + * @name Phaser.Input.Keyboard.Key#_tick + * @type {number} + * @private + * @since 3.11.0 + */ + this._tick = -1; + }, + + /** + * Controls if this Key will continuously emit a `down` event while being held down (true), + * or emit the event just once, on first press, and then skip future events (false). + * + * @method Phaser.Input.Keyboard.Key#setEmitOnRepeat + * @since 3.16.0 + * + * @param {boolean} value - Emit `down` events on repeated key down actions, or just once? + * + * @return {Phaser.Input.Keyboard.Key} This Key instance. + */ + setEmitOnRepeat: function (value) + { + this.emitOnRepeat = value; + + return this; + }, + + /** + * Processes the Key Down action for this Key. + * Called automatically by the Keyboard Plugin. + * + * @method Phaser.Input.Keyboard.Key#onDown + * @fires Phaser.Input.Keyboard.Events#DOWN + * @since 3.16.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard event. + */ + onDown: function (event) + { + this.originalEvent = event; + + if (!this.enabled) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + this.metaKey = event.metaKey; + this.location = event.location; + + this.repeats++; + + if (!this.isDown) + { + this.isDown = true; + this.isUp = false; + this.timeDown = event.timeStamp; + this.duration = 0; + this._justDown = true; + this._justUp = false; + + this.emit(Events.DOWN, this, event); + } + else if (this.emitOnRepeat) + { + this.emit(Events.DOWN, this, event); + } + }, + + /** + * Processes the Key Up action for this Key. + * Called automatically by the Keyboard Plugin. + * + * @method Phaser.Input.Keyboard.Key#onUp + * @fires Phaser.Input.Keyboard.Events#UP + * @since 3.16.0 + * + * @param {KeyboardEvent} event - The native DOM Keyboard event. + */ + onUp: function (event) + { + this.originalEvent = event; + + if (!this.enabled) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = event.timeStamp; + this.duration = this.timeUp - this.timeDown; + this.repeats = 0; + + this._justDown = false; + this._justUp = true; + this._tick = -1; + + this.emit(Events.UP, this, event); + }, + + /** + * Resets this Key object back to its default un-pressed state. + * + * @method Phaser.Input.Keyboard.Key#reset + * @since 3.6.0 + * + * @return {Phaser.Input.Keyboard.Key} This Key instance. + */ + reset: function () + { + this.preventDefault = true; + this.enabled = true; + this.isDown = false; + this.isUp = true; + this.altKey = false; + this.ctrlKey = false; + this.shiftKey = false; + this.metaKey = false; + this.timeDown = 0; + this.duration = 0; + this.timeUp = 0; + this.repeats = 0; + this._justDown = false; + this._justUp = false; + this._tick = -1; + + return this; + }, + + /** + * Returns the duration, in ms, that the Key has been held down for. + * + * If the key is not currently down it will return zero. + * + * The get the duration the Key was held down for in the previous up-down cycle, + * use the `Key.duration` property value instead. + * + * @method Phaser.Input.Keyboard.Key#getDuration + * @since 3.17.0 + * + * @return {number} The duration, in ms, that the Key has been held down for if currently down. + */ + getDuration: function () + { + if (this.isDown) + { + return (this.plugin.game.loop.time - this.timeDown); + } + else + { + return 0; + } + }, + + /** + * Removes any bound event handlers and removes local references. + * + * @method Phaser.Input.Keyboard.Key#destroy + * @since 3.16.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.originalEvent = null; + + this.plugin = null; + } + +}); + +module.exports = Key; diff --git a/src/input/keyboard/keys/KeyCodes.js b/src/input/keyboard/keys/KeyCodes.js index 1744bef66..599958e03 100644 --- a/src/input/keyboard/keys/KeyCodes.js +++ b/src/input/keyboard/keys/KeyCodes.js @@ -1,900 +1,900 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Keyboard Codes. - * - * @namespace Phaser.Input.Keyboard.KeyCodes - * @memberof Phaser.Input.Keyboard - * @since 3.0.0 - */ - -var KeyCodes = { - - /** - * The BACKSPACE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.BACKSPACE - * @type {integer} - * @since 3.0.0 - */ - BACKSPACE: 8, - - /** - * The TAB key. - * - * @name Phaser.Input.Keyboard.KeyCodes.TAB - * @type {integer} - * @since 3.0.0 - */ - TAB: 9, - - /** - * The ENTER key. - * - * @name Phaser.Input.Keyboard.KeyCodes.ENTER - * @type {integer} - * @since 3.0.0 - */ - ENTER: 13, - - /** - * The SHIFT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.SHIFT - * @type {integer} - * @since 3.0.0 - */ - SHIFT: 16, - - /** - * The CTRL key. - * - * @name Phaser.Input.Keyboard.KeyCodes.CTRL - * @type {integer} - * @since 3.0.0 - */ - CTRL: 17, - - /** - * The ALT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.ALT - * @type {integer} - * @since 3.0.0 - */ - ALT: 18, - - /** - * The PAUSE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.PAUSE - * @type {integer} - * @since 3.0.0 - */ - PAUSE: 19, - - /** - * The CAPS_LOCK key. - * - * @name Phaser.Input.Keyboard.KeyCodes.CAPS_LOCK - * @type {integer} - * @since 3.0.0 - */ - CAPS_LOCK: 20, - - /** - * The ESC key. - * - * @name Phaser.Input.Keyboard.KeyCodes.ESC - * @type {integer} - * @since 3.0.0 - */ - ESC: 27, - - /** - * The SPACE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.SPACE - * @type {integer} - * @since 3.0.0 - */ - SPACE: 32, - - /** - * The PAGE_UP key. - * - * @name Phaser.Input.Keyboard.KeyCodes.PAGE_UP - * @type {integer} - * @since 3.0.0 - */ - PAGE_UP: 33, - - /** - * The PAGE_DOWN key. - * - * @name Phaser.Input.Keyboard.KeyCodes.PAGE_DOWN - * @type {integer} - * @since 3.0.0 - */ - PAGE_DOWN: 34, - - /** - * The END key. - * - * @name Phaser.Input.Keyboard.KeyCodes.END - * @type {integer} - * @since 3.0.0 - */ - END: 35, - - /** - * The HOME key. - * - * @name Phaser.Input.Keyboard.KeyCodes.HOME - * @type {integer} - * @since 3.0.0 - */ - HOME: 36, - - /** - * The LEFT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.LEFT - * @type {integer} - * @since 3.0.0 - */ - LEFT: 37, - - /** - * The UP key. - * - * @name Phaser.Input.Keyboard.KeyCodes.UP - * @type {integer} - * @since 3.0.0 - */ - UP: 38, - - /** - * The RIGHT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.RIGHT - * @type {integer} - * @since 3.0.0 - */ - RIGHT: 39, - - /** - * The DOWN key. - * - * @name Phaser.Input.Keyboard.KeyCodes.DOWN - * @type {integer} - * @since 3.0.0 - */ - DOWN: 40, - - /** - * The PRINT_SCREEN key. - * - * @name Phaser.Input.Keyboard.KeyCodes.PRINT_SCREEN - * @type {integer} - * @since 3.0.0 - */ - PRINT_SCREEN: 42, - - /** - * The INSERT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.INSERT - * @type {integer} - * @since 3.0.0 - */ - INSERT: 45, - - /** - * The DELETE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.DELETE - * @type {integer} - * @since 3.0.0 - */ - DELETE: 46, - - /** - * The ZERO key. - * - * @name Phaser.Input.Keyboard.KeyCodes.ZERO - * @type {integer} - * @since 3.0.0 - */ - ZERO: 48, - - /** - * The ONE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.ONE - * @type {integer} - * @since 3.0.0 - */ - ONE: 49, - - /** - * The TWO key. - * - * @name Phaser.Input.Keyboard.KeyCodes.TWO - * @type {integer} - * @since 3.0.0 - */ - TWO: 50, - - /** - * The THREE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.THREE - * @type {integer} - * @since 3.0.0 - */ - THREE: 51, - - /** - * The FOUR key. - * - * @name Phaser.Input.Keyboard.KeyCodes.FOUR - * @type {integer} - * @since 3.0.0 - */ - FOUR: 52, - - /** - * The FIVE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.FIVE - * @type {integer} - * @since 3.0.0 - */ - FIVE: 53, - - /** - * The SIX key. - * - * @name Phaser.Input.Keyboard.KeyCodes.SIX - * @type {integer} - * @since 3.0.0 - */ - SIX: 54, - - /** - * The SEVEN key. - * - * @name Phaser.Input.Keyboard.KeyCodes.SEVEN - * @type {integer} - * @since 3.0.0 - */ - SEVEN: 55, - - /** - * The EIGHT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.EIGHT - * @type {integer} - * @since 3.0.0 - */ - EIGHT: 56, - - /** - * The NINE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NINE - * @type {integer} - * @since 3.0.0 - */ - NINE: 57, - - /** - * The NUMPAD_ZERO key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ZERO - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_ZERO: 96, - - /** - * The NUMPAD_ONE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ONE - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_ONE: 97, - - /** - * The NUMPAD_TWO key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_TWO - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_TWO: 98, - - /** - * The NUMPAD_THREE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_THREE - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_THREE: 99, - - /** - * The NUMPAD_FOUR key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_FOUR - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_FOUR: 100, - - /** - * The NUMPAD_FIVE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_FIVE - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_FIVE: 101, - - /** - * The NUMPAD_SIX key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SIX - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_SIX: 102, - - /** - * The NUMPAD_SEVEN key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SEVEN - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_SEVEN: 103, - - /** - * The NUMPAD_EIGHT key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_EIGHT - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_EIGHT: 104, - - /** - * The NUMPAD_NINE key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_NINE - * @type {integer} - * @since 3.0.0 - */ - NUMPAD_NINE: 105, - - /** - * The Numpad Addition (+) key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ADD - * @type {integer} - * @since 3.21.0 - */ - NUMPAD_ADD: 107, - - /** - * The Numpad Subtraction (-) key. - * - * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SUBTRACT - * @type {integer} - * @since 3.21.0 - */ - NUMPAD_SUBTRACT: 109, - - /** - * The A key. - * - * @name Phaser.Input.Keyboard.KeyCodes.A - * @type {integer} - * @since 3.0.0 - */ - A: 65, - - /** - * The B key. - * - * @name Phaser.Input.Keyboard.KeyCodes.B - * @type {integer} - * @since 3.0.0 - */ - B: 66, - - /** - * The C key. - * - * @name Phaser.Input.Keyboard.KeyCodes.C - * @type {integer} - * @since 3.0.0 - */ - C: 67, - - /** - * The D key. - * - * @name Phaser.Input.Keyboard.KeyCodes.D - * @type {integer} - * @since 3.0.0 - */ - D: 68, - - /** - * The E key. - * - * @name Phaser.Input.Keyboard.KeyCodes.E - * @type {integer} - * @since 3.0.0 - */ - E: 69, - - /** - * The F key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F - * @type {integer} - * @since 3.0.0 - */ - F: 70, - - /** - * The G key. - * - * @name Phaser.Input.Keyboard.KeyCodes.G - * @type {integer} - * @since 3.0.0 - */ - G: 71, - - /** - * The H key. - * - * @name Phaser.Input.Keyboard.KeyCodes.H - * @type {integer} - * @since 3.0.0 - */ - H: 72, - - /** - * The I key. - * - * @name Phaser.Input.Keyboard.KeyCodes.I - * @type {integer} - * @since 3.0.0 - */ - I: 73, - - /** - * The J key. - * - * @name Phaser.Input.Keyboard.KeyCodes.J - * @type {integer} - * @since 3.0.0 - */ - J: 74, - - /** - * The K key. - * - * @name Phaser.Input.Keyboard.KeyCodes.K - * @type {integer} - * @since 3.0.0 - */ - K: 75, - - /** - * The L key. - * - * @name Phaser.Input.Keyboard.KeyCodes.L - * @type {integer} - * @since 3.0.0 - */ - L: 76, - - /** - * The M key. - * - * @name Phaser.Input.Keyboard.KeyCodes.M - * @type {integer} - * @since 3.0.0 - */ - M: 77, - - /** - * The N key. - * - * @name Phaser.Input.Keyboard.KeyCodes.N - * @type {integer} - * @since 3.0.0 - */ - N: 78, - - /** - * The O key. - * - * @name Phaser.Input.Keyboard.KeyCodes.O - * @type {integer} - * @since 3.0.0 - */ - O: 79, - - /** - * The P key. - * - * @name Phaser.Input.Keyboard.KeyCodes.P - * @type {integer} - * @since 3.0.0 - */ - P: 80, - - /** - * The Q key. - * - * @name Phaser.Input.Keyboard.KeyCodes.Q - * @type {integer} - * @since 3.0.0 - */ - Q: 81, - - /** - * The R key. - * - * @name Phaser.Input.Keyboard.KeyCodes.R - * @type {integer} - * @since 3.0.0 - */ - R: 82, - - /** - * The S key. - * - * @name Phaser.Input.Keyboard.KeyCodes.S - * @type {integer} - * @since 3.0.0 - */ - S: 83, - - /** - * The T key. - * - * @name Phaser.Input.Keyboard.KeyCodes.T - * @type {integer} - * @since 3.0.0 - */ - T: 84, - - /** - * The U key. - * - * @name Phaser.Input.Keyboard.KeyCodes.U - * @type {integer} - * @since 3.0.0 - */ - U: 85, - - /** - * The V key. - * - * @name Phaser.Input.Keyboard.KeyCodes.V - * @type {integer} - * @since 3.0.0 - */ - V: 86, - - /** - * The W key. - * - * @name Phaser.Input.Keyboard.KeyCodes.W - * @type {integer} - * @since 3.0.0 - */ - W: 87, - - /** - * The X key. - * - * @name Phaser.Input.Keyboard.KeyCodes.X - * @type {integer} - * @since 3.0.0 - */ - X: 88, - - /** - * The Y key. - * - * @name Phaser.Input.Keyboard.KeyCodes.Y - * @type {integer} - * @since 3.0.0 - */ - Y: 89, - - /** - * The Z key. - * - * @name Phaser.Input.Keyboard.KeyCodes.Z - * @type {integer} - * @since 3.0.0 - */ - Z: 90, - - /** - * The F1 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F1 - * @type {integer} - * @since 3.0.0 - */ - F1: 112, - - /** - * The F2 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F2 - * @type {integer} - * @since 3.0.0 - */ - F2: 113, - - /** - * The F3 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F3 - * @type {integer} - * @since 3.0.0 - */ - F3: 114, - - /** - * The F4 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F4 - * @type {integer} - * @since 3.0.0 - */ - F4: 115, - - /** - * The F5 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F5 - * @type {integer} - * @since 3.0.0 - */ - F5: 116, - - /** - * The F6 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F6 - * @type {integer} - * @since 3.0.0 - */ - F6: 117, - - /** - * The F7 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F7 - * @type {integer} - * @since 3.0.0 - */ - F7: 118, - - /** - * The F8 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F8 - * @type {integer} - * @since 3.0.0 - */ - F8: 119, - - /** - * The F9 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F9 - * @type {integer} - * @since 3.0.0 - */ - F9: 120, - - /** - * The F10 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F10 - * @type {integer} - * @since 3.0.0 - */ - F10: 121, - - /** - * The F11 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F11 - * @type {integer} - * @since 3.0.0 - */ - F11: 122, - - /** - * The F12 key. - * - * @name Phaser.Input.Keyboard.KeyCodes.F12 - * @type {integer} - * @since 3.0.0 - */ - F12: 123, - - /** - * The SEMICOLON key. - * - * @name Phaser.Input.Keyboard.KeyCodes.SEMICOLON - * @type {integer} - * @since 3.0.0 - */ - SEMICOLON: 186, - - /** - * The PLUS key. - * - * @name Phaser.Input.Keyboard.KeyCodes.PLUS - * @type {integer} - * @since 3.0.0 - */ - PLUS: 187, - - /** - * The COMMA key. - * - * @name Phaser.Input.Keyboard.KeyCodes.COMMA - * @type {integer} - * @since 3.0.0 - */ - COMMA: 188, - - /** - * The MINUS key. - * - * @name Phaser.Input.Keyboard.KeyCodes.MINUS - * @type {integer} - * @since 3.0.0 - */ - MINUS: 189, - - /** - * The PERIOD key. - * - * @name Phaser.Input.Keyboard.KeyCodes.PERIOD - * @type {integer} - * @since 3.0.0 - */ - PERIOD: 190, - - /** - * The FORWARD_SLASH key. - * - * @name Phaser.Input.Keyboard.KeyCodes.FORWARD_SLASH - * @type {integer} - * @since 3.0.0 - */ - FORWARD_SLASH: 191, - - /** - * The BACK_SLASH key. - * - * @name Phaser.Input.Keyboard.KeyCodes.BACK_SLASH - * @type {integer} - * @since 3.0.0 - */ - BACK_SLASH: 220, - - /** - * The QUOTES key. - * - * @name Phaser.Input.Keyboard.KeyCodes.QUOTES - * @type {integer} - * @since 3.0.0 - */ - QUOTES: 222, - - /** - * The BACKTICK key. - * - * @name Phaser.Input.Keyboard.KeyCodes.BACKTICK - * @type {integer} - * @since 3.0.0 - */ - BACKTICK: 192, - - /** - * The OPEN_BRACKET key. - * - * @name Phaser.Input.Keyboard.KeyCodes.OPEN_BRACKET - * @type {integer} - * @since 3.0.0 - */ - OPEN_BRACKET: 219, - - /** - * The CLOSED_BRACKET key. - * - * @name Phaser.Input.Keyboard.KeyCodes.CLOSED_BRACKET - * @type {integer} - * @since 3.0.0 - */ - CLOSED_BRACKET: 221, - - /** - * The SEMICOLON_FIREFOX key. - * - * @name Phaser.Input.Keyboard.KeyCodes.SEMICOLON_FIREFOX - * @type {integer} - * @since 3.0.0 - */ - SEMICOLON_FIREFOX: 59, - - /** - * The COLON key. - * - * @name Phaser.Input.Keyboard.KeyCodes.COLON - * @type {integer} - * @since 3.0.0 - */ - COLON: 58, - - /** - * The COMMA_FIREFOX_WINDOWS key. - * - * @name Phaser.Input.Keyboard.KeyCodes.COMMA_FIREFOX_WINDOWS - * @type {integer} - * @since 3.0.0 - */ - COMMA_FIREFOX_WINDOWS: 60, - - /** - * The COMMA_FIREFOX key. - * - * @name Phaser.Input.Keyboard.KeyCodes.COMMA_FIREFOX - * @type {integer} - * @since 3.0.0 - */ - COMMA_FIREFOX: 62, - - /** - * The BRACKET_RIGHT_FIREFOX key. - * - * @name Phaser.Input.Keyboard.KeyCodes.BRACKET_RIGHT_FIREFOX - * @type {integer} - * @since 3.0.0 - */ - BRACKET_RIGHT_FIREFOX: 174, - - /** - * The BRACKET_LEFT_FIREFOX key. - * - * @name Phaser.Input.Keyboard.KeyCodes.BRACKET_LEFT_FIREFOX - * @type {integer} - * @since 3.0.0 - */ - BRACKET_LEFT_FIREFOX: 175 -}; - -module.exports = KeyCodes; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Keyboard Codes. + * + * @namespace Phaser.Input.Keyboard.KeyCodes + * @memberof Phaser.Input.Keyboard + * @since 3.0.0 + */ + +var KeyCodes = { + + /** + * The BACKSPACE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BACKSPACE + * @type {integer} + * @since 3.0.0 + */ + BACKSPACE: 8, + + /** + * The TAB key. + * + * @name Phaser.Input.Keyboard.KeyCodes.TAB + * @type {integer} + * @since 3.0.0 + */ + TAB: 9, + + /** + * The ENTER key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ENTER + * @type {integer} + * @since 3.0.0 + */ + ENTER: 13, + + /** + * The SHIFT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SHIFT + * @type {integer} + * @since 3.0.0 + */ + SHIFT: 16, + + /** + * The CTRL key. + * + * @name Phaser.Input.Keyboard.KeyCodes.CTRL + * @type {integer} + * @since 3.0.0 + */ + CTRL: 17, + + /** + * The ALT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ALT + * @type {integer} + * @since 3.0.0 + */ + ALT: 18, + + /** + * The PAUSE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PAUSE + * @type {integer} + * @since 3.0.0 + */ + PAUSE: 19, + + /** + * The CAPS_LOCK key. + * + * @name Phaser.Input.Keyboard.KeyCodes.CAPS_LOCK + * @type {integer} + * @since 3.0.0 + */ + CAPS_LOCK: 20, + + /** + * The ESC key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ESC + * @type {integer} + * @since 3.0.0 + */ + ESC: 27, + + /** + * The SPACE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SPACE + * @type {integer} + * @since 3.0.0 + */ + SPACE: 32, + + /** + * The PAGE_UP key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PAGE_UP + * @type {integer} + * @since 3.0.0 + */ + PAGE_UP: 33, + + /** + * The PAGE_DOWN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PAGE_DOWN + * @type {integer} + * @since 3.0.0 + */ + PAGE_DOWN: 34, + + /** + * The END key. + * + * @name Phaser.Input.Keyboard.KeyCodes.END + * @type {integer} + * @since 3.0.0 + */ + END: 35, + + /** + * The HOME key. + * + * @name Phaser.Input.Keyboard.KeyCodes.HOME + * @type {integer} + * @since 3.0.0 + */ + HOME: 36, + + /** + * The LEFT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.LEFT + * @type {integer} + * @since 3.0.0 + */ + LEFT: 37, + + /** + * The UP key. + * + * @name Phaser.Input.Keyboard.KeyCodes.UP + * @type {integer} + * @since 3.0.0 + */ + UP: 38, + + /** + * The RIGHT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.RIGHT + * @type {integer} + * @since 3.0.0 + */ + RIGHT: 39, + + /** + * The DOWN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.DOWN + * @type {integer} + * @since 3.0.0 + */ + DOWN: 40, + + /** + * The PRINT_SCREEN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PRINT_SCREEN + * @type {integer} + * @since 3.0.0 + */ + PRINT_SCREEN: 42, + + /** + * The INSERT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.INSERT + * @type {integer} + * @since 3.0.0 + */ + INSERT: 45, + + /** + * The DELETE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.DELETE + * @type {integer} + * @since 3.0.0 + */ + DELETE: 46, + + /** + * The ZERO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ZERO + * @type {integer} + * @since 3.0.0 + */ + ZERO: 48, + + /** + * The ONE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.ONE + * @type {integer} + * @since 3.0.0 + */ + ONE: 49, + + /** + * The TWO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.TWO + * @type {integer} + * @since 3.0.0 + */ + TWO: 50, + + /** + * The THREE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.THREE + * @type {integer} + * @since 3.0.0 + */ + THREE: 51, + + /** + * The FOUR key. + * + * @name Phaser.Input.Keyboard.KeyCodes.FOUR + * @type {integer} + * @since 3.0.0 + */ + FOUR: 52, + + /** + * The FIVE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.FIVE + * @type {integer} + * @since 3.0.0 + */ + FIVE: 53, + + /** + * The SIX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SIX + * @type {integer} + * @since 3.0.0 + */ + SIX: 54, + + /** + * The SEVEN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SEVEN + * @type {integer} + * @since 3.0.0 + */ + SEVEN: 55, + + /** + * The EIGHT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.EIGHT + * @type {integer} + * @since 3.0.0 + */ + EIGHT: 56, + + /** + * The NINE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NINE + * @type {integer} + * @since 3.0.0 + */ + NINE: 57, + + /** + * The NUMPAD_ZERO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ZERO + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_ZERO: 96, + + /** + * The NUMPAD_ONE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ONE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_ONE: 97, + + /** + * The NUMPAD_TWO key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_TWO + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_TWO: 98, + + /** + * The NUMPAD_THREE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_THREE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_THREE: 99, + + /** + * The NUMPAD_FOUR key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_FOUR + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_FOUR: 100, + + /** + * The NUMPAD_FIVE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_FIVE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_FIVE: 101, + + /** + * The NUMPAD_SIX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SIX + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_SIX: 102, + + /** + * The NUMPAD_SEVEN key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SEVEN + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_SEVEN: 103, + + /** + * The NUMPAD_EIGHT key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_EIGHT + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_EIGHT: 104, + + /** + * The NUMPAD_NINE key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_NINE + * @type {integer} + * @since 3.0.0 + */ + NUMPAD_NINE: 105, + + /** + * The Numpad Addition (+) key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_ADD + * @type {integer} + * @since 3.21.0 + */ + NUMPAD_ADD: 107, + + /** + * The Numpad Subtraction (-) key. + * + * @name Phaser.Input.Keyboard.KeyCodes.NUMPAD_SUBTRACT + * @type {integer} + * @since 3.21.0 + */ + NUMPAD_SUBTRACT: 109, + + /** + * The A key. + * + * @name Phaser.Input.Keyboard.KeyCodes.A + * @type {integer} + * @since 3.0.0 + */ + A: 65, + + /** + * The B key. + * + * @name Phaser.Input.Keyboard.KeyCodes.B + * @type {integer} + * @since 3.0.0 + */ + B: 66, + + /** + * The C key. + * + * @name Phaser.Input.Keyboard.KeyCodes.C + * @type {integer} + * @since 3.0.0 + */ + C: 67, + + /** + * The D key. + * + * @name Phaser.Input.Keyboard.KeyCodes.D + * @type {integer} + * @since 3.0.0 + */ + D: 68, + + /** + * The E key. + * + * @name Phaser.Input.Keyboard.KeyCodes.E + * @type {integer} + * @since 3.0.0 + */ + E: 69, + + /** + * The F key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F + * @type {integer} + * @since 3.0.0 + */ + F: 70, + + /** + * The G key. + * + * @name Phaser.Input.Keyboard.KeyCodes.G + * @type {integer} + * @since 3.0.0 + */ + G: 71, + + /** + * The H key. + * + * @name Phaser.Input.Keyboard.KeyCodes.H + * @type {integer} + * @since 3.0.0 + */ + H: 72, + + /** + * The I key. + * + * @name Phaser.Input.Keyboard.KeyCodes.I + * @type {integer} + * @since 3.0.0 + */ + I: 73, + + /** + * The J key. + * + * @name Phaser.Input.Keyboard.KeyCodes.J + * @type {integer} + * @since 3.0.0 + */ + J: 74, + + /** + * The K key. + * + * @name Phaser.Input.Keyboard.KeyCodes.K + * @type {integer} + * @since 3.0.0 + */ + K: 75, + + /** + * The L key. + * + * @name Phaser.Input.Keyboard.KeyCodes.L + * @type {integer} + * @since 3.0.0 + */ + L: 76, + + /** + * The M key. + * + * @name Phaser.Input.Keyboard.KeyCodes.M + * @type {integer} + * @since 3.0.0 + */ + M: 77, + + /** + * The N key. + * + * @name Phaser.Input.Keyboard.KeyCodes.N + * @type {integer} + * @since 3.0.0 + */ + N: 78, + + /** + * The O key. + * + * @name Phaser.Input.Keyboard.KeyCodes.O + * @type {integer} + * @since 3.0.0 + */ + O: 79, + + /** + * The P key. + * + * @name Phaser.Input.Keyboard.KeyCodes.P + * @type {integer} + * @since 3.0.0 + */ + P: 80, + + /** + * The Q key. + * + * @name Phaser.Input.Keyboard.KeyCodes.Q + * @type {integer} + * @since 3.0.0 + */ + Q: 81, + + /** + * The R key. + * + * @name Phaser.Input.Keyboard.KeyCodes.R + * @type {integer} + * @since 3.0.0 + */ + R: 82, + + /** + * The S key. + * + * @name Phaser.Input.Keyboard.KeyCodes.S + * @type {integer} + * @since 3.0.0 + */ + S: 83, + + /** + * The T key. + * + * @name Phaser.Input.Keyboard.KeyCodes.T + * @type {integer} + * @since 3.0.0 + */ + T: 84, + + /** + * The U key. + * + * @name Phaser.Input.Keyboard.KeyCodes.U + * @type {integer} + * @since 3.0.0 + */ + U: 85, + + /** + * The V key. + * + * @name Phaser.Input.Keyboard.KeyCodes.V + * @type {integer} + * @since 3.0.0 + */ + V: 86, + + /** + * The W key. + * + * @name Phaser.Input.Keyboard.KeyCodes.W + * @type {integer} + * @since 3.0.0 + */ + W: 87, + + /** + * The X key. + * + * @name Phaser.Input.Keyboard.KeyCodes.X + * @type {integer} + * @since 3.0.0 + */ + X: 88, + + /** + * The Y key. + * + * @name Phaser.Input.Keyboard.KeyCodes.Y + * @type {integer} + * @since 3.0.0 + */ + Y: 89, + + /** + * The Z key. + * + * @name Phaser.Input.Keyboard.KeyCodes.Z + * @type {integer} + * @since 3.0.0 + */ + Z: 90, + + /** + * The F1 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F1 + * @type {integer} + * @since 3.0.0 + */ + F1: 112, + + /** + * The F2 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F2 + * @type {integer} + * @since 3.0.0 + */ + F2: 113, + + /** + * The F3 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F3 + * @type {integer} + * @since 3.0.0 + */ + F3: 114, + + /** + * The F4 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F4 + * @type {integer} + * @since 3.0.0 + */ + F4: 115, + + /** + * The F5 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F5 + * @type {integer} + * @since 3.0.0 + */ + F5: 116, + + /** + * The F6 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F6 + * @type {integer} + * @since 3.0.0 + */ + F6: 117, + + /** + * The F7 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F7 + * @type {integer} + * @since 3.0.0 + */ + F7: 118, + + /** + * The F8 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F8 + * @type {integer} + * @since 3.0.0 + */ + F8: 119, + + /** + * The F9 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F9 + * @type {integer} + * @since 3.0.0 + */ + F9: 120, + + /** + * The F10 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F10 + * @type {integer} + * @since 3.0.0 + */ + F10: 121, + + /** + * The F11 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F11 + * @type {integer} + * @since 3.0.0 + */ + F11: 122, + + /** + * The F12 key. + * + * @name Phaser.Input.Keyboard.KeyCodes.F12 + * @type {integer} + * @since 3.0.0 + */ + F12: 123, + + /** + * The SEMICOLON key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SEMICOLON + * @type {integer} + * @since 3.0.0 + */ + SEMICOLON: 186, + + /** + * The PLUS key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PLUS + * @type {integer} + * @since 3.0.0 + */ + PLUS: 187, + + /** + * The COMMA key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COMMA + * @type {integer} + * @since 3.0.0 + */ + COMMA: 188, + + /** + * The MINUS key. + * + * @name Phaser.Input.Keyboard.KeyCodes.MINUS + * @type {integer} + * @since 3.0.0 + */ + MINUS: 189, + + /** + * The PERIOD key. + * + * @name Phaser.Input.Keyboard.KeyCodes.PERIOD + * @type {integer} + * @since 3.0.0 + */ + PERIOD: 190, + + /** + * The FORWARD_SLASH key. + * + * @name Phaser.Input.Keyboard.KeyCodes.FORWARD_SLASH + * @type {integer} + * @since 3.0.0 + */ + FORWARD_SLASH: 191, + + /** + * The BACK_SLASH key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BACK_SLASH + * @type {integer} + * @since 3.0.0 + */ + BACK_SLASH: 220, + + /** + * The QUOTES key. + * + * @name Phaser.Input.Keyboard.KeyCodes.QUOTES + * @type {integer} + * @since 3.0.0 + */ + QUOTES: 222, + + /** + * The BACKTICK key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BACKTICK + * @type {integer} + * @since 3.0.0 + */ + BACKTICK: 192, + + /** + * The OPEN_BRACKET key. + * + * @name Phaser.Input.Keyboard.KeyCodes.OPEN_BRACKET + * @type {integer} + * @since 3.0.0 + */ + OPEN_BRACKET: 219, + + /** + * The CLOSED_BRACKET key. + * + * @name Phaser.Input.Keyboard.KeyCodes.CLOSED_BRACKET + * @type {integer} + * @since 3.0.0 + */ + CLOSED_BRACKET: 221, + + /** + * The SEMICOLON_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.SEMICOLON_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + SEMICOLON_FIREFOX: 59, + + /** + * The COLON key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COLON + * @type {integer} + * @since 3.0.0 + */ + COLON: 58, + + /** + * The COMMA_FIREFOX_WINDOWS key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COMMA_FIREFOX_WINDOWS + * @type {integer} + * @since 3.0.0 + */ + COMMA_FIREFOX_WINDOWS: 60, + + /** + * The COMMA_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.COMMA_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + COMMA_FIREFOX: 62, + + /** + * The BRACKET_RIGHT_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BRACKET_RIGHT_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + BRACKET_RIGHT_FIREFOX: 174, + + /** + * The BRACKET_LEFT_FIREFOX key. + * + * @name Phaser.Input.Keyboard.KeyCodes.BRACKET_LEFT_FIREFOX + * @type {integer} + * @since 3.0.0 + */ + BRACKET_LEFT_FIREFOX: 175 +}; + +module.exports = KeyCodes; diff --git a/src/input/keyboard/keys/KeyMap.js b/src/input/keyboard/keys/KeyMap.js index 3f90e0816..a7800e52d 100644 --- a/src/input/keyboard/keys/KeyMap.js +++ b/src/input/keyboard/keys/KeyMap.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var KeyCodes = require('./KeyCodes'); - -var KeyMap = {}; - -for (var key in KeyCodes) -{ - KeyMap[KeyCodes[key]] = key; -} - -module.exports = KeyMap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var KeyCodes = require('./KeyCodes'); + +var KeyMap = {}; + +for (var key in KeyCodes) +{ + KeyMap[KeyCodes[key]] = key; +} + +module.exports = KeyMap; diff --git a/src/input/keyboard/keys/UpDuration.js b/src/input/keyboard/keys/UpDuration.js index edb402c83..f74f0a924 100644 --- a/src/input/keyboard/keys/UpDuration.js +++ b/src/input/keyboard/keys/UpDuration.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 {integer} [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`. - */ -var UpDuration = function (key, duration) -{ - if (duration === undefined) { duration = 50; } - - var current = key.plugin.game.loop.time - key.timeUp; - - return (key.isUp && current < duration); -}; - -module.exports = UpDuration; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} [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`. + */ +var UpDuration = function (key, duration) +{ + if (duration === undefined) { duration = 50; } + + var current = key.plugin.game.loop.time - key.timeUp; + + return (key.isUp && current < duration); +}; + +module.exports = UpDuration; diff --git a/src/input/keyboard/typedefs/index.js b/src/input/keyboard/typedefs/index.js index 159297c1b..195d968bc 100644 --- a/src/input/keyboard/typedefs/index.js +++ b/src/input/keyboard/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Input.Keyboard - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Input.Keyboard + */ diff --git a/src/input/mouse/MouseManager.js b/src/input/mouse/MouseManager.js index eb5f7e0b7..924d92eb1 100644 --- a/src/input/mouse/MouseManager.js +++ b/src/input/mouse/MouseManager.js @@ -1,480 +1,480 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Features = require('../../device/Features'); -var InputEvents = require('../events'); -var NOOP = require('../../utils/Class'); - -// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent -// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md - -/** - * @classdesc - * The Mouse Manager is a helper class that belongs to the Input Manager. - * - * Its role is to listen for native DOM Mouse Events and then pass them onto the Input Manager for further processing. - * - * You do not need to create this class directly, the Input Manager will create an instance of it automatically. - * - * @class MouseManager - * @memberof Phaser.Input.Mouse - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. - */ -var MouseManager = new Class({ - - initialize: - - function MouseManager (inputManager) - { - /** - * A reference to the Input Manager. - * - * @name Phaser.Input.Mouse.MouseManager#manager - * @type {Phaser.Input.InputManager} - * @since 3.0.0 - */ - this.manager = inputManager; - - /** - * If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. - * - * @name Phaser.Input.Mouse.MouseManager#capture - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.capture = true; - - /** - * A boolean that controls if the Mouse Manager is enabled or not. - * Can be toggled on the fly. - * - * @name Phaser.Input.Mouse.MouseManager#enabled - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.enabled = false; - - /** - * The Mouse target, as defined in the Game Config. - * Typically the canvas to which the game is rendering, but can be any interactive DOM element. - * - * @name Phaser.Input.Mouse.MouseManager#target - * @type {any} - * @since 3.0.0 - */ - this.target; - - /** - * If the mouse has been pointer locked successfully this will be set to true. - * - * @name Phaser.Input.Mouse.MouseManager#locked - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.locked = false; - - /** - * The Mouse Move Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseMove - * @type {function} - * @since 3.10.0 - */ - this.onMouseMove = NOOP; - - /** - * The Mouse Down Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseDown - * @type {function} - * @since 3.10.0 - */ - this.onMouseDown = NOOP; - - /** - * The Mouse Up Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseUp - * @type {function} - * @since 3.10.0 - */ - this.onMouseUp = NOOP; - - /** - * The Mouse Down Event handler specifically for events on the Window. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseDownWindow - * @type {function} - * @since 3.17.0 - */ - this.onMouseDownWindow = NOOP; - - /** - * The Mouse Up Event handler specifically for events on the Window. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseUpWindow - * @type {function} - * @since 3.17.0 - */ - this.onMouseUpWindow = NOOP; - - /** - * The Mouse Over Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseOver - * @type {function} - * @since 3.16.0 - */ - this.onMouseOver = NOOP; - - /** - * The Mouse Out Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseOut - * @type {function} - * @since 3.16.0 - */ - this.onMouseOut = NOOP; - - /** - * The Mouse Wheel Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#onMouseWheel - * @type {function} - * @since 3.18.0 - */ - this.onMouseWheel = NOOP; - - /** - * Internal pointerLockChange handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Mouse.MouseManager#pointerLockChange - * @type {function} - * @since 3.0.0 - */ - this.pointerLockChange = NOOP; - - inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); - }, - - /** - * The Touch Manager boot process. - * - * @method Phaser.Input.Mouse.MouseManager#boot - * @private - * @since 3.0.0 - */ - boot: function () - { - var config = this.manager.config; - - this.enabled = config.inputMouse; - this.target = config.inputMouseEventTarget; - this.capture = config.inputMouseCapture; - - if (!this.target) - { - this.target = this.manager.game.canvas; - } - else if (typeof this.target === 'string') - { - this.target = document.getElementById(this.target); - } - - if (config.disableContextMenu) - { - this.disableContextMenu(); - } - - if (this.enabled && this.target) - { - this.startListeners(); - } - }, - - /** - * Attempts to disable the context menu from appearing if you right-click on the browser. - * - * Works by listening for the `contextmenu` event and prevent defaulting it. - * - * Use this if you need to enable right-button mouse support in your game, and the browser - * menu keeps getting in the way. - * - * @method Phaser.Input.Mouse.MouseManager#disableContextMenu - * @since 3.0.0 - * - * @return {Phaser.Input.Mouse.MouseManager} This Mouse Manager instance. - */ - disableContextMenu: function () - { - document.body.addEventListener('contextmenu', function (event) - { - event.preventDefault(); - return false; - }); - - return this; - }, - - /** - * 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. - * - * @method Phaser.Input.Mouse.MouseManager#requestPointerLock - * @since 3.0.0 - */ - requestPointerLock: function () - { - if (Features.pointerLock) - { - var element = this.target; - - element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; - - element.requestPointerLock(); - } - }, - - /** - * If the browser supports pointer lock, this will request that the pointer lock is released. If - * the browser successfully enters a locked state, a 'POINTER_LOCK_CHANGE_EVENT' will be - * dispatched - from the game's input manager - with an `isPointerLocked` property. - * - * @method Phaser.Input.Mouse.MouseManager#releasePointerLock - * @since 3.0.0 - */ - releasePointerLock: function () - { - if (Features.pointerLock) - { - document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; - document.exitPointerLock(); - } - }, - - /** - * Starts the Mouse Event listeners running. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Mouse.MouseManager#startListeners - * @since 3.0.0 - */ - startListeners: function () - { - var _this = this; - var canvas = this.manager.canvas; - var autoFocus = (window && window.focus && this.manager.game.config.autoFocus); - - this.onMouseMove = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onMouseMove(event); - - if (_this.capture) - { - event.preventDefault(); - } - } - }; - - this.onMouseDown = function (event) - { - if (autoFocus) - { - window.focus(); - } - - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onMouseDown(event); - - if (_this.capture && event.target === canvas) - { - event.preventDefault(); - } - } - }; - - this.onMouseDownWindow = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) - { - // Only process the event if the target isn't the canvas - _this.manager.onMouseDown(event); - } - }; - - this.onMouseUp = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onMouseUp(event); - - if (_this.capture && event.target === canvas) - { - event.preventDefault(); - } - } - }; - - this.onMouseUpWindow = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) - { - // Only process the event if the target isn't the canvas - _this.manager.onMouseUp(event); - } - }; - - this.onMouseOver = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.setCanvasOver(event); - } - }; - - this.onMouseOut = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.setCanvasOut(event); - } - }; - - this.onMouseWheel = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onMouseWheel(event); - } - }; - - var target = this.target; - - if (!target) - { - return; - } - - var passive = { passive: true }; - var nonPassive = { passive: false }; - - target.addEventListener('mousemove', this.onMouseMove, (this.capture) ? nonPassive : passive); - target.addEventListener('mousedown', this.onMouseDown, (this.capture) ? nonPassive : passive); - target.addEventListener('mouseup', this.onMouseUp, (this.capture) ? nonPassive : passive); - target.addEventListener('mouseover', this.onMouseOver, (this.capture) ? nonPassive : passive); - target.addEventListener('mouseout', this.onMouseOut, (this.capture) ? nonPassive : passive); - target.addEventListener('wheel', this.onMouseWheel, (this.capture) ? nonPassive : passive); - - if (window && this.manager.game.config.inputWindowEvents) - { - window.addEventListener('mousedown', this.onMouseDownWindow, nonPassive); - window.addEventListener('mouseup', this.onMouseUpWindow, nonPassive); - } - - if (Features.pointerLock) - { - this.pointerLockChange = function (event) - { - var element = _this.target; - - _this.locked = (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) ? true : false; - - _this.manager.onPointerLockChange(event); - }; - - document.addEventListener('pointerlockchange', this.pointerLockChange, true); - document.addEventListener('mozpointerlockchange', this.pointerLockChange, true); - document.addEventListener('webkitpointerlockchange', this.pointerLockChange, true); - } - - this.enabled = true; - }, - - /** - * Stops the Mouse Event listeners. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Mouse.MouseManager#stopListeners - * @since 3.0.0 - */ - stopListeners: function () - { - var target = this.target; - - target.removeEventListener('mousemove', this.onMouseMove); - target.removeEventListener('mousedown', this.onMouseDown); - target.removeEventListener('mouseup', this.onMouseUp); - target.removeEventListener('mouseover', this.onMouseOver); - target.removeEventListener('mouseout', this.onMouseOut); - - if (window) - { - window.removeEventListener('mousedown', this.onMouseDownWindow); - window.removeEventListener('mouseup', this.onMouseUpWindow); - } - - if (Features.pointerLock) - { - document.removeEventListener('pointerlockchange', this.pointerLockChange, true); - document.removeEventListener('mozpointerlockchange', this.pointerLockChange, true); - document.removeEventListener('webkitpointerlockchange', this.pointerLockChange, true); - } - }, - - /** - * Destroys this Mouse Manager instance. - * - * @method Phaser.Input.Mouse.MouseManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.stopListeners(); - - this.target = null; - this.enabled = false; - this.manager = null; - } - -}); - -module.exports = MouseManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Features = require('../../device/Features'); +var InputEvents = require('../events'); +var NOOP = require('../../utils/Class'); + +// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent +// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md + +/** + * @classdesc + * The Mouse Manager is a helper class that belongs to the Input Manager. + * + * Its role is to listen for native DOM Mouse Events and then pass them onto the Input Manager for further processing. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically. + * + * @class MouseManager + * @memberof Phaser.Input.Mouse + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. + */ +var MouseManager = new Class({ + + initialize: + + function MouseManager (inputManager) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Mouse.MouseManager#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = inputManager; + + /** + * If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + * + * @name Phaser.Input.Mouse.MouseManager#capture + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.capture = true; + + /** + * A boolean that controls if the Mouse Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Mouse.MouseManager#enabled + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.enabled = false; + + /** + * The Mouse target, as defined in the Game Config. + * Typically the canvas to which the game is rendering, but can be any interactive DOM element. + * + * @name Phaser.Input.Mouse.MouseManager#target + * @type {any} + * @since 3.0.0 + */ + this.target; + + /** + * If the mouse has been pointer locked successfully this will be set to true. + * + * @name Phaser.Input.Mouse.MouseManager#locked + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.locked = false; + + /** + * The Mouse Move Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseMove + * @type {function} + * @since 3.10.0 + */ + this.onMouseMove = NOOP; + + /** + * The Mouse Down Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseDown + * @type {function} + * @since 3.10.0 + */ + this.onMouseDown = NOOP; + + /** + * The Mouse Up Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseUp + * @type {function} + * @since 3.10.0 + */ + this.onMouseUp = NOOP; + + /** + * The Mouse Down Event handler specifically for events on the Window. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseDownWindow + * @type {function} + * @since 3.17.0 + */ + this.onMouseDownWindow = NOOP; + + /** + * The Mouse Up Event handler specifically for events on the Window. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseUpWindow + * @type {function} + * @since 3.17.0 + */ + this.onMouseUpWindow = NOOP; + + /** + * The Mouse Over Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseOver + * @type {function} + * @since 3.16.0 + */ + this.onMouseOver = NOOP; + + /** + * The Mouse Out Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseOut + * @type {function} + * @since 3.16.0 + */ + this.onMouseOut = NOOP; + + /** + * The Mouse Wheel Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#onMouseWheel + * @type {function} + * @since 3.18.0 + */ + this.onMouseWheel = NOOP; + + /** + * Internal pointerLockChange handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Mouse.MouseManager#pointerLockChange + * @type {function} + * @since 3.0.0 + */ + this.pointerLockChange = NOOP; + + inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); + }, + + /** + * The Touch Manager boot process. + * + * @method Phaser.Input.Mouse.MouseManager#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + var config = this.manager.config; + + this.enabled = config.inputMouse; + this.target = config.inputMouseEventTarget; + this.capture = config.inputMouseCapture; + + if (!this.target) + { + this.target = this.manager.game.canvas; + } + else if (typeof this.target === 'string') + { + this.target = document.getElementById(this.target); + } + + if (config.disableContextMenu) + { + this.disableContextMenu(); + } + + if (this.enabled && this.target) + { + this.startListeners(); + } + }, + + /** + * Attempts to disable the context menu from appearing if you right-click on the browser. + * + * Works by listening for the `contextmenu` event and prevent defaulting it. + * + * Use this if you need to enable right-button mouse support in your game, and the browser + * menu keeps getting in the way. + * + * @method Phaser.Input.Mouse.MouseManager#disableContextMenu + * @since 3.0.0 + * + * @return {Phaser.Input.Mouse.MouseManager} This Mouse Manager instance. + */ + disableContextMenu: function () + { + document.body.addEventListener('contextmenu', function (event) + { + event.preventDefault(); + return false; + }); + + return this; + }, + + /** + * 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. + * + * @method Phaser.Input.Mouse.MouseManager#requestPointerLock + * @since 3.0.0 + */ + requestPointerLock: function () + { + if (Features.pointerLock) + { + var element = this.target; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + } + }, + + /** + * If the browser supports pointer lock, this will request that the pointer lock is released. If + * the browser successfully enters a locked state, a 'POINTER_LOCK_CHANGE_EVENT' will be + * dispatched - from the game's input manager - with an `isPointerLocked` property. + * + * @method Phaser.Input.Mouse.MouseManager#releasePointerLock + * @since 3.0.0 + */ + releasePointerLock: function () + { + if (Features.pointerLock) + { + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + document.exitPointerLock(); + } + }, + + /** + * Starts the Mouse Event listeners running. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Mouse.MouseManager#startListeners + * @since 3.0.0 + */ + startListeners: function () + { + var _this = this; + var canvas = this.manager.canvas; + var autoFocus = (window && window.focus && this.manager.game.config.autoFocus); + + this.onMouseMove = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseMove(event); + + if (_this.capture) + { + event.preventDefault(); + } + } + }; + + this.onMouseDown = function (event) + { + if (autoFocus) + { + window.focus(); + } + + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseDown(event); + + if (_this.capture && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onMouseDownWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onMouseDown(event); + } + }; + + this.onMouseUp = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseUp(event); + + if (_this.capture && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onMouseUpWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onMouseUp(event); + } + }; + + this.onMouseOver = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOver(event); + } + }; + + this.onMouseOut = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOut(event); + } + }; + + this.onMouseWheel = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onMouseWheel(event); + } + }; + + var target = this.target; + + if (!target) + { + return; + } + + var passive = { passive: true }; + var nonPassive = { passive: false }; + + target.addEventListener('mousemove', this.onMouseMove, (this.capture) ? nonPassive : passive); + target.addEventListener('mousedown', this.onMouseDown, (this.capture) ? nonPassive : passive); + target.addEventListener('mouseup', this.onMouseUp, (this.capture) ? nonPassive : passive); + target.addEventListener('mouseover', this.onMouseOver, (this.capture) ? nonPassive : passive); + target.addEventListener('mouseout', this.onMouseOut, (this.capture) ? nonPassive : passive); + target.addEventListener('wheel', this.onMouseWheel, (this.capture) ? nonPassive : passive); + + if (window && this.manager.game.config.inputWindowEvents) + { + window.addEventListener('mousedown', this.onMouseDownWindow, nonPassive); + window.addEventListener('mouseup', this.onMouseUpWindow, nonPassive); + } + + if (Features.pointerLock) + { + this.pointerLockChange = function (event) + { + var element = _this.target; + + _this.locked = (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) ? true : false; + + _this.manager.onPointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this.pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this.pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this.pointerLockChange, true); + } + + this.enabled = true; + }, + + /** + * Stops the Mouse Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Mouse.MouseManager#stopListeners + * @since 3.0.0 + */ + stopListeners: function () + { + var target = this.target; + + target.removeEventListener('mousemove', this.onMouseMove); + target.removeEventListener('mousedown', this.onMouseDown); + target.removeEventListener('mouseup', this.onMouseUp); + target.removeEventListener('mouseover', this.onMouseOver); + target.removeEventListener('mouseout', this.onMouseOut); + + if (window) + { + window.removeEventListener('mousedown', this.onMouseDownWindow); + window.removeEventListener('mouseup', this.onMouseUpWindow); + } + + if (Features.pointerLock) + { + document.removeEventListener('pointerlockchange', this.pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this.pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this.pointerLockChange, true); + } + }, + + /** + * Destroys this Mouse Manager instance. + * + * @method Phaser.Input.Mouse.MouseManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stopListeners(); + + this.target = null; + this.enabled = false; + this.manager = null; + } + +}); + +module.exports = MouseManager; diff --git a/src/input/mouse/index.js b/src/input/mouse/index.js index a5ff433ab..843b95f2c 100644 --- a/src/input/mouse/index.js +++ b/src/input/mouse/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Mouse - */ - -/* eslint-disable */ -module.exports = { - - MouseManager: require('./MouseManager') - -}; -/* eslint-enable */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Mouse + */ + +/* eslint-disable */ +module.exports = { + + MouseManager: require('./MouseManager') + +}; +/* eslint-enable */ diff --git a/src/input/touch/TouchManager.js b/src/input/touch/TouchManager.js index 472de4dab..e9dba9cf8 100644 --- a/src/input/touch/TouchManager.js +++ b/src/input/touch/TouchManager.js @@ -1,407 +1,407 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var InputEvents = require('../events'); -var NOOP = require('../../utils/NOOP'); - -// 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/ - -/** - * @classdesc - * The Touch Manager is a helper class that belongs to the Input Manager. - * - * Its role is to listen for native DOM Touch Events and then pass them onto the Input Manager for further processing. - * - * You do not need to create this class directly, the Input Manager will create an instance of it automatically. - * - * @class TouchManager - * @memberof Phaser.Input.Touch - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. - */ -var TouchManager = new Class({ - - initialize: - - function TouchManager (inputManager) - { - /** - * A reference to the Input Manager. - * - * @name Phaser.Input.Touch.TouchManager#manager - * @type {Phaser.Input.InputManager} - * @since 3.0.0 - */ - this.manager = inputManager; - - /** - * If true the DOM events will have event.preventDefault applied to them, if false they will propagate fully. - * - * @name Phaser.Input.Touch.TouchManager#capture - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.capture = true; - - /** - * A boolean that controls if the Touch Manager is enabled or not. - * Can be toggled on the fly. - * - * @name Phaser.Input.Touch.TouchManager#enabled - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.enabled = false; - - /** - * The Touch Event target, as defined in the Game Config. - * Typically the canvas to which the game is rendering, but can be any interactive DOM element. - * - * @name Phaser.Input.Touch.TouchManager#target - * @type {any} - * @since 3.0.0 - */ - this.target; - - /** - * The Touch Start event handler function. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchStart - * @type {function} - * @since 3.0.0 - */ - this.onTouchStart = NOOP; - - /** - * The Touch Start event handler function specifically for events on the Window. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchStartWindow - * @type {function} - * @since 3.17.0 - */ - this.onTouchStartWindow = NOOP; - - /** - * The Touch Move event handler function. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchMove - * @type {function} - * @since 3.0.0 - */ - this.onTouchMove = NOOP; - - /** - * The Touch End event handler function. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchEnd - * @type {function} - * @since 3.0.0 - */ - this.onTouchEnd = NOOP; - - /** - * The Touch End event handler function specifically for events on the Window. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchEndWindow - * @type {function} - * @since 3.17.0 - */ - this.onTouchEndWindow = NOOP; - - /** - * The Touch Cancel event handler function. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchCancel - * @type {function} - * @since 3.15.0 - */ - this.onTouchCancel = NOOP; - - /** - * The Touch Cancel event handler function specifically for events on the Window. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchCancelWindow - * @type {function} - * @since 3.18.0 - */ - this.onTouchCancelWindow = NOOP; - - /** - * The Touch Over event handler function. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchOver - * @type {function} - * @since 3.16.0 - */ - this.onTouchOver = NOOP; - - /** - * The Touch Out event handler function. - * Initially empty and bound in the `startListeners` method. - * - * @name Phaser.Input.Touch.TouchManager#onTouchOut - * @type {function} - * @since 3.16.0 - */ - this.onTouchOut = NOOP; - - inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); - }, - - /** - * The Touch Manager boot process. - * - * @method Phaser.Input.Touch.TouchManager#boot - * @private - * @since 3.0.0 - */ - boot: function () - { - var config = this.manager.config; - - this.enabled = config.inputTouch; - this.target = config.inputTouchEventTarget; - this.capture = config.inputTouchCapture; - - if (!this.target) - { - this.target = this.manager.game.canvas; - } - - if (config.disableContextMenu) - { - this.disableContextMenu(); - } - - if (this.enabled && this.target) - { - this.startListeners(); - } - }, - - /** - * Attempts to disable the context menu from appearing if you touch-hold on the browser. - * - * Works by listening for the `contextmenu` event and prevent defaulting it. - * - * Use this if you need to disable the OS context menu on mobile. - * - * @method Phaser.Input.Touch.TouchManager#disableContextMenu - * @since 3.20.0 - * - * @return {Phaser.Input.Touch.TouchManager} This Touch Manager instance. - */ - disableContextMenu: function () - { - document.body.addEventListener('contextmenu', function (event) - { - event.preventDefault(); - return false; - }); - - return this; - }, - - /** - * Starts the Touch Event listeners running as long as an input target is set. - * - * This method is called automatically if Touch Input is enabled in the game config, - * which it is by default. However, you can call it manually should you need to - * delay input capturing until later in the game. - * - * @method Phaser.Input.Touch.TouchManager#startListeners - * @since 3.0.0 - */ - startListeners: function () - { - var _this = this; - var canvas = this.manager.canvas; - var autoFocus = (window && window.focus && this.manager.game.config.autoFocus); - - this.onTouchStart = function (event) - { - if (autoFocus) - { - window.focus(); - } - - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onTouchStart(event); - - if (_this.capture && event.cancelable && event.target === canvas) - { - event.preventDefault(); - } - } - }; - - this.onTouchStartWindow = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) - { - // Only process the event if the target isn't the canvas - _this.manager.onTouchStart(event); - } - }; - - this.onTouchMove = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onTouchMove(event); - - if (_this.capture && event.cancelable) - { - event.preventDefault(); - } - } - }; - - this.onTouchEnd = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onTouchEnd(event); - - if (_this.capture && event.cancelable && event.target === canvas) - { - event.preventDefault(); - } - } - }; - - this.onTouchEndWindow = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) - { - // Only process the event if the target isn't the canvas - _this.manager.onTouchEnd(event); - } - }; - - this.onTouchCancel = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onTouchCancel(event); - - if (_this.capture) - { - event.preventDefault(); - } - } - }; - - this.onTouchCancelWindow = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.onTouchCancel(event); - } - }; - - this.onTouchOver = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.setCanvasOver(event); - } - }; - - this.onTouchOut = function (event) - { - if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) - { - _this.manager.setCanvasOut(event); - } - }; - - var target = this.target; - - if (!target) - { - return; - } - - var passive = { passive: true }; - var nonPassive = { passive: false }; - - target.addEventListener('touchstart', this.onTouchStart, (this.capture) ? nonPassive : passive); - target.addEventListener('touchmove', this.onTouchMove, (this.capture) ? nonPassive : passive); - target.addEventListener('touchend', this.onTouchEnd, (this.capture) ? nonPassive : passive); - target.addEventListener('touchcancel', this.onTouchCancel, (this.capture) ? nonPassive : passive); - target.addEventListener('touchover', this.onTouchOver, (this.capture) ? nonPassive : passive); - target.addEventListener('touchout', this.onTouchOut, (this.capture) ? nonPassive : passive); - - if (window && this.manager.game.config.inputWindowEvents) - { - window.addEventListener('touchstart', this.onTouchStartWindow, nonPassive); - window.addEventListener('touchend', this.onTouchEndWindow, nonPassive); - window.addEventListener('touchcancel', this.onTouchCancelWindow, nonPassive); - } - - this.enabled = true; - }, - - /** - * Stops the Touch Event listeners. - * This is called automatically and does not need to be manually invoked. - * - * @method Phaser.Input.Touch.TouchManager#stopListeners - * @since 3.0.0 - */ - stopListeners: function () - { - var target = this.target; - - target.removeEventListener('touchstart', this.onTouchStart); - target.removeEventListener('touchmove', this.onTouchMove); - target.removeEventListener('touchend', this.onTouchEnd); - target.removeEventListener('touchcancel', this.onTouchCancel); - target.removeEventListener('touchover', this.onTouchOver); - target.removeEventListener('touchout', this.onTouchOut); - - if (window) - { - window.removeEventListener('touchstart', this.onTouchStartWindow); - window.removeEventListener('touchend', this.onTouchEndWindow); - } - }, - - /** - * Destroys this Touch Manager instance. - * - * @method Phaser.Input.Touch.TouchManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.stopListeners(); - - this.target = null; - this.enabled = false; - this.manager = null; - } - -}); - -module.exports = TouchManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var InputEvents = require('../events'); +var NOOP = require('../../utils/NOOP'); + +// 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/ + +/** + * @classdesc + * The Touch Manager is a helper class that belongs to the Input Manager. + * + * Its role is to listen for native DOM Touch Events and then pass them onto the Input Manager for further processing. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically. + * + * @class TouchManager + * @memberof Phaser.Input.Touch + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Input.InputManager} inputManager - A reference to the Input Manager. + */ +var TouchManager = new Class({ + + initialize: + + function TouchManager (inputManager) + { + /** + * A reference to the Input Manager. + * + * @name Phaser.Input.Touch.TouchManager#manager + * @type {Phaser.Input.InputManager} + * @since 3.0.0 + */ + this.manager = inputManager; + + /** + * If true the DOM events will have event.preventDefault applied to them, if false they will propagate fully. + * + * @name Phaser.Input.Touch.TouchManager#capture + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.capture = true; + + /** + * A boolean that controls if the Touch Manager is enabled or not. + * Can be toggled on the fly. + * + * @name Phaser.Input.Touch.TouchManager#enabled + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.enabled = false; + + /** + * The Touch Event target, as defined in the Game Config. + * Typically the canvas to which the game is rendering, but can be any interactive DOM element. + * + * @name Phaser.Input.Touch.TouchManager#target + * @type {any} + * @since 3.0.0 + */ + this.target; + + /** + * The Touch Start event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchStart + * @type {function} + * @since 3.0.0 + */ + this.onTouchStart = NOOP; + + /** + * The Touch Start event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchStartWindow + * @type {function} + * @since 3.17.0 + */ + this.onTouchStartWindow = NOOP; + + /** + * The Touch Move event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchMove + * @type {function} + * @since 3.0.0 + */ + this.onTouchMove = NOOP; + + /** + * The Touch End event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchEnd + * @type {function} + * @since 3.0.0 + */ + this.onTouchEnd = NOOP; + + /** + * The Touch End event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchEndWindow + * @type {function} + * @since 3.17.0 + */ + this.onTouchEndWindow = NOOP; + + /** + * The Touch Cancel event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchCancel + * @type {function} + * @since 3.15.0 + */ + this.onTouchCancel = NOOP; + + /** + * The Touch Cancel event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchCancelWindow + * @type {function} + * @since 3.18.0 + */ + this.onTouchCancelWindow = NOOP; + + /** + * The Touch Over event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchOver + * @type {function} + * @since 3.16.0 + */ + this.onTouchOver = NOOP; + + /** + * The Touch Out event handler function. + * Initially empty and bound in the `startListeners` method. + * + * @name Phaser.Input.Touch.TouchManager#onTouchOut + * @type {function} + * @since 3.16.0 + */ + this.onTouchOut = NOOP; + + inputManager.events.once(InputEvents.MANAGER_BOOT, this.boot, this); + }, + + /** + * The Touch Manager boot process. + * + * @method Phaser.Input.Touch.TouchManager#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + var config = this.manager.config; + + this.enabled = config.inputTouch; + this.target = config.inputTouchEventTarget; + this.capture = config.inputTouchCapture; + + if (!this.target) + { + this.target = this.manager.game.canvas; + } + + if (config.disableContextMenu) + { + this.disableContextMenu(); + } + + if (this.enabled && this.target) + { + this.startListeners(); + } + }, + + /** + * Attempts to disable the context menu from appearing if you touch-hold on the browser. + * + * Works by listening for the `contextmenu` event and prevent defaulting it. + * + * Use this if you need to disable the OS context menu on mobile. + * + * @method Phaser.Input.Touch.TouchManager#disableContextMenu + * @since 3.20.0 + * + * @return {Phaser.Input.Touch.TouchManager} This Touch Manager instance. + */ + disableContextMenu: function () + { + document.body.addEventListener('contextmenu', function (event) + { + event.preventDefault(); + return false; + }); + + return this; + }, + + /** + * Starts the Touch Event listeners running as long as an input target is set. + * + * This method is called automatically if Touch Input is enabled in the game config, + * which it is by default. However, you can call it manually should you need to + * delay input capturing until later in the game. + * + * @method Phaser.Input.Touch.TouchManager#startListeners + * @since 3.0.0 + */ + startListeners: function () + { + var _this = this; + var canvas = this.manager.canvas; + var autoFocus = (window && window.focus && this.manager.game.config.autoFocus); + + this.onTouchStart = function (event) + { + if (autoFocus) + { + window.focus(); + } + + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchStart(event); + + if (_this.capture && event.cancelable && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onTouchStartWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onTouchStart(event); + } + }; + + this.onTouchMove = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchMove(event); + + if (_this.capture && event.cancelable) + { + event.preventDefault(); + } + } + }; + + this.onTouchEnd = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchEnd(event); + + if (_this.capture && event.cancelable && event.target === canvas) + { + event.preventDefault(); + } + } + }; + + this.onTouchEndWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled && event.target !== canvas) + { + // Only process the event if the target isn't the canvas + _this.manager.onTouchEnd(event); + } + }; + + this.onTouchCancel = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchCancel(event); + + if (_this.capture) + { + event.preventDefault(); + } + } + }; + + this.onTouchCancelWindow = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.onTouchCancel(event); + } + }; + + this.onTouchOver = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOver(event); + } + }; + + this.onTouchOut = function (event) + { + if (!event.defaultPrevented && _this.enabled && _this.manager && _this.manager.enabled) + { + _this.manager.setCanvasOut(event); + } + }; + + var target = this.target; + + if (!target) + { + return; + } + + var passive = { passive: true }; + var nonPassive = { passive: false }; + + target.addEventListener('touchstart', this.onTouchStart, (this.capture) ? nonPassive : passive); + target.addEventListener('touchmove', this.onTouchMove, (this.capture) ? nonPassive : passive); + target.addEventListener('touchend', this.onTouchEnd, (this.capture) ? nonPassive : passive); + target.addEventListener('touchcancel', this.onTouchCancel, (this.capture) ? nonPassive : passive); + target.addEventListener('touchover', this.onTouchOver, (this.capture) ? nonPassive : passive); + target.addEventListener('touchout', this.onTouchOut, (this.capture) ? nonPassive : passive); + + if (window && this.manager.game.config.inputWindowEvents) + { + window.addEventListener('touchstart', this.onTouchStartWindow, nonPassive); + window.addEventListener('touchend', this.onTouchEndWindow, nonPassive); + window.addEventListener('touchcancel', this.onTouchCancelWindow, nonPassive); + } + + this.enabled = true; + }, + + /** + * Stops the Touch Event listeners. + * This is called automatically and does not need to be manually invoked. + * + * @method Phaser.Input.Touch.TouchManager#stopListeners + * @since 3.0.0 + */ + stopListeners: function () + { + var target = this.target; + + target.removeEventListener('touchstart', this.onTouchStart); + target.removeEventListener('touchmove', this.onTouchMove); + target.removeEventListener('touchend', this.onTouchEnd); + target.removeEventListener('touchcancel', this.onTouchCancel); + target.removeEventListener('touchover', this.onTouchOver); + target.removeEventListener('touchout', this.onTouchOut); + + if (window) + { + window.removeEventListener('touchstart', this.onTouchStartWindow); + window.removeEventListener('touchend', this.onTouchEndWindow); + } + }, + + /** + * Destroys this Touch Manager instance. + * + * @method Phaser.Input.Touch.TouchManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.stopListeners(); + + this.target = null; + this.enabled = false; + this.manager = null; + } + +}); + +module.exports = TouchManager; diff --git a/src/input/touch/index.js b/src/input/touch/index.js index 097c1bc7a..881a61e16 100644 --- a/src/input/touch/index.js +++ b/src/input/touch/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Input.Touch - */ - -/* eslint-disable */ -module.exports = { - - TouchManager: require('./TouchManager') - -}; -/* eslint-enable */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Input.Touch + */ + +/* eslint-disable */ +module.exports = { + + TouchManager: require('./TouchManager') + +}; +/* eslint-enable */ diff --git a/src/input/typedefs/EventData.js b/src/input/typedefs/EventData.js index 664589337..02b64433b 100644 --- a/src/input/typedefs/EventData.js +++ b/src/input/typedefs/EventData.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A Phaser Input Event Data object. - * - * This object is passed to the registered event listeners and allows you to stop any further propagation. - * - * @typedef {object} Phaser.Types.Input.EventData - * @since 3.15.1 - * - * @property {boolean} [cancelled=false] - The cancelled state of this Event. - * @property {function} stopPropagation - Call this method to stop this event from passing any further down the event chain. - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A Phaser Input Event Data object. + * + * This object is passed to the registered event listeners and allows you to stop any further propagation. + * + * @typedef {object} Phaser.Types.Input.EventData + * @since 3.15.1 + * + * @property {boolean} [cancelled=false] - The cancelled state of this Event. + * @property {function} stopPropagation - Call this method to stop this event from passing any further down the event chain. + */ diff --git a/src/input/typedefs/index.js b/src/input/typedefs/index.js index 96498d6a9..5f91959df 100644 --- a/src/input/typedefs/index.js +++ b/src/input/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Input - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Input + */ diff --git a/src/loader/File.js b/src/loader/File.js index 12b088c91..890eda780 100644 --- a/src/loader/File.js +++ b/src/loader/File.js @@ -1,535 +1,535 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CONST = require('./const'); -var Events = require('./events'); -var GetFastValue = require('../utils/object/GetFastValue'); -var GetURL = require('./GetURL'); -var MergeXHRSettings = require('./MergeXHRSettings'); -var XHRLoader = require('./XHRLoader'); -var XHRSettings = require('./XHRSettings'); - -/** - * @classdesc - * The base File class used by all File Types that the Loader can support. - * You shouldn't create an instance of a File directly, but should extend it with your own class, setting a custom type and processing methods. - * - * @class File - * @memberof Phaser.Loader - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File. - * @param {Phaser.Types.Loader.FileConfig} fileConfig - The file configuration object, as created by the file type. - */ -var File = new Class({ - - initialize: - - function File (loader, fileConfig) - { - /** - * A reference to the Loader that is going to load this file. - * - * @name Phaser.Loader.File#loader - * @type {Phaser.Loader.LoaderPlugin} - * @since 3.0.0 - */ - this.loader = loader; - - /** - * A reference to the Cache, or Texture Manager, that is going to store this file if it loads. - * - * @name Phaser.Loader.File#cache - * @type {(Phaser.Cache.BaseCache|Phaser.Textures.TextureManager)} - * @since 3.7.0 - */ - this.cache = GetFastValue(fileConfig, 'cache', false); - - /** - * The file type string (image, json, etc) for sorting within the Loader. - * - * @name Phaser.Loader.File#type - * @type {string} - * @since 3.0.0 - */ - this.type = GetFastValue(fileConfig, 'type', false); - - /** - * Unique cache key (unique within its file type) - * - * @name Phaser.Loader.File#key - * @type {string} - * @since 3.0.0 - */ - this.key = GetFastValue(fileConfig, 'key', false); - - var loadKey = this.key; - - if (loader.prefix && loader.prefix !== '') - { - this.key = loader.prefix + loadKey; - } - - if (!this.type || !this.key) - { - throw new Error('Error calling \'Loader.' + this.type + '\' invalid key provided.'); - } - - /** - * The URL of the file, not including baseURL. - * Automatically has Loader.path prepended to it. - * - * @name Phaser.Loader.File#url - * @type {string} - * @since 3.0.0 - */ - this.url = GetFastValue(fileConfig, 'url'); - - if (this.url === undefined) - { - this.url = loader.path + loadKey + '.' + GetFastValue(fileConfig, 'extension', ''); - } - else if (typeof(this.url) !== 'function') - { - this.url = loader.path + this.url; - } - - /** - * The final URL this file will load from, including baseURL and path. - * Set automatically when the Loader calls 'load' on this file. - * - * @name Phaser.Loader.File#src - * @type {string} - * @since 3.0.0 - */ - this.src = ''; - - /** - * The merged XHRSettings for this file. - * - * @name Phaser.Loader.File#xhrSettings - * @type {Phaser.Types.Loader.XHRSettingsObject} - * @since 3.0.0 - */ - this.xhrSettings = XHRSettings(GetFastValue(fileConfig, 'responseType', undefined)); - - if (GetFastValue(fileConfig, 'xhrSettings', false)) - { - this.xhrSettings = MergeXHRSettings(this.xhrSettings, GetFastValue(fileConfig, 'xhrSettings', {})); - } - - /** - * The XMLHttpRequest instance (as created by XHR Loader) that is loading this File. - * - * @name Phaser.Loader.File#xhrLoader - * @type {?XMLHttpRequest} - * @since 3.0.0 - */ - this.xhrLoader = null; - - /** - * The current state of the file. One of the FILE_CONST values. - * - * @name Phaser.Loader.File#state - * @type {integer} - * @since 3.0.0 - */ - this.state = (typeof(this.url) === 'function') ? CONST.FILE_POPULATED : CONST.FILE_PENDING; - - /** - * The total size of this file. - * Set by onProgress and only if loading via XHR. - * - * @name Phaser.Loader.File#bytesTotal - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.bytesTotal = 0; - - /** - * Updated as the file loads. - * Only set if loading via XHR. - * - * @name Phaser.Loader.File#bytesLoaded - * @type {number} - * @default -1 - * @since 3.0.0 - */ - this.bytesLoaded = -1; - - /** - * A percentage value between 0 and 1 indicating how much of this file has loaded. - * Only set if loading via XHR. - * - * @name Phaser.Loader.File#percentComplete - * @type {number} - * @default -1 - * @since 3.0.0 - */ - this.percentComplete = -1; - - /** - * For CORs based loading. - * If this is undefined then the File will check BaseLoader.crossOrigin and use that (if set) - * - * @name Phaser.Loader.File#crossOrigin - * @type {(string|undefined)} - * @since 3.0.0 - */ - this.crossOrigin = undefined; - - /** - * The processed file data, stored here after the file has loaded. - * - * @name Phaser.Loader.File#data - * @type {*} - * @since 3.0.0 - */ - this.data = undefined; - - /** - * A config object that can be used by file types to store transitional data. - * - * @name Phaser.Loader.File#config - * @type {*} - * @since 3.0.0 - */ - this.config = GetFastValue(fileConfig, 'config', {}); - - /** - * If this is a multipart file, i.e. an atlas and its json together, then this is a reference - * to the parent MultiFile. Set and used internally by the Loader or specific file types. - * - * @name Phaser.Loader.File#multiFile - * @type {?Phaser.Loader.MultiFile} - * @since 3.7.0 - */ - this.multiFile; - - /** - * Does this file have an associated linked file? Such as an image and a normal map. - * Atlases and Bitmap Fonts use the multiFile, because those files need loading together but aren't - * actually bound by data, where-as a linkFile is. - * - * @name Phaser.Loader.File#linkFile - * @type {?Phaser.Loader.File} - * @since 3.7.0 - */ - this.linkFile; - }, - - /** - * Links this File with another, so they depend upon each other for loading and processing. - * - * @method Phaser.Loader.File#setLink - * @since 3.7.0 - * - * @param {Phaser.Loader.File} fileB - The file to link to this one. - */ - setLink: function (fileB) - { - this.linkFile = fileB; - - fileB.linkFile = this; - }, - - /** - * Resets the XHRLoader instance this file is using. - * - * @method Phaser.Loader.File#resetXHR - * @since 3.0.0 - */ - resetXHR: function () - { - if (this.xhrLoader) - { - this.xhrLoader.onload = undefined; - this.xhrLoader.onerror = undefined; - this.xhrLoader.onprogress = undefined; - } - }, - - /** - * 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 - */ - load: function () - { - if (this.state === CONST.FILE_POPULATED) - { - // Can happen for example in a JSONFile if they've provided a JSON object instead of a URL - this.loader.nextFile(this, true); - } - else - { - this.src = GetURL(this, this.loader.baseURL); - - if (this.src.indexOf('data:') === 0) - { - console.warn('Local data URIs are not supported: ' + this.key); - } - else - { - // The creation of this XHRLoader starts the load process going. - // It will automatically call the following, based on the load outcome: - // - // xhr.onload = this.onLoad - // xhr.onerror = this.onError - // xhr.onprogress = this.onProgress - - this.xhrLoader = XHRLoader(this, this.loader.xhr); - } - } - }, - - /** - * Called when the file finishes loading, is sent a DOM ProgressEvent. - * - * @method Phaser.Loader.File#onLoad - * @since 3.0.0 - * - * @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event. - * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. - */ - onLoad: function (xhr, event) - { - var localFileOk = ((xhr.responseURL && xhr.responseURL.indexOf('file://') === 0 && event.target.status === 0)); - - var success = !(event.target && event.target.status !== 200) || localFileOk; - - // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. - if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) - { - success = false; - } - - this.resetXHR(); - - this.loader.nextFile(this, success); - }, - - /** - * Called if the file errors while loading, is sent a DOM ProgressEvent. - * - * @method Phaser.Loader.File#onError - * @since 3.0.0 - * - * @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event. - * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this error. - */ - onError: function () - { - this.resetXHR(); - - this.loader.nextFile(this, false); - }, - - /** - * Called during the file load progress. Is sent a DOM ProgressEvent. - * - * @method Phaser.Loader.File#onProgress - * @fires Phaser.Loader.Events#FILE_PROGRESS - * @since 3.0.0 - * - * @param {ProgressEvent} event - The DOM ProgressEvent. - */ - onProgress: function (event) - { - if (event.lengthComputable) - { - this.bytesLoaded = event.loaded; - this.bytesTotal = event.total; - - this.percentComplete = Math.min((this.bytesLoaded / this.bytesTotal), 1); - - this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete); - } - }, - - /** - * Usually overridden by the FileTypes and is called by Loader.nextFile. - * This method controls what extra work this File does with its loaded data, for example a JSON file will parse itself during this stage. - * - * @method Phaser.Loader.File#onProcess - * @since 3.0.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.onProcessComplete(); - }, - - /** - * Called when the File has completed processing. - * Checks on the state of its multifile, if set. - * - * @method Phaser.Loader.File#onProcessComplete - * @since 3.7.0 - */ - onProcessComplete: function () - { - this.state = CONST.FILE_COMPLETE; - - if (this.multiFile) - { - this.multiFile.onFileComplete(this); - } - - this.loader.fileProcessComplete(this); - }, - - /** - * Called when the File has completed processing but it generated an error. - * Checks on the state of its multifile, if set. - * - * @method Phaser.Loader.File#onProcessError - * @since 3.7.0 - */ - onProcessError: function () - { - this.state = CONST.FILE_ERRORED; - - if (this.multiFile) - { - this.multiFile.onFileFailed(this); - } - - this.loader.fileProcessComplete(this); - }, - - /** - * Checks if a key matching the one used by this file exists in the target Cache or not. - * This is called automatically by the LoaderPlugin to decide if the file can be safely - * loaded or will conflict. - * - * @method Phaser.Loader.File#hasCacheConflict - * @since 3.7.0 - * - * @return {boolean} `true` if adding this file will cause a conflict, otherwise `false`. - */ - hasCacheConflict: function () - { - return (this.cache && this.cache.exists(this.key)); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * This method is often overridden by specific file types. - * - * @method Phaser.Loader.File#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.cache) - { - this.cache.add(this.key, this.data); - } - - this.pendingDestroy(); - }, - - /** - * Called once the file has been added to its cache and is now ready for deletion from the Loader. - * It will emit a `filecomplete` event from the LoaderPlugin. - * - * @method Phaser.Loader.File#pendingDestroy - * @fires Phaser.Loader.Events#FILE_COMPLETE - * @fires Phaser.Loader.Events#FILE_KEY_COMPLETE - * @since 3.7.0 - */ - pendingDestroy: function (data) - { - if (data === undefined) { data = this.data; } - - var key = this.key; - var type = this.type; - - this.loader.emit(Events.FILE_COMPLETE, key, type, data); - this.loader.emit(Events.FILE_KEY_COMPLETE + type + '-' + key, key, type, data); - - this.loader.flagForRemoval(this); - }, - - /** - * Destroy this File and any references it holds. - * - * @method Phaser.Loader.File#destroy - * @since 3.7.0 - */ - destroy: function () - { - this.loader = null; - this.cache = null; - this.xhrSettings = null; - this.multiFile = null; - this.linkFile = null; - this.data = null; - } - -}); - -/** - * Static method for creating object URL using URL API and setting it as image 'src' attribute. - * If URL API is not supported (usually on old browsers) it falls back to creating Base64 encoded url using FileReader. - * - * @method Phaser.Loader.File.createObjectURL - * @static - * @since 3.7.0 - * - * @param {HTMLImageElement} image - Image object which 'src' attribute should be set to object URL. - * @param {Blob} blob - A Blob object to create an object URL for. - * @param {string} defaultType - Default mime type used if blob type is not available. - */ -File.createObjectURL = function (image, blob, defaultType) -{ - if (typeof URL === 'function') - { - image.src = URL.createObjectURL(blob); - } - else - { - var reader = new FileReader(); - - reader.onload = function () - { - image.removeAttribute('crossOrigin'); - image.src = 'data:' + (blob.type || defaultType) + ';base64,' + reader.result.split(',')[1]; - }; - - reader.onerror = image.onerror; - - reader.readAsDataURL(blob); - } -}; - -/** - * Static method for releasing an existing object URL which was previously created - * by calling {@link File#createObjectURL} method. - * - * @method Phaser.Loader.File.revokeObjectURL - * @static - * @since 3.7.0 - * - * @param {HTMLImageElement} image - Image object which 'src' attribute should be revoked. - */ -File.revokeObjectURL = function (image) -{ - if (typeof URL === 'function') - { - URL.revokeObjectURL(image.src); - } -}; - -module.exports = File; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CONST = require('./const'); +var Events = require('./events'); +var GetFastValue = require('../utils/object/GetFastValue'); +var GetURL = require('./GetURL'); +var MergeXHRSettings = require('./MergeXHRSettings'); +var XHRLoader = require('./XHRLoader'); +var XHRSettings = require('./XHRSettings'); + +/** + * @classdesc + * The base File class used by all File Types that the Loader can support. + * You shouldn't create an instance of a File directly, but should extend it with your own class, setting a custom type and processing methods. + * + * @class File + * @memberof Phaser.Loader + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File. + * @param {Phaser.Types.Loader.FileConfig} fileConfig - The file configuration object, as created by the file type. + */ +var File = new Class({ + + initialize: + + function File (loader, fileConfig) + { + /** + * A reference to the Loader that is going to load this file. + * + * @name Phaser.Loader.File#loader + * @type {Phaser.Loader.LoaderPlugin} + * @since 3.0.0 + */ + this.loader = loader; + + /** + * A reference to the Cache, or Texture Manager, that is going to store this file if it loads. + * + * @name Phaser.Loader.File#cache + * @type {(Phaser.Cache.BaseCache|Phaser.Textures.TextureManager)} + * @since 3.7.0 + */ + this.cache = GetFastValue(fileConfig, 'cache', false); + + /** + * The file type string (image, json, etc) for sorting within the Loader. + * + * @name Phaser.Loader.File#type + * @type {string} + * @since 3.0.0 + */ + this.type = GetFastValue(fileConfig, 'type', false); + + /** + * Unique cache key (unique within its file type) + * + * @name Phaser.Loader.File#key + * @type {string} + * @since 3.0.0 + */ + this.key = GetFastValue(fileConfig, 'key', false); + + var loadKey = this.key; + + if (loader.prefix && loader.prefix !== '') + { + this.key = loader.prefix + loadKey; + } + + if (!this.type || !this.key) + { + throw new Error('Error calling \'Loader.' + this.type + '\' invalid key provided.'); + } + + /** + * The URL of the file, not including baseURL. + * Automatically has Loader.path prepended to it. + * + * @name Phaser.Loader.File#url + * @type {string} + * @since 3.0.0 + */ + this.url = GetFastValue(fileConfig, 'url'); + + if (this.url === undefined) + { + this.url = loader.path + loadKey + '.' + GetFastValue(fileConfig, 'extension', ''); + } + else if (typeof(this.url) !== 'function') + { + this.url = loader.path + this.url; + } + + /** + * The final URL this file will load from, including baseURL and path. + * Set automatically when the Loader calls 'load' on this file. + * + * @name Phaser.Loader.File#src + * @type {string} + * @since 3.0.0 + */ + this.src = ''; + + /** + * The merged XHRSettings for this file. + * + * @name Phaser.Loader.File#xhrSettings + * @type {Phaser.Types.Loader.XHRSettingsObject} + * @since 3.0.0 + */ + this.xhrSettings = XHRSettings(GetFastValue(fileConfig, 'responseType', undefined)); + + if (GetFastValue(fileConfig, 'xhrSettings', false)) + { + this.xhrSettings = MergeXHRSettings(this.xhrSettings, GetFastValue(fileConfig, 'xhrSettings', {})); + } + + /** + * The XMLHttpRequest instance (as created by XHR Loader) that is loading this File. + * + * @name Phaser.Loader.File#xhrLoader + * @type {?XMLHttpRequest} + * @since 3.0.0 + */ + this.xhrLoader = null; + + /** + * The current state of the file. One of the FILE_CONST values. + * + * @name Phaser.Loader.File#state + * @type {integer} + * @since 3.0.0 + */ + this.state = (typeof(this.url) === 'function') ? CONST.FILE_POPULATED : CONST.FILE_PENDING; + + /** + * The total size of this file. + * Set by onProgress and only if loading via XHR. + * + * @name Phaser.Loader.File#bytesTotal + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.bytesTotal = 0; + + /** + * Updated as the file loads. + * Only set if loading via XHR. + * + * @name Phaser.Loader.File#bytesLoaded + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.bytesLoaded = -1; + + /** + * A percentage value between 0 and 1 indicating how much of this file has loaded. + * Only set if loading via XHR. + * + * @name Phaser.Loader.File#percentComplete + * @type {number} + * @default -1 + * @since 3.0.0 + */ + this.percentComplete = -1; + + /** + * For CORs based loading. + * If this is undefined then the File will check BaseLoader.crossOrigin and use that (if set) + * + * @name Phaser.Loader.File#crossOrigin + * @type {(string|undefined)} + * @since 3.0.0 + */ + this.crossOrigin = undefined; + + /** + * The processed file data, stored here after the file has loaded. + * + * @name Phaser.Loader.File#data + * @type {*} + * @since 3.0.0 + */ + this.data = undefined; + + /** + * A config object that can be used by file types to store transitional data. + * + * @name Phaser.Loader.File#config + * @type {*} + * @since 3.0.0 + */ + this.config = GetFastValue(fileConfig, 'config', {}); + + /** + * If this is a multipart file, i.e. an atlas and its json together, then this is a reference + * to the parent MultiFile. Set and used internally by the Loader or specific file types. + * + * @name Phaser.Loader.File#multiFile + * @type {?Phaser.Loader.MultiFile} + * @since 3.7.0 + */ + this.multiFile; + + /** + * Does this file have an associated linked file? Such as an image and a normal map. + * Atlases and Bitmap Fonts use the multiFile, because those files need loading together but aren't + * actually bound by data, where-as a linkFile is. + * + * @name Phaser.Loader.File#linkFile + * @type {?Phaser.Loader.File} + * @since 3.7.0 + */ + this.linkFile; + }, + + /** + * Links this File with another, so they depend upon each other for loading and processing. + * + * @method Phaser.Loader.File#setLink + * @since 3.7.0 + * + * @param {Phaser.Loader.File} fileB - The file to link to this one. + */ + setLink: function (fileB) + { + this.linkFile = fileB; + + fileB.linkFile = this; + }, + + /** + * Resets the XHRLoader instance this file is using. + * + * @method Phaser.Loader.File#resetXHR + * @since 3.0.0 + */ + resetXHR: function () + { + if (this.xhrLoader) + { + this.xhrLoader.onload = undefined; + this.xhrLoader.onerror = undefined; + this.xhrLoader.onprogress = undefined; + } + }, + + /** + * 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 + */ + load: function () + { + if (this.state === CONST.FILE_POPULATED) + { + // Can happen for example in a JSONFile if they've provided a JSON object instead of a URL + this.loader.nextFile(this, true); + } + else + { + this.src = GetURL(this, this.loader.baseURL); + + if (this.src.indexOf('data:') === 0) + { + console.warn('Local data URIs are not supported: ' + this.key); + } + else + { + // The creation of this XHRLoader starts the load process going. + // It will automatically call the following, based on the load outcome: + // + // xhr.onload = this.onLoad + // xhr.onerror = this.onError + // xhr.onprogress = this.onProgress + + this.xhrLoader = XHRLoader(this, this.loader.xhr); + } + } + }, + + /** + * Called when the file finishes loading, is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.File#onLoad + * @since 3.0.0 + * + * @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event. + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. + */ + onLoad: function (xhr, event) + { + var localFileOk = ((xhr.responseURL && xhr.responseURL.indexOf('file://') === 0 && event.target.status === 0)); + + var success = !(event.target && event.target.status !== 200) || localFileOk; + + // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) + { + success = false; + } + + this.resetXHR(); + + this.loader.nextFile(this, success); + }, + + /** + * Called if the file errors while loading, is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.File#onError + * @since 3.0.0 + * + * @param {XMLHttpRequest} xhr - The XMLHttpRequest that caused this onload event. + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this error. + */ + onError: function () + { + this.resetXHR(); + + this.loader.nextFile(this, false); + }, + + /** + * Called during the file load progress. Is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.File#onProgress + * @fires Phaser.Loader.Events#FILE_PROGRESS + * @since 3.0.0 + * + * @param {ProgressEvent} event - The DOM ProgressEvent. + */ + onProgress: function (event) + { + if (event.lengthComputable) + { + this.bytesLoaded = event.loaded; + this.bytesTotal = event.total; + + this.percentComplete = Math.min((this.bytesLoaded / this.bytesTotal), 1); + + this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete); + } + }, + + /** + * Usually overridden by the FileTypes and is called by Loader.nextFile. + * This method controls what extra work this File does with its loaded data, for example a JSON file will parse itself during this stage. + * + * @method Phaser.Loader.File#onProcess + * @since 3.0.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.onProcessComplete(); + }, + + /** + * Called when the File has completed processing. + * Checks on the state of its multifile, if set. + * + * @method Phaser.Loader.File#onProcessComplete + * @since 3.7.0 + */ + onProcessComplete: function () + { + this.state = CONST.FILE_COMPLETE; + + if (this.multiFile) + { + this.multiFile.onFileComplete(this); + } + + this.loader.fileProcessComplete(this); + }, + + /** + * Called when the File has completed processing but it generated an error. + * Checks on the state of its multifile, if set. + * + * @method Phaser.Loader.File#onProcessError + * @since 3.7.0 + */ + onProcessError: function () + { + this.state = CONST.FILE_ERRORED; + + if (this.multiFile) + { + this.multiFile.onFileFailed(this); + } + + this.loader.fileProcessComplete(this); + }, + + /** + * Checks if a key matching the one used by this file exists in the target Cache or not. + * This is called automatically by the LoaderPlugin to decide if the file can be safely + * loaded or will conflict. + * + * @method Phaser.Loader.File#hasCacheConflict + * @since 3.7.0 + * + * @return {boolean} `true` if adding this file will cause a conflict, otherwise `false`. + */ + hasCacheConflict: function () + { + return (this.cache && this.cache.exists(this.key)); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * This method is often overridden by specific file types. + * + * @method Phaser.Loader.File#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.cache) + { + this.cache.add(this.key, this.data); + } + + this.pendingDestroy(); + }, + + /** + * Called once the file has been added to its cache and is now ready for deletion from the Loader. + * It will emit a `filecomplete` event from the LoaderPlugin. + * + * @method Phaser.Loader.File#pendingDestroy + * @fires Phaser.Loader.Events#FILE_COMPLETE + * @fires Phaser.Loader.Events#FILE_KEY_COMPLETE + * @since 3.7.0 + */ + pendingDestroy: function (data) + { + if (data === undefined) { data = this.data; } + + var key = this.key; + var type = this.type; + + this.loader.emit(Events.FILE_COMPLETE, key, type, data); + this.loader.emit(Events.FILE_KEY_COMPLETE + type + '-' + key, key, type, data); + + this.loader.flagForRemoval(this); + }, + + /** + * Destroy this File and any references it holds. + * + * @method Phaser.Loader.File#destroy + * @since 3.7.0 + */ + destroy: function () + { + this.loader = null; + this.cache = null; + this.xhrSettings = null; + this.multiFile = null; + this.linkFile = null; + this.data = null; + } + +}); + +/** + * Static method for creating object URL using URL API and setting it as image 'src' attribute. + * If URL API is not supported (usually on old browsers) it falls back to creating Base64 encoded url using FileReader. + * + * @method Phaser.Loader.File.createObjectURL + * @static + * @since 3.7.0 + * + * @param {HTMLImageElement} image - Image object which 'src' attribute should be set to object URL. + * @param {Blob} blob - A Blob object to create an object URL for. + * @param {string} defaultType - Default mime type used if blob type is not available. + */ +File.createObjectURL = function (image, blob, defaultType) +{ + if (typeof URL === 'function') + { + image.src = URL.createObjectURL(blob); + } + else + { + var reader = new FileReader(); + + reader.onload = function () + { + image.removeAttribute('crossOrigin'); + image.src = 'data:' + (blob.type || defaultType) + ';base64,' + reader.result.split(',')[1]; + }; + + reader.onerror = image.onerror; + + reader.readAsDataURL(blob); + } +}; + +/** + * Static method for releasing an existing object URL which was previously created + * by calling {@link File#createObjectURL} method. + * + * @method Phaser.Loader.File.revokeObjectURL + * @static + * @since 3.7.0 + * + * @param {HTMLImageElement} image - Image object which 'src' attribute should be revoked. + */ +File.revokeObjectURL = function (image) +{ + if (typeof URL === 'function') + { + URL.revokeObjectURL(image.src); + } +}; + +module.exports = File; diff --git a/src/loader/FileTypesManager.js b/src/loader/FileTypesManager.js index ec1d68109..55925742d 100644 --- a/src/loader/FileTypesManager.js +++ b/src/loader/FileTypesManager.js @@ -1,63 +1,63 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var types = {}; - -/** - * @namespace Phaser.Loader.FileTypesManager - */ - -var FileTypesManager = { - - /** - * Static method called when a LoaderPlugin is created. - * - * Loops through the local types object and injects all of them as - * properties into the LoaderPlugin instance. - * - * @method Phaser.Loader.FileTypesManager.install - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - The LoaderPlugin to install the types into. - */ - install: function (loader) - { - for (var key in types) - { - loader[key] = types[key]; - } - }, - - /** - * Static method called directly by the File Types. - * - * The key is a reference to the function used to load the files via the Loader, i.e. `image`. - * - * @method Phaser.Loader.FileTypesManager.register - * @since 3.0.0 - * - * @param {string} key - The key that will be used as the method name in the LoaderPlugin. - * @param {function} factoryFunction - The function that will be called when LoaderPlugin.key is invoked. - */ - register: function (key, factoryFunction) - { - types[key] = factoryFunction; - }, - - /** - * Removed all associated file types. - * - * @method Phaser.Loader.FileTypesManager.destroy - * @since 3.0.0 - */ - destroy: function () - { - types = {}; - } - -}; - -module.exports = FileTypesManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var types = {}; + +/** + * @namespace Phaser.Loader.FileTypesManager + */ + +var FileTypesManager = { + + /** + * Static method called when a LoaderPlugin is created. + * + * Loops through the local types object and injects all of them as + * properties into the LoaderPlugin instance. + * + * @method Phaser.Loader.FileTypesManager.install + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The LoaderPlugin to install the types into. + */ + install: function (loader) + { + for (var key in types) + { + loader[key] = types[key]; + } + }, + + /** + * Static method called directly by the File Types. + * + * The key is a reference to the function used to load the files via the Loader, i.e. `image`. + * + * @method Phaser.Loader.FileTypesManager.register + * @since 3.0.0 + * + * @param {string} key - The key that will be used as the method name in the LoaderPlugin. + * @param {function} factoryFunction - The function that will be called when LoaderPlugin.key is invoked. + */ + register: function (key, factoryFunction) + { + types[key] = factoryFunction; + }, + + /** + * Removed all associated file types. + * + * @method Phaser.Loader.FileTypesManager.destroy + * @since 3.0.0 + */ + destroy: function () + { + types = {}; + } + +}; + +module.exports = FileTypesManager; diff --git a/src/loader/GetURL.js b/src/loader/GetURL.js index 4e3ed3ce5..f9b3a761e 100644 --- a/src/loader/GetURL.js +++ b/src/loader/GetURL.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Given a File and a baseURL value this returns the URL the File will use to download from. - * - * @function Phaser.Loader.GetURL - * @since 3.0.0 - * - * @param {Phaser.Loader.File} file - The File object. - * @param {string} baseURL - A default base URL. - * - * @return {string} The URL the File will use. - */ -var GetURL = function (file, baseURL) -{ - if (!file.url) - { - return false; - } - - if (file.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) - { - return file.url; - } - else - { - return baseURL + file.url; - } -}; - -module.exports = GetURL; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Given a File and a baseURL value this returns the URL the File will use to download from. + * + * @function Phaser.Loader.GetURL + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - The File object. + * @param {string} baseURL - A default base URL. + * + * @return {string} The URL the File will use. + */ +var GetURL = function (file, baseURL) +{ + if (!file.url) + { + return false; + } + + if (file.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return file.url; + } + else + { + return baseURL + file.url; + } +}; + +module.exports = GetURL; diff --git a/src/loader/LoaderPlugin.js b/src/loader/LoaderPlugin.js index 36d12f177..8c6e84db1 100644 --- a/src/loader/LoaderPlugin.js +++ b/src/loader/LoaderPlugin.js @@ -1,1072 +1,1072 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CONST = require('./const'); -var CustomSet = require('../structs/Set'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var FileTypesManager = require('./FileTypesManager'); -var GetFastValue = require('../utils/object/GetFastValue'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); -var XHRSettings = require('./XHRSettings'); - -/** - * @classdesc - * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. - * You typically interact with it via `this.load` in your Scene. Scenes can have a `preload` method, which is always - * called before the Scenes `create` method, allowing you to preload assets that the Scene may need. - * - * If you call any `this.load` methods from outside of `Scene.preload` then you need to start the Loader going - * yourself by calling `Loader.start()`. It's only automatically started during the Scene preload. - * - * The Loader uses a combination of tag loading (eg. Audio elements) and XHR and provides progress and completion events. - * Files are loaded in parallel by default. The amount of concurrent connections can be controlled in your Game Configuration. - * - * Once the Loader has started loading you are still able to add files to it. These can be injected as a result of a loader - * event, the type of file being loaded (such as a pack file) or other external events. As long as the Loader hasn't finished - * simply adding a new file to it, while running, will ensure it's added into the current queue. - * - * Every Scene has its own instance of the Loader and they are bound to the Scene in which they are created. However, - * assets loaded by the Loader are placed into global game-level caches. For example, loading an XML file will place that - * file inside `Game.cache.xml`, which is accessible from every Scene in your game, no matter who was responsible - * for loading it. The same is true of Textures. A texture loaded in one Scene is instantly available to all other Scenes - * in your game. - * - * The Loader works by using custom File Types. These are stored in the FileTypesManager, which injects them into the Loader - * when it's instantiated. You can create your own custom file types by extending either the File or MultiFile classes. - * See those files for more details. - * - * @class LoaderPlugin - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Loader - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene which owns this Loader instance. - */ -var LoaderPlugin = new Class({ - - Extends: EventEmitter, - - initialize: - - function LoaderPlugin (scene) - { - EventEmitter.call(this); - - var gameConfig = scene.sys.game.config; - var sceneConfig = scene.sys.settings.loader; - - /** - * The Scene which owns this Loader instance. - * - * @name Phaser.Loader.LoaderPlugin#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene Systems. - * - * @name Phaser.Loader.LoaderPlugin#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * A reference to the global Cache Manager. - * - * @name Phaser.Loader.LoaderPlugin#cacheManager - * @type {Phaser.Cache.CacheManager} - * @since 3.7.0 - */ - this.cacheManager = scene.sys.cache; - - /** - * A reference to the global Texture Manager. - * - * @name Phaser.Loader.LoaderPlugin#textureManager - * @type {Phaser.Textures.TextureManager} - * @since 3.7.0 - */ - this.textureManager = scene.sys.textures; - - /** - * A reference to the global Scene Manager. - * - * @name Phaser.Loader.LoaderPlugin#sceneManager - * @type {Phaser.Scenes.SceneManager} - * @protected - * @since 3.16.0 - */ - this.sceneManager = scene.sys.game.scene; - - // Inject the available filetypes into the Loader - FileTypesManager.install(this); - - /** - * An optional prefix that is automatically prepended to the start of every file key. - * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. - * You can set this directly, or call `Loader.setPrefix()`. 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. - * - * @name Phaser.Loader.LoaderPlugin#prefix - * @type {string} - * @default '' - * @since 3.7.0 - */ - this.prefix = ''; - - /** - * 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 - */ - this.path = ''; - - /** - * If you want to append a URL before the path of any asset you can set this here. - * - * Useful if allowing the asset base url to be configured outside of the game code. - * - * If you set this property directly then it _must_ end with a "/". Alternatively, call `setBaseURL()` and it'll do it for you. - * - * @name Phaser.Loader.LoaderPlugin#baseURL - * @type {string} - * @default '' - * @since 3.0.0 - */ - this.baseURL = ''; - - this.setBaseURL(GetFastValue(sceneConfig, 'baseURL', gameConfig.loaderBaseURL)); - - this.setPath(GetFastValue(sceneConfig, 'path', gameConfig.loaderPath)); - - this.setPrefix(GetFastValue(sceneConfig, 'prefix', gameConfig.loaderPrefix)); - - /** - * The number of concurrent / parallel resources to try and fetch at once. - * - * Old browsers limit 6 requests per domain; modern ones, especially those with HTTP/2 don't limit it at all. - * - * The default is 32 but you can change this in your Game Config, or by changing this property before the Loader starts. - * - * @name Phaser.Loader.LoaderPlugin#maxParallelDownloads - * @type {integer} - * @since 3.0.0 - */ - this.maxParallelDownloads = GetFastValue(sceneConfig, 'maxParallelDownloads', gameConfig.loaderMaxParallelDownloads); - - /** - * xhr specific global settings (can be overridden on a per-file basis) - * - * @name Phaser.Loader.LoaderPlugin#xhr - * @type {Phaser.Types.Loader.XHRSettingsObject} - * @since 3.0.0 - */ - this.xhr = XHRSettings( - GetFastValue(sceneConfig, 'responseType', gameConfig.loaderResponseType), - GetFastValue(sceneConfig, 'async', gameConfig.loaderAsync), - GetFastValue(sceneConfig, 'user', gameConfig.loaderUser), - GetFastValue(sceneConfig, 'password', gameConfig.loaderPassword), - GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout), - GetFastValue(sceneConfig, 'withCredentials', gameConfig.loaderWithCredentials) - ); - - /** - * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. - * - * @name Phaser.Loader.LoaderPlugin#crossOrigin - * @type {string} - * @since 3.0.0 - */ - this.crossOrigin = GetFastValue(sceneConfig, 'crossOrigin', gameConfig.loaderCrossOrigin); - - /** - * The total number of files to load. It may not always be accurate because you may add to the Loader during the process - * of loading, especially if you load a Pack File. Therefore this value can change, but in most cases remains static. - * - * @name Phaser.Loader.LoaderPlugin#totalToLoad - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.totalToLoad = 0; - - /** - * The progress of the current load queue, as a float value between 0 and 1. - * This is updated automatically as files complete loading. - * Note that it is possible for this value to go down again if you add content to the current load queue during a load. - * - * @name Phaser.Loader.LoaderPlugin#progress - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.progress = 0; - - /** - * Files are placed in this Set when they're added to the Loader via `addFile`. - * - * They are moved to the `inflight` Set when they start loading, and assuming a successful - * load, to the `queue` Set for further processing. - * - * By the end of the load process this Set will be empty. - * - * @name Phaser.Loader.LoaderPlugin#list - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.list = new CustomSet(); - - /** - * Files are stored in this Set while they're in the process of being loaded. - * - * Upon a successful load they are moved to the `queue` Set. - * - * By the end of the load process this Set will be empty. - * - * @name Phaser.Loader.LoaderPlugin#inflight - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.inflight = new CustomSet(); - - /** - * Files are stored in this Set while they're being processed. - * - * If the process is successful they are moved to their final destination, which could be - * a Cache or the Texture Manager. - * - * At the end of the load process this Set will be empty. - * - * @name Phaser.Loader.LoaderPlugin#queue - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.queue = new CustomSet(); - - /** - * A temporary Set in which files are stored after processing, - * awaiting destruction at the end of the load process. - * - * @name Phaser.Loader.LoaderPlugin#_deleteQueue - * @type {Phaser.Structs.Set.} - * @private - * @since 3.7.0 - */ - this._deleteQueue = new CustomSet(); - - /** - * The total number of files that failed to load during the most recent load. - * This value is reset when you call `Loader.start`. - * - * @name Phaser.Loader.LoaderPlugin#totalFailed - * @type {integer} - * @default 0 - * @since 3.7.0 - */ - this.totalFailed = 0; - - /** - * The total number of files that successfully loaded during the most recent load. - * This value is reset when you call `Loader.start`. - * - * @name Phaser.Loader.LoaderPlugin#totalComplete - * @type {integer} - * @default 0 - * @since 3.7.0 - */ - this.totalComplete = 0; - - /** - * The current state of the Loader. - * - * @name Phaser.Loader.LoaderPlugin#state - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.state = CONST.LOADER_IDLE; - - /** - * The current index being used by multi-file loaders to avoid key clashes. - * - * @name Phaser.Loader.LoaderPlugin#multiKeyIndex - * @type {integer} - * @private - * @since 3.20.0 - */ - this.multiKeyIndex = 0; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.pluginStart, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Loader.LoaderPlugin#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Loader.LoaderPlugin#pluginStart - * @private - * @since 3.5.1 - */ - pluginStart: function () - { - this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * If you want to append a URL before the path of any asset you can set this here. - * - * Useful if allowing the asset base url to be configured outside of the game code. - * - * Once a base URL is set it will affect every file loaded by the Loader from that point on. It does _not_ change any - * file _already_ being loaded. To reset it, call this method with no arguments. - * - * @method Phaser.Loader.LoaderPlugin#setBaseURL - * @since 3.0.0 - * - * @param {string} [url] - The URL to use. Leave empty to reset. - * - * @return {this} This Loader object. - */ - setBaseURL: function (url) - { - if (url === undefined) { url = ''; } - - if (url !== '' && url.substr(-1) !== '/') - { - url = url.concat('/'); - } - - this.baseURL = url; - - return this; - }, - - /** - * 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. - */ - setPath: function (path) - { - if (path === undefined) { path = ''; } - - if (path !== '' && path.substr(-1) !== '/') - { - path = path.concat('/'); - } - - this.path = path; - - return this; - }, - - /** - * An optional prefix that is automatically prepended to the start of every file key. - * - * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. - * - * Once a prefix 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#setPrefix - * @since 3.7.0 - * - * @param {string} [prefix] - The prefix to use. Leave empty to reset. - * - * @return {this} This Loader object. - */ - setPrefix: function (prefix) - { - if (prefix === undefined) { prefix = ''; } - - this.prefix = prefix; - - return this; - }, - - /** - * 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. - */ - setCORS: function (crossOrigin) - { - this.crossOrigin = crossOrigin; - - return this; - }, - - /** - * Adds a file, or array of files, into the load queue. - * - * The file must be an instance of `Phaser.Loader.File`, or a class that extends it. The Loader will check that the key - * used by the file won't conflict with any other key either in the loader, the inflight queue or the target cache. - * If allowed it will then add the file into the pending list, read for the load to start. Or, if the load has already - * started, ready for the next batch of files to be pulled from the list to the inflight queue. - * - * You should not normally call this method directly, but rather use one of the Loader methods like `image` or `atlas`, - * however you can call this as long as the file given to it is well formed. - * - * @method Phaser.Loader.LoaderPlugin#addFile - * @fires Phaser.Loader.Events#ADD - * @since 3.0.0 - * - * @param {(Phaser.Loader.File|Phaser.Loader.File[])} file - The file, or array of files, to be added to the load queue. - */ - addFile: function (file) - { - if (!Array.isArray(file)) - { - file = [ file ]; - } - - for (var i = 0; i < file.length; i++) - { - var item = file[i]; - - // 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 (!this.keyExists(item)) - { - this.list.set(item); - - this.emit(Events.ADD, item.key, item.type, this, item); - - if (this.isLoading()) - { - this.totalToLoad++; - this.updateProgress(); - } - } - } - }, - - /** - * Checks the key and type of the given file to see if it will conflict with anything already - * in a Cache, the Texture Manager, or the list or inflight queues. - * - * @method Phaser.Loader.LoaderPlugin#keyExists - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The file to check the key of. - * - * @return {boolean} `true` if adding this file will cause a cache or queue conflict, otherwise `false`. - */ - keyExists: function (file) - { - var keyConflict = file.hasCacheConflict(); - - if (!keyConflict) - { - this.list.iterate(function (item) - { - if (item.type === file.type && item.key === file.key) - { - keyConflict = true; - - return false; - } - - }); - } - - if (!keyConflict && this.isLoading()) - { - this.inflight.iterate(function (item) - { - if (item.type === file.type && item.key === file.key) - { - keyConflict = true; - - return false; - } - - }); - - this.queue.iterate(function (item) - { - if (item.type === file.type && item.key === file.key) - { - keyConflict = true; - - return false; - } - - }); - } - - return keyConflict; - }, - - /** - * Takes a well formed, fully parsed pack file object and adds its entries into the load queue. Usually you do not call - * this method directly, but instead use `Loader.pack` and supply a path to a JSON file that holds the - * pack data. However, if you've got the data prepared you can pass it to this method. - * - * You can also provide an optional key. If you do then it will only add the entries from that part of the pack into - * to the load queue. If not specified it will add all entries it finds. For more details about the pack file format - * see the `LoaderPlugin.pack` method. - * - * @method Phaser.Loader.LoaderPlugin#addPack - * @since 3.7.0 - * - * @param {any} data - The Pack File data to be parsed and each entry of it to added to the load queue. - * @param {string} [packKey] - An optional key to use from the pack file data. - * - * @return {boolean} `true` if any files were added to the queue, otherwise `false`. - */ - addPack: function (pack, packKey) - { - // if no packKey provided we'll add everything to the queue - if (packKey && pack.hasOwnProperty(packKey)) - { - pack = { packKey: pack[packKey] }; - } - - var total = 0; - - // Store the loader settings in case this pack replaces them - var currentBaseURL = this.baseURL; - var currentPath = this.path; - var currentPrefix = this.prefix; - - // Here we go ... - for (var key in pack) - { - var config = pack[key]; - - // Any meta data to process? - var baseURL = GetFastValue(config, 'baseURL', currentBaseURL); - var path = GetFastValue(config, 'path', currentPath); - var prefix = GetFastValue(config, 'prefix', currentPrefix); - var files = GetFastValue(config, 'files', null); - var defaultType = GetFastValue(config, 'defaultType', 'void'); - - if (Array.isArray(files)) - { - this.setBaseURL(baseURL); - this.setPath(path); - this.setPrefix(prefix); - - for (var i = 0; i < files.length; i++) - { - var file = files[i]; - var type = (file.hasOwnProperty('type')) ? file.type : defaultType; - - if (this[type]) - { - this[type](file); - total++; - } - } - } - } - - // Reset the loader settings - this.setBaseURL(currentBaseURL); - this.setPath(currentPath); - this.setPrefix(currentPrefix); - - return (total > 0); - }, - - /** - * Is the Loader actively loading, or processing loaded files? - * - * @method Phaser.Loader.LoaderPlugin#isLoading - * @since 3.0.0 - * - * @return {boolean} `true` if the Loader is busy loading or processing, otherwise `false`. - */ - isLoading: function () - { - return (this.state === CONST.LOADER_LOADING || this.state === CONST.LOADER_PROCESSING); - }, - - /** - * Is the Loader ready to start a new load? - * - * @method Phaser.Loader.LoaderPlugin#isReady - * @since 3.0.0 - * - * @return {boolean} `true` if the Loader is ready to start a new load, otherwise `false`. - */ - isReady: function () - { - return (this.state === CONST.LOADER_IDLE || this.state === CONST.LOADER_COMPLETE); - }, - - /** - * Starts the Loader running. This will reset the progress and totals and then emit a `start` event. - * If there is nothing in the queue the Loader will immediately complete, otherwise it will start - * loading the first batch of files. - * - * The Loader is started automatically if the queue is populated within your Scenes `preload` method. - * - * However, outside of this, you need to call this method to start it. - * - * If the Loader is already running this method will simply return. - * - * @method Phaser.Loader.LoaderPlugin#start - * @fires Phaser.Loader.Events#START - * @since 3.0.0 - */ - start: function () - { - if (!this.isReady()) - { - return; - } - - this.progress = 0; - - this.totalFailed = 0; - this.totalComplete = 0; - this.totalToLoad = this.list.size; - - this.emit(Events.START, this); - - if (this.list.size === 0) - { - this.loadComplete(); - } - else - { - this.state = CONST.LOADER_LOADING; - - this.inflight.clear(); - this.queue.clear(); - - this.updateProgress(); - - this.checkLoadQueue(); - - this.systems.events.on(SceneEvents.UPDATE, this.update, this); - } - }, - - /** - * Called automatically during the load process. - * It updates the `progress` value and then emits a progress event, which you can use to - * display a loading bar in your game. - * - * @method Phaser.Loader.LoaderPlugin#updateProgress - * @fires Phaser.Loader.Events#PROGRESS - * @since 3.0.0 - */ - updateProgress: function () - { - this.progress = 1 - ((this.list.size + this.inflight.size) / this.totalToLoad); - - this.emit(Events.PROGRESS, this.progress); - }, - - /** - * Called automatically during the load process. - * - * @method Phaser.Loader.LoaderPlugin#update - * @since 3.10.0 - */ - update: function () - { - if (this.state === CONST.LOADER_LOADING && this.list.size > 0 && this.inflight.size < this.maxParallelDownloads) - { - this.checkLoadQueue(); - } - }, - - /** - * An internal method called by the Loader. - * - * It will check to see if there are any more files in the pending list that need loading, and if so it will move - * them from the list Set into the inflight Set, set their CORs flag and start them loading. - * - * It will carrying on doing this for each file in the pending list until it runs out, or hits the max allowed parallel downloads. - * - * @method Phaser.Loader.LoaderPlugin#checkLoadQueue - * @private - * @since 3.7.0 - */ - checkLoadQueue: function () - { - this.list.each(function (file) - { - if (file.state === CONST.FILE_POPULATED || (file.state === CONST.FILE_PENDING && this.inflight.size < this.maxParallelDownloads)) - { - this.inflight.set(file); - - this.list.delete(file); - - // If the file doesn't have its own crossOrigin set, we'll use the Loaders (which is undefined by default) - if (!file.crossOrigin) - { - file.crossOrigin = this.crossOrigin; - } - - file.load(); - } - - if (this.inflight.size === this.maxParallelDownloads) - { - // Tells the Set iterator to abort - return false; - } - - }, this); - }, - - /** - * An internal method called automatically by the XHRLoader belong to a File. - * - * This method will remove the given file from the inflight Set and update the load progress. - * If the file was successful its `onProcess` method is called, otherwise it is added to the delete queue. - * - * @method Phaser.Loader.LoaderPlugin#nextFile - * @fires Phaser.Loader.Events#FILE_LOAD - * @fires Phaser.Loader.Events#FILE_LOAD_ERROR - * @since 3.0.0 - * - * @param {Phaser.Loader.File} file - The File that just finished loading, or errored during load. - * @param {boolean} success - `true` if the file loaded successfully, otherwise `false`. - */ - nextFile: function (file, success) - { - // Has the game been destroyed during load? If so, bail out now. - if (!this.inflight) - { - return; - } - - this.inflight.delete(file); - - this.updateProgress(); - - if (success) - { - this.totalComplete++; - - this.queue.set(file); - - this.emit(Events.FILE_LOAD, file); - - file.onProcess(); - } - else - { - this.totalFailed++; - - this._deleteQueue.set(file); - - this.emit(Events.FILE_LOAD_ERROR, file); - - this.fileProcessComplete(file); - } - }, - - /** - * An internal method that is called automatically by the File when it has finished processing. - * - * If the process was successful, and the File isn't part of a MultiFile, its `addToCache` method is called. - * - * It this then removed from the queue. If there are no more files to load `loadComplete` is called. - * - * @method Phaser.Loader.LoaderPlugin#fileProcessComplete - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The file that has finished processing. - */ - fileProcessComplete: function (file) - { - // Has the game been destroyed during load? If so, bail out now. - if (!this.scene || !this.systems || !this.systems.game || this.systems.game.pendingDestroy) - { - return; - } - - // This file has failed, so move it to the failed Set - if (file.state === CONST.FILE_ERRORED) - { - if (file.multiFile) - { - file.multiFile.onFileFailed(file); - } - } - else if (file.state === CONST.FILE_COMPLETE) - { - if (file.multiFile) - { - if (file.multiFile.isReadyToProcess()) - { - // If we got here then all files the link file needs are ready to add to the cache - file.multiFile.addToCache(); - } - } - else - { - // If we got here, then the file processed, so let it add itself to its cache - file.addToCache(); - } - } - - // Remove it from the queue - this.queue.delete(file); - - // Nothing left to do? - - if (this.list.size === 0 && this.inflight.size === 0 && this.queue.size === 0) - { - this.loadComplete(); - } - }, - - /** - * Called at the end when the load queue is exhausted and all files have either loaded or errored. - * By this point every loaded file will now be in its associated cache and ready for use. - * - * Also clears down the Sets, puts progress to 1 and clears the deletion queue. - * - * @method Phaser.Loader.LoaderPlugin#loadComplete - * @fires Phaser.Loader.Events#COMPLETE - * @fires Phaser.Loader.Events#POST_PROCESS - * @since 3.7.0 - */ - loadComplete: function () - { - this.emit(Events.POST_PROCESS, this); - - this.list.clear(); - this.inflight.clear(); - this.queue.clear(); - - this.progress = 1; - - this.state = CONST.LOADER_COMPLETE; - - this.systems.events.off(SceneEvents.UPDATE, this.update, this); - - // Call 'destroy' on each file ready for deletion - this._deleteQueue.iterateLocal('destroy'); - - this._deleteQueue.clear(); - - this.emit(Events.COMPLETE, this, this.totalComplete, this.totalFailed); - }, - - /** - * Adds a File into the pending-deletion queue. - * - * @method Phaser.Loader.LoaderPlugin#flagForRemoval - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The File to be queued for deletion when the Loader completes. - */ - flagForRemoval: function (file) - { - this._deleteQueue.set(file); - }, - - /** - * Converts the given JSON data into a file that the browser then prompts you to download so you can save it locally. - * - * The data must be well formed JSON and ready-parsed, not a JavaScript object. - * - * @method Phaser.Loader.LoaderPlugin#saveJSON - * @since 3.0.0 - * - * @param {*} data - The JSON data, ready parsed. - * @param {string} [filename=file.json] - The name to save the JSON file as. - * - * @return {this} This Loader plugin. - */ - saveJSON: function (data, filename) - { - return this.save(JSON.stringify(data), filename); - }, - - /** - * 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. - */ - save: function (data, filename, filetype) - { - if (filename === undefined) { filename = 'file.json'; } - if (filetype === undefined) { filetype = 'application/json'; } - - var blob = new Blob([ data ], { type: filetype }); - - var url = URL.createObjectURL(blob); - - var a = document.createElement('a'); - - a.download = filename; - a.textContent = 'Download ' + filename; - a.href = url; - a.click(); - - return this; - }, - - /** - * Resets the Loader. - * - * This will clear all lists and reset the base URL, path and prefix. - * - * Warning: If the Loader is currently downloading files, or has files in its queue, they will be aborted. - * - * @method Phaser.Loader.LoaderPlugin#reset - * @since 3.0.0 - */ - reset: function () - { - this.list.clear(); - this.inflight.clear(); - this.queue.clear(); - - var gameConfig = this.systems.game.config; - var sceneConfig = this.systems.settings.loader; - - this.setBaseURL(GetFastValue(sceneConfig, 'baseURL', gameConfig.loaderBaseURL)); - this.setPath(GetFastValue(sceneConfig, 'path', gameConfig.loaderPath)); - this.setPrefix(GetFastValue(sceneConfig, 'prefix', gameConfig.loaderPrefix)); - - this.state = CONST.LOADER_IDLE; - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Loader.LoaderPlugin#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - this.reset(); - - this.state = CONST.LOADER_SHUTDOWN; - - this.systems.events.off(SceneEvents.UPDATE, this.update, this); - this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Loader.LoaderPlugin#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.state = CONST.LOADER_DESTROYED; - - this.systems.events.off(SceneEvents.UPDATE, this.update, this); - this.systems.events.off(SceneEvents.START, this.pluginStart, this); - - this.list = null; - this.inflight = null; - this.queue = null; - - this.scene = null; - this.systems = null; - this.textureManager = null; - this.cacheManager = null; - this.sceneManager = null; - } - -}); - -PluginCache.register('Loader', LoaderPlugin, 'load'); - -module.exports = LoaderPlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CONST = require('./const'); +var CustomSet = require('../structs/Set'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var FileTypesManager = require('./FileTypesManager'); +var GetFastValue = require('../utils/object/GetFastValue'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); +var XHRSettings = require('./XHRSettings'); + +/** + * @classdesc + * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. + * You typically interact with it via `this.load` in your Scene. Scenes can have a `preload` method, which is always + * called before the Scenes `create` method, allowing you to preload assets that the Scene may need. + * + * If you call any `this.load` methods from outside of `Scene.preload` then you need to start the Loader going + * yourself by calling `Loader.start()`. It's only automatically started during the Scene preload. + * + * The Loader uses a combination of tag loading (eg. Audio elements) and XHR and provides progress and completion events. + * Files are loaded in parallel by default. The amount of concurrent connections can be controlled in your Game Configuration. + * + * Once the Loader has started loading you are still able to add files to it. These can be injected as a result of a loader + * event, the type of file being loaded (such as a pack file) or other external events. As long as the Loader hasn't finished + * simply adding a new file to it, while running, will ensure it's added into the current queue. + * + * Every Scene has its own instance of the Loader and they are bound to the Scene in which they are created. However, + * assets loaded by the Loader are placed into global game-level caches. For example, loading an XML file will place that + * file inside `Game.cache.xml`, which is accessible from every Scene in your game, no matter who was responsible + * for loading it. The same is true of Textures. A texture loaded in one Scene is instantly available to all other Scenes + * in your game. + * + * The Loader works by using custom File Types. These are stored in the FileTypesManager, which injects them into the Loader + * when it's instantiated. You can create your own custom file types by extending either the File or MultiFile classes. + * See those files for more details. + * + * @class LoaderPlugin + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Loader + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which owns this Loader instance. + */ +var LoaderPlugin = new Class({ + + Extends: EventEmitter, + + initialize: + + function LoaderPlugin (scene) + { + EventEmitter.call(this); + + var gameConfig = scene.sys.game.config; + var sceneConfig = scene.sys.settings.loader; + + /** + * The Scene which owns this Loader instance. + * + * @name Phaser.Loader.LoaderPlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems. + * + * @name Phaser.Loader.LoaderPlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A reference to the global Cache Manager. + * + * @name Phaser.Loader.LoaderPlugin#cacheManager + * @type {Phaser.Cache.CacheManager} + * @since 3.7.0 + */ + this.cacheManager = scene.sys.cache; + + /** + * A reference to the global Texture Manager. + * + * @name Phaser.Loader.LoaderPlugin#textureManager + * @type {Phaser.Textures.TextureManager} + * @since 3.7.0 + */ + this.textureManager = scene.sys.textures; + + /** + * A reference to the global Scene Manager. + * + * @name Phaser.Loader.LoaderPlugin#sceneManager + * @type {Phaser.Scenes.SceneManager} + * @protected + * @since 3.16.0 + */ + this.sceneManager = scene.sys.game.scene; + + // Inject the available filetypes into the Loader + FileTypesManager.install(this); + + /** + * An optional prefix that is automatically prepended to the start of every file key. + * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. + * You can set this directly, or call `Loader.setPrefix()`. 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. + * + * @name Phaser.Loader.LoaderPlugin#prefix + * @type {string} + * @default '' + * @since 3.7.0 + */ + this.prefix = ''; + + /** + * 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 + */ + this.path = ''; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * + * Useful if allowing the asset base url to be configured outside of the game code. + * + * If you set this property directly then it _must_ end with a "/". Alternatively, call `setBaseURL()` and it'll do it for you. + * + * @name Phaser.Loader.LoaderPlugin#baseURL + * @type {string} + * @default '' + * @since 3.0.0 + */ + this.baseURL = ''; + + this.setBaseURL(GetFastValue(sceneConfig, 'baseURL', gameConfig.loaderBaseURL)); + + this.setPath(GetFastValue(sceneConfig, 'path', gameConfig.loaderPath)); + + this.setPrefix(GetFastValue(sceneConfig, 'prefix', gameConfig.loaderPrefix)); + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Old browsers limit 6 requests per domain; modern ones, especially those with HTTP/2 don't limit it at all. + * + * The default is 32 but you can change this in your Game Config, or by changing this property before the Loader starts. + * + * @name Phaser.Loader.LoaderPlugin#maxParallelDownloads + * @type {integer} + * @since 3.0.0 + */ + this.maxParallelDownloads = GetFastValue(sceneConfig, 'maxParallelDownloads', gameConfig.loaderMaxParallelDownloads); + + /** + * xhr specific global settings (can be overridden on a per-file basis) + * + * @name Phaser.Loader.LoaderPlugin#xhr + * @type {Phaser.Types.Loader.XHRSettingsObject} + * @since 3.0.0 + */ + this.xhr = XHRSettings( + GetFastValue(sceneConfig, 'responseType', gameConfig.loaderResponseType), + GetFastValue(sceneConfig, 'async', gameConfig.loaderAsync), + GetFastValue(sceneConfig, 'user', gameConfig.loaderUser), + GetFastValue(sceneConfig, 'password', gameConfig.loaderPassword), + GetFastValue(sceneConfig, 'timeout', gameConfig.loaderTimeout), + GetFastValue(sceneConfig, 'withCredentials', gameConfig.loaderWithCredentials) + ); + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * + * @name Phaser.Loader.LoaderPlugin#crossOrigin + * @type {string} + * @since 3.0.0 + */ + this.crossOrigin = GetFastValue(sceneConfig, 'crossOrigin', gameConfig.loaderCrossOrigin); + + /** + * The total number of files to load. It may not always be accurate because you may add to the Loader during the process + * of loading, especially if you load a Pack File. Therefore this value can change, but in most cases remains static. + * + * @name Phaser.Loader.LoaderPlugin#totalToLoad + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.totalToLoad = 0; + + /** + * The progress of the current load queue, as a float value between 0 and 1. + * This is updated automatically as files complete loading. + * Note that it is possible for this value to go down again if you add content to the current load queue during a load. + * + * @name Phaser.Loader.LoaderPlugin#progress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.progress = 0; + + /** + * Files are placed in this Set when they're added to the Loader via `addFile`. + * + * They are moved to the `inflight` Set when they start loading, and assuming a successful + * load, to the `queue` Set for further processing. + * + * By the end of the load process this Set will be empty. + * + * @name Phaser.Loader.LoaderPlugin#list + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.list = new CustomSet(); + + /** + * Files are stored in this Set while they're in the process of being loaded. + * + * Upon a successful load they are moved to the `queue` Set. + * + * By the end of the load process this Set will be empty. + * + * @name Phaser.Loader.LoaderPlugin#inflight + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.inflight = new CustomSet(); + + /** + * Files are stored in this Set while they're being processed. + * + * If the process is successful they are moved to their final destination, which could be + * a Cache or the Texture Manager. + * + * At the end of the load process this Set will be empty. + * + * @name Phaser.Loader.LoaderPlugin#queue + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.queue = new CustomSet(); + + /** + * A temporary Set in which files are stored after processing, + * awaiting destruction at the end of the load process. + * + * @name Phaser.Loader.LoaderPlugin#_deleteQueue + * @type {Phaser.Structs.Set.} + * @private + * @since 3.7.0 + */ + this._deleteQueue = new CustomSet(); + + /** + * The total number of files that failed to load during the most recent load. + * This value is reset when you call `Loader.start`. + * + * @name Phaser.Loader.LoaderPlugin#totalFailed + * @type {integer} + * @default 0 + * @since 3.7.0 + */ + this.totalFailed = 0; + + /** + * The total number of files that successfully loaded during the most recent load. + * This value is reset when you call `Loader.start`. + * + * @name Phaser.Loader.LoaderPlugin#totalComplete + * @type {integer} + * @default 0 + * @since 3.7.0 + */ + this.totalComplete = 0; + + /** + * The current state of the Loader. + * + * @name Phaser.Loader.LoaderPlugin#state + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.state = CONST.LOADER_IDLE; + + /** + * The current index being used by multi-file loaders to avoid key clashes. + * + * @name Phaser.Loader.LoaderPlugin#multiKeyIndex + * @type {integer} + * @private + * @since 3.20.0 + */ + this.multiKeyIndex = 0; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.pluginStart, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Loader.LoaderPlugin#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Loader.LoaderPlugin#pluginStart + * @private + * @since 3.5.1 + */ + pluginStart: function () + { + this.systems.events.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * If you want to append a URL before the path of any asset you can set this here. + * + * Useful if allowing the asset base url to be configured outside of the game code. + * + * Once a base URL is set it will affect every file loaded by the Loader from that point on. It does _not_ change any + * file _already_ being loaded. To reset it, call this method with no arguments. + * + * @method Phaser.Loader.LoaderPlugin#setBaseURL + * @since 3.0.0 + * + * @param {string} [url] - The URL to use. Leave empty to reset. + * + * @return {this} This Loader object. + */ + setBaseURL: function (url) + { + if (url === undefined) { url = ''; } + + if (url !== '' && url.substr(-1) !== '/') + { + url = url.concat('/'); + } + + this.baseURL = url; + + return this; + }, + + /** + * 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. + */ + setPath: function (path) + { + if (path === undefined) { path = ''; } + + if (path !== '' && path.substr(-1) !== '/') + { + path = path.concat('/'); + } + + this.path = path; + + return this; + }, + + /** + * An optional prefix that is automatically prepended to the start of every file key. + * + * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. + * + * Once a prefix 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#setPrefix + * @since 3.7.0 + * + * @param {string} [prefix] - The prefix to use. Leave empty to reset. + * + * @return {this} This Loader object. + */ + setPrefix: function (prefix) + { + if (prefix === undefined) { prefix = ''; } + + this.prefix = prefix; + + return this; + }, + + /** + * 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. + */ + setCORS: function (crossOrigin) + { + this.crossOrigin = crossOrigin; + + return this; + }, + + /** + * Adds a file, or array of files, into the load queue. + * + * The file must be an instance of `Phaser.Loader.File`, or a class that extends it. The Loader will check that the key + * used by the file won't conflict with any other key either in the loader, the inflight queue or the target cache. + * If allowed it will then add the file into the pending list, read for the load to start. Or, if the load has already + * started, ready for the next batch of files to be pulled from the list to the inflight queue. + * + * You should not normally call this method directly, but rather use one of the Loader methods like `image` or `atlas`, + * however you can call this as long as the file given to it is well formed. + * + * @method Phaser.Loader.LoaderPlugin#addFile + * @fires Phaser.Loader.Events#ADD + * @since 3.0.0 + * + * @param {(Phaser.Loader.File|Phaser.Loader.File[])} file - The file, or array of files, to be added to the load queue. + */ + addFile: function (file) + { + if (!Array.isArray(file)) + { + file = [ file ]; + } + + for (var i = 0; i < file.length; i++) + { + var item = file[i]; + + // 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 (!this.keyExists(item)) + { + this.list.set(item); + + this.emit(Events.ADD, item.key, item.type, this, item); + + if (this.isLoading()) + { + this.totalToLoad++; + this.updateProgress(); + } + } + } + }, + + /** + * Checks the key and type of the given file to see if it will conflict with anything already + * in a Cache, the Texture Manager, or the list or inflight queues. + * + * @method Phaser.Loader.LoaderPlugin#keyExists + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The file to check the key of. + * + * @return {boolean} `true` if adding this file will cause a cache or queue conflict, otherwise `false`. + */ + keyExists: function (file) + { + var keyConflict = file.hasCacheConflict(); + + if (!keyConflict) + { + this.list.iterate(function (item) + { + if (item.type === file.type && item.key === file.key) + { + keyConflict = true; + + return false; + } + + }); + } + + if (!keyConflict && this.isLoading()) + { + this.inflight.iterate(function (item) + { + if (item.type === file.type && item.key === file.key) + { + keyConflict = true; + + return false; + } + + }); + + this.queue.iterate(function (item) + { + if (item.type === file.type && item.key === file.key) + { + keyConflict = true; + + return false; + } + + }); + } + + return keyConflict; + }, + + /** + * Takes a well formed, fully parsed pack file object and adds its entries into the load queue. Usually you do not call + * this method directly, but instead use `Loader.pack` and supply a path to a JSON file that holds the + * pack data. However, if you've got the data prepared you can pass it to this method. + * + * You can also provide an optional key. If you do then it will only add the entries from that part of the pack into + * to the load queue. If not specified it will add all entries it finds. For more details about the pack file format + * see the `LoaderPlugin.pack` method. + * + * @method Phaser.Loader.LoaderPlugin#addPack + * @since 3.7.0 + * + * @param {any} data - The Pack File data to be parsed and each entry of it to added to the load queue. + * @param {string} [packKey] - An optional key to use from the pack file data. + * + * @return {boolean} `true` if any files were added to the queue, otherwise `false`. + */ + addPack: function (pack, packKey) + { + // if no packKey provided we'll add everything to the queue + if (packKey && pack.hasOwnProperty(packKey)) + { + pack = { packKey: pack[packKey] }; + } + + var total = 0; + + // Store the loader settings in case this pack replaces them + var currentBaseURL = this.baseURL; + var currentPath = this.path; + var currentPrefix = this.prefix; + + // Here we go ... + for (var key in pack) + { + var config = pack[key]; + + // Any meta data to process? + var baseURL = GetFastValue(config, 'baseURL', currentBaseURL); + var path = GetFastValue(config, 'path', currentPath); + var prefix = GetFastValue(config, 'prefix', currentPrefix); + var files = GetFastValue(config, 'files', null); + var defaultType = GetFastValue(config, 'defaultType', 'void'); + + if (Array.isArray(files)) + { + this.setBaseURL(baseURL); + this.setPath(path); + this.setPrefix(prefix); + + for (var i = 0; i < files.length; i++) + { + var file = files[i]; + var type = (file.hasOwnProperty('type')) ? file.type : defaultType; + + if (this[type]) + { + this[type](file); + total++; + } + } + } + } + + // Reset the loader settings + this.setBaseURL(currentBaseURL); + this.setPath(currentPath); + this.setPrefix(currentPrefix); + + return (total > 0); + }, + + /** + * Is the Loader actively loading, or processing loaded files? + * + * @method Phaser.Loader.LoaderPlugin#isLoading + * @since 3.0.0 + * + * @return {boolean} `true` if the Loader is busy loading or processing, otherwise `false`. + */ + isLoading: function () + { + return (this.state === CONST.LOADER_LOADING || this.state === CONST.LOADER_PROCESSING); + }, + + /** + * Is the Loader ready to start a new load? + * + * @method Phaser.Loader.LoaderPlugin#isReady + * @since 3.0.0 + * + * @return {boolean} `true` if the Loader is ready to start a new load, otherwise `false`. + */ + isReady: function () + { + return (this.state === CONST.LOADER_IDLE || this.state === CONST.LOADER_COMPLETE); + }, + + /** + * Starts the Loader running. This will reset the progress and totals and then emit a `start` event. + * If there is nothing in the queue the Loader will immediately complete, otherwise it will start + * loading the first batch of files. + * + * The Loader is started automatically if the queue is populated within your Scenes `preload` method. + * + * However, outside of this, you need to call this method to start it. + * + * If the Loader is already running this method will simply return. + * + * @method Phaser.Loader.LoaderPlugin#start + * @fires Phaser.Loader.Events#START + * @since 3.0.0 + */ + start: function () + { + if (!this.isReady()) + { + return; + } + + this.progress = 0; + + this.totalFailed = 0; + this.totalComplete = 0; + this.totalToLoad = this.list.size; + + this.emit(Events.START, this); + + if (this.list.size === 0) + { + this.loadComplete(); + } + else + { + this.state = CONST.LOADER_LOADING; + + this.inflight.clear(); + this.queue.clear(); + + this.updateProgress(); + + this.checkLoadQueue(); + + this.systems.events.on(SceneEvents.UPDATE, this.update, this); + } + }, + + /** + * Called automatically during the load process. + * It updates the `progress` value and then emits a progress event, which you can use to + * display a loading bar in your game. + * + * @method Phaser.Loader.LoaderPlugin#updateProgress + * @fires Phaser.Loader.Events#PROGRESS + * @since 3.0.0 + */ + updateProgress: function () + { + this.progress = 1 - ((this.list.size + this.inflight.size) / this.totalToLoad); + + this.emit(Events.PROGRESS, this.progress); + }, + + /** + * Called automatically during the load process. + * + * @method Phaser.Loader.LoaderPlugin#update + * @since 3.10.0 + */ + update: function () + { + if (this.state === CONST.LOADER_LOADING && this.list.size > 0 && this.inflight.size < this.maxParallelDownloads) + { + this.checkLoadQueue(); + } + }, + + /** + * An internal method called by the Loader. + * + * It will check to see if there are any more files in the pending list that need loading, and if so it will move + * them from the list Set into the inflight Set, set their CORs flag and start them loading. + * + * It will carrying on doing this for each file in the pending list until it runs out, or hits the max allowed parallel downloads. + * + * @method Phaser.Loader.LoaderPlugin#checkLoadQueue + * @private + * @since 3.7.0 + */ + checkLoadQueue: function () + { + this.list.each(function (file) + { + if (file.state === CONST.FILE_POPULATED || (file.state === CONST.FILE_PENDING && this.inflight.size < this.maxParallelDownloads)) + { + this.inflight.set(file); + + this.list.delete(file); + + // If the file doesn't have its own crossOrigin set, we'll use the Loaders (which is undefined by default) + if (!file.crossOrigin) + { + file.crossOrigin = this.crossOrigin; + } + + file.load(); + } + + if (this.inflight.size === this.maxParallelDownloads) + { + // Tells the Set iterator to abort + return false; + } + + }, this); + }, + + /** + * An internal method called automatically by the XHRLoader belong to a File. + * + * This method will remove the given file from the inflight Set and update the load progress. + * If the file was successful its `onProcess` method is called, otherwise it is added to the delete queue. + * + * @method Phaser.Loader.LoaderPlugin#nextFile + * @fires Phaser.Loader.Events#FILE_LOAD + * @fires Phaser.Loader.Events#FILE_LOAD_ERROR + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - The File that just finished loading, or errored during load. + * @param {boolean} success - `true` if the file loaded successfully, otherwise `false`. + */ + nextFile: function (file, success) + { + // Has the game been destroyed during load? If so, bail out now. + if (!this.inflight) + { + return; + } + + this.inflight.delete(file); + + this.updateProgress(); + + if (success) + { + this.totalComplete++; + + this.queue.set(file); + + this.emit(Events.FILE_LOAD, file); + + file.onProcess(); + } + else + { + this.totalFailed++; + + this._deleteQueue.set(file); + + this.emit(Events.FILE_LOAD_ERROR, file); + + this.fileProcessComplete(file); + } + }, + + /** + * An internal method that is called automatically by the File when it has finished processing. + * + * If the process was successful, and the File isn't part of a MultiFile, its `addToCache` method is called. + * + * It this then removed from the queue. If there are no more files to load `loadComplete` is called. + * + * @method Phaser.Loader.LoaderPlugin#fileProcessComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The file that has finished processing. + */ + fileProcessComplete: function (file) + { + // Has the game been destroyed during load? If so, bail out now. + if (!this.scene || !this.systems || !this.systems.game || this.systems.game.pendingDestroy) + { + return; + } + + // This file has failed, so move it to the failed Set + if (file.state === CONST.FILE_ERRORED) + { + if (file.multiFile) + { + file.multiFile.onFileFailed(file); + } + } + else if (file.state === CONST.FILE_COMPLETE) + { + if (file.multiFile) + { + if (file.multiFile.isReadyToProcess()) + { + // If we got here then all files the link file needs are ready to add to the cache + file.multiFile.addToCache(); + } + } + else + { + // If we got here, then the file processed, so let it add itself to its cache + file.addToCache(); + } + } + + // Remove it from the queue + this.queue.delete(file); + + // Nothing left to do? + + if (this.list.size === 0 && this.inflight.size === 0 && this.queue.size === 0) + { + this.loadComplete(); + } + }, + + /** + * Called at the end when the load queue is exhausted and all files have either loaded or errored. + * By this point every loaded file will now be in its associated cache and ready for use. + * + * Also clears down the Sets, puts progress to 1 and clears the deletion queue. + * + * @method Phaser.Loader.LoaderPlugin#loadComplete + * @fires Phaser.Loader.Events#COMPLETE + * @fires Phaser.Loader.Events#POST_PROCESS + * @since 3.7.0 + */ + loadComplete: function () + { + this.emit(Events.POST_PROCESS, this); + + this.list.clear(); + this.inflight.clear(); + this.queue.clear(); + + this.progress = 1; + + this.state = CONST.LOADER_COMPLETE; + + this.systems.events.off(SceneEvents.UPDATE, this.update, this); + + // Call 'destroy' on each file ready for deletion + this._deleteQueue.iterateLocal('destroy'); + + this._deleteQueue.clear(); + + this.emit(Events.COMPLETE, this, this.totalComplete, this.totalFailed); + }, + + /** + * Adds a File into the pending-deletion queue. + * + * @method Phaser.Loader.LoaderPlugin#flagForRemoval + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File to be queued for deletion when the Loader completes. + */ + flagForRemoval: function (file) + { + this._deleteQueue.set(file); + }, + + /** + * Converts the given JSON data into a file that the browser then prompts you to download so you can save it locally. + * + * The data must be well formed JSON and ready-parsed, not a JavaScript object. + * + * @method Phaser.Loader.LoaderPlugin#saveJSON + * @since 3.0.0 + * + * @param {*} data - The JSON data, ready parsed. + * @param {string} [filename=file.json] - The name to save the JSON file as. + * + * @return {this} This Loader plugin. + */ + saveJSON: function (data, filename) + { + return this.save(JSON.stringify(data), filename); + }, + + /** + * 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. + */ + save: function (data, filename, filetype) + { + if (filename === undefined) { filename = 'file.json'; } + if (filetype === undefined) { filetype = 'application/json'; } + + var blob = new Blob([ data ], { type: filetype }); + + var url = URL.createObjectURL(blob); + + var a = document.createElement('a'); + + a.download = filename; + a.textContent = 'Download ' + filename; + a.href = url; + a.click(); + + return this; + }, + + /** + * Resets the Loader. + * + * This will clear all lists and reset the base URL, path and prefix. + * + * Warning: If the Loader is currently downloading files, or has files in its queue, they will be aborted. + * + * @method Phaser.Loader.LoaderPlugin#reset + * @since 3.0.0 + */ + reset: function () + { + this.list.clear(); + this.inflight.clear(); + this.queue.clear(); + + var gameConfig = this.systems.game.config; + var sceneConfig = this.systems.settings.loader; + + this.setBaseURL(GetFastValue(sceneConfig, 'baseURL', gameConfig.loaderBaseURL)); + this.setPath(GetFastValue(sceneConfig, 'path', gameConfig.loaderPath)); + this.setPrefix(GetFastValue(sceneConfig, 'prefix', gameConfig.loaderPrefix)); + + this.state = CONST.LOADER_IDLE; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Loader.LoaderPlugin#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + this.reset(); + + this.state = CONST.LOADER_SHUTDOWN; + + this.systems.events.off(SceneEvents.UPDATE, this.update, this); + this.systems.events.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Loader.LoaderPlugin#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.state = CONST.LOADER_DESTROYED; + + this.systems.events.off(SceneEvents.UPDATE, this.update, this); + this.systems.events.off(SceneEvents.START, this.pluginStart, this); + + this.list = null; + this.inflight = null; + this.queue = null; + + this.scene = null; + this.systems = null; + this.textureManager = null; + this.cacheManager = null; + this.sceneManager = null; + } + +}); + +PluginCache.register('Loader', LoaderPlugin, 'load'); + +module.exports = LoaderPlugin; diff --git a/src/loader/MergeXHRSettings.js b/src/loader/MergeXHRSettings.js index 62ca3671b..dee8c057d 100644 --- a/src/loader/MergeXHRSettings.js +++ b/src/loader/MergeXHRSettings.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Extend = require('../utils/object/Extend'); -var XHRSettings = require('./XHRSettings'); - -/** - * Takes two XHRSettings Objects and creates a new XHRSettings object from them. - * - * The new object is seeded by the values given in the global settings, but any setting in - * the local object overrides the global ones. - * - * @function Phaser.Loader.MergeXHRSettings - * @since 3.0.0 - * - * @param {Phaser.Types.Loader.XHRSettingsObject} global - The global XHRSettings object. - * @param {Phaser.Types.Loader.XHRSettingsObject} local - The local XHRSettings object. - * - * @return {Phaser.Types.Loader.XHRSettingsObject} A newly formed XHRSettings object. - */ -var MergeXHRSettings = function (global, local) -{ - var output = (global === undefined) ? XHRSettings() : Extend({}, global); - - if (local) - { - for (var setting in local) - { - if (local[setting] !== undefined) - { - output[setting] = local[setting]; - } - } - } - - return output; -}; - -module.exports = MergeXHRSettings; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = require('../utils/object/Extend'); +var XHRSettings = require('./XHRSettings'); + +/** + * Takes two XHRSettings Objects and creates a new XHRSettings object from them. + * + * The new object is seeded by the values given in the global settings, but any setting in + * the local object overrides the global ones. + * + * @function Phaser.Loader.MergeXHRSettings + * @since 3.0.0 + * + * @param {Phaser.Types.Loader.XHRSettingsObject} global - The global XHRSettings object. + * @param {Phaser.Types.Loader.XHRSettingsObject} local - The local XHRSettings object. + * + * @return {Phaser.Types.Loader.XHRSettingsObject} A newly formed XHRSettings object. + */ +var MergeXHRSettings = function (global, local) +{ + var output = (global === undefined) ? XHRSettings() : Extend({}, global); + + if (local) + { + for (var setting in local) + { + if (local[setting] !== undefined) + { + output[setting] = local[setting]; + } + } + } + + return output; +}; + +module.exports = MergeXHRSettings; diff --git a/src/loader/MultiFile.js b/src/loader/MultiFile.js index 5eb37bf3d..33011853c 100644 --- a/src/loader/MultiFile.js +++ b/src/loader/MultiFile.js @@ -1,228 +1,228 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A MultiFile is a special kind of parent that contains two, or more, Files as children and looks after - * the loading and processing of them all. It is commonly extended and used as a base class for file types such as AtlasJSON or BitmapFont. - * - * You shouldn't create an instance of a MultiFile directly, but should extend it with your own class, setting a custom type and processing methods. - * - * @class MultiFile - * @memberof Phaser.Loader - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File. - * @param {string} type - The file type string for sorting within the Loader. - * @param {string} key - The key of the file within the loader. - * @param {Phaser.Loader.File[]} files - An array of Files that make-up this MultiFile. - */ -var MultiFile = new Class({ - - initialize: - - function MultiFile (loader, type, key, files) - { - /** - * A reference to the Loader that is going to load this file. - * - * @name Phaser.Loader.MultiFile#loader - * @type {Phaser.Loader.LoaderPlugin} - * @since 3.7.0 - */ - this.loader = loader; - - /** - * The file type string for sorting within the Loader. - * - * @name Phaser.Loader.MultiFile#type - * @type {string} - * @since 3.7.0 - */ - this.type = type; - - /** - * Unique cache key (unique within its file type) - * - * @name Phaser.Loader.MultiFile#key - * @type {string} - * @since 3.7.0 - */ - this.key = key; - - /** - * The current index being used by multi-file loaders to avoid key clashes. - * - * @name Phaser.Loader.MultiFile#multiKeyIndex - * @type {integer} - * @private - * @since 3.20.0 - */ - this.multiKeyIndex = loader.multiKeyIndex++; - - /** - * Array of files that make up this MultiFile. - * - * @name Phaser.Loader.MultiFile#files - * @type {Phaser.Loader.File[]} - * @since 3.7.0 - */ - this.files = files; - - /** - * The completion status of this MultiFile. - * - * @name Phaser.Loader.MultiFile#complete - * @type {boolean} - * @default false - * @since 3.7.0 - */ - this.complete = false; - - /** - * The number of files to load. - * - * @name Phaser.Loader.MultiFile#pending - * @type {integer} - * @since 3.7.0 - */ - - this.pending = files.length; - - /** - * The number of files that failed to load. - * - * @name Phaser.Loader.MultiFile#failed - * @type {integer} - * @default 0 - * @since 3.7.0 - */ - this.failed = 0; - - /** - * A storage container for transient data that the loading files need. - * - * @name Phaser.Loader.MultiFile#config - * @type {any} - * @since 3.7.0 - */ - this.config = {}; - - /** - * A reference to the Loaders baseURL at the time this MultiFile was created. - * Used to populate child-files. - * - * @name Phaser.Loader.MultiFile#baseURL - * @type {string} - * @since 3.20.0 - */ - this.baseURL = loader.baseURL; - - /** - * A reference to the Loaders path at the time this MultiFile was created. - * Used to populate child-files. - * - * @name Phaser.Loader.MultiFile#path - * @type {string} - * @since 3.20.0 - */ - this.path = loader.path; - - /** - * A reference to the Loaders prefix at the time this MultiFile was created. - * Used to populate child-files. - * - * @name Phaser.Loader.MultiFile#prefix - * @type {string} - * @since 3.20.0 - */ - this.prefix = loader.prefix; - - // Link the files - for (var i = 0; i < files.length; i++) - { - files[i].multiFile = this; - } - }, - - /** - * Checks if this MultiFile is ready to process its children or not. - * - * @method Phaser.Loader.MultiFile#isReadyToProcess - * @since 3.7.0 - * - * @return {boolean} `true` if all children of this MultiFile have loaded, otherwise `false`. - */ - isReadyToProcess: function () - { - return (this.pending === 0 && this.failed === 0 && !this.complete); - }, - - /** - * Adds another child to this MultiFile, increases the pending count and resets the completion status. - * - * @method Phaser.Loader.MultiFile#addToMultiFile - * @since 3.7.0 - * - * @param {Phaser.Loader.File} files - The File to add to this MultiFile. - * - * @return {Phaser.Loader.MultiFile} This MultiFile instance. - */ - addToMultiFile: function (file) - { - this.files.push(file); - - file.multiFile = this; - - this.pending++; - - this.complete = false; - - return this; - }, - - /** - * Called by each File when it finishes loading. - * - * @method Phaser.Loader.MultiFile#onFileComplete - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The File that has completed processing. - */ - onFileComplete: function (file) - { - var index = this.files.indexOf(file); - - if (index !== -1) - { - this.pending--; - } - }, - - /** - * Called by each File that fails to load. - * - * @method Phaser.Loader.MultiFile#onFileFailed - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The File that has failed to load. - */ - onFileFailed: function (file) - { - var index = this.files.indexOf(file); - - if (index !== -1) - { - this.failed++; - } - } - -}); - -module.exports = MultiFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A MultiFile is a special kind of parent that contains two, or more, Files as children and looks after + * the loading and processing of them all. It is commonly extended and used as a base class for file types such as AtlasJSON or BitmapFont. + * + * You shouldn't create an instance of a MultiFile directly, but should extend it with your own class, setting a custom type and processing methods. + * + * @class MultiFile + * @memberof Phaser.Loader + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The Loader that is going to load this File. + * @param {string} type - The file type string for sorting within the Loader. + * @param {string} key - The key of the file within the loader. + * @param {Phaser.Loader.File[]} files - An array of Files that make-up this MultiFile. + */ +var MultiFile = new Class({ + + initialize: + + function MultiFile (loader, type, key, files) + { + /** + * A reference to the Loader that is going to load this file. + * + * @name Phaser.Loader.MultiFile#loader + * @type {Phaser.Loader.LoaderPlugin} + * @since 3.7.0 + */ + this.loader = loader; + + /** + * The file type string for sorting within the Loader. + * + * @name Phaser.Loader.MultiFile#type + * @type {string} + * @since 3.7.0 + */ + this.type = type; + + /** + * Unique cache key (unique within its file type) + * + * @name Phaser.Loader.MultiFile#key + * @type {string} + * @since 3.7.0 + */ + this.key = key; + + /** + * The current index being used by multi-file loaders to avoid key clashes. + * + * @name Phaser.Loader.MultiFile#multiKeyIndex + * @type {integer} + * @private + * @since 3.20.0 + */ + this.multiKeyIndex = loader.multiKeyIndex++; + + /** + * Array of files that make up this MultiFile. + * + * @name Phaser.Loader.MultiFile#files + * @type {Phaser.Loader.File[]} + * @since 3.7.0 + */ + this.files = files; + + /** + * The completion status of this MultiFile. + * + * @name Phaser.Loader.MultiFile#complete + * @type {boolean} + * @default false + * @since 3.7.0 + */ + this.complete = false; + + /** + * The number of files to load. + * + * @name Phaser.Loader.MultiFile#pending + * @type {integer} + * @since 3.7.0 + */ + + this.pending = files.length; + + /** + * The number of files that failed to load. + * + * @name Phaser.Loader.MultiFile#failed + * @type {integer} + * @default 0 + * @since 3.7.0 + */ + this.failed = 0; + + /** + * A storage container for transient data that the loading files need. + * + * @name Phaser.Loader.MultiFile#config + * @type {any} + * @since 3.7.0 + */ + this.config = {}; + + /** + * A reference to the Loaders baseURL at the time this MultiFile was created. + * Used to populate child-files. + * + * @name Phaser.Loader.MultiFile#baseURL + * @type {string} + * @since 3.20.0 + */ + this.baseURL = loader.baseURL; + + /** + * A reference to the Loaders path at the time this MultiFile was created. + * Used to populate child-files. + * + * @name Phaser.Loader.MultiFile#path + * @type {string} + * @since 3.20.0 + */ + this.path = loader.path; + + /** + * A reference to the Loaders prefix at the time this MultiFile was created. + * Used to populate child-files. + * + * @name Phaser.Loader.MultiFile#prefix + * @type {string} + * @since 3.20.0 + */ + this.prefix = loader.prefix; + + // Link the files + for (var i = 0; i < files.length; i++) + { + files[i].multiFile = this; + } + }, + + /** + * Checks if this MultiFile is ready to process its children or not. + * + * @method Phaser.Loader.MultiFile#isReadyToProcess + * @since 3.7.0 + * + * @return {boolean} `true` if all children of this MultiFile have loaded, otherwise `false`. + */ + isReadyToProcess: function () + { + return (this.pending === 0 && this.failed === 0 && !this.complete); + }, + + /** + * Adds another child to this MultiFile, increases the pending count and resets the completion status. + * + * @method Phaser.Loader.MultiFile#addToMultiFile + * @since 3.7.0 + * + * @param {Phaser.Loader.File} files - The File to add to this MultiFile. + * + * @return {Phaser.Loader.MultiFile} This MultiFile instance. + */ + addToMultiFile: function (file) + { + this.files.push(file); + + file.multiFile = this; + + this.pending++; + + this.complete = false; + + return this; + }, + + /** + * Called by each File when it finishes loading. + * + * @method Phaser.Loader.MultiFile#onFileComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has completed processing. + */ + onFileComplete: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.pending--; + } + }, + + /** + * Called by each File that fails to load. + * + * @method Phaser.Loader.MultiFile#onFileFailed + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has failed to load. + */ + onFileFailed: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.failed++; + } + } + +}); + +module.exports = MultiFile; diff --git a/src/loader/XHRLoader.js b/src/loader/XHRLoader.js index fa246f6a3..73bcf3b02 100644 --- a/src/loader/XHRLoader.js +++ b/src/loader/XHRLoader.js @@ -1,67 +1,67 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MergeXHRSettings = require('./MergeXHRSettings'); - -/** - * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings - * and starts the download of it. It uses the Files 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. - */ -var XHRLoader = function (file, globalXHRSettings) -{ - var config = MergeXHRSettings(globalXHRSettings, file.xhrSettings); - - var xhr = new XMLHttpRequest(); - - xhr.open('GET', file.src, config.async, config.user, config.password); - - xhr.responseType = file.xhrSettings.responseType; - xhr.timeout = config.timeout; - - if (config.header && config.headerValue) - { - xhr.setRequestHeader(config.header, config.headerValue); - } - - if (config.requestedWith) - { - xhr.setRequestHeader('X-Requested-With', config.requestedWith); - } - - if (config.overrideMimeType) - { - xhr.overrideMimeType(config.overrideMimeType); - } - - if (config.withCredentials) - { - xhr.withCredentials = true; - } - - // 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.) - - xhr.onload = file.onLoad.bind(file, xhr); - xhr.onerror = file.onError.bind(file, xhr); - xhr.onprogress = file.onProgress.bind(file); - - // This is the only standard method, the ones above are browser additions (maybe not universal?) - // xhr.onreadystatechange - - xhr.send(); - - return xhr; -}; - -module.exports = XHRLoader; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MergeXHRSettings = require('./MergeXHRSettings'); + +/** + * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings + * and starts the download of it. It uses the Files 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. + */ +var XHRLoader = function (file, globalXHRSettings) +{ + var config = MergeXHRSettings(globalXHRSettings, file.xhrSettings); + + var xhr = new XMLHttpRequest(); + + xhr.open('GET', file.src, config.async, config.user, config.password); + + xhr.responseType = file.xhrSettings.responseType; + xhr.timeout = config.timeout; + + if (config.header && config.headerValue) + { + xhr.setRequestHeader(config.header, config.headerValue); + } + + if (config.requestedWith) + { + xhr.setRequestHeader('X-Requested-With', config.requestedWith); + } + + if (config.overrideMimeType) + { + xhr.overrideMimeType(config.overrideMimeType); + } + + if (config.withCredentials) + { + xhr.withCredentials = true; + } + + // 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.) + + xhr.onload = file.onLoad.bind(file, xhr); + xhr.onerror = file.onError.bind(file, xhr); + xhr.onprogress = file.onProgress.bind(file); + + // This is the only standard method, the ones above are browser additions (maybe not universal?) + // xhr.onreadystatechange + + xhr.send(); + + return xhr; +}; + +module.exports = XHRLoader; diff --git a/src/loader/XHRSettings.js b/src/loader/XHRSettings.js index fb86b00a4..4d1baec36 100644 --- a/src/loader/XHRSettings.js +++ b/src/loader/XHRSettings.js @@ -1,63 +1,63 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Creates an XHRSettings Object with default values. - * - * @function Phaser.Loader.XHRSettings - * @since 3.0.0 - * - * @param {XMLHttpRequestResponseType} [responseType=''] - The responseType, such as 'text'. - * @param {boolean} [async=true] - Should the XHR request use async or not? - * @param {string} [user=''] - Optional username for the XHR request. - * @param {string} [password=''] - Optional password for the XHR request. - * @param {integer} [timeout=0] - Optional XHR timeout value. - * @param {boolean} [withCredentials=false] - Optional XHR withCredentials value. - * - * @return {Phaser.Types.Loader.XHRSettingsObject} The XHRSettings object as used by the Loader. - */ -var XHRSettings = function (responseType, async, user, password, timeout, withCredentials) -{ - if (responseType === undefined) { responseType = ''; } - if (async === undefined) { async = true; } - if (user === undefined) { user = ''; } - if (password === undefined) { password = ''; } - if (timeout === undefined) { timeout = 0; } - if (withCredentials === undefined) { withCredentials = false; } - - // 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". - - return { - - // Ignored by the Loader, only used by File. - responseType: responseType, - - async: async, - - // credentials - user: user, - password: password, - - // timeout in ms (0 = no timeout) - timeout: timeout, - - // setRequestHeader - header: undefined, - headerValue: undefined, - requestedWith: false, - - // overrideMimeType - overrideMimeType: undefined, - - // withCredentials - withCredentials: withCredentials - - }; -}; - -module.exports = XHRSettings; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates an XHRSettings Object with default values. + * + * @function Phaser.Loader.XHRSettings + * @since 3.0.0 + * + * @param {XMLHttpRequestResponseType} [responseType=''] - The responseType, such as 'text'. + * @param {boolean} [async=true] - Should the XHR request use async or not? + * @param {string} [user=''] - Optional username for the XHR request. + * @param {string} [password=''] - Optional password for the XHR request. + * @param {integer} [timeout=0] - Optional XHR timeout value. + * @param {boolean} [withCredentials=false] - Optional XHR withCredentials value. + * + * @return {Phaser.Types.Loader.XHRSettingsObject} The XHRSettings object as used by the Loader. + */ +var XHRSettings = function (responseType, async, user, password, timeout, withCredentials) +{ + if (responseType === undefined) { responseType = ''; } + if (async === undefined) { async = true; } + if (user === undefined) { user = ''; } + if (password === undefined) { password = ''; } + if (timeout === undefined) { timeout = 0; } + if (withCredentials === undefined) { withCredentials = false; } + + // 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". + + return { + + // Ignored by the Loader, only used by File. + responseType: responseType, + + async: async, + + // credentials + user: user, + password: password, + + // timeout in ms (0 = no timeout) + timeout: timeout, + + // setRequestHeader + header: undefined, + headerValue: undefined, + requestedWith: false, + + // overrideMimeType + overrideMimeType: undefined, + + // withCredentials + withCredentials: withCredentials + + }; +}; + +module.exports = XHRSettings; diff --git a/src/loader/const.js b/src/loader/const.js index 5796fab53..caddc19b5 100644 --- a/src/loader/const.js +++ b/src/loader/const.js @@ -1,146 +1,146 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FILE_CONST = { - - /** - * The Loader is idle. - * - * @name Phaser.Loader.LOADER_IDLE - * @type {integer} - * @since 3.0.0 - */ - LOADER_IDLE: 0, - - /** - * The Loader is actively loading. - * - * @name Phaser.Loader.LOADER_LOADING - * @type {integer} - * @since 3.0.0 - */ - LOADER_LOADING: 1, - - /** - * The Loader is processing files is has loaded. - * - * @name Phaser.Loader.LOADER_PROCESSING - * @type {integer} - * @since 3.0.0 - */ - LOADER_PROCESSING: 2, - - /** - * The Loader has completed loading and processing. - * - * @name Phaser.Loader.LOADER_COMPLETE - * @type {integer} - * @since 3.0.0 - */ - LOADER_COMPLETE: 3, - - /** - * The Loader is shutting down. - * - * @name Phaser.Loader.LOADER_SHUTDOWN - * @type {integer} - * @since 3.0.0 - */ - LOADER_SHUTDOWN: 4, - - /** - * The Loader has been destroyed. - * - * @name Phaser.Loader.LOADER_DESTROYED - * @type {integer} - * @since 3.0.0 - */ - LOADER_DESTROYED: 5, - - /** - * File is in the load queue but not yet started - * - * @name Phaser.Loader.FILE_PENDING - * @type {integer} - * @since 3.0.0 - */ - FILE_PENDING: 10, - - /** - * File has been started to load by the loader (onLoad called) - * - * @name Phaser.Loader.FILE_LOADING - * @type {integer} - * @since 3.0.0 - */ - FILE_LOADING: 11, - - /** - * File has loaded successfully, awaiting processing - * - * @name Phaser.Loader.FILE_LOADED - * @type {integer} - * @since 3.0.0 - */ - FILE_LOADED: 12, - - /** - * File failed to load - * - * @name Phaser.Loader.FILE_FAILED - * @type {integer} - * @since 3.0.0 - */ - FILE_FAILED: 13, - - /** - * File is being processed (onProcess callback) - * - * @name Phaser.Loader.FILE_PROCESSING - * @type {integer} - * @since 3.0.0 - */ - FILE_PROCESSING: 14, - - /** - * The File has errored somehow during processing. - * - * @name Phaser.Loader.FILE_ERRORED - * @type {integer} - * @since 3.0.0 - */ - FILE_ERRORED: 16, - - /** - * File has finished processing. - * - * @name Phaser.Loader.FILE_COMPLETE - * @type {integer} - * @since 3.0.0 - */ - FILE_COMPLETE: 17, - - /** - * File has been destroyed - * - * @name Phaser.Loader.FILE_DESTROYED - * @type {integer} - * @since 3.0.0 - */ - FILE_DESTROYED: 18, - - /** - * File was populated from local data and doesn't need an HTTP request - * - * @name Phaser.Loader.FILE_POPULATED - * @type {integer} - * @since 3.0.0 - */ - FILE_POPULATED: 19 - -}; - -module.exports = FILE_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FILE_CONST = { + + /** + * The Loader is idle. + * + * @name Phaser.Loader.LOADER_IDLE + * @type {integer} + * @since 3.0.0 + */ + LOADER_IDLE: 0, + + /** + * The Loader is actively loading. + * + * @name Phaser.Loader.LOADER_LOADING + * @type {integer} + * @since 3.0.0 + */ + LOADER_LOADING: 1, + + /** + * The Loader is processing files is has loaded. + * + * @name Phaser.Loader.LOADER_PROCESSING + * @type {integer} + * @since 3.0.0 + */ + LOADER_PROCESSING: 2, + + /** + * The Loader has completed loading and processing. + * + * @name Phaser.Loader.LOADER_COMPLETE + * @type {integer} + * @since 3.0.0 + */ + LOADER_COMPLETE: 3, + + /** + * The Loader is shutting down. + * + * @name Phaser.Loader.LOADER_SHUTDOWN + * @type {integer} + * @since 3.0.0 + */ + LOADER_SHUTDOWN: 4, + + /** + * The Loader has been destroyed. + * + * @name Phaser.Loader.LOADER_DESTROYED + * @type {integer} + * @since 3.0.0 + */ + LOADER_DESTROYED: 5, + + /** + * File is in the load queue but not yet started + * + * @name Phaser.Loader.FILE_PENDING + * @type {integer} + * @since 3.0.0 + */ + FILE_PENDING: 10, + + /** + * File has been started to load by the loader (onLoad called) + * + * @name Phaser.Loader.FILE_LOADING + * @type {integer} + * @since 3.0.0 + */ + FILE_LOADING: 11, + + /** + * File has loaded successfully, awaiting processing + * + * @name Phaser.Loader.FILE_LOADED + * @type {integer} + * @since 3.0.0 + */ + FILE_LOADED: 12, + + /** + * File failed to load + * + * @name Phaser.Loader.FILE_FAILED + * @type {integer} + * @since 3.0.0 + */ + FILE_FAILED: 13, + + /** + * File is being processed (onProcess callback) + * + * @name Phaser.Loader.FILE_PROCESSING + * @type {integer} + * @since 3.0.0 + */ + FILE_PROCESSING: 14, + + /** + * The File has errored somehow during processing. + * + * @name Phaser.Loader.FILE_ERRORED + * @type {integer} + * @since 3.0.0 + */ + FILE_ERRORED: 16, + + /** + * File has finished processing. + * + * @name Phaser.Loader.FILE_COMPLETE + * @type {integer} + * @since 3.0.0 + */ + FILE_COMPLETE: 17, + + /** + * File has been destroyed + * + * @name Phaser.Loader.FILE_DESTROYED + * @type {integer} + * @since 3.0.0 + */ + FILE_DESTROYED: 18, + + /** + * File was populated from local data and doesn't need an HTTP request + * + * @name Phaser.Loader.FILE_POPULATED + * @type {integer} + * @since 3.0.0 + */ + FILE_POPULATED: 19 + +}; + +module.exports = FILE_CONST; diff --git a/src/loader/events/ADD_EVENT.js b/src/loader/events/ADD_EVENT.js index d6aaaa124..0e79dff7e 100644 --- a/src/loader/events/ADD_EVENT.js +++ b/src/loader/events/ADD_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Loader Plugin Add File Event. - * - * This event is dispatched when a new file is successfully added to the Loader and placed into the load queue. - * - * Listen to it from a Scene using: `this.load.on('addfile', listener)`. - * - * If you add lots of files to a Loader from a `preload` method, it will dispatch this event for each one of them. - * - * @event Phaser.Loader.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique key of the file that was added to the Loader. - * @param {string} type - The [file type]{@link Phaser.Loader.File#type} string of the file that was added to the Loader, i.e. `image`. - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. - * @param {Phaser.Loader.File} file - A reference to the File which was added to the Loader. - */ -module.exports = 'addfile'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Add File Event. + * + * This event is dispatched when a new file is successfully added to the Loader and placed into the load queue. + * + * Listen to it from a Scene using: `this.load.on('addfile', listener)`. + * + * If you add lots of files to a Loader from a `preload` method, it will dispatch this event for each one of them. + * + * @event Phaser.Loader.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique key of the file that was added to the Loader. + * @param {string} type - The [file type]{@link Phaser.Loader.File#type} string of the file that was added to the Loader, i.e. `image`. + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + * @param {Phaser.Loader.File} file - A reference to the File which was added to the Loader. + */ +module.exports = 'addfile'; diff --git a/src/loader/events/COMPLETE_EVENT.js b/src/loader/events/COMPLETE_EVENT.js index 107c6cf0a..97db07ee7 100644 --- a/src/loader/events/COMPLETE_EVENT.js +++ b/src/loader/events/COMPLETE_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Loader Plugin Complete Event. - * - * This event is dispatched when the Loader has fully processed everything in the load queue. - * By this point every loaded file will now be in its associated cache and ready for use. - * - * Listen to it from a Scene using: `this.load.on('complete', listener)`. - * - * @event Phaser.Loader.Events#COMPLETE - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. - * @param {integer} totalComplete - The total number of files that successfully loaded. - * @param {integer} totalFailed - The total number of files that failed to load. - */ -module.exports = 'complete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Complete Event. + * + * This event is dispatched when the Loader has fully processed everything in the load queue. + * By this point every loaded file will now be in its associated cache and ready for use. + * + * Listen to it from a Scene using: `this.load.on('complete', listener)`. + * + * @event Phaser.Loader.Events#COMPLETE + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + * @param {integer} totalComplete - The total number of files that successfully loaded. + * @param {integer} totalFailed - The total number of files that failed to load. + */ +module.exports = 'complete'; diff --git a/src/loader/events/FILE_COMPLETE_EVENT.js b/src/loader/events/FILE_COMPLETE_EVENT.js index 29b369626..bd7f43c8f 100644 --- a/src/loader/events/FILE_COMPLETE_EVENT.js +++ b/src/loader/events/FILE_COMPLETE_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The File Load Complete Event. - * - * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. - * - * Listen to it from a Scene using: `this.load.on('filecomplete', listener)`. - * - * You can also listen for the completion of a specific file. See the [FILE_KEY_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_KEY_COMPLETE} event. - * - * @event Phaser.Loader.Events#FILE_COMPLETE - * @since 3.0.0 - * - * @param {string} key - The key of the file that just loaded and finished processing. - * @param {string} type - The [file type]{@link Phaser.Loader.File#type} of the file that just loaded, i.e. `image`. - * @param {any} data - The raw data the file contained. - */ -module.exports = 'filecomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Complete Event. + * + * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. + * + * Listen to it from a Scene using: `this.load.on('filecomplete', listener)`. + * + * You can also listen for the completion of a specific file. See the [FILE_KEY_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_KEY_COMPLETE} event. + * + * @event Phaser.Loader.Events#FILE_COMPLETE + * @since 3.0.0 + * + * @param {string} key - The key of the file that just loaded and finished processing. + * @param {string} type - The [file type]{@link Phaser.Loader.File#type} of the file that just loaded, i.e. `image`. + * @param {any} data - The raw data the file contained. + */ +module.exports = 'filecomplete'; diff --git a/src/loader/events/FILE_KEY_COMPLETE_EVENT.js b/src/loader/events/FILE_KEY_COMPLETE_EVENT.js index 45fc30087..f32b2802d 100644 --- a/src/loader/events/FILE_KEY_COMPLETE_EVENT.js +++ b/src/loader/events/FILE_KEY_COMPLETE_EVENT.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The File Load Complete Event. - * - * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. - * - * It uses a special dynamic event name constructed from the key and type of the file. - * - * For example, if you have loaded an `image` with a key of `monster`, you can listen for it - * using the following: - * - * ```javascript - * this.load.on('filecomplete-image-monster', function (key, type, data) { - * // Your handler code - * }); - * ``` - * - * Or, if you have loaded a texture `atlas` with a key of `Level1`: - * - * ```javascript - * this.load.on('filecomplete-atlas-Level1', function (key, type, data) { - * // Your handler code - * }); - * ``` - * - * Or, if you have loaded a sprite sheet with a key of `Explosion` and a prefix of `GAMEOVER`: - * - * ```javascript - * this.load.on('filecomplete-spritesheet-GAMEOVERExplosion', function (key, type, data) { - * // Your handler code - * }); - * ``` - * - * You can also listen for the generic completion of files. See the [FILE_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_COMPLETE} event. - * - * @event Phaser.Loader.Events#FILE_KEY_COMPLETE - * @since 3.0.0 - * - * @param {string} key - The key of the file that just loaded and finished processing. - * @param {string} type - The [file type]{@link Phaser.Loader.File#type} of the file that just loaded, i.e. `image`. - * @param {any} data - The raw data the file contained. - */ -module.exports = 'filecomplete-'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Complete Event. + * + * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. + * + * It uses a special dynamic event name constructed from the key and type of the file. + * + * For example, if you have loaded an `image` with a key of `monster`, you can listen for it + * using the following: + * + * ```javascript + * this.load.on('filecomplete-image-monster', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * Or, if you have loaded a texture `atlas` with a key of `Level1`: + * + * ```javascript + * this.load.on('filecomplete-atlas-Level1', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * Or, if you have loaded a sprite sheet with a key of `Explosion` and a prefix of `GAMEOVER`: + * + * ```javascript + * this.load.on('filecomplete-spritesheet-GAMEOVERExplosion', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * You can also listen for the generic completion of files. See the [FILE_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_COMPLETE} event. + * + * @event Phaser.Loader.Events#FILE_KEY_COMPLETE + * @since 3.0.0 + * + * @param {string} key - The key of the file that just loaded and finished processing. + * @param {string} type - The [file type]{@link Phaser.Loader.File#type} of the file that just loaded, i.e. `image`. + * @param {any} data - The raw data the file contained. + */ +module.exports = 'filecomplete-'; diff --git a/src/loader/events/FILE_LOAD_ERROR_EVENT.js b/src/loader/events/FILE_LOAD_ERROR_EVENT.js index a9aba5f09..e09123151 100644 --- a/src/loader/events/FILE_LOAD_ERROR_EVENT.js +++ b/src/loader/events/FILE_LOAD_ERROR_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The File Load Error Event. - * - * This event is dispatched by the Loader Plugin when a file fails to load. - * - * Listen to it from a Scene using: `this.load.on('loaderror', listener)`. - * - * @event Phaser.Loader.Events#FILE_LOAD_ERROR - * @since 3.0.0 - * - * @param {Phaser.Loader.File} file - A reference to the File which errored during load. - */ -module.exports = 'loaderror'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Error Event. + * + * This event is dispatched by the Loader Plugin when a file fails to load. + * + * Listen to it from a Scene using: `this.load.on('loaderror', listener)`. + * + * @event Phaser.Loader.Events#FILE_LOAD_ERROR + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - A reference to the File which errored during load. + */ +module.exports = 'loaderror'; diff --git a/src/loader/events/FILE_LOAD_EVENT.js b/src/loader/events/FILE_LOAD_EVENT.js index 7f300f425..59137e3b6 100644 --- a/src/loader/events/FILE_LOAD_EVENT.js +++ b/src/loader/events/FILE_LOAD_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The File Load Event. - * - * This event is dispatched by the Loader Plugin when a file finishes loading, - * but _before_ it is processed and added to the internal Phaser caches. - * - * Listen to it from a Scene using: `this.load.on('load', listener)`. - * - * @event Phaser.Loader.Events#FILE_LOAD - * @since 3.0.0 - * - * @param {Phaser.Loader.File} file - A reference to the File which just finished loading. - */ -module.exports = 'load'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Event. + * + * This event is dispatched by the Loader Plugin when a file finishes loading, + * but _before_ it is processed and added to the internal Phaser caches. + * + * Listen to it from a Scene using: `this.load.on('load', listener)`. + * + * @event Phaser.Loader.Events#FILE_LOAD + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - A reference to the File which just finished loading. + */ +module.exports = 'load'; diff --git a/src/loader/events/FILE_PROGRESS_EVENT.js b/src/loader/events/FILE_PROGRESS_EVENT.js index 9a98b4bf6..d8b241413 100644 --- a/src/loader/events/FILE_PROGRESS_EVENT.js +++ b/src/loader/events/FILE_PROGRESS_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The File Load Progress Event. - * - * This event is dispatched by the Loader Plugin during the load of a file, if the browser receives a DOM ProgressEvent and - * the `lengthComputable` event property is true. Depending on the size of the file and browser in use, this may, or may not happen. - * - * Listen to it from a Scene using: `this.load.on('fileprogress', listener)`. - * - * @event Phaser.Loader.Events#FILE_PROGRESS - * @since 3.0.0 - * - * @param {Phaser.Loader.File} file - A reference to the File which errored during load. - * @param {number} percentComplete - A value between 0 and 1 indicating how 'complete' this file is. - */ -module.exports = 'fileprogress'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The File Load Progress Event. + * + * This event is dispatched by the Loader Plugin during the load of a file, if the browser receives a DOM ProgressEvent and + * the `lengthComputable` event property is true. Depending on the size of the file and browser in use, this may, or may not happen. + * + * Listen to it from a Scene using: `this.load.on('fileprogress', listener)`. + * + * @event Phaser.Loader.Events#FILE_PROGRESS + * @since 3.0.0 + * + * @param {Phaser.Loader.File} file - A reference to the File which errored during load. + * @param {number} percentComplete - A value between 0 and 1 indicating how 'complete' this file is. + */ +module.exports = 'fileprogress'; diff --git a/src/loader/events/POST_PROCESS_EVENT.js b/src/loader/events/POST_PROCESS_EVENT.js index 875f70f2d..a7a14ccb8 100644 --- a/src/loader/events/POST_PROCESS_EVENT.js +++ b/src/loader/events/POST_PROCESS_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Loader Plugin Post Process Event. - * - * This event is dispatched by the Loader Plugin when the Loader has finished loading everything in the load queue. - * It is dispatched before the internal lists are cleared and each File is destroyed. - * - * Use this hook to perform any last minute processing of files that can only happen once the - * Loader has completed, but prior to it emitting the `complete` event. - * - * Listen to it from a Scene using: `this.load.on('postprocess', listener)`. - * - * @event Phaser.Loader.Events#POST_PROCESS - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. - */ -module.exports = 'postprocess'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Post Process Event. + * + * This event is dispatched by the Loader Plugin when the Loader has finished loading everything in the load queue. + * It is dispatched before the internal lists are cleared and each File is destroyed. + * + * Use this hook to perform any last minute processing of files that can only happen once the + * Loader has completed, but prior to it emitting the `complete` event. + * + * Listen to it from a Scene using: `this.load.on('postprocess', listener)`. + * + * @event Phaser.Loader.Events#POST_PROCESS + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + */ +module.exports = 'postprocess'; diff --git a/src/loader/events/PROGRESS_EVENT.js b/src/loader/events/PROGRESS_EVENT.js index 0099c77ab..d96558ca8 100644 --- a/src/loader/events/PROGRESS_EVENT.js +++ b/src/loader/events/PROGRESS_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Loader Plugin Progress Event. - * - * This event is dispatched when the Loader updates its load progress, typically as a result of a file having completed loading. - * - * Listen to it from a Scene using: `this.load.on('progress', listener)`. - * - * @event Phaser.Loader.Events#PROGRESS - * @since 3.0.0 - * - * @param {number} progress - The current progress of the load. A value between 0 and 1. - */ -module.exports = 'progress'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Progress Event. + * + * This event is dispatched when the Loader updates its load progress, typically as a result of a file having completed loading. + * + * Listen to it from a Scene using: `this.load.on('progress', listener)`. + * + * @event Phaser.Loader.Events#PROGRESS + * @since 3.0.0 + * + * @param {number} progress - The current progress of the load. A value between 0 and 1. + */ +module.exports = 'progress'; diff --git a/src/loader/events/START_EVENT.js b/src/loader/events/START_EVENT.js index e5748b3e0..5a6b6b91d 100644 --- a/src/loader/events/START_EVENT.js +++ b/src/loader/events/START_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Loader Plugin Start Event. - * - * This event is dispatched when the Loader starts running. At this point load progress is zero. - * - * This event is dispatched even if there aren't any files in the load queue. - * - * Listen to it from a Scene using: `this.load.on('start', listener)`. - * - * @event Phaser.Loader.Events#START - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. - */ -module.exports = 'start'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Loader Plugin Start Event. + * + * This event is dispatched when the Loader starts running. At this point load progress is zero. + * + * This event is dispatched even if there aren't any files in the load queue. + * + * Listen to it from a Scene using: `this.load.on('start', listener)`. + * + * @event Phaser.Loader.Events#START + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader Plugin that dispatched this event. + */ +module.exports = 'start'; diff --git a/src/loader/events/index.js b/src/loader/events/index.js index 6c8a6fb40..104c5bd4b 100644 --- a/src/loader/events/index.js +++ b/src/loader/events/index.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Loader.Events - */ - -module.exports = { - - ADD: require('./ADD_EVENT'), - COMPLETE: require('./COMPLETE_EVENT'), - FILE_COMPLETE: require('./FILE_COMPLETE_EVENT'), - FILE_KEY_COMPLETE: require('./FILE_KEY_COMPLETE_EVENT'), - FILE_LOAD_ERROR: require('./FILE_LOAD_ERROR_EVENT'), - FILE_LOAD: require('./FILE_LOAD_EVENT'), - FILE_PROGRESS: require('./FILE_PROGRESS_EVENT'), - POST_PROCESS: require('./POST_PROCESS_EVENT'), - PROGRESS: require('./PROGRESS_EVENT'), - START: require('./START_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Loader.Events + */ + +module.exports = { + + ADD: require('./ADD_EVENT'), + COMPLETE: require('./COMPLETE_EVENT'), + FILE_COMPLETE: require('./FILE_COMPLETE_EVENT'), + FILE_KEY_COMPLETE: require('./FILE_KEY_COMPLETE_EVENT'), + FILE_LOAD_ERROR: require('./FILE_LOAD_ERROR_EVENT'), + FILE_LOAD: require('./FILE_LOAD_EVENT'), + FILE_PROGRESS: require('./FILE_PROGRESS_EVENT'), + POST_PROCESS: require('./POST_PROCESS_EVENT'), + PROGRESS: require('./PROGRESS_EVENT'), + START: require('./START_EVENT') + +}; diff --git a/src/loader/filetypes/AnimationJSONFile.js b/src/loader/filetypes/AnimationJSONFile.js index aa2ba09a6..f2d5511ef 100644 --- a/src/loader/filetypes/AnimationJSONFile.js +++ b/src/loader/filetypes/AnimationJSONFile.js @@ -1,197 +1,197 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var JSONFile = require('./JSONFile.js'); -var LoaderEvents = require('../events'); - -/** - * @classdesc - * A single Animation JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#animation method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#animation. - * - * @class AnimationJSONFile - * @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.JSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. - */ -var AnimationJSONFile = new Class({ - - Extends: JSONFile, - - initialize: - - // 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 - - function AnimationJSONFile (loader, key, url, xhrSettings, dataKey) - { - JSONFile.call(this, loader, key, url, xhrSettings, dataKey); - - this.type = 'animationJSON'; - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.AnimationJSONFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - // We need to hook into this event: - this.loader.once(LoaderEvents.POST_PROCESS, this.onLoadComplete, this); - - // But the rest is the same as a normal JSON file - JSONFile.prototype.onProcess.call(this); - }, - - /** - * Called at the end of the load process, after the Loader has finished all files in its queue. - * - * @method Phaser.Loader.FileTypes.AnimationJSONFile#onLoadComplete - * @since 3.7.0 - */ - onLoadComplete: function () - { - this.loader.systems.anims.fromJSON(this.data); - - this.pendingDestroy(); - } - -}); - -/** - * Adds an Animation JSON Data file, or array of Animation JSON 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.animation('baddieAnims', 'files/BaddieAnims.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 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.animation({ - * key: 'baddieAnims', - * url: 'files/BaddieAnims.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. - * - * Once the file has finished loading it will automatically be passed to the global Animation Managers `fromJSON` method. - * This will parse all of the JSON data and create animation data from it. This process happens at the very end - * of the Loader, once every other file in the load queue has finished. The reason for this is to allow you to load - * both animation data and the images it relies upon in the same load call. - * - * Once the animation data has been parsed you will be able to play animations using that data. - * Please see the Animation Manager `fromJSON` method for more details about the format and playback. - * - * You can also access the raw animation data from its Cache using its key: - * - * ```javascript - * this.load.animation('baddieAnims', 'files/BaddieAnims.json'); - * // and later in your game ... - * var data = this.cache.json.get('baddieAnims'); - * ``` - * - * 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 if you only wanted to create animations from the `boss` data, 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 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#animation - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.JSONFileConfig|Phaser.Types.Loader.FileTypes.JSONFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {string} [dataKey] - When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. - * @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. - */ -FileTypesManager.register('animation', function (key, url, dataKey, xhrSettings) -{ - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - this.addFile(new AnimationJSONFile(this, key[i])); - } - } - else - { - this.addFile(new AnimationJSONFile(this, key, url, xhrSettings, dataKey)); - } - - return this; -}); - -module.exports = AnimationJSONFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var JSONFile = require('./JSONFile.js'); +var LoaderEvents = require('../events'); + +/** + * @classdesc + * A single Animation JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#animation method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#animation. + * + * @class AnimationJSONFile + * @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.JSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. + */ +var AnimationJSONFile = new Class({ + + Extends: JSONFile, + + initialize: + + // 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 + + function AnimationJSONFile (loader, key, url, xhrSettings, dataKey) + { + JSONFile.call(this, loader, key, url, xhrSettings, dataKey); + + this.type = 'animationJSON'; + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.AnimationJSONFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + // We need to hook into this event: + this.loader.once(LoaderEvents.POST_PROCESS, this.onLoadComplete, this); + + // But the rest is the same as a normal JSON file + JSONFile.prototype.onProcess.call(this); + }, + + /** + * Called at the end of the load process, after the Loader has finished all files in its queue. + * + * @method Phaser.Loader.FileTypes.AnimationJSONFile#onLoadComplete + * @since 3.7.0 + */ + onLoadComplete: function () + { + this.loader.systems.anims.fromJSON(this.data); + + this.pendingDestroy(); + } + +}); + +/** + * Adds an Animation JSON Data file, or array of Animation JSON 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.animation('baddieAnims', 'files/BaddieAnims.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 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.animation({ + * key: 'baddieAnims', + * url: 'files/BaddieAnims.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. + * + * Once the file has finished loading it will automatically be passed to the global Animation Managers `fromJSON` method. + * This will parse all of the JSON data and create animation data from it. This process happens at the very end + * of the Loader, once every other file in the load queue has finished. The reason for this is to allow you to load + * both animation data and the images it relies upon in the same load call. + * + * Once the animation data has been parsed you will be able to play animations using that data. + * Please see the Animation Manager `fromJSON` method for more details about the format and playback. + * + * You can also access the raw animation data from its Cache using its key: + * + * ```javascript + * this.load.animation('baddieAnims', 'files/BaddieAnims.json'); + * // and later in your game ... + * var data = this.cache.json.get('baddieAnims'); + * ``` + * + * 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 if you only wanted to create animations from the `boss` data, 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 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#animation + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.JSONFileConfig|Phaser.Types.Loader.FileTypes.JSONFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {string} [dataKey] - When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. + * @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. + */ +FileTypesManager.register('animation', function (key, url, dataKey, xhrSettings) +{ + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + this.addFile(new AnimationJSONFile(this, key[i])); + } + } + else + { + this.addFile(new AnimationJSONFile(this, key, url, xhrSettings, dataKey)); + } + + return this; +}); + +module.exports = AnimationJSONFile; diff --git a/src/loader/filetypes/AtlasJSONFile.js b/src/loader/filetypes/AtlasJSONFile.js index ca064dece..ef05f0e4d 100644 --- a/src/loader/filetypes/AtlasJSONFile.js +++ b/src/loader/filetypes/AtlasJSONFile.js @@ -1,243 +1,243 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var ImageFile = require('./ImageFile.js'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var JSONFile = require('./JSONFile.js'); -var MultiFile = require('../MultiFile.js'); - -/** - * @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. - * - * https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm - * - * @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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @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. - */ -var AtlasJSONFile = new Class({ - - Extends: MultiFile, - - initialize: - - function AtlasJSONFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) - { - var image; - var data; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - - image = new ImageFile(loader, { - key: key, - url: GetFastValue(config, 'textureURL'), - extension: GetFastValue(config, 'textureExtension', 'png'), - normalMap: GetFastValue(config, 'normalMap'), - xhrSettings: GetFastValue(config, 'textureXhrSettings') - }); - - data = new JSONFile(loader, { - key: key, - url: GetFastValue(config, 'atlasURL'), - extension: GetFastValue(config, 'atlasExtension', 'json'), - xhrSettings: GetFastValue(config, 'atlasXhrSettings') - }); - } - else - { - image = new ImageFile(loader, key, textureURL, textureXhrSettings); - data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); - } - - if (image.linkFile) - { - // Image has a normal map - MultiFile.call(this, loader, 'atlasjson', key, [ image, data, image.linkFile ]); - } - else - { - MultiFile.call(this, loader, 'atlasjson', key, [ image, data ]); - } - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.AtlasJSONFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - var image = this.files[0]; - var json = this.files[1]; - var normalMap = (this.files[2]) ? this.files[2].data : null; - - this.loader.textureManager.addAtlas(image.key, image.data, json.data, normalMap); - - json.addToCache(); - - this.complete = true; - } - } - -}); - -/** - * 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, Shoebox and Adobe Flash / Animate. - * 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.LoaderPlugin#addFileEvent - * @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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @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. - */ -FileTypesManager.register('atlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) -{ - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new AtlasJSONFile(this, key[i]); - - this.addFile(multifile.files); - } - } - else - { - multifile = new AtlasJSONFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); - - this.addFile(multifile.files); - } - - return this; -}); - -module.exports = AtlasJSONFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var ImageFile = require('./ImageFile.js'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var JSONFile = require('./JSONFile.js'); +var MultiFile = require('../MultiFile.js'); + +/** + * @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. + * + * https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm + * + * @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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @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. + */ +var AtlasJSONFile = new Class({ + + Extends: MultiFile, + + initialize: + + function AtlasJSONFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new JSONFile(loader, { + key: key, + url: GetFastValue(config, 'atlasURL'), + extension: GetFastValue(config, 'atlasExtension', 'json'), + xhrSettings: GetFastValue(config, 'atlasXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'atlasjson', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'atlasjson', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.AtlasJSONFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var json = this.files[1]; + var normalMap = (this.files[2]) ? this.files[2].data : null; + + this.loader.textureManager.addAtlas(image.key, image.data, json.data, normalMap); + + json.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * 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, Shoebox and Adobe Flash / Animate. + * 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.LoaderPlugin#addFileEvent + * @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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @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. + */ +FileTypesManager.register('atlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new AtlasJSONFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new AtlasJSONFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = AtlasJSONFile; diff --git a/src/loader/filetypes/AtlasXMLFile.js b/src/loader/filetypes/AtlasXMLFile.js index a0c107c35..08572a61a 100644 --- a/src/loader/filetypes/AtlasXMLFile.js +++ b/src/loader/filetypes/AtlasXMLFile.js @@ -1,237 +1,237 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var ImageFile = require('./ImageFile.js'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var MultiFile = require('../MultiFile.js'); -var XMLFile = require('./XMLFile.js'); - -/** - * @classdesc - * A single XML based Texture Atlas File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#atlasXML method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#atlasXML. - * - * @class AtlasXMLFile - * @extends Phaser.Loader.MultiFile - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.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 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 xml file. Used in replacement of the Loaders default XHR Settings. - */ -var AtlasXMLFile = new Class({ - - Extends: MultiFile, - - initialize: - - function AtlasXMLFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) - { - var image; - var data; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - - image = new ImageFile(loader, { - key: key, - url: GetFastValue(config, 'textureURL'), - extension: GetFastValue(config, 'textureExtension', 'png'), - normalMap: GetFastValue(config, 'normalMap'), - xhrSettings: GetFastValue(config, 'textureXhrSettings') - }); - - data = new XMLFile(loader, { - key: key, - url: GetFastValue(config, 'atlasURL'), - extension: GetFastValue(config, 'atlasExtension', 'xml'), - xhrSettings: GetFastValue(config, 'atlasXhrSettings') - }); - } - else - { - image = new ImageFile(loader, key, textureURL, textureXhrSettings); - data = new XMLFile(loader, key, atlasURL, atlasXhrSettings); - } - - if (image.linkFile) - { - // Image has a normal map - MultiFile.call(this, loader, 'atlasxml', key, [ image, data, image.linkFile ]); - } - else - { - MultiFile.call(this, loader, 'atlasxml', key, [ image, data ]); - } - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.AtlasXMLFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - var image = this.files[0]; - var xml = this.files[1]; - var normalMap = (this.files[2]) ? this.files[2].data : null; - - this.loader.textureManager.addAtlasXML(image.key, image.data, xml.data, normalMap); - - xml.addToCache(); - - this.complete = true; - } - } - -}); - -/** - * Adds an XML 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.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 atlas data to be provided in an XML file format. - * These files are created by software such as Shoebox and Adobe Flash / Animate. - * - * 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.atlasXML({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * atlasURL: 'images/MainMenu.xml' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig` for more details. - * - * 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.xml'); - * // 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.atlasXML('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.xml'); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.atlasXML({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * normalMap: 'images/MainMenu-n.png', - * atlasURL: 'images/MainMenu.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 Atlas XML 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#atlasXML - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.7.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.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 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 xml file. Used in replacement of the Loaders default XHR Settings. - * - * @return {this} The Loader instance. - */ -FileTypesManager.register('atlasXML', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) -{ - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new AtlasXMLFile(this, key[i]); - - this.addFile(multifile.files); - } - } - else - { - multifile = new AtlasXMLFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); - - this.addFile(multifile.files); - } - - return this; -}); - -module.exports = AtlasXMLFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var ImageFile = require('./ImageFile.js'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var MultiFile = require('../MultiFile.js'); +var XMLFile = require('./XMLFile.js'); + +/** + * @classdesc + * A single XML based Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#atlasXML method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#atlasXML. + * + * @class AtlasXMLFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.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 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 xml file. Used in replacement of the Loaders default XHR Settings. + */ +var AtlasXMLFile = new Class({ + + Extends: MultiFile, + + initialize: + + function AtlasXMLFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new XMLFile(loader, { + key: key, + url: GetFastValue(config, 'atlasURL'), + extension: GetFastValue(config, 'atlasExtension', 'xml'), + xhrSettings: GetFastValue(config, 'atlasXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new XMLFile(loader, key, atlasURL, atlasXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'atlasxml', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'atlasxml', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.AtlasXMLFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var xml = this.files[1]; + var normalMap = (this.files[2]) ? this.files[2].data : null; + + this.loader.textureManager.addAtlasXML(image.key, image.data, xml.data, normalMap); + + xml.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * Adds an XML 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.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 atlas data to be provided in an XML file format. + * These files are created by software such as Shoebox and Adobe Flash / Animate. + * + * 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.atlasXML({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * atlasURL: 'images/MainMenu.xml' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig` for more details. + * + * 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.xml'); + * // 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.atlasXML('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.xml'); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.atlasXML({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * normalMap: 'images/MainMenu-n.png', + * atlasURL: 'images/MainMenu.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 Atlas XML 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#atlasXML + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.7.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig|Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.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 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 xml file. Used in replacement of the Loaders default XHR Settings. + * + * @return {this} The Loader instance. + */ +FileTypesManager.register('atlasXML', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new AtlasXMLFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new AtlasXMLFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = AtlasXMLFile; diff --git a/src/loader/filetypes/AudioFile.js b/src/loader/filetypes/AudioFile.js index 2e6f1918d..7fca02372 100644 --- a/src/loader/filetypes/AudioFile.js +++ b/src/loader/filetypes/AudioFile.js @@ -1,265 +1,265 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var HTML5AudioFile = require('./HTML5AudioFile'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Audio File suitable for loading by the Loader. - * - * 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 {any} [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. - */ -var AudioFile = new Class({ - - Extends: File, - - initialize: - - // URL is an object created by AudioFile.findAudioURL - function AudioFile (loader, key, urlConfig, xhrSettings, audioContext) - { - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - audioContext = GetFastValue(config, 'context', audioContext); - } - - var fileConfig = { - type: 'audio', - cache: loader.cacheManager.audio, - extension: urlConfig.type, - responseType: 'arraybuffer', - key: key, - url: urlConfig.url, - xhrSettings: xhrSettings, - config: { context: audioContext } - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.AudioFile#onProcess - * @since 3.0.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - var _this = this; - - // interesting read https://github.com/WebAudio/web-audio-api/issues/1305 - this.config.context.decodeAudioData(this.xhrLoader.response, - function (audioBuffer) - { - _this.data = audioBuffer; - - _this.onProcessComplete(); - }, - function (e) - { - // eslint-disable-next-line no-console - console.error('Error decoding audio: ' + this.key + ' - ', e ? e.message : null); - - _this.onProcessError(); - } - ); - - this.config.context = null; - } - -}); - -AudioFile.create = function (loader, key, urls, config, xhrSettings) -{ - var game = loader.systems.game; - var audioConfig = game.config.audio; - var deviceAudio = game.device.audio; - - // url may be inside key, which may be an object - if (IsPlainObject(key)) - { - urls = GetFastValue(key, 'url', []); - config = GetFastValue(key, 'config', {}); - } - - var urlConfig = AudioFile.getAudioURL(game, urls); - - if (!urlConfig) - { - return null; - } - - // https://developers.google.com/web/updates/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs - // var stream = GetFastValue(config, 'stream', false); - - if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) - { - return new AudioFile(loader, key, urlConfig, xhrSettings, game.sound.context); - } - else - { - return new HTML5AudioFile(loader, key, urlConfig, config); - } -}; - -AudioFile.getAudioURL = function (game, urls) -{ - if (!Array.isArray(urls)) - { - urls = [ urls ]; - } - - for (var i = 0; i < urls.length; i++) - { - var url = GetFastValue(urls[i], 'url', urls[i]); - - if (url.indexOf('blob:') === 0 || url.indexOf('data:') === 0) - { - return url; - } - - var audioType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); - - audioType = GetFastValue(urls[i], 'type', (audioType) ? audioType[1] : '').toLowerCase(); - - if (game.device.audio[audioType]) - { - return { - url: url, - type: audioType - }; - } - } - - return null; -}; - -/** - * 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.LoaderPlugin#addFileEvent - * @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[])} [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. - */ -FileTypesManager.register('audio', function (key, urls, config, xhrSettings) -{ - var game = this.systems.game; - var audioConfig = game.config.audio; - var deviceAudio = game.device.audio; - - if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) - { - // Sounds are disabled, so skip loading audio - return this; - } - - var audioFile; - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - audioFile = AudioFile.create(this, key[i]); - - if (audioFile) - { - this.addFile(audioFile); - } - } - } - else - { - audioFile = AudioFile.create(this, key, urls, config, xhrSettings); - - if (audioFile) - { - this.addFile(audioFile); - } - } - - return this; -}); - -module.exports = AudioFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var HTML5AudioFile = require('./HTML5AudioFile'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Audio File suitable for loading by the Loader. + * + * 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 {any} [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. + */ +var AudioFile = new Class({ + + Extends: File, + + initialize: + + // URL is an object created by AudioFile.findAudioURL + function AudioFile (loader, key, urlConfig, xhrSettings, audioContext) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + audioContext = GetFastValue(config, 'context', audioContext); + } + + var fileConfig = { + type: 'audio', + cache: loader.cacheManager.audio, + extension: urlConfig.type, + responseType: 'arraybuffer', + key: key, + url: urlConfig.url, + xhrSettings: xhrSettings, + config: { context: audioContext } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.AudioFile#onProcess + * @since 3.0.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var _this = this; + + // interesting read https://github.com/WebAudio/web-audio-api/issues/1305 + this.config.context.decodeAudioData(this.xhrLoader.response, + function (audioBuffer) + { + _this.data = audioBuffer; + + _this.onProcessComplete(); + }, + function (e) + { + // eslint-disable-next-line no-console + console.error('Error decoding audio: ' + this.key + ' - ', e ? e.message : null); + + _this.onProcessError(); + } + ); + + this.config.context = null; + } + +}); + +AudioFile.create = function (loader, key, urls, config, xhrSettings) +{ + var game = loader.systems.game; + var audioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + // url may be inside key, which may be an object + if (IsPlainObject(key)) + { + urls = GetFastValue(key, 'url', []); + config = GetFastValue(key, 'config', {}); + } + + var urlConfig = AudioFile.getAudioURL(game, urls); + + if (!urlConfig) + { + return null; + } + + // https://developers.google.com/web/updates/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs + // var stream = GetFastValue(config, 'stream', false); + + if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) + { + return new AudioFile(loader, key, urlConfig, xhrSettings, game.sound.context); + } + else + { + return new HTML5AudioFile(loader, key, urlConfig, config); + } +}; + +AudioFile.getAudioURL = function (game, urls) +{ + if (!Array.isArray(urls)) + { + urls = [ urls ]; + } + + for (var i = 0; i < urls.length; i++) + { + var url = GetFastValue(urls[i], 'url', urls[i]); + + if (url.indexOf('blob:') === 0 || url.indexOf('data:') === 0) + { + return url; + } + + var audioType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); + + audioType = GetFastValue(urls[i], 'type', (audioType) ? audioType[1] : '').toLowerCase(); + + if (game.device.audio[audioType]) + { + return { + url: url, + type: audioType + }; + } + } + + return null; +}; + +/** + * 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.LoaderPlugin#addFileEvent + * @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[])} [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. + */ +FileTypesManager.register('audio', function (key, urls, config, xhrSettings) +{ + var game = this.systems.game; + var audioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + // Sounds are disabled, so skip loading audio + return this; + } + + var audioFile; + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + audioFile = AudioFile.create(this, key[i]); + + if (audioFile) + { + this.addFile(audioFile); + } + } + } + else + { + audioFile = AudioFile.create(this, key, urls, config, xhrSettings); + + if (audioFile) + { + this.addFile(audioFile); + } + } + + return this; +}); + +module.exports = AudioFile; diff --git a/src/loader/filetypes/AudioSpriteFile.js b/src/loader/filetypes/AudioSpriteFile.js index 4d31537e8..cc7355375 100644 --- a/src/loader/filetypes/AudioSpriteFile.js +++ b/src/loader/filetypes/AudioSpriteFile.js @@ -1,284 +1,284 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AudioFile = require('./AudioFile.js'); -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var JSONFile = require('./JSONFile.js'); -var MultiFile = require('../MultiFile.js'); - -/** - * @classdesc - * An Audio Sprite File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#audioSprite method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audioSprite. - * - * @class AudioSpriteFile - * @extends Phaser.Loader.MultiFile - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig)} key - The key to use for this file, or a file configuration object. - * @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. - */ -var AudioSpriteFile = new Class({ - - Extends: MultiFile, - - initialize: - - function AudioSpriteFile (loader, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) - { - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - jsonURL = GetFastValue(config, 'jsonURL'); - audioURL = GetFastValue(config, 'audioURL'); - audioConfig = GetFastValue(config, 'audioConfig'); - audioXhrSettings = GetFastValue(config, 'audioXhrSettings'); - jsonXhrSettings = GetFastValue(config, 'jsonXhrSettings'); - } - - var data; - - // No url? then we're going to do a json load and parse it from that - if (!audioURL) - { - data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); - - MultiFile.call(this, loader, 'audiosprite', key, [ data ]); - - this.config.resourceLoad = true; - this.config.audioConfig = audioConfig; - this.config.audioXhrSettings = audioXhrSettings; - } - else - { - var audio = AudioFile.create(loader, key, audioURL, audioConfig, audioXhrSettings); - - if (audio) - { - data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); - - MultiFile.call(this, loader, 'audiosprite', key, [ audio, data ]); - - this.config.resourceLoad = false; - } - } - }, - - /** - * Called by each File when it finishes loading. - * - * @method Phaser.Loader.FileTypes.AudioSpriteFile#onFileComplete - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The File that has completed processing. - */ - onFileComplete: function (file) - { - var index = this.files.indexOf(file); - - if (index !== -1) - { - this.pending--; - - if (this.config.resourceLoad && file.type === 'json' && file.data.hasOwnProperty('resources')) - { - // Inspect the data for the files to now load - var urls = file.data.resources; - - var audioConfig = GetFastValue(this.config, 'audioConfig'); - var audioXhrSettings = GetFastValue(this.config, 'audioXhrSettings'); - - var audio = AudioFile.create(this.loader, file.key, urls, audioConfig, audioXhrSettings); - - if (audio) - { - this.addToMultiFile(audio); - - this.loader.addFile(audio); - } - } - } - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.AudioSpriteFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - var fileA = this.files[0]; - var fileB = this.files[1]; - - fileA.addToCache(); - fileB.addToCache(); - - this.complete = true; - } - } - -}); - -/** - * 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 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. - * - * 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.LoaderPlugin#addFileEvent - * @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. - */ -FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) -{ - var game = this.systems.game; - var gameAudioConfig = game.config.audio; - var deviceAudio = game.device.audio; - - if ((gameAudioConfig && gameAudioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) - { - // Sounds are disabled, so skip loading audio - return this; - } - - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new AudioSpriteFile(this, key[i]); - - if (multifile.files) - { - this.addFile(multifile.files); - } - } - } - else - { - multifile = new AudioSpriteFile(this, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings); - - if (multifile.files) - { - this.addFile(multifile.files); - } - } - - return this; -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AudioFile = require('./AudioFile.js'); +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var JSONFile = require('./JSONFile.js'); +var MultiFile = require('../MultiFile.js'); + +/** + * @classdesc + * An Audio Sprite File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#audioSprite method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audioSprite. + * + * @class AudioSpriteFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig)} key - The key to use for this file, or a file configuration object. + * @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. + */ +var AudioSpriteFile = new Class({ + + Extends: MultiFile, + + initialize: + + function AudioSpriteFile (loader, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + jsonURL = GetFastValue(config, 'jsonURL'); + audioURL = GetFastValue(config, 'audioURL'); + audioConfig = GetFastValue(config, 'audioConfig'); + audioXhrSettings = GetFastValue(config, 'audioXhrSettings'); + jsonXhrSettings = GetFastValue(config, 'jsonXhrSettings'); + } + + var data; + + // No url? then we're going to do a json load and parse it from that + if (!audioURL) + { + data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); + + MultiFile.call(this, loader, 'audiosprite', key, [ data ]); + + this.config.resourceLoad = true; + this.config.audioConfig = audioConfig; + this.config.audioXhrSettings = audioXhrSettings; + } + else + { + var audio = AudioFile.create(loader, key, audioURL, audioConfig, audioXhrSettings); + + if (audio) + { + data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); + + MultiFile.call(this, loader, 'audiosprite', key, [ audio, data ]); + + this.config.resourceLoad = false; + } + } + }, + + /** + * Called by each File when it finishes loading. + * + * @method Phaser.Loader.FileTypes.AudioSpriteFile#onFileComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has completed processing. + */ + onFileComplete: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.pending--; + + if (this.config.resourceLoad && file.type === 'json' && file.data.hasOwnProperty('resources')) + { + // Inspect the data for the files to now load + var urls = file.data.resources; + + var audioConfig = GetFastValue(this.config, 'audioConfig'); + var audioXhrSettings = GetFastValue(this.config, 'audioXhrSettings'); + + var audio = AudioFile.create(this.loader, file.key, urls, audioConfig, audioXhrSettings); + + if (audio) + { + this.addToMultiFile(audio); + + this.loader.addFile(audio); + } + } + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.AudioSpriteFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var fileA = this.files[0]; + var fileB = this.files[1]; + + fileA.addToCache(); + fileB.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * 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 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. + * + * 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.LoaderPlugin#addFileEvent + * @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. + */ +FileTypesManager.register('audioSprite', function (key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) +{ + var game = this.systems.game; + var gameAudioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + if ((gameAudioConfig && gameAudioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + // Sounds are disabled, so skip loading audio + return this; + } + + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new AudioSpriteFile(this, key[i]); + + if (multifile.files) + { + this.addFile(multifile.files); + } + } + } + else + { + multifile = new AudioSpriteFile(this, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings); + + if (multifile.files) + { + this.addFile(multifile.files); + } + } + + return this; +}); diff --git a/src/loader/filetypes/BinaryFile.js b/src/loader/filetypes/BinaryFile.js index 997e705d1..22a17fb50 100644 --- a/src/loader/filetypes/BinaryFile.js +++ b/src/loader/filetypes/BinaryFile.js @@ -1,176 +1,176 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Binary File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#binary method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#binary. - * - * @class BinaryFile - * @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.BinaryFileConfig)} 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 `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. - */ -var BinaryFile = new Class({ - - Extends: File, - - initialize: - - function BinaryFile (loader, key, url, xhrSettings, dataType) - { - var extension = 'bin'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - dataType = GetFastValue(config, 'dataType', dataType); - } - - var fileConfig = { - type: 'binary', - cache: loader.cacheManager.binary, - extension: extension, - responseType: 'arraybuffer', - key: key, - url: url, - xhrSettings: xhrSettings, - config: { dataType: dataType } - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.BinaryFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - var ctor = this.config.dataType; - - this.data = (ctor) ? new ctor(this.xhrLoader.response) : this.xhrLoader.response; - - this.onProcessComplete(); - } - -}); - -/** - * Adds a Binary file, or array of Binary 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.binary('doom', 'files/Doom.wad'); - * } - * ``` - * - * 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 Binary Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Binary 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 Binary Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.binary({ - * key: 'doom', - * url: 'files/Doom.wad', - * dataType: Uint8Array - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.BinaryFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.binary('doom', 'files/Doom.wad'); - * // and later in your game ... - * var data = this.cache.binary.get('doom'); - * ``` - * - * 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 `Data` the final key will be `LEVEL1.Data` and - * this is what you would use to retrieve the text from the Binary 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 "doom" - * and no URL is given then the Loader will set the URL to be "doom.bin". It will always add `.bin` 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 Binary 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#binary - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.BinaryFileConfig|Phaser.Types.Loader.FileTypes.BinaryFileConfig[])} 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 `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". - * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. - * @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. - */ -FileTypesManager.register('binary', function (key, url, dataType, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new BinaryFile(this, key[i])); - } - } - else - { - this.addFile(new BinaryFile(this, key, url, xhrSettings, dataType)); - } - - return this; -}); - -module.exports = BinaryFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Binary File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#binary method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#binary. + * + * @class BinaryFile + * @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.BinaryFileConfig)} 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 `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + */ +var BinaryFile = new Class({ + + Extends: File, + + initialize: + + function BinaryFile (loader, key, url, xhrSettings, dataType) + { + var extension = 'bin'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + dataType = GetFastValue(config, 'dataType', dataType); + } + + var fileConfig = { + type: 'binary', + cache: loader.cacheManager.binary, + extension: extension, + responseType: 'arraybuffer', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { dataType: dataType } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.BinaryFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var ctor = this.config.dataType; + + this.data = (ctor) ? new ctor(this.xhrLoader.response) : this.xhrLoader.response; + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Binary file, or array of Binary 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.binary('doom', 'files/Doom.wad'); + * } + * ``` + * + * 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 Binary Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Binary 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 Binary Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.binary({ + * key: 'doom', + * url: 'files/Doom.wad', + * dataType: Uint8Array + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.BinaryFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.binary('doom', 'files/Doom.wad'); + * // and later in your game ... + * var data = this.cache.binary.get('doom'); + * ``` + * + * 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 `Data` the final key will be `LEVEL1.Data` and + * this is what you would use to retrieve the text from the Binary 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 "doom" + * and no URL is given then the Loader will set the URL to be "doom.bin". It will always add `.bin` 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 Binary 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#binary + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.BinaryFileConfig|Phaser.Types.Loader.FileTypes.BinaryFileConfig[])} 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 `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {any} [dataType] - Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + * @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. + */ +FileTypesManager.register('binary', function (key, url, dataType, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new BinaryFile(this, key[i])); + } + } + else + { + this.addFile(new BinaryFile(this, key, url, xhrSettings, dataType)); + } + + return this; +}); + +module.exports = BinaryFile; diff --git a/src/loader/filetypes/BitmapFontFile.js b/src/loader/filetypes/BitmapFontFile.js index 0404e8e7a..bcd1e7a44 100644 --- a/src/loader/filetypes/BitmapFontFile.js +++ b/src/loader/filetypes/BitmapFontFile.js @@ -1,237 +1,237 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var ImageFile = require('./ImageFile.js'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var MultiFile = require('../MultiFile.js'); -var ParseXMLBitmapFont = require('../../gameobjects/bitmaptext/ParseXMLBitmapFont.js'); -var XMLFile = require('./XMLFile.js'); - -/** - * @classdesc - * A single Bitmap Font based File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#bitmapFont method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#bitmapFont. - * - * @class BitmapFontFile - * @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.BitmapFontFileConfig)} 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 font image file from. If undefined or `null` it will be set to `.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 `.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. - */ -var BitmapFontFile = new Class({ - - Extends: MultiFile, - - initialize: - - function BitmapFontFile (loader, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) - { - var image; - var data; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - - image = new ImageFile(loader, { - key: key, - url: GetFastValue(config, 'textureURL'), - extension: GetFastValue(config, 'textureExtension', 'png'), - normalMap: GetFastValue(config, 'normalMap'), - xhrSettings: GetFastValue(config, 'textureXhrSettings') - }); - - data = new XMLFile(loader, { - key: key, - url: GetFastValue(config, 'fontDataURL'), - extension: GetFastValue(config, 'fontDataExtension', 'xml'), - xhrSettings: GetFastValue(config, 'fontDataXhrSettings') - }); - } - else - { - image = new ImageFile(loader, key, textureURL, textureXhrSettings); - data = new XMLFile(loader, key, fontDataURL, fontDataXhrSettings); - } - - if (image.linkFile) - { - // Image has a normal map - MultiFile.call(this, loader, 'bitmapfont', key, [ image, data, image.linkFile ]); - } - else - { - MultiFile.call(this, loader, 'bitmapfont', key, [ image, data ]); - } - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.BitmapFontFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - var image = this.files[0]; - var xml = this.files[1]; - - image.addToCache(); - xml.addToCache(); - - this.loader.cacheManager.bitmapFont.add(image.key, { data: ParseXMLBitmapFont(xml.data), texture: image.key, frame: null }); - - this.complete = true; - } - } - -}); - -/** - * 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 atlas has finished loading you can use 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.LoaderPlugin#addFileEvent - * @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 `.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 `.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. - */ -FileTypesManager.register('bitmapFont', function (key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) -{ - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new BitmapFontFile(this, key[i]); - - this.addFile(multifile.files); - } - } - else - { - multifile = new BitmapFontFile(this, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings); - - this.addFile(multifile.files); - } - - return this; -}); - -module.exports = BitmapFontFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var ImageFile = require('./ImageFile.js'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var MultiFile = require('../MultiFile.js'); +var ParseXMLBitmapFont = require('../../gameobjects/bitmaptext/ParseXMLBitmapFont.js'); +var XMLFile = require('./XMLFile.js'); + +/** + * @classdesc + * A single Bitmap Font based File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#bitmapFont method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#bitmapFont. + * + * @class BitmapFontFile + * @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.BitmapFontFileConfig)} 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 font image file from. If undefined or `null` it will be set to `.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 `.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. + */ +var BitmapFontFile = new Class({ + + Extends: MultiFile, + + initialize: + + function BitmapFontFile (loader, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new XMLFile(loader, { + key: key, + url: GetFastValue(config, 'fontDataURL'), + extension: GetFastValue(config, 'fontDataExtension', 'xml'), + xhrSettings: GetFastValue(config, 'fontDataXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new XMLFile(loader, key, fontDataURL, fontDataXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'bitmapfont', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'bitmapfont', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.BitmapFontFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var xml = this.files[1]; + + image.addToCache(); + xml.addToCache(); + + this.loader.cacheManager.bitmapFont.add(image.key, { data: ParseXMLBitmapFont(xml.data), texture: image.key, frame: null }); + + this.complete = true; + } + } + +}); + +/** + * 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 atlas has finished loading you can use 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.LoaderPlugin#addFileEvent + * @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 `.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 `.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. + */ +FileTypesManager.register('bitmapFont', function (key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new BitmapFontFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new BitmapFontFile(this, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = BitmapFontFile; diff --git a/src/loader/filetypes/CSSFile.js b/src/loader/filetypes/CSSFile.js index 80165fb79..c4b676f66 100644 --- a/src/loader/filetypes/CSSFile.js +++ b/src/loader/filetypes/CSSFile.js @@ -1,162 +1,162 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single CSS File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#css method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#css. - * - * @class CSSFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.17.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var CSSFile = new Class({ - - Extends: File, - - initialize: - - function CSSFile (loader, key, url, xhrSettings) - { - var extension = 'css'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'script', - cache: false, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.CSSFile#onProcess - * @since 3.17.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = document.createElement('style'); - this.data.defer = false; - this.data.innerHTML = this.xhrLoader.responseText; - - document.head.appendChild(this.data); - - this.onProcessComplete(); - } - -}); - -/** - * Adds a CSS file, or array of CSS 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.css('headers', 'styles/headers.css'); - * } - * ``` - * - * 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.css({ - * key: 'headers', - * url: 'styles/headers.css' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.CSSFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a style DOM element - * via `document.createElement('style')`. It will have its `defer` property set to false and then the - * resulting element will be appended to `document.head`. The CSS styles are then applied to the current document. - * - * 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.css". It will always add `.css` 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 CSS 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#css - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.17.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig|Phaser.Types.Loader.FileTypes.CSSFileConfig[])} 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 `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". - * @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. - */ -FileTypesManager.register('css', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new CSSFile(this, key[i])); - } - } - else - { - this.addFile(new CSSFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = CSSFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single CSS File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#css method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#css. + * + * @class CSSFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.17.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var CSSFile = new Class({ + + Extends: File, + + initialize: + + function CSSFile (loader, key, url, xhrSettings) + { + var extension = 'css'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'script', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.CSSFile#onProcess + * @since 3.17.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('style'); + this.data.defer = false; + this.data.innerHTML = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + this.onProcessComplete(); + } + +}); + +/** + * Adds a CSS file, or array of CSS 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.css('headers', 'styles/headers.css'); + * } + * ``` + * + * 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.css({ + * key: 'headers', + * url: 'styles/headers.css' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.CSSFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a style DOM element + * via `document.createElement('style')`. It will have its `defer` property set to false and then the + * resulting element will be appended to `document.head`. The CSS styles are then applied to the current document. + * + * 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.css". It will always add `.css` 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 CSS 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#css + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.17.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig|Phaser.Types.Loader.FileTypes.CSSFileConfig[])} 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 `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". + * @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. + */ +FileTypesManager.register('css', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new CSSFile(this, key[i])); + } + } + else + { + this.addFile(new CSSFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = CSSFile; diff --git a/src/loader/filetypes/GLSLFile.js b/src/loader/filetypes/GLSLFile.js index ebe1141f9..3ebe23e3b 100644 --- a/src/loader/filetypes/GLSLFile.js +++ b/src/loader/filetypes/GLSLFile.js @@ -1,405 +1,405 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var Shader = require('../../display/shader/BaseShader'); - -/** - * @classdesc - * A single GLSL File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#glsl method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#glsl. - * - * @class GLSLFile - * @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.GLSLFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var GLSLFile = new Class({ - - Extends: File, - - initialize: - - function GLSLFile (loader, key, url, shaderType, xhrSettings) - { - var extension = 'glsl'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - shaderType = GetFastValue(config, 'shaderType', 'fragment'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - else if (shaderType === undefined) - { - shaderType = 'fragment'; - } - - var fileConfig = { - type: 'glsl', - cache: loader.cacheManager.shader, - extension: extension, - responseType: 'text', - key: key, - url: url, - config: { - shaderType: shaderType - }, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.GLSLFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = this.xhrLoader.responseText; - - this.onProcessComplete(); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.GLSLFile#addToCache - * @since 3.17.0 - */ - addToCache: function () - { - var data = this.data.split('\n'); - - // Check to see if this is a shader bundle, or raw glsl file. - var block = this.extractBlock(data, 0); - - if (block) - { - while (block) - { - var key = this.getShaderName(block.header); - var shaderType = this.getShaderType(block.header); - var uniforms = this.getShaderUniforms(block.header); - var shaderSrc = block.shader; - - if (this.cache.has(key)) - { - var shader = this.cache.get(key); - - if (shaderType === 'fragment') - { - shader.fragmentSrc = shaderSrc; - } - else - { - shader.vertexSrc = shaderSrc; - } - - if (!shader.uniforms) - { - shader.uniforms = uniforms; - } - } - else if (shaderType === 'fragment') - { - this.cache.add(key, new Shader(key, shaderSrc, '', uniforms)); - } - else - { - this.cache.add(key, new Shader(key, '', shaderSrc, uniforms)); - } - - block = this.extractBlock(data, block.offset); - } - } - else if (this.config.shaderType === 'fragment') - { - // Single shader - this.cache.add(this.key, new Shader(this.key, this.data)); - } - else - { - this.cache.add(this.key, new Shader(this.key, '', this.data)); - } - - this.pendingDestroy(); - }, - - /** - * Returns the name of the shader from the header block. - * - * @method Phaser.Loader.FileTypes.GLSLFile#getShaderName - * @since 3.17.0 - * - * @param {string[]} headerSource - The header data. - * - * @return {string} The shader name. - */ - getShaderName: function (headerSource) - { - for (var i = 0; i < headerSource.length; i++) - { - var line = headerSource[i].trim(); - - if (line.substring(0, 5) === 'name:') - { - return line.substring(5).trim(); - } - } - - return this.key; - }, - - /** - * Returns the type of the shader from the header block. - * - * @method Phaser.Loader.FileTypes.GLSLFile#getShaderType - * @since 3.17.0 - * - * @param {string[]} headerSource - The header data. - * - * @return {string} The shader type. Either 'fragment' or 'vertex'. - */ - getShaderType: function (headerSource) - { - for (var i = 0; i < headerSource.length; i++) - { - var line = headerSource[i].trim(); - - if (line.substring(0, 5) === 'type:') - { - return line.substring(5).trim(); - } - } - - return this.config.shaderType; - }, - - /** - * Returns the shader uniforms from the header block. - * - * @method Phaser.Loader.FileTypes.GLSLFile#getShaderUniforms - * @since 3.17.0 - * - * @param {string[]} headerSource - The header data. - * - * @return {any} The shader uniforms object. - */ - getShaderUniforms: function (headerSource) - { - var uniforms = {}; - - for (var i = 0; i < headerSource.length; i++) - { - var line = headerSource[i].trim(); - - if (line.substring(0, 8) === 'uniform.') - { - var pos = line.indexOf(':'); - - if (pos) - { - var key = line.substring(8, pos); - - try - { - uniforms[key] = JSON.parse(line.substring(pos + 1)); - } - catch (e) - { - console.warn('Invalid uniform JSON: ' + key); - } - } - } - } - - return uniforms; - }, - - /** - * Processes the shader file and extracts the relevant data. - * - * @method Phaser.Loader.FileTypes.GLSLFile#extractBlock - * @private - * @since 3.17.0 - * - * @param {string[]} data - The array of shader data to process. - * @param {integer} offset - The offset to start processing from. - * - * @return {any} The processed shader block, or null. - */ - extractBlock: function (data, offset) - { - var headerStart = -1; - var headerEnd = -1; - var blockEnd = -1; - var headerOpen = false; - var captureSource = false; - var headerSource = []; - var shaderSource = []; - - for (var i = offset; i < data.length; i++) - { - var line = data[i].trim(); - - if (line === '---') - { - if (headerStart === -1) - { - headerStart = i; - headerOpen = true; - } - else if (headerOpen) - { - headerEnd = i; - headerOpen = false; - captureSource = true; - } - else - { - // We've hit another --- delimiter, break out - captureSource = false; - break; - } - } - else if (headerOpen) - { - headerSource.push(line); - } - else if (captureSource) - { - shaderSource.push(line); - blockEnd = i; - } - } - - if (!headerOpen && headerEnd !== -1) - { - return { header: headerSource, shader: shaderSource.join('\n'), offset: blockEnd }; - } - else - { - return null; - } - } - -}); - -/** - * Adds a GLSL file, or array of GLSL files, to the current load queue. - * In Phaser 3 GLSL files are just plain Text files at the current moment in time. - * - * 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.glsl('plasma', 'shaders/Plasma.glsl'); - * } - * ``` - * - * 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 Shader Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Shader 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 Shader Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.glsl({ - * key: 'plasma', - * shaderType: 'fragment', - * url: 'shaders/Plasma.glsl' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.GLSLFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.glsl('plasma', 'shaders/Plasma.glsl'); - * // and later in your game ... - * var data = this.cache.shader.get('plasma'); - * ``` - * - * 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 `FX.` and the key was `Plasma` the final key will be `FX.Plasma` and - * this is what you would use to retrieve the text from the Shader 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 "plasma" - * and no URL is given then the Loader will set the URL to be "plasma.glsl". It will always add `.glsl` 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 GLSL 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#glsl - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.GLSLFileConfig|Phaser.Types.Loader.FileTypes.GLSLFileConfig[])} 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 `.glsl`, i.e. if `key` was "alien" then the URL will be "alien.glsl". - * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. - * @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. - */ -FileTypesManager.register('glsl', function (key, url, shaderType, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new GLSLFile(this, key[i])); - } - } - else - { - this.addFile(new GLSLFile(this, key, url, shaderType, xhrSettings)); - } - - return this; -}); - -module.exports = GLSLFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var Shader = require('../../display/shader/BaseShader'); + +/** + * @classdesc + * A single GLSL File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#glsl method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#glsl. + * + * @class GLSLFile + * @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.GLSLFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var GLSLFile = new Class({ + + Extends: File, + + initialize: + + function GLSLFile (loader, key, url, shaderType, xhrSettings) + { + var extension = 'glsl'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + shaderType = GetFastValue(config, 'shaderType', 'fragment'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + else if (shaderType === undefined) + { + shaderType = 'fragment'; + } + + var fileConfig = { + type: 'glsl', + cache: loader.cacheManager.shader, + extension: extension, + responseType: 'text', + key: key, + url: url, + config: { + shaderType: shaderType + }, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.GLSLFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.GLSLFile#addToCache + * @since 3.17.0 + */ + addToCache: function () + { + var data = this.data.split('\n'); + + // Check to see if this is a shader bundle, or raw glsl file. + var block = this.extractBlock(data, 0); + + if (block) + { + while (block) + { + var key = this.getShaderName(block.header); + var shaderType = this.getShaderType(block.header); + var uniforms = this.getShaderUniforms(block.header); + var shaderSrc = block.shader; + + if (this.cache.has(key)) + { + var shader = this.cache.get(key); + + if (shaderType === 'fragment') + { + shader.fragmentSrc = shaderSrc; + } + else + { + shader.vertexSrc = shaderSrc; + } + + if (!shader.uniforms) + { + shader.uniforms = uniforms; + } + } + else if (shaderType === 'fragment') + { + this.cache.add(key, new Shader(key, shaderSrc, '', uniforms)); + } + else + { + this.cache.add(key, new Shader(key, '', shaderSrc, uniforms)); + } + + block = this.extractBlock(data, block.offset); + } + } + else if (this.config.shaderType === 'fragment') + { + // Single shader + this.cache.add(this.key, new Shader(this.key, this.data)); + } + else + { + this.cache.add(this.key, new Shader(this.key, '', this.data)); + } + + this.pendingDestroy(); + }, + + /** + * Returns the name of the shader from the header block. + * + * @method Phaser.Loader.FileTypes.GLSLFile#getShaderName + * @since 3.17.0 + * + * @param {string[]} headerSource - The header data. + * + * @return {string} The shader name. + */ + getShaderName: function (headerSource) + { + for (var i = 0; i < headerSource.length; i++) + { + var line = headerSource[i].trim(); + + if (line.substring(0, 5) === 'name:') + { + return line.substring(5).trim(); + } + } + + return this.key; + }, + + /** + * Returns the type of the shader from the header block. + * + * @method Phaser.Loader.FileTypes.GLSLFile#getShaderType + * @since 3.17.0 + * + * @param {string[]} headerSource - The header data. + * + * @return {string} The shader type. Either 'fragment' or 'vertex'. + */ + getShaderType: function (headerSource) + { + for (var i = 0; i < headerSource.length; i++) + { + var line = headerSource[i].trim(); + + if (line.substring(0, 5) === 'type:') + { + return line.substring(5).trim(); + } + } + + return this.config.shaderType; + }, + + /** + * Returns the shader uniforms from the header block. + * + * @method Phaser.Loader.FileTypes.GLSLFile#getShaderUniforms + * @since 3.17.0 + * + * @param {string[]} headerSource - The header data. + * + * @return {any} The shader uniforms object. + */ + getShaderUniforms: function (headerSource) + { + var uniforms = {}; + + for (var i = 0; i < headerSource.length; i++) + { + var line = headerSource[i].trim(); + + if (line.substring(0, 8) === 'uniform.') + { + var pos = line.indexOf(':'); + + if (pos) + { + var key = line.substring(8, pos); + + try + { + uniforms[key] = JSON.parse(line.substring(pos + 1)); + } + catch (e) + { + console.warn('Invalid uniform JSON: ' + key); + } + } + } + } + + return uniforms; + }, + + /** + * Processes the shader file and extracts the relevant data. + * + * @method Phaser.Loader.FileTypes.GLSLFile#extractBlock + * @private + * @since 3.17.0 + * + * @param {string[]} data - The array of shader data to process. + * @param {integer} offset - The offset to start processing from. + * + * @return {any} The processed shader block, or null. + */ + extractBlock: function (data, offset) + { + var headerStart = -1; + var headerEnd = -1; + var blockEnd = -1; + var headerOpen = false; + var captureSource = false; + var headerSource = []; + var shaderSource = []; + + for (var i = offset; i < data.length; i++) + { + var line = data[i].trim(); + + if (line === '---') + { + if (headerStart === -1) + { + headerStart = i; + headerOpen = true; + } + else if (headerOpen) + { + headerEnd = i; + headerOpen = false; + captureSource = true; + } + else + { + // We've hit another --- delimiter, break out + captureSource = false; + break; + } + } + else if (headerOpen) + { + headerSource.push(line); + } + else if (captureSource) + { + shaderSource.push(line); + blockEnd = i; + } + } + + if (!headerOpen && headerEnd !== -1) + { + return { header: headerSource, shader: shaderSource.join('\n'), offset: blockEnd }; + } + else + { + return null; + } + } + +}); + +/** + * Adds a GLSL file, or array of GLSL files, to the current load queue. + * In Phaser 3 GLSL files are just plain Text files at the current moment in time. + * + * 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.glsl('plasma', 'shaders/Plasma.glsl'); + * } + * ``` + * + * 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 Shader Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Shader 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 Shader Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.glsl({ + * key: 'plasma', + * shaderType: 'fragment', + * url: 'shaders/Plasma.glsl' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.GLSLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.glsl('plasma', 'shaders/Plasma.glsl'); + * // and later in your game ... + * var data = this.cache.shader.get('plasma'); + * ``` + * + * 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 `FX.` and the key was `Plasma` the final key will be `FX.Plasma` and + * this is what you would use to retrieve the text from the Shader 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 "plasma" + * and no URL is given then the Loader will set the URL to be "plasma.glsl". It will always add `.glsl` 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 GLSL 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#glsl + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.GLSLFileConfig|Phaser.Types.Loader.FileTypes.GLSLFileConfig[])} 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 `.glsl`, i.e. if `key` was "alien" then the URL will be "alien.glsl". + * @param {string} [shaderType='fragment'] - The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. + * @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. + */ +FileTypesManager.register('glsl', function (key, url, shaderType, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new GLSLFile(this, key[i])); + } + } + else + { + this.addFile(new GLSLFile(this, key, url, shaderType, xhrSettings)); + } + + return this; +}); + +module.exports = GLSLFile; diff --git a/src/loader/filetypes/HTML5AudioFile.js b/src/loader/filetypes/HTML5AudioFile.js index 21ed6c941..86806e0c3 100644 --- a/src/loader/filetypes/HTML5AudioFile.js +++ b/src/loader/filetypes/HTML5AudioFile.js @@ -1,192 +1,192 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Events = require('../events'); -var File = require('../File'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetURL = require('../GetURL'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Audio File suitable for loading by the Loader. - * - * 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 HTML5AudioFile - * @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 {string} [urlConfig] - The absolute or relative URL to load this file from. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var HTML5AudioFile = new Class({ - - Extends: File, - - initialize: - - function HTML5AudioFile (loader, key, urlConfig, audioConfig) - { - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - audioConfig = GetFastValue(config, 'config', audioConfig); - } - - var fileConfig = { - type: 'audio', - cache: loader.cacheManager.audio, - extension: urlConfig.type, - key: key, - url: urlConfig.url, - config: audioConfig - }; - - File.call(this, loader, fileConfig); - - // New properties specific to this class - this.locked = 'ontouchstart' in window; - this.loaded = false; - this.filesLoaded = 0; - this.filesTotal = 0; - }, - - /** - * Called when the file finishes loading. - * - * @method Phaser.Loader.FileTypes.HTML5AudioFile#onLoad - * @since 3.0.0 - */ - onLoad: function () - { - if (this.loaded) - { - return; - } - - this.loaded = true; - - this.loader.nextFile(this, true); - }, - - /** - * Called if the file errors while loading. - * - * @method Phaser.Loader.FileTypes.HTML5AudioFile#onError - * @since 3.0.0 - */ - onError: function () - { - for (var i = 0; i < this.data.length; i++) - { - var audio = this.data[i]; - - audio.oncanplaythrough = null; - audio.onerror = null; - } - - this.loader.nextFile(this, false); - }, - - /** - * Called during the file load progress. Is sent a DOM ProgressEvent. - * - * @method Phaser.Loader.FileTypes.HTML5AudioFile#onProgress - * @fires Phaser.Loader.Events#FILE_PROGRESS - * @since 3.0.0 - */ - onProgress: function (event) - { - var audio = event.target; - - audio.oncanplaythrough = null; - audio.onerror = null; - - this.filesLoaded++; - - this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1); - - this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete); - - if (this.filesLoaded === this.filesTotal) - { - this.onLoad(); - } - }, - - /** - * 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.FileTypes.HTML5AudioFile#load - * @since 3.0.0 - */ - load: function () - { - this.data = []; - - var instances = (this.config && this.config.instances) || 1; - - this.filesTotal = instances; - this.filesLoaded = 0; - this.percentComplete = 0; - - for (var i = 0; i < instances; i++) - { - var audio = new Audio(); - audio.dataset = {}; - audio.dataset.name = this.key + ('0' + i).slice(-2); - audio.dataset.used = 'false'; - - if (this.locked) - { - audio.dataset.locked = 'true'; - } - else - { - audio.dataset.locked = 'false'; - - audio.preload = 'auto'; - audio.oncanplaythrough = this.onProgress.bind(this); - audio.onerror = this.onError.bind(this); - } - - this.data.push(audio); - } - - for (i = 0; i < this.data.length; i++) - { - audio = this.data[i]; - audio.src = GetURL(this, this.loader.baseURL); - - if (!this.locked) - { - audio.load(); - } - } - - if (this.locked) - { - // This is super-dangerous but works. Race condition potential high. - // Is there another way? - setTimeout(this.onLoad.bind(this)); - } - } - -}); - -module.exports = HTML5AudioFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Events = require('../events'); +var File = require('../File'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetURL = require('../GetURL'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Audio File suitable for loading by the Loader. + * + * 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 HTML5AudioFile + * @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 {string} [urlConfig] - The absolute or relative URL to load this file from. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var HTML5AudioFile = new Class({ + + Extends: File, + + initialize: + + function HTML5AudioFile (loader, key, urlConfig, audioConfig) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + audioConfig = GetFastValue(config, 'config', audioConfig); + } + + var fileConfig = { + type: 'audio', + cache: loader.cacheManager.audio, + extension: urlConfig.type, + key: key, + url: urlConfig.url, + config: audioConfig + }; + + File.call(this, loader, fileConfig); + + // New properties specific to this class + this.locked = 'ontouchstart' in window; + this.loaded = false; + this.filesLoaded = 0; + this.filesTotal = 0; + }, + + /** + * Called when the file finishes loading. + * + * @method Phaser.Loader.FileTypes.HTML5AudioFile#onLoad + * @since 3.0.0 + */ + onLoad: function () + { + if (this.loaded) + { + return; + } + + this.loaded = true; + + this.loader.nextFile(this, true); + }, + + /** + * Called if the file errors while loading. + * + * @method Phaser.Loader.FileTypes.HTML5AudioFile#onError + * @since 3.0.0 + */ + onError: function () + { + for (var i = 0; i < this.data.length; i++) + { + var audio = this.data[i]; + + audio.oncanplaythrough = null; + audio.onerror = null; + } + + this.loader.nextFile(this, false); + }, + + /** + * Called during the file load progress. Is sent a DOM ProgressEvent. + * + * @method Phaser.Loader.FileTypes.HTML5AudioFile#onProgress + * @fires Phaser.Loader.Events#FILE_PROGRESS + * @since 3.0.0 + */ + onProgress: function (event) + { + var audio = event.target; + + audio.oncanplaythrough = null; + audio.onerror = null; + + this.filesLoaded++; + + this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1); + + this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete); + + if (this.filesLoaded === this.filesTotal) + { + this.onLoad(); + } + }, + + /** + * 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.FileTypes.HTML5AudioFile#load + * @since 3.0.0 + */ + load: function () + { + this.data = []; + + var instances = (this.config && this.config.instances) || 1; + + this.filesTotal = instances; + this.filesLoaded = 0; + this.percentComplete = 0; + + for (var i = 0; i < instances; i++) + { + var audio = new Audio(); + audio.dataset = {}; + audio.dataset.name = this.key + ('0' + i).slice(-2); + audio.dataset.used = 'false'; + + if (this.locked) + { + audio.dataset.locked = 'true'; + } + else + { + audio.dataset.locked = 'false'; + + audio.preload = 'auto'; + audio.oncanplaythrough = this.onProgress.bind(this); + audio.onerror = this.onError.bind(this); + } + + this.data.push(audio); + } + + for (i = 0; i < this.data.length; i++) + { + audio = this.data[i]; + audio.src = GetURL(this, this.loader.baseURL); + + if (!this.locked) + { + audio.load(); + } + } + + if (this.locked) + { + // This is super-dangerous but works. Race condition potential high. + // Is there another way? + setTimeout(this.onLoad.bind(this)); + } + } + +}); + +module.exports = HTML5AudioFile; diff --git a/src/loader/filetypes/HTMLFile.js b/src/loader/filetypes/HTMLFile.js index c746c18d0..64d3d2193 100644 --- a/src/loader/filetypes/HTMLFile.js +++ b/src/loader/filetypes/HTMLFile.js @@ -1,169 +1,169 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single HTML File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#html method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#html. - * - * @class HTMLFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.12.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.HTMLFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.html". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var HTMLFile = new Class({ - - Extends: File, - - initialize: - - function HTMLFile (loader, key, url, xhrSettings) - { - var extension = 'html'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'text', - cache: loader.cacheManager.html, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.HTMLFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = this.xhrLoader.responseText; - - this.onProcessComplete(); - } - -}); - -/** - * Adds an HTML file, or array of HTML 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.html('story', 'files/LoginForm.html'); - * } - * ``` - * - * 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 HTML Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the HTML 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 HTML Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.html({ - * key: 'login', - * url: 'files/LoginForm.html' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.HTMLFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.html('login', 'files/LoginForm.html'); - * // and later in your game ... - * var data = this.cache.html.get('login'); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the html from the HTML 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 "story" - * and no URL is given then the Loader will set the URL to be "story.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. - * - * Note: The ability to load this type of file will only be available if the HTML 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#html - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.12.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.HTMLFileConfig|Phaser.Types.Loader.FileTypes.HTMLFileConfig[])} 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 `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". - * @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. - */ -FileTypesManager.register('html', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new HTMLFile(this, key[i])); - } - } - else - { - this.addFile(new HTMLFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = HTMLFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single HTML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#html method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#html. + * + * @class HTMLFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.12.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.HTMLFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var HTMLFile = new Class({ + + Extends: File, + + initialize: + + function HTMLFile (loader, key, url, xhrSettings) + { + var extension = 'html'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'text', + cache: loader.cacheManager.html, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.HTMLFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + } + +}); + +/** + * Adds an HTML file, or array of HTML 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.html('story', 'files/LoginForm.html'); + * } + * ``` + * + * 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 HTML Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the HTML 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 HTML Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.html({ + * key: 'login', + * url: 'files/LoginForm.html' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.HTMLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.html('login', 'files/LoginForm.html'); + * // and later in your game ... + * var data = this.cache.html.get('login'); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the html from the HTML 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 "story" + * and no URL is given then the Loader will set the URL to be "story.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. + * + * Note: The ability to load this type of file will only be available if the HTML 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#html + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.12.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.HTMLFileConfig|Phaser.Types.Loader.FileTypes.HTMLFileConfig[])} 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 `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @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. + */ +FileTypesManager.register('html', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new HTMLFile(this, key[i])); + } + } + else + { + this.addFile(new HTMLFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = HTMLFile; diff --git a/src/loader/filetypes/HTMLTextureFile.js b/src/loader/filetypes/HTMLTextureFile.js index 68594b870..ce9766e36 100644 --- a/src/loader/filetypes/HTMLTextureFile.js +++ b/src/loader/filetypes/HTMLTextureFile.js @@ -1,252 +1,252 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single HTML File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#htmlTexture method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#htmlTexture. - * - * @class HTMLTextureFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.12.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {integer} [width] - The width of the texture the HTML will be rendered to. - * @param {integer} [height] - The height of the texture the HTML will be rendered to. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var HTMLTextureFile = new Class({ - - Extends: File, - - initialize: - - function HTMLTextureFile (loader, key, url, width, height, xhrSettings) - { - if (width === undefined) { width = 512; } - if (height === undefined) { height = 512; } - - var extension = 'html'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - width = GetFastValue(config, 'width', width); - height = GetFastValue(config, 'height', height); - } - - var fileConfig = { - type: 'html', - cache: loader.textureManager, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings, - config: { - width: width, - height: height - } - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.HTMLTextureFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - var w = this.config.width; - var h = this.config.height; - - var data = []; - - data.push(''); - data.push(''); - data.push(''); - data.push(this.xhrLoader.responseText); - data.push(''); - data.push(''); - data.push(''); - - var svg = [ data.join('\n') ]; - var _this = this; - - try - { - var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' }); - } - catch (e) - { - _this.state = CONST.FILE_ERRORED; - - _this.onProcessComplete(); - - return; - } - - this.data = new Image(); - - this.data.crossOrigin = this.crossOrigin; - - this.data.onload = function () - { - File.revokeObjectURL(_this.data); - - _this.onProcessComplete(); - }; - - this.data.onerror = function () - { - File.revokeObjectURL(_this.data); - - _this.onProcessError(); - }; - - File.createObjectURL(this.data, blob, 'image/svg+xml'); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.HTMLTextureFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var texture = this.cache.addImage(this.key, this.data); - - this.pendingDestroy(texture); - } - -}); - -/** - * 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.LoaderPlugin#addFileEvent - * @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 `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". - * @param {integer} [width=512] - The width of the texture the HTML will be rendered to. - * @param {integer} [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. - */ -FileTypesManager.register('htmlTexture', function (key, url, width, height, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new HTMLTextureFile(this, key[i])); - } - } - else - { - this.addFile(new HTMLTextureFile(this, key, url, width, height, xhrSettings)); - } - - return this; -}); - -module.exports = HTMLTextureFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single HTML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#htmlTexture method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#htmlTexture. + * + * @class HTMLTextureFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.12.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {integer} [width] - The width of the texture the HTML will be rendered to. + * @param {integer} [height] - The height of the texture the HTML will be rendered to. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var HTMLTextureFile = new Class({ + + Extends: File, + + initialize: + + function HTMLTextureFile (loader, key, url, width, height, xhrSettings) + { + if (width === undefined) { width = 512; } + if (height === undefined) { height = 512; } + + var extension = 'html'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + width = GetFastValue(config, 'width', width); + height = GetFastValue(config, 'height', height); + } + + var fileConfig = { + type: 'html', + cache: loader.textureManager, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + width: width, + height: height + } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.HTMLTextureFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var w = this.config.width; + var h = this.config.height; + + var data = []; + + data.push(''); + data.push(''); + data.push(''); + data.push(this.xhrLoader.responseText); + data.push(''); + data.push(''); + data.push(''); + + var svg = [ data.join('\n') ]; + var _this = this; + + try + { + var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' }); + } + catch (e) + { + _this.state = CONST.FILE_ERRORED; + + _this.onProcessComplete(); + + return; + } + + this.data = new Image(); + + this.data.crossOrigin = this.crossOrigin; + + this.data.onload = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessError(); + }; + + File.createObjectURL(this.data, blob, 'image/svg+xml'); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.HTMLTextureFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture = this.cache.addImage(this.key, this.data); + + this.pendingDestroy(texture); + } + +}); + +/** + * 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.LoaderPlugin#addFileEvent + * @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 `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param {integer} [width=512] - The width of the texture the HTML will be rendered to. + * @param {integer} [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. + */ +FileTypesManager.register('htmlTexture', function (key, url, width, height, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new HTMLTextureFile(this, key[i])); + } + } + else + { + this.addFile(new HTMLTextureFile(this, key, url, width, height, xhrSettings)); + } + + return this; +}); + +module.exports = HTMLTextureFile; diff --git a/src/loader/filetypes/ImageFile.js b/src/loader/filetypes/ImageFile.js index a6d3e6201..8daeb8f53 100644 --- a/src/loader/filetypes/ImageFile.js +++ b/src/loader/filetypes/ImageFile.js @@ -1,268 +1,268 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Image File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#image method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#image. - * - * @class ImageFile - * @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.ImageFileConfig)} key - The key to use for this file, or a file configuration object. - * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. Only provided for, and used by, Sprite Sheets. - */ -var ImageFile = new Class({ - - Extends: File, - - initialize: - - function ImageFile (loader, key, url, xhrSettings, frameConfig) - { - var extension = 'png'; - var normalMapURL; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - normalMapURL = GetFastValue(config, 'normalMap'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - frameConfig = GetFastValue(config, 'frameConfig'); - } - - if (Array.isArray(url)) - { - normalMapURL = url[1]; - url = url[0]; - } - - var fileConfig = { - type: 'image', - cache: loader.textureManager, - extension: extension, - responseType: 'blob', - key: key, - url: url, - xhrSettings: xhrSettings, - config: frameConfig - }; - - File.call(this, loader, fileConfig); - - // Do we have a normal map to load as well? - if (normalMapURL) - { - var normalMap = new ImageFile(loader, this.key, normalMapURL, xhrSettings, frameConfig); - - normalMap.type = 'normalMap'; - - this.setLink(normalMap); - - loader.addFile(normalMap); - } - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.ImageFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = new Image(); - - this.data.crossOrigin = this.crossOrigin; - - var _this = this; - - this.data.onload = function () - { - File.revokeObjectURL(_this.data); - - _this.onProcessComplete(); - }; - - this.data.onerror = function () - { - File.revokeObjectURL(_this.data); - - _this.onProcessError(); - }; - - File.createObjectURL(this.data, this.xhrLoader.response, 'image/png'); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.ImageFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var texture; - var linkFile = this.linkFile; - - if (linkFile && linkFile.state === CONST.FILE_COMPLETE) - { - if (this.type === 'image') - { - texture = this.cache.addImage(this.key, this.data, linkFile.data); - } - else - { - texture = this.cache.addImage(linkFile.key, linkFile.data, this.data); - } - - this.pendingDestroy(texture); - - linkFile.pendingDestroy(texture); - } - else if (!linkFile) - { - texture = this.cache.addImage(this.key, this.data); - - this.pendingDestroy(texture); - } - } - -}); - -/** - * Adds an Image, or array of Images, 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.image('logo', 'images/phaserLogo.png'); - * } - * ``` - * - * 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. - * - * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. - * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback - * of animated gifs to Canvas elements. - * - * 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.image({ - * key: 'logo', - * url: 'images/AtariLogo.png' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.ImageFileConfig` 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.image('logo', 'images/AtariLogo.png'); - * // and later in your game ... - * this.add.image(x, y, 'logo'); - * ``` - * - * 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.image('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ]); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.image({ - * key: 'logo', - * url: 'images/AtariLogo.png', - * normalMap: 'images/AtariLogo-n.png' - * }); - * ``` - * - * 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 Image 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#image - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.ImageFileConfig|Phaser.Types.Loader.FileTypes.ImageFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. - * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @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. - */ -FileTypesManager.register('image', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new ImageFile(this, key[i])); - } - } - else - { - this.addFile(new ImageFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = ImageFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Image File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#image method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#image. + * + * @class ImageFile + * @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.ImageFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. Only provided for, and used by, Sprite Sheets. + */ +var ImageFile = new Class({ + + Extends: File, + + initialize: + + function ImageFile (loader, key, url, xhrSettings, frameConfig) + { + var extension = 'png'; + var normalMapURL; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + normalMapURL = GetFastValue(config, 'normalMap'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + frameConfig = GetFastValue(config, 'frameConfig'); + } + + if (Array.isArray(url)) + { + normalMapURL = url[1]; + url = url[0]; + } + + var fileConfig = { + type: 'image', + cache: loader.textureManager, + extension: extension, + responseType: 'blob', + key: key, + url: url, + xhrSettings: xhrSettings, + config: frameConfig + }; + + File.call(this, loader, fileConfig); + + // Do we have a normal map to load as well? + if (normalMapURL) + { + var normalMap = new ImageFile(loader, this.key, normalMapURL, xhrSettings, frameConfig); + + normalMap.type = 'normalMap'; + + this.setLink(normalMap); + + loader.addFile(normalMap); + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.ImageFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = new Image(); + + this.data.crossOrigin = this.crossOrigin; + + var _this = this; + + this.data.onload = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessError(); + }; + + File.createObjectURL(this.data, this.xhrLoader.response, 'image/png'); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.ImageFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture; + var linkFile = this.linkFile; + + if (linkFile && linkFile.state === CONST.FILE_COMPLETE) + { + if (this.type === 'image') + { + texture = this.cache.addImage(this.key, this.data, linkFile.data); + } + else + { + texture = this.cache.addImage(linkFile.key, linkFile.data, this.data); + } + + this.pendingDestroy(texture); + + linkFile.pendingDestroy(texture); + } + else if (!linkFile) + { + texture = this.cache.addImage(this.key, this.data); + + this.pendingDestroy(texture); + } + } + +}); + +/** + * Adds an Image, or array of Images, 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.image('logo', 'images/phaserLogo.png'); + * } + * ``` + * + * 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. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback + * of animated gifs to Canvas elements. + * + * 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.image({ + * key: 'logo', + * url: 'images/AtariLogo.png' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ImageFileConfig` 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.image('logo', 'images/AtariLogo.png'); + * // and later in your game ... + * this.add.image(x, y, 'logo'); + * ``` + * + * 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.image('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ]); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.image({ + * key: 'logo', + * url: 'images/AtariLogo.png', + * normalMap: 'images/AtariLogo-n.png' + * }); + * ``` + * + * 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 Image 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#image + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.ImageFileConfig|Phaser.Types.Loader.FileTypes.ImageFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @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. + */ +FileTypesManager.register('image', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new ImageFile(this, key[i])); + } + } + else + { + this.addFile(new ImageFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = ImageFile; diff --git a/src/loader/filetypes/JSONFile.js b/src/loader/filetypes/JSONFile.js index 6d7d5c49c..8696d09e7 100644 --- a/src/loader/filetypes/JSONFile.js +++ b/src/loader/filetypes/JSONFile.js @@ -1,224 +1,224 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetValue = require('../../utils/object/GetValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#json method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#json. - * - * @class JSONFile - * @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.JSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. - */ -var JSONFile = new Class({ - - Extends: File, - - initialize: - - // 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 - - function JSONFile (loader, key, url, xhrSettings, dataKey) - { - var extension = 'json'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - dataKey = GetFastValue(config, 'dataKey', dataKey); - } - - var fileConfig = { - type: 'json', - cache: loader.cacheManager.json, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings, - config: dataKey - }; - - File.call(this, loader, fileConfig); - - if (IsPlainObject(url)) - { - // Object provided instead of a URL, so no need to actually load it (populate data with value) - if (dataKey) - { - this.data = GetValue(url, dataKey); - } - else - { - this.data = url; - } - - this.state = CONST.FILE_POPULATED; - } - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.JSONFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - if (this.state !== CONST.FILE_POPULATED) - { - this.state = CONST.FILE_PROCESSING; - - var json = JSON.parse(this.xhrLoader.responseText); - - var key = this.config; - - if (typeof key === 'string') - { - this.data = GetValue(json, key, json); - } - else - { - this.data = json; - } - } - - this.onProcessComplete(); - } - -}); - -/** - * Adds a JSON file, or array of JSON 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.json('wavedata', 'files/AlienWaveData.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. - * - * 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.json({ - * key: 'wavedata', - * url: 'files/AlienWaveData.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.json('wavedata', 'files/AlienWaveData.json'); - * // and later in your game ... - * var data = this.cache.json.get('wavedata'); - * ``` - * - * 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 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#json - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.JSONFileConfig|Phaser.Types.Loader.FileTypes.JSONFileConfig[])} 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 `.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. - */ -FileTypesManager.register('json', function (key, url, dataKey, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new JSONFile(this, key[i])); - } - } - else - { - this.addFile(new JSONFile(this, key, url, xhrSettings, dataKey)); - } - - return this; -}); - -module.exports = JSONFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetValue = require('../../utils/object/GetValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#json method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#json. + * + * @class JSONFile + * @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.JSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. + */ +var JSONFile = new Class({ + + Extends: File, + + initialize: + + // 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 + + function JSONFile (loader, key, url, xhrSettings, dataKey) + { + var extension = 'json'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + dataKey = GetFastValue(config, 'dataKey', dataKey); + } + + var fileConfig = { + type: 'json', + cache: loader.cacheManager.json, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: dataKey + }; + + File.call(this, loader, fileConfig); + + if (IsPlainObject(url)) + { + // Object provided instead of a URL, so no need to actually load it (populate data with value) + if (dataKey) + { + this.data = GetValue(url, dataKey); + } + else + { + this.data = url; + } + + this.state = CONST.FILE_POPULATED; + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.JSONFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + if (this.state !== CONST.FILE_POPULATED) + { + this.state = CONST.FILE_PROCESSING; + + var json = JSON.parse(this.xhrLoader.responseText); + + var key = this.config; + + if (typeof key === 'string') + { + this.data = GetValue(json, key, json); + } + else + { + this.data = json; + } + } + + this.onProcessComplete(); + } + +}); + +/** + * Adds a JSON file, or array of JSON 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.json('wavedata', 'files/AlienWaveData.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. + * + * 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.json({ + * key: 'wavedata', + * url: 'files/AlienWaveData.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.json('wavedata', 'files/AlienWaveData.json'); + * // and later in your game ... + * var data = this.cache.json.get('wavedata'); + * ``` + * + * 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 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#json + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.JSONFileConfig|Phaser.Types.Loader.FileTypes.JSONFileConfig[])} 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 `.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. + */ +FileTypesManager.register('json', function (key, url, dataKey, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new JSONFile(this, key[i])); + } + } + else + { + this.addFile(new JSONFile(this, key, url, xhrSettings, dataKey)); + } + + return this; +}); + +module.exports = JSONFile; diff --git a/src/loader/filetypes/MultiAtlasFile.js b/src/loader/filetypes/MultiAtlasFile.js index 83765e00f..1e3d16dd8 100644 --- a/src/loader/filetypes/MultiAtlasFile.js +++ b/src/loader/filetypes/MultiAtlasFile.js @@ -1,327 +1,327 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var ImageFile = require('./ImageFile.js'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var JSONFile = require('./JSONFile.js'); -var MultiFile = require('../MultiFile.js'); - -/** - * @classdesc - * A single Multi Texture Atlas File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#multiatlas method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#multiatlas. - * - * @class MultiAtlasFile - * @extends Phaser.Loader.MultiFile - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig)} key - The key of the file. Must be unique within both the Loader and the Texture Manager. Or a config object. - * @param {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from. - * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data. - * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. - * @param {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file. - * @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files. - */ -var MultiAtlasFile = new Class({ - - Extends: MultiFile, - - initialize: - - function MultiAtlasFile (loader, key, atlasURL, path, baseURL, atlasXhrSettings, textureXhrSettings) - { - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - - if (GetFastValue(config, 'url', false)) - { - atlasURL = GetFastValue(config, 'url'); - } - else - { - atlasURL = GetFastValue(config, 'atlasURL'); - } - - atlasXhrSettings = GetFastValue(config, 'xhrSettings'); - path = GetFastValue(config, 'path'); - baseURL = GetFastValue(config, 'baseURL'); - textureXhrSettings = GetFastValue(config, 'textureXhrSettings'); - } - - var data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); - - MultiFile.call(this, loader, 'multiatlas', key, [ data ]); - - this.config.path = path; - this.config.baseURL = baseURL; - this.config.textureXhrSettings = textureXhrSettings; - }, - - /** - * Called by each File when it finishes loading. - * - * @method Phaser.Loader.FileTypes.MultiAtlasFile#onFileComplete - * @since 3.7.0 - * - * @param {Phaser.Loader.File} file - The File that has completed processing. - */ - onFileComplete: function (file) - { - var index = this.files.indexOf(file); - - if (index !== -1) - { - this.pending--; - - if (file.type === 'json' && file.data.hasOwnProperty('textures')) - { - // Inspect the data for the files to now load - var textures = file.data.textures; - - var config = this.config; - var loader = this.loader; - - var currentBaseURL = loader.baseURL; - var currentPath = loader.path; - var currentPrefix = loader.prefix; - - var baseURL = GetFastValue(config, 'baseURL', this.baseURL); - var path = GetFastValue(config, 'path', this.path); - var prefix = GetFastValue(config, 'prefix', this.prefix); - var textureXhrSettings = GetFastValue(config, 'textureXhrSettings'); - - loader.setBaseURL(baseURL); - loader.setPath(path); - loader.setPrefix(prefix); - - for (var i = 0; i < textures.length; i++) - { - // "image": "texture-packer-multi-atlas-0.png", - var textureURL = textures[i].image; - - var key = 'MA' + this.multiKeyIndex + '_' + textureURL; - - var image = new ImageFile(loader, key, textureURL, textureXhrSettings); - - this.addToMultiFile(image); - - loader.addFile(image); - - // "normalMap": "texture-packer-multi-atlas-0_n.png", - if (textures[i].normalMap) - { - var normalMap = new ImageFile(loader, key, textures[i].normalMap, textureXhrSettings); - - normalMap.type = 'normalMap'; - - image.setLink(normalMap); - - this.addToMultiFile(normalMap); - - loader.addFile(normalMap); - } - } - - // Reset the loader settings - loader.setBaseURL(currentBaseURL); - loader.setPath(currentPath); - loader.setPrefix(currentPrefix); - } - } - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.MultiAtlasFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - var fileJSON = this.files[0]; - - var data = []; - var images = []; - var normalMaps = []; - - for (var i = 1; i < this.files.length; i++) - { - var file = this.files[i]; - - if (file.type === 'normalMap') - { - continue; - } - - var pos = file.key.indexOf('_'); - var key = file.key.substr(pos + 1); - - var image = file.data; - - // Now we need to find out which json entry this mapped to - for (var t = 0; t < fileJSON.data.textures.length; t++) - { - var item = fileJSON.data.textures[t]; - - if (item.image === key) - { - images.push(image); - - data.push(item); - - if (file.linkFile) - { - normalMaps.push(file.linkFile.data); - } - - break; - } - } - } - - if (normalMaps.length === 0) - { - normalMaps = undefined; - } - - this.loader.textureManager.addAtlasJSONArray(this.key, images, data, normalMaps); - - this.complete = true; - - for (i = 0; i < this.files.length; i++) - { - this.files[i].pendingDestroy(); - } - } - } - -}); - -/** - * Adds a Multi Texture Atlas, or array of multi 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.multiatlas('level1', 'images/Level1.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 as exported from the application Texture Packer, - * version 4.6.3 or above, where you have made sure to use the Phaser 3 Export option. - * - * The way it works internally is that you provide a URL to the JSON file. Phaser then loads this JSON, parses it and - * extracts which texture files it also needs to load to complete the process. If the JSON also defines normal maps, - * Phaser will load those as well. - * - * 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.multiatlas({ - * key: 'level1', - * atlasURL: 'images/Level1.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig` 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.multiatlas('level1', 'images/Level1.json'); - * // and later in your game ... - * this.add.image(x, y, 'level1', '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. - * - * Note: The ability to load this type of file will only be available if the Multi Atlas 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#multiatlas - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.7.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. - * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data. - * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. - * @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. - */ -FileTypesManager.register('multiatlas', function (key, atlasURL, path, baseURL, atlasXhrSettings) -{ - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new MultiAtlasFile(this, key[i]); - - this.addFile(multifile.files); - } - } - else - { - multifile = new MultiAtlasFile(this, key, atlasURL, path, baseURL, atlasXhrSettings); - - this.addFile(multifile.files); - } - - return this; -}); - -module.exports = MultiAtlasFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var ImageFile = require('./ImageFile.js'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var JSONFile = require('./JSONFile.js'); +var MultiFile = require('../MultiFile.js'); + +/** + * @classdesc + * A single Multi Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#multiatlas method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#multiatlas. + * + * @class MultiAtlasFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig)} key - The key of the file. Must be unique within both the Loader and the Texture Manager. Or a config object. + * @param {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from. + * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data. + * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. + * @param {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file. + * @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files. + */ +var MultiAtlasFile = new Class({ + + Extends: MultiFile, + + initialize: + + function MultiAtlasFile (loader, key, atlasURL, path, baseURL, atlasXhrSettings, textureXhrSettings) + { + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + if (GetFastValue(config, 'url', false)) + { + atlasURL = GetFastValue(config, 'url'); + } + else + { + atlasURL = GetFastValue(config, 'atlasURL'); + } + + atlasXhrSettings = GetFastValue(config, 'xhrSettings'); + path = GetFastValue(config, 'path'); + baseURL = GetFastValue(config, 'baseURL'); + textureXhrSettings = GetFastValue(config, 'textureXhrSettings'); + } + + var data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); + + MultiFile.call(this, loader, 'multiatlas', key, [ data ]); + + this.config.path = path; + this.config.baseURL = baseURL; + this.config.textureXhrSettings = textureXhrSettings; + }, + + /** + * Called by each File when it finishes loading. + * + * @method Phaser.Loader.FileTypes.MultiAtlasFile#onFileComplete + * @since 3.7.0 + * + * @param {Phaser.Loader.File} file - The File that has completed processing. + */ + onFileComplete: function (file) + { + var index = this.files.indexOf(file); + + if (index !== -1) + { + this.pending--; + + if (file.type === 'json' && file.data.hasOwnProperty('textures')) + { + // Inspect the data for the files to now load + var textures = file.data.textures; + + var config = this.config; + var loader = this.loader; + + var currentBaseURL = loader.baseURL; + var currentPath = loader.path; + var currentPrefix = loader.prefix; + + var baseURL = GetFastValue(config, 'baseURL', this.baseURL); + var path = GetFastValue(config, 'path', this.path); + var prefix = GetFastValue(config, 'prefix', this.prefix); + var textureXhrSettings = GetFastValue(config, 'textureXhrSettings'); + + loader.setBaseURL(baseURL); + loader.setPath(path); + loader.setPrefix(prefix); + + for (var i = 0; i < textures.length; i++) + { + // "image": "texture-packer-multi-atlas-0.png", + var textureURL = textures[i].image; + + var key = 'MA' + this.multiKeyIndex + '_' + textureURL; + + var image = new ImageFile(loader, key, textureURL, textureXhrSettings); + + this.addToMultiFile(image); + + loader.addFile(image); + + // "normalMap": "texture-packer-multi-atlas-0_n.png", + if (textures[i].normalMap) + { + var normalMap = new ImageFile(loader, key, textures[i].normalMap, textureXhrSettings); + + normalMap.type = 'normalMap'; + + image.setLink(normalMap); + + this.addToMultiFile(normalMap); + + loader.addFile(normalMap); + } + } + + // Reset the loader settings + loader.setBaseURL(currentBaseURL); + loader.setPath(currentPath); + loader.setPrefix(currentPrefix); + } + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.MultiAtlasFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var fileJSON = this.files[0]; + + var data = []; + var images = []; + var normalMaps = []; + + for (var i = 1; i < this.files.length; i++) + { + var file = this.files[i]; + + if (file.type === 'normalMap') + { + continue; + } + + var pos = file.key.indexOf('_'); + var key = file.key.substr(pos + 1); + + var image = file.data; + + // Now we need to find out which json entry this mapped to + for (var t = 0; t < fileJSON.data.textures.length; t++) + { + var item = fileJSON.data.textures[t]; + + if (item.image === key) + { + images.push(image); + + data.push(item); + + if (file.linkFile) + { + normalMaps.push(file.linkFile.data); + } + + break; + } + } + } + + if (normalMaps.length === 0) + { + normalMaps = undefined; + } + + this.loader.textureManager.addAtlasJSONArray(this.key, images, data, normalMaps); + + this.complete = true; + + for (i = 0; i < this.files.length; i++) + { + this.files[i].pendingDestroy(); + } + } + } + +}); + +/** + * Adds a Multi Texture Atlas, or array of multi 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.multiatlas('level1', 'images/Level1.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 as exported from the application Texture Packer, + * version 4.6.3 or above, where you have made sure to use the Phaser 3 Export option. + * + * The way it works internally is that you provide a URL to the JSON file. Phaser then loads this JSON, parses it and + * extracts which texture files it also needs to load to complete the process. If the JSON also defines normal maps, + * Phaser will load those as well. + * + * 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.multiatlas({ + * key: 'level1', + * atlasURL: 'images/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig` 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.multiatlas('level1', 'images/Level1.json'); + * // and later in your game ... + * this.add.image(x, y, 'level1', '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. + * + * Note: The ability to load this type of file will only be available if the Multi Atlas 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#multiatlas + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.7.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig|Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {string} [path] - Optional path to use when loading the textures defined in the atlas data. + * @param {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. + * @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. + */ +FileTypesManager.register('multiatlas', function (key, atlasURL, path, baseURL, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new MultiAtlasFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new MultiAtlasFile(this, key, atlasURL, path, baseURL, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = MultiAtlasFile; diff --git a/src/loader/filetypes/MultiScriptFile.js b/src/loader/filetypes/MultiScriptFile.js index 581f9add0..5be8bad7e 100644 --- a/src/loader/filetypes/MultiScriptFile.js +++ b/src/loader/filetypes/MultiScriptFile.js @@ -1,211 +1,211 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var MultiFile = require('../MultiFile.js'); -var ScriptFile = require('./ScriptFile.js'); - -/** - * @classdesc - * A Multi Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#scripts method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scripts. - * - * @class MultiScriptFile - * @extends Phaser.Loader.MultiFile - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.17.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig)} key - The key to use for this file, or a file configuration object. - * @param {string[]} [url] - An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object for the script files. Used in replacement of the Loaders default XHR Settings. - */ -var MultiScriptFile = new Class({ - - Extends: MultiFile, - - initialize: - - function MultiScriptFile (loader, key, url, xhrSettings) - { - var extension = 'js'; - var files = []; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - if (!Array.isArray(url)) - { - url = [ url ]; - } - - for (var i = 0; i < url.length; i++) - { - var scriptFile = new ScriptFile(loader, { - key: key + '_' + i.toString(), - url: url[i], - extension: extension, - xhrSettings: xhrSettings - }); - - // Override the default onProcess function - scriptFile.onProcess = function () - { - this.onProcessComplete(); - }; - - files.push(scriptFile); - } - - MultiFile.call(this, loader, 'scripts', key, files); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.MultiScriptFile#addToCache - * @since 3.17.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - for (var i = 0; i < this.files.length; i++) - { - var file = this.files[i]; - - file.data = document.createElement('script'); - file.data.language = 'javascript'; - file.data.type = 'text/javascript'; - file.data.defer = false; - file.data.text = file.xhrLoader.responseText; - - document.head.appendChild(file.data); - } - - this.complete = true; - } - } - -}); - -/** - * Adds an array of Script files to the current load queue. - * - * The difference between this and the `ScriptFile` file type is that you give an array of scripts to this method, - * and the scripts are then processed _exactly_ in that order. This allows you to load a bunch of scripts that - * may have dependencies on each other without worrying about the async nature of traditional script loading. - * - * 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.scripts('PostProcess', [ - * 'libs/shaders/CopyShader.js', - * 'libs/postprocessing/EffectComposer.js', - * 'libs/postprocessing/RenderPass.js', - * 'libs/postprocessing/MaskPass.js', - * 'libs/postprocessing/ShaderPass.js', - * 'libs/postprocessing/AfterimagePass.js' - * ]); - * } - * ``` - * - * In the code above the script files will all be loaded in parallel but only processed (i.e. invoked) in the exact - * order given in the array. - * - * The files are **not** loaded right away. They are 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 files are queued - * it means you cannot use the files immediately after calling this method, but must wait for the files 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.scripts({ - * key: 'PostProcess', - * url: [ - * 'libs/shaders/CopyShader.js', - * 'libs/postprocessing/EffectComposer.js', - * 'libs/postprocessing/RenderPass.js', - * 'libs/postprocessing/MaskPass.js', - * 'libs/postprocessing/ShaderPass.js', - * 'libs/postprocessing/AfterimagePass.js' - * ] - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.MultiScriptFileConfig` for more details. - * - * Once all the files have finished loading they will automatically be converted into a script element - * via `document.createElement('script')`. They will have their language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. This is done in the exact order the files are specified in the url array. - * - * The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them. - * - * Note: The ability to load this type of file will only be available if the MultiScript 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#scripts - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.17.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. - * @param {string[]} [url] - An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. - * @param {string} [extension='js'] - The default file extension to use if no url is provided. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for these files. - * - * @return {this} The Loader instance. - */ -FileTypesManager.register('scripts', function (key, url, xhrSettings) -{ - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new MultiScriptFile(this, key[i]); - - this.addFile(multifile.files); - } - } - else - { - multifile = new MultiScriptFile(this, key, url, xhrSettings); - - this.addFile(multifile.files); - } - - return this; -}); - -module.exports = MultiScriptFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var MultiFile = require('../MultiFile.js'); +var ScriptFile = require('./ScriptFile.js'); + +/** + * @classdesc + * A Multi Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#scripts method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scripts. + * + * @class MultiScriptFile + * @extends Phaser.Loader.MultiFile + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.17.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {string[]} [url] - An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object for the script files. Used in replacement of the Loaders default XHR Settings. + */ +var MultiScriptFile = new Class({ + + Extends: MultiFile, + + initialize: + + function MultiScriptFile (loader, key, url, xhrSettings) + { + var extension = 'js'; + var files = []; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + if (!Array.isArray(url)) + { + url = [ url ]; + } + + for (var i = 0; i < url.length; i++) + { + var scriptFile = new ScriptFile(loader, { + key: key + '_' + i.toString(), + url: url[i], + extension: extension, + xhrSettings: xhrSettings + }); + + // Override the default onProcess function + scriptFile.onProcess = function () + { + this.onProcessComplete(); + }; + + files.push(scriptFile); + } + + MultiFile.call(this, loader, 'scripts', key, files); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.MultiScriptFile#addToCache + * @since 3.17.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + for (var i = 0; i < this.files.length; i++) + { + var file = this.files[i]; + + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = file.xhrLoader.responseText; + + document.head.appendChild(file.data); + } + + this.complete = true; + } + } + +}); + +/** + * Adds an array of Script files to the current load queue. + * + * The difference between this and the `ScriptFile` file type is that you give an array of scripts to this method, + * and the scripts are then processed _exactly_ in that order. This allows you to load a bunch of scripts that + * may have dependencies on each other without worrying about the async nature of traditional script loading. + * + * 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.scripts('PostProcess', [ + * 'libs/shaders/CopyShader.js', + * 'libs/postprocessing/EffectComposer.js', + * 'libs/postprocessing/RenderPass.js', + * 'libs/postprocessing/MaskPass.js', + * 'libs/postprocessing/ShaderPass.js', + * 'libs/postprocessing/AfterimagePass.js' + * ]); + * } + * ``` + * + * In the code above the script files will all be loaded in parallel but only processed (i.e. invoked) in the exact + * order given in the array. + * + * The files are **not** loaded right away. They are 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 files are queued + * it means you cannot use the files immediately after calling this method, but must wait for the files 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.scripts({ + * key: 'PostProcess', + * url: [ + * 'libs/shaders/CopyShader.js', + * 'libs/postprocessing/EffectComposer.js', + * 'libs/postprocessing/RenderPass.js', + * 'libs/postprocessing/MaskPass.js', + * 'libs/postprocessing/ShaderPass.js', + * 'libs/postprocessing/AfterimagePass.js' + * ] + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.MultiScriptFileConfig` for more details. + * + * Once all the files have finished loading they will automatically be converted into a script element + * via `document.createElement('script')`. They will have their language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. This is done in the exact order the files are specified in the url array. + * + * The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them. + * + * Note: The ability to load this type of file will only be available if the MultiScript 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#scripts + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.17.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig|Phaser.Types.Loader.FileTypes.MultiScriptFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {string[]} [url] - An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + * @param {string} [extension='js'] - The default file extension to use if no url is provided. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for these files. + * + * @return {this} The Loader instance. + */ +FileTypesManager.register('scripts', function (key, url, xhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new MultiScriptFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new MultiScriptFile(this, key, url, xhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = MultiScriptFile; diff --git a/src/loader/filetypes/PackFile.js b/src/loader/filetypes/PackFile.js index 75dbb1360..a5cc62494 100644 --- a/src/loader/filetypes/PackFile.js +++ b/src/loader/filetypes/PackFile.js @@ -1,212 +1,212 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var FileTypesManager = require('../FileTypesManager'); -var JSONFile = require('./JSONFile.js'); - -/** - * @classdesc - * A single JSON Pack File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#pack method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#pack. - * - * @class PackFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.PackFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. - */ -var PackFile = new Class({ - - Extends: JSONFile, - - initialize: - - // 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 - - function PackFile (loader, key, url, xhrSettings, dataKey) - { - JSONFile.call(this, loader, key, url, xhrSettings, dataKey); - - this.type = 'packfile'; - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.PackFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - if (this.state !== CONST.FILE_POPULATED) - { - this.state = CONST.FILE_PROCESSING; - - this.data = JSON.parse(this.xhrLoader.responseText); - } - - // Let's pass the pack file data over to the Loader ... - this.loader.addPack(this.data, this.config); - - this.onProcessComplete(); - } - -}); - -/** - * 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. - * - * 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.LoaderPlugin#addFileEvent - * @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 `.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. - */ -FileTypesManager.register('pack', function (key, url, packKey, xhrSettings) -{ - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - this.addFile(new PackFile(this, key[i])); - } - } - else - { - this.addFile(new PackFile(this, key, url, xhrSettings, packKey)); - } - - return this; -}); - -module.exports = PackFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var FileTypesManager = require('../FileTypesManager'); +var JSONFile = require('./JSONFile.js'); + +/** + * @classdesc + * A single JSON Pack File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#pack method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#pack. + * + * @class PackFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.PackFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + * @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache. + */ +var PackFile = new Class({ + + Extends: JSONFile, + + initialize: + + // 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 + + function PackFile (loader, key, url, xhrSettings, dataKey) + { + JSONFile.call(this, loader, key, url, xhrSettings, dataKey); + + this.type = 'packfile'; + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.PackFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + if (this.state !== CONST.FILE_POPULATED) + { + this.state = CONST.FILE_PROCESSING; + + this.data = JSON.parse(this.xhrLoader.responseText); + } + + // Let's pass the pack file data over to the Loader ... + this.loader.addPack(this.data, this.config); + + this.onProcessComplete(); + } + +}); + +/** + * 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. + * + * 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.LoaderPlugin#addFileEvent + * @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 `.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. + */ +FileTypesManager.register('pack', function (key, url, packKey, xhrSettings) +{ + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + this.addFile(new PackFile(this, key[i])); + } + } + else + { + this.addFile(new PackFile(this, key, url, xhrSettings, packKey)); + } + + return this; +}); + +module.exports = PackFile; diff --git a/src/loader/filetypes/PluginFile.js b/src/loader/filetypes/PluginFile.js index 361392c27..e9551b8ea 100644 --- a/src/loader/filetypes/PluginFile.js +++ b/src/loader/filetypes/PluginFile.js @@ -1,206 +1,206 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Plugin Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#plugin method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#plugin. - * - * @class PluginFile - * @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.PluginFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param {boolean} [start=false] - Automatically start the plugin after loading? - * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var PluginFile = new Class({ - - Extends: File, - - initialize: - - function PluginFile (loader, key, url, start, mapping, xhrSettings) - { - var extension = 'js'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - start = GetFastValue(config, 'start'); - mapping = GetFastValue(config, 'mapping'); - } - - var fileConfig = { - type: 'plugin', - cache: false, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings, - config: { - start: start, - mapping: mapping - } - }; - - File.call(this, loader, fileConfig); - - // If the url variable refers to a class, add the plugin directly - if (typeof url === 'function') - { - this.data = url; - - this.state = CONST.FILE_POPULATED; - } - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.PluginFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - var pluginManager = this.loader.systems.plugins; - var config = this.config; - - var start = GetFastValue(config, 'start', false); - var mapping = GetFastValue(config, 'mapping', null); - - if (this.state === CONST.FILE_POPULATED) - { - pluginManager.install(this.key, this.data, start, mapping); - } - else - { - // Plugin added via a js file - this.state = CONST.FILE_PROCESSING; - - this.data = document.createElement('script'); - this.data.language = 'javascript'; - this.data.type = 'text/javascript'; - this.data.defer = false; - this.data.text = this.xhrLoader.responseText; - - document.head.appendChild(this.data); - - var plugin = pluginManager.install(this.key, window[this.key], start, mapping); - - if (start || mapping) - { - // Install into the current Scene Systems and Scene - this.loader.systems[mapping] = plugin; - this.loader.scene[mapping] = plugin; - } - } - - this.onProcessComplete(); - } - -}); - -/** - * Adds a Plugin Script file, or array of plugin 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.plugin('modplayer', 'plugins/ModPlayer.js'); - * } - * ``` - * - * 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.plugin({ - * key: 'modplayer', - * url: 'plugins/ModPlayer.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.PluginFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a script element - * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. It will then be passed to the Phaser PluginCache.register method. - * - * 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.js". It will always add `.js` 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 Plugin 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#plugin - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.PluginFileConfig|Phaser.Types.Loader.FileTypes.PluginFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. - * @param {(string|function)} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, a plugin function. - * @param {boolean} [start] - Automatically start the plugin after loading? - * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. - * @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. - */ -FileTypesManager.register('plugin', function (key, url, start, mapping, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new PluginFile(this, key[i])); - } - } - else - { - this.addFile(new PluginFile(this, key, url, start, mapping, xhrSettings)); - } - - return this; -}); - -module.exports = PluginFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Plugin Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#plugin method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#plugin. + * + * @class PluginFile + * @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.PluginFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {boolean} [start=false] - Automatically start the plugin after loading? + * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var PluginFile = new Class({ + + Extends: File, + + initialize: + + function PluginFile (loader, key, url, start, mapping, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + start = GetFastValue(config, 'start'); + mapping = GetFastValue(config, 'mapping'); + } + + var fileConfig = { + type: 'plugin', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + start: start, + mapping: mapping + } + }; + + File.call(this, loader, fileConfig); + + // If the url variable refers to a class, add the plugin directly + if (typeof url === 'function') + { + this.data = url; + + this.state = CONST.FILE_POPULATED; + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.PluginFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + var pluginManager = this.loader.systems.plugins; + var config = this.config; + + var start = GetFastValue(config, 'start', false); + var mapping = GetFastValue(config, 'mapping', null); + + if (this.state === CONST.FILE_POPULATED) + { + pluginManager.install(this.key, this.data, start, mapping); + } + else + { + // Plugin added via a js file + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('script'); + this.data.language = 'javascript'; + this.data.type = 'text/javascript'; + this.data.defer = false; + this.data.text = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + var plugin = pluginManager.install(this.key, window[this.key], start, mapping); + + if (start || mapping) + { + // Install into the current Scene Systems and Scene + this.loader.systems[mapping] = plugin; + this.loader.scene[mapping] = plugin; + } + } + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Plugin Script file, or array of plugin 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.plugin('modplayer', 'plugins/ModPlayer.js'); + * } + * ``` + * + * 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.plugin({ + * key: 'modplayer', + * url: 'plugins/ModPlayer.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.PluginFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. It will then be passed to the Phaser PluginCache.register method. + * + * 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.js". It will always add `.js` 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 Plugin 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#plugin + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.PluginFileConfig|Phaser.Types.Loader.FileTypes.PluginFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {(string|function)} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, a plugin function. + * @param {boolean} [start] - Automatically start the plugin after loading? + * @param {string} [mapping] - If this plugin is to be injected into the Scene, this is the property key used. + * @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. + */ +FileTypesManager.register('plugin', function (key, url, start, mapping, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new PluginFile(this, key[i])); + } + } + else + { + this.addFile(new PluginFile(this, key, url, start, mapping, xhrSettings)); + } + + return this; +}); + +module.exports = PluginFile; diff --git a/src/loader/filetypes/SVGFile.js b/src/loader/filetypes/SVGFile.js index 6bcac2068..037514a6e 100644 --- a/src/loader/filetypes/SVGFile.js +++ b/src/loader/filetypes/SVGFile.js @@ -1,333 +1,333 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single SVG File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#svg method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#svg. - * - * @class SVGFile - * @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.SVGFileConfig)} 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 `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". - * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var SVGFile = new Class({ - - Extends: File, - - initialize: - - function SVGFile (loader, key, url, svgConfig, xhrSettings) - { - var extension = 'svg'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - svgConfig = GetFastValue(config, 'svgConfig', {}); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'svg', - cache: loader.textureManager, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings, - config: { - width: GetFastValue(svgConfig, 'width'), - height: GetFastValue(svgConfig, 'height'), - scale: GetFastValue(svgConfig, 'scale') - } - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.SVGFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - var text = this.xhrLoader.responseText; - var svg = [ text ]; - var width = this.config.width; - var height = this.config.height; - var scale = this.config.scale; - - resize: if (width && height || scale) - { - var xml = null; - var parser = new DOMParser(); - xml = parser.parseFromString(text, 'text/xml'); - var svgXML = xml.getElementsByTagName('svg')[0]; - - var hasViewBox = svgXML.hasAttribute('viewBox'); - var svgWidth = parseFloat(svgXML.getAttribute('width')); - var svgHeight = parseFloat(svgXML.getAttribute('height')); - - if (!hasViewBox && svgWidth && svgHeight) - { - // If there's no viewBox attribute, set one - svgXML.setAttribute('viewBox', '0 0 ' + svgWidth + ' ' + svgHeight); - } - else if (hasViewBox && !svgWidth && !svgHeight) - { - // Get the w/h from the viewbox - var viewBox = svgXML.getAttribute('viewBox').split(/\s+|,/); - - svgWidth = viewBox[2]; - svgHeight = viewBox[3]; - } - - if (scale) - { - if (svgWidth && svgHeight) - { - width = svgWidth * scale; - height = svgHeight * scale; - } - else - { - break resize; - } - } - - svgXML.setAttribute('width', width.toString() + 'px'); - svgXML.setAttribute('height', height.toString() + 'px'); - - svg = [ (new XMLSerializer()).serializeToString(svgXML) ]; - } - - try - { - var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' }); - } - catch (e) - { - this.onProcessError(); - - return; - } - - this.data = new Image(); - - this.data.crossOrigin = this.crossOrigin; - - var _this = this; - var retry = false; - - this.data.onload = function () - { - if (!retry) - { - File.revokeObjectURL(_this.data); - } - - _this.onProcessComplete(); - }; - - this.data.onerror = function () - { - // Safari 8 re-try - if (!retry) - { - retry = true; - - File.revokeObjectURL(_this.data); - - _this.data.src = 'data:image/svg+xml,' + encodeURIComponent(svg.join('')); - } - else - { - _this.onProcessError(); - } - }; - - File.createObjectURL(this.data, blob, 'image/svg+xml'); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.SVGFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var texture = this.cache.addImage(this.key, this.data); - - this.pendingDestroy(texture); - } - -}); - -/** - * Adds an SVG File, or array of SVG Files, to the current load queue. When the files are loaded they - * will be rendered to bitmap 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.svg('morty', 'images/Morty.svg'); - * } - * ``` - * - * 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.svg({ - * key: 'morty', - * url: 'images/Morty.svg' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.SVGFileConfig` 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.svg('morty', 'images/Morty.svg'); - * // and later in your game ... - * this.add.image(x, y, 'morty'); - * ``` - * - * 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. - * - * You can optionally pass an SVG Resize Configuration object when you load an SVG file. By default the SVG will be rendered to a texture - * at the same size defined in the SVG file attributes. However, this isn't always desirable. You may wish to resize the SVG (either down - * or up) to improve texture clarity, or reduce texture memory consumption. You can either specify an exact width and height to resize - * the SVG to: - * - * ```javascript - * function preload () - * { - * this.load.svg('morty', 'images/Morty.svg', { width: 300, height: 600 }); - * } - * ``` - * - * Or when using a configuration object: - * - * ```javascript - * this.load.svg({ - * key: 'morty', - * url: 'images/Morty.svg', - * svgConfig: { - * width: 300, - * height: 600 - * } - * }); - * ``` - * - * Alternatively, you can just provide a scale factor instead: - * - * ```javascript - * function preload () - * { - * this.load.svg('morty', 'images/Morty.svg', { scale: 2.5 }); - * } - * ``` - * - * Or when using a configuration object: - * - * ```javascript - * this.load.svg({ - * key: 'morty', - * url: 'images/Morty.svg', - * svgConfig: { - * scale: 2.5 - * } - * }); - * ``` - * - * If scale, width and height values are all given, the scale has priority and the width and height values are ignored. - * - * Note: The ability to load this type of file will only be available if the SVG 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#svg - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.SVGFileConfig|Phaser.Types.Loader.FileTypes.SVGFileConfig[])} 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 `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". - * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. - * @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. - */ -FileTypesManager.register('svg', function (key, url, svgConfig, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new SVGFile(this, key[i])); - } - } - else - { - this.addFile(new SVGFile(this, key, url, svgConfig, xhrSettings)); - } - - return this; -}); - -module.exports = SVGFile; - +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single SVG File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#svg method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#svg. + * + * @class SVGFile + * @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.SVGFileConfig)} 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 `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". + * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var SVGFile = new Class({ + + Extends: File, + + initialize: + + function SVGFile (loader, key, url, svgConfig, xhrSettings) + { + var extension = 'svg'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + svgConfig = GetFastValue(config, 'svgConfig', {}); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'svg', + cache: loader.textureManager, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + width: GetFastValue(svgConfig, 'width'), + height: GetFastValue(svgConfig, 'height'), + scale: GetFastValue(svgConfig, 'scale') + } + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.SVGFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + var text = this.xhrLoader.responseText; + var svg = [ text ]; + var width = this.config.width; + var height = this.config.height; + var scale = this.config.scale; + + resize: if (width && height || scale) + { + var xml = null; + var parser = new DOMParser(); + xml = parser.parseFromString(text, 'text/xml'); + var svgXML = xml.getElementsByTagName('svg')[0]; + + var hasViewBox = svgXML.hasAttribute('viewBox'); + var svgWidth = parseFloat(svgXML.getAttribute('width')); + var svgHeight = parseFloat(svgXML.getAttribute('height')); + + if (!hasViewBox && svgWidth && svgHeight) + { + // If there's no viewBox attribute, set one + svgXML.setAttribute('viewBox', '0 0 ' + svgWidth + ' ' + svgHeight); + } + else if (hasViewBox && !svgWidth && !svgHeight) + { + // Get the w/h from the viewbox + var viewBox = svgXML.getAttribute('viewBox').split(/\s+|,/); + + svgWidth = viewBox[2]; + svgHeight = viewBox[3]; + } + + if (scale) + { + if (svgWidth && svgHeight) + { + width = svgWidth * scale; + height = svgHeight * scale; + } + else + { + break resize; + } + } + + svgXML.setAttribute('width', width.toString() + 'px'); + svgXML.setAttribute('height', height.toString() + 'px'); + + svg = [ (new XMLSerializer()).serializeToString(svgXML) ]; + } + + try + { + var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' }); + } + catch (e) + { + this.onProcessError(); + + return; + } + + this.data = new Image(); + + this.data.crossOrigin = this.crossOrigin; + + var _this = this; + var retry = false; + + this.data.onload = function () + { + if (!retry) + { + File.revokeObjectURL(_this.data); + } + + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + // Safari 8 re-try + if (!retry) + { + retry = true; + + File.revokeObjectURL(_this.data); + + _this.data.src = 'data:image/svg+xml,' + encodeURIComponent(svg.join('')); + } + else + { + _this.onProcessError(); + } + }; + + File.createObjectURL(this.data, blob, 'image/svg+xml'); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.SVGFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture = this.cache.addImage(this.key, this.data); + + this.pendingDestroy(texture); + } + +}); + +/** + * Adds an SVG File, or array of SVG Files, to the current load queue. When the files are loaded they + * will be rendered to bitmap 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.svg('morty', 'images/Morty.svg'); + * } + * ``` + * + * 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.svg({ + * key: 'morty', + * url: 'images/Morty.svg' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SVGFileConfig` 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.svg('morty', 'images/Morty.svg'); + * // and later in your game ... + * this.add.image(x, y, 'morty'); + * ``` + * + * 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. + * + * You can optionally pass an SVG Resize Configuration object when you load an SVG file. By default the SVG will be rendered to a texture + * at the same size defined in the SVG file attributes. However, this isn't always desirable. You may wish to resize the SVG (either down + * or up) to improve texture clarity, or reduce texture memory consumption. You can either specify an exact width and height to resize + * the SVG to: + * + * ```javascript + * function preload () + * { + * this.load.svg('morty', 'images/Morty.svg', { width: 300, height: 600 }); + * } + * ``` + * + * Or when using a configuration object: + * + * ```javascript + * this.load.svg({ + * key: 'morty', + * url: 'images/Morty.svg', + * svgConfig: { + * width: 300, + * height: 600 + * } + * }); + * ``` + * + * Alternatively, you can just provide a scale factor instead: + * + * ```javascript + * function preload () + * { + * this.load.svg('morty', 'images/Morty.svg', { scale: 2.5 }); + * } + * ``` + * + * Or when using a configuration object: + * + * ```javascript + * this.load.svg({ + * key: 'morty', + * url: 'images/Morty.svg', + * svgConfig: { + * scale: 2.5 + * } + * }); + * ``` + * + * If scale, width and height values are all given, the scale has priority and the width and height values are ignored. + * + * Note: The ability to load this type of file will only be available if the SVG 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#svg + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.SVGFileConfig|Phaser.Types.Loader.FileTypes.SVGFileConfig[])} 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 `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". + * @param {Phaser.Types.Loader.FileTypes.SVGSizeConfig} [svgConfig] - The svg size configuration object. + * @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. + */ +FileTypesManager.register('svg', function (key, url, svgConfig, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new SVGFile(this, key[i])); + } + } + else + { + this.addFile(new SVGFile(this, key, url, svgConfig, xhrSettings)); + } + + return this; +}); + +module.exports = SVGFile; + diff --git a/src/loader/filetypes/SceneFile.js b/src/loader/filetypes/SceneFile.js index 15a54d8ef..70b8f260d 100644 --- a/src/loader/filetypes/SceneFile.js +++ b/src/loader/filetypes/SceneFile.js @@ -1,215 +1,215 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * An external Scene JavaScript File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#sceneFile method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#sceneFile. - * - * @class SceneFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.16.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.SceneFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var SceneFile = new Class({ - - Extends: File, - - initialize: - - function SceneFile (loader, key, url, xhrSettings) - { - var extension = 'js'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'text', - cache: loader.cacheManager.text, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.SceneFile#onProcess - * @since 3.16.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = this.xhrLoader.responseText; - - this.onProcessComplete(); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.SceneFile#addToCache - * @since 3.16.0 - */ - addToCache: function () - { - var code = this.data.concat('(function(){\n' + 'return new ' + this.key + '();\n' + '}).call(this);'); - - // Stops rollup from freaking out during build - var eval2 = eval; - - this.loader.sceneManager.add(this.key, eval2(code)); - - this.complete = true; - } - -}); - -/** - * Adds an external Scene file, or array of Scene 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.sceneFile('Level1', 'src/Level1.js'); - * } - * ``` - * - * 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 Scene Manager upon a successful load. - * - * For a Scene File it's vitally important that the key matches the class name in the JavaScript file. - * - * For example here is the source file: - * - * ```javascript - * class ExternalScene extends Phaser.Scene { - * - * constructor () - * { - * super('myScene'); - * } - * - * } - * ``` - * - * Because the class is called `ExternalScene` that is the exact same key you must use when loading it: - * - * ```javascript - * function preload () - * { - * this.load.sceneFile('ExternalScene', 'src/yourScene.js'); - * } - * ``` - * - * The key that is used within the Scene Manager can either be set to the same, or you can override it in the Scene - * constructor, as we've done in the example above, where the Scene key was changed to `myScene`. - * - * The key should be unique both in terms of files being loaded and Scenes already present in the Scene 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 Scene Manager first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.sceneFile({ - * key: 'Level1', - * url: 'src/Level1.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.SceneFileConfig` for more details. - * - * Once the file has finished loading it will be added to the Scene Manager. - * - * ```javascript - * this.load.sceneFile('Level1', 'src/Level1.js'); - * // and later in your game ... - * this.scene.start('Level1'); - * ``` - * - * 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 `WORLD1.` and the key was `Story` the final key will be `WORLD1.Story` and - * this is what you would use to retrieve the text from the Scene 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 "story" - * and no URL is given then the Loader will set the URL to be "story.js". It will always add `.js` 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 Scene 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#sceneFile - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.16.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.SceneFileConfig|Phaser.Types.Loader.FileTypes.SceneFileConfig[])} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @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. - */ -FileTypesManager.register('sceneFile', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new SceneFile(this, key[i])); - } - } - else - { - this.addFile(new SceneFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = SceneFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * An external Scene JavaScript File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#sceneFile method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#sceneFile. + * + * @class SceneFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.16.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.SceneFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var SceneFile = new Class({ + + Extends: File, + + initialize: + + function SceneFile (loader, key, url, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'text', + cache: loader.cacheManager.text, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.SceneFile#onProcess + * @since 3.16.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.SceneFile#addToCache + * @since 3.16.0 + */ + addToCache: function () + { + var code = this.data.concat('(function(){\n' + 'return new ' + this.key + '();\n' + '}).call(this);'); + + // Stops rollup from freaking out during build + var eval2 = eval; + + this.loader.sceneManager.add(this.key, eval2(code)); + + this.complete = true; + } + +}); + +/** + * Adds an external Scene file, or array of Scene 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.sceneFile('Level1', 'src/Level1.js'); + * } + * ``` + * + * 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 Scene Manager upon a successful load. + * + * For a Scene File it's vitally important that the key matches the class name in the JavaScript file. + * + * For example here is the source file: + * + * ```javascript + * class ExternalScene extends Phaser.Scene { + * + * constructor () + * { + * super('myScene'); + * } + * + * } + * ``` + * + * Because the class is called `ExternalScene` that is the exact same key you must use when loading it: + * + * ```javascript + * function preload () + * { + * this.load.sceneFile('ExternalScene', 'src/yourScene.js'); + * } + * ``` + * + * The key that is used within the Scene Manager can either be set to the same, or you can override it in the Scene + * constructor, as we've done in the example above, where the Scene key was changed to `myScene`. + * + * The key should be unique both in terms of files being loaded and Scenes already present in the Scene 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 Scene Manager first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.sceneFile({ + * key: 'Level1', + * url: 'src/Level1.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SceneFileConfig` for more details. + * + * Once the file has finished loading it will be added to the Scene Manager. + * + * ```javascript + * this.load.sceneFile('Level1', 'src/Level1.js'); + * // and later in your game ... + * this.scene.start('Level1'); + * ``` + * + * 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 `WORLD1.` and the key was `Story` the final key will be `WORLD1.Story` and + * this is what you would use to retrieve the text from the Scene 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 "story" + * and no URL is given then the Loader will set the URL to be "story.js". It will always add `.js` 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 Scene 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#sceneFile + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.16.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.SceneFileConfig|Phaser.Types.Loader.FileTypes.SceneFileConfig[])} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @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. + */ +FileTypesManager.register('sceneFile', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new SceneFile(this, key[i])); + } + } + else + { + this.addFile(new SceneFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = SceneFile; diff --git a/src/loader/filetypes/ScenePluginFile.js b/src/loader/filetypes/ScenePluginFile.js index fc2654fc1..fb8241a36 100644 --- a/src/loader/filetypes/ScenePluginFile.js +++ b/src/loader/filetypes/ScenePluginFile.js @@ -1,200 +1,200 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Scene Plugin Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#scenePlugin method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scenePlugin. - * - * @class ScenePluginFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.8.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param {string} [systemKey] - If this plugin is to be added to Scene.Systems, this is the property key for it. - * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var ScenePluginFile = new Class({ - - Extends: File, - - initialize: - - function ScenePluginFile (loader, key, url, systemKey, sceneKey, xhrSettings) - { - var extension = 'js'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - systemKey = GetFastValue(config, 'systemKey'); - sceneKey = GetFastValue(config, 'sceneKey'); - } - - var fileConfig = { - type: 'scenePlugin', - cache: false, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings, - config: { - systemKey: systemKey, - sceneKey: sceneKey - } - }; - - File.call(this, loader, fileConfig); - - // If the url variable refers to a class, add the plugin directly - if (typeof url === 'function') - { - this.data = url; - - this.state = CONST.FILE_POPULATED; - } - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.ScenePluginFile#onProcess - * @since 3.8.0 - */ - onProcess: function () - { - var pluginManager = this.loader.systems.plugins; - var config = this.config; - - var key = this.key; - var systemKey = GetFastValue(config, 'systemKey', key); - var sceneKey = GetFastValue(config, 'sceneKey', key); - - if (this.state === CONST.FILE_POPULATED) - { - pluginManager.installScenePlugin(systemKey, this.data, sceneKey, this.loader.scene, true); - } - else - { - // Plugin added via a js file - this.state = CONST.FILE_PROCESSING; - - this.data = document.createElement('script'); - this.data.language = 'javascript'; - this.data.type = 'text/javascript'; - this.data.defer = false; - this.data.text = this.xhrLoader.responseText; - - document.head.appendChild(this.data); - - pluginManager.installScenePlugin(systemKey, window[this.key], sceneKey, this.loader.scene, true); - } - - this.onProcessComplete(); - } - -}); - -/** - * Adds a Scene Plugin Script file, or array of plugin 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.scenePlugin('ModPlayer', 'plugins/ModPlayer.js', 'modPlayer', 'mods'); - * } - * ``` - * - * 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.scenePlugin({ - * key: 'modplayer', - * url: 'plugins/ModPlayer.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.ScenePluginFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a script element - * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. It will then be passed to the Phaser PluginCache.register method. - * - * 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.js". It will always add `.js` 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 Script 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#scenePlugin - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.8.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. - * @param {(string|function)} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, set to a plugin function. - * @param {string} [systemKey] - If this plugin is to be added to Scene.Systems, this is the property key for it. - * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. - * @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. - */ -FileTypesManager.register('scenePlugin', function (key, url, systemKey, sceneKey, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new ScenePluginFile(this, key[i])); - } - } - else - { - this.addFile(new ScenePluginFile(this, key, url, systemKey, sceneKey, xhrSettings)); - } - - return this; -}); - -module.exports = ScenePluginFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Scene Plugin Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#scenePlugin method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scenePlugin. + * + * @class ScenePluginFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.8.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {string} [systemKey] - If this plugin is to be added to Scene.Systems, this is the property key for it. + * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var ScenePluginFile = new Class({ + + Extends: File, + + initialize: + + function ScenePluginFile (loader, key, url, systemKey, sceneKey, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + systemKey = GetFastValue(config, 'systemKey'); + sceneKey = GetFastValue(config, 'sceneKey'); + } + + var fileConfig = { + type: 'scenePlugin', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings, + config: { + systemKey: systemKey, + sceneKey: sceneKey + } + }; + + File.call(this, loader, fileConfig); + + // If the url variable refers to a class, add the plugin directly + if (typeof url === 'function') + { + this.data = url; + + this.state = CONST.FILE_POPULATED; + } + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.ScenePluginFile#onProcess + * @since 3.8.0 + */ + onProcess: function () + { + var pluginManager = this.loader.systems.plugins; + var config = this.config; + + var key = this.key; + var systemKey = GetFastValue(config, 'systemKey', key); + var sceneKey = GetFastValue(config, 'sceneKey', key); + + if (this.state === CONST.FILE_POPULATED) + { + pluginManager.installScenePlugin(systemKey, this.data, sceneKey, this.loader.scene, true); + } + else + { + // Plugin added via a js file + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('script'); + this.data.language = 'javascript'; + this.data.type = 'text/javascript'; + this.data.defer = false; + this.data.text = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + pluginManager.installScenePlugin(systemKey, window[this.key], sceneKey, this.loader.scene, true); + } + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Scene Plugin Script file, or array of plugin 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.scenePlugin('ModPlayer', 'plugins/ModPlayer.js', 'modPlayer', 'mods'); + * } + * ``` + * + * 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.scenePlugin({ + * key: 'modplayer', + * url: 'plugins/ModPlayer.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ScenePluginFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. It will then be passed to the Phaser PluginCache.register method. + * + * 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.js". It will always add `.js` 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 Script 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#scenePlugin + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.8.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig|Phaser.Types.Loader.FileTypes.ScenePluginFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them. + * @param {(string|function)} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, set to a plugin function. + * @param {string} [systemKey] - If this plugin is to be added to Scene.Systems, this is the property key for it. + * @param {string} [sceneKey] - If this plugin is to be added to the Scene, this is the property key for it. + * @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. + */ +FileTypesManager.register('scenePlugin', function (key, url, systemKey, sceneKey, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new ScenePluginFile(this, key[i])); + } + } + else + { + this.addFile(new ScenePluginFile(this, key, url, systemKey, sceneKey, xhrSettings)); + } + + return this; +}); + +module.exports = ScenePluginFile; diff --git a/src/loader/filetypes/ScriptFile.js b/src/loader/filetypes/ScriptFile.js index 90e37b902..88a4df6d7 100644 --- a/src/loader/filetypes/ScriptFile.js +++ b/src/loader/filetypes/ScriptFile.js @@ -1,165 +1,165 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#script method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#script. - * - * @class ScriptFile - * @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.ScriptFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var ScriptFile = new Class({ - - Extends: File, - - initialize: - - function ScriptFile (loader, key, url, xhrSettings) - { - var extension = 'js'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'script', - cache: false, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.ScriptFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = document.createElement('script'); - this.data.language = 'javascript'; - this.data.type = 'text/javascript'; - this.data.defer = false; - this.data.text = this.xhrLoader.responseText; - - document.head.appendChild(this.data); - - this.onProcessComplete(); - } - -}); - -/** - * Adds a Script file, or array of Script 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.script('aliens', 'lib/aliens.js'); - * } - * ``` - * - * 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.script({ - * key: 'aliens', - * url: 'lib/aliens.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.ScriptFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a script element - * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. - * - * 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.js". It will always add `.js` 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 Script 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#script - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.ScriptFileConfig|Phaser.Types.Loader.FileTypes.ScriptFileConfig[])} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @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. - */ -FileTypesManager.register('script', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new ScriptFile(this, key[i])); - } - } - else - { - this.addFile(new ScriptFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = ScriptFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#script method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#script. + * + * @class ScriptFile + * @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.ScriptFileConfig)} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var ScriptFile = new Class({ + + Extends: File, + + initialize: + + function ScriptFile (loader, key, url, xhrSettings) + { + var extension = 'js'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'script', + cache: false, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.ScriptFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = document.createElement('script'); + this.data.language = 'javascript'; + this.data.type = 'text/javascript'; + this.data.defer = false; + this.data.text = this.xhrLoader.responseText; + + document.head.appendChild(this.data); + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Script file, or array of Script 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.script('aliens', 'lib/aliens.js'); + * } + * ``` + * + * 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.script({ + * key: 'aliens', + * url: 'lib/aliens.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ScriptFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. + * + * 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.js". It will always add `.js` 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 Script 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#script + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.ScriptFileConfig|Phaser.Types.Loader.FileTypes.ScriptFileConfig[])} 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 `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @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. + */ +FileTypesManager.register('script', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new ScriptFile(this, key[i])); + } + } + else + { + this.addFile(new ScriptFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = ScriptFile; diff --git a/src/loader/filetypes/SpriteSheetFile.js b/src/loader/filetypes/SpriteSheetFile.js index 12c74a4e3..e35ea5302 100644 --- a/src/loader/filetypes/SpriteSheetFile.js +++ b/src/loader/filetypes/SpriteSheetFile.js @@ -1,185 +1,185 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var ImageFile = require('./ImageFile.js'); - -/** - * @classdesc - * A single Sprite Sheet Image File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#spritesheet method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spritesheet. - * - * @class SpriteSheetFile - * @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.SpriteSheetFileConfig)} key - The key to use for this file, or a file configuration object. - * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var SpriteSheetFile = new Class({ - - Extends: ImageFile, - - initialize: - - function SpriteSheetFile (loader, key, url, frameConfig, xhrSettings) - { - ImageFile.call(this, loader, key, url, xhrSettings, frameConfig); - - this.type = 'spritesheet'; - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.SpriteSheetFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var texture = this.cache.addSpriteSheet(this.key, this.data, this.config); - - this.pendingDestroy(texture); - } - -}); - -/** - * Adds a Sprite Sheet Image, or array of Sprite Sheet Images, to the current load queue. - * - * The term 'Sprite Sheet' in Phaser means a fixed-size sheet. Where every frame in the sheet is the exact same size, - * and you reference those frames using numbers, not frame names. This is not the same thing as a Texture Atlas, where - * the frames are packed in a way where they take up the least amount of space, and are referenced by their names, - * not numbers. Some articles and software use the term 'Sprite Sheet' to mean Texture Atlas, so please be aware of - * what sort of file you're actually trying to load. - * - * 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); - * } - * ``` - * - * 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. - * - * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. - * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback - * of animated gifs to Canvas elements. - * - * 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.spritesheet({ - * key: 'bot', - * url: 'images/robot.png', - * frameConfig: { - * frameWidth: 32, - * frameHeight: 38, - * startFrame: 0, - * endFrame: 8 - * } - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig` 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); - * // and later in your game ... - * this.add.image(x, y, 'bot', 0); - * ``` - * - * 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 `PLAYER.` and the key was `Running` the final key will be `PLAYER.Running` 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.spritesheet('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ], { frameWidth: 256, frameHeight: 80 }); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.spritesheet({ - * key: 'logo', - * url: 'images/AtariLogo.png', - * normalMap: 'images/AtariLogo-n.png', - * frameConfig: { - * frameWidth: 256, - * frameHeight: 80 - * } - * }); - * ``` - * - * 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 Sprite Sheet 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#spritesheet - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig|Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. At a minimum it should have a `frameWidth` property. - * @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. - */ -FileTypesManager.register('spritesheet', function (key, url, frameConfig, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new SpriteSheetFile(this, key[i])); - } - } - else - { - this.addFile(new SpriteSheetFile(this, key, url, frameConfig, xhrSettings)); - } - - return this; -}); - -module.exports = SpriteSheetFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var ImageFile = require('./ImageFile.js'); + +/** + * @classdesc + * A single Sprite Sheet Image File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#spritesheet method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spritesheet. + * + * @class SpriteSheetFile + * @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.SpriteSheetFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {string|string[]} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var SpriteSheetFile = new Class({ + + Extends: ImageFile, + + initialize: + + function SpriteSheetFile (loader, key, url, frameConfig, xhrSettings) + { + ImageFile.call(this, loader, key, url, xhrSettings, frameConfig); + + this.type = 'spritesheet'; + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.SpriteSheetFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var texture = this.cache.addSpriteSheet(this.key, this.data, this.config); + + this.pendingDestroy(texture); + } + +}); + +/** + * Adds a Sprite Sheet Image, or array of Sprite Sheet Images, to the current load queue. + * + * The term 'Sprite Sheet' in Phaser means a fixed-size sheet. Where every frame in the sheet is the exact same size, + * and you reference those frames using numbers, not frame names. This is not the same thing as a Texture Atlas, where + * the frames are packed in a way where they take up the least amount of space, and are referenced by their names, + * not numbers. Some articles and software use the term 'Sprite Sheet' to mean Texture Atlas, so please be aware of + * what sort of file you're actually trying to load. + * + * 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); + * } + * ``` + * + * 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. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback + * of animated gifs to Canvas elements. + * + * 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.spritesheet({ + * key: 'bot', + * url: 'images/robot.png', + * frameConfig: { + * frameWidth: 32, + * frameHeight: 38, + * startFrame: 0, + * endFrame: 8 + * } + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig` 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); + * // and later in your game ... + * this.add.image(x, y, 'bot', 0); + * ``` + * + * 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 `PLAYER.` and the key was `Running` the final key will be `PLAYER.Running` 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.spritesheet('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ], { frameWidth: 256, frameHeight: 80 }); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.spritesheet({ + * key: 'logo', + * url: 'images/AtariLogo.png', + * normalMap: 'images/AtariLogo-n.png', + * frameConfig: { + * frameWidth: 256, + * frameHeight: 80 + * } + * }); + * ``` + * + * 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 Sprite Sheet 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#spritesheet + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig|Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {Phaser.Types.Loader.FileTypes.ImageFrameConfig} [frameConfig] - The frame configuration object. At a minimum it should have a `frameWidth` property. + * @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. + */ +FileTypesManager.register('spritesheet', function (key, url, frameConfig, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new SpriteSheetFile(this, key[i])); + } + } + else + { + this.addFile(new SpriteSheetFile(this, key, url, frameConfig, xhrSettings)); + } + + return this; +}); + +module.exports = SpriteSheetFile; diff --git a/src/loader/filetypes/TextFile.js b/src/loader/filetypes/TextFile.js index 5f5e222d6..6672312f6 100644 --- a/src/loader/filetypes/TextFile.js +++ b/src/loader/filetypes/TextFile.js @@ -1,169 +1,169 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Text File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#text method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#text. - * - * @class TextFile - * @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.TextFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var TextFile = new Class({ - - Extends: File, - - initialize: - - function TextFile (loader, key, url, xhrSettings) - { - var extension = 'txt'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'text', - cache: loader.cacheManager.text, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.TextFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = this.xhrLoader.responseText; - - this.onProcessComplete(); - } - -}); - -/** - * Adds a Text file, or array of Text 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.text('story', 'files/IntroStory.txt'); - * } - * ``` - * - * 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 Text Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Text 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.text({ - * key: 'story', - * url: 'files/IntroStory.txt' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TextFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.text('story', 'files/IntroStory.txt'); - * // and later in your game ... - * var data = this.cache.text.get('story'); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Text 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 "story" - * and no URL is given then the Loader will set the URL to be "story.txt". It will always add `.txt` 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 Text 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#text - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.TextFileConfig|Phaser.Types.Loader.FileTypes.TextFileConfig[])} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @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. - */ -FileTypesManager.register('text', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new TextFile(this, key[i])); - } - } - else - { - this.addFile(new TextFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = TextFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Text File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#text method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#text. + * + * @class TextFile + * @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.TextFileConfig)} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TextFile = new Class({ + + Extends: File, + + initialize: + + function TextFile (loader, key, url, xhrSettings) + { + var extension = 'txt'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'text', + cache: loader.cacheManager.text, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.TextFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + } + +}); + +/** + * Adds a Text file, or array of Text 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.text('story', 'files/IntroStory.txt'); + * } + * ``` + * + * 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 Text Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Text 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.text({ + * key: 'story', + * url: 'files/IntroStory.txt' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TextFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.text('story', 'files/IntroStory.txt'); + * // and later in your game ... + * var data = this.cache.text.get('story'); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Text 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 "story" + * and no URL is given then the Loader will set the URL to be "story.txt". It will always add `.txt` 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 Text 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#text + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TextFileConfig|Phaser.Types.Loader.FileTypes.TextFileConfig[])} 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 `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @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. + */ +FileTypesManager.register('text', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TextFile(this, key[i])); + } + } + else + { + this.addFile(new TextFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TextFile; diff --git a/src/loader/filetypes/TilemapCSVFile.js b/src/loader/filetypes/TilemapCSVFile.js index 9fee12d80..d17d4b019 100644 --- a/src/loader/filetypes/TilemapCSVFile.js +++ b/src/loader/filetypes/TilemapCSVFile.js @@ -1,189 +1,189 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var TILEMAP_FORMATS = require('../../tilemaps/Formats'); - -/** - * @classdesc - * A single Tilemap CSV File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapCSV method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapCSV. - * - * @class TilemapCSVFile - * @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.TilemapCSVFileConfig)} 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 `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var TilemapCSVFile = new Class({ - - Extends: File, - - initialize: - - function TilemapCSVFile (loader, key, url, xhrSettings) - { - var extension = 'csv'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'tilemapCSV', - cache: loader.cacheManager.tilemap, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - - this.tilemapFormat = TILEMAP_FORMATS.CSV; - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.TilemapCSVFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = this.xhrLoader.responseText; - - this.onProcessComplete(); - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.TilemapCSVFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var tiledata = { format: this.tilemapFormat, data: this.data }; - - this.cache.add(this.key, tiledata); - - this.pendingDestroy(tiledata); - } - -}); - -/** - * Adds a CSV Tilemap file, or array of CSV 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.tilemapCSV('level1', 'maps/Level1.csv'); - * } - * ``` - * - * Tilemap CSV data can be created in a text editor, or a 3rd party app that exports as CSV. - * - * 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 Tilemap Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.tilemapCSV({ - * key: 'level1', - * url: 'maps/Level1.csv' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.tilemapCSV('level1', 'maps/Level1.csv'); - * // and later in your game ... - * var map = this.make.tilemap({ key: 'level1' }); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Tilemap 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 "level" - * and no URL is given then the Loader will set the URL to be "level.csv". It will always add `.csv` 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 Tilemap CSV 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#tilemapCSV - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig|Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig[])} 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 `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". - * @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. - */ -FileTypesManager.register('tilemapCSV', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new TilemapCSVFile(this, key[i])); - } - } - else - { - this.addFile(new TilemapCSVFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = TilemapCSVFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var TILEMAP_FORMATS = require('../../tilemaps/Formats'); + +/** + * @classdesc + * A single Tilemap CSV File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapCSV method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapCSV. + * + * @class TilemapCSVFile + * @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.TilemapCSVFileConfig)} 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 `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TilemapCSVFile = new Class({ + + Extends: File, + + initialize: + + function TilemapCSVFile (loader, key, url, xhrSettings) + { + var extension = 'csv'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'tilemapCSV', + cache: loader.cacheManager.tilemap, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + + this.tilemapFormat = TILEMAP_FORMATS.CSV; + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.TilemapCSVFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = this.xhrLoader.responseText; + + this.onProcessComplete(); + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.TilemapCSVFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var tiledata = { format: this.tilemapFormat, data: this.data }; + + this.cache.add(this.key, tiledata); + + this.pendingDestroy(tiledata); + } + +}); + +/** + * Adds a CSV Tilemap file, or array of CSV 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.tilemapCSV('level1', 'maps/Level1.csv'); + * } + * ``` + * + * Tilemap CSV data can be created in a text editor, or a 3rd party app that exports as CSV. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapCSV({ + * key: 'level1', + * url: 'maps/Level1.csv' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapCSV('level1', 'maps/Level1.csv'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.csv". It will always add `.csv` 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 Tilemap CSV 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#tilemapCSV + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig|Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig[])} 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 `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". + * @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. + */ +FileTypesManager.register('tilemapCSV', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TilemapCSVFile(this, key[i])); + } + } + else + { + this.addFile(new TilemapCSVFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TilemapCSVFile; diff --git a/src/loader/filetypes/TilemapImpactFile.js b/src/loader/filetypes/TilemapImpactFile.js index 90f56ce95..b6bd2a33c 100644 --- a/src/loader/filetypes/TilemapImpactFile.js +++ b/src/loader/filetypes/TilemapImpactFile.js @@ -1,150 +1,150 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var JSONFile = require('./JSONFile.js'); -var TILEMAP_FORMATS = require('../../tilemaps/Formats'); - -/** - * @classdesc - * A single Impact.js Tilemap JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapImpact method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapImpact. - * - * @class TilemapImpactFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var TilemapImpactFile = new Class({ - - Extends: JSONFile, - - initialize: - - function TilemapImpactFile (loader, key, url, xhrSettings) - { - JSONFile.call(this, loader, key, url, xhrSettings); - - this.type = 'tilemapJSON'; - - this.cache = loader.cacheManager.tilemap; - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.TilemapImpactFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var tiledata = { format: TILEMAP_FORMATS.WELTMEISTER, data: this.data }; - - this.cache.add(this.key, tiledata); - - this.pendingDestroy(tiledata); - } - -}); - -/** - * Adds an Impact.js Tilemap file, or array of map 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.tilemapImpact('level1', 'maps/Level1.json'); - * } - * ``` - * - * Impact Tilemap data is created the Impact.js Map Editor called Weltmeister. - * - * 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 Tilemap Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.tilemapImpact({ - * key: 'level1', - * url: 'maps/Level1.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.tilemapImpact('level1', 'maps/Level1.json'); - * // and later in your game ... - * var map = this.make.tilemap({ key: 'level1' }); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Tilemap 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 "level" - * and no URL is given then the Loader will set the URL to be "level.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. - * - * Note: The ability to load this type of file will only be available if the Tilemap Impact 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#tilemapImpact - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.7.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @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. - */ -FileTypesManager.register('tilemapImpact', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new TilemapImpactFile(this, key[i])); - } - } - else - { - this.addFile(new TilemapImpactFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = TilemapImpactFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var JSONFile = require('./JSONFile.js'); +var TILEMAP_FORMATS = require('../../tilemaps/Formats'); + +/** + * @classdesc + * A single Impact.js Tilemap JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapImpact method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapImpact. + * + * @class TilemapImpactFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TilemapImpactFile = new Class({ + + Extends: JSONFile, + + initialize: + + function TilemapImpactFile (loader, key, url, xhrSettings) + { + JSONFile.call(this, loader, key, url, xhrSettings); + + this.type = 'tilemapJSON'; + + this.cache = loader.cacheManager.tilemap; + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.TilemapImpactFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var tiledata = { format: TILEMAP_FORMATS.WELTMEISTER, data: this.data }; + + this.cache.add(this.key, tiledata); + + this.pendingDestroy(tiledata); + } + +}); + +/** + * Adds an Impact.js Tilemap file, or array of map 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.tilemapImpact('level1', 'maps/Level1.json'); + * } + * ``` + * + * Impact Tilemap data is created the Impact.js Map Editor called Weltmeister. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapImpact({ + * key: 'level1', + * url: 'maps/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapImpact('level1', 'maps/Level1.json'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.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. + * + * Note: The ability to load this type of file will only be available if the Tilemap Impact 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#tilemapImpact + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.7.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig|Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @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. + */ +FileTypesManager.register('tilemapImpact', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TilemapImpactFile(this, key[i])); + } + } + else + { + this.addFile(new TilemapImpactFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TilemapImpactFile; diff --git a/src/loader/filetypes/TilemapJSONFile.js b/src/loader/filetypes/TilemapJSONFile.js index e6ecdfe6b..83bce2118 100644 --- a/src/loader/filetypes/TilemapJSONFile.js +++ b/src/loader/filetypes/TilemapJSONFile.js @@ -1,150 +1,150 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var JSONFile = require('./JSONFile.js'); -var TILEMAP_FORMATS = require('../../tilemaps/Formats'); - -/** - * @classdesc - * A single Tiled Tilemap JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapTiledJSON method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapTiledJSON. - * - * @class TilemapJSONFile - * @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.TilemapJSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var TilemapJSONFile = new Class({ - - Extends: JSONFile, - - initialize: - - function TilemapJSONFile (loader, key, url, xhrSettings) - { - JSONFile.call(this, loader, key, url, xhrSettings); - - this.type = 'tilemapJSON'; - - this.cache = loader.cacheManager.tilemap; - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.TilemapJSONFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - var tiledata = { format: TILEMAP_FORMATS.TILED_JSON, data: this.data }; - - this.cache.add(this.key, tiledata); - - this.pendingDestroy(tiledata); - } - -}); - -/** - * Adds a Tiled JSON Tilemap file, or array of map 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.tilemapTiledJSON('level1', 'maps/Level1.json'); - * } - * ``` - * - * The Tilemap data is created using the Tiled Map Editor and selecting JSON as the export format. - * - * 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 Tilemap Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.tilemapTiledJSON({ - * key: 'level1', - * url: 'maps/Level1.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.tilemapTiledJSON('level1', 'maps/Level1.json'); - * // and later in your game ... - * var map = this.make.tilemap({ key: 'level1' }); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Tilemap 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 "level" - * and no URL is given then the Loader will set the URL to be "level.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. - * - * Note: The ability to load this type of file will only be available if the Tilemap 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#tilemapTiledJSON - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig|Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @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. - */ -FileTypesManager.register('tilemapTiledJSON', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new TilemapJSONFile(this, key[i])); - } - } - else - { - this.addFile(new TilemapJSONFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = TilemapJSONFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var JSONFile = require('./JSONFile.js'); +var TILEMAP_FORMATS = require('../../tilemaps/Formats'); + +/** + * @classdesc + * A single Tiled Tilemap JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapTiledJSON method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapTiledJSON. + * + * @class TilemapJSONFile + * @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.TilemapJSONFileConfig)} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var TilemapJSONFile = new Class({ + + Extends: JSONFile, + + initialize: + + function TilemapJSONFile (loader, key, url, xhrSettings) + { + JSONFile.call(this, loader, key, url, xhrSettings); + + this.type = 'tilemapJSON'; + + this.cache = loader.cacheManager.tilemap; + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.TilemapJSONFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + var tiledata = { format: TILEMAP_FORMATS.TILED_JSON, data: this.data }; + + this.cache.add(this.key, tiledata); + + this.pendingDestroy(tiledata); + } + +}); + +/** + * Adds a Tiled JSON Tilemap file, or array of map 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.tilemapTiledJSON('level1', 'maps/Level1.json'); + * } + * ``` + * + * The Tilemap data is created using the Tiled Map Editor and selecting JSON as the export format. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapTiledJSON({ + * key: 'level1', + * url: 'maps/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapTiledJSON('level1', 'maps/Level1.json'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.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. + * + * Note: The ability to load this type of file will only be available if the Tilemap 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#tilemapTiledJSON + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig|Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig[])} 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 `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @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. + */ +FileTypesManager.register('tilemapTiledJSON', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new TilemapJSONFile(this, key[i])); + } + } + else + { + this.addFile(new TilemapJSONFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = TilemapJSONFile; diff --git a/src/loader/filetypes/UnityAtlasFile.js b/src/loader/filetypes/UnityAtlasFile.js index 690fe0315..e48eed013 100644 --- a/src/loader/filetypes/UnityAtlasFile.js +++ b/src/loader/filetypes/UnityAtlasFile.js @@ -1,236 +1,236 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var ImageFile = require('./ImageFile.js'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var MultiFile = require('../MultiFile.js'); -var TextFile = require('./TextFile.js'); - -/** - * @classdesc - * A single text file based Unity Texture Atlas File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#unityAtlas method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#unityAtlas. - * - * @class UnityAtlasFile - * @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.UnityAtlasFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @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 data file. Used in replacement of the Loaders default XHR Settings. - */ -var UnityAtlasFile = new Class({ - - Extends: MultiFile, - - initialize: - - function UnityAtlasFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) - { - var image; - var data; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - - image = new ImageFile(loader, { - key: key, - url: GetFastValue(config, 'textureURL'), - extension: GetFastValue(config, 'textureExtension', 'png'), - normalMap: GetFastValue(config, 'normalMap'), - xhrSettings: GetFastValue(config, 'textureXhrSettings') - }); - - data = new TextFile(loader, { - key: key, - url: GetFastValue(config, 'atlasURL'), - extension: GetFastValue(config, 'atlasExtension', 'txt'), - xhrSettings: GetFastValue(config, 'atlasXhrSettings') - }); - } - else - { - image = new ImageFile(loader, key, textureURL, textureXhrSettings); - data = new TextFile(loader, key, atlasURL, atlasXhrSettings); - } - - if (image.linkFile) - { - // Image has a normal map - MultiFile.call(this, loader, 'unityatlas', key, [ image, data, image.linkFile ]); - } - else - { - MultiFile.call(this, loader, 'unityatlas', key, [ image, data ]); - } - }, - - /** - * Adds this file to its target cache upon successful loading and processing. - * - * @method Phaser.Loader.FileTypes.UnityAtlasFile#addToCache - * @since 3.7.0 - */ - addToCache: function () - { - if (this.isReadyToProcess()) - { - var image = this.files[0]; - var text = this.files[1]; - var normalMap = (this.files[2]) ? this.files[2].data : null; - - this.loader.textureManager.addUnityAtlas(image.key, image.data, text.data, normalMap); - - text.addToCache(); - - this.complete = true; - } - } - -}); - -/** - * Adds a Unity YAML 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.unityAtlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.txt'); - * } - * ``` - * - * 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 YAML formatted text file as exported from Unity. - * - * 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.unityAtlas({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * atlasURL: 'images/MainMenu.txt' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig` for more details. - * - * 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.unityAtlas('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.unityAtlas('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.txt'); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.unityAtlas({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * normalMap: 'images/MainMenu-n.png', - * atlasURL: 'images/MainMenu.txt' - * }); - * ``` - * - * 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 Unity Atlas 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#unityAtlas - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig|Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @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 data file. Used in replacement of the Loaders default XHR Settings. - * - * @return {this} The Loader instance. - */ -FileTypesManager.register('unityAtlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) -{ - var multifile; - - // 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 - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - multifile = new UnityAtlasFile(this, key[i]); - - this.addFile(multifile.files); - } - } - else - { - multifile = new UnityAtlasFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); - - this.addFile(multifile.files); - } - - return this; -}); - -module.exports = UnityAtlasFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var ImageFile = require('./ImageFile.js'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var MultiFile = require('../MultiFile.js'); +var TextFile = require('./TextFile.js'); + +/** + * @classdesc + * A single text file based Unity Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#unityAtlas method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#unityAtlas. + * + * @class UnityAtlasFile + * @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.UnityAtlasFileConfig)} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @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 data file. Used in replacement of the Loaders default XHR Settings. + */ +var UnityAtlasFile = new Class({ + + Extends: MultiFile, + + initialize: + + function UnityAtlasFile (loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) + { + var image; + var data; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + + image = new ImageFile(loader, { + key: key, + url: GetFastValue(config, 'textureURL'), + extension: GetFastValue(config, 'textureExtension', 'png'), + normalMap: GetFastValue(config, 'normalMap'), + xhrSettings: GetFastValue(config, 'textureXhrSettings') + }); + + data = new TextFile(loader, { + key: key, + url: GetFastValue(config, 'atlasURL'), + extension: GetFastValue(config, 'atlasExtension', 'txt'), + xhrSettings: GetFastValue(config, 'atlasXhrSettings') + }); + } + else + { + image = new ImageFile(loader, key, textureURL, textureXhrSettings); + data = new TextFile(loader, key, atlasURL, atlasXhrSettings); + } + + if (image.linkFile) + { + // Image has a normal map + MultiFile.call(this, loader, 'unityatlas', key, [ image, data, image.linkFile ]); + } + else + { + MultiFile.call(this, loader, 'unityatlas', key, [ image, data ]); + } + }, + + /** + * Adds this file to its target cache upon successful loading and processing. + * + * @method Phaser.Loader.FileTypes.UnityAtlasFile#addToCache + * @since 3.7.0 + */ + addToCache: function () + { + if (this.isReadyToProcess()) + { + var image = this.files[0]; + var text = this.files[1]; + var normalMap = (this.files[2]) ? this.files[2].data : null; + + this.loader.textureManager.addUnityAtlas(image.key, image.data, text.data, normalMap); + + text.addToCache(); + + this.complete = true; + } + } + +}); + +/** + * Adds a Unity YAML 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.unityAtlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.txt'); + * } + * ``` + * + * 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 YAML formatted text file as exported from Unity. + * + * 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.unityAtlas({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * atlasURL: 'images/MainMenu.txt' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig` for more details. + * + * 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.unityAtlas('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.unityAtlas('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.txt'); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.unityAtlas({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * normalMap: 'images/MainMenu-n.png', + * atlasURL: 'images/MainMenu.txt' + * }); + * ``` + * + * 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 Unity Atlas 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#unityAtlas + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig|Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig[])} 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 `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @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 data file. Used in replacement of the Loaders default XHR Settings. + * + * @return {this} The Loader instance. + */ +FileTypesManager.register('unityAtlas', function (key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) +{ + var multifile; + + // 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 + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + multifile = new UnityAtlasFile(this, key[i]); + + this.addFile(multifile.files); + } + } + else + { + multifile = new UnityAtlasFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); + + this.addFile(multifile.files); + } + + return this; +}); + +module.exports = UnityAtlasFile; diff --git a/src/loader/filetypes/VideoFile.js b/src/loader/filetypes/VideoFile.js index d3188e877..7fe73626c 100644 --- a/src/loader/filetypes/VideoFile.js +++ b/src/loader/filetypes/VideoFile.js @@ -1,385 +1,385 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetURL = require('../GetURL'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * A single Video File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#video method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#video. - * - * @class VideoFile - * @extends Phaser.Loader.File - * @memberof Phaser.Loader.FileTypes - * @constructor - * @since 3.20.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. - * @param {(string|Phaser.Types.Loader.FileTypes.VideoFileConfig)} key - The key to use for this file, or a file configuration object. - * @param {any} [urlConfig] - The absolute or relative URL to load this file from in a config object. - * @param {string} [loadEvent] - The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. - * @param {boolean} [asBlob] - Load the video as a data blob, or via the Video element? - * @param {boolean} [noAudio] - Does the video have an audio track? If not you can enable auto-playing on it. - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var VideoFile = new Class({ - - Extends: File, - - initialize: - - // URL is an object created by VideoFile.getVideoURL - function VideoFile (loader, key, urlConfig, loadEvent, asBlob, noAudio, xhrSettings) - { - if (loadEvent === undefined) { loadEvent = 'loadeddata'; } - if (asBlob === undefined) { asBlob = false; } - if (noAudio === undefined) { noAudio = false; } - - if (loadEvent !== 'loadeddata' && loadEvent !== 'canplay' && loadEvent !== 'canplaythrough') - { - loadEvent = 'loadeddata'; - } - - var fileConfig = { - type: 'video', - cache: loader.cacheManager.video, - extension: urlConfig.type, - responseType: 'blob', - key: key, - url: urlConfig.url, - xhrSettings: xhrSettings, - config: { - loadEvent: loadEvent, - asBlob: asBlob, - noAudio: noAudio - } - }; - - this.onLoadCallback = this.onVideoLoadHandler.bind(this); - this.onErrorCallback = this.onVideoErrorHandler.bind(this); - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.VideoFile#onProcess - * @since 3.20.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - if (!this.config.asBlob) - { - this.onProcessComplete(); - - return; - } - - // Load Video as blob - - var video = this.createVideoElement(); - - this.data = video; - - var _this = this; - - this.data.onloadeddata = function () - { - _this.onProcessComplete(); - }; - - this.data.onerror = function () - { - File.revokeObjectURL(_this.data); - - _this.onProcessError(); - }; - - File.createObjectURL(video, this.xhrLoader.response, ''); - - video.load(); - }, - - /** - * Creates a Video Element within the DOM. - * - * @method Phaser.Loader.FileTypes.VideoFile#createVideoElement - * @private - * @since 3.20.0 - * - * @return {HTMLVideoElement} The newly created Video element. - */ - createVideoElement: function () - { - var video = document.createElement('video'); - - video.controls = false; - video.crossOrigin = this.loader.crossOrigin; - - if (this.config.noAudio) - { - video.muted = true; - video.defaultMuted = true; - - video.setAttribute('autoplay', 'autoplay'); - } - - video.setAttribute('playsinline', 'playsinline'); - video.setAttribute('preload', 'auto'); - - return video; - }, - - /** - * Internal load event callback. - * - * @method Phaser.Loader.FileTypes.VideoFile#onVideoLoadHandler - * @private - * @since 3.20.0 - * - * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. - */ - onVideoLoadHandler: function (event) - { - var video = event.target; - - video.removeEventListener(this.config.loadEvent, this.onLoadCallback, true); - video.removeEventListener('error', this.onErrorCallback, true); - - this.data = video; - - this.resetXHR(); - - this.loader.nextFile(this, true); - }, - - /** - * Internal load error event callback. - * - * @method Phaser.Loader.FileTypes.VideoFile#onVideoErrorHandler - * @private - * @since 3.20.0 - * - * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. - */ - onVideoErrorHandler: function (event) - { - var video = event.target; - - if (video) - { - video.removeEventListener(this.config.loadEvent, this.onLoadCallback, true); - video.removeEventListener('error', this.onErrorCallback, true); - } - - this.resetXHR(); - - this.loader.nextFile(this, false); - }, - - /** - * 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.FileTypes.VideoFile#load - * @since 3.20.0 - */ - load: function () - { - var loadEvent = this.config.loadEvent; - - if (this.config.asBlob) - { - File.prototype.load.call(this); - } - else - { - this.percentComplete = 0; - - var video = this.createVideoElement(); - - video.addEventListener(loadEvent, this.onLoadCallback, true); - video.addEventListener('error', this.onErrorCallback, true); - - video.src = GetURL(this, this.loader.baseURL); - - video.load(); - } - } - -}); - -VideoFile.create = function (loader, key, urls, loadEvent, asBlob, noAudio, xhrSettings) -{ - var game = loader.systems.game; - - // url may be inside key, which may be an object - if (IsPlainObject(key)) - { - urls = GetFastValue(key, 'url', []); - loadEvent = GetFastValue(key, 'loadEvent', 'loadeddata'); - asBlob = GetFastValue(key, 'asBlob', false); - noAudio = GetFastValue(key, 'noAudio', false); - xhrSettings = GetFastValue(key, 'xhrSettings'); - } - - var urlConfig = VideoFile.getVideoURL(game, urls); - - if (urlConfig) - { - return new VideoFile(loader, key, urlConfig, loadEvent, asBlob, noAudio, xhrSettings); - } -}; - -VideoFile.getVideoURL = function (game, urls) -{ - if (!Array.isArray(urls)) - { - urls = [ urls ]; - } - - for (var i = 0; i < urls.length; i++) - { - var url = GetFastValue(urls[i], 'url', urls[i]); - - if (url.indexOf('blob:') === 0) - { - return url; - } - - var videoType; - - if (url.indexOf('data:') === 0) - { - videoType = url.split(',')[0].match(/\/(.*?);/); - } - else - { - videoType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); - } - - videoType = GetFastValue(urls[i], 'type', (videoType) ? videoType[1] : '').toLowerCase(); - - if (game.device.video[videoType]) - { - return { - url: url, - type: videoType - }; - } - } - - return null; -}; - -/** - * 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' ], - * asBlob: false, - * 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.LoaderPlugin#addFileEvent - * @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[])} [urls] - The absolute or relative URL to load the video files from. - * @param {string} [loadEvent='loadeddata'] - The load event to listen for when _not_ loading as a blob. Either `loadeddata`, `canplay` or `canplaythrough`. - * @param {boolean} [asBlob=false] - Load the video as a data blob, or stream it via the Video element? - * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. - * @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. - */ -FileTypesManager.register('video', function (key, urls, loadEvent, asBlob, noAudio, xhrSettings) -{ - var videoFile; - - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - videoFile = VideoFile.create(this, key[i]); - - if (videoFile) - { - this.addFile(videoFile); - } - } - } - else - { - videoFile = VideoFile.create(this, key, urls, loadEvent, asBlob, noAudio, xhrSettings); - - if (videoFile) - { - this.addFile(videoFile); - } - } - - return this; -}); - -module.exports = VideoFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetURL = require('../GetURL'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * A single Video File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#video method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#video. + * + * @class VideoFile + * @extends Phaser.Loader.File + * @memberof Phaser.Loader.FileTypes + * @constructor + * @since 3.20.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file. + * @param {(string|Phaser.Types.Loader.FileTypes.VideoFileConfig)} key - The key to use for this file, or a file configuration object. + * @param {any} [urlConfig] - The absolute or relative URL to load this file from in a config object. + * @param {string} [loadEvent] - The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. + * @param {boolean} [asBlob] - Load the video as a data blob, or via the Video element? + * @param {boolean} [noAudio] - Does the video have an audio track? If not you can enable auto-playing on it. + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var VideoFile = new Class({ + + Extends: File, + + initialize: + + // URL is an object created by VideoFile.getVideoURL + function VideoFile (loader, key, urlConfig, loadEvent, asBlob, noAudio, xhrSettings) + { + if (loadEvent === undefined) { loadEvent = 'loadeddata'; } + if (asBlob === undefined) { asBlob = false; } + if (noAudio === undefined) { noAudio = false; } + + if (loadEvent !== 'loadeddata' && loadEvent !== 'canplay' && loadEvent !== 'canplaythrough') + { + loadEvent = 'loadeddata'; + } + + var fileConfig = { + type: 'video', + cache: loader.cacheManager.video, + extension: urlConfig.type, + responseType: 'blob', + key: key, + url: urlConfig.url, + xhrSettings: xhrSettings, + config: { + loadEvent: loadEvent, + asBlob: asBlob, + noAudio: noAudio + } + }; + + this.onLoadCallback = this.onVideoLoadHandler.bind(this); + this.onErrorCallback = this.onVideoErrorHandler.bind(this); + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.VideoFile#onProcess + * @since 3.20.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + if (!this.config.asBlob) + { + this.onProcessComplete(); + + return; + } + + // Load Video as blob + + var video = this.createVideoElement(); + + this.data = video; + + var _this = this; + + this.data.onloadeddata = function () + { + _this.onProcessComplete(); + }; + + this.data.onerror = function () + { + File.revokeObjectURL(_this.data); + + _this.onProcessError(); + }; + + File.createObjectURL(video, this.xhrLoader.response, ''); + + video.load(); + }, + + /** + * Creates a Video Element within the DOM. + * + * @method Phaser.Loader.FileTypes.VideoFile#createVideoElement + * @private + * @since 3.20.0 + * + * @return {HTMLVideoElement} The newly created Video element. + */ + createVideoElement: function () + { + var video = document.createElement('video'); + + video.controls = false; + video.crossOrigin = this.loader.crossOrigin; + + if (this.config.noAudio) + { + video.muted = true; + video.defaultMuted = true; + + video.setAttribute('autoplay', 'autoplay'); + } + + video.setAttribute('playsinline', 'playsinline'); + video.setAttribute('preload', 'auto'); + + return video; + }, + + /** + * Internal load event callback. + * + * @method Phaser.Loader.FileTypes.VideoFile#onVideoLoadHandler + * @private + * @since 3.20.0 + * + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. + */ + onVideoLoadHandler: function (event) + { + var video = event.target; + + video.removeEventListener(this.config.loadEvent, this.onLoadCallback, true); + video.removeEventListener('error', this.onErrorCallback, true); + + this.data = video; + + this.resetXHR(); + + this.loader.nextFile(this, true); + }, + + /** + * Internal load error event callback. + * + * @method Phaser.Loader.FileTypes.VideoFile#onVideoErrorHandler + * @private + * @since 3.20.0 + * + * @param {ProgressEvent} event - The DOM ProgressEvent that resulted from this load. + */ + onVideoErrorHandler: function (event) + { + var video = event.target; + + if (video) + { + video.removeEventListener(this.config.loadEvent, this.onLoadCallback, true); + video.removeEventListener('error', this.onErrorCallback, true); + } + + this.resetXHR(); + + this.loader.nextFile(this, false); + }, + + /** + * 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.FileTypes.VideoFile#load + * @since 3.20.0 + */ + load: function () + { + var loadEvent = this.config.loadEvent; + + if (this.config.asBlob) + { + File.prototype.load.call(this); + } + else + { + this.percentComplete = 0; + + var video = this.createVideoElement(); + + video.addEventListener(loadEvent, this.onLoadCallback, true); + video.addEventListener('error', this.onErrorCallback, true); + + video.src = GetURL(this, this.loader.baseURL); + + video.load(); + } + } + +}); + +VideoFile.create = function (loader, key, urls, loadEvent, asBlob, noAudio, xhrSettings) +{ + var game = loader.systems.game; + + // url may be inside key, which may be an object + if (IsPlainObject(key)) + { + urls = GetFastValue(key, 'url', []); + loadEvent = GetFastValue(key, 'loadEvent', 'loadeddata'); + asBlob = GetFastValue(key, 'asBlob', false); + noAudio = GetFastValue(key, 'noAudio', false); + xhrSettings = GetFastValue(key, 'xhrSettings'); + } + + var urlConfig = VideoFile.getVideoURL(game, urls); + + if (urlConfig) + { + return new VideoFile(loader, key, urlConfig, loadEvent, asBlob, noAudio, xhrSettings); + } +}; + +VideoFile.getVideoURL = function (game, urls) +{ + if (!Array.isArray(urls)) + { + urls = [ urls ]; + } + + for (var i = 0; i < urls.length; i++) + { + var url = GetFastValue(urls[i], 'url', urls[i]); + + if (url.indexOf('blob:') === 0) + { + return url; + } + + var videoType; + + if (url.indexOf('data:') === 0) + { + videoType = url.split(',')[0].match(/\/(.*?);/); + } + else + { + videoType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); + } + + videoType = GetFastValue(urls[i], 'type', (videoType) ? videoType[1] : '').toLowerCase(); + + if (game.device.video[videoType]) + { + return { + url: url, + type: videoType + }; + } + } + + return null; +}; + +/** + * 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' ], + * asBlob: false, + * 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.LoaderPlugin#addFileEvent + * @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[])} [urls] - The absolute or relative URL to load the video files from. + * @param {string} [loadEvent='loadeddata'] - The load event to listen for when _not_ loading as a blob. Either `loadeddata`, `canplay` or `canplaythrough`. + * @param {boolean} [asBlob=false] - Load the video as a data blob, or stream it via the Video element? + * @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it. + * @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. + */ +FileTypesManager.register('video', function (key, urls, loadEvent, asBlob, noAudio, xhrSettings) +{ + var videoFile; + + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + videoFile = VideoFile.create(this, key[i]); + + if (videoFile) + { + this.addFile(videoFile); + } + } + } + else + { + videoFile = VideoFile.create(this, key, urls, loadEvent, asBlob, noAudio, xhrSettings); + + if (videoFile) + { + this.addFile(videoFile); + } + } + + return this; +}); + +module.exports = VideoFile; diff --git a/src/loader/filetypes/XMLFile.js b/src/loader/filetypes/XMLFile.js index 8008d66d6..69fb139db 100644 --- a/src/loader/filetypes/XMLFile.js +++ b/src/loader/filetypes/XMLFile.js @@ -1,179 +1,179 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('../const'); -var File = require('../File'); -var FileTypesManager = require('../FileTypesManager'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); -var ParseXML = require('../../dom/ParseXML'); - -/** - * @classdesc - * A single XML File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#xml method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#xml. - * - * @class XMLFile - * @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.XMLFileConfig)} 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 `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. - */ -var XMLFile = new Class({ - - Extends: File, - - initialize: - - function XMLFile (loader, key, url, xhrSettings) - { - var extension = 'xml'; - - if (IsPlainObject(key)) - { - var config = key; - - key = GetFastValue(config, 'key'); - url = GetFastValue(config, 'url'); - xhrSettings = GetFastValue(config, 'xhrSettings'); - extension = GetFastValue(config, 'extension', extension); - } - - var fileConfig = { - type: 'xml', - cache: loader.cacheManager.xml, - extension: extension, - responseType: 'text', - key: key, - url: url, - xhrSettings: xhrSettings - }; - - File.call(this, loader, fileConfig); - }, - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - * - * @method Phaser.Loader.FileTypes.XMLFile#onProcess - * @since 3.7.0 - */ - onProcess: function () - { - this.state = CONST.FILE_PROCESSING; - - this.data = ParseXML(this.xhrLoader.responseText); - - if (this.data) - { - this.onProcessComplete(); - } - else - { - console.warn('Invalid XMLFile: ' + this.key); - - this.onProcessError(); - } - } - -}); - -/** - * Adds an XML file, or array of XML 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.xml('wavedata', 'files/AlienWaveData.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. - * - * The key must be a unique String. It is used to add the file to the global XML Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the XML 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 XML Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.xml({ - * key: 'wavedata', - * url: 'files/AlienWaveData.xml' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.XMLFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.xml('wavedata', 'files/AlienWaveData.xml'); - * // and later in your game ... - * var data = this.cache.xml.get('wavedata'); - * ``` - * - * 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 XML 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.xml". It will always add `.xml` 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 XML 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#xml - * @fires Phaser.Loader.LoaderPlugin#addFileEvent - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Loader.FileTypes.XMLFileConfig|Phaser.Types.Loader.FileTypes.XMLFileConfig[])} 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 `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @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. - */ -FileTypesManager.register('xml', function (key, url, xhrSettings) -{ - if (Array.isArray(key)) - { - for (var i = 0; i < key.length; i++) - { - // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object - this.addFile(new XMLFile(this, key[i])); - } - } - else - { - this.addFile(new XMLFile(this, key, url, xhrSettings)); - } - - return this; -}); - -module.exports = XMLFile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('../const'); +var File = require('../File'); +var FileTypesManager = require('../FileTypesManager'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); +var ParseXML = require('../../dom/ParseXML'); + +/** + * @classdesc + * A single XML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#xml method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#xml. + * + * @class XMLFile + * @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.XMLFileConfig)} 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 `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file. + */ +var XMLFile = new Class({ + + Extends: File, + + initialize: + + function XMLFile (loader, key, url, xhrSettings) + { + var extension = 'xml'; + + if (IsPlainObject(key)) + { + var config = key; + + key = GetFastValue(config, 'key'); + url = GetFastValue(config, 'url'); + xhrSettings = GetFastValue(config, 'xhrSettings'); + extension = GetFastValue(config, 'extension', extension); + } + + var fileConfig = { + type: 'xml', + cache: loader.cacheManager.xml, + extension: extension, + responseType: 'text', + key: key, + url: url, + xhrSettings: xhrSettings + }; + + File.call(this, loader, fileConfig); + }, + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + * + * @method Phaser.Loader.FileTypes.XMLFile#onProcess + * @since 3.7.0 + */ + onProcess: function () + { + this.state = CONST.FILE_PROCESSING; + + this.data = ParseXML(this.xhrLoader.responseText); + + if (this.data) + { + this.onProcessComplete(); + } + else + { + console.warn('Invalid XMLFile: ' + this.key); + + this.onProcessError(); + } + } + +}); + +/** + * Adds an XML file, or array of XML 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.xml('wavedata', 'files/AlienWaveData.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. + * + * The key must be a unique String. It is used to add the file to the global XML Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the XML 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 XML Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.xml({ + * key: 'wavedata', + * url: 'files/AlienWaveData.xml' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.XMLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.xml('wavedata', 'files/AlienWaveData.xml'); + * // and later in your game ... + * var data = this.cache.xml.get('wavedata'); + * ``` + * + * 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 XML 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.xml". It will always add `.xml` 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 XML 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#xml + * @fires Phaser.Loader.LoaderPlugin#addFileEvent + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Loader.FileTypes.XMLFileConfig|Phaser.Types.Loader.FileTypes.XMLFileConfig[])} 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 `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @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. + */ +FileTypesManager.register('xml', function (key, url, xhrSettings) +{ + if (Array.isArray(key)) + { + for (var i = 0; i < key.length; i++) + { + // If it's an array it has to be an array of Objects, so we get everything out of the 'key' object + this.addFile(new XMLFile(this, key[i])); + } + } + else + { + this.addFile(new XMLFile(this, key, url, xhrSettings)); + } + + return this; +}); + +module.exports = XMLFile; diff --git a/src/loader/filetypes/index.js b/src/loader/filetypes/index.js index 0dcd88de1..b224ca5fb 100644 --- a/src/loader/filetypes/index.js +++ b/src/loader/filetypes/index.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Loader.FileTypes - */ - -module.exports = { - - AnimationJSONFile: require('./AnimationJSONFile'), - AtlasJSONFile: require('./AtlasJSONFile'), - AtlasXMLFile: require('./AtlasXMLFile'), - AudioFile: require('./AudioFile'), - AudioSpriteFile: require('./AudioSpriteFile'), - BinaryFile: require('./BinaryFile'), - BitmapFontFile: require('./BitmapFontFile'), - CSSFile: require('./CSSFile'), - GLSLFile: require('./GLSLFile'), - HTML5AudioFile: require('./HTML5AudioFile'), - HTMLFile: require('./HTMLFile'), - HTMLTextureFile: require('./HTMLTextureFile'), - ImageFile: require('./ImageFile'), - JSONFile: require('./JSONFile'), - MultiAtlasFile: require('./MultiAtlasFile'), - MultiScriptFile: require('./MultiScriptFile'), - PackFile: require('./PackFile'), - PluginFile: require('./PluginFile'), - SceneFile: require('./SceneFile'), - ScenePluginFile: require('./ScenePluginFile'), - ScriptFile: require('./ScriptFile'), - SpriteSheetFile: require('./SpriteSheetFile'), - SVGFile: require('./SVGFile'), - TextFile: require('./TextFile'), - TilemapCSVFile: require('./TilemapCSVFile'), - TilemapImpactFile: require('./TilemapImpactFile'), - TilemapJSONFile: require('./TilemapJSONFile'), - UnityAtlasFile: require('./UnityAtlasFile'), - VideoFile: require('./VideoFile'), - XMLFile: require('./XMLFile') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Loader.FileTypes + */ + +module.exports = { + + AnimationJSONFile: require('./AnimationJSONFile'), + AtlasJSONFile: require('./AtlasJSONFile'), + AtlasXMLFile: require('./AtlasXMLFile'), + AudioFile: require('./AudioFile'), + AudioSpriteFile: require('./AudioSpriteFile'), + BinaryFile: require('./BinaryFile'), + BitmapFontFile: require('./BitmapFontFile'), + CSSFile: require('./CSSFile'), + GLSLFile: require('./GLSLFile'), + HTML5AudioFile: require('./HTML5AudioFile'), + HTMLFile: require('./HTMLFile'), + HTMLTextureFile: require('./HTMLTextureFile'), + ImageFile: require('./ImageFile'), + JSONFile: require('./JSONFile'), + MultiAtlasFile: require('./MultiAtlasFile'), + MultiScriptFile: require('./MultiScriptFile'), + PackFile: require('./PackFile'), + PluginFile: require('./PluginFile'), + SceneFile: require('./SceneFile'), + ScenePluginFile: require('./ScenePluginFile'), + ScriptFile: require('./ScriptFile'), + SpriteSheetFile: require('./SpriteSheetFile'), + SVGFile: require('./SVGFile'), + TextFile: require('./TextFile'), + TilemapCSVFile: require('./TilemapCSVFile'), + TilemapImpactFile: require('./TilemapImpactFile'), + TilemapJSONFile: require('./TilemapJSONFile'), + UnityAtlasFile: require('./UnityAtlasFile'), + VideoFile: require('./VideoFile'), + XMLFile: require('./XMLFile') + +}; diff --git a/src/loader/filetypes/typedefs/MultiAtlasFileConfig.js b/src/loader/filetypes/typedefs/MultiAtlasFileConfig.js index 4dcfc071a..8a9624d88 100644 --- a/src/loader/filetypes/typedefs/MultiAtlasFileConfig.js +++ b/src/loader/filetypes/typedefs/MultiAtlasFileConfig.js @@ -1,12 +1,12 @@ -/** - * @typedef {object} Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig - * - * @property {string} key - The key of the file. Must be unique within both the Loader and the Texture Manager. - * @property {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from. Or, a well formed JSON object. - * @property {string} [url] - An alias for 'atlasURL'. If given, it overrides anything set in 'atlasURL'. - * @property {string} [atlasExtension='json'] - The default file extension to use for the atlas json if no url is provided. - * @property {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file. - * @property {string} [path] - Optional path to use when loading the textures defined in the atlas data. - * @property {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. - * @property {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files. - */ +/** + * @typedef {object} Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig + * + * @property {string} key - The key of the file. Must be unique within both the Loader and the Texture Manager. + * @property {string} [atlasURL] - The absolute or relative URL to load the multi atlas json file from. Or, a well formed JSON object. + * @property {string} [url] - An alias for 'atlasURL'. If given, it overrides anything set in 'atlasURL'. + * @property {string} [atlasExtension='json'] - The default file extension to use for the atlas json if no url is provided. + * @property {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - Extra XHR Settings specifically for the atlas json file. + * @property {string} [path] - Optional path to use when loading the textures defined in the atlas data. + * @property {string} [baseURL] - Optional Base URL to use when loading the textures defined in the atlas data. + * @property {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - Extra XHR Settings specifically for the texture files. + */ diff --git a/src/loader/filetypes/typedefs/index.js b/src/loader/filetypes/typedefs/index.js index 9993b8210..b3135b1ee 100644 --- a/src/loader/filetypes/typedefs/index.js +++ b/src/loader/filetypes/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Loader.FileTypes - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Loader.FileTypes + */ diff --git a/src/loader/index.js b/src/loader/index.js index d1c83460e..fcc2e0794 100644 --- a/src/loader/index.js +++ b/src/loader/index.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../utils/object/Extend'); - -/** - * @namespace Phaser.Loader - */ - -var Loader = { - - Events: require('./events'), - - FileTypes: require('./filetypes'), - - File: require('./File'), - FileTypesManager: require('./FileTypesManager'), - GetURL: require('./GetURL'), - LoaderPlugin: require('./LoaderPlugin'), - MergeXHRSettings: require('./MergeXHRSettings'), - MultiFile: require('./MultiFile'), - XHRLoader: require('./XHRLoader'), - XHRSettings: require('./XHRSettings') - -}; - -// Merge in the consts -Loader = Extend(false, Loader, CONST); - -module.exports = Loader; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../utils/object/Extend'); + +/** + * @namespace Phaser.Loader + */ + +var Loader = { + + Events: require('./events'), + + FileTypes: require('./filetypes'), + + File: require('./File'), + FileTypesManager: require('./FileTypesManager'), + GetURL: require('./GetURL'), + LoaderPlugin: require('./LoaderPlugin'), + MergeXHRSettings: require('./MergeXHRSettings'), + MultiFile: require('./MultiFile'), + XHRLoader: require('./XHRLoader'), + XHRSettings: require('./XHRSettings') + +}; + +// Merge in the consts +Loader = Extend(false, Loader, CONST); + +module.exports = Loader; diff --git a/src/loader/typedefs/XHRSettingsObject.js b/src/loader/typedefs/XHRSettingsObject.js index 7ab530b3a..e2212d428 100644 --- a/src/loader/typedefs/XHRSettingsObject.js +++ b/src/loader/typedefs/XHRSettingsObject.js @@ -1,15 +1,15 @@ -/** - * @typedef {object} Phaser.Types.Loader.XHRSettingsObject - * @since 3.0.0 - * - * @property {XMLHttpRequestResponseType} responseType - The response type of the XHR request, i.e. `blob`, `text`, etc. - * @property {boolean} [async=true] - Should the XHR request use async or not? - * @property {string} [user=''] - Optional username for the XHR request. - * @property {string} [password=''] - Optional password for the XHR request. - * @property {integer} [timeout=0] - Optional XHR timeout value. - * @property {(string|undefined)} [header] - This value is used to populate the XHR `setRequestHeader` and is undefined by default. - * @property {(string|undefined)} [headerValue] - This value is used to populate the XHR `setRequestHeader` and is undefined by default. - * @property {(string|undefined)} [requestedWith] - This value is used to populate the XHR `setRequestHeader` and is undefined by default. - * @property {(string|undefined)} [overrideMimeType] - Provide a custom mime-type to use instead of the default. - * @property {boolean} [withCredentials=false] - The withCredentials property indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests. - */ +/** + * @typedef {object} Phaser.Types.Loader.XHRSettingsObject + * @since 3.0.0 + * + * @property {XMLHttpRequestResponseType} responseType - The response type of the XHR request, i.e. `blob`, `text`, etc. + * @property {boolean} [async=true] - Should the XHR request use async or not? + * @property {string} [user=''] - Optional username for the XHR request. + * @property {string} [password=''] - Optional password for the XHR request. + * @property {integer} [timeout=0] - Optional XHR timeout value. + * @property {(string|undefined)} [header] - This value is used to populate the XHR `setRequestHeader` and is undefined by default. + * @property {(string|undefined)} [headerValue] - This value is used to populate the XHR `setRequestHeader` and is undefined by default. + * @property {(string|undefined)} [requestedWith] - This value is used to populate the XHR `setRequestHeader` and is undefined by default. + * @property {(string|undefined)} [overrideMimeType] - Provide a custom mime-type to use instead of the default. + * @property {boolean} [withCredentials=false] - The withCredentials property indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests. + */ diff --git a/src/loader/typedefs/index.js b/src/loader/typedefs/index.js index 5c58ffa11..4dc5f16f9 100644 --- a/src/loader/typedefs/index.js +++ b/src/loader/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Loader - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Loader + */ diff --git a/src/math/Average.js b/src/math/Average.js index d846323bf..2bf89be71 100644 --- a/src/math/Average.js +++ b/src/math/Average.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the mean average of the given values. - * - * @function Phaser.Math.Average - * @since 3.0.0 - * - * @param {number[]} values - The values to average. - * - * @return {number} The average value. - */ -var Average = function (values) -{ - var sum = 0; - - for (var i = 0; i < values.length; i++) - { - sum += (+values[i]); - } - - return sum / values.length; -}; - -module.exports = Average; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the mean average of the given values. + * + * @function Phaser.Math.Average + * @since 3.0.0 + * + * @param {number[]} values - The values to average. + * + * @return {number} The average value. + */ +var Average = function (values) +{ + var sum = 0; + + for (var i = 0; i < values.length; i++) + { + sum += (+values[i]); + } + + return sum / values.length; +}; + +module.exports = Average; diff --git a/src/math/Bernstein.js b/src/math/Bernstein.js index 6ba3f5a0c..beb524b43 100644 --- a/src/math/Bernstein.js +++ b/src/math/Bernstein.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Factorial = require('./Factorial'); - -/** - * Calculates the Bernstein basis from the three factorial coefficients. - * - * @function Phaser.Math.Bernstein - * @since 3.0.0 - * - * @param {number} n - The first value. - * @param {number} i - The second value. - * - * @return {number} The Bernstein basis of Factorial(n) / Factorial(i) / Factorial(n - i) - */ -var Bernstein = function (n, i) -{ - return Factorial(n) / Factorial(i) / Factorial(n - i); -}; - -module.exports = Bernstein; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Factorial = require('./Factorial'); + +/** + * Calculates the Bernstein basis from the three factorial coefficients. + * + * @function Phaser.Math.Bernstein + * @since 3.0.0 + * + * @param {number} n - The first value. + * @param {number} i - The second value. + * + * @return {number} The Bernstein basis of Factorial(n) / Factorial(i) / Factorial(n - i) + */ +var Bernstein = function (n, i) +{ + return Factorial(n) / Factorial(i) / Factorial(n - i); +}; + +module.exports = Bernstein; diff --git a/src/math/Between.js b/src/math/Between.js index bd4101f99..fb2b89523 100644 --- a/src/math/Between.js +++ b/src/math/Between.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compute a random integer between the `min` and `max` values, inclusive. - * - * @function Phaser.Math.Between - * @since 3.0.0 - * - * @param {integer} min - The minimum value. - * @param {integer} max - The maximum value. - * - * @return {integer} The random integer. - */ -var Between = function (min, max) -{ - return Math.floor(Math.random() * (max - min + 1) + min); -}; - -module.exports = Between; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random integer between the `min` and `max` values, inclusive. + * + * @function Phaser.Math.Between + * @since 3.0.0 + * + * @param {integer} min - The minimum value. + * @param {integer} max - The maximum value. + * + * @return {integer} The random integer. + */ +var Between = function (min, max) +{ + return Math.floor(Math.random() * (max - min + 1) + min); +}; + +module.exports = Between; diff --git a/src/math/CatmullRom.js b/src/math/CatmullRom.js index b801833a9..ea7b98968 100644 --- a/src/math/CatmullRom.js +++ b/src/math/CatmullRom.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates a Catmull-Rom value from the given points, based on an alpha of 0.5. - * - * @function Phaser.Math.CatmullRom - * @since 3.0.0 - * - * @param {number} t - The amount to interpolate by. - * @param {number} p0 - The first control point. - * @param {number} p1 - The second control point. - * @param {number} p2 - The third control point. - * @param {number} p3 - The fourth control point. - * - * @return {number} The Catmull-Rom value. - */ -var CatmullRom = function (t, p0, p1, p2, p3) -{ - var v0 = (p2 - p0) * 0.5; - var v1 = (p3 - p1) * 0.5; - var t2 = t * t; - var t3 = t * t2; - - return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; -}; - -module.exports = CatmullRom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates a Catmull-Rom value from the given points, based on an alpha of 0.5. + * + * @function Phaser.Math.CatmullRom + * @since 3.0.0 + * + * @param {number} t - The amount to interpolate by. + * @param {number} p0 - The first control point. + * @param {number} p1 - The second control point. + * @param {number} p2 - The third control point. + * @param {number} p3 - The fourth control point. + * + * @return {number} The Catmull-Rom value. + */ +var CatmullRom = function (t, p0, p1, p2, p3) +{ + var v0 = (p2 - p0) * 0.5; + var v1 = (p3 - p1) * 0.5; + var t2 = t * t; + var t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; +}; + +module.exports = CatmullRom; diff --git a/src/math/CeilTo.js b/src/math/CeilTo.js index 675875923..86b7e4af1 100644 --- a/src/math/CeilTo.js +++ b/src/math/CeilTo.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Ceils to some place comparative to a `base`, default is 10 for decimal place. - * - * The `place` is represented by the power applied to `base` to get that place. - * - * @function Phaser.Math.CeilTo - * @since 3.0.0 - * - * @param {number} value - The value to round. - * @param {number} [place=0] - The place to round to. - * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. - * - * @return {number} The rounded value. - */ -var CeilTo = function (value, place, base) -{ - if (place === undefined) { place = 0; } - if (base === undefined) { base = 10; } - - var p = Math.pow(base, -place); - - return Math.ceil(value * p) / p; -}; - -module.exports = CeilTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * + * The `place` is represented by the power applied to `base` to get that place. + * + * @function Phaser.Math.CeilTo + * @since 3.0.0 + * + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. + * + * @return {number} The rounded value. + */ +var CeilTo = function (value, place, base) +{ + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; +}; + +module.exports = CeilTo; diff --git a/src/math/Clamp.js b/src/math/Clamp.js index 4f3a6e848..57d962dd7 100644 --- a/src/math/Clamp.js +++ b/src/math/Clamp.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Force a value within the boundaries by clamping it to the range `min`, `max`. - * - * @function Phaser.Math.Clamp - * @since 3.0.0 - * - * @param {number} value - The value to be clamped. - * @param {number} min - The minimum bounds. - * @param {number} max - The maximum bounds. - * - * @return {number} The clamped value. - */ -var Clamp = function (value, min, max) -{ - return Math.max(min, Math.min(max, value)); -}; - -module.exports = Clamp; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @function Phaser.Math.Clamp + * @since 3.0.0 + * + * @param {number} value - The value to be clamped. + * @param {number} min - The minimum bounds. + * @param {number} max - The maximum bounds. + * + * @return {number} The clamped value. + */ +var Clamp = function (value, min, max) +{ + return Math.max(min, Math.min(max, value)); +}; + +module.exports = Clamp; diff --git a/src/math/DegToRad.js b/src/math/DegToRad.js index 5fd989c20..c049bbcf3 100644 --- a/src/math/DegToRad.js +++ b/src/math/DegToRad.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); - -/** - * Convert the given angle from degrees, to the equivalent angle in radians. - * - * @function Phaser.Math.DegToRad - * @since 3.0.0 - * - * @param {integer} degrees - The angle (in degrees) to convert to radians. - * - * @return {number} The given angle converted to radians. - */ -var DegToRad = function (degrees) -{ - return degrees * CONST.DEG_TO_RAD; -}; - -module.exports = DegToRad; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); + +/** + * Convert the given angle from degrees, to the equivalent angle in radians. + * + * @function Phaser.Math.DegToRad + * @since 3.0.0 + * + * @param {integer} degrees - The angle (in degrees) to convert to radians. + * + * @return {number} The given angle converted to radians. + */ +var DegToRad = function (degrees) +{ + return degrees * CONST.DEG_TO_RAD; +}; + +module.exports = DegToRad; diff --git a/src/math/Difference.js b/src/math/Difference.js index 41a5a83c1..f6f68fcf2 100644 --- a/src/math/Difference.js +++ b/src/math/Difference.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the positive difference of two given numbers. - * - * @function Phaser.Math.Difference - * @since 3.0.0 - * - * @param {number} a - The first number in the calculation. - * @param {number} b - The second number in the calculation. - * - * @return {number} The positive difference of the two given numbers. - */ -var Difference = function (a, b) -{ - return Math.abs(a - b); -}; - -module.exports = Difference; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the positive difference of two given numbers. + * + * @function Phaser.Math.Difference + * @since 3.0.0 + * + * @param {number} a - The first number in the calculation. + * @param {number} b - The second number in the calculation. + * + * @return {number} The positive difference of the two given numbers. + */ +var Difference = function (a, b) +{ + return Math.abs(a - b); +}; + +module.exports = Difference; diff --git a/src/math/Factorial.js b/src/math/Factorial.js index 61f38bcef..6285c98f9 100644 --- a/src/math/Factorial.js +++ b/src/math/Factorial.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates the factorial of a given number for integer values greater than 0. - * - * @function Phaser.Math.Factorial - * @since 3.0.0 - * - * @param {number} value - A positive integer to calculate the factorial of. - * - * @return {number} The factorial of the given number. - */ -var Factorial = function (value) -{ - if (value === 0) - { - return 1; - } - - var res = value; - - while (--value) - { - res *= value; - } - - return res; -}; - -module.exports = Factorial; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates the factorial of a given number for integer values greater than 0. + * + * @function Phaser.Math.Factorial + * @since 3.0.0 + * + * @param {number} value - A positive integer to calculate the factorial of. + * + * @return {number} The factorial of the given number. + */ +var Factorial = function (value) +{ + if (value === 0) + { + return 1; + } + + var res = value; + + while (--value) + { + res *= value; + } + + return res; +}; + +module.exports = Factorial; diff --git a/src/math/FloatBetween.js b/src/math/FloatBetween.js index 86a406978..bceef5e13 100644 --- a/src/math/FloatBetween.js +++ b/src/math/FloatBetween.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Generate a random floating point number between the two given bounds, minimum inclusive, maximum exclusive. - * - * @function Phaser.Math.FloatBetween - * @since 3.0.0 - * - * @param {number} min - The lower bound for the float, inclusive. - * @param {number} max - The upper bound for the float exclusive. - * - * @return {number} A random float within the given range. - */ -var FloatBetween = function (min, max) -{ - return Math.random() * (max - min) + min; -}; - -module.exports = FloatBetween; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Generate a random floating point number between the two given bounds, minimum inclusive, maximum exclusive. + * + * @function Phaser.Math.FloatBetween + * @since 3.0.0 + * + * @param {number} min - The lower bound for the float, inclusive. + * @param {number} max - The upper bound for the float exclusive. + * + * @return {number} A random float within the given range. + */ +var FloatBetween = function (min, max) +{ + return Math.random() * (max - min) + min; +}; + +module.exports = FloatBetween; diff --git a/src/math/FloorTo.js b/src/math/FloorTo.js index 15ad4a8a7..449a26969 100644 --- a/src/math/FloorTo.js +++ b/src/math/FloorTo.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Floors to some place comparative to a `base`, default is 10 for decimal place. - * - * The `place` is represented by the power applied to `base` to get that place. - * - * @function Phaser.Math.FloorTo - * @since 3.0.0 - * - * @param {number} value - The value to round. - * @param {integer} [place=0] - The place to round to. - * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. - * - * @return {number} The rounded value. - */ -var FloorTo = function (value, place, base) -{ - if (place === undefined) { place = 0; } - if (base === undefined) { base = 10; } - - var p = Math.pow(base, -place); - - return Math.floor(value * p) / p; -}; - -module.exports = FloorTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * + * The `place` is represented by the power applied to `base` to get that place. + * + * @function Phaser.Math.FloorTo + * @since 3.0.0 + * + * @param {number} value - The value to round. + * @param {integer} [place=0] - The place to round to. + * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. + * + * @return {number} The rounded value. + */ +var FloorTo = function (value, place, base) +{ + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; +}; + +module.exports = FloorTo; diff --git a/src/math/FromPercent.js b/src/math/FromPercent.js index 8fb150514..ede4f3e9d 100644 --- a/src/math/FromPercent.js +++ b/src/math/FromPercent.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('./Clamp'); - -/** - * Return 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 between 0 and 1 representing the percentage. - * @param {number} min - The minimum value. - * @param {number} [max] - The maximum value. - * - * @return {number} The value that is `percent` percent between `min` and `max`. - */ -var FromPercent = function (percent, min, max) -{ - percent = Clamp(percent, 0, 1); - - return (max - min) * percent; -}; - -module.exports = FromPercent; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('./Clamp'); + +/** + * Return 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 between 0 and 1 representing the percentage. + * @param {number} min - The minimum value. + * @param {number} [max] - The maximum value. + * + * @return {number} The value that is `percent` percent between `min` and `max`. + */ +var FromPercent = function (percent, min, max) +{ + percent = Clamp(percent, 0, 1); + + return (max - min) * percent; +}; + +module.exports = FromPercent; diff --git a/src/math/GetSpeed.js b/src/math/GetSpeed.js index 0c21b7e48..dba0cd7a7 100644 --- a/src/math/GetSpeed.js +++ b/src/math/GetSpeed.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate a per-ms speed from a distance and time (given in seconds). - * - * @function Phaser.Math.GetSpeed - * @since 3.0.0 - * - * @param {number} distance - The distance. - * @param {integer} time - The time, in seconds. - * - * @return {number} The speed, in distance per ms. - * - * @example - * // 400px over 1 second is 0.4 px/ms - * Phaser.Math.GetSpeed(400, 1) // -> 0.4 - */ -var GetSpeed = function (distance, time) -{ - return (distance / time) / 1000; -}; - -module.exports = GetSpeed; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate a per-ms speed from a distance and time (given in seconds). + * + * @function Phaser.Math.GetSpeed + * @since 3.0.0 + * + * @param {number} distance - The distance. + * @param {integer} time - The time, in seconds. + * + * @return {number} The speed, in distance per ms. + * + * @example + * // 400px over 1 second is 0.4 px/ms + * Phaser.Math.GetSpeed(400, 1) // -> 0.4 + */ +var GetSpeed = function (distance, time) +{ + return (distance / time) / 1000; +}; + +module.exports = GetSpeed; diff --git a/src/math/IsEven.js b/src/math/IsEven.js index 736bdba22..6b85cb453 100644 --- a/src/math/IsEven.js +++ b/src/math/IsEven.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check if a given value is an even number. - * - * @function Phaser.Math.IsEven - * @since 3.0.0 - * - * @param {number} value - The number to perform the check with. - * - * @return {boolean} Whether the number is even or not. - */ -var IsEven = function (value) -{ - // Use abstract equality == for "is number" test - - // eslint-disable-next-line eqeqeq - return (value == parseFloat(value)) ? !(value % 2) : void 0; -}; - -module.exports = IsEven; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check if a given value is an even number. + * + * @function Phaser.Math.IsEven + * @since 3.0.0 + * + * @param {number} value - The number to perform the check with. + * + * @return {boolean} Whether the number is even or not. + */ +var IsEven = function (value) +{ + // Use abstract equality == for "is number" test + + // eslint-disable-next-line eqeqeq + return (value == parseFloat(value)) ? !(value % 2) : void 0; +}; + +module.exports = IsEven; diff --git a/src/math/IsEvenStrict.js b/src/math/IsEvenStrict.js index d7003c87d..fc701a30b 100644 --- a/src/math/IsEvenStrict.js +++ b/src/math/IsEvenStrict.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check if a given value is an even number using a strict type check. - * - * @function Phaser.Math.IsEvenStrict - * @since 3.0.0 - * - * @param {number} value - The number to perform the check with. - * - * @return {boolean} Whether the number is even or not. - */ -var IsEvenStrict = function (value) -{ - // Use strict equality === for "is number" test - return (value === parseFloat(value)) ? !(value % 2) : void 0; -}; - -module.exports = IsEvenStrict; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check if a given value is an even number using a strict type check. + * + * @function Phaser.Math.IsEvenStrict + * @since 3.0.0 + * + * @param {number} value - The number to perform the check with. + * + * @return {boolean} Whether the number is even or not. + */ +var IsEvenStrict = function (value) +{ + // Use strict equality === for "is number" test + return (value === parseFloat(value)) ? !(value % 2) : void 0; +}; + +module.exports = IsEvenStrict; diff --git a/src/math/Linear.js b/src/math/Linear.js index f7c242004..1ae5c8471 100644 --- a/src/math/Linear.js +++ b/src/math/Linear.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculates a linear (interpolation) value over t. - * - * @function Phaser.Math.Linear - * @since 3.0.0 - * - * @param {number} p0 - The first point. - * @param {number} p1 - The second point. - * @param {number} t - The percentage between p0 and p1 to return, represented as a number between 0 and 1. - * - * @return {number} The step t% of the way between p0 and p1. - */ -var Linear = function (p0, p1, t) -{ - return (p1 - p0) * t + p0; -}; - -module.exports = Linear; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculates a linear (interpolation) value over t. + * + * @function Phaser.Math.Linear + * @since 3.0.0 + * + * @param {number} p0 - The first point. + * @param {number} p1 - The second point. + * @param {number} t - The percentage between p0 and p1 to return, represented as a number between 0 and 1. + * + * @return {number} The step t% of the way between p0 and p1. + */ +var Linear = function (p0, p1, t) +{ + return (p1 - p0) * t + p0; +}; + +module.exports = Linear; diff --git a/src/math/Matrix3.js b/src/math/Matrix3.js index 4a3f59fd1..c44971ba5 100644 --- a/src/math/Matrix3.js +++ b/src/math/Matrix3.js @@ -1,587 +1,587 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji -// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A three-dimensional matrix. - * - * Defaults to the identity matrix when instantiated. - * - * @class Matrix3 - * @memberof Phaser.Math - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} [m] - Optional Matrix3 to copy values from. - */ -var Matrix3 = new Class({ - - initialize: - - function Matrix3 (m) - { - /** - * The matrix values. - * - * @name Phaser.Math.Matrix3#val - * @type {Float32Array} - * @since 3.0.0 - */ - this.val = new Float32Array(9); - - if (m) - { - // Assume Matrix3 with val: - this.copy(m); - } - else - { - // Default to identity - this.identity(); - } - }, - - /** - * Make a clone of this Matrix3. - * - * @method Phaser.Math.Matrix3#clone - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix3} A clone of this Matrix3. - */ - clone: function () - { - return new Matrix3(this); - }, - - /** - * This method is an alias for `Matrix3.copy`. - * - * @method Phaser.Math.Matrix3#set - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} src - The Matrix to set the values of this Matrix's from. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - set: function (src) - { - return this.copy(src); - }, - - /** - * Copy the values of a given Matrix into this Matrix. - * - * @method Phaser.Math.Matrix3#copy - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} src - The Matrix to copy the values from. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - copy: function (src) - { - var out = this.val; - var a = src.val; - - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - - return this; - }, - - /** - * Copy the values of a given Matrix4 into this Matrix3. - * - * @method Phaser.Math.Matrix3#fromMat4 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} m - The Matrix4 to copy the values from. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - fromMat4: function (m) - { - var a = m.val; - var out = this.val; - - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[4]; - out[4] = a[5]; - out[5] = a[6]; - out[6] = a[8]; - out[7] = a[9]; - out[8] = a[10]; - - return this; - }, - - /** - * Set the values of this Matrix from the given array. - * - * @method Phaser.Math.Matrix3#fromArray - * @since 3.0.0 - * - * @param {array} a - The array to copy the values from. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - fromArray: function (a) - { - var out = this.val; - - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - - return this; - }, - - /** - * Reset this Matrix to an identity (default) matrix. - * - * @method Phaser.Math.Matrix3#identity - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - identity: function () - { - var out = this.val; - - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 1; - out[5] = 0; - out[6] = 0; - out[7] = 0; - out[8] = 1; - - return this; - }, - - /** - * Transpose this Matrix. - * - * @method Phaser.Math.Matrix3#transpose - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - transpose: function () - { - var a = this.val; - var a01 = a[1]; - var a02 = a[2]; - var a12 = a[5]; - - a[1] = a[3]; - a[2] = a[6]; - a[3] = a01; - a[5] = a[7]; - a[6] = a02; - a[7] = a12; - - return this; - }, - - /** - * Invert this Matrix. - * - * @method Phaser.Math.Matrix3#invert - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - invert: function () - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a10 = a[3]; - var a11 = a[4]; - var a12 = a[5]; - var a20 = a[6]; - var a21 = a[7]; - var a22 = a[8]; - - var b01 = a22 * a11 - a12 * a21; - var b11 = -a22 * a10 + a12 * a20; - var b21 = a21 * a10 - a11 * a20; - - // Calculate the determinant - var det = a00 * b01 + a01 * b11 + a02 * b21; - - if (!det) - { - return null; - } - - det = 1 / det; - - a[0] = b01 * det; - a[1] = (-a22 * a01 + a02 * a21) * det; - a[2] = (a12 * a01 - a02 * a11) * det; - a[3] = b11 * det; - a[4] = (a22 * a00 - a02 * a20) * det; - a[5] = (-a12 * a00 + a02 * a10) * det; - a[6] = b21 * det; - a[7] = (-a21 * a00 + a01 * a20) * det; - a[8] = (a11 * a00 - a01 * a10) * det; - - return this; - }, - - /** - * Calculate the adjoint, or adjugate, of this Matrix. - * - * @method Phaser.Math.Matrix3#adjoint - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - adjoint: function () - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a10 = a[3]; - var a11 = a[4]; - var a12 = a[5]; - var a20 = a[6]; - var a21 = a[7]; - var a22 = a[8]; - - a[0] = (a11 * a22 - a12 * a21); - a[1] = (a02 * a21 - a01 * a22); - a[2] = (a01 * a12 - a02 * a11); - a[3] = (a12 * a20 - a10 * a22); - a[4] = (a00 * a22 - a02 * a20); - a[5] = (a02 * a10 - a00 * a12); - a[6] = (a10 * a21 - a11 * a20); - a[7] = (a01 * a20 - a00 * a21); - a[8] = (a00 * a11 - a01 * a10); - - return this; - }, - - /** - * Calculate the determinant of this Matrix. - * - * @method Phaser.Math.Matrix3#determinant - * @since 3.0.0 - * - * @return {number} The determinant of this Matrix. - */ - determinant: function () - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a10 = a[3]; - var a11 = a[4]; - var a12 = a[5]; - var a20 = a[6]; - var a21 = a[7]; - var a22 = a[8]; - - return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); - }, - - /** - * Multiply this Matrix by the given Matrix. - * - * @method Phaser.Math.Matrix3#multiply - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} src - The Matrix to multiply this Matrix by. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - multiply: function (src) - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a10 = a[3]; - var a11 = a[4]; - var a12 = a[5]; - var a20 = a[6]; - var a21 = a[7]; - var a22 = a[8]; - - var b = src.val; - - var b00 = b[0]; - var b01 = b[1]; - var b02 = b[2]; - var b10 = b[3]; - var b11 = b[4]; - var b12 = b[5]; - var b20 = b[6]; - var b21 = b[7]; - var b22 = b[8]; - - a[0] = b00 * a00 + b01 * a10 + b02 * a20; - a[1] = b00 * a01 + b01 * a11 + b02 * a21; - a[2] = b00 * a02 + b01 * a12 + b02 * a22; - - a[3] = b10 * a00 + b11 * a10 + b12 * a20; - a[4] = b10 * a01 + b11 * a11 + b12 * a21; - a[5] = b10 * a02 + b11 * a12 + b12 * a22; - - a[6] = b20 * a00 + b21 * a10 + b22 * a20; - a[7] = b20 * a01 + b21 * a11 + b22 * a21; - a[8] = b20 * a02 + b21 * a12 + b22 * a22; - - return this; - }, - - /** - * Translate this Matrix using the given Vector. - * - * @method Phaser.Math.Matrix3#translate - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to translate this Matrix with. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - translate: function (v) - { - var a = this.val; - var x = v.x; - var y = v.y; - - a[6] = x * a[0] + y * a[3] + a[6]; - a[7] = x * a[1] + y * a[4] + a[7]; - a[8] = x * a[2] + y * a[5] + a[8]; - - return this; - }, - - /** - * Apply a rotation transformation to this Matrix. - * - * @method Phaser.Math.Matrix3#rotate - * @since 3.0.0 - * - * @param {number} rad - The angle in radians to rotate by. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - rotate: function (rad) - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a10 = a[3]; - var a11 = a[4]; - var a12 = a[5]; - - var s = Math.sin(rad); - var c = Math.cos(rad); - - a[0] = c * a00 + s * a10; - a[1] = c * a01 + s * a11; - a[2] = c * a02 + s * a12; - - a[3] = c * a10 - s * a00; - a[4] = c * a11 - s * a01; - a[5] = c * a12 - s * a02; - - return this; - }, - - /** - * Apply a scale transformation to this Matrix. - * - * Uses the `x` and `y` components of the given Vector to scale the Matrix. - * - * @method Phaser.Math.Matrix3#scale - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to scale this Matrix with. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - scale: function (v) - { - var a = this.val; - var x = v.x; - var y = v.y; - - a[0] = x * a[0]; - a[1] = x * a[1]; - a[2] = x * a[2]; - - a[3] = y * a[3]; - a[4] = y * a[4]; - a[5] = y * a[5]; - - return this; - }, - - /** - * Set the values of this Matrix from the given Quaternion. - * - * @method Phaser.Math.Matrix3#fromQuat - * @since 3.0.0 - * - * @param {Phaser.Math.Quaternion} q - The Quaternion to set the values of this Matrix from. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - fromQuat: function (q) - { - var x = q.x; - var y = q.y; - var z = q.z; - var w = q.w; - - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - var out = this.val; - - out[0] = 1 - (yy + zz); - out[3] = xy + wz; - out[6] = xz - wy; - - out[1] = xy - wz; - out[4] = 1 - (xx + zz); - out[7] = yz + wx; - - out[2] = xz + wy; - out[5] = yz - wx; - out[8] = 1 - (xx + yy); - - return this; - }, - - /** - * Set the values of this Matrix3 to be normalized from the given Matrix4. - * - * @method Phaser.Math.Matrix3#normalFromMat4 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} m - The Matrix4 to normalize the values from. - * - * @return {Phaser.Math.Matrix3} This Matrix3. - */ - normalFromMat4: function (m) - { - var a = m.val; - var out = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - var a30 = a[12]; - var a31 = a[13]; - var a32 = a[14]; - var a33 = a[15]; - - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) - { - return null; - } - - det = 1 / det; - - out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - - out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - - out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - - return this; - } - -}); - -module.exports = Matrix3; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A three-dimensional matrix. + * + * Defaults to the identity matrix when instantiated. + * + * @class Matrix3 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} [m] - Optional Matrix3 to copy values from. + */ +var Matrix3 = new Class({ + + initialize: + + function Matrix3 (m) + { + /** + * The matrix values. + * + * @name Phaser.Math.Matrix3#val + * @type {Float32Array} + * @since 3.0.0 + */ + this.val = new Float32Array(9); + + if (m) + { + // Assume Matrix3 with val: + this.copy(m); + } + else + { + // Default to identity + this.identity(); + } + }, + + /** + * Make a clone of this Matrix3. + * + * @method Phaser.Math.Matrix3#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} A clone of this Matrix3. + */ + clone: function () + { + return new Matrix3(this); + }, + + /** + * This method is an alias for `Matrix3.copy`. + * + * @method Phaser.Math.Matrix3#set + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} src - The Matrix to set the values of this Matrix's from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + set: function (src) + { + return this.copy(src); + }, + + /** + * Copy the values of a given Matrix into this Matrix. + * + * @method Phaser.Math.Matrix3#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} src - The Matrix to copy the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + copy: function (src) + { + var out = this.val; + var a = src.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + + return this; + }, + + /** + * Copy the values of a given Matrix4 into this Matrix3. + * + * @method Phaser.Math.Matrix3#fromMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} m - The Matrix4 to copy the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + fromMat4: function (m) + { + var a = m.val; + var out = this.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + + return this; + }, + + /** + * Set the values of this Matrix from the given array. + * + * @method Phaser.Math.Matrix3#fromArray + * @since 3.0.0 + * + * @param {array} a - The array to copy the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + fromArray: function (a) + { + var out = this.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + + return this; + }, + + /** + * Reset this Matrix to an identity (default) matrix. + * + * @method Phaser.Math.Matrix3#identity + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + identity: function () + { + var out = this.val; + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + + return this; + }, + + /** + * Transpose this Matrix. + * + * @method Phaser.Math.Matrix3#transpose + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + transpose: function () + { + var a = this.val; + var a01 = a[1]; + var a02 = a[2]; + var a12 = a[5]; + + a[1] = a[3]; + a[2] = a[6]; + a[3] = a01; + a[5] = a[7]; + a[6] = a02; + a[7] = a12; + + return this; + }, + + /** + * Invert this Matrix. + * + * @method Phaser.Math.Matrix3#invert + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + invert: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + var b01 = a22 * a11 - a12 * a21; + var b11 = -a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; + + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) + { + return null; + } + + det = 1 / det; + + a[0] = b01 * det; + a[1] = (-a22 * a01 + a02 * a21) * det; + a[2] = (a12 * a01 - a02 * a11) * det; + a[3] = b11 * det; + a[4] = (a22 * a00 - a02 * a20) * det; + a[5] = (-a12 * a00 + a02 * a10) * det; + a[6] = b21 * det; + a[7] = (-a21 * a00 + a01 * a20) * det; + a[8] = (a11 * a00 - a01 * a10) * det; + + return this; + }, + + /** + * Calculate the adjoint, or adjugate, of this Matrix. + * + * @method Phaser.Math.Matrix3#adjoint + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + adjoint: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + a[0] = (a11 * a22 - a12 * a21); + a[1] = (a02 * a21 - a01 * a22); + a[2] = (a01 * a12 - a02 * a11); + a[3] = (a12 * a20 - a10 * a22); + a[4] = (a00 * a22 - a02 * a20); + a[5] = (a02 * a10 - a00 * a12); + a[6] = (a10 * a21 - a11 * a20); + a[7] = (a01 * a20 - a00 * a21); + a[8] = (a00 * a11 - a01 * a10); + + return this; + }, + + /** + * Calculate the determinant of this Matrix. + * + * @method Phaser.Math.Matrix3#determinant + * @since 3.0.0 + * + * @return {number} The determinant of this Matrix. + */ + determinant: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); + }, + + /** + * Multiply this Matrix by the given Matrix. + * + * @method Phaser.Math.Matrix3#multiply + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} src - The Matrix to multiply this Matrix by. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + multiply: function (src) + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + var a20 = a[6]; + var a21 = a[7]; + var a22 = a[8]; + + var b = src.val; + + var b00 = b[0]; + var b01 = b[1]; + var b02 = b[2]; + var b10 = b[3]; + var b11 = b[4]; + var b12 = b[5]; + var b20 = b[6]; + var b21 = b[7]; + var b22 = b[8]; + + a[0] = b00 * a00 + b01 * a10 + b02 * a20; + a[1] = b00 * a01 + b01 * a11 + b02 * a21; + a[2] = b00 * a02 + b01 * a12 + b02 * a22; + + a[3] = b10 * a00 + b11 * a10 + b12 * a20; + a[4] = b10 * a01 + b11 * a11 + b12 * a21; + a[5] = b10 * a02 + b11 * a12 + b12 * a22; + + a[6] = b20 * a00 + b21 * a10 + b22 * a20; + a[7] = b20 * a01 + b21 * a11 + b22 * a21; + a[8] = b20 * a02 + b21 * a12 + b22 * a22; + + return this; + }, + + /** + * Translate this Matrix using the given Vector. + * + * @method Phaser.Math.Matrix3#translate + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to translate this Matrix with. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + translate: function (v) + { + var a = this.val; + var x = v.x; + var y = v.y; + + a[6] = x * a[0] + y * a[3] + a[6]; + a[7] = x * a[1] + y * a[4] + a[7]; + a[8] = x * a[2] + y * a[5] + a[8]; + + return this; + }, + + /** + * Apply a rotation transformation to this Matrix. + * + * @method Phaser.Math.Matrix3#rotate + * @since 3.0.0 + * + * @param {number} rad - The angle in radians to rotate by. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + rotate: function (rad) + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a10 = a[3]; + var a11 = a[4]; + var a12 = a[5]; + + var s = Math.sin(rad); + var c = Math.cos(rad); + + a[0] = c * a00 + s * a10; + a[1] = c * a01 + s * a11; + a[2] = c * a02 + s * a12; + + a[3] = c * a10 - s * a00; + a[4] = c * a11 - s * a01; + a[5] = c * a12 - s * a02; + + return this; + }, + + /** + * Apply a scale transformation to this Matrix. + * + * Uses the `x` and `y` components of the given Vector to scale the Matrix. + * + * @method Phaser.Math.Matrix3#scale + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to scale this Matrix with. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + scale: function (v) + { + var a = this.val; + var x = v.x; + var y = v.y; + + a[0] = x * a[0]; + a[1] = x * a[1]; + a[2] = x * a[2]; + + a[3] = y * a[3]; + a[4] = y * a[4]; + a[5] = y * a[5]; + + return this; + }, + + /** + * Set the values of this Matrix from the given Quaternion. + * + * @method Phaser.Math.Matrix3#fromQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to set the values of this Matrix from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + fromQuat: function (q) + { + var x = q.x; + var y = q.y; + var z = q.z; + var w = q.w; + + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + var out = this.val; + + out[0] = 1 - (yy + zz); + out[3] = xy + wz; + out[6] = xz - wy; + + out[1] = xy - wz; + out[4] = 1 - (xx + zz); + out[7] = yz + wx; + + out[2] = xz + wy; + out[5] = yz - wx; + out[8] = 1 - (xx + yy); + + return this; + }, + + /** + * Set the values of this Matrix3 to be normalized from the given Matrix4. + * + * @method Phaser.Math.Matrix3#normalFromMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} m - The Matrix4 to normalize the values from. + * + * @return {Phaser.Math.Matrix3} This Matrix3. + */ + normalFromMat4: function (m) + { + var a = m.val; + var out = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) + { + return null; + } + + det = 1 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + + return this; + } + +}); + +module.exports = Matrix3; diff --git a/src/math/Matrix4.js b/src/math/Matrix4.js index 79494eb49..51e00a809 100644 --- a/src/math/Matrix4.js +++ b/src/math/Matrix4.js @@ -1,1456 +1,1456 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji -// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl - -var Class = require('../utils/Class'); - -var EPSILON = 0.000001; - -/** - * @classdesc - * A four-dimensional matrix. - * - * @class Matrix4 - * @memberof Phaser.Math - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} [m] - Optional Matrix4 to copy values from. - */ -var Matrix4 = new Class({ - - initialize: - - function Matrix4 (m) - { - /** - * The matrix values. - * - * @name Phaser.Math.Matrix4#val - * @type {Float32Array} - * @since 3.0.0 - */ - this.val = new Float32Array(16); - - if (m) - { - // Assume Matrix4 with val: - this.copy(m); - } - else - { - // Default to identity - this.identity(); - } - }, - - /** - * Make a clone of this Matrix4. - * - * @method Phaser.Math.Matrix4#clone - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix4} A clone of this Matrix4. - */ - clone: function () - { - return new Matrix4(this); - }, - - // TODO - Should work with basic values - - /** - * This method is an alias for `Matrix4.copy`. - * - * @method Phaser.Math.Matrix4#set - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} src - The Matrix to set the values of this Matrix's from. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - set: function (src) - { - return this.copy(src); - }, - - /** - * Copy the values of a given Matrix into this Matrix. - * - * @method Phaser.Math.Matrix4#copy - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} src - The Matrix to copy the values from. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - copy: function (src) - { - var out = this.val; - var a = src.val; - - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - - return this; - }, - - /** - * Set the values of this Matrix from the given array. - * - * @method Phaser.Math.Matrix4#fromArray - * @since 3.0.0 - * - * @param {array} a - The array to copy the values from. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - fromArray: function (a) - { - var out = this.val; - - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - - return this; - }, - - /** - * Reset this Matrix. - * - * Sets all values to `0`. - * - * @method Phaser.Math.Matrix4#zero - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - zero: function () - { - var out = this.val; - - out[0] = 0; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 0; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 0; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 0; - - return this; - }, - - /** - * Set the `x`, `y` and `z` values of this Matrix. - * - * @method Phaser.Math.Matrix4#xyz - * @since 3.0.0 - * - * @param {number} x - The x value. - * @param {number} y - The y value. - * @param {number} z - The z value. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - xyz: function (x, y, z) - { - this.identity(); - - var out = this.val; - - out[12] = x; - out[13] = y; - out[14] = z; - - return this; - }, - - /** - * Set the scaling values of this Matrix. - * - * @method Phaser.Math.Matrix4#scaling - * @since 3.0.0 - * - * @param {number} x - The x scaling value. - * @param {number} y - The y scaling value. - * @param {number} z - The z scaling value. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - scaling: function (x, y, z) - { - this.zero(); - - var out = this.val; - - out[0] = x; - out[5] = y; - out[10] = z; - out[15] = 1; - - return this; - }, - - /** - * Reset this Matrix to an identity (default) matrix. - * - * @method Phaser.Math.Matrix4#identity - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - identity: function () - { - var out = this.val; - - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - - return this; - }, - - /** - * Transpose this Matrix. - * - * @method Phaser.Math.Matrix4#transpose - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - transpose: function () - { - var a = this.val; - - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - var a12 = a[6]; - var a13 = a[7]; - var a23 = a[11]; - - a[1] = a[4]; - a[2] = a[8]; - a[3] = a[12]; - a[4] = a01; - a[6] = a[9]; - a[7] = a[13]; - a[8] = a02; - a[9] = a12; - a[11] = a[14]; - a[12] = a03; - a[13] = a13; - a[14] = a23; - - return this; - }, - - /** - * Invert this Matrix. - * - * @method Phaser.Math.Matrix4#invert - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - invert: function () - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - var a30 = a[12]; - var a31 = a[13]; - var a32 = a[14]; - var a33 = a[15]; - - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) - { - return null; - } - - det = 1 / det; - - a[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - a[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - a[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - a[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - a[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - a[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - a[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - a[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - a[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - a[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - a[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - a[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - a[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - a[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - a[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - a[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - - return this; - }, - - /** - * Calculate the adjoint, or adjugate, of this Matrix. - * - * @method Phaser.Math.Matrix4#adjoint - * @since 3.0.0 - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - adjoint: function () - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - var a30 = a[12]; - var a31 = a[13]; - var a32 = a[14]; - var a33 = a[15]; - - a[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); - a[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); - a[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); - a[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); - a[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); - a[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); - a[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); - a[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); - a[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); - a[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); - a[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); - a[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); - a[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); - a[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); - a[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); - a[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); - - return this; - }, - - /** - * Calculate the determinant of this Matrix. - * - * @method Phaser.Math.Matrix4#determinant - * @since 3.0.0 - * - * @return {number} The determinant of this Matrix. - */ - determinant: function () - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - var a30 = a[12]; - var a31 = a[13]; - var a32 = a[14]; - var a33 = a[15]; - - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - }, - - /** - * Multiply this Matrix by the given Matrix. - * - * @method Phaser.Math.Matrix4#multiply - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} src - The Matrix to multiply this Matrix by. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - multiply: function (src) - { - var a = this.val; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - var a30 = a[12]; - var a31 = a[13]; - var a32 = a[14]; - var a33 = a[15]; - - var b = src.val; - - // Cache only the current line of the second matrix - var b0 = b[0]; - var b1 = b[1]; - var b2 = b[2]; - var b3 = b[3]; - - a[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - a[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - a[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - a[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = b[4]; - b1 = b[5]; - b2 = b[6]; - b3 = b[7]; - - a[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - a[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - a[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - a[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = b[8]; - b1 = b[9]; - b2 = b[10]; - b3 = b[11]; - - a[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - a[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - a[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - a[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = b[12]; - b1 = b[13]; - b2 = b[14]; - b3 = b[15]; - - a[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - a[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - a[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - a[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - return this; - }, - - /** - * Multiply the values of this Matrix4 by those given in the `src` argument. - * - * @method Phaser.Math.Matrix4#multiplyLocal - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} src - The source Matrix4 that this Matrix4 is multiplied by. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - multiplyLocal: function (src) - { - var a = []; - var m1 = this.val; - var m2 = src.val; - - a[0] = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12]; - a[1] = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13]; - a[2] = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14]; - a[3] = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15]; - - a[4] = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12]; - a[5] = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13]; - a[6] = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14]; - a[7] = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15]; - - a[8] = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12]; - a[9] = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13]; - a[10] = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14]; - a[11] = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15]; - - a[12] = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12]; - a[13] = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13]; - a[14] = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14]; - a[15] = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15]; - - return this.fromArray(a); - }, - - /** - * Translate this Matrix using the given Vector. - * - * @method Phaser.Math.Matrix4#translate - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to translate this Matrix with. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - translate: function (v) - { - var x = v.x; - var y = v.y; - var z = v.z; - var a = this.val; - - a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; - a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; - a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; - a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; - - return this; - }, - - /** - * Translate this Matrix using the given values. - * - * @method Phaser.Math.Matrix4#translateXYZ - * @since 3.16.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - translateXYZ: function (x, y, z) - { - var a = this.val; - - a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; - a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; - a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; - a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; - - return this; - }, - - /** - * Apply a scale transformation to this Matrix. - * - * Uses the `x`, `y` and `z` components of the given Vector to scale the Matrix. - * - * @method Phaser.Math.Matrix4#scale - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to scale this Matrix with. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - scale: function (v) - { - var x = v.x; - var y = v.y; - var z = v.z; - var a = this.val; - - a[0] = a[0] * x; - a[1] = a[1] * x; - a[2] = a[2] * x; - a[3] = a[3] * x; - - a[4] = a[4] * y; - a[5] = a[5] * y; - a[6] = a[6] * y; - a[7] = a[7] * y; - - a[8] = a[8] * z; - a[9] = a[9] * z; - a[10] = a[10] * z; - a[11] = a[11] * z; - - return this; - }, - - /** - * Apply a scale transformation to this Matrix. - * - * @method Phaser.Math.Matrix4#scaleXYZ - * @since 3.16.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - scaleXYZ: function (x, y, z) - { - var a = this.val; - - a[0] = a[0] * x; - a[1] = a[1] * x; - a[2] = a[2] * x; - a[3] = a[3] * x; - - a[4] = a[4] * y; - a[5] = a[5] * y; - a[6] = a[6] * y; - a[7] = a[7] * y; - - a[8] = a[8] * z; - a[9] = a[9] * z; - a[10] = a[10] * z; - a[11] = a[11] * z; - - return this; - }, - - /** - * Derive a rotation matrix around the given axis. - * - * @method Phaser.Math.Matrix4#makeRotationAxis - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} axis - The rotation axis. - * @param {number} angle - The rotation angle in radians. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - makeRotationAxis: function (axis, angle) - { - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - var c = Math.cos(angle); - var s = Math.sin(angle); - var t = 1 - c; - var x = axis.x; - var y = axis.y; - var z = axis.z; - var tx = t * x; - var ty = t * y; - - this.fromArray([ - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 - ]); - - return this; - }, - - /** - * Apply a rotation transformation to this Matrix. - * - * @method Phaser.Math.Matrix4#rotate - * @since 3.0.0 - * - * @param {number} rad - The angle in radians to rotate by. - * @param {Phaser.Math.Vector3} axis - The axis to rotate upon. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - rotate: function (rad, axis) - { - var a = this.val; - var x = axis.x; - var y = axis.y; - var z = axis.z; - var len = Math.sqrt(x * x + y * y + z * z); - - if (Math.abs(len) < EPSILON) - { - return null; - } - - len = 1 / len; - x *= len; - y *= len; - z *= len; - - var s = Math.sin(rad); - var c = Math.cos(rad); - var t = 1 - c; - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - // Construct the elements of the rotation matrix - var b00 = x * x * t + c; - var b01 = y * x * t + z * s; - var b02 = z * x * t - y * s; - - var b10 = x * y * t - z * s; - var b11 = y * y * t + c; - var b12 = z * y * t + x * s; - - var b20 = x * z * t + y * s; - var b21 = y * z * t - x * s; - var b22 = z * z * t + c; - - // Perform rotation-specific matrix multiplication - a[0] = a00 * b00 + a10 * b01 + a20 * b02; - a[1] = a01 * b00 + a11 * b01 + a21 * b02; - a[2] = a02 * b00 + a12 * b01 + a22 * b02; - a[3] = a03 * b00 + a13 * b01 + a23 * b02; - a[4] = a00 * b10 + a10 * b11 + a20 * b12; - a[5] = a01 * b10 + a11 * b11 + a21 * b12; - a[6] = a02 * b10 + a12 * b11 + a22 * b12; - a[7] = a03 * b10 + a13 * b11 + a23 * b12; - a[8] = a00 * b20 + a10 * b21 + a20 * b22; - a[9] = a01 * b20 + a11 * b21 + a21 * b22; - a[10] = a02 * b20 + a12 * b21 + a22 * b22; - a[11] = a03 * b20 + a13 * b21 + a23 * b22; - - return this; - }, - - /** - * Rotate this matrix on its X axis. - * - * @method Phaser.Math.Matrix4#rotateX - * @since 3.0.0 - * - * @param {number} rad - The angle in radians to rotate by. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - rotateX: function (rad) - { - var a = this.val; - var s = Math.sin(rad); - var c = Math.cos(rad); - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - // Perform axis-specific matrix multiplication - a[4] = a10 * c + a20 * s; - a[5] = a11 * c + a21 * s; - a[6] = a12 * c + a22 * s; - a[7] = a13 * c + a23 * s; - a[8] = a20 * c - a10 * s; - a[9] = a21 * c - a11 * s; - a[10] = a22 * c - a12 * s; - a[11] = a23 * c - a13 * s; - - return this; - }, - - /** - * Rotate this matrix on its Y axis. - * - * @method Phaser.Math.Matrix4#rotateY - * @since 3.0.0 - * - * @param {number} rad - The angle to rotate by, in radians. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - rotateY: function (rad) - { - var a = this.val; - var s = Math.sin(rad); - var c = Math.cos(rad); - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a20 = a[8]; - var a21 = a[9]; - var a22 = a[10]; - var a23 = a[11]; - - // Perform axis-specific matrix multiplication - a[0] = a00 * c - a20 * s; - a[1] = a01 * c - a21 * s; - a[2] = a02 * c - a22 * s; - a[3] = a03 * c - a23 * s; - a[8] = a00 * s + a20 * c; - a[9] = a01 * s + a21 * c; - a[10] = a02 * s + a22 * c; - a[11] = a03 * s + a23 * c; - - return this; - }, - - /** - * Rotate this matrix on its Z axis. - * - * @method Phaser.Math.Matrix4#rotateZ - * @since 3.0.0 - * - * @param {number} rad - The angle to rotate by, in radians. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - rotateZ: function (rad) - { - var a = this.val; - var s = Math.sin(rad); - var c = Math.cos(rad); - - var a00 = a[0]; - var a01 = a[1]; - var a02 = a[2]; - var a03 = a[3]; - - var a10 = a[4]; - var a11 = a[5]; - var a12 = a[6]; - var a13 = a[7]; - - // Perform axis-specific matrix multiplication - a[0] = a00 * c + a10 * s; - a[1] = a01 * c + a11 * s; - a[2] = a02 * c + a12 * s; - a[3] = a03 * c + a13 * s; - a[4] = a10 * c - a00 * s; - a[5] = a11 * c - a01 * s; - a[6] = a12 * c - a02 * s; - a[7] = a13 * c - a03 * s; - - return this; - }, - - /** - * Set the values of this Matrix from the given rotation Quaternion and translation Vector. - * - * @method Phaser.Math.Matrix4#fromRotationTranslation - * @since 3.0.0 - * - * @param {Phaser.Math.Quaternion} q - The Quaternion to set rotation from. - * @param {Phaser.Math.Vector3} v - The Vector to set translation from. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - fromRotationTranslation: function (q, v) - { - // Quaternion math - var out = this.val; - - var x = q.x; - var y = q.y; - var z = q.z; - var w = q.w; - - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - out[0] = 1 - (yy + zz); - out[1] = xy + wz; - out[2] = xz - wy; - out[3] = 0; - - out[4] = xy - wz; - out[5] = 1 - (xx + zz); - out[6] = yz + wx; - out[7] = 0; - - out[8] = xz + wy; - out[9] = yz - wx; - out[10] = 1 - (xx + yy); - out[11] = 0; - - out[12] = v.x; - out[13] = v.y; - out[14] = v.z; - out[15] = 1; - - return this; - }, - - /** - * Set the values of this Matrix from the given Quaternion. - * - * @method Phaser.Math.Matrix4#fromQuat - * @since 3.0.0 - * - * @param {Phaser.Math.Quaternion} q - The Quaternion to set the values of this Matrix from. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - fromQuat: function (q) - { - var out = this.val; - - var x = q.x; - var y = q.y; - var z = q.z; - var w = q.w; - - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - - out[0] = 1 - (yy + zz); - out[1] = xy + wz; - out[2] = xz - wy; - out[3] = 0; - - out[4] = xy - wz; - out[5] = 1 - (xx + zz); - out[6] = yz + wx; - out[7] = 0; - - out[8] = xz + wy; - out[9] = yz - wx; - out[10] = 1 - (xx + yy); - out[11] = 0; - - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - - return this; - }, - - /** - * Generate a frustum matrix with the given bounds. - * - * @method Phaser.Math.Matrix4#frustum - * @since 3.0.0 - * - * @param {number} left - The left bound of the frustum. - * @param {number} right - The right bound of the frustum. - * @param {number} bottom - The bottom bound of the frustum. - * @param {number} top - The top bound of the frustum. - * @param {number} near - The near bound of the frustum. - * @param {number} far - The far bound of the frustum. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - frustum: function (left, right, bottom, top, near, far) - { - var out = this.val; - - var rl = 1 / (right - left); - var tb = 1 / (top - bottom); - var nf = 1 / (near - far); - - out[0] = (near * 2) * rl; - out[1] = 0; - out[2] = 0; - out[3] = 0; - - out[4] = 0; - out[5] = (near * 2) * tb; - out[6] = 0; - out[7] = 0; - - out[8] = (right + left) * rl; - out[9] = (top + bottom) * tb; - out[10] = (far + near) * nf; - out[11] = -1; - - out[12] = 0; - out[13] = 0; - out[14] = (far * near * 2) * nf; - out[15] = 0; - - return this; - }, - - /** - * Generate a perspective projection matrix with the given bounds. - * - * @method Phaser.Math.Matrix4#perspective - * @since 3.0.0 - * - * @param {number} fovy - Vertical field of view in radians - * @param {number} aspect - Aspect ratio. Typically viewport width /height. - * @param {number} near - Near bound of the frustum. - * @param {number} far - Far bound of the frustum. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - perspective: function (fovy, aspect, near, far) - { - var out = this.val; - var f = 1.0 / Math.tan(fovy / 2); - var nf = 1 / (near - far); - - out[0] = f / aspect; - out[1] = 0; - out[2] = 0; - out[3] = 0; - - out[4] = 0; - out[5] = f; - out[6] = 0; - out[7] = 0; - - out[8] = 0; - out[9] = 0; - out[10] = (far + near) * nf; - out[11] = -1; - - out[12] = 0; - out[13] = 0; - out[14] = (2 * far * near) * nf; - out[15] = 0; - - return this; - }, - - /** - * Generate a perspective projection matrix with the given bounds. - * - * @method Phaser.Math.Matrix4#perspectiveLH - * @since 3.0.0 - * - * @param {number} width - The width of the frustum. - * @param {number} height - The height of the frustum. - * @param {number} near - Near bound of the frustum. - * @param {number} far - Far bound of the frustum. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - perspectiveLH: function (width, height, near, far) - { - var out = this.val; - - out[0] = (2 * near) / width; - out[1] = 0; - out[2] = 0; - out[3] = 0; - - out[4] = 0; - out[5] = (2 * near) / height; - out[6] = 0; - out[7] = 0; - - out[8] = 0; - out[9] = 0; - out[10] = -far / (near - far); - out[11] = 1; - - out[12] = 0; - out[13] = 0; - out[14] = (near * far) / (near - far); - out[15] = 0; - - return this; - }, - - /** - * Generate an orthogonal projection matrix with the given bounds. - * - * @method Phaser.Math.Matrix4#ortho - * @since 3.0.0 - * - * @param {number} left - The left bound of the frustum. - * @param {number} right - The right bound of the frustum. - * @param {number} bottom - The bottom bound of the frustum. - * @param {number} top - The top bound of the frustum. - * @param {number} near - The near bound of the frustum. - * @param {number} far - The far bound of the frustum. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - ortho: function (left, right, bottom, top, near, far) - { - var out = this.val; - var lr = left - right; - var bt = bottom - top; - var nf = near - far; - - // Avoid division by zero - lr = (lr === 0) ? lr : 1 / lr; - bt = (bt === 0) ? bt : 1 / bt; - nf = (nf === 0) ? nf : 1 / nf; - - out[0] = -2 * lr; - out[1] = 0; - out[2] = 0; - out[3] = 0; - - out[4] = 0; - out[5] = -2 * bt; - out[6] = 0; - out[7] = 0; - - out[8] = 0; - out[9] = 0; - out[10] = 2 * nf; - out[11] = 0; - - out[12] = (left + right) * lr; - out[13] = (top + bottom) * bt; - out[14] = (far + near) * nf; - out[15] = 1; - - return this; - }, - - /** - * Generate a look-at matrix with the given eye position, focal point, and up axis. - * - * @method Phaser.Math.Matrix4#lookAt - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} eye - Position of the viewer - * @param {Phaser.Math.Vector3} center - Point the viewer is looking at - * @param {Phaser.Math.Vector3} up - vec3 pointing up. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - lookAt: function (eye, center, up) - { - var out = this.val; - - var eyex = eye.x; - var eyey = eye.y; - var eyez = eye.z; - - var upx = up.x; - var upy = up.y; - var upz = up.z; - - var centerx = center.x; - var centery = center.y; - var centerz = center.z; - - if (Math.abs(eyex - centerx) < EPSILON && - Math.abs(eyey - centery) < EPSILON && - Math.abs(eyez - centerz) < EPSILON) - { - return this.identity(); - } - - var z0 = eyex - centerx; - var z1 = eyey - centery; - var z2 = eyez - centerz; - - var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); - - z0 *= len; - z1 *= len; - z2 *= len; - - var x0 = upy * z2 - upz * z1; - var x1 = upz * z0 - upx * z2; - var x2 = upx * z1 - upy * z0; - - len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); - - if (!len) - { - x0 = 0; - x1 = 0; - x2 = 0; - } - else - { - len = 1 / len; - x0 *= len; - x1 *= len; - x2 *= len; - } - - var y0 = z1 * x2 - z2 * x1; - var y1 = z2 * x0 - z0 * x2; - var y2 = z0 * x1 - z1 * x0; - - len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); - - if (!len) - { - y0 = 0; - y1 = 0; - y2 = 0; - } - else - { - len = 1 / len; - y0 *= len; - y1 *= len; - y2 *= len; - } - - out[0] = x0; - out[1] = y0; - out[2] = z0; - out[3] = 0; - - out[4] = x1; - out[5] = y1; - out[6] = z1; - out[7] = 0; - - out[8] = x2; - out[9] = y2; - out[10] = z2; - out[11] = 0; - - out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); - out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); - out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); - out[15] = 1; - - return this; - }, - - /** - * Set the values of this matrix from the given `yaw`, `pitch` and `roll` values. - * - * @method Phaser.Math.Matrix4#yawPitchRoll - * @since 3.0.0 - * - * @param {number} yaw - The yaw value. - * @param {number} pitch - The pitch value. - * @param {number} roll - The roll value. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - yawPitchRoll: function (yaw, pitch, roll) - { - this.zero(); - _tempMat1.zero(); - _tempMat2.zero(); - - var m0 = this.val; - var m1 = _tempMat1.val; - var m2 = _tempMat2.val; - - // Rotate Z - var s = Math.sin(roll); - var c = Math.cos(roll); - - m0[10] = 1; - m0[15] = 1; - m0[0] = c; - m0[1] = s; - m0[4] = -s; - m0[5] = c; - - // Rotate X - s = Math.sin(pitch); - c = Math.cos(pitch); - - m1[0] = 1; - m1[15] = 1; - m1[5] = c; - m1[10] = c; - m1[9] = -s; - m1[6] = s; - - // Rotate Y - s = Math.sin(yaw); - c = Math.cos(yaw); - - m2[5] = 1; - m2[15] = 1; - m2[0] = c; - m2[2] = -s; - m2[8] = s; - m2[10] = c; - - this.multiplyLocal(_tempMat1); - this.multiplyLocal(_tempMat2); - - return this; - }, - - /** - * Generate a world matrix from the given rotation, position, scale, view matrix and projection matrix. - * - * @method Phaser.Math.Matrix4#setWorldMatrix - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} rotation - The rotation of the world matrix. - * @param {Phaser.Math.Vector3} position - The position of the world matrix. - * @param {Phaser.Math.Vector3} scale - The scale of the world matrix. - * @param {Phaser.Math.Matrix4} [viewMatrix] - The view matrix. - * @param {Phaser.Math.Matrix4} [projectionMatrix] - The projection matrix. - * - * @return {Phaser.Math.Matrix4} This Matrix4. - */ - setWorldMatrix: function (rotation, position, scale, viewMatrix, projectionMatrix) - { - this.yawPitchRoll(rotation.y, rotation.x, rotation.z); - - _tempMat1.scaling(scale.x, scale.y, scale.z); - _tempMat2.xyz(position.x, position.y, position.z); - - this.multiplyLocal(_tempMat1); - this.multiplyLocal(_tempMat2); - - if (viewMatrix !== undefined) - { - this.multiplyLocal(viewMatrix); - } - - if (projectionMatrix !== undefined) - { - this.multiplyLocal(projectionMatrix); - } - - return this; - } - -}); - -var _tempMat1 = new Matrix4(); -var _tempMat2 = new Matrix4(); - -module.exports = Matrix4; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = require('../utils/Class'); + +var EPSILON = 0.000001; + +/** + * @classdesc + * A four-dimensional matrix. + * + * @class Matrix4 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} [m] - Optional Matrix4 to copy values from. + */ +var Matrix4 = new Class({ + + initialize: + + function Matrix4 (m) + { + /** + * The matrix values. + * + * @name Phaser.Math.Matrix4#val + * @type {Float32Array} + * @since 3.0.0 + */ + this.val = new Float32Array(16); + + if (m) + { + // Assume Matrix4 with val: + this.copy(m); + } + else + { + // Default to identity + this.identity(); + } + }, + + /** + * Make a clone of this Matrix4. + * + * @method Phaser.Math.Matrix4#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} A clone of this Matrix4. + */ + clone: function () + { + return new Matrix4(this); + }, + + // TODO - Should work with basic values + + /** + * This method is an alias for `Matrix4.copy`. + * + * @method Phaser.Math.Matrix4#set + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The Matrix to set the values of this Matrix's from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + set: function (src) + { + return this.copy(src); + }, + + /** + * Copy the values of a given Matrix into this Matrix. + * + * @method Phaser.Math.Matrix4#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The Matrix to copy the values from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + copy: function (src) + { + var out = this.val; + var a = src.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + + return this; + }, + + /** + * Set the values of this Matrix from the given array. + * + * @method Phaser.Math.Matrix4#fromArray + * @since 3.0.0 + * + * @param {array} a - The array to copy the values from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + fromArray: function (a) + { + var out = this.val; + + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + + return this; + }, + + /** + * Reset this Matrix. + * + * Sets all values to `0`. + * + * @method Phaser.Math.Matrix4#zero + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + zero: function () + { + var out = this.val; + + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 0; + + return this; + }, + + /** + * Set the `x`, `y` and `z` values of this Matrix. + * + * @method Phaser.Math.Matrix4#xyz + * @since 3.0.0 + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * @param {number} z - The z value. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + xyz: function (x, y, z) + { + this.identity(); + + var out = this.val; + + out[12] = x; + out[13] = y; + out[14] = z; + + return this; + }, + + /** + * Set the scaling values of this Matrix. + * + * @method Phaser.Math.Matrix4#scaling + * @since 3.0.0 + * + * @param {number} x - The x scaling value. + * @param {number} y - The y scaling value. + * @param {number} z - The z scaling value. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + scaling: function (x, y, z) + { + this.zero(); + + var out = this.val; + + out[0] = x; + out[5] = y; + out[10] = z; + out[15] = 1; + + return this; + }, + + /** + * Reset this Matrix to an identity (default) matrix. + * + * @method Phaser.Math.Matrix4#identity + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + identity: function () + { + var out = this.val; + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + + return this; + }, + + /** + * Transpose this Matrix. + * + * @method Phaser.Math.Matrix4#transpose + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + transpose: function () + { + var a = this.val; + + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a12 = a[6]; + var a13 = a[7]; + var a23 = a[11]; + + a[1] = a[4]; + a[2] = a[8]; + a[3] = a[12]; + a[4] = a01; + a[6] = a[9]; + a[7] = a[13]; + a[8] = a02; + a[9] = a12; + a[11] = a[14]; + a[12] = a03; + a[13] = a13; + a[14] = a23; + + return this; + }, + + /** + * Invert this Matrix. + * + * @method Phaser.Math.Matrix4#invert + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + invert: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) + { + return null; + } + + det = 1 / det; + + a[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + a[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + a[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + a[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + a[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + a[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + a[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + a[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + a[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + a[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + a[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + a[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + a[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + a[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + a[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + a[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return this; + }, + + /** + * Calculate the adjoint, or adjugate, of this Matrix. + * + * @method Phaser.Math.Matrix4#adjoint + * @since 3.0.0 + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + adjoint: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + a[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); + a[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + a[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); + a[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + a[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + a[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); + a[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + a[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); + a[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); + a[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + a[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); + a[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + a[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + a[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); + a[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + a[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); + + return this; + }, + + /** + * Calculate the determinant of this Matrix. + * + * @method Phaser.Math.Matrix4#determinant + * @since 3.0.0 + * + * @return {number} The determinant of this Matrix. + */ + determinant: function () + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + }, + + /** + * Multiply this Matrix by the given Matrix. + * + * @method Phaser.Math.Matrix4#multiply + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The Matrix to multiply this Matrix by. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + multiply: function (src) + { + var a = this.val; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + var a30 = a[12]; + var a31 = a[13]; + var a32 = a[14]; + var a33 = a[15]; + + var b = src.val; + + // Cache only the current line of the second matrix + var b0 = b[0]; + var b1 = b[1]; + var b2 = b[2]; + var b3 = b[3]; + + a[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + + a[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + + a[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + + a[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + a[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + a[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + a[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + return this; + }, + + /** + * Multiply the values of this Matrix4 by those given in the `src` argument. + * + * @method Phaser.Math.Matrix4#multiplyLocal + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} src - The source Matrix4 that this Matrix4 is multiplied by. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + multiplyLocal: function (src) + { + var a = []; + var m1 = this.val; + var m2 = src.val; + + a[0] = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12]; + a[1] = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13]; + a[2] = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14]; + a[3] = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15]; + + a[4] = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12]; + a[5] = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13]; + a[6] = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14]; + a[7] = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15]; + + a[8] = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12]; + a[9] = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13]; + a[10] = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14]; + a[11] = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15]; + + a[12] = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12]; + a[13] = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13]; + a[14] = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14]; + a[15] = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15]; + + return this.fromArray(a); + }, + + /** + * Translate this Matrix using the given Vector. + * + * @method Phaser.Math.Matrix4#translate + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to translate this Matrix with. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + translate: function (v) + { + var x = v.x; + var y = v.y; + var z = v.z; + var a = this.val; + + a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + + return this; + }, + + /** + * Translate this Matrix using the given values. + * + * @method Phaser.Math.Matrix4#translateXYZ + * @since 3.16.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + translateXYZ: function (x, y, z) + { + var a = this.val; + + a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + + return this; + }, + + /** + * Apply a scale transformation to this Matrix. + * + * Uses the `x`, `y` and `z` components of the given Vector to scale the Matrix. + * + * @method Phaser.Math.Matrix4#scale + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to scale this Matrix with. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + scale: function (v) + { + var x = v.x; + var y = v.y; + var z = v.z; + var a = this.val; + + a[0] = a[0] * x; + a[1] = a[1] * x; + a[2] = a[2] * x; + a[3] = a[3] * x; + + a[4] = a[4] * y; + a[5] = a[5] * y; + a[6] = a[6] * y; + a[7] = a[7] * y; + + a[8] = a[8] * z; + a[9] = a[9] * z; + a[10] = a[10] * z; + a[11] = a[11] * z; + + return this; + }, + + /** + * Apply a scale transformation to this Matrix. + * + * @method Phaser.Math.Matrix4#scaleXYZ + * @since 3.16.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + scaleXYZ: function (x, y, z) + { + var a = this.val; + + a[0] = a[0] * x; + a[1] = a[1] * x; + a[2] = a[2] * x; + a[3] = a[3] * x; + + a[4] = a[4] * y; + a[5] = a[5] * y; + a[6] = a[6] * y; + a[7] = a[7] * y; + + a[8] = a[8] * z; + a[9] = a[9] * z; + a[10] = a[10] * z; + a[11] = a[11] * z; + + return this; + }, + + /** + * Derive a rotation matrix around the given axis. + * + * @method Phaser.Math.Matrix4#makeRotationAxis + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector3|Phaser.Math.Vector4)} axis - The rotation axis. + * @param {number} angle - The rotation angle in radians. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + makeRotationAxis: function (axis, angle) + { + // Based on http://www.gamedev.net/reference/articles/article1199.asp + + var c = Math.cos(angle); + var s = Math.sin(angle); + var t = 1 - c; + var x = axis.x; + var y = axis.y; + var z = axis.z; + var tx = t * x; + var ty = t * y; + + this.fromArray([ + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 + ]); + + return this; + }, + + /** + * Apply a rotation transformation to this Matrix. + * + * @method Phaser.Math.Matrix4#rotate + * @since 3.0.0 + * + * @param {number} rad - The angle in radians to rotate by. + * @param {Phaser.Math.Vector3} axis - The axis to rotate upon. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotate: function (rad, axis) + { + var a = this.val; + var x = axis.x; + var y = axis.y; + var z = axis.z; + var len = Math.sqrt(x * x + y * y + z * z); + + if (Math.abs(len) < EPSILON) + { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + + var s = Math.sin(rad); + var c = Math.cos(rad); + var t = 1 - c; + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + // Construct the elements of the rotation matrix + var b00 = x * x * t + c; + var b01 = y * x * t + z * s; + var b02 = z * x * t - y * s; + + var b10 = x * y * t - z * s; + var b11 = y * y * t + c; + var b12 = z * y * t + x * s; + + var b20 = x * z * t + y * s; + var b21 = y * z * t - x * s; + var b22 = z * z * t + c; + + // Perform rotation-specific matrix multiplication + a[0] = a00 * b00 + a10 * b01 + a20 * b02; + a[1] = a01 * b00 + a11 * b01 + a21 * b02; + a[2] = a02 * b00 + a12 * b01 + a22 * b02; + a[3] = a03 * b00 + a13 * b01 + a23 * b02; + a[4] = a00 * b10 + a10 * b11 + a20 * b12; + a[5] = a01 * b10 + a11 * b11 + a21 * b12; + a[6] = a02 * b10 + a12 * b11 + a22 * b12; + a[7] = a03 * b10 + a13 * b11 + a23 * b12; + a[8] = a00 * b20 + a10 * b21 + a20 * b22; + a[9] = a01 * b20 + a11 * b21 + a21 * b22; + a[10] = a02 * b20 + a12 * b21 + a22 * b22; + a[11] = a03 * b20 + a13 * b21 + a23 * b22; + + return this; + }, + + /** + * Rotate this matrix on its X axis. + * + * @method Phaser.Math.Matrix4#rotateX + * @since 3.0.0 + * + * @param {number} rad - The angle in radians to rotate by. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotateX: function (rad) + { + var a = this.val; + var s = Math.sin(rad); + var c = Math.cos(rad); + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + // Perform axis-specific matrix multiplication + a[4] = a10 * c + a20 * s; + a[5] = a11 * c + a21 * s; + a[6] = a12 * c + a22 * s; + a[7] = a13 * c + a23 * s; + a[8] = a20 * c - a10 * s; + a[9] = a21 * c - a11 * s; + a[10] = a22 * c - a12 * s; + a[11] = a23 * c - a13 * s; + + return this; + }, + + /** + * Rotate this matrix on its Y axis. + * + * @method Phaser.Math.Matrix4#rotateY + * @since 3.0.0 + * + * @param {number} rad - The angle to rotate by, in radians. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotateY: function (rad) + { + var a = this.val; + var s = Math.sin(rad); + var c = Math.cos(rad); + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + // Perform axis-specific matrix multiplication + a[0] = a00 * c - a20 * s; + a[1] = a01 * c - a21 * s; + a[2] = a02 * c - a22 * s; + a[3] = a03 * c - a23 * s; + a[8] = a00 * s + a20 * c; + a[9] = a01 * s + a21 * c; + a[10] = a02 * s + a22 * c; + a[11] = a03 * s + a23 * c; + + return this; + }, + + /** + * Rotate this matrix on its Z axis. + * + * @method Phaser.Math.Matrix4#rotateZ + * @since 3.0.0 + * + * @param {number} rad - The angle to rotate by, in radians. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + rotateZ: function (rad) + { + var a = this.val; + var s = Math.sin(rad); + var c = Math.cos(rad); + + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + // Perform axis-specific matrix multiplication + a[0] = a00 * c + a10 * s; + a[1] = a01 * c + a11 * s; + a[2] = a02 * c + a12 * s; + a[3] = a03 * c + a13 * s; + a[4] = a10 * c - a00 * s; + a[5] = a11 * c - a01 * s; + a[6] = a12 * c - a02 * s; + a[7] = a13 * c - a03 * s; + + return this; + }, + + /** + * Set the values of this Matrix from the given rotation Quaternion and translation Vector. + * + * @method Phaser.Math.Matrix4#fromRotationTranslation + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to set rotation from. + * @param {Phaser.Math.Vector3} v - The Vector to set translation from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + fromRotationTranslation: function (q, v) + { + // Quaternion math + var out = this.val; + + var x = q.x; + var y = q.y; + var z = q.z; + var w = q.w; + + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + + out[12] = v.x; + out[13] = v.y; + out[14] = v.z; + out[15] = 1; + + return this; + }, + + /** + * Set the values of this Matrix from the given Quaternion. + * + * @method Phaser.Math.Matrix4#fromQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to set the values of this Matrix from. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + fromQuat: function (q) + { + var out = this.val; + + var x = q.x; + var y = q.y; + var z = q.z; + var w = q.w; + + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + + return this; + }, + + /** + * Generate a frustum matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#frustum + * @since 3.0.0 + * + * @param {number} left - The left bound of the frustum. + * @param {number} right - The right bound of the frustum. + * @param {number} bottom - The bottom bound of the frustum. + * @param {number} top - The top bound of the frustum. + * @param {number} near - The near bound of the frustum. + * @param {number} far - The far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + frustum: function (left, right, bottom, top, near, far) + { + var out = this.val; + + var rl = 1 / (right - left); + var tb = 1 / (top - bottom); + var nf = 1 / (near - far); + + out[0] = (near * 2) * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = (near * 2) * tb; + out[6] = 0; + out[7] = 0; + + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + + out[12] = 0; + out[13] = 0; + out[14] = (far * near * 2) * nf; + out[15] = 0; + + return this; + }, + + /** + * Generate a perspective projection matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#perspective + * @since 3.0.0 + * + * @param {number} fovy - Vertical field of view in radians + * @param {number} aspect - Aspect ratio. Typically viewport width /height. + * @param {number} near - Near bound of the frustum. + * @param {number} far - Far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + perspective: function (fovy, aspect, near, far) + { + var out = this.val; + var f = 1.0 / Math.tan(fovy / 2); + var nf = 1 / (near - far); + + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + + out[12] = 0; + out[13] = 0; + out[14] = (2 * far * near) * nf; + out[15] = 0; + + return this; + }, + + /** + * Generate a perspective projection matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#perspectiveLH + * @since 3.0.0 + * + * @param {number} width - The width of the frustum. + * @param {number} height - The height of the frustum. + * @param {number} near - Near bound of the frustum. + * @param {number} far - Far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + perspectiveLH: function (width, height, near, far) + { + var out = this.val; + + out[0] = (2 * near) / width; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = (2 * near) / height; + out[6] = 0; + out[7] = 0; + + out[8] = 0; + out[9] = 0; + out[10] = -far / (near - far); + out[11] = 1; + + out[12] = 0; + out[13] = 0; + out[14] = (near * far) / (near - far); + out[15] = 0; + + return this; + }, + + /** + * Generate an orthogonal projection matrix with the given bounds. + * + * @method Phaser.Math.Matrix4#ortho + * @since 3.0.0 + * + * @param {number} left - The left bound of the frustum. + * @param {number} right - The right bound of the frustum. + * @param {number} bottom - The bottom bound of the frustum. + * @param {number} top - The top bound of the frustum. + * @param {number} near - The near bound of the frustum. + * @param {number} far - The far bound of the frustum. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + ortho: function (left, right, bottom, top, near, far) + { + var out = this.val; + var lr = left - right; + var bt = bottom - top; + var nf = near - far; + + // Avoid division by zero + lr = (lr === 0) ? lr : 1 / lr; + bt = (bt === 0) ? bt : 1 / bt; + nf = (nf === 0) ? nf : 1 / nf; + + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + + return this; + }, + + /** + * Generate a look-at matrix with the given eye position, focal point, and up axis. + * + * @method Phaser.Math.Matrix4#lookAt + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} eye - Position of the viewer + * @param {Phaser.Math.Vector3} center - Point the viewer is looking at + * @param {Phaser.Math.Vector3} up - vec3 pointing up. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + lookAt: function (eye, center, up) + { + var out = this.val; + + var eyex = eye.x; + var eyey = eye.y; + var eyez = eye.z; + + var upx = up.x; + var upy = up.y; + var upz = up.z; + + var centerx = center.x; + var centery = center.y; + var centerz = center.z; + + if (Math.abs(eyex - centerx) < EPSILON && + Math.abs(eyey - centery) < EPSILON && + Math.abs(eyez - centerz) < EPSILON) + { + return this.identity(); + } + + var z0 = eyex - centerx; + var z1 = eyey - centery; + var z2 = eyez - centerz; + + var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + + z0 *= len; + z1 *= len; + z2 *= len; + + var x0 = upy * z2 - upz * z1; + var x1 = upz * z0 - upx * z2; + var x2 = upx * z1 - upy * z0; + + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + + if (!len) + { + x0 = 0; + x1 = 0; + x2 = 0; + } + else + { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + var y0 = z1 * x2 - z2 * x1; + var y1 = z2 * x0 - z0 * x2; + var y2 = z0 * x1 - z1 * x0; + + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + + if (!len) + { + y0 = 0; + y1 = 0; + y2 = 0; + } + else + { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + + return this; + }, + + /** + * Set the values of this matrix from the given `yaw`, `pitch` and `roll` values. + * + * @method Phaser.Math.Matrix4#yawPitchRoll + * @since 3.0.0 + * + * @param {number} yaw - The yaw value. + * @param {number} pitch - The pitch value. + * @param {number} roll - The roll value. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + yawPitchRoll: function (yaw, pitch, roll) + { + this.zero(); + _tempMat1.zero(); + _tempMat2.zero(); + + var m0 = this.val; + var m1 = _tempMat1.val; + var m2 = _tempMat2.val; + + // Rotate Z + var s = Math.sin(roll); + var c = Math.cos(roll); + + m0[10] = 1; + m0[15] = 1; + m0[0] = c; + m0[1] = s; + m0[4] = -s; + m0[5] = c; + + // Rotate X + s = Math.sin(pitch); + c = Math.cos(pitch); + + m1[0] = 1; + m1[15] = 1; + m1[5] = c; + m1[10] = c; + m1[9] = -s; + m1[6] = s; + + // Rotate Y + s = Math.sin(yaw); + c = Math.cos(yaw); + + m2[5] = 1; + m2[15] = 1; + m2[0] = c; + m2[2] = -s; + m2[8] = s; + m2[10] = c; + + this.multiplyLocal(_tempMat1); + this.multiplyLocal(_tempMat2); + + return this; + }, + + /** + * Generate a world matrix from the given rotation, position, scale, view matrix and projection matrix. + * + * @method Phaser.Math.Matrix4#setWorldMatrix + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} rotation - The rotation of the world matrix. + * @param {Phaser.Math.Vector3} position - The position of the world matrix. + * @param {Phaser.Math.Vector3} scale - The scale of the world matrix. + * @param {Phaser.Math.Matrix4} [viewMatrix] - The view matrix. + * @param {Phaser.Math.Matrix4} [projectionMatrix] - The projection matrix. + * + * @return {Phaser.Math.Matrix4} This Matrix4. + */ + setWorldMatrix: function (rotation, position, scale, viewMatrix, projectionMatrix) + { + this.yawPitchRoll(rotation.y, rotation.x, rotation.z); + + _tempMat1.scaling(scale.x, scale.y, scale.z); + _tempMat2.xyz(position.x, position.y, position.z); + + this.multiplyLocal(_tempMat1); + this.multiplyLocal(_tempMat2); + + if (viewMatrix !== undefined) + { + this.multiplyLocal(viewMatrix); + } + + if (projectionMatrix !== undefined) + { + this.multiplyLocal(projectionMatrix); + } + + return this; + } + +}); + +var _tempMat1 = new Matrix4(); +var _tempMat2 = new Matrix4(); + +module.exports = Matrix4; diff --git a/src/math/MaxAdd.js b/src/math/MaxAdd.js index 512d43d60..e4b20474d 100644 --- a/src/math/MaxAdd.js +++ b/src/math/MaxAdd.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Add an `amount` to a `value`, limiting the maximum result to `max`. - * - * @function Phaser.Math.MaxAdd - * @since 3.0.0 - * - * @param {number} value - The value to add to. - * @param {number} amount - The amount to add. - * @param {number} max - The maximum value to return. - * - * @return {number} The resulting value. - */ -var MaxAdd = function (value, amount, max) -{ - return Math.min(value + amount, max); -}; - -module.exports = MaxAdd; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Add an `amount` to a `value`, limiting the maximum result to `max`. + * + * @function Phaser.Math.MaxAdd + * @since 3.0.0 + * + * @param {number} value - The value to add to. + * @param {number} amount - The amount to add. + * @param {number} max - The maximum value to return. + * + * @return {number} The resulting value. + */ +var MaxAdd = function (value, amount, max) +{ + return Math.min(value + amount, max); +}; + +module.exports = MaxAdd; diff --git a/src/math/MinSub.js b/src/math/MinSub.js index 5eb3bbf64..b6dada3ee 100644 --- a/src/math/MinSub.js +++ b/src/math/MinSub.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Subtract an `amount` from `value`, limiting the minimum result to `min`. - * - * @function Phaser.Math.MinSub - * @since 3.0.0 - * - * @param {number} value - The value to subtract from. - * @param {number} amount - The amount to subtract. - * @param {number} min - The minimum value to return. - * - * @return {number} The resulting value. - */ -var MinSub = function (value, amount, min) -{ - return Math.max(value - amount, min); -}; - -module.exports = MinSub; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Subtract an `amount` from `value`, limiting the minimum result to `min`. + * + * @function Phaser.Math.MinSub + * @since 3.0.0 + * + * @param {number} value - The value to subtract from. + * @param {number} amount - The amount to subtract. + * @param {number} min - The minimum value to return. + * + * @return {number} The resulting value. + */ +var MinSub = function (value, amount, min) +{ + return Math.max(value - amount, min); +}; + +module.exports = MinSub; diff --git a/src/math/Percent.js b/src/math/Percent.js index 94296e289..406a54f51 100644 --- a/src/math/Percent.js +++ b/src/math/Percent.js @@ -1,53 +1,53 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Work out what percentage `value` is of the range between `min` and `max`. - * If `max` isn't given then it will return the percentage of `value` to `min`. - * - * You can optionally specify an `upperMax` value, which is a mid-way point in the range that represents 100%, after which the % starts to go down to zero again. - * - * @function Phaser.Math.Percent - * @since 3.0.0 - * - * @param {number} value - The value to determine the percentage of. - * @param {number} min - The minimum value. - * @param {number} [max] - The maximum value. - * @param {number} [upperMax] - The mid-way point in the range that represents 100%. - * - * @return {number} A value between 0 and 1 representing the percentage. - */ -var Percent = function (value, min, max, upperMax) -{ - if (max === undefined) { max = min + 1; } - - var percentage = (value - min) / (max - min); - - if (percentage > 1) - { - if (upperMax !== undefined) - { - percentage = ((upperMax - value)) / (upperMax - max); - - if (percentage < 0) - { - percentage = 0; - } - } - else - { - percentage = 1; - } - } - else if (percentage < 0) - { - percentage = 0; - } - - return percentage; -}; - -module.exports = Percent; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Work out what percentage `value` is of the range between `min` and `max`. + * If `max` isn't given then it will return the percentage of `value` to `min`. + * + * You can optionally specify an `upperMax` value, which is a mid-way point in the range that represents 100%, after which the % starts to go down to zero again. + * + * @function Phaser.Math.Percent + * @since 3.0.0 + * + * @param {number} value - The value to determine the percentage of. + * @param {number} min - The minimum value. + * @param {number} [max] - The maximum value. + * @param {number} [upperMax] - The mid-way point in the range that represents 100%. + * + * @return {number} A value between 0 and 1 representing the percentage. + */ +var Percent = function (value, min, max, upperMax) +{ + if (max === undefined) { max = min + 1; } + + var percentage = (value - min) / (max - min); + + if (percentage > 1) + { + if (upperMax !== undefined) + { + percentage = ((upperMax - value)) / (upperMax - max); + + if (percentage < 0) + { + percentage = 0; + } + } + else + { + percentage = 1; + } + } + else if (percentage < 0) + { + percentage = 0; + } + + return percentage; +}; + +module.exports = Percent; diff --git a/src/math/Quaternion.js b/src/math/Quaternion.js index c1d33199e..66162c540 100644 --- a/src/math/Quaternion.js +++ b/src/math/Quaternion.js @@ -1,766 +1,766 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji -// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl - -var Class = require('../utils/Class'); -var Vector3 = require('./Vector3'); -var Matrix3 = require('./Matrix3'); - -var EPSILON = 0.000001; - -// Some shared 'private' arrays -var siNext = new Int8Array([ 1, 2, 0 ]); -var tmp = new Float32Array([ 0, 0, 0 ]); - -var xUnitVec3 = new Vector3(1, 0, 0); -var yUnitVec3 = new Vector3(0, 1, 0); - -var tmpvec = new Vector3(); -var tmpMat3 = new Matrix3(); - -/** - * @classdesc - * A quaternion. - * - * @class Quaternion - * @memberof Phaser.Math - * @constructor - * @since 3.0.0 - * - * @param {number} [x] - The x component. - * @param {number} [y] - The y component. - * @param {number} [z] - The z component. - * @param {number} [w] - The w component. - */ -var Quaternion = new Class({ - - initialize: - - function Quaternion (x, y, z, w) - { - /** - * The x component of this Quaternion. - * - * @name Phaser.Math.Quaternion#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - - /** - * The y component of this Quaternion. - * - * @name Phaser.Math.Quaternion#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - - /** - * The z component of this Quaternion. - * - * @name Phaser.Math.Quaternion#z - * @type {number} - * @default 0 - * @since 3.0.0 - */ - - /** - * The w component of this Quaternion. - * - * @name Phaser.Math.Quaternion#w - * @type {number} - * @default 0 - * @since 3.0.0 - */ - - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - this.z = x.z || 0; - this.w = x.w || 0; - } - else - { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = w || 0; - } - }, - - /** - * Copy the components of a given Quaternion or Vector into this Quaternion. - * - * @method Phaser.Math.Quaternion#copy - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} src - The Quaternion or Vector to copy the components from. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - copy: function (src) - { - this.x = src.x; - this.y = src.y; - this.z = src.z; - this.w = src.w; - - return this; - }, - - /** - * Set the components of this Quaternion. - * - * @method Phaser.Math.Quaternion#set - * @since 3.0.0 - * - * @param {(number|object)} [x=0] - The x component, or an object containing x, y, z, and w components. - * @param {number} [y=0] - The y component. - * @param {number} [z=0] - The z component. - * @param {number} [w=0] - The w component. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - set: function (x, y, z, w) - { - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - this.z = x.z || 0; - this.w = x.w || 0; - } - else - { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = w || 0; - } - - return this; - }, - - /** - * Add a given Quaternion or Vector to this Quaternion. Addition is component-wise. - * - * @method Phaser.Math.Quaternion#add - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to add to this Quaternion. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - add: function (v) - { - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; - - return this; - }, - - /** - * Subtract a given Quaternion or Vector from this Quaternion. Subtraction is component-wise. - * - * @method Phaser.Math.Quaternion#subtract - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to subtract from this Quaternion. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - subtract: function (v) - { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; - - return this; - }, - - /** - * Scale this Quaternion by the given value. - * - * @method Phaser.Math.Quaternion#scale - * @since 3.0.0 - * - * @param {number} scale - The value to scale this Quaternion by. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - scale: function (scale) - { - this.x *= scale; - this.y *= scale; - this.z *= scale; - this.w *= scale; - - return this; - }, - - /** - * Calculate the length of this Quaternion. - * - * @method Phaser.Math.Quaternion#length - * @since 3.0.0 - * - * @return {number} The length of this Quaternion. - */ - length: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - - return Math.sqrt(x * x + y * y + z * z + w * w); - }, - - /** - * Calculate the length of this Quaternion squared. - * - * @method Phaser.Math.Quaternion#lengthSq - * @since 3.0.0 - * - * @return {number} The length of this Quaternion, squared. - */ - lengthSq: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - - return x * x + y * y + z * z + w * w; - }, - - /** - * Normalize this Quaternion. - * - * @method Phaser.Math.Quaternion#normalize - * @since 3.0.0 - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - normalize: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - var len = x * x + y * y + z * z + w * w; - - if (len > 0) - { - len = 1 / Math.sqrt(len); - - this.x = x * len; - this.y = y * len; - this.z = z * len; - this.w = w * len; - } - - return this; - }, - - /** - * Calculate the dot product of this Quaternion and the given Quaternion or Vector. - * - * @method Phaser.Math.Quaternion#dot - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to dot product with this Quaternion. - * - * @return {number} The dot product of this Quaternion and the given Quaternion or Vector. - */ - dot: function (v) - { - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - }, - - /** - * Linearly interpolate this Quaternion towards the given Quaternion or Vector. - * - * @method Phaser.Math.Quaternion#lerp - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to interpolate towards. - * @param {number} [t=0] - The percentage of interpolation. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - lerp: function (v, t) - { - if (t === undefined) { t = 0; } - - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - this.x = ax + t * (v.x - ax); - this.y = ay + t * (v.y - ay); - this.z = az + t * (v.z - az); - this.w = aw + t * (v.w - aw); - - return this; - }, - - /** - * Rotates this Quaternion based on the two given vectors. - * - * @method Phaser.Math.Quaternion#rotationTo - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} a - The transform rotation vector. - * @param {Phaser.Math.Vector3} b - The target rotation vector. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - rotationTo: function (a, b) - { - var dot = a.x * b.x + a.y * b.y + a.z * b.z; - - if (dot < -0.999999) - { - if (tmpvec.copy(xUnitVec3).cross(a).length() < EPSILON) - { - tmpvec.copy(yUnitVec3).cross(a); - } - - tmpvec.normalize(); - - return this.setAxisAngle(tmpvec, Math.PI); - - } - else if (dot > 0.999999) - { - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 1; - - return this; - } - else - { - tmpvec.copy(a).cross(b); - - this.x = tmpvec.x; - this.y = tmpvec.y; - this.z = tmpvec.z; - this.w = 1 + dot; - - return this.normalize(); - } - }, - - /** - * Set the axes of this Quaternion. - * - * @method Phaser.Math.Quaternion#setAxes - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} view - The view axis. - * @param {Phaser.Math.Vector3} right - The right axis. - * @param {Phaser.Math.Vector3} up - The upwards axis. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - setAxes: function (view, right, up) - { - var m = tmpMat3.val; - - m[0] = right.x; - m[3] = right.y; - m[6] = right.z; - - m[1] = up.x; - m[4] = up.y; - m[7] = up.z; - - m[2] = -view.x; - m[5] = -view.y; - m[8] = -view.z; - - return this.fromMat3(tmpMat3).normalize(); - }, - - /** - * Reset this Matrix to an identity (default) Quaternion. - * - * @method Phaser.Math.Quaternion#identity - * @since 3.0.0 - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - identity: function () - { - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 1; - - return this; - }, - - /** - * Set the axis angle of this Quaternion. - * - * @method Phaser.Math.Quaternion#setAxisAngle - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} axis - The axis. - * @param {number} rad - The angle in radians. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - setAxisAngle: function (axis, rad) - { - rad = rad * 0.5; - - var s = Math.sin(rad); - - this.x = s * axis.x; - this.y = s * axis.y; - this.z = s * axis.z; - this.w = Math.cos(rad); - - return this; - }, - - /** - * Multiply this Quaternion by the given Quaternion or Vector. - * - * @method Phaser.Math.Quaternion#multiply - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} b - The Quaternion or Vector to multiply this Quaternion by. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - multiply: function (b) - { - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - var bx = b.x; - var by = b.y; - var bz = b.z; - var bw = b.w; - - this.x = ax * bw + aw * bx + ay * bz - az * by; - this.y = ay * bw + aw * by + az * bx - ax * bz; - this.z = az * bw + aw * bz + ax * by - ay * bx; - this.w = aw * bw - ax * bx - ay * by - az * bz; - - return this; - }, - - /** - * Smoothly linearly interpolate this Quaternion towards the given Quaternion or Vector. - * - * @method Phaser.Math.Quaternion#slerp - * @since 3.0.0 - * - * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} b - The Quaternion or Vector to interpolate towards. - * @param {number} t - The percentage of interpolation. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - slerp: function (b, t) - { - // benchmarks: http://jsperf.com/quaternion-slerp-implementations - - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - var bx = b.x; - var by = b.y; - var bz = b.z; - var bw = b.w; - - // calc cosine - var cosom = ax * bx + ay * by + az * bz + aw * bw; - - // adjust signs (if necessary) - if (cosom < 0) - { - cosom = -cosom; - bx = - bx; - by = - by; - bz = - bz; - bw = - bw; - } - - // "from" and "to" quaternions are very close - // ... so we can do a linear interpolation - var scale0 = 1 - t; - var scale1 = t; - - // calculate coefficients - if ((1 - cosom) > EPSILON) - { - // standard case (slerp) - var omega = Math.acos(cosom); - var sinom = Math.sin(omega); - - scale0 = Math.sin((1.0 - t) * omega) / sinom; - scale1 = Math.sin(t * omega) / sinom; - } - - // calculate final values - this.x = scale0 * ax + scale1 * bx; - this.y = scale0 * ay + scale1 * by; - this.z = scale0 * az + scale1 * bz; - this.w = scale0 * aw + scale1 * bw; - - return this; - }, - - /** - * Invert this Quaternion. - * - * @method Phaser.Math.Quaternion#invert - * @since 3.0.0 - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - invert: function () - { - var a0 = this.x; - var a1 = this.y; - var a2 = this.z; - var a3 = this.w; - - var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; - var invDot = (dot) ? 1 / dot : 0; - - // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 - - this.x = -a0 * invDot; - this.y = -a1 * invDot; - this.z = -a2 * invDot; - this.w = a3 * invDot; - - return this; - }, - - /** - * Convert this Quaternion into its conjugate. - * - * Sets the x, y and z components. - * - * @method Phaser.Math.Quaternion#conjugate - * @since 3.0.0 - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - conjugate: function () - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - - return this; - }, - - /** - * Rotate this Quaternion on the X axis. - * - * @method Phaser.Math.Quaternion#rotateX - * @since 3.0.0 - * - * @param {number} rad - The rotation angle in radians. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - rotateX: function (rad) - { - rad *= 0.5; - - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - var bx = Math.sin(rad); - var bw = Math.cos(rad); - - this.x = ax * bw + aw * bx; - this.y = ay * bw + az * bx; - this.z = az * bw - ay * bx; - this.w = aw * bw - ax * bx; - - return this; - }, - - /** - * Rotate this Quaternion on the Y axis. - * - * @method Phaser.Math.Quaternion#rotateY - * @since 3.0.0 - * - * @param {number} rad - The rotation angle in radians. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - rotateY: function (rad) - { - rad *= 0.5; - - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - var by = Math.sin(rad); - var bw = Math.cos(rad); - - this.x = ax * bw - az * by; - this.y = ay * bw + aw * by; - this.z = az * bw + ax * by; - this.w = aw * bw - ay * by; - - return this; - }, - - /** - * Rotate this Quaternion on the Z axis. - * - * @method Phaser.Math.Quaternion#rotateZ - * @since 3.0.0 - * - * @param {number} rad - The rotation angle in radians. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - rotateZ: function (rad) - { - rad *= 0.5; - - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - var bz = Math.sin(rad); - var bw = Math.cos(rad); - - this.x = ax * bw + ay * bz; - this.y = ay * bw - ax * bz; - this.z = az * bw + aw * bz; - this.w = aw * bw - az * bz; - - return this; - }, - - /** - * Create a unit (or rotation) Quaternion from its x, y, and z components. - * - * Sets the w component. - * - * @method Phaser.Math.Quaternion#calculateW - * @since 3.0.0 - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - calculateW: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - - this.w = -Math.sqrt(1.0 - x * x - y * y - z * z); - - return this; - }, - - /** - * Convert the given Matrix into this Quaternion. - * - * @method Phaser.Math.Quaternion#fromMat3 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} mat - The Matrix to convert from. - * - * @return {Phaser.Math.Quaternion} This Quaternion. - */ - fromMat3: function (mat) - { - // 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". - var m = mat.val; - var fTrace = m[0] + m[4] + m[8]; - var fRoot; - - if (fTrace > 0) - { - // |w| > 1/2, may as well choose w > 1/2 - fRoot = Math.sqrt(fTrace + 1.0); // 2w - - this.w = 0.5 * fRoot; - - fRoot = 0.5 / fRoot; // 1/(4w) - - this.x = (m[7] - m[5]) * fRoot; - this.y = (m[2] - m[6]) * fRoot; - this.z = (m[3] - m[1]) * fRoot; - } - else - { - // |w| <= 1/2 - var i = 0; - - if (m[4] > m[0]) - { - i = 1; - } - - if (m[8] > m[i * 3 + i]) - { - i = 2; - } - - var j = siNext[i]; - var k = siNext[j]; - - // This isn't quite as clean without array access - fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1); - tmp[i] = 0.5 * fRoot; - - fRoot = 0.5 / fRoot; - - tmp[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; - tmp[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; - - this.x = tmp[0]; - this.y = tmp[1]; - this.z = tmp[2]; - this.w = (m[k * 3 + j] - m[j * 3 + k]) * fRoot; - } - - return this; - } - -}); - -module.exports = Quaternion; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = require('../utils/Class'); +var Vector3 = require('./Vector3'); +var Matrix3 = require('./Matrix3'); + +var EPSILON = 0.000001; + +// Some shared 'private' arrays +var siNext = new Int8Array([ 1, 2, 0 ]); +var tmp = new Float32Array([ 0, 0, 0 ]); + +var xUnitVec3 = new Vector3(1, 0, 0); +var yUnitVec3 = new Vector3(0, 1, 0); + +var tmpvec = new Vector3(); +var tmpMat3 = new Matrix3(); + +/** + * @classdesc + * A quaternion. + * + * @class Quaternion + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - The x component. + * @param {number} [y] - The y component. + * @param {number} [z] - The z component. + * @param {number} [w] - The w component. + */ +var Quaternion = new Class({ + + initialize: + + function Quaternion (x, y, z, w) + { + /** + * The x component of this Quaternion. + * + * @name Phaser.Math.Quaternion#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + /** + * The y component of this Quaternion. + * + * @name Phaser.Math.Quaternion#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + /** + * The z component of this Quaternion. + * + * @name Phaser.Math.Quaternion#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + /** + * The w component of this Quaternion. + * + * @name Phaser.Math.Quaternion#w + * @type {number} + * @default 0 + * @since 3.0.0 + */ + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + }, + + /** + * Copy the components of a given Quaternion or Vector into this Quaternion. + * + * @method Phaser.Math.Quaternion#copy + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} src - The Quaternion or Vector to copy the components from. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + copy: function (src) + { + this.x = src.x; + this.y = src.y; + this.z = src.z; + this.w = src.w; + + return this; + }, + + /** + * Set the components of this Quaternion. + * + * @method Phaser.Math.Quaternion#set + * @since 3.0.0 + * + * @param {(number|object)} [x=0] - The x component, or an object containing x, y, z, and w components. + * @param {number} [y=0] - The y component. + * @param {number} [z=0] - The z component. + * @param {number} [w=0] - The w component. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + set: function (x, y, z, w) + { + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + + return this; + }, + + /** + * Add a given Quaternion or Vector to this Quaternion. Addition is component-wise. + * + * @method Phaser.Math.Quaternion#add + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to add to this Quaternion. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + add: function (v) + { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + + return this; + }, + + /** + * Subtract a given Quaternion or Vector from this Quaternion. Subtraction is component-wise. + * + * @method Phaser.Math.Quaternion#subtract + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to subtract from this Quaternion. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + subtract: function (v) + { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + + return this; + }, + + /** + * Scale this Quaternion by the given value. + * + * @method Phaser.Math.Quaternion#scale + * @since 3.0.0 + * + * @param {number} scale - The value to scale this Quaternion by. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + scale: function (scale) + { + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + + return this; + }, + + /** + * Calculate the length of this Quaternion. + * + * @method Phaser.Math.Quaternion#length + * @since 3.0.0 + * + * @return {number} The length of this Quaternion. + */ + length: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return Math.sqrt(x * x + y * y + z * z + w * w); + }, + + /** + * Calculate the length of this Quaternion squared. + * + * @method Phaser.Math.Quaternion#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Quaternion, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return x * x + y * y + z * z + w * w; + }, + + /** + * Normalize this Quaternion. + * + * @method Phaser.Math.Quaternion#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + this.z = z * len; + this.w = w * len; + } + + return this; + }, + + /** + * Calculate the dot product of this Quaternion and the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#dot + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to dot product with this Quaternion. + * + * @return {number} The dot product of this Quaternion and the given Quaternion or Vector. + */ + dot: function (v) + { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + }, + + /** + * Linearly interpolate this Quaternion towards the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#lerp + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} v - The Quaternion or Vector to interpolate towards. + * @param {number} [t=0] - The percentage of interpolation. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + lerp: function (v, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + this.x = ax + t * (v.x - ax); + this.y = ay + t * (v.y - ay); + this.z = az + t * (v.z - az); + this.w = aw + t * (v.w - aw); + + return this; + }, + + /** + * Rotates this Quaternion based on the two given vectors. + * + * @method Phaser.Math.Quaternion#rotationTo + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} a - The transform rotation vector. + * @param {Phaser.Math.Vector3} b - The target rotation vector. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotationTo: function (a, b) + { + var dot = a.x * b.x + a.y * b.y + a.z * b.z; + + if (dot < -0.999999) + { + if (tmpvec.copy(xUnitVec3).cross(a).length() < EPSILON) + { + tmpvec.copy(yUnitVec3).cross(a); + } + + tmpvec.normalize(); + + return this.setAxisAngle(tmpvec, Math.PI); + + } + else if (dot > 0.999999) + { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 1; + + return this; + } + else + { + tmpvec.copy(a).cross(b); + + this.x = tmpvec.x; + this.y = tmpvec.y; + this.z = tmpvec.z; + this.w = 1 + dot; + + return this.normalize(); + } + }, + + /** + * Set the axes of this Quaternion. + * + * @method Phaser.Math.Quaternion#setAxes + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} view - The view axis. + * @param {Phaser.Math.Vector3} right - The right axis. + * @param {Phaser.Math.Vector3} up - The upwards axis. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + setAxes: function (view, right, up) + { + var m = tmpMat3.val; + + m[0] = right.x; + m[3] = right.y; + m[6] = right.z; + + m[1] = up.x; + m[4] = up.y; + m[7] = up.z; + + m[2] = -view.x; + m[5] = -view.y; + m[8] = -view.z; + + return this.fromMat3(tmpMat3).normalize(); + }, + + /** + * Reset this Matrix to an identity (default) Quaternion. + * + * @method Phaser.Math.Quaternion#identity + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + identity: function () + { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 1; + + return this; + }, + + /** + * Set the axis angle of this Quaternion. + * + * @method Phaser.Math.Quaternion#setAxisAngle + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} axis - The axis. + * @param {number} rad - The angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + setAxisAngle: function (axis, rad) + { + rad = rad * 0.5; + + var s = Math.sin(rad); + + this.x = s * axis.x; + this.y = s * axis.y; + this.z = s * axis.z; + this.w = Math.cos(rad); + + return this; + }, + + /** + * Multiply this Quaternion by the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#multiply + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} b - The Quaternion or Vector to multiply this Quaternion by. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + multiply: function (b) + { + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bx = b.x; + var by = b.y; + var bz = b.z; + var bw = b.w; + + this.x = ax * bw + aw * bx + ay * bz - az * by; + this.y = ay * bw + aw * by + az * bx - ax * bz; + this.z = az * bw + aw * bz + ax * by - ay * bx; + this.w = aw * bw - ax * bx - ay * by - az * bz; + + return this; + }, + + /** + * Smoothly linearly interpolate this Quaternion towards the given Quaternion or Vector. + * + * @method Phaser.Math.Quaternion#slerp + * @since 3.0.0 + * + * @param {(Phaser.Math.Quaternion|Phaser.Math.Vector4)} b - The Quaternion or Vector to interpolate towards. + * @param {number} t - The percentage of interpolation. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + slerp: function (b, t) + { + // benchmarks: http://jsperf.com/quaternion-slerp-implementations + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bx = b.x; + var by = b.y; + var bz = b.z; + var bw = b.w; + + // calc cosine + var cosom = ax * bx + ay * by + az * bz + aw * bw; + + // adjust signs (if necessary) + if (cosom < 0) + { + cosom = -cosom; + bx = - bx; + by = - by; + bz = - bz; + bw = - bw; + } + + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + var scale0 = 1 - t; + var scale1 = t; + + // calculate coefficients + if ((1 - cosom) > EPSILON) + { + // standard case (slerp) + var omega = Math.acos(cosom); + var sinom = Math.sin(omega); + + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } + + // calculate final values + this.x = scale0 * ax + scale1 * bx; + this.y = scale0 * ay + scale1 * by; + this.z = scale0 * az + scale1 * bz; + this.w = scale0 * aw + scale1 * bw; + + return this; + }, + + /** + * Invert this Quaternion. + * + * @method Phaser.Math.Quaternion#invert + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + invert: function () + { + var a0 = this.x; + var a1 = this.y; + var a2 = this.z; + var a3 = this.w; + + var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; + var invDot = (dot) ? 1 / dot : 0; + + // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + this.x = -a0 * invDot; + this.y = -a1 * invDot; + this.z = -a2 * invDot; + this.w = a3 * invDot; + + return this; + }, + + /** + * Convert this Quaternion into its conjugate. + * + * Sets the x, y and z components. + * + * @method Phaser.Math.Quaternion#conjugate + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + conjugate: function () + { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + + return this; + }, + + /** + * Rotate this Quaternion on the X axis. + * + * @method Phaser.Math.Quaternion#rotateX + * @since 3.0.0 + * + * @param {number} rad - The rotation angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotateX: function (rad) + { + rad *= 0.5; + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bx = Math.sin(rad); + var bw = Math.cos(rad); + + this.x = ax * bw + aw * bx; + this.y = ay * bw + az * bx; + this.z = az * bw - ay * bx; + this.w = aw * bw - ax * bx; + + return this; + }, + + /** + * Rotate this Quaternion on the Y axis. + * + * @method Phaser.Math.Quaternion#rotateY + * @since 3.0.0 + * + * @param {number} rad - The rotation angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotateY: function (rad) + { + rad *= 0.5; + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var by = Math.sin(rad); + var bw = Math.cos(rad); + + this.x = ax * bw - az * by; + this.y = ay * bw + aw * by; + this.z = az * bw + ax * by; + this.w = aw * bw - ay * by; + + return this; + }, + + /** + * Rotate this Quaternion on the Z axis. + * + * @method Phaser.Math.Quaternion#rotateZ + * @since 3.0.0 + * + * @param {number} rad - The rotation angle in radians. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + rotateZ: function (rad) + { + rad *= 0.5; + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + var bz = Math.sin(rad); + var bw = Math.cos(rad); + + this.x = ax * bw + ay * bz; + this.y = ay * bw - ax * bz; + this.z = az * bw + aw * bz; + this.w = aw * bw - az * bz; + + return this; + }, + + /** + * Create a unit (or rotation) Quaternion from its x, y, and z components. + * + * Sets the w component. + * + * @method Phaser.Math.Quaternion#calculateW + * @since 3.0.0 + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + calculateW: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + + this.w = -Math.sqrt(1.0 - x * x - y * y - z * z); + + return this; + }, + + /** + * Convert the given Matrix into this Quaternion. + * + * @method Phaser.Math.Quaternion#fromMat3 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} mat - The Matrix to convert from. + * + * @return {Phaser.Math.Quaternion} This Quaternion. + */ + fromMat3: function (mat) + { + // 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". + var m = mat.val; + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if (fTrace > 0) + { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + + this.w = 0.5 * fRoot; + + fRoot = 0.5 / fRoot; // 1/(4w) + + this.x = (m[7] - m[5]) * fRoot; + this.y = (m[2] - m[6]) * fRoot; + this.z = (m[3] - m[1]) * fRoot; + } + else + { + // |w| <= 1/2 + var i = 0; + + if (m[4] > m[0]) + { + i = 1; + } + + if (m[8] > m[i * 3 + i]) + { + i = 2; + } + + var j = siNext[i]; + var k = siNext[j]; + + // This isn't quite as clean without array access + fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1); + tmp[i] = 0.5 * fRoot; + + fRoot = 0.5 / fRoot; + + tmp[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; + tmp[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; + + this.x = tmp[0]; + this.y = tmp[1]; + this.z = tmp[2]; + this.w = (m[k * 3 + j] - m[j * 3 + k]) * fRoot; + } + + return this; + } + +}); + +module.exports = Quaternion; diff --git a/src/math/RadToDeg.js b/src/math/RadToDeg.js index 18674cd0b..456b0ffb1 100644 --- a/src/math/RadToDeg.js +++ b/src/math/RadToDeg.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); - -/** - * Convert the given angle in radians, to the equivalent angle in degrees. - * - * @function Phaser.Math.RadToDeg - * @since 3.0.0 - * - * @param {number} radians - The angle in radians to convert ot degrees. - * - * @return {integer} The given angle converted to degrees. - */ -var RadToDeg = function (radians) -{ - return radians * CONST.RAD_TO_DEG; -}; - -module.exports = RadToDeg; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); + +/** + * Convert the given angle in radians, to the equivalent angle in degrees. + * + * @function Phaser.Math.RadToDeg + * @since 3.0.0 + * + * @param {number} radians - The angle in radians to convert ot degrees. + * + * @return {integer} The given angle converted to degrees. + */ +var RadToDeg = function (radians) +{ + return radians * CONST.RAD_TO_DEG; +}; + +module.exports = RadToDeg; diff --git a/src/math/RandomXY.js b/src/math/RandomXY.js index 7b9d0c12f..7acee253e 100644 --- a/src/math/RandomXY.js +++ b/src/math/RandomXY.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compute a random unit vector. - * - * Computes random values for the given vector between -1 and 1 that can be used to represent a direction. - * - * Optionally accepts a scale value to scale the resulting vector by. - * - * @function Phaser.Math.RandomXY - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} vector - The Vector to compute random values for. - * @param {number} [scale=1] - The scale of the random values. - * - * @return {Phaser.Math.Vector2} The given Vector. - */ -var RandomXY = function (vector, scale) -{ - if (scale === undefined) { scale = 1; } - - var r = Math.random() * 2 * Math.PI; - - vector.x = Math.cos(r) * scale; - vector.y = Math.sin(r) * scale; - - return vector; -}; - -module.exports = RandomXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random unit vector. + * + * Computes random values for the given vector between -1 and 1 that can be used to represent a direction. + * + * Optionally accepts a scale value to scale the resulting vector by. + * + * @function Phaser.Math.RandomXY + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} vector - The Vector to compute random values for. + * @param {number} [scale=1] - The scale of the random values. + * + * @return {Phaser.Math.Vector2} The given Vector. + */ +var RandomXY = function (vector, scale) +{ + if (scale === undefined) { scale = 1; } + + var r = Math.random() * 2 * Math.PI; + + vector.x = Math.cos(r) * scale; + vector.y = Math.sin(r) * scale; + + return vector; +}; + +module.exports = RandomXY; diff --git a/src/math/RandomXYZ.js b/src/math/RandomXYZ.js index 1f28ab787..6e661e0de 100644 --- a/src/math/RandomXYZ.js +++ b/src/math/RandomXYZ.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compute a random position vector in a spherical area, optionally defined by the given radius. - * - * @function Phaser.Math.RandomXYZ - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} vec3 - The Vector to compute random values for. - * @param {number} [radius=1] - The radius. - * - * @return {Phaser.Math.Vector3} The given Vector. - */ -var RandomXYZ = function (vec3, radius) -{ - if (radius === undefined) { radius = 1; } - - var r = Math.random() * 2 * Math.PI; - var z = (Math.random() * 2) - 1; - var zScale = Math.sqrt(1 - z * z) * radius; - - vec3.x = Math.cos(r) * zScale; - vec3.y = Math.sin(r) * zScale; - vec3.z = z * radius; - - return vec3; -}; - -module.exports = RandomXYZ; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random position vector in a spherical area, optionally defined by the given radius. + * + * @function Phaser.Math.RandomXYZ + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} vec3 - The Vector to compute random values for. + * @param {number} [radius=1] - The radius. + * + * @return {Phaser.Math.Vector3} The given Vector. + */ +var RandomXYZ = function (vec3, radius) +{ + if (radius === undefined) { radius = 1; } + + var r = Math.random() * 2 * Math.PI; + var z = (Math.random() * 2) - 1; + var zScale = Math.sqrt(1 - z * z) * radius; + + vec3.x = Math.cos(r) * zScale; + vec3.y = Math.sin(r) * zScale; + vec3.z = z * radius; + + return vec3; +}; + +module.exports = RandomXYZ; diff --git a/src/math/RandomXYZW.js b/src/math/RandomXYZW.js index 4a59fe19b..d884706fc 100644 --- a/src/math/RandomXYZW.js +++ b/src/math/RandomXYZW.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Compute a random four-dimensional vector. - * - * @function Phaser.Math.RandomXYZW - * @since 3.0.0 - * - * @param {Phaser.Math.Vector4} vec4 - The Vector to compute random values for. - * @param {number} [scale=1] - The scale of the random values. - * - * @return {Phaser.Math.Vector4} The given Vector. - */ -var RandomXYZW = function (vec4, scale) -{ - if (scale === undefined) { scale = 1; } - - // TODO: Not spherical; should fix this for more uniform distribution - vec4.x = (Math.random() * 2 - 1) * scale; - vec4.y = (Math.random() * 2 - 1) * scale; - vec4.z = (Math.random() * 2 - 1) * scale; - vec4.w = (Math.random() * 2 - 1) * scale; - - return vec4; -}; - -module.exports = RandomXYZW; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Compute a random four-dimensional vector. + * + * @function Phaser.Math.RandomXYZW + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} vec4 - The Vector to compute random values for. + * @param {number} [scale=1] - The scale of the random values. + * + * @return {Phaser.Math.Vector4} The given Vector. + */ +var RandomXYZW = function (vec4, scale) +{ + if (scale === undefined) { scale = 1; } + + // TODO: Not spherical; should fix this for more uniform distribution + vec4.x = (Math.random() * 2 - 1) * scale; + vec4.y = (Math.random() * 2 - 1) * scale; + vec4.z = (Math.random() * 2 - 1) * scale; + vec4.w = (Math.random() * 2 - 1) * scale; + + return vec4; +}; + +module.exports = RandomXYZW; diff --git a/src/math/Rotate.js b/src/math/Rotate.js index 09876dd16..19c5752d7 100644 --- a/src/math/Rotate.js +++ b/src/math/Rotate.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rotate a given point by a given angle around the origin (0, 0), in an anti-clockwise direction. - * - * @function Phaser.Math.Rotate - * @since 3.0.0 - * - * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. - * @param {number} angle - The angle to be rotated by in an anticlockwise direction. - * - * @return {Phaser.Geom.Point} The given point, rotated by the given angle in an anticlockwise direction. - */ -var Rotate = function (point, angle) -{ - var x = point.x; - var y = point.y; - - point.x = (x * Math.cos(angle)) - (y * Math.sin(angle)); - point.y = (x * Math.sin(angle)) + (y * Math.cos(angle)); - - return point; -}; - -module.exports = Rotate; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a given point by a given angle around the origin (0, 0), in an anti-clockwise direction. + * + * @function Phaser.Math.Rotate + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. + * @param {number} angle - The angle to be rotated by in an anticlockwise direction. + * + * @return {Phaser.Geom.Point} The given point, rotated by the given angle in an anticlockwise direction. + */ +var Rotate = function (point, angle) +{ + var x = point.x; + var y = point.y; + + point.x = (x * Math.cos(angle)) - (y * Math.sin(angle)); + point.y = (x * Math.sin(angle)) + (y * Math.cos(angle)); + + return point; +}; + +module.exports = Rotate; diff --git a/src/math/RotateAround.js b/src/math/RotateAround.js index 7874d5608..202486910 100644 --- a/src/math/RotateAround.js +++ b/src/math/RotateAround.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rotate a `point` around `x` and `y` by the given `angle`. - * - * @function Phaser.Math.RotateAround - * @since 3.0.0 - * - * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. - * @param {number} x - The horizontal coordinate to rotate around. - * @param {number} y - The vertical coordinate to rotate around. - * @param {number} angle - The angle of rotation in radians. - * - * @return {Phaser.Geom.Point} The given point, rotated by the given angle around the given coordinates. - */ -var RotateAround = function (point, x, y, angle) -{ - var c = Math.cos(angle); - var s = Math.sin(angle); - - var tx = point.x - x; - var ty = point.y - y; - - point.x = tx * c - ty * s + x; - point.y = tx * s + ty * c + y; - - return point; -}; - -module.exports = RotateAround; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a `point` around `x` and `y` by the given `angle`. + * + * @function Phaser.Math.RotateAround + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. + * @param {number} x - The horizontal coordinate to rotate around. + * @param {number} y - The vertical coordinate to rotate around. + * @param {number} angle - The angle of rotation in radians. + * + * @return {Phaser.Geom.Point} The given point, rotated by the given angle around the given coordinates. + */ +var RotateAround = function (point, x, y, angle) +{ + var c = Math.cos(angle); + var s = Math.sin(angle); + + var tx = point.x - x; + var ty = point.y - y; + + point.x = tx * c - ty * s + x; + point.y = tx * s + ty * c + y; + + return point; +}; + +module.exports = RotateAround; diff --git a/src/math/RotateAroundDistance.js b/src/math/RotateAroundDistance.js index 81fc2266b..38482127a 100644 --- a/src/math/RotateAroundDistance.js +++ b/src/math/RotateAroundDistance.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Rotate a `point` around `x` and `y` by the given `angle` and `distance`. - * - * @function Phaser.Math.RotateAroundDistance - * @since 3.0.0 - * - * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. - * @param {number} x - The horizontal coordinate to rotate around. - * @param {number} y - The vertical coordinate to rotate around. - * @param {number} angle - The angle of rotation in radians. - * @param {number} distance - The distance from (x, y) to place the point at. - * - * @return {Phaser.Geom.Point} The given point. - */ -var RotateAroundDistance = function (point, x, y, angle, distance) -{ - var t = angle + Math.atan2(point.y - y, point.x - x); - - point.x = x + (distance * Math.cos(t)); - point.y = y + (distance * Math.sin(t)); - - return point; -}; - -module.exports = RotateAroundDistance; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Rotate a `point` around `x` and `y` by the given `angle` and `distance`. + * + * @function Phaser.Math.RotateAroundDistance + * @since 3.0.0 + * + * @param {(Phaser.Geom.Point|object)} point - The point to be rotated. + * @param {number} x - The horizontal coordinate to rotate around. + * @param {number} y - The vertical coordinate to rotate around. + * @param {number} angle - The angle of rotation in radians. + * @param {number} distance - The distance from (x, y) to place the point at. + * + * @return {Phaser.Geom.Point} The given point. + */ +var RotateAroundDistance = function (point, x, y, angle, distance) +{ + var t = angle + Math.atan2(point.y - y, point.x - x); + + point.x = x + (distance * Math.cos(t)); + point.y = y + (distance * Math.sin(t)); + + return point; +}; + +module.exports = RotateAroundDistance; diff --git a/src/math/RotateVec3.js b/src/math/RotateVec3.js index bcc4005d3..53176b977 100644 --- a/src/math/RotateVec3.js +++ b/src/math/RotateVec3.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Vector3 = require('../math/Vector3'); -var Matrix4 = require('../math/Matrix4'); -var Quaternion = require('../math/Quaternion'); - -var tmpMat4 = new Matrix4(); -var tmpQuat = new Quaternion(); -var tmpVec3 = new Vector3(); - -/** - * Rotates a vector in place by axis angle. - * - * This is the same as transforming a point by an - * axis-angle quaternion, but it has higher precision. - * - * @function Phaser.Math.RotateVec3 - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} vec - The vector to be rotated. - * @param {Phaser.Math.Vector3} axis - The axis to rotate around. - * @param {number} radians - The angle of rotation in radians. - * - * @return {Phaser.Math.Vector3} The given vector. - */ -var RotateVec3 = function (vec, axis, radians) -{ - // Set the quaternion to our axis angle - tmpQuat.setAxisAngle(axis, radians); - - // Create a rotation matrix from the axis angle - tmpMat4.fromRotationTranslation(tmpQuat, tmpVec3.set(0, 0, 0)); - - // Multiply our vector by the rotation matrix - return vec.transformMat4(tmpMat4); -}; - -module.exports = RotateVec3; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector3 = require('../math/Vector3'); +var Matrix4 = require('../math/Matrix4'); +var Quaternion = require('../math/Quaternion'); + +var tmpMat4 = new Matrix4(); +var tmpQuat = new Quaternion(); +var tmpVec3 = new Vector3(); + +/** + * Rotates a vector in place by axis angle. + * + * This is the same as transforming a point by an + * axis-angle quaternion, but it has higher precision. + * + * @function Phaser.Math.RotateVec3 + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} vec - The vector to be rotated. + * @param {Phaser.Math.Vector3} axis - The axis to rotate around. + * @param {number} radians - The angle of rotation in radians. + * + * @return {Phaser.Math.Vector3} The given vector. + */ +var RotateVec3 = function (vec, axis, radians) +{ + // Set the quaternion to our axis angle + tmpQuat.setAxisAngle(axis, radians); + + // Create a rotation matrix from the axis angle + tmpMat4.fromRotationTranslation(tmpQuat, tmpVec3.set(0, 0, 0)); + + // Multiply our vector by the rotation matrix + return vec.transformMat4(tmpMat4); +}; + +module.exports = RotateVec3; diff --git a/src/math/RoundAwayFromZero.js b/src/math/RoundAwayFromZero.js index ab67ccf0b..d37c85dd1 100644 --- a/src/math/RoundAwayFromZero.js +++ b/src/math/RoundAwayFromZero.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Round a given number so it is further away from zero. That is, positive numbers are rounded up, and negative numbers are rounded down. - * - * @function Phaser.Math.RoundAwayFromZero - * @since 3.0.0 - * - * @param {number} value - The number to round. - * - * @return {number} The rounded number, rounded away from zero. - */ -var RoundAwayFromZero = function (value) -{ - // "Opposite" of truncate. - return (value > 0) ? Math.ceil(value) : Math.floor(value); -}; - -module.exports = RoundAwayFromZero; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Round a given number so it is further away from zero. That is, positive numbers are rounded up, and negative numbers are rounded down. + * + * @function Phaser.Math.RoundAwayFromZero + * @since 3.0.0 + * + * @param {number} value - The number to round. + * + * @return {number} The rounded number, rounded away from zero. + */ +var RoundAwayFromZero = function (value) +{ + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); +}; + +module.exports = RoundAwayFromZero; diff --git a/src/math/RoundTo.js b/src/math/RoundTo.js index eff8f4a2f..551792d60 100644 --- a/src/math/RoundTo.js +++ b/src/math/RoundTo.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Round a value to the given precision. - * - * For example: - * - * ```javascript - * RoundTo(123.456, 0) = 123 - * RoundTo(123.456, 1) = 120 - * RoundTo(123.456, 2) = 100 - * ``` - * - * To round the decimal, i.e. to round to precision, pass in a negative `place`: - * - * ```javascript - * RoundTo(123.456789, 0) = 123 - * RoundTo(123.456789, -1) = 123.5 - * RoundTo(123.456789, -2) = 123.46 - * RoundTo(123.456789, -3) = 123.457 - * ``` - * - * @function Phaser.Math.RoundTo - * @since 3.0.0 - * - * @param {number} value - The value to round. - * @param {integer} [place=0] - The place to round to. Positive to round the units, negative to round the decimal. - * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. - * - * @return {number} The rounded value. - */ -var RoundTo = function (value, place, base) -{ - if (place === undefined) { place = 0; } - if (base === undefined) { base = 10; } - - var p = Math.pow(base, -place); - - return Math.round(value * p) / p; -}; - -module.exports = RoundTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Round a value to the given precision. + * + * For example: + * + * ```javascript + * RoundTo(123.456, 0) = 123 + * RoundTo(123.456, 1) = 120 + * RoundTo(123.456, 2) = 100 + * ``` + * + * To round the decimal, i.e. to round to precision, pass in a negative `place`: + * + * ```javascript + * RoundTo(123.456789, 0) = 123 + * RoundTo(123.456789, -1) = 123.5 + * RoundTo(123.456789, -2) = 123.46 + * RoundTo(123.456789, -3) = 123.457 + * ``` + * + * @function Phaser.Math.RoundTo + * @since 3.0.0 + * + * @param {number} value - The value to round. + * @param {integer} [place=0] - The place to round to. Positive to round the units, negative to round the decimal. + * @param {integer} [base=10] - The base to round in. Default is 10 for decimal. + * + * @return {number} The rounded value. + */ +var RoundTo = function (value, place, base) +{ + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; +}; + +module.exports = RoundTo; diff --git a/src/math/SinCosTableGenerator.js b/src/math/SinCosTableGenerator.js index 319c0c72d..d6bceab3b 100644 --- a/src/math/SinCosTableGenerator.js +++ b/src/math/SinCosTableGenerator.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Generate a series of sine and cosine values. - * - * @function Phaser.Math.SinCosTableGenerator - * @since 3.0.0 - * - * @param {number} length - The number of values to generate. - * @param {number} [sinAmp=1] - The sine value amplitude. - * @param {number} [cosAmp=1] - The cosine value amplitude. - * @param {number} [frequency=1] - The frequency of the values. - * - * @return {Phaser.Types.Math.SinCosTable} The generated values. - */ -var SinCosTableGenerator = function (length, sinAmp, cosAmp, frequency) -{ - if (sinAmp === undefined) { sinAmp = 1; } - if (cosAmp === undefined) { cosAmp = 1; } - if (frequency === undefined) { frequency = 1; } - - frequency *= Math.PI / length; - - var cos = []; - var sin = []; - - for (var c = 0; c < length; c++) - { - cosAmp -= sinAmp * frequency; - sinAmp += cosAmp * frequency; - - cos[c] = cosAmp; - sin[c] = sinAmp; - } - - return { - sin: sin, - cos: cos, - length: length - }; -}; - -module.exports = SinCosTableGenerator; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Generate a series of sine and cosine values. + * + * @function Phaser.Math.SinCosTableGenerator + * @since 3.0.0 + * + * @param {number} length - The number of values to generate. + * @param {number} [sinAmp=1] - The sine value amplitude. + * @param {number} [cosAmp=1] - The cosine value amplitude. + * @param {number} [frequency=1] - The frequency of the values. + * + * @return {Phaser.Types.Math.SinCosTable} The generated values. + */ +var SinCosTableGenerator = function (length, sinAmp, cosAmp, frequency) +{ + if (sinAmp === undefined) { sinAmp = 1; } + if (cosAmp === undefined) { cosAmp = 1; } + if (frequency === undefined) { frequency = 1; } + + frequency *= Math.PI / length; + + var cos = []; + var sin = []; + + for (var c = 0; c < length; c++) + { + cosAmp -= sinAmp * frequency; + sinAmp += cosAmp * frequency; + + cos[c] = cosAmp; + sin[c] = sinAmp; + } + + return { + sin: sin, + cos: cos, + length: length + }; +}; + +module.exports = SinCosTableGenerator; diff --git a/src/math/SmoothStep.js b/src/math/SmoothStep.js index 666982fa9..9b1cd4418 100644 --- a/src/math/SmoothStep.js +++ b/src/math/SmoothStep.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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. - */ -var SmoothStep = function (x, min, max) -{ - if (x <= min) - { - return 0; - } - - if (x >= max) - { - return 1; - } - - x = (x - min) / (max - min); - - return x * x * (3 - 2 * x); -}; - -module.exports = SmoothStep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var SmoothStep = function (x, min, max) +{ + if (x <= min) + { + return 0; + } + + if (x >= max) + { + return 1; + } + + x = (x - min) / (max - min); + + return x * x * (3 - 2 * x); +}; + +module.exports = SmoothStep; diff --git a/src/math/SmootherStep.js b/src/math/SmootherStep.js index 5a642eb5f..21a742946 100644 --- a/src/math/SmootherStep.js +++ b/src/math/SmootherStep.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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. - */ -var SmootherStep = function (x, min, max) -{ - x = Math.max(0, Math.min(1, (x - min) / (max - min))); - - return x * x * x * (x * (x * 6 - 15) + 10); -}; - -module.exports = SmootherStep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. + */ +var SmootherStep = function (x, min, max) +{ + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); +}; + +module.exports = SmootherStep; diff --git a/src/math/ToXY.js b/src/math/ToXY.js index be5a67cca..a628e0ce0 100644 --- a/src/math/ToXY.js +++ b/src/math/ToXY.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Vector2 = require('./Vector2'); - -/** - * Returns a Vector2 containing the x and y position of the given index in a `width` x `height` sized grid. - * - * For example, in a 6 x 4 grid, index 16 would equal x: 4 y: 2. - * - * If the given index is out of range an empty Vector2 is returned. - * - * @function Phaser.Math.ToXY - * @since 3.19.0 - * - * @param {integer} index - The position within the grid to get the x/y value for. - * @param {integer} width - The width of the grid. - * @param {integer} height - The height of the grid. - * @param {Phaser.Math.Vector2} [out] - An optional Vector2 to store the result in. If not given, a new Vector2 instance will be created. - * - * @return {Phaser.Math.Vector2} A Vector2 where the x and y properties contain the given grid index. - */ -var ToXY = function (index, width, height, out) -{ - if (out === undefined) { out = new Vector2(); } - - var x = 0; - var y = 0; - var total = width * height; - - if (index > 0 && index <= total) - { - if (index > width - 1) - { - y = Math.floor(index / width); - x = index - (y * width); - } - else - { - x = index; - } - - out.set(x, y); - } - - return out; -}; - -module.exports = ToXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = require('./Vector2'); + +/** + * Returns a Vector2 containing the x and y position of the given index in a `width` x `height` sized grid. + * + * For example, in a 6 x 4 grid, index 16 would equal x: 4 y: 2. + * + * If the given index is out of range an empty Vector2 is returned. + * + * @function Phaser.Math.ToXY + * @since 3.19.0 + * + * @param {integer} index - The position within the grid to get the x/y value for. + * @param {integer} width - The width of the grid. + * @param {integer} height - The height of the grid. + * @param {Phaser.Math.Vector2} [out] - An optional Vector2 to store the result in. If not given, a new Vector2 instance will be created. + * + * @return {Phaser.Math.Vector2} A Vector2 where the x and y properties contain the given grid index. + */ +var ToXY = function (index, width, height, out) +{ + if (out === undefined) { out = new Vector2(); } + + var x = 0; + var y = 0; + var total = width * height; + + if (index > 0 && index <= total) + { + if (index > width - 1) + { + y = Math.floor(index / width); + x = index - (y * width); + } + else + { + x = index; + } + + out.set(x, y); + } + + return out; +}; + +module.exports = ToXY; diff --git a/src/math/TransformXY.js b/src/math/TransformXY.js index bfe7ea7f1..8a81b2877 100644 --- a/src/math/TransformXY.js +++ b/src/math/TransformXY.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Vector2 = require('./Vector2'); - -/** - * Takes the `x` and `y` coordinates and transforms them into the same space as - * defined by the position, rotation and scale values. - * - * @function Phaser.Math.TransformXY - * @since 3.0.0 - * - * @param {number} x - The x coordinate to be transformed. - * @param {number} y - The y coordinate to be transformed. - * @param {number} positionX - Horizontal position of the transform point. - * @param {number} positionY - Vertical position of the transform point. - * @param {number} rotation - Rotation of the transform point, in radians. - * @param {number} scaleX - Horizontal scale of the transform point. - * @param {number} scaleY - Vertical scale of the transform point. - * @param {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} [output] - The output vector, point or object for the translated coordinates. - * - * @return {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} The translated point. - */ -var TransformXY = function (x, y, positionX, positionY, rotation, scaleX, scaleY, output) -{ - if (output === undefined) { output = new Vector2(); } - - var radianSin = Math.sin(rotation); - var radianCos = Math.cos(rotation); - - // Rotate and Scale - var a = radianCos * scaleX; - var b = radianSin * scaleX; - var c = -radianSin * scaleY; - var d = radianCos * scaleY; - - // Invert - var id = 1 / ((a * d) + (c * -b)); - - output.x = (d * id * x) + (-c * id * y) + (((positionY * c) - (positionX * d)) * id); - output.y = (a * id * y) + (-b * id * x) + (((-positionY * a) + (positionX * b)) * id); - - return output; -}; - -module.exports = TransformXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Vector2 = require('./Vector2'); + +/** + * Takes the `x` and `y` coordinates and transforms them into the same space as + * defined by the position, rotation and scale values. + * + * @function Phaser.Math.TransformXY + * @since 3.0.0 + * + * @param {number} x - The x coordinate to be transformed. + * @param {number} y - The y coordinate to be transformed. + * @param {number} positionX - Horizontal position of the transform point. + * @param {number} positionY - Vertical position of the transform point. + * @param {number} rotation - Rotation of the transform point, in radians. + * @param {number} scaleX - Horizontal scale of the transform point. + * @param {number} scaleY - Vertical scale of the transform point. + * @param {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} [output] - The output vector, point or object for the translated coordinates. + * + * @return {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} The translated point. + */ +var TransformXY = function (x, y, positionX, positionY, rotation, scaleX, scaleY, output) +{ + if (output === undefined) { output = new Vector2(); } + + var radianSin = Math.sin(rotation); + var radianCos = Math.cos(rotation); + + // Rotate and Scale + var a = radianCos * scaleX; + var b = radianSin * scaleX; + var c = -radianSin * scaleY; + var d = radianCos * scaleY; + + // Invert + var id = 1 / ((a * d) + (c * -b)); + + output.x = (d * id * x) + (-c * id * y) + (((positionY * c) - (positionX * d)) * id); + output.y = (a * id * y) + (-b * id * x) + (((-positionY * a) + (positionX * b)) * id); + + return output; +}; + +module.exports = TransformXY; diff --git a/src/math/Vector2.js b/src/math/Vector2.js index d254fa151..3d92e4fd4 100644 --- a/src/math/Vector2.js +++ b/src/math/Vector2.js @@ -1,633 +1,633 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji -// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A representation of a vector in 2D space. - * - * A two-component vector. - * - * @class Vector2 - * @memberof Phaser.Math - * @constructor - * @since 3.0.0 - * - * @param {number|Phaser.Types.Math.Vector2Like} [x] - The x component, or an object with `x` and `y` properties. - * @param {number} [y] - The y component. - */ -var Vector2 = new Class({ - - initialize: - - function Vector2 (x, y) - { - /** - * The x component of this Vector. - * - * @name Phaser.Math.Vector2#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = 0; - - /** - * The y component of this Vector. - * - * @name Phaser.Math.Vector2#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = 0; - - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - } - else - { - if (y === undefined) { y = x; } - - this.x = x || 0; - this.y = y || 0; - } - }, - - /** - * Make a clone of this Vector2. - * - * @method Phaser.Math.Vector2#clone - * @since 3.0.0 - * - * @return {Phaser.Math.Vector2} A clone of this Vector2. - */ - clone: function () - { - return new Vector2(this.x, this.y); - }, - - /** - * Copy the components of a given Vector into this Vector. - * - * @method Phaser.Math.Vector2#copy - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to copy the components from. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - copy: function (src) - { - this.x = src.x || 0; - this.y = src.y || 0; - - return this; - }, - - /** - * Set the component values of this Vector from a given Vector2Like object. - * - * @method Phaser.Math.Vector2#setFromObject - * @since 3.0.0 - * - * @param {Phaser.Types.Math.Vector2Like} obj - The object containing the component values to set for this Vector. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - setFromObject: function (obj) - { - this.x = obj.x || 0; - this.y = obj.y || 0; - - return this; - }, - - /** - * Set the `x` and `y` components of the this Vector to the given `x` and `y` values. - * - * @method Phaser.Math.Vector2#set - * @since 3.0.0 - * - * @param {number} x - The x value to set for this Vector. - * @param {number} [y=x] - The y value to set for this Vector. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - set: function (x, y) - { - if (y === undefined) { y = x; } - - this.x = x; - this.y = y; - - return this; - }, - - /** - * This method is an alias for `Vector2.set`. - * - * @method Phaser.Math.Vector2#setTo - * @since 3.4.0 - * - * @param {number} x - The x value to set for this Vector. - * @param {number} [y=x] - The y value to set for this Vector. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - setTo: function (x, y) - { - return this.set(x, y); - }, - - /** - * Sets the `x` and `y` values of this object from a given polar coordinate. - * - * @method Phaser.Math.Vector2#setToPolar - * @since 3.0.0 - * - * @param {number} azimuth - The angular coordinate, in radians. - * @param {number} [radius=1] - The radial coordinate (length). - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - setToPolar: function (azimuth, radius) - { - if (radius == null) { radius = 1; } - - this.x = Math.cos(azimuth) * radius; - this.y = Math.sin(azimuth) * radius; - - return this; - }, - - /** - * Check whether this Vector is equal to a given Vector. - * - * Performs a strict equality check against each Vector's components. - * - * @method Phaser.Math.Vector2#equals - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} v - The vector to compare with this Vector. - * - * @return {boolean} Whether the given Vector is equal to this Vector. - */ - equals: function (v) - { - return ((this.x === v.x) && (this.y === v.y)); - }, - - /** - * Calculate the angle between this Vector and the positive x-axis, in radians. - * - * @method Phaser.Math.Vector2#angle - * @since 3.0.0 - * - * @return {number} The angle between this Vector, and the positive x-axis, given in radians. - */ - angle: function () - { - // computes the angle in radians with respect to the positive x-axis - - var angle = Math.atan2(this.y, this.x); - - if (angle < 0) - { - angle += 2 * Math.PI; - } - - return angle; - }, - - /** - * Add a given Vector to this Vector. Addition is component-wise. - * - * @method Phaser.Math.Vector2#add - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to add to this Vector. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - add: function (src) - { - this.x += src.x; - this.y += src.y; - - return this; - }, - - /** - * Subtract the given Vector from this Vector. Subtraction is component-wise. - * - * @method Phaser.Math.Vector2#subtract - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to subtract from this Vector. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - subtract: function (src) - { - this.x -= src.x; - this.y -= src.y; - - return this; - }, - - /** - * Perform a component-wise multiplication between this Vector and the given Vector. - * - * Multiplies this Vector by the given Vector. - * - * @method Phaser.Math.Vector2#multiply - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to multiply this Vector by. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - multiply: function (src) - { - this.x *= src.x; - this.y *= src.y; - - return this; - }, - - /** - * Scale this Vector by the given value. - * - * @method Phaser.Math.Vector2#scale - * @since 3.0.0 - * - * @param {number} value - The value to scale this Vector by. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - scale: function (value) - { - if (isFinite(value)) - { - this.x *= value; - this.y *= value; - } - else - { - this.x = 0; - this.y = 0; - } - - return this; - }, - - /** - * Perform a component-wise division between this Vector and the given Vector. - * - * Divides this Vector by the given Vector. - * - * @method Phaser.Math.Vector2#divide - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to divide this Vector by. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - divide: function (src) - { - this.x /= src.x; - this.y /= src.y; - - return this; - }, - - /** - * Negate the `x` and `y` components of this Vector. - * - * @method Phaser.Math.Vector2#negate - * @since 3.0.0 - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - negate: function () - { - this.x = -this.x; - this.y = -this.y; - - return this; - }, - - /** - * Calculate the distance between this Vector and the given Vector. - * - * @method Phaser.Math.Vector2#distance - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to calculate the distance to. - * - * @return {number} The distance from this Vector to the given Vector. - */ - distance: function (src) - { - var dx = src.x - this.x; - var dy = src.y - this.y; - - return Math.sqrt(dx * dx + dy * dy); - }, - - /** - * Calculate the distance between this Vector and the given Vector, squared. - * - * @method Phaser.Math.Vector2#distanceSq - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector to calculate the distance to. - * - * @return {number} The distance from this Vector to the given Vector, squared. - */ - distanceSq: function (src) - { - var dx = src.x - this.x; - var dy = src.y - this.y; - - return dx * dx + dy * dy; - }, - - /** - * Calculate the length (or magnitude) of this Vector. - * - * @method Phaser.Math.Vector2#length - * @since 3.0.0 - * - * @return {number} The length of this Vector. - */ - length: function () - { - var x = this.x; - var y = this.y; - - return Math.sqrt(x * x + y * y); - }, - - /** - * Calculate the length of this Vector squared. - * - * @method Phaser.Math.Vector2#lengthSq - * @since 3.0.0 - * - * @return {number} The length of this Vector, squared. - */ - lengthSq: function () - { - var x = this.x; - var y = this.y; - - return x * x + y * y; - }, - - /** - * Normalize this Vector. - * - * Makes the vector a unit length vector (magnitude of 1) in the same direction. - * - * @method Phaser.Math.Vector2#normalize - * @since 3.0.0 - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - normalize: function () - { - var x = this.x; - var y = this.y; - var len = x * x + y * y; - - if (len > 0) - { - len = 1 / Math.sqrt(len); - - this.x = x * len; - this.y = y * len; - } - - return this; - }, - - /** - * Right-hand normalize (make unit length) this Vector. - * - * @method Phaser.Math.Vector2#normalizeRightHand - * @since 3.0.0 - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - normalizeRightHand: function () - { - var x = this.x; - - this.x = this.y * -1; - this.y = x; - - return this; - }, - - /** - * Calculate the dot product of this Vector and the given Vector. - * - * @method Phaser.Math.Vector2#dot - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector2 to dot product with this Vector2. - * - * @return {number} The dot product of this Vector and the given Vector. - */ - dot: function (src) - { - return this.x * src.x + this.y * src.y; - }, - - /** - * Calculate the cross product of this Vector and the given Vector. - * - * @method Phaser.Math.Vector2#cross - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector2 to cross with this Vector2. - * - * @return {number} The cross product of this Vector and the given Vector. - */ - cross: function (src) - { - return this.x * src.y - this.y * src.x; - }, - - /** - * Linearly interpolate between this Vector and the given Vector. - * - * Interpolates this Vector towards the given Vector. - * - * @method Phaser.Math.Vector2#lerp - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} src - The Vector2 to interpolate towards. - * @param {number} [t=0] - The interpolation percentage, between 0 and 1. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - lerp: function (src, t) - { - if (t === undefined) { t = 0; } - - var ax = this.x; - var ay = this.y; - - this.x = ax + t * (src.x - ax); - this.y = ay + t * (src.y - ay); - - return this; - }, - - /** - * Transform this Vector with the given Matrix. - * - * @method Phaser.Math.Vector2#transformMat3 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} mat - The Matrix3 to transform this Vector2 with. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - transformMat3: function (mat) - { - var x = this.x; - var y = this.y; - var m = mat.val; - - this.x = m[0] * x + m[3] * y + m[6]; - this.y = m[1] * x + m[4] * y + m[7]; - - return this; - }, - - /** - * Transform this Vector with the given Matrix. - * - * @method Phaser.Math.Vector2#transformMat4 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector2 with. - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - transformMat4: function (mat) - { - var x = this.x; - var y = this.y; - var m = mat.val; - - this.x = m[0] * x + m[4] * y + m[12]; - this.y = m[1] * x + m[5] * y + m[13]; - - return this; - }, - - /** - * Make this Vector the zero vector (0, 0). - * - * @method Phaser.Math.Vector2#reset - * @since 3.0.0 - * - * @return {Phaser.Math.Vector2} This Vector2. - */ - reset: function () - { - this.x = 0; - this.y = 0; - - return this; - } - -}); - -/** - * A static zero Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector2.ZERO - * @type {Phaser.Math.Vector2} - * @since 3.1.0 - */ -Vector2.ZERO = new Vector2(); - -/** - * A static right Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector2.RIGHT - * @type {Phaser.Math.Vector2} - * @since 3.16.0 - */ -Vector2.RIGHT = new Vector2(1, 0); - -/** - * A static left Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector2.LEFT - * @type {Phaser.Math.Vector2} - * @since 3.16.0 - */ -Vector2.LEFT = new Vector2(-1, 0); - -/** - * A static up Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector2.UP - * @type {Phaser.Math.Vector2} - * @since 3.16.0 - */ -Vector2.UP = new Vector2(0, -1); - -/** - * A static down Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector2.DOWN - * @type {Phaser.Math.Vector2} - * @since 3.16.0 - */ -Vector2.DOWN = new Vector2(0, 1); - -/** - * A static one Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector2.ONE - * @type {Phaser.Math.Vector2} - * @since 3.16.0 - */ -Vector2.ONE = new Vector2(1, 1); - -module.exports = Vector2; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A representation of a vector in 2D space. + * + * A two-component vector. + * + * @class Vector2 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number|Phaser.Types.Math.Vector2Like} [x] - The x component, or an object with `x` and `y` properties. + * @param {number} [y] - The y component. + */ +var Vector2 = new Class({ + + initialize: + + function Vector2 (x, y) + { + /** + * The x component of this Vector. + * + * @name Phaser.Math.Vector2#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y component of this Vector. + * + * @name Phaser.Math.Vector2#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + } + else + { + if (y === undefined) { y = x; } + + this.x = x || 0; + this.y = y || 0; + } + }, + + /** + * Make a clone of this Vector2. + * + * @method Phaser.Math.Vector2#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} A clone of this Vector2. + */ + clone: function () + { + return new Vector2(this.x, this.y); + }, + + /** + * Copy the components of a given Vector into this Vector. + * + * @method Phaser.Math.Vector2#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to copy the components from. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + copy: function (src) + { + this.x = src.x || 0; + this.y = src.y || 0; + + return this; + }, + + /** + * Set the component values of this Vector from a given Vector2Like object. + * + * @method Phaser.Math.Vector2#setFromObject + * @since 3.0.0 + * + * @param {Phaser.Types.Math.Vector2Like} obj - The object containing the component values to set for this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + setFromObject: function (obj) + { + this.x = obj.x || 0; + this.y = obj.y || 0; + + return this; + }, + + /** + * Set the `x` and `y` components of the this Vector to the given `x` and `y` values. + * + * @method Phaser.Math.Vector2#set + * @since 3.0.0 + * + * @param {number} x - The x value to set for this Vector. + * @param {number} [y=x] - The y value to set for this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + set: function (x, y) + { + if (y === undefined) { y = x; } + + this.x = x; + this.y = y; + + return this; + }, + + /** + * This method is an alias for `Vector2.set`. + * + * @method Phaser.Math.Vector2#setTo + * @since 3.4.0 + * + * @param {number} x - The x value to set for this Vector. + * @param {number} [y=x] - The y value to set for this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + setTo: function (x, y) + { + return this.set(x, y); + }, + + /** + * Sets the `x` and `y` values of this object from a given polar coordinate. + * + * @method Phaser.Math.Vector2#setToPolar + * @since 3.0.0 + * + * @param {number} azimuth - The angular coordinate, in radians. + * @param {number} [radius=1] - The radial coordinate (length). + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + setToPolar: function (azimuth, radius) + { + if (radius == null) { radius = 1; } + + this.x = Math.cos(azimuth) * radius; + this.y = Math.sin(azimuth) * radius; + + return this; + }, + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict equality check against each Vector's components. + * + * @method Phaser.Math.Vector2#equals + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} v - The vector to compare with this Vector. + * + * @return {boolean} Whether the given Vector is equal to this Vector. + */ + equals: function (v) + { + return ((this.x === v.x) && (this.y === v.y)); + }, + + /** + * Calculate the angle between this Vector and the positive x-axis, in radians. + * + * @method Phaser.Math.Vector2#angle + * @since 3.0.0 + * + * @return {number} The angle between this Vector, and the positive x-axis, given in radians. + */ + angle: function () + { + // computes the angle in radians with respect to the positive x-axis + + var angle = Math.atan2(this.y, this.x); + + if (angle < 0) + { + angle += 2 * Math.PI; + } + + return angle; + }, + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * + * @method Phaser.Math.Vector2#add + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to add to this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + add: function (src) + { + this.x += src.x; + this.y += src.y; + + return this; + }, + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * + * @method Phaser.Math.Vector2#subtract + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to subtract from this Vector. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + subtract: function (src) + { + this.x -= src.x; + this.y -= src.y; + + return this; + }, + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * + * @method Phaser.Math.Vector2#multiply + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to multiply this Vector by. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + multiply: function (src) + { + this.x *= src.x; + this.y *= src.y; + + return this; + }, + + /** + * Scale this Vector by the given value. + * + * @method Phaser.Math.Vector2#scale + * @since 3.0.0 + * + * @param {number} value - The value to scale this Vector by. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + scale: function (value) + { + if (isFinite(value)) + { + this.x *= value; + this.y *= value; + } + else + { + this.x = 0; + this.y = 0; + } + + return this; + }, + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * + * @method Phaser.Math.Vector2#divide + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to divide this Vector by. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + divide: function (src) + { + this.x /= src.x; + this.y /= src.y; + + return this; + }, + + /** + * Negate the `x` and `y` components of this Vector. + * + * @method Phaser.Math.Vector2#negate + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + negate: function () + { + this.x = -this.x; + this.y = -this.y; + + return this; + }, + + /** + * Calculate the distance between this Vector and the given Vector. + * + * @method Phaser.Math.Vector2#distance + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector. + */ + distance: function (src) + { + var dx = src.x - this.x; + var dy = src.y - this.y; + + return Math.sqrt(dx * dx + dy * dy); + }, + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * + * @method Phaser.Math.Vector2#distanceSq + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector, squared. + */ + distanceSq: function (src) + { + var dx = src.x - this.x; + var dy = src.y - this.y; + + return dx * dx + dy * dy; + }, + + /** + * Calculate the length (or magnitude) of this Vector. + * + * @method Phaser.Math.Vector2#length + * @since 3.0.0 + * + * @return {number} The length of this Vector. + */ + length: function () + { + var x = this.x; + var y = this.y; + + return Math.sqrt(x * x + y * y); + }, + + /** + * Calculate the length of this Vector squared. + * + * @method Phaser.Math.Vector2#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Vector, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + + return x * x + y * y; + }, + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + * + * @method Phaser.Math.Vector2#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var len = x * x + y * y; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + } + + return this; + }, + + /** + * Right-hand normalize (make unit length) this Vector. + * + * @method Phaser.Math.Vector2#normalizeRightHand + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + normalizeRightHand: function () + { + var x = this.x; + + this.x = this.y * -1; + this.y = x; + + return this; + }, + + /** + * Calculate the dot product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector2#dot + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector2 to dot product with this Vector2. + * + * @return {number} The dot product of this Vector and the given Vector. + */ + dot: function (src) + { + return this.x * src.x + this.y * src.y; + }, + + /** + * Calculate the cross product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector2#cross + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector2 to cross with this Vector2. + * + * @return {number} The cross product of this Vector and the given Vector. + */ + cross: function (src) + { + return this.x * src.y - this.y * src.x; + }, + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * + * @method Phaser.Math.Vector2#lerp + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} src - The Vector2 to interpolate towards. + * @param {number} [t=0] - The interpolation percentage, between 0 and 1. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + lerp: function (src, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + + this.x = ax + t * (src.x - ax); + this.y = ay + t * (src.y - ay); + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector2#transformMat3 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} mat - The Matrix3 to transform this Vector2 with. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + transformMat3: function (mat) + { + var x = this.x; + var y = this.y; + var m = mat.val; + + this.x = m[0] * x + m[3] * y + m[6]; + this.y = m[1] * x + m[4] * y + m[7]; + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector2#transformMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector2 with. + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + transformMat4: function (mat) + { + var x = this.x; + var y = this.y; + var m = mat.val; + + this.x = m[0] * x + m[4] * y + m[12]; + this.y = m[1] * x + m[5] * y + m[13]; + + return this; + }, + + /** + * Make this Vector the zero vector (0, 0). + * + * @method Phaser.Math.Vector2#reset + * @since 3.0.0 + * + * @return {Phaser.Math.Vector2} This Vector2. + */ + reset: function () + { + this.x = 0; + this.y = 0; + + return this; + } + +}); + +/** + * A static zero Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.ZERO + * @type {Phaser.Math.Vector2} + * @since 3.1.0 + */ +Vector2.ZERO = new Vector2(); + +/** + * A static right Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.RIGHT + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.RIGHT = new Vector2(1, 0); + +/** + * A static left Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.LEFT + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.LEFT = new Vector2(-1, 0); + +/** + * A static up Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.UP + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.UP = new Vector2(0, -1); + +/** + * A static down Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.DOWN + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.DOWN = new Vector2(0, 1); + +/** + * A static one Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector2.ONE + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ +Vector2.ONE = new Vector2(1, 1); + +module.exports = Vector2; diff --git a/src/math/Vector3.js b/src/math/Vector3.js index f22b37155..0d3bf3cf2 100644 --- a/src/math/Vector3.js +++ b/src/math/Vector3.js @@ -1,804 +1,804 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji -// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A representation of a vector in 3D space. - * - * A three-component vector. - * - * @class Vector3 - * @memberof Phaser.Math - * @constructor - * @since 3.0.0 - * - * @param {number} [x] - The x component. - * @param {number} [y] - The y component. - * @param {number} [z] - The z component. - */ -var Vector3 = new Class({ - - initialize: - - function Vector3 (x, y, z) - { - /** - * The x component of this Vector. - * - * @name Phaser.Math.Vector3#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = 0; - - /** - * The y component of this Vector. - * - * @name Phaser.Math.Vector3#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = 0; - - /** - * The z component of this Vector. - * - * @name Phaser.Math.Vector3#z - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.z = 0; - - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - this.z = x.z || 0; - } - else - { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - } - }, - - /** - * Set this Vector to point up. - * - * Sets the y component of the vector to 1, and the others to 0. - * - * @method Phaser.Math.Vector3#up - * @since 3.0.0 - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - up: function () - { - this.x = 0; - this.y = 1; - this.z = 0; - - return this; - }, - - /** - * Make a clone of this Vector3. - * - * @method Phaser.Math.Vector3#clone - * @since 3.0.0 - * - * @return {Phaser.Math.Vector3} A new Vector3 object containing this Vectors values. - */ - clone: function () - { - return new Vector3(this.x, this.y, this.z); - }, - - /** - * Calculate the cross (vector) product of two given Vectors. - * - * @method Phaser.Math.Vector3#crossVectors - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} a - The first Vector to multiply. - * @param {Phaser.Math.Vector3} b - The second Vector to multiply. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - crossVectors: function (a, b) - { - var ax = a.x; - var ay = a.y; - var az = a.z; - var bx = b.x; - var by = b.y; - var bz = b.z; - - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - - return this; - }, - - /** - * Check whether this Vector is equal to a given Vector. - * - * Performs a strict equality check against each Vector's components. - * - * @method Phaser.Math.Vector3#equals - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} v - The Vector3 to compare against. - * - * @return {boolean} True if the two vectors strictly match, otherwise false. - */ - equals: function (v) - { - return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z)); - }, - - /** - * Copy the components of a given Vector into this Vector. - * - * @method Phaser.Math.Vector3#copy - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} src - The Vector to copy the components from. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - copy: function (src) - { - this.x = src.x; - this.y = src.y; - this.z = src.z || 0; - - return this; - }, - - /** - * Set the `x`, `y`, and `z` components of this Vector to the given `x`, `y`, and `z` values. - * - * @method Phaser.Math.Vector3#set - * @since 3.0.0 - * - * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y and z components. - * @param {number} [y] - The y value to set for this Vector. - * @param {number} [z] - The z value to set for this Vector. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - set: function (x, y, z) - { - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - this.z = x.z || 0; - } - else - { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - } - - return this; - }, - - /** - * Add a given Vector to this Vector. Addition is component-wise. - * - * @method Phaser.Math.Vector3#add - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to add to this Vector. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - add: function (v) - { - this.x += v.x; - this.y += v.y; - this.z += v.z || 0; - - return this; - }, - - /** - * Subtract the given Vector from this Vector. Subtraction is component-wise. - * - * @method Phaser.Math.Vector3#subtract - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to subtract from this Vector. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - subtract: function (v) - { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z || 0; - - return this; - }, - - /** - * Perform a component-wise multiplication between this Vector and the given Vector. - * - * Multiplies this Vector by the given Vector. - * - * @method Phaser.Math.Vector3#multiply - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to multiply this Vector by. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - multiply: function (v) - { - this.x *= v.x; - this.y *= v.y; - this.z *= v.z || 1; - - return this; - }, - - /** - * Scale this Vector by the given value. - * - * @method Phaser.Math.Vector3#scale - * @since 3.0.0 - * - * @param {number} scale - The value to scale this Vector by. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - scale: function (scale) - { - if (isFinite(scale)) - { - this.x *= scale; - this.y *= scale; - this.z *= scale; - } - else - { - this.x = 0; - this.y = 0; - this.z = 0; - } - - return this; - }, - - /** - * Perform a component-wise division between this Vector and the given Vector. - * - * Divides this Vector by the given Vector. - * - * @method Phaser.Math.Vector3#divide - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to divide this Vector by. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - divide: function (v) - { - this.x /= v.x; - this.y /= v.y; - this.z /= v.z || 1; - - return this; - }, - - /** - * Negate the `x`, `y` and `z` components of this Vector. - * - * @method Phaser.Math.Vector3#negate - * @since 3.0.0 - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - negate: function () - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - - return this; - }, - - /** - * Calculate the distance between this Vector and the given Vector. - * - * @method Phaser.Math.Vector3#distance - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to calculate the distance to. - * - * @return {number} The distance from this Vector to the given Vector. - */ - distance: function (v) - { - var dx = v.x - this.x; - var dy = v.y - this.y; - var dz = v.z - this.z || 0; - - return Math.sqrt(dx * dx + dy * dy + dz * dz); - }, - - /** - * Calculate the distance between this Vector and the given Vector, squared. - * - * @method Phaser.Math.Vector3#distanceSq - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to calculate the distance to. - * - * @return {number} The distance from this Vector to the given Vector, squared. - */ - distanceSq: function (v) - { - var dx = v.x - this.x; - var dy = v.y - this.y; - var dz = v.z - this.z || 0; - - return dx * dx + dy * dy + dz * dz; - }, - - /** - * Calculate the length (or magnitude) of this Vector. - * - * @method Phaser.Math.Vector3#length - * @since 3.0.0 - * - * @return {number} The length of this Vector. - */ - length: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - - return Math.sqrt(x * x + y * y + z * z); - }, - - /** - * Calculate the length of this Vector squared. - * - * @method Phaser.Math.Vector3#lengthSq - * @since 3.0.0 - * - * @return {number} The length of this Vector, squared. - */ - lengthSq: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - - return x * x + y * y + z * z; - }, - - /** - * Normalize this Vector. - * - * Makes the vector a unit length vector (magnitude of 1) in the same direction. - * - * @method Phaser.Math.Vector3#normalize - * @since 3.0.0 - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - normalize: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var len = x * x + y * y + z * z; - - if (len > 0) - { - len = 1 / Math.sqrt(len); - - this.x = x * len; - this.y = y * len; - this.z = z * len; - } - - return this; - }, - - /** - * Calculate the dot product of this Vector and the given Vector. - * - * @method Phaser.Math.Vector3#dot - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} v - The Vector3 to dot product with this Vector3. - * - * @return {number} The dot product of this Vector and `v`. - */ - dot: function (v) - { - return this.x * v.x + this.y * v.y + this.z * v.z; - }, - - /** - * Calculate the cross (vector) product of this Vector (which will be modified) and the given Vector. - * - * @method Phaser.Math.Vector3#cross - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} v - The Vector to cross product with. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - cross: function (v) - { - var ax = this.x; - var ay = this.y; - var az = this.z; - var bx = v.x; - var by = v.y; - var bz = v.z; - - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - - return this; - }, - - /** - * Linearly interpolate between this Vector and the given Vector. - * - * Interpolates this Vector towards the given Vector. - * - * @method Phaser.Math.Vector3#lerp - * @since 3.0.0 - * - * @param {Phaser.Math.Vector3} v - The Vector3 to interpolate towards. - * @param {number} [t=0] - The interpolation percentage, between 0 and 1. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - lerp: function (v, t) - { - if (t === undefined) { t = 0; } - - var ax = this.x; - var ay = this.y; - var az = this.z; - - this.x = ax + t * (v.x - ax); - this.y = ay + t * (v.y - ay); - this.z = az + t * (v.z - az); - - return this; - }, - - /** - * Transform this Vector with the given Matrix. - * - * @method Phaser.Math.Vector3#transformMat3 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix3} mat - The Matrix3 to transform this Vector3 with. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - transformMat3: function (mat) - { - var x = this.x; - var y = this.y; - var z = this.z; - var m = mat.val; - - this.x = x * m[0] + y * m[3] + z * m[6]; - this.y = x * m[1] + y * m[4] + z * m[7]; - this.z = x * m[2] + y * m[5] + z * m[8]; - - return this; - }, - - /** - * Transform this Vector with the given Matrix. - * - * @method Phaser.Math.Vector3#transformMat4 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector3 with. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - transformMat4: function (mat) - { - var x = this.x; - var y = this.y; - var z = this.z; - var m = mat.val; - - this.x = m[0] * x + m[4] * y + m[8] * z + m[12]; - this.y = m[1] * x + m[5] * y + m[9] * z + m[13]; - this.z = m[2] * x + m[6] * y + m[10] * z + m[14]; - - return this; - }, - - /** - * Transforms the coordinates of this Vector3 with the given Matrix4. - * - * @method Phaser.Math.Vector3#transformCoordinates - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector3 with. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - transformCoordinates: function (mat) - { - var x = this.x; - var y = this.y; - var z = this.z; - var m = mat.val; - - var tx = (x * m[0]) + (y * m[4]) + (z * m[8]) + m[12]; - var ty = (x * m[1]) + (y * m[5]) + (z * m[9]) + m[13]; - var tz = (x * m[2]) + (y * m[6]) + (z * m[10]) + m[14]; - var tw = (x * m[3]) + (y * m[7]) + (z * m[11]) + m[15]; - - this.x = tx / tw; - this.y = ty / tw; - this.z = tz / tw; - - return this; - }, - - /** - * Transform this Vector with the given Quaternion. - * - * @method Phaser.Math.Vector3#transformQuat - * @since 3.0.0 - * - * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - transformQuat: function (q) - { - // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations - var x = this.x; - var y = this.y; - var z = this.z; - var qx = q.x; - var qy = q.y; - var qz = q.z; - var qw = q.w; - - // calculate quat * vec - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = -qx * x - qy * y - qz * z; - - // calculate result * inverse quat - this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - - return this; - }, - - /** - * Multiplies this Vector3 by the specified matrix, applying a W divide. This is useful for projection, - * e.g. unprojecting a 2D point into 3D space. - * - * @method Phaser.Math.Vector3#project - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} mat - The Matrix4 to multiply this Vector3 with. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - project: function (mat) - { - var x = this.x; - var y = this.y; - var z = this.z; - var m = mat.val; - - var a00 = m[0]; - var a01 = m[1]; - var a02 = m[2]; - var a03 = m[3]; - var a10 = m[4]; - var a11 = m[5]; - var a12 = m[6]; - var a13 = m[7]; - var a20 = m[8]; - var a21 = m[9]; - var a22 = m[10]; - var a23 = m[11]; - var a30 = m[12]; - var a31 = m[13]; - var a32 = m[14]; - var a33 = m[15]; - - var lw = 1 / (x * a03 + y * a13 + z * a23 + a33); - - this.x = (x * a00 + y * a10 + z * a20 + a30) * lw; - this.y = (x * a01 + y * a11 + z * a21 + a31) * lw; - this.z = (x * a02 + y * a12 + z * a22 + a32) * lw; - - return this; - }, - - /** - * Unproject this point from 2D space to 3D space. - * The point should have its x and y properties set to - * 2D screen space, and the z either at 0 (near plane) - * or 1 (far plane). The provided matrix is assumed to already - * be combined, i.e. projection * view * model. - * - * After this operation, this vector's (x, y, z) components will - * represent the unprojected 3D coordinate. - * - * @method Phaser.Math.Vector3#unproject - * @since 3.0.0 - * - * @param {Phaser.Math.Vector4} viewport - Screen x, y, width and height in pixels. - * @param {Phaser.Math.Matrix4} invProjectionView - Combined projection and view matrix. - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - unproject: function (viewport, invProjectionView) - { - var viewX = viewport.x; - var viewY = viewport.y; - var viewWidth = viewport.z; - var viewHeight = viewport.w; - - var x = this.x - viewX; - var y = (viewHeight - this.y - 1) - viewY; - var z = this.z; - - this.x = (2 * x) / viewWidth - 1; - this.y = (2 * y) / viewHeight - 1; - this.z = 2 * z - 1; - - return this.project(invProjectionView); - }, - - /** - * Make this Vector the zero vector (0, 0, 0). - * - * @method Phaser.Math.Vector3#reset - * @since 3.0.0 - * - * @return {Phaser.Math.Vector3} This Vector3. - */ - reset: function () - { - this.x = 0; - this.y = 0; - this.z = 0; - - return this; - } - -}); - -/** - * A static zero Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.ZERO - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.ZERO = new Vector3(); - -/** - * A static right Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.RIGHT - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.RIGHT = new Vector3(1, 0, 0); - -/** - * A static left Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.LEFT - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.LEFT = new Vector3(-1, 0, 0); - -/** - * A static up Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.UP - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.UP = new Vector3(0, -1, 0); - -/** - * A static down Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.DOWN - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.DOWN = new Vector3(0, 1, 0); - -/** - * A static forward Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.FORWARD - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.FORWARD = new Vector3(0, 0, 1); - -/** - * A static back Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.BACK - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.BACK = new Vector3(0, 0, -1); - -/** - * A static one Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - * - * @constant - * @name Phaser.Math.Vector3.ONE - * @type {Phaser.Math.Vector3} - * @since 3.16.0 - */ -Vector3.ONE = new Vector3(1, 1, 1); - -module.exports = Vector3; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A representation of a vector in 3D space. + * + * A three-component vector. + * + * @class Vector3 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - The x component. + * @param {number} [y] - The y component. + * @param {number} [z] - The z component. + */ +var Vector3 = new Class({ + + initialize: + + function Vector3 (x, y, z) + { + /** + * The x component of this Vector. + * + * @name Phaser.Math.Vector3#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y component of this Vector. + * + * @name Phaser.Math.Vector3#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The z component of this Vector. + * + * @name Phaser.Math.Vector3#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.z = 0; + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + } + }, + + /** + * Set this Vector to point up. + * + * Sets the y component of the vector to 1, and the others to 0. + * + * @method Phaser.Math.Vector3#up + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + up: function () + { + this.x = 0; + this.y = 1; + this.z = 0; + + return this; + }, + + /** + * Make a clone of this Vector3. + * + * @method Phaser.Math.Vector3#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} A new Vector3 object containing this Vectors values. + */ + clone: function () + { + return new Vector3(this.x, this.y, this.z); + }, + + /** + * Calculate the cross (vector) product of two given Vectors. + * + * @method Phaser.Math.Vector3#crossVectors + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} a - The first Vector to multiply. + * @param {Phaser.Math.Vector3} b - The second Vector to multiply. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + crossVectors: function (a, b) + { + var ax = a.x; + var ay = a.y; + var az = a.z; + var bx = b.x; + var by = b.y; + var bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + }, + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict equality check against each Vector's components. + * + * @method Phaser.Math.Vector3#equals + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector3 to compare against. + * + * @return {boolean} True if the two vectors strictly match, otherwise false. + */ + equals: function (v) + { + return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z)); + }, + + /** + * Copy the components of a given Vector into this Vector. + * + * @method Phaser.Math.Vector3#copy + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} src - The Vector to copy the components from. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + copy: function (src) + { + this.x = src.x; + this.y = src.y; + this.z = src.z || 0; + + return this; + }, + + /** + * Set the `x`, `y`, and `z` components of this Vector to the given `x`, `y`, and `z` values. + * + * @method Phaser.Math.Vector3#set + * @since 3.0.0 + * + * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y and z components. + * @param {number} [y] - The y value to set for this Vector. + * @param {number} [z] - The z value to set for this Vector. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + set: function (x, y, z) + { + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + } + + return this; + }, + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * + * @method Phaser.Math.Vector3#add + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to add to this Vector. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + add: function (v) + { + this.x += v.x; + this.y += v.y; + this.z += v.z || 0; + + return this; + }, + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * + * @method Phaser.Math.Vector3#subtract + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to subtract from this Vector. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + subtract: function (v) + { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z || 0; + + return this; + }, + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * + * @method Phaser.Math.Vector3#multiply + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to multiply this Vector by. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + multiply: function (v) + { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z || 1; + + return this; + }, + + /** + * Scale this Vector by the given value. + * + * @method Phaser.Math.Vector3#scale + * @since 3.0.0 + * + * @param {number} scale - The value to scale this Vector by. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + scale: function (scale) + { + if (isFinite(scale)) + { + this.x *= scale; + this.y *= scale; + this.z *= scale; + } + else + { + this.x = 0; + this.y = 0; + this.z = 0; + } + + return this; + }, + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * + * @method Phaser.Math.Vector3#divide + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to divide this Vector by. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + divide: function (v) + { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z || 1; + + return this; + }, + + /** + * Negate the `x`, `y` and `z` components of this Vector. + * + * @method Phaser.Math.Vector3#negate + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + negate: function () + { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + + return this; + }, + + /** + * Calculate the distance between this Vector and the given Vector. + * + * @method Phaser.Math.Vector3#distance + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector. + */ + distance: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + + return Math.sqrt(dx * dx + dy * dy + dz * dz); + }, + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * + * @method Phaser.Math.Vector3#distanceSq + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector, squared. + */ + distanceSq: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + + return dx * dx + dy * dy + dz * dz; + }, + + /** + * Calculate the length (or magnitude) of this Vector. + * + * @method Phaser.Math.Vector3#length + * @since 3.0.0 + * + * @return {number} The length of this Vector. + */ + length: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + + return Math.sqrt(x * x + y * y + z * z); + }, + + /** + * Calculate the length of this Vector squared. + * + * @method Phaser.Math.Vector3#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Vector, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + + return x * x + y * y + z * z; + }, + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + * + * @method Phaser.Math.Vector3#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var len = x * x + y * y + z * z; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + this.z = z * len; + } + + return this; + }, + + /** + * Calculate the dot product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector3#dot + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector3 to dot product with this Vector3. + * + * @return {number} The dot product of this Vector and `v`. + */ + dot: function (v) + { + return this.x * v.x + this.y * v.y + this.z * v.z; + }, + + /** + * Calculate the cross (vector) product of this Vector (which will be modified) and the given Vector. + * + * @method Phaser.Math.Vector3#cross + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector to cross product with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + cross: function (v) + { + var ax = this.x; + var ay = this.y; + var az = this.z; + var bx = v.x; + var by = v.y; + var bz = v.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + }, + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * + * @method Phaser.Math.Vector3#lerp + * @since 3.0.0 + * + * @param {Phaser.Math.Vector3} v - The Vector3 to interpolate towards. + * @param {number} [t=0] - The interpolation percentage, between 0 and 1. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + lerp: function (v, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + var az = this.z; + + this.x = ax + t * (v.x - ax); + this.y = ay + t * (v.y - ay); + this.z = az + t * (v.z - az); + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector3#transformMat3 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix3} mat - The Matrix3 to transform this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformMat3: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + this.x = x * m[0] + y * m[3] + z * m[6]; + this.y = x * m[1] + y * m[4] + z * m[7]; + this.z = x * m[2] + y * m[5] + z * m[8]; + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector3#transformMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformMat4: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + this.x = m[0] * x + m[4] * y + m[8] * z + m[12]; + this.y = m[1] * x + m[5] * y + m[9] * z + m[13]; + this.z = m[2] * x + m[6] * y + m[10] * z + m[14]; + + return this; + }, + + /** + * Transforms the coordinates of this Vector3 with the given Matrix4. + * + * @method Phaser.Math.Vector3#transformCoordinates + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformCoordinates: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + var tx = (x * m[0]) + (y * m[4]) + (z * m[8]) + m[12]; + var ty = (x * m[1]) + (y * m[5]) + (z * m[9]) + m[13]; + var tz = (x * m[2]) + (y * m[6]) + (z * m[10]) + m[14]; + var tw = (x * m[3]) + (y * m[7]) + (z * m[11]) + m[15]; + + this.x = tx / tw; + this.y = ty / tw; + this.z = tz / tw; + + return this; + }, + + /** + * Transform this Vector with the given Quaternion. + * + * @method Phaser.Math.Vector3#transformQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + transformQuat: function (q) + { + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + var x = this.x; + var y = this.y; + var z = this.z; + var qx = q.x; + var qy = q.y; + var qz = q.z; + var qw = q.w; + + // calculate quat * vec + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + + return this; + }, + + /** + * Multiplies this Vector3 by the specified matrix, applying a W divide. This is useful for projection, + * e.g. unprojecting a 2D point into 3D space. + * + * @method Phaser.Math.Vector3#project + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to multiply this Vector3 with. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + project: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var m = mat.val; + + var a00 = m[0]; + var a01 = m[1]; + var a02 = m[2]; + var a03 = m[3]; + var a10 = m[4]; + var a11 = m[5]; + var a12 = m[6]; + var a13 = m[7]; + var a20 = m[8]; + var a21 = m[9]; + var a22 = m[10]; + var a23 = m[11]; + var a30 = m[12]; + var a31 = m[13]; + var a32 = m[14]; + var a33 = m[15]; + + var lw = 1 / (x * a03 + y * a13 + z * a23 + a33); + + this.x = (x * a00 + y * a10 + z * a20 + a30) * lw; + this.y = (x * a01 + y * a11 + z * a21 + a31) * lw; + this.z = (x * a02 + y * a12 + z * a22 + a32) * lw; + + return this; + }, + + /** + * Unproject this point from 2D space to 3D space. + * The point should have its x and y properties set to + * 2D screen space, and the z either at 0 (near plane) + * or 1 (far plane). The provided matrix is assumed to already + * be combined, i.e. projection * view * model. + * + * After this operation, this vector's (x, y, z) components will + * represent the unprojected 3D coordinate. + * + * @method Phaser.Math.Vector3#unproject + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} viewport - Screen x, y, width and height in pixels. + * @param {Phaser.Math.Matrix4} invProjectionView - Combined projection and view matrix. + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + unproject: function (viewport, invProjectionView) + { + var viewX = viewport.x; + var viewY = viewport.y; + var viewWidth = viewport.z; + var viewHeight = viewport.w; + + var x = this.x - viewX; + var y = (viewHeight - this.y - 1) - viewY; + var z = this.z; + + this.x = (2 * x) / viewWidth - 1; + this.y = (2 * y) / viewHeight - 1; + this.z = 2 * z - 1; + + return this.project(invProjectionView); + }, + + /** + * Make this Vector the zero vector (0, 0, 0). + * + * @method Phaser.Math.Vector3#reset + * @since 3.0.0 + * + * @return {Phaser.Math.Vector3} This Vector3. + */ + reset: function () + { + this.x = 0; + this.y = 0; + this.z = 0; + + return this; + } + +}); + +/** + * A static zero Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.ZERO + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.ZERO = new Vector3(); + +/** + * A static right Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.RIGHT + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.RIGHT = new Vector3(1, 0, 0); + +/** + * A static left Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.LEFT + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.LEFT = new Vector3(-1, 0, 0); + +/** + * A static up Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.UP + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.UP = new Vector3(0, -1, 0); + +/** + * A static down Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.DOWN + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.DOWN = new Vector3(0, 1, 0); + +/** + * A static forward Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.FORWARD + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.FORWARD = new Vector3(0, 0, 1); + +/** + * A static back Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.BACK + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.BACK = new Vector3(0, 0, -1); + +/** + * A static one Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + * + * @constant + * @name Phaser.Math.Vector3.ONE + * @type {Phaser.Math.Vector3} + * @since 3.16.0 + */ +Vector3.ONE = new Vector3(1, 1, 1); + +module.exports = Vector3; diff --git a/src/math/Vector4.js b/src/math/Vector4.js index 5fba6bce7..b15de4cd2 100644 --- a/src/math/Vector4.js +++ b/src/math/Vector4.js @@ -1,539 +1,539 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji -// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A representation of a vector in 4D space. - * - * A four-component vector. - * - * @class Vector4 - * @memberof Phaser.Math - * @constructor - * @since 3.0.0 - * - * @param {number} [x] - The x component. - * @param {number} [y] - The y component. - * @param {number} [z] - The z component. - * @param {number} [w] - The w component. - */ -var Vector4 = new Class({ - - initialize: - - function Vector4 (x, y, z, w) - { - /** - * The x component of this Vector. - * - * @name Phaser.Math.Vector4#x - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.x = 0; - - /** - * The y component of this Vector. - * - * @name Phaser.Math.Vector4#y - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.y = 0; - - /** - * The z component of this Vector. - * - * @name Phaser.Math.Vector4#z - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.z = 0; - - /** - * The w component of this Vector. - * - * @name Phaser.Math.Vector4#w - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.w = 0; - - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - this.z = x.z || 0; - this.w = x.w || 0; - } - else - { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = w || 0; - } - }, - - /** - * Make a clone of this Vector4. - * - * @method Phaser.Math.Vector4#clone - * @since 3.0.0 - * - * @return {Phaser.Math.Vector4} A clone of this Vector4. - */ - clone: function () - { - return new Vector4(this.x, this.y, this.z, this.w); - }, - - /** - * Copy the components of a given Vector into this Vector. - * - * @method Phaser.Math.Vector4#copy - * @since 3.0.0 - * - * @param {Phaser.Math.Vector4} src - The Vector to copy the components from. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - copy: function (src) - { - this.x = src.x; - this.y = src.y; - this.z = src.z || 0; - this.w = src.w || 0; - - return this; - }, - - /** - * Check whether this Vector is equal to a given Vector. - * - * Performs a strict quality check against each Vector's components. - * - * @method Phaser.Math.Vector4#equals - * @since 3.0.0 - * - * @param {Phaser.Math.Vector4} v - The vector to check equality with. - * - * @return {boolean} A boolean indicating whether the two Vectors are equal or not. - */ - equals: function (v) - { - return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z) && (this.w === v.w)); - }, - - /** - * Set the `x`, `y`, `z` and `w` components of the this Vector to the given `x`, `y`, `z` and `w` values. - * - * @method Phaser.Math.Vector4#set - * @since 3.0.0 - * - * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y, z and w components. - * @param {number} y - The y value to set for this Vector. - * @param {number} z - The z value to set for this Vector. - * @param {number} w - The z value to set for this Vector. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - set: function (x, y, z, w) - { - if (typeof x === 'object') - { - this.x = x.x || 0; - this.y = x.y || 0; - this.z = x.z || 0; - this.w = x.w || 0; - } - else - { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = w || 0; - } - - return this; - }, - - /** - * Add a given Vector to this Vector. Addition is component-wise. - * - * @method Phaser.Math.Vector4#add - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to add to this Vector. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - add: function (v) - { - this.x += v.x; - this.y += v.y; - this.z += v.z || 0; - this.w += v.w || 0; - - return this; - }, - - /** - * Subtract the given Vector from this Vector. Subtraction is component-wise. - * - * @method Phaser.Math.Vector4#subtract - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to subtract from this Vector. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - subtract: function (v) - { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z || 0; - this.w -= v.w || 0; - - return this; - }, - - /** - * Scale this Vector by the given value. - * - * @method Phaser.Math.Vector4#scale - * @since 3.0.0 - * - * @param {number} scale - The value to scale this Vector by. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - scale: function (scale) - { - this.x *= scale; - this.y *= scale; - this.z *= scale; - this.w *= scale; - - return this; - }, - - /** - * Calculate the length (or magnitude) of this Vector. - * - * @method Phaser.Math.Vector4#length - * @since 3.0.0 - * - * @return {number} The length of this Vector. - */ - length: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - - return Math.sqrt(x * x + y * y + z * z + w * w); - }, - - /** - * Calculate the length of this Vector squared. - * - * @method Phaser.Math.Vector4#lengthSq - * @since 3.0.0 - * - * @return {number} The length of this Vector, squared. - */ - lengthSq: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - - return x * x + y * y + z * z + w * w; - }, - - /** - * Normalize this Vector. - * - * Makes the vector a unit length vector (magnitude of 1) in the same direction. - * - * @method Phaser.Math.Vector4#normalize - * @since 3.0.0 - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - normalize: function () - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - var len = x * x + y * y + z * z + w * w; - - if (len > 0) - { - len = 1 / Math.sqrt(len); - - this.x = x * len; - this.y = y * len; - this.z = z * len; - this.w = w * len; - } - - return this; - }, - - /** - * Calculate the dot product of this Vector and the given Vector. - * - * @method Phaser.Math.Vector4#dot - * @since 3.0.0 - * - * @param {Phaser.Math.Vector4} v - The Vector4 to dot product with this Vector4. - * - * @return {number} The dot product of this Vector and the given Vector. - */ - dot: function (v) - { - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - }, - - /** - * Linearly interpolate between this Vector and the given Vector. - * - * Interpolates this Vector towards the given Vector. - * - * @method Phaser.Math.Vector4#lerp - * @since 3.0.0 - * - * @param {Phaser.Math.Vector4} v - The Vector4 to interpolate towards. - * @param {number} [t=0] - The interpolation percentage, between 0 and 1. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - lerp: function (v, t) - { - if (t === undefined) { t = 0; } - - var ax = this.x; - var ay = this.y; - var az = this.z; - var aw = this.w; - - this.x = ax + t * (v.x - ax); - this.y = ay + t * (v.y - ay); - this.z = az + t * (v.z - az); - this.w = aw + t * (v.w - aw); - - return this; - }, - - /** - * Perform a component-wise multiplication between this Vector and the given Vector. - * - * Multiplies this Vector by the given Vector. - * - * @method Phaser.Math.Vector4#multiply - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to multiply this Vector by. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - multiply: function (v) - { - this.x *= v.x; - this.y *= v.y; - this.z *= v.z || 1; - this.w *= v.w || 1; - - return this; - }, - - /** - * Perform a component-wise division between this Vector and the given Vector. - * - * Divides this Vector by the given Vector. - * - * @method Phaser.Math.Vector4#divide - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to divide this Vector by. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - divide: function (v) - { - this.x /= v.x; - this.y /= v.y; - this.z /= v.z || 1; - this.w /= v.w || 1; - - return this; - }, - - /** - * Calculate the distance between this Vector and the given Vector. - * - * @method Phaser.Math.Vector4#distance - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. - * - * @return {number} The distance from this Vector to the given Vector. - */ - distance: function (v) - { - var dx = v.x - this.x; - var dy = v.y - this.y; - var dz = v.z - this.z || 0; - var dw = v.w - this.w || 0; - - return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); - }, - - /** - * Calculate the distance between this Vector and the given Vector, squared. - * - * @method Phaser.Math.Vector4#distanceSq - * @since 3.0.0 - * - * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. - * - * @return {number} The distance from this Vector to the given Vector, squared. - */ - distanceSq: function (v) - { - var dx = v.x - this.x; - var dy = v.y - this.y; - var dz = v.z - this.z || 0; - var dw = v.w - this.w || 0; - - return dx * dx + dy * dy + dz * dz + dw * dw; - }, - - /** - * Negate the `x`, `y`, `z` and `w` components of this Vector. - * - * @method Phaser.Math.Vector4#negate - * @since 3.0.0 - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - negate: function () - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; - - return this; - }, - - /** - * Transform this Vector with the given Matrix. - * - * @method Phaser.Math.Vector4#transformMat4 - * @since 3.0.0 - * - * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector4 with. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - transformMat4: function (mat) - { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; - var m = mat.val; - - this.x = m[0] * x + m[4] * y + m[8] * z + m[12] * w; - this.y = m[1] * x + m[5] * y + m[9] * z + m[13] * w; - this.z = m[2] * x + m[6] * y + m[10] * z + m[14] * w; - this.w = m[3] * x + m[7] * y + m[11] * z + m[15] * w; - - return this; - }, - - /** - * Transform this Vector with the given Quaternion. - * - * @method Phaser.Math.Vector4#transformQuat - * @since 3.0.0 - * - * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - transformQuat: function (q) - { - // TODO: is this really the same as Vector3? - // Also, what about this: http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ - // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations - var x = this.x; - var y = this.y; - var z = this.z; - var qx = q.x; - var qy = q.y; - var qz = q.z; - var qw = q.w; - - // calculate quat * vec - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = -qx * x - qy * y - qz * z; - - // calculate result * inverse quat - this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - - return this; - }, - - /** - * Make this Vector the zero vector (0, 0, 0, 0). - * - * @method Phaser.Math.Vector4#reset - * @since 3.0.0 - * - * @return {Phaser.Math.Vector4} This Vector4. - */ - reset: function () - { - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; - - return this; - } - -}); - -// TODO: Check if these are required internally, if not, remove. -Vector4.prototype.sub = Vector4.prototype.subtract; -Vector4.prototype.mul = Vector4.prototype.multiply; -Vector4.prototype.div = Vector4.prototype.divide; -Vector4.prototype.dist = Vector4.prototype.distance; -Vector4.prototype.distSq = Vector4.prototype.distanceSq; -Vector4.prototype.len = Vector4.prototype.length; -Vector4.prototype.lenSq = Vector4.prototype.lengthSq; - -module.exports = Vector4; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji +// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A representation of a vector in 4D space. + * + * A four-component vector. + * + * @class Vector4 + * @memberof Phaser.Math + * @constructor + * @since 3.0.0 + * + * @param {number} [x] - The x component. + * @param {number} [y] - The y component. + * @param {number} [z] - The z component. + * @param {number} [w] - The w component. + */ +var Vector4 = new Class({ + + initialize: + + function Vector4 (x, y, z, w) + { + /** + * The x component of this Vector. + * + * @name Phaser.Math.Vector4#x + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The y component of this Vector. + * + * @name Phaser.Math.Vector4#y + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The z component of this Vector. + * + * @name Phaser.Math.Vector4#z + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.z = 0; + + /** + * The w component of this Vector. + * + * @name Phaser.Math.Vector4#w + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.w = 0; + + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + }, + + /** + * Make a clone of this Vector4. + * + * @method Phaser.Math.Vector4#clone + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} A clone of this Vector4. + */ + clone: function () + { + return new Vector4(this.x, this.y, this.z, this.w); + }, + + /** + * Copy the components of a given Vector into this Vector. + * + * @method Phaser.Math.Vector4#copy + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} src - The Vector to copy the components from. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + copy: function (src) + { + this.x = src.x; + this.y = src.y; + this.z = src.z || 0; + this.w = src.w || 0; + + return this; + }, + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict quality check against each Vector's components. + * + * @method Phaser.Math.Vector4#equals + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} v - The vector to check equality with. + * + * @return {boolean} A boolean indicating whether the two Vectors are equal or not. + */ + equals: function (v) + { + return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z) && (this.w === v.w)); + }, + + /** + * Set the `x`, `y`, `z` and `w` components of the this Vector to the given `x`, `y`, `z` and `w` values. + * + * @method Phaser.Math.Vector4#set + * @since 3.0.0 + * + * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y, z and w components. + * @param {number} y - The y value to set for this Vector. + * @param {number} z - The z value to set for this Vector. + * @param {number} w - The z value to set for this Vector. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + set: function (x, y, z, w) + { + if (typeof x === 'object') + { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + this.w = x.w || 0; + } + else + { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + + return this; + }, + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * + * @method Phaser.Math.Vector4#add + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to add to this Vector. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + add: function (v) + { + this.x += v.x; + this.y += v.y; + this.z += v.z || 0; + this.w += v.w || 0; + + return this; + }, + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * + * @method Phaser.Math.Vector4#subtract + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to subtract from this Vector. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + subtract: function (v) + { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z || 0; + this.w -= v.w || 0; + + return this; + }, + + /** + * Scale this Vector by the given value. + * + * @method Phaser.Math.Vector4#scale + * @since 3.0.0 + * + * @param {number} scale - The value to scale this Vector by. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + scale: function (scale) + { + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + + return this; + }, + + /** + * Calculate the length (or magnitude) of this Vector. + * + * @method Phaser.Math.Vector4#length + * @since 3.0.0 + * + * @return {number} The length of this Vector. + */ + length: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return Math.sqrt(x * x + y * y + z * z + w * w); + }, + + /** + * Calculate the length of this Vector squared. + * + * @method Phaser.Math.Vector4#lengthSq + * @since 3.0.0 + * + * @return {number} The length of this Vector, squared. + */ + lengthSq: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + + return x * x + y * y + z * z + w * w; + }, + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + * + * @method Phaser.Math.Vector4#normalize + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + normalize: function () + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) + { + len = 1 / Math.sqrt(len); + + this.x = x * len; + this.y = y * len; + this.z = z * len; + this.w = w * len; + } + + return this; + }, + + /** + * Calculate the dot product of this Vector and the given Vector. + * + * @method Phaser.Math.Vector4#dot + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} v - The Vector4 to dot product with this Vector4. + * + * @return {number} The dot product of this Vector and the given Vector. + */ + dot: function (v) + { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + }, + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * + * @method Phaser.Math.Vector4#lerp + * @since 3.0.0 + * + * @param {Phaser.Math.Vector4} v - The Vector4 to interpolate towards. + * @param {number} [t=0] - The interpolation percentage, between 0 and 1. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + lerp: function (v, t) + { + if (t === undefined) { t = 0; } + + var ax = this.x; + var ay = this.y; + var az = this.z; + var aw = this.w; + + this.x = ax + t * (v.x - ax); + this.y = ay + t * (v.y - ay); + this.z = az + t * (v.z - az); + this.w = aw + t * (v.w - aw); + + return this; + }, + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * + * @method Phaser.Math.Vector4#multiply + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to multiply this Vector by. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + multiply: function (v) + { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z || 1; + this.w *= v.w || 1; + + return this; + }, + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * + * @method Phaser.Math.Vector4#divide + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to divide this Vector by. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + divide: function (v) + { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z || 1; + this.w /= v.w || 1; + + return this; + }, + + /** + * Calculate the distance between this Vector and the given Vector. + * + * @method Phaser.Math.Vector4#distance + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector. + */ + distance: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + var dw = v.w - this.w || 0; + + return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); + }, + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * + * @method Phaser.Math.Vector4#distanceSq + * @since 3.0.0 + * + * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. + * + * @return {number} The distance from this Vector to the given Vector, squared. + */ + distanceSq: function (v) + { + var dx = v.x - this.x; + var dy = v.y - this.y; + var dz = v.z - this.z || 0; + var dw = v.w - this.w || 0; + + return dx * dx + dy * dy + dz * dz + dw * dw; + }, + + /** + * Negate the `x`, `y`, `z` and `w` components of this Vector. + * + * @method Phaser.Math.Vector4#negate + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + negate: function () + { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + + return this; + }, + + /** + * Transform this Vector with the given Matrix. + * + * @method Phaser.Math.Vector4#transformMat4 + * @since 3.0.0 + * + * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector4 with. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + transformMat4: function (mat) + { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; + var m = mat.val; + + this.x = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + this.y = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + this.z = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + this.w = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + + return this; + }, + + /** + * Transform this Vector with the given Quaternion. + * + * @method Phaser.Math.Vector4#transformQuat + * @since 3.0.0 + * + * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + transformQuat: function (q) + { + // TODO: is this really the same as Vector3? + // Also, what about this: http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + var x = this.x; + var y = this.y; + var z = this.z; + var qx = q.x; + var qy = q.y; + var qz = q.z; + var qw = q.w; + + // calculate quat * vec + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + + return this; + }, + + /** + * Make this Vector the zero vector (0, 0, 0, 0). + * + * @method Phaser.Math.Vector4#reset + * @since 3.0.0 + * + * @return {Phaser.Math.Vector4} This Vector4. + */ + reset: function () + { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + + return this; + } + +}); + +// TODO: Check if these are required internally, if not, remove. +Vector4.prototype.sub = Vector4.prototype.subtract; +Vector4.prototype.mul = Vector4.prototype.multiply; +Vector4.prototype.div = Vector4.prototype.divide; +Vector4.prototype.dist = Vector4.prototype.distance; +Vector4.prototype.distSq = Vector4.prototype.distanceSq; +Vector4.prototype.len = Vector4.prototype.length; +Vector4.prototype.lenSq = Vector4.prototype.lengthSq; + +module.exports = Vector4; diff --git a/src/math/Within.js b/src/math/Within.js index 00d8fa959..6276bbb7a 100644 --- a/src/math/Within.js +++ b/src/math/Within.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if the two values are within the given `tolerance` of each other. - * - * @function Phaser.Math.Within - * @since 3.0.0 - * - * @param {number} a - The first value to use in the calculation. - * @param {number} b - The second value to use in the calculation. - * @param {number} tolerance - The tolerance. Anything equal to or less than this value is considered as being within range. - * - * @return {boolean} Returns `true` if `a` is less than or equal to the tolerance of `b`. - */ -var Within = function (a, b, tolerance) -{ - return (Math.abs(a - b) <= tolerance); -}; - -module.exports = Within; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the two values are within the given `tolerance` of each other. + * + * @function Phaser.Math.Within + * @since 3.0.0 + * + * @param {number} a - The first value to use in the calculation. + * @param {number} b - The second value to use in the calculation. + * @param {number} tolerance - The tolerance. Anything equal to or less than this value is considered as being within range. + * + * @return {boolean} Returns `true` if `a` is less than or equal to the tolerance of `b`. + */ +var Within = function (a, b, tolerance) +{ + return (Math.abs(a - b) <= tolerance); +}; + +module.exports = Within; diff --git a/src/math/Wrap.js b/src/math/Wrap.js index 7bf6a2d8d..cdf37168c 100644 --- a/src/math/Wrap.js +++ b/src/math/Wrap.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Wrap the given `value` between `min` and `max. - * - * @function Phaser.Math.Wrap - * @since 3.0.0 - * - * @param {number} value - The value to wrap. - * @param {number} min - The minimum value. - * @param {number} max - The maximum value. - * - * @return {number} The wrapped value. - */ -var Wrap = function (value, min, max) -{ - var range = max - min; - - return (min + ((((value - min) % range) + range) % range)); -}; - -module.exports = Wrap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Wrap the given `value` between `min` and `max. + * + * @function Phaser.Math.Wrap + * @since 3.0.0 + * + * @param {number} value - The value to wrap. + * @param {number} min - The minimum value. + * @param {number} max - The maximum value. + * + * @return {number} The wrapped value. + */ +var Wrap = function (value, min, max) +{ + var range = max - min; + + return (min + ((((value - min) % range) + range) % range)); +}; + +module.exports = Wrap; diff --git a/src/math/angle/Between.js b/src/math/angle/Between.js index e8d8f8cd0..51678abe8 100644 --- a/src/math/angle/Between.js +++ b/src/math/angle/Between.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Find the angle of a segment from (x1, y1) -> (x2, y2). - * - * @function Phaser.Math.Angle.Between - * @since 3.0.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * - * @return {number} The angle in radians. - */ -var Between = function (x1, y1, x2, y2) -{ - return Math.atan2(y2 - y1, x2 - x1); -}; - -module.exports = Between; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @function Phaser.Math.Angle.Between + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The angle in radians. + */ +var Between = function (x1, y1, x2, y2) +{ + return Math.atan2(y2 - y1, x2 - x1); +}; + +module.exports = Between; diff --git a/src/math/angle/BetweenPoints.js b/src/math/angle/BetweenPoints.js index 574d8740a..f3150e307 100644 --- a/src/math/angle/BetweenPoints.js +++ b/src/math/angle/BetweenPoints.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). - * - * Calculates the angle of the vector from the first point to the second point. - * - * @function Phaser.Math.Angle.BetweenPoints - * @since 3.0.0 - * - * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. - * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. - * - * @return {number} The angle in radians. - */ -var BetweenPoints = function (point1, point2) -{ - return Math.atan2(point2.y - point1.y, point2.x - point1.x); -}; - -module.exports = BetweenPoints; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * Calculates the angle of the vector from the first point to the second point. + * + * @function Phaser.Math.Angle.BetweenPoints + * @since 3.0.0 + * + * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. + * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. + * + * @return {number} The angle in radians. + */ +var BetweenPoints = function (point1, point2) +{ + return Math.atan2(point2.y - point1.y, point2.x - point1.x); +}; + +module.exports = BetweenPoints; diff --git a/src/math/angle/BetweenPointsY.js b/src/math/angle/BetweenPointsY.js index a48b9b055..480c05724 100644 --- a/src/math/angle/BetweenPointsY.js +++ b/src/math/angle/BetweenPointsY.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). - * - * The difference between this method and {@link Phaser.Math.Angle.BetweenPoints} is that this assumes the y coordinate - * travels down the screen. - * - * @function Phaser.Math.Angle.BetweenPointsY - * @since 3.0.0 - * - * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. - * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. - * - * @return {number} The angle in radians. - */ -var BetweenPointsY = function (point1, point2) -{ - return Math.atan2(point2.x - point1.x, point2.y - point1.y); -}; - -module.exports = BetweenPointsY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * The difference between this method and {@link Phaser.Math.Angle.BetweenPoints} is that this assumes the y coordinate + * travels down the screen. + * + * @function Phaser.Math.Angle.BetweenPointsY + * @since 3.0.0 + * + * @param {Phaser.Types.Math.Vector2Like} point1 - The first point. + * @param {Phaser.Types.Math.Vector2Like} point2 - The second point. + * + * @return {number} The angle in radians. + */ +var BetweenPointsY = function (point1, point2) +{ + return Math.atan2(point2.x - point1.x, point2.y - point1.y); +}; + +module.exports = BetweenPointsY; diff --git a/src/math/angle/BetweenY.js b/src/math/angle/BetweenY.js index 997c632fb..65f1ab44e 100644 --- a/src/math/angle/BetweenY.js +++ b/src/math/angle/BetweenY.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Find the angle of a segment from (x1, y1) -> (x2, y2). - * - * The difference between this method and {@link Phaser.Math.Angle.Between} is that this assumes the y coordinate - * travels down the screen. - * - * @function Phaser.Math.Angle.BetweenY - * @since 3.0.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * - * @return {number} The angle in radians. - */ -var BetweenY = function (x1, y1, x2, y2) -{ - return Math.atan2(x2 - x1, y2 - y1); -}; - -module.exports = BetweenY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and {@link Phaser.Math.Angle.Between} is that this assumes the y coordinate + * travels down the screen. + * + * @function Phaser.Math.Angle.BetweenY + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The angle in radians. + */ +var BetweenY = function (x1, y1, x2, y2) +{ + return Math.atan2(x2 - x1, y2 - y1); +}; + +module.exports = BetweenY; diff --git a/src/math/angle/CounterClockwise.js b/src/math/angle/CounterClockwise.js index 3d20c3ad3..301d740fa 100644 --- a/src/math/angle/CounterClockwise.js +++ b/src/math/angle/CounterClockwise.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../const'); - -/** - * Takes an angle in Phasers default clockwise format and converts it so that - * 0 is North, 90 is West, 180 is South and 270 is East, - * therefore running counter-clockwise instead of clockwise. - * - * You can pass in the angle from a Game Object using: - * - * ```javascript - * var converted = CounterClockwise(gameobject.rotation); - * ``` - * - * All values for this function are in radians. - * - * @function Phaser.Math.Angle.CounterClockwise - * @since 3.16.0 - * - * @param {number} angle - The angle to convert, in radians. - * - * @return {number} The converted angle, in radians. - */ -var CounterClockwise = function (angle) -{ - if (angle > Math.PI) - { - angle -= CONST.PI2; - } - - return Math.abs((((angle + CONST.TAU) % CONST.PI2) - CONST.PI2) % CONST.PI2); -}; - -module.exports = CounterClockwise; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../const'); + +/** + * Takes an angle in Phasers default clockwise format and converts it so that + * 0 is North, 90 is West, 180 is South and 270 is East, + * therefore running counter-clockwise instead of clockwise. + * + * You can pass in the angle from a Game Object using: + * + * ```javascript + * var converted = CounterClockwise(gameobject.rotation); + * ``` + * + * All values for this function are in radians. + * + * @function Phaser.Math.Angle.CounterClockwise + * @since 3.16.0 + * + * @param {number} angle - The angle to convert, in radians. + * + * @return {number} The converted angle, in radians. + */ +var CounterClockwise = function (angle) +{ + if (angle > Math.PI) + { + angle -= CONST.PI2; + } + + return Math.abs((((angle + CONST.TAU) % CONST.PI2) - CONST.PI2) % CONST.PI2); +}; + +module.exports = CounterClockwise; diff --git a/src/math/angle/Normalize.js b/src/math/angle/Normalize.js index 495243f2e..47d6ea41d 100644 --- a/src/math/angle/Normalize.js +++ b/src/math/angle/Normalize.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Normalize an angle to the [0, 2pi] range. - * - * @function Phaser.Math.Angle.Normalize - * @since 3.0.0 - * - * @param {number} angle - The angle to normalize, in radians. - * - * @return {number} The normalized angle, in radians. - */ -var Normalize = function (angle) -{ - angle = angle % (2 * Math.PI); - - if (angle >= 0) - { - return angle; - } - else - { - return angle + 2 * Math.PI; - } -}; - -module.exports = Normalize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Normalize an angle to the [0, 2pi] range. + * + * @function Phaser.Math.Angle.Normalize + * @since 3.0.0 + * + * @param {number} angle - The angle to normalize, in radians. + * + * @return {number} The normalized angle, in radians. + */ +var Normalize = function (angle) +{ + angle = angle % (2 * Math.PI); + + if (angle >= 0) + { + return angle; + } + else + { + return angle + 2 * Math.PI; + } +}; + +module.exports = Normalize; diff --git a/src/math/angle/Reverse.js b/src/math/angle/Reverse.js index 6d0aa73e9..730413ef6 100644 --- a/src/math/angle/Reverse.js +++ b/src/math/angle/Reverse.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Normalize = require('./Normalize'); - -/** - * Reverse the given angle. - * - * @function Phaser.Math.Angle.Reverse - * @since 3.0.0 - * - * @param {number} angle - The angle to reverse, in radians. - * - * @return {number} The reversed angle, in radians. - */ -var Reverse = function (angle) -{ - return Normalize(angle + Math.PI); -}; - -module.exports = Reverse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Normalize = require('./Normalize'); + +/** + * Reverse the given angle. + * + * @function Phaser.Math.Angle.Reverse + * @since 3.0.0 + * + * @param {number} angle - The angle to reverse, in radians. + * + * @return {number} The reversed angle, in radians. + */ +var Reverse = function (angle) +{ + return Normalize(angle + Math.PI); +}; + +module.exports = Reverse; diff --git a/src/math/angle/RotateTo.js b/src/math/angle/RotateTo.js index 43f5aaf0e..a893d9e1e 100644 --- a/src/math/angle/RotateTo.js +++ b/src/math/angle/RotateTo.js @@ -1,61 +1,61 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = require('../const'); - -/** - * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. - * - * @function Phaser.Math.Angle.RotateTo - * @since 3.0.0 - * - * @param {number} currentAngle - The current angle, in radians. - * @param {number} targetAngle - The target angle to rotate to, in radians. - * @param {number} [lerp=0.05] - The lerp value to add to the current angle. - * - * @return {number} The adjusted angle. - */ -var RotateTo = function (currentAngle, targetAngle, lerp) -{ - if (lerp === undefined) { lerp = 0.05; } - - if (currentAngle === targetAngle) - { - return currentAngle; - } - - if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (MATH_CONST.PI2 - lerp)) - { - currentAngle = targetAngle; - } - else - { - if (Math.abs(targetAngle - currentAngle) > Math.PI) - { - if (targetAngle < currentAngle) - { - targetAngle += MATH_CONST.PI2; - } - else - { - targetAngle -= MATH_CONST.PI2; - } - } - - if (targetAngle > currentAngle) - { - currentAngle += lerp; - } - else if (targetAngle < currentAngle) - { - currentAngle -= lerp; - } - } - - return currentAngle; -}; - -module.exports = RotateTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = require('../const'); + +/** + * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. + * + * @function Phaser.Math.Angle.RotateTo + * @since 3.0.0 + * + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * + * @return {number} The adjusted angle. + */ +var RotateTo = function (currentAngle, targetAngle, lerp) +{ + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (MATH_CONST.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += MATH_CONST.PI2; + } + else + { + targetAngle -= MATH_CONST.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; +}; + +module.exports = RotateTo; diff --git a/src/math/angle/ShortestBetween.js b/src/math/angle/ShortestBetween.js index 78f14e62e..fa91c9a94 100644 --- a/src/math/angle/ShortestBetween.js +++ b/src/math/angle/ShortestBetween.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Gets the shortest angle between `angle1` and `angle2`. - * - * Both angles must be in the range -180 to 180, which is the same clamped - * range that `sprite.angle` uses, so you can pass in two sprite angles to - * this method and get the shortest angle back between the two of them. - * - * The angle returned will be in the same range. If the returned angle is - * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's - * a clockwise rotation. - * - * TODO: Wrap the angles in this function? - * - * @function Phaser.Math.Angle.ShortestBetween - * @since 3.0.0 - * - * @param {number} angle1 - The first angle in the range -180 to 180. - * @param {number} angle2 - The second angle in the range -180 to 180. - * - * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. - */ -var ShortestBetween = function (angle1, angle2) -{ - var difference = angle2 - angle1; - - if (difference === 0) - { - return 0; - } - - var times = Math.floor((difference - (-180)) / 360); - - return difference - (times * 360); - -}; - -module.exports = ShortestBetween; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Gets the shortest angle between `angle1` and `angle2`. + * + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * TODO: Wrap the angles in this function? + * + * @function Phaser.Math.Angle.ShortestBetween + * @since 3.0.0 + * + * @param {number} angle1 - The first angle in the range -180 to 180. + * @param {number} angle2 - The second angle in the range -180 to 180. + * + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ +var ShortestBetween = function (angle1, angle2) +{ + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + +}; + +module.exports = ShortestBetween; diff --git a/src/math/angle/Wrap.js b/src/math/angle/Wrap.js index c4accbcb6..37202df18 100644 --- a/src/math/angle/Wrap.js +++ b/src/math/angle/Wrap.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MathWrap = require('../Wrap'); - -/** - * Wrap an angle. - * - * Wraps the angle to a value in the range of -PI to PI. - * - * @function Phaser.Math.Angle.Wrap - * @since 3.0.0 - * - * @param {number} angle - The angle to wrap, in radians. - * - * @return {number} The wrapped angle, in radians. - */ -var Wrap = function (angle) -{ - return MathWrap(angle, -Math.PI, Math.PI); -}; - -module.exports = Wrap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MathWrap = require('../Wrap'); + +/** + * Wrap an angle. + * + * Wraps the angle to a value in the range of -PI to PI. + * + * @function Phaser.Math.Angle.Wrap + * @since 3.0.0 + * + * @param {number} angle - The angle to wrap, in radians. + * + * @return {number} The wrapped angle, in radians. + */ +var Wrap = function (angle) +{ + return MathWrap(angle, -Math.PI, Math.PI); +}; + +module.exports = Wrap; diff --git a/src/math/angle/WrapDegrees.js b/src/math/angle/WrapDegrees.js index 3e5784914..f0427745e 100644 --- a/src/math/angle/WrapDegrees.js +++ b/src/math/angle/WrapDegrees.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Wrap = require('../Wrap'); - -/** - * Wrap an angle in degrees. - * - * Wraps the angle to a value in the range of -180 to 180. - * - * @function Phaser.Math.Angle.WrapDegrees - * @since 3.0.0 - * - * @param {number} angle - The angle to wrap, in degrees. - * - * @return {number} The wrapped angle, in degrees. - */ -var WrapDegrees = function (angle) -{ - return Wrap(angle, -180, 180); -}; - -module.exports = WrapDegrees; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Wrap = require('../Wrap'); + +/** + * Wrap an angle in degrees. + * + * Wraps the angle to a value in the range of -180 to 180. + * + * @function Phaser.Math.Angle.WrapDegrees + * @since 3.0.0 + * + * @param {number} angle - The angle to wrap, in degrees. + * + * @return {number} The wrapped angle, in degrees. + */ +var WrapDegrees = function (angle) +{ + return Wrap(angle, -180, 180); +}; + +module.exports = WrapDegrees; diff --git a/src/math/angle/index.js b/src/math/angle/index.js index 5ff8d9e53..fc22fcaa1 100644 --- a/src/math/angle/index.js +++ b/src/math/angle/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Angle - */ - -module.exports = { - - Between: require('./Between'), - BetweenPoints: require('./BetweenPoints'), - BetweenPointsY: require('./BetweenPointsY'), - BetweenY: require('./BetweenY'), - CounterClockwise: require('./CounterClockwise'), - Normalize: require('./Normalize'), - Reverse: require('./Reverse'), - RotateTo: require('./RotateTo'), - ShortestBetween: require('./ShortestBetween'), - Wrap: require('./Wrap'), - WrapDegrees: require('./WrapDegrees') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Angle + */ + +module.exports = { + + Between: require('./Between'), + BetweenPoints: require('./BetweenPoints'), + BetweenPointsY: require('./BetweenPointsY'), + BetweenY: require('./BetweenY'), + CounterClockwise: require('./CounterClockwise'), + Normalize: require('./Normalize'), + Reverse: require('./Reverse'), + RotateTo: require('./RotateTo'), + ShortestBetween: require('./ShortestBetween'), + Wrap: require('./Wrap'), + WrapDegrees: require('./WrapDegrees') + +}; diff --git a/src/math/const.js b/src/math/const.js index e1824cdef..e1428f8df 100644 --- a/src/math/const.js +++ b/src/math/const.js @@ -1,86 +1,86 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH_CONST = { - - /** - * The value of PI * 2. - * - * @name Phaser.Math.PI2 - * @type {number} - * @since 3.0.0 - */ - PI2: Math.PI * 2, - - /** - * The value of PI * 0.5. - * - * @name Phaser.Math.TAU - * @type {number} - * @since 3.0.0 - */ - TAU: Math.PI * 0.5, - - /** - * An epsilon value (1.0e-6) - * - * @name Phaser.Math.EPSILON - * @type {number} - * @since 3.0.0 - */ - EPSILON: 1.0e-6, - - /** - * For converting degrees to radians (PI / 180) - * - * @name Phaser.Math.DEG_TO_RAD - * @type {number} - * @since 3.0.0 - */ - DEG_TO_RAD: Math.PI / 180, - - /** - * For converting radians to degrees (180 / PI) - * - * @name Phaser.Math.RAD_TO_DEG - * @type {number} - * @since 3.0.0 - */ - RAD_TO_DEG: 180 / Math.PI, - - /** - * An instance of the Random Number Generator. - * This is not set until the Game boots. - * - * @name Phaser.Math.RND - * @type {Phaser.Math.RandomDataGenerator} - * @since 3.0.0 - */ - RND: null, - - /** - * The minimum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - * - * @name Phaser.Math.MIN_SAFE_INTEGER - * @type {number} - * @since 3.21.0 - */ - MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, - - /** - * The maximum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - * - * @name Phaser.Math.MAX_SAFE_INTEGER - * @type {number} - * @since 3.21.0 - */ - MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 - -}; - -module.exports = MATH_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH_CONST = { + + /** + * The value of PI * 2. + * + * @name Phaser.Math.PI2 + * @type {number} + * @since 3.0.0 + */ + PI2: Math.PI * 2, + + /** + * The value of PI * 0.5. + * + * @name Phaser.Math.TAU + * @type {number} + * @since 3.0.0 + */ + TAU: Math.PI * 0.5, + + /** + * An epsilon value (1.0e-6) + * + * @name Phaser.Math.EPSILON + * @type {number} + * @since 3.0.0 + */ + EPSILON: 1.0e-6, + + /** + * For converting degrees to radians (PI / 180) + * + * @name Phaser.Math.DEG_TO_RAD + * @type {number} + * @since 3.0.0 + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * For converting radians to degrees (180 / PI) + * + * @name Phaser.Math.RAD_TO_DEG + * @type {number} + * @since 3.0.0 + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * An instance of the Random Number Generator. + * This is not set until the Game boots. + * + * @name Phaser.Math.RND + * @type {Phaser.Math.RandomDataGenerator} + * @since 3.0.0 + */ + RND: null, + + /** + * The minimum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MIN_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER || -9007199254740991, + + /** + * The maximum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + * + * @name Phaser.Math.MAX_SAFE_INTEGER + * @type {number} + * @since 3.21.0 + */ + MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER || 9007199254740991 + +}; + +module.exports = MATH_CONST; diff --git a/src/math/distance/DistanceBetween.js b/src/math/distance/DistanceBetween.js index a82ea25b5..b6b24a58d 100644 --- a/src/math/distance/DistanceBetween.js +++ b/src/math/distance/DistanceBetween.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the distance between two sets of coordinates (points). - * - * @function Phaser.Math.Distance.Between - * @since 3.0.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * - * @return {number} The distance between each point. - */ -var DistanceBetween = function (x1, y1, x2, y2) -{ - var dx = x1 - x2; - var dy = y1 - y2; - - return Math.sqrt(dx * dx + dy * dy); -}; - -module.exports = DistanceBetween; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two sets of coordinates (points). + * + * @function Phaser.Math.Distance.Between + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point. + */ +var DistanceBetween = function (x1, y1, x2, y2) +{ + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); +}; + +module.exports = DistanceBetween; diff --git a/src/math/distance/DistanceBetweenPoints.js b/src/math/distance/DistanceBetweenPoints.js index 93fe82d37..5741a0df1 100644 --- a/src/math/distance/DistanceBetweenPoints.js +++ b/src/math/distance/DistanceBetweenPoints.js @@ -1,26 +1,26 @@ -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the distance between two points. - * - * @function Phaser.Math.Distance.BetweenPoints - * @since 3.22.0 - * - * @param {Phaser.Types.Math.Vector2Like} a - The first point. - * @param {Phaser.Types.Math.Vector2Like} b - The second point. - * - * @return {number} The distance between the points. - */ -var DistanceBetweenPoints = function (a, b) -{ - var dx = a.x - b.x; - var dy = a.y - b.y; - - return Math.sqrt(dx * dx + dy * dy); -}; - -module.exports = DistanceBetweenPoints; +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two points. + * + * @function Phaser.Math.Distance.BetweenPoints + * @since 3.22.0 + * + * @param {Phaser.Types.Math.Vector2Like} a - The first point. + * @param {Phaser.Types.Math.Vector2Like} b - The second point. + * + * @return {number} The distance between the points. + */ +var DistanceBetweenPoints = function (a, b) +{ + var dx = a.x - b.x; + var dy = a.y - b.y; + + return Math.sqrt(dx * dx + dy * dy); +}; + +module.exports = DistanceBetweenPoints; diff --git a/src/math/distance/DistanceBetweenPointsSquared.js b/src/math/distance/DistanceBetweenPointsSquared.js index bea07156f..5d20c9a4e 100644 --- a/src/math/distance/DistanceBetweenPointsSquared.js +++ b/src/math/distance/DistanceBetweenPointsSquared.js @@ -1,26 +1,26 @@ -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the squared distance between two points. - * - * @function Phaser.Math.Distance.BetweenPointsSquared - * @since 3.22.0 - * - * @param {Phaser.Types.Math.Vector2Like} a - The first point. - * @param {Phaser.Types.Math.Vector2Like} b - The second point. - * - * @return {number} The squared distance between the points. - */ -var DistanceBetweenPointsSquared = function (a, b) -{ - var dx = a.x - b.x; - var dy = a.y - b.y; - - return dx * dx + dy * dy; -}; - -module.exports = DistanceBetweenPointsSquared; +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the squared distance between two points. + * + * @function Phaser.Math.Distance.BetweenPointsSquared + * @since 3.22.0 + * + * @param {Phaser.Types.Math.Vector2Like} a - The first point. + * @param {Phaser.Types.Math.Vector2Like} b - The second point. + * + * @return {number} The squared distance between the points. + */ +var DistanceBetweenPointsSquared = function (a, b) +{ + var dx = a.x - b.x; + var dy = a.y - b.y; + + return dx * dx + dy * dy; +}; + +module.exports = DistanceBetweenPointsSquared; diff --git a/src/math/distance/DistanceChebyshev.js b/src/math/distance/DistanceChebyshev.js index 6952fb4f4..4e8b51350 100644 --- a/src/math/distance/DistanceChebyshev.js +++ b/src/math/distance/DistanceChebyshev.js @@ -1,28 +1,28 @@ -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the Chebyshev distance between two sets of coordinates (points). - * - * Chebyshev distance (or chessboard distance) is the maximum of the horizontal and vertical distances. - * It's the effective distance when movement can be horizontal, vertical, or diagonal. - * - * @function Phaser.Math.Distance.Chebyshev - * @since 3.22.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * - * @return {number} The distance between each point. - */ -var ChebyshevDistance = function (x1, y1, x2, y2) -{ - return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); -}; - -module.exports = ChebyshevDistance; +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the Chebyshev distance between two sets of coordinates (points). + * + * Chebyshev distance (or chessboard distance) is the maximum of the horizontal and vertical distances. + * It's the effective distance when movement can be horizontal, vertical, or diagonal. + * + * @function Phaser.Math.Distance.Chebyshev + * @since 3.22.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point. + */ +var ChebyshevDistance = function (x1, y1, x2, y2) +{ + return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); +}; + +module.exports = ChebyshevDistance; diff --git a/src/math/distance/DistancePower.js b/src/math/distance/DistancePower.js index 892497aac..3db38865e 100644 --- a/src/math/distance/DistancePower.js +++ b/src/math/distance/DistancePower.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the distance between two sets of coordinates (points) to the power of `pow`. - * - * @function Phaser.Math.Distance.Power - * @since 3.0.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * @param {number} pow - The exponent. - * - * @return {number} The distance between each point. - */ -var DistancePower = function (x1, y1, x2, y2, pow) -{ - if (pow === undefined) { pow = 2; } - - return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); -}; - -module.exports = DistancePower; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two sets of coordinates (points) to the power of `pow`. + * + * @function Phaser.Math.Distance.Power + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * @param {number} pow - The exponent. + * + * @return {number} The distance between each point. + */ +var DistancePower = function (x1, y1, x2, y2, pow) +{ + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); +}; + +module.exports = DistancePower; diff --git a/src/math/distance/DistanceSnake.js b/src/math/distance/DistanceSnake.js index b5235174e..ec3cfc99d 100644 --- a/src/math/distance/DistanceSnake.js +++ b/src/math/distance/DistanceSnake.js @@ -1,28 +1,28 @@ -/** - * @author samme - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the snake distance between two sets of coordinates (points). - * - * Snake distance (rectilinear distance, Manhattan distance) is the sum of the horizontal and vertical distances. - * It's the effective distance when movement is allowed only horizontally or vertically (but not both). - * - * @function Phaser.Math.Distance.Snake - * @since 3.22.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * - * @return {number} The distance between each point. - */ -var SnakeDistance = function (x1, y1, x2, y2) -{ - return Math.abs(x1 - x2) + Math.abs(y1 - y2); -}; - -module.exports = SnakeDistance; +/** + * @author samme + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the snake distance between two sets of coordinates (points). + * + * Snake distance (rectilinear distance, Manhattan distance) is the sum of the horizontal and vertical distances. + * It's the effective distance when movement is allowed only horizontally or vertically (but not both). + * + * @function Phaser.Math.Distance.Snake + * @since 3.22.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point. + */ +var SnakeDistance = function (x1, y1, x2, y2) +{ + return Math.abs(x1 - x2) + Math.abs(y1 - y2); +}; + +module.exports = SnakeDistance; diff --git a/src/math/distance/DistanceSquared.js b/src/math/distance/DistanceSquared.js index 28ff22733..e1d5af9e6 100644 --- a/src/math/distance/DistanceSquared.js +++ b/src/math/distance/DistanceSquared.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the distance between two sets of coordinates (points), squared. - * - * @function Phaser.Math.Distance.Squared - * @since 3.0.0 - * - * @param {number} x1 - The x coordinate of the first point. - * @param {number} y1 - The y coordinate of the first point. - * @param {number} x2 - The x coordinate of the second point. - * @param {number} y2 - The y coordinate of the second point. - * - * @return {number} The distance between each point, squared. - */ -var DistanceSquared = function (x1, y1, x2, y2) -{ - var dx = x1 - x2; - var dy = y1 - y2; - - return dx * dx + dy * dy; -}; - -module.exports = DistanceSquared; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the distance between two sets of coordinates (points), squared. + * + * @function Phaser.Math.Distance.Squared + * @since 3.0.0 + * + * @param {number} x1 - The x coordinate of the first point. + * @param {number} y1 - The y coordinate of the first point. + * @param {number} x2 - The x coordinate of the second point. + * @param {number} y2 - The y coordinate of the second point. + * + * @return {number} The distance between each point, squared. + */ +var DistanceSquared = function (x1, y1, x2, y2) +{ + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; +}; + +module.exports = DistanceSquared; diff --git a/src/math/distance/index.js b/src/math/distance/index.js index 432dc569d..6d415ee90 100644 --- a/src/math/distance/index.js +++ b/src/math/distance/index.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Distance - */ - -module.exports = { - - Between: require('./DistanceBetween'), - BetweenPoints: require('./DistanceBetweenPoints'), - BetweenPointsSquared: require('./DistanceBetweenPointsSquared'), - Chebyshev: require('./DistanceChebyshev'), - Power: require('./DistancePower'), - Snake: require('./DistanceSnake'), - Squared: require('./DistanceSquared') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Distance + */ + +module.exports = { + + Between: require('./DistanceBetween'), + BetweenPoints: require('./DistanceBetweenPoints'), + BetweenPointsSquared: require('./DistanceBetweenPointsSquared'), + Chebyshev: require('./DistanceChebyshev'), + Power: require('./DistancePower'), + Snake: require('./DistanceSnake'), + Squared: require('./DistanceSquared') + +}; diff --git a/src/math/easing/EaseMap.js b/src/math/easing/EaseMap.js index a7f742395..5ec1c30a3 100644 --- a/src/math/easing/EaseMap.js +++ b/src/math/easing/EaseMap.js @@ -1,75 +1,75 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Back = require('./back'); -var Bounce = require('./bounce'); -var Circular = require('./circular'); -var Cubic = require('./cubic'); -var Elastic = require('./elastic'); -var Expo = require('./expo'); -var Linear = require('./linear'); -var Quadratic = require('./quadratic'); -var Quartic = require('./quartic'); -var Quintic = require('./quintic'); -var Sine = require('./sine'); -var Stepped = require('./stepped'); - -// EaseMap -module.exports = { - - Power0: Linear, - Power1: Quadratic.Out, - Power2: Cubic.Out, - Power3: Quartic.Out, - Power4: Quintic.Out, - - Linear: Linear, - Quad: Quadratic.Out, - Cubic: Cubic.Out, - Quart: Quartic.Out, - Quint: Quintic.Out, - Sine: Sine.Out, - Expo: Expo.Out, - Circ: Circular.Out, - Elastic: Elastic.Out, - Back: Back.Out, - Bounce: Bounce.Out, - Stepped: Stepped, - - 'Quad.easeIn': Quadratic.In, - 'Cubic.easeIn': Cubic.In, - 'Quart.easeIn': Quartic.In, - 'Quint.easeIn': Quintic.In, - 'Sine.easeIn': Sine.In, - 'Expo.easeIn': Expo.In, - 'Circ.easeIn': Circular.In, - 'Elastic.easeIn': Elastic.In, - 'Back.easeIn': Back.In, - 'Bounce.easeIn': Bounce.In, - - 'Quad.easeOut': Quadratic.Out, - 'Cubic.easeOut': Cubic.Out, - 'Quart.easeOut': Quartic.Out, - 'Quint.easeOut': Quintic.Out, - 'Sine.easeOut': Sine.Out, - 'Expo.easeOut': Expo.Out, - 'Circ.easeOut': Circular.Out, - 'Elastic.easeOut': Elastic.Out, - 'Back.easeOut': Back.Out, - 'Bounce.easeOut': Bounce.Out, - - 'Quad.easeInOut': Quadratic.InOut, - 'Cubic.easeInOut': Cubic.InOut, - 'Quart.easeInOut': Quartic.InOut, - 'Quint.easeInOut': Quintic.InOut, - 'Sine.easeInOut': Sine.InOut, - 'Expo.easeInOut': Expo.InOut, - 'Circ.easeInOut': Circular.InOut, - 'Elastic.easeInOut': Elastic.InOut, - 'Back.easeInOut': Back.InOut, - 'Bounce.easeInOut': Bounce.InOut - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Back = require('./back'); +var Bounce = require('./bounce'); +var Circular = require('./circular'); +var Cubic = require('./cubic'); +var Elastic = require('./elastic'); +var Expo = require('./expo'); +var Linear = require('./linear'); +var Quadratic = require('./quadratic'); +var Quartic = require('./quartic'); +var Quintic = require('./quintic'); +var Sine = require('./sine'); +var Stepped = require('./stepped'); + +// EaseMap +module.exports = { + + Power0: Linear, + Power1: Quadratic.Out, + Power2: Cubic.Out, + Power3: Quartic.Out, + Power4: Quintic.Out, + + Linear: Linear, + Quad: Quadratic.Out, + Cubic: Cubic.Out, + Quart: Quartic.Out, + Quint: Quintic.Out, + Sine: Sine.Out, + Expo: Expo.Out, + Circ: Circular.Out, + Elastic: Elastic.Out, + Back: Back.Out, + Bounce: Bounce.Out, + Stepped: Stepped, + + 'Quad.easeIn': Quadratic.In, + 'Cubic.easeIn': Cubic.In, + 'Quart.easeIn': Quartic.In, + 'Quint.easeIn': Quintic.In, + 'Sine.easeIn': Sine.In, + 'Expo.easeIn': Expo.In, + 'Circ.easeIn': Circular.In, + 'Elastic.easeIn': Elastic.In, + 'Back.easeIn': Back.In, + 'Bounce.easeIn': Bounce.In, + + 'Quad.easeOut': Quadratic.Out, + 'Cubic.easeOut': Cubic.Out, + 'Quart.easeOut': Quartic.Out, + 'Quint.easeOut': Quintic.Out, + 'Sine.easeOut': Sine.Out, + 'Expo.easeOut': Expo.Out, + 'Circ.easeOut': Circular.Out, + 'Elastic.easeOut': Elastic.Out, + 'Back.easeOut': Back.Out, + 'Bounce.easeOut': Bounce.Out, + + 'Quad.easeInOut': Quadratic.InOut, + 'Cubic.easeInOut': Cubic.InOut, + 'Quart.easeInOut': Quartic.InOut, + 'Quint.easeInOut': Quintic.InOut, + 'Sine.easeInOut': Sine.InOut, + 'Expo.easeInOut': Expo.InOut, + 'Circ.easeInOut': Circular.InOut, + 'Elastic.easeInOut': Elastic.InOut, + 'Back.easeInOut': Back.InOut, + 'Bounce.easeInOut': Bounce.InOut + +}; diff --git a/src/math/easing/back/In.js b/src/math/easing/back/In.js index ed96041d7..372001446 100644 --- a/src/math/easing/back/In.js +++ b/src/math/easing/back/In.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Back ease-in. - * - * @function Phaser.Math.Easing.Back.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [overshoot=1.70158] - The overshoot amount. - * - * @return {number} The tweened value. - */ -var In = function (v, overshoot) -{ - if (overshoot === undefined) { overshoot = 1.70158; } - - return v * v * ((overshoot + 1) * v - overshoot); -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Back ease-in. + * + * @function Phaser.Math.Easing.Back.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [overshoot=1.70158] - The overshoot amount. + * + * @return {number} The tweened value. + */ +var In = function (v, overshoot) +{ + if (overshoot === undefined) { overshoot = 1.70158; } + + return v * v * ((overshoot + 1) * v - overshoot); +}; + +module.exports = In; diff --git a/src/math/easing/back/InOut.js b/src/math/easing/back/InOut.js index ccbdbc364..d47735b57 100644 --- a/src/math/easing/back/InOut.js +++ b/src/math/easing/back/InOut.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Back ease-in/out. - * - * @function Phaser.Math.Easing.Back.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [overshoot=1.70158] - The overshoot amount. - * - * @return {number} The tweened value. - */ -var InOut = function (v, overshoot) -{ - if (overshoot === undefined) { overshoot = 1.70158; } - - var s = overshoot * 1.525; - - if ((v *= 2) < 1) - { - return 0.5 * (v * v * ((s + 1) * v - s)); - } - else - { - return 0.5 * ((v -= 2) * v * ((s + 1) * v + s) + 2); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Back ease-in/out. + * + * @function Phaser.Math.Easing.Back.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [overshoot=1.70158] - The overshoot amount. + * + * @return {number} The tweened value. + */ +var InOut = function (v, overshoot) +{ + if (overshoot === undefined) { overshoot = 1.70158; } + + var s = overshoot * 1.525; + + if ((v *= 2) < 1) + { + return 0.5 * (v * v * ((s + 1) * v - s)); + } + else + { + return 0.5 * ((v -= 2) * v * ((s + 1) * v + s) + 2); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/back/Out.js b/src/math/easing/back/Out.js index e5cb02cff..2b8f788de 100644 --- a/src/math/easing/back/Out.js +++ b/src/math/easing/back/Out.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Back ease-out. - * - * @function Phaser.Math.Easing.Back.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [overshoot=1.70158] - The overshoot amount. - * - * @return {number} The tweened value. - */ -var Out = function (v, overshoot) -{ - if (overshoot === undefined) { overshoot = 1.70158; } - - return --v * v * ((overshoot + 1) * v + overshoot) + 1; -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Back ease-out. + * + * @function Phaser.Math.Easing.Back.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [overshoot=1.70158] - The overshoot amount. + * + * @return {number} The tweened value. + */ +var Out = function (v, overshoot) +{ + if (overshoot === undefined) { overshoot = 1.70158; } + + return --v * v * ((overshoot + 1) * v + overshoot) + 1; +}; + +module.exports = Out; diff --git a/src/math/easing/back/index.js b/src/math/easing/back/index.js index 1a743967d..c5a61c48d 100644 --- a/src/math/easing/back/index.js +++ b/src/math/easing/back/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Back - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Back + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/bounce/In.js b/src/math/easing/bounce/In.js index 7285451cf..218d91a4a 100644 --- a/src/math/easing/bounce/In.js +++ b/src/math/easing/bounce/In.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Bounce ease-in. - * - * @function Phaser.Math.Easing.Bounce.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - v = 1 - v; - - if (v < 1 / 2.75) - { - return 1 - (7.5625 * v * v); - } - else if (v < 2 / 2.75) - { - return 1 - (7.5625 * (v -= 1.5 / 2.75) * v + 0.75); - } - else if (v < 2.5 / 2.75) - { - return 1 - (7.5625 * (v -= 2.25 / 2.75) * v + 0.9375); - } - else - { - return 1 - (7.5625 * (v -= 2.625 / 2.75) * v + 0.984375); - } -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Bounce ease-in. + * + * @function Phaser.Math.Easing.Bounce.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + v = 1 - v; + + if (v < 1 / 2.75) + { + return 1 - (7.5625 * v * v); + } + else if (v < 2 / 2.75) + { + return 1 - (7.5625 * (v -= 1.5 / 2.75) * v + 0.75); + } + else if (v < 2.5 / 2.75) + { + return 1 - (7.5625 * (v -= 2.25 / 2.75) * v + 0.9375); + } + else + { + return 1 - (7.5625 * (v -= 2.625 / 2.75) * v + 0.984375); + } +}; + +module.exports = In; diff --git a/src/math/easing/bounce/InOut.js b/src/math/easing/bounce/InOut.js index eb995b160..be39a9aca 100644 --- a/src/math/easing/bounce/InOut.js +++ b/src/math/easing/bounce/InOut.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Bounce ease-in/out. - * - * @function Phaser.Math.Easing.Bounce.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - var reverse = false; - - if (v < 0.5) - { - v = 1 - (v * 2); - reverse = true; - } - else - { - v = (v * 2) - 1; - } - - if (v < 1 / 2.75) - { - v = 7.5625 * v * v; - } - else if (v < 2 / 2.75) - { - v = 7.5625 * (v -= 1.5 / 2.75) * v + 0.75; - } - else if (v < 2.5 / 2.75) - { - v = 7.5625 * (v -= 2.25 / 2.75) * v + 0.9375; - } - else - { - v = 7.5625 * (v -= 2.625 / 2.75) * v + 0.984375; - } - - if (reverse) - { - return (1 - v) * 0.5; - } - else - { - return v * 0.5 + 0.5; - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Bounce ease-in/out. + * + * @function Phaser.Math.Easing.Bounce.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + var reverse = false; + + if (v < 0.5) + { + v = 1 - (v * 2); + reverse = true; + } + else + { + v = (v * 2) - 1; + } + + if (v < 1 / 2.75) + { + v = 7.5625 * v * v; + } + else if (v < 2 / 2.75) + { + v = 7.5625 * (v -= 1.5 / 2.75) * v + 0.75; + } + else if (v < 2.5 / 2.75) + { + v = 7.5625 * (v -= 2.25 / 2.75) * v + 0.9375; + } + else + { + v = 7.5625 * (v -= 2.625 / 2.75) * v + 0.984375; + } + + if (reverse) + { + return (1 - v) * 0.5; + } + else + { + return v * 0.5 + 0.5; + } +}; + +module.exports = InOut; diff --git a/src/math/easing/bounce/Out.js b/src/math/easing/bounce/Out.js index 2b6fc9cbe..32f33eafc 100644 --- a/src/math/easing/bounce/Out.js +++ b/src/math/easing/bounce/Out.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Bounce ease-out. - * - * @function Phaser.Math.Easing.Bounce.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - if (v < 1 / 2.75) - { - return 7.5625 * v * v; - } - else if (v < 2 / 2.75) - { - return 7.5625 * (v -= 1.5 / 2.75) * v + 0.75; - } - else if (v < 2.5 / 2.75) - { - return 7.5625 * (v -= 2.25 / 2.75) * v + 0.9375; - } - else - { - return 7.5625 * (v -= 2.625 / 2.75) * v + 0.984375; - } -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Bounce ease-out. + * + * @function Phaser.Math.Easing.Bounce.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + if (v < 1 / 2.75) + { + return 7.5625 * v * v; + } + else if (v < 2 / 2.75) + { + return 7.5625 * (v -= 1.5 / 2.75) * v + 0.75; + } + else if (v < 2.5 / 2.75) + { + return 7.5625 * (v -= 2.25 / 2.75) * v + 0.9375; + } + else + { + return 7.5625 * (v -= 2.625 / 2.75) * v + 0.984375; + } +}; + +module.exports = Out; diff --git a/src/math/easing/bounce/index.js b/src/math/easing/bounce/index.js index 7df070ae3..b81b91fbe 100644 --- a/src/math/easing/bounce/index.js +++ b/src/math/easing/bounce/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Bounce - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Bounce + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/circular/In.js b/src/math/easing/circular/In.js index d3fab741a..3368f5505 100644 --- a/src/math/easing/circular/In.js +++ b/src/math/easing/circular/In.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Circular ease-in. - * - * @function Phaser.Math.Easing.Circular.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - return 1 - Math.sqrt(1 - v * v); -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Circular ease-in. + * + * @function Phaser.Math.Easing.Circular.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return 1 - Math.sqrt(1 - v * v); +}; + +module.exports = In; diff --git a/src/math/easing/circular/InOut.js b/src/math/easing/circular/InOut.js index 1db2492e7..7b4f0dfc6 100644 --- a/src/math/easing/circular/InOut.js +++ b/src/math/easing/circular/InOut.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Circular ease-in/out. - * - * @function Phaser.Math.Easing.Circular.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if ((v *= 2) < 1) - { - return -0.5 * (Math.sqrt(1 - v * v) - 1); - } - else - { - return 0.5 * (Math.sqrt(1 - (v -= 2) * v) + 1); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Circular ease-in/out. + * + * @function Phaser.Math.Easing.Circular.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return -0.5 * (Math.sqrt(1 - v * v) - 1); + } + else + { + return 0.5 * (Math.sqrt(1 - (v -= 2) * v) + 1); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/circular/Out.js b/src/math/easing/circular/Out.js index d95dedfe1..fead77874 100644 --- a/src/math/easing/circular/Out.js +++ b/src/math/easing/circular/Out.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Circular ease-out. - * - * @function Phaser.Math.Easing.Circular.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - return Math.sqrt(1 - (--v * v)); -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Circular ease-out. + * + * @function Phaser.Math.Easing.Circular.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return Math.sqrt(1 - (--v * v)); +}; + +module.exports = Out; diff --git a/src/math/easing/circular/index.js b/src/math/easing/circular/index.js index d7bbc72f6..e721cfec4 100644 --- a/src/math/easing/circular/index.js +++ b/src/math/easing/circular/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Circular - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Circular + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/cubic/In.js b/src/math/easing/cubic/In.js index ebefde8c2..f3f9b3f9a 100644 --- a/src/math/easing/cubic/In.js +++ b/src/math/easing/cubic/In.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Cubic ease-in. - * - * @function Phaser.Math.Easing.Cubic.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - return v * v * v; -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Cubic ease-in. + * + * @function Phaser.Math.Easing.Cubic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v * v; +}; + +module.exports = In; diff --git a/src/math/easing/cubic/InOut.js b/src/math/easing/cubic/InOut.js index 85ccf3de0..f502ca7b7 100644 --- a/src/math/easing/cubic/InOut.js +++ b/src/math/easing/cubic/InOut.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Cubic ease-in/out. - * - * @function Phaser.Math.Easing.Cubic.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if ((v *= 2) < 1) - { - return 0.5 * v * v * v; - } - else - { - return 0.5 * ((v -= 2) * v * v + 2); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Cubic ease-in/out. + * + * @function Phaser.Math.Easing.Cubic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v * v; + } + else + { + return 0.5 * ((v -= 2) * v * v + 2); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/cubic/Out.js b/src/math/easing/cubic/Out.js index 621e100e5..8d8cdab96 100644 --- a/src/math/easing/cubic/Out.js +++ b/src/math/easing/cubic/Out.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Cubic ease-out. - * - * @function Phaser.Math.Easing.Cubic.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - return --v * v * v + 1; -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Cubic ease-out. + * + * @function Phaser.Math.Easing.Cubic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return --v * v * v + 1; +}; + +module.exports = Out; diff --git a/src/math/easing/cubic/index.js b/src/math/easing/cubic/index.js index 441b7fe46..637aa3e12 100644 --- a/src/math/easing/cubic/index.js +++ b/src/math/easing/cubic/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Cubic - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Cubic + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/elastic/In.js b/src/math/easing/elastic/In.js index c4c125810..496494ca0 100644 --- a/src/math/easing/elastic/In.js +++ b/src/math/easing/elastic/In.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Elastic ease-in. - * - * @function Phaser.Math.Easing.Elastic.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. - * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. - * - * @return {number} The tweened value. - */ -var In = function (v, amplitude, period) -{ - if (amplitude === undefined) { amplitude = 0.1; } - if (period === undefined) { period = 0.1; } - - if (v === 0) - { - return 0; - } - else if (v === 1) - { - return 1; - } - else - { - var s = period / 4; - - if (amplitude < 1) - { - amplitude = 1; - } - else - { - s = period * Math.asin(1 / amplitude) / (2 * Math.PI); - } - - return -(amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)); - } -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Elastic ease-in. + * + * @function Phaser.Math.Easing.Elastic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. + * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. + * + * @return {number} The tweened value. + */ +var In = function (v, amplitude, period) +{ + if (amplitude === undefined) { amplitude = 0.1; } + if (period === undefined) { period = 0.1; } + + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + var s = period / 4; + + if (amplitude < 1) + { + amplitude = 1; + } + else + { + s = period * Math.asin(1 / amplitude) / (2 * Math.PI); + } + + return -(amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)); + } +}; + +module.exports = In; diff --git a/src/math/easing/elastic/InOut.js b/src/math/easing/elastic/InOut.js index 01e410d08..dea6ecd18 100644 --- a/src/math/easing/elastic/InOut.js +++ b/src/math/easing/elastic/InOut.js @@ -1,56 +1,56 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Elastic ease-in/out. - * - * @function Phaser.Math.Easing.Elastic.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. - * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. - * - * @return {number} The tweened value. - */ -var InOut = function (v, amplitude, period) -{ - if (amplitude === undefined) { amplitude = 0.1; } - if (period === undefined) { period = 0.1; } - - if (v === 0) - { - return 0; - } - else if (v === 1) - { - return 1; - } - else - { - var s = period / 4; - - if (amplitude < 1) - { - amplitude = 1; - } - else - { - s = period * Math.asin(1 / amplitude) / (2 * Math.PI); - } - - if ((v *= 2) < 1) - { - return -0.5 * (amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)); - } - else - { - return amplitude * Math.pow(2, -10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period) * 0.5 + 1; - } - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Elastic ease-in/out. + * + * @function Phaser.Math.Easing.Elastic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. + * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. + * + * @return {number} The tweened value. + */ +var InOut = function (v, amplitude, period) +{ + if (amplitude === undefined) { amplitude = 0.1; } + if (period === undefined) { period = 0.1; } + + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + var s = period / 4; + + if (amplitude < 1) + { + amplitude = 1; + } + else + { + s = period * Math.asin(1 / amplitude) / (2 * Math.PI); + } + + if ((v *= 2) < 1) + { + return -0.5 * (amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)); + } + else + { + return amplitude * Math.pow(2, -10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period) * 0.5 + 1; + } + } +}; + +module.exports = InOut; diff --git a/src/math/easing/elastic/Out.js b/src/math/easing/elastic/Out.js index 4d22b0234..1acdb5713 100644 --- a/src/math/easing/elastic/Out.js +++ b/src/math/easing/elastic/Out.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Elastic ease-out. - * - * @function Phaser.Math.Easing.Elastic.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. - * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. - * - * @return {number} The tweened value. - */ -var Out = function (v, amplitude, period) -{ - if (amplitude === undefined) { amplitude = 0.1; } - if (period === undefined) { period = 0.1; } - - if (v === 0) - { - return 0; - } - else if (v === 1) - { - return 1; - } - else - { - var s = period / 4; - - if (amplitude < 1) - { - amplitude = 1; - } - else - { - s = period * Math.asin(1 / amplitude) / (2 * Math.PI); - } - - return (amplitude * Math.pow(2, -10 * v) * Math.sin((v - s) * (2 * Math.PI) / period) + 1); - } -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Elastic ease-out. + * + * @function Phaser.Math.Easing.Elastic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [amplitude=0.1] - The amplitude of the elastic ease. + * @param {number} [period=0.1] - Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. + * + * @return {number} The tweened value. + */ +var Out = function (v, amplitude, period) +{ + if (amplitude === undefined) { amplitude = 0.1; } + if (period === undefined) { period = 0.1; } + + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + var s = period / 4; + + if (amplitude < 1) + { + amplitude = 1; + } + else + { + s = period * Math.asin(1 / amplitude) / (2 * Math.PI); + } + + return (amplitude * Math.pow(2, -10 * v) * Math.sin((v - s) * (2 * Math.PI) / period) + 1); + } +}; + +module.exports = Out; diff --git a/src/math/easing/elastic/index.js b/src/math/easing/elastic/index.js index 30bbe34d5..8f906cf43 100644 --- a/src/math/easing/elastic/index.js +++ b/src/math/easing/elastic/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Elastic - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Elastic + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/expo/In.js b/src/math/easing/expo/In.js index cfad035e5..eab2c51e0 100644 --- a/src/math/easing/expo/In.js +++ b/src/math/easing/expo/In.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Exponential ease-in. - * - * @function Phaser.Math.Easing.Expo.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - return Math.pow(2, 10 * (v - 1)) - 0.001; -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Exponential ease-in. + * + * @function Phaser.Math.Easing.Expo.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return Math.pow(2, 10 * (v - 1)) - 0.001; +}; + +module.exports = In; diff --git a/src/math/easing/expo/InOut.js b/src/math/easing/expo/InOut.js index 21f58960a..a7ad2ef96 100644 --- a/src/math/easing/expo/InOut.js +++ b/src/math/easing/expo/InOut.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Exponential ease-in/out. - * - * @function Phaser.Math.Easing.Expo.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if ((v *= 2) < 1) - { - return 0.5 * Math.pow(2, 10 * (v - 1)); - } - else - { - return 0.5 * (2 - Math.pow(2, -10 * (v - 1))); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Exponential ease-in/out. + * + * @function Phaser.Math.Easing.Expo.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * Math.pow(2, 10 * (v - 1)); + } + else + { + return 0.5 * (2 - Math.pow(2, -10 * (v - 1))); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/expo/Out.js b/src/math/easing/expo/Out.js index 8915b0088..4d1b084b2 100644 --- a/src/math/easing/expo/Out.js +++ b/src/math/easing/expo/Out.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Exponential ease-out. - * - * @function Phaser.Math.Easing.Expo.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - return 1 - Math.pow(2, -10 * v); -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Exponential ease-out. + * + * @function Phaser.Math.Easing.Expo.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return 1 - Math.pow(2, -10 * v); +}; + +module.exports = Out; diff --git a/src/math/easing/expo/index.js b/src/math/easing/expo/index.js index 00bf463a1..c45767b41 100644 --- a/src/math/easing/expo/index.js +++ b/src/math/easing/expo/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Expo - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Expo + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/index.js b/src/math/easing/index.js index d75d9f942..49f9d6c75 100644 --- a/src/math/easing/index.js +++ b/src/math/easing/index.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing - */ - -module.exports = { - - Back: require('./back'), - Bounce: require('./bounce'), - Circular: require('./circular'), - Cubic: require('./cubic'), - Elastic: require('./elastic'), - Expo: require('./expo'), - Linear: require('./linear'), - Quadratic: require('./quadratic'), - Quartic: require('./quartic'), - Quintic: require('./quintic'), - Sine: require('./sine'), - Stepped: require('./stepped') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing + */ + +module.exports = { + + Back: require('./back'), + Bounce: require('./bounce'), + Circular: require('./circular'), + Cubic: require('./cubic'), + Elastic: require('./elastic'), + Expo: require('./expo'), + Linear: require('./linear'), + Quadratic: require('./quadratic'), + Quartic: require('./quartic'), + Quintic: require('./quintic'), + Sine: require('./sine'), + Stepped: require('./stepped') + +}; diff --git a/src/math/easing/linear/Linear.js b/src/math/easing/linear/Linear.js index 939f63997..b5176f4f5 100644 --- a/src/math/easing/linear/Linear.js +++ b/src/math/easing/linear/Linear.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Linear easing (no variation). - * - * @function Phaser.Math.Easing.Linear.Linear - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Linear = function (v) -{ - return v; -}; - -module.exports = Linear; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Linear easing (no variation). + * + * @function Phaser.Math.Easing.Linear.Linear + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Linear = function (v) +{ + return v; +}; + +module.exports = Linear; diff --git a/src/math/easing/linear/index.js b/src/math/easing/linear/index.js index 776bc03a2..ac31c780c 100644 --- a/src/math/easing/linear/index.js +++ b/src/math/easing/linear/index.js @@ -1,11 +1,11 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Linear - */ - -module.exports = require('./Linear'); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Linear + */ + +module.exports = require('./Linear'); diff --git a/src/math/easing/quadratic/In.js b/src/math/easing/quadratic/In.js index 49de22428..f603ed428 100644 --- a/src/math/easing/quadratic/In.js +++ b/src/math/easing/quadratic/In.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quadratic ease-in. - * - * @function Phaser.Math.Easing.Quadratic.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - return v * v; -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quadratic ease-in. + * + * @function Phaser.Math.Easing.Quadratic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v; +}; + +module.exports = In; diff --git a/src/math/easing/quadratic/InOut.js b/src/math/easing/quadratic/InOut.js index 1971f2d5c..fbfe1ba4b 100644 --- a/src/math/easing/quadratic/InOut.js +++ b/src/math/easing/quadratic/InOut.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quadratic ease-in/out. - * - * @function Phaser.Math.Easing.Quadratic.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if ((v *= 2) < 1) - { - return 0.5 * v * v; - } - else - { - return -0.5 * (--v * (v - 2) - 1); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quadratic ease-in/out. + * + * @function Phaser.Math.Easing.Quadratic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v; + } + else + { + return -0.5 * (--v * (v - 2) - 1); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/quadratic/Out.js b/src/math/easing/quadratic/Out.js index ac17bc135..156f889d5 100644 --- a/src/math/easing/quadratic/Out.js +++ b/src/math/easing/quadratic/Out.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quadratic ease-out. - * - * @function Phaser.Math.Easing.Quadratic.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - return v * (2 - v); -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quadratic ease-out. + * + * @function Phaser.Math.Easing.Quadratic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return v * (2 - v); +}; + +module.exports = Out; diff --git a/src/math/easing/quadratic/index.js b/src/math/easing/quadratic/index.js index 7474a5b25..eed052378 100644 --- a/src/math/easing/quadratic/index.js +++ b/src/math/easing/quadratic/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Quadratic - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Quadratic + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/quartic/In.js b/src/math/easing/quartic/In.js index 84eaae530..60a6b92f4 100644 --- a/src/math/easing/quartic/In.js +++ b/src/math/easing/quartic/In.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quartic ease-in. - * - * @function Phaser.Math.Easing.Quartic.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - return v * v * v * v; -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quartic ease-in. + * + * @function Phaser.Math.Easing.Quartic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v * v * v; +}; + +module.exports = In; diff --git a/src/math/easing/quartic/InOut.js b/src/math/easing/quartic/InOut.js index 607228040..69de55a07 100644 --- a/src/math/easing/quartic/InOut.js +++ b/src/math/easing/quartic/InOut.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quartic ease-in/out. - * - * @function Phaser.Math.Easing.Quartic.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if ((v *= 2) < 1) - { - return 0.5 * v * v * v * v; - } - else - { - return -0.5 * ((v -= 2) * v * v * v - 2); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quartic ease-in/out. + * + * @function Phaser.Math.Easing.Quartic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v * v * v; + } + else + { + return -0.5 * ((v -= 2) * v * v * v - 2); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/quartic/Out.js b/src/math/easing/quartic/Out.js index 5693179ab..ab3c42fbf 100644 --- a/src/math/easing/quartic/Out.js +++ b/src/math/easing/quartic/Out.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quartic ease-out. - * - * @function Phaser.Math.Easing.Quartic.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - return 1 - (--v * v * v * v); -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quartic ease-out. + * + * @function Phaser.Math.Easing.Quartic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return 1 - (--v * v * v * v); +}; + +module.exports = Out; diff --git a/src/math/easing/quartic/index.js b/src/math/easing/quartic/index.js index 5550895b4..e3596f861 100644 --- a/src/math/easing/quartic/index.js +++ b/src/math/easing/quartic/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Quartic - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Quartic + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/quintic/In.js b/src/math/easing/quintic/In.js index 23ad6ae6c..2f4539da1 100644 --- a/src/math/easing/quintic/In.js +++ b/src/math/easing/quintic/In.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quintic ease-in. - * - * @function Phaser.Math.Easing.Quintic.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - return v * v * v * v * v; -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quintic ease-in. + * + * @function Phaser.Math.Easing.Quintic.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + return v * v * v * v * v; +}; + +module.exports = In; diff --git a/src/math/easing/quintic/InOut.js b/src/math/easing/quintic/InOut.js index 2c6daf11b..d8e99ad42 100644 --- a/src/math/easing/quintic/InOut.js +++ b/src/math/easing/quintic/InOut.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quintic ease-in/out. - * - * @function Phaser.Math.Easing.Quintic.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if ((v *= 2) < 1) - { - return 0.5 * v * v * v * v * v; - } - else - { - return 0.5 * ((v -= 2) * v * v * v * v + 2); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quintic ease-in/out. + * + * @function Phaser.Math.Easing.Quintic.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if ((v *= 2) < 1) + { + return 0.5 * v * v * v * v * v; + } + else + { + return 0.5 * ((v -= 2) * v * v * v * v + 2); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/quintic/Out.js b/src/math/easing/quintic/Out.js index 03b37c99f..89be4c54b 100644 --- a/src/math/easing/quintic/Out.js +++ b/src/math/easing/quintic/Out.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Quintic ease-out. - * - * @function Phaser.Math.Easing.Quintic.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - return --v * v * v * v * v + 1; -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Quintic ease-out. + * + * @function Phaser.Math.Easing.Quintic.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + return --v * v * v * v * v + 1; +}; + +module.exports = Out; diff --git a/src/math/easing/quintic/index.js b/src/math/easing/quintic/index.js index 24a0d4c75..968467e29 100644 --- a/src/math/easing/quintic/index.js +++ b/src/math/easing/quintic/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Quintic - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Quintic + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/sine/In.js b/src/math/easing/sine/In.js index 4e5cf8392..ee8c97c73 100644 --- a/src/math/easing/sine/In.js +++ b/src/math/easing/sine/In.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sinusoidal ease-in. - * - * @function Phaser.Math.Easing.Sine.In - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var In = function (v) -{ - if (v === 0) - { - return 0; - } - else if (v === 1) - { - return 1; - } - else - { - return 1 - Math.cos(v * Math.PI / 2); - } -}; - -module.exports = In; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sinusoidal ease-in. + * + * @function Phaser.Math.Easing.Sine.In + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var In = function (v) +{ + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + return 1 - Math.cos(v * Math.PI / 2); + } +}; + +module.exports = In; diff --git a/src/math/easing/sine/InOut.js b/src/math/easing/sine/InOut.js index d265e6406..d2be33373 100644 --- a/src/math/easing/sine/InOut.js +++ b/src/math/easing/sine/InOut.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sinusoidal ease-in/out. - * - * @function Phaser.Math.Easing.Sine.InOut - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var InOut = function (v) -{ - if (v === 0) - { - return 0; - } - else if (v === 1) - { - return 1; - } - else - { - return 0.5 * (1 - Math.cos(Math.PI * v)); - } -}; - -module.exports = InOut; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sinusoidal ease-in/out. + * + * @function Phaser.Math.Easing.Sine.InOut + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var InOut = function (v) +{ + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + return 0.5 * (1 - Math.cos(Math.PI * v)); + } +}; + +module.exports = InOut; diff --git a/src/math/easing/sine/Out.js b/src/math/easing/sine/Out.js index 4b61be5a8..f66d99c36 100644 --- a/src/math/easing/sine/Out.js +++ b/src/math/easing/sine/Out.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sinusoidal ease-out. - * - * @function Phaser.Math.Easing.Sine.Out - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * - * @return {number} The tweened value. - */ -var Out = function (v) -{ - if (v === 0) - { - return 0; - } - else if (v === 1) - { - return 1; - } - else - { - return Math.sin(v * Math.PI / 2); - } -}; - -module.exports = Out; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sinusoidal ease-out. + * + * @function Phaser.Math.Easing.Sine.Out + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * + * @return {number} The tweened value. + */ +var Out = function (v) +{ + if (v === 0) + { + return 0; + } + else if (v === 1) + { + return 1; + } + else + { + return Math.sin(v * Math.PI / 2); + } +}; + +module.exports = Out; diff --git a/src/math/easing/sine/index.js b/src/math/easing/sine/index.js index fe563be57..e6ab5b43a 100644 --- a/src/math/easing/sine/index.js +++ b/src/math/easing/sine/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Sine - */ - -module.exports = { - - In: require('./In'), - Out: require('./Out'), - InOut: require('./InOut') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Sine + */ + +module.exports = { + + In: require('./In'), + Out: require('./Out'), + InOut: require('./InOut') + +}; diff --git a/src/math/easing/stepped/Stepped.js b/src/math/easing/stepped/Stepped.js index 1004d3a13..3df23fa3b 100644 --- a/src/math/easing/stepped/Stepped.js +++ b/src/math/easing/stepped/Stepped.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Stepped easing. - * - * @function Phaser.Math.Easing.Stepped.Stepped - * @since 3.0.0 - * - * @param {number} v - The value to be tweened. - * @param {number} [steps=1] - The number of steps in the ease. - * - * @return {number} The tweened value. - */ -var Stepped = function (v, steps) -{ - if (steps === undefined) { steps = 1; } - - if (v <= 0) - { - return 0; - } - else if (v >= 1) - { - return 1; - } - else - { - return (((steps * v) | 0) + 1) * (1 / steps); - } -}; - -module.exports = Stepped; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Stepped easing. + * + * @function Phaser.Math.Easing.Stepped.Stepped + * @since 3.0.0 + * + * @param {number} v - The value to be tweened. + * @param {number} [steps=1] - The number of steps in the ease. + * + * @return {number} The tweened value. + */ +var Stepped = function (v, steps) +{ + if (steps === undefined) { steps = 1; } + + if (v <= 0) + { + return 0; + } + else if (v >= 1) + { + return 1; + } + else + { + return (((steps * v) | 0) + 1) * (1 / steps); + } +}; + +module.exports = Stepped; diff --git a/src/math/easing/stepped/index.js b/src/math/easing/stepped/index.js index 82bcdee2d..35a15b1e7 100644 --- a/src/math/easing/stepped/index.js +++ b/src/math/easing/stepped/index.js @@ -1,11 +1,11 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Easing.Stepped - */ - -module.exports = require('./Stepped'); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Easing.Stepped + */ + +module.exports = require('./Stepped'); diff --git a/src/math/fuzzy/Ceil.js b/src/math/fuzzy/Ceil.js index f5a8e2863..29a206c4c 100644 --- a/src/math/fuzzy/Ceil.js +++ b/src/math/fuzzy/Ceil.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the fuzzy ceiling of the given value. - * - * @function Phaser.Math.Fuzzy.Ceil - * @since 3.0.0 - * - * @param {number} value - The value. - * @param {number} [epsilon=0.0001] - The epsilon. - * - * @return {number} The fuzzy ceiling of the value. - */ -var Ceil = function (value, epsilon) -{ - if (epsilon === undefined) { epsilon = 0.0001; } - - return Math.ceil(value - epsilon); -}; - -module.exports = Ceil; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the fuzzy ceiling of the given value. + * + * @function Phaser.Math.Fuzzy.Ceil + * @since 3.0.0 + * + * @param {number} value - The value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {number} The fuzzy ceiling of the value. + */ +var Ceil = function (value, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(value - epsilon); +}; + +module.exports = Ceil; diff --git a/src/math/fuzzy/Equal.js b/src/math/fuzzy/Equal.js index 919b18418..af1e9c361 100644 --- a/src/math/fuzzy/Equal.js +++ b/src/math/fuzzy/Equal.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check whether the given values are fuzzily equal. - * - * Two numbers are fuzzily equal if their difference is less than `epsilon`. - * - * @function Phaser.Math.Fuzzy.Equal - * @since 3.0.0 - * - * @param {number} a - The first value. - * @param {number} b - The second value. - * @param {number} [epsilon=0.0001] - The epsilon. - * - * @return {boolean} `true` if the values are fuzzily equal, otherwise `false`. - */ -var Equal = function (a, b, epsilon) -{ - if (epsilon === undefined) { epsilon = 0.0001; } - - return Math.abs(a - b) < epsilon; -}; - -module.exports = Equal; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check whether the given values are fuzzily equal. + * + * Two numbers are fuzzily equal if their difference is less than `epsilon`. + * + * @function Phaser.Math.Fuzzy.Equal + * @since 3.0.0 + * + * @param {number} a - The first value. + * @param {number} b - The second value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {boolean} `true` if the values are fuzzily equal, otherwise `false`. + */ +var Equal = function (a, b, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.abs(a - b) < epsilon; +}; + +module.exports = Equal; diff --git a/src/math/fuzzy/Floor.js b/src/math/fuzzy/Floor.js index 4f0138b1c..3446f3cda 100644 --- a/src/math/fuzzy/Floor.js +++ b/src/math/fuzzy/Floor.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Calculate the fuzzy floor of the given value. - * - * @function Phaser.Math.Fuzzy.Floor - * @since 3.0.0 - * - * @param {number} value - The value. - * @param {number} [epsilon=0.0001] - The epsilon. - * - * @return {number} The floor of the value. - */ -var Floor = function (value, epsilon) -{ - if (epsilon === undefined) { epsilon = 0.0001; } - - return Math.floor(value + epsilon); -}; - -module.exports = Floor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Calculate the fuzzy floor of the given value. + * + * @function Phaser.Math.Fuzzy.Floor + * @since 3.0.0 + * + * @param {number} value - The value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {number} The floor of the value. + */ +var Floor = function (value, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(value + epsilon); +}; + +module.exports = Floor; diff --git a/src/math/fuzzy/GreaterThan.js b/src/math/fuzzy/GreaterThan.js index 459b2b283..463dc68d1 100644 --- a/src/math/fuzzy/GreaterThan.js +++ b/src/math/fuzzy/GreaterThan.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check whether `a` is fuzzily greater than `b`. - * - * `a` is fuzzily greater than `b` if it is more than `b - epsilon`. - * - * @function Phaser.Math.Fuzzy.GreaterThan - * @since 3.0.0 - * - * @param {number} a - The first value. - * @param {number} b - The second value. - * @param {number} [epsilon=0.0001] - The epsilon. - * - * @return {boolean} `true` if `a` is fuzzily greater than than `b`, otherwise `false`. - */ -var GreaterThan = function (a, b, epsilon) -{ - if (epsilon === undefined) { epsilon = 0.0001; } - - return a > b - epsilon; -}; - -module.exports = GreaterThan; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check whether `a` is fuzzily greater than `b`. + * + * `a` is fuzzily greater than `b` if it is more than `b - epsilon`. + * + * @function Phaser.Math.Fuzzy.GreaterThan + * @since 3.0.0 + * + * @param {number} a - The first value. + * @param {number} b - The second value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {boolean} `true` if `a` is fuzzily greater than than `b`, otherwise `false`. + */ +var GreaterThan = function (a, b, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; +}; + +module.exports = GreaterThan; diff --git a/src/math/fuzzy/LessThan.js b/src/math/fuzzy/LessThan.js index 24e6c8ff8..44b346210 100644 --- a/src/math/fuzzy/LessThan.js +++ b/src/math/fuzzy/LessThan.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Check whether `a` is fuzzily less than `b`. - * - * `a` is fuzzily less than `b` if it is less than `b + epsilon`. - * - * @function Phaser.Math.Fuzzy.LessThan - * @since 3.0.0 - * - * @param {number} a - The first value. - * @param {number} b - The second value. - * @param {number} [epsilon=0.0001] - The epsilon. - * - * @return {boolean} `true` if `a` is fuzzily less than `b`, otherwise `false`. - */ -var LessThan = function (a, b, epsilon) -{ - if (epsilon === undefined) { epsilon = 0.0001; } - - return a < b + epsilon; -}; - -module.exports = LessThan; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Check whether `a` is fuzzily less than `b`. + * + * `a` is fuzzily less than `b` if it is less than `b + epsilon`. + * + * @function Phaser.Math.Fuzzy.LessThan + * @since 3.0.0 + * + * @param {number} a - The first value. + * @param {number} b - The second value. + * @param {number} [epsilon=0.0001] - The epsilon. + * + * @return {boolean} `true` if `a` is fuzzily less than `b`, otherwise `false`. + */ +var LessThan = function (a, b, epsilon) +{ + if (epsilon === undefined) { epsilon = 0.0001; } + + return a < b + epsilon; +}; + +module.exports = LessThan; diff --git a/src/math/fuzzy/index.js b/src/math/fuzzy/index.js index a7be5b777..3f2c1b7be 100644 --- a/src/math/fuzzy/index.js +++ b/src/math/fuzzy/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Fuzzy - */ - -module.exports = { - - Ceil: require('./Ceil'), - Equal: require('./Equal'), - Floor: require('./Floor'), - GreaterThan: require('./GreaterThan'), - LessThan: require('./LessThan') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Fuzzy + */ + +module.exports = { + + Ceil: require('./Ceil'), + Equal: require('./Equal'), + Floor: require('./Floor'), + GreaterThan: require('./GreaterThan'), + LessThan: require('./LessThan') + +}; diff --git a/src/math/index.js b/src/math/index.js index 11a3b1350..422975cbd 100644 --- a/src/math/index.js +++ b/src/math/index.js @@ -1,82 +1,82 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../utils/object/Extend'); - -/** - * @namespace Phaser.Math - */ - -var PhaserMath = { - - // Collections of functions - Angle: require('./angle/'), - Distance: require('./distance/'), - Easing: require('./easing/'), - Fuzzy: require('./fuzzy/'), - Interpolation: require('./interpolation/'), - Pow2: require('./pow2/'), - Snap: require('./snap/'), - - // Expose the RNG Class - RandomDataGenerator: require('./random-data-generator/RandomDataGenerator'), - - // Single functions - Average: require('./Average'), - Bernstein: require('./Bernstein'), - Between: require('./Between'), - CatmullRom: require('./CatmullRom'), - CeilTo: require('./CeilTo'), - Clamp: require('./Clamp'), - DegToRad: require('./DegToRad'), - Difference: require('./Difference'), - Factorial: require('./Factorial'), - FloatBetween: require('./FloatBetween'), - FloorTo: require('./FloorTo'), - FromPercent: require('./FromPercent'), - GetSpeed: require('./GetSpeed'), - IsEven: require('./IsEven'), - IsEvenStrict: require('./IsEvenStrict'), - Linear: require('./Linear'), - MaxAdd: require('./MaxAdd'), - MinSub: require('./MinSub'), - Percent: require('./Percent'), - RadToDeg: require('./RadToDeg'), - RandomXY: require('./RandomXY'), - RandomXYZ: require('./RandomXYZ'), - RandomXYZW: require('./RandomXYZW'), - Rotate: require('./Rotate'), - RotateAround: require('./RotateAround'), - RotateAroundDistance: require('./RotateAroundDistance'), - RoundAwayFromZero: require('./RoundAwayFromZero'), - RoundTo: require('./RoundTo'), - SinCosTableGenerator: require('./SinCosTableGenerator'), - SmootherStep: require('./SmootherStep'), - SmoothStep: require('./SmoothStep'), - ToXY: require('./ToXY'), - TransformXY: require('./TransformXY'), - Within: require('./Within'), - Wrap: require('./Wrap'), - - // Vector classes - Vector2: require('./Vector2'), - Vector3: require('./Vector3'), - Vector4: require('./Vector4'), - Matrix3: require('./Matrix3'), - Matrix4: require('./Matrix4'), - Quaternion: require('./Quaternion'), - RotateVec3: require('./RotateVec3') - -}; - -// Merge in the consts - -PhaserMath = Extend(false, PhaserMath, CONST); - -// Export it - -module.exports = PhaserMath; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../utils/object/Extend'); + +/** + * @namespace Phaser.Math + */ + +var PhaserMath = { + + // Collections of functions + Angle: require('./angle/'), + Distance: require('./distance/'), + Easing: require('./easing/'), + Fuzzy: require('./fuzzy/'), + Interpolation: require('./interpolation/'), + Pow2: require('./pow2/'), + Snap: require('./snap/'), + + // Expose the RNG Class + RandomDataGenerator: require('./random-data-generator/RandomDataGenerator'), + + // Single functions + Average: require('./Average'), + Bernstein: require('./Bernstein'), + Between: require('./Between'), + CatmullRom: require('./CatmullRom'), + CeilTo: require('./CeilTo'), + Clamp: require('./Clamp'), + DegToRad: require('./DegToRad'), + Difference: require('./Difference'), + Factorial: require('./Factorial'), + FloatBetween: require('./FloatBetween'), + FloorTo: require('./FloorTo'), + FromPercent: require('./FromPercent'), + GetSpeed: require('./GetSpeed'), + IsEven: require('./IsEven'), + IsEvenStrict: require('./IsEvenStrict'), + Linear: require('./Linear'), + MaxAdd: require('./MaxAdd'), + MinSub: require('./MinSub'), + Percent: require('./Percent'), + RadToDeg: require('./RadToDeg'), + RandomXY: require('./RandomXY'), + RandomXYZ: require('./RandomXYZ'), + RandomXYZW: require('./RandomXYZW'), + Rotate: require('./Rotate'), + RotateAround: require('./RotateAround'), + RotateAroundDistance: require('./RotateAroundDistance'), + RoundAwayFromZero: require('./RoundAwayFromZero'), + RoundTo: require('./RoundTo'), + SinCosTableGenerator: require('./SinCosTableGenerator'), + SmootherStep: require('./SmootherStep'), + SmoothStep: require('./SmoothStep'), + ToXY: require('./ToXY'), + TransformXY: require('./TransformXY'), + Within: require('./Within'), + Wrap: require('./Wrap'), + + // Vector classes + Vector2: require('./Vector2'), + Vector3: require('./Vector3'), + Vector4: require('./Vector4'), + Matrix3: require('./Matrix3'), + Matrix4: require('./Matrix4'), + Quaternion: require('./Quaternion'), + RotateVec3: require('./RotateVec3') + +}; + +// Merge in the consts + +PhaserMath = Extend(false, PhaserMath, CONST); + +// Export it + +module.exports = PhaserMath; diff --git a/src/math/interpolation/BezierInterpolation.js b/src/math/interpolation/BezierInterpolation.js index 48a6d9ac0..fd44105c4 100644 --- a/src/math/interpolation/BezierInterpolation.js +++ b/src/math/interpolation/BezierInterpolation.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bernstein = require('../Bernstein'); - -/** - * A bezier interpolation method. - * - * @function Phaser.Math.Interpolation.Bezier - * @since 3.0.0 - * - * @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. - */ -var BezierInterpolation = function (v, k) -{ - var b = 0; - var n = v.length - 1; - - for (var i = 0; i <= n; i++) - { - b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * Bernstein(n, i); - } - - return b; -}; - -module.exports = BezierInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bernstein = require('../Bernstein'); + +/** + * A bezier interpolation method. + * + * @function Phaser.Math.Interpolation.Bezier + * @since 3.0.0 + * + * @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. + */ +var BezierInterpolation = function (v, k) +{ + var b = 0; + var n = v.length - 1; + + for (var i = 0; i <= n; i++) + { + b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * Bernstein(n, i); + } + + return b; +}; + +module.exports = BezierInterpolation; diff --git a/src/math/interpolation/CatmullRomInterpolation.js b/src/math/interpolation/CatmullRomInterpolation.js index f95a9a9d7..d8ab7dc27 100644 --- a/src/math/interpolation/CatmullRomInterpolation.js +++ b/src/math/interpolation/CatmullRomInterpolation.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CatmullRom = require('../CatmullRom'); - -/** - * A Catmull-Rom interpolation method. - * - * @function Phaser.Math.Interpolation.CatmullRom - * @since 3.0.0 - * - * @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. - */ -var CatmullRomInterpolation = function (v, k) -{ - var m = v.length - 1; - var f = m * k; - var i = Math.floor(f); - - if (v[0] === v[m]) - { - if (k < 0) - { - i = Math.floor(f = m * (1 + k)); - } - - return CatmullRom(f - i, v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m]); - } - else - { - if (k < 0) - { - return v[0] - (CatmullRom(-f, v[0], v[0], v[1], v[1]) - v[0]); - } - - if (k > 1) - { - return v[m] - (CatmullRom(f - m, v[m], v[m], v[m - 1], v[m - 1]) - v[m]); - } - - return CatmullRom(f - i, v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2]); - } -}; - -module.exports = CatmullRomInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CatmullRom = require('../CatmullRom'); + +/** + * A Catmull-Rom interpolation method. + * + * @function Phaser.Math.Interpolation.CatmullRom + * @since 3.0.0 + * + * @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. + */ +var CatmullRomInterpolation = function (v, k) +{ + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (v[0] === v[m]) + { + if (k < 0) + { + i = Math.floor(f = m * (1 + k)); + } + + return CatmullRom(f - i, v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m]); + } + else + { + if (k < 0) + { + return v[0] - (CatmullRom(-f, v[0], v[0], v[1], v[1]) - v[0]); + } + + if (k > 1) + { + return v[m] - (CatmullRom(f - m, v[m], v[m], v[m - 1], v[m - 1]) - v[m]); + } + + return CatmullRom(f - i, v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2]); + } +}; + +module.exports = CatmullRomInterpolation; diff --git a/src/math/interpolation/CubicBezierInterpolation.js b/src/math/interpolation/CubicBezierInterpolation.js index 97f715c11..96b61489b 100644 --- a/src/math/interpolation/CubicBezierInterpolation.js +++ b/src/math/interpolation/CubicBezierInterpolation.js @@ -1,64 +1,64 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @ignore - */ -function P0 (t, p) -{ - var k = 1 - t; - - return k * k * k * p; -} - -/** - * @ignore - */ -function P1 (t, p) -{ - var k = 1 - t; - - return 3 * k * k * t * p; -} - -/** - * @ignore - */ -function P2 (t, p) -{ - return 3 * (1 - t) * t * t * p; -} - -/** - * @ignore - */ -function P3 (t, p) -{ - return t * t * t * p; -} - -/** - * A cubic bezier interpolation method. - * - * 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. - */ -var CubicBezierInterpolation = function (t, p0, p1, p2, p3) -{ - return P0(t, p0) + P1(t, p1) + P2(t, p2) + P3(t, p3); -}; - -module.exports = CubicBezierInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function P0 (t, p) +{ + var k = 1 - t; + + return k * k * k * p; +} + +/** + * @ignore + */ +function P1 (t, p) +{ + var k = 1 - t; + + return 3 * k * k * t * p; +} + +/** + * @ignore + */ +function P2 (t, p) +{ + return 3 * (1 - t) * t * t * p; +} + +/** + * @ignore + */ +function P3 (t, p) +{ + return t * t * t * p; +} + +/** + * A cubic bezier interpolation method. + * + * 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. + */ +var CubicBezierInterpolation = function (t, p0, p1, p2, p3) +{ + return P0(t, p0) + P1(t, p1) + P2(t, p2) + P3(t, p3); +}; + +module.exports = CubicBezierInterpolation; diff --git a/src/math/interpolation/LinearInterpolation.js b/src/math/interpolation/LinearInterpolation.js index ac1016e7c..ca0daf272 100644 --- a/src/math/interpolation/LinearInterpolation.js +++ b/src/math/interpolation/LinearInterpolation.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Linear = require('../Linear'); - -/** - * A linear interpolation method. - * - * @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. - */ -var LinearInterpolation = function (v, k) -{ - var m = v.length - 1; - var f = m * k; - var i = Math.floor(f); - - if (k < 0) - { - return Linear(v[0], v[1], f); - } - else if (k > 1) - { - return Linear(v[m], v[m - 1], m - f); - } - else - { - return Linear(v[i], v[(i + 1 > m) ? m : i + 1], f - i); - } -}; - -module.exports = LinearInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Linear = require('../Linear'); + +/** + * A linear interpolation method. + * + * @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. + */ +var LinearInterpolation = function (v, k) +{ + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return Linear(v[0], v[1], f); + } + else if (k > 1) + { + return Linear(v[m], v[m - 1], m - f); + } + else + { + return Linear(v[i], v[(i + 1 > m) ? m : i + 1], f - i); + } +}; + +module.exports = LinearInterpolation; diff --git a/src/math/interpolation/QuadraticBezierInterpolation.js b/src/math/interpolation/QuadraticBezierInterpolation.js index 5df3be18f..abbe9c393 100644 --- a/src/math/interpolation/QuadraticBezierInterpolation.js +++ b/src/math/interpolation/QuadraticBezierInterpolation.js @@ -1,53 +1,53 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @ignore - */ -function P0 (t, p) -{ - var k = 1 - t; - - return k * k * p; -} - -/** - * @ignore - */ -function P1 (t, p) -{ - return 2 * (1 - t) * t * p; -} - -/** - * @ignore - */ -function P2 (t, p) -{ - return t * t * p; -} - -// https://github.com/mrdoob/three.js/blob/master/src/extras/core/Interpolations.js - -/** - * A quadratic bezier interpolation method. - * - * @function Phaser.Math.Interpolation.QuadraticBezier - * @since 3.2.0 - * - * @param {number} t - The percentage of interpolation, between 0 and 1. - * @param {number} p0 - The start point. - * @param {number} p1 - The control point. - * @param {number} p2 - The end point. - * - * @return {number} The interpolated value. - */ -var QuadraticBezierInterpolation = function (t, p0, p1, p2) -{ - return P0(t, p0) + P1(t, p1) + P2(t, p2); -}; - -module.exports = QuadraticBezierInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function P0 (t, p) +{ + var k = 1 - t; + + return k * k * p; +} + +/** + * @ignore + */ +function P1 (t, p) +{ + return 2 * (1 - t) * t * p; +} + +/** + * @ignore + */ +function P2 (t, p) +{ + return t * t * p; +} + +// https://github.com/mrdoob/three.js/blob/master/src/extras/core/Interpolations.js + +/** + * A quadratic bezier interpolation method. + * + * @function Phaser.Math.Interpolation.QuadraticBezier + * @since 3.2.0 + * + * @param {number} t - The percentage of interpolation, between 0 and 1. + * @param {number} p0 - The start point. + * @param {number} p1 - The control point. + * @param {number} p2 - The end point. + * + * @return {number} The interpolated value. + */ +var QuadraticBezierInterpolation = function (t, p0, p1, p2) +{ + return P0(t, p0) + P1(t, p1) + P2(t, p2); +}; + +module.exports = QuadraticBezierInterpolation; diff --git a/src/math/interpolation/SmoothStepInterpolation.js b/src/math/interpolation/SmoothStepInterpolation.js index 832c9543b..647ca25ad 100644 --- a/src/math/interpolation/SmoothStepInterpolation.js +++ b/src/math/interpolation/SmoothStepInterpolation.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SmoothStep = require('../SmoothStep'); - -/** - * A Smooth Step interpolation method. - * - * @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. - */ -var SmoothStepInterpolation = function (t, min, max) -{ - return min + (max - min) * SmoothStep(t, 0, 1); -}; - -module.exports = SmoothStepInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SmoothStep = require('../SmoothStep'); + +/** + * A Smooth Step interpolation method. + * + * @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. + */ +var SmoothStepInterpolation = function (t, min, max) +{ + return min + (max - min) * SmoothStep(t, 0, 1); +}; + +module.exports = SmoothStepInterpolation; diff --git a/src/math/interpolation/SmootherStepInterpolation.js b/src/math/interpolation/SmootherStepInterpolation.js index a4aede0ed..78b002e5c 100644 --- a/src/math/interpolation/SmootherStepInterpolation.js +++ b/src/math/interpolation/SmootherStepInterpolation.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SmootherStep = require('../SmootherStep'); - -/** - * A Smoother Step interpolation method. - * - * @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. - */ -var SmootherStepInterpolation = function (t, min, max) -{ - return min + (max - min) * SmootherStep(t, 0, 1); -}; - -module.exports = SmootherStepInterpolation; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SmootherStep = require('../SmootherStep'); + +/** + * A Smoother Step interpolation method. + * + * @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. + */ +var SmootherStepInterpolation = function (t, min, max) +{ + return min + (max - min) * SmootherStep(t, 0, 1); +}; + +module.exports = SmootherStepInterpolation; diff --git a/src/math/interpolation/index.js b/src/math/interpolation/index.js index c073729f0..d9d66e866 100644 --- a/src/math/interpolation/index.js +++ b/src/math/interpolation/index.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Interpolation - */ - -module.exports = { - - Bezier: require('./BezierInterpolation'), - CatmullRom: require('./CatmullRomInterpolation'), - CubicBezier: require('./CubicBezierInterpolation'), - Linear: require('./LinearInterpolation'), - QuadraticBezier: require('./QuadraticBezierInterpolation'), - SmoothStep: require('./SmoothStepInterpolation'), - SmootherStep: require('./SmootherStepInterpolation') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Interpolation + */ + +module.exports = { + + Bezier: require('./BezierInterpolation'), + CatmullRom: require('./CatmullRomInterpolation'), + CubicBezier: require('./CubicBezierInterpolation'), + Linear: require('./LinearInterpolation'), + QuadraticBezier: require('./QuadraticBezierInterpolation'), + SmoothStep: require('./SmoothStepInterpolation'), + SmootherStep: require('./SmootherStepInterpolation') + +}; diff --git a/src/math/pow2/GetPowerOfTwo.js b/src/math/pow2/GetPowerOfTwo.js index 5d581d7cc..a6275443b 100644 --- a/src/math/pow2/GetPowerOfTwo.js +++ b/src/math/pow2/GetPowerOfTwo.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns the nearest power of 2 to the given `value`. - * - * @function Phaser.Math.Pow2.GetNext - * @since 3.0.0 - * - * @param {number} value - The value. - * - * @return {integer} The nearest power of 2 to `value`. - */ -var GetPowerOfTwo = function (value) -{ - var index = Math.log(value) / 0.6931471805599453; - - return (1 << Math.ceil(index)); -}; - -module.exports = GetPowerOfTwo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns the nearest power of 2 to the given `value`. + * + * @function Phaser.Math.Pow2.GetNext + * @since 3.0.0 + * + * @param {number} value - The value. + * + * @return {integer} The nearest power of 2 to `value`. + */ +var GetPowerOfTwo = function (value) +{ + var index = Math.log(value) / 0.6931471805599453; + + return (1 << Math.ceil(index)); +}; + +module.exports = GetPowerOfTwo; diff --git a/src/math/pow2/IsSizePowerOfTwo.js b/src/math/pow2/IsSizePowerOfTwo.js index 2d280967d..c00cf1b81 100644 --- a/src/math/pow2/IsSizePowerOfTwo.js +++ b/src/math/pow2/IsSizePowerOfTwo.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if the given `width` and `height` are a power of two. - * Useful for checking texture dimensions. - * - * @function Phaser.Math.Pow2.IsSize - * @since 3.0.0 - * - * @param {number} width - The width. - * @param {number} height - The height. - * - * @return {boolean} `true` if `width` and `height` are a power of two, otherwise `false`. - */ -var IsSizePowerOfTwo = function (width, height) -{ - return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); -}; - -module.exports = IsSizePowerOfTwo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the given `width` and `height` are a power of two. + * Useful for checking texture dimensions. + * + * @function Phaser.Math.Pow2.IsSize + * @since 3.0.0 + * + * @param {number} width - The width. + * @param {number} height - The height. + * + * @return {boolean} `true` if `width` and `height` are a power of two, otherwise `false`. + */ +var IsSizePowerOfTwo = function (width, height) +{ + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); +}; + +module.exports = IsSizePowerOfTwo; diff --git a/src/math/pow2/IsValuePowerOfTwo.js b/src/math/pow2/IsValuePowerOfTwo.js index 40ab861fd..21e319325 100644 --- a/src/math/pow2/IsValuePowerOfTwo.js +++ b/src/math/pow2/IsValuePowerOfTwo.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Tests the value and returns `true` if it is a power of two. - * - * @function Phaser.Math.Pow2.IsValue - * @since 3.0.0 - * - * @param {number} value - The value to check if it's a power of two. - * - * @return {boolean} Returns `true` if `value` is a power of two, otherwise `false`. - */ -var IsValuePowerOfTwo = function (value) -{ - return (value > 0 && (value & (value - 1)) === 0); -}; - -module.exports = IsValuePowerOfTwo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tests the value and returns `true` if it is a power of two. + * + * @function Phaser.Math.Pow2.IsValue + * @since 3.0.0 + * + * @param {number} value - The value to check if it's a power of two. + * + * @return {boolean} Returns `true` if `value` is a power of two, otherwise `false`. + */ +var IsValuePowerOfTwo = function (value) +{ + return (value > 0 && (value & (value - 1)) === 0); +}; + +module.exports = IsValuePowerOfTwo; diff --git a/src/math/pow2/index.js b/src/math/pow2/index.js index 8eccd11c4..94c14c9ea 100644 --- a/src/math/pow2/index.js +++ b/src/math/pow2/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Pow2 - */ - -module.exports = { - - GetNext: require('./GetPowerOfTwo'), - IsSize: require('./IsSizePowerOfTwo'), - IsValue: require('./IsValuePowerOfTwo') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Pow2 + */ + +module.exports = { + + GetNext: require('./GetPowerOfTwo'), + IsSize: require('./IsSizePowerOfTwo'), + IsValue: require('./IsValuePowerOfTwo') + +}; diff --git a/src/math/random-data-generator/RandomDataGenerator.js b/src/math/random-data-generator/RandomDataGenerator.js index a0fffd2bf..6a57bbe88 100644 --- a/src/math/random-data-generator/RandomDataGenerator.js +++ b/src/math/random-data-generator/RandomDataGenerator.js @@ -1,504 +1,504 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); - -/** - * @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. - */ -var RandomDataGenerator = new Class({ - - initialize: - - function RandomDataGenerator (seeds) - { - if (seeds === undefined) { seeds = [ (Date.now() * Math.random()).toString() ]; } - - /** - * Internal var. - * - * @name Phaser.Math.RandomDataGenerator#c - * @type {number} - * @default 1 - * @private - * @since 3.0.0 - */ - this.c = 1; - - /** - * Internal var. - * - * @name Phaser.Math.RandomDataGenerator#s0 - * @type {number} - * @default 0 - * @private - * @since 3.0.0 - */ - this.s0 = 0; - - /** - * Internal var. - * - * @name Phaser.Math.RandomDataGenerator#s1 - * @type {number} - * @default 0 - * @private - * @since 3.0.0 - */ - this.s1 = 0; - - /** - * Internal var. - * - * @name Phaser.Math.RandomDataGenerator#s2 - * @type {number} - * @default 0 - * @private - * @since 3.0.0 - */ - this.s2 = 0; - - /** - * Internal var. - * - * @name Phaser.Math.RandomDataGenerator#n - * @type {number} - * @default 0 - * @private - * @since 3.2.0 - */ - this.n = 0; - - /** - * Signs to choose from. - * - * @name Phaser.Math.RandomDataGenerator#signs - * @type {number[]} - * @since 3.0.0 - */ - this.signs = [ -1, 1 ]; - - if (seeds) - { - this.init(seeds); - } - }, - - /** - * Private random helper. - * - * @method Phaser.Math.RandomDataGenerator#rnd - * @since 3.0.0 - * @private - * - * @return {number} A random number. - */ - rnd: function () - { - var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 - - this.c = t | 0; - this.s0 = this.s1; - this.s1 = this.s2; - this.s2 = t - this.c; - - return this.s2; - }, - - /** - * Internal method that creates a seed hash. - * - * @method Phaser.Math.RandomDataGenerator#hash - * @since 3.0.0 - * @private - * - * @param {string} data - The value to hash. - * - * @return {number} The hashed value. - */ - hash: function (data) - { - var h; - var n = this.n; - - data = data.toString(); - - for (var i = 0; i < data.length; i++) - { - n += data.charCodeAt(i); - h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 0x100000000;// 2^32 - } - - this.n = n; - - return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 - }, - - /** - * Initialize the state of the random data generator. - * - * @method Phaser.Math.RandomDataGenerator#init - * @since 3.0.0 - * - * @param {(string|string[])} seeds - The seeds to initialize the random data generator with. - */ - init: function (seeds) - { - if (typeof seeds === 'string') - { - this.state(seeds); - } - else - { - this.sow(seeds); - } - }, - - /** - * Reset the seed of the random data generator. - * - * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. - * - * @method Phaser.Math.RandomDataGenerator#sow - * @since 3.0.0 - * - * @param {string[]} seeds - The array of seeds: the `toString()` of each value is used. - */ - sow: function (seeds) - { - // Always reset to default seed - this.n = 0xefc8249d; - this.s0 = this.hash(' '); - this.s1 = this.hash(' '); - this.s2 = this.hash(' '); - this.c = 1; - - if (!seeds) - { - return; - } - - // Apply any seeds - for (var i = 0; i < seeds.length && (seeds[i] != null); i++) - { - var seed = seeds[i]; - - this.s0 -= this.hash(seed); - this.s0 += ~~(this.s0 < 0); - this.s1 -= this.hash(seed); - this.s1 += ~~(this.s1 < 0); - this.s2 -= this.hash(seed); - this.s2 += ~~(this.s2 < 0); - } - }, - - /** - * Returns a random integer between 0 and 2^32. - * - * @method Phaser.Math.RandomDataGenerator#integer - * @since 3.0.0 - * - * @return {number} A random integer between 0 and 2^32. - */ - integer: function () - { - // 2^32 - return this.rnd() * 0x100000000; - }, - - /** - * Returns a random real number between 0 and 1. - * - * @method Phaser.Math.RandomDataGenerator#frac - * @since 3.0.0 - * - * @return {number} A random real number between 0 and 1. - */ - frac: function () - { - // 2^-53 - return this.rnd() + (this.rnd() * 0x200000 | 0) * 1.1102230246251565e-16; - }, - - /** - * Returns a random real number between 0 and 2^32. - * - * @method Phaser.Math.RandomDataGenerator#real - * @since 3.0.0 - * - * @return {number} A random real number between 0 and 2^32. - */ - real: function () - { - return this.integer() + this.frac(); - }, - - /** - * Returns a random integer between and including min and max. - * - * @method Phaser.Math.RandomDataGenerator#integerInRange - * @since 3.0.0 - * - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * - * @return {number} A random number between min and max. - */ - integerInRange: function (min, max) - { - return Math.floor(this.realInRange(0, max - min + 1) + min); - }, - - /** - * Returns a random integer between and including min and max. - * This method is an alias for RandomDataGenerator.integerInRange. - * - * @method Phaser.Math.RandomDataGenerator#between - * @since 3.0.0 - * - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * - * @return {number} A random number between min and max. - */ - between: function (min, max) - { - return Math.floor(this.realInRange(0, max - min + 1) + min); - }, - - /** - * Returns a random real number between min and max. - * - * @method Phaser.Math.RandomDataGenerator#realInRange - * @since 3.0.0 - * - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * - * @return {number} A random number between min and max. - */ - realInRange: function (min, max) - { - return this.frac() * (max - min) + min; - }, - - /** - * Returns a random real number between -1 and 1. - * - * @method Phaser.Math.RandomDataGenerator#normal - * @since 3.0.0 - * - * @return {number} A random real number between -1 and 1. - */ - normal: function () - { - return 1 - (2 * this.frac()); - }, - - /** - * 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 - */ - uuid: function () - { - var a = ''; - var b = ''; - - for (b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac() * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') - { - // eslint-disable-next-line no-empty - } - - return b; - }, - - /** - * Returns a random element from within the given array. - * - * @method Phaser.Math.RandomDataGenerator#pick - * @since 3.0.0 - * - * @generic T - * @genericUse {T[]} - [array] - * @genericUse {T} - [$return] - * - * @param {T[]} array - The array to pick a random element from. - * - * @return {T} A random member of the array. - */ - pick: function (array) - { - return array[this.integerInRange(0, array.length - 1)]; - }, - - /** - * Returns a sign to be used with multiplication operator. - * - * @method Phaser.Math.RandomDataGenerator#sign - * @since 3.0.0 - * - * @return {number} -1 or +1. - */ - sign: function () - { - return this.pick(this.signs); - }, - - /** - * Returns a random element from within the given array, favoring the earlier entries. - * - * @method Phaser.Math.RandomDataGenerator#weightedPick - * @since 3.0.0 - * - * @generic T - * @genericUse {T[]} - [array] - * @genericUse {T} - [$return] - * - * @param {T[]} array - The array to pick a random element from. - * - * @return {T} A random member of the array. - */ - weightedPick: function (array) - { - return array[~~(Math.pow(this.frac(), 2) * (array.length - 1) + 0.5)]; - }, - - /** - * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. - * - * @method Phaser.Math.RandomDataGenerator#timestamp - * @since 3.0.0 - * - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * - * @return {number} A random timestamp between min and max. - */ - timestamp: function (min, max) - { - return this.realInRange(min || 946684800000, max || 1577862000000); - }, - - /** - * Returns a random angle between -180 and 180. - * - * @method Phaser.Math.RandomDataGenerator#angle - * @since 3.0.0 - * - * @return {number} A random number between -180 and 180. - */ - angle: function () - { - return this.integerInRange(-180, 180); - }, - - /** - * Returns a random rotation in radians, between -3.141 and 3.141 - * - * @method Phaser.Math.RandomDataGenerator#rotation - * @since 3.0.0 - * - * @return {number} A random number between -3.141 and 3.141 - */ - rotation: function () - { - return this.realInRange(-3.1415926, 3.1415926); - }, - - /** - * Gets or Sets the state of the generator. This allows you to retain the values - * that the generator is using between games, i.e. in a game save file. - * - * To seed this generator with a previously saved state you can pass it as the - * `seed` value in your game config, or call this method directly after Phaser has booted. - * - * Call this method with no parameters to return the current state. - * - * If providing a state it should match the same format that this method - * returns, which is a string with a header `!rnd` followed by the `c`, - * `s0`, `s1` and `s2` values respectively, each comma-delimited. - * - * @method Phaser.Math.RandomDataGenerator#state - * @since 3.0.0 - * - * @param {string} [state] - Generator state to be set. - * - * @return {string} The current state of the generator. - */ - state: function (state) - { - if (typeof state === 'string' && state.match(/^!rnd/)) - { - state = state.split(','); - - this.c = parseFloat(state[1]); - this.s0 = parseFloat(state[2]); - this.s1 = parseFloat(state[3]); - this.s2 = parseFloat(state[4]); - } - - return [ '!rnd', this.c, this.s0, this.s1, this.s2 ].join(','); - }, - - /** - * Shuffles the given array, using the current seed. - * - * @method Phaser.Math.RandomDataGenerator#shuffle - * @since 3.7.0 - * - * @generic T - * @genericUse {T[]} - [array,$return] - * - * @param {T[]} [array] - The array to be shuffled. - * - * @return {T[]} The shuffled array. - */ - shuffle: function (array) - { - var len = array.length - 1; - - for (var i = len; i > 0; i--) - { - var randomIndex = Math.floor(this.frac() * (i + 1)); - var itemAtIndex = array[randomIndex]; - - array[randomIndex] = array[i]; - array[i] = itemAtIndex; - } - - return array; - } - -}); - -module.exports = RandomDataGenerator; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); + +/** + * @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. + */ +var RandomDataGenerator = new Class({ + + initialize: + + function RandomDataGenerator (seeds) + { + if (seeds === undefined) { seeds = [ (Date.now() * Math.random()).toString() ]; } + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#c + * @type {number} + * @default 1 + * @private + * @since 3.0.0 + */ + this.c = 1; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#s0 + * @type {number} + * @default 0 + * @private + * @since 3.0.0 + */ + this.s0 = 0; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#s1 + * @type {number} + * @default 0 + * @private + * @since 3.0.0 + */ + this.s1 = 0; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#s2 + * @type {number} + * @default 0 + * @private + * @since 3.0.0 + */ + this.s2 = 0; + + /** + * Internal var. + * + * @name Phaser.Math.RandomDataGenerator#n + * @type {number} + * @default 0 + * @private + * @since 3.2.0 + */ + this.n = 0; + + /** + * Signs to choose from. + * + * @name Phaser.Math.RandomDataGenerator#signs + * @type {number[]} + * @since 3.0.0 + */ + this.signs = [ -1, 1 ]; + + if (seeds) + { + this.init(seeds); + } + }, + + /** + * Private random helper. + * + * @method Phaser.Math.RandomDataGenerator#rnd + * @since 3.0.0 + * @private + * + * @return {number} A random number. + */ + rnd: function () + { + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.Math.RandomDataGenerator#hash + * @since 3.0.0 + * @private + * + * @param {string} data - The value to hash. + * + * @return {number} The hashed value. + */ + hash: function (data) + { + var h; + var n = this.n; + + data = data.toString(); + + for (var i = 0; i < data.length; i++) + { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + this.n = n; + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + }, + + /** + * Initialize the state of the random data generator. + * + * @method Phaser.Math.RandomDataGenerator#init + * @since 3.0.0 + * + * @param {(string|string[])} seeds - The seeds to initialize the random data generator with. + */ + init: function (seeds) + { + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.Math.RandomDataGenerator#sow + * @since 3.0.0 + * + * @param {string[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) + { + // Always reset to default seed + this.n = 0xefc8249d; + this.s0 = this.hash(' '); + this.s1 = this.hash(' '); + this.s2 = this.hash(' '); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var seed = seeds[i]; + + this.s0 -= this.hash(seed); + this.s0 += ~~(this.s0 < 0); + this.s1 -= this.hash(seed); + this.s1 += ~~(this.s1 < 0); + this.s2 -= this.hash(seed); + this.s2 += ~~(this.s2 < 0); + } + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.Math.RandomDataGenerator#integer + * @since 3.0.0 + * + * @return {number} A random integer between 0 and 2^32. + */ + integer: function () + { + // 2^32 + return this.rnd() * 0x100000000; + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.Math.RandomDataGenerator#frac + * @since 3.0.0 + * + * @return {number} A random real number between 0 and 1. + */ + frac: function () + { + // 2^-53 + return this.rnd() + (this.rnd() * 0x200000 | 0) * 1.1102230246251565e-16; + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.Math.RandomDataGenerator#real + * @since 3.0.0 + * + * @return {number} A random real number between 0 and 2^32. + */ + real: function () + { + return this.integer() + this.frac(); + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.Math.RandomDataGenerator#integerInRange + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) + { + return Math.floor(this.realInRange(0, max - min + 1) + min); + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.Math.RandomDataGenerator#between + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random number between min and max. + */ + between: function (min, max) + { + return Math.floor(this.realInRange(0, max - min + 1) + min); + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.Math.RandomDataGenerator#realInRange + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) + { + return this.frac() * (max - min) + min; + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.Math.RandomDataGenerator#normal + * @since 3.0.0 + * + * @return {number} A random real number between -1 and 1. + */ + normal: function () + { + return 1 - (2 * this.frac()); + }, + + /** + * 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 + */ + uuid: function () + { + var a = ''; + var b = ''; + + for (b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac() * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') + { + // eslint-disable-next-line no-empty + } + + return b; + }, + + /** + * Returns a random element from within the given array. + * + * @method Phaser.Math.RandomDataGenerator#pick + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [array] + * @genericUse {T} - [$return] + * + * @param {T[]} array - The array to pick a random element from. + * + * @return {T} A random member of the array. + */ + pick: function (array) + { + return array[this.integerInRange(0, array.length - 1)]; + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.Math.RandomDataGenerator#sign + * @since 3.0.0 + * + * @return {number} -1 or +1. + */ + sign: function () + { + return this.pick(this.signs); + }, + + /** + * Returns a random element from within the given array, favoring the earlier entries. + * + * @method Phaser.Math.RandomDataGenerator#weightedPick + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [array] + * @genericUse {T} - [$return] + * + * @param {T[]} array - The array to pick a random element from. + * + * @return {T} A random member of the array. + */ + weightedPick: function (array) + { + return array[~~(Math.pow(this.frac(), 2) * (array.length - 1) + 0.5)]; + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.Math.RandomDataGenerator#timestamp + * @since 3.0.0 + * + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) + { + return this.realInRange(min || 946684800000, max || 1577862000000); + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.Math.RandomDataGenerator#angle + * @since 3.0.0 + * + * @return {number} A random number between -180 and 180. + */ + angle: function () + { + return this.integerInRange(-180, 180); + }, + + /** + * Returns a random rotation in radians, between -3.141 and 3.141 + * + * @method Phaser.Math.RandomDataGenerator#rotation + * @since 3.0.0 + * + * @return {number} A random number between -3.141 and 3.141 + */ + rotation: function () + { + return this.realInRange(-3.1415926, 3.1415926); + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.Math.RandomDataGenerator#state + * @since 3.0.0 + * + * @param {string} [state] - Generator state to be set. + * + * @return {string} The current state of the generator. + */ + state: function (state) + { + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return [ '!rnd', this.c, this.s0, this.s1, this.s2 ].join(','); + }, + + /** + * Shuffles the given array, using the current seed. + * + * @method Phaser.Math.RandomDataGenerator#shuffle + * @since 3.7.0 + * + * @generic T + * @genericUse {T[]} - [array,$return] + * + * @param {T[]} [array] - The array to be shuffled. + * + * @return {T[]} The shuffled array. + */ + shuffle: function (array) + { + var len = array.length - 1; + + for (var i = len; i > 0; i--) + { + var randomIndex = Math.floor(this.frac() * (i + 1)); + var itemAtIndex = array[randomIndex]; + + array[randomIndex] = array[i]; + array[i] = itemAtIndex; + } + + return array; + } + +}); + +module.exports = RandomDataGenerator; diff --git a/src/math/snap/SnapCeil.js b/src/math/snap/SnapCeil.js index 61f984ed9..78470ba58 100644 --- a/src/math/snap/SnapCeil.js +++ b/src/math/snap/SnapCeil.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Snap a value to nearest grid slice, using ceil. - * - * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `15`. - * As will `14` snap to `15`... but `16` will snap to `20`. - * - * @function Phaser.Math.Snap.Ceil - * @since 3.0.0 - * - * @param {number} value - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start=0] - Optional starting offset for gap. - * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. - * - * @return {number} The snapped value. - */ -var SnapCeil = function (value, gap, start, divide) -{ - if (start === undefined) { start = 0; } - - if (gap === 0) - { - return value; - } - - value -= start; - value = gap * Math.ceil(value / gap); - - return (divide) ? (start + value) / gap : start + value; -}; - -module.exports = SnapCeil; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `15`. + * As will `14` snap to `15`... but `16` will snap to `20`. + * + * @function Phaser.Math.Snap.Ceil + * @since 3.0.0 + * + * @param {number} value - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. + * + * @return {number} The snapped value. + */ +var SnapCeil = function (value, gap, start, divide) +{ + if (start === undefined) { start = 0; } + + if (gap === 0) + { + return value; + } + + value -= start; + value = gap * Math.ceil(value / gap); + + return (divide) ? (start + value) / gap : start + value; +}; + +module.exports = SnapCeil; diff --git a/src/math/snap/SnapFloor.js b/src/math/snap/SnapFloor.js index ab607a5c7..fa64f5388 100644 --- a/src/math/snap/SnapFloor.js +++ b/src/math/snap/SnapFloor.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Snap a value to nearest grid slice, using floor. - * - * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10`. - * As will `14` snap to `10`... but `16` will snap to `15`. - * - * @function Phaser.Math.Snap.Floor - * @since 3.0.0 - * - * @param {number} value - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start=0] - Optional starting offset for gap. - * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. - * - * @return {number} The snapped value. - */ -var SnapFloor = function (value, gap, start, divide) -{ - if (start === undefined) { start = 0; } - - if (gap === 0) - { - return value; - } - - value -= start; - value = gap * Math.floor(value / gap); - - return (divide) ? (start + value) / gap : start + value; -}; - -module.exports = SnapFloor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10`. + * As will `14` snap to `10`... but `16` will snap to `15`. + * + * @function Phaser.Math.Snap.Floor + * @since 3.0.0 + * + * @param {number} value - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. + * + * @return {number} The snapped value. + */ +var SnapFloor = function (value, gap, start, divide) +{ + if (start === undefined) { start = 0; } + + if (gap === 0) + { + return value; + } + + value -= start; + value = gap * Math.floor(value / gap); + + return (divide) ? (start + value) / gap : start + value; +}; + +module.exports = SnapFloor; diff --git a/src/math/snap/SnapTo.js b/src/math/snap/SnapTo.js index d0de1dcf6..f663482f3 100644 --- a/src/math/snap/SnapTo.js +++ b/src/math/snap/SnapTo.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Snap a value to nearest grid slice, using rounding. - * - * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10` whereas `14` will snap to `15`. - * - * @function Phaser.Math.Snap.To - * @since 3.0.0 - * - * @param {number} value - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start=0] - Optional starting offset for gap. - * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. - * - * @return {number} The snapped value. - */ -var SnapTo = function (value, gap, start, divide) -{ - if (start === undefined) { start = 0; } - - if (gap === 0) - { - return value; - } - - value -= start; - value = gap * Math.round(value / gap); - - return (divide) ? (start + value) / gap : start + value; -}; - -module.exports = SnapTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10` whereas `14` will snap to `15`. + * + * @function Phaser.Math.Snap.To + * @since 3.0.0 + * + * @param {number} value - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @param {boolean} [divide=false] - If `true` it will divide the snapped value by the gap before returning. + * + * @return {number} The snapped value. + */ +var SnapTo = function (value, gap, start, divide) +{ + if (start === undefined) { start = 0; } + + if (gap === 0) + { + return value; + } + + value -= start; + value = gap * Math.round(value / gap); + + return (divide) ? (start + value) / gap : start + value; +}; + +module.exports = SnapTo; diff --git a/src/math/snap/index.js b/src/math/snap/index.js index d793b9fdd..482ab5a32 100644 --- a/src/math/snap/index.js +++ b/src/math/snap/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Math.Snap - */ - -module.exports = { - - Ceil: require('./SnapCeil'), - Floor: require('./SnapFloor'), - To: require('./SnapTo') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Math.Snap + */ + +module.exports = { + + Ceil: require('./SnapCeil'), + Floor: require('./SnapFloor'), + To: require('./SnapTo') + +}; diff --git a/src/math/typedefs/index.js b/src/math/typedefs/index.js index 7800ca27d..afd2445ef 100644 --- a/src/math/typedefs/index.js +++ b/src/math/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Math - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Math + */ diff --git a/src/phaser-arcade-physics.js b/src/phaser-arcade-physics.js index d33ebc11d..d3f3c47ae 100644 --- a/src/phaser-arcade-physics.js +++ b/src/phaser-arcade-physics.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -require('./polyfills'); - -var CONST = require('./const'); -var Extend = require('./utils/object/Extend'); - -/** - * @namespace Phaser - */ - -/** - * The root types namespace. - * - * @namespace Phaser.Types - * @since 3.17.0 - */ - -var Phaser = { - - Actions: require('./actions'), - Animations: require('./animations'), - Cache: require('./cache'), - Cameras: require('./cameras'), - Core: require('./core'), - Class: require('./utils/Class'), - Create: require('./create'), - Curves: require('./curves'), - Data: require('./data'), - Display: require('./display'), - DOM: require('./dom'), - Events: require('./events'), - Game: require('./core/Game'), - GameObjects: require('./gameobjects'), - Geom: require('./geom'), - Input: require('./input'), - Loader: require('./loader'), - Math: require('./math'), - Physics: { - Arcade: require('./physics/arcade') - }, - Plugins: require('./plugins'), - Scale: require('./scale'), - Scene: require('./scene/Scene'), - Scenes: require('./scene'), - Structs: require('./structs'), - Textures: require('./textures'), - Tilemaps: require('./tilemaps'), - Time: require('./time'), - Tweens: require('./tweens'), - Utils: require('./utils') - -}; - -// Merge in the consts - -Phaser = Extend(false, Phaser, CONST); - -if (typeof FEATURE_SOUND) -{ - Phaser.Sound = require('./sound'); -} - -// Export it - -module.exports = Phaser; - -global.Phaser = Phaser; - -/* - * "Documentation is like pizza: when it is good, it is very, very good; - * and when it is bad, it is better than nothing." - * -- Dick Brandon - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +require('./polyfills'); + +var CONST = require('./const'); +var Extend = require('./utils/object/Extend'); + +/** + * @namespace Phaser + */ + +/** + * The root types namespace. + * + * @namespace Phaser.Types + * @since 3.17.0 + */ + +var Phaser = { + + Actions: require('./actions'), + Animations: require('./animations'), + Cache: require('./cache'), + Cameras: require('./cameras'), + Core: require('./core'), + Class: require('./utils/Class'), + Create: require('./create'), + Curves: require('./curves'), + Data: require('./data'), + Display: require('./display'), + DOM: require('./dom'), + Events: require('./events'), + Game: require('./core/Game'), + GameObjects: require('./gameobjects'), + Geom: require('./geom'), + Input: require('./input'), + Loader: require('./loader'), + Math: require('./math'), + Physics: { + Arcade: require('./physics/arcade') + }, + Plugins: require('./plugins'), + Scale: require('./scale'), + Scene: require('./scene/Scene'), + Scenes: require('./scene'), + Structs: require('./structs'), + Textures: require('./textures'), + Tilemaps: require('./tilemaps'), + Time: require('./time'), + Tweens: require('./tweens'), + Utils: require('./utils') + +}; + +// Merge in the consts + +Phaser = Extend(false, Phaser, CONST); + +if (typeof FEATURE_SOUND) +{ + Phaser.Sound = require('./sound'); +} + +// Export it + +module.exports = Phaser; + +global.Phaser = Phaser; + +/* + * "Documentation is like pizza: when it is good, it is very, very good; + * and when it is bad, it is better than nothing." + * -- Dick Brandon + */ diff --git a/src/phaser-core.js b/src/phaser-core.js index 512d78118..10756f09f 100644 --- a/src/phaser-core.js +++ b/src/phaser-core.js @@ -1,123 +1,123 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -require('./polyfills'); - -var CONST = require('./const'); -var Extend = require('./utils/object/Extend'); - -/** - * @namespace Phaser - */ - -/** - * The root types namespace. - * - * @namespace Phaser.Types - * @since 3.17.0 - */ - -var Phaser = { - - Animations: require('./animations'), - Cache: require('./cache'), - Cameras: { Scene2D: require('./cameras/2d') }, - Core: require('./core'), - Class: require('./utils/Class'), - Data: require('./data'), - Display: { Masks: require('./display/mask') }, - Events: require('./events'), - Game: require('./core/Game'), - GameObjects: { - DisplayList: require('./gameobjects/DisplayList'), - GameObjectCreator: require('./gameobjects/GameObjectCreator'), - GameObjectFactory: require('./gameobjects/GameObjectFactory'), - UpdateList: require('./gameobjects/UpdateList'), - Components: require('./gameobjects/components'), - BuildGameObject: require('./gameobjects/BuildGameObject'), - BuildGameObjectAnimation: require('./gameobjects/BuildGameObjectAnimation'), - GameObject: require('./gameobjects/GameObject'), - Graphics: require('./gameobjects/graphics/Graphics.js'), - Image: require('./gameobjects/image/Image'), - Sprite: require('./gameobjects/sprite/Sprite'), - Text: require('./gameobjects/text/static/Text'), - Factories: { - Graphics: require('./gameobjects/graphics/GraphicsFactory'), - Image: require('./gameobjects/image/ImageFactory'), - Sprite: require('./gameobjects/sprite/SpriteFactory'), - Text: require('./gameobjects/text/static/TextFactory') - }, - Creators: { - Graphics: require('./gameobjects/graphics/GraphicsCreator'), - Image: require('./gameobjects/image/ImageCreator'), - Sprite: require('./gameobjects/sprite/SpriteCreator'), - Text: require('./gameobjects/text/static/TextCreator') - } - }, - Input: require('./input'), - Loader: { - FileTypes: { - AnimationJSONFile: require('./loader/filetypes/AnimationJSONFile'), - AtlasJSONFile: require('./loader/filetypes/AtlasJSONFile'), - AudioFile: require('./loader/filetypes/AudioFile'), - AudioSpriteFile: require('./loader/filetypes/AudioSpriteFile'), - HTML5AudioFile: require('./loader/filetypes/HTML5AudioFile'), - ImageFile: require('./loader/filetypes/ImageFile'), - JSONFile: require('./loader/filetypes/JSONFile'), - MultiAtlasFile: require('./loader/filetypes/MultiAtlasFile'), - PluginFile: require('./loader/filetypes/PluginFile'), - ScriptFile: require('./loader/filetypes/ScriptFile'), - SpriteSheetFile: require('./loader/filetypes/SpriteSheetFile'), - TextFile: require('./loader/filetypes/TextFile'), - XMLFile: require('./loader/filetypes/XMLFile') - }, - File: require('./loader/File'), - FileTypesManager: require('./loader/FileTypesManager'), - GetURL: require('./loader/GetURL'), - LoaderPlugin: require('./loader/LoaderPlugin'), - MergeXHRSettings: require('./loader/MergeXHRSettings'), - MultiFile: require('./loader/MultiFile'), - XHRLoader: require('./loader/XHRLoader'), - XHRSettings: require('./loader/XHRSettings') - }, - Math: { - Between: require('./math/Between'), - DegToRad: require('./math/DegToRad'), - FloatBetween: require('./math/FloatBetween'), - RadToDeg: require('./math/RadToDeg'), - Vector2: require('./math/Vector2') - }, - Plugins: require('./plugins'), - Renderer: require('./renderer'), - Scale: require('./scale'), - Scene: require('./scene/Scene'), - Scenes: require('./scene'), - Structs: require('./structs'), - Textures: require('./textures'), - Time: require('./time'), - Tweens: require('./tweens') -}; - -// Merge in the consts - -Phaser = Extend(false, Phaser, CONST); - -// Export it - -if (typeof FEATURE_SOUND) -{ - Phaser.Sound = require('./sound'); -} - -module.exports = Phaser; - -global.Phaser = Phaser; - -/* - * "Documentation is like pizza: when it is good, it is very, very good; - * and when it is bad, it is better than nothing." - * -- Dick Brandon - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +require('./polyfills'); + +var CONST = require('./const'); +var Extend = require('./utils/object/Extend'); + +/** + * @namespace Phaser + */ + +/** + * The root types namespace. + * + * @namespace Phaser.Types + * @since 3.17.0 + */ + +var Phaser = { + + Animations: require('./animations'), + Cache: require('./cache'), + Cameras: { Scene2D: require('./cameras/2d') }, + Core: require('./core'), + Class: require('./utils/Class'), + Data: require('./data'), + Display: { Masks: require('./display/mask') }, + Events: require('./events'), + Game: require('./core/Game'), + GameObjects: { + DisplayList: require('./gameobjects/DisplayList'), + GameObjectCreator: require('./gameobjects/GameObjectCreator'), + GameObjectFactory: require('./gameobjects/GameObjectFactory'), + UpdateList: require('./gameobjects/UpdateList'), + Components: require('./gameobjects/components'), + BuildGameObject: require('./gameobjects/BuildGameObject'), + BuildGameObjectAnimation: require('./gameobjects/BuildGameObjectAnimation'), + GameObject: require('./gameobjects/GameObject'), + Graphics: require('./gameobjects/graphics/Graphics.js'), + Image: require('./gameobjects/image/Image'), + Sprite: require('./gameobjects/sprite/Sprite'), + Text: require('./gameobjects/text/static/Text'), + Factories: { + Graphics: require('./gameobjects/graphics/GraphicsFactory'), + Image: require('./gameobjects/image/ImageFactory'), + Sprite: require('./gameobjects/sprite/SpriteFactory'), + Text: require('./gameobjects/text/static/TextFactory') + }, + Creators: { + Graphics: require('./gameobjects/graphics/GraphicsCreator'), + Image: require('./gameobjects/image/ImageCreator'), + Sprite: require('./gameobjects/sprite/SpriteCreator'), + Text: require('./gameobjects/text/static/TextCreator') + } + }, + Input: require('./input'), + Loader: { + FileTypes: { + AnimationJSONFile: require('./loader/filetypes/AnimationJSONFile'), + AtlasJSONFile: require('./loader/filetypes/AtlasJSONFile'), + AudioFile: require('./loader/filetypes/AudioFile'), + AudioSpriteFile: require('./loader/filetypes/AudioSpriteFile'), + HTML5AudioFile: require('./loader/filetypes/HTML5AudioFile'), + ImageFile: require('./loader/filetypes/ImageFile'), + JSONFile: require('./loader/filetypes/JSONFile'), + MultiAtlasFile: require('./loader/filetypes/MultiAtlasFile'), + PluginFile: require('./loader/filetypes/PluginFile'), + ScriptFile: require('./loader/filetypes/ScriptFile'), + SpriteSheetFile: require('./loader/filetypes/SpriteSheetFile'), + TextFile: require('./loader/filetypes/TextFile'), + XMLFile: require('./loader/filetypes/XMLFile') + }, + File: require('./loader/File'), + FileTypesManager: require('./loader/FileTypesManager'), + GetURL: require('./loader/GetURL'), + LoaderPlugin: require('./loader/LoaderPlugin'), + MergeXHRSettings: require('./loader/MergeXHRSettings'), + MultiFile: require('./loader/MultiFile'), + XHRLoader: require('./loader/XHRLoader'), + XHRSettings: require('./loader/XHRSettings') + }, + Math: { + Between: require('./math/Between'), + DegToRad: require('./math/DegToRad'), + FloatBetween: require('./math/FloatBetween'), + RadToDeg: require('./math/RadToDeg'), + Vector2: require('./math/Vector2') + }, + Plugins: require('./plugins'), + Renderer: require('./renderer'), + Scale: require('./scale'), + Scene: require('./scene/Scene'), + Scenes: require('./scene'), + Structs: require('./structs'), + Textures: require('./textures'), + Time: require('./time'), + Tweens: require('./tweens') +}; + +// Merge in the consts + +Phaser = Extend(false, Phaser, CONST); + +// Export it + +if (typeof FEATURE_SOUND) +{ + Phaser.Sound = require('./sound'); +} + +module.exports = Phaser; + +global.Phaser = Phaser; + +/* + * "Documentation is like pizza: when it is good, it is very, very good; + * and when it is bad, it is better than nothing." + * -- Dick Brandon + */ diff --git a/src/phaser.js b/src/phaser.js index e0635c19e..00bb55b55 100644 --- a/src/phaser.js +++ b/src/phaser.js @@ -1,94 +1,94 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -require('./polyfills'); - -var CONST = require('./const'); -var Extend = require('./utils/object/Extend'); - -/** - * @namespace Phaser - */ - -var Phaser = { - - Actions: require('./actions'), - Animations: require('./animations'), - BlendModes: require('./renderer/BlendModes'), - Cache: require('./cache'), - Cameras: require('./cameras'), - Core: require('./core'), - Class: require('./utils/Class'), - Create: require('./create'), - Curves: require('./curves'), - Data: require('./data'), - Display: require('./display'), - DOM: require('./dom'), - Events: require('./events'), - Game: require('./core/Game'), - GameObjects: require('./gameobjects'), - Geom: require('./geom'), - Input: require('./input'), - Loader: require('./loader'), - Math: require('./math'), - Physics: require('./physics'), - Plugins: require('./plugins'), - Renderer: require('./renderer'), - Scale: require('./scale'), - ScaleModes: require('./renderer/ScaleModes'), - Scene: require('./scene/Scene'), - Scenes: require('./scene'), - Structs: require('./structs'), - Textures: require('./textures'), - Tilemaps: require('./tilemaps'), - Time: require('./time'), - Tweens: require('./tweens'), - Utils: require('./utils') - -}; - -// Merge in the optional plugins - -if (typeof FEATURE_SOUND) -{ - Phaser.Sound = require('./sound'); -} - -if (typeof PLUGIN_CAMERA3D) -{ - Phaser.Cameras.Sprite3D = require('../plugins/camera3d/src'); - Phaser.GameObjects.Sprite3D = require('../plugins/camera3d/src/sprite3d/Sprite3D'); - Phaser.GameObjects.Factories.Sprite3D = require('../plugins/camera3d/src/sprite3d/Sprite3DFactory'); - Phaser.GameObjects.Creators.Sprite3D = require('../plugins/camera3d/src/sprite3d/Sprite3DCreator'); -} - -if (typeof PLUGIN_FBINSTANT) -{ - Phaser.FacebookInstantGamesPlugin = require('../plugins/fbinstant/src/FacebookInstantGamesPlugin'); -} - -// Merge in the consts - -Phaser = Extend(false, Phaser, CONST); - -/** - * The root types namespace. - * - * @namespace Phaser.Types - * @since 3.17.0 - */ - -// Export it - -module.exports = Phaser; - -global.Phaser = Phaser; - -/* - * "Documentation is like pizza: when it is good, it is very, very good; - * and when it is bad, it is better than nothing." - * -- Dick Brandon - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +require('./polyfills'); + +var CONST = require('./const'); +var Extend = require('./utils/object/Extend'); + +/** + * @namespace Phaser + */ + +var Phaser = { + + Actions: require('./actions'), + Animations: require('./animations'), + BlendModes: require('./renderer/BlendModes'), + Cache: require('./cache'), + Cameras: require('./cameras'), + Core: require('./core'), + Class: require('./utils/Class'), + Create: require('./create'), + Curves: require('./curves'), + Data: require('./data'), + Display: require('./display'), + DOM: require('./dom'), + Events: require('./events'), + Game: require('./core/Game'), + GameObjects: require('./gameobjects'), + Geom: require('./geom'), + Input: require('./input'), + Loader: require('./loader'), + Math: require('./math'), + Physics: require('./physics'), + Plugins: require('./plugins'), + Renderer: require('./renderer'), + Scale: require('./scale'), + ScaleModes: require('./renderer/ScaleModes'), + Scene: require('./scene/Scene'), + Scenes: require('./scene'), + Structs: require('./structs'), + Textures: require('./textures'), + Tilemaps: require('./tilemaps'), + Time: require('./time'), + Tweens: require('./tweens'), + Utils: require('./utils') + +}; + +// Merge in the optional plugins + +if (typeof FEATURE_SOUND) +{ + Phaser.Sound = require('./sound'); +} + +if (typeof PLUGIN_CAMERA3D) +{ + Phaser.Cameras.Sprite3D = require('../plugins/camera3d/src'); + Phaser.GameObjects.Sprite3D = require('../plugins/camera3d/src/sprite3d/Sprite3D'); + Phaser.GameObjects.Factories.Sprite3D = require('../plugins/camera3d/src/sprite3d/Sprite3DFactory'); + Phaser.GameObjects.Creators.Sprite3D = require('../plugins/camera3d/src/sprite3d/Sprite3DCreator'); +} + +if (typeof PLUGIN_FBINSTANT) +{ + Phaser.FacebookInstantGamesPlugin = require('../plugins/fbinstant/src/FacebookInstantGamesPlugin'); +} + +// Merge in the consts + +Phaser = Extend(false, Phaser, CONST); + +/** + * The root types namespace. + * + * @namespace Phaser.Types + * @since 3.17.0 + */ + +// Export it + +module.exports = Phaser; + +global.Phaser = Phaser; + +/* + * "Documentation is like pizza: when it is good, it is very, very good; + * and when it is bad, it is better than nothing." + * -- Dick Brandon + */ diff --git a/src/physics/arcade/ArcadeImage.js b/src/physics/arcade/ArcadeImage.js index 2bab27da0..8b25a5735 100644 --- a/src/physics/arcade/ArcadeImage.js +++ b/src/physics/arcade/ArcadeImage.js @@ -1,94 +1,94 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('./components'); -var Image = require('../../gameobjects/image/Image'); - -/** - * @classdesc - * An Arcade Physics Image is an Image with an Arcade Physics body and related components. - * The body can be dynamic or static. - * - * The main difference between an Arcade Image and an Arcade Sprite is that you cannot animate an Arcade Image. - * - * @class Image - * @extends Phaser.GameObjects.Image - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Arcade.Components.Acceleration - * @extends Phaser.Physics.Arcade.Components.Angular - * @extends Phaser.Physics.Arcade.Components.Bounce - * @extends Phaser.Physics.Arcade.Components.Debug - * @extends Phaser.Physics.Arcade.Components.Drag - * @extends Phaser.Physics.Arcade.Components.Enable - * @extends Phaser.Physics.Arcade.Components.Friction - * @extends Phaser.Physics.Arcade.Components.Gravity - * @extends Phaser.Physics.Arcade.Components.Immovable - * @extends Phaser.Physics.Arcade.Components.Mass - * @extends Phaser.Physics.Arcade.Components.Size - * @extends Phaser.Physics.Arcade.Components.Velocity - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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. 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var ArcadeImage = new Class({ - - Extends: Image, - - Mixins: [ - Components.Acceleration, - Components.Angular, - Components.Bounce, - Components.Debug, - Components.Drag, - Components.Enable, - Components.Friction, - Components.Gravity, - Components.Immovable, - Components.Mass, - Components.Size, - Components.Velocity - ], - - initialize: - - function ArcadeImage (scene, x, y, texture, frame) - { - Image.call(this, scene, x, y, texture, frame); - - /** - * This Game Object's Physics Body. - * - * @name Phaser.Physics.Arcade.Image#body - * @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} - * @default null - * @since 3.0.0 - */ - this.body = null; - } - -}); - -module.exports = ArcadeImage; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('./components'); +var Image = require('../../gameobjects/image/Image'); + +/** + * @classdesc + * An Arcade Physics Image is an Image with an Arcade Physics body and related components. + * The body can be dynamic or static. + * + * The main difference between an Arcade Image and an Arcade Sprite is that you cannot animate an Arcade Image. + * + * @class Image + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Arcade.Components.Acceleration + * @extends Phaser.Physics.Arcade.Components.Angular + * @extends Phaser.Physics.Arcade.Components.Bounce + * @extends Phaser.Physics.Arcade.Components.Debug + * @extends Phaser.Physics.Arcade.Components.Drag + * @extends Phaser.Physics.Arcade.Components.Enable + * @extends Phaser.Physics.Arcade.Components.Friction + * @extends Phaser.Physics.Arcade.Components.Gravity + * @extends Phaser.Physics.Arcade.Components.Immovable + * @extends Phaser.Physics.Arcade.Components.Mass + * @extends Phaser.Physics.Arcade.Components.Size + * @extends Phaser.Physics.Arcade.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ArcadeImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Acceleration, + Components.Angular, + Components.Bounce, + Components.Debug, + Components.Drag, + Components.Enable, + Components.Friction, + Components.Gravity, + Components.Immovable, + Components.Mass, + Components.Size, + Components.Velocity + ], + + initialize: + + function ArcadeImage (scene, x, y, texture, frame) + { + Image.call(this, scene, x, y, texture, frame); + + /** + * This Game Object's Physics Body. + * + * @name Phaser.Physics.Arcade.Image#body + * @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} + * @default null + * @since 3.0.0 + */ + this.body = null; + } + +}); + +module.exports = ArcadeImage; diff --git a/src/physics/arcade/ArcadePhysics.js b/src/physics/arcade/ArcadePhysics.js index 4c9bc8158..e973543b3 100644 --- a/src/physics/arcade/ArcadePhysics.js +++ b/src/physics/arcade/ArcadePhysics.js @@ -1,683 +1,683 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var DegToRad = require('../../math/DegToRad'); -var DistanceBetween = require('../../math/distance/DistanceBetween'); -var DistanceSquared = require('../../math/distance/DistanceSquared'); -var Factory = require('./Factory'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Merge = require('../../utils/object/Merge'); -var OverlapCirc = require('./components/OverlapCirc'); -var OverlapRect = require('./components/OverlapRect'); -var PluginCache = require('../../plugins/PluginCache'); -var SceneEvents = require('../../scene/events'); -var Vector2 = require('../../math/Vector2'); -var World = require('./World'); - -/** - * @classdesc - * The Arcade Physics Plugin belongs to a Scene and sets up and manages the Scene's physics simulation. - * It also holds some useful methods for moving and rotating Arcade Physics Bodies. - * - * You can access it from within a Scene using `this.physics`. - * - * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable - * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. - * The separation that stops two objects penetrating may create a new penetration against a different object. If you - * require a high level of stability please consider using an alternative physics system, such as Matter.js. - * - * @class ArcadePhysics - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that this Plugin belongs to. - */ -var ArcadePhysics = new Class({ - - initialize: - - function ArcadePhysics (scene) - { - /** - * The Scene that this Plugin belongs to. - * - * @name Phaser.Physics.Arcade.ArcadePhysics#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The Scene's Systems. - * - * @name Phaser.Physics.Arcade.ArcadePhysics#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * A configuration object. Union of the `physics.arcade.*` properties of the GameConfig and SceneConfig objects. - * - * @name Phaser.Physics.Arcade.ArcadePhysics#config - * @type {object} - * @since 3.0.0 - */ - this.config = this.getConfig(); - - /** - * The physics simulation. - * - * @name Phaser.Physics.Arcade.ArcadePhysics#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world; - - /** - * An object holding the Arcade Physics factory methods. - * - * @name Phaser.Physics.Arcade.ArcadePhysics#add - * @type {Phaser.Physics.Arcade.Factory} - * @since 3.0.0 - */ - this.add; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.world = new World(this.scene, this.config); - this.add = new Factory(this.world); - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#start - * @private - * @since 3.5.0 - */ - start: function () - { - if (!this.world) - { - this.world = new World(this.scene, this.config); - this.add = new Factory(this.world); - } - - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); - eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * Creates the physics configuration for the current Scene. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#getConfig - * @since 3.0.0 - * - * @return {object} The physics configuration. - */ - getConfig: function () - { - var gameConfig = this.systems.game.config.physics; - var sceneConfig = this.systems.settings.physics; - - var config = Merge( - GetFastValue(sceneConfig, 'arcade', {}), - GetFastValue(gameConfig, 'arcade', {}) - ); - - return config; - }, - - /** - * Tests if Game Objects overlap. See {@link Phaser.Physics.Arcade.World#overlap} - * - * @method Phaser.Physics.Arcade.ArcadePhysics#overlap - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {*} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if at least one Game Object overlaps another. - * - * @see Phaser.Physics.Arcade.World#overlap - */ - overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) - { - if (overlapCallback === undefined) { overlapCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = overlapCallback; } - - return this.world.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); - }, - - /** - * Performs a collision check and separation between the two physics enabled objects given, which can be single - * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. - * - * If you don't require separation then use {@link #overlap} instead. - * - * If two Groups or arrays are passed, each member of one will be tested against each member of the other. - * - * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. - * - * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. - * - * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding - * objects are passed to it. - * - * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable - * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. - * The separation that stops two objects penetrating may create a new penetration against a different object. If you - * require a high level of stability please consider using an alternative physics system, such as Matter.js. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#collide - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {*} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if any overlapping Game Objects were separated, otherwise false. - * - * @see Phaser.Physics.Arcade.World#collide - */ - collide: function (object1, object2, collideCallback, processCallback, callbackContext) - { - if (collideCallback === undefined) { collideCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = collideCallback; } - - return this.world.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); - }, - - /** - * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. - * - * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for collision with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions - * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * - * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have - * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the - * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on - * dynamic maps, this method can prove very useful. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#collideTiles - * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE - * @since 3.17.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) - { - return this.world.collideTiles(sprite, tiles, collideCallback, processCallback, callbackContext); - }, - - /** - * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. - * - * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap - * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#overlapTiles - * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP - * @since 3.17.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects overlap. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - overlapTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) - { - return this.world.overlapTiles(sprite, tiles, collideCallback, processCallback, callbackContext); - }, - - /** - * Pauses the simulation. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#pause - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.World} The simulation. - */ - pause: function () - { - return this.world.pause(); - }, - - /** - * Resumes the simulation (if paused). - * - * @method Phaser.Physics.Arcade.ArcadePhysics#resume - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.World} The simulation. - */ - resume: function () - { - return this.world.resume(); - }, - - /** - * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) - * - * You must give a maximum speed value, beyond which the game object won't go any faster. - * - * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. - * Note: The game object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#accelerateTo - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. - * @param {number} x - The x coordinate to accelerate towards. - * @param {number} y - The y coordinate to accelerate towards. - * @param {number} [speed=60] - The acceleration (change in speed) in pixels per second squared. - * @param {number} [xSpeedMax=500] - The maximum x velocity the game object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the game object can reach. - * - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - accelerateTo: function (gameObject, x, y, speed, xSpeedMax, ySpeedMax) - { - if (speed === undefined) { speed = 60; } - - var angle = Math.atan2(y - gameObject.y, x - gameObject.x); - - gameObject.body.acceleration.setToPolar(angle, speed); - - if (xSpeedMax !== undefined && ySpeedMax !== undefined) - { - gameObject.body.maxVelocity.set(xSpeedMax, ySpeedMax); - } - - return angle; - }, - - /** - * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) - * - * You must give a maximum speed value, beyond which the game object won't go any faster. - * - * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. - * Note: The game object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#accelerateToObject - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. - * @param {Phaser.GameObjects.GameObject} destination - The Game Object to move towards. Can be any object but must have visible x/y properties. - * @param {number} [speed=60] - The acceleration (change in speed) in pixels per second squared. - * @param {number} [xSpeedMax=500] - The maximum x velocity the game object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the game object can reach. - * - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - accelerateToObject: function (gameObject, destination, speed, xSpeedMax, ySpeedMax) - { - return this.accelerateTo(gameObject, destination.x, destination.y, speed, xSpeedMax, ySpeedMax); - }, - - /** - * Finds the Body or Game Object closest to a source point or object. - * - * If a `targets` argument is passed, this method finds the closest of those. - * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. - * - * If no `targets` argument is passed, this method finds the closest Dynamic Body. - * - * If two or more targets are the exact same distance from the source point, only the first target - * is returned. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#closest - * @since 3.0.0 - * - * @param {any} source - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. - * @param {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[]|Phaser.GameObjects.GameObject[])} [targets] - The targets. - * - * @return {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody|Phaser.GameObjects.GameObject)} The target closest to the given source point. - */ - closest: function (source, targets) - { - if (!targets) - { - targets = this.world.bodies.entries; - } - - var min = Number.MAX_VALUE; - var closest = null; - var x = source.x; - var y = source.y; - var len = targets.length; - - for (var i = 0; i < len; i++) - { - var target = targets[i]; - var body = target.body || target; - - if (source === target || source === body || source === body.gameObject || source === body.center) - { - continue; - } - - var distance = DistanceSquared(x, y, body.center.x, body.center.y); - - if (distance < min) - { - closest = target; - min = distance; - } - } - - return closest; - }, - - /** - * Finds the Body or Game Object farthest from a source point or object. - * - * If a `targets` argument is passed, this method finds the farthest of those. - * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. - * - * If no `targets` argument is passed, this method finds the farthest Dynamic Body. - * - * If two or more targets are the exact same distance from the source point, only the first target - * is returned. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#furthest - * @since 3.0.0 - * - * @param {any} source - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. - * @param {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[]|Phaser.GameObjects.GameObject[])} [targets] - The targets. - * - * @return {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody|Phaser.GameObjects.GameObject)} The target farthest from the given source point. - */ - furthest: function (source, targets) - { - if (!targets) - { - targets = this.world.bodies.entries; - } - - var max = -1; - var farthest = null; - var x = source.x; - var y = source.y; - var len = targets.length; - - for (var i = 0; i < len; i++) - { - var target = targets[i]; - var body = target.body || target; - - if (source === target || source === body || source === body.gameObject || source === body.center) - { - continue; - } - - var distance = DistanceSquared(x, y, body.center.x, body.center.y); - - if (distance > max) - { - farthest = target; - max = distance; - } - - } - - return farthest; - }, - - /** - * Move the given display object towards the x/y coordinates at a steady velocity. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * - * @method Phaser.Physics.Arcade.ArcadePhysics#moveTo - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. - * @param {number} x - The x coordinate to move towards. - * @param {number} y - The y coordinate to move towards. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - moveTo: function (gameObject, x, y, speed, maxTime) - { - if (speed === undefined) { speed = 60; } - if (maxTime === undefined) { maxTime = 0; } - - var angle = Math.atan2(y - gameObject.y, x - gameObject.x); - - if (maxTime > 0) - { - // We know how many pixels we need to move, but how fast? - speed = DistanceBetween(gameObject.x, gameObject.y, x, y) / (maxTime / 1000); - } - - gameObject.body.velocity.setToPolar(angle, speed); - - return angle; - }, - - /** - * Move the given display object towards the destination object at a steady velocity. - * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * - * @method Phaser.Physics.Arcade.ArcadePhysics#moveToObject - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. - * @param {object} destination - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - moveToObject: function (gameObject, destination, speed, maxTime) - { - return this.moveTo(gameObject, destination.x, destination.y, speed, maxTime); - }, - - /** - * Given the angle (in degrees) and speed calculate the velocity and return it as a vector, or set it to the given vector object. - * One way to use this is: velocityFromAngle(angle, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#velocityFromAngle - * @since 3.0.0 - * - * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * @param {number} [speed=60] - The speed it will move, in pixels per second squared. - * @param {Phaser.Math.Vector2} [vec2] - The Vector2 in which the x and y properties will be set to the calculated velocity. - * - * @return {Phaser.Math.Vector2} The Vector2 that stores the velocity. - */ - velocityFromAngle: function (angle, speed, vec2) - { - if (speed === undefined) { speed = 60; } - if (vec2 === undefined) { vec2 = new Vector2(); } - - return vec2.setToPolar(DegToRad(angle), speed); - }, - - /** - * Given the rotation (in radians) and speed calculate the velocity and return it as a vector, or set it to the given vector object. - * One way to use this is: velocityFromRotation(rotation, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#velocityFromRotation - * @since 3.0.0 - * - * @param {number} rotation - The angle in radians. - * @param {number} [speed=60] - The speed it will move, in pixels per second squared - * @param {Phaser.Math.Vector2} [vec2] - The Vector2 in which the x and y properties will be set to the calculated velocity. - * - * @return {Phaser.Math.Vector2} The Vector2 that stores the velocity. - */ - velocityFromRotation: function (rotation, speed, vec2) - { - if (speed === undefined) { speed = 60; } - if (vec2 === undefined) { vec2 = new Vector2(); } - - return vec2.setToPolar(rotation, speed); - }, - - /** - * This method will search the given rectangular area and return an array of all physics bodies that - * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. - * - * A body only has to intersect with the search area to be considered, it doesn't have to be fully - * contained within it. - * - * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, - * otherwise the search is O(N) for Dynamic Bodies. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#overlapRect - * @since 3.17.0 - * - * @param {number} x - The top-left x coordinate of the area to search within. - * @param {number} y - The top-left y coordinate of the area to search within. - * @param {number} width - The width of the area to search within. - * @param {number} height - The height of the area to search within. - * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? - * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? - * - * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. - */ - overlapRect: function (x, y, width, height, includeDynamic, includeStatic) - { - return OverlapRect(this.world, x, y, width, height, includeDynamic, includeStatic); - }, - - /** - * This method will search the given circular area and return an array of all physics bodies that - * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. - * - * A body only has to intersect with the search area to be considered, it doesn't have to be fully - * contained within it. - * - * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, - * otherwise the search is O(N) for Dynamic Bodies. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#overlapCirc - * @since 3.21.0 - * - * @param {number} x - The x coordinate of the center of the area to search within. - * @param {number} y - The y coordinate of the center of the area to search within. - * @param {number} radius - The radius of the area to search within. - * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? - * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? - * - * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. - */ - overlapCirc: function (x, y, radius, includeDynamic, includeStatic) - { - return OverlapCirc(this.world, x, y, radius, includeDynamic, includeStatic); - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - if (!this.world) - { - // Already destroyed - return; - } - - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); - eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - - this.add.destroy(); - this.world.destroy(); - - this.add = null; - this.world = null; - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Physics.Arcade.ArcadePhysics#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('ArcadePhysics', ArcadePhysics, 'arcadePhysics'); - -module.exports = ArcadePhysics; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var DegToRad = require('../../math/DegToRad'); +var DistanceBetween = require('../../math/distance/DistanceBetween'); +var DistanceSquared = require('../../math/distance/DistanceSquared'); +var Factory = require('./Factory'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Merge = require('../../utils/object/Merge'); +var OverlapCirc = require('./components/OverlapCirc'); +var OverlapRect = require('./components/OverlapRect'); +var PluginCache = require('../../plugins/PluginCache'); +var SceneEvents = require('../../scene/events'); +var Vector2 = require('../../math/Vector2'); +var World = require('./World'); + +/** + * @classdesc + * The Arcade Physics Plugin belongs to a Scene and sets up and manages the Scene's physics simulation. + * It also holds some useful methods for moving and rotating Arcade Physics Bodies. + * + * You can access it from within a Scene using `this.physics`. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * + * @class ArcadePhysics + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this Plugin belongs to. + */ +var ArcadePhysics = new Class({ + + initialize: + + function ArcadePhysics (scene) + { + /** + * The Scene that this Plugin belongs to. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene's Systems. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * A configuration object. Union of the `physics.arcade.*` properties of the GameConfig and SceneConfig objects. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#config + * @type {object} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * The physics simulation. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world; + + /** + * An object holding the Arcade Physics factory methods. + * + * @name Phaser.Physics.Arcade.ArcadePhysics#add + * @type {Phaser.Physics.Arcade.Factory} + * @since 3.0.0 + */ + this.add; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Creates the physics configuration for the current Scene. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#getConfig + * @since 3.0.0 + * + * @return {object} The physics configuration. + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'arcade', {}), + GetFastValue(gameConfig, 'arcade', {}) + ); + + return config; + }, + + /** + * Tests if Game Objects overlap. See {@link Phaser.Physics.Arcade.World#overlap} + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlap + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {*} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if at least one Game Object overlaps another. + * + * @see Phaser.Physics.Arcade.World#overlap + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) + { + if (overlapCallback === undefined) { overlapCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = overlapCallback; } + + return this.world.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + }, + + /** + * Performs a collision check and separation between the two physics enabled objects given, which can be single + * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. + * + * If you don't require separation then use {@link #overlap} instead. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. + * + * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding + * objects are passed to it. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#collide + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {*} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any overlapping Game Objects were separated, otherwise false. + * + * @see Phaser.Physics.Arcade.World#collide + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + return this.world.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + }, + + /** + * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. + * + * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for collision with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions + * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have + * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the + * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on + * dynamic maps, this method can prove very useful. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#collideTiles + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + return this.world.collideTiles(sprite, tiles, collideCallback, processCallback, callbackContext); + }, + + /** + * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. + * + * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap + * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlapTiles + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + overlapTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + return this.world.overlapTiles(sprite, tiles, collideCallback, processCallback, callbackContext); + }, + + /** + * Pauses the simulation. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#pause + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} The simulation. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * Resumes the simulation (if paused). + * + * @method Phaser.Physics.Arcade.ArcadePhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} The simulation. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) + * + * You must give a maximum speed value, beyond which the game object won't go any faster. + * + * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. + * Note: The game object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#accelerateTo + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The acceleration (change in speed) in pixels per second squared. + * @param {number} [xSpeedMax=500] - The maximum x velocity the game object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the game object can reach. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + accelerateTo: function (gameObject, x, y, speed, xSpeedMax, ySpeedMax) + { + if (speed === undefined) { speed = 60; } + + var angle = Math.atan2(y - gameObject.y, x - gameObject.x); + + gameObject.body.acceleration.setToPolar(angle, speed); + + if (xSpeedMax !== undefined && ySpeedMax !== undefined) + { + gameObject.body.maxVelocity.set(xSpeedMax, ySpeedMax); + } + + return angle; + }, + + /** + * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) + * + * You must give a maximum speed value, beyond which the game object won't go any faster. + * + * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. + * Note: The game object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#accelerateToObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {Phaser.GameObjects.GameObject} destination - The Game Object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The acceleration (change in speed) in pixels per second squared. + * @param {number} [xSpeedMax=500] - The maximum x velocity the game object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the game object can reach. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + accelerateToObject: function (gameObject, destination, speed, xSpeedMax, ySpeedMax) + { + return this.accelerateTo(gameObject, destination.x, destination.y, speed, xSpeedMax, ySpeedMax); + }, + + /** + * Finds the Body or Game Object closest to a source point or object. + * + * If a `targets` argument is passed, this method finds the closest of those. + * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. + * + * If no `targets` argument is passed, this method finds the closest Dynamic Body. + * + * If two or more targets are the exact same distance from the source point, only the first target + * is returned. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#closest + * @since 3.0.0 + * + * @param {any} source - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[]|Phaser.GameObjects.GameObject[])} [targets] - The targets. + * + * @return {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody|Phaser.GameObjects.GameObject)} The target closest to the given source point. + */ + closest: function (source, targets) + { + if (!targets) + { + targets = this.world.bodies.entries; + } + + var min = Number.MAX_VALUE; + var closest = null; + var x = source.x; + var y = source.y; + var len = targets.length; + + for (var i = 0; i < len; i++) + { + var target = targets[i]; + var body = target.body || target; + + if (source === target || source === body || source === body.gameObject || source === body.center) + { + continue; + } + + var distance = DistanceSquared(x, y, body.center.x, body.center.y); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * Finds the Body or Game Object farthest from a source point or object. + * + * If a `targets` argument is passed, this method finds the farthest of those. + * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. + * + * If no `targets` argument is passed, this method finds the farthest Dynamic Body. + * + * If two or more targets are the exact same distance from the source point, only the first target + * is returned. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#furthest + * @since 3.0.0 + * + * @param {any} source - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[]|Phaser.GameObjects.GameObject[])} [targets] - The targets. + * + * @return {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody|Phaser.GameObjects.GameObject)} The target farthest from the given source point. + */ + furthest: function (source, targets) + { + if (!targets) + { + targets = this.world.bodies.entries; + } + + var max = -1; + var farthest = null; + var x = source.x; + var y = source.y; + var len = targets.length; + + for (var i = 0; i < len; i++) + { + var target = targets[i]; + var body = target.body || target; + + if (source === target || source === body || source === body.gameObject || source === body.center) + { + continue; + } + + var distance = DistanceSquared(x, y, body.center.x, body.center.y); + + if (distance > max) + { + farthest = target; + max = distance; + } + + } + + return farthest; + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade.ArcadePhysics#moveTo + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveTo: function (gameObject, x, y, speed, maxTime) + { + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - gameObject.y, x - gameObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = DistanceBetween(gameObject.x, gameObject.y, x, y) / (maxTime / 1000); + } + + gameObject.body.velocity.setToPolar(angle, speed); + + return angle; + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade.ArcadePhysics#moveToObject + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Any Game Object with an Arcade Physics body. + * @param {object} destination - Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (gameObject, destination, speed, maxTime) + { + return this.moveTo(gameObject, destination.x, destination.y, speed, maxTime); + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a vector, or set it to the given vector object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#velocityFromAngle + * @since 3.0.0 + * + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second squared. + * @param {Phaser.Math.Vector2} [vec2] - The Vector2 in which the x and y properties will be set to the calculated velocity. + * + * @return {Phaser.Math.Vector2} The Vector2 that stores the velocity. + */ + velocityFromAngle: function (angle, speed, vec2) + { + if (speed === undefined) { speed = 60; } + if (vec2 === undefined) { vec2 = new Vector2(); } + + return vec2.setToPolar(DegToRad(angle), speed); + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a vector, or set it to the given vector object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#velocityFromRotation + * @since 3.0.0 + * + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second squared + * @param {Phaser.Math.Vector2} [vec2] - The Vector2 in which the x and y properties will be set to the calculated velocity. + * + * @return {Phaser.Math.Vector2} The Vector2 that stores the velocity. + */ + velocityFromRotation: function (rotation, speed, vec2) + { + if (speed === undefined) { speed = 60; } + if (vec2 === undefined) { vec2 = new Vector2(); } + + return vec2.setToPolar(rotation, speed); + }, + + /** + * This method will search the given rectangular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, + * otherwise the search is O(N) for Dynamic Bodies. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlapRect + * @since 3.17.0 + * + * @param {number} x - The top-left x coordinate of the area to search within. + * @param {number} y - The top-left y coordinate of the area to search within. + * @param {number} width - The width of the area to search within. + * @param {number} height - The height of the area to search within. + * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? + * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? + * + * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. + */ + overlapRect: function (x, y, width, height, includeDynamic, includeStatic) + { + return OverlapRect(this.world, x, y, width, height, includeDynamic, includeStatic); + }, + + /** + * This method will search the given circular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, + * otherwise the search is O(N) for Dynamic Bodies. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#overlapCirc + * @since 3.21.0 + * + * @param {number} x - The x coordinate of the center of the area to search within. + * @param {number} y - The y coordinate of the center of the area to search within. + * @param {number} radius - The radius of the area to search within. + * @param {boolean} [includeDynamic=true] - Should the search include Dynamic Bodies? + * @param {boolean} [includeStatic=false] - Should the search include Static Bodies? + * + * @return {(Phaser.Physics.Arcade.Body[]|Phaser.Physics.Arcade.StaticBody[])} An array of bodies that overlap with the given area. + */ + overlapCirc: function (x, y, radius, includeDynamic, includeStatic) + { + return OverlapCirc(this.world, x, y, radius, includeDynamic, includeStatic); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + if (!this.world) + { + // Already destroyed + return; + } + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.add.destroy(); + this.world.destroy(); + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Arcade.ArcadePhysics#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('ArcadePhysics', ArcadePhysics, 'arcadePhysics'); + +module.exports = ArcadePhysics; diff --git a/src/physics/arcade/ArcadeSprite.js b/src/physics/arcade/ArcadeSprite.js index 5d579afee..b02a3a584 100644 --- a/src/physics/arcade/ArcadeSprite.js +++ b/src/physics/arcade/ArcadeSprite.js @@ -1,95 +1,95 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('./components'); -var Sprite = require('../../gameobjects/sprite/Sprite'); - -/** - * @classdesc - * An Arcade Physics Sprite is a Sprite with an Arcade Physics body and related components. - * The body can be dynamic or static. - * - * The main difference between an Arcade Sprite and an Arcade Image is that you cannot animate an Arcade Image. - * If you do not require animation then you can safely use Arcade Images instead of Arcade Sprites. - * - * @class Sprite - * @extends Phaser.GameObjects.Sprite - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Arcade.Components.Acceleration - * @extends Phaser.Physics.Arcade.Components.Angular - * @extends Phaser.Physics.Arcade.Components.Bounce - * @extends Phaser.Physics.Arcade.Components.Debug - * @extends Phaser.Physics.Arcade.Components.Drag - * @extends Phaser.Physics.Arcade.Components.Enable - * @extends Phaser.Physics.Arcade.Components.Friction - * @extends Phaser.Physics.Arcade.Components.Gravity - * @extends Phaser.Physics.Arcade.Components.Immovable - * @extends Phaser.Physics.Arcade.Components.Mass - * @extends Phaser.Physics.Arcade.Components.Size - * @extends Phaser.Physics.Arcade.Components.Velocity - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @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. 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - */ -var ArcadeSprite = new Class({ - - Extends: Sprite, - - Mixins: [ - Components.Acceleration, - Components.Angular, - Components.Bounce, - Components.Debug, - Components.Drag, - Components.Enable, - Components.Friction, - Components.Gravity, - Components.Immovable, - Components.Mass, - Components.Size, - Components.Velocity - ], - - initialize: - - function ArcadeSprite (scene, x, y, texture, frame) - { - Sprite.call(this, scene, x, y, texture, frame); - - /** - * This Game Object's Physics Body. - * - * @name Phaser.Physics.Arcade.Sprite#body - * @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} - * @default null - * @since 3.0.0 - */ - this.body = null; - } - -}); - -module.exports = ArcadeSprite; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('./components'); +var Sprite = require('../../gameobjects/sprite/Sprite'); + +/** + * @classdesc + * An Arcade Physics Sprite is a Sprite with an Arcade Physics body and related components. + * The body can be dynamic or static. + * + * The main difference between an Arcade Sprite and an Arcade Image is that you cannot animate an Arcade Image. + * If you do not require animation then you can safely use Arcade Images instead of Arcade Sprites. + * + * @class Sprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Arcade.Components.Acceleration + * @extends Phaser.Physics.Arcade.Components.Angular + * @extends Phaser.Physics.Arcade.Components.Bounce + * @extends Phaser.Physics.Arcade.Components.Debug + * @extends Phaser.Physics.Arcade.Components.Drag + * @extends Phaser.Physics.Arcade.Components.Enable + * @extends Phaser.Physics.Arcade.Components.Friction + * @extends Phaser.Physics.Arcade.Components.Gravity + * @extends Phaser.Physics.Arcade.Components.Immovable + * @extends Phaser.Physics.Arcade.Components.Mass + * @extends Phaser.Physics.Arcade.Components.Size + * @extends Phaser.Physics.Arcade.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @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. 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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + */ +var ArcadeSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Acceleration, + Components.Angular, + Components.Bounce, + Components.Debug, + Components.Drag, + Components.Enable, + Components.Friction, + Components.Gravity, + Components.Immovable, + Components.Mass, + Components.Size, + Components.Velocity + ], + + initialize: + + function ArcadeSprite (scene, x, y, texture, frame) + { + Sprite.call(this, scene, x, y, texture, frame); + + /** + * This Game Object's Physics Body. + * + * @name Phaser.Physics.Arcade.Sprite#body + * @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} + * @default null + * @since 3.0.0 + */ + this.body = null; + } + +}); + +module.exports = ArcadeSprite; diff --git a/src/physics/arcade/Body.js b/src/physics/arcade/Body.js index 37155b34c..8b52d691e 100644 --- a/src/physics/arcade/Body.js +++ b/src/physics/arcade/Body.js @@ -1,2329 +1,2329 @@ -/** - * @author Richard Davey - * @author Benjamin D. Richards - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var CONST = require('./const'); -var Events = require('./events'); -var RadToDeg = require('../../math/RadToDeg'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var RectangleContains = require('../../geom/rectangle/Contains'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Dynamic Arcade Body. - * - * Its static counterpart is {@link Phaser.Physics.Arcade.StaticBody}. - * - * @class Body - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics simulation this Body belongs to. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object this Body belongs to. - */ -var Body = new Class({ - - initialize: - - function Body (world, gameObject) - { - var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; - var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; - - /** - * The Arcade Physics simulation this Body belongs to. - * - * @name Phaser.Physics.Arcade.Body#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The Game Object this Body belongs to. - * - * @name Phaser.Physics.Arcade.Body#gameObject - * @type {Phaser.GameObjects.GameObject} - * @since 3.0.0 - */ - this.gameObject = gameObject; - - /** - * Transformations applied to this Body. - * - * @name Phaser.Physics.Arcade.Body#transform - * @type {object} - * @since 3.4.0 - */ - this.transform = { - x: gameObject.x, - y: gameObject.y, - rotation: gameObject.angle, - scaleX: gameObject.scaleX, - scaleY: gameObject.scaleY, - displayOriginX: gameObject.displayOriginX, - displayOriginY: gameObject.displayOriginY - }; - - /** - * Whether the Body's boundary is drawn to the debug display. - * - * @name Phaser.Physics.Arcade.Body#debugShowBody - * @type {boolean} - * @since 3.0.0 - */ - this.debugShowBody = world.defaults.debugShowBody; - - /** - * Whether the Body's velocity is drawn to the debug display. - * - * @name Phaser.Physics.Arcade.Body#debugShowVelocity - * @type {boolean} - * @since 3.0.0 - */ - this.debugShowVelocity = world.defaults.debugShowVelocity; - - /** - * The color of this Body on the debug display. - * - * @name Phaser.Physics.Arcade.Body#debugBodyColor - * @type {integer} - * @since 3.0.0 - */ - this.debugBodyColor = world.defaults.bodyDebugColor; - - /** - * Whether this Body is updated by the physics simulation. - * - * @name Phaser.Physics.Arcade.Body#enable - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enable = true; - - /** - * Whether this Body's boundary is circular (true) or rectangular (false). - * - * @name Phaser.Physics.Arcade.Body#isCircle - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#setCircle - */ - this.isCircle = false; - - /** - * If this Body is circular, this is the unscaled radius of the Body's boundary, as set by setCircle(), in source pixels. - * The true radius is equal to `halfWidth`. - * - * @name Phaser.Physics.Arcade.Body#radius - * @type {number} - * @default 0 - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#setCircle - */ - this.radius = 0; - - /** - * The offset of this Body's position from its Game Object's position, in source pixels. - * - * @name Phaser.Physics.Arcade.Body#offset - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#setOffset - */ - this.offset = new Vector2(); - - /** - * The position of this Body within the simulation. - * - * @name Phaser.Physics.Arcade.Body#position - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.position = new Vector2( - gameObject.x - gameObject.scaleX * gameObject.displayOriginX, - gameObject.y - gameObject.scaleY * gameObject.displayOriginY - ); - - /** - * The position of this Body during the previous step. - * - * @name Phaser.Physics.Arcade.Body#prev - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.prev = new Vector2(gameObject.x, gameObject.y); - - /** - * The position of this Body during the previous frame. - * - * @name Phaser.Physics.Arcade.Body#prevFrame - * @type {Phaser.Math.Vector2} - * @since 3.20.0 - */ - this.prevFrame = new Vector2(gameObject.x, gameObject.y); - - /** - * Whether this Body's `rotation` is affected by its angular acceleration and angular velocity. - * - * @name Phaser.Physics.Arcade.Body#allowRotation - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.allowRotation = true; - - /** - * 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 boundary, which is always an axis-aligned rectangle or a circle. - * - * @name Phaser.Physics.Arcade.Body#rotation - * @type {number} - * @since 3.0.0 - */ - this.rotation = gameObject.angle; - - /** - * The Body rotation, in degrees, during the previous step. - * - * @name Phaser.Physics.Arcade.Body#preRotation - * @type {number} - * @since 3.0.0 - */ - this.preRotation = gameObject.angle; - - /** - * The width of the Body boundary, in pixels. - * If the Body is circular, this is also the diameter. - * If you wish to change the width use the `Body.setSize` method. - * - * @name Phaser.Physics.Arcade.Body#width - * @type {number} - * @readonly - * @default 64 - * @since 3.0.0 - */ - this.width = width; - - /** - * The height of the Body boundary, in pixels. - * If the Body is circular, this is also the diameter. - * If you wish to change the height use the `Body.setSize` method. - * - * @name Phaser.Physics.Arcade.Body#height - * @type {number} - * @readonly - * @default 64 - * @since 3.0.0 - */ - this.height = height; - - /** - * The unscaled width of the Body, in source pixels, as set by setSize(). - * The default is the width of the Body's Game Object's texture frame. - * - * @name Phaser.Physics.Arcade.Body#sourceWidth - * @type {number} - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#setSize - */ - this.sourceWidth = width; - - /** - * The unscaled height of the Body, in source pixels, as set by setSize(). - * The default is the height of the Body's Game Object's texture frame. - * - * @name Phaser.Physics.Arcade.Body#sourceHeight - * @type {number} - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#setSize - */ - this.sourceHeight = height; - - if (gameObject.frame) - { - this.sourceWidth = gameObject.frame.realWidth; - this.sourceHeight = gameObject.frame.realHeight; - } - - /** - * Half the Body's width, in pixels. - * - * @name Phaser.Physics.Arcade.Body#halfWidth - * @type {number} - * @since 3.0.0 - */ - this.halfWidth = Math.abs(width / 2); - - /** - * Half the Body's height, in pixels. - * - * @name Phaser.Physics.Arcade.Body#halfHeight - * @type {number} - * @since 3.0.0 - */ - this.halfHeight = Math.abs(height / 2); - - /** - * The center of the Body's boundary. - * The midpoint of its `position` (top-left corner) and its bottom-right corner. - * - * @name Phaser.Physics.Arcade.Body#center - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); - - /** - * The Body's velocity, in pixels per second. - * - * @name Phaser.Physics.Arcade.Body#velocity - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.velocity = new Vector2(); - - /** - * The Body's change in position (due to velocity) at the last step, in pixels. - * - * The size of this value depends on the simulation's step rate. - * - * @name Phaser.Physics.Arcade.Body#newVelocity - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.0.0 - */ - this.newVelocity = new Vector2(); - - /** - * The Body's absolute maximum change in position, in pixels per step. - * - * @name Phaser.Physics.Arcade.Body#deltaMax - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.deltaMax = new Vector2(); - - /** - * The Body's change in velocity, in pixels per second squared. - * - * @name Phaser.Physics.Arcade.Body#acceleration - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.acceleration = new Vector2(); - - /** - * Whether this Body's velocity is affected by its `drag`. - * - * @name Phaser.Physics.Arcade.Body#allowDrag - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.allowDrag = true; - - /** - * Absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * - * @name Phaser.Physics.Arcade.Body#drag - * @type {(Phaser.Math.Vector2|number)} - * @since 3.0.0 - */ - this.drag = new Vector2(); - - /** - * Whether this Body's position is affected by gravity (local or world). - * - * @name Phaser.Physics.Arcade.Body#allowGravity - * @type {boolean} - * @default true - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#gravity - * @see Phaser.Physics.Arcade.World#gravity - */ - this.allowGravity = true; - - /** - * Acceleration due to gravity (specific to this Body), in pixels per second squared. - * Total gravity is the sum of this vector and the simulation's `gravity`. - * - * @name Phaser.Physics.Arcade.Body#gravity - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - * @see Phaser.Physics.Arcade.World#gravity - */ - this.gravity = new Vector2(); - - /** - * Rebound following a collision, relative to 1. - * - * @name Phaser.Physics.Arcade.Body#bounce - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.bounce = new Vector2(); - - /** - * Rebound following a collision with the world boundary, relative to 1. - * If null, `bounce` is used instead. - * - * @name Phaser.Physics.Arcade.Body#worldBounce - * @type {?Phaser.Math.Vector2} - * @default null - * @since 3.0.0 - */ - this.worldBounce = null; - - /** - * The rectangle used for world boundary collisions. - * - * By default it is set to the world boundary rectangle. Or, if this Body was - * created by a Physics Group, then whatever rectangle that Group defined. - * - * You can also change it by using the `Body.setBoundsRectangle` method. - * - * @name Phaser.Physics.Arcade.Body#customBoundsRectangle - * @type {?Phaser.Geom.Rectangle} - * @since 3.20 - */ - this.customBoundsRectangle = world.bounds; - - // If true this Body will dispatch events - - /** - * Whether the simulation emits a `worldbounds` event when this Body collides with the world boundary (and `collideWorldBounds` is also true). - * - * @name Phaser.Physics.Arcade.Body#onWorldBounds - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.Physics.Arcade.World#worldboundsEvent - */ - this.onWorldBounds = false; - - /** - * Whether the simulation emits a `collide` event when this Body collides with another. - * - * @name Phaser.Physics.Arcade.Body#onCollide - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.Physics.Arcade.World#collideEvent - */ - this.onCollide = false; - - /** - * Whether the simulation emits an `overlap` event when this Body overlaps with another. - * - * @name Phaser.Physics.Arcade.Body#onOverlap - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.Physics.Arcade.World#overlapEvent - */ - this.onOverlap = false; - - /** - * The Body's absolute maximum velocity, in pixels per second. - * The horizontal and vertical components are applied separately. - * - * @name Phaser.Physics.Arcade.Body#maxVelocity - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.maxVelocity = new Vector2(10000, 10000); - - /** - * The maximum speed this Body is allowed to reach, in pixels per second. - * - * If not negative it limits the scalar value of speed. - * - * Any negative value means no maximum is being applied (the default). - * - * @name Phaser.Physics.Arcade.Body#maxSpeed - * @type {number} - * @default -1 - * @since 3.16.0 - */ - this.maxSpeed = -1; - - /** - * If this Body is `immovable` and in motion, `friction` is the proportion of this Body's motion received by the riding Body on each axis, relative to 1. - * The horizontal component (x) is applied only when two colliding Bodies are separated vertically. - * The vertical component (y) is applied only when two colliding Bodies are separated horizontally. - * The default value (1, 0) moves the riding Body horizontally in equal proportion to this Body and vertically not at all. - * - * @name Phaser.Physics.Arcade.Body#friction - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.friction = new Vector2(1, 0); - - /** - * If this Body is using `drag` for deceleration this property controls how the drag is applied. - * If set to `true` drag will use a damping effect rather than a linear approach. If you are - * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in - * the game Asteroids) then you will get a far smoother and more visually correct deceleration - * by using damping, avoiding the axis-drift that is prone with linear deceleration. - * - * If you enable this property then you should use far smaller `drag` values than with linear, as - * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow - * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. - * - * @name Phaser.Physics.Arcade.Body#useDamping - * @type {boolean} - * @default false - * @since 3.10.0 - */ - this.useDamping = false; - - /** - * The rate of change of this Body's `rotation`, in degrees per second. - * - * @name Phaser.Physics.Arcade.Body#angularVelocity - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.angularVelocity = 0; - - /** - * The Body's angular acceleration (change in angular velocity), in degrees per second squared. - * - * @name Phaser.Physics.Arcade.Body#angularAcceleration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.angularAcceleration = 0; - - /** - * Loss of angular velocity due to angular movement, in degrees per second. - * - * Angular drag is applied only when angular acceleration is zero. - * - * @name Phaser.Physics.Arcade.Body#angularDrag - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.angularDrag = 0; - - /** - * The Body's maximum angular velocity, in degrees per second. - * - * @name Phaser.Physics.Arcade.Body#maxAngular - * @type {number} - * @default 1000 - * @since 3.0.0 - */ - this.maxAngular = 1000; - - /** - * The Body's inertia, relative to a default unit (1). - * With `bounce`, this affects the exchange of momentum (velocities) during collisions. - * - * @name Phaser.Physics.Arcade.Body#mass - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.mass = 1; - - /** - * The calculated angle of this Body's velocity vector, in radians, during the last step. - * - * @name Phaser.Physics.Arcade.Body#angle - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.angle = 0; - - /** - * The calculated magnitude of the Body's velocity, in pixels per second, during the last step. - * - * @name Phaser.Physics.Arcade.Body#speed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.speed = 0; - - /** - * The direction of the Body's velocity, as calculated during the last step. - * If the Body is moving on both axes (diagonally), this describes motion on the vertical axis only. - * - * @name Phaser.Physics.Arcade.Body#facing - * @type {integer} - * @since 3.0.0 - */ - this.facing = CONST.FACING_NONE; - - /** - * Whether this Body can be moved by collisions with another Body. - * - * @name Phaser.Physics.Arcade.Body#immovable - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.immovable = false; - - /** - * Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity. - * - * @name Phaser.Physics.Arcade.Body#moves - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.moves = true; - - /** - * A flag disabling the default horizontal separation of colliding bodies. - * Pass your own `collideCallback` to the collider. - * - * @name Phaser.Physics.Arcade.Body#customSeparateX - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.customSeparateX = false; - - /** - * A flag disabling the default vertical separation of colliding bodies. - * Pass your own `collideCallback` to the collider. - * - * @name Phaser.Physics.Arcade.Body#customSeparateY - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.customSeparateY = false; - - /** - * The amount of horizontal overlap (before separation), if this Body is colliding with another. - * - * @name Phaser.Physics.Arcade.Body#overlapX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.overlapX = 0; - - /** - * The amount of vertical overlap (before separation), if this Body is colliding with another. - * - * @name Phaser.Physics.Arcade.Body#overlapY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.overlapY = 0; - - /** - * The amount of overlap (before separation), if this Body is circular and colliding with another circular body. - * - * @name Phaser.Physics.Arcade.Body#overlapR - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.overlapR = 0; - - /** - * Whether this Body is overlapped with another and both are not moving, on at least one axis. - * - * @name Phaser.Physics.Arcade.Body#embedded - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.embedded = false; - - /** - * Whether this Body interacts with the world boundary. - * - * @name Phaser.Physics.Arcade.Body#collideWorldBounds - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.collideWorldBounds = false; - - /** - * Whether this Body is checked for collisions and for which directions. - * You can set `checkCollision.none = true` to disable collision checks. - * - * @name Phaser.Physics.Arcade.Body#checkCollision - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - */ - this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; - - /** - * Whether this Body is colliding with a Body or Static Body and in which direction. - * In a collision where both bodies have zero velocity, `embedded` will be set instead. - * - * @name Phaser.Physics.Arcade.Body#touching - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#blocked - * @see Phaser.Physics.Arcade.Body#embedded - */ - this.touching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * This Body's `touching` value during the previous step. - * - * @name Phaser.Physics.Arcade.Body#wasTouching - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#touching - */ - this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * Whether this Body is colliding with a Static Body, a tile, or the world boundary. - * In a collision with a Static Body, if this Body has zero velocity then `embedded` will be set instead. - * - * @name Phaser.Physics.Arcade.Body#blocked - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#embedded - * @see Phaser.Physics.Arcade.Body#touching - */ - this.blocked = { none: true, up: false, down: false, left: false, right: false }; - - /** - * Whether to automatically synchronize this Body's dimensions to the dimensions of its Game Object's visual bounds. - * - * @name Phaser.Physics.Arcade.Body#syncBounds - * @type {boolean} - * @default false - * @since 3.0.0 - * @see Phaser.GameObjects.Components.GetBounds#getBounds - */ - this.syncBounds = false; - - /** - * The Body's physics type (dynamic or static). - * - * @name Phaser.Physics.Arcade.Body#physicsType - * @type {integer} - * @readonly - * @default Phaser.Physics.Arcade.DYNAMIC_BODY - * @since 3.0.0 - */ - this.physicsType = CONST.DYNAMIC_BODY; - - /** - * Cached horizontal scale of the Body's Game Object. - * - * @name Phaser.Physics.Arcade.Body#_sx - * @type {number} - * @private - * @since 3.0.0 - */ - this._sx = gameObject.scaleX; - - /** - * Cached vertical scale of the Body's Game Object. - * - * @name Phaser.Physics.Arcade.Body#_sy - * @type {number} - * @private - * @since 3.0.0 - */ - this._sy = gameObject.scaleY; - - /** - * The calculated change in the Body's horizontal position during the last step. - * - * @name Phaser.Physics.Arcade.Body#_dx - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._dx = 0; - - /** - * The calculated change in the Body's vertical position during the last step. - * - * @name Phaser.Physics.Arcade.Body#_dy - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._dy = 0; - - /** - * The final calculated change in the Body's horizontal position as of `postUpdate`. - * - * @name Phaser.Physics.Arcade.Body#_tx - * @type {number} - * @private - * @default 0 - * @since 3.22.0 - */ - this._tx = 0; - - /** - * The final calculated change in the Body's vertical position as of `postUpdate`. - * - * @name Phaser.Physics.Arcade.Body#_ty - * @type {number} - * @private - * @default 0 - * @since 3.22.0 - */ - this._ty = 0; - - /** - * Stores the Game Object's bounds. - * - * @name Phaser.Physics.Arcade.Body#_bounds - * @type {Phaser.Geom.Rectangle} - * @private - * @since 3.0.0 - */ - this._bounds = new Rectangle(); - }, - - /** - * Updates the Body's `transform`, `width`, `height`, and `center` from its Game Object. - * The Body's `position` isn't changed. - * - * @method Phaser.Physics.Arcade.Body#updateBounds - * @since 3.0.0 - */ - updateBounds: function () - { - var sprite = this.gameObject; - - // Container? - - var transform = this.transform; - - if (sprite.parentContainer) - { - var matrix = sprite.getWorldTransformMatrix(this.world._tempMatrix, this.world._tempMatrix2); - - transform.x = matrix.tx; - transform.y = matrix.ty; - transform.rotation = RadToDeg(matrix.rotation); - transform.scaleX = matrix.scaleX; - transform.scaleY = matrix.scaleY; - transform.displayOriginX = sprite.displayOriginX; - transform.displayOriginY = sprite.displayOriginY; - } - else - { - transform.x = sprite.x; - transform.y = sprite.y; - transform.rotation = sprite.angle; - transform.scaleX = sprite.scaleX; - transform.scaleY = sprite.scaleY; - transform.displayOriginX = sprite.displayOriginX; - transform.displayOriginY = sprite.displayOriginY; - } - - var recalc = false; - - if (this.syncBounds) - { - var b = sprite.getBounds(this._bounds); - - this.width = b.width; - this.height = b.height; - recalc = true; - } - else - { - var asx = Math.abs(transform.scaleX); - var asy = Math.abs(transform.scaleY); - - if (this._sx !== asx || this._sy !== asy) - { - this.width = this.sourceWidth * asx; - this.height = this.sourceHeight * asy; - this._sx = asx; - this._sy = asy; - recalc = true; - } - } - - if (recalc) - { - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - this.updateCenter(); - } - }, - - /** - * Updates the Body's `center` from its `position`, `width`, and `height`. - * - * @method Phaser.Physics.Arcade.Body#updateCenter - * @since 3.0.0 - */ - updateCenter: function () - { - this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); - }, - - /** - * Prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. - * - * This method is only called if the physics world is going to run a step this frame. - * - * @method Phaser.Physics.Arcade.Body#resetFlags - * @since 3.18.0 - */ - resetFlags: function () - { - // Store and reset collision flags - var wasTouching = this.wasTouching; - var touching = this.touching; - var blocked = this.blocked; - - wasTouching.none = touching.none; - wasTouching.up = touching.up; - wasTouching.down = touching.down; - wasTouching.left = touching.left; - wasTouching.right = touching.right; - - touching.none = true; - touching.up = false; - touching.down = false; - touching.left = false; - touching.right = false; - - blocked.none = true; - blocked.up = false; - blocked.down = false; - blocked.left = false; - blocked.right = false; - - this.overlapR = 0; - this.overlapX = 0; - this.overlapY = 0; - - this.embedded = false; - }, - - /** - * Syncs the position body position with the parent Game Object. - * - * This method is called every game frame, regardless if the world steps or not. - * - * @method Phaser.Physics.Arcade.Body#preUpdate - * @since 3.17.0 - * - * @param {boolean} willStep - Will this Body run an update as well? - * @param {number} delta - The delta time, in seconds, elapsed since the last frame. - */ - preUpdate: function (willStep, delta) - { - if (willStep) - { - this.resetFlags(); - } - - this.updateBounds(); - - var sprite = this.transform; - - this.position.x = sprite.x + sprite.scaleX * (this.offset.x - sprite.displayOriginX); - this.position.y = sprite.y + sprite.scaleY * (this.offset.y - sprite.displayOriginY); - - this.updateCenter(); - - this.rotation = sprite.rotation; - - this.preRotation = this.rotation; - - if (this.moves) - { - this.prev.x = this.position.x; - this.prev.y = this.position.y; - this.prevFrame.x = this.position.x; - this.prevFrame.y = this.position.y; - } - - if (willStep) - { - this.update(delta); - } - }, - - /** - * Performs a single physics step and updates the body velocity, angle, speed and other properties. - * - * This method can be called multiple times per game frame, depending on the physics step rate. - * - * The results are synced back to the Game Object in `postUpdate`. - * - * @method Phaser.Physics.Arcade.Body#update - * @fires Phaser.Physics.Arcade.Events#WORLD_BOUNDS - * @since 3.0.0 - * - * @param {number} delta - The delta time, in seconds, elapsed since the last frame. - */ - update: function (delta) - { - this.prev.x = this.position.x; - this.prev.y = this.position.y; - - if (this.moves) - { - this.world.updateMotion(this, delta); - - var vx = this.velocity.x; - var vy = this.velocity.y; - - this.newVelocity.set(vx * delta, vy * delta); - - this.position.add(this.newVelocity); - - this.updateCenter(); - - this.angle = Math.atan2(vy, vx); - this.speed = Math.sqrt(vx * vx + vy * vy); - - // Now the update will throw collision checks at the Body - // And finally we'll integrate the new position back to the Sprite in postUpdate - - if (this.collideWorldBounds && this.checkWorldBounds() && this.onWorldBounds) - { - this.world.emit(Events.WORLD_BOUNDS, this, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); - } - } - - this._dx = this.position.x - this.prev.x; - this._dy = this.position.y - this.prev.y; - }, - - /** - * Feeds the Body results back into the parent Game Object. - * - * This method is called every game frame, regardless if the world steps or not. - * - * @method Phaser.Physics.Arcade.Body#postUpdate - * @since 3.0.0 - */ - postUpdate: function () - { - var dx = this.position.x - this.prevFrame.x; - var dy = this.position.y - this.prevFrame.y; - - if (this.moves) - { - var mx = this.deltaMax.x; - var my = this.deltaMax.y; - - if (mx !== 0 && dx !== 0) - { - if (dx < 0 && dx < -mx) - { - dx = -mx; - } - else if (dx > 0 && dx > mx) - { - dx = mx; - } - } - - if (my !== 0 && dy !== 0) - { - if (dy < 0 && dy < -my) - { - dy = -my; - } - else if (dy > 0 && dy > my) - { - dy = my; - } - } - - this.gameObject.x += dx; - this.gameObject.y += dy; - } - - if (dx < 0) - { - this.facing = CONST.FACING_LEFT; - } - else if (dx > 0) - { - this.facing = CONST.FACING_RIGHT; - } - - if (dy < 0) - { - this.facing = CONST.FACING_UP; - } - else if (dy > 0) - { - this.facing = CONST.FACING_DOWN; - } - - if (this.allowRotation) - { - this.gameObject.angle += this.deltaZ(); - } - - this._tx = dx; - this._ty = dy; - }, - - /** - * Sets a custom collision boundary rectangle. Use if you want to have a custom - * boundary instead of the world boundaries. - * - * @method Phaser.Physics.Arcade.Body#setBoundsRectangle - * @since 3.20 - * - * @param {?Phaser.Geom.Rectangle} [bounds] - The new boundary rectangle. Pass `null` to use the World bounds. - * - * @return {this} This Body object. - */ - setBoundsRectangle: function (bounds) - { - this.customBoundsRectangle = (!bounds) ? this.world.bounds : bounds; - - return this; - }, - - /** - * Checks for collisions between this Body and the world boundary and separates them. - * - * @method Phaser.Physics.Arcade.Body#checkWorldBounds - * @since 3.0.0 - * - * @return {boolean} True if this Body is colliding with the world boundary. - */ - checkWorldBounds: function () - { - var pos = this.position; - var bounds = this.customBoundsRectangle; - var check = this.world.checkCollision; - - var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; - var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; - - var wasSet = false; - - if (pos.x < bounds.x && check.left) - { - pos.x = bounds.x; - this.velocity.x *= bx; - this.blocked.left = true; - wasSet = true; - } - else if (this.right > bounds.right && check.right) - { - pos.x = bounds.right - this.width; - this.velocity.x *= bx; - this.blocked.right = true; - wasSet = true; - } - - if (pos.y < bounds.y && check.up) - { - pos.y = bounds.y; - this.velocity.y *= by; - this.blocked.up = true; - wasSet = true; - } - else if (this.bottom > bounds.bottom && check.down) - { - pos.y = bounds.bottom - this.height; - this.velocity.y *= by; - this.blocked.down = true; - wasSet = true; - } - - if (wasSet) - { - this.blocked.none = false; - } - - return wasSet; - }, - - /** - * Sets the offset of the Body's position from its Game Object's position. - * - * @method Phaser.Physics.Arcade.Body#setOffset - * @since 3.0.0 - * - * @param {number} x - The horizontal offset, in source pixels. - * @param {number} [y=x] - The vertical offset, in source pixels. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setOffset: function (x, y) - { - if (y === undefined) { y = x; } - - this.offset.set(x, y); - this.updateCenter(); - - return this; - }, - - /** - * Sizes and positions this Body's boundary, as a rectangle. - * Modifies the Body `offset` if `center` is true (the default). - * Resets the width and height to match current frame, if no width and height provided and a frame is found. - * - * @method Phaser.Physics.Arcade.Body#setSize - * @since 3.0.0 - * - * @param {integer} [width] - The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. - * @param {integer} [height] - The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. - * @param {boolean} [center=true] - Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setSize: function (width, height, center) - { - if (center === undefined) { center = true; } - - var gameObject = this.gameObject; - - if (!width && gameObject.frame) - { - width = gameObject.frame.realWidth; - } - - if (!height && gameObject.frame) - { - height = gameObject.frame.realHeight; - } - - this.sourceWidth = width; - this.sourceHeight = height; - - this.width = this.sourceWidth * this._sx; - this.height = this.sourceHeight * this._sy; - - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - - this.updateCenter(); - - if (center && gameObject.getCenter) - { - var ox = (gameObject.width - width) / 2; - var oy = (gameObject.height - height) / 2; - - this.offset.set(ox, oy); - } - - this.isCircle = false; - this.radius = 0; - - return this; - }, - - /** - * Sizes and positions this Body's boundary, as a circle. - * - * @method Phaser.Physics.Arcade.Body#setCircle - * @since 3.0.0 - * - * @param {number} radius - The radius of the Body, in source pixels. - * @param {number} [offsetX] - The horizontal offset of the Body from its Game Object, in source pixels. - * @param {number} [offsetY] - The vertical offset of the Body from its Game Object, in source pixels. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setCircle: function (radius, offsetX, offsetY) - { - if (offsetX === undefined) { offsetX = this.offset.x; } - if (offsetY === undefined) { offsetY = this.offset.y; } - - if (radius > 0) - { - this.isCircle = true; - this.radius = radius; - - this.sourceWidth = radius * 2; - this.sourceHeight = radius * 2; - - this.width = this.sourceWidth * this._sx; - this.height = this.sourceHeight * this._sy; - - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - - this.offset.set(offsetX, offsetY); - - this.updateCenter(); - } - else - { - this.isCircle = false; - } - - return this; - }, - - /** - * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. - * If the Body had any velocity or acceleration it is lost as a result of calling this. - * - * @method Phaser.Physics.Arcade.Body#reset - * @since 3.0.0 - * - * @param {number} x - The horizontal position to place the Game Object and Body. - * @param {number} y - The vertical position to place the Game Object and Body. - */ - reset: function (x, y) - { - this.stop(); - - var gameObject = this.gameObject; - - gameObject.setPosition(x, y); - - if (gameObject.getTopLeft) - { - gameObject.getTopLeft(this.position); - } - else - { - this.position.set(x, y); - } - - this.prev.copy(this.position); - this.prevFrame.copy(this.position); - - this.rotation = gameObject.angle; - this.preRotation = gameObject.angle; - - this.updateBounds(); - this.updateCenter(); - }, - - /** - * Sets acceleration, velocity, and speed to zero. - * - * @method Phaser.Physics.Arcade.Body#stop - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - stop: function () - { - this.velocity.set(0); - this.acceleration.set(0); - this.speed = 0; - this.angularVelocity = 0; - this.angularAcceleration = 0; - - return this; - }, - - /** - * Copies the coordinates of this Body's edges into an object. - * - * @method Phaser.Physics.Arcade.Body#getBounds - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} obj - An object to copy the values into. - * - * @return {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} - An object with {x, y, right, bottom}. - */ - getBounds: function (obj) - { - obj.x = this.x; - obj.y = this.y; - obj.right = this.right; - obj.bottom = this.bottom; - - return obj; - }, - - /** - * Tests if the coordinates are within this Body's boundary. - * - * @method Phaser.Physics.Arcade.Body#hitTest - * @since 3.0.0 - * - * @param {number} x - The horizontal coordinate. - * @param {number} y - The vertical coordinate. - * - * @return {boolean} True if (x, y) is within this Body. - */ - hitTest: function (x, y) - { - if (!this.isCircle) - { - return RectangleContains(this, x, y); - } - - // Check if x/y are within the bounds first - if (this.radius > 0 && x >= this.left && x <= this.right && y >= this.top && y <= this.bottom) - { - var dx = (this.center.x - x) * (this.center.x - x); - var dy = (this.center.y - y) * (this.center.y - y); - - return (dx + dy) <= (this.radius * this.radius); - } - - return false; - }, - - /** - * Whether this Body is touching a tile or the world boundary while moving down. - * - * @method Phaser.Physics.Arcade.Body#onFloor - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#blocked - * - * @return {boolean} True if touching. - */ - onFloor: function () - { - return this.blocked.down; - }, - - /** - * Whether this Body is touching a tile or the world boundary while moving up. - * - * @method Phaser.Physics.Arcade.Body#onCeiling - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#blocked - * - * @return {boolean} True if touching. - */ - onCeiling: function () - { - return this.blocked.up; - }, - - /** - * Whether this Body is touching a tile or the world boundary while moving left or right. - * - * @method Phaser.Physics.Arcade.Body#onWall - * @since 3.0.0 - * @see Phaser.Physics.Arcade.Body#blocked - * - * @return {boolean} True if touching. - */ - onWall: function () - { - return (this.blocked.left || this.blocked.right); - }, - - /** - * The absolute (non-negative) change in this Body's horizontal position from the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaAbsX - * @since 3.0.0 - * - * @return {number} The delta value. - */ - deltaAbsX: function () - { - return (this._dx > 0) ? this._dx : -this._dx; - }, - - /** - * The absolute (non-negative) change in this Body's vertical position from the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaAbsY - * @since 3.0.0 - * - * @return {number} The delta value. - */ - deltaAbsY: function () - { - return (this._dy > 0) ? this._dy : -this._dy; - }, - - /** - * The change in this Body's horizontal position from the previous step. - * This value is set during the Body's update phase. - * - * As a Body can update multiple times per step this may not hold the final - * delta value for the Body. In this case, please see the `deltaXFinal` method. - * - * @method Phaser.Physics.Arcade.Body#deltaX - * @since 3.0.0 - * - * @return {number} The delta value. - */ - deltaX: function () - { - return this._dx; - }, - - /** - * The change in this Body's vertical position from the previous step. - * This value is set during the Body's update phase. - * - * As a Body can update multiple times per step this may not hold the final - * delta value for the Body. In this case, please see the `deltaYFinal` method. - * - * @method Phaser.Physics.Arcade.Body#deltaY - * @since 3.0.0 - * - * @return {number} The delta value. - */ - deltaY: function () - { - return this._dy; - }, - - /** - * The change in this Body's horizontal position from the previous game update. - * - * This value is set during the `postUpdate` phase and takes into account the - * `deltaMax` and final position of the Body. - * - * Because this value is not calculated until `postUpdate`, you must listen for it - * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will - * not be calculated by that point. If you _do_ use these values in `update` they - * will represent the delta from the _previous_ game frame. - * - * @method Phaser.Physics.Arcade.Body#deltaXFinal - * @since 3.22.0 - * - * @return {number} The final delta x value. - */ - deltaXFinal: function () - { - return this._tx; - }, - - /** - * The change in this Body's vertical position from the previous game update. - * - * This value is set during the `postUpdate` phase and takes into account the - * `deltaMax` and final position of the Body. - * - * Because this value is not calculated until `postUpdate`, you must listen for it - * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will - * not be calculated by that point. If you _do_ use these values in `update` they - * will represent the delta from the _previous_ game frame. - * - * @method Phaser.Physics.Arcade.Body#deltaYFinal - * @since 3.22.0 - * - * @return {number} The final delta y value. - */ - deltaYFinal: function () - { - return this._ty; - }, - - /** - * The change in this Body's rotation from the previous step, in degrees. - * - * @method Phaser.Physics.Arcade.Body#deltaZ - * @since 3.0.0 - * - * @return {number} The delta value. - */ - deltaZ: function () - { - return this.rotation - this.preRotation; - }, - - /** - * Disables this Body and marks it for deletion by the simulation. - * - * @method Phaser.Physics.Arcade.Body#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.enable = false; - - if (this.world) - { - this.world.pendingDestroy.set(this); - } - }, - - /** - * Draws this Body's boundary and velocity, if enabled. - * - * @method Phaser.Physics.Arcade.Body#drawDebug - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphic - The Graphics object to draw on. - */ - drawDebug: function (graphic) - { - var pos = this.position; - - var x = pos.x + this.halfWidth; - var y = pos.y + this.halfHeight; - - if (this.debugShowBody) - { - graphic.lineStyle(graphic.defaultStrokeWidth, this.debugBodyColor); - - if (this.isCircle) - { - graphic.strokeCircle(x, y, this.width / 2); - } - else - { - // Only draw the sides where checkCollision is true, similar to debugger in layer - if (this.checkCollision.up) - { - graphic.lineBetween(pos.x, pos.y, pos.x + this.width, pos.y); - } - - if (this.checkCollision.right) - { - graphic.lineBetween(pos.x + this.width, pos.y, pos.x + this.width, pos.y + this.height); - } - - if (this.checkCollision.down) - { - graphic.lineBetween(pos.x, pos.y + this.height, pos.x + this.width, pos.y + this.height); - } - - if (this.checkCollision.left) - { - graphic.lineBetween(pos.x, pos.y, pos.x, pos.y + this.height); - } - } - } - - if (this.debugShowVelocity) - { - graphic.lineStyle(graphic.defaultStrokeWidth, this.world.defaults.velocityDebugColor, 1); - graphic.lineBetween(x, y, x + this.velocity.x / 2, y + this.velocity.y / 2); - } - }, - - /** - * Whether this Body will be drawn to the debug display. - * - * @method Phaser.Physics.Arcade.Body#willDrawDebug - * @since 3.0.0 - * - * @return {boolean} True if either `debugShowBody` or `debugShowVelocity` are enabled. - */ - willDrawDebug: function () - { - return (this.debugShowBody || this.debugShowVelocity); - }, - - /** - * Sets whether this Body collides with the world boundary. - * - * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. - * - * @method Phaser.Physics.Arcade.Body#setCollideWorldBounds - * @since 3.0.0 - * - * @param {boolean} [value=true] - `true` if this body should collide with the world bounds, otherwise `false`. - * @param {number} [bounceX] - If given this will be replace the `worldBounce.x` value. - * @param {number} [bounceY] - If given this will be replace the `worldBounce.y` value. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setCollideWorldBounds: function (value, bounceX, bounceY) - { - if (value === undefined) { value = true; } - - this.collideWorldBounds = value; - - var setBounceX = (bounceX !== undefined); - var setBounceY = (bounceY !== undefined); - - if (setBounceX || setBounceY) - { - if (!this.worldBounce) - { - this.worldBounce = new Vector2(); - } - - if (setBounceX) - { - this.worldBounce.x = bounceX; - } - - if (setBounceY) - { - this.worldBounce.y = bounceY; - } - } - - return this; - }, - - /** - * Sets the Body's velocity. - * - * @method Phaser.Physics.Arcade.Body#setVelocity - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity, in pixels per second. - * @param {number} [y=x] - The vertical velocity, in pixels per second. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setVelocity: function (x, y) - { - this.velocity.set(x, y); - - x = this.velocity.x; - y = this.velocity.y; - - this.speed = Math.sqrt(x * x + y * y); - - return this; - }, - - /** - * Sets the Body's horizontal velocity. - * - * @method Phaser.Physics.Arcade.Body#setVelocityX - * @since 3.0.0 - * - * @param {number} value - The velocity, in pixels per second. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setVelocityX: function (value) - { - this.velocity.x = value; - - var x = value; - var y = this.velocity.y; - - this.speed = Math.sqrt(x * x + y * y); - - return this; - }, - - /** - * Sets the Body's vertical velocity. - * - * @method Phaser.Physics.Arcade.Body#setVelocityY - * @since 3.0.0 - * - * @param {number} value - The velocity, in pixels per second. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setVelocityY: function (value) - { - this.velocity.y = value; - - var x = this.velocity.x; - var y = value; - - this.speed = Math.sqrt(x * x + y * y); - - return this; - }, - - /** - * Sets the Body's maximum velocity. - * - * @method Phaser.Physics.Arcade.Body#setMaxVelocity - * @since 3.10.0 - * - * @param {number} x - The horizontal velocity, in pixels per second. - * @param {number} [y=x] - The vertical velocity, in pixels per second. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setMaxVelocity: function (x, y) - { - this.maxVelocity.set(x, y); - - return this; - }, - - /** - * Sets the maximum speed the Body can move. - * - * @method Phaser.Physics.Arcade.Body#setMaxSpeed - * @since 3.16.0 - * - * @param {number} value - The maximum speed value, in pixels per second. Set to a negative value to disable. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setMaxSpeed: function (value) - { - this.maxSpeed = value; - - return this; - }, - - /** - * Sets the Body's bounce. - * - * @method Phaser.Physics.Arcade.Body#setBounce - * @since 3.0.0 - * - * @param {number} x - The horizontal bounce, relative to 1. - * @param {number} y - The vertical bounce, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setBounce: function (x, y) - { - this.bounce.set(x, y); - - return this; - }, - - /** - * Sets the Body's horizontal bounce. - * - * @method Phaser.Physics.Arcade.Body#setBounceX - * @since 3.0.0 - * - * @param {number} value - The bounce, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setBounceX: function (value) - { - this.bounce.x = value; - - return this; - }, - - /** - * Sets the Body's vertical bounce. - * - * @method Phaser.Physics.Arcade.Body#setBounceY - * @since 3.0.0 - * - * @param {number} value - The bounce, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setBounceY: function (value) - { - this.bounce.y = value; - - return this; - }, - - /** - * Sets the Body's acceleration. - * - * @method Phaser.Physics.Arcade.Body#setAcceleration - * @since 3.0.0 - * - * @param {number} x - The horizontal component, in pixels per second squared. - * @param {number} y - The vertical component, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAcceleration: function (x, y) - { - this.acceleration.set(x, y); - - return this; - }, - - /** - * Sets the Body's horizontal acceleration. - * - * @method Phaser.Physics.Arcade.Body#setAccelerationX - * @since 3.0.0 - * - * @param {number} value - The acceleration, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAccelerationX: function (value) - { - this.acceleration.x = value; - - return this; - }, - - /** - * Sets the Body's vertical acceleration. - * - * @method Phaser.Physics.Arcade.Body#setAccelerationY - * @since 3.0.0 - * - * @param {number} value - The acceleration, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAccelerationY: function (value) - { - this.acceleration.y = value; - - return this; - }, - - /** - * Enables or disables drag. - * - * @method Phaser.Physics.Arcade.Body#setAllowDrag - * @since 3.9.0 - * @see Phaser.Physics.Arcade.Body#allowDrag - * - * @param {boolean} [value=true] - `true` to allow drag on this body, or `false` to disable it. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAllowDrag: function (value) - { - if (value === undefined) { value = true; } - - this.allowDrag = value; - - return this; - }, - - /** - * Enables or disables gravity's effect on this Body. - * - * @method Phaser.Physics.Arcade.Body#setAllowGravity - * @since 3.9.0 - * @see Phaser.Physics.Arcade.Body#allowGravity - * - * @param {boolean} [value=true] - `true` to allow gravity on this body, or `false` to disable it. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAllowGravity: function (value) - { - if (value === undefined) { value = true; } - - this.allowGravity = value; - - return this; - }, - - /** - * Enables or disables rotation. - * - * @method Phaser.Physics.Arcade.Body#setAllowRotation - * @since 3.9.0 - * @see Phaser.Physics.Arcade.Body#allowRotation - * - * @param {boolean} [value=true] - `true` to allow rotation on this body, or `false` to disable it. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAllowRotation: function (value) - { - if (value === undefined) { value = true; } - - this.allowRotation = value; - - return this; - }, - - /** - * Sets the Body's drag. - * - * @method Phaser.Physics.Arcade.Body#setDrag - * @since 3.0.0 - * - * @param {number} x - The horizontal component, in pixels per second squared. - * @param {number} y - The vertical component, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setDrag: function (x, y) - { - this.drag.set(x, y); - - return this; - }, - - /** - * Sets the Body's horizontal drag. - * - * @method Phaser.Physics.Arcade.Body#setDragX - * @since 3.0.0 - * - * @param {number} value - The drag, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setDragX: function (value) - { - this.drag.x = value; - - return this; - }, - - /** - * Sets the Body's vertical drag. - * - * @method Phaser.Physics.Arcade.Body#setDragY - * @since 3.0.0 - * - * @param {number} value - The drag, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setDragY: function (value) - { - this.drag.y = value; - - return this; - }, - - /** - * Sets the Body's gravity. - * - * @method Phaser.Physics.Arcade.Body#setGravity - * @since 3.0.0 - * - * @param {number} x - The horizontal component, in pixels per second squared. - * @param {number} y - The vertical component, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setGravity: function (x, y) - { - this.gravity.set(x, y); - - return this; - }, - - /** - * Sets the Body's horizontal gravity. - * - * @method Phaser.Physics.Arcade.Body#setGravityX - * @since 3.0.0 - * - * @param {number} value - The gravity, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setGravityX: function (value) - { - this.gravity.x = value; - - return this; - }, - - /** - * Sets the Body's vertical gravity. - * - * @method Phaser.Physics.Arcade.Body#setGravityY - * @since 3.0.0 - * - * @param {number} value - The gravity, in pixels per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setGravityY: function (value) - { - this.gravity.y = value; - - return this; - }, - - /** - * Sets the Body's friction. - * - * @method Phaser.Physics.Arcade.Body#setFriction - * @since 3.0.0 - * - * @param {number} x - The horizontal component, relative to 1. - * @param {number} y - The vertical component, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setFriction: function (x, y) - { - this.friction.set(x, y); - - return this; - }, - - /** - * Sets the Body's horizontal friction. - * - * @method Phaser.Physics.Arcade.Body#setFrictionX - * @since 3.0.0 - * - * @param {number} value - The friction value, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setFrictionX: function (value) - { - this.friction.x = value; - - return this; - }, - - /** - * Sets the Body's vertical friction. - * - * @method Phaser.Physics.Arcade.Body#setFrictionY - * @since 3.0.0 - * - * @param {number} value - The friction value, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setFrictionY: function (value) - { - this.friction.y = value; - - return this; - }, - - /** - * Sets the Body's angular velocity. - * - * @method Phaser.Physics.Arcade.Body#setAngularVelocity - * @since 3.0.0 - * - * @param {number} value - The velocity, in degrees per second. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAngularVelocity: function (value) - { - this.angularVelocity = value; - - return this; - }, - - /** - * Sets the Body's angular acceleration. - * - * @method Phaser.Physics.Arcade.Body#setAngularAcceleration - * @since 3.0.0 - * - * @param {number} value - The acceleration, in degrees per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAngularAcceleration: function (value) - { - this.angularAcceleration = value; - - return this; - }, - - /** - * Sets the Body's angular drag. - * - * @method Phaser.Physics.Arcade.Body#setAngularDrag - * @since 3.0.0 - * - * @param {number} value - The drag, in degrees per second squared. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setAngularDrag: function (value) - { - this.angularDrag = value; - - return this; - }, - - /** - * Sets the Body's mass. - * - * @method Phaser.Physics.Arcade.Body#setMass - * @since 3.0.0 - * - * @param {number} value - The mass value, relative to 1. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setMass: function (value) - { - this.mass = value; - - return this; - }, - - /** - * Sets the Body's `immovable` property. - * - * @method Phaser.Physics.Arcade.Body#setImmovable - * @since 3.0.0 - * - * @param {boolean} [value=true] - The value to assign to `immovable`. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setImmovable: function (value) - { - if (value === undefined) { value = true; } - - this.immovable = value; - - return this; - }, - - /** - * Sets the Body's `enable` property. - * - * @method Phaser.Physics.Arcade.Body#setEnable - * @since 3.15.0 - * - * @param {boolean} [value=true] - The value to assign to `enable`. - * - * @return {Phaser.Physics.Arcade.Body} This Body object. - */ - setEnable: function (value) - { - if (value === undefined) { value = true; } - - this.enable = value; - - return this; - }, - - /** - * The Body's horizontal position (left edge). - * - * @name Phaser.Physics.Arcade.Body#x - * @type {number} - * @since 3.0.0 - */ - x: { - - get: function () - { - return this.position.x; - }, - - set: function (value) - { - this.position.x = value; - } - - }, - - /** - * The Body's vertical position (top edge). - * - * @name Phaser.Physics.Arcade.Body#y - * @type {number} - * @since 3.0.0 - */ - y: { - - get: function () - { - return this.position.y; - }, - - set: function (value) - { - this.position.y = value; - } - - }, - - /** - * The left edge of the Body's boundary. Identical to x. - * - * @name Phaser.Physics.Arcade.Body#left - * @type {number} - * @readonly - * @since 3.0.0 - */ - left: { - - get: function () - { - return this.position.x; - } - - }, - - /** - * The right edge of the Body's boundary. - * - * @name Phaser.Physics.Arcade.Body#right - * @type {number} - * @readonly - * @since 3.0.0 - */ - right: { - - get: function () - { - return this.position.x + this.width; - } - - }, - - /** - * The top edge of the Body's boundary. Identical to y. - * - * @name Phaser.Physics.Arcade.Body#top - * @type {number} - * @readonly - * @since 3.0.0 - */ - top: { - - get: function () - { - return this.position.y; - } - - }, - - /** - * The bottom edge of this Body's boundary. - * - * @name Phaser.Physics.Arcade.Body#bottom - * @type {number} - * @readonly - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return this.position.y + this.height; - } - - } - -}); - -module.exports = Body; +/** + * @author Richard Davey + * @author Benjamin D. Richards + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var CONST = require('./const'); +var Events = require('./events'); +var RadToDeg = require('../../math/RadToDeg'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var RectangleContains = require('../../geom/rectangle/Contains'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Dynamic Arcade Body. + * + * Its static counterpart is {@link Phaser.Physics.Arcade.StaticBody}. + * + * @class Body + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics simulation this Body belongs to. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object this Body belongs to. + */ +var Body = new Class({ + + initialize: + + function Body (world, gameObject) + { + var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; + var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; + + /** + * The Arcade Physics simulation this Body belongs to. + * + * @name Phaser.Physics.Arcade.Body#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Game Object this Body belongs to. + * + * @name Phaser.Physics.Arcade.Body#gameObject + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.gameObject = gameObject; + + /** + * Transformations applied to this Body. + * + * @name Phaser.Physics.Arcade.Body#transform + * @type {object} + * @since 3.4.0 + */ + this.transform = { + x: gameObject.x, + y: gameObject.y, + rotation: gameObject.angle, + scaleX: gameObject.scaleX, + scaleY: gameObject.scaleY, + displayOriginX: gameObject.displayOriginX, + displayOriginY: gameObject.displayOriginY + }; + + /** + * Whether the Body's boundary is drawn to the debug display. + * + * @name Phaser.Physics.Arcade.Body#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowBody; + + /** + * Whether the Body's velocity is drawn to the debug display. + * + * @name Phaser.Physics.Arcade.Body#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowVelocity = world.defaults.debugShowVelocity; + + /** + * The color of this Body on the debug display. + * + * @name Phaser.Physics.Arcade.Body#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.bodyDebugColor; + + /** + * Whether this Body is updated by the physics simulation. + * + * @name Phaser.Physics.Arcade.Body#enable + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enable = true; + + /** + * Whether this Body's boundary is circular (true) or rectangular (false). + * + * @name Phaser.Physics.Arcade.Body#isCircle + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setCircle + */ + this.isCircle = false; + + /** + * If this Body is circular, this is the unscaled radius of the Body's boundary, as set by setCircle(), in source pixels. + * The true radius is equal to `halfWidth`. + * + * @name Phaser.Physics.Arcade.Body#radius + * @type {number} + * @default 0 + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setCircle + */ + this.radius = 0; + + /** + * The offset of this Body's position from its Game Object's position, in source pixels. + * + * @name Phaser.Physics.Arcade.Body#offset + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setOffset + */ + this.offset = new Vector2(); + + /** + * The position of this Body within the simulation. + * + * @name Phaser.Physics.Arcade.Body#position + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.position = new Vector2( + gameObject.x - gameObject.scaleX * gameObject.displayOriginX, + gameObject.y - gameObject.scaleY * gameObject.displayOriginY + ); + + /** + * The position of this Body during the previous step. + * + * @name Phaser.Physics.Arcade.Body#prev + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.prev = new Vector2(gameObject.x, gameObject.y); + + /** + * The position of this Body during the previous frame. + * + * @name Phaser.Physics.Arcade.Body#prevFrame + * @type {Phaser.Math.Vector2} + * @since 3.20.0 + */ + this.prevFrame = new Vector2(gameObject.x, gameObject.y); + + /** + * Whether this Body's `rotation` is affected by its angular acceleration and angular velocity. + * + * @name Phaser.Physics.Arcade.Body#allowRotation + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.allowRotation = true; + + /** + * 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 boundary, which is always an axis-aligned rectangle or a circle. + * + * @name Phaser.Physics.Arcade.Body#rotation + * @type {number} + * @since 3.0.0 + */ + this.rotation = gameObject.angle; + + /** + * The Body rotation, in degrees, during the previous step. + * + * @name Phaser.Physics.Arcade.Body#preRotation + * @type {number} + * @since 3.0.0 + */ + this.preRotation = gameObject.angle; + + /** + * The width of the Body boundary, in pixels. + * If the Body is circular, this is also the diameter. + * If you wish to change the width use the `Body.setSize` method. + * + * @name Phaser.Physics.Arcade.Body#width + * @type {number} + * @readonly + * @default 64 + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the Body boundary, in pixels. + * If the Body is circular, this is also the diameter. + * If you wish to change the height use the `Body.setSize` method. + * + * @name Phaser.Physics.Arcade.Body#height + * @type {number} + * @readonly + * @default 64 + * @since 3.0.0 + */ + this.height = height; + + /** + * The unscaled width of the Body, in source pixels, as set by setSize(). + * The default is the width of the Body's Game Object's texture frame. + * + * @name Phaser.Physics.Arcade.Body#sourceWidth + * @type {number} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setSize + */ + this.sourceWidth = width; + + /** + * The unscaled height of the Body, in source pixels, as set by setSize(). + * The default is the height of the Body's Game Object's texture frame. + * + * @name Phaser.Physics.Arcade.Body#sourceHeight + * @type {number} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#setSize + */ + this.sourceHeight = height; + + if (gameObject.frame) + { + this.sourceWidth = gameObject.frame.realWidth; + this.sourceHeight = gameObject.frame.realHeight; + } + + /** + * Half the Body's width, in pixels. + * + * @name Phaser.Physics.Arcade.Body#halfWidth + * @type {number} + * @since 3.0.0 + */ + this.halfWidth = Math.abs(width / 2); + + /** + * Half the Body's height, in pixels. + * + * @name Phaser.Physics.Arcade.Body#halfHeight + * @type {number} + * @since 3.0.0 + */ + this.halfHeight = Math.abs(height / 2); + + /** + * The center of the Body's boundary. + * The midpoint of its `position` (top-left corner) and its bottom-right corner. + * + * @name Phaser.Physics.Arcade.Body#center + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + /** + * The Body's velocity, in pixels per second. + * + * @name Phaser.Physics.Arcade.Body#velocity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.velocity = new Vector2(); + + /** + * The Body's change in position (due to velocity) at the last step, in pixels. + * + * The size of this value depends on the simulation's step rate. + * + * @name Phaser.Physics.Arcade.Body#newVelocity + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.newVelocity = new Vector2(); + + /** + * The Body's absolute maximum change in position, in pixels per step. + * + * @name Phaser.Physics.Arcade.Body#deltaMax + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.deltaMax = new Vector2(); + + /** + * The Body's change in velocity, in pixels per second squared. + * + * @name Phaser.Physics.Arcade.Body#acceleration + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.acceleration = new Vector2(); + + /** + * Whether this Body's velocity is affected by its `drag`. + * + * @name Phaser.Physics.Arcade.Body#allowDrag + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.allowDrag = true; + + /** + * Absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @name Phaser.Physics.Arcade.Body#drag + * @type {(Phaser.Math.Vector2|number)} + * @since 3.0.0 + */ + this.drag = new Vector2(); + + /** + * Whether this Body's position is affected by gravity (local or world). + * + * @name Phaser.Physics.Arcade.Body#allowGravity + * @type {boolean} + * @default true + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#gravity + * @see Phaser.Physics.Arcade.World#gravity + */ + this.allowGravity = true; + + /** + * Acceleration due to gravity (specific to this Body), in pixels per second squared. + * Total gravity is the sum of this vector and the simulation's `gravity`. + * + * @name Phaser.Physics.Arcade.Body#gravity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#gravity + */ + this.gravity = new Vector2(); + + /** + * Rebound following a collision, relative to 1. + * + * @name Phaser.Physics.Arcade.Body#bounce + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.bounce = new Vector2(); + + /** + * Rebound following a collision with the world boundary, relative to 1. + * If null, `bounce` is used instead. + * + * @name Phaser.Physics.Arcade.Body#worldBounce + * @type {?Phaser.Math.Vector2} + * @default null + * @since 3.0.0 + */ + this.worldBounce = null; + + /** + * The rectangle used for world boundary collisions. + * + * By default it is set to the world boundary rectangle. Or, if this Body was + * created by a Physics Group, then whatever rectangle that Group defined. + * + * You can also change it by using the `Body.setBoundsRectangle` method. + * + * @name Phaser.Physics.Arcade.Body#customBoundsRectangle + * @type {?Phaser.Geom.Rectangle} + * @since 3.20 + */ + this.customBoundsRectangle = world.bounds; + + // If true this Body will dispatch events + + /** + * Whether the simulation emits a `worldbounds` event when this Body collides with the world boundary (and `collideWorldBounds` is also true). + * + * @name Phaser.Physics.Arcade.Body#onWorldBounds + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#worldboundsEvent + */ + this.onWorldBounds = false; + + /** + * Whether the simulation emits a `collide` event when this Body collides with another. + * + * @name Phaser.Physics.Arcade.Body#onCollide + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#collideEvent + */ + this.onCollide = false; + + /** + * Whether the simulation emits an `overlap` event when this Body overlaps with another. + * + * @name Phaser.Physics.Arcade.Body#onOverlap + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#overlapEvent + */ + this.onOverlap = false; + + /** + * The Body's absolute maximum velocity, in pixels per second. + * The horizontal and vertical components are applied separately. + * + * @name Phaser.Physics.Arcade.Body#maxVelocity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.maxVelocity = new Vector2(10000, 10000); + + /** + * The maximum speed this Body is allowed to reach, in pixels per second. + * + * If not negative it limits the scalar value of speed. + * + * Any negative value means no maximum is being applied (the default). + * + * @name Phaser.Physics.Arcade.Body#maxSpeed + * @type {number} + * @default -1 + * @since 3.16.0 + */ + this.maxSpeed = -1; + + /** + * If this Body is `immovable` and in motion, `friction` is the proportion of this Body's motion received by the riding Body on each axis, relative to 1. + * The horizontal component (x) is applied only when two colliding Bodies are separated vertically. + * The vertical component (y) is applied only when two colliding Bodies are separated horizontally. + * The default value (1, 0) moves the riding Body horizontally in equal proportion to this Body and vertically not at all. + * + * @name Phaser.Physics.Arcade.Body#friction + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.friction = new Vector2(1, 0); + + /** + * If this Body is using `drag` for deceleration this property controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * + * @name Phaser.Physics.Arcade.Body#useDamping + * @type {boolean} + * @default false + * @since 3.10.0 + */ + this.useDamping = false; + + /** + * The rate of change of this Body's `rotation`, in degrees per second. + * + * @name Phaser.Physics.Arcade.Body#angularVelocity + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angularVelocity = 0; + + /** + * The Body's angular acceleration (change in angular velocity), in degrees per second squared. + * + * @name Phaser.Physics.Arcade.Body#angularAcceleration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angularAcceleration = 0; + + /** + * Loss of angular velocity due to angular movement, in degrees per second. + * + * Angular drag is applied only when angular acceleration is zero. + * + * @name Phaser.Physics.Arcade.Body#angularDrag + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angularDrag = 0; + + /** + * The Body's maximum angular velocity, in degrees per second. + * + * @name Phaser.Physics.Arcade.Body#maxAngular + * @type {number} + * @default 1000 + * @since 3.0.0 + */ + this.maxAngular = 1000; + + /** + * The Body's inertia, relative to a default unit (1). + * With `bounce`, this affects the exchange of momentum (velocities) during collisions. + * + * @name Phaser.Physics.Arcade.Body#mass + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.mass = 1; + + /** + * The calculated angle of this Body's velocity vector, in radians, during the last step. + * + * @name Phaser.Physics.Arcade.Body#angle + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.angle = 0; + + /** + * The calculated magnitude of the Body's velocity, in pixels per second, during the last step. + * + * @name Phaser.Physics.Arcade.Body#speed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.speed = 0; + + /** + * The direction of the Body's velocity, as calculated during the last step. + * If the Body is moving on both axes (diagonally), this describes motion on the vertical axis only. + * + * @name Phaser.Physics.Arcade.Body#facing + * @type {integer} + * @since 3.0.0 + */ + this.facing = CONST.FACING_NONE; + + /** + * Whether this Body can be moved by collisions with another Body. + * + * @name Phaser.Physics.Arcade.Body#immovable + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.immovable = false; + + /** + * Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity. + * + * @name Phaser.Physics.Arcade.Body#moves + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.moves = true; + + /** + * A flag disabling the default horizontal separation of colliding bodies. + * Pass your own `collideCallback` to the collider. + * + * @name Phaser.Physics.Arcade.Body#customSeparateX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateX = false; + + /** + * A flag disabling the default vertical separation of colliding bodies. + * Pass your own `collideCallback` to the collider. + * + * @name Phaser.Physics.Arcade.Body#customSeparateY + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateY = false; + + /** + * The amount of horizontal overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.Body#overlapX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapX = 0; + + /** + * The amount of vertical overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.Body#overlapY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapY = 0; + + /** + * The amount of overlap (before separation), if this Body is circular and colliding with another circular body. + * + * @name Phaser.Physics.Arcade.Body#overlapR + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapR = 0; + + /** + * Whether this Body is overlapped with another and both are not moving, on at least one axis. + * + * @name Phaser.Physics.Arcade.Body#embedded + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.embedded = false; + + /** + * Whether this Body interacts with the world boundary. + * + * @name Phaser.Physics.Arcade.Body#collideWorldBounds + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.collideWorldBounds = false; + + /** + * Whether this Body is checked for collisions and for which directions. + * You can set `checkCollision.none = true` to disable collision checks. + * + * @name Phaser.Physics.Arcade.Body#checkCollision + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * Whether this Body is colliding with a Body or Static Body and in which direction. + * In a collision where both bodies have zero velocity, `embedded` will be set instead. + * + * @name Phaser.Physics.Arcade.Body#touching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#blocked + * @see Phaser.Physics.Arcade.Body#embedded + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This Body's `touching` value during the previous step. + * + * @name Phaser.Physics.Arcade.Body#wasTouching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#touching + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether this Body is colliding with a Static Body, a tile, or the world boundary. + * In a collision with a Static Body, if this Body has zero velocity then `embedded` will be set instead. + * + * @name Phaser.Physics.Arcade.Body#blocked + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#embedded + * @see Phaser.Physics.Arcade.Body#touching + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether to automatically synchronize this Body's dimensions to the dimensions of its Game Object's visual bounds. + * + * @name Phaser.Physics.Arcade.Body#syncBounds + * @type {boolean} + * @default false + * @since 3.0.0 + * @see Phaser.GameObjects.Components.GetBounds#getBounds + */ + this.syncBounds = false; + + /** + * The Body's physics type (dynamic or static). + * + * @name Phaser.Physics.Arcade.Body#physicsType + * @type {integer} + * @readonly + * @default Phaser.Physics.Arcade.DYNAMIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.DYNAMIC_BODY; + + /** + * Cached horizontal scale of the Body's Game Object. + * + * @name Phaser.Physics.Arcade.Body#_sx + * @type {number} + * @private + * @since 3.0.0 + */ + this._sx = gameObject.scaleX; + + /** + * Cached vertical scale of the Body's Game Object. + * + * @name Phaser.Physics.Arcade.Body#_sy + * @type {number} + * @private + * @since 3.0.0 + */ + this._sy = gameObject.scaleY; + + /** + * The calculated change in the Body's horizontal position during the last step. + * + * @name Phaser.Physics.Arcade.Body#_dx + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._dx = 0; + + /** + * The calculated change in the Body's vertical position during the last step. + * + * @name Phaser.Physics.Arcade.Body#_dy + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._dy = 0; + + /** + * The final calculated change in the Body's horizontal position as of `postUpdate`. + * + * @name Phaser.Physics.Arcade.Body#_tx + * @type {number} + * @private + * @default 0 + * @since 3.22.0 + */ + this._tx = 0; + + /** + * The final calculated change in the Body's vertical position as of `postUpdate`. + * + * @name Phaser.Physics.Arcade.Body#_ty + * @type {number} + * @private + * @default 0 + * @since 3.22.0 + */ + this._ty = 0; + + /** + * Stores the Game Object's bounds. + * + * @name Phaser.Physics.Arcade.Body#_bounds + * @type {Phaser.Geom.Rectangle} + * @private + * @since 3.0.0 + */ + this._bounds = new Rectangle(); + }, + + /** + * Updates the Body's `transform`, `width`, `height`, and `center` from its Game Object. + * The Body's `position` isn't changed. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @since 3.0.0 + */ + updateBounds: function () + { + var sprite = this.gameObject; + + // Container? + + var transform = this.transform; + + if (sprite.parentContainer) + { + var matrix = sprite.getWorldTransformMatrix(this.world._tempMatrix, this.world._tempMatrix2); + + transform.x = matrix.tx; + transform.y = matrix.ty; + transform.rotation = RadToDeg(matrix.rotation); + transform.scaleX = matrix.scaleX; + transform.scaleY = matrix.scaleY; + transform.displayOriginX = sprite.displayOriginX; + transform.displayOriginY = sprite.displayOriginY; + } + else + { + transform.x = sprite.x; + transform.y = sprite.y; + transform.rotation = sprite.angle; + transform.scaleX = sprite.scaleX; + transform.scaleY = sprite.scaleY; + transform.displayOriginX = sprite.displayOriginX; + transform.displayOriginY = sprite.displayOriginY; + } + + var recalc = false; + + if (this.syncBounds) + { + var b = sprite.getBounds(this._bounds); + + this.width = b.width; + this.height = b.height; + recalc = true; + } + else + { + var asx = Math.abs(transform.scaleX); + var asy = Math.abs(transform.scaleY); + + if (this._sx !== asx || this._sy !== asy) + { + this.width = this.sourceWidth * asx; + this.height = this.sourceHeight * asy; + this._sx = asx; + this._sy = asy; + recalc = true; + } + } + + if (recalc) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + }, + + /** + * Updates the Body's `center` from its `position`, `width`, and `height`. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @since 3.0.0 + */ + updateCenter: function () + { + this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + }, + + /** + * Prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. + * + * This method is only called if the physics world is going to run a step this frame. + * + * @method Phaser.Physics.Arcade.Body#resetFlags + * @since 3.18.0 + */ + resetFlags: function () + { + // Store and reset collision flags + var wasTouching = this.wasTouching; + var touching = this.touching; + var blocked = this.blocked; + + wasTouching.none = touching.none; + wasTouching.up = touching.up; + wasTouching.down = touching.down; + wasTouching.left = touching.left; + wasTouching.right = touching.right; + + touching.none = true; + touching.up = false; + touching.down = false; + touching.left = false; + touching.right = false; + + blocked.none = true; + blocked.up = false; + blocked.down = false; + blocked.left = false; + blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + }, + + /** + * Syncs the position body position with the parent Game Object. + * + * This method is called every game frame, regardless if the world steps or not. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @since 3.17.0 + * + * @param {boolean} willStep - Will this Body run an update as well? + * @param {number} delta - The delta time, in seconds, elapsed since the last frame. + */ + preUpdate: function (willStep, delta) + { + if (willStep) + { + this.resetFlags(); + } + + this.updateBounds(); + + var sprite = this.transform; + + this.position.x = sprite.x + sprite.scaleX * (this.offset.x - sprite.displayOriginX); + this.position.y = sprite.y + sprite.scaleY * (this.offset.y - sprite.displayOriginY); + + this.updateCenter(); + + this.rotation = sprite.rotation; + + this.preRotation = this.rotation; + + if (this.moves) + { + this.prev.x = this.position.x; + this.prev.y = this.position.y; + this.prevFrame.x = this.position.x; + this.prevFrame.y = this.position.y; + } + + if (willStep) + { + this.update(delta); + } + }, + + /** + * Performs a single physics step and updates the body velocity, angle, speed and other properties. + * + * This method can be called multiple times per game frame, depending on the physics step rate. + * + * The results are synced back to the Game Object in `postUpdate`. + * + * @method Phaser.Physics.Arcade.Body#update + * @fires Phaser.Physics.Arcade.Events#WORLD_BOUNDS + * @since 3.0.0 + * + * @param {number} delta - The delta time, in seconds, elapsed since the last frame. + */ + update: function (delta) + { + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + if (this.moves) + { + this.world.updateMotion(this, delta); + + var vx = this.velocity.x; + var vy = this.velocity.y; + + this.newVelocity.set(vx * delta, vy * delta); + + this.position.add(this.newVelocity); + + this.updateCenter(); + + this.angle = Math.atan2(vy, vx); + this.speed = Math.sqrt(vx * vx + vy * vy); + + // Now the update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds && this.checkWorldBounds() && this.onWorldBounds) + { + this.world.emit(Events.WORLD_BOUNDS, this, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + + this._dx = this.position.x - this.prev.x; + this._dy = this.position.y - this.prev.y; + }, + + /** + * Feeds the Body results back into the parent Game Object. + * + * This method is called every game frame, regardless if the world steps or not. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @since 3.0.0 + */ + postUpdate: function () + { + var dx = this.position.x - this.prevFrame.x; + var dy = this.position.y - this.prevFrame.y; + + if (this.moves) + { + var mx = this.deltaMax.x; + var my = this.deltaMax.y; + + if (mx !== 0 && dx !== 0) + { + if (dx < 0 && dx < -mx) + { + dx = -mx; + } + else if (dx > 0 && dx > mx) + { + dx = mx; + } + } + + if (my !== 0 && dy !== 0) + { + if (dy < 0 && dy < -my) + { + dy = -my; + } + else if (dy > 0 && dy > my) + { + dy = my; + } + } + + this.gameObject.x += dx; + this.gameObject.y += dy; + } + + if (dx < 0) + { + this.facing = CONST.FACING_LEFT; + } + else if (dx > 0) + { + this.facing = CONST.FACING_RIGHT; + } + + if (dy < 0) + { + this.facing = CONST.FACING_UP; + } + else if (dy > 0) + { + this.facing = CONST.FACING_DOWN; + } + + if (this.allowRotation) + { + this.gameObject.angle += this.deltaZ(); + } + + this._tx = dx; + this._ty = dy; + }, + + /** + * Sets a custom collision boundary rectangle. Use if you want to have a custom + * boundary instead of the world boundaries. + * + * @method Phaser.Physics.Arcade.Body#setBoundsRectangle + * @since 3.20 + * + * @param {?Phaser.Geom.Rectangle} [bounds] - The new boundary rectangle. Pass `null` to use the World bounds. + * + * @return {this} This Body object. + */ + setBoundsRectangle: function (bounds) + { + this.customBoundsRectangle = (!bounds) ? this.world.bounds : bounds; + + return this; + }, + + /** + * Checks for collisions between this Body and the world boundary and separates them. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @since 3.0.0 + * + * @return {boolean} True if this Body is colliding with the world boundary. + */ + checkWorldBounds: function () + { + var pos = this.position; + var bounds = this.customBoundsRectangle; + var check = this.world.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + var wasSet = false; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + wasSet = true; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + wasSet = true; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + wasSet = true; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + wasSet = true; + } + + if (wasSet) + { + this.blocked.none = false; + } + + return wasSet; + }, + + /** + * Sets the offset of the Body's position from its Game Object's position. + * + * @method Phaser.Physics.Arcade.Body#setOffset + * @since 3.0.0 + * + * @param {number} x - The horizontal offset, in source pixels. + * @param {number} [y=x] - The vertical offset, in source pixels. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setOffset: function (x, y) + { + if (y === undefined) { y = x; } + + this.offset.set(x, y); + this.updateCenter(); + + return this; + }, + + /** + * Sizes and positions this Body's boundary, as a rectangle. + * Modifies the Body `offset` if `center` is true (the default). + * Resets the width and height to match current frame, if no width and height provided and a frame is found. + * + * @method Phaser.Physics.Arcade.Body#setSize + * @since 3.0.0 + * + * @param {integer} [width] - The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param {integer} [height] - The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param {boolean} [center=true] - Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setSize: function (width, height, center) + { + if (center === undefined) { center = true; } + + var gameObject = this.gameObject; + + if (!width && gameObject.frame) + { + width = gameObject.frame.realWidth; + } + + if (!height && gameObject.frame) + { + height = gameObject.frame.realHeight; + } + + this.sourceWidth = width; + this.sourceHeight = height; + + this.width = this.sourceWidth * this._sx; + this.height = this.sourceHeight * this._sy; + + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + + this.updateCenter(); + + if (center && gameObject.getCenter) + { + var ox = (gameObject.width - width) / 2; + var oy = (gameObject.height - height) / 2; + + this.offset.set(ox, oy); + } + + this.isCircle = false; + this.radius = 0; + + return this; + }, + + /** + * Sizes and positions this Body's boundary, as a circle. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the Body, in source pixels. + * @param {number} [offsetX] - The horizontal offset of the Body from its Game Object, in source pixels. + * @param {number} [offsetY] - The vertical offset of the Body from its Game Object, in source pixels. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setCircle: function (radius, offsetX, offsetY) + { + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + this.width = this.sourceWidth * this._sx; + this.height = this.sourceHeight * this._sy; + + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + + this.offset.set(offsetX, offsetY); + + this.updateCenter(); + } + else + { + this.isCircle = false; + } + + return this; + }, + + /** + * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. + * If the Body had any velocity or acceleration it is lost as a result of calling this. + * + * @method Phaser.Physics.Arcade.Body#reset + * @since 3.0.0 + * + * @param {number} x - The horizontal position to place the Game Object and Body. + * @param {number} y - The vertical position to place the Game Object and Body. + */ + reset: function (x, y) + { + this.stop(); + + var gameObject = this.gameObject; + + gameObject.setPosition(x, y); + + if (gameObject.getTopLeft) + { + gameObject.getTopLeft(this.position); + } + else + { + this.position.set(x, y); + } + + this.prev.copy(this.position); + this.prevFrame.copy(this.position); + + this.rotation = gameObject.angle; + this.preRotation = gameObject.angle; + + this.updateBounds(); + this.updateCenter(); + }, + + /** + * Sets acceleration, velocity, and speed to zero. + * + * @method Phaser.Physics.Arcade.Body#stop + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + stop: function () + { + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + return this; + }, + + /** + * Copies the coordinates of this Body's edges into an object. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} obj - An object to copy the values into. + * + * @return {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} - An object with {x, y, right, bottom}. + */ + getBounds: function (obj) + { + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + }, + + /** + * Tests if the coordinates are within this Body's boundary. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @since 3.0.0 + * + * @param {number} x - The horizontal coordinate. + * @param {number} y - The vertical coordinate. + * + * @return {boolean} True if (x, y) is within this Body. + */ + hitTest: function (x, y) + { + if (!this.isCircle) + { + return RectangleContains(this, x, y); + } + + // Check if x/y are within the bounds first + if (this.radius > 0 && x >= this.left && x <= this.right && y >= this.top && y <= this.bottom) + { + var dx = (this.center.x - x) * (this.center.x - x); + var dy = (this.center.y - y) * (this.center.y - y); + + return (dx + dy) <= (this.radius * this.radius); + } + + return false; + }, + + /** + * Whether this Body is touching a tile or the world boundary while moving down. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#blocked + * + * @return {boolean} True if touching. + */ + onFloor: function () + { + return this.blocked.down; + }, + + /** + * Whether this Body is touching a tile or the world boundary while moving up. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#blocked + * + * @return {boolean} True if touching. + */ + onCeiling: function () + { + return this.blocked.up; + }, + + /** + * Whether this Body is touching a tile or the world boundary while moving left or right. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @since 3.0.0 + * @see Phaser.Physics.Arcade.Body#blocked + * + * @return {boolean} True if touching. + */ + onWall: function () + { + return (this.blocked.left || this.blocked.right); + }, + + /** + * The absolute (non-negative) change in this Body's horizontal position from the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaAbsX: function () + { + return (this._dx > 0) ? this._dx : -this._dx; + }, + + /** + * The absolute (non-negative) change in this Body's vertical position from the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaAbsY: function () + { + return (this._dy > 0) ? this._dy : -this._dy; + }, + + /** + * The change in this Body's horizontal position from the previous step. + * This value is set during the Body's update phase. + * + * As a Body can update multiple times per step this may not hold the final + * delta value for the Body. In this case, please see the `deltaXFinal` method. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaX: function () + { + return this._dx; + }, + + /** + * The change in this Body's vertical position from the previous step. + * This value is set during the Body's update phase. + * + * As a Body can update multiple times per step this may not hold the final + * delta value for the Body. In this case, please see the `deltaYFinal` method. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaY: function () + { + return this._dy; + }, + + /** + * The change in this Body's horizontal position from the previous game update. + * + * This value is set during the `postUpdate` phase and takes into account the + * `deltaMax` and final position of the Body. + * + * Because this value is not calculated until `postUpdate`, you must listen for it + * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will + * not be calculated by that point. If you _do_ use these values in `update` they + * will represent the delta from the _previous_ game frame. + * + * @method Phaser.Physics.Arcade.Body#deltaXFinal + * @since 3.22.0 + * + * @return {number} The final delta x value. + */ + deltaXFinal: function () + { + return this._tx; + }, + + /** + * The change in this Body's vertical position from the previous game update. + * + * This value is set during the `postUpdate` phase and takes into account the + * `deltaMax` and final position of the Body. + * + * Because this value is not calculated until `postUpdate`, you must listen for it + * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will + * not be calculated by that point. If you _do_ use these values in `update` they + * will represent the delta from the _previous_ game frame. + * + * @method Phaser.Physics.Arcade.Body#deltaYFinal + * @since 3.22.0 + * + * @return {number} The final delta y value. + */ + deltaYFinal: function () + { + return this._ty; + }, + + /** + * The change in this Body's rotation from the previous step, in degrees. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @since 3.0.0 + * + * @return {number} The delta value. + */ + deltaZ: function () + { + return this.rotation - this.preRotation; + }, + + /** + * Disables this Body and marks it for deletion by the simulation. + * + * @method Phaser.Physics.Arcade.Body#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.enable = false; + + if (this.world) + { + this.world.pendingDestroy.set(this); + } + }, + + /** + * Draws this Body's boundary and velocity, if enabled. + * + * @method Phaser.Physics.Arcade.Body#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - The Graphics object to draw on. + */ + drawDebug: function (graphic) + { + var pos = this.position; + + var x = pos.x + this.halfWidth; + var y = pos.y + this.halfHeight; + + if (this.debugShowBody) + { + graphic.lineStyle(graphic.defaultStrokeWidth, this.debugBodyColor); + + if (this.isCircle) + { + graphic.strokeCircle(x, y, this.width / 2); + } + else + { + // Only draw the sides where checkCollision is true, similar to debugger in layer + if (this.checkCollision.up) + { + graphic.lineBetween(pos.x, pos.y, pos.x + this.width, pos.y); + } + + if (this.checkCollision.right) + { + graphic.lineBetween(pos.x + this.width, pos.y, pos.x + this.width, pos.y + this.height); + } + + if (this.checkCollision.down) + { + graphic.lineBetween(pos.x, pos.y + this.height, pos.x + this.width, pos.y + this.height); + } + + if (this.checkCollision.left) + { + graphic.lineBetween(pos.x, pos.y, pos.x, pos.y + this.height); + } + } + } + + if (this.debugShowVelocity) + { + graphic.lineStyle(graphic.defaultStrokeWidth, this.world.defaults.velocityDebugColor, 1); + graphic.lineBetween(x, y, x + this.velocity.x / 2, y + this.velocity.y / 2); + } + }, + + /** + * Whether this Body will be drawn to the debug display. + * + * @method Phaser.Physics.Arcade.Body#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} True if either `debugShowBody` or `debugShowVelocity` are enabled. + */ + willDrawDebug: function () + { + return (this.debugShowBody || this.debugShowVelocity); + }, + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * + * @method Phaser.Physics.Arcade.Body#setCollideWorldBounds + * @since 3.0.0 + * + * @param {boolean} [value=true] - `true` if this body should collide with the world bounds, otherwise `false`. + * @param {number} [bounceX] - If given this will be replace the `worldBounce.x` value. + * @param {number} [bounceY] - If given this will be replace the `worldBounce.y` value. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setCollideWorldBounds: function (value, bounceX, bounceY) + { + if (value === undefined) { value = true; } + + this.collideWorldBounds = value; + + var setBounceX = (bounceX !== undefined); + var setBounceY = (bounceY !== undefined); + + if (setBounceX || setBounceY) + { + if (!this.worldBounce) + { + this.worldBounce = new Vector2(); + } + + if (setBounceX) + { + this.worldBounce.x = bounceX; + } + + if (setBounceY) + { + this.worldBounce.y = bounceY; + } + } + + return this; + }, + + /** + * Sets the Body's velocity. + * + * @method Phaser.Physics.Arcade.Body#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity, in pixels per second. + * @param {number} [y=x] - The vertical velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setVelocity: function (x, y) + { + this.velocity.set(x, y); + + x = this.velocity.x; + y = this.velocity.y; + + this.speed = Math.sqrt(x * x + y * y); + + return this; + }, + + /** + * Sets the Body's horizontal velocity. + * + * @method Phaser.Physics.Arcade.Body#setVelocityX + * @since 3.0.0 + * + * @param {number} value - The velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setVelocityX: function (value) + { + this.velocity.x = value; + + var x = value; + var y = this.velocity.y; + + this.speed = Math.sqrt(x * x + y * y); + + return this; + }, + + /** + * Sets the Body's vertical velocity. + * + * @method Phaser.Physics.Arcade.Body#setVelocityY + * @since 3.0.0 + * + * @param {number} value - The velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setVelocityY: function (value) + { + this.velocity.y = value; + + var x = this.velocity.x; + var y = value; + + this.speed = Math.sqrt(x * x + y * y); + + return this; + }, + + /** + * Sets the Body's maximum velocity. + * + * @method Phaser.Physics.Arcade.Body#setMaxVelocity + * @since 3.10.0 + * + * @param {number} x - The horizontal velocity, in pixels per second. + * @param {number} [y=x] - The vertical velocity, in pixels per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setMaxVelocity: function (x, y) + { + this.maxVelocity.set(x, y); + + return this; + }, + + /** + * Sets the maximum speed the Body can move. + * + * @method Phaser.Physics.Arcade.Body#setMaxSpeed + * @since 3.16.0 + * + * @param {number} value - The maximum speed value, in pixels per second. Set to a negative value to disable. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setMaxSpeed: function (value) + { + this.maxSpeed = value; + + return this; + }, + + /** + * Sets the Body's bounce. + * + * @method Phaser.Physics.Arcade.Body#setBounce + * @since 3.0.0 + * + * @param {number} x - The horizontal bounce, relative to 1. + * @param {number} y - The vertical bounce, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setBounce: function (x, y) + { + this.bounce.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal bounce. + * + * @method Phaser.Physics.Arcade.Body#setBounceX + * @since 3.0.0 + * + * @param {number} value - The bounce, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setBounceX: function (value) + { + this.bounce.x = value; + + return this; + }, + + /** + * Sets the Body's vertical bounce. + * + * @method Phaser.Physics.Arcade.Body#setBounceY + * @since 3.0.0 + * + * @param {number} value - The bounce, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setBounceY: function (value) + { + this.bounce.y = value; + + return this; + }, + + /** + * Sets the Body's acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The horizontal component, in pixels per second squared. + * @param {number} y - The vertical component, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAcceleration: function (x, y) + { + this.acceleration.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAccelerationX + * @since 3.0.0 + * + * @param {number} value - The acceleration, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAccelerationX: function (value) + { + this.acceleration.x = value; + + return this; + }, + + /** + * Sets the Body's vertical acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAccelerationY + * @since 3.0.0 + * + * @param {number} value - The acceleration, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAccelerationY: function (value) + { + this.acceleration.y = value; + + return this; + }, + + /** + * Enables or disables drag. + * + * @method Phaser.Physics.Arcade.Body#setAllowDrag + * @since 3.9.0 + * @see Phaser.Physics.Arcade.Body#allowDrag + * + * @param {boolean} [value=true] - `true` to allow drag on this body, or `false` to disable it. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAllowDrag: function (value) + { + if (value === undefined) { value = true; } + + this.allowDrag = value; + + return this; + }, + + /** + * Enables or disables gravity's effect on this Body. + * + * @method Phaser.Physics.Arcade.Body#setAllowGravity + * @since 3.9.0 + * @see Phaser.Physics.Arcade.Body#allowGravity + * + * @param {boolean} [value=true] - `true` to allow gravity on this body, or `false` to disable it. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAllowGravity: function (value) + { + if (value === undefined) { value = true; } + + this.allowGravity = value; + + return this; + }, + + /** + * Enables or disables rotation. + * + * @method Phaser.Physics.Arcade.Body#setAllowRotation + * @since 3.9.0 + * @see Phaser.Physics.Arcade.Body#allowRotation + * + * @param {boolean} [value=true] - `true` to allow rotation on this body, or `false` to disable it. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAllowRotation: function (value) + { + if (value === undefined) { value = true; } + + this.allowRotation = value; + + return this; + }, + + /** + * Sets the Body's drag. + * + * @method Phaser.Physics.Arcade.Body#setDrag + * @since 3.0.0 + * + * @param {number} x - The horizontal component, in pixels per second squared. + * @param {number} y - The vertical component, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setDrag: function (x, y) + { + this.drag.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal drag. + * + * @method Phaser.Physics.Arcade.Body#setDragX + * @since 3.0.0 + * + * @param {number} value - The drag, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setDragX: function (value) + { + this.drag.x = value; + + return this; + }, + + /** + * Sets the Body's vertical drag. + * + * @method Phaser.Physics.Arcade.Body#setDragY + * @since 3.0.0 + * + * @param {number} value - The drag, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setDragY: function (value) + { + this.drag.y = value; + + return this; + }, + + /** + * Sets the Body's gravity. + * + * @method Phaser.Physics.Arcade.Body#setGravity + * @since 3.0.0 + * + * @param {number} x - The horizontal component, in pixels per second squared. + * @param {number} y - The vertical component, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setGravity: function (x, y) + { + this.gravity.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal gravity. + * + * @method Phaser.Physics.Arcade.Body#setGravityX + * @since 3.0.0 + * + * @param {number} value - The gravity, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setGravityX: function (value) + { + this.gravity.x = value; + + return this; + }, + + /** + * Sets the Body's vertical gravity. + * + * @method Phaser.Physics.Arcade.Body#setGravityY + * @since 3.0.0 + * + * @param {number} value - The gravity, in pixels per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setGravityY: function (value) + { + this.gravity.y = value; + + return this; + }, + + /** + * Sets the Body's friction. + * + * @method Phaser.Physics.Arcade.Body#setFriction + * @since 3.0.0 + * + * @param {number} x - The horizontal component, relative to 1. + * @param {number} y - The vertical component, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setFriction: function (x, y) + { + this.friction.set(x, y); + + return this; + }, + + /** + * Sets the Body's horizontal friction. + * + * @method Phaser.Physics.Arcade.Body#setFrictionX + * @since 3.0.0 + * + * @param {number} value - The friction value, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setFrictionX: function (value) + { + this.friction.x = value; + + return this; + }, + + /** + * Sets the Body's vertical friction. + * + * @method Phaser.Physics.Arcade.Body#setFrictionY + * @since 3.0.0 + * + * @param {number} value - The friction value, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setFrictionY: function (value) + { + this.friction.y = value; + + return this; + }, + + /** + * Sets the Body's angular velocity. + * + * @method Phaser.Physics.Arcade.Body#setAngularVelocity + * @since 3.0.0 + * + * @param {number} value - The velocity, in degrees per second. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAngularVelocity: function (value) + { + this.angularVelocity = value; + + return this; + }, + + /** + * Sets the Body's angular acceleration. + * + * @method Phaser.Physics.Arcade.Body#setAngularAcceleration + * @since 3.0.0 + * + * @param {number} value - The acceleration, in degrees per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAngularAcceleration: function (value) + { + this.angularAcceleration = value; + + return this; + }, + + /** + * Sets the Body's angular drag. + * + * @method Phaser.Physics.Arcade.Body#setAngularDrag + * @since 3.0.0 + * + * @param {number} value - The drag, in degrees per second squared. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setAngularDrag: function (value) + { + this.angularDrag = value; + + return this; + }, + + /** + * Sets the Body's mass. + * + * @method Phaser.Physics.Arcade.Body#setMass + * @since 3.0.0 + * + * @param {number} value - The mass value, relative to 1. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setMass: function (value) + { + this.mass = value; + + return this; + }, + + /** + * Sets the Body's `immovable` property. + * + * @method Phaser.Physics.Arcade.Body#setImmovable + * @since 3.0.0 + * + * @param {boolean} [value=true] - The value to assign to `immovable`. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setImmovable: function (value) + { + if (value === undefined) { value = true; } + + this.immovable = value; + + return this; + }, + + /** + * Sets the Body's `enable` property. + * + * @method Phaser.Physics.Arcade.Body#setEnable + * @since 3.15.0 + * + * @param {boolean} [value=true] - The value to assign to `enable`. + * + * @return {Phaser.Physics.Arcade.Body} This Body object. + */ + setEnable: function (value) + { + if (value === undefined) { value = true; } + + this.enable = value; + + return this; + }, + + /** + * The Body's horizontal position (left edge). + * + * @name Phaser.Physics.Arcade.Body#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.position.x; + }, + + set: function (value) + { + this.position.x = value; + } + + }, + + /** + * The Body's vertical position (top edge). + * + * @name Phaser.Physics.Arcade.Body#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.position.y; + }, + + set: function (value) + { + this.position.y = value; + } + + }, + + /** + * The left edge of the Body's boundary. Identical to x. + * + * @name Phaser.Physics.Arcade.Body#left + * @type {number} + * @readonly + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.position.x; + } + + }, + + /** + * The right edge of the Body's boundary. + * + * @name Phaser.Physics.Arcade.Body#right + * @type {number} + * @readonly + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.position.x + this.width; + } + + }, + + /** + * The top edge of the Body's boundary. Identical to y. + * + * @name Phaser.Physics.Arcade.Body#top + * @type {number} + * @readonly + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.position.y; + } + + }, + + /** + * The bottom edge of this Body's boundary. + * + * @name Phaser.Physics.Arcade.Body#bottom + * @type {number} + * @readonly + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.position.y + this.height; + } + + } + +}); + +module.exports = Body; diff --git a/src/physics/arcade/Collider.js b/src/physics/arcade/Collider.js index 87cca7b84..1db1b4e77 100644 --- a/src/physics/arcade/Collider.js +++ b/src/physics/arcade/Collider.js @@ -1,177 +1,177 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); - -/** - * @classdesc - * An Arcade Physics Collider will automatically check for collision, or overlaps, between two objects - * every step. If a collision, or overlap, occurs it will invoke the given callbacks. - * - * @class Collider - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.World} world - The Arcade physics World that will manage the collisions. - * @param {boolean} overlapOnly - Whether to check for collisions or overlap. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for collision. - * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. - * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. - * @param {any} callbackContext - The scope in which to call the callbacks. - */ -var Collider = new Class({ - - initialize: - - function Collider (world, overlapOnly, object1, object2, collideCallback, processCallback, callbackContext) - { - /** - * The world in which the bodies will collide. - * - * @name Phaser.Physics.Arcade.Collider#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The name of the collider (unused by Phaser). - * - * @name Phaser.Physics.Arcade.Collider#name - * @type {string} - * @since 3.1.0 - */ - this.name = ''; - - /** - * Whether the collider is active. - * - * @name Phaser.Physics.Arcade.Collider#active - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.active = true; - - /** - * Whether to check for collisions or overlaps. - * - * @name Phaser.Physics.Arcade.Collider#overlapOnly - * @type {boolean} - * @since 3.0.0 - */ - this.overlapOnly = overlapOnly; - - /** - * The first object to check for collision. - * - * @name Phaser.Physics.Arcade.Collider#object1 - * @type {Phaser.Types.Physics.Arcade.ArcadeColliderType} - * @since 3.0.0 - */ - this.object1 = object1; - - /** - * The second object to check for collision. - * - * @name Phaser.Physics.Arcade.Collider#object2 - * @type {Phaser.Types.Physics.Arcade.ArcadeColliderType} - * @since 3.0.0 - */ - this.object2 = object2; - - /** - * The callback to invoke when the two objects collide. - * - * @name Phaser.Physics.Arcade.Collider#collideCallback - * @type {ArcadePhysicsCallback} - * @since 3.0.0 - */ - this.collideCallback = collideCallback; - - /** - * If a processCallback exists it must return true or collision checking will be skipped. - * - * @name Phaser.Physics.Arcade.Collider#processCallback - * @type {ArcadePhysicsCallback} - * @since 3.0.0 - */ - this.processCallback = processCallback; - - /** - * The context the collideCallback and processCallback will run in. - * - * @name Phaser.Physics.Arcade.Collider#callbackContext - * @type {object} - * @since 3.0.0 - */ - this.callbackContext = callbackContext; - }, - - /** - * A name for the Collider. - * - * Phaser does not use this value, it's for your own reference. - * - * @method Phaser.Physics.Arcade.Collider#setName - * @since 3.1.0 - * - * @param {string} name - The name to assign to the Collider. - * - * @return {Phaser.Physics.Arcade.Collider} This Collider instance. - */ - setName: function (name) - { - this.name = name; - - return this; - }, - - /** - * Called by World as part of its step processing, initial operation of collision checking. - * - * @method Phaser.Physics.Arcade.Collider#update - * @since 3.0.0 - */ - update: function () - { - this.world.collideObjects( - this.object1, - this.object2, - this.collideCallback, - this.processCallback, - this.callbackContext, - this.overlapOnly - ); - }, - - /** - * Removes Collider from World and disposes of its resources. - * - * @method Phaser.Physics.Arcade.Collider#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.world.removeCollider(this); - - this.active = false; - - this.world = null; - - this.object1 = null; - this.object2 = null; - - this.collideCallback = null; - this.processCallback = null; - this.callbackContext = null; - } - -}); - -module.exports = Collider; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); + +/** + * @classdesc + * An Arcade Physics Collider will automatically check for collision, or overlaps, between two objects + * every step. If a collision, or overlap, occurs it will invoke the given callbacks. + * + * @class Collider + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade physics World that will manage the collisions. + * @param {boolean} overlapOnly - Whether to check for collisions or overlap. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. + * @param {any} callbackContext - The scope in which to call the callbacks. + */ +var Collider = new Class({ + + initialize: + + function Collider (world, overlapOnly, object1, object2, collideCallback, processCallback, callbackContext) + { + /** + * The world in which the bodies will collide. + * + * @name Phaser.Physics.Arcade.Collider#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The name of the collider (unused by Phaser). + * + * @name Phaser.Physics.Arcade.Collider#name + * @type {string} + * @since 3.1.0 + */ + this.name = ''; + + /** + * Whether the collider is active. + * + * @name Phaser.Physics.Arcade.Collider#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * Whether to check for collisions or overlaps. + * + * @name Phaser.Physics.Arcade.Collider#overlapOnly + * @type {boolean} + * @since 3.0.0 + */ + this.overlapOnly = overlapOnly; + + /** + * The first object to check for collision. + * + * @name Phaser.Physics.Arcade.Collider#object1 + * @type {Phaser.Types.Physics.Arcade.ArcadeColliderType} + * @since 3.0.0 + */ + this.object1 = object1; + + /** + * The second object to check for collision. + * + * @name Phaser.Physics.Arcade.Collider#object2 + * @type {Phaser.Types.Physics.Arcade.ArcadeColliderType} + * @since 3.0.0 + */ + this.object2 = object2; + + /** + * The callback to invoke when the two objects collide. + * + * @name Phaser.Physics.Arcade.Collider#collideCallback + * @type {ArcadePhysicsCallback} + * @since 3.0.0 + */ + this.collideCallback = collideCallback; + + /** + * If a processCallback exists it must return true or collision checking will be skipped. + * + * @name Phaser.Physics.Arcade.Collider#processCallback + * @type {ArcadePhysicsCallback} + * @since 3.0.0 + */ + this.processCallback = processCallback; + + /** + * The context the collideCallback and processCallback will run in. + * + * @name Phaser.Physics.Arcade.Collider#callbackContext + * @type {object} + * @since 3.0.0 + */ + this.callbackContext = callbackContext; + }, + + /** + * A name for the Collider. + * + * Phaser does not use this value, it's for your own reference. + * + * @method Phaser.Physics.Arcade.Collider#setName + * @since 3.1.0 + * + * @param {string} name - The name to assign to the Collider. + * + * @return {Phaser.Physics.Arcade.Collider} This Collider instance. + */ + setName: function (name) + { + this.name = name; + + return this; + }, + + /** + * Called by World as part of its step processing, initial operation of collision checking. + * + * @method Phaser.Physics.Arcade.Collider#update + * @since 3.0.0 + */ + update: function () + { + this.world.collideObjects( + this.object1, + this.object2, + this.collideCallback, + this.processCallback, + this.callbackContext, + this.overlapOnly + ); + }, + + /** + * Removes Collider from World and disposes of its resources. + * + * @method Phaser.Physics.Arcade.Collider#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.removeCollider(this); + + this.active = false; + + this.world = null; + + this.object1 = null; + this.object2 = null; + + this.collideCallback = null; + this.processCallback = null; + this.callbackContext = null; + } + +}); + +module.exports = Collider; diff --git a/src/physics/arcade/Factory.js b/src/physics/arcade/Factory.js index d972c0742..cbe109d28 100644 --- a/src/physics/arcade/Factory.js +++ b/src/physics/arcade/Factory.js @@ -1,265 +1,265 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArcadeImage = require('./ArcadeImage'); -var ArcadeSprite = require('./ArcadeSprite'); -var Class = require('../../utils/Class'); -var CONST = require('./const'); -var PhysicsGroup = require('./PhysicsGroup'); -var StaticPhysicsGroup = require('./StaticPhysicsGroup'); - -/** - * @classdesc - * The Arcade Physics Factory allows you to easily create Arcade Physics enabled Game Objects. - * Objects that are created by this Factory are automatically added to the physics world. - * - * @class Factory - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics World instance. - */ -var Factory = new Class({ - - initialize: - - function Factory (world) - { - /** - * A reference to the Arcade Physics World. - * - * @name Phaser.Physics.Arcade.Factory#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * A reference to the Scene this Arcade Physics instance belongs to. - * - * @name Phaser.Physics.Arcade.Factory#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = world.scene; - - /** - * A reference to the Scene.Systems this Arcade Physics instance belongs to. - * - * @name Phaser.Physics.Arcade.Factory#sys - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.sys = world.scene.sys; - }, - - /** - * Creates a new Arcade Physics Collider object. - * - * @method Phaser.Physics.Arcade.Factory#collider - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object1 - The first object to check for collision. - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object2 - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. - * @param {*} [callbackContext] - The scope in which to call the callbacks. - * - * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. - */ - collider: function (object1, object2, collideCallback, processCallback, callbackContext) - { - return this.world.addCollider(object1, object2, collideCallback, processCallback, callbackContext); - }, - - /** - * Creates a new Arcade Physics Collider Overlap object. - * - * @method Phaser.Physics.Arcade.Factory#overlap - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object1 - The first object to check for overlap. - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object2 - The second object to check for overlap. - * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. - * @param {*} [callbackContext] - The scope in which to call the callbacks. - * - * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. - */ - overlap: function (object1, object2, collideCallback, processCallback, callbackContext) - { - return this.world.addOverlap(object1, object2, collideCallback, processCallback, callbackContext); - }, - - /** - * Adds an Arcade Physics Body to the given Game Object. - * - * @method Phaser.Physics.Arcade.Factory#existing - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - A Game Object. - * @param {boolean} [isStatic=false] - Create a Static body (true) or Dynamic body (false). - * - * @return {Phaser.GameObjects.GameObject} The Game Object. - */ - existing: function (gameObject, isStatic) - { - var type = (isStatic) ? CONST.STATIC_BODY : CONST.DYNAMIC_BODY; - - this.world.enableBody(gameObject, type); - - return gameObject; - }, - - /** - * Creates a new Arcade Image object with a Static body. - * - * @method Phaser.Physics.Arcade.Factory#staticImage - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.Physics.Arcade.Image} The Image object that was created. - */ - staticImage: function (x, y, key, frame) - { - var image = new ArcadeImage(this.scene, x, y, key, frame); - - this.sys.displayList.add(image); - - this.world.enableBody(image, CONST.STATIC_BODY); - - return image; - }, - - /** - * Creates a new Arcade Image object with a Dynamic body. - * - * @method Phaser.Physics.Arcade.Factory#image - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.Physics.Arcade.Image} The Image object that was created. - */ - image: function (x, y, key, frame) - { - var image = new ArcadeImage(this.scene, x, y, key, frame); - - this.sys.displayList.add(image); - - this.world.enableBody(image, CONST.DYNAMIC_BODY); - - return image; - }, - - /** - * Creates a new Arcade Sprite object with a Static body. - * - * @method Phaser.Physics.Arcade.Factory#staticSprite - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.Physics.Arcade.Sprite} The Sprite object that was created. - */ - staticSprite: function (x, y, key, frame) - { - var sprite = new ArcadeSprite(this.scene, x, y, key, frame); - - this.sys.displayList.add(sprite); - this.sys.updateList.add(sprite); - - this.world.enableBody(sprite, CONST.STATIC_BODY); - - return sprite; - }, - - /** - * Creates a new Arcade Sprite object with a Dynamic body. - * - * @method Phaser.Physics.Arcade.Factory#sprite - * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * - * @return {Phaser.Physics.Arcade.Sprite} The Sprite object that was created. - */ - sprite: function (x, y, key, frame) - { - var sprite = new ArcadeSprite(this.scene, x, y, key, frame); - - this.sys.displayList.add(sprite); - this.sys.updateList.add(sprite); - - this.world.enableBody(sprite, CONST.DYNAMIC_BODY); - - return sprite; - }, - - /** - * Creates a Static Physics Group object. - * All Game Objects created by this Group will automatically be static Arcade Physics objects. - * - * @method Phaser.Physics.Arcade.Factory#staticGroup - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. - * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. - * - * @return {Phaser.Physics.Arcade.StaticGroup} The Static Group object that was created. - */ - staticGroup: function (children, config) - { - return this.sys.updateList.add(new StaticPhysicsGroup(this.world, this.world.scene, children, config)); - }, - - /** - * Creates a Physics Group object. - * All Game Objects created by this Group will automatically be dynamic Arcade Physics objects. - * - * @method Phaser.Physics.Arcade.Factory#group - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. - * @param {Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. - * - * @return {Phaser.Physics.Arcade.Group} The Group object that was created. - */ - group: function (children, config) - { - return this.sys.updateList.add(new PhysicsGroup(this.world, this.world.scene, children, config)); - }, - - /** - * Destroys this Factory. - * - * @method Phaser.Physics.Arcade.Factory#destroy - * @since 3.5.0 - */ - destroy: function () - { - this.world = null; - this.scene = null; - this.sys = null; - } - -}); - -module.exports = Factory; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcadeImage = require('./ArcadeImage'); +var ArcadeSprite = require('./ArcadeSprite'); +var Class = require('../../utils/Class'); +var CONST = require('./const'); +var PhysicsGroup = require('./PhysicsGroup'); +var StaticPhysicsGroup = require('./StaticPhysicsGroup'); + +/** + * @classdesc + * The Arcade Physics Factory allows you to easily create Arcade Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + * + * @class Factory + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics World instance. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * A reference to the Arcade Physics World. + * + * @name Phaser.Physics.Arcade.Factory#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * A reference to the Scene this Arcade Physics instance belongs to. + * + * @name Phaser.Physics.Arcade.Factory#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = world.scene; + + /** + * A reference to the Scene.Systems this Arcade Physics instance belongs to. + * + * @name Phaser.Physics.Arcade.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new Arcade Physics Collider object. + * + * @method Phaser.Physics.Arcade.Factory#collider + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object1 - The first object to check for collision. + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + collider: function (object1, object2, collideCallback, processCallback, callbackContext) + { + return this.world.addCollider(object1, object2, collideCallback, processCallback, callbackContext); + }, + + /** + * Creates a new Arcade Physics Collider Overlap object. + * + * @method Phaser.Physics.Arcade.Factory#overlap + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object1 - The first object to check for overlap. + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object2 - The second object to check for overlap. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + overlap: function (object1, object2, collideCallback, processCallback, callbackContext) + { + return this.world.addOverlap(object1, object2, collideCallback, processCallback, callbackContext); + }, + + /** + * Adds an Arcade Physics Body to the given Game Object. + * + * @method Phaser.Physics.Arcade.Factory#existing + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - A Game Object. + * @param {boolean} [isStatic=false] - Create a Static body (true) or Dynamic body (false). + * + * @return {Phaser.GameObjects.GameObject} The Game Object. + */ + existing: function (gameObject, isStatic) + { + var type = (isStatic) ? CONST.STATIC_BODY : CONST.DYNAMIC_BODY; + + this.world.enableBody(gameObject, type); + + return gameObject; + }, + + /** + * Creates a new Arcade Image object with a Static body. + * + * @method Phaser.Physics.Arcade.Factory#staticImage + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Image} The Image object that was created. + */ + staticImage: function (x, y, key, frame) + { + var image = new ArcadeImage(this.scene, x, y, key, frame); + + this.sys.displayList.add(image); + + this.world.enableBody(image, CONST.STATIC_BODY); + + return image; + }, + + /** + * Creates a new Arcade Image object with a Dynamic body. + * + * @method Phaser.Physics.Arcade.Factory#image + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Image} The Image object that was created. + */ + image: function (x, y, key, frame) + { + var image = new ArcadeImage(this.scene, x, y, key, frame); + + this.sys.displayList.add(image); + + this.world.enableBody(image, CONST.DYNAMIC_BODY); + + return image; + }, + + /** + * Creates a new Arcade Sprite object with a Static body. + * + * @method Phaser.Physics.Arcade.Factory#staticSprite + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Sprite} The Sprite object that was created. + */ + staticSprite: function (x, y, key, frame) + { + var sprite = new ArcadeSprite(this.scene, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + this.world.enableBody(sprite, CONST.STATIC_BODY); + + return sprite; + }, + + /** + * Creates a new Arcade Sprite object with a Dynamic body. + * + * @method Phaser.Physics.Arcade.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * + * @return {Phaser.Physics.Arcade.Sprite} The Sprite object that was created. + */ + sprite: function (x, y, key, frame) + { + var sprite = new ArcadeSprite(this.scene, x, y, key, frame); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + this.world.enableBody(sprite, CONST.DYNAMIC_BODY); + + return sprite; + }, + + /** + * Creates a Static Physics Group object. + * All Game Objects created by this Group will automatically be static Arcade Physics objects. + * + * @method Phaser.Physics.Arcade.Factory#staticGroup + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + * + * @return {Phaser.Physics.Arcade.StaticGroup} The Static Group object that was created. + */ + staticGroup: function (children, config) + { + return this.sys.updateList.add(new StaticPhysicsGroup(this.world, this.world.scene, children, config)); + }, + + /** + * Creates a Physics Group object. + * All Game Objects created by this Group will automatically be dynamic Arcade Physics objects. + * + * @method Phaser.Physics.Arcade.Factory#group + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + * + * @return {Phaser.Physics.Arcade.Group} The Group object that was created. + */ + group: function (children, config) + { + return this.sys.updateList.add(new PhysicsGroup(this.world, this.world.scene, children, config)); + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Arcade.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.scene = null; + this.sys = null; + } + +}); + +module.exports = Factory; diff --git a/src/physics/arcade/GetOverlapX.js b/src/physics/arcade/GetOverlapX.js index 16de46997..a842cb571 100644 --- a/src/physics/arcade/GetOverlapX.js +++ b/src/physics/arcade/GetOverlapX.js @@ -1,102 +1,102 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); - -/** - * Calculates and returns the horizontal overlap between two arcade physics bodies and sets their properties - * accordingly, including: `touching.left`, `touching.right`, `touching.none` and `overlapX'. - * - * @function Phaser.Physics.Arcade.GetOverlapX - * @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 - Is this an overlap only check, or part of separation? - * @param {number} bias - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). - * - * @return {number} The amount of overlap. - */ -var GetOverlapX = function (body1, body2, overlapOnly, bias) -{ - var overlap = 0; - var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + bias; - - if (body1._dx === 0 && body2._dx === 0) - { - // They overlap but neither of them are moving - body1.embedded = true; - body2.embedded = true; - } - else if (body1._dx > body2._dx) - { - // Body1 is moving right and / or Body2 is moving left - overlap = body1.right - body2.x; - - if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) - { - overlap = 0; - } - else - { - body1.touching.none = false; - body1.touching.right = true; - - body2.touching.none = false; - body2.touching.left = true; - - if (body2.physicsType === CONST.STATIC_BODY) - { - body1.blocked.none = false; - body1.blocked.right = true; - } - - if (body1.physicsType === CONST.STATIC_BODY) - { - body2.blocked.none = false; - body2.blocked.left = true; - } - } - } - else if (body1._dx < body2._dx) - { - // Body1 is moving left and/or Body2 is moving right - overlap = body1.x - body2.width - body2.x; - - if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) - { - overlap = 0; - } - else - { - body1.touching.none = false; - body1.touching.left = true; - - body2.touching.none = false; - body2.touching.right = true; - - if (body2.physicsType === CONST.STATIC_BODY) - { - body1.blocked.none = false; - body1.blocked.left = true; - } - - if (body1.physicsType === CONST.STATIC_BODY) - { - body2.blocked.none = false; - body2.blocked.right = true; - } - } - } - - // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is - body1.overlapX = overlap; - body2.overlapX = overlap; - - return overlap; -}; - -module.exports = GetOverlapX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); + +/** + * Calculates and returns the horizontal overlap between two arcade physics bodies and sets their properties + * accordingly, including: `touching.left`, `touching.right`, `touching.none` and `overlapX'. + * + * @function Phaser.Physics.Arcade.GetOverlapX + * @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 - Is this an overlap only check, or part of separation? + * @param {number} bias - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). + * + * @return {number} The amount of overlap. + */ +var GetOverlapX = function (body1, body2, overlapOnly, bias) +{ + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + bias; + + if (body1._dx === 0 && body2._dx === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1._dx > body2._dx) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + + body2.touching.none = false; + body2.touching.left = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.right = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.left = true; + } + } + } + else if (body1._dx < body2._dx) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + + body2.touching.none = false; + body2.touching.right = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.left = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.right = true; + } + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; +}; + +module.exports = GetOverlapX; diff --git a/src/physics/arcade/GetOverlapY.js b/src/physics/arcade/GetOverlapY.js index a4112b76b..5db59b596 100644 --- a/src/physics/arcade/GetOverlapY.js +++ b/src/physics/arcade/GetOverlapY.js @@ -1,102 +1,102 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); - -/** - * Calculates and returns the vertical overlap between two arcade physics bodies and sets their properties - * accordingly, including: `touching.up`, `touching.down`, `touching.none` and `overlapY'. - * - * @function Phaser.Physics.Arcade.GetOverlapY - * @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 - Is this an overlap only check, or part of separation? - * @param {number} bias - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). - * - * @return {number} The amount of overlap. - */ -var GetOverlapY = function (body1, body2, overlapOnly, bias) -{ - var overlap = 0; - var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + bias; - - if (body1._dy === 0 && body2._dy === 0) - { - // They overlap but neither of them are moving - body1.embedded = true; - body2.embedded = true; - } - else if (body1._dy > body2._dy) - { - // Body1 is moving down and/or Body2 is moving up - overlap = body1.bottom - body2.y; - - if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) - { - overlap = 0; - } - else - { - body1.touching.none = false; - body1.touching.down = true; - - body2.touching.none = false; - body2.touching.up = true; - - if (body2.physicsType === CONST.STATIC_BODY) - { - body1.blocked.none = false; - body1.blocked.down = true; - } - - if (body1.physicsType === CONST.STATIC_BODY) - { - body2.blocked.none = false; - body2.blocked.up = true; - } - } - } - else if (body1._dy < body2._dy) - { - // Body1 is moving up and/or Body2 is moving down - overlap = body1.y - body2.bottom; - - if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) - { - overlap = 0; - } - else - { - body1.touching.none = false; - body1.touching.up = true; - - body2.touching.none = false; - body2.touching.down = true; - - if (body2.physicsType === CONST.STATIC_BODY) - { - body1.blocked.none = false; - body1.blocked.up = true; - } - - if (body1.physicsType === CONST.STATIC_BODY) - { - body2.blocked.none = false; - body2.blocked.down = true; - } - } - } - - // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is - body1.overlapY = overlap; - body2.overlapY = overlap; - - return overlap; -}; - -module.exports = GetOverlapY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); + +/** + * Calculates and returns the vertical overlap between two arcade physics bodies and sets their properties + * accordingly, including: `touching.up`, `touching.down`, `touching.none` and `overlapY'. + * + * @function Phaser.Physics.Arcade.GetOverlapY + * @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 - Is this an overlap only check, or part of separation? + * @param {number} bias - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). + * + * @return {number} The amount of overlap. + */ +var GetOverlapY = function (body1, body2, overlapOnly, bias) +{ + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + bias; + + if (body1._dy === 0 && body2._dy === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1._dy > body2._dy) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + + body2.touching.none = false; + body2.touching.up = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.down = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.up = true; + } + } + } + else if (body1._dy < body2._dy) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + + body2.touching.none = false; + body2.touching.down = true; + + if (body2.physicsType === CONST.STATIC_BODY) + { + body1.blocked.none = false; + body1.blocked.up = true; + } + + if (body1.physicsType === CONST.STATIC_BODY) + { + body2.blocked.none = false; + body2.blocked.down = true; + } + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; +}; + +module.exports = GetOverlapY; diff --git a/src/physics/arcade/PhysicsGroup.js b/src/physics/arcade/PhysicsGroup.js index 0ec12d832..77e93eff6 100644 --- a/src/physics/arcade/PhysicsGroup.js +++ b/src/physics/arcade/PhysicsGroup.js @@ -1,279 +1,279 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArcadeSprite = require('./ArcadeSprite'); -var Class = require('../../utils/Class'); -var CONST = require('./const'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Group = require('../../gameobjects/group/Group'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * An Arcade Physics Group object. - * - * All Game Objects created by this Group will automatically be given dynamic Arcade Physics bodies. - * - * Its static counterpart is {@link Phaser.Physics.Arcade.StaticGroup}. - * - * @class Group - * @extends Phaser.GameObjects.Group - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.World} world - The physics simulation. - * @param {Phaser.Scene} scene - The scene this group belongs to. - * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. - * @param {Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. - */ -var PhysicsGroup = new Class({ - - Extends: Group, - - initialize: - - function PhysicsGroup (world, scene, children, config) - { - if (!children && !config) - { - config = { - internalCreateCallback: this.createCallbackHandler, - internalRemoveCallback: this.removeCallbackHandler - }; - } - else if (IsPlainObject(children)) - { - // children is a plain object, so swizzle them: - config = children; - children = null; - - config.internalCreateCallback = this.createCallbackHandler; - config.internalRemoveCallback = this.removeCallbackHandler; - } - else if (Array.isArray(children) && IsPlainObject(children[0])) - { - // children is an array of plain objects - config = children[0]; - - var _this = this; - - children.forEach(function (singleConfig) - { - singleConfig.internalCreateCallback = _this.createCallbackHandler; - singleConfig.internalRemoveCallback = _this.removeCallbackHandler; - }); - } - else - { - // config is not defined and children is not a plain object nor an array of plain objects - config = { - internalCreateCallback: this.createCallbackHandler, - internalRemoveCallback: this.removeCallbackHandler - }; - } - - /** - * The physics simulation. - * - * @name Phaser.Physics.Arcade.Group#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The class to create new Group members from. - * - * This should be either `Phaser.Physics.Arcade.Image`, `Phaser.Physics.Arcade.Sprite`, or a class extending one of those. - * - * @name Phaser.Physics.Arcade.Group#classType - * @type {Function} - * @default ArcadeSprite - * @since 3.0.0 - */ - config.classType = GetFastValue(config, 'classType', ArcadeSprite); - - /** - * The physics type of the Group's members. - * - * @name Phaser.Physics.Arcade.Group#physicsType - * @type {integer} - * @default Phaser.Physics.Arcade.DYNAMIC_BODY - * @since 3.0.0 - */ - this.physicsType = CONST.DYNAMIC_BODY; - - /** - * Default physics properties applied to Game Objects added to the Group or created by the Group. Derived from the `config` argument. - * - * @name Phaser.Physics.Arcade.Group#defaults - * @type {Phaser.Types.Physics.Arcade.PhysicsGroupDefaults} - * @since 3.0.0 - */ - this.defaults = { - setCollideWorldBounds: GetFastValue(config, 'collideWorldBounds', false), - setBoundsRectangle: GetFastValue(config, 'customBoundsRectangle', null), - setAccelerationX: GetFastValue(config, 'accelerationX', 0), - setAccelerationY: GetFastValue(config, 'accelerationY', 0), - setAllowDrag: GetFastValue(config, 'allowDrag', true), - setAllowGravity: GetFastValue(config, 'allowGravity', true), - setAllowRotation: GetFastValue(config, 'allowRotation', true), - setBounceX: GetFastValue(config, 'bounceX', 0), - setBounceY: GetFastValue(config, 'bounceY', 0), - setDragX: GetFastValue(config, 'dragX', 0), - setDragY: GetFastValue(config, 'dragY', 0), - setEnable: GetFastValue(config, 'enable', true), - setGravityX: GetFastValue(config, 'gravityX', 0), - setGravityY: GetFastValue(config, 'gravityY', 0), - setFrictionX: GetFastValue(config, 'frictionX', 0), - setFrictionY: GetFastValue(config, 'frictionY', 0), - setVelocityX: GetFastValue(config, 'velocityX', 0), - setVelocityY: GetFastValue(config, 'velocityY', 0), - setAngularVelocity: GetFastValue(config, 'angularVelocity', 0), - setAngularAcceleration: GetFastValue(config, 'angularAcceleration', 0), - setAngularDrag: GetFastValue(config, 'angularDrag', 0), - setMass: GetFastValue(config, 'mass', 1), - setImmovable: GetFastValue(config, 'immovable', false) - }; - - if (Array.isArray(children)) - { - config = null; - } - - Group.call(this, scene, children, config); - - /** - * A textual representation of this Game Object. - * Used internally by Phaser but is available for your own custom classes to populate. - * - * @name Phaser.Physics.Arcade.Group#type - * @type {string} - * @default 'PhysicsGroup' - * @since 3.21.0 - */ - this.type = 'PhysicsGroup'; - }, - - /** - * Enables a Game Object's Body and assigns `defaults`. Called when a Group member is added or created. - * - * @method Phaser.Physics.Arcade.Group#createCallbackHandler - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object being added. - */ - createCallbackHandler: function (child) - { - if (!child.body) - { - this.world.enableBody(child, CONST.DYNAMIC_BODY); - } - - var body = child.body; - - for (var key in this.defaults) - { - body[key](this.defaults[key]); - } - }, - - /** - * Disables a Game Object's Body. Called when a Group member is removed. - * - * @method Phaser.Physics.Arcade.Group#removeCallbackHandler - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The Game Object being removed. - */ - removeCallbackHandler: function (child) - { - if (child.body) - { - this.world.disableBody(child); - } - }, - - /** - * Sets the velocity of each Group member. - * - * @method Phaser.Physics.Arcade.Group#setVelocity - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity. - * @param {number} y - The vertical velocity. - * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (x, y), the second (x + step, y + step), and so on. - * - * @return {Phaser.Physics.Arcade.Group} This Physics Group object. - */ - setVelocity: function (x, y, step) - { - if (step === undefined) { step = 0; } - - var items = this.getChildren(); - - for (var i = 0; i < items.length; i++) - { - items[i].body.velocity.set(x + (i * step), y + (i * step)); - } - - return this; - }, - - /** - * Sets the horizontal velocity of each Group member. - * - * @method Phaser.Physics.Arcade.Group#setVelocityX - * @since 3.0.0 - * - * @param {number} value - The velocity value. - * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (x), the second (x + step), and so on. - * - * @return {Phaser.Physics.Arcade.Group} This Physics Group object. - */ - setVelocityX: function (value, step) - { - if (step === undefined) { step = 0; } - - var items = this.getChildren(); - - for (var i = 0; i < items.length; i++) - { - items[i].body.velocity.x = value + (i * step); - } - - return this; - }, - - /** - * Sets the vertical velocity of each Group member. - * - * @method Phaser.Physics.Arcade.Group#setVelocityY - * @since 3.0.0 - * - * @param {number} value - The velocity value. - * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (y), the second (y + step), and so on. - * - * @return {Phaser.Physics.Arcade.Group} This Physics Group object. - */ - setVelocityY: function (value, step) - { - if (step === undefined) { step = 0; } - - var items = this.getChildren(); - - for (var i = 0; i < items.length; i++) - { - items[i].body.velocity.y = value + (i * step); - } - - return this; - } - -}); - -module.exports = PhysicsGroup; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcadeSprite = require('./ArcadeSprite'); +var Class = require('../../utils/Class'); +var CONST = require('./const'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Group = require('../../gameobjects/group/Group'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * An Arcade Physics Group object. + * + * All Game Objects created by this Group will automatically be given dynamic Arcade Physics bodies. + * + * Its static counterpart is {@link Phaser.Physics.Arcade.StaticGroup}. + * + * @class Group + * @extends Phaser.GameObjects.Group + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The physics simulation. + * @param {Phaser.Scene} scene - The scene this group belongs to. + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.Physics.Arcade.PhysicsGroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + */ +var PhysicsGroup = new Class({ + + Extends: Group, + + initialize: + + function PhysicsGroup (world, scene, children, config) + { + if (!children && !config) + { + config = { + internalCreateCallback: this.createCallbackHandler, + internalRemoveCallback: this.removeCallbackHandler + }; + } + else if (IsPlainObject(children)) + { + // children is a plain object, so swizzle them: + config = children; + children = null; + + config.internalCreateCallback = this.createCallbackHandler; + config.internalRemoveCallback = this.removeCallbackHandler; + } + else if (Array.isArray(children) && IsPlainObject(children[0])) + { + // children is an array of plain objects + config = children[0]; + + var _this = this; + + children.forEach(function (singleConfig) + { + singleConfig.internalCreateCallback = _this.createCallbackHandler; + singleConfig.internalRemoveCallback = _this.removeCallbackHandler; + }); + } + else + { + // config is not defined and children is not a plain object nor an array of plain objects + config = { + internalCreateCallback: this.createCallbackHandler, + internalRemoveCallback: this.removeCallbackHandler + }; + } + + /** + * The physics simulation. + * + * @name Phaser.Physics.Arcade.Group#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The class to create new Group members from. + * + * This should be either `Phaser.Physics.Arcade.Image`, `Phaser.Physics.Arcade.Sprite`, or a class extending one of those. + * + * @name Phaser.Physics.Arcade.Group#classType + * @type {Function} + * @default ArcadeSprite + * @since 3.0.0 + */ + config.classType = GetFastValue(config, 'classType', ArcadeSprite); + + /** + * The physics type of the Group's members. + * + * @name Phaser.Physics.Arcade.Group#physicsType + * @type {integer} + * @default Phaser.Physics.Arcade.DYNAMIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.DYNAMIC_BODY; + + /** + * Default physics properties applied to Game Objects added to the Group or created by the Group. Derived from the `config` argument. + * + * @name Phaser.Physics.Arcade.Group#defaults + * @type {Phaser.Types.Physics.Arcade.PhysicsGroupDefaults} + * @since 3.0.0 + */ + this.defaults = { + setCollideWorldBounds: GetFastValue(config, 'collideWorldBounds', false), + setBoundsRectangle: GetFastValue(config, 'customBoundsRectangle', null), + setAccelerationX: GetFastValue(config, 'accelerationX', 0), + setAccelerationY: GetFastValue(config, 'accelerationY', 0), + setAllowDrag: GetFastValue(config, 'allowDrag', true), + setAllowGravity: GetFastValue(config, 'allowGravity', true), + setAllowRotation: GetFastValue(config, 'allowRotation', true), + setBounceX: GetFastValue(config, 'bounceX', 0), + setBounceY: GetFastValue(config, 'bounceY', 0), + setDragX: GetFastValue(config, 'dragX', 0), + setDragY: GetFastValue(config, 'dragY', 0), + setEnable: GetFastValue(config, 'enable', true), + setGravityX: GetFastValue(config, 'gravityX', 0), + setGravityY: GetFastValue(config, 'gravityY', 0), + setFrictionX: GetFastValue(config, 'frictionX', 0), + setFrictionY: GetFastValue(config, 'frictionY', 0), + setVelocityX: GetFastValue(config, 'velocityX', 0), + setVelocityY: GetFastValue(config, 'velocityY', 0), + setAngularVelocity: GetFastValue(config, 'angularVelocity', 0), + setAngularAcceleration: GetFastValue(config, 'angularAcceleration', 0), + setAngularDrag: GetFastValue(config, 'angularDrag', 0), + setMass: GetFastValue(config, 'mass', 1), + setImmovable: GetFastValue(config, 'immovable', false) + }; + + if (Array.isArray(children)) + { + config = null; + } + + Group.call(this, scene, children, config); + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.Physics.Arcade.Group#type + * @type {string} + * @default 'PhysicsGroup' + * @since 3.21.0 + */ + this.type = 'PhysicsGroup'; + }, + + /** + * Enables a Game Object's Body and assigns `defaults`. Called when a Group member is added or created. + * + * @method Phaser.Physics.Arcade.Group#createCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object being added. + */ + createCallbackHandler: function (child) + { + if (!child.body) + { + this.world.enableBody(child, CONST.DYNAMIC_BODY); + } + + var body = child.body; + + for (var key in this.defaults) + { + body[key](this.defaults[key]); + } + }, + + /** + * Disables a Game Object's Body. Called when a Group member is removed. + * + * @method Phaser.Physics.Arcade.Group#removeCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The Game Object being removed. + */ + removeCallbackHandler: function (child) + { + if (child.body) + { + this.world.disableBody(child); + } + }, + + /** + * Sets the velocity of each Group member. + * + * @method Phaser.Physics.Arcade.Group#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity. + * @param {number} y - The vertical velocity. + * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (x, y), the second (x + step, y + step), and so on. + * + * @return {Phaser.Physics.Arcade.Group} This Physics Group object. + */ + setVelocity: function (x, y, step) + { + if (step === undefined) { step = 0; } + + var items = this.getChildren(); + + for (var i = 0; i < items.length; i++) + { + items[i].body.velocity.set(x + (i * step), y + (i * step)); + } + + return this; + }, + + /** + * Sets the horizontal velocity of each Group member. + * + * @method Phaser.Physics.Arcade.Group#setVelocityX + * @since 3.0.0 + * + * @param {number} value - The velocity value. + * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (x), the second (x + step), and so on. + * + * @return {Phaser.Physics.Arcade.Group} This Physics Group object. + */ + setVelocityX: function (value, step) + { + if (step === undefined) { step = 0; } + + var items = this.getChildren(); + + for (var i = 0; i < items.length; i++) + { + items[i].body.velocity.x = value + (i * step); + } + + return this; + }, + + /** + * Sets the vertical velocity of each Group member. + * + * @method Phaser.Physics.Arcade.Group#setVelocityY + * @since 3.0.0 + * + * @param {number} value - The velocity value. + * @param {number} [step=0] - The velocity increment. When set, the first member receives velocity (y), the second (y + step), and so on. + * + * @return {Phaser.Physics.Arcade.Group} This Physics Group object. + */ + setVelocityY: function (value, step) + { + if (step === undefined) { step = 0; } + + var items = this.getChildren(); + + for (var i = 0; i < items.length; i++) + { + items[i].body.velocity.y = value + (i * step); + } + + return this; + } + +}); + +module.exports = PhysicsGroup; diff --git a/src/physics/arcade/SeparateX.js b/src/physics/arcade/SeparateX.js index 35b7d2acf..a1012d051 100644 --- a/src/physics/arcade/SeparateX.js +++ b/src/physics/arcade/SeparateX.js @@ -1,85 +1,85 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetOverlapX = require('./GetOverlapX'); - -/** - * 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 they are static, or if either one uses custom logic for its separation. - * - * @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. - * - * @return {boolean} `true` if the two bodies overlap horizontally, otherwise `false`. - */ -var SeparateX = function (body1, body2, overlapOnly, bias) -{ - var overlap = GetOverlapX(body1, body2, overlapOnly, bias); - - // Can't separate two immovable bodies, or a body with its own custom separation logic - if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) - { - // return true if there was some overlap, otherwise false - return (overlap !== 0) || (body1.embedded && body2.embedded); - } - - // Adjust their positions and velocities accordingly (if there was any overlap) - var v1 = body1.velocity.x; - var v2 = body2.velocity.x; - - if (!body1.immovable && !body2.immovable) - { - overlap *= 0.5; - - body1.x -= overlap; - body2.x += overlap; - - var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); - var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); - var avg = (nv1 + nv2) * 0.5; - - nv1 -= avg; - nv2 -= avg; - - body1.velocity.x = avg + nv1 * body1.bounce.x; - body2.velocity.x = avg + nv2 * body2.bounce.x; - } - else if (!body1.immovable) - { - body1.x -= overlap; - body1.velocity.x = v2 - v1 * body1.bounce.x; - - // This is special case code that handles things like vertically moving platforms you can ride - if (body2.moves) - { - body1.y += (body2.y - body2.prev.y) * body2.friction.y; - } - } - else - { - body2.x += overlap; - body2.velocity.x = v1 - v2 * body2.bounce.x; - - // This is special case code that handles things like vertically moving platforms you can ride - if (body1.moves) - { - body2.y += (body1.y - body1.prev.y) * body1.friction.y; - } - } - - // If we got this far then there WAS overlap, and separation is complete, so return true - return true; -}; - -module.exports = SeparateX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetOverlapX = require('./GetOverlapX'); + +/** + * 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 they are static, or if either one uses custom logic for its separation. + * + * @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. + * + * @return {boolean} `true` if the two bodies overlap horizontally, otherwise `false`. + */ +var SeparateX = function (body1, body2, overlapOnly, bias) +{ + var overlap = GetOverlapX(body1, body2, overlapOnly, bias); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; +}; + +module.exports = SeparateX; diff --git a/src/physics/arcade/SeparateY.js b/src/physics/arcade/SeparateY.js index 12b153715..6d4dc722a 100644 --- a/src/physics/arcade/SeparateY.js +++ b/src/physics/arcade/SeparateY.js @@ -1,85 +1,85 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetOverlapY = require('./GetOverlapY'); - -/** - * 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. - * - * @return {boolean} `true` if the two bodies overlap vertically, otherwise `false`. - */ -var SeparateY = function (body1, body2, overlapOnly, bias) -{ - var overlap = GetOverlapY(body1, body2, overlapOnly, bias); - - // Can't separate two immovable bodies, or a body with its own custom separation logic - if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) - { - // return true if there was some overlap, otherwise false - return (overlap !== 0) || (body1.embedded && body2.embedded); - } - - // Adjust their positions and velocities accordingly (if there was any overlap) - var v1 = body1.velocity.y; - var v2 = body2.velocity.y; - - if (!body1.immovable && !body2.immovable) - { - overlap *= 0.5; - - body1.y -= overlap; - body2.y += overlap; - - var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); - var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); - var avg = (nv1 + nv2) * 0.5; - - nv1 -= avg; - nv2 -= avg; - - body1.velocity.y = avg + nv1 * body1.bounce.y; - body2.velocity.y = avg + nv2 * body2.bounce.y; - } - else if (!body1.immovable) - { - body1.y -= overlap; - body1.velocity.y = v2 - v1 * body1.bounce.y; - - // This is special case code that handles things like horizontal moving platforms you can ride - if (body2.moves) - { - body1.x += (body2.x - body2.prev.x) * body2.friction.x; - } - } - else - { - body2.y += overlap; - body2.velocity.y = v1 - v2 * body2.bounce.y; - - // This is special case code that handles things like horizontal moving platforms you can ride - if (body1.moves) - { - body2.x += (body1.x - body1.prev.x) * body1.friction.x; - } - } - - // If we got this far then there WAS overlap, and separation is complete, so return true - return true; -}; - -module.exports = SeparateY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetOverlapY = require('./GetOverlapY'); + +/** + * 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. + * + * @return {boolean} `true` if the two bodies overlap vertically, otherwise `false`. + */ +var SeparateY = function (body1, body2, overlapOnly, bias) +{ + var overlap = GetOverlapY(body1, body2, overlapOnly, bias); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; +}; + +module.exports = SeparateY; diff --git a/src/physics/arcade/StaticBody.js b/src/physics/arcade/StaticBody.js index c88108b97..a918ae2bd 100644 --- a/src/physics/arcade/StaticBody.js +++ b/src/physics/arcade/StaticBody.js @@ -1,983 +1,983 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CircleContains = require('../../geom/circle/Contains'); -var Class = require('../../utils/Class'); -var CONST = require('./const'); -var RectangleContains = require('../../geom/rectangle/Contains'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Static Arcade Physics Body. - * - * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. - * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Static Body manually. - * - * A Static Body can collide with other Bodies, but is never moved by collisions. - * - * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Body}. - * - * @class StaticBody - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics simulation this Static Body belongs to. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object this Static Body belongs to. - */ -var StaticBody = new Class({ - - initialize: - - function StaticBody (world, gameObject) - { - var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; - var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; - - /** - * The Arcade Physics simulation this Static Body belongs to. - * - * @name Phaser.Physics.Arcade.StaticBody#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The Game Object this Static Body belongs to. - * - * @name Phaser.Physics.Arcade.StaticBody#gameObject - * @type {Phaser.GameObjects.GameObject} - * @since 3.0.0 - */ - this.gameObject = gameObject; - - /** - * Whether the Static Body's boundary is drawn to the debug display. - * - * @name Phaser.Physics.Arcade.StaticBody#debugShowBody - * @type {boolean} - * @since 3.0.0 - */ - this.debugShowBody = world.defaults.debugShowStaticBody; - - /** - * The color of this Static Body on the debug display. - * - * @name Phaser.Physics.Arcade.StaticBody#debugBodyColor - * @type {integer} - * @since 3.0.0 - */ - this.debugBodyColor = world.defaults.staticBodyDebugColor; - - /** - * Whether this Static Body is updated by the physics simulation. - * - * @name Phaser.Physics.Arcade.StaticBody#enable - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enable = true; - - /** - * Whether this Static Body's boundary is circular (`true`) or rectangular (`false`). - * - * @name Phaser.Physics.Arcade.StaticBody#isCircle - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isCircle = false; - - /** - * If this Static Body is circular, this is the radius of the boundary, as set by {@link Phaser.Physics.Arcade.StaticBody#setCircle}, in pixels. - * Equal to `halfWidth`. - * - * @name Phaser.Physics.Arcade.StaticBody#radius - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.radius = 0; - - /** - * The offset set by {@link Phaser.Physics.Arcade.StaticBody#setCircle} or {@link Phaser.Physics.Arcade.StaticBody#setSize}. - * - * This doesn't affect the Static Body's position, because a Static Body does not follow its Game Object. - * - * @name Phaser.Physics.Arcade.StaticBody#offset - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.0.0 - */ - this.offset = new Vector2(); - - /** - * The position of this Static Body within the simulation. - * - * @name Phaser.Physics.Arcade.StaticBody#position - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.position = new Vector2(gameObject.x - gameObject.displayOriginX, gameObject.y - gameObject.displayOriginY); - - /** - * The width of the Static Body's boundary, in pixels. - * If the Static Body is circular, this is also the Static Body's diameter. - * - * @name Phaser.Physics.Arcade.StaticBody#width - * @type {number} - * @since 3.0.0 - */ - this.width = width; - - /** - * The height of the Static Body's boundary, in pixels. - * If the Static Body is circular, this is also the Static Body's diameter. - * - * @name Phaser.Physics.Arcade.StaticBody#height - * @type {number} - * @since 3.0.0 - */ - this.height = height; - - /** - * Half the Static Body's width, in pixels. - * If the Static Body is circular, this is also the Static Body's radius. - * - * @name Phaser.Physics.Arcade.StaticBody#halfWidth - * @type {number} - * @since 3.0.0 - */ - this.halfWidth = Math.abs(this.width / 2); - - /** - * Half the Static Body's height, in pixels. - * If the Static Body is circular, this is also the Static Body's radius. - * - * @name Phaser.Physics.Arcade.StaticBody#halfHeight - * @type {number} - * @since 3.0.0 - */ - this.halfHeight = Math.abs(this.height / 2); - - /** - * The center of the Static Body's boundary. - * This is the midpoint of its `position` (top-left corner) and its bottom-right corner. - * - * @name Phaser.Physics.Arcade.StaticBody#center - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); - - /** - * A constant zero velocity used by the Arcade Physics simulation for calculations. - * - * @name Phaser.Physics.Arcade.StaticBody#velocity - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.0.0 - */ - this.velocity = Vector2.ZERO; - - /** - * A constant `false` value expected by the Arcade Physics simulation. - * - * @name Phaser.Physics.Arcade.StaticBody#allowGravity - * @type {boolean} - * @readonly - * @default false - * @since 3.0.0 - */ - this.allowGravity = false; - - /** - * Gravitational force applied specifically to this Body. Values are in pixels per second squared. Always zero for a Static Body. - * - * @name Phaser.Physics.Arcade.StaticBody#gravity - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.0.0 - */ - this.gravity = Vector2.ZERO; - - /** - * Rebound, or restitution, following a collision, relative to 1. Always zero for a Static Body. - * - * @name Phaser.Physics.Arcade.StaticBody#bounce - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.0.0 - */ - this.bounce = Vector2.ZERO; - - // If true this Body will dispatch events - - /** - * Whether the simulation emits a `worldbounds` event when this StaticBody collides with the world boundary. - * Always false for a Static Body. (Static Bodies never collide with the world boundary and never trigger a `worldbounds` event.) - * - * @name Phaser.Physics.Arcade.StaticBody#onWorldBounds - * @type {boolean} - * @readonly - * @default false - * @since 3.0.0 - */ - this.onWorldBounds = false; - - /** - * Whether the simulation emits a `collide` event when this StaticBody collides with another. - * - * @name Phaser.Physics.Arcade.StaticBody#onCollide - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.onCollide = false; - - /** - * Whether the simulation emits an `overlap` event when this StaticBody overlaps with another. - * - * @name Phaser.Physics.Arcade.StaticBody#onOverlap - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.onOverlap = false; - - /** - * The StaticBody's inertia, relative to a default unit (1). With `bounce`, this affects the exchange of momentum (velocities) during collisions. - * - * @name Phaser.Physics.Arcade.StaticBody#mass - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.mass = 1; - - /** - * Whether this object can be moved by collisions with another body. - * - * @name Phaser.Physics.Arcade.StaticBody#immovable - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.immovable = true; - - /** - * A flag disabling the default horizontal separation of colliding bodies. Pass your own `collideHandler` to the collider. - * - * @name Phaser.Physics.Arcade.StaticBody#customSeparateX - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.customSeparateX = false; - - /** - * A flag disabling the default vertical separation of colliding bodies. Pass your own `collideHandler` to the collider. - * - * @name Phaser.Physics.Arcade.StaticBody#customSeparateY - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.customSeparateY = false; - - /** - * The amount of horizontal overlap (before separation), if this Body is colliding with another. - * - * @name Phaser.Physics.Arcade.StaticBody#overlapX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.overlapX = 0; - - /** - * The amount of vertical overlap (before separation), if this Body is colliding with another. - * - * @name Phaser.Physics.Arcade.StaticBody#overlapY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.overlapY = 0; - - /** - * The amount of overlap (before separation), if this StaticBody is circular and colliding with another circular body. - * - * @name Phaser.Physics.Arcade.StaticBody#overlapR - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.overlapR = 0; - - /** - * Whether this StaticBody has ever overlapped with another while both were not moving. - * - * @name Phaser.Physics.Arcade.StaticBody#embedded - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.embedded = false; - - /** - * Whether this StaticBody interacts with the world boundary. - * Always false for a Static Body. (Static Bodies never collide with the world boundary.) - * - * @name Phaser.Physics.Arcade.StaticBody#collideWorldBounds - * @type {boolean} - * @readonly - * @default false - * @since 3.0.0 - */ - this.collideWorldBounds = false; - - /** - * Whether this StaticBody is checked for collisions and for which directions. You can set `checkCollision.none = false` to disable collision checks. - * - * @name Phaser.Physics.Arcade.StaticBody#checkCollision - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - */ - this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; - - /** - * Whether this StaticBody has ever collided with another body and in which direction. - * - * @name Phaser.Physics.Arcade.StaticBody#touching - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - */ - this.touching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * Whether this StaticBody was colliding with another body during the last step or any previous step, and in which direction. - * - * @name Phaser.Physics.Arcade.StaticBody#wasTouching - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - */ - this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * Whether this StaticBody has ever collided with a tile or the world boundary. - * - * @name Phaser.Physics.Arcade.StaticBody#blocked - * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} - * @since 3.0.0 - */ - this.blocked = { none: true, up: false, down: false, left: false, right: false }; - - /** - * The StaticBody's physics type (static by default). - * - * @name Phaser.Physics.Arcade.StaticBody#physicsType - * @type {integer} - * @default Phaser.Physics.Arcade.STATIC_BODY - * @since 3.0.0 - */ - this.physicsType = CONST.STATIC_BODY; - - /** - * The calculated change in the Static Body's horizontal position during the current step. - * For a static body this is always zero. - * - * @name Phaser.Physics.Arcade.StaticBody#_dx - * @type {number} - * @private - * @default 0 - * @since 3.10.0 - */ - this._dx = 0; - - /** - * The calculated change in the Static Body's vertical position during the current step. - * For a static body this is always zero. - * - * @name Phaser.Physics.Arcade.StaticBody#_dy - * @type {number} - * @private - * @default 0 - * @since 3.10.0 - */ - this._dy = 0; - }, - - /** - * Changes the Game Object this Body is bound to. - * First it removes its reference from the old Game Object, then sets the new one. - * You can optionally update the position and dimensions of this Body to reflect that of the new Game Object. - * - * @method Phaser.Physics.Arcade.StaticBody#setGameObject - * @since 3.1.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The new Game Object that will own this Body. - * @param {boolean} [update=true] - Reposition and resize this Body to match the new Game Object? - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - * - * @see Phaser.Physics.Arcade.StaticBody#updateFromGameObject - */ - setGameObject: function (gameObject, update) - { - if (gameObject && gameObject !== this.gameObject) - { - // Remove this body from the old game object - this.gameObject.body = null; - - gameObject.body = this; - - // Update our reference - this.gameObject = gameObject; - } - - if (update) - { - this.updateFromGameObject(); - } - - return this; - }, - - /** - * Syncs the Static Body's position and size with its parent Game Object. - * - * @method Phaser.Physics.Arcade.StaticBody#updateFromGameObject - * @since 3.1.0 - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - */ - updateFromGameObject: function () - { - this.world.staticTree.remove(this); - - var gameObject = this.gameObject; - - gameObject.getTopLeft(this.position); - - this.width = gameObject.displayWidth; - this.height = gameObject.displayHeight; - - this.halfWidth = Math.abs(this.width / 2); - this.halfHeight = Math.abs(this.height / 2); - - this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); - - this.world.staticTree.insert(this); - - return this; - }, - - /** - * Positions the Static Body at an offset from its Game Object. - * - * @method Phaser.Physics.Arcade.StaticBody#setOffset - * @since 3.4.0 - * - * @param {number} x - The horizontal offset of the Static Body from the Game Object's `x`. - * @param {number} y - The vertical offset of the Static Body from the Game Object's `y`. - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - */ - setOffset: function (x, y) - { - if (y === undefined) { y = x; } - - this.world.staticTree.remove(this); - - this.position.x -= this.offset.x; - this.position.y -= this.offset.y; - - this.offset.set(x, y); - - this.position.x += this.offset.x; - this.position.y += this.offset.y; - - this.updateCenter(); - - this.world.staticTree.insert(this); - - return this; - }, - - /** - * Sets the size of the Static Body. - * When `center` is true, also repositions it. - * Resets the width and height to match current frame, if no width and height provided and a frame is found. - * - * @method Phaser.Physics.Arcade.StaticBody#setSize - * @since 3.0.0 - * - * @param {integer} [width] - The width of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. - * @param {integer} [height] - The height of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. - * @param {boolean} [center=true] - Place the Static Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - */ - setSize: function (width, height, center) - { - if (center === undefined) { center = true; } - - var gameObject = this.gameObject; - - if (!width && gameObject.frame) - { - width = gameObject.frame.realWidth; - } - - if (!height && gameObject.frame) - { - height = gameObject.frame.realHeight; - } - - this.world.staticTree.remove(this); - - this.width = width; - this.height = height; - - this.halfWidth = Math.floor(width / 2); - this.halfHeight = Math.floor(height / 2); - - if (center && gameObject.getCenter) - { - var ox = gameObject.displayWidth / 2; - var oy = gameObject.displayHeight / 2; - - this.position.x -= this.offset.x; - this.position.y -= this.offset.y; - - this.offset.set(ox - this.halfWidth, oy - this.halfHeight); - - this.position.x += this.offset.x; - this.position.y += this.offset.y; - } - - this.updateCenter(); - - this.isCircle = false; - this.radius = 0; - - this.world.staticTree.insert(this); - - return this; - }, - - /** - * Sets this Static Body to have a circular body and sets its size and position. - * - * @method Phaser.Physics.Arcade.StaticBody#setCircle - * @since 3.0.0 - * - * @param {number} radius - The radius of the StaticBody, in pixels. - * @param {number} [offsetX] - The horizontal offset of the StaticBody from its Game Object, in pixels. - * @param {number} [offsetY] - The vertical offset of the StaticBody from its Game Object, in pixels. - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - */ - setCircle: function (radius, offsetX, offsetY) - { - if (offsetX === undefined) { offsetX = this.offset.x; } - if (offsetY === undefined) { offsetY = this.offset.y; } - - if (radius > 0) - { - this.world.staticTree.remove(this); - - this.isCircle = true; - - this.radius = radius; - - this.width = radius * 2; - this.height = radius * 2; - - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - - this.offset.set(offsetX, offsetY); - - this.updateCenter(); - - this.world.staticTree.insert(this); - } - else - { - this.isCircle = false; - } - - return this; - }, - - /** - * Updates the StaticBody's `center` from its `position` and dimensions. - * - * @method Phaser.Physics.Arcade.StaticBody#updateCenter - * @since 3.0.0 - */ - updateCenter: function () - { - this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); - }, - - /** - * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. - * - * @method Phaser.Physics.Arcade.StaticBody#reset - * @since 3.0.0 - * - * @param {number} [x] - The x coordinate to reset the body to. If not given will use the parent Game Object's coordinate. - * @param {number} [y] - The y coordinate to reset the body to. If not given will use the parent Game Object's coordinate. - */ - reset: function (x, y) - { - var gameObject = this.gameObject; - - if (x === undefined) { x = gameObject.x; } - if (y === undefined) { y = gameObject.y; } - - this.world.staticTree.remove(this); - - gameObject.setPosition(x, y); - - gameObject.getTopLeft(this.position); - - this.updateCenter(); - - this.world.staticTree.insert(this); - }, - - /** - * NOOP function. A Static Body cannot be stopped. - * - * @method Phaser.Physics.Arcade.StaticBody#stop - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - */ - stop: function () - { - return this; - }, - - /** - * Returns the x and y coordinates of the top left and bottom right points of the StaticBody. - * - * @method Phaser.Physics.Arcade.StaticBody#getBounds - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} obj - The object which will hold the coordinates of the bounds. - * - * @return {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} The same object that was passed with `x`, `y`, `right` and `bottom` values matching the respective values of the StaticBody. - */ - getBounds: function (obj) - { - obj.x = this.x; - obj.y = this.y; - obj.right = this.right; - obj.bottom = this.bottom; - - return obj; - }, - - /** - * Checks to see if a given x,y coordinate is colliding with this Static Body. - * - * @method Phaser.Physics.Arcade.StaticBody#hitTest - * @since 3.0.0 - * - * @param {number} x - The x coordinate to check against this body. - * @param {number} y - The y coordinate to check against this body. - * - * @return {boolean} `true` if the given coordinate lies within this body, otherwise `false`. - */ - hitTest: function (x, y) - { - return (this.isCircle) ? CircleContains(this, x, y) : RectangleContains(this, x, y); - }, - - /** - * NOOP - * - * @method Phaser.Physics.Arcade.StaticBody#postUpdate - * @since 3.12.0 - */ - postUpdate: function () - { - }, - - /** - * The absolute (non-negative) change in this StaticBody's horizontal position from the previous step. Always zero. - * - * @method Phaser.Physics.Arcade.StaticBody#deltaAbsX - * @since 3.0.0 - * - * @return {number} Always zero for a Static Body. - */ - deltaAbsX: function () - { - return 0; - }, - - /** - * The absolute (non-negative) change in this StaticBody's vertical position from the previous step. Always zero. - * - * @method Phaser.Physics.Arcade.StaticBody#deltaAbsY - * @since 3.0.0 - * - * @return {number} Always zero for a Static Body. - */ - deltaAbsY: function () - { - return 0; - }, - - /** - * The change in this StaticBody's horizontal position from the previous step. Always zero. - * - * @method Phaser.Physics.Arcade.StaticBody#deltaX - * @since 3.0.0 - * - * @return {number} The change in this StaticBody's velocity from the previous step. Always zero. - */ - deltaX: function () - { - return 0; - }, - - /** - * The change in this StaticBody's vertical position from the previous step. Always zero. - * - * @method Phaser.Physics.Arcade.StaticBody#deltaY - * @since 3.0.0 - * - * @return {number} The change in this StaticBody's velocity from the previous step. Always zero. - */ - deltaY: function () - { - return 0; - }, - - /** - * The change in this StaticBody's rotation from the previous step. Always zero. - * - * @method Phaser.Physics.Arcade.StaticBody#deltaZ - * @since 3.0.0 - * - * @return {number} The change in this StaticBody's rotation from the previous step. Always zero. - */ - deltaZ: function () - { - return 0; - }, - - /** - * Disables this Body and marks it for destruction during the next step. - * - * @method Phaser.Physics.Arcade.StaticBody#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.enable = false; - - this.world.pendingDestroy.set(this); - }, - - /** - * Draws a graphical representation of the StaticBody for visual debugging purposes. - * - * @method Phaser.Physics.Arcade.StaticBody#drawDebug - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphic - The Graphics object to use for the debug drawing of the StaticBody. - */ - drawDebug: function (graphic) - { - var pos = this.position; - - var x = pos.x + this.halfWidth; - var y = pos.y + this.halfHeight; - - if (this.debugShowBody) - { - graphic.lineStyle(graphic.defaultStrokeWidth, this.debugBodyColor, 1); - - if (this.isCircle) - { - graphic.strokeCircle(x, y, this.width / 2); - } - else - { - graphic.strokeRect(pos.x, pos.y, this.width, this.height); - } - - } - }, - - /** - * Indicates whether the StaticBody is going to be showing a debug visualization during postUpdate. - * - * @method Phaser.Physics.Arcade.StaticBody#willDrawDebug - * @since 3.0.0 - * - * @return {boolean} Whether or not the StaticBody is going to show the debug visualization during postUpdate. - */ - willDrawDebug: function () - { - return this.debugShowBody; - }, - - /** - * Sets the Mass of the StaticBody. Will set the Mass to 0.1 if the value passed is less than or equal to zero. - * - * @method Phaser.Physics.Arcade.StaticBody#setMass - * @since 3.0.0 - * - * @param {number} value - The value to set the Mass to. Values of zero or less are changed to 0.1. - * - * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. - */ - setMass: function (value) - { - if (value <= 0) - { - // Causes havoc otherwise - value = 0.1; - } - - this.mass = value; - - return this; - }, - - /** - * The x coordinate of the StaticBody. - * - * @name Phaser.Physics.Arcade.StaticBody#x - * @type {number} - * @since 3.0.0 - */ - x: { - - get: function () - { - return this.position.x; - }, - - set: function (value) - { - this.world.staticTree.remove(this); - - this.position.x = value; - - this.world.staticTree.insert(this); - } - - }, - - /** - * The y coordinate of the StaticBody. - * - * @name Phaser.Physics.Arcade.StaticBody#y - * @type {number} - * @since 3.0.0 - */ - y: { - - get: function () - { - return this.position.y; - }, - - set: function (value) - { - this.world.staticTree.remove(this); - - this.position.y = value; - - this.world.staticTree.insert(this); - } - - }, - - /** - * Returns the left-most x coordinate of the area of the StaticBody. - * - * @name Phaser.Physics.Arcade.StaticBody#left - * @type {number} - * @readonly - * @since 3.0.0 - */ - left: { - - get: function () - { - return this.position.x; - } - - }, - - /** - * The right-most x coordinate of the area of the StaticBody. - * - * @name Phaser.Physics.Arcade.StaticBody#right - * @type {number} - * @readonly - * @since 3.0.0 - */ - right: { - - get: function () - { - return this.position.x + this.width; - } - - }, - - /** - * The highest y coordinate of the area of the StaticBody. - * - * @name Phaser.Physics.Arcade.StaticBody#top - * @type {number} - * @readonly - * @since 3.0.0 - */ - top: { - - get: function () - { - return this.position.y; - } - - }, - - /** - * The lowest y coordinate of the area of the StaticBody. (y + height) - * - * @name Phaser.Physics.Arcade.StaticBody#bottom - * @type {number} - * @readonly - * @since 3.0.0 - */ - bottom: { - - get: function () - { - return this.position.y + this.height; - } - - } - -}); - -module.exports = StaticBody; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CircleContains = require('../../geom/circle/Contains'); +var Class = require('../../utils/Class'); +var CONST = require('./const'); +var RectangleContains = require('../../geom/rectangle/Contains'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Static Arcade Physics Body. + * + * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. + * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Static Body manually. + * + * A Static Body can collide with other Bodies, but is never moved by collisions. + * + * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Body}. + * + * @class StaticBody + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The Arcade Physics simulation this Static Body belongs to. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object this Static Body belongs to. + */ +var StaticBody = new Class({ + + initialize: + + function StaticBody (world, gameObject) + { + var width = (gameObject.displayWidth) ? gameObject.displayWidth : 64; + var height = (gameObject.displayHeight) ? gameObject.displayHeight : 64; + + /** + * The Arcade Physics simulation this Static Body belongs to. + * + * @name Phaser.Physics.Arcade.StaticBody#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Game Object this Static Body belongs to. + * + * @name Phaser.Physics.Arcade.StaticBody#gameObject + * @type {Phaser.GameObjects.GameObject} + * @since 3.0.0 + */ + this.gameObject = gameObject; + + /** + * Whether the Static Body's boundary is drawn to the debug display. + * + * @name Phaser.Physics.Arcade.StaticBody#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + this.debugShowBody = world.defaults.debugShowStaticBody; + + /** + * The color of this Static Body on the debug display. + * + * @name Phaser.Physics.Arcade.StaticBody#debugBodyColor + * @type {integer} + * @since 3.0.0 + */ + this.debugBodyColor = world.defaults.staticBodyDebugColor; + + /** + * Whether this Static Body is updated by the physics simulation. + * + * @name Phaser.Physics.Arcade.StaticBody#enable + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enable = true; + + /** + * Whether this Static Body's boundary is circular (`true`) or rectangular (`false`). + * + * @name Phaser.Physics.Arcade.StaticBody#isCircle + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isCircle = false; + + /** + * If this Static Body is circular, this is the radius of the boundary, as set by {@link Phaser.Physics.Arcade.StaticBody#setCircle}, in pixels. + * Equal to `halfWidth`. + * + * @name Phaser.Physics.Arcade.StaticBody#radius + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.radius = 0; + + /** + * The offset set by {@link Phaser.Physics.Arcade.StaticBody#setCircle} or {@link Phaser.Physics.Arcade.StaticBody#setSize}. + * + * This doesn't affect the Static Body's position, because a Static Body does not follow its Game Object. + * + * @name Phaser.Physics.Arcade.StaticBody#offset + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.offset = new Vector2(); + + /** + * The position of this Static Body within the simulation. + * + * @name Phaser.Physics.Arcade.StaticBody#position + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.position = new Vector2(gameObject.x - gameObject.displayOriginX, gameObject.y - gameObject.displayOriginY); + + /** + * The width of the Static Body's boundary, in pixels. + * If the Static Body is circular, this is also the Static Body's diameter. + * + * @name Phaser.Physics.Arcade.StaticBody#width + * @type {number} + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the Static Body's boundary, in pixels. + * If the Static Body is circular, this is also the Static Body's diameter. + * + * @name Phaser.Physics.Arcade.StaticBody#height + * @type {number} + * @since 3.0.0 + */ + this.height = height; + + /** + * Half the Static Body's width, in pixels. + * If the Static Body is circular, this is also the Static Body's radius. + * + * @name Phaser.Physics.Arcade.StaticBody#halfWidth + * @type {number} + * @since 3.0.0 + */ + this.halfWidth = Math.abs(this.width / 2); + + /** + * Half the Static Body's height, in pixels. + * If the Static Body is circular, this is also the Static Body's radius. + * + * @name Phaser.Physics.Arcade.StaticBody#halfHeight + * @type {number} + * @since 3.0.0 + */ + this.halfHeight = Math.abs(this.height / 2); + + /** + * The center of the Static Body's boundary. + * This is the midpoint of its `position` (top-left corner) and its bottom-right corner. + * + * @name Phaser.Physics.Arcade.StaticBody#center + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.center = new Vector2(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + /** + * A constant zero velocity used by the Arcade Physics simulation for calculations. + * + * @name Phaser.Physics.Arcade.StaticBody#velocity + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.velocity = Vector2.ZERO; + + /** + * A constant `false` value expected by the Arcade Physics simulation. + * + * @name Phaser.Physics.Arcade.StaticBody#allowGravity + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.allowGravity = false; + + /** + * Gravitational force applied specifically to this Body. Values are in pixels per second squared. Always zero for a Static Body. + * + * @name Phaser.Physics.Arcade.StaticBody#gravity + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.gravity = Vector2.ZERO; + + /** + * Rebound, or restitution, following a collision, relative to 1. Always zero for a Static Body. + * + * @name Phaser.Physics.Arcade.StaticBody#bounce + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.0.0 + */ + this.bounce = Vector2.ZERO; + + // If true this Body will dispatch events + + /** + * Whether the simulation emits a `worldbounds` event when this StaticBody collides with the world boundary. + * Always false for a Static Body. (Static Bodies never collide with the world boundary and never trigger a `worldbounds` event.) + * + * @name Phaser.Physics.Arcade.StaticBody#onWorldBounds + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.onWorldBounds = false; + + /** + * Whether the simulation emits a `collide` event when this StaticBody collides with another. + * + * @name Phaser.Physics.Arcade.StaticBody#onCollide + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.onCollide = false; + + /** + * Whether the simulation emits an `overlap` event when this StaticBody overlaps with another. + * + * @name Phaser.Physics.Arcade.StaticBody#onOverlap + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.onOverlap = false; + + /** + * The StaticBody's inertia, relative to a default unit (1). With `bounce`, this affects the exchange of momentum (velocities) during collisions. + * + * @name Phaser.Physics.Arcade.StaticBody#mass + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.mass = 1; + + /** + * Whether this object can be moved by collisions with another body. + * + * @name Phaser.Physics.Arcade.StaticBody#immovable + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.immovable = true; + + /** + * A flag disabling the default horizontal separation of colliding bodies. Pass your own `collideHandler` to the collider. + * + * @name Phaser.Physics.Arcade.StaticBody#customSeparateX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateX = false; + + /** + * A flag disabling the default vertical separation of colliding bodies. Pass your own `collideHandler` to the collider. + * + * @name Phaser.Physics.Arcade.StaticBody#customSeparateY + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customSeparateY = false; + + /** + * The amount of horizontal overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.StaticBody#overlapX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapX = 0; + + /** + * The amount of vertical overlap (before separation), if this Body is colliding with another. + * + * @name Phaser.Physics.Arcade.StaticBody#overlapY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapY = 0; + + /** + * The amount of overlap (before separation), if this StaticBody is circular and colliding with another circular body. + * + * @name Phaser.Physics.Arcade.StaticBody#overlapR + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.overlapR = 0; + + /** + * Whether this StaticBody has ever overlapped with another while both were not moving. + * + * @name Phaser.Physics.Arcade.StaticBody#embedded + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.embedded = false; + + /** + * Whether this StaticBody interacts with the world boundary. + * Always false for a Static Body. (Static Bodies never collide with the world boundary.) + * + * @name Phaser.Physics.Arcade.StaticBody#collideWorldBounds + * @type {boolean} + * @readonly + * @default false + * @since 3.0.0 + */ + this.collideWorldBounds = false; + + /** + * Whether this StaticBody is checked for collisions and for which directions. You can set `checkCollision.none = false` to disable collision checks. + * + * @name Phaser.Physics.Arcade.StaticBody#checkCollision + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * Whether this StaticBody has ever collided with another body and in which direction. + * + * @name Phaser.Physics.Arcade.StaticBody#touching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether this StaticBody was colliding with another body during the last step or any previous step, and in which direction. + * + * @name Phaser.Physics.Arcade.StaticBody#wasTouching + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * Whether this StaticBody has ever collided with a tile or the world boundary. + * + * @name Phaser.Physics.Arcade.StaticBody#blocked + * @type {Phaser.Types.Physics.Arcade.ArcadeBodyCollision} + * @since 3.0.0 + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * The StaticBody's physics type (static by default). + * + * @name Phaser.Physics.Arcade.StaticBody#physicsType + * @type {integer} + * @default Phaser.Physics.Arcade.STATIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.STATIC_BODY; + + /** + * The calculated change in the Static Body's horizontal position during the current step. + * For a static body this is always zero. + * + * @name Phaser.Physics.Arcade.StaticBody#_dx + * @type {number} + * @private + * @default 0 + * @since 3.10.0 + */ + this._dx = 0; + + /** + * The calculated change in the Static Body's vertical position during the current step. + * For a static body this is always zero. + * + * @name Phaser.Physics.Arcade.StaticBody#_dy + * @type {number} + * @private + * @default 0 + * @since 3.10.0 + */ + this._dy = 0; + }, + + /** + * Changes the Game Object this Body is bound to. + * First it removes its reference from the old Game Object, then sets the new one. + * You can optionally update the position and dimensions of this Body to reflect that of the new Game Object. + * + * @method Phaser.Physics.Arcade.StaticBody#setGameObject + * @since 3.1.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The new Game Object that will own this Body. + * @param {boolean} [update=true] - Reposition and resize this Body to match the new Game Object? + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + * + * @see Phaser.Physics.Arcade.StaticBody#updateFromGameObject + */ + setGameObject: function (gameObject, update) + { + if (gameObject && gameObject !== this.gameObject) + { + // Remove this body from the old game object + this.gameObject.body = null; + + gameObject.body = this; + + // Update our reference + this.gameObject = gameObject; + } + + if (update) + { + this.updateFromGameObject(); + } + + return this; + }, + + /** + * Syncs the Static Body's position and size with its parent Game Object. + * + * @method Phaser.Physics.Arcade.StaticBody#updateFromGameObject + * @since 3.1.0 + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + updateFromGameObject: function () + { + this.world.staticTree.remove(this); + + var gameObject = this.gameObject; + + gameObject.getTopLeft(this.position); + + this.width = gameObject.displayWidth; + this.height = gameObject.displayHeight; + + this.halfWidth = Math.abs(this.width / 2); + this.halfHeight = Math.abs(this.height / 2); + + this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + this.world.staticTree.insert(this); + + return this; + }, + + /** + * Positions the Static Body at an offset from its Game Object. + * + * @method Phaser.Physics.Arcade.StaticBody#setOffset + * @since 3.4.0 + * + * @param {number} x - The horizontal offset of the Static Body from the Game Object's `x`. + * @param {number} y - The vertical offset of the Static Body from the Game Object's `y`. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setOffset: function (x, y) + { + if (y === undefined) { y = x; } + + this.world.staticTree.remove(this); + + this.position.x -= this.offset.x; + this.position.y -= this.offset.y; + + this.offset.set(x, y); + + this.position.x += this.offset.x; + this.position.y += this.offset.y; + + this.updateCenter(); + + this.world.staticTree.insert(this); + + return this; + }, + + /** + * Sets the size of the Static Body. + * When `center` is true, also repositions it. + * Resets the width and height to match current frame, if no width and height provided and a frame is found. + * + * @method Phaser.Physics.Arcade.StaticBody#setSize + * @since 3.0.0 + * + * @param {integer} [width] - The width of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param {integer} [height] - The height of the Static Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param {boolean} [center=true] - Place the Static Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setSize: function (width, height, center) + { + if (center === undefined) { center = true; } + + var gameObject = this.gameObject; + + if (!width && gameObject.frame) + { + width = gameObject.frame.realWidth; + } + + if (!height && gameObject.frame) + { + height = gameObject.frame.realHeight; + } + + this.world.staticTree.remove(this); + + this.width = width; + this.height = height; + + this.halfWidth = Math.floor(width / 2); + this.halfHeight = Math.floor(height / 2); + + if (center && gameObject.getCenter) + { + var ox = gameObject.displayWidth / 2; + var oy = gameObject.displayHeight / 2; + + this.position.x -= this.offset.x; + this.position.y -= this.offset.y; + + this.offset.set(ox - this.halfWidth, oy - this.halfHeight); + + this.position.x += this.offset.x; + this.position.y += this.offset.y; + } + + this.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + this.world.staticTree.insert(this); + + return this; + }, + + /** + * Sets this Static Body to have a circular body and sets its size and position. + * + * @method Phaser.Physics.Arcade.StaticBody#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the StaticBody, in pixels. + * @param {number} [offsetX] - The horizontal offset of the StaticBody from its Game Object, in pixels. + * @param {number} [offsetY] - The vertical offset of the StaticBody from its Game Object, in pixels. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setCircle: function (radius, offsetX, offsetY) + { + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.world.staticTree.remove(this); + + this.isCircle = true; + + this.radius = radius; + + this.width = radius * 2; + this.height = radius * 2; + + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + + this.offset.set(offsetX, offsetY); + + this.updateCenter(); + + this.world.staticTree.insert(this); + } + else + { + this.isCircle = false; + } + + return this; + }, + + /** + * Updates the StaticBody's `center` from its `position` and dimensions. + * + * @method Phaser.Physics.Arcade.StaticBody#updateCenter + * @since 3.0.0 + */ + updateCenter: function () + { + this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + }, + + /** + * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. + * + * @method Phaser.Physics.Arcade.StaticBody#reset + * @since 3.0.0 + * + * @param {number} [x] - The x coordinate to reset the body to. If not given will use the parent Game Object's coordinate. + * @param {number} [y] - The y coordinate to reset the body to. If not given will use the parent Game Object's coordinate. + */ + reset: function (x, y) + { + var gameObject = this.gameObject; + + if (x === undefined) { x = gameObject.x; } + if (y === undefined) { y = gameObject.y; } + + this.world.staticTree.remove(this); + + gameObject.setPosition(x, y); + + gameObject.getTopLeft(this.position); + + this.updateCenter(); + + this.world.staticTree.insert(this); + }, + + /** + * NOOP function. A Static Body cannot be stopped. + * + * @method Phaser.Physics.Arcade.StaticBody#stop + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + stop: function () + { + return this; + }, + + /** + * Returns the x and y coordinates of the top left and bottom right points of the StaticBody. + * + * @method Phaser.Physics.Arcade.StaticBody#getBounds + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} obj - The object which will hold the coordinates of the bounds. + * + * @return {Phaser.Types.Physics.Arcade.ArcadeBodyBounds} The same object that was passed with `x`, `y`, `right` and `bottom` values matching the respective values of the StaticBody. + */ + getBounds: function (obj) + { + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + }, + + /** + * Checks to see if a given x,y coordinate is colliding with this Static Body. + * + * @method Phaser.Physics.Arcade.StaticBody#hitTest + * @since 3.0.0 + * + * @param {number} x - The x coordinate to check against this body. + * @param {number} y - The y coordinate to check against this body. + * + * @return {boolean} `true` if the given coordinate lies within this body, otherwise `false`. + */ + hitTest: function (x, y) + { + return (this.isCircle) ? CircleContains(this, x, y) : RectangleContains(this, x, y); + }, + + /** + * NOOP + * + * @method Phaser.Physics.Arcade.StaticBody#postUpdate + * @since 3.12.0 + */ + postUpdate: function () + { + }, + + /** + * The absolute (non-negative) change in this StaticBody's horizontal position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaAbsX + * @since 3.0.0 + * + * @return {number} Always zero for a Static Body. + */ + deltaAbsX: function () + { + return 0; + }, + + /** + * The absolute (non-negative) change in this StaticBody's vertical position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaAbsY + * @since 3.0.0 + * + * @return {number} Always zero for a Static Body. + */ + deltaAbsY: function () + { + return 0; + }, + + /** + * The change in this StaticBody's horizontal position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaX + * @since 3.0.0 + * + * @return {number} The change in this StaticBody's velocity from the previous step. Always zero. + */ + deltaX: function () + { + return 0; + }, + + /** + * The change in this StaticBody's vertical position from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaY + * @since 3.0.0 + * + * @return {number} The change in this StaticBody's velocity from the previous step. Always zero. + */ + deltaY: function () + { + return 0; + }, + + /** + * The change in this StaticBody's rotation from the previous step. Always zero. + * + * @method Phaser.Physics.Arcade.StaticBody#deltaZ + * @since 3.0.0 + * + * @return {number} The change in this StaticBody's rotation from the previous step. Always zero. + */ + deltaZ: function () + { + return 0; + }, + + /** + * Disables this Body and marks it for destruction during the next step. + * + * @method Phaser.Physics.Arcade.StaticBody#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.enable = false; + + this.world.pendingDestroy.set(this); + }, + + /** + * Draws a graphical representation of the StaticBody for visual debugging purposes. + * + * @method Phaser.Physics.Arcade.StaticBody#drawDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphic - The Graphics object to use for the debug drawing of the StaticBody. + */ + drawDebug: function (graphic) + { + var pos = this.position; + + var x = pos.x + this.halfWidth; + var y = pos.y + this.halfHeight; + + if (this.debugShowBody) + { + graphic.lineStyle(graphic.defaultStrokeWidth, this.debugBodyColor, 1); + + if (this.isCircle) + { + graphic.strokeCircle(x, y, this.width / 2); + } + else + { + graphic.strokeRect(pos.x, pos.y, this.width, this.height); + } + + } + }, + + /** + * Indicates whether the StaticBody is going to be showing a debug visualization during postUpdate. + * + * @method Phaser.Physics.Arcade.StaticBody#willDrawDebug + * @since 3.0.0 + * + * @return {boolean} Whether or not the StaticBody is going to show the debug visualization during postUpdate. + */ + willDrawDebug: function () + { + return this.debugShowBody; + }, + + /** + * Sets the Mass of the StaticBody. Will set the Mass to 0.1 if the value passed is less than or equal to zero. + * + * @method Phaser.Physics.Arcade.StaticBody#setMass + * @since 3.0.0 + * + * @param {number} value - The value to set the Mass to. Values of zero or less are changed to 0.1. + * + * @return {Phaser.Physics.Arcade.StaticBody} This Static Body object. + */ + setMass: function (value) + { + if (value <= 0) + { + // Causes havoc otherwise + value = 0.1; + } + + this.mass = value; + + return this; + }, + + /** + * The x coordinate of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.position.x; + }, + + set: function (value) + { + this.world.staticTree.remove(this); + + this.position.x = value; + + this.world.staticTree.insert(this); + } + + }, + + /** + * The y coordinate of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.position.y; + }, + + set: function (value) + { + this.world.staticTree.remove(this); + + this.position.y = value; + + this.world.staticTree.insert(this); + } + + }, + + /** + * Returns the left-most x coordinate of the area of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#left + * @type {number} + * @readonly + * @since 3.0.0 + */ + left: { + + get: function () + { + return this.position.x; + } + + }, + + /** + * The right-most x coordinate of the area of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#right + * @type {number} + * @readonly + * @since 3.0.0 + */ + right: { + + get: function () + { + return this.position.x + this.width; + } + + }, + + /** + * The highest y coordinate of the area of the StaticBody. + * + * @name Phaser.Physics.Arcade.StaticBody#top + * @type {number} + * @readonly + * @since 3.0.0 + */ + top: { + + get: function () + { + return this.position.y; + } + + }, + + /** + * The lowest y coordinate of the area of the StaticBody. (y + height) + * + * @name Phaser.Physics.Arcade.StaticBody#bottom + * @type {number} + * @readonly + * @since 3.0.0 + */ + bottom: { + + get: function () + { + return this.position.y + this.height; + } + + } + +}); + +module.exports = StaticBody; diff --git a/src/physics/arcade/StaticPhysicsGroup.js b/src/physics/arcade/StaticPhysicsGroup.js index a5ff2821a..68ba34245 100644 --- a/src/physics/arcade/StaticPhysicsGroup.js +++ b/src/physics/arcade/StaticPhysicsGroup.js @@ -1,185 +1,185 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArcadeSprite = require('./ArcadeSprite'); -var Class = require('../../utils/Class'); -var CONST = require('./const'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Group = require('../../gameobjects/group/Group'); -var IsPlainObject = require('../../utils/object/IsPlainObject'); - -/** - * @classdesc - * An Arcade Physics Static Group object. - * - * All Game Objects created by this Group will automatically be given static Arcade Physics bodies. - * - * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Group}. - * - * @class StaticGroup - * @extends Phaser.GameObjects.Group - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.World} world - The physics simulation. - * @param {Phaser.Scene} scene - The scene this group belongs to. - * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. - * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. - */ -var StaticPhysicsGroup = new Class({ - - Extends: Group, - - initialize: - - function StaticPhysicsGroup (world, scene, children, config) - { - if (!children && !config) - { - config = { - internalCreateCallback: this.createCallbackHandler, - internalRemoveCallback: this.removeCallbackHandler, - createMultipleCallback: this.createMultipleCallbackHandler, - classType: ArcadeSprite - }; - } - else if (IsPlainObject(children)) - { - // children is a plain object, so swizzle them: - config = children; - children = null; - - config.internalCreateCallback = this.createCallbackHandler; - config.internalRemoveCallback = this.removeCallbackHandler; - config.createMultipleCallback = this.createMultipleCallbackHandler; - config.classType = GetFastValue(config, 'classType', ArcadeSprite); - } - else if (Array.isArray(children) && IsPlainObject(children[0])) - { - // children is an array of plain objects - config = children; - children = null; - - config.forEach(function (singleConfig) - { - singleConfig.internalCreateCallback = this.createCallbackHandler; - singleConfig.internalRemoveCallback = this.removeCallbackHandler; - singleConfig.createMultipleCallback = this.createMultipleCallbackHandler; - singleConfig.classType = GetFastValue(singleConfig, 'classType', ArcadeSprite); - }); - } - - /** - * The physics simulation. - * - * @name Phaser.Physics.Arcade.StaticGroup#world - * @type {Phaser.Physics.Arcade.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The scene this group belongs to. - * - * @name Phaser.Physics.Arcade.StaticGroup#physicsType - * @type {integer} - * @default Phaser.Physics.Arcade.STATIC_BODY - * @since 3.0.0 - */ - this.physicsType = CONST.STATIC_BODY; - - Group.call(this, scene, children, config); - - /** - * A textual representation of this Game Object. - * Used internally by Phaser but is available for your own custom classes to populate. - * - * @name Phaser.Physics.Arcade.StaticGroup#type - * @type {string} - * @default 'StaticPhysicsGroup' - * @since 3.21.0 - */ - this.type = 'StaticPhysicsGroup'; - }, - - /** - * Adds a static physics body to the new group member (if it lacks one) and adds it to the simulation. - * - * @method Phaser.Physics.Arcade.StaticGroup#createCallbackHandler - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The new group member. - * - * @see Phaser.Physics.Arcade.World#enableBody - */ - createCallbackHandler: function (child) - { - if (!child.body) - { - this.world.enableBody(child, CONST.STATIC_BODY); - } - }, - - /** - * Disables the group member's physics body, removing it from the simulation. - * - * @method Phaser.Physics.Arcade.StaticGroup#removeCallbackHandler - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} child - The group member being removed. - * - * @see Phaser.Physics.Arcade.World#disableBody - */ - removeCallbackHandler: function (child) - { - if (child.body) - { - this.world.disableBody(child); - } - }, - - /** - * Refreshes the group. - * - * @method Phaser.Physics.Arcade.StaticGroup#createMultipleCallbackHandler - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject[]} entries - The newly created group members. - * - * @see Phaser.Physics.Arcade.StaticGroup#refresh - */ - createMultipleCallbackHandler: function () - { - this.refresh(); - }, - - /** - * Resets each Body to the position of its parent Game Object. - * Body sizes aren't changed (use {@link Phaser.Physics.Arcade.Components.Enable#refreshBody} for that). - * - * @method Phaser.Physics.Arcade.StaticGroup#refresh - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.StaticGroup} This group. - * - * @see Phaser.Physics.Arcade.StaticBody#reset - */ - refresh: function () - { - var children = this.children.entries; - - for (var i = 0; i < children.length; i++) - { - children[i].body.reset(); - } - - return this; - } - -}); - -module.exports = StaticPhysicsGroup; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArcadeSprite = require('./ArcadeSprite'); +var Class = require('../../utils/Class'); +var CONST = require('./const'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Group = require('../../gameobjects/group/Group'); +var IsPlainObject = require('../../utils/object/IsPlainObject'); + +/** + * @classdesc + * An Arcade Physics Static Group object. + * + * All Game Objects created by this Group will automatically be given static Arcade Physics bodies. + * + * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Group}. + * + * @class StaticGroup + * @extends Phaser.GameObjects.Group + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.World} world - The physics simulation. + * @param {Phaser.Scene} scene - The scene this group belongs to. + * @param {(Phaser.GameObjects.GameObject[]|Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig)} [children] - Game Objects to add to this group; or the `config` argument. + * @param {Phaser.Types.GameObjects.Group.GroupConfig|Phaser.Types.GameObjects.Group.GroupCreateConfig} [config] - Settings for this group. + */ +var StaticPhysicsGroup = new Class({ + + Extends: Group, + + initialize: + + function StaticPhysicsGroup (world, scene, children, config) + { + if (!children && !config) + { + config = { + internalCreateCallback: this.createCallbackHandler, + internalRemoveCallback: this.removeCallbackHandler, + createMultipleCallback: this.createMultipleCallbackHandler, + classType: ArcadeSprite + }; + } + else if (IsPlainObject(children)) + { + // children is a plain object, so swizzle them: + config = children; + children = null; + + config.internalCreateCallback = this.createCallbackHandler; + config.internalRemoveCallback = this.removeCallbackHandler; + config.createMultipleCallback = this.createMultipleCallbackHandler; + config.classType = GetFastValue(config, 'classType', ArcadeSprite); + } + else if (Array.isArray(children) && IsPlainObject(children[0])) + { + // children is an array of plain objects + config = children; + children = null; + + config.forEach(function (singleConfig) + { + singleConfig.internalCreateCallback = this.createCallbackHandler; + singleConfig.internalRemoveCallback = this.removeCallbackHandler; + singleConfig.createMultipleCallback = this.createMultipleCallbackHandler; + singleConfig.classType = GetFastValue(singleConfig, 'classType', ArcadeSprite); + }); + } + + /** + * The physics simulation. + * + * @name Phaser.Physics.Arcade.StaticGroup#world + * @type {Phaser.Physics.Arcade.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The scene this group belongs to. + * + * @name Phaser.Physics.Arcade.StaticGroup#physicsType + * @type {integer} + * @default Phaser.Physics.Arcade.STATIC_BODY + * @since 3.0.0 + */ + this.physicsType = CONST.STATIC_BODY; + + Group.call(this, scene, children, config); + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + * + * @name Phaser.Physics.Arcade.StaticGroup#type + * @type {string} + * @default 'StaticPhysicsGroup' + * @since 3.21.0 + */ + this.type = 'StaticPhysicsGroup'; + }, + + /** + * Adds a static physics body to the new group member (if it lacks one) and adds it to the simulation. + * + * @method Phaser.Physics.Arcade.StaticGroup#createCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The new group member. + * + * @see Phaser.Physics.Arcade.World#enableBody + */ + createCallbackHandler: function (child) + { + if (!child.body) + { + this.world.enableBody(child, CONST.STATIC_BODY); + } + }, + + /** + * Disables the group member's physics body, removing it from the simulation. + * + * @method Phaser.Physics.Arcade.StaticGroup#removeCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} child - The group member being removed. + * + * @see Phaser.Physics.Arcade.World#disableBody + */ + removeCallbackHandler: function (child) + { + if (child.body) + { + this.world.disableBody(child); + } + }, + + /** + * Refreshes the group. + * + * @method Phaser.Physics.Arcade.StaticGroup#createMultipleCallbackHandler + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject[]} entries - The newly created group members. + * + * @see Phaser.Physics.Arcade.StaticGroup#refresh + */ + createMultipleCallbackHandler: function () + { + this.refresh(); + }, + + /** + * Resets each Body to the position of its parent Game Object. + * Body sizes aren't changed (use {@link Phaser.Physics.Arcade.Components.Enable#refreshBody} for that). + * + * @method Phaser.Physics.Arcade.StaticGroup#refresh + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.StaticGroup} This group. + * + * @see Phaser.Physics.Arcade.StaticBody#reset + */ + refresh: function () + { + var children = this.children.entries; + + for (var i = 0; i < children.length; i++) + { + children[i].body.reset(); + } + + return this; + } + +}); + +module.exports = StaticPhysicsGroup; diff --git a/src/physics/arcade/World.js b/src/physics/arcade/World.js index 72766aa6f..e0ebb5581 100644 --- a/src/physics/arcade/World.js +++ b/src/physics/arcade/World.js @@ -1,2383 +1,2383 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('./Body'); -var Clamp = require('../../math/Clamp'); -var Class = require('../../utils/Class'); -var Collider = require('./Collider'); -var CONST = require('./const'); -var DistanceBetween = require('../../math/distance/DistanceBetween'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var FuzzyEqual = require('../../math/fuzzy/Equal'); -var FuzzyGreaterThan = require('../../math/fuzzy/GreaterThan'); -var FuzzyLessThan = require('../../math/fuzzy/LessThan'); -var GetOverlapX = require('./GetOverlapX'); -var GetOverlapY = require('./GetOverlapY'); -var GetValue = require('../../utils/object/GetValue'); -var ProcessQueue = require('../../structs/ProcessQueue'); -var ProcessTileCallbacks = require('./tilemap/ProcessTileCallbacks'); -var Rectangle = require('../../geom/rectangle/Rectangle'); -var RTree = require('../../structs/RTree'); -var SeparateTile = require('./tilemap/SeparateTile'); -var SeparateX = require('./SeparateX'); -var SeparateY = require('./SeparateY'); -var Set = require('../../structs/Set'); -var StaticBody = require('./StaticBody'); -var TileIntersectsBody = require('./tilemap/TileIntersectsBody'); -var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); -var Vector2 = require('../../math/Vector2'); -var Wrap = require('../../math/Wrap'); - -/** - * @classdesc - * The Arcade Physics World. - * - * The World is responsible for creating, managing, colliding and updating all of the bodies within it. - * - * An instance of the World belongs to a Phaser.Scene and is accessed via the property `physics.world`. - * - * @class World - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Physics.Arcade - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this World instance belongs. - * @param {Phaser.Types.Physics.Arcade.ArcadeWorldConfig} config - An Arcade Physics Configuration object. - */ -var World = new Class({ - - Extends: EventEmitter, - - initialize: - - function World (scene, config) - { - EventEmitter.call(this); - - /** - * The Scene this simulation belongs to. - * - * @name Phaser.Physics.Arcade.World#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * Dynamic Bodies in this simulation. - * - * @name Phaser.Physics.Arcade.World#bodies - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.bodies = new Set(); - - /** - * Static Bodies in this simulation. - * - * @name Phaser.Physics.Arcade.World#staticBodies - * @type {Phaser.Structs.Set.} - * @since 3.0.0 - */ - this.staticBodies = new Set(); - - /** - * Static Bodies marked for deletion. - * - * @name Phaser.Physics.Arcade.World#pendingDestroy - * @type {Phaser.Structs.Set.<(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)>} - * @since 3.1.0 - */ - this.pendingDestroy = new Set(); - - /** - * This simulation's collision processors. - * - * @name Phaser.Physics.Arcade.World#colliders - * @type {Phaser.Structs.ProcessQueue.} - * @since 3.0.0 - */ - this.colliders = new ProcessQueue(); - - /** - * Acceleration of Bodies due to gravity, in pixels per second. - * - * @name Phaser.Physics.Arcade.World#gravity - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.gravity = new Vector2(GetValue(config, 'gravity.x', 0), GetValue(config, 'gravity.y', 0)); - - /** - * A boundary constraining Bodies. - * - * @name Phaser.Physics.Arcade.World#bounds - * @type {Phaser.Geom.Rectangle} - * @since 3.0.0 - */ - this.bounds = new Rectangle( - GetValue(config, 'x', 0), - GetValue(config, 'y', 0), - GetValue(config, 'width', scene.sys.scale.width), - GetValue(config, 'height', scene.sys.scale.height) - ); - - /** - * The boundary edges that Bodies can collide with. - * - * @name Phaser.Physics.Arcade.World#checkCollision - * @type {Phaser.Types.Physics.Arcade.CheckCollisionObject} - * @since 3.0.0 - */ - this.checkCollision = { - up: GetValue(config, 'checkCollision.up', true), - down: GetValue(config, 'checkCollision.down', true), - left: GetValue(config, 'checkCollision.left', true), - right: GetValue(config, 'checkCollision.right', true) - }; - - /** - * The number of physics steps to be taken per second. - * - * This property is read-only. Use the `setFPS` method to modify it at run-time. - * - * @name Phaser.Physics.Arcade.World#fps - * @readonly - * @type {number} - * @default 60 - * @since 3.10.0 - */ - this.fps = GetValue(config, 'fps', 60); - - /** - * The amount of elapsed ms since the last frame. - * - * @name Phaser.Physics.Arcade.World#_elapsed - * @private - * @type {number} - * @since 3.10.0 - */ - this._elapsed = 0; - - /** - * Internal frame time value. - * - * @name Phaser.Physics.Arcade.World#_frameTime - * @private - * @type {number} - * @since 3.10.0 - */ - this._frameTime = 1 / this.fps; - - /** - * Internal frame time ms value. - * - * @name Phaser.Physics.Arcade.World#_frameTimeMS - * @private - * @type {number} - * @since 3.10.0 - */ - this._frameTimeMS = 1000 * this._frameTime; - - /** - * The number of steps that took place in the last frame. - * - * @name Phaser.Physics.Arcade.World#stepsLastFrame - * @readonly - * @type {number} - * @since 3.10.0 - */ - this.stepsLastFrame = 0; - - /** - * Scaling factor applied to the frame rate. - * - * - 1.0 = normal speed - * - 2.0 = half speed - * - 0.5 = double speed - * - * @name Phaser.Physics.Arcade.World#timeScale - * @type {number} - * @default 1 - * @since 3.10.0 - */ - this.timeScale = GetValue(config, 'timeScale', 1); - - /** - * The maximum absolute difference of a Body's per-step velocity and its overlap with another Body that will result in separation on *each axis*. - * Larger values favor separation. - * Smaller values favor no separation. - * - * @name Phaser.Physics.Arcade.World#OVERLAP_BIAS - * @type {number} - * @default 4 - * @since 3.0.0 - */ - this.OVERLAP_BIAS = GetValue(config, 'overlapBias', 4); - - /** - * The maximum absolute value of a Body's overlap with a tile that will result in separation on *each axis*. - * Larger values favor separation. - * Smaller values favor no separation. - * The optimum value may be similar to the tile size. - * - * @name Phaser.Physics.Arcade.World#TILE_BIAS - * @type {number} - * @default 16 - * @since 3.0.0 - */ - this.TILE_BIAS = GetValue(config, 'tileBias', 16); - - /** - * Always separate overlapping Bodies horizontally before vertically. - * False (the default) means Bodies are first separated on the axis of greater gravity, or the vertical axis if neither is greater. - * - * @name Phaser.Physics.Arcade.World#forceX - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.forceX = GetValue(config, 'forceX', false); - - /** - * Whether the simulation advances with the game loop. - * - * @name Phaser.Physics.Arcade.World#isPaused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.isPaused = GetValue(config, 'isPaused', false); - - /** - * Temporary total of colliding Bodies. - * - * @name Phaser.Physics.Arcade.World#_total - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._total = 0; - - /** - * Enables the debug display. - * - * @name Phaser.Physics.Arcade.World#drawDebug - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.drawDebug = GetValue(config, 'debug', false); - - /** - * The graphics object drawing the debug display. - * - * @name Phaser.Physics.Arcade.World#debugGraphic - * @type {Phaser.GameObjects.Graphics} - * @since 3.0.0 - */ - this.debugGraphic; - - /** - * Default debug display settings for new Bodies. - * - * @name Phaser.Physics.Arcade.World#defaults - * @type {Phaser.Types.Physics.Arcade.ArcadeWorldDefaults} - * @since 3.0.0 - */ - this.defaults = { - debugShowBody: GetValue(config, 'debugShowBody', true), - debugShowStaticBody: GetValue(config, 'debugShowStaticBody', true), - debugShowVelocity: GetValue(config, 'debugShowVelocity', true), - bodyDebugColor: GetValue(config, 'debugBodyColor', 0xff00ff), - staticBodyDebugColor: GetValue(config, 'debugStaticBodyColor', 0x0000ff), - velocityDebugColor: GetValue(config, 'debugVelocityColor', 0x00ff00) - }; - - /** - * The maximum number of items per node on the RTree. - * - * This is ignored if `useTree` is `false`. If you have a large number of bodies in - * your world then you may find search performance improves by increasing this value, - * to allow more items per node and less node division. - * - * @name Phaser.Physics.Arcade.World#maxEntries - * @type {integer} - * @default 16 - * @since 3.0.0 - */ - this.maxEntries = GetValue(config, 'maxEntries', 16); - - /** - * Should this Arcade Physics World use an RTree for Dynamic and Static Physics bodies? - * - * An RTree is a fast way of spatially sorting of all the bodies in the world. - * However, at certain limits, the cost of clearing and inserting the bodies into the - * tree every frame becomes more expensive than the search speed gains it provides. - * - * If you have a large number of dynamic bodies in your world then it may be best to - * disable the use of the RTree by setting this property to `false` in the physics config. - * - * The number it can cope with depends on browser and device, but a conservative estimate - * of around 5,000 bodies should be considered the max before disabling it. - * - * This only applies to dynamic bodies. Static bodies are always kept in an RTree, - * because they don't have to be cleared every frame, so you benefit from the - * massive search speeds all the time. - * - * @name Phaser.Physics.Arcade.World#useTree - * @type {boolean} - * @default true - * @since 3.10.0 - */ - this.useTree = GetValue(config, 'useTree', true); - - /** - * The spatial index of Dynamic Bodies. - * - * @name Phaser.Physics.Arcade.World#tree - * @type {Phaser.Structs.RTree} - * @since 3.0.0 - */ - this.tree = new RTree(this.maxEntries); - - /** - * The spatial index of Static Bodies. - * - * @name Phaser.Physics.Arcade.World#staticTree - * @type {Phaser.Structs.RTree} - * @since 3.0.0 - */ - this.staticTree = new RTree(this.maxEntries); - - /** - * Recycled input for tree searches. - * - * @name Phaser.Physics.Arcade.World#treeMinMax - * @type {Phaser.Types.Physics.Arcade.ArcadeWorldTreeMinMax} - * @since 3.0.0 - */ - this.treeMinMax = { minX: 0, minY: 0, maxX: 0, maxY: 0 }; - - /** - * A temporary Transform Matrix used by bodies for calculations without them needing their own local copy. - * - * @name Phaser.Physics.Arcade.World#_tempMatrix - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @private - * @since 3.12.0 - */ - this._tempMatrix = new TransformMatrix(); - - /** - * A temporary Transform Matrix used by bodies for calculations without them needing their own local copy. - * - * @name Phaser.Physics.Arcade.World#_tempMatrix2 - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @private - * @since 3.12.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - if (this.drawDebug) - { - this.createDebugGraphic(); - } - }, - - /** - * Adds an Arcade Physics Body to a Game Object, an array of Game Objects, or the children of a Group. - * - * The difference between this and the `enableBody` method is that you can pass arrays or Groups - * to this method. - * - * You can specify if the bodies are to be Dynamic or Static. A dynamic body can move via velocity and - * acceleration. A static body remains fixed in place and as such is able to use an optimized search - * tree, making it ideal for static elements such as level objects. You can still collide and overlap - * with static bodies. - * - * Normally, rather than calling this method directly, you'd use the helper methods available in the - * Arcade Physics Factory, such as: - * - * ```javascript - * this.physics.add.image(x, y, textureKey); - * this.physics.add.sprite(x, y, textureKey); - * ``` - * - * Calling factory methods encapsulates the creation of a Game Object and the creation of its - * body at the same time. If you are creating custom classes then you can pass them to this - * method to have their bodies created. - * - * @method Phaser.Physics.Arcade.World#enable - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object - The object, or objects, on which to create the bodies. - * @param {integer} [bodyType] - The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. - */ - enable: function (object, bodyType) - { - if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY; } - - if (!Array.isArray(object)) - { - object = [ object ]; - } - - for (var i = 0; i < object.length; i++) - { - var entry = object[i]; - - if (entry.isParent) - { - var children = entry.getChildren(); - - for (var c = 0; c < children.length; c++) - { - var child = children[c]; - - if (child.isParent) - { - // Handle Groups nested inside of Groups - this.enable(child, bodyType); - } - else - { - this.enableBody(child, bodyType); - } - } - } - else - { - this.enableBody(entry, bodyType); - } - } - }, - - /** - * Creates an Arcade Physics Body on a single Game Object. - * - * If the Game Object already has a body, this method will simply add it back into the simulation. - * - * You can specify if the body is Dynamic or Static. A dynamic body can move via velocity and - * acceleration. A static body remains fixed in place and as such is able to use an optimized search - * tree, making it ideal for static elements such as level objects. You can still collide and overlap - * with static bodies. - * - * Normally, rather than calling this method directly, you'd use the helper methods available in the - * Arcade Physics Factory, such as: - * - * ```javascript - * this.physics.add.image(x, y, textureKey); - * this.physics.add.sprite(x, y, textureKey); - * ``` - * - * Calling factory methods encapsulates the creation of a Game Object and the creation of its - * body at the same time. If you are creating custom classes then you can pass them to this - * method to have their bodies created. - * - * @method Phaser.Physics.Arcade.World#enableBody - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} object - The Game Object on which to create the body. - * @param {integer} [bodyType] - The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. - * - * @return {Phaser.GameObjects.GameObject} The Game Object on which the body was created. - */ - enableBody: function (object, bodyType) - { - if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY; } - - if (!object.body) - { - if (bodyType === CONST.DYNAMIC_BODY) - { - object.body = new Body(this, object); - } - else if (bodyType === CONST.STATIC_BODY) - { - object.body = new StaticBody(this, object); - } - } - - this.add(object.body); - - return object; - }, - - /** - * Adds an existing Arcade Physics Body or StaticBody to the simulation. - * - * The body is enabled and added to the local search trees. - * - * @method Phaser.Physics.Arcade.World#add - * @since 3.10.0 - * - * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The Body to be added to the simulation. - * - * @return {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} The Body that was added to the simulation. - */ - add: function (body) - { - if (body.physicsType === CONST.DYNAMIC_BODY) - { - this.bodies.set(body); - } - else if (body.physicsType === CONST.STATIC_BODY) - { - this.staticBodies.set(body); - - this.staticTree.insert(body); - } - - body.enable = true; - - return body; - }, - - /** - * Disables the Arcade Physics Body of a Game Object, an array of Game Objects, or the children of a Group. - * - * The difference between this and the `disableBody` method is that you can pass arrays or Groups - * to this method. - * - * The body itself is not deleted, it just has its `enable` property set to false, which - * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. - * - * @method Phaser.Physics.Arcade.World#disable - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object - The object, or objects, on which to disable the bodies. - */ - disable: function (object) - { - if (!Array.isArray(object)) - { - object = [ object ]; - } - - for (var i = 0; i < object.length; i++) - { - var entry = object[i]; - - if (entry.isParent) - { - var children = entry.getChildren(); - - for (var c = 0; c < children.length; c++) - { - var child = children[c]; - - if (child.isParent) - { - // Handle Groups nested inside of Groups - this.disable(child); - } - else - { - this.disableBody(child.body); - } - } - } - else - { - this.disableBody(entry.body); - } - } - }, - - /** - * Disables an existing Arcade Physics Body or StaticBody and removes it from the simulation. - * - * The body is disabled and removed from the local search trees. - * - * The body itself is not deleted, it just has its `enable` property set to false, which - * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. - * - * @method Phaser.Physics.Arcade.World#disableBody - * @since 3.0.0 - * - * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The Body to be disabled. - */ - disableBody: function (body) - { - this.remove(body); - - body.enable = false; - }, - - /** - * Removes an existing Arcade Physics Body or StaticBody from the simulation. - * - * The body is disabled and removed from the local search trees. - * - * The body itself is not deleted, it just has its `enabled` property set to false, which - * means you can re-enable it again at any point by passing it to enable `enable` or `add`. - * - * @method Phaser.Physics.Arcade.World#remove - * @since 3.0.0 - * - * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The body to be removed from the simulation. - */ - remove: function (body) - { - if (body.physicsType === CONST.DYNAMIC_BODY) - { - this.tree.remove(body); - this.bodies.delete(body); - } - else if (body.physicsType === CONST.STATIC_BODY) - { - this.staticBodies.delete(body); - this.staticTree.remove(body); - } - }, - - /** - * Creates a Graphics Game Object that the world will use to render the debug display to. - * - * This is called automatically when the World is instantiated if the `debug` config property - * was set to `true`. However, you can call it at any point should you need to display the - * debug Graphic from a fixed point. - * - * You can control which objects are drawn to the Graphics object, and the colors they use, - * by setting the debug properties in the physics config. - * - * You should not typically use this in a production game. Use it to aid during debugging. - * - * @method Phaser.Physics.Arcade.World#createDebugGraphic - * @since 3.0.0 - * - * @return {Phaser.GameObjects.Graphics} The Graphics object that was created for use by the World. - */ - createDebugGraphic: function () - { - var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); - - graphic.setDepth(Number.MAX_VALUE); - - this.debugGraphic = graphic; - - this.drawDebug = true; - - return graphic; - }, - - /** - * Sets the position, size and properties of the World boundary. - * - * The World boundary is an invisible rectangle that defines the edges of the World. - * If a Body is set to collide with the world bounds then it will automatically stop - * when it reaches any of the edges. You can optionally set which edges of the boundary - * should be checked against. - * - * @method Phaser.Physics.Arcade.World#setBounds - * @since 3.0.0 - * - * @param {number} x - The top-left x coordinate of the boundary. - * @param {number} y - The top-left y coordinate of the boundary. - * @param {number} width - The width of the boundary. - * @param {number} height - The height of the boundary. - * @param {boolean} [checkLeft] - Should bodies check against the left edge of the boundary? - * @param {boolean} [checkRight] - Should bodies check against the right edge of the boundary? - * @param {boolean} [checkUp] - Should bodies check against the top edge of the boundary? - * @param {boolean} [checkDown] - Should bodies check against the bottom edge of the boundary? - * - * @return {Phaser.Physics.Arcade.World} This World object. - */ - setBounds: function (x, y, width, height, checkLeft, checkRight, checkUp, checkDown) - { - this.bounds.setTo(x, y, width, height); - - if (checkLeft !== undefined) - { - this.setBoundsCollision(checkLeft, checkRight, checkUp, checkDown); - } - - return this; - }, - - /** - * Enables or disables collisions on each edge of the World boundary. - * - * @method Phaser.Physics.Arcade.World#setBoundsCollision - * @since 3.0.0 - * - * @param {boolean} [left=true] - Should bodies check against the left edge of the boundary? - * @param {boolean} [right=true] - Should bodies check against the right edge of the boundary? - * @param {boolean} [up=true] - Should bodies check against the top edge of the boundary? - * @param {boolean} [down=true] - Should bodies check against the bottom edge of the boundary? - * - * @return {Phaser.Physics.Arcade.World} This World object. - */ - setBoundsCollision: function (left, right, up, down) - { - if (left === undefined) { left = true; } - if (right === undefined) { right = true; } - if (up === undefined) { up = true; } - if (down === undefined) { down = true; } - - this.checkCollision.left = left; - this.checkCollision.right = right; - this.checkCollision.up = up; - this.checkCollision.down = down; - - return this; - }, - - /** - * Pauses the simulation. - * - * A paused simulation does not update any existing bodies, or run any Colliders. - * - * However, you can still enable and disable bodies within it, or manually run collide or overlap - * checks. - * - * @method Phaser.Physics.Arcade.World#pause - * @fires Phaser.Physics.Arcade.Events#PAUSE - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.World} This World object. - */ - pause: function () - { - this.isPaused = true; - - this.emit(Events.PAUSE); - - return this; - }, - - /** - * Resumes the simulation, if paused. - * - * @method Phaser.Physics.Arcade.World#resume - * @fires Phaser.Physics.Arcade.Events#RESUME - * @since 3.0.0 - * - * @return {Phaser.Physics.Arcade.World} This World object. - */ - resume: function () - { - this.isPaused = false; - - this.emit(Events.RESUME); - - return this; - }, - - /** - * Creates a new Collider object and adds it to the simulation. - * - * A Collider is a way to automatically perform collision checks between two objects, - * calling the collide and process callbacks if they occur. - * - * Colliders are run as part of the World update, after all of the Bodies have updated. - * - * By creating a Collider you don't need then call `World.collide` in your `update` loop, - * as it will be handled for you automatically. - * - * @method Phaser.Physics.Arcade.World#addCollider - * @since 3.0.0 - * @see Phaser.Physics.Arcade.World#collide - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. - * @param {*} [callbackContext] - The scope in which to call the callbacks. - * - * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. - */ - addCollider: function (object1, object2, collideCallback, processCallback, callbackContext) - { - if (collideCallback === undefined) { collideCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = collideCallback; } - - var collider = new Collider(this, false, object1, object2, collideCallback, processCallback, callbackContext); - - this.colliders.add(collider); - - return collider; - }, - - /** - * Creates a new Overlap Collider object and adds it to the simulation. - * - * A Collider is a way to automatically perform overlap checks between two objects, - * calling the collide and process callbacks if they occur. - * - * Colliders are run as part of the World update, after all of the Bodies have updated. - * - * By creating a Collider you don't need then call `World.overlap` in your `update` loop, - * as it will be handled for you automatically. - * - * @method Phaser.Physics.Arcade.World#addOverlap - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for overlap. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for overlap. - * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects overlap. - * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects overlap. Must return a boolean. - * @param {*} [callbackContext] - The scope in which to call the callbacks. - * - * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. - */ - addOverlap: function (object1, object2, collideCallback, processCallback, callbackContext) - { - if (collideCallback === undefined) { collideCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = collideCallback; } - - var collider = new Collider(this, true, object1, object2, collideCallback, processCallback, callbackContext); - - this.colliders.add(collider); - - return collider; - }, - - /** - * Removes a Collider from the simulation so it is no longer processed. - * - * This method does not destroy the Collider. If you wish to add it back at a later stage you can call - * `World.colliders.add(Collider)`. - * - * If you no longer need the Collider you can call the `Collider.destroy` method instead, which will - * automatically clear all of its references and then remove it from the World. If you call destroy on - * a Collider you _don't_ need to pass it to this method too. - * - * @method Phaser.Physics.Arcade.World#removeCollider - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Collider} collider - The Collider to remove from the simulation. - * - * @return {Phaser.Physics.Arcade.World} This World object. - */ - removeCollider: function (collider) - { - this.colliders.remove(collider); - - return this; - }, - - /** - * Sets the frame rate to run the simulation at. - * - * The frame rate value is used to simulate a fixed update time step. This fixed - * time step allows for a straightforward implementation of a deterministic game state. - * - * This frame rate is independent of the frequency at which the game is rendering. The - * higher you set the fps, the more physics simulation steps will occur per game step. - * Conversely, the lower you set it, the less will take place. - * - * You can optionally advance the simulation directly yourself by calling the `step` method. - * - * @method Phaser.Physics.Arcade.World#setFPS - * @since 3.10.0 - * - * @param {integer} framerate - The frame rate to advance the simulation at. - * - * @return {this} This World object. - */ - setFPS: function (framerate) - { - this.fps = framerate; - this._frameTime = 1 / this.fps; - this._frameTimeMS = 1000 * this._frameTime; - - return this; - }, - - /** - * 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 - * @protected - * @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. - */ - update: function (time, delta) - { - if (this.isPaused || this.bodies.size === 0) - { - return; - } - - var i; - var fixedDelta = this._frameTime; - var msPerFrame = this._frameTimeMS * this.timeScale; - - this._elapsed += delta; - - // Update all active bodies - var body; - var bodies = this.bodies.entries; - - // Will a step happen this frame? - var willStep = (this._elapsed >= msPerFrame); - - for (i = 0; i < bodies.length; i++) - { - body = bodies[i]; - - if (body.enable) - { - body.preUpdate(willStep, fixedDelta); - } - } - - // We know that a step will happen this frame, so let's bundle it all together to save branching and iteration costs - if (willStep) - { - this._elapsed -= msPerFrame; - this.stepsLastFrame = 1; - - // Optionally populate our dynamic collision tree - if (this.useTree) - { - this.tree.clear(); - this.tree.load(bodies); - } - - // Process any colliders - var colliders = this.colliders.update(); - - for (i = 0; i < colliders.length; i++) - { - var collider = colliders[i]; - - if (collider.active) - { - collider.update(); - } - } - - this.emit(Events.WORLD_STEP); - } - - // Process any additional steps this frame - while (this._elapsed >= msPerFrame) - { - this._elapsed -= msPerFrame; - - this.step(fixedDelta); - } - }, - - /** - * Advances the simulation by a time increment. - * - * @method Phaser.Physics.Arcade.World#step - * @fires Phaser.Physics.Arcade.Events#WORLD_STEP - * @since 3.10.0 - * - * @param {number} delta - The delta time amount, in seconds, by which to advance the simulation. - */ - step: function (delta) - { - // Update all active bodies - var i; - var body; - var bodies = this.bodies.entries; - var len = bodies.length; - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body.enable) - { - body.update(delta); - } - } - - // Optionally populate our dynamic collision tree - if (this.useTree) - { - this.tree.clear(); - this.tree.load(bodies); - } - - // Process any colliders - var colliders = this.colliders.update(); - - for (i = 0; i < colliders.length; i++) - { - var collider = colliders[i]; - - if (collider.active) - { - collider.update(); - } - } - - this.emit(Events.WORLD_STEP); - - this.stepsLastFrame++; - }, - - /** - * Updates bodies, draws the debug display, and handles pending queue operations. - * - * @method Phaser.Physics.Arcade.World#postUpdate - * @since 3.0.0 - */ - postUpdate: function () - { - var i; - var body; - var bodies = this.bodies.entries; - var len = bodies.length; - - var dynamic = this.bodies; - var staticBodies = this.staticBodies; - - // We don't need to postUpdate if there wasn't a step this frame - if (this.stepsLastFrame) - { - this.stepsLastFrame = 0; - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body.enable) - { - body.postUpdate(); - } - } - } - - if (this.drawDebug) - { - var graphics = this.debugGraphic; - - graphics.clear(); - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body.willDrawDebug()) - { - body.drawDebug(graphics); - } - } - - bodies = staticBodies.entries; - len = bodies.length; - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body.willDrawDebug()) - { - body.drawDebug(graphics); - } - } - } - - var pending = this.pendingDestroy; - - if (pending.size > 0) - { - var dynamicTree = this.tree; - var staticTree = this.staticTree; - - bodies = pending.entries; - len = bodies.length; - - for (i = 0; i < len; i++) - { - body = bodies[i]; - - if (body.physicsType === CONST.DYNAMIC_BODY) - { - dynamicTree.remove(body); - dynamic.delete(body); - } - else if (body.physicsType === CONST.STATIC_BODY) - { - staticTree.remove(body); - staticBodies.delete(body); - } - - body.world = undefined; - body.gameObject = undefined; - } - - pending.clear(); - } - }, - - /** - * Calculates a Body's velocity and updates its position. - * - * @method Phaser.Physics.Arcade.World#updateMotion - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body - The Body to be updated. - * @param {number} delta - The delta value to be used in the motion calculations, in seconds. - */ - updateMotion: function (body, delta) - { - if (body.allowRotation) - { - this.computeAngularVelocity(body, delta); - } - - this.computeVelocity(body, delta); - }, - - /** - * Calculates a Body's angular velocity. - * - * @method Phaser.Physics.Arcade.World#computeAngularVelocity - * @since 3.10.0 - * - * @param {Phaser.Physics.Arcade.Body} body - The Body to compute the velocity for. - * @param {number} delta - The delta value to be used in the calculation, in seconds. - */ - computeAngularVelocity: function (body, delta) - { - var velocity = body.angularVelocity; - var acceleration = body.angularAcceleration; - var drag = body.angularDrag; - var max = body.maxAngular; - - if (acceleration) - { - velocity += acceleration * delta; - } - else if (body.allowDrag && drag) - { - drag *= delta; - - if (FuzzyGreaterThan(velocity - drag, 0, 0.1)) - { - velocity -= drag; - } - else if (FuzzyLessThan(velocity + drag, 0, 0.1)) - { - velocity += drag; - } - else - { - velocity = 0; - } - } - - velocity = Clamp(velocity, -max, max); - - var velocityDelta = velocity - body.angularVelocity; - - body.angularVelocity += velocityDelta; - body.rotation += (body.angularVelocity * delta); - }, - - /** - * Calculates a Body's per-axis velocity. - * - * @method Phaser.Physics.Arcade.World#computeVelocity - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body - The Body to compute the velocity for. - * @param {number} delta - The delta value to be used in the calculation, in seconds. - */ - computeVelocity: function (body, delta) - { - var velocityX = body.velocity.x; - var accelerationX = body.acceleration.x; - var dragX = body.drag.x; - var maxX = body.maxVelocity.x; - - var velocityY = body.velocity.y; - var accelerationY = body.acceleration.y; - var dragY = body.drag.y; - var maxY = body.maxVelocity.y; - - var speed = body.speed; - var maxSpeed = body.maxSpeed; - var allowDrag = body.allowDrag; - var useDamping = body.useDamping; - - if (body.allowGravity) - { - velocityX += (this.gravity.x + body.gravity.x) * delta; - velocityY += (this.gravity.y + body.gravity.y) * delta; - } - - if (accelerationX) - { - velocityX += accelerationX * delta; - } - else if (allowDrag && dragX) - { - if (useDamping) - { - // Damping based deceleration - - velocityX *= dragX; - - speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY); - - if (FuzzyEqual(speed, 0, 0.001)) - { - velocityX = 0; - } - } - else - { - // Linear deceleration - dragX *= delta; - - if (FuzzyGreaterThan(velocityX - dragX, 0, 0.01)) - { - velocityX -= dragX; - } - else if (FuzzyLessThan(velocityX + dragX, 0, 0.01)) - { - velocityX += dragX; - } - else - { - velocityX = 0; - } - } - } - - if (accelerationY) - { - velocityY += accelerationY * delta; - } - else if (allowDrag && dragY) - { - if (useDamping) - { - // Damping based deceleration - velocityY *= dragY; - - speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY); - - if (FuzzyEqual(speed, 0, 0.001)) - { - velocityY = 0; - } - } - else - { - // Linear deceleration - dragY *= delta; - - if (FuzzyGreaterThan(velocityY - dragY, 0, 0.01)) - { - velocityY -= dragY; - } - else if (FuzzyLessThan(velocityY + dragY, 0, 0.01)) - { - velocityY += dragY; - } - else - { - velocityY = 0; - } - } - } - - velocityX = Clamp(velocityX, -maxX, maxX); - velocityY = Clamp(velocityY, -maxY, maxY); - - body.velocity.set(velocityX, velocityY); - - if (maxSpeed > -1 && speed > maxSpeed) - { - body.velocity.normalize().scale(maxSpeed); - speed = maxSpeed; - } - - body.speed = speed; - }, - - /** - * Separates two Bodies. - * - * @method Phaser.Physics.Arcade.World#separate - * @fires Phaser.Physics.Arcade.Events#COLLIDE - * @fires Phaser.Physics.Arcade.Events#OVERLAP - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to be separated. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to be separated. - * @param {ArcadePhysicsCallback} [processCallback] - The process callback. - * @param {*} [callbackContext] - The context in which to invoke the callback. - * @param {boolean} [overlapOnly] - If this a collide or overlap check? - * - * @return {boolean} True if separation occurred, otherwise false. - */ - separate: function (body1, body2, processCallback, callbackContext, overlapOnly) - { - if ( - !body1.enable || - !body2.enable || - body1.checkCollision.none || - body2.checkCollision.none || - !this.intersects(body1, body2)) - { - return false; - } - - // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. - if (processCallback && processCallback.call(callbackContext, body1.gameObject, body2.gameObject) === false) - { - return false; - } - - // Circle vs. Circle quick bail out - if (body1.isCircle && body2.isCircle) - { - return this.separateCircle(body1, body2, overlapOnly); - } - - // We define the behavior of bodies in a collision circle and rectangle - // If a collision occurs in the corner points of the rectangle, the body behave like circles - - // Either body1 or body2 is a circle - if (body1.isCircle !== body2.isCircle) - { - var bodyRect = (body1.isCircle) ? body2 : body1; - var bodyCircle = (body1.isCircle) ? body1 : body2; - - var rect = { - x: bodyRect.x, - y: bodyRect.y, - right: bodyRect.right, - bottom: bodyRect.bottom - }; - - var circle = bodyCircle.center; - - if (circle.y < rect.y || circle.y > rect.bottom) - { - if (circle.x < rect.x || circle.x > rect.right) - { - return this.separateCircle(body1, body2, overlapOnly); - } - } - } - - var resultX = false; - var resultY = false; - - // Do we separate on x or y first? - if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) - { - resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); - - // Are they still intersecting? Let's do the other axis then - if (this.intersects(body1, body2)) - { - resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); - } - } - else - { - resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); - - // Are they still intersecting? Let's do the other axis then - if (this.intersects(body1, body2)) - { - resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); - } - } - - var result = (resultX || resultY); - - if (result) - { - if (overlapOnly) - { - if (body1.onOverlap || body2.onOverlap) - { - this.emit(Events.OVERLAP, body1.gameObject, body2.gameObject, body1, body2); - } - } - else if (body1.onCollide || body2.onCollide) - { - this.emit(Events.COLLIDE, body1.gameObject, body2.gameObject, body1, body2); - } - } - - return result; - }, - - /** - * Separates two Bodies, when both are circular. - * - * @method Phaser.Physics.Arcade.World#separateCircle - * @fires Phaser.Physics.Arcade.Events#COLLIDE - * @fires Phaser.Physics.Arcade.Events#OVERLAP - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to be separated. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to be separated. - * @param {boolean} [overlapOnly] - If this a collide or overlap check? - * @param {number} [bias] - A small value added to the calculations. - * - * @return {boolean} True if separation occurred, otherwise false. - */ - separateCircle: function (body1, body2, overlapOnly, bias) - { - // Set the bounding box overlap values into the bodies themselves (hence we don't use the return values here) - GetOverlapX(body1, body2, false, bias); - GetOverlapY(body1, body2, false, bias); - - var overlap = 0; - - if (body1.isCircle !== body2.isCircle) - { - var rect = { - x: (body2.isCircle) ? body1.position.x : body2.position.x, - y: (body2.isCircle) ? body1.position.y : body2.position.y, - right: (body2.isCircle) ? body1.right : body2.right, - bottom: (body2.isCircle) ? body1.bottom : body2.bottom - }; - - var circle = { - x: (body1.isCircle) ? body1.center.x : body2.center.x, - y: (body1.isCircle) ? body1.center.y : body2.center.y, - radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth - }; - - if (circle.y < rect.y) - { - if (circle.x < rect.x) - { - overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.y) - circle.radius; - } - else if (circle.x > rect.right) - { - overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.y) - circle.radius; - } - } - else if (circle.y > rect.bottom) - { - if (circle.x < rect.x) - { - overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; - } - else if (circle.x > rect.right) - { - overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; - } - } - - overlap *= -1; - } - else - { - overlap = (body1.halfWidth + body2.halfWidth) - DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y); - } - - // Can't separate two immovable bodies, or a body with its own custom separation logic - if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) - { - if (overlap !== 0 && (body1.onOverlap || body2.onOverlap)) - { - this.emit(Events.OVERLAP, body1.gameObject, body2.gameObject, body1, body2); - } - - // return true if there was some overlap, otherwise false - return (overlap !== 0); - } - - var dx = body1.center.x - body2.center.x; - var dy = body1.center.y - body2.center.y; - var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); - var nx = ((body2.center.x - body1.center.x) / d) || 0; - var ny = ((body2.center.y - body1.center.y) / d) || 0; - var p = 2 * (body1.velocity.x * nx + body1.velocity.y * ny - body2.velocity.x * nx - body2.velocity.y * ny) / (body1.mass + body2.mass); - - if (!body1.immovable) - { - body1.velocity.x = (body1.velocity.x - p * body1.mass * nx); - body1.velocity.y = (body1.velocity.y - p * body1.mass * ny); - } - - if (!body2.immovable) - { - body2.velocity.x = (body2.velocity.x + p * body2.mass * nx); - body2.velocity.y = (body2.velocity.y + p * body2.mass * ny); - } - - var dvx = body2.velocity.x - body1.velocity.x; - var dvy = body2.velocity.y - body1.velocity.y; - var angleCollision = Math.atan2(dvy, dvx); - - var delta = this._frameTime; - - if (!body1.immovable && !body2.immovable) - { - overlap /= 2; - } - - if (!body1.immovable) - { - body1.x += (body1.velocity.x * delta) - overlap * Math.cos(angleCollision); - body1.y += (body1.velocity.y * delta) - overlap * Math.sin(angleCollision); - } - - if (!body2.immovable) - { - body2.x += (body2.velocity.x * delta) + overlap * Math.cos(angleCollision); - body2.y += (body2.velocity.y * delta) + overlap * Math.sin(angleCollision); - } - - body1.velocity.x *= body1.bounce.x; - body1.velocity.y *= body1.bounce.y; - body2.velocity.x *= body2.bounce.x; - body2.velocity.y *= body2.bounce.y; - - if (body1.onCollide || body2.onCollide) - { - this.emit(Events.COLLIDE, body1.gameObject, body2.gameObject, body1, body2); - } - - return true; - }, - - /** - * Checks to see if two Bodies intersect at all. - * - * @method Phaser.Physics.Arcade.World#intersects - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body1 - The first body to check. - * @param {Phaser.Physics.Arcade.Body} body2 - The second body to check. - * - * @return {boolean} True if the two bodies intersect, otherwise false. - */ - intersects: function (body1, body2) - { - if (body1 === body2) - { - return false; - } - - if (!body1.isCircle && !body2.isCircle) - { - // Rect vs. Rect - return !( - body1.right <= body2.position.x || - body1.bottom <= body2.position.y || - body1.position.x >= body2.right || - body1.position.y >= body2.bottom - ); - } - else if (body1.isCircle) - { - if (body2.isCircle) - { - // Circle vs. Circle - return DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); - } - else - { - // Circle vs. Rect - return this.circleBodyIntersects(body1, body2); - } - } - else - { - // Rect vs. Circle - return this.circleBodyIntersects(body2, body1); - } - }, - - /** - * Tests if a circular Body intersects with another Body. - * - * @method Phaser.Physics.Arcade.World#circleBodyIntersects - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} circle - The circular body to test. - * @param {Phaser.Physics.Arcade.Body} body - The rectangular body to test. - * - * @return {boolean} True if the two bodies intersect, otherwise false. - */ - circleBodyIntersects: function (circle, body) - { - var x = Clamp(circle.center.x, body.left, body.right); - var y = Clamp(circle.center.y, body.top, body.bottom); - - var dx = (circle.center.x - x) * (circle.center.x - x); - var dy = (circle.center.y - y) * (circle.center.y - y); - - return (dx + dy) <= (circle.halfWidth * circle.halfWidth); - }, - - /** - * Tests if Game Objects overlap. - * - * @method Phaser.Physics.Arcade.World#overlap - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. - * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the objects overlap. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. - * @param {*} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if at least one Game Object overlaps another. - */ - overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) - { - if (overlapCallback === undefined) { overlapCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = overlapCallback; } - - return this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); - }, - - /** - * Performs a collision check and separation between the two physics enabled objects given, which can be single - * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. - * - * If you don't require separation then use {@link #overlap} instead. - * - * If two Groups or arrays are passed, each member of one will be tested against each member of the other. - * - * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. - * - * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. - * - * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding - * objects are passed to it. - * - * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable - * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. - * The separation that stops two objects penetrating may create a new penetration against a different object. If you - * require a high level of stability please consider using an alternative physics system, such as Matter.js. - * - * @method Phaser.Physics.Arcade.World#collide - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} `true` if any overlapping Game Objects were separated, otherwise `false`. - */ - collide: function (object1, object2, collideCallback, processCallback, callbackContext) - { - if (collideCallback === undefined) { collideCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = collideCallback; } - - return this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); - }, - - /** - * Internal helper function. Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideObjects - * @private - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object to check for collision. - * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. - * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. - * @param {any} callbackContext - The scope in which to call the callbacks. - * @param {boolean} overlapOnly - Whether this is a collision or overlap check. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) - { - var i; - var j; - - if (object1.isParent && object1.physicsType === undefined) - { - object1 = object1.children.entries; - } - - if (object2 && object2.isParent && object2.physicsType === undefined) - { - object2 = object2.children.entries; - } - - var object1isArray = Array.isArray(object1); - var object2isArray = Array.isArray(object2); - - this._total = 0; - - if (!object1isArray && !object2isArray) - { - // Neither of them are arrays - do this first as it's the most common use-case - this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - else if (!object1isArray && object2isArray) - { - // Object 2 is an Array - for (i = 0; i < object2.length; i++) - { - this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); - } - } - else if (object1isArray && !object2isArray) - { - // Object 1 is an Array - if (!object2) - { - // Special case for array vs. self - for (i = 0; i < object1.length; i++) - { - var child = object1[i]; - - for (j = i + 1; j < object1.length; j++) - { - if (i === j) - { - continue; - } - - this.collideHandler(child, object1[j], collideCallback, processCallback, callbackContext, overlapOnly); - } - } - } - else - { - for (i = 0; i < object1.length; i++) - { - this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - } - } - else - { - // They're both arrays - for (i = 0; i < object1.length; i++) - { - for (j = 0; j < object2.length; j++) - { - this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); - } - } - } - - return (this._total > 0); - }, - - /** - * Internal helper function. Please use Phaser.Physics.Arcade.World#collide and Phaser.Physics.Arcade.World#overlap instead. - * - * @method Phaser.Physics.Arcade.World#collideHandler - * @private - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. - * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object or array of objects to check, or `undefined`. - * @param {ArcadePhysicsCallback} collideCallback - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} processCallback - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Whether this is a collision or overlap check. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) - { - // Collide Group with Self - // Only collide valid objects - if (object2 === undefined && object1.isParent) - { - return this.collideGroupVsGroup(object1, object1, collideCallback, processCallback, callbackContext, overlapOnly); - } - - // If neither of the objects are set then bail out - if (!object1 || !object2) - { - return false; - } - - // A Body - if (object1.body) - { - if (object2.body) - { - return this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - else if (object2.isParent) - { - return this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - else if (object2.isTilemap) - { - return this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - } - - // GROUPS - else if (object1.isParent) - { - if (object2.body) - { - return this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); - } - else if (object2.isParent) - { - return this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - else if (object2.isTilemap) - { - return this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); - } - } - - // TILEMAP LAYERS - else if (object1.isTilemap) - { - if (object2.body) - { - return this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); - } - else if (object2.isParent) - { - return this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); - } - } - }, - - /** - * Internal handler for Sprite vs. Sprite collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideSpriteVsSprite - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} sprite1 - The first object to check for collision. - * @param {Phaser.GameObjects.GameObject} sprite2 - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Whether this is a collision or overlap check. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) - { - if (!sprite1.body || !sprite2.body) - { - return false; - } - - if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly)) - { - if (collideCallback) - { - collideCallback.call(callbackContext, sprite1, sprite2); - } - - this._total++; - } - - return true; - }, - - /** - * Internal handler for Sprite vs. Group collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideSpriteVsGroup - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {Phaser.GameObjects.Group} group - The second object to check for collision. - * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. - * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. - * @param {any} callbackContext - The scope in which to call the callbacks. - * @param {boolean} overlapOnly - Whether this is a collision or overlap check. - * - * @return {boolean} `true` if the Sprite collided with the given Group, otherwise `false`. - */ - collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) - { - var bodyA = sprite.body; - - if (group.length === 0 || !bodyA || !bodyA.enable) - { - return; - } - - // Does sprite collide with anything? - - var i; - var len; - var bodyB; - - if (this.useTree) - { - var minMax = this.treeMinMax; - - minMax.minX = bodyA.left; - minMax.minY = bodyA.top; - minMax.maxX = bodyA.right; - minMax.maxY = bodyA.bottom; - - var results = (group.physicsType === CONST.DYNAMIC_BODY) ? this.tree.search(minMax) : this.staticTree.search(minMax); - - len = results.length; - - for (i = 0; i < len; i++) - { - bodyB = results[i]; - - if (bodyA === bodyB || !bodyB.enable || !group.contains(bodyB.gameObject)) - { - // Skip if comparing against itself, or if bodyB isn't actually part of the Group - continue; - } - - if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) - { - if (collideCallback) - { - collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject); - } - - this._total++; - } - } - } - else - { - var children = group.getChildren(); - var skipIndex = group.children.entries.indexOf(sprite); - - len = children.length; - - for (i = 0; i < len; i++) - { - bodyB = children[i].body; - - if (!bodyB || i === skipIndex || !bodyB.enable) - { - continue; - } - - if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) - { - if (collideCallback) - { - collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject); - } - - this._total++; - } - } - } - }, - - /** - * Internal handler for Group vs. Tilemap collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideGroupVsTilemapLayer - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Group} group - The first object to check for collision. - * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Whether this is a collision or overlap check. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) - { - var children = group.getChildren(); - - if (children.length === 0) - { - return false; - } - - var didCollide = false; - - for (var i = 0; i < children.length; i++) - { - if (children[i].body) - { - if (this.collideSpriteVsTilemapLayer(children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly)) - { - didCollide = true; - } - } - } - - return didCollide; - }, - - /** - * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. - * - * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for collision with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions - * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * - * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have - * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the - * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on - * dynamic maps, this method can prove very useful. - * - * @method Phaser.Physics.Arcade.World#collideTiles - * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE - * @since 3.17.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) - { - if (!sprite.body.enable || tiles.length === 0) - { - return false; - } - else - { - return this.collideSpriteVsTilesHandler(sprite, tiles, collideCallback, processCallback, callbackContext, false, false); - } - }, - - /** - * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. - * - * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap - * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * - * @method Phaser.Physics.Arcade.World#overlapTiles - * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP - * @since 3.17.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects overlap. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - overlapTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) - { - if (!sprite.body.enable || tiles.length === 0) - { - return false; - } - else - { - return this.collideSpriteVsTilesHandler(sprite, tiles, collideCallback, processCallback, callbackContext, true, false); - } - }, - - /** - * Internal handler for Sprite vs. Tilemap collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideSpriteVsTilemapLayer - * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE - * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * @param {boolean} [overlapOnly] - Whether this is a collision or overlap check. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) - { - var body = sprite.body; - - if (!body.enable) - { - return false; - } - - var x = body.position.x; - var y = body.position.y; - var w = body.width; - var h = body.height; - - // TODO: this logic should be encapsulated within the Tilemap API at some point. - // If the maps base tile size differs from the layer's tile size, we need to adjust the - // selection area by the difference between the two. - var layerData = tilemapLayer.layer; - - if (layerData.tileWidth > layerData.baseTileWidth) - { - // The x origin of a tile is the left side, so x and width need to be adjusted. - var xDiff = (layerData.tileWidth - layerData.baseTileWidth) * tilemapLayer.scaleX; - x -= xDiff; - w += xDiff; - } - - if (layerData.tileHeight > layerData.baseTileHeight) - { - // The y origin of a tile is the bottom side, so just the height needs to be adjusted. - var yDiff = (layerData.tileHeight - layerData.baseTileHeight) * tilemapLayer.scaleY; - h += yDiff; - } - - var mapData = tilemapLayer.getTilesWithinWorldXY(x, y, w, h); - - if (mapData.length === 0) - { - return false; - } - else - { - return this.collideSpriteVsTilesHandler(sprite, mapData, collideCallback, processCallback, callbackContext, overlapOnly, true); - } - }, - - /** - * Internal handler for Sprite vs. Tilemap collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideSpriteVsTilesHandler - * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE - * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP - * @private - * @since 3.17.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. - * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * @param {boolean} [overlapOnly] - Whether this is a collision or overlap check. - * @param {boolean} [isLayer] - Is this check coming from a TilemapLayer or an array of tiles? - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideSpriteVsTilesHandler: function (sprite, tiles, collideCallback, processCallback, callbackContext, overlapOnly, isLayer) - { - var body = sprite.body; - - var tile; - var tileWorldRect = { left: 0, right: 0, top: 0, bottom: 0 }; - var tilemapLayer; - var collision = false; - - for (var i = 0; i < tiles.length; i++) - { - tile = tiles[i]; - - tilemapLayer = tile.tilemapLayer; - - tileWorldRect.left = tilemapLayer.tileToWorldX(tile.x); - tileWorldRect.top = tilemapLayer.tileToWorldY(tile.y); - - // If the map's base tile size differs from the layer's tile size, only the top of the rect - // needs to be adjusted since its origin is (0, 1). - if (tile.baseHeight !== tile.height) - { - tileWorldRect.top -= (tile.height - tile.baseHeight) * tilemapLayer.scaleY; - } - - tileWorldRect.right = tileWorldRect.left + tile.width * tilemapLayer.scaleX; - tileWorldRect.bottom = tileWorldRect.top + tile.height * tilemapLayer.scaleY; - - if (TileIntersectsBody(tileWorldRect, body) - && (!processCallback || processCallback.call(callbackContext, sprite, tile)) - && ProcessTileCallbacks(tile, sprite) - && (overlapOnly || SeparateTile(i, body, tile, tileWorldRect, tilemapLayer, this.TILE_BIAS, isLayer))) - { - this._total++; - - collision = true; - - if (collideCallback) - { - collideCallback.call(callbackContext, sprite, tile); - } - - if (overlapOnly && body.onOverlap) - { - this.emit(Events.TILE_OVERLAP, sprite, tile, body); - } - else if (body.onCollide) - { - this.emit(Events.TILE_COLLIDE, sprite, tile, body); - } - } - } - - return collision; - }, - - /** - * Internal helper for Group vs. Group collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * - * @method Phaser.Physics.Arcade.World#collideGroupVsGroup - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Group} group1 - The first object to check for collision. - * @param {Phaser.GameObjects.Group} group2 - The second object to check for collision. - * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param {any} [callbackContext] - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Whether this is a collision or overlap check. - * - * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. - */ - collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) - { - if (group1.length === 0 || group2.length === 0) - { - return; - } - - var children = group1.getChildren(); - - for (var i = 0; i < children.length; i++) - { - this.collideSpriteVsGroup(children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); - } - }, - - /** - * Wrap an object's coordinates (or several objects' coordinates) within {@link Phaser.Physics.Arcade.World#bounds}. - * - * If the object is outside any boundary edge (left, top, right, bottom), it will be moved to the same offset from the opposite edge (the interior). - * - * @method Phaser.Physics.Arcade.World#wrap - * @since 3.3.0 - * - * @param {*} object - A Game Object, a Group, an object with `x` and `y` coordinates, or an array of such objects. - * @param {number} [padding=0] - An amount added to each boundary edge during the operation. - */ - wrap: function (object, padding) - { - if (object.body) - { - this.wrapObject(object, padding); - } - else if (object.getChildren) - { - this.wrapArray(object.getChildren(), padding); - } - else if (Array.isArray(object)) - { - this.wrapArray(object, padding); - } - else - { - this.wrapObject(object, padding); - } - }, - - /** - * Wrap each object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. - * - * @method Phaser.Physics.Arcade.World#wrapArray - * @since 3.3.0 - * - * @param {Array.<*>} objects - An array of objects to be wrapped. - * @param {number} [padding=0] - An amount added to the boundary. - */ - wrapArray: function (objects, padding) - { - for (var i = 0; i < objects.length; i++) - { - this.wrapObject(objects[i], padding); - } - }, - - /** - * Wrap an object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. - * - * @method Phaser.Physics.Arcade.World#wrapObject - * @since 3.3.0 - * - * @param {*} object - A Game Object, a Physics Body, or any object with `x` and `y` coordinates - * @param {number} [padding=0] - An amount added to the boundary. - */ - wrapObject: function (object, padding) - { - if (padding === undefined) { padding = 0; } - - object.x = Wrap(object.x, this.bounds.left - padding, this.bounds.right + padding); - object.y = Wrap(object.y, this.bounds.top - padding, this.bounds.bottom + padding); - }, - - /** - * Shuts down the simulation, clearing physics data and removing listeners. - * - * @method Phaser.Physics.Arcade.World#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - this.tree.clear(); - this.staticTree.clear(); - this.bodies.clear(); - this.staticBodies.clear(); - this.colliders.destroy(); - - this.removeAllListeners(); - }, - - /** - * Shuts down the simulation and disconnects it from the current scene. - * - * @method Phaser.Physics.Arcade.World#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene = null; - } - -}); - -module.exports = World; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('./Body'); +var Clamp = require('../../math/Clamp'); +var Class = require('../../utils/Class'); +var Collider = require('./Collider'); +var CONST = require('./const'); +var DistanceBetween = require('../../math/distance/DistanceBetween'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var FuzzyEqual = require('../../math/fuzzy/Equal'); +var FuzzyGreaterThan = require('../../math/fuzzy/GreaterThan'); +var FuzzyLessThan = require('../../math/fuzzy/LessThan'); +var GetOverlapX = require('./GetOverlapX'); +var GetOverlapY = require('./GetOverlapY'); +var GetValue = require('../../utils/object/GetValue'); +var ProcessQueue = require('../../structs/ProcessQueue'); +var ProcessTileCallbacks = require('./tilemap/ProcessTileCallbacks'); +var Rectangle = require('../../geom/rectangle/Rectangle'); +var RTree = require('../../structs/RTree'); +var SeparateTile = require('./tilemap/SeparateTile'); +var SeparateX = require('./SeparateX'); +var SeparateY = require('./SeparateY'); +var Set = require('../../structs/Set'); +var StaticBody = require('./StaticBody'); +var TileIntersectsBody = require('./tilemap/TileIntersectsBody'); +var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); +var Vector2 = require('../../math/Vector2'); +var Wrap = require('../../math/Wrap'); + +/** + * @classdesc + * The Arcade Physics World. + * + * The World is responsible for creating, managing, colliding and updating all of the bodies within it. + * + * An instance of the World belongs to a Phaser.Scene and is accessed via the property `physics.world`. + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Arcade + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this World instance belongs. + * @param {Phaser.Types.Physics.Arcade.ArcadeWorldConfig} config - An Arcade Physics Configuration object. + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * The Scene this simulation belongs to. + * + * @name Phaser.Physics.Arcade.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * Dynamic Bodies in this simulation. + * + * @name Phaser.Physics.Arcade.World#bodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.bodies = new Set(); + + /** + * Static Bodies in this simulation. + * + * @name Phaser.Physics.Arcade.World#staticBodies + * @type {Phaser.Structs.Set.} + * @since 3.0.0 + */ + this.staticBodies = new Set(); + + /** + * Static Bodies marked for deletion. + * + * @name Phaser.Physics.Arcade.World#pendingDestroy + * @type {Phaser.Structs.Set.<(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)>} + * @since 3.1.0 + */ + this.pendingDestroy = new Set(); + + /** + * This simulation's collision processors. + * + * @name Phaser.Physics.Arcade.World#colliders + * @type {Phaser.Structs.ProcessQueue.} + * @since 3.0.0 + */ + this.colliders = new ProcessQueue(); + + /** + * Acceleration of Bodies due to gravity, in pixels per second. + * + * @name Phaser.Physics.Arcade.World#gravity + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.gravity = new Vector2(GetValue(config, 'gravity.x', 0), GetValue(config, 'gravity.y', 0)); + + /** + * A boundary constraining Bodies. + * + * @name Phaser.Physics.Arcade.World#bounds + * @type {Phaser.Geom.Rectangle} + * @since 3.0.0 + */ + this.bounds = new Rectangle( + GetValue(config, 'x', 0), + GetValue(config, 'y', 0), + GetValue(config, 'width', scene.sys.scale.width), + GetValue(config, 'height', scene.sys.scale.height) + ); + + /** + * The boundary edges that Bodies can collide with. + * + * @name Phaser.Physics.Arcade.World#checkCollision + * @type {Phaser.Types.Physics.Arcade.CheckCollisionObject} + * @since 3.0.0 + */ + this.checkCollision = { + up: GetValue(config, 'checkCollision.up', true), + down: GetValue(config, 'checkCollision.down', true), + left: GetValue(config, 'checkCollision.left', true), + right: GetValue(config, 'checkCollision.right', true) + }; + + /** + * The number of physics steps to be taken per second. + * + * This property is read-only. Use the `setFPS` method to modify it at run-time. + * + * @name Phaser.Physics.Arcade.World#fps + * @readonly + * @type {number} + * @default 60 + * @since 3.10.0 + */ + this.fps = GetValue(config, 'fps', 60); + + /** + * The amount of elapsed ms since the last frame. + * + * @name Phaser.Physics.Arcade.World#_elapsed + * @private + * @type {number} + * @since 3.10.0 + */ + this._elapsed = 0; + + /** + * Internal frame time value. + * + * @name Phaser.Physics.Arcade.World#_frameTime + * @private + * @type {number} + * @since 3.10.0 + */ + this._frameTime = 1 / this.fps; + + /** + * Internal frame time ms value. + * + * @name Phaser.Physics.Arcade.World#_frameTimeMS + * @private + * @type {number} + * @since 3.10.0 + */ + this._frameTimeMS = 1000 * this._frameTime; + + /** + * The number of steps that took place in the last frame. + * + * @name Phaser.Physics.Arcade.World#stepsLastFrame + * @readonly + * @type {number} + * @since 3.10.0 + */ + this.stepsLastFrame = 0; + + /** + * Scaling factor applied to the frame rate. + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * @name Phaser.Physics.Arcade.World#timeScale + * @type {number} + * @default 1 + * @since 3.10.0 + */ + this.timeScale = GetValue(config, 'timeScale', 1); + + /** + * The maximum absolute difference of a Body's per-step velocity and its overlap with another Body that will result in separation on *each axis*. + * Larger values favor separation. + * Smaller values favor no separation. + * + * @name Phaser.Physics.Arcade.World#OVERLAP_BIAS + * @type {number} + * @default 4 + * @since 3.0.0 + */ + this.OVERLAP_BIAS = GetValue(config, 'overlapBias', 4); + + /** + * The maximum absolute value of a Body's overlap with a tile that will result in separation on *each axis*. + * Larger values favor separation. + * Smaller values favor no separation. + * The optimum value may be similar to the tile size. + * + * @name Phaser.Physics.Arcade.World#TILE_BIAS + * @type {number} + * @default 16 + * @since 3.0.0 + */ + this.TILE_BIAS = GetValue(config, 'tileBias', 16); + + /** + * Always separate overlapping Bodies horizontally before vertically. + * False (the default) means Bodies are first separated on the axis of greater gravity, or the vertical axis if neither is greater. + * + * @name Phaser.Physics.Arcade.World#forceX + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.forceX = GetValue(config, 'forceX', false); + + /** + * Whether the simulation advances with the game loop. + * + * @name Phaser.Physics.Arcade.World#isPaused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.isPaused = GetValue(config, 'isPaused', false); + + /** + * Temporary total of colliding Bodies. + * + * @name Phaser.Physics.Arcade.World#_total + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._total = 0; + + /** + * Enables the debug display. + * + * @name Phaser.Physics.Arcade.World#drawDebug + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.drawDebug = GetValue(config, 'debug', false); + + /** + * The graphics object drawing the debug display. + * + * @name Phaser.Physics.Arcade.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + /** + * Default debug display settings for new Bodies. + * + * @name Phaser.Physics.Arcade.World#defaults + * @type {Phaser.Types.Physics.Arcade.ArcadeWorldDefaults} + * @since 3.0.0 + */ + this.defaults = { + debugShowBody: GetValue(config, 'debugShowBody', true), + debugShowStaticBody: GetValue(config, 'debugShowStaticBody', true), + debugShowVelocity: GetValue(config, 'debugShowVelocity', true), + bodyDebugColor: GetValue(config, 'debugBodyColor', 0xff00ff), + staticBodyDebugColor: GetValue(config, 'debugStaticBodyColor', 0x0000ff), + velocityDebugColor: GetValue(config, 'debugVelocityColor', 0x00ff00) + }; + + /** + * The maximum number of items per node on the RTree. + * + * This is ignored if `useTree` is `false`. If you have a large number of bodies in + * your world then you may find search performance improves by increasing this value, + * to allow more items per node and less node division. + * + * @name Phaser.Physics.Arcade.World#maxEntries + * @type {integer} + * @default 16 + * @since 3.0.0 + */ + this.maxEntries = GetValue(config, 'maxEntries', 16); + + /** + * Should this Arcade Physics World use an RTree for Dynamic and Static Physics bodies? + * + * An RTree is a fast way of spatially sorting of all the bodies in the world. + * However, at certain limits, the cost of clearing and inserting the bodies into the + * tree every frame becomes more expensive than the search speed gains it provides. + * + * If you have a large number of dynamic bodies in your world then it may be best to + * disable the use of the RTree by setting this property to `false` in the physics config. + * + * The number it can cope with depends on browser and device, but a conservative estimate + * of around 5,000 bodies should be considered the max before disabling it. + * + * This only applies to dynamic bodies. Static bodies are always kept in an RTree, + * because they don't have to be cleared every frame, so you benefit from the + * massive search speeds all the time. + * + * @name Phaser.Physics.Arcade.World#useTree + * @type {boolean} + * @default true + * @since 3.10.0 + */ + this.useTree = GetValue(config, 'useTree', true); + + /** + * The spatial index of Dynamic Bodies. + * + * @name Phaser.Physics.Arcade.World#tree + * @type {Phaser.Structs.RTree} + * @since 3.0.0 + */ + this.tree = new RTree(this.maxEntries); + + /** + * The spatial index of Static Bodies. + * + * @name Phaser.Physics.Arcade.World#staticTree + * @type {Phaser.Structs.RTree} + * @since 3.0.0 + */ + this.staticTree = new RTree(this.maxEntries); + + /** + * Recycled input for tree searches. + * + * @name Phaser.Physics.Arcade.World#treeMinMax + * @type {Phaser.Types.Physics.Arcade.ArcadeWorldTreeMinMax} + * @since 3.0.0 + */ + this.treeMinMax = { minX: 0, minY: 0, maxX: 0, maxY: 0 }; + + /** + * A temporary Transform Matrix used by bodies for calculations without them needing their own local copy. + * + * @name Phaser.Physics.Arcade.World#_tempMatrix + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.12.0 + */ + this._tempMatrix = new TransformMatrix(); + + /** + * A temporary Transform Matrix used by bodies for calculations without them needing their own local copy. + * + * @name Phaser.Physics.Arcade.World#_tempMatrix2 + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @private + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + }, + + /** + * Adds an Arcade Physics Body to a Game Object, an array of Game Objects, or the children of a Group. + * + * The difference between this and the `enableBody` method is that you can pass arrays or Groups + * to this method. + * + * You can specify if the bodies are to be Dynamic or Static. A dynamic body can move via velocity and + * acceleration. A static body remains fixed in place and as such is able to use an optimized search + * tree, making it ideal for static elements such as level objects. You can still collide and overlap + * with static bodies. + * + * Normally, rather than calling this method directly, you'd use the helper methods available in the + * Arcade Physics Factory, such as: + * + * ```javascript + * this.physics.add.image(x, y, textureKey); + * this.physics.add.sprite(x, y, textureKey); + * ``` + * + * Calling factory methods encapsulates the creation of a Game Object and the creation of its + * body at the same time. If you are creating custom classes then you can pass them to this + * method to have their bodies created. + * + * @method Phaser.Physics.Arcade.World#enable + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object - The object, or objects, on which to create the bodies. + * @param {integer} [bodyType] - The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. + */ + enable: function (object, bodyType) + { + if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY; } + + if (!Array.isArray(object)) + { + object = [ object ]; + } + + for (var i = 0; i < object.length; i++) + { + var entry = object[i]; + + if (entry.isParent) + { + var children = entry.getChildren(); + + for (var c = 0; c < children.length; c++) + { + var child = children[c]; + + if (child.isParent) + { + // Handle Groups nested inside of Groups + this.enable(child, bodyType); + } + else + { + this.enableBody(child, bodyType); + } + } + } + else + { + this.enableBody(entry, bodyType); + } + } + }, + + /** + * Creates an Arcade Physics Body on a single Game Object. + * + * If the Game Object already has a body, this method will simply add it back into the simulation. + * + * You can specify if the body is Dynamic or Static. A dynamic body can move via velocity and + * acceleration. A static body remains fixed in place and as such is able to use an optimized search + * tree, making it ideal for static elements such as level objects. You can still collide and overlap + * with static bodies. + * + * Normally, rather than calling this method directly, you'd use the helper methods available in the + * Arcade Physics Factory, such as: + * + * ```javascript + * this.physics.add.image(x, y, textureKey); + * this.physics.add.sprite(x, y, textureKey); + * ``` + * + * Calling factory methods encapsulates the creation of a Game Object and the creation of its + * body at the same time. If you are creating custom classes then you can pass them to this + * method to have their bodies created. + * + * @method Phaser.Physics.Arcade.World#enableBody + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} object - The Game Object on which to create the body. + * @param {integer} [bodyType] - The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. + * + * @return {Phaser.GameObjects.GameObject} The Game Object on which the body was created. + */ + enableBody: function (object, bodyType) + { + if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY; } + + if (!object.body) + { + if (bodyType === CONST.DYNAMIC_BODY) + { + object.body = new Body(this, object); + } + else if (bodyType === CONST.STATIC_BODY) + { + object.body = new StaticBody(this, object); + } + } + + this.add(object.body); + + return object; + }, + + /** + * Adds an existing Arcade Physics Body or StaticBody to the simulation. + * + * The body is enabled and added to the local search trees. + * + * @method Phaser.Physics.Arcade.World#add + * @since 3.10.0 + * + * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The Body to be added to the simulation. + * + * @return {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} The Body that was added to the simulation. + */ + add: function (body) + { + if (body.physicsType === CONST.DYNAMIC_BODY) + { + this.bodies.set(body); + } + else if (body.physicsType === CONST.STATIC_BODY) + { + this.staticBodies.set(body); + + this.staticTree.insert(body); + } + + body.enable = true; + + return body; + }, + + /** + * Disables the Arcade Physics Body of a Game Object, an array of Game Objects, or the children of a Group. + * + * The difference between this and the `disableBody` method is that you can pass arrays or Groups + * to this method. + * + * The body itself is not deleted, it just has its `enable` property set to false, which + * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. + * + * @method Phaser.Physics.Arcade.World#disable + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[]|Phaser.GameObjects.Group|Phaser.GameObjects.Group[])} object - The object, or objects, on which to disable the bodies. + */ + disable: function (object) + { + if (!Array.isArray(object)) + { + object = [ object ]; + } + + for (var i = 0; i < object.length; i++) + { + var entry = object[i]; + + if (entry.isParent) + { + var children = entry.getChildren(); + + for (var c = 0; c < children.length; c++) + { + var child = children[c]; + + if (child.isParent) + { + // Handle Groups nested inside of Groups + this.disable(child); + } + else + { + this.disableBody(child.body); + } + } + } + else + { + this.disableBody(entry.body); + } + } + }, + + /** + * Disables an existing Arcade Physics Body or StaticBody and removes it from the simulation. + * + * The body is disabled and removed from the local search trees. + * + * The body itself is not deleted, it just has its `enable` property set to false, which + * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. + * + * @method Phaser.Physics.Arcade.World#disableBody + * @since 3.0.0 + * + * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The Body to be disabled. + */ + disableBody: function (body) + { + this.remove(body); + + body.enable = false; + }, + + /** + * Removes an existing Arcade Physics Body or StaticBody from the simulation. + * + * The body is disabled and removed from the local search trees. + * + * The body itself is not deleted, it just has its `enabled` property set to false, which + * means you can re-enable it again at any point by passing it to enable `enable` or `add`. + * + * @method Phaser.Physics.Arcade.World#remove + * @since 3.0.0 + * + * @param {(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)} body - The body to be removed from the simulation. + */ + remove: function (body) + { + if (body.physicsType === CONST.DYNAMIC_BODY) + { + this.tree.remove(body); + this.bodies.delete(body); + } + else if (body.physicsType === CONST.STATIC_BODY) + { + this.staticBodies.delete(body); + this.staticTree.remove(body); + } + }, + + /** + * Creates a Graphics Game Object that the world will use to render the debug display to. + * + * This is called automatically when the World is instantiated if the `debug` config property + * was set to `true`. However, you can call it at any point should you need to display the + * debug Graphic from a fixed point. + * + * You can control which objects are drawn to the Graphics object, and the colors they use, + * by setting the debug properties in the physics config. + * + * You should not typically use this in a production game. Use it to aid during debugging. + * + * @method Phaser.Physics.Arcade.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The Graphics object that was created for use by the World. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * Sets the position, size and properties of the World boundary. + * + * The World boundary is an invisible rectangle that defines the edges of the World. + * If a Body is set to collide with the world bounds then it will automatically stop + * when it reaches any of the edges. You can optionally set which edges of the boundary + * should be checked against. + * + * @method Phaser.Physics.Arcade.World#setBounds + * @since 3.0.0 + * + * @param {number} x - The top-left x coordinate of the boundary. + * @param {number} y - The top-left y coordinate of the boundary. + * @param {number} width - The width of the boundary. + * @param {number} height - The height of the boundary. + * @param {boolean} [checkLeft] - Should bodies check against the left edge of the boundary? + * @param {boolean} [checkRight] - Should bodies check against the right edge of the boundary? + * @param {boolean} [checkUp] - Should bodies check against the top edge of the boundary? + * @param {boolean} [checkDown] - Should bodies check against the bottom edge of the boundary? + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + setBounds: function (x, y, width, height, checkLeft, checkRight, checkUp, checkDown) + { + this.bounds.setTo(x, y, width, height); + + if (checkLeft !== undefined) + { + this.setBoundsCollision(checkLeft, checkRight, checkUp, checkDown); + } + + return this; + }, + + /** + * Enables or disables collisions on each edge of the World boundary. + * + * @method Phaser.Physics.Arcade.World#setBoundsCollision + * @since 3.0.0 + * + * @param {boolean} [left=true] - Should bodies check against the left edge of the boundary? + * @param {boolean} [right=true] - Should bodies check against the right edge of the boundary? + * @param {boolean} [up=true] - Should bodies check against the top edge of the boundary? + * @param {boolean} [down=true] - Should bodies check against the bottom edge of the boundary? + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + setBoundsCollision: function (left, right, up, down) + { + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (up === undefined) { up = true; } + if (down === undefined) { down = true; } + + this.checkCollision.left = left; + this.checkCollision.right = right; + this.checkCollision.up = up; + this.checkCollision.down = down; + + return this; + }, + + /** + * Pauses the simulation. + * + * A paused simulation does not update any existing bodies, or run any Colliders. + * + * However, you can still enable and disable bodies within it, or manually run collide or overlap + * checks. + * + * @method Phaser.Physics.Arcade.World#pause + * @fires Phaser.Physics.Arcade.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + pause: function () + { + this.isPaused = true; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * Resumes the simulation, if paused. + * + * @method Phaser.Physics.Arcade.World#resume + * @fires Phaser.Physics.Arcade.Events#RESUME + * @since 3.0.0 + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + resume: function () + { + this.isPaused = false; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * Creates a new Collider object and adds it to the simulation. + * + * A Collider is a way to automatically perform collision checks between two objects, + * calling the collide and process callbacks if they occur. + * + * Colliders are run as part of the World update, after all of the Bodies have updated. + * + * By creating a Collider you don't need then call `World.collide` in your `update` loop, + * as it will be handled for you automatically. + * + * @method Phaser.Physics.Arcade.World#addCollider + * @since 3.0.0 + * @see Phaser.Physics.Arcade.World#collide + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects collide. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + addCollider: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + var collider = new Collider(this, false, object1, object2, collideCallback, processCallback, callbackContext); + + this.colliders.add(collider); + + return collider; + }, + + /** + * Creates a new Overlap Collider object and adds it to the simulation. + * + * A Collider is a way to automatically perform overlap checks between two objects, + * calling the collide and process callbacks if they occur. + * + * Colliders are run as part of the World update, after all of the Bodies have updated. + * + * By creating a Collider you don't need then call `World.overlap` in your `update` loop, + * as it will be handled for you automatically. + * + * @method Phaser.Physics.Arcade.World#addOverlap + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for overlap. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object to check for overlap. + * @param {ArcadePhysicsCallback} [collideCallback] - The callback to invoke when the two objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - The callback to invoke when the two objects overlap. Must return a boolean. + * @param {*} [callbackContext] - The scope in which to call the callbacks. + * + * @return {Phaser.Physics.Arcade.Collider} The Collider that was created. + */ + addOverlap: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + var collider = new Collider(this, true, object1, object2, collideCallback, processCallback, callbackContext); + + this.colliders.add(collider); + + return collider; + }, + + /** + * Removes a Collider from the simulation so it is no longer processed. + * + * This method does not destroy the Collider. If you wish to add it back at a later stage you can call + * `World.colliders.add(Collider)`. + * + * If you no longer need the Collider you can call the `Collider.destroy` method instead, which will + * automatically clear all of its references and then remove it from the World. If you call destroy on + * a Collider you _don't_ need to pass it to this method too. + * + * @method Phaser.Physics.Arcade.World#removeCollider + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Collider} collider - The Collider to remove from the simulation. + * + * @return {Phaser.Physics.Arcade.World} This World object. + */ + removeCollider: function (collider) + { + this.colliders.remove(collider); + + return this; + }, + + /** + * Sets the frame rate to run the simulation at. + * + * The frame rate value is used to simulate a fixed update time step. This fixed + * time step allows for a straightforward implementation of a deterministic game state. + * + * This frame rate is independent of the frequency at which the game is rendering. The + * higher you set the fps, the more physics simulation steps will occur per game step. + * Conversely, the lower you set it, the less will take place. + * + * You can optionally advance the simulation directly yourself by calling the `step` method. + * + * @method Phaser.Physics.Arcade.World#setFPS + * @since 3.10.0 + * + * @param {integer} framerate - The frame rate to advance the simulation at. + * + * @return {this} This World object. + */ + setFPS: function (framerate) + { + this.fps = framerate; + this._frameTime = 1 / this.fps; + this._frameTimeMS = 1000 * this._frameTime; + + return this; + }, + + /** + * 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 + * @protected + * @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. + */ + update: function (time, delta) + { + if (this.isPaused || this.bodies.size === 0) + { + return; + } + + var i; + var fixedDelta = this._frameTime; + var msPerFrame = this._frameTimeMS * this.timeScale; + + this._elapsed += delta; + + // Update all active bodies + var body; + var bodies = this.bodies.entries; + + // Will a step happen this frame? + var willStep = (this._elapsed >= msPerFrame); + + for (i = 0; i < bodies.length; i++) + { + body = bodies[i]; + + if (body.enable) + { + body.preUpdate(willStep, fixedDelta); + } + } + + // We know that a step will happen this frame, so let's bundle it all together to save branching and iteration costs + if (willStep) + { + this._elapsed -= msPerFrame; + this.stepsLastFrame = 1; + + // Optionally populate our dynamic collision tree + if (this.useTree) + { + this.tree.clear(); + this.tree.load(bodies); + } + + // Process any colliders + var colliders = this.colliders.update(); + + for (i = 0; i < colliders.length; i++) + { + var collider = colliders[i]; + + if (collider.active) + { + collider.update(); + } + } + + this.emit(Events.WORLD_STEP); + } + + // Process any additional steps this frame + while (this._elapsed >= msPerFrame) + { + this._elapsed -= msPerFrame; + + this.step(fixedDelta); + } + }, + + /** + * Advances the simulation by a time increment. + * + * @method Phaser.Physics.Arcade.World#step + * @fires Phaser.Physics.Arcade.Events#WORLD_STEP + * @since 3.10.0 + * + * @param {number} delta - The delta time amount, in seconds, by which to advance the simulation. + */ + step: function (delta) + { + // Update all active bodies + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enable) + { + body.update(delta); + } + } + + // Optionally populate our dynamic collision tree + if (this.useTree) + { + this.tree.clear(); + this.tree.load(bodies); + } + + // Process any colliders + var colliders = this.colliders.update(); + + for (i = 0; i < colliders.length; i++) + { + var collider = colliders[i]; + + if (collider.active) + { + collider.update(); + } + } + + this.emit(Events.WORLD_STEP); + + this.stepsLastFrame++; + }, + + /** + * Updates bodies, draws the debug display, and handles pending queue operations. + * + * @method Phaser.Physics.Arcade.World#postUpdate + * @since 3.0.0 + */ + postUpdate: function () + { + var i; + var body; + var bodies = this.bodies.entries; + var len = bodies.length; + + var dynamic = this.bodies; + var staticBodies = this.staticBodies; + + // We don't need to postUpdate if there wasn't a step this frame + if (this.stepsLastFrame) + { + this.stepsLastFrame = 0; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.enable) + { + body.postUpdate(); + } + } + } + + if (this.drawDebug) + { + var graphics = this.debugGraphic; + + graphics.clear(); + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + + bodies = staticBodies.entries; + len = bodies.length; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.willDrawDebug()) + { + body.drawDebug(graphics); + } + } + } + + var pending = this.pendingDestroy; + + if (pending.size > 0) + { + var dynamicTree = this.tree; + var staticTree = this.staticTree; + + bodies = pending.entries; + len = bodies.length; + + for (i = 0; i < len; i++) + { + body = bodies[i]; + + if (body.physicsType === CONST.DYNAMIC_BODY) + { + dynamicTree.remove(body); + dynamic.delete(body); + } + else if (body.physicsType === CONST.STATIC_BODY) + { + staticTree.remove(body); + staticBodies.delete(body); + } + + body.world = undefined; + body.gameObject = undefined; + } + + pending.clear(); + } + }, + + /** + * Calculates a Body's velocity and updates its position. + * + * @method Phaser.Physics.Arcade.World#updateMotion + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body to be updated. + * @param {number} delta - The delta value to be used in the motion calculations, in seconds. + */ + updateMotion: function (body, delta) + { + if (body.allowRotation) + { + this.computeAngularVelocity(body, delta); + } + + this.computeVelocity(body, delta); + }, + + /** + * Calculates a Body's angular velocity. + * + * @method Phaser.Physics.Arcade.World#computeAngularVelocity + * @since 3.10.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body to compute the velocity for. + * @param {number} delta - The delta value to be used in the calculation, in seconds. + */ + computeAngularVelocity: function (body, delta) + { + var velocity = body.angularVelocity; + var acceleration = body.angularAcceleration; + var drag = body.angularDrag; + var max = body.maxAngular; + + if (acceleration) + { + velocity += acceleration * delta; + } + else if (body.allowDrag && drag) + { + drag *= delta; + + if (FuzzyGreaterThan(velocity - drag, 0, 0.1)) + { + velocity -= drag; + } + else if (FuzzyLessThan(velocity + drag, 0, 0.1)) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + velocity = Clamp(velocity, -max, max); + + var velocityDelta = velocity - body.angularVelocity; + + body.angularVelocity += velocityDelta; + body.rotation += (body.angularVelocity * delta); + }, + + /** + * Calculates a Body's per-axis velocity. + * + * @method Phaser.Physics.Arcade.World#computeVelocity + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body to compute the velocity for. + * @param {number} delta - The delta value to be used in the calculation, in seconds. + */ + computeVelocity: function (body, delta) + { + var velocityX = body.velocity.x; + var accelerationX = body.acceleration.x; + var dragX = body.drag.x; + var maxX = body.maxVelocity.x; + + var velocityY = body.velocity.y; + var accelerationY = body.acceleration.y; + var dragY = body.drag.y; + var maxY = body.maxVelocity.y; + + var speed = body.speed; + var maxSpeed = body.maxSpeed; + var allowDrag = body.allowDrag; + var useDamping = body.useDamping; + + if (body.allowGravity) + { + velocityX += (this.gravity.x + body.gravity.x) * delta; + velocityY += (this.gravity.y + body.gravity.y) * delta; + } + + if (accelerationX) + { + velocityX += accelerationX * delta; + } + else if (allowDrag && dragX) + { + if (useDamping) + { + // Damping based deceleration + + velocityX *= dragX; + + speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY); + + if (FuzzyEqual(speed, 0, 0.001)) + { + velocityX = 0; + } + } + else + { + // Linear deceleration + dragX *= delta; + + if (FuzzyGreaterThan(velocityX - dragX, 0, 0.01)) + { + velocityX -= dragX; + } + else if (FuzzyLessThan(velocityX + dragX, 0, 0.01)) + { + velocityX += dragX; + } + else + { + velocityX = 0; + } + } + } + + if (accelerationY) + { + velocityY += accelerationY * delta; + } + else if (allowDrag && dragY) + { + if (useDamping) + { + // Damping based deceleration + velocityY *= dragY; + + speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY); + + if (FuzzyEqual(speed, 0, 0.001)) + { + velocityY = 0; + } + } + else + { + // Linear deceleration + dragY *= delta; + + if (FuzzyGreaterThan(velocityY - dragY, 0, 0.01)) + { + velocityY -= dragY; + } + else if (FuzzyLessThan(velocityY + dragY, 0, 0.01)) + { + velocityY += dragY; + } + else + { + velocityY = 0; + } + } + } + + velocityX = Clamp(velocityX, -maxX, maxX); + velocityY = Clamp(velocityY, -maxY, maxY); + + body.velocity.set(velocityX, velocityY); + + if (maxSpeed > -1 && speed > maxSpeed) + { + body.velocity.normalize().scale(maxSpeed); + speed = maxSpeed; + } + + body.speed = speed; + }, + + /** + * Separates two Bodies. + * + * @method Phaser.Physics.Arcade.World#separate + * @fires Phaser.Physics.Arcade.Events#COLLIDE + * @fires Phaser.Physics.Arcade.Events#OVERLAP + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to be separated. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to be separated. + * @param {ArcadePhysicsCallback} [processCallback] - The process callback. + * @param {*} [callbackContext] - The context in which to invoke the callback. + * @param {boolean} [overlapOnly] - If this a collide or overlap check? + * + * @return {boolean} True if separation occurred, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) + { + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.gameObject, body2.gameObject) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); + } + } + else + { + resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap || body2.onOverlap) + { + this.emit(Events.OVERLAP, body1.gameObject, body2.gameObject, body1, body2); + } + } + else if (body1.onCollide || body2.onCollide) + { + this.emit(Events.COLLIDE, body1.gameObject, body2.gameObject, body1, body2); + } + } + + return result; + }, + + /** + * Separates two Bodies, when both are circular. + * + * @method Phaser.Physics.Arcade.World#separateCircle + * @fires Phaser.Physics.Arcade.Events#COLLIDE + * @fires Phaser.Physics.Arcade.Events#OVERLAP + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to be separated. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to be separated. + * @param {boolean} [overlapOnly] - If this a collide or overlap check? + * @param {number} [bias] - A small value added to the calculations. + * + * @return {boolean} True if separation occurred, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly, bias) + { + // Set the bounding box overlap values into the bodies themselves (hence we don't use the return values here) + GetOverlapX(body1, body2, false, bias); + GetOverlapY(body1, body2, false, bias); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0 && (body1.onOverlap || body2.onOverlap)) + { + this.emit(Events.OVERLAP, body1.gameObject, body2.gameObject, body1, body2); + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + var dx = body1.center.x - body2.center.x; + var dy = body1.center.y - body2.center.y; + var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); + var nx = ((body2.center.x - body1.center.x) / d) || 0; + var ny = ((body2.center.y - body1.center.y) / d) || 0; + var p = 2 * (body1.velocity.x * nx + body1.velocity.y * ny - body2.velocity.x * nx - body2.velocity.y * ny) / (body1.mass + body2.mass); + + if (!body1.immovable) + { + body1.velocity.x = (body1.velocity.x - p * body1.mass * nx); + body1.velocity.y = (body1.velocity.y - p * body1.mass * ny); + } + + if (!body2.immovable) + { + body2.velocity.x = (body2.velocity.x + p * body2.mass * nx); + body2.velocity.y = (body2.velocity.y + p * body2.mass * ny); + } + + var dvx = body2.velocity.x - body1.velocity.x; + var dvy = body2.velocity.y - body1.velocity.y; + var angleCollision = Math.atan2(dvy, dvx); + + var delta = this._frameTime; + + if (!body1.immovable && !body2.immovable) + { + overlap /= 2; + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * delta) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * delta) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * delta) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * delta) + overlap * Math.sin(angleCollision); + } + + body1.velocity.x *= body1.bounce.x; + body1.velocity.y *= body1.bounce.y; + body2.velocity.x *= body2.bounce.x; + body2.velocity.y *= body2.bounce.y; + + if (body1.onCollide || body2.onCollide) + { + this.emit(Events.COLLIDE, body1.gameObject, body2.gameObject, body1, body2); + } + + return true; + }, + + /** + * Checks to see if two Bodies intersect at all. + * + * @method Phaser.Physics.Arcade.World#intersects + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body1 - The first body to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second body to check. + * + * @return {boolean} True if the two bodies intersect, otherwise false. + */ + intersects: function (body1, body2) + { + if (body1 === body2) + { + return false; + } + + if (!body1.isCircle && !body2.isCircle) + { + // Rect vs. Rect + return !( + body1.right <= body2.position.x || + body1.bottom <= body2.position.y || + body1.position.x >= body2.right || + body1.position.y >= body2.bottom + ); + } + else if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + }, + + /** + * Tests if a circular Body intersects with another Body. + * + * @method Phaser.Physics.Arcade.World#circleBodyIntersects + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} circle - The circular body to test. + * @param {Phaser.Physics.Arcade.Body} body - The rectangular body to test. + * + * @return {boolean} True if the two bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) + { + var x = Clamp(circle.center.x, body.left, body.right); + var y = Clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + }, + + /** + * Tests if Game Objects overlap. + * + * @method Phaser.Physics.Arcade.World#overlap + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {*} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if at least one Game Object overlaps another. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) + { + if (overlapCallback === undefined) { overlapCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = overlapCallback; } + + return this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + }, + + /** + * Performs a collision check and separation between the two physics enabled objects given, which can be single + * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. + * + * If you don't require separation then use {@link #overlap} instead. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. + * + * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding + * objects are passed to it. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * + * @method Phaser.Physics.Arcade.World#collide + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} `true` if any overlapping Game Objects were separated, otherwise `false`. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) + { + if (collideCallback === undefined) { collideCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = collideCallback; } + + return this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + }, + + /** + * Internal helper function. Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideObjects + * @private + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object to check for collision. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} [object2] - The second object to check for collision. + * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. + * @param {any} callbackContext - The scope in which to call the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) + { + var i; + var j; + + if (object1.isParent && object1.physicsType === undefined) + { + object1 = object1.children.entries; + } + + if (object2 && object2.isParent && object2.physicsType === undefined) + { + object2 = object2.children.entries; + } + + var object1isArray = Array.isArray(object1); + var object2isArray = Array.isArray(object2); + + this._total = 0; + + if (!object1isArray && !object2isArray) + { + // Neither of them are arrays - do this first as it's the most common use-case + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (!object1isArray && object2isArray) + { + // Object 2 is an Array + for (i = 0; i < object2.length; i++) + { + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (object1isArray && !object2isArray) + { + // Object 1 is an Array + if (!object2) + { + // Special case for array vs. self + for (i = 0; i < object1.length; i++) + { + var child = object1[i]; + + for (j = i + 1; j < object1.length; j++) + { + if (i === j) + { + continue; + } + + this.collideHandler(child, object1[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + for (i = 0; i < object1.length; i++) + { + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + // They're both arrays + for (i = 0; i < object1.length; i++) + { + for (j = 0; j < object2.length; j++) + { + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + return (this._total > 0); + }, + + /** + * Internal helper function. Please use Phaser.Physics.Arcade.World#collide and Phaser.Physics.Arcade.World#overlap instead. + * + * @method Phaser.Physics.Arcade.World#collideHandler + * @private + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object1 - The first object or array of objects to check. + * @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} object2 - The second object or array of objects to check, or `undefined`. + * @param {ArcadePhysicsCallback} collideCallback - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} processCallback - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) + { + // Collide Group with Self + // Only collide valid objects + if (object2 === undefined && object1.isParent) + { + return this.collideGroupVsGroup(object1, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + + // If neither of the objects are set then bail out + if (!object1 || !object2) + { + return false; + } + + // A Body + if (object1.body) + { + if (object2.body) + { + return this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isParent) + { + return this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isTilemap) + { + return this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + // GROUPS + else if (object1.isParent) + { + if (object2.body) + { + return this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isParent) + { + return this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isTilemap) + { + return this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + // TILEMAP LAYERS + else if (object1.isTilemap) + { + if (object2.body) + { + return this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.isParent) + { + return this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + }, + + /** + * Internal handler for Sprite vs. Sprite collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsSprite + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} sprite1 - The first object to check for collision. + * @param {Phaser.GameObjects.GameObject} sprite2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) + { + if (!sprite1.body || !sprite2.body) + { + return false; + } + + if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite1, sprite2); + } + + this._total++; + } + + return true; + }, + + /** + * Internal handler for Sprite vs. Group collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsGroup + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.GameObjects.Group} group - The second object to check for collision. + * @param {ArcadePhysicsCallback} collideCallback - The callback to invoke when the two objects collide. + * @param {ArcadePhysicsCallback} processCallback - The callback to invoke when the two objects collide. Must return a boolean. + * @param {any} callbackContext - The scope in which to call the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} `true` if the Sprite collided with the given Group, otherwise `false`. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) + { + var bodyA = sprite.body; + + if (group.length === 0 || !bodyA || !bodyA.enable) + { + return; + } + + // Does sprite collide with anything? + + var i; + var len; + var bodyB; + + if (this.useTree) + { + var minMax = this.treeMinMax; + + minMax.minX = bodyA.left; + minMax.minY = bodyA.top; + minMax.maxX = bodyA.right; + minMax.maxY = bodyA.bottom; + + var results = (group.physicsType === CONST.DYNAMIC_BODY) ? this.tree.search(minMax) : this.staticTree.search(minMax); + + len = results.length; + + for (i = 0; i < len; i++) + { + bodyB = results[i]; + + if (bodyA === bodyB || !bodyB.enable || !group.contains(bodyB.gameObject)) + { + // Skip if comparing against itself, or if bodyB isn't actually part of the Group + continue; + } + + if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject); + } + + this._total++; + } + } + } + else + { + var children = group.getChildren(); + var skipIndex = group.children.entries.indexOf(sprite); + + len = children.length; + + for (i = 0; i < len; i++) + { + bodyB = children[i].body; + + if (!bodyB || i === skipIndex || !bodyB.enable) + { + continue; + } + + if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject); + } + + this._total++; + } + } + } + }, + + /** + * Internal handler for Group vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideGroupVsTilemapLayer + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Group} group - The first object to check for collision. + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) + { + var children = group.getChildren(); + + if (children.length === 0) + { + return false; + } + + var didCollide = false; + + for (var i = 0; i < children.length; i++) + { + if (children[i].body) + { + if (this.collideSpriteVsTilemapLayer(children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly)) + { + didCollide = true; + } + } + } + + return didCollide; + }, + + /** + * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. + * + * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for collision with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions + * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have + * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the + * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on + * dynamic maps, this method can prove very useful. + * + * @method Phaser.Physics.Arcade.World#collideTiles + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + if (!sprite.body.enable || tiles.length === 0) + { + return false; + } + else + { + return this.collideSpriteVsTilesHandler(sprite, tiles, collideCallback, processCallback, callbackContext, false, false); + } + }, + + /** + * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. + * + * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap + * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * @method Phaser.Physics.Arcade.World#overlapTiles + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of Tiles to check for collision against. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + overlapTiles: function (sprite, tiles, collideCallback, processCallback, callbackContext) + { + if (!sprite.body.enable || tiles.length === 0) + { + return false; + } + else + { + return this.collideSpriteVsTilesHandler(sprite, tiles, collideCallback, processCallback, callbackContext, true, false); + } + }, + + /** + * Internal handler for Sprite vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsTilemapLayer + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} [overlapOnly] - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) + { + var body = sprite.body; + + if (!body.enable) + { + return false; + } + + var x = body.position.x; + var y = body.position.y; + var w = body.width; + var h = body.height; + + // TODO: this logic should be encapsulated within the Tilemap API at some point. + // If the maps base tile size differs from the layer's tile size, we need to adjust the + // selection area by the difference between the two. + var layerData = tilemapLayer.layer; + + if (layerData.tileWidth > layerData.baseTileWidth) + { + // The x origin of a tile is the left side, so x and width need to be adjusted. + var xDiff = (layerData.tileWidth - layerData.baseTileWidth) * tilemapLayer.scaleX; + x -= xDiff; + w += xDiff; + } + + if (layerData.tileHeight > layerData.baseTileHeight) + { + // The y origin of a tile is the bottom side, so just the height needs to be adjusted. + var yDiff = (layerData.tileHeight - layerData.baseTileHeight) * tilemapLayer.scaleY; + h += yDiff; + } + + var mapData = tilemapLayer.getTilesWithinWorldXY(x, y, w, h); + + if (mapData.length === 0) + { + return false; + } + else + { + return this.collideSpriteVsTilesHandler(sprite, mapData, collideCallback, processCallback, callbackContext, overlapOnly, true); + } + }, + + /** + * Internal handler for Sprite vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideSpriteVsTilesHandler + * @fires Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @fires Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @private + * @since 3.17.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The first object to check for collision. + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} [overlapOnly] - Whether this is a collision or overlap check. + * @param {boolean} [isLayer] - Is this check coming from a TilemapLayer or an array of tiles? + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideSpriteVsTilesHandler: function (sprite, tiles, collideCallback, processCallback, callbackContext, overlapOnly, isLayer) + { + var body = sprite.body; + + var tile; + var tileWorldRect = { left: 0, right: 0, top: 0, bottom: 0 }; + var tilemapLayer; + var collision = false; + + for (var i = 0; i < tiles.length; i++) + { + tile = tiles[i]; + + tilemapLayer = tile.tilemapLayer; + + tileWorldRect.left = tilemapLayer.tileToWorldX(tile.x); + tileWorldRect.top = tilemapLayer.tileToWorldY(tile.y); + + // If the map's base tile size differs from the layer's tile size, only the top of the rect + // needs to be adjusted since its origin is (0, 1). + if (tile.baseHeight !== tile.height) + { + tileWorldRect.top -= (tile.height - tile.baseHeight) * tilemapLayer.scaleY; + } + + tileWorldRect.right = tileWorldRect.left + tile.width * tilemapLayer.scaleX; + tileWorldRect.bottom = tileWorldRect.top + tile.height * tilemapLayer.scaleY; + + if (TileIntersectsBody(tileWorldRect, body) + && (!processCallback || processCallback.call(callbackContext, sprite, tile)) + && ProcessTileCallbacks(tile, sprite) + && (overlapOnly || SeparateTile(i, body, tile, tileWorldRect, tilemapLayer, this.TILE_BIAS, isLayer))) + { + this._total++; + + collision = true; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, tile); + } + + if (overlapOnly && body.onOverlap) + { + this.emit(Events.TILE_OVERLAP, sprite, tile, body); + } + else if (body.onCollide) + { + this.emit(Events.TILE_COLLIDE, sprite, tile, body); + } + } + } + + return collision; + }, + + /** + * Internal helper for Group vs. Group collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * + * @method Phaser.Physics.Arcade.World#collideGroupVsGroup + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Group} group1 - The first object to check for collision. + * @param {Phaser.GameObjects.Group} group2 - The second object to check for collision. + * @param {ArcadePhysicsCallback} [collideCallback] - An optional callback function that is called if the objects collide. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param {any} [callbackContext] - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Whether this is a collision or overlap check. + * + * @return {boolean} True if any objects overlap (with `overlapOnly`); or true if any overlapping objects were separated. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) + { + if (group1.length === 0 || group2.length === 0) + { + return; + } + + var children = group1.getChildren(); + + for (var i = 0; i < children.length; i++) + { + this.collideSpriteVsGroup(children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + }, + + /** + * Wrap an object's coordinates (or several objects' coordinates) within {@link Phaser.Physics.Arcade.World#bounds}. + * + * If the object is outside any boundary edge (left, top, right, bottom), it will be moved to the same offset from the opposite edge (the interior). + * + * @method Phaser.Physics.Arcade.World#wrap + * @since 3.3.0 + * + * @param {*} object - A Game Object, a Group, an object with `x` and `y` coordinates, or an array of such objects. + * @param {number} [padding=0] - An amount added to each boundary edge during the operation. + */ + wrap: function (object, padding) + { + if (object.body) + { + this.wrapObject(object, padding); + } + else if (object.getChildren) + { + this.wrapArray(object.getChildren(), padding); + } + else if (Array.isArray(object)) + { + this.wrapArray(object, padding); + } + else + { + this.wrapObject(object, padding); + } + }, + + /** + * Wrap each object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. + * + * @method Phaser.Physics.Arcade.World#wrapArray + * @since 3.3.0 + * + * @param {Array.<*>} objects - An array of objects to be wrapped. + * @param {number} [padding=0] - An amount added to the boundary. + */ + wrapArray: function (objects, padding) + { + for (var i = 0; i < objects.length; i++) + { + this.wrapObject(objects[i], padding); + } + }, + + /** + * Wrap an object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. + * + * @method Phaser.Physics.Arcade.World#wrapObject + * @since 3.3.0 + * + * @param {*} object - A Game Object, a Physics Body, or any object with `x` and `y` coordinates + * @param {number} [padding=0] - An amount added to the boundary. + */ + wrapObject: function (object, padding) + { + if (padding === undefined) { padding = 0; } + + object.x = Wrap(object.x, this.bounds.left - padding, this.bounds.right + padding); + object.y = Wrap(object.y, this.bounds.top - padding, this.bounds.bottom + padding); + }, + + /** + * Shuts down the simulation, clearing physics data and removing listeners. + * + * @method Phaser.Physics.Arcade.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.tree.clear(); + this.staticTree.clear(); + this.bodies.clear(); + this.staticBodies.clear(); + this.colliders.destroy(); + + this.removeAllListeners(); + }, + + /** + * Shuts down the simulation and disconnects it from the current scene. + * + * @method Phaser.Physics.Arcade.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene = null; + } + +}); + +module.exports = World; diff --git a/src/physics/arcade/components/Acceleration.js b/src/physics/arcade/components/Acceleration.js index 8cc2a2aeb..0483b10b9 100644 --- a/src/physics/arcade/components/Acceleration.js +++ b/src/physics/arcade/components/Acceleration.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the acceleration properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Acceleration - * @since 3.0.0 - */ -var Acceleration = { - - /** - * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. - * - * @method Phaser.Physics.Arcade.Components.Acceleration#setAcceleration - * @since 3.0.0 - * - * @param {number} x - The horizontal acceleration - * @param {number} [y=x] - The vertical acceleration - * - * @return {this} This Game Object. - */ - setAcceleration: function (x, y) - { - this.body.acceleration.set(x, y); - - return this; - }, - - /** - * Sets the body's horizontal acceleration. - * - * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationX - * @since 3.0.0 - * - * @param {number} value - The horizontal acceleration - * - * @return {this} This Game Object. - */ - setAccelerationX: function (value) - { - this.body.acceleration.x = value; - - return this; - }, - - /** - * Sets the body's vertical acceleration. - * - * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationY - * @since 3.0.0 - * - * @param {number} value - The vertical acceleration - * - * @return {this} This Game Object. - */ - setAccelerationY: function (value) - { - this.body.acceleration.y = value; - - return this; - } - -}; - -module.exports = Acceleration; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the acceleration properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Acceleration + * @since 3.0.0 + */ +var Acceleration = { + + /** + * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. + * + * @method Phaser.Physics.Arcade.Components.Acceleration#setAcceleration + * @since 3.0.0 + * + * @param {number} x - The horizontal acceleration + * @param {number} [y=x] - The vertical acceleration + * + * @return {this} This Game Object. + */ + setAcceleration: function (x, y) + { + this.body.acceleration.set(x, y); + + return this; + }, + + /** + * Sets the body's horizontal acceleration. + * + * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationX + * @since 3.0.0 + * + * @param {number} value - The horizontal acceleration + * + * @return {this} This Game Object. + */ + setAccelerationX: function (value) + { + this.body.acceleration.x = value; + + return this; + }, + + /** + * Sets the body's vertical acceleration. + * + * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationY + * @since 3.0.0 + * + * @param {number} value - The vertical acceleration + * + * @return {this} This Game Object. + */ + setAccelerationY: function (value) + { + this.body.acceleration.y = value; + + return this; + } + +}; + +module.exports = Acceleration; diff --git a/src/physics/arcade/components/Angular.js b/src/physics/arcade/components/Angular.js index 0f502f387..3a252a8a0 100644 --- a/src/physics/arcade/components/Angular.js +++ b/src/physics/arcade/components/Angular.js @@ -1,76 +1,76 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the angular acceleration properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Angular - * @since 3.0.0 - */ -var Angular = { - - /** - * Sets the angular velocity of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * - * @method Phaser.Physics.Arcade.Components.Angular#setAngularVelocity - * @since 3.0.0 - * - * @param {number} value - The amount of angular velocity. - * - * @return {this} This Game Object. - */ - setAngularVelocity: function (value) - { - this.body.angularVelocity = value; - - return this; - }, - - /** - * Sets the angular acceleration of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * - * @method Phaser.Physics.Arcade.Components.Angular#setAngularAcceleration - * @since 3.0.0 - * - * @param {number} value - The amount of angular acceleration. - * - * @return {this} This Game Object. - */ - setAngularAcceleration: function (value) - { - this.body.angularAcceleration = value; - - return this; - }, - - /** - * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. - * - * @method Phaser.Physics.Arcade.Components.Angular#setAngularDrag - * @since 3.0.0 - * - * @param {number} value - The amount of drag. - * - * @return {this} This Game Object. - */ - setAngularDrag: function (value) - { - this.body.angularDrag = value; - - return this; - } - -}; - -module.exports = Angular; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the angular acceleration properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Angular + * @since 3.0.0 + */ +var Angular = { + + /** + * Sets the angular velocity of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * + * @method Phaser.Physics.Arcade.Components.Angular#setAngularVelocity + * @since 3.0.0 + * + * @param {number} value - The amount of angular velocity. + * + * @return {this} This Game Object. + */ + setAngularVelocity: function (value) + { + this.body.angularVelocity = value; + + return this; + }, + + /** + * Sets the angular acceleration of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * + * @method Phaser.Physics.Arcade.Components.Angular#setAngularAcceleration + * @since 3.0.0 + * + * @param {number} value - The amount of angular acceleration. + * + * @return {this} This Game Object. + */ + setAngularAcceleration: function (value) + { + this.body.angularAcceleration = value; + + return this; + }, + + /** + * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. + * + * @method Phaser.Physics.Arcade.Components.Angular#setAngularDrag + * @since 3.0.0 + * + * @param {number} value - The amount of drag. + * + * @return {this} This Game Object. + */ + setAngularDrag: function (value) + { + this.body.angularDrag = value; + + return this; + } + +}; + +module.exports = Angular; diff --git a/src/physics/arcade/components/Bounce.js b/src/physics/arcade/components/Bounce.js index f2d556694..239287d25 100644 --- a/src/physics/arcade/components/Bounce.js +++ b/src/physics/arcade/components/Bounce.js @@ -1,93 +1,93 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the bounce properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Bounce - * @since 3.0.0 - */ -var Bounce = { - - /** - * Sets the bounce values of this body. - * - * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. - * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. - * - * @method Phaser.Physics.Arcade.Components.Bounce#setBounce - * @since 3.0.0 - * - * @param {number} x - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - * @param {number} [y=x] - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. - * - * @return {this} This Game Object. - */ - setBounce: function (x, y) - { - this.body.bounce.set(x, y); - - return this; - }, - - /** - * Sets the horizontal bounce value for this body. - * - * @method Phaser.Physics.Arcade.Components.Bounce#setBounceX - * @since 3.0.0 - * - * @param {number} value - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - * - * @return {this} This Game Object. - */ - setBounceX: function (value) - { - this.body.bounce.x = value; - - return this; - }, - - /** - * Sets the vertical bounce value for this body. - * - * @method Phaser.Physics.Arcade.Components.Bounce#setBounceY - * @since 3.0.0 - * - * @param {number} value - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. - * - * @return {this} This Game Object. - */ - setBounceY: function (value) - { - this.body.bounce.y = value; - - return this; - }, - - /** - * Sets whether this Body collides with the world boundary. - * - * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. - * - * @method Phaser.Physics.Arcade.Components.Bounce#setCollideWorldBounds - * @since 3.0.0 - * - * @param {boolean} [value=true] - `true` if this body should collide with the world bounds, otherwise `false`. - * @param {number} [bounceX] - If given this will be replace the `worldBounce.x` value. - * @param {number} [bounceY] - If given this will be replace the `worldBounce.y` value. - * - * @return {this} This Game Object. - */ - setCollideWorldBounds: function (value, bounceX, bounceY) - { - this.body.setCollideWorldBounds(value, bounceX, bounceY); - - return this; - } - -}; - -module.exports = Bounce; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the bounce properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the bounce values of this body. + * + * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. + * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setBounce + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * @param {number} [y=x] - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + * + * @return {this} This Game Object. + */ + setBounce: function (x, y) + { + this.body.bounce.set(x, y); + + return this; + }, + + /** + * Sets the horizontal bounce value for this body. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setBounceX + * @since 3.0.0 + * + * @param {number} value - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * + * @return {this} This Game Object. + */ + setBounceX: function (value) + { + this.body.bounce.x = value; + + return this; + }, + + /** + * Sets the vertical bounce value for this body. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setBounceY + * @since 3.0.0 + * + * @param {number} value - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + * + * @return {this} This Game Object. + */ + setBounceY: function (value) + { + this.body.bounce.y = value; + + return this; + }, + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * + * @method Phaser.Physics.Arcade.Components.Bounce#setCollideWorldBounds + * @since 3.0.0 + * + * @param {boolean} [value=true] - `true` if this body should collide with the world bounds, otherwise `false`. + * @param {number} [bounceX] - If given this will be replace the `worldBounce.x` value. + * @param {number} [bounceY] - If given this will be replace the `worldBounce.y` value. + * + * @return {this} This Game Object. + */ + setCollideWorldBounds: function (value, bounceX, bounceY) + { + this.body.setCollideWorldBounds(value, bounceX, bounceY); + + return this; + } + +}; + +module.exports = Bounce; diff --git a/src/physics/arcade/components/Debug.js b/src/physics/arcade/components/Debug.js index dd3545ac4..121e62e59 100644 --- a/src/physics/arcade/components/Debug.js +++ b/src/physics/arcade/components/Debug.js @@ -1,121 +1,121 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the debug properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Debug - * @since 3.0.0 - */ -var Debug = { - - /** - * Sets the debug values of this body. - * - * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. - * Note that there is a performance cost in drawing debug displays. It should never be used in production. - * - * @method Phaser.Physics.Arcade.Components.Debug#setDebug - * @since 3.0.0 - * - * @param {boolean} showBody - Set to `true` to have this body render its outline to the debug display. - * @param {boolean} showVelocity - Set to `true` to have this body render a velocity marker to the debug display. - * @param {number} bodyColor - The color of the body outline when rendered to the debug display. - * - * @return {this} This Game Object. - */ - setDebug: function (showBody, showVelocity, bodyColor) - { - this.debugShowBody = showBody; - this.debugShowVelocity = showVelocity; - this.debugBodyColor = bodyColor; - - return this; - }, - - /** - * Sets the color of the body outline when it renders to the debug display. - * - * @method Phaser.Physics.Arcade.Components.Debug#setDebugBodyColor - * @since 3.0.0 - * - * @param {number} value - The color of the body outline when rendered to the debug display. - * - * @return {this} This Game Object. - */ - setDebugBodyColor: function (value) - { - this.body.debugBodyColor = value; - - return this; - }, - - /** - * Set to `true` to have this body render its outline to the debug display. - * - * @name Phaser.Physics.Arcade.Components.Debug#debugShowBody - * @type {boolean} - * @since 3.0.0 - */ - debugShowBody: { - - get: function () - { - return this.body.debugShowBody; - }, - - set: function (value) - { - this.body.debugShowBody = value; - } - - }, - - /** - * Set to `true` to have this body render a velocity marker to the debug display. - * - * @name Phaser.Physics.Arcade.Components.Debug#debugShowVelocity - * @type {boolean} - * @since 3.0.0 - */ - debugShowVelocity: { - - get: function () - { - return this.body.debugShowVelocity; - }, - - set: function (value) - { - this.body.debugShowVelocity = value; - } - - }, - - /** - * The color of the body outline when it renders to the debug display. - * - * @name Phaser.Physics.Arcade.Components.Debug#debugBodyColor - * @type {number} - * @since 3.0.0 - */ - debugBodyColor: { - - get: function () - { - return this.body.debugBodyColor; - }, - - set: function (value) - { - this.body.debugBodyColor = value; - } - - } - -}; - -module.exports = Debug; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the debug properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Debug + * @since 3.0.0 + */ +var Debug = { + + /** + * Sets the debug values of this body. + * + * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. + * Note that there is a performance cost in drawing debug displays. It should never be used in production. + * + * @method Phaser.Physics.Arcade.Components.Debug#setDebug + * @since 3.0.0 + * + * @param {boolean} showBody - Set to `true` to have this body render its outline to the debug display. + * @param {boolean} showVelocity - Set to `true` to have this body render a velocity marker to the debug display. + * @param {number} bodyColor - The color of the body outline when rendered to the debug display. + * + * @return {this} This Game Object. + */ + setDebug: function (showBody, showVelocity, bodyColor) + { + this.debugShowBody = showBody; + this.debugShowVelocity = showVelocity; + this.debugBodyColor = bodyColor; + + return this; + }, + + /** + * Sets the color of the body outline when it renders to the debug display. + * + * @method Phaser.Physics.Arcade.Components.Debug#setDebugBodyColor + * @since 3.0.0 + * + * @param {number} value - The color of the body outline when rendered to the debug display. + * + * @return {this} This Game Object. + */ + setDebugBodyColor: function (value) + { + this.body.debugBodyColor = value; + + return this; + }, + + /** + * Set to `true` to have this body render its outline to the debug display. + * + * @name Phaser.Physics.Arcade.Components.Debug#debugShowBody + * @type {boolean} + * @since 3.0.0 + */ + debugShowBody: { + + get: function () + { + return this.body.debugShowBody; + }, + + set: function (value) + { + this.body.debugShowBody = value; + } + + }, + + /** + * Set to `true` to have this body render a velocity marker to the debug display. + * + * @name Phaser.Physics.Arcade.Components.Debug#debugShowVelocity + * @type {boolean} + * @since 3.0.0 + */ + debugShowVelocity: { + + get: function () + { + return this.body.debugShowVelocity; + }, + + set: function (value) + { + this.body.debugShowVelocity = value; + } + + }, + + /** + * The color of the body outline when it renders to the debug display. + * + * @name Phaser.Physics.Arcade.Components.Debug#debugBodyColor + * @type {number} + * @since 3.0.0 + */ + debugBodyColor: { + + get: function () + { + return this.body.debugBodyColor; + }, + + set: function (value) + { + this.body.debugBodyColor = value; + } + + } + +}; + +module.exports = Debug; diff --git a/src/physics/arcade/components/Drag.js b/src/physics/arcade/components/Drag.js index 441cc079a..19ebe2138 100644 --- a/src/physics/arcade/components/Drag.js +++ b/src/physics/arcade/components/Drag.js @@ -1,127 +1,127 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the drag properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Drag - * @since 3.0.0 - */ -var Drag = { - - /** - * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * - * @method Phaser.Physics.Arcade.Components.Drag#setDrag - * @since 3.0.0 - * - * @param {number} x - The amount of horizontal drag to apply. - * @param {number} [y=x] - The amount of vertical drag to apply. - * - * @return {this} This Game Object. - */ - setDrag: function (x, y) - { - this.body.drag.set(x, y); - - return this; - }, - - /** - * Sets the body's horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * - * @method Phaser.Physics.Arcade.Components.Drag#setDragX - * @since 3.0.0 - * - * @param {number} value - The amount of horizontal drag to apply. - * - * @return {this} This Game Object. - */ - setDragX: function (value) - { - this.body.drag.x = value; - - return this; - }, - - /** - * Sets the body's vertical drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * - * @method Phaser.Physics.Arcade.Components.Drag#setDragY - * @since 3.0.0 - * - * @param {number} value - The amount of vertical drag to apply. - * - * @return {this} This Game Object. - */ - setDragY: function (value) - { - this.body.drag.y = value; - - return this; - }, - - /** - * If this Body is using `drag` for deceleration this function controls how the drag is applied. - * If set to `true` drag will use a damping effect rather than a linear approach. If you are - * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in - * the game Asteroids) then you will get a far smoother and more visually correct deceleration - * by using damping, avoiding the axis-drift that is prone with linear deceleration. - * - * If you enable this property then you should use far smaller `drag` values than with linear, as - * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow - * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. - * - * @method Phaser.Physics.Arcade.Components.Drag#setDamping - * @since 3.10.0 - * - * @param {boolean} value - `true` to use damping for deceleration, or `false` to use linear deceleration. - * - * @return {this} This Game Object. - */ - setDamping: function (value) - { - this.body.useDamping = value; - - return this; - } - -}; - -module.exports = Drag; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the drag properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Drag + * @since 3.0.0 + */ +var Drag = { + + /** + * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDrag + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal drag to apply. + * @param {number} [y=x] - The amount of vertical drag to apply. + * + * @return {this} This Game Object. + */ + setDrag: function (x, y) + { + this.body.drag.set(x, y); + + return this; + }, + + /** + * Sets the body's horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDragX + * @since 3.0.0 + * + * @param {number} value - The amount of horizontal drag to apply. + * + * @return {this} This Game Object. + */ + setDragX: function (value) + { + this.body.drag.x = value; + + return this; + }, + + /** + * Sets the body's vertical drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDragY + * @since 3.0.0 + * + * @param {number} value - The amount of vertical drag to apply. + * + * @return {this} This Game Object. + */ + setDragY: function (value) + { + this.body.drag.y = value; + + return this; + }, + + /** + * If this Body is using `drag` for deceleration this function controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * + * @method Phaser.Physics.Arcade.Components.Drag#setDamping + * @since 3.10.0 + * + * @param {boolean} value - `true` to use damping for deceleration, or `false` to use linear deceleration. + * + * @return {this} This Game Object. + */ + setDamping: function (value) + { + this.body.useDamping = value; + + return this; + } + +}; + +module.exports = Drag; diff --git a/src/physics/arcade/components/Enable.js b/src/physics/arcade/components/Enable.js index 16a10612b..253bf18bd 100644 --- a/src/physics/arcade/components/Enable.js +++ b/src/physics/arcade/components/Enable.js @@ -1,118 +1,118 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the enable properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Enable - * @since 3.0.0 - */ -var Enable = { - - /** - * Enables this Game Object's Body. - * - * @method Phaser.Physics.Arcade.Components.Enable#enableBody - * @since 3.0.0 - * - * @param {boolean} reset - Also reset the Body and place it at (x, y). - * @param {number} x - The horizontal position to place the Game Object and Body. - * @param {number} y - The horizontal position to place the Game Object and Body. - * @param {boolean} enableGameObject - Also activate this Game Object. - * @param {boolean} showGameObject - Also show this Game Object. - * - * @return {this} This Game Object. - * - * @see Phaser.Physics.Arcade.Body#enable - * @see Phaser.Physics.Arcade.StaticBody#enable - * @see Phaser.Physics.Arcade.Body#reset - * @see Phaser.Physics.Arcade.StaticBody#reset - * @see Phaser.GameObjects.GameObject#active - * @see Phaser.GameObjects.GameObject#visible - */ - enableBody: function (reset, x, y, enableGameObject, showGameObject) - { - if (reset) - { - this.body.reset(x, y); - } - - if (enableGameObject) - { - this.body.gameObject.active = true; - } - - if (showGameObject) - { - this.body.gameObject.visible = true; - } - - this.body.enable = true; - - return this; - }, - - /** - * Stops and disables this Game Object's Body. - * - * @method Phaser.Physics.Arcade.Components.Enable#disableBody - * @since 3.0.0 - * - * @param {boolean} [disableGameObject=false] - Also deactivate this Game Object. - * @param {boolean} [hideGameObject=false] - Also hide this Game Object. - * - * @return {this} This Game Object. - * - * @see Phaser.Physics.Arcade.Body#enable - * @see Phaser.Physics.Arcade.StaticBody#enable - * @see Phaser.GameObjects.GameObject#active - * @see Phaser.GameObjects.GameObject#visible - */ - disableBody: function (disableGameObject, hideGameObject) - { - if (disableGameObject === undefined) { disableGameObject = false; } - if (hideGameObject === undefined) { hideGameObject = false; } - - this.body.stop(); - - this.body.enable = false; - - if (disableGameObject) - { - this.body.gameObject.active = false; - } - - if (hideGameObject) - { - this.body.gameObject.visible = false; - } - - return this; - }, - - /** - * 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 - */ - refreshBody: function () - { - this.body.updateFromGameObject(); - - return this; - } - -}; - -module.exports = Enable; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the enable properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Enable + * @since 3.0.0 + */ +var Enable = { + + /** + * Enables this Game Object's Body. + * + * @method Phaser.Physics.Arcade.Components.Enable#enableBody + * @since 3.0.0 + * + * @param {boolean} reset - Also reset the Body and place it at (x, y). + * @param {number} x - The horizontal position to place the Game Object and Body. + * @param {number} y - The horizontal position to place the Game Object and Body. + * @param {boolean} enableGameObject - Also activate this Game Object. + * @param {boolean} showGameObject - Also show this Game Object. + * + * @return {this} This Game Object. + * + * @see Phaser.Physics.Arcade.Body#enable + * @see Phaser.Physics.Arcade.StaticBody#enable + * @see Phaser.Physics.Arcade.Body#reset + * @see Phaser.Physics.Arcade.StaticBody#reset + * @see Phaser.GameObjects.GameObject#active + * @see Phaser.GameObjects.GameObject#visible + */ + enableBody: function (reset, x, y, enableGameObject, showGameObject) + { + if (reset) + { + this.body.reset(x, y); + } + + if (enableGameObject) + { + this.body.gameObject.active = true; + } + + if (showGameObject) + { + this.body.gameObject.visible = true; + } + + this.body.enable = true; + + return this; + }, + + /** + * Stops and disables this Game Object's Body. + * + * @method Phaser.Physics.Arcade.Components.Enable#disableBody + * @since 3.0.0 + * + * @param {boolean} [disableGameObject=false] - Also deactivate this Game Object. + * @param {boolean} [hideGameObject=false] - Also hide this Game Object. + * + * @return {this} This Game Object. + * + * @see Phaser.Physics.Arcade.Body#enable + * @see Phaser.Physics.Arcade.StaticBody#enable + * @see Phaser.GameObjects.GameObject#active + * @see Phaser.GameObjects.GameObject#visible + */ + disableBody: function (disableGameObject, hideGameObject) + { + if (disableGameObject === undefined) { disableGameObject = false; } + if (hideGameObject === undefined) { hideGameObject = false; } + + this.body.stop(); + + this.body.enable = false; + + if (disableGameObject) + { + this.body.gameObject.active = false; + } + + if (hideGameObject) + { + this.body.gameObject.visible = false; + } + + return this; + }, + + /** + * 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 + */ + refreshBody: function () + { + this.body.updateFromGameObject(); + + return this; + } + +}; + +module.exports = Enable; diff --git a/src/physics/arcade/components/Friction.js b/src/physics/arcade/components/Friction.js index a89d68b8f..eaccabb01 100644 --- a/src/physics/arcade/components/Friction.js +++ b/src/physics/arcade/components/Friction.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. The higher than friction, the faster the body will slow down once force stops being applied to it. - * - * @namespace Phaser.Physics.Arcade.Components.Friction - * @since 3.0.0 - */ -var Friction = { - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * - * @method Phaser.Physics.Arcade.Components.Friction#setFriction - * @since 3.0.0 - * - * @param {number} x - The amount of horizontal friction to apply. - * @param {number} [y=x] - The amount of vertical friction to apply. - * - * @return {this} This Game Object. - */ - setFriction: function (x, y) - { - this.body.friction.set(x, y); - - return this; - }, - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * - * @method Phaser.Physics.Arcade.Components.Friction#setFrictionX - * @since 3.0.0 - * - * @param {number} x - The amount of friction to apply. - * - * @return {this} This Game Object. - */ - setFrictionX: function (x) - { - this.body.friction.x = x; - - return this; - }, - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * - * @method Phaser.Physics.Arcade.Components.Friction#setFrictionY - * @since 3.0.0 - * - * @param {number} x - The amount of friction to apply. - * - * @return {this} This Game Object. - */ - setFrictionY: function (y) - { - this.body.friction.y = y; - - return this; - } - -}; - -module.exports = Friction; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @namespace Phaser.Physics.Arcade.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @method Phaser.Physics.Arcade.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} x - The amount of horizontal friction to apply. + * @param {number} [y=x] - The amount of vertical friction to apply. + * + * @return {this} This Game Object. + */ + setFriction: function (x, y) + { + this.body.friction.set(x, y); + + return this; + }, + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @method Phaser.Physics.Arcade.Components.Friction#setFrictionX + * @since 3.0.0 + * + * @param {number} x - The amount of friction to apply. + * + * @return {this} This Game Object. + */ + setFrictionX: function (x) + { + this.body.friction.x = x; + + return this; + }, + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * + * @method Phaser.Physics.Arcade.Components.Friction#setFrictionY + * @since 3.0.0 + * + * @param {number} x - The amount of friction to apply. + * + * @return {this} This Game Object. + */ + setFrictionY: function (y) + { + this.body.friction.y = y; + + return this; + } + +}; + +module.exports = Friction; diff --git a/src/physics/arcade/components/Gravity.js b/src/physics/arcade/components/Gravity.js index 1f21858ec..a7ea64e91 100644 --- a/src/physics/arcade/components/Gravity.js +++ b/src/physics/arcade/components/Gravity.js @@ -1,72 +1,72 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods for setting the gravity properties of an Arcade Physics Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.Physics.Arcade.Components.Gravity - * @since 3.0.0 - */ -var Gravity = { - - /** - * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. - * - * If only one value is provided, this value will be used for both the X and Y axis. - * - * @method Phaser.Physics.Arcade.Components.Gravity#setGravity - * @since 3.0.0 - * - * @param {number} x - The gravitational force to be applied to the X-axis. - * @param {number} [y=x] - The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. - * - * @return {this} This Game Object. - */ - setGravity: function (x, y) - { - this.body.gravity.set(x, y); - - return this; - }, - - /** - * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. - * - * @method Phaser.Physics.Arcade.Components.Gravity#setGravityX - * @since 3.0.0 - * - * @param {number} x - The gravitational force to be applied to the X-axis. - * - * @return {this} This Game Object. - */ - setGravityX: function (x) - { - this.body.gravity.x = x; - - return this; - }, - - /** - * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. - * - * @method Phaser.Physics.Arcade.Components.Gravity#setGravityY - * @since 3.0.0 - * - * @param {number} y - The gravitational force to be applied to the Y-axis. - * - * @return {this} This Game Object. - */ - setGravityY: function (y) - { - this.body.gravity.y = y; - - return this; - } - -}; - -module.exports = Gravity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods for setting the gravity properties of an Arcade Physics Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.Physics.Arcade.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. + * + * If only one value is provided, this value will be used for both the X and Y axis. + * + * @method Phaser.Physics.Arcade.Components.Gravity#setGravity + * @since 3.0.0 + * + * @param {number} x - The gravitational force to be applied to the X-axis. + * @param {number} [y=x] - The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. + * + * @return {this} This Game Object. + */ + setGravity: function (x, y) + { + this.body.gravity.set(x, y); + + return this; + }, + + /** + * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. + * + * @method Phaser.Physics.Arcade.Components.Gravity#setGravityX + * @since 3.0.0 + * + * @param {number} x - The gravitational force to be applied to the X-axis. + * + * @return {this} This Game Object. + */ + setGravityX: function (x) + { + this.body.gravity.x = x; + + return this; + }, + + /** + * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. + * + * @method Phaser.Physics.Arcade.Components.Gravity#setGravityY + * @since 3.0.0 + * + * @param {number} y - The gravitational force to be applied to the Y-axis. + * + * @return {this} This Game Object. + */ + setGravityY: function (y) + { + this.body.gravity.y = y; + + return this; + } + +}; + +module.exports = Gravity; diff --git a/src/physics/arcade/components/Immovable.js b/src/physics/arcade/components/Immovable.js index 613e05309..2c81329d3 100644 --- a/src/physics/arcade/components/Immovable.js +++ b/src/physics/arcade/components/Immovable.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the immovable properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Immovable - * @since 3.0.0 - */ -var Immovable = { - - /** - * Sets Whether this Body can be moved by collisions with another Body. - * - * @method Phaser.Physics.Arcade.Components.Immovable#setImmovable - * @since 3.0.0 - * - * @param {boolean} [value=true] - Sets if this body can be moved by collisions with another Body. - * - * @return {this} This Game Object. - */ - setImmovable: function (value) - { - if (value === undefined) { value = true; } - - this.body.immovable = value; - - return this; - } - -}; - -module.exports = Immovable; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the immovable properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Immovable + * @since 3.0.0 + */ +var Immovable = { + + /** + * Sets Whether this Body can be moved by collisions with another Body. + * + * @method Phaser.Physics.Arcade.Components.Immovable#setImmovable + * @since 3.0.0 + * + * @param {boolean} [value=true] - Sets if this body can be moved by collisions with another Body. + * + * @return {this} This Game Object. + */ + setImmovable: function (value) + { + if (value === undefined) { value = true; } + + this.body.immovable = value; + + return this; + } + +}; + +module.exports = Immovable; diff --git a/src/physics/arcade/components/Mass.js b/src/physics/arcade/components/Mass.js index a56c7d596..527bb5f38 100644 --- a/src/physics/arcade/components/Mass.js +++ b/src/physics/arcade/components/Mass.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods used for setting the mass properties of an Arcade Physics Body. - * - * @namespace Phaser.Physics.Arcade.Components.Mass - * @since 3.0.0 - */ -var Mass = { - - /** - * Sets the mass of the physics body - * - * @method Phaser.Physics.Arcade.Components.Mass#setMass - * @since 3.0.0 - * - * @param {number} value - New value for the mass of the body. - * - * @return {this} This Game Object. - */ - setMass: function (value) - { - this.body.mass = value; - - return this; - } - -}; - -module.exports = Mass; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods used for setting the mass properties of an Arcade Physics Body. + * + * @namespace Phaser.Physics.Arcade.Components.Mass + * @since 3.0.0 + */ +var Mass = { + + /** + * Sets the mass of the physics body + * + * @method Phaser.Physics.Arcade.Components.Mass#setMass + * @since 3.0.0 + * + * @param {number} value - New value for the mass of the body. + * + * @return {this} This Game Object. + */ + setMass: function (value) + { + this.body.mass = value; + + return this; + } + +}; + +module.exports = Mass; diff --git a/src/physics/arcade/components/Size.js b/src/physics/arcade/components/Size.js index ca000e8a3..b3ca9d9dc 100644 --- a/src/physics/arcade/components/Size.js +++ b/src/physics/arcade/components/Size.js @@ -1,76 +1,76 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods for setting the size of an Arcade Physics Game Object. - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.Physics.Arcade.Components.Size - * @since 3.0.0 - */ -var Size = { - - /** - * Sets the body offset. This allows you to adjust the difference between the center of the body - * and the x and y coordinates of the parent Game Object. - * - * @method Phaser.Physics.Arcade.Components.Size#setOffset - * @since 3.0.0 - * - * @param {number} x - The amount to offset the body from the parent Game Object along the x-axis. - * @param {number} [y=x] - The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. - * - * @return {this} This Game Object. - */ - setOffset: function (x, y) - { - this.body.setOffset(x, y); - - return this; - }, - - /** - * Sets the size of this physics body. Setting the size does not adjust the dimensions - * of the parent Game Object. - * - * @method Phaser.Physics.Arcade.Components.Size#setSize - * @since 3.0.0 - * - * @param {number} width - The new width of the physics body, in pixels. - * @param {number} height - The new height of the physics body, in pixels. - * @param {boolean} [center=true] - Should the body be re-positioned so its center aligns with the parent Game Object? - * - * @return {this} This Game Object. - */ - setSize: function (width, height, center) - { - this.body.setSize(width, height, center); - - return this; - }, - - /** - * Sets this physics body to use a circle for collision instead of a rectangle. - * - * @method Phaser.Physics.Arcade.Components.Size#setCircle - * @since 3.0.0 - * - * @param {number} radius - The radius of the physics body, in pixels. - * @param {number} [offsetX] - The amount to offset the body from the parent Game Object along the x-axis. - * @param {number} [offsetY] - The amount to offset the body from the parent Game Object along the y-axis. - * - * @return {this} This Game Object. - */ - setCircle: function (radius, offsetX, offsetY) - { - this.body.setCircle(radius, offsetX, offsetY); - - return this; - } - -}; - -module.exports = Size; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods for setting the size of an Arcade Physics Game Object. + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.Physics.Arcade.Components.Size + * @since 3.0.0 + */ +var Size = { + + /** + * Sets the body offset. This allows you to adjust the difference between the center of the body + * and the x and y coordinates of the parent Game Object. + * + * @method Phaser.Physics.Arcade.Components.Size#setOffset + * @since 3.0.0 + * + * @param {number} x - The amount to offset the body from the parent Game Object along the x-axis. + * @param {number} [y=x] - The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. + * + * @return {this} This Game Object. + */ + setOffset: function (x, y) + { + this.body.setOffset(x, y); + + return this; + }, + + /** + * Sets the size of this physics body. Setting the size does not adjust the dimensions + * of the parent Game Object. + * + * @method Phaser.Physics.Arcade.Components.Size#setSize + * @since 3.0.0 + * + * @param {number} width - The new width of the physics body, in pixels. + * @param {number} height - The new height of the physics body, in pixels. + * @param {boolean} [center=true] - Should the body be re-positioned so its center aligns with the parent Game Object? + * + * @return {this} This Game Object. + */ + setSize: function (width, height, center) + { + this.body.setSize(width, height, center); + + return this; + }, + + /** + * Sets this physics body to use a circle for collision instead of a rectangle. + * + * @method Phaser.Physics.Arcade.Components.Size#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the physics body, in pixels. + * @param {number} [offsetX] - The amount to offset the body from the parent Game Object along the x-axis. + * @param {number} [offsetY] - The amount to offset the body from the parent Game Object along the y-axis. + * + * @return {this} This Game Object. + */ + setCircle: function (radius, offsetX, offsetY) + { + this.body.setCircle(radius, offsetX, offsetY); + + return this; + } + +}; + +module.exports = Size; diff --git a/src/physics/arcade/components/Velocity.js b/src/physics/arcade/components/Velocity.js index 2e78ffedf..d2960c203 100644 --- a/src/physics/arcade/components/Velocity.js +++ b/src/physics/arcade/components/Velocity.js @@ -1,93 +1,93 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Provides methods for modifying the velocity of an Arcade Physics body. - * - * Should be applied as a mixin and not used directly. - * - * @namespace Phaser.Physics.Arcade.Components.Velocity - * @since 3.0.0 - */ -var Velocity = { - - /** - * Sets the velocity of the Body. - * - * @method Phaser.Physics.Arcade.Components.Velocity#setVelocity - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. - * @param {number} [y=x] - The vertical velocity of the body. Positive values move the body down, while negative values move it up. - * - * @return {this} This Game Object. - */ - setVelocity: function (x, y) - { - this.body.setVelocity(x, y); - - return this; - }, - - /** - * Sets the horizontal component of the body's velocity. - * - * Positive values move the body to the right, while negative values move it to the left. - * - * @method Phaser.Physics.Arcade.Components.Velocity#setVelocityX - * @since 3.0.0 - * - * @param {number} x - The new horizontal velocity. - * - * @return {this} This Game Object. - */ - setVelocityX: function (x) - { - this.body.setVelocityX(x); - - return this; - }, - - /** - * Sets the vertical component of the body's velocity. - * - * Positive values move the body down, while negative values move it up. - * - * @method Phaser.Physics.Arcade.Components.Velocity#setVelocityY - * @since 3.0.0 - * - * @param {number} y - The new vertical velocity of the body. - * - * @return {this} This Game Object. - */ - setVelocityY: function (y) - { - this.body.setVelocityY(y); - - return this; - }, - - /** - * Sets the maximum velocity of the body. - * - * @method Phaser.Physics.Arcade.Components.Velocity#setMaxVelocity - * @since 3.0.0 - * - * @param {number} x - The new maximum horizontal velocity. - * @param {number} [y=x] - The new maximum vertical velocity. - * - * @return {this} This Game Object. - */ - setMaxVelocity: function (x, y) - { - this.body.maxVelocity.set(x, y); - - return this; - } - -}; - -module.exports = Velocity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Provides methods for modifying the velocity of an Arcade Physics body. + * + * Should be applied as a mixin and not used directly. + * + * @namespace Phaser.Physics.Arcade.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the velocity of the Body. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. + * @param {number} [y=x] - The vertical velocity of the body. Positive values move the body down, while negative values move it up. + * + * @return {this} This Game Object. + */ + setVelocity: function (x, y) + { + this.body.setVelocity(x, y); + + return this; + }, + + /** + * Sets the horizontal component of the body's velocity. + * + * Positive values move the body to the right, while negative values move it to the left. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The new horizontal velocity. + * + * @return {this} This Game Object. + */ + setVelocityX: function (x) + { + this.body.setVelocityX(x); + + return this; + }, + + /** + * Sets the vertical component of the body's velocity. + * + * Positive values move the body down, while negative values move it up. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The new vertical velocity of the body. + * + * @return {this} This Game Object. + */ + setVelocityY: function (y) + { + this.body.setVelocityY(y); + + return this; + }, + + /** + * Sets the maximum velocity of the body. + * + * @method Phaser.Physics.Arcade.Components.Velocity#setMaxVelocity + * @since 3.0.0 + * + * @param {number} x - The new maximum horizontal velocity. + * @param {number} [y=x] - The new maximum vertical velocity. + * + * @return {this} This Game Object. + */ + setMaxVelocity: function (x, y) + { + this.body.maxVelocity.set(x, y); + + return this; + } + +}; + +module.exports = Velocity; diff --git a/src/physics/arcade/components/index.js b/src/physics/arcade/components/index.js index e6123aa88..9b4aaee29 100644 --- a/src/physics/arcade/components/index.js +++ b/src/physics/arcade/components/index.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Arcade.Components - */ - -module.exports = { - - Acceleration: require('./Acceleration'), - Angular: require('./Angular'), - Bounce: require('./Bounce'), - Debug: require('./Debug'), - Drag: require('./Drag'), - Enable: require('./Enable'), - Friction: require('./Friction'), - Gravity: require('./Gravity'), - Immovable: require('./Immovable'), - Mass: require('./Mass'), - Size: require('./Size'), - Velocity: require('./Velocity') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Arcade.Components + */ + +module.exports = { + + Acceleration: require('./Acceleration'), + Angular: require('./Angular'), + Bounce: require('./Bounce'), + Debug: require('./Debug'), + Drag: require('./Drag'), + Enable: require('./Enable'), + Friction: require('./Friction'), + Gravity: require('./Gravity'), + Immovable: require('./Immovable'), + Mass: require('./Mass'), + Size: require('./Size'), + Velocity: require('./Velocity') + +}; diff --git a/src/physics/arcade/const.js b/src/physics/arcade/const.js index a80a5f1b9..9dfbeaef3 100644 --- a/src/physics/arcade/const.js +++ b/src/physics/arcade/const.js @@ -1,123 +1,123 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Arcade Physics consts. - * - * @ignore - */ - -var CONST = { - - /** - * Dynamic Body. - * - * @name Phaser.Physics.Arcade.DYNAMIC_BODY - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#physicsType - * @see Phaser.Physics.Arcade.Group#physicsType - */ - DYNAMIC_BODY: 0, - - /** - * Static Body. - * - * @name Phaser.Physics.Arcade.STATIC_BODY - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#physicsType - * @see Phaser.Physics.Arcade.StaticBody#physicsType - */ - STATIC_BODY: 1, - - /** - * Arcade Physics Group containing Dynamic Bodies. - * - * @name Phaser.Physics.Arcade.GROUP - * @readonly - * @type {number} - * @since 3.0.0 - */ - GROUP: 2, - - /** - * A Tilemap Layer. - * - * @name Phaser.Physics.Arcade.TILEMAPLAYER - * @readonly - * @type {number} - * @since 3.0.0 - */ - TILEMAPLAYER: 3, - - /** - * Facing no direction (initial value). - * - * @name Phaser.Physics.Arcade.FACING_NONE - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#facing - */ - FACING_NONE: 10, - - /** - * Facing up. - * - * @name Phaser.Physics.Arcade.FACING_UP - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#facing - */ - FACING_UP: 11, - - /** - * Facing down. - * - * @name Phaser.Physics.Arcade.FACING_DOWN - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#facing - */ - FACING_DOWN: 12, - - /** - * Facing left. - * - * @name Phaser.Physics.Arcade.FACING_LEFT - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#facing - */ - FACING_LEFT: 13, - - /** - * Facing right. - * - * @name Phaser.Physics.Arcade.FACING_RIGHT - * @readonly - * @type {number} - * @since 3.0.0 - * - * @see Phaser.Physics.Arcade.Body#facing - */ - FACING_RIGHT: 14 - -}; - -module.exports = CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Arcade Physics consts. + * + * @ignore + */ + +var CONST = { + + /** + * Dynamic Body. + * + * @name Phaser.Physics.Arcade.DYNAMIC_BODY + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#physicsType + * @see Phaser.Physics.Arcade.Group#physicsType + */ + DYNAMIC_BODY: 0, + + /** + * Static Body. + * + * @name Phaser.Physics.Arcade.STATIC_BODY + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#physicsType + * @see Phaser.Physics.Arcade.StaticBody#physicsType + */ + STATIC_BODY: 1, + + /** + * Arcade Physics Group containing Dynamic Bodies. + * + * @name Phaser.Physics.Arcade.GROUP + * @readonly + * @type {number} + * @since 3.0.0 + */ + GROUP: 2, + + /** + * A Tilemap Layer. + * + * @name Phaser.Physics.Arcade.TILEMAPLAYER + * @readonly + * @type {number} + * @since 3.0.0 + */ + TILEMAPLAYER: 3, + + /** + * Facing no direction (initial value). + * + * @name Phaser.Physics.Arcade.FACING_NONE + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_NONE: 10, + + /** + * Facing up. + * + * @name Phaser.Physics.Arcade.FACING_UP + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_UP: 11, + + /** + * Facing down. + * + * @name Phaser.Physics.Arcade.FACING_DOWN + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_DOWN: 12, + + /** + * Facing left. + * + * @name Phaser.Physics.Arcade.FACING_LEFT + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_LEFT: 13, + + /** + * Facing right. + * + * @name Phaser.Physics.Arcade.FACING_RIGHT + * @readonly + * @type {number} + * @since 3.0.0 + * + * @see Phaser.Physics.Arcade.Body#facing + */ + FACING_RIGHT: 14 + +}; + +module.exports = CONST; diff --git a/src/physics/arcade/events/COLLIDE_EVENT.js b/src/physics/arcade/events/COLLIDE_EVENT.js index fc1b14c32..71a0c7654 100644 --- a/src/physics/arcade/events/COLLIDE_EVENT.js +++ b/src/physics/arcade/events/COLLIDE_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics World Collide Event. - * - * This event is dispatched by an Arcade Physics World instance if two bodies collide _and_ at least - * one of them has their [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. - * - * It provides an alternative means to handling collide events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('collide', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - * - * @event Phaser.Physics.Arcade.Events#COLLIDE - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject1 - The first Game Object involved in the collision. This is the parent of `body1`. - * @param {Phaser.GameObjects.GameObject} gameObject2 - The second Game Object involved in the collision. This is the parent of `body2`. - * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body1 - The first Physics Body involved in the collision. - * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body2 - The second Physics Body involved in the collision. - */ -module.exports = 'collide'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Collide Event. + * + * This event is dispatched by an Arcade Physics World instance if two bodies collide _and_ at least + * one of them has their [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('collide', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#COLLIDE + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject1 - The first Game Object involved in the collision. This is the parent of `body1`. + * @param {Phaser.GameObjects.GameObject} gameObject2 - The second Game Object involved in the collision. This is the parent of `body2`. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body1 - The first Physics Body involved in the collision. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body2 - The second Physics Body involved in the collision. + */ +module.exports = 'collide'; diff --git a/src/physics/arcade/events/OVERLAP_EVENT.js b/src/physics/arcade/events/OVERLAP_EVENT.js index ec42658ba..1d4acff16 100644 --- a/src/physics/arcade/events/OVERLAP_EVENT.js +++ b/src/physics/arcade/events/OVERLAP_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics World Overlap Event. - * - * This event is dispatched by an Arcade Physics World instance if two bodies overlap _and_ at least - * one of them has their [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. - * - * It provides an alternative means to handling overlap events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('overlap', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - * - * @event Phaser.Physics.Arcade.Events#OVERLAP - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject1 - The first Game Object involved in the overlap. This is the parent of `body1`. - * @param {Phaser.GameObjects.GameObject} gameObject2 - The second Game Object involved in the overlap. This is the parent of `body2`. - * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body1 - The first Physics Body involved in the overlap. - * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body2 - The second Physics Body involved in the overlap. - */ -module.exports = 'overlap'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Overlap Event. + * + * This event is dispatched by an Arcade Physics World instance if two bodies overlap _and_ at least + * one of them has their [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. + * + * It provides an alternative means to handling overlap events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('overlap', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#OVERLAP + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject1 - The first Game Object involved in the overlap. This is the parent of `body1`. + * @param {Phaser.GameObjects.GameObject} gameObject2 - The second Game Object involved in the overlap. This is the parent of `body2`. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body1 - The first Physics Body involved in the overlap. + * @param {Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody} body2 - The second Physics Body involved in the overlap. + */ +module.exports = 'overlap'; diff --git a/src/physics/arcade/events/PAUSE_EVENT.js b/src/physics/arcade/events/PAUSE_EVENT.js index 71db1e140..94c57bae5 100644 --- a/src/physics/arcade/events/PAUSE_EVENT.js +++ b/src/physics/arcade/events/PAUSE_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics World Pause Event. - * - * This event is dispatched by an Arcade Physics World instance when it is paused. - * - * Listen to it from a Scene using: `this.physics.world.on('pause', listener)`. - * - * @event Phaser.Physics.Arcade.Events#PAUSE - * @since 3.0.0 - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Pause Event. + * + * This event is dispatched by an Arcade Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.physics.world.on('pause', listener)`. + * + * @event Phaser.Physics.Arcade.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; diff --git a/src/physics/arcade/events/RESUME_EVENT.js b/src/physics/arcade/events/RESUME_EVENT.js index b12f0a977..0bebf8d88 100644 --- a/src/physics/arcade/events/RESUME_EVENT.js +++ b/src/physics/arcade/events/RESUME_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics World Resume Event. - * - * This event is dispatched by an Arcade Physics World instance when it resumes from a paused state. - * - * Listen to it from a Scene using: `this.physics.world.on('resume', listener)`. - * - * @event Phaser.Physics.Arcade.Events#RESUME - * @since 3.0.0 - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Resume Event. + * + * This event is dispatched by an Arcade Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.physics.world.on('resume', listener)`. + * + * @event Phaser.Physics.Arcade.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; diff --git a/src/physics/arcade/events/TILE_COLLIDE_EVENT.js b/src/physics/arcade/events/TILE_COLLIDE_EVENT.js index 1e948b827..64e8ff1dc 100644 --- a/src/physics/arcade/events/TILE_COLLIDE_EVENT.js +++ b/src/physics/arcade/events/TILE_COLLIDE_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics Tile Collide Event. - * - * This event is dispatched by an Arcade Physics World instance if a body collides with a Tile _and_ - * has its [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. - * - * It provides an alternative means to handling collide events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('tilecollide', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - * - * @event Phaser.Physics.Arcade.Events#TILE_COLLIDE - * @since 3.16.1 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object involved in the collision. This is the parent of `body`. - * @param {Phaser.Tilemaps.Tile} tile - The tile the body collided with. - * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body of the Game Object involved in the collision. - */ -module.exports = 'tilecollide'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics Tile Collide Event. + * + * This event is dispatched by an Arcade Physics World instance if a body collides with a Tile _and_ + * has its [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('tilecollide', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#TILE_COLLIDE + * @since 3.16.1 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object involved in the collision. This is the parent of `body`. + * @param {Phaser.Tilemaps.Tile} tile - The tile the body collided with. + * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body of the Game Object involved in the collision. + */ +module.exports = 'tilecollide'; diff --git a/src/physics/arcade/events/TILE_OVERLAP_EVENT.js b/src/physics/arcade/events/TILE_OVERLAP_EVENT.js index 64fcbd82b..fd584c4f2 100644 --- a/src/physics/arcade/events/TILE_OVERLAP_EVENT.js +++ b/src/physics/arcade/events/TILE_OVERLAP_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics Tile Overlap Event. - * - * This event is dispatched by an Arcade Physics World instance if a body overlaps with a Tile _and_ - * has its [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. - * - * It provides an alternative means to handling overlap events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('tileoverlap', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - * - * @event Phaser.Physics.Arcade.Events#TILE_OVERLAP - * @since 3.16.1 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object involved in the overlap. This is the parent of `body`. - * @param {Phaser.Tilemaps.Tile} tile - The tile the body overlapped. - * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body of the Game Object involved in the overlap. - */ -module.exports = 'tileoverlap'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics Tile Overlap Event. + * + * This event is dispatched by an Arcade Physics World instance if a body overlaps with a Tile _and_ + * has its [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. + * + * It provides an alternative means to handling overlap events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('tileoverlap', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + * + * @event Phaser.Physics.Arcade.Events#TILE_OVERLAP + * @since 3.16.1 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object involved in the overlap. This is the parent of `body`. + * @param {Phaser.Tilemaps.Tile} tile - The tile the body overlapped. + * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body of the Game Object involved in the overlap. + */ +module.exports = 'tileoverlap'; diff --git a/src/physics/arcade/events/WORLD_BOUNDS_EVENT.js b/src/physics/arcade/events/WORLD_BOUNDS_EVENT.js index b2f4ba019..4826f6eba 100644 --- a/src/physics/arcade/events/WORLD_BOUNDS_EVENT.js +++ b/src/physics/arcade/events/WORLD_BOUNDS_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics World Bounds Event. - * - * This event is dispatched by an Arcade Physics World instance if a body makes contact with the world bounds _and_ - * it has its [onWorldBounds]{@link Phaser.Physics.Arcade.Body#onWorldBounds} property set to `true`. - * - * It provides an alternative means to handling collide events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('worldbounds', listener)`. - * - * @event Phaser.Physics.Arcade.Events#WORLD_BOUNDS - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body that hit the world bounds. - * @param {boolean} up - Is the Body blocked up? I.e. collided with the top of the world bounds. - * @param {boolean} down - Is the Body blocked down? I.e. collided with the bottom of the world bounds. - * @param {boolean} left - Is the Body blocked left? I.e. collided with the left of the world bounds. - * @param {boolean} right - Is the Body blocked right? I.e. collided with the right of the world bounds. - */ -module.exports = 'worldbounds'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Bounds Event. + * + * This event is dispatched by an Arcade Physics World instance if a body makes contact with the world bounds _and_ + * it has its [onWorldBounds]{@link Phaser.Physics.Arcade.Body#onWorldBounds} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('worldbounds', listener)`. + * + * @event Phaser.Physics.Arcade.Events#WORLD_BOUNDS + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Arcade Physics Body that hit the world bounds. + * @param {boolean} up - Is the Body blocked up? I.e. collided with the top of the world bounds. + * @param {boolean} down - Is the Body blocked down? I.e. collided with the bottom of the world bounds. + * @param {boolean} left - Is the Body blocked left? I.e. collided with the left of the world bounds. + * @param {boolean} right - Is the Body blocked right? I.e. collided with the right of the world bounds. + */ +module.exports = 'worldbounds'; diff --git a/src/physics/arcade/events/WORLD_STEP_EVENT.js b/src/physics/arcade/events/WORLD_STEP_EVENT.js index dc404d7a6..9419acbfb 100644 --- a/src/physics/arcade/events/WORLD_STEP_EVENT.js +++ b/src/physics/arcade/events/WORLD_STEP_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Arcade Physics World Step Event. - * - * This event is dispatched by an Arcade Physics World instance whenever a physics step is run. - * It is emitted _after_ the bodies and colliders have been updated. - * - * In high framerate settings this can be multiple times per game frame. - * - * Listen to it from a Scene using: `this.physics.world.on('worldstep', listener)`. - * - * @event Phaser.Physics.Arcade.Events#WORLD_STEP - * @since 3.18.0 - */ -module.exports = 'worldstep'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Arcade Physics World Step Event. + * + * This event is dispatched by an Arcade Physics World instance whenever a physics step is run. + * It is emitted _after_ the bodies and colliders have been updated. + * + * In high framerate settings this can be multiple times per game frame. + * + * Listen to it from a Scene using: `this.physics.world.on('worldstep', listener)`. + * + * @event Phaser.Physics.Arcade.Events#WORLD_STEP + * @since 3.18.0 + */ +module.exports = 'worldstep'; diff --git a/src/physics/arcade/events/index.js b/src/physics/arcade/events/index.js index 1150eaae8..ab6df6a24 100644 --- a/src/physics/arcade/events/index.js +++ b/src/physics/arcade/events/index.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Arcade.Events - */ - -module.exports = { - - COLLIDE: require('./COLLIDE_EVENT'), - OVERLAP: require('./OVERLAP_EVENT'), - PAUSE: require('./PAUSE_EVENT'), - RESUME: require('./RESUME_EVENT'), - TILE_COLLIDE: require('./TILE_COLLIDE_EVENT'), - TILE_OVERLAP: require('./TILE_OVERLAP_EVENT'), - WORLD_BOUNDS: require('./WORLD_BOUNDS_EVENT'), - WORLD_STEP: require('./WORLD_STEP_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Arcade.Events + */ + +module.exports = { + + COLLIDE: require('./COLLIDE_EVENT'), + OVERLAP: require('./OVERLAP_EVENT'), + PAUSE: require('./PAUSE_EVENT'), + RESUME: require('./RESUME_EVENT'), + TILE_COLLIDE: require('./TILE_COLLIDE_EVENT'), + TILE_OVERLAP: require('./TILE_OVERLAP_EVENT'), + WORLD_BOUNDS: require('./WORLD_BOUNDS_EVENT'), + WORLD_STEP: require('./WORLD_STEP_EVENT') + +}; diff --git a/src/physics/arcade/index.js b/src/physics/arcade/index.js index c6298153f..e0a7aa639 100644 --- a/src/physics/arcade/index.js +++ b/src/physics/arcade/index.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../../utils/object/Extend'); - -/** - * @callback ArcadePhysicsCallback - * - * @param {Phaser.GameObjects.GameObject} object1 - The first Body to separate. - * @param {Phaser.GameObjects.GameObject} object2 - The second Body to separate. - */ - -/** - * @namespace Phaser.Physics.Arcade - */ - -var Arcade = { - - ArcadePhysics: require('./ArcadePhysics'), - Body: require('./Body'), - Collider: require('./Collider'), - Components: require('./components'), - Events: require('./events'), - Factory: require('./Factory'), - Group: require('./PhysicsGroup'), - Image: require('./ArcadeImage'), - Sprite: require('./ArcadeSprite'), - StaticBody: require('./StaticBody'), - StaticGroup: require('./StaticPhysicsGroup'), - World: require('./World') - -}; - -// Merge in the consts -Arcade = Extend(false, Arcade, CONST); - -module.exports = Arcade; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../../utils/object/Extend'); + +/** + * @callback ArcadePhysicsCallback + * + * @param {Phaser.GameObjects.GameObject} object1 - The first Body to separate. + * @param {Phaser.GameObjects.GameObject} object2 - The second Body to separate. + */ + +/** + * @namespace Phaser.Physics.Arcade + */ + +var Arcade = { + + ArcadePhysics: require('./ArcadePhysics'), + Body: require('./Body'), + Collider: require('./Collider'), + Components: require('./components'), + Events: require('./events'), + Factory: require('./Factory'), + Group: require('./PhysicsGroup'), + Image: require('./ArcadeImage'), + Sprite: require('./ArcadeSprite'), + StaticBody: require('./StaticBody'), + StaticGroup: require('./StaticPhysicsGroup'), + World: require('./World') + +}; + +// Merge in the consts +Arcade = Extend(false, Arcade, CONST); + +module.exports = Arcade; diff --git a/src/physics/arcade/tilemap/ProcessTileCallbacks.js b/src/physics/arcade/tilemap/ProcessTileCallbacks.js index 4f91076c9..bd1830214 100644 --- a/src/physics/arcade/tilemap/ProcessTileCallbacks.js +++ b/src/physics/arcade/tilemap/ProcessTileCallbacks.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A function to process the collision callbacks between a single tile and an Arcade Physics enabled Game Object. - * - * @function Phaser.Physics.Arcade.Tilemap.ProcessTileCallbacks - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.Tile} tile - The Tile to process. - * @param {Phaser.GameObjects.Sprite} sprite - The Game Object to process with the Tile. - * - * @return {boolean} The result of the callback, `true` for further processing, or `false` to skip this pair. - */ -var ProcessTileCallbacks = function (tile, sprite) -{ - // Tile callbacks take priority over layer level callbacks - if (tile.collisionCallback) - { - return !tile.collisionCallback.call(tile.collisionCallbackContext, sprite, tile); - } - else if (tile.layer.callbacks[tile.index]) - { - return !tile.layer.callbacks[tile.index].callback.call( - tile.layer.callbacks[tile.index].callbackContext, sprite, tile - ); - } - - return true; -}; - -module.exports = ProcessTileCallbacks; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A function to process the collision callbacks between a single tile and an Arcade Physics enabled Game Object. + * + * @function Phaser.Physics.Arcade.Tilemap.ProcessTileCallbacks + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The Tile to process. + * @param {Phaser.GameObjects.Sprite} sprite - The Game Object to process with the Tile. + * + * @return {boolean} The result of the callback, `true` for further processing, or `false` to skip this pair. + */ +var ProcessTileCallbacks = function (tile, sprite) +{ + // Tile callbacks take priority over layer level callbacks + if (tile.collisionCallback) + { + return !tile.collisionCallback.call(tile.collisionCallbackContext, sprite, tile); + } + else if (tile.layer.callbacks[tile.index]) + { + return !tile.layer.callbacks[tile.index].callback.call( + tile.layer.callbacks[tile.index].callbackContext, sprite, tile + ); + } + + return true; +}; + +module.exports = ProcessTileCallbacks; diff --git a/src/physics/arcade/tilemap/ProcessTileSeparationX.js b/src/physics/arcade/tilemap/ProcessTileSeparationX.js index a9a6b4250..fc6f20508 100644 --- a/src/physics/arcade/tilemap/ProcessTileSeparationX.js +++ b/src/physics/arcade/tilemap/ProcessTileSeparationX.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Internal function to process the separation of a physics body from a tile. - * - * @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 separation amount. - */ -var ProcessTileSeparationX = function (body, x) -{ - if (x < 0) - { - body.blocked.none = false; - body.blocked.left = true; - } - else if (x > 0) - { - body.blocked.none = false; - body.blocked.right = true; - } - - body.position.x -= x; - - if (body.bounce.x === 0) - { - body.velocity.x = 0; - } - else - { - body.velocity.x = -body.velocity.x * body.bounce.x; - } -}; - -module.exports = ProcessTileSeparationX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internal function to process the separation of a physics body from a tile. + * + * @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 separation amount. + */ +var ProcessTileSeparationX = function (body, x) +{ + if (x < 0) + { + body.blocked.none = false; + body.blocked.left = true; + } + else if (x > 0) + { + body.blocked.none = false; + body.blocked.right = true; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } +}; + +module.exports = ProcessTileSeparationX; diff --git a/src/physics/arcade/tilemap/ProcessTileSeparationY.js b/src/physics/arcade/tilemap/ProcessTileSeparationY.js index 820d0922c..4abee9b6a 100644 --- a/src/physics/arcade/tilemap/ProcessTileSeparationY.js +++ b/src/physics/arcade/tilemap/ProcessTileSeparationY.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Internal function to process the separation of a physics body from a tile. - * - * @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 y separation amount. - */ -var ProcessTileSeparationY = function (body, y) -{ - if (y < 0) - { - body.blocked.none = false; - body.blocked.up = true; - } - else if (y > 0) - { - body.blocked.none = false; - body.blocked.down = true; - } - - body.position.y -= y; - - if (body.bounce.y === 0) - { - body.velocity.y = 0; - } - else - { - body.velocity.y = -body.velocity.y * body.bounce.y; - } -}; - -module.exports = ProcessTileSeparationY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internal function to process the separation of a physics body from a tile. + * + * @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 y separation amount. + */ +var ProcessTileSeparationY = function (body, y) +{ + if (y < 0) + { + body.blocked.none = false; + body.blocked.up = true; + } + else if (y > 0) + { + body.blocked.none = false; + body.blocked.down = true; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } +}; + +module.exports = ProcessTileSeparationY; diff --git a/src/physics/arcade/tilemap/SeparateTile.js b/src/physics/arcade/tilemap/SeparateTile.js index e9bc03b7f..467eb1b49 100644 --- a/src/physics/arcade/tilemap/SeparateTile.js +++ b/src/physics/arcade/tilemap/SeparateTile.js @@ -1,114 +1,114 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var TileCheckX = require('./TileCheckX'); -var TileCheckY = require('./TileCheckY'); -var TileIntersectsBody = require('./TileIntersectsBody'); - -/** - * The core separation function to separate a physics body and a tile. - * - * @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.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemapLayer to collide against. - * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. - * @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`. - */ -var SeparateTile = function (i, body, tile, tileWorldRect, tilemapLayer, tileBias, isLayer) -{ - var tileLeft = tileWorldRect.left; - var tileTop = tileWorldRect.top; - var tileRight = tileWorldRect.right; - var tileBottom = tileWorldRect.bottom; - var faceHorizontal = tile.faceLeft || tile.faceRight; - var faceVertical = tile.faceTop || tile.faceBottom; - - if (!isLayer) - { - faceHorizontal = true; - faceVertical = true; - } - - // 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. - if (!faceHorizontal && !faceVertical) - { - return false; - } - - var ox = 0; - var oy = 0; - var minX = 0; - var minY = 1; - - if (body.deltaAbsX() > body.deltaAbsY()) - { - // Moving faster horizontally, check X axis first - minX = -1; - } - else if (body.deltaAbsX() < body.deltaAbsY()) - { - // Moving faster vertically, check Y axis first - minY = -1; - } - - if (body.deltaX() !== 0 && body.deltaY() !== 0 && faceHorizontal && faceVertical) - { - // We only need do this if both axes have colliding faces AND we're moving in both - // directions - minX = Math.min(Math.abs(body.position.x - tileRight), Math.abs(body.right - tileLeft)); - minY = Math.min(Math.abs(body.position.y - tileBottom), Math.abs(body.bottom - tileTop)); - } - - if (minX < minY) - { - if (faceHorizontal) - { - ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias, isLayer); - - // That's horizontal done, check if we still intersects? If not then we can return now - if (ox !== 0 && !TileIntersectsBody(tileWorldRect, body)) - { - return true; - } - } - - if (faceVertical) - { - oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias, isLayer); - } - } - else - { - if (faceVertical) - { - oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias, isLayer); - - // That's vertical done, check if we still intersects? If not then we can return now - if (oy !== 0 && !TileIntersectsBody(tileWorldRect, body)) - { - return true; - } - } - - if (faceHorizontal) - { - ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias, isLayer); - } - } - - return (ox !== 0 || oy !== 0); -}; - -module.exports = SeparateTile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TileCheckX = require('./TileCheckX'); +var TileCheckY = require('./TileCheckY'); +var TileIntersectsBody = require('./TileIntersectsBody'); + +/** + * The core separation function to separate a physics body and a tile. + * + * @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.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - The tilemapLayer to collide against. + * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @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`. + */ +var SeparateTile = function (i, body, tile, tileWorldRect, tilemapLayer, tileBias, isLayer) +{ + var tileLeft = tileWorldRect.left; + var tileTop = tileWorldRect.top; + var tileRight = tileWorldRect.right; + var tileBottom = tileWorldRect.bottom; + var faceHorizontal = tile.faceLeft || tile.faceRight; + var faceVertical = tile.faceTop || tile.faceBottom; + + if (!isLayer) + { + faceHorizontal = true; + faceVertical = true; + } + + // 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. + if (!faceHorizontal && !faceVertical) + { + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && faceHorizontal && faceVertical) + { + // We only need do this if both axes have colliding faces AND we're moving in both + // directions + minX = Math.min(Math.abs(body.position.x - tileRight), Math.abs(body.right - tileLeft)); + minY = Math.min(Math.abs(body.position.y - tileBottom), Math.abs(body.bottom - tileTop)); + } + + if (minX < minY) + { + if (faceHorizontal) + { + ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias, isLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !TileIntersectsBody(tileWorldRect, body)) + { + return true; + } + } + + if (faceVertical) + { + oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias, isLayer); + } + } + else + { + if (faceVertical) + { + oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias, isLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !TileIntersectsBody(tileWorldRect, body)) + { + return true; + } + } + + if (faceHorizontal) + { + ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias, isLayer); + } + } + + return (ox !== 0 || oy !== 0); +}; + +module.exports = SeparateTile; diff --git a/src/physics/arcade/tilemap/TileCheckX.js b/src/physics/arcade/tilemap/TileCheckX.js index c6f65b793..2d7c01777 100644 --- a/src/physics/arcade/tilemap/TileCheckX.js +++ b/src/physics/arcade/tilemap/TileCheckX.js @@ -1,84 +1,84 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ProcessTileSeparationX = require('./ProcessTileSeparationX'); - -/** - * Check the body against the given tile on the X axis. - * Used internally by the SeparateTile function. - * - * @function Phaser.Physics.Arcade.Tilemap.TileCheckX - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {Phaser.Tilemaps.Tile} tile - The tile to check. - * @param {number} tileLeft - The left position of the tile within the tile world. - * @param {number} tileRight - The right position of the tile within the tile world. - * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. - * @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles? - * - * @return {number} The amount of separation that occurred. - */ -var TileCheckX = function (body, tile, tileLeft, tileRight, tileBias, isLayer) -{ - var ox = 0; - - var faceLeft = tile.faceLeft; - var faceRight = tile.faceRight; - var collideLeft = tile.collideLeft; - var collideRight = tile.collideRight; - - if (!isLayer) - { - faceLeft = true; - faceRight = true; - collideLeft = true; - collideRight = true; - } - - if (body.deltaX() < 0 && collideRight && body.checkCollision.left) - { - // Body is moving LEFT - if (faceRight && body.x < tileRight) - { - ox = body.x - tileRight; - - if (ox < -tileBias) - { - ox = 0; - } - } - } - else if (body.deltaX() > 0 && collideLeft && body.checkCollision.right) - { - // Body is moving RIGHT - if (faceLeft && body.right > tileLeft) - { - ox = body.right - tileLeft; - - if (ox > tileBias) - { - ox = 0; - } - } - } - - if (ox !== 0) - { - if (body.customSeparateX) - { - body.overlapX = ox; - } - else - { - ProcessTileSeparationX(body, ox); - } - } - - return ox; -}; - -module.exports = TileCheckX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ProcessTileSeparationX = require('./ProcessTileSeparationX'); + +/** + * Check the body against the given tile on the X axis. + * Used internally by the SeparateTile function. + * + * @function Phaser.Physics.Arcade.Tilemap.TileCheckX + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tilemaps.Tile} tile - The tile to check. + * @param {number} tileLeft - The left position of the tile within the tile world. + * @param {number} tileRight - The right position of the tile within the tile world. + * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles? + * + * @return {number} The amount of separation that occurred. + */ +var TileCheckX = function (body, tile, tileLeft, tileRight, tileBias, isLayer) +{ + var ox = 0; + + var faceLeft = tile.faceLeft; + var faceRight = tile.faceRight; + var collideLeft = tile.collideLeft; + var collideRight = tile.collideRight; + + if (!isLayer) + { + faceLeft = true; + faceRight = true; + collideLeft = true; + collideRight = true; + } + + if (body.deltaX() < 0 && collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (faceRight && body.x < tileRight) + { + ox = body.x - tileRight; + + if (ox < -tileBias) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (faceLeft && body.right > tileLeft) + { + ox = body.right - tileLeft; + + if (ox > tileBias) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + ProcessTileSeparationX(body, ox); + } + } + + return ox; +}; + +module.exports = TileCheckX; diff --git a/src/physics/arcade/tilemap/TileCheckY.js b/src/physics/arcade/tilemap/TileCheckY.js index 5129a646c..12ffdccba 100644 --- a/src/physics/arcade/tilemap/TileCheckY.js +++ b/src/physics/arcade/tilemap/TileCheckY.js @@ -1,84 +1,84 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ProcessTileSeparationY = require('./ProcessTileSeparationY'); - -/** - * Check the body against the given tile on the Y axis. - * Used internally by the SeparateTile function. - * - * @function Phaser.Physics.Arcade.Tilemap.TileCheckY - * @since 3.0.0 - * - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {Phaser.Tilemaps.Tile} tile - The tile to check. - * @param {number} tileTop - The top position of the tile within the tile world. - * @param {number} tileBottom - The bottom position of the tile within the tile world. - * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. - * @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles? - * - * @return {number} The amount of separation that occurred. - */ -var TileCheckY = function (body, tile, tileTop, tileBottom, tileBias, isLayer) -{ - var oy = 0; - - var faceTop = tile.faceTop; - var faceBottom = tile.faceBottom; - var collideUp = tile.collideUp; - var collideDown = tile.collideDown; - - if (!isLayer) - { - faceTop = true; - faceBottom = true; - collideUp = true; - collideDown = true; - } - - if (body.deltaY() < 0 && collideDown && body.checkCollision.up) - { - // Body is moving UP - if (faceBottom && body.y < tileBottom) - { - oy = body.y - tileBottom; - - if (oy < -tileBias) - { - oy = 0; - } - } - } - else if (body.deltaY() > 0 && collideUp && body.checkCollision.down) - { - // Body is moving DOWN - if (faceTop && body.bottom > tileTop) - { - oy = body.bottom - tileTop; - - if (oy > tileBias) - { - oy = 0; - } - } - } - - if (oy !== 0) - { - if (body.customSeparateY) - { - body.overlapY = oy; - } - else - { - ProcessTileSeparationY(body, oy); - } - } - - return oy; -}; - -module.exports = TileCheckY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ProcessTileSeparationY = require('./ProcessTileSeparationY'); + +/** + * Check the body against the given tile on the Y axis. + * Used internally by the SeparateTile function. + * + * @function Phaser.Physics.Arcade.Tilemap.TileCheckY + * @since 3.0.0 + * + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tilemaps.Tile} tile - The tile to check. + * @param {number} tileTop - The top position of the tile within the tile world. + * @param {number} tileBottom - The bottom position of the tile within the tile world. + * @param {number} tileBias - The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles? + * + * @return {number} The amount of separation that occurred. + */ +var TileCheckY = function (body, tile, tileTop, tileBottom, tileBias, isLayer) +{ + var oy = 0; + + var faceTop = tile.faceTop; + var faceBottom = tile.faceBottom; + var collideUp = tile.collideUp; + var collideDown = tile.collideDown; + + if (!isLayer) + { + faceTop = true; + faceBottom = true; + collideUp = true; + collideDown = true; + } + + if (body.deltaY() < 0 && collideDown && body.checkCollision.up) + { + // Body is moving UP + if (faceBottom && body.y < tileBottom) + { + oy = body.y - tileBottom; + + if (oy < -tileBias) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (faceTop && body.bottom > tileTop) + { + oy = body.bottom - tileTop; + + if (oy > tileBias) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + ProcessTileSeparationY(body, oy); + } + } + + return oy; +}; + +module.exports = TileCheckY; diff --git a/src/physics/arcade/tilemap/TileIntersectsBody.js b/src/physics/arcade/tilemap/TileIntersectsBody.js index 9fbd2ba2f..59709fbb5 100644 --- a/src/physics/arcade/tilemap/TileIntersectsBody.js +++ b/src/physics/arcade/tilemap/TileIntersectsBody.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks for intersection between the given tile rectangle-like object and an Arcade Physics body. - * - * @function Phaser.Physics.Arcade.Tilemap.TileIntersectsBody - * @since 3.0.0 - * - * @param {{ left: number, right: number, top: number, bottom: number }} tileWorldRect - A rectangle object that defines the tile placement in the world. - * @param {Phaser.Physics.Arcade.Body} body - The body to check for intersection against. - * - * @return {boolean} Returns `true` of the tile intersects with the body, otherwise `false`. - */ -var TileIntersectsBody = function (tileWorldRect, body) -{ - // Currently, all bodies are treated as rectangles when colliding with a Tile. - - return !( - body.right <= tileWorldRect.left || - body.bottom <= tileWorldRect.top || - body.position.x >= tileWorldRect.right || - body.position.y >= tileWorldRect.bottom - ); -}; - -module.exports = TileIntersectsBody; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks for intersection between the given tile rectangle-like object and an Arcade Physics body. + * + * @function Phaser.Physics.Arcade.Tilemap.TileIntersectsBody + * @since 3.0.0 + * + * @param {{ left: number, right: number, top: number, bottom: number }} tileWorldRect - A rectangle object that defines the tile placement in the world. + * @param {Phaser.Physics.Arcade.Body} body - The body to check for intersection against. + * + * @return {boolean} Returns `true` of the tile intersects with the body, otherwise `false`. + */ +var TileIntersectsBody = function (tileWorldRect, body) +{ + // Currently, all bodies are treated as rectangles when colliding with a Tile. + + return !( + body.right <= tileWorldRect.left || + body.bottom <= tileWorldRect.top || + body.position.x >= tileWorldRect.right || + body.position.y >= tileWorldRect.bottom + ); +}; + +module.exports = TileIntersectsBody; diff --git a/src/physics/arcade/typedefs/index.js b/src/physics/arcade/typedefs/index.js index 10e9c7e8b..69dfe19f4 100644 --- a/src/physics/arcade/typedefs/index.js +++ b/src/physics/arcade/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Physics.Arcade - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Physics.Arcade + */ diff --git a/src/physics/index.js b/src/physics/index.js index cd52da3b0..421dde21e 100644 --- a/src/physics/index.js +++ b/src/physics/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics - */ - -/** - * @namespace Phaser.Types.Physics - */ - -module.exports = { - - Arcade: require('./arcade'), - Matter: require('./matter-js') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics + */ + +/** + * @namespace Phaser.Types.Physics + */ + +module.exports = { + + Arcade: require('./arcade'), + Matter: require('./matter-js') + +}; diff --git a/src/physics/matter-js/BodyBounds.js b/src/physics/matter-js/BodyBounds.js index 7ccc6fc7f..112b19450 100644 --- a/src/physics/matter-js/BodyBounds.js +++ b/src/physics/matter-js/BodyBounds.js @@ -1,400 +1,400 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Vector2 = require('../../math/Vector2'); - -/** - * @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 - */ -var BodyBounds = new Class({ - - initialize: - - function BodyBounds () - { - /** - * A Vector2 that stores the temporary bounds center value during calculations by methods in this class. - * - * @name Phaser.Physics.Matter.BodyBounds#boundsCenter - * @type {Phaser.Math.Vector2} - * @since 3.22.0 - */ - this.boundsCenter = new Vector2(); - - /** - * A Vector2 that stores the temporary center diff values during calculations by methods in this class. - * - * @name Phaser.Physics.Matter.BodyBounds#centerDiff - * @type {Phaser.Math.Vector2} - * @since 3.22.0 - */ - this.centerDiff = new Vector2(); - }, - - /** - * Parses the given body to get the bounds diff values from it. - * - * They're stored in this class in the temporary properties `boundsCenter` and `centerDiff`. - * - * This method is called automatically by all other methods in this class. - * - * @method Phaser.Physics.Matter.BodyBounds#parseBody - * @since 3.22.0 - * - * @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the bounds position from. - * - * @return {boolean} `true` if it was able to get the bounds, otherwise `false`. - */ - parseBody: function (body) - { - body = (body.hasOwnProperty('body')) ? body.body : body; - - if (!body.hasOwnProperty('bounds') || !body.hasOwnProperty('centerOfMass')) - { - return false; - } - - var boundsCenter = this.boundsCenter; - var centerDiff = this.centerDiff; - - var boundsWidth = body.bounds.max.x - body.bounds.min.x; - var boundsHeight = body.bounds.max.y - body.bounds.min.y; - - var bodyCenterX = boundsWidth * body.centerOfMass.x; - var bodyCenterY = boundsHeight * body.centerOfMass.y; - - boundsCenter.set(boundsWidth / 2, boundsHeight / 2); - centerDiff.set(bodyCenterX - boundsCenter.x, bodyCenterY - boundsCenter.y); - - return true; - }, - - /** - * 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 bodies _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. - */ - getTopLeft: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x + center.x + diff.x, - y + center.y + diff.y - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getTopCenter: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x + diff.x, - y + center.y + diff.y - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getTopRight: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x - (center.x - diff.x), - y + center.y + diff.y - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getLeftCenter: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x + center.x + diff.x, - y + diff.y - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getCenter: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var diff = this.centerDiff; - - return new Vector2( - x + diff.x, - y + diff.y - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getRightCenter: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x - (center.x - diff.x), - y + diff.y - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getBottomLeft: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x + center.x + diff.x, - y - (center.y - diff.y) - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getBottomCenter: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x + diff.x, - y - (center.y - diff.y) - ); - } - - return false; - }, - - /** - * 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 bodies _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. - */ - getBottomRight: function (body, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - if (this.parseBody(body)) - { - var center = this.boundsCenter; - var diff = this.centerDiff; - - return new Vector2( - x - (center.x - diff.x), - y - (center.y - diff.y) - ); - } - - return false; - } - -}); - -module.exports = BodyBounds; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Vector2 = require('../../math/Vector2'); + +/** + * @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 + */ +var BodyBounds = new Class({ + + initialize: + + function BodyBounds () + { + /** + * A Vector2 that stores the temporary bounds center value during calculations by methods in this class. + * + * @name Phaser.Physics.Matter.BodyBounds#boundsCenter + * @type {Phaser.Math.Vector2} + * @since 3.22.0 + */ + this.boundsCenter = new Vector2(); + + /** + * A Vector2 that stores the temporary center diff values during calculations by methods in this class. + * + * @name Phaser.Physics.Matter.BodyBounds#centerDiff + * @type {Phaser.Math.Vector2} + * @since 3.22.0 + */ + this.centerDiff = new Vector2(); + }, + + /** + * Parses the given body to get the bounds diff values from it. + * + * They're stored in this class in the temporary properties `boundsCenter` and `centerDiff`. + * + * This method is called automatically by all other methods in this class. + * + * @method Phaser.Physics.Matter.BodyBounds#parseBody + * @since 3.22.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the bounds position from. + * + * @return {boolean} `true` if it was able to get the bounds, otherwise `false`. + */ + parseBody: function (body) + { + body = (body.hasOwnProperty('body')) ? body.body : body; + + if (!body.hasOwnProperty('bounds') || !body.hasOwnProperty('centerOfMass')) + { + return false; + } + + var boundsCenter = this.boundsCenter; + var centerDiff = this.centerDiff; + + var boundsWidth = body.bounds.max.x - body.bounds.min.x; + var boundsHeight = body.bounds.max.y - body.bounds.min.y; + + var bodyCenterX = boundsWidth * body.centerOfMass.x; + var bodyCenterY = boundsHeight * body.centerOfMass.y; + + boundsCenter.set(boundsWidth / 2, boundsHeight / 2); + centerDiff.set(bodyCenterX - boundsCenter.x, bodyCenterY - boundsCenter.y); + + return true; + }, + + /** + * 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 bodies _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. + */ + getTopLeft: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + center.x + diff.x, + y + center.y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getTopCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + diff.x, + y + center.y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getTopRight: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x - (center.x - diff.x), + y + center.y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getLeftCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + center.x + diff.x, + y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var diff = this.centerDiff; + + return new Vector2( + x + diff.x, + y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getRightCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x - (center.x - diff.x), + y + diff.y + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getBottomLeft: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + center.x + diff.x, + y - (center.y - diff.y) + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getBottomCenter: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x + diff.x, + y - (center.y - diff.y) + ); + } + + return false; + }, + + /** + * 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 bodies _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. + */ + getBottomRight: function (body, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + if (this.parseBody(body)) + { + var center = this.boundsCenter; + var diff = this.centerDiff; + + return new Vector2( + x - (center.x - diff.x), + y - (center.y - diff.y) + ); + } + + return false; + } + +}); + +module.exports = BodyBounds; diff --git a/src/physics/matter-js/CustomMain.js b/src/physics/matter-js/CustomMain.js index 09c3d3061..c1150e60e 100644 --- a/src/physics/matter-js/CustomMain.js +++ b/src/physics/matter-js/CustomMain.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Matter.Matter - */ - -var Matter = require('./lib/core/Matter'); - -Matter.Body = require('./lib/body/Body'); -Matter.Composite = require('./lib/body/Composite'); -Matter.World = require('./lib/body/World'); - -Matter.Detector = require('./lib/collision/Detector'); -Matter.Grid = require('./lib/collision/Grid'); -Matter.Pairs = require('./lib/collision/Pairs'); -Matter.Pair = require('./lib/collision/Pair'); -Matter.Query = require('./lib/collision/Query'); -Matter.Resolver = require('./lib/collision/Resolver'); -Matter.SAT = require('./lib/collision/SAT'); - -Matter.Constraint = require('./lib/constraint/Constraint'); - -Matter.Common = require('./lib/core/Common'); -Matter.Engine = require('./lib/core/Engine'); -Matter.Events = require('./lib/core/Events'); -Matter.Sleeping = require('./lib/core/Sleeping'); -Matter.Plugin = require('./lib/core/Plugin'); - -Matter.Bodies = require('./lib/factory/Bodies'); -Matter.Composites = require('./lib/factory/Composites'); - -Matter.Axes = require('./lib/geometry/Axes'); -Matter.Bounds = require('./lib/geometry/Bounds'); -Matter.Svg = require('./lib/geometry/Svg'); -Matter.Vector = require('./lib/geometry/Vector'); -Matter.Vertices = require('./lib/geometry/Vertices'); - -// aliases - -Matter.World.add = Matter.Composite.add; -Matter.World.remove = Matter.Composite.remove; -Matter.World.addComposite = Matter.Composite.addComposite; -Matter.World.addBody = Matter.Composite.addBody; -Matter.World.addConstraint = Matter.Composite.addConstraint; -Matter.World.clear = Matter.Composite.clear; - -module.exports = Matter; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter.Matter + */ + +var Matter = require('./lib/core/Matter'); + +Matter.Body = require('./lib/body/Body'); +Matter.Composite = require('./lib/body/Composite'); +Matter.World = require('./lib/body/World'); + +Matter.Detector = require('./lib/collision/Detector'); +Matter.Grid = require('./lib/collision/Grid'); +Matter.Pairs = require('./lib/collision/Pairs'); +Matter.Pair = require('./lib/collision/Pair'); +Matter.Query = require('./lib/collision/Query'); +Matter.Resolver = require('./lib/collision/Resolver'); +Matter.SAT = require('./lib/collision/SAT'); + +Matter.Constraint = require('./lib/constraint/Constraint'); + +Matter.Common = require('./lib/core/Common'); +Matter.Engine = require('./lib/core/Engine'); +Matter.Events = require('./lib/core/Events'); +Matter.Sleeping = require('./lib/core/Sleeping'); +Matter.Plugin = require('./lib/core/Plugin'); + +Matter.Bodies = require('./lib/factory/Bodies'); +Matter.Composites = require('./lib/factory/Composites'); + +Matter.Axes = require('./lib/geometry/Axes'); +Matter.Bounds = require('./lib/geometry/Bounds'); +Matter.Svg = require('./lib/geometry/Svg'); +Matter.Vector = require('./lib/geometry/Vector'); +Matter.Vertices = require('./lib/geometry/Vertices'); + +// aliases + +Matter.World.add = Matter.Composite.add; +Matter.World.remove = Matter.Composite.remove; +Matter.World.addComposite = Matter.Composite.addComposite; +Matter.World.addBody = Matter.Composite.addBody; +Matter.World.addConstraint = Matter.Composite.addConstraint; +Matter.World.clear = Matter.Composite.clear; + +module.exports = Matter; diff --git a/src/physics/matter-js/Factory.js b/src/physics/matter-js/Factory.js index 8851832aa..ac2842f6f 100644 --- a/src/physics/matter-js/Factory.js +++ b/src/physics/matter-js/Factory.js @@ -1,924 +1,924 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bodies = require('./lib/factory/Bodies'); -var Class = require('../../utils/Class'); -var Composites = require('./lib/factory/Composites'); -var Constraint = require('./lib/constraint/Constraint'); -var Svg = require('./lib/geometry/Svg'); -var MatterGameObject = require('./MatterGameObject'); -var MatterImage = require('./MatterImage'); -var MatterSprite = require('./MatterSprite'); -var MatterTileBody = require('./MatterTileBody'); -var PhysicsEditorParser = require('./PhysicsEditorParser'); -var PhysicsJSONParser = require('./PhysicsJSONParser'); -var PointerConstraint = require('./PointerConstraint'); -var Vertices = require('./lib/geometry/Vertices'); - -/** - * @classdesc - * The Matter Factory is responsible for quickly creating a variety of different types of - * bodies, constraints and Game Objects and adding them into the physics world. - * - * You access the factory from within a Scene using `add`: - * - * ```javascript - * this.matter.add.rectangle(x, y, width, height); - * ``` - * - * Use of the Factory is optional. All of the objects it creates can also be created - * directly via your own code or constructors. It is provided as a means to keep your - * code concise. - * - * @class Factory - * @memberof Phaser.Physics.Matter - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.World} world - The Matter World which this Factory adds to. - */ -var Factory = new Class({ - - initialize: - - function Factory (world) - { - /** - * The Matter World which this Factory adds to. - * - * @name Phaser.Physics.Matter.Factory#world - * @type {Phaser.Physics.Matter.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The Scene which this Factory's Matter World belongs to. - * - * @name Phaser.Physics.Matter.Factory#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = world.scene; - - /** - * A reference to the Scene.Systems this Matter Physics instance belongs to. - * - * @name Phaser.Physics.Matter.Factory#sys - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.sys = world.scene.sys; - }, - - /** - * Creates a new rigid rectangular Body and adds it to the World. - * - * @method Phaser.Physics.Matter.Factory#rectangle - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the center of the Body. - * @param {number} y - The Y coordinate of the center of the Body. - * @param {number} width - The width of the Body. - * @param {number} height - The height of the Body. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.BodyType} A Matter JS Body. - */ - rectangle: function (x, y, width, height, options) - { - var body = Bodies.rectangle(x, y, width, height, options); - - this.world.add(body); - - return body; - }, - - /** - * Creates a new rigid trapezoidal Body and adds it to the World. - * - * @method Phaser.Physics.Matter.Factory#trapezoid - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the center of the Body. - * @param {number} y - The Y coordinate of the center of the Body. - * @param {number} width - The width of the trapezoid Body. - * @param {number} height - The height of the trapezoid Body. - * @param {number} slope - The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.BodyType} A Matter JS Body. - */ - trapezoid: function (x, y, width, height, slope, options) - { - var body = Bodies.trapezoid(x, y, width, height, slope, options); - - this.world.add(body); - - return body; - }, - - /** - * Creates a new rigid circular Body and adds it to the World. - * - * @method Phaser.Physics.Matter.Factory#circle - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the center of the Body. - * @param {number} y - The Y coordinate of the center of the Body. - * @param {number} radius - The radius of the circle. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * @param {number} [maxSides] - The maximum amount of sides to use for the polygon which will approximate this circle. - * - * @return {MatterJS.BodyType} A Matter JS Body. - */ - circle: function (x, y, radius, options, maxSides) - { - var body = Bodies.circle(x, y, radius, options, maxSides); - - this.world.add(body); - - return body; - }, - - /** - * Creates a new rigid polygonal Body and adds it to the World. - * - * @method Phaser.Physics.Matter.Factory#polygon - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the center of the Body. - * @param {number} y - The Y coordinate of the center of the Body. - * @param {number} sides - The number of sides the polygon will have. - * @param {number} radius - The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.BodyType} A Matter JS Body. - */ - polygon: function (x, y, sides, radius, options) - { - var body = Bodies.polygon(x, y, sides, radius, options); - - this.world.add(body); - - return body; - }, - - /** - * Creates a body using the supplied vertices (or an array containing multiple sets of vertices) and adds it to the World. - * If the vertices are convex, they will pass through as supplied. Otherwise, if the vertices are concave, they will be decomposed. Note that this process is not guaranteed to support complex sets of vertices, e.g. ones with holes. - * - * @method Phaser.Physics.Matter.Factory#fromVertices - * @since 3.0.0 - * - * @param {number} x - The X coordinate of the center of the Body. - * @param {number} y - The Y coordinate of the center of the Body. - * @param {(string|array)} vertexSets - The vertices data. Either a path string or an array of vertices. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * @param {boolean} [flagInternal=false] - Flag internal edges (coincident part edges) - * @param {number} [removeCollinear=0.01] - Whether Matter.js will discard collinear edges (to improve performance). - * @param {number} [minimumArea=10] - During decomposition discard parts that have an area less than this. - * - * @return {MatterJS.BodyType} A Matter JS Body. - */ - fromVertices: function (x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) - { - if (typeof vertexSets === 'string') - { - vertexSets = Vertices.fromPath(vertexSets); - } - - var body = Bodies.fromVertices(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea); - - this.world.add(body); - - return 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 pas 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. - */ - fromPhysicsEditor: function (x, y, config, options, addToWorld) - { - if (addToWorld === undefined) { addToWorld = true; } - - var body = PhysicsEditorParser.parseBody(x, y, config, options); - - if (addToWorld && !this.world.has(body)) - { - this.world.add(body); - } - - return 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. - */ - fromSVG: function (x, y, xml, scale, options, addToWorld) - { - if (scale === undefined) { scale = 1; } - if (options === undefined) { options = {}; } - if (addToWorld === undefined) { addToWorld = true; } - - var path = xml.getElementsByTagName('path'); - var vertexSets = []; - - for (var i = 0; i < path.length; i++) - { - var points = Svg.pathToVertices(path[i], 30); - - if (scale !== 1) - { - Vertices.scale(points, scale, scale); - } - - vertexSets.push(points); - } - - var body = Bodies.fromVertices(x, y, vertexSets, options); - - if (addToWorld) - { - this.world.add(body); - } - - return body; - }, - - /** - * Creates a body using the supplied physics data, as provided by a JSON file. - * - * The data file should be loaded as JSON: - * - * ```javascript - * preload () - * { - * this.load.json('ninjas', 'assets/ninjas.json); - * } - * - * create () - * { - * const ninjaShapes = this.cache.json.get('ninjas'); - * - * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); - * } - * ``` - * - * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. - * - * If you pas in an `options` object, any settings in there will override those in the config object. - * - * The structure of the JSON file is as follows: - * - * ```text - * { - * 'generator_info': // The name of the application that created the JSON data - * 'shapeName': { - * 'type': // The type of body - * 'label': // Optional body label - * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs - * } - * } - * ``` - * - * At the time of writing, only the Phaser Physics Tracer App exports in this format. - * - * @method Phaser.Physics.Matter.Factory#fromJSON - * @since 3.22.0 - * - * @param {number} x - The X coordinate of the body. - * @param {number} y - The Y coordinate of the body. - * @param {any} config - The JSON physics data. - * @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. - */ - fromJSON: function (x, y, config, options, addToWorld) - { - if (options === undefined) { options = {}; } - if (addToWorld === undefined) { addToWorld = true; } - - var body = PhysicsJSONParser.parseBody(x, y, config, options); - - if (body && addToWorld) - { - this.world.add(body); - } - - return body; - }, - - /** - * Create a new composite containing Matter Image objects created in a grid arrangement. - * This function uses the body bounds to prevent overlaps. - * - * @method Phaser.Physics.Matter.Factory#imageStack - * @since 3.0.0 - * - * @param {string} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} frame - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. - * @param {number} x - The horizontal position of this composite in the world. - * @param {number} y - The vertical position of this composite in the world. - * @param {number} columns - The number of columns in the grid. - * @param {number} rows - The number of rows in the grid. - * @param {number} [columnGap=0] - The distance between each column. - * @param {number} [rowGap=0] - The distance between each row. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.CompositeType} A Matter JS Composite Stack. - */ - imageStack: function (key, frame, x, y, columns, rows, columnGap, rowGap, options) - { - if (columnGap === undefined) { columnGap = 0; } - if (rowGap === undefined) { rowGap = 0; } - if (options === undefined) { options = {}; } - - var world = this.world; - var displayList = this.sys.displayList; - - options.addToWorld = false; - - var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, function (x, y) - { - var image = new MatterImage(world, x, y, key, frame, options); - - displayList.add(image); - - return image.body; - }); - - world.add(stack); - - return stack; - }, - - /** - * Create a new composite containing bodies created in the callback in a grid arrangement. - * - * This function uses the body bounds to prevent overlaps. - * - * @method Phaser.Physics.Matter.Factory#stack - * @since 3.0.0 - * - * @param {number} x - The horizontal position of this composite in the world. - * @param {number} y - The vertical position of this composite in the world. - * @param {number} columns - The number of columns in the grid. - * @param {number} rows - The number of rows in the grid. - * @param {number} columnGap - The distance between each column. - * @param {number} rowGap - The distance between each row. - * @param {function} callback - The callback that creates the stack. - * - * @return {MatterJS.CompositeType} A new composite containing objects created in the callback. - */ - stack: function (x, y, columns, rows, columnGap, rowGap, callback) - { - var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, callback); - - this.world.add(stack); - - return stack; - }, - - /** - * Create a new composite containing bodies created in the callback in a pyramid arrangement. - * This function uses the body bounds to prevent overlaps. - * - * @method Phaser.Physics.Matter.Factory#pyramid - * @since 3.0.0 - * - * @param {number} x - The horizontal position of this composite in the world. - * @param {number} y - The vertical position of this composite in the world. - * @param {number} columns - The number of columns in the pyramid. - * @param {number} rows - The number of rows in the pyramid. - * @param {number} columnGap - The distance between each column. - * @param {number} rowGap - The distance between each row. - * @param {function} callback - The callback function to be invoked. - * - * @return {MatterJS.CompositeType} A Matter JS Composite pyramid. - */ - pyramid: function (x, y, columns, rows, columnGap, rowGap, callback) - { - var stack = Composites.pyramid(x, y, columns, rows, columnGap, rowGap, callback); - - this.world.add(stack); - - return stack; - }, - - /** - * 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. - */ - chain: function (composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) - { - return Composites.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options); - }, - - /** - * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. - * - * @method Phaser.Physics.Matter.Factory#mesh - * @since 3.0.0 - * - * @param {MatterJS.CompositeType} composite - The composite in which all bodies will be chained together. - * @param {number} columns - The number of columns in the mesh. - * @param {number} rows - The number of rows in the mesh. - * @param {boolean} crossBrace - Create cross braces for the mesh as well? - * @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. - */ - mesh: function (composite, columns, rows, crossBrace, options) - { - return Composites.mesh(composite, columns, rows, crossBrace, options); - }, - - /** - * Creates a composite with a Newton's Cradle setup of bodies and constraints. - * - * @method Phaser.Physics.Matter.Factory#newtonsCradle - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the start of the cradle. - * @param {number} y - The vertical position of the start of the cradle. - * @param {number} number - The number of balls in the cradle. - * @param {number} size - The radius of each ball in the cradle. - * @param {number} length - The length of the 'string' the balls hang from. - * - * @return {MatterJS.CompositeType} A Newton's cradle composite. - */ - newtonsCradle: function (x, y, number, size, length) - { - var composite = Composites.newtonsCradle(x, y, number, size, length); - - this.world.add(composite); - - return composite; - }, - - /** - * Creates a composite with simple car setup of bodies and constraints. - * - * @method Phaser.Physics.Matter.Factory#car - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the car in the world. - * @param {number} y - The vertical position of the car in the world. - * @param {number} width - The width of the car chasis. - * @param {number} height - The height of the car chasis. - * @param {number} wheelSize - The radius of the car wheels. - * - * @return {MatterJS.CompositeType} A new composite car body. - */ - car: function (x, y, width, height, wheelSize) - { - var composite = Composites.car(x, y, width, height, wheelSize); - - this.world.add(composite); - - return composite; - }, - - /** - * Creates a simple soft body like object. - * - * @method Phaser.Physics.Matter.Factory#softBody - * @since 3.0.0 - * - * @param {number} x - The horizontal position of this composite in the world. - * @param {number} y - The vertical position of this composite in the world. - * @param {number} columns - The number of columns in the Composite. - * @param {number} rows - The number of rows in the Composite. - * @param {number} columnGap - The distance between each column. - * @param {number} rowGap - The distance between each row. - * @param {boolean} crossBrace - `true` to create cross braces between the bodies, or `false` to create just straight braces. - * @param {number} particleRadius - The radius of this circlular composite. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [particleOptions] - An optional Body configuration object that is used to set initial Body properties on creation. - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [constraintOptions] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.CompositeType} A new composite simple soft body. - */ - softBody: function (x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) - { - var composite = Composites.softBody(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions); - - this.world.add(composite); - - return composite; - }, - - /** - * This method is an alias for `Factory.constraint`. - * - * Constraints (or joints) 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. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * - * @method Phaser.Physics.Matter.Factory#joint - * @since 3.0.0 - * - * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. - * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. - * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.ConstraintType} A Matter JS Constraint. - */ - joint: function (bodyA, bodyB, length, stiffness, options) - { - return this.constraint(bodyA, bodyB, length, stiffness, options); - }, - - /** - * This method is an alias for `Factory.constraint`. - * - * Constraints (or joints) 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. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * - * @method Phaser.Physics.Matter.Factory#spring - * @since 3.0.0 - * - * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. - * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. - * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.ConstraintType} A Matter JS Constraint. - */ - spring: function (bodyA, bodyB, length, stiffness, options) - { - return this.constraint(bodyA, bodyB, length, stiffness, options); - }, - - /** - * Constraints (or joints) 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. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * - * @method Phaser.Physics.Matter.Factory#constraint - * @since 3.0.0 - * - * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. - * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. - * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.ConstraintType} A Matter JS Constraint. - */ - constraint: function (bodyA, bodyB, length, stiffness, options) - { - if (stiffness === undefined) { stiffness = 1; } - if (options === undefined) { options = {}; } - - options.bodyA = (bodyA.type === 'body') ? bodyA : bodyA.body; - options.bodyB = (bodyB.type === 'body') ? bodyB : bodyB.body; - - if (!isNaN(length)) - { - options.length = length; - } - - options.stiffness = stiffness; - - var constraint = Constraint.create(options); - - this.world.add(constraint); - - return constraint; - }, - - /** - * Constraints (or joints) are used for specifying that a fixed distance must be maintained - * between two bodies, or a body and a fixed world-space position. - * - * A world constraint has only one body, you should specify a `pointA` position in - * the constraint options parameter to attach the constraint to the world. - * - * The stiffness of constraints can be modified to create springs or elastic. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * - * @method Phaser.Physics.Matter.Factory#worldConstraint - * @since 3.0.0 - * - * @param {MatterJS.BodyType} body - The Matter `Body` that this constraint is attached to. - * @param {number} [length] - A number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.ConstraintType} A Matter JS Constraint. - */ - worldConstraint: function (body, length, stiffness, options) - { - if (stiffness === undefined) { stiffness = 1; } - if (options === undefined) { options = {}; } - - options.bodyB = (body.type === 'body') ? body : body.body; - - if (!isNaN(length)) - { - options.length = length; - } - - options.stiffness = stiffness; - - var constraint = Constraint.create(options); - - this.world.add(constraint); - - return constraint; - }, - - /** - * This method is an alias for `Factory.pointerConstraint`. - * - * A Pointer Constraint is a special type of constraint that allows you to click - * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, - * and when one is pressed down it checks to see if that hit any part of any active - * body in the world. If it did, and the body has input enabled, it will begin to - * drag it until either released, or you stop it via the `stopDrag` method. - * - * You can adjust the stiffness, length and other properties of the constraint via - * the `options` object on creation. - * - * @method Phaser.Physics.Matter.Factory#mouseSpring - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.ConstraintType} A Matter JS Constraint. - */ - mouseSpring: function (options) - { - return this.pointerConstraint(options); - }, - - /** - * A Pointer Constraint is a special type of constraint that allows you to click - * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, - * and when one is pressed down it checks to see if that hit any part of any active - * body in the world. If it did, and the body has input enabled, it will begin to - * drag it until either released, or you stop it via the `stopDrag` method. - * - * You can adjust the stiffness, length and other properties of the constraint via - * the `options` object on creation. - * - * @method Phaser.Physics.Matter.Factory#pointerConstraint - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. - * - * @return {MatterJS.ConstraintType} A Matter JS Constraint. - */ - pointerConstraint: function (options) - { - if (options === undefined) { options = {}; } - - if (!options.hasOwnProperty('render')) - { - options.render = { visible: false }; - } - - var pointerConstraint = new PointerConstraint(this.scene, this.world, options); - - this.world.add(pointerConstraint.constraint); - - return pointerConstraint; - }, - - /** - * Creates a Matter Physics Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * - * @method Phaser.Physics.Matter.Factory#image - * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {Phaser.Physics.Matter.Image} The Matter Image Game Object. - */ - image: function (x, y, key, frame, options) - { - var image = new MatterImage(this.world, x, y, key, frame, options); - - this.sys.displayList.add(image); - - return image; - }, - - /** - * Creates a wrapper around a Tile that provides access to a corresponding Matter body. A tile can only - * have one Matter body associated with it. You can either pass in an existing Matter body for - * the tile or allow the constructor to create the corresponding body for you. If the Tile has a - * collision group (defined in Tiled), those shapes will be used to create the body. If not, the - * tile's rectangle bounding box will be used. - * - * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. - * - * Note: not all Tiled collision shapes are supported. See - * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. - * - * @method Phaser.Physics.Matter.Factory#tileBody - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.Tile} tile - The target tile that should have a Matter body. - * @param {Phaser.Types.Physics.Matter.MatterTileOptions} [options] - Options to be used when creating the Matter body. - * - * @return {Phaser.Physics.Matter.TileBody} The Matter Tile Body Game Object. - */ - tileBody: function (tile, options) - { - return new MatterTileBody(this.world, tile, options); - }, - - /** - * Creates a Matter Physics Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * - * @method Phaser.Physics.Matter.Factory#sprite - * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {Phaser.Physics.Matter.Sprite} The Matter Sprite Game Object. - */ - sprite: function (x, y, key, frame, options) - { - var sprite = new MatterSprite(this.world, x, y, key, frame, options); - - this.sys.displayList.add(sprite); - this.sys.updateList.add(sprite); - - return sprite; - }, - - /** - * Takes an existing Game Object and injects all of the Matter Components into it. - * - * This enables you to use component methods such as `setVelocity` or `isSensor` directly from - * this Game Object. - * - * You can also pass in either a Matter Body Configuration object, or a Matter Body instance - * to link with this Game Object. - * - * @method Phaser.Physics.Matter.Factory#gameObject - * @since 3.3.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to inject the Matter Components in to. - * @param {(Phaser.Types.Physics.Matter.MatterBodyConfig|MatterJS.Body)} [options] - A Matter Body configuration object, or an instance of a Matter Body. - * @param {boolean} [addToWorld=true] - Add this Matter Body to the World? - * - * @return {Phaser.GameObjects.GameObject} The Game Object that had the Matter Components injected into it. - */ - gameObject: function (gameObject, options, addToWorld) - { - return MatterGameObject(this.world, gameObject, options, addToWorld); - }, - - /** - * Destroys this Factory. - * - * @method Phaser.Physics.Matter.Factory#destroy - * @since 3.5.0 - */ - destroy: function () - { - this.world = null; - this.scene = null; - this.sys = null; - } - -}); - -module.exports = Factory; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = require('./lib/factory/Bodies'); +var Class = require('../../utils/Class'); +var Composites = require('./lib/factory/Composites'); +var Constraint = require('./lib/constraint/Constraint'); +var Svg = require('./lib/geometry/Svg'); +var MatterGameObject = require('./MatterGameObject'); +var MatterImage = require('./MatterImage'); +var MatterSprite = require('./MatterSprite'); +var MatterTileBody = require('./MatterTileBody'); +var PhysicsEditorParser = require('./PhysicsEditorParser'); +var PhysicsJSONParser = require('./PhysicsJSONParser'); +var PointerConstraint = require('./PointerConstraint'); +var Vertices = require('./lib/geometry/Vertices'); + +/** + * @classdesc + * The Matter Factory is responsible for quickly creating a variety of different types of + * bodies, constraints and Game Objects and adding them into the physics world. + * + * You access the factory from within a Scene using `add`: + * + * ```javascript + * this.matter.add.rectangle(x, y, width, height); + * ``` + * + * Use of the Factory is optional. All of the objects it creates can also be created + * directly via your own code or constructors. It is provided as a means to keep your + * code concise. + * + * @class Factory + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.World} world - The Matter World which this Factory adds to. + */ +var Factory = new Class({ + + initialize: + + function Factory (world) + { + /** + * The Matter World which this Factory adds to. + * + * @name Phaser.Physics.Matter.Factory#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Scene which this Factory's Matter World belongs to. + * + * @name Phaser.Physics.Matter.Factory#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = world.scene; + + /** + * A reference to the Scene.Systems this Matter Physics instance belongs to. + * + * @name Phaser.Physics.Matter.Factory#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = world.scene.sys; + }, + + /** + * Creates a new rigid rectangular Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#rectangle + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} width - The width of the Body. + * @param {number} height - The height of the Body. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + rectangle: function (x, y, width, height, options) + { + var body = Bodies.rectangle(x, y, width, height, options); + + this.world.add(body); + + return body; + }, + + /** + * Creates a new rigid trapezoidal Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#trapezoid + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} width - The width of the trapezoid Body. + * @param {number} height - The height of the trapezoid Body. + * @param {number} slope - The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + trapezoid: function (x, y, width, height, slope, options) + { + var body = Bodies.trapezoid(x, y, width, height, slope, options); + + this.world.add(body); + + return body; + }, + + /** + * Creates a new rigid circular Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#circle + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} radius - The radius of the circle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * @param {number} [maxSides] - The maximum amount of sides to use for the polygon which will approximate this circle. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + circle: function (x, y, radius, options, maxSides) + { + var body = Bodies.circle(x, y, radius, options, maxSides); + + this.world.add(body); + + return body; + }, + + /** + * Creates a new rigid polygonal Body and adds it to the World. + * + * @method Phaser.Physics.Matter.Factory#polygon + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {number} sides - The number of sides the polygon will have. + * @param {number} radius - The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + polygon: function (x, y, sides, radius, options) + { + var body = Bodies.polygon(x, y, sides, radius, options); + + this.world.add(body); + + return body; + }, + + /** + * Creates a body using the supplied vertices (or an array containing multiple sets of vertices) and adds it to the World. + * If the vertices are convex, they will pass through as supplied. Otherwise, if the vertices are concave, they will be decomposed. Note that this process is not guaranteed to support complex sets of vertices, e.g. ones with holes. + * + * @method Phaser.Physics.Matter.Factory#fromVertices + * @since 3.0.0 + * + * @param {number} x - The X coordinate of the center of the Body. + * @param {number} y - The Y coordinate of the center of the Body. + * @param {(string|array)} vertexSets - The vertices data. Either a path string or an array of vertices. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * @param {boolean} [flagInternal=false] - Flag internal edges (coincident part edges) + * @param {number} [removeCollinear=0.01] - Whether Matter.js will discard collinear edges (to improve performance). + * @param {number} [minimumArea=10] - During decomposition discard parts that have an area less than this. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + fromVertices: function (x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) + { + if (typeof vertexSets === 'string') + { + vertexSets = Vertices.fromPath(vertexSets); + } + + var body = Bodies.fromVertices(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea); + + this.world.add(body); + + return 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 pas 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. + */ + fromPhysicsEditor: function (x, y, config, options, addToWorld) + { + if (addToWorld === undefined) { addToWorld = true; } + + var body = PhysicsEditorParser.parseBody(x, y, config, options); + + if (addToWorld && !this.world.has(body)) + { + this.world.add(body); + } + + return 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. + */ + fromSVG: function (x, y, xml, scale, options, addToWorld) + { + if (scale === undefined) { scale = 1; } + if (options === undefined) { options = {}; } + if (addToWorld === undefined) { addToWorld = true; } + + var path = xml.getElementsByTagName('path'); + var vertexSets = []; + + for (var i = 0; i < path.length; i++) + { + var points = Svg.pathToVertices(path[i], 30); + + if (scale !== 1) + { + Vertices.scale(points, scale, scale); + } + + vertexSets.push(points); + } + + var body = Bodies.fromVertices(x, y, vertexSets, options); + + if (addToWorld) + { + this.world.add(body); + } + + return body; + }, + + /** + * Creates a body using the supplied physics data, as provided by a JSON file. + * + * The data file should be loaded as JSON: + * + * ```javascript + * preload () + * { + * this.load.json('ninjas', 'assets/ninjas.json); + * } + * + * create () + * { + * const ninjaShapes = this.cache.json.get('ninjas'); + * + * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); + * } + * ``` + * + * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. + * + * If you pas in an `options` object, any settings in there will override those in the config object. + * + * The structure of the JSON file is as follows: + * + * ```text + * { + * 'generator_info': // The name of the application that created the JSON data + * 'shapeName': { + * 'type': // The type of body + * 'label': // Optional body label + * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs + * } + * } + * ``` + * + * At the time of writing, only the Phaser Physics Tracer App exports in this format. + * + * @method Phaser.Physics.Matter.Factory#fromJSON + * @since 3.22.0 + * + * @param {number} x - The X coordinate of the body. + * @param {number} y - The Y coordinate of the body. + * @param {any} config - The JSON physics data. + * @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. + */ + fromJSON: function (x, y, config, options, addToWorld) + { + if (options === undefined) { options = {}; } + if (addToWorld === undefined) { addToWorld = true; } + + var body = PhysicsJSONParser.parseBody(x, y, config, options); + + if (body && addToWorld) + { + this.world.add(body); + } + + return body; + }, + + /** + * Create a new composite containing Matter Image objects created in a grid arrangement. + * This function uses the body bounds to prevent overlaps. + * + * @method Phaser.Physics.Matter.Factory#imageStack + * @since 3.0.0 + * + * @param {string} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} frame - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the grid. + * @param {number} rows - The number of rows in the grid. + * @param {number} [columnGap=0] - The distance between each column. + * @param {number} [rowGap=0] - The distance between each row. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.CompositeType} A Matter JS Composite Stack. + */ + imageStack: function (key, frame, x, y, columns, rows, columnGap, rowGap, options) + { + if (columnGap === undefined) { columnGap = 0; } + if (rowGap === undefined) { rowGap = 0; } + if (options === undefined) { options = {}; } + + var world = this.world; + var displayList = this.sys.displayList; + + options.addToWorld = false; + + var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, function (x, y) + { + var image = new MatterImage(world, x, y, key, frame, options); + + displayList.add(image); + + return image.body; + }); + + world.add(stack); + + return stack; + }, + + /** + * Create a new composite containing bodies created in the callback in a grid arrangement. + * + * This function uses the body bounds to prevent overlaps. + * + * @method Phaser.Physics.Matter.Factory#stack + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the grid. + * @param {number} rows - The number of rows in the grid. + * @param {number} columnGap - The distance between each column. + * @param {number} rowGap - The distance between each row. + * @param {function} callback - The callback that creates the stack. + * + * @return {MatterJS.CompositeType} A new composite containing objects created in the callback. + */ + stack: function (x, y, columns, rows, columnGap, rowGap, callback) + { + var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, callback); + + this.world.add(stack); + + return stack; + }, + + /** + * Create a new composite containing bodies created in the callback in a pyramid arrangement. + * This function uses the body bounds to prevent overlaps. + * + * @method Phaser.Physics.Matter.Factory#pyramid + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the pyramid. + * @param {number} rows - The number of rows in the pyramid. + * @param {number} columnGap - The distance between each column. + * @param {number} rowGap - The distance between each row. + * @param {function} callback - The callback function to be invoked. + * + * @return {MatterJS.CompositeType} A Matter JS Composite pyramid. + */ + pyramid: function (x, y, columns, rows, columnGap, rowGap, callback) + { + var stack = Composites.pyramid(x, y, columns, rows, columnGap, rowGap, callback); + + this.world.add(stack); + + return stack; + }, + + /** + * 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. + */ + chain: function (composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) + { + return Composites.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options); + }, + + /** + * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. + * + * @method Phaser.Physics.Matter.Factory#mesh + * @since 3.0.0 + * + * @param {MatterJS.CompositeType} composite - The composite in which all bodies will be chained together. + * @param {number} columns - The number of columns in the mesh. + * @param {number} rows - The number of rows in the mesh. + * @param {boolean} crossBrace - Create cross braces for the mesh as well? + * @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. + */ + mesh: function (composite, columns, rows, crossBrace, options) + { + return Composites.mesh(composite, columns, rows, crossBrace, options); + }, + + /** + * Creates a composite with a Newton's Cradle setup of bodies and constraints. + * + * @method Phaser.Physics.Matter.Factory#newtonsCradle + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the start of the cradle. + * @param {number} y - The vertical position of the start of the cradle. + * @param {number} number - The number of balls in the cradle. + * @param {number} size - The radius of each ball in the cradle. + * @param {number} length - The length of the 'string' the balls hang from. + * + * @return {MatterJS.CompositeType} A Newton's cradle composite. + */ + newtonsCradle: function (x, y, number, size, length) + { + var composite = Composites.newtonsCradle(x, y, number, size, length); + + this.world.add(composite); + + return composite; + }, + + /** + * Creates a composite with simple car setup of bodies and constraints. + * + * @method Phaser.Physics.Matter.Factory#car + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the car in the world. + * @param {number} y - The vertical position of the car in the world. + * @param {number} width - The width of the car chasis. + * @param {number} height - The height of the car chasis. + * @param {number} wheelSize - The radius of the car wheels. + * + * @return {MatterJS.CompositeType} A new composite car body. + */ + car: function (x, y, width, height, wheelSize) + { + var composite = Composites.car(x, y, width, height, wheelSize); + + this.world.add(composite); + + return composite; + }, + + /** + * Creates a simple soft body like object. + * + * @method Phaser.Physics.Matter.Factory#softBody + * @since 3.0.0 + * + * @param {number} x - The horizontal position of this composite in the world. + * @param {number} y - The vertical position of this composite in the world. + * @param {number} columns - The number of columns in the Composite. + * @param {number} rows - The number of rows in the Composite. + * @param {number} columnGap - The distance between each column. + * @param {number} rowGap - The distance between each row. + * @param {boolean} crossBrace - `true` to create cross braces between the bodies, or `false` to create just straight braces. + * @param {number} particleRadius - The radius of this circlular composite. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [particleOptions] - An optional Body configuration object that is used to set initial Body properties on creation. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [constraintOptions] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.CompositeType} A new composite simple soft body. + */ + softBody: function (x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) + { + var composite = Composites.softBody(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions); + + this.world.add(composite); + + return composite; + }, + + /** + * This method is an alias for `Factory.constraint`. + * + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#joint + * @since 3.0.0 + * + * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. + * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. + * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + joint: function (bodyA, bodyB, length, stiffness, options) + { + return this.constraint(bodyA, bodyB, length, stiffness, options); + }, + + /** + * This method is an alias for `Factory.constraint`. + * + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#spring + * @since 3.0.0 + * + * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. + * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. + * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + spring: function (bodyA, bodyB, length, stiffness, options) + { + return this.constraint(bodyA, bodyB, length, stiffness, options); + }, + + /** + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#constraint + * @since 3.0.0 + * + * @param {MatterJS.BodyType} bodyA - The first possible `Body` that this constraint is attached to. + * @param {MatterJS.BodyType} bodyB - The second possible `Body` that this constraint is attached to. + * @param {number} [length] - A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + constraint: function (bodyA, bodyB, length, stiffness, options) + { + if (stiffness === undefined) { stiffness = 1; } + if (options === undefined) { options = {}; } + + options.bodyA = (bodyA.type === 'body') ? bodyA : bodyA.body; + options.bodyB = (bodyB.type === 'body') ? bodyB : bodyB.body; + + if (!isNaN(length)) + { + options.length = length; + } + + options.stiffness = stiffness; + + var constraint = Constraint.create(options); + + this.world.add(constraint); + + return constraint; + }, + + /** + * Constraints (or joints) are used for specifying that a fixed distance must be maintained + * between two bodies, or a body and a fixed world-space position. + * + * A world constraint has only one body, you should specify a `pointA` position in + * the constraint options parameter to attach the constraint to the world. + * + * The stiffness of constraints can be modified to create springs or elastic. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * + * @method Phaser.Physics.Matter.Factory#worldConstraint + * @since 3.0.0 + * + * @param {MatterJS.BodyType} body - The Matter `Body` that this constraint is attached to. + * @param {number} [length] - A number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param {number} [stiffness=1] - A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + worldConstraint: function (body, length, stiffness, options) + { + if (stiffness === undefined) { stiffness = 1; } + if (options === undefined) { options = {}; } + + options.bodyB = (body.type === 'body') ? body : body.body; + + if (!isNaN(length)) + { + options.length = length; + } + + options.stiffness = stiffness; + + var constraint = Constraint.create(options); + + this.world.add(constraint); + + return constraint; + }, + + /** + * This method is an alias for `Factory.pointerConstraint`. + * + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * + * @method Phaser.Physics.Matter.Factory#mouseSpring + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + mouseSpring: function (options) + { + return this.pointerConstraint(options); + }, + + /** + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * + * @method Phaser.Physics.Matter.Factory#pointerConstraint + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation. + * + * @return {MatterJS.ConstraintType} A Matter JS Constraint. + */ + pointerConstraint: function (options) + { + if (options === undefined) { options = {}; } + + if (!options.hasOwnProperty('render')) + { + options.render = { visible: false }; + } + + var pointerConstraint = new PointerConstraint(this.scene, this.world, options); + + this.world.add(pointerConstraint.constraint); + + return pointerConstraint; + }, + + /** + * Creates a Matter Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @method Phaser.Physics.Matter.Factory#image + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.Physics.Matter.Image} The Matter Image Game Object. + */ + image: function (x, y, key, frame, options) + { + var image = new MatterImage(this.world, x, y, key, frame, options); + + this.sys.displayList.add(image); + + return image; + }, + + /** + * Creates a wrapper around a Tile that provides access to a corresponding Matter body. A tile can only + * have one Matter body associated with it. You can either pass in an existing Matter body for + * the tile or allow the constructor to create the corresponding body for you. If the Tile has a + * collision group (defined in Tiled), those shapes will be used to create the body. If not, the + * tile's rectangle bounding box will be used. + * + * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. + * + * Note: not all Tiled collision shapes are supported. See + * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. + * + * @method Phaser.Physics.Matter.Factory#tileBody + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The target tile that should have a Matter body. + * @param {Phaser.Types.Physics.Matter.MatterTileOptions} [options] - Options to be used when creating the Matter body. + * + * @return {Phaser.Physics.Matter.TileBody} The Matter Tile Body Game Object. + */ + tileBody: function (tile, options) + { + return new MatterTileBody(this.world, tile, options); + }, + + /** + * Creates a Matter Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @method Phaser.Physics.Matter.Factory#sprite + * @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} key - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.Physics.Matter.Sprite} The Matter Sprite Game Object. + */ + sprite: function (x, y, key, frame, options) + { + var sprite = new MatterSprite(this.world, x, y, key, frame, options); + + this.sys.displayList.add(sprite); + this.sys.updateList.add(sprite); + + return sprite; + }, + + /** + * Takes an existing Game Object and injects all of the Matter Components into it. + * + * This enables you to use component methods such as `setVelocity` or `isSensor` directly from + * this Game Object. + * + * You can also pass in either a Matter Body Configuration object, or a Matter Body instance + * to link with this Game Object. + * + * @method Phaser.Physics.Matter.Factory#gameObject + * @since 3.3.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to inject the Matter Components in to. + * @param {(Phaser.Types.Physics.Matter.MatterBodyConfig|MatterJS.Body)} [options] - A Matter Body configuration object, or an instance of a Matter Body. + * @param {boolean} [addToWorld=true] - Add this Matter Body to the World? + * + * @return {Phaser.GameObjects.GameObject} The Game Object that had the Matter Components injected into it. + */ + gameObject: function (gameObject, options, addToWorld) + { + return MatterGameObject(this.world, gameObject, options, addToWorld); + }, + + /** + * Destroys this Factory. + * + * @method Phaser.Physics.Matter.Factory#destroy + * @since 3.5.0 + */ + destroy: function () + { + this.world = null; + this.scene = null; + this.sys = null; + } + +}); + +module.exports = Factory; diff --git a/src/physics/matter-js/MatterGameObject.js b/src/physics/matter-js/MatterGameObject.js index a5726cb24..6ff4e3fcd 100644 --- a/src/physics/matter-js/MatterGameObject.js +++ b/src/physics/matter-js/MatterGameObject.js @@ -1,120 +1,120 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Components = require('./components'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Vector2 = require('../../math/Vector2'); - -/** - * Internal function to check if the object has a getter or setter. - * - * @function hasGetterOrSetter - * @private - * - * @param {object} def - The object to check. - * - * @return {boolean} True if it has a getter or setter, otherwise false. - */ -function hasGetterOrSetter (def) -{ - return (!!def.get && typeof def.get === 'function') || (!!def.set && typeof def.set === 'function'); -} - -/** - * A Matter Game Object is a generic object that allows you to combine any Phaser Game Object, - * including those you have extended or created yourself, with all of the Matter Components. - * - * This enables you to use component methods such as `setVelocity` or `isSensor` directly from - * this Game Object. - * - * @function Phaser.Physics.Matter.MatterGameObject - * @since 3.3.0 - * - * @param {Phaser.Physics.Matter.World} world - The Matter world to add the body to. - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will have the Matter body applied to it. - * @param {(Phaser.Types.Physics.Matter.MatterBodyConfig|MatterJS.Body)} [options] - A Matter Body configuration object, or an instance of a Matter Body. - * @param {boolean} [addToWorld=true] - Should the newly created body be immediately added to the World? - * - * @return {Phaser.GameObjects.GameObject} The Game Object that was created with the Matter body. - */ -var MatterGameObject = function (world, gameObject, options, addToWorld) -{ - if (options === undefined) { options = {}; } - if (addToWorld === undefined) { addToWorld = true; } - - var x = gameObject.x; - var y = gameObject.y; - - // Temp body pos to avoid body null checks - gameObject.body = { - temp: true, - position: { - x: x, - y: y - } - }; - - var mixins = [ - Components.Bounce, - Components.Collision, - Components.Force, - Components.Friction, - Components.Gravity, - Components.Mass, - Components.Sensor, - Components.SetBody, - Components.Sleep, - Components.Static, - Components.Transform, - Components.Velocity - ]; - - // First let's inject all of the components into the Game Object - mixins.forEach(function (mixin) - { - for (var key in mixin) - { - if (hasGetterOrSetter(mixin[key])) - { - Object.defineProperty(gameObject, key, { - get: mixin[key].get, - set: mixin[key].set - }); - } - else - { - Object.defineProperty(gameObject, key, {value: mixin[key]}); - } - } - - }); - - gameObject.world = world; - - gameObject._tempVec2 = new Vector2(x, y); - - if (options.hasOwnProperty('type') && options.type === 'body') - { - gameObject.setExistingBody(options, addToWorld); - } - else - { - var shape = GetFastValue(options, 'shape', null); - - if (!shape) - { - shape = 'rectangle'; - } - - options.addToWorld = addToWorld; - - gameObject.setBody(shape, options); - } - - return gameObject; -}; - -module.exports = MatterGameObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Components = require('./components'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Vector2 = require('../../math/Vector2'); + +/** + * Internal function to check if the object has a getter or setter. + * + * @function hasGetterOrSetter + * @private + * + * @param {object} def - The object to check. + * + * @return {boolean} True if it has a getter or setter, otherwise false. + */ +function hasGetterOrSetter (def) +{ + return (!!def.get && typeof def.get === 'function') || (!!def.set && typeof def.set === 'function'); +} + +/** + * A Matter Game Object is a generic object that allows you to combine any Phaser Game Object, + * including those you have extended or created yourself, with all of the Matter Components. + * + * This enables you to use component methods such as `setVelocity` or `isSensor` directly from + * this Game Object. + * + * @function Phaser.Physics.Matter.MatterGameObject + * @since 3.3.0 + * + * @param {Phaser.Physics.Matter.World} world - The Matter world to add the body to. + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will have the Matter body applied to it. + * @param {(Phaser.Types.Physics.Matter.MatterBodyConfig|MatterJS.Body)} [options] - A Matter Body configuration object, or an instance of a Matter Body. + * @param {boolean} [addToWorld=true] - Should the newly created body be immediately added to the World? + * + * @return {Phaser.GameObjects.GameObject} The Game Object that was created with the Matter body. + */ +var MatterGameObject = function (world, gameObject, options, addToWorld) +{ + if (options === undefined) { options = {}; } + if (addToWorld === undefined) { addToWorld = true; } + + var x = gameObject.x; + var y = gameObject.y; + + // Temp body pos to avoid body null checks + gameObject.body = { + temp: true, + position: { + x: x, + y: y + } + }; + + var mixins = [ + Components.Bounce, + Components.Collision, + Components.Force, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.SetBody, + Components.Sleep, + Components.Static, + Components.Transform, + Components.Velocity + ]; + + // First let's inject all of the components into the Game Object + mixins.forEach(function (mixin) + { + for (var key in mixin) + { + if (hasGetterOrSetter(mixin[key])) + { + Object.defineProperty(gameObject, key, { + get: mixin[key].get, + set: mixin[key].set + }); + } + else + { + Object.defineProperty(gameObject, key, {value: mixin[key]}); + } + } + + }); + + gameObject.world = world; + + gameObject._tempVec2 = new Vector2(x, y); + + if (options.hasOwnProperty('type') && options.type === 'body') + { + gameObject.setExistingBody(options, addToWorld); + } + else + { + var shape = GetFastValue(options, 'shape', null); + + if (!shape) + { + shape = 'rectangle'; + } + + options.addToWorld = addToWorld; + + gameObject.setBody(shape, options); + } + + return gameObject; +}; + +module.exports = MatterGameObject; diff --git a/src/physics/matter-js/MatterImage.js b/src/physics/matter-js/MatterImage.js index 0184cae22..e3c89b81c 100644 --- a/src/physics/matter-js/MatterImage.js +++ b/src/physics/matter-js/MatterImage.js @@ -1,130 +1,130 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('./components'); -var GameObject = require('../../gameobjects/GameObject'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Image = require('../../gameobjects/image/Image'); -var Pipeline = require('../../gameobjects/components/Pipeline'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Matter Physics Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * - * @class Image - * @extends Phaser.GameObjects.Image - * @memberof Phaser.Physics.Matter - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Matter.Components.Bounce - * @extends Phaser.Physics.Matter.Components.Collision - * @extends Phaser.Physics.Matter.Components.Force - * @extends Phaser.Physics.Matter.Components.Friction - * @extends Phaser.Physics.Matter.Components.Gravity - * @extends Phaser.Physics.Matter.Components.Mass - * @extends Phaser.Physics.Matter.Components.Sensor - * @extends Phaser.Physics.Matter.Components.SetBody - * @extends Phaser.Physics.Matter.Components.Sleep - * @extends Phaser.Physics.Matter.Components.Static - * @extends Phaser.Physics.Matter.Components.Transform - * @extends Phaser.Physics.Matter.Components.Velocity - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Tint - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Physics.Matter.World} world - A reference to the Matter.World instance that this body belongs to. - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - */ -var MatterImage = new Class({ - - Extends: Image, - - Mixins: [ - Components.Bounce, - Components.Collision, - Components.Force, - Components.Friction, - Components.Gravity, - Components.Mass, - Components.Sensor, - Components.SetBody, - Components.Sleep, - Components.Static, - Components.Transform, - Components.Velocity, - Pipeline - ], - - initialize: - - function MatterImage (world, x, y, texture, frame, options) - { - GameObject.call(this, world.scene, 'Image'); - - this.setTexture(texture, frame); - this.setSizeToFrame(); - this.setOrigin(); - - /** - * A reference to the Matter.World instance that this body belongs to. - * - * @name Phaser.Physics.Matter.Image#world - * @type {Phaser.Physics.Matter.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * An internal temp vector used for velocity and force calculations. - * - * @name Phaser.Physics.Matter.Image#_tempVec2 - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tempVec2 = new Vector2(x, y); - - var shape = GetFastValue(options, 'shape', null); - - if (shape) - { - this.setBody(shape, options); - } - else - { - this.setRectangle(this.width, this.height, options); - } - - this.setPosition(x, y); - - this.initPipeline('TextureTintPipeline'); - } - -}); - -module.exports = MatterImage; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('./components'); +var GameObject = require('../../gameobjects/GameObject'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Image = require('../../gameobjects/image/Image'); +var Pipeline = require('../../gameobjects/components/Pipeline'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Matter Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * + * @class Image + * @extends Phaser.GameObjects.Image + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Matter.Components.Bounce + * @extends Phaser.Physics.Matter.Components.Collision + * @extends Phaser.Physics.Matter.Components.Force + * @extends Phaser.Physics.Matter.Components.Friction + * @extends Phaser.Physics.Matter.Components.Gravity + * @extends Phaser.Physics.Matter.Components.Mass + * @extends Phaser.Physics.Matter.Components.Sensor + * @extends Phaser.Physics.Matter.Components.SetBody + * @extends Phaser.Physics.Matter.Components.Sleep + * @extends Phaser.Physics.Matter.Components.Static + * @extends Phaser.Physics.Matter.Components.Transform + * @extends Phaser.Physics.Matter.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Matter.World} world - A reference to the Matter.World instance that this body belongs to. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + */ +var MatterImage = new Class({ + + Extends: Image, + + Mixins: [ + Components.Bounce, + Components.Collision, + Components.Force, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.SetBody, + Components.Sleep, + Components.Static, + Components.Transform, + Components.Velocity, + Pipeline + ], + + initialize: + + function MatterImage (world, x, y, texture, frame, options) + { + GameObject.call(this, world.scene, 'Image'); + + this.setTexture(texture, frame); + this.setSizeToFrame(); + this.setOrigin(); + + /** + * A reference to the Matter.World instance that this body belongs to. + * + * @name Phaser.Physics.Matter.Image#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * An internal temp vector used for velocity and force calculations. + * + * @name Phaser.Physics.Matter.Image#_tempVec2 + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tempVec2 = new Vector2(x, y); + + var shape = GetFastValue(options, 'shape', null); + + if (shape) + { + this.setBody(shape, options); + } + else + { + this.setRectangle(this.width, this.height, options); + } + + this.setPosition(x, y); + + this.initPipeline('TextureTintPipeline'); + } + +}); + +module.exports = MatterImage; diff --git a/src/physics/matter-js/MatterPhysics.js b/src/physics/matter-js/MatterPhysics.js index a93444404..77488eb23 100644 --- a/src/physics/matter-js/MatterPhysics.js +++ b/src/physics/matter-js/MatterPhysics.js @@ -1,1463 +1,1463 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ALIGN_CONST = require('../../display/align/const'); -var Axes = require('./lib/geometry/Axes'); -var Bodies = require('./lib/factory/Bodies'); -var Body = require('./lib/body/Body'); -var BodyBounds = require('./BodyBounds'); -var Bounds = require('./lib/geometry/Bounds'); -var Class = require('../../utils/Class'); -var Composite = require('./lib/body/Composite'); -var Composites = require('./lib/factory/Composites'); -var Constraint = require('./lib/constraint/Constraint'); -var Detector = require('./lib/collision/Detector'); -var DistanceBetween = require('../../math/distance/DistanceBetween'); -var Factory = require('./Factory'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetValue = require('../../utils/object/GetValue'); -var Grid = require('./lib/collision/Grid'); -var MatterAttractors = require('./lib/plugins/MatterAttractors'); -var MatterCollisionEvents = require('./lib/plugins/MatterCollisionEvents'); -var MatterLib = require('./lib/core/Matter'); -var MatterWrap = require('./lib/plugins/MatterWrap'); -var Merge = require('../../utils/object/Merge'); -var Pair = require('./lib/collision/Pair'); -var Pairs = require('./lib/collision/Pairs'); -var Plugin = require('./lib/core/Plugin'); -var PluginCache = require('../../plugins/PluginCache'); -var Query = require('./lib/collision/Query'); -var Resolver = require('./lib/collision/Resolver'); -var SAT = require('./lib/collision/SAT'); -var SceneEvents = require('../../scene/events'); -var Svg = require('./lib/geometry/Svg'); -var Vector = require('./lib/geometry/Vector'); -var Vertices = require('./lib/geometry/Vertices'); -var World = require('./World'); - -/** - * @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. - */ -var MatterPhysics = new Class({ - - initialize: - - function MatterPhysics (scene) - { - /** - * The Phaser Scene that owns this Matter Physics instance - * - * @name Phaser.Physics.Matter.MatterPhysics#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Scene Systems that belong to the Scene owning this Matter Physics instance. - * - * @name Phaser.Physics.Matter.MatterPhysics#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * The parsed Matter Configuration object. - * - * @name Phaser.Physics.Matter.MatterPhysics#config - * @type {Phaser.Types.Physics.Matter.MatterWorldConfig} - * @since 3.0.0 - */ - this.config = this.getConfig(); - - /** - * An instance of the Matter World class. This class is responsible for the updating of the - * Matter Physics world, as well as handling debug drawing functions. - * - * @name Phaser.Physics.Matter.MatterPhysics#world - * @type {Phaser.Physics.Matter.World} - * @since 3.0.0 - */ - this.world; - - /** - * An instance of the Matter Factory. This class provides lots of functions for creating a - * wide variety of physics objects and adds them automatically to the Matter World. - * - * You can use this class to cut-down on the amount of code required in your game, however, - * use of the Factory is entirely optional and should be seen as a development aid. It's - * perfectly possible to create and add components to the Matter world without using it. - * - * @name Phaser.Physics.Matter.MatterPhysics#add - * @type {Phaser.Physics.Matter.Factory} - * @since 3.0.0 - */ - this.add; - - /** - * An instance of the Body Bounds class. This class contains functions used for getting the - * world position from various points around the bounds of a physics body. - * - * @name Phaser.Physics.Matter.MatterPhysics#bodyBounds - * @type {Phaser.Physics.Matter.BodyBounds} - * @since 3.22.0 - */ - this.bodyBounds; - - // Body - - /** - * A reference to the `Matter.Body` module. - * - * 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 `Bodies` module. - * - * @name Phaser.Physics.Matter.MatterPhysics#body - * @type {MatterJS.BodyFactory} - * @since 3.18.0 - */ - this.body = Body; - - /** - * A reference to the `Matter.Composite` module. - * - * 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`. - * - * @name Phaser.Physics.Matter.MatterPhysics#composite - * @type {MatterJS.CompositeFactory} - * @since 3.22.0 - */ - this.composite = Composite; - - // Collision: - - /** - * A reference to the `Matter.Detector` module. - * - * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. - * - * @name Phaser.Physics.Matter.MatterPhysics#detector - * @type {MatterJS.DetectorFactory} - * @since 3.22.0 - */ - this.detector = Detector; - - /** - * A reference to the `Matter.Grid` module. - * - * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. - * - * @name Phaser.Physics.Matter.MatterPhysics#grid - * @type {MatterJS.GridFactory} - * @since 3.22.0 - */ - this.grid = Grid; - - /** - * A reference to the `Matter.Pair` module. - * - * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. - * - * @name Phaser.Physics.Matter.MatterPhysics#pair - * @type {MatterJS.PairFactory} - * @since 3.22.0 - */ - this.pair = Pair; - - /** - * A reference to the `Matter.Pairs` module. - * - * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. - * - * @name Phaser.Physics.Matter.MatterPhysics#pairs - * @type {MatterJS.PairsFactory} - * @since 3.22.0 - */ - this.pairs = Pairs; - - /** - * A reference to the `Matter.Query` module. - * - * The `Matter.Query` module contains methods for performing collision queries. - * - * @name Phaser.Physics.Matter.MatterPhysics#query - * @type {MatterJS.QueryFactory} - * @since 3.22.0 - */ - this.query = Query; - - /** - * A reference to the `Matter.Resolver` module. - * - * The `Matter.Resolver` module contains methods for resolving collision pairs. - * - * @name Phaser.Physics.Matter.MatterPhysics#resolver - * @type {MatterJS.ResolverFactory} - * @since 3.22.0 - */ - this.resolver = Resolver; - - /** - * A reference to the `Matter.SAT` module. - * - * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. - * - * @name Phaser.Physics.Matter.MatterPhysics#sat - * @type {MatterJS.SATFactory} - * @since 3.22.0 - */ - this.sat = SAT; - - // Constraint - - /** - * A reference to the `Matter.Constraint` module. - * - * 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. - * - * @name Phaser.Physics.Matter.MatterPhysics#constraint - * @type {MatterJS.ConstraintFactory} - * @since 3.22.0 - */ - this.constraint = Constraint; - - // Factory - - /** - * A reference to the `Matter.Bodies` module. - * - * The `Matter.Bodies` module contains factory methods for creating rigid bodies - * with commonly used body configurations (such as rectangles, circles and other polygons). - * - * @name Phaser.Physics.Matter.MatterPhysics#bodies - * @type {MatterJS.BodiesFactory} - * @since 3.18.0 - */ - this.bodies = Bodies; - - /** - * A reference to the `Matter.Composites` module. - * - * The `Matter.Composites` module contains factory methods for creating composite bodies - * with commonly used configurations (such as stacks and chains). - * - * @name Phaser.Physics.Matter.MatterPhysics#composites - * @type {MatterJS.CompositesFactory} - * @since 3.22.0 - */ - this.composites = Composites; - - // Geometry - - /** - * A reference to the `Matter.Axes` module. - * - * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. - * - * @name Phaser.Physics.Matter.MatterPhysics#axes - * @type {MatterJS.AxesFactory} - * @since 3.22.0 - */ - this.axes = Axes; - - /** - * A reference to the `Matter.Bounds` module. - * - * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). - * - * @name Phaser.Physics.Matter.MatterPhysics#bounds - * @type {MatterJS.BoundsFactory} - * @since 3.22.0 - */ - this.bounds = Bounds; - - /** - * 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 - */ - this.svg = Svg; - - /** - * A reference to the `Matter.Vector` module. - * - * 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 }`. - * - * @name Phaser.Physics.Matter.MatterPhysics#vector - * @type {MatterJS.VectorFactory} - * @since 3.22.0 - */ - this.vector = Vector; - - /** - * A reference to the `Matter.Vertices` module. - * - * 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). - * - * @name Phaser.Physics.Matter.MatterPhysics#vertices - * @type {MatterJS.VerticesFactory} - * @since 3.22.0 - */ - this.vertices = Vertices; - - /** - * A reference to the `Matter.Vertices` module. - * - * 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). - * - * @name Phaser.Physics.Matter.MatterPhysics#verts - * @type {MatterJS.VerticesFactory} - * @since 3.14.0 - */ - this.verts = Vertices; - - /** - * An internal temp vector used for velocity and force calculations. - * - * @name Phaser.Physics.Matter.MatterPhysics#_tempVec2 - * @type {MatterJS.Vector} - * @private - * @since 3.22.0 - */ - this._tempVec2 = Vector.create(); - - // Matter plugins - - if (GetValue(this.config, 'plugins.collisionevents', true)) - { - this.enableCollisionEventsPlugin(); - } - - if (GetValue(this.config, 'plugins.attractors', false)) - { - this.enableAttractorPlugin(); - } - - if (GetValue(this.config, 'plugins.wrap', false)) - { - this.enableWrapPlugin(); - } - - Resolver._restingThresh = GetValue(this.config, 'restingThresh', 4); - Resolver._restingThreshTangent = GetValue(this.config, 'restingThreshTangent', 6); - Resolver._positionDampen = GetValue(this.config, 'positionDampen', 0.9); - Resolver._positionWarming = GetValue(this.config, 'positionWarming', 0.8); - Resolver._frictionNormalMultiplier = GetValue(this.config, 'frictionNormalMultiplier', 5); - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Physics.Matter.MatterPhysics#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.world = new World(this.scene, this.config); - this.add = new Factory(this.world); - this.bodyBounds = new BodyBounds(); - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Physics.Matter.MatterPhysics#start - * @private - * @since 3.5.0 - */ - start: function () - { - if (!this.world) - { - this.world = new World(this.scene, this.config); - this.add = new Factory(this.world); - } - - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); - eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * This internal method is called when this class starts and retrieves the final Matter World Config. - * - * @method Phaser.Physics.Matter.MatterPhysics#getConfig - * @since 3.0.0 - * - * @return {Phaser.Types.Physics.Matter.MatterWorldConfig} The Matter World Config. - */ - getConfig: function () - { - var gameConfig = this.systems.game.config.physics; - var sceneConfig = this.systems.settings.physics; - - var config = Merge( - GetFastValue(sceneConfig, 'matter', {}), - GetFastValue(gameConfig, 'matter', {}) - ); - - return config; - }, - - /** - * Enables the Matter Attractors Plugin. - * - * The attractors plugin that makes it easy to apply continual forces on bodies. - * It's possible to simulate effects such as wind, gravity and magnetism. - * - * https://github.com/liabru/matter-attractors - * - * This method is called automatically if `plugins.attractors` is set in the Matter World Config. - * However, you can also call it directly from within your game. - * - * @method Phaser.Physics.Matter.MatterPhysics#enableAttractorPlugin - * @since 3.0.0 - * - * @return {this} This Matter Physics instance. - */ - enableAttractorPlugin: function () - { - Plugin.register(MatterAttractors); - Plugin.use(MatterLib, MatterAttractors); - - return this; - }, - - /** - * Enables the Matter Wrap Plugin. - * - * The coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay - * within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, - * while maintaining its velocity. - * - * https://github.com/liabru/matter-wrap - * - * This method is called automatically if `plugins.wrap` is set in the Matter World Config. - * However, you can also call it directly from within your game. - * - * @method Phaser.Physics.Matter.MatterPhysics#enableWrapPlugin - * @since 3.0.0 - * - * @return {this} This Matter Physics instance. - */ - enableWrapPlugin: function () - { - Plugin.register(MatterWrap); - Plugin.use(MatterLib, MatterWrap); - - return this; - }, - - /** - * Enables the Matter Collision Events Plugin. - * - * Note that this plugin is enabled by default. So you should only ever need to call this - * method if you have specifically disabled the plugin in your Matter World Config. - * You can disable it by setting `plugins.collisionevents: false` in your Matter World Config. - * - * This plugin triggers three new events on Matter.Body: - * - * 1. `onCollide` - * 2. `onCollideEnd` - * 3. `onCollideActive` - * - * These events correspond to the Matter.js events `collisionStart`, `collisionActive` and `collisionEnd`, respectively. - * You can listen to these events via Matter.Events or they will also be emitted from the Matter World. - * - * This plugin also extends Matter.Body with three convenience functions: - * - * `Matter.Body.setOnCollide(callback)` - * `Matter.Body.setOnCollideEnd(callback)` - * `Matter.Body.setOnCollideActive(callback)` - * - * You can register event callbacks by providing a function of type (pair: Matter.Pair) => void - * - * https://github.com/dxu/matter-collision-events - * - * @method Phaser.Physics.Matter.MatterPhysics#enableCollisionEventsPlugin - * @since 3.22.0 - * - * @return {this} This Matter Physics instance. - */ - enableCollisionEventsPlugin: function () - { - Plugin.register(MatterCollisionEvents); - Plugin.use(MatterLib, MatterCollisionEvents); - - return this; - }, - - /** - * Pauses the Matter World instance and sets `enabled` to `false`. - * - * A paused world will not run any simulations for the duration it is paused. - * - * @method Phaser.Physics.Matter.MatterPhysics#pause - * @fires Phaser.Physics.Matter.Events#PAUSE - * @since 3.0.0 - * - * @return {Phaser.Physics.Matter.World} The Matter World object. - */ - pause: function () - { - return this.world.pause(); - }, - - /** - * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. - * - * @method Phaser.Physics.Matter.MatterPhysics#resume - * @since 3.0.0 - * - * @return {Phaser.Physics.Matter.World} The Matter World object. - */ - resume: function () - { - return this.world.resume(); - }, - - /** - * Sets the Matter Engine to run at fixed timestep of 60Hz and enables `autoUpdate`. - * If you have set a custom `getDelta` function then this will override it. - * - * @method Phaser.Physics.Matter.MatterPhysics#set60Hz - * @since 3.4.0 - * - * @return {this} This Matter Physics instance. - */ - set60Hz: function () - { - this.world.getDelta = this.world.update60Hz; - this.world.autoUpdate = true; - - return this; - }, - - /** - * Sets the Matter Engine to run at fixed timestep of 30Hz and enables `autoUpdate`. - * If you have set a custom `getDelta` function then this will override it. - * - * @method Phaser.Physics.Matter.MatterPhysics#set30Hz - * @since 3.4.0 - * - * @return {this} This Matter Physics instance. - */ - set30Hz: function () - { - this.world.getDelta = this.world.update30Hz; - this.world.autoUpdate = true; - - return this; - }, - - /** - * Manually advances the physics simulation by one iteration. - * - * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. - * If undefined they use the Matter defaults of 60Hz and no correction. - * - * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. - * - * It also ignores any custom `getDelta` functions, as you should be passing the delta - * value in to this call. - * - * You can adjust the number of iterations that Engine.update performs internally. - * Use the Scene Matter Physics config object to set the following properties: - * - * positionIterations (defaults to 6) - * velocityIterations (defaults to 4) - * constraintIterations (defaults to 2) - * - * Adjusting these values can help performance in certain situations, depending on the physics requirements - * of your game. - * - * @method Phaser.Physics.Matter.MatterPhysics#step - * @since 3.4.0 - * - * @param {number} [delta=16.666] - The delta value. - * @param {number} [correction=1] - Optional delta correction value. - */ - step: function (delta, correction) - { - this.world.step(delta, correction); - }, - - /** - * Checks if the vertices of the given body, or an array of bodies, contains the given point, or not. - * - * You can pass in either a single body, or an array of bodies to be checked. This method will - * return `true` if _any_ of the bodies in the array contain the point. See the `intersectPoint` method if you need - * to get a list of intersecting bodies. - * - * The point should be transformed into the Matter World coordinate system in advance. This happens by - * default with Input Pointers, but if you wish to use points from another system you may need to - * transform them before passing them. - * - * @method Phaser.Physics.Matter.MatterPhysics#containsPoint - * @since 3.22.0 - * - * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} body - The body, or an array of bodies, to check against the point. - * @param {number} x - The horizontal coordinate of the point. - * @param {number} y - The vertical coordinate of the point. - * - * @return {boolean} `true` if the point is within one of the bodies given, otherwise `false`. - */ - containsPoint: function (body, x, y) - { - body = this.getMatterBodies(body); - - var position = Vector.create(x, y); - - var result = Query.point(body, position); - - return (result.length > 0) ? true : false; - }, - - /** - * Checks the given coordinates to see if any vertices of the given bodies contain it. - * - * If no bodies are provided it will search all bodies in the Matter World, including within Composites. - * - * The coordinates should be transformed into the Matter World coordinate system in advance. This happens by - * default with Input Pointers, but if you wish to use coordinates from another system you may need to - * transform them before passing them. - * - * @method Phaser.Physics.Matter.MatterPhysics#intersectPoint - * @since 3.22.0 - * - * @param {number} x - The horizontal coordinate of the point. - * @param {number} y - The vertical coordinate of the point. - * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. - * - * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies which contain the given point. - */ - intersectPoint: function (x, y, bodies) - { - bodies = this.getMatterBodies(bodies); - - var position = Vector.create(x, y); - - var output = []; - - var result = Query.point(bodies, position); - - result.forEach(function (body) - { - if (output.indexOf(body) === -1) - { - output.push(body); - } - }); - - return output; - }, - - /** - * Checks the given rectangular area to see if any vertices of the given bodies intersect with it. - * Or, if the `outside` parameter is set to `true`, it checks to see which bodies do not - * intersect with it. - * - * If no bodies are provided it will search all bodies in the Matter World, including within Composites. - * - * @method Phaser.Physics.Matter.MatterPhysics#intersectRect - * @since 3.22.0 - * - * @param {number} x - The horizontal coordinate of the top-left of the area. - * @param {number} y - The vertical coordinate of the top-left of the area. - * @param {number} width - The width of the area. - * @param {number} height - The height of the area. - * @param {boolean} [outside=false] - If `false` it checks for vertices inside the area, if `true` it checks for vertices outside the area. - * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. - * - * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies that intersect with the given area. - */ - intersectRect: function (x, y, width, height, outside, bodies) - { - if (outside === undefined) { outside = false; } - - bodies = this.getMatterBodies(bodies); - - var bounds = { - min: { x: x, y: y }, - max: { x: x + width, y: y + height } - }; - - var output = []; - - var result = Query.region(bodies, bounds, outside); - - result.forEach(function (body) - { - if (output.indexOf(body) === -1) - { - output.push(body); - } - }); - - return output; - }, - - /** - * Checks the given ray segment to see if any vertices of the given bodies intersect with it. - * - * If no bodies are provided it will search all bodies in the Matter World. - * - * The width of the ray can be specified via the `rayWidth` parameter. - * - * @method Phaser.Physics.Matter.MatterPhysics#intersectRay - * @since 3.22.0 - * - * @param {number} x1 - The horizontal coordinate of the start of the ray segment. - * @param {number} y1 - The vertical coordinate of the start of the ray segment. - * @param {number} x2 - The horizontal coordinate of the end of the ray segment. - * @param {number} y2 - The vertical coordinate of the end of the ray segment. - * @param {number} [rayWidth=1] - The width of the ray segment. - * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. - * - * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with the ray segment. - */ - intersectRay: function (x1, y1, x2, y2, rayWidth, bodies) - { - if (rayWidth === undefined) { rayWidth = 1; } - - bodies = this.getMatterBodies(bodies); - - var result = []; - var collisions = Query.ray(bodies, Vector.create(x1, y1), Vector.create(x2, y2), rayWidth); - - for (var i = 0; i < collisions.length; i++) - { - result.push(collisions[i].body); - } - - return result; - }, - - /** - * Checks the given Matter Body to see if it intersects with any of the given bodies. - * - * If no bodies are provided it will check against all bodies in the Matter World. - * - * @method Phaser.Physics.Matter.MatterPhysics#intersectBody - * @since 3.22.0 - * - * @param {Phaser.Types.Physics.Matter.MatterBody} body - The target body. - * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check the target body against. If not provided it will search all bodies in the world. - * - * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with target body. - */ - intersectBody: function (body, bodies) - { - bodies = this.getMatterBodies(bodies); - - var result = []; - var collisions = Query.collides(body, bodies); - - for (var i = 0; i < collisions.length; i++) - { - var pair = collisions[i]; - - if (pair.bodyA === body) - { - result.push(pair.bodyB); - } - else - { - result.push(pair.bodyA); - } - } - - return result; - }, - - /** - * Checks to see if the target body, or an array of target bodies, intersects with any of the given bodies. - * - * If intersection occurs this method will return `true` and, if provided, invoke the callbacks. - * - * If no bodies are provided for the second parameter the target will check again all bodies in the Matter World. - * - * Note that bodies can only overlap if they are in non-colliding collision groups or categories. - * - * If you provide a `processCallback` then the two bodies that overlap are sent to it. This callback - * must return a boolean and is used to allow you to perform additional processing tests before a final - * outcome is decided. If it returns `true` then the bodies are finally passed to the `overlapCallback`, if set. - * - * If you provide an `overlapCallback` then the matching pairs of overlapping bodies will be sent to it. - * - * Both callbacks have the following signature: `function (bodyA, bodyB, collisionInfo)` where `bodyA` is always - * the target body. The `collisionInfo` object contains additional data, such as the angle and depth of penetration. - * - * @method Phaser.Physics.Matter.MatterPhysics#overlap - * @since 3.22.0 - * - * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} target - The target body, or array of target bodies, to check. - * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - The second body, or array of bodies, to check. If falsey it will check against all bodies in the world. - * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the bodies overlap. - * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two bodies if they overlap. If this is set then `overlapCallback` will only be invoked if this callback returns `true`. - * @param {*} [callbackContext] - The context, or scope, in which to run the callbacks. - * - * @return {boolean} `true` if the target body intersects with _any_ of the bodies given, otherwise `false`. - */ - overlap: function (target, bodies, overlapCallback, processCallback, callbackContext) - { - if (overlapCallback === undefined) { overlapCallback = null; } - if (processCallback === undefined) { processCallback = null; } - if (callbackContext === undefined) { callbackContext = overlapCallback; } - - if (!Array.isArray(target)) - { - target = [ target ]; - } - - target = this.getMatterBodies(target); - bodies = this.getMatterBodies(bodies); - - var match = false; - - for (var i = 0; i < target.length; i++) - { - var entry = target[i]; - - var collisions = Query.collides(entry, bodies); - - for (var c = 0; c < collisions.length; c++) - { - var info = collisions[c]; - var bodyB = (info.bodyA.id === entry.id) ? info.bodyB : info.bodyA; - - if (!processCallback || processCallback.call(callbackContext, entry, bodyB, info)) - { - match = true; - - if (overlapCallback) - { - overlapCallback.call(callbackContext, entry, bodyB, info); - } - else if (!processCallback) - { - // If there are no callbacks we don't need to test every body, just exit when the first is found - return true; - } - } - } - } - - return match; - }, - - /** - * Sets the collision filter category of all given Matter Bodies to the given value. - * - * This number must be a power of two between 2^0 (= 1) and 2^31. - * - * Bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * - * @method Phaser.Physics.Matter.MatterPhysics#setCollisionCategory - * @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} value - Unique category bitfield. - * - * @return {this} This Matter Physics instance. - */ - setCollisionCategory: function (bodies, value) - { - bodies = this.getMatterBodies(bodies); - - bodies.forEach(function (body) - { - body.collisionFilter.category = value; - }); - - return this; - }, - - /** - * Sets the collision filter group of all given Matter Bodies to the given value. - * - * If the group value is zero, or if two Matter Bodies have different group values, - * they will collide according to the usual collision filter rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * - * If two Matter Bodies have the same positive group value, they will always collide; - * if they have the same negative group value they will never collide. - * - * @method Phaser.Physics.Matter.MatterPhysics#setCollisionGroup - * @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} value - Unique group index. - * - * @return {this} This Matter Physics instance. - */ - setCollisionGroup: function (bodies, value) - { - bodies = this.getMatterBodies(bodies); - - bodies.forEach(function (body) - { - body.collisionFilter.group = value; - }); - - return this; - }, - - /** - * 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. - */ - setCollidesWith: function (bodies, categories) - { - bodies = this.getMatterBodies(bodies); - - var flags = 0; - - if (!Array.isArray(categories)) - { - flags = categories; - } - else - { - for (var i = 0; i < categories.length; i++) - { - flags |= categories[i]; - } - } - - bodies.forEach(function (body) - { - body.collisionFilter.mask = flags; - }); - - return this; - }, - - /** - * Takes an array and returns a new array made from all of the Matter Bodies found in the original array. - * - * For example, passing in Matter Game Objects, such as a bunch of Matter Sprites, to this method, would - * return an array containing all of their native Matter Body objects. - * - * If the `bodies` argument is falsey, it will return all bodies in the world. - * - * @method Phaser.Physics.Matter.MatterPhysics#getMatterBodies - * @since 3.22.0 - * - * @param {array} [bodies] - An array of objects to extract the bodies from. If falsey, it will return all bodies in the world. - * - * @return {MatterJS.BodyType[]} An array of native Matter Body objects. - */ - getMatterBodies: function (bodies) - { - if (!bodies) - { - return this.world.getAllBodies(); - } - - if (!Array.isArray(bodies)) - { - bodies = [ bodies ]; - } - - var output = []; - - for (var i = 0; i < bodies.length; i++) - { - var body = (bodies[i].hasOwnProperty('body')) ? bodies[i].body : bodies[i]; - - output.push(body); - } - - return output; - }, - - /** - * Sets both the horizontal and vertical linear velocity of the physics bodies. - * - * @method Phaser.Physics.Matter.MatterPhysics#setVelocity - * @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} x - The horizontal linear velocity value. - * @param {number} y - The vertical linear velocity value. - * - * @return {this} This Matter Physics instance. - */ - setVelocity: function (bodies, x, y) - { - bodies = this.getMatterBodies(bodies); - - var vec2 = this._tempVec2; - - vec2.x = x; - vec2.y = y; - - bodies.forEach(function (body) - { - Body.setVelocity(body, vec2); - }); - - return this; - }, - - /** - * Sets just the horizontal linear velocity of the physics bodies. - * The vertical velocity of the body is unchanged. - * - * @method Phaser.Physics.Matter.MatterPhysics#setVelocityX - * @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} x - The horizontal linear velocity value. - * - * @return {this} This Matter Physics instance. - */ - setVelocityX: function (bodies, x) - { - bodies = this.getMatterBodies(bodies); - - var vec2 = this._tempVec2; - - vec2.x = x; - - bodies.forEach(function (body) - { - vec2.y = body.velocity.y; - Body.setVelocity(body, vec2); - }); - - return this; - }, - - /** - * Sets just the vertical linear velocity of the physics bodies. - * The horizontal velocity of the body is unchanged. - * - * @method Phaser.Physics.Matter.MatterPhysics#setVelocityY - * @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} y - The vertical linear velocity value. - * - * @return {this} This Matter Physics instance. - */ - setVelocityY: function (bodies, y) - { - bodies = this.getMatterBodies(bodies); - - var vec2 = this._tempVec2; - - vec2.y = y; - - bodies.forEach(function (body) - { - vec2.x = body.velocity.x; - Body.setVelocity(body, vec2); - }); - - return this; - }, - - /** - * Sets the angular velocity of the bodies instantly. - * Position, angle, force etc. are unchanged. - * - * @method Phaser.Physics.Matter.MatterPhysics#setAngularVelocity - * @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} value - The angular velocity. - * - * @return {this} This Matter Physics instance. - */ - setAngularVelocity: function (bodies, value) - { - bodies = this.getMatterBodies(bodies); - - bodies.forEach(function (body) - { - Body.setAngularVelocity(body, value); - }); - - return this; - }, - - /** - * Applies a force to a body, at the bodies current position, including resulting torque. - * - * @method Phaser.Physics.Matter.MatterPhysics#applyForce - * @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 {Phaser.Types.Math.Vector2Like} force - A Vector that specifies the force to apply. - * - * @return {this} This Matter Physics instance. - */ - applyForce: function (bodies, force) - { - bodies = this.getMatterBodies(bodies); - - var vec2 = this._tempVec2; - - bodies.forEach(function (body) - { - vec2.x = body.position.x; - vec2.y = body.position.y; - - Body.applyForce(body, vec2, force); - }); - - return this; - }, - - /** - * Applies a force to a body, from the given world position, including resulting torque. - * 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#applyForceFromPosition - * @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 {Phaser.Types.Math.Vector2Like} position - A Vector that specifies the world-space position to apply the force at. - * @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. - */ - applyForceFromPosition: function (bodies, position, speed, angle) - { - bodies = this.getMatterBodies(bodies); - - var vec2 = this._tempVec2; - - bodies.forEach(function (body) - { - if (angle === undefined) - { - angle = body.angle; - } - - vec2.x = speed * Math.cos(angle); - vec2.y = speed * Math.sin(angle); - - Body.applyForce(body, position, vec2); - }); - - return this; - }, - - /** - * 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. - */ - applyForceFromAngle: function (bodies, speed, angle) - { - bodies = this.getMatterBodies(bodies); - - var vec2 = this._tempVec2; - - bodies.forEach(function (body) - { - if (angle === undefined) - { - angle = body.angle; - } - - vec2.x = speed * Math.cos(angle); - vec2.y = speed * Math.sin(angle); - - Body.applyForce(body, { x: body.position.x, y: body.position.y }, vec2); - }); - - return this; - }, - - /** - * Returns the length of the given constraint, which is the distance between the two points. - * - * @method Phaser.Physics.Matter.MatterPhysics#getConstraintLength - * @since 3.22.0 - * - * @param {MatterJS.ConstraintType} constraint - The constraint to get the length from. - * - * @return {number} The length of the constraint. - */ - getConstraintLength: function (constraint) - { - var aX = constraint.pointA.x; - var aY = constraint.pointA.y; - var bX = constraint.pointB.x; - var bY = constraint.pointB.y; - - if (constraint.bodyA) - { - aX += constraint.bodyA.position.x; - aY += constraint.bodyA.position.y; - } - - if (constraint.bodyB) - { - bX += constraint.bodyB.position.x; - bY += constraint.bodyB.position.y; - } - - return DistanceBetween(aX, aY, bX, bY); - }, - - /** - * 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 {integer} align - One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`. - * - * @return {this} This Matter Physics instance. - */ - alignBody: function (body, x, y, align) - { - body = (body.hasOwnProperty('body')) ? body.body : body; - - var pos; - - switch (align) - { - case ALIGN_CONST.TOP_LEFT: - case ALIGN_CONST.LEFT_TOP: - pos = this.bodyBounds.getTopLeft(body, x, y); - break; - - case ALIGN_CONST.TOP_CENTER: - pos = this.bodyBounds.getTopCenter(body, x, y); - break; - - case ALIGN_CONST.TOP_RIGHT: - case ALIGN_CONST.RIGHT_TOP: - pos = this.bodyBounds.getTopRight(body, x, y); - break; - - case ALIGN_CONST.LEFT_CENTER: - pos = this.bodyBounds.getLeftCenter(body, x, y); - break; - - case ALIGN_CONST.CENTER: - pos = this.bodyBounds.getCenter(body, x, y); - break; - - case ALIGN_CONST.RIGHT_CENTER: - pos = this.bodyBounds.getRightCenter(body, x, y); - break; - - case ALIGN_CONST.LEFT_BOTTOM: - case ALIGN_CONST.BOTTOM_LEFT: - pos = this.bodyBounds.getBottomLeft(body, x, y); - break; - - case ALIGN_CONST.BOTTOM_CENTER: - pos = this.bodyBounds.getBottomCenter(body, x, y); - break; - - case ALIGN_CONST.BOTTOM_RIGHT: - case ALIGN_CONST.RIGHT_BOTTOM: - pos = this.bodyBounds.getBottomRight(body, x, y); - break; - } - - if (pos) - { - Body.setPosition(body, pos); - } - - return this; - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Physics.Matter.MatterPhysics#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - var eventEmitter = this.systems.events; - - if (this.world) - { - eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); - eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); - } - - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - - if (this.add) - { - this.add.destroy(); - } - - if (this.world) - { - this.world.destroy(); - } - - this.add = null; - this.world = null; - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Physics.Matter.MatterPhysics#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('MatterPhysics', MatterPhysics, 'matterPhysics'); - -module.exports = MatterPhysics; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ALIGN_CONST = require('../../display/align/const'); +var Axes = require('./lib/geometry/Axes'); +var Bodies = require('./lib/factory/Bodies'); +var Body = require('./lib/body/Body'); +var BodyBounds = require('./BodyBounds'); +var Bounds = require('./lib/geometry/Bounds'); +var Class = require('../../utils/Class'); +var Composite = require('./lib/body/Composite'); +var Composites = require('./lib/factory/Composites'); +var Constraint = require('./lib/constraint/Constraint'); +var Detector = require('./lib/collision/Detector'); +var DistanceBetween = require('../../math/distance/DistanceBetween'); +var Factory = require('./Factory'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetValue = require('../../utils/object/GetValue'); +var Grid = require('./lib/collision/Grid'); +var MatterAttractors = require('./lib/plugins/MatterAttractors'); +var MatterCollisionEvents = require('./lib/plugins/MatterCollisionEvents'); +var MatterLib = require('./lib/core/Matter'); +var MatterWrap = require('./lib/plugins/MatterWrap'); +var Merge = require('../../utils/object/Merge'); +var Pair = require('./lib/collision/Pair'); +var Pairs = require('./lib/collision/Pairs'); +var Plugin = require('./lib/core/Plugin'); +var PluginCache = require('../../plugins/PluginCache'); +var Query = require('./lib/collision/Query'); +var Resolver = require('./lib/collision/Resolver'); +var SAT = require('./lib/collision/SAT'); +var SceneEvents = require('../../scene/events'); +var Svg = require('./lib/geometry/Svg'); +var Vector = require('./lib/geometry/Vector'); +var Vertices = require('./lib/geometry/Vertices'); +var World = require('./World'); + +/** + * @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. + */ +var MatterPhysics = new Class({ + + initialize: + + function MatterPhysics (scene) + { + /** + * The Phaser Scene that owns this Matter Physics instance + * + * @name Phaser.Physics.Matter.MatterPhysics#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems that belong to the Scene owning this Matter Physics instance. + * + * @name Phaser.Physics.Matter.MatterPhysics#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The parsed Matter Configuration object. + * + * @name Phaser.Physics.Matter.MatterPhysics#config + * @type {Phaser.Types.Physics.Matter.MatterWorldConfig} + * @since 3.0.0 + */ + this.config = this.getConfig(); + + /** + * An instance of the Matter World class. This class is responsible for the updating of the + * Matter Physics world, as well as handling debug drawing functions. + * + * @name Phaser.Physics.Matter.MatterPhysics#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world; + + /** + * An instance of the Matter Factory. This class provides lots of functions for creating a + * wide variety of physics objects and adds them automatically to the Matter World. + * + * You can use this class to cut-down on the amount of code required in your game, however, + * use of the Factory is entirely optional and should be seen as a development aid. It's + * perfectly possible to create and add components to the Matter world without using it. + * + * @name Phaser.Physics.Matter.MatterPhysics#add + * @type {Phaser.Physics.Matter.Factory} + * @since 3.0.0 + */ + this.add; + + /** + * An instance of the Body Bounds class. This class contains functions used for getting the + * world position from various points around the bounds of a physics body. + * + * @name Phaser.Physics.Matter.MatterPhysics#bodyBounds + * @type {Phaser.Physics.Matter.BodyBounds} + * @since 3.22.0 + */ + this.bodyBounds; + + // Body + + /** + * A reference to the `Matter.Body` module. + * + * 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 `Bodies` module. + * + * @name Phaser.Physics.Matter.MatterPhysics#body + * @type {MatterJS.BodyFactory} + * @since 3.18.0 + */ + this.body = Body; + + /** + * A reference to the `Matter.Composite` module. + * + * 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`. + * + * @name Phaser.Physics.Matter.MatterPhysics#composite + * @type {MatterJS.CompositeFactory} + * @since 3.22.0 + */ + this.composite = Composite; + + // Collision: + + /** + * A reference to the `Matter.Detector` module. + * + * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. + * + * @name Phaser.Physics.Matter.MatterPhysics#detector + * @type {MatterJS.DetectorFactory} + * @since 3.22.0 + */ + this.detector = Detector; + + /** + * A reference to the `Matter.Grid` module. + * + * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. + * + * @name Phaser.Physics.Matter.MatterPhysics#grid + * @type {MatterJS.GridFactory} + * @since 3.22.0 + */ + this.grid = Grid; + + /** + * A reference to the `Matter.Pair` module. + * + * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. + * + * @name Phaser.Physics.Matter.MatterPhysics#pair + * @type {MatterJS.PairFactory} + * @since 3.22.0 + */ + this.pair = Pair; + + /** + * A reference to the `Matter.Pairs` module. + * + * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. + * + * @name Phaser.Physics.Matter.MatterPhysics#pairs + * @type {MatterJS.PairsFactory} + * @since 3.22.0 + */ + this.pairs = Pairs; + + /** + * A reference to the `Matter.Query` module. + * + * The `Matter.Query` module contains methods for performing collision queries. + * + * @name Phaser.Physics.Matter.MatterPhysics#query + * @type {MatterJS.QueryFactory} + * @since 3.22.0 + */ + this.query = Query; + + /** + * A reference to the `Matter.Resolver` module. + * + * The `Matter.Resolver` module contains methods for resolving collision pairs. + * + * @name Phaser.Physics.Matter.MatterPhysics#resolver + * @type {MatterJS.ResolverFactory} + * @since 3.22.0 + */ + this.resolver = Resolver; + + /** + * A reference to the `Matter.SAT` module. + * + * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. + * + * @name Phaser.Physics.Matter.MatterPhysics#sat + * @type {MatterJS.SATFactory} + * @since 3.22.0 + */ + this.sat = SAT; + + // Constraint + + /** + * A reference to the `Matter.Constraint` module. + * + * 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. + * + * @name Phaser.Physics.Matter.MatterPhysics#constraint + * @type {MatterJS.ConstraintFactory} + * @since 3.22.0 + */ + this.constraint = Constraint; + + // Factory + + /** + * A reference to the `Matter.Bodies` module. + * + * The `Matter.Bodies` module contains factory methods for creating rigid bodies + * with commonly used body configurations (such as rectangles, circles and other polygons). + * + * @name Phaser.Physics.Matter.MatterPhysics#bodies + * @type {MatterJS.BodiesFactory} + * @since 3.18.0 + */ + this.bodies = Bodies; + + /** + * A reference to the `Matter.Composites` module. + * + * The `Matter.Composites` module contains factory methods for creating composite bodies + * with commonly used configurations (such as stacks and chains). + * + * @name Phaser.Physics.Matter.MatterPhysics#composites + * @type {MatterJS.CompositesFactory} + * @since 3.22.0 + */ + this.composites = Composites; + + // Geometry + + /** + * A reference to the `Matter.Axes` module. + * + * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. + * + * @name Phaser.Physics.Matter.MatterPhysics#axes + * @type {MatterJS.AxesFactory} + * @since 3.22.0 + */ + this.axes = Axes; + + /** + * A reference to the `Matter.Bounds` module. + * + * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). + * + * @name Phaser.Physics.Matter.MatterPhysics#bounds + * @type {MatterJS.BoundsFactory} + * @since 3.22.0 + */ + this.bounds = Bounds; + + /** + * 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 + */ + this.svg = Svg; + + /** + * A reference to the `Matter.Vector` module. + * + * 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 }`. + * + * @name Phaser.Physics.Matter.MatterPhysics#vector + * @type {MatterJS.VectorFactory} + * @since 3.22.0 + */ + this.vector = Vector; + + /** + * A reference to the `Matter.Vertices` module. + * + * 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). + * + * @name Phaser.Physics.Matter.MatterPhysics#vertices + * @type {MatterJS.VerticesFactory} + * @since 3.22.0 + */ + this.vertices = Vertices; + + /** + * A reference to the `Matter.Vertices` module. + * + * 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). + * + * @name Phaser.Physics.Matter.MatterPhysics#verts + * @type {MatterJS.VerticesFactory} + * @since 3.14.0 + */ + this.verts = Vertices; + + /** + * An internal temp vector used for velocity and force calculations. + * + * @name Phaser.Physics.Matter.MatterPhysics#_tempVec2 + * @type {MatterJS.Vector} + * @private + * @since 3.22.0 + */ + this._tempVec2 = Vector.create(); + + // Matter plugins + + if (GetValue(this.config, 'plugins.collisionevents', true)) + { + this.enableCollisionEventsPlugin(); + } + + if (GetValue(this.config, 'plugins.attractors', false)) + { + this.enableAttractorPlugin(); + } + + if (GetValue(this.config, 'plugins.wrap', false)) + { + this.enableWrapPlugin(); + } + + Resolver._restingThresh = GetValue(this.config, 'restingThresh', 4); + Resolver._restingThreshTangent = GetValue(this.config, 'restingThreshTangent', 6); + Resolver._positionDampen = GetValue(this.config, 'positionDampen', 0.9); + Resolver._positionWarming = GetValue(this.config, 'positionWarming', 0.8); + Resolver._frictionNormalMultiplier = GetValue(this.config, 'frictionNormalMultiplier', 5); + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Physics.Matter.MatterPhysics#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + this.bodyBounds = new BodyBounds(); + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Physics.Matter.MatterPhysics#start + * @private + * @since 3.5.0 + */ + start: function () + { + if (!this.world) + { + this.world = new World(this.scene, this.config); + this.add = new Factory(this.world); + } + + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * This internal method is called when this class starts and retrieves the final Matter World Config. + * + * @method Phaser.Physics.Matter.MatterPhysics#getConfig + * @since 3.0.0 + * + * @return {Phaser.Types.Physics.Matter.MatterWorldConfig} The Matter World Config. + */ + getConfig: function () + { + var gameConfig = this.systems.game.config.physics; + var sceneConfig = this.systems.settings.physics; + + var config = Merge( + GetFastValue(sceneConfig, 'matter', {}), + GetFastValue(gameConfig, 'matter', {}) + ); + + return config; + }, + + /** + * Enables the Matter Attractors Plugin. + * + * The attractors plugin that makes it easy to apply continual forces on bodies. + * It's possible to simulate effects such as wind, gravity and magnetism. + * + * https://github.com/liabru/matter-attractors + * + * This method is called automatically if `plugins.attractors` is set in the Matter World Config. + * However, you can also call it directly from within your game. + * + * @method Phaser.Physics.Matter.MatterPhysics#enableAttractorPlugin + * @since 3.0.0 + * + * @return {this} This Matter Physics instance. + */ + enableAttractorPlugin: function () + { + Plugin.register(MatterAttractors); + Plugin.use(MatterLib, MatterAttractors); + + return this; + }, + + /** + * Enables the Matter Wrap Plugin. + * + * The coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay + * within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, + * while maintaining its velocity. + * + * https://github.com/liabru/matter-wrap + * + * This method is called automatically if `plugins.wrap` is set in the Matter World Config. + * However, you can also call it directly from within your game. + * + * @method Phaser.Physics.Matter.MatterPhysics#enableWrapPlugin + * @since 3.0.0 + * + * @return {this} This Matter Physics instance. + */ + enableWrapPlugin: function () + { + Plugin.register(MatterWrap); + Plugin.use(MatterLib, MatterWrap); + + return this; + }, + + /** + * Enables the Matter Collision Events Plugin. + * + * Note that this plugin is enabled by default. So you should only ever need to call this + * method if you have specifically disabled the plugin in your Matter World Config. + * You can disable it by setting `plugins.collisionevents: false` in your Matter World Config. + * + * This plugin triggers three new events on Matter.Body: + * + * 1. `onCollide` + * 2. `onCollideEnd` + * 3. `onCollideActive` + * + * These events correspond to the Matter.js events `collisionStart`, `collisionActive` and `collisionEnd`, respectively. + * You can listen to these events via Matter.Events or they will also be emitted from the Matter World. + * + * This plugin also extends Matter.Body with three convenience functions: + * + * `Matter.Body.setOnCollide(callback)` + * `Matter.Body.setOnCollideEnd(callback)` + * `Matter.Body.setOnCollideActive(callback)` + * + * You can register event callbacks by providing a function of type (pair: Matter.Pair) => void + * + * https://github.com/dxu/matter-collision-events + * + * @method Phaser.Physics.Matter.MatterPhysics#enableCollisionEventsPlugin + * @since 3.22.0 + * + * @return {this} This Matter Physics instance. + */ + enableCollisionEventsPlugin: function () + { + Plugin.register(MatterCollisionEvents); + Plugin.use(MatterLib, MatterCollisionEvents); + + return this; + }, + + /** + * Pauses the Matter World instance and sets `enabled` to `false`. + * + * A paused world will not run any simulations for the duration it is paused. + * + * @method Phaser.Physics.Matter.MatterPhysics#pause + * @fires Phaser.Physics.Matter.Events#PAUSE + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.World} The Matter World object. + */ + pause: function () + { + return this.world.pause(); + }, + + /** + * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. + * + * @method Phaser.Physics.Matter.MatterPhysics#resume + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.World} The Matter World object. + */ + resume: function () + { + return this.world.resume(); + }, + + /** + * Sets the Matter Engine to run at fixed timestep of 60Hz and enables `autoUpdate`. + * If you have set a custom `getDelta` function then this will override it. + * + * @method Phaser.Physics.Matter.MatterPhysics#set60Hz + * @since 3.4.0 + * + * @return {this} This Matter Physics instance. + */ + set60Hz: function () + { + this.world.getDelta = this.world.update60Hz; + this.world.autoUpdate = true; + + return this; + }, + + /** + * Sets the Matter Engine to run at fixed timestep of 30Hz and enables `autoUpdate`. + * If you have set a custom `getDelta` function then this will override it. + * + * @method Phaser.Physics.Matter.MatterPhysics#set30Hz + * @since 3.4.0 + * + * @return {this} This Matter Physics instance. + */ + set30Hz: function () + { + this.world.getDelta = this.world.update30Hz; + this.world.autoUpdate = true; + + return this; + }, + + /** + * Manually advances the physics simulation by one iteration. + * + * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. + * If undefined they use the Matter defaults of 60Hz and no correction. + * + * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. + * + * It also ignores any custom `getDelta` functions, as you should be passing the delta + * value in to this call. + * + * You can adjust the number of iterations that Engine.update performs internally. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * + * @method Phaser.Physics.Matter.MatterPhysics#step + * @since 3.4.0 + * + * @param {number} [delta=16.666] - The delta value. + * @param {number} [correction=1] - Optional delta correction value. + */ + step: function (delta, correction) + { + this.world.step(delta, correction); + }, + + /** + * Checks if the vertices of the given body, or an array of bodies, contains the given point, or not. + * + * You can pass in either a single body, or an array of bodies to be checked. This method will + * return `true` if _any_ of the bodies in the array contain the point. See the `intersectPoint` method if you need + * to get a list of intersecting bodies. + * + * The point should be transformed into the Matter World coordinate system in advance. This happens by + * default with Input Pointers, but if you wish to use points from another system you may need to + * transform them before passing them. + * + * @method Phaser.Physics.Matter.MatterPhysics#containsPoint + * @since 3.22.0 + * + * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} body - The body, or an array of bodies, to check against the point. + * @param {number} x - The horizontal coordinate of the point. + * @param {number} y - The vertical coordinate of the point. + * + * @return {boolean} `true` if the point is within one of the bodies given, otherwise `false`. + */ + containsPoint: function (body, x, y) + { + body = this.getMatterBodies(body); + + var position = Vector.create(x, y); + + var result = Query.point(body, position); + + return (result.length > 0) ? true : false; + }, + + /** + * Checks the given coordinates to see if any vertices of the given bodies contain it. + * + * If no bodies are provided it will search all bodies in the Matter World, including within Composites. + * + * The coordinates should be transformed into the Matter World coordinate system in advance. This happens by + * default with Input Pointers, but if you wish to use coordinates from another system you may need to + * transform them before passing them. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectPoint + * @since 3.22.0 + * + * @param {number} x - The horizontal coordinate of the point. + * @param {number} y - The vertical coordinate of the point. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies which contain the given point. + */ + intersectPoint: function (x, y, bodies) + { + bodies = this.getMatterBodies(bodies); + + var position = Vector.create(x, y); + + var output = []; + + var result = Query.point(bodies, position); + + result.forEach(function (body) + { + if (output.indexOf(body) === -1) + { + output.push(body); + } + }); + + return output; + }, + + /** + * Checks the given rectangular area to see if any vertices of the given bodies intersect with it. + * Or, if the `outside` parameter is set to `true`, it checks to see which bodies do not + * intersect with it. + * + * If no bodies are provided it will search all bodies in the Matter World, including within Composites. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectRect + * @since 3.22.0 + * + * @param {number} x - The horizontal coordinate of the top-left of the area. + * @param {number} y - The vertical coordinate of the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {boolean} [outside=false] - If `false` it checks for vertices inside the area, if `true` it checks for vertices outside the area. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies that intersect with the given area. + */ + intersectRect: function (x, y, width, height, outside, bodies) + { + if (outside === undefined) { outside = false; } + + bodies = this.getMatterBodies(bodies); + + var bounds = { + min: { x: x, y: y }, + max: { x: x + width, y: y + height } + }; + + var output = []; + + var result = Query.region(bodies, bounds, outside); + + result.forEach(function (body) + { + if (output.indexOf(body) === -1) + { + output.push(body); + } + }); + + return output; + }, + + /** + * Checks the given ray segment to see if any vertices of the given bodies intersect with it. + * + * If no bodies are provided it will search all bodies in the Matter World. + * + * The width of the ray can be specified via the `rayWidth` parameter. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectRay + * @since 3.22.0 + * + * @param {number} x1 - The horizontal coordinate of the start of the ray segment. + * @param {number} y1 - The vertical coordinate of the start of the ray segment. + * @param {number} x2 - The horizontal coordinate of the end of the ray segment. + * @param {number} y2 - The vertical coordinate of the end of the ray segment. + * @param {number} [rayWidth=1] - The width of the ray segment. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with the ray segment. + */ + intersectRay: function (x1, y1, x2, y2, rayWidth, bodies) + { + if (rayWidth === undefined) { rayWidth = 1; } + + bodies = this.getMatterBodies(bodies); + + var result = []; + var collisions = Query.ray(bodies, Vector.create(x1, y1), Vector.create(x2, y2), rayWidth); + + for (var i = 0; i < collisions.length; i++) + { + result.push(collisions[i].body); + } + + return result; + }, + + /** + * Checks the given Matter Body to see if it intersects with any of the given bodies. + * + * If no bodies are provided it will check against all bodies in the Matter World. + * + * @method Phaser.Physics.Matter.MatterPhysics#intersectBody + * @since 3.22.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBody} body - The target body. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check the target body against. If not provided it will search all bodies in the world. + * + * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with target body. + */ + intersectBody: function (body, bodies) + { + bodies = this.getMatterBodies(bodies); + + var result = []; + var collisions = Query.collides(body, bodies); + + for (var i = 0; i < collisions.length; i++) + { + var pair = collisions[i]; + + if (pair.bodyA === body) + { + result.push(pair.bodyB); + } + else + { + result.push(pair.bodyA); + } + } + + return result; + }, + + /** + * Checks to see if the target body, or an array of target bodies, intersects with any of the given bodies. + * + * If intersection occurs this method will return `true` and, if provided, invoke the callbacks. + * + * If no bodies are provided for the second parameter the target will check again all bodies in the Matter World. + * + * Note that bodies can only overlap if they are in non-colliding collision groups or categories. + * + * If you provide a `processCallback` then the two bodies that overlap are sent to it. This callback + * must return a boolean and is used to allow you to perform additional processing tests before a final + * outcome is decided. If it returns `true` then the bodies are finally passed to the `overlapCallback`, if set. + * + * If you provide an `overlapCallback` then the matching pairs of overlapping bodies will be sent to it. + * + * Both callbacks have the following signature: `function (bodyA, bodyB, collisionInfo)` where `bodyA` is always + * the target body. The `collisionInfo` object contains additional data, such as the angle and depth of penetration. + * + * @method Phaser.Physics.Matter.MatterPhysics#overlap + * @since 3.22.0 + * + * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} target - The target body, or array of target bodies, to check. + * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - The second body, or array of bodies, to check. If falsey it will check against all bodies in the world. + * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the bodies overlap. + * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two bodies if they overlap. If this is set then `overlapCallback` will only be invoked if this callback returns `true`. + * @param {*} [callbackContext] - The context, or scope, in which to run the callbacks. + * + * @return {boolean} `true` if the target body intersects with _any_ of the bodies given, otherwise `false`. + */ + overlap: function (target, bodies, overlapCallback, processCallback, callbackContext) + { + if (overlapCallback === undefined) { overlapCallback = null; } + if (processCallback === undefined) { processCallback = null; } + if (callbackContext === undefined) { callbackContext = overlapCallback; } + + if (!Array.isArray(target)) + { + target = [ target ]; + } + + target = this.getMatterBodies(target); + bodies = this.getMatterBodies(bodies); + + var match = false; + + for (var i = 0; i < target.length; i++) + { + var entry = target[i]; + + var collisions = Query.collides(entry, bodies); + + for (var c = 0; c < collisions.length; c++) + { + var info = collisions[c]; + var bodyB = (info.bodyA.id === entry.id) ? info.bodyB : info.bodyA; + + if (!processCallback || processCallback.call(callbackContext, entry, bodyB, info)) + { + match = true; + + if (overlapCallback) + { + overlapCallback.call(callbackContext, entry, bodyB, info); + } + else if (!processCallback) + { + // If there are no callbacks we don't need to test every body, just exit when the first is found + return true; + } + } + } + } + + return match; + }, + + /** + * Sets the collision filter category of all given Matter Bodies to the given value. + * + * This number must be a power of two between 2^0 (= 1) and 2^31. + * + * Bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * + * @method Phaser.Physics.Matter.MatterPhysics#setCollisionCategory + * @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} value - Unique category bitfield. + * + * @return {this} This Matter Physics instance. + */ + setCollisionCategory: function (bodies, value) + { + bodies = this.getMatterBodies(bodies); + + bodies.forEach(function (body) + { + body.collisionFilter.category = value; + }); + + return this; + }, + + /** + * Sets the collision filter group of all given Matter Bodies to the given value. + * + * If the group value is zero, or if two Matter Bodies have different group values, + * they will collide according to the usual collision filter rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * + * If two Matter Bodies have the same positive group value, they will always collide; + * if they have the same negative group value they will never collide. + * + * @method Phaser.Physics.Matter.MatterPhysics#setCollisionGroup + * @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} value - Unique group index. + * + * @return {this} This Matter Physics instance. + */ + setCollisionGroup: function (bodies, value) + { + bodies = this.getMatterBodies(bodies); + + bodies.forEach(function (body) + { + body.collisionFilter.group = value; + }); + + return this; + }, + + /** + * 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. + */ + setCollidesWith: function (bodies, categories) + { + bodies = this.getMatterBodies(bodies); + + var flags = 0; + + if (!Array.isArray(categories)) + { + flags = categories; + } + else + { + for (var i = 0; i < categories.length; i++) + { + flags |= categories[i]; + } + } + + bodies.forEach(function (body) + { + body.collisionFilter.mask = flags; + }); + + return this; + }, + + /** + * Takes an array and returns a new array made from all of the Matter Bodies found in the original array. + * + * For example, passing in Matter Game Objects, such as a bunch of Matter Sprites, to this method, would + * return an array containing all of their native Matter Body objects. + * + * If the `bodies` argument is falsey, it will return all bodies in the world. + * + * @method Phaser.Physics.Matter.MatterPhysics#getMatterBodies + * @since 3.22.0 + * + * @param {array} [bodies] - An array of objects to extract the bodies from. If falsey, it will return all bodies in the world. + * + * @return {MatterJS.BodyType[]} An array of native Matter Body objects. + */ + getMatterBodies: function (bodies) + { + if (!bodies) + { + return this.world.getAllBodies(); + } + + if (!Array.isArray(bodies)) + { + bodies = [ bodies ]; + } + + var output = []; + + for (var i = 0; i < bodies.length; i++) + { + var body = (bodies[i].hasOwnProperty('body')) ? bodies[i].body : bodies[i]; + + output.push(body); + } + + return output; + }, + + /** + * Sets both the horizontal and vertical linear velocity of the physics bodies. + * + * @method Phaser.Physics.Matter.MatterPhysics#setVelocity + * @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} x - The horizontal linear velocity value. + * @param {number} y - The vertical linear velocity value. + * + * @return {this} This Matter Physics instance. + */ + setVelocity: function (bodies, x, y) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + vec2.x = x; + vec2.y = y; + + bodies.forEach(function (body) + { + Body.setVelocity(body, vec2); + }); + + return this; + }, + + /** + * Sets just the horizontal linear velocity of the physics bodies. + * The vertical velocity of the body is unchanged. + * + * @method Phaser.Physics.Matter.MatterPhysics#setVelocityX + * @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} x - The horizontal linear velocity value. + * + * @return {this} This Matter Physics instance. + */ + setVelocityX: function (bodies, x) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + vec2.x = x; + + bodies.forEach(function (body) + { + vec2.y = body.velocity.y; + Body.setVelocity(body, vec2); + }); + + return this; + }, + + /** + * Sets just the vertical linear velocity of the physics bodies. + * The horizontal velocity of the body is unchanged. + * + * @method Phaser.Physics.Matter.MatterPhysics#setVelocityY + * @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} y - The vertical linear velocity value. + * + * @return {this} This Matter Physics instance. + */ + setVelocityY: function (bodies, y) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + vec2.y = y; + + bodies.forEach(function (body) + { + vec2.x = body.velocity.x; + Body.setVelocity(body, vec2); + }); + + return this; + }, + + /** + * Sets the angular velocity of the bodies instantly. + * Position, angle, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.MatterPhysics#setAngularVelocity + * @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} value - The angular velocity. + * + * @return {this} This Matter Physics instance. + */ + setAngularVelocity: function (bodies, value) + { + bodies = this.getMatterBodies(bodies); + + bodies.forEach(function (body) + { + Body.setAngularVelocity(body, value); + }); + + return this; + }, + + /** + * Applies a force to a body, at the bodies current position, including resulting torque. + * + * @method Phaser.Physics.Matter.MatterPhysics#applyForce + * @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 {Phaser.Types.Math.Vector2Like} force - A Vector that specifies the force to apply. + * + * @return {this} This Matter Physics instance. + */ + applyForce: function (bodies, force) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + bodies.forEach(function (body) + { + vec2.x = body.position.x; + vec2.y = body.position.y; + + Body.applyForce(body, vec2, force); + }); + + return this; + }, + + /** + * Applies a force to a body, from the given world position, including resulting torque. + * 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#applyForceFromPosition + * @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 {Phaser.Types.Math.Vector2Like} position - A Vector that specifies the world-space position to apply the force at. + * @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. + */ + applyForceFromPosition: function (bodies, position, speed, angle) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + bodies.forEach(function (body) + { + if (angle === undefined) + { + angle = body.angle; + } + + vec2.x = speed * Math.cos(angle); + vec2.y = speed * Math.sin(angle); + + Body.applyForce(body, position, vec2); + }); + + return this; + }, + + /** + * 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. + */ + applyForceFromAngle: function (bodies, speed, angle) + { + bodies = this.getMatterBodies(bodies); + + var vec2 = this._tempVec2; + + bodies.forEach(function (body) + { + if (angle === undefined) + { + angle = body.angle; + } + + vec2.x = speed * Math.cos(angle); + vec2.y = speed * Math.sin(angle); + + Body.applyForce(body, { x: body.position.x, y: body.position.y }, vec2); + }); + + return this; + }, + + /** + * Returns the length of the given constraint, which is the distance between the two points. + * + * @method Phaser.Physics.Matter.MatterPhysics#getConstraintLength + * @since 3.22.0 + * + * @param {MatterJS.ConstraintType} constraint - The constraint to get the length from. + * + * @return {number} The length of the constraint. + */ + getConstraintLength: function (constraint) + { + var aX = constraint.pointA.x; + var aY = constraint.pointA.y; + var bX = constraint.pointB.x; + var bY = constraint.pointB.y; + + if (constraint.bodyA) + { + aX += constraint.bodyA.position.x; + aY += constraint.bodyA.position.y; + } + + if (constraint.bodyB) + { + bX += constraint.bodyB.position.x; + bY += constraint.bodyB.position.y; + } + + return DistanceBetween(aX, aY, bX, bY); + }, + + /** + * 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 {integer} align - One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`. + * + * @return {this} This Matter Physics instance. + */ + alignBody: function (body, x, y, align) + { + body = (body.hasOwnProperty('body')) ? body.body : body; + + var pos; + + switch (align) + { + case ALIGN_CONST.TOP_LEFT: + case ALIGN_CONST.LEFT_TOP: + pos = this.bodyBounds.getTopLeft(body, x, y); + break; + + case ALIGN_CONST.TOP_CENTER: + pos = this.bodyBounds.getTopCenter(body, x, y); + break; + + case ALIGN_CONST.TOP_RIGHT: + case ALIGN_CONST.RIGHT_TOP: + pos = this.bodyBounds.getTopRight(body, x, y); + break; + + case ALIGN_CONST.LEFT_CENTER: + pos = this.bodyBounds.getLeftCenter(body, x, y); + break; + + case ALIGN_CONST.CENTER: + pos = this.bodyBounds.getCenter(body, x, y); + break; + + case ALIGN_CONST.RIGHT_CENTER: + pos = this.bodyBounds.getRightCenter(body, x, y); + break; + + case ALIGN_CONST.LEFT_BOTTOM: + case ALIGN_CONST.BOTTOM_LEFT: + pos = this.bodyBounds.getBottomLeft(body, x, y); + break; + + case ALIGN_CONST.BOTTOM_CENTER: + pos = this.bodyBounds.getBottomCenter(body, x, y); + break; + + case ALIGN_CONST.BOTTOM_RIGHT: + case ALIGN_CONST.RIGHT_BOTTOM: + pos = this.bodyBounds.getBottomRight(body, x, y); + break; + } + + if (pos) + { + Body.setPosition(body, pos); + } + + return this; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Physics.Matter.MatterPhysics#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + if (this.world) + { + eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); + eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); + } + + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + + if (this.add) + { + this.add.destroy(); + } + + if (this.world) + { + this.world.destroy(); + } + + this.add = null; + this.world = null; + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Physics.Matter.MatterPhysics#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('MatterPhysics', MatterPhysics, 'matterPhysics'); + +module.exports = MatterPhysics; diff --git a/src/physics/matter-js/MatterSprite.js b/src/physics/matter-js/MatterSprite.js index e04ed61fa..23845386c 100644 --- a/src/physics/matter-js/MatterSprite.js +++ b/src/physics/matter-js/MatterSprite.js @@ -1,136 +1,136 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var AnimationComponent = require('../../gameobjects/components/Animation'); -var Class = require('../../utils/Class'); -var Components = require('./components'); -var GameObject = require('../../gameobjects/GameObject'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Pipeline = require('../../gameobjects/components/Pipeline'); -var Sprite = require('../../gameobjects/sprite/Sprite'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Matter Physics Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * - * @class Sprite - * @extends Phaser.GameObjects.Sprite - * @memberof Phaser.Physics.Matter - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Matter.Components.Bounce - * @extends Phaser.Physics.Matter.Components.Collision - * @extends Phaser.Physics.Matter.Components.Force - * @extends Phaser.Physics.Matter.Components.Friction - * @extends Phaser.Physics.Matter.Components.Gravity - * @extends Phaser.Physics.Matter.Components.Mass - * @extends Phaser.Physics.Matter.Components.Sensor - * @extends Phaser.Physics.Matter.Components.SetBody - * @extends Phaser.Physics.Matter.Components.Sleep - * @extends Phaser.Physics.Matter.Components.Static - * @extends Phaser.Physics.Matter.Components.Transform - * @extends Phaser.Physics.Matter.Components.Velocity - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.BlendMode - * @extends Phaser.GameObjects.Components.Depth - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.GetBounds - * @extends Phaser.GameObjects.Components.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Size - * @extends Phaser.GameObjects.Components.Texture - * @extends Phaser.GameObjects.Components.Tint - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Physics.Matter.World} world - A reference to the Matter.World instance that this body belongs to. - * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - */ -var MatterSprite = new Class({ - - Extends: Sprite, - - Mixins: [ - Components.Bounce, - Components.Collision, - Components.Force, - Components.Friction, - Components.Gravity, - Components.Mass, - Components.Sensor, - Components.SetBody, - Components.Sleep, - Components.Static, - Components.Transform, - Components.Velocity, - Pipeline - ], - - initialize: - - function MatterSprite (world, x, y, texture, frame, options) - { - GameObject.call(this, world.scene, 'Sprite'); - - this.anims = new AnimationComponent(this); - - this.setTexture(texture, frame); - this.setSizeToFrame(); - this.setOrigin(); - - /** - * A reference to the Matter.World instance that this body belongs to. - * - * @name Phaser.Physics.Matter.Sprite#world - * @type {Phaser.Physics.Matter.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * An internal temp vector used for velocity and force calculations. - * - * @name Phaser.Physics.Matter.Sprite#_tempVec2 - * @type {Phaser.Math.Vector2} - * @private - * @since 3.0.0 - */ - this._tempVec2 = new Vector2(x, y); - - var shape = GetFastValue(options, 'shape', null); - - if (shape) - { - this.setBody(shape, options); - } - else - { - this.setRectangle(this.width, this.height, options); - } - - this.setPosition(x, y); - - this.initPipeline('TextureTintPipeline'); - } - -}); - -module.exports = MatterSprite; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var AnimationComponent = require('../../gameobjects/components/Animation'); +var Class = require('../../utils/Class'); +var Components = require('./components'); +var GameObject = require('../../gameobjects/GameObject'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Pipeline = require('../../gameobjects/components/Pipeline'); +var Sprite = require('../../gameobjects/sprite/Sprite'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Matter Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * + * @class Sprite + * @extends Phaser.GameObjects.Sprite + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Matter.Components.Bounce + * @extends Phaser.Physics.Matter.Components.Collision + * @extends Phaser.Physics.Matter.Components.Force + * @extends Phaser.Physics.Matter.Components.Friction + * @extends Phaser.Physics.Matter.Components.Gravity + * @extends Phaser.Physics.Matter.Components.Mass + * @extends Phaser.Physics.Matter.Components.Sensor + * @extends Phaser.Physics.Matter.Components.SetBody + * @extends Phaser.Physics.Matter.Components.Sleep + * @extends Phaser.Physics.Matter.Components.Static + * @extends Phaser.Physics.Matter.Components.Transform + * @extends Phaser.Physics.Matter.Components.Velocity + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.BlendMode + * @extends Phaser.GameObjects.Components.Depth + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.GetBounds + * @extends Phaser.GameObjects.Components.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Size + * @extends Phaser.GameObjects.Components.Texture + * @extends Phaser.GameObjects.Components.Tint + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Physics.Matter.World} world - A reference to the Matter.World instance that this body belongs to. + * @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} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + */ +var MatterSprite = new Class({ + + Extends: Sprite, + + Mixins: [ + Components.Bounce, + Components.Collision, + Components.Force, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.SetBody, + Components.Sleep, + Components.Static, + Components.Transform, + Components.Velocity, + Pipeline + ], + + initialize: + + function MatterSprite (world, x, y, texture, frame, options) + { + GameObject.call(this, world.scene, 'Sprite'); + + this.anims = new AnimationComponent(this); + + this.setTexture(texture, frame); + this.setSizeToFrame(); + this.setOrigin(); + + /** + * A reference to the Matter.World instance that this body belongs to. + * + * @name Phaser.Physics.Matter.Sprite#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * An internal temp vector used for velocity and force calculations. + * + * @name Phaser.Physics.Matter.Sprite#_tempVec2 + * @type {Phaser.Math.Vector2} + * @private + * @since 3.0.0 + */ + this._tempVec2 = new Vector2(x, y); + + var shape = GetFastValue(options, 'shape', null); + + if (shape) + { + this.setBody(shape, options); + } + else + { + this.setRectangle(this.width, this.height, options); + } + + this.setPosition(x, y); + + this.initPipeline('TextureTintPipeline'); + } + +}); + +module.exports = MatterSprite; diff --git a/src/physics/matter-js/MatterTileBody.js b/src/physics/matter-js/MatterTileBody.js index 050f2f2a6..263066aa0 100644 --- a/src/physics/matter-js/MatterTileBody.js +++ b/src/physics/matter-js/MatterTileBody.js @@ -1,314 +1,314 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bodies = require('./lib/factory/Bodies'); -var Body = require('./lib/body/Body'); -var Class = require('../../utils/Class'); -var Components = require('./components'); -var EventEmitter = require('eventemitter3'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var HasValue = require('../../utils/object/HasValue'); -var Vertices = require('./lib/geometry/Vertices'); - -/** - * @classdesc - * A wrapper around a Tile that provides access to a corresponding Matter body. A tile can only - * have one Matter body associated with it. You can either pass in an existing Matter body for - * the tile or allow the constructor to create the corresponding body for you. If the Tile has a - * collision group (defined in Tiled), those shapes will be used to create the body. If not, the - * tile's rectangle bounding box will be used. - * - * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. - * - * Note: not all Tiled collision shapes are supported. See - * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. - * - * @class TileBody - * @memberof Phaser.Physics.Matter - * @extends Phaser.Events.EventEmitter - * @constructor - * @since 3.0.0 - * - * @extends Phaser.Physics.Matter.Components.Bounce - * @extends Phaser.Physics.Matter.Components.Collision - * @extends Phaser.Physics.Matter.Components.Friction - * @extends Phaser.Physics.Matter.Components.Gravity - * @extends Phaser.Physics.Matter.Components.Mass - * @extends Phaser.Physics.Matter.Components.Sensor - * @extends Phaser.Physics.Matter.Components.Sleep - * @extends Phaser.Physics.Matter.Components.Static - * - * @param {Phaser.Physics.Matter.World} world - The Matter world instance this body belongs to. - * @param {Phaser.Tilemaps.Tile} tile - The target tile that should have a Matter body. - * @param {Phaser.Types.Physics.Matter.MatterTileOptions} [options] - Options to be used when creating the Matter body. - */ -var MatterTileBody = new Class({ - - Extends: EventEmitter, - - Mixins: [ - Components.Bounce, - Components.Collision, - Components.Friction, - Components.Gravity, - Components.Mass, - Components.Sensor, - Components.Sleep, - Components.Static - ], - - initialize: - - function MatterTileBody (world, tile, options) - { - EventEmitter.call(this); - - /** - * The tile object the body is associated with. - * - * @name Phaser.Physics.Matter.TileBody#tile - * @type {Phaser.Tilemaps.Tile} - * @since 3.0.0 - */ - this.tile = tile; - - /** - * The Matter world the body exists within. - * - * @name Phaser.Physics.Matter.TileBody#world - * @type {Phaser.Physics.Matter.World} - * @since 3.0.0 - */ - this.world = world; - - // Install a reference to 'this' on the tile and ensure there can only be one matter body - // associated with the tile - if (tile.physics.matterBody) - { - tile.physics.matterBody.destroy(); - } - - tile.physics.matterBody = this; - - // 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. - var body = GetFastValue(options, 'body', null); - - var addToWorld = GetFastValue(options, 'addToWorld', true); - - if (!body) - { - var collisionGroup = tile.getCollisionGroup(); - var collisionObjects = GetFastValue(collisionGroup, 'objects', []); - - if (collisionObjects.length > 0) - { - this.setFromTileCollision(options); - } - else - { - this.setFromTileRectangle(options); - } - } - else - { - this.setBody(body, addToWorld); - } - }, - - /** - * Sets the current body to a rectangle that matches the bounds of the tile. - * - * @method Phaser.Physics.Matter.TileBody#setFromTileRectangle - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Matter.MatterBodyTileOptions} [options] - Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. - * - * @return {Phaser.Physics.Matter.TileBody} This TileBody object. - */ - setFromTileRectangle: function (options) - { - if (options === undefined) { options = {}; } - if (!HasValue(options, 'isStatic')) { options.isStatic = true; } - if (!HasValue(options, 'addToWorld')) { options.addToWorld = true; } - - var bounds = this.tile.getBounds(); - var cx = bounds.x + (bounds.width / 2); - var cy = bounds.y + (bounds.height / 2); - var body = Bodies.rectangle(cx, cy, bounds.width, bounds.height, options); - - this.setBody(body, options.addToWorld); - - return this; - }, - - /** - * Sets the current body from the collision group associated with the Tile. This is typically - * set up in Tiled's collision editor. - * - * Note: Matter doesn't support all shapes from Tiled. Rectangles and polygons are directly - * supported. Ellipses are converted into circle bodies. Polylines are treated as if they are - * closed polygons. If a tile has multiple shapes, a multi-part body will be created. Concave - * shapes are supported if poly-decomp library is included. Decomposition is not guaranteed to - * work for complex shapes (e.g. holes), so it's often best to manually decompose a concave - * polygon into multiple convex polygons yourself. - * - * @method Phaser.Physics.Matter.TileBody#setFromTileCollision - * @since 3.0.0 - * - * @param {Phaser.Types.Physics.Matter.MatterBodyTileOptions} [options] - Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. - * - * @return {Phaser.Physics.Matter.TileBody} This TileBody object. - */ - setFromTileCollision: function (options) - { - if (options === undefined) { options = {}; } - if (!HasValue(options, 'isStatic')) { options.isStatic = true; } - if (!HasValue(options, 'addToWorld')) { options.addToWorld = true; } - - var sx = this.tile.tilemapLayer.scaleX; - var sy = this.tile.tilemapLayer.scaleY; - var tileX = this.tile.getLeft(); - var tileY = this.tile.getTop(); - var collisionGroup = this.tile.getCollisionGroup(); - var collisionObjects = GetFastValue(collisionGroup, 'objects', []); - - var parts = []; - - for (var i = 0; i < collisionObjects.length; i++) - { - var object = collisionObjects[i]; - var ox = tileX + (object.x * sx); - var oy = tileY + (object.y * sy); - var ow = object.width * sx; - var oh = object.height * sy; - var body = null; - - if (object.rectangle) - { - body = Bodies.rectangle(ox + ow / 2, oy + oh / 2, ow, oh, options); - } - else if (object.ellipse) - { - body = Bodies.circle(ox + ow / 2, oy + oh / 2, ow / 2, options); - } - else if (object.polygon || object.polyline) - { - // Polygons and polylines are both treated as closed polygons - var originalPoints = object.polygon ? object.polygon : object.polyline; - - var points = originalPoints.map(function (p) - { - return { x: p.x * sx, y: p.y * sy }; - }); - - var vertices = Vertices.create(points); - - // 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. - - var center = Vertices.centre(vertices); - - ox += center.x; - oy += center.y; - - body = Bodies.fromVertices(ox, oy, vertices, options); - } - - if (body) - { - parts.push(body); - } - } - - if (parts.length === 1) - { - this.setBody(parts[0], options.addToWorld); - } - else if (parts.length > 1) - { - options.parts = parts; - this.setBody(Body.create(options), options.addToWorld); - } - - return this; - }, - - /** - * Sets the current body to the given body. This will remove the previous body, if one already - * exists. - * - * @method Phaser.Physics.Matter.TileBody#setBody - * @since 3.0.0 - * - * @param {MatterJS.BodyType} body - The new Matter body to use. - * @param {boolean} [addToWorld=true] - Whether or not to add the body to the Matter world. - * - * @return {Phaser.Physics.Matter.TileBody} This TileBody object. - */ - setBody: function (body, addToWorld) - { - if (addToWorld === undefined) { addToWorld = true; } - - if (this.body) - { - this.removeBody(); - } - - this.body = body; - this.body.gameObject = this; - - if (addToWorld) - { - this.world.add(this.body); - } - - return this; - }, - - /** - * Removes the current body from the TileBody and from the Matter world - * - * @method Phaser.Physics.Matter.TileBody#removeBody - * @since 3.0.0 - * - * @return {Phaser.Physics.Matter.TileBody} This TileBody object. - */ - removeBody: function () - { - if (this.body) - { - this.world.remove(this.body); - this.body.gameObject = undefined; - this.body = undefined; - } - - return this; - }, - - /** - * Removes the current body from the tile and the world. - * - * @method Phaser.Physics.Matter.TileBody#destroy - * @since 3.0.0 - * - * @return {Phaser.Physics.Matter.TileBody} This TileBody object. - */ - destroy: function () - { - this.removeBody(); - this.tile.physics.matterBody = undefined; - this.removeAllListeners(); - } - -}); - -module.exports = MatterTileBody; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = require('./lib/factory/Bodies'); +var Body = require('./lib/body/Body'); +var Class = require('../../utils/Class'); +var Components = require('./components'); +var EventEmitter = require('eventemitter3'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var HasValue = require('../../utils/object/HasValue'); +var Vertices = require('./lib/geometry/Vertices'); + +/** + * @classdesc + * A wrapper around a Tile that provides access to a corresponding Matter body. A tile can only + * have one Matter body associated with it. You can either pass in an existing Matter body for + * the tile or allow the constructor to create the corresponding body for you. If the Tile has a + * collision group (defined in Tiled), those shapes will be used to create the body. If not, the + * tile's rectangle bounding box will be used. + * + * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. + * + * Note: not all Tiled collision shapes are supported. See + * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. + * + * @class TileBody + * @memberof Phaser.Physics.Matter + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @extends Phaser.Physics.Matter.Components.Bounce + * @extends Phaser.Physics.Matter.Components.Collision + * @extends Phaser.Physics.Matter.Components.Friction + * @extends Phaser.Physics.Matter.Components.Gravity + * @extends Phaser.Physics.Matter.Components.Mass + * @extends Phaser.Physics.Matter.Components.Sensor + * @extends Phaser.Physics.Matter.Components.Sleep + * @extends Phaser.Physics.Matter.Components.Static + * + * @param {Phaser.Physics.Matter.World} world - The Matter world instance this body belongs to. + * @param {Phaser.Tilemaps.Tile} tile - The target tile that should have a Matter body. + * @param {Phaser.Types.Physics.Matter.MatterTileOptions} [options] - Options to be used when creating the Matter body. + */ +var MatterTileBody = new Class({ + + Extends: EventEmitter, + + Mixins: [ + Components.Bounce, + Components.Collision, + Components.Friction, + Components.Gravity, + Components.Mass, + Components.Sensor, + Components.Sleep, + Components.Static + ], + + initialize: + + function MatterTileBody (world, tile, options) + { + EventEmitter.call(this); + + /** + * The tile object the body is associated with. + * + * @name Phaser.Physics.Matter.TileBody#tile + * @type {Phaser.Tilemaps.Tile} + * @since 3.0.0 + */ + this.tile = tile; + + /** + * The Matter world the body exists within. + * + * @name Phaser.Physics.Matter.TileBody#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + // Install a reference to 'this' on the tile and ensure there can only be one matter body + // associated with the tile + if (tile.physics.matterBody) + { + tile.physics.matterBody.destroy(); + } + + tile.physics.matterBody = this; + + // 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. + var body = GetFastValue(options, 'body', null); + + var addToWorld = GetFastValue(options, 'addToWorld', true); + + if (!body) + { + var collisionGroup = tile.getCollisionGroup(); + var collisionObjects = GetFastValue(collisionGroup, 'objects', []); + + if (collisionObjects.length > 0) + { + this.setFromTileCollision(options); + } + else + { + this.setFromTileRectangle(options); + } + } + else + { + this.setBody(body, addToWorld); + } + }, + + /** + * Sets the current body to a rectangle that matches the bounds of the tile. + * + * @method Phaser.Physics.Matter.TileBody#setFromTileRectangle + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBodyTileOptions} [options] - Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + setFromTileRectangle: function (options) + { + if (options === undefined) { options = {}; } + if (!HasValue(options, 'isStatic')) { options.isStatic = true; } + if (!HasValue(options, 'addToWorld')) { options.addToWorld = true; } + + var bounds = this.tile.getBounds(); + var cx = bounds.x + (bounds.width / 2); + var cy = bounds.y + (bounds.height / 2); + var body = Bodies.rectangle(cx, cy, bounds.width, bounds.height, options); + + this.setBody(body, options.addToWorld); + + return this; + }, + + /** + * Sets the current body from the collision group associated with the Tile. This is typically + * set up in Tiled's collision editor. + * + * Note: Matter doesn't support all shapes from Tiled. Rectangles and polygons are directly + * supported. Ellipses are converted into circle bodies. Polylines are treated as if they are + * closed polygons. If a tile has multiple shapes, a multi-part body will be created. Concave + * shapes are supported if poly-decomp library is included. Decomposition is not guaranteed to + * work for complex shapes (e.g. holes), so it's often best to manually decompose a concave + * polygon into multiple convex polygons yourself. + * + * @method Phaser.Physics.Matter.TileBody#setFromTileCollision + * @since 3.0.0 + * + * @param {Phaser.Types.Physics.Matter.MatterBodyTileOptions} [options] - Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + setFromTileCollision: function (options) + { + if (options === undefined) { options = {}; } + if (!HasValue(options, 'isStatic')) { options.isStatic = true; } + if (!HasValue(options, 'addToWorld')) { options.addToWorld = true; } + + var sx = this.tile.tilemapLayer.scaleX; + var sy = this.tile.tilemapLayer.scaleY; + var tileX = this.tile.getLeft(); + var tileY = this.tile.getTop(); + var collisionGroup = this.tile.getCollisionGroup(); + var collisionObjects = GetFastValue(collisionGroup, 'objects', []); + + var parts = []; + + for (var i = 0; i < collisionObjects.length; i++) + { + var object = collisionObjects[i]; + var ox = tileX + (object.x * sx); + var oy = tileY + (object.y * sy); + var ow = object.width * sx; + var oh = object.height * sy; + var body = null; + + if (object.rectangle) + { + body = Bodies.rectangle(ox + ow / 2, oy + oh / 2, ow, oh, options); + } + else if (object.ellipse) + { + body = Bodies.circle(ox + ow / 2, oy + oh / 2, ow / 2, options); + } + else if (object.polygon || object.polyline) + { + // Polygons and polylines are both treated as closed polygons + var originalPoints = object.polygon ? object.polygon : object.polyline; + + var points = originalPoints.map(function (p) + { + return { x: p.x * sx, y: p.y * sy }; + }); + + var vertices = Vertices.create(points); + + // 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. + + var center = Vertices.centre(vertices); + + ox += center.x; + oy += center.y; + + body = Bodies.fromVertices(ox, oy, vertices, options); + } + + if (body) + { + parts.push(body); + } + } + + if (parts.length === 1) + { + this.setBody(parts[0], options.addToWorld); + } + else if (parts.length > 1) + { + options.parts = parts; + this.setBody(Body.create(options), options.addToWorld); + } + + return this; + }, + + /** + * Sets the current body to the given body. This will remove the previous body, if one already + * exists. + * + * @method Phaser.Physics.Matter.TileBody#setBody + * @since 3.0.0 + * + * @param {MatterJS.BodyType} body - The new Matter body to use. + * @param {boolean} [addToWorld=true] - Whether or not to add the body to the Matter world. + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + setBody: function (body, addToWorld) + { + if (addToWorld === undefined) { addToWorld = true; } + + if (this.body) + { + this.removeBody(); + } + + this.body = body; + this.body.gameObject = this; + + if (addToWorld) + { + this.world.add(this.body); + } + + return this; + }, + + /** + * Removes the current body from the TileBody and from the Matter world + * + * @method Phaser.Physics.Matter.TileBody#removeBody + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + removeBody: function () + { + if (this.body) + { + this.world.remove(this.body); + this.body.gameObject = undefined; + this.body = undefined; + } + + return this; + }, + + /** + * Removes the current body from the tile and the world. + * + * @method Phaser.Physics.Matter.TileBody#destroy + * @since 3.0.0 + * + * @return {Phaser.Physics.Matter.TileBody} This TileBody object. + */ + destroy: function () + { + this.removeBody(); + this.tile.physics.matterBody = undefined; + this.removeAllListeners(); + } + +}); + +module.exports = MatterTileBody; diff --git a/src/physics/matter-js/PhysicsEditorParser.js b/src/physics/matter-js/PhysicsEditorParser.js index 978a72aa5..c218552ba 100644 --- a/src/physics/matter-js/PhysicsEditorParser.js +++ b/src/physics/matter-js/PhysicsEditorParser.js @@ -1,136 +1,136 @@ -/** - * @author Joachim Grill - * @author Richard Davey - * @copyright 2018 CodeAndWeb GmbH - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bodies = require('./lib/factory/Bodies'); -var Body = require('./lib/body/Body'); -var Common = require('./lib/core/Common'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var Vertices = require('./lib/geometry/Vertices'); - -/** - * Use PhysicsEditorParser.parseBody() to build a Matter body object, based on a physics data file - * created and exported with PhysicsEditor (https://www.codeandweb.com/physicseditor). - * - * @namespace Phaser.Physics.Matter.PhysicsEditorParser - * @since 3.10.0 - */ -var PhysicsEditorParser = { - - /** - * Parses a body element exported by PhysicsEditor. - * - * @function Phaser.Physics.Matter.PhysicsEditorParser.parseBody - * @since 3.10.0 - * - * @param {number} x - The horizontal world location of the body. - * @param {number} y - The vertical world location of the body. - * @param {object} config - The body configuration and fixture (child body) definitions, as exported by PhysicsEditor. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.BodyType} A compound Matter JS Body. - */ - parseBody: function (x, y, config, options) - { - if (options === undefined) { options = {}; } - - var fixtureConfigs = GetFastValue(config, 'fixtures', []); - var fixtures = []; - - for (var fc = 0; fc < fixtureConfigs.length; fc++) - { - var fixtureParts = this.parseFixture(fixtureConfigs[fc]); - - for (var i = 0; i < fixtureParts.length; i++) - { - fixtures.push(fixtureParts[i]); - } - } - - var matterConfig = Common.clone(config, true); - - Common.extend(matterConfig, options, true); - - delete matterConfig.fixtures; - delete matterConfig.type; - - var body = Body.create(matterConfig); - - Body.setParts(body, fixtures); - - Body.setPosition(body, { x: x, y: y }); - - return body; - }, - - /** - * Parses an element of the "fixtures" list exported by PhysicsEditor - * - * @function Phaser.Physics.Matter.PhysicsEditorParser.parseFixture - * @since 3.10.0 - * - * @param {object} fixtureConfig - The fixture object to parse. - * - * @return {MatterJS.BodyType[]} - An array of Matter JS Bodies. - */ - parseFixture: function (fixtureConfig) - { - var matterConfig = Common.extend({}, false, fixtureConfig); - - delete matterConfig.circle; - delete matterConfig.vertices; - - var fixtures; - - if (fixtureConfig.circle) - { - var x = GetFastValue(fixtureConfig.circle, 'x'); - var y = GetFastValue(fixtureConfig.circle, 'y'); - var r = GetFastValue(fixtureConfig.circle, 'radius'); - fixtures = [ Bodies.circle(x, y, r, matterConfig) ]; - } - else if (fixtureConfig.vertices) - { - fixtures = this.parseVertices(fixtureConfig.vertices, matterConfig); - } - - return fixtures; - }, - - /** - * Parses the "vertices" lists exported by PhysicsEditor. - * - * @function Phaser.Physics.Matter.PhysicsEditorParser.parseVertices - * @since 3.10.0 - * - * @param {array} vertexSets - The vertex lists to parse. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.BodyType[]} - An array of Matter JS Bodies. - */ - parseVertices: function (vertexSets, options) - { - if (options === undefined) { options = {}; } - - var parts = []; - - for (var v = 0; v < vertexSets.length; v++) - { - Vertices.clockwiseSort(vertexSets[v]); - - parts.push(Body.create(Common.extend({ - position: Vertices.centre(vertexSets[v]), - vertices: vertexSets[v] - }, options))); - } - - // flag coincident part edges - return Bodies.flagCoincidentParts(parts); - } -}; - -module.exports = PhysicsEditorParser; +/** + * @author Joachim Grill + * @author Richard Davey + * @copyright 2018 CodeAndWeb GmbH + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = require('./lib/factory/Bodies'); +var Body = require('./lib/body/Body'); +var Common = require('./lib/core/Common'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var Vertices = require('./lib/geometry/Vertices'); + +/** + * Use PhysicsEditorParser.parseBody() to build a Matter body object, based on a physics data file + * created and exported with PhysicsEditor (https://www.codeandweb.com/physicseditor). + * + * @namespace Phaser.Physics.Matter.PhysicsEditorParser + * @since 3.10.0 + */ +var PhysicsEditorParser = { + + /** + * Parses a body element exported by PhysicsEditor. + * + * @function Phaser.Physics.Matter.PhysicsEditorParser.parseBody + * @since 3.10.0 + * + * @param {number} x - The horizontal world location of the body. + * @param {number} y - The vertical world location of the body. + * @param {object} config - The body configuration and fixture (child body) definitions, as exported by PhysicsEditor. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A compound Matter JS Body. + */ + parseBody: function (x, y, config, options) + { + if (options === undefined) { options = {}; } + + var fixtureConfigs = GetFastValue(config, 'fixtures', []); + var fixtures = []; + + for (var fc = 0; fc < fixtureConfigs.length; fc++) + { + var fixtureParts = this.parseFixture(fixtureConfigs[fc]); + + for (var i = 0; i < fixtureParts.length; i++) + { + fixtures.push(fixtureParts[i]); + } + } + + var matterConfig = Common.clone(config, true); + + Common.extend(matterConfig, options, true); + + delete matterConfig.fixtures; + delete matterConfig.type; + + var body = Body.create(matterConfig); + + Body.setParts(body, fixtures); + + Body.setPosition(body, { x: x, y: y }); + + return body; + }, + + /** + * Parses an element of the "fixtures" list exported by PhysicsEditor + * + * @function Phaser.Physics.Matter.PhysicsEditorParser.parseFixture + * @since 3.10.0 + * + * @param {object} fixtureConfig - The fixture object to parse. + * + * @return {MatterJS.BodyType[]} - An array of Matter JS Bodies. + */ + parseFixture: function (fixtureConfig) + { + var matterConfig = Common.extend({}, false, fixtureConfig); + + delete matterConfig.circle; + delete matterConfig.vertices; + + var fixtures; + + if (fixtureConfig.circle) + { + var x = GetFastValue(fixtureConfig.circle, 'x'); + var y = GetFastValue(fixtureConfig.circle, 'y'); + var r = GetFastValue(fixtureConfig.circle, 'radius'); + fixtures = [ Bodies.circle(x, y, r, matterConfig) ]; + } + else if (fixtureConfig.vertices) + { + fixtures = this.parseVertices(fixtureConfig.vertices, matterConfig); + } + + return fixtures; + }, + + /** + * Parses the "vertices" lists exported by PhysicsEditor. + * + * @function Phaser.Physics.Matter.PhysicsEditorParser.parseVertices + * @since 3.10.0 + * + * @param {array} vertexSets - The vertex lists to parse. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType[]} - An array of Matter JS Bodies. + */ + parseVertices: function (vertexSets, options) + { + if (options === undefined) { options = {}; } + + var parts = []; + + for (var v = 0; v < vertexSets.length; v++) + { + Vertices.clockwiseSort(vertexSets[v]); + + parts.push(Body.create(Common.extend({ + position: Vertices.centre(vertexSets[v]), + vertices: vertexSets[v] + }, options))); + } + + // flag coincident part edges + return Bodies.flagCoincidentParts(parts); + } +}; + +module.exports = PhysicsEditorParser; diff --git a/src/physics/matter-js/PhysicsJSONParser.js b/src/physics/matter-js/PhysicsJSONParser.js index 7c9aa3622..7282e92b4 100644 --- a/src/physics/matter-js/PhysicsJSONParser.js +++ b/src/physics/matter-js/PhysicsJSONParser.js @@ -1,111 +1,111 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bodies = require('./lib/factory/Bodies'); -var Body = require('./lib/body/Body'); - -/** - * Creates a body using the supplied physics data, as provided by a JSON file. - * - * The data file should be loaded as JSON: - * - * ```javascript - * preload () - * { - * this.load.json('ninjas', 'assets/ninjas.json); - * } - * - * create () - * { - * const ninjaShapes = this.cache.json.get('ninjas'); - * - * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); - * } - * ``` - * - * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. - * - * If you pas in an `options` object, any settings in there will override those in the config object. - * - * The structure of the JSON file is as follows: - * - * ```text - * { - * 'generator_info': // The name of the application that created the JSON data - * 'shapeName': { - * 'type': // The type of body - * 'label': // Optional body label - * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs - * } - * } - * ``` - * - * At the time of writing, only the Phaser Physics Tracer App exports in this format. - * - * @namespace Phaser.Physics.Matter.PhysicsJSONParser - * @since 3.22.0 - */ -var PhysicsJSONParser = { - - /** - * Parses a body element from the given JSON data. - * - * @function Phaser.Physics.Matter.PhysicsJSONParser.parseBody - * @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 {object} config - The body configuration data. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {MatterJS.BodyType} A Matter JS Body. - */ - parseBody: function (x, y, config, options) - { - if (options === undefined) { options = {}; } - - var body; - var vertexSets = config.vertices; - - if (vertexSets.length === 1) - { - // Just a single Body - options.vertices = vertexSets[0]; - - body = Body.create(options); - - Bodies.flagCoincidentParts(body.parts); - } - else - { - var parts = []; - - for (var i = 0; i < vertexSets.length; i++) - { - var part = Body.create({ - vertices: vertexSets[i] - }); - - parts.push(part); - } - - Bodies.flagCoincidentParts(parts); - - options.parts = parts; - - body = Body.create(options); - } - - body.label = config.label; - - Body.setPosition(body, { x: x, y: y }); - - return body; - } - -}; - -module.exports = PhysicsJSONParser; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = require('./lib/factory/Bodies'); +var Body = require('./lib/body/Body'); + +/** + * Creates a body using the supplied physics data, as provided by a JSON file. + * + * The data file should be loaded as JSON: + * + * ```javascript + * preload () + * { + * this.load.json('ninjas', 'assets/ninjas.json); + * } + * + * create () + * { + * const ninjaShapes = this.cache.json.get('ninjas'); + * + * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); + * } + * ``` + * + * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. + * + * If you pas in an `options` object, any settings in there will override those in the config object. + * + * The structure of the JSON file is as follows: + * + * ```text + * { + * 'generator_info': // The name of the application that created the JSON data + * 'shapeName': { + * 'type': // The type of body + * 'label': // Optional body label + * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs + * } + * } + * ``` + * + * At the time of writing, only the Phaser Physics Tracer App exports in this format. + * + * @namespace Phaser.Physics.Matter.PhysicsJSONParser + * @since 3.22.0 + */ +var PhysicsJSONParser = { + + /** + * Parses a body element from the given JSON data. + * + * @function Phaser.Physics.Matter.PhysicsJSONParser.parseBody + * @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 {object} config - The body configuration data. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {MatterJS.BodyType} A Matter JS Body. + */ + parseBody: function (x, y, config, options) + { + if (options === undefined) { options = {}; } + + var body; + var vertexSets = config.vertices; + + if (vertexSets.length === 1) + { + // Just a single Body + options.vertices = vertexSets[0]; + + body = Body.create(options); + + Bodies.flagCoincidentParts(body.parts); + } + else + { + var parts = []; + + for (var i = 0; i < vertexSets.length; i++) + { + var part = Body.create({ + vertices: vertexSets[i] + }); + + parts.push(part); + } + + Bodies.flagCoincidentParts(parts); + + options.parts = parts; + + body = Body.create(options); + } + + body.label = config.label; + + Body.setPosition(body, { x: x, y: y }); + + return body; + } + +}; + +module.exports = PhysicsJSONParser; diff --git a/src/physics/matter-js/PointerConstraint.js b/src/physics/matter-js/PointerConstraint.js index 87c89f7df..d07d822e1 100644 --- a/src/physics/matter-js/PointerConstraint.js +++ b/src/physics/matter-js/PointerConstraint.js @@ -1,382 +1,382 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bounds = require('./lib/geometry/Bounds'); -var Class = require('../../utils/Class'); -var Composite = require('./lib/body/Composite'); -var Constraint = require('./lib/constraint/Constraint'); -var Detector = require('./lib/collision/Detector'); -var Events = require('./events'); -var InputEvents = require('../../input/events'); -var Merge = require('../../utils/object/Merge'); -var Sleeping = require('./lib/core/Sleeping'); -var Vector2 = require('../../math/Vector2'); -var Vertices = require('./lib/geometry/Vertices'); - -/** - * @classdesc - * A Pointer Constraint is a special type of constraint that allows you to click - * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, - * and when one is pressed down it checks to see if that hit any part of any active - * body in the world. If it did, and the body has input enabled, it will begin to - * drag it until either released, or you stop it via the `stopDrag` method. - * - * You can adjust the stiffness, length and other properties of the constraint via - * the `options` object on creation. - * - * @class PointerConstraint - * @memberof Phaser.Physics.Matter - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - A reference to the Scene to which this Pointer Constraint belongs. - * @param {Phaser.Physics.Matter.World} world - A reference to the Matter World instance to which this Constraint belongs. - * @param {object} [options] - A Constraint configuration object. - */ -var PointerConstraint = new Class({ - - initialize: - - function PointerConstraint (scene, world, options) - { - if (options === undefined) { options = {}; } - - // Defaults - var defaults = { - label: 'Pointer Constraint', - pointA: { x: 0, y: 0 }, - pointB: { x: 0, y: 0 }, - length: 0.01, - stiffness: 0.1, - angularStiffness: 1, - collisionFilter: { - category: 0x0001, - mask: 0xFFFFFFFF, - group: 0 - } - }; - - /** - * A reference to the Scene to which this Pointer Constraint belongs. - * This is the same Scene as the Matter World instance. - * - * @name Phaser.Physics.Matter.PointerConstraint#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Matter World instance to which this Constraint belongs. - * - * @name Phaser.Physics.Matter.PointerConstraint#world - * @type {Phaser.Physics.Matter.World} - * @since 3.0.0 - */ - this.world = world; - - /** - * The Camera the Pointer was interacting with when the input - * down event was processed. - * - * @name Phaser.Physics.Matter.PointerConstraint#camera - * @type {Phaser.Cameras.Scene2D.Camera} - * @since 3.0.0 - */ - this.camera = null; - - /** - * A reference to the Input Pointer that activated this Constraint. - * This is set in the `onDown` handler. - * - * @name Phaser.Physics.Matter.PointerConstraint#pointer - * @type {Phaser.Input.Pointer} - * @default null - * @since 3.0.0 - */ - this.pointer = null; - - /** - * Is this Constraint active or not? - * - * An active constraint will be processed each update. An inactive one will be skipped. - * Use this to toggle a Pointer Constraint on and off. - * - * @name Phaser.Physics.Matter.PointerConstraint#active - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.active = true; - - /** - * The internal transformed position. - * - * @name Phaser.Physics.Matter.PointerConstraint#position - * @type {Phaser.Math.Vector2} - * @since 3.0.0 - */ - this.position = new Vector2(); - - /** - * The body that is currently being dragged, if any. - * - * @name Phaser.Physics.Matter.PointerConstraint#body - * @type {?MatterJS.BodyType} - * @since 3.16.2 - */ - this.body = null; - - /** - * The part of the body that was clicked on to start the drag. - * - * @name Phaser.Physics.Matter.PointerConstraint#part - * @type {?MatterJS.BodyType} - * @since 3.16.2 - */ - this.part = null; - - /** - * The native Matter Constraint that is used to attach to bodies. - * - * @name Phaser.Physics.Matter.PointerConstraint#constraint - * @type {MatterJS.ConstraintType} - * @since 3.0.0 - */ - this.constraint = Constraint.create(Merge(options, defaults)); - - this.world.on(Events.BEFORE_UPDATE, this.update, this); - - scene.sys.input.on(InputEvents.POINTER_DOWN, this.onDown, this); - scene.sys.input.on(InputEvents.POINTER_UP, this.onUp, this); - }, - - /** - * A Pointer has been pressed down onto the Scene. - * - * If this Constraint doesn't have an active Pointer then a hit test is set to - * run against all active bodies in the world during the _next_ call to `update`. - * If a body is found, it is bound to this constraint and the drag begins. - * - * @method Phaser.Physics.Matter.PointerConstraint#onDown - * @since 3.0.0 - * - * @param {Phaser.Input.Pointer} pointer - A reference to the Pointer that was pressed. - */ - onDown: function (pointer) - { - if (!this.pointer) - { - this.pointer = pointer; - this.camera = pointer.camera; - } - }, - - /** - * A Pointer has been released from the Scene. If it was the one this constraint was using, it's cleared. - * - * @method Phaser.Physics.Matter.PointerConstraint#onUp - * @since 3.22.0 - * - * @param {Phaser.Input.Pointer} pointer - A reference to the Pointer that was pressed. - */ - onUp: function (pointer) - { - if (pointer === this.pointer) - { - this.pointer = null; - } - }, - - /** - * Scans all active bodies in the current Matter World to see if any of them - * are hit by the Pointer. The _first one_ found to hit is set as the active contraint - * body. - * - * @method Phaser.Physics.Matter.PointerConstraint#getBody - * @fires Phaser.Physics.Matter.Events#DRAG_START - * @since 3.16.2 - * - * @return {boolean} `true` if a body was found and set, otherwise `false`. - */ - getBody: function (pointer) - { - var pos = this.position; - var constraint = this.constraint; - - this.camera.getWorldPoint(pointer.x, pointer.y, pos); - - var bodies = Composite.allBodies(this.world.localWorld); - - for (var i = 0; i < bodies.length; i++) - { - var body = bodies[i]; - - if (!body.ignorePointer && - Bounds.contains(body.bounds, pos) && - Detector.canCollide(body.collisionFilter, constraint.collisionFilter)) - { - if (this.hitTestBody(body, pos)) - { - this.world.emit(Events.DRAG_START, body, this.part, this); - - return true; - } - } - } - - return false; - }, - - /** - * Scans the current body to determine if a part of it was clicked on. - * If a part is found the body is set as the `constraint.bodyB` property, - * as well as the `body` property of this class. The part is also set. - * - * @method Phaser.Physics.Matter.PointerConstraint#hitTestBody - * @since 3.16.2 - * - * @param {MatterJS.BodyType} body - The Matter Body to check. - * @param {Phaser.Math.Vector2} position - A translated hit test position. - * - * @return {boolean} `true` if a part of the body was hit, otherwise `false`. - */ - hitTestBody: function (body, position) - { - var constraint = this.constraint; - var partsLength = body.parts.length; - - var start = (partsLength > 1) ? 1 : 0; - - for (var i = start; i < partsLength; i++) - { - var part = body.parts[i]; - - if (Vertices.contains(part.vertices, position)) - { - constraint.pointA = position; - constraint.pointB = { x: position.x - body.position.x, y: position.y - body.position.y }; - - constraint.bodyB = body; - constraint.angleB = body.angle; - - Sleeping.set(body, false); - - this.part = part; - this.body = body; - - return true; - } - } - - return false; - }, - - /** - * Internal update handler. Called in the Matter BEFORE_UPDATE step. - * - * @method Phaser.Physics.Matter.PointerConstraint#update - * @fires Phaser.Physics.Matter.Events#DRAG - * @since 3.0.0 - */ - update: function () - { - var pointer = this.pointer; - var body = this.body; - - if (!this.active || !pointer) - { - if (body) - { - this.stopDrag(); - } - - return; - } - - if (!pointer.isDown && body) - { - this.stopDrag(); - - return; - } - else if (pointer.isDown) - { - if (!body && !this.getBody(pointer)) - { - return; - } - - body = this.body; - - var pos = this.position; - var constraint = this.constraint; - - this.camera.getWorldPoint(pointer.x, pointer.y, pos); - - // Drag update - constraint.pointA.x = pos.x; - constraint.pointA.y = pos.y; - - Sleeping.set(body, false); - - this.world.emit(Events.DRAG, body, this); - } - }, - - /** - * Stops the Pointer Constraint from dragging the body any further. - * - * This is called automatically if the Pointer is released while actively - * dragging a body. Or, you can call it manually to release a body from a - * constraint without having to first release the pointer. - * - * @method Phaser.Physics.Matter.PointerConstraint#stopDrag - * @fires Phaser.Physics.Matter.Events#DRAG_END - * @since 3.16.2 - */ - stopDrag: function () - { - var body = this.body; - var constraint = this.constraint; - - constraint.bodyB = null; - constraint.pointB = null; - - this.pointer = null; - this.body = null; - this.part = null; - - if (body) - { - this.world.emit(Events.DRAG_END, body, this); - } - }, - - /** - * Destroys this Pointer Constraint instance and all of its references. - * - * @method Phaser.Physics.Matter.PointerConstraint#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.world.removeConstraint(this.constraint); - - this.pointer = null; - this.constraint = null; - this.body = null; - this.part = null; - - this.world.off(Events.BEFORE_UPDATE, this.update); - - this.scene.sys.input.off(InputEvents.POINTER_DOWN, this.onDown, this); - this.scene.sys.input.off(InputEvents.POINTER_UP, this.onUp, this); - } - -}); - -module.exports = PointerConstraint; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bounds = require('./lib/geometry/Bounds'); +var Class = require('../../utils/Class'); +var Composite = require('./lib/body/Composite'); +var Constraint = require('./lib/constraint/Constraint'); +var Detector = require('./lib/collision/Detector'); +var Events = require('./events'); +var InputEvents = require('../../input/events'); +var Merge = require('../../utils/object/Merge'); +var Sleeping = require('./lib/core/Sleeping'); +var Vector2 = require('../../math/Vector2'); +var Vertices = require('./lib/geometry/Vertices'); + +/** + * @classdesc + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * + * @class PointerConstraint + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene to which this Pointer Constraint belongs. + * @param {Phaser.Physics.Matter.World} world - A reference to the Matter World instance to which this Constraint belongs. + * @param {object} [options] - A Constraint configuration object. + */ +var PointerConstraint = new Class({ + + initialize: + + function PointerConstraint (scene, world, options) + { + if (options === undefined) { options = {}; } + + // Defaults + var defaults = { + label: 'Pointer Constraint', + pointA: { x: 0, y: 0 }, + pointB: { x: 0, y: 0 }, + length: 0.01, + stiffness: 0.1, + angularStiffness: 1, + collisionFilter: { + category: 0x0001, + mask: 0xFFFFFFFF, + group: 0 + } + }; + + /** + * A reference to the Scene to which this Pointer Constraint belongs. + * This is the same Scene as the Matter World instance. + * + * @name Phaser.Physics.Matter.PointerConstraint#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Matter World instance to which this Constraint belongs. + * + * @name Phaser.Physics.Matter.PointerConstraint#world + * @type {Phaser.Physics.Matter.World} + * @since 3.0.0 + */ + this.world = world; + + /** + * The Camera the Pointer was interacting with when the input + * down event was processed. + * + * @name Phaser.Physics.Matter.PointerConstraint#camera + * @type {Phaser.Cameras.Scene2D.Camera} + * @since 3.0.0 + */ + this.camera = null; + + /** + * A reference to the Input Pointer that activated this Constraint. + * This is set in the `onDown` handler. + * + * @name Phaser.Physics.Matter.PointerConstraint#pointer + * @type {Phaser.Input.Pointer} + * @default null + * @since 3.0.0 + */ + this.pointer = null; + + /** + * Is this Constraint active or not? + * + * An active constraint will be processed each update. An inactive one will be skipped. + * Use this to toggle a Pointer Constraint on and off. + * + * @name Phaser.Physics.Matter.PointerConstraint#active + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.active = true; + + /** + * The internal transformed position. + * + * @name Phaser.Physics.Matter.PointerConstraint#position + * @type {Phaser.Math.Vector2} + * @since 3.0.0 + */ + this.position = new Vector2(); + + /** + * The body that is currently being dragged, if any. + * + * @name Phaser.Physics.Matter.PointerConstraint#body + * @type {?MatterJS.BodyType} + * @since 3.16.2 + */ + this.body = null; + + /** + * The part of the body that was clicked on to start the drag. + * + * @name Phaser.Physics.Matter.PointerConstraint#part + * @type {?MatterJS.BodyType} + * @since 3.16.2 + */ + this.part = null; + + /** + * The native Matter Constraint that is used to attach to bodies. + * + * @name Phaser.Physics.Matter.PointerConstraint#constraint + * @type {MatterJS.ConstraintType} + * @since 3.0.0 + */ + this.constraint = Constraint.create(Merge(options, defaults)); + + this.world.on(Events.BEFORE_UPDATE, this.update, this); + + scene.sys.input.on(InputEvents.POINTER_DOWN, this.onDown, this); + scene.sys.input.on(InputEvents.POINTER_UP, this.onUp, this); + }, + + /** + * A Pointer has been pressed down onto the Scene. + * + * If this Constraint doesn't have an active Pointer then a hit test is set to + * run against all active bodies in the world during the _next_ call to `update`. + * If a body is found, it is bound to this constraint and the drag begins. + * + * @method Phaser.Physics.Matter.PointerConstraint#onDown + * @since 3.0.0 + * + * @param {Phaser.Input.Pointer} pointer - A reference to the Pointer that was pressed. + */ + onDown: function (pointer) + { + if (!this.pointer) + { + this.pointer = pointer; + this.camera = pointer.camera; + } + }, + + /** + * A Pointer has been released from the Scene. If it was the one this constraint was using, it's cleared. + * + * @method Phaser.Physics.Matter.PointerConstraint#onUp + * @since 3.22.0 + * + * @param {Phaser.Input.Pointer} pointer - A reference to the Pointer that was pressed. + */ + onUp: function (pointer) + { + if (pointer === this.pointer) + { + this.pointer = null; + } + }, + + /** + * Scans all active bodies in the current Matter World to see if any of them + * are hit by the Pointer. The _first one_ found to hit is set as the active contraint + * body. + * + * @method Phaser.Physics.Matter.PointerConstraint#getBody + * @fires Phaser.Physics.Matter.Events#DRAG_START + * @since 3.16.2 + * + * @return {boolean} `true` if a body was found and set, otherwise `false`. + */ + getBody: function (pointer) + { + var pos = this.position; + var constraint = this.constraint; + + this.camera.getWorldPoint(pointer.x, pointer.y, pos); + + var bodies = Composite.allBodies(this.world.localWorld); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + if (!body.ignorePointer && + Bounds.contains(body.bounds, pos) && + Detector.canCollide(body.collisionFilter, constraint.collisionFilter)) + { + if (this.hitTestBody(body, pos)) + { + this.world.emit(Events.DRAG_START, body, this.part, this); + + return true; + } + } + } + + return false; + }, + + /** + * Scans the current body to determine if a part of it was clicked on. + * If a part is found the body is set as the `constraint.bodyB` property, + * as well as the `body` property of this class. The part is also set. + * + * @method Phaser.Physics.Matter.PointerConstraint#hitTestBody + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Matter Body to check. + * @param {Phaser.Math.Vector2} position - A translated hit test position. + * + * @return {boolean} `true` if a part of the body was hit, otherwise `false`. + */ + hitTestBody: function (body, position) + { + var constraint = this.constraint; + var partsLength = body.parts.length; + + var start = (partsLength > 1) ? 1 : 0; + + for (var i = start; i < partsLength; i++) + { + var part = body.parts[i]; + + if (Vertices.contains(part.vertices, position)) + { + constraint.pointA = position; + constraint.pointB = { x: position.x - body.position.x, y: position.y - body.position.y }; + + constraint.bodyB = body; + constraint.angleB = body.angle; + + Sleeping.set(body, false); + + this.part = part; + this.body = body; + + return true; + } + } + + return false; + }, + + /** + * Internal update handler. Called in the Matter BEFORE_UPDATE step. + * + * @method Phaser.Physics.Matter.PointerConstraint#update + * @fires Phaser.Physics.Matter.Events#DRAG + * @since 3.0.0 + */ + update: function () + { + var pointer = this.pointer; + var body = this.body; + + if (!this.active || !pointer) + { + if (body) + { + this.stopDrag(); + } + + return; + } + + if (!pointer.isDown && body) + { + this.stopDrag(); + + return; + } + else if (pointer.isDown) + { + if (!body && !this.getBody(pointer)) + { + return; + } + + body = this.body; + + var pos = this.position; + var constraint = this.constraint; + + this.camera.getWorldPoint(pointer.x, pointer.y, pos); + + // Drag update + constraint.pointA.x = pos.x; + constraint.pointA.y = pos.y; + + Sleeping.set(body, false); + + this.world.emit(Events.DRAG, body, this); + } + }, + + /** + * Stops the Pointer Constraint from dragging the body any further. + * + * This is called automatically if the Pointer is released while actively + * dragging a body. Or, you can call it manually to release a body from a + * constraint without having to first release the pointer. + * + * @method Phaser.Physics.Matter.PointerConstraint#stopDrag + * @fires Phaser.Physics.Matter.Events#DRAG_END + * @since 3.16.2 + */ + stopDrag: function () + { + var body = this.body; + var constraint = this.constraint; + + constraint.bodyB = null; + constraint.pointB = null; + + this.pointer = null; + this.body = null; + this.part = null; + + if (body) + { + this.world.emit(Events.DRAG_END, body, this); + } + }, + + /** + * Destroys this Pointer Constraint instance and all of its references. + * + * @method Phaser.Physics.Matter.PointerConstraint#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.world.removeConstraint(this.constraint); + + this.pointer = null; + this.constraint = null; + this.body = null; + this.part = null; + + this.world.off(Events.BEFORE_UPDATE, this.update); + + this.scene.sys.input.off(InputEvents.POINTER_DOWN, this.onDown, this); + this.scene.sys.input.off(InputEvents.POINTER_UP, this.onUp, this); + } + +}); + +module.exports = PointerConstraint; diff --git a/src/physics/matter-js/World.js b/src/physics/matter-js/World.js index 35264015c..2301c501f 100644 --- a/src/physics/matter-js/World.js +++ b/src/physics/matter-js/World.js @@ -1,2215 +1,2215 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bodies = require('./lib/factory/Bodies'); -var Body = require('./lib/body/Body'); -var Class = require('../../utils/Class'); -var Common = require('./lib/core/Common'); -var Composite = require('./lib/body/Composite'); -var Engine = require('./lib/core/Engine'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var GetValue = require('../../utils/object/GetValue'); -var MatterBody = require('./lib/body/Body'); -var MatterEvents = require('./lib/core/Events'); -var MatterTileBody = require('./MatterTileBody'); -var MatterWorld = require('./lib/body/World'); -var Vector = require('./lib/geometry/Vector'); - -/** - * @classdesc - * The Matter World class is responsible for managing one single instance of a Matter Physics World for Phaser. - * - * Access this via `this.matter.world` from within a Scene. - * - * This class creates a Matter JS World Composite along with the Matter JS Engine during instantiation. It also - * handles delta timing, bounds, body and constraint creation and debug drawing. - * - * If you wish to access the Matter JS World object directly, see the `localWorld` property. - * If you wish to access the Matter Engine directly, see the `engine` property. - * - * This class is an Event Emitter and will proxy _all_ Matter JS events, as they are received. - * - * @class World - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Physics.Matter - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Matter World instance belongs. - * @param {Phaser.Types.Physics.Matter.MatterWorldConfig} config - The Matter World configuration object. - */ -var World = new Class({ - - Extends: EventEmitter, - - initialize: - - function World (scene, config) - { - EventEmitter.call(this); - - /** - * The Scene to which this Matter World instance belongs. - * - * @name Phaser.Physics.Matter.World#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * An instance of the MatterJS Engine. - * - * @name Phaser.Physics.Matter.World#engine - * @type {MatterJS.Engine} - * @since 3.0.0 - */ - this.engine = Engine.create(config); - - /** - * A `World` composite object that will contain all simulated bodies and constraints. - * - * @name Phaser.Physics.Matter.World#localWorld - * @type {MatterJS.World} - * @since 3.0.0 - */ - this.localWorld = this.engine.world; - - var gravity = GetValue(config, 'gravity', null); - - if (gravity) - { - this.setGravity(gravity.x, gravity.y, gravity.scale); - } - else if (gravity === false) - { - this.setGravity(0, 0, 0); - } - - /** - * An object containing the 4 wall bodies that bound the physics world. - * - * @name Phaser.Physics.Matter.World#walls - * @type {object} - * @since 3.0.0 - */ - this.walls = { left: null, right: null, top: null, bottom: null }; - - /** - * A flag that toggles if the world is enabled or not. - * - * @name Phaser.Physics.Matter.World#enabled - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.enabled = GetValue(config, 'enabled', true); - - /** - * The correction argument is 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. - * - * @name Phaser.Physics.Matter.World#correction - * @type {number} - * @default 1 - * @since 3.4.0 - */ - this.correction = GetValue(config, 'correction', 1); - - /** - * This function is called every time the core game loop steps, which is bound to the - * Request Animation Frame frequency unless otherwise modified. - * - * The function is passed two values: `time` and `delta`, both of which come from the game step values. - * - * It must return a number. This number is used as the delta value passed to Matter.Engine.update. - * - * You can override this function with your own to define your own timestep. - * - * If you need to update the Engine multiple times in a single game step then call - * `World.update` as many times as required. Each call will trigger the `getDelta` function. - * If you wish to have full control over when the Engine updates then see the property `autoUpdate`. - * - * You can also adjust the number of iterations that Engine.update performs. - * Use the Scene Matter Physics config object to set the following properties: - * - * positionIterations (defaults to 6) - * velocityIterations (defaults to 4) - * constraintIterations (defaults to 2) - * - * Adjusting these values can help performance in certain situations, depending on the physics requirements - * of your game. - * - * @name Phaser.Physics.Matter.World#getDelta - * @type {function} - * @since 3.4.0 - */ - this.getDelta = GetValue(config, 'getDelta', this.update60Hz); - - var runnerConfig = GetFastValue(config, 'runner', {}); - - var hasFPS = GetFastValue(runnerConfig, 'fps', false); - - var fps = GetFastValue(runnerConfig, 'fps', 60); - - var delta = GetFastValue(runnerConfig, 'delta', 1000 / fps); - var deltaMin = GetFastValue(runnerConfig, 'deltaMin', 1000 / fps); - var deltaMax = GetFastValue(runnerConfig, 'deltaMax', 1000 / (fps * 0.5)); - - if (!hasFPS) - { - fps = 1000 / delta; - } - - /** - * The Matter JS Runner Configuration object. - * - * This object is populated via the Matter Configuration object's `runner` property and is - * updated constantly during the game step. - * - * @name Phaser.Physics.Matter.World#runner - * @type {Phaser.Types.Physics.Matter.MatterRunnerConfig} - * @since 3.22.0 - */ - this.runner = { - fps: fps, - correction: GetFastValue(runnerConfig, 'correction', 1), - deltaSampleSize: GetFastValue(runnerConfig, 'deltaSampleSize', 60), - counterTimestamp: 0, - frameCounter: 0, - deltaHistory: [], - timePrev: null, - timeScalePrev: 1, - frameRequestId: null, - isFixed: GetFastValue(runnerConfig, 'isFixed', false), - delta: delta, - deltaMin: deltaMin, - deltaMax: deltaMax - }; - - /** - * Automatically call Engine.update every time the game steps. - * If you disable this then you are responsible for calling `World.step` directly from your game. - * If you call `set60Hz` or `set30Hz` then `autoUpdate` is reset to `true`. - * - * @name Phaser.Physics.Matter.World#autoUpdate - * @type {boolean} - * @default true - * @since 3.4.0 - */ - this.autoUpdate = GetValue(config, 'autoUpdate', true); - - var debugConfig = GetValue(config, 'debug', false); - - /** - * A flag that controls if the debug graphics will be drawn to or not. - * - * @name Phaser.Physics.Matter.World#drawDebug - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.drawDebug = (typeof(debugConfig) === 'object') ? true : debugConfig; - - /** - * An instance of the Graphics object the debug bodies are drawn to, if enabled. - * - * @name Phaser.Physics.Matter.World#debugGraphic - * @type {Phaser.GameObjects.Graphics} - * @since 3.0.0 - */ - this.debugGraphic; - - /** - * The debug configuration object. - * - * The values stored in this object are read from the Matter World Config `debug` property. - * - * When a new Body or Constraint is _added to the World_, they are given the values stored in this object, - * unless they have their own `render` object set that will override them. - * - * Note that while you can modify the values of properties in this object at run-time, it will not change - * any of the Matter objects _already added_. It will only impact objects newly added to the world, or one - * that is removed and then re-added at a later time. - * - * @name Phaser.Physics.Matter.World#debugConfig - * @type {Phaser.Types.Physics.Matter.MatterDebugConfig} - * @since 3.22.0 - */ - this.debugConfig = { - showAxes: GetFastValue(debugConfig, 'showAxes', false), - showAngleIndicator: GetFastValue(debugConfig, 'showAngleIndicator', false), - angleColor: GetFastValue(debugConfig, 'angleColor', 0xe81153), - - showBroadphase: GetFastValue(debugConfig, 'showBroadphase', false), - broadphaseColor: GetFastValue(debugConfig, 'broadphaseColor', 0xffb400), - - showBounds: GetFastValue(debugConfig, 'showBounds', false), - boundsColor: GetFastValue(debugConfig, 'boundsColor', 0xffffff), - - showVelocity: GetFastValue(debugConfig, 'showVelocity', false), - velocityColor: GetFastValue(debugConfig, 'velocityColor', 0x00aeef), - - showCollisions: GetFastValue(debugConfig, 'showCollisions', false), - collisionColor: GetFastValue(debugConfig, 'collisionColor', 0xf5950c), - - showSeparations: GetFastValue(debugConfig, 'showSeparations', false), - separationColor: GetFastValue(debugConfig, 'separationColor', 0xffa500), - - showBody: GetFastValue(debugConfig, 'showBody', true), - showStaticBody: GetFastValue(debugConfig, 'showStaticBody', true), - showInternalEdges: GetFastValue(debugConfig, 'showInternalEdges', false), - - renderFill: GetFastValue(debugConfig, 'renderFill', false), - renderLine: GetFastValue(debugConfig, 'renderLine', true), - - fillColor: GetFastValue(debugConfig, 'fillColor', 0x106909), - fillOpacity: GetFastValue(debugConfig, 'fillOpacity', 1), - lineColor: GetFastValue(debugConfig, 'lineColor', 0x28de19), - lineOpacity: GetFastValue(debugConfig, 'lineOpacity', 1), - lineThickness: GetFastValue(debugConfig, 'lineThickness', 1), - - staticFillColor: GetFastValue(debugConfig, 'staticFillColor', 0x0d177b), - staticLineColor: GetFastValue(debugConfig, 'staticLineColor', 0x1327e4), - - showSleeping: GetFastValue(debugConfig, 'showSleeping', false), - staticBodySleepOpacity: GetFastValue(debugConfig, 'staticBodySleepOpacity', 0.7), - sleepFillColor: GetFastValue(debugConfig, 'sleepFillColor', 0x464646), - sleepLineColor: GetFastValue(debugConfig, 'sleepLineColor', 0x999a99), - - showSensors: GetFastValue(debugConfig, 'showSensors', true), - sensorFillColor: GetFastValue(debugConfig, 'sensorFillColor', 0x0d177b), - sensorLineColor: GetFastValue(debugConfig, 'sensorLineColor', 0x1327e4), - - showPositions: GetFastValue(debugConfig, 'showPositions', true), - positionSize: GetFastValue(debugConfig, 'positionSize', 4), - positionColor: GetFastValue(debugConfig, 'positionColor', 0xe042da), - - showJoint: GetFastValue(debugConfig, 'showJoint', true), - jointColor: GetFastValue(debugConfig, 'jointColor', 0xe0e042), - jointLineOpacity: GetFastValue(debugConfig, 'jointLineOpacity', 1), - jointLineThickness: GetFastValue(debugConfig, 'jointLineThickness', 2), - - pinSize: GetFastValue(debugConfig, 'pinSize', 4), - pinColor: GetFastValue(debugConfig, 'pinColor', 0x42e0e0), - - springColor: GetFastValue(debugConfig, 'springColor', 0xe042e0), - - anchorColor: GetFastValue(debugConfig, 'anchorColor', 0xefefef), - anchorSize: GetFastValue(debugConfig, 'anchorSize', 4), - - showConvexHulls: GetFastValue(debugConfig, 'showConvexHulls', false), - hullColor: GetFastValue(debugConfig, 'hullColor', 0xd703d0) - }; - - if (this.drawDebug) - { - this.createDebugGraphic(); - } - - this.setEventsProxy(); - - // Create the walls - - if (GetFastValue(config, 'setBounds', false)) - { - var boundsConfig = config['setBounds']; - - if (typeof boundsConfig === 'boolean') - { - this.setBounds(); - } - else - { - var x = GetFastValue(boundsConfig, 'x', 0); - var y = GetFastValue(boundsConfig, 'y', 0); - var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); - var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); - var thickness = GetFastValue(boundsConfig, 'thickness', 64); - var left = GetFastValue(boundsConfig, 'left', true); - var right = GetFastValue(boundsConfig, 'right', true); - var top = GetFastValue(boundsConfig, 'top', true); - var bottom = GetFastValue(boundsConfig, 'bottom', true); - - this.setBounds(x, y, width, height, thickness, left, right, top, bottom); - } - } - }, - - /** - * Sets the debug render style for the children of the given Matter Composite. - * - * Composites themselves do not render, but they can contain bodies, constraints and other composites that may do. - * So the children of this composite are passed to the `setBodyRenderStyle`, `setCompositeRenderStyle` and - * `setConstraintRenderStyle` methods accordingly. - * - * @method Phaser.Physics.Matter.World#setCompositeRenderStyle - * @since 3.22.0 - * - * @param {MatterJS.CompositeType} composite - The Matter Composite to set the render style on. - * - * @return {this} This Matter World instance for method chaining. - */ - setCompositeRenderStyle: function (composite) - { - var bodies = composite.bodies; - var constraints = composite.constraints; - var composites = composite.composites; - - var i; - var obj; - var render; - - for (i = 0; i < bodies.length; i++) - { - obj = bodies[i]; - render = obj.render; - - this.setBodyRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.fillColor, render.fillOpacity); - } - - for (i = 0; i < constraints.length; i++) - { - obj = constraints[i]; - render = obj.render; - - this.setConstraintRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.pinSize, render.anchorColor, render.anchorSize); - } - - for (i = 0; i < composites.length; i++) - { - obj = composites[i]; - - this.setCompositeRenderStyle(obj); - } - - return this; - }, - - /** - * Sets the debug render style for the given Matter Body. - * - * If you are using this on a Phaser Game Object, such as a Matter Sprite, then pass in the body property - * to this method, not the Game Object itself. - * - * If you wish to skip a parameter, so it retains its current value, pass `false` for it. - * - * If you wish to reset the Body render colors to the defaults found in the World Debug Config, then call - * this method with just the `body` parameter provided and no others. - * - * @method Phaser.Physics.Matter.World#setBodyRenderStyle - * @since 3.22.0 - * - * @param {MatterJS.BodyType} body - The Matter Body to set the render style on. - * @param {number} [lineColor] - The line color. If `null` it will use the World Debug Config value. - * @param {number} [lineOpacity] - The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. - * @param {number} [lineThickness] - The line thickness. If `null` it will use the World Debug Config value. - * @param {number} [fillColor] - The fill color. If `null` it will use the World Debug Config value. - * @param {number} [fillOpacity] - The fill opacity, between 0 and 1. If `null` it will use the World Debug Config value. - * - * @return {this} This Matter World instance for method chaining. - */ - setBodyRenderStyle: function (body, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) - { - var render = body.render; - var config = this.debugConfig; - - if (!render) - { - return this; - } - - if (lineColor === undefined || lineColor === null) - { - lineColor = (body.isStatic) ? config.staticLineColor : config.lineColor; - } - - if (lineOpacity === undefined || lineOpacity === null) - { - lineOpacity = config.lineOpacity; - } - - if (lineThickness === undefined || lineThickness === null) - { - lineThickness = config.lineThickness; - } - - if (fillColor === undefined || fillColor === null) - { - fillColor = (body.isStatic) ? config.staticFillColor : config.fillColor; - } - - if (fillOpacity === undefined || fillOpacity === null) - { - fillOpacity = config.fillOpacity; - } - - if (lineColor !== false) - { - render.lineColor = lineColor; - } - - if (lineOpacity !== false) - { - render.lineOpacity = lineOpacity; - } - - if (lineThickness !== false) - { - render.lineThickness = lineThickness; - } - - if (fillColor !== false) - { - render.fillColor = fillColor; - } - - if (fillOpacity !== false) - { - render.fillOpacity = fillOpacity; - } - - return this; - }, - - /** - * Sets the debug render style for the given Matter Constraint. - * - * If you are using this on a Phaser Game Object, then pass in the body property - * to this method, not the Game Object itself. - * - * If you wish to skip a parameter, so it retains its current value, pass `false` for it. - * - * If you wish to reset the Constraint render colors to the defaults found in the World Debug Config, then call - * this method with just the `constraint` parameter provided and no others. - * - * @method Phaser.Physics.Matter.World#setConstraintRenderStyle - * @since 3.22.0 - * - * @param {MatterJS.ConstraintType} constraint - The Matter Constraint to set the render style on. - * @param {number} [lineColor] - The line color. If `null` it will use the World Debug Config value. - * @param {number} [lineOpacity] - The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. - * @param {number} [lineThickness] - The line thickness. If `null` it will use the World Debug Config value. - * @param {number} [pinSize] - If this constraint is a pin, this sets the size of the pin circle. If `null` it will use the World Debug Config value. - * @param {number} [anchorColor] - The color used when rendering this constraints anchors. If `null` it will use the World Debug Config value. - * @param {number} [anchorSize] - The size of the anchor circle, if this constraint has anchors. If `null` it will use the World Debug Config value. - * - * @return {this} This Matter World instance for method chaining. - */ - setConstraintRenderStyle: function (constraint, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize) - { - var render = constraint.render; - var config = this.debugConfig; - - if (!render) - { - return this; - } - - // Reset them - if (lineColor === undefined || lineColor === null) - { - var type = render.type; - - if (type === 'line') - { - lineColor = config.jointColor; - } - else if (type === 'pin') - { - lineColor = config.pinColor; - } - else if (type === 'spring') - { - lineColor = config.springColor; - } - } - - if (lineOpacity === undefined || lineOpacity === null) - { - lineOpacity = config.jointLineOpacity; - } - - if (lineThickness === undefined || lineThickness === null) - { - lineThickness = config.jointLineThickness; - } - - if (pinSize === undefined || pinSize === null) - { - pinSize = config.pinSize; - } - - if (anchorColor === undefined || anchorColor === null) - { - anchorColor = config.anchorColor; - } - - if (anchorSize === undefined || anchorSize === null) - { - anchorSize = config.anchorSize; - } - - if (lineColor !== false) - { - render.lineColor = lineColor; - } - - if (lineOpacity !== false) - { - render.lineOpacity = lineOpacity; - } - - if (lineThickness !== false) - { - render.lineThickness = lineThickness; - } - - if (pinSize !== false) - { - render.pinSize = pinSize; - } - - if (anchorColor !== false) - { - render.anchorColor = anchorColor; - } - - if (anchorSize !== false) - { - render.anchorSize = anchorSize; - } - - return this; - }, - - /** - * This internal method acts as a proxy between all of the Matter JS events and then re-emits them - * via this class. - * - * @method Phaser.Physics.Matter.World#setEventsProxy - * @since 3.0.0 - */ - setEventsProxy: function () - { - var _this = this; - var engine = this.engine; - var world = this.localWorld; - - // Inject debug styles - - if (this.drawDebug) - { - MatterEvents.on(world, 'compositeModified', function (composite) - { - _this.setCompositeRenderStyle(composite); - }); - - MatterEvents.on(world, 'beforeAdd', function (event) - { - var objects = [].concat(event.object); - - for (var i = 0; i < objects.length; i++) - { - var obj = objects[i]; - var render = obj.render; - - if (obj.type === 'body') - { - _this.setBodyRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.fillColor, render.fillOpacity); - } - else if (obj.type === 'composite') - { - _this.setCompositeRenderStyle(obj); - } - else if (obj.type === 'constraint') - { - _this.setConstraintRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.pinSize, render.anchorColor, render.anchorSize); - } - } - }); - } - - MatterEvents.on(world, 'beforeAdd', function (event) - { - _this.emit(Events.BEFORE_ADD, event); - }); - - MatterEvents.on(world, 'afterAdd', function (event) - { - _this.emit(Events.AFTER_ADD, event); - }); - - MatterEvents.on(world, 'beforeRemove', function (event) - { - _this.emit(Events.BEFORE_REMOVE, event); - }); - - MatterEvents.on(world, 'afterRemove', function (event) - { - _this.emit(Events.AFTER_REMOVE, event); - }); - - MatterEvents.on(engine, 'beforeUpdate', function (event) - { - _this.emit(Events.BEFORE_UPDATE, event); - }); - - MatterEvents.on(engine, 'afterUpdate', function (event) - { - _this.emit(Events.AFTER_UPDATE, event); - }); - - MatterEvents.on(engine, 'collisionStart', function (event) - { - var pairs = event.pairs; - var bodyA; - var bodyB; - - if (pairs.length > 0) - { - bodyA = pairs[0].bodyA; - bodyB = pairs[0].bodyB; - } - - _this.emit(Events.COLLISION_START, event, bodyA, bodyB); - }); - - MatterEvents.on(engine, 'collisionActive', function (event) - { - var pairs = event.pairs; - var bodyA; - var bodyB; - - if (pairs.length > 0) - { - bodyA = pairs[0].bodyA; - bodyB = pairs[0].bodyB; - } - - _this.emit(Events.COLLISION_ACTIVE, event, bodyA, bodyB); - }); - - MatterEvents.on(engine, 'collisionEnd', function (event) - { - var pairs = event.pairs; - var bodyA; - var bodyB; - - if (pairs.length > 0) - { - bodyA = pairs[0].bodyA; - bodyB = pairs[0].bodyB; - } - - _this.emit(Events.COLLISION_END, event, bodyA, bodyB); - }); - }, - - /** - * Sets the bounds of the Physics world to match the given world pixel dimensions. - * You can optionally set which 'walls' to create: left, right, top or bottom. - * If none of the walls are given it will default to use the walls settings it had previously. - * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size - * the newly created bounds will also not have the left and right walls. - * Explicitly state them in the parameters to override this. - * - * @method Phaser.Physics.Matter.World#setBounds - * @since 3.0.0 - * - * @param {number} [x=0] - The x coordinate of the top-left corner of the bounds. - * @param {number} [y=0] - The y coordinate of the top-left corner of the bounds. - * @param {number} [width] - The width of the bounds. - * @param {number} [height] - The height of the bounds. - * @param {number} [thickness=64] - The thickness of each wall, in pixels. - * @param {boolean} [left=true] - If true will create the left bounds wall. - * @param {boolean} [right=true] - If true will create the right bounds wall. - * @param {boolean} [top=true] - If true will create the top bounds wall. - * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. - * - * @return {Phaser.Physics.Matter.World} This Matter World object. - */ - setBounds: function (x, y, width, height, thickness, left, right, top, bottom) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.scene.sys.scale.width; } - if (height === undefined) { height = this.scene.sys.scale.height; } - if (thickness === undefined) { thickness = 64; } - if (left === undefined) { left = true; } - if (right === undefined) { right = true; } - if (top === undefined) { top = true; } - if (bottom === undefined) { bottom = true; } - - this.updateWall(left, 'left', x - thickness, y - thickness, thickness, height + (thickness * 2)); - this.updateWall(right, 'right', x + width, y - thickness, thickness, height + (thickness * 2)); - this.updateWall(top, 'top', x, y - thickness, width, thickness); - this.updateWall(bottom, 'bottom', x, y + height, width, thickness); - - return this; - }, - - /** - * Updates the 4 rectangle bodies that were created, if `setBounds` was set in the Matter config, to use - * the new positions and sizes. This method is usually only called internally via the `setBounds` method. - * - * @method Phaser.Physics.Matter.World#updateWall - * @since 3.0.0 - * - * @param {boolean} add - `true` if the walls are being added or updated, `false` to remove them from the world. - * @param {string} [position] - Either `left`, `right`, `top` or `bottom`. Only optional if `add` is `false`. - * @param {number} [x] - The horizontal position to place the walls at. Only optional if `add` is `false`. - * @param {number} [y] - The vertical position to place the walls at. Only optional if `add` is `false`. - * @param {number} [width] - The width of the walls, in pixels. Only optional if `add` is `false`. - * @param {number} [height] - The height of the walls, in pixels. Only optional if `add` is `false`. - */ - updateWall: function (add, position, x, y, width, height) - { - var wall = this.walls[position]; - - if (add) - { - if (wall) - { - MatterWorld.remove(this.localWorld, wall); - } - - // adjust center - x += (width / 2); - y += (height / 2); - - this.walls[position] = this.create(x, y, width, height, { isStatic: true, friction: 0, frictionStatic: 0 }); - } - else - { - if (wall) - { - MatterWorld.remove(this.localWorld, wall); - } - - this.walls[position] = null; - } - }, - - /** - * Creates a Phaser.GameObjects.Graphics object that is used to render all of the debug bodies and joints to. - * - * This method is called automatically by the constructor, if debugging has been enabled. - * - * The created Graphics object is automatically added to the Scene at 0x0 and given a depth of `Number.MAX_VALUE`, - * so it renders above all else in the Scene. - * - * The Graphics object is assigned to the `debugGraphic` property of this class and `drawDebug` is enabled. - * - * @method Phaser.Physics.Matter.World#createDebugGraphic - * @since 3.0.0 - * - * @return {Phaser.GameObjects.Graphics} The newly created Graphics object. - */ - createDebugGraphic: function () - { - var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); - - graphic.setDepth(Number.MAX_VALUE); - - this.debugGraphic = graphic; - - this.drawDebug = true; - - return graphic; - }, - - /** - * Sets the world gravity and gravity scale to 0. - * - * @method Phaser.Physics.Matter.World#disableGravity - * @since 3.0.0 - * - * @return {this} This Matter World object. - */ - disableGravity: function () - { - this.localWorld.gravity.x = 0; - this.localWorld.gravity.y = 0; - this.localWorld.gravity.scale = 0; - - return this; - }, - - /** - * Sets the worlds gravity to the values given. - * - * Gravity effects all bodies in the world, unless they have the `ignoreGravity` flag set. - * - * @method Phaser.Physics.Matter.World#setGravity - * @since 3.0.0 - * - * @param {number} [x=0] - The world gravity x component. - * @param {number} [y=1] - The world gravity y component. - * @param {number} [scale=0.001] - The gravity scale factor. - * - * @return {this} This Matter World object. - */ - setGravity: function (x, y, scale) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 1; } - - this.localWorld.gravity.x = x; - this.localWorld.gravity.y = y; - - if (scale !== undefined) - { - this.localWorld.gravity.scale = scale; - } - - return this; - }, - - /** - * Creates a rectangle Matter body and adds it to the world. - * - * @method Phaser.Physics.Matter.World#create - * @since 3.0.0 - * - * @param {number} x - The horizontal position of the body in the world. - * @param {number} y - The vertical position of the body in the world. - * @param {number} width - The width of the body. - * @param {number} height - The height of the body. - * @param {object} options - Optional Matter configuration object. - * - * @return {MatterJS.BodyType} The Matter.js body that was created. - */ - create: function (x, y, width, height, options) - { - var body = Bodies.rectangle(x, y, width, height, options); - - MatterWorld.add(this.localWorld, body); - - return body; - }, - - /** - * Adds a Matter JS object, or array of objects, to the world. - * - * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. - * - * Triggers `beforeAdd` and `afterAdd` events. - * - * @method Phaser.Physics.Matter.World#add - * @since 3.0.0 - * - * @param {(object|object[])} object - Can be single object, or an array, and can be a body, composite or constraint. - * - * @return {this} This Matter World object. - */ - add: function (object) - { - MatterWorld.add(this.localWorld, object); - - return this; - }, - - /** - * Removes a Matter JS object, or array of objects, from the world. - * - * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. - * - * Triggers `beforeRemove` and `afterRemove` events. - * - * @method Phaser.Physics.Matter.World#remove - * @since 3.0.0 - * - * @param {(object|object[])} object - Can be single object, or an array, and can be a body, composite or constraint. - * @param {boolean} [deep=false] - Optionally search the objects children and recursively remove those as well. - * - * @return {this} This Matter World object. - */ - remove: function (object, deep) - { - if (!Array.isArray(object)) - { - object = [ object ]; - } - - for (var i = 0; i < object.length; i++) - { - var entity = object[i]; - - var body = (entity.body) ? entity.body : entity; - - Composite.remove(this.localWorld, body, deep); - } - - return this; - }, - - /** - * Removes a Matter JS constraint, or array of constraints, from the world. - * - * Triggers `beforeRemove` and `afterRemove` events. - * - * @method Phaser.Physics.Matter.World#removeConstraint - * @since 3.0.0 - * - * @param {(MatterJS.ConstraintType|MatterJS.ConstraintType[])} constraint - A Matter JS Constraint, or an array of constraints, to be removed. - * @param {boolean} [deep=false] - Optionally search the objects children and recursively remove those as well. - * - * @return {this} This Matter World object. - */ - removeConstraint: function (constraint, deep) - { - Composite.remove(this.localWorld, constraint, deep); - - return this; - }, - - /** - * Adds `MatterTileBody` instances for all the colliding tiles within the given tilemap layer. - * - * Set the appropriate tiles in your layer to collide before calling this method! - * - * @method Phaser.Physics.Matter.World#convertTilemapLayer - * @since 3.0.0 - * - * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - - * An array of tiles. - * @param {object} [options] - Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} - * - * @return {this} This Matter World object. - */ - convertTilemapLayer: function (tilemapLayer, options) - { - var layerData = tilemapLayer.layer; - var tiles = tilemapLayer.getTilesWithin(0, 0, layerData.width, layerData.height, { isColliding: true }); - - this.convertTiles(tiles, options); - - return this; - }, - - /** - * Adds `MatterTileBody` instances for the given tiles. This adds bodies regardless of whether the - * tiles are set to collide or not. - * - * @method Phaser.Physics.Matter.World#convertTiles - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.Tile[]} tiles - An array of tiles. - * @param {object} [options] - Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} - * - * @return {this} This Matter World object. - */ - convertTiles: function (tiles, options) - { - if (tiles.length === 0) - { - return this; - } - - for (var i = 0; i < tiles.length; i++) - { - new MatterTileBody(this, tiles[i], options); - } - - return this; - }, - - /** - * Returns the next unique group index for which bodies will collide. - * If `isNonColliding` is `true`, returns the next unique group index for which bodies will not collide. - * - * @method Phaser.Physics.Matter.World#nextGroup - * @since 3.0.0 - * - * @param {boolean} [isNonColliding=false] - If `true`, returns the next unique group index for which bodies will _not_ collide. - * - * @return {number} Unique category bitfield - */ - nextGroup: function (isNonColliding) - { - return MatterBody.nextGroup(isNonColliding); - }, - - /** - * Returns the next unique category bitfield (starting after the initial default category 0x0001). - * There are 32 available. - * - * @method Phaser.Physics.Matter.World#nextCategory - * @since 3.0.0 - * - * @return {number} Unique category bitfield - */ - nextCategory: function () - { - return MatterBody.nextCategory(); - }, - - /** - * Pauses this Matter World instance and sets `enabled` to `false`. - * - * A paused world will not run any simulations for the duration it is paused. - * - * @method Phaser.Physics.Matter.World#pause - * @fires Phaser.Physics.Matter.Events#PAUSE - * @since 3.0.0 - * - * @return {this} This Matter World object. - */ - pause: function () - { - this.enabled = false; - - this.emit(Events.PAUSE); - - return this; - }, - - /** - * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. - * - * @method Phaser.Physics.Matter.World#resume - * @fires Phaser.Physics.Matter.Events#RESUME - * @since 3.0.0 - * - * @return {this} This Matter World object. - */ - resume: function () - { - this.enabled = true; - - this.emit(Events.RESUME); - - return this; - }, - - /** - * 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. - */ - update: function (time, delta) - { - if (!this.enabled || !this.autoUpdate) - { - return; - } - - var engine = this.engine; - var runner = this.runner; - - var timing = engine.timing; - var correction = this.correction; - - if (runner.isFixed) - { - // fixed timestep - delta = this.getDelta(time, delta); - } - else - { - // dynamic timestep based on wall clock between calls - delta = (time - runner.timePrev) || runner.delta; - runner.timePrev = time; - - // optimistically filter delta over a few frames, to improve stability - runner.deltaHistory.push(delta); - runner.deltaHistory = runner.deltaHistory.slice(-runner.deltaSampleSize); - delta = Math.min.apply(null, runner.deltaHistory); - - // limit delta - delta = delta < runner.deltaMin ? runner.deltaMin : delta; - delta = delta > runner.deltaMax ? runner.deltaMax : delta; - - // correction for delta - correction = delta / runner.delta; - - // update engine timing object - runner.delta = delta; - } - - // time correction for time scaling - if (runner.timeScalePrev !== 0) - { - correction *= timing.timeScale / runner.timeScalePrev; - } - - if (timing.timeScale === 0) - { - correction = 0; - } - - runner.timeScalePrev = timing.timeScale; - runner.correction = correction; - - // fps counter - runner.frameCounter += 1; - - if (time - runner.counterTimestamp >= 1000) - { - runner.fps = runner.frameCounter * ((time - runner.counterTimestamp) / 1000); - runner.counterTimestamp = time; - runner.frameCounter = 0; - } - - Engine.update(engine, delta, correction); - }, - - /** - * Manually advances the physics simulation by one iteration. - * - * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. - * If undefined they use the Matter defaults of 60Hz and no correction. - * - * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. - * - * It also ignores any custom `getDelta` functions, as you should be passing the delta - * value in to this call. - * - * You can adjust the number of iterations that Engine.update performs internally. - * Use the Scene Matter Physics config object to set the following properties: - * - * positionIterations (defaults to 6) - * velocityIterations (defaults to 4) - * constraintIterations (defaults to 2) - * - * Adjusting these values can help performance in certain situations, depending on the physics requirements - * of your game. - * - * @method Phaser.Physics.Matter.World#step - * @since 3.4.0 - * - * @param {number} [delta=16.666] - The delta value. - * @param {number} [correction=1] - Optional delta correction value. - */ - step: function (delta, correction) - { - Engine.update(this.engine, delta, correction); - }, - - /** - * Runs the Matter Engine.update at a fixed timestep of 60Hz. - * - * @method Phaser.Physics.Matter.World#update60Hz - * @since 3.4.0 - * - * @return {number} The delta value to be passed to Engine.update. - */ - update60Hz: function () - { - return 1000 / 60; - }, - - /** - * Runs the Matter Engine.update at a fixed timestep of 30Hz. - * - * @method Phaser.Physics.Matter.World#update30Hz - * @since 3.4.0 - * - * @return {number} The delta value to be passed to Engine.update. - */ - update30Hz: function () - { - return 1000 / 30; - }, - - /** - * Returns `true` if the given body can be found within the World. - * - * @method Phaser.Physics.Matter.World#has - * @since 3.22.0 - * - * @param {(MatterJS.Body|Phaser.GameObjects.GameObject)} body - The Matter Body, or Game Object, to search for within the world. - * - * @return {MatterJS.BodyType[]} An array of all the Matter JS Bodies in this World. - */ - has: function (body) - { - var src = (body.hasOwnProperty('body')) ? body.body : body; - - return (Composite.get(this.localWorld, src.id, src.type) !== null); - }, - - /** - * Returns all the bodies in the Matter World, including all bodies in children, recursively. - * - * @method Phaser.Physics.Matter.World#getAllBodies - * @since 3.22.0 - * - * @return {MatterJS.BodyType[]} An array of all the Matter JS Bodies in this World. - */ - getAllBodies: function () - { - return Composite.allBodies(this.localWorld); - }, - - /** - * Returns all the constraints in the Matter World, including all constraints in children, recursively. - * - * @method Phaser.Physics.Matter.World#getAllConstraints - * @since 3.22.0 - * - * @return {MatterJS.ConstraintType[]} An array of all the Matter JS Constraints in this World. - */ - getAllConstraints: function () - { - return Composite.allConstraints(this.localWorld); - }, - - /** - * Returns all the composites in the Matter World, including all composites in children, recursively. - * - * @method Phaser.Physics.Matter.World#getAllComposites - * @since 3.22.0 - * - * @return {MatterJS.CompositeType[]} An array of all the Matter JS Composites in this World. - */ - getAllComposites: function () - { - return Composite.allComposites(this.localWorld); - }, - - /** - * Handles the rendering of bodies and debug information to the debug Graphics object, if enabled. - * - * This method is called automatically by the Scene after all processing has taken place. - * - * @method Phaser.Physics.Matter.World#postUpdate - * @private - * @since 3.0.0 - */ - postUpdate: function () - { - if (!this.drawDebug) - { - return; - } - - var config = this.debugConfig; - var engine = this.engine; - var graphics = this.debugGraphic; - - var bodies = Composite.allBodies(this.localWorld); - - this.debugGraphic.clear(); - - if (config.showBroadphase && engine.broadphase.controller) - { - this.renderGrid(engine.broadphase, graphics, config.broadphaseColor, 0.5); - } - - if (config.showBounds) - { - this.renderBodyBounds(bodies, graphics, config.boundsColor, 0.5); - } - - if (config.showBody || config.showStaticBody) - { - this.renderBodies(bodies); - } - - if (config.showJoint) - { - this.renderJoints(); - } - - if (config.showAxes || config.showAngleIndicator) - { - this.renderBodyAxes(bodies, graphics, config.showAxes, config.angleColor, 0.5); - } - - if (config.showVelocity) - { - this.renderBodyVelocity(bodies, graphics, config.velocityColor, 1, 2); - } - - if (config.showSeparations) - { - this.renderSeparations(engine.pairs.list, graphics, config.separationColor); - } - - if (config.showCollisions) - { - this.renderCollisions(engine.pairs.list, graphics, config.collisionColor); - } - }, - - /** - * Renders the Engine Broadphase Controller Grid to the given Graphics instance. - * - * The debug renderer calls this method if the `showBroadphase` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render the Grid to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderGrid - * @since 3.22.0 - * - * @param {MatterJS.Grid} grid - The Matter Grid to be rendered. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} lineColor - The line color. - * @param {number} lineOpacity - The line opacity, between 0 and 1. - * - * @return {this} This Matter World instance for method chaining. - */ - renderGrid: function (grid, graphics, lineColor, lineOpacity) - { - graphics.lineStyle(1, lineColor, lineOpacity); - - var bucketKeys = Common.keys(grid.buckets); - - for (var i = 0; i < bucketKeys.length; i++) - { - var bucketId = bucketKeys[i]; - - if (grid.buckets[bucketId].length < 2) - { - continue; - } - - var region = bucketId.split(/C|R/); - - graphics.strokeRect( - parseInt(region[1], 10) * grid.bucketWidth, - parseInt(region[2], 10) * grid.bucketHeight, - grid.bucketWidth, - grid.bucketHeight - ); - } - - return this; - }, - - /** - * Renders the list of Pair separations to the given Graphics instance. - * - * The debug renderer calls this method if the `showSeparations` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render the Grid to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderSeparations - * @since 3.22.0 - * - * @param {MatterJS.Pair[]} pairs - An array of Matter Pairs to be rendered. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} lineColor - The line color. - * - * @return {this} This Matter World instance for method chaining. - */ - renderSeparations: function (pairs, graphics, lineColor) - { - graphics.lineStyle(1, lineColor, 1); - - for (var i = 0; i < pairs.length; i++) - { - var pair = pairs[i]; - - if (!pair.isActive) - { - continue; - } - - var collision = pair.collision; - var bodyA = collision.bodyA; - var bodyB = collision.bodyB; - var posA = bodyA.position; - var posB = bodyB.position; - var penetration = collision.penetration; - - var k = (!bodyA.isStatic && !bodyB.isStatic) ? 4 : 1; - - if (bodyB.isStatic) - { - k = 0; - } - - graphics.lineBetween( - posB.x, - posB.y, - posB.x - (penetration.x * k), - posB.y - (penetration.y * k) - ); - - k = (!bodyA.isStatic && !bodyB.isStatic) ? 4 : 1; - - if (bodyA.isStatic) - { - k = 0; - } - - graphics.lineBetween( - posA.x, - posA.y, - posA.x - (penetration.x * k), - posA.y - (penetration.y * k) - ); - } - - return this; - }, - - /** - * Renders the list of collision points and normals to the given Graphics instance. - * - * The debug renderer calls this method if the `showCollisions` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render the Grid to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderCollisions - * @since 3.22.0 - * - * @param {MatterJS.Pair[]} pairs - An array of Matter Pairs to be rendered. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} lineColor - The line color. - * - * @return {this} This Matter World instance for method chaining. - */ - renderCollisions: function (pairs, graphics, lineColor) - { - graphics.lineStyle(1, lineColor, 0.5); - graphics.fillStyle(lineColor, 1); - - var i; - var pair; - - // Collision Positions - - for (i = 0; i < pairs.length; i++) - { - pair = pairs[i]; - - if (!pair.isActive) - { - continue; - } - - for (var j = 0; j < pair.activeContacts.length; j++) - { - var contact = pair.activeContacts[j]; - var vertex = contact.vertex; - - graphics.fillRect(vertex.x - 2, vertex.y - 2, 5, 5); - } - } - - // Collision Normals - - for (i = 0; i < pairs.length; i++) - { - pair = pairs[i]; - - if (!pair.isActive) - { - continue; - } - - var collision = pair.collision; - var contacts = pair.activeContacts; - - if (contacts.length > 0) - { - var normalPosX = contacts[0].vertex.x; - var normalPosY = contacts[0].vertex.y; - - if (contacts.length === 2) - { - normalPosX = (contacts[0].vertex.x + contacts[1].vertex.x) / 2; - normalPosY = (contacts[0].vertex.y + contacts[1].vertex.y) / 2; - } - - if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic) - { - graphics.lineBetween( - normalPosX - collision.normal.x * 8, - normalPosY - collision.normal.y * 8, - normalPosX, - normalPosY - ); - } - else - { - graphics.lineBetween( - normalPosX + collision.normal.x * 8, - normalPosY + collision.normal.y * 8, - normalPosX, - normalPosY - ); - } - } - } - - return this; - }, - - /** - * Renders the bounds of an array of Bodies to the given Graphics instance. - * - * If the body is a compound body, it will render the bounds for the parent compound. - * - * The debug renderer calls this method if the `showBounds` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render bounds to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderBodyBounds - * @since 3.22.0 - * - * @param {array} bodies - An array of bodies from the localWorld. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} lineColor - The line color. - * @param {number} lineOpacity - The line opacity, between 0 and 1. - */ - renderBodyBounds: function (bodies, graphics, lineColor, lineOpacity) - { - graphics.lineStyle(1, lineColor, lineOpacity); - - for (var i = 0; i < bodies.length; i++) - { - var body = bodies[i]; - - // 1) Don't show invisible bodies - if (!body.render.visible) - { - continue; - } - - var bounds = body.bounds; - - if (bounds) - { - graphics.strokeRect( - bounds.min.x, - bounds.min.y, - bounds.max.x - bounds.min.x, - bounds.max.y - bounds.min.y - ); - } - else - { - var parts = body.parts; - - for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) - { - var part = parts[j]; - - graphics.strokeRect( - part.bounds.min.x, - part.bounds.min.y, - part.bounds.max.x - part.bounds.min.x, - part.bounds.max.y - part.bounds.min.y - ); - } - } - } - - return this; - }, - - /** - * Renders either all axes, or a single axis indicator, for an array of Bodies, to the given Graphics instance. - * - * The debug renderer calls this method if the `showAxes` or `showAngleIndicator` config values are set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render bounds to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderBodyAxes - * @since 3.22.0 - * - * @param {array} bodies - An array of bodies from the localWorld. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {boolean} showAxes - If `true` it will render all body axes. If `false` it will render a single axis indicator. - * @param {number} lineColor - The line color. - * @param {number} lineOpacity - The line opacity, between 0 and 1. - */ - renderBodyAxes: function (bodies, graphics, showAxes, lineColor, lineOpacity) - { - graphics.lineStyle(1, lineColor, lineOpacity); - - for (var i = 0; i < bodies.length; i++) - { - var body = bodies[i]; - var parts = body.parts; - - // 1) Don't show invisible bodies - if (!body.render.visible) - { - continue; - } - - var part; - var j; - var k; - - if (showAxes) - { - for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) - { - part = parts[j]; - - for (k = 0; k < part.axes.length; k++) - { - var axis = part.axes[k]; - - graphics.lineBetween( - part.position.x, - part.position.y, - part.position.x + axis.x * 20, - part.position.y + axis.y * 20 - ); - } - } - } - else - { - for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) - { - part = parts[j]; - - for (k = 0; k < part.axes.length; k++) - { - graphics.lineBetween( - part.position.x, - part.position.y, - (part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2, - (part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2 - ); - } - } - } - } - - return this; - }, - - /** - * Renders a velocity indicator for an array of Bodies, to the given Graphics instance. - * - * The debug renderer calls this method if the `showVelocity` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render bounds to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderBodyVelocity - * @since 3.22.0 - * - * @param {array} bodies - An array of bodies from the localWorld. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} lineColor - The line color. - * @param {number} lineOpacity - The line opacity, between 0 and 1. - * @param {number} lineThickness - The line thickness. - */ - renderBodyVelocity: function (bodies, graphics, lineColor, lineOpacity, lineThickness) - { - graphics.lineStyle(lineThickness, lineColor, lineOpacity); - - for (var i = 0; i < bodies.length; i++) - { - var body = bodies[i]; - - // 1) Don't show invisible bodies - if (!body.render.visible) - { - continue; - } - - graphics.lineBetween( - body.position.x, - body.position.y, - body.position.x + (body.position.x - body.positionPrev.x) * 2, - body.position.y + (body.position.y - body.positionPrev.y) * 2 - ); - } - - return this; - }, - - /** - * Renders the given array of Bodies to the debug graphics instance. - * - * Called automatically by the `postUpdate` method. - * - * @method Phaser.Physics.Matter.World#renderBodies - * @private - * @since 3.14.0 - * - * @param {array} bodies - An array of bodies from the localWorld. - */ - renderBodies: function (bodies) - { - var graphics = this.debugGraphic; - - var config = this.debugConfig; - - var showBody = config.showBody; - var showStaticBody = config.showStaticBody; - var showSleeping = config.showSleeping; - var showInternalEdges = config.showInternalEdges; - var showConvexHulls = config.showConvexHulls; - - var renderFill = config.renderFill; - var renderLine = config.renderLine; - - var staticBodySleepOpacity = config.staticBodySleepOpacity; - var sleepFillColor = config.sleepFillColor; - var sleepLineColor = config.sleepLineColor; - - var hullColor = config.hullColor; - - for (var i = 0; i < bodies.length; i++) - { - var body = bodies[i]; - - // 1) Don't show invisible bodies - if (!body.render.visible) - { - continue; - } - - // 2) Don't show static bodies, OR - // 3) Don't show dynamic bodies - if ((!showStaticBody && body.isStatic) || (!showBody && !body.isStatic)) - { - continue; - } - - var lineColor = body.render.lineColor; - var lineOpacity = body.render.lineOpacity; - var lineThickness = body.render.lineThickness; - var fillColor = body.render.fillColor; - var fillOpacity = body.render.fillOpacity; - - if (showSleeping && body.isSleeping) - { - if (body.isStatic) - { - lineOpacity *= staticBodySleepOpacity; - fillOpacity *= staticBodySleepOpacity; - } - else - { - lineColor = sleepLineColor; - fillColor = sleepFillColor; - } - } - - if (!renderFill) - { - fillColor = null; - } - - if (!renderLine) - { - lineColor = null; - } - - this.renderBody(body, graphics, showInternalEdges, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity); - - var partsLength = body.parts.length; - - if (showConvexHulls && partsLength > 1) - { - this.renderConvexHull(body, graphics, hullColor, lineThickness); - } - } - }, - - /** - * Renders a single Matter Body to the given Phaser Graphics Game Object. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render a Body to your own Graphics instance. - * - * If you don't wish to render a line around the body, set the `lineColor` parameter to `null`. - * Equally, if you don't wish to render a fill, set the `fillColor` parameter to `null`. - * - * @method Phaser.Physics.Matter.World#renderBody - * @since 3.22.0 - * - * @param {MatterJS.BodyType} body - The Matter Body to be rendered. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {boolean} showInternalEdges - Render internal edges of the polygon? - * @param {number} [lineColor] - The line color. - * @param {number} [lineOpacity] - The line opacity, between 0 and 1. - * @param {number} [lineThickness=1] - The line thickness. - * @param {number} [fillColor] - The fill color. - * @param {number} [fillOpacity] - The fill opacity, between 0 and 1. - * - * @return {this} This Matter World instance for method chaining. - */ - renderBody: function (body, graphics, showInternalEdges, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) - { - if (lineColor === undefined) { lineColor = null; } - if (lineOpacity === undefined) { lineOpacity = null; } - if (lineThickness === undefined) { lineThickness = 1; } - if (fillColor === undefined) { fillColor = null; } - if (fillOpacity === undefined) { fillOpacity = null; } - - var config = this.debugConfig; - - var sensorFillColor = config.sensorFillColor; - var sensorLineColor = config.sensorLineColor; - - // Handle compound parts - var parts = body.parts; - var partsLength = parts.length; - - for (var k = (partsLength > 1) ? 1 : 0; k < partsLength; k++) - { - var part = parts[k]; - var render = part.render; - var opacity = render.opacity; - - if (!render.visible || opacity === 0 || (part.isSensor && !config.showSensors)) - { - continue; - } - - // Part polygon - var circleRadius = part.circleRadius; - - graphics.beginPath(); - - if (part.isSensor) - { - if (fillColor !== null) - { - graphics.fillStyle(sensorFillColor, fillOpacity * opacity); - } - - if (lineColor !== null) - { - graphics.lineStyle(lineThickness, sensorLineColor, lineOpacity * opacity); - } - } - else - { - if (fillColor !== null) - { - graphics.fillStyle(fillColor, fillOpacity * opacity); - } - - if (lineColor !== null) - { - graphics.lineStyle(lineThickness, lineColor, lineOpacity * opacity); - } - } - - if (circleRadius) - { - graphics.arc(part.position.x, part.position.y, circleRadius, 0, 2 * Math.PI); - } - else - { - var vertices = part.vertices; - var vertLength = vertices.length; - - graphics.moveTo(vertices[0].x, vertices[0].y); - - for (var j = 1; j < vertLength; j++) - { - var vert = vertices[j]; - - if (!vertices[j - 1].isInternal || showInternalEdges) - { - graphics.lineTo(vert.x, vert.y); - } - else - { - graphics.moveTo(vert.x, vert.y); - } - - if (j < vertLength && vert.isInternal && !showInternalEdges) - { - var nextIndex = (j + 1) % vertLength; - - graphics.moveTo(vertices[nextIndex].x, vertices[nextIndex].y); - } - } - - graphics.closePath(); - } - - if (fillColor !== null) - { - graphics.fillPath(); - } - - if (lineColor !== null) - { - graphics.strokePath(); - } - } - - if (config.showPositions && !body.isStatic) - { - var px = body.position.x; - var py = body.position.y; - var hs = Math.ceil(config.positionSize / 2); - - graphics.fillStyle(config.positionColor, 1); - graphics.fillRect(px - hs, py - hs, config.positionSize, config.positionSize); - } - - return this; - }, - - /** - * Renders the Convex Hull for a single Matter Body to the given Phaser Graphics Game Object. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render a Body hull to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderConvexHull - * @since 3.22.0 - * - * @param {MatterJS.BodyType} body - The Matter Body to be rendered. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} hullColor - The color used to render the hull. - * @param {number} [lineThickness=1] - The hull line thickness. - * - * @return {this} This Matter World instance for method chaining. - */ - renderConvexHull: function (body, graphics, hullColor, lineThickness) - { - if (lineThickness === undefined) { lineThickness = 1; } - - var parts = body.parts; - var partsLength = parts.length; - - // Render Convex Hulls - if (partsLength > 1) - { - var verts = body.vertices; - - graphics.lineStyle(lineThickness, hullColor); - - graphics.beginPath(); - - graphics.moveTo(verts[0].x, verts[0].y); - - for (var v = 1; v < verts.length; v++) - { - graphics.lineTo(verts[v].x, verts[v].y); - } - - graphics.lineTo(verts[0].x, verts[0].y); - - graphics.strokePath(); - } - - return this; - }, - - /** - * Renders all of the constraints in the world (unless they are specifically set to invisible). - * - * Called automatically by the `postUpdate` method. - * - * @method Phaser.Physics.Matter.World#renderJoints - * @private - * @since 3.14.0 - */ - renderJoints: function () - { - var graphics = this.debugGraphic; - - // Render constraints - var constraints = Composite.allConstraints(this.localWorld); - - for (var i = 0; i < constraints.length; i++) - { - var config = constraints[i].render; - - var lineColor = config.lineColor; - var lineOpacity = config.lineOpacity; - var lineThickness = config.lineThickness; - var pinSize = config.pinSize; - var anchorColor = config.anchorColor; - var anchorSize = config.anchorSize; - - this.renderConstraint(constraints[i], graphics, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize); - } - }, - - /** - * Renders a single Matter Constraint, such as a Pin or a Spring, to the given Phaser Graphics Game Object. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render a Constraint to your own Graphics instance. - * - * @method Phaser.Physics.Matter.World#renderConstraint - * @since 3.22.0 - * - * @param {MatterJS.ConstraintType} constraint - The Matter Constraint to render. - * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. - * @param {number} lineColor - The line color. - * @param {number} lineOpacity - The line opacity, between 0 and 1. - * @param {number} lineThickness - The line thickness. - * @param {number} pinSize - If this constraint is a pin, this sets the size of the pin circle. - * @param {number} anchorColor - The color used when rendering this constraints anchors. Set to `null` to not render anchors. - * @param {number} anchorSize - The size of the anchor circle, if this constraint has anchors and is rendering them. - * - * @return {this} This Matter World instance for method chaining. - */ - renderConstraint: function (constraint, graphics, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize) - { - var render = constraint.render; - - if (!render.visible || !constraint.pointA || !constraint.pointB) - { - return this; - } - - graphics.lineStyle(lineThickness, lineColor, lineOpacity); - - var bodyA = constraint.bodyA; - var bodyB = constraint.bodyB; - var start; - var end; - - if (bodyA) - { - start = Vector.add(bodyA.position, constraint.pointA); - } - else - { - start = constraint.pointA; - } - - if (render.type === 'pin') - { - graphics.strokeCircle(start.x, start.y, pinSize); - } - else - { - if (bodyB) - { - end = Vector.add(bodyB.position, constraint.pointB); - } - else - { - end = constraint.pointB; - } - - graphics.beginPath(); - graphics.moveTo(start.x, start.y); - - if (render.type === 'spring') - { - var delta = Vector.sub(end, start); - var normal = Vector.perp(Vector.normalise(delta)); - var coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)); - var offset; - - for (var j = 1; j < coils; j += 1) - { - offset = (j % 2 === 0) ? 1 : -1; - - graphics.lineTo( - start.x + delta.x * (j / coils) + normal.x * offset * 4, - start.y + delta.y * (j / coils) + normal.y * offset * 4 - ); - } - } - - graphics.lineTo(end.x, end.y); - } - - graphics.strokePath(); - - if (render.anchors && anchorSize > 0) - { - graphics.fillStyle(anchorColor); - graphics.fillCircle(start.x, start.y, anchorSize); - graphics.fillCircle(end.x, end.y, anchorSize); - } - - return this; - }, - - /** - * Resets the internal collision IDs that Matter.JS uses for Body collision groups. - * - * You should call this before destroying your game if you need to restart the game - * again on the same page, without first reloading the page. Or, if you wish to - * consistently destroy a Scene that contains Matter.js and then run it again - * later in the same game. - * - * @method Phaser.Physics.Matter.World#resetCollisionIDs - * @since 3.17.0 - */ - resetCollisionIDs: function () - { - Body._nextCollidingGroupId = 1; - Body._nextNonCollidingGroupId = -1; - Body._nextCategory = 0x0001; - - return this; - }, - - /** - * Will remove all Matter physics event listeners and clear the matter physics world, - * engine and any debug graphics, if any. - * - * @method Phaser.Physics.Matter.World#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - MatterEvents.off(this.engine); - - this.removeAllListeners(); - - MatterWorld.clear(this.localWorld, false); - - Engine.clear(this.engine); - - if (this.drawDebug) - { - this.debugGraphic.destroy(); - } - }, - - /** - * Will remove all Matter physics event listeners and clear the matter physics world, - * engine and any debug graphics, if any. - * - * After destroying the world it cannot be re-used again. - * - * @method Phaser.Physics.Matter.World#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - } - -}); - -module.exports = World; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = require('./lib/factory/Bodies'); +var Body = require('./lib/body/Body'); +var Class = require('../../utils/Class'); +var Common = require('./lib/core/Common'); +var Composite = require('./lib/body/Composite'); +var Engine = require('./lib/core/Engine'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var GetValue = require('../../utils/object/GetValue'); +var MatterBody = require('./lib/body/Body'); +var MatterEvents = require('./lib/core/Events'); +var MatterTileBody = require('./MatterTileBody'); +var MatterWorld = require('./lib/body/World'); +var Vector = require('./lib/geometry/Vector'); + +/** + * @classdesc + * The Matter World class is responsible for managing one single instance of a Matter Physics World for Phaser. + * + * Access this via `this.matter.world` from within a Scene. + * + * This class creates a Matter JS World Composite along with the Matter JS Engine during instantiation. It also + * handles delta timing, bounds, body and constraint creation and debug drawing. + * + * If you wish to access the Matter JS World object directly, see the `localWorld` property. + * If you wish to access the Matter Engine directly, see the `engine` property. + * + * This class is an Event Emitter and will proxy _all_ Matter JS events, as they are received. + * + * @class World + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Physics.Matter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Matter World instance belongs. + * @param {Phaser.Types.Physics.Matter.MatterWorldConfig} config - The Matter World configuration object. + */ +var World = new Class({ + + Extends: EventEmitter, + + initialize: + + function World (scene, config) + { + EventEmitter.call(this); + + /** + * The Scene to which this Matter World instance belongs. + * + * @name Phaser.Physics.Matter.World#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * An instance of the MatterJS Engine. + * + * @name Phaser.Physics.Matter.World#engine + * @type {MatterJS.Engine} + * @since 3.0.0 + */ + this.engine = Engine.create(config); + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + * + * @name Phaser.Physics.Matter.World#localWorld + * @type {MatterJS.World} + * @since 3.0.0 + */ + this.localWorld = this.engine.world; + + var gravity = GetValue(config, 'gravity', null); + + if (gravity) + { + this.setGravity(gravity.x, gravity.y, gravity.scale); + } + else if (gravity === false) + { + this.setGravity(0, 0, 0); + } + + /** + * An object containing the 4 wall bodies that bound the physics world. + * + * @name Phaser.Physics.Matter.World#walls + * @type {object} + * @since 3.0.0 + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * A flag that toggles if the world is enabled or not. + * + * @name Phaser.Physics.Matter.World#enabled + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.enabled = GetValue(config, 'enabled', true); + + /** + * The correction argument is 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. + * + * @name Phaser.Physics.Matter.World#correction + * @type {number} + * @default 1 + * @since 3.4.0 + */ + this.correction = GetValue(config, 'correction', 1); + + /** + * This function is called every time the core game loop steps, which is bound to the + * Request Animation Frame frequency unless otherwise modified. + * + * The function is passed two values: `time` and `delta`, both of which come from the game step values. + * + * It must return a number. This number is used as the delta value passed to Matter.Engine.update. + * + * You can override this function with your own to define your own timestep. + * + * If you need to update the Engine multiple times in a single game step then call + * `World.update` as many times as required. Each call will trigger the `getDelta` function. + * If you wish to have full control over when the Engine updates then see the property `autoUpdate`. + * + * You can also adjust the number of iterations that Engine.update performs. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * + * @name Phaser.Physics.Matter.World#getDelta + * @type {function} + * @since 3.4.0 + */ + this.getDelta = GetValue(config, 'getDelta', this.update60Hz); + + var runnerConfig = GetFastValue(config, 'runner', {}); + + var hasFPS = GetFastValue(runnerConfig, 'fps', false); + + var fps = GetFastValue(runnerConfig, 'fps', 60); + + var delta = GetFastValue(runnerConfig, 'delta', 1000 / fps); + var deltaMin = GetFastValue(runnerConfig, 'deltaMin', 1000 / fps); + var deltaMax = GetFastValue(runnerConfig, 'deltaMax', 1000 / (fps * 0.5)); + + if (!hasFPS) + { + fps = 1000 / delta; + } + + /** + * The Matter JS Runner Configuration object. + * + * This object is populated via the Matter Configuration object's `runner` property and is + * updated constantly during the game step. + * + * @name Phaser.Physics.Matter.World#runner + * @type {Phaser.Types.Physics.Matter.MatterRunnerConfig} + * @since 3.22.0 + */ + this.runner = { + fps: fps, + correction: GetFastValue(runnerConfig, 'correction', 1), + deltaSampleSize: GetFastValue(runnerConfig, 'deltaSampleSize', 60), + counterTimestamp: 0, + frameCounter: 0, + deltaHistory: [], + timePrev: null, + timeScalePrev: 1, + frameRequestId: null, + isFixed: GetFastValue(runnerConfig, 'isFixed', false), + delta: delta, + deltaMin: deltaMin, + deltaMax: deltaMax + }; + + /** + * Automatically call Engine.update every time the game steps. + * If you disable this then you are responsible for calling `World.step` directly from your game. + * If you call `set60Hz` or `set30Hz` then `autoUpdate` is reset to `true`. + * + * @name Phaser.Physics.Matter.World#autoUpdate + * @type {boolean} + * @default true + * @since 3.4.0 + */ + this.autoUpdate = GetValue(config, 'autoUpdate', true); + + var debugConfig = GetValue(config, 'debug', false); + + /** + * A flag that controls if the debug graphics will be drawn to or not. + * + * @name Phaser.Physics.Matter.World#drawDebug + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.drawDebug = (typeof(debugConfig) === 'object') ? true : debugConfig; + + /** + * An instance of the Graphics object the debug bodies are drawn to, if enabled. + * + * @name Phaser.Physics.Matter.World#debugGraphic + * @type {Phaser.GameObjects.Graphics} + * @since 3.0.0 + */ + this.debugGraphic; + + /** + * The debug configuration object. + * + * The values stored in this object are read from the Matter World Config `debug` property. + * + * When a new Body or Constraint is _added to the World_, they are given the values stored in this object, + * unless they have their own `render` object set that will override them. + * + * Note that while you can modify the values of properties in this object at run-time, it will not change + * any of the Matter objects _already added_. It will only impact objects newly added to the world, or one + * that is removed and then re-added at a later time. + * + * @name Phaser.Physics.Matter.World#debugConfig + * @type {Phaser.Types.Physics.Matter.MatterDebugConfig} + * @since 3.22.0 + */ + this.debugConfig = { + showAxes: GetFastValue(debugConfig, 'showAxes', false), + showAngleIndicator: GetFastValue(debugConfig, 'showAngleIndicator', false), + angleColor: GetFastValue(debugConfig, 'angleColor', 0xe81153), + + showBroadphase: GetFastValue(debugConfig, 'showBroadphase', false), + broadphaseColor: GetFastValue(debugConfig, 'broadphaseColor', 0xffb400), + + showBounds: GetFastValue(debugConfig, 'showBounds', false), + boundsColor: GetFastValue(debugConfig, 'boundsColor', 0xffffff), + + showVelocity: GetFastValue(debugConfig, 'showVelocity', false), + velocityColor: GetFastValue(debugConfig, 'velocityColor', 0x00aeef), + + showCollisions: GetFastValue(debugConfig, 'showCollisions', false), + collisionColor: GetFastValue(debugConfig, 'collisionColor', 0xf5950c), + + showSeparations: GetFastValue(debugConfig, 'showSeparations', false), + separationColor: GetFastValue(debugConfig, 'separationColor', 0xffa500), + + showBody: GetFastValue(debugConfig, 'showBody', true), + showStaticBody: GetFastValue(debugConfig, 'showStaticBody', true), + showInternalEdges: GetFastValue(debugConfig, 'showInternalEdges', false), + + renderFill: GetFastValue(debugConfig, 'renderFill', false), + renderLine: GetFastValue(debugConfig, 'renderLine', true), + + fillColor: GetFastValue(debugConfig, 'fillColor', 0x106909), + fillOpacity: GetFastValue(debugConfig, 'fillOpacity', 1), + lineColor: GetFastValue(debugConfig, 'lineColor', 0x28de19), + lineOpacity: GetFastValue(debugConfig, 'lineOpacity', 1), + lineThickness: GetFastValue(debugConfig, 'lineThickness', 1), + + staticFillColor: GetFastValue(debugConfig, 'staticFillColor', 0x0d177b), + staticLineColor: GetFastValue(debugConfig, 'staticLineColor', 0x1327e4), + + showSleeping: GetFastValue(debugConfig, 'showSleeping', false), + staticBodySleepOpacity: GetFastValue(debugConfig, 'staticBodySleepOpacity', 0.7), + sleepFillColor: GetFastValue(debugConfig, 'sleepFillColor', 0x464646), + sleepLineColor: GetFastValue(debugConfig, 'sleepLineColor', 0x999a99), + + showSensors: GetFastValue(debugConfig, 'showSensors', true), + sensorFillColor: GetFastValue(debugConfig, 'sensorFillColor', 0x0d177b), + sensorLineColor: GetFastValue(debugConfig, 'sensorLineColor', 0x1327e4), + + showPositions: GetFastValue(debugConfig, 'showPositions', true), + positionSize: GetFastValue(debugConfig, 'positionSize', 4), + positionColor: GetFastValue(debugConfig, 'positionColor', 0xe042da), + + showJoint: GetFastValue(debugConfig, 'showJoint', true), + jointColor: GetFastValue(debugConfig, 'jointColor', 0xe0e042), + jointLineOpacity: GetFastValue(debugConfig, 'jointLineOpacity', 1), + jointLineThickness: GetFastValue(debugConfig, 'jointLineThickness', 2), + + pinSize: GetFastValue(debugConfig, 'pinSize', 4), + pinColor: GetFastValue(debugConfig, 'pinColor', 0x42e0e0), + + springColor: GetFastValue(debugConfig, 'springColor', 0xe042e0), + + anchorColor: GetFastValue(debugConfig, 'anchorColor', 0xefefef), + anchorSize: GetFastValue(debugConfig, 'anchorSize', 4), + + showConvexHulls: GetFastValue(debugConfig, 'showConvexHulls', false), + hullColor: GetFastValue(debugConfig, 'hullColor', 0xd703d0) + }; + + if (this.drawDebug) + { + this.createDebugGraphic(); + } + + this.setEventsProxy(); + + // Create the walls + + if (GetFastValue(config, 'setBounds', false)) + { + var boundsConfig = config['setBounds']; + + if (typeof boundsConfig === 'boolean') + { + this.setBounds(); + } + else + { + var x = GetFastValue(boundsConfig, 'x', 0); + var y = GetFastValue(boundsConfig, 'y', 0); + var width = GetFastValue(boundsConfig, 'width', scene.sys.scale.width); + var height = GetFastValue(boundsConfig, 'height', scene.sys.scale.height); + var thickness = GetFastValue(boundsConfig, 'thickness', 64); + var left = GetFastValue(boundsConfig, 'left', true); + var right = GetFastValue(boundsConfig, 'right', true); + var top = GetFastValue(boundsConfig, 'top', true); + var bottom = GetFastValue(boundsConfig, 'bottom', true); + + this.setBounds(x, y, width, height, thickness, left, right, top, bottom); + } + } + }, + + /** + * Sets the debug render style for the children of the given Matter Composite. + * + * Composites themselves do not render, but they can contain bodies, constraints and other composites that may do. + * So the children of this composite are passed to the `setBodyRenderStyle`, `setCompositeRenderStyle` and + * `setConstraintRenderStyle` methods accordingly. + * + * @method Phaser.Physics.Matter.World#setCompositeRenderStyle + * @since 3.22.0 + * + * @param {MatterJS.CompositeType} composite - The Matter Composite to set the render style on. + * + * @return {this} This Matter World instance for method chaining. + */ + setCompositeRenderStyle: function (composite) + { + var bodies = composite.bodies; + var constraints = composite.constraints; + var composites = composite.composites; + + var i; + var obj; + var render; + + for (i = 0; i < bodies.length; i++) + { + obj = bodies[i]; + render = obj.render; + + this.setBodyRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.fillColor, render.fillOpacity); + } + + for (i = 0; i < constraints.length; i++) + { + obj = constraints[i]; + render = obj.render; + + this.setConstraintRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.pinSize, render.anchorColor, render.anchorSize); + } + + for (i = 0; i < composites.length; i++) + { + obj = composites[i]; + + this.setCompositeRenderStyle(obj); + } + + return this; + }, + + /** + * Sets the debug render style for the given Matter Body. + * + * If you are using this on a Phaser Game Object, such as a Matter Sprite, then pass in the body property + * to this method, not the Game Object itself. + * + * If you wish to skip a parameter, so it retains its current value, pass `false` for it. + * + * If you wish to reset the Body render colors to the defaults found in the World Debug Config, then call + * this method with just the `body` parameter provided and no others. + * + * @method Phaser.Physics.Matter.World#setBodyRenderStyle + * @since 3.22.0 + * + * @param {MatterJS.BodyType} body - The Matter Body to set the render style on. + * @param {number} [lineColor] - The line color. If `null` it will use the World Debug Config value. + * @param {number} [lineOpacity] - The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * @param {number} [lineThickness] - The line thickness. If `null` it will use the World Debug Config value. + * @param {number} [fillColor] - The fill color. If `null` it will use the World Debug Config value. + * @param {number} [fillOpacity] - The fill opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * + * @return {this} This Matter World instance for method chaining. + */ + setBodyRenderStyle: function (body, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) + { + var render = body.render; + var config = this.debugConfig; + + if (!render) + { + return this; + } + + if (lineColor === undefined || lineColor === null) + { + lineColor = (body.isStatic) ? config.staticLineColor : config.lineColor; + } + + if (lineOpacity === undefined || lineOpacity === null) + { + lineOpacity = config.lineOpacity; + } + + if (lineThickness === undefined || lineThickness === null) + { + lineThickness = config.lineThickness; + } + + if (fillColor === undefined || fillColor === null) + { + fillColor = (body.isStatic) ? config.staticFillColor : config.fillColor; + } + + if (fillOpacity === undefined || fillOpacity === null) + { + fillOpacity = config.fillOpacity; + } + + if (lineColor !== false) + { + render.lineColor = lineColor; + } + + if (lineOpacity !== false) + { + render.lineOpacity = lineOpacity; + } + + if (lineThickness !== false) + { + render.lineThickness = lineThickness; + } + + if (fillColor !== false) + { + render.fillColor = fillColor; + } + + if (fillOpacity !== false) + { + render.fillOpacity = fillOpacity; + } + + return this; + }, + + /** + * Sets the debug render style for the given Matter Constraint. + * + * If you are using this on a Phaser Game Object, then pass in the body property + * to this method, not the Game Object itself. + * + * If you wish to skip a parameter, so it retains its current value, pass `false` for it. + * + * If you wish to reset the Constraint render colors to the defaults found in the World Debug Config, then call + * this method with just the `constraint` parameter provided and no others. + * + * @method Phaser.Physics.Matter.World#setConstraintRenderStyle + * @since 3.22.0 + * + * @param {MatterJS.ConstraintType} constraint - The Matter Constraint to set the render style on. + * @param {number} [lineColor] - The line color. If `null` it will use the World Debug Config value. + * @param {number} [lineOpacity] - The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * @param {number} [lineThickness] - The line thickness. If `null` it will use the World Debug Config value. + * @param {number} [pinSize] - If this constraint is a pin, this sets the size of the pin circle. If `null` it will use the World Debug Config value. + * @param {number} [anchorColor] - The color used when rendering this constraints anchors. If `null` it will use the World Debug Config value. + * @param {number} [anchorSize] - The size of the anchor circle, if this constraint has anchors. If `null` it will use the World Debug Config value. + * + * @return {this} This Matter World instance for method chaining. + */ + setConstraintRenderStyle: function (constraint, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize) + { + var render = constraint.render; + var config = this.debugConfig; + + if (!render) + { + return this; + } + + // Reset them + if (lineColor === undefined || lineColor === null) + { + var type = render.type; + + if (type === 'line') + { + lineColor = config.jointColor; + } + else if (type === 'pin') + { + lineColor = config.pinColor; + } + else if (type === 'spring') + { + lineColor = config.springColor; + } + } + + if (lineOpacity === undefined || lineOpacity === null) + { + lineOpacity = config.jointLineOpacity; + } + + if (lineThickness === undefined || lineThickness === null) + { + lineThickness = config.jointLineThickness; + } + + if (pinSize === undefined || pinSize === null) + { + pinSize = config.pinSize; + } + + if (anchorColor === undefined || anchorColor === null) + { + anchorColor = config.anchorColor; + } + + if (anchorSize === undefined || anchorSize === null) + { + anchorSize = config.anchorSize; + } + + if (lineColor !== false) + { + render.lineColor = lineColor; + } + + if (lineOpacity !== false) + { + render.lineOpacity = lineOpacity; + } + + if (lineThickness !== false) + { + render.lineThickness = lineThickness; + } + + if (pinSize !== false) + { + render.pinSize = pinSize; + } + + if (anchorColor !== false) + { + render.anchorColor = anchorColor; + } + + if (anchorSize !== false) + { + render.anchorSize = anchorSize; + } + + return this; + }, + + /** + * This internal method acts as a proxy between all of the Matter JS events and then re-emits them + * via this class. + * + * @method Phaser.Physics.Matter.World#setEventsProxy + * @since 3.0.0 + */ + setEventsProxy: function () + { + var _this = this; + var engine = this.engine; + var world = this.localWorld; + + // Inject debug styles + + if (this.drawDebug) + { + MatterEvents.on(world, 'compositeModified', function (composite) + { + _this.setCompositeRenderStyle(composite); + }); + + MatterEvents.on(world, 'beforeAdd', function (event) + { + var objects = [].concat(event.object); + + for (var i = 0; i < objects.length; i++) + { + var obj = objects[i]; + var render = obj.render; + + if (obj.type === 'body') + { + _this.setBodyRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.fillColor, render.fillOpacity); + } + else if (obj.type === 'composite') + { + _this.setCompositeRenderStyle(obj); + } + else if (obj.type === 'constraint') + { + _this.setConstraintRenderStyle(obj, render.lineColor, render.lineOpacity, render.lineThickness, render.pinSize, render.anchorColor, render.anchorSize); + } + } + }); + } + + MatterEvents.on(world, 'beforeAdd', function (event) + { + _this.emit(Events.BEFORE_ADD, event); + }); + + MatterEvents.on(world, 'afterAdd', function (event) + { + _this.emit(Events.AFTER_ADD, event); + }); + + MatterEvents.on(world, 'beforeRemove', function (event) + { + _this.emit(Events.BEFORE_REMOVE, event); + }); + + MatterEvents.on(world, 'afterRemove', function (event) + { + _this.emit(Events.AFTER_REMOVE, event); + }); + + MatterEvents.on(engine, 'beforeUpdate', function (event) + { + _this.emit(Events.BEFORE_UPDATE, event); + }); + + MatterEvents.on(engine, 'afterUpdate', function (event) + { + _this.emit(Events.AFTER_UPDATE, event); + }); + + MatterEvents.on(engine, 'collisionStart', function (event) + { + var pairs = event.pairs; + var bodyA; + var bodyB; + + if (pairs.length > 0) + { + bodyA = pairs[0].bodyA; + bodyB = pairs[0].bodyB; + } + + _this.emit(Events.COLLISION_START, event, bodyA, bodyB); + }); + + MatterEvents.on(engine, 'collisionActive', function (event) + { + var pairs = event.pairs; + var bodyA; + var bodyB; + + if (pairs.length > 0) + { + bodyA = pairs[0].bodyA; + bodyB = pairs[0].bodyB; + } + + _this.emit(Events.COLLISION_ACTIVE, event, bodyA, bodyB); + }); + + MatterEvents.on(engine, 'collisionEnd', function (event) + { + var pairs = event.pairs; + var bodyA; + var bodyB; + + if (pairs.length > 0) + { + bodyA = pairs[0].bodyA; + bodyB = pairs[0].bodyB; + } + + _this.emit(Events.COLLISION_END, event, bodyA, bodyB); + }); + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.Matter.World#setBounds + * @since 3.0.0 + * + * @param {number} [x=0] - The x coordinate of the top-left corner of the bounds. + * @param {number} [y=0] - The y coordinate of the top-left corner of the bounds. + * @param {number} [width] - The width of the bounds. + * @param {number} [height] - The height of the bounds. + * @param {number} [thickness=64] - The thickness of each wall, in pixels. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * + * @return {Phaser.Physics.Matter.World} This Matter World object. + */ + setBounds: function (x, y, width, height, thickness, left, right, top, bottom) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.scene.sys.scale.width; } + if (height === undefined) { height = this.scene.sys.scale.height; } + if (thickness === undefined) { thickness = 64; } + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (bottom === undefined) { bottom = true; } + + this.updateWall(left, 'left', x - thickness, y - thickness, thickness, height + (thickness * 2)); + this.updateWall(right, 'right', x + width, y - thickness, thickness, height + (thickness * 2)); + this.updateWall(top, 'top', x, y - thickness, width, thickness); + this.updateWall(bottom, 'bottom', x, y + height, width, thickness); + + return this; + }, + + /** + * Updates the 4 rectangle bodies that were created, if `setBounds` was set in the Matter config, to use + * the new positions and sizes. This method is usually only called internally via the `setBounds` method. + * + * @method Phaser.Physics.Matter.World#updateWall + * @since 3.0.0 + * + * @param {boolean} add - `true` if the walls are being added or updated, `false` to remove them from the world. + * @param {string} [position] - Either `left`, `right`, `top` or `bottom`. Only optional if `add` is `false`. + * @param {number} [x] - The horizontal position to place the walls at. Only optional if `add` is `false`. + * @param {number} [y] - The vertical position to place the walls at. Only optional if `add` is `false`. + * @param {number} [width] - The width of the walls, in pixels. Only optional if `add` is `false`. + * @param {number} [height] - The height of the walls, in pixels. Only optional if `add` is `false`. + */ + updateWall: function (add, position, x, y, width, height) + { + var wall = this.walls[position]; + + if (add) + { + if (wall) + { + MatterWorld.remove(this.localWorld, wall); + } + + // adjust center + x += (width / 2); + y += (height / 2); + + this.walls[position] = this.create(x, y, width, height, { isStatic: true, friction: 0, frictionStatic: 0 }); + } + else + { + if (wall) + { + MatterWorld.remove(this.localWorld, wall); + } + + this.walls[position] = null; + } + }, + + /** + * Creates a Phaser.GameObjects.Graphics object that is used to render all of the debug bodies and joints to. + * + * This method is called automatically by the constructor, if debugging has been enabled. + * + * The created Graphics object is automatically added to the Scene at 0x0 and given a depth of `Number.MAX_VALUE`, + * so it renders above all else in the Scene. + * + * The Graphics object is assigned to the `debugGraphic` property of this class and `drawDebug` is enabled. + * + * @method Phaser.Physics.Matter.World#createDebugGraphic + * @since 3.0.0 + * + * @return {Phaser.GameObjects.Graphics} The newly created Graphics object. + */ + createDebugGraphic: function () + { + var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); + + graphic.setDepth(Number.MAX_VALUE); + + this.debugGraphic = graphic; + + this.drawDebug = true; + + return graphic; + }, + + /** + * Sets the world gravity and gravity scale to 0. + * + * @method Phaser.Physics.Matter.World#disableGravity + * @since 3.0.0 + * + * @return {this} This Matter World object. + */ + disableGravity: function () + { + this.localWorld.gravity.x = 0; + this.localWorld.gravity.y = 0; + this.localWorld.gravity.scale = 0; + + return this; + }, + + /** + * Sets the worlds gravity to the values given. + * + * Gravity effects all bodies in the world, unless they have the `ignoreGravity` flag set. + * + * @method Phaser.Physics.Matter.World#setGravity + * @since 3.0.0 + * + * @param {number} [x=0] - The world gravity x component. + * @param {number} [y=1] - The world gravity y component. + * @param {number} [scale=0.001] - The gravity scale factor. + * + * @return {this} This Matter World object. + */ + setGravity: function (x, y, scale) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 1; } + + this.localWorld.gravity.x = x; + this.localWorld.gravity.y = y; + + if (scale !== undefined) + { + this.localWorld.gravity.scale = scale; + } + + return this; + }, + + /** + * Creates a rectangle Matter body and adds it to the world. + * + * @method Phaser.Physics.Matter.World#create + * @since 3.0.0 + * + * @param {number} x - The horizontal position of the body in the world. + * @param {number} y - The vertical position of the body in the world. + * @param {number} width - The width of the body. + * @param {number} height - The height of the body. + * @param {object} options - Optional Matter configuration object. + * + * @return {MatterJS.BodyType} The Matter.js body that was created. + */ + create: function (x, y, width, height, options) + { + var body = Bodies.rectangle(x, y, width, height, options); + + MatterWorld.add(this.localWorld, body); + + return body; + }, + + /** + * Adds a Matter JS object, or array of objects, to the world. + * + * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. + * + * Triggers `beforeAdd` and `afterAdd` events. + * + * @method Phaser.Physics.Matter.World#add + * @since 3.0.0 + * + * @param {(object|object[])} object - Can be single object, or an array, and can be a body, composite or constraint. + * + * @return {this} This Matter World object. + */ + add: function (object) + { + MatterWorld.add(this.localWorld, object); + + return this; + }, + + /** + * Removes a Matter JS object, or array of objects, from the world. + * + * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. + * + * Triggers `beforeRemove` and `afterRemove` events. + * + * @method Phaser.Physics.Matter.World#remove + * @since 3.0.0 + * + * @param {(object|object[])} object - Can be single object, or an array, and can be a body, composite or constraint. + * @param {boolean} [deep=false] - Optionally search the objects children and recursively remove those as well. + * + * @return {this} This Matter World object. + */ + remove: function (object, deep) + { + if (!Array.isArray(object)) + { + object = [ object ]; + } + + for (var i = 0; i < object.length; i++) + { + var entity = object[i]; + + var body = (entity.body) ? entity.body : entity; + + Composite.remove(this.localWorld, body, deep); + } + + return this; + }, + + /** + * Removes a Matter JS constraint, or array of constraints, from the world. + * + * Triggers `beforeRemove` and `afterRemove` events. + * + * @method Phaser.Physics.Matter.World#removeConstraint + * @since 3.0.0 + * + * @param {(MatterJS.ConstraintType|MatterJS.ConstraintType[])} constraint - A Matter JS Constraint, or an array of constraints, to be removed. + * @param {boolean} [deep=false] - Optionally search the objects children and recursively remove those as well. + * + * @return {this} This Matter World object. + */ + removeConstraint: function (constraint, deep) + { + Composite.remove(this.localWorld, constraint, deep); + + return this; + }, + + /** + * Adds `MatterTileBody` instances for all the colliding tiles within the given tilemap layer. + * + * Set the appropriate tiles in your layer to collide before calling this method! + * + * @method Phaser.Physics.Matter.World#convertTilemapLayer + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} tilemapLayer - + * An array of tiles. + * @param {object} [options] - Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} + * + * @return {this} This Matter World object. + */ + convertTilemapLayer: function (tilemapLayer, options) + { + var layerData = tilemapLayer.layer; + var tiles = tilemapLayer.getTilesWithin(0, 0, layerData.width, layerData.height, { isColliding: true }); + + this.convertTiles(tiles, options); + + return this; + }, + + /** + * Adds `MatterTileBody` instances for the given tiles. This adds bodies regardless of whether the + * tiles are set to collide or not. + * + * @method Phaser.Physics.Matter.World#convertTiles + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile[]} tiles - An array of tiles. + * @param {object} [options] - Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} + * + * @return {this} This Matter World object. + */ + convertTiles: function (tiles, options) + { + if (tiles.length === 0) + { + return this; + } + + for (var i = 0; i < tiles.length; i++) + { + new MatterTileBody(this, tiles[i], options); + } + + return this; + }, + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will not collide. + * + * @method Phaser.Physics.Matter.World#nextGroup + * @since 3.0.0 + * + * @param {boolean} [isNonColliding=false] - If `true`, returns the next unique group index for which bodies will _not_ collide. + * + * @return {number} Unique category bitfield + */ + nextGroup: function (isNonColliding) + { + return MatterBody.nextGroup(isNonColliding); + }, + + /** + * Returns the next unique category bitfield (starting after the initial default category 0x0001). + * There are 32 available. + * + * @method Phaser.Physics.Matter.World#nextCategory + * @since 3.0.0 + * + * @return {number} Unique category bitfield + */ + nextCategory: function () + { + return MatterBody.nextCategory(); + }, + + /** + * Pauses this Matter World instance and sets `enabled` to `false`. + * + * A paused world will not run any simulations for the duration it is paused. + * + * @method Phaser.Physics.Matter.World#pause + * @fires Phaser.Physics.Matter.Events#PAUSE + * @since 3.0.0 + * + * @return {this} This Matter World object. + */ + pause: function () + { + this.enabled = false; + + this.emit(Events.PAUSE); + + return this; + }, + + /** + * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. + * + * @method Phaser.Physics.Matter.World#resume + * @fires Phaser.Physics.Matter.Events#RESUME + * @since 3.0.0 + * + * @return {this} This Matter World object. + */ + resume: function () + { + this.enabled = true; + + this.emit(Events.RESUME); + + return this; + }, + + /** + * 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. + */ + update: function (time, delta) + { + if (!this.enabled || !this.autoUpdate) + { + return; + } + + var engine = this.engine; + var runner = this.runner; + + var timing = engine.timing; + var correction = this.correction; + + if (runner.isFixed) + { + // fixed timestep + delta = this.getDelta(time, delta); + } + else + { + // dynamic timestep based on wall clock between calls + delta = (time - runner.timePrev) || runner.delta; + runner.timePrev = time; + + // optimistically filter delta over a few frames, to improve stability + runner.deltaHistory.push(delta); + runner.deltaHistory = runner.deltaHistory.slice(-runner.deltaSampleSize); + delta = Math.min.apply(null, runner.deltaHistory); + + // limit delta + delta = delta < runner.deltaMin ? runner.deltaMin : delta; + delta = delta > runner.deltaMax ? runner.deltaMax : delta; + + // correction for delta + correction = delta / runner.delta; + + // update engine timing object + runner.delta = delta; + } + + // time correction for time scaling + if (runner.timeScalePrev !== 0) + { + correction *= timing.timeScale / runner.timeScalePrev; + } + + if (timing.timeScale === 0) + { + correction = 0; + } + + runner.timeScalePrev = timing.timeScale; + runner.correction = correction; + + // fps counter + runner.frameCounter += 1; + + if (time - runner.counterTimestamp >= 1000) + { + runner.fps = runner.frameCounter * ((time - runner.counterTimestamp) / 1000); + runner.counterTimestamp = time; + runner.frameCounter = 0; + } + + Engine.update(engine, delta, correction); + }, + + /** + * Manually advances the physics simulation by one iteration. + * + * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. + * If undefined they use the Matter defaults of 60Hz and no correction. + * + * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. + * + * It also ignores any custom `getDelta` functions, as you should be passing the delta + * value in to this call. + * + * You can adjust the number of iterations that Engine.update performs internally. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * + * @method Phaser.Physics.Matter.World#step + * @since 3.4.0 + * + * @param {number} [delta=16.666] - The delta value. + * @param {number} [correction=1] - Optional delta correction value. + */ + step: function (delta, correction) + { + Engine.update(this.engine, delta, correction); + }, + + /** + * Runs the Matter Engine.update at a fixed timestep of 60Hz. + * + * @method Phaser.Physics.Matter.World#update60Hz + * @since 3.4.0 + * + * @return {number} The delta value to be passed to Engine.update. + */ + update60Hz: function () + { + return 1000 / 60; + }, + + /** + * Runs the Matter Engine.update at a fixed timestep of 30Hz. + * + * @method Phaser.Physics.Matter.World#update30Hz + * @since 3.4.0 + * + * @return {number} The delta value to be passed to Engine.update. + */ + update30Hz: function () + { + return 1000 / 30; + }, + + /** + * Returns `true` if the given body can be found within the World. + * + * @method Phaser.Physics.Matter.World#has + * @since 3.22.0 + * + * @param {(MatterJS.Body|Phaser.GameObjects.GameObject)} body - The Matter Body, or Game Object, to search for within the world. + * + * @return {MatterJS.BodyType[]} An array of all the Matter JS Bodies in this World. + */ + has: function (body) + { + var src = (body.hasOwnProperty('body')) ? body.body : body; + + return (Composite.get(this.localWorld, src.id, src.type) !== null); + }, + + /** + * Returns all the bodies in the Matter World, including all bodies in children, recursively. + * + * @method Phaser.Physics.Matter.World#getAllBodies + * @since 3.22.0 + * + * @return {MatterJS.BodyType[]} An array of all the Matter JS Bodies in this World. + */ + getAllBodies: function () + { + return Composite.allBodies(this.localWorld); + }, + + /** + * Returns all the constraints in the Matter World, including all constraints in children, recursively. + * + * @method Phaser.Physics.Matter.World#getAllConstraints + * @since 3.22.0 + * + * @return {MatterJS.ConstraintType[]} An array of all the Matter JS Constraints in this World. + */ + getAllConstraints: function () + { + return Composite.allConstraints(this.localWorld); + }, + + /** + * Returns all the composites in the Matter World, including all composites in children, recursively. + * + * @method Phaser.Physics.Matter.World#getAllComposites + * @since 3.22.0 + * + * @return {MatterJS.CompositeType[]} An array of all the Matter JS Composites in this World. + */ + getAllComposites: function () + { + return Composite.allComposites(this.localWorld); + }, + + /** + * Handles the rendering of bodies and debug information to the debug Graphics object, if enabled. + * + * This method is called automatically by the Scene after all processing has taken place. + * + * @method Phaser.Physics.Matter.World#postUpdate + * @private + * @since 3.0.0 + */ + postUpdate: function () + { + if (!this.drawDebug) + { + return; + } + + var config = this.debugConfig; + var engine = this.engine; + var graphics = this.debugGraphic; + + var bodies = Composite.allBodies(this.localWorld); + + this.debugGraphic.clear(); + + if (config.showBroadphase && engine.broadphase.controller) + { + this.renderGrid(engine.broadphase, graphics, config.broadphaseColor, 0.5); + } + + if (config.showBounds) + { + this.renderBodyBounds(bodies, graphics, config.boundsColor, 0.5); + } + + if (config.showBody || config.showStaticBody) + { + this.renderBodies(bodies); + } + + if (config.showJoint) + { + this.renderJoints(); + } + + if (config.showAxes || config.showAngleIndicator) + { + this.renderBodyAxes(bodies, graphics, config.showAxes, config.angleColor, 0.5); + } + + if (config.showVelocity) + { + this.renderBodyVelocity(bodies, graphics, config.velocityColor, 1, 2); + } + + if (config.showSeparations) + { + this.renderSeparations(engine.pairs.list, graphics, config.separationColor); + } + + if (config.showCollisions) + { + this.renderCollisions(engine.pairs.list, graphics, config.collisionColor); + } + }, + + /** + * Renders the Engine Broadphase Controller Grid to the given Graphics instance. + * + * The debug renderer calls this method if the `showBroadphase` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderGrid + * @since 3.22.0 + * + * @param {MatterJS.Grid} grid - The Matter Grid to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + * + * @return {this} This Matter World instance for method chaining. + */ + renderGrid: function (grid, graphics, lineColor, lineOpacity) + { + graphics.lineStyle(1, lineColor, lineOpacity); + + var bucketKeys = Common.keys(grid.buckets); + + for (var i = 0; i < bucketKeys.length; i++) + { + var bucketId = bucketKeys[i]; + + if (grid.buckets[bucketId].length < 2) + { + continue; + } + + var region = bucketId.split(/C|R/); + + graphics.strokeRect( + parseInt(region[1], 10) * grid.bucketWidth, + parseInt(region[2], 10) * grid.bucketHeight, + grid.bucketWidth, + grid.bucketHeight + ); + } + + return this; + }, + + /** + * Renders the list of Pair separations to the given Graphics instance. + * + * The debug renderer calls this method if the `showSeparations` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderSeparations + * @since 3.22.0 + * + * @param {MatterJS.Pair[]} pairs - An array of Matter Pairs to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * + * @return {this} This Matter World instance for method chaining. + */ + renderSeparations: function (pairs, graphics, lineColor) + { + graphics.lineStyle(1, lineColor, 1); + + for (var i = 0; i < pairs.length; i++) + { + var pair = pairs[i]; + + if (!pair.isActive) + { + continue; + } + + var collision = pair.collision; + var bodyA = collision.bodyA; + var bodyB = collision.bodyB; + var posA = bodyA.position; + var posB = bodyB.position; + var penetration = collision.penetration; + + var k = (!bodyA.isStatic && !bodyB.isStatic) ? 4 : 1; + + if (bodyB.isStatic) + { + k = 0; + } + + graphics.lineBetween( + posB.x, + posB.y, + posB.x - (penetration.x * k), + posB.y - (penetration.y * k) + ); + + k = (!bodyA.isStatic && !bodyB.isStatic) ? 4 : 1; + + if (bodyA.isStatic) + { + k = 0; + } + + graphics.lineBetween( + posA.x, + posA.y, + posA.x - (penetration.x * k), + posA.y - (penetration.y * k) + ); + } + + return this; + }, + + /** + * Renders the list of collision points and normals to the given Graphics instance. + * + * The debug renderer calls this method if the `showCollisions` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderCollisions + * @since 3.22.0 + * + * @param {MatterJS.Pair[]} pairs - An array of Matter Pairs to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * + * @return {this} This Matter World instance for method chaining. + */ + renderCollisions: function (pairs, graphics, lineColor) + { + graphics.lineStyle(1, lineColor, 0.5); + graphics.fillStyle(lineColor, 1); + + var i; + var pair; + + // Collision Positions + + for (i = 0; i < pairs.length; i++) + { + pair = pairs[i]; + + if (!pair.isActive) + { + continue; + } + + for (var j = 0; j < pair.activeContacts.length; j++) + { + var contact = pair.activeContacts[j]; + var vertex = contact.vertex; + + graphics.fillRect(vertex.x - 2, vertex.y - 2, 5, 5); + } + } + + // Collision Normals + + for (i = 0; i < pairs.length; i++) + { + pair = pairs[i]; + + if (!pair.isActive) + { + continue; + } + + var collision = pair.collision; + var contacts = pair.activeContacts; + + if (contacts.length > 0) + { + var normalPosX = contacts[0].vertex.x; + var normalPosY = contacts[0].vertex.y; + + if (contacts.length === 2) + { + normalPosX = (contacts[0].vertex.x + contacts[1].vertex.x) / 2; + normalPosY = (contacts[0].vertex.y + contacts[1].vertex.y) / 2; + } + + if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic) + { + graphics.lineBetween( + normalPosX - collision.normal.x * 8, + normalPosY - collision.normal.y * 8, + normalPosX, + normalPosY + ); + } + else + { + graphics.lineBetween( + normalPosX + collision.normal.x * 8, + normalPosY + collision.normal.y * 8, + normalPosX, + normalPosY + ); + } + } + } + + return this; + }, + + /** + * Renders the bounds of an array of Bodies to the given Graphics instance. + * + * If the body is a compound body, it will render the bounds for the parent compound. + * + * The debug renderer calls this method if the `showBounds` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderBodyBounds + * @since 3.22.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + */ + renderBodyBounds: function (bodies, graphics, lineColor, lineOpacity) + { + graphics.lineStyle(1, lineColor, lineOpacity); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + var bounds = body.bounds; + + if (bounds) + { + graphics.strokeRect( + bounds.min.x, + bounds.min.y, + bounds.max.x - bounds.min.x, + bounds.max.y - bounds.min.y + ); + } + else + { + var parts = body.parts; + + for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) + { + var part = parts[j]; + + graphics.strokeRect( + part.bounds.min.x, + part.bounds.min.y, + part.bounds.max.x - part.bounds.min.x, + part.bounds.max.y - part.bounds.min.y + ); + } + } + } + + return this; + }, + + /** + * Renders either all axes, or a single axis indicator, for an array of Bodies, to the given Graphics instance. + * + * The debug renderer calls this method if the `showAxes` or `showAngleIndicator` config values are set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderBodyAxes + * @since 3.22.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {boolean} showAxes - If `true` it will render all body axes. If `false` it will render a single axis indicator. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + */ + renderBodyAxes: function (bodies, graphics, showAxes, lineColor, lineOpacity) + { + graphics.lineStyle(1, lineColor, lineOpacity); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + var parts = body.parts; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + var part; + var j; + var k; + + if (showAxes) + { + for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) + { + part = parts[j]; + + for (k = 0; k < part.axes.length; k++) + { + var axis = part.axes[k]; + + graphics.lineBetween( + part.position.x, + part.position.y, + part.position.x + axis.x * 20, + part.position.y + axis.y * 20 + ); + } + } + } + else + { + for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) + { + part = parts[j]; + + for (k = 0; k < part.axes.length; k++) + { + graphics.lineBetween( + part.position.x, + part.position.y, + (part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2, + (part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2 + ); + } + } + } + } + + return this; + }, + + /** + * Renders a velocity indicator for an array of Bodies, to the given Graphics instance. + * + * The debug renderer calls this method if the `showVelocity` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderBodyVelocity + * @since 3.22.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + * @param {number} lineThickness - The line thickness. + */ + renderBodyVelocity: function (bodies, graphics, lineColor, lineOpacity, lineThickness) + { + graphics.lineStyle(lineThickness, lineColor, lineOpacity); + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + graphics.lineBetween( + body.position.x, + body.position.y, + body.position.x + (body.position.x - body.positionPrev.x) * 2, + body.position.y + (body.position.y - body.positionPrev.y) * 2 + ); + } + + return this; + }, + + /** + * Renders the given array of Bodies to the debug graphics instance. + * + * Called automatically by the `postUpdate` method. + * + * @method Phaser.Physics.Matter.World#renderBodies + * @private + * @since 3.14.0 + * + * @param {array} bodies - An array of bodies from the localWorld. + */ + renderBodies: function (bodies) + { + var graphics = this.debugGraphic; + + var config = this.debugConfig; + + var showBody = config.showBody; + var showStaticBody = config.showStaticBody; + var showSleeping = config.showSleeping; + var showInternalEdges = config.showInternalEdges; + var showConvexHulls = config.showConvexHulls; + + var renderFill = config.renderFill; + var renderLine = config.renderLine; + + var staticBodySleepOpacity = config.staticBodySleepOpacity; + var sleepFillColor = config.sleepFillColor; + var sleepLineColor = config.sleepLineColor; + + var hullColor = config.hullColor; + + for (var i = 0; i < bodies.length; i++) + { + var body = bodies[i]; + + // 1) Don't show invisible bodies + if (!body.render.visible) + { + continue; + } + + // 2) Don't show static bodies, OR + // 3) Don't show dynamic bodies + if ((!showStaticBody && body.isStatic) || (!showBody && !body.isStatic)) + { + continue; + } + + var lineColor = body.render.lineColor; + var lineOpacity = body.render.lineOpacity; + var lineThickness = body.render.lineThickness; + var fillColor = body.render.fillColor; + var fillOpacity = body.render.fillOpacity; + + if (showSleeping && body.isSleeping) + { + if (body.isStatic) + { + lineOpacity *= staticBodySleepOpacity; + fillOpacity *= staticBodySleepOpacity; + } + else + { + lineColor = sleepLineColor; + fillColor = sleepFillColor; + } + } + + if (!renderFill) + { + fillColor = null; + } + + if (!renderLine) + { + lineColor = null; + } + + this.renderBody(body, graphics, showInternalEdges, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity); + + var partsLength = body.parts.length; + + if (showConvexHulls && partsLength > 1) + { + this.renderConvexHull(body, graphics, hullColor, lineThickness); + } + } + }, + + /** + * Renders a single Matter Body to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Body to your own Graphics instance. + * + * If you don't wish to render a line around the body, set the `lineColor` parameter to `null`. + * Equally, if you don't wish to render a fill, set the `fillColor` parameter to `null`. + * + * @method Phaser.Physics.Matter.World#renderBody + * @since 3.22.0 + * + * @param {MatterJS.BodyType} body - The Matter Body to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {boolean} showInternalEdges - Render internal edges of the polygon? + * @param {number} [lineColor] - The line color. + * @param {number} [lineOpacity] - The line opacity, between 0 and 1. + * @param {number} [lineThickness=1] - The line thickness. + * @param {number} [fillColor] - The fill color. + * @param {number} [fillOpacity] - The fill opacity, between 0 and 1. + * + * @return {this} This Matter World instance for method chaining. + */ + renderBody: function (body, graphics, showInternalEdges, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) + { + if (lineColor === undefined) { lineColor = null; } + if (lineOpacity === undefined) { lineOpacity = null; } + if (lineThickness === undefined) { lineThickness = 1; } + if (fillColor === undefined) { fillColor = null; } + if (fillOpacity === undefined) { fillOpacity = null; } + + var config = this.debugConfig; + + var sensorFillColor = config.sensorFillColor; + var sensorLineColor = config.sensorLineColor; + + // Handle compound parts + var parts = body.parts; + var partsLength = parts.length; + + for (var k = (partsLength > 1) ? 1 : 0; k < partsLength; k++) + { + var part = parts[k]; + var render = part.render; + var opacity = render.opacity; + + if (!render.visible || opacity === 0 || (part.isSensor && !config.showSensors)) + { + continue; + } + + // Part polygon + var circleRadius = part.circleRadius; + + graphics.beginPath(); + + if (part.isSensor) + { + if (fillColor !== null) + { + graphics.fillStyle(sensorFillColor, fillOpacity * opacity); + } + + if (lineColor !== null) + { + graphics.lineStyle(lineThickness, sensorLineColor, lineOpacity * opacity); + } + } + else + { + if (fillColor !== null) + { + graphics.fillStyle(fillColor, fillOpacity * opacity); + } + + if (lineColor !== null) + { + graphics.lineStyle(lineThickness, lineColor, lineOpacity * opacity); + } + } + + if (circleRadius) + { + graphics.arc(part.position.x, part.position.y, circleRadius, 0, 2 * Math.PI); + } + else + { + var vertices = part.vertices; + var vertLength = vertices.length; + + graphics.moveTo(vertices[0].x, vertices[0].y); + + for (var j = 1; j < vertLength; j++) + { + var vert = vertices[j]; + + if (!vertices[j - 1].isInternal || showInternalEdges) + { + graphics.lineTo(vert.x, vert.y); + } + else + { + graphics.moveTo(vert.x, vert.y); + } + + if (j < vertLength && vert.isInternal && !showInternalEdges) + { + var nextIndex = (j + 1) % vertLength; + + graphics.moveTo(vertices[nextIndex].x, vertices[nextIndex].y); + } + } + + graphics.closePath(); + } + + if (fillColor !== null) + { + graphics.fillPath(); + } + + if (lineColor !== null) + { + graphics.strokePath(); + } + } + + if (config.showPositions && !body.isStatic) + { + var px = body.position.x; + var py = body.position.y; + var hs = Math.ceil(config.positionSize / 2); + + graphics.fillStyle(config.positionColor, 1); + graphics.fillRect(px - hs, py - hs, config.positionSize, config.positionSize); + } + + return this; + }, + + /** + * Renders the Convex Hull for a single Matter Body to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Body hull to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderConvexHull + * @since 3.22.0 + * + * @param {MatterJS.BodyType} body - The Matter Body to be rendered. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} hullColor - The color used to render the hull. + * @param {number} [lineThickness=1] - The hull line thickness. + * + * @return {this} This Matter World instance for method chaining. + */ + renderConvexHull: function (body, graphics, hullColor, lineThickness) + { + if (lineThickness === undefined) { lineThickness = 1; } + + var parts = body.parts; + var partsLength = parts.length; + + // Render Convex Hulls + if (partsLength > 1) + { + var verts = body.vertices; + + graphics.lineStyle(lineThickness, hullColor); + + graphics.beginPath(); + + graphics.moveTo(verts[0].x, verts[0].y); + + for (var v = 1; v < verts.length; v++) + { + graphics.lineTo(verts[v].x, verts[v].y); + } + + graphics.lineTo(verts[0].x, verts[0].y); + + graphics.strokePath(); + } + + return this; + }, + + /** + * Renders all of the constraints in the world (unless they are specifically set to invisible). + * + * Called automatically by the `postUpdate` method. + * + * @method Phaser.Physics.Matter.World#renderJoints + * @private + * @since 3.14.0 + */ + renderJoints: function () + { + var graphics = this.debugGraphic; + + // Render constraints + var constraints = Composite.allConstraints(this.localWorld); + + for (var i = 0; i < constraints.length; i++) + { + var config = constraints[i].render; + + var lineColor = config.lineColor; + var lineOpacity = config.lineOpacity; + var lineThickness = config.lineThickness; + var pinSize = config.pinSize; + var anchorColor = config.anchorColor; + var anchorSize = config.anchorSize; + + this.renderConstraint(constraints[i], graphics, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize); + } + }, + + /** + * Renders a single Matter Constraint, such as a Pin or a Spring, to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Constraint to your own Graphics instance. + * + * @method Phaser.Physics.Matter.World#renderConstraint + * @since 3.22.0 + * + * @param {MatterJS.ConstraintType} constraint - The Matter Constraint to render. + * @param {Phaser.GameObjects.Graphics} graphics - The Graphics object to render to. + * @param {number} lineColor - The line color. + * @param {number} lineOpacity - The line opacity, between 0 and 1. + * @param {number} lineThickness - The line thickness. + * @param {number} pinSize - If this constraint is a pin, this sets the size of the pin circle. + * @param {number} anchorColor - The color used when rendering this constraints anchors. Set to `null` to not render anchors. + * @param {number} anchorSize - The size of the anchor circle, if this constraint has anchors and is rendering them. + * + * @return {this} This Matter World instance for method chaining. + */ + renderConstraint: function (constraint, graphics, lineColor, lineOpacity, lineThickness, pinSize, anchorColor, anchorSize) + { + var render = constraint.render; + + if (!render.visible || !constraint.pointA || !constraint.pointB) + { + return this; + } + + graphics.lineStyle(lineThickness, lineColor, lineOpacity); + + var bodyA = constraint.bodyA; + var bodyB = constraint.bodyB; + var start; + var end; + + if (bodyA) + { + start = Vector.add(bodyA.position, constraint.pointA); + } + else + { + start = constraint.pointA; + } + + if (render.type === 'pin') + { + graphics.strokeCircle(start.x, start.y, pinSize); + } + else + { + if (bodyB) + { + end = Vector.add(bodyB.position, constraint.pointB); + } + else + { + end = constraint.pointB; + } + + graphics.beginPath(); + graphics.moveTo(start.x, start.y); + + if (render.type === 'spring') + { + var delta = Vector.sub(end, start); + var normal = Vector.perp(Vector.normalise(delta)); + var coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)); + var offset; + + for (var j = 1; j < coils; j += 1) + { + offset = (j % 2 === 0) ? 1 : -1; + + graphics.lineTo( + start.x + delta.x * (j / coils) + normal.x * offset * 4, + start.y + delta.y * (j / coils) + normal.y * offset * 4 + ); + } + } + + graphics.lineTo(end.x, end.y); + } + + graphics.strokePath(); + + if (render.anchors && anchorSize > 0) + { + graphics.fillStyle(anchorColor); + graphics.fillCircle(start.x, start.y, anchorSize); + graphics.fillCircle(end.x, end.y, anchorSize); + } + + return this; + }, + + /** + * Resets the internal collision IDs that Matter.JS uses for Body collision groups. + * + * You should call this before destroying your game if you need to restart the game + * again on the same page, without first reloading the page. Or, if you wish to + * consistently destroy a Scene that contains Matter.js and then run it again + * later in the same game. + * + * @method Phaser.Physics.Matter.World#resetCollisionIDs + * @since 3.17.0 + */ + resetCollisionIDs: function () + { + Body._nextCollidingGroupId = 1; + Body._nextNonCollidingGroupId = -1; + Body._nextCategory = 0x0001; + + return this; + }, + + /** + * Will remove all Matter physics event listeners and clear the matter physics world, + * engine and any debug graphics, if any. + * + * @method Phaser.Physics.Matter.World#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + MatterEvents.off(this.engine); + + this.removeAllListeners(); + + MatterWorld.clear(this.localWorld, false); + + Engine.clear(this.engine); + + if (this.drawDebug) + { + this.debugGraphic.destroy(); + } + }, + + /** + * Will remove all Matter physics event listeners and clear the matter physics world, + * engine and any debug graphics, if any. + * + * After destroying the world it cannot be re-used again. + * + * @method Phaser.Physics.Matter.World#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + } + +}); + +module.exports = World; diff --git a/src/physics/matter-js/components/Bounce.js b/src/physics/matter-js/components/Bounce.js index c0b1c6bf7..77749079b 100644 --- a/src/physics/matter-js/components/Bounce.js +++ b/src/physics/matter-js/components/Bounce.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A component to set restitution on objects. - * - * @namespace Phaser.Physics.Matter.Components.Bounce - * @since 3.0.0 - */ -var Bounce = { - - /** - * Sets the restitution on the physics object. - * - * @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 {Phaser.GameObjects.GameObject} This Game Object. - */ - setBounce: function (value) - { - this.body.restitution = value; - - return this; - } - -}; - -module.exports = Bounce; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A component to set restitution on objects. + * + * @namespace Phaser.Physics.Matter.Components.Bounce + * @since 3.0.0 + */ +var Bounce = { + + /** + * Sets the restitution on the physics object. + * + * @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 {Phaser.GameObjects.GameObject} This Game Object. + */ + setBounce: function (value) + { + this.body.restitution = value; + + return this; + } + +}; + +module.exports = Bounce; diff --git a/src/physics/matter-js/components/Collision.js b/src/physics/matter-js/components/Collision.js index a538de061..31d30d6c7 100644 --- a/src/physics/matter-js/components/Collision.js +++ b/src/physics/matter-js/components/Collision.js @@ -1,180 +1,180 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Contains methods for changing the collision filter of a Matter Body. Should be used as a mixin and not called directly. - * - * @namespace Phaser.Physics.Matter.Components.Collision - * @since 3.0.0 - */ -var Collision = { - - /** - * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. - * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * - * @method Phaser.Physics.Matter.Components.Collision#setCollisionCategory - * @since 3.0.0 - * - * @param {number} value - Unique category bitfield. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCollisionCategory: function (value) - { - this.body.collisionFilter.category = value; - - return this; - }, - - /** - * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, - * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, - * they will never collide. - * - * @method Phaser.Physics.Matter.Components.Collision#setCollisionGroup - * @since 3.0.0 - * - * @param {number} value - Unique group index. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCollisionGroup: function (value) - { - this.body.collisionFilter.group = value; - - return this; - }, - - /** - * 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 {Phaser.GameObjects.GameObject} This Game Object. - */ - setCollidesWith: function (categories) - { - var flags = 0; - - if (!Array.isArray(categories)) - { - flags = categories; - } - else - { - for (var i = 0; i < categories.length; i++) - { - flags |= categories[i]; - } - } - - this.body.collisionFilter.mask = flags; - - return this; - }, - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * - * @method Phaser.Physics.Matter.Components.Collision#setOnCollide - * @since 3.22.0 - * - * @param {function} callback - The callback to invoke when this body starts colliding with another. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setOnCollide: function (callback) - { - this.body.onCollideCallback = callback; - - return this; - }, - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * - * @method Phaser.Physics.Matter.Components.Collision#setOnCollideEnd - * @since 3.22.0 - * - * @param {function} callback - The callback to invoke when this body stops colliding with another. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setOnCollideEnd: function (callback) - { - this.body.onCollideEndCallback = callback; - - return this; - }, - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * - * @method Phaser.Physics.Matter.Components.Collision#setOnCollideActive - * @since 3.22.0 - * - * @param {function} callback - The callback to invoke for the duration of this body colliding with another. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setOnCollideActive: function (callback) - { - this.body.onCollideActiveCallback = callback; - - return this; - }, - - /** - * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * - * @method Phaser.Physics.Matter.Components.Collision#setOnCollideWith - * @since 3.22.0 - * - * @param {(MatterJS.Body|MatterJS.Body[])} body - The body, or an array of bodies, to test for collisions with. - * @param {function} callback - The callback to invoke when this body collides with the given body or bodies. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setOnCollideWith: function (body, callback) - { - if (!Array.isArray(body)) - { - body = [ body ]; - } - - for (var i = 0; i < body.length; i++) - { - var src = (body[i].hasOwnProperty('body')) ? body[i].body : body[i]; - - this.body.setOnCollideWith(src, callback); - } - - return this; - } - -}; - -module.exports = Collision; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Contains methods for changing the collision filter of a Matter Body. Should be used as a mixin and not called directly. + * + * @namespace Phaser.Physics.Matter.Components.Collision + * @since 3.0.0 + */ +var Collision = { + + /** + * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. + * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * + * @method Phaser.Physics.Matter.Components.Collision#setCollisionCategory + * @since 3.0.0 + * + * @param {number} value - Unique category bitfield. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollisionCategory: function (value) + { + this.body.collisionFilter.category = value; + + return this; + }, + + /** + * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, + * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, + * they will never collide. + * + * @method Phaser.Physics.Matter.Components.Collision#setCollisionGroup + * @since 3.0.0 + * + * @param {number} value - Unique group index. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollisionGroup: function (value) + { + this.body.collisionFilter.group = value; + + return this; + }, + + /** + * 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 {Phaser.GameObjects.GameObject} This Game Object. + */ + setCollidesWith: function (categories) + { + var flags = 0; + + if (!Array.isArray(categories)) + { + flags = categories; + } + else + { + for (var i = 0; i < categories.length; i++) + { + flags |= categories[i]; + } + } + + this.body.collisionFilter.mask = flags; + + return this; + }, + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollide + * @since 3.22.0 + * + * @param {function} callback - The callback to invoke when this body starts colliding with another. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollide: function (callback) + { + this.body.onCollideCallback = callback; + + return this; + }, + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollideEnd + * @since 3.22.0 + * + * @param {function} callback - The callback to invoke when this body stops colliding with another. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollideEnd: function (callback) + { + this.body.onCollideEndCallback = callback; + + return this; + }, + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollideActive + * @since 3.22.0 + * + * @param {function} callback - The callback to invoke for the duration of this body colliding with another. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollideActive: function (callback) + { + this.body.onCollideActiveCallback = callback; + + return this; + }, + + /** + * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * + * @method Phaser.Physics.Matter.Components.Collision#setOnCollideWith + * @since 3.22.0 + * + * @param {(MatterJS.Body|MatterJS.Body[])} body - The body, or an array of bodies, to test for collisions with. + * @param {function} callback - The callback to invoke when this body collides with the given body or bodies. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setOnCollideWith: function (body, callback) + { + if (!Array.isArray(body)) + { + body = [ body ]; + } + + for (var i = 0; i < body.length; i++) + { + var src = (body[i].hasOwnProperty('body')) ? body[i].body : body[i]; + + this.body.setOnCollideWith(src, callback); + } + + return this; + } + +}; + +module.exports = Collision; diff --git a/src/physics/matter-js/components/Force.js b/src/physics/matter-js/components/Force.js index 87fbac383..581e52998 100644 --- a/src/physics/matter-js/components/Force.js +++ b/src/physics/matter-js/components/Force.js @@ -1,150 +1,150 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('../lib/body/Body'); - -/** - * A component to apply force to Matter.js bodies. - * - * @namespace Phaser.Physics.Matter.Components.Force - * @since 3.0.0 - */ -var Force = { - - // force = vec2 / point - - /** - * Applies a force to a body. - * - * @method Phaser.Physics.Matter.Components.Force#applyForce - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} force - A Vector that specifies the force to apply. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - applyForce: function (force) - { - this._tempVec2.set(this.body.position.x, this.body.position.y); - - Body.applyForce(this.body, this._tempVec2, force); - - return this; - }, - - /** - * Applies a force to a body from a given position. - * - * @method Phaser.Physics.Matter.Components.Force#applyForceFrom - * @since 3.0.0 - * - * @param {Phaser.Math.Vector2} position - The position in which the force comes from. - * @param {Phaser.Math.Vector2} force - A Vector that specifies the force to apply. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - applyForceFrom: function (position, force) - { - Body.applyForce(this.body, position, force); - - return this; - }, - - /** - * Apply thrust to the forward position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * - * @method Phaser.Physics.Matter.Components.Force#thrust - * @since 3.0.0 - * - * @param {number} speed - A speed value to be applied to a directional force. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - thrust: function (speed) - { - var angle = this.body.angle; - - this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); - - Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); - - return this; - }, - - /** - * Apply thrust to the left position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * - * @method Phaser.Physics.Matter.Components.Force#thrustLeft - * @since 3.0.0 - * - * @param {number} speed - A speed value to be applied to a directional force. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - thrustLeft: function (speed) - { - var angle = this.body.angle - Math.PI / 2; - - this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); - - Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); - - return this; - }, - - /** - * Apply thrust to the right position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * - * @method Phaser.Physics.Matter.Components.Force#thrustRight - * @since 3.0.0 - * - * @param {number} speed - A speed value to be applied to a directional force. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - thrustRight: function (speed) - { - var angle = this.body.angle + Math.PI / 2; - - this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); - - Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); - - return this; - }, - - /** - * Apply thrust to the back position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * - * @method Phaser.Physics.Matter.Components.Force#thrustBack - * @since 3.0.0 - * - * @param {number} speed - A speed value to be applied to a directional force. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - thrustBack: function (speed) - { - var angle = this.body.angle - Math.PI; - - this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); - - Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); - - return this; - } - -}; - -module.exports = Force; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('../lib/body/Body'); + +/** + * A component to apply force to Matter.js bodies. + * + * @namespace Phaser.Physics.Matter.Components.Force + * @since 3.0.0 + */ +var Force = { + + // force = vec2 / point + + /** + * Applies a force to a body. + * + * @method Phaser.Physics.Matter.Components.Force#applyForce + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} force - A Vector that specifies the force to apply. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + applyForce: function (force) + { + this._tempVec2.set(this.body.position.x, this.body.position.y); + + Body.applyForce(this.body, this._tempVec2, force); + + return this; + }, + + /** + * Applies a force to a body from a given position. + * + * @method Phaser.Physics.Matter.Components.Force#applyForceFrom + * @since 3.0.0 + * + * @param {Phaser.Math.Vector2} position - The position in which the force comes from. + * @param {Phaser.Math.Vector2} force - A Vector that specifies the force to apply. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + applyForceFrom: function (position, force) + { + Body.applyForce(this.body, position, force); + + return this; + }, + + /** + * Apply thrust to the forward position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrust + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrust: function (speed) + { + var angle = this.body.angle; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + }, + + /** + * Apply thrust to the left position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrustLeft + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrustLeft: function (speed) + { + var angle = this.body.angle - Math.PI / 2; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + }, + + /** + * Apply thrust to the right position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrustRight + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrustRight: function (speed) + { + var angle = this.body.angle + Math.PI / 2; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + }, + + /** + * Apply thrust to the back position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * + * @method Phaser.Physics.Matter.Components.Force#thrustBack + * @since 3.0.0 + * + * @param {number} speed - A speed value to be applied to a directional force. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + thrustBack: function (speed) + { + var angle = this.body.angle - Math.PI; + + this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); + + Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); + + return this; + } + +}; + +module.exports = Force; diff --git a/src/physics/matter-js/components/Friction.js b/src/physics/matter-js/components/Friction.js index 4e0595d1f..5469813b6 100644 --- a/src/physics/matter-js/components/Friction.js +++ b/src/physics/matter-js/components/Friction.js @@ -1,84 +1,84 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Contains methods for changing the friction of a Game Object's Matter Body. Should be used a mixin, not called directly. - * - * @namespace Phaser.Physics.Matter.Components.Friction - * @since 3.0.0 - */ -var Friction = { - - /** - * Sets new friction values for this Game Object's Matter Body. - * - * @method Phaser.Physics.Matter.Components.Friction#setFriction - * @since 3.0.0 - * - * @param {number} value - The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. - * @param {number} [air] - If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. - * @param {number} [fstatic] - If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFriction: function (value, air, fstatic) - { - this.body.friction = value; - - if (air !== undefined) - { - this.body.frictionAir = air; - } - - if (fstatic !== undefined) - { - this.body.frictionStatic = fstatic; - } - - return this; - }, - - /** - * Sets a new air resistance for this Game Object's Matter Body. - * A value of 0 means the Body will never slow as it moves through space. - * The higher the value, the faster a Body slows when moving through space. - * - * @method Phaser.Physics.Matter.Components.Friction#setFrictionAir - * @since 3.0.0 - * - * @param {number} value - The new air resistance for the Body. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFrictionAir: function (value) - { - this.body.frictionAir = value; - - return this; - }, - - /** - * Sets a new static friction for this Game Object's Matter Body. - * A value of 0 means the Body will never "stick" when it is nearly stationary. - * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. - * - * @method Phaser.Physics.Matter.Components.Friction#setFrictionStatic - * @since 3.0.0 - * - * @param {number} value - The new static friction for the Body. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setFrictionStatic: function (value) - { - this.body.frictionStatic = value; - - return this; - } - -}; - -module.exports = Friction; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Contains methods for changing the friction of a Game Object's Matter Body. Should be used a mixin, not called directly. + * + * @namespace Phaser.Physics.Matter.Components.Friction + * @since 3.0.0 + */ +var Friction = { + + /** + * Sets new friction values for this Game Object's Matter Body. + * + * @method Phaser.Physics.Matter.Components.Friction#setFriction + * @since 3.0.0 + * + * @param {number} value - The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. + * @param {number} [air] - If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. + * @param {number} [fstatic] - If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFriction: function (value, air, fstatic) + { + this.body.friction = value; + + if (air !== undefined) + { + this.body.frictionAir = air; + } + + if (fstatic !== undefined) + { + this.body.frictionStatic = fstatic; + } + + return this; + }, + + /** + * Sets a new air resistance for this Game Object's Matter Body. + * A value of 0 means the Body will never slow as it moves through space. + * The higher the value, the faster a Body slows when moving through space. + * + * @method Phaser.Physics.Matter.Components.Friction#setFrictionAir + * @since 3.0.0 + * + * @param {number} value - The new air resistance for the Body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionAir: function (value) + { + this.body.frictionAir = value; + + return this; + }, + + /** + * Sets a new static friction for this Game Object's Matter Body. + * A value of 0 means the Body will never "stick" when it is nearly stationary. + * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. + * + * @method Phaser.Physics.Matter.Components.Friction#setFrictionStatic + * @since 3.0.0 + * + * @param {number} value - The new static friction for the Body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setFrictionStatic: function (value) + { + this.body.frictionStatic = value; + + return this; + } + +}; + +module.exports = Friction; diff --git a/src/physics/matter-js/components/Gravity.js b/src/physics/matter-js/components/Gravity.js index 3180fc970..721c142f8 100644 --- a/src/physics/matter-js/components/Gravity.js +++ b/src/physics/matter-js/components/Gravity.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A component to manipulate world gravity for Matter.js bodies. - * - * @namespace Phaser.Physics.Matter.Components.Gravity - * @since 3.0.0 - */ -var Gravity = { - - /** - * A togglable function for ignoring world gravity in real-time on the current body. - * - * @method Phaser.Physics.Matter.Components.Gravity#setIgnoreGravity - * @since 3.0.0 - * - * @param {boolean} value - Set to true to ignore the effect of world gravity, or false to not ignore it. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setIgnoreGravity: function (value) - { - this.body.ignoreGravity = value; - - return this; - } - -}; - -module.exports = Gravity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A component to manipulate world gravity for Matter.js bodies. + * + * @namespace Phaser.Physics.Matter.Components.Gravity + * @since 3.0.0 + */ +var Gravity = { + + /** + * A togglable function for ignoring world gravity in real-time on the current body. + * + * @method Phaser.Physics.Matter.Components.Gravity#setIgnoreGravity + * @since 3.0.0 + * + * @param {boolean} value - Set to true to ignore the effect of world gravity, or false to not ignore it. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setIgnoreGravity: function (value) + { + this.body.ignoreGravity = value; + + return this; + } + +}; + +module.exports = Gravity; diff --git a/src/physics/matter-js/components/Mass.js b/src/physics/matter-js/components/Mass.js index 3b10ece78..346c6a270 100644 --- a/src/physics/matter-js/components/Mass.js +++ b/src/physics/matter-js/components/Mass.js @@ -1,76 +1,76 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('../lib/body/Body'); -var Vector2 = require('../../../math/Vector2'); - -/** - * Allows accessing the mass, density, and center of mass of a Matter-enabled Game Object. Should be used as a mixin and not directly. - * - * @namespace Phaser.Physics.Matter.Components.Mass - * @since 3.0.0 - */ -var Mass = { - - /** - * Sets the mass of the Game Object's Matter Body. - * - * @method Phaser.Physics.Matter.Components.Mass#setMass - * @since 3.0.0 - * - * @param {number} value - The new mass of the body. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setMass: function (value) - { - Body.setMass(this.body, value); - - return this; - }, - - /** - * Sets density of the body. - * - * @method Phaser.Physics.Matter.Components.Mass#setDensity - * @since 3.0.0 - * - * @param {number} value - The new density of the body. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setDensity: function (value) - { - Body.setDensity(this.body, value); - - return this; - }, - - /** - * The body's center of mass. - * - * Calling this creates a new `Vector2 each time to avoid mutation. - * - * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. - * - * @name Phaser.Physics.Matter.Components.Mass#centerOfMass - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.10.0 - * - * @return {Phaser.Math.Vector2} The center of mass. - */ - centerOfMass: { - - get: function () - { - return new Vector2(this.body.centerOfMass.x, this.body.centerOfMass.y); - } - } - -}; - -module.exports = Mass; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('../lib/body/Body'); +var Vector2 = require('../../../math/Vector2'); + +/** + * Allows accessing the mass, density, and center of mass of a Matter-enabled Game Object. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.Mass + * @since 3.0.0 + */ +var Mass = { + + /** + * Sets the mass of the Game Object's Matter Body. + * + * @method Phaser.Physics.Matter.Components.Mass#setMass + * @since 3.0.0 + * + * @param {number} value - The new mass of the body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setMass: function (value) + { + Body.setMass(this.body, value); + + return this; + }, + + /** + * Sets density of the body. + * + * @method Phaser.Physics.Matter.Components.Mass#setDensity + * @since 3.0.0 + * + * @param {number} value - The new density of the body. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setDensity: function (value) + { + Body.setDensity(this.body, value); + + return this; + }, + + /** + * The body's center of mass. + * + * Calling this creates a new `Vector2 each time to avoid mutation. + * + * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. + * + * @name Phaser.Physics.Matter.Components.Mass#centerOfMass + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.10.0 + * + * @return {Phaser.Math.Vector2} The center of mass. + */ + centerOfMass: { + + get: function () + { + return new Vector2(this.body.centerOfMass.x, this.body.centerOfMass.y); + } + } + +}; + +module.exports = Mass; diff --git a/src/physics/matter-js/components/Sensor.js b/src/physics/matter-js/components/Sensor.js index 6ff17db18..1dc418ba8 100644 --- a/src/physics/matter-js/components/Sensor.js +++ b/src/physics/matter-js/components/Sensor.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Enables a Matter-enabled Game Object to be a sensor. Should be used as a mixin and not directly. - * - * @namespace Phaser.Physics.Matter.Components.Sensor - * @since 3.0.0 - */ -var Sensor = { - - /** - * Set the body belonging to this Game Object to be a sensor. - * Sensors trigger collision events, but don't react with colliding body physically. - * - * @method Phaser.Physics.Matter.Components.Sensor#setSensor - * @since 3.0.0 - * - * @param {boolean} value - `true` to set the body as a sensor, or `false` to disable it. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setSensor: function (value) - { - this.body.isSensor = value; - - return this; - }, - - /** - * Is the body belonging to this Game Object a sensor or not? - * - * @method Phaser.Physics.Matter.Components.Sensor#isSensor - * @since 3.0.0 - * - * @return {boolean} `true` if the body is a sensor, otherwise `false`. - */ - isSensor: function () - { - return this.body.isSensor; - } - -}; - -module.exports = Sensor; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Enables a Matter-enabled Game Object to be a sensor. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.Sensor + * @since 3.0.0 + */ +var Sensor = { + + /** + * Set the body belonging to this Game Object to be a sensor. + * Sensors trigger collision events, but don't react with colliding body physically. + * + * @method Phaser.Physics.Matter.Components.Sensor#setSensor + * @since 3.0.0 + * + * @param {boolean} value - `true` to set the body as a sensor, or `false` to disable it. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setSensor: function (value) + { + this.body.isSensor = value; + + return this; + }, + + /** + * Is the body belonging to this Game Object a sensor or not? + * + * @method Phaser.Physics.Matter.Components.Sensor#isSensor + * @since 3.0.0 + * + * @return {boolean} `true` if the body is a sensor, otherwise `false`. + */ + isSensor: function () + { + return this.body.isSensor; + } + +}; + +module.exports = Sensor; diff --git a/src/physics/matter-js/components/SetBody.js b/src/physics/matter-js/components/SetBody.js index 7c4230cc9..9badf52fa 100644 --- a/src/physics/matter-js/components/SetBody.js +++ b/src/physics/matter-js/components/SetBody.js @@ -1,284 +1,284 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Bodies = require('../lib/factory/Bodies'); -var Body = require('../lib/body/Body'); -var FuzzyEquals = require('../../../math/fuzzy/Equal'); -var GetFastValue = require('../../../utils/object/GetFastValue'); -var PhysicsEditorParser = require('../PhysicsEditorParser'); -var PhysicsJSONParser = require('../PhysicsJSONParser'); -var Vertices = require('../lib/geometry/Vertices'); - -/** - * Enables a Matter-enabled Game Object to set its Body. Should be used as a mixin and not directly. - * - * @namespace Phaser.Physics.Matter.Components.SetBody - * @since 3.0.0 - */ -var SetBody = { - - /** - * Set the body on a Game Object to a rectangle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * - * @method Phaser.Physics.Matter.Components.SetBody#setRectangle - * @since 3.0.0 - * - * @param {number} width - Width of the rectangle. - * @param {number} height - Height of the rectangle. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setRectangle: function (width, height, options) - { - return this.setBody({ type: 'rectangle', width: width, height: height }, options); - }, - - /** - * Set the body on a Game Object to a circle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * - * @method Phaser.Physics.Matter.Components.SetBody#setCircle - * @since 3.0.0 - * - * @param {number} radius - The radius of the circle. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setCircle: function (radius, options) - { - return this.setBody({ type: 'circle', radius: radius }, options); - }, - - /** - * Set the body on the Game Object to a polygon shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * - * @method Phaser.Physics.Matter.Components.SetBody#setPolygon - * @since 3.0.0 - * - * @param {number} sides - The number of sides the polygon will have. - * @param {number} radius - The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setPolygon: function (radius, sides, options) - { - return this.setBody({ type: 'polygon', sides: sides, radius: radius }, options); - }, - - /** - * Set the body on the Game Object to a trapezoid shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * - * @method Phaser.Physics.Matter.Components.SetBody#setTrapezoid - * @since 3.0.0 - * - * @param {number} width - The width of the trapezoid Body. - * @param {number} height - The height of the trapezoid Body. - * @param {number} slope - The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setTrapezoid: function (width, height, slope, options) - { - return this.setBody({ type: 'trapezoid', width: width, height: height, slope: slope }, options); - }, - - /** - * Set this Game Object to use the given existing Matter Body. - * - * The body is first removed from the world before being added to this Game Object. - * - * @method Phaser.Physics.Matter.Components.SetBody#setExistingBody - * @since 3.0.0 - * - * @param {MatterJS.BodyType} body - The Body this Game Object should use. - * @param {boolean} [addToWorld=true] - Should the body be immediately added to the World? - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setExistingBody: function (body, addToWorld) - { - if (addToWorld === undefined) { addToWorld = true; } - - if (this.body) - { - this.world.remove(this.body, true); - } - - this.body = body; - - for (var i = 0; i < body.parts.length; i++) - { - body.parts[i].gameObject = this; - } - - var _this = this; - - body.destroy = function destroy () - { - _this.world.remove(_this.body, true); - _this.body.gameObject = null; - }; - - if (addToWorld) - { - if (this.world.has(body)) - { - // Because it could be part of another Composite - this.world.remove(body, true); - } - - this.world.add(body); - } - - if (this._originComponent) - { - var rx = body.render.sprite.xOffset; - var ry = body.render.sprite.yOffset; - - var comx = body.centerOfMass.x; - var comy = body.centerOfMass.y; - - if (FuzzyEquals(comx, 0.5) && FuzzyEquals(comy, 0.5)) - { - this.setOrigin(rx + 0.5, ry + 0.5); - } - else - { - var cx = body.centerOffset.x; - var cy = body.centerOffset.y; - - this.setOrigin(rx + (cx / this.displayWidth), ry + (cy / this.displayHeight)); - } - } - - return this; - }, - - /** - * Set this Game Object to create and use a new Body based on the configuration object given. - * - * Calling this method resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if 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 {Phaser.GameObjects.GameObject} This Game Object. - */ - setBody: function (config, options) - { - if (!config) - { - return this; - } - - var body; - - // Allow them to do: shape: 'circle' instead of shape: { type: 'circle' } - if (typeof config === 'string') - { - // Using defaults - config = { type: config }; - } - - var shapeType = GetFastValue(config, 'type', 'rectangle'); - var bodyX = GetFastValue(config, 'x', this._tempVec2.x); - var bodyY = GetFastValue(config, 'y', this._tempVec2.y); - var bodyWidth = GetFastValue(config, 'width', this.width); - var bodyHeight = GetFastValue(config, 'height', this.height); - - switch (shapeType) - { - case 'rectangle': - body = Bodies.rectangle(bodyX, bodyY, bodyWidth, bodyHeight, options); - break; - - case 'circle': - var radius = GetFastValue(config, 'radius', Math.max(bodyWidth, bodyHeight) / 2); - var maxSides = GetFastValue(config, 'maxSides', 25); - body = Bodies.circle(bodyX, bodyY, radius, options, maxSides); - break; - - case 'trapezoid': - var slope = GetFastValue(config, 'slope', 0.5); - body = Bodies.trapezoid(bodyX, bodyY, bodyWidth, bodyHeight, slope, options); - break; - - case 'polygon': - var sides = GetFastValue(config, 'sides', 5); - var pRadius = GetFastValue(config, 'radius', Math.max(bodyWidth, bodyHeight) / 2); - body = Bodies.polygon(bodyX, bodyY, sides, pRadius, options); - break; - - case 'fromVertices': - case 'fromVerts': - - var verts = GetFastValue(config, 'verts', null); - - if (verts) - { - // Has the verts array come from Vertices.fromPath, or is it raw? - if (typeof verts === 'string') - { - verts = Vertices.fromPath(verts); - } - - if (this.body && !this.body.hasOwnProperty('temp')) - { - Body.setVertices(this.body, verts); - - body = this.body; - } - else - { - var flagInternal = GetFastValue(config, 'flagInternal', false); - var removeCollinear = GetFastValue(config, 'removeCollinear', 0.01); - var minimumArea = GetFastValue(config, 'minimumArea', 10); - - body = Bodies.fromVertices(bodyX, bodyY, verts, options, flagInternal, removeCollinear, minimumArea); - } - } - - break; - - case 'fromPhysicsEditor': - body = PhysicsEditorParser.parseBody(bodyX, bodyY, config, options); - break; - - case 'fromPhysicsTracer': - body = PhysicsJSONParser.parseBody(bodyX, bodyY, config, options); - break; - } - - if (body) - { - this.setExistingBody(body, config.addToWorld); - } - - return this; - } - -}; - -module.exports = SetBody; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Bodies = require('../lib/factory/Bodies'); +var Body = require('../lib/body/Body'); +var FuzzyEquals = require('../../../math/fuzzy/Equal'); +var GetFastValue = require('../../../utils/object/GetFastValue'); +var PhysicsEditorParser = require('../PhysicsEditorParser'); +var PhysicsJSONParser = require('../PhysicsJSONParser'); +var Vertices = require('../lib/geometry/Vertices'); + +/** + * Enables a Matter-enabled Game Object to set its Body. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.SetBody + * @since 3.0.0 + */ +var SetBody = { + + /** + * Set the body on a Game Object to a rectangle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setRectangle + * @since 3.0.0 + * + * @param {number} width - Width of the rectangle. + * @param {number} height - Height of the rectangle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setRectangle: function (width, height, options) + { + return this.setBody({ type: 'rectangle', width: width, height: height }, options); + }, + + /** + * Set the body on a Game Object to a circle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setCircle + * @since 3.0.0 + * + * @param {number} radius - The radius of the circle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setCircle: function (radius, options) + { + return this.setBody({ type: 'circle', radius: radius }, options); + }, + + /** + * Set the body on the Game Object to a polygon shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setPolygon + * @since 3.0.0 + * + * @param {number} sides - The number of sides the polygon will have. + * @param {number} radius - The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setPolygon: function (radius, sides, options) + { + return this.setBody({ type: 'polygon', sides: sides, radius: radius }, options); + }, + + /** + * Set the body on the Game Object to a trapezoid shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * + * @method Phaser.Physics.Matter.Components.SetBody#setTrapezoid + * @since 3.0.0 + * + * @param {number} width - The width of the trapezoid Body. + * @param {number} height - The height of the trapezoid Body. + * @param {number} slope - The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setTrapezoid: function (width, height, slope, options) + { + return this.setBody({ type: 'trapezoid', width: width, height: height, slope: slope }, options); + }, + + /** + * Set this Game Object to use the given existing Matter Body. + * + * The body is first removed from the world before being added to this Game Object. + * + * @method Phaser.Physics.Matter.Components.SetBody#setExistingBody + * @since 3.0.0 + * + * @param {MatterJS.BodyType} body - The Body this Game Object should use. + * @param {boolean} [addToWorld=true] - Should the body be immediately added to the World? + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setExistingBody: function (body, addToWorld) + { + if (addToWorld === undefined) { addToWorld = true; } + + if (this.body) + { + this.world.remove(this.body, true); + } + + this.body = body; + + for (var i = 0; i < body.parts.length; i++) + { + body.parts[i].gameObject = this; + } + + var _this = this; + + body.destroy = function destroy () + { + _this.world.remove(_this.body, true); + _this.body.gameObject = null; + }; + + if (addToWorld) + { + if (this.world.has(body)) + { + // Because it could be part of another Composite + this.world.remove(body, true); + } + + this.world.add(body); + } + + if (this._originComponent) + { + var rx = body.render.sprite.xOffset; + var ry = body.render.sprite.yOffset; + + var comx = body.centerOfMass.x; + var comy = body.centerOfMass.y; + + if (FuzzyEquals(comx, 0.5) && FuzzyEquals(comy, 0.5)) + { + this.setOrigin(rx + 0.5, ry + 0.5); + } + else + { + var cx = body.centerOffset.x; + var cy = body.centerOffset.y; + + this.setOrigin(rx + (cx / this.displayWidth), ry + (cy / this.displayHeight)); + } + } + + return this; + }, + + /** + * Set this Game Object to create and use a new Body based on the configuration object given. + * + * Calling this method resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if 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 {Phaser.GameObjects.GameObject} This Game Object. + */ + setBody: function (config, options) + { + if (!config) + { + return this; + } + + var body; + + // Allow them to do: shape: 'circle' instead of shape: { type: 'circle' } + if (typeof config === 'string') + { + // Using defaults + config = { type: config }; + } + + var shapeType = GetFastValue(config, 'type', 'rectangle'); + var bodyX = GetFastValue(config, 'x', this._tempVec2.x); + var bodyY = GetFastValue(config, 'y', this._tempVec2.y); + var bodyWidth = GetFastValue(config, 'width', this.width); + var bodyHeight = GetFastValue(config, 'height', this.height); + + switch (shapeType) + { + case 'rectangle': + body = Bodies.rectangle(bodyX, bodyY, bodyWidth, bodyHeight, options); + break; + + case 'circle': + var radius = GetFastValue(config, 'radius', Math.max(bodyWidth, bodyHeight) / 2); + var maxSides = GetFastValue(config, 'maxSides', 25); + body = Bodies.circle(bodyX, bodyY, radius, options, maxSides); + break; + + case 'trapezoid': + var slope = GetFastValue(config, 'slope', 0.5); + body = Bodies.trapezoid(bodyX, bodyY, bodyWidth, bodyHeight, slope, options); + break; + + case 'polygon': + var sides = GetFastValue(config, 'sides', 5); + var pRadius = GetFastValue(config, 'radius', Math.max(bodyWidth, bodyHeight) / 2); + body = Bodies.polygon(bodyX, bodyY, sides, pRadius, options); + break; + + case 'fromVertices': + case 'fromVerts': + + var verts = GetFastValue(config, 'verts', null); + + if (verts) + { + // Has the verts array come from Vertices.fromPath, or is it raw? + if (typeof verts === 'string') + { + verts = Vertices.fromPath(verts); + } + + if (this.body && !this.body.hasOwnProperty('temp')) + { + Body.setVertices(this.body, verts); + + body = this.body; + } + else + { + var flagInternal = GetFastValue(config, 'flagInternal', false); + var removeCollinear = GetFastValue(config, 'removeCollinear', 0.01); + var minimumArea = GetFastValue(config, 'minimumArea', 10); + + body = Bodies.fromVertices(bodyX, bodyY, verts, options, flagInternal, removeCollinear, minimumArea); + } + } + + break; + + case 'fromPhysicsEditor': + body = PhysicsEditorParser.parseBody(bodyX, bodyY, config, options); + break; + + case 'fromPhysicsTracer': + body = PhysicsJSONParser.parseBody(bodyX, bodyY, config, options); + break; + } + + if (body) + { + this.setExistingBody(body, config.addToWorld); + } + + return this; + } + +}; + +module.exports = SetBody; diff --git a/src/physics/matter-js/components/Sleep.js b/src/physics/matter-js/components/Sleep.js index 8ab26708a..bb1a69349 100644 --- a/src/physics/matter-js/components/Sleep.js +++ b/src/physics/matter-js/components/Sleep.js @@ -1,148 +1,148 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Events = require('../events'); -var Sleeping = require('../lib/core/Sleeping'); -var MatterEvents = require('../lib/core/Events'); - -/** - * Enables a Matter-enabled Game Object to be able to go to sleep. Should be used as a mixin and not directly. - * - * @namespace Phaser.Physics.Matter.Components.Sleep - * @since 3.0.0 - */ -var Sleep = { - - /** - * Sets this Body to sleep. - * - * @method Phaser.Physics.Matter.Components.Sleep#setToSleep - * @since 3.22.0 - * - * @return {this} This Game Object. - */ - setToSleep: function () - { - Sleeping.set(this.body, true); - }, - - /** - * Wakes this Body if asleep. - * - * @method Phaser.Physics.Matter.Components.Sleep#setAwake - * @since 3.22.0 - * - * @return {this} This Game Object. - */ - setAwake: function () - { - Sleeping.set(this.body, false); - }, - - /** - * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). - * - * @method Phaser.Physics.Matter.Components.Sleep#setSleepThreshold - * @since 3.0.0 - * - * @param {number} [value=60] - A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. - * - * @return {this} This Game Object. - */ - setSleepThreshold: function (value) - { - if (value === undefined) { value = 60; } - - this.body.sleepThreshold = value; - - return this; - }, - - /** - * Enable sleep and wake events for this body. - * - * By default when a body goes to sleep, or wakes up, it will not emit any events. - * - * The events are emitted by the Matter World instance and can be listened to via - * the `SLEEP_START` and `SLEEP_END` events. - * - * @method Phaser.Physics.Matter.Components.Sleep#setSleepEvents - * @since 3.0.0 - * - * @param {boolean} start - `true` if you want the sleep start event to be emitted for this body. - * @param {boolean} end - `true` if you want the sleep end event to be emitted for this body. - * - * @return {this} This Game Object. - */ - setSleepEvents: function (start, end) - { - this.setSleepStartEvent(start); - this.setSleepEndEvent(end); - - return this; - }, - - /** - * Enables or disables the Sleep Start event for this body. - * - * @method Phaser.Physics.Matter.Components.Sleep#setSleepStartEvent - * @since 3.0.0 - * - * @param {boolean} value - `true` to enable the sleep event, or `false` to disable it. - * - * @return {this} This Game Object. - */ - setSleepStartEvent: function (value) - { - if (value) - { - var world = this.world; - - MatterEvents.on(this.body, 'sleepStart', function (event) - { - world.emit(Events.SLEEP_START, event, this); - }); - } - else - { - MatterEvents.off(this.body, 'sleepStart'); - } - - return this; - }, - - /** - * Enables or disables the Sleep End event for this body. - * - * @method Phaser.Physics.Matter.Components.Sleep#setSleepEndEvent - * @since 3.0.0 - * - * @param {boolean} value - `true` to enable the sleep event, or `false` to disable it. - * - * @return {this} This Game Object. - */ - setSleepEndEvent: function (value) - { - if (value) - { - var world = this.world; - - MatterEvents.on(this.body, 'sleepEnd', function (event) - { - world.emit(Events.SLEEP_END, event, this); - }); - } - else - { - MatterEvents.off(this.body, 'sleepEnd'); - } - - return this; - } - -}; - -module.exports = Sleep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Events = require('../events'); +var Sleeping = require('../lib/core/Sleeping'); +var MatterEvents = require('../lib/core/Events'); + +/** + * Enables a Matter-enabled Game Object to be able to go to sleep. Should be used as a mixin and not directly. + * + * @namespace Phaser.Physics.Matter.Components.Sleep + * @since 3.0.0 + */ +var Sleep = { + + /** + * Sets this Body to sleep. + * + * @method Phaser.Physics.Matter.Components.Sleep#setToSleep + * @since 3.22.0 + * + * @return {this} This Game Object. + */ + setToSleep: function () + { + Sleeping.set(this.body, true); + }, + + /** + * Wakes this Body if asleep. + * + * @method Phaser.Physics.Matter.Components.Sleep#setAwake + * @since 3.22.0 + * + * @return {this} This Game Object. + */ + setAwake: function () + { + Sleeping.set(this.body, false); + }, + + /** + * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepThreshold + * @since 3.0.0 + * + * @param {number} [value=60] - A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. + * + * @return {this} This Game Object. + */ + setSleepThreshold: function (value) + { + if (value === undefined) { value = 60; } + + this.body.sleepThreshold = value; + + return this; + }, + + /** + * Enable sleep and wake events for this body. + * + * By default when a body goes to sleep, or wakes up, it will not emit any events. + * + * The events are emitted by the Matter World instance and can be listened to via + * the `SLEEP_START` and `SLEEP_END` events. + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepEvents + * @since 3.0.0 + * + * @param {boolean} start - `true` if you want the sleep start event to be emitted for this body. + * @param {boolean} end - `true` if you want the sleep end event to be emitted for this body. + * + * @return {this} This Game Object. + */ + setSleepEvents: function (start, end) + { + this.setSleepStartEvent(start); + this.setSleepEndEvent(end); + + return this; + }, + + /** + * Enables or disables the Sleep Start event for this body. + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepStartEvent + * @since 3.0.0 + * + * @param {boolean} value - `true` to enable the sleep event, or `false` to disable it. + * + * @return {this} This Game Object. + */ + setSleepStartEvent: function (value) + { + if (value) + { + var world = this.world; + + MatterEvents.on(this.body, 'sleepStart', function (event) + { + world.emit(Events.SLEEP_START, event, this); + }); + } + else + { + MatterEvents.off(this.body, 'sleepStart'); + } + + return this; + }, + + /** + * Enables or disables the Sleep End event for this body. + * + * @method Phaser.Physics.Matter.Components.Sleep#setSleepEndEvent + * @since 3.0.0 + * + * @param {boolean} value - `true` to enable the sleep event, or `false` to disable it. + * + * @return {this} This Game Object. + */ + setSleepEndEvent: function (value) + { + if (value) + { + var world = this.world; + + MatterEvents.on(this.body, 'sleepEnd', function (event) + { + world.emit(Events.SLEEP_END, event, this); + }); + } + else + { + MatterEvents.off(this.body, 'sleepEnd'); + } + + return this; + } + +}; + +module.exports = Sleep; diff --git a/src/physics/matter-js/components/Static.js b/src/physics/matter-js/components/Static.js index 0358c4078..851307c3c 100644 --- a/src/physics/matter-js/components/Static.js +++ b/src/physics/matter-js/components/Static.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('../lib/body/Body'); - -/** - * Provides methods used for getting and setting the static state of a physics body. - * - * @namespace Phaser.Physics.Matter.Components.Static - * @since 3.0.0 - */ -var Static = { - - /** - * Changes the physics body to be either static `true` or dynamic `false`. - * - * @method Phaser.Physics.Matter.Components.Static#setStatic - * @since 3.0.0 - * - * @param {boolean} value - `true` to set the body as being static, or `false` to make it dynamic. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setStatic: function (value) - { - Body.setStatic(this.body, value); - - return this; - }, - - /** - * Returns `true` if the body is static, otherwise `false` for a dynamic body. - * - * @method Phaser.Physics.Matter.Components.Static#isStatic - * @since 3.0.0 - * - * @return {boolean} `true` if the body is static, otherwise `false`. - */ - isStatic: function () - { - return this.body.isStatic; - } - -}; - -module.exports = Static; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('../lib/body/Body'); + +/** + * Provides methods used for getting and setting the static state of a physics body. + * + * @namespace Phaser.Physics.Matter.Components.Static + * @since 3.0.0 + */ +var Static = { + + /** + * Changes the physics body to be either static `true` or dynamic `false`. + * + * @method Phaser.Physics.Matter.Components.Static#setStatic + * @since 3.0.0 + * + * @param {boolean} value - `true` to set the body as being static, or `false` to make it dynamic. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setStatic: function (value) + { + Body.setStatic(this.body, value); + + return this; + }, + + /** + * Returns `true` if the body is static, otherwise `false` for a dynamic body. + * + * @method Phaser.Physics.Matter.Components.Static#isStatic + * @since 3.0.0 + * + * @return {boolean} `true` if the body is static, otherwise `false`. + */ + isStatic: function () + { + return this.body.isStatic; + } + +}; + +module.exports = Static; diff --git a/src/physics/matter-js/components/Transform.js b/src/physics/matter-js/components/Transform.js index e7934460f..fe02a6c03 100644 --- a/src/physics/matter-js/components/Transform.js +++ b/src/physics/matter-js/components/Transform.js @@ -1,309 +1,309 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('../lib/body/Body'); -var MATH_CONST = require('../../../math/const'); -var WrapAngle = require('../../../math/angle/Wrap'); -var WrapAngleDegrees = require('../../../math/angle/WrapDegrees'); - -// global bitmask flag for GameObject.renderMask (used by Scale) -var _FLAG = 4; // 0100 - -// Transform Component - -/** - * Provides methods used for getting and setting the position, scale and rotation of a Game Object. - * - * @namespace Phaser.Physics.Matter.Components.Transform - * @since 3.0.0 - */ -var Transform = { - - /** - * The x position of this Game Object. - * - * @name Phaser.Physics.Matter.Components.Transform#x - * @type {number} - * @since 3.0.0 - */ - x: { - - get: function () - { - return this.body.position.x; - }, - - set: function (value) - { - this._tempVec2.set(value, this.y); - - Body.setPosition(this.body, this._tempVec2); - } - - }, - - /** - * The y position of this Game Object. - * - * @name Phaser.Physics.Matter.Components.Transform#y - * @type {number} - * @since 3.0.0 - */ - y: { - - get: function () - { - return this.body.position.y; - }, - - set: function (value) - { - this._tempVec2.set(this.x, value); - - Body.setPosition(this.body, this._tempVec2); - } - - }, - - /** - * The horizontal scale of this Game Object. - * - * @name Phaser.Physics.Matter.Components.Transform#scaleX - * @type {number} - * @since 3.0.0 - */ - scaleX: { - - get: function () - { - return this._scaleX; - }, - - set: function (value) - { - var factorX = 1 / this._scaleX; - var factorY = 1 / this._scaleY; - - this._scaleX = value; - - if (this._scaleX === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - - // Reset Matter scale back to 1 (sigh) - Body.scale(this.body, factorX, factorY); - - Body.scale(this.body, value, this._scaleY); - } - - }, - - /** - * The vertical scale of this Game Object. - * - * @name Phaser.Physics.Matter.Components.Transform#scaleY - * @type {number} - * @since 3.0.0 - */ - scaleY: { - - get: function () - { - return this._scaleY; - }, - - set: function (value) - { - var factorX = 1 / this._scaleX; - var factorY = 1 / this._scaleY; - - this._scaleY = value; - - if (this._scaleY === 0) - { - this.renderFlags &= ~_FLAG; - } - else - { - this.renderFlags |= _FLAG; - } - - Body.scale(this.body, factorX, factorY); - - Body.scale(this.body, this._scaleX, value); - } - - }, - - /** - * Use `angle` to set or get rotation of the physics body associated to this GameObject. - * Unlike rotation, when using set the value can be in degrees, which will be converted to radians internally. - * - * @name Phaser.Physics.Matter.Components.Transform#angle - * @type {number} - * @since 3.0.0 - */ - angle: { - - get: function () - { - return WrapAngleDegrees(this.body.angle * MATH_CONST.RAD_TO_DEG); - }, - - set: function (value) - { - // value is in degrees - this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD; - } - }, - - /** - * Use `rotation` to set or get the rotation of the physics body associated with this GameObject. - * The value when set must be in radians. - * - * @name Phaser.Physics.Matter.Components.Transform#rotation - * @type {number} - * @since 3.0.0 - */ - rotation: { - - get: function () - { - return this.body.angle; - }, - - set: function (value) - { - // value is in radians - this._rotation = WrapAngle(value); - - Body.setAngle(this.body, this._rotation); - } - }, - - /** - * Sets the position of the physics body along x and y axes. - * Both the parameters to this function are optional and if not passed any they default to 0. - * Velocity, angle, force etc. are unchanged. - * - * @method Phaser.Physics.Matter.Components.Transform#setPosition - * @since 3.0.0 - * - * @param {number} [x=0] - The horizontal position of the body. - * @param {number} [y=x] - The vertical position of the body. - * - * @return {this} This Game Object. - */ - setPosition: function (x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = x; } - - this._tempVec2.set(x, y); - - Body.setPosition(this.body, this._tempVec2); - - return this; - }, - - /** - * Immediately sets the angle of the Body. - * Angular velocity, position, force etc. are unchanged. - * - * @method Phaser.Physics.Matter.Components.Transform#setRotation - * @since 3.0.0 - * - * @param {number} [radians=0] - The angle of the body, in radians. - * - * @return {this} This Game Object. - */ - setRotation: function (radians) - { - if (radians === undefined) { radians = 0; } - - this._rotation = WrapAngle(radians); - - Body.setAngle(this.body, radians); - - return this; - }, - - /** - * Setting fixed rotation sets the Body inertia to Infinity, which stops it - * from being able to rotate when forces are applied to it. - * - * @method Phaser.Physics.Matter.Components.Transform#setFixedRotation - * @since 3.0.0 - * - * @return {this} This Game Object. - */ - setFixedRotation: function () - { - Body.setInertia(this.body, Infinity); - - return this; - }, - - /** - * Immediately sets the angle of the Body. - * Angular velocity, position, force etc. are unchanged. - * - * @method Phaser.Physics.Matter.Components.Transform#setAngle - * @since 3.0.0 - * - * @param {number} [degrees=0] - The angle to set, in degrees. - * - * @return {this} This Game Object. - */ - setAngle: function (degrees) - { - if (degrees === undefined) { degrees = 0; } - - this.angle = degrees; - - Body.setAngle(this.body, this.rotation); - - return this; - }, - - /** - * Sets the scale of this Game Object. - * - * @method Phaser.Physics.Matter.Components.Transform#setScale - * @since 3.0.0 - * - * @param {number} [x=1] - The horizontal scale of this Game Object. - * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the x value. - * @param {Phaser.Math.Vector2} [point] - The point (Vector2) from which scaling will occur. - * - * @return {this} This Game Object. - */ - setScale: function (x, y, point) - { - if (x === undefined) { x = 1; } - if (y === undefined) { y = x; } - - var factorX = 1 / this._scaleX; - var factorY = 1 / this._scaleY; - - this._scaleX = x; - this._scaleY = y; - - Body.scale(this.body, factorX, factorY, point); - - Body.scale(this.body, x, y, point); - - return this; - } - -}; - -module.exports = Transform; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('../lib/body/Body'); +var MATH_CONST = require('../../../math/const'); +var WrapAngle = require('../../../math/angle/Wrap'); +var WrapAngleDegrees = require('../../../math/angle/WrapDegrees'); + +// global bitmask flag for GameObject.renderMask (used by Scale) +var _FLAG = 4; // 0100 + +// Transform Component + +/** + * Provides methods used for getting and setting the position, scale and rotation of a Game Object. + * + * @namespace Phaser.Physics.Matter.Components.Transform + * @since 3.0.0 + */ +var Transform = { + + /** + * The x position of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#x + * @type {number} + * @since 3.0.0 + */ + x: { + + get: function () + { + return this.body.position.x; + }, + + set: function (value) + { + this._tempVec2.set(value, this.y); + + Body.setPosition(this.body, this._tempVec2); + } + + }, + + /** + * The y position of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#y + * @type {number} + * @since 3.0.0 + */ + y: { + + get: function () + { + return this.body.position.y; + }, + + set: function (value) + { + this._tempVec2.set(this.x, value); + + Body.setPosition(this.body, this._tempVec2); + } + + }, + + /** + * The horizontal scale of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#scaleX + * @type {number} + * @since 3.0.0 + */ + scaleX: { + + get: function () + { + return this._scaleX; + }, + + set: function (value) + { + var factorX = 1 / this._scaleX; + var factorY = 1 / this._scaleY; + + this._scaleX = value; + + if (this._scaleX === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + // Reset Matter scale back to 1 (sigh) + Body.scale(this.body, factorX, factorY); + + Body.scale(this.body, value, this._scaleY); + } + + }, + + /** + * The vertical scale of this Game Object. + * + * @name Phaser.Physics.Matter.Components.Transform#scaleY + * @type {number} + * @since 3.0.0 + */ + scaleY: { + + get: function () + { + return this._scaleY; + }, + + set: function (value) + { + var factorX = 1 / this._scaleX; + var factorY = 1 / this._scaleY; + + this._scaleY = value; + + if (this._scaleY === 0) + { + this.renderFlags &= ~_FLAG; + } + else + { + this.renderFlags |= _FLAG; + } + + Body.scale(this.body, factorX, factorY); + + Body.scale(this.body, this._scaleX, value); + } + + }, + + /** + * Use `angle` to set or get rotation of the physics body associated to this GameObject. + * Unlike rotation, when using set the value can be in degrees, which will be converted to radians internally. + * + * @name Phaser.Physics.Matter.Components.Transform#angle + * @type {number} + * @since 3.0.0 + */ + angle: { + + get: function () + { + return WrapAngleDegrees(this.body.angle * MATH_CONST.RAD_TO_DEG); + }, + + set: function (value) + { + // value is in degrees + this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD; + } + }, + + /** + * Use `rotation` to set or get the rotation of the physics body associated with this GameObject. + * The value when set must be in radians. + * + * @name Phaser.Physics.Matter.Components.Transform#rotation + * @type {number} + * @since 3.0.0 + */ + rotation: { + + get: function () + { + return this.body.angle; + }, + + set: function (value) + { + // value is in radians + this._rotation = WrapAngle(value); + + Body.setAngle(this.body, this._rotation); + } + }, + + /** + * Sets the position of the physics body along x and y axes. + * Both the parameters to this function are optional and if not passed any they default to 0. + * Velocity, angle, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Transform#setPosition + * @since 3.0.0 + * + * @param {number} [x=0] - The horizontal position of the body. + * @param {number} [y=x] - The vertical position of the body. + * + * @return {this} This Game Object. + */ + setPosition: function (x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = x; } + + this._tempVec2.set(x, y); + + Body.setPosition(this.body, this._tempVec2); + + return this; + }, + + /** + * Immediately sets the angle of the Body. + * Angular velocity, position, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Transform#setRotation + * @since 3.0.0 + * + * @param {number} [radians=0] - The angle of the body, in radians. + * + * @return {this} This Game Object. + */ + setRotation: function (radians) + { + if (radians === undefined) { radians = 0; } + + this._rotation = WrapAngle(radians); + + Body.setAngle(this.body, radians); + + return this; + }, + + /** + * Setting fixed rotation sets the Body inertia to Infinity, which stops it + * from being able to rotate when forces are applied to it. + * + * @method Phaser.Physics.Matter.Components.Transform#setFixedRotation + * @since 3.0.0 + * + * @return {this} This Game Object. + */ + setFixedRotation: function () + { + Body.setInertia(this.body, Infinity); + + return this; + }, + + /** + * Immediately sets the angle of the Body. + * Angular velocity, position, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Transform#setAngle + * @since 3.0.0 + * + * @param {number} [degrees=0] - The angle to set, in degrees. + * + * @return {this} This Game Object. + */ + setAngle: function (degrees) + { + if (degrees === undefined) { degrees = 0; } + + this.angle = degrees; + + Body.setAngle(this.body, this.rotation); + + return this; + }, + + /** + * Sets the scale of this Game Object. + * + * @method Phaser.Physics.Matter.Components.Transform#setScale + * @since 3.0.0 + * + * @param {number} [x=1] - The horizontal scale of this Game Object. + * @param {number} [y=x] - The vertical scale of this Game Object. If not set it will use the x value. + * @param {Phaser.Math.Vector2} [point] - The point (Vector2) from which scaling will occur. + * + * @return {this} This Game Object. + */ + setScale: function (x, y, point) + { + if (x === undefined) { x = 1; } + if (y === undefined) { y = x; } + + var factorX = 1 / this._scaleX; + var factorY = 1 / this._scaleY; + + this._scaleX = x; + this._scaleY = y; + + Body.scale(this.body, factorX, factorY, point); + + Body.scale(this.body, x, y, point); + + return this; + } + +}; + +module.exports = Transform; diff --git a/src/physics/matter-js/components/Velocity.js b/src/physics/matter-js/components/Velocity.js index 619719787..13bc109f7 100644 --- a/src/physics/matter-js/components/Velocity.js +++ b/src/physics/matter-js/components/Velocity.js @@ -1,95 +1,95 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Body = require('../lib/body/Body'); - -/** - * Contains methods for changing the velocity of a Matter Body. Should be used as a mixin and not called directly. - * - * @namespace Phaser.Physics.Matter.Components.Velocity - * @since 3.0.0 - */ -var Velocity = { - - /** - * Sets the angular velocity of the body instantly. - * Position, angle, force etc. are unchanged. - * - * @method Phaser.Physics.Matter.Components.Velocity#setAngularVelocity - * @since 3.0.0 - * - * @param {number} value - The angular velocity. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setAngularVelocity: function (value) - { - Body.setAngularVelocity(this.body, value); - - return this; - }, - - /** - * Sets the horizontal velocity of the physics body. - * - * @method Phaser.Physics.Matter.Components.Velocity#setVelocityX - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity value. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setVelocityX: function (x) - { - this._tempVec2.set(x, this.body.velocity.y); - - Body.setVelocity(this.body, this._tempVec2); - - return this; - }, - - /** - * Sets vertical velocity of the physics body. - * - * @method Phaser.Physics.Matter.Components.Velocity#setVelocityY - * @since 3.0.0 - * - * @param {number} y - The vertical velocity value. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setVelocityY: function (y) - { - this._tempVec2.set(this.body.velocity.x, y); - - Body.setVelocity(this.body, this._tempVec2); - - return this; - }, - - /** - * Sets both the horizontal and vertical velocity of the physics body. - * - * @method Phaser.Physics.Matter.Components.Velocity#setVelocity - * @since 3.0.0 - * - * @param {number} x - The horizontal velocity value. - * @param {number} [y=x] - The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. - * - * @return {Phaser.GameObjects.GameObject} This Game Object. - */ - setVelocity: function (x, y) - { - this._tempVec2.set(x, y); - - Body.setVelocity(this.body, this._tempVec2); - - return this; - } - -}; - -module.exports = Velocity; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Body = require('../lib/body/Body'); + +/** + * Contains methods for changing the velocity of a Matter Body. Should be used as a mixin and not called directly. + * + * @namespace Phaser.Physics.Matter.Components.Velocity + * @since 3.0.0 + */ +var Velocity = { + + /** + * Sets the angular velocity of the body instantly. + * Position, angle, force etc. are unchanged. + * + * @method Phaser.Physics.Matter.Components.Velocity#setAngularVelocity + * @since 3.0.0 + * + * @param {number} value - The angular velocity. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setAngularVelocity: function (value) + { + Body.setAngularVelocity(this.body, value); + + return this; + }, + + /** + * Sets the horizontal velocity of the physics body. + * + * @method Phaser.Physics.Matter.Components.Velocity#setVelocityX + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setVelocityX: function (x) + { + this._tempVec2.set(x, this.body.velocity.y); + + Body.setVelocity(this.body, this._tempVec2); + + return this; + }, + + /** + * Sets vertical velocity of the physics body. + * + * @method Phaser.Physics.Matter.Components.Velocity#setVelocityY + * @since 3.0.0 + * + * @param {number} y - The vertical velocity value. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setVelocityY: function (y) + { + this._tempVec2.set(this.body.velocity.x, y); + + Body.setVelocity(this.body, this._tempVec2); + + return this; + }, + + /** + * Sets both the horizontal and vertical velocity of the physics body. + * + * @method Phaser.Physics.Matter.Components.Velocity#setVelocity + * @since 3.0.0 + * + * @param {number} x - The horizontal velocity value. + * @param {number} [y=x] - The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. + * + * @return {Phaser.GameObjects.GameObject} This Game Object. + */ + setVelocity: function (x, y) + { + this._tempVec2.set(x, y); + + Body.setVelocity(this.body, this._tempVec2); + + return this; + } + +}; + +module.exports = Velocity; diff --git a/src/physics/matter-js/components/index.js b/src/physics/matter-js/components/index.js index 56c6e87f9..4798a03d4 100644 --- a/src/physics/matter-js/components/index.js +++ b/src/physics/matter-js/components/index.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Matter.Components - */ - -module.exports = { - - Bounce: require('./Bounce'), - Collision: require('./Collision'), - Force: require('./Force'), - Friction: require('./Friction'), - Gravity: require('./Gravity'), - Mass: require('./Mass'), - Static: require('./Static'), - Sensor: require('./Sensor'), - SetBody: require('./SetBody'), - Sleep: require('./Sleep'), - Transform: require('./Transform'), - Velocity: require('./Velocity') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter.Components + */ + +module.exports = { + + Bounce: require('./Bounce'), + Collision: require('./Collision'), + Force: require('./Force'), + Friction: require('./Friction'), + Gravity: require('./Gravity'), + Mass: require('./Mass'), + Static: require('./Static'), + Sensor: require('./Sensor'), + SetBody: require('./SetBody'), + Sleep: require('./Sleep'), + Transform: require('./Transform'), + Velocity: require('./Velocity') + +}; diff --git a/src/physics/matter-js/events/AFTER_ADD_EVENT.js b/src/physics/matter-js/events/AFTER_ADD_EVENT.js index 4a73e419b..3895b5b8d 100644 --- a/src/physics/matter-js/events/AFTER_ADD_EVENT.js +++ b/src/physics/matter-js/events/AFTER_ADD_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.AfterAddEvent - * - * @property {any[]} object - An array of the object(s) that have been added. May be a single body, constraint, composite or a mixture of these. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics After Add Event. - * - * This event is dispatched by a Matter Physics World instance at the end of the process when a new Body - * or Constraint has just been added to the world. - * - * Listen to it from a Scene using: `this.matter.world.on('afteradd', listener)`. - * - * @event Phaser.Physics.Matter.Events#AFTER_ADD - * @since 3.22.0 - * - * @param {Phaser.Physics.Matter.Events.AfterAddEvent} event - The Add Event object. - */ -module.exports = 'afteradd'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.AfterAddEvent + * + * @property {any[]} object - An array of the object(s) that have been added. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics After Add Event. + * + * This event is dispatched by a Matter Physics World instance at the end of the process when a new Body + * or Constraint has just been added to the world. + * + * Listen to it from a Scene using: `this.matter.world.on('afteradd', listener)`. + * + * @event Phaser.Physics.Matter.Events#AFTER_ADD + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.AfterAddEvent} event - The Add Event object. + */ +module.exports = 'afteradd'; diff --git a/src/physics/matter-js/events/AFTER_REMOVE_EVENT.js b/src/physics/matter-js/events/AFTER_REMOVE_EVENT.js index f745ced80..8ea4bb8db 100644 --- a/src/physics/matter-js/events/AFTER_REMOVE_EVENT.js +++ b/src/physics/matter-js/events/AFTER_REMOVE_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.AfterRemoveEvent - * - * @property {any[]} object - An array of the object(s) that were removed. May be a single body, constraint, composite or a mixture of these. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics After Remove Event. - * - * This event is dispatched by a Matter Physics World instance at the end of the process when a - * Body or Constraint was removed from the world. - * - * Listen to it from a Scene using: `this.matter.world.on('afterremove', listener)`. - * - * @event Phaser.Physics.Matter.Events#AFTER_REMOVE - * @since 3.22.0 - * - * @param {Phaser.Physics.Matter.Events.AfterRemoveEvent} event - The Remove Event object. - */ -module.exports = 'afterremove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.AfterRemoveEvent + * + * @property {any[]} object - An array of the object(s) that were removed. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics After Remove Event. + * + * This event is dispatched by a Matter Physics World instance at the end of the process when a + * Body or Constraint was removed from the world. + * + * Listen to it from a Scene using: `this.matter.world.on('afterremove', listener)`. + * + * @event Phaser.Physics.Matter.Events#AFTER_REMOVE + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.AfterRemoveEvent} event - The Remove Event object. + */ +module.exports = 'afterremove'; diff --git a/src/physics/matter-js/events/AFTER_UPDATE_EVENT.js b/src/physics/matter-js/events/AFTER_UPDATE_EVENT.js index 999aba1d5..5ecd9830a 100644 --- a/src/physics/matter-js/events/AFTER_UPDATE_EVENT.js +++ b/src/physics/matter-js/events/AFTER_UPDATE_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.AfterUpdateEvent - * - * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics After Update Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated and all collision events have resolved. - * - * Listen to it from a Scene using: `this.matter.world.on('afterupdate', listener)`. - * - * @event Phaser.Physics.Matter.Events#AFTER_UPDATE - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.AfterUpdateEvent} event - The Update Event object. - */ -module.exports = 'afterupdate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.AfterUpdateEvent + * + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics After Update Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated and all collision events have resolved. + * + * Listen to it from a Scene using: `this.matter.world.on('afterupdate', listener)`. + * + * @event Phaser.Physics.Matter.Events#AFTER_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.AfterUpdateEvent} event - The Update Event object. + */ +module.exports = 'afterupdate'; diff --git a/src/physics/matter-js/events/BEFORE_ADD_EVENT.js b/src/physics/matter-js/events/BEFORE_ADD_EVENT.js index a97d2f0de..f12faf881 100644 --- a/src/physics/matter-js/events/BEFORE_ADD_EVENT.js +++ b/src/physics/matter-js/events/BEFORE_ADD_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.BeforeAddEvent - * - * @property {any[]} object - An array of the object(s) to be added. May be a single body, constraint, composite or a mixture of these. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Before Add Event. - * - * This event is dispatched by a Matter Physics World instance at the start of the process when a new Body - * or Constraint is being added to the world. - * - * Listen to it from a Scene using: `this.matter.world.on('beforeadd', listener)`. - * - * @event Phaser.Physics.Matter.Events#BEFORE_ADD - * @since 3.22.0 - * - * @param {Phaser.Physics.Matter.Events.BeforeAddEvent} event - The Add Event object. - */ -module.exports = 'beforeadd'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.BeforeAddEvent + * + * @property {any[]} object - An array of the object(s) to be added. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Before Add Event. + * + * This event is dispatched by a Matter Physics World instance at the start of the process when a new Body + * or Constraint is being added to the world. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeadd', listener)`. + * + * @event Phaser.Physics.Matter.Events#BEFORE_ADD + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.BeforeAddEvent} event - The Add Event object. + */ +module.exports = 'beforeadd'; diff --git a/src/physics/matter-js/events/BEFORE_REMOVE_EVENT.js b/src/physics/matter-js/events/BEFORE_REMOVE_EVENT.js index d263e7475..e1dd68442 100644 --- a/src/physics/matter-js/events/BEFORE_REMOVE_EVENT.js +++ b/src/physics/matter-js/events/BEFORE_REMOVE_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.BeforeRemoveEvent - * - * @property {any[]} object - An array of the object(s) to be removed. May be a single body, constraint, composite or a mixture of these. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Before Remove Event. - * - * This event is dispatched by a Matter Physics World instance at the start of the process when a - * Body or Constraint is being removed from the world. - * - * Listen to it from a Scene using: `this.matter.world.on('beforeremove', listener)`. - * - * @event Phaser.Physics.Matter.Events#BEFORE_REMOVE - * @since 3.22.0 - * - * @param {Phaser.Physics.Matter.Events.BeforeRemoveEvent} event - The Remove Event object. - */ -module.exports = 'beforeremove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.BeforeRemoveEvent + * + * @property {any[]} object - An array of the object(s) to be removed. May be a single body, constraint, composite or a mixture of these. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Before Remove Event. + * + * This event is dispatched by a Matter Physics World instance at the start of the process when a + * Body or Constraint is being removed from the world. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeremove', listener)`. + * + * @event Phaser.Physics.Matter.Events#BEFORE_REMOVE + * @since 3.22.0 + * + * @param {Phaser.Physics.Matter.Events.BeforeRemoveEvent} event - The Remove Event object. + */ +module.exports = 'beforeremove'; diff --git a/src/physics/matter-js/events/BEFORE_UPDATE_EVENT.js b/src/physics/matter-js/events/BEFORE_UPDATE_EVENT.js index 3cf763a35..6eb6e95d2 100644 --- a/src/physics/matter-js/events/BEFORE_UPDATE_EVENT.js +++ b/src/physics/matter-js/events/BEFORE_UPDATE_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.BeforeUpdateEvent - * - * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Before Update Event. - * - * This event is dispatched by a Matter Physics World instance right before all the collision processing takes place. - * - * Listen to it from a Scene using: `this.matter.world.on('beforeupdate', listener)`. - * - * @event Phaser.Physics.Matter.Events#BEFORE_UPDATE - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.BeforeUpdateEvent} event - The Update Event object. - */ -module.exports = 'beforeupdate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.BeforeUpdateEvent + * + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Before Update Event. + * + * This event is dispatched by a Matter Physics World instance right before all the collision processing takes place. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeupdate', listener)`. + * + * @event Phaser.Physics.Matter.Events#BEFORE_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.BeforeUpdateEvent} event - The Update Event object. + */ +module.exports = 'beforeupdate'; diff --git a/src/physics/matter-js/events/COLLISION_ACTIVE_EVENT.js b/src/physics/matter-js/events/COLLISION_ACTIVE_EVENT.js index a272652a9..9bb8791cc 100644 --- a/src/physics/matter-js/events/COLLISION_ACTIVE_EVENT.js +++ b/src/physics/matter-js/events/COLLISION_ACTIVE_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.CollisionActiveEvent - * - * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. - * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Collision Active Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated. - * It provides a list of all pairs that are colliding in the current tick (if any). - * - * Listen to it from a Scene using: `this.matter.world.on('collisionactive', listener)`. - * - * @event Phaser.Physics.Matter.Events#COLLISION_ACTIVE - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.CollisionActiveEvent} event - The Collision Event object. - * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. - * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. - */ -module.exports = 'collisionactive'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.CollisionActiveEvent + * + * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Collision Active Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that are colliding in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionactive', listener)`. + * + * @event Phaser.Physics.Matter.Events#COLLISION_ACTIVE + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.CollisionActiveEvent} event - The Collision Event object. + * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + */ +module.exports = 'collisionactive'; diff --git a/src/physics/matter-js/events/COLLISION_END_EVENT.js b/src/physics/matter-js/events/COLLISION_END_EVENT.js index 543618135..2f1e0105a 100644 --- a/src/physics/matter-js/events/COLLISION_END_EVENT.js +++ b/src/physics/matter-js/events/COLLISION_END_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.CollisionEndEvent - * - * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. - * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Collision End Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated. - * It provides a list of all pairs that have finished colliding in the current tick (if any). - * - * Listen to it from a Scene using: `this.matter.world.on('collisionend', listener)`. - * - * @event Phaser.Physics.Matter.Events#COLLISION_END - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.CollisionEndEvent} event - The Collision Event object. - * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. - * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. - */ -module.exports = 'collisionend'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.CollisionEndEvent + * + * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Collision End Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that have finished colliding in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionend', listener)`. + * + * @event Phaser.Physics.Matter.Events#COLLISION_END + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.CollisionEndEvent} event - The Collision Event object. + * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + */ +module.exports = 'collisionend'; diff --git a/src/physics/matter-js/events/COLLISION_START_EVENT.js b/src/physics/matter-js/events/COLLISION_START_EVENT.js index 9a0ce1105..150daef62 100644 --- a/src/physics/matter-js/events/COLLISION_START_EVENT.js +++ b/src/physics/matter-js/events/COLLISION_START_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.CollisionStartEvent - * - * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. - * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Collision Start Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated. - * It provides a list of all pairs that have started to collide in the current tick (if any). - * - * Listen to it from a Scene using: `this.matter.world.on('collisionstart', listener)`. - * - * @event Phaser.Physics.Matter.Events#COLLISION_START - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.CollisionStartEvent} event - The Collision Event object. - * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. - * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. - */ -module.exports = 'collisionstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.CollisionStartEvent + * + * @property {Phaser.Types.Physics.Matter.MatterCollisionData[]} pairs - A list of all affected pairs in the collision. + * @property {number} timestamp - The Matter Engine `timing.timestamp` value for the event. + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Collision Start Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that have started to collide in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionstart', listener)`. + * + * @event Phaser.Physics.Matter.Events#COLLISION_START + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.CollisionStartEvent} event - The Collision Event object. + * @param {MatterJS.BodyType} bodyA - The first body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + * @param {MatterJS.BodyType} bodyB - The second body of the first colliding pair. The `event.pairs` array may contain more colliding bodies. + */ +module.exports = 'collisionstart'; diff --git a/src/physics/matter-js/events/DRAG_END_EVENT.js b/src/physics/matter-js/events/DRAG_END_EVENT.js index e01eed8cf..7b140854c 100644 --- a/src/physics/matter-js/events/DRAG_END_EVENT.js +++ b/src/physics/matter-js/events/DRAG_END_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Matter Physics Drag End Event. - * - * This event is dispatched by a Matter Physics World instance when a Pointer Constraint - * stops dragging a body. - * - * Listen to it from a Scene using: `this.matter.world.on('dragend', listener)`. - * - * @event Phaser.Physics.Matter.Events#DRAG_END - * @since 3.16.2 - * - * @param {MatterJS.BodyType} body - The Body that has stopped being dragged. This is a Matter Body, not a Phaser Game Object. - * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that was dragging the body. - */ -module.exports = 'dragend'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics Drag End Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * stops dragging a body. + * + * Listen to it from a Scene using: `this.matter.world.on('dragend', listener)`. + * + * @event Phaser.Physics.Matter.Events#DRAG_END + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Body that has stopped being dragged. This is a Matter Body, not a Phaser Game Object. + * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that was dragging the body. + */ +module.exports = 'dragend'; diff --git a/src/physics/matter-js/events/DRAG_EVENT.js b/src/physics/matter-js/events/DRAG_EVENT.js index 103c7ac3d..9851516c9 100644 --- a/src/physics/matter-js/events/DRAG_EVENT.js +++ b/src/physics/matter-js/events/DRAG_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Matter Physics Drag Event. - * - * This event is dispatched by a Matter Physics World instance when a Pointer Constraint - * is actively dragging a body. It is emitted each time the pointer moves. - * - * Listen to it from a Scene using: `this.matter.world.on('drag', listener)`. - * - * @event Phaser.Physics.Matter.Events#DRAG - * @since 3.16.2 - * - * @param {MatterJS.BodyType} body - The Body that is being dragged. This is a Matter Body, not a Phaser Game Object. - * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. - */ -module.exports = 'drag'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics Drag Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * is actively dragging a body. It is emitted each time the pointer moves. + * + * Listen to it from a Scene using: `this.matter.world.on('drag', listener)`. + * + * @event Phaser.Physics.Matter.Events#DRAG + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Body that is being dragged. This is a Matter Body, not a Phaser Game Object. + * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. + */ +module.exports = 'drag'; diff --git a/src/physics/matter-js/events/DRAG_START_EVENT.js b/src/physics/matter-js/events/DRAG_START_EVENT.js index 7eaa0ba1b..f7e0158b6 100644 --- a/src/physics/matter-js/events/DRAG_START_EVENT.js +++ b/src/physics/matter-js/events/DRAG_START_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Matter Physics Drag Start Event. - * - * This event is dispatched by a Matter Physics World instance when a Pointer Constraint - * starts dragging a body. - * - * Listen to it from a Scene using: `this.matter.world.on('dragstart', listener)`. - * - * @event Phaser.Physics.Matter.Events#DRAG_START - * @since 3.16.2 - * - * @param {MatterJS.BodyType} body - The Body that has started being dragged. This is a Matter Body, not a Phaser Game Object. - * @param {MatterJS.BodyType} part - The part of the body that was clicked on. - * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. - */ -module.exports = 'dragstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics Drag Start Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * starts dragging a body. + * + * Listen to it from a Scene using: `this.matter.world.on('dragstart', listener)`. + * + * @event Phaser.Physics.Matter.Events#DRAG_START + * @since 3.16.2 + * + * @param {MatterJS.BodyType} body - The Body that has started being dragged. This is a Matter Body, not a Phaser Game Object. + * @param {MatterJS.BodyType} part - The part of the body that was clicked on. + * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. + */ +module.exports = 'dragstart'; diff --git a/src/physics/matter-js/events/PAUSE_EVENT.js b/src/physics/matter-js/events/PAUSE_EVENT.js index dba8f5553..59c5dd37f 100644 --- a/src/physics/matter-js/events/PAUSE_EVENT.js +++ b/src/physics/matter-js/events/PAUSE_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Matter Physics World Pause Event. - * - * This event is dispatched by an Matter Physics World instance when it is paused. - * - * Listen to it from a Scene using: `this.matter.world.on('pause', listener)`. - * - * @event Phaser.Physics.Matter.Events#PAUSE - * @since 3.0.0 - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics World Pause Event. + * + * This event is dispatched by an Matter Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.matter.world.on('pause', listener)`. + * + * @event Phaser.Physics.Matter.Events#PAUSE + * @since 3.0.0 + */ +module.exports = 'pause'; diff --git a/src/physics/matter-js/events/RESUME_EVENT.js b/src/physics/matter-js/events/RESUME_EVENT.js index 23cb25304..0771de24f 100644 --- a/src/physics/matter-js/events/RESUME_EVENT.js +++ b/src/physics/matter-js/events/RESUME_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Matter Physics World Resume Event. - * - * This event is dispatched by an Matter Physics World instance when it resumes from a paused state. - * - * Listen to it from a Scene using: `this.matter.world.on('resume', listener)`. - * - * @event Phaser.Physics.Matter.Events#RESUME - * @since 3.0.0 - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Matter Physics World Resume Event. + * + * This event is dispatched by an Matter Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.matter.world.on('resume', listener)`. + * + * @event Phaser.Physics.Matter.Events#RESUME + * @since 3.0.0 + */ +module.exports = 'resume'; diff --git a/src/physics/matter-js/events/SLEEP_END_EVENT.js b/src/physics/matter-js/events/SLEEP_END_EVENT.js index eab024c97..068c20f77 100644 --- a/src/physics/matter-js/events/SLEEP_END_EVENT.js +++ b/src/physics/matter-js/events/SLEEP_END_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.SleepEndEvent - * - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Sleep End Event. - * - * This event is dispatched by a Matter Physics World instance when a Body stop sleeping. - * - * Listen to it from a Scene using: `this.matter.world.on('sleepend', listener)`. - * - * @event Phaser.Physics.Matter.Events#SLEEP_END - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.SleepEndEvent} event - The Sleep Event object. - * @param {MatterJS.BodyType} body - The body that has stopped sleeping. - */ -module.exports = 'sleepend'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.SleepEndEvent + * + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Sleep End Event. + * + * This event is dispatched by a Matter Physics World instance when a Body stop sleeping. + * + * Listen to it from a Scene using: `this.matter.world.on('sleepend', listener)`. + * + * @event Phaser.Physics.Matter.Events#SLEEP_END + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.SleepEndEvent} event - The Sleep Event object. + * @param {MatterJS.BodyType} body - The body that has stopped sleeping. + */ +module.exports = 'sleepend'; diff --git a/src/physics/matter-js/events/SLEEP_START_EVENT.js b/src/physics/matter-js/events/SLEEP_START_EVENT.js index 70b4a2242..440702d84 100644 --- a/src/physics/matter-js/events/SLEEP_START_EVENT.js +++ b/src/physics/matter-js/events/SLEEP_START_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Physics.Matter.Events.SleepStartEvent - * - * @property {any} source - The source object of the event. - * @property {string} name - The name of the event. - */ - -/** - * The Matter Physics Sleep Start Event. - * - * This event is dispatched by a Matter Physics World instance when a Body goes to sleep. - * - * Listen to it from a Scene using: `this.matter.world.on('sleepstart', listener)`. - * - * @event Phaser.Physics.Matter.Events#SLEEP_START - * @since 3.0.0 - * - * @param {Phaser.Physics.Matter.Events.SleepStartEvent} event - The Sleep Event object. - * @param {MatterJS.BodyType} body - The body that has gone to sleep. - */ -module.exports = 'sleepstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Physics.Matter.Events.SleepStartEvent + * + * @property {any} source - The source object of the event. + * @property {string} name - The name of the event. + */ + +/** + * The Matter Physics Sleep Start Event. + * + * This event is dispatched by a Matter Physics World instance when a Body goes to sleep. + * + * Listen to it from a Scene using: `this.matter.world.on('sleepstart', listener)`. + * + * @event Phaser.Physics.Matter.Events#SLEEP_START + * @since 3.0.0 + * + * @param {Phaser.Physics.Matter.Events.SleepStartEvent} event - The Sleep Event object. + * @param {MatterJS.BodyType} body - The body that has gone to sleep. + */ +module.exports = 'sleepstart'; diff --git a/src/physics/matter-js/events/index.js b/src/physics/matter-js/events/index.js index 6697df1b9..b4a50ffe8 100644 --- a/src/physics/matter-js/events/index.js +++ b/src/physics/matter-js/events/index.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Matter.Events - */ - -module.exports = { - - AFTER_ADD: require('./AFTER_ADD_EVENT'), - AFTER_REMOVE: require('./AFTER_REMOVE_EVENT'), - AFTER_UPDATE: require('./AFTER_UPDATE_EVENT'), - BEFORE_ADD: require('./BEFORE_ADD_EVENT'), - BEFORE_REMOVE: require('./BEFORE_REMOVE_EVENT'), - BEFORE_UPDATE: require('./BEFORE_UPDATE_EVENT'), - COLLISION_ACTIVE: require('./COLLISION_ACTIVE_EVENT'), - COLLISION_END: require('./COLLISION_END_EVENT'), - COLLISION_START: require('./COLLISION_START_EVENT'), - DRAG_END: require('./DRAG_END_EVENT'), - DRAG: require('./DRAG_EVENT'), - DRAG_START: require('./DRAG_START_EVENT'), - PAUSE: require('./PAUSE_EVENT'), - RESUME: require('./RESUME_EVENT'), - SLEEP_END: require('./SLEEP_END_EVENT'), - SLEEP_START: require('./SLEEP_START_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter.Events + */ + +module.exports = { + + AFTER_ADD: require('./AFTER_ADD_EVENT'), + AFTER_REMOVE: require('./AFTER_REMOVE_EVENT'), + AFTER_UPDATE: require('./AFTER_UPDATE_EVENT'), + BEFORE_ADD: require('./BEFORE_ADD_EVENT'), + BEFORE_REMOVE: require('./BEFORE_REMOVE_EVENT'), + BEFORE_UPDATE: require('./BEFORE_UPDATE_EVENT'), + COLLISION_ACTIVE: require('./COLLISION_ACTIVE_EVENT'), + COLLISION_END: require('./COLLISION_END_EVENT'), + COLLISION_START: require('./COLLISION_START_EVENT'), + DRAG_END: require('./DRAG_END_EVENT'), + DRAG: require('./DRAG_EVENT'), + DRAG_START: require('./DRAG_START_EVENT'), + PAUSE: require('./PAUSE_EVENT'), + RESUME: require('./RESUME_EVENT'), + SLEEP_END: require('./SLEEP_END_EVENT'), + SLEEP_START: require('./SLEEP_START_EVENT') + +}; diff --git a/src/physics/matter-js/index.js b/src/physics/matter-js/index.js index ec2ff8b4b..30a8c3d6f 100644 --- a/src/physics/matter-js/index.js +++ b/src/physics/matter-js/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Physics.Matter - */ - -module.exports = { - - BodyBounds: require('./BodyBounds'), - Factory: require('./Factory'), - Image: require('./MatterImage'), - Matter: require('./CustomMain'), - MatterPhysics: require('./MatterPhysics'), - PolyDecomp: require('./poly-decomp'), - Sprite: require('./MatterSprite'), - TileBody: require('./MatterTileBody'), - PhysicsEditorParser: require('./PhysicsEditorParser'), - PhysicsJSONParser: require('./PhysicsJSONParser'), - World: require('./World') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Physics.Matter + */ + +module.exports = { + + BodyBounds: require('./BodyBounds'), + Factory: require('./Factory'), + Image: require('./MatterImage'), + Matter: require('./CustomMain'), + MatterPhysics: require('./MatterPhysics'), + PolyDecomp: require('./poly-decomp'), + Sprite: require('./MatterSprite'), + TileBody: require('./MatterTileBody'), + PhysicsEditorParser: require('./PhysicsEditorParser'), + PhysicsJSONParser: require('./PhysicsJSONParser'), + World: require('./World') + +}; diff --git a/src/physics/matter-js/lib/body/Body.js b/src/physics/matter-js/lib/body/Body.js index 1b84a99ba..3bd2fbb29 100644 --- a/src/physics/matter-js/lib/body/Body.js +++ b/src/physics/matter-js/lib/body/Body.js @@ -1,1376 +1,1376 @@ -/** - * 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 - */ - -var Body = {}; - -module.exports = Body; - -var Vertices = require('../geometry/Vertices'); -var Vector = require('../geometry/Vector'); -var Sleeping = require('../core/Sleeping'); -var Common = require('../core/Common'); -var Bounds = require('../geometry/Bounds'); -var Axes = require('../geometry/Axes'); - -(function() { - - Body._inertiaScale = 4; - Body._nextCollidingGroupId = 1; - Body._nextNonCollidingGroupId = -1; - Body._nextCategory = 0x0001; - - /** - * 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 - */ - Body.create = function(options) { - var defaults = { - id: Common.nextId(), - type: 'body', - label: 'Body', - parts: [], - plugin: {}, - angle: 0, - vertices: null, // Phaser change: no point calling fromPath if they pass in vertices anyway - position: { x: 0, y: 0 }, - force: { x: 0, y: 0 }, - torque: 0, - positionImpulse: { x: 0, y: 0 }, - previousPositionImpulse: { x: 0, y: 0 }, - constraintImpulse: { x: 0, y: 0, angle: 0 }, - totalContacts: 0, - speed: 0, - angularSpeed: 0, - velocity: { x: 0, y: 0 }, - angularVelocity: 0, - isSensor: false, - isStatic: false, - isSleeping: false, - motion: 0, - sleepThreshold: 60, - density: 0.001, - restitution: 0, - friction: 0.1, - frictionStatic: 0.5, - frictionAir: 0.01, - collisionFilter: { - category: 0x0001, - mask: 0xFFFFFFFF, - group: 0 - }, - slop: 0.05, - timeScale: 1, - events: null, - bounds: null, - chamfer: null, - circleRadius: 0, - positionPrev: null, - anglePrev: 0, - parent: null, - axes: null, - area: 0, - mass: 0, - inverseMass: 0, - inertia: 0, - inverseInertia: 0, - _original: null, - render: { - visible: true, - opacity: 1, - sprite: { - xOffset: 0, - yOffset: 0 - }, - fillColor: null, // custom Phaser property - fillOpacity: null, // custom Phaser property - lineColor: null, // custom Phaser property - lineOpacity: null, // custom Phaser property - lineThickness: null // custom Phaser property - }, - gameObject: null, // custom Phaser property - scale: { x: 1, y: 1 }, // custom Phaser property - centerOfMass: { x: 0, y: 0 }, // custom Phaser property (float, 0 - 1) - centerOffset: { x: 0, y: 0 }, // custom Phaser property (pixel values) - gravityScale: { x: 1, y: 1 }, // custom Phaser property - ignoreGravity: false, // custom Phaser property - ignorePointer: false, // custom Phaser property - onCollideCallback: null, // custom Phaser property - onCollideEndCallback: null, // custom Phaser property - onCollideActiveCallback: null, // custom Phaser property - onCollideWith: {} // custom Phaser property - }; - - if (!options.hasOwnProperty('position') && options.hasOwnProperty('vertices')) - { - options.position = Vertices.centre(options.vertices); - } - else if (!options.hasOwnProperty('vertices')) - { - defaults.vertices = Vertices.fromPath('L 0 0 L 40 0 L 40 40 L 0 40'); - } - - var body = Common.extend(defaults, options); - - _initProperties(body, options); - - // Helper function - body.setOnCollideWith = function (body, callback) - { - if (callback) - { - this.onCollideWith[body.id] = callback; - } - else - { - delete this.onCollideWith[body.id]; - } - - return this; - } - - return body; - }; - - /** - * Returns the next unique group index for which bodies will collide. - * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. - * See `body.collisionFilter` for more information. - * @method nextGroup - * @param {bool} [isNonColliding=false] - * @return {Number} Unique group index - */ - Body.nextGroup = function(isNonColliding) { - if (isNonColliding) - return Body._nextNonCollidingGroupId--; - - return Body._nextCollidingGroupId++; - }; - - /** - * Returns the next unique category bitfield (starting after the initial default category `0x0001`). - * There are 32 available. See `body.collisionFilter` for more information. - * @method nextCategory - * @return {Number} Unique category bitfield - */ - Body.nextCategory = function() { - Body._nextCategory = Body._nextCategory << 1; - return Body._nextCategory; - }; - - /** - * Initialises body properties. - * @method _initProperties - * @private - * @param {body} body - * @param {} [options] - */ - var _initProperties = function(body, options) { - options = options || {}; - - // init required properties (order is important) - Body.set(body, { - bounds: body.bounds || Bounds.create(body.vertices), - positionPrev: body.positionPrev || Vector.clone(body.position), - anglePrev: body.anglePrev || body.angle, - vertices: body.vertices, - parts: body.parts || [body], - isStatic: body.isStatic, - isSleeping: body.isSleeping, - parent: body.parent || body - }); - - var bounds = body.bounds; - - Vertices.rotate(body.vertices, body.angle, body.position); - Axes.rotate(body.axes, body.angle); - Bounds.update(bounds, body.vertices, body.velocity); - - // allow options to override the automatically calculated properties - Body.set(body, { - axes: options.axes || body.axes, - area: options.area || body.area, - mass: options.mass || body.mass, - inertia: options.inertia || body.inertia - }); - - if (body.parts.length === 1) - { - var centerOfMass = body.centerOfMass; - var centerOffset = body.centerOffset; - - var bodyWidth = bounds.max.x - bounds.min.x; - var bodyHeight = bounds.max.y - bounds.min.y; - - centerOfMass.x = -(bounds.min.x - body.position.x) / bodyWidth; - centerOfMass.y = -(bounds.min.y - body.position.y) / bodyHeight; - - centerOffset.x = bodyWidth * centerOfMass.x; - centerOffset.y = bodyHeight * centerOfMass.y; - } - }; - - /** - * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. - * Prefer to use the actual setter functions in performance critical situations. - * @method set - * @param {body} body - * @param {} settings A property name (or map of properties and values) to set on the body. - * @param {} value The value to set if `settings` is a single property name. - */ - Body.set = function(body, settings, value) { - var property; - - if (typeof settings === 'string') { - property = settings; - settings = {}; - settings[property] = value; - } - - for (property in settings) { - if (!Object.prototype.hasOwnProperty.call(settings, property)) - continue; - - value = settings[property]; - switch (property) { - - case 'isStatic': - Body.setStatic(body, value); - break; - case 'isSleeping': - Sleeping.set(body, value); - break; - case 'mass': - Body.setMass(body, value); - break; - case 'density': - Body.setDensity(body, value); - break; - case 'inertia': - Body.setInertia(body, value); - break; - case 'vertices': - Body.setVertices(body, value); - break; - case 'position': - Body.setPosition(body, value); - break; - case 'angle': - Body.setAngle(body, value); - break; - case 'velocity': - Body.setVelocity(body, value); - break; - case 'angularVelocity': - Body.setAngularVelocity(body, value); - break; - case 'parts': - Body.setParts(body, value); - break; - case 'centre': - Body.setCentre(body, value); - break; - default: - body[property] = value; - } - } - }; - - /** - * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. - * @method setStatic - * @param {body} body - * @param {bool} isStatic - */ - Body.setStatic = function(body, isStatic) { - for (var i = 0; i < body.parts.length; i++) { - var part = body.parts[i]; - part.isStatic = isStatic; - - if (isStatic) { - part._original = { - restitution: part.restitution, - friction: part.friction, - mass: part.mass, - inertia: part.inertia, - density: part.density, - inverseMass: part.inverseMass, - inverseInertia: part.inverseInertia - }; - - part.restitution = 0; - part.friction = 1; - part.mass = part.inertia = part.density = Infinity; - part.inverseMass = part.inverseInertia = 0; - - part.positionPrev.x = part.position.x; - part.positionPrev.y = part.position.y; - part.anglePrev = part.angle; - part.angularVelocity = 0; - part.speed = 0; - part.angularSpeed = 0; - part.motion = 0; - } else if (part._original) { - part.restitution = part._original.restitution; - part.friction = part._original.friction; - part.mass = part._original.mass; - part.inertia = part._original.inertia; - part.density = part._original.density; - part.inverseMass = part._original.inverseMass; - part.inverseInertia = part._original.inverseInertia; - - part._original = null; - } - } - }; - - /** - * Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change. - * @method setMass - * @param {body} body - * @param {number} mass - */ - Body.setMass = function(body, mass) { - var moment = body.inertia / (body.mass / 6); - body.inertia = moment * (mass / 6); - body.inverseInertia = 1 / body.inertia; - - body.mass = mass; - body.inverseMass = 1 / body.mass; - body.density = body.mass / body.area; - }; - - /** - * Sets the density of the body. Mass and inertia are automatically updated to reflect the change. - * @method setDensity - * @param {body} body - * @param {number} density - */ - Body.setDensity = function(body, density) { - Body.setMass(body, density * body.area); - body.density = density; - }; - - /** - * Sets the moment of inertia (i.e. second moment of area) of the body. - * Inverse inertia is automatically updated to reflect the change. Mass is not changed. - * @method setInertia - * @param {body} body - * @param {number} inertia - */ - Body.setInertia = function(body, inertia) { - body.inertia = inertia; - body.inverseInertia = 1 / body.inertia; - }; - - /** - * 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 - */ - Body.setVertices = function(body, vertices) { - // change vertices - if (vertices[0].body === body) { - body.vertices = vertices; - } else { - body.vertices = Vertices.create(vertices, body); - } - - // update properties - body.axes = Axes.fromVertices(body.vertices); - body.area = Vertices.area(body.vertices); - Body.setMass(body, body.density * body.area); - - // orient vertices around the centre of mass at origin (0, 0) - var centre = Vertices.centre(body.vertices); - Vertices.translate(body.vertices, centre, -1); - - // update inertia while vertices are at origin (0, 0) - Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass)); - - // update geometry - Vertices.translate(body.vertices, body.position); - - Bounds.update(body.bounds, body.vertices, body.velocity); - }; - - /** - * Sets the parts of the `body` and updates mass, inertia and centroid. - * Each part will have its parent set to `body`. - * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` - * Note that this method will ensure that the first part in `body.parts` will always be the `body`. - * @method setParts - * @param {body} body - * @param [body] parts - * @param {bool} [autoHull=true] - */ - Body.setParts = function(body, parts, autoHull) { - var i; - - // add all the parts, ensuring that the first part is always the parent body - parts = parts.slice(0); - body.parts.length = 0; - body.parts.push(body); - body.parent = body; - - for (i = 0; i < parts.length; i++) { - var part = parts[i]; - if (part !== body) { - part.parent = body; - body.parts.push(part); - } - } - - if (body.parts.length === 1) - return; - - autoHull = typeof autoHull !== 'undefined' ? autoHull : true; - - // find the convex hull of all parts to set on the parent body - if (autoHull) { - var vertices = []; - for (i = 0; i < parts.length; i++) { - vertices = vertices.concat(parts[i].vertices); - } - - Vertices.clockwiseSort(vertices); - - var hull = Vertices.hull(vertices), - hullCentre = Vertices.centre(hull); - - Body.setVertices(body, hull); - Vertices.translate(body.vertices, hullCentre); - } - - // sum the properties of all compound parts of the parent body - var total = Body._totalProperties(body); - - // Phaser addition - var cx = total.centre.x; - var cy = total.centre.y; - - var bounds = body.bounds; - var centerOfMass = body.centerOfMass; - var centerOffset = body.centerOffset; - - Bounds.update(bounds, body.vertices, body.velocity); - - centerOfMass.x = -(bounds.min.x - cx) / (bounds.max.x - bounds.min.x); - centerOfMass.y = -(bounds.min.y - cy) / (bounds.max.y - bounds.min.y); - - centerOffset.x = cx; - centerOffset.y = cy; - - body.area = total.area; - body.parent = body; - body.position.x = cx; - body.position.y = cy; - body.positionPrev.x = cx; - body.positionPrev.y = cy; - - Body.setMass(body, total.mass); - Body.setInertia(body, total.inertia); - Body.setPosition(body, total.centre); - }; - - /** - * Set the centre of mass of the body. - * The `centre` is a vector in world-space unless `relative` is set, in which case it is a translation. - * The centre of mass is the point the body rotates about and can be used to simulate non-uniform density. - * This is equal to moving `body.position` but not the `body.vertices`. - * Invalid if the `centre` falls outside the body's convex hull. - * @method setCentre - * @param {body} body - * @param {vector} centre - * @param {bool} relative - */ - Body.setCentre = function(body, centre, relative) { - if (!relative) { - body.positionPrev.x = centre.x - (body.position.x - body.positionPrev.x); - body.positionPrev.y = centre.y - (body.position.y - body.positionPrev.y); - body.position.x = centre.x; - body.position.y = centre.y; - } else { - body.positionPrev.x += centre.x; - body.positionPrev.y += centre.y; - body.position.x += centre.x; - body.position.y += centre.y; - } - }; - - /** - * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. - * @method setPosition - * @param {body} body - * @param {vector} position - */ - Body.setPosition = function(body, position) { - var delta = Vector.sub(position, body.position); - body.positionPrev.x += delta.x; - body.positionPrev.y += delta.y; - - for (var i = 0; i < body.parts.length; i++) { - var part = body.parts[i]; - part.position.x += delta.x; - part.position.y += delta.y; - Vertices.translate(part.vertices, delta); - Bounds.update(part.bounds, part.vertices, body.velocity); - } - }; - - /** - * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. - * @method setAngle - * @param {body} body - * @param {number} angle - */ - Body.setAngle = function(body, angle) { - var delta = angle - body.angle; - body.anglePrev += delta; - - for (var i = 0; i < body.parts.length; i++) { - var part = body.parts[i]; - part.angle += delta; - Vertices.rotate(part.vertices, delta, body.position); - Axes.rotate(part.axes, delta); - Bounds.update(part.bounds, part.vertices, body.velocity); - if (i > 0) { - Vector.rotateAbout(part.position, delta, body.position, part.position); - } - } - }; - - /** - * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. - * @method setVelocity - * @param {body} body - * @param {vector} velocity - */ - Body.setVelocity = function(body, velocity) { - body.positionPrev.x = body.position.x - velocity.x; - body.positionPrev.y = body.position.y - velocity.y; - body.velocity.x = velocity.x; - body.velocity.y = velocity.y; - body.speed = Vector.magnitude(body.velocity); - }; - - /** - * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. - * @method setAngularVelocity - * @param {body} body - * @param {number} velocity - */ - Body.setAngularVelocity = function(body, velocity) { - body.anglePrev = body.angle - velocity; - body.angularVelocity = velocity; - body.angularSpeed = Math.abs(body.angularVelocity); - }; - - /** - * Moves a body by a given vector relative to its current position, without imparting any velocity. - * @method translate - * @param {body} body - * @param {vector} translation - */ - Body.translate = function(body, translation) { - Body.setPosition(body, Vector.add(body.position, translation)); - }; - - /** - * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. - * @method rotate - * @param {body} body - * @param {number} rotation - * @param {vector} [point] - */ - Body.rotate = function(body, rotation, point) { - if (!point) { - Body.setAngle(body, body.angle + rotation); - } else { - var cos = Math.cos(rotation), - sin = Math.sin(rotation), - dx = body.position.x - point.x, - dy = body.position.y - point.y; - - Body.setPosition(body, { - x: point.x + (dx * cos - dy * sin), - y: point.y + (dx * sin + dy * cos) - }); - - Body.setAngle(body, body.angle + rotation); - } - }; - - /** - * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). - * @method scale - * @param {body} body - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} [point] - */ - Body.scale = function(body, scaleX, scaleY, point) { - var totalArea = 0, - totalInertia = 0; - - point = point || body.position; - - for (var i = 0; i < body.parts.length; i++) { - var part = body.parts[i]; - - part.scale.x = scaleX; - part.scale.y = scaleY; - - // scale vertices - Vertices.scale(part.vertices, scaleX, scaleY, point); - - // update properties - part.axes = Axes.fromVertices(part.vertices); - part.area = Vertices.area(part.vertices); - Body.setMass(part, body.density * part.area); - - // update inertia (requires vertices to be at origin) - Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y }); - Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass)); - Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y }); - - if (i > 0) { - totalArea += part.area; - totalInertia += part.inertia; - } - - // scale position - part.position.x = point.x + (part.position.x - point.x) * scaleX; - part.position.y = point.y + (part.position.y - point.y) * scaleY; - - // update bounds - Bounds.update(part.bounds, part.vertices, body.velocity); - } - - // handle parent body - if (body.parts.length > 1) { - body.area = totalArea; - - if (!body.isStatic) { - Body.setMass(body, body.density * totalArea); - Body.setInertia(body, totalInertia); - } - } - - // handle circles - if (body.circleRadius) { - if (scaleX === scaleY) { - body.circleRadius *= scaleX; - } else { - // body is no longer a circle - body.circleRadius = null; - } - } - }; - - /** - * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. - * @method update - * @param {body} body - * @param {number} deltaTime - * @param {number} timeScale - * @param {number} correction - */ - Body.update = function(body, deltaTime, timeScale, correction) { - var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2); - - // from the previous step - var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale, - velocityPrevX = body.position.x - body.positionPrev.x, - velocityPrevY = body.position.y - body.positionPrev.y; - - // update velocity with Verlet integration - body.velocity.x = (velocityPrevX * frictionAir * correction) + (body.force.x / body.mass) * deltaTimeSquared; - body.velocity.y = (velocityPrevY * frictionAir * correction) + (body.force.y / body.mass) * deltaTimeSquared; - - body.positionPrev.x = body.position.x; - body.positionPrev.y = body.position.y; - body.position.x += body.velocity.x; - body.position.y += body.velocity.y; - - // update angular velocity with Verlet integration - body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared; - body.anglePrev = body.angle; - body.angle += body.angularVelocity; - - // track speed and acceleration - body.speed = Vector.magnitude(body.velocity); - body.angularSpeed = Math.abs(body.angularVelocity); - - // transform the body geometry - for (var i = 0; i < body.parts.length; i++) { - var part = body.parts[i]; - - Vertices.translate(part.vertices, body.velocity); - - if (i > 0) { - part.position.x += body.velocity.x; - part.position.y += body.velocity.y; - } - - if (body.angularVelocity !== 0) { - Vertices.rotate(part.vertices, body.angularVelocity, body.position); - Axes.rotate(part.axes, body.angularVelocity); - if (i > 0) { - Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position); - } - } - - Bounds.update(part.bounds, part.vertices, body.velocity); - } - }; - - /** - * Applies a force to a body from a given world-space position, including resulting torque. - * @method applyForce - * @param {body} body - * @param {vector} position - * @param {vector} force - */ - Body.applyForce = function(body, position, force) { - body.force.x += force.x; - body.force.y += force.y; - var offset = { x: position.x - body.position.x, y: position.y - body.position.y }; - body.torque += offset.x * force.y - offset.y * force.x; - }; - - /** - * Returns the sums of the properties of all compound parts of the parent body. - * @method _totalProperties - * @private - * @param {body} body - * @return {} - */ - Body._totalProperties = function(body) { - // 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 - - var properties = { - mass: 0, - area: 0, - inertia: 0, - centre: { x: 0, y: 0 } - }; - - // sum the properties of all compound parts of the parent body - for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) { - var part = body.parts[i], - mass = part.mass !== Infinity ? part.mass : 1; - - properties.mass += mass; - properties.area += part.area; - properties.inertia += part.inertia; - properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass)); - } - - properties.centre = Vector.div(properties.centre, properties.mass); - - return properties; - }; - - /* - * - * Events Documentation - * - */ - - /** - * Fired when a body starts sleeping (where `this` is the body). - * - * @event sleepStart - * @this {body} The body that has started sleeping - * @param {} event An event object - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired when a body ends sleeping (where `this` is the body). - * - * @event sleepEnd - * @this {body} The body that has ended sleeping - * @param {} event An event object - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /* - * - * Properties Documentation - * - */ - - /** - * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`. - * - * @property id - * @type number - */ - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "body" - * @readOnly - */ - - /** - * An arbitrary `String` name to help the user identify and manage bodies. - * - * @property label - * @type string - * @default "Body" - */ - - /** - * An array of bodies that make up this body. - * The first body in the array must always be a self reference to the current body instance. - * All bodies in the `parts` array together form a single rigid compound body. - * Parts are allowed to overlap, have gaps or holes or even form concave bodies. - * Parts themselves should never be added to a `World`, only the parent body should be. - * Use `Body.setParts` when setting parts to ensure correct updates of all properties. - * - * @property parts - * @type body[] - */ - - /** - * An object reserved for storing plugin-specific properties. - * - * @property plugin - * @type {} - */ - - /** - * A self reference if the body is _not_ a part of another body. - * Otherwise this is a reference to the body that this is a part of. - * See `body.parts`. - * - * @property parent - * @type body - */ - - /** - * A `Number` specifying the angle of the body, in radians. - * - * @property angle - * @type number - * @default 0 - */ - - /** - * An array of `Vector` objects that specify the convex hull of the rigid body. - * These should be provided about the origin `(0, 0)`. E.g. - * - * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] - * - * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). - * The `Vector` objects are also augmented with additional properties required for efficient collision detection. - * - * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). - * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. - * - * @property vertices - * @type vector[] - */ - - /** - * A `Vector` that specifies the current world-space position of the body. - * - * @property position - * @type vector - * @default { x: 0, y: 0 } - */ - - /** - * A `Vector` that holds the current scale values as set by `Body.setScale`. - * - * @property scale - * @type vector - * @default { x: 1, y: 1 } - */ - - /** - * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. - * - * @property force - * @type vector - * @default { x: 0, y: 0 } - */ - - /** - * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. - * - * @property torque - * @type number - * @default 0 - */ - - /** - * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). - * - * @readOnly - * @property speed - * @type number - * @default 0 - */ - - /** - * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). - * - * @readOnly - * @property angularSpeed - * @type number - * @default 0 - */ - - /** - * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. - * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). - * - * @readOnly - * @property velocity - * @type vector - * @default { x: 0, y: 0 } - */ - - /** - * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. - * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). - * - * @readOnly - * @property angularVelocity - * @type number - * @default 0 - */ - - /** - * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. - * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. - * - * @property isStatic - * @type boolean - * @default false - */ - - /** - * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. - * - * @property isSensor - * @type boolean - * @default false - */ - - /** - * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. - * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. - * - * @property isSleeping - * @type boolean - * @default false - */ - - /** - * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. - * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. - * - * @readOnly - * @property motion - * @type number - * @default 0 - */ - - /** - * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). - * - * @property sleepThreshold - * @type number - * @default 60 - */ - - /** - * 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 mass of the body, although it may be more appropriate to specify the `density` property instead. - * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). - * - * @property mass - * @type number - */ - - /** - * A `Number` that defines the inverse mass of the body (`1 / mass`). - * If you modify this value, you must also modify the `body.mass` property. - * - * @property inverseMass - * @type number - */ - - /** - * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. - * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. - * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). - * - * @property inertia - * @type number - */ - - /** - * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). - * If you modify this value, you must also modify the `body.inertia` property. - * - * @property inverseInertia - * @type number - */ - - /** - * 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 - */ - - /** - * A `Number` that defines the static friction of the body (in the Coulomb friction model). - * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. - * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. - * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. - * - * @property frictionStatic - * @type number - * @default 0.5 - */ - - /** - * A `Number` that defines the air friction of the body (air resistance). - * A value of `0` means the body will never slow as it moves through space. - * The higher the value, the faster a body slows when moving through space. - * The effects of the value are non-linear. - * - * @property frictionAir - * @type number - * @default 0.01 - */ - - /** - * An `Object` that specifies the collision filtering properties of this body. - * - * Collisions between two bodies will obey the following rules: - * - If the two bodies have the same non-zero value of `collisionFilter.group`, - * they will always collide if the value is positive, and they will never collide - * if the value is negative. - * - If the two bodies have different values of `collisionFilter.group` or if one - * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: - * - * Each body belongs to a collision category, given by `collisionFilter.category`. This - * value is used as a bit field and the category should have only one bit set, meaning that - * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 - * different collision categories available. - * - * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies - * the categories it collides with (the value is the bitwise AND value of all these categories). - * - * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's - * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` - * are both true. - * - * @property collisionFilter - * @type object - */ - - /** - * An Integer `Number`, that specifies the collision group this body belongs to. - * See `body.collisionFilter` for more information. - * - * @property collisionFilter.group - * @type object - * @default 0 - */ - - /** - * A bit field that specifies the collision category this body belongs to. - * The category value should have only one bit set, for example `0x0001`. - * This means there are up to 32 unique collision categories available. - * See `body.collisionFilter` for more information. - * - * @property collisionFilter.category - * @type object - * @default 1 - */ - - /** - * A bit mask that specifies the collision categories this body may collide with. - * See `body.collisionFilter` for more information. - * - * @property collisionFilter.mask - * @type object - * @default -1 - */ - - /** - * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. - * Avoid changing this value unless you understand the purpose of `slop` in physics engines. - * The default should generally suffice, although very large bodies may require larger values for stable stacking. - * - * @property slop - * @type number - * @default 0.05 - */ - - /** - * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - * - * @property timeScale - * @type number - * @default 1 - */ - - /** - * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. - * - * @property render - * @type object - */ - - /** - * A flag that indicates if the body should be rendered. - * - * @property render.visible - * @type boolean - * @default true - */ - - /** - * Sets the opacity to use when rendering. - * - * @property render.opacity - * @type number - * @default 1 - */ - - /** - * An `Object` that defines the sprite properties to use when rendering, if any. - * - * @property render.sprite - * @type object - */ - - /** - * A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width). - * - * @property render.sprite.xOffset - * @type number - * @default 0 - */ - - /** - * A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height). - * - * @property render.sprite.yOffset - * @type number - * @default 0 - */ - - /** - * A hex color value that defines the fill color to use when rendering the body. - * - * @property render.fillColor - * @type number - */ - - /** - * A value that defines the fill opacity to use when rendering the body. - * - * @property render.fillOpacity - * @type number - */ - - /** - * A hex color value that defines the line color to use when rendering the body. - * - * @property render.lineColor - * @type number - */ - - /** - * A value that defines the line opacity to use when rendering the body. - * - * @property render.lineOpacity - * @type number - */ - - /** - * A `Number` that defines the line width to use when rendering the body outline. - * - * @property render.lineThickness - * @type number - */ - - /** - * An array of unique axis vectors (edge normals) used for collision detection. - * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. - * They are constantly updated by `Body.update` during the simulation. - * - * @property axes - * @type vector[] - */ - - /** - * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. - * - * @property area - * @type string - * @default - */ - - /** - * A `Bounds` object that defines the AABB region for the body. - * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. - * - * @property bounds - * @type bounds - */ - - /** - * A reference to the Phaser Game Object this body belongs to, if any. - * - * @property gameObject - * @type Phaser.GameObjects.GameObject - */ - - /** - * The center of mass of the Body. - * - * @property centerOfMass - * @type vector - * @default { x: 0, y: 0 } - */ - - /** - * The center of the body in pixel values. - * Used by Phaser for texture aligment. - * - * @property centerOffset - * @type vector - * @default { x: 0, y: 0 } - */ - - /** - * Will this Body ignore World gravity during the Engine update? - * - * @property ignoreGravity - * @type boolean - * @default false - */ - - /** - * Scale the influence of World gravity when applied to this body. - * - * @property gravityScale - * @type vector - * @default { x: 1, y: 1 } - */ - - /** - * Will this Body ignore Phaser Pointer input events? - * - * @property ignorePointer - * @type boolean - * @default false - */ - - /** - * A callback that is invoked when this Body starts colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideCallback - * @type function - * @default null - */ - - /** - * A callback that is invoked when this Body stops colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideEndCallback - * @type function - * @default null - */ - - /** - * A callback that is invoked for the duration that this Body is colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideActiveCallback - * @type function - * @default null - */ - - /** - * A collision callback dictionary used by the `Body.setOnCollideWith` function. - * - * @property onCollideWith - * @type object - * @default null - */ - -})(); +/** + * 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 + */ + +var Body = {}; + +module.exports = Body; + +var Vertices = require('../geometry/Vertices'); +var Vector = require('../geometry/Vector'); +var Sleeping = require('../core/Sleeping'); +var Common = require('../core/Common'); +var Bounds = require('../geometry/Bounds'); +var Axes = require('../geometry/Axes'); + +(function() { + + Body._inertiaScale = 4; + Body._nextCollidingGroupId = 1; + Body._nextNonCollidingGroupId = -1; + Body._nextCategory = 0x0001; + + /** + * 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 + */ + Body.create = function(options) { + var defaults = { + id: Common.nextId(), + type: 'body', + label: 'Body', + parts: [], + plugin: {}, + angle: 0, + vertices: null, // Phaser change: no point calling fromPath if they pass in vertices anyway + position: { x: 0, y: 0 }, + force: { x: 0, y: 0 }, + torque: 0, + positionImpulse: { x: 0, y: 0 }, + previousPositionImpulse: { x: 0, y: 0 }, + constraintImpulse: { x: 0, y: 0, angle: 0 }, + totalContacts: 0, + speed: 0, + angularSpeed: 0, + velocity: { x: 0, y: 0 }, + angularVelocity: 0, + isSensor: false, + isStatic: false, + isSleeping: false, + motion: 0, + sleepThreshold: 60, + density: 0.001, + restitution: 0, + friction: 0.1, + frictionStatic: 0.5, + frictionAir: 0.01, + collisionFilter: { + category: 0x0001, + mask: 0xFFFFFFFF, + group: 0 + }, + slop: 0.05, + timeScale: 1, + events: null, + bounds: null, + chamfer: null, + circleRadius: 0, + positionPrev: null, + anglePrev: 0, + parent: null, + axes: null, + area: 0, + mass: 0, + inverseMass: 0, + inertia: 0, + inverseInertia: 0, + _original: null, + render: { + visible: true, + opacity: 1, + sprite: { + xOffset: 0, + yOffset: 0 + }, + fillColor: null, // custom Phaser property + fillOpacity: null, // custom Phaser property + lineColor: null, // custom Phaser property + lineOpacity: null, // custom Phaser property + lineThickness: null // custom Phaser property + }, + gameObject: null, // custom Phaser property + scale: { x: 1, y: 1 }, // custom Phaser property + centerOfMass: { x: 0, y: 0 }, // custom Phaser property (float, 0 - 1) + centerOffset: { x: 0, y: 0 }, // custom Phaser property (pixel values) + gravityScale: { x: 1, y: 1 }, // custom Phaser property + ignoreGravity: false, // custom Phaser property + ignorePointer: false, // custom Phaser property + onCollideCallback: null, // custom Phaser property + onCollideEndCallback: null, // custom Phaser property + onCollideActiveCallback: null, // custom Phaser property + onCollideWith: {} // custom Phaser property + }; + + if (!options.hasOwnProperty('position') && options.hasOwnProperty('vertices')) + { + options.position = Vertices.centre(options.vertices); + } + else if (!options.hasOwnProperty('vertices')) + { + defaults.vertices = Vertices.fromPath('L 0 0 L 40 0 L 40 40 L 0 40'); + } + + var body = Common.extend(defaults, options); + + _initProperties(body, options); + + // Helper function + body.setOnCollideWith = function (body, callback) + { + if (callback) + { + this.onCollideWith[body.id] = callback; + } + else + { + delete this.onCollideWith[body.id]; + } + + return this; + } + + return body; + }; + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. + * See `body.collisionFilter` for more information. + * @method nextGroup + * @param {bool} [isNonColliding=false] + * @return {Number} Unique group index + */ + Body.nextGroup = function(isNonColliding) { + if (isNonColliding) + return Body._nextNonCollidingGroupId--; + + return Body._nextCollidingGroupId++; + }; + + /** + * Returns the next unique category bitfield (starting after the initial default category `0x0001`). + * There are 32 available. See `body.collisionFilter` for more information. + * @method nextCategory + * @return {Number} Unique category bitfield + */ + Body.nextCategory = function() { + Body._nextCategory = Body._nextCategory << 1; + return Body._nextCategory; + }; + + /** + * Initialises body properties. + * @method _initProperties + * @private + * @param {body} body + * @param {} [options] + */ + var _initProperties = function(body, options) { + options = options || {}; + + // init required properties (order is important) + Body.set(body, { + bounds: body.bounds || Bounds.create(body.vertices), + positionPrev: body.positionPrev || Vector.clone(body.position), + anglePrev: body.anglePrev || body.angle, + vertices: body.vertices, + parts: body.parts || [body], + isStatic: body.isStatic, + isSleeping: body.isSleeping, + parent: body.parent || body + }); + + var bounds = body.bounds; + + Vertices.rotate(body.vertices, body.angle, body.position); + Axes.rotate(body.axes, body.angle); + Bounds.update(bounds, body.vertices, body.velocity); + + // allow options to override the automatically calculated properties + Body.set(body, { + axes: options.axes || body.axes, + area: options.area || body.area, + mass: options.mass || body.mass, + inertia: options.inertia || body.inertia + }); + + if (body.parts.length === 1) + { + var centerOfMass = body.centerOfMass; + var centerOffset = body.centerOffset; + + var bodyWidth = bounds.max.x - bounds.min.x; + var bodyHeight = bounds.max.y - bounds.min.y; + + centerOfMass.x = -(bounds.min.x - body.position.x) / bodyWidth; + centerOfMass.y = -(bounds.min.y - body.position.y) / bodyHeight; + + centerOffset.x = bodyWidth * centerOfMass.x; + centerOffset.y = bodyHeight * centerOfMass.y; + } + }; + + /** + * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. + * Prefer to use the actual setter functions in performance critical situations. + * @method set + * @param {body} body + * @param {} settings A property name (or map of properties and values) to set on the body. + * @param {} value The value to set if `settings` is a single property name. + */ + Body.set = function(body, settings, value) { + var property; + + if (typeof settings === 'string') { + property = settings; + settings = {}; + settings[property] = value; + } + + for (property in settings) { + if (!Object.prototype.hasOwnProperty.call(settings, property)) + continue; + + value = settings[property]; + switch (property) { + + case 'isStatic': + Body.setStatic(body, value); + break; + case 'isSleeping': + Sleeping.set(body, value); + break; + case 'mass': + Body.setMass(body, value); + break; + case 'density': + Body.setDensity(body, value); + break; + case 'inertia': + Body.setInertia(body, value); + break; + case 'vertices': + Body.setVertices(body, value); + break; + case 'position': + Body.setPosition(body, value); + break; + case 'angle': + Body.setAngle(body, value); + break; + case 'velocity': + Body.setVelocity(body, value); + break; + case 'angularVelocity': + Body.setAngularVelocity(body, value); + break; + case 'parts': + Body.setParts(body, value); + break; + case 'centre': + Body.setCentre(body, value); + break; + default: + body[property] = value; + } + } + }; + + /** + * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. + * @method setStatic + * @param {body} body + * @param {bool} isStatic + */ + Body.setStatic = function(body, isStatic) { + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + part.isStatic = isStatic; + + if (isStatic) { + part._original = { + restitution: part.restitution, + friction: part.friction, + mass: part.mass, + inertia: part.inertia, + density: part.density, + inverseMass: part.inverseMass, + inverseInertia: part.inverseInertia + }; + + part.restitution = 0; + part.friction = 1; + part.mass = part.inertia = part.density = Infinity; + part.inverseMass = part.inverseInertia = 0; + + part.positionPrev.x = part.position.x; + part.positionPrev.y = part.position.y; + part.anglePrev = part.angle; + part.angularVelocity = 0; + part.speed = 0; + part.angularSpeed = 0; + part.motion = 0; + } else if (part._original) { + part.restitution = part._original.restitution; + part.friction = part._original.friction; + part.mass = part._original.mass; + part.inertia = part._original.inertia; + part.density = part._original.density; + part.inverseMass = part._original.inverseMass; + part.inverseInertia = part._original.inverseInertia; + + part._original = null; + } + } + }; + + /** + * Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change. + * @method setMass + * @param {body} body + * @param {number} mass + */ + Body.setMass = function(body, mass) { + var moment = body.inertia / (body.mass / 6); + body.inertia = moment * (mass / 6); + body.inverseInertia = 1 / body.inertia; + + body.mass = mass; + body.inverseMass = 1 / body.mass; + body.density = body.mass / body.area; + }; + + /** + * Sets the density of the body. Mass and inertia are automatically updated to reflect the change. + * @method setDensity + * @param {body} body + * @param {number} density + */ + Body.setDensity = function(body, density) { + Body.setMass(body, density * body.area); + body.density = density; + }; + + /** + * Sets the moment of inertia (i.e. second moment of area) of the body. + * Inverse inertia is automatically updated to reflect the change. Mass is not changed. + * @method setInertia + * @param {body} body + * @param {number} inertia + */ + Body.setInertia = function(body, inertia) { + body.inertia = inertia; + body.inverseInertia = 1 / body.inertia; + }; + + /** + * 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 + */ + Body.setVertices = function(body, vertices) { + // change vertices + if (vertices[0].body === body) { + body.vertices = vertices; + } else { + body.vertices = Vertices.create(vertices, body); + } + + // update properties + body.axes = Axes.fromVertices(body.vertices); + body.area = Vertices.area(body.vertices); + Body.setMass(body, body.density * body.area); + + // orient vertices around the centre of mass at origin (0, 0) + var centre = Vertices.centre(body.vertices); + Vertices.translate(body.vertices, centre, -1); + + // update inertia while vertices are at origin (0, 0) + Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass)); + + // update geometry + Vertices.translate(body.vertices, body.position); + + Bounds.update(body.bounds, body.vertices, body.velocity); + }; + + /** + * Sets the parts of the `body` and updates mass, inertia and centroid. + * Each part will have its parent set to `body`. + * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` + * Note that this method will ensure that the first part in `body.parts` will always be the `body`. + * @method setParts + * @param {body} body + * @param [body] parts + * @param {bool} [autoHull=true] + */ + Body.setParts = function(body, parts, autoHull) { + var i; + + // add all the parts, ensuring that the first part is always the parent body + parts = parts.slice(0); + body.parts.length = 0; + body.parts.push(body); + body.parent = body; + + for (i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part !== body) { + part.parent = body; + body.parts.push(part); + } + } + + if (body.parts.length === 1) + return; + + autoHull = typeof autoHull !== 'undefined' ? autoHull : true; + + // find the convex hull of all parts to set on the parent body + if (autoHull) { + var vertices = []; + for (i = 0; i < parts.length; i++) { + vertices = vertices.concat(parts[i].vertices); + } + + Vertices.clockwiseSort(vertices); + + var hull = Vertices.hull(vertices), + hullCentre = Vertices.centre(hull); + + Body.setVertices(body, hull); + Vertices.translate(body.vertices, hullCentre); + } + + // sum the properties of all compound parts of the parent body + var total = Body._totalProperties(body); + + // Phaser addition + var cx = total.centre.x; + var cy = total.centre.y; + + var bounds = body.bounds; + var centerOfMass = body.centerOfMass; + var centerOffset = body.centerOffset; + + Bounds.update(bounds, body.vertices, body.velocity); + + centerOfMass.x = -(bounds.min.x - cx) / (bounds.max.x - bounds.min.x); + centerOfMass.y = -(bounds.min.y - cy) / (bounds.max.y - bounds.min.y); + + centerOffset.x = cx; + centerOffset.y = cy; + + body.area = total.area; + body.parent = body; + body.position.x = cx; + body.position.y = cy; + body.positionPrev.x = cx; + body.positionPrev.y = cy; + + Body.setMass(body, total.mass); + Body.setInertia(body, total.inertia); + Body.setPosition(body, total.centre); + }; + + /** + * Set the centre of mass of the body. + * The `centre` is a vector in world-space unless `relative` is set, in which case it is a translation. + * The centre of mass is the point the body rotates about and can be used to simulate non-uniform density. + * This is equal to moving `body.position` but not the `body.vertices`. + * Invalid if the `centre` falls outside the body's convex hull. + * @method setCentre + * @param {body} body + * @param {vector} centre + * @param {bool} relative + */ + Body.setCentre = function(body, centre, relative) { + if (!relative) { + body.positionPrev.x = centre.x - (body.position.x - body.positionPrev.x); + body.positionPrev.y = centre.y - (body.position.y - body.positionPrev.y); + body.position.x = centre.x; + body.position.y = centre.y; + } else { + body.positionPrev.x += centre.x; + body.positionPrev.y += centre.y; + body.position.x += centre.x; + body.position.y += centre.y; + } + }; + + /** + * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. + * @method setPosition + * @param {body} body + * @param {vector} position + */ + Body.setPosition = function(body, position) { + var delta = Vector.sub(position, body.position); + body.positionPrev.x += delta.x; + body.positionPrev.y += delta.y; + + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + part.position.x += delta.x; + part.position.y += delta.y; + Vertices.translate(part.vertices, delta); + Bounds.update(part.bounds, part.vertices, body.velocity); + } + }; + + /** + * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. + * @method setAngle + * @param {body} body + * @param {number} angle + */ + Body.setAngle = function(body, angle) { + var delta = angle - body.angle; + body.anglePrev += delta; + + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + part.angle += delta; + Vertices.rotate(part.vertices, delta, body.position); + Axes.rotate(part.axes, delta); + Bounds.update(part.bounds, part.vertices, body.velocity); + if (i > 0) { + Vector.rotateAbout(part.position, delta, body.position, part.position); + } + } + }; + + /** + * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setVelocity + * @param {body} body + * @param {vector} velocity + */ + Body.setVelocity = function(body, velocity) { + body.positionPrev.x = body.position.x - velocity.x; + body.positionPrev.y = body.position.y - velocity.y; + body.velocity.x = velocity.x; + body.velocity.y = velocity.y; + body.speed = Vector.magnitude(body.velocity); + }; + + /** + * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setAngularVelocity + * @param {body} body + * @param {number} velocity + */ + Body.setAngularVelocity = function(body, velocity) { + body.anglePrev = body.angle - velocity; + body.angularVelocity = velocity; + body.angularSpeed = Math.abs(body.angularVelocity); + }; + + /** + * Moves a body by a given vector relative to its current position, without imparting any velocity. + * @method translate + * @param {body} body + * @param {vector} translation + */ + Body.translate = function(body, translation) { + Body.setPosition(body, Vector.add(body.position, translation)); + }; + + /** + * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. + * @method rotate + * @param {body} body + * @param {number} rotation + * @param {vector} [point] + */ + Body.rotate = function(body, rotation, point) { + if (!point) { + Body.setAngle(body, body.angle + rotation); + } else { + var cos = Math.cos(rotation), + sin = Math.sin(rotation), + dx = body.position.x - point.x, + dy = body.position.y - point.y; + + Body.setPosition(body, { + x: point.x + (dx * cos - dy * sin), + y: point.y + (dx * sin + dy * cos) + }); + + Body.setAngle(body, body.angle + rotation); + } + }; + + /** + * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). + * @method scale + * @param {body} body + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} [point] + */ + Body.scale = function(body, scaleX, scaleY, point) { + var totalArea = 0, + totalInertia = 0; + + point = point || body.position; + + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + + part.scale.x = scaleX; + part.scale.y = scaleY; + + // scale vertices + Vertices.scale(part.vertices, scaleX, scaleY, point); + + // update properties + part.axes = Axes.fromVertices(part.vertices); + part.area = Vertices.area(part.vertices); + Body.setMass(part, body.density * part.area); + + // update inertia (requires vertices to be at origin) + Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y }); + Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass)); + Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y }); + + if (i > 0) { + totalArea += part.area; + totalInertia += part.inertia; + } + + // scale position + part.position.x = point.x + (part.position.x - point.x) * scaleX; + part.position.y = point.y + (part.position.y - point.y) * scaleY; + + // update bounds + Bounds.update(part.bounds, part.vertices, body.velocity); + } + + // handle parent body + if (body.parts.length > 1) { + body.area = totalArea; + + if (!body.isStatic) { + Body.setMass(body, body.density * totalArea); + Body.setInertia(body, totalInertia); + } + } + + // handle circles + if (body.circleRadius) { + if (scaleX === scaleY) { + body.circleRadius *= scaleX; + } else { + // body is no longer a circle + body.circleRadius = null; + } + } + }; + + /** + * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. + * @method update + * @param {body} body + * @param {number} deltaTime + * @param {number} timeScale + * @param {number} correction + */ + Body.update = function(body, deltaTime, timeScale, correction) { + var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2); + + // from the previous step + var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale, + velocityPrevX = body.position.x - body.positionPrev.x, + velocityPrevY = body.position.y - body.positionPrev.y; + + // update velocity with Verlet integration + body.velocity.x = (velocityPrevX * frictionAir * correction) + (body.force.x / body.mass) * deltaTimeSquared; + body.velocity.y = (velocityPrevY * frictionAir * correction) + (body.force.y / body.mass) * deltaTimeSquared; + + body.positionPrev.x = body.position.x; + body.positionPrev.y = body.position.y; + body.position.x += body.velocity.x; + body.position.y += body.velocity.y; + + // update angular velocity with Verlet integration + body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared; + body.anglePrev = body.angle; + body.angle += body.angularVelocity; + + // track speed and acceleration + body.speed = Vector.magnitude(body.velocity); + body.angularSpeed = Math.abs(body.angularVelocity); + + // transform the body geometry + for (var i = 0; i < body.parts.length; i++) { + var part = body.parts[i]; + + Vertices.translate(part.vertices, body.velocity); + + if (i > 0) { + part.position.x += body.velocity.x; + part.position.y += body.velocity.y; + } + + if (body.angularVelocity !== 0) { + Vertices.rotate(part.vertices, body.angularVelocity, body.position); + Axes.rotate(part.axes, body.angularVelocity); + if (i > 0) { + Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position); + } + } + + Bounds.update(part.bounds, part.vertices, body.velocity); + } + }; + + /** + * Applies a force to a body from a given world-space position, including resulting torque. + * @method applyForce + * @param {body} body + * @param {vector} position + * @param {vector} force + */ + Body.applyForce = function(body, position, force) { + body.force.x += force.x; + body.force.y += force.y; + var offset = { x: position.x - body.position.x, y: position.y - body.position.y }; + body.torque += offset.x * force.y - offset.y * force.x; + }; + + /** + * Returns the sums of the properties of all compound parts of the parent body. + * @method _totalProperties + * @private + * @param {body} body + * @return {} + */ + Body._totalProperties = function(body) { + // 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 + + var properties = { + mass: 0, + area: 0, + inertia: 0, + centre: { x: 0, y: 0 } + }; + + // sum the properties of all compound parts of the parent body + for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) { + var part = body.parts[i], + mass = part.mass !== Infinity ? part.mass : 1; + + properties.mass += mass; + properties.area += part.area; + properties.inertia += part.inertia; + properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass)); + } + + properties.centre = Vector.div(properties.centre, properties.mass); + + return properties; + }; + + /* + * + * Events Documentation + * + */ + + /** + * Fired when a body starts sleeping (where `this` is the body). + * + * @event sleepStart + * @this {body} The body that has started sleeping + * @param {} event An event object + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a body ends sleeping (where `this` is the body). + * + * @event sleepEnd + * @this {body} The body that has ended sleeping + * @param {} event An event object + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`. + * + * @property id + * @type number + */ + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "body" + * @readOnly + */ + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Body" + */ + + /** + * An array of bodies that make up this body. + * The first body in the array must always be a self reference to the current body instance. + * All bodies in the `parts` array together form a single rigid compound body. + * Parts are allowed to overlap, have gaps or holes or even form concave bodies. + * Parts themselves should never be added to a `World`, only the parent body should be. + * Use `Body.setParts` when setting parts to ensure correct updates of all properties. + * + * @property parts + * @type body[] + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + + /** + * A self reference if the body is _not_ a part of another body. + * Otherwise this is a reference to the body that this is a part of. + * See `body.parts`. + * + * @property parent + * @type body + */ + + /** + * A `Number` specifying the angle of the body, in radians. + * + * @property angle + * @type number + * @default 0 + */ + + /** + * An array of `Vector` objects that specify the convex hull of the rigid body. + * These should be provided about the origin `(0, 0)`. E.g. + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). + * The `Vector` objects are also augmented with additional properties required for efficient collision detection. + * + * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). + * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. + * + * @property vertices + * @type vector[] + */ + + /** + * A `Vector` that specifies the current world-space position of the body. + * + * @property position + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Vector` that holds the current scale values as set by `Body.setScale`. + * + * @property scale + * @type vector + * @default { x: 1, y: 1 } + */ + + /** + * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. + * + * @property force + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. + * + * @property torque + * @type number + * @default 0 + */ + + /** + * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). + * + * @readOnly + * @property speed + * @type number + * @default 0 + */ + + /** + * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). + * + * @readOnly + * @property angularSpeed + * @type number + * @default 0 + */ + + /** + * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property velocity + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property angularVelocity + * @type number + * @default 0 + */ + + /** + * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. + * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. + * + * @property isStatic + * @type boolean + * @default false + */ + + /** + * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + * + * @property isSensor + * @type boolean + * @default false + */ + + /** + * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. + * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. + * + * @property isSleeping + * @type boolean + * @default false + */ + + /** + * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. + * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. + * + * @readOnly + * @property motion + * @type number + * @default 0 + */ + + /** + * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). + * + * @property sleepThreshold + * @type number + * @default 60 + */ + + /** + * 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 mass of the body, although it may be more appropriate to specify the `density` property instead. + * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). + * + * @property mass + * @type number + */ + + /** + * A `Number` that defines the inverse mass of the body (`1 / mass`). + * If you modify this value, you must also modify the `body.mass` property. + * + * @property inverseMass + * @type number + */ + + /** + * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. + * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. + * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). + * + * @property inertia + * @type number + */ + + /** + * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). + * If you modify this value, you must also modify the `body.inertia` property. + * + * @property inverseInertia + * @type number + */ + + /** + * 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 + */ + + /** + * A `Number` that defines the static friction of the body (in the Coulomb friction model). + * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. + * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. + * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. + * + * @property frictionStatic + * @type number + * @default 0.5 + */ + + /** + * A `Number` that defines the air friction of the body (air resistance). + * A value of `0` means the body will never slow as it moves through space. + * The higher the value, the faster a body slows when moving through space. + * The effects of the value are non-linear. + * + * @property frictionAir + * @type number + * @default 0.01 + */ + + /** + * An `Object` that specifies the collision filtering properties of this body. + * + * Collisions between two bodies will obey the following rules: + * - If the two bodies have the same non-zero value of `collisionFilter.group`, + * they will always collide if the value is positive, and they will never collide + * if the value is negative. + * - If the two bodies have different values of `collisionFilter.group` or if one + * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: + * + * Each body belongs to a collision category, given by `collisionFilter.category`. This + * value is used as a bit field and the category should have only one bit set, meaning that + * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 + * different collision categories available. + * + * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies + * the categories it collides with (the value is the bitwise AND value of all these categories). + * + * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's + * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` + * are both true. + * + * @property collisionFilter + * @type object + */ + + /** + * An Integer `Number`, that specifies the collision group this body belongs to. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter.group + * @type object + * @default 0 + */ + + /** + * A bit field that specifies the collision category this body belongs to. + * The category value should have only one bit set, for example `0x0001`. + * This means there are up to 32 unique collision categories available. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter.category + * @type object + * @default 1 + */ + + /** + * A bit mask that specifies the collision categories this body may collide with. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter.mask + * @type object + * @default -1 + */ + + /** + * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. + * Avoid changing this value unless you understand the purpose of `slop` in physics engines. + * The default should generally suffice, although very large bodies may require larger values for stable stacking. + * + * @property slop + * @type number + * @default 0.05 + */ + + /** + * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + * + * @property timeScale + * @type number + * @default 1 + */ + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + + /** + * A flag that indicates if the body should be rendered. + * + * @property render.visible + * @type boolean + * @default true + */ + + /** + * Sets the opacity to use when rendering. + * + * @property render.opacity + * @type number + * @default 1 + */ + + /** + * An `Object` that defines the sprite properties to use when rendering, if any. + * + * @property render.sprite + * @type object + */ + + /** + * A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width). + * + * @property render.sprite.xOffset + * @type number + * @default 0 + */ + + /** + * A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height). + * + * @property render.sprite.yOffset + * @type number + * @default 0 + */ + + /** + * A hex color value that defines the fill color to use when rendering the body. + * + * @property render.fillColor + * @type number + */ + + /** + * A value that defines the fill opacity to use when rendering the body. + * + * @property render.fillOpacity + * @type number + */ + + /** + * A hex color value that defines the line color to use when rendering the body. + * + * @property render.lineColor + * @type number + */ + + /** + * A value that defines the line opacity to use when rendering the body. + * + * @property render.lineOpacity + * @type number + */ + + /** + * A `Number` that defines the line width to use when rendering the body outline. + * + * @property render.lineThickness + * @type number + */ + + /** + * An array of unique axis vectors (edge normals) used for collision detection. + * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. + * They are constantly updated by `Body.update` during the simulation. + * + * @property axes + * @type vector[] + */ + + /** + * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. + * + * @property area + * @type string + * @default + */ + + /** + * A `Bounds` object that defines the AABB region for the body. + * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. + * + * @property bounds + * @type bounds + */ + + /** + * A reference to the Phaser Game Object this body belongs to, if any. + * + * @property gameObject + * @type Phaser.GameObjects.GameObject + */ + + /** + * The center of mass of the Body. + * + * @property centerOfMass + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * The center of the body in pixel values. + * Used by Phaser for texture aligment. + * + * @property centerOffset + * @type vector + * @default { x: 0, y: 0 } + */ + + /** + * Will this Body ignore World gravity during the Engine update? + * + * @property ignoreGravity + * @type boolean + * @default false + */ + + /** + * Scale the influence of World gravity when applied to this body. + * + * @property gravityScale + * @type vector + * @default { x: 1, y: 1 } + */ + + /** + * Will this Body ignore Phaser Pointer input events? + * + * @property ignorePointer + * @type boolean + * @default false + */ + + /** + * A callback that is invoked when this Body starts colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideCallback + * @type function + * @default null + */ + + /** + * A callback that is invoked when this Body stops colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideEndCallback + * @type function + * @default null + */ + + /** + * A callback that is invoked for the duration that this Body is colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideActiveCallback + * @type function + * @default null + */ + + /** + * A collision callback dictionary used by the `Body.setOnCollideWith` function. + * + * @property onCollideWith + * @type object + * @default null + */ + +})(); diff --git a/src/physics/matter-js/lib/body/Composite.js b/src/physics/matter-js/lib/body/Composite.js index ef364654d..f2f77ece0 100644 --- a/src/physics/matter-js/lib/body/Composite.js +++ b/src/physics/matter-js/lib/body/Composite.js @@ -1,688 +1,688 @@ -/** -* 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 -*/ - -var Composite = {}; - -module.exports = Composite; - -var Events = require('../core/Events'); -var Common = require('../core/Common'); -var Bounds = require('../geometry/Bounds'); -var Body = require('./Body'); - -(function() { - - /** - * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. - * See the properites section below for detailed information on what you can pass via the `options` object. - * @method create - * @param {} [options] - * @return {composite} A new composite - */ - Composite.create = function(options) { - return Common.extend({ - id: Common.nextId(), - type: 'composite', - parent: null, - isModified: false, - bodies: [], - constraints: [], - composites: [], - label: 'Composite', - plugin: {} - }, options); - }; - - /** - * Sets the composite's `isModified` flag. - * If `updateParents` is true, all parents will be set (default: false). - * If `updateChildren` is true, all children will be set (default: false). - * @method setModified - * @param {composite} composite - * @param {boolean} isModified - * @param {boolean} [updateParents=false] - * @param {boolean} [updateChildren=false] - */ - Composite.setModified = function(composite, isModified, updateParents, updateChildren) { - - Events.trigger(composite, 'compositeModified', composite); - - composite.isModified = isModified; - - if (updateParents && composite.parent) { - Composite.setModified(composite.parent, isModified, updateParents, updateChildren); - } - - if (updateChildren) { - for(var i = 0; i < composite.composites.length; i++) { - var childComposite = composite.composites[i]; - Composite.setModified(childComposite, isModified, updateParents, updateChildren); - } - } - }; - - /** - * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. - * Triggers `beforeAdd` and `afterAdd` events on the `composite`. - * @method add - * @param {composite} composite - * @param {} object - * @return {composite} The original composite with the objects added - */ - Composite.add = function(composite, object) { - var objects = [].concat(object); - - Events.trigger(composite, 'beforeAdd', { object: object }); - - for (var i = 0; i < objects.length; i++) { - var obj = objects[i]; - - switch (obj.type) { - - case 'body': - // skip adding compound parts - if (obj.parent !== obj) { - Common.warn('Composite.add: skipped adding a compound body part (you must add its parent instead)'); - break; - } - - Composite.addBody(composite, obj); - break; - case 'constraint': - Composite.addConstraint(composite, obj); - break; - case 'composite': - Composite.addComposite(composite, obj); - break; - case 'mouseConstraint': - Composite.addConstraint(composite, obj.constraint); - break; - - } - } - - Events.trigger(composite, 'afterAdd', { object: object }); - - return composite; - }; - - /** - * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. - * Optionally searching its children recursively. - * Triggers `beforeRemove` and `afterRemove` events on the `composite`. - * @method remove - * @param {composite} composite - * @param {} object - * @param {boolean} [deep=false] - * @return {composite} The original composite with the objects removed - */ - Composite.remove = function(composite, object, deep) { - var objects = [].concat(object); - - Events.trigger(composite, 'beforeRemove', { object: object }); - - for (var i = 0; i < objects.length; i++) { - var obj = objects[i]; - - switch (obj.type) { - - case 'body': - Composite.removeBody(composite, obj, deep); - break; - case 'constraint': - Composite.removeConstraint(composite, obj, deep); - break; - case 'composite': - Composite.removeComposite(composite, obj, deep); - break; - case 'mouseConstraint': - Composite.removeConstraint(composite, obj.constraint); - break; - - } - } - - Events.trigger(composite, 'afterRemove', { object: object }); - - return composite; - }; - - /** - * Adds a composite to the given composite. - * @private - * @method addComposite - * @param {composite} compositeA - * @param {composite} compositeB - * @return {composite} The original compositeA with the objects from compositeB added - */ - Composite.addComposite = function(compositeA, compositeB) { - compositeA.composites.push(compositeB); - compositeB.parent = compositeA; - Composite.setModified(compositeA, true, true, false); - return compositeA; - }; - - /** - * Removes a composite from the given composite, and optionally searching its children recursively. - * @private - * @method removeComposite - * @param {composite} compositeA - * @param {composite} compositeB - * @param {boolean} [deep=false] - * @return {composite} The original compositeA with the composite removed - */ - Composite.removeComposite = function(compositeA, compositeB, deep) { - var position = compositeA.composites.indexOf(compositeB); - if (position !== -1) { - Composite.removeCompositeAt(compositeA, position); - Composite.setModified(compositeA, true, true, false); - } - - if (deep) { - for (var i = 0; i < compositeA.composites.length; i++){ - Composite.removeComposite(compositeA.composites[i], compositeB, true); - } - } - - return compositeA; - }; - - /** - * Removes a composite from the given composite. - * @private - * @method removeCompositeAt - * @param {composite} composite - * @param {number} position - * @return {composite} The original composite with the composite removed - */ - Composite.removeCompositeAt = function(composite, position) { - composite.composites.splice(position, 1); - Composite.setModified(composite, true, true, false); - return composite; - }; - - /** - * Adds a body to the given composite. - * @private - * @method addBody - * @param {composite} composite - * @param {body} body - * @return {composite} The original composite with the body added - */ - Composite.addBody = function(composite, body) { - composite.bodies.push(body); - Composite.setModified(composite, true, true, false); - return composite; - }; - - /** - * Removes a body from the given composite, and optionally searching its children recursively. - * @private - * @method removeBody - * @param {composite} composite - * @param {body} body - * @param {boolean} [deep=false] - * @return {composite} The original composite with the body removed - */ - Composite.removeBody = function(composite, body, deep) { - var position = composite.bodies.indexOf(body); - if (position !== -1) { - Composite.removeBodyAt(composite, position); - Composite.setModified(composite, true, true, false); - } - - if (deep) { - for (var i = 0; i < composite.composites.length; i++){ - Composite.removeBody(composite.composites[i], body, true); - } - } - - return composite; - }; - - /** - * Removes a body from the given composite. - * @private - * @method removeBodyAt - * @param {composite} composite - * @param {number} position - * @return {composite} The original composite with the body removed - */ - Composite.removeBodyAt = function(composite, position) { - composite.bodies.splice(position, 1); - Composite.setModified(composite, true, true, false); - return composite; - }; - - /** - * Adds a constraint to the given composite. - * @private - * @method addConstraint - * @param {composite} composite - * @param {constraint} constraint - * @return {composite} The original composite with the constraint added - */ - Composite.addConstraint = function(composite, constraint) { - composite.constraints.push(constraint); - Composite.setModified(composite, true, true, false); - return composite; - }; - - /** - * Removes a constraint from the given composite, and optionally searching its children recursively. - * @private - * @method removeConstraint - * @param {composite} composite - * @param {constraint} constraint - * @param {boolean} [deep=false] - * @return {composite} The original composite with the constraint removed - */ - Composite.removeConstraint = function(composite, constraint, deep) { - var position = composite.constraints.indexOf(constraint); - if (position !== -1) { - Composite.removeConstraintAt(composite, position); - } - - if (deep) { - for (var i = 0; i < composite.composites.length; i++){ - Composite.removeConstraint(composite.composites[i], constraint, true); - } - } - - return composite; - }; - - /** - * Removes a body from the given composite. - * @private - * @method removeConstraintAt - * @param {composite} composite - * @param {number} position - * @return {composite} The original composite with the constraint removed - */ - Composite.removeConstraintAt = function(composite, position) { - composite.constraints.splice(position, 1); - Composite.setModified(composite, true, true, false); - return composite; - }; - - /** - * Removes all bodies, constraints and composites from the given composite. - * Optionally clearing its children recursively. - * @method clear - * @param {composite} composite - * @param {boolean} keepStatic - * @param {boolean} [deep=false] - */ - Composite.clear = function(composite, keepStatic, deep) { - if (deep) { - for (var i = 0; i < composite.composites.length; i++){ - Composite.clear(composite.composites[i], keepStatic, true); - } - } - - if (keepStatic) { - composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; }); - } else { - composite.bodies.length = 0; - } - - composite.constraints.length = 0; - composite.composites.length = 0; - Composite.setModified(composite, true, true, false); - - return composite; - }; - - /** - * Returns all bodies in the given composite, including all bodies in its children, recursively. - * @method allBodies - * @param {composite} composite - * @return {body[]} All the bodies - */ - Composite.allBodies = function(composite) { - var bodies = [].concat(composite.bodies); - - for (var i = 0; i < composite.composites.length; i++) - bodies = bodies.concat(Composite.allBodies(composite.composites[i])); - - return bodies; - }; - - /** - * Returns all constraints in the given composite, including all constraints in its children, recursively. - * @method allConstraints - * @param {composite} composite - * @return {constraint[]} All the constraints - */ - Composite.allConstraints = function(composite) { - var constraints = [].concat(composite.constraints); - - for (var i = 0; i < composite.composites.length; i++) - constraints = constraints.concat(Composite.allConstraints(composite.composites[i])); - - return constraints; - }; - - /** - * Returns all composites in the given composite, including all composites in its children, recursively. - * @method allComposites - * @param {composite} composite - * @return {composite[]} All the composites - */ - Composite.allComposites = function(composite) { - var composites = [].concat(composite.composites); - - for (var i = 0; i < composite.composites.length; i++) - composites = composites.concat(Composite.allComposites(composite.composites[i])); - - return composites; - }; - - /** - * Searches the composite recursively for an object matching the type and id supplied, null if not found. - * @method get - * @param {composite} composite - * @param {number} id - * @param {string} type - * @return {object} The requested object, if found - */ - Composite.get = function(composite, id, type) { - var objects, - object; - - switch (type) { - case 'body': - objects = Composite.allBodies(composite); - break; - case 'constraint': - objects = Composite.allConstraints(composite); - break; - case 'composite': - objects = Composite.allComposites(composite).concat(composite); - break; - } - - if (!objects) - return null; - - object = objects.filter(function(object) { - return object.id.toString() === id.toString(); - }); - - return object.length === 0 ? null : object[0]; - }; - - /** - * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). - * @method move - * @param {compositeA} compositeA - * @param {object[]} objects - * @param {compositeB} compositeB - * @return {composite} Returns compositeA - */ - Composite.move = function(compositeA, objects, compositeB) { - Composite.remove(compositeA, objects); - Composite.add(compositeB, objects); - return compositeA; - }; - - /** - * Assigns new ids for all objects in the composite, recursively. - * @method rebase - * @param {composite} composite - * @return {composite} Returns composite - */ - Composite.rebase = function(composite) { - var objects = Composite.allBodies(composite) - .concat(Composite.allConstraints(composite)) - .concat(Composite.allComposites(composite)); - - for (var i = 0; i < objects.length; i++) { - objects[i].id = Common.nextId(); - } - - Composite.setModified(composite, true, true, false); - - return composite; - }; - - /** - * Translates all children in the composite by a given vector relative to their current positions, - * without imparting any velocity. - * @method translate - * @param {composite} composite - * @param {vector} translation - * @param {bool} [recursive=true] - */ - Composite.translate = function(composite, translation, recursive) { - var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; - - for (var i = 0; i < bodies.length; i++) { - Body.translate(bodies[i], translation); - } - - Composite.setModified(composite, true, true, false); - - return composite; - }; - - /** - * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. - * @method rotate - * @param {composite} composite - * @param {number} rotation - * @param {vector} point - * @param {bool} [recursive=true] - */ - Composite.rotate = function(composite, rotation, point, recursive) { - var cos = Math.cos(rotation), - sin = Math.sin(rotation), - bodies = recursive ? Composite.allBodies(composite) : composite.bodies; - - for (var i = 0; i < bodies.length; i++) { - var body = bodies[i], - dx = body.position.x - point.x, - dy = body.position.y - point.y; - - Body.setPosition(body, { - x: point.x + (dx * cos - dy * sin), - y: point.y + (dx * sin + dy * cos) - }); - - Body.rotate(body, rotation); - } - - Composite.setModified(composite, true, true, false); - - return composite; - }; - - /** - * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. - * @method scale - * @param {composite} composite - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} point - * @param {bool} [recursive=true] - */ - Composite.scale = function(composite, scaleX, scaleY, point, recursive) { - var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; - - for (var i = 0; i < bodies.length; i++) { - var body = bodies[i], - dx = body.position.x - point.x, - dy = body.position.y - point.y; - - Body.setPosition(body, { - x: point.x + dx * scaleX, - y: point.y + dy * scaleY - }); - - Body.scale(body, scaleX, scaleY); - } - - Composite.setModified(composite, true, true, false); - - return composite; - }; - - /** - * Returns the union of the bounds of all of the composite's bodies. - * @method bounds - * @param {composite} composite The composite. - * @returns {bounds} The composite bounds. - */ - Composite.bounds = function(composite) { - var bodies = Composite.allBodies(composite), - vertices = []; - - for (var i = 0; i < bodies.length; i += 1) { - var body = bodies[i]; - vertices.push(body.bounds.min, body.bounds.max); - } - - return Bounds.create(vertices); - }; - - /* - * - * Events Documentation - * - */ - - /** - * Fired when a call to `Composite.add` is made, before objects have been added. - * - * @event beforeAdd - * @param {} event An event object - * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired when a call to `Composite.add` is made, after objects have been added. - * - * @event afterAdd - * @param {} event An event object - * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired when a call to `Composite.remove` is made, before objects have been removed. - * - * @event beforeRemove - * @param {} event An event object - * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired when a call to `Composite.remove` is made, after objects have been removed. - * - * @event afterRemove - * @param {} event An event object - * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /* - * - * Properties Documentation - * - */ - - /** - * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. - * - * @property id - * @type number - */ - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "composite" - * @readOnly - */ - - /** - * An arbitrary `String` name to help the user identify and manage composites. - * - * @property label - * @type string - * @default "Composite" - */ - - /** - * A flag that specifies whether the composite has been modified during the current step. - * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. - * If you need to change it manually, you should use the `Composite.setModified` method. - * - * @property isModified - * @type boolean - * @default false - */ - - /** - * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. - * - * @property parent - * @type composite - * @default null - */ - - /** - * An array of `Body` that are _direct_ children of this composite. - * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. - * - * @property bodies - * @type body[] - * @default [] - */ - - /** - * An array of `Constraint` that are _direct_ children of this composite. - * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. - * - * @property constraints - * @type constraint[] - * @default [] - */ - - /** - * An array of `Composite` that are _direct_ children of this composite. - * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. - * - * @property composites - * @type composite[] - * @default [] - */ - - /** - * An object reserved for storing plugin-specific properties. - * - * @property plugin - * @type {} - */ - -})(); +/** +* 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 +*/ + +var Composite = {}; + +module.exports = Composite; + +var Events = require('../core/Events'); +var Common = require('../core/Common'); +var Bounds = require('../geometry/Bounds'); +var Body = require('./Body'); + +(function() { + + /** + * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. + * See the properites section below for detailed information on what you can pass via the `options` object. + * @method create + * @param {} [options] + * @return {composite} A new composite + */ + Composite.create = function(options) { + return Common.extend({ + id: Common.nextId(), + type: 'composite', + parent: null, + isModified: false, + bodies: [], + constraints: [], + composites: [], + label: 'Composite', + plugin: {} + }, options); + }; + + /** + * Sets the composite's `isModified` flag. + * If `updateParents` is true, all parents will be set (default: false). + * If `updateChildren` is true, all children will be set (default: false). + * @method setModified + * @param {composite} composite + * @param {boolean} isModified + * @param {boolean} [updateParents=false] + * @param {boolean} [updateChildren=false] + */ + Composite.setModified = function(composite, isModified, updateParents, updateChildren) { + + Events.trigger(composite, 'compositeModified', composite); + + composite.isModified = isModified; + + if (updateParents && composite.parent) { + Composite.setModified(composite.parent, isModified, updateParents, updateChildren); + } + + if (updateChildren) { + for(var i = 0; i < composite.composites.length; i++) { + var childComposite = composite.composites[i]; + Composite.setModified(childComposite, isModified, updateParents, updateChildren); + } + } + }; + + /** + * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. + * Triggers `beforeAdd` and `afterAdd` events on the `composite`. + * @method add + * @param {composite} composite + * @param {} object + * @return {composite} The original composite with the objects added + */ + Composite.add = function(composite, object) { + var objects = [].concat(object); + + Events.trigger(composite, 'beforeAdd', { object: object }); + + for (var i = 0; i < objects.length; i++) { + var obj = objects[i]; + + switch (obj.type) { + + case 'body': + // skip adding compound parts + if (obj.parent !== obj) { + Common.warn('Composite.add: skipped adding a compound body part (you must add its parent instead)'); + break; + } + + Composite.addBody(composite, obj); + break; + case 'constraint': + Composite.addConstraint(composite, obj); + break; + case 'composite': + Composite.addComposite(composite, obj); + break; + case 'mouseConstraint': + Composite.addConstraint(composite, obj.constraint); + break; + + } + } + + Events.trigger(composite, 'afterAdd', { object: object }); + + return composite; + }; + + /** + * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. + * Optionally searching its children recursively. + * Triggers `beforeRemove` and `afterRemove` events on the `composite`. + * @method remove + * @param {composite} composite + * @param {} object + * @param {boolean} [deep=false] + * @return {composite} The original composite with the objects removed + */ + Composite.remove = function(composite, object, deep) { + var objects = [].concat(object); + + Events.trigger(composite, 'beforeRemove', { object: object }); + + for (var i = 0; i < objects.length; i++) { + var obj = objects[i]; + + switch (obj.type) { + + case 'body': + Composite.removeBody(composite, obj, deep); + break; + case 'constraint': + Composite.removeConstraint(composite, obj, deep); + break; + case 'composite': + Composite.removeComposite(composite, obj, deep); + break; + case 'mouseConstraint': + Composite.removeConstraint(composite, obj.constraint); + break; + + } + } + + Events.trigger(composite, 'afterRemove', { object: object }); + + return composite; + }; + + /** + * Adds a composite to the given composite. + * @private + * @method addComposite + * @param {composite} compositeA + * @param {composite} compositeB + * @return {composite} The original compositeA with the objects from compositeB added + */ + Composite.addComposite = function(compositeA, compositeB) { + compositeA.composites.push(compositeB); + compositeB.parent = compositeA; + Composite.setModified(compositeA, true, true, false); + return compositeA; + }; + + /** + * Removes a composite from the given composite, and optionally searching its children recursively. + * @private + * @method removeComposite + * @param {composite} compositeA + * @param {composite} compositeB + * @param {boolean} [deep=false] + * @return {composite} The original compositeA with the composite removed + */ + Composite.removeComposite = function(compositeA, compositeB, deep) { + var position = compositeA.composites.indexOf(compositeB); + if (position !== -1) { + Composite.removeCompositeAt(compositeA, position); + Composite.setModified(compositeA, true, true, false); + } + + if (deep) { + for (var i = 0; i < compositeA.composites.length; i++){ + Composite.removeComposite(compositeA.composites[i], compositeB, true); + } + } + + return compositeA; + }; + + /** + * Removes a composite from the given composite. + * @private + * @method removeCompositeAt + * @param {composite} composite + * @param {number} position + * @return {composite} The original composite with the composite removed + */ + Composite.removeCompositeAt = function(composite, position) { + composite.composites.splice(position, 1); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Adds a body to the given composite. + * @private + * @method addBody + * @param {composite} composite + * @param {body} body + * @return {composite} The original composite with the body added + */ + Composite.addBody = function(composite, body) { + composite.bodies.push(body); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Removes a body from the given composite, and optionally searching its children recursively. + * @private + * @method removeBody + * @param {composite} composite + * @param {body} body + * @param {boolean} [deep=false] + * @return {composite} The original composite with the body removed + */ + Composite.removeBody = function(composite, body, deep) { + var position = composite.bodies.indexOf(body); + if (position !== -1) { + Composite.removeBodyAt(composite, position); + Composite.setModified(composite, true, true, false); + } + + if (deep) { + for (var i = 0; i < composite.composites.length; i++){ + Composite.removeBody(composite.composites[i], body, true); + } + } + + return composite; + }; + + /** + * Removes a body from the given composite. + * @private + * @method removeBodyAt + * @param {composite} composite + * @param {number} position + * @return {composite} The original composite with the body removed + */ + Composite.removeBodyAt = function(composite, position) { + composite.bodies.splice(position, 1); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Adds a constraint to the given composite. + * @private + * @method addConstraint + * @param {composite} composite + * @param {constraint} constraint + * @return {composite} The original composite with the constraint added + */ + Composite.addConstraint = function(composite, constraint) { + composite.constraints.push(constraint); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Removes a constraint from the given composite, and optionally searching its children recursively. + * @private + * @method removeConstraint + * @param {composite} composite + * @param {constraint} constraint + * @param {boolean} [deep=false] + * @return {composite} The original composite with the constraint removed + */ + Composite.removeConstraint = function(composite, constraint, deep) { + var position = composite.constraints.indexOf(constraint); + if (position !== -1) { + Composite.removeConstraintAt(composite, position); + } + + if (deep) { + for (var i = 0; i < composite.composites.length; i++){ + Composite.removeConstraint(composite.composites[i], constraint, true); + } + } + + return composite; + }; + + /** + * Removes a body from the given composite. + * @private + * @method removeConstraintAt + * @param {composite} composite + * @param {number} position + * @return {composite} The original composite with the constraint removed + */ + Composite.removeConstraintAt = function(composite, position) { + composite.constraints.splice(position, 1); + Composite.setModified(composite, true, true, false); + return composite; + }; + + /** + * Removes all bodies, constraints and composites from the given composite. + * Optionally clearing its children recursively. + * @method clear + * @param {composite} composite + * @param {boolean} keepStatic + * @param {boolean} [deep=false] + */ + Composite.clear = function(composite, keepStatic, deep) { + if (deep) { + for (var i = 0; i < composite.composites.length; i++){ + Composite.clear(composite.composites[i], keepStatic, true); + } + } + + if (keepStatic) { + composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; }); + } else { + composite.bodies.length = 0; + } + + composite.constraints.length = 0; + composite.composites.length = 0; + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Returns all bodies in the given composite, including all bodies in its children, recursively. + * @method allBodies + * @param {composite} composite + * @return {body[]} All the bodies + */ + Composite.allBodies = function(composite) { + var bodies = [].concat(composite.bodies); + + for (var i = 0; i < composite.composites.length; i++) + bodies = bodies.concat(Composite.allBodies(composite.composites[i])); + + return bodies; + }; + + /** + * Returns all constraints in the given composite, including all constraints in its children, recursively. + * @method allConstraints + * @param {composite} composite + * @return {constraint[]} All the constraints + */ + Composite.allConstraints = function(composite) { + var constraints = [].concat(composite.constraints); + + for (var i = 0; i < composite.composites.length; i++) + constraints = constraints.concat(Composite.allConstraints(composite.composites[i])); + + return constraints; + }; + + /** + * Returns all composites in the given composite, including all composites in its children, recursively. + * @method allComposites + * @param {composite} composite + * @return {composite[]} All the composites + */ + Composite.allComposites = function(composite) { + var composites = [].concat(composite.composites); + + for (var i = 0; i < composite.composites.length; i++) + composites = composites.concat(Composite.allComposites(composite.composites[i])); + + return composites; + }; + + /** + * Searches the composite recursively for an object matching the type and id supplied, null if not found. + * @method get + * @param {composite} composite + * @param {number} id + * @param {string} type + * @return {object} The requested object, if found + */ + Composite.get = function(composite, id, type) { + var objects, + object; + + switch (type) { + case 'body': + objects = Composite.allBodies(composite); + break; + case 'constraint': + objects = Composite.allConstraints(composite); + break; + case 'composite': + objects = Composite.allComposites(composite).concat(composite); + break; + } + + if (!objects) + return null; + + object = objects.filter(function(object) { + return object.id.toString() === id.toString(); + }); + + return object.length === 0 ? null : object[0]; + }; + + /** + * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). + * @method move + * @param {compositeA} compositeA + * @param {object[]} objects + * @param {compositeB} compositeB + * @return {composite} Returns compositeA + */ + Composite.move = function(compositeA, objects, compositeB) { + Composite.remove(compositeA, objects); + Composite.add(compositeB, objects); + return compositeA; + }; + + /** + * Assigns new ids for all objects in the composite, recursively. + * @method rebase + * @param {composite} composite + * @return {composite} Returns composite + */ + Composite.rebase = function(composite) { + var objects = Composite.allBodies(composite) + .concat(Composite.allConstraints(composite)) + .concat(Composite.allComposites(composite)); + + for (var i = 0; i < objects.length; i++) { + objects[i].id = Common.nextId(); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Translates all children in the composite by a given vector relative to their current positions, + * without imparting any velocity. + * @method translate + * @param {composite} composite + * @param {vector} translation + * @param {bool} [recursive=true] + */ + Composite.translate = function(composite, translation, recursive) { + var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; + + for (var i = 0; i < bodies.length; i++) { + Body.translate(bodies[i], translation); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. + * @method rotate + * @param {composite} composite + * @param {number} rotation + * @param {vector} point + * @param {bool} [recursive=true] + */ + Composite.rotate = function(composite, rotation, point, recursive) { + var cos = Math.cos(rotation), + sin = Math.sin(rotation), + bodies = recursive ? Composite.allBodies(composite) : composite.bodies; + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + dx = body.position.x - point.x, + dy = body.position.y - point.y; + + Body.setPosition(body, { + x: point.x + (dx * cos - dy * sin), + y: point.y + (dx * sin + dy * cos) + }); + + Body.rotate(body, rotation); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. + * @method scale + * @param {composite} composite + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + * @param {bool} [recursive=true] + */ + Composite.scale = function(composite, scaleX, scaleY, point, recursive) { + var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i], + dx = body.position.x - point.x, + dy = body.position.y - point.y; + + Body.setPosition(body, { + x: point.x + dx * scaleX, + y: point.y + dy * scaleY + }); + + Body.scale(body, scaleX, scaleY); + } + + Composite.setModified(composite, true, true, false); + + return composite; + }; + + /** + * Returns the union of the bounds of all of the composite's bodies. + * @method bounds + * @param {composite} composite The composite. + * @returns {bounds} The composite bounds. + */ + Composite.bounds = function(composite) { + var bodies = Composite.allBodies(composite), + vertices = []; + + for (var i = 0; i < bodies.length; i += 1) { + var body = bodies[i]; + vertices.push(body.bounds.min, body.bounds.max); + } + + return Bounds.create(vertices); + }; + + /* + * + * Events Documentation + * + */ + + /** + * Fired when a call to `Composite.add` is made, before objects have been added. + * + * @event beforeAdd + * @param {} event An event object + * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a call to `Composite.add` is made, after objects have been added. + * + * @event afterAdd + * @param {} event An event object + * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a call to `Composite.remove` is made, before objects have been removed. + * + * @event beforeRemove + * @param {} event An event object + * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired when a call to `Composite.remove` is made, after objects have been removed. + * + * @event afterRemove + * @param {} event An event object + * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "composite" + * @readOnly + */ + + /** + * An arbitrary `String` name to help the user identify and manage composites. + * + * @property label + * @type string + * @default "Composite" + */ + + /** + * A flag that specifies whether the composite has been modified during the current step. + * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. + * If you need to change it manually, you should use the `Composite.setModified` method. + * + * @property isModified + * @type boolean + * @default false + */ + + /** + * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. + * + * @property parent + * @type composite + * @default null + */ + + /** + * An array of `Body` that are _direct_ children of this composite. + * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. + * + * @property bodies + * @type body[] + * @default [] + */ + + /** + * An array of `Constraint` that are _direct_ children of this composite. + * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. + * + * @property constraints + * @type constraint[] + * @default [] + */ + + /** + * An array of `Composite` that are _direct_ children of this composite. + * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. + * + * @property composites + * @type composite[] + * @default [] + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + +})(); diff --git a/src/physics/matter-js/lib/core/Engine.js b/src/physics/matter-js/lib/core/Engine.js index e95732f83..9dfb5d847 100644 --- a/src/physics/matter-js/lib/core/Engine.js +++ b/src/physics/matter-js/lib/core/Engine.js @@ -1,487 +1,487 @@ -/** -* 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 -*/ - -var Engine = {}; - -module.exports = Engine; - -var World = require('../body/World'); -var Sleeping = require('./Sleeping'); -var Resolver = require('../collision/Resolver'); -var Pairs = require('../collision/Pairs'); -var Metrics = require('./Metrics'); -var Grid = require('../collision/Grid'); -var Events = require('./Events'); -var Composite = require('../body/Composite'); -var Constraint = require('../constraint/Constraint'); -var Common = require('./Common'); -var Body = require('../body/Body'); - -(function() { - - /** - * 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 - */ - Engine.create = function(element, options) { - // options may be passed as the first (and only) argument - options = Common.isElement(element) ? options : element; - element = Common.isElement(element) ? element : null; - options = options || {}; - - if (element || options.render) { - Common.warn('Engine.create: engine.render is deprecated (see docs)'); - } - - var defaults = { - positionIterations: 6, - velocityIterations: 4, - constraintIterations: 2, - enableSleeping: false, - events: [], - plugin: {}, - timing: { - timestamp: 0, - timeScale: 1 - }, - broadphase: { - controller: Grid - } - }; - - var engine = Common.extend(defaults, options); - - engine.world = options.world || World.create(engine.world); - engine.pairs = Pairs.create(); - engine.broadphase = engine.broadphase.controller.create(engine.broadphase); - engine.metrics = engine.metrics || { extended: false }; - - // @if DEBUG - engine.metrics = Metrics.create(engine.metrics); - // @endif - - return engine; - }; - - /** - * Moves the simulation forward in time by `delta` ms. - * The `correction` argument is 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` 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. - * @method update - * @param {engine} engine - * @param {number} [delta=16.666] - * @param {number} [correction=1] - */ - Engine.update = function(engine, delta, correction) { - delta = delta || 1000 / 60; - correction = correction || 1; - - var world = engine.world, - timing = engine.timing, - broadphase = engine.broadphase, - broadphasePairs = [], - i; - - // increment timestamp - timing.timestamp += delta * timing.timeScale; - - // create an event object - var event = { - timestamp: timing.timestamp - }; - - Events.trigger(engine, 'beforeUpdate', event); - - // get lists of all bodies and constraints, no matter what composites they are in - var allBodies = Composite.allBodies(world), - allConstraints = Composite.allConstraints(world); - - // @if DEBUG - // reset metrics logging - Metrics.reset(engine.metrics); - // @endif - - // if sleeping enabled, call the sleeping controller - if (engine.enableSleeping) - Sleeping.update(allBodies, timing.timeScale); - - // applies gravity to all bodies - Engine._bodiesApplyGravity(allBodies, world.gravity); - - // update all body position and rotation by integration - Engine._bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds); - - // update all constraints (first pass) - Constraint.preSolveAll(allBodies); - for (i = 0; i < engine.constraintIterations; i++) { - Constraint.solveAll(allConstraints, timing.timeScale); - } - Constraint.postSolveAll(allBodies); - - // broadphase pass: find potential collision pairs - if (broadphase.controller) { - // if world is dirty, we must flush the whole grid - if (world.isModified) - broadphase.controller.clear(broadphase); - - // update the grid buckets based on current bodies - broadphase.controller.update(broadphase, allBodies, engine, world.isModified); - broadphasePairs = broadphase.pairsList; - } else { - // if no broadphase set, we just pass all bodies - broadphasePairs = allBodies; - } - - // clear all composite modified flags - if (world.isModified) { - Composite.setModified(world, false, false, true); - } - - // narrowphase pass: find actual collisions, then create or update collision pairs - var collisions = broadphase.detector(broadphasePairs, engine); - - // update collision pairs - var pairs = engine.pairs, - timestamp = timing.timestamp; - Pairs.update(pairs, collisions, timestamp); - Pairs.removeOld(pairs, timestamp); - - // wake up bodies involved in collisions - if (engine.enableSleeping) - Sleeping.afterCollisions(pairs.list, timing.timeScale); - - // trigger collision events - if (pairs.collisionStart.length > 0) - Events.trigger(engine, 'collisionStart', { pairs: pairs.collisionStart }); - - // iteratively resolve position between collisions - Resolver.preSolvePosition(pairs.list); - for (i = 0; i < engine.positionIterations; i++) { - Resolver.solvePosition(pairs.list, allBodies, timing.timeScale); - } - Resolver.postSolvePosition(allBodies); - - // update all constraints (second pass) - Constraint.preSolveAll(allBodies); - for (i = 0; i < engine.constraintIterations; i++) { - Constraint.solveAll(allConstraints, timing.timeScale); - } - Constraint.postSolveAll(allBodies); - - // iteratively resolve velocity between collisions - Resolver.preSolveVelocity(pairs.list); - for (i = 0; i < engine.velocityIterations; i++) { - Resolver.solveVelocity(pairs.list, timing.timeScale); - } - - // trigger collision events - if (pairs.collisionActive.length > 0) - Events.trigger(engine, 'collisionActive', { pairs: pairs.collisionActive }); - - if (pairs.collisionEnd.length > 0) - Events.trigger(engine, 'collisionEnd', { pairs: pairs.collisionEnd }); - - // @if DEBUG - // update metrics log - Metrics.update(engine.metrics, engine); - // @endif - - // clear force buffers - Engine._bodiesClearForces(allBodies); - - Events.trigger(engine, 'afterUpdate', event); - - return engine; - }; - - /** - * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. - * @method merge - * @param {engine} engineA - * @param {engine} engineB - */ - Engine.merge = function(engineA, engineB) { - Common.extend(engineA, engineB); - - if (engineB.world) { - engineA.world = engineB.world; - - Engine.clear(engineA); - - var bodies = Composite.allBodies(engineA.world); - - for (var i = 0; i < bodies.length; i++) { - var body = bodies[i]; - Sleeping.set(body, false); - body.id = Common.nextId(); - } - } - }; - - /** - * Clears the engine including the world, pairs and broadphase. - * @method clear - * @param {engine} engine - */ - Engine.clear = function(engine) { - var world = engine.world; - - Pairs.clear(engine.pairs); - - var broadphase = engine.broadphase; - if (broadphase.controller) { - var bodies = Composite.allBodies(world); - broadphase.controller.clear(broadphase); - broadphase.controller.update(broadphase, bodies, engine, true); - } - }; - - /** - * Zeroes the `body.force` and `body.torque` force buffers. - * @method _bodiesClearForces - * @private - * @param {body[]} bodies - */ - Engine._bodiesClearForces = function(bodies) { - for (var i = 0; i < bodies.length; i++) { - var body = bodies[i]; - - // reset force buffers - body.force.x = 0; - body.force.y = 0; - body.torque = 0; - } - }; - - /** - * Applys a mass dependant force to all given bodies. - * @method _bodiesApplyGravity - * @private - * @param {body[]} bodies - * @param {vector} gravity - */ - Engine._bodiesApplyGravity = function(bodies, gravity) { - var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001; - - if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) { - return; - } - - for (var i = 0; i < bodies.length; i++) { - var body = bodies[i]; - - if (body.ignoreGravity || body.isStatic || body.isSleeping) - continue; - - // apply gravity - body.force.x += (body.mass * gravity.x * gravityScale) * body.gravityScale.x; - body.force.y += (body.mass * gravity.y * gravityScale) * body.gravityScale.y; - } - }; - - /** - * Applys `Body.update` to all given `bodies`. - * @method _bodiesUpdate - * @private - * @param {body[]} bodies - * @param {number} deltaTime - * The amount of time elapsed between updates - * @param {number} timeScale - * @param {number} correction - * The Verlet correction factor (deltaTime / lastDeltaTime) - * @param {bounds} worldBounds - */ - Engine._bodiesUpdate = function(bodies, deltaTime, timeScale, correction, worldBounds) { - for (var i = 0; i < bodies.length; i++) { - var body = bodies[i]; - - if (body.isStatic || body.isSleeping) - continue; - - Body.update(body, deltaTime, timeScale, correction); - } - }; - - /** - * An alias for `Runner.run`, see `Matter.Runner` for more information. - * @method run - * @param {engine} engine - */ - - /** - * Fired just before an update - * - * @event beforeUpdate - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after engine update and all collision events - * - * @event afterUpdate - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) - * - * @event collisionStart - * @param {} event An event object - * @param {} event.pairs List of affected pairs - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) - * - * @event collisionActive - * @param {} event An event object - * @param {} event.pairs List of affected pairs - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /** - * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) - * - * @event collisionEnd - * @param {} event An event object - * @param {} event.pairs List of affected pairs - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - - /* - * - * Properties Documentation - * - */ - - /** - * An integer `Number` that specifies the number of position iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * - * @property positionIterations - * @type number - * @default 6 - */ - - /** - * An integer `Number` that specifies the number of velocity iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * - * @property velocityIterations - * @type number - * @default 4 - */ - - /** - * An integer `Number` that specifies the number of constraint iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * The default value of `2` is usually very adequate. - * - * @property constraintIterations - * @type number - * @default 2 - */ - - /** - * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. - * Sleeping can improve stability and performance, but often at the expense of accuracy. - * - * @property enableSleeping - * @type boolean - * @default false - */ - - /** - * An `Object` containing properties regarding the timing systems of the engine. - * - * @property timing - * @type object - */ - - /** - * A `Number` that specifies the global scaling factor of time for all bodies. - * A value of `0` freezes the simulation. - * A value of `0.1` gives a slow-motion effect. - * A value of `1.2` gives a speed-up effect. - * - * @property timing.timeScale - * @type number - * @default 1 - */ - - /** - * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. - * It is incremented on every `Engine.update` by the given `delta` argument. - * - * @property timing.timestamp - * @type number - * @default 0 - */ - - /** - * An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`. - * One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`. - * - * A minimal custom renderer object must define at least three functions: `create`, `clear` and `world` (see `Matter.Render`). - * It is also possible to instead pass the _module_ reference via `options.render.controller` and `Engine.create` will instantiate one for you. - * - * @property render - * @type render - * @deprecated see Demo.js for an example of creating a renderer - * @default a Matter.Render instance - */ - - /** - * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. - * - * @property broadphase - * @type grid - * @default a Matter.Grid instance - */ - - /** - * A `World` composite object that will contain all simulated bodies and constraints. - * - * @property world - * @type world - * @default a Matter.World instance - */ - - /** - * An object reserved for storing plugin-specific properties. - * - * @property plugin - * @type {} - */ - -})(); +/** +* 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 +*/ + +var Engine = {}; + +module.exports = Engine; + +var World = require('../body/World'); +var Sleeping = require('./Sleeping'); +var Resolver = require('../collision/Resolver'); +var Pairs = require('../collision/Pairs'); +var Metrics = require('./Metrics'); +var Grid = require('../collision/Grid'); +var Events = require('./Events'); +var Composite = require('../body/Composite'); +var Constraint = require('../constraint/Constraint'); +var Common = require('./Common'); +var Body = require('../body/Body'); + +(function() { + + /** + * 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 + */ + Engine.create = function(element, options) { + // options may be passed as the first (and only) argument + options = Common.isElement(element) ? options : element; + element = Common.isElement(element) ? element : null; + options = options || {}; + + if (element || options.render) { + Common.warn('Engine.create: engine.render is deprecated (see docs)'); + } + + var defaults = { + positionIterations: 6, + velocityIterations: 4, + constraintIterations: 2, + enableSleeping: false, + events: [], + plugin: {}, + timing: { + timestamp: 0, + timeScale: 1 + }, + broadphase: { + controller: Grid + } + }; + + var engine = Common.extend(defaults, options); + + engine.world = options.world || World.create(engine.world); + engine.pairs = Pairs.create(); + engine.broadphase = engine.broadphase.controller.create(engine.broadphase); + engine.metrics = engine.metrics || { extended: false }; + + // @if DEBUG + engine.metrics = Metrics.create(engine.metrics); + // @endif + + return engine; + }; + + /** + * Moves the simulation forward in time by `delta` ms. + * The `correction` argument is 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` 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. + * @method update + * @param {engine} engine + * @param {number} [delta=16.666] + * @param {number} [correction=1] + */ + Engine.update = function(engine, delta, correction) { + delta = delta || 1000 / 60; + correction = correction || 1; + + var world = engine.world, + timing = engine.timing, + broadphase = engine.broadphase, + broadphasePairs = [], + i; + + // increment timestamp + timing.timestamp += delta * timing.timeScale; + + // create an event object + var event = { + timestamp: timing.timestamp + }; + + Events.trigger(engine, 'beforeUpdate', event); + + // get lists of all bodies and constraints, no matter what composites they are in + var allBodies = Composite.allBodies(world), + allConstraints = Composite.allConstraints(world); + + // @if DEBUG + // reset metrics logging + Metrics.reset(engine.metrics); + // @endif + + // if sleeping enabled, call the sleeping controller + if (engine.enableSleeping) + Sleeping.update(allBodies, timing.timeScale); + + // applies gravity to all bodies + Engine._bodiesApplyGravity(allBodies, world.gravity); + + // update all body position and rotation by integration + Engine._bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds); + + // update all constraints (first pass) + Constraint.preSolveAll(allBodies); + for (i = 0; i < engine.constraintIterations; i++) { + Constraint.solveAll(allConstraints, timing.timeScale); + } + Constraint.postSolveAll(allBodies); + + // broadphase pass: find potential collision pairs + if (broadphase.controller) { + // if world is dirty, we must flush the whole grid + if (world.isModified) + broadphase.controller.clear(broadphase); + + // update the grid buckets based on current bodies + broadphase.controller.update(broadphase, allBodies, engine, world.isModified); + broadphasePairs = broadphase.pairsList; + } else { + // if no broadphase set, we just pass all bodies + broadphasePairs = allBodies; + } + + // clear all composite modified flags + if (world.isModified) { + Composite.setModified(world, false, false, true); + } + + // narrowphase pass: find actual collisions, then create or update collision pairs + var collisions = broadphase.detector(broadphasePairs, engine); + + // update collision pairs + var pairs = engine.pairs, + timestamp = timing.timestamp; + Pairs.update(pairs, collisions, timestamp); + Pairs.removeOld(pairs, timestamp); + + // wake up bodies involved in collisions + if (engine.enableSleeping) + Sleeping.afterCollisions(pairs.list, timing.timeScale); + + // trigger collision events + if (pairs.collisionStart.length > 0) + Events.trigger(engine, 'collisionStart', { pairs: pairs.collisionStart }); + + // iteratively resolve position between collisions + Resolver.preSolvePosition(pairs.list); + for (i = 0; i < engine.positionIterations; i++) { + Resolver.solvePosition(pairs.list, allBodies, timing.timeScale); + } + Resolver.postSolvePosition(allBodies); + + // update all constraints (second pass) + Constraint.preSolveAll(allBodies); + for (i = 0; i < engine.constraintIterations; i++) { + Constraint.solveAll(allConstraints, timing.timeScale); + } + Constraint.postSolveAll(allBodies); + + // iteratively resolve velocity between collisions + Resolver.preSolveVelocity(pairs.list); + for (i = 0; i < engine.velocityIterations; i++) { + Resolver.solveVelocity(pairs.list, timing.timeScale); + } + + // trigger collision events + if (pairs.collisionActive.length > 0) + Events.trigger(engine, 'collisionActive', { pairs: pairs.collisionActive }); + + if (pairs.collisionEnd.length > 0) + Events.trigger(engine, 'collisionEnd', { pairs: pairs.collisionEnd }); + + // @if DEBUG + // update metrics log + Metrics.update(engine.metrics, engine); + // @endif + + // clear force buffers + Engine._bodiesClearForces(allBodies); + + Events.trigger(engine, 'afterUpdate', event); + + return engine; + }; + + /** + * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. + * @method merge + * @param {engine} engineA + * @param {engine} engineB + */ + Engine.merge = function(engineA, engineB) { + Common.extend(engineA, engineB); + + if (engineB.world) { + engineA.world = engineB.world; + + Engine.clear(engineA); + + var bodies = Composite.allBodies(engineA.world); + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + Sleeping.set(body, false); + body.id = Common.nextId(); + } + } + }; + + /** + * Clears the engine including the world, pairs and broadphase. + * @method clear + * @param {engine} engine + */ + Engine.clear = function(engine) { + var world = engine.world; + + Pairs.clear(engine.pairs); + + var broadphase = engine.broadphase; + if (broadphase.controller) { + var bodies = Composite.allBodies(world); + broadphase.controller.clear(broadphase); + broadphase.controller.update(broadphase, bodies, engine, true); + } + }; + + /** + * Zeroes the `body.force` and `body.torque` force buffers. + * @method _bodiesClearForces + * @private + * @param {body[]} bodies + */ + Engine._bodiesClearForces = function(bodies) { + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + // reset force buffers + body.force.x = 0; + body.force.y = 0; + body.torque = 0; + } + }; + + /** + * Applys a mass dependant force to all given bodies. + * @method _bodiesApplyGravity + * @private + * @param {body[]} bodies + * @param {vector} gravity + */ + Engine._bodiesApplyGravity = function(bodies, gravity) { + var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001; + + if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) { + return; + } + + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + if (body.ignoreGravity || body.isStatic || body.isSleeping) + continue; + + // apply gravity + body.force.x += (body.mass * gravity.x * gravityScale) * body.gravityScale.x; + body.force.y += (body.mass * gravity.y * gravityScale) * body.gravityScale.y; + } + }; + + /** + * Applys `Body.update` to all given `bodies`. + * @method _bodiesUpdate + * @private + * @param {body[]} bodies + * @param {number} deltaTime + * The amount of time elapsed between updates + * @param {number} timeScale + * @param {number} correction + * The Verlet correction factor (deltaTime / lastDeltaTime) + * @param {bounds} worldBounds + */ + Engine._bodiesUpdate = function(bodies, deltaTime, timeScale, correction, worldBounds) { + for (var i = 0; i < bodies.length; i++) { + var body = bodies[i]; + + if (body.isStatic || body.isSleeping) + continue; + + Body.update(body, deltaTime, timeScale, correction); + } + }; + + /** + * An alias for `Runner.run`, see `Matter.Runner` for more information. + * @method run + * @param {engine} engine + */ + + /** + * Fired just before an update + * + * @event beforeUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update and all collision events + * + * @event afterUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) + * + * @event collisionStart + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) + * + * @event collisionActive + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /** + * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) + * + * @event collisionEnd + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + + /* + * + * Properties Documentation + * + */ + + /** + * An integer `Number` that specifies the number of position iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property positionIterations + * @type number + * @default 6 + */ + + /** + * An integer `Number` that specifies the number of velocity iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property velocityIterations + * @type number + * @default 4 + */ + + /** + * An integer `Number` that specifies the number of constraint iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * The default value of `2` is usually very adequate. + * + * @property constraintIterations + * @type number + * @default 2 + */ + + /** + * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. + * Sleeping can improve stability and performance, but often at the expense of accuracy. + * + * @property enableSleeping + * @type boolean + * @default false + */ + + /** + * An `Object` containing properties regarding the timing systems of the engine. + * + * @property timing + * @type object + */ + + /** + * A `Number` that specifies the global scaling factor of time for all bodies. + * A value of `0` freezes the simulation. + * A value of `0.1` gives a slow-motion effect. + * A value of `1.2` gives a speed-up effect. + * + * @property timing.timeScale + * @type number + * @default 1 + */ + + /** + * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. + * It is incremented on every `Engine.update` by the given `delta` argument. + * + * @property timing.timestamp + * @type number + * @default 0 + */ + + /** + * An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`. + * One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`. + * + * A minimal custom renderer object must define at least three functions: `create`, `clear` and `world` (see `Matter.Render`). + * It is also possible to instead pass the _module_ reference via `options.render.controller` and `Engine.create` will instantiate one for you. + * + * @property render + * @type render + * @deprecated see Demo.js for an example of creating a renderer + * @default a Matter.Render instance + */ + + /** + * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. + * + * @property broadphase + * @type grid + * @default a Matter.Grid instance + */ + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + * + * @property world + * @type world + * @default a Matter.World instance + */ + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + +})(); diff --git a/src/physics/matter-js/typedefs/MatterBody.js b/src/physics/matter-js/typedefs/MatterBody.js index 2ae5dbc3a..cbac77d69 100644 --- a/src/physics/matter-js/typedefs/MatterBody.js +++ b/src/physics/matter-js/typedefs/MatterBody.js @@ -1,4 +1,4 @@ -/** - * @typedef {(MatterJS.BodyType|Phaser.GameObjects.GameObject|Phaser.Physics.Matter.Image|Phaser.Physics.Matter.Sprite|Phaser.Physics.Matter.TileBody)} Phaser.Types.Physics.Matter.MatterBody - * @since 3.22.0 - */ +/** + * @typedef {(MatterJS.BodyType|Phaser.GameObjects.GameObject|Phaser.Physics.Matter.Image|Phaser.Physics.Matter.Sprite|Phaser.Physics.Matter.TileBody)} Phaser.Types.Physics.Matter.MatterBody + * @since 3.22.0 + */ diff --git a/src/physics/matter-js/typedefs/MatterBodyConfig.js b/src/physics/matter-js/typedefs/MatterBodyConfig.js index a9f328730..cf3312448 100644 --- a/src/physics/matter-js/typedefs/MatterBodyConfig.js +++ b/src/physics/matter-js/typedefs/MatterBodyConfig.js @@ -1,37 +1,37 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterBodyConfig - * @since 3.22.0 - * - * @property {string} [label='Body'] - An arbitrary string-based name to help identify this body. - * @property {MatterJS.BodyType[]} [parts] - An array of bodies that make up this body. The first body in the array must always be a self reference to the current body instance. All bodies in the `parts` array together form a single rigid compound body. - * @property {any} [plugin] - An object reserved for storing plugin-specific properties. - * @property {number} [angle=0] - A number specifying the angle of the body, in radians. - * @property {Phaser.Types.Math.Vector2Like[]} [vertices=null] - An array of `Vector` objects that specify the convex hull of the rigid body. These should be provided about the origin `(0, 0)`. - * @property {Phaser.Types.Math.Vector2Like} [position] - A `Vector` that specifies the current world-space position of the body. - * @property {Phaser.Types.Math.Vector2Like} [force] - A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. - * @property {number} [torque=0] - A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. - * @property {boolean} [isSensor=false] - A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. - * @property {boolean} [isStatic=false] - A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. - * @property {number} [sleepThreshold=60] - A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). - * @property {number} [density=0.001] - 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 {number} [restitution=0] - A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`. - * @property {number} [friction=0.1] - 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. - * @property {number} [frictionStatic=0.5] - A `Number` that defines the static friction of the body (in the Coulomb friction model). A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. - * @property {number} [frictionAir=0.01] - A `Number` that defines the air friction of the body (air resistance). A value of `0` means the body will never slow as it moves through space. The higher the value, the faster a body slows when moving through space. - * @property {Phaser.Types.Physics.Matter.MatterCollisionFilter} [collisionFilter] - An `Object` that specifies the collision filtering properties of this body. - * @property {number} [slop=0.05] - A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. Avoid changing this value unless you understand the purpose of `slop` in physics engines. The default should generally suffice, although very large bodies may require larger values for stable stacking. - * @property {number} [timeScale=1] - A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - * @property {(number|number[]|Phaser.Types.Physics.Matter.MatterChamferConfig)} [chamfer=null] - A number, or array of numbers, to chamfer the vertices of the body, or a full Chamfer configuration object. - * @property {number} [circleRadius=0] - The radius of this body if a circle. - * @property {number} [mass=0] - A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). - * @property {number} [inverseMass=0] - A `Number` that defines the inverse mass of the body (`1 / mass`). If you modify this value, you must also modify the `body.mass` property. - * @property {Phaser.Types.Math.Vector2Like} [scale] - A `Vector` that specifies the initial scale of the body. - * @property {Phaser.Types.Math.Vector2Like} [gravityScale] - A `Vector` that scales the influence of World gravity when applied to this body. - * @property {boolean} [ignoreGravity=false] - A boolean that toggles if this body should ignore world gravity or not. - * @property {boolean} [ignorePointer=false] - A boolean that toggles if this body should ignore pointer / mouse constraints or not. - * @property {Phaser.Types.Physics.Matter.MatterBodyRenderConfig} [render] - The Debug Render configuration object for this body. - * @property {function} [onCollideCallback] - A callback that is invoked when this Body starts colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * @property {function} [onCollideEndCallback] - A callback that is invoked when this Body stops colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * @property {function} [onCollideActiveCallback] - A callback that is invoked for the duration that this Body is colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * @property {any} [onCollideWith] - A collision callback dictionary used by the `Body.setOnCollideWith` function. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterBodyConfig + * @since 3.22.0 + * + * @property {string} [label='Body'] - An arbitrary string-based name to help identify this body. + * @property {MatterJS.BodyType[]} [parts] - An array of bodies that make up this body. The first body in the array must always be a self reference to the current body instance. All bodies in the `parts` array together form a single rigid compound body. + * @property {any} [plugin] - An object reserved for storing plugin-specific properties. + * @property {number} [angle=0] - A number specifying the angle of the body, in radians. + * @property {Phaser.Types.Math.Vector2Like[]} [vertices=null] - An array of `Vector` objects that specify the convex hull of the rigid body. These should be provided about the origin `(0, 0)`. + * @property {Phaser.Types.Math.Vector2Like} [position] - A `Vector` that specifies the current world-space position of the body. + * @property {Phaser.Types.Math.Vector2Like} [force] - A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. + * @property {number} [torque=0] - A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. + * @property {boolean} [isSensor=false] - A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + * @property {boolean} [isStatic=false] - A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. + * @property {number} [sleepThreshold=60] - A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). + * @property {number} [density=0.001] - 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 {number} [restitution=0] - A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`. + * @property {number} [friction=0.1] - 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. + * @property {number} [frictionStatic=0.5] - A `Number` that defines the static friction of the body (in the Coulomb friction model). A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. + * @property {number} [frictionAir=0.01] - A `Number` that defines the air friction of the body (air resistance). A value of `0` means the body will never slow as it moves through space. The higher the value, the faster a body slows when moving through space. + * @property {Phaser.Types.Physics.Matter.MatterCollisionFilter} [collisionFilter] - An `Object` that specifies the collision filtering properties of this body. + * @property {number} [slop=0.05] - A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. Avoid changing this value unless you understand the purpose of `slop` in physics engines. The default should generally suffice, although very large bodies may require larger values for stable stacking. + * @property {number} [timeScale=1] - A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + * @property {(number|number[]|Phaser.Types.Physics.Matter.MatterChamferConfig)} [chamfer=null] - A number, or array of numbers, to chamfer the vertices of the body, or a full Chamfer configuration object. + * @property {number} [circleRadius=0] - The radius of this body if a circle. + * @property {number} [mass=0] - A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). + * @property {number} [inverseMass=0] - A `Number` that defines the inverse mass of the body (`1 / mass`). If you modify this value, you must also modify the `body.mass` property. + * @property {Phaser.Types.Math.Vector2Like} [scale] - A `Vector` that specifies the initial scale of the body. + * @property {Phaser.Types.Math.Vector2Like} [gravityScale] - A `Vector` that scales the influence of World gravity when applied to this body. + * @property {boolean} [ignoreGravity=false] - A boolean that toggles if this body should ignore world gravity or not. + * @property {boolean} [ignorePointer=false] - A boolean that toggles if this body should ignore pointer / mouse constraints or not. + * @property {Phaser.Types.Physics.Matter.MatterBodyRenderConfig} [render] - The Debug Render configuration object for this body. + * @property {function} [onCollideCallback] - A callback that is invoked when this Body starts colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * @property {function} [onCollideEndCallback] - A callback that is invoked when this Body stops colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * @property {function} [onCollideActiveCallback] - A callback that is invoked for the duration that this Body is colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * @property {any} [onCollideWith] - A collision callback dictionary used by the `Body.setOnCollideWith` function. + */ diff --git a/src/physics/matter-js/typedefs/MatterBodyRenderConfig.js b/src/physics/matter-js/typedefs/MatterBodyRenderConfig.js index 204ec6bbc..5fdef9e76 100644 --- a/src/physics/matter-js/typedefs/MatterBodyRenderConfig.js +++ b/src/physics/matter-js/typedefs/MatterBodyRenderConfig.js @@ -1,15 +1,15 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterBodyRenderConfig - * @since 3.22.0 - * - * @property {boolean} [visible=true] - Should this body be rendered by the Debug Renderer? - * @property {number} [opacity=1] - The opacity of the body and all parts within it. - * @property {number} [fillColor] - The color value of the fill when rendering this body. - * @property {number} [fillOpacity] - The opacity of the fill when rendering this body, a value between 0 and 1. - * @property {number} [lineColor] - The color value of the line stroke when rendering this body. - * @property {number} [lineOpacity] - The opacity of the line when rendering this body, a value between 0 and 1. - * @property {number} [lineThickness] - If rendering lines, the thickness of the line. - * @property {object} [sprite] - Controls the offset between the body and the parent Game Object, if it has one. - * @property {number} [sprite.xOffset=0] - The horizontal offset between the body and the parent Game Object texture, if it has one. - * @property {number} [sprite.yOffset=0] - The vertical offset between the body and the parent Game Object texture, if it has one. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterBodyRenderConfig + * @since 3.22.0 + * + * @property {boolean} [visible=true] - Should this body be rendered by the Debug Renderer? + * @property {number} [opacity=1] - The opacity of the body and all parts within it. + * @property {number} [fillColor] - The color value of the fill when rendering this body. + * @property {number} [fillOpacity] - The opacity of the fill when rendering this body, a value between 0 and 1. + * @property {number} [lineColor] - The color value of the line stroke when rendering this body. + * @property {number} [lineOpacity] - The opacity of the line when rendering this body, a value between 0 and 1. + * @property {number} [lineThickness] - If rendering lines, the thickness of the line. + * @property {object} [sprite] - Controls the offset between the body and the parent Game Object, if it has one. + * @property {number} [sprite.xOffset=0] - The horizontal offset between the body and the parent Game Object texture, if it has one. + * @property {number} [sprite.yOffset=0] - The vertical offset between the body and the parent Game Object texture, if it has one. + */ diff --git a/src/physics/matter-js/typedefs/MatterChamferConfig.js b/src/physics/matter-js/typedefs/MatterChamferConfig.js index f9869b4d7..173441251 100644 --- a/src/physics/matter-js/typedefs/MatterChamferConfig.js +++ b/src/physics/matter-js/typedefs/MatterChamferConfig.js @@ -1,9 +1,9 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterChamferConfig - * @since 3.22.0 - * - * @property {(number|number[])} [radius=8] - A single number, or an array, to specify the radius for each vertex. - * @property {number} [quality=-1] - The quality of the chamfering. -1 means 'auto'. - * @property {number} [qualityMin=2] - The minimum quality of the chamfering. The higher this value, the more vertices are created. - * @property {number} [qualityMax=14] - The maximum quality of the chamfering. The higher this value, the more vertices are created. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterChamferConfig + * @since 3.22.0 + * + * @property {(number|number[])} [radius=8] - A single number, or an array, to specify the radius for each vertex. + * @property {number} [quality=-1] - The quality of the chamfering. -1 means 'auto'. + * @property {number} [qualityMin=2] - The minimum quality of the chamfering. The higher this value, the more vertices are created. + * @property {number} [qualityMax=14] - The maximum quality of the chamfering. The higher this value, the more vertices are created. + */ diff --git a/src/physics/matter-js/typedefs/MatterCollisionData.js b/src/physics/matter-js/typedefs/MatterCollisionData.js index 96e6d38f4..0358316b4 100644 --- a/src/physics/matter-js/typedefs/MatterCollisionData.js +++ b/src/physics/matter-js/typedefs/MatterCollisionData.js @@ -1,22 +1,22 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterCollisionData - * @since 3.22.0 - * - * @property {boolean} collided - Have the pair collided or not? - * @property {MatterJS.BodyType} bodyA - A reference to the first body involved in the collision. - * @property {MatterJS.BodyType} bodyB - A reference to the second body involved in the collision. - * @property {MatterJS.BodyType} axisBody - A reference to the dominant axis body. - * @property {number} axisNumber - The index of the dominant collision axis vector (edge normal) - * @property {number} depth - The depth of the collision on the minimum overlap. - * @property {MatterJS.BodyType} parentA - A reference to the parent of Body A, or to Body A itself if it has no parent. - * @property {MatterJS.BodyType} parentB - A reference to the parent of Body B, or to Body B itself if it has no parent. - * @property {MatterJS.Vector} normal - The collision normal, facing away from Body A. - * @property {MatterJS.Vector} tangent - The tangent of the collision normal. - * @property {MatterJS.Vector} penetration - The penetration distances between the two bodies. - * @property {MatterJS.Vector[]} supports - An array of support points, either exactly one or two points. - * @property {number} inverseMass - The resulting inverse mass from the collision. - * @property {number} friction - The resulting friction from the collision. - * @property {number} frictionStatic - The resulting static friction from the collision. - * @property {number} restitution - The resulting restitution from the collision. - * @property {number} slop - The resulting slop from the collision. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterCollisionData + * @since 3.22.0 + * + * @property {boolean} collided - Have the pair collided or not? + * @property {MatterJS.BodyType} bodyA - A reference to the first body involved in the collision. + * @property {MatterJS.BodyType} bodyB - A reference to the second body involved in the collision. + * @property {MatterJS.BodyType} axisBody - A reference to the dominant axis body. + * @property {number} axisNumber - The index of the dominant collision axis vector (edge normal) + * @property {number} depth - The depth of the collision on the minimum overlap. + * @property {MatterJS.BodyType} parentA - A reference to the parent of Body A, or to Body A itself if it has no parent. + * @property {MatterJS.BodyType} parentB - A reference to the parent of Body B, or to Body B itself if it has no parent. + * @property {MatterJS.Vector} normal - The collision normal, facing away from Body A. + * @property {MatterJS.Vector} tangent - The tangent of the collision normal. + * @property {MatterJS.Vector} penetration - The penetration distances between the two bodies. + * @property {MatterJS.Vector[]} supports - An array of support points, either exactly one or two points. + * @property {number} inverseMass - The resulting inverse mass from the collision. + * @property {number} friction - The resulting friction from the collision. + * @property {number} frictionStatic - The resulting static friction from the collision. + * @property {number} restitution - The resulting restitution from the collision. + * @property {number} slop - The resulting slop from the collision. + */ diff --git a/src/physics/matter-js/typedefs/MatterCollisionFilter.js b/src/physics/matter-js/typedefs/MatterCollisionFilter.js index a966159c5..1b368dc12 100644 --- a/src/physics/matter-js/typedefs/MatterCollisionFilter.js +++ b/src/physics/matter-js/typedefs/MatterCollisionFilter.js @@ -1,29 +1,29 @@ -/** - * An `Object` that specifies the collision filtering properties of this body. - * - * Collisions between two bodies will obey the following rules: - * - If the two bodies have the same non-zero value of `collisionFilter.group`, - * they will always collide if the value is positive, and they will never collide - * if the value is negative. - * - If the two bodies have different values of `collisionFilter.group` or if one - * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: - * - * Each body belongs to a collision category, given by `collisionFilter.category`. This - * value is used as a bit field and the category should have only one bit set, meaning that - * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 - * different collision categories available. - * - * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies - * the categories it collides with (the value is the bitwise AND value of all these categories). - * - * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's - * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` - * are both true. - * - * @typedef {object} Phaser.Types.Physics.Matter.MatterCollisionFilter - * @since 3.22.0 - * - * @property {number} [category=0x0001] - A bit field that specifies the collision category this body belongs to. The category value should have only one bit set, for example `0x0001`. This means there are up to 32 unique collision categories available. - * @property {number} [mask=0xFFFFFFFF] - A bit mask that specifies the collision categories this body may collide with. - * @property {number} [group=0] - An Integer `Number`, that specifies the collision group this body belongs to. - */ +/** + * An `Object` that specifies the collision filtering properties of this body. + * + * Collisions between two bodies will obey the following rules: + * - If the two bodies have the same non-zero value of `collisionFilter.group`, + * they will always collide if the value is positive, and they will never collide + * if the value is negative. + * - If the two bodies have different values of `collisionFilter.group` or if one + * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: + * + * Each body belongs to a collision category, given by `collisionFilter.category`. This + * value is used as a bit field and the category should have only one bit set, meaning that + * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 + * different collision categories available. + * + * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies + * the categories it collides with (the value is the bitwise AND value of all these categories). + * + * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's + * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` + * are both true. + * + * @typedef {object} Phaser.Types.Physics.Matter.MatterCollisionFilter + * @since 3.22.0 + * + * @property {number} [category=0x0001] - A bit field that specifies the collision category this body belongs to. The category value should have only one bit set, for example `0x0001`. This means there are up to 32 unique collision categories available. + * @property {number} [mask=0xFFFFFFFF] - A bit mask that specifies the collision categories this body may collide with. + * @property {number} [group=0] - An Integer `Number`, that specifies the collision group this body belongs to. + */ diff --git a/src/physics/matter-js/typedefs/MatterCollisionPair.js b/src/physics/matter-js/typedefs/MatterCollisionPair.js index 7b46e7555..caaa02ef0 100644 --- a/src/physics/matter-js/typedefs/MatterCollisionPair.js +++ b/src/physics/matter-js/typedefs/MatterCollisionPair.js @@ -1,21 +1,21 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterCollisionPair - * @since 3.22.0 - * - * @property {string} id - The unique auto-generated collision pair id. A combination of the body A and B IDs. - * @property {MatterJS.BodyType} bodyA - A reference to the first body involved in the collision. - * @property {MatterJS.BodyType} bodyB - A reference to the second body involved in the collision. - * @property {MatterJS.Vector[]} activeContacts - An array containing all of the active contacts between bodies A and B. - * @property {number} separation - The amount of separation that occured between bodies A and B. - * @property {boolean} isActive - Is the collision still active or not? - * @property {boolean} confirmedActive - Has Matter determined the collision are being active yet? - * @property {boolean} isSensor - Is either body A or B a sensor? - * @property {number} timeCreated - The timestamp when the collision pair was created. - * @property {number} timeUpdated - The timestamp when the collision pair was most recently updated. - * @property {Phaser.Types.Physics.Matter.MatterCollisionData} collision - The collision data object. - * @property {number} inverseMass - The resulting inverse mass from the collision. - * @property {number} friction - The resulting friction from the collision. - * @property {number} frictionStatic - The resulting static friction from the collision. - * @property {number} restitution - The resulting restitution from the collision. - * @property {number} slop - The resulting slop from the collision. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterCollisionPair + * @since 3.22.0 + * + * @property {string} id - The unique auto-generated collision pair id. A combination of the body A and B IDs. + * @property {MatterJS.BodyType} bodyA - A reference to the first body involved in the collision. + * @property {MatterJS.BodyType} bodyB - A reference to the second body involved in the collision. + * @property {MatterJS.Vector[]} activeContacts - An array containing all of the active contacts between bodies A and B. + * @property {number} separation - The amount of separation that occured between bodies A and B. + * @property {boolean} isActive - Is the collision still active or not? + * @property {boolean} confirmedActive - Has Matter determined the collision are being active yet? + * @property {boolean} isSensor - Is either body A or B a sensor? + * @property {number} timeCreated - The timestamp when the collision pair was created. + * @property {number} timeUpdated - The timestamp when the collision pair was most recently updated. + * @property {Phaser.Types.Physics.Matter.MatterCollisionData} collision - The collision data object. + * @property {number} inverseMass - The resulting inverse mass from the collision. + * @property {number} friction - The resulting friction from the collision. + * @property {number} frictionStatic - The resulting static friction from the collision. + * @property {number} restitution - The resulting restitution from the collision. + * @property {number} slop - The resulting slop from the collision. + */ diff --git a/src/physics/matter-js/typedefs/MatterConstraintConfig.js b/src/physics/matter-js/typedefs/MatterConstraintConfig.js index 9345dae08..49765d549 100644 --- a/src/physics/matter-js/typedefs/MatterConstraintConfig.js +++ b/src/physics/matter-js/typedefs/MatterConstraintConfig.js @@ -1,18 +1,18 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterConstraintConfig - * @since 3.22.0 - * - * @property {string} [label='Constraint'] - An arbitrary string-based name to help identify this constraint. - * @property {MatterJS.BodyType} [bodyA] - The first possible `Body` that this constraint is attached to. - * @property {MatterJS.BodyType} [bodyB] - The second possible `Body` that this constraint is attached to. - * @property {Phaser.Types.Math.Vector2Like} [pointA] - A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. - * @property {Phaser.Types.Math.Vector2Like} [pointB] - A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. - * @property {number} [stiffness=1] - A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts like a soft spring. - * @property {number} [angularStiffness=0] - A `Number` that specifies the angular stiffness of the constraint. - * @property {number} [angleA=0] - The angleA of the constraint. If bodyA is set, the angle of bodyA is used instead. - * @property {number} [angleB=0] - The angleB of the constraint. If bodyB is set, the angle of bodyB is used instead. - * @property {number} [damping=0] - 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 {number} [length] - A `Number` that specifies the target resting length of the constraint. It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @property {any} [plugin] - An object reserved for storing plugin-specific properties. - * @property {Phaser.Types.Physics.Matter.MatterConstraintRenderConfig} [render] - The Debug Render configuration object for this constraint. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterConstraintConfig + * @since 3.22.0 + * + * @property {string} [label='Constraint'] - An arbitrary string-based name to help identify this constraint. + * @property {MatterJS.BodyType} [bodyA] - The first possible `Body` that this constraint is attached to. + * @property {MatterJS.BodyType} [bodyB] - The second possible `Body` that this constraint is attached to. + * @property {Phaser.Types.Math.Vector2Like} [pointA] - A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. + * @property {Phaser.Types.Math.Vector2Like} [pointB] - A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. + * @property {number} [stiffness=1] - A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts like a soft spring. + * @property {number} [angularStiffness=0] - A `Number` that specifies the angular stiffness of the constraint. + * @property {number} [angleA=0] - The angleA of the constraint. If bodyA is set, the angle of bodyA is used instead. + * @property {number} [angleB=0] - The angleB of the constraint. If bodyB is set, the angle of bodyB is used instead. + * @property {number} [damping=0] - 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 {number} [length] - A `Number` that specifies the target resting length of the constraint. It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @property {any} [plugin] - An object reserved for storing plugin-specific properties. + * @property {Phaser.Types.Physics.Matter.MatterConstraintRenderConfig} [render] - The Debug Render configuration object for this constraint. + */ diff --git a/src/physics/matter-js/typedefs/MatterConstraintRenderConfig.js b/src/physics/matter-js/typedefs/MatterConstraintRenderConfig.js index a3c89f007..baaa733d0 100644 --- a/src/physics/matter-js/typedefs/MatterConstraintRenderConfig.js +++ b/src/physics/matter-js/typedefs/MatterConstraintRenderConfig.js @@ -1,13 +1,13 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterConstraintRenderConfig - * @since 3.22.0 - * - * @property {boolean} [visible=true] - Should this constraint be rendered by the Debug Renderer? - * @property {boolean} [anchors=true] - If this constraint has anchors, should they be rendered? Pin constraints never have anchors. - * @property {number} [lineColor] - The color value of the line stroke when rendering this constraint. - * @property {number} [lineOpacity] - The opacity of the line when rendering this constraint, a value between 0 and 1. - * @property {number} [lineThickness] - If rendering lines, the thickness of the line. - * @property {number} [pinSize=4] - The size of the circles drawn when rendering pin constraints. - * @property {number} [anchorSize=4] - The size of the circles drawn as the constraint anchors. - * @property {number} [anchorColor=0xefefef] - The color value of constraint anchors. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterConstraintRenderConfig + * @since 3.22.0 + * + * @property {boolean} [visible=true] - Should this constraint be rendered by the Debug Renderer? + * @property {boolean} [anchors=true] - If this constraint has anchors, should they be rendered? Pin constraints never have anchors. + * @property {number} [lineColor] - The color value of the line stroke when rendering this constraint. + * @property {number} [lineOpacity] - The opacity of the line when rendering this constraint, a value between 0 and 1. + * @property {number} [lineThickness] - If rendering lines, the thickness of the line. + * @property {number} [pinSize=4] - The size of the circles drawn when rendering pin constraints. + * @property {number} [anchorSize=4] - The size of the circles drawn as the constraint anchors. + * @property {number} [anchorColor=0xefefef] - The color value of constraint anchors. + */ diff --git a/src/physics/matter-js/typedefs/MatterDebugConfig.js b/src/physics/matter-js/typedefs/MatterDebugConfig.js index 989f916ed..c038d51fc 100644 --- a/src/physics/matter-js/typedefs/MatterDebugConfig.js +++ b/src/physics/matter-js/typedefs/MatterDebugConfig.js @@ -1,51 +1,51 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterDebugConfig - * @since 3.22.0 - * - * @property {boolean} [showAxes=false] - Render all of the body axes? - * @property {boolean} [showAngleIndicator=false] - Render just a single body axis? - * @property {boolean} [angleColor=0xe81153] - The color of the body angle / axes lines. - * @property {boolean} [showBroadphase=false] - Render the broadphase grid? - * @property {boolean} [broadphaseColor=0xffb400] - The color of the broadphase grid. - * @property {boolean} [showBounds=false] - Render the bounds of the bodies in the world? - * @property {boolean} [boundsColor=0xffffff] - The color of the body bounds. - * @property {boolean} [showVelocity=false] - Render the velocity of the bodies in the world? - * @property {boolean} [velocityColor=0x00aeef] - The color of the body velocity line. - * @property {boolean} [showCollisions=false] - Render the collision points and normals for colliding pairs. - * @property {boolean} [collisionColor=0xf5950c] - The color of the collision points. - * @property {boolean} [showSeparation=false] - Render lines showing the separation between bodies. - * @property {boolean} [separationColor=0xffa500] - The color of the body separation line. - * @property {boolean} [showBody=true] - Render the dynamic bodies in the world to the Graphics object? - * @property {boolean} [showStaticBody=true] - Render the static bodies in the world to the Graphics object? - * @property {boolean} [showInternalEdges=false] - When rendering bodies, render the internal edges as well? - * @property {boolean} [renderFill=false] - Render the bodies using a fill color. - * @property {boolean} [renderLine=true] - Render the bodies using a line stroke. - * @property {number} [fillColor=0x106909] - The color value of the fill when rendering dynamic bodies. - * @property {number} [fillOpacity=1] - The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. - * @property {number} [lineColor=0x28de19] - The color value of the line stroke when rendering dynamic bodies. - * @property {number} [lineOpacity=1] - The opacity of the line when rendering dynamic bodies, a value between 0 and 1. - * @property {number} [lineThickness=1] - If rendering lines, the thickness of the line. - * @property {number} [staticFillColor=0x0d177b] - The color value of the fill when rendering static bodies. - * @property {number} [staticLineColor=0x1327e4] - The color value of the line stroke when rendering static bodies. - * @property {boolean} [showSleeping=false] - Render any sleeping bodies (dynamic or static) in the world to the Graphics object? - * @property {number} [staticBodySleepOpacity=0.7] - The amount to multiply the opacity of sleeping static bodies by. - * @property {number} [sleepFillColor=0x464646] - The color value of the fill when rendering sleeping dynamic bodies. - * @property {number} [sleepLineColor=0x999a99] - The color value of the line stroke when rendering sleeping dynamic bodies. - * @property {boolean} [showSensors=true] - Render bodies or body parts that are flagged as being a sensor? - * @property {number} [sensorFillColor=0x0d177b] - The fill color when rendering body sensors. - * @property {number} [sensorLineColor=0x1327e4] - The line color when rendering body sensors. - * @property {boolean} [showPositions=true] - Render the position of non-static bodies? - * @property {number} [positionSize=4] - The size of the rectangle drawn when rendering the body position. - * @property {number} [positionColor=0xe042da] - The color value of the rectangle drawn when rendering the body position. - * @property {boolean} [showJoint=true] - Render all world constraints to the Graphics object? - * @property {number} [jointColor=0xe0e042] - The color value of joints when `showJoint` is set. - * @property {number} [jointLineOpacity=1] - The line opacity when rendering joints, a value between 0 and 1. - * @property {number} [jointLineThickness=2] - The line thickness when rendering joints. - * @property {number} [pinSize=4] - The size of the circles drawn when rendering pin constraints. - * @property {number} [pinColor=0x42e0e0] - The color value of the circles drawn when rendering pin constraints. - * @property {number} [springColor=0xe042e0] - The color value of spring constraints. - * @property {number} [anchorColor=0xefefef] - The color value of constraint anchors. - * @property {number} [anchorSize=4] - The size of the circles drawn as the constraint anchors. - * @property {boolean} [showConvexHulls=false] - When rendering polygon bodies, render the convex hull as well? - * @property {number} [hullColor=0xd703d0] - The color value of hulls when `showConvexHulls` is set. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterDebugConfig + * @since 3.22.0 + * + * @property {boolean} [showAxes=false] - Render all of the body axes? + * @property {boolean} [showAngleIndicator=false] - Render just a single body axis? + * @property {boolean} [angleColor=0xe81153] - The color of the body angle / axes lines. + * @property {boolean} [showBroadphase=false] - Render the broadphase grid? + * @property {boolean} [broadphaseColor=0xffb400] - The color of the broadphase grid. + * @property {boolean} [showBounds=false] - Render the bounds of the bodies in the world? + * @property {boolean} [boundsColor=0xffffff] - The color of the body bounds. + * @property {boolean} [showVelocity=false] - Render the velocity of the bodies in the world? + * @property {boolean} [velocityColor=0x00aeef] - The color of the body velocity line. + * @property {boolean} [showCollisions=false] - Render the collision points and normals for colliding pairs. + * @property {boolean} [collisionColor=0xf5950c] - The color of the collision points. + * @property {boolean} [showSeparation=false] - Render lines showing the separation between bodies. + * @property {boolean} [separationColor=0xffa500] - The color of the body separation line. + * @property {boolean} [showBody=true] - Render the dynamic bodies in the world to the Graphics object? + * @property {boolean} [showStaticBody=true] - Render the static bodies in the world to the Graphics object? + * @property {boolean} [showInternalEdges=false] - When rendering bodies, render the internal edges as well? + * @property {boolean} [renderFill=false] - Render the bodies using a fill color. + * @property {boolean} [renderLine=true] - Render the bodies using a line stroke. + * @property {number} [fillColor=0x106909] - The color value of the fill when rendering dynamic bodies. + * @property {number} [fillOpacity=1] - The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. + * @property {number} [lineColor=0x28de19] - The color value of the line stroke when rendering dynamic bodies. + * @property {number} [lineOpacity=1] - The opacity of the line when rendering dynamic bodies, a value between 0 and 1. + * @property {number} [lineThickness=1] - If rendering lines, the thickness of the line. + * @property {number} [staticFillColor=0x0d177b] - The color value of the fill when rendering static bodies. + * @property {number} [staticLineColor=0x1327e4] - The color value of the line stroke when rendering static bodies. + * @property {boolean} [showSleeping=false] - Render any sleeping bodies (dynamic or static) in the world to the Graphics object? + * @property {number} [staticBodySleepOpacity=0.7] - The amount to multiply the opacity of sleeping static bodies by. + * @property {number} [sleepFillColor=0x464646] - The color value of the fill when rendering sleeping dynamic bodies. + * @property {number} [sleepLineColor=0x999a99] - The color value of the line stroke when rendering sleeping dynamic bodies. + * @property {boolean} [showSensors=true] - Render bodies or body parts that are flagged as being a sensor? + * @property {number} [sensorFillColor=0x0d177b] - The fill color when rendering body sensors. + * @property {number} [sensorLineColor=0x1327e4] - The line color when rendering body sensors. + * @property {boolean} [showPositions=true] - Render the position of non-static bodies? + * @property {number} [positionSize=4] - The size of the rectangle drawn when rendering the body position. + * @property {number} [positionColor=0xe042da] - The color value of the rectangle drawn when rendering the body position. + * @property {boolean} [showJoint=true] - Render all world constraints to the Graphics object? + * @property {number} [jointColor=0xe0e042] - The color value of joints when `showJoint` is set. + * @property {number} [jointLineOpacity=1] - The line opacity when rendering joints, a value between 0 and 1. + * @property {number} [jointLineThickness=2] - The line thickness when rendering joints. + * @property {number} [pinSize=4] - The size of the circles drawn when rendering pin constraints. + * @property {number} [pinColor=0x42e0e0] - The color value of the circles drawn when rendering pin constraints. + * @property {number} [springColor=0xe042e0] - The color value of spring constraints. + * @property {number} [anchorColor=0xefefef] - The color value of constraint anchors. + * @property {number} [anchorSize=4] - The size of the circles drawn as the constraint anchors. + * @property {boolean} [showConvexHulls=false] - When rendering polygon bodies, render the convex hull as well? + * @property {number} [hullColor=0xd703d0] - The color value of hulls when `showConvexHulls` is set. + */ diff --git a/src/physics/matter-js/typedefs/MatterSetBodyConfig.js b/src/physics/matter-js/typedefs/MatterSetBodyConfig.js index 69f1df972..e1f876893 100644 --- a/src/physics/matter-js/typedefs/MatterSetBodyConfig.js +++ b/src/physics/matter-js/typedefs/MatterSetBodyConfig.js @@ -1,19 +1,19 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterSetBodyConfig - * @since 3.22.0 - * - * @property {string} [type='rectangle'] - The shape type. Either `rectangle`, `circle`, `trapezoid`, `polygon`, `fromVertices`, `fromVerts` or `fromPhysicsEditor`. - * @property {number} [x] - The horizontal world position to place the body at. - * @property {number} [y] - The vertical world position to place the body at. - * @property {number} [width] - The width of the body. - * @property {number} [height] - The height of the body. - * @property {number} [radius] - The radius of the body. Used by `circle` and `polygon` shapes. - * @property {number} [maxSides=25] - The max sizes of the body. Used by the `circle` shape. - * @property {number} [slope=0.5] - Used by the `trapezoid` shape. The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @property {number} [sides=5] - Used by the `polygon` shape. The number of sides the polygon will have. - * @property {(string|array)} [verts] - Used by the `fromVerts` shape. The vertices data. Either a path string or an array of vertices. - * @property {boolean} [flagInternal=false] - Used by the `fromVerts` shape. Flag internal edges (coincident part edges) - * @property {number} [removeCollinear=0.01] - Used by the `fromVerts` shape. Whether Matter.js will discard collinear edges (to improve performance). - * @property {number} [minimumArea=10] - Used by the `fromVerts` shape. During decomposition discard parts that have an area less than this. - * @property {boolean} [addToWorld=true] - Should the new body be automatically added to the world? - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterSetBodyConfig + * @since 3.22.0 + * + * @property {string} [type='rectangle'] - The shape type. Either `rectangle`, `circle`, `trapezoid`, `polygon`, `fromVertices`, `fromVerts` or `fromPhysicsEditor`. + * @property {number} [x] - The horizontal world position to place the body at. + * @property {number} [y] - The vertical world position to place the body at. + * @property {number} [width] - The width of the body. + * @property {number} [height] - The height of the body. + * @property {number} [radius] - The radius of the body. Used by `circle` and `polygon` shapes. + * @property {number} [maxSides=25] - The max sizes of the body. Used by the `circle` shape. + * @property {number} [slope=0.5] - Used by the `trapezoid` shape. The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @property {number} [sides=5] - Used by the `polygon` shape. The number of sides the polygon will have. + * @property {(string|array)} [verts] - Used by the `fromVerts` shape. The vertices data. Either a path string or an array of vertices. + * @property {boolean} [flagInternal=false] - Used by the `fromVerts` shape. Flag internal edges (coincident part edges) + * @property {number} [removeCollinear=0.01] - Used by the `fromVerts` shape. Whether Matter.js will discard collinear edges (to improve performance). + * @property {number} [minimumArea=10] - Used by the `fromVerts` shape. During decomposition discard parts that have an area less than this. + * @property {boolean} [addToWorld=true] - Should the new body be automatically added to the world? + */ diff --git a/src/physics/matter-js/typedefs/MatterTileOptions.js b/src/physics/matter-js/typedefs/MatterTileOptions.js index 9dbe7838a..ae2bed278 100644 --- a/src/physics/matter-js/typedefs/MatterTileOptions.js +++ b/src/physics/matter-js/typedefs/MatterTileOptions.js @@ -1,8 +1,8 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterTileOptions - * @since 3.0.0 - * - * @property {MatterJS.BodyType} [body=null] - An existing Matter body to be used instead of creating a new one. - * @property {boolean} [isStatic=true] - Whether or not the newly created body should be made static. This defaults to true since typically tiles should not be moved. - * @property {boolean} [addToWorld=true] - Whether or not to add the newly created body (or existing body if options.body is used) to the Matter world. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterTileOptions + * @since 3.0.0 + * + * @property {MatterJS.BodyType} [body=null] - An existing Matter body to be used instead of creating a new one. + * @property {boolean} [isStatic=true] - Whether or not the newly created body should be made static. This defaults to true since typically tiles should not be moved. + * @property {boolean} [addToWorld=true] - Whether or not to add the newly created body (or existing body if options.body is used) to the Matter world. + */ diff --git a/src/physics/matter-js/typedefs/MatterWorldConfig.js b/src/physics/matter-js/typedefs/MatterWorldConfig.js index c417b8bd1..40221f2f9 100644 --- a/src/physics/matter-js/typedefs/MatterWorldConfig.js +++ b/src/physics/matter-js/typedefs/MatterWorldConfig.js @@ -1,36 +1,36 @@ -/** - * @typedef {object} Phaser.Types.Physics.Matter.MatterWorldConfig - * @since 3.0.0 - * - * @property {(Phaser.Types.Math.Vector2Like|boolean)} [gravity] - Sets {@link Phaser.Physics.Matter.World#gravity}. If `false` Gravity will be set to zero. - * @property {(object|boolean)} [setBounds] - Should the world have bounds enabled by default? - * @property {number} [setBounds.x=0] - The x coordinate of the world bounds. - * @property {number} [setBounds.y=0] - The y coordinate of the world bounds. - * @property {number} [setBounds.width] - The width of the world bounds. - * @property {number} [setBounds.height] - The height of the world bounds. - * @property {number} [setBounds.thickness=64] - The thickness of the walls of the world bounds. - * @property {boolean} [setBounds.left=true] - Should the left-side world bounds wall be created? - * @property {boolean} [setBounds.right=true] - Should the right-side world bounds wall be created? - * @property {boolean} [setBounds.top=true] - Should the top world bounds wall be created? - * @property {boolean} [setBounds.bottom=true] - Should the bottom world bounds wall be created? - * @property {number} [positionIterations=6] - The number of position iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. - * @property {number} [velocityIterations=4] - The number of velocity iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. - * @property {number} [constraintIterations=2] - The number of constraint iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. - * @property {boolean} [enableSleeping=false] - A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. Sleeping can improve stability and performance, but often at the expense of accuracy. - * @property {number} [timing.timestamp=0] - A `Number` that specifies the current simulation-time in milliseconds starting from `0`. It is incremented on every `Engine.update` by the given `delta` argument. - * @property {number} [timing.timeScale=1] - A `Number` that specifies the global scaling factor of time for all bodies. A value of `0` freezes the simulation. A value of `0.1` gives a slow-motion effect. A value of `1.2` gives a speed-up effect. - * @property {boolean} [plugins.attractors=false] - Should the Matter Attractor Plugin be enabled? An attractors plugin that makes it easy to apply continual forces on bodies. It's possible to simulate effects such as wind, gravity and magnetism. - * @property {boolean} [plugins.wrap=false] - Should the Matter Wrap Plugin be enabled? A coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, while maintaining its velocity. - * @property {boolean} [plugins.collisionevents=true] - Should the Matter Collision Events Plugin be enabled? - * @property {boolean} [enabled=true] - Toggles if the world is enabled or not. - * @property {number} [correction=1] - An optional Number that specifies the time correction factor to apply to the update. - * @property {function} [getDelta] - This function is called every time the core game loop steps, which is bound to the Request Animation Frame frequency unless otherwise modified. - * @property {boolean} [autoUpdate=true] - Automatically call Engine.update every time the game steps. - * @property {number} [restingThresh=4] - Sets the Resolver resting threshold property. - * @property {number} [restingThreshTangent=6] - Sets the Resolver resting threshold tangent property. - * @property {number} [positionDampen=0.9] - Sets the Resolver position dampen property. - * @property {number} [positionWarming=0.8] - Sets the Resolver position warming property. - * @property {number} [frictionNormalMultiplier=5] - Sets the Resolver friction normal multiplier property. - * @property {(boolean|Phaser.Types.Physics.Matter.MatterDebugConfig)} [debug=false] - Controls the Matter Debug Rendering options. If a boolean it will use the default values, otherwise, specify a Debug Config object. - * @property {Phaser.Types.Physics.Matter.MatterRunnerConfig} [runner] - Sets the Matter Runner options. - */ +/** + * @typedef {object} Phaser.Types.Physics.Matter.MatterWorldConfig + * @since 3.0.0 + * + * @property {(Phaser.Types.Math.Vector2Like|boolean)} [gravity] - Sets {@link Phaser.Physics.Matter.World#gravity}. If `false` Gravity will be set to zero. + * @property {(object|boolean)} [setBounds] - Should the world have bounds enabled by default? + * @property {number} [setBounds.x=0] - The x coordinate of the world bounds. + * @property {number} [setBounds.y=0] - The y coordinate of the world bounds. + * @property {number} [setBounds.width] - The width of the world bounds. + * @property {number} [setBounds.height] - The height of the world bounds. + * @property {number} [setBounds.thickness=64] - The thickness of the walls of the world bounds. + * @property {boolean} [setBounds.left=true] - Should the left-side world bounds wall be created? + * @property {boolean} [setBounds.right=true] - Should the right-side world bounds wall be created? + * @property {boolean} [setBounds.top=true] - Should the top world bounds wall be created? + * @property {boolean} [setBounds.bottom=true] - Should the bottom world bounds wall be created? + * @property {number} [positionIterations=6] - The number of position iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + * @property {number} [velocityIterations=4] - The number of velocity iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + * @property {number} [constraintIterations=2] - The number of constraint iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + * @property {boolean} [enableSleeping=false] - A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. Sleeping can improve stability and performance, but often at the expense of accuracy. + * @property {number} [timing.timestamp=0] - A `Number` that specifies the current simulation-time in milliseconds starting from `0`. It is incremented on every `Engine.update` by the given `delta` argument. + * @property {number} [timing.timeScale=1] - A `Number` that specifies the global scaling factor of time for all bodies. A value of `0` freezes the simulation. A value of `0.1` gives a slow-motion effect. A value of `1.2` gives a speed-up effect. + * @property {boolean} [plugins.attractors=false] - Should the Matter Attractor Plugin be enabled? An attractors plugin that makes it easy to apply continual forces on bodies. It's possible to simulate effects such as wind, gravity and magnetism. + * @property {boolean} [plugins.wrap=false] - Should the Matter Wrap Plugin be enabled? A coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, while maintaining its velocity. + * @property {boolean} [plugins.collisionevents=true] - Should the Matter Collision Events Plugin be enabled? + * @property {boolean} [enabled=true] - Toggles if the world is enabled or not. + * @property {number} [correction=1] - An optional Number that specifies the time correction factor to apply to the update. + * @property {function} [getDelta] - This function is called every time the core game loop steps, which is bound to the Request Animation Frame frequency unless otherwise modified. + * @property {boolean} [autoUpdate=true] - Automatically call Engine.update every time the game steps. + * @property {number} [restingThresh=4] - Sets the Resolver resting threshold property. + * @property {number} [restingThreshTangent=6] - Sets the Resolver resting threshold tangent property. + * @property {number} [positionDampen=0.9] - Sets the Resolver position dampen property. + * @property {number} [positionWarming=0.8] - Sets the Resolver position warming property. + * @property {number} [frictionNormalMultiplier=5] - Sets the Resolver friction normal multiplier property. + * @property {(boolean|Phaser.Types.Physics.Matter.MatterDebugConfig)} [debug=false] - Controls the Matter Debug Rendering options. If a boolean it will use the default values, otherwise, specify a Debug Config object. + * @property {Phaser.Types.Physics.Matter.MatterRunnerConfig} [runner] - Sets the Matter Runner options. + */ diff --git a/src/physics/matter-js/typedefs/index.js b/src/physics/matter-js/typedefs/index.js index ee3bae2e3..4c3428819 100644 --- a/src/physics/matter-js/typedefs/index.js +++ b/src/physics/matter-js/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Physics.Matter - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Physics.Matter + */ diff --git a/src/plugins/BasePlugin.js b/src/plugins/BasePlugin.js index ccb38fedb..d3e6cfcb7 100644 --- a/src/plugins/BasePlugin.js +++ b/src/plugins/BasePlugin.js @@ -1,124 +1,124 @@ -/** -* @author Richard Davey -* @copyright 2020 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} -*/ - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A Global Plugin is installed just once into the Game owned Plugin Manager. - * It can listen for Game events and respond to them. - * - * @class BasePlugin - * @memberof Phaser.Plugins - * @constructor - * @since 3.8.0 - * - * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Plugin Manager. - */ -var BasePlugin = new Class({ - - initialize: - - function BasePlugin (pluginManager) - { - /** - * A handy reference to the Plugin Manager that is responsible for this plugin. - * Can be used as a route to gain access to game systems and events. - * - * @name Phaser.Plugins.BasePlugin#pluginManager - * @type {Phaser.Plugins.PluginManager} - * @protected - * @since 3.8.0 - */ - this.pluginManager = pluginManager; - - /** - * A reference to the Game instance this plugin is running under. - * - * @name Phaser.Plugins.BasePlugin#game - * @type {Phaser.Game} - * @protected - * @since 3.8.0 - */ - this.game = pluginManager.game; - }, - - /** - * The PluginManager calls this method on a Global Plugin when the plugin is first instantiated. - * It will never be called again on this instance. - * In here you can set-up whatever you need for this plugin to run. - * If a plugin is set to automatically start then `BasePlugin.start` will be called immediately after this. - * On a Scene Plugin, this method is never called. Use {@link Phaser.Plugins.ScenePlugin#boot} instead. - * - * @method Phaser.Plugins.BasePlugin#init - * @since 3.8.0 - * - * @param {?any} [data] - A value specified by the user, if any, from the `data` property of the plugin's configuration object (if started at game boot) or passed in the PluginManager's `install` method (if started manually). - */ - init: function () - { - }, - - /** - * The PluginManager calls this method on a Global Plugin when the plugin is started. - * If a plugin is stopped, and then started again, this will get called again. - * Typically called immediately after `BasePlugin.init`. - * On a Scene Plugin, this method is never called. - * - * @method Phaser.Plugins.BasePlugin#start - * @since 3.8.0 - */ - start: function () - { - // 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); - }, - - /** - * The PluginManager calls this method on a Global Plugin when the plugin is stopped. - * The game code has requested that your plugin stop doing whatever it does. - * It is now considered as 'inactive' by the PluginManager. - * Handle that process here (i.e. stop listening for events, etc) - * If the plugin is started again then `BasePlugin.start` will be called again. - * On a Scene Plugin, this method is never called. - * - * @method Phaser.Plugins.BasePlugin#stop - * @since 3.8.0 - */ - stop: function () - { - }, - - /** - * Game instance has been destroyed. - * You must release everything in here, all references, all objects, free it all up. - * - * @method Phaser.Plugins.BasePlugin#destroy - * @since 3.8.0 - */ - destroy: function () - { - this.pluginManager = null; - this.game = null; - this.scene = null; - this.systems = null; - } - -}); - -module.exports = BasePlugin; +/** +* @author Richard Davey +* @copyright 2020 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} +*/ + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A Global Plugin is installed just once into the Game owned Plugin Manager. + * It can listen for Game events and respond to them. + * + * @class BasePlugin + * @memberof Phaser.Plugins + * @constructor + * @since 3.8.0 + * + * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Plugin Manager. + */ +var BasePlugin = new Class({ + + initialize: + + function BasePlugin (pluginManager) + { + /** + * A handy reference to the Plugin Manager that is responsible for this plugin. + * Can be used as a route to gain access to game systems and events. + * + * @name Phaser.Plugins.BasePlugin#pluginManager + * @type {Phaser.Plugins.PluginManager} + * @protected + * @since 3.8.0 + */ + this.pluginManager = pluginManager; + + /** + * A reference to the Game instance this plugin is running under. + * + * @name Phaser.Plugins.BasePlugin#game + * @type {Phaser.Game} + * @protected + * @since 3.8.0 + */ + this.game = pluginManager.game; + }, + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is first instantiated. + * It will never be called again on this instance. + * In here you can set-up whatever you need for this plugin to run. + * If a plugin is set to automatically start then `BasePlugin.start` will be called immediately after this. + * On a Scene Plugin, this method is never called. Use {@link Phaser.Plugins.ScenePlugin#boot} instead. + * + * @method Phaser.Plugins.BasePlugin#init + * @since 3.8.0 + * + * @param {?any} [data] - A value specified by the user, if any, from the `data` property of the plugin's configuration object (if started at game boot) or passed in the PluginManager's `install` method (if started manually). + */ + init: function () + { + }, + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is started. + * If a plugin is stopped, and then started again, this will get called again. + * Typically called immediately after `BasePlugin.init`. + * On a Scene Plugin, this method is never called. + * + * @method Phaser.Plugins.BasePlugin#start + * @since 3.8.0 + */ + start: function () + { + // 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); + }, + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is stopped. + * The game code has requested that your plugin stop doing whatever it does. + * It is now considered as 'inactive' by the PluginManager. + * Handle that process here (i.e. stop listening for events, etc) + * If the plugin is started again then `BasePlugin.start` will be called again. + * On a Scene Plugin, this method is never called. + * + * @method Phaser.Plugins.BasePlugin#stop + * @since 3.8.0 + */ + stop: function () + { + }, + + /** + * Game instance has been destroyed. + * You must release everything in here, all references, all objects, free it all up. + * + * @method Phaser.Plugins.BasePlugin#destroy + * @since 3.8.0 + */ + destroy: function () + { + this.pluginManager = null; + this.game = null; + this.scene = null; + this.systems = null; + } + +}); + +module.exports = BasePlugin; diff --git a/src/plugins/DefaultPlugins.js b/src/plugins/DefaultPlugins.js index 8558c2932..6f17f826c 100644 --- a/src/plugins/DefaultPlugins.js +++ b/src/plugins/DefaultPlugins.js @@ -1,99 +1,99 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Plugins.DefaultPlugins - * - * @property {array} Global - These are the Global Managers that are created by the Phaser.Game instance. - * @property {array} CoreScene - These are the core plugins that are installed into every Scene.Systems instance, no matter what. - * @property {array} DefaultScene - These plugins are created in Scene.Systems in addition to the CoreScenePlugins. - */ - -var DefaultPlugins = { - - /** - * These are the Global Managers that are created by the Phaser.Game instance. - * They are referenced from Scene.Systems so that plugins can use them. - * - * @name Phaser.Plugins.Global - * @type {array} - * @since 3.0.0 - */ - Global: [ - - 'game', - 'anims', - 'cache', - 'plugins', - 'registry', - 'scale', - 'sound', - 'textures' - - ], - - /** - * These are the core plugins that are installed into every Scene.Systems instance, no matter what. - * They are optionally exposed in the Scene as well (see the InjectionMap for details) - * - * They are created in the order in which they appear in this array and EventEmitter is always first. - * - * @name Phaser.Plugins.CoreScene - * @type {array} - * @since 3.0.0 - */ - CoreScene: [ - - 'EventEmitter', - - 'CameraManager', - 'GameObjectCreator', - 'GameObjectFactory', - 'ScenePlugin', - 'DisplayList', - 'UpdateList' - - ], - - /** - * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. - * - * You can elect not to have these plugins by either creating a DefaultPlugins object as part - * of the Game Config, by creating a Plugins object as part of a Scene Config, or by modifying this array - * and building your own bundle. - * - * They are optionally exposed in the Scene as well (see the InjectionMap for details) - * - * They are always created in the order in which they appear in the array. - * - * @name Phaser.Plugins.DefaultScene - * @type {array} - * @since 3.0.0 - */ - DefaultScene: [ - - 'Clock', - 'DataManagerPlugin', - 'InputPlugin', - 'Loader', - 'TweenManager', - 'LightsPlugin' - - ] - -}; - -if (typeof PLUGIN_CAMERA3D) -{ - DefaultPlugins.DefaultScene.push('CameraManager3D'); -} - -if (typeof PLUGIN_FBINSTANT) -{ - DefaultPlugins.Global.push('facebook'); -} - -module.exports = DefaultPlugins; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Plugins.DefaultPlugins + * + * @property {array} Global - These are the Global Managers that are created by the Phaser.Game instance. + * @property {array} CoreScene - These are the core plugins that are installed into every Scene.Systems instance, no matter what. + * @property {array} DefaultScene - These plugins are created in Scene.Systems in addition to the CoreScenePlugins. + */ + +var DefaultPlugins = { + + /** + * These are the Global Managers that are created by the Phaser.Game instance. + * They are referenced from Scene.Systems so that plugins can use them. + * + * @name Phaser.Plugins.Global + * @type {array} + * @since 3.0.0 + */ + Global: [ + + 'game', + 'anims', + 'cache', + 'plugins', + 'registry', + 'scale', + 'sound', + 'textures' + + ], + + /** + * These are the core plugins that are installed into every Scene.Systems instance, no matter what. + * They are optionally exposed in the Scene as well (see the InjectionMap for details) + * + * They are created in the order in which they appear in this array and EventEmitter is always first. + * + * @name Phaser.Plugins.CoreScene + * @type {array} + * @since 3.0.0 + */ + CoreScene: [ + + 'EventEmitter', + + 'CameraManager', + 'GameObjectCreator', + 'GameObjectFactory', + 'ScenePlugin', + 'DisplayList', + 'UpdateList' + + ], + + /** + * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. + * + * You can elect not to have these plugins by either creating a DefaultPlugins object as part + * of the Game Config, by creating a Plugins object as part of a Scene Config, or by modifying this array + * and building your own bundle. + * + * They are optionally exposed in the Scene as well (see the InjectionMap for details) + * + * They are always created in the order in which they appear in the array. + * + * @name Phaser.Plugins.DefaultScene + * @type {array} + * @since 3.0.0 + */ + DefaultScene: [ + + 'Clock', + 'DataManagerPlugin', + 'InputPlugin', + 'Loader', + 'TweenManager', + 'LightsPlugin' + + ] + +}; + +if (typeof PLUGIN_CAMERA3D) +{ + DefaultPlugins.DefaultScene.push('CameraManager3D'); +} + +if (typeof PLUGIN_FBINSTANT) +{ + DefaultPlugins.Global.push('facebook'); +} + +module.exports = DefaultPlugins; diff --git a/src/plugins/PluginCache.js b/src/plugins/PluginCache.js index 7a6b92818..1a09a274b 100644 --- a/src/plugins/PluginCache.js +++ b/src/plugins/PluginCache.js @@ -1,203 +1,203 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Contains the plugins that Phaser uses globally and locally. -// These are the source objects, not instantiated. -var corePlugins = {}; - -// Contains the plugins that the dev has loaded into their game -// These are the source objects, not instantiated. -var customPlugins = {}; - -var PluginCache = {}; - -/** - * @namespace Phaser.Plugins.PluginCache - */ - -/** - * Static method called directly by the Core internal Plugins. - * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) - * Plugin is the object to instantiate to create the plugin - * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) - * - * @method Phaser.Plugins.PluginCache.register - * @since 3.8.0 - * - * @param {string} key - A reference used to get this plugin from the plugin cache. - * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. - * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. - * @param {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin? - */ -PluginCache.register = function (key, plugin, mapping, custom) -{ - if (custom === undefined) { custom = false; } - - corePlugins[key] = { plugin: plugin, mapping: mapping, custom: custom }; -}; - -/** - * Stores a custom plugin in the global plugin cache. - * The key must be unique, within the scope of the cache. - * - * @method Phaser.Plugins.PluginCache.registerCustom - * @since 3.8.0 - * - * @param {string} key - A reference used to get this plugin from the plugin cache. - * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. - * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. - * @param {?any} data - A value to be passed to the plugin's `init` method. - */ -PluginCache.registerCustom = function (key, plugin, mapping, data) -{ - customPlugins[key] = { plugin: plugin, mapping: mapping, data: data }; -}; - -/** - * Checks if the given key is already being used in the core plugin cache. - * - * @method Phaser.Plugins.PluginCache.hasCore - * @since 3.8.0 - * - * @param {string} key - The key to check for. - * - * @return {boolean} `true` if the key is already in use in the core cache, otherwise `false`. - */ -PluginCache.hasCore = function (key) -{ - return corePlugins.hasOwnProperty(key); -}; - -/** - * Checks if the given key is already being used in the custom plugin cache. - * - * @method Phaser.Plugins.PluginCache.hasCustom - * @since 3.8.0 - * - * @param {string} key - The key to check for. - * - * @return {boolean} `true` if the key is already in use in the custom cache, otherwise `false`. - */ -PluginCache.hasCustom = function (key) -{ - return customPlugins.hasOwnProperty(key); -}; - -/** - * 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. - */ -PluginCache.getCore = function (key) -{ - return corePlugins[key]; -}; - -/** - * 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. - */ -PluginCache.getCustom = function (key) -{ - return customPlugins[key]; -}; - -/** - * Returns an object from the custom cache based on the given key that can be instantiated. - * - * @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. - */ -PluginCache.getCustomClass = function (key) -{ - return (customPlugins.hasOwnProperty(key)) ? customPlugins[key].plugin : null; -}; - -/** - * 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. - */ -PluginCache.remove = function (key) -{ - if (corePlugins.hasOwnProperty(key)) - { - delete corePlugins[key]; - } -}; - -/** - * 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. - */ -PluginCache.removeCustom = function (key) -{ - if (customPlugins.hasOwnProperty(key)) - { - delete customPlugins[key]; - } -}; - -/** - * Removes all Core Plugins. - * - * This includes all of the internal system plugins that Phaser needs, like the Input Plugin and Loader Plugin. - * So be sure you only call this if you do not wish to run Phaser again. - * - * @method Phaser.Plugins.PluginCache.destroyCorePlugins - * @since 3.12.0 - */ -PluginCache.destroyCorePlugins = function () -{ - for (var key in corePlugins) - { - if (corePlugins.hasOwnProperty(key)) - { - delete corePlugins[key]; - } - } -}; - -/** - * Removes all Custom Plugins. - * - * @method Phaser.Plugins.PluginCache.destroyCustomPlugins - * @since 3.12.0 - */ -PluginCache.destroyCustomPlugins = function () -{ - for (var key in customPlugins) - { - if (customPlugins.hasOwnProperty(key)) - { - delete customPlugins[key]; - } - } -}; - -module.exports = PluginCache; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Contains the plugins that Phaser uses globally and locally. +// These are the source objects, not instantiated. +var corePlugins = {}; + +// Contains the plugins that the dev has loaded into their game +// These are the source objects, not instantiated. +var customPlugins = {}; + +var PluginCache = {}; + +/** + * @namespace Phaser.Plugins.PluginCache + */ + +/** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * + * @method Phaser.Plugins.PluginCache.register + * @since 3.8.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin? + */ +PluginCache.register = function (key, plugin, mapping, custom) +{ + if (custom === undefined) { custom = false; } + + corePlugins[key] = { plugin: plugin, mapping: mapping, custom: custom }; +}; + +/** + * Stores a custom plugin in the global plugin cache. + * The key must be unique, within the scope of the cache. + * + * @method Phaser.Plugins.PluginCache.registerCustom + * @since 3.8.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param {?any} data - A value to be passed to the plugin's `init` method. + */ +PluginCache.registerCustom = function (key, plugin, mapping, data) +{ + customPlugins[key] = { plugin: plugin, mapping: mapping, data: data }; +}; + +/** + * Checks if the given key is already being used in the core plugin cache. + * + * @method Phaser.Plugins.PluginCache.hasCore + * @since 3.8.0 + * + * @param {string} key - The key to check for. + * + * @return {boolean} `true` if the key is already in use in the core cache, otherwise `false`. + */ +PluginCache.hasCore = function (key) +{ + return corePlugins.hasOwnProperty(key); +}; + +/** + * Checks if the given key is already being used in the custom plugin cache. + * + * @method Phaser.Plugins.PluginCache.hasCustom + * @since 3.8.0 + * + * @param {string} key - The key to check for. + * + * @return {boolean} `true` if the key is already in use in the custom cache, otherwise `false`. + */ +PluginCache.hasCustom = function (key) +{ + return customPlugins.hasOwnProperty(key); +}; + +/** + * 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. + */ +PluginCache.getCore = function (key) +{ + return corePlugins[key]; +}; + +/** + * 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. + */ +PluginCache.getCustom = function (key) +{ + return customPlugins[key]; +}; + +/** + * Returns an object from the custom cache based on the given key that can be instantiated. + * + * @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. + */ +PluginCache.getCustomClass = function (key) +{ + return (customPlugins.hasOwnProperty(key)) ? customPlugins[key].plugin : null; +}; + +/** + * 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. + */ +PluginCache.remove = function (key) +{ + if (corePlugins.hasOwnProperty(key)) + { + delete corePlugins[key]; + } +}; + +/** + * 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. + */ +PluginCache.removeCustom = function (key) +{ + if (customPlugins.hasOwnProperty(key)) + { + delete customPlugins[key]; + } +}; + +/** + * Removes all Core Plugins. + * + * This includes all of the internal system plugins that Phaser needs, like the Input Plugin and Loader Plugin. + * So be sure you only call this if you do not wish to run Phaser again. + * + * @method Phaser.Plugins.PluginCache.destroyCorePlugins + * @since 3.12.0 + */ +PluginCache.destroyCorePlugins = function () +{ + for (var key in corePlugins) + { + if (corePlugins.hasOwnProperty(key)) + { + delete corePlugins[key]; + } + } +}; + +/** + * Removes all Custom Plugins. + * + * @method Phaser.Plugins.PluginCache.destroyCustomPlugins + * @since 3.12.0 + */ +PluginCache.destroyCustomPlugins = function () +{ + for (var key in customPlugins) + { + if (customPlugins.hasOwnProperty(key)) + { + delete customPlugins[key]; + } + } +}; + +module.exports = PluginCache; diff --git a/src/plugins/PluginManager.js b/src/plugins/PluginManager.js index 40d502abc..371b0d21d 100644 --- a/src/plugins/PluginManager.js +++ b/src/plugins/PluginManager.js @@ -1,896 +1,896 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var GameEvents = require('../core/events'); -var EventEmitter = require('eventemitter3'); -var FileTypesManager = require('../loader/FileTypesManager'); -var GameObjectCreator = require('../gameobjects/GameObjectCreator'); -var GameObjectFactory = require('../gameobjects/GameObjectFactory'); -var GetFastValue = require('../utils/object/GetFastValue'); -var PluginCache = require('./PluginCache'); -var Remove = require('../utils/array/Remove'); - -/** - * @classdesc - * The PluginManager is responsible for installing and adding plugins to Phaser. - * - * It is a global system and therefore belongs to the Game instance, not a specific Scene. - * - * It works in conjunction with the PluginCache. Core internal plugins automatically register themselves - * with the Cache, but it's the Plugin Manager that is responsible for injecting them into the Scenes. - * - * There are two types of plugin: - * - * 1. A Global Plugin - * 2. A Scene Plugin - * - * A Global Plugin is a plugin that lives within the Plugin Manager rather than a Scene. You can get - * access to it by calling `PluginManager.get` and providing a key. Any Scene that requests a plugin in - * this way will all get access to the same plugin instance, allowing you to use a single plugin across - * multiple Scenes. - * - * A Scene Plugin is a plugin dedicated to running within a Scene. These are different to Global Plugins - * in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. - * And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene - * Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. - * - * You can add a plugin to Phaser in three different ways: - * - * 1. Preload it - * 2. Include it in your source code and install it via the Game Config - * 3. Include it in your source code and install it within a Scene - * - * For examples of all of these approaches please see the Phaser 3 Examples Repo `plugins` folder. - * - * For information on creating your own plugin please see the Phaser 3 Plugin Template. - * - * @class PluginManager - * @memberof Phaser.Plugins - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - The game instance that owns this Plugin Manager. - */ -var PluginManager = new Class({ - - Extends: EventEmitter, - - initialize: - - function PluginManager (game) - { - EventEmitter.call(this); - - /** - * The game instance that owns this Plugin Manager. - * - * @name Phaser.Plugins.PluginManager#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = game; - - /** - * The global plugins currently running and managed by this Plugin Manager. - * A plugin must have been started at least once in order to appear in this list. - * - * @name Phaser.Plugins.PluginManager#plugins - * @type {Phaser.Types.Plugins.GlobalPlugin[]} - * @since 3.8.0 - */ - this.plugins = []; - - /** - * A list of plugin keys that should be installed into Scenes as well as the Core Plugins. - * - * @name Phaser.Plugins.PluginManager#scenePlugins - * @type {string[]} - * @since 3.8.0 - */ - this.scenePlugins = []; - - /** - * A temporary list of plugins to install when the game has booted. - * - * @name Phaser.Plugins.PluginManager#_pendingGlobal - * @private - * @type {array} - * @since 3.8.0 - */ - this._pendingGlobal = []; - - /** - * A temporary list of scene plugins to install when the game has booted. - * - * @name Phaser.Plugins.PluginManager#_pendingScene - * @private - * @type {array} - * @since 3.8.0 - */ - this._pendingScene = []; - - if (game.isBooted) - { - this.boot(); - } - else - { - game.events.once(GameEvents.BOOT, this.boot, this); - } - }, - - /** - * Run once the game has booted and installs all of the plugins configured in the Game Config. - * - * @method Phaser.Plugins.PluginManager#boot - * @protected - * @since 3.0.0 - */ - boot: function () - { - var i; - var entry; - var key; - var plugin; - var start; - var mapping; - var data; - var config = this.game.config; - - // Any plugins to install? - var list = config.installGlobalPlugins; - - // Any plugins added outside of the game config, but before the game booted? - list = list.concat(this._pendingGlobal); - - for (i = 0; i < list.length; i++) - { - entry = list[i]; - - // { key: 'TestPlugin', plugin: TestPlugin, start: true, mapping: 'test', data: { msg: 'The plugin is alive' } } - - key = GetFastValue(entry, 'key', null); - plugin = GetFastValue(entry, 'plugin', null); - start = GetFastValue(entry, 'start', false); - mapping = GetFastValue(entry, 'mapping', null); - data = GetFastValue(entry, 'data', null); - - if (key) - { - if (plugin) - { - this.install(key, plugin, start, mapping, data); - } - else - { - console.warn('Missing `plugin` for key: ' + key); - } - - } - } - - // Any scene plugins to install? - list = config.installScenePlugins; - - // Any plugins added outside of the game config, but before the game booted? - list = list.concat(this._pendingScene); - - for (i = 0; i < list.length; i++) - { - entry = list[i]; - - // { key: 'moveSpritePlugin', plugin: MoveSpritePlugin, , mapping: 'move' } - - key = GetFastValue(entry, 'key', null); - plugin = GetFastValue(entry, 'plugin', null); - mapping = GetFastValue(entry, 'mapping', null); - - if (key) - { - if (plugin) - { - this.installScenePlugin(key, plugin, mapping); - } - else - { - console.warn('Missing `plugin` for key: ' + key); - } - } - } - - this._pendingGlobal = []; - this._pendingScene = []; - - this.game.events.once(GameEvents.DESTROY, this.destroy, this); - }, - - /** - * Called by the Scene Systems class. Tells the plugin manager to install all Scene plugins into it. - * - * First it will install global references, i.e. references from the Game systems into the Scene Systems (and Scene if mapped.) - * Then it will install Core Scene Plugins followed by Scene Plugins registered with the PluginManager. - * Finally it will install any references to Global Plugins that have a Scene mapping property into the Scene itself. - * - * @method Phaser.Plugins.PluginManager#addToScene - * @protected - * @since 3.8.0 - * - * @param {Phaser.Scenes.Systems} sys - The Scene Systems class to install all the plugins in to. - * @param {array} globalPlugins - An array of global plugins to install. - * @param {array} scenePlugins - An array of scene plugins to install. - */ - addToScene: function (sys, globalPlugins, scenePlugins) - { - var i; - var pluginKey; - var pluginList; - var game = this.game; - var scene = sys.scene; - var map = sys.settings.map; - var isBooted = sys.settings.isBooted; - - // Reference the GlobalPlugins from Game into Scene.Systems - for (i = 0; i < globalPlugins.length; i++) - { - pluginKey = globalPlugins[i]; - - if (game[pluginKey]) - { - sys[pluginKey] = game[pluginKey]; - - // Scene level injection - if (map.hasOwnProperty(pluginKey)) - { - scene[map[pluginKey]] = sys[pluginKey]; - } - } - else if (pluginKey === 'game' && map.hasOwnProperty(pluginKey)) - { - scene[map[pluginKey]] = game; - } - } - - for (var s = 0; s < scenePlugins.length; s++) - { - pluginList = scenePlugins[s]; - - for (i = 0; i < pluginList.length; i++) - { - pluginKey = pluginList[i]; - - if (!PluginCache.hasCore(pluginKey)) - { - continue; - } - - var source = PluginCache.getCore(pluginKey); - - var plugin = new source.plugin(scene, this); - - sys[source.mapping] = plugin; - - // Scene level injection - if (source.custom) - { - scene[source.mapping] = plugin; - } - else if (map.hasOwnProperty(source.mapping)) - { - scene[map[source.mapping]] = plugin; - } - - // Scene is already booted, usually because this method is being called at run-time, so boot the plugin - if (isBooted) - { - plugin.boot(); - } - } - } - - // And finally, inject any 'global scene plugins' - pluginList = this.plugins; - - for (i = 0; i < pluginList.length; i++) - { - var entry = pluginList[i]; - - if (entry.mapping) - { - scene[entry.mapping] = entry.plugin; - } - } - }, - - /** - * Called by the Scene Systems class. Returns a list of plugins to be installed. - * - * @method Phaser.Plugins.PluginManager#getDefaultScenePlugins - * @protected - * @since 3.8.0 - * - * @return {string[]} A list keys of all the Scene Plugins to install. - */ - getDefaultScenePlugins: function () - { - var list = this.game.config.defaultPlugins; - - // Merge in custom Scene plugins - list = list.concat(this.scenePlugins); - - return list; - }, - - /** - * Installs a new Scene Plugin into the Plugin Manager and optionally adds it - * to the given Scene as well. A Scene Plugin added to the manager in this way - * will be automatically installed into all new Scenes using the key and mapping given. - * - * The `key` property is what the plugin is injected into Scene.Systems as. - * The `mapping` property is optional, and if specified is what the plugin is installed into - * the Scene as. For example: - * - * ```javascript - * this.plugins.installScenePlugin('powerupsPlugin', pluginCode, 'powerups'); - * - * // and from within the scene: - * this.sys.powerupsPlugin; // key value - * this.powerups; // mapping value - * ``` - * - * This method is called automatically by Phaser if you install your plugins using either the - * Game Configuration object, or by preloading them via the Loader. - * - * @method Phaser.Plugins.PluginManager#installScenePlugin - * @since 3.8.0 - * - * @param {string} key - The property key that will be used to add this plugin to Scene.Systems. - * @param {function} plugin - The plugin code. This should be the non-instantiated version. - * @param {string} [mapping] - If this plugin is injected into the Phaser.Scene class, this is the property key to use. - * @param {Phaser.Scene} [addToScene] - Optionally automatically add this plugin to the given Scene. - * @param {boolean} [fromLoader=false] - Is this being called by the Loader? - */ - installScenePlugin: function (key, plugin, mapping, addToScene, fromLoader) - { - if (fromLoader === undefined) { fromLoader = false; } - - if (typeof plugin !== 'function') - { - console.warn('Invalid Scene Plugin: ' + key); - return; - } - - if (!PluginCache.hasCore(key)) - { - // Plugin is freshly loaded - PluginCache.register(key, plugin, mapping, true); - - this.scenePlugins.push(key); - } - else if (!fromLoader && PluginCache.hasCore(key)) - { - // Plugin wasn't from the loader but already exists - console.warn('Scene Plugin key in use: ' + key); - return; - } - - if (addToScene) - { - var instance = new plugin(addToScene, this); - - addToScene.sys[key] = instance; - - if (mapping && mapping !== '') - { - addToScene[mapping] = instance; - } - - instance.boot(); - } - }, - - /** - * Installs a new Global Plugin into the Plugin Manager and optionally starts it running. - * A global plugin belongs to the Plugin Manager, rather than a specific Scene, and can be accessed - * and used by all Scenes in your game. - * - * The `key` property is what you use to access this plugin from the Plugin Manager. - * - * ```javascript - * this.plugins.install('powerupsPlugin', pluginCode); - * - * // and from within the scene: - * this.plugins.get('powerupsPlugin'); - * ``` - * - * This method is called automatically by Phaser if you install your plugins using either the - * Game Configuration object, or by preloading them via the Loader. - * - * The same plugin can be installed multiple times into the Plugin Manager by simply giving each - * instance its own unique key. - * - * @method Phaser.Plugins.PluginManager#install - * @since 3.8.0 - * - * @param {string} key - The unique handle given to this plugin within the Plugin Manager. - * @param {function} plugin - The plugin code. This should be the non-instantiated version. - * @param {boolean} [start=false] - Automatically start the plugin running? This is always `true` if you provide a mapping value. - * @param {string} [mapping] - If this plugin is injected into the Phaser.Scene class, this is the property key to use. - * @param {any} [data] - A value passed to the plugin's `init` method. - * - * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if `start` was false, or game isn't yet booted. - */ - install: function (key, plugin, start, mapping, data) - { - if (start === undefined) { start = false; } - if (mapping === undefined) { mapping = null; } - if (data === undefined) { data = null; } - - if (typeof plugin !== 'function') - { - console.warn('Invalid Plugin: ' + key); - return null; - } - - if (PluginCache.hasCustom(key)) - { - console.warn('Plugin key in use: ' + key); - return null; - } - - if (mapping !== null) - { - start = true; - } - - if (!this.game.isBooted) - { - this._pendingGlobal.push({ key: key, plugin: plugin, start: start, mapping: mapping, data: data }); - } - else - { - // Add it to the plugin store - PluginCache.registerCustom(key, plugin, mapping, data); - - if (start) - { - return this.start(key); - } - } - - return null; - }, - - /** - * 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 {integer} The index of the plugin within the plugins array. - */ - getIndex: function (key) - { - var list = this.plugins; - - for (var i = 0; i < list.length; i++) - { - var entry = list[i]; - - if (entry.key === key) - { - return i; - } - } - - return -1; - }, - - /** - * 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. - */ - getEntry: function (key) - { - var idx = this.getIndex(key); - - if (idx !== -1) - { - return this.plugins[idx]; - } - }, - - /** - * 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`. - */ - isActive: function (key) - { - var entry = this.getEntry(key); - - return (entry && entry.active); - }, - - /** - * Starts a global plugin running. - * - * If the plugin was previously active then calling `start` will reset it to an active state and then - * call its `start` method. - * - * If the plugin has never been run before a new instance of it will be created within the Plugin Manager, - * its active state set and then both of its `init` and `start` methods called, in that order. - * - * If the plugin is already running under the given key then nothing happens. - * - * @method Phaser.Plugins.PluginManager#start - * @since 3.8.0 - * - * @param {string} key - The key of the plugin to start. - * @param {string} [runAs] - Run the plugin under a new key. This allows you to run one plugin multiple times. - * - * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if invalid key given or plugin is already stopped. - */ - start: function (key, runAs) - { - if (runAs === undefined) { runAs = key; } - - var entry = this.getEntry(runAs); - - // Plugin already running under this key? - if (entry && !entry.active) - { - // It exists, we just need to start it up again - entry.active = true; - entry.plugin.start(); - } - else if (!entry) - { - entry = this.createEntry(key, runAs); - } - - return (entry) ? entry.plugin : null; - }, - - /** - * Creates a new instance of a global plugin, adds an entry into the plugins array and returns it. - * - * @method Phaser.Plugins.PluginManager#createEntry - * @private - * @since 3.9.0 - * - * @param {string} key - The key of the plugin to create an instance of. - * @param {string} [runAs] - Run the plugin under a new key. This allows you to run one plugin multiple times. - * - * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if invalid key given. - */ - createEntry: function (key, runAs) - { - var entry = PluginCache.getCustom(key); - - if (entry) - { - var instance = new entry.plugin(this); - - entry = { - key: runAs, - plugin: instance, - active: true, - mapping: entry.mapping, - data: entry.data - }; - - this.plugins.push(entry); - - instance.init(entry.data); - instance.start(); - } - - return entry; - }, - - /** - * Stops a global plugin from running. - * - * If the plugin is active then its active state will be set to false and the plugins `stop` method - * will be called. - * - * If the plugin is not already running, nothing will happen. - * - * @method Phaser.Plugins.PluginManager#stop - * @since 3.8.0 - * - * @param {string} key - The key of the plugin to stop. - * - * @return {Phaser.Plugins.PluginManager} The Plugin Manager. - */ - stop: function (key) - { - var entry = this.getEntry(key); - - if (entry && entry.active) - { - entry.active = false; - entry.plugin.stop(); - } - - return this; - }, - - /** - * 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. - */ - get: function (key, autoStart) - { - if (autoStart === undefined) { autoStart = true; } - - var entry = this.getEntry(key); - - if (entry) - { - return entry.plugin; - } - else - { - var plugin = this.getClass(key); - - if (plugin && autoStart) - { - entry = this.createEntry(key, key); - - return (entry) ? entry.plugin : null; - } - else if (plugin) - { - return plugin; - } - } - - return null; - }, - - /** - * Returns the plugin class from the cache. - * Used internally by the Plugin Manager. - * - * @method Phaser.Plugins.PluginManager#getClass - * @since 3.8.0 - * - * @param {string} key - The key of the plugin to get. - * - * @return {Phaser.Plugins.BasePlugin} A Plugin object - */ - getClass: function (key) - { - return PluginCache.getCustomClass(key); - }, - - /** - * Removes a global plugin from the Plugin Manager and Plugin Cache. - * - * It is up to you to remove all references to this plugin that you may hold within your game code. - * - * @method Phaser.Plugins.PluginManager#removeGlobalPlugin - * @since 3.8.0 - * - * @param {string} key - The key of the plugin to remove. - */ - removeGlobalPlugin: function (key) - { - var entry = this.getEntry(key); - - if (entry) - { - Remove(this.plugins, entry); - } - - PluginCache.removeCustom(key); - }, - - /** - * Removes a scene plugin from the Plugin Manager and Plugin Cache. - * - * This will not remove the plugin from any active Scenes that are already using it. - * - * It is up to you to remove all references to this plugin that you may hold within your game code. - * - * @method Phaser.Plugins.PluginManager#removeScenePlugin - * @since 3.8.0 - * - * @param {string} key - The key of the plugin to remove. - */ - removeScenePlugin: function (key) - { - Remove(this.scenePlugins, key); - - PluginCache.remove(key); - }, - - /** - * Registers a new type of Game Object with the global Game Object Factory and / or Creator. - * This is usually called from within your Plugin code and is a helpful short-cut for creating - * new Game Objects. - * - * The key is the property that will be injected into the factories and used to create the - * Game Object. For example: - * - * ```javascript - * this.plugins.registerGameObject('clown', clownFactoryCallback, clownCreatorCallback); - * // later in your game code: - * this.add.clown(); - * this.make.clown(); - * ``` - * - * The callbacks are what are called when the factories try to create a Game Object - * matching the given key. It's important to understand that the callbacks are invoked within - * the context of the GameObjectFactory. In this 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. - * - * See the GameObjectFactory and GameObjectCreator classes for more details. - * Any public property or method listed is available from your callbacks under `this`. - * - * @method Phaser.Plugins.PluginManager#registerGameObject - * @since 3.8.0 - * - * @param {string} key - The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. - * @param {function} [factoryCallback] - The callback to invoke when the Game Object Factory is called. - * @param {function} [creatorCallback] - The callback to invoke when the Game Object Creator is called. - */ - registerGameObject: function (key, factoryCallback, creatorCallback) - { - if (factoryCallback) - { - GameObjectFactory.register(key, factoryCallback); - } - - if (creatorCallback) - { - GameObjectCreator.register(key, creatorCallback); - } - - return this; - }, - - /** - * Removes a previously registered Game Object from the global Game Object Factory and / or Creator. - * This is usually called from within your Plugin destruction code to help clean-up after your plugin has been removed. - * - * @method Phaser.Plugins.PluginManager#removeGameObject - * @since 3.19.0 - * - * @param {string} key - The key of the Game Object to be removed from the factories. - * @param {boolean} [removeFromFactory=true] - Should the Game Object be removed from the Game Object Factory? - * @param {boolean} [removeFromCreator=true] - Should the Game Object be removed from the Game Object Creator? - */ - removeGameObject: function (key, removeFromFactory, removeFromCreator) - { - if (removeFromFactory === undefined) { removeFromFactory = true; } - if (removeFromCreator === undefined) { removeFromCreator = true; } - - if (removeFromFactory) - { - GameObjectFactory.remove(key); - } - - if (removeFromCreator) - { - GameObjectCreator.remove(key); - } - - return this; - }, - - /** - * Registers a new file type with the global File Types Manager, making it available to all Loader - * Plugins created after this. - * - * This is usually called from within your Plugin code and is a helpful short-cut for creating - * new loader file types. - * - * The key is the property that will be injected into the Loader Plugin and used to load the - * files. For example: - * - * ```javascript - * this.plugins.registerFileType('wad', doomWadLoaderCallback); - * // later in your preload code: - * this.load.wad(); - * ``` - * - * The callback is what is called when the loader tries to load a file matching the given key. - * It's important to understand that the callback is invoked within - * the context of the LoaderPlugin. In this context there are several properties / methods available - * to use: - * - * this.addFile - A method to add the new file to the load queue. - * this.scene - The Scene that owns the Loader Plugin instance. - * - * See the LoaderPlugin class for more details. Any public property or method listed is available from - * your callback under `this`. - * - * @method Phaser.Plugins.PluginManager#registerFileType - * @since 3.8.0 - * - * @param {string} key - The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. - * @param {function} callback - The callback to invoke when the Game Object Factory is called. - * @param {Phaser.Scene} [addToScene] - Optionally add this file type into the Loader Plugin owned by the given Scene. - */ - registerFileType: function (key, callback, addToScene) - { - FileTypesManager.register(key, callback); - - if (addToScene && addToScene.sys.load) - { - addToScene.sys.load[key] = callback; - } - }, - - /** - * Destroys this Plugin Manager and all associated plugins. - * It will iterate all plugins found and call their `destroy` methods. - * - * The PluginCache will remove all custom plugins. - * - * @method Phaser.Plugins.PluginManager#destroy - * @since 3.8.0 - */ - destroy: function () - { - for (var i = 0; i < this.plugins.length; i++) - { - this.plugins[i].plugin.destroy(); - } - - PluginCache.destroyCustomPlugins(); - - if (this.game.noReturn) - { - PluginCache.destroyCorePlugins(); - } - - this.game = null; - this.plugins = []; - this.scenePlugins = []; - } - -}); - -/* - * "Sometimes, the elegant implementation is just a function. - * Not a method. Not a class. Not a framework. Just a function." - * -- John Carmack - */ - -module.exports = PluginManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var GameEvents = require('../core/events'); +var EventEmitter = require('eventemitter3'); +var FileTypesManager = require('../loader/FileTypesManager'); +var GameObjectCreator = require('../gameobjects/GameObjectCreator'); +var GameObjectFactory = require('../gameobjects/GameObjectFactory'); +var GetFastValue = require('../utils/object/GetFastValue'); +var PluginCache = require('./PluginCache'); +var Remove = require('../utils/array/Remove'); + +/** + * @classdesc + * The PluginManager is responsible for installing and adding plugins to Phaser. + * + * It is a global system and therefore belongs to the Game instance, not a specific Scene. + * + * It works in conjunction with the PluginCache. Core internal plugins automatically register themselves + * with the Cache, but it's the Plugin Manager that is responsible for injecting them into the Scenes. + * + * There are two types of plugin: + * + * 1. A Global Plugin + * 2. A Scene Plugin + * + * A Global Plugin is a plugin that lives within the Plugin Manager rather than a Scene. You can get + * access to it by calling `PluginManager.get` and providing a key. Any Scene that requests a plugin in + * this way will all get access to the same plugin instance, allowing you to use a single plugin across + * multiple Scenes. + * + * A Scene Plugin is a plugin dedicated to running within a Scene. These are different to Global Plugins + * in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. + * And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene + * Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. + * + * You can add a plugin to Phaser in three different ways: + * + * 1. Preload it + * 2. Include it in your source code and install it via the Game Config + * 3. Include it in your source code and install it within a Scene + * + * For examples of all of these approaches please see the Phaser 3 Examples Repo `plugins` folder. + * + * For information on creating your own plugin please see the Phaser 3 Plugin Template. + * + * @class PluginManager + * @memberof Phaser.Plugins + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The game instance that owns this Plugin Manager. + */ +var PluginManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function PluginManager (game) + { + EventEmitter.call(this); + + /** + * The game instance that owns this Plugin Manager. + * + * @name Phaser.Plugins.PluginManager#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * The global plugins currently running and managed by this Plugin Manager. + * A plugin must have been started at least once in order to appear in this list. + * + * @name Phaser.Plugins.PluginManager#plugins + * @type {Phaser.Types.Plugins.GlobalPlugin[]} + * @since 3.8.0 + */ + this.plugins = []; + + /** + * A list of plugin keys that should be installed into Scenes as well as the Core Plugins. + * + * @name Phaser.Plugins.PluginManager#scenePlugins + * @type {string[]} + * @since 3.8.0 + */ + this.scenePlugins = []; + + /** + * A temporary list of plugins to install when the game has booted. + * + * @name Phaser.Plugins.PluginManager#_pendingGlobal + * @private + * @type {array} + * @since 3.8.0 + */ + this._pendingGlobal = []; + + /** + * A temporary list of scene plugins to install when the game has booted. + * + * @name Phaser.Plugins.PluginManager#_pendingScene + * @private + * @type {array} + * @since 3.8.0 + */ + this._pendingScene = []; + + if (game.isBooted) + { + this.boot(); + } + else + { + game.events.once(GameEvents.BOOT, this.boot, this); + } + }, + + /** + * Run once the game has booted and installs all of the plugins configured in the Game Config. + * + * @method Phaser.Plugins.PluginManager#boot + * @protected + * @since 3.0.0 + */ + boot: function () + { + var i; + var entry; + var key; + var plugin; + var start; + var mapping; + var data; + var config = this.game.config; + + // Any plugins to install? + var list = config.installGlobalPlugins; + + // Any plugins added outside of the game config, but before the game booted? + list = list.concat(this._pendingGlobal); + + for (i = 0; i < list.length; i++) + { + entry = list[i]; + + // { key: 'TestPlugin', plugin: TestPlugin, start: true, mapping: 'test', data: { msg: 'The plugin is alive' } } + + key = GetFastValue(entry, 'key', null); + plugin = GetFastValue(entry, 'plugin', null); + start = GetFastValue(entry, 'start', false); + mapping = GetFastValue(entry, 'mapping', null); + data = GetFastValue(entry, 'data', null); + + if (key) + { + if (plugin) + { + this.install(key, plugin, start, mapping, data); + } + else + { + console.warn('Missing `plugin` for key: ' + key); + } + + } + } + + // Any scene plugins to install? + list = config.installScenePlugins; + + // Any plugins added outside of the game config, but before the game booted? + list = list.concat(this._pendingScene); + + for (i = 0; i < list.length; i++) + { + entry = list[i]; + + // { key: 'moveSpritePlugin', plugin: MoveSpritePlugin, , mapping: 'move' } + + key = GetFastValue(entry, 'key', null); + plugin = GetFastValue(entry, 'plugin', null); + mapping = GetFastValue(entry, 'mapping', null); + + if (key) + { + if (plugin) + { + this.installScenePlugin(key, plugin, mapping); + } + else + { + console.warn('Missing `plugin` for key: ' + key); + } + } + } + + this._pendingGlobal = []; + this._pendingScene = []; + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Called by the Scene Systems class. Tells the plugin manager to install all Scene plugins into it. + * + * First it will install global references, i.e. references from the Game systems into the Scene Systems (and Scene if mapped.) + * Then it will install Core Scene Plugins followed by Scene Plugins registered with the PluginManager. + * Finally it will install any references to Global Plugins that have a Scene mapping property into the Scene itself. + * + * @method Phaser.Plugins.PluginManager#addToScene + * @protected + * @since 3.8.0 + * + * @param {Phaser.Scenes.Systems} sys - The Scene Systems class to install all the plugins in to. + * @param {array} globalPlugins - An array of global plugins to install. + * @param {array} scenePlugins - An array of scene plugins to install. + */ + addToScene: function (sys, globalPlugins, scenePlugins) + { + var i; + var pluginKey; + var pluginList; + var game = this.game; + var scene = sys.scene; + var map = sys.settings.map; + var isBooted = sys.settings.isBooted; + + // Reference the GlobalPlugins from Game into Scene.Systems + for (i = 0; i < globalPlugins.length; i++) + { + pluginKey = globalPlugins[i]; + + if (game[pluginKey]) + { + sys[pluginKey] = game[pluginKey]; + + // Scene level injection + if (map.hasOwnProperty(pluginKey)) + { + scene[map[pluginKey]] = sys[pluginKey]; + } + } + else if (pluginKey === 'game' && map.hasOwnProperty(pluginKey)) + { + scene[map[pluginKey]] = game; + } + } + + for (var s = 0; s < scenePlugins.length; s++) + { + pluginList = scenePlugins[s]; + + for (i = 0; i < pluginList.length; i++) + { + pluginKey = pluginList[i]; + + if (!PluginCache.hasCore(pluginKey)) + { + continue; + } + + var source = PluginCache.getCore(pluginKey); + + var plugin = new source.plugin(scene, this); + + sys[source.mapping] = plugin; + + // Scene level injection + if (source.custom) + { + scene[source.mapping] = plugin; + } + else if (map.hasOwnProperty(source.mapping)) + { + scene[map[source.mapping]] = plugin; + } + + // Scene is already booted, usually because this method is being called at run-time, so boot the plugin + if (isBooted) + { + plugin.boot(); + } + } + } + + // And finally, inject any 'global scene plugins' + pluginList = this.plugins; + + for (i = 0; i < pluginList.length; i++) + { + var entry = pluginList[i]; + + if (entry.mapping) + { + scene[entry.mapping] = entry.plugin; + } + } + }, + + /** + * Called by the Scene Systems class. Returns a list of plugins to be installed. + * + * @method Phaser.Plugins.PluginManager#getDefaultScenePlugins + * @protected + * @since 3.8.0 + * + * @return {string[]} A list keys of all the Scene Plugins to install. + */ + getDefaultScenePlugins: function () + { + var list = this.game.config.defaultPlugins; + + // Merge in custom Scene plugins + list = list.concat(this.scenePlugins); + + return list; + }, + + /** + * Installs a new Scene Plugin into the Plugin Manager and optionally adds it + * to the given Scene as well. A Scene Plugin added to the manager in this way + * will be automatically installed into all new Scenes using the key and mapping given. + * + * The `key` property is what the plugin is injected into Scene.Systems as. + * The `mapping` property is optional, and if specified is what the plugin is installed into + * the Scene as. For example: + * + * ```javascript + * this.plugins.installScenePlugin('powerupsPlugin', pluginCode, 'powerups'); + * + * // and from within the scene: + * this.sys.powerupsPlugin; // key value + * this.powerups; // mapping value + * ``` + * + * This method is called automatically by Phaser if you install your plugins using either the + * Game Configuration object, or by preloading them via the Loader. + * + * @method Phaser.Plugins.PluginManager#installScenePlugin + * @since 3.8.0 + * + * @param {string} key - The property key that will be used to add this plugin to Scene.Systems. + * @param {function} plugin - The plugin code. This should be the non-instantiated version. + * @param {string} [mapping] - If this plugin is injected into the Phaser.Scene class, this is the property key to use. + * @param {Phaser.Scene} [addToScene] - Optionally automatically add this plugin to the given Scene. + * @param {boolean} [fromLoader=false] - Is this being called by the Loader? + */ + installScenePlugin: function (key, plugin, mapping, addToScene, fromLoader) + { + if (fromLoader === undefined) { fromLoader = false; } + + if (typeof plugin !== 'function') + { + console.warn('Invalid Scene Plugin: ' + key); + return; + } + + if (!PluginCache.hasCore(key)) + { + // Plugin is freshly loaded + PluginCache.register(key, plugin, mapping, true); + + this.scenePlugins.push(key); + } + else if (!fromLoader && PluginCache.hasCore(key)) + { + // Plugin wasn't from the loader but already exists + console.warn('Scene Plugin key in use: ' + key); + return; + } + + if (addToScene) + { + var instance = new plugin(addToScene, this); + + addToScene.sys[key] = instance; + + if (mapping && mapping !== '') + { + addToScene[mapping] = instance; + } + + instance.boot(); + } + }, + + /** + * Installs a new Global Plugin into the Plugin Manager and optionally starts it running. + * A global plugin belongs to the Plugin Manager, rather than a specific Scene, and can be accessed + * and used by all Scenes in your game. + * + * The `key` property is what you use to access this plugin from the Plugin Manager. + * + * ```javascript + * this.plugins.install('powerupsPlugin', pluginCode); + * + * // and from within the scene: + * this.plugins.get('powerupsPlugin'); + * ``` + * + * This method is called automatically by Phaser if you install your plugins using either the + * Game Configuration object, or by preloading them via the Loader. + * + * The same plugin can be installed multiple times into the Plugin Manager by simply giving each + * instance its own unique key. + * + * @method Phaser.Plugins.PluginManager#install + * @since 3.8.0 + * + * @param {string} key - The unique handle given to this plugin within the Plugin Manager. + * @param {function} plugin - The plugin code. This should be the non-instantiated version. + * @param {boolean} [start=false] - Automatically start the plugin running? This is always `true` if you provide a mapping value. + * @param {string} [mapping] - If this plugin is injected into the Phaser.Scene class, this is the property key to use. + * @param {any} [data] - A value passed to the plugin's `init` method. + * + * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if `start` was false, or game isn't yet booted. + */ + install: function (key, plugin, start, mapping, data) + { + if (start === undefined) { start = false; } + if (mapping === undefined) { mapping = null; } + if (data === undefined) { data = null; } + + if (typeof plugin !== 'function') + { + console.warn('Invalid Plugin: ' + key); + return null; + } + + if (PluginCache.hasCustom(key)) + { + console.warn('Plugin key in use: ' + key); + return null; + } + + if (mapping !== null) + { + start = true; + } + + if (!this.game.isBooted) + { + this._pendingGlobal.push({ key: key, plugin: plugin, start: start, mapping: mapping, data: data }); + } + else + { + // Add it to the plugin store + PluginCache.registerCustom(key, plugin, mapping, data); + + if (start) + { + return this.start(key); + } + } + + return null; + }, + + /** + * 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 {integer} The index of the plugin within the plugins array. + */ + getIndex: function (key) + { + var list = this.plugins; + + for (var i = 0; i < list.length; i++) + { + var entry = list[i]; + + if (entry.key === key) + { + return i; + } + } + + return -1; + }, + + /** + * 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. + */ + getEntry: function (key) + { + var idx = this.getIndex(key); + + if (idx !== -1) + { + return this.plugins[idx]; + } + }, + + /** + * 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`. + */ + isActive: function (key) + { + var entry = this.getEntry(key); + + return (entry && entry.active); + }, + + /** + * Starts a global plugin running. + * + * If the plugin was previously active then calling `start` will reset it to an active state and then + * call its `start` method. + * + * If the plugin has never been run before a new instance of it will be created within the Plugin Manager, + * its active state set and then both of its `init` and `start` methods called, in that order. + * + * If the plugin is already running under the given key then nothing happens. + * + * @method Phaser.Plugins.PluginManager#start + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to start. + * @param {string} [runAs] - Run the plugin under a new key. This allows you to run one plugin multiple times. + * + * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if invalid key given or plugin is already stopped. + */ + start: function (key, runAs) + { + if (runAs === undefined) { runAs = key; } + + var entry = this.getEntry(runAs); + + // Plugin already running under this key? + if (entry && !entry.active) + { + // It exists, we just need to start it up again + entry.active = true; + entry.plugin.start(); + } + else if (!entry) + { + entry = this.createEntry(key, runAs); + } + + return (entry) ? entry.plugin : null; + }, + + /** + * Creates a new instance of a global plugin, adds an entry into the plugins array and returns it. + * + * @method Phaser.Plugins.PluginManager#createEntry + * @private + * @since 3.9.0 + * + * @param {string} key - The key of the plugin to create an instance of. + * @param {string} [runAs] - Run the plugin under a new key. This allows you to run one plugin multiple times. + * + * @return {?Phaser.Plugins.BasePlugin} The plugin that was started, or `null` if invalid key given. + */ + createEntry: function (key, runAs) + { + var entry = PluginCache.getCustom(key); + + if (entry) + { + var instance = new entry.plugin(this); + + entry = { + key: runAs, + plugin: instance, + active: true, + mapping: entry.mapping, + data: entry.data + }; + + this.plugins.push(entry); + + instance.init(entry.data); + instance.start(); + } + + return entry; + }, + + /** + * Stops a global plugin from running. + * + * If the plugin is active then its active state will be set to false and the plugins `stop` method + * will be called. + * + * If the plugin is not already running, nothing will happen. + * + * @method Phaser.Plugins.PluginManager#stop + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to stop. + * + * @return {Phaser.Plugins.PluginManager} The Plugin Manager. + */ + stop: function (key) + { + var entry = this.getEntry(key); + + if (entry && entry.active) + { + entry.active = false; + entry.plugin.stop(); + } + + return this; + }, + + /** + * 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. + */ + get: function (key, autoStart) + { + if (autoStart === undefined) { autoStart = true; } + + var entry = this.getEntry(key); + + if (entry) + { + return entry.plugin; + } + else + { + var plugin = this.getClass(key); + + if (plugin && autoStart) + { + entry = this.createEntry(key, key); + + return (entry) ? entry.plugin : null; + } + else if (plugin) + { + return plugin; + } + } + + return null; + }, + + /** + * Returns the plugin class from the cache. + * Used internally by the Plugin Manager. + * + * @method Phaser.Plugins.PluginManager#getClass + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to get. + * + * @return {Phaser.Plugins.BasePlugin} A Plugin object + */ + getClass: function (key) + { + return PluginCache.getCustomClass(key); + }, + + /** + * Removes a global plugin from the Plugin Manager and Plugin Cache. + * + * It is up to you to remove all references to this plugin that you may hold within your game code. + * + * @method Phaser.Plugins.PluginManager#removeGlobalPlugin + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to remove. + */ + removeGlobalPlugin: function (key) + { + var entry = this.getEntry(key); + + if (entry) + { + Remove(this.plugins, entry); + } + + PluginCache.removeCustom(key); + }, + + /** + * Removes a scene plugin from the Plugin Manager and Plugin Cache. + * + * This will not remove the plugin from any active Scenes that are already using it. + * + * It is up to you to remove all references to this plugin that you may hold within your game code. + * + * @method Phaser.Plugins.PluginManager#removeScenePlugin + * @since 3.8.0 + * + * @param {string} key - The key of the plugin to remove. + */ + removeScenePlugin: function (key) + { + Remove(this.scenePlugins, key); + + PluginCache.remove(key); + }, + + /** + * Registers a new type of Game Object with the global Game Object Factory and / or Creator. + * This is usually called from within your Plugin code and is a helpful short-cut for creating + * new Game Objects. + * + * The key is the property that will be injected into the factories and used to create the + * Game Object. For example: + * + * ```javascript + * this.plugins.registerGameObject('clown', clownFactoryCallback, clownCreatorCallback); + * // later in your game code: + * this.add.clown(); + * this.make.clown(); + * ``` + * + * The callbacks are what are called when the factories try to create a Game Object + * matching the given key. It's important to understand that the callbacks are invoked within + * the context of the GameObjectFactory. In this 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. + * + * See the GameObjectFactory and GameObjectCreator classes for more details. + * Any public property or method listed is available from your callbacks under `this`. + * + * @method Phaser.Plugins.PluginManager#registerGameObject + * @since 3.8.0 + * + * @param {string} key - The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. + * @param {function} [factoryCallback] - The callback to invoke when the Game Object Factory is called. + * @param {function} [creatorCallback] - The callback to invoke when the Game Object Creator is called. + */ + registerGameObject: function (key, factoryCallback, creatorCallback) + { + if (factoryCallback) + { + GameObjectFactory.register(key, factoryCallback); + } + + if (creatorCallback) + { + GameObjectCreator.register(key, creatorCallback); + } + + return this; + }, + + /** + * Removes a previously registered Game Object from the global Game Object Factory and / or Creator. + * This is usually called from within your Plugin destruction code to help clean-up after your plugin has been removed. + * + * @method Phaser.Plugins.PluginManager#removeGameObject + * @since 3.19.0 + * + * @param {string} key - The key of the Game Object to be removed from the factories. + * @param {boolean} [removeFromFactory=true] - Should the Game Object be removed from the Game Object Factory? + * @param {boolean} [removeFromCreator=true] - Should the Game Object be removed from the Game Object Creator? + */ + removeGameObject: function (key, removeFromFactory, removeFromCreator) + { + if (removeFromFactory === undefined) { removeFromFactory = true; } + if (removeFromCreator === undefined) { removeFromCreator = true; } + + if (removeFromFactory) + { + GameObjectFactory.remove(key); + } + + if (removeFromCreator) + { + GameObjectCreator.remove(key); + } + + return this; + }, + + /** + * Registers a new file type with the global File Types Manager, making it available to all Loader + * Plugins created after this. + * + * This is usually called from within your Plugin code and is a helpful short-cut for creating + * new loader file types. + * + * The key is the property that will be injected into the Loader Plugin and used to load the + * files. For example: + * + * ```javascript + * this.plugins.registerFileType('wad', doomWadLoaderCallback); + * // later in your preload code: + * this.load.wad(); + * ``` + * + * The callback is what is called when the loader tries to load a file matching the given key. + * It's important to understand that the callback is invoked within + * the context of the LoaderPlugin. In this context there are several properties / methods available + * to use: + * + * this.addFile - A method to add the new file to the load queue. + * this.scene - The Scene that owns the Loader Plugin instance. + * + * See the LoaderPlugin class for more details. Any public property or method listed is available from + * your callback under `this`. + * + * @method Phaser.Plugins.PluginManager#registerFileType + * @since 3.8.0 + * + * @param {string} key - The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. + * @param {function} callback - The callback to invoke when the Game Object Factory is called. + * @param {Phaser.Scene} [addToScene] - Optionally add this file type into the Loader Plugin owned by the given Scene. + */ + registerFileType: function (key, callback, addToScene) + { + FileTypesManager.register(key, callback); + + if (addToScene && addToScene.sys.load) + { + addToScene.sys.load[key] = callback; + } + }, + + /** + * Destroys this Plugin Manager and all associated plugins. + * It will iterate all plugins found and call their `destroy` methods. + * + * The PluginCache will remove all custom plugins. + * + * @method Phaser.Plugins.PluginManager#destroy + * @since 3.8.0 + */ + destroy: function () + { + for (var i = 0; i < this.plugins.length; i++) + { + this.plugins[i].plugin.destroy(); + } + + PluginCache.destroyCustomPlugins(); + + if (this.game.noReturn) + { + PluginCache.destroyCorePlugins(); + } + + this.game = null; + this.plugins = []; + this.scenePlugins = []; + } + +}); + +/* + * "Sometimes, the elegant implementation is just a function. + * Not a method. Not a class. Not a framework. Just a function." + * -- John Carmack + */ + +module.exports = PluginManager; diff --git a/src/plugins/ScenePlugin.js b/src/plugins/ScenePlugin.js index fb4130d70..77ddbed0b 100644 --- a/src/plugins/ScenePlugin.js +++ b/src/plugins/ScenePlugin.js @@ -1,122 +1,122 @@ -/** -* @author Richard Davey -* @copyright 2020 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} -*/ - -var BasePlugin = require('./BasePlugin'); -var Class = require('../utils/Class'); -var SceneEvents = require('../scene/events'); - -/** - * @classdesc - * A Scene Level Plugin is installed into every Scene and belongs to that Scene. - * It can listen for Scene events and respond to them. - * It can map itself to a Scene property, or into the Scene Systems, or both. - * - * @class ScenePlugin - * @memberof Phaser.Plugins - * @extends Phaser.Plugins.BasePlugin - * @constructor - * @since 3.8.0 - * - * @param {Phaser.Scene} scene - A reference to the Scene that has installed this plugin. - * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Plugin Manager. - */ -var ScenePlugin = new Class({ - - Extends: BasePlugin, - - initialize: - - function ScenePlugin (scene, pluginManager) - { - BasePlugin.call(this, pluginManager); - - /** - * A reference to the Scene that has installed this plugin. - * Only set if it's a Scene Plugin, otherwise `null`. - * This property is only set when the plugin is instantiated and added to the Scene, not before. - * You can use it during the `boot` method. - * - * @name Phaser.Plugins.ScenePlugin#scene - * @type {?Phaser.Scene} - * @protected - * @since 3.8.0 - */ - this.scene = scene; - - /** - * A reference to the Scene Systems of the Scene that has installed this plugin. - * Only set if it's a Scene Plugin, otherwise `null`. - * This property is only set when the plugin is instantiated and added to the Scene, not before. - * You can use it during the `boot` method. - * - * @name Phaser.Plugins.ScenePlugin#systems - * @type {?Phaser.Scenes.Systems} - * @protected - * @since 3.8.0 - */ - this.systems = scene.sys; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - }, - - /** - * This method is called when the Scene boots. It is only ever called once. - * - * By this point the plugin properties `scene` and `systems` will have already been set. - * - * In here you can listen for {@link Phaser.Scenes.Events Scene events} and set-up whatever you need for this plugin to run. - * Here are the Scene events you can listen to: - * - * - start - * - ready - * - preupdate - * - update - * - postupdate - * - resize - * - pause - * - resume - * - sleep - * - wake - * - transitioninit - * - transitionstart - * - transitioncomplete - * - transitionout - * - shutdown - * - destroy - * - * At the very least you should offer a destroy handler for when the Scene closes down, i.e: - * - * ```javascript - * var eventEmitter = this.systems.events; - * eventEmitter.once('destroy', this.sceneDestroy, this); - * ``` - * - * @method Phaser.Plugins.ScenePlugin#boot - * @since 3.8.0 - */ - boot: function () - { - }, - - /** - * Game instance has been destroyed. - * - * You must release everything in here, all references, all objects, free it all up. - * - * @method Phaser.Plugins.ScenePlugin#destroy - * @since 3.8.0 - */ - destroy: function () - { - this.pluginManager = null; - this.game = null; - this.scene = null; - this.systems = null; - } - -}); - -module.exports = ScenePlugin; +/** +* @author Richard Davey +* @copyright 2020 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License} +*/ + +var BasePlugin = require('./BasePlugin'); +var Class = require('../utils/Class'); +var SceneEvents = require('../scene/events'); + +/** + * @classdesc + * A Scene Level Plugin is installed into every Scene and belongs to that Scene. + * It can listen for Scene events and respond to them. + * It can map itself to a Scene property, or into the Scene Systems, or both. + * + * @class ScenePlugin + * @memberof Phaser.Plugins + * @extends Phaser.Plugins.BasePlugin + * @constructor + * @since 3.8.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that has installed this plugin. + * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Plugin Manager. + */ +var ScenePlugin = new Class({ + + Extends: BasePlugin, + + initialize: + + function ScenePlugin (scene, pluginManager) + { + BasePlugin.call(this, pluginManager); + + /** + * A reference to the Scene that has installed this plugin. + * Only set if it's a Scene Plugin, otherwise `null`. + * This property is only set when the plugin is instantiated and added to the Scene, not before. + * You can use it during the `boot` method. + * + * @name Phaser.Plugins.ScenePlugin#scene + * @type {?Phaser.Scene} + * @protected + * @since 3.8.0 + */ + this.scene = scene; + + /** + * A reference to the Scene Systems of the Scene that has installed this plugin. + * Only set if it's a Scene Plugin, otherwise `null`. + * This property is only set when the plugin is instantiated and added to the Scene, not before. + * You can use it during the `boot` method. + * + * @name Phaser.Plugins.ScenePlugin#systems + * @type {?Phaser.Scenes.Systems} + * @protected + * @since 3.8.0 + */ + this.systems = scene.sys; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + }, + + /** + * This method is called when the Scene boots. It is only ever called once. + * + * By this point the plugin properties `scene` and `systems` will have already been set. + * + * In here you can listen for {@link Phaser.Scenes.Events Scene events} and set-up whatever you need for this plugin to run. + * Here are the Scene events you can listen to: + * + * - start + * - ready + * - preupdate + * - update + * - postupdate + * - resize + * - pause + * - resume + * - sleep + * - wake + * - transitioninit + * - transitionstart + * - transitioncomplete + * - transitionout + * - shutdown + * - destroy + * + * At the very least you should offer a destroy handler for when the Scene closes down, i.e: + * + * ```javascript + * var eventEmitter = this.systems.events; + * eventEmitter.once('destroy', this.sceneDestroy, this); + * ``` + * + * @method Phaser.Plugins.ScenePlugin#boot + * @since 3.8.0 + */ + boot: function () + { + }, + + /** + * Game instance has been destroyed. + * + * You must release everything in here, all references, all objects, free it all up. + * + * @method Phaser.Plugins.ScenePlugin#destroy + * @since 3.8.0 + */ + destroy: function () + { + this.pluginManager = null; + this.game = null; + this.scene = null; + this.systems = null; + } + +}); + +module.exports = ScenePlugin; diff --git a/src/plugins/index.js b/src/plugins/index.js index 8e4b5ef7b..10b5862cd 100644 --- a/src/plugins/index.js +++ b/src/plugins/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Plugins - */ - -module.exports = { - - BasePlugin: require('./BasePlugin'), - DefaultPlugins: require('./DefaultPlugins'), - PluginCache: require('./PluginCache'), - PluginManager: require('./PluginManager'), - ScenePlugin: require('./ScenePlugin') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Plugins + */ + +module.exports = { + + BasePlugin: require('./BasePlugin'), + DefaultPlugins: require('./DefaultPlugins'), + PluginCache: require('./PluginCache'), + PluginManager: require('./PluginManager'), + ScenePlugin: require('./ScenePlugin') + +}; diff --git a/src/plugins/typedefs/index.js b/src/plugins/typedefs/index.js index b0087b40c..4a7842a81 100644 --- a/src/plugins/typedefs/index.js +++ b/src/plugins/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Plugins - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Plugins + */ diff --git a/src/renderer/BlendModes.js b/src/renderer/BlendModes.js index 7aa4ae668..e3aabda32 100644 --- a/src/renderer/BlendModes.js +++ b/src/renderer/BlendModes.js @@ -1,333 +1,333 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Blend Modes. - * - * @namespace Phaser.BlendModes - * @since 3.0.0 - */ - -module.exports = { - - /** - * Skips the Blend Mode check in the renderer. - * - * @name Phaser.BlendModes.SKIP_CHECK - * @type {integer} - * @const - * @since 3.0.0 - */ - SKIP_CHECK: -1, - - /** - * Normal blend mode. For Canvas and WebGL. - * This is the default setting and draws new shapes on top of the existing canvas content. - * - * @name Phaser.BlendModes.NORMAL - * @type {integer} - * @const - * @since 3.0.0 - */ - NORMAL: 0, - - /** - * Add blend mode. For Canvas and WebGL. - * Where both shapes overlap the color is determined by adding color values. - * - * @name Phaser.BlendModes.ADD - * @type {integer} - * @const - * @since 3.0.0 - */ - ADD: 1, - - /** - * Multiply blend mode. For Canvas and WebGL. - * The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result. - * - * @name Phaser.BlendModes.MULTIPLY - * @type {integer} - * @const - * @since 3.0.0 - */ - MULTIPLY: 2, - - /** - * Screen blend mode. For Canvas and WebGL. - * The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply) - * - * @name Phaser.BlendModes.SCREEN - * @type {integer} - * @const - * @since 3.0.0 - */ - SCREEN: 3, - - /** - * Overlay blend mode. For Canvas only. - * A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter. - * - * @name Phaser.BlendModes.OVERLAY - * @type {integer} - * @const - * @since 3.0.0 - */ - OVERLAY: 4, - - /** - * Darken blend mode. For Canvas only. - * Retains the darkest pixels of both layers. - * - * @name Phaser.BlendModes.DARKEN - * @type {integer} - * @const - * @since 3.0.0 - */ - DARKEN: 5, - - /** - * Lighten blend mode. For Canvas only. - * Retains the lightest pixels of both layers. - * - * @name Phaser.BlendModes.LIGHTEN - * @type {integer} - * @const - * @since 3.0.0 - */ - LIGHTEN: 6, - - /** - * Color Dodge blend mode. For Canvas only. - * Divides the bottom layer by the inverted top layer. - * - * @name Phaser.BlendModes.COLOR_DODGE - * @type {integer} - * @const - * @since 3.0.0 - */ - COLOR_DODGE: 7, - - /** - * Color Burn blend mode. For Canvas only. - * Divides the inverted bottom layer by the top layer, and then inverts the result. - * - * @name Phaser.BlendModes.COLOR_BURN - * @type {integer} - * @const - * @since 3.0.0 - */ - COLOR_BURN: 8, - - /** - * Hard Light blend mode. For Canvas only. - * A combination of multiply and screen like overlay, but with top and bottom layer swapped. - * - * @name Phaser.BlendModes.HARD_LIGHT - * @type {integer} - * @const - * @since 3.0.0 - */ - HARD_LIGHT: 9, - - /** - * Soft Light blend mode. For Canvas only. - * A softer version of hard-light. Pure black or white does not result in pure black or white. - * - * @name Phaser.BlendModes.SOFT_LIGHT - * @type {integer} - * @const - * @since 3.0.0 - */ - SOFT_LIGHT: 10, - - /** - * Difference blend mode. For Canvas only. - * Subtracts the bottom layer from the top layer or the other way round to always get a positive value. - * - * @name Phaser.BlendModes.DIFFERENCE - * @type {integer} - * @const - * @since 3.0.0 - */ - DIFFERENCE: 11, - - /** - * Exclusion blend mode. For Canvas only. - * Like difference, but with lower contrast. - * - * @name Phaser.BlendModes.EXCLUSION - * @type {integer} - * @const - * @since 3.0.0 - */ - EXCLUSION: 12, - - /** - * Hue blend mode. For Canvas only. - * Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer. - * - * @name Phaser.BlendModes.HUE - * @type {integer} - * @const - * @since 3.0.0 - */ - HUE: 13, - - /** - * Saturation blend mode. For Canvas only. - * Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer. - * - * @name Phaser.BlendModes.SATURATION - * @type {integer} - * @const - * @since 3.0.0 - */ - SATURATION: 14, - - /** - * Color blend mode. For Canvas only. - * Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer. - * - * @name Phaser.BlendModes.COLOR - * @type {integer} - * @const - * @since 3.0.0 - */ - COLOR: 15, - - /** - * Luminosity blend mode. For Canvas only. - * Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer. - * - * @name Phaser.BlendModes.LUMINOSITY - * @type {integer} - * @const - * @since 3.0.0 - */ - LUMINOSITY: 16, - - /** - * Alpha erase blend mode. For Canvas and WebGL. - * - * @name Phaser.BlendModes.ERASE - * @type {integer} - * @const - * @since 3.0.0 - */ - ERASE: 17, - - /** - * Source-in blend mode. For Canvas only. - * The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent. - * - * @name Phaser.BlendModes.SOURCE_IN - * @type {integer} - * @const - * @since 3.0.0 - */ - SOURCE_IN: 18, - - /** - * Source-out blend mode. For Canvas only. - * The new shape is drawn where it doesn't overlap the existing canvas content. - * - * @name Phaser.BlendModes.SOURCE_OUT - * @type {integer} - * @const - * @since 3.0.0 - */ - SOURCE_OUT: 19, - - /** - * Source-out blend mode. For Canvas only. - * The new shape is only drawn where it overlaps the existing canvas content. - * - * @name Phaser.BlendModes.SOURCE_ATOP - * @type {integer} - * @const - * @since 3.0.0 - */ - SOURCE_ATOP: 20, - - /** - * Destination-over blend mode. For Canvas only. - * New shapes are drawn behind the existing canvas content. - * - * @name Phaser.BlendModes.DESTINATION_OVER - * @type {integer} - * @const - * @since 3.0.0 - */ - DESTINATION_OVER: 21, - - /** - * Destination-in blend mode. For Canvas only. - * The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent. - * - * @name Phaser.BlendModes.DESTINATION_IN - * @type {integer} - * @const - * @since 3.0.0 - */ - DESTINATION_IN: 22, - - /** - * Destination-out blend mode. For Canvas only. - * The existing content is kept where it doesn't overlap the new shape. - * - * @name Phaser.BlendModes.DESTINATION_OUT - * @type {integer} - * @const - * @since 3.0.0 - */ - DESTINATION_OUT: 23, - - /** - * Destination-out blend mode. For Canvas only. - * The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content. - * - * @name Phaser.BlendModes.DESTINATION_ATOP - * @type {integer} - * @const - * @since 3.0.0 - */ - DESTINATION_ATOP: 24, - - /** - * Lighten blend mode. For Canvas only. - * Where both shapes overlap the color is determined by adding color values. - * - * @name Phaser.BlendModes.LIGHTER - * @type {integer} - * @const - * @since 3.0.0 - */ - LIGHTER: 25, - - /** - * Copy blend mode. For Canvas only. - * Only the new shape is shown. - * - * @name Phaser.BlendModes.COPY - * @type {integer} - * @const - * @since 3.0.0 - */ - COPY: 26, - - /** - * Xor blend mode. For Canvas only. - * Shapes are made transparent where both overlap and drawn normal everywhere else. - * - * @name Phaser.BlendModes.XOR - * @type {integer} - * @const - * @since 3.0.0 - */ - XOR: 27 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Blend Modes. + * + * @namespace Phaser.BlendModes + * @since 3.0.0 + */ + +module.exports = { + + /** + * Skips the Blend Mode check in the renderer. + * + * @name Phaser.BlendModes.SKIP_CHECK + * @type {integer} + * @const + * @since 3.0.0 + */ + SKIP_CHECK: -1, + + /** + * Normal blend mode. For Canvas and WebGL. + * This is the default setting and draws new shapes on top of the existing canvas content. + * + * @name Phaser.BlendModes.NORMAL + * @type {integer} + * @const + * @since 3.0.0 + */ + NORMAL: 0, + + /** + * Add blend mode. For Canvas and WebGL. + * Where both shapes overlap the color is determined by adding color values. + * + * @name Phaser.BlendModes.ADD + * @type {integer} + * @const + * @since 3.0.0 + */ + ADD: 1, + + /** + * Multiply blend mode. For Canvas and WebGL. + * The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result. + * + * @name Phaser.BlendModes.MULTIPLY + * @type {integer} + * @const + * @since 3.0.0 + */ + MULTIPLY: 2, + + /** + * Screen blend mode. For Canvas and WebGL. + * The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply) + * + * @name Phaser.BlendModes.SCREEN + * @type {integer} + * @const + * @since 3.0.0 + */ + SCREEN: 3, + + /** + * Overlay blend mode. For Canvas only. + * A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter. + * + * @name Phaser.BlendModes.OVERLAY + * @type {integer} + * @const + * @since 3.0.0 + */ + OVERLAY: 4, + + /** + * Darken blend mode. For Canvas only. + * Retains the darkest pixels of both layers. + * + * @name Phaser.BlendModes.DARKEN + * @type {integer} + * @const + * @since 3.0.0 + */ + DARKEN: 5, + + /** + * Lighten blend mode. For Canvas only. + * Retains the lightest pixels of both layers. + * + * @name Phaser.BlendModes.LIGHTEN + * @type {integer} + * @const + * @since 3.0.0 + */ + LIGHTEN: 6, + + /** + * Color Dodge blend mode. For Canvas only. + * Divides the bottom layer by the inverted top layer. + * + * @name Phaser.BlendModes.COLOR_DODGE + * @type {integer} + * @const + * @since 3.0.0 + */ + COLOR_DODGE: 7, + + /** + * Color Burn blend mode. For Canvas only. + * Divides the inverted bottom layer by the top layer, and then inverts the result. + * + * @name Phaser.BlendModes.COLOR_BURN + * @type {integer} + * @const + * @since 3.0.0 + */ + COLOR_BURN: 8, + + /** + * Hard Light blend mode. For Canvas only. + * A combination of multiply and screen like overlay, but with top and bottom layer swapped. + * + * @name Phaser.BlendModes.HARD_LIGHT + * @type {integer} + * @const + * @since 3.0.0 + */ + HARD_LIGHT: 9, + + /** + * Soft Light blend mode. For Canvas only. + * A softer version of hard-light. Pure black or white does not result in pure black or white. + * + * @name Phaser.BlendModes.SOFT_LIGHT + * @type {integer} + * @const + * @since 3.0.0 + */ + SOFT_LIGHT: 10, + + /** + * Difference blend mode. For Canvas only. + * Subtracts the bottom layer from the top layer or the other way round to always get a positive value. + * + * @name Phaser.BlendModes.DIFFERENCE + * @type {integer} + * @const + * @since 3.0.0 + */ + DIFFERENCE: 11, + + /** + * Exclusion blend mode. For Canvas only. + * Like difference, but with lower contrast. + * + * @name Phaser.BlendModes.EXCLUSION + * @type {integer} + * @const + * @since 3.0.0 + */ + EXCLUSION: 12, + + /** + * Hue blend mode. For Canvas only. + * Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer. + * + * @name Phaser.BlendModes.HUE + * @type {integer} + * @const + * @since 3.0.0 + */ + HUE: 13, + + /** + * Saturation blend mode. For Canvas only. + * Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer. + * + * @name Phaser.BlendModes.SATURATION + * @type {integer} + * @const + * @since 3.0.0 + */ + SATURATION: 14, + + /** + * Color blend mode. For Canvas only. + * Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer. + * + * @name Phaser.BlendModes.COLOR + * @type {integer} + * @const + * @since 3.0.0 + */ + COLOR: 15, + + /** + * Luminosity blend mode. For Canvas only. + * Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer. + * + * @name Phaser.BlendModes.LUMINOSITY + * @type {integer} + * @const + * @since 3.0.0 + */ + LUMINOSITY: 16, + + /** + * Alpha erase blend mode. For Canvas and WebGL. + * + * @name Phaser.BlendModes.ERASE + * @type {integer} + * @const + * @since 3.0.0 + */ + ERASE: 17, + + /** + * Source-in blend mode. For Canvas only. + * The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent. + * + * @name Phaser.BlendModes.SOURCE_IN + * @type {integer} + * @const + * @since 3.0.0 + */ + SOURCE_IN: 18, + + /** + * Source-out blend mode. For Canvas only. + * The new shape is drawn where it doesn't overlap the existing canvas content. + * + * @name Phaser.BlendModes.SOURCE_OUT + * @type {integer} + * @const + * @since 3.0.0 + */ + SOURCE_OUT: 19, + + /** + * Source-out blend mode. For Canvas only. + * The new shape is only drawn where it overlaps the existing canvas content. + * + * @name Phaser.BlendModes.SOURCE_ATOP + * @type {integer} + * @const + * @since 3.0.0 + */ + SOURCE_ATOP: 20, + + /** + * Destination-over blend mode. For Canvas only. + * New shapes are drawn behind the existing canvas content. + * + * @name Phaser.BlendModes.DESTINATION_OVER + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_OVER: 21, + + /** + * Destination-in blend mode. For Canvas only. + * The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent. + * + * @name Phaser.BlendModes.DESTINATION_IN + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_IN: 22, + + /** + * Destination-out blend mode. For Canvas only. + * The existing content is kept where it doesn't overlap the new shape. + * + * @name Phaser.BlendModes.DESTINATION_OUT + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_OUT: 23, + + /** + * Destination-out blend mode. For Canvas only. + * The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content. + * + * @name Phaser.BlendModes.DESTINATION_ATOP + * @type {integer} + * @const + * @since 3.0.0 + */ + DESTINATION_ATOP: 24, + + /** + * Lighten blend mode. For Canvas only. + * Where both shapes overlap the color is determined by adding color values. + * + * @name Phaser.BlendModes.LIGHTER + * @type {integer} + * @const + * @since 3.0.0 + */ + LIGHTER: 25, + + /** + * Copy blend mode. For Canvas only. + * Only the new shape is shown. + * + * @name Phaser.BlendModes.COPY + * @type {integer} + * @const + * @since 3.0.0 + */ + COPY: 26, + + /** + * Xor blend mode. For Canvas only. + * Shapes are made transparent where both overlap and drawn normal everywhere else. + * + * @name Phaser.BlendModes.XOR + * @type {integer} + * @const + * @since 3.0.0 + */ + XOR: 27 + +}; diff --git a/src/renderer/ScaleModes.js b/src/renderer/ScaleModes.js index 92d1a3af6..1f791047e 100644 --- a/src/renderer/ScaleModes.js +++ b/src/renderer/ScaleModes.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Scale Modes. - * - * @namespace Phaser.ScaleModes - * @since 3.0.0 - */ - -var ScaleModes = { - - /** - * Default Scale Mode (Linear). - * - * @name Phaser.ScaleModes.DEFAULT - * @type {integer} - * @readonly - * @since 3.0.0 - */ - DEFAULT: 0, - - /** - * Linear Scale Mode. - * - * @name Phaser.ScaleModes.LINEAR - * @type {integer} - * @readonly - * @since 3.0.0 - */ - LINEAR: 0, - - /** - * Nearest Scale Mode. - * - * @name Phaser.ScaleModes.NEAREST - * @type {integer} - * @readonly - * @since 3.0.0 - */ - NEAREST: 1 - -}; - -module.exports = ScaleModes; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Modes. + * + * @namespace Phaser.ScaleModes + * @since 3.0.0 + */ + +var ScaleModes = { + + /** + * Default Scale Mode (Linear). + * + * @name Phaser.ScaleModes.DEFAULT + * @type {integer} + * @readonly + * @since 3.0.0 + */ + DEFAULT: 0, + + /** + * Linear Scale Mode. + * + * @name Phaser.ScaleModes.LINEAR + * @type {integer} + * @readonly + * @since 3.0.0 + */ + LINEAR: 0, + + /** + * Nearest Scale Mode. + * + * @name Phaser.ScaleModes.NEAREST + * @type {integer} + * @readonly + * @since 3.0.0 + */ + NEAREST: 1 + +}; + +module.exports = ScaleModes; diff --git a/src/renderer/canvas/CanvasRenderer.js b/src/renderer/canvas/CanvasRenderer.js index 20513708f..fd8f29d91 100644 --- a/src/renderer/canvas/CanvasRenderer.js +++ b/src/renderer/canvas/CanvasRenderer.js @@ -1,791 +1,791 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasSnapshot = require('../snapshot/CanvasSnapshot'); -var CameraEvents = require('../../cameras/2d/events'); -var Class = require('../../utils/Class'); -var CONST = require('../../const'); -var GetBlendModes = require('./utils/GetBlendModes'); -var ScaleEvents = require('../../scale/events'); -var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); - -/** - * @classdesc - * The Canvas Renderer is responsible for managing 2D canvas rendering contexts, including the one used by the Game's canvas. It tracks the internal state of a given context and can renderer textured Game Objects to it, taking into account alpha, blending, and scaling. - * - * @class CanvasRenderer - * @memberof Phaser.Renderer.Canvas - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Phaser Game instance that owns this renderer. - */ -var CanvasRenderer = new Class({ - - initialize: - - function CanvasRenderer (game) - { - /** - * The Phaser Game instance that owns this renderer. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = game; - - /** - * A constant which allows the renderer to be easily identified as a Canvas Renderer. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#type - * @type {integer} - * @since 3.0.0 - */ - this.type = CONST.CANVAS; - - /** - * The total number of Game Objects which were rendered in a frame. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#drawCount - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.drawCount = 0; - - /** - * The width of the canvas being rendered to. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#width - * @type {integer} - * @since 3.0.0 - */ - this.width = 0; - - /** - * The height of the canvas being rendered to. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#height - * @type {integer} - * @since 3.0.0 - */ - this.height = 0; - - /** - * The local configuration settings of the CanvasRenderer. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#config - * @type {object} - * @since 3.0.0 - */ - this.config = { - clearBeforeRender: game.config.clearBeforeRender, - backgroundColor: game.config.backgroundColor, - resolution: game.config.resolution, - antialias: game.config.antialias, - roundPixels: game.config.roundPixels - }; - - /** - * The canvas element which the Game uses. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#gameCanvas - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.gameCanvas = game.canvas; - - var contextOptions = { - alpha: game.config.transparent, - desynchronized: game.config.desynchronized - }; - - /** - * The canvas context used to render all Cameras in all Scenes during the game loop. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#gameContext - * @type {CanvasRenderingContext2D} - * @since 3.0.0 - */ - this.gameContext = (this.game.config.context) ? this.game.config.context : this.gameCanvas.getContext('2d', contextOptions); - - /** - * The canvas context currently used by the CanvasRenderer for all rendering operations. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#currentContext - * @type {CanvasRenderingContext2D} - * @since 3.0.0 - */ - this.currentContext = this.gameContext; - - /** - * Should the Canvas use Image Smoothing or not when drawing Sprites? - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#antialias - * @type {boolean} - * @since 3.20.0 - */ - this.antialias = game.config.antialias; - - /** - * The blend modes supported by the Canvas Renderer. - * - * This object maps the {@link Phaser.BlendModes} to canvas compositing operations. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#blendModes - * @type {array} - * @since 3.0.0 - */ - this.blendModes = GetBlendModes(); - - /** - * Details about the currently scheduled snapshot. - * - * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#snapshotState - * @type {Phaser.Types.Renderer.Snapshot.SnapshotState} - * @since 3.16.0 - */ - this.snapshotState = { - x: 0, - y: 0, - width: 1, - height: 1, - getPixel: false, - callback: null, - type: 'image/png', - encoder: 0.92 - }; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix4 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix4 = new TransformMatrix(); - - this.init(); - }, - - /** - * Prepares the game canvas for rendering. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#init - * @since 3.0.0 - */ - init: function () - { - this.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); - - var baseSize = this.game.scale.baseSize; - - this.resize(baseSize.width, baseSize.height); - }, - - /** - * The event handler that manages the `resize` event dispatched by the Scale Manager. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#onResize - * @since 3.16.0 - * - * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. - * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. - * @param {Phaser.Structs.Size} displaySize - The display Size object. The size of the canvas style width / height attributes. - * @param {number} [resolution] - The Scale Manager resolution setting. - */ - onResize: function (gameSize, baseSize) - { - // Has the underlying canvas size changed? - if (baseSize.width !== this.width || baseSize.height !== this.height) - { - this.resize(baseSize.width, baseSize.height); - } - }, - - /** - * Resize the main game canvas. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#resize - * @since 3.0.0 - * - * @param {number} [width] - The new width of the renderer. - * @param {number} [height] - The new height of the renderer. - */ - resize: function (width, height) - { - this.width = width; - this.height = height; - }, - - /** - * Resets the transformation matrix of the current context to the identity matrix, thus resetting any transformation. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#resetTransform - * @since 3.0.0 - */ - resetTransform: function () - { - this.currentContext.setTransform(1, 0, 0, 1, 0, 0); - }, - - /** - * Sets the blend mode (compositing operation) of the current context. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#setBlendMode - * @since 3.0.0 - * - * @param {string} blendMode - The new blend mode which should be used. - * - * @return {this} This CanvasRenderer object. - */ - setBlendMode: function (blendMode) - { - this.currentContext.globalCompositeOperation = blendMode; - - return this; - }, - - /** - * Changes the Canvas Rendering Context that all draw operations are performed against. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#setContext - * @since 3.12.0 - * - * @param {?CanvasRenderingContext2D} [ctx] - The new Canvas Rendering Context to draw everything to. Leave empty to reset to the Game Canvas. - * - * @return {this} The Canvas Renderer instance. - */ - setContext: function (ctx) - { - this.currentContext = (ctx) ? ctx : this.gameContext; - - return this; - }, - - /** - * Sets the global alpha of the current context. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#setAlpha - * @since 3.0.0 - * - * @param {number} alpha - The new alpha to use, where 0 is fully transparent and 1 is fully opaque. - * - * @return {this} This CanvasRenderer object. - */ - setAlpha: function (alpha) - { - this.currentContext.globalAlpha = alpha; - - return this; - }, - - /** - * Called at the start of the render loop. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#preRender - * @since 3.0.0 - */ - preRender: function () - { - var ctx = this.gameContext; - var config = this.config; - - var width = this.width; - var height = this.height; - - ctx.globalAlpha = 1; - ctx.globalCompositeOperation = 'source-over'; - ctx.setTransform(1, 0, 0, 1, 0, 0); - - if (config.clearBeforeRender) - { - ctx.clearRect(0, 0, width, height); - } - - if (!config.transparent) - { - ctx.fillStyle = config.backgroundColor.rgba; - ctx.fillRect(0, 0, width, height); - } - - ctx.save(); - - this.drawCount = 0; - }, - - /** - * Renders the Scene to the given Camera. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#render - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to render. - * @param {Phaser.GameObjects.DisplayList} children - The Game Objects within the Scene to be rendered. - * @param {number} interpolationPercentage - The interpolation percentage to apply. Currently unused. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera to render with. - */ - render: function (scene, children, interpolationPercentage, camera) - { - var list = children.list; - var childCount = list.length; - - var cx = camera._cx; - var cy = camera._cy; - var cw = camera._cw; - var ch = camera._ch; - - var ctx = (camera.renderToTexture) ? camera.context : scene.sys.context; - - // Save context pre-clip - ctx.save(); - - if (this.game.scene.customViewports) - { - ctx.beginPath(); - ctx.rect(cx, cy, cw, ch); - ctx.clip(); - } - - this.currentContext = ctx; - - var mask = camera.mask; - - if (mask) - { - mask.preRenderCanvas(this, null, camera._maskCamera); - } - - if (!camera.transparent) - { - ctx.fillStyle = camera.backgroundColor.rgba; - ctx.fillRect(cx, cy, cw, ch); - } - - ctx.globalAlpha = camera.alpha; - - ctx.globalCompositeOperation = 'source-over'; - - this.drawCount += list.length; - - if (camera.renderToTexture) - { - camera.emit(CameraEvents.PRE_RENDER, camera); - } - - camera.matrix.copyToContext(ctx); - - for (var i = 0; i < childCount; i++) - { - var child = list[i]; - - if (!child.willRender(camera)) - { - continue; - } - - if (child.mask) - { - child.mask.preRenderCanvas(this, child, camera); - } - - child.renderCanvas(this, child, interpolationPercentage, camera); - - if (child.mask) - { - child.mask.postRenderCanvas(this, child, camera); - } - } - - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.globalCompositeOperation = 'source-over'; - ctx.globalAlpha = 1; - - camera.flashEffect.postRenderCanvas(ctx); - camera.fadeEffect.postRenderCanvas(ctx); - - camera.dirty = false; - - if (mask) - { - mask.postRenderCanvas(this); - } - - // Restore pre-clip context - ctx.restore(); - - if (camera.renderToTexture) - { - camera.emit(CameraEvents.POST_RENDER, camera); - - if (camera.renderToGame) - { - scene.sys.context.drawImage(camera.canvas, cx, cy); - } - } - }, - - /** - * Restores the game context's global settings and takes a snapshot if one is scheduled. - * - * The post-render step happens after all Cameras in all Scenes have been rendered. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#postRender - * @since 3.0.0 - */ - postRender: function () - { - var ctx = this.gameContext; - - ctx.restore(); - - var state = this.snapshotState; - - if (state.callback) - { - CanvasSnapshot(this.gameCanvas, state); - - state.callback = null; - } - }, - - /** - * Takes a snapshot of the given area of the given canvas. - * - * Unlike the other snapshot methods, this one is processed immediately and doesn't wait for the next render. - * - * Snapshots work by creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshotCanvas - * @since 3.19.0 - * - * @param {HTMLCanvasElement} canvas - The canvas to grab from. - * @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 {integer} [x=0] - The x coordinate to grab from. - * @param {integer} [y=0] - The y coordinate to grab from. - * @param {integer} [width=canvas.width] - The width of the area to grab. - * @param {integer} [height=canvas.height] - 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 Canvas Renderer. - */ - snapshotCanvas: function (canvas, callback, getPixel, x, y, width, height, type, encoderOptions) - { - if (getPixel === undefined) { getPixel = false; } - - this.snapshotArea(x, y, width, height, callback, type, encoderOptions); - - var state = this.snapshotState; - - state.getPixel = getPixel; - - CanvasSnapshot(this.canvas, state); - - state.callback = null; - - return this; - }, - - /** - * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. - * - * To capture a specific area see the `snapshotArea` 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 creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshot - * @since 3.0.0 - * - * @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. - */ - snapshot: function (callback, type, encoderOptions) - { - return this.snapshotArea(0, 0, this.gameCanvas.width, this.gameCanvas.height, callback, type, encoderOptions); - }, - - /** - * 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 creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshotArea - * @since 3.16.0 - * - * @param {integer} x - The x coordinate to grab from. - * @param {integer} y - The y coordinate to grab from. - * @param {integer} width - The width of the area to grab. - * @param {integer} 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. - */ - snapshotArea: function (x, y, width, height, callback, type, encoderOptions) - { - var state = this.snapshotState; - - state.callback = callback; - state.type = type; - state.encoder = encoderOptions; - state.getPixel = false; - state.x = x; - state.y = y; - state.width = Math.min(width, this.gameCanvas.width); - state.height = Math.min(height, this.gameCanvas.height); - - return this; - }, - - /** - * 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.Canvas.CanvasRenderer#snapshotPixel - * @since 3.16.0 - * - * @param {integer} x - The x coordinate of the pixel to get. - * @param {integer} y - The y coordinate of the pixel to get. - * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. - * - * @return {this} This WebGL Renderer. - */ - snapshotPixel: function (x, y, callback) - { - this.snapshotArea(x, y, 1, 1, callback); - - this.snapshotState.getPixel = true; - - return this; - }, - - /** - * Takes a Sprite Game Object, or any object that extends it, and draws it to the current context. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#batchSprite - * @since 3.12.0 - * - * @param {Phaser.GameObjects.GameObject} sprite - The texture based Game Object to draw. - * @param {Phaser.Textures.Frame} frame - The frame to draw, doesn't have to be that owned by the Game Object. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - The transform matrix of the parent container, if set. - */ - batchSprite: function (sprite, frame, camera, parentTransformMatrix) - { - var alpha = camera.alpha * sprite.alpha; - - if (alpha === 0) - { - // Nothing to see, so abort early - return; - } - - var ctx = this.currentContext; - - var camMatrix = this._tempMatrix1; - var spriteMatrix = this._tempMatrix2; - var calcMatrix = this._tempMatrix3; - - var cd = frame.canvasData; - - var frameX = cd.x; - var frameY = cd.y; - var frameWidth = frame.cutWidth; - var frameHeight = frame.cutHeight; - var customPivot = frame.customPivot; - - var res = frame.source.resolution; - - var displayOriginX = sprite.displayOriginX; - var displayOriginY = sprite.displayOriginY; - - var x = -displayOriginX + frame.x; - var y = -displayOriginY + frame.y; - - if (sprite.isCropped) - { - var crop = sprite._crop; - - if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) - { - frame.updateCropUVs(crop, sprite.flipX, sprite.flipY); - } - - frameWidth = crop.cw; - frameHeight = crop.ch; - - frameX = crop.cx; - frameY = crop.cy; - - x = -displayOriginX + crop.x; - y = -displayOriginY + crop.y; - - if (sprite.flipX) - { - if (x >= 0) - { - x = -(x + frameWidth); - } - else if (x < 0) - { - x = (Math.abs(x) - frameWidth); - } - } - - if (sprite.flipY) - { - if (y >= 0) - { - y = -(y + frameHeight); - } - else if (y < 0) - { - y = (Math.abs(y) - frameHeight); - } - } - } - - var flipX = 1; - var flipY = 1; - - if (sprite.flipX) - { - if (!customPivot) - { - x += (-frame.realWidth + (displayOriginX * 2)); - } - - flipX = -1; - } - - // Auto-invert the flipY if this is coming from a GLTexture - if (sprite.flipY) - { - if (!customPivot) - { - y += (-frame.realHeight + (displayOriginY * 2)); - } - - flipY = -1; - } - - spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX * flipX, sprite.scaleY * flipY); - - camMatrix.copyFrom(camera.matrix); - - if (parentTransformMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = sprite.x; - spriteMatrix.f = sprite.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; - spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - ctx.save(); - - calcMatrix.setToContext(ctx); - - ctx.globalCompositeOperation = this.blendModes[sprite.blendMode]; - - ctx.globalAlpha = alpha; - - ctx.imageSmoothingEnabled = !(!this.antialias || frame.source.scaleMode); - - ctx.drawImage(frame.source.image, frameX, frameY, frameWidth, frameHeight, x, y, frameWidth / res, frameHeight / res); - - ctx.restore(); - }, - - /** - * Destroys all object references in the Canvas Renderer. - * - * @method Phaser.Renderer.Canvas.CanvasRenderer#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.gameCanvas = null; - this.gameContext = null; - - this.game = null; - } - -}); - -module.exports = CanvasRenderer; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasSnapshot = require('../snapshot/CanvasSnapshot'); +var CameraEvents = require('../../cameras/2d/events'); +var Class = require('../../utils/Class'); +var CONST = require('../../const'); +var GetBlendModes = require('./utils/GetBlendModes'); +var ScaleEvents = require('../../scale/events'); +var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); + +/** + * @classdesc + * The Canvas Renderer is responsible for managing 2D canvas rendering contexts, including the one used by the Game's canvas. It tracks the internal state of a given context and can renderer textured Game Objects to it, taking into account alpha, blending, and scaling. + * + * @class CanvasRenderer + * @memberof Phaser.Renderer.Canvas + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser Game instance that owns this renderer. + */ +var CanvasRenderer = new Class({ + + initialize: + + function CanvasRenderer (game) + { + /** + * The Phaser Game instance that owns this renderer. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * A constant which allows the renderer to be easily identified as a Canvas Renderer. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#type + * @type {integer} + * @since 3.0.0 + */ + this.type = CONST.CANVAS; + + /** + * The total number of Game Objects which were rendered in a frame. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#drawCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.drawCount = 0; + + /** + * The width of the canvas being rendered to. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#width + * @type {integer} + * @since 3.0.0 + */ + this.width = 0; + + /** + * The height of the canvas being rendered to. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#height + * @type {integer} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The local configuration settings of the CanvasRenderer. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#config + * @type {object} + * @since 3.0.0 + */ + this.config = { + clearBeforeRender: game.config.clearBeforeRender, + backgroundColor: game.config.backgroundColor, + resolution: game.config.resolution, + antialias: game.config.antialias, + roundPixels: game.config.roundPixels + }; + + /** + * The canvas element which the Game uses. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#gameCanvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.gameCanvas = game.canvas; + + var contextOptions = { + alpha: game.config.transparent, + desynchronized: game.config.desynchronized + }; + + /** + * The canvas context used to render all Cameras in all Scenes during the game loop. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#gameContext + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.gameContext = (this.game.config.context) ? this.game.config.context : this.gameCanvas.getContext('2d', contextOptions); + + /** + * The canvas context currently used by the CanvasRenderer for all rendering operations. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#currentContext + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.currentContext = this.gameContext; + + /** + * Should the Canvas use Image Smoothing or not when drawing Sprites? + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#antialias + * @type {boolean} + * @since 3.20.0 + */ + this.antialias = game.config.antialias; + + /** + * The blend modes supported by the Canvas Renderer. + * + * This object maps the {@link Phaser.BlendModes} to canvas compositing operations. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#blendModes + * @type {array} + * @since 3.0.0 + */ + this.blendModes = GetBlendModes(); + + /** + * Details about the currently scheduled snapshot. + * + * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#snapshotState + * @type {Phaser.Types.Renderer.Snapshot.SnapshotState} + * @since 3.16.0 + */ + this.snapshotState = { + x: 0, + y: 0, + width: 1, + height: 1, + getPixel: false, + callback: null, + type: 'image/png', + encoder: 0.92 + }; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.Canvas.CanvasRenderer#_tempMatrix4 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix4 = new TransformMatrix(); + + this.init(); + }, + + /** + * Prepares the game canvas for rendering. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#init + * @since 3.0.0 + */ + init: function () + { + this.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); + + var baseSize = this.game.scale.baseSize; + + this.resize(baseSize.width, baseSize.height); + }, + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#onResize + * @since 3.16.0 + * + * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. + * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + * @param {Phaser.Structs.Size} displaySize - The display Size object. The size of the canvas style width / height attributes. + * @param {number} [resolution] - The Scale Manager resolution setting. + */ + onResize: function (gameSize, baseSize) + { + // Has the underlying canvas size changed? + if (baseSize.width !== this.width || baseSize.height !== this.height) + { + this.resize(baseSize.width, baseSize.height); + } + }, + + /** + * Resize the main game canvas. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#resize + * @since 3.0.0 + * + * @param {number} [width] - The new width of the renderer. + * @param {number} [height] - The new height of the renderer. + */ + resize: function (width, height) + { + this.width = width; + this.height = height; + }, + + /** + * Resets the transformation matrix of the current context to the identity matrix, thus resetting any transformation. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#resetTransform + * @since 3.0.0 + */ + resetTransform: function () + { + this.currentContext.setTransform(1, 0, 0, 1, 0, 0); + }, + + /** + * Sets the blend mode (compositing operation) of the current context. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#setBlendMode + * @since 3.0.0 + * + * @param {string} blendMode - The new blend mode which should be used. + * + * @return {this} This CanvasRenderer object. + */ + setBlendMode: function (blendMode) + { + this.currentContext.globalCompositeOperation = blendMode; + + return this; + }, + + /** + * Changes the Canvas Rendering Context that all draw operations are performed against. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#setContext + * @since 3.12.0 + * + * @param {?CanvasRenderingContext2D} [ctx] - The new Canvas Rendering Context to draw everything to. Leave empty to reset to the Game Canvas. + * + * @return {this} The Canvas Renderer instance. + */ + setContext: function (ctx) + { + this.currentContext = (ctx) ? ctx : this.gameContext; + + return this; + }, + + /** + * Sets the global alpha of the current context. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#setAlpha + * @since 3.0.0 + * + * @param {number} alpha - The new alpha to use, where 0 is fully transparent and 1 is fully opaque. + * + * @return {this} This CanvasRenderer object. + */ + setAlpha: function (alpha) + { + this.currentContext.globalAlpha = alpha; + + return this; + }, + + /** + * Called at the start of the render loop. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#preRender + * @since 3.0.0 + */ + preRender: function () + { + var ctx = this.gameContext; + var config = this.config; + + var width = this.width; + var height = this.height; + + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = 'source-over'; + ctx.setTransform(1, 0, 0, 1, 0, 0); + + if (config.clearBeforeRender) + { + ctx.clearRect(0, 0, width, height); + } + + if (!config.transparent) + { + ctx.fillStyle = config.backgroundColor.rgba; + ctx.fillRect(0, 0, width, height); + } + + ctx.save(); + + this.drawCount = 0; + }, + + /** + * Renders the Scene to the given Camera. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#render + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to render. + * @param {Phaser.GameObjects.DisplayList} children - The Game Objects within the Scene to be rendered. + * @param {number} interpolationPercentage - The interpolation percentage to apply. Currently unused. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera to render with. + */ + render: function (scene, children, interpolationPercentage, camera) + { + var list = children.list; + var childCount = list.length; + + var cx = camera._cx; + var cy = camera._cy; + var cw = camera._cw; + var ch = camera._ch; + + var ctx = (camera.renderToTexture) ? camera.context : scene.sys.context; + + // Save context pre-clip + ctx.save(); + + if (this.game.scene.customViewports) + { + ctx.beginPath(); + ctx.rect(cx, cy, cw, ch); + ctx.clip(); + } + + this.currentContext = ctx; + + var mask = camera.mask; + + if (mask) + { + mask.preRenderCanvas(this, null, camera._maskCamera); + } + + if (!camera.transparent) + { + ctx.fillStyle = camera.backgroundColor.rgba; + ctx.fillRect(cx, cy, cw, ch); + } + + ctx.globalAlpha = camera.alpha; + + ctx.globalCompositeOperation = 'source-over'; + + this.drawCount += list.length; + + if (camera.renderToTexture) + { + camera.emit(CameraEvents.PRE_RENDER, camera); + } + + camera.matrix.copyToContext(ctx); + + for (var i = 0; i < childCount; i++) + { + var child = list[i]; + + if (!child.willRender(camera)) + { + continue; + } + + if (child.mask) + { + child.mask.preRenderCanvas(this, child, camera); + } + + child.renderCanvas(this, child, interpolationPercentage, camera); + + if (child.mask) + { + child.mask.postRenderCanvas(this, child, camera); + } + } + + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalCompositeOperation = 'source-over'; + ctx.globalAlpha = 1; + + camera.flashEffect.postRenderCanvas(ctx); + camera.fadeEffect.postRenderCanvas(ctx); + + camera.dirty = false; + + if (mask) + { + mask.postRenderCanvas(this); + } + + // Restore pre-clip context + ctx.restore(); + + if (camera.renderToTexture) + { + camera.emit(CameraEvents.POST_RENDER, camera); + + if (camera.renderToGame) + { + scene.sys.context.drawImage(camera.canvas, cx, cy); + } + } + }, + + /** + * Restores the game context's global settings and takes a snapshot if one is scheduled. + * + * The post-render step happens after all Cameras in all Scenes have been rendered. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#postRender + * @since 3.0.0 + */ + postRender: function () + { + var ctx = this.gameContext; + + ctx.restore(); + + var state = this.snapshotState; + + if (state.callback) + { + CanvasSnapshot(this.gameCanvas, state); + + state.callback = null; + } + }, + + /** + * Takes a snapshot of the given area of the given canvas. + * + * Unlike the other snapshot methods, this one is processed immediately and doesn't wait for the next render. + * + * Snapshots work by creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshotCanvas + * @since 3.19.0 + * + * @param {HTMLCanvasElement} canvas - The canvas to grab from. + * @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 {integer} [x=0] - The x coordinate to grab from. + * @param {integer} [y=0] - The y coordinate to grab from. + * @param {integer} [width=canvas.width] - The width of the area to grab. + * @param {integer} [height=canvas.height] - 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 Canvas Renderer. + */ + snapshotCanvas: function (canvas, callback, getPixel, x, y, width, height, type, encoderOptions) + { + if (getPixel === undefined) { getPixel = false; } + + this.snapshotArea(x, y, width, height, callback, type, encoderOptions); + + var state = this.snapshotState; + + state.getPixel = getPixel; + + CanvasSnapshot(this.canvas, state); + + state.callback = null; + + return this; + }, + + /** + * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. + * + * To capture a specific area see the `snapshotArea` 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 creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshot + * @since 3.0.0 + * + * @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. + */ + snapshot: function (callback, type, encoderOptions) + { + return this.snapshotArea(0, 0, this.gameCanvas.width, this.gameCanvas.height, callback, type, encoderOptions); + }, + + /** + * 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 creating an Image object from the canvas data, this is a 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.Canvas.CanvasRenderer#snapshotArea + * @since 3.16.0 + * + * @param {integer} x - The x coordinate to grab from. + * @param {integer} y - The y coordinate to grab from. + * @param {integer} width - The width of the area to grab. + * @param {integer} 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. + */ + snapshotArea: function (x, y, width, height, callback, type, encoderOptions) + { + var state = this.snapshotState; + + state.callback = callback; + state.type = type; + state.encoder = encoderOptions; + state.getPixel = false; + state.x = x; + state.y = y; + state.width = Math.min(width, this.gameCanvas.width); + state.height = Math.min(height, this.gameCanvas.height); + + return this; + }, + + /** + * 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.Canvas.CanvasRenderer#snapshotPixel + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the pixel to get. + * @param {integer} y - The y coordinate of the pixel to get. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. + * + * @return {this} This WebGL Renderer. + */ + snapshotPixel: function (x, y, callback) + { + this.snapshotArea(x, y, 1, 1, callback); + + this.snapshotState.getPixel = true; + + return this; + }, + + /** + * Takes a Sprite Game Object, or any object that extends it, and draws it to the current context. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#batchSprite + * @since 3.12.0 + * + * @param {Phaser.GameObjects.GameObject} sprite - The texture based Game Object to draw. + * @param {Phaser.Textures.Frame} frame - The frame to draw, doesn't have to be that owned by the Game Object. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - The transform matrix of the parent container, if set. + */ + batchSprite: function (sprite, frame, camera, parentTransformMatrix) + { + var alpha = camera.alpha * sprite.alpha; + + if (alpha === 0) + { + // Nothing to see, so abort early + return; + } + + var ctx = this.currentContext; + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var cd = frame.canvasData; + + var frameX = cd.x; + var frameY = cd.y; + var frameWidth = frame.cutWidth; + var frameHeight = frame.cutHeight; + var customPivot = frame.customPivot; + + var res = frame.source.resolution; + + var displayOriginX = sprite.displayOriginX; + var displayOriginY = sprite.displayOriginY; + + var x = -displayOriginX + frame.x; + var y = -displayOriginY + frame.y; + + if (sprite.isCropped) + { + var crop = sprite._crop; + + if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) + { + frame.updateCropUVs(crop, sprite.flipX, sprite.flipY); + } + + frameWidth = crop.cw; + frameHeight = crop.ch; + + frameX = crop.cx; + frameY = crop.cy; + + x = -displayOriginX + crop.x; + y = -displayOriginY + crop.y; + + if (sprite.flipX) + { + if (x >= 0) + { + x = -(x + frameWidth); + } + else if (x < 0) + { + x = (Math.abs(x) - frameWidth); + } + } + + if (sprite.flipY) + { + if (y >= 0) + { + y = -(y + frameHeight); + } + else if (y < 0) + { + y = (Math.abs(y) - frameHeight); + } + } + } + + var flipX = 1; + var flipY = 1; + + if (sprite.flipX) + { + if (!customPivot) + { + x += (-frame.realWidth + (displayOriginX * 2)); + } + + flipX = -1; + } + + // Auto-invert the flipY if this is coming from a GLTexture + if (sprite.flipY) + { + if (!customPivot) + { + y += (-frame.realHeight + (displayOriginY * 2)); + } + + flipY = -1; + } + + spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX * flipX, sprite.scaleY * flipY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = sprite.x; + spriteMatrix.f = sprite.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; + spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + ctx.save(); + + calcMatrix.setToContext(ctx); + + ctx.globalCompositeOperation = this.blendModes[sprite.blendMode]; + + ctx.globalAlpha = alpha; + + ctx.imageSmoothingEnabled = !(!this.antialias || frame.source.scaleMode); + + ctx.drawImage(frame.source.image, frameX, frameY, frameWidth, frameHeight, x, y, frameWidth / res, frameHeight / res); + + ctx.restore(); + }, + + /** + * Destroys all object references in the Canvas Renderer. + * + * @method Phaser.Renderer.Canvas.CanvasRenderer#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.gameCanvas = null; + this.gameContext = null; + + this.game = null; + } + +}); + +module.exports = CanvasRenderer; diff --git a/src/renderer/canvas/index.js b/src/renderer/canvas/index.js index da088d3c8..882e83e85 100644 --- a/src/renderer/canvas/index.js +++ b/src/renderer/canvas/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.Canvas - */ - -module.exports = { - - CanvasRenderer: require('./CanvasRenderer'), - GetBlendModes: require('./utils/GetBlendModes'), - SetTransform: require('./utils/SetTransform') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.Canvas + */ + +module.exports = { + + CanvasRenderer: require('./CanvasRenderer'), + GetBlendModes: require('./utils/GetBlendModes'), + SetTransform: require('./utils/SetTransform') + +}; diff --git a/src/renderer/canvas/utils/GetBlendModes.js b/src/renderer/canvas/utils/GetBlendModes.js index 9b5830a30..82ccb4208 100644 --- a/src/renderer/canvas/utils/GetBlendModes.js +++ b/src/renderer/canvas/utils/GetBlendModes.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var modes = require('../../BlendModes'); -var CanvasFeatures = require('../../../device/CanvasFeatures'); - -/** - * Returns an array which maps the default blend modes to supported Canvas blend modes. - * - * If the browser doesn't support a blend mode, it will default to the normal `source-over` blend mode. - * - * @function Phaser.Renderer.Canvas.GetBlendModes - * @since 3.0.0 - * - * @return {array} Which Canvas blend mode corresponds to which default Phaser blend mode. - */ -var GetBlendModes = function () -{ - var output = []; - var useNew = CanvasFeatures.supportNewBlendModes; - var so = 'source-over'; - - output[modes.NORMAL] = so; - output[modes.ADD] = 'lighter'; - output[modes.MULTIPLY] = (useNew) ? 'multiply' : so; - output[modes.SCREEN] = (useNew) ? 'screen' : so; - output[modes.OVERLAY] = (useNew) ? 'overlay' : so; - output[modes.DARKEN] = (useNew) ? 'darken' : so; - output[modes.LIGHTEN] = (useNew) ? 'lighten' : so; - output[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : so; - output[modes.COLOR_BURN] = (useNew) ? 'color-burn' : so; - output[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : so; - output[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : so; - output[modes.DIFFERENCE] = (useNew) ? 'difference' : so; - output[modes.EXCLUSION] = (useNew) ? 'exclusion' : so; - output[modes.HUE] = (useNew) ? 'hue' : so; - output[modes.SATURATION] = (useNew) ? 'saturation' : so; - output[modes.COLOR] = (useNew) ? 'color' : so; - output[modes.LUMINOSITY] = (useNew) ? 'luminosity' : so; - output[modes.ERASE] = 'destination-out'; - output[modes.SOURCE_IN] = 'source-in'; - output[modes.SOURCE_OUT] = 'source-out'; - output[modes.SOURCE_ATOP] = 'source-atop'; - output[modes.DESTINATION_OVER] = 'destination-over'; - output[modes.DESTINATION_IN] = 'destination-in'; - output[modes.DESTINATION_OUT] = 'destination-out'; - output[modes.DESTINATION_ATOP] = 'destination-atop'; - output[modes.LIGHTER] = 'lighter'; - output[modes.COPY] = 'copy'; - output[modes.XOR] = 'xor'; - - return output; -}; - -module.exports = GetBlendModes; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var modes = require('../../BlendModes'); +var CanvasFeatures = require('../../../device/CanvasFeatures'); + +/** + * Returns an array which maps the default blend modes to supported Canvas blend modes. + * + * If the browser doesn't support a blend mode, it will default to the normal `source-over` blend mode. + * + * @function Phaser.Renderer.Canvas.GetBlendModes + * @since 3.0.0 + * + * @return {array} Which Canvas blend mode corresponds to which default Phaser blend mode. + */ +var GetBlendModes = function () +{ + var output = []; + var useNew = CanvasFeatures.supportNewBlendModes; + var so = 'source-over'; + + output[modes.NORMAL] = so; + output[modes.ADD] = 'lighter'; + output[modes.MULTIPLY] = (useNew) ? 'multiply' : so; + output[modes.SCREEN] = (useNew) ? 'screen' : so; + output[modes.OVERLAY] = (useNew) ? 'overlay' : so; + output[modes.DARKEN] = (useNew) ? 'darken' : so; + output[modes.LIGHTEN] = (useNew) ? 'lighten' : so; + output[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : so; + output[modes.COLOR_BURN] = (useNew) ? 'color-burn' : so; + output[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : so; + output[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : so; + output[modes.DIFFERENCE] = (useNew) ? 'difference' : so; + output[modes.EXCLUSION] = (useNew) ? 'exclusion' : so; + output[modes.HUE] = (useNew) ? 'hue' : so; + output[modes.SATURATION] = (useNew) ? 'saturation' : so; + output[modes.COLOR] = (useNew) ? 'color' : so; + output[modes.LUMINOSITY] = (useNew) ? 'luminosity' : so; + output[modes.ERASE] = 'destination-out'; + output[modes.SOURCE_IN] = 'source-in'; + output[modes.SOURCE_OUT] = 'source-out'; + output[modes.SOURCE_ATOP] = 'source-atop'; + output[modes.DESTINATION_OVER] = 'destination-over'; + output[modes.DESTINATION_IN] = 'destination-in'; + output[modes.DESTINATION_OUT] = 'destination-out'; + output[modes.DESTINATION_ATOP] = 'destination-atop'; + output[modes.LIGHTER] = 'lighter'; + output[modes.COPY] = 'copy'; + output[modes.XOR] = 'xor'; + + return output; +}; + +module.exports = GetBlendModes; diff --git a/src/renderer/canvas/utils/SetTransform.js b/src/renderer/canvas/utils/SetTransform.js index 4849b0fa7..1e4a5402d 100644 --- a/src/renderer/canvas/utils/SetTransform.js +++ b/src/renderer/canvas/utils/SetTransform.js @@ -1,82 +1,82 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. - * - * 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`. - */ -var SetTransform = function (renderer, ctx, src, camera, parentMatrix) -{ - var alpha = camera.alpha * src.alpha; - - if (alpha <= 0) - { - // Nothing to see, so don't waste time calculating stuff - return false; - } - - var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); - var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - var calcMatrix = renderer._tempMatrix3; - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - gameObjectMatrix.e = src.x; - gameObjectMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(gameObjectMatrix, calcMatrix); - } - else - { - gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; - gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(gameObjectMatrix, calcMatrix); - } - - // Blend Mode - ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; - - // Alpha - ctx.globalAlpha = alpha; - - ctx.save(); - - calcMatrix.setToContext(ctx); - - ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); - - return true; -}; - -module.exports = SetTransform; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. + * + * 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`. + */ +var SetTransform = function (renderer, ctx, src, camera, parentMatrix) +{ + var alpha = camera.alpha * src.alpha; + + if (alpha <= 0) + { + // Nothing to see, so don't waste time calculating stuff + return false; + } + + var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); + var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + var calcMatrix = renderer._tempMatrix3; + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + gameObjectMatrix.e = src.x; + gameObjectMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + else + { + gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; + gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(gameObjectMatrix, calcMatrix); + } + + // Blend Mode + ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; + + // Alpha + ctx.globalAlpha = alpha; + + ctx.save(); + + calcMatrix.setToContext(ctx); + + ctx.imageSmoothingEnabled = !(!renderer.antialias || (src.frame && src.frame.source.scaleMode)); + + return true; +}; + +module.exports = SetTransform; diff --git a/src/renderer/index.js b/src/renderer/index.js index 51347ea77..4599bc19d 100644 --- a/src/renderer/index.js +++ b/src/renderer/index.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer - */ - -/** - * @namespace Phaser.Types.Renderer - */ - -module.exports = { - - Canvas: require('./canvas'), - Snapshot: require('./snapshot'), - WebGL: require('./webgl') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer + */ + +/** + * @namespace Phaser.Types.Renderer + */ + +module.exports = { + + Canvas: require('./canvas'), + Snapshot: require('./snapshot'), + WebGL: require('./webgl') + +}; diff --git a/src/renderer/snapshot/CanvasSnapshot.js b/src/renderer/snapshot/CanvasSnapshot.js index 76a523bcb..5a05a9aa7 100644 --- a/src/renderer/snapshot/CanvasSnapshot.js +++ b/src/renderer/snapshot/CanvasSnapshot.js @@ -1,87 +1,87 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../../display/canvas/CanvasPool'); -var Color = require('../../display/color/Color'); -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * Takes a snapshot of an area from the current frame displayed by a canvas. - * - * This is then copied to an Image object. When this loads, the results are sent - * to the callback provided in the Snapshot Configuration object. - * - * @function Phaser.Renderer.Snapshot.Canvas - * @since 3.0.0 - * - * @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of. - * @param {Phaser.Types.Renderer.Snapshot.SnapshotState} config - The snapshot configuration object. - */ -var CanvasSnapshot = function (canvas, config) -{ - var callback = GetFastValue(config, 'callback'); - var type = GetFastValue(config, 'type', 'image/png'); - var encoderOptions = GetFastValue(config, 'encoder', 0.92); - var x = Math.abs(Math.round(GetFastValue(config, 'x', 0))); - var y = Math.abs(Math.round(GetFastValue(config, 'y', 0))); - var width = GetFastValue(config, 'width', canvas.width); - var height = GetFastValue(config, 'height', canvas.height); - var getPixel = GetFastValue(config, 'getPixel', false); - - if (getPixel) - { - var context = canvas.getContext('2d'); - var imageData = context.getImageData(x, y, 1, 1); - var data = imageData.data; - - callback.call(null, new Color(data[0], data[1], data[2], data[3] / 255)); - } - else if (x !== 0 || y !== 0 || width !== canvas.width || height !== canvas.height) - { - // Area Grab - var copyCanvas = CanvasPool.createWebGL(this, width, height); - var ctx = copyCanvas.getContext('2d'); - - ctx.drawImage(canvas, x, y, width, height, 0, 0, width, height); - - var image1 = new Image(); - - image1.onerror = function () - { - callback.call(null); - - CanvasPool.remove(copyCanvas); - }; - - image1.onload = function () - { - callback.call(null, image1); - - CanvasPool.remove(copyCanvas); - }; - - image1.src = copyCanvas.toDataURL(type, encoderOptions); - } - else - { - // Full Grab - var image2 = new Image(); - - image2.onerror = function () - { - callback.call(null); - }; - - image2.onload = function () - { - callback.call(null, image2); - }; - - image2.src = canvas.toDataURL(type, encoderOptions); - } -}; - -module.exports = CanvasSnapshot; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../../display/canvas/CanvasPool'); +var Color = require('../../display/color/Color'); +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * Takes a snapshot of an area from the current frame displayed by a canvas. + * + * This is then copied to an Image object. When this loads, the results are sent + * to the callback provided in the Snapshot Configuration object. + * + * @function Phaser.Renderer.Snapshot.Canvas + * @since 3.0.0 + * + * @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotState} config - The snapshot configuration object. + */ +var CanvasSnapshot = function (canvas, config) +{ + var callback = GetFastValue(config, 'callback'); + var type = GetFastValue(config, 'type', 'image/png'); + var encoderOptions = GetFastValue(config, 'encoder', 0.92); + var x = Math.abs(Math.round(GetFastValue(config, 'x', 0))); + var y = Math.abs(Math.round(GetFastValue(config, 'y', 0))); + var width = GetFastValue(config, 'width', canvas.width); + var height = GetFastValue(config, 'height', canvas.height); + var getPixel = GetFastValue(config, 'getPixel', false); + + if (getPixel) + { + var context = canvas.getContext('2d'); + var imageData = context.getImageData(x, y, 1, 1); + var data = imageData.data; + + callback.call(null, new Color(data[0], data[1], data[2], data[3] / 255)); + } + else if (x !== 0 || y !== 0 || width !== canvas.width || height !== canvas.height) + { + // Area Grab + var copyCanvas = CanvasPool.createWebGL(this, width, height); + var ctx = copyCanvas.getContext('2d'); + + ctx.drawImage(canvas, x, y, width, height, 0, 0, width, height); + + var image1 = new Image(); + + image1.onerror = function () + { + callback.call(null); + + CanvasPool.remove(copyCanvas); + }; + + image1.onload = function () + { + callback.call(null, image1); + + CanvasPool.remove(copyCanvas); + }; + + image1.src = copyCanvas.toDataURL(type, encoderOptions); + } + else + { + // Full Grab + var image2 = new Image(); + + image2.onerror = function () + { + callback.call(null); + }; + + image2.onload = function () + { + callback.call(null, image2); + }; + + image2.src = canvas.toDataURL(type, encoderOptions); + } +}; + +module.exports = CanvasSnapshot; diff --git a/src/renderer/snapshot/WebGLSnapshot.js b/src/renderer/snapshot/WebGLSnapshot.js index d587e2e47..79647c58d 100644 --- a/src/renderer/snapshot/WebGLSnapshot.js +++ b/src/renderer/snapshot/WebGLSnapshot.js @@ -1,104 +1,104 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../../display/canvas/CanvasPool'); -var Color = require('../../display/color/Color'); -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * Takes a snapshot of an area from the current frame displayed by a WebGL canvas. - * - * This is then copied to an Image object. When this loads, the results are sent - * to the callback provided in the Snapshot Configuration object. - * - * @function Phaser.Renderer.Snapshot.WebGL - * @since 3.0.0 - * - * @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of. - * @param {Phaser.Types.Renderer.Snapshot.SnapshotState} config - The snapshot configuration object. - */ -var WebGLSnapshot = function (sourceCanvas, config) -{ - var gl = sourceCanvas.getContext('experimental-webgl'); - - var callback = GetFastValue(config, 'callback'); - var type = GetFastValue(config, 'type', 'image/png'); - var encoderOptions = GetFastValue(config, 'encoder', 0.92); - var x = GetFastValue(config, 'x', 0); - var y = GetFastValue(config, 'y', 0); - - var getPixel = GetFastValue(config, 'getPixel', false); - - var isFramebuffer = GetFastValue(config, 'isFramebuffer', false); - - var bufferWidth = (isFramebuffer) ? GetFastValue(config, 'bufferWidth', 1) : gl.drawingBufferWidth; - var bufferHeight = (isFramebuffer) ? GetFastValue(config, 'bufferHeight', 1) : gl.drawingBufferHeight; - - if (getPixel) - { - var pixel = new Uint8Array(4); - - var destY = (isFramebuffer) ? y : bufferHeight - y; - - gl.readPixels(x, destY, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); - - callback.call(null, new Color(pixel[0], pixel[1], pixel[2], pixel[3] / 255)); - } - else - { - var width = GetFastValue(config, 'width', bufferWidth); - var height = GetFastValue(config, 'height', bufferHeight); - - var total = width * height * 4; - - var pixels = new Uint8Array(total); - - gl.readPixels(x, bufferHeight - y - height, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - - var canvas = CanvasPool.createWebGL(this, width, height); - var ctx = canvas.getContext('2d'); - - var imageData = ctx.getImageData(0, 0, width, height); - - var data = imageData.data; - - for (var py = 0; py < height; py++) - { - for (var px = 0; px < width; px++) - { - var sourceIndex = ((height - py) * width + px) * 4; - var destIndex = (isFramebuffer) ? total - ((py * width + (width - px)) * 4) : (py * width + px) * 4; - - data[destIndex + 0] = pixels[sourceIndex + 0]; - data[destIndex + 1] = pixels[sourceIndex + 1]; - data[destIndex + 2] = pixels[sourceIndex + 2]; - data[destIndex + 3] = pixels[sourceIndex + 3]; - } - } - - ctx.putImageData(imageData, 0, 0); - - var image = new Image(); - - image.onerror = function () - { - callback.call(null); - - CanvasPool.remove(canvas); - }; - - image.onload = function () - { - callback.call(null, image); - - CanvasPool.remove(canvas); - }; - - image.src = canvas.toDataURL(type, encoderOptions); - } -}; - -module.exports = WebGLSnapshot; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../../display/canvas/CanvasPool'); +var Color = require('../../display/color/Color'); +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * Takes a snapshot of an area from the current frame displayed by a WebGL canvas. + * + * This is then copied to an Image object. When this loads, the results are sent + * to the callback provided in the Snapshot Configuration object. + * + * @function Phaser.Renderer.Snapshot.WebGL + * @since 3.0.0 + * + * @param {HTMLCanvasElement} sourceCanvas - The canvas to take a snapshot of. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotState} config - The snapshot configuration object. + */ +var WebGLSnapshot = function (sourceCanvas, config) +{ + var gl = sourceCanvas.getContext('experimental-webgl'); + + var callback = GetFastValue(config, 'callback'); + var type = GetFastValue(config, 'type', 'image/png'); + var encoderOptions = GetFastValue(config, 'encoder', 0.92); + var x = GetFastValue(config, 'x', 0); + var y = GetFastValue(config, 'y', 0); + + var getPixel = GetFastValue(config, 'getPixel', false); + + var isFramebuffer = GetFastValue(config, 'isFramebuffer', false); + + var bufferWidth = (isFramebuffer) ? GetFastValue(config, 'bufferWidth', 1) : gl.drawingBufferWidth; + var bufferHeight = (isFramebuffer) ? GetFastValue(config, 'bufferHeight', 1) : gl.drawingBufferHeight; + + if (getPixel) + { + var pixel = new Uint8Array(4); + + var destY = (isFramebuffer) ? y : bufferHeight - y; + + gl.readPixels(x, destY, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); + + callback.call(null, new Color(pixel[0], pixel[1], pixel[2], pixel[3] / 255)); + } + else + { + var width = GetFastValue(config, 'width', bufferWidth); + var height = GetFastValue(config, 'height', bufferHeight); + + var total = width * height * 4; + + var pixels = new Uint8Array(total); + + gl.readPixels(x, bufferHeight - y - height, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + + var canvas = CanvasPool.createWebGL(this, width, height); + var ctx = canvas.getContext('2d'); + + var imageData = ctx.getImageData(0, 0, width, height); + + var data = imageData.data; + + for (var py = 0; py < height; py++) + { + for (var px = 0; px < width; px++) + { + var sourceIndex = ((height - py) * width + px) * 4; + var destIndex = (isFramebuffer) ? total - ((py * width + (width - px)) * 4) : (py * width + px) * 4; + + data[destIndex + 0] = pixels[sourceIndex + 0]; + data[destIndex + 1] = pixels[sourceIndex + 1]; + data[destIndex + 2] = pixels[sourceIndex + 2]; + data[destIndex + 3] = pixels[sourceIndex + 3]; + } + } + + ctx.putImageData(imageData, 0, 0); + + var image = new Image(); + + image.onerror = function () + { + callback.call(null); + + CanvasPool.remove(canvas); + }; + + image.onload = function () + { + callback.call(null, image); + + CanvasPool.remove(canvas); + }; + + image.src = canvas.toDataURL(type, encoderOptions); + } +}; + +module.exports = WebGLSnapshot; diff --git a/src/renderer/snapshot/index.js b/src/renderer/snapshot/index.js index 67299651a..b5fb0e055 100644 --- a/src/renderer/snapshot/index.js +++ b/src/renderer/snapshot/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.Snapshot - */ - -module.exports = { - - Canvas: require('./CanvasSnapshot'), - WebGL: require('./WebGLSnapshot') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.Snapshot + */ + +module.exports = { + + Canvas: require('./CanvasSnapshot'), + WebGL: require('./WebGLSnapshot') + +}; diff --git a/src/renderer/snapshot/typedefs/index.js b/src/renderer/snapshot/typedefs/index.js index 4d13c21f1..d64921032 100644 --- a/src/renderer/snapshot/typedefs/index.js +++ b/src/renderer/snapshot/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Renderer.Snapshot - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Renderer.Snapshot + */ diff --git a/src/renderer/webgl/Utils.js b/src/renderer/webgl/Utils.js index 99436a6ed..204e77a2f 100644 --- a/src/renderer/webgl/Utils.js +++ b/src/renderer/webgl/Utils.js @@ -1,129 +1,129 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.WebGL.Utils - * @since 3.0.0 - */ -module.exports = { - - /** - * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats - * @since 3.0.0 - * - * @param {number} r - Red component in a range from 0.0 to 1.0 - * @param {number} g - Green component in a range from 0.0 to 1.0 - * @param {number} b - Blue component in a range from 0.0 to 1.0 - * @param {number} a - Alpha component in a range from 0.0 to 1.0 - * - * @return {number} The packed RGBA values as a Uint32. - */ - getTintFromFloats: function (r, g, b, a) - { - var ur = ((r * 255.0)|0) & 0xFF; - var ug = ((g * 255.0)|0) & 0xFF; - var ub = ((b * 255.0)|0) & 0xFF; - var ua = ((a * 255.0)|0) & 0xFF; - - return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; - }, - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha - * @since 3.0.0 - * - * @param {number} rgb - Uint24 representing RGB components - * @param {number} a - Float32 representing Alpha component - * - * @return {number} Packed RGBA as Uint32 - */ - getTintAppendFloatAlpha: function (rgb, a) - { - var ua = ((a * 255.0)|0) & 0xFF; - return ((ua << 24) | rgb) >>> 0; - }, - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a - * swizzled Uint32 - * - * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap - * @since 3.0.0 - * - * @param {number} rgb - Uint24 representing RGB components - * @param {number} a - Float32 representing Alpha component - * - * @return {number} Packed RGBA as Uint32 - */ - getTintAppendFloatAlphaAndSwap: function (rgb, a) - { - var ur = ((rgb >> 16)|0) & 0xff; - var ug = ((rgb >> 8)|0) & 0xff; - var ub = (rgb|0) & 0xff; - var ua = ((a * 255.0)|0) & 0xFF; - - return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; - }, - - /** - * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 - * - * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB - * @since 3.0.0 - * - * @param {number} rgb - RGB packed as a Uint24 - * - * @return {array} Array of floats representing each component as a float - */ - getFloatsFromUintRGB: function (rgb) - { - var ur = ((rgb >> 16)|0) & 0xff; - var ug = ((rgb >> 8)|0) & 0xff; - var ub = (rgb|0) & 0xff; - - return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; - }, - - /** - * Counts how many attributes of 32 bits a vertex has - * - * @function Phaser.Renderer.WebGL.Utils.getComponentCount - * @since 3.0.0 - * - * @param {array} attributes - Array of attributes - * @param {WebGLRenderingContext} glContext - WebGLContext used for check types - * - * @return {number} Count of 32 bit attributes in vertex - */ - getComponentCount: function (attributes, glContext) - { - var count = 0; - - for (var index = 0; index < attributes.length; ++index) - { - var element = attributes[index]; - - if (element.type === glContext.FLOAT) - { - count += element.size; - } - else - { - count += 1; // We'll force any other type to be 32 bit. for now - } - } - - return count; - } - -}; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.WebGL.Utils + * @since 3.0.0 + */ +module.exports = { + + /** + * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintFromFloats + * @since 3.0.0 + * + * @param {number} r - Red component in a range from 0.0 to 1.0 + * @param {number} g - Green component in a range from 0.0 to 1.0 + * @param {number} b - Blue component in a range from 0.0 to 1.0 + * @param {number} a - Alpha component in a range from 0.0 to 1.0 + * + * @return {number} The packed RGBA values as a Uint32. + */ + getTintFromFloats: function (r, g, b, a) + { + var ur = ((r * 255.0)|0) & 0xFF; + var ug = ((g * 255.0)|0) & 0xFF; + var ub = ((b * 255.0)|0) & 0xFF; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ur << 16) | (ug << 8) | ub) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlpha: function (rgb, a) + { + var ua = ((a * 255.0)|0) & 0xFF; + return ((ua << 24) | rgb) >>> 0; + }, + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a + * swizzled Uint32 + * + * @function Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlphaAndSwap + * @since 3.0.0 + * + * @param {number} rgb - Uint24 representing RGB components + * @param {number} a - Float32 representing Alpha component + * + * @return {number} Packed RGBA as Uint32 + */ + getTintAppendFloatAlphaAndSwap: function (rgb, a) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + var ua = ((a * 255.0)|0) & 0xFF; + + return ((ua << 24) | (ub << 16) | (ug << 8) | ur) >>> 0; + }, + + /** + * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 + * + * @function Phaser.Renderer.WebGL.Utils.getFloatsFromUintRGB + * @since 3.0.0 + * + * @param {number} rgb - RGB packed as a Uint24 + * + * @return {array} Array of floats representing each component as a float + */ + getFloatsFromUintRGB: function (rgb) + { + var ur = ((rgb >> 16)|0) & 0xff; + var ug = ((rgb >> 8)|0) & 0xff; + var ub = (rgb|0) & 0xff; + + return [ ur / 255.0, ug / 255.0, ub / 255.0 ]; + }, + + /** + * Counts how many attributes of 32 bits a vertex has + * + * @function Phaser.Renderer.WebGL.Utils.getComponentCount + * @since 3.0.0 + * + * @param {array} attributes - Array of attributes + * @param {WebGLRenderingContext} glContext - WebGLContext used for check types + * + * @return {number} Count of 32 bit attributes in vertex + */ + getComponentCount: function (attributes, glContext) + { + var count = 0; + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + + if (element.type === glContext.FLOAT) + { + count += element.size; + } + else + { + count += 1; // We'll force any other type to be 32 bit. for now + } + } + + return count; + } + +}; diff --git a/src/renderer/webgl/WebGLPipeline.js b/src/renderer/webgl/WebGLPipeline.js index 42c13c711..37f9c42d4 100644 --- a/src/renderer/webgl/WebGLPipeline.js +++ b/src/renderer/webgl/WebGLPipeline.js @@ -1,763 +1,763 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Utils = require('./Utils'); - -/** - * @classdesc - * WebGLPipeline is a class that describes the way elements will be renderered - * in WebGL, specially focused on batching vertices (batching is not provided). - * Pipelines are mostly used for describing 2D rendering passes but it's - * flexible enough to be used for any type of rendering including 3D. - * Internally WebGLPipeline will handle things like compiling shaders, - * creating vertex buffers, assigning primitive topology and binding - * vertex attributes. - * - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - gl: Current WebGL context. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - vertices: An optional buffer of vertices - * - attributes: An array describing the vertex attributes - * - * The vertex attributes properties are: - * - name : String - Name of the attribute in the vertex shader - * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 - * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) - * - normalized : boolean - Is the attribute normalized - * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C - * Here you can find more information of how to describe an attribute: - * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer - * - * @class WebGLPipeline - * @memberof Phaser.Renderer.WebGL - * @constructor - * @since 3.0.0 - * - * @param {object} config - The configuration object for this WebGL Pipeline, as described above. - */ -var WebGLPipeline = new Class({ - - initialize: - - function WebGLPipeline (config) - { - /** - * Name of the Pipeline. Used for identifying - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#name - * @type {string} - * @since 3.0.0 - */ - this.name = 'WebGLPipeline'; - - /** - * The Game which owns this WebGL Pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = config.game; - - /** - * The canvas which this WebGL Pipeline renders to. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#view - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.view = config.game.canvas; - - /** - * Used to store the current game resolution - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution - * @type {number} - * @since 3.0.0 - */ - this.resolution = 1; - - /** - * Width of the current viewport - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#width - * @type {number} - * @since 3.0.0 - */ - this.width = 0; - - /** - * Height of the current viewport - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#height - * @type {number} - * @since 3.0.0 - */ - this.height = 0; - - /** - * The WebGL context this WebGL Pipeline uses. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#gl - * @type {WebGLRenderingContext} - * @since 3.0.0 - */ - this.gl = config.gl; - - /** - * How many vertices have been fed to the current pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.vertexCount = 0; - - /** - * The limit of vertices that the pipeline can hold - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity - * @type {integer} - * @since 3.0.0 - */ - this.vertexCapacity = config.vertexCapacity; - - /** - * The WebGL Renderer which owns this WebGL Pipeline. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer - * @type {Phaser.Renderer.WebGL.WebGLRenderer} - * @since 3.0.0 - */ - this.renderer = config.renderer; - - /** - * Raw byte buffer of vertices. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData - * @type {ArrayBuffer} - * @since 3.0.0 - */ - this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); - - /** - * The handle to a WebGL vertex buffer object. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer - * @type {WebGLBuffer} - * @since 3.0.0 - */ - this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); - - /** - * The handle to a WebGL program - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#program - * @type {WebGLProgram} - * @since 3.0.0 - */ - this.program = this.renderer.createProgram(config.vertShader, config.fragShader); - - /** - * Array of objects that describe the vertex attributes - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes - * @type {object} - * @since 3.0.0 - */ - this.attributes = config.attributes; - - /** - * The size in bytes of the vertex - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize - * @type {integer} - * @since 3.0.0 - */ - this.vertexSize = config.vertexSize; - - /** - * The primitive topology which the pipeline will use to submit draw calls - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#topology - * @type {integer} - * @since 3.0.0 - */ - this.topology = config.topology; - - /** - * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources - * to the GPU. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes - * @type {Uint8Array} - * @since 3.0.0 - */ - this.bytes = new Uint8Array(this.vertexData); - - /** - * This will store the amount of components of 32 bit length - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount - * @type {integer} - * @since 3.0.0 - */ - this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); - - /** - * Indicates if the current pipeline is flushing the contents to the GPU. - * When the variable is set the flush function will be locked. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked - * @type {boolean} - * @since 3.1.0 - */ - this.flushLocked = false; - - /** - * Indicates if the current pipeline is active or not for this frame only. - * Reset in the onRender method. - * - * @name Phaser.Renderer.WebGL.WebGLPipeline#active - * @type {boolean} - * @since 3.10.0 - */ - this.active = false; - }, - - /** - * Called when the Game has fully booted and the Renderer has finished setting up. - * - * By this stage all Game level systems are now in place and you can perform any final - * tasks that the pipeline may need that relied on game systems such as the Texture Manager. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#boot - * @since 3.11.0 - */ - boot: function () - { - }, - - /** - * Adds a description of vertex attribute to the pipeline - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute - * @since 3.2.0 - * - * @param {string} name - Name of the vertex attribute - * @param {integer} size - Vertex component size - * @param {integer} type - Type of the attribute - * @param {boolean} normalized - Is the value normalized to a range - * @param {integer} offset - Byte offset to the beginning of the first element in the vertex - * - * @return {this} This WebGLPipeline instance. - */ - addAttribute: function (name, size, type, normalized, offset) - { - this.attributes.push({ - name: name, - size: size, - type: this.renderer.glFormats[type], - normalized: normalized, - offset: offset - }); - - this.vertexComponentCount = Utils.getComponentCount( - this.attributes, - this.gl - ); - return this; - }, - - /** - * Check if the current batch of vertices is full. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush - * @since 3.0.0 - * - * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. - */ - shouldFlush: function () - { - return (this.vertexCount >= this.vertexCapacity); - }, - - /** - * Resizes the properties used to describe the viewport - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#resize - * @since 3.0.0 - * - * @param {number} width - The new width of this WebGL Pipeline. - * @param {number} height - The new height of this WebGL Pipeline. - * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - this.width = width * resolution; - this.height = height * resolution; - this.resolution = resolution; - - return this; - }, - - /** - * Binds the pipeline resources, including programs, vertex buffers and binds attributes - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#bind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - bind: function () - { - var gl = this.gl; - var vertexBuffer = this.vertexBuffer; - var attributes = this.attributes; - var program = this.program; - var renderer = this.renderer; - var vertexSize = this.vertexSize; - - renderer.setProgram(program); - renderer.setVertexBuffer(vertexBuffer); - - for (var index = 0; index < attributes.length; ++index) - { - var element = attributes[index]; - var location = gl.getAttribLocation(program, element.name); - - if (location >= 0) - { - gl.enableVertexAttribArray(location); - gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); - } - else if (location !== -1) - { - gl.disableVertexAttribArray(location); - } - } - - return this; - }, - - /** - * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. - * - * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - // This is for updating uniform data it's called on each bind attempt. - return this; - }, - - /** - * Called before each frame is rendered, but after the canvas has been cleared. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onPreRender: function () - { - // called once every frame - return this; - }, - - /** - * Called before a Scene's Camera is rendered. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene being rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. - * - * @return {this} This WebGLPipeline instance. - */ - onRender: function () - { - // called for each camera - return this; - }, - - /** - * Called after each frame has been completely rendered and snapshots have been taken. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onPostRender: function () - { - // called once every frame - return this; - }, - - /** - * Uploads the vertex data and emits a draw call - * for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#flush - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - flush: function () - { - if (this.flushLocked) { return this; } - - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - - if (vertexCount === 0) - { - this.flushLocked = false; - return; - } - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); - gl.drawArrays(topology, 0, vertexCount); - - this.vertexCount = 0; - this.flushLocked = false; - - return this; - }, - - /** - * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - destroy: function () - { - var gl = this.gl; - - gl.deleteProgram(this.program); - gl.deleteBuffer(this.vertexBuffer); - - delete this.program; - delete this.vertexBuffer; - delete this.gl; - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new value of the `float` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat1: function (name, x) - { - this.renderer.setFloat1(this.program, name, x); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new X component of the `vec2` uniform. - * @param {number} y - The new Y component of the `vec2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat2: function (name, x, y) - { - this.renderer.setFloat2(this.program, name, x, y); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The new X component of the `vec3` uniform. - * @param {number} y - The new Y component of the `vec3` uniform. - * @param {number} z - The new Z component of the `vec3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat3: function (name, x, y, z) - { - this.renderer.setFloat3(this.program, name, x, y, z); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - X component of the uniform - * @param {number} y - Y component of the uniform - * @param {number} z - Z component of the uniform - * @param {number} w - W component of the uniform - * - * @return {this} This WebGLPipeline instance. - */ - setFloat4: function (name, x, y, z, w) - { - this.renderer.setFloat4(this.program, name, x, y, z, w); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat1v: function (name, arr) - { - this.renderer.setFloat1v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat2v: function (name, arr) - { - this.renderer.setFloat2v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat3v: function (name, arr) - { - this.renderer.setFloat3v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v - * @since 3.13.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGLPipeline instance. - */ - setFloat4v: function (name, arr) - { - this.renderer.setFloat4v(this.program, name, arr); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new value of the `int` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt1: function (name, x) - { - this.renderer.setInt1(this.program, name, x); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new X component of the `ivec2` uniform. - * @param {integer} y - The new Y component of the `ivec2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt2: function (name, x, y) - { - this.renderer.setInt2(this.program, name, x, y); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The new X component of the `ivec3` uniform. - * @param {integer} y - The new Y component of the `ivec3` uniform. - * @param {integer} z - The new Z component of the `ivec3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setInt3: function (name, x, y, z) - { - this.renderer.setInt3(this.program, name, x, y, z); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - X component of the uniform - * @param {integer} y - Y component of the uniform - * @param {integer} z - Z component of the uniform - * @param {integer} w - W component of the uniform - * - * @return {this} This WebGLPipeline instance. - */ - setInt4: function (name, x, y, z, w) - { - this.renderer.setInt4(this.program, name, x, y, z, w); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. - * @param {Float32Array} matrix - The new values for the `mat2` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix2: function (name, transpose, matrix) - { - this.renderer.setMatrix2(this.program, name, transpose, matrix); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. - * @param {Float32Array} matrix - The new values for the `mat3` uniform. - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix3: function (name, transpose, matrix) - { - this.renderer.setMatrix3(this.program, name, transpose, matrix); - - return this; - }, - - /** - * Set a uniform value of the current pipeline program. - * - * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 - * @since 3.2.0 - * - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - Should the matrix be transpose - * @param {Float32Array} matrix - Matrix data - * - * @return {this} This WebGLPipeline instance. - */ - setMatrix4: function (name, transpose, matrix) - { - this.renderer.setMatrix4(this.program, name, transpose, matrix); - - return this; - } - -}); - -module.exports = WebGLPipeline; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Utils = require('./Utils'); + +/** + * @classdesc + * WebGLPipeline is a class that describes the way elements will be renderered + * in WebGL, specially focused on batching vertices (batching is not provided). + * Pipelines are mostly used for describing 2D rendering passes but it's + * flexible enough to be used for any type of rendering including 3D. + * Internally WebGLPipeline will handle things like compiling shaders, + * creating vertex buffers, assigning primitive topology and binding + * vertex attributes. + * + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - gl: Current WebGL context. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * - vertices: An optional buffer of vertices + * - attributes: An array describing the vertex attributes + * + * The vertex attributes properties are: + * - name : String - Name of the attribute in the vertex shader + * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 + * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) + * - normalized : boolean - Is the attribute normalized + * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C + * Here you can find more information of how to describe an attribute: + * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer + * + * @class WebGLPipeline + * @memberof Phaser.Renderer.WebGL + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration object for this WebGL Pipeline, as described above. + */ +var WebGLPipeline = new Class({ + + initialize: + + function WebGLPipeline (config) + { + /** + * Name of the Pipeline. Used for identifying + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'WebGLPipeline'; + + /** + * The Game which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = config.game; + + /** + * The canvas which this WebGL Pipeline renders to. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#view + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.view = config.game.canvas; + + /** + * Used to store the current game resolution + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#resolution + * @type {number} + * @since 3.0.0 + */ + this.resolution = 1; + + /** + * Width of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#width + * @type {number} + * @since 3.0.0 + */ + this.width = 0; + + /** + * Height of the current viewport + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#height + * @type {number} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The WebGL context this WebGL Pipeline uses. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#gl + * @type {WebGLRenderingContext} + * @since 3.0.0 + */ + this.gl = config.gl; + + /** + * How many vertices have been fed to the current pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.vertexCount = 0; + + /** + * The limit of vertices that the pipeline can hold + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexCapacity + * @type {integer} + * @since 3.0.0 + */ + this.vertexCapacity = config.vertexCapacity; + + /** + * The WebGL Renderer which owns this WebGL Pipeline. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#renderer + * @type {Phaser.Renderer.WebGL.WebGLRenderer} + * @since 3.0.0 + */ + this.renderer = config.renderer; + + /** + * Raw byte buffer of vertices. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexData + * @type {ArrayBuffer} + * @since 3.0.0 + */ + this.vertexData = (config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize)); + + /** + * The handle to a WebGL vertex buffer object. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexBuffer + * @type {WebGLBuffer} + * @since 3.0.0 + */ + this.vertexBuffer = this.renderer.createVertexBuffer((config.vertices ? config.vertices : this.vertexData.byteLength), this.gl.STREAM_DRAW); + + /** + * The handle to a WebGL program + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#program + * @type {WebGLProgram} + * @since 3.0.0 + */ + this.program = this.renderer.createProgram(config.vertShader, config.fragShader); + + /** + * Array of objects that describe the vertex attributes + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#attributes + * @type {object} + * @since 3.0.0 + */ + this.attributes = config.attributes; + + /** + * The size in bytes of the vertex + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexSize + * @type {integer} + * @since 3.0.0 + */ + this.vertexSize = config.vertexSize; + + /** + * The primitive topology which the pipeline will use to submit draw calls + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#topology + * @type {integer} + * @since 3.0.0 + */ + this.topology = config.topology; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources + * to the GPU. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#bytes + * @type {Uint8Array} + * @since 3.0.0 + */ + this.bytes = new Uint8Array(this.vertexData); + + /** + * This will store the amount of components of 32 bit length + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#vertexComponentCount + * @type {integer} + * @since 3.0.0 + */ + this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); + + /** + * Indicates if the current pipeline is flushing the contents to the GPU. + * When the variable is set the flush function will be locked. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#flushLocked + * @type {boolean} + * @since 3.1.0 + */ + this.flushLocked = false; + + /** + * Indicates if the current pipeline is active or not for this frame only. + * Reset in the onRender method. + * + * @name Phaser.Renderer.WebGL.WebGLPipeline#active + * @type {boolean} + * @since 3.10.0 + */ + this.active = false; + }, + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#boot + * @since 3.11.0 + */ + boot: function () + { + }, + + /** + * Adds a description of vertex attribute to the pipeline + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#addAttribute + * @since 3.2.0 + * + * @param {string} name - Name of the vertex attribute + * @param {integer} size - Vertex component size + * @param {integer} type - Type of the attribute + * @param {boolean} normalized - Is the value normalized to a range + * @param {integer} offset - Byte offset to the beginning of the first element in the vertex + * + * @return {this} This WebGLPipeline instance. + */ + addAttribute: function (name, size, type, normalized, offset) + { + this.attributes.push({ + name: name, + size: size, + type: this.renderer.glFormats[type], + normalized: normalized, + offset: offset + }); + + this.vertexComponentCount = Utils.getComponentCount( + this.attributes, + this.gl + ); + return this; + }, + + /** + * Check if the current batch of vertices is full. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#shouldFlush + * @since 3.0.0 + * + * @return {boolean} `true` if the current batch should be flushed, otherwise `false`. + */ + shouldFlush: function () + { + return (this.vertexCount >= this.vertexCapacity); + }, + + /** + * Resizes the properties used to describe the viewport + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width of this WebGL Pipeline. + * @param {number} height - The new height of this WebGL Pipeline. + * @param {number} resolution - The resolution this WebGL Pipeline should be resized to. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + this.width = width * resolution; + this.height = height * resolution; + this.resolution = resolution; + + return this; + }, + + /** + * Binds the pipeline resources, including programs, vertex buffers and binds attributes + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#bind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + bind: function () + { + var gl = this.gl; + var vertexBuffer = this.vertexBuffer; + var attributes = this.attributes; + var program = this.program; + var renderer = this.renderer; + var vertexSize = this.vertexSize; + + renderer.setProgram(program); + renderer.setVertexBuffer(vertexBuffer); + + for (var index = 0; index < attributes.length; ++index) + { + var element = attributes[index]; + var location = gl.getAttribLocation(program, element.name); + + if (location >= 0) + { + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset); + } + else if (location !== -1) + { + gl.disableVertexAttribArray(location); + } + } + + return this; + }, + + /** + * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. + * + * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + // This is for updating uniform data it's called on each bind attempt. + return this; + }, + + /** + * Called before each frame is rendered, but after the canvas has been cleared. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPreRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPreRender: function () + { + // called once every frame + return this; + }, + + /** + * Called before a Scene's Camera is rendered. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onRender + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. + * + * @return {this} This WebGLPipeline instance. + */ + onRender: function () + { + // called for each camera + return this; + }, + + /** + * Called after each frame has been completely rendered and snapshots have been taken. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#onPostRender + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onPostRender: function () + { + // called once every frame + return this; + }, + + /** + * Uploads the vertex data and emits a draw call + * for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#flush + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) { return this; } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + + if (vertexCount === 0) + { + this.flushLocked = false; + return; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + gl.drawArrays(topology, 0, vertexCount); + + this.vertexCount = 0; + this.flushLocked = false; + + return this; + }, + + /** + * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#destroy + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + destroy: function () + { + var gl = this.gl; + + gl.deleteProgram(this.program); + gl.deleteBuffer(this.vertexBuffer); + + delete this.program; + delete this.vertexBuffer; + delete this.gl; + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new value of the `float` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1: function (name, x) + { + this.renderer.setFloat1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec2` uniform. + * @param {number} y - The new Y component of the `vec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2: function (name, x, y) + { + this.renderer.setFloat2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The new X component of the `vec3` uniform. + * @param {number} y - The new Y component of the `vec3` uniform. + * @param {number} z - The new Z component of the `vec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3: function (name, x, y, z) + { + this.renderer.setFloat3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - X component of the uniform + * @param {number} y - Y component of the uniform + * @param {number} z - Z component of the uniform + * @param {number} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4: function (name, x, y, z, w) + { + this.renderer.setFloat4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat1v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat1v: function (name, arr) + { + this.renderer.setFloat1v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat2v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat2v: function (name, arr) + { + this.renderer.setFloat2v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat3v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat3v: function (name, arr) + { + this.renderer.setFloat3v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setFloat4v + * @since 3.13.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGLPipeline instance. + */ + setFloat4v: function (name, arr) + { + this.renderer.setFloat4v(this.program, name, arr); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt1 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new value of the `int` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt1: function (name, x) + { + this.renderer.setInt1(this.program, name, x); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec2` uniform. + * @param {integer} y - The new Y component of the `ivec2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt2: function (name, x, y) + { + this.renderer.setInt2(this.program, name, x, y); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The new X component of the `ivec3` uniform. + * @param {integer} y - The new Y component of the `ivec3` uniform. + * @param {integer} z - The new Z component of the `ivec3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setInt3: function (name, x, y, z) + { + this.renderer.setInt3(this.program, name, x, y, z); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setInt4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - X component of the uniform + * @param {integer} y - Y component of the uniform + * @param {integer} z - Z component of the uniform + * @param {integer} w - W component of the uniform + * + * @return {this} This WebGLPipeline instance. + */ + setInt4: function (name, x, y, z, w) + { + this.renderer.setInt4(this.program, name, x, y, z, w); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix2 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat2` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix2: function (name, transpose, matrix) + { + this.renderer.setMatrix2(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix3 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Whether to transpose the matrix. Should be `false`. + * @param {Float32Array} matrix - The new values for the `mat3` uniform. + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix3: function (name, transpose, matrix) + { + this.renderer.setMatrix3(this.program, name, transpose, matrix); + + return this; + }, + + /** + * Set a uniform value of the current pipeline program. + * + * @method Phaser.Renderer.WebGL.WebGLPipeline#setMatrix4 + * @since 3.2.0 + * + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - Should the matrix be transpose + * @param {Float32Array} matrix - Matrix data + * + * @return {this} This WebGLPipeline instance. + */ + setMatrix4: function (name, transpose, matrix) + { + this.renderer.setMatrix4(this.program, name, transpose, matrix); + + return this; + } + +}); + +module.exports = WebGLPipeline; diff --git a/src/renderer/webgl/WebGLRenderer.js b/src/renderer/webgl/WebGLRenderer.js index 84b928445..b9655d57e 100644 --- a/src/renderer/webgl/WebGLRenderer.js +++ b/src/renderer/webgl/WebGLRenderer.js @@ -1,2983 +1,2983 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseCamera = require('../../cameras/2d/BaseCamera'); -var CameraEvents = require('../../cameras/2d/events'); -var Class = require('../../utils/Class'); -var CONST = require('../../const'); -var GameEvents = require('../../core/events'); -var IsSizePowerOfTwo = require('../../math/pow2/IsSizePowerOfTwo'); -var NOOP = require('../../utils/NOOP'); -var ScaleEvents = require('../../scale/events'); -var SpliceOne = require('../../utils/array/SpliceOne'); -var TextureEvents = require('../../textures/events'); -var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); -var Utils = require('./Utils'); -var WebGLSnapshot = require('../snapshot/WebGLSnapshot'); - -// Default Pipelines -var BitmapMaskPipeline = require('./pipelines/BitmapMaskPipeline'); -var ForwardDiffuseLightPipeline = require('./pipelines/ForwardDiffuseLightPipeline'); -var TextureTintPipeline = require('./pipelines/TextureTintPipeline'); -var TextureTintStripPipeline = require('./pipelines/TextureTintStripPipeline'); - -/** - * @callback WebGLContextCallback - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer which owns the context. - */ - -/** - * @classdesc - * WebGLRenderer is a class that contains the needed functionality to keep the - * WebGLRenderingContext state clean. The main idea of the WebGLRenderer is to keep track of - * any context change that happens for WebGL rendering inside of Phaser. This means - * if raw webgl functions are called outside the WebGLRenderer of the Phaser WebGL - * rendering ecosystem they might pollute the current WebGLRenderingContext state producing - * unexpected behavior. It's recommended that WebGL interaction is done through - * WebGLRenderer and/or WebGLPipeline. - * - * @class WebGLRenderer - * @memberof Phaser.Renderer.WebGL - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Game instance which owns this WebGL Renderer. - */ -var WebGLRenderer = new Class({ - - initialize: - - function WebGLRenderer (game) - { - var gameConfig = game.config; - - var contextCreationConfig = { - alpha: gameConfig.transparent, - desynchronized: gameConfig.desynchronized, - depth: false, - antialias: gameConfig.antialiasGL, - premultipliedAlpha: gameConfig.premultipliedAlpha, - stencil: true, - failIfMajorPerformanceCaveat: gameConfig.failIfMajorPerformanceCaveat, - powerPreference: gameConfig.powerPreference - }; - - /** - * The local configuration settings of this WebGL Renderer. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#config - * @type {object} - * @since 3.0.0 - */ - this.config = { - clearBeforeRender: gameConfig.clearBeforeRender, - antialias: gameConfig.antialias, - backgroundColor: gameConfig.backgroundColor, - contextCreation: contextCreationConfig, - resolution: gameConfig.resolution, - roundPixels: gameConfig.roundPixels, - maxTextures: gameConfig.maxTextures, - maxTextureSize: gameConfig.maxTextureSize, - batchSize: gameConfig.batchSize, - maxLights: gameConfig.maxLights, - mipmapFilter: gameConfig.mipmapFilter - }; - - /** - * The Game instance which owns this WebGL Renderer. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = game; - - /** - * A constant which allows the renderer to be easily identified as a WebGL Renderer. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#type - * @type {integer} - * @since 3.0.0 - */ - this.type = CONST.WEBGL; - - /** - * The width of the canvas being rendered to. - * This is populated in the onResize event handler. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#width - * @type {integer} - * @since 3.0.0 - */ - this.width = 0; - - /** - * The height of the canvas being rendered to. - * This is populated in the onResize event handler. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#height - * @type {integer} - * @since 3.0.0 - */ - this.height = 0; - - /** - * The canvas which this WebGL Renderer draws to. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#canvas - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.canvas = game.canvas; - - /** - * An array of blend modes supported by the WebGL Renderer. - * - * This array includes the default blend modes as well as any custom blend modes added through {@link #addBlendMode}. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#blendModes - * @type {array} - * @default [] - * @since 3.0.0 - */ - this.blendModes = []; - - /** - * Keeps track of any WebGLTexture created with the current WebGLRenderingContext - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#nativeTextures - * @type {array} - * @default [] - * @since 3.0.0 - */ - this.nativeTextures = []; - - /** - * This property is set to `true` if the WebGL context of the renderer is lost. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#contextLost - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.contextLost = false; - - /** - * This object will store all pipelines created through addPipeline - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#pipelines - * @type {object} - * @default null - * @since 3.0.0 - */ - this.pipelines = null; - - /** - * Details about the currently scheduled snapshot. - * - * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#snapshotState - * @type {Phaser.Types.Renderer.Snapshot.SnapshotState} - * @since 3.0.0 - */ - this.snapshotState = { - x: 0, - y: 0, - width: 1, - height: 1, - getPixel: false, - callback: null, - type: 'image/png', - encoder: 0.92, - isFramebuffer: false, - bufferWidth: 0, - bufferHeight: 0 - }; - - // Internal Renderer State (Textures, Framebuffers, Pipelines, Buffers, etc) - - /** - * Cached value for the last texture unit that was used - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentActiveTextureUnit - * @type {integer} - * @since 3.1.0 - */ - this.currentActiveTextureUnit = 0; - - /** - * An array of the last texture handles that were bound to the WebGLRenderingContext - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentTextures - * @type {array} - * @since 3.0.0 - */ - this.currentTextures = new Array(16); - - /** - * Current framebuffer in use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentFramebuffer - * @type {WebGLFramebuffer} - * @default null - * @since 3.0.0 - */ - this.currentFramebuffer = null; - - /** - * Current WebGLPipeline in use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentPipeline - * @type {Phaser.Renderer.WebGL.WebGLPipeline} - * @default null - * @since 3.0.0 - */ - this.currentPipeline = null; - - /** - * Current WebGLProgram in use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentProgram - * @type {WebGLProgram} - * @default null - * @since 3.0.0 - */ - this.currentProgram = null; - - /** - * Current WebGLBuffer (Vertex buffer) in use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentVertexBuffer - * @type {WebGLBuffer} - * @default null - * @since 3.0.0 - */ - this.currentVertexBuffer = null; - - /** - * Current WebGLBuffer (Index buffer) in use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentIndexBuffer - * @type {WebGLBuffer} - * @default null - * @since 3.0.0 - */ - this.currentIndexBuffer = null; - - /** - * Current blend mode in use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentBlendMode - * @type {integer} - * @since 3.0.0 - */ - this.currentBlendMode = Infinity; - - /** - * Indicates if the the scissor state is enabled in WebGLRenderingContext - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentScissorEnabled - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.currentScissorEnabled = false; - - /** - * Stores the current scissor data - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentScissor - * @type {Uint32Array} - * @since 3.0.0 - */ - this.currentScissor = null; - - /** - * Stack of scissor data - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#scissorStack - * @type {Uint32Array} - * @since 3.0.0 - */ - this.scissorStack = []; - - /** - * The handler to invoke when the context is lost. - * This should not be changed and is set in the boot method. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#contextLostHandler - * @type {function} - * @since 3.19.0 - */ - this.contextLostHandler = NOOP; - - /** - * The handler to invoke when the context is restored. - * This should not be changed and is set in the boot method. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#contextRestoredHandler - * @type {function} - * @since 3.19.0 - */ - this.contextRestoredHandler = NOOP; - - /** - * The underlying WebGL context of the renderer. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#gl - * @type {WebGLRenderingContext} - * @default null - * @since 3.0.0 - */ - this.gl = null; - - /** - * Array of strings that indicate which WebGL extensions are supported by the browser - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#supportedExtensions - * @type {object} - * @default null - * @since 3.0.0 - */ - this.supportedExtensions = null; - - /** - * Extensions loaded into the current context - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#extensions - * @type {object} - * @default {} - * @since 3.0.0 - */ - this.extensions = {}; - - /** - * Stores the current WebGL component formats for further use - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#glFormats - * @type {array} - * @default [] - * @since 3.2.0 - */ - this.glFormats = []; - - /** - * Stores the supported WebGL texture compression formats. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#compression - * @type {array} - * @since 3.8.0 - */ - this.compression = { - ETC1: false, - PVRTC: false, - S3TC: false - }; - - /** - * Cached drawing buffer height to reduce gl calls. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#drawingBufferHeight - * @type {number} - * @readonly - * @since 3.11.0 - */ - this.drawingBufferHeight = 0; - - /** - * A blank 32x32 transparent texture, as used by the Graphics system where needed. - * This is set in the `boot` method. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#blankTexture - * @type {WebGLTexture} - * @readonly - * @since 3.12.0 - */ - this.blankTexture = null; - - /** - * A default Camera used in calls when no other camera has been provided. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#defaultCamera - * @type {Phaser.Cameras.Scene2D.BaseCamera} - * @since 3.12.0 - */ - this.defaultCamera = new BaseCamera(0, 0, 0, 0); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix4 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.12.0 - */ - this._tempMatrix4 = new TransformMatrix(); - - /** - * The total number of masks currently stacked. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#maskCount - * @type {integer} - * @since 3.17.0 - */ - this.maskCount = 0; - - /** - * The mask stack. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#maskStack - * @type {Phaser.Display.Masks.GeometryMask[]} - * @since 3.17.0 - */ - this.maskStack = []; - - /** - * Internal property that tracks the currently set mask. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentMask - * @type {any} - * @since 3.17.0 - */ - this.currentMask = { mask: null, camera: null }; - - /** - * Internal property that tracks the currently set camera mask. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentCameraMask - * @type {any} - * @since 3.17.0 - */ - this.currentCameraMask = { mask: null, camera: null }; - - /** - * Internal gl function mapping for uniform look-up. - * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#glFuncMap - * @type {any} - * @since 3.17.0 - */ - this.glFuncMap = null; - - /** - * The `type` of the Game Object being currently rendered. - * This can be used by advanced render functions for batching look-ahead. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#currentType - * @type {string} - * @since 3.19.0 - */ - this.currentType = ''; - - /** - * Is the `type` of the Game Object being currently rendered different than the - * type of the object before it in the display list? I.e. it's a 'new' type. - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#newType - * @type {boolean} - * @since 3.19.0 - */ - this.newType = false; - - /** - * Does the `type` of the next Game Object in the display list match that - * of the object being currently rendered? - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#nextTypeMatch - * @type {boolean} - * @since 3.19.0 - */ - this.nextTypeMatch = false; - - /** - * The mipmap magFilter to be used when creating textures. - * - * You can specify this as a string in the game config, i.e.: - * - * `renderer: { 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 - * - * @name Phaser.Renderer.WebGL.WebGLRenderer#mipmapFilter - * @type {GLenum} - * @since 3.21.0 - */ - this.mipmapFilter = null; - - this.init(this.config); - }, - - /** - * Creates a new WebGLRenderingContext and initializes all internal state. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#init - * @since 3.0.0 - * - * @param {object} config - The configuration object for the renderer. - * - * @return {this} This WebGLRenderer instance. - */ - init: function (config) - { - var gl; - var game = this.game; - var canvas = this.canvas; - var clearColor = config.backgroundColor; - - // Did they provide their own context? - if (game.config.context) - { - gl = game.config.context; - } - else - { - gl = canvas.getContext('webgl', config.contextCreation) || canvas.getContext('experimental-webgl', config.contextCreation); - } - - if (!gl || gl.isContextLost()) - { - this.contextLost = true; - - throw new Error('WebGL unsupported'); - } - - this.gl = gl; - - var _this = this; - - this.contextLostHandler = function (event) - { - _this.contextLost = true; - - _this.game.events.emit(GameEvents.CONTEXT_LOST, _this); - - event.preventDefault(); - }; - - this.contextRestoredHandler = function () - { - _this.contextLost = false; - - _this.init(_this.config); - - _this.game.events.emit(GameEvents.CONTEXT_RESTORED, _this); - }; - - canvas.addEventListener('webglcontextlost', this.contextLostHandler, false); - canvas.addEventListener('webglcontextrestored', this.contextRestoredHandler, false); - - // Set it back into the Game, so developers can access it from there too - game.context = gl; - - for (var i = 0; i <= 27; i++) - { - this.blendModes.push({ func: [ gl.ONE, gl.ONE_MINUS_SRC_ALPHA ], equation: gl.FUNC_ADD }); - } - - // ADD - this.blendModes[1].func = [ gl.ONE, gl.DST_ALPHA ]; - - // MULTIPLY - this.blendModes[2].func = [ gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA ]; - - // SCREEN - this.blendModes[3].func = [ gl.ONE, gl.ONE_MINUS_SRC_COLOR ]; - - // ERASE - this.blendModes[17] = { func: [ gl.ZERO, gl.ONE_MINUS_SRC_ALPHA ], equation: gl.FUNC_REVERSE_SUBTRACT }; - - this.glFormats[0] = gl.BYTE; - this.glFormats[1] = gl.SHORT; - this.glFormats[2] = gl.UNSIGNED_BYTE; - this.glFormats[3] = gl.UNSIGNED_SHORT; - this.glFormats[4] = gl.FLOAT; - - // Set the gl function map - this.glFuncMap = { - - mat2: { func: gl.uniformMatrix2fv, length: 1, matrix: true }, - mat3: { func: gl.uniformMatrix3fv, length: 1, matrix: true }, - mat4: { func: gl.uniformMatrix4fv, length: 1, matrix: true }, - - '1f': { func: gl.uniform1f, length: 1 }, - '1fv': { func: gl.uniform1fv, length: 1 }, - '1i': { func: gl.uniform1i, length: 1 }, - '1iv': { func: gl.uniform1iv, length: 1 }, - - '2f': { func: gl.uniform2f, length: 2 }, - '2fv': { func: gl.uniform2fv, length: 1 }, - '2i': { func: gl.uniform2i, length: 2 }, - '2iv': { func: gl.uniform2iv, length: 1 }, - - '3f': { func: gl.uniform3f, length: 3 }, - '3fv': { func: gl.uniform3fv, length: 1 }, - '3i': { func: gl.uniform3i, length: 3 }, - '3iv': { func: gl.uniform3iv, length: 1 }, - - '4f': { func: gl.uniform4f, length: 4 }, - '4fv': { func: gl.uniform4fv, length: 1 }, - '4i': { func: gl.uniform4i, length: 4 }, - '4iv': { func: gl.uniform4iv, length: 1 } - - }; - - // Load supported extensions - var exts = gl.getSupportedExtensions(); - - if (!config.maxTextures) - { - config.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - } - - if (!config.maxTextureSize) - { - config.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); - } - - var extString = 'WEBGL_compressed_texture_'; - var wkExtString = 'WEBKIT_' + extString; - - this.compression.ETC1 = gl.getExtension(extString + 'etc1') || gl.getExtension(wkExtString + 'etc1'); - this.compression.PVRTC = gl.getExtension(extString + 'pvrtc') || gl.getExtension(wkExtString + 'pvrtc'); - this.compression.S3TC = gl.getExtension(extString + 's3tc') || gl.getExtension(wkExtString + 's3tc'); - - this.supportedExtensions = exts; - - // Setup initial WebGL state - gl.disable(gl.DEPTH_TEST); - gl.disable(gl.CULL_FACE); - - gl.enable(gl.BLEND); - - gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, clearColor.alphaGL); - - // Mipmaps - this.mipmapFilter = gl[config.mipmapFilter]; - - // Initialize all textures to null - for (var index = 0; index < this.currentTextures.length; ++index) - { - this.currentTextures[index] = null; - } - - // Clear previous pipelines and reload default ones - this.pipelines = {}; - - this.addPipeline('TextureTintPipeline', new TextureTintPipeline({ game: game, renderer: this })); - this.addPipeline('TextureTintStripPipeline', new TextureTintStripPipeline({ game: game, renderer: this })); - this.addPipeline('BitmapMaskPipeline', new BitmapMaskPipeline({ game: game, renderer: this })); - this.addPipeline('Light2D', new ForwardDiffuseLightPipeline({ game: game, renderer: this, maxLights: config.maxLights })); - - this.setBlendMode(CONST.BlendModes.NORMAL); - - game.textures.once(TextureEvents.READY, this.boot, this); - - return this; - }, - - /** - * Internal boot handler. Calls 'boot' on each pipeline. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#boot - * @private - * @since 3.11.0 - */ - boot: function () - { - for (var pipelineName in this.pipelines) - { - this.pipelines[pipelineName].boot(); - } - - var blank = this.game.textures.getFrame('__DEFAULT'); - - this.pipelines.TextureTintPipeline.currentFrame = blank; - - this.blankTexture = blank; - - var gl = this.gl; - - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - - gl.enable(gl.SCISSOR_TEST); - - this.setPipeline(this.pipelines.TextureTintPipeline); - - this.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); - - var baseSize = this.game.scale.baseSize; - - this.resize(baseSize.width, baseSize.height, this.game.scale.resolution); - }, - - /** - * The event handler that manages the `resize` event dispatched by the Scale Manager. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#onResize - * @since 3.16.0 - * - * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. - * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. - * @param {Phaser.Structs.Size} displaySize - The display Size object. The size of the canvas style width / height attributes. - * @param {number} [resolution] - The Scale Manager resolution setting. - */ - onResize: function (gameSize, baseSize, displaySize, resolution) - { - // Has the underlying canvas size changed? - if (baseSize.width !== this.width || baseSize.height !== this.height || resolution !== this.resolution) - { - this.resize(baseSize.width, baseSize.height, resolution); - } - }, - - /** - * Resizes the drawing buffer to match that required by the Scale Manager. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#resize - * @since 3.0.0 - * - * @param {number} [width] - The new width of the renderer. - * @param {number} [height] - The new height of the renderer. - * @param {number} [resolution] - The new resolution of the renderer. - * - * @return {this} This WebGLRenderer instance. - */ - resize: function (width, height, resolution) - { - var gl = this.gl; - var pipelines = this.pipelines; - - this.width = width; - this.height = height; - this.resolution = resolution; - - gl.viewport(0, 0, width, height); - - // Update all registered pipelines - for (var pipelineName in pipelines) - { - pipelines[pipelineName].resize(width, height, resolution); - } - - this.drawingBufferHeight = gl.drawingBufferHeight; - - gl.scissor(0, (gl.drawingBufferHeight - height), width, height); - - this.defaultCamera.setSize(width, height); - - return this; - }, - - /** - * Checks if a WebGL extension is supported - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#hasExtension - * @since 3.0.0 - * - * @param {string} extensionName - Name of the WebGL extension - * - * @return {boolean} `true` if the extension is supported, otherwise `false`. - */ - hasExtension: function (extensionName) - { - return this.supportedExtensions ? this.supportedExtensions.indexOf(extensionName) : false; - }, - - /** - * Loads a WebGL extension - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#getExtension - * @since 3.0.0 - * - * @param {string} extensionName - The name of the extension to load. - * - * @return {object} WebGL extension if the extension is supported - */ - getExtension: function (extensionName) - { - if (!this.hasExtension(extensionName)) { return null; } - - if (!(extensionName in this.extensions)) - { - this.extensions[extensionName] = this.gl.getExtension(extensionName); - } - - return this.extensions[extensionName]; - }, - - /** - * Flushes the current pipeline if the pipeline is bound - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#flush - * @since 3.0.0 - */ - flush: function () - { - if (this.currentPipeline) - { - this.currentPipeline.flush(); - } - }, - - /** - * Checks if a pipeline is present in the current WebGLRenderer - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#hasPipeline - * @since 3.0.0 - * - * @param {string} pipelineName - The name of the pipeline. - * - * @return {boolean} `true` if the given pipeline is loaded, otherwise `false`. - */ - hasPipeline: function (pipelineName) - { - return (pipelineName in this.pipelines); - }, - - /** - * Returns the pipeline by name if the pipeline exists - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#getPipeline - * @since 3.0.0 - * - * @param {string} pipelineName - The name of the pipeline. - * - * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline instance, or `null` if not found. - */ - getPipeline: function (pipelineName) - { - return (this.hasPipeline(pipelineName)) ? this.pipelines[pipelineName] : null; - }, - - /** - * Removes a pipeline by name. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#removePipeline - * @since 3.0.0 - * - * @param {string} pipelineName - The name of the pipeline to be removed. - * - * @return {this} This WebGLRenderer instance. - */ - removePipeline: function (pipelineName) - { - delete this.pipelines[pipelineName]; - - return this; - }, - - /** - * Adds a pipeline instance into the collection of pipelines - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#addPipeline - * @since 3.0.0 - * - * @param {string} pipelineName - A unique string-based key for the pipeline. - * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - A pipeline instance which must extend WebGLPipeline. - * - * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline instance that was passed. - */ - addPipeline: function (pipelineName, pipelineInstance) - { - if (!this.hasPipeline(pipelineName)) - { - this.pipelines[pipelineName] = pipelineInstance; - } - else - { - console.warn('Pipeline exists: ' + pipelineName); - } - - pipelineInstance.name = pipelineName; - - this.pipelines[pipelineName].resize(this.width, this.height, this.config.resolution); - - return pipelineInstance; - }, - - /** - * Pushes a new scissor state. This is used to set nested scissor states. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#pushScissor - * @since 3.0.0 - * - * @param {integer} x - The x position of the scissor. - * @param {integer} y - The y position of the scissor. - * @param {integer} width - The width of the scissor. - * @param {integer} height - The height of the scissor. - * @param {integer} [drawingBufferHeight] - Optional drawingBufferHeight override value. - * - * @return {integer[]} An array containing the scissor values. - */ - pushScissor: function (x, y, width, height, drawingBufferHeight) - { - if (drawingBufferHeight === undefined) { drawingBufferHeight = this.drawingBufferHeight; } - - var scissorStack = this.scissorStack; - - var scissor = [ x, y, width, height ]; - - scissorStack.push(scissor); - - this.setScissor(x, y, width, height, drawingBufferHeight); - - this.currentScissor = scissor; - - return scissor; - }, - - /** - * Sets the current scissor state. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setScissor - * @since 3.0.0 - * - * @param {integer} x - The x position of the scissor. - * @param {integer} y - The y position of the scissor. - * @param {integer} width - The width of the scissor. - * @param {integer} height - The height of the scissor. - * @param {integer} [drawingBufferHeight] - Optional drawingBufferHeight override value. - */ - setScissor: function (x, y, width, height, drawingBufferHeight) - { - if (drawingBufferHeight === undefined) { drawingBufferHeight = this.drawingBufferHeight; } - - var gl = this.gl; - - var current = this.currentScissor; - - var setScissor = (width > 0 && height > 0); - - if (current && setScissor) - { - var cx = current[0]; - var cy = current[1]; - var cw = current[2]; - var ch = current[3]; - - setScissor = (cx !== x || cy !== y || cw !== width || ch !== height); - } - - if (setScissor) - { - this.flush(); - - // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/scissor - gl.scissor(x, (drawingBufferHeight - y - height), width, height); - } - }, - - /** - * Pops the last scissor state and sets it. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#popScissor - * @since 3.0.0 - */ - popScissor: function () - { - var scissorStack = this.scissorStack; - - // Remove the current scissor - scissorStack.pop(); - - // Reset the previous scissor - var scissor = scissorStack[scissorStack.length - 1]; - - if (scissor) - { - this.setScissor(scissor[0], scissor[1], scissor[2], scissor[3]); - } - - this.currentScissor = scissor; - }, - - /** - * Binds a WebGLPipeline and sets it as the current pipeline to be used. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setPipeline - * @since 3.0.0 - * - * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - The pipeline instance to be activated. - * @param {Phaser.GameObjects.GameObject} [gameObject] - The Game Object that invoked this pipeline, if any. - * - * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline that was activated. - */ - setPipeline: function (pipelineInstance, gameObject) - { - if (this.currentPipeline !== pipelineInstance || - this.currentPipeline.vertexBuffer !== this.currentVertexBuffer || - this.currentPipeline.program !== this.currentProgram) - { - this.flush(); - this.currentPipeline = pipelineInstance; - this.currentPipeline.bind(); - } - - this.currentPipeline.onBind(gameObject); - - return this.currentPipeline; - }, - - /** - * Is there an active stencil mask? - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#hasActiveStencilMask - * @since 3.17.0 - * - * @return {boolean} `true` if there is an active stencil mask, otherwise `false`. - */ - hasActiveStencilMask: function () - { - var mask = this.currentMask.mask; - var camMask = this.currentCameraMask.mask; - - return ((mask && mask.isStencil) || (camMask && camMask.isStencil)); - }, - - /** - * Use this to reset the gl context to the state that Phaser requires to continue rendering. - * Calling this will: - * - * * Disable `DEPTH_TEST`, `CULL_FACE` and `STENCIL_TEST`. - * * Clear the depth buffer and stencil buffers. - * * Reset the viewport size. - * * Reset the blend mode. - * * Bind a blank texture as the active texture on texture unit zero. - * * Rebinds the given pipeline instance. - * - * You should call this having previously called `clearPipeline` and then wishing to return - * control to Phaser again. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#rebindPipeline - * @since 3.16.0 - * - * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - The pipeline instance to be activated. - */ - rebindPipeline: function (pipelineInstance) - { - var gl = this.gl; - - gl.disable(gl.DEPTH_TEST); - gl.disable(gl.CULL_FACE); - - if (this.hasActiveStencilMask()) - { - gl.clear(gl.DEPTH_BUFFER_BIT); - } - else - { - // If there wasn't a stencil mask set before this call, we can disable it safely - gl.disable(gl.STENCIL_TEST); - gl.clear(gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); - } - - gl.viewport(0, 0, this.width, this.height); - - this.setBlendMode(0, true); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this.blankTexture.glTexture); - - this.currentActiveTextureUnit = 0; - this.currentTextures[0] = this.blankTexture.glTexture; - - this.currentPipeline = pipelineInstance; - this.currentPipeline.bind(); - this.currentPipeline.onBind(); - }, - - /** - * Flushes the current WebGLPipeline being used and then clears it, along with the - * the current shader program and vertex buffer. Then resets the blend mode to NORMAL. - * Call this before jumping to your own gl context handler, and then call `rebindPipeline` when - * you wish to return control to Phaser again. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#clearPipeline - * @since 3.16.0 - */ - clearPipeline: function () - { - this.flush(); - - this.currentPipeline = null; - this.currentProgram = null; - this.currentVertexBuffer = null; - this.currentIndexBuffer = null; - - this.setBlendMode(0, true); - }, - - /** - * Sets the blend mode to the value given. - * - * If the current blend mode is different from the one given, the pipeline is flushed and the new - * blend mode is enabled. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setBlendMode - * @since 3.0.0 - * - * @param {integer} blendModeId - The blend mode to be set. Can be a `BlendModes` const or an integer value. - * @param {boolean} [force=false] - Force the blend mode to be set, regardless of the currently set blend mode. - * - * @return {boolean} `true` if the blend mode was changed as a result of this call, forcing a flush, otherwise `false`. - */ - setBlendMode: function (blendModeId, force) - { - if (force === undefined) { force = false; } - - var gl = this.gl; - var blendMode = this.blendModes[blendModeId]; - - if (force || (blendModeId !== CONST.BlendModes.SKIP_CHECK && this.currentBlendMode !== blendModeId)) - { - this.flush(); - - gl.enable(gl.BLEND); - gl.blendEquation(blendMode.equation); - - if (blendMode.func.length > 2) - { - gl.blendFuncSeparate(blendMode.func[0], blendMode.func[1], blendMode.func[2], blendMode.func[3]); - } - else - { - gl.blendFunc(blendMode.func[0], blendMode.func[1]); - } - - this.currentBlendMode = blendModeId; - - return true; - } - - return false; - }, - - /** - * 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 {integer} The index of the new blend mode, used for referencing it in the future. - */ - addBlendMode: function (func, equation) - { - var index = this.blendModes.push({ func: func, equation: equation }); - - return index - 1; - }, - - /** - * Updates the function bound to a given custom blend mode. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#updateBlendMode - * @since 3.0.0 - * - * @param {integer} index - The index of the custom blend mode. - * @param {function} func - The function to use for the blend mode. - * @param {function} equation - The equation to use for the blend mode. - * - * @return {this} This WebGLRenderer instance. - */ - updateBlendMode: function (index, func, equation) - { - if (this.blendModes[index]) - { - this.blendModes[index].func = func; - - if (equation) - { - this.blendModes[index].equation = equation; - } - } - - return this; - }, - - /** - * Removes a custom blend mode from the renderer. - * Any Game Objects still using this blend mode will error, so be sure to clear them first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#removeBlendMode - * @since 3.0.0 - * - * @param {integer} index - The index of the custom blend mode to be removed. - * - * @return {this} This WebGLRenderer instance. - */ - removeBlendMode: function (index) - { - if (index > 17 && this.blendModes[index]) - { - this.blendModes.splice(index, 1); - } - - return this; - }, - - /** - * Sets the current active texture for texture unit zero to be a blank texture. - * This only happens if there isn't a texture already in use by texture unit zero. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setBlankTexture - * @private - * @since 3.12.0 - * - * @param {boolean} [force=false] - Force a blank texture set, regardless of what's already bound? - */ - setBlankTexture: function (force) - { - if (force === undefined) { force = false; } - - if (force || this.currentActiveTextureUnit !== 0 || !this.currentTextures[0]) - { - this.setTexture2D(this.blankTexture.glTexture, 0); - } - }, - - /** - * Binds a texture at a texture unit. If a texture is already - * bound to that unit it will force a flush on the current pipeline. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setTexture2D - * @since 3.0.0 - * - * @param {WebGLTexture} texture - The WebGL texture that needs to be bound. - * @param {integer} textureUnit - The texture unit to which the texture will be bound. - * @param {boolean} [flush=true] - Will the current pipeline be flushed if this is a new texture, or not? - * - * @return {this} This WebGLRenderer instance. - */ - setTexture2D: function (texture, textureUnit, flush) - { - if (flush === undefined) { flush = true; } - - var gl = this.gl; - - if (texture !== this.currentTextures[textureUnit]) - { - if (flush) - { - this.flush(); - } - - if (this.currentActiveTextureUnit !== textureUnit) - { - gl.activeTexture(gl.TEXTURE0 + textureUnit); - - this.currentActiveTextureUnit = textureUnit; - } - - gl.bindTexture(gl.TEXTURE_2D, texture); - - this.currentTextures[textureUnit] = texture; - } - - return this; - }, - - /** - * Binds a framebuffer. If there was another framebuffer already bound it will force a pipeline flush. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFramebuffer - * @since 3.0.0 - * - * @param {WebGLFramebuffer} framebuffer - The framebuffer that needs to be bound. - * @param {boolean} [updateScissor=false] - If a framebuffer is given, set the gl scissor to match the frame buffer size? Or, if `null` given, pop the scissor from the stack. - * - * @return {this} This WebGLRenderer instance. - */ - setFramebuffer: function (framebuffer, updateScissor) - { - if (updateScissor === undefined) { updateScissor = false; } - - var gl = this.gl; - - var width = this.width; - var height = this.height; - - if (framebuffer !== this.currentFramebuffer) - { - if (framebuffer && framebuffer.renderTexture) - { - width = framebuffer.renderTexture.width; - height = framebuffer.renderTexture.height; - } - else - { - this.flush(); - } - - gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); - - gl.viewport(0, 0, width, height); - - if (updateScissor) - { - if (framebuffer) - { - this.drawingBufferHeight = height; - - this.pushScissor(0, 0, width, height); - } - else - { - this.drawingBufferHeight = this.height; - - this.popScissor(); - } - } - - this.currentFramebuffer = framebuffer; - } - - return this; - }, - - /** - * Binds a program. If there was another program already bound it will force a pipeline flush. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setProgram - * @since 3.0.0 - * - * @param {WebGLProgram} program - The program that needs to be bound. - * - * @return {this} This WebGLRenderer instance. - */ - setProgram: function (program) - { - var gl = this.gl; - - if (program !== this.currentProgram) - { - this.flush(); - - gl.useProgram(program); - - this.currentProgram = program; - } - - return this; - }, - - /** - * Bounds a vertex buffer. If there is a vertex buffer already bound it'll force a pipeline flush. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setVertexBuffer - * @since 3.0.0 - * - * @param {WebGLBuffer} vertexBuffer - The buffer that needs to be bound. - * - * @return {this} This WebGLRenderer instance. - */ - setVertexBuffer: function (vertexBuffer) - { - var gl = this.gl; - - if (vertexBuffer !== this.currentVertexBuffer) - { - this.flush(); - - gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); - - this.currentVertexBuffer = vertexBuffer; - } - - return this; - }, - - /** - * Bounds a index buffer. If there is a index buffer already bound it'll force a pipeline flush. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setIndexBuffer - * @since 3.0.0 - * - * @param {WebGLBuffer} indexBuffer - The buffer the needs to be bound. - * - * @return {this} This WebGLRenderer instance. - */ - setIndexBuffer: function (indexBuffer) - { - var gl = this.gl; - - if (indexBuffer !== this.currentIndexBuffer) - { - this.flush(); - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); - - this.currentIndexBuffer = indexBuffer; - } - - return this; - }, - - /** - * Creates a texture from an image source. If the source is not valid it creates an empty texture. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#createTextureFromSource - * @since 3.0.0 - * - * @param {object} source - The source of the texture. - * @param {integer} width - The width of the texture. - * @param {integer} height - The height of the texture. - * @param {integer} scaleMode - The scale mode to be used by the texture. - * - * @return {?WebGLTexture} The WebGL Texture that was created, or `null` if it couldn't be created. - */ - createTextureFromSource: function (source, width, height, scaleMode) - { - var gl = this.gl; - var minFilter = gl.NEAREST; - var magFilter = gl.NEAREST; - var wrap = gl.CLAMP_TO_EDGE; - var texture = null; - - width = source ? source.width : width; - height = source ? source.height : height; - - var pow = IsSizePowerOfTwo(width, height); - - if (pow) - { - wrap = gl.REPEAT; - } - - if (scaleMode === CONST.ScaleModes.LINEAR && this.config.antialias) - { - minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; - magFilter = gl.LINEAR; - } - - if (!source && typeof width === 'number' && typeof height === 'number') - { - texture = this.createTexture2D(0, minFilter, magFilter, wrap, wrap, gl.RGBA, null, width, height); - } - else - { - texture = this.createTexture2D(0, minFilter, magFilter, wrap, wrap, gl.RGBA, source); - } - - return texture; - }, - - /** - * A wrapper for creating a WebGLTexture. If no pixel data is passed it will create an empty texture. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#createTexture2D - * @since 3.0.0 - * - * @param {integer} mipLevel - Mip level of the texture. - * @param {integer} minFilter - Filtering of the texture. - * @param {integer} magFilter - Filtering of the texture. - * @param {integer} wrapT - Wrapping mode of the texture. - * @param {integer} wrapS - Wrapping mode of the texture. - * @param {integer} format - Which format does the texture use. - * @param {?object} pixels - pixel data. - * @param {integer} width - Width of the texture in pixels. - * @param {integer} height - Height of the texture in pixels. - * @param {boolean} [pma=true] - Does the texture have premultiplied alpha? - * @param {boolean} [forceSize=false] - If `true` it will use the width and height passed to this method, regardless of the pixels dimension. - * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. - * - * @return {WebGLTexture} The WebGLTexture that was created. - */ - createTexture2D: function (mipLevel, minFilter, magFilter, wrapT, wrapS, format, pixels, width, height, pma, forceSize, flipY) - { - pma = (pma === undefined || pma === null) ? true : pma; - if (forceSize === undefined) { forceSize = false; } - if (flipY === undefined) { flipY = false; } - - var gl = this.gl; - var texture = gl.createTexture(); - - this.setTexture2D(texture, 0); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); - - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, pma); - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - - if (pixels === null || pixels === undefined) - { - gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, width, height, 0, format, gl.UNSIGNED_BYTE, null); - } - else - { - if (!forceSize) - { - width = pixels.width; - height = pixels.height; - } - - gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, format, gl.UNSIGNED_BYTE, pixels); - } - - if (IsSizePowerOfTwo(width, height)) - { - gl.generateMipmap(gl.TEXTURE_2D); - } - - this.setTexture2D(null, 0); - - texture.isAlphaPremultiplied = pma; - texture.isRenderTexture = false; - texture.width = width; - texture.height = height; - - this.nativeTextures.push(texture); - - return texture; - }, - - /** - * Wrapper for creating WebGLFramebuffer. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#createFramebuffer - * @since 3.0.0 - * - * @param {integer} width - Width in pixels of the framebuffer - * @param {integer} height - Height in pixels of the framebuffer - * @param {WebGLTexture} renderTexture - The color texture to where the color pixels are written - * @param {boolean} addDepthStencilBuffer - Indicates if the current framebuffer support depth and stencil buffers - * - * @return {WebGLFramebuffer} Raw WebGLFramebuffer - */ - createFramebuffer: function (width, height, renderTexture, addDepthStencilBuffer) - { - var gl = this.gl; - var framebuffer = gl.createFramebuffer(); - var complete = 0; - - this.setFramebuffer(framebuffer); - - if (addDepthStencilBuffer) - { - var depthStencilBuffer = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); - } - - renderTexture.isRenderTexture = true; - renderTexture.isAlphaPremultiplied = false; - - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, renderTexture, 0); - - complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER); - - if (complete !== gl.FRAMEBUFFER_COMPLETE) - { - var errors = { - 36054: 'Incomplete Attachment', - 36055: 'Missing Attachment', - 36057: 'Incomplete Dimensions', - 36061: 'Framebuffer Unsupported' - }; - - throw new Error('Framebuffer incomplete. Framebuffer status: ' + errors[complete]); - } - - framebuffer.renderTexture = renderTexture; - - this.setFramebuffer(null); - - return framebuffer; - }, - - /** - * Wrapper for creating a WebGLProgram - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#createProgram - * @since 3.0.0 - * - * @param {string} vertexShader - Source to the vertex shader - * @param {string} fragmentShader - Source to the fragment shader - * - * @return {WebGLProgram} Raw WebGLProgram - */ - createProgram: function (vertexShader, fragmentShader) - { - var gl = this.gl; - var program = gl.createProgram(); - var vs = gl.createShader(gl.VERTEX_SHADER); - var fs = gl.createShader(gl.FRAGMENT_SHADER); - - gl.shaderSource(vs, vertexShader); - gl.shaderSource(fs, fragmentShader); - gl.compileShader(vs); - gl.compileShader(fs); - - if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) - { - throw new Error('Failed to compile Vertex Shader:\n' + gl.getShaderInfoLog(vs)); - } - if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) - { - throw new Error('Failed to compile Fragment Shader:\n' + gl.getShaderInfoLog(fs)); - } - - gl.attachShader(program, vs); - gl.attachShader(program, fs); - gl.linkProgram(program); - - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) - { - throw new Error('Failed to link program:\n' + gl.getProgramInfoLog(program)); - } - - return program; - }, - - /** - * Wrapper for creating a vertex buffer. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#createVertexBuffer - * @since 3.0.0 - * - * @param {ArrayBuffer} initialDataOrSize - It's either ArrayBuffer or an integer indicating the size of the vbo - * @param {integer} bufferUsage - How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW - * - * @return {WebGLBuffer} Raw vertex buffer - */ - createVertexBuffer: function (initialDataOrSize, bufferUsage) - { - var gl = this.gl; - var vertexBuffer = gl.createBuffer(); - - this.setVertexBuffer(vertexBuffer); - - gl.bufferData(gl.ARRAY_BUFFER, initialDataOrSize, bufferUsage); - - this.setVertexBuffer(null); - - return vertexBuffer; - }, - - /** - * Wrapper for creating a vertex buffer. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#createIndexBuffer - * @since 3.0.0 - * - * @param {ArrayBuffer} initialDataOrSize - Either ArrayBuffer or an integer indicating the size of the vbo. - * @param {integer} bufferUsage - How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW. - * - * @return {WebGLBuffer} Raw index buffer - */ - createIndexBuffer: function (initialDataOrSize, bufferUsage) - { - var gl = this.gl; - var indexBuffer = gl.createBuffer(); - - this.setIndexBuffer(indexBuffer); - - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, initialDataOrSize, bufferUsage); - - this.setIndexBuffer(null); - - return indexBuffer; - }, - - /** - * Removes the given texture from the nativeTextures array and then deletes it from the GPU. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteTexture - * @since 3.0.0 - * - * @param {WebGLTexture} texture - The WebGL Texture to be deleted. - * - * @return {this} This WebGLRenderer instance. - */ - deleteTexture: function (texture) - { - var index = this.nativeTextures.indexOf(texture); - - if (index !== -1) - { - SpliceOne(this.nativeTextures, index); - } - - this.gl.deleteTexture(texture); - - if (this.currentTextures[0] === texture && !this.game.pendingDestroy) - { - // texture we just deleted is in use, so bind a blank texture - this.setBlankTexture(true); - } - - return this; - }, - - /** - * Deletes a WebGLFramebuffer from the GL instance. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteFramebuffer - * @since 3.0.0 - * - * @param {WebGLFramebuffer} framebuffer - The Framebuffer to be deleted. - * - * @return {this} This WebGLRenderer instance. - */ - deleteFramebuffer: function (framebuffer) - { - this.gl.deleteFramebuffer(framebuffer); - - return this; - }, - - /** - * Deletes a WebGLProgram from the GL instance. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteProgram - * @since 3.0.0 - * - * @param {WebGLProgram} program - The shader program to be deleted. - * - * @return {this} This WebGLRenderer instance. - */ - deleteProgram: function (program) - { - this.gl.deleteProgram(program); - - return this; - }, - - /** - * Deletes a WebGLBuffer from the GL instance. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteBuffer - * @since 3.0.0 - * - * @param {WebGLBuffer} vertexBuffer - The WebGLBuffer to be deleted. - * - * @return {this} This WebGLRenderer instance. - */ - deleteBuffer: function (buffer) - { - this.gl.deleteBuffer(buffer); - - return this; - }, - - /** - * Controls the pre-render operations for the given camera. - * Handles any clipping needed by the camera and renders the background color if a color is visible. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#preRenderCamera - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to pre-render. - */ - preRenderCamera: function (camera) - { - var cx = camera._cx; - var cy = camera._cy; - var cw = camera._cw; - var ch = camera._ch; - - var TextureTintPipeline = this.pipelines.TextureTintPipeline; - - var color = camera.backgroundColor; - - if (camera.renderToTexture) - { - this.flush(); - - this.pushScissor(cx, cy, cw, -ch); - - this.setFramebuffer(camera.framebuffer); - - var gl = this.gl; - - gl.clearColor(0, 0, 0, 0); - - gl.clear(gl.COLOR_BUFFER_BIT); - - TextureTintPipeline.projOrtho(cx, cw + cx, cy, ch + cy, -1000, 1000); - - if (camera.mask) - { - this.currentCameraMask.mask = camera.mask; - this.currentCameraMask.camera = camera._maskCamera; - - camera.mask.preRenderWebGL(this, camera, camera._maskCamera); - } - - if (color.alphaGL > 0) - { - TextureTintPipeline.drawFillRect( - cx, cy, cw + cx, ch + cy, - Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), - color.alphaGL - ); - } - - camera.emit(CameraEvents.PRE_RENDER, camera); - } - else - { - this.pushScissor(cx, cy, cw, ch); - - if (camera.mask) - { - this.currentCameraMask.mask = camera.mask; - this.currentCameraMask.camera = camera._maskCamera; - - camera.mask.preRenderWebGL(this, camera, camera._maskCamera); - } - - if (color.alphaGL > 0) - { - TextureTintPipeline.drawFillRect( - cx, cy, cw , ch, - Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), - color.alphaGL - ); - } - } - }, - - getCurrentStencilMask: function () - { - var prev = null; - var stack = this.maskStack; - var cameraMask = this.currentCameraMask; - - if (stack.length > 0) - { - prev = stack[stack.length - 1]; - } - else if (cameraMask.mask && cameraMask.mask.isStencil) - { - prev = cameraMask; - } - - return prev; - }, - - /** - * Controls the post-render operations for the given camera. - * Renders the foreground camera effects like flash and fading. It resets the current scissor state. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#postRenderCamera - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to post-render. - */ - postRenderCamera: function (camera) - { - var TextureTintPipeline = this.pipelines.TextureTintPipeline; - - camera.flashEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); - camera.fadeEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); - - camera.dirty = false; - - this.popScissor(); - - if (camera.renderToTexture) - { - TextureTintPipeline.flush(); - - this.setFramebuffer(null); - - camera.emit(CameraEvents.POST_RENDER, camera); - - if (camera.renderToGame) - { - TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); - - var getTint = Utils.getTintAppendFloatAlpha; - - var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; - - pipeline.batchTexture( - camera, - camera.glTexture, - camera.width, camera.height, - camera.x, camera.y, - camera.width, camera.height, - camera.zoom, camera.zoom, - camera.rotation, - camera.flipX, !camera.flipY, - 1, 1, - 0, 0, - 0, 0, camera.width, camera.height, - getTint(camera._tintTL, camera._alphaTL), - getTint(camera._tintTR, camera._alphaTR), - getTint(camera._tintBL, camera._alphaBL), - getTint(camera._tintBR, camera._alphaBR), - (camera._isTinted && camera.tintFill), - 0, 0, - this.defaultCamera, - null - ); - } - - // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it - this.setBlankTexture(true); - } - - if (camera.mask) - { - this.currentCameraMask.mask = null; - - camera.mask.postRenderWebGL(this, camera._maskCamera); - } - }, - - /** - * Clears the current vertex buffer and updates pipelines. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#preRender - * @since 3.0.0 - */ - preRender: function () - { - if (this.contextLost) { return; } - - var gl = this.gl; - var pipelines = this.pipelines; - - // Make sure we are bound to the main frame buffer - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - - if (this.config.clearBeforeRender) - { - var clearColor = this.config.backgroundColor; - - gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, clearColor.alphaGL); - - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); - } - - gl.enable(gl.SCISSOR_TEST); - - for (var key in pipelines) - { - pipelines[key].onPreRender(); - } - - // TODO - Find a way to stop needing to create these arrays every frame - // and equally not need a huge array buffer created to hold them - - this.currentScissor = [ 0, 0, this.width, this.height ]; - this.scissorStack = [ this.currentScissor ]; - - if (this.game.scene.customViewports) - { - gl.scissor(0, (this.drawingBufferHeight - this.height), this.width, this.height); - } - - this.currentMask.mask = null; - this.currentCameraMask.mask = null; - this.maskStack.length = 0; - - this.setPipeline(this.pipelines.TextureTintPipeline); - }, - - /** - * The core render step for a Scene Camera. - * - * Iterates through the given Game Object's array and renders them with the given Camera. - * - * This is called by the `CameraManager.render` method. The Camera Manager instance belongs to a Scene, and is invoked - * by the Scene Systems.render method. - * - * This method is not called if `Camera.visible` is `false`, or `Camera.alpha` is zero. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#render - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to render. - * @param {Phaser.GameObjects.GameObject} children - The Game Object's within the Scene to be rendered. - * @param {number} interpolationPercentage - The interpolation percentage to apply. Currently un-used. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera to render with. - */ - render: function (scene, children, interpolationPercentage, camera) - { - if (this.contextLost) { return; } - - var list = children.list; - var childCount = list.length; - var pipelines = this.pipelines; - - for (var key in pipelines) - { - pipelines[key].onRender(scene, camera); - } - - // Apply scissor for cam region + render background color, if not transparent - this.preRenderCamera(camera); - - // Nothing to render, so bail out - if (childCount === 0) - { - this.setBlendMode(CONST.BlendModes.NORMAL); - - // Applies camera effects and pops the scissor, if set - this.postRenderCamera(camera); - - return; - } - - // Reset the current type - this.currentType = ''; - - var current = this.currentMask; - - for (var i = 0; i < childCount; i++) - { - var child = list[i]; - - if (!child.willRender(camera)) - { - continue; - } - - if (child.blendMode !== this.currentBlendMode) - { - this.setBlendMode(child.blendMode); - } - - var mask = child.mask; - - current = this.currentMask; - - if (current.mask && current.mask !== mask) - { - // Render out the previously set mask - current.mask.postRenderWebGL(this, current.camera); - } - - if (mask && current.mask !== mask) - { - mask.preRenderWebGL(this, child, camera); - } - - var type = child.type; - - if (type !== this.currentType) - { - this.newType = true; - this.currentType = type; - } - - this.nextTypeMatch = (i < childCount - 1) ? (list[i + 1].type === this.currentType) : false; - - child.renderWebGL(this, child, interpolationPercentage, camera); - - this.newType = false; - } - - current = this.currentMask; - - if (current.mask) - { - // Render out the previously set mask, if it was the last item in the display list - current.mask.postRenderWebGL(this, current.camera); - } - - this.setBlendMode(CONST.BlendModes.NORMAL); - - // Applies camera effects and pops the scissor, if set - this.postRenderCamera(camera); - }, - - /** - * The post-render step happens after all Cameras in all Scenes have been rendered. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#postRender - * @since 3.0.0 - */ - postRender: function () - { - if (this.contextLost) { return; } - - this.flush(); - - // Unbind custom framebuffer here - - var state = this.snapshotState; - - if (state.callback) - { - WebGLSnapshot(this.canvas, state); - - state.callback = null; - } - - var pipelines = this.pipelines; - - for (var key in pipelines) - { - pipelines[key].onPostRender(); - } - }, - - /** - * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. - * - * To capture a specific area see the `snapshotArea` 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#snapshot - * @since 3.0.0 - * - * @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. - */ - snapshot: function (callback, type, encoderOptions) - { - return this.snapshotArea(0, 0, this.gl.drawingBufferWidth, this.gl.drawingBufferHeight, callback, type, encoderOptions); - }, - - /** - * 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 {integer} x - The x coordinate to grab from. - * @param {integer} y - The y coordinate to grab from. - * @param {integer} width - The width of the area to grab. - * @param {integer} 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. - */ - snapshotArea: function (x, y, width, height, callback, type, encoderOptions) - { - var state = this.snapshotState; - - state.callback = callback; - state.type = type; - state.encoder = encoderOptions; - state.getPixel = false; - state.x = x; - state.y = y; - state.width = Math.min(width, this.gl.drawingBufferWidth); - state.height = Math.min(height, this.gl.drawingBufferHeight); - - return this; - }, - - /** - * 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 {integer} x - The x coordinate of the pixel to get. - * @param {integer} y - The y coordinate of the pixel to get. - * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. - * - * @return {this} This WebGL Renderer. - */ - snapshotPixel: function (x, y, callback) - { - this.snapshotArea(x, y, 1, 1, callback); - - this.snapshotState.getPixel = true; - - return this; - }, - - /** - * 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 {WebGLFramebuffer} framebuffer - The framebuffer to grab from. - * @param {integer} bufferWidth - The width of the framebuffer. - * @param {integer} 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 {integer} [x=0] - The x coordinate to grab from. - * @param {integer} [y=0] - The y coordinate to grab from. - * @param {integer} [width=bufferWidth] - The width of the area to grab. - * @param {integer} [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. - */ - snapshotFramebuffer: function (framebuffer, bufferWidth, bufferHeight, callback, getPixel, x, y, width, height, type, encoderOptions) - { - if (getPixel === undefined) { getPixel = false; } - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = bufferWidth; } - if (height === undefined) { height = bufferHeight; } - - var currentFramebuffer = this.currentFramebuffer; - - this.snapshotArea(x, y, width, height, callback, type, encoderOptions); - - var state = this.snapshotState; - - state.getPixel = getPixel; - - state.isFramebuffer = true; - state.bufferWidth = bufferWidth; - state.bufferHeight = bufferHeight; - - this.setFramebuffer(framebuffer); - - WebGLSnapshot(this.canvas, state); - - this.setFramebuffer(currentFramebuffer); - - state.callback = null; - state.isFramebuffer = false; - - return this; - }, - - /** - * 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 {WebGLTexture} [dstTexture] - The destination WebGL Texture to set. - * @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT` (such as for Text objects?) - * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? - * - * @return {WebGLTexture} The newly created, or updated, WebGL Texture. - */ - canvasToTexture: function (srcCanvas, dstTexture, noRepeat, flipY) - { - if (noRepeat === undefined) { noRepeat = false; } - if (flipY === undefined) { flipY = false; } - - if (!dstTexture) - { - return this.createCanvasTexture(srcCanvas, noRepeat, flipY); - } - else - { - return this.updateCanvasTexture(srcCanvas, dstTexture, flipY); - } - }, - - /** - * 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=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? - * - * @return {WebGLTexture} The newly created WebGL Texture. - */ - createCanvasTexture: function (srcCanvas, noRepeat, flipY) - { - if (noRepeat === undefined) { noRepeat = false; } - if (flipY === undefined) { flipY = false; } - - var gl = this.gl; - var minFilter = gl.NEAREST; - var magFilter = gl.NEAREST; - - var width = srcCanvas.width; - var height = srcCanvas.height; - - var wrapping = gl.CLAMP_TO_EDGE; - - var pow = IsSizePowerOfTwo(width, height); - - if (!noRepeat && pow) - { - wrapping = gl.REPEAT; - } - - if (this.config.antialias) - { - minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; - magFilter = gl.LINEAR; - } - - return this.createTexture2D(0, minFilter, magFilter, wrapping, wrapping, gl.RGBA, srcCanvas, width, height, true, false, flipY); - }, - - /** - * 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 {WebGLTexture} dstTexture - The destination WebGL Texture to update. - * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? - * - * @return {WebGLTexture} The updated WebGL Texture. - */ - updateCanvasTexture: function (srcCanvas, dstTexture, flipY) - { - if (flipY === undefined) { flipY = false; } - - var gl = this.gl; - - var width = srcCanvas.width; - var height = srcCanvas.height; - - if (width > 0 && height > 0) - { - this.setTexture2D(dstTexture, 0); - - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcCanvas); - - dstTexture.width = width; - dstTexture.height = height; - - this.setTexture2D(null, 0); - } - - return dstTexture; - }, - - /** - * 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=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? - * - * @return {WebGLTexture} The newly created WebGL Texture. - */ - createVideoTexture: function (srcVideo, noRepeat, flipY) - { - if (noRepeat === undefined) { noRepeat = false; } - if (flipY === undefined) { flipY = false; } - - var gl = this.gl; - var minFilter = gl.NEAREST; - var magFilter = gl.NEAREST; - - var width = srcVideo.videoWidth; - var height = srcVideo.videoHeight; - - var wrapping = gl.CLAMP_TO_EDGE; - - var pow = IsSizePowerOfTwo(width, height); - - if (!noRepeat && pow) - { - wrapping = gl.REPEAT; - } - - if (this.config.antialias) - { - minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; - magFilter = gl.LINEAR; - } - - return this.createTexture2D(0, minFilter, magFilter, wrapping, wrapping, gl.RGBA, srcVideo, width, height, true, true, flipY); - }, - - /** - * 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 {WebGLTexture} dstTexture - The destination WebGL Texture to update. - * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? - * - * @return {WebGLTexture} The updated WebGL Texture. - */ - updateVideoTexture: function (srcVideo, dstTexture, flipY) - { - if (flipY === undefined) { flipY = false; } - - var gl = this.gl; - - var width = srcVideo.videoWidth; - var height = srcVideo.videoHeight; - - if (width > 0 && height > 0) - { - this.setTexture2D(dstTexture, 0); - - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcVideo); - - dstTexture.width = width; - dstTexture.height = height; - - this.setTexture2D(null, 0); - } - - return dstTexture; - }, - - /** - * Sets the minification and magnification filter for a texture. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setTextureFilter - * @since 3.0.0 - * - * @param {integer} texture - The texture to set the filter for. - * @param {integer} filter - The filter to set. 0 for linear filtering, 1 for nearest neighbor (blocky) filtering. - * - * @return {this} This WebGL Renderer instance. - */ - setTextureFilter: function (texture, filter) - { - var gl = this.gl; - var glFilter = [ gl.LINEAR, gl.NEAREST ][filter]; - - this.setTexture2D(texture, 0); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter); - - this.setTexture2D(null, 0); - - return this; - }, - - /** - * Sets a 1f uniform value on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 1f value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat1: function (program, name, x) - { - this.setProgram(program); - - this.gl.uniform1f(this.gl.getUniformLocation(program, name), x); - - return this; - }, - - /** - * Sets the 2f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 2f x value to set on the named uniform. - * @param {number} y - The 2f y value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat2: function (program, name, x, y) - { - this.setProgram(program); - - this.gl.uniform2f(this.gl.getUniformLocation(program, name), x, y); - - return this; - }, - - /** - * Sets the 3f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 3f x value to set on the named uniform. - * @param {number} y - The 3f y value to set on the named uniform. - * @param {number} z - The 3f z value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat3: function (program, name, x, y, z) - { - this.setProgram(program); - - this.gl.uniform3f(this.gl.getUniformLocation(program, name), x, y, z); - - return this; - }, - - /** - * Sets the 4f uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {number} x - The 4f x value to set on the named uniform. - * @param {number} y - The 4f y value to set on the named uniform. - * @param {number} z - The 4f z value to set on the named uniform. - * @param {number} w - The 4f w value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat4: function (program, name, x, y, z, w) - { - this.setProgram(program); - - this.gl.uniform4f(this.gl.getUniformLocation(program, name), x, y, z, w); - - return this; - }, - - /** - * Sets the value of a 1fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1v - * @since 3.13.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat1v: function (program, name, arr) - { - this.setProgram(program); - - this.gl.uniform1fv(this.gl.getUniformLocation(program, name), arr); - - return this; - }, - - /** - * Sets the value of a 2fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2v - * @since 3.13.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat2v: function (program, name, arr) - { - this.setProgram(program); - - this.gl.uniform2fv(this.gl.getUniformLocation(program, name), arr); - - return this; - }, - - /** - * Sets the value of a 3fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3v - * @since 3.13.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGL Renderer instance. - */ - setFloat3v: function (program, name, arr) - { - this.setProgram(program); - - this.gl.uniform3fv(this.gl.getUniformLocation(program, name), arr); - - return this; - }, - - /** - * Sets the value of a 4fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4v - * @since 3.13.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {Float32Array} arr - The new value to be used for the uniform variable. - * - * @return {this} This WebGL Renderer instance. - */ - - setFloat4v: function (program, name, arr) - { - this.setProgram(program); - - this.gl.uniform4fv(this.gl.getUniformLocation(program, name), arr); - - return this; - }, - - /** - * Sets a 1i uniform value on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt1 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 1i value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setInt1: function (program, name, x) - { - this.setProgram(program); - - this.gl.uniform1i(this.gl.getUniformLocation(program, name), x); - - return this; - }, - - /** - * Sets the 2i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt2 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 2i x value to set on the named uniform. - * @param {integer} y - The 2i y value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setInt2: function (program, name, x, y) - { - this.setProgram(program); - - this.gl.uniform2i(this.gl.getUniformLocation(program, name), x, y); - - return this; - }, - - /** - * Sets the 3i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt3 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 3i x value to set on the named uniform. - * @param {integer} y - The 3i y value to set on the named uniform. - * @param {integer} z - The 3i z value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setInt3: function (program, name, x, y, z) - { - this.setProgram(program); - - this.gl.uniform3i(this.gl.getUniformLocation(program, name), x, y, z); - - return this; - }, - - /** - * Sets the 4i uniform values on the given shader. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt4 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {integer} x - The 4i x value to set on the named uniform. - * @param {integer} y - The 4i y value to set on the named uniform. - * @param {integer} z - The 4i z value to set on the named uniform. - * @param {integer} w - The 4i w value to set on the named uniform. - * - * @return {this} This WebGL Renderer instance. - */ - setInt4: function (program, name, x, y, z, w) - { - this.setProgram(program); - - this.gl.uniform4i(this.gl.getUniformLocation(program, name), x, y, z, w); - - return this; - }, - - /** - * Sets the value of a matrix 2fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix2 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 4 float values. - * - * @return {this} This WebGL Renderer instance. - */ - setMatrix2: function (program, name, transpose, matrix) - { - this.setProgram(program); - - this.gl.uniformMatrix2fv(this.gl.getUniformLocation(program, name), transpose, matrix); - - return this; - }, - - /** - * Sets the value of a matrix 3fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix3 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 9 float values. - * - * @return {this} This WebGL Renderer instance. - */ - setMatrix3: function (program, name, transpose, matrix) - { - this.setProgram(program); - - this.gl.uniformMatrix3fv(this.gl.getUniformLocation(program, name), transpose, matrix); - - return this; - }, - - /** - * Sets the value of a matrix 4fv uniform variable in the given WebGLProgram. - * - * If the shader is not currently active, it is made active first. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix4 - * @since 3.0.0 - * - * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. - * @param {string} name - The name of the uniform to look-up and modify. - * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. - * @param {Float32Array} matrix - A Float32Array or sequence of 16 float values. - * - * @return {this} This WebGL Renderer instance. - */ - setMatrix4: function (program, name, transpose, matrix) - { - this.setProgram(program); - - this.gl.uniformMatrix4fv(this.gl.getUniformLocation(program, name), transpose, matrix); - - return this; - }, - - /** - * Returns the maximum number of texture units that can be used in a fragment shader. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#getMaxTextures - * @since 3.8.0 - * - * @return {integer} The maximum number of textures WebGL supports. - */ - getMaxTextures: function () - { - return this.config.maxTextures; - }, - - /** - * Returns the largest texture size (either width or height) that can be created. - * Note that VRAM may not allow a texture of any given size, it just expresses - * hardware / driver support for a given size. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#getMaxTextureSize - * @since 3.8.0 - * - * @return {integer} The maximum supported texture size. - */ - getMaxTextureSize: function () - { - return this.config.maxTextureSize; - }, - - /** - * Destroy this WebGLRenderer, cleaning up all related resources such as pipelines, native textures, etc. - * - * @method Phaser.Renderer.WebGL.WebGLRenderer#destroy - * @since 3.0.0 - */ - destroy: function () - { - // Clear-up anything that should be cleared :) - - for (var i = 0; i < this.nativeTextures.length; i++) - { - this.gl.deleteTexture(this.nativeTextures[i]); - } - - this.nativeTextures = []; - - for (var key in this.pipelines) - { - this.pipelines[key].destroy(); - - delete this.pipelines[key]; - } - - this.defaultCamera.destroy(); - - this.currentMask = null; - this.currentCameraMask = null; - - this.canvas.removeEventListener('webglcontextlost', this.contextLostHandler, false); - this.canvas.removeEventListener('webglcontextrestored', this.contextRestoredHandler, false); - - this.game = null; - this.gl = null; - this.canvas = null; - - this.maskStack = []; - - this.contextLost = true; - - this.extensions = {}; - } - -}); - -module.exports = WebGLRenderer; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseCamera = require('../../cameras/2d/BaseCamera'); +var CameraEvents = require('../../cameras/2d/events'); +var Class = require('../../utils/Class'); +var CONST = require('../../const'); +var GameEvents = require('../../core/events'); +var IsSizePowerOfTwo = require('../../math/pow2/IsSizePowerOfTwo'); +var NOOP = require('../../utils/NOOP'); +var ScaleEvents = require('../../scale/events'); +var SpliceOne = require('../../utils/array/SpliceOne'); +var TextureEvents = require('../../textures/events'); +var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); +var Utils = require('./Utils'); +var WebGLSnapshot = require('../snapshot/WebGLSnapshot'); + +// Default Pipelines +var BitmapMaskPipeline = require('./pipelines/BitmapMaskPipeline'); +var ForwardDiffuseLightPipeline = require('./pipelines/ForwardDiffuseLightPipeline'); +var TextureTintPipeline = require('./pipelines/TextureTintPipeline'); +var TextureTintStripPipeline = require('./pipelines/TextureTintStripPipeline'); + +/** + * @callback WebGLContextCallback + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGL Renderer which owns the context. + */ + +/** + * @classdesc + * WebGLRenderer is a class that contains the needed functionality to keep the + * WebGLRenderingContext state clean. The main idea of the WebGLRenderer is to keep track of + * any context change that happens for WebGL rendering inside of Phaser. This means + * if raw webgl functions are called outside the WebGLRenderer of the Phaser WebGL + * rendering ecosystem they might pollute the current WebGLRenderingContext state producing + * unexpected behavior. It's recommended that WebGL interaction is done through + * WebGLRenderer and/or WebGLPipeline. + * + * @class WebGLRenderer + * @memberof Phaser.Renderer.WebGL + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Game instance which owns this WebGL Renderer. + */ +var WebGLRenderer = new Class({ + + initialize: + + function WebGLRenderer (game) + { + var gameConfig = game.config; + + var contextCreationConfig = { + alpha: gameConfig.transparent, + desynchronized: gameConfig.desynchronized, + depth: false, + antialias: gameConfig.antialiasGL, + premultipliedAlpha: gameConfig.premultipliedAlpha, + stencil: true, + failIfMajorPerformanceCaveat: gameConfig.failIfMajorPerformanceCaveat, + powerPreference: gameConfig.powerPreference + }; + + /** + * The local configuration settings of this WebGL Renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#config + * @type {object} + * @since 3.0.0 + */ + this.config = { + clearBeforeRender: gameConfig.clearBeforeRender, + antialias: gameConfig.antialias, + backgroundColor: gameConfig.backgroundColor, + contextCreation: contextCreationConfig, + resolution: gameConfig.resolution, + roundPixels: gameConfig.roundPixels, + maxTextures: gameConfig.maxTextures, + maxTextureSize: gameConfig.maxTextureSize, + batchSize: gameConfig.batchSize, + maxLights: gameConfig.maxLights, + mipmapFilter: gameConfig.mipmapFilter + }; + + /** + * The Game instance which owns this WebGL Renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * A constant which allows the renderer to be easily identified as a WebGL Renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#type + * @type {integer} + * @since 3.0.0 + */ + this.type = CONST.WEBGL; + + /** + * The width of the canvas being rendered to. + * This is populated in the onResize event handler. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#width + * @type {integer} + * @since 3.0.0 + */ + this.width = 0; + + /** + * The height of the canvas being rendered to. + * This is populated in the onResize event handler. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#height + * @type {integer} + * @since 3.0.0 + */ + this.height = 0; + + /** + * The canvas which this WebGL Renderer draws to. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas = game.canvas; + + /** + * An array of blend modes supported by the WebGL Renderer. + * + * This array includes the default blend modes as well as any custom blend modes added through {@link #addBlendMode}. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#blendModes + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.blendModes = []; + + /** + * Keeps track of any WebGLTexture created with the current WebGLRenderingContext + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#nativeTextures + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.nativeTextures = []; + + /** + * This property is set to `true` if the WebGL context of the renderer is lost. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#contextLost + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.contextLost = false; + + /** + * This object will store all pipelines created through addPipeline + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#pipelines + * @type {object} + * @default null + * @since 3.0.0 + */ + this.pipelines = null; + + /** + * Details about the currently scheduled snapshot. + * + * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#snapshotState + * @type {Phaser.Types.Renderer.Snapshot.SnapshotState} + * @since 3.0.0 + */ + this.snapshotState = { + x: 0, + y: 0, + width: 1, + height: 1, + getPixel: false, + callback: null, + type: 'image/png', + encoder: 0.92, + isFramebuffer: false, + bufferWidth: 0, + bufferHeight: 0 + }; + + // Internal Renderer State (Textures, Framebuffers, Pipelines, Buffers, etc) + + /** + * Cached value for the last texture unit that was used + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentActiveTextureUnit + * @type {integer} + * @since 3.1.0 + */ + this.currentActiveTextureUnit = 0; + + /** + * An array of the last texture handles that were bound to the WebGLRenderingContext + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentTextures + * @type {array} + * @since 3.0.0 + */ + this.currentTextures = new Array(16); + + /** + * Current framebuffer in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentFramebuffer + * @type {WebGLFramebuffer} + * @default null + * @since 3.0.0 + */ + this.currentFramebuffer = null; + + /** + * Current WebGLPipeline in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentPipeline + * @type {Phaser.Renderer.WebGL.WebGLPipeline} + * @default null + * @since 3.0.0 + */ + this.currentPipeline = null; + + /** + * Current WebGLProgram in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentProgram + * @type {WebGLProgram} + * @default null + * @since 3.0.0 + */ + this.currentProgram = null; + + /** + * Current WebGLBuffer (Vertex buffer) in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentVertexBuffer + * @type {WebGLBuffer} + * @default null + * @since 3.0.0 + */ + this.currentVertexBuffer = null; + + /** + * Current WebGLBuffer (Index buffer) in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentIndexBuffer + * @type {WebGLBuffer} + * @default null + * @since 3.0.0 + */ + this.currentIndexBuffer = null; + + /** + * Current blend mode in use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentBlendMode + * @type {integer} + * @since 3.0.0 + */ + this.currentBlendMode = Infinity; + + /** + * Indicates if the the scissor state is enabled in WebGLRenderingContext + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentScissorEnabled + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.currentScissorEnabled = false; + + /** + * Stores the current scissor data + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentScissor + * @type {Uint32Array} + * @since 3.0.0 + */ + this.currentScissor = null; + + /** + * Stack of scissor data + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#scissorStack + * @type {Uint32Array} + * @since 3.0.0 + */ + this.scissorStack = []; + + /** + * The handler to invoke when the context is lost. + * This should not be changed and is set in the boot method. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#contextLostHandler + * @type {function} + * @since 3.19.0 + */ + this.contextLostHandler = NOOP; + + /** + * The handler to invoke when the context is restored. + * This should not be changed and is set in the boot method. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#contextRestoredHandler + * @type {function} + * @since 3.19.0 + */ + this.contextRestoredHandler = NOOP; + + /** + * The underlying WebGL context of the renderer. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#gl + * @type {WebGLRenderingContext} + * @default null + * @since 3.0.0 + */ + this.gl = null; + + /** + * Array of strings that indicate which WebGL extensions are supported by the browser + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#supportedExtensions + * @type {object} + * @default null + * @since 3.0.0 + */ + this.supportedExtensions = null; + + /** + * Extensions loaded into the current context + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#extensions + * @type {object} + * @default {} + * @since 3.0.0 + */ + this.extensions = {}; + + /** + * Stores the current WebGL component formats for further use + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#glFormats + * @type {array} + * @default [] + * @since 3.2.0 + */ + this.glFormats = []; + + /** + * Stores the supported WebGL texture compression formats. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#compression + * @type {array} + * @since 3.8.0 + */ + this.compression = { + ETC1: false, + PVRTC: false, + S3TC: false + }; + + /** + * Cached drawing buffer height to reduce gl calls. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#drawingBufferHeight + * @type {number} + * @readonly + * @since 3.11.0 + */ + this.drawingBufferHeight = 0; + + /** + * A blank 32x32 transparent texture, as used by the Graphics system where needed. + * This is set in the `boot` method. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#blankTexture + * @type {WebGLTexture} + * @readonly + * @since 3.12.0 + */ + this.blankTexture = null; + + /** + * A default Camera used in calls when no other camera has been provided. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#defaultCamera + * @type {Phaser.Cameras.Scene2D.BaseCamera} + * @since 3.12.0 + */ + this.defaultCamera = new BaseCamera(0, 0, 0, 0); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#_tempMatrix4 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.12.0 + */ + this._tempMatrix4 = new TransformMatrix(); + + /** + * The total number of masks currently stacked. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#maskCount + * @type {integer} + * @since 3.17.0 + */ + this.maskCount = 0; + + /** + * The mask stack. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#maskStack + * @type {Phaser.Display.Masks.GeometryMask[]} + * @since 3.17.0 + */ + this.maskStack = []; + + /** + * Internal property that tracks the currently set mask. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentMask + * @type {any} + * @since 3.17.0 + */ + this.currentMask = { mask: null, camera: null }; + + /** + * Internal property that tracks the currently set camera mask. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentCameraMask + * @type {any} + * @since 3.17.0 + */ + this.currentCameraMask = { mask: null, camera: null }; + + /** + * Internal gl function mapping for uniform look-up. + * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#glFuncMap + * @type {any} + * @since 3.17.0 + */ + this.glFuncMap = null; + + /** + * The `type` of the Game Object being currently rendered. + * This can be used by advanced render functions for batching look-ahead. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#currentType + * @type {string} + * @since 3.19.0 + */ + this.currentType = ''; + + /** + * Is the `type` of the Game Object being currently rendered different than the + * type of the object before it in the display list? I.e. it's a 'new' type. + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#newType + * @type {boolean} + * @since 3.19.0 + */ + this.newType = false; + + /** + * Does the `type` of the next Game Object in the display list match that + * of the object being currently rendered? + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#nextTypeMatch + * @type {boolean} + * @since 3.19.0 + */ + this.nextTypeMatch = false; + + /** + * The mipmap magFilter to be used when creating textures. + * + * You can specify this as a string in the game config, i.e.: + * + * `renderer: { 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 + * + * @name Phaser.Renderer.WebGL.WebGLRenderer#mipmapFilter + * @type {GLenum} + * @since 3.21.0 + */ + this.mipmapFilter = null; + + this.init(this.config); + }, + + /** + * Creates a new WebGLRenderingContext and initializes all internal state. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#init + * @since 3.0.0 + * + * @param {object} config - The configuration object for the renderer. + * + * @return {this} This WebGLRenderer instance. + */ + init: function (config) + { + var gl; + var game = this.game; + var canvas = this.canvas; + var clearColor = config.backgroundColor; + + // Did they provide their own context? + if (game.config.context) + { + gl = game.config.context; + } + else + { + gl = canvas.getContext('webgl', config.contextCreation) || canvas.getContext('experimental-webgl', config.contextCreation); + } + + if (!gl || gl.isContextLost()) + { + this.contextLost = true; + + throw new Error('WebGL unsupported'); + } + + this.gl = gl; + + var _this = this; + + this.contextLostHandler = function (event) + { + _this.contextLost = true; + + _this.game.events.emit(GameEvents.CONTEXT_LOST, _this); + + event.preventDefault(); + }; + + this.contextRestoredHandler = function () + { + _this.contextLost = false; + + _this.init(_this.config); + + _this.game.events.emit(GameEvents.CONTEXT_RESTORED, _this); + }; + + canvas.addEventListener('webglcontextlost', this.contextLostHandler, false); + canvas.addEventListener('webglcontextrestored', this.contextRestoredHandler, false); + + // Set it back into the Game, so developers can access it from there too + game.context = gl; + + for (var i = 0; i <= 27; i++) + { + this.blendModes.push({ func: [ gl.ONE, gl.ONE_MINUS_SRC_ALPHA ], equation: gl.FUNC_ADD }); + } + + // ADD + this.blendModes[1].func = [ gl.ONE, gl.DST_ALPHA ]; + + // MULTIPLY + this.blendModes[2].func = [ gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA ]; + + // SCREEN + this.blendModes[3].func = [ gl.ONE, gl.ONE_MINUS_SRC_COLOR ]; + + // ERASE + this.blendModes[17] = { func: [ gl.ZERO, gl.ONE_MINUS_SRC_ALPHA ], equation: gl.FUNC_REVERSE_SUBTRACT }; + + this.glFormats[0] = gl.BYTE; + this.glFormats[1] = gl.SHORT; + this.glFormats[2] = gl.UNSIGNED_BYTE; + this.glFormats[3] = gl.UNSIGNED_SHORT; + this.glFormats[4] = gl.FLOAT; + + // Set the gl function map + this.glFuncMap = { + + mat2: { func: gl.uniformMatrix2fv, length: 1, matrix: true }, + mat3: { func: gl.uniformMatrix3fv, length: 1, matrix: true }, + mat4: { func: gl.uniformMatrix4fv, length: 1, matrix: true }, + + '1f': { func: gl.uniform1f, length: 1 }, + '1fv': { func: gl.uniform1fv, length: 1 }, + '1i': { func: gl.uniform1i, length: 1 }, + '1iv': { func: gl.uniform1iv, length: 1 }, + + '2f': { func: gl.uniform2f, length: 2 }, + '2fv': { func: gl.uniform2fv, length: 1 }, + '2i': { func: gl.uniform2i, length: 2 }, + '2iv': { func: gl.uniform2iv, length: 1 }, + + '3f': { func: gl.uniform3f, length: 3 }, + '3fv': { func: gl.uniform3fv, length: 1 }, + '3i': { func: gl.uniform3i, length: 3 }, + '3iv': { func: gl.uniform3iv, length: 1 }, + + '4f': { func: gl.uniform4f, length: 4 }, + '4fv': { func: gl.uniform4fv, length: 1 }, + '4i': { func: gl.uniform4i, length: 4 }, + '4iv': { func: gl.uniform4iv, length: 1 } + + }; + + // Load supported extensions + var exts = gl.getSupportedExtensions(); + + if (!config.maxTextures) + { + config.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + } + + if (!config.maxTextureSize) + { + config.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + } + + var extString = 'WEBGL_compressed_texture_'; + var wkExtString = 'WEBKIT_' + extString; + + this.compression.ETC1 = gl.getExtension(extString + 'etc1') || gl.getExtension(wkExtString + 'etc1'); + this.compression.PVRTC = gl.getExtension(extString + 'pvrtc') || gl.getExtension(wkExtString + 'pvrtc'); + this.compression.S3TC = gl.getExtension(extString + 's3tc') || gl.getExtension(wkExtString + 's3tc'); + + this.supportedExtensions = exts; + + // Setup initial WebGL state + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + + gl.enable(gl.BLEND); + + gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, clearColor.alphaGL); + + // Mipmaps + this.mipmapFilter = gl[config.mipmapFilter]; + + // Initialize all textures to null + for (var index = 0; index < this.currentTextures.length; ++index) + { + this.currentTextures[index] = null; + } + + // Clear previous pipelines and reload default ones + this.pipelines = {}; + + this.addPipeline('TextureTintPipeline', new TextureTintPipeline({ game: game, renderer: this })); + this.addPipeline('TextureTintStripPipeline', new TextureTintStripPipeline({ game: game, renderer: this })); + this.addPipeline('BitmapMaskPipeline', new BitmapMaskPipeline({ game: game, renderer: this })); + this.addPipeline('Light2D', new ForwardDiffuseLightPipeline({ game: game, renderer: this, maxLights: config.maxLights })); + + this.setBlendMode(CONST.BlendModes.NORMAL); + + game.textures.once(TextureEvents.READY, this.boot, this); + + return this; + }, + + /** + * Internal boot handler. Calls 'boot' on each pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#boot + * @private + * @since 3.11.0 + */ + boot: function () + { + for (var pipelineName in this.pipelines) + { + this.pipelines[pipelineName].boot(); + } + + var blank = this.game.textures.getFrame('__DEFAULT'); + + this.pipelines.TextureTintPipeline.currentFrame = blank; + + this.blankTexture = blank; + + var gl = this.gl; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + gl.enable(gl.SCISSOR_TEST); + + this.setPipeline(this.pipelines.TextureTintPipeline); + + this.game.scale.on(ScaleEvents.RESIZE, this.onResize, this); + + var baseSize = this.game.scale.baseSize; + + this.resize(baseSize.width, baseSize.height, this.game.scale.resolution); + }, + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#onResize + * @since 3.16.0 + * + * @param {Phaser.Structs.Size} gameSize - The default Game Size object. This is the un-modified game dimensions. + * @param {Phaser.Structs.Size} baseSize - The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + * @param {Phaser.Structs.Size} displaySize - The display Size object. The size of the canvas style width / height attributes. + * @param {number} [resolution] - The Scale Manager resolution setting. + */ + onResize: function (gameSize, baseSize, displaySize, resolution) + { + // Has the underlying canvas size changed? + if (baseSize.width !== this.width || baseSize.height !== this.height || resolution !== this.resolution) + { + this.resize(baseSize.width, baseSize.height, resolution); + } + }, + + /** + * Resizes the drawing buffer to match that required by the Scale Manager. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#resize + * @since 3.0.0 + * + * @param {number} [width] - The new width of the renderer. + * @param {number} [height] - The new height of the renderer. + * @param {number} [resolution] - The new resolution of the renderer. + * + * @return {this} This WebGLRenderer instance. + */ + resize: function (width, height, resolution) + { + var gl = this.gl; + var pipelines = this.pipelines; + + this.width = width; + this.height = height; + this.resolution = resolution; + + gl.viewport(0, 0, width, height); + + // Update all registered pipelines + for (var pipelineName in pipelines) + { + pipelines[pipelineName].resize(width, height, resolution); + } + + this.drawingBufferHeight = gl.drawingBufferHeight; + + gl.scissor(0, (gl.drawingBufferHeight - height), width, height); + + this.defaultCamera.setSize(width, height); + + return this; + }, + + /** + * Checks if a WebGL extension is supported + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#hasExtension + * @since 3.0.0 + * + * @param {string} extensionName - Name of the WebGL extension + * + * @return {boolean} `true` if the extension is supported, otherwise `false`. + */ + hasExtension: function (extensionName) + { + return this.supportedExtensions ? this.supportedExtensions.indexOf(extensionName) : false; + }, + + /** + * Loads a WebGL extension + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getExtension + * @since 3.0.0 + * + * @param {string} extensionName - The name of the extension to load. + * + * @return {object} WebGL extension if the extension is supported + */ + getExtension: function (extensionName) + { + if (!this.hasExtension(extensionName)) { return null; } + + if (!(extensionName in this.extensions)) + { + this.extensions[extensionName] = this.gl.getExtension(extensionName); + } + + return this.extensions[extensionName]; + }, + + /** + * Flushes the current pipeline if the pipeline is bound + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#flush + * @since 3.0.0 + */ + flush: function () + { + if (this.currentPipeline) + { + this.currentPipeline.flush(); + } + }, + + /** + * Checks if a pipeline is present in the current WebGLRenderer + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#hasPipeline + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline. + * + * @return {boolean} `true` if the given pipeline is loaded, otherwise `false`. + */ + hasPipeline: function (pipelineName) + { + return (pipelineName in this.pipelines); + }, + + /** + * Returns the pipeline by name if the pipeline exists + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getPipeline + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline. + * + * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline instance, or `null` if not found. + */ + getPipeline: function (pipelineName) + { + return (this.hasPipeline(pipelineName)) ? this.pipelines[pipelineName] : null; + }, + + /** + * Removes a pipeline by name. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#removePipeline + * @since 3.0.0 + * + * @param {string} pipelineName - The name of the pipeline to be removed. + * + * @return {this} This WebGLRenderer instance. + */ + removePipeline: function (pipelineName) + { + delete this.pipelines[pipelineName]; + + return this; + }, + + /** + * Adds a pipeline instance into the collection of pipelines + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#addPipeline + * @since 3.0.0 + * + * @param {string} pipelineName - A unique string-based key for the pipeline. + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - A pipeline instance which must extend WebGLPipeline. + * + * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline instance that was passed. + */ + addPipeline: function (pipelineName, pipelineInstance) + { + if (!this.hasPipeline(pipelineName)) + { + this.pipelines[pipelineName] = pipelineInstance; + } + else + { + console.warn('Pipeline exists: ' + pipelineName); + } + + pipelineInstance.name = pipelineName; + + this.pipelines[pipelineName].resize(this.width, this.height, this.config.resolution); + + return pipelineInstance; + }, + + /** + * Pushes a new scissor state. This is used to set nested scissor states. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#pushScissor + * @since 3.0.0 + * + * @param {integer} x - The x position of the scissor. + * @param {integer} y - The y position of the scissor. + * @param {integer} width - The width of the scissor. + * @param {integer} height - The height of the scissor. + * @param {integer} [drawingBufferHeight] - Optional drawingBufferHeight override value. + * + * @return {integer[]} An array containing the scissor values. + */ + pushScissor: function (x, y, width, height, drawingBufferHeight) + { + if (drawingBufferHeight === undefined) { drawingBufferHeight = this.drawingBufferHeight; } + + var scissorStack = this.scissorStack; + + var scissor = [ x, y, width, height ]; + + scissorStack.push(scissor); + + this.setScissor(x, y, width, height, drawingBufferHeight); + + this.currentScissor = scissor; + + return scissor; + }, + + /** + * Sets the current scissor state. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setScissor + * @since 3.0.0 + * + * @param {integer} x - The x position of the scissor. + * @param {integer} y - The y position of the scissor. + * @param {integer} width - The width of the scissor. + * @param {integer} height - The height of the scissor. + * @param {integer} [drawingBufferHeight] - Optional drawingBufferHeight override value. + */ + setScissor: function (x, y, width, height, drawingBufferHeight) + { + if (drawingBufferHeight === undefined) { drawingBufferHeight = this.drawingBufferHeight; } + + var gl = this.gl; + + var current = this.currentScissor; + + var setScissor = (width > 0 && height > 0); + + if (current && setScissor) + { + var cx = current[0]; + var cy = current[1]; + var cw = current[2]; + var ch = current[3]; + + setScissor = (cx !== x || cy !== y || cw !== width || ch !== height); + } + + if (setScissor) + { + this.flush(); + + // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/scissor + gl.scissor(x, (drawingBufferHeight - y - height), width, height); + } + }, + + /** + * Pops the last scissor state and sets it. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#popScissor + * @since 3.0.0 + */ + popScissor: function () + { + var scissorStack = this.scissorStack; + + // Remove the current scissor + scissorStack.pop(); + + // Reset the previous scissor + var scissor = scissorStack[scissorStack.length - 1]; + + if (scissor) + { + this.setScissor(scissor[0], scissor[1], scissor[2], scissor[3]); + } + + this.currentScissor = scissor; + }, + + /** + * Binds a WebGLPipeline and sets it as the current pipeline to be used. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setPipeline + * @since 3.0.0 + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - The pipeline instance to be activated. + * @param {Phaser.GameObjects.GameObject} [gameObject] - The Game Object that invoked this pipeline, if any. + * + * @return {Phaser.Renderer.WebGL.WebGLPipeline} The pipeline that was activated. + */ + setPipeline: function (pipelineInstance, gameObject) + { + if (this.currentPipeline !== pipelineInstance || + this.currentPipeline.vertexBuffer !== this.currentVertexBuffer || + this.currentPipeline.program !== this.currentProgram) + { + this.flush(); + this.currentPipeline = pipelineInstance; + this.currentPipeline.bind(); + } + + this.currentPipeline.onBind(gameObject); + + return this.currentPipeline; + }, + + /** + * Is there an active stencil mask? + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#hasActiveStencilMask + * @since 3.17.0 + * + * @return {boolean} `true` if there is an active stencil mask, otherwise `false`. + */ + hasActiveStencilMask: function () + { + var mask = this.currentMask.mask; + var camMask = this.currentCameraMask.mask; + + return ((mask && mask.isStencil) || (camMask && camMask.isStencil)); + }, + + /** + * Use this to reset the gl context to the state that Phaser requires to continue rendering. + * Calling this will: + * + * * Disable `DEPTH_TEST`, `CULL_FACE` and `STENCIL_TEST`. + * * Clear the depth buffer and stencil buffers. + * * Reset the viewport size. + * * Reset the blend mode. + * * Bind a blank texture as the active texture on texture unit zero. + * * Rebinds the given pipeline instance. + * + * You should call this having previously called `clearPipeline` and then wishing to return + * control to Phaser again. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#rebindPipeline + * @since 3.16.0 + * + * @param {Phaser.Renderer.WebGL.WebGLPipeline} pipelineInstance - The pipeline instance to be activated. + */ + rebindPipeline: function (pipelineInstance) + { + var gl = this.gl; + + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + + if (this.hasActiveStencilMask()) + { + gl.clear(gl.DEPTH_BUFFER_BIT); + } + else + { + // If there wasn't a stencil mask set before this call, we can disable it safely + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + } + + gl.viewport(0, 0, this.width, this.height); + + this.setBlendMode(0, true); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, this.blankTexture.glTexture); + + this.currentActiveTextureUnit = 0; + this.currentTextures[0] = this.blankTexture.glTexture; + + this.currentPipeline = pipelineInstance; + this.currentPipeline.bind(); + this.currentPipeline.onBind(); + }, + + /** + * Flushes the current WebGLPipeline being used and then clears it, along with the + * the current shader program and vertex buffer. Then resets the blend mode to NORMAL. + * Call this before jumping to your own gl context handler, and then call `rebindPipeline` when + * you wish to return control to Phaser again. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#clearPipeline + * @since 3.16.0 + */ + clearPipeline: function () + { + this.flush(); + + this.currentPipeline = null; + this.currentProgram = null; + this.currentVertexBuffer = null; + this.currentIndexBuffer = null; + + this.setBlendMode(0, true); + }, + + /** + * Sets the blend mode to the value given. + * + * If the current blend mode is different from the one given, the pipeline is flushed and the new + * blend mode is enabled. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setBlendMode + * @since 3.0.0 + * + * @param {integer} blendModeId - The blend mode to be set. Can be a `BlendModes` const or an integer value. + * @param {boolean} [force=false] - Force the blend mode to be set, regardless of the currently set blend mode. + * + * @return {boolean} `true` if the blend mode was changed as a result of this call, forcing a flush, otherwise `false`. + */ + setBlendMode: function (blendModeId, force) + { + if (force === undefined) { force = false; } + + var gl = this.gl; + var blendMode = this.blendModes[blendModeId]; + + if (force || (blendModeId !== CONST.BlendModes.SKIP_CHECK && this.currentBlendMode !== blendModeId)) + { + this.flush(); + + gl.enable(gl.BLEND); + gl.blendEquation(blendMode.equation); + + if (blendMode.func.length > 2) + { + gl.blendFuncSeparate(blendMode.func[0], blendMode.func[1], blendMode.func[2], blendMode.func[3]); + } + else + { + gl.blendFunc(blendMode.func[0], blendMode.func[1]); + } + + this.currentBlendMode = blendModeId; + + return true; + } + + return false; + }, + + /** + * 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 {integer} The index of the new blend mode, used for referencing it in the future. + */ + addBlendMode: function (func, equation) + { + var index = this.blendModes.push({ func: func, equation: equation }); + + return index - 1; + }, + + /** + * Updates the function bound to a given custom blend mode. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#updateBlendMode + * @since 3.0.0 + * + * @param {integer} index - The index of the custom blend mode. + * @param {function} func - The function to use for the blend mode. + * @param {function} equation - The equation to use for the blend mode. + * + * @return {this} This WebGLRenderer instance. + */ + updateBlendMode: function (index, func, equation) + { + if (this.blendModes[index]) + { + this.blendModes[index].func = func; + + if (equation) + { + this.blendModes[index].equation = equation; + } + } + + return this; + }, + + /** + * Removes a custom blend mode from the renderer. + * Any Game Objects still using this blend mode will error, so be sure to clear them first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#removeBlendMode + * @since 3.0.0 + * + * @param {integer} index - The index of the custom blend mode to be removed. + * + * @return {this} This WebGLRenderer instance. + */ + removeBlendMode: function (index) + { + if (index > 17 && this.blendModes[index]) + { + this.blendModes.splice(index, 1); + } + + return this; + }, + + /** + * Sets the current active texture for texture unit zero to be a blank texture. + * This only happens if there isn't a texture already in use by texture unit zero. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setBlankTexture + * @private + * @since 3.12.0 + * + * @param {boolean} [force=false] - Force a blank texture set, regardless of what's already bound? + */ + setBlankTexture: function (force) + { + if (force === undefined) { force = false; } + + if (force || this.currentActiveTextureUnit !== 0 || !this.currentTextures[0]) + { + this.setTexture2D(this.blankTexture.glTexture, 0); + } + }, + + /** + * Binds a texture at a texture unit. If a texture is already + * bound to that unit it will force a flush on the current pipeline. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setTexture2D + * @since 3.0.0 + * + * @param {WebGLTexture} texture - The WebGL texture that needs to be bound. + * @param {integer} textureUnit - The texture unit to which the texture will be bound. + * @param {boolean} [flush=true] - Will the current pipeline be flushed if this is a new texture, or not? + * + * @return {this} This WebGLRenderer instance. + */ + setTexture2D: function (texture, textureUnit, flush) + { + if (flush === undefined) { flush = true; } + + var gl = this.gl; + + if (texture !== this.currentTextures[textureUnit]) + { + if (flush) + { + this.flush(); + } + + if (this.currentActiveTextureUnit !== textureUnit) + { + gl.activeTexture(gl.TEXTURE0 + textureUnit); + + this.currentActiveTextureUnit = textureUnit; + } + + gl.bindTexture(gl.TEXTURE_2D, texture); + + this.currentTextures[textureUnit] = texture; + } + + return this; + }, + + /** + * Binds a framebuffer. If there was another framebuffer already bound it will force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFramebuffer + * @since 3.0.0 + * + * @param {WebGLFramebuffer} framebuffer - The framebuffer that needs to be bound. + * @param {boolean} [updateScissor=false] - If a framebuffer is given, set the gl scissor to match the frame buffer size? Or, if `null` given, pop the scissor from the stack. + * + * @return {this} This WebGLRenderer instance. + */ + setFramebuffer: function (framebuffer, updateScissor) + { + if (updateScissor === undefined) { updateScissor = false; } + + var gl = this.gl; + + var width = this.width; + var height = this.height; + + if (framebuffer !== this.currentFramebuffer) + { + if (framebuffer && framebuffer.renderTexture) + { + width = framebuffer.renderTexture.width; + height = framebuffer.renderTexture.height; + } + else + { + this.flush(); + } + + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + + gl.viewport(0, 0, width, height); + + if (updateScissor) + { + if (framebuffer) + { + this.drawingBufferHeight = height; + + this.pushScissor(0, 0, width, height); + } + else + { + this.drawingBufferHeight = this.height; + + this.popScissor(); + } + } + + this.currentFramebuffer = framebuffer; + } + + return this; + }, + + /** + * Binds a program. If there was another program already bound it will force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setProgram + * @since 3.0.0 + * + * @param {WebGLProgram} program - The program that needs to be bound. + * + * @return {this} This WebGLRenderer instance. + */ + setProgram: function (program) + { + var gl = this.gl; + + if (program !== this.currentProgram) + { + this.flush(); + + gl.useProgram(program); + + this.currentProgram = program; + } + + return this; + }, + + /** + * Bounds a vertex buffer. If there is a vertex buffer already bound it'll force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setVertexBuffer + * @since 3.0.0 + * + * @param {WebGLBuffer} vertexBuffer - The buffer that needs to be bound. + * + * @return {this} This WebGLRenderer instance. + */ + setVertexBuffer: function (vertexBuffer) + { + var gl = this.gl; + + if (vertexBuffer !== this.currentVertexBuffer) + { + this.flush(); + + gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); + + this.currentVertexBuffer = vertexBuffer; + } + + return this; + }, + + /** + * Bounds a index buffer. If there is a index buffer already bound it'll force a pipeline flush. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setIndexBuffer + * @since 3.0.0 + * + * @param {WebGLBuffer} indexBuffer - The buffer the needs to be bound. + * + * @return {this} This WebGLRenderer instance. + */ + setIndexBuffer: function (indexBuffer) + { + var gl = this.gl; + + if (indexBuffer !== this.currentIndexBuffer) + { + this.flush(); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); + + this.currentIndexBuffer = indexBuffer; + } + + return this; + }, + + /** + * Creates a texture from an image source. If the source is not valid it creates an empty texture. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createTextureFromSource + * @since 3.0.0 + * + * @param {object} source - The source of the texture. + * @param {integer} width - The width of the texture. + * @param {integer} height - The height of the texture. + * @param {integer} scaleMode - The scale mode to be used by the texture. + * + * @return {?WebGLTexture} The WebGL Texture that was created, or `null` if it couldn't be created. + */ + createTextureFromSource: function (source, width, height, scaleMode) + { + var gl = this.gl; + var minFilter = gl.NEAREST; + var magFilter = gl.NEAREST; + var wrap = gl.CLAMP_TO_EDGE; + var texture = null; + + width = source ? source.width : width; + height = source ? source.height : height; + + var pow = IsSizePowerOfTwo(width, height); + + if (pow) + { + wrap = gl.REPEAT; + } + + if (scaleMode === CONST.ScaleModes.LINEAR && this.config.antialias) + { + minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; + magFilter = gl.LINEAR; + } + + if (!source && typeof width === 'number' && typeof height === 'number') + { + texture = this.createTexture2D(0, minFilter, magFilter, wrap, wrap, gl.RGBA, null, width, height); + } + else + { + texture = this.createTexture2D(0, minFilter, magFilter, wrap, wrap, gl.RGBA, source); + } + + return texture; + }, + + /** + * A wrapper for creating a WebGLTexture. If no pixel data is passed it will create an empty texture. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createTexture2D + * @since 3.0.0 + * + * @param {integer} mipLevel - Mip level of the texture. + * @param {integer} minFilter - Filtering of the texture. + * @param {integer} magFilter - Filtering of the texture. + * @param {integer} wrapT - Wrapping mode of the texture. + * @param {integer} wrapS - Wrapping mode of the texture. + * @param {integer} format - Which format does the texture use. + * @param {?object} pixels - pixel data. + * @param {integer} width - Width of the texture in pixels. + * @param {integer} height - Height of the texture in pixels. + * @param {boolean} [pma=true] - Does the texture have premultiplied alpha? + * @param {boolean} [forceSize=false] - If `true` it will use the width and height passed to this method, regardless of the pixels dimension. + * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + * + * @return {WebGLTexture} The WebGLTexture that was created. + */ + createTexture2D: function (mipLevel, minFilter, magFilter, wrapT, wrapS, format, pixels, width, height, pma, forceSize, flipY) + { + pma = (pma === undefined || pma === null) ? true : pma; + if (forceSize === undefined) { forceSize = false; } + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + var texture = gl.createTexture(); + + this.setTexture2D(texture, 0); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, pma); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + + if (pixels === null || pixels === undefined) + { + gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, width, height, 0, format, gl.UNSIGNED_BYTE, null); + } + else + { + if (!forceSize) + { + width = pixels.width; + height = pixels.height; + } + + gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, format, gl.UNSIGNED_BYTE, pixels); + } + + if (IsSizePowerOfTwo(width, height)) + { + gl.generateMipmap(gl.TEXTURE_2D); + } + + this.setTexture2D(null, 0); + + texture.isAlphaPremultiplied = pma; + texture.isRenderTexture = false; + texture.width = width; + texture.height = height; + + this.nativeTextures.push(texture); + + return texture; + }, + + /** + * Wrapper for creating WebGLFramebuffer. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createFramebuffer + * @since 3.0.0 + * + * @param {integer} width - Width in pixels of the framebuffer + * @param {integer} height - Height in pixels of the framebuffer + * @param {WebGLTexture} renderTexture - The color texture to where the color pixels are written + * @param {boolean} addDepthStencilBuffer - Indicates if the current framebuffer support depth and stencil buffers + * + * @return {WebGLFramebuffer} Raw WebGLFramebuffer + */ + createFramebuffer: function (width, height, renderTexture, addDepthStencilBuffer) + { + var gl = this.gl; + var framebuffer = gl.createFramebuffer(); + var complete = 0; + + this.setFramebuffer(framebuffer); + + if (addDepthStencilBuffer) + { + var depthStencilBuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); + } + + renderTexture.isRenderTexture = true; + renderTexture.isAlphaPremultiplied = false; + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, renderTexture, 0); + + complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + + if (complete !== gl.FRAMEBUFFER_COMPLETE) + { + var errors = { + 36054: 'Incomplete Attachment', + 36055: 'Missing Attachment', + 36057: 'Incomplete Dimensions', + 36061: 'Framebuffer Unsupported' + }; + + throw new Error('Framebuffer incomplete. Framebuffer status: ' + errors[complete]); + } + + framebuffer.renderTexture = renderTexture; + + this.setFramebuffer(null); + + return framebuffer; + }, + + /** + * Wrapper for creating a WebGLProgram + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createProgram + * @since 3.0.0 + * + * @param {string} vertexShader - Source to the vertex shader + * @param {string} fragmentShader - Source to the fragment shader + * + * @return {WebGLProgram} Raw WebGLProgram + */ + createProgram: function (vertexShader, fragmentShader) + { + var gl = this.gl; + var program = gl.createProgram(); + var vs = gl.createShader(gl.VERTEX_SHADER); + var fs = gl.createShader(gl.FRAGMENT_SHADER); + + gl.shaderSource(vs, vertexShader); + gl.shaderSource(fs, fragmentShader); + gl.compileShader(vs); + gl.compileShader(fs); + + if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) + { + throw new Error('Failed to compile Vertex Shader:\n' + gl.getShaderInfoLog(vs)); + } + if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) + { + throw new Error('Failed to compile Fragment Shader:\n' + gl.getShaderInfoLog(fs)); + } + + gl.attachShader(program, vs); + gl.attachShader(program, fs); + gl.linkProgram(program); + + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + throw new Error('Failed to link program:\n' + gl.getProgramInfoLog(program)); + } + + return program; + }, + + /** + * Wrapper for creating a vertex buffer. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createVertexBuffer + * @since 3.0.0 + * + * @param {ArrayBuffer} initialDataOrSize - It's either ArrayBuffer or an integer indicating the size of the vbo + * @param {integer} bufferUsage - How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW + * + * @return {WebGLBuffer} Raw vertex buffer + */ + createVertexBuffer: function (initialDataOrSize, bufferUsage) + { + var gl = this.gl; + var vertexBuffer = gl.createBuffer(); + + this.setVertexBuffer(vertexBuffer); + + gl.bufferData(gl.ARRAY_BUFFER, initialDataOrSize, bufferUsage); + + this.setVertexBuffer(null); + + return vertexBuffer; + }, + + /** + * Wrapper for creating a vertex buffer. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#createIndexBuffer + * @since 3.0.0 + * + * @param {ArrayBuffer} initialDataOrSize - Either ArrayBuffer or an integer indicating the size of the vbo. + * @param {integer} bufferUsage - How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW. + * + * @return {WebGLBuffer} Raw index buffer + */ + createIndexBuffer: function (initialDataOrSize, bufferUsage) + { + var gl = this.gl; + var indexBuffer = gl.createBuffer(); + + this.setIndexBuffer(indexBuffer); + + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, initialDataOrSize, bufferUsage); + + this.setIndexBuffer(null); + + return indexBuffer; + }, + + /** + * Removes the given texture from the nativeTextures array and then deletes it from the GPU. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteTexture + * @since 3.0.0 + * + * @param {WebGLTexture} texture - The WebGL Texture to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteTexture: function (texture) + { + var index = this.nativeTextures.indexOf(texture); + + if (index !== -1) + { + SpliceOne(this.nativeTextures, index); + } + + this.gl.deleteTexture(texture); + + if (this.currentTextures[0] === texture && !this.game.pendingDestroy) + { + // texture we just deleted is in use, so bind a blank texture + this.setBlankTexture(true); + } + + return this; + }, + + /** + * Deletes a WebGLFramebuffer from the GL instance. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteFramebuffer + * @since 3.0.0 + * + * @param {WebGLFramebuffer} framebuffer - The Framebuffer to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteFramebuffer: function (framebuffer) + { + this.gl.deleteFramebuffer(framebuffer); + + return this; + }, + + /** + * Deletes a WebGLProgram from the GL instance. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteProgram + * @since 3.0.0 + * + * @param {WebGLProgram} program - The shader program to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteProgram: function (program) + { + this.gl.deleteProgram(program); + + return this; + }, + + /** + * Deletes a WebGLBuffer from the GL instance. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#deleteBuffer + * @since 3.0.0 + * + * @param {WebGLBuffer} vertexBuffer - The WebGLBuffer to be deleted. + * + * @return {this} This WebGLRenderer instance. + */ + deleteBuffer: function (buffer) + { + this.gl.deleteBuffer(buffer); + + return this; + }, + + /** + * Controls the pre-render operations for the given camera. + * Handles any clipping needed by the camera and renders the background color if a color is visible. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#preRenderCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to pre-render. + */ + preRenderCamera: function (camera) + { + var cx = camera._cx; + var cy = camera._cy; + var cw = camera._cw; + var ch = camera._ch; + + var TextureTintPipeline = this.pipelines.TextureTintPipeline; + + var color = camera.backgroundColor; + + if (camera.renderToTexture) + { + this.flush(); + + this.pushScissor(cx, cy, cw, -ch); + + this.setFramebuffer(camera.framebuffer); + + var gl = this.gl; + + gl.clearColor(0, 0, 0, 0); + + gl.clear(gl.COLOR_BUFFER_BIT); + + TextureTintPipeline.projOrtho(cx, cw + cx, cy, ch + cy, -1000, 1000); + + if (camera.mask) + { + this.currentCameraMask.mask = camera.mask; + this.currentCameraMask.camera = camera._maskCamera; + + camera.mask.preRenderWebGL(this, camera, camera._maskCamera); + } + + if (color.alphaGL > 0) + { + TextureTintPipeline.drawFillRect( + cx, cy, cw + cx, ch + cy, + Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), + color.alphaGL + ); + } + + camera.emit(CameraEvents.PRE_RENDER, camera); + } + else + { + this.pushScissor(cx, cy, cw, ch); + + if (camera.mask) + { + this.currentCameraMask.mask = camera.mask; + this.currentCameraMask.camera = camera._maskCamera; + + camera.mask.preRenderWebGL(this, camera, camera._maskCamera); + } + + if (color.alphaGL > 0) + { + TextureTintPipeline.drawFillRect( + cx, cy, cw , ch, + Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), + color.alphaGL + ); + } + } + }, + + getCurrentStencilMask: function () + { + var prev = null; + var stack = this.maskStack; + var cameraMask = this.currentCameraMask; + + if (stack.length > 0) + { + prev = stack[stack.length - 1]; + } + else if (cameraMask.mask && cameraMask.mask.isStencil) + { + prev = cameraMask; + } + + return prev; + }, + + /** + * Controls the post-render operations for the given camera. + * Renders the foreground camera effects like flash and fading. It resets the current scissor state. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#postRenderCamera + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to post-render. + */ + postRenderCamera: function (camera) + { + var TextureTintPipeline = this.pipelines.TextureTintPipeline; + + camera.flashEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); + camera.fadeEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); + + camera.dirty = false; + + this.popScissor(); + + if (camera.renderToTexture) + { + TextureTintPipeline.flush(); + + this.setFramebuffer(null); + + camera.emit(CameraEvents.POST_RENDER, camera); + + if (camera.renderToGame) + { + TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1000.0, 1000.0); + + var getTint = Utils.getTintAppendFloatAlpha; + + var pipeline = (camera.pipeline) ? camera.pipeline : TextureTintPipeline; + + pipeline.batchTexture( + camera, + camera.glTexture, + camera.width, camera.height, + camera.x, camera.y, + camera.width, camera.height, + camera.zoom, camera.zoom, + camera.rotation, + camera.flipX, !camera.flipY, + 1, 1, + 0, 0, + 0, 0, camera.width, camera.height, + getTint(camera._tintTL, camera._alphaTL), + getTint(camera._tintTR, camera._alphaTR), + getTint(camera._tintBL, camera._alphaBL), + getTint(camera._tintBR, camera._alphaBR), + (camera._isTinted && camera.tintFill), + 0, 0, + this.defaultCamera, + null + ); + } + + // Force clear the current texture so that items next in the batch (like Graphics) don't try and use it + this.setBlankTexture(true); + } + + if (camera.mask) + { + this.currentCameraMask.mask = null; + + camera.mask.postRenderWebGL(this, camera._maskCamera); + } + }, + + /** + * Clears the current vertex buffer and updates pipelines. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#preRender + * @since 3.0.0 + */ + preRender: function () + { + if (this.contextLost) { return; } + + var gl = this.gl; + var pipelines = this.pipelines; + + // Make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.config.clearBeforeRender) + { + var clearColor = this.config.backgroundColor; + + gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, clearColor.alphaGL); + + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + } + + gl.enable(gl.SCISSOR_TEST); + + for (var key in pipelines) + { + pipelines[key].onPreRender(); + } + + // TODO - Find a way to stop needing to create these arrays every frame + // and equally not need a huge array buffer created to hold them + + this.currentScissor = [ 0, 0, this.width, this.height ]; + this.scissorStack = [ this.currentScissor ]; + + if (this.game.scene.customViewports) + { + gl.scissor(0, (this.drawingBufferHeight - this.height), this.width, this.height); + } + + this.currentMask.mask = null; + this.currentCameraMask.mask = null; + this.maskStack.length = 0; + + this.setPipeline(this.pipelines.TextureTintPipeline); + }, + + /** + * The core render step for a Scene Camera. + * + * Iterates through the given Game Object's array and renders them with the given Camera. + * + * This is called by the `CameraManager.render` method. The Camera Manager instance belongs to a Scene, and is invoked + * by the Scene Systems.render method. + * + * This method is not called if `Camera.visible` is `false`, or `Camera.alpha` is zero. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#render + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to render. + * @param {Phaser.GameObjects.GameObject} children - The Game Object's within the Scene to be rendered. + * @param {number} interpolationPercentage - The interpolation percentage to apply. Currently un-used. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera to render with. + */ + render: function (scene, children, interpolationPercentage, camera) + { + if (this.contextLost) { return; } + + var list = children.list; + var childCount = list.length; + var pipelines = this.pipelines; + + for (var key in pipelines) + { + pipelines[key].onRender(scene, camera); + } + + // Apply scissor for cam region + render background color, if not transparent + this.preRenderCamera(camera); + + // Nothing to render, so bail out + if (childCount === 0) + { + this.setBlendMode(CONST.BlendModes.NORMAL); + + // Applies camera effects and pops the scissor, if set + this.postRenderCamera(camera); + + return; + } + + // Reset the current type + this.currentType = ''; + + var current = this.currentMask; + + for (var i = 0; i < childCount; i++) + { + var child = list[i]; + + if (!child.willRender(camera)) + { + continue; + } + + if (child.blendMode !== this.currentBlendMode) + { + this.setBlendMode(child.blendMode); + } + + var mask = child.mask; + + current = this.currentMask; + + if (current.mask && current.mask !== mask) + { + // Render out the previously set mask + current.mask.postRenderWebGL(this, current.camera); + } + + if (mask && current.mask !== mask) + { + mask.preRenderWebGL(this, child, camera); + } + + var type = child.type; + + if (type !== this.currentType) + { + this.newType = true; + this.currentType = type; + } + + this.nextTypeMatch = (i < childCount - 1) ? (list[i + 1].type === this.currentType) : false; + + child.renderWebGL(this, child, interpolationPercentage, camera); + + this.newType = false; + } + + current = this.currentMask; + + if (current.mask) + { + // Render out the previously set mask, if it was the last item in the display list + current.mask.postRenderWebGL(this, current.camera); + } + + this.setBlendMode(CONST.BlendModes.NORMAL); + + // Applies camera effects and pops the scissor, if set + this.postRenderCamera(camera); + }, + + /** + * The post-render step happens after all Cameras in all Scenes have been rendered. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#postRender + * @since 3.0.0 + */ + postRender: function () + { + if (this.contextLost) { return; } + + this.flush(); + + // Unbind custom framebuffer here + + var state = this.snapshotState; + + if (state.callback) + { + WebGLSnapshot(this.canvas, state); + + state.callback = null; + } + + var pipelines = this.pipelines; + + for (var key in pipelines) + { + pipelines[key].onPostRender(); + } + }, + + /** + * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. + * + * To capture a specific area see the `snapshotArea` 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#snapshot + * @since 3.0.0 + * + * @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. + */ + snapshot: function (callback, type, encoderOptions) + { + return this.snapshotArea(0, 0, this.gl.drawingBufferWidth, this.gl.drawingBufferHeight, callback, type, encoderOptions); + }, + + /** + * 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 {integer} x - The x coordinate to grab from. + * @param {integer} y - The y coordinate to grab from. + * @param {integer} width - The width of the area to grab. + * @param {integer} 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. + */ + snapshotArea: function (x, y, width, height, callback, type, encoderOptions) + { + var state = this.snapshotState; + + state.callback = callback; + state.type = type; + state.encoder = encoderOptions; + state.getPixel = false; + state.x = x; + state.y = y; + state.width = Math.min(width, this.gl.drawingBufferWidth); + state.height = Math.min(height, this.gl.drawingBufferHeight); + + return this; + }, + + /** + * 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 {integer} x - The x coordinate of the pixel to get. + * @param {integer} y - The y coordinate of the pixel to get. + * @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted. + * + * @return {this} This WebGL Renderer. + */ + snapshotPixel: function (x, y, callback) + { + this.snapshotArea(x, y, 1, 1, callback); + + this.snapshotState.getPixel = true; + + return this; + }, + + /** + * 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 {WebGLFramebuffer} framebuffer - The framebuffer to grab from. + * @param {integer} bufferWidth - The width of the framebuffer. + * @param {integer} 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 {integer} [x=0] - The x coordinate to grab from. + * @param {integer} [y=0] - The y coordinate to grab from. + * @param {integer} [width=bufferWidth] - The width of the area to grab. + * @param {integer} [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. + */ + snapshotFramebuffer: function (framebuffer, bufferWidth, bufferHeight, callback, getPixel, x, y, width, height, type, encoderOptions) + { + if (getPixel === undefined) { getPixel = false; } + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = bufferWidth; } + if (height === undefined) { height = bufferHeight; } + + var currentFramebuffer = this.currentFramebuffer; + + this.snapshotArea(x, y, width, height, callback, type, encoderOptions); + + var state = this.snapshotState; + + state.getPixel = getPixel; + + state.isFramebuffer = true; + state.bufferWidth = bufferWidth; + state.bufferHeight = bufferHeight; + + this.setFramebuffer(framebuffer); + + WebGLSnapshot(this.canvas, state); + + this.setFramebuffer(currentFramebuffer); + + state.callback = null; + state.isFramebuffer = false; + + return this; + }, + + /** + * 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 {WebGLTexture} [dstTexture] - The destination WebGL Texture to set. + * @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT` (such as for Text objects?) + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The newly created, or updated, WebGL Texture. + */ + canvasToTexture: function (srcCanvas, dstTexture, noRepeat, flipY) + { + if (noRepeat === undefined) { noRepeat = false; } + if (flipY === undefined) { flipY = false; } + + if (!dstTexture) + { + return this.createCanvasTexture(srcCanvas, noRepeat, flipY); + } + else + { + return this.updateCanvasTexture(srcCanvas, dstTexture, flipY); + } + }, + + /** + * 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=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The newly created WebGL Texture. + */ + createCanvasTexture: function (srcCanvas, noRepeat, flipY) + { + if (noRepeat === undefined) { noRepeat = false; } + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + var minFilter = gl.NEAREST; + var magFilter = gl.NEAREST; + + var width = srcCanvas.width; + var height = srcCanvas.height; + + var wrapping = gl.CLAMP_TO_EDGE; + + var pow = IsSizePowerOfTwo(width, height); + + if (!noRepeat && pow) + { + wrapping = gl.REPEAT; + } + + if (this.config.antialias) + { + minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; + magFilter = gl.LINEAR; + } + + return this.createTexture2D(0, minFilter, magFilter, wrapping, wrapping, gl.RGBA, srcCanvas, width, height, true, false, flipY); + }, + + /** + * 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 {WebGLTexture} dstTexture - The destination WebGL Texture to update. + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The updated WebGL Texture. + */ + updateCanvasTexture: function (srcCanvas, dstTexture, flipY) + { + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + + var width = srcCanvas.width; + var height = srcCanvas.height; + + if (width > 0 && height > 0) + { + this.setTexture2D(dstTexture, 0); + + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcCanvas); + + dstTexture.width = width; + dstTexture.height = height; + + this.setTexture2D(null, 0); + } + + return dstTexture; + }, + + /** + * 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=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The newly created WebGL Texture. + */ + createVideoTexture: function (srcVideo, noRepeat, flipY) + { + if (noRepeat === undefined) { noRepeat = false; } + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + var minFilter = gl.NEAREST; + var magFilter = gl.NEAREST; + + var width = srcVideo.videoWidth; + var height = srcVideo.videoHeight; + + var wrapping = gl.CLAMP_TO_EDGE; + + var pow = IsSizePowerOfTwo(width, height); + + if (!noRepeat && pow) + { + wrapping = gl.REPEAT; + } + + if (this.config.antialias) + { + minFilter = (pow) ? this.mipmapFilter : gl.LINEAR; + magFilter = gl.LINEAR; + } + + return this.createTexture2D(0, minFilter, magFilter, wrapping, wrapping, gl.RGBA, srcVideo, width, height, true, true, flipY); + }, + + /** + * 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 {WebGLTexture} dstTexture - The destination WebGL Texture to update. + * @param {boolean} [flipY=false] - Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? + * + * @return {WebGLTexture} The updated WebGL Texture. + */ + updateVideoTexture: function (srcVideo, dstTexture, flipY) + { + if (flipY === undefined) { flipY = false; } + + var gl = this.gl; + + var width = srcVideo.videoWidth; + var height = srcVideo.videoHeight; + + if (width > 0 && height > 0) + { + this.setTexture2D(dstTexture, 0); + + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcVideo); + + dstTexture.width = width; + dstTexture.height = height; + + this.setTexture2D(null, 0); + } + + return dstTexture; + }, + + /** + * Sets the minification and magnification filter for a texture. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setTextureFilter + * @since 3.0.0 + * + * @param {integer} texture - The texture to set the filter for. + * @param {integer} filter - The filter to set. 0 for linear filtering, 1 for nearest neighbor (blocky) filtering. + * + * @return {this} This WebGL Renderer instance. + */ + setTextureFilter: function (texture, filter) + { + var gl = this.gl; + var glFilter = [ gl.LINEAR, gl.NEAREST ][filter]; + + this.setTexture2D(texture, 0); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter); + + this.setTexture2D(null, 0); + + return this; + }, + + /** + * Sets a 1f uniform value on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The 1f value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat1: function (program, name, x) + { + this.setProgram(program); + + this.gl.uniform1f(this.gl.getUniformLocation(program, name), x); + + return this; + }, + + /** + * Sets the 2f uniform values on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The 2f x value to set on the named uniform. + * @param {number} y - The 2f y value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat2: function (program, name, x, y) + { + this.setProgram(program); + + this.gl.uniform2f(this.gl.getUniformLocation(program, name), x, y); + + return this; + }, + + /** + * Sets the 3f uniform values on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The 3f x value to set on the named uniform. + * @param {number} y - The 3f y value to set on the named uniform. + * @param {number} z - The 3f z value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat3: function (program, name, x, y, z) + { + this.setProgram(program); + + this.gl.uniform3f(this.gl.getUniformLocation(program, name), x, y, z); + + return this; + }, + + /** + * Sets the 4f uniform values on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {number} x - The 4f x value to set on the named uniform. + * @param {number} y - The 4f y value to set on the named uniform. + * @param {number} z - The 4f z value to set on the named uniform. + * @param {number} w - The 4f w value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat4: function (program, name, x, y, z, w) + { + this.setProgram(program); + + this.gl.uniform4f(this.gl.getUniformLocation(program, name), x, y, z, w); + + return this; + }, + + /** + * Sets the value of a 1fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat1v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat1v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform1fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a 2fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat2v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat2v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform2fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a 3fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat3v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + setFloat3v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform3fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets the value of a 4fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setFloat4v + * @since 3.13.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {Float32Array} arr - The new value to be used for the uniform variable. + * + * @return {this} This WebGL Renderer instance. + */ + + setFloat4v: function (program, name, arr) + { + this.setProgram(program); + + this.gl.uniform4fv(this.gl.getUniformLocation(program, name), arr); + + return this; + }, + + /** + * Sets a 1i uniform value on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt1 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The 1i value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setInt1: function (program, name, x) + { + this.setProgram(program); + + this.gl.uniform1i(this.gl.getUniformLocation(program, name), x); + + return this; + }, + + /** + * Sets the 2i uniform values on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt2 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The 2i x value to set on the named uniform. + * @param {integer} y - The 2i y value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setInt2: function (program, name, x, y) + { + this.setProgram(program); + + this.gl.uniform2i(this.gl.getUniformLocation(program, name), x, y); + + return this; + }, + + /** + * Sets the 3i uniform values on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt3 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The 3i x value to set on the named uniform. + * @param {integer} y - The 3i y value to set on the named uniform. + * @param {integer} z - The 3i z value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setInt3: function (program, name, x, y, z) + { + this.setProgram(program); + + this.gl.uniform3i(this.gl.getUniformLocation(program, name), x, y, z); + + return this; + }, + + /** + * Sets the 4i uniform values on the given shader. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setInt4 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {integer} x - The 4i x value to set on the named uniform. + * @param {integer} y - The 4i y value to set on the named uniform. + * @param {integer} z - The 4i z value to set on the named uniform. + * @param {integer} w - The 4i w value to set on the named uniform. + * + * @return {this} This WebGL Renderer instance. + */ + setInt4: function (program, name, x, y, z, w) + { + this.setProgram(program); + + this.gl.uniform4i(this.gl.getUniformLocation(program, name), x, y, z, w); + + return this; + }, + + /** + * Sets the value of a matrix 2fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix2 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. + * @param {Float32Array} matrix - A Float32Array or sequence of 4 float values. + * + * @return {this} This WebGL Renderer instance. + */ + setMatrix2: function (program, name, transpose, matrix) + { + this.setProgram(program); + + this.gl.uniformMatrix2fv(this.gl.getUniformLocation(program, name), transpose, matrix); + + return this; + }, + + /** + * Sets the value of a matrix 3fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix3 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. + * @param {Float32Array} matrix - A Float32Array or sequence of 9 float values. + * + * @return {this} This WebGL Renderer instance. + */ + setMatrix3: function (program, name, transpose, matrix) + { + this.setProgram(program); + + this.gl.uniformMatrix3fv(this.gl.getUniformLocation(program, name), transpose, matrix); + + return this; + }, + + /** + * Sets the value of a matrix 4fv uniform variable in the given WebGLProgram. + * + * If the shader is not currently active, it is made active first. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#setMatrix4 + * @since 3.0.0 + * + * @param {WebGLProgram} program - The target WebGLProgram from which the uniform location will be looked-up. + * @param {string} name - The name of the uniform to look-up and modify. + * @param {boolean} transpose - The value indicating whether to transpose the matrix. Must be false. + * @param {Float32Array} matrix - A Float32Array or sequence of 16 float values. + * + * @return {this} This WebGL Renderer instance. + */ + setMatrix4: function (program, name, transpose, matrix) + { + this.setProgram(program); + + this.gl.uniformMatrix4fv(this.gl.getUniformLocation(program, name), transpose, matrix); + + return this; + }, + + /** + * Returns the maximum number of texture units that can be used in a fragment shader. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getMaxTextures + * @since 3.8.0 + * + * @return {integer} The maximum number of textures WebGL supports. + */ + getMaxTextures: function () + { + return this.config.maxTextures; + }, + + /** + * Returns the largest texture size (either width or height) that can be created. + * Note that VRAM may not allow a texture of any given size, it just expresses + * hardware / driver support for a given size. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#getMaxTextureSize + * @since 3.8.0 + * + * @return {integer} The maximum supported texture size. + */ + getMaxTextureSize: function () + { + return this.config.maxTextureSize; + }, + + /** + * Destroy this WebGLRenderer, cleaning up all related resources such as pipelines, native textures, etc. + * + * @method Phaser.Renderer.WebGL.WebGLRenderer#destroy + * @since 3.0.0 + */ + destroy: function () + { + // Clear-up anything that should be cleared :) + + for (var i = 0; i < this.nativeTextures.length; i++) + { + this.gl.deleteTexture(this.nativeTextures[i]); + } + + this.nativeTextures = []; + + for (var key in this.pipelines) + { + this.pipelines[key].destroy(); + + delete this.pipelines[key]; + } + + this.defaultCamera.destroy(); + + this.currentMask = null; + this.currentCameraMask = null; + + this.canvas.removeEventListener('webglcontextlost', this.contextLostHandler, false); + this.canvas.removeEventListener('webglcontextrestored', this.contextRestoredHandler, false); + + this.game = null; + this.gl = null; + this.canvas = null; + + this.maskStack = []; + + this.contextLost = true; + + this.extensions = {}; + } + +}); + +module.exports = WebGLRenderer; diff --git a/src/renderer/webgl/index.js b/src/renderer/webgl/index.js index f28c4ba41..898e686f2 100644 --- a/src/renderer/webgl/index.js +++ b/src/renderer/webgl/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.WebGL - */ - -module.exports = { - - Utils: require('./Utils'), - WebGLPipeline: require('./WebGLPipeline'), - WebGLRenderer: require('./WebGLRenderer'), - Pipelines: require('./pipelines'), - - // Constants - BYTE: 0, - SHORT: 1, - UNSIGNED_BYTE: 2, - UNSIGNED_SHORT: 3, - FLOAT: 4 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.WebGL + */ + +module.exports = { + + Utils: require('./Utils'), + WebGLPipeline: require('./WebGLPipeline'), + WebGLRenderer: require('./WebGLRenderer'), + Pipelines: require('./pipelines'), + + // Constants + BYTE: 0, + SHORT: 1, + UNSIGNED_BYTE: 2, + UNSIGNED_SHORT: 3, + FLOAT: 4 + +}; diff --git a/src/renderer/webgl/pipelines/BitmapMaskPipeline.js b/src/renderer/webgl/pipelines/BitmapMaskPipeline.js index 9d9870c18..3fd09eee2 100644 --- a/src/renderer/webgl/pipelines/BitmapMaskPipeline.js +++ b/src/renderer/webgl/pipelines/BitmapMaskPipeline.js @@ -1,259 +1,259 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var ShaderSourceFS = require('../shaders/BitmapMask-frag.js'); -var ShaderSourceVS = require('../shaders/BitmapMask-vert.js'); -var WebGLPipeline = require('../WebGLPipeline'); - -/** - * @classdesc - * BitmapMaskPipeline handles all bitmap masking rendering in WebGL. It works by using - * sampling two texture on the fragment shader and using the fragment's alpha to clip the region. - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - * @class BitmapMaskPipeline - * @extends Phaser.Renderer.WebGL.WebGLPipeline - * @memberof Phaser.Renderer.WebGL.Pipelines - * @constructor - * @since 3.0.0 - * - * @param {object} config - Used for overriding shader an pipeline properties if extending this pipeline. - */ -var BitmapMaskPipeline = new Class({ - - Extends: WebGLPipeline, - - initialize: - - function BitmapMaskPipeline (config) - { - WebGLPipeline.call(this, { - game: config.game, - renderer: config.renderer, - gl: config.renderer.gl, - topology: (config.topology ? config.topology : config.renderer.gl.TRIANGLES), - vertShader: (config.vertShader ? config.vertShader : ShaderSourceVS), - fragShader: (config.fragShader ? config.fragShader : ShaderSourceFS), - vertexCapacity: (config.vertexCapacity ? config.vertexCapacity : 3), - - vertexSize: (config.vertexSize ? config.vertexSize : - Float32Array.BYTES_PER_ELEMENT * 2), - - vertices: new Float32Array([ - -1, +1, -1, -7, +7, +1 - ]).buffer, - - attributes: [ - { - name: 'inPosition', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: 0 - } - ] - }); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#vertexViewF32 - * @type {Float32Array} - * @since 3.0.0 - */ - this.vertexViewF32 = new Float32Array(this.vertexData); - - /** - * Size of the batch. - * - * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#maxQuads - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.maxQuads = 1; - - /** - * Dirty flag to check if resolution properties need to be updated on the - * masking shader. - * - * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resolutionDirty - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.resolutionDirty = true; - }, - - /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - * - * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#onBind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - WebGLPipeline.prototype.onBind.call(this); - - var renderer = this.renderer; - var program = this.program; - - if (this.resolutionDirty) - { - renderer.setFloat2(program, 'uResolution', this.width, this.height); - renderer.setInt1(program, 'uMainSampler', 0); - renderer.setInt1(program, 'uMaskSampler', 1); - this.resolutionDirty = false; - } - - return this; - }, - - /** - * Resizes this pipeline and updates the projection. - * - * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resize - * @since 3.0.0 - * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - WebGLPipeline.prototype.resize.call(this, width, height, resolution); - - this.resolutionDirty = true; - - return this; - }, - - /** - * Binds necessary resources and renders the mask to a separated framebuffer. - * The framebuffer for the masked object is also bound for further use. - * - * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#beginMask - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} mask - GameObject used as mask. - * @param {Phaser.GameObjects.GameObject} maskedObject - GameObject masked by the mask GameObject. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera rendering the current mask. - */ - beginMask: function (mask, maskedObject, camera) - { - var renderer = this.renderer; - var gl = this.gl; - - // The renderable Game Object that is being used for the bitmap mask - var bitmapMask = mask.bitmapMask; - - if (bitmapMask && gl) - { - renderer.flush(); - - mask.prevFramebuffer = renderer.currentFramebuffer; - - renderer.setFramebuffer(mask.mainFramebuffer); - - gl.disable(gl.STENCIL_TEST); - - gl.clearColor(0, 0, 0, 0); - - gl.clear(gl.COLOR_BUFFER_BIT); - - if (renderer.currentCameraMask.mask !== mask) - { - renderer.currentMask.mask = mask; - renderer.currentMask.camera = camera; - } - } - }, - - /** - * The masked game objects framebuffer is unbound and its texture - * is bound together with the mask texture and the mask shader and - * a draw call with a single quad is processed. Here is where the - * masking effect is applied. - * - * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#endMask - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} mask - GameObject used as a mask. - */ - endMask: function (mask, camera) - { - var gl = this.gl; - var renderer = this.renderer; - - // The renderable Game Object that is being used for the bitmap mask - var bitmapMask = mask.bitmapMask; - - if (bitmapMask && gl) - { - renderer.flush(); - - // First we draw the mask to the mask fb - renderer.setFramebuffer(mask.maskFramebuffer); - - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - - renderer.setBlendMode(0, true); - - bitmapMask.renderWebGL(renderer, bitmapMask, 0, camera); - - renderer.flush(); - - renderer.setFramebuffer(mask.prevFramebuffer); - - // Is there a stencil further up the stack? - var prev = renderer.getCurrentStencilMask(); - - if (prev) - { - gl.enable(gl.STENCIL_TEST); - - prev.mask.applyStencil(renderer, prev.camera, true); - } - else - { - renderer.currentMask.mask = null; - } - - // Bind bitmap mask pipeline and draw - renderer.setPipeline(this); - - gl.activeTexture(gl.TEXTURE1); - gl.bindTexture(gl.TEXTURE_2D, mask.maskTexture); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, mask.mainTexture); - - gl.uniform1i(gl.getUniformLocation(this.program, 'uInvertMaskAlpha'), mask.invertAlpha); - - // Finally, draw a triangle filling the whole screen - gl.drawArrays(this.topology, 0, 3); - } - } - -}); - -module.exports = BitmapMaskPipeline; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var ShaderSourceFS = require('../shaders/BitmapMask-frag.js'); +var ShaderSourceVS = require('../shaders/BitmapMask-vert.js'); +var WebGLPipeline = require('../WebGLPipeline'); + +/** + * @classdesc + * BitmapMaskPipeline handles all bitmap masking rendering in WebGL. It works by using + * sampling two texture on the fragment shader and using the fragment's alpha to clip the region. + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * + * @class BitmapMaskPipeline + * @extends Phaser.Renderer.WebGL.WebGLPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.0.0 + * + * @param {object} config - Used for overriding shader an pipeline properties if extending this pipeline. + */ +var BitmapMaskPipeline = new Class({ + + Extends: WebGLPipeline, + + initialize: + + function BitmapMaskPipeline (config) + { + WebGLPipeline.call(this, { + game: config.game, + renderer: config.renderer, + gl: config.renderer.gl, + topology: (config.topology ? config.topology : config.renderer.gl.TRIANGLES), + vertShader: (config.vertShader ? config.vertShader : ShaderSourceVS), + fragShader: (config.fragShader ? config.fragShader : ShaderSourceFS), + vertexCapacity: (config.vertexCapacity ? config.vertexCapacity : 3), + + vertexSize: (config.vertexSize ? config.vertexSize : + Float32Array.BYTES_PER_ELEMENT * 2), + + vertices: new Float32Array([ + -1, +1, -1, -7, +7, +1 + ]).buffer, + + attributes: [ + { + name: 'inPosition', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: 0 + } + ] + }); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#vertexViewF32 + * @type {Float32Array} + * @since 3.0.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * Size of the batch. + * + * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#maxQuads + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.maxQuads = 1; + + /** + * Dirty flag to check if resolution properties need to be updated on the + * masking shader. + * + * @name Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resolutionDirty + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.resolutionDirty = true; + }, + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + WebGLPipeline.prototype.onBind.call(this); + + var renderer = this.renderer; + var program = this.program; + + if (this.resolutionDirty) + { + renderer.setFloat2(program, 'uResolution', this.width, this.height); + renderer.setInt1(program, 'uMainSampler', 0); + renderer.setInt1(program, 'uMaskSampler', 1); + this.resolutionDirty = false; + } + + return this; + }, + + /** + * Resizes this pipeline and updates the projection. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width. + * @param {number} height - The new height. + * @param {number} resolution - The resolution. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + WebGLPipeline.prototype.resize.call(this, width, height, resolution); + + this.resolutionDirty = true; + + return this; + }, + + /** + * Binds necessary resources and renders the mask to a separated framebuffer. + * The framebuffer for the masked object is also bound for further use. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#beginMask + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} mask - GameObject used as mask. + * @param {Phaser.GameObjects.GameObject} maskedObject - GameObject masked by the mask GameObject. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera rendering the current mask. + */ + beginMask: function (mask, maskedObject, camera) + { + var renderer = this.renderer; + var gl = this.gl; + + // The renderable Game Object that is being used for the bitmap mask + var bitmapMask = mask.bitmapMask; + + if (bitmapMask && gl) + { + renderer.flush(); + + mask.prevFramebuffer = renderer.currentFramebuffer; + + renderer.setFramebuffer(mask.mainFramebuffer); + + gl.disable(gl.STENCIL_TEST); + + gl.clearColor(0, 0, 0, 0); + + gl.clear(gl.COLOR_BUFFER_BIT); + + if (renderer.currentCameraMask.mask !== mask) + { + renderer.currentMask.mask = mask; + renderer.currentMask.camera = camera; + } + } + }, + + /** + * The masked game objects framebuffer is unbound and its texture + * is bound together with the mask texture and the mask shader and + * a draw call with a single quad is processed. Here is where the + * masking effect is applied. + * + * @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#endMask + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} mask - GameObject used as a mask. + */ + endMask: function (mask, camera) + { + var gl = this.gl; + var renderer = this.renderer; + + // The renderable Game Object that is being used for the bitmap mask + var bitmapMask = mask.bitmapMask; + + if (bitmapMask && gl) + { + renderer.flush(); + + // First we draw the mask to the mask fb + renderer.setFramebuffer(mask.maskFramebuffer); + + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + + renderer.setBlendMode(0, true); + + bitmapMask.renderWebGL(renderer, bitmapMask, 0, camera); + + renderer.flush(); + + renderer.setFramebuffer(mask.prevFramebuffer); + + // Is there a stencil further up the stack? + var prev = renderer.getCurrentStencilMask(); + + if (prev) + { + gl.enable(gl.STENCIL_TEST); + + prev.mask.applyStencil(renderer, prev.camera, true); + } + else + { + renderer.currentMask.mask = null; + } + + // Bind bitmap mask pipeline and draw + renderer.setPipeline(this); + + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, mask.maskTexture); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, mask.mainTexture); + + gl.uniform1i(gl.getUniformLocation(this.program, 'uInvertMaskAlpha'), mask.invertAlpha); + + // Finally, draw a triangle filling the whole screen + gl.drawArrays(this.topology, 0, 3); + } + } + +}); + +module.exports = BitmapMaskPipeline; diff --git a/src/renderer/webgl/pipelines/ForwardDiffuseLightPipeline.js b/src/renderer/webgl/pipelines/ForwardDiffuseLightPipeline.js index f62a667b1..927906e59 100644 --- a/src/renderer/webgl/pipelines/ForwardDiffuseLightPipeline.js +++ b/src/renderer/webgl/pipelines/ForwardDiffuseLightPipeline.js @@ -1,515 +1,515 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var ShaderSourceFS = require('../shaders/ForwardDiffuse-frag.js'); -var TextureTintPipeline = require('./TextureTintPipeline'); - -var LIGHT_COUNT = 10; - -/** - * @classdesc - * ForwardDiffuseLightPipeline implements a forward rendering approach for 2D lights. - * This pipeline extends TextureTintPipeline so it implements all it's rendering functions - * and batching system. - * - * @class ForwardDiffuseLightPipeline - * @extends Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline - * @memberof Phaser.Renderer.WebGL.Pipelines - * @constructor - * @since 3.0.0 - * - * @param {object} config - The configuration of the pipeline, same as the {@link Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline}. The fragment shader will be replaced with the lighting shader. - */ -var ForwardDiffuseLightPipeline = new Class({ - - Extends: TextureTintPipeline, - - initialize: - - function ForwardDiffuseLightPipeline (config) - { - LIGHT_COUNT = config.maxLights; - - config.fragShader = ShaderSourceFS.replace('%LIGHT_COUNT%', LIGHT_COUNT.toString()); - - TextureTintPipeline.call(this, config); - - /** - * Default normal map texture to use. - * - * @name Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#defaultNormalMap - * @type {Phaser.Texture.Frame} - * @private - * @since 3.11.0 - */ - this.defaultNormalMap; - - /** - * Inverse rotation matrix for normal map rotations. - * - * @name Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#inverseRotationMatrix - * @type {Float32Array} - * @private - * @since 3.16.0 - */ - this.inverseRotationMatrix = new Float32Array([ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ]); - }, - - /** - * Called when the Game has fully booted and the Renderer has finished setting up. - * - * By this stage all Game level systems are now in place and you can perform any final - * tasks that the pipeline may need that relied on game systems such as the Texture Manager. - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#boot - * @override - * @since 3.11.0 - */ - boot: function () - { - this.defaultNormalMap = this.game.textures.getFrame('__DEFAULT'); - }, - - /** - * This function binds its base class resources and this lights 2D resources. - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#onBind - * @override - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} [gameObject] - The Game Object that invoked this pipeline, if any. - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function (gameObject) - { - TextureTintPipeline.prototype.onBind.call(this); - - var renderer = this.renderer; - var program = this.program; - - this.mvpUpdate(); - - renderer.setInt1(program, 'uNormSampler', 1); - renderer.setFloat2(program, 'uResolution', this.width, this.height); - - if (gameObject) - { - this.setNormalMap(gameObject); - } - - return this; - }, - - /** - * This function sets all the needed resources for each camera pass. - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#onRender - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene being rendered. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. - * - * @return {this} This WebGLPipeline instance. - */ - onRender: function (scene, camera) - { - this.active = false; - - var lightManager = scene.sys.lights; - - if (!lightManager || lightManager.lights.length <= 0 || !lightManager.active) - { - // Passthru - return this; - } - - var lights = lightManager.cull(camera); - var lightCount = Math.min(lights.length, LIGHT_COUNT); - - if (lightCount === 0) - { - return this; - } - - this.active = true; - - var renderer = this.renderer; - var program = this.program; - var cameraMatrix = camera.matrix; - var point = {x: 0, y: 0}; - var height = renderer.height; - var index; - - for (index = 0; index < LIGHT_COUNT; ++index) - { - // Reset lights - renderer.setFloat1(program, 'uLights[' + index + '].radius', 0); - } - - renderer.setFloat4(program, 'uCamera', camera.x, camera.y, camera.rotation, camera.zoom); - renderer.setFloat3(program, 'uAmbientLightColor', lightManager.ambientColor.r, lightManager.ambientColor.g, lightManager.ambientColor.b); - - for (index = 0; index < lightCount; ++index) - { - var light = lights[index]; - var lightName = 'uLights[' + index + '].'; - - cameraMatrix.transformPoint(light.x, light.y, point); - - renderer.setFloat2(program, lightName + 'position', point.x - (camera.scrollX * light.scrollFactorX * camera.zoom), height - (point.y - (camera.scrollY * light.scrollFactorY) * camera.zoom)); - renderer.setFloat3(program, lightName + 'color', light.r, light.g, light.b); - renderer.setFloat1(program, lightName + 'intensity', light.intensity); - renderer.setFloat1(program, lightName + 'radius', light.radius); - } - - this.currentNormalMapRotation = null; - - return this; - }, - - /** - * Generic function for batching a textured quad - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#batchTexture - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - Source GameObject - * @param {WebGLTexture} texture - Raw WebGLTexture associated with the quad - * @param {integer} textureWidth - Real texture width - * @param {integer} textureHeight - Real texture height - * @param {number} srcX - X coordinate of the quad - * @param {number} srcY - Y coordinate of the quad - * @param {number} srcWidth - Width of the quad - * @param {number} srcHeight - Height of the quad - * @param {number} scaleX - X component of scale - * @param {number} scaleY - Y component of scale - * @param {number} rotation - Rotation of the quad - * @param {boolean} flipX - Indicates if the quad is horizontally flipped - * @param {boolean} flipY - Indicates if the quad is vertically flipped - * @param {number} scrollFactorX - By which factor is the quad affected by the camera horizontal scroll - * @param {number} scrollFactorY - By which factor is the quad effected by the camera vertical scroll - * @param {number} displayOriginX - Horizontal origin in pixels - * @param {number} displayOriginY - Vertical origin in pixels - * @param {number} frameX - X coordinate of the texture frame - * @param {number} frameY - Y coordinate of the texture frame - * @param {number} frameWidth - Width of the texture frame - * @param {number} frameHeight - Height of the texture frame - * @param {integer} tintTL - Tint for top left - * @param {integer} tintTR - Tint for top right - * @param {integer} tintBL - Tint for bottom left - * @param {integer} tintBR - Tint for bottom right - * @param {number} tintEffect - The tint effect (0 for additive, 1 for replacement) - * @param {number} uOffset - Horizontal offset on texture coordinate - * @param {number} vOffset - Vertical offset on texture coordinate - * @param {Phaser.Cameras.Scene2D.Camera} camera - Current used camera - * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - Parent container - */ - batchTexture: function ( - gameObject, - texture, - textureWidth, textureHeight, - srcX, srcY, - srcWidth, srcHeight, - scaleX, scaleY, - rotation, - flipX, flipY, - scrollFactorX, scrollFactorY, - displayOriginX, displayOriginY, - frameX, frameY, frameWidth, frameHeight, - tintTL, tintTR, tintBL, tintBR, tintEffect, - uOffset, vOffset, - camera, - parentTransformMatrix) - { - if (!this.active) - { - return; - } - - this.renderer.setPipeline(this); - - var normalTexture; - - if (gameObject.displayTexture) - { - normalTexture = gameObject.displayTexture.dataSource[gameObject.displayFrame.sourceIndex]; - } - else if (gameObject.texture) - { - normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex]; - } - else if (gameObject.tileset) - { - if (Array.isArray(gameObject.tileset)) - { - normalTexture = gameObject.tileset[0].image.dataSource[0]; - } - else - { - normalTexture = gameObject.tileset.image.dataSource[0]; - } - } - - if (!normalTexture) - { - console.warn('Normal map missing or invalid'); - return; - } - - this.setTexture2D(normalTexture.glTexture, 1); - this.setNormalMapRotation(rotation); - - var camMatrix = this._tempMatrix1; - var spriteMatrix = this._tempMatrix2; - var calcMatrix = this._tempMatrix3; - - var u0 = (frameX / textureWidth) + uOffset; - var v0 = (frameY / textureHeight) + vOffset; - var u1 = (frameX + frameWidth) / textureWidth + uOffset; - var v1 = (frameY + frameHeight) / textureHeight + vOffset; - - var width = srcWidth; - var height = srcHeight; - - // var x = -displayOriginX + frameX; - // var y = -displayOriginY + frameY; - - var x = -displayOriginX; - var y = -displayOriginY; - - if (gameObject.isCropped) - { - var crop = gameObject._crop; - - width = crop.width; - height = crop.height; - - srcWidth = crop.width; - srcHeight = crop.height; - - frameX = crop.x; - frameY = crop.y; - - var ox = frameX; - var oy = frameY; - - if (flipX) - { - ox = (frameWidth - crop.x - crop.width); - } - - if (flipY && !texture.isRenderTexture) - { - oy = (frameHeight - crop.y - crop.height); - } - - u0 = (ox / textureWidth) + uOffset; - v0 = (oy / textureHeight) + vOffset; - u1 = (ox + crop.width) / textureWidth + uOffset; - v1 = (oy + crop.height) / textureHeight + vOffset; - - x = -displayOriginX + frameX; - y = -displayOriginY + frameY; - } - - // Invert the flipY if this is a RenderTexture - flipY = flipY ^ (texture.isRenderTexture ? 1 : 0); - - if (flipX) - { - width *= -1; - x += srcWidth; - } - - if (flipY) - { - height *= -1; - y += srcHeight; - } - - // Do we need this? (doubt it) - // if (camera.roundPixels) - // { - // x |= 0; - // y |= 0; - // } - - var xw = x + width; - var yh = y + height; - - spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentTransformMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = srcX; - spriteMatrix.f = srcY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * scrollFactorX; - spriteMatrix.f -= camera.scrollY * scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(x, yh); - var ty1 = calcMatrix.getY(x, yh); - - var tx2 = calcMatrix.getX(xw, yh); - var ty2 = calcMatrix.getY(xw, yh); - - var tx3 = calcMatrix.getX(xw, y); - var ty3 = calcMatrix.getY(xw, y); - - if (camera.roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - this.setTexture2D(texture, 0); - - this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); - }, - - /** - * Sets the Game Objects normal map as the active texture. - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#setNormalMap - * @since 3.11.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to update. - */ - setNormalMap: function (gameObject) - { - if (!this.active || !gameObject) - { - return; - } - - var normalTexture; - - if (gameObject.texture) - { - normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex]; - } - - if (!normalTexture) - { - normalTexture = this.defaultNormalMap; - } - - this.setTexture2D(normalTexture.glTexture, 1); - - this.renderer.setPipeline(gameObject.defaultPipeline); - }, - - /** - * Rotates the normal map vectors inversely by the given angle. - * Only works in 2D space. - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#setNormalMapRotation - * @since 3.16.0 - * - * @param {number} rotation - The angle of rotation in radians. - */ - setNormalMapRotation: function (rotation) - { - if (rotation !== this.currentNormalMapRotation || this.batches.length === 0) - { - if (this.batches.length > 0) - { - this.flush(); - } - - var inverseRotationMatrix = this.inverseRotationMatrix; - - if (rotation) - { - var rot = -rotation; - var c = Math.cos(rot); - var s = Math.sin(rot); - - inverseRotationMatrix[1] = s; - inverseRotationMatrix[3] = -s; - inverseRotationMatrix[0] = inverseRotationMatrix[4] = c; - } - else - { - inverseRotationMatrix[0] = inverseRotationMatrix[4] = 1; - inverseRotationMatrix[1] = inverseRotationMatrix[3] = 0; - } - - this.renderer.setMatrix3(this.program, 'uInverseRotationMatrix', false, inverseRotationMatrix); - - this.currentNormalMapRotation = rotation; - } - }, - - /** - * Takes a Sprite Game Object, or any object that extends it, which has a normal texture and adds it to the batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#batchSprite - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Sprite} sprite - The texture-based Game Object to add to the batch. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - The transform matrix of the parent container, if set. - */ - batchSprite: function (sprite, camera, parentTransformMatrix) - { - if (!this.active) - { - return; - } - - var normalTexture = sprite.texture.dataSource[sprite.frame.sourceIndex]; - - if (normalTexture) - { - this.renderer.setPipeline(this); - - this.setTexture2D(normalTexture.glTexture, 1); - this.setNormalMapRotation(sprite.rotation); - - TextureTintPipeline.prototype.batchSprite.call(this, sprite, camera, parentTransformMatrix); - } - } - -}); - -ForwardDiffuseLightPipeline.LIGHT_COUNT = LIGHT_COUNT; - -module.exports = ForwardDiffuseLightPipeline; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var ShaderSourceFS = require('../shaders/ForwardDiffuse-frag.js'); +var TextureTintPipeline = require('./TextureTintPipeline'); + +var LIGHT_COUNT = 10; + +/** + * @classdesc + * ForwardDiffuseLightPipeline implements a forward rendering approach for 2D lights. + * This pipeline extends TextureTintPipeline so it implements all it's rendering functions + * and batching system. + * + * @class ForwardDiffuseLightPipeline + * @extends Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration of the pipeline, same as the {@link Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline}. The fragment shader will be replaced with the lighting shader. + */ +var ForwardDiffuseLightPipeline = new Class({ + + Extends: TextureTintPipeline, + + initialize: + + function ForwardDiffuseLightPipeline (config) + { + LIGHT_COUNT = config.maxLights; + + config.fragShader = ShaderSourceFS.replace('%LIGHT_COUNT%', LIGHT_COUNT.toString()); + + TextureTintPipeline.call(this, config); + + /** + * Default normal map texture to use. + * + * @name Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#defaultNormalMap + * @type {Phaser.Texture.Frame} + * @private + * @since 3.11.0 + */ + this.defaultNormalMap; + + /** + * Inverse rotation matrix for normal map rotations. + * + * @name Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#inverseRotationMatrix + * @type {Float32Array} + * @private + * @since 3.16.0 + */ + this.inverseRotationMatrix = new Float32Array([ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]); + }, + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#boot + * @override + * @since 3.11.0 + */ + boot: function () + { + this.defaultNormalMap = this.game.textures.getFrame('__DEFAULT'); + }, + + /** + * This function binds its base class resources and this lights 2D resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#onBind + * @override + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} [gameObject] - The Game Object that invoked this pipeline, if any. + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function (gameObject) + { + TextureTintPipeline.prototype.onBind.call(this); + + var renderer = this.renderer; + var program = this.program; + + this.mvpUpdate(); + + renderer.setInt1(program, 'uNormSampler', 1); + renderer.setFloat2(program, 'uResolution', this.width, this.height); + + if (gameObject) + { + this.setNormalMap(gameObject); + } + + return this; + }, + + /** + * This function sets all the needed resources for each camera pass. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#onRender + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene being rendered. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Scene Camera being rendered with. + * + * @return {this} This WebGLPipeline instance. + */ + onRender: function (scene, camera) + { + this.active = false; + + var lightManager = scene.sys.lights; + + if (!lightManager || lightManager.lights.length <= 0 || !lightManager.active) + { + // Passthru + return this; + } + + var lights = lightManager.cull(camera); + var lightCount = Math.min(lights.length, LIGHT_COUNT); + + if (lightCount === 0) + { + return this; + } + + this.active = true; + + var renderer = this.renderer; + var program = this.program; + var cameraMatrix = camera.matrix; + var point = {x: 0, y: 0}; + var height = renderer.height; + var index; + + for (index = 0; index < LIGHT_COUNT; ++index) + { + // Reset lights + renderer.setFloat1(program, 'uLights[' + index + '].radius', 0); + } + + renderer.setFloat4(program, 'uCamera', camera.x, camera.y, camera.rotation, camera.zoom); + renderer.setFloat3(program, 'uAmbientLightColor', lightManager.ambientColor.r, lightManager.ambientColor.g, lightManager.ambientColor.b); + + for (index = 0; index < lightCount; ++index) + { + var light = lights[index]; + var lightName = 'uLights[' + index + '].'; + + cameraMatrix.transformPoint(light.x, light.y, point); + + renderer.setFloat2(program, lightName + 'position', point.x - (camera.scrollX * light.scrollFactorX * camera.zoom), height - (point.y - (camera.scrollY * light.scrollFactorY) * camera.zoom)); + renderer.setFloat3(program, lightName + 'color', light.r, light.g, light.b); + renderer.setFloat1(program, lightName + 'intensity', light.intensity); + renderer.setFloat1(program, lightName + 'radius', light.radius); + } + + this.currentNormalMapRotation = null; + + return this; + }, + + /** + * Generic function for batching a textured quad + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#batchTexture + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Source GameObject + * @param {WebGLTexture} texture - Raw WebGLTexture associated with the quad + * @param {integer} textureWidth - Real texture width + * @param {integer} textureHeight - Real texture height + * @param {number} srcX - X coordinate of the quad + * @param {number} srcY - Y coordinate of the quad + * @param {number} srcWidth - Width of the quad + * @param {number} srcHeight - Height of the quad + * @param {number} scaleX - X component of scale + * @param {number} scaleY - Y component of scale + * @param {number} rotation - Rotation of the quad + * @param {boolean} flipX - Indicates if the quad is horizontally flipped + * @param {boolean} flipY - Indicates if the quad is vertically flipped + * @param {number} scrollFactorX - By which factor is the quad affected by the camera horizontal scroll + * @param {number} scrollFactorY - By which factor is the quad effected by the camera vertical scroll + * @param {number} displayOriginX - Horizontal origin in pixels + * @param {number} displayOriginY - Vertical origin in pixels + * @param {number} frameX - X coordinate of the texture frame + * @param {number} frameY - Y coordinate of the texture frame + * @param {number} frameWidth - Width of the texture frame + * @param {number} frameHeight - Height of the texture frame + * @param {integer} tintTL - Tint for top left + * @param {integer} tintTR - Tint for top right + * @param {integer} tintBL - Tint for bottom left + * @param {integer} tintBR - Tint for bottom right + * @param {number} tintEffect - The tint effect (0 for additive, 1 for replacement) + * @param {number} uOffset - Horizontal offset on texture coordinate + * @param {number} vOffset - Vertical offset on texture coordinate + * @param {Phaser.Cameras.Scene2D.Camera} camera - Current used camera + * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - Parent container + */ + batchTexture: function ( + gameObject, + texture, + textureWidth, textureHeight, + srcX, srcY, + srcWidth, srcHeight, + scaleX, scaleY, + rotation, + flipX, flipY, + scrollFactorX, scrollFactorY, + displayOriginX, displayOriginY, + frameX, frameY, frameWidth, frameHeight, + tintTL, tintTR, tintBL, tintBR, tintEffect, + uOffset, vOffset, + camera, + parentTransformMatrix) + { + if (!this.active) + { + return; + } + + this.renderer.setPipeline(this); + + var normalTexture; + + if (gameObject.displayTexture) + { + normalTexture = gameObject.displayTexture.dataSource[gameObject.displayFrame.sourceIndex]; + } + else if (gameObject.texture) + { + normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex]; + } + else if (gameObject.tileset) + { + if (Array.isArray(gameObject.tileset)) + { + normalTexture = gameObject.tileset[0].image.dataSource[0]; + } + else + { + normalTexture = gameObject.tileset.image.dataSource[0]; + } + } + + if (!normalTexture) + { + console.warn('Normal map missing or invalid'); + return; + } + + this.setTexture2D(normalTexture.glTexture, 1); + this.setNormalMapRotation(rotation); + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var u0 = (frameX / textureWidth) + uOffset; + var v0 = (frameY / textureHeight) + vOffset; + var u1 = (frameX + frameWidth) / textureWidth + uOffset; + var v1 = (frameY + frameHeight) / textureHeight + vOffset; + + var width = srcWidth; + var height = srcHeight; + + // var x = -displayOriginX + frameX; + // var y = -displayOriginY + frameY; + + var x = -displayOriginX; + var y = -displayOriginY; + + if (gameObject.isCropped) + { + var crop = gameObject._crop; + + width = crop.width; + height = crop.height; + + srcWidth = crop.width; + srcHeight = crop.height; + + frameX = crop.x; + frameY = crop.y; + + var ox = frameX; + var oy = frameY; + + if (flipX) + { + ox = (frameWidth - crop.x - crop.width); + } + + if (flipY && !texture.isRenderTexture) + { + oy = (frameHeight - crop.y - crop.height); + } + + u0 = (ox / textureWidth) + uOffset; + v0 = (oy / textureHeight) + vOffset; + u1 = (ox + crop.width) / textureWidth + uOffset; + v1 = (oy + crop.height) / textureHeight + vOffset; + + x = -displayOriginX + frameX; + y = -displayOriginY + frameY; + } + + // Invert the flipY if this is a RenderTexture + flipY = flipY ^ (texture.isRenderTexture ? 1 : 0); + + if (flipX) + { + width *= -1; + x += srcWidth; + } + + if (flipY) + { + height *= -1; + y += srcHeight; + } + + // Do we need this? (doubt it) + // if (camera.roundPixels) + // { + // x |= 0; + // y |= 0; + // } + + var xw = x + width; + var yh = y + height; + + spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = srcX; + spriteMatrix.f = srcY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * scrollFactorX; + spriteMatrix.f -= camera.scrollY * scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + this.setTexture2D(texture, 0); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + }, + + /** + * Sets the Game Objects normal map as the active texture. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#setNormalMap + * @since 3.11.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to update. + */ + setNormalMap: function (gameObject) + { + if (!this.active || !gameObject) + { + return; + } + + var normalTexture; + + if (gameObject.texture) + { + normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex]; + } + + if (!normalTexture) + { + normalTexture = this.defaultNormalMap; + } + + this.setTexture2D(normalTexture.glTexture, 1); + + this.renderer.setPipeline(gameObject.defaultPipeline); + }, + + /** + * Rotates the normal map vectors inversely by the given angle. + * Only works in 2D space. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#setNormalMapRotation + * @since 3.16.0 + * + * @param {number} rotation - The angle of rotation in radians. + */ + setNormalMapRotation: function (rotation) + { + if (rotation !== this.currentNormalMapRotation || this.batches.length === 0) + { + if (this.batches.length > 0) + { + this.flush(); + } + + var inverseRotationMatrix = this.inverseRotationMatrix; + + if (rotation) + { + var rot = -rotation; + var c = Math.cos(rot); + var s = Math.sin(rot); + + inverseRotationMatrix[1] = s; + inverseRotationMatrix[3] = -s; + inverseRotationMatrix[0] = inverseRotationMatrix[4] = c; + } + else + { + inverseRotationMatrix[0] = inverseRotationMatrix[4] = 1; + inverseRotationMatrix[1] = inverseRotationMatrix[3] = 0; + } + + this.renderer.setMatrix3(this.program, 'uInverseRotationMatrix', false, inverseRotationMatrix); + + this.currentNormalMapRotation = rotation; + } + }, + + /** + * Takes a Sprite Game Object, or any object that extends it, which has a normal texture and adds it to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline#batchSprite + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Sprite} sprite - The texture-based Game Object to add to the batch. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - The transform matrix of the parent container, if set. + */ + batchSprite: function (sprite, camera, parentTransformMatrix) + { + if (!this.active) + { + return; + } + + var normalTexture = sprite.texture.dataSource[sprite.frame.sourceIndex]; + + if (normalTexture) + { + this.renderer.setPipeline(this); + + this.setTexture2D(normalTexture.glTexture, 1); + this.setNormalMapRotation(sprite.rotation); + + TextureTintPipeline.prototype.batchSprite.call(this, sprite, camera, parentTransformMatrix); + } + } + +}); + +ForwardDiffuseLightPipeline.LIGHT_COUNT = LIGHT_COUNT; + +module.exports = ForwardDiffuseLightPipeline; diff --git a/src/renderer/webgl/pipelines/TextureTintPipeline.js b/src/renderer/webgl/pipelines/TextureTintPipeline.js index 5615062f6..8ccd798ab 100644 --- a/src/renderer/webgl/pipelines/TextureTintPipeline.js +++ b/src/renderer/webgl/pipelines/TextureTintPipeline.js @@ -1,1502 +1,1502 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var Earcut = require('../../../geom/polygon/Earcut'); -var GetFastValue = require('../../../utils/object/GetFastValue'); -var ModelViewProjection = require('./components/ModelViewProjection'); -var ShaderSourceFS = require('../shaders/TextureTint-frag.js'); -var ShaderSourceVS = require('../shaders/TextureTint-vert.js'); -var TransformMatrix = require('../../../gameobjects/components/TransformMatrix'); -var Utils = require('../Utils'); -var WebGLPipeline = require('../WebGLPipeline'); - -/** - * @classdesc - * TextureTintPipeline implements the rendering infrastructure - * for displaying textured objects - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - * @class TextureTintPipeline - * @extends Phaser.Renderer.WebGL.WebGLPipeline - * @memberof Phaser.Renderer.WebGL.Pipelines - * @constructor - * @since 3.0.0 - * - * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. - */ -var TextureTintPipeline = new Class({ - - Extends: WebGLPipeline, - - Mixins: [ - ModelViewProjection - ], - - initialize: - - function TextureTintPipeline (config) - { - var rendererConfig = config.renderer.config; - - // Vertex Size = attribute size added together (2 + 2 + 1 + 4) - - WebGLPipeline.call(this, { - game: config.game, - renderer: config.renderer, - gl: config.renderer.gl, - topology: GetFastValue(config, 'topology', config.renderer.gl.TRIANGLES), - vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), - fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), - vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), - vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), - attributes: [ - { - name: 'inPosition', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: 0 - }, - { - name: 'inTexCoord', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 2 - }, - { - name: 'inTintEffect', - size: 1, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 4 - }, - { - name: 'inTint', - size: 4, - type: config.renderer.gl.UNSIGNED_BYTE, - normalized: true, - offset: Float32Array.BYTES_PER_ELEMENT * 5 - } - ] - }); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#vertexViewF32 - * @type {Float32Array} - * @since 3.0.0 - */ - this.vertexViewF32 = new Float32Array(this.vertexData); - - /** - * Uint32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#vertexViewU32 - * @type {Uint32Array} - * @since 3.0.0 - */ - this.vertexViewU32 = new Uint32Array(this.vertexData); - - /** - * Size of the batch. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#maxQuads - * @type {integer} - * @since 3.0.0 - */ - this.maxQuads = rendererConfig.batchSize; - - /** - * Collection of batch information - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batches - * @type {array} - * @since 3.1.0 - */ - this.batches = []; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.11.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.11.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.11.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix4 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.11.0 - */ - this._tempMatrix4 = new TransformMatrix(); - - /** - * Used internally to draw stroked triangles. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#tempTriangle - * @type {array} - * @private - * @since 3.12.0 - */ - this.tempTriangle = [ - { x: 0, y: 0, width: 0 }, - { x: 0, y: 0, width: 0 }, - { x: 0, y: 0, width: 0 }, - { x: 0, y: 0, width: 0 } - ]; - - /** - * The tint effect to be applied by the shader in the next geometry draw: - * - * 0 = texture multiplied by color - * 1 = solid color + texture alpha - * 2 = solid color, no texture - * 3 = solid texture, no color - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#tintEffect - * @type {number} - * @private - * @since 3.12.0 - */ - this.tintEffect = 2; - - /** - * Cached stroke tint. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#strokeTint - * @type {object} - * @private - * @since 3.12.0 - */ - this.strokeTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; - - /** - * Cached fill tint. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#fillTint - * @type {object} - * @private - * @since 3.12.0 - */ - this.fillTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; - - /** - * Internal texture frame reference. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#currentFrame - * @type {Phaser.Textures.Frame} - * @private - * @since 3.12.0 - */ - this.currentFrame = { u0: 0, v0: 0, u1: 1, v1: 1 }; - - /** - * Internal path quad cache. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#firstQuad - * @type {array} - * @private - * @since 3.12.0 - */ - this.firstQuad = [ 0, 0, 0, 0, 0 ]; - - /** - * Internal path quad cache. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#prevQuad - * @type {array} - * @private - * @since 3.12.0 - */ - this.prevQuad = [ 0, 0, 0, 0, 0 ]; - - /** - * Used internally for triangulating a polygon. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#polygonCache - * @type {array} - * @private - * @since 3.12.0 - */ - this.polygonCache = []; - - this.mvpInit(); - }, - - /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#onBind - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - WebGLPipeline.prototype.onBind.call(this); - - this.mvpUpdate(); - - return this; - }, - - /** - * Resizes this pipeline and updates the projection. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#resize - * @since 3.0.0 - * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - WebGLPipeline.prototype.resize.call(this, width, height, resolution); - - this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); - - return this; - }, - - /** - * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#setTexture2D - * @since 3.1.0 - * - * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. - * - * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} This pipeline instance. - */ - setTexture2D: function (texture, unit) - { - if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } - if (unit === undefined) { unit = 0; } - - if (this.requireTextureBatch(texture, unit)) - { - this.pushBatch(texture, unit); - } - - return this; - }, - - /** - * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#requireTextureBatch - * @since 3.16.0 - * - * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} unit - Texture unit to which the texture needs to be bound. - * - * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. - */ - requireTextureBatch: function (texture, unit) - { - var batches = this.batches; - var batchLength = batches.length; - - if (batchLength > 0) - { - // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property - var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; - - return !(currentTexture === texture); - } - - return true; - }, - - /** - * Creates a new batch object and pushes it to a batch array. - * The batch object contains information relevant to the current - * vertex batch like the offset in the vertex buffer, vertex count and - * the textures used by that batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#pushBatch - * @since 3.1.0 - * - * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. - * @param {integer} unit - Texture unit to which the texture needs to be bound. - */ - pushBatch: function (texture, unit) - { - if (unit === 0) - { - this.batches.push({ - first: this.vertexCount, - texture: texture, - textures: [] - }); - } - else - { - var textures = []; - - textures[unit - 1] = texture; - - this.batches.push({ - first: this.vertexCount, - texture: null, - textures: textures - }); - } - }, - - /** - * Uploads the vertex data and emits a draw call for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#flush - * @since 3.0.0 - * - * @return {this} This WebGLPipeline instance. - */ - flush: function () - { - if (this.flushLocked) - { - return this; - } - - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - var renderer = this.renderer; - - var batches = this.batches; - var batchCount = batches.length; - var batchVertexCount = 0; - var batch = null; - var batchNext; - var textureIndex; - var nTexture; - - if (batchCount === 0 || vertexCount === 0) - { - this.flushLocked = false; - - return this; - } - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); - - // Process the TEXTURE BATCHES - - for (var index = 0; index < batchCount - 1; index++) - { - batch = batches[index]; - batchNext = batches[index + 1]; - - // Multi-texture check (for non-zero texture units) - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; - - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } - - gl.activeTexture(gl.TEXTURE0); - } - - batchVertexCount = batchNext.first - batch.first; - - // Bail out if texture property is null (i.e. if a texture unit > 0) - if (batch.texture === null || batchVertexCount <= 0) - { - continue; - } - - renderer.setTexture2D(batch.texture, 0, false); - - gl.drawArrays(topology, batch.first, batchVertexCount); - } - - // Left over data - batch = batches[batchCount - 1]; - - // Multi-texture check (for non-zero texture units) - - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; - - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } - - gl.activeTexture(gl.TEXTURE0); - } - - batchVertexCount = vertexCount - batch.first; - - if (batch.texture && batchVertexCount > 0) - { - renderer.setTexture2D(batch.texture, 0, false); - - gl.drawArrays(topology, batch.first, batchVertexCount); - } - - this.vertexCount = 0; - - batches.length = 0; - - this.flushLocked = false; - - return this; - }, - - /** - * Takes a Sprite Game Object, or any object that extends it, and adds it to the batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchSprite - * @since 3.0.0 - * - * @param {(Phaser.GameObjects.Image|Phaser.GameObjects.Sprite)} sprite - The texture based Game Object to add to the batch. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - The transform matrix of the parent container, if set. - */ - batchSprite: function (sprite, camera, parentTransformMatrix) - { - // Will cause a flush if there are batchSize entries already - this.renderer.setPipeline(this); - - var camMatrix = this._tempMatrix1; - var spriteMatrix = this._tempMatrix2; - var calcMatrix = this._tempMatrix3; - - var frame = sprite.frame; - var texture = frame.glTexture; - - var u0 = frame.u0; - var v0 = frame.v0; - var u1 = frame.u1; - var v1 = frame.v1; - var frameX = frame.x; - var frameY = frame.y; - var frameWidth = frame.cutWidth; - var frameHeight = frame.cutHeight; - var customPivot = frame.customPivot; - - var displayOriginX = sprite.displayOriginX; - var displayOriginY = sprite.displayOriginY; - - var x = -displayOriginX + frameX; - var y = -displayOriginY + frameY; - - if (sprite.isCropped) - { - var crop = sprite._crop; - - if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) - { - frame.updateCropUVs(crop, sprite.flipX, sprite.flipY); - } - - u0 = crop.u0; - v0 = crop.v0; - u1 = crop.u1; - v1 = crop.v1; - - frameWidth = crop.width; - frameHeight = crop.height; - - frameX = crop.x; - frameY = crop.y; - - x = -displayOriginX + frameX; - y = -displayOriginY + frameY; - } - - var flipX = 1; - var flipY = 1; - - if (sprite.flipX) - { - if (!customPivot) - { - x += (-frame.realWidth + (displayOriginX * 2)); - } - - flipX = -1; - } - - // Auto-invert the flipY if this is coming from a GLTexture - if (sprite.flipY || (frame.source.isGLTexture && !texture.flipY)) - { - if (!customPivot) - { - y += (-frame.realHeight + (displayOriginY * 2)); - } - - flipY = -1; - } - - spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX * flipX, sprite.scaleY * flipY); - - camMatrix.copyFrom(camera.matrix); - - if (parentTransformMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = sprite.x; - spriteMatrix.f = sprite.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; - spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var xw = x + frameWidth; - var yh = y + frameHeight; - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(x, yh); - var ty1 = calcMatrix.getY(x, yh); - - var tx2 = calcMatrix.getX(xw, yh); - var ty2 = calcMatrix.getY(xw, yh); - - var tx3 = calcMatrix.getX(xw, y); - var ty3 = calcMatrix.getY(xw, y); - - var tintTL = Utils.getTintAppendFloatAlpha(sprite._tintTL, camera.alpha * sprite._alphaTL); - var tintTR = Utils.getTintAppendFloatAlpha(sprite._tintTR, camera.alpha * sprite._alphaTR); - var tintBL = Utils.getTintAppendFloatAlpha(sprite._tintBL, camera.alpha * sprite._alphaBL); - var tintBR = Utils.getTintAppendFloatAlpha(sprite._tintBR, camera.alpha * sprite._alphaBR); - - if (camera.roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - this.setTexture2D(texture, 0); - - var tintEffect = (sprite._isTinted && sprite.tintFill); - - this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); - }, - - /** - * Adds the vertices data into the batch and flushes if full. - * - * Assumes 6 vertices in the following arrangement: - * - * ``` - * 0----3 - * |\ B| - * | \ | - * | \ | - * | A \| - * | \ - * 1----2 - * ``` - * - * Where tx0/ty0 = 0, tx1/ty1 = 1, tx2/ty2 = 2 and tx3/ty3 = 3 - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchQuad - * @since 3.12.0 - * - * @param {number} x0 - The top-left x position. - * @param {number} y0 - The top-left y position. - * @param {number} x1 - The bottom-left x position. - * @param {number} y1 - The bottom-left y position. - * @param {number} x2 - The bottom-right x position. - * @param {number} y2 - The bottom-right y position. - * @param {number} x3 - The top-right x position. - * @param {number} y3 - The top-right y position. - * @param {number} u0 - UV u0 value. - * @param {number} v0 - UV v0 value. - * @param {number} u1 - UV u1 value. - * @param {number} v1 - UV v1 value. - * @param {number} tintTL - The top-left tint color value. - * @param {number} tintTR - The top-right tint color value. - * @param {number} tintBL - The bottom-left tint color value. - * @param {number} tintBR - The bottom-right tint color value. - * @param {(number|boolean)} tintEffect - The tint effect for the shader to use. - * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch if a flush occurs. - * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. - * - * @return {boolean} `true` if this method caused the batch to flush, otherwise `false`. - */ - batchQuad: function (x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, unit) - { - var hasFlushed = false; - - if (this.vertexCount + 6 > this.vertexCapacity) - { - this.flush(); - - hasFlushed = true; - - this.setTexture2D(texture, unit); - } - - var vertexViewF32 = this.vertexViewF32; - var vertexViewU32 = this.vertexViewU32; - - var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; - - vertexViewF32[++vertexOffset] = x0; - vertexViewF32[++vertexOffset] = y0; - vertexViewF32[++vertexOffset] = u0; - vertexViewF32[++vertexOffset] = v0; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintTL; - - vertexViewF32[++vertexOffset] = x1; - vertexViewF32[++vertexOffset] = y1; - vertexViewF32[++vertexOffset] = u0; - vertexViewF32[++vertexOffset] = v1; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintBL; - - vertexViewF32[++vertexOffset] = x2; - vertexViewF32[++vertexOffset] = y2; - vertexViewF32[++vertexOffset] = u1; - vertexViewF32[++vertexOffset] = v1; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintBR; - - vertexViewF32[++vertexOffset] = x0; - vertexViewF32[++vertexOffset] = y0; - vertexViewF32[++vertexOffset] = u0; - vertexViewF32[++vertexOffset] = v0; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintTL; - - vertexViewF32[++vertexOffset] = x2; - vertexViewF32[++vertexOffset] = y2; - vertexViewF32[++vertexOffset] = u1; - vertexViewF32[++vertexOffset] = v1; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintBR; - - vertexViewF32[++vertexOffset] = x3; - vertexViewF32[++vertexOffset] = y3; - vertexViewF32[++vertexOffset] = u1; - vertexViewF32[++vertexOffset] = v0; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintTR; - - this.vertexCount += 6; - - return hasFlushed; - }, - - /** - * Adds the vertices data into the batch and flushes if full. - * - * Assumes 3 vertices in the following arrangement: - * - * ``` - * 0 - * |\ - * | \ - * | \ - * | \ - * | \ - * 1-----2 - * ``` - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTri - * @since 3.12.0 - * - * @param {number} x1 - The bottom-left x position. - * @param {number} y1 - The bottom-left y position. - * @param {number} x2 - The bottom-right x position. - * @param {number} y2 - The bottom-right y position. - * @param {number} x3 - The top-right x position. - * @param {number} y3 - The top-right y position. - * @param {number} u0 - UV u0 value. - * @param {number} v0 - UV v0 value. - * @param {number} u1 - UV u1 value. - * @param {number} v1 - UV v1 value. - * @param {number} tintTL - The top-left tint color value. - * @param {number} tintTR - The top-right tint color value. - * @param {number} tintBL - The bottom-left tint color value. - * @param {(number|boolean)} tintEffect - The tint effect for the shader to use. - * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch if a flush occurs. - * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. - * - * @return {boolean} `true` if this method caused the batch to flush, otherwise `false`. - */ - batchTri: function (x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect, texture, unit) - { - var hasFlushed = false; - - if (this.vertexCount + 3 > this.vertexCapacity) - { - this.flush(); - - this.setTexture2D(texture, unit); - - hasFlushed = true; - } - - var vertexViewF32 = this.vertexViewF32; - var vertexViewU32 = this.vertexViewU32; - - var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; - - vertexViewF32[++vertexOffset] = x1; - vertexViewF32[++vertexOffset] = y1; - vertexViewF32[++vertexOffset] = u0; - vertexViewF32[++vertexOffset] = v0; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintTL; - - vertexViewF32[++vertexOffset] = x2; - vertexViewF32[++vertexOffset] = y2; - vertexViewF32[++vertexOffset] = u0; - vertexViewF32[++vertexOffset] = v1; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintTR; - - vertexViewF32[++vertexOffset] = x3; - vertexViewF32[++vertexOffset] = y3; - vertexViewF32[++vertexOffset] = u1; - vertexViewF32[++vertexOffset] = v1; - vertexViewF32[++vertexOffset] = tintEffect; - vertexViewU32[++vertexOffset] = tintBL; - - this.vertexCount += 3; - - return hasFlushed; - }, - - /** - * Generic function for batching a textured quad using argument values instead of a Game Object. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTexture - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - Source GameObject. - * @param {WebGLTexture} texture - Raw WebGLTexture associated with the quad. - * @param {integer} textureWidth - Real texture width. - * @param {integer} textureHeight - Real texture height. - * @param {number} srcX - X coordinate of the quad. - * @param {number} srcY - Y coordinate of the quad. - * @param {number} srcWidth - Width of the quad. - * @param {number} srcHeight - Height of the quad. - * @param {number} scaleX - X component of scale. - * @param {number} scaleY - Y component of scale. - * @param {number} rotation - Rotation of the quad. - * @param {boolean} flipX - Indicates if the quad is horizontally flipped. - * @param {boolean} flipY - Indicates if the quad is vertically flipped. - * @param {number} scrollFactorX - By which factor is the quad affected by the camera horizontal scroll. - * @param {number} scrollFactorY - By which factor is the quad effected by the camera vertical scroll. - * @param {number} displayOriginX - Horizontal origin in pixels. - * @param {number} displayOriginY - Vertical origin in pixels. - * @param {number} frameX - X coordinate of the texture frame. - * @param {number} frameY - Y coordinate of the texture frame. - * @param {number} frameWidth - Width of the texture frame. - * @param {number} frameHeight - Height of the texture frame. - * @param {integer} tintTL - Tint for top left. - * @param {integer} tintTR - Tint for top right. - * @param {integer} tintBL - Tint for bottom left. - * @param {integer} tintBR - Tint for bottom right. - * @param {number} tintEffect - The tint effect. - * @param {number} uOffset - Horizontal offset on texture coordinate. - * @param {number} vOffset - Vertical offset on texture coordinate. - * @param {Phaser.Cameras.Scene2D.Camera} camera - Current used camera. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - Parent container. - * @param {boolean} [skipFlip=false] - Skip the renderTexture check. - */ - batchTexture: function ( - gameObject, - texture, - textureWidth, textureHeight, - srcX, srcY, - srcWidth, srcHeight, - scaleX, scaleY, - rotation, - flipX, flipY, - scrollFactorX, scrollFactorY, - displayOriginX, displayOriginY, - frameX, frameY, frameWidth, frameHeight, - tintTL, tintTR, tintBL, tintBR, tintEffect, - uOffset, vOffset, - camera, - parentTransformMatrix, - skipFlip) - { - this.renderer.setPipeline(this, gameObject); - - var camMatrix = this._tempMatrix1; - var spriteMatrix = this._tempMatrix2; - var calcMatrix = this._tempMatrix3; - - var u0 = (frameX / textureWidth) + uOffset; - var v0 = (frameY / textureHeight) + vOffset; - var u1 = (frameX + frameWidth) / textureWidth + uOffset; - var v1 = (frameY + frameHeight) / textureHeight + vOffset; - - var width = srcWidth; - var height = srcHeight; - - var x = -displayOriginX; - var y = -displayOriginY; - - if (gameObject.isCropped) - { - var crop = gameObject._crop; - - width = crop.width; - height = crop.height; - - srcWidth = crop.width; - srcHeight = crop.height; - - frameX = crop.x; - frameY = crop.y; - - var ox = frameX; - var oy = frameY; - - if (flipX) - { - ox = (frameWidth - crop.x - crop.width); - } - - if (flipY && !texture.isRenderTexture) - { - oy = (frameHeight - crop.y - crop.height); - } - - u0 = (ox / textureWidth) + uOffset; - v0 = (oy / textureHeight) + vOffset; - u1 = (ox + crop.width) / textureWidth + uOffset; - v1 = (oy + crop.height) / textureHeight + vOffset; - - x = -displayOriginX + frameX; - y = -displayOriginY + frameY; - } - - // Invert the flipY if this is a RenderTexture - flipY = flipY ^ (!skipFlip && texture.isRenderTexture ? 1 : 0); - - if (flipX) - { - width *= -1; - x += srcWidth; - } - - if (flipY) - { - height *= -1; - y += srcHeight; - } - - var xw = x + width; - var yh = y + height; - - spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); - - camMatrix.copyFrom(camera.matrix); - - if (parentTransformMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); - - // Undo the camera scroll - spriteMatrix.e = srcX; - spriteMatrix.f = srcY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - else - { - spriteMatrix.e -= camera.scrollX * scrollFactorX; - spriteMatrix.f -= camera.scrollY * scrollFactorY; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(spriteMatrix, calcMatrix); - } - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(x, yh); - var ty1 = calcMatrix.getY(x, yh); - - var tx2 = calcMatrix.getX(xw, yh); - var ty2 = calcMatrix.getY(xw, yh); - - var tx3 = calcMatrix.getX(xw, y); - var ty3 = calcMatrix.getY(xw, y); - - if (camera.roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - this.setTexture2D(texture, 0); - - this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); - }, - - /** - * Adds a Texture Frame into the batch for rendering. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTextureFrame - * @since 3.12.0 - * - * @param {Phaser.Textures.Frame} frame - The Texture Frame to be rendered. - * @param {number} x - The horizontal position to render the texture at. - * @param {number} y - The vertical position to render the texture at. - * @param {number} tint - The tint color. - * @param {number} alpha - The alpha value. - * @param {Phaser.GameObjects.Components.TransformMatrix} transformMatrix - The Transform Matrix to use for the texture. - * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - A parent Transform Matrix. - */ - batchTextureFrame: function ( - frame, - x, y, - tint, alpha, - transformMatrix, - parentTransformMatrix - ) - { - this.renderer.setPipeline(this); - - var spriteMatrix = this._tempMatrix1.copyFrom(transformMatrix); - var calcMatrix = this._tempMatrix2; - - var xw = x + frame.width; - var yh = y + frame.height; - - if (parentTransformMatrix) - { - spriteMatrix.multiply(parentTransformMatrix, calcMatrix); - } - else - { - calcMatrix = spriteMatrix; - } - - var tx0 = calcMatrix.getX(x, y); - var ty0 = calcMatrix.getY(x, y); - - var tx1 = calcMatrix.getX(x, yh); - var ty1 = calcMatrix.getY(x, yh); - - var tx2 = calcMatrix.getX(xw, yh); - var ty2 = calcMatrix.getY(xw, yh); - - var tx3 = calcMatrix.getX(xw, y); - var ty3 = calcMatrix.getY(xw, y); - - this.setTexture2D(frame.glTexture, 0); - - tint = Utils.getTintAppendFloatAlpha(tint, alpha); - - this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, 0, frame.glTexture, 0); - }, - - /** - * Pushes a filled rectangle into the vertex batch. - * Rectangle has no transform values and isn't transformed into the local space. - * Used for directly batching untransformed rectangles, such as Camera background colors. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#drawFillRect - * @since 3.12.0 - * - * @param {number} x - Horizontal top left coordinate of the rectangle. - * @param {number} y - Vertical top left coordinate of the rectangle. - * @param {number} width - Width of the rectangle. - * @param {number} height - Height of the rectangle. - * @param {number} color - Color of the rectangle to draw. - * @param {number} alpha - Alpha value of the rectangle to draw. - */ - drawFillRect: function (x, y, width, height, color, alpha) - { - var xw = x + width; - var yh = y + height; - - this.setTexture2D(); - - var tint = Utils.getTintAppendFloatAlphaAndSwap(color, alpha); - - this.batchQuad(x, y, x, yh, xw, yh, xw, y, 0, 0, 1, 1, tint, tint, tint, tint, 2); - }, - - /** - * Pushes a filled rectangle into the vertex batch. - * Rectangle factors in the given transform matrices before adding to the batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillRect - * @since 3.12.0 - * - * @param {number} x - Horizontal top left coordinate of the rectangle. - * @param {number} y - Vertical top left coordinate of the rectangle. - * @param {number} width - Width of the rectangle. - * @param {number} height - Height of the rectangle. - * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. - */ - batchFillRect: function (x, y, width, height, currentMatrix, parentMatrix) - { - this.renderer.setPipeline(this); - - var calcMatrix = this._tempMatrix3; - - // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix - if (parentMatrix) - { - parentMatrix.multiply(currentMatrix, calcMatrix); - } - - var xw = x + width; - var yh = y + height; - - var x0 = calcMatrix.getX(x, y); - var y0 = calcMatrix.getY(x, y); - - var x1 = calcMatrix.getX(x, yh); - var y1 = calcMatrix.getY(x, yh); - - var x2 = calcMatrix.getX(xw, yh); - var y2 = calcMatrix.getY(xw, yh); - - var x3 = calcMatrix.getX(xw, y); - var y3 = calcMatrix.getY(xw, y); - - var frame = this.currentFrame; - - var u0 = frame.u0; - var v0 = frame.v0; - var u1 = frame.u1; - var v1 = frame.v1; - - this.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.fillTint.BR, this.tintEffect); - }, - - /** - * Pushes a filled triangle into the vertex batch. - * Triangle factors in the given transform matrices before adding to the batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillTriangle - * @since 3.12.0 - * - * @param {number} x0 - Point 0 x coordinate. - * @param {number} y0 - Point 0 y coordinate. - * @param {number} x1 - Point 1 x coordinate. - * @param {number} y1 - Point 1 y coordinate. - * @param {number} x2 - Point 2 x coordinate. - * @param {number} y2 - Point 2 y coordinate. - * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. - */ - batchFillTriangle: function (x0, y0, x1, y1, x2, y2, currentMatrix, parentMatrix) - { - this.renderer.setPipeline(this); - - var calcMatrix = this._tempMatrix3; - - // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix - if (parentMatrix) - { - parentMatrix.multiply(currentMatrix, calcMatrix); - } - - var tx0 = calcMatrix.getX(x0, y0); - var ty0 = calcMatrix.getY(x0, y0); - - var tx1 = calcMatrix.getX(x1, y1); - var ty1 = calcMatrix.getY(x1, y1); - - var tx2 = calcMatrix.getX(x2, y2); - var ty2 = calcMatrix.getY(x2, y2); - - var frame = this.currentFrame; - - var u0 = frame.u0; - var v0 = frame.v0; - var u1 = frame.u1; - var v1 = frame.v1; - - this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.tintEffect); - }, - - /** - * Pushes a stroked triangle into the vertex batch. - * Triangle factors in the given transform matrices before adding to the batch. - * The triangle is created from 3 lines and drawn using the `batchStrokePath` method. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchStrokeTriangle - * @since 3.12.0 - * - * @param {number} x0 - Point 0 x coordinate. - * @param {number} y0 - Point 0 y coordinate. - * @param {number} x1 - Point 1 x coordinate. - * @param {number} y1 - Point 1 y coordinate. - * @param {number} x2 - Point 2 x coordinate. - * @param {number} y2 - Point 2 y coordinate. - * @param {number} lineWidth - The width of the line in pixels. - * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. - */ - batchStrokeTriangle: function (x0, y0, x1, y1, x2, y2, lineWidth, currentMatrix, parentMatrix) - { - var tempTriangle = this.tempTriangle; - - tempTriangle[0].x = x0; - tempTriangle[0].y = y0; - tempTriangle[0].width = lineWidth; - - tempTriangle[1].x = x1; - tempTriangle[1].y = y1; - tempTriangle[1].width = lineWidth; - - tempTriangle[2].x = x2; - tempTriangle[2].y = y2; - tempTriangle[2].width = lineWidth; - - tempTriangle[3].x = x0; - tempTriangle[3].y = y0; - tempTriangle[3].width = lineWidth; - - this.batchStrokePath(tempTriangle, lineWidth, false, currentMatrix, parentMatrix); - }, - - /** - * Adds the given path to the vertex batch for rendering. - * - * It works by taking the array of path data and then passing it through Earcut, which - * creates a list of polygons. Each polygon is then added to the batch. - * - * The path is always automatically closed because it's filled. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillPath - * @since 3.12.0 - * - * @param {array} path - Collection of points that represent the path. - * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. - */ - batchFillPath: function (path, currentMatrix, parentMatrix) - { - this.renderer.setPipeline(this); - - var calcMatrix = this._tempMatrix3; - - // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix - if (parentMatrix) - { - parentMatrix.multiply(currentMatrix, calcMatrix); - } - - var length = path.length; - var polygonCache = this.polygonCache; - var polygonIndexArray; - var point; - - var tintTL = this.fillTint.TL; - var tintTR = this.fillTint.TR; - var tintBL = this.fillTint.BL; - var tintEffect = this.tintEffect; - - for (var pathIndex = 0; pathIndex < length; ++pathIndex) - { - point = path[pathIndex]; - polygonCache.push(point.x, point.y); - } - - polygonIndexArray = Earcut(polygonCache); - length = polygonIndexArray.length; - - var frame = this.currentFrame; - - for (var index = 0; index < length; index += 3) - { - var p0 = polygonIndexArray[index + 0] * 2; - var p1 = polygonIndexArray[index + 1] * 2; - var p2 = polygonIndexArray[index + 2] * 2; - - var x0 = polygonCache[p0 + 0]; - var y0 = polygonCache[p0 + 1]; - var x1 = polygonCache[p1 + 0]; - var y1 = polygonCache[p1 + 1]; - var x2 = polygonCache[p2 + 0]; - var y2 = polygonCache[p2 + 1]; - - var tx0 = calcMatrix.getX(x0, y0); - var ty0 = calcMatrix.getY(x0, y0); - - var tx1 = calcMatrix.getX(x1, y1); - var ty1 = calcMatrix.getY(x1, y1); - - var tx2 = calcMatrix.getX(x2, y2); - var ty2 = calcMatrix.getY(x2, y2); - - var u0 = frame.u0; - var v0 = frame.v0; - var u1 = frame.u1; - var v1 = frame.v1; - - this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect); - } - - polygonCache.length = 0; - }, - - /** - * Adds the given path to the vertex batch for rendering. - * - * It works by taking the array of path data and calling `batchLine` for each section - * of the path. - * - * The path is optionally closed at the end. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchStrokePath - * @since 3.12.0 - * - * @param {array} path - Collection of points that represent the path. - * @param {number} lineWidth - The width of the line segments in pixels. - * @param {boolean} pathOpen - Indicates if the path should be closed or left open. - * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. - */ - batchStrokePath: function (path, lineWidth, pathOpen, currentMatrix, parentMatrix) - { - this.renderer.setPipeline(this); - - // Reset the closePath booleans - this.prevQuad[4] = 0; - this.firstQuad[4] = 0; - - var pathLength = path.length - 1; - - for (var pathIndex = 0; pathIndex < pathLength; pathIndex++) - { - var point0 = path[pathIndex]; - var point1 = path[pathIndex + 1]; - - this.batchLine( - point0.x, - point0.y, - point1.x, - point1.y, - point0.width / 2, - point1.width / 2, - lineWidth, - pathIndex, - !pathOpen && (pathIndex === pathLength - 1), - currentMatrix, - parentMatrix - ); - } - }, - - /** - * Creates a quad and adds it to the vertex batch based on the given line values. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchLine - * @since 3.12.0 - * - * @param {number} ax - X coordinate to the start of the line - * @param {number} ay - Y coordinate to the start of the line - * @param {number} bx - X coordinate to the end of the line - * @param {number} by - Y coordinate to the end of the line - * @param {number} aLineWidth - Width of the start of the line - * @param {number} bLineWidth - Width of the end of the line - * @param {Float32Array} currentMatrix - Parent matrix, generally used by containers - */ - batchLine: function (ax, ay, bx, by, aLineWidth, bLineWidth, lineWidth, index, closePath, currentMatrix, parentMatrix) - { - this.renderer.setPipeline(this); - - var calcMatrix = this._tempMatrix3; - - // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix - if (parentMatrix) - { - parentMatrix.multiply(currentMatrix, calcMatrix); - } - - var dx = bx - ax; - var dy = by - ay; - - var len = Math.sqrt(dx * dx + dy * dy); - var al0 = aLineWidth * (by - ay) / len; - var al1 = aLineWidth * (ax - bx) / len; - var bl0 = bLineWidth * (by - ay) / len; - var bl1 = bLineWidth * (ax - bx) / len; - - var lx0 = bx - bl0; - var ly0 = by - bl1; - var lx1 = ax - al0; - var ly1 = ay - al1; - var lx2 = bx + bl0; - var ly2 = by + bl1; - var lx3 = ax + al0; - var ly3 = ay + al1; - - // tx0 = bottom right - var brX = calcMatrix.getX(lx0, ly0); - var brY = calcMatrix.getY(lx0, ly0); - - // tx1 = bottom left - var blX = calcMatrix.getX(lx1, ly1); - var blY = calcMatrix.getY(lx1, ly1); - - // tx2 = top right - var trX = calcMatrix.getX(lx2, ly2); - var trY = calcMatrix.getY(lx2, ly2); - - // tx3 = top left - var tlX = calcMatrix.getX(lx3, ly3); - var tlY = calcMatrix.getY(lx3, ly3); - - var tint = this.strokeTint; - var tintEffect = this.tintEffect; - - var tintTL = tint.TL; - var tintTR = tint.TR; - var tintBL = tint.BL; - var tintBR = tint.BR; - - var frame = this.currentFrame; - - var u0 = frame.u0; - var v0 = frame.v0; - var u1 = frame.u1; - var v1 = frame.v1; - - // TL, BL, BR, TR - this.batchQuad(tlX, tlY, blX, blY, brX, brY, trX, trY, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); - - if (lineWidth <= 2) - { - // No point doing a linejoin if the line isn't thick enough - return; - } - - var prev = this.prevQuad; - var first = this.firstQuad; - - if (index > 0 && prev[4]) - { - this.batchQuad(tlX, tlY, blX, blY, prev[0], prev[1], prev[2], prev[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); - } - else - { - first[0] = tlX; - first[1] = tlY; - first[2] = blX; - first[3] = blY; - first[4] = 1; - } - - if (closePath && first[4]) - { - // Add a join for the final path segment - this.batchQuad(brX, brY, trX, trY, first[0], first[1], first[2], first[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); - } - else - { - // Store it - - prev[0] = brX; - prev[1] = brY; - prev[2] = trX; - prev[3] = trY; - prev[4] = 1; - } - } - -}); - -module.exports = TextureTintPipeline; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var Earcut = require('../../../geom/polygon/Earcut'); +var GetFastValue = require('../../../utils/object/GetFastValue'); +var ModelViewProjection = require('./components/ModelViewProjection'); +var ShaderSourceFS = require('../shaders/TextureTint-frag.js'); +var ShaderSourceVS = require('../shaders/TextureTint-vert.js'); +var TransformMatrix = require('../../../gameobjects/components/TransformMatrix'); +var Utils = require('../Utils'); +var WebGLPipeline = require('../WebGLPipeline'); + +/** + * @classdesc + * TextureTintPipeline implements the rendering infrastructure + * for displaying textured objects + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * + * @class TextureTintPipeline + * @extends Phaser.Renderer.WebGL.WebGLPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.0.0 + * + * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. + */ +var TextureTintPipeline = new Class({ + + Extends: WebGLPipeline, + + Mixins: [ + ModelViewProjection + ], + + initialize: + + function TextureTintPipeline (config) + { + var rendererConfig = config.renderer.config; + + // Vertex Size = attribute size added together (2 + 2 + 1 + 4) + + WebGLPipeline.call(this, { + game: config.game, + renderer: config.renderer, + gl: config.renderer.gl, + topology: GetFastValue(config, 'topology', config.renderer.gl.TRIANGLES), + vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), + fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), + vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), + vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), + attributes: [ + { + name: 'inPosition', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: 0 + }, + { + name: 'inTexCoord', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: Float32Array.BYTES_PER_ELEMENT * 2 + }, + { + name: 'inTintEffect', + size: 1, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: Float32Array.BYTES_PER_ELEMENT * 4 + }, + { + name: 'inTint', + size: 4, + type: config.renderer.gl.UNSIGNED_BYTE, + normalized: true, + offset: Float32Array.BYTES_PER_ELEMENT * 5 + } + ] + }); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#vertexViewF32 + * @type {Float32Array} + * @since 3.0.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * Uint32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#vertexViewU32 + * @type {Uint32Array} + * @since 3.0.0 + */ + this.vertexViewU32 = new Uint32Array(this.vertexData); + + /** + * Size of the batch. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#maxQuads + * @type {integer} + * @since 3.0.0 + */ + this.maxQuads = rendererConfig.batchSize; + + /** + * Collection of batch information + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batches + * @type {array} + * @since 3.1.0 + */ + this.batches = []; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#_tempMatrix4 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.11.0 + */ + this._tempMatrix4 = new TransformMatrix(); + + /** + * Used internally to draw stroked triangles. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#tempTriangle + * @type {array} + * @private + * @since 3.12.0 + */ + this.tempTriangle = [ + { x: 0, y: 0, width: 0 }, + { x: 0, y: 0, width: 0 }, + { x: 0, y: 0, width: 0 }, + { x: 0, y: 0, width: 0 } + ]; + + /** + * The tint effect to be applied by the shader in the next geometry draw: + * + * 0 = texture multiplied by color + * 1 = solid color + texture alpha + * 2 = solid color, no texture + * 3 = solid texture, no color + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#tintEffect + * @type {number} + * @private + * @since 3.12.0 + */ + this.tintEffect = 2; + + /** + * Cached stroke tint. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#strokeTint + * @type {object} + * @private + * @since 3.12.0 + */ + this.strokeTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; + + /** + * Cached fill tint. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#fillTint + * @type {object} + * @private + * @since 3.12.0 + */ + this.fillTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; + + /** + * Internal texture frame reference. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#currentFrame + * @type {Phaser.Textures.Frame} + * @private + * @since 3.12.0 + */ + this.currentFrame = { u0: 0, v0: 0, u1: 1, v1: 1 }; + + /** + * Internal path quad cache. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#firstQuad + * @type {array} + * @private + * @since 3.12.0 + */ + this.firstQuad = [ 0, 0, 0, 0, 0 ]; + + /** + * Internal path quad cache. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#prevQuad + * @type {array} + * @private + * @since 3.12.0 + */ + this.prevQuad = [ 0, 0, 0, 0, 0 ]; + + /** + * Used internally for triangulating a polygon. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#polygonCache + * @type {array} + * @private + * @since 3.12.0 + */ + this.polygonCache = []; + + this.mvpInit(); + }, + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#onBind + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + WebGLPipeline.prototype.onBind.call(this); + + this.mvpUpdate(); + + return this; + }, + + /** + * Resizes this pipeline and updates the projection. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#resize + * @since 3.0.0 + * + * @param {number} width - The new width. + * @param {number} height - The new height. + * @param {number} resolution - The resolution. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + WebGLPipeline.prototype.resize.call(this, width, height, resolution); + + this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); + + return this; + }, + + /** + * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#setTexture2D + * @since 3.1.0 + * + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline} This pipeline instance. + */ + setTexture2D: function (texture, unit) + { + if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } + if (unit === undefined) { unit = 0; } + + if (this.requireTextureBatch(texture, unit)) + { + this.pushBatch(texture, unit); + } + + return this; + }, + + /** + * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#requireTextureBatch + * @since 3.16.0 + * + * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param {integer} unit - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. + */ + requireTextureBatch: function (texture, unit) + { + var batches = this.batches; + var batchLength = batches.length; + + if (batchLength > 0) + { + // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property + var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; + + return !(currentTexture === texture); + } + + return true; + }, + + /** + * Creates a new batch object and pushes it to a batch array. + * The batch object contains information relevant to the current + * vertex batch like the offset in the vertex buffer, vertex count and + * the textures used by that batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#pushBatch + * @since 3.1.0 + * + * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. + * @param {integer} unit - Texture unit to which the texture needs to be bound. + */ + pushBatch: function (texture, unit) + { + if (unit === 0) + { + this.batches.push({ + first: this.vertexCount, + texture: texture, + textures: [] + }); + } + else + { + var textures = []; + + textures[unit - 1] = texture; + + this.batches.push({ + first: this.vertexCount, + texture: null, + textures: textures + }); + } + }, + + /** + * Uploads the vertex data and emits a draw call for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#flush + * @since 3.0.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) + { + return this; + } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + var renderer = this.renderer; + + var batches = this.batches; + var batchCount = batches.length; + var batchVertexCount = 0; + var batch = null; + var batchNext; + var textureIndex; + var nTexture; + + if (batchCount === 0 || vertexCount === 0) + { + this.flushLocked = false; + + return this; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + + // Process the TEXTURE BATCHES + + for (var index = 0; index < batchCount - 1; index++) + { + batch = batches[index]; + batchNext = batches[index + 1]; + + // Multi-texture check (for non-zero texture units) + if (batch.textures.length > 0) + { + for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) + { + nTexture = batch.textures[textureIndex]; + + if (nTexture) + { + renderer.setTexture2D(nTexture, 1 + textureIndex, false); + } + } + + gl.activeTexture(gl.TEXTURE0); + } + + batchVertexCount = batchNext.first - batch.first; + + // Bail out if texture property is null (i.e. if a texture unit > 0) + if (batch.texture === null || batchVertexCount <= 0) + { + continue; + } + + renderer.setTexture2D(batch.texture, 0, false); + + gl.drawArrays(topology, batch.first, batchVertexCount); + } + + // Left over data + batch = batches[batchCount - 1]; + + // Multi-texture check (for non-zero texture units) + + if (batch.textures.length > 0) + { + for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) + { + nTexture = batch.textures[textureIndex]; + + if (nTexture) + { + renderer.setTexture2D(nTexture, 1 + textureIndex, false); + } + } + + gl.activeTexture(gl.TEXTURE0); + } + + batchVertexCount = vertexCount - batch.first; + + if (batch.texture && batchVertexCount > 0) + { + renderer.setTexture2D(batch.texture, 0, false); + + gl.drawArrays(topology, batch.first, batchVertexCount); + } + + this.vertexCount = 0; + + batches.length = 0; + + this.flushLocked = false; + + return this; + }, + + /** + * Takes a Sprite Game Object, or any object that extends it, and adds it to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchSprite + * @since 3.0.0 + * + * @param {(Phaser.GameObjects.Image|Phaser.GameObjects.Sprite)} sprite - The texture based Game Object to add to the batch. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the rendering transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - The transform matrix of the parent container, if set. + */ + batchSprite: function (sprite, camera, parentTransformMatrix) + { + // Will cause a flush if there are batchSize entries already + this.renderer.setPipeline(this); + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var frame = sprite.frame; + var texture = frame.glTexture; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + var frameX = frame.x; + var frameY = frame.y; + var frameWidth = frame.cutWidth; + var frameHeight = frame.cutHeight; + var customPivot = frame.customPivot; + + var displayOriginX = sprite.displayOriginX; + var displayOriginY = sprite.displayOriginY; + + var x = -displayOriginX + frameX; + var y = -displayOriginY + frameY; + + if (sprite.isCropped) + { + var crop = sprite._crop; + + if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) + { + frame.updateCropUVs(crop, sprite.flipX, sprite.flipY); + } + + u0 = crop.u0; + v0 = crop.v0; + u1 = crop.u1; + v1 = crop.v1; + + frameWidth = crop.width; + frameHeight = crop.height; + + frameX = crop.x; + frameY = crop.y; + + x = -displayOriginX + frameX; + y = -displayOriginY + frameY; + } + + var flipX = 1; + var flipY = 1; + + if (sprite.flipX) + { + if (!customPivot) + { + x += (-frame.realWidth + (displayOriginX * 2)); + } + + flipX = -1; + } + + // Auto-invert the flipY if this is coming from a GLTexture + if (sprite.flipY || (frame.source.isGLTexture && !texture.flipY)) + { + if (!customPivot) + { + y += (-frame.realHeight + (displayOriginY * 2)); + } + + flipY = -1; + } + + spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX * flipX, sprite.scaleY * flipY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = sprite.x; + spriteMatrix.f = sprite.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; + spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var xw = x + frameWidth; + var yh = y + frameHeight; + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + var tintTL = Utils.getTintAppendFloatAlpha(sprite._tintTL, camera.alpha * sprite._alphaTL); + var tintTR = Utils.getTintAppendFloatAlpha(sprite._tintTR, camera.alpha * sprite._alphaTR); + var tintBL = Utils.getTintAppendFloatAlpha(sprite._tintBL, camera.alpha * sprite._alphaBL); + var tintBR = Utils.getTintAppendFloatAlpha(sprite._tintBR, camera.alpha * sprite._alphaBR); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + this.setTexture2D(texture, 0); + + var tintEffect = (sprite._isTinted && sprite.tintFill); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + }, + + /** + * Adds the vertices data into the batch and flushes if full. + * + * Assumes 6 vertices in the following arrangement: + * + * ``` + * 0----3 + * |\ B| + * | \ | + * | \ | + * | A \| + * | \ + * 1----2 + * ``` + * + * Where tx0/ty0 = 0, tx1/ty1 = 1, tx2/ty2 = 2 and tx3/ty3 = 3 + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchQuad + * @since 3.12.0 + * + * @param {number} x0 - The top-left x position. + * @param {number} y0 - The top-left y position. + * @param {number} x1 - The bottom-left x position. + * @param {number} y1 - The bottom-left y position. + * @param {number} x2 - The bottom-right x position. + * @param {number} y2 - The bottom-right y position. + * @param {number} x3 - The top-right x position. + * @param {number} y3 - The top-right y position. + * @param {number} u0 - UV u0 value. + * @param {number} v0 - UV v0 value. + * @param {number} u1 - UV u1 value. + * @param {number} v1 - UV v1 value. + * @param {number} tintTL - The top-left tint color value. + * @param {number} tintTR - The top-right tint color value. + * @param {number} tintBL - The bottom-left tint color value. + * @param {number} tintBR - The bottom-right tint color value. + * @param {(number|boolean)} tintEffect - The tint effect for the shader to use. + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch if a flush occurs. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if this method caused the batch to flush, otherwise `false`. + */ + batchQuad: function (x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, unit) + { + var hasFlushed = false; + + if (this.vertexCount + 6 > this.vertexCapacity) + { + this.flush(); + + hasFlushed = true; + + this.setTexture2D(texture, unit); + } + + var vertexViewF32 = this.vertexViewF32; + var vertexViewU32 = this.vertexViewU32; + + var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; + + vertexViewF32[++vertexOffset] = x0; + vertexViewF32[++vertexOffset] = y0; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTL; + + vertexViewF32[++vertexOffset] = x1; + vertexViewF32[++vertexOffset] = y1; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBL; + + vertexViewF32[++vertexOffset] = x2; + vertexViewF32[++vertexOffset] = y2; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBR; + + vertexViewF32[++vertexOffset] = x0; + vertexViewF32[++vertexOffset] = y0; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTL; + + vertexViewF32[++vertexOffset] = x2; + vertexViewF32[++vertexOffset] = y2; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBR; + + vertexViewF32[++vertexOffset] = x3; + vertexViewF32[++vertexOffset] = y3; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTR; + + this.vertexCount += 6; + + return hasFlushed; + }, + + /** + * Adds the vertices data into the batch and flushes if full. + * + * Assumes 3 vertices in the following arrangement: + * + * ``` + * 0 + * |\ + * | \ + * | \ + * | \ + * | \ + * 1-----2 + * ``` + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTri + * @since 3.12.0 + * + * @param {number} x1 - The bottom-left x position. + * @param {number} y1 - The bottom-left y position. + * @param {number} x2 - The bottom-right x position. + * @param {number} y2 - The bottom-right y position. + * @param {number} x3 - The top-right x position. + * @param {number} y3 - The top-right y position. + * @param {number} u0 - UV u0 value. + * @param {number} v0 - UV v0 value. + * @param {number} u1 - UV u1 value. + * @param {number} v1 - UV v1 value. + * @param {number} tintTL - The top-left tint color value. + * @param {number} tintTR - The top-right tint color value. + * @param {number} tintBL - The bottom-left tint color value. + * @param {(number|boolean)} tintEffect - The tint effect for the shader to use. + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch if a flush occurs. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if this method caused the batch to flush, otherwise `false`. + */ + batchTri: function (x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect, texture, unit) + { + var hasFlushed = false; + + if (this.vertexCount + 3 > this.vertexCapacity) + { + this.flush(); + + this.setTexture2D(texture, unit); + + hasFlushed = true; + } + + var vertexViewF32 = this.vertexViewF32; + var vertexViewU32 = this.vertexViewU32; + + var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; + + vertexViewF32[++vertexOffset] = x1; + vertexViewF32[++vertexOffset] = y1; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v0; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTL; + + vertexViewF32[++vertexOffset] = x2; + vertexViewF32[++vertexOffset] = y2; + vertexViewF32[++vertexOffset] = u0; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintTR; + + vertexViewF32[++vertexOffset] = x3; + vertexViewF32[++vertexOffset] = y3; + vertexViewF32[++vertexOffset] = u1; + vertexViewF32[++vertexOffset] = v1; + vertexViewF32[++vertexOffset] = tintEffect; + vertexViewU32[++vertexOffset] = tintBL; + + this.vertexCount += 3; + + return hasFlushed; + }, + + /** + * Generic function for batching a textured quad using argument values instead of a Game Object. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTexture + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - Source GameObject. + * @param {WebGLTexture} texture - Raw WebGLTexture associated with the quad. + * @param {integer} textureWidth - Real texture width. + * @param {integer} textureHeight - Real texture height. + * @param {number} srcX - X coordinate of the quad. + * @param {number} srcY - Y coordinate of the quad. + * @param {number} srcWidth - Width of the quad. + * @param {number} srcHeight - Height of the quad. + * @param {number} scaleX - X component of scale. + * @param {number} scaleY - Y component of scale. + * @param {number} rotation - Rotation of the quad. + * @param {boolean} flipX - Indicates if the quad is horizontally flipped. + * @param {boolean} flipY - Indicates if the quad is vertically flipped. + * @param {number} scrollFactorX - By which factor is the quad affected by the camera horizontal scroll. + * @param {number} scrollFactorY - By which factor is the quad effected by the camera vertical scroll. + * @param {number} displayOriginX - Horizontal origin in pixels. + * @param {number} displayOriginY - Vertical origin in pixels. + * @param {number} frameX - X coordinate of the texture frame. + * @param {number} frameY - Y coordinate of the texture frame. + * @param {number} frameWidth - Width of the texture frame. + * @param {number} frameHeight - Height of the texture frame. + * @param {integer} tintTL - Tint for top left. + * @param {integer} tintTR - Tint for top right. + * @param {integer} tintBL - Tint for bottom left. + * @param {integer} tintBR - Tint for bottom right. + * @param {number} tintEffect - The tint effect. + * @param {number} uOffset - Horizontal offset on texture coordinate. + * @param {number} vOffset - Vertical offset on texture coordinate. + * @param {Phaser.Cameras.Scene2D.Camera} camera - Current used camera. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentTransformMatrix - Parent container. + * @param {boolean} [skipFlip=false] - Skip the renderTexture check. + */ + batchTexture: function ( + gameObject, + texture, + textureWidth, textureHeight, + srcX, srcY, + srcWidth, srcHeight, + scaleX, scaleY, + rotation, + flipX, flipY, + scrollFactorX, scrollFactorY, + displayOriginX, displayOriginY, + frameX, frameY, frameWidth, frameHeight, + tintTL, tintTR, tintBL, tintBR, tintEffect, + uOffset, vOffset, + camera, + parentTransformMatrix, + skipFlip) + { + this.renderer.setPipeline(this, gameObject); + + var camMatrix = this._tempMatrix1; + var spriteMatrix = this._tempMatrix2; + var calcMatrix = this._tempMatrix3; + + var u0 = (frameX / textureWidth) + uOffset; + var v0 = (frameY / textureHeight) + vOffset; + var u1 = (frameX + frameWidth) / textureWidth + uOffset; + var v1 = (frameY + frameHeight) / textureHeight + vOffset; + + var width = srcWidth; + var height = srcHeight; + + var x = -displayOriginX; + var y = -displayOriginY; + + if (gameObject.isCropped) + { + var crop = gameObject._crop; + + width = crop.width; + height = crop.height; + + srcWidth = crop.width; + srcHeight = crop.height; + + frameX = crop.x; + frameY = crop.y; + + var ox = frameX; + var oy = frameY; + + if (flipX) + { + ox = (frameWidth - crop.x - crop.width); + } + + if (flipY && !texture.isRenderTexture) + { + oy = (frameHeight - crop.y - crop.height); + } + + u0 = (ox / textureWidth) + uOffset; + v0 = (oy / textureHeight) + vOffset; + u1 = (ox + crop.width) / textureWidth + uOffset; + v1 = (oy + crop.height) / textureHeight + vOffset; + + x = -displayOriginX + frameX; + y = -displayOriginY + frameY; + } + + // Invert the flipY if this is a RenderTexture + flipY = flipY ^ (!skipFlip && texture.isRenderTexture ? 1 : 0); + + if (flipX) + { + width *= -1; + x += srcWidth; + } + + if (flipY) + { + height *= -1; + y += srcHeight; + } + + var xw = x + width; + var yh = y + height; + + spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); + + camMatrix.copyFrom(camera.matrix); + + if (parentTransformMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); + + // Undo the camera scroll + spriteMatrix.e = srcX; + spriteMatrix.f = srcY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + else + { + spriteMatrix.e -= camera.scrollX * scrollFactorX; + spriteMatrix.f -= camera.scrollY * scrollFactorY; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(spriteMatrix, calcMatrix); + } + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + this.setTexture2D(texture, 0); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect, texture, 0); + }, + + /** + * Adds a Texture Frame into the batch for rendering. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchTextureFrame + * @since 3.12.0 + * + * @param {Phaser.Textures.Frame} frame - The Texture Frame to be rendered. + * @param {number} x - The horizontal position to render the texture at. + * @param {number} y - The vertical position to render the texture at. + * @param {number} tint - The tint color. + * @param {number} alpha - The alpha value. + * @param {Phaser.GameObjects.Components.TransformMatrix} transformMatrix - The Transform Matrix to use for the texture. + * @param {Phaser.GameObjects.Components.TransformMatrix} [parentTransformMatrix] - A parent Transform Matrix. + */ + batchTextureFrame: function ( + frame, + x, y, + tint, alpha, + transformMatrix, + parentTransformMatrix + ) + { + this.renderer.setPipeline(this); + + var spriteMatrix = this._tempMatrix1.copyFrom(transformMatrix); + var calcMatrix = this._tempMatrix2; + + var xw = x + frame.width; + var yh = y + frame.height; + + if (parentTransformMatrix) + { + spriteMatrix.multiply(parentTransformMatrix, calcMatrix); + } + else + { + calcMatrix = spriteMatrix; + } + + var tx0 = calcMatrix.getX(x, y); + var ty0 = calcMatrix.getY(x, y); + + var tx1 = calcMatrix.getX(x, yh); + var ty1 = calcMatrix.getY(x, yh); + + var tx2 = calcMatrix.getX(xw, yh); + var ty2 = calcMatrix.getY(xw, yh); + + var tx3 = calcMatrix.getX(xw, y); + var ty3 = calcMatrix.getY(xw, y); + + this.setTexture2D(frame.glTexture, 0); + + tint = Utils.getTintAppendFloatAlpha(tint, alpha); + + this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, 0, frame.glTexture, 0); + }, + + /** + * Pushes a filled rectangle into the vertex batch. + * Rectangle has no transform values and isn't transformed into the local space. + * Used for directly batching untransformed rectangles, such as Camera background colors. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#drawFillRect + * @since 3.12.0 + * + * @param {number} x - Horizontal top left coordinate of the rectangle. + * @param {number} y - Vertical top left coordinate of the rectangle. + * @param {number} width - Width of the rectangle. + * @param {number} height - Height of the rectangle. + * @param {number} color - Color of the rectangle to draw. + * @param {number} alpha - Alpha value of the rectangle to draw. + */ + drawFillRect: function (x, y, width, height, color, alpha) + { + var xw = x + width; + var yh = y + height; + + this.setTexture2D(); + + var tint = Utils.getTintAppendFloatAlphaAndSwap(color, alpha); + + this.batchQuad(x, y, x, yh, xw, yh, xw, y, 0, 0, 1, 1, tint, tint, tint, tint, 2); + }, + + /** + * Pushes a filled rectangle into the vertex batch. + * Rectangle factors in the given transform matrices before adding to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillRect + * @since 3.12.0 + * + * @param {number} x - Horizontal top left coordinate of the rectangle. + * @param {number} y - Vertical top left coordinate of the rectangle. + * @param {number} width - Width of the rectangle. + * @param {number} height - Height of the rectangle. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchFillRect: function (x, y, width, height, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var xw = x + width; + var yh = y + height; + + var x0 = calcMatrix.getX(x, y); + var y0 = calcMatrix.getY(x, y); + + var x1 = calcMatrix.getX(x, yh); + var y1 = calcMatrix.getY(x, yh); + + var x2 = calcMatrix.getX(xw, yh); + var y2 = calcMatrix.getY(xw, yh); + + var x3 = calcMatrix.getX(xw, y); + var y3 = calcMatrix.getY(xw, y); + + var frame = this.currentFrame; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + this.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.fillTint.BR, this.tintEffect); + }, + + /** + * Pushes a filled triangle into the vertex batch. + * Triangle factors in the given transform matrices before adding to the batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillTriangle + * @since 3.12.0 + * + * @param {number} x0 - Point 0 x coordinate. + * @param {number} y0 - Point 0 y coordinate. + * @param {number} x1 - Point 1 x coordinate. + * @param {number} y1 - Point 1 y coordinate. + * @param {number} x2 - Point 2 x coordinate. + * @param {number} y2 - Point 2 y coordinate. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchFillTriangle: function (x0, y0, x1, y1, x2, y2, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var tx0 = calcMatrix.getX(x0, y0); + var ty0 = calcMatrix.getY(x0, y0); + + var tx1 = calcMatrix.getX(x1, y1); + var ty1 = calcMatrix.getY(x1, y1); + + var tx2 = calcMatrix.getX(x2, y2); + var ty2 = calcMatrix.getY(x2, y2); + + var frame = this.currentFrame; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.tintEffect); + }, + + /** + * Pushes a stroked triangle into the vertex batch. + * Triangle factors in the given transform matrices before adding to the batch. + * The triangle is created from 3 lines and drawn using the `batchStrokePath` method. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchStrokeTriangle + * @since 3.12.0 + * + * @param {number} x0 - Point 0 x coordinate. + * @param {number} y0 - Point 0 y coordinate. + * @param {number} x1 - Point 1 x coordinate. + * @param {number} y1 - Point 1 y coordinate. + * @param {number} x2 - Point 2 x coordinate. + * @param {number} y2 - Point 2 y coordinate. + * @param {number} lineWidth - The width of the line in pixels. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchStrokeTriangle: function (x0, y0, x1, y1, x2, y2, lineWidth, currentMatrix, parentMatrix) + { + var tempTriangle = this.tempTriangle; + + tempTriangle[0].x = x0; + tempTriangle[0].y = y0; + tempTriangle[0].width = lineWidth; + + tempTriangle[1].x = x1; + tempTriangle[1].y = y1; + tempTriangle[1].width = lineWidth; + + tempTriangle[2].x = x2; + tempTriangle[2].y = y2; + tempTriangle[2].width = lineWidth; + + tempTriangle[3].x = x0; + tempTriangle[3].y = y0; + tempTriangle[3].width = lineWidth; + + this.batchStrokePath(tempTriangle, lineWidth, false, currentMatrix, parentMatrix); + }, + + /** + * Adds the given path to the vertex batch for rendering. + * + * It works by taking the array of path data and then passing it through Earcut, which + * creates a list of polygons. Each polygon is then added to the batch. + * + * The path is always automatically closed because it's filled. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchFillPath + * @since 3.12.0 + * + * @param {array} path - Collection of points that represent the path. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchFillPath: function (path, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var length = path.length; + var polygonCache = this.polygonCache; + var polygonIndexArray; + var point; + + var tintTL = this.fillTint.TL; + var tintTR = this.fillTint.TR; + var tintBL = this.fillTint.BL; + var tintEffect = this.tintEffect; + + for (var pathIndex = 0; pathIndex < length; ++pathIndex) + { + point = path[pathIndex]; + polygonCache.push(point.x, point.y); + } + + polygonIndexArray = Earcut(polygonCache); + length = polygonIndexArray.length; + + var frame = this.currentFrame; + + for (var index = 0; index < length; index += 3) + { + var p0 = polygonIndexArray[index + 0] * 2; + var p1 = polygonIndexArray[index + 1] * 2; + var p2 = polygonIndexArray[index + 2] * 2; + + var x0 = polygonCache[p0 + 0]; + var y0 = polygonCache[p0 + 1]; + var x1 = polygonCache[p1 + 0]; + var y1 = polygonCache[p1 + 1]; + var x2 = polygonCache[p2 + 0]; + var y2 = polygonCache[p2 + 1]; + + var tx0 = calcMatrix.getX(x0, y0); + var ty0 = calcMatrix.getY(x0, y0); + + var tx1 = calcMatrix.getX(x1, y1); + var ty1 = calcMatrix.getY(x1, y1); + + var tx2 = calcMatrix.getX(x2, y2); + var ty2 = calcMatrix.getY(x2, y2); + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect); + } + + polygonCache.length = 0; + }, + + /** + * Adds the given path to the vertex batch for rendering. + * + * It works by taking the array of path data and calling `batchLine` for each section + * of the path. + * + * The path is optionally closed at the end. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchStrokePath + * @since 3.12.0 + * + * @param {array} path - Collection of points that represent the path. + * @param {number} lineWidth - The width of the line segments in pixels. + * @param {boolean} pathOpen - Indicates if the path should be closed or left open. + * @param {Phaser.GameObjects.Components.TransformMatrix} currentMatrix - The current transform. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform. + */ + batchStrokePath: function (path, lineWidth, pathOpen, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + // Reset the closePath booleans + this.prevQuad[4] = 0; + this.firstQuad[4] = 0; + + var pathLength = path.length - 1; + + for (var pathIndex = 0; pathIndex < pathLength; pathIndex++) + { + var point0 = path[pathIndex]; + var point1 = path[pathIndex + 1]; + + this.batchLine( + point0.x, + point0.y, + point1.x, + point1.y, + point0.width / 2, + point1.width / 2, + lineWidth, + pathIndex, + !pathOpen && (pathIndex === pathLength - 1), + currentMatrix, + parentMatrix + ); + } + }, + + /** + * Creates a quad and adds it to the vertex batch based on the given line values. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline#batchLine + * @since 3.12.0 + * + * @param {number} ax - X coordinate to the start of the line + * @param {number} ay - Y coordinate to the start of the line + * @param {number} bx - X coordinate to the end of the line + * @param {number} by - Y coordinate to the end of the line + * @param {number} aLineWidth - Width of the start of the line + * @param {number} bLineWidth - Width of the end of the line + * @param {Float32Array} currentMatrix - Parent matrix, generally used by containers + */ + batchLine: function (ax, ay, bx, by, aLineWidth, bLineWidth, lineWidth, index, closePath, currentMatrix, parentMatrix) + { + this.renderer.setPipeline(this); + + var calcMatrix = this._tempMatrix3; + + // Multiply and store result in calcMatrix, only if the parentMatrix is set, otherwise we'll use whatever values are already in the calcMatrix + if (parentMatrix) + { + parentMatrix.multiply(currentMatrix, calcMatrix); + } + + var dx = bx - ax; + var dy = by - ay; + + var len = Math.sqrt(dx * dx + dy * dy); + var al0 = aLineWidth * (by - ay) / len; + var al1 = aLineWidth * (ax - bx) / len; + var bl0 = bLineWidth * (by - ay) / len; + var bl1 = bLineWidth * (ax - bx) / len; + + var lx0 = bx - bl0; + var ly0 = by - bl1; + var lx1 = ax - al0; + var ly1 = ay - al1; + var lx2 = bx + bl0; + var ly2 = by + bl1; + var lx3 = ax + al0; + var ly3 = ay + al1; + + // tx0 = bottom right + var brX = calcMatrix.getX(lx0, ly0); + var brY = calcMatrix.getY(lx0, ly0); + + // tx1 = bottom left + var blX = calcMatrix.getX(lx1, ly1); + var blY = calcMatrix.getY(lx1, ly1); + + // tx2 = top right + var trX = calcMatrix.getX(lx2, ly2); + var trY = calcMatrix.getY(lx2, ly2); + + // tx3 = top left + var tlX = calcMatrix.getX(lx3, ly3); + var tlY = calcMatrix.getY(lx3, ly3); + + var tint = this.strokeTint; + var tintEffect = this.tintEffect; + + var tintTL = tint.TL; + var tintTR = tint.TR; + var tintBL = tint.BL; + var tintBR = tint.BR; + + var frame = this.currentFrame; + + var u0 = frame.u0; + var v0 = frame.v0; + var u1 = frame.u1; + var v1 = frame.v1; + + // TL, BL, BR, TR + this.batchQuad(tlX, tlY, blX, blY, brX, brY, trX, trY, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); + + if (lineWidth <= 2) + { + // No point doing a linejoin if the line isn't thick enough + return; + } + + var prev = this.prevQuad; + var first = this.firstQuad; + + if (index > 0 && prev[4]) + { + this.batchQuad(tlX, tlY, blX, blY, prev[0], prev[1], prev[2], prev[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); + } + else + { + first[0] = tlX; + first[1] = tlY; + first[2] = blX; + first[3] = blY; + first[4] = 1; + } + + if (closePath && first[4]) + { + // Add a join for the final path segment + this.batchQuad(brX, brY, trX, trY, first[0], first[1], first[2], first[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); + } + else + { + // Store it + + prev[0] = brX; + prev[1] = brY; + prev[2] = trX; + prev[3] = trY; + prev[4] = 1; + } + } + +}); + +module.exports = TextureTintPipeline; diff --git a/src/renderer/webgl/pipelines/TextureTintStripPipeline.js b/src/renderer/webgl/pipelines/TextureTintStripPipeline.js index fe2f2febc..a95f79975 100644 --- a/src/renderer/webgl/pipelines/TextureTintStripPipeline.js +++ b/src/renderer/webgl/pipelines/TextureTintStripPipeline.js @@ -1,404 +1,404 @@ -/** - * @author Richard Davey - * @author Felipe Alfonso <@bitnenfer> - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../../utils/Class'); -var GetFastValue = require('../../../utils/object/GetFastValue'); -var ModelViewProjection = require('./components/ModelViewProjection'); -var ShaderSourceFS = require('../shaders/TextureTint-frag.js'); -var ShaderSourceVS = require('../shaders/TextureTint-vert.js'); -var TransformMatrix = require('../../../gameobjects/components/TransformMatrix'); -var WebGLPipeline = require('../WebGLPipeline'); - -/** - * @classdesc - * TextureTintStripPipeline implements the rendering infrastructure - * for displaying textured objects - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - * @class TextureTintStripPipeline - * @extends Phaser.Renderer.WebGL.WebGLPipeline - * @memberof Phaser.Renderer.WebGL.Pipelines - * @constructor - * @since 3.23.0 - * - * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. - */ -var TextureTintStripPipeline = new Class({ - - Extends: WebGLPipeline, - - Mixins: [ - ModelViewProjection - ], - - initialize: - - function TextureTintStripPipeline (config) - { - var rendererConfig = config.renderer.config; - - // Vertex Size = attribute size added together (2 + 2 + 1 + 4) - - WebGLPipeline.call(this, { - game: config.game, - renderer: config.renderer, - gl: config.renderer.gl, - topology: config.renderer.gl.TRIANGLE_STRIP, - vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), - fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), - vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), - vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), - attributes: [ - { - name: 'inPosition', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: 0 - }, - { - name: 'inTexCoord', - size: 2, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 2 - }, - { - name: 'inTintEffect', - size: 1, - type: config.renderer.gl.FLOAT, - normalized: false, - offset: Float32Array.BYTES_PER_ELEMENT * 4 - }, - { - name: 'inTint', - size: 4, - type: config.renderer.gl.UNSIGNED_BYTE, - normalized: true, - offset: Float32Array.BYTES_PER_ELEMENT * 5 - } - ] - }); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewF32 - * @type {Float32Array} - * @since 3.23.0 - */ - this.vertexViewF32 = new Float32Array(this.vertexData); - - /** - * Uint32 view of the array buffer containing the pipeline's vertices. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewU32 - * @type {Uint32Array} - * @since 3.23.0 - */ - this.vertexViewU32 = new Uint32Array(this.vertexData); - - /** - * Size of the batch. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#maxQuads - * @type {integer} - * @since 3.23.0 - */ - this.maxQuads = rendererConfig.batchSize; - - /** - * Collection of batch information - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#batches - * @type {array} - * @since 3.23.0 - */ - this.batches = []; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix1 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix1 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix2 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix2 = new TransformMatrix(); - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix3 - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.23.0 - */ - this._tempMatrix3 = new TransformMatrix(); - - this.mvpInit(); - }, - - /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#onBind - * @since 3.23.0 - * - * @return {this} This WebGLPipeline instance. - */ - onBind: function () - { - WebGLPipeline.prototype.onBind.call(this); - - this.mvpUpdate(); - - return this; - }, - - /** - * Resizes this pipeline and updates the projection. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#resize - * @since 3.23.0 - * - * @param {number} width - The new width. - * @param {number} height - The new height. - * @param {number} resolution - The resolution. - * - * @return {this} This WebGLPipeline instance. - */ - resize: function (width, height, resolution) - { - WebGLPipeline.prototype.resize.call(this, width, height, resolution); - - this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); - - return this; - }, - - /** - * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#setTexture2D - * @since 3.23.0 - * - * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. - * - * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline} This pipeline instance. - */ - setTexture2D: function (texture, unit) - { - if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } - if (unit === undefined) { unit = 0; } - - if (this.requireTextureBatch(texture, unit)) - { - this.pushBatch(texture, unit); - } - - return this; - }, - - /** - * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#requireTextureBatch - * @since 3.23.0 - * - * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param {integer} unit - Texture unit to which the texture needs to be bound. - * - * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. - */ - requireTextureBatch: function (texture, unit) - { - var batches = this.batches; - var batchLength = batches.length; - - if (batchLength > 0) - { - // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property - var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; - - return !(currentTexture === texture); - } - - return true; - }, - - /** - * Creates a new batch object and pushes it to a batch array. - * The batch object contains information relevant to the current - * vertex batch like the offset in the vertex buffer, vertex count and - * the textures used by that batch. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#pushBatch - * @since 3.23.0 - * - * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. - * @param {integer} unit - Texture unit to which the texture needs to be bound. - */ - pushBatch: function (texture, unit) - { - if (unit === 0) - { - this.batches.push({ - first: this.vertexCount, - texture: texture, - textures: [] - }); - } - else - { - var textures = []; - - textures[unit - 1] = texture; - - this.batches.push({ - first: this.vertexCount, - texture: null, - textures: textures - }); - } - }, - - /** - * Uploads the vertex data and emits a draw call for the current batch of vertices. - * - * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#flush - * @since 3.23.0 - * - * @return {this} This WebGLPipeline instance. - */ - flush: function () - { - if (this.flushLocked) - { - return this; - } - - this.flushLocked = true; - - var gl = this.gl; - var vertexCount = this.vertexCount; - var topology = this.topology; - var vertexSize = this.vertexSize; - var renderer = this.renderer; - - var batches = this.batches; - var batchCount = batches.length; - var batchVertexCount = 0; - var batch = null; - var batchNext; - var textureIndex; - var nTexture; - - if (batchCount === 0 || vertexCount === 0) - { - this.flushLocked = false; - - return this; - } - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); - - // Process the TEXTURE BATCHES - - for (var index = 0; index < batchCount - 1; index++) - { - batch = batches[index]; - batchNext = batches[index + 1]; - - // Multi-texture check (for non-zero texture units) - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; - - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } - - gl.activeTexture(gl.TEXTURE0); - } - - batchVertexCount = batchNext.first - batch.first; - - // Bail out if texture property is null (i.e. if a texture unit > 0) - if (batch.texture === null || batchVertexCount <= 0) - { - continue; - } - - renderer.setTexture2D(batch.texture, 0, false); - - gl.drawArrays(topology, batch.first, batchVertexCount); - } - - // Left over data - batch = batches[batchCount - 1]; - - // Multi-texture check (for non-zero texture units) - - if (batch.textures.length > 0) - { - for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) - { - nTexture = batch.textures[textureIndex]; - - if (nTexture) - { - renderer.setTexture2D(nTexture, 1 + textureIndex, false); - } - } - - gl.activeTexture(gl.TEXTURE0); - } - - batchVertexCount = vertexCount - batch.first; - - if (batch.texture && batchVertexCount > 0) - { - renderer.setTexture2D(batch.texture, 0, false); - - gl.drawArrays(topology, batch.first, batchVertexCount); - } - - this.vertexCount = 0; - - batches.length = 0; - - this.flushLocked = false; - - return this; - } - -}); - -module.exports = TextureTintStripPipeline; +/** + * @author Richard Davey + * @author Felipe Alfonso <@bitnenfer> + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../../utils/Class'); +var GetFastValue = require('../../../utils/object/GetFastValue'); +var ModelViewProjection = require('./components/ModelViewProjection'); +var ShaderSourceFS = require('../shaders/TextureTint-frag.js'); +var ShaderSourceVS = require('../shaders/TextureTint-vert.js'); +var TransformMatrix = require('../../../gameobjects/components/TransformMatrix'); +var WebGLPipeline = require('../WebGLPipeline'); + +/** + * @classdesc + * TextureTintStripPipeline implements the rendering infrastructure + * for displaying textured objects + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * + * @class TextureTintStripPipeline + * @extends Phaser.Renderer.WebGL.WebGLPipeline + * @memberof Phaser.Renderer.WebGL.Pipelines + * @constructor + * @since 3.23.0 + * + * @param {object} config - The configuration options for this Texture Tint Pipeline, as described above. + */ +var TextureTintStripPipeline = new Class({ + + Extends: WebGLPipeline, + + Mixins: [ + ModelViewProjection + ], + + initialize: + + function TextureTintStripPipeline (config) + { + var rendererConfig = config.renderer.config; + + // Vertex Size = attribute size added together (2 + 2 + 1 + 4) + + WebGLPipeline.call(this, { + game: config.game, + renderer: config.renderer, + gl: config.renderer.gl, + topology: config.renderer.gl.TRIANGLE_STRIP, + vertShader: GetFastValue(config, 'vertShader', ShaderSourceVS), + fragShader: GetFastValue(config, 'fragShader', ShaderSourceFS), + vertexCapacity: GetFastValue(config, 'vertexCapacity', 6 * rendererConfig.batchSize), + vertexSize: GetFastValue(config, 'vertexSize', Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), + attributes: [ + { + name: 'inPosition', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: 0 + }, + { + name: 'inTexCoord', + size: 2, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: Float32Array.BYTES_PER_ELEMENT * 2 + }, + { + name: 'inTintEffect', + size: 1, + type: config.renderer.gl.FLOAT, + normalized: false, + offset: Float32Array.BYTES_PER_ELEMENT * 4 + }, + { + name: 'inTint', + size: 4, + type: config.renderer.gl.UNSIGNED_BYTE, + normalized: true, + offset: Float32Array.BYTES_PER_ELEMENT * 5 + } + ] + }); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewF32 + * @type {Float32Array} + * @since 3.23.0 + */ + this.vertexViewF32 = new Float32Array(this.vertexData); + + /** + * Uint32 view of the array buffer containing the pipeline's vertices. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#vertexViewU32 + * @type {Uint32Array} + * @since 3.23.0 + */ + this.vertexViewU32 = new Uint32Array(this.vertexData); + + /** + * Size of the batch. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#maxQuads + * @type {integer} + * @since 3.23.0 + */ + this.maxQuads = rendererConfig.batchSize; + + /** + * Collection of batch information + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#batches + * @type {array} + * @since 3.23.0 + */ + this.batches = []; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix1 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.23.0 + */ + this._tempMatrix1 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix2 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.23.0 + */ + this._tempMatrix2 = new TransformMatrix(); + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#_tempMatrix3 + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.23.0 + */ + this._tempMatrix3 = new TransformMatrix(); + + this.mvpInit(); + }, + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#onBind + * @since 3.23.0 + * + * @return {this} This WebGLPipeline instance. + */ + onBind: function () + { + WebGLPipeline.prototype.onBind.call(this); + + this.mvpUpdate(); + + return this; + }, + + /** + * Resizes this pipeline and updates the projection. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#resize + * @since 3.23.0 + * + * @param {number} width - The new width. + * @param {number} height - The new height. + * @param {number} resolution - The resolution. + * + * @return {this} This WebGLPipeline instance. + */ + resize: function (width, height, resolution) + { + WebGLPipeline.prototype.resize.call(this, width, height, resolution); + + this.projOrtho(0, this.width, this.height, 0, -1000.0, 1000.0); + + return this; + }, + + /** + * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#setTexture2D + * @since 3.23.0 + * + * @param {WebGLTexture} [texture] - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param {integer} [unit=0] - Texture unit to which the texture needs to be bound. + * + * @return {Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline} This pipeline instance. + */ + setTexture2D: function (texture, unit) + { + if (texture === undefined) { texture = this.renderer.blankTexture.glTexture; } + if (unit === undefined) { unit = 0; } + + if (this.requireTextureBatch(texture, unit)) + { + this.pushBatch(texture, unit); + } + + return this; + }, + + /** + * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#requireTextureBatch + * @since 3.23.0 + * + * @param {WebGLTexture} texture - WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param {integer} unit - Texture unit to which the texture needs to be bound. + * + * @return {boolean} `true` if the pipeline needs to create a new batch, otherwise `false`. + */ + requireTextureBatch: function (texture, unit) + { + var batches = this.batches; + var batchLength = batches.length; + + if (batchLength > 0) + { + // If Texture Unit specified, we get the texture from the textures array, otherwise we use the texture property + var currentTexture = (unit > 0) ? batches[batchLength - 1].textures[unit - 1] : batches[batchLength - 1].texture; + + return !(currentTexture === texture); + } + + return true; + }, + + /** + * Creates a new batch object and pushes it to a batch array. + * The batch object contains information relevant to the current + * vertex batch like the offset in the vertex buffer, vertex count and + * the textures used by that batch. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#pushBatch + * @since 3.23.0 + * + * @param {WebGLTexture} texture - Optional WebGLTexture that will be assigned to the created batch. + * @param {integer} unit - Texture unit to which the texture needs to be bound. + */ + pushBatch: function (texture, unit) + { + if (unit === 0) + { + this.batches.push({ + first: this.vertexCount, + texture: texture, + textures: [] + }); + } + else + { + var textures = []; + + textures[unit - 1] = texture; + + this.batches.push({ + first: this.vertexCount, + texture: null, + textures: textures + }); + } + }, + + /** + * Uploads the vertex data and emits a draw call for the current batch of vertices. + * + * @method Phaser.Renderer.WebGL.Pipelines.TextureTintStripPipeline#flush + * @since 3.23.0 + * + * @return {this} This WebGLPipeline instance. + */ + flush: function () + { + if (this.flushLocked) + { + return this; + } + + this.flushLocked = true; + + var gl = this.gl; + var vertexCount = this.vertexCount; + var topology = this.topology; + var vertexSize = this.vertexSize; + var renderer = this.renderer; + + var batches = this.batches; + var batchCount = batches.length; + var batchVertexCount = 0; + var batch = null; + var batchNext; + var textureIndex; + var nTexture; + + if (batchCount === 0 || vertexCount === 0) + { + this.flushLocked = false; + + return this; + } + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); + + // Process the TEXTURE BATCHES + + for (var index = 0; index < batchCount - 1; index++) + { + batch = batches[index]; + batchNext = batches[index + 1]; + + // Multi-texture check (for non-zero texture units) + if (batch.textures.length > 0) + { + for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) + { + nTexture = batch.textures[textureIndex]; + + if (nTexture) + { + renderer.setTexture2D(nTexture, 1 + textureIndex, false); + } + } + + gl.activeTexture(gl.TEXTURE0); + } + + batchVertexCount = batchNext.first - batch.first; + + // Bail out if texture property is null (i.e. if a texture unit > 0) + if (batch.texture === null || batchVertexCount <= 0) + { + continue; + } + + renderer.setTexture2D(batch.texture, 0, false); + + gl.drawArrays(topology, batch.first, batchVertexCount); + } + + // Left over data + batch = batches[batchCount - 1]; + + // Multi-texture check (for non-zero texture units) + + if (batch.textures.length > 0) + { + for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) + { + nTexture = batch.textures[textureIndex]; + + if (nTexture) + { + renderer.setTexture2D(nTexture, 1 + textureIndex, false); + } + } + + gl.activeTexture(gl.TEXTURE0); + } + + batchVertexCount = vertexCount - batch.first; + + if (batch.texture && batchVertexCount > 0) + { + renderer.setTexture2D(batch.texture, 0, false); + + gl.drawArrays(topology, batch.first, batchVertexCount); + } + + this.vertexCount = 0; + + batches.length = 0; + + this.flushLocked = false; + + return this; + } + +}); + +module.exports = TextureTintStripPipeline; diff --git a/src/renderer/webgl/pipelines/components/ModelViewProjection.js b/src/renderer/webgl/pipelines/components/ModelViewProjection.js index df36a1cdd..8e64ca7ce 100644 --- a/src/renderer/webgl/pipelines/components/ModelViewProjection.js +++ b/src/renderer/webgl/pipelines/components/ModelViewProjection.js @@ -1,744 +1,744 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Implements a model view projection matrices. - * Pipelines can implement this for doing 2D and 3D rendering. - * - * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection - * @since 3.0.0 - */ -var ModelViewProjection = { - - /** - * Dirty flag for checking if model matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - modelMatrixDirty: false, - - /** - * Dirty flag for checking if view matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - viewMatrixDirty: false, - - /** - * Dirty flag for checking if projection matrix needs to be updated on GPU. - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty - * @type {boolean} - * @since 3.0.0 - */ - projectionMatrixDirty: false, - - /** - * Model matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - modelMatrix: null, - - /** - * View matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - viewMatrix: null, - - /** - * Projection matrix - * - * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix - * @type {?Float32Array} - * @since 3.0.0 - */ - projectionMatrix: null, - - /** - * Initializes MVP matrices with an identity matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit - * @since 3.0.0 - */ - mvpInit: function () - { - this.modelMatrixDirty = true; - this.viewMatrixDirty = true; - this.projectionMatrixDirty = true; - - this.modelMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - this.viewMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - this.projectionMatrix = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ]); - - return this; - }, - - /** - * If dirty flags are set then the matrices are uploaded to the GPU. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate - * @since 3.0.0 - */ - mvpUpdate: function () - { - var program = this.program; - - if (this.modelMatrixDirty) - { - this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); - this.modelMatrixDirty = false; - } - - if (this.viewMatrixDirty) - { - this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); - this.viewMatrixDirty = false; - } - - if (this.projectionMatrixDirty) - { - this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); - this.projectionMatrixDirty = false; - } - - return this; - }, - - /** - * Loads an identity matrix to the model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity - * @since 3.0.0 - */ - modelIdentity: function () - { - var modelMatrix = this.modelMatrix; - - modelMatrix[0] = 1; - modelMatrix[1] = 0; - modelMatrix[2] = 0; - modelMatrix[3] = 0; - modelMatrix[4] = 0; - modelMatrix[5] = 1; - modelMatrix[6] = 0; - modelMatrix[7] = 0; - modelMatrix[8] = 0; - modelMatrix[9] = 0; - modelMatrix[10] = 1; - modelMatrix[11] = 0; - modelMatrix[12] = 0; - modelMatrix[13] = 0; - modelMatrix[14] = 0; - modelMatrix[15] = 1; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Scale model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - modelScale: function (x, y, z) - { - var modelMatrix = this.modelMatrix; - - modelMatrix[0] = modelMatrix[0] * x; - modelMatrix[1] = modelMatrix[1] * x; - modelMatrix[2] = modelMatrix[2] * x; - modelMatrix[3] = modelMatrix[3] * x; - modelMatrix[4] = modelMatrix[4] * y; - modelMatrix[5] = modelMatrix[5] * y; - modelMatrix[6] = modelMatrix[6] * y; - modelMatrix[7] = modelMatrix[7] * y; - modelMatrix[8] = modelMatrix[8] * z; - modelMatrix[9] = modelMatrix[9] * z; - modelMatrix[10] = modelMatrix[10] * z; - modelMatrix[11] = modelMatrix[11] * z; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Translate model matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - modelTranslate: function (x, y, z) - { - var modelMatrix = this.modelMatrix; - - modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; - modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; - modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; - modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the X axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateX: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a10 = modelMatrix[4]; - var a11 = modelMatrix[5]; - var a12 = modelMatrix[6]; - var a13 = modelMatrix[7]; - var a20 = modelMatrix[8]; - var a21 = modelMatrix[9]; - var a22 = modelMatrix[10]; - var a23 = modelMatrix[11]; - - modelMatrix[4] = a10 * c + a20 * s; - modelMatrix[5] = a11 * c + a21 * s; - modelMatrix[6] = a12 * c + a22 * s; - modelMatrix[7] = a13 * c + a23 * s; - modelMatrix[8] = a20 * c - a10 * s; - modelMatrix[9] = a21 * c - a11 * s; - modelMatrix[10] = a22 * c - a12 * s; - modelMatrix[11] = a23 * c - a13 * s; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the Y axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateY: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = modelMatrix[0]; - var a01 = modelMatrix[1]; - var a02 = modelMatrix[2]; - var a03 = modelMatrix[3]; - var a20 = modelMatrix[8]; - var a21 = modelMatrix[9]; - var a22 = modelMatrix[10]; - var a23 = modelMatrix[11]; - - modelMatrix[0] = a00 * c - a20 * s; - modelMatrix[1] = a01 * c - a21 * s; - modelMatrix[2] = a02 * c - a22 * s; - modelMatrix[3] = a03 * c - a23 * s; - modelMatrix[8] = a00 * s + a20 * c; - modelMatrix[9] = a01 * s + a21 * c; - modelMatrix[10] = a02 * s + a22 * c; - modelMatrix[11] = a03 * s + a23 * c; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Rotates the model matrix in the Z axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - modelRotateZ: function (radians) - { - var modelMatrix = this.modelMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = modelMatrix[0]; - var a01 = modelMatrix[1]; - var a02 = modelMatrix[2]; - var a03 = modelMatrix[3]; - var a10 = modelMatrix[4]; - var a11 = modelMatrix[5]; - var a12 = modelMatrix[6]; - var a13 = modelMatrix[7]; - - modelMatrix[0] = a00 * c + a10 * s; - modelMatrix[1] = a01 * c + a11 * s; - modelMatrix[2] = a02 * c + a12 * s; - modelMatrix[3] = a03 * c + a13 * s; - modelMatrix[4] = a10 * c - a00 * s; - modelMatrix[5] = a11 * c - a01 * s; - modelMatrix[6] = a12 * c - a02 * s; - modelMatrix[7] = a13 * c - a03 * s; - - this.modelMatrixDirty = true; - - return this; - }, - - /** - * Loads identity matrix into the view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity - * @since 3.0.0 - * - * @return {this} This Model View Projection. - */ - viewIdentity: function () - { - var viewMatrix = this.viewMatrix; - - viewMatrix[0] = 1; - viewMatrix[1] = 0; - viewMatrix[2] = 0; - viewMatrix[3] = 0; - viewMatrix[4] = 0; - viewMatrix[5] = 1; - viewMatrix[6] = 0; - viewMatrix[7] = 0; - viewMatrix[8] = 0; - viewMatrix[9] = 0; - viewMatrix[10] = 1; - viewMatrix[11] = 0; - viewMatrix[12] = 0; - viewMatrix[13] = 0; - viewMatrix[14] = 0; - viewMatrix[15] = 1; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Scales view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - viewScale: function (x, y, z) - { - var viewMatrix = this.viewMatrix; - - viewMatrix[0] = viewMatrix[0] * x; - viewMatrix[1] = viewMatrix[1] * x; - viewMatrix[2] = viewMatrix[2] * x; - viewMatrix[3] = viewMatrix[3] * x; - viewMatrix[4] = viewMatrix[4] * y; - viewMatrix[5] = viewMatrix[5] * y; - viewMatrix[6] = viewMatrix[6] * y; - viewMatrix[7] = viewMatrix[7] * y; - viewMatrix[8] = viewMatrix[8] * z; - viewMatrix[9] = viewMatrix[9] * z; - viewMatrix[10] = viewMatrix[10] * z; - viewMatrix[11] = viewMatrix[11] * z; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Translates view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate - * @since 3.0.0 - * - * @param {number} x - The x component. - * @param {number} y - The y component. - * @param {number} z - The z component. - * - * @return {this} This Model View Projection. - */ - viewTranslate: function (x, y, z) - { - var viewMatrix = this.viewMatrix; - - viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; - viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; - viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; - viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the X axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateX: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a10 = viewMatrix[4]; - var a11 = viewMatrix[5]; - var a12 = viewMatrix[6]; - var a13 = viewMatrix[7]; - var a20 = viewMatrix[8]; - var a21 = viewMatrix[9]; - var a22 = viewMatrix[10]; - var a23 = viewMatrix[11]; - - viewMatrix[4] = a10 * c + a20 * s; - viewMatrix[5] = a11 * c + a21 * s; - viewMatrix[6] = a12 * c + a22 * s; - viewMatrix[7] = a13 * c + a23 * s; - viewMatrix[8] = a20 * c - a10 * s; - viewMatrix[9] = a21 * c - a11 * s; - viewMatrix[10] = a22 * c - a12 * s; - viewMatrix[11] = a23 * c - a13 * s; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the Y axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateY: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = viewMatrix[0]; - var a01 = viewMatrix[1]; - var a02 = viewMatrix[2]; - var a03 = viewMatrix[3]; - var a20 = viewMatrix[8]; - var a21 = viewMatrix[9]; - var a22 = viewMatrix[10]; - var a23 = viewMatrix[11]; - - viewMatrix[0] = a00 * c - a20 * s; - viewMatrix[1] = a01 * c - a21 * s; - viewMatrix[2] = a02 * c - a22 * s; - viewMatrix[3] = a03 * c - a23 * s; - viewMatrix[8] = a00 * s + a20 * c; - viewMatrix[9] = a01 * s + a21 * c; - viewMatrix[10] = a02 * s + a22 * c; - viewMatrix[11] = a03 * s + a23 * c; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Rotates view matrix in the Z axis. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ - * @since 3.0.0 - * - * @param {number} radians - The amount to rotate by. - * - * @return {this} This Model View Projection. - */ - viewRotateZ: function (radians) - { - var viewMatrix = this.viewMatrix; - var s = Math.sin(radians); - var c = Math.cos(radians); - var a00 = viewMatrix[0]; - var a01 = viewMatrix[1]; - var a02 = viewMatrix[2]; - var a03 = viewMatrix[3]; - var a10 = viewMatrix[4]; - var a11 = viewMatrix[5]; - var a12 = viewMatrix[6]; - var a13 = viewMatrix[7]; - - viewMatrix[0] = a00 * c + a10 * s; - viewMatrix[1] = a01 * c + a11 * s; - viewMatrix[2] = a02 * c + a12 * s; - viewMatrix[3] = a03 * c + a13 * s; - viewMatrix[4] = a10 * c - a00 * s; - viewMatrix[5] = a11 * c - a01 * s; - viewMatrix[6] = a12 * c - a02 * s; - viewMatrix[7] = a13 * c - a03 * s; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D - * @since 3.0.0 - * - * @param {Float32Array} matrix2D - The Matrix2D. - * - * @return {this} This Model View Projection. - */ - viewLoad2D: function (matrix2D) - { - var vm = this.viewMatrix; - - vm[0] = matrix2D[0]; - vm[1] = matrix2D[1]; - vm[2] = 0.0; - vm[3] = 0.0; - vm[4] = matrix2D[2]; - vm[5] = matrix2D[3]; - vm[6] = 0.0; - vm[7] = 0.0; - vm[8] = matrix2D[4]; - vm[9] = matrix2D[5]; - vm[10] = 1.0; - vm[11] = 0.0; - vm[12] = 0.0; - vm[13] = 0.0; - vm[14] = 0.0; - vm[15] = 1.0; - - this.viewMatrixDirty = true; - - return this; - }, - - - /** - * Copies a 4x4 matrix into the view matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad - * @since 3.0.0 - * - * @param {Float32Array} matrix - The Matrix2D. - * - * @return {this} This Model View Projection. - */ - viewLoad: function (matrix) - { - var vm = this.viewMatrix; - - vm[0] = matrix[0]; - vm[1] = matrix[1]; - vm[2] = matrix[2]; - vm[3] = matrix[3]; - vm[4] = matrix[4]; - vm[5] = matrix[5]; - vm[6] = matrix[6]; - vm[7] = matrix[7]; - vm[8] = matrix[8]; - vm[9] = matrix[9]; - vm[10] = matrix[10]; - vm[11] = matrix[11]; - vm[12] = matrix[12]; - vm[13] = matrix[13]; - vm[14] = matrix[14]; - vm[15] = matrix[15]; - - this.viewMatrixDirty = true; - - return this; - }, - - /** - * Loads identity matrix into the projection matrix. - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity - * @since 3.0.0 - * - * @return {this} This Model View Projection. - */ - projIdentity: function () - { - var projectionMatrix = this.projectionMatrix; - - projectionMatrix[0] = 1; - projectionMatrix[1] = 0; - projectionMatrix[2] = 0; - projectionMatrix[3] = 0; - projectionMatrix[4] = 0; - projectionMatrix[5] = 1; - projectionMatrix[6] = 0; - projectionMatrix[7] = 0; - projectionMatrix[8] = 0; - projectionMatrix[9] = 0; - projectionMatrix[10] = 1; - projectionMatrix[11] = 0; - projectionMatrix[12] = 0; - projectionMatrix[13] = 0; - projectionMatrix[14] = 0; - projectionMatrix[15] = 1; - - this.projectionMatrixDirty = true; - - return this; - }, - - /** - * Sets up an orthographic projection matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho - * @since 3.0.0 - * - * @param {number} left - The left value. - * @param {number} right - The right value. - * @param {number} bottom - The bottom value. - * @param {number} top - The top value. - * @param {number} near - The near value. - * @param {number} far - The far value. - * - * @return {this} This Model View Projection. - */ - projOrtho: function (left, right, bottom, top, near, far) - { - var projectionMatrix = this.projectionMatrix; - var leftRight = 1.0 / (left - right); - var bottomTop = 1.0 / (bottom - top); - var nearFar = 1.0 / (near - far); - - projectionMatrix[0] = -2.0 * leftRight; - projectionMatrix[1] = 0.0; - projectionMatrix[2] = 0.0; - projectionMatrix[3] = 0.0; - projectionMatrix[4] = 0.0; - projectionMatrix[5] = -2.0 * bottomTop; - projectionMatrix[6] = 0.0; - projectionMatrix[7] = 0.0; - projectionMatrix[8] = 0.0; - projectionMatrix[9] = 0.0; - projectionMatrix[10] = 2.0 * nearFar; - projectionMatrix[11] = 0.0; - projectionMatrix[12] = (left + right) * leftRight; - projectionMatrix[13] = (top + bottom) * bottomTop; - projectionMatrix[14] = (far + near) * nearFar; - projectionMatrix[15] = 1.0; - - this.projectionMatrixDirty = true; - - return this; - }, - - /** - * Sets up a perspective projection matrix - * - * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp - * @since 3.0.0 - * - * @param {number} fovY - The fov value. - * @param {number} aspectRatio - The aspectRatio value. - * @param {number} near - The near value. - * @param {number} far - The far value. - * - * @return {this} This Model View Projection. - */ - projPersp: function (fovY, aspectRatio, near, far) - { - var projectionMatrix = this.projectionMatrix; - var fov = 1.0 / Math.tan(fovY / 2.0); - var nearFar = 1.0 / (near - far); - - projectionMatrix[0] = fov / aspectRatio; - projectionMatrix[1] = 0.0; - projectionMatrix[2] = 0.0; - projectionMatrix[3] = 0.0; - projectionMatrix[4] = 0.0; - projectionMatrix[5] = fov; - projectionMatrix[6] = 0.0; - projectionMatrix[7] = 0.0; - projectionMatrix[8] = 0.0; - projectionMatrix[9] = 0.0; - projectionMatrix[10] = (far + near) * nearFar; - projectionMatrix[11] = -1.0; - projectionMatrix[12] = 0.0; - projectionMatrix[13] = 0.0; - projectionMatrix[14] = (2.0 * far * near) * nearFar; - projectionMatrix[15] = 0.0; - - this.projectionMatrixDirty = true; - - return this; - } -}; - -module.exports = ModelViewProjection; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Implements a model view projection matrices. + * Pipelines can implement this for doing 2D and 3D rendering. + * + * @namespace Phaser.Renderer.WebGL.Pipelines.ModelViewProjection + * @since 3.0.0 + */ +var ModelViewProjection = { + + /** + * Dirty flag for checking if model matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + modelMatrixDirty: false, + + /** + * Dirty flag for checking if view matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + viewMatrixDirty: false, + + /** + * Dirty flag for checking if projection matrix needs to be updated on GPU. + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrixDirty + * @type {boolean} + * @since 3.0.0 + */ + projectionMatrixDirty: false, + + /** + * Model matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + modelMatrix: null, + + /** + * View matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + viewMatrix: null, + + /** + * Projection matrix + * + * @name Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projectionMatrix + * @type {?Float32Array} + * @since 3.0.0 + */ + projectionMatrix: null, + + /** + * Initializes MVP matrices with an identity matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpInit + * @since 3.0.0 + */ + mvpInit: function () + { + this.modelMatrixDirty = true; + this.viewMatrixDirty = true; + this.projectionMatrixDirty = true; + + this.modelMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.viewMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + this.projectionMatrix = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]); + + return this; + }, + + /** + * If dirty flags are set then the matrices are uploaded to the GPU. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#mvpUpdate + * @since 3.0.0 + */ + mvpUpdate: function () + { + var program = this.program; + + if (this.modelMatrixDirty) + { + this.renderer.setMatrix4(program, 'uModelMatrix', false, this.modelMatrix); + this.modelMatrixDirty = false; + } + + if (this.viewMatrixDirty) + { + this.renderer.setMatrix4(program, 'uViewMatrix', false, this.viewMatrix); + this.viewMatrixDirty = false; + } + + if (this.projectionMatrixDirty) + { + this.renderer.setMatrix4(program, 'uProjectionMatrix', false, this.projectionMatrix); + this.projectionMatrixDirty = false; + } + + return this; + }, + + /** + * Loads an identity matrix to the model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelIdentity + * @since 3.0.0 + */ + modelIdentity: function () + { + var modelMatrix = this.modelMatrix; + + modelMatrix[0] = 1; + modelMatrix[1] = 0; + modelMatrix[2] = 0; + modelMatrix[3] = 0; + modelMatrix[4] = 0; + modelMatrix[5] = 1; + modelMatrix[6] = 0; + modelMatrix[7] = 0; + modelMatrix[8] = 0; + modelMatrix[9] = 0; + modelMatrix[10] = 1; + modelMatrix[11] = 0; + modelMatrix[12] = 0; + modelMatrix[13] = 0; + modelMatrix[14] = 0; + modelMatrix[15] = 1; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Scale model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelScale: function (x, y, z) + { + var modelMatrix = this.modelMatrix; + + modelMatrix[0] = modelMatrix[0] * x; + modelMatrix[1] = modelMatrix[1] * x; + modelMatrix[2] = modelMatrix[2] * x; + modelMatrix[3] = modelMatrix[3] * x; + modelMatrix[4] = modelMatrix[4] * y; + modelMatrix[5] = modelMatrix[5] * y; + modelMatrix[6] = modelMatrix[6] * y; + modelMatrix[7] = modelMatrix[7] * y; + modelMatrix[8] = modelMatrix[8] * z; + modelMatrix[9] = modelMatrix[9] * z; + modelMatrix[10] = modelMatrix[10] * z; + modelMatrix[11] = modelMatrix[11] * z; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Translate model matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + modelTranslate: function (x, y, z) + { + var modelMatrix = this.modelMatrix; + + modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; + modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; + modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; + modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateX: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; + + modelMatrix[4] = a10 * c + a20 * s; + modelMatrix[5] = a11 * c + a21 * s; + modelMatrix[6] = a12 * c + a22 * s; + modelMatrix[7] = a13 * c + a23 * s; + modelMatrix[8] = a20 * c - a10 * s; + modelMatrix[9] = a21 * c - a11 * s; + modelMatrix[10] = a22 * c - a12 * s; + modelMatrix[11] = a23 * c - a13 * s; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateY: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a20 = modelMatrix[8]; + var a21 = modelMatrix[9]; + var a22 = modelMatrix[10]; + var a23 = modelMatrix[11]; + + modelMatrix[0] = a00 * c - a20 * s; + modelMatrix[1] = a01 * c - a21 * s; + modelMatrix[2] = a02 * c - a22 * s; + modelMatrix[3] = a03 * c - a23 * s; + modelMatrix[8] = a00 * s + a20 * c; + modelMatrix[9] = a01 * s + a21 * c; + modelMatrix[10] = a02 * s + a22 * c; + modelMatrix[11] = a03 * s + a23 * c; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Rotates the model matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#modelRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + modelRotateZ: function (radians) + { + var modelMatrix = this.modelMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = modelMatrix[0]; + var a01 = modelMatrix[1]; + var a02 = modelMatrix[2]; + var a03 = modelMatrix[3]; + var a10 = modelMatrix[4]; + var a11 = modelMatrix[5]; + var a12 = modelMatrix[6]; + var a13 = modelMatrix[7]; + + modelMatrix[0] = a00 * c + a10 * s; + modelMatrix[1] = a01 * c + a11 * s; + modelMatrix[2] = a02 * c + a12 * s; + modelMatrix[3] = a03 * c + a13 * s; + modelMatrix[4] = a10 * c - a00 * s; + modelMatrix[5] = a11 * c - a01 * s; + modelMatrix[6] = a12 * c - a02 * s; + modelMatrix[7] = a13 * c - a03 * s; + + this.modelMatrixDirty = true; + + return this; + }, + + /** + * Loads identity matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + viewIdentity: function () + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = 1; + viewMatrix[1] = 0; + viewMatrix[2] = 0; + viewMatrix[3] = 0; + viewMatrix[4] = 0; + viewMatrix[5] = 1; + viewMatrix[6] = 0; + viewMatrix[7] = 0; + viewMatrix[8] = 0; + viewMatrix[9] = 0; + viewMatrix[10] = 1; + viewMatrix[11] = 0; + viewMatrix[12] = 0; + viewMatrix[13] = 0; + viewMatrix[14] = 0; + viewMatrix[15] = 1; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Scales view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewScale + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewScale: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[0] = viewMatrix[0] * x; + viewMatrix[1] = viewMatrix[1] * x; + viewMatrix[2] = viewMatrix[2] * x; + viewMatrix[3] = viewMatrix[3] * x; + viewMatrix[4] = viewMatrix[4] * y; + viewMatrix[5] = viewMatrix[5] * y; + viewMatrix[6] = viewMatrix[6] * y; + viewMatrix[7] = viewMatrix[7] * y; + viewMatrix[8] = viewMatrix[8] * z; + viewMatrix[9] = viewMatrix[9] * z; + viewMatrix[10] = viewMatrix[10] * z; + viewMatrix[11] = viewMatrix[11] * z; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Translates view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewTranslate + * @since 3.0.0 + * + * @param {number} x - The x component. + * @param {number} y - The y component. + * @param {number} z - The z component. + * + * @return {this} This Model View Projection. + */ + viewTranslate: function (x, y, z) + { + var viewMatrix = this.viewMatrix; + + viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; + viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; + viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; + viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the X axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateX + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateX: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[4] = a10 * c + a20 * s; + viewMatrix[5] = a11 * c + a21 * s; + viewMatrix[6] = a12 * c + a22 * s; + viewMatrix[7] = a13 * c + a23 * s; + viewMatrix[8] = a20 * c - a10 * s; + viewMatrix[9] = a21 * c - a11 * s; + viewMatrix[10] = a22 * c - a12 * s; + viewMatrix[11] = a23 * c - a13 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Y axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateY + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateY: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a20 = viewMatrix[8]; + var a21 = viewMatrix[9]; + var a22 = viewMatrix[10]; + var a23 = viewMatrix[11]; + + viewMatrix[0] = a00 * c - a20 * s; + viewMatrix[1] = a01 * c - a21 * s; + viewMatrix[2] = a02 * c - a22 * s; + viewMatrix[3] = a03 * c - a23 * s; + viewMatrix[8] = a00 * s + a20 * c; + viewMatrix[9] = a01 * s + a21 * c; + viewMatrix[10] = a02 * s + a22 * c; + viewMatrix[11] = a03 * s + a23 * c; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Rotates view matrix in the Z axis. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewRotateZ + * @since 3.0.0 + * + * @param {number} radians - The amount to rotate by. + * + * @return {this} This Model View Projection. + */ + viewRotateZ: function (radians) + { + var viewMatrix = this.viewMatrix; + var s = Math.sin(radians); + var c = Math.cos(radians); + var a00 = viewMatrix[0]; + var a01 = viewMatrix[1]; + var a02 = viewMatrix[2]; + var a03 = viewMatrix[3]; + var a10 = viewMatrix[4]; + var a11 = viewMatrix[5]; + var a12 = viewMatrix[6]; + var a13 = viewMatrix[7]; + + viewMatrix[0] = a00 * c + a10 * s; + viewMatrix[1] = a01 * c + a11 * s; + viewMatrix[2] = a02 * c + a12 * s; + viewMatrix[3] = a03 * c + a13 * s; + viewMatrix[4] = a10 * c - a00 * s; + viewMatrix[5] = a11 * c - a01 * s; + viewMatrix[6] = a12 * c - a02 * s; + viewMatrix[7] = a13 * c - a03 * s; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad2D + * @since 3.0.0 + * + * @param {Float32Array} matrix2D - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad2D: function (matrix2D) + { + var vm = this.viewMatrix; + + vm[0] = matrix2D[0]; + vm[1] = matrix2D[1]; + vm[2] = 0.0; + vm[3] = 0.0; + vm[4] = matrix2D[2]; + vm[5] = matrix2D[3]; + vm[6] = 0.0; + vm[7] = 0.0; + vm[8] = matrix2D[4]; + vm[9] = matrix2D[5]; + vm[10] = 1.0; + vm[11] = 0.0; + vm[12] = 0.0; + vm[13] = 0.0; + vm[14] = 0.0; + vm[15] = 1.0; + + this.viewMatrixDirty = true; + + return this; + }, + + + /** + * Copies a 4x4 matrix into the view matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#viewLoad + * @since 3.0.0 + * + * @param {Float32Array} matrix - The Matrix2D. + * + * @return {this} This Model View Projection. + */ + viewLoad: function (matrix) + { + var vm = this.viewMatrix; + + vm[0] = matrix[0]; + vm[1] = matrix[1]; + vm[2] = matrix[2]; + vm[3] = matrix[3]; + vm[4] = matrix[4]; + vm[5] = matrix[5]; + vm[6] = matrix[6]; + vm[7] = matrix[7]; + vm[8] = matrix[8]; + vm[9] = matrix[9]; + vm[10] = matrix[10]; + vm[11] = matrix[11]; + vm[12] = matrix[12]; + vm[13] = matrix[13]; + vm[14] = matrix[14]; + vm[15] = matrix[15]; + + this.viewMatrixDirty = true; + + return this; + }, + + /** + * Loads identity matrix into the projection matrix. + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projIdentity + * @since 3.0.0 + * + * @return {this} This Model View Projection. + */ + projIdentity: function () + { + var projectionMatrix = this.projectionMatrix; + + projectionMatrix[0] = 1; + projectionMatrix[1] = 0; + projectionMatrix[2] = 0; + projectionMatrix[3] = 0; + projectionMatrix[4] = 0; + projectionMatrix[5] = 1; + projectionMatrix[6] = 0; + projectionMatrix[7] = 0; + projectionMatrix[8] = 0; + projectionMatrix[9] = 0; + projectionMatrix[10] = 1; + projectionMatrix[11] = 0; + projectionMatrix[12] = 0; + projectionMatrix[13] = 0; + projectionMatrix[14] = 0; + projectionMatrix[15] = 1; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up an orthographic projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projOrtho + * @since 3.0.0 + * + * @param {number} left - The left value. + * @param {number} right - The right value. + * @param {number} bottom - The bottom value. + * @param {number} top - The top value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projOrtho: function (left, right, bottom, top, near, far) + { + var projectionMatrix = this.projectionMatrix; + var leftRight = 1.0 / (left - right); + var bottomTop = 1.0 / (bottom - top); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = -2.0 * leftRight; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = -2.0 * bottomTop; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = 2.0 * nearFar; + projectionMatrix[11] = 0.0; + projectionMatrix[12] = (left + right) * leftRight; + projectionMatrix[13] = (top + bottom) * bottomTop; + projectionMatrix[14] = (far + near) * nearFar; + projectionMatrix[15] = 1.0; + + this.projectionMatrixDirty = true; + + return this; + }, + + /** + * Sets up a perspective projection matrix + * + * @method Phaser.Renderer.WebGL.Pipelines.ModelViewProjection#projPersp + * @since 3.0.0 + * + * @param {number} fovY - The fov value. + * @param {number} aspectRatio - The aspectRatio value. + * @param {number} near - The near value. + * @param {number} far - The far value. + * + * @return {this} This Model View Projection. + */ + projPersp: function (fovY, aspectRatio, near, far) + { + var projectionMatrix = this.projectionMatrix; + var fov = 1.0 / Math.tan(fovY / 2.0); + var nearFar = 1.0 / (near - far); + + projectionMatrix[0] = fov / aspectRatio; + projectionMatrix[1] = 0.0; + projectionMatrix[2] = 0.0; + projectionMatrix[3] = 0.0; + projectionMatrix[4] = 0.0; + projectionMatrix[5] = fov; + projectionMatrix[6] = 0.0; + projectionMatrix[7] = 0.0; + projectionMatrix[8] = 0.0; + projectionMatrix[9] = 0.0; + projectionMatrix[10] = (far + near) * nearFar; + projectionMatrix[11] = -1.0; + projectionMatrix[12] = 0.0; + projectionMatrix[13] = 0.0; + projectionMatrix[14] = (2.0 * far * near) * nearFar; + projectionMatrix[15] = 0.0; + + this.projectionMatrixDirty = true; + + return this; + } +}; + +module.exports = ModelViewProjection; diff --git a/src/renderer/webgl/pipelines/index.js b/src/renderer/webgl/pipelines/index.js index 10bd15cb3..0aa6f91e3 100644 --- a/src/renderer/webgl/pipelines/index.js +++ b/src/renderer/webgl/pipelines/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Renderer.WebGL.Pipelines - */ - -module.exports = { - - BitmapMaskPipeline: require('./BitmapMaskPipeline'), - ForwardDiffuseLightPipeline: require('./ForwardDiffuseLightPipeline'), - TextureTintPipeline: require('./TextureTintPipeline'), - TextureTintStripPipeline: require('./TextureTintStripPipeline'), - ModelViewProjection: require('./components/ModelViewProjection') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Renderer.WebGL.Pipelines + */ + +module.exports = { + + BitmapMaskPipeline: require('./BitmapMaskPipeline'), + ForwardDiffuseLightPipeline: require('./ForwardDiffuseLightPipeline'), + TextureTintPipeline: require('./TextureTintPipeline'), + TextureTintStripPipeline: require('./TextureTintStripPipeline'), + ModelViewProjection: require('./components/ModelViewProjection') + +}; diff --git a/src/scale/ScaleManager.js b/src/scale/ScaleManager.js index 5f9934dad..bac2f502c 100644 --- a/src/scale/ScaleManager.js +++ b/src/scale/ScaleManager.js @@ -1,1711 +1,1711 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Class = require('../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GameEvents = require('../core/events'); -var GetInnerHeight = require('../dom/GetInnerHeight'); -var GetTarget = require('../dom/GetTarget'); -var GetScreenOrientation = require('../dom/GetScreenOrientation'); -var NOOP = require('../utils/NOOP'); -var Rectangle = require('../geom/rectangle/Rectangle'); -var Size = require('../structs/Size'); -var SnapFloor = require('../math/snap/SnapFloor'); -var Vector2 = require('../math/Vector2'); - -/** - * @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. - */ -var ScaleManager = new Class({ - - Extends: EventEmitter, - - initialize: - - function ScaleManager (game) - { - EventEmitter.call(this); - - /** - * A reference to the Phaser.Game instance. - * - * @name Phaser.Scale.ScaleManager#game - * @type {Phaser.Game} - * @readonly - * @since 3.15.0 - */ - this.game = game; - - /** - * A reference to the HTML Canvas Element that Phaser uses to render the game. - * - * @name Phaser.Scale.ScaleManager#canvas - * @type {HTMLCanvasElement} - * @since 3.16.0 - */ - this.canvas; - - /** - * The DOM bounds of the canvas element. - * - * @name Phaser.Scale.ScaleManager#canvasBounds - * @type {Phaser.Geom.Rectangle} - * @since 3.16.0 - */ - this.canvasBounds = new Rectangle(); - - /** - * The parent object of the Canvas. Often a div, or the browser window, or nothing in non-browser environments. - * - * This is set in the Game Config as the `parent` property. If undefined (or just not present), it will default - * to use the document body. If specifically set to `null` Phaser will ignore all parent operations. - * - * @name Phaser.Scale.ScaleManager#parent - * @type {?any} - * @since 3.16.0 - */ - this.parent = null; - - /** - * Is the parent element the browser window? - * - * @name Phaser.Scale.ScaleManager#parentIsWindow - * @type {boolean} - * @since 3.16.0 - */ - this.parentIsWindow = false; - - /** - * The Parent Size component. - * - * @name Phaser.Scale.ScaleManager#parentSize - * @type {Phaser.Structs.Size} - * @since 3.16.0 - */ - this.parentSize = new Size(); - - /** - * The Game Size component. - * - * The un-modified game size, as requested in the game config (the raw width / height), - * as used for world bounds, cameras, etc - * - * @name Phaser.Scale.ScaleManager#gameSize - * @type {Phaser.Structs.Size} - * @since 3.16.0 - */ - this.gameSize = new Size(); - - /** - * The Base Size component. - * - * The modified game size, which is the gameSize * resolution, used to set the canvas width and height - * (but not the CSS style) - * - * @name Phaser.Scale.ScaleManager#baseSize - * @type {Phaser.Structs.Size} - * @since 3.16.0 - */ - this.baseSize = new Size(); - - /** - * The Display Size component. - * - * The size used for the canvas style, factoring in the scale mode, parent and other values. - * - * @name Phaser.Scale.ScaleManager#displaySize - * @type {Phaser.Structs.Size} - * @since 3.16.0 - */ - this.displaySize = new Size(); - - /** - * The game scale mode. - * - * @name Phaser.Scale.ScaleManager#scaleMode - * @type {Phaser.Scale.ScaleModeType} - * @since 3.16.0 - */ - this.scaleMode = CONST.SCALE_MODE.NONE; - - /** - * The canvas resolution. - * - * This is hard-coded to a value of 1 in the 3.16 release of Phaser and will be enabled at a later date. - * - * @name Phaser.Scale.ScaleManager#resolution - * @type {number} - * @since 3.16.0 - */ - this.resolution = 1; - - /** - * The game zoom factor. - * - * This value allows you to multiply your games base size by the given zoom factor. - * This is then used when calculating the display size, even in `NONE` situations. - * If you don't want Phaser to touch the canvas style at all, this value should be 1. - * - * Can also be set to `MAX_ZOOM` in which case the zoom value will be derived based - * on the game size and available space within the parent. - * - * @name Phaser.Scale.ScaleManager#zoom - * @type {number} - * @since 3.16.0 - */ - this.zoom = 1; - - /** - * Internal flag set when the game zoom factor is modified. - * - * @name Phaser.Scale.ScaleManager#_resetZoom - * @type {boolean} - * @readonly - * @since 3.19.0 - */ - this._resetZoom = false; - - /** - * The scale factor between the baseSize and the canvasBounds. - * - * @name Phaser.Scale.ScaleManager#displayScale - * @type {Phaser.Math.Vector2} - * @since 3.16.0 - */ - this.displayScale = new Vector2(1, 1); - - /** - * If set, the canvas sizes will be automatically passed through Math.floor. - * This results in rounded pixel display values, which is important for performance on legacy - * and low powered devices, but at the cost of not achieving a 'perfect' fit in some browser windows. - * - * @name Phaser.Scale.ScaleManager#autoRound - * @type {boolean} - * @since 3.16.0 - */ - this.autoRound = false; - - /** - * Automatically center the canvas within the parent? The different centering modes are: - * - * 1. No centering. - * 2. Center both horizontally and vertically. - * 3. Center horizontally. - * 4. Center vertically. - * - * Please be aware that in order to center the game canvas, you must have specified a parent - * that has a size set, or the canvas parent is the document.body. - * - * @name Phaser.Scale.ScaleManager#autoCenter - * @type {Phaser.Scale.CenterType} - * @since 3.16.0 - */ - this.autoCenter = CONST.CENTER.NO_CENTER; - - /** - * The current device orientation. - * - * Orientation events are dispatched via the Device Orientation API, typically only on mobile browsers. - * - * @name Phaser.Scale.ScaleManager#orientation - * @type {Phaser.Scale.OrientationType} - * @since 3.16.0 - */ - this.orientation = CONST.ORIENTATION.LANDSCAPE; - - /** - * A reference to the Device.Fullscreen object. - * - * @name Phaser.Scale.ScaleManager#fullscreen - * @type {Phaser.Device.Fullscreen} - * @since 3.16.0 - */ - this.fullscreen; - - /** - * The DOM Element which is sent into fullscreen mode. - * - * @name Phaser.Scale.ScaleManager#fullscreenTarget - * @type {?any} - * @since 3.16.0 - */ - this.fullscreenTarget = null; - - /** - * Did Phaser create the fullscreen target div, or was it provided in the game config? - * - * @name Phaser.Scale.ScaleManager#_createdFullscreenTarget - * @type {boolean} - * @private - * @since 3.16.0 - */ - this._createdFullscreenTarget = false; - - /** - * The dirty state of the Scale Manager. - * Set if there is a change between the parent size and the current size. - * - * @name Phaser.Scale.ScaleManager#dirty - * @type {boolean} - * @since 3.16.0 - */ - this.dirty = false; - - /** - * 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 {integer} - * @since 3.16.0 - */ - this.resizeInterval = 500; - - /** - * Internal size interval tracker. - * - * @name Phaser.Scale.ScaleManager#_lastCheck - * @type {integer} - * @private - * @since 3.16.0 - */ - this._lastCheck = 0; - - /** - * Internal flag to check orientation state. - * - * @name Phaser.Scale.ScaleManager#_checkOrientation - * @type {boolean} - * @private - * @since 3.16.0 - */ - this._checkOrientation = false; - - /** - * Internal object containing our defined event listeners. - * - * @name Phaser.Scale.ScaleManager#listeners - * @type {object} - * @private - * @since 3.16.0 - */ - this.listeners = { - - orientationChange: NOOP, - windowResize: NOOP, - fullScreenChange: NOOP, - fullScreenError: NOOP - - }; - }, - - /** - * Called _before_ the canvas object is created and added to the DOM. - * - * @method Phaser.Scale.ScaleManager#preBoot - * @protected - * @listens Phaser.Core.Events#BOOT - * @since 3.16.0 - */ - preBoot: function () - { - // Parse the config to get the scaling values we need - this.parseConfig(this.game.config); - - this.game.events.once('boot', this.boot, this); - }, - - /** - * The Boot handler is called by Phaser.Game when it first starts up. - * The renderer is available by now and the canvas has been added to the DOM. - * - * @method Phaser.Scale.ScaleManager#boot - * @protected - * @fires Phaser.Scale.Events#RESIZE - * @since 3.16.0 - */ - boot: function () - { - var game = this.game; - - this.canvas = game.canvas; - - this.fullscreen = game.device.fullscreen; - - if (this.scaleMode !== CONST.SCALE_MODE.RESIZE) - { - this.displaySize.setAspectMode(this.scaleMode); - } - - if (this.scaleMode === CONST.SCALE_MODE.NONE) - { - this.resize(this.width, this.height); - } - else - { - this.getParentBounds(); - - // Only set the parent bounds if the parent has an actual size - if (this.parentSize.width > 0 && this.parentSize.height > 0) - { - this.displaySize.setParent(this.parentSize); - } - - this.refresh(); - } - - game.events.on(GameEvents.PRE_STEP, this.step, this); - game.events.once(GameEvents.DESTROY, this.destroy, this); - - this.startListeners(); - }, - - /** - * Parses the game configuration to set-up the scale defaults. - * - * @method Phaser.Scale.ScaleManager#parseConfig - * @protected - * @since 3.16.0 - * - * @param {Phaser.Types.Core.GameConfig} config - The Game configuration object. - */ - parseConfig: function (config) - { - // Get the parent element, if any - this.getParent(config); - - // Get the size of the parent element - // This can often set a height of zero (especially for un-styled divs) - this.getParentBounds(); - - var width = config.width; - var height = config.height; - var scaleMode = config.scaleMode; - var resolution = config.resolution; - var zoom = config.zoom; - var autoRound = config.autoRound; - - // If width = '100%', or similar value - if (typeof width === 'string') - { - // If we have a parent with a height, we'll work it out from that - var parentWidth = this.parentSize.width; - - if (parentWidth === 0) - { - parentWidth = window.innerWidth; - } - - var parentScaleX = parseInt(width, 10) / 100; - - width = Math.floor(parentWidth * parentScaleX); - } - - // If height = '100%', or similar value - if (typeof height === 'string') - { - // If we have a parent with a height, we'll work it out from that - var parentHeight = this.parentSize.height; - - if (parentHeight === 0) - { - parentHeight = window.innerHeight; - } - - var parentScaleY = parseInt(height, 10) / 100; - - height = Math.floor(parentHeight * parentScaleY); - } - - // This is fixed at 1 on purpose. - // Changing it will break all user input. - // Wait for another release to solve this issue. - this.resolution = 1; - - this.scaleMode = scaleMode; - - this.autoRound = autoRound; - - this.autoCenter = config.autoCenter; - - this.resizeInterval = config.resizeInterval; - - if (autoRound) - { - width = Math.floor(width); - height = Math.floor(height); - } - - // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc - this.gameSize.setSize(width, height); - - if (zoom === CONST.ZOOM.MAX_ZOOM) - { - zoom = this.getMaxZoom(); - } - - this.zoom = zoom; - - if (zoom !== 1) - { - this._resetZoom = true; - } - - // The modified game size, which is the w/h * resolution - this.baseSize.setSize(width * resolution, height * resolution); - - if (autoRound) - { - this.baseSize.width = Math.floor(this.baseSize.width); - this.baseSize.height = Math.floor(this.baseSize.height); - } - - if (config.minWidth > 0) - { - this.displaySize.setMin(config.minWidth * zoom, config.minHeight * zoom); - } - - if (config.maxWidth > 0) - { - this.displaySize.setMax(config.maxWidth * zoom, config.maxHeight * zoom); - } - - // 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) - this.displaySize.setSize(width, height); - - this.orientation = GetScreenOrientation(width, height); - }, - - /** - * 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. - */ - getParent: function (config) - { - var parent = config.parent; - - if (parent === null) - { - // User is responsible for managing the parent - return; - } - - this.parent = GetTarget(parent); - this.parentIsWindow = (this.parent === document.body); - - if (config.expandParent && config.scaleMode !== CONST.SCALE_MODE.NONE) - { - var DOMRect = this.parent.getBoundingClientRect(); - - if (this.parentIsWindow || DOMRect.height === 0) - { - document.documentElement.style.height = '100%'; - document.body.style.height = '100%'; - - DOMRect = this.parent.getBoundingClientRect(); - - // The parent STILL has no height, clearly no CSS - // has been set on it even though we fixed the body :( - if (!this.parentIsWindow && DOMRect.height === 0) - { - this.parent.style.overflow = 'hidden'; - this.parent.style.width = '100%'; - this.parent.style.height = '100%'; - } - } - } - - // And now get the fullscreenTarget - if (config.fullscreenTarget && !this.fullscreenTarget) - { - this.fullscreenTarget = GetTarget(config.fullscreenTarget); - } - }, - - /** - * Calculates the size of the parent bounds and updates the `parentSize` component, if the canvas has a dom parent. - * - * @method Phaser.Scale.ScaleManager#getParentBounds - * @since 3.16.0 - * - * @return {boolean} `true` if the parent bounds have changed size, otherwise `false`. - */ - getParentBounds: function () - { - if (!this.parent) - { - return false; - } - - var parentSize = this.parentSize; - - // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect - - var DOMRect = this.parent.getBoundingClientRect(); - - if (this.parentIsWindow && this.game.device.os.iOS) - { - DOMRect.height = GetInnerHeight(true); - } - - var resolution = this.resolution; - var newWidth = DOMRect.width * resolution; - var newHeight = DOMRect.height * resolution; - - if (parentSize.width !== newWidth || parentSize.height !== newHeight) - { - parentSize.setSize(newWidth, newHeight); - - return true; - } - else - { - return false; - } - }, - - /** - * 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`. - */ - lockOrientation: function (orientation) - { - var lock = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; - - if (lock) - { - return lock(orientation); - } - - return false; - }, - - /** - * This method will set the size of the Parent Size component, which is used in scaling - * and centering calculations. You only need to call this method if you have explicitly - * disabled the use of a parent in your game config, but still wish to take advantage of - * other Scale Manager features. - * - * @method Phaser.Scale.ScaleManager#setParentSize - * @fires Phaser.Scale.Events#RESIZE - * @since 3.16.0 - * - * @param {number} width - The new width of the parent. - * @param {number} height - The new height of the parent. - * - * @return {this} The Scale Manager instance. - */ - setParentSize: function (width, height) - { - this.parentSize.setSize(width, height); - - return this.refresh(); - }, - - /** - * This method will set a new size for your game. - * - * It should only be used if you're looking to change the base size of your game and are using - * one of the Scale Manager scaling modes, i.e. `FIT`. If you're using `NONE` and wish to - * change the game and canvas size directly, then please use the `resize` method instead. - * - * @method Phaser.Scale.ScaleManager#setGameSize - * @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. - */ - setGameSize: function (width, height) - { - var autoRound = this.autoRound; - var resolution = this.resolution; - - if (autoRound) - { - width = Math.floor(width); - height = Math.floor(height); - } - - var previousWidth = this.width; - var previousHeight = this.height; - - // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc - this.gameSize.resize(width, height); - - // The modified game size, which is the w/h * resolution - this.baseSize.resize(width * resolution, height * resolution); - - if (autoRound) - { - this.baseSize.width = Math.floor(this.baseSize.width); - this.baseSize.height = Math.floor(this.baseSize.height); - } - - // 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) - this.displaySize.setSize(width, height); - - this.canvas.width = this.baseSize.width; - this.canvas.height = this.baseSize.height; - - return this.refresh(previousWidth, previousHeight); - }, - - /** - * 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. - */ - resize: function (width, height) - { - var zoom = this.zoom; - var resolution = this.resolution; - var autoRound = this.autoRound; - - if (autoRound) - { - width = Math.floor(width); - height = Math.floor(height); - } - - var previousWidth = this.width; - var previousHeight = this.height; - - // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc - this.gameSize.resize(width, height); - - // The modified game size, which is the w/h * resolution - this.baseSize.resize(width * resolution, height * resolution); - - if (autoRound) - { - this.baseSize.width = Math.floor(this.baseSize.width); - this.baseSize.height = Math.floor(this.baseSize.height); - } - - // 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) - this.displaySize.setSize((width * zoom) * resolution, (height * zoom) * resolution); - - this.canvas.width = this.baseSize.width; - this.canvas.height = this.baseSize.height; - - var style = this.canvas.style; - - var styleWidth = width * zoom; - var styleHeight = height * zoom; - - if (autoRound) - { - styleWidth = Math.floor(styleWidth); - styleHeight = Math.floor(styleHeight); - } - - if (styleWidth !== width || styleHeight !== height) - { - style.width = styleWidth + 'px'; - style.height = styleHeight + 'px'; - } - - return this.refresh(previousWidth, previousHeight); - }, - - /** - * Sets the zoom value of the Scale Manager. - * - * @method Phaser.Scale.ScaleManager#setZoom - * @fires Phaser.Scale.Events#RESIZE - * @since 3.16.0 - * - * @param {integer} value - The new zoom value of the game. - * - * @return {this} The Scale Manager instance. - */ - setZoom: function (value) - { - this.zoom = value; - this._resetZoom = true; - - return this.refresh(); - }, - - /** - * 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. - */ - setMaxZoom: function () - { - this.zoom = this.getMaxZoom(); - this._resetZoom = true; - - return this.refresh(); - }, - - /** - * Refreshes the internal scale values, bounds sizes and orientation checks. - * - * Once finished, dispatches the resize event. - * - * This is called automatically by the Scale Manager when the browser window size changes, - * as long as it is using a Scale Mode other than 'NONE'. - * - * @method Phaser.Scale.ScaleManager#refresh - * @fires Phaser.Scale.Events#RESIZE - * @since 3.16.0 - * - * @param {number} [previousWidth] - The previous width of the game. Only set if the gameSize has changed. - * @param {number} [previousHeight] - The previous height of the game. Only set if the gameSize has changed. - * - * @return {this} The Scale Manager instance. - */ - refresh: function (previousWidth, previousHeight) - { - if (previousWidth === undefined) { previousWidth = this.width; } - if (previousHeight === undefined) { previousHeight = this.height; } - - this.updateScale(); - this.updateBounds(); - this.updateOrientation(); - - this.displayScale.set(this.baseSize.width / this.canvasBounds.width, this.baseSize.height / this.canvasBounds.height); - - var domContainer = this.game.domContainer; - - if (domContainer) - { - this.baseSize.setCSS(domContainer); - - var canvasStyle = this.canvas.style; - var domStyle = domContainer.style; - - domStyle.transform = 'scale(' + this.displaySize.width / this.baseSize.width + ',' + this.displaySize.height / this.baseSize.height + ')'; - - domStyle.marginLeft = canvasStyle.marginLeft; - domStyle.marginTop = canvasStyle.marginTop; - } - - this.emit(Events.RESIZE, this.gameSize, this.baseSize, this.displaySize, this.resolution, previousWidth, previousHeight); - - return this; - }, - - /** - * Internal method that checks the current screen orientation, only if the internal check flag is set. - * - * If the orientation has changed it updates the orientation property and then dispatches the orientation change event. - * - * @method Phaser.Scale.ScaleManager#updateOrientation - * @fires Phaser.Scale.Events#ORIENTATION_CHANGE - * @since 3.16.0 - */ - updateOrientation: function () - { - if (this._checkOrientation) - { - this._checkOrientation = false; - - var newOrientation = GetScreenOrientation(this.width, this.height); - - if (newOrientation !== this.orientation) - { - this.orientation = newOrientation; - - this.emit(Events.ORIENTATION_CHANGE, newOrientation); - } - } - }, - - /** - * Internal method that manages updating the size components based on the scale mode. - * - * @method Phaser.Scale.ScaleManager#updateScale - * @since 3.16.0 - */ - updateScale: function () - { - var style = this.canvas.style; - - var width = this.gameSize.width; - var height = this.gameSize.height; - - var styleWidth; - var styleHeight; - - var zoom = this.zoom; - var autoRound = this.autoRound; - var resolution = 1; - - if (this.scaleMode === CONST.SCALE_MODE.NONE) - { - // No scale - this.displaySize.setSize((width * zoom) * resolution, (height * zoom) * resolution); - - styleWidth = this.displaySize.width / resolution; - styleHeight = this.displaySize.height / resolution; - - if (autoRound) - { - styleWidth = Math.floor(styleWidth); - styleHeight = Math.floor(styleHeight); - } - - if (this._resetZoom) - { - style.width = styleWidth + 'px'; - style.height = styleHeight + 'px'; - - this._resetZoom = false; - } - } - else if (this.scaleMode === CONST.SCALE_MODE.RESIZE) - { - // Resize to match parent - - // This will constrain using min/max - this.displaySize.setSize(this.parentSize.width, this.parentSize.height); - - this.gameSize.setSize(this.displaySize.width, this.displaySize.height); - - this.baseSize.setSize(this.displaySize.width * resolution, this.displaySize.height * resolution); - - styleWidth = this.displaySize.width / resolution; - styleHeight = this.displaySize.height / resolution; - - if (autoRound) - { - styleWidth = Math.floor(styleWidth); - styleHeight = Math.floor(styleHeight); - } - - this.canvas.width = styleWidth; - this.canvas.height = styleHeight; - } - else - { - // All other scale modes - this.displaySize.setSize(this.parentSize.width, this.parentSize.height); - - styleWidth = this.displaySize.width / resolution; - styleHeight = this.displaySize.height / resolution; - - if (autoRound) - { - styleWidth = Math.floor(styleWidth); - styleHeight = Math.floor(styleHeight); - } - - style.width = styleWidth + 'px'; - style.height = styleHeight + 'px'; - } - - // Update the parentSize in case the canvas / style change modified it - this.getParentBounds(); - - // Finally, update the centering - this.updateCenter(); - }, - - /** - * 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 {integer} The maximum possible zoom factor. At a minimum this value is always at least 1. - */ - getMaxZoom: function () - { - var zoomH = SnapFloor(this.parentSize.width, this.gameSize.width, 0, true); - var zoomV = SnapFloor(this.parentSize.height, this.gameSize.height, 0, true); - - return Math.max(Math.min(zoomH, zoomV), 1); - }, - - /** - * Calculates and updates the canvas CSS style in order to center it within the - * bounds of its parent. If you have explicitly set parent to be `null` in your - * game config then this method will likely give incorrect results unless you have called the - * `setParentSize` method first. - * - * It works by modifying the canvas CSS `marginLeft` and `marginTop` properties. - * - * If they have already been set by your own style sheet, or code, this will overwrite them. - * - * To prevent the Scale Manager from centering the canvas, either do not set the - * `autoCenter` property in your game config, or make sure it is set to `NO_CENTER`. - * - * @method Phaser.Scale.ScaleManager#updateCenter - * @since 3.16.0 - */ - updateCenter: function () - { - var autoCenter = this.autoCenter; - - if (autoCenter === CONST.CENTER.NO_CENTER) - { - return; - } - - var canvas = this.canvas; - - var style = canvas.style; - - var bounds = canvas.getBoundingClientRect(); - - // var width = parseInt(canvas.style.width, 10) || canvas.width; - // var height = parseInt(canvas.style.height, 10) || canvas.height; - - var width = bounds.width; - var height = bounds.height; - - var offsetX = Math.floor((this.parentSize.width - width) / 2); - var offsetY = Math.floor((this.parentSize.height - height) / 2); - - if (autoCenter === CONST.CENTER.CENTER_HORIZONTALLY) - { - offsetY = 0; - } - else if (autoCenter === CONST.CENTER.CENTER_VERTICALLY) - { - offsetX = 0; - } - - style.marginLeft = offsetX + 'px'; - style.marginTop = offsetY + 'px'; - }, - - /** - * Updates the `canvasBounds` rectangle to match the bounding client rectangle of the - * canvas element being used to track input events. - * - * @method Phaser.Scale.ScaleManager#updateBounds - * @since 3.16.0 - */ - updateBounds: function () - { - var bounds = this.canvasBounds; - var clientRect = this.canvas.getBoundingClientRect(); - - bounds.x = clientRect.left + (window.pageXOffset || 0) - (document.documentElement.clientLeft || 0); - bounds.y = clientRect.top + (window.pageYOffset || 0) - (document.documentElement.clientTop || 0); - bounds.width = clientRect.width; - bounds.height = clientRect.height; - }, - - /** - * Transforms the pageX value into the scaled coordinate space of the Scale Manager. - * - * @method Phaser.Scale.ScaleManager#transformX - * @since 3.16.0 - * - * @param {number} pageX - The DOM pageX value. - * - * @return {number} The translated value. - */ - transformX: function (pageX) - { - return (pageX - this.canvasBounds.left) * this.displayScale.x; - }, - - /** - * Transforms the pageY value into the scaled coordinate space of the Scale Manager. - * - * @method Phaser.Scale.ScaleManager#transformY - * @since 3.16.0 - * - * @param {number} pageY - The DOM pageY value. - * - * @return {number} The translated value. - */ - transformY: function (pageY) - { - return (pageY - this.canvasBounds.top) * this.displayScale.y; - }, - - /** - * 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 user-input gesture, such as `pointerup`. 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 `
` 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. - */ - startFullscreen: function (fullscreenOptions) - { - if (fullscreenOptions === undefined) { fullscreenOptions = { navigationUI: 'hide' }; } - - var fullscreen = this.fullscreen; - - if (!fullscreen.available) - { - this.emit(Events.FULLSCREEN_UNSUPPORTED); - - return; - } - - if (!fullscreen.active) - { - var fsTarget = this.getFullscreenTarget(); - - var fsPromise; - - if (fullscreen.keyboard) - { - fsPromise = fsTarget[fullscreen.request](Element.ALLOW_KEYBOARD_INPUT); - } - else - { - fsPromise = fsTarget[fullscreen.request](fullscreenOptions); - } - - if (fsPromise) - { - fsPromise.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)); - } - else if (fullscreen.active) - { - this.fullscreenSuccessHandler(); - } - else - { - this.fullscreenErrorHandler(); - } - } - }, - - /** - * The browser has successfully entered fullscreen mode. - * - * @method Phaser.Scale.ScaleManager#fullscreenSuccessHandler - * @private - * @fires Phaser.Scale.Events#ENTER_FULLSCREEN - * @fires Phaser.Scale.Events#RESIZE - * @since 3.17.0 - */ - fullscreenSuccessHandler: function () - { - this.getParentBounds(); - - this.refresh(); - - this.emit(Events.ENTER_FULLSCREEN); - }, - - /** - * The browser failed to enter fullscreen mode. - * - * @method Phaser.Scale.ScaleManager#fullscreenErrorHandler - * @private - * @fires Phaser.Scale.Events#FULLSCREEN_FAILED - * @fires Phaser.Scale.Events#RESIZE - * @since 3.17.0 - * - * @param {any} error - The DOM error event. - */ - fullscreenErrorHandler: function (error) - { - this.removeFullscreenTarget(); - - this.emit(Events.FULLSCREEN_FAILED, error); - }, - - /** - * An internal method that gets the target element that is used when entering fullscreen mode. - * - * @method Phaser.Scale.ScaleManager#getFullscreenTarget - * @since 3.16.0 - * - * @return {object} The fullscreen target element. - */ - getFullscreenTarget: function () - { - if (!this.fullscreenTarget) - { - var fsTarget = document.createElement('div'); - - fsTarget.style.margin = '0'; - fsTarget.style.padding = '0'; - fsTarget.style.width = '100%'; - fsTarget.style.height = '100%'; - - this.fullscreenTarget = fsTarget; - - this._createdFullscreenTarget = true; - } - - if (this._createdFullscreenTarget) - { - var canvasParent = this.canvas.parentNode; - - canvasParent.insertBefore(this.fullscreenTarget, this.canvas); - - this.fullscreenTarget.appendChild(this.canvas); - } - - return this.fullscreenTarget; - }, - - /** - * Removes the fullscreen target that was added to the DOM. - * - * @method Phaser.Scale.ScaleManager#removeFullscreenTarget - * @since 3.17.0 - */ - removeFullscreenTarget: function () - { - if (this._createdFullscreenTarget) - { - var fsTarget = this.fullscreenTarget; - - if (fsTarget && fsTarget.parentNode) - { - var parent = fsTarget.parentNode; - - parent.insertBefore(this.canvas, fsTarget); - - parent.removeChild(fsTarget); - } - } - }, - - /** - * Calling this method will cancel fullscreen mode, if the browser has entered it. - * - * @method Phaser.Scale.ScaleManager#stopFullscreen - * @fires Phaser.Scale.Events#LEAVE_FULLSCREEN - * @fires Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED - * @since 3.16.0 - */ - stopFullscreen: function () - { - var fullscreen = this.fullscreen; - - if (!fullscreen.available) - { - this.emit(Events.FULLSCREEN_UNSUPPORTED); - - return false; - } - - if (fullscreen.active) - { - document[fullscreen.cancel](); - } - - this.removeFullscreenTarget(); - - // Get the parent size again as it will have changed - this.getParentBounds(); - - this.emit(Events.LEAVE_FULLSCREEN); - - this.refresh(); - }, - - /** - * Toggles the fullscreen mode. If already in fullscreen, calling this will cancel it. - * If not in fullscreen, this will request the browser to enter fullscreen mode. - * - * If the browser does not support this, a `FULLSCREEN_UNSUPPORTED` event will be emitted. - * - * This method _must_ be called from a user-input gesture, such as `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. - * - * @method Phaser.Scale.ScaleManager#toggleFullscreen - * @fires Phaser.Scale.Events#ENTER_FULLSCREEN - * @fires Phaser.Scale.Events#LEAVE_FULLSCREEN - * @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. - */ - toggleFullscreen: function (fullscreenOptions) - { - if (this.fullscreen.active) - { - this.stopFullscreen(); - } - else - { - this.startFullscreen(fullscreenOptions); - } - }, - - /** - * An internal method that starts the different DOM event listeners running. - * - * @method Phaser.Scale.ScaleManager#startListeners - * @since 3.16.0 - */ - startListeners: function () - { - var _this = this; - var listeners = this.listeners; - - listeners.orientationChange = function () - { - _this._checkOrientation = true; - _this.dirty = true; - }; - - listeners.windowResize = function () - { - _this.dirty = true; - }; - - // Only dispatched on mobile devices - window.addEventListener('orientationchange', listeners.orientationChange, false); - - window.addEventListener('resize', listeners.windowResize, false); - - if (this.fullscreen.available) - { - listeners.fullScreenChange = function (event) - { - return _this.onFullScreenChange(event); - }; - - listeners.fullScreenError = function (event) - { - return _this.onFullScreenError(event); - }; - - var vendors = [ 'webkit', 'moz', '' ]; - - vendors.forEach(function (prefix) - { - document.addEventListener(prefix + 'fullscreenchange', listeners.fullScreenChange, false); - document.addEventListener(prefix + 'fullscreenerror', listeners.fullScreenError, false); - }); - - // MS Specific - document.addEventListener('MSFullscreenChange', listeners.fullScreenChange, false); - document.addEventListener('MSFullscreenError', listeners.fullScreenError, false); - } - }, - - /** - * Triggered when a fullscreenchange event is dispatched by the DOM. - * - * @method Phaser.Scale.ScaleManager#onFullScreenChange - * @since 3.16.0 - */ - onFullScreenChange: function () - { - // They pressed ESC while in fullscreen mode - if (!(document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement || document.mozFullScreenElement)) - { - this.stopFullscreen(); - } - }, - - /** - * Triggered when a fullscreenerror event is dispatched by the DOM. - * - * @method Phaser.Scale.ScaleManager#onFullScreenError - * @since 3.16.0 - */ - onFullScreenError: function () - { - this.removeFullscreenTarget(); - }, - - /** - * Internal method, called automatically by the game step. - * Monitors the elapsed time and resize interval to see if a parent bounds check needs to take place. - * - * @method Phaser.Scale.ScaleManager#step - * @since 3.16.0 - * - * @param {number} time - The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). - * @param {number} delta - The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. - */ - step: function (time, delta) - { - if (!this.parent) - { - return; - } - - this._lastCheck += delta; - - if (this.dirty || this._lastCheck > this.resizeInterval) - { - // Returns true if the parent bounds have changed size - if (this.getParentBounds()) - { - this.refresh(); - } - - this.dirty = false; - this._lastCheck = 0; - } - }, - - /** - * Stops all DOM event listeners. - * - * @method Phaser.Scale.ScaleManager#stopListeners - * @since 3.16.0 - */ - stopListeners: function () - { - var listeners = this.listeners; - - window.removeEventListener('orientationchange', listeners.orientationChange, false); - window.removeEventListener('resize', listeners.windowResize, false); - - var vendors = [ 'webkit', 'moz', '' ]; - - vendors.forEach(function (prefix) - { - document.removeEventListener(prefix + 'fullscreenchange', listeners.fullScreenChange, false); - document.removeEventListener(prefix + 'fullscreenerror', listeners.fullScreenError, false); - }); - - // MS Specific - document.removeEventListener('MSFullscreenChange', listeners.fullScreenChange, false); - document.removeEventListener('MSFullscreenError', listeners.fullScreenError, false); - }, - - /** - * Destroys this Scale Manager, releasing all references to external resources. - * Once destroyed, the Scale Manager cannot be used again. - * - * @method Phaser.Scale.ScaleManager#destroy - * @since 3.16.0 - */ - destroy: function () - { - this.removeAllListeners(); - - this.stopListeners(); - - this.game = null; - this.canvas = null; - this.canvasBounds = null; - this.parent = null; - this.fullscreenTarget = null; - - this.parentSize.destroy(); - this.gameSize.destroy(); - this.baseSize.destroy(); - this.displaySize.destroy(); - }, - - /** - * Is the browser currently in fullscreen mode or not? - * - * @name Phaser.Scale.ScaleManager#isFullscreen - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - isFullscreen: { - - get: function () - { - return this.fullscreen.active; - } - - }, - - /** - * The game width. - * - * This is typically the size given in the game configuration. - * - * @name Phaser.Scale.ScaleManager#width - * @type {number} - * @readonly - * @since 3.16.0 - */ - width: { - - get: function () - { - return this.gameSize.width; - } - - }, - - /** - * The game height. - * - * This is typically the size given in the game configuration. - * - * @name Phaser.Scale.ScaleManager#height - * @type {number} - * @readonly - * @since 3.16.0 - */ - height: { - - get: function () - { - return this.gameSize.height; - } - - }, - - /** - * Is the device in a portrait orientation as reported by the Orientation API? - * This value is usually only available on mobile devices. - * - * @name Phaser.Scale.ScaleManager#isPortrait - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - isPortrait: { - - get: function () - { - return (this.orientation === CONST.ORIENTATION.PORTRAIT); - } - - }, - - /** - * Is the device in a landscape orientation as reported by the Orientation API? - * This value is usually only available on mobile devices. - * - * @name Phaser.Scale.ScaleManager#isLandscape - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - isLandscape: { - - get: function () - { - return (this.orientation === CONST.ORIENTATION.LANDSCAPE); - } - - }, - - /** - * Are the game dimensions portrait? (i.e. taller than they are wide) - * - * This is different to the device itself being in a portrait orientation. - * - * @name Phaser.Scale.ScaleManager#isGamePortrait - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - isGamePortrait: { - - get: function () - { - return (this.height > this.width); - } - - }, - - /** - * Are the game dimensions landscape? (i.e. wider than they are tall) - * - * This is different to the device itself being in a landscape orientation. - * - * @name Phaser.Scale.ScaleManager#isGameLandscape - * @type {boolean} - * @readonly - * @since 3.16.0 - */ - isGameLandscape: { - - get: function () - { - return (this.width > this.height); - } - - } - -}); - -module.exports = ScaleManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Class = require('../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GameEvents = require('../core/events'); +var GetInnerHeight = require('../dom/GetInnerHeight'); +var GetTarget = require('../dom/GetTarget'); +var GetScreenOrientation = require('../dom/GetScreenOrientation'); +var NOOP = require('../utils/NOOP'); +var Rectangle = require('../geom/rectangle/Rectangle'); +var Size = require('../structs/Size'); +var SnapFloor = require('../math/snap/SnapFloor'); +var Vector2 = require('../math/Vector2'); + +/** + * @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. + */ +var ScaleManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function ScaleManager (game) + { + EventEmitter.call(this); + + /** + * A reference to the Phaser.Game instance. + * + * @name Phaser.Scale.ScaleManager#game + * @type {Phaser.Game} + * @readonly + * @since 3.15.0 + */ + this.game = game; + + /** + * A reference to the HTML Canvas Element that Phaser uses to render the game. + * + * @name Phaser.Scale.ScaleManager#canvas + * @type {HTMLCanvasElement} + * @since 3.16.0 + */ + this.canvas; + + /** + * The DOM bounds of the canvas element. + * + * @name Phaser.Scale.ScaleManager#canvasBounds + * @type {Phaser.Geom.Rectangle} + * @since 3.16.0 + */ + this.canvasBounds = new Rectangle(); + + /** + * The parent object of the Canvas. Often a div, or the browser window, or nothing in non-browser environments. + * + * This is set in the Game Config as the `parent` property. If undefined (or just not present), it will default + * to use the document body. If specifically set to `null` Phaser will ignore all parent operations. + * + * @name Phaser.Scale.ScaleManager#parent + * @type {?any} + * @since 3.16.0 + */ + this.parent = null; + + /** + * Is the parent element the browser window? + * + * @name Phaser.Scale.ScaleManager#parentIsWindow + * @type {boolean} + * @since 3.16.0 + */ + this.parentIsWindow = false; + + /** + * The Parent Size component. + * + * @name Phaser.Scale.ScaleManager#parentSize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.parentSize = new Size(); + + /** + * The Game Size component. + * + * The un-modified game size, as requested in the game config (the raw width / height), + * as used for world bounds, cameras, etc + * + * @name Phaser.Scale.ScaleManager#gameSize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.gameSize = new Size(); + + /** + * The Base Size component. + * + * The modified game size, which is the gameSize * resolution, used to set the canvas width and height + * (but not the CSS style) + * + * @name Phaser.Scale.ScaleManager#baseSize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.baseSize = new Size(); + + /** + * The Display Size component. + * + * The size used for the canvas style, factoring in the scale mode, parent and other values. + * + * @name Phaser.Scale.ScaleManager#displaySize + * @type {Phaser.Structs.Size} + * @since 3.16.0 + */ + this.displaySize = new Size(); + + /** + * The game scale mode. + * + * @name Phaser.Scale.ScaleManager#scaleMode + * @type {Phaser.Scale.ScaleModeType} + * @since 3.16.0 + */ + this.scaleMode = CONST.SCALE_MODE.NONE; + + /** + * The canvas resolution. + * + * This is hard-coded to a value of 1 in the 3.16 release of Phaser and will be enabled at a later date. + * + * @name Phaser.Scale.ScaleManager#resolution + * @type {number} + * @since 3.16.0 + */ + this.resolution = 1; + + /** + * The game zoom factor. + * + * This value allows you to multiply your games base size by the given zoom factor. + * This is then used when calculating the display size, even in `NONE` situations. + * If you don't want Phaser to touch the canvas style at all, this value should be 1. + * + * Can also be set to `MAX_ZOOM` in which case the zoom value will be derived based + * on the game size and available space within the parent. + * + * @name Phaser.Scale.ScaleManager#zoom + * @type {number} + * @since 3.16.0 + */ + this.zoom = 1; + + /** + * Internal flag set when the game zoom factor is modified. + * + * @name Phaser.Scale.ScaleManager#_resetZoom + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this._resetZoom = false; + + /** + * The scale factor between the baseSize and the canvasBounds. + * + * @name Phaser.Scale.ScaleManager#displayScale + * @type {Phaser.Math.Vector2} + * @since 3.16.0 + */ + this.displayScale = new Vector2(1, 1); + + /** + * If set, the canvas sizes will be automatically passed through Math.floor. + * This results in rounded pixel display values, which is important for performance on legacy + * and low powered devices, but at the cost of not achieving a 'perfect' fit in some browser windows. + * + * @name Phaser.Scale.ScaleManager#autoRound + * @type {boolean} + * @since 3.16.0 + */ + this.autoRound = false; + + /** + * Automatically center the canvas within the parent? The different centering modes are: + * + * 1. No centering. + * 2. Center both horizontally and vertically. + * 3. Center horizontally. + * 4. Center vertically. + * + * Please be aware that in order to center the game canvas, you must have specified a parent + * that has a size set, or the canvas parent is the document.body. + * + * @name Phaser.Scale.ScaleManager#autoCenter + * @type {Phaser.Scale.CenterType} + * @since 3.16.0 + */ + this.autoCenter = CONST.CENTER.NO_CENTER; + + /** + * The current device orientation. + * + * Orientation events are dispatched via the Device Orientation API, typically only on mobile browsers. + * + * @name Phaser.Scale.ScaleManager#orientation + * @type {Phaser.Scale.OrientationType} + * @since 3.16.0 + */ + this.orientation = CONST.ORIENTATION.LANDSCAPE; + + /** + * A reference to the Device.Fullscreen object. + * + * @name Phaser.Scale.ScaleManager#fullscreen + * @type {Phaser.Device.Fullscreen} + * @since 3.16.0 + */ + this.fullscreen; + + /** + * The DOM Element which is sent into fullscreen mode. + * + * @name Phaser.Scale.ScaleManager#fullscreenTarget + * @type {?any} + * @since 3.16.0 + */ + this.fullscreenTarget = null; + + /** + * Did Phaser create the fullscreen target div, or was it provided in the game config? + * + * @name Phaser.Scale.ScaleManager#_createdFullscreenTarget + * @type {boolean} + * @private + * @since 3.16.0 + */ + this._createdFullscreenTarget = false; + + /** + * The dirty state of the Scale Manager. + * Set if there is a change between the parent size and the current size. + * + * @name Phaser.Scale.ScaleManager#dirty + * @type {boolean} + * @since 3.16.0 + */ + this.dirty = false; + + /** + * 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 {integer} + * @since 3.16.0 + */ + this.resizeInterval = 500; + + /** + * Internal size interval tracker. + * + * @name Phaser.Scale.ScaleManager#_lastCheck + * @type {integer} + * @private + * @since 3.16.0 + */ + this._lastCheck = 0; + + /** + * Internal flag to check orientation state. + * + * @name Phaser.Scale.ScaleManager#_checkOrientation + * @type {boolean} + * @private + * @since 3.16.0 + */ + this._checkOrientation = false; + + /** + * Internal object containing our defined event listeners. + * + * @name Phaser.Scale.ScaleManager#listeners + * @type {object} + * @private + * @since 3.16.0 + */ + this.listeners = { + + orientationChange: NOOP, + windowResize: NOOP, + fullScreenChange: NOOP, + fullScreenError: NOOP + + }; + }, + + /** + * Called _before_ the canvas object is created and added to the DOM. + * + * @method Phaser.Scale.ScaleManager#preBoot + * @protected + * @listens Phaser.Core.Events#BOOT + * @since 3.16.0 + */ + preBoot: function () + { + // Parse the config to get the scaling values we need + this.parseConfig(this.game.config); + + this.game.events.once('boot', this.boot, this); + }, + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * The renderer is available by now and the canvas has been added to the DOM. + * + * @method Phaser.Scale.ScaleManager#boot + * @protected + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + */ + boot: function () + { + var game = this.game; + + this.canvas = game.canvas; + + this.fullscreen = game.device.fullscreen; + + if (this.scaleMode !== CONST.SCALE_MODE.RESIZE) + { + this.displaySize.setAspectMode(this.scaleMode); + } + + if (this.scaleMode === CONST.SCALE_MODE.NONE) + { + this.resize(this.width, this.height); + } + else + { + this.getParentBounds(); + + // Only set the parent bounds if the parent has an actual size + if (this.parentSize.width > 0 && this.parentSize.height > 0) + { + this.displaySize.setParent(this.parentSize); + } + + this.refresh(); + } + + game.events.on(GameEvents.PRE_STEP, this.step, this); + game.events.once(GameEvents.DESTROY, this.destroy, this); + + this.startListeners(); + }, + + /** + * Parses the game configuration to set-up the scale defaults. + * + * @method Phaser.Scale.ScaleManager#parseConfig + * @protected + * @since 3.16.0 + * + * @param {Phaser.Types.Core.GameConfig} config - The Game configuration object. + */ + parseConfig: function (config) + { + // Get the parent element, if any + this.getParent(config); + + // Get the size of the parent element + // This can often set a height of zero (especially for un-styled divs) + this.getParentBounds(); + + var width = config.width; + var height = config.height; + var scaleMode = config.scaleMode; + var resolution = config.resolution; + var zoom = config.zoom; + var autoRound = config.autoRound; + + // If width = '100%', or similar value + if (typeof width === 'string') + { + // If we have a parent with a height, we'll work it out from that + var parentWidth = this.parentSize.width; + + if (parentWidth === 0) + { + parentWidth = window.innerWidth; + } + + var parentScaleX = parseInt(width, 10) / 100; + + width = Math.floor(parentWidth * parentScaleX); + } + + // If height = '100%', or similar value + if (typeof height === 'string') + { + // If we have a parent with a height, we'll work it out from that + var parentHeight = this.parentSize.height; + + if (parentHeight === 0) + { + parentHeight = window.innerHeight; + } + + var parentScaleY = parseInt(height, 10) / 100; + + height = Math.floor(parentHeight * parentScaleY); + } + + // This is fixed at 1 on purpose. + // Changing it will break all user input. + // Wait for another release to solve this issue. + this.resolution = 1; + + this.scaleMode = scaleMode; + + this.autoRound = autoRound; + + this.autoCenter = config.autoCenter; + + this.resizeInterval = config.resizeInterval; + + if (autoRound) + { + width = Math.floor(width); + height = Math.floor(height); + } + + // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc + this.gameSize.setSize(width, height); + + if (zoom === CONST.ZOOM.MAX_ZOOM) + { + zoom = this.getMaxZoom(); + } + + this.zoom = zoom; + + if (zoom !== 1) + { + this._resetZoom = true; + } + + // The modified game size, which is the w/h * resolution + this.baseSize.setSize(width * resolution, height * resolution); + + if (autoRound) + { + this.baseSize.width = Math.floor(this.baseSize.width); + this.baseSize.height = Math.floor(this.baseSize.height); + } + + if (config.minWidth > 0) + { + this.displaySize.setMin(config.minWidth * zoom, config.minHeight * zoom); + } + + if (config.maxWidth > 0) + { + this.displaySize.setMax(config.maxWidth * zoom, config.maxHeight * zoom); + } + + // 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) + this.displaySize.setSize(width, height); + + this.orientation = GetScreenOrientation(width, height); + }, + + /** + * 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. + */ + getParent: function (config) + { + var parent = config.parent; + + if (parent === null) + { + // User is responsible for managing the parent + return; + } + + this.parent = GetTarget(parent); + this.parentIsWindow = (this.parent === document.body); + + if (config.expandParent && config.scaleMode !== CONST.SCALE_MODE.NONE) + { + var DOMRect = this.parent.getBoundingClientRect(); + + if (this.parentIsWindow || DOMRect.height === 0) + { + document.documentElement.style.height = '100%'; + document.body.style.height = '100%'; + + DOMRect = this.parent.getBoundingClientRect(); + + // The parent STILL has no height, clearly no CSS + // has been set on it even though we fixed the body :( + if (!this.parentIsWindow && DOMRect.height === 0) + { + this.parent.style.overflow = 'hidden'; + this.parent.style.width = '100%'; + this.parent.style.height = '100%'; + } + } + } + + // And now get the fullscreenTarget + if (config.fullscreenTarget && !this.fullscreenTarget) + { + this.fullscreenTarget = GetTarget(config.fullscreenTarget); + } + }, + + /** + * Calculates the size of the parent bounds and updates the `parentSize` component, if the canvas has a dom parent. + * + * @method Phaser.Scale.ScaleManager#getParentBounds + * @since 3.16.0 + * + * @return {boolean} `true` if the parent bounds have changed size, otherwise `false`. + */ + getParentBounds: function () + { + if (!this.parent) + { + return false; + } + + var parentSize = this.parentSize; + + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + + var DOMRect = this.parent.getBoundingClientRect(); + + if (this.parentIsWindow && this.game.device.os.iOS) + { + DOMRect.height = GetInnerHeight(true); + } + + var resolution = this.resolution; + var newWidth = DOMRect.width * resolution; + var newHeight = DOMRect.height * resolution; + + if (parentSize.width !== newWidth || parentSize.height !== newHeight) + { + parentSize.setSize(newWidth, newHeight); + + return true; + } + else + { + return false; + } + }, + + /** + * 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`. + */ + lockOrientation: function (orientation) + { + var lock = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; + + if (lock) + { + return lock(orientation); + } + + return false; + }, + + /** + * This method will set the size of the Parent Size component, which is used in scaling + * and centering calculations. You only need to call this method if you have explicitly + * disabled the use of a parent in your game config, but still wish to take advantage of + * other Scale Manager features. + * + * @method Phaser.Scale.ScaleManager#setParentSize + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + * + * @param {number} width - The new width of the parent. + * @param {number} height - The new height of the parent. + * + * @return {this} The Scale Manager instance. + */ + setParentSize: function (width, height) + { + this.parentSize.setSize(width, height); + + return this.refresh(); + }, + + /** + * This method will set a new size for your game. + * + * It should only be used if you're looking to change the base size of your game and are using + * one of the Scale Manager scaling modes, i.e. `FIT`. If you're using `NONE` and wish to + * change the game and canvas size directly, then please use the `resize` method instead. + * + * @method Phaser.Scale.ScaleManager#setGameSize + * @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. + */ + setGameSize: function (width, height) + { + var autoRound = this.autoRound; + var resolution = this.resolution; + + if (autoRound) + { + width = Math.floor(width); + height = Math.floor(height); + } + + var previousWidth = this.width; + var previousHeight = this.height; + + // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc + this.gameSize.resize(width, height); + + // The modified game size, which is the w/h * resolution + this.baseSize.resize(width * resolution, height * resolution); + + if (autoRound) + { + this.baseSize.width = Math.floor(this.baseSize.width); + this.baseSize.height = Math.floor(this.baseSize.height); + } + + // 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) + this.displaySize.setSize(width, height); + + this.canvas.width = this.baseSize.width; + this.canvas.height = this.baseSize.height; + + return this.refresh(previousWidth, previousHeight); + }, + + /** + * 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. + */ + resize: function (width, height) + { + var zoom = this.zoom; + var resolution = this.resolution; + var autoRound = this.autoRound; + + if (autoRound) + { + width = Math.floor(width); + height = Math.floor(height); + } + + var previousWidth = this.width; + var previousHeight = this.height; + + // The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc + this.gameSize.resize(width, height); + + // The modified game size, which is the w/h * resolution + this.baseSize.resize(width * resolution, height * resolution); + + if (autoRound) + { + this.baseSize.width = Math.floor(this.baseSize.width); + this.baseSize.height = Math.floor(this.baseSize.height); + } + + // 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) + this.displaySize.setSize((width * zoom) * resolution, (height * zoom) * resolution); + + this.canvas.width = this.baseSize.width; + this.canvas.height = this.baseSize.height; + + var style = this.canvas.style; + + var styleWidth = width * zoom; + var styleHeight = height * zoom; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + if (styleWidth !== width || styleHeight !== height) + { + style.width = styleWidth + 'px'; + style.height = styleHeight + 'px'; + } + + return this.refresh(previousWidth, previousHeight); + }, + + /** + * Sets the zoom value of the Scale Manager. + * + * @method Phaser.Scale.ScaleManager#setZoom + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + * + * @param {integer} value - The new zoom value of the game. + * + * @return {this} The Scale Manager instance. + */ + setZoom: function (value) + { + this.zoom = value; + this._resetZoom = true; + + return this.refresh(); + }, + + /** + * 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. + */ + setMaxZoom: function () + { + this.zoom = this.getMaxZoom(); + this._resetZoom = true; + + return this.refresh(); + }, + + /** + * Refreshes the internal scale values, bounds sizes and orientation checks. + * + * Once finished, dispatches the resize event. + * + * This is called automatically by the Scale Manager when the browser window size changes, + * as long as it is using a Scale Mode other than 'NONE'. + * + * @method Phaser.Scale.ScaleManager#refresh + * @fires Phaser.Scale.Events#RESIZE + * @since 3.16.0 + * + * @param {number} [previousWidth] - The previous width of the game. Only set if the gameSize has changed. + * @param {number} [previousHeight] - The previous height of the game. Only set if the gameSize has changed. + * + * @return {this} The Scale Manager instance. + */ + refresh: function (previousWidth, previousHeight) + { + if (previousWidth === undefined) { previousWidth = this.width; } + if (previousHeight === undefined) { previousHeight = this.height; } + + this.updateScale(); + this.updateBounds(); + this.updateOrientation(); + + this.displayScale.set(this.baseSize.width / this.canvasBounds.width, this.baseSize.height / this.canvasBounds.height); + + var domContainer = this.game.domContainer; + + if (domContainer) + { + this.baseSize.setCSS(domContainer); + + var canvasStyle = this.canvas.style; + var domStyle = domContainer.style; + + domStyle.transform = 'scale(' + this.displaySize.width / this.baseSize.width + ',' + this.displaySize.height / this.baseSize.height + ')'; + + domStyle.marginLeft = canvasStyle.marginLeft; + domStyle.marginTop = canvasStyle.marginTop; + } + + this.emit(Events.RESIZE, this.gameSize, this.baseSize, this.displaySize, this.resolution, previousWidth, previousHeight); + + return this; + }, + + /** + * Internal method that checks the current screen orientation, only if the internal check flag is set. + * + * If the orientation has changed it updates the orientation property and then dispatches the orientation change event. + * + * @method Phaser.Scale.ScaleManager#updateOrientation + * @fires Phaser.Scale.Events#ORIENTATION_CHANGE + * @since 3.16.0 + */ + updateOrientation: function () + { + if (this._checkOrientation) + { + this._checkOrientation = false; + + var newOrientation = GetScreenOrientation(this.width, this.height); + + if (newOrientation !== this.orientation) + { + this.orientation = newOrientation; + + this.emit(Events.ORIENTATION_CHANGE, newOrientation); + } + } + }, + + /** + * Internal method that manages updating the size components based on the scale mode. + * + * @method Phaser.Scale.ScaleManager#updateScale + * @since 3.16.0 + */ + updateScale: function () + { + var style = this.canvas.style; + + var width = this.gameSize.width; + var height = this.gameSize.height; + + var styleWidth; + var styleHeight; + + var zoom = this.zoom; + var autoRound = this.autoRound; + var resolution = 1; + + if (this.scaleMode === CONST.SCALE_MODE.NONE) + { + // No scale + this.displaySize.setSize((width * zoom) * resolution, (height * zoom) * resolution); + + styleWidth = this.displaySize.width / resolution; + styleHeight = this.displaySize.height / resolution; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + if (this._resetZoom) + { + style.width = styleWidth + 'px'; + style.height = styleHeight + 'px'; + + this._resetZoom = false; + } + } + else if (this.scaleMode === CONST.SCALE_MODE.RESIZE) + { + // Resize to match parent + + // This will constrain using min/max + this.displaySize.setSize(this.parentSize.width, this.parentSize.height); + + this.gameSize.setSize(this.displaySize.width, this.displaySize.height); + + this.baseSize.setSize(this.displaySize.width * resolution, this.displaySize.height * resolution); + + styleWidth = this.displaySize.width / resolution; + styleHeight = this.displaySize.height / resolution; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + this.canvas.width = styleWidth; + this.canvas.height = styleHeight; + } + else + { + // All other scale modes + this.displaySize.setSize(this.parentSize.width, this.parentSize.height); + + styleWidth = this.displaySize.width / resolution; + styleHeight = this.displaySize.height / resolution; + + if (autoRound) + { + styleWidth = Math.floor(styleWidth); + styleHeight = Math.floor(styleHeight); + } + + style.width = styleWidth + 'px'; + style.height = styleHeight + 'px'; + } + + // Update the parentSize in case the canvas / style change modified it + this.getParentBounds(); + + // Finally, update the centering + this.updateCenter(); + }, + + /** + * 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 {integer} The maximum possible zoom factor. At a minimum this value is always at least 1. + */ + getMaxZoom: function () + { + var zoomH = SnapFloor(this.parentSize.width, this.gameSize.width, 0, true); + var zoomV = SnapFloor(this.parentSize.height, this.gameSize.height, 0, true); + + return Math.max(Math.min(zoomH, zoomV), 1); + }, + + /** + * Calculates and updates the canvas CSS style in order to center it within the + * bounds of its parent. If you have explicitly set parent to be `null` in your + * game config then this method will likely give incorrect results unless you have called the + * `setParentSize` method first. + * + * It works by modifying the canvas CSS `marginLeft` and `marginTop` properties. + * + * If they have already been set by your own style sheet, or code, this will overwrite them. + * + * To prevent the Scale Manager from centering the canvas, either do not set the + * `autoCenter` property in your game config, or make sure it is set to `NO_CENTER`. + * + * @method Phaser.Scale.ScaleManager#updateCenter + * @since 3.16.0 + */ + updateCenter: function () + { + var autoCenter = this.autoCenter; + + if (autoCenter === CONST.CENTER.NO_CENTER) + { + return; + } + + var canvas = this.canvas; + + var style = canvas.style; + + var bounds = canvas.getBoundingClientRect(); + + // var width = parseInt(canvas.style.width, 10) || canvas.width; + // var height = parseInt(canvas.style.height, 10) || canvas.height; + + var width = bounds.width; + var height = bounds.height; + + var offsetX = Math.floor((this.parentSize.width - width) / 2); + var offsetY = Math.floor((this.parentSize.height - height) / 2); + + if (autoCenter === CONST.CENTER.CENTER_HORIZONTALLY) + { + offsetY = 0; + } + else if (autoCenter === CONST.CENTER.CENTER_VERTICALLY) + { + offsetX = 0; + } + + style.marginLeft = offsetX + 'px'; + style.marginTop = offsetY + 'px'; + }, + + /** + * Updates the `canvasBounds` rectangle to match the bounding client rectangle of the + * canvas element being used to track input events. + * + * @method Phaser.Scale.ScaleManager#updateBounds + * @since 3.16.0 + */ + updateBounds: function () + { + var bounds = this.canvasBounds; + var clientRect = this.canvas.getBoundingClientRect(); + + bounds.x = clientRect.left + (window.pageXOffset || 0) - (document.documentElement.clientLeft || 0); + bounds.y = clientRect.top + (window.pageYOffset || 0) - (document.documentElement.clientTop || 0); + bounds.width = clientRect.width; + bounds.height = clientRect.height; + }, + + /** + * Transforms the pageX value into the scaled coordinate space of the Scale Manager. + * + * @method Phaser.Scale.ScaleManager#transformX + * @since 3.16.0 + * + * @param {number} pageX - The DOM pageX value. + * + * @return {number} The translated value. + */ + transformX: function (pageX) + { + return (pageX - this.canvasBounds.left) * this.displayScale.x; + }, + + /** + * Transforms the pageY value into the scaled coordinate space of the Scale Manager. + * + * @method Phaser.Scale.ScaleManager#transformY + * @since 3.16.0 + * + * @param {number} pageY - The DOM pageY value. + * + * @return {number} The translated value. + */ + transformY: function (pageY) + { + return (pageY - this.canvasBounds.top) * this.displayScale.y; + }, + + /** + * 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 user-input gesture, such as `pointerup`. 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 `
` 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. + */ + startFullscreen: function (fullscreenOptions) + { + if (fullscreenOptions === undefined) { fullscreenOptions = { navigationUI: 'hide' }; } + + var fullscreen = this.fullscreen; + + if (!fullscreen.available) + { + this.emit(Events.FULLSCREEN_UNSUPPORTED); + + return; + } + + if (!fullscreen.active) + { + var fsTarget = this.getFullscreenTarget(); + + var fsPromise; + + if (fullscreen.keyboard) + { + fsPromise = fsTarget[fullscreen.request](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsPromise = fsTarget[fullscreen.request](fullscreenOptions); + } + + if (fsPromise) + { + fsPromise.then(this.fullscreenSuccessHandler.bind(this)).catch(this.fullscreenErrorHandler.bind(this)); + } + else if (fullscreen.active) + { + this.fullscreenSuccessHandler(); + } + else + { + this.fullscreenErrorHandler(); + } + } + }, + + /** + * The browser has successfully entered fullscreen mode. + * + * @method Phaser.Scale.ScaleManager#fullscreenSuccessHandler + * @private + * @fires Phaser.Scale.Events#ENTER_FULLSCREEN + * @fires Phaser.Scale.Events#RESIZE + * @since 3.17.0 + */ + fullscreenSuccessHandler: function () + { + this.getParentBounds(); + + this.refresh(); + + this.emit(Events.ENTER_FULLSCREEN); + }, + + /** + * The browser failed to enter fullscreen mode. + * + * @method Phaser.Scale.ScaleManager#fullscreenErrorHandler + * @private + * @fires Phaser.Scale.Events#FULLSCREEN_FAILED + * @fires Phaser.Scale.Events#RESIZE + * @since 3.17.0 + * + * @param {any} error - The DOM error event. + */ + fullscreenErrorHandler: function (error) + { + this.removeFullscreenTarget(); + + this.emit(Events.FULLSCREEN_FAILED, error); + }, + + /** + * An internal method that gets the target element that is used when entering fullscreen mode. + * + * @method Phaser.Scale.ScaleManager#getFullscreenTarget + * @since 3.16.0 + * + * @return {object} The fullscreen target element. + */ + getFullscreenTarget: function () + { + if (!this.fullscreenTarget) + { + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + + this.fullscreenTarget = fsTarget; + + this._createdFullscreenTarget = true; + } + + if (this._createdFullscreenTarget) + { + var canvasParent = this.canvas.parentNode; + + canvasParent.insertBefore(this.fullscreenTarget, this.canvas); + + this.fullscreenTarget.appendChild(this.canvas); + } + + return this.fullscreenTarget; + }, + + /** + * Removes the fullscreen target that was added to the DOM. + * + * @method Phaser.Scale.ScaleManager#removeFullscreenTarget + * @since 3.17.0 + */ + removeFullscreenTarget: function () + { + if (this._createdFullscreenTarget) + { + var fsTarget = this.fullscreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + var parent = fsTarget.parentNode; + + parent.insertBefore(this.canvas, fsTarget); + + parent.removeChild(fsTarget); + } + } + }, + + /** + * Calling this method will cancel fullscreen mode, if the browser has entered it. + * + * @method Phaser.Scale.ScaleManager#stopFullscreen + * @fires Phaser.Scale.Events#LEAVE_FULLSCREEN + * @fires Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED + * @since 3.16.0 + */ + stopFullscreen: function () + { + var fullscreen = this.fullscreen; + + if (!fullscreen.available) + { + this.emit(Events.FULLSCREEN_UNSUPPORTED); + + return false; + } + + if (fullscreen.active) + { + document[fullscreen.cancel](); + } + + this.removeFullscreenTarget(); + + // Get the parent size again as it will have changed + this.getParentBounds(); + + this.emit(Events.LEAVE_FULLSCREEN); + + this.refresh(); + }, + + /** + * Toggles the fullscreen mode. If already in fullscreen, calling this will cancel it. + * If not in fullscreen, this will request the browser to enter fullscreen mode. + * + * If the browser does not support this, a `FULLSCREEN_UNSUPPORTED` event will be emitted. + * + * This method _must_ be called from a user-input gesture, such as `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. + * + * @method Phaser.Scale.ScaleManager#toggleFullscreen + * @fires Phaser.Scale.Events#ENTER_FULLSCREEN + * @fires Phaser.Scale.Events#LEAVE_FULLSCREEN + * @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. + */ + toggleFullscreen: function (fullscreenOptions) + { + if (this.fullscreen.active) + { + this.stopFullscreen(); + } + else + { + this.startFullscreen(fullscreenOptions); + } + }, + + /** + * An internal method that starts the different DOM event listeners running. + * + * @method Phaser.Scale.ScaleManager#startListeners + * @since 3.16.0 + */ + startListeners: function () + { + var _this = this; + var listeners = this.listeners; + + listeners.orientationChange = function () + { + _this._checkOrientation = true; + _this.dirty = true; + }; + + listeners.windowResize = function () + { + _this.dirty = true; + }; + + // Only dispatched on mobile devices + window.addEventListener('orientationchange', listeners.orientationChange, false); + + window.addEventListener('resize', listeners.windowResize, false); + + if (this.fullscreen.available) + { + listeners.fullScreenChange = function (event) + { + return _this.onFullScreenChange(event); + }; + + listeners.fullScreenError = function (event) + { + return _this.onFullScreenError(event); + }; + + var vendors = [ 'webkit', 'moz', '' ]; + + vendors.forEach(function (prefix) + { + document.addEventListener(prefix + 'fullscreenchange', listeners.fullScreenChange, false); + document.addEventListener(prefix + 'fullscreenerror', listeners.fullScreenError, false); + }); + + // MS Specific + document.addEventListener('MSFullscreenChange', listeners.fullScreenChange, false); + document.addEventListener('MSFullscreenError', listeners.fullScreenError, false); + } + }, + + /** + * Triggered when a fullscreenchange event is dispatched by the DOM. + * + * @method Phaser.Scale.ScaleManager#onFullScreenChange + * @since 3.16.0 + */ + onFullScreenChange: function () + { + // They pressed ESC while in fullscreen mode + if (!(document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement || document.mozFullScreenElement)) + { + this.stopFullscreen(); + } + }, + + /** + * Triggered when a fullscreenerror event is dispatched by the DOM. + * + * @method Phaser.Scale.ScaleManager#onFullScreenError + * @since 3.16.0 + */ + onFullScreenError: function () + { + this.removeFullscreenTarget(); + }, + + /** + * Internal method, called automatically by the game step. + * Monitors the elapsed time and resize interval to see if a parent bounds check needs to take place. + * + * @method Phaser.Scale.ScaleManager#step + * @since 3.16.0 + * + * @param {number} time - The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). + * @param {number} delta - The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. + */ + step: function (time, delta) + { + if (!this.parent) + { + return; + } + + this._lastCheck += delta; + + if (this.dirty || this._lastCheck > this.resizeInterval) + { + // Returns true if the parent bounds have changed size + if (this.getParentBounds()) + { + this.refresh(); + } + + this.dirty = false; + this._lastCheck = 0; + } + }, + + /** + * Stops all DOM event listeners. + * + * @method Phaser.Scale.ScaleManager#stopListeners + * @since 3.16.0 + */ + stopListeners: function () + { + var listeners = this.listeners; + + window.removeEventListener('orientationchange', listeners.orientationChange, false); + window.removeEventListener('resize', listeners.windowResize, false); + + var vendors = [ 'webkit', 'moz', '' ]; + + vendors.forEach(function (prefix) + { + document.removeEventListener(prefix + 'fullscreenchange', listeners.fullScreenChange, false); + document.removeEventListener(prefix + 'fullscreenerror', listeners.fullScreenError, false); + }); + + // MS Specific + document.removeEventListener('MSFullscreenChange', listeners.fullScreenChange, false); + document.removeEventListener('MSFullscreenError', listeners.fullScreenError, false); + }, + + /** + * Destroys this Scale Manager, releasing all references to external resources. + * Once destroyed, the Scale Manager cannot be used again. + * + * @method Phaser.Scale.ScaleManager#destroy + * @since 3.16.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.stopListeners(); + + this.game = null; + this.canvas = null; + this.canvasBounds = null; + this.parent = null; + this.fullscreenTarget = null; + + this.parentSize.destroy(); + this.gameSize.destroy(); + this.baseSize.destroy(); + this.displaySize.destroy(); + }, + + /** + * Is the browser currently in fullscreen mode or not? + * + * @name Phaser.Scale.ScaleManager#isFullscreen + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isFullscreen: { + + get: function () + { + return this.fullscreen.active; + } + + }, + + /** + * The game width. + * + * This is typically the size given in the game configuration. + * + * @name Phaser.Scale.ScaleManager#width + * @type {number} + * @readonly + * @since 3.16.0 + */ + width: { + + get: function () + { + return this.gameSize.width; + } + + }, + + /** + * The game height. + * + * This is typically the size given in the game configuration. + * + * @name Phaser.Scale.ScaleManager#height + * @type {number} + * @readonly + * @since 3.16.0 + */ + height: { + + get: function () + { + return this.gameSize.height; + } + + }, + + /** + * Is the device in a portrait orientation as reported by the Orientation API? + * This value is usually only available on mobile devices. + * + * @name Phaser.Scale.ScaleManager#isPortrait + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isPortrait: { + + get: function () + { + return (this.orientation === CONST.ORIENTATION.PORTRAIT); + } + + }, + + /** + * Is the device in a landscape orientation as reported by the Orientation API? + * This value is usually only available on mobile devices. + * + * @name Phaser.Scale.ScaleManager#isLandscape + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isLandscape: { + + get: function () + { + return (this.orientation === CONST.ORIENTATION.LANDSCAPE); + } + + }, + + /** + * Are the game dimensions portrait? (i.e. taller than they are wide) + * + * This is different to the device itself being in a portrait orientation. + * + * @name Phaser.Scale.ScaleManager#isGamePortrait + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isGamePortrait: { + + get: function () + { + return (this.height > this.width); + } + + }, + + /** + * Are the game dimensions landscape? (i.e. wider than they are tall) + * + * This is different to the device itself being in a landscape orientation. + * + * @name Phaser.Scale.ScaleManager#isGameLandscape + * @type {boolean} + * @readonly + * @since 3.16.0 + */ + isGameLandscape: { + + get: function () + { + return (this.width > this.height); + } + + } + +}); + +module.exports = ScaleManager; diff --git a/src/scale/const/CENTER_CONST.js b/src/scale/const/CENTER_CONST.js index 46f89c540..25fca6024 100644 --- a/src/scale/const/CENTER_CONST.js +++ b/src/scale/const/CENTER_CONST.js @@ -1,80 +1,80 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Scale Manager constants for centering the game canvas. - * - * @namespace Phaser.Scale.Center - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -/** - * Phaser Scale Manager constants for centering the game canvas. - * - * To find out what each mode does please see [Phaser.Scale.Center]{@link Phaser.Scale.Center}. - * - * @typedef {Phaser.Scale.Center} Phaser.Scale.CenterType - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -module.exports = { - - /** - * The game canvas is not centered within the parent by Phaser. - * You can still center it yourself via CSS. - * - * @name Phaser.Scale.Center.NO_CENTER - * @type {integer} - * @const - * @since 3.16.0 - */ - NO_CENTER: 0, - - /** - * The game canvas is centered both horizontally and vertically within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - * - * @name Phaser.Scale.Center.CENTER_BOTH - * @type {integer} - * @const - * @since 3.16.0 - */ - CENTER_BOTH: 1, - - /** - * The game canvas is centered horizontally within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - * - * @name Phaser.Scale.Center.CENTER_HORIZONTALLY - * @type {integer} - * @const - * @since 3.16.0 - */ - CENTER_HORIZONTALLY: 2, - - /** - * The game canvas is centered both vertically within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - * - * @name Phaser.Scale.Center.CENTER_VERTICALLY - * @type {integer} - * @const - * @since 3.16.0 - */ - CENTER_VERTICALLY: 3 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for centering the game canvas. + * + * @namespace Phaser.Scale.Center + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for centering the game canvas. + * + * To find out what each mode does please see [Phaser.Scale.Center]{@link Phaser.Scale.Center}. + * + * @typedef {Phaser.Scale.Center} Phaser.Scale.CenterType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * The game canvas is not centered within the parent by Phaser. + * You can still center it yourself via CSS. + * + * @name Phaser.Scale.Center.NO_CENTER + * @type {integer} + * @const + * @since 3.16.0 + */ + NO_CENTER: 0, + + /** + * The game canvas is centered both horizontally and vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + * + * @name Phaser.Scale.Center.CENTER_BOTH + * @type {integer} + * @const + * @since 3.16.0 + */ + CENTER_BOTH: 1, + + /** + * The game canvas is centered horizontally within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + * + * @name Phaser.Scale.Center.CENTER_HORIZONTALLY + * @type {integer} + * @const + * @since 3.16.0 + */ + CENTER_HORIZONTALLY: 2, + + /** + * The game canvas is centered both vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + * + * @name Phaser.Scale.Center.CENTER_VERTICALLY + * @type {integer} + * @const + * @since 3.16.0 + */ + CENTER_VERTICALLY: 3 + +}; diff --git a/src/scale/const/ORIENTATION_CONST.js b/src/scale/const/ORIENTATION_CONST.js index a166acd02..fcae6f2ff 100644 --- a/src/scale/const/ORIENTATION_CONST.js +++ b/src/scale/const/ORIENTATION_CONST.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Scale Manager constants for orientation. - * - * @namespace Phaser.Scale.Orientation - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -/** - * Phaser Scale Manager constants for orientation. - * - * To find out what each mode does please see [Phaser.Scale.Orientation]{@link Phaser.Scale.Orientation}. - * - * @typedef {Phaser.Scale.Orientation} Phaser.Scale.OrientationType - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -module.exports = { - - /** - * A landscape orientation. - * - * @name Phaser.Scale.Orientation.LANDSCAPE - * @type {string} - * @const - * @since 3.16.0 - */ - LANDSCAPE: 'landscape-primary', - - /** - * A portrait orientation. - * - * @name Phaser.Scale.Orientation.PORTRAIT - * @type {string} - * @const - * @since 3.16.0 - */ - PORTRAIT: 'portrait-primary' - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for orientation. + * + * @namespace Phaser.Scale.Orientation + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for orientation. + * + * To find out what each mode does please see [Phaser.Scale.Orientation]{@link Phaser.Scale.Orientation}. + * + * @typedef {Phaser.Scale.Orientation} Phaser.Scale.OrientationType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * A landscape orientation. + * + * @name Phaser.Scale.Orientation.LANDSCAPE + * @type {string} + * @const + * @since 3.16.0 + */ + LANDSCAPE: 'landscape-primary', + + /** + * A portrait orientation. + * + * @name Phaser.Scale.Orientation.PORTRAIT + * @type {string} + * @const + * @since 3.16.0 + */ + PORTRAIT: 'portrait-primary' + +}; diff --git a/src/scale/const/SCALE_MODE_CONST.js b/src/scale/const/SCALE_MODE_CONST.js index 1924f110e..f63f0bc74 100644 --- a/src/scale/const/SCALE_MODE_CONST.js +++ b/src/scale/const/SCALE_MODE_CONST.js @@ -1,92 +1,92 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Scale Manager constants for the different scale modes available. - * - * @namespace Phaser.Scale.ScaleModes - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -/** - * Phaser Scale Manager constants for the different scale modes available. - * - * To find out what each mode does please see [Phaser.Scale.ScaleModes]{@link Phaser.Scale.ScaleModes}. - * - * @typedef {Phaser.Scale.ScaleModes} Phaser.Scale.ScaleModeType - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -module.exports = { - - /** - * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it - * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need - * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. - * - * @name Phaser.Scale.ScaleModes.NONE - * @type {integer} - * @const - * @since 3.16.0 - */ - NONE: 0, - - /** - * The height is automatically adjusted based on the width. - * - * @name Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT - * @type {integer} - * @const - * @since 3.16.0 - */ - WIDTH_CONTROLS_HEIGHT: 1, - - /** - * The width is automatically adjusted based on the height. - * - * @name Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH - * @type {integer} - * @const - * @since 3.16.0 - */ - HEIGHT_CONTROLS_WIDTH: 2, - - /** - * 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. - * - * @name Phaser.Scale.ScaleModes.FIT - * @type {integer} - * @const - * @since 3.16.0 - */ - FIT: 3, - - /** - * 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. - * - * @name Phaser.Scale.ScaleModes.ENVELOP - * @type {integer} - * @const - * @since 3.16.0 - */ - ENVELOP: 4, - - /** - * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. - * - * @name Phaser.Scale.ScaleModes.RESIZE - * @type {integer} - * @const - * @since 3.16.0 - */ - RESIZE: 5 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for the different scale modes available. + * + * @namespace Phaser.Scale.ScaleModes + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for the different scale modes available. + * + * To find out what each mode does please see [Phaser.Scale.ScaleModes]{@link Phaser.Scale.ScaleModes}. + * + * @typedef {Phaser.Scale.ScaleModes} Phaser.Scale.ScaleModeType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it + * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need + * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. + * + * @name Phaser.Scale.ScaleModes.NONE + * @type {integer} + * @const + * @since 3.16.0 + */ + NONE: 0, + + /** + * The height is automatically adjusted based on the width. + * + * @name Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT + * @type {integer} + * @const + * @since 3.16.0 + */ + WIDTH_CONTROLS_HEIGHT: 1, + + /** + * The width is automatically adjusted based on the height. + * + * @name Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH + * @type {integer} + * @const + * @since 3.16.0 + */ + HEIGHT_CONTROLS_WIDTH: 2, + + /** + * 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. + * + * @name Phaser.Scale.ScaleModes.FIT + * @type {integer} + * @const + * @since 3.16.0 + */ + FIT: 3, + + /** + * 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. + * + * @name Phaser.Scale.ScaleModes.ENVELOP + * @type {integer} + * @const + * @since 3.16.0 + */ + ENVELOP: 4, + + /** + * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. + * + * @name Phaser.Scale.ScaleModes.RESIZE + * @type {integer} + * @const + * @since 3.16.0 + */ + RESIZE: 5 + +}; diff --git a/src/scale/const/ZOOM_CONST.js b/src/scale/const/ZOOM_CONST.js index c2e57b064..aa8c298c6 100644 --- a/src/scale/const/ZOOM_CONST.js +++ b/src/scale/const/ZOOM_CONST.js @@ -1,68 +1,68 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Phaser Scale Manager constants for zoom modes. - * - * @namespace Phaser.Scale.Zoom - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -/** - * Phaser Scale Manager constants for zoom modes. - * - * To find out what each mode does please see [Phaser.Scale.Zoom]{@link Phaser.Scale.Zoom}. - * - * @typedef {Phaser.Scale.Zoom} Phaser.Scale.ZoomType - * @memberof Phaser.Scale - * @since 3.16.0 - */ - -module.exports = { - - /** - * The game canvas will not be zoomed by Phaser. - * - * @name Phaser.Scale.Zoom.NO_ZOOM - * @type {integer} - * @const - * @since 3.16.0 - */ - NO_ZOOM: 1, - - /** - * The game canvas will be 2x zoomed by Phaser. - * - * @name Phaser.Scale.Zoom.ZOOM_2X - * @type {integer} - * @const - * @since 3.16.0 - */ - ZOOM_2X: 2, - - /** - * The game canvas will be 4x zoomed by Phaser. - * - * @name Phaser.Scale.Zoom.ZOOM_4X - * @type {integer} - * @const - * @since 3.16.0 - */ - ZOOM_4X: 4, - - /** - * 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 {integer} - * @const - * @since 3.16.0 - */ - MAX_ZOOM: -1 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Phaser Scale Manager constants for zoom modes. + * + * @namespace Phaser.Scale.Zoom + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +/** + * Phaser Scale Manager constants for zoom modes. + * + * To find out what each mode does please see [Phaser.Scale.Zoom]{@link Phaser.Scale.Zoom}. + * + * @typedef {Phaser.Scale.Zoom} Phaser.Scale.ZoomType + * @memberof Phaser.Scale + * @since 3.16.0 + */ + +module.exports = { + + /** + * The game canvas will not be zoomed by Phaser. + * + * @name Phaser.Scale.Zoom.NO_ZOOM + * @type {integer} + * @const + * @since 3.16.0 + */ + NO_ZOOM: 1, + + /** + * The game canvas will be 2x zoomed by Phaser. + * + * @name Phaser.Scale.Zoom.ZOOM_2X + * @type {integer} + * @const + * @since 3.16.0 + */ + ZOOM_2X: 2, + + /** + * The game canvas will be 4x zoomed by Phaser. + * + * @name Phaser.Scale.Zoom.ZOOM_4X + * @type {integer} + * @const + * @since 3.16.0 + */ + ZOOM_4X: 4, + + /** + * 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 {integer} + * @const + * @since 3.16.0 + */ + MAX_ZOOM: -1 + +}; diff --git a/src/scale/const/index.js b/src/scale/const/index.js index 4513124cb..7c5257f38 100644 --- a/src/scale/const/index.js +++ b/src/scale/const/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = { - - CENTER: require('./CENTER_CONST'), - ORIENTATION: require('./ORIENTATION_CONST'), - SCALE_MODE: require('./SCALE_MODE_CONST'), - ZOOM: require('./ZOOM_CONST') - -}; - -module.exports = CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = { + + CENTER: require('./CENTER_CONST'), + ORIENTATION: require('./ORIENTATION_CONST'), + SCALE_MODE: require('./SCALE_MODE_CONST'), + ZOOM: require('./ZOOM_CONST') + +}; + +module.exports = CONST; diff --git a/src/scale/events/ENTER_FULLSCREEN_EVENT.js b/src/scale/events/ENTER_FULLSCREEN_EVENT.js index b0762a88a..45bef1b5a 100644 --- a/src/scale/events/ENTER_FULLSCREEN_EVENT.js +++ b/src/scale/events/ENTER_FULLSCREEN_EVENT.js @@ -1,13 +1,13 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scale Manager has successfully entered fullscreen mode. - * - * @event Phaser.Scale.Events#ENTER_FULLSCREEN - * @since 3.16.1 - */ -module.exports = 'enterfullscreen'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager has successfully entered fullscreen mode. + * + * @event Phaser.Scale.Events#ENTER_FULLSCREEN + * @since 3.16.1 + */ +module.exports = 'enterfullscreen'; diff --git a/src/scale/events/FULLSCREEN_FAILED_EVENT.js b/src/scale/events/FULLSCREEN_FAILED_EVENT.js index aea4c6072..bace47fbc 100644 --- a/src/scale/events/FULLSCREEN_FAILED_EVENT.js +++ b/src/scale/events/FULLSCREEN_FAILED_EVENT.js @@ -1,13 +1,13 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scale Manager tried to enter fullscreen mode but failed. - * - * @event Phaser.Scale.Events#FULLSCREEN_FAILED - * @since 3.17.0 - */ -module.exports = 'fullscreenfailed'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager tried to enter fullscreen mode but failed. + * + * @event Phaser.Scale.Events#FULLSCREEN_FAILED + * @since 3.17.0 + */ +module.exports = 'fullscreenfailed'; diff --git a/src/scale/events/FULLSCREEN_UNSUPPORTED_EVENT.js b/src/scale/events/FULLSCREEN_UNSUPPORTED_EVENT.js index 195eb4c64..ad53c25ab 100644 --- a/src/scale/events/FULLSCREEN_UNSUPPORTED_EVENT.js +++ b/src/scale/events/FULLSCREEN_UNSUPPORTED_EVENT.js @@ -1,13 +1,13 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scale Manager tried to enter fullscreen mode, but it is unsupported by the browser. - * - * @event Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED - * @since 3.16.1 - */ -module.exports = 'fullscreenunsupported'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager tried to enter fullscreen mode, but it is unsupported by the browser. + * + * @event Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED + * @since 3.16.1 + */ +module.exports = 'fullscreenunsupported'; diff --git a/src/scale/events/LEAVE_FULLSCREEN_EVENT.js b/src/scale/events/LEAVE_FULLSCREEN_EVENT.js index e2bac6560..5a93a2537 100644 --- a/src/scale/events/LEAVE_FULLSCREEN_EVENT.js +++ b/src/scale/events/LEAVE_FULLSCREEN_EVENT.js @@ -1,14 +1,14 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scale Manager was in fullscreen mode, but has since left, either directly via game code, - * or via a user gestured, such as pressing the ESC key. - * - * @event Phaser.Scale.Events#LEAVE_FULLSCREEN - * @since 3.16.1 - */ -module.exports = 'leavefullscreen'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager was in fullscreen mode, but has since left, either directly via game code, + * or via a user gestured, such as pressing the ESC key. + * + * @event Phaser.Scale.Events#LEAVE_FULLSCREEN + * @since 3.16.1 + */ +module.exports = 'leavefullscreen'; diff --git a/src/scale/events/ORIENTATION_CHANGE_EVENT.js b/src/scale/events/ORIENTATION_CHANGE_EVENT.js index c83e98d39..10e1515c0 100644 --- a/src/scale/events/ORIENTATION_CHANGE_EVENT.js +++ b/src/scale/events/ORIENTATION_CHANGE_EVENT.js @@ -1,15 +1,15 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scale Manager Orientation Change Event. - * - * @event Phaser.Scale.Events#ORIENTATION_CHANGE - * @since 3.16.1 - * - * @param {string} orientation - - */ -module.exports = 'orientationchange'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager Orientation Change Event. + * + * @event Phaser.Scale.Events#ORIENTATION_CHANGE + * @since 3.16.1 + * + * @param {string} orientation - + */ +module.exports = 'orientationchange'; diff --git a/src/scale/events/RESIZE_EVENT.js b/src/scale/events/RESIZE_EVENT.js index cbee53336..8d040a243 100644 --- a/src/scale/events/RESIZE_EVENT.js +++ b/src/scale/events/RESIZE_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scale Manager Resize Event. - * - * This event is dispatched whenever the Scale Manager detects a resize event from the browser. - * It sends three parameters to the callback, each of them being Size components. You can read - * the `width`, `height`, `aspectRatio` and other properties of these components to help with - * scaling your own game content. - * - * @event Phaser.Scale.Events#RESIZE - * @since 3.16.1 - * - * @param {Phaser.Structs.Size} gameSize - A reference to the Game Size component. This is the un-scaled size of your game canvas. - * @param {Phaser.Structs.Size} baseSize - A reference to the Base Size component. This is the game size multiplied by resolution. - * @param {Phaser.Structs.Size} displaySize - A reference to the Display Size component. This is the scaled canvas size, after applying zoom and scale mode. - * @param {number} resolution - The current resolution. Defaults to 1 at the moment. - * @param {number} previousWidth - If the `gameSize` has changed, this value contains its previous width, otherwise it contains the current width. - * @param {number} previousHeight - If the `gameSize` has changed, this value contains its previous height, otherwise it contains the current height. - */ -module.exports = 'resize'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scale Manager Resize Event. + * + * This event is dispatched whenever the Scale Manager detects a resize event from the browser. + * It sends three parameters to the callback, each of them being Size components. You can read + * the `width`, `height`, `aspectRatio` and other properties of these components to help with + * scaling your own game content. + * + * @event Phaser.Scale.Events#RESIZE + * @since 3.16.1 + * + * @param {Phaser.Structs.Size} gameSize - A reference to the Game Size component. This is the un-scaled size of your game canvas. + * @param {Phaser.Structs.Size} baseSize - A reference to the Base Size component. This is the game size multiplied by resolution. + * @param {Phaser.Structs.Size} displaySize - A reference to the Display Size component. This is the scaled canvas size, after applying zoom and scale mode. + * @param {number} resolution - The current resolution. Defaults to 1 at the moment. + * @param {number} previousWidth - If the `gameSize` has changed, this value contains its previous width, otherwise it contains the current width. + * @param {number} previousHeight - If the `gameSize` has changed, this value contains its previous height, otherwise it contains the current height. + */ +module.exports = 'resize'; diff --git a/src/scale/events/index.js b/src/scale/events/index.js index b6e206074..d826e5de0 100644 --- a/src/scale/events/index.js +++ b/src/scale/events/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Scale.Events - */ - -module.exports = { - - ENTER_FULLSCREEN: require('./ENTER_FULLSCREEN_EVENT'), - FULLSCREEN_FAILED: require('./FULLSCREEN_FAILED_EVENT'), - FULLSCREEN_UNSUPPORTED: require('./FULLSCREEN_UNSUPPORTED_EVENT'), - LEAVE_FULLSCREEN: require('./LEAVE_FULLSCREEN_EVENT'), - ORIENTATION_CHANGE: require('./ORIENTATION_CHANGE_EVENT'), - RESIZE: require('./RESIZE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Scale.Events + */ + +module.exports = { + + ENTER_FULLSCREEN: require('./ENTER_FULLSCREEN_EVENT'), + FULLSCREEN_FAILED: require('./FULLSCREEN_FAILED_EVENT'), + FULLSCREEN_UNSUPPORTED: require('./FULLSCREEN_UNSUPPORTED_EVENT'), + LEAVE_FULLSCREEN: require('./LEAVE_FULLSCREEN_EVENT'), + ORIENTATION_CHANGE: require('./ORIENTATION_CHANGE_EVENT'), + RESIZE: require('./RESIZE_EVENT') + +}; diff --git a/src/scale/index.js b/src/scale/index.js index 5455feb2e..c2463da60 100644 --- a/src/scale/index.js +++ b/src/scale/index.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Extend = require('../utils/object/Extend'); -var CONST = require('./const'); - -/** - * @namespace Phaser.Scale - * - * @borrows Phaser.Scale.Center.NO_CENTER as NO_CENTER - * @borrows Phaser.Scale.Center.CENTER_BOTH as CENTER_BOTH - * @borrows Phaser.Scale.Center.CENTER_HORIZONTALLY as CENTER_HORIZONTALLY - * @borrows Phaser.Scale.Center.CENTER_VERTICALLY as CENTER_VERTICALLY - * - * @borrows Phaser.Scale.Orientation.LANDSCAPE as LANDSCAPE - * @borrows Phaser.Scale.Orientation.PORTRAIT as PORTRAIT - * - * @borrows Phaser.Scale.ScaleModes.NONE as NONE - * @borrows Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT as WIDTH_CONTROLS_HEIGHT - * @borrows Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH as HEIGHT_CONTROLS_WIDTH - * @borrows Phaser.Scale.ScaleModes.FIT as FIT - * @borrows Phaser.Scale.ScaleModes.ENVELOP as ENVELOP - * @borrows Phaser.Scale.ScaleModes.RESIZE as RESIZE - * - * @borrows Phaser.Scale.Zoom.NO_ZOOM as NO_ZOOM - * @borrows Phaser.Scale.Zoom.ZOOM_2X as ZOOM_2X - * @borrows Phaser.Scale.Zoom.ZOOM_4X as ZOOM_4X - * @borrows Phaser.Scale.Zoom.MAX_ZOOM as MAX_ZOOM - */ - -var Scale = { - - Center: require('./const/CENTER_CONST'), - Events: require('./events'), - Orientation: require('./const/ORIENTATION_CONST'), - ScaleManager: require('./ScaleManager'), - ScaleModes: require('./const/SCALE_MODE_CONST'), - Zoom: require('./const/ZOOM_CONST') - -}; - -Scale = Extend(false, Scale, CONST.CENTER); -Scale = Extend(false, Scale, CONST.ORIENTATION); -Scale = Extend(false, Scale, CONST.SCALE_MODE); -Scale = Extend(false, Scale, CONST.ZOOM); - -module.exports = Scale; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = require('../utils/object/Extend'); +var CONST = require('./const'); + +/** + * @namespace Phaser.Scale + * + * @borrows Phaser.Scale.Center.NO_CENTER as NO_CENTER + * @borrows Phaser.Scale.Center.CENTER_BOTH as CENTER_BOTH + * @borrows Phaser.Scale.Center.CENTER_HORIZONTALLY as CENTER_HORIZONTALLY + * @borrows Phaser.Scale.Center.CENTER_VERTICALLY as CENTER_VERTICALLY + * + * @borrows Phaser.Scale.Orientation.LANDSCAPE as LANDSCAPE + * @borrows Phaser.Scale.Orientation.PORTRAIT as PORTRAIT + * + * @borrows Phaser.Scale.ScaleModes.NONE as NONE + * @borrows Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT as WIDTH_CONTROLS_HEIGHT + * @borrows Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH as HEIGHT_CONTROLS_WIDTH + * @borrows Phaser.Scale.ScaleModes.FIT as FIT + * @borrows Phaser.Scale.ScaleModes.ENVELOP as ENVELOP + * @borrows Phaser.Scale.ScaleModes.RESIZE as RESIZE + * + * @borrows Phaser.Scale.Zoom.NO_ZOOM as NO_ZOOM + * @borrows Phaser.Scale.Zoom.ZOOM_2X as ZOOM_2X + * @borrows Phaser.Scale.Zoom.ZOOM_4X as ZOOM_4X + * @borrows Phaser.Scale.Zoom.MAX_ZOOM as MAX_ZOOM + */ + +var Scale = { + + Center: require('./const/CENTER_CONST'), + Events: require('./events'), + Orientation: require('./const/ORIENTATION_CONST'), + ScaleManager: require('./ScaleManager'), + ScaleModes: require('./const/SCALE_MODE_CONST'), + Zoom: require('./const/ZOOM_CONST') + +}; + +Scale = Extend(false, Scale, CONST.CENTER); +Scale = Extend(false, Scale, CONST.ORIENTATION); +Scale = Extend(false, Scale, CONST.SCALE_MODE); +Scale = Extend(false, Scale, CONST.ZOOM); + +module.exports = Scale; diff --git a/src/scene/GetPhysicsPlugins.js b/src/scene/GetPhysicsPlugins.js index d12aca86c..76f2ee245 100644 --- a/src/scene/GetPhysicsPlugins.js +++ b/src/scene/GetPhysicsPlugins.js @@ -1,56 +1,56 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../utils/object/GetFastValue'); -var UppercaseFirst = require('../utils/string/UppercaseFirst'); - -/** - * Builds an array of which physics plugins should be activated for the given Scene. - * - * @function Phaser.Scenes.GetPhysicsPlugins - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - The scene system to get the physics systems of. - * - * @return {array} An array of Physics systems to start for this Scene. - */ -var GetPhysicsPlugins = function (sys) -{ - var defaultSystem = sys.game.config.defaultPhysicsSystem; - var sceneSystems = GetFastValue(sys.settings, 'physics', false); - - if (!defaultSystem && !sceneSystems) - { - // No default physics system or systems in this scene - return; - } - - // Let's build the systems array - var output = []; - - if (defaultSystem) - { - output.push(UppercaseFirst(defaultSystem + 'Physics')); - } - - if (sceneSystems) - { - for (var key in sceneSystems) - { - key = UppercaseFirst(key.concat('Physics')); - - if (output.indexOf(key) === -1) - { - output.push(key); - } - } - } - - // An array of Physics systems to start for this Scene - return output; -}; - -module.exports = GetPhysicsPlugins; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../utils/object/GetFastValue'); +var UppercaseFirst = require('../utils/string/UppercaseFirst'); + +/** + * Builds an array of which physics plugins should be activated for the given Scene. + * + * @function Phaser.Scenes.GetPhysicsPlugins + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - The scene system to get the physics systems of. + * + * @return {array} An array of Physics systems to start for this Scene. + */ +var GetPhysicsPlugins = function (sys) +{ + var defaultSystem = sys.game.config.defaultPhysicsSystem; + var sceneSystems = GetFastValue(sys.settings, 'physics', false); + + if (!defaultSystem && !sceneSystems) + { + // No default physics system or systems in this scene + return; + } + + // Let's build the systems array + var output = []; + + if (defaultSystem) + { + output.push(UppercaseFirst(defaultSystem + 'Physics')); + } + + if (sceneSystems) + { + for (var key in sceneSystems) + { + key = UppercaseFirst(key.concat('Physics')); + + if (output.indexOf(key) === -1) + { + output.push(key); + } + } + } + + // An array of Physics systems to start for this Scene + return output; +}; + +module.exports = GetPhysicsPlugins; diff --git a/src/scene/GetScenePlugins.js b/src/scene/GetScenePlugins.js index d3b3fd16b..2b6f3d20c 100644 --- a/src/scene/GetScenePlugins.js +++ b/src/scene/GetScenePlugins.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../utils/object/GetFastValue'); - -/** - * Builds an array of which plugins (not including physics plugins) should be activated for the given Scene. - * - * @function Phaser.Scenes.GetScenePlugins - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - The Scene Systems object to check for plugins. - * - * @return {array} An array of all plugins which should be activated, either the default ones or the ones configured in the Scene Systems object. - */ -var GetScenePlugins = function (sys) -{ - var defaultPlugins = sys.plugins.getDefaultScenePlugins(); - - var scenePlugins = GetFastValue(sys.settings, 'plugins', false); - - // Scene Plugins always override Default Plugins - if (Array.isArray(scenePlugins)) - { - return scenePlugins; - } - else if (defaultPlugins) - { - return defaultPlugins; - } - else - { - // No default plugins or plugins in this scene - return []; - } -}; - -module.exports = GetScenePlugins; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../utils/object/GetFastValue'); + +/** + * Builds an array of which plugins (not including physics plugins) should be activated for the given Scene. + * + * @function Phaser.Scenes.GetScenePlugins + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - The Scene Systems object to check for plugins. + * + * @return {array} An array of all plugins which should be activated, either the default ones or the ones configured in the Scene Systems object. + */ +var GetScenePlugins = function (sys) +{ + var defaultPlugins = sys.plugins.getDefaultScenePlugins(); + + var scenePlugins = GetFastValue(sys.settings, 'plugins', false); + + // Scene Plugins always override Default Plugins + if (Array.isArray(scenePlugins)) + { + return scenePlugins; + } + else if (defaultPlugins) + { + return defaultPlugins; + } + else + { + // No default plugins or plugins in this scene + return []; + } +}; + +module.exports = GetScenePlugins; diff --git a/src/scene/InjectionMap.js b/src/scene/InjectionMap.js index 1d5cec1d5..fcef02c58 100644 --- a/src/scene/InjectionMap.js +++ b/src/scene/InjectionMap.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// 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' -// } -// }; - -var InjectionMap = { - - game: 'game', - - anims: 'anims', - cache: 'cache', - plugins: 'plugins', - registry: 'registry', - scale: 'scale', - sound: 'sound', - textures: 'textures', - - events: 'events', - cameras: 'cameras', - add: 'add', - make: 'make', - scenePlugin: 'scene', - displayList: 'children', - lights: 'lights', - - data: 'data', - input: 'input', - load: 'load', - time: 'time', - tweens: 'tweens', - - arcadePhysics: 'physics', - impactPhysics: 'impact', - matterPhysics: 'matter' - -}; - -if (typeof PLUGIN_CAMERA3D) -{ - InjectionMap.cameras3d = 'cameras3d'; -} - -if (typeof PLUGIN_FBINSTANT) -{ - InjectionMap.facebook = 'facebook'; -} - -module.exports = InjectionMap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// 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' +// } +// }; + +var InjectionMap = { + + game: 'game', + + anims: 'anims', + cache: 'cache', + plugins: 'plugins', + registry: 'registry', + scale: 'scale', + sound: 'sound', + textures: 'textures', + + events: 'events', + cameras: 'cameras', + add: 'add', + make: 'make', + scenePlugin: 'scene', + displayList: 'children', + lights: 'lights', + + data: 'data', + input: 'input', + load: 'load', + time: 'time', + tweens: 'tweens', + + arcadePhysics: 'physics', + impactPhysics: 'impact', + matterPhysics: 'matter' + +}; + +if (typeof PLUGIN_CAMERA3D) +{ + InjectionMap.cameras3d = 'cameras3d'; +} + +if (typeof PLUGIN_FBINSTANT) +{ + InjectionMap.facebook = 'facebook'; +} + +module.exports = InjectionMap; diff --git a/src/scene/Scene.js b/src/scene/Scene.js index 6818d3956..8f9617cc5 100644 --- a/src/scene/Scene.js +++ b/src/scene/Scene.js @@ -1,290 +1,290 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Systems = require('./Systems'); - -/** - * @classdesc - * A base Phaser.Scene class which can be extended for your own use. - * - * You can also define the optional methods {@link Phaser.Types.Scenes.SceneInitCallback init()}, {@link Phaser.Types.Scenes.ScenePreloadCallback preload()}, and {@link Phaser.Types.Scenes.SceneCreateCallback create()}. - * - * @class Scene - * @memberof Phaser - * @constructor - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - Scene specific configuration settings. - */ -var Scene = new Class({ - - initialize: - - function Scene (config) - { - /** - * The Scene Systems. You must never overwrite this property, or all hell will break lose. - * - * @name Phaser.Scene#sys - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.sys = new Systems(this, config); - - /** - * A reference to the Phaser.Game instance. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game; - - /** - * A reference to the global Animation Manager. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#anims - * @type {Phaser.Animations.AnimationManager} - * @since 3.0.0 - */ - this.anims; - - /** - * A reference to the global Cache. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#cache - * @type {Phaser.Cache.CacheManager} - * @since 3.0.0 - */ - this.cache; - - /** - * A reference to the game level Data Manager. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#registry - * @type {Phaser.Data.DataManager} - * @since 3.0.0 - */ - this.registry; - - /** - * A reference to the Sound Manager. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#sound - * @type {Phaser.Sound.BaseSoundManager} - * @since 3.0.0 - */ - this.sound; - - /** - * A reference to the Texture Manager. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#textures - * @type {Phaser.Textures.TextureManager} - * @since 3.0.0 - */ - this.textures; - - /** - * A scene level Event Emitter. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events; - - /** - * A scene level Camera System. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#cameras - * @type {Phaser.Cameras.Scene2D.CameraManager} - * @since 3.0.0 - */ - this.cameras; - - /** - * A scene level Game Object Factory. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#add - * @type {Phaser.GameObjects.GameObjectFactory} - * @since 3.0.0 - */ - this.add; - - /** - * A scene level Game Object Creator. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#make - * @type {Phaser.GameObjects.GameObjectCreator} - * @since 3.0.0 - */ - this.make; - - /** - * A reference to the Scene Manager Plugin. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#scene - * @type {Phaser.Scenes.ScenePlugin} - * @since 3.0.0 - */ - this.scene; - - /** - * A scene level Game Object Display List. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#children - * @type {Phaser.GameObjects.DisplayList} - * @since 3.0.0 - */ - this.children; - - /** - * A scene level Lights Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#lights - * @type {Phaser.GameObjects.LightsManager} - * @since 3.0.0 - */ - this.lights; - - /** - * A scene level Data Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#data - * @type {Phaser.Data.DataManager} - * @since 3.0.0 - */ - this.data; - - /** - * A scene level Input Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#input - * @type {Phaser.Input.InputPlugin} - * @since 3.0.0 - */ - this.input; - - /** - * A scene level Loader Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#load - * @type {Phaser.Loader.LoaderPlugin} - * @since 3.0.0 - */ - this.load; - - /** - * A scene level Time and Clock Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#time - * @type {Phaser.Time.Clock} - * @since 3.0.0 - */ - this.time; - - /** - * A scene level Tween Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - * - * @name Phaser.Scene#tweens - * @type {Phaser.Tweens.TweenManager} - * @since 3.0.0 - */ - this.tweens; - - /** - * A scene level Arcade Physics Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - * - * @name Phaser.Scene#physics - * @type {Phaser.Physics.Arcade.ArcadePhysics} - * @since 3.0.0 - */ - this.physics; - - /** - * A scene level Matter Physics Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - * - * @name Phaser.Scene#matter - * @type {Phaser.Physics.Matter.MatterPhysics} - * @since 3.0.0 - */ - this.matter; - - if (typeof PLUGIN_FBINSTANT) - { - /** - * A scene level Facebook Instant Games Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - * - * @name Phaser.Scene#facebook - * @type {Phaser.FacebookInstantGamesPlugin} - * @since 3.12.0 - */ - this.facebook; - } - - /** - * A reference to the global Scale Manager. - * This property will only be available if defined in the Scene Injection Map. - * - * @name Phaser.Scene#scale - * @type {Phaser.Scale.ScaleManager} - * @since 3.16.2 - */ - this.scale; - - /** - * A reference to the Plugin Manager. - * - * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install - * those plugins into Scenes as required. - * - * @name Phaser.Scene#plugins - * @type {Phaser.Plugins.PluginManager} - * @since 3.0.0 - */ - this.plugins; - }, - - /** - * Should be overridden by your own Scenes. - * This method is called once per game step while the scene is running. - * - * @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. - */ - update: function () - { - } - -}); - -module.exports = Scene; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Systems = require('./Systems'); + +/** + * @classdesc + * A base Phaser.Scene class which can be extended for your own use. + * + * You can also define the optional methods {@link Phaser.Types.Scenes.SceneInitCallback init()}, {@link Phaser.Types.Scenes.ScenePreloadCallback preload()}, and {@link Phaser.Types.Scenes.SceneCreateCallback create()}. + * + * @class Scene + * @memberof Phaser + * @constructor + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - Scene specific configuration settings. + */ +var Scene = new Class({ + + initialize: + + function Scene (config) + { + /** + * The Scene Systems. You must never overwrite this property, or all hell will break lose. + * + * @name Phaser.Scene#sys + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.sys = new Systems(this, config); + + /** + * A reference to the Phaser.Game instance. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game; + + /** + * A reference to the global Animation Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#anims + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.anims; + + /** + * A reference to the global Cache. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#cache + * @type {Phaser.Cache.CacheManager} + * @since 3.0.0 + */ + this.cache; + + /** + * A reference to the game level Data Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#registry + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.registry; + + /** + * A reference to the Sound Manager. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#sound + * @type {Phaser.Sound.BaseSoundManager} + * @since 3.0.0 + */ + this.sound; + + /** + * A reference to the Texture Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#textures + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.textures; + + /** + * A scene level Event Emitter. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events; + + /** + * A scene level Camera System. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#cameras + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.0.0 + */ + this.cameras; + + /** + * A scene level Game Object Factory. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#add + * @type {Phaser.GameObjects.GameObjectFactory} + * @since 3.0.0 + */ + this.add; + + /** + * A scene level Game Object Creator. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#make + * @type {Phaser.GameObjects.GameObjectCreator} + * @since 3.0.0 + */ + this.make; + + /** + * A reference to the Scene Manager Plugin. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#scene + * @type {Phaser.Scenes.ScenePlugin} + * @since 3.0.0 + */ + this.scene; + + /** + * A scene level Game Object Display List. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#children + * @type {Phaser.GameObjects.DisplayList} + * @since 3.0.0 + */ + this.children; + + /** + * A scene level Lights Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#lights + * @type {Phaser.GameObjects.LightsManager} + * @since 3.0.0 + */ + this.lights; + + /** + * A scene level Data Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#data + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.data; + + /** + * A scene level Input Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#input + * @type {Phaser.Input.InputPlugin} + * @since 3.0.0 + */ + this.input; + + /** + * A scene level Loader Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#load + * @type {Phaser.Loader.LoaderPlugin} + * @since 3.0.0 + */ + this.load; + + /** + * A scene level Time and Clock Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#time + * @type {Phaser.Time.Clock} + * @since 3.0.0 + */ + this.time; + + /** + * A scene level Tween Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + * + * @name Phaser.Scene#tweens + * @type {Phaser.Tweens.TweenManager} + * @since 3.0.0 + */ + this.tweens; + + /** + * A scene level Arcade Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#physics + * @type {Phaser.Physics.Arcade.ArcadePhysics} + * @since 3.0.0 + */ + this.physics; + + /** + * A scene level Matter Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#matter + * @type {Phaser.Physics.Matter.MatterPhysics} + * @since 3.0.0 + */ + this.matter; + + if (typeof PLUGIN_FBINSTANT) + { + /** + * A scene level Facebook Instant Games Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + * + * @name Phaser.Scene#facebook + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.12.0 + */ + this.facebook; + } + + /** + * A reference to the global Scale Manager. + * This property will only be available if defined in the Scene Injection Map. + * + * @name Phaser.Scene#scale + * @type {Phaser.Scale.ScaleManager} + * @since 3.16.2 + */ + this.scale; + + /** + * A reference to the Plugin Manager. + * + * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install + * those plugins into Scenes as required. + * + * @name Phaser.Scene#plugins + * @type {Phaser.Plugins.PluginManager} + * @since 3.0.0 + */ + this.plugins; + }, + + /** + * Should be overridden by your own Scenes. + * This method is called once per game step while the scene is running. + * + * @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. + */ + update: function () + { + } + +}); + +module.exports = Scene; diff --git a/src/scene/SceneManager.js b/src/scene/SceneManager.js index cc4fd73b6..ffb133463 100644 --- a/src/scene/SceneManager.js +++ b/src/scene/SceneManager.js @@ -1,1634 +1,1634 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CONST = require('./const'); -var Events = require('./events'); -var GameEvents = require('../core/events'); -var GetValue = require('../utils/object/GetValue'); -var LoaderEvents = require('../loader/events'); -var NOOP = require('../utils/NOOP'); -var Scene = require('./Scene'); -var Systems = require('./Systems'); - -/** - * @classdesc - * The Scene Manager. - * - * The Scene Manager is a Game level system, responsible for creating, processing and updating all of the - * Scenes in a Game instance. - * - * - * @class SceneManager - * @memberof Phaser.Scenes - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Phaser.Game instance this Scene Manager belongs to. - * @param {object} sceneConfig - Scene specific configuration settings. - */ -var SceneManager = new Class({ - - initialize: - - function SceneManager (game, sceneConfig) - { - /** - * The Game that this SceneManager belongs to. - * - * @name Phaser.Scenes.SceneManager#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = game; - - /** - * An object that maps the keys to the scene so we can quickly get a scene from a key without iteration. - * - * @name Phaser.Scenes.SceneManager#keys - * @type {object} - * @since 3.0.0 - */ - this.keys = {}; - - /** - * The array in which all of the scenes are kept. - * - * @name Phaser.Scenes.SceneManager#scenes - * @type {array} - * @since 3.0.0 - */ - this.scenes = []; - - /** - * Scenes pending to be added are stored in here until the manager has time to add it. - * - * @name Phaser.Scenes.SceneManager#_pending - * @type {array} - * @private - * @since 3.0.0 - */ - this._pending = []; - - /** - * An array of scenes waiting to be started once the game has booted. - * - * @name Phaser.Scenes.SceneManager#_start - * @type {array} - * @private - * @since 3.0.0 - */ - this._start = []; - - /** - * An operations queue, because we don't manipulate the scenes array during processing. - * - * @name Phaser.Scenes.SceneManager#_queue - * @type {array} - * @private - * @since 3.0.0 - */ - this._queue = []; - - /** - * Boot time data to merge. - * - * @name Phaser.Scenes.SceneManager#_data - * @type {object} - * @private - * @since 3.4.0 - */ - this._data = {}; - - /** - * Is the Scene Manager actively processing the Scenes list? - * - * @name Phaser.Scenes.SceneManager#isProcessing - * @type {boolean} - * @default false - * @readonly - * @since 3.0.0 - */ - this.isProcessing = false; - - /** - * Has the Scene Manager properly started? - * - * @name Phaser.Scenes.SceneManager#isBooted - * @type {boolean} - * @default false - * @readonly - * @since 3.4.0 - */ - this.isBooted = false; - - /** - * Do any of the Cameras in any of the Scenes require a custom viewport? - * If not we can skip scissor tests. - * - * @name Phaser.Scenes.SceneManager#customViewports - * @type {number} - * @default 0 - * @since 3.12.0 - */ - this.customViewports = 0; - - if (sceneConfig) - { - if (!Array.isArray(sceneConfig)) - { - sceneConfig = [ sceneConfig ]; - } - - for (var i = 0; i < sceneConfig.length; i++) - { - // The i === 0 part just autostarts the first Scene given (unless it says otherwise in its config) - this._pending.push({ - key: 'default', - scene: sceneConfig[i], - autoStart: (i === 0), - data: {} - }); - } - } - - game.events.once(GameEvents.READY, this.bootQueue, this); - }, - - /** - * Internal first-time Scene boot handler. - * - * @method Phaser.Scenes.SceneManager#bootQueue - * @private - * @since 3.2.0 - */ - bootQueue: function () - { - if (this.isBooted) - { - return; - } - - var i; - var entry; - var key; - var sceneConfig; - - for (i = 0; i < this._pending.length; i++) - { - entry = this._pending[i]; - - key = entry.key; - sceneConfig = entry.scene; - - var newScene; - - if (sceneConfig instanceof Scene) - { - newScene = this.createSceneFromInstance(key, sceneConfig); - } - else if (typeof sceneConfig === 'object') - { - newScene = this.createSceneFromObject(key, sceneConfig); - } - else if (typeof sceneConfig === 'function') - { - newScene = this.createSceneFromFunction(key, sceneConfig); - } - - // Replace key in case the scene changed it - key = newScene.sys.settings.key; - - this.keys[key] = newScene; - - this.scenes.push(newScene); - - // Any data to inject? - if (this._data[key]) - { - newScene.sys.settings.data = this._data[key].data; - - if (this._data[key].autoStart) - { - entry.autoStart = true; - } - } - - if (entry.autoStart || newScene.sys.settings.active) - { - this._start.push(key); - } - } - - // Clear the pending lists - this._pending.length = 0; - - this._data = {}; - - this.isBooted = true; - - // _start might have been populated by the above - for (i = 0; i < this._start.length; i++) - { - entry = this._start[i]; - - this.start(entry); - } - - this._start.length = 0; - }, - - /** - * Process the Scene operations queue. - * - * @method Phaser.Scenes.SceneManager#processQueue - * @since 3.0.0 - */ - processQueue: function () - { - var pendingLength = this._pending.length; - var queueLength = this._queue.length; - - if (pendingLength === 0 && queueLength === 0) - { - return; - } - - var i; - var entry; - - if (pendingLength) - { - for (i = 0; i < pendingLength; i++) - { - entry = this._pending[i]; - - this.add(entry.key, entry.scene, entry.autoStart, entry.data); - } - - // _start might have been populated by this.add - for (i = 0; i < this._start.length; i++) - { - entry = this._start[i]; - - this.start(entry); - } - - // Clear the pending lists - this._start.length = 0; - this._pending.length = 0; - - return; - } - - for (i = 0; i < this._queue.length; i++) - { - entry = this._queue[i]; - - this[entry.op](entry.keyA, entry.keyB); - } - - this._queue.length = 0; - }, - - /** - * Adds a new Scene into the SceneManager. - * You must give each Scene a unique key by which you'll identify it. - * - * The `sceneConfig` can be: - * - * * A `Phaser.Scene` object, or an object that extends it. - * * A plain JavaScript object - * * A JavaScript ES6 Class that extends `Phaser.Scene` - * * A JavaScript ES5 prototype based Class - * * A JavaScript function - * - * If a function is given then a new Scene will be created by calling it. - * - * @method Phaser.Scenes.SceneManager#add - * @since 3.0.0 - * - * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. - * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene - * @param {boolean} [autoStart=false] - If `true` the Scene will be started immediately after being added. - * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. - * - * @return {?Phaser.Scene} The added Scene, if it was added immediately, otherwise `null`. - */ - add: function (key, sceneConfig, autoStart, data) - { - if (autoStart === undefined) { autoStart = false; } - if (data === undefined) { data = {}; } - - // If processing or not booted then put scene into a holding pattern - if (this.isProcessing || !this.isBooted) - { - this._pending.push({ - key: key, - scene: sceneConfig, - autoStart: autoStart, - data: data - }); - - if (!this.isBooted) - { - this._data[key] = { data: data }; - } - - return null; - } - - key = this.getKey(key, sceneConfig); - - var newScene; - - if (sceneConfig instanceof Scene) - { - newScene = this.createSceneFromInstance(key, sceneConfig); - } - else if (typeof sceneConfig === 'object') - { - sceneConfig.key = key; - - newScene = this.createSceneFromObject(key, sceneConfig); - } - else if (typeof sceneConfig === 'function') - { - newScene = this.createSceneFromFunction(key, sceneConfig); - } - - // Any data to inject? - newScene.sys.settings.data = data; - - // Replace key in case the scene changed it - key = newScene.sys.settings.key; - - this.keys[key] = newScene; - - this.scenes.push(newScene); - - if (autoStart || newScene.sys.settings.active) - { - if (this._pending.length) - { - this._start.push(key); - } - else - { - this.start(key); - } - } - - return newScene; - }, - - /** - * Removes a Scene from the SceneManager. - * - * The Scene is removed from the local scenes array, it's key is cleared from the keys - * cache and Scene.Systems.destroy is then called on it. - * - * If the SceneManager is processing the Scenes when this method is called it will - * queue the operation for the next update sequence. - * - * @method Phaser.Scenes.SceneManager#remove - * @since 3.2.0 - * - * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - remove: function (key) - { - if (this.isProcessing) - { - this._queue.push({ op: 'remove', keyA: key, keyB: null }); - } - else - { - var sceneToRemove = this.getScene(key); - - if (!sceneToRemove || sceneToRemove.sys.isTransitioning()) - { - return this; - } - - var index = this.scenes.indexOf(sceneToRemove); - var sceneKey = sceneToRemove.sys.settings.key; - - if (index > -1) - { - delete this.keys[sceneKey]; - this.scenes.splice(index, 1); - - if (this._start.indexOf(sceneKey) > -1) - { - index = this._start.indexOf(sceneKey); - this._start.splice(index, 1); - } - - sceneToRemove.sys.destroy(); - } - } - - return this; - }, - - /** - * Boot the given Scene. - * - * @method Phaser.Scenes.SceneManager#bootScene - * @private - * @fires Phaser.Scenes.Events#TRANSITION_INIT - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to boot. - */ - bootScene: function (scene) - { - var sys = scene.sys; - var settings = sys.settings; - - if (scene.init) - { - scene.init.call(scene, settings.data); - - settings.status = CONST.INIT; - - if (settings.isTransition) - { - sys.events.emit(Events.TRANSITION_INIT, settings.transitionFrom, settings.transitionDuration); - } - } - - var loader; - - if (sys.load) - { - loader = sys.load; - - loader.reset(); - } - - if (loader && scene.preload) - { - scene.preload.call(scene); - - // Is the loader empty? - if (loader.list.size === 0) - { - this.create(scene); - } - else - { - settings.status = CONST.LOADING; - - // Start the loader going as we have something in the queue - loader.once(LoaderEvents.COMPLETE, this.loadComplete, this); - - loader.start(); - } - } - else - { - // No preload? Then there was nothing to load either - this.create(scene); - } - }, - - /** - * Handles load completion for a Scene's Loader. - * - * Starts the Scene that the Loader belongs to. - * - * @method Phaser.Scenes.SceneManager#loadComplete - * @private - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading. - */ - loadComplete: function (loader) - { - var scene = loader.scene; - - // TODO - Remove. This should *not* be handled here - // Try to unlock HTML5 sounds every time any loader completes - if (this.game.sound && this.game.sound.onBlurPausedSounds) - { - this.game.sound.unlock(); - } - - this.create(scene); - }, - - /** - * Handle payload completion for a Scene. - * - * @method Phaser.Scenes.SceneManager#payloadComplete - * @private - * @since 3.0.0 - * - * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading its Scene's payload. - */ - payloadComplete: function (loader) - { - this.bootScene(loader.scene); - }, - - /** - * Updates the Scenes. - * - * @method Phaser.Scenes.SceneManager#update - * @since 3.0.0 - * - * @param {number} time - Time elapsed. - * @param {number} delta - Delta time from the last update. - */ - update: function (time, delta) - { - this.processQueue(); - - this.isProcessing = true; - - // Loop through the active scenes in reverse order - for (var i = this.scenes.length - 1; i >= 0; i--) - { - var sys = this.scenes[i].sys; - - if (sys.settings.status > CONST.START && sys.settings.status <= CONST.RUNNING) - { - sys.step(time, delta); - } - } - }, - - /** - * Renders the Scenes. - * - * @method Phaser.Scenes.SceneManager#render - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer to use. - */ - render: function (renderer) - { - // Loop through the scenes in forward order - for (var i = 0; i < this.scenes.length; i++) - { - var sys = this.scenes[i].sys; - - if (sys.settings.visible && sys.settings.status >= CONST.LOADING && sys.settings.status < CONST.SLEEPING) - { - sys.render(renderer); - } - } - - this.isProcessing = false; - }, - - /** - * Calls the given Scene's {@link Phaser.Scene#create} method and updates its status. - * - * @method Phaser.Scenes.SceneManager#create - * @private - * @fires Phaser.Scenes.Events#CREATE - * @fires Phaser.Scenes.Events#TRANSITION_INIT - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to create. - */ - create: function (scene) - { - var sys = scene.sys; - var settings = sys.settings; - - if (scene.create) - { - settings.status = CONST.CREATING; - - scene.create.call(scene, settings.data); - - if (settings.status === CONST.DESTROYED) - { - return; - } - } - - if (settings.isTransition) - { - sys.events.emit(Events.TRANSITION_START, settings.transitionFrom, settings.transitionDuration); - } - - // If the Scene has an update function we'll set it now, otherwise it'll remain as NOOP - if (scene.update) - { - sys.sceneUpdate = scene.update; - } - - settings.status = CONST.RUNNING; - - sys.events.emit(Events.CREATE, scene); - }, - - /** - * Creates and initializes a Scene from a function. - * - * @method Phaser.Scenes.SceneManager#createSceneFromFunction - * @private - * @since 3.0.0 - * - * @param {string} key - The key of the Scene. - * @param {function} scene - The function to create the Scene from. - * - * @return {Phaser.Scene} The created Scene. - */ - createSceneFromFunction: function (key, scene) - { - var newScene = new scene(); - - if (newScene instanceof Scene) - { - var configKey = newScene.sys.settings.key; - - if (configKey !== '') - { - key = configKey; - } - - if (this.keys.hasOwnProperty(key)) - { - throw new Error('Cannot add a Scene with duplicate key: ' + key); - } - - return this.createSceneFromInstance(key, newScene); - } - else - { - newScene.sys = new Systems(newScene); - - newScene.sys.settings.key = key; - - newScene.sys.init(this.game); - - return newScene; - } - }, - - /** - * Creates and initializes a Scene instance. - * - * @method Phaser.Scenes.SceneManager#createSceneFromInstance - * @private - * @since 3.0.0 - * - * @param {string} key - The key of the Scene. - * @param {Phaser.Scene} newScene - The Scene instance. - * - * @return {Phaser.Scene} The created Scene. - */ - createSceneFromInstance: function (key, newScene) - { - var configKey = newScene.sys.settings.key; - - if (configKey !== '') - { - key = configKey; - } - else - { - newScene.sys.settings.key = key; - } - - newScene.sys.init(this.game); - - return newScene; - }, - - /** - * Creates and initializes a Scene from an Object definition. - * - * @method Phaser.Scenes.SceneManager#createSceneFromObject - * @private - * @since 3.0.0 - * - * @param {string} key - The key of the Scene. - * @param {(string|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig)} sceneConfig - The Scene config. - * - * @return {Phaser.Scene} The created Scene. - */ - createSceneFromObject: function (key, sceneConfig) - { - var newScene = new Scene(sceneConfig); - - var configKey = newScene.sys.settings.key; - - if (configKey !== '') - { - key = configKey; - } - else - { - newScene.sys.settings.key = key; - } - - newScene.sys.init(this.game); - - // Extract callbacks - - var defaults = [ 'init', 'preload', 'create', 'update', 'render' ]; - - for (var i = 0; i < defaults.length; i++) - { - var sceneCallback = GetValue(sceneConfig, defaults[i], null); - - if (sceneCallback) - { - newScene[defaults[i]] = sceneCallback; - } - } - - // Now let's move across any other functions or properties that may exist in the extend object: - - /* - scene: { - preload: preload, - create: create, - extend: { - hello: 1, - test: 'atari', - addImage: addImage - } - } - */ - - if (sceneConfig.hasOwnProperty('extend')) - { - for (var propertyKey in sceneConfig.extend) - { - if (!sceneConfig.extend.hasOwnProperty(propertyKey)) - { - continue; - } - - var value = sceneConfig.extend[propertyKey]; - - if (propertyKey === 'data' && newScene.hasOwnProperty('data') && typeof value === 'object') - { - // Populate the DataManager - newScene.data.merge(value); - } - else if (propertyKey !== 'sys') - { - newScene[propertyKey] = value; - } - } - } - - return newScene; - }, - - /** - * Retrieves the key of a Scene from a Scene config. - * - * @method Phaser.Scenes.SceneManager#getKey - * @private - * @since 3.0.0 - * - * @param {string} key - The key to check in the Scene config. - * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|function)} sceneConfig - The Scene config. - * - * @return {string} The Scene key. - */ - getKey: function (key, sceneConfig) - { - if (!key) { key = 'default'; } - - if (typeof sceneConfig === 'function') - { - return key; - } - else if (sceneConfig instanceof Scene) - { - key = sceneConfig.sys.settings.key; - } - else if (typeof sceneConfig === 'object' && sceneConfig.hasOwnProperty('key')) - { - key = sceneConfig.key; - } - - // By this point it's either 'default' or extracted from the Scene - - if (this.keys.hasOwnProperty(key)) - { - throw new Error('Cannot add a Scene with duplicate key: ' + key); - } - else - { - return key; - } - }, - - /** - * Returns an array of all the current Scenes being managed by this Scene Manager. - * - * You can filter the output by the active state of the Scene and choose to have - * the array returned in normal or reversed order. - * - * @method Phaser.Scenes.SceneManager#getScenes - * @since 3.16.0 - * - * @param {boolean} [isActive=true] - Only include Scene's that are currently active? - * @param {boolean} [inReverse=false] - Return the array of Scenes in reverse? - * - * @return {Phaser.Scene[]} An array containing all of the Scenes in the Scene Manager. - */ - getScenes: function (isActive, inReverse) - { - if (isActive === undefined) { isActive = true; } - if (inReverse === undefined) { inReverse = false; } - - var out = []; - var scenes = this.scenes; - - for (var i = 0; i < scenes.length; i++) - { - var scene = scenes[i]; - - if (scene && (!isActive || (isActive && scene.sys.isActive()))) - { - out.push(scene); - } - } - - return (inReverse) ? out.reverse() : out; - }, - - /** - * Retrieves a Scene. - * - * @method Phaser.Scenes.SceneManager#getScene - * @since 3.0.0 - * - * @param {string|Phaser.Scene} key - The Scene to retrieve. - * - * @return {?Phaser.Scene} The Scene. - */ - getScene: function (key) - { - if (typeof key === 'string') - { - if (this.keys[key]) - { - return this.keys[key]; - } - } - else - { - for (var i = 0; i < this.scenes.length; i++) - { - if (key === this.scenes[i]) - { - return key; - } - } - } - - return null; - }, - - /** - * Determines whether a Scene is running. - * - * @method Phaser.Scenes.SceneManager#isActive - * @since 3.0.0 - * - * @param {string} key - The Scene to check. - * - * @return {boolean} Whether the Scene is running. - */ - isActive: function (key) - { - var scene = this.getScene(key); - - if (scene) - { - return scene.sys.isActive(); - } - - return null; - }, - - /** - * Determines whether a Scene is paused. - * - * @method Phaser.Scenes.SceneManager#isPaused - * @since 3.17.0 - * - * @param {string} key - The Scene to check. - * - * @return {boolean} Whether the Scene is paused. - */ - isPaused: function (key) - { - var scene = this.getScene(key); - - if (scene) - { - return scene.sys.isPaused(); - } - - return null; - }, - - /** - * Determines whether a Scene is visible. - * - * @method Phaser.Scenes.SceneManager#isVisible - * @since 3.0.0 - * - * @param {string} key - The Scene to check. - * - * @return {boolean} Whether the Scene is visible. - */ - isVisible: function (key) - { - var scene = this.getScene(key); - - if (scene) - { - return scene.sys.isVisible(); - } - - return null; - }, - - /** - * Determines whether a Scene is sleeping. - * - * @method Phaser.Scenes.SceneManager#isSleeping - * @since 3.0.0 - * - * @param {string} key - The Scene to check. - * - * @return {boolean} Whether the Scene is sleeping. - */ - isSleeping: function (key) - { - var scene = this.getScene(key); - - if (scene) - { - return scene.sys.isSleeping(); - } - - return null; - }, - - /** - * Pauses the given Scene. - * - * @method Phaser.Scenes.SceneManager#pause - * @since 3.0.0 - * - * @param {string} key - The Scene to pause. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its pause event. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - pause: function (key, data) - { - var scene = this.getScene(key); - - if (scene) - { - scene.sys.pause(data); - } - - return this; - }, - - /** - * Resumes the given Scene. - * - * @method Phaser.Scenes.SceneManager#resume - * @since 3.0.0 - * - * @param {string} key - The Scene to resume. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its resume event. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - resume: function (key, data) - { - var scene = this.getScene(key); - - if (scene) - { - scene.sys.resume(data); - } - - return this; - }, - - /** - * Puts the given Scene to sleep. - * - * @method Phaser.Scenes.SceneManager#sleep - * @since 3.0.0 - * - * @param {string} key - The Scene to put to sleep. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its sleep event. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - sleep: function (key, data) - { - var scene = this.getScene(key); - - if (scene && !scene.sys.isTransitioning()) - { - scene.sys.sleep(data); - } - - return this; - }, - - /** - * Awakens the given Scene. - * - * @method Phaser.Scenes.SceneManager#wake - * @since 3.0.0 - * - * @param {string} key - The Scene to wake up. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its wake event. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - wake: function (key, data) - { - var scene = this.getScene(key); - - if (scene) - { - scene.sys.wake(data); - } - - return this; - }, - - /** - * Runs the given Scene. - * - * If the given Scene is paused, it will resume it. If sleeping, it will wake it. - * If not running at all, it will be started. - * - * Use this if you wish to open a modal Scene by calling `pause` on the current - * Scene, then `run` on the modal Scene. - * - * @method Phaser.Scenes.SceneManager#run - * @since 3.10.0 - * - * @param {string} key - The Scene to run. - * @param {object} [data] - A data object that will be passed to the Scene on start, wake, or resume. - * - * @return {Phaser.Scenes.SceneManager} This Scene Manager. - */ - run: function (key, data) - { - var scene = this.getScene(key); - - if (!scene) - { - for (var i = 0; i < this._pending.length; i++) - { - if (this._pending[i].key === key) - { - this.queueOp('start', key, data); - break; - } - } - return this; - } - - if (scene.sys.isSleeping()) - { - // Sleeping? - scene.sys.wake(data); - } - else if (scene.sys.isPaused()) - { - // Paused? - scene.sys.resume(data); - } - else - { - // Not actually running? - this.start(key, data); - } - }, - - /** - * Starts the given Scene. - * - * @method Phaser.Scenes.SceneManager#start - * @since 3.0.0 - * - * @param {string} key - The Scene to start. - * @param {object} [data] - Optional data object to pass to Scene.Settings and Scene.init. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - start: function (key, data) - { - // If the Scene Manager is not running, then put the Scene into a holding pattern - if (!this.isBooted) - { - this._data[key] = { - autoStart: true, - data: data - }; - - return this; - } - - var scene = this.getScene(key); - - if (scene) - { - // If the Scene is already running (perhaps they called start from a launched sub-Scene?) - // then we close it down before starting it again. - if (scene.sys.isActive() || scene.sys.isPaused()) - { - scene.sys.shutdown(); - - scene.sys.start(data); - } - else - { - scene.sys.start(data); - - var loader; - - if (scene.sys.load) - { - loader = scene.sys.load; - } - - // Files payload? - if (loader && scene.sys.settings.hasOwnProperty('pack')) - { - loader.reset(); - - if (loader.addPack({ payload: scene.sys.settings.pack })) - { - scene.sys.settings.status = CONST.LOADING; - - loader.once(LoaderEvents.COMPLETE, this.payloadComplete, this); - - loader.start(); - - return this; - } - } - } - - this.bootScene(scene); - } - - return this; - }, - - /** - * Stops the given Scene. - * - * @method Phaser.Scenes.SceneManager#stop - * @since 3.0.0 - * - * @param {string} key - The Scene to stop. - * @param {object} [data] - Optional data object to pass to Scene.shutdown. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - stop: function (key, data) - { - var scene = this.getScene(key); - - if (scene && !scene.sys.isTransitioning()) - { - scene.sys.shutdown(data); - } - - return this; - }, - - /** - * Sleeps one one Scene and starts the other. - * - * @method Phaser.Scenes.SceneManager#switch - * @since 3.0.0 - * - * @param {string} from - The Scene to sleep. - * @param {string} to - The Scene to start. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - switch: function (from, to) - { - var sceneA = this.getScene(from); - var sceneB = this.getScene(to); - - if (sceneA && sceneB && sceneA !== sceneB) - { - this.sleep(from); - - if (this.isSleeping(to)) - { - this.wake(to); - } - else - { - this.start(to); - } - } - - return this; - }, - - /** - * Retrieves a Scene by numeric index. - * - * @method Phaser.Scenes.SceneManager#getAt - * @since 3.0.0 - * - * @param {integer} index - The index of the Scene to retrieve. - * - * @return {(Phaser.Scene|undefined)} The Scene. - */ - getAt: function (index) - { - return this.scenes[index]; - }, - - /** - * Retrieves the numeric index of a Scene. - * - * @method Phaser.Scenes.SceneManager#getIndex - * @since 3.0.0 - * - * @param {(string|Phaser.Scene)} key - The key of the Scene. - * - * @return {integer} The index of the Scene. - */ - getIndex: function (key) - { - var scene = this.getScene(key); - - return this.scenes.indexOf(scene); - }, - - /** - * Brings a Scene to the top of the Scenes list. - * - * This means it will render above all other Scenes. - * - * @method Phaser.Scenes.SceneManager#bringToTop - * @since 3.0.0 - * - * @param {(string|Phaser.Scene)} key - The Scene to move. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - bringToTop: function (key) - { - if (this.isProcessing) - { - this._queue.push({ op: 'bringToTop', keyA: key, keyB: null }); - } - else - { - var index = this.getIndex(key); - - if (index !== -1 && index < this.scenes.length) - { - var scene = this.getScene(key); - - this.scenes.splice(index, 1); - this.scenes.push(scene); - } - } - - return this; - }, - - /** - * Sends a Scene to the back of the Scenes list. - * - * This means it will render below all other Scenes. - * - * @method Phaser.Scenes.SceneManager#sendToBack - * @since 3.0.0 - * - * @param {(string|Phaser.Scene)} key - The Scene to move. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - sendToBack: function (key) - { - if (this.isProcessing) - { - this._queue.push({ op: 'sendToBack', keyA: key, keyB: null }); - } - else - { - var index = this.getIndex(key); - - if (index !== -1 && index > 0) - { - var scene = this.getScene(key); - - this.scenes.splice(index, 1); - this.scenes.unshift(scene); - } - } - - return this; - }, - - /** - * Moves a Scene down one position in the Scenes list. - * - * @method Phaser.Scenes.SceneManager#moveDown - * @since 3.0.0 - * - * @param {(string|Phaser.Scene)} key - The Scene to move. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - moveDown: function (key) - { - if (this.isProcessing) - { - this._queue.push({ op: 'moveDown', keyA: key, keyB: null }); - } - else - { - var indexA = this.getIndex(key); - - if (indexA > 0) - { - var indexB = indexA - 1; - var sceneA = this.getScene(key); - var sceneB = this.getAt(indexB); - - this.scenes[indexA] = sceneB; - this.scenes[indexB] = sceneA; - } - } - - return this; - }, - - /** - * Moves a Scene up one position in the Scenes list. - * - * @method Phaser.Scenes.SceneManager#moveUp - * @since 3.0.0 - * - * @param {(string|Phaser.Scene)} key - The Scene to move. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - moveUp: function (key) - { - if (this.isProcessing) - { - this._queue.push({ op: 'moveUp', keyA: key, keyB: null }); - } - else - { - var indexA = this.getIndex(key); - - if (indexA < this.scenes.length - 1) - { - var indexB = indexA + 1; - var sceneA = this.getScene(key); - var sceneB = this.getAt(indexB); - - this.scenes[indexA] = sceneB; - this.scenes[indexB] = sceneA; - } - } - - return this; - }, - - /** - * Moves a Scene so it is immediately above another Scene in the Scenes list. - * - * This means it will render over the top of the other Scene. - * - * @method Phaser.Scenes.SceneManager#moveAbove - * @since 3.2.0 - * - * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. - * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - moveAbove: function (keyA, keyB) - { - if (keyA === keyB) - { - return this; - } - - if (this.isProcessing) - { - this._queue.push({ op: 'moveAbove', keyA: keyA, keyB: keyB }); - } - else - { - var indexA = this.getIndex(keyA); - var indexB = this.getIndex(keyB); - - if (indexA !== -1 && indexB !== -1) - { - var tempScene = this.getAt(indexB); - - // Remove - this.scenes.splice(indexB, 1); - - // Add in new location - this.scenes.splice(indexA + 1, 0, tempScene); - } - } - - return this; - }, - - /** - * Moves a Scene so it is immediately below another Scene in the Scenes list. - * - * This means it will render behind the other Scene. - * - * @method Phaser.Scenes.SceneManager#moveBelow - * @since 3.2.0 - * - * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. - * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - moveBelow: function (keyA, keyB) - { - if (keyA === keyB) - { - return this; - } - - if (this.isProcessing) - { - this._queue.push({ op: 'moveBelow', keyA: keyA, keyB: keyB }); - } - else - { - var indexA = this.getIndex(keyA); - var indexB = this.getIndex(keyB); - - if (indexA !== -1 && indexB !== -1) - { - var tempScene = this.getAt(indexB); - - // Remove - this.scenes.splice(indexB, 1); - - if (indexA === 0) - { - this.scenes.unshift(tempScene); - } - else - { - // Add in new location - this.scenes.splice(indexA, 0, tempScene); - } - } - } - - return this; - }, - - /** - * Queue a Scene operation for the next update. - * - * @method Phaser.Scenes.SceneManager#queueOp - * @private - * @since 3.0.0 - * - * @param {string} op - The operation to perform. - * @param {(string|Phaser.Scene)} keyA - Scene A. - * @param {(any|string|Phaser.Scene)} [keyB] - Scene B, or a data object. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - queueOp: function (op, keyA, keyB) - { - this._queue.push({ op: op, keyA: keyA, keyB: keyB }); - - return this; - }, - - /** - * Swaps the positions of two Scenes in the Scenes list. - * - * @method Phaser.Scenes.SceneManager#swapPosition - * @since 3.0.0 - * - * @param {(string|Phaser.Scene)} keyA - The first Scene to swap. - * @param {(string|Phaser.Scene)} keyB - The second Scene to swap. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - swapPosition: function (keyA, keyB) - { - if (keyA === keyB) - { - return this; - } - - if (this.isProcessing) - { - this._queue.push({ op: 'swapPosition', keyA: keyA, keyB: keyB }); - } - else - { - var indexA = this.getIndex(keyA); - var indexB = this.getIndex(keyB); - - if (indexA !== indexB && indexA !== -1 && indexB !== -1) - { - var tempScene = this.getAt(indexA); - - this.scenes[indexA] = this.scenes[indexB]; - this.scenes[indexB] = tempScene; - } - } - - return this; - }, - - /** - * Dumps debug information about each Scene to the developer console. - * - * @method Phaser.Scenes.SceneManager#dump - * @since 3.2.0 - */ - dump: function () - { - var out = []; - var map = [ 'pending', 'init', 'start', 'loading', 'creating', 'running', 'paused', 'sleeping', 'shutdown', 'destroyed' ]; - - for (var i = 0; i < this.scenes.length; i++) - { - var sys = this.scenes[i].sys; - - var key = (sys.settings.visible && (sys.settings.status === CONST.RUNNING || sys.settings.status === CONST.PAUSED)) ? '[*] ' : '[-] '; - key += sys.settings.key + ' (' + map[sys.settings.status] + ')'; - - out.push(key); - } - - console.log(out.join('\n')); - }, - - /** - * Destroy the SceneManager and all of its Scene's systems. - * - * @method Phaser.Scenes.SceneManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - for (var i = 0; i < this.scenes.length; i++) - { - var sys = this.scenes[i].sys; - - sys.destroy(); - } - - this.update = NOOP; - - this.scenes = []; - - this._pending = []; - this._start = []; - this._queue = []; - - this.game = null; - } - -}); - -module.exports = SceneManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CONST = require('./const'); +var Events = require('./events'); +var GameEvents = require('../core/events'); +var GetValue = require('../utils/object/GetValue'); +var LoaderEvents = require('../loader/events'); +var NOOP = require('../utils/NOOP'); +var Scene = require('./Scene'); +var Systems = require('./Systems'); + +/** + * @classdesc + * The Scene Manager. + * + * The Scene Manager is a Game level system, responsible for creating, processing and updating all of the + * Scenes in a Game instance. + * + * + * @class SceneManager + * @memberof Phaser.Scenes + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance this Scene Manager belongs to. + * @param {object} sceneConfig - Scene specific configuration settings. + */ +var SceneManager = new Class({ + + initialize: + + function SceneManager (game, sceneConfig) + { + /** + * The Game that this SceneManager belongs to. + * + * @name Phaser.Scenes.SceneManager#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * An object that maps the keys to the scene so we can quickly get a scene from a key without iteration. + * + * @name Phaser.Scenes.SceneManager#keys + * @type {object} + * @since 3.0.0 + */ + this.keys = {}; + + /** + * The array in which all of the scenes are kept. + * + * @name Phaser.Scenes.SceneManager#scenes + * @type {array} + * @since 3.0.0 + */ + this.scenes = []; + + /** + * Scenes pending to be added are stored in here until the manager has time to add it. + * + * @name Phaser.Scenes.SceneManager#_pending + * @type {array} + * @private + * @since 3.0.0 + */ + this._pending = []; + + /** + * An array of scenes waiting to be started once the game has booted. + * + * @name Phaser.Scenes.SceneManager#_start + * @type {array} + * @private + * @since 3.0.0 + */ + this._start = []; + + /** + * An operations queue, because we don't manipulate the scenes array during processing. + * + * @name Phaser.Scenes.SceneManager#_queue + * @type {array} + * @private + * @since 3.0.0 + */ + this._queue = []; + + /** + * Boot time data to merge. + * + * @name Phaser.Scenes.SceneManager#_data + * @type {object} + * @private + * @since 3.4.0 + */ + this._data = {}; + + /** + * Is the Scene Manager actively processing the Scenes list? + * + * @name Phaser.Scenes.SceneManager#isProcessing + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isProcessing = false; + + /** + * Has the Scene Manager properly started? + * + * @name Phaser.Scenes.SceneManager#isBooted + * @type {boolean} + * @default false + * @readonly + * @since 3.4.0 + */ + this.isBooted = false; + + /** + * Do any of the Cameras in any of the Scenes require a custom viewport? + * If not we can skip scissor tests. + * + * @name Phaser.Scenes.SceneManager#customViewports + * @type {number} + * @default 0 + * @since 3.12.0 + */ + this.customViewports = 0; + + if (sceneConfig) + { + if (!Array.isArray(sceneConfig)) + { + sceneConfig = [ sceneConfig ]; + } + + for (var i = 0; i < sceneConfig.length; i++) + { + // The i === 0 part just autostarts the first Scene given (unless it says otherwise in its config) + this._pending.push({ + key: 'default', + scene: sceneConfig[i], + autoStart: (i === 0), + data: {} + }); + } + } + + game.events.once(GameEvents.READY, this.bootQueue, this); + }, + + /** + * Internal first-time Scene boot handler. + * + * @method Phaser.Scenes.SceneManager#bootQueue + * @private + * @since 3.2.0 + */ + bootQueue: function () + { + if (this.isBooted) + { + return; + } + + var i; + var entry; + var key; + var sceneConfig; + + for (i = 0; i < this._pending.length; i++) + { + entry = this._pending[i]; + + key = entry.key; + sceneConfig = entry.scene; + + var newScene; + + if (sceneConfig instanceof Scene) + { + newScene = this.createSceneFromInstance(key, sceneConfig); + } + else if (typeof sceneConfig === 'object') + { + newScene = this.createSceneFromObject(key, sceneConfig); + } + else if (typeof sceneConfig === 'function') + { + newScene = this.createSceneFromFunction(key, sceneConfig); + } + + // Replace key in case the scene changed it + key = newScene.sys.settings.key; + + this.keys[key] = newScene; + + this.scenes.push(newScene); + + // Any data to inject? + if (this._data[key]) + { + newScene.sys.settings.data = this._data[key].data; + + if (this._data[key].autoStart) + { + entry.autoStart = true; + } + } + + if (entry.autoStart || newScene.sys.settings.active) + { + this._start.push(key); + } + } + + // Clear the pending lists + this._pending.length = 0; + + this._data = {}; + + this.isBooted = true; + + // _start might have been populated by the above + for (i = 0; i < this._start.length; i++) + { + entry = this._start[i]; + + this.start(entry); + } + + this._start.length = 0; + }, + + /** + * Process the Scene operations queue. + * + * @method Phaser.Scenes.SceneManager#processQueue + * @since 3.0.0 + */ + processQueue: function () + { + var pendingLength = this._pending.length; + var queueLength = this._queue.length; + + if (pendingLength === 0 && queueLength === 0) + { + return; + } + + var i; + var entry; + + if (pendingLength) + { + for (i = 0; i < pendingLength; i++) + { + entry = this._pending[i]; + + this.add(entry.key, entry.scene, entry.autoStart, entry.data); + } + + // _start might have been populated by this.add + for (i = 0; i < this._start.length; i++) + { + entry = this._start[i]; + + this.start(entry); + } + + // Clear the pending lists + this._start.length = 0; + this._pending.length = 0; + + return; + } + + for (i = 0; i < this._queue.length; i++) + { + entry = this._queue[i]; + + this[entry.op](entry.keyA, entry.keyB); + } + + this._queue.length = 0; + }, + + /** + * Adds a new Scene into the SceneManager. + * You must give each Scene a unique key by which you'll identify it. + * + * The `sceneConfig` can be: + * + * * A `Phaser.Scene` object, or an object that extends it. + * * A plain JavaScript object + * * A JavaScript ES6 Class that extends `Phaser.Scene` + * * A JavaScript ES5 prototype based Class + * * A JavaScript function + * + * If a function is given then a new Scene will be created by calling it. + * + * @method Phaser.Scenes.SceneManager#add + * @since 3.0.0 + * + * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. + * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene + * @param {boolean} [autoStart=false] - If `true` the Scene will be started immediately after being added. + * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. + * + * @return {?Phaser.Scene} The added Scene, if it was added immediately, otherwise `null`. + */ + add: function (key, sceneConfig, autoStart, data) + { + if (autoStart === undefined) { autoStart = false; } + if (data === undefined) { data = {}; } + + // If processing or not booted then put scene into a holding pattern + if (this.isProcessing || !this.isBooted) + { + this._pending.push({ + key: key, + scene: sceneConfig, + autoStart: autoStart, + data: data + }); + + if (!this.isBooted) + { + this._data[key] = { data: data }; + } + + return null; + } + + key = this.getKey(key, sceneConfig); + + var newScene; + + if (sceneConfig instanceof Scene) + { + newScene = this.createSceneFromInstance(key, sceneConfig); + } + else if (typeof sceneConfig === 'object') + { + sceneConfig.key = key; + + newScene = this.createSceneFromObject(key, sceneConfig); + } + else if (typeof sceneConfig === 'function') + { + newScene = this.createSceneFromFunction(key, sceneConfig); + } + + // Any data to inject? + newScene.sys.settings.data = data; + + // Replace key in case the scene changed it + key = newScene.sys.settings.key; + + this.keys[key] = newScene; + + this.scenes.push(newScene); + + if (autoStart || newScene.sys.settings.active) + { + if (this._pending.length) + { + this._start.push(key); + } + else + { + this.start(key); + } + } + + return newScene; + }, + + /** + * Removes a Scene from the SceneManager. + * + * The Scene is removed from the local scenes array, it's key is cleared from the keys + * cache and Scene.Systems.destroy is then called on it. + * + * If the SceneManager is processing the Scenes when this method is called it will + * queue the operation for the next update sequence. + * + * @method Phaser.Scenes.SceneManager#remove + * @since 3.2.0 + * + * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + remove: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'remove', keyA: key, keyB: null }); + } + else + { + var sceneToRemove = this.getScene(key); + + if (!sceneToRemove || sceneToRemove.sys.isTransitioning()) + { + return this; + } + + var index = this.scenes.indexOf(sceneToRemove); + var sceneKey = sceneToRemove.sys.settings.key; + + if (index > -1) + { + delete this.keys[sceneKey]; + this.scenes.splice(index, 1); + + if (this._start.indexOf(sceneKey) > -1) + { + index = this._start.indexOf(sceneKey); + this._start.splice(index, 1); + } + + sceneToRemove.sys.destroy(); + } + } + + return this; + }, + + /** + * Boot the given Scene. + * + * @method Phaser.Scenes.SceneManager#bootScene + * @private + * @fires Phaser.Scenes.Events#TRANSITION_INIT + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to boot. + */ + bootScene: function (scene) + { + var sys = scene.sys; + var settings = sys.settings; + + if (scene.init) + { + scene.init.call(scene, settings.data); + + settings.status = CONST.INIT; + + if (settings.isTransition) + { + sys.events.emit(Events.TRANSITION_INIT, settings.transitionFrom, settings.transitionDuration); + } + } + + var loader; + + if (sys.load) + { + loader = sys.load; + + loader.reset(); + } + + if (loader && scene.preload) + { + scene.preload.call(scene); + + // Is the loader empty? + if (loader.list.size === 0) + { + this.create(scene); + } + else + { + settings.status = CONST.LOADING; + + // Start the loader going as we have something in the queue + loader.once(LoaderEvents.COMPLETE, this.loadComplete, this); + + loader.start(); + } + } + else + { + // No preload? Then there was nothing to load either + this.create(scene); + } + }, + + /** + * Handles load completion for a Scene's Loader. + * + * Starts the Scene that the Loader belongs to. + * + * @method Phaser.Scenes.SceneManager#loadComplete + * @private + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading. + */ + loadComplete: function (loader) + { + var scene = loader.scene; + + // TODO - Remove. This should *not* be handled here + // Try to unlock HTML5 sounds every time any loader completes + if (this.game.sound && this.game.sound.onBlurPausedSounds) + { + this.game.sound.unlock(); + } + + this.create(scene); + }, + + /** + * Handle payload completion for a Scene. + * + * @method Phaser.Scenes.SceneManager#payloadComplete + * @private + * @since 3.0.0 + * + * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading its Scene's payload. + */ + payloadComplete: function (loader) + { + this.bootScene(loader.scene); + }, + + /** + * Updates the Scenes. + * + * @method Phaser.Scenes.SceneManager#update + * @since 3.0.0 + * + * @param {number} time - Time elapsed. + * @param {number} delta - Delta time from the last update. + */ + update: function (time, delta) + { + this.processQueue(); + + this.isProcessing = true; + + // Loop through the active scenes in reverse order + for (var i = this.scenes.length - 1; i >= 0; i--) + { + var sys = this.scenes[i].sys; + + if (sys.settings.status > CONST.START && sys.settings.status <= CONST.RUNNING) + { + sys.step(time, delta); + } + } + }, + + /** + * Renders the Scenes. + * + * @method Phaser.Scenes.SceneManager#render + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer to use. + */ + render: function (renderer) + { + // Loop through the scenes in forward order + for (var i = 0; i < this.scenes.length; i++) + { + var sys = this.scenes[i].sys; + + if (sys.settings.visible && sys.settings.status >= CONST.LOADING && sys.settings.status < CONST.SLEEPING) + { + sys.render(renderer); + } + } + + this.isProcessing = false; + }, + + /** + * Calls the given Scene's {@link Phaser.Scene#create} method and updates its status. + * + * @method Phaser.Scenes.SceneManager#create + * @private + * @fires Phaser.Scenes.Events#CREATE + * @fires Phaser.Scenes.Events#TRANSITION_INIT + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to create. + */ + create: function (scene) + { + var sys = scene.sys; + var settings = sys.settings; + + if (scene.create) + { + settings.status = CONST.CREATING; + + scene.create.call(scene, settings.data); + + if (settings.status === CONST.DESTROYED) + { + return; + } + } + + if (settings.isTransition) + { + sys.events.emit(Events.TRANSITION_START, settings.transitionFrom, settings.transitionDuration); + } + + // If the Scene has an update function we'll set it now, otherwise it'll remain as NOOP + if (scene.update) + { + sys.sceneUpdate = scene.update; + } + + settings.status = CONST.RUNNING; + + sys.events.emit(Events.CREATE, scene); + }, + + /** + * Creates and initializes a Scene from a function. + * + * @method Phaser.Scenes.SceneManager#createSceneFromFunction + * @private + * @since 3.0.0 + * + * @param {string} key - The key of the Scene. + * @param {function} scene - The function to create the Scene from. + * + * @return {Phaser.Scene} The created Scene. + */ + createSceneFromFunction: function (key, scene) + { + var newScene = new scene(); + + if (newScene instanceof Scene) + { + var configKey = newScene.sys.settings.key; + + if (configKey !== '') + { + key = configKey; + } + + if (this.keys.hasOwnProperty(key)) + { + throw new Error('Cannot add a Scene with duplicate key: ' + key); + } + + return this.createSceneFromInstance(key, newScene); + } + else + { + newScene.sys = new Systems(newScene); + + newScene.sys.settings.key = key; + + newScene.sys.init(this.game); + + return newScene; + } + }, + + /** + * Creates and initializes a Scene instance. + * + * @method Phaser.Scenes.SceneManager#createSceneFromInstance + * @private + * @since 3.0.0 + * + * @param {string} key - The key of the Scene. + * @param {Phaser.Scene} newScene - The Scene instance. + * + * @return {Phaser.Scene} The created Scene. + */ + createSceneFromInstance: function (key, newScene) + { + var configKey = newScene.sys.settings.key; + + if (configKey !== '') + { + key = configKey; + } + else + { + newScene.sys.settings.key = key; + } + + newScene.sys.init(this.game); + + return newScene; + }, + + /** + * Creates and initializes a Scene from an Object definition. + * + * @method Phaser.Scenes.SceneManager#createSceneFromObject + * @private + * @since 3.0.0 + * + * @param {string} key - The key of the Scene. + * @param {(string|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig)} sceneConfig - The Scene config. + * + * @return {Phaser.Scene} The created Scene. + */ + createSceneFromObject: function (key, sceneConfig) + { + var newScene = new Scene(sceneConfig); + + var configKey = newScene.sys.settings.key; + + if (configKey !== '') + { + key = configKey; + } + else + { + newScene.sys.settings.key = key; + } + + newScene.sys.init(this.game); + + // Extract callbacks + + var defaults = [ 'init', 'preload', 'create', 'update', 'render' ]; + + for (var i = 0; i < defaults.length; i++) + { + var sceneCallback = GetValue(sceneConfig, defaults[i], null); + + if (sceneCallback) + { + newScene[defaults[i]] = sceneCallback; + } + } + + // Now let's move across any other functions or properties that may exist in the extend object: + + /* + scene: { + preload: preload, + create: create, + extend: { + hello: 1, + test: 'atari', + addImage: addImage + } + } + */ + + if (sceneConfig.hasOwnProperty('extend')) + { + for (var propertyKey in sceneConfig.extend) + { + if (!sceneConfig.extend.hasOwnProperty(propertyKey)) + { + continue; + } + + var value = sceneConfig.extend[propertyKey]; + + if (propertyKey === 'data' && newScene.hasOwnProperty('data') && typeof value === 'object') + { + // Populate the DataManager + newScene.data.merge(value); + } + else if (propertyKey !== 'sys') + { + newScene[propertyKey] = value; + } + } + } + + return newScene; + }, + + /** + * Retrieves the key of a Scene from a Scene config. + * + * @method Phaser.Scenes.SceneManager#getKey + * @private + * @since 3.0.0 + * + * @param {string} key - The key to check in the Scene config. + * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|function)} sceneConfig - The Scene config. + * + * @return {string} The Scene key. + */ + getKey: function (key, sceneConfig) + { + if (!key) { key = 'default'; } + + if (typeof sceneConfig === 'function') + { + return key; + } + else if (sceneConfig instanceof Scene) + { + key = sceneConfig.sys.settings.key; + } + else if (typeof sceneConfig === 'object' && sceneConfig.hasOwnProperty('key')) + { + key = sceneConfig.key; + } + + // By this point it's either 'default' or extracted from the Scene + + if (this.keys.hasOwnProperty(key)) + { + throw new Error('Cannot add a Scene with duplicate key: ' + key); + } + else + { + return key; + } + }, + + /** + * Returns an array of all the current Scenes being managed by this Scene Manager. + * + * You can filter the output by the active state of the Scene and choose to have + * the array returned in normal or reversed order. + * + * @method Phaser.Scenes.SceneManager#getScenes + * @since 3.16.0 + * + * @param {boolean} [isActive=true] - Only include Scene's that are currently active? + * @param {boolean} [inReverse=false] - Return the array of Scenes in reverse? + * + * @return {Phaser.Scene[]} An array containing all of the Scenes in the Scene Manager. + */ + getScenes: function (isActive, inReverse) + { + if (isActive === undefined) { isActive = true; } + if (inReverse === undefined) { inReverse = false; } + + var out = []; + var scenes = this.scenes; + + for (var i = 0; i < scenes.length; i++) + { + var scene = scenes[i]; + + if (scene && (!isActive || (isActive && scene.sys.isActive()))) + { + out.push(scene); + } + } + + return (inReverse) ? out.reverse() : out; + }, + + /** + * Retrieves a Scene. + * + * @method Phaser.Scenes.SceneManager#getScene + * @since 3.0.0 + * + * @param {string|Phaser.Scene} key - The Scene to retrieve. + * + * @return {?Phaser.Scene} The Scene. + */ + getScene: function (key) + { + if (typeof key === 'string') + { + if (this.keys[key]) + { + return this.keys[key]; + } + } + else + { + for (var i = 0; i < this.scenes.length; i++) + { + if (key === this.scenes[i]) + { + return key; + } + } + } + + return null; + }, + + /** + * Determines whether a Scene is running. + * + * @method Phaser.Scenes.SceneManager#isActive + * @since 3.0.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is running. + */ + isActive: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isActive(); + } + + return null; + }, + + /** + * Determines whether a Scene is paused. + * + * @method Phaser.Scenes.SceneManager#isPaused + * @since 3.17.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is paused. + */ + isPaused: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isPaused(); + } + + return null; + }, + + /** + * Determines whether a Scene is visible. + * + * @method Phaser.Scenes.SceneManager#isVisible + * @since 3.0.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is visible. + */ + isVisible: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isVisible(); + } + + return null; + }, + + /** + * Determines whether a Scene is sleeping. + * + * @method Phaser.Scenes.SceneManager#isSleeping + * @since 3.0.0 + * + * @param {string} key - The Scene to check. + * + * @return {boolean} Whether the Scene is sleeping. + */ + isSleeping: function (key) + { + var scene = this.getScene(key); + + if (scene) + { + return scene.sys.isSleeping(); + } + + return null; + }, + + /** + * Pauses the given Scene. + * + * @method Phaser.Scenes.SceneManager#pause + * @since 3.0.0 + * + * @param {string} key - The Scene to pause. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its pause event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + pause: function (key, data) + { + var scene = this.getScene(key); + + if (scene) + { + scene.sys.pause(data); + } + + return this; + }, + + /** + * Resumes the given Scene. + * + * @method Phaser.Scenes.SceneManager#resume + * @since 3.0.0 + * + * @param {string} key - The Scene to resume. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its resume event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + resume: function (key, data) + { + var scene = this.getScene(key); + + if (scene) + { + scene.sys.resume(data); + } + + return this; + }, + + /** + * Puts the given Scene to sleep. + * + * @method Phaser.Scenes.SceneManager#sleep + * @since 3.0.0 + * + * @param {string} key - The Scene to put to sleep. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its sleep event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + sleep: function (key, data) + { + var scene = this.getScene(key); + + if (scene && !scene.sys.isTransitioning()) + { + scene.sys.sleep(data); + } + + return this; + }, + + /** + * Awakens the given Scene. + * + * @method Phaser.Scenes.SceneManager#wake + * @since 3.0.0 + * + * @param {string} key - The Scene to wake up. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its wake event. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + wake: function (key, data) + { + var scene = this.getScene(key); + + if (scene) + { + scene.sys.wake(data); + } + + return this; + }, + + /** + * Runs the given Scene. + * + * If the given Scene is paused, it will resume it. If sleeping, it will wake it. + * If not running at all, it will be started. + * + * Use this if you wish to open a modal Scene by calling `pause` on the current + * Scene, then `run` on the modal Scene. + * + * @method Phaser.Scenes.SceneManager#run + * @since 3.10.0 + * + * @param {string} key - The Scene to run. + * @param {object} [data] - A data object that will be passed to the Scene on start, wake, or resume. + * + * @return {Phaser.Scenes.SceneManager} This Scene Manager. + */ + run: function (key, data) + { + var scene = this.getScene(key); + + if (!scene) + { + for (var i = 0; i < this._pending.length; i++) + { + if (this._pending[i].key === key) + { + this.queueOp('start', key, data); + break; + } + } + return this; + } + + if (scene.sys.isSleeping()) + { + // Sleeping? + scene.sys.wake(data); + } + else if (scene.sys.isPaused()) + { + // Paused? + scene.sys.resume(data); + } + else + { + // Not actually running? + this.start(key, data); + } + }, + + /** + * Starts the given Scene. + * + * @method Phaser.Scenes.SceneManager#start + * @since 3.0.0 + * + * @param {string} key - The Scene to start. + * @param {object} [data] - Optional data object to pass to Scene.Settings and Scene.init. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + start: function (key, data) + { + // If the Scene Manager is not running, then put the Scene into a holding pattern + if (!this.isBooted) + { + this._data[key] = { + autoStart: true, + data: data + }; + + return this; + } + + var scene = this.getScene(key); + + if (scene) + { + // If the Scene is already running (perhaps they called start from a launched sub-Scene?) + // then we close it down before starting it again. + if (scene.sys.isActive() || scene.sys.isPaused()) + { + scene.sys.shutdown(); + + scene.sys.start(data); + } + else + { + scene.sys.start(data); + + var loader; + + if (scene.sys.load) + { + loader = scene.sys.load; + } + + // Files payload? + if (loader && scene.sys.settings.hasOwnProperty('pack')) + { + loader.reset(); + + if (loader.addPack({ payload: scene.sys.settings.pack })) + { + scene.sys.settings.status = CONST.LOADING; + + loader.once(LoaderEvents.COMPLETE, this.payloadComplete, this); + + loader.start(); + + return this; + } + } + } + + this.bootScene(scene); + } + + return this; + }, + + /** + * Stops the given Scene. + * + * @method Phaser.Scenes.SceneManager#stop + * @since 3.0.0 + * + * @param {string} key - The Scene to stop. + * @param {object} [data] - Optional data object to pass to Scene.shutdown. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + stop: function (key, data) + { + var scene = this.getScene(key); + + if (scene && !scene.sys.isTransitioning()) + { + scene.sys.shutdown(data); + } + + return this; + }, + + /** + * Sleeps one one Scene and starts the other. + * + * @method Phaser.Scenes.SceneManager#switch + * @since 3.0.0 + * + * @param {string} from - The Scene to sleep. + * @param {string} to - The Scene to start. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + switch: function (from, to) + { + var sceneA = this.getScene(from); + var sceneB = this.getScene(to); + + if (sceneA && sceneB && sceneA !== sceneB) + { + this.sleep(from); + + if (this.isSleeping(to)) + { + this.wake(to); + } + else + { + this.start(to); + } + } + + return this; + }, + + /** + * Retrieves a Scene by numeric index. + * + * @method Phaser.Scenes.SceneManager#getAt + * @since 3.0.0 + * + * @param {integer} index - The index of the Scene to retrieve. + * + * @return {(Phaser.Scene|undefined)} The Scene. + */ + getAt: function (index) + { + return this.scenes[index]; + }, + + /** + * Retrieves the numeric index of a Scene. + * + * @method Phaser.Scenes.SceneManager#getIndex + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The key of the Scene. + * + * @return {integer} The index of the Scene. + */ + getIndex: function (key) + { + var scene = this.getScene(key); + + return this.scenes.indexOf(scene); + }, + + /** + * Brings a Scene to the top of the Scenes list. + * + * This means it will render above all other Scenes. + * + * @method Phaser.Scenes.SceneManager#bringToTop + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + bringToTop: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'bringToTop', keyA: key, keyB: null }); + } + else + { + var index = this.getIndex(key); + + if (index !== -1 && index < this.scenes.length) + { + var scene = this.getScene(key); + + this.scenes.splice(index, 1); + this.scenes.push(scene); + } + } + + return this; + }, + + /** + * Sends a Scene to the back of the Scenes list. + * + * This means it will render below all other Scenes. + * + * @method Phaser.Scenes.SceneManager#sendToBack + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + sendToBack: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'sendToBack', keyA: key, keyB: null }); + } + else + { + var index = this.getIndex(key); + + if (index !== -1 && index > 0) + { + var scene = this.getScene(key); + + this.scenes.splice(index, 1); + this.scenes.unshift(scene); + } + } + + return this; + }, + + /** + * Moves a Scene down one position in the Scenes list. + * + * @method Phaser.Scenes.SceneManager#moveDown + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveDown: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'moveDown', keyA: key, keyB: null }); + } + else + { + var indexA = this.getIndex(key); + + if (indexA > 0) + { + var indexB = indexA - 1; + var sceneA = this.getScene(key); + var sceneB = this.getAt(indexB); + + this.scenes[indexA] = sceneB; + this.scenes[indexB] = sceneA; + } + } + + return this; + }, + + /** + * Moves a Scene up one position in the Scenes list. + * + * @method Phaser.Scenes.SceneManager#moveUp + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} key - The Scene to move. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveUp: function (key) + { + if (this.isProcessing) + { + this._queue.push({ op: 'moveUp', keyA: key, keyB: null }); + } + else + { + var indexA = this.getIndex(key); + + if (indexA < this.scenes.length - 1) + { + var indexB = indexA + 1; + var sceneA = this.getScene(key); + var sceneB = this.getAt(indexB); + + this.scenes[indexA] = sceneB; + this.scenes[indexB] = sceneA; + } + } + + return this; + }, + + /** + * Moves a Scene so it is immediately above another Scene in the Scenes list. + * + * This means it will render over the top of the other Scene. + * + * @method Phaser.Scenes.SceneManager#moveAbove + * @since 3.2.0 + * + * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. + * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveAbove: function (keyA, keyB) + { + if (keyA === keyB) + { + return this; + } + + if (this.isProcessing) + { + this._queue.push({ op: 'moveAbove', keyA: keyA, keyB: keyB }); + } + else + { + var indexA = this.getIndex(keyA); + var indexB = this.getIndex(keyB); + + if (indexA !== -1 && indexB !== -1) + { + var tempScene = this.getAt(indexB); + + // Remove + this.scenes.splice(indexB, 1); + + // Add in new location + this.scenes.splice(indexA + 1, 0, tempScene); + } + } + + return this; + }, + + /** + * Moves a Scene so it is immediately below another Scene in the Scenes list. + * + * This means it will render behind the other Scene. + * + * @method Phaser.Scenes.SceneManager#moveBelow + * @since 3.2.0 + * + * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. + * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + moveBelow: function (keyA, keyB) + { + if (keyA === keyB) + { + return this; + } + + if (this.isProcessing) + { + this._queue.push({ op: 'moveBelow', keyA: keyA, keyB: keyB }); + } + else + { + var indexA = this.getIndex(keyA); + var indexB = this.getIndex(keyB); + + if (indexA !== -1 && indexB !== -1) + { + var tempScene = this.getAt(indexB); + + // Remove + this.scenes.splice(indexB, 1); + + if (indexA === 0) + { + this.scenes.unshift(tempScene); + } + else + { + // Add in new location + this.scenes.splice(indexA, 0, tempScene); + } + } + } + + return this; + }, + + /** + * Queue a Scene operation for the next update. + * + * @method Phaser.Scenes.SceneManager#queueOp + * @private + * @since 3.0.0 + * + * @param {string} op - The operation to perform. + * @param {(string|Phaser.Scene)} keyA - Scene A. + * @param {(any|string|Phaser.Scene)} [keyB] - Scene B, or a data object. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + queueOp: function (op, keyA, keyB) + { + this._queue.push({ op: op, keyA: keyA, keyB: keyB }); + + return this; + }, + + /** + * Swaps the positions of two Scenes in the Scenes list. + * + * @method Phaser.Scenes.SceneManager#swapPosition + * @since 3.0.0 + * + * @param {(string|Phaser.Scene)} keyA - The first Scene to swap. + * @param {(string|Phaser.Scene)} keyB - The second Scene to swap. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + swapPosition: function (keyA, keyB) + { + if (keyA === keyB) + { + return this; + } + + if (this.isProcessing) + { + this._queue.push({ op: 'swapPosition', keyA: keyA, keyB: keyB }); + } + else + { + var indexA = this.getIndex(keyA); + var indexB = this.getIndex(keyB); + + if (indexA !== indexB && indexA !== -1 && indexB !== -1) + { + var tempScene = this.getAt(indexA); + + this.scenes[indexA] = this.scenes[indexB]; + this.scenes[indexB] = tempScene; + } + } + + return this; + }, + + /** + * Dumps debug information about each Scene to the developer console. + * + * @method Phaser.Scenes.SceneManager#dump + * @since 3.2.0 + */ + dump: function () + { + var out = []; + var map = [ 'pending', 'init', 'start', 'loading', 'creating', 'running', 'paused', 'sleeping', 'shutdown', 'destroyed' ]; + + for (var i = 0; i < this.scenes.length; i++) + { + var sys = this.scenes[i].sys; + + var key = (sys.settings.visible && (sys.settings.status === CONST.RUNNING || sys.settings.status === CONST.PAUSED)) ? '[*] ' : '[-] '; + key += sys.settings.key + ' (' + map[sys.settings.status] + ')'; + + out.push(key); + } + + console.log(out.join('\n')); + }, + + /** + * Destroy the SceneManager and all of its Scene's systems. + * + * @method Phaser.Scenes.SceneManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + for (var i = 0; i < this.scenes.length; i++) + { + var sys = this.scenes[i].sys; + + sys.destroy(); + } + + this.update = NOOP; + + this.scenes = []; + + this._pending = []; + this._start = []; + this._queue = []; + + this.game = null; + } + +}); + +module.exports = SceneManager; diff --git a/src/scene/ScenePlugin.js b/src/scene/ScenePlugin.js index ad01d6cde..0dd7a5ec3 100644 --- a/src/scene/ScenePlugin.js +++ b/src/scene/ScenePlugin.js @@ -1,1004 +1,1004 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../math/Clamp'); -var Class = require('../utils/Class'); -var Events = require('./events'); -var GetFastValue = require('../utils/object/GetFastValue'); -var PluginCache = require('../plugins/PluginCache'); - -/** - * @classdesc - * A proxy class to the Global Scene Manager. - * - * @class ScenePlugin - * @memberof Phaser.Scenes - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that this ScenePlugin belongs to. - */ -var ScenePlugin = new Class({ - - initialize: - - function ScenePlugin (scene) - { - /** - * The Scene that this ScenePlugin belongs to. - * - * @name Phaser.Scenes.ScenePlugin#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The Scene Systems instance of the Scene that this ScenePlugin belongs to. - * - * @name Phaser.Scenes.ScenePlugin#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * The settings of the Scene this ScenePlugin belongs to. - * - * @name Phaser.Scenes.ScenePlugin#settings - * @type {Phaser.Types.Scenes.SettingsObject} - * @since 3.0.0 - */ - this.settings = scene.sys.settings; - - /** - * The key of the Scene this ScenePlugin belongs to. - * - * @name Phaser.Scenes.ScenePlugin#key - * @type {string} - * @since 3.0.0 - */ - this.key = scene.sys.settings.key; - - /** - * The Game's SceneManager. - * - * @name Phaser.Scenes.ScenePlugin#manager - * @type {Phaser.Scenes.SceneManager} - * @since 3.0.0 - */ - this.manager = scene.sys.game.scene; - - /** - * If this Scene is currently transitioning to another, this holds - * the current percentage of the transition progress, between 0 and 1. - * - * @name Phaser.Scenes.ScenePlugin#transitionProgress - * @type {number} - * @since 3.5.0 - */ - this.transitionProgress = 0; - - /** - * Transition elapsed timer. - * - * @name Phaser.Scenes.ScenePlugin#_elapsed - * @type {integer} - * @private - * @since 3.5.0 - */ - this._elapsed = 0; - - /** - * Transition elapsed timer. - * - * @name Phaser.Scenes.ScenePlugin#_target - * @type {?Phaser.Scenes.Scene} - * @private - * @since 3.5.0 - */ - this._target = null; - - /** - * Transition duration. - * - * @name Phaser.Scenes.ScenePlugin#_duration - * @type {integer} - * @private - * @since 3.5.0 - */ - this._duration = 0; - - /** - * Transition callback. - * - * @name Phaser.Scenes.ScenePlugin#_onUpdate - * @type {function} - * @private - * @since 3.5.0 - */ - this._onUpdate; - - /** - * Transition callback scope. - * - * @name Phaser.Scenes.ScenePlugin#_onUpdateScope - * @type {object} - * @private - * @since 3.5.0 - */ - this._onUpdateScope; - - /** - * Will this Scene sleep (true) after the transition, or stop (false) - * - * @name Phaser.Scenes.ScenePlugin#_willSleep - * @type {boolean} - * @private - * @since 3.5.0 - */ - this._willSleep = false; - - /** - * Will this Scene be removed from the Scene Manager after the transition completes? - * - * @name Phaser.Scenes.ScenePlugin#_willRemove - * @type {boolean} - * @private - * @since 3.5.0 - */ - this._willRemove = false; - - scene.sys.events.once(Events.BOOT, this.boot, this); - scene.sys.events.on(Events.START, this.pluginStart, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Scenes.ScenePlugin#boot - * @private - * @since 3.0.0 - */ - boot: function () - { - this.systems.events.once(Events.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Scenes.ScenePlugin#pluginStart - * @private - * @since 3.5.0 - */ - pluginStart: function () - { - this._target = null; - - this.systems.events.once(Events.SHUTDOWN, this.shutdown, this); - }, - - /** - * Shutdown this Scene and run the given one. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#start - * @since 3.0.0 - * - * @param {string} [key] - The Scene to start. - * @param {object} [data] - The Scene data. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - start: function (key, data) - { - if (key === undefined) { key = this.key; } - - this.manager.queueOp('stop', this.key); - this.manager.queueOp('start', key, data); - - return this; - }, - - /** - * Restarts this Scene. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#restart - * @since 3.4.0 - * - * @param {object} [data] - The Scene data. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - restart: function (data) - { - var key = this.key; - - this.manager.queueOp('stop', key); - this.manager.queueOp('start', key, data); - - return this; - }, - - /** - * This will start a transition from the current Scene to the target Scene given. - * - * The transition will last for the duration specified in milliseconds. - * - * You can have the target Scene moved above or below this one in the display list. - * - * You can specify an update callback. This callback will be invoked _every frame_ for the duration - * of the transition. - * - * This Scene can either be sent to sleep at the end of the transition, or stopped. The default is to stop. - * - * There are also 5 transition related events: This scene will emit the event `transitionout` when - * the transition begins, which is typically the frame after calling this method. - * - * The target Scene will emit the event `transitioninit` when that Scene's `init` method is called. - * It will then emit the event `transitionstart` when its `create` method is called. - * If the Scene was sleeping and has been woken up, it will emit the event `transitionwake` instead of these two, - * as the Scenes `init` and `create` methods are not invoked when a Scene wakes up. - * - * When the duration of the transition has elapsed it will emit the event `transitioncomplete`. - * These events are cleared of all listeners when the Scene shuts down, but not if it is sent to sleep. - * - * It's important to understand that the duration of the transition begins the moment you call this method. - * If the Scene you are transitioning to includes delayed processes, such as waiting for files to load, the - * time still counts down even while that is happening. If the game itself pauses, or something else causes - * this Scenes update loop to stop, then the transition will also pause for that duration. There are - * checks in place to prevent you accidentally stopping a transitioning Scene but if you've got code to - * override this understand that until the target Scene completes it might never be unlocked for input events. - * - * @method Phaser.Scenes.ScenePlugin#transition - * @fires Phaser.Scenes.Events#TRANSITION_OUT - * @since 3.5.0 - * - * @param {Phaser.Types.Scenes.SceneTransitionConfig} config - The transition configuration object. - * - * @return {boolean} `true` is the transition was started, otherwise `false`. - */ - transition: function (config) - { - if (config === undefined) { config = {}; } - - var key = GetFastValue(config, 'target', false); - - var target = this.manager.getScene(key); - - if (!key || !this.checkValidTransition(target)) - { - return false; - } - - var duration = GetFastValue(config, 'duration', 1000); - - this._elapsed = 0; - this._target = target; - this._duration = duration; - this._willSleep = GetFastValue(config, 'sleep', false); - this._willRemove = GetFastValue(config, 'remove', false); - - var callback = GetFastValue(config, 'onUpdate', null); - - if (callback) - { - this._onUpdate = callback; - this._onUpdateScope = GetFastValue(config, 'onUpdateScope', this.scene); - } - - var allowInput = GetFastValue(config, 'allowInput', false); - - this.settings.transitionAllowInput = allowInput; - - var targetSettings = target.sys.settings; - - targetSettings.isTransition = true; - targetSettings.transitionFrom = this.scene; - targetSettings.transitionDuration = duration; - targetSettings.transitionAllowInput = allowInput; - - if (GetFastValue(config, 'moveAbove', false)) - { - this.manager.moveAbove(this.key, key); - } - else if (GetFastValue(config, 'moveBelow', false)) - { - this.manager.moveBelow(this.key, key); - } - - if (target.sys.isSleeping()) - { - target.sys.wake(); - } - else - { - this.manager.start(key, GetFastValue(config, 'data')); - } - - this.systems.events.emit(Events.TRANSITION_OUT, target, duration); - - this.systems.events.on(Events.UPDATE, this.step, this); - - return true; - }, - - /** - * Checks to see if this Scene can transition to the target Scene or not. - * - * @method Phaser.Scenes.ScenePlugin#checkValidTransition - * @private - * @since 3.5.0 - * - * @param {Phaser.Scene} target - The Scene to test against. - * - * @return {boolean} `true` if this Scene can transition, otherwise `false`. - */ - checkValidTransition: function (target) - { - // Not a valid target if it doesn't exist, isn't active or is already transitioning in or out - if (!target || target.sys.isActive() || target.sys.isTransitioning() || target === this.scene || this.systems.isTransitioning()) - { - return false; - } - - return true; - }, - - /** - * 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. - */ - step: function (time, delta) - { - this._elapsed += delta; - - this.transitionProgress = Clamp(this._elapsed / this._duration, 0, 1); - - if (this._onUpdate) - { - this._onUpdate.call(this._onUpdateScope, this.transitionProgress); - } - - if (this._elapsed >= this._duration) - { - this.transitionComplete(); - } - }, - - /** - * Called by `step` when the transition out of this scene to another is over. - * - * @method Phaser.Scenes.ScenePlugin#transitionComplete - * @private - * @fires Phaser.Scenes.Events#TRANSITION_COMPLETE - * @since 3.5.0 - */ - transitionComplete: function () - { - var targetSys = this._target.sys; - var targetSettings = this._target.sys.settings; - - // Stop the step - this.systems.events.off(Events.UPDATE, this.step, this); - - // Notify target scene - targetSys.events.emit(Events.TRANSITION_COMPLETE, this.scene); - - // Clear target scene settings - targetSettings.isTransition = false; - targetSettings.transitionFrom = null; - - // Clear local settings - this._duration = 0; - this._target = null; - this._onUpdate = null; - this._onUpdateScope = null; - - // Now everything is clear we can handle what happens to this Scene - if (this._willRemove) - { - this.manager.remove(this.key); - } - else if (this._willSleep) - { - this.systems.sleep(); - } - else - { - this.manager.stop(this.key); - } - }, - - /** - * Add the Scene into the Scene Manager and start it if 'autoStart' is true or the Scene config 'active' property is set. - * - * @method Phaser.Scenes.ScenePlugin#add - * @since 3.0.0 - * - * @param {string} key - The Scene key. - * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene. - * @param {boolean} autoStart - Whether to start the Scene after it's added. - * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. - * - * @return {Phaser.Scene} An instance of the Scene that was added to the Scene Manager. - */ - add: function (key, sceneConfig, autoStart, data) - { - return this.manager.add(key, sceneConfig, autoStart, data); - }, - - /** - * Launch the given Scene and run it in parallel with this one. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#launch - * @since 3.0.0 - * - * @param {string} key - The Scene to launch. - * @param {object} [data] - The Scene data. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - launch: function (key, data) - { - if (key && key !== this.key) - { - this.manager.queueOp('start', key, data); - } - - return this; - }, - - /** - * Runs the given Scene, but does not change the state of this Scene. - * - * This will happen at the next Scene Manager update, not immediately. - * - * If the given Scene is paused, it will resume it. If sleeping, it will wake it. - * If not running at all, it will be started. - * - * Use this if you wish to open a modal Scene by calling `pause` on the current - * Scene, then `run` on the modal Scene. - * - * @method Phaser.Scenes.ScenePlugin#run - * @since 3.10.0 - * - * @param {string} key - The Scene to run. - * @param {object} [data] - A data object that will be passed to the Scene and emitted in its ready, wake, or resume events. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - run: function (key, data) - { - if (key && key !== this.key) - { - this.manager.queueOp('run', key, data); - } - - return this; - }, - - /** - * Pause the Scene - this stops the update step from happening but it still renders. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#pause - * @since 3.0.0 - * - * @param {string} [key] - The Scene to pause. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its pause event. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - pause: function (key, data) - { - if (key === undefined) { key = this.key; } - - this.manager.queueOp('pause', key, data); - - return this; - }, - - /** - * Resume the Scene - starts the update loop again. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#resume - * @since 3.0.0 - * - * @param {string} [key] - The Scene to resume. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its resume event. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - resume: function (key, data) - { - if (key === undefined) { key = this.key; } - - this.manager.queueOp('resume', key, data); - - return this; - }, - - /** - * Makes the Scene sleep (no update, no render) but doesn't shutdown. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#sleep - * @since 3.0.0 - * - * @param {string} [key] - The Scene to put to sleep. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its sleep event. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - sleep: function (key, data) - { - if (key === undefined) { key = this.key; } - - this.manager.queueOp('sleep', key, data); - - return this; - }, - - /** - * Makes the Scene wake-up (starts update and render) - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#wake - * @since 3.0.0 - * - * @param {string} [key] - The Scene to wake up. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its wake event. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - wake: function (key, data) - { - if (key === undefined) { key = this.key; } - - this.manager.queueOp('wake', key, data); - - return this; - }, - - /** - * Makes this Scene sleep then starts the Scene given. - * - * This will happen at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#switch - * @since 3.0.0 - * - * @param {string} key - The Scene to start. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - switch: function (key) - { - if (key !== this.key) - { - this.manager.queueOp('switch', this.key, key); - } - - return this; - }, - - /** - * Shutdown the Scene, clearing display list, timers, etc. - * - * This happens at the next Scene Manager update, not immediately. - * - * @method Phaser.Scenes.ScenePlugin#stop - * @since 3.0.0 - * - * @param {string} [key] - The Scene to stop. - * @param {any} [data] - Optional data object to pass to Scene.Systems.shutdown. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - stop: function (key, data) - { - if (key === undefined) { key = this.key; } - - this.manager.queueOp('stop', key, data); - - return this; - }, - - /** - * Sets the active state of the given Scene. - * - * @method Phaser.Scenes.ScenePlugin#setActive - * @since 3.0.0 - * - * @param {boolean} value - If `true` the Scene will be resumed. If `false` it will be paused. - * @param {string} [key] - The Scene to set the active state of. - * @param {object} [data] - An optional data object that will be passed to the Scene and emitted with its events. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - setActive: function (value, key, data) - { - if (key === undefined) { key = this.key; } - - var scene = this.manager.getScene(key); - - if (scene) - { - scene.sys.setActive(value, data); - } - - return this; - }, - - /** - * Sets the visible state of the given Scene. - * - * @method Phaser.Scenes.ScenePlugin#setVisible - * @since 3.0.0 - * - * @param {boolean} value - The visible value. - * @param {string} [key] - The Scene to set the visible state for. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - setVisible: function (value, key) - { - if (key === undefined) { key = this.key; } - - var scene = this.manager.getScene(key); - - if (scene) - { - scene.sys.setVisible(value); - } - - return this; - }, - - /** - * Checks if the given Scene is sleeping or not? - * - * @method Phaser.Scenes.ScenePlugin#isSleeping - * @since 3.0.0 - * - * @param {string} [key] - The Scene to check. - * - * @return {boolean} Whether the Scene is sleeping. - */ - isSleeping: function (key) - { - if (key === undefined) { key = this.key; } - - return this.manager.isSleeping(key); - }, - - /** - * Checks if the given Scene is running or not? - * - * @method Phaser.Scenes.ScenePlugin#isActive - * @since 3.0.0 - * - * @param {string} [key] - The Scene to check. - * - * @return {boolean} Whether the Scene is running. - */ - isActive: function (key) - { - if (key === undefined) { key = this.key; } - - return this.manager.isActive(key); - }, - - /** - * Checks if the given Scene is paused or not? - * - * @method Phaser.Scenes.ScenePlugin#isPaused - * @since 3.17.0 - * - * @param {string} [key] - The Scene to check. - * - * @return {boolean} Whether the Scene is paused. - */ - isPaused: function (key) - { - if (key === undefined) { key = this.key; } - - return this.manager.isPaused(key); - }, - - /** - * Checks if the given Scene is visible or not? - * - * @method Phaser.Scenes.ScenePlugin#isVisible - * @since 3.0.0 - * - * @param {string} [key] - The Scene to check. - * - * @return {boolean} Whether the Scene is visible. - */ - isVisible: function (key) - { - if (key === undefined) { key = this.key; } - - return this.manager.isVisible(key); - }, - - /** - * Swaps the position of two scenes in the Scenes list. - * - * This controls the order in which they are rendered and updated. - * - * @method Phaser.Scenes.ScenePlugin#swapPosition - * @since 3.2.0 - * - * @param {string} keyA - The first Scene to swap. - * @param {string} [keyB] - The second Scene to swap. If none is given it defaults to this Scene. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - swapPosition: function (keyA, keyB) - { - if (keyB === undefined) { keyB = this.key; } - - if (keyA !== keyB) - { - this.manager.swapPosition(keyA, keyB); - } - - return this; - }, - - /** - * Swaps the position of two scenes in the Scenes list, so that Scene B is directly above Scene A. - * - * This controls the order in which they are rendered and updated. - * - * @method Phaser.Scenes.ScenePlugin#moveAbove - * @since 3.2.0 - * - * @param {string} keyA - The Scene that Scene B will be moved to be above. - * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - moveAbove: function (keyA, keyB) - { - if (keyB === undefined) { keyB = this.key; } - - if (keyA !== keyB) - { - this.manager.moveAbove(keyA, keyB); - } - - return this; - }, - - /** - * Swaps the position of two scenes in the Scenes list, so that Scene B is directly below Scene A. - * - * This controls the order in which they are rendered and updated. - * - * @method Phaser.Scenes.ScenePlugin#moveBelow - * @since 3.2.0 - * - * @param {string} keyA - The Scene that Scene B will be moved to be below. - * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - moveBelow: function (keyA, keyB) - { - if (keyB === undefined) { keyB = this.key; } - - if (keyA !== keyB) - { - this.manager.moveBelow(keyA, keyB); - } - - return this; - }, - - /** - * Removes a Scene from the SceneManager. - * - * The Scene is removed from the local scenes array, it's key is cleared from the keys - * cache and Scene.Systems.destroy is then called on it. - * - * If the SceneManager is processing the Scenes when this method is called it will - * queue the operation for the next update sequence. - * - * @method Phaser.Scenes.ScenePlugin#remove - * @since 3.2.0 - * - * @param {(string|Phaser.Scene)} [key] - The Scene to be removed. - * - * @return {Phaser.Scenes.SceneManager} This SceneManager. - */ - remove: function (key) - { - if (key === undefined) { key = this.key; } - - this.manager.remove(key); - - return this; - }, - - /** - * Moves a Scene up one position in the Scenes list. - * - * @method Phaser.Scenes.ScenePlugin#moveUp - * @since 3.0.0 - * - * @param {string} [key] - The Scene to move. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - moveUp: function (key) - { - if (key === undefined) { key = this.key; } - - this.manager.moveUp(key); - - return this; - }, - - /** - * Moves a Scene down one position in the Scenes list. - * - * @method Phaser.Scenes.ScenePlugin#moveDown - * @since 3.0.0 - * - * @param {string} [key] - The Scene to move. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - moveDown: function (key) - { - if (key === undefined) { key = this.key; } - - this.manager.moveDown(key); - - return this; - }, - - /** - * Brings a Scene to the top of the Scenes list. - * - * This means it will render above all other Scenes. - * - * @method Phaser.Scenes.ScenePlugin#bringToTop - * @since 3.0.0 - * - * @param {string} [key] - The Scene to move. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - bringToTop: function (key) - { - if (key === undefined) { key = this.key; } - - this.manager.bringToTop(key); - - return this; - }, - - /** - * Sends a Scene to the back of the Scenes list. - * - * This means it will render below all other Scenes. - * - * @method Phaser.Scenes.ScenePlugin#sendToBack - * @since 3.0.0 - * - * @param {string} [key] - The Scene to move. - * - * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. - */ - sendToBack: function (key) - { - if (key === undefined) { key = this.key; } - - this.manager.sendToBack(key); - - return this; - }, - - /** - * Retrieve a Scene. - * - * @method Phaser.Scenes.ScenePlugin#get - * @since 3.0.0 - * - * @param {string} key - The Scene to retrieve. - * - * @return {Phaser.Scene} The Scene. - */ - get: function (key) - { - return this.manager.getScene(key); - }, - - /** - * Retrieves the numeric index of a Scene in the Scenes list. - * - * @method Phaser.Scenes.ScenePlugin#getIndex - * @since 3.7.0 - * - * @param {(string|Phaser.Scene)} [key] - The Scene to get the index of. - * - * @return {integer} The index of the Scene. - */ - getIndex: function (key) - { - if (key === undefined) { key = this.key; } - - return this.manager.getIndex(key); - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Scenes.ScenePlugin#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.off(Events.SHUTDOWN, this.shutdown, this); - eventEmitter.off(Events.POST_UPDATE, this.step, this); - eventEmitter.off(Events.TRANSITION_OUT); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Scenes.ScenePlugin#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(Events.START, this.start, this); - - this.scene = null; - this.systems = null; - this.settings = null; - this.manager = null; - } - -}); - -PluginCache.register('ScenePlugin', ScenePlugin, 'scenePlugin'); - -module.exports = ScenePlugin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../math/Clamp'); +var Class = require('../utils/Class'); +var Events = require('./events'); +var GetFastValue = require('../utils/object/GetFastValue'); +var PluginCache = require('../plugins/PluginCache'); + +/** + * @classdesc + * A proxy class to the Global Scene Manager. + * + * @class ScenePlugin + * @memberof Phaser.Scenes + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that this ScenePlugin belongs to. + */ +var ScenePlugin = new Class({ + + initialize: + + function ScenePlugin (scene) + { + /** + * The Scene that this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene Systems instance of the Scene that this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The settings of the Scene this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#settings + * @type {Phaser.Types.Scenes.SettingsObject} + * @since 3.0.0 + */ + this.settings = scene.sys.settings; + + /** + * The key of the Scene this ScenePlugin belongs to. + * + * @name Phaser.Scenes.ScenePlugin#key + * @type {string} + * @since 3.0.0 + */ + this.key = scene.sys.settings.key; + + /** + * The Game's SceneManager. + * + * @name Phaser.Scenes.ScenePlugin#manager + * @type {Phaser.Scenes.SceneManager} + * @since 3.0.0 + */ + this.manager = scene.sys.game.scene; + + /** + * If this Scene is currently transitioning to another, this holds + * the current percentage of the transition progress, between 0 and 1. + * + * @name Phaser.Scenes.ScenePlugin#transitionProgress + * @type {number} + * @since 3.5.0 + */ + this.transitionProgress = 0; + + /** + * Transition elapsed timer. + * + * @name Phaser.Scenes.ScenePlugin#_elapsed + * @type {integer} + * @private + * @since 3.5.0 + */ + this._elapsed = 0; + + /** + * Transition elapsed timer. + * + * @name Phaser.Scenes.ScenePlugin#_target + * @type {?Phaser.Scenes.Scene} + * @private + * @since 3.5.0 + */ + this._target = null; + + /** + * Transition duration. + * + * @name Phaser.Scenes.ScenePlugin#_duration + * @type {integer} + * @private + * @since 3.5.0 + */ + this._duration = 0; + + /** + * Transition callback. + * + * @name Phaser.Scenes.ScenePlugin#_onUpdate + * @type {function} + * @private + * @since 3.5.0 + */ + this._onUpdate; + + /** + * Transition callback scope. + * + * @name Phaser.Scenes.ScenePlugin#_onUpdateScope + * @type {object} + * @private + * @since 3.5.0 + */ + this._onUpdateScope; + + /** + * Will this Scene sleep (true) after the transition, or stop (false) + * + * @name Phaser.Scenes.ScenePlugin#_willSleep + * @type {boolean} + * @private + * @since 3.5.0 + */ + this._willSleep = false; + + /** + * Will this Scene be removed from the Scene Manager after the transition completes? + * + * @name Phaser.Scenes.ScenePlugin#_willRemove + * @type {boolean} + * @private + * @since 3.5.0 + */ + this._willRemove = false; + + scene.sys.events.once(Events.BOOT, this.boot, this); + scene.sys.events.on(Events.START, this.pluginStart, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Scenes.ScenePlugin#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + this.systems.events.once(Events.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Scenes.ScenePlugin#pluginStart + * @private + * @since 3.5.0 + */ + pluginStart: function () + { + this._target = null; + + this.systems.events.once(Events.SHUTDOWN, this.shutdown, this); + }, + + /** + * Shutdown this Scene and run the given one. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#start + * @since 3.0.0 + * + * @param {string} [key] - The Scene to start. + * @param {object} [data] - The Scene data. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + start: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('stop', this.key); + this.manager.queueOp('start', key, data); + + return this; + }, + + /** + * Restarts this Scene. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#restart + * @since 3.4.0 + * + * @param {object} [data] - The Scene data. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + restart: function (data) + { + var key = this.key; + + this.manager.queueOp('stop', key); + this.manager.queueOp('start', key, data); + + return this; + }, + + /** + * This will start a transition from the current Scene to the target Scene given. + * + * The transition will last for the duration specified in milliseconds. + * + * You can have the target Scene moved above or below this one in the display list. + * + * You can specify an update callback. This callback will be invoked _every frame_ for the duration + * of the transition. + * + * This Scene can either be sent to sleep at the end of the transition, or stopped. The default is to stop. + * + * There are also 5 transition related events: This scene will emit the event `transitionout` when + * the transition begins, which is typically the frame after calling this method. + * + * The target Scene will emit the event `transitioninit` when that Scene's `init` method is called. + * It will then emit the event `transitionstart` when its `create` method is called. + * If the Scene was sleeping and has been woken up, it will emit the event `transitionwake` instead of these two, + * as the Scenes `init` and `create` methods are not invoked when a Scene wakes up. + * + * When the duration of the transition has elapsed it will emit the event `transitioncomplete`. + * These events are cleared of all listeners when the Scene shuts down, but not if it is sent to sleep. + * + * It's important to understand that the duration of the transition begins the moment you call this method. + * If the Scene you are transitioning to includes delayed processes, such as waiting for files to load, the + * time still counts down even while that is happening. If the game itself pauses, or something else causes + * this Scenes update loop to stop, then the transition will also pause for that duration. There are + * checks in place to prevent you accidentally stopping a transitioning Scene but if you've got code to + * override this understand that until the target Scene completes it might never be unlocked for input events. + * + * @method Phaser.Scenes.ScenePlugin#transition + * @fires Phaser.Scenes.Events#TRANSITION_OUT + * @since 3.5.0 + * + * @param {Phaser.Types.Scenes.SceneTransitionConfig} config - The transition configuration object. + * + * @return {boolean} `true` is the transition was started, otherwise `false`. + */ + transition: function (config) + { + if (config === undefined) { config = {}; } + + var key = GetFastValue(config, 'target', false); + + var target = this.manager.getScene(key); + + if (!key || !this.checkValidTransition(target)) + { + return false; + } + + var duration = GetFastValue(config, 'duration', 1000); + + this._elapsed = 0; + this._target = target; + this._duration = duration; + this._willSleep = GetFastValue(config, 'sleep', false); + this._willRemove = GetFastValue(config, 'remove', false); + + var callback = GetFastValue(config, 'onUpdate', null); + + if (callback) + { + this._onUpdate = callback; + this._onUpdateScope = GetFastValue(config, 'onUpdateScope', this.scene); + } + + var allowInput = GetFastValue(config, 'allowInput', false); + + this.settings.transitionAllowInput = allowInput; + + var targetSettings = target.sys.settings; + + targetSettings.isTransition = true; + targetSettings.transitionFrom = this.scene; + targetSettings.transitionDuration = duration; + targetSettings.transitionAllowInput = allowInput; + + if (GetFastValue(config, 'moveAbove', false)) + { + this.manager.moveAbove(this.key, key); + } + else if (GetFastValue(config, 'moveBelow', false)) + { + this.manager.moveBelow(this.key, key); + } + + if (target.sys.isSleeping()) + { + target.sys.wake(); + } + else + { + this.manager.start(key, GetFastValue(config, 'data')); + } + + this.systems.events.emit(Events.TRANSITION_OUT, target, duration); + + this.systems.events.on(Events.UPDATE, this.step, this); + + return true; + }, + + /** + * Checks to see if this Scene can transition to the target Scene or not. + * + * @method Phaser.Scenes.ScenePlugin#checkValidTransition + * @private + * @since 3.5.0 + * + * @param {Phaser.Scene} target - The Scene to test against. + * + * @return {boolean} `true` if this Scene can transition, otherwise `false`. + */ + checkValidTransition: function (target) + { + // Not a valid target if it doesn't exist, isn't active or is already transitioning in or out + if (!target || target.sys.isActive() || target.sys.isTransitioning() || target === this.scene || this.systems.isTransitioning()) + { + return false; + } + + return true; + }, + + /** + * 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. + */ + step: function (time, delta) + { + this._elapsed += delta; + + this.transitionProgress = Clamp(this._elapsed / this._duration, 0, 1); + + if (this._onUpdate) + { + this._onUpdate.call(this._onUpdateScope, this.transitionProgress); + } + + if (this._elapsed >= this._duration) + { + this.transitionComplete(); + } + }, + + /** + * Called by `step` when the transition out of this scene to another is over. + * + * @method Phaser.Scenes.ScenePlugin#transitionComplete + * @private + * @fires Phaser.Scenes.Events#TRANSITION_COMPLETE + * @since 3.5.0 + */ + transitionComplete: function () + { + var targetSys = this._target.sys; + var targetSettings = this._target.sys.settings; + + // Stop the step + this.systems.events.off(Events.UPDATE, this.step, this); + + // Notify target scene + targetSys.events.emit(Events.TRANSITION_COMPLETE, this.scene); + + // Clear target scene settings + targetSettings.isTransition = false; + targetSettings.transitionFrom = null; + + // Clear local settings + this._duration = 0; + this._target = null; + this._onUpdate = null; + this._onUpdateScope = null; + + // Now everything is clear we can handle what happens to this Scene + if (this._willRemove) + { + this.manager.remove(this.key); + } + else if (this._willSleep) + { + this.systems.sleep(); + } + else + { + this.manager.stop(this.key); + } + }, + + /** + * Add the Scene into the Scene Manager and start it if 'autoStart' is true or the Scene config 'active' property is set. + * + * @method Phaser.Scenes.ScenePlugin#add + * @since 3.0.0 + * + * @param {string} key - The Scene key. + * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene. + * @param {boolean} autoStart - Whether to start the Scene after it's added. + * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. + * + * @return {Phaser.Scene} An instance of the Scene that was added to the Scene Manager. + */ + add: function (key, sceneConfig, autoStart, data) + { + return this.manager.add(key, sceneConfig, autoStart, data); + }, + + /** + * Launch the given Scene and run it in parallel with this one. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#launch + * @since 3.0.0 + * + * @param {string} key - The Scene to launch. + * @param {object} [data] - The Scene data. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + launch: function (key, data) + { + if (key && key !== this.key) + { + this.manager.queueOp('start', key, data); + } + + return this; + }, + + /** + * Runs the given Scene, but does not change the state of this Scene. + * + * This will happen at the next Scene Manager update, not immediately. + * + * If the given Scene is paused, it will resume it. If sleeping, it will wake it. + * If not running at all, it will be started. + * + * Use this if you wish to open a modal Scene by calling `pause` on the current + * Scene, then `run` on the modal Scene. + * + * @method Phaser.Scenes.ScenePlugin#run + * @since 3.10.0 + * + * @param {string} key - The Scene to run. + * @param {object} [data] - A data object that will be passed to the Scene and emitted in its ready, wake, or resume events. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + run: function (key, data) + { + if (key && key !== this.key) + { + this.manager.queueOp('run', key, data); + } + + return this; + }, + + /** + * Pause the Scene - this stops the update step from happening but it still renders. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#pause + * @since 3.0.0 + * + * @param {string} [key] - The Scene to pause. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its pause event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + pause: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('pause', key, data); + + return this; + }, + + /** + * Resume the Scene - starts the update loop again. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#resume + * @since 3.0.0 + * + * @param {string} [key] - The Scene to resume. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its resume event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + resume: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('resume', key, data); + + return this; + }, + + /** + * Makes the Scene sleep (no update, no render) but doesn't shutdown. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#sleep + * @since 3.0.0 + * + * @param {string} [key] - The Scene to put to sleep. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its sleep event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + sleep: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('sleep', key, data); + + return this; + }, + + /** + * Makes the Scene wake-up (starts update and render) + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#wake + * @since 3.0.0 + * + * @param {string} [key] - The Scene to wake up. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its wake event. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + wake: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('wake', key, data); + + return this; + }, + + /** + * Makes this Scene sleep then starts the Scene given. + * + * This will happen at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#switch + * @since 3.0.0 + * + * @param {string} key - The Scene to start. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + switch: function (key) + { + if (key !== this.key) + { + this.manager.queueOp('switch', this.key, key); + } + + return this; + }, + + /** + * Shutdown the Scene, clearing display list, timers, etc. + * + * This happens at the next Scene Manager update, not immediately. + * + * @method Phaser.Scenes.ScenePlugin#stop + * @since 3.0.0 + * + * @param {string} [key] - The Scene to stop. + * @param {any} [data] - Optional data object to pass to Scene.Systems.shutdown. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + stop: function (key, data) + { + if (key === undefined) { key = this.key; } + + this.manager.queueOp('stop', key, data); + + return this; + }, + + /** + * Sets the active state of the given Scene. + * + * @method Phaser.Scenes.ScenePlugin#setActive + * @since 3.0.0 + * + * @param {boolean} value - If `true` the Scene will be resumed. If `false` it will be paused. + * @param {string} [key] - The Scene to set the active state of. + * @param {object} [data] - An optional data object that will be passed to the Scene and emitted with its events. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + setActive: function (value, key, data) + { + if (key === undefined) { key = this.key; } + + var scene = this.manager.getScene(key); + + if (scene) + { + scene.sys.setActive(value, data); + } + + return this; + }, + + /** + * Sets the visible state of the given Scene. + * + * @method Phaser.Scenes.ScenePlugin#setVisible + * @since 3.0.0 + * + * @param {boolean} value - The visible value. + * @param {string} [key] - The Scene to set the visible state for. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + setVisible: function (value, key) + { + if (key === undefined) { key = this.key; } + + var scene = this.manager.getScene(key); + + if (scene) + { + scene.sys.setVisible(value); + } + + return this; + }, + + /** + * Checks if the given Scene is sleeping or not? + * + * @method Phaser.Scenes.ScenePlugin#isSleeping + * @since 3.0.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is sleeping. + */ + isSleeping: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isSleeping(key); + }, + + /** + * Checks if the given Scene is running or not? + * + * @method Phaser.Scenes.ScenePlugin#isActive + * @since 3.0.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is running. + */ + isActive: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isActive(key); + }, + + /** + * Checks if the given Scene is paused or not? + * + * @method Phaser.Scenes.ScenePlugin#isPaused + * @since 3.17.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is paused. + */ + isPaused: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isPaused(key); + }, + + /** + * Checks if the given Scene is visible or not? + * + * @method Phaser.Scenes.ScenePlugin#isVisible + * @since 3.0.0 + * + * @param {string} [key] - The Scene to check. + * + * @return {boolean} Whether the Scene is visible. + */ + isVisible: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.isVisible(key); + }, + + /** + * Swaps the position of two scenes in the Scenes list. + * + * This controls the order in which they are rendered and updated. + * + * @method Phaser.Scenes.ScenePlugin#swapPosition + * @since 3.2.0 + * + * @param {string} keyA - The first Scene to swap. + * @param {string} [keyB] - The second Scene to swap. If none is given it defaults to this Scene. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + swapPosition: function (keyA, keyB) + { + if (keyB === undefined) { keyB = this.key; } + + if (keyA !== keyB) + { + this.manager.swapPosition(keyA, keyB); + } + + return this; + }, + + /** + * Swaps the position of two scenes in the Scenes list, so that Scene B is directly above Scene A. + * + * This controls the order in which they are rendered and updated. + * + * @method Phaser.Scenes.ScenePlugin#moveAbove + * @since 3.2.0 + * + * @param {string} keyA - The Scene that Scene B will be moved to be above. + * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveAbove: function (keyA, keyB) + { + if (keyB === undefined) { keyB = this.key; } + + if (keyA !== keyB) + { + this.manager.moveAbove(keyA, keyB); + } + + return this; + }, + + /** + * Swaps the position of two scenes in the Scenes list, so that Scene B is directly below Scene A. + * + * This controls the order in which they are rendered and updated. + * + * @method Phaser.Scenes.ScenePlugin#moveBelow + * @since 3.2.0 + * + * @param {string} keyA - The Scene that Scene B will be moved to be below. + * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveBelow: function (keyA, keyB) + { + if (keyB === undefined) { keyB = this.key; } + + if (keyA !== keyB) + { + this.manager.moveBelow(keyA, keyB); + } + + return this; + }, + + /** + * Removes a Scene from the SceneManager. + * + * The Scene is removed from the local scenes array, it's key is cleared from the keys + * cache and Scene.Systems.destroy is then called on it. + * + * If the SceneManager is processing the Scenes when this method is called it will + * queue the operation for the next update sequence. + * + * @method Phaser.Scenes.ScenePlugin#remove + * @since 3.2.0 + * + * @param {(string|Phaser.Scene)} [key] - The Scene to be removed. + * + * @return {Phaser.Scenes.SceneManager} This SceneManager. + */ + remove: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.remove(key); + + return this; + }, + + /** + * Moves a Scene up one position in the Scenes list. + * + * @method Phaser.Scenes.ScenePlugin#moveUp + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveUp: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.moveUp(key); + + return this; + }, + + /** + * Moves a Scene down one position in the Scenes list. + * + * @method Phaser.Scenes.ScenePlugin#moveDown + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + moveDown: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.moveDown(key); + + return this; + }, + + /** + * Brings a Scene to the top of the Scenes list. + * + * This means it will render above all other Scenes. + * + * @method Phaser.Scenes.ScenePlugin#bringToTop + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + bringToTop: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.bringToTop(key); + + return this; + }, + + /** + * Sends a Scene to the back of the Scenes list. + * + * This means it will render below all other Scenes. + * + * @method Phaser.Scenes.ScenePlugin#sendToBack + * @since 3.0.0 + * + * @param {string} [key] - The Scene to move. + * + * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object. + */ + sendToBack: function (key) + { + if (key === undefined) { key = this.key; } + + this.manager.sendToBack(key); + + return this; + }, + + /** + * Retrieve a Scene. + * + * @method Phaser.Scenes.ScenePlugin#get + * @since 3.0.0 + * + * @param {string} key - The Scene to retrieve. + * + * @return {Phaser.Scene} The Scene. + */ + get: function (key) + { + return this.manager.getScene(key); + }, + + /** + * Retrieves the numeric index of a Scene in the Scenes list. + * + * @method Phaser.Scenes.ScenePlugin#getIndex + * @since 3.7.0 + * + * @param {(string|Phaser.Scene)} [key] - The Scene to get the index of. + * + * @return {integer} The index of the Scene. + */ + getIndex: function (key) + { + if (key === undefined) { key = this.key; } + + return this.manager.getIndex(key); + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Scenes.ScenePlugin#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.off(Events.SHUTDOWN, this.shutdown, this); + eventEmitter.off(Events.POST_UPDATE, this.step, this); + eventEmitter.off(Events.TRANSITION_OUT); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Scenes.ScenePlugin#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(Events.START, this.start, this); + + this.scene = null; + this.systems = null; + this.settings = null; + this.manager = null; + } + +}); + +PluginCache.register('ScenePlugin', ScenePlugin, 'scenePlugin'); + +module.exports = ScenePlugin; diff --git a/src/scene/Settings.js b/src/scene/Settings.js index d53e866d1..5dd538db9 100644 --- a/src/scene/Settings.js +++ b/src/scene/Settings.js @@ -1,90 +1,90 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var GetValue = require('../utils/object/GetValue'); -var Merge = require('../utils/object/Merge'); -var InjectionMap = require('./InjectionMap'); - -/** - * @namespace Phaser.Scenes.Settings - */ - -var Settings = { - - /** - * Takes a Scene configuration object and returns a fully formed System Settings object. - * - * @function Phaser.Scenes.Settings.create - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - The Scene configuration object used to create this Scene Settings. - * - * @return {Phaser.Types.Scenes.SettingsObject} The Scene Settings object created as a result of the config and default settings. - */ - create: function (config) - { - if (typeof config === 'string') - { - config = { key: config }; - } - else if (config === undefined) - { - // Pass the 'hasOwnProperty' checks - config = {}; - } - - return { - - status: CONST.PENDING, - - key: GetValue(config, 'key', ''), - active: GetValue(config, 'active', false), - visible: GetValue(config, 'visible', true), - - isBooted: false, - - isTransition: false, - transitionFrom: null, - transitionDuration: 0, - transitionAllowInput: true, - - // Loader payload array - - data: {}, - - pack: GetValue(config, 'pack', false), - - // Cameras - - cameras: GetValue(config, 'cameras', null), - - // Scene Property Injection Map - - map: GetValue(config, 'map', Merge(InjectionMap, GetValue(config, 'mapAdd', {}))), - - // Physics - - physics: GetValue(config, 'physics', {}), - - // Loader - - loader: GetValue(config, 'loader', {}), - - // Plugins - - plugins: GetValue(config, 'plugins', false), - - // Input - - input: GetValue(config, 'input', {}) - - }; - } - -}; - -module.exports = Settings; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var GetValue = require('../utils/object/GetValue'); +var Merge = require('../utils/object/Merge'); +var InjectionMap = require('./InjectionMap'); + +/** + * @namespace Phaser.Scenes.Settings + */ + +var Settings = { + + /** + * Takes a Scene configuration object and returns a fully formed System Settings object. + * + * @function Phaser.Scenes.Settings.create + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - The Scene configuration object used to create this Scene Settings. + * + * @return {Phaser.Types.Scenes.SettingsObject} The Scene Settings object created as a result of the config and default settings. + */ + create: function (config) + { + if (typeof config === 'string') + { + config = { key: config }; + } + else if (config === undefined) + { + // Pass the 'hasOwnProperty' checks + config = {}; + } + + return { + + status: CONST.PENDING, + + key: GetValue(config, 'key', ''), + active: GetValue(config, 'active', false), + visible: GetValue(config, 'visible', true), + + isBooted: false, + + isTransition: false, + transitionFrom: null, + transitionDuration: 0, + transitionAllowInput: true, + + // Loader payload array + + data: {}, + + pack: GetValue(config, 'pack', false), + + // Cameras + + cameras: GetValue(config, 'cameras', null), + + // Scene Property Injection Map + + map: GetValue(config, 'map', Merge(InjectionMap, GetValue(config, 'mapAdd', {}))), + + // Physics + + physics: GetValue(config, 'physics', {}), + + // Loader + + loader: GetValue(config, 'loader', {}), + + // Plugins + + plugins: GetValue(config, 'plugins', false), + + // Input + + input: GetValue(config, 'input', {}) + + }; + } + +}; + +module.exports = Settings; diff --git a/src/scene/Systems.js b/src/scene/Systems.js index 48ebddb42..a0a233df9 100644 --- a/src/scene/Systems.js +++ b/src/scene/Systems.js @@ -1,777 +1,777 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var CONST = require('./const'); -var DefaultPlugins = require('../plugins/DefaultPlugins'); -var Events = require('./events'); -var GetPhysicsPlugins = require('./GetPhysicsPlugins'); -var GetScenePlugins = require('./GetScenePlugins'); -var NOOP = require('../utils/NOOP'); -var Settings = require('./Settings'); - -/** - * @classdesc - * The Scene Systems class. - * - * This class is available from within a Scene under the property `sys`. - * It is responsible for managing all of the plugins a Scene has running, including the display list, and - * handling the update step and renderer. It also contains references to global systems belonging to Game. - * - * @class Systems - * @memberof Phaser.Scenes - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene that owns this Systems instance. - * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - Scene specific configuration settings. - */ -var Systems = new Class({ - - initialize: - - function Systems (scene, config) - { - /** - * A reference to the Scene that these Systems belong to. - * - * @name Phaser.Scenes.Systems#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * A reference to the Phaser Game instance. - * - * @name Phaser.Scenes.Systems#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game; - - /** - * A reference to either the Canvas or WebGL Renderer that this Game is using. - * - * @name Phaser.Scenes.Systems#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.17.0 - */ - this.renderer; - - if (typeof PLUGIN_FBINSTANT) - { - /** - * The Facebook Instant Games Plugin. - * - * @name Phaser.Scenes.Systems#facebook - * @type {Phaser.FacebookInstantGamesPlugin} - * @since 3.12.0 - */ - this.facebook; - } - - /** - * The Scene Configuration object, as passed in when creating the Scene. - * - * @name Phaser.Scenes.Systems#config - * @type {(string|Phaser.Types.Scenes.SettingsConfig)} - * @since 3.0.0 - */ - this.config = config; - - /** - * 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 - */ - this.settings = Settings.create(config); - - /** - * A handy reference to the Scene canvas / context. - * - * @name Phaser.Scenes.Systems#canvas - * @type {HTMLCanvasElement} - * @since 3.0.0 - */ - this.canvas; - - /** - * A reference to the Canvas Rendering Context being used by the renderer. - * - * @name Phaser.Scenes.Systems#context - * @type {CanvasRenderingContext2D} - * @since 3.0.0 - */ - this.context; - - // Global Systems - these are single-instance global managers that belong to Game - - /** - * A reference to the global Animations Manager. - * - * In the default set-up you can access this from within a Scene via the `this.anims` property. - * - * @name Phaser.Scenes.Systems#anims - * @type {Phaser.Animations.AnimationManager} - * @since 3.0.0 - */ - this.anims; - - /** - * A reference to the global Cache. The Cache stores all files bought in to Phaser via - * the Loader, with the exception of images. Images are stored in the Texture Manager. - * - * In the default set-up you can access this from within a Scene via the `this.cache` property. - * - * @name Phaser.Scenes.Systems#cache - * @type {Phaser.Cache.CacheManager} - * @since 3.0.0 - */ - this.cache; - - /** - * A reference to the global Plugins Manager. - * - * In the default set-up you can access this from within a Scene via the `this.plugins` property. - * - * @name Phaser.Scenes.Systems#plugins - * @type {Phaser.Plugins.PluginManager} - * @since 3.0.0 - */ - this.plugins; - - /** - * A reference to the global registry. This is a game-wide instance of the Data Manager, allowing - * you to exchange data between Scenes via a universal and shared point. - * - * In the default set-up you can access this from within a Scene via the `this.registry` property. - * - * @name Phaser.Scenes.Systems#registry - * @type {Phaser.Data.DataManager} - * @since 3.0.0 - */ - this.registry; - - /** - * A reference to the global Scale Manager. - * - * In the default set-up you can access this from within a Scene via the `this.scale` property. - * - * @name Phaser.Scenes.Systems#scale - * @type {Phaser.Scale.ScaleManager} - * @since 3.15.0 - */ - this.scale; - - /** - * A reference to the global Sound Manager. - * - * In the default set-up you can access this from within a Scene via the `this.sound` property. - * - * @name Phaser.Scenes.Systems#sound - * @type {(Phaser.Sound.NoAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager)} - * @since 3.0.0 - */ - this.sound; - - /** - * A reference to the global Texture Manager. - * - * In the default set-up you can access this from within a Scene via the `this.textures` property. - * - * @name Phaser.Scenes.Systems#textures - * @type {Phaser.Textures.TextureManager} - * @since 3.0.0 - */ - this.textures; - - // Core Plugins - these are non-optional Scene plugins, needed by lots of the other systems - - /** - * A reference to the Scene's Game Object Factory. - * - * Use this to quickly and easily create new Game Object's. - * - * In the default set-up you can access this from within a Scene via the `this.add` property. - * - * @name Phaser.Scenes.Systems#add - * @type {Phaser.GameObjects.GameObjectFactory} - * @since 3.0.0 - */ - this.add; - - /** - * A reference to the Scene's Camera Manager. - * - * Use this to manipulate and create Cameras for this specific Scene. - * - * In the default set-up you can access this from within a Scene via the `this.cameras` property. - * - * @name Phaser.Scenes.Systems#cameras - * @type {Phaser.Cameras.Scene2D.CameraManager} - * @since 3.0.0 - */ - this.cameras; - - /** - * A reference to the Scene's Display List. - * - * Use this to organize the children contained in the display list. - * - * In the default set-up you can access this from within a Scene via the `this.children` property. - * - * @name Phaser.Scenes.Systems#displayList - * @type {Phaser.GameObjects.DisplayList} - * @since 3.0.0 - */ - this.displayList; - - /** - * A reference to the Scene's Event Manager. - * - * Use this to listen for Scene specific events, such as `pause` and `shutdown`. - * - * In the default set-up you can access this from within a Scene via the `this.events` property. - * - * @name Phaser.Scenes.Systems#events - * @type {Phaser.Events.EventEmitter} - * @since 3.0.0 - */ - this.events; - - /** - * A reference to the Scene's Game Object Creator. - * - * Use this to quickly and easily create new Game Object's. The difference between this and the - * Game Object Factory, is that the Creator just creates and returns Game Object instances, it - * doesn't then add them to the Display List or Update List. - * - * In the default set-up you can access this from within a Scene via the `this.make` property. - * - * @name Phaser.Scenes.Systems#make - * @type {Phaser.GameObjects.GameObjectCreator} - * @since 3.0.0 - */ - this.make; - - /** - * A reference to the Scene Manager Plugin. - * - * Use this to manipulate both this and other Scene's in your game, for example to launch a parallel Scene, - * or pause or resume a Scene, or switch from this Scene to another. - * - * In the default set-up you can access this from within a Scene via the `this.scene` property. - * - * @name Phaser.Scenes.Systems#scenePlugin - * @type {Phaser.Scenes.ScenePlugin} - * @since 3.0.0 - */ - this.scenePlugin; - - /** - * A reference to the Scene's Update List. - * - * Use this to organize the children contained in the update list. - * - * The Update List is responsible for managing children that need their `preUpdate` methods called, - * in order to process so internal components, such as Sprites with Animations. - * - * In the default set-up there is no reference to this from within the Scene itself. - * - * @name Phaser.Scenes.Systems#updateList - * @type {Phaser.GameObjects.UpdateList} - * @since 3.0.0 - */ - this.updateList; - - /** - * The Scene Update function. - * - * This starts out as NOOP during init, preload and create, and at the end of create - * it swaps to be whatever the Scene.update function is. - * - * @name Phaser.Scenes.Systems#sceneUpdate - * @type {function} - * @private - * @since 3.10.0 - */ - this.sceneUpdate = NOOP; - }, - - /** - * This method is called only once by the Scene Manager when the Scene is instantiated. - * It is responsible for setting up all of the Scene plugins and references. - * It should never be called directly. - * - * @method Phaser.Scenes.Systems#init - * @protected - * @fires Phaser.Scenes.Events#BOOT - * @since 3.0.0 - * - * @param {Phaser.Game} game - A reference to the Phaser Game instance. - */ - init: function (game) - { - this.settings.status = CONST.INIT; - - // This will get replaced by the SceneManager with the actual update function, if it exists, once create is over. - this.sceneUpdate = NOOP; - - this.game = game; - this.renderer = game.renderer; - - this.canvas = game.canvas; - this.context = game.context; - - var pluginManager = game.plugins; - - this.plugins = pluginManager; - - pluginManager.addToScene(this, DefaultPlugins.Global, [ DefaultPlugins.CoreScene, GetScenePlugins(this), GetPhysicsPlugins(this) ]); - - this.events.emit(Events.BOOT, this); - - this.settings.isBooted = true; - }, - - /** - * Called by a plugin, it tells the System to install the plugin locally. - * - * @method Phaser.Scenes.Systems#install - * @private - * @since 3.0.0 - * - * @param {array} plugin - An array of plugins to install into this Scene. - */ - install: function (plugin) - { - if (!Array.isArray(plugin)) - { - plugin = [ plugin ]; - } - - this.plugins.installLocal(this, plugin); - }, - - /** - * A single game step. Called automatically by the Scene Manager as a result of a Request Animation - * Frame or Set Timeout call to the main Game instance. - * - * @method Phaser.Scenes.Systems#step - * @fires Phaser.Scenes.Events#PRE_UPDATE - * @fires Phaser.Scenes.Events#_UPDATE - * @fires Phaser.Scenes.Events#POST_UPDATE - * @since 3.0.0 - * - * @param {number} time - The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). - * @param {number} delta - The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. - */ - step: function (time, delta) - { - this.events.emit(Events.PRE_UPDATE, time, delta); - - this.events.emit(Events.UPDATE, time, delta); - - this.sceneUpdate.call(this.scene, time, delta); - - this.events.emit(Events.POST_UPDATE, time, delta); - }, - - /** - * Called automatically by the Scene Manager. - * Instructs the Scene to render itself via its Camera Manager to the renderer given. - * - * @method Phaser.Scenes.Systems#render - * @fires Phaser.Scenes.Events#RENDER - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer that invoked the render call. - */ - render: function (renderer) - { - var displayList = this.displayList; - - displayList.depthSort(); - - this.cameras.render(renderer, displayList); - - this.events.emit(Events.RENDER, renderer); - }, - - /** - * Force a sort of the display list on the next render. - * - * @method Phaser.Scenes.Systems#queueDepthSort - * @since 3.0.0 - */ - queueDepthSort: function () - { - this.displayList.queueDepthSort(); - }, - - /** - * Immediately sorts the display list if the flag is set. - * - * @method Phaser.Scenes.Systems#depthSort - * @since 3.0.0 - */ - depthSort: function () - { - this.displayList.depthSort(); - }, - - /** - * Pause this Scene. - * A paused Scene still renders, it just doesn't run ANY of its update handlers or systems. - * - * @method Phaser.Scenes.Systems#pause - * @fires Phaser.Scenes.Events#PAUSE - * @since 3.0.0 - * - * @param {object} [data] - A data object that will be passed in the 'pause' event. - * - * @return {Phaser.Scenes.Systems} This Systems object. - */ - pause: function (data) - { - if (this.settings.active) - { - this.settings.status = CONST.PAUSED; - - this.settings.active = false; - - this.events.emit(Events.PAUSE, this, data); - } - - return this; - }, - - /** - * Resume this Scene from a paused state. - * - * @method Phaser.Scenes.Systems#resume - * @fires Phaser.Scenes.Events#RESUME - * @since 3.0.0 - * - * @param {object} [data] - A data object that will be passed in the 'resume' event. - * - * @return {Phaser.Scenes.Systems} This Systems object. - */ - resume: function (data) - { - if (!this.settings.active) - { - this.settings.status = CONST.RUNNING; - - this.settings.active = true; - - this.events.emit(Events.RESUME, this, data); - } - - return this; - }, - - /** - * Send this Scene to sleep. - * - * A sleeping Scene doesn't run its update step or render anything, but it also isn't shut down - * or has any of its systems or children removed, meaning it can be re-activated at any point and - * will carry on from where it left off. It also keeps everything in memory and events and callbacks - * from other Scenes may still invoke changes within it, so be careful what is left active. - * - * @method Phaser.Scenes.Systems#sleep - * @fires Phaser.Scenes.Events#SLEEP - * @since 3.0.0 - * - * @param {object} [data] - A data object that will be passed in the 'sleep' event. - * - * @return {Phaser.Scenes.Systems} This Systems object. - */ - sleep: function (data) - { - this.settings.status = CONST.SLEEPING; - - this.settings.active = false; - this.settings.visible = false; - - this.events.emit(Events.SLEEP, this, data); - - return this; - }, - - /** - * Wake-up this Scene if it was previously asleep. - * - * @method Phaser.Scenes.Systems#wake - * @fires Phaser.Scenes.Events#WAKE - * @since 3.0.0 - * - * @param {object} [data] - A data object that will be passed in the 'wake' event. - * - * @return {Phaser.Scenes.Systems} This Systems object. - */ - wake: function (data) - { - var settings = this.settings; - - settings.status = CONST.RUNNING; - - settings.active = true; - settings.visible = true; - - this.events.emit(Events.WAKE, this, data); - - if (settings.isTransition) - { - this.events.emit(Events.TRANSITION_WAKE, settings.transitionFrom, settings.transitionDuration); - } - - return this; - }, - - /** - * Returns any data that was sent to this Scene by another Scene. - * - * The data is also passed to `Scene.init` and in various Scene events, but - * you can access it at any point via this method. - * - * @method Phaser.Scenes.Systems#getData - * @since 3.22.0 - * - * @return {any} - */ - getData: function () - { - return this.settings.data; - }, - - /** - * Is this Scene sleeping? - * - * @method Phaser.Scenes.Systems#isSleeping - * @since 3.0.0 - * - * @return {boolean} `true` if this Scene is asleep, otherwise `false`. - */ - isSleeping: function () - { - return (this.settings.status === CONST.SLEEPING); - }, - - /** - * Is this Scene running? - * - * @method Phaser.Scenes.Systems#isActive - * @since 3.0.0 - * - * @return {boolean} `true` if this Scene is running, otherwise `false`. - */ - isActive: function () - { - return (this.settings.status === CONST.RUNNING); - }, - - /** - * Is this Scene paused? - * - * @method Phaser.Scenes.Systems#isPaused - * @since 3.13.0 - * - * @return {boolean} `true` if this Scene is paused, otherwise `false`. - */ - isPaused: function () - { - return (this.settings.status === CONST.PAUSED); - }, - - /** - * Is this Scene currently transitioning out to, or in from another Scene? - * - * @method Phaser.Scenes.Systems#isTransitioning - * @since 3.5.0 - * - * @return {boolean} `true` if this Scene is currently transitioning, otherwise `false`. - */ - isTransitioning: function () - { - return (this.settings.isTransition || this.scenePlugin._target !== null); - }, - - /** - * Is this Scene currently transitioning out from itself to another Scene? - * - * @method Phaser.Scenes.Systems#isTransitionOut - * @since 3.5.0 - * - * @return {boolean} `true` if this Scene is in transition to another Scene, otherwise `false`. - */ - isTransitionOut: function () - { - return (this.scenePlugin._target !== null && this.scenePlugin._duration > 0); - }, - - /** - * Is this Scene currently transitioning in from another Scene? - * - * @method Phaser.Scenes.Systems#isTransitionIn - * @since 3.5.0 - * - * @return {boolean} `true` if this Scene is transitioning in from another Scene, otherwise `false`. - */ - isTransitionIn: function () - { - return (this.settings.isTransition); - }, - - /** - * Is this Scene visible and rendering? - * - * @method Phaser.Scenes.Systems#isVisible - * @since 3.0.0 - * - * @return {boolean} `true` if this Scene is visible, otherwise `false`. - */ - isVisible: function () - { - return this.settings.visible; - }, - - /** - * Sets the visible state of this Scene. - * An invisible Scene will not render, but will still process updates. - * - * @method Phaser.Scenes.Systems#setVisible - * @since 3.0.0 - * - * @param {boolean} value - `true` to render this Scene, otherwise `false`. - * - * @return {Phaser.Scenes.Systems} This Systems object. - */ - setVisible: function (value) - { - this.settings.visible = value; - - return this; - }, - - /** - * Set the active state of this Scene. - * - * An active Scene will run its core update loop. - * - * @method Phaser.Scenes.Systems#setActive - * @since 3.0.0 - * - * @param {boolean} value - If `true` the Scene will be resumed, if previously paused. If `false` it will be paused. - * @param {object} [data] - A data object that will be passed in the 'resume' or 'pause' events. - * - * @return {Phaser.Scenes.Systems} This Systems object. - */ - setActive: function (value, data) - { - if (value) - { - return this.resume(data); - } - else - { - return this.pause(data); - } - }, - - /** - * Start this Scene running and rendering. - * Called automatically by the SceneManager. - * - * @method Phaser.Scenes.Systems#start - * @fires Phaser.Scenes.Events#START - * @fires Phaser.Scenes.Events#READY - * @since 3.0.0 - * - * @param {object} data - Optional data object that may have been passed to this Scene from another. - */ - start: function (data) - { - if (data) - { - this.settings.data = data; - } - - this.settings.status = CONST.START; - - this.settings.active = true; - this.settings.visible = true; - - // For plugins to listen out for - this.events.emit(Events.START, this); - - // For user-land code to listen out for - this.events.emit(Events.READY, this, data); - }, - - /** - * Shutdown this Scene and send a shutdown event to all of its systems. - * A Scene that has been shutdown will not run its update loop or render, but it does - * not destroy any of its plugins or references. It is put into hibernation for later use. - * If you don't ever plan to use this Scene again, then it should be destroyed instead - * to free-up resources. - * - * @method Phaser.Scenes.Systems#shutdown - * @fires Phaser.Scenes.Events#SHUTDOWN - * @since 3.0.0 - * - * @param {object} [data] - A data object that will be passed in the 'shutdown' event. - */ - shutdown: function (data) - { - this.events.off(Events.TRANSITION_INIT); - this.events.off(Events.TRANSITION_START); - this.events.off(Events.TRANSITION_COMPLETE); - this.events.off(Events.TRANSITION_OUT); - - this.settings.status = CONST.SHUTDOWN; - - this.settings.active = false; - this.settings.visible = false; - - this.events.emit(Events.SHUTDOWN, this, data); - }, - - /** - * Destroy this Scene and send a destroy event all of its systems. - * A destroyed Scene cannot be restarted. - * You should not call this directly, instead use `SceneManager.remove`. - * - * @method Phaser.Scenes.Systems#destroy - * @private - * @fires Phaser.Scenes.Events#DESTROY - * @since 3.0.0 - */ - destroy: function () - { - this.settings.status = CONST.DESTROYED; - - this.settings.active = false; - this.settings.visible = false; - - this.events.emit(Events.DESTROY, this); - - this.events.removeAllListeners(); - - var props = [ 'scene', 'game', 'anims', 'cache', 'plugins', 'registry', 'sound', 'textures', 'add', 'camera', 'displayList', 'events', 'make', 'scenePlugin', 'updateList' ]; - - for (var i = 0; i < props.length; i++) - { - this[props[i]] = null; - } - } - -}); - -module.exports = Systems; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var CONST = require('./const'); +var DefaultPlugins = require('../plugins/DefaultPlugins'); +var Events = require('./events'); +var GetPhysicsPlugins = require('./GetPhysicsPlugins'); +var GetScenePlugins = require('./GetScenePlugins'); +var NOOP = require('../utils/NOOP'); +var Settings = require('./Settings'); + +/** + * @classdesc + * The Scene Systems class. + * + * This class is available from within a Scene under the property `sys`. + * It is responsible for managing all of the plugins a Scene has running, including the display list, and + * handling the update step and renderer. It also contains references to global systems belonging to Game. + * + * @class Systems + * @memberof Phaser.Scenes + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene that owns this Systems instance. + * @param {(string|Phaser.Types.Scenes.SettingsConfig)} config - Scene specific configuration settings. + */ +var Systems = new Class({ + + initialize: + + function Systems (scene, config) + { + /** + * A reference to the Scene that these Systems belong to. + * + * @name Phaser.Scenes.Systems#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * A reference to the Phaser Game instance. + * + * @name Phaser.Scenes.Systems#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game; + + /** + * A reference to either the Canvas or WebGL Renderer that this Game is using. + * + * @name Phaser.Scenes.Systems#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.17.0 + */ + this.renderer; + + if (typeof PLUGIN_FBINSTANT) + { + /** + * The Facebook Instant Games Plugin. + * + * @name Phaser.Scenes.Systems#facebook + * @type {Phaser.FacebookInstantGamesPlugin} + * @since 3.12.0 + */ + this.facebook; + } + + /** + * The Scene Configuration object, as passed in when creating the Scene. + * + * @name Phaser.Scenes.Systems#config + * @type {(string|Phaser.Types.Scenes.SettingsConfig)} + * @since 3.0.0 + */ + this.config = config; + + /** + * 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 + */ + this.settings = Settings.create(config); + + /** + * A handy reference to the Scene canvas / context. + * + * @name Phaser.Scenes.Systems#canvas + * @type {HTMLCanvasElement} + * @since 3.0.0 + */ + this.canvas; + + /** + * A reference to the Canvas Rendering Context being used by the renderer. + * + * @name Phaser.Scenes.Systems#context + * @type {CanvasRenderingContext2D} + * @since 3.0.0 + */ + this.context; + + // Global Systems - these are single-instance global managers that belong to Game + + /** + * A reference to the global Animations Manager. + * + * In the default set-up you can access this from within a Scene via the `this.anims` property. + * + * @name Phaser.Scenes.Systems#anims + * @type {Phaser.Animations.AnimationManager} + * @since 3.0.0 + */ + this.anims; + + /** + * A reference to the global Cache. The Cache stores all files bought in to Phaser via + * the Loader, with the exception of images. Images are stored in the Texture Manager. + * + * In the default set-up you can access this from within a Scene via the `this.cache` property. + * + * @name Phaser.Scenes.Systems#cache + * @type {Phaser.Cache.CacheManager} + * @since 3.0.0 + */ + this.cache; + + /** + * A reference to the global Plugins Manager. + * + * In the default set-up you can access this from within a Scene via the `this.plugins` property. + * + * @name Phaser.Scenes.Systems#plugins + * @type {Phaser.Plugins.PluginManager} + * @since 3.0.0 + */ + this.plugins; + + /** + * A reference to the global registry. This is a game-wide instance of the Data Manager, allowing + * you to exchange data between Scenes via a universal and shared point. + * + * In the default set-up you can access this from within a Scene via the `this.registry` property. + * + * @name Phaser.Scenes.Systems#registry + * @type {Phaser.Data.DataManager} + * @since 3.0.0 + */ + this.registry; + + /** + * A reference to the global Scale Manager. + * + * In the default set-up you can access this from within a Scene via the `this.scale` property. + * + * @name Phaser.Scenes.Systems#scale + * @type {Phaser.Scale.ScaleManager} + * @since 3.15.0 + */ + this.scale; + + /** + * A reference to the global Sound Manager. + * + * In the default set-up you can access this from within a Scene via the `this.sound` property. + * + * @name Phaser.Scenes.Systems#sound + * @type {(Phaser.Sound.NoAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager)} + * @since 3.0.0 + */ + this.sound; + + /** + * A reference to the global Texture Manager. + * + * In the default set-up you can access this from within a Scene via the `this.textures` property. + * + * @name Phaser.Scenes.Systems#textures + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.textures; + + // Core Plugins - these are non-optional Scene plugins, needed by lots of the other systems + + /** + * A reference to the Scene's Game Object Factory. + * + * Use this to quickly and easily create new Game Object's. + * + * In the default set-up you can access this from within a Scene via the `this.add` property. + * + * @name Phaser.Scenes.Systems#add + * @type {Phaser.GameObjects.GameObjectFactory} + * @since 3.0.0 + */ + this.add; + + /** + * A reference to the Scene's Camera Manager. + * + * Use this to manipulate and create Cameras for this specific Scene. + * + * In the default set-up you can access this from within a Scene via the `this.cameras` property. + * + * @name Phaser.Scenes.Systems#cameras + * @type {Phaser.Cameras.Scene2D.CameraManager} + * @since 3.0.0 + */ + this.cameras; + + /** + * A reference to the Scene's Display List. + * + * Use this to organize the children contained in the display list. + * + * In the default set-up you can access this from within a Scene via the `this.children` property. + * + * @name Phaser.Scenes.Systems#displayList + * @type {Phaser.GameObjects.DisplayList} + * @since 3.0.0 + */ + this.displayList; + + /** + * A reference to the Scene's Event Manager. + * + * Use this to listen for Scene specific events, such as `pause` and `shutdown`. + * + * In the default set-up you can access this from within a Scene via the `this.events` property. + * + * @name Phaser.Scenes.Systems#events + * @type {Phaser.Events.EventEmitter} + * @since 3.0.0 + */ + this.events; + + /** + * A reference to the Scene's Game Object Creator. + * + * Use this to quickly and easily create new Game Object's. The difference between this and the + * Game Object Factory, is that the Creator just creates and returns Game Object instances, it + * doesn't then add them to the Display List or Update List. + * + * In the default set-up you can access this from within a Scene via the `this.make` property. + * + * @name Phaser.Scenes.Systems#make + * @type {Phaser.GameObjects.GameObjectCreator} + * @since 3.0.0 + */ + this.make; + + /** + * A reference to the Scene Manager Plugin. + * + * Use this to manipulate both this and other Scene's in your game, for example to launch a parallel Scene, + * or pause or resume a Scene, or switch from this Scene to another. + * + * In the default set-up you can access this from within a Scene via the `this.scene` property. + * + * @name Phaser.Scenes.Systems#scenePlugin + * @type {Phaser.Scenes.ScenePlugin} + * @since 3.0.0 + */ + this.scenePlugin; + + /** + * A reference to the Scene's Update List. + * + * Use this to organize the children contained in the update list. + * + * The Update List is responsible for managing children that need their `preUpdate` methods called, + * in order to process so internal components, such as Sprites with Animations. + * + * In the default set-up there is no reference to this from within the Scene itself. + * + * @name Phaser.Scenes.Systems#updateList + * @type {Phaser.GameObjects.UpdateList} + * @since 3.0.0 + */ + this.updateList; + + /** + * The Scene Update function. + * + * This starts out as NOOP during init, preload and create, and at the end of create + * it swaps to be whatever the Scene.update function is. + * + * @name Phaser.Scenes.Systems#sceneUpdate + * @type {function} + * @private + * @since 3.10.0 + */ + this.sceneUpdate = NOOP; + }, + + /** + * This method is called only once by the Scene Manager when the Scene is instantiated. + * It is responsible for setting up all of the Scene plugins and references. + * It should never be called directly. + * + * @method Phaser.Scenes.Systems#init + * @protected + * @fires Phaser.Scenes.Events#BOOT + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser Game instance. + */ + init: function (game) + { + this.settings.status = CONST.INIT; + + // This will get replaced by the SceneManager with the actual update function, if it exists, once create is over. + this.sceneUpdate = NOOP; + + this.game = game; + this.renderer = game.renderer; + + this.canvas = game.canvas; + this.context = game.context; + + var pluginManager = game.plugins; + + this.plugins = pluginManager; + + pluginManager.addToScene(this, DefaultPlugins.Global, [ DefaultPlugins.CoreScene, GetScenePlugins(this), GetPhysicsPlugins(this) ]); + + this.events.emit(Events.BOOT, this); + + this.settings.isBooted = true; + }, + + /** + * Called by a plugin, it tells the System to install the plugin locally. + * + * @method Phaser.Scenes.Systems#install + * @private + * @since 3.0.0 + * + * @param {array} plugin - An array of plugins to install into this Scene. + */ + install: function (plugin) + { + if (!Array.isArray(plugin)) + { + plugin = [ plugin ]; + } + + this.plugins.installLocal(this, plugin); + }, + + /** + * A single game step. Called automatically by the Scene Manager as a result of a Request Animation + * Frame or Set Timeout call to the main Game instance. + * + * @method Phaser.Scenes.Systems#step + * @fires Phaser.Scenes.Events#PRE_UPDATE + * @fires Phaser.Scenes.Events#_UPDATE + * @fires Phaser.Scenes.Events#POST_UPDATE + * @since 3.0.0 + * + * @param {number} time - The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). + * @param {number} delta - The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. + */ + step: function (time, delta) + { + this.events.emit(Events.PRE_UPDATE, time, delta); + + this.events.emit(Events.UPDATE, time, delta); + + this.sceneUpdate.call(this.scene, time, delta); + + this.events.emit(Events.POST_UPDATE, time, delta); + }, + + /** + * Called automatically by the Scene Manager. + * Instructs the Scene to render itself via its Camera Manager to the renderer given. + * + * @method Phaser.Scenes.Systems#render + * @fires Phaser.Scenes.Events#RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer that invoked the render call. + */ + render: function (renderer) + { + var displayList = this.displayList; + + displayList.depthSort(); + + this.cameras.render(renderer, displayList); + + this.events.emit(Events.RENDER, renderer); + }, + + /** + * Force a sort of the display list on the next render. + * + * @method Phaser.Scenes.Systems#queueDepthSort + * @since 3.0.0 + */ + queueDepthSort: function () + { + this.displayList.queueDepthSort(); + }, + + /** + * Immediately sorts the display list if the flag is set. + * + * @method Phaser.Scenes.Systems#depthSort + * @since 3.0.0 + */ + depthSort: function () + { + this.displayList.depthSort(); + }, + + /** + * Pause this Scene. + * A paused Scene still renders, it just doesn't run ANY of its update handlers or systems. + * + * @method Phaser.Scenes.Systems#pause + * @fires Phaser.Scenes.Events#PAUSE + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'pause' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + pause: function (data) + { + if (this.settings.active) + { + this.settings.status = CONST.PAUSED; + + this.settings.active = false; + + this.events.emit(Events.PAUSE, this, data); + } + + return this; + }, + + /** + * Resume this Scene from a paused state. + * + * @method Phaser.Scenes.Systems#resume + * @fires Phaser.Scenes.Events#RESUME + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'resume' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + resume: function (data) + { + if (!this.settings.active) + { + this.settings.status = CONST.RUNNING; + + this.settings.active = true; + + this.events.emit(Events.RESUME, this, data); + } + + return this; + }, + + /** + * Send this Scene to sleep. + * + * A sleeping Scene doesn't run its update step or render anything, but it also isn't shut down + * or has any of its systems or children removed, meaning it can be re-activated at any point and + * will carry on from where it left off. It also keeps everything in memory and events and callbacks + * from other Scenes may still invoke changes within it, so be careful what is left active. + * + * @method Phaser.Scenes.Systems#sleep + * @fires Phaser.Scenes.Events#SLEEP + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'sleep' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + sleep: function (data) + { + this.settings.status = CONST.SLEEPING; + + this.settings.active = false; + this.settings.visible = false; + + this.events.emit(Events.SLEEP, this, data); + + return this; + }, + + /** + * Wake-up this Scene if it was previously asleep. + * + * @method Phaser.Scenes.Systems#wake + * @fires Phaser.Scenes.Events#WAKE + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'wake' event. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + wake: function (data) + { + var settings = this.settings; + + settings.status = CONST.RUNNING; + + settings.active = true; + settings.visible = true; + + this.events.emit(Events.WAKE, this, data); + + if (settings.isTransition) + { + this.events.emit(Events.TRANSITION_WAKE, settings.transitionFrom, settings.transitionDuration); + } + + return this; + }, + + /** + * Returns any data that was sent to this Scene by another Scene. + * + * The data is also passed to `Scene.init` and in various Scene events, but + * you can access it at any point via this method. + * + * @method Phaser.Scenes.Systems#getData + * @since 3.22.0 + * + * @return {any} + */ + getData: function () + { + return this.settings.data; + }, + + /** + * Is this Scene sleeping? + * + * @method Phaser.Scenes.Systems#isSleeping + * @since 3.0.0 + * + * @return {boolean} `true` if this Scene is asleep, otherwise `false`. + */ + isSleeping: function () + { + return (this.settings.status === CONST.SLEEPING); + }, + + /** + * Is this Scene running? + * + * @method Phaser.Scenes.Systems#isActive + * @since 3.0.0 + * + * @return {boolean} `true` if this Scene is running, otherwise `false`. + */ + isActive: function () + { + return (this.settings.status === CONST.RUNNING); + }, + + /** + * Is this Scene paused? + * + * @method Phaser.Scenes.Systems#isPaused + * @since 3.13.0 + * + * @return {boolean} `true` if this Scene is paused, otherwise `false`. + */ + isPaused: function () + { + return (this.settings.status === CONST.PAUSED); + }, + + /** + * Is this Scene currently transitioning out to, or in from another Scene? + * + * @method Phaser.Scenes.Systems#isTransitioning + * @since 3.5.0 + * + * @return {boolean} `true` if this Scene is currently transitioning, otherwise `false`. + */ + isTransitioning: function () + { + return (this.settings.isTransition || this.scenePlugin._target !== null); + }, + + /** + * Is this Scene currently transitioning out from itself to another Scene? + * + * @method Phaser.Scenes.Systems#isTransitionOut + * @since 3.5.0 + * + * @return {boolean} `true` if this Scene is in transition to another Scene, otherwise `false`. + */ + isTransitionOut: function () + { + return (this.scenePlugin._target !== null && this.scenePlugin._duration > 0); + }, + + /** + * Is this Scene currently transitioning in from another Scene? + * + * @method Phaser.Scenes.Systems#isTransitionIn + * @since 3.5.0 + * + * @return {boolean} `true` if this Scene is transitioning in from another Scene, otherwise `false`. + */ + isTransitionIn: function () + { + return (this.settings.isTransition); + }, + + /** + * Is this Scene visible and rendering? + * + * @method Phaser.Scenes.Systems#isVisible + * @since 3.0.0 + * + * @return {boolean} `true` if this Scene is visible, otherwise `false`. + */ + isVisible: function () + { + return this.settings.visible; + }, + + /** + * Sets the visible state of this Scene. + * An invisible Scene will not render, but will still process updates. + * + * @method Phaser.Scenes.Systems#setVisible + * @since 3.0.0 + * + * @param {boolean} value - `true` to render this Scene, otherwise `false`. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + setVisible: function (value) + { + this.settings.visible = value; + + return this; + }, + + /** + * Set the active state of this Scene. + * + * An active Scene will run its core update loop. + * + * @method Phaser.Scenes.Systems#setActive + * @since 3.0.0 + * + * @param {boolean} value - If `true` the Scene will be resumed, if previously paused. If `false` it will be paused. + * @param {object} [data] - A data object that will be passed in the 'resume' or 'pause' events. + * + * @return {Phaser.Scenes.Systems} This Systems object. + */ + setActive: function (value, data) + { + if (value) + { + return this.resume(data); + } + else + { + return this.pause(data); + } + }, + + /** + * Start this Scene running and rendering. + * Called automatically by the SceneManager. + * + * @method Phaser.Scenes.Systems#start + * @fires Phaser.Scenes.Events#START + * @fires Phaser.Scenes.Events#READY + * @since 3.0.0 + * + * @param {object} data - Optional data object that may have been passed to this Scene from another. + */ + start: function (data) + { + if (data) + { + this.settings.data = data; + } + + this.settings.status = CONST.START; + + this.settings.active = true; + this.settings.visible = true; + + // For plugins to listen out for + this.events.emit(Events.START, this); + + // For user-land code to listen out for + this.events.emit(Events.READY, this, data); + }, + + /** + * Shutdown this Scene and send a shutdown event to all of its systems. + * A Scene that has been shutdown will not run its update loop or render, but it does + * not destroy any of its plugins or references. It is put into hibernation for later use. + * If you don't ever plan to use this Scene again, then it should be destroyed instead + * to free-up resources. + * + * @method Phaser.Scenes.Systems#shutdown + * @fires Phaser.Scenes.Events#SHUTDOWN + * @since 3.0.0 + * + * @param {object} [data] - A data object that will be passed in the 'shutdown' event. + */ + shutdown: function (data) + { + this.events.off(Events.TRANSITION_INIT); + this.events.off(Events.TRANSITION_START); + this.events.off(Events.TRANSITION_COMPLETE); + this.events.off(Events.TRANSITION_OUT); + + this.settings.status = CONST.SHUTDOWN; + + this.settings.active = false; + this.settings.visible = false; + + this.events.emit(Events.SHUTDOWN, this, data); + }, + + /** + * Destroy this Scene and send a destroy event all of its systems. + * A destroyed Scene cannot be restarted. + * You should not call this directly, instead use `SceneManager.remove`. + * + * @method Phaser.Scenes.Systems#destroy + * @private + * @fires Phaser.Scenes.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + this.settings.status = CONST.DESTROYED; + + this.settings.active = false; + this.settings.visible = false; + + this.events.emit(Events.DESTROY, this); + + this.events.removeAllListeners(); + + var props = [ 'scene', 'game', 'anims', 'cache', 'plugins', 'registry', 'sound', 'textures', 'add', 'camera', 'displayList', 'events', 'make', 'scenePlugin', 'updateList' ]; + + for (var i = 0; i < props.length; i++) + { + this[props[i]] = null; + } + } + +}); + +module.exports = Systems; diff --git a/src/scene/const.js b/src/scene/const.js index d461d476e..47fc4b66c 100644 --- a/src/scene/const.js +++ b/src/scene/const.js @@ -1,117 +1,117 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Scene consts. - * - * @ignore - */ - -var CONST = { - - /** - * Scene state. - * - * @name Phaser.Scenes.PENDING - * @readonly - * @type {integer} - * @since 3.0.0 - */ - PENDING: 0, - - /** - * Scene state. - * - * @name Phaser.Scenes.INIT - * @readonly - * @type {integer} - * @since 3.0.0 - */ - INIT: 1, - - /** - * Scene state. - * - * @name Phaser.Scenes.START - * @readonly - * @type {integer} - * @since 3.0.0 - */ - START: 2, - - /** - * Scene state. - * - * @name Phaser.Scenes.LOADING - * @readonly - * @type {integer} - * @since 3.0.0 - */ - LOADING: 3, - - /** - * Scene state. - * - * @name Phaser.Scenes.CREATING - * @readonly - * @type {integer} - * @since 3.0.0 - */ - CREATING: 4, - - /** - * Scene state. - * - * @name Phaser.Scenes.RUNNING - * @readonly - * @type {integer} - * @since 3.0.0 - */ - RUNNING: 5, - - /** - * Scene state. - * - * @name Phaser.Scenes.PAUSED - * @readonly - * @type {integer} - * @since 3.0.0 - */ - PAUSED: 6, - - /** - * Scene state. - * - * @name Phaser.Scenes.SLEEPING - * @readonly - * @type {integer} - * @since 3.0.0 - */ - SLEEPING: 7, - - /** - * Scene state. - * - * @name Phaser.Scenes.SHUTDOWN - * @readonly - * @type {integer} - * @since 3.0.0 - */ - SHUTDOWN: 8, - - /** - * Scene state. - * - * @name Phaser.Scenes.DESTROYED - * @readonly - * @type {integer} - * @since 3.0.0 - */ - DESTROYED: 9 - -}; - -module.exports = CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Scene consts. + * + * @ignore + */ + +var CONST = { + + /** + * Scene state. + * + * @name Phaser.Scenes.PENDING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + PENDING: 0, + + /** + * Scene state. + * + * @name Phaser.Scenes.INIT + * @readonly + * @type {integer} + * @since 3.0.0 + */ + INIT: 1, + + /** + * Scene state. + * + * @name Phaser.Scenes.START + * @readonly + * @type {integer} + * @since 3.0.0 + */ + START: 2, + + /** + * Scene state. + * + * @name Phaser.Scenes.LOADING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + LOADING: 3, + + /** + * Scene state. + * + * @name Phaser.Scenes.CREATING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + CREATING: 4, + + /** + * Scene state. + * + * @name Phaser.Scenes.RUNNING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + RUNNING: 5, + + /** + * Scene state. + * + * @name Phaser.Scenes.PAUSED + * @readonly + * @type {integer} + * @since 3.0.0 + */ + PAUSED: 6, + + /** + * Scene state. + * + * @name Phaser.Scenes.SLEEPING + * @readonly + * @type {integer} + * @since 3.0.0 + */ + SLEEPING: 7, + + /** + * Scene state. + * + * @name Phaser.Scenes.SHUTDOWN + * @readonly + * @type {integer} + * @since 3.0.0 + */ + SHUTDOWN: 8, + + /** + * Scene state. + * + * @name Phaser.Scenes.DESTROYED + * @readonly + * @type {integer} + * @since 3.0.0 + */ + DESTROYED: 9 + +}; + +module.exports = CONST; diff --git a/src/scene/events/BOOT_EVENT.js b/src/scene/events/BOOT_EVENT.js index c016257ad..1c23ef0f6 100644 --- a/src/scene/events/BOOT_EVENT.js +++ b/src/scene/events/BOOT_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Boot Event. - * - * This event is dispatched by a Scene during the Scene Systems boot process. Primarily used by Scene Plugins. - * - * Listen to it from a Scene using `this.scene.events.on('boot', listener)`. - * - * @event Phaser.Scenes.Events#BOOT - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - */ -module.exports = 'boot'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Boot Event. + * + * This event is dispatched by a Scene during the Scene Systems boot process. Primarily used by Scene Plugins. + * + * Listen to it from a Scene using `this.scene.events.on('boot', listener)`. + * + * @event Phaser.Scenes.Events#BOOT + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + */ +module.exports = 'boot'; diff --git a/src/scene/events/CREATE_EVENT.js b/src/scene/events/CREATE_EVENT.js index eaf00f246..d70118afc 100644 --- a/src/scene/events/CREATE_EVENT.js +++ b/src/scene/events/CREATE_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Create Event. - * - * This event is dispatched by a Scene after it has been created by the Scene Manager. - * - * If a Scene has a `create` method then this event is emitted _after_ that has run. - * - * If there is a transition, this event will be fired after the `TRANSITION_START` event. - * - * Listen to it from a Scene using `this.scene.events.on('create', listener)`. - * - * @event Phaser.Scenes.Events#CREATE - * @since 3.17.0 - * - * @param {Phaser.Scene} scene - A reference to the Scene that emitted this event. - */ -module.exports = 'create'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Create Event. + * + * This event is dispatched by a Scene after it has been created by the Scene Manager. + * + * If a Scene has a `create` method then this event is emitted _after_ that has run. + * + * If there is a transition, this event will be fired after the `TRANSITION_START` event. + * + * Listen to it from a Scene using `this.scene.events.on('create', listener)`. + * + * @event Phaser.Scenes.Events#CREATE + * @since 3.17.0 + * + * @param {Phaser.Scene} scene - A reference to the Scene that emitted this event. + */ +module.exports = 'create'; diff --git a/src/scene/events/DESTROY_EVENT.js b/src/scene/events/DESTROY_EVENT.js index 86cb018b4..bc67b1bdc 100644 --- a/src/scene/events/DESTROY_EVENT.js +++ b/src/scene/events/DESTROY_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Destroy Event. - * - * This event is dispatched by a Scene during the Scene Systems destroy process. - * - * Listen to it from a Scene using `this.scene.events.on('destroy', listener)`. - * - * You should destroy any resources that may be in use by your Scene in this event handler. - * - * @event Phaser.Scenes.Events#DESTROY - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - */ -module.exports = 'destroy'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Destroy Event. + * + * This event is dispatched by a Scene during the Scene Systems destroy process. + * + * Listen to it from a Scene using `this.scene.events.on('destroy', listener)`. + * + * You should destroy any resources that may be in use by your Scene in this event handler. + * + * @event Phaser.Scenes.Events#DESTROY + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + */ +module.exports = 'destroy'; diff --git a/src/scene/events/PAUSE_EVENT.js b/src/scene/events/PAUSE_EVENT.js index 6f9926964..22bd4725c 100644 --- a/src/scene/events/PAUSE_EVENT.js +++ b/src/scene/events/PAUSE_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Pause Event. - * - * This event is dispatched by a Scene when it is paused, either directly via the `pause` method, or as an - * action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('pause', listener)`. - * - * @event Phaser.Scenes.Events#PAUSE - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @param {any} [data] - An optional data object that was passed to this Scene when it was paused. - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Pause Event. + * + * This event is dispatched by a Scene when it is paused, either directly via the `pause` method, or as an + * action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('pause', listener)`. + * + * @event Phaser.Scenes.Events#PAUSE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was paused. + */ +module.exports = 'pause'; diff --git a/src/scene/events/POST_UPDATE_EVENT.js b/src/scene/events/POST_UPDATE_EVENT.js index 967f7ea02..cf1234538 100644 --- a/src/scene/events/POST_UPDATE_EVENT.js +++ b/src/scene/events/POST_UPDATE_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('postupdate', listener)`. - * - * A Scene will only run its step if it is active. - * - * @event Phaser.Scenes.Events#POST_UPDATE - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @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. - */ -module.exports = 'postupdate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('postupdate', listener)`. + * + * A Scene will only run its step if it is active. + * + * @event Phaser.Scenes.Events#POST_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @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. + */ +module.exports = 'postupdate'; diff --git a/src/scene/events/PRE_UPDATE_EVENT.js b/src/scene/events/PRE_UPDATE_EVENT.js index f0b8f02bc..23811fbf1 100644 --- a/src/scene/events/PRE_UPDATE_EVENT.js +++ b/src/scene/events/PRE_UPDATE_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('preupdate', listener)`. - * - * A Scene will only run its step if it is active. - * - * @event Phaser.Scenes.Events#PRE_UPDATE - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @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. - */ -module.exports = 'preupdate'; +/** + * @author Richard Davey + * @copyright 2020 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('preupdate', listener)`. + * + * A Scene will only run its step if it is active. + * + * @event Phaser.Scenes.Events#PRE_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @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. + */ +module.exports = 'preupdate'; diff --git a/src/scene/events/READY_EVENT.js b/src/scene/events/READY_EVENT.js index ebfb11bea..60b3e9587 100644 --- a/src/scene/events/READY_EVENT.js +++ b/src/scene/events/READY_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Ready Event. - * - * This event is dispatched by a Scene during the Scene Systems start process. - * By this point in the process the Scene is now fully active and rendering. - * This event is meant for your game code to use, as all plugins have responded to the earlier 'start' event. - * - * Listen to it from a Scene using `this.scene.events.on('ready', listener)`. - * - * @event Phaser.Scenes.Events#READY - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @param {any} [data] - An optional data object that was passed to this Scene when it was started. - */ -module.exports = 'ready'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Ready Event. + * + * This event is dispatched by a Scene during the Scene Systems start process. + * By this point in the process the Scene is now fully active and rendering. + * This event is meant for your game code to use, as all plugins have responded to the earlier 'start' event. + * + * Listen to it from a Scene using `this.scene.events.on('ready', listener)`. + * + * @event Phaser.Scenes.Events#READY + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was started. + */ +module.exports = 'ready'; diff --git a/src/scene/events/RENDER_EVENT.js b/src/scene/events/RENDER_EVENT.js index 3120fb598..b2f5ef264 100644 --- a/src/scene/events/RENDER_EVENT.js +++ b/src/scene/events/RENDER_EVENT.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Render 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('render', listener)`. - * - * A Scene will only render if it is visible and active. - * By the time this event is dispatched, the Scene will have already been rendered. - * - * @event Phaser.Scenes.Events#RENDER - * @since 3.0.0 - * - * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer that rendered the Scene. - */ -module.exports = 'render'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Render 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('render', listener)`. + * + * A Scene will only render if it is visible and active. + * By the time this event is dispatched, the Scene will have already been rendered. + * + * @event Phaser.Scenes.Events#RENDER + * @since 3.0.0 + * + * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer that rendered the Scene. + */ +module.exports = 'render'; diff --git a/src/scene/events/RESUME_EVENT.js b/src/scene/events/RESUME_EVENT.js index a3f3a0467..7516cda92 100644 --- a/src/scene/events/RESUME_EVENT.js +++ b/src/scene/events/RESUME_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Resume Event. - * - * This event is dispatched by a Scene when it is resumed from a paused state, either directly via the `resume` method, - * or as an action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('resume', listener)`. - * - * @event Phaser.Scenes.Events#RESUME - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @param {any} [data] - An optional data object that was passed to this Scene when it was resumed. - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Resume Event. + * + * This event is dispatched by a Scene when it is resumed from a paused state, either directly via the `resume` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('resume', listener)`. + * + * @event Phaser.Scenes.Events#RESUME + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was resumed. + */ +module.exports = 'resume'; diff --git a/src/scene/events/SHUTDOWN_EVENT.js b/src/scene/events/SHUTDOWN_EVENT.js index c315330f8..f2058856a 100644 --- a/src/scene/events/SHUTDOWN_EVENT.js +++ b/src/scene/events/SHUTDOWN_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Shutdown Event. - * - * This event is dispatched by a Scene during the Scene Systems shutdown process. - * - * Listen to it from a Scene using `this.scene.events.on('shutdown', listener)`. - * - * You should free-up any resources that may be in use by your Scene in this event handler, on the understanding - * that the Scene may, at any time, become active again. A shutdown Scene is not 'destroyed', it's simply not - * currently active. Use the [DESTROY]{@linkcode Phaser.Scenes.Events#event:DESTROY} event to completely clear resources. - * - * @event Phaser.Scenes.Events#SHUTDOWN - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @param {any} [data] - An optional data object that was passed to this Scene when it was shutdown. - */ -module.exports = 'shutdown'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Shutdown Event. + * + * This event is dispatched by a Scene during the Scene Systems shutdown process. + * + * Listen to it from a Scene using `this.scene.events.on('shutdown', listener)`. + * + * You should free-up any resources that may be in use by your Scene in this event handler, on the understanding + * that the Scene may, at any time, become active again. A shutdown Scene is not 'destroyed', it's simply not + * currently active. Use the [DESTROY]{@linkcode Phaser.Scenes.Events#event:DESTROY} event to completely clear resources. + * + * @event Phaser.Scenes.Events#SHUTDOWN + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was shutdown. + */ +module.exports = 'shutdown'; diff --git a/src/scene/events/SLEEP_EVENT.js b/src/scene/events/SLEEP_EVENT.js index f2dc6735e..9ada53d9e 100644 --- a/src/scene/events/SLEEP_EVENT.js +++ b/src/scene/events/SLEEP_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Sleep Event. - * - * This event is dispatched by a Scene when it is sent to sleep, either directly via the `sleep` method, - * or as an action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('sleep', listener)`. - * - * @event Phaser.Scenes.Events#SLEEP - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @param {any} [data] - An optional data object that was passed to this Scene when it was sent to sleep. - */ -module.exports = 'sleep'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Sleep Event. + * + * This event is dispatched by a Scene when it is sent to sleep, either directly via the `sleep` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('sleep', listener)`. + * + * @event Phaser.Scenes.Events#SLEEP + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was sent to sleep. + */ +module.exports = 'sleep'; diff --git a/src/scene/events/START_EVENT.js b/src/scene/events/START_EVENT.js index 9fed5e886..cd24744bc 100644 --- a/src/scene/events/START_EVENT.js +++ b/src/scene/events/START_EVENT.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Start Event. - * - * This event is dispatched by a Scene during the Scene Systems start process. Primarily used by Scene Plugins. - * - * Listen to it from a Scene using `this.scene.events.on('start', listener)`. - * - * @event Phaser.Scenes.Events#START - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - */ -module.exports = 'start'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Start Event. + * + * This event is dispatched by a Scene during the Scene Systems start process. Primarily used by Scene Plugins. + * + * Listen to it from a Scene using `this.scene.events.on('start', listener)`. + * + * @event Phaser.Scenes.Events#START + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + */ +module.exports = 'start'; diff --git a/src/scene/events/TRANSITION_COMPLETE_EVENT.js b/src/scene/events/TRANSITION_COMPLETE_EVENT.js index 8951ad520..d3cbd03bc 100644 --- a/src/scene/events/TRANSITION_COMPLETE_EVENT.js +++ b/src/scene/events/TRANSITION_COMPLETE_EVENT.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Transition Complete Event. - * - * This event is dispatched by the Target Scene of a transition. - * - * It happens when the transition process has completed. This occurs when the duration timer equals or exceeds the duration - * of the transition. - * - * Listen to it from a Scene using `this.scene.events.on('transitioncomplete', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - * - * @event Phaser.Scenes.Events#TRANSITION_COMPLETE - * @since 3.5.0 - * - * @param {Phaser.Scene} scene -The Scene on which the transitioned completed. - */ -module.exports = 'transitioncomplete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Complete Event. + * + * This event is dispatched by the Target Scene of a transition. + * + * It happens when the transition process has completed. This occurs when the duration timer equals or exceeds the duration + * of the transition. + * + * Listen to it from a Scene using `this.scene.events.on('transitioncomplete', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_COMPLETE + * @since 3.5.0 + * + * @param {Phaser.Scene} scene -The Scene on which the transitioned completed. + */ +module.exports = 'transitioncomplete'; diff --git a/src/scene/events/TRANSITION_INIT_EVENT.js b/src/scene/events/TRANSITION_INIT_EVENT.js index f77f301b9..ccdba8e07 100644 --- a/src/scene/events/TRANSITION_INIT_EVENT.js +++ b/src/scene/events/TRANSITION_INIT_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Transition Init Event. - * - * This event is dispatched by the Target Scene of a transition. - * - * It happens immediately after the `Scene.init` method is called. If the Scene does not have an `init` method, - * this event is not dispatched. - * - * Listen to it from a Scene using `this.scene.events.on('transitioninit', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - * - * @event Phaser.Scenes.Events#TRANSITION_INIT - * @since 3.5.0 - * - * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. - * @param {number} duration - The duration of the transition in ms. - */ -module.exports = 'transitioninit'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Init Event. + * + * This event is dispatched by the Target Scene of a transition. + * + * It happens immediately after the `Scene.init` method is called. If the Scene does not have an `init` method, + * this event is not dispatched. + * + * Listen to it from a Scene using `this.scene.events.on('transitioninit', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_INIT + * @since 3.5.0 + * + * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitioninit'; diff --git a/src/scene/events/TRANSITION_OUT_EVENT.js b/src/scene/events/TRANSITION_OUT_EVENT.js index 74084cd5b..b7caa32dc 100644 --- a/src/scene/events/TRANSITION_OUT_EVENT.js +++ b/src/scene/events/TRANSITION_OUT_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Transition Out Event. - * - * This event is dispatched by a Scene when it initiates a transition to another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('transitionout', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - * - * @event Phaser.Scenes.Events#TRANSITION_OUT - * @since 3.5.0 - * - * @param {Phaser.Scene} target - A reference to the Scene that is being transitioned to. - * @param {number} duration - The duration of the transition in ms. - */ -module.exports = 'transitionout'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Out Event. + * + * This event is dispatched by a Scene when it initiates a transition to another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('transitionout', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_OUT + * @since 3.5.0 + * + * @param {Phaser.Scene} target - A reference to the Scene that is being transitioned to. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitionout'; diff --git a/src/scene/events/TRANSITION_START_EVENT.js b/src/scene/events/TRANSITION_START_EVENT.js index cd6c15e98..3b6ff82b9 100644 --- a/src/scene/events/TRANSITION_START_EVENT.js +++ b/src/scene/events/TRANSITION_START_EVENT.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Transition Start Event. - * - * This event is dispatched by the Target Scene of a transition, only if that Scene was not asleep. - * - * It happens immediately after the `Scene.create` method is called. If the Scene does not have a `create` method, - * this event is dispatched anyway. - * - * If the Target Scene was sleeping then the [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} event is - * dispatched instead of this event. - * - * Listen to it from a Scene using `this.scene.events.on('transitionstart', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - * - * @event Phaser.Scenes.Events#TRANSITION_START - * @since 3.5.0 - * - * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. - * @param {number} duration - The duration of the transition in ms. - */ -module.exports = 'transitionstart'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Start Event. + * + * This event is dispatched by the Target Scene of a transition, only if that Scene was not asleep. + * + * It happens immediately after the `Scene.create` method is called. If the Scene does not have a `create` method, + * this event is dispatched anyway. + * + * If the Target Scene was sleeping then the [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} event is + * dispatched instead of this event. + * + * Listen to it from a Scene using `this.scene.events.on('transitionstart', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_START + * @since 3.5.0 + * + * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitionstart'; diff --git a/src/scene/events/TRANSITION_WAKE_EVENT.js b/src/scene/events/TRANSITION_WAKE_EVENT.js index 71637628b..84b1f427c 100644 --- a/src/scene/events/TRANSITION_WAKE_EVENT.js +++ b/src/scene/events/TRANSITION_WAKE_EVENT.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Transition Wake Event. - * - * This event is dispatched by the Target Scene of a transition, only if that Scene was asleep before - * the transition began. If the Scene was not asleep the [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} event is dispatched instead. - * - * Listen to it from a Scene using `this.scene.events.on('transitionwake', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - * - * @event Phaser.Scenes.Events#TRANSITION_WAKE - * @since 3.5.0 - * - * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. - * @param {number} duration - The duration of the transition in ms. - */ -module.exports = 'transitionwake'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Transition Wake Event. + * + * This event is dispatched by the Target Scene of a transition, only if that Scene was asleep before + * the transition began. If the Scene was not asleep the [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} event is dispatched instead. + * + * Listen to it from a Scene using `this.scene.events.on('transitionwake', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + * + * @event Phaser.Scenes.Events#TRANSITION_WAKE + * @since 3.5.0 + * + * @param {Phaser.Scene} from - A reference to the Scene that is being transitioned from. + * @param {number} duration - The duration of the transition in ms. + */ +module.exports = 'transitionwake'; diff --git a/src/scene/events/UPDATE_EVENT.js b/src/scene/events/UPDATE_EVENT.js index bfaf6d87a..20dd7c274 100644 --- a/src/scene/events/UPDATE_EVENT.js +++ b/src/scene/events/UPDATE_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 - * 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE} - * 5. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('update', listener)`. - * - * A Scene will only run its step if it is active. - * - * @event Phaser.Scenes.Events#UPDATE - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @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. - */ -module.exports = 'update'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 + * 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE} + * 5. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('update', listener)`. + * + * A Scene will only run its step if it is active. + * + * @event Phaser.Scenes.Events#UPDATE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @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. + */ +module.exports = 'update'; diff --git a/src/scene/events/WAKE_EVENT.js b/src/scene/events/WAKE_EVENT.js index 258361285..c92ee9cd6 100644 --- a/src/scene/events/WAKE_EVENT.js +++ b/src/scene/events/WAKE_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Scene Systems Wake Event. - * - * This event is dispatched by a Scene when it is woken from sleep, either directly via the `wake` method, - * or as an action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('wake', listener)`. - * - * @event Phaser.Scenes.Events#WAKE - * @since 3.0.0 - * - * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. - * @param {any} [data] - An optional data object that was passed to this Scene when it was woken up. - */ -module.exports = 'wake'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Scene Systems Wake Event. + * + * This event is dispatched by a Scene when it is woken from sleep, either directly via the `wake` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('wake', listener)`. + * + * @event Phaser.Scenes.Events#WAKE + * @since 3.0.0 + * + * @param {Phaser.Scenes.Systems} sys - A reference to the Scene Systems class of the Scene that emitted this event. + * @param {any} [data] - An optional data object that was passed to this Scene when it was woken up. + */ +module.exports = 'wake'; diff --git a/src/scene/events/index.js b/src/scene/events/index.js index 78d88e885..55cf96ddb 100644 --- a/src/scene/events/index.js +++ b/src/scene/events/index.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Scenes.Events - */ - -module.exports = { - - BOOT: require('./BOOT_EVENT'), - CREATE: require('./CREATE_EVENT'), - DESTROY: require('./DESTROY_EVENT'), - PAUSE: require('./PAUSE_EVENT'), - POST_UPDATE: require('./POST_UPDATE_EVENT'), - PRE_UPDATE: require('./PRE_UPDATE_EVENT'), - READY: require('./READY_EVENT'), - RENDER: require('./RENDER_EVENT'), - RESUME: require('./RESUME_EVENT'), - SHUTDOWN: require('./SHUTDOWN_EVENT'), - SLEEP: require('./SLEEP_EVENT'), - START: require('./START_EVENT'), - TRANSITION_COMPLETE: require('./TRANSITION_COMPLETE_EVENT'), - TRANSITION_INIT: require('./TRANSITION_INIT_EVENT'), - TRANSITION_OUT: require('./TRANSITION_OUT_EVENT'), - TRANSITION_START: require('./TRANSITION_START_EVENT'), - TRANSITION_WAKE: require('./TRANSITION_WAKE_EVENT'), - UPDATE: require('./UPDATE_EVENT'), - WAKE: require('./WAKE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Scenes.Events + */ + +module.exports = { + + BOOT: require('./BOOT_EVENT'), + CREATE: require('./CREATE_EVENT'), + DESTROY: require('./DESTROY_EVENT'), + PAUSE: require('./PAUSE_EVENT'), + POST_UPDATE: require('./POST_UPDATE_EVENT'), + PRE_UPDATE: require('./PRE_UPDATE_EVENT'), + READY: require('./READY_EVENT'), + RENDER: require('./RENDER_EVENT'), + RESUME: require('./RESUME_EVENT'), + SHUTDOWN: require('./SHUTDOWN_EVENT'), + SLEEP: require('./SLEEP_EVENT'), + START: require('./START_EVENT'), + TRANSITION_COMPLETE: require('./TRANSITION_COMPLETE_EVENT'), + TRANSITION_INIT: require('./TRANSITION_INIT_EVENT'), + TRANSITION_OUT: require('./TRANSITION_OUT_EVENT'), + TRANSITION_START: require('./TRANSITION_START_EVENT'), + TRANSITION_WAKE: require('./TRANSITION_WAKE_EVENT'), + UPDATE: require('./UPDATE_EVENT'), + WAKE: require('./WAKE_EVENT') + +}; diff --git a/src/scene/index.js b/src/scene/index.js index 3367e2dab..14e20c1c0 100644 --- a/src/scene/index.js +++ b/src/scene/index.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./const'); -var Extend = require('../utils/object/Extend'); - -/** - * @namespace Phaser.Scenes - */ - -var Scene = { - - Events: require('./events'), - SceneManager: require('./SceneManager'), - ScenePlugin: require('./ScenePlugin'), - Settings: require('./Settings'), - Systems: require('./Systems') - -}; - -// Merge in the consts -Scene = Extend(false, Scene, CONST); - -module.exports = Scene; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./const'); +var Extend = require('../utils/object/Extend'); + +/** + * @namespace Phaser.Scenes + */ + +var Scene = { + + Events: require('./events'), + SceneManager: require('./SceneManager'), + ScenePlugin: require('./ScenePlugin'), + Settings: require('./Settings'), + Systems: require('./Systems') + +}; + +// Merge in the consts +Scene = Extend(false, Scene, CONST); + +module.exports = Scene; diff --git a/src/scene/typedefs/index.js b/src/scene/typedefs/index.js index 52fa2e234..698a84875 100644 --- a/src/scene/typedefs/index.js +++ b/src/scene/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Scenes - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Scenes + */ diff --git a/src/sound/BaseSound.js b/src/sound/BaseSound.js index e2bd3cedb..cb01bed2a 100644 --- a/src/sound/BaseSound.js +++ b/src/sound/BaseSound.js @@ -1,494 +1,494 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var Extend = require('../utils/object/Extend'); -var NOOP = require('../utils/NOOP'); - -/** - * @classdesc - * Class containing all the shared state and behavior of a sound object, independent of the implementation. - * - * @class BaseSound - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} 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. - */ -var BaseSound = new Class({ - - Extends: EventEmitter, - - initialize: - - function BaseSound (manager, key, config) - { - EventEmitter.call(this); - - /** - * Local reference to the sound manager. - * - * @name Phaser.Sound.BaseSound#manager - * @type {Phaser.Sound.BaseSoundManager} - * @private - * @since 3.0.0 - */ - this.manager = manager; - - /** - * Asset key for the sound. - * - * @name Phaser.Sound.BaseSound#key - * @type {string} - * @readonly - * @since 3.0.0 - */ - this.key = key; - - /** - * Flag indicating if sound is currently playing. - * - * @name Phaser.Sound.BaseSound#isPlaying - * @type {boolean} - * @default false - * @readonly - * @since 3.0.0 - */ - this.isPlaying = false; - - /** - * Flag indicating if sound is currently paused. - * - * @name Phaser.Sound.BaseSound#isPaused - * @type {boolean} - * @default false - * @readonly - * @since 3.0.0 - */ - this.isPaused = false; - - /** - * A property that holds the value of sound's actual playback rate, - * after its rate and detune values has been combined with global - * rate and detune values. - * - * @name Phaser.Sound.BaseSound#totalRate - * @type {number} - * @default 1 - * @readonly - * @since 3.0.0 - */ - this.totalRate = 1; - - /** - * A value representing the duration, in seconds. - * It could be total sound duration or a marker duration. - * - * @name Phaser.Sound.BaseSound#duration - * @type {number} - * @readonly - * @since 3.0.0 - */ - this.duration = this.duration || 0; - - /** - * The total duration of the sound in seconds. - * - * @name Phaser.Sound.BaseSound#totalDuration - * @type {number} - * @readonly - * @since 3.0.0 - */ - this.totalDuration = this.totalDuration || 0; - - /** - * A config object used to store default sound settings' values. - * Default values will be set by properties' setters. - * - * @name Phaser.Sound.BaseSound#config - * @type {Phaser.Types.Sound.SoundConfig} - * @private - * @since 3.0.0 - */ - this.config = { - - mute: false, - volume: 1, - rate: 1, - detune: 0, - seek: 0, - loop: false, - delay: 0 - - }; - - /** - * Reference to the currently used config. - * It could be default config or marker config. - * - * @name Phaser.Sound.BaseSound#currentConfig - * @type {Phaser.Types.Sound.SoundConfig} - * @private - * @since 3.0.0 - */ - this.currentConfig = this.config; - - this.config = Extend(this.config, config); - - /** - * Object containing markers definitions. - * - * @name Phaser.Sound.BaseSound#markers - * @type {Object.} - * @default {} - * @readonly - * @since 3.0.0 - */ - this.markers = {}; - - /** - * Currently playing marker. - * 'null' if whole sound is playing. - * - * @name Phaser.Sound.BaseSound#currentMarker - * @type {Phaser.Types.Sound.SoundMarker} - * @default null - * @readonly - * @since 3.0.0 - */ - this.currentMarker = null; - - /** - * Flag indicating if destroy method was called on this sound. - * - * @name Phaser.Sound.BaseSound#pendingRemove - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this.pendingRemove = false; - }, - - /** - * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object. - * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. - * - * @method Phaser.Sound.BaseSound#addMarker - * @since 3.0.0 - * - * @param {Phaser.Types.Sound.SoundMarker} marker - Marker object. - * - * @return {boolean} Whether the marker was added successfully. - */ - addMarker: function (marker) - { - if (!marker || !marker.name || typeof marker.name !== 'string') - { - return false; - } - - if (this.markers[marker.name]) - { - // eslint-disable-next-line no-console - console.error('addMarker ' + marker.name + ' already exists in Sound'); - - return false; - } - - marker = Extend(true, { - name: '', - start: 0, - duration: this.totalDuration - (marker.start || 0), - config: { - mute: false, - volume: 1, - rate: 1, - detune: 0, - seek: 0, - loop: false, - delay: 0 - } - }, marker); - - this.markers[marker.name] = marker; - - return true; - }, - - /** - * Updates previously added marker. - * - * @method Phaser.Sound.BaseSound#updateMarker - * @since 3.0.0 - * - * @param {Phaser.Types.Sound.SoundMarker} marker - Marker object with updated values. - * - * @return {boolean} Whether the marker was updated successfully. - */ - updateMarker: function (marker) - { - if (!marker || !marker.name || typeof marker.name !== 'string') - { - return false; - } - - if (!this.markers[marker.name]) - { - // eslint-disable-next-line no-console - console.warn('Audio Marker: ' + marker.name + ' missing in Sound: ' + this.key); - - return false; - } - - this.markers[marker.name] = Extend(true, this.markers[marker.name], marker); - - return true; - }, - - /** - * Removes a marker from the sound. - * - * @method Phaser.Sound.BaseSound#removeMarker - * @since 3.0.0 - * - * @param {string} markerName - The name of the marker to remove. - * - * @return {?Phaser.Types.Sound.SoundMarker} Removed marker object or 'null' if there was no marker with provided name. - */ - removeMarker: function (markerName) - { - var marker = this.markers[markerName]; - - if (!marker) - { - return null; - } - - this.markers[markerName] = null; - - return marker; - }, - - /** - * Play this sound, or a marked section of it. - * It always plays the sound from the start. If you want to start playback from a specific time - * you can set 'seek' setting of the config object, provided to this call, to that value. - * - * @method Phaser.Sound.BaseSound#play - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. - * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. - * - * @return {boolean} Whether the sound started playing successfully. - */ - play: function (markerName, config) - { - if (markerName === undefined) { markerName = ''; } - - if (typeof markerName === 'object') - { - config = markerName; - markerName = ''; - } - - if (typeof markerName !== 'string') - { - return false; - } - - if (!markerName) - { - this.currentMarker = null; - this.currentConfig = this.config; - this.duration = this.totalDuration; - } - else - { - if (!this.markers[markerName]) - { - // eslint-disable-next-line no-console - console.warn('Marker: ' + markerName + ' missing in Sound: ' + this.key); - - return false; - } - - this.currentMarker = this.markers[markerName]; - this.currentConfig = this.currentMarker.config; - this.duration = this.currentMarker.duration; - } - - this.resetConfig(); - - this.currentConfig = Extend(this.currentConfig, config); - - this.isPlaying = true; - this.isPaused = false; - - return true; - }, - - /** - * Pauses the sound. - * - * @method Phaser.Sound.BaseSound#pause - * @since 3.0.0 - * - * @return {boolean} Whether the sound was paused successfully. - */ - pause: function () - { - if (this.isPaused || !this.isPlaying) - { - return false; - } - - this.isPlaying = false; - this.isPaused = true; - - return true; - }, - - /** - * Resumes the sound. - * - * @method Phaser.Sound.BaseSound#resume - * @since 3.0.0 - * - * @return {boolean} Whether the sound was resumed successfully. - */ - resume: function () - { - if (!this.isPaused || this.isPlaying) - { - return false; - } - - this.isPlaying = true; - this.isPaused = false; - - return true; - }, - - /** - * Stop playing this sound. - * - * @method Phaser.Sound.BaseSound#stop - * @since 3.0.0 - * - * @return {boolean} Whether the sound was stopped successfully. - */ - stop: function () - { - if (!this.isPaused && !this.isPlaying) - { - return false; - } - - this.isPlaying = false; - this.isPaused = false; - - this.resetConfig(); - - return true; - }, - - /** - * Method used internally for applying config values to some of the sound properties. - * - * @method Phaser.Sound.BaseSound#applyConfig - * @protected - * @since 3.0.0 - */ - applyConfig: function () - { - this.mute = this.currentConfig.mute; - this.volume = this.currentConfig.volume; - this.rate = this.currentConfig.rate; - this.detune = this.currentConfig.detune; - this.loop = this.currentConfig.loop; - }, - - /** - * Method used internally for resetting values of some of the config properties. - * - * @method Phaser.Sound.BaseSound#resetConfig - * @protected - * @since 3.0.0 - */ - resetConfig: function () - { - this.currentConfig.seek = 0; - this.currentConfig.delay = 0; - }, - - /** - * Update method called automatically by sound manager on every game step. - * - * @method Phaser.Sound.BaseSound#update - * @override - * @protected - * @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 elapsed since the last frame. - */ - update: NOOP, - - /** - * Method used internally to calculate total playback rate of the sound. - * - * @method Phaser.Sound.BaseSound#calculateRate - * @protected - * @since 3.0.0 - */ - calculateRate: function () - { - var cent = 1.0005777895065548; // Math.pow(2, 1/1200); - var totalDetune = this.currentConfig.detune + this.manager.detune; - var detuneRate = Math.pow(cent, totalDetune); - - this.totalRate = this.currentConfig.rate * this.manager.rate * detuneRate; - }, - - /** - * Destroys this sound and all associated events and marks it for removal from the sound manager. - * - * @method Phaser.Sound.BaseSound#destroy - * @fires Phaser.Sound.Events#DESTROY - * @since 3.0.0 - */ - destroy: function () - { - if (this.pendingRemove) - { - return; - } - - this.emit(Events.DESTROY, this); - this.pendingRemove = true; - this.manager = null; - this.key = ''; - this.removeAllListeners(); - this.isPlaying = false; - this.isPaused = false; - this.config = null; - this.currentConfig = null; - this.markers = null; - this.currentMarker = null; - } - -}); - -module.exports = BaseSound; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var Extend = require('../utils/object/Extend'); +var NOOP = require('../utils/NOOP'); + +/** + * @classdesc + * Class containing all the shared state and behavior of a sound object, independent of the implementation. + * + * @class BaseSound + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} 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. + */ +var BaseSound = new Class({ + + Extends: EventEmitter, + + initialize: + + function BaseSound (manager, key, config) + { + EventEmitter.call(this); + + /** + * Local reference to the sound manager. + * + * @name Phaser.Sound.BaseSound#manager + * @type {Phaser.Sound.BaseSoundManager} + * @private + * @since 3.0.0 + */ + this.manager = manager; + + /** + * Asset key for the sound. + * + * @name Phaser.Sound.BaseSound#key + * @type {string} + * @readonly + * @since 3.0.0 + */ + this.key = key; + + /** + * Flag indicating if sound is currently playing. + * + * @name Phaser.Sound.BaseSound#isPlaying + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isPlaying = false; + + /** + * Flag indicating if sound is currently paused. + * + * @name Phaser.Sound.BaseSound#isPaused + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.isPaused = false; + + /** + * A property that holds the value of sound's actual playback rate, + * after its rate and detune values has been combined with global + * rate and detune values. + * + * @name Phaser.Sound.BaseSound#totalRate + * @type {number} + * @default 1 + * @readonly + * @since 3.0.0 + */ + this.totalRate = 1; + + /** + * A value representing the duration, in seconds. + * It could be total sound duration or a marker duration. + * + * @name Phaser.Sound.BaseSound#duration + * @type {number} + * @readonly + * @since 3.0.0 + */ + this.duration = this.duration || 0; + + /** + * The total duration of the sound in seconds. + * + * @name Phaser.Sound.BaseSound#totalDuration + * @type {number} + * @readonly + * @since 3.0.0 + */ + this.totalDuration = this.totalDuration || 0; + + /** + * A config object used to store default sound settings' values. + * Default values will be set by properties' setters. + * + * @name Phaser.Sound.BaseSound#config + * @type {Phaser.Types.Sound.SoundConfig} + * @private + * @since 3.0.0 + */ + this.config = { + + mute: false, + volume: 1, + rate: 1, + detune: 0, + seek: 0, + loop: false, + delay: 0 + + }; + + /** + * Reference to the currently used config. + * It could be default config or marker config. + * + * @name Phaser.Sound.BaseSound#currentConfig + * @type {Phaser.Types.Sound.SoundConfig} + * @private + * @since 3.0.0 + */ + this.currentConfig = this.config; + + this.config = Extend(this.config, config); + + /** + * Object containing markers definitions. + * + * @name Phaser.Sound.BaseSound#markers + * @type {Object.} + * @default {} + * @readonly + * @since 3.0.0 + */ + this.markers = {}; + + /** + * Currently playing marker. + * 'null' if whole sound is playing. + * + * @name Phaser.Sound.BaseSound#currentMarker + * @type {Phaser.Types.Sound.SoundMarker} + * @default null + * @readonly + * @since 3.0.0 + */ + this.currentMarker = null; + + /** + * Flag indicating if destroy method was called on this sound. + * + * @name Phaser.Sound.BaseSound#pendingRemove + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this.pendingRemove = false; + }, + + /** + * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound.BaseSound#addMarker + * @since 3.0.0 + * + * @param {Phaser.Types.Sound.SoundMarker} marker - Marker object. + * + * @return {boolean} Whether the marker was added successfully. + */ + addMarker: function (marker) + { + if (!marker || !marker.name || typeof marker.name !== 'string') + { + return false; + } + + if (this.markers[marker.name]) + { + // eslint-disable-next-line no-console + console.error('addMarker ' + marker.name + ' already exists in Sound'); + + return false; + } + + marker = Extend(true, { + name: '', + start: 0, + duration: this.totalDuration - (marker.start || 0), + config: { + mute: false, + volume: 1, + rate: 1, + detune: 0, + seek: 0, + loop: false, + delay: 0 + } + }, marker); + + this.markers[marker.name] = marker; + + return true; + }, + + /** + * Updates previously added marker. + * + * @method Phaser.Sound.BaseSound#updateMarker + * @since 3.0.0 + * + * @param {Phaser.Types.Sound.SoundMarker} marker - Marker object with updated values. + * + * @return {boolean} Whether the marker was updated successfully. + */ + updateMarker: function (marker) + { + if (!marker || !marker.name || typeof marker.name !== 'string') + { + return false; + } + + if (!this.markers[marker.name]) + { + // eslint-disable-next-line no-console + console.warn('Audio Marker: ' + marker.name + ' missing in Sound: ' + this.key); + + return false; + } + + this.markers[marker.name] = Extend(true, this.markers[marker.name], marker); + + return true; + }, + + /** + * Removes a marker from the sound. + * + * @method Phaser.Sound.BaseSound#removeMarker + * @since 3.0.0 + * + * @param {string} markerName - The name of the marker to remove. + * + * @return {?Phaser.Types.Sound.SoundMarker} Removed marker object or 'null' if there was no marker with provided name. + */ + removeMarker: function (markerName) + { + var marker = this.markers[markerName]; + + if (!marker) + { + return null; + } + + this.markers[markerName] = null; + + return marker; + }, + + /** + * Play this sound, or a marked section of it. + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * + * @method Phaser.Sound.BaseSound#play + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. + * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (markerName, config) + { + if (markerName === undefined) { markerName = ''; } + + if (typeof markerName === 'object') + { + config = markerName; + markerName = ''; + } + + if (typeof markerName !== 'string') + { + return false; + } + + if (!markerName) + { + this.currentMarker = null; + this.currentConfig = this.config; + this.duration = this.totalDuration; + } + else + { + if (!this.markers[markerName]) + { + // eslint-disable-next-line no-console + console.warn('Marker: ' + markerName + ' missing in Sound: ' + this.key); + + return false; + } + + this.currentMarker = this.markers[markerName]; + this.currentConfig = this.currentMarker.config; + this.duration = this.currentMarker.duration; + } + + this.resetConfig(); + + this.currentConfig = Extend(this.currentConfig, config); + + this.isPlaying = true; + this.isPaused = false; + + return true; + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound.BaseSound#pause + * @since 3.0.0 + * + * @return {boolean} Whether the sound was paused successfully. + */ + pause: function () + { + if (this.isPaused || !this.isPlaying) + { + return false; + } + + this.isPlaying = false; + this.isPaused = true; + + return true; + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound.BaseSound#resume + * @since 3.0.0 + * + * @return {boolean} Whether the sound was resumed successfully. + */ + resume: function () + { + if (!this.isPaused || this.isPlaying) + { + return false; + } + + this.isPlaying = true; + this.isPaused = false; + + return true; + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound.BaseSound#stop + * @since 3.0.0 + * + * @return {boolean} Whether the sound was stopped successfully. + */ + stop: function () + { + if (!this.isPaused && !this.isPlaying) + { + return false; + } + + this.isPlaying = false; + this.isPaused = false; + + this.resetConfig(); + + return true; + }, + + /** + * Method used internally for applying config values to some of the sound properties. + * + * @method Phaser.Sound.BaseSound#applyConfig + * @protected + * @since 3.0.0 + */ + applyConfig: function () + { + this.mute = this.currentConfig.mute; + this.volume = this.currentConfig.volume; + this.rate = this.currentConfig.rate; + this.detune = this.currentConfig.detune; + this.loop = this.currentConfig.loop; + }, + + /** + * Method used internally for resetting values of some of the config properties. + * + * @method Phaser.Sound.BaseSound#resetConfig + * @protected + * @since 3.0.0 + */ + resetConfig: function () + { + this.currentConfig.seek = 0; + this.currentConfig.delay = 0; + }, + + /** + * Update method called automatically by sound manager on every game step. + * + * @method Phaser.Sound.BaseSound#update + * @override + * @protected + * @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 elapsed since the last frame. + */ + update: NOOP, + + /** + * Method used internally to calculate total playback rate of the sound. + * + * @method Phaser.Sound.BaseSound#calculateRate + * @protected + * @since 3.0.0 + */ + calculateRate: function () + { + var cent = 1.0005777895065548; // Math.pow(2, 1/1200); + var totalDetune = this.currentConfig.detune + this.manager.detune; + var detuneRate = Math.pow(cent, totalDetune); + + this.totalRate = this.currentConfig.rate * this.manager.rate * detuneRate; + }, + + /** + * Destroys this sound and all associated events and marks it for removal from the sound manager. + * + * @method Phaser.Sound.BaseSound#destroy + * @fires Phaser.Sound.Events#DESTROY + * @since 3.0.0 + */ + destroy: function () + { + if (this.pendingRemove) + { + return; + } + + this.emit(Events.DESTROY, this); + this.pendingRemove = true; + this.manager = null; + this.key = ''; + this.removeAllListeners(); + this.isPlaying = false; + this.isPaused = false; + this.config = null; + this.currentConfig = null; + this.markers = null; + this.currentMarker = null; + } + +}); + +module.exports = BaseSound; diff --git a/src/sound/BaseSoundManager.js b/src/sound/BaseSoundManager.js index 72d222e85..270f23720 100644 --- a/src/sound/BaseSoundManager.js +++ b/src/sound/BaseSoundManager.js @@ -1,619 +1,619 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Clone = require('../utils/object/Clone'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GameEvents = require('../core/events'); -var NOOP = require('../utils/NOOP'); - -/** - * @classdesc - * The sound manager is responsible for playing back audio via Web Audio API or HTML Audio tag as fallback. - * The audio file type and the encoding of those files are extremely important. - * - * Not all browsers can play all audio formats. - * - * There is a good guide to what's supported [here](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support). - * - * @class BaseSoundManager - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - Reference to the current game instance. - */ -var BaseSoundManager = new Class({ - - Extends: EventEmitter, - - initialize: - - function BaseSoundManager (game) - { - EventEmitter.call(this); - - /** - * Local reference to game. - * - * @name Phaser.Sound.BaseSoundManager#game - * @type {Phaser.Game} - * @readonly - * @since 3.0.0 - */ - this.game = game; - - /** - * Local reference to the JSON Cache, as used by Audio Sprites. - * - * @name Phaser.Sound.BaseSoundManager#jsonCache - * @type {Phaser.Cache.BaseCache} - * @readonly - * @since 3.7.0 - */ - this.jsonCache = game.cache.json; - - /** - * An array containing all added sounds. - * - * @name Phaser.Sound.BaseSoundManager#sounds - * @type {Phaser.Sound.BaseSound[]} - * @default [] - * @private - * @since 3.0.0 - */ - this.sounds = []; - - /** - * Global mute setting. - * - * @name Phaser.Sound.BaseSoundManager#mute - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.mute = false; - - /** - * Global volume setting. - * - * @name Phaser.Sound.BaseSoundManager#volume - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.volume = 1; - - /** - * Flag indicating if sounds should be paused when game looses focus, - * for instance when user switches to another tab/program/app. - * - * @name Phaser.Sound.BaseSoundManager#pauseOnBlur - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.pauseOnBlur = true; - - /** - * Property that actually holds the value of global playback rate. - * - * @name Phaser.Sound.BaseSoundManager#_rate - * @type {number} - * @private - * @default 1 - * @since 3.0.0 - */ - this._rate = 1; - - /** - * Property that actually holds the value of global detune. - * - * @name Phaser.Sound.BaseSoundManager#_detune - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this._detune = 0; - - /** - * Mobile devices require sounds to be triggered from an explicit user action, - * such as a tap, before any sound can be loaded/played on a web page. - * Set to true if the audio system is currently locked awaiting user interaction. - * - * @name Phaser.Sound.BaseSoundManager#locked - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - this.locked = this.locked || false; - - /** - * Flag used internally for handling when the audio system - * has been unlocked, if there ever was a need for it. - * - * @name Phaser.Sound.BaseSoundManager#unlocked - * @type {boolean} - * @default false - * @private - * @since 3.0.0 - */ - this.unlocked = false; - - game.events.on(GameEvents.BLUR, function () - { - if (this.pauseOnBlur) - { - this.onBlur(); - } - }, this); - - game.events.on(GameEvents.FOCUS, function () - { - if (this.pauseOnBlur) - { - this.onFocus(); - } - }, this); - - game.events.on(GameEvents.PRE_STEP, this.update, this); - game.events.once(GameEvents.DESTROY, this.destroy, this); - }, - - /** - * Adds a new sound into the sound manager. - * - * @method Phaser.Sound.BaseSoundManager#add - * @override - * @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.BaseSound} The new sound instance. - */ - add: NOOP, - - /** - * 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.HTML5AudioSound|Phaser.Sound.WebAudioSound)} The new audio sprite sound instance. - */ - addAudioSprite: function (key, config) - { - if (config === undefined) { config = {}; } - - var sound = this.add(key, config); - - sound.spritemap = this.jsonCache.get(key).spritemap; - - for (var markerName in sound.spritemap) - { - if (!sound.spritemap.hasOwnProperty(markerName)) - { - continue; - } - - var markerConfig = Clone(config); - - var marker = sound.spritemap[markerName]; - - markerConfig.loop = (marker.hasOwnProperty('loop')) ? marker.loop : false; - - sound.addMarker({ - name: markerName, - start: marker.start, - duration: marker.end - marker.start, - config: markerConfig - }); - } - - return sound; - }, - - /** - * Adds a new sound to the sound manager and plays it. - * The sound will be automatically removed (destroyed) once playback ends. - * This lets you play a new sound on the fly without the need to keep a reference to it. - * - * @method Phaser.Sound.BaseSoundManager#play - * @listens Phaser.Sound.Events#COMPLETE - * @since 3.0.0 - * - * @param {string} key - Asset key for the sound. - * @param {(Phaser.Types.Sound.SoundConfig|Phaser.Types.Sound.SoundMarker)} [extra] - An optional additional object containing settings to be applied to the sound. It could be either config or marker object. - * - * @return {boolean} Whether the sound started playing successfully. - */ - play: function (key, extra) - { - var sound = this.add(key); - - sound.once(Events.COMPLETE, sound.destroy, sound); - - if (extra) - { - if (extra.name) - { - sound.addMarker(extra); - - return sound.play(extra.name); - } - else - { - return sound.play(extra); - } - } - else - { - return sound.play(); - } - }, - - /** - * Enables playing audio sprite sound on the fly without the need to keep a reference to it. - * Sound will auto destroy once its playback ends. - * - * @method Phaser.Sound.BaseSoundManager#playAudioSprite - * @listens Phaser.Sound.Events#COMPLETE - * @since 3.0.0 - * - * @param {string} key - Asset key for the sound. - * @param {string} spriteName - The name of the sound sprite to play. - * @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings. - * - * @return {boolean} Whether the audio sprite sound started playing successfully. - */ - playAudioSprite: function (key, spriteName, config) - { - var sound = this.addAudioSprite(key); - - sound.once(Events.COMPLETE, sound.destroy, sound); - - return sound.play(spriteName, config); - }, - - /** - * Removes a sound from the sound manager. - * The removed sound is destroyed before removal. - * - * @method Phaser.Sound.BaseSoundManager#remove - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSound} sound - The sound object to remove. - * - * @return {boolean} True if the sound was removed successfully, otherwise false. - */ - remove: function (sound) - { - var index = this.sounds.indexOf(sound); - - if (index !== -1) - { - sound.destroy(); - - this.sounds.splice(index, 1); - - return true; - } - - return false; - }, - - /** - * Removes all sounds from the sound manager that have an asset key matching the given value. - * The removed sounds are destroyed before removal. - * - * @method Phaser.Sound.BaseSoundManager#removeByKey - * @since 3.0.0 - * - * @param {string} key - The key to match when removing sound objects. - * - * @return {number} The number of matching sound objects that were removed. - */ - removeByKey: function (key) - { - var removed = 0; - - for (var i = this.sounds.length - 1; i >= 0; i--) - { - var sound = this.sounds[i]; - - if (sound.key === key) - { - sound.destroy(); - - this.sounds.splice(i, 1); - - removed++; - } - } - - return removed; - }, - - /** - * Pauses all the sounds in the game. - * - * @method Phaser.Sound.BaseSoundManager#pauseAll - * @fires Phaser.Sound.Events#PAUSE_ALL - * @since 3.0.0 - */ - pauseAll: function () - { - this.forEachActiveSound(function (sound) - { - sound.pause(); - }); - - this.emit(Events.PAUSE_ALL, this); - }, - - /** - * Resumes all the sounds in the game. - * - * @method Phaser.Sound.BaseSoundManager#resumeAll - * @fires Phaser.Sound.Events#RESUME_ALL - * @since 3.0.0 - */ - resumeAll: function () - { - this.forEachActiveSound(function (sound) - { - sound.resume(); - }); - - this.emit(Events.RESUME_ALL, this); - }, - - /** - * Stops all the sounds in the game. - * - * @method Phaser.Sound.BaseSoundManager#stopAll - * @fires Phaser.Sound.Events#STOP_ALL - * @since 3.0.0 - */ - stopAll: function () - { - this.forEachActiveSound(function (sound) - { - sound.stop(); - }); - - this.emit(Events.STOP_ALL, this); - }, - - /** - * 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 - */ - unlock: NOOP, - - /** - * Method used internally for pausing sound manager if - * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.BaseSoundManager#onBlur - * @override - * @protected - * @since 3.0.0 - */ - onBlur: NOOP, - - /** - * Method used internally for resuming sound manager if - * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.BaseSoundManager#onFocus - * @override - * @protected - * @since 3.0.0 - */ - onFocus: NOOP, - - /** - * Update method called on every game step. - * Removes destroyed sounds and updates every active sound in the game. - * - * @method Phaser.Sound.BaseSoundManager#update - * @protected - * @fires Phaser.Sound.Events#UNLOCKED - * @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 elapsed since the last frame. - */ - update: function (time, delta) - { - if (this.unlocked) - { - this.unlocked = false; - this.locked = false; - - this.emit(Events.UNLOCKED, this); - } - - for (var i = this.sounds.length - 1; i >= 0; i--) - { - if (this.sounds[i].pendingRemove) - { - this.sounds.splice(i, 1); - } - } - - this.sounds.forEach(function (sound) - { - sound.update(time, delta); - }); - }, - - /** - * Destroys all the sounds in the game and all associated events. - * - * @method Phaser.Sound.BaseSoundManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.removeAllListeners(); - - this.forEachActiveSound(function (sound) - { - sound.destroy(); - }); - - this.sounds.length = 0; - this.sounds = null; - - this.game = null; - }, - - /** - * Method used internally for iterating only over active sounds and skipping sounds that are marked for removal. - * - * @method Phaser.Sound.BaseSoundManager#forEachActiveSound - * @private - * @since 3.0.0 - * - * @param {Phaser.Types.Sound.EachActiveSoundCallback} callback - Callback function. (manager: Phaser.Sound.BaseSoundManager, sound: Phaser.Sound.BaseSound, index: number, sounds: Phaser.Manager.BaseSound[]) => void - * @param {*} [scope] - Callback context. - */ - forEachActiveSound: function (callback, scope) - { - var _this = this; - - this.sounds.forEach(function (sound, index) - { - if (sound && !sound.pendingRemove) - { - callback.call(scope || _this, sound, index, _this.sounds); - } - }); - }, - - /** - * Sets the global playback rate at which all the sounds will be played. - * - * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * - * @method Phaser.Sound.BaseSoundManager#setRate - * @fires Phaser.Sound.Events#GLOBAL_RATE - * @since 3.3.0 - * - * @param {number} value - Global playback rate at which all the sounds will be played. - * - * @return {Phaser.Sound.BaseSoundManager} This Sound Manager. - */ - setRate: function (value) - { - this.rate = value; - - return this; - }, - - /** - * Global playback rate at which all the sounds will be played. - * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audio's playback speed. - * - * @name Phaser.Sound.BaseSoundManager#rate - * @type {number} - * @default 1 - * @since 3.0.0 - */ - rate: { - - get: function () - { - return this._rate; - }, - - set: function (value) - { - this._rate = value; - - this.forEachActiveSound(function (sound) - { - sound.calculateRate(); - }); - - this.emit(Events.GLOBAL_RATE, this, value); - } - - }, - - /** - * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - * - * @method Phaser.Sound.BaseSoundManager#setDetune - * @fires Phaser.Sound.Events#GLOBAL_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 {Phaser.Sound.BaseSoundManager} This Sound Manager. - */ - setDetune: function (value) - { - this.detune = value; - - return this; - }, - - /** - * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - * - * @name Phaser.Sound.BaseSoundManager#detune - * @type {number} - * @default 0 - * @since 3.0.0 - */ - detune: { - - get: function () - { - return this._detune; - }, - - set: function (value) - { - this._detune = value; - - this.forEachActiveSound(function (sound) - { - sound.calculateRate(); - }); - - this.emit(Events.GLOBAL_DETUNE, this, value); - } - - } - -}); - -module.exports = BaseSoundManager; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Clone = require('../utils/object/Clone'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GameEvents = require('../core/events'); +var NOOP = require('../utils/NOOP'); + +/** + * @classdesc + * The sound manager is responsible for playing back audio via Web Audio API or HTML Audio tag as fallback. + * The audio file type and the encoding of those files are extremely important. + * + * Not all browsers can play all audio formats. + * + * There is a good guide to what's supported [here](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support). + * + * @class BaseSoundManager + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var BaseSoundManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function BaseSoundManager (game) + { + EventEmitter.call(this); + + /** + * Local reference to game. + * + * @name Phaser.Sound.BaseSoundManager#game + * @type {Phaser.Game} + * @readonly + * @since 3.0.0 + */ + this.game = game; + + /** + * Local reference to the JSON Cache, as used by Audio Sprites. + * + * @name Phaser.Sound.BaseSoundManager#jsonCache + * @type {Phaser.Cache.BaseCache} + * @readonly + * @since 3.7.0 + */ + this.jsonCache = game.cache.json; + + /** + * An array containing all added sounds. + * + * @name Phaser.Sound.BaseSoundManager#sounds + * @type {Phaser.Sound.BaseSound[]} + * @default [] + * @private + * @since 3.0.0 + */ + this.sounds = []; + + /** + * Global mute setting. + * + * @name Phaser.Sound.BaseSoundManager#mute + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.mute = false; + + /** + * Global volume setting. + * + * @name Phaser.Sound.BaseSoundManager#volume + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.volume = 1; + + /** + * Flag indicating if sounds should be paused when game looses focus, + * for instance when user switches to another tab/program/app. + * + * @name Phaser.Sound.BaseSoundManager#pauseOnBlur + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.pauseOnBlur = true; + + /** + * Property that actually holds the value of global playback rate. + * + * @name Phaser.Sound.BaseSoundManager#_rate + * @type {number} + * @private + * @default 1 + * @since 3.0.0 + */ + this._rate = 1; + + /** + * Property that actually holds the value of global detune. + * + * @name Phaser.Sound.BaseSoundManager#_detune + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this._detune = 0; + + /** + * Mobile devices require sounds to be triggered from an explicit user action, + * such as a tap, before any sound can be loaded/played on a web page. + * Set to true if the audio system is currently locked awaiting user interaction. + * + * @name Phaser.Sound.BaseSoundManager#locked + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.locked = this.locked || false; + + /** + * Flag used internally for handling when the audio system + * has been unlocked, if there ever was a need for it. + * + * @name Phaser.Sound.BaseSoundManager#unlocked + * @type {boolean} + * @default false + * @private + * @since 3.0.0 + */ + this.unlocked = false; + + game.events.on(GameEvents.BLUR, function () + { + if (this.pauseOnBlur) + { + this.onBlur(); + } + }, this); + + game.events.on(GameEvents.FOCUS, function () + { + if (this.pauseOnBlur) + { + this.onFocus(); + } + }, this); + + game.events.on(GameEvents.PRE_STEP, this.update, this); + game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * Adds a new sound into the sound manager. + * + * @method Phaser.Sound.BaseSoundManager#add + * @override + * @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.BaseSound} The new sound instance. + */ + add: NOOP, + + /** + * 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.HTML5AudioSound|Phaser.Sound.WebAudioSound)} The new audio sprite sound instance. + */ + addAudioSprite: function (key, config) + { + if (config === undefined) { config = {}; } + + var sound = this.add(key, config); + + sound.spritemap = this.jsonCache.get(key).spritemap; + + for (var markerName in sound.spritemap) + { + if (!sound.spritemap.hasOwnProperty(markerName)) + { + continue; + } + + var markerConfig = Clone(config); + + var marker = sound.spritemap[markerName]; + + markerConfig.loop = (marker.hasOwnProperty('loop')) ? marker.loop : false; + + sound.addMarker({ + name: markerName, + start: marker.start, + duration: marker.end - marker.start, + config: markerConfig + }); + } + + return sound; + }, + + /** + * Adds a new sound to the sound manager and plays it. + * The sound will be automatically removed (destroyed) once playback ends. + * This lets you play a new sound on the fly without the need to keep a reference to it. + * + * @method Phaser.Sound.BaseSoundManager#play + * @listens Phaser.Sound.Events#COMPLETE + * @since 3.0.0 + * + * @param {string} key - Asset key for the sound. + * @param {(Phaser.Types.Sound.SoundConfig|Phaser.Types.Sound.SoundMarker)} [extra] - An optional additional object containing settings to be applied to the sound. It could be either config or marker object. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (key, extra) + { + var sound = this.add(key); + + sound.once(Events.COMPLETE, sound.destroy, sound); + + if (extra) + { + if (extra.name) + { + sound.addMarker(extra); + + return sound.play(extra.name); + } + else + { + return sound.play(extra); + } + } + else + { + return sound.play(); + } + }, + + /** + * Enables playing audio sprite sound on the fly without the need to keep a reference to it. + * Sound will auto destroy once its playback ends. + * + * @method Phaser.Sound.BaseSoundManager#playAudioSprite + * @listens Phaser.Sound.Events#COMPLETE + * @since 3.0.0 + * + * @param {string} key - Asset key for the sound. + * @param {string} spriteName - The name of the sound sprite to play. + * @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings. + * + * @return {boolean} Whether the audio sprite sound started playing successfully. + */ + playAudioSprite: function (key, spriteName, config) + { + var sound = this.addAudioSprite(key); + + sound.once(Events.COMPLETE, sound.destroy, sound); + + return sound.play(spriteName, config); + }, + + /** + * Removes a sound from the sound manager. + * The removed sound is destroyed before removal. + * + * @method Phaser.Sound.BaseSoundManager#remove + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSound} sound - The sound object to remove. + * + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) + { + var index = this.sounds.indexOf(sound); + + if (index !== -1) + { + sound.destroy(); + + this.sounds.splice(index, 1); + + return true; + } + + return false; + }, + + /** + * Removes all sounds from the sound manager that have an asset key matching the given value. + * The removed sounds are destroyed before removal. + * + * @method Phaser.Sound.BaseSoundManager#removeByKey + * @since 3.0.0 + * + * @param {string} key - The key to match when removing sound objects. + * + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) + { + var removed = 0; + + for (var i = this.sounds.length - 1; i >= 0; i--) + { + var sound = this.sounds[i]; + + if (sound.key === key) + { + sound.destroy(); + + this.sounds.splice(i, 1); + + removed++; + } + } + + return removed; + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.Sound.BaseSoundManager#pauseAll + * @fires Phaser.Sound.Events#PAUSE_ALL + * @since 3.0.0 + */ + pauseAll: function () + { + this.forEachActiveSound(function (sound) + { + sound.pause(); + }); + + this.emit(Events.PAUSE_ALL, this); + }, + + /** + * Resumes all the sounds in the game. + * + * @method Phaser.Sound.BaseSoundManager#resumeAll + * @fires Phaser.Sound.Events#RESUME_ALL + * @since 3.0.0 + */ + resumeAll: function () + { + this.forEachActiveSound(function (sound) + { + sound.resume(); + }); + + this.emit(Events.RESUME_ALL, this); + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.Sound.BaseSoundManager#stopAll + * @fires Phaser.Sound.Events#STOP_ALL + * @since 3.0.0 + */ + stopAll: function () + { + this.forEachActiveSound(function (sound) + { + sound.stop(); + }); + + this.emit(Events.STOP_ALL, this); + }, + + /** + * 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 + */ + unlock: NOOP, + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.BaseSoundManager#onBlur + * @override + * @protected + * @since 3.0.0 + */ + onBlur: NOOP, + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.BaseSoundManager#onFocus + * @override + * @protected + * @since 3.0.0 + */ + onFocus: NOOP, + + /** + * Update method called on every game step. + * Removes destroyed sounds and updates every active sound in the game. + * + * @method Phaser.Sound.BaseSoundManager#update + * @protected + * @fires Phaser.Sound.Events#UNLOCKED + * @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 elapsed since the last frame. + */ + update: function (time, delta) + { + if (this.unlocked) + { + this.unlocked = false; + this.locked = false; + + this.emit(Events.UNLOCKED, this); + } + + for (var i = this.sounds.length - 1; i >= 0; i--) + { + if (this.sounds[i].pendingRemove) + { + this.sounds.splice(i, 1); + } + } + + this.sounds.forEach(function (sound) + { + sound.update(time, delta); + }); + }, + + /** + * Destroys all the sounds in the game and all associated events. + * + * @method Phaser.Sound.BaseSoundManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllListeners(); + + this.forEachActiveSound(function (sound) + { + sound.destroy(); + }); + + this.sounds.length = 0; + this.sounds = null; + + this.game = null; + }, + + /** + * Method used internally for iterating only over active sounds and skipping sounds that are marked for removal. + * + * @method Phaser.Sound.BaseSoundManager#forEachActiveSound + * @private + * @since 3.0.0 + * + * @param {Phaser.Types.Sound.EachActiveSoundCallback} callback - Callback function. (manager: Phaser.Sound.BaseSoundManager, sound: Phaser.Sound.BaseSound, index: number, sounds: Phaser.Manager.BaseSound[]) => void + * @param {*} [scope] - Callback context. + */ + forEachActiveSound: function (callback, scope) + { + var _this = this; + + this.sounds.forEach(function (sound, index) + { + if (sound && !sound.pendingRemove) + { + callback.call(scope || _this, sound, index, _this.sounds); + } + }); + }, + + /** + * Sets the global playback rate at which all the sounds will be played. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @method Phaser.Sound.BaseSoundManager#setRate + * @fires Phaser.Sound.Events#GLOBAL_RATE + * @since 3.3.0 + * + * @param {number} value - Global playback rate at which all the sounds will be played. + * + * @return {Phaser.Sound.BaseSoundManager} This Sound Manager. + */ + setRate: function (value) + { + this.rate = value; + + return this; + }, + + /** + * Global playback rate at which all the sounds will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audio's playback speed. + * + * @name Phaser.Sound.BaseSoundManager#rate + * @type {number} + * @default 1 + * @since 3.0.0 + */ + rate: { + + get: function () + { + return this._rate; + }, + + set: function (value) + { + this._rate = value; + + this.forEachActiveSound(function (sound) + { + sound.calculateRate(); + }); + + this.emit(Events.GLOBAL_RATE, this, value); + } + + }, + + /** + * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + * + * @method Phaser.Sound.BaseSoundManager#setDetune + * @fires Phaser.Sound.Events#GLOBAL_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 {Phaser.Sound.BaseSoundManager} This Sound Manager. + */ + setDetune: function (value) + { + this.detune = value; + + return this; + }, + + /** + * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + * + * @name Phaser.Sound.BaseSoundManager#detune + * @type {number} + * @default 0 + * @since 3.0.0 + */ + detune: { + + get: function () + { + return this._detune; + }, + + set: function (value) + { + this._detune = value; + + this.forEachActiveSound(function (sound) + { + sound.calculateRate(); + }); + + this.emit(Events.GLOBAL_DETUNE, this, value); + } + + } + +}); + +module.exports = BaseSoundManager; diff --git a/src/sound/SoundManagerCreator.js b/src/sound/SoundManagerCreator.js index 46c5ec590..c7092ee6d 100644 --- a/src/sound/SoundManagerCreator.js +++ b/src/sound/SoundManagerCreator.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var HTML5AudioSoundManager = require('./html5/HTML5AudioSoundManager'); -var NoAudioSoundManager = require('./noaudio/NoAudioSoundManager'); -var WebAudioSoundManager = require('./webaudio/WebAudioSoundManager'); - -/** - * 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 - * - * @function Phaser.Sound.SoundManagerCreator - * @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. - */ -var SoundManagerCreator = { - - create: function (game) - { - var audioConfig = game.config.audio; - var deviceAudio = game.device.audio; - - if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) - { - return new NoAudioSoundManager(game); - } - - if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) - { - return new WebAudioSoundManager(game); - } - - return new HTML5AudioSoundManager(game); - } - -}; - -module.exports = SoundManagerCreator; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HTML5AudioSoundManager = require('./html5/HTML5AudioSoundManager'); +var NoAudioSoundManager = require('./noaudio/NoAudioSoundManager'); +var WebAudioSoundManager = require('./webaudio/WebAudioSoundManager'); + +/** + * 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 + * + * @function Phaser.Sound.SoundManagerCreator + * @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. + */ +var SoundManagerCreator = { + + create: function (game) + { + var audioConfig = game.config.audio; + var deviceAudio = game.device.audio; + + if ((audioConfig && audioConfig.noAudio) || (!deviceAudio.webAudio && !deviceAudio.audioData)) + { + return new NoAudioSoundManager(game); + } + + if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) + { + return new WebAudioSoundManager(game); + } + + return new HTML5AudioSoundManager(game); + } + +}; + +module.exports = SoundManagerCreator; diff --git a/src/sound/events/COMPLETE_EVENT.js b/src/sound/events/COMPLETE_EVENT.js index c2c54b494..f3d07be82 100644 --- a/src/sound/events/COMPLETE_EVENT.js +++ b/src/sound/events/COMPLETE_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Complete Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they complete playback. - * - * Listen to it from a Sound instance using `Sound.on('complete', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('complete', listener); - * music.play(); - * ``` - * - * @event Phaser.Sound.Events#COMPLETE - * @since 3.16.1 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'complete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Complete Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they complete playback. + * + * Listen to it from a Sound instance using `Sound.on('complete', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('complete', listener); + * music.play(); + * ``` + * + * @event Phaser.Sound.Events#COMPLETE + * @since 3.16.1 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'complete'; diff --git a/src/sound/events/DECODED_ALL_EVENT.js b/src/sound/events/DECODED_ALL_EVENT.js index bfef313f8..dc5443741 100644 --- a/src/sound/events/DECODED_ALL_EVENT.js +++ b/src/sound/events/DECODED_ALL_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Audio Data Decoded All Event. - * - * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method, - * once all files passed to the method have been decoded (or errored). - * - * Use `Phaser.Sound.Events#DECODED` to listen for single sounds being decoded, and `DECODED_ALL` to - * listen for them all completing. - * - * Listen to it from the Sound Manager in a Scene using `this.sound.on('decodedall', listener)`, i.e.: - * - * ```javascript - * this.sound.once('decodedall', handler); - * this.sound.decodeAudio([ audioFiles ]); - * ``` - * - * @event Phaser.Sound.Events#DECODED_ALL - * @since 3.18.0 - */ -module.exports = 'decodedall'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Audio Data Decoded All Event. + * + * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method, + * once all files passed to the method have been decoded (or errored). + * + * Use `Phaser.Sound.Events#DECODED` to listen for single sounds being decoded, and `DECODED_ALL` to + * listen for them all completing. + * + * Listen to it from the Sound Manager in a Scene using `this.sound.on('decodedall', listener)`, i.e.: + * + * ```javascript + * this.sound.once('decodedall', handler); + * this.sound.decodeAudio([ audioFiles ]); + * ``` + * + * @event Phaser.Sound.Events#DECODED_ALL + * @since 3.18.0 + */ +module.exports = 'decodedall'; diff --git a/src/sound/events/DECODED_EVENT.js b/src/sound/events/DECODED_EVENT.js index abb3ed56e..fcb52690c 100644 --- a/src/sound/events/DECODED_EVENT.js +++ b/src/sound/events/DECODED_EVENT.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Audio Data Decoded Event. - * - * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method. - * - * Listen to it from the Sound Manager in a Scene using `this.sound.on('decoded', listener)`, i.e.: - * - * ```javascript - * this.sound.on('decoded', handler); - * this.sound.decodeAudio(key, audioData); - * ``` - * - * @event Phaser.Sound.Events#DECODED - * @since 3.18.0 - * - * @param {string} key - The key of the audio file that was decoded and added to the audio cache. - */ -module.exports = 'decoded'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Audio Data Decoded Event. + * + * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method. + * + * Listen to it from the Sound Manager in a Scene using `this.sound.on('decoded', listener)`, i.e.: + * + * ```javascript + * this.sound.on('decoded', handler); + * this.sound.decodeAudio(key, audioData); + * ``` + * + * @event Phaser.Sound.Events#DECODED + * @since 3.18.0 + * + * @param {string} key - The key of the audio file that was decoded and added to the audio cache. + */ +module.exports = 'decoded'; diff --git a/src/sound/events/DESTROY_EVENT.js b/src/sound/events/DESTROY_EVENT.js index 2ddc5b513..917eb1647 100644 --- a/src/sound/events/DESTROY_EVENT.js +++ b/src/sound/events/DESTROY_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Destroy Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are destroyed, either - * directly or via a Sound Manager. - * - * Listen to it from a Sound instance using `Sound.on('destroy', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('destroy', listener); - * music.destroy(); - * ``` - * - * @event Phaser.Sound.Events#DESTROY - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'destroy'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Destroy Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are destroyed, either + * directly or via a Sound Manager. + * + * Listen to it from a Sound instance using `Sound.on('destroy', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('destroy', listener); + * music.destroy(); + * ``` + * + * @event Phaser.Sound.Events#DESTROY + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'destroy'; diff --git a/src/sound/events/DETUNE_EVENT.js b/src/sound/events/DETUNE_EVENT.js index aac3b4076..70e930cf5 100644 --- a/src/sound/events/DETUNE_EVENT.js +++ b/src/sound/events/DETUNE_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Detune Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their detune value changes. - * - * Listen to it from a Sound instance using `Sound.on('detune', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('detune', listener); - * music.play(); - * music.setDetune(200); - * ``` - * - * @event Phaser.Sound.Events#DETUNE - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - * @param {number} detune - The new detune value of the Sound. - */ -module.exports = 'detune'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Detune Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their detune value changes. + * + * Listen to it from a Sound instance using `Sound.on('detune', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('detune', listener); + * music.play(); + * music.setDetune(200); + * ``` + * + * @event Phaser.Sound.Events#DETUNE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} detune - The new detune value of the Sound. + */ +module.exports = 'detune'; diff --git a/src/sound/events/GLOBAL_DETUNE_EVENT.js b/src/sound/events/GLOBAL_DETUNE_EVENT.js index c8d09861a..3c17fa873 100644 --- a/src/sound/events/GLOBAL_DETUNE_EVENT.js +++ b/src/sound/events/GLOBAL_DETUNE_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Manager Global Detune Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `detune` property of the Sound Manager is changed, which globally - * adjusts the detuning of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('rate', listener)`. - * - * @event Phaser.Sound.Events#GLOBAL_DETUNE - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. - * @param {number} detune - The updated detune value. - */ -module.exports = 'detune'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Detune Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `detune` property of the Sound Manager is changed, which globally + * adjusts the detuning of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('rate', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_DETUNE + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + * @param {number} detune - The updated detune value. + */ +module.exports = 'detune'; diff --git a/src/sound/events/GLOBAL_MUTE_EVENT.js b/src/sound/events/GLOBAL_MUTE_EVENT.js index 7b9164e69..de9a25070 100644 --- a/src/sound/events/GLOBAL_MUTE_EVENT.js +++ b/src/sound/events/GLOBAL_MUTE_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Manager Global Mute Event. - * - * This event is dispatched by the Sound Manager when its `mute` property is changed, either directly - * or via the `setMute` method. This changes the mute state of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('mute', listener)`. - * - * @event Phaser.Sound.Events#GLOBAL_MUTE - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the Sound Manager that emitted the event. - * @param {boolean} mute - The mute value. `true` if the Sound Manager is now muted, otherwise `false`. - */ -module.exports = 'mute'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Mute Event. + * + * This event is dispatched by the Sound Manager when its `mute` property is changed, either directly + * or via the `setMute` method. This changes the mute state of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('mute', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the Sound Manager that emitted the event. + * @param {boolean} mute - The mute value. `true` if the Sound Manager is now muted, otherwise `false`. + */ +module.exports = 'mute'; diff --git a/src/sound/events/GLOBAL_RATE_EVENT.js b/src/sound/events/GLOBAL_RATE_EVENT.js index 5a43b2364..fbbc6dda2 100644 --- a/src/sound/events/GLOBAL_RATE_EVENT.js +++ b/src/sound/events/GLOBAL_RATE_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Manager Global Rate Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `rate` property of the Sound Manager is changed, which globally - * adjusts the playback rate of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('rate', listener)`. - * - * @event Phaser.Sound.Events#GLOBAL_RATE - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. - * @param {number} rate - The updated rate value. - */ -module.exports = 'rate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Rate Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `rate` property of the Sound Manager is changed, which globally + * adjusts the playback rate of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('rate', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_RATE + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + * @param {number} rate - The updated rate value. + */ +module.exports = 'rate'; diff --git a/src/sound/events/GLOBAL_VOLUME_EVENT.js b/src/sound/events/GLOBAL_VOLUME_EVENT.js index ec86a707b..f583c6234 100644 --- a/src/sound/events/GLOBAL_VOLUME_EVENT.js +++ b/src/sound/events/GLOBAL_VOLUME_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Manager Global Volume Event. - * - * This event is dispatched by the Sound Manager when its `volume` property is changed, either directly - * or via the `setVolume` method. This changes the volume of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('volume', listener)`. - * - * @event Phaser.Sound.Events#GLOBAL_VOLUME - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the sound manager that emitted the event. - * @param {number} volume - The new global volume of the Sound Manager. - */ -module.exports = 'volume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Global Volume Event. + * + * This event is dispatched by the Sound Manager when its `volume` property is changed, either directly + * or via the `setVolume` method. This changes the volume of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('volume', listener)`. + * + * @event Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSoundManager|Phaser.Sound.HTML5AudioSoundManager)} soundManager - A reference to the sound manager that emitted the event. + * @param {number} volume - The new global volume of the Sound Manager. + */ +module.exports = 'volume'; diff --git a/src/sound/events/LOOPED_EVENT.js b/src/sound/events/LOOPED_EVENT.js index 337b927e6..fe32da971 100644 --- a/src/sound/events/LOOPED_EVENT.js +++ b/src/sound/events/LOOPED_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Looped Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they loop during playback. - * - * Listen to it from a Sound instance using `Sound.on('looped', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('looped', listener); - * music.setLoop(true); - * music.play(); - * ``` - * - * This is not to be confused with the [LOOP]{@linkcode Phaser.Sound.Events#event:LOOP} event, which only emits when the loop state of a Sound is changed. - * - * @event Phaser.Sound.Events#LOOPED - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'looped'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Looped Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they loop during playback. + * + * Listen to it from a Sound instance using `Sound.on('looped', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('looped', listener); + * music.setLoop(true); + * music.play(); + * ``` + * + * This is not to be confused with the [LOOP]{@linkcode Phaser.Sound.Events#event:LOOP} event, which only emits when the loop state of a Sound is changed. + * + * @event Phaser.Sound.Events#LOOPED + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'looped'; diff --git a/src/sound/events/LOOP_EVENT.js b/src/sound/events/LOOP_EVENT.js index fa2e375b0..9b5c5cb4d 100644 --- a/src/sound/events/LOOP_EVENT.js +++ b/src/sound/events/LOOP_EVENT.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Loop Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their loop state is changed. - * - * Listen to it from a Sound instance using `Sound.on('loop', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('loop', listener); - * music.setLoop(true); - * ``` - * - * This is not to be confused with the [LOOPED]{@linkcode Phaser.Sound.Events#event:LOOPED} event, which emits each time a Sound loops during playback. - * - * @event Phaser.Sound.Events#LOOP - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - * @param {boolean} loop - The new loop value. `true` if the Sound will loop, otherwise `false`. - */ -module.exports = 'loop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Loop Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their loop state is changed. + * + * Listen to it from a Sound instance using `Sound.on('loop', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('loop', listener); + * music.setLoop(true); + * ``` + * + * This is not to be confused with the [LOOPED]{@linkcode Phaser.Sound.Events#event:LOOPED} event, which emits each time a Sound loops during playback. + * + * @event Phaser.Sound.Events#LOOP + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {boolean} loop - The new loop value. `true` if the Sound will loop, otherwise `false`. + */ +module.exports = 'loop'; diff --git a/src/sound/events/MUTE_EVENT.js b/src/sound/events/MUTE_EVENT.js index f0589c514..7ed48f9eb 100644 --- a/src/sound/events/MUTE_EVENT.js +++ b/src/sound/events/MUTE_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Mute Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their mute state changes. - * - * Listen to it from a Sound instance using `Sound.on('mute', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('mute', listener); - * music.play(); - * music.setMute(true); - * ``` - * - * @event Phaser.Sound.Events#MUTE - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - * @param {boolean} mute - The mute value. `true` if the Sound is now muted, otherwise `false`. - */ -module.exports = 'mute'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Mute Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their mute state changes. + * + * Listen to it from a Sound instance using `Sound.on('mute', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('mute', listener); + * music.play(); + * music.setMute(true); + * ``` + * + * @event Phaser.Sound.Events#MUTE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {boolean} mute - The mute value. `true` if the Sound is now muted, otherwise `false`. + */ +module.exports = 'mute'; diff --git a/src/sound/events/PAUSE_ALL_EVENT.js b/src/sound/events/PAUSE_ALL_EVENT.js index 7f406978f..84de223a2 100644 --- a/src/sound/events/PAUSE_ALL_EVENT.js +++ b/src/sound/events/PAUSE_ALL_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Pause All Sounds Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `pauseAll` method is invoked and after all current Sounds - * have been paused. - * - * Listen to it from a Scene using: `this.sound.on('pauseall', listener)`. - * - * @event Phaser.Sound.Events#PAUSE_ALL - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. - */ -module.exports = 'pauseall'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Pause All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `pauseAll` method is invoked and after all current Sounds + * have been paused. + * + * Listen to it from a Scene using: `this.sound.on('pauseall', listener)`. + * + * @event Phaser.Sound.Events#PAUSE_ALL + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'pauseall'; diff --git a/src/sound/events/PAUSE_EVENT.js b/src/sound/events/PAUSE_EVENT.js index 9f5b9ad26..bbe35cab4 100644 --- a/src/sound/events/PAUSE_EVENT.js +++ b/src/sound/events/PAUSE_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Pause Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are paused. - * - * Listen to it from a Sound instance using `Sound.on('pause', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('pause', listener); - * music.play(); - * music.pause(); - * ``` - * - * @event Phaser.Sound.Events#PAUSE - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Pause Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are paused. + * + * Listen to it from a Sound instance using `Sound.on('pause', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('pause', listener); + * music.play(); + * music.pause(); + * ``` + * + * @event Phaser.Sound.Events#PAUSE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'pause'; diff --git a/src/sound/events/PLAY_EVENT.js b/src/sound/events/PLAY_EVENT.js index 0dfe868ba..39cff1deb 100644 --- a/src/sound/events/PLAY_EVENT.js +++ b/src/sound/events/PLAY_EVENT.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Play Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are played. - * - * Listen to it from a Sound instance using `Sound.on('play', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('play', listener); - * music.play(); - * ``` - * - * @event Phaser.Sound.Events#PLAY - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'play'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Play Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are played. + * + * Listen to it from a Sound instance using `Sound.on('play', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('play', listener); + * music.play(); + * ``` + * + * @event Phaser.Sound.Events#PLAY + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'play'; diff --git a/src/sound/events/RATE_EVENT.js b/src/sound/events/RATE_EVENT.js index d15e0b150..59c24f876 100644 --- a/src/sound/events/RATE_EVENT.js +++ b/src/sound/events/RATE_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Rate Change Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their rate changes. - * - * Listen to it from a Sound instance using `Sound.on('rate', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('rate', listener); - * music.play(); - * music.setRate(0.5); - * ``` - * - * @event Phaser.Sound.Events#RATE - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - * @param {number} rate - The new rate of the Sound. - */ -module.exports = 'rate'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Rate Change Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their rate changes. + * + * Listen to it from a Sound instance using `Sound.on('rate', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('rate', listener); + * music.play(); + * music.setRate(0.5); + * ``` + * + * @event Phaser.Sound.Events#RATE + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} rate - The new rate of the Sound. + */ +module.exports = 'rate'; diff --git a/src/sound/events/RESUME_ALL_EVENT.js b/src/sound/events/RESUME_ALL_EVENT.js index a2d36cdc8..b1ccdc617 100644 --- a/src/sound/events/RESUME_ALL_EVENT.js +++ b/src/sound/events/RESUME_ALL_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Resume All Sounds Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `resumeAll` method is invoked and after all current Sounds - * have been resumed. - * - * Listen to it from a Scene using: `this.sound.on('resumeall', listener)`. - * - * @event Phaser.Sound.Events#RESUME_ALL - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. - */ -module.exports = 'resumeall'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Resume All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `resumeAll` method is invoked and after all current Sounds + * have been resumed. + * + * Listen to it from a Scene using: `this.sound.on('resumeall', listener)`. + * + * @event Phaser.Sound.Events#RESUME_ALL + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'resumeall'; diff --git a/src/sound/events/RESUME_EVENT.js b/src/sound/events/RESUME_EVENT.js index 5fa1aad40..f59238109 100644 --- a/src/sound/events/RESUME_EVENT.js +++ b/src/sound/events/RESUME_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Resume Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are resumed from a paused state. - * - * Listen to it from a Sound instance using `Sound.on('resume', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('resume', listener); - * music.play(); - * music.pause(); - * music.resume(); - * ``` - * - * @event Phaser.Sound.Events#RESUME - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Resume Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are resumed from a paused state. + * + * Listen to it from a Sound instance using `Sound.on('resume', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('resume', listener); + * music.play(); + * music.pause(); + * music.resume(); + * ``` + * + * @event Phaser.Sound.Events#RESUME + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'resume'; diff --git a/src/sound/events/SEEK_EVENT.js b/src/sound/events/SEEK_EVENT.js index 2fe9164d2..c576bfecc 100644 --- a/src/sound/events/SEEK_EVENT.js +++ b/src/sound/events/SEEK_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Seek Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are seeked to a new position. - * - * Listen to it from a Sound instance using `Sound.on('seek', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('seek', listener); - * music.play(); - * music.setSeek(5000); - * ``` - * - * @event Phaser.Sound.Events#SEEK - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - * @param {number} detune - The new detune value of the Sound. - */ -module.exports = 'seek'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Seek Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are seeked to a new position. + * + * Listen to it from a Sound instance using `Sound.on('seek', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('seek', listener); + * music.play(); + * music.setSeek(5000); + * ``` + * + * @event Phaser.Sound.Events#SEEK + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} detune - The new detune value of the Sound. + */ +module.exports = 'seek'; diff --git a/src/sound/events/STOP_ALL_EVENT.js b/src/sound/events/STOP_ALL_EVENT.js index b69d0c9f4..83338fc96 100644 --- a/src/sound/events/STOP_ALL_EVENT.js +++ b/src/sound/events/STOP_ALL_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Stop All Sounds Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `stopAll` method is invoked and after all current Sounds - * have been stopped. - * - * Listen to it from a Scene using: `this.sound.on('stopall', listener)`. - * - * @event Phaser.Sound.Events#STOP_ALL - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. - */ -module.exports = 'stopall'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Stop All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `stopAll` method is invoked and after all current Sounds + * have been stopped. + * + * Listen to it from a Scene using: `this.sound.on('stopall', listener)`. + * + * @event Phaser.Sound.Events#STOP_ALL + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'stopall'; diff --git a/src/sound/events/STOP_EVENT.js b/src/sound/events/STOP_EVENT.js index dcebca4c8..9cdfdf7bb 100644 --- a/src/sound/events/STOP_EVENT.js +++ b/src/sound/events/STOP_EVENT.js @@ -1,26 +1,26 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Stop Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are stopped. - * - * Listen to it from a Sound instance using `Sound.on('stop', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('stop', listener); - * music.play(); - * music.stop(); - * ``` - * - * @event Phaser.Sound.Events#STOP - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - */ -module.exports = 'stop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Stop Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are stopped. + * + * Listen to it from a Sound instance using `Sound.on('stop', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('stop', listener); + * music.play(); + * music.stop(); + * ``` + * + * @event Phaser.Sound.Events#STOP + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + */ +module.exports = 'stop'; diff --git a/src/sound/events/UNLOCKED_EVENT.js b/src/sound/events/UNLOCKED_EVENT.js index 889267748..fabc201e4 100644 --- a/src/sound/events/UNLOCKED_EVENT.js +++ b/src/sound/events/UNLOCKED_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Manager Unlocked Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched during the update loop when the Sound Manager becomes unlocked. For - * Web Audio this is on the first user gesture on the page. - * - * Listen to it from a Scene using: `this.sound.on('unlocked', listener)`. - * - * @event Phaser.Sound.Events#UNLOCKED - * @since 3.0.0 - * - * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. - */ -module.exports = 'unlocked'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Manager Unlocked Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched during the update loop when the Sound Manager becomes unlocked. For + * Web Audio this is on the first user gesture on the page. + * + * Listen to it from a Scene using: `this.sound.on('unlocked', listener)`. + * + * @event Phaser.Sound.Events#UNLOCKED + * @since 3.0.0 + * + * @param {Phaser.Sound.BaseSoundManager} soundManager - A reference to the sound manager that emitted the event. + */ +module.exports = 'unlocked'; diff --git a/src/sound/events/VOLUME_EVENT.js b/src/sound/events/VOLUME_EVENT.js index 8e5e4c92f..7276f98ea 100644 --- a/src/sound/events/VOLUME_EVENT.js +++ b/src/sound/events/VOLUME_EVENT.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Sound Volume Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their volume changes. - * - * Listen to it from a Sound instance using `Sound.on('volume', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('volume', listener); - * music.play(); - * music.setVolume(0.5); - * ``` - * - * @event Phaser.Sound.Events#VOLUME - * @since 3.0.0 - * - * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. - * @param {number} volume - The new volume of the Sound. - */ -module.exports = 'volume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Sound Volume Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their volume changes. + * + * Listen to it from a Sound instance using `Sound.on('volume', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('volume', listener); + * music.play(); + * music.setVolume(0.5); + * ``` + * + * @event Phaser.Sound.Events#VOLUME + * @since 3.0.0 + * + * @param {(Phaser.Sound.WebAudioSound|Phaser.Sound.HTML5AudioSound)} sound - A reference to the Sound that emitted the event. + * @param {number} volume - The new volume of the Sound. + */ +module.exports = 'volume'; diff --git a/src/sound/events/index.js b/src/sound/events/index.js index 139bb2461..3f15710a1 100644 --- a/src/sound/events/index.js +++ b/src/sound/events/index.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Sound.Events - */ - -module.exports = { - - COMPLETE: require('./COMPLETE_EVENT'), - DECODED: require('./DECODED_EVENT'), - DECODED_ALL: require('./DECODED_ALL_EVENT'), - DESTROY: require('./DESTROY_EVENT'), - DETUNE: require('./DETUNE_EVENT'), - GLOBAL_DETUNE: require('./GLOBAL_DETUNE_EVENT'), - GLOBAL_MUTE: require('./GLOBAL_MUTE_EVENT'), - GLOBAL_RATE: require('./GLOBAL_RATE_EVENT'), - GLOBAL_VOLUME: require('./GLOBAL_VOLUME_EVENT'), - LOOP: require('./LOOP_EVENT'), - LOOPED: require('./LOOPED_EVENT'), - MUTE: require('./MUTE_EVENT'), - PAUSE_ALL: require('./PAUSE_ALL_EVENT'), - PAUSE: require('./PAUSE_EVENT'), - PLAY: require('./PLAY_EVENT'), - RATE: require('./RATE_EVENT'), - RESUME_ALL: require('./RESUME_ALL_EVENT'), - RESUME: require('./RESUME_EVENT'), - SEEK: require('./SEEK_EVENT'), - STOP_ALL: require('./STOP_ALL_EVENT'), - STOP: require('./STOP_EVENT'), - UNLOCKED: require('./UNLOCKED_EVENT'), - VOLUME: require('./VOLUME_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Sound.Events + */ + +module.exports = { + + COMPLETE: require('./COMPLETE_EVENT'), + DECODED: require('./DECODED_EVENT'), + DECODED_ALL: require('./DECODED_ALL_EVENT'), + DESTROY: require('./DESTROY_EVENT'), + DETUNE: require('./DETUNE_EVENT'), + GLOBAL_DETUNE: require('./GLOBAL_DETUNE_EVENT'), + GLOBAL_MUTE: require('./GLOBAL_MUTE_EVENT'), + GLOBAL_RATE: require('./GLOBAL_RATE_EVENT'), + GLOBAL_VOLUME: require('./GLOBAL_VOLUME_EVENT'), + LOOP: require('./LOOP_EVENT'), + LOOPED: require('./LOOPED_EVENT'), + MUTE: require('./MUTE_EVENT'), + PAUSE_ALL: require('./PAUSE_ALL_EVENT'), + PAUSE: require('./PAUSE_EVENT'), + PLAY: require('./PLAY_EVENT'), + RATE: require('./RATE_EVENT'), + RESUME_ALL: require('./RESUME_ALL_EVENT'), + RESUME: require('./RESUME_EVENT'), + SEEK: require('./SEEK_EVENT'), + STOP_ALL: require('./STOP_ALL_EVENT'), + STOP: require('./STOP_EVENT'), + UNLOCKED: require('./UNLOCKED_EVENT'), + VOLUME: require('./VOLUME_EVENT') + +}; diff --git a/src/sound/html5/HTML5AudioSound.js b/src/sound/html5/HTML5AudioSound.js index f72d6716f..0f412ceae 100644 --- a/src/sound/html5/HTML5AudioSound.js +++ b/src/sound/html5/HTML5AudioSound.js @@ -1,919 +1,919 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseSound = require('../BaseSound'); -var Class = require('../../utils/Class'); -var Events = require('../events'); - -/** - * @classdesc - * HTML5 Audio implementation of the sound. - * - * @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. - */ -var HTML5AudioSound = new Class({ - - Extends: BaseSound, - - initialize: - - function HTML5AudioSound (manager, key, config) - { - if (config === undefined) { config = {}; } - - /** - * An array containing all HTML5 Audio tags that could be used for individual - * sound's playback. Number of instances depends on the config value passed - * to the Loader#audio method call, default is 1. - * - * @name Phaser.Sound.HTML5AudioSound#tags - * @type {HTMLAudioElement[]} - * @private - * @since 3.0.0 - */ - this.tags = manager.game.cache.audio.get(key); - - if (!this.tags) - { - throw new Error('There is no audio asset with key "' + key + '" in the audio cache'); - } - - /** - * Reference to an HTML5 Audio tag used for playing sound. - * - * @name Phaser.Sound.HTML5AudioSound#audio - * @type {HTMLAudioElement} - * @private - * @default null - * @since 3.0.0 - */ - this.audio = null; - - /** - * Timestamp as generated by the Request Animation Frame or SetTimeout - * representing the time at which the delayed sound playback should start. - * Set to 0 if sound playback is not delayed. - * - * @name Phaser.Sound.HTML5AudioSound#startTime - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.startTime = 0; - - /** - * Audio tag's playback position recorded on previous - * update method call. Set to 0 if sound is not playing. - * - * @name Phaser.Sound.HTML5AudioSound#previousTime - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.previousTime = 0; - - this.duration = this.tags[0].duration; - - this.totalDuration = this.tags[0].duration; - - BaseSound.call(this, manager, key, config); - }, - - /** - * Play this sound, or a marked section of it. - * It always plays the sound from the start. If you want to start playback from a specific time - * you can set 'seek' setting of the config object, provided to this call, to that value. - * - * @method Phaser.Sound.HTML5AudioSound#play - * @fires Phaser.Sound.Events#PLAY - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. - * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. - * - * @return {boolean} Whether the sound started playing successfully. - */ - play: function (markerName, config) - { - if (this.manager.isLocked(this, 'play', [ markerName, config ])) - { - return false; - } - - if (!BaseSound.prototype.play.call(this, markerName, config)) - { - return false; - } - - // \/\/\/ isPlaying = true, isPaused = false \/\/\/ - if (!this.pickAndPlayAudioTag()) - { - return false; - } - - this.emit(Events.PLAY, this); - - return true; - }, - - /** - * Pauses the sound. - * - * @method Phaser.Sound.HTML5AudioSound#pause - * @fires Phaser.Sound.Events#PAUSE - * @since 3.0.0 - * - * @return {boolean} Whether the sound was paused successfully. - */ - pause: function () - { - if (this.manager.isLocked(this, 'pause')) - { - return false; - } - - if (this.startTime > 0) - { - return false; - } - - if (!BaseSound.prototype.pause.call(this)) - { - return false; - } - - // \/\/\/ isPlaying = false, isPaused = true \/\/\/ - this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); - - this.stopAndReleaseAudioTag(); - - this.emit(Events.PAUSE, this); - - return true; - }, - - /** - * Resumes the sound. - * - * @method Phaser.Sound.HTML5AudioSound#resume - * @fires Phaser.Sound.Events#RESUME - * @since 3.0.0 - * - * @return {boolean} Whether the sound was resumed successfully. - */ - resume: function () - { - if (this.manager.isLocked(this, 'resume')) - { - return false; - } - - if (this.startTime > 0) - { - return false; - } - - if (!BaseSound.prototype.resume.call(this)) - { - return false; - } - - // \/\/\/ isPlaying = true, isPaused = false \/\/\/ - if (!this.pickAndPlayAudioTag()) - { - return false; - } - - this.emit(Events.RESUME, this); - - return true; - }, - - /** - * Stop playing this sound. - * - * @method Phaser.Sound.HTML5AudioSound#stop - * @fires Phaser.Sound.Events#STOP - * @since 3.0.0 - * - * @return {boolean} Whether the sound was stopped successfully. - */ - stop: function () - { - if (this.manager.isLocked(this, 'stop')) - { - return false; - } - - if (!BaseSound.prototype.stop.call(this)) - { - return false; - } - - // \/\/\/ isPlaying = false, isPaused = false \/\/\/ - this.stopAndReleaseAudioTag(); - - this.emit(Events.STOP, this); - - return true; - }, - - /** - * Used internally to do what the name says. - * - * @method Phaser.Sound.HTML5AudioSound#pickAndPlayAudioTag - * @private - * @since 3.0.0 - * - * @return {boolean} Whether the sound was assigned an audio tag successfully. - */ - pickAndPlayAudioTag: function () - { - if (!this.pickAudioTag()) - { - this.reset(); - return false; - } - - var seek = this.currentConfig.seek; - var delay = this.currentConfig.delay; - var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; - - this.previousTime = offset; - this.audio.currentTime = offset; - this.applyConfig(); - - if (delay === 0) - { - this.startTime = 0; - - if (this.audio.paused) - { - this.playCatchPromise(); - } - } - else - { - this.startTime = window.performance.now() + delay * 1000; - - if (!this.audio.paused) - { - this.audio.pause(); - } - } - - this.resetConfig(); - - return true; - }, - - /** - * 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 - * @private - * @since 3.0.0 - * - * @return {boolean} Whether the sound was assigned an audio tag successfully. - */ - pickAudioTag: function () - { - if (this.audio) - { - return true; - } - - for (var i = 0; i < this.tags.length; i++) - { - var audio = this.tags[i]; - - if (audio.dataset.used === 'false') - { - audio.dataset.used = 'true'; - this.audio = audio; - return true; - } - } - - if (!this.manager.override) - { - return false; - } - - var otherSounds = []; - - this.manager.forEachActiveSound(function (sound) - { - if (sound.key === this.key && sound.audio) - { - otherSounds.push(sound); - } - }, this); - - otherSounds.sort(function (a1, a2) - { - if (a1.loop === a2.loop) - { - // sort by progress - return (a2.seek / a2.duration) - (a1.seek / a1.duration); - } - return a1.loop ? 1 : -1; - }); - - var selectedSound = otherSounds[0]; - - this.audio = selectedSound.audio; - - selectedSound.reset(); - selectedSound.audio = null; - selectedSound.startTime = 0; - selectedSound.previousTime = 0; - - return true; - }, - - /** - * Method used for playing audio tag and catching possible exceptions - * thrown from rejected Promise returned from play method call. - * - * @method Phaser.Sound.HTML5AudioSound#playCatchPromise - * @private - * @since 3.0.0 - */ - playCatchPromise: function () - { - var playPromise = this.audio.play(); - - if (playPromise) - { - // eslint-disable-next-line no-unused-vars - playPromise.catch(function (reason) - { - console.warn(reason); - }); - } - }, - - /** - * Used internally to do what the name says. - * - * @method Phaser.Sound.HTML5AudioSound#stopAndReleaseAudioTag - * @private - * @since 3.0.0 - */ - stopAndReleaseAudioTag: function () - { - this.audio.pause(); - this.audio.dataset.used = 'false'; - this.audio = null; - this.startTime = 0; - this.previousTime = 0; - }, - - /** - * Method used internally to reset sound state, usually when stopping sound - * or when hijacking audio tag from another sound. - * - * @method Phaser.Sound.HTML5AudioSound#reset - * @private - * @since 3.0.0 - */ - reset: function () - { - BaseSound.prototype.stop.call(this); - }, - - /** - * Method used internally by sound manager for pausing sound if - * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.HTML5AudioSoundManager#onBlur - * @private - * @since 3.0.0 - */ - onBlur: function () - { - this.isPlaying = false; - this.isPaused = true; - - this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); - - this.currentConfig.delay = Math.max(0, (this.startTime - window.performance.now()) / 1000); - - this.stopAndReleaseAudioTag(); - }, - - /** - * Method used internally by sound manager for resuming sound if - * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.HTML5AudioSound#onFocus - * @private - * @since 3.0.0 - */ - onFocus: function () - { - this.isPlaying = true; - this.isPaused = false; - this.pickAndPlayAudioTag(); - }, - - /** - * Update method called automatically by sound manager on every game step. - * - * @method Phaser.Sound.HTML5AudioSound#update - * @fires Phaser.Sound.Events#COMPLETE - * @fires Phaser.Sound.Events#LOOPED - * @protected - * @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 elapsed since the last frame. - */ - // eslint-disable-next-line no-unused-vars - update: function (time, delta) - { - if (!this.isPlaying) - { - return; - } - - // handling delayed playback - if (this.startTime > 0) - { - if (this.startTime < time - this.manager.audioPlayDelay) - { - this.audio.currentTime += Math.max(0, time - this.startTime) / 1000; - this.startTime = 0; - this.previousTime = this.audio.currentTime; - this.playCatchPromise(); - } - - return; - } - - // handle looping and ending - var startTime = this.currentMarker ? this.currentMarker.start : 0; - var endTime = startTime + this.duration; - var currentTime = this.audio.currentTime; - - if (this.currentConfig.loop) - { - if (currentTime >= endTime - this.manager.loopEndOffset) - { - this.audio.currentTime = startTime + Math.max(0, currentTime - endTime); - currentTime = this.audio.currentTime; - } - else if (currentTime < startTime) - { - this.audio.currentTime += startTime; - currentTime = this.audio.currentTime; - } - - if (currentTime < this.previousTime) - { - this.emit(Events.LOOPED, this); - } - } - else if (currentTime >= endTime) - { - this.reset(); - - this.stopAndReleaseAudioTag(); - - this.emit(Events.COMPLETE, this); - - return; - } - - this.previousTime = currentTime; - }, - - /** - * Calls Phaser.Sound.BaseSound#destroy method - * and cleans up all HTML5 Audio related stuff. - * - * @method Phaser.Sound.HTML5AudioSound#destroy - * @since 3.0.0 - */ - destroy: function () - { - BaseSound.prototype.destroy.call(this); - - this.tags = null; - - if (this.audio) - { - this.stopAndReleaseAudioTag(); - } - }, - - /** - * Method used internally to determine mute setting of the sound. - * - * @method Phaser.Sound.HTML5AudioSound#updateMute - * @private - * @since 3.0.0 - */ - updateMute: function () - { - if (this.audio) - { - this.audio.muted = this.currentConfig.mute || this.manager.mute; - } - }, - - /** - * Method used internally to calculate total volume of the sound. - * - * @method Phaser.Sound.HTML5AudioSound#updateVolume - * @private - * @since 3.0.0 - */ - updateVolume: function () - { - if (this.audio) - { - this.audio.volume = this.currentConfig.volume * this.manager.volume; - } - }, - - /** - * Method used internally to calculate total playback rate of the sound. - * - * @method Phaser.Sound.HTML5AudioSound#calculateRate - * @protected - * @since 3.0.0 - */ - calculateRate: function () - { - BaseSound.prototype.calculateRate.call(this); - - if (this.audio) - { - this.audio.playbackRate = this.totalRate; - } - }, - - /** - * Boolean indicating whether the sound is muted or not. - * Gets or sets the muted state of this sound. - * - * @name Phaser.Sound.HTML5AudioSound#mute - * @type {boolean} - * @default false - * @fires Phaser.Sound.Events#MUTE - * @since 3.0.0 - */ - mute: { - - get: function () - { - return this.currentConfig.mute; - }, - - set: function (value) - { - this.currentConfig.mute = value; - - if (this.manager.isLocked(this, 'mute', value)) - { - return; - } - - this.updateMute(); - - this.emit(Events.MUTE, this, value); - } - }, - - /** - * Sets the muted state of this Sound. - * - * @method Phaser.Sound.HTML5AudioSound#setMute - * @fires Phaser.Sound.Events#MUTE - * @since 3.4.0 - * - * @param {boolean} value - `true` to mute this sound, `false` to unmute it. - * - * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. - */ - setMute: function (value) - { - this.mute = value; - - return this; - }, - - /** - * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). - * - * @name Phaser.Sound.HTML5AudioSound#volume - * @type {number} - * @default 1 - * @fires Phaser.Sound.Events#VOLUME - * @since 3.0.0 - */ - volume: { - - get: function () - { - return this.currentConfig.volume; - }, - - set: function (value) - { - this.currentConfig.volume = value; - - if (this.manager.isLocked(this, 'volume', value)) - { - return; - } - - this.updateVolume(); - - this.emit(Events.VOLUME, this, value); - } - }, - - /** - * Sets the volume of this Sound. - * - * @method Phaser.Sound.HTML5AudioSound#setVolume - * @fires Phaser.Sound.Events#VOLUME - * @since 3.4.0 - * - * @param {number} value - The volume of the sound. - * - * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. - */ - setVolume: function (value) - { - this.volume = value; - - return this; - }, - - /** - * Rate at which this Sound will be played. - * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * - * @name Phaser.Sound.HTML5AudioSound#rate - * @type {number} - * @default 1 - * @fires Phaser.Sound.Events#RATE - * @since 3.0.0 - */ - rate: { - - get: function () - { - return this.currentConfig.rate; - }, - - set: function (value) - { - this.currentConfig.rate = value; - - if (this.manager.isLocked(this, Events.RATE, value)) - { - return; - } - else - { - this.calculateRate(); - - this.emit(Events.RATE, this, value); - } - } - - }, - - /** - * Sets the playback rate of this Sound. - * - * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * - * @method Phaser.Sound.HTML5AudioSound#setRate - * @fires Phaser.Sound.Events#RATE - * @since 3.3.0 - * - * @param {number} value - The playback rate at of this Sound. - * - * @return {Phaser.Sound.HTML5AudioSound} This Sound. - */ - setRate: function (value) - { - this.rate = value; - - return this; - }, - - /** - * 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 - */ - detune: { - - get: function () - { - return this.currentConfig.detune; - }, - - set: function (value) - { - this.currentConfig.detune = value; - - if (this.manager.isLocked(this, Events.DETUNE, value)) - { - return; - } - else - { - this.calculateRate(); - - this.emit(Events.DETUNE, this, value); - } - } - - }, - - /** - * 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 {Phaser.Sound.HTML5AudioSound} This Sound. - */ - setDetune: function (value) - { - this.detune = value; - - return this; - }, - - /** - * Property representing the position of playback for this sound, in seconds. - * Setting it to a specific value moves current playback to that position. - * The value given is clamped to the range 0 to current marker duration. - * Setting seek of a stopped sound has no effect. - * - * @name Phaser.Sound.HTML5AudioSound#seek - * @type {number} - * @fires Phaser.Sound.Events#SEEK - * @since 3.0.0 - */ - seek: { - - get: function () - { - if (this.isPlaying) - { - return this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); - } - else if (this.isPaused) - { - return this.currentConfig.seek; - } - else - { - return 0; - } - }, - - set: function (value) - { - if (this.manager.isLocked(this, 'seek', value)) - { - return; - } - - if (this.startTime > 0) - { - return; - } - - if (this.isPlaying || this.isPaused) - { - value = Math.min(Math.max(0, value), this.duration); - - if (this.isPlaying) - { - this.previousTime = value; - this.audio.currentTime = value; - } - else if (this.isPaused) - { - this.currentConfig.seek = value; - } - - this.emit(Events.SEEK, this, value); - } - } - }, - - /** - * Seeks to a specific point in this sound. - * - * @method Phaser.Sound.HTML5AudioSound#setSeek - * @fires Phaser.Sound.Events#SEEK - * @since 3.4.0 - * - * @param {number} value - The point in the sound to seek to. - * - * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. - */ - setSeek: function (value) - { - this.seek = value; - - return this; - }, - - /** - * Flag indicating whether or not the sound or current sound marker will loop. - * - * @name Phaser.Sound.HTML5AudioSound#loop - * @type {boolean} - * @default false - * @fires Phaser.Sound.Events#LOOP - * @since 3.0.0 - */ - loop: { - - get: function () - { - return this.currentConfig.loop; - }, - - set: function (value) - { - this.currentConfig.loop = value; - - if (this.manager.isLocked(this, 'loop', value)) - { - return; - } - - if (this.audio) - { - this.audio.loop = value; - } - - this.emit(Events.LOOP, this, value); - } - - }, - - /** - * Sets the loop state of this Sound. - * - * @method Phaser.Sound.HTML5AudioSound#setLoop - * @fires Phaser.Sound.Events#LOOP - * @since 3.4.0 - * - * @param {boolean} value - `true` to loop this sound, `false` to not loop it. - * - * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. - */ - setLoop: function (value) - { - this.loop = value; - - return this; - } - -}); - -module.exports = HTML5AudioSound; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSound = require('../BaseSound'); +var Class = require('../../utils/Class'); +var Events = require('../events'); + +/** + * @classdesc + * HTML5 Audio implementation of the sound. + * + * @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. + */ +var HTML5AudioSound = new Class({ + + Extends: BaseSound, + + initialize: + + function HTML5AudioSound (manager, key, config) + { + if (config === undefined) { config = {}; } + + /** + * An array containing all HTML5 Audio tags that could be used for individual + * sound's playback. Number of instances depends on the config value passed + * to the Loader#audio method call, default is 1. + * + * @name Phaser.Sound.HTML5AudioSound#tags + * @type {HTMLAudioElement[]} + * @private + * @since 3.0.0 + */ + this.tags = manager.game.cache.audio.get(key); + + if (!this.tags) + { + throw new Error('There is no audio asset with key "' + key + '" in the audio cache'); + } + + /** + * Reference to an HTML5 Audio tag used for playing sound. + * + * @name Phaser.Sound.HTML5AudioSound#audio + * @type {HTMLAudioElement} + * @private + * @default null + * @since 3.0.0 + */ + this.audio = null; + + /** + * Timestamp as generated by the Request Animation Frame or SetTimeout + * representing the time at which the delayed sound playback should start. + * Set to 0 if sound playback is not delayed. + * + * @name Phaser.Sound.HTML5AudioSound#startTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.startTime = 0; + + /** + * Audio tag's playback position recorded on previous + * update method call. Set to 0 if sound is not playing. + * + * @name Phaser.Sound.HTML5AudioSound#previousTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.previousTime = 0; + + this.duration = this.tags[0].duration; + + this.totalDuration = this.tags[0].duration; + + BaseSound.call(this, manager, key, config); + }, + + /** + * Play this sound, or a marked section of it. + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * + * @method Phaser.Sound.HTML5AudioSound#play + * @fires Phaser.Sound.Events#PLAY + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. + * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (markerName, config) + { + if (this.manager.isLocked(this, 'play', [ markerName, config ])) + { + return false; + } + + if (!BaseSound.prototype.play.call(this, markerName, config)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + if (!this.pickAndPlayAudioTag()) + { + return false; + } + + this.emit(Events.PLAY, this); + + return true; + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound.HTML5AudioSound#pause + * @fires Phaser.Sound.Events#PAUSE + * @since 3.0.0 + * + * @return {boolean} Whether the sound was paused successfully. + */ + pause: function () + { + if (this.manager.isLocked(this, 'pause')) + { + return false; + } + + if (this.startTime > 0) + { + return false; + } + + if (!BaseSound.prototype.pause.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = true \/\/\/ + this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); + + this.stopAndReleaseAudioTag(); + + this.emit(Events.PAUSE, this); + + return true; + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound.HTML5AudioSound#resume + * @fires Phaser.Sound.Events#RESUME + * @since 3.0.0 + * + * @return {boolean} Whether the sound was resumed successfully. + */ + resume: function () + { + if (this.manager.isLocked(this, 'resume')) + { + return false; + } + + if (this.startTime > 0) + { + return false; + } + + if (!BaseSound.prototype.resume.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + if (!this.pickAndPlayAudioTag()) + { + return false; + } + + this.emit(Events.RESUME, this); + + return true; + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound.HTML5AudioSound#stop + * @fires Phaser.Sound.Events#STOP + * @since 3.0.0 + * + * @return {boolean} Whether the sound was stopped successfully. + */ + stop: function () + { + if (this.manager.isLocked(this, 'stop')) + { + return false; + } + + if (!BaseSound.prototype.stop.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = false \/\/\/ + this.stopAndReleaseAudioTag(); + + this.emit(Events.STOP, this); + + return true; + }, + + /** + * Used internally to do what the name says. + * + * @method Phaser.Sound.HTML5AudioSound#pickAndPlayAudioTag + * @private + * @since 3.0.0 + * + * @return {boolean} Whether the sound was assigned an audio tag successfully. + */ + pickAndPlayAudioTag: function () + { + if (!this.pickAudioTag()) + { + this.reset(); + return false; + } + + var seek = this.currentConfig.seek; + var delay = this.currentConfig.delay; + var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; + + this.previousTime = offset; + this.audio.currentTime = offset; + this.applyConfig(); + + if (delay === 0) + { + this.startTime = 0; + + if (this.audio.paused) + { + this.playCatchPromise(); + } + } + else + { + this.startTime = window.performance.now() + delay * 1000; + + if (!this.audio.paused) + { + this.audio.pause(); + } + } + + this.resetConfig(); + + return true; + }, + + /** + * 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 + * @private + * @since 3.0.0 + * + * @return {boolean} Whether the sound was assigned an audio tag successfully. + */ + pickAudioTag: function () + { + if (this.audio) + { + return true; + } + + for (var i = 0; i < this.tags.length; i++) + { + var audio = this.tags[i]; + + if (audio.dataset.used === 'false') + { + audio.dataset.used = 'true'; + this.audio = audio; + return true; + } + } + + if (!this.manager.override) + { + return false; + } + + var otherSounds = []; + + this.manager.forEachActiveSound(function (sound) + { + if (sound.key === this.key && sound.audio) + { + otherSounds.push(sound); + } + }, this); + + otherSounds.sort(function (a1, a2) + { + if (a1.loop === a2.loop) + { + // sort by progress + return (a2.seek / a2.duration) - (a1.seek / a1.duration); + } + return a1.loop ? 1 : -1; + }); + + var selectedSound = otherSounds[0]; + + this.audio = selectedSound.audio; + + selectedSound.reset(); + selectedSound.audio = null; + selectedSound.startTime = 0; + selectedSound.previousTime = 0; + + return true; + }, + + /** + * Method used for playing audio tag and catching possible exceptions + * thrown from rejected Promise returned from play method call. + * + * @method Phaser.Sound.HTML5AudioSound#playCatchPromise + * @private + * @since 3.0.0 + */ + playCatchPromise: function () + { + var playPromise = this.audio.play(); + + if (playPromise) + { + // eslint-disable-next-line no-unused-vars + playPromise.catch(function (reason) + { + console.warn(reason); + }); + } + }, + + /** + * Used internally to do what the name says. + * + * @method Phaser.Sound.HTML5AudioSound#stopAndReleaseAudioTag + * @private + * @since 3.0.0 + */ + stopAndReleaseAudioTag: function () + { + this.audio.pause(); + this.audio.dataset.used = 'false'; + this.audio = null; + this.startTime = 0; + this.previousTime = 0; + }, + + /** + * Method used internally to reset sound state, usually when stopping sound + * or when hijacking audio tag from another sound. + * + * @method Phaser.Sound.HTML5AudioSound#reset + * @private + * @since 3.0.0 + */ + reset: function () + { + BaseSound.prototype.stop.call(this); + }, + + /** + * Method used internally by sound manager for pausing sound if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSoundManager#onBlur + * @private + * @since 3.0.0 + */ + onBlur: function () + { + this.isPlaying = false; + this.isPaused = true; + + this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); + + this.currentConfig.delay = Math.max(0, (this.startTime - window.performance.now()) / 1000); + + this.stopAndReleaseAudioTag(); + }, + + /** + * Method used internally by sound manager for resuming sound if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSound#onFocus + * @private + * @since 3.0.0 + */ + onFocus: function () + { + this.isPlaying = true; + this.isPaused = false; + this.pickAndPlayAudioTag(); + }, + + /** + * Update method called automatically by sound manager on every game step. + * + * @method Phaser.Sound.HTML5AudioSound#update + * @fires Phaser.Sound.Events#COMPLETE + * @fires Phaser.Sound.Events#LOOPED + * @protected + * @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 elapsed since the last frame. + */ + // eslint-disable-next-line no-unused-vars + update: function (time, delta) + { + if (!this.isPlaying) + { + return; + } + + // handling delayed playback + if (this.startTime > 0) + { + if (this.startTime < time - this.manager.audioPlayDelay) + { + this.audio.currentTime += Math.max(0, time - this.startTime) / 1000; + this.startTime = 0; + this.previousTime = this.audio.currentTime; + this.playCatchPromise(); + } + + return; + } + + // handle looping and ending + var startTime = this.currentMarker ? this.currentMarker.start : 0; + var endTime = startTime + this.duration; + var currentTime = this.audio.currentTime; + + if (this.currentConfig.loop) + { + if (currentTime >= endTime - this.manager.loopEndOffset) + { + this.audio.currentTime = startTime + Math.max(0, currentTime - endTime); + currentTime = this.audio.currentTime; + } + else if (currentTime < startTime) + { + this.audio.currentTime += startTime; + currentTime = this.audio.currentTime; + } + + if (currentTime < this.previousTime) + { + this.emit(Events.LOOPED, this); + } + } + else if (currentTime >= endTime) + { + this.reset(); + + this.stopAndReleaseAudioTag(); + + this.emit(Events.COMPLETE, this); + + return; + } + + this.previousTime = currentTime; + }, + + /** + * Calls Phaser.Sound.BaseSound#destroy method + * and cleans up all HTML5 Audio related stuff. + * + * @method Phaser.Sound.HTML5AudioSound#destroy + * @since 3.0.0 + */ + destroy: function () + { + BaseSound.prototype.destroy.call(this); + + this.tags = null; + + if (this.audio) + { + this.stopAndReleaseAudioTag(); + } + }, + + /** + * Method used internally to determine mute setting of the sound. + * + * @method Phaser.Sound.HTML5AudioSound#updateMute + * @private + * @since 3.0.0 + */ + updateMute: function () + { + if (this.audio) + { + this.audio.muted = this.currentConfig.mute || this.manager.mute; + } + }, + + /** + * Method used internally to calculate total volume of the sound. + * + * @method Phaser.Sound.HTML5AudioSound#updateVolume + * @private + * @since 3.0.0 + */ + updateVolume: function () + { + if (this.audio) + { + this.audio.volume = this.currentConfig.volume * this.manager.volume; + } + }, + + /** + * Method used internally to calculate total playback rate of the sound. + * + * @method Phaser.Sound.HTML5AudioSound#calculateRate + * @protected + * @since 3.0.0 + */ + calculateRate: function () + { + BaseSound.prototype.calculateRate.call(this); + + if (this.audio) + { + this.audio.playbackRate = this.totalRate; + } + }, + + /** + * Boolean indicating whether the sound is muted or not. + * Gets or sets the muted state of this sound. + * + * @name Phaser.Sound.HTML5AudioSound#mute + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return this.currentConfig.mute; + }, + + set: function (value) + { + this.currentConfig.mute = value; + + if (this.manager.isLocked(this, 'mute', value)) + { + return; + } + + this.updateMute(); + + this.emit(Events.MUTE, this, value); + } + }, + + /** + * Sets the muted state of this Sound. + * + * @method Phaser.Sound.HTML5AudioSound#setMute + * @fires Phaser.Sound.Events#MUTE + * @since 3.4.0 + * + * @param {boolean} value - `true` to mute this sound, `false` to unmute it. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). + * + * @name Phaser.Sound.HTML5AudioSound#volume + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this.currentConfig.volume; + }, + + set: function (value) + { + this.currentConfig.volume = value; + + if (this.manager.isLocked(this, 'volume', value)) + { + return; + } + + this.updateVolume(); + + this.emit(Events.VOLUME, this, value); + } + }, + + /** + * Sets the volume of this Sound. + * + * @method Phaser.Sound.HTML5AudioSound#setVolume + * @fires Phaser.Sound.Events#VOLUME + * @since 3.4.0 + * + * @param {number} value - The volume of the sound. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * Rate at which this Sound will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @name Phaser.Sound.HTML5AudioSound#rate + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#RATE + * @since 3.0.0 + */ + rate: { + + get: function () + { + return this.currentConfig.rate; + }, + + set: function (value) + { + this.currentConfig.rate = value; + + if (this.manager.isLocked(this, Events.RATE, value)) + { + return; + } + else + { + this.calculateRate(); + + this.emit(Events.RATE, this, value); + } + } + + }, + + /** + * Sets the playback rate of this Sound. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @method Phaser.Sound.HTML5AudioSound#setRate + * @fires Phaser.Sound.Events#RATE + * @since 3.3.0 + * + * @param {number} value - The playback rate at of this Sound. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound. + */ + setRate: function (value) + { + this.rate = value; + + return this; + }, + + /** + * 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 + */ + detune: { + + get: function () + { + return this.currentConfig.detune; + }, + + set: function (value) + { + this.currentConfig.detune = value; + + if (this.manager.isLocked(this, Events.DETUNE, value)) + { + return; + } + else + { + this.calculateRate(); + + this.emit(Events.DETUNE, this, value); + } + } + + }, + + /** + * 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 {Phaser.Sound.HTML5AudioSound} This Sound. + */ + setDetune: function (value) + { + this.detune = value; + + return this; + }, + + /** + * Property representing the position of playback for this sound, in seconds. + * Setting it to a specific value moves current playback to that position. + * The value given is clamped to the range 0 to current marker duration. + * Setting seek of a stopped sound has no effect. + * + * @name Phaser.Sound.HTML5AudioSound#seek + * @type {number} + * @fires Phaser.Sound.Events#SEEK + * @since 3.0.0 + */ + seek: { + + get: function () + { + if (this.isPlaying) + { + return this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); + } + else if (this.isPaused) + { + return this.currentConfig.seek; + } + else + { + return 0; + } + }, + + set: function (value) + { + if (this.manager.isLocked(this, 'seek', value)) + { + return; + } + + if (this.startTime > 0) + { + return; + } + + if (this.isPlaying || this.isPaused) + { + value = Math.min(Math.max(0, value), this.duration); + + if (this.isPlaying) + { + this.previousTime = value; + this.audio.currentTime = value; + } + else if (this.isPaused) + { + this.currentConfig.seek = value; + } + + this.emit(Events.SEEK, this, value); + } + } + }, + + /** + * Seeks to a specific point in this sound. + * + * @method Phaser.Sound.HTML5AudioSound#setSeek + * @fires Phaser.Sound.Events#SEEK + * @since 3.4.0 + * + * @param {number} value - The point in the sound to seek to. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setSeek: function (value) + { + this.seek = value; + + return this; + }, + + /** + * Flag indicating whether or not the sound or current sound marker will loop. + * + * @name Phaser.Sound.HTML5AudioSound#loop + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#LOOP + * @since 3.0.0 + */ + loop: { + + get: function () + { + return this.currentConfig.loop; + }, + + set: function (value) + { + this.currentConfig.loop = value; + + if (this.manager.isLocked(this, 'loop', value)) + { + return; + } + + if (this.audio) + { + this.audio.loop = value; + } + + this.emit(Events.LOOP, this, value); + } + + }, + + /** + * Sets the loop state of this Sound. + * + * @method Phaser.Sound.HTML5AudioSound#setLoop + * @fires Phaser.Sound.Events#LOOP + * @since 3.4.0 + * + * @param {boolean} value - `true` to loop this sound, `false` to not loop it. + * + * @return {Phaser.Sound.HTML5AudioSound} This Sound instance. + */ + setLoop: function (value) + { + this.loop = value; + + return this; + } + +}); + +module.exports = HTML5AudioSound; diff --git a/src/sound/html5/HTML5AudioSoundManager.js b/src/sound/html5/HTML5AudioSoundManager.js index d4735ff37..be8c0468f 100644 --- a/src/sound/html5/HTML5AudioSoundManager.js +++ b/src/sound/html5/HTML5AudioSoundManager.js @@ -1,459 +1,459 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseSoundManager = require('../BaseSoundManager'); -var Class = require('../../utils/Class'); -var Events = require('../events'); -var HTML5AudioSound = require('./HTML5AudioSound'); - -/** - * HTML5 Audio implementation of the Sound Manager. - * - * Note: 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 - * }); - * ``` - * - * @class HTML5AudioSoundManager - * @extends Phaser.Sound.BaseSoundManager - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - Reference to the current game instance. - */ -var HTML5AudioSoundManager = new Class({ - - Extends: BaseSoundManager, - - initialize: - - function HTML5AudioSoundManager (game) - { - /** - * Flag indicating whether if there are no idle instances of HTML5 Audio tag, - * for any particular sound, if one of the used tags should be hijacked and used - * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play - * call should be ignored. - * - * @name Phaser.Sound.HTML5AudioSoundManager#override - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.override = true; - - /** - * Value representing time difference, in seconds, between calling - * play method on an audio tag and when it actually starts playing. - * It is used to achieve more accurate delayed sound playback. - * - * You might need to tweak this value to get the desired results - * since audio play delay varies depending on the browser/platform. - * - * @name Phaser.Sound.HTML5AudioSoundManager#audioPlayDelay - * @type {number} - * @default 0.1 - * @since 3.0.0 - */ - this.audioPlayDelay = 0.1; - - /** - * A value by which we should offset the loop end marker of the - * looping sound to compensate for lag, caused by changing audio - * tag playback position, in order to achieve gapless looping. - * - * You might need to tweak this value to get the desired results - * since loop lag varies depending on the browser/platform. - * - * @name Phaser.Sound.HTML5AudioSoundManager#loopEndOffset - * @type {number} - * @default 0.05 - * @since 3.0.0 - */ - this.loopEndOffset = 0.05; - - /** - * An array for keeping track of all the sounds - * that were paused when game lost focus. - * - * @name Phaser.Sound.HTML5AudioSoundManager#onBlurPausedSounds - * @type {Phaser.Sound.HTML5AudioSound[]} - * @private - * @default [] - * @since 3.0.0 - */ - this.onBlurPausedSounds = []; - - this.locked = 'ontouchstart' in window; - - /** - * A queue of all actions performed on sound objects while audio was locked. - * Once the audio gets unlocked, after an explicit user interaction, - * all actions will be performed in chronological order. - * Array of object types: { sound: Phaser.Sound.HTML5AudioSound, name: string, value?: * } - * - * @name Phaser.Sound.HTML5AudioSoundManager#lockedActionsQueue - * @type {array} - * @private - * @since 3.0.0 - */ - this.lockedActionsQueue = this.locked ? [] : null; - - /** - * Property that actually holds the value of global mute - * for HTML5 Audio sound manager implementation. - * - * @name Phaser.Sound.HTML5AudioSoundManager#_mute - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this._mute = false; - - /** - * Property that actually holds the value of global volume - * for HTML5 Audio sound manager implementation. - * - * @name Phaser.Sound.HTML5AudioSoundManager#_volume - * @type {boolean} - * @private - * @default 1 - * @since 3.0.0 - */ - this._volume = 1; - - BaseSoundManager.call(this, game); - }, - - /** - * Adds a new sound into the sound manager. - * - * @method Phaser.Sound.HTML5AudioSoundManager#add - * @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.HTML5AudioSound} The new sound instance. - */ - add: function (key, config) - { - var sound = new HTML5AudioSound(this, key, config); - - this.sounds.push(sound); - - return sound; - }, - - /** - * Unlocks HTML5 Audio loading and playback on mobile - * devices on the initial explicit user interaction. - * - * @method Phaser.Sound.HTML5AudioSoundManager#unlock - * @since 3.0.0 - */ - unlock: function () - { - this.locked = false; - - var _this = this; - - this.game.cache.audio.entries.each(function (key, tags) - { - for (var i = 0; i < tags.length; i++) - { - if (tags[i].dataset.locked === 'true') - { - _this.locked = true; - - return false; - } - } - - return true; - }); - - if (!this.locked) - { - return; - } - - var moved = false; - - var detectMove = function () - { - moved = true; - }; - - var unlock = function () - { - if (moved) - { - moved = false; - return; - } - - document.body.removeEventListener('touchmove', detectMove); - document.body.removeEventListener('touchend', unlock); - - var lockedTags = []; - - _this.game.cache.audio.entries.each(function (key, tags) - { - for (var i = 0; i < tags.length; i++) - { - var tag = tags[i]; - - if (tag.dataset.locked === 'true') - { - lockedTags.push(tag); - } - } - - return true; - }); - - if (lockedTags.length === 0) - { - return; - } - - var lastTag = lockedTags[lockedTags.length - 1]; - - lastTag.oncanplaythrough = function () - { - lastTag.oncanplaythrough = null; - - lockedTags.forEach(function (tag) - { - tag.dataset.locked = 'false'; - }); - - _this.unlocked = true; - }; - - lockedTags.forEach(function (tag) - { - tag.load(); - }); - }; - - this.once(Events.UNLOCKED, function () - { - this.forEachActiveSound(function (sound) - { - if (sound.currentMarker === null && sound.duration === 0) - { - sound.duration = sound.tags[0].duration; - } - - sound.totalDuration = sound.tags[0].duration; - }); - - while (this.lockedActionsQueue.length) - { - var lockedAction = this.lockedActionsQueue.shift(); - - if (lockedAction.sound[lockedAction.prop].apply) - { - lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []); - } - else - { - lockedAction.sound[lockedAction.prop] = lockedAction.value; - } - } - - }, this); - - document.body.addEventListener('touchmove', detectMove, false); - document.body.addEventListener('touchend', unlock, false); - }, - - /** - * Method used internally for pausing sound manager if - * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.HTML5AudioSoundManager#onBlur - * @protected - * @since 3.0.0 - */ - onBlur: function () - { - this.forEachActiveSound(function (sound) - { - if (sound.isPlaying) - { - this.onBlurPausedSounds.push(sound); - sound.onBlur(); - } - }); - }, - - /** - * Method used internally for resuming sound manager if - * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.HTML5AudioSoundManager#onFocus - * @protected - * @since 3.0.0 - */ - onFocus: function () - { - this.onBlurPausedSounds.forEach(function (sound) - { - sound.onFocus(); - }); - - this.onBlurPausedSounds.length = 0; - }, - - /** - * Calls Phaser.Sound.BaseSoundManager#destroy method - * and cleans up all HTML5 Audio related stuff. - * - * @method Phaser.Sound.HTML5AudioSoundManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - BaseSoundManager.prototype.destroy.call(this); - - this.onBlurPausedSounds.length = 0; - this.onBlurPausedSounds = null; - }, - - /** - * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters - * to check if sound manager is locked and then either perform action immediately or queue it - * to be performed once the sound manager gets unlocked. - * - * @method Phaser.Sound.HTML5AudioSoundManager#isLocked - * @protected - * @since 3.0.0 - * - * @param {Phaser.Sound.HTML5AudioSound} sound - Sound object on which to perform queued action. - * @param {string} prop - Name of the method to be called or property to be assigned a value to. - * @param {*} [value] - An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property. - * - * @return {boolean} Whether the sound manager is locked. - */ - isLocked: function (sound, prop, value) - { - if (sound.tags[0].dataset.locked === 'true') - { - this.lockedActionsQueue.push({ - sound: sound, - prop: prop, - value: value - }); - - return true; - } - - return false; - }, - - /** - * Sets the muted state of all this Sound Manager. - * - * @method Phaser.Sound.HTML5AudioSoundManager#setMute - * @fires Phaser.Sound.Events#GLOBAL_MUTE - * @since 3.3.0 - * - * @param {boolean} value - `true` to mute all sounds, `false` to unmute them. - * - * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager. - */ - setMute: function (value) - { - this.mute = value; - - return this; - }, - - /** - * @name Phaser.Sound.HTML5AudioSoundManager#mute - * @type {boolean} - * @fires Phaser.Sound.Events#GLOBAL_MUTE - * @since 3.0.0 - */ - mute: { - - get: function () - { - return this._mute; - }, - - set: function (value) - { - this._mute = value; - - this.forEachActiveSound(function (sound) - { - sound.updateMute(); - }); - - this.emit(Events.GLOBAL_MUTE, this, value); - } - - }, - - /** - * Sets the volume of this Sound Manager. - * - * @method Phaser.Sound.HTML5AudioSoundManager#setVolume - * @fires Phaser.Sound.Events#GLOBAL_VOLUME - * @since 3.3.0 - * - * @param {number} value - The global volume of this Sound Manager. - * - * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager. - */ - setVolume: function (value) - { - this.volume = value; - - return this; - }, - - /** - * @name Phaser.Sound.HTML5AudioSoundManager#volume - * @type {number} - * @fires Phaser.Sound.Events#GLOBAL_VOLUME - * @since 3.0.0 - */ - volume: { - - get: function () - { - return this._volume; - }, - - set: function (value) - { - this._volume = value; - - this.forEachActiveSound(function (sound) - { - sound.updateVolume(); - }); - - this.emit(Events.GLOBAL_VOLUME, this, value); - } - - } - -}); - -module.exports = HTML5AudioSoundManager; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSoundManager = require('../BaseSoundManager'); +var Class = require('../../utils/Class'); +var Events = require('../events'); +var HTML5AudioSound = require('./HTML5AudioSound'); + +/** + * HTML5 Audio implementation of the Sound Manager. + * + * Note: 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 + * }); + * ``` + * + * @class HTML5AudioSoundManager + * @extends Phaser.Sound.BaseSoundManager + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var HTML5AudioSoundManager = new Class({ + + Extends: BaseSoundManager, + + initialize: + + function HTML5AudioSoundManager (game) + { + /** + * Flag indicating whether if there are no idle instances of HTML5 Audio tag, + * for any particular sound, if one of the used tags should be hijacked and used + * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play + * call should be ignored. + * + * @name Phaser.Sound.HTML5AudioSoundManager#override + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.override = true; + + /** + * Value representing time difference, in seconds, between calling + * play method on an audio tag and when it actually starts playing. + * It is used to achieve more accurate delayed sound playback. + * + * You might need to tweak this value to get the desired results + * since audio play delay varies depending on the browser/platform. + * + * @name Phaser.Sound.HTML5AudioSoundManager#audioPlayDelay + * @type {number} + * @default 0.1 + * @since 3.0.0 + */ + this.audioPlayDelay = 0.1; + + /** + * A value by which we should offset the loop end marker of the + * looping sound to compensate for lag, caused by changing audio + * tag playback position, in order to achieve gapless looping. + * + * You might need to tweak this value to get the desired results + * since loop lag varies depending on the browser/platform. + * + * @name Phaser.Sound.HTML5AudioSoundManager#loopEndOffset + * @type {number} + * @default 0.05 + * @since 3.0.0 + */ + this.loopEndOffset = 0.05; + + /** + * An array for keeping track of all the sounds + * that were paused when game lost focus. + * + * @name Phaser.Sound.HTML5AudioSoundManager#onBlurPausedSounds + * @type {Phaser.Sound.HTML5AudioSound[]} + * @private + * @default [] + * @since 3.0.0 + */ + this.onBlurPausedSounds = []; + + this.locked = 'ontouchstart' in window; + + /** + * A queue of all actions performed on sound objects while audio was locked. + * Once the audio gets unlocked, after an explicit user interaction, + * all actions will be performed in chronological order. + * Array of object types: { sound: Phaser.Sound.HTML5AudioSound, name: string, value?: * } + * + * @name Phaser.Sound.HTML5AudioSoundManager#lockedActionsQueue + * @type {array} + * @private + * @since 3.0.0 + */ + this.lockedActionsQueue = this.locked ? [] : null; + + /** + * Property that actually holds the value of global mute + * for HTML5 Audio sound manager implementation. + * + * @name Phaser.Sound.HTML5AudioSoundManager#_mute + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this._mute = false; + + /** + * Property that actually holds the value of global volume + * for HTML5 Audio sound manager implementation. + * + * @name Phaser.Sound.HTML5AudioSoundManager#_volume + * @type {boolean} + * @private + * @default 1 + * @since 3.0.0 + */ + this._volume = 1; + + BaseSoundManager.call(this, game); + }, + + /** + * Adds a new sound into the sound manager. + * + * @method Phaser.Sound.HTML5AudioSoundManager#add + * @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.HTML5AudioSound} The new sound instance. + */ + add: function (key, config) + { + var sound = new HTML5AudioSound(this, key, config); + + this.sounds.push(sound); + + return sound; + }, + + /** + * Unlocks HTML5 Audio loading and playback on mobile + * devices on the initial explicit user interaction. + * + * @method Phaser.Sound.HTML5AudioSoundManager#unlock + * @since 3.0.0 + */ + unlock: function () + { + this.locked = false; + + var _this = this; + + this.game.cache.audio.entries.each(function (key, tags) + { + for (var i = 0; i < tags.length; i++) + { + if (tags[i].dataset.locked === 'true') + { + _this.locked = true; + + return false; + } + } + + return true; + }); + + if (!this.locked) + { + return; + } + + var moved = false; + + var detectMove = function () + { + moved = true; + }; + + var unlock = function () + { + if (moved) + { + moved = false; + return; + } + + document.body.removeEventListener('touchmove', detectMove); + document.body.removeEventListener('touchend', unlock); + + var lockedTags = []; + + _this.game.cache.audio.entries.each(function (key, tags) + { + for (var i = 0; i < tags.length; i++) + { + var tag = tags[i]; + + if (tag.dataset.locked === 'true') + { + lockedTags.push(tag); + } + } + + return true; + }); + + if (lockedTags.length === 0) + { + return; + } + + var lastTag = lockedTags[lockedTags.length - 1]; + + lastTag.oncanplaythrough = function () + { + lastTag.oncanplaythrough = null; + + lockedTags.forEach(function (tag) + { + tag.dataset.locked = 'false'; + }); + + _this.unlocked = true; + }; + + lockedTags.forEach(function (tag) + { + tag.load(); + }); + }; + + this.once(Events.UNLOCKED, function () + { + this.forEachActiveSound(function (sound) + { + if (sound.currentMarker === null && sound.duration === 0) + { + sound.duration = sound.tags[0].duration; + } + + sound.totalDuration = sound.tags[0].duration; + }); + + while (this.lockedActionsQueue.length) + { + var lockedAction = this.lockedActionsQueue.shift(); + + if (lockedAction.sound[lockedAction.prop].apply) + { + lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []); + } + else + { + lockedAction.sound[lockedAction.prop] = lockedAction.value; + } + } + + }, this); + + document.body.addEventListener('touchmove', detectMove, false); + document.body.addEventListener('touchend', unlock, false); + }, + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSoundManager#onBlur + * @protected + * @since 3.0.0 + */ + onBlur: function () + { + this.forEachActiveSound(function (sound) + { + if (sound.isPlaying) + { + this.onBlurPausedSounds.push(sound); + sound.onBlur(); + } + }); + }, + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.HTML5AudioSoundManager#onFocus + * @protected + * @since 3.0.0 + */ + onFocus: function () + { + this.onBlurPausedSounds.forEach(function (sound) + { + sound.onFocus(); + }); + + this.onBlurPausedSounds.length = 0; + }, + + /** + * Calls Phaser.Sound.BaseSoundManager#destroy method + * and cleans up all HTML5 Audio related stuff. + * + * @method Phaser.Sound.HTML5AudioSoundManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + BaseSoundManager.prototype.destroy.call(this); + + this.onBlurPausedSounds.length = 0; + this.onBlurPausedSounds = null; + }, + + /** + * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters + * to check if sound manager is locked and then either perform action immediately or queue it + * to be performed once the sound manager gets unlocked. + * + * @method Phaser.Sound.HTML5AudioSoundManager#isLocked + * @protected + * @since 3.0.0 + * + * @param {Phaser.Sound.HTML5AudioSound} sound - Sound object on which to perform queued action. + * @param {string} prop - Name of the method to be called or property to be assigned a value to. + * @param {*} [value] - An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property. + * + * @return {boolean} Whether the sound manager is locked. + */ + isLocked: function (sound, prop, value) + { + if (sound.tags[0].dataset.locked === 'true') + { + this.lockedActionsQueue.push({ + sound: sound, + prop: prop, + value: value + }); + + return true; + } + + return false; + }, + + /** + * Sets the muted state of all this Sound Manager. + * + * @method Phaser.Sound.HTML5AudioSoundManager#setMute + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.3.0 + * + * @param {boolean} value - `true` to mute all sounds, `false` to unmute them. + * + * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * @name Phaser.Sound.HTML5AudioSoundManager#mute + * @type {boolean} + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return this._mute; + }, + + set: function (value) + { + this._mute = value; + + this.forEachActiveSound(function (sound) + { + sound.updateMute(); + }); + + this.emit(Events.GLOBAL_MUTE, this, value); + } + + }, + + /** + * Sets the volume of this Sound Manager. + * + * @method Phaser.Sound.HTML5AudioSoundManager#setVolume + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.3.0 + * + * @param {number} value - The global volume of this Sound Manager. + * + * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * @name Phaser.Sound.HTML5AudioSoundManager#volume + * @type {number} + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this._volume; + }, + + set: function (value) + { + this._volume = value; + + this.forEachActiveSound(function (sound) + { + sound.updateVolume(); + }); + + this.emit(Events.GLOBAL_VOLUME, this, value); + } + + } + +}); + +module.exports = HTML5AudioSoundManager; diff --git a/src/sound/index.js b/src/sound/index.js index 888bf7b7b..0e998766b 100644 --- a/src/sound/index.js +++ b/src/sound/index.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Sound - */ - -module.exports = { - - SoundManagerCreator: require('./SoundManagerCreator'), - - Events: require('./events'), - - BaseSound: require('./BaseSound'), - BaseSoundManager: require('./BaseSoundManager'), - - WebAudioSound: require('./webaudio/WebAudioSound'), - WebAudioSoundManager: require('./webaudio/WebAudioSoundManager'), - - HTML5AudioSound: require('./html5/HTML5AudioSound'), - HTML5AudioSoundManager: require('./html5/HTML5AudioSoundManager'), - - NoAudioSound: require('./noaudio/NoAudioSound'), - NoAudioSoundManager: require('./noaudio/NoAudioSoundManager') - -}; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Sound + */ + +module.exports = { + + SoundManagerCreator: require('./SoundManagerCreator'), + + Events: require('./events'), + + BaseSound: require('./BaseSound'), + BaseSoundManager: require('./BaseSoundManager'), + + WebAudioSound: require('./webaudio/WebAudioSound'), + WebAudioSoundManager: require('./webaudio/WebAudioSoundManager'), + + HTML5AudioSound: require('./html5/HTML5AudioSound'), + HTML5AudioSoundManager: require('./html5/HTML5AudioSoundManager'), + + NoAudioSound: require('./noaudio/NoAudioSound'), + NoAudioSoundManager: require('./noaudio/NoAudioSoundManager') + +}; diff --git a/src/sound/noaudio/NoAudioSound.js b/src/sound/noaudio/NoAudioSound.js index 5878d4019..4aefe15ad 100644 --- a/src/sound/noaudio/NoAudioSound.js +++ b/src/sound/noaudio/NoAudioSound.js @@ -1,121 +1,121 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseSound = require('../BaseSound'); -var Class = require('../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Extend = require('../../utils/object/Extend'); - -/** - * @classdesc - * No audio implementation of the sound. It is used if audio has been - * disabled in the game config or the device doesn't support any audio. - * - * It represents a graceful degradation of sound logic that provides - * minimal functionality and prevents Phaser projects that use audio from - * breaking on devices that don't support any audio playback technologies. - * - * @class NoAudioSound - * @extends Phaser.Sound.BaseSound - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Sound.NoAudioSoundManager} 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. - */ -var NoAudioSound = new Class({ - - Extends: EventEmitter, - - initialize: - - function NoAudioSound (manager, key, config) - { - if (config === void 0) { config = {}; } - - EventEmitter.call(this); - - this.manager = manager; - this.key = key; - this.isPlaying = false; - this.isPaused = false; - this.totalRate = 1; - this.duration = 0; - this.totalDuration = 0; - - this.config = Extend({ - mute: false, - volume: 1, - rate: 1, - detune: 0, - seek: 0, - loop: false, - delay: 0 - }, config); - - this.currentConfig = this.config; - this.mute = false; - this.volume = 1; - this.rate = 1; - this.detune = 0; - this.seek = 0; - this.loop = false; - this.markers = {}; - this.currentMarker = null; - this.pendingRemove = false; - }, - - // eslint-disable-next-line no-unused-vars - addMarker: function (marker) - { - return false; - }, - - // eslint-disable-next-line no-unused-vars - updateMarker: function (marker) - { - return false; - }, - - // eslint-disable-next-line no-unused-vars - removeMarker: function (markerName) - { - return null; - }, - - // eslint-disable-next-line no-unused-vars - play: function (markerName, config) - { - return false; - }, - - pause: function () - { - return false; - }, - - resume: function () - { - return false; - }, - - stop: function () - { - return false; - }, - - destroy: function () - { - this.manager.remove(this); - - BaseSound.prototype.destroy.call(this); - } -}); - -module.exports = NoAudioSound; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSound = require('../BaseSound'); +var Class = require('../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Extend = require('../../utils/object/Extend'); + +/** + * @classdesc + * No audio implementation of the sound. It is used if audio has been + * disabled in the game config or the device doesn't support any audio. + * + * It represents a graceful degradation of sound logic that provides + * minimal functionality and prevents Phaser projects that use audio from + * breaking on devices that don't support any audio playback technologies. + * + * @class NoAudioSound + * @extends Phaser.Sound.BaseSound + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Sound.NoAudioSoundManager} 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. + */ +var NoAudioSound = new Class({ + + Extends: EventEmitter, + + initialize: + + function NoAudioSound (manager, key, config) + { + if (config === void 0) { config = {}; } + + EventEmitter.call(this); + + this.manager = manager; + this.key = key; + this.isPlaying = false; + this.isPaused = false; + this.totalRate = 1; + this.duration = 0; + this.totalDuration = 0; + + this.config = Extend({ + mute: false, + volume: 1, + rate: 1, + detune: 0, + seek: 0, + loop: false, + delay: 0 + }, config); + + this.currentConfig = this.config; + this.mute = false; + this.volume = 1; + this.rate = 1; + this.detune = 0; + this.seek = 0; + this.loop = false; + this.markers = {}; + this.currentMarker = null; + this.pendingRemove = false; + }, + + // eslint-disable-next-line no-unused-vars + addMarker: function (marker) + { + return false; + }, + + // eslint-disable-next-line no-unused-vars + updateMarker: function (marker) + { + return false; + }, + + // eslint-disable-next-line no-unused-vars + removeMarker: function (markerName) + { + return null; + }, + + // eslint-disable-next-line no-unused-vars + play: function (markerName, config) + { + return false; + }, + + pause: function () + { + return false; + }, + + resume: function () + { + return false; + }, + + stop: function () + { + return false; + }, + + destroy: function () + { + this.manager.remove(this); + + BaseSound.prototype.destroy.call(this); + } +}); + +module.exports = NoAudioSound; diff --git a/src/sound/noaudio/NoAudioSoundManager.js b/src/sound/noaudio/NoAudioSoundManager.js index b8c81fb28..1cf62ad57 100644 --- a/src/sound/noaudio/NoAudioSoundManager.js +++ b/src/sound/noaudio/NoAudioSoundManager.js @@ -1,112 +1,112 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseSoundManager = require('../BaseSoundManager'); -var Class = require('../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var NoAudioSound = require('./NoAudioSound'); -var NOOP = require('../../utils/NOOP'); - -/** - * @classdesc - * No audio implementation of the sound manager. It is used if audio has been - * disabled in the game config or the device doesn't support any audio. - * - * It represents a graceful degradation of sound manager logic that provides - * minimal functionality and prevents Phaser projects that use audio from - * breaking on devices that don't support any audio playback technologies. - * - * @class NoAudioSoundManager - * @extends Phaser.Sound.BaseSoundManager - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - Reference to the current game instance. - */ -var NoAudioSoundManager = new Class({ - - Extends: EventEmitter, - - initialize: - - function NoAudioSoundManager (game) - { - EventEmitter.call(this); - - this.game = game; - this.sounds = []; - this.mute = false; - this.volume = 1; - this.rate = 1; - this.detune = 0; - this.pauseOnBlur = true; - this.locked = false; - }, - - add: function (key, config) - { - var sound = new NoAudioSound(this, key, config); - - this.sounds.push(sound); - - return sound; - }, - - addAudioSprite: function (key, config) - { - var sound = this.add(key, config); - - sound.spritemap = {}; - - return sound; - }, - - // eslint-disable-next-line no-unused-vars - play: function (key, extra) - { - return false; - }, - - // eslint-disable-next-line no-unused-vars - playAudioSprite: function (key, spriteName, config) - { - return false; - }, - - remove: function (sound) - { - return BaseSoundManager.prototype.remove.call(this, sound); - }, - - removeByKey: function (key) - { - return BaseSoundManager.prototype.removeByKey.call(this, key); - }, - - pauseAll: NOOP, - resumeAll: NOOP, - stopAll: NOOP, - update: NOOP, - setRate: NOOP, - setDetune: NOOP, - setMute: NOOP, - setVolume: NOOP, - - forEachActiveSound: function (callbackfn, scope) - { - BaseSoundManager.prototype.forEachActiveSound.call(this, callbackfn, scope); - }, - - destroy: function () - { - BaseSoundManager.prototype.destroy.call(this); - } - -}); - -module.exports = NoAudioSoundManager; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSoundManager = require('../BaseSoundManager'); +var Class = require('../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var NoAudioSound = require('./NoAudioSound'); +var NOOP = require('../../utils/NOOP'); + +/** + * @classdesc + * No audio implementation of the sound manager. It is used if audio has been + * disabled in the game config or the device doesn't support any audio. + * + * It represents a graceful degradation of sound manager logic that provides + * minimal functionality and prevents Phaser projects that use audio from + * breaking on devices that don't support any audio playback technologies. + * + * @class NoAudioSoundManager + * @extends Phaser.Sound.BaseSoundManager + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var NoAudioSoundManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function NoAudioSoundManager (game) + { + EventEmitter.call(this); + + this.game = game; + this.sounds = []; + this.mute = false; + this.volume = 1; + this.rate = 1; + this.detune = 0; + this.pauseOnBlur = true; + this.locked = false; + }, + + add: function (key, config) + { + var sound = new NoAudioSound(this, key, config); + + this.sounds.push(sound); + + return sound; + }, + + addAudioSprite: function (key, config) + { + var sound = this.add(key, config); + + sound.spritemap = {}; + + return sound; + }, + + // eslint-disable-next-line no-unused-vars + play: function (key, extra) + { + return false; + }, + + // eslint-disable-next-line no-unused-vars + playAudioSprite: function (key, spriteName, config) + { + return false; + }, + + remove: function (sound) + { + return BaseSoundManager.prototype.remove.call(this, sound); + }, + + removeByKey: function (key) + { + return BaseSoundManager.prototype.removeByKey.call(this, key); + }, + + pauseAll: NOOP, + resumeAll: NOOP, + stopAll: NOOP, + update: NOOP, + setRate: NOOP, + setDetune: NOOP, + setMute: NOOP, + setVolume: NOOP, + + forEachActiveSound: function (callbackfn, scope) + { + BaseSoundManager.prototype.forEachActiveSound.call(this, callbackfn, scope); + }, + + destroy: function () + { + BaseSoundManager.prototype.destroy.call(this); + } + +}); + +module.exports = NoAudioSoundManager; diff --git a/src/sound/typedefs/index.js b/src/sound/typedefs/index.js index f8fa08519..6dd560241 100644 --- a/src/sound/typedefs/index.js +++ b/src/sound/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Sound - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Sound + */ diff --git a/src/sound/webaudio/WebAudioSound.js b/src/sound/webaudio/WebAudioSound.js index fd8e25fdd..acb589c91 100644 --- a/src/sound/webaudio/WebAudioSound.js +++ b/src/sound/webaudio/WebAudioSound.js @@ -1,900 +1,900 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var BaseSound = require('../BaseSound'); -var Class = require('../../utils/Class'); -var Events = require('../events'); - -/** - * @classdesc - * Web Audio API implementation of the sound. - * - * @class WebAudioSound - * @extends Phaser.Sound.BaseSound - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Sound.WebAudioSoundManager} 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. - */ -var WebAudioSound = new Class({ - - Extends: BaseSound, - - initialize: - - function WebAudioSound (manager, key, config) - { - if (config === undefined) { config = {}; } - - /** - * Audio buffer containing decoded data of the audio asset to be played. - * - * @name Phaser.Sound.WebAudioSound#audioBuffer - * @type {AudioBuffer} - * @private - * @since 3.0.0 - */ - this.audioBuffer = manager.game.cache.audio.get(key); - - if (!this.audioBuffer) - { - throw new Error('There is no audio asset with key "' + key + '" in the audio cache'); - } - - /** - * A reference to an audio source node used for playing back audio from - * audio data stored in Phaser.Sound.WebAudioSound#audioBuffer. - * - * @name Phaser.Sound.WebAudioSound#source - * @type {AudioBufferSourceNode} - * @private - * @default null - * @since 3.0.0 - */ - this.source = null; - - /** - * A reference to a second audio source used for gapless looped playback. - * - * @name Phaser.Sound.WebAudioSound#loopSource - * @type {AudioBufferSourceNode} - * @private - * @default null - * @since 3.0.0 - */ - this.loopSource = null; - - /** - * Gain node responsible for controlling this sound's muting. - * - * @name Phaser.Sound.WebAudioSound#muteNode - * @type {GainNode} - * @private - * @since 3.0.0 - */ - this.muteNode = manager.context.createGain(); - - /** - * Gain node responsible for controlling this sound's volume. - * - * @name Phaser.Sound.WebAudioSound#volumeNode - * @type {GainNode} - * @private - * @since 3.0.0 - */ - this.volumeNode = manager.context.createGain(); - - /** - * The time at which the sound should have started playback from the beginning. - * Based on BaseAudioContext.currentTime value. - * - * @name Phaser.Sound.WebAudioSound#playTime - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.playTime = 0; - - /** - * The time at which the sound source should have actually started playback. - * Based on BaseAudioContext.currentTime value. - * - * @name Phaser.Sound.WebAudioSound#startTime - * @type {number} - * @private - * @default 0 - * @since 3.0.0 - */ - this.startTime = 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} - * @private - * @default 0 - * @since 3.0.0 - */ - this.loopTime = 0; - - /** - * An array where we keep track of all rate updates during playback. - * Array of object types: { time: number, rate: number } - * - * @name Phaser.Sound.WebAudioSound#rateUpdates - * @type {array} - * @private - * @default [] - * @since 3.0.0 - */ - this.rateUpdates = []; - - /** - * Used for keeping track when sound source playback has ended - * so its state can be updated accordingly. - * - * @name Phaser.Sound.WebAudioSound#hasEnded - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this.hasEnded = false; - - /** - * Used for keeping track when sound source has looped - * so its state can be updated accordingly. - * - * @name Phaser.Sound.WebAudioSound#hasLooped - * @type {boolean} - * @private - * @default false - * @since 3.0.0 - */ - this.hasLooped = false; - - this.muteNode.connect(this.volumeNode); - - this.volumeNode.connect(manager.destination); - - this.duration = this.audioBuffer.duration; - - this.totalDuration = this.audioBuffer.duration; - - BaseSound.call(this, manager, key, config); - }, - - /** - * Play this sound, or a marked section of it. - * - * It always plays the sound from the start. If you want to start playback from a specific time - * you can set 'seek' setting of the config object, provided to this call, to that value. - * - * @method Phaser.Sound.WebAudioSound#play - * @fires Phaser.Sound.Events#PLAY - * @since 3.0.0 - * - * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. - * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. - * - * @return {boolean} Whether the sound started playing successfully. - */ - play: function (markerName, config) - { - if (!BaseSound.prototype.play.call(this, markerName, config)) - { - return false; - } - - // \/\/\/ isPlaying = true, isPaused = false \/\/\/ - this.stopAndRemoveBufferSource(); - this.createAndStartBufferSource(); - - this.emit(Events.PLAY, this); - - return true; - }, - - /** - * Pauses the sound. - * - * @method Phaser.Sound.WebAudioSound#pause - * @fires Phaser.Sound.Events#PAUSE - * @since 3.0.0 - * - * @return {boolean} Whether the sound was paused successfully. - */ - pause: function () - { - if (this.manager.context.currentTime < this.startTime) - { - return false; - } - - if (!BaseSound.prototype.pause.call(this)) - { - return false; - } - - // \/\/\/ isPlaying = false, isPaused = true \/\/\/ - this.currentConfig.seek = this.getCurrentTime(); // Equivalent to setting paused time - this.stopAndRemoveBufferSource(); - - this.emit(Events.PAUSE, this); - - return true; - }, - - /** - * Resumes the sound. - * - * @method Phaser.Sound.WebAudioSound#resume - * @fires Phaser.Sound.Events#RESUME - * @since 3.0.0 - * - * @return {boolean} Whether the sound was resumed successfully. - */ - resume: function () - { - if (this.manager.context.currentTime < this.startTime) - { - return false; - } - - if (!BaseSound.prototype.resume.call(this)) - { - return false; - } - - // \/\/\/ isPlaying = true, isPaused = false \/\/\/ - this.createAndStartBufferSource(); - - this.emit(Events.RESUME, this); - - return true; - }, - - /** - * Stop playing this sound. - * - * @method Phaser.Sound.WebAudioSound#stop - * @fires Phaser.Sound.Events#STOP - * @since 3.0.0 - * - * @return {boolean} Whether the sound was stopped successfully. - */ - stop: function () - { - if (!BaseSound.prototype.stop.call(this)) - { - return false; - } - - // \/\/\/ isPlaying = false, isPaused = false \/\/\/ - this.stopAndRemoveBufferSource(); - - this.emit(Events.STOP, this); - - return true; - }, - - /** - * Used internally. - * - * @method Phaser.Sound.WebAudioSound#createAndStartBufferSource - * @private - * @since 3.0.0 - */ - createAndStartBufferSource: function () - { - var seek = this.currentConfig.seek; - var delay = this.currentConfig.delay; - var when = this.manager.context.currentTime + delay; - var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; - var duration = this.duration - seek; - - this.playTime = when - seek; - this.startTime = when; - this.source = this.createBufferSource(); - - this.applyConfig(); - - this.source.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); - - this.resetConfig(); - }, - - /** - * Used internally. - * - * @method Phaser.Sound.WebAudioSound#createAndStartLoopBufferSource - * @private - * @since 3.0.0 - */ - createAndStartLoopBufferSource: function () - { - var when = this.getLoopTime(); - var offset = this.currentMarker ? this.currentMarker.start : 0; - var duration = this.duration; - - this.loopTime = when; - this.loopSource = this.createBufferSource(); - this.loopSource.playbackRate.setValueAtTime(this.totalRate, 0); - this.loopSource.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); - }, - - /** - * Used internally. - * - * @method Phaser.Sound.WebAudioSound#createBufferSource - * @private - * @since 3.0.0 - * - * @return {AudioBufferSourceNode} - */ - createBufferSource: function () - { - var _this = this; - var source = this.manager.context.createBufferSource(); - - source.buffer = this.audioBuffer; - - source.connect(this.muteNode); - - source.onended = function (ev) - { - if (ev.target === _this.source) - { - // sound ended - if (_this.currentConfig.loop) - { - _this.hasLooped = true; - } - else - { - _this.hasEnded = true; - } - } - - // else was stopped - }; - - return source; - }, - - /** - * Used internally. - * - * @method Phaser.Sound.WebAudioSound#stopAndRemoveBufferSource - * @private - * @since 3.0.0 - */ - stopAndRemoveBufferSource: function () - { - if (this.source) - { - this.source.stop(); - this.source.disconnect(); - this.source = null; - } - - this.playTime = 0; - this.startTime = 0; - - this.stopAndRemoveLoopBufferSource(); - }, - - /** - * Used internally. - * - * @method Phaser.Sound.WebAudioSound#stopAndRemoveLoopBufferSource - * @private - * @since 3.0.0 - */ - stopAndRemoveLoopBufferSource: function () - { - if (this.loopSource) - { - this.loopSource.stop(); - this.loopSource.disconnect(); - this.loopSource = null; - } - - this.loopTime = 0; - }, - - /** - * Method used internally for applying config values to some of the sound properties. - * - * @method Phaser.Sound.WebAudioSound#applyConfig - * @protected - * @since 3.0.0 - */ - applyConfig: function () - { - this.rateUpdates.length = 0; - - this.rateUpdates.push({ - time: 0, - rate: 1 - }); - - BaseSound.prototype.applyConfig.call(this); - }, - - /** - * Update method called automatically by sound manager on every game step. - * - * @method Phaser.Sound.WebAudioSound#update - * @fires Phaser.Sound.Events#COMPLETE - * @fires Phaser.Sound.Events#LOOPED - * @protected - * @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 elapsed since the last frame. - */ - // eslint-disable-next-line no-unused-vars - update: function (time, delta) - { - if (this.hasEnded) - { - this.hasEnded = false; - - BaseSound.prototype.stop.call(this); - - this.stopAndRemoveBufferSource(); - - this.emit(Events.COMPLETE, this); - } - else if (this.hasLooped) - { - this.hasLooped = false; - this.source = this.loopSource; - this.loopSource = null; - this.playTime = this.startTime = this.loopTime; - this.rateUpdates.length = 0; - - this.rateUpdates.push({ - time: 0, - rate: this.totalRate - }); - - this.createAndStartLoopBufferSource(); - - this.emit(Events.LOOPED, this); - } - }, - - /** - * Calls Phaser.Sound.BaseSound#destroy method - * and cleans up all Web Audio API related stuff. - * - * @method Phaser.Sound.WebAudioSound#destroy - * @since 3.0.0 - */ - destroy: function () - { - BaseSound.prototype.destroy.call(this); - - this.audioBuffer = null; - this.stopAndRemoveBufferSource(); - this.muteNode.disconnect(); - this.muteNode = null; - this.volumeNode.disconnect(); - this.volumeNode = null; - this.rateUpdates.length = 0; - this.rateUpdates = null; - }, - - /** - * Method used internally to calculate total playback rate of the sound. - * - * @method Phaser.Sound.WebAudioSound#calculateRate - * @protected - * @since 3.0.0 - */ - calculateRate: function () - { - BaseSound.prototype.calculateRate.call(this); - - var now = this.manager.context.currentTime; - - if (this.source && typeof this.totalRate === 'number') - { - this.source.playbackRate.setValueAtTime(this.totalRate, now); - } - - if (this.isPlaying) - { - this.rateUpdates.push({ - time: Math.max(this.startTime, now) - this.playTime, - rate: this.totalRate - }); - - if (this.loopSource) - { - this.stopAndRemoveLoopBufferSource(); - this.createAndStartLoopBufferSource(); - } - } - }, - - /** - * Method used internally for calculating current playback time of a playing sound. - * - * @method Phaser.Sound.WebAudioSound#getCurrentTime - * @private - * @since 3.0.0 - */ - getCurrentTime: function () - { - var currentTime = 0; - - for (var i = 0; i < this.rateUpdates.length; i++) - { - var nextTime = 0; - - if (i < this.rateUpdates.length - 1) - { - nextTime = this.rateUpdates[i + 1].time; - } - else - { - nextTime = this.manager.context.currentTime - this.playTime; - } - - currentTime += (nextTime - this.rateUpdates[i].time) * this.rateUpdates[i].rate; - } - - return currentTime; - }, - - /** - * Method used internally for calculating the time - * at witch the loop source should start playing. - * - * @method Phaser.Sound.WebAudioSound#getLoopTime - * @private - * @since 3.0.0 - */ - getLoopTime: function () - { - var lastRateUpdateCurrentTime = 0; - - for (var i = 0; i < this.rateUpdates.length - 1; i++) - { - lastRateUpdateCurrentTime += (this.rateUpdates[i + 1].time - this.rateUpdates[i].time) * this.rateUpdates[i].rate; - } - - var lastRateUpdate = this.rateUpdates[this.rateUpdates.length - 1]; - - return this.playTime + lastRateUpdate.time + (this.duration - lastRateUpdateCurrentTime) / lastRateUpdate.rate; - }, - - /** - * Rate at which this Sound will be played. - * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * - * @name Phaser.Sound.WebAudioSound#rate - * @type {number} - * @default 1 - * @fires Phaser.Sound.Events#RATE - * @since 3.0.0 - */ - rate: { - - get: function () - { - return this.currentConfig.rate; - }, - - set: function (value) - { - this.currentConfig.rate = value; - - this.calculateRate(); - - this.emit(Events.RATE, this, value); - } - - }, - - /** - * Sets the playback rate of this Sound. - * - * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * - * @method Phaser.Sound.WebAudioSound#setRate - * @fires Phaser.Sound.Events#RATE - * @since 3.3.0 - * - * @param {number} value - The playback rate at of this Sound. - * - * @return {Phaser.Sound.WebAudioSound} This Sound. - */ - setRate: function (value) - { - this.rate = value; - - return this; - }, - - /** - * 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 - */ - detune: { - - get: function () - { - return this.currentConfig.detune; - }, - - set: function (value) - { - this.currentConfig.detune = value; - - this.calculateRate(); - - this.emit(Events.DETUNE, this, value); - } - - }, - - /** - * 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 {Phaser.Sound.WebAudioSound} This Sound. - */ - setDetune: function (value) - { - this.detune = value; - - return this; - }, - - /** - * Boolean indicating whether the sound is muted or not. - * Gets or sets the muted state of this sound. - * - * @name Phaser.Sound.WebAudioSound#mute - * @type {boolean} - * @default false - * @fires Phaser.Sound.Events#MUTE - * @since 3.0.0 - */ - mute: { - - get: function () - { - return (this.muteNode.gain.value === 0); - }, - - set: function (value) - { - this.currentConfig.mute = value; - this.muteNode.gain.setValueAtTime(value ? 0 : 1, 0); - - this.emit(Events.MUTE, this, value); - } - - }, - - /** - * Sets the muted state of this Sound. - * - * @method Phaser.Sound.WebAudioSound#setMute - * @fires Phaser.Sound.Events#MUTE - * @since 3.4.0 - * - * @param {boolean} value - `true` to mute this sound, `false` to unmute it. - * - * @return {Phaser.Sound.WebAudioSound} This Sound instance. - */ - setMute: function (value) - { - this.mute = value; - - return this; - }, - - /** - * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). - * - * @name Phaser.Sound.WebAudioSound#volume - * @type {number} - * @default 1 - * @fires Phaser.Sound.Events#VOLUME - * @since 3.0.0 - */ - volume: { - - get: function () - { - return this.volumeNode.gain.value; - }, - - set: function (value) - { - this.currentConfig.volume = value; - this.volumeNode.gain.setValueAtTime(value, 0); - - this.emit(Events.VOLUME, this, value); - } - }, - - /** - * Sets the volume of this Sound. - * - * @method Phaser.Sound.WebAudioSound#setVolume - * @fires Phaser.Sound.Events#VOLUME - * @since 3.4.0 - * - * @param {number} value - The volume of the sound. - * - * @return {Phaser.Sound.WebAudioSound} This Sound instance. - */ - setVolume: function (value) - { - this.volume = value; - - return this; - }, - - /** - * Property representing the position of playback for this sound, in seconds. - * Setting it to a specific value moves current playback to that position. - * The value given is clamped to the range 0 to current marker duration. - * Setting seek of a stopped sound has no effect. - * - * @name Phaser.Sound.WebAudioSound#seek - * @type {number} - * @fires Phaser.Sound.Events#SEEK - * @since 3.0.0 - */ - seek: { - - get: function () - { - if (this.isPlaying) - { - if (this.manager.context.currentTime < this.startTime) - { - return this.startTime - this.playTime; - } - - return this.getCurrentTime(); - } - else if (this.isPaused) - { - return this.currentConfig.seek; - } - else - { - return 0; - } - }, - - set: function (value) - { - if (this.manager.context.currentTime < this.startTime) - { - return; - } - - if (this.isPlaying || this.isPaused) - { - value = Math.min(Math.max(0, value), this.duration); - - this.currentConfig.seek = value; - - if (this.isPlaying) - { - this.stopAndRemoveBufferSource(); - this.createAndStartBufferSource(); - } - - this.emit(Events.SEEK, this, value); - } - } - }, - - /** - * Seeks to a specific point in this sound. - * - * @method Phaser.Sound.WebAudioSound#setSeek - * @fires Phaser.Sound.Events#SEEK - * @since 3.4.0 - * - * @param {number} value - The point in the sound to seek to. - * - * @return {Phaser.Sound.WebAudioSound} This Sound instance. - */ - setSeek: function (value) - { - this.seek = value; - - return this; - }, - - /** - * Flag indicating whether or not the sound or current sound marker will loop. - * - * @name Phaser.Sound.WebAudioSound#loop - * @type {boolean} - * @default false - * @fires Phaser.Sound.Events#LOOP - * @since 3.0.0 - */ - loop: { - - get: function () - { - return this.currentConfig.loop; - }, - - set: function (value) - { - this.currentConfig.loop = value; - - if (this.isPlaying) - { - this.stopAndRemoveLoopBufferSource(); - - if (value) - { - this.createAndStartLoopBufferSource(); - } - } - - this.emit(Events.LOOP, this, value); - } - }, - - /** - * Sets the loop state of this Sound. - * - * @method Phaser.Sound.WebAudioSound#setLoop - * @fires Phaser.Sound.Events#LOOP - * @since 3.4.0 - * - * @param {boolean} value - `true` to loop this sound, `false` to not loop it. - * - * @return {Phaser.Sound.WebAudioSound} This Sound instance. - */ - setLoop: function (value) - { - this.loop = value; - - return this; - } - -}); - -module.exports = WebAudioSound; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var BaseSound = require('../BaseSound'); +var Class = require('../../utils/Class'); +var Events = require('../events'); + +/** + * @classdesc + * Web Audio API implementation of the sound. + * + * @class WebAudioSound + * @extends Phaser.Sound.BaseSound + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Sound.WebAudioSoundManager} 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. + */ +var WebAudioSound = new Class({ + + Extends: BaseSound, + + initialize: + + function WebAudioSound (manager, key, config) + { + if (config === undefined) { config = {}; } + + /** + * Audio buffer containing decoded data of the audio asset to be played. + * + * @name Phaser.Sound.WebAudioSound#audioBuffer + * @type {AudioBuffer} + * @private + * @since 3.0.0 + */ + this.audioBuffer = manager.game.cache.audio.get(key); + + if (!this.audioBuffer) + { + throw new Error('There is no audio asset with key "' + key + '" in the audio cache'); + } + + /** + * A reference to an audio source node used for playing back audio from + * audio data stored in Phaser.Sound.WebAudioSound#audioBuffer. + * + * @name Phaser.Sound.WebAudioSound#source + * @type {AudioBufferSourceNode} + * @private + * @default null + * @since 3.0.0 + */ + this.source = null; + + /** + * A reference to a second audio source used for gapless looped playback. + * + * @name Phaser.Sound.WebAudioSound#loopSource + * @type {AudioBufferSourceNode} + * @private + * @default null + * @since 3.0.0 + */ + this.loopSource = null; + + /** + * Gain node responsible for controlling this sound's muting. + * + * @name Phaser.Sound.WebAudioSound#muteNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.muteNode = manager.context.createGain(); + + /** + * Gain node responsible for controlling this sound's volume. + * + * @name Phaser.Sound.WebAudioSound#volumeNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.volumeNode = manager.context.createGain(); + + /** + * The time at which the sound should have started playback from the beginning. + * Based on BaseAudioContext.currentTime value. + * + * @name Phaser.Sound.WebAudioSound#playTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.playTime = 0; + + /** + * The time at which the sound source should have actually started playback. + * Based on BaseAudioContext.currentTime value. + * + * @name Phaser.Sound.WebAudioSound#startTime + * @type {number} + * @private + * @default 0 + * @since 3.0.0 + */ + this.startTime = 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} + * @private + * @default 0 + * @since 3.0.0 + */ + this.loopTime = 0; + + /** + * An array where we keep track of all rate updates during playback. + * Array of object types: { time: number, rate: number } + * + * @name Phaser.Sound.WebAudioSound#rateUpdates + * @type {array} + * @private + * @default [] + * @since 3.0.0 + */ + this.rateUpdates = []; + + /** + * Used for keeping track when sound source playback has ended + * so its state can be updated accordingly. + * + * @name Phaser.Sound.WebAudioSound#hasEnded + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this.hasEnded = false; + + /** + * Used for keeping track when sound source has looped + * so its state can be updated accordingly. + * + * @name Phaser.Sound.WebAudioSound#hasLooped + * @type {boolean} + * @private + * @default false + * @since 3.0.0 + */ + this.hasLooped = false; + + this.muteNode.connect(this.volumeNode); + + this.volumeNode.connect(manager.destination); + + this.duration = this.audioBuffer.duration; + + this.totalDuration = this.audioBuffer.duration; + + BaseSound.call(this, manager, key, config); + }, + + /** + * Play this sound, or a marked section of it. + * + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * + * @method Phaser.Sound.WebAudioSound#play + * @fires Phaser.Sound.Events#PLAY + * @since 3.0.0 + * + * @param {(string|Phaser.Types.Sound.SoundConfig)} [markerName=''] - If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. + * @param {Phaser.Types.Sound.SoundConfig} [config] - Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + * + * @return {boolean} Whether the sound started playing successfully. + */ + play: function (markerName, config) + { + if (!BaseSound.prototype.play.call(this, markerName, config)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + this.stopAndRemoveBufferSource(); + this.createAndStartBufferSource(); + + this.emit(Events.PLAY, this); + + return true; + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound.WebAudioSound#pause + * @fires Phaser.Sound.Events#PAUSE + * @since 3.0.0 + * + * @return {boolean} Whether the sound was paused successfully. + */ + pause: function () + { + if (this.manager.context.currentTime < this.startTime) + { + return false; + } + + if (!BaseSound.prototype.pause.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = true \/\/\/ + this.currentConfig.seek = this.getCurrentTime(); // Equivalent to setting paused time + this.stopAndRemoveBufferSource(); + + this.emit(Events.PAUSE, this); + + return true; + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound.WebAudioSound#resume + * @fires Phaser.Sound.Events#RESUME + * @since 3.0.0 + * + * @return {boolean} Whether the sound was resumed successfully. + */ + resume: function () + { + if (this.manager.context.currentTime < this.startTime) + { + return false; + } + + if (!BaseSound.prototype.resume.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = true, isPaused = false \/\/\/ + this.createAndStartBufferSource(); + + this.emit(Events.RESUME, this); + + return true; + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound.WebAudioSound#stop + * @fires Phaser.Sound.Events#STOP + * @since 3.0.0 + * + * @return {boolean} Whether the sound was stopped successfully. + */ + stop: function () + { + if (!BaseSound.prototype.stop.call(this)) + { + return false; + } + + // \/\/\/ isPlaying = false, isPaused = false \/\/\/ + this.stopAndRemoveBufferSource(); + + this.emit(Events.STOP, this); + + return true; + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#createAndStartBufferSource + * @private + * @since 3.0.0 + */ + createAndStartBufferSource: function () + { + var seek = this.currentConfig.seek; + var delay = this.currentConfig.delay; + var when = this.manager.context.currentTime + delay; + var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; + var duration = this.duration - seek; + + this.playTime = when - seek; + this.startTime = when; + this.source = this.createBufferSource(); + + this.applyConfig(); + + this.source.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); + + this.resetConfig(); + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#createAndStartLoopBufferSource + * @private + * @since 3.0.0 + */ + createAndStartLoopBufferSource: function () + { + var when = this.getLoopTime(); + var offset = this.currentMarker ? this.currentMarker.start : 0; + var duration = this.duration; + + this.loopTime = when; + this.loopSource = this.createBufferSource(); + this.loopSource.playbackRate.setValueAtTime(this.totalRate, 0); + this.loopSource.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#createBufferSource + * @private + * @since 3.0.0 + * + * @return {AudioBufferSourceNode} + */ + createBufferSource: function () + { + var _this = this; + var source = this.manager.context.createBufferSource(); + + source.buffer = this.audioBuffer; + + source.connect(this.muteNode); + + source.onended = function (ev) + { + if (ev.target === _this.source) + { + // sound ended + if (_this.currentConfig.loop) + { + _this.hasLooped = true; + } + else + { + _this.hasEnded = true; + } + } + + // else was stopped + }; + + return source; + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#stopAndRemoveBufferSource + * @private + * @since 3.0.0 + */ + stopAndRemoveBufferSource: function () + { + if (this.source) + { + this.source.stop(); + this.source.disconnect(); + this.source = null; + } + + this.playTime = 0; + this.startTime = 0; + + this.stopAndRemoveLoopBufferSource(); + }, + + /** + * Used internally. + * + * @method Phaser.Sound.WebAudioSound#stopAndRemoveLoopBufferSource + * @private + * @since 3.0.0 + */ + stopAndRemoveLoopBufferSource: function () + { + if (this.loopSource) + { + this.loopSource.stop(); + this.loopSource.disconnect(); + this.loopSource = null; + } + + this.loopTime = 0; + }, + + /** + * Method used internally for applying config values to some of the sound properties. + * + * @method Phaser.Sound.WebAudioSound#applyConfig + * @protected + * @since 3.0.0 + */ + applyConfig: function () + { + this.rateUpdates.length = 0; + + this.rateUpdates.push({ + time: 0, + rate: 1 + }); + + BaseSound.prototype.applyConfig.call(this); + }, + + /** + * Update method called automatically by sound manager on every game step. + * + * @method Phaser.Sound.WebAudioSound#update + * @fires Phaser.Sound.Events#COMPLETE + * @fires Phaser.Sound.Events#LOOPED + * @protected + * @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 elapsed since the last frame. + */ + // eslint-disable-next-line no-unused-vars + update: function (time, delta) + { + if (this.hasEnded) + { + this.hasEnded = false; + + BaseSound.prototype.stop.call(this); + + this.stopAndRemoveBufferSource(); + + this.emit(Events.COMPLETE, this); + } + else if (this.hasLooped) + { + this.hasLooped = false; + this.source = this.loopSource; + this.loopSource = null; + this.playTime = this.startTime = this.loopTime; + this.rateUpdates.length = 0; + + this.rateUpdates.push({ + time: 0, + rate: this.totalRate + }); + + this.createAndStartLoopBufferSource(); + + this.emit(Events.LOOPED, this); + } + }, + + /** + * Calls Phaser.Sound.BaseSound#destroy method + * and cleans up all Web Audio API related stuff. + * + * @method Phaser.Sound.WebAudioSound#destroy + * @since 3.0.0 + */ + destroy: function () + { + BaseSound.prototype.destroy.call(this); + + this.audioBuffer = null; + this.stopAndRemoveBufferSource(); + this.muteNode.disconnect(); + this.muteNode = null; + this.volumeNode.disconnect(); + this.volumeNode = null; + this.rateUpdates.length = 0; + this.rateUpdates = null; + }, + + /** + * Method used internally to calculate total playback rate of the sound. + * + * @method Phaser.Sound.WebAudioSound#calculateRate + * @protected + * @since 3.0.0 + */ + calculateRate: function () + { + BaseSound.prototype.calculateRate.call(this); + + var now = this.manager.context.currentTime; + + if (this.source && typeof this.totalRate === 'number') + { + this.source.playbackRate.setValueAtTime(this.totalRate, now); + } + + if (this.isPlaying) + { + this.rateUpdates.push({ + time: Math.max(this.startTime, now) - this.playTime, + rate: this.totalRate + }); + + if (this.loopSource) + { + this.stopAndRemoveLoopBufferSource(); + this.createAndStartLoopBufferSource(); + } + } + }, + + /** + * Method used internally for calculating current playback time of a playing sound. + * + * @method Phaser.Sound.WebAudioSound#getCurrentTime + * @private + * @since 3.0.0 + */ + getCurrentTime: function () + { + var currentTime = 0; + + for (var i = 0; i < this.rateUpdates.length; i++) + { + var nextTime = 0; + + if (i < this.rateUpdates.length - 1) + { + nextTime = this.rateUpdates[i + 1].time; + } + else + { + nextTime = this.manager.context.currentTime - this.playTime; + } + + currentTime += (nextTime - this.rateUpdates[i].time) * this.rateUpdates[i].rate; + } + + return currentTime; + }, + + /** + * Method used internally for calculating the time + * at witch the loop source should start playing. + * + * @method Phaser.Sound.WebAudioSound#getLoopTime + * @private + * @since 3.0.0 + */ + getLoopTime: function () + { + var lastRateUpdateCurrentTime = 0; + + for (var i = 0; i < this.rateUpdates.length - 1; i++) + { + lastRateUpdateCurrentTime += (this.rateUpdates[i + 1].time - this.rateUpdates[i].time) * this.rateUpdates[i].rate; + } + + var lastRateUpdate = this.rateUpdates[this.rateUpdates.length - 1]; + + return this.playTime + lastRateUpdate.time + (this.duration - lastRateUpdateCurrentTime) / lastRateUpdate.rate; + }, + + /** + * Rate at which this Sound will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @name Phaser.Sound.WebAudioSound#rate + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#RATE + * @since 3.0.0 + */ + rate: { + + get: function () + { + return this.currentConfig.rate; + }, + + set: function (value) + { + this.currentConfig.rate = value; + + this.calculateRate(); + + this.emit(Events.RATE, this, value); + } + + }, + + /** + * Sets the playback rate of this Sound. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * + * @method Phaser.Sound.WebAudioSound#setRate + * @fires Phaser.Sound.Events#RATE + * @since 3.3.0 + * + * @param {number} value - The playback rate at of this Sound. + * + * @return {Phaser.Sound.WebAudioSound} This Sound. + */ + setRate: function (value) + { + this.rate = value; + + return this; + }, + + /** + * 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 + */ + detune: { + + get: function () + { + return this.currentConfig.detune; + }, + + set: function (value) + { + this.currentConfig.detune = value; + + this.calculateRate(); + + this.emit(Events.DETUNE, this, value); + } + + }, + + /** + * 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 {Phaser.Sound.WebAudioSound} This Sound. + */ + setDetune: function (value) + { + this.detune = value; + + return this; + }, + + /** + * Boolean indicating whether the sound is muted or not. + * Gets or sets the muted state of this sound. + * + * @name Phaser.Sound.WebAudioSound#mute + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return (this.muteNode.gain.value === 0); + }, + + set: function (value) + { + this.currentConfig.mute = value; + this.muteNode.gain.setValueAtTime(value ? 0 : 1, 0); + + this.emit(Events.MUTE, this, value); + } + + }, + + /** + * Sets the muted state of this Sound. + * + * @method Phaser.Sound.WebAudioSound#setMute + * @fires Phaser.Sound.Events#MUTE + * @since 3.4.0 + * + * @param {boolean} value - `true` to mute this sound, `false` to unmute it. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). + * + * @name Phaser.Sound.WebAudioSound#volume + * @type {number} + * @default 1 + * @fires Phaser.Sound.Events#VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this.volumeNode.gain.value; + }, + + set: function (value) + { + this.currentConfig.volume = value; + this.volumeNode.gain.setValueAtTime(value, 0); + + this.emit(Events.VOLUME, this, value); + } + }, + + /** + * Sets the volume of this Sound. + * + * @method Phaser.Sound.WebAudioSound#setVolume + * @fires Phaser.Sound.Events#VOLUME + * @since 3.4.0 + * + * @param {number} value - The volume of the sound. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * Property representing the position of playback for this sound, in seconds. + * Setting it to a specific value moves current playback to that position. + * The value given is clamped to the range 0 to current marker duration. + * Setting seek of a stopped sound has no effect. + * + * @name Phaser.Sound.WebAudioSound#seek + * @type {number} + * @fires Phaser.Sound.Events#SEEK + * @since 3.0.0 + */ + seek: { + + get: function () + { + if (this.isPlaying) + { + if (this.manager.context.currentTime < this.startTime) + { + return this.startTime - this.playTime; + } + + return this.getCurrentTime(); + } + else if (this.isPaused) + { + return this.currentConfig.seek; + } + else + { + return 0; + } + }, + + set: function (value) + { + if (this.manager.context.currentTime < this.startTime) + { + return; + } + + if (this.isPlaying || this.isPaused) + { + value = Math.min(Math.max(0, value), this.duration); + + this.currentConfig.seek = value; + + if (this.isPlaying) + { + this.stopAndRemoveBufferSource(); + this.createAndStartBufferSource(); + } + + this.emit(Events.SEEK, this, value); + } + } + }, + + /** + * Seeks to a specific point in this sound. + * + * @method Phaser.Sound.WebAudioSound#setSeek + * @fires Phaser.Sound.Events#SEEK + * @since 3.4.0 + * + * @param {number} value - The point in the sound to seek to. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setSeek: function (value) + { + this.seek = value; + + return this; + }, + + /** + * Flag indicating whether or not the sound or current sound marker will loop. + * + * @name Phaser.Sound.WebAudioSound#loop + * @type {boolean} + * @default false + * @fires Phaser.Sound.Events#LOOP + * @since 3.0.0 + */ + loop: { + + get: function () + { + return this.currentConfig.loop; + }, + + set: function (value) + { + this.currentConfig.loop = value; + + if (this.isPlaying) + { + this.stopAndRemoveLoopBufferSource(); + + if (value) + { + this.createAndStartLoopBufferSource(); + } + } + + this.emit(Events.LOOP, this, value); + } + }, + + /** + * Sets the loop state of this Sound. + * + * @method Phaser.Sound.WebAudioSound#setLoop + * @fires Phaser.Sound.Events#LOOP + * @since 3.4.0 + * + * @param {boolean} value - `true` to loop this sound, `false` to not loop it. + * + * @return {Phaser.Sound.WebAudioSound} This Sound instance. + */ + setLoop: function (value) + { + this.loop = value; + + return this; + } + +}); + +module.exports = WebAudioSound; diff --git a/src/sound/webaudio/WebAudioSoundManager.js b/src/sound/webaudio/WebAudioSoundManager.js index a17471c7a..829eee5ee 100644 --- a/src/sound/webaudio/WebAudioSoundManager.js +++ b/src/sound/webaudio/WebAudioSoundManager.js @@ -1,453 +1,453 @@ -/** - * @author Richard Davey - * @author Pavle Goloskokovic (http://prunegames.com) - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Base64ToArrayBuffer = require('../../utils/base64/Base64ToArrayBuffer'); -var BaseSoundManager = require('../BaseSoundManager'); -var Class = require('../../utils/Class'); -var Events = require('../events'); -var WebAudioSound = require('./WebAudioSound'); - -/** - * @classdesc - * Web Audio API implementation of the sound manager. - * - * @class WebAudioSoundManager - * @extends Phaser.Sound.BaseSoundManager - * @memberof Phaser.Sound - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - Reference to the current game instance. - */ -var WebAudioSoundManager = new Class({ - - Extends: BaseSoundManager, - - initialize: - - function WebAudioSoundManager (game) - { - /** - * The AudioContext being used for playback. - * - * @name Phaser.Sound.WebAudioSoundManager#context - * @type {AudioContext} - * @private - * @since 3.0.0 - */ - this.context = this.createAudioContext(game); - - /** - * Gain node responsible for controlling global muting. - * - * @name Phaser.Sound.WebAudioSoundManager#masterMuteNode - * @type {GainNode} - * @private - * @since 3.0.0 - */ - this.masterMuteNode = this.context.createGain(); - - /** - * Gain node responsible for controlling global volume. - * - * @name Phaser.Sound.WebAudioSoundManager#masterVolumeNode - * @type {GainNode} - * @private - * @since 3.0.0 - */ - this.masterVolumeNode = this.context.createGain(); - - this.masterMuteNode.connect(this.masterVolumeNode); - - this.masterVolumeNode.connect(this.context.destination); - - /** - * Destination node for connecting individual sounds to. - * - * @name Phaser.Sound.WebAudioSoundManager#destination - * @type {AudioNode} - * @private - * @since 3.0.0 - */ - this.destination = this.masterMuteNode; - - this.locked = this.context.state === 'suspended' && ('ontouchstart' in window || 'onclick' in window); - - BaseSoundManager.call(this, game); - - if (this.locked) - { - this.unlock(); - } - }, - - /** - * Method responsible for instantiating and returning AudioContext instance. - * If an instance of an AudioContext class was provided through the game config, - * that instance will be returned instead. This can come in handy if you are reloading - * a Phaser game on a page that never properly refreshes (such as in an SPA project) - * and you want to reuse already instantiated AudioContext. - * - * @method Phaser.Sound.WebAudioSoundManager#createAudioContext - * @private - * @since 3.0.0 - * - * @param {Phaser.Game} game - Reference to the current game instance. - * - * @return {AudioContext} The AudioContext instance to be used for playback. - */ - createAudioContext: function (game) - { - var audioConfig = game.config.audio; - - if (audioConfig && audioConfig.context) - { - audioConfig.context.resume(); - - return audioConfig.context; - } - - return new AudioContext(); - }, - - /** - * This method takes a new AudioContext reference and then sets - * this Sound Manager to use that context for all playback. - * - * As part of this call it also disconnects the master mute and volume - * nodes and then re-creates them on the new given context. - * - * @method Phaser.Sound.WebAudioSoundManager#setAudioContext - * @since 3.21.0 - * - * @param {AudioContext} context - Reference to an already created AudioContext instance. - * - * @return {this} The WebAudioSoundManager instance. - */ - setAudioContext: function (context) - { - if (this.context) - { - this.context.close(); - } - - if (this.masterMuteNode) - { - this.masterMuteNode.disconnect(); - } - - if (this.masterVolumeNode) - { - this.masterVolumeNode.disconnect(); - } - - this.context = context; - - this.masterMuteNode = context.createGain(); - this.masterVolumeNode = context.createGain(); - - this.masterMuteNode.connect(this.masterVolumeNode); - this.masterVolumeNode.connect(context.destination); - - this.destination = this.masterMuteNode; - - return this; - }, - - /** - * Adds a new sound into the sound manager. - * - * @method Phaser.Sound.WebAudioSoundManager#add - * @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.WebAudioSound} The new sound instance. - */ - add: function (key, config) - { - var sound = new WebAudioSound(this, key, config); - - this.sounds.push(sound); - - return sound; - }, - - /** - * Decode audio data into a format ready for playback via Web Audio. - * - * The audio data can be a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. - * - * The `audioKey` is the key that will be used to save the decoded audio to the audio cache. - * - * Instead of passing a single entry you can instead pass an array of `Phaser.Types.Sound.DecodeAudioConfig` - * objects as the first and only argument. - * - * Decoding is an async process, so be sure to listen for the events to know when decoding has completed. - * - * Once the audio has decoded it can be added to the Sound Manager or played via its key. - * - * @method Phaser.Sound.WebAudioSoundManager#decodeAudio - * @fires Phaser.Sound.Events#DECODED - * @fires Phaser.Sound.Events#DECODED_ALL - * @since 3.18.0 - * - * @param {(Phaser.Types.Sound.DecodeAudioConfig[]|string)} [audioKey] - The string-based key to be used to reference the decoded audio in the audio cache, or an array of audio config objects. - * @param {(ArrayBuffer|string)} [audioData] - The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. - */ - decodeAudio: function (audioKey, audioData) - { - var audioFiles; - - if (!Array.isArray(audioKey)) - { - audioFiles = [ { key: audioKey, data: audioData } ]; - } - else - { - audioFiles = audioKey; - } - - var cache = this.game.cache.audio; - var remaining = audioFiles.length; - - for (var i = 0; i < audioFiles.length; i++) - { - var entry = audioFiles[i]; - - var key = entry.key; - var data = entry.data; - - if (typeof data === 'string') - { - data = Base64ToArrayBuffer(data); - } - - var success = function (key, audioBuffer) - { - cache.add(key, audioBuffer); - - this.emit(Events.DECODED, key); - - remaining--; - - if (remaining === 0) - { - this.emit(Events.DECODED_ALL); - } - }.bind(this, key); - - var failure = function (key, error) - { - // eslint-disable-next-line no-console - console.error('Error decoding audio: ' + key + ' - ', error ? error.message : ''); - - remaining--; - - if (remaining === 0) - { - this.emit(Events.DECODED_ALL); - } - }.bind(this, key); - - this.context.decodeAudioData(data, success, failure); - } - }, - - /** - * 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 - */ - unlock: function () - { - var _this = this; - - var body = document.body; - - var unlockHandler = function unlockHandler () - { - if (_this.context) - { - _this.context.resume().then(function () - { - body.removeEventListener('touchstart', unlockHandler); - body.removeEventListener('touchend', unlockHandler); - body.removeEventListener('click', unlockHandler); - body.removeEventListener('keydown', unlockHandler); - - _this.unlocked = true; - }, function () - { - body.removeEventListener('touchstart', unlockHandler); - body.removeEventListener('touchend', unlockHandler); - body.removeEventListener('click', unlockHandler); - body.removeEventListener('keydown', unlockHandler); - }); - } - }; - - if (body) - { - body.addEventListener('touchstart', unlockHandler, false); - body.addEventListener('touchend', unlockHandler, false); - body.addEventListener('click', unlockHandler, false); - body.addEventListener('keydown', unlockHandler, false); - } - }, - - /** - * Method used internally for pausing sound manager if - * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.WebAudioSoundManager#onBlur - * @protected - * @since 3.0.0 - */ - onBlur: function () - { - if (!this.locked) - { - this.context.suspend(); - } - }, - - /** - * Method used internally for resuming sound manager if - * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. - * - * @method Phaser.Sound.WebAudioSoundManager#onFocus - * @protected - * @since 3.0.0 - */ - onFocus: function () - { - if (!this.locked) - { - this.context.resume(); - } - }, - - /** - * Calls Phaser.Sound.BaseSoundManager#destroy method - * and cleans up all Web Audio API related stuff. - * - * @method Phaser.Sound.WebAudioSoundManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.destination = null; - this.masterVolumeNode.disconnect(); - this.masterVolumeNode = null; - this.masterMuteNode.disconnect(); - this.masterMuteNode = null; - - if (this.game.config.audio && this.game.config.audio.context) - { - this.context.suspend(); - } - else - { - var _this = this; - - this.context.close().then(function () - { - _this.context = null; - }); - } - - BaseSoundManager.prototype.destroy.call(this); - }, - - /** - * Sets the muted state of all this Sound Manager. - * - * @method Phaser.Sound.WebAudioSoundManager#setMute - * @fires Phaser.Sound.Events#GLOBAL_MUTE - * @since 3.3.0 - * - * @param {boolean} value - `true` to mute all sounds, `false` to unmute them. - * - * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager. - */ - setMute: function (value) - { - this.mute = value; - - return this; - }, - - /** - * @name Phaser.Sound.WebAudioSoundManager#mute - * @type {boolean} - * @fires Phaser.Sound.Events#GLOBAL_MUTE - * @since 3.0.0 - */ - mute: { - - get: function () - { - return (this.masterMuteNode.gain.value === 0); - }, - - set: function (value) - { - this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0); - - this.emit(Events.GLOBAL_MUTE, this, value); - } - - }, - - /** - * Sets the volume of this Sound Manager. - * - * @method Phaser.Sound.WebAudioSoundManager#setVolume - * @fires Phaser.Sound.Events#GLOBAL_VOLUME - * @since 3.3.0 - * - * @param {number} value - The global volume of this Sound Manager. - * - * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager. - */ - setVolume: function (value) - { - this.volume = value; - - return this; - }, - - /** - * @name Phaser.Sound.WebAudioSoundManager#volume - * @type {number} - * @fires Phaser.Sound.Events#GLOBAL_VOLUME - * @since 3.0.0 - */ - volume: { - - get: function () - { - return this.masterVolumeNode.gain.value; - }, - - set: function (value) - { - this.masterVolumeNode.gain.setValueAtTime(value, 0); - - this.emit(Events.GLOBAL_VOLUME, this, value); - } - - } - -}); - -module.exports = WebAudioSoundManager; +/** + * @author Richard Davey + * @author Pavle Goloskokovic (http://prunegames.com) + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Base64ToArrayBuffer = require('../../utils/base64/Base64ToArrayBuffer'); +var BaseSoundManager = require('../BaseSoundManager'); +var Class = require('../../utils/Class'); +var Events = require('../events'); +var WebAudioSound = require('./WebAudioSound'); + +/** + * @classdesc + * Web Audio API implementation of the sound manager. + * + * @class WebAudioSoundManager + * @extends Phaser.Sound.BaseSoundManager + * @memberof Phaser.Sound + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + */ +var WebAudioSoundManager = new Class({ + + Extends: BaseSoundManager, + + initialize: + + function WebAudioSoundManager (game) + { + /** + * The AudioContext being used for playback. + * + * @name Phaser.Sound.WebAudioSoundManager#context + * @type {AudioContext} + * @private + * @since 3.0.0 + */ + this.context = this.createAudioContext(game); + + /** + * Gain node responsible for controlling global muting. + * + * @name Phaser.Sound.WebAudioSoundManager#masterMuteNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.masterMuteNode = this.context.createGain(); + + /** + * Gain node responsible for controlling global volume. + * + * @name Phaser.Sound.WebAudioSoundManager#masterVolumeNode + * @type {GainNode} + * @private + * @since 3.0.0 + */ + this.masterVolumeNode = this.context.createGain(); + + this.masterMuteNode.connect(this.masterVolumeNode); + + this.masterVolumeNode.connect(this.context.destination); + + /** + * Destination node for connecting individual sounds to. + * + * @name Phaser.Sound.WebAudioSoundManager#destination + * @type {AudioNode} + * @private + * @since 3.0.0 + */ + this.destination = this.masterMuteNode; + + this.locked = this.context.state === 'suspended' && ('ontouchstart' in window || 'onclick' in window); + + BaseSoundManager.call(this, game); + + if (this.locked) + { + this.unlock(); + } + }, + + /** + * Method responsible for instantiating and returning AudioContext instance. + * If an instance of an AudioContext class was provided through the game config, + * that instance will be returned instead. This can come in handy if you are reloading + * a Phaser game on a page that never properly refreshes (such as in an SPA project) + * and you want to reuse already instantiated AudioContext. + * + * @method Phaser.Sound.WebAudioSoundManager#createAudioContext + * @private + * @since 3.0.0 + * + * @param {Phaser.Game} game - Reference to the current game instance. + * + * @return {AudioContext} The AudioContext instance to be used for playback. + */ + createAudioContext: function (game) + { + var audioConfig = game.config.audio; + + if (audioConfig && audioConfig.context) + { + audioConfig.context.resume(); + + return audioConfig.context; + } + + return new AudioContext(); + }, + + /** + * This method takes a new AudioContext reference and then sets + * this Sound Manager to use that context for all playback. + * + * As part of this call it also disconnects the master mute and volume + * nodes and then re-creates them on the new given context. + * + * @method Phaser.Sound.WebAudioSoundManager#setAudioContext + * @since 3.21.0 + * + * @param {AudioContext} context - Reference to an already created AudioContext instance. + * + * @return {this} The WebAudioSoundManager instance. + */ + setAudioContext: function (context) + { + if (this.context) + { + this.context.close(); + } + + if (this.masterMuteNode) + { + this.masterMuteNode.disconnect(); + } + + if (this.masterVolumeNode) + { + this.masterVolumeNode.disconnect(); + } + + this.context = context; + + this.masterMuteNode = context.createGain(); + this.masterVolumeNode = context.createGain(); + + this.masterMuteNode.connect(this.masterVolumeNode); + this.masterVolumeNode.connect(context.destination); + + this.destination = this.masterMuteNode; + + return this; + }, + + /** + * Adds a new sound into the sound manager. + * + * @method Phaser.Sound.WebAudioSoundManager#add + * @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.WebAudioSound} The new sound instance. + */ + add: function (key, config) + { + var sound = new WebAudioSound(this, key, config); + + this.sounds.push(sound); + + return sound; + }, + + /** + * Decode audio data into a format ready for playback via Web Audio. + * + * The audio data can be a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + * + * The `audioKey` is the key that will be used to save the decoded audio to the audio cache. + * + * Instead of passing a single entry you can instead pass an array of `Phaser.Types.Sound.DecodeAudioConfig` + * objects as the first and only argument. + * + * Decoding is an async process, so be sure to listen for the events to know when decoding has completed. + * + * Once the audio has decoded it can be added to the Sound Manager or played via its key. + * + * @method Phaser.Sound.WebAudioSoundManager#decodeAudio + * @fires Phaser.Sound.Events#DECODED + * @fires Phaser.Sound.Events#DECODED_ALL + * @since 3.18.0 + * + * @param {(Phaser.Types.Sound.DecodeAudioConfig[]|string)} [audioKey] - The string-based key to be used to reference the decoded audio in the audio cache, or an array of audio config objects. + * @param {(ArrayBuffer|string)} [audioData] - The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + */ + decodeAudio: function (audioKey, audioData) + { + var audioFiles; + + if (!Array.isArray(audioKey)) + { + audioFiles = [ { key: audioKey, data: audioData } ]; + } + else + { + audioFiles = audioKey; + } + + var cache = this.game.cache.audio; + var remaining = audioFiles.length; + + for (var i = 0; i < audioFiles.length; i++) + { + var entry = audioFiles[i]; + + var key = entry.key; + var data = entry.data; + + if (typeof data === 'string') + { + data = Base64ToArrayBuffer(data); + } + + var success = function (key, audioBuffer) + { + cache.add(key, audioBuffer); + + this.emit(Events.DECODED, key); + + remaining--; + + if (remaining === 0) + { + this.emit(Events.DECODED_ALL); + } + }.bind(this, key); + + var failure = function (key, error) + { + // eslint-disable-next-line no-console + console.error('Error decoding audio: ' + key + ' - ', error ? error.message : ''); + + remaining--; + + if (remaining === 0) + { + this.emit(Events.DECODED_ALL); + } + }.bind(this, key); + + this.context.decodeAudioData(data, success, failure); + } + }, + + /** + * 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 + */ + unlock: function () + { + var _this = this; + + var body = document.body; + + var unlockHandler = function unlockHandler () + { + if (_this.context) + { + _this.context.resume().then(function () + { + body.removeEventListener('touchstart', unlockHandler); + body.removeEventListener('touchend', unlockHandler); + body.removeEventListener('click', unlockHandler); + body.removeEventListener('keydown', unlockHandler); + + _this.unlocked = true; + }, function () + { + body.removeEventListener('touchstart', unlockHandler); + body.removeEventListener('touchend', unlockHandler); + body.removeEventListener('click', unlockHandler); + body.removeEventListener('keydown', unlockHandler); + }); + } + }; + + if (body) + { + body.addEventListener('touchstart', unlockHandler, false); + body.addEventListener('touchend', unlockHandler, false); + body.addEventListener('click', unlockHandler, false); + body.addEventListener('keydown', unlockHandler, false); + } + }, + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.WebAudioSoundManager#onBlur + * @protected + * @since 3.0.0 + */ + onBlur: function () + { + if (!this.locked) + { + this.context.suspend(); + } + }, + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. + * + * @method Phaser.Sound.WebAudioSoundManager#onFocus + * @protected + * @since 3.0.0 + */ + onFocus: function () + { + if (!this.locked) + { + this.context.resume(); + } + }, + + /** + * Calls Phaser.Sound.BaseSoundManager#destroy method + * and cleans up all Web Audio API related stuff. + * + * @method Phaser.Sound.WebAudioSoundManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.destination = null; + this.masterVolumeNode.disconnect(); + this.masterVolumeNode = null; + this.masterMuteNode.disconnect(); + this.masterMuteNode = null; + + if (this.game.config.audio && this.game.config.audio.context) + { + this.context.suspend(); + } + else + { + var _this = this; + + this.context.close().then(function () + { + _this.context = null; + }); + } + + BaseSoundManager.prototype.destroy.call(this); + }, + + /** + * Sets the muted state of all this Sound Manager. + * + * @method Phaser.Sound.WebAudioSoundManager#setMute + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.3.0 + * + * @param {boolean} value - `true` to mute all sounds, `false` to unmute them. + * + * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager. + */ + setMute: function (value) + { + this.mute = value; + + return this; + }, + + /** + * @name Phaser.Sound.WebAudioSoundManager#mute + * @type {boolean} + * @fires Phaser.Sound.Events#GLOBAL_MUTE + * @since 3.0.0 + */ + mute: { + + get: function () + { + return (this.masterMuteNode.gain.value === 0); + }, + + set: function (value) + { + this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0); + + this.emit(Events.GLOBAL_MUTE, this, value); + } + + }, + + /** + * Sets the volume of this Sound Manager. + * + * @method Phaser.Sound.WebAudioSoundManager#setVolume + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.3.0 + * + * @param {number} value - The global volume of this Sound Manager. + * + * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager. + */ + setVolume: function (value) + { + this.volume = value; + + return this; + }, + + /** + * @name Phaser.Sound.WebAudioSoundManager#volume + * @type {number} + * @fires Phaser.Sound.Events#GLOBAL_VOLUME + * @since 3.0.0 + */ + volume: { + + get: function () + { + return this.masterVolumeNode.gain.value; + }, + + set: function (value) + { + this.masterVolumeNode.gain.setValueAtTime(value, 0); + + this.emit(Events.GLOBAL_VOLUME, this, value); + } + + } + +}); + +module.exports = WebAudioSoundManager; diff --git a/src/structs/List.js b/src/structs/List.js index 2e54e0cba..d118fd4ed 100644 --- a/src/structs/List.js +++ b/src/structs/List.js @@ -1,810 +1,810 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArrayUtils = require('../utils/array'); -var Class = require('../utils/Class'); -var NOOP = require('../utils/NOOP'); -var StableSort = require('../utils/array/StableSort'); - -/** - * @callback EachListCallback - * - * @param {I} item - The item which is currently being processed. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - */ - -/** - * @classdesc - * List is a generic implementation of an ordered list which contains utility methods for retrieving, manipulating, and iterating items. - * - * @class List - * @memberof Phaser.Structs - * @constructor - * @since 3.0.0 - * - * @generic T - * - * @param {*} parent - The parent of this list. - */ -var List = new Class({ - - initialize: - - function List (parent) - { - /** - * The parent of this list. - * - * @name Phaser.Structs.List#parent - * @type {*} - * @since 3.0.0 - */ - this.parent = parent; - - /** - * The objects that belong to this collection. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.List#list - * @type {Array.<*>} - * @default [] - * @since 3.0.0 - */ - this.list = []; - - /** - * The index of the current element. - * - * This is used internally when iterating through the list with the {@link #first}, {@link #last}, {@link #get}, and {@link #previous} properties. - * - * @name Phaser.Structs.List#position - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.position = 0; - - /** - * A callback that is invoked every time a child is added to this list. - * - * @name Phaser.Structs.List#addCallback - * @type {function} - * @since 3.4.0 - */ - this.addCallback = NOOP; - - /** - * A callback that is invoked every time a child is removed from this list. - * - * @name Phaser.Structs.List#removeCallback - * @type {function} - * @since 3.4.0 - */ - this.removeCallback = NOOP; - - /** - * The property key to sort by. - * - * @name Phaser.Structs.List#_sortKey - * @type {string} - * @since 3.4.0 - */ - this._sortKey = ''; - }, - - /** - * Adds the given item to the end of the list. Each item must be unique. - * - * @method Phaser.Structs.List#add - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*|Array.<*>} child - The item, or array of items, to add to the list. - * @param {boolean} [skipCallback=false] - Skip calling the List.addCallback if this child is added successfully. - * - * @return {*} The list's underlying array. - */ - add: function (child, skipCallback) - { - if (skipCallback) - { - return ArrayUtils.Add(this.list, child); - } - else - { - return ArrayUtils.Add(this.list, child, 0, this.addCallback, this); - } - }, - - /** - * Adds an item to list, starting at a specified index. Each item must be unique within the list. - * - * @method Phaser.Structs.List#addAt - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item, or array of items, to add to the list. - * @param {integer} [index=0] - The index in the list at which the element(s) will be inserted. - * @param {boolean} [skipCallback=false] - Skip calling the List.addCallback if this child is added successfully. - * - * @return {*} The List's underlying array. - */ - addAt: function (child, index, skipCallback) - { - if (skipCallback) - { - return ArrayUtils.AddAt(this.list, child, index); - } - else - { - return ArrayUtils.AddAt(this.list, child, index, 0, this.addCallback, this); - } - }, - - /** - * Retrieves the item at a given position inside the List. - * - * @method Phaser.Structs.List#getAt - * @since 3.0.0 - * - * @genericUse {T} - [$return] - * - * @param {integer} index - The index of the item. - * - * @return {*} The retrieved item, or `undefined` if it's outside the List's bounds. - */ - getAt: function (index) - { - return this.list[index]; - }, - - /** - * Locates an item within the List and returns its index. - * - * @method Phaser.Structs.List#getIndex - * @since 3.0.0 - * - * @genericUse {T} - [child] - * - * @param {*} child - The item to locate. - * - * @return {integer} The index of the item within the List, or -1 if it's not in the List. - */ - getIndex: function (child) - { - // Return -1 if given child isn't a child of this display list - return this.list.indexOf(child); - }, - - /** - * 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 boolean. - * - * @return {Phaser.Structs.List} This List object. - */ - sort: function (property, handler) - { - if (!property) - { - return this; - } - - if (handler === undefined) - { - handler = function (childA, childB) - { - return childA[property] - childB[property]; - }; - } - - StableSort.inplace(this.list, handler); - - return this; - }, - - /** - * Searches for the first instance of a child with its `name` - * property matching the given argument. Should more than one child have - * the same name only the first is returned. - * - * @method Phaser.Structs.List#getByName - * @since 3.0.0 - * - * @genericUse {T | null} - [$return] - * - * @param {string} name - The name to search for. - * - * @return {?*} The first child with a matching name, or null if none were found. - */ - getByName: function (name) - { - return ArrayUtils.GetFirst(this.list, 'name', name); - }, - - /** - * Returns a random child from the group. - * - * @method Phaser.Structs.List#getRandom - * @since 3.0.0 - * - * @genericUse {T | null} - [$return] - * - * @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). - * @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. - * - * @return {?*} A random child of this Group. - */ - getRandom: function (startIndex, length) - { - return ArrayUtils.GetRandom(this.list, startIndex, length); - }, - - /** - * Returns the first element in a given part of the List which matches a specific criterion. - * - * @method Phaser.Structs.List#getFirst - * @since 3.0.0 - * - * @genericUse {T | null} - [$return] - * - * @param {string} property - The name of the property to test or a falsey value to have no criterion. - * @param {*} value - The value to test the `property` against, or `undefined` to allow any value and only check for existence. - * @param {number} [startIndex=0] - The position in the List to start the search at. - * @param {number} [endIndex] - The position in the List to optionally stop the search at. It won't be checked. - * - * @return {?*} The first item which matches the given criterion, or `null` if no such item exists. - */ - getFirst: function (property, value, startIndex, endIndex) - { - return ArrayUtils.GetFirst(this.list, property, value, startIndex, endIndex); - }, - - /** - * Returns all children in this List. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('parent')` would return only children that have a property called `parent`. - * - * You can also specify a value to compare the property to: - * - * `getAll('visible', true)` would return only children that have their visible property set to `true`. - * - * Optionally you can specify a start and end index. For example if this List had 100 children, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 children in the List. - * - * @method Phaser.Structs.List#getAll - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {T[]} - [$return] - * - * @param {string} [property] - An optional property to test against the value argument. - * @param {*} [value] - If property is set then Child.property must strictly equal this value to be included in the results. - * @param {integer} [startIndex] - The first child index to start the search from. - * @param {integer} [endIndex] - The last child index to search up until. - * - * @return {Array.<*>} All items of the List which match the given criterion, if any. - */ - getAll: function (property, value, startIndex, endIndex) - { - return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex); - }, - - /** - * Returns the total number of items in the List which have a property matching the given value. - * - * @method Phaser.Structs.List#count - * @since 3.0.0 - * - * @genericUse {T} - [value] - * - * @param {string} property - The property to test on each item. - * @param {*} value - The value to test the property against. - * - * @return {integer} The total number of matching elements. - */ - count: function (property, value) - { - return ArrayUtils.CountAllMatching(this.list, property, value); - }, - - /** - * Swaps the positions of two items in the list. - * - * @method Phaser.Structs.List#swap - * @since 3.0.0 - * - * @genericUse {T} - [child1,child2] - * - * @param {*} child1 - The first item to swap. - * @param {*} child2 - The second item to swap. - */ - swap: function (child1, child2) - { - ArrayUtils.Swap(this.list, child1, child2); - }, - - /** - * Moves an item in the List to a new position. - * - * @method Phaser.Structs.List#moveTo - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item to move. - * @param {integer} index - Moves an item in the List to a new position. - * - * @return {*} The item that was moved. - */ - moveTo: function (child, index) - { - return ArrayUtils.MoveTo(this.list, child, index); - }, - - /** - * Removes one or many items from the List. - * - * @method Phaser.Structs.List#remove - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item, or array of items, to remove. - * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. - * - * @return {*} The item, or array of items, which were successfully removed from the List. - */ - remove: function (child, skipCallback) - { - if (skipCallback) - { - return ArrayUtils.Remove(this.list, child); - } - else - { - return ArrayUtils.Remove(this.list, child, this.removeCallback, this); - } - }, - - /** - * Removes the item at the given position in the List. - * - * @method Phaser.Structs.List#removeAt - * @since 3.0.0 - * - * @genericUse {T} - [$return] - * - * @param {integer} index - The position to remove the item from. - * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. - * - * @return {*} The item that was removed. - */ - removeAt: function (index, skipCallback) - { - if (skipCallback) - { - return ArrayUtils.RemoveAt(this.list, index); - } - else - { - return ArrayUtils.RemoveAt(this.list, index, this.removeCallback, this); - } - }, - - /** - * Removes the items within the given range in the List. - * - * @method Phaser.Structs.List#removeBetween - * @since 3.0.0 - * - * @genericUse {T[]} - [$return] - * - * @param {integer} [startIndex=0] - The index to start removing from. - * @param {integer} [endIndex] - The position to stop removing at. The item at this position won't be removed. - * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. - * - * @return {Array.<*>} An array of the items which were removed. - */ - removeBetween: function (startIndex, endIndex, skipCallback) - { - if (skipCallback) - { - return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex); - } - else - { - return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeCallback, this); - } - }, - - /** - * Removes all the items. - * - * @method Phaser.Structs.List#removeAll - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.List.} - [$return] - * - * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. - * - * @return {Phaser.Structs.List} This List object. - */ - removeAll: function (skipCallback) - { - var i = this.list.length; - - while (i--) - { - this.remove(this.list[i], skipCallback); - } - - return this; - }, - - /** - * Brings the given child to the top of this List. - * - * @method Phaser.Structs.List#bringToTop - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item to bring to the top of the List. - * - * @return {*} The item which was moved. - */ - bringToTop: function (child) - { - return ArrayUtils.BringToTop(this.list, child); - }, - - /** - * Sends the given child to the bottom of this List. - * - * @method Phaser.Structs.List#sendToBack - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item to send to the back of the list. - * - * @return {*} The item which was moved. - */ - sendToBack: function (child) - { - return ArrayUtils.SendToBack(this.list, child); - }, - - /** - * Moves the given child up one place in this group unless it's already at the top. - * - * @method Phaser.Structs.List#moveUp - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item to move up. - * - * @return {*} The item which was moved. - */ - moveUp: function (child) - { - ArrayUtils.MoveUp(this.list, child); - - return child; - }, - - /** - * Moves the given child down one place in this group unless it's already at the bottom. - * - * @method Phaser.Structs.List#moveDown - * @since 3.0.0 - * - * @genericUse {T} - [child,$return] - * - * @param {*} child - The item to move down. - * - * @return {*} The item which was moved. - */ - moveDown: function (child) - { - ArrayUtils.MoveDown(this.list, child); - - return child; - }, - - /** - * Reverses the order of all children in this List. - * - * @method Phaser.Structs.List#reverse - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.List.} - [$return] - * - * @return {Phaser.Structs.List} This List object. - */ - reverse: function () - { - this.list.reverse(); - - return this; - }, - - /** - * Shuffles the items in the list. - * - * @method Phaser.Structs.List#shuffle - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.List.} - [$return] - * - * @return {Phaser.Structs.List} This List object. - */ - shuffle: function () - { - ArrayUtils.Shuffle(this.list); - - return this; - }, - - /** - * Replaces a child of this List with the given newChild. The newChild cannot be a member of this List. - * - * @method Phaser.Structs.List#replace - * @since 3.0.0 - * - * @genericUse {T} - [oldChild,newChild,$return] - * - * @param {*} oldChild - The child in this List that will be replaced. - * @param {*} newChild - The child to be inserted into this List. - * - * @return {*} Returns the oldChild that was replaced within this group. - */ - replace: function (oldChild, newChild) - { - return ArrayUtils.Replace(this.list, oldChild, newChild); - }, - - /** - * Checks if an item exists within the List. - * - * @method Phaser.Structs.List#exists - * @since 3.0.0 - * - * @genericUse {T} - [child] - * - * @param {*} child - The item to check for the existence of. - * - * @return {boolean} `true` if the item is found in the list, otherwise `false`. - */ - exists: function (child) - { - return (this.list.indexOf(child) > -1); - }, - - /** - * Sets the property `key` to the given value on all members of this List. - * - * @method Phaser.Structs.List#setAll - * @since 3.0.0 - * - * @genericUse {T} - [value] - * - * @param {string} property - The name of the property to set. - * @param {*} value - The value to set the property to. - * @param {integer} [startIndex] - The first child index to start the search from. - * @param {integer} [endIndex] - The last child index to search up until. - */ - setAll: function (property, value, startIndex, endIndex) - { - ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); - - return this; - }, - - /** - * Passes all children to the given callback. - * - * @method Phaser.Structs.List#each - * @since 3.0.0 - * - * @genericUse {EachListCallback.} - [callback] - * - * @param {EachListCallback} callback - The function to call. - * @param {*} [context] - Value to use as `this` when executing callback. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - */ - each: function (callback, context) - { - var args = [ null ]; - - for (var i = 2; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (i = 0; i < this.list.length; i++) - { - args[0] = this.list[i]; - - callback.apply(context, args); - } - }, - - /** - * Clears the List and recreates its internal array. - * - * @method Phaser.Structs.List#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - this.removeAll(); - - this.list = []; - }, - - /** - * Destroys this List. - * - * @method Phaser.Structs.List#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.removeAll(); - - this.parent = null; - this.addCallback = null; - this.removeCallback = null; - }, - - /** - * The number of items inside the List. - * - * @name Phaser.Structs.List#length - * @type {integer} - * @readonly - * @since 3.0.0 - */ - length: { - - get: function () - { - return this.list.length; - } - - }, - - /** - * The first item in the List or `null` for an empty List. - * - * @name Phaser.Structs.List#first - * @genericUse {T} - [$type] - * @type {*} - * @readonly - * @since 3.0.0 - */ - first: { - - get: function () - { - this.position = 0; - - if (this.list.length > 0) - { - return this.list[0]; - } - else - { - return null; - } - } - - }, - - /** - * The last item in the List, or `null` for an empty List. - * - * @name Phaser.Structs.List#last - * @genericUse {T} - [$type] - * @type {*} - * @readonly - * @since 3.0.0 - */ - last: { - - get: function () - { - if (this.list.length > 0) - { - this.position = this.list.length - 1; - - return this.list[this.position]; - } - else - { - return null; - } - } - - }, - - /** - * The next item in the List, or `null` if the entire List has been traversed. - * - * This property can be read successively after reading {@link #first} or manually setting the {@link #position} to iterate the List. - * - * @name Phaser.Structs.List#next - * @genericUse {T} - [$type] - * @type {*} - * @readonly - * @since 3.0.0 - */ - next: { - - get: function () - { - if (this.position < this.list.length) - { - this.position++; - - return this.list[this.position]; - } - else - { - return null; - } - } - - }, - - /** - * The previous item in the List, or `null` if the entire List has been traversed. - * - * This property can be read successively after reading {@link #last} or manually setting the {@link #position} to iterate the List backwards. - * - * @name Phaser.Structs.List#previous - * @genericUse {T} - [$type] - * @type {*} - * @readonly - * @since 3.0.0 - */ - previous: { - - get: function () - { - if (this.position > 0) - { - this.position--; - - return this.list[this.position]; - } - else - { - return null; - } - } - - } - -}); - -module.exports = List; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayUtils = require('../utils/array'); +var Class = require('../utils/Class'); +var NOOP = require('../utils/NOOP'); +var StableSort = require('../utils/array/StableSort'); + +/** + * @callback EachListCallback + * + * @param {I} item - The item which is currently being processed. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + +/** + * @classdesc + * List is a generic implementation of an ordered list which contains utility methods for retrieving, manipulating, and iterating items. + * + * @class List + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic T + * + * @param {*} parent - The parent of this list. + */ +var List = new Class({ + + initialize: + + function List (parent) + { + /** + * The parent of this list. + * + * @name Phaser.Structs.List#parent + * @type {*} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * The objects that belong to this collection. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.List#list + * @type {Array.<*>} + * @default [] + * @since 3.0.0 + */ + this.list = []; + + /** + * The index of the current element. + * + * This is used internally when iterating through the list with the {@link #first}, {@link #last}, {@link #get}, and {@link #previous} properties. + * + * @name Phaser.Structs.List#position + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.position = 0; + + /** + * A callback that is invoked every time a child is added to this list. + * + * @name Phaser.Structs.List#addCallback + * @type {function} + * @since 3.4.0 + */ + this.addCallback = NOOP; + + /** + * A callback that is invoked every time a child is removed from this list. + * + * @name Phaser.Structs.List#removeCallback + * @type {function} + * @since 3.4.0 + */ + this.removeCallback = NOOP; + + /** + * The property key to sort by. + * + * @name Phaser.Structs.List#_sortKey + * @type {string} + * @since 3.4.0 + */ + this._sortKey = ''; + }, + + /** + * Adds the given item to the end of the list. Each item must be unique. + * + * @method Phaser.Structs.List#add + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*|Array.<*>} child - The item, or array of items, to add to the list. + * @param {boolean} [skipCallback=false] - Skip calling the List.addCallback if this child is added successfully. + * + * @return {*} The list's underlying array. + */ + add: function (child, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.Add(this.list, child); + } + else + { + return ArrayUtils.Add(this.list, child, 0, this.addCallback, this); + } + }, + + /** + * Adds an item to list, starting at a specified index. Each item must be unique within the list. + * + * @method Phaser.Structs.List#addAt + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item, or array of items, to add to the list. + * @param {integer} [index=0] - The index in the list at which the element(s) will be inserted. + * @param {boolean} [skipCallback=false] - Skip calling the List.addCallback if this child is added successfully. + * + * @return {*} The List's underlying array. + */ + addAt: function (child, index, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.AddAt(this.list, child, index); + } + else + { + return ArrayUtils.AddAt(this.list, child, index, 0, this.addCallback, this); + } + }, + + /** + * Retrieves the item at a given position inside the List. + * + * @method Phaser.Structs.List#getAt + * @since 3.0.0 + * + * @genericUse {T} - [$return] + * + * @param {integer} index - The index of the item. + * + * @return {*} The retrieved item, or `undefined` if it's outside the List's bounds. + */ + getAt: function (index) + { + return this.list[index]; + }, + + /** + * Locates an item within the List and returns its index. + * + * @method Phaser.Structs.List#getIndex + * @since 3.0.0 + * + * @genericUse {T} - [child] + * + * @param {*} child - The item to locate. + * + * @return {integer} The index of the item within the List, or -1 if it's not in the List. + */ + getIndex: function (child) + { + // Return -1 if given child isn't a child of this display list + return this.list.indexOf(child); + }, + + /** + * 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 boolean. + * + * @return {Phaser.Structs.List} This List object. + */ + sort: function (property, handler) + { + if (!property) + { + return this; + } + + if (handler === undefined) + { + handler = function (childA, childB) + { + return childA[property] - childB[property]; + }; + } + + StableSort.inplace(this.list, handler); + + return this; + }, + + /** + * Searches for the first instance of a child with its `name` + * property matching the given argument. Should more than one child have + * the same name only the first is returned. + * + * @method Phaser.Structs.List#getByName + * @since 3.0.0 + * + * @genericUse {T | null} - [$return] + * + * @param {string} name - The name to search for. + * + * @return {?*} The first child with a matching name, or null if none were found. + */ + getByName: function (name) + { + return ArrayUtils.GetFirst(this.list, 'name', name); + }, + + /** + * Returns a random child from the group. + * + * @method Phaser.Structs.List#getRandom + * @since 3.0.0 + * + * @genericUse {T | null} - [$return] + * + * @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). + * @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. + * + * @return {?*} A random child of this Group. + */ + getRandom: function (startIndex, length) + { + return ArrayUtils.GetRandom(this.list, startIndex, length); + }, + + /** + * Returns the first element in a given part of the List which matches a specific criterion. + * + * @method Phaser.Structs.List#getFirst + * @since 3.0.0 + * + * @genericUse {T | null} - [$return] + * + * @param {string} property - The name of the property to test or a falsey value to have no criterion. + * @param {*} value - The value to test the `property` against, or `undefined` to allow any value and only check for existence. + * @param {number} [startIndex=0] - The position in the List to start the search at. + * @param {number} [endIndex] - The position in the List to optionally stop the search at. It won't be checked. + * + * @return {?*} The first item which matches the given criterion, or `null` if no such item exists. + */ + getFirst: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetFirst(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns all children in this List. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('parent')` would return only children that have a property called `parent`. + * + * You can also specify a value to compare the property to: + * + * `getAll('visible', true)` would return only children that have their visible property set to `true`. + * + * Optionally you can specify a start and end index. For example if this List had 100 children, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 children in the List. + * + * @method Phaser.Structs.List#getAll + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {T[]} - [$return] + * + * @param {string} [property] - An optional property to test against the value argument. + * @param {*} [value] - If property is set then Child.property must strictly equal this value to be included in the results. + * @param {integer} [startIndex] - The first child index to start the search from. + * @param {integer} [endIndex] - The last child index to search up until. + * + * @return {Array.<*>} All items of the List which match the given criterion, if any. + */ + getAll: function (property, value, startIndex, endIndex) + { + return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex); + }, + + /** + * Returns the total number of items in the List which have a property matching the given value. + * + * @method Phaser.Structs.List#count + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {string} property - The property to test on each item. + * @param {*} value - The value to test the property against. + * + * @return {integer} The total number of matching elements. + */ + count: function (property, value) + { + return ArrayUtils.CountAllMatching(this.list, property, value); + }, + + /** + * Swaps the positions of two items in the list. + * + * @method Phaser.Structs.List#swap + * @since 3.0.0 + * + * @genericUse {T} - [child1,child2] + * + * @param {*} child1 - The first item to swap. + * @param {*} child2 - The second item to swap. + */ + swap: function (child1, child2) + { + ArrayUtils.Swap(this.list, child1, child2); + }, + + /** + * Moves an item in the List to a new position. + * + * @method Phaser.Structs.List#moveTo + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to move. + * @param {integer} index - Moves an item in the List to a new position. + * + * @return {*} The item that was moved. + */ + moveTo: function (child, index) + { + return ArrayUtils.MoveTo(this.list, child, index); + }, + + /** + * Removes one or many items from the List. + * + * @method Phaser.Structs.List#remove + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item, or array of items, to remove. + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {*} The item, or array of items, which were successfully removed from the List. + */ + remove: function (child, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.Remove(this.list, child); + } + else + { + return ArrayUtils.Remove(this.list, child, this.removeCallback, this); + } + }, + + /** + * Removes the item at the given position in the List. + * + * @method Phaser.Structs.List#removeAt + * @since 3.0.0 + * + * @genericUse {T} - [$return] + * + * @param {integer} index - The position to remove the item from. + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {*} The item that was removed. + */ + removeAt: function (index, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.RemoveAt(this.list, index); + } + else + { + return ArrayUtils.RemoveAt(this.list, index, this.removeCallback, this); + } + }, + + /** + * Removes the items within the given range in the List. + * + * @method Phaser.Structs.List#removeBetween + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @param {integer} [startIndex=0] - The index to start removing from. + * @param {integer} [endIndex] - The position to stop removing at. The item at this position won't be removed. + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {Array.<*>} An array of the items which were removed. + */ + removeBetween: function (startIndex, endIndex, skipCallback) + { + if (skipCallback) + { + return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex); + } + else + { + return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeCallback, this); + } + }, + + /** + * Removes all the items. + * + * @method Phaser.Structs.List#removeAll + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.List.} - [$return] + * + * @param {boolean} [skipCallback=false] - Skip calling the List.removeCallback. + * + * @return {Phaser.Structs.List} This List object. + */ + removeAll: function (skipCallback) + { + var i = this.list.length; + + while (i--) + { + this.remove(this.list[i], skipCallback); + } + + return this; + }, + + /** + * Brings the given child to the top of this List. + * + * @method Phaser.Structs.List#bringToTop + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to bring to the top of the List. + * + * @return {*} The item which was moved. + */ + bringToTop: function (child) + { + return ArrayUtils.BringToTop(this.list, child); + }, + + /** + * Sends the given child to the bottom of this List. + * + * @method Phaser.Structs.List#sendToBack + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to send to the back of the list. + * + * @return {*} The item which was moved. + */ + sendToBack: function (child) + { + return ArrayUtils.SendToBack(this.list, child); + }, + + /** + * Moves the given child up one place in this group unless it's already at the top. + * + * @method Phaser.Structs.List#moveUp + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to move up. + * + * @return {*} The item which was moved. + */ + moveUp: function (child) + { + ArrayUtils.MoveUp(this.list, child); + + return child; + }, + + /** + * Moves the given child down one place in this group unless it's already at the bottom. + * + * @method Phaser.Structs.List#moveDown + * @since 3.0.0 + * + * @genericUse {T} - [child,$return] + * + * @param {*} child - The item to move down. + * + * @return {*} The item which was moved. + */ + moveDown: function (child) + { + ArrayUtils.MoveDown(this.list, child); + + return child; + }, + + /** + * Reverses the order of all children in this List. + * + * @method Phaser.Structs.List#reverse + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.List.} - [$return] + * + * @return {Phaser.Structs.List} This List object. + */ + reverse: function () + { + this.list.reverse(); + + return this; + }, + + /** + * Shuffles the items in the list. + * + * @method Phaser.Structs.List#shuffle + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.List.} - [$return] + * + * @return {Phaser.Structs.List} This List object. + */ + shuffle: function () + { + ArrayUtils.Shuffle(this.list); + + return this; + }, + + /** + * Replaces a child of this List with the given newChild. The newChild cannot be a member of this List. + * + * @method Phaser.Structs.List#replace + * @since 3.0.0 + * + * @genericUse {T} - [oldChild,newChild,$return] + * + * @param {*} oldChild - The child in this List that will be replaced. + * @param {*} newChild - The child to be inserted into this List. + * + * @return {*} Returns the oldChild that was replaced within this group. + */ + replace: function (oldChild, newChild) + { + return ArrayUtils.Replace(this.list, oldChild, newChild); + }, + + /** + * Checks if an item exists within the List. + * + * @method Phaser.Structs.List#exists + * @since 3.0.0 + * + * @genericUse {T} - [child] + * + * @param {*} child - The item to check for the existence of. + * + * @return {boolean} `true` if the item is found in the list, otherwise `false`. + */ + exists: function (child) + { + return (this.list.indexOf(child) > -1); + }, + + /** + * Sets the property `key` to the given value on all members of this List. + * + * @method Phaser.Structs.List#setAll + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {string} property - The name of the property to set. + * @param {*} value - The value to set the property to. + * @param {integer} [startIndex] - The first child index to start the search from. + * @param {integer} [endIndex] - The last child index to search up until. + */ + setAll: function (property, value, startIndex, endIndex) + { + ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); + + return this; + }, + + /** + * Passes all children to the given callback. + * + * @method Phaser.Structs.List#each + * @since 3.0.0 + * + * @genericUse {EachListCallback.} - [callback] + * + * @param {EachListCallback} callback - The function to call. + * @param {*} [context] - Value to use as `this` when executing callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + each: function (callback, context) + { + var args = [ null ]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < this.list.length; i++) + { + args[0] = this.list[i]; + + callback.apply(context, args); + } + }, + + /** + * Clears the List and recreates its internal array. + * + * @method Phaser.Structs.List#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.removeAll(); + + this.list = []; + }, + + /** + * Destroys this List. + * + * @method Phaser.Structs.List#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAll(); + + this.parent = null; + this.addCallback = null; + this.removeCallback = null; + }, + + /** + * The number of items inside the List. + * + * @name Phaser.Structs.List#length + * @type {integer} + * @readonly + * @since 3.0.0 + */ + length: { + + get: function () + { + return this.list.length; + } + + }, + + /** + * The first item in the List or `null` for an empty List. + * + * @name Phaser.Structs.List#first + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + first: { + + get: function () + { + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + } + + }, + + /** + * The last item in the List, or `null` for an empty List. + * + * @name Phaser.Structs.List#last + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + last: { + + get: function () + { + if (this.list.length > 0) + { + this.position = this.list.length - 1; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * The next item in the List, or `null` if the entire List has been traversed. + * + * This property can be read successively after reading {@link #first} or manually setting the {@link #position} to iterate the List. + * + * @name Phaser.Structs.List#next + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + next: { + + get: function () + { + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + } + + }, + + /** + * The previous item in the List, or `null` if the entire List has been traversed. + * + * This property can be read successively after reading {@link #last} or manually setting the {@link #position} to iterate the List backwards. + * + * @name Phaser.Structs.List#previous + * @genericUse {T} - [$type] + * @type {*} + * @readonly + * @since 3.0.0 + */ + previous: { + + get: function () + { + if (this.position > 0) + { + this.position--; + + return this.list[this.position]; + } + else + { + return null; + } + } + + } + +}); + +module.exports = List; diff --git a/src/structs/Map.js b/src/structs/Map.js index 28ab15b22..bacbc7406 100644 --- a/src/structs/Map.js +++ b/src/structs/Map.js @@ -1,367 +1,367 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); - -/** - * @callback EachMapCallback - * - * @param {string} key - The key of the Map entry. - * @param {E} entry - The value of the Map entry. - * - * @return {?boolean} The callback result. - */ - -/** - * @classdesc - * The keys of a Map can be arbitrary values. - * - * ```javascript - * var map = new Map([ - * [ 1, 'one' ], - * [ 2, 'two' ], - * [ 3, 'three' ] - * ]); - * ``` - * - * @class Map - * @memberof Phaser.Structs - * @constructor - * @since 3.0.0 - * - * @generic K - * @generic V - * @genericUse {V[]} - [elements] - * - * @param {Array.<*>} elements - An optional array of key-value pairs to populate this Map with. - */ -var Map = new Class({ - - initialize: - - function Map (elements) - { - /** - * The entries in this Map. - * - * @genericUse {Object.} - [$type] - * - * @name Phaser.Structs.Map#entries - * @type {Object.} - * @default {} - * @since 3.0.0 - */ - this.entries = {}; - - /** - * The number of key / value pairs in this Map. - * - * @name Phaser.Structs.Map#size - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.size = 0; - - if (Array.isArray(elements)) - { - for (var i = 0; i < elements.length; i++) - { - this.set(elements[i][0], elements[i][1]); - } - } - }, - - /** - * Adds an element with a specified `key` and `value` to this Map. - * If the `key` already exists, the value will be replaced. - * - * @method Phaser.Structs.Map#set - * @since 3.0.0 - * - * @genericUse {K} - [key] - * @genericUse {V} - [value] - * @genericUse {Phaser.Structs.Map.} - [$return] - * - * @param {string} key - The key of the element to be added to this Map. - * @param {*} value - The value of the element to be added to this Map. - * - * @return {Phaser.Structs.Map} This Map object. - */ - set: function (key, value) - { - if (!this.has(key)) - { - this.size++; - } - - this.entries[key] = value; - - return this; - }, - - /** - * Returns the value associated to the `key`, or `undefined` if there is none. - * - * @method Phaser.Structs.Map#get - * @since 3.0.0 - * - * @genericUse {K} - [key] - * @genericUse {V} - [$return] - * - * @param {string} key - The key of the element to return from the `Map` object. - * - * @return {*} The element associated with the specified key or `undefined` if the key can't be found in this Map object. - */ - get: function (key) - { - if (this.has(key)) - { - return this.entries[key]; - } - }, - - /** - * Returns an `Array` of all the values stored in this Map. - * - * @method Phaser.Structs.Map#getArray - * @since 3.0.0 - * - * @genericUse {V[]} - [$return] - * - * @return {Array.<*>} An array of the values stored in this Map. - */ - getArray: function () - { - var output = []; - var entries = this.entries; - - for (var key in entries) - { - output.push(entries[key]); - } - - return output; - }, - - /** - * Returns a boolean indicating whether an element with the specified key exists or not. - * - * @method Phaser.Structs.Map#has - * @since 3.0.0 - * - * @genericUse {K} - [key] - * - * @param {string} key - The key of the element to test for presence of in this Map. - * - * @return {boolean} Returns `true` if an element with the specified key exists in this Map, otherwise `false`. - */ - has: function (key) - { - return (this.entries.hasOwnProperty(key)); - }, - - /** - * Delete the specified element from this Map. - * - * @method Phaser.Structs.Map#delete - * @since 3.0.0 - * - * @genericUse {K} - [key] - * @genericUse {Phaser.Structs.Map.} - [$return] - * - * @param {string} key - The key of the element to delete from this Map. - * - * @return {Phaser.Structs.Map} This Map object. - */ - delete: function (key) - { - if (this.has(key)) - { - delete this.entries[key]; - this.size--; - } - - return this; - }, - - /** - * Delete all entries from this Map. - * - * @method Phaser.Structs.Map#clear - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Map.} - [$return] - * - * @return {Phaser.Structs.Map} This Map object. - */ - clear: function () - { - Object.keys(this.entries).forEach(function (prop) - { - delete this.entries[prop]; - - }, this); - - this.size = 0; - - return this; - }, - - /** - * Returns all entries keys in this Map. - * - * @method Phaser.Structs.Map#keys - * @since 3.0.0 - * - * @genericUse {K[]} - [$return] - * - * @return {string[]} Array containing entries' keys. - */ - keys: function () - { - return Object.keys(this.entries); - }, - - /** - * Returns an `Array` of all entries. - * - * @method Phaser.Structs.Map#values - * @since 3.0.0 - * - * @genericUse {V[]} - [$return] - * - * @return {Array.<*>} An `Array` of entries. - */ - values: function () - { - var output = []; - var entries = this.entries; - - for (var key in entries) - { - output.push(entries[key]); - } - - return output; - }, - - /** - * Dumps the contents of this Map to the console via `console.group`. - * - * @method Phaser.Structs.Map#dump - * @since 3.0.0 - */ - dump: function () - { - var entries = this.entries; - - // eslint-disable-next-line no-console - console.group('Map'); - - for (var key in entries) - { - console.log(key, entries[key]); - } - - // eslint-disable-next-line no-console - console.groupEnd(); - }, - - /** - * Passes all entries in this Map to the given callback. - * - * @method Phaser.Structs.Map#each - * @since 3.0.0 - * - * @genericUse {EachMapCallback.} - [callback] - * @genericUse {Phaser.Structs.Map.} - [$return] - * - * @param {EachMapCallback} callback - The callback which will receive the keys and entries held in this Map. - * - * @return {Phaser.Structs.Map} This Map object. - */ - each: function (callback) - { - var entries = this.entries; - - for (var key in entries) - { - if (callback(key, entries[key]) === false) - { - break; - } - } - - return this; - }, - - /** - * Returns `true` if the value exists within this Map. Otherwise, returns `false`. - * - * @method Phaser.Structs.Map#contains - * @since 3.0.0 - * - * @genericUse {V} - [value] - * - * @param {*} value - The value to search for. - * - * @return {boolean} `true` if the value is found, otherwise `false`. - */ - contains: function (value) - { - var entries = this.entries; - - for (var key in entries) - { - if (entries[key] === value) - { - return true; - } - } - - return false; - }, - - /** - * Merges all new keys from the given Map into this one. - * If it encounters a key that already exists it will be skipped unless override is set to `true`. - * - * @method Phaser.Structs.Map#merge - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Map.} - [map,$return] - * - * @param {Phaser.Structs.Map} map - The Map to merge in to this Map. - * @param {boolean} [override=false] - Set to `true` to replace values in this Map with those from the source map, or `false` to skip them. - * - * @return {Phaser.Structs.Map} This Map object. - */ - merge: function (map, override) - { - if (override === undefined) { override = false; } - - var local = this.entries; - var source = map.entries; - - for (var key in source) - { - if (local.hasOwnProperty(key) && override) - { - local[key] = source[key]; - } - else - { - this.set(key, source[key]); - } - } - - return this; - } - -}); - -module.exports = Map; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); + +/** + * @callback EachMapCallback + * + * @param {string} key - The key of the Map entry. + * @param {E} entry - The value of the Map entry. + * + * @return {?boolean} The callback result. + */ + +/** + * @classdesc + * The keys of a Map can be arbitrary values. + * + * ```javascript + * var map = new Map([ + * [ 1, 'one' ], + * [ 2, 'two' ], + * [ 3, 'three' ] + * ]); + * ``` + * + * @class Map + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic K + * @generic V + * @genericUse {V[]} - [elements] + * + * @param {Array.<*>} elements - An optional array of key-value pairs to populate this Map with. + */ +var Map = new Class({ + + initialize: + + function Map (elements) + { + /** + * The entries in this Map. + * + * @genericUse {Object.} - [$type] + * + * @name Phaser.Structs.Map#entries + * @type {Object.} + * @default {} + * @since 3.0.0 + */ + this.entries = {}; + + /** + * The number of key / value pairs in this Map. + * + * @name Phaser.Structs.Map#size + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.size = 0; + + if (Array.isArray(elements)) + { + for (var i = 0; i < elements.length; i++) + { + this.set(elements[i][0], elements[i][1]); + } + } + }, + + /** + * Adds an element with a specified `key` and `value` to this Map. + * If the `key` already exists, the value will be replaced. + * + * @method Phaser.Structs.Map#set + * @since 3.0.0 + * + * @genericUse {K} - [key] + * @genericUse {V} - [value] + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @param {string} key - The key of the element to be added to this Map. + * @param {*} value - The value of the element to be added to this Map. + * + * @return {Phaser.Structs.Map} This Map object. + */ + set: function (key, value) + { + if (!this.has(key)) + { + this.size++; + } + + this.entries[key] = value; + + return this; + }, + + /** + * Returns the value associated to the `key`, or `undefined` if there is none. + * + * @method Phaser.Structs.Map#get + * @since 3.0.0 + * + * @genericUse {K} - [key] + * @genericUse {V} - [$return] + * + * @param {string} key - The key of the element to return from the `Map` object. + * + * @return {*} The element associated with the specified key or `undefined` if the key can't be found in this Map object. + */ + get: function (key) + { + if (this.has(key)) + { + return this.entries[key]; + } + }, + + /** + * Returns an `Array` of all the values stored in this Map. + * + * @method Phaser.Structs.Map#getArray + * @since 3.0.0 + * + * @genericUse {V[]} - [$return] + * + * @return {Array.<*>} An array of the values stored in this Map. + */ + getArray: function () + { + var output = []; + var entries = this.entries; + + for (var key in entries) + { + output.push(entries[key]); + } + + return output; + }, + + /** + * Returns a boolean indicating whether an element with the specified key exists or not. + * + * @method Phaser.Structs.Map#has + * @since 3.0.0 + * + * @genericUse {K} - [key] + * + * @param {string} key - The key of the element to test for presence of in this Map. + * + * @return {boolean} Returns `true` if an element with the specified key exists in this Map, otherwise `false`. + */ + has: function (key) + { + return (this.entries.hasOwnProperty(key)); + }, + + /** + * Delete the specified element from this Map. + * + * @method Phaser.Structs.Map#delete + * @since 3.0.0 + * + * @genericUse {K} - [key] + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @param {string} key - The key of the element to delete from this Map. + * + * @return {Phaser.Structs.Map} This Map object. + */ + delete: function (key) + { + if (this.has(key)) + { + delete this.entries[key]; + this.size--; + } + + return this; + }, + + /** + * Delete all entries from this Map. + * + * @method Phaser.Structs.Map#clear + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @return {Phaser.Structs.Map} This Map object. + */ + clear: function () + { + Object.keys(this.entries).forEach(function (prop) + { + delete this.entries[prop]; + + }, this); + + this.size = 0; + + return this; + }, + + /** + * Returns all entries keys in this Map. + * + * @method Phaser.Structs.Map#keys + * @since 3.0.0 + * + * @genericUse {K[]} - [$return] + * + * @return {string[]} Array containing entries' keys. + */ + keys: function () + { + return Object.keys(this.entries); + }, + + /** + * Returns an `Array` of all entries. + * + * @method Phaser.Structs.Map#values + * @since 3.0.0 + * + * @genericUse {V[]} - [$return] + * + * @return {Array.<*>} An `Array` of entries. + */ + values: function () + { + var output = []; + var entries = this.entries; + + for (var key in entries) + { + output.push(entries[key]); + } + + return output; + }, + + /** + * Dumps the contents of this Map to the console via `console.group`. + * + * @method Phaser.Structs.Map#dump + * @since 3.0.0 + */ + dump: function () + { + var entries = this.entries; + + // eslint-disable-next-line no-console + console.group('Map'); + + for (var key in entries) + { + console.log(key, entries[key]); + } + + // eslint-disable-next-line no-console + console.groupEnd(); + }, + + /** + * Passes all entries in this Map to the given callback. + * + * @method Phaser.Structs.Map#each + * @since 3.0.0 + * + * @genericUse {EachMapCallback.} - [callback] + * @genericUse {Phaser.Structs.Map.} - [$return] + * + * @param {EachMapCallback} callback - The callback which will receive the keys and entries held in this Map. + * + * @return {Phaser.Structs.Map} This Map object. + */ + each: function (callback) + { + var entries = this.entries; + + for (var key in entries) + { + if (callback(key, entries[key]) === false) + { + break; + } + } + + return this; + }, + + /** + * Returns `true` if the value exists within this Map. Otherwise, returns `false`. + * + * @method Phaser.Structs.Map#contains + * @since 3.0.0 + * + * @genericUse {V} - [value] + * + * @param {*} value - The value to search for. + * + * @return {boolean} `true` if the value is found, otherwise `false`. + */ + contains: function (value) + { + var entries = this.entries; + + for (var key in entries) + { + if (entries[key] === value) + { + return true; + } + } + + return false; + }, + + /** + * Merges all new keys from the given Map into this one. + * If it encounters a key that already exists it will be skipped unless override is set to `true`. + * + * @method Phaser.Structs.Map#merge + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Map.} - [map,$return] + * + * @param {Phaser.Structs.Map} map - The Map to merge in to this Map. + * @param {boolean} [override=false] - Set to `true` to replace values in this Map with those from the source map, or `false` to skip them. + * + * @return {Phaser.Structs.Map} This Map object. + */ + merge: function (map, override) + { + if (override === undefined) { override = false; } + + var local = this.entries; + var source = map.entries; + + for (var key in source) + { + if (local.hasOwnProperty(key) && override) + { + local[key] = source[key]; + } + else + { + this.set(key, source[key]); + } + } + + return this; + } + +}); + +module.exports = Map; diff --git a/src/structs/ProcessQueue.js b/src/structs/ProcessQueue.js index d1831fd0d..fc239e428 100644 --- a/src/structs/ProcessQueue.js +++ b/src/structs/ProcessQueue.js @@ -1,285 +1,285 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); - -/** - * @classdesc - * A Process Queue maintains three internal lists. - * - * The `pending` list is a selection of items which are due to be made 'active' in the next update. - * The `active` list is a selection of items which are considered active and should be updated. - * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. - * - * When new items are added to a Process Queue they are put in the pending list, rather than being added - * immediately the active list. Equally, items that are removed are put into the destroy list, rather than - * being destroyed immediately. This allows the Process Queue to carefully process each item at a specific, fixed - * time, rather than at the time of the request from the API. - * - * @class ProcessQueue - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Structs - * @constructor - * @since 3.0.0 - * - * @generic T - */ -var ProcessQueue = new Class({ - - Extends: EventEmitter, - - initialize: - - function ProcessQueue () - { - EventEmitter.call(this); - - /** - * The `pending` list is a selection of items which are due to be made 'active' in the next update. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.ProcessQueue#_pending - * @type {Array.<*>} - * @private - * @default [] - * @since 3.0.0 - */ - this._pending = []; - - /** - * The `active` list is a selection of items which are considered active and should be updated. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.ProcessQueue#_active - * @type {Array.<*>} - * @private - * @default [] - * @since 3.0.0 - */ - this._active = []; - - /** - * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.ProcessQueue#_destroy - * @type {Array.<*>} - * @private - * @default [] - * @since 3.0.0 - */ - this._destroy = []; - - /** - * The total number of items awaiting processing. - * - * @name Phaser.Structs.ProcessQueue#_toProcess - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - this._toProcess = 0; - }, - - /** - * Adds a new item to the Process Queue. - * - * The item is added to the pending list and made active in the next update. - * - * @method Phaser.Structs.ProcessQueue#add - * @since 3.0.0 - * - * @genericUse {T} - [item] - * @genericUse {Phaser.Structs.ProcessQueue.} - [$return] - * - * @param {*} item - The item to add to the queue. - * - * @return {*} The item that was added. - */ - add: function (item) - { - this._pending.push(item); - - this._toProcess++; - - return item; - }, - - /** - * Removes an item from the Process Queue. - * - * The item is added to the pending destroy and fully removed in the next update. - * - * @method Phaser.Structs.ProcessQueue#remove - * @since 3.0.0 - * - * @genericUse {T} - [item] - * @genericUse {Phaser.Structs.ProcessQueue.} - [$return] - * - * @param {*} item - The item to be removed from the queue. - * - * @return {*} The item that was removed. - */ - remove: function (item) - { - this._destroy.push(item); - - this._toProcess++; - - return item; - }, - - /** - * Removes all active items from this Process Queue. - * - * All the items are marked as 'pending destroy' and fully removed in the next update. - * - * @method Phaser.Structs.ProcessQueue#removeAll - * @since 3.20.0 - * - * @return {this} This Process Queue object. - */ - removeAll: function () - { - var list = this._active; - var destroy = this._destroy; - var i = list.length; - - while (i--) - { - destroy.push(list[i]); - - this._toProcess++; - } - - return this; - }, - - /** - * Update this queue. First it will process any items awaiting destruction, and remove them. - * - * Then it will check to see if there are any items pending insertion, and move them to an - * active state. Finally, it will return a list of active items for further processing. - * - * @method Phaser.Structs.ProcessQueue#update - * @since 3.0.0 - * - * @genericUse {T[]} - [$return] - * - * @return {Array.<*>} A list of active items. - */ - update: function () - { - if (this._toProcess === 0) - { - // Quick bail - return this._active; - } - - var list = this._destroy; - var active = this._active; - var i; - var item; - - // Clear the 'destroy' list - for (i = 0; i < list.length; i++) - { - item = list[i]; - - // Remove from the 'active' array - var idx = active.indexOf(item); - - if (idx !== -1) - { - active.splice(idx, 1); - - this.emit(Events.REMOVE, item); - } - } - - list.length = 0; - - // Process the pending addition list - // This stops callbacks and out of sync events from populating the active array mid-way during an update - - list = this._pending; - - for (i = 0; i < list.length; i++) - { - item = list[i]; - - this._active.push(item); - - this.emit(Events.ADD, item); - } - - list.length = 0; - - this._toProcess = 0; - - // The owner of this queue can now safely do whatever it needs to with the active list - return this._active; - }, - - /** - * Returns the current list of active items. - * - * This method returns a reference to the active list array, not a copy of it. - * Therefore, be careful to not modify this array outside of the ProcessQueue. - * - * @method Phaser.Structs.ProcessQueue#getActive - * @since 3.0.0 - * - * @genericUse {T[]} - [$return] - * - * @return {Array.<*>} A list of active items. - */ - getActive: function () - { - return this._active; - }, - - /** - * The number of entries in the active list. - * - * @name Phaser.Structs.ProcessQueue#length - * @type {integer} - * @readonly - * @since 3.20.0 - */ - length: { - - get: function () - { - return this._active.length; - } - - }, - - /** - * Immediately destroys this process queue, clearing all of its internal arrays and resetting the process totals. - * - * @method Phaser.Structs.ProcessQueue#destroy - * @since 3.0.0 - */ - destroy: function () - { - this._toProcess = 0; - - this._pending = []; - this._active = []; - this._destroy = []; - } - -}); - -module.exports = ProcessQueue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); + +/** + * @classdesc + * A Process Queue maintains three internal lists. + * + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * The `active` list is a selection of items which are considered active and should be updated. + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * When new items are added to a Process Queue they are put in the pending list, rather than being added + * immediately the active list. Equally, items that are removed are put into the destroy list, rather than + * being destroyed immediately. This allows the Process Queue to carefully process each item at a specific, fixed + * time, rather than at the time of the request from the API. + * + * @class ProcessQueue + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic T + */ +var ProcessQueue = new Class({ + + Extends: EventEmitter, + + initialize: + + function ProcessQueue () + { + EventEmitter.call(this); + + /** + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.ProcessQueue#_pending + * @type {Array.<*>} + * @private + * @default [] + * @since 3.0.0 + */ + this._pending = []; + + /** + * The `active` list is a selection of items which are considered active and should be updated. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.ProcessQueue#_active + * @type {Array.<*>} + * @private + * @default [] + * @since 3.0.0 + */ + this._active = []; + + /** + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.ProcessQueue#_destroy + * @type {Array.<*>} + * @private + * @default [] + * @since 3.0.0 + */ + this._destroy = []; + + /** + * The total number of items awaiting processing. + * + * @name Phaser.Structs.ProcessQueue#_toProcess + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._toProcess = 0; + }, + + /** + * Adds a new item to the Process Queue. + * + * The item is added to the pending list and made active in the next update. + * + * @method Phaser.Structs.ProcessQueue#add + * @since 3.0.0 + * + * @genericUse {T} - [item] + * @genericUse {Phaser.Structs.ProcessQueue.} - [$return] + * + * @param {*} item - The item to add to the queue. + * + * @return {*} The item that was added. + */ + add: function (item) + { + this._pending.push(item); + + this._toProcess++; + + return item; + }, + + /** + * Removes an item from the Process Queue. + * + * The item is added to the pending destroy and fully removed in the next update. + * + * @method Phaser.Structs.ProcessQueue#remove + * @since 3.0.0 + * + * @genericUse {T} - [item] + * @genericUse {Phaser.Structs.ProcessQueue.} - [$return] + * + * @param {*} item - The item to be removed from the queue. + * + * @return {*} The item that was removed. + */ + remove: function (item) + { + this._destroy.push(item); + + this._toProcess++; + + return item; + }, + + /** + * Removes all active items from this Process Queue. + * + * All the items are marked as 'pending destroy' and fully removed in the next update. + * + * @method Phaser.Structs.ProcessQueue#removeAll + * @since 3.20.0 + * + * @return {this} This Process Queue object. + */ + removeAll: function () + { + var list = this._active; + var destroy = this._destroy; + var i = list.length; + + while (i--) + { + destroy.push(list[i]); + + this._toProcess++; + } + + return this; + }, + + /** + * Update this queue. First it will process any items awaiting destruction, and remove them. + * + * Then it will check to see if there are any items pending insertion, and move them to an + * active state. Finally, it will return a list of active items for further processing. + * + * @method Phaser.Structs.ProcessQueue#update + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} A list of active items. + */ + update: function () + { + if (this._toProcess === 0) + { + // Quick bail + return this._active; + } + + var list = this._destroy; + var active = this._active; + var i; + var item; + + // Clear the 'destroy' list + for (i = 0; i < list.length; i++) + { + item = list[i]; + + // Remove from the 'active' array + var idx = active.indexOf(item); + + if (idx !== -1) + { + active.splice(idx, 1); + + this.emit(Events.REMOVE, item); + } + } + + list.length = 0; + + // Process the pending addition list + // This stops callbacks and out of sync events from populating the active array mid-way during an update + + list = this._pending; + + for (i = 0; i < list.length; i++) + { + item = list[i]; + + this._active.push(item); + + this.emit(Events.ADD, item); + } + + list.length = 0; + + this._toProcess = 0; + + // The owner of this queue can now safely do whatever it needs to with the active list + return this._active; + }, + + /** + * Returns the current list of active items. + * + * This method returns a reference to the active list array, not a copy of it. + * Therefore, be careful to not modify this array outside of the ProcessQueue. + * + * @method Phaser.Structs.ProcessQueue#getActive + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} A list of active items. + */ + getActive: function () + { + return this._active; + }, + + /** + * The number of entries in the active list. + * + * @name Phaser.Structs.ProcessQueue#length + * @type {integer} + * @readonly + * @since 3.20.0 + */ + length: { + + get: function () + { + return this._active.length; + } + + }, + + /** + * Immediately destroys this process queue, clearing all of its internal arrays and resetting the process totals. + * + * @method Phaser.Structs.ProcessQueue#destroy + * @since 3.0.0 + */ + destroy: function () + { + this._toProcess = 0; + + this._pending = []; + this._active = []; + this._destroy = []; + } + +}); + +module.exports = ProcessQueue; diff --git a/src/structs/RTree.js b/src/structs/RTree.js index 01bb5be09..883086c9d 100644 --- a/src/structs/RTree.js +++ b/src/structs/RTree.js @@ -1,606 +1,606 @@ -/** - * @author Vladimir Agafonkin - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var quickselect = require('../utils/array/QuickSelect'); - -/** - * @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 - */ - -function rbush (maxEntries) -{ - var format = [ '.left', '.top', '.right', '.bottom' ]; - - if (!(this instanceof rbush)) return new rbush(maxEntries, format); - - // max entries in a node is 9 by default; min node fill is 40% for best performance - this._maxEntries = Math.max(4, maxEntries || 9); - this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)); - - this.clear(); -} - -rbush.prototype = { - - all: function () - { - return this._all(this.data, []); - }, - - search: function (bbox) - { - var node = this.data, - result = [], - toBBox = this.toBBox; - - if (!intersects(bbox, node)) return result; - - var nodesToSearch = [], - i, len, child, childBBox; - - while (node) { - for (i = 0, len = node.children.length; i < len; i++) { - - child = node.children[i]; - childBBox = node.leaf ? toBBox(child) : child; - - if (intersects(bbox, childBBox)) { - if (node.leaf) result.push(child); - else if (contains(bbox, childBBox)) this._all(child, result); - else nodesToSearch.push(child); - } - } - node = nodesToSearch.pop(); - } - - return result; - }, - - collides: function (bbox) - { - var node = this.data, - toBBox = this.toBBox; - - if (!intersects(bbox, node)) return false; - - var nodesToSearch = [], - i, len, child, childBBox; - - while (node) { - for (i = 0, len = node.children.length; i < len; i++) { - - child = node.children[i]; - childBBox = node.leaf ? toBBox(child) : child; - - if (intersects(bbox, childBBox)) { - if (node.leaf || contains(bbox, childBBox)) return true; - nodesToSearch.push(child); - } - } - node = nodesToSearch.pop(); - } - - return false; - }, - - load: function (data) - { - if (!(data && data.length)) return this; - - if (data.length < this._minEntries) { - for (var i = 0, len = data.length; i < len; i++) { - this.insert(data[i]); - } - return this; - } - - // recursively build the tree with the given data from scratch using OMT algorithm - var node = this._build(data.slice(), 0, data.length - 1, 0); - - if (!this.data.children.length) { - // save as is if tree is empty - this.data = node; - - } else if (this.data.height === node.height) { - // split root if trees have the same height - this._splitRoot(this.data, node); - - } else { - if (this.data.height < node.height) { - // swap trees if inserted one is bigger - var tmpNode = this.data; - this.data = node; - node = tmpNode; - } - - // insert the small tree into the large tree at appropriate level - this._insert(node, this.data.height - node.height - 1, true); - } - - return this; - }, - - insert: function (item) - { - if (item) this._insert(item, this.data.height - 1); - return this; - }, - - clear: function () - { - this.data = createNode([]); - return this; - }, - - remove: function (item, equalsFn) - { - if (!item) return this; - - var node = this.data, - bbox = this.toBBox(item), - path = [], - indexes = [], - i, parent, index, goingUp; - - // depth-first iterative tree traversal - while (node || path.length) { - - if (!node) { // go up - node = path.pop(); - parent = path[path.length - 1]; - i = indexes.pop(); - goingUp = true; - } - - if (node.leaf) { // check current node - index = findItem(item, node.children, equalsFn); - - if (index !== -1) { - // item found, remove the item and condense tree upwards - node.children.splice(index, 1); - path.push(node); - this._condense(path); - return this; - } - } - - if (!goingUp && !node.leaf && contains(node, bbox)) { // go down - path.push(node); - indexes.push(i); - i = 0; - parent = node; - node = node.children[0]; - - } else if (parent) { // go right - i++; - node = parent.children[i]; - goingUp = false; - - } else node = null; // nothing found - } - - return this; - }, - - toBBox: function (item) { return item; }, - - compareMinX: compareNodeMinX, - compareMinY: compareNodeMinY, - - toJSON: function () { return this.data; }, - - fromJSON: function (data) - { - this.data = data; - return this; - }, - - _all: function (node, result) - { - var nodesToSearch = []; - while (node) { - if (node.leaf) result.push.apply(result, node.children); - else nodesToSearch.push.apply(nodesToSearch, node.children); - - node = nodesToSearch.pop(); - } - return result; - }, - - _build: function (items, left, right, height) - { - var N = right - left + 1, - M = this._maxEntries, - node; - - if (N <= M) { - // reached leaf level; return leaf - node = createNode(items.slice(left, right + 1)); - calcBBox(node, this.toBBox); - return node; - } - - if (!height) { - // target height of the bulk-loaded tree - height = Math.ceil(Math.log(N) / Math.log(M)); - - // target number of root entries to maximize storage utilization - M = Math.ceil(N / Math.pow(M, height - 1)); - } - - node = createNode([]); - node.leaf = false; - node.height = height; - - // split the items into M mostly square tiles - - var N2 = Math.ceil(N / M), - N1 = N2 * Math.ceil(Math.sqrt(M)), - i, j, right2, right3; - - multiSelect(items, left, right, N1, this.compareMinX); - - for (i = left; i <= right; i += N1) { - - right2 = Math.min(i + N1 - 1, right); - - multiSelect(items, i, right2, N2, this.compareMinY); - - for (j = i; j <= right2; j += N2) { - - right3 = Math.min(j + N2 - 1, right2); - - // pack each entry recursively - node.children.push(this._build(items, j, right3, height - 1)); - } - } - - calcBBox(node, this.toBBox); - - return node; - }, - - _chooseSubtree: function (bbox, node, level, path) - { - var i, len, child, targetNode, area, enlargement, minArea, minEnlargement; - - while (true) { - path.push(node); - - if (node.leaf || path.length - 1 === level) break; - - minArea = minEnlargement = Infinity; - - for (i = 0, len = node.children.length; i < len; i++) { - child = node.children[i]; - area = bboxArea(child); - enlargement = enlargedArea(bbox, child) - area; - - // choose entry with the least area enlargement - if (enlargement < minEnlargement) { - minEnlargement = enlargement; - minArea = area < minArea ? area : minArea; - targetNode = child; - - } else if (enlargement === minEnlargement) { - // otherwise choose one with the smallest area - if (area < minArea) { - minArea = area; - targetNode = child; - } - } - } - - node = targetNode || node.children[0]; - } - - return node; - }, - - _insert: function (item, level, isNode) - { - var toBBox = this.toBBox, - bbox = isNode ? item : toBBox(item), - insertPath = []; - - // find the best node for accommodating the item, saving all nodes along the path too - var node = this._chooseSubtree(bbox, this.data, level, insertPath); - - // put the item into the node - node.children.push(item); - extend(node, bbox); - - // split on node overflow; propagate upwards if necessary - while (level >= 0) { - if (insertPath[level].children.length > this._maxEntries) { - this._split(insertPath, level); - level--; - } else break; - } - - // adjust bboxes along the insertion path - this._adjustParentBBoxes(bbox, insertPath, level); - }, - - // split overflowed node into two - _split: function (insertPath, level) - { - var node = insertPath[level], - M = node.children.length, - m = this._minEntries; - - this._chooseSplitAxis(node, m, M); - - var splitIndex = this._chooseSplitIndex(node, m, M); - - var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); - newNode.height = node.height; - newNode.leaf = node.leaf; - - calcBBox(node, this.toBBox); - calcBBox(newNode, this.toBBox); - - if (level) insertPath[level - 1].children.push(newNode); - else this._splitRoot(node, newNode); - }, - - _splitRoot: function (node, newNode) - { - // split root node - this.data = createNode([node, newNode]); - this.data.height = node.height + 1; - this.data.leaf = false; - calcBBox(this.data, this.toBBox); - }, - - _chooseSplitIndex: function (node, m, M) - { - var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index; - - minOverlap = minArea = Infinity; - - for (i = m; i <= M - m; i++) { - bbox1 = distBBox(node, 0, i, this.toBBox); - bbox2 = distBBox(node, i, M, this.toBBox); - - overlap = intersectionArea(bbox1, bbox2); - area = bboxArea(bbox1) + bboxArea(bbox2); - - // choose distribution with minimum overlap - if (overlap < minOverlap) { - minOverlap = overlap; - index = i; - - minArea = area < minArea ? area : minArea; - - } else if (overlap === minOverlap) { - // otherwise choose distribution with minimum area - if (area < minArea) { - minArea = area; - index = i; - } - } - } - - return index; - }, - - // sorts node children by the best axis for split - _chooseSplitAxis: function (node, m, M) - { - var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX, - compareMinY = node.leaf ? this.compareMinY : compareNodeMinY, - xMargin = this._allDistMargin(node, m, M, compareMinX), - yMargin = this._allDistMargin(node, m, M, compareMinY); - - // if total distributions margin value is minimal for x, sort by minX, - // otherwise it's already sorted by minY - if (xMargin < yMargin) node.children.sort(compareMinX); - }, - - // total margin of all possible split distributions where each node is at least m full - _allDistMargin: function (node, m, M, compare) - { - node.children.sort(compare); - - var toBBox = this.toBBox, - leftBBox = distBBox(node, 0, m, toBBox), - rightBBox = distBBox(node, M - m, M, toBBox), - margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), - i, child; - - for (i = m; i < M - m; i++) { - child = node.children[i]; - extend(leftBBox, node.leaf ? toBBox(child) : child); - margin += bboxMargin(leftBBox); - } - - for (i = M - m - 1; i >= m; i--) { - child = node.children[i]; - extend(rightBBox, node.leaf ? toBBox(child) : child); - margin += bboxMargin(rightBBox); - } - - return margin; - }, - - _adjustParentBBoxes: function (bbox, path, level) - { - // adjust bboxes along the given tree path - for (var i = level; i >= 0; i--) { - extend(path[i], bbox); - } - }, - - _condense: function (path) - { - // go through the path, removing empty nodes and updating bboxes - for (var i = path.length - 1, siblings; i >= 0; i--) { - if (path[i].children.length === 0) { - if (i > 0) { - siblings = path[i - 1].children; - siblings.splice(siblings.indexOf(path[i]), 1); - - } else this.clear(); - - } else calcBBox(path[i], this.toBBox); - } - }, - - compareMinX: function (a, b) - { - return a.left - b.left; - }, - - compareMinY: function (a, b) - { - return a.top - b.top; - }, - - toBBox: function (a) - { - return { - minX: a.left, - minY: a.top, - maxX: a.right, - maxY: a.bottom - }; - } -}; - -function findItem (item, items, equalsFn) -{ - if (!equalsFn) return items.indexOf(item); - - for (var i = 0; i < items.length; i++) { - if (equalsFn(item, items[i])) return i; - } - return -1; -} - -// calculate node's bbox from bboxes of its children -function calcBBox (node, toBBox) -{ - distBBox(node, 0, node.children.length, toBBox, node); -} - -// min bounding rectangle of node children from k to p-1 -function distBBox (node, k, p, toBBox, destNode) -{ - if (!destNode) destNode = createNode(null); - destNode.minX = Infinity; - destNode.minY = Infinity; - destNode.maxX = -Infinity; - destNode.maxY = -Infinity; - - for (var i = k, child; i < p; i++) { - child = node.children[i]; - extend(destNode, node.leaf ? toBBox(child) : child); - } - - return destNode; -} - -function extend (a, b) -{ - a.minX = Math.min(a.minX, b.minX); - a.minY = Math.min(a.minY, b.minY); - a.maxX = Math.max(a.maxX, b.maxX); - a.maxY = Math.max(a.maxY, b.maxY); - return a; -} - -function compareNodeMinX (a, b) { return a.minX - b.minX; } -function compareNodeMinY (a, b) { return a.minY - b.minY; } - -function bboxArea (a) { return (a.maxX - a.minX) * (a.maxY - a.minY); } -function bboxMargin (a) { return (a.maxX - a.minX) + (a.maxY - a.minY); } - -function enlargedArea (a, b) -{ - return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * - (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)); -} - -function intersectionArea (a, b) -{ - var minX = Math.max(a.minX, b.minX), - minY = Math.max(a.minY, b.minY), - maxX = Math.min(a.maxX, b.maxX), - maxY = Math.min(a.maxY, b.maxY); - - return Math.max(0, maxX - minX) * - Math.max(0, maxY - minY); -} - -function contains (a, b) -{ - return a.minX <= b.minX && - a.minY <= b.minY && - b.maxX <= a.maxX && - b.maxY <= a.maxY; -} - -function intersects (a, b) -{ - return b.minX <= a.maxX && - b.minY <= a.maxY && - b.maxX >= a.minX && - b.maxY >= a.minY; -} - -function createNode (children) -{ - return { - children: children, - height: 1, - leaf: true, - minX: Infinity, - minY: Infinity, - maxX: -Infinity, - maxY: -Infinity - }; -} - -// 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 - -function multiSelect (arr, left, right, n, compare) -{ - var stack = [left, right], - mid; - - while (stack.length) - { - right = stack.pop(); - left = stack.pop(); - - if (right - left <= n) continue; - - mid = left + Math.ceil((right - left) / n / 2) * n; - quickselect(arr, mid, left, right, compare); - - stack.push(left, mid, mid, right); - } -} - +/** + * @author Vladimir Agafonkin + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var quickselect = require('../utils/array/QuickSelect'); + +/** + * @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 + */ + +function rbush (maxEntries) +{ + var format = [ '.left', '.top', '.right', '.bottom' ]; + + if (!(this instanceof rbush)) return new rbush(maxEntries, format); + + // max entries in a node is 9 by default; min node fill is 40% for best performance + this._maxEntries = Math.max(4, maxEntries || 9); + this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)); + + this.clear(); +} + +rbush.prototype = { + + all: function () + { + return this._all(this.data, []); + }, + + search: function (bbox) + { + var node = this.data, + result = [], + toBBox = this.toBBox; + + if (!intersects(bbox, node)) return result; + + var nodesToSearch = [], + i, len, child, childBBox; + + while (node) { + for (i = 0, len = node.children.length; i < len; i++) { + + child = node.children[i]; + childBBox = node.leaf ? toBBox(child) : child; + + if (intersects(bbox, childBBox)) { + if (node.leaf) result.push(child); + else if (contains(bbox, childBBox)) this._all(child, result); + else nodesToSearch.push(child); + } + } + node = nodesToSearch.pop(); + } + + return result; + }, + + collides: function (bbox) + { + var node = this.data, + toBBox = this.toBBox; + + if (!intersects(bbox, node)) return false; + + var nodesToSearch = [], + i, len, child, childBBox; + + while (node) { + for (i = 0, len = node.children.length; i < len; i++) { + + child = node.children[i]; + childBBox = node.leaf ? toBBox(child) : child; + + if (intersects(bbox, childBBox)) { + if (node.leaf || contains(bbox, childBBox)) return true; + nodesToSearch.push(child); + } + } + node = nodesToSearch.pop(); + } + + return false; + }, + + load: function (data) + { + if (!(data && data.length)) return this; + + if (data.length < this._minEntries) { + for (var i = 0, len = data.length; i < len; i++) { + this.insert(data[i]); + } + return this; + } + + // recursively build the tree with the given data from scratch using OMT algorithm + var node = this._build(data.slice(), 0, data.length - 1, 0); + + if (!this.data.children.length) { + // save as is if tree is empty + this.data = node; + + } else if (this.data.height === node.height) { + // split root if trees have the same height + this._splitRoot(this.data, node); + + } else { + if (this.data.height < node.height) { + // swap trees if inserted one is bigger + var tmpNode = this.data; + this.data = node; + node = tmpNode; + } + + // insert the small tree into the large tree at appropriate level + this._insert(node, this.data.height - node.height - 1, true); + } + + return this; + }, + + insert: function (item) + { + if (item) this._insert(item, this.data.height - 1); + return this; + }, + + clear: function () + { + this.data = createNode([]); + return this; + }, + + remove: function (item, equalsFn) + { + if (!item) return this; + + var node = this.data, + bbox = this.toBBox(item), + path = [], + indexes = [], + i, parent, index, goingUp; + + // depth-first iterative tree traversal + while (node || path.length) { + + if (!node) { // go up + node = path.pop(); + parent = path[path.length - 1]; + i = indexes.pop(); + goingUp = true; + } + + if (node.leaf) { // check current node + index = findItem(item, node.children, equalsFn); + + if (index !== -1) { + // item found, remove the item and condense tree upwards + node.children.splice(index, 1); + path.push(node); + this._condense(path); + return this; + } + } + + if (!goingUp && !node.leaf && contains(node, bbox)) { // go down + path.push(node); + indexes.push(i); + i = 0; + parent = node; + node = node.children[0]; + + } else if (parent) { // go right + i++; + node = parent.children[i]; + goingUp = false; + + } else node = null; // nothing found + } + + return this; + }, + + toBBox: function (item) { return item; }, + + compareMinX: compareNodeMinX, + compareMinY: compareNodeMinY, + + toJSON: function () { return this.data; }, + + fromJSON: function (data) + { + this.data = data; + return this; + }, + + _all: function (node, result) + { + var nodesToSearch = []; + while (node) { + if (node.leaf) result.push.apply(result, node.children); + else nodesToSearch.push.apply(nodesToSearch, node.children); + + node = nodesToSearch.pop(); + } + return result; + }, + + _build: function (items, left, right, height) + { + var N = right - left + 1, + M = this._maxEntries, + node; + + if (N <= M) { + // reached leaf level; return leaf + node = createNode(items.slice(left, right + 1)); + calcBBox(node, this.toBBox); + return node; + } + + if (!height) { + // target height of the bulk-loaded tree + height = Math.ceil(Math.log(N) / Math.log(M)); + + // target number of root entries to maximize storage utilization + M = Math.ceil(N / Math.pow(M, height - 1)); + } + + node = createNode([]); + node.leaf = false; + node.height = height; + + // split the items into M mostly square tiles + + var N2 = Math.ceil(N / M), + N1 = N2 * Math.ceil(Math.sqrt(M)), + i, j, right2, right3; + + multiSelect(items, left, right, N1, this.compareMinX); + + for (i = left; i <= right; i += N1) { + + right2 = Math.min(i + N1 - 1, right); + + multiSelect(items, i, right2, N2, this.compareMinY); + + for (j = i; j <= right2; j += N2) { + + right3 = Math.min(j + N2 - 1, right2); + + // pack each entry recursively + node.children.push(this._build(items, j, right3, height - 1)); + } + } + + calcBBox(node, this.toBBox); + + return node; + }, + + _chooseSubtree: function (bbox, node, level, path) + { + var i, len, child, targetNode, area, enlargement, minArea, minEnlargement; + + while (true) { + path.push(node); + + if (node.leaf || path.length - 1 === level) break; + + minArea = minEnlargement = Infinity; + + for (i = 0, len = node.children.length; i < len; i++) { + child = node.children[i]; + area = bboxArea(child); + enlargement = enlargedArea(bbox, child) - area; + + // choose entry with the least area enlargement + if (enlargement < minEnlargement) { + minEnlargement = enlargement; + minArea = area < minArea ? area : minArea; + targetNode = child; + + } else if (enlargement === minEnlargement) { + // otherwise choose one with the smallest area + if (area < minArea) { + minArea = area; + targetNode = child; + } + } + } + + node = targetNode || node.children[0]; + } + + return node; + }, + + _insert: function (item, level, isNode) + { + var toBBox = this.toBBox, + bbox = isNode ? item : toBBox(item), + insertPath = []; + + // find the best node for accommodating the item, saving all nodes along the path too + var node = this._chooseSubtree(bbox, this.data, level, insertPath); + + // put the item into the node + node.children.push(item); + extend(node, bbox); + + // split on node overflow; propagate upwards if necessary + while (level >= 0) { + if (insertPath[level].children.length > this._maxEntries) { + this._split(insertPath, level); + level--; + } else break; + } + + // adjust bboxes along the insertion path + this._adjustParentBBoxes(bbox, insertPath, level); + }, + + // split overflowed node into two + _split: function (insertPath, level) + { + var node = insertPath[level], + M = node.children.length, + m = this._minEntries; + + this._chooseSplitAxis(node, m, M); + + var splitIndex = this._chooseSplitIndex(node, m, M); + + var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); + newNode.height = node.height; + newNode.leaf = node.leaf; + + calcBBox(node, this.toBBox); + calcBBox(newNode, this.toBBox); + + if (level) insertPath[level - 1].children.push(newNode); + else this._splitRoot(node, newNode); + }, + + _splitRoot: function (node, newNode) + { + // split root node + this.data = createNode([node, newNode]); + this.data.height = node.height + 1; + this.data.leaf = false; + calcBBox(this.data, this.toBBox); + }, + + _chooseSplitIndex: function (node, m, M) + { + var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index; + + minOverlap = minArea = Infinity; + + for (i = m; i <= M - m; i++) { + bbox1 = distBBox(node, 0, i, this.toBBox); + bbox2 = distBBox(node, i, M, this.toBBox); + + overlap = intersectionArea(bbox1, bbox2); + area = bboxArea(bbox1) + bboxArea(bbox2); + + // choose distribution with minimum overlap + if (overlap < minOverlap) { + minOverlap = overlap; + index = i; + + minArea = area < minArea ? area : minArea; + + } else if (overlap === minOverlap) { + // otherwise choose distribution with minimum area + if (area < minArea) { + minArea = area; + index = i; + } + } + } + + return index; + }, + + // sorts node children by the best axis for split + _chooseSplitAxis: function (node, m, M) + { + var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX, + compareMinY = node.leaf ? this.compareMinY : compareNodeMinY, + xMargin = this._allDistMargin(node, m, M, compareMinX), + yMargin = this._allDistMargin(node, m, M, compareMinY); + + // if total distributions margin value is minimal for x, sort by minX, + // otherwise it's already sorted by minY + if (xMargin < yMargin) node.children.sort(compareMinX); + }, + + // total margin of all possible split distributions where each node is at least m full + _allDistMargin: function (node, m, M, compare) + { + node.children.sort(compare); + + var toBBox = this.toBBox, + leftBBox = distBBox(node, 0, m, toBBox), + rightBBox = distBBox(node, M - m, M, toBBox), + margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), + i, child; + + for (i = m; i < M - m; i++) { + child = node.children[i]; + extend(leftBBox, node.leaf ? toBBox(child) : child); + margin += bboxMargin(leftBBox); + } + + for (i = M - m - 1; i >= m; i--) { + child = node.children[i]; + extend(rightBBox, node.leaf ? toBBox(child) : child); + margin += bboxMargin(rightBBox); + } + + return margin; + }, + + _adjustParentBBoxes: function (bbox, path, level) + { + // adjust bboxes along the given tree path + for (var i = level; i >= 0; i--) { + extend(path[i], bbox); + } + }, + + _condense: function (path) + { + // go through the path, removing empty nodes and updating bboxes + for (var i = path.length - 1, siblings; i >= 0; i--) { + if (path[i].children.length === 0) { + if (i > 0) { + siblings = path[i - 1].children; + siblings.splice(siblings.indexOf(path[i]), 1); + + } else this.clear(); + + } else calcBBox(path[i], this.toBBox); + } + }, + + compareMinX: function (a, b) + { + return a.left - b.left; + }, + + compareMinY: function (a, b) + { + return a.top - b.top; + }, + + toBBox: function (a) + { + return { + minX: a.left, + minY: a.top, + maxX: a.right, + maxY: a.bottom + }; + } +}; + +function findItem (item, items, equalsFn) +{ + if (!equalsFn) return items.indexOf(item); + + for (var i = 0; i < items.length; i++) { + if (equalsFn(item, items[i])) return i; + } + return -1; +} + +// calculate node's bbox from bboxes of its children +function calcBBox (node, toBBox) +{ + distBBox(node, 0, node.children.length, toBBox, node); +} + +// min bounding rectangle of node children from k to p-1 +function distBBox (node, k, p, toBBox, destNode) +{ + if (!destNode) destNode = createNode(null); + destNode.minX = Infinity; + destNode.minY = Infinity; + destNode.maxX = -Infinity; + destNode.maxY = -Infinity; + + for (var i = k, child; i < p; i++) { + child = node.children[i]; + extend(destNode, node.leaf ? toBBox(child) : child); + } + + return destNode; +} + +function extend (a, b) +{ + a.minX = Math.min(a.minX, b.minX); + a.minY = Math.min(a.minY, b.minY); + a.maxX = Math.max(a.maxX, b.maxX); + a.maxY = Math.max(a.maxY, b.maxY); + return a; +} + +function compareNodeMinX (a, b) { return a.minX - b.minX; } +function compareNodeMinY (a, b) { return a.minY - b.minY; } + +function bboxArea (a) { return (a.maxX - a.minX) * (a.maxY - a.minY); } +function bboxMargin (a) { return (a.maxX - a.minX) + (a.maxY - a.minY); } + +function enlargedArea (a, b) +{ + return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * + (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)); +} + +function intersectionArea (a, b) +{ + var minX = Math.max(a.minX, b.minX), + minY = Math.max(a.minY, b.minY), + maxX = Math.min(a.maxX, b.maxX), + maxY = Math.min(a.maxY, b.maxY); + + return Math.max(0, maxX - minX) * + Math.max(0, maxY - minY); +} + +function contains (a, b) +{ + return a.minX <= b.minX && + a.minY <= b.minY && + b.maxX <= a.maxX && + b.maxY <= a.maxY; +} + +function intersects (a, b) +{ + return b.minX <= a.maxX && + b.minY <= a.maxY && + b.maxX >= a.minX && + b.maxY >= a.minY; +} + +function createNode (children) +{ + return { + children: children, + height: 1, + leaf: true, + minX: Infinity, + minY: Infinity, + maxX: -Infinity, + maxY: -Infinity + }; +} + +// 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 + +function multiSelect (arr, left, right, n, compare) +{ + var stack = [left, right], + mid; + + while (stack.length) + { + right = stack.pop(); + left = stack.pop(); + + if (right - left <= n) continue; + + mid = left + Math.ceil((right - left) / n / 2) * n; + quickselect(arr, mid, left, right, compare); + + stack.push(left, mid, mid, right); + } +} + module.exports = rbush; \ No newline at end of file diff --git a/src/structs/Set.js b/src/structs/Set.js index b2911a8cb..d31b936a7 100644 --- a/src/structs/Set.js +++ b/src/structs/Set.js @@ -1,443 +1,443 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); - -/** - * @callback EachSetCallback - * - * @param {E} entry - The Set entry. - * @param {number} index - The index of the entry within the Set. - * - * @return {?boolean} The callback result. - */ - -/** - * @classdesc - * A Set is a collection of unique elements. - * - * @class Set - * @memberof Phaser.Structs - * @constructor - * @since 3.0.0 - * - * @generic T - * @genericUse {T[]} - [elements] - * - * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. - */ -var Set = new Class({ - - initialize: - - function Set (elements) - { - /** - * The entries of this Set. Stored internally as an array. - * - * @genericUse {T[]} - [$type] - * - * @name Phaser.Structs.Set#entries - * @type {Array.<*>} - * @default [] - * @since 3.0.0 - */ - this.entries = []; - - if (Array.isArray(elements)) - { - for (var i = 0; i < elements.length; i++) - { - this.set(elements[i]); - } - } - }, - - /** - * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. - * - * @method Phaser.Structs.Set#set - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {*} value - The value to insert into this Set. - * - * @return {Phaser.Structs.Set} This Set object. - */ - set: function (value) - { - if (this.entries.indexOf(value) === -1) - { - this.entries.push(value); - } - - return this; - }, - - /** - * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. - * If no elements of this Set satisfy the condition then this method will return `null`. - * - * @method Phaser.Structs.Set#get - * @since 3.0.0 - * - * @genericUse {T} - [value,$return] - * - * @param {string} property - The property name to check on the elements of this Set. - * @param {*} value - The value to check for. - * - * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. - */ - get: function (property, value) - { - for (var i = 0; i < this.entries.length; i++) - { - var entry = this.entries[i]; - - if (entry[property] === value) - { - return entry; - } - } - }, - - /** - * Returns an array containing all the values in this Set. - * - * @method Phaser.Structs.Set#getArray - * @since 3.0.0 - * - * @genericUse {T[]} - [$return] - * - * @return {Array.<*>} An array containing all the values in this Set. - */ - getArray: function () - { - return this.entries.slice(0); - }, - - /** - * Removes the given value from this Set if this Set contains that value. - * - * @method Phaser.Structs.Set#delete - * @since 3.0.0 - * - * @genericUse {T} - [value] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {*} value - The value to remove from the Set. - * - * @return {Phaser.Structs.Set} This Set object. - */ - delete: function (value) - { - var index = this.entries.indexOf(value); - - if (index > -1) - { - this.entries.splice(index, 1); - } - - return this; - }, - - /** - * Dumps the contents of this Set to the console via `console.group`. - * - * @method Phaser.Structs.Set#dump - * @since 3.0.0 - */ - dump: function () - { - // eslint-disable-next-line no-console - console.group('Set'); - - for (var i = 0; i < this.entries.length; i++) - { - var entry = this.entries[i]; - console.log(entry); - } - - // eslint-disable-next-line no-console - console.groupEnd(); - }, - - /** - * Passes each value in this Set to the given callback. - * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. - * - * @method Phaser.Structs.Set#each - * @since 3.0.0 - * - * @genericUse {EachSetCallback.} - [callback] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. - * @param {*} [callbackScope] - The scope of the callback. - * - * @return {Phaser.Structs.Set} This Set object. - */ - each: function (callback, callbackScope) - { - var i; - var temp = this.entries.slice(); - var len = temp.length; - - if (callbackScope) - { - for (i = 0; i < len; i++) - { - if (callback.call(callbackScope, temp[i], i) === false) - { - break; - } - } - } - else - { - for (i = 0; i < len; i++) - { - if (callback(temp[i], i) === false) - { - break; - } - } - } - - return this; - }, - - /** - * Passes each value in this Set to the given callback. - * For when you absolutely know this Set won't be modified during the iteration. - * - * @method Phaser.Structs.Set#iterate - * @since 3.0.0 - * - * @genericUse {EachSetCallback.} - [callback] - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. - * @param {*} [callbackScope] - The scope of the callback. - * - * @return {Phaser.Structs.Set} This Set object. - */ - iterate: function (callback, callbackScope) - { - var i; - var len = this.entries.length; - - if (callbackScope) - { - for (i = 0; i < len; i++) - { - if (callback.call(callbackScope, this.entries[i], i) === false) - { - break; - } - } - } - else - { - for (i = 0; i < len; i++) - { - if (callback(this.entries[i], i) === false) - { - break; - } - } - } - - return this; - }, - - /** - * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. - * - * @method Phaser.Structs.Set#iterateLocal - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @param {string} callbackKey - The key of the function to be invoked on each Set entry. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - * - * @return {Phaser.Structs.Set} This Set object. - */ - iterateLocal: function (callbackKey) - { - var i; - var args = []; - - for (i = 1; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - var len = this.entries.length; - - for (i = 0; i < len; i++) - { - var entry = this.entries[i]; - - entry[callbackKey].apply(entry, args); - } - - return this; - }, - - /** - * Clears this Set so that it no longer contains any values. - * - * @method Phaser.Structs.Set#clear - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [$return] - * - * @return {Phaser.Structs.Set} This Set object. - */ - clear: function () - { - this.entries.length = 0; - - return this; - }, - - /** - * Returns `true` if this Set contains the given value, otherwise returns `false`. - * - * @method Phaser.Structs.Set#contains - * @since 3.0.0 - * - * @genericUse {T} - [value] - * - * @param {*} value - The value to check for in this Set. - * - * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. - */ - contains: function (value) - { - return (this.entries.indexOf(value) > -1); - }, - - /** - * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. - * - * @method Phaser.Structs.Set#union - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to perform the union with. - * - * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. - */ - union: function (set) - { - var newSet = new Set(); - - set.entries.forEach(function (value) - { - newSet.set(value); - }); - - this.entries.forEach(function (value) - { - newSet.set(value); - }); - - return newSet; - }, - - /** - * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. - * - * @method Phaser.Structs.Set#intersect - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to intersect this set with. - * - * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. - */ - intersect: function (set) - { - var newSet = new Set(); - - this.entries.forEach(function (value) - { - if (set.contains(value)) - { - newSet.set(value); - } - }); - - return newSet; - }, - - /** - * Returns a new Set containing all the values in this Set which are *not* also in the given Set. - * - * @method Phaser.Structs.Set#difference - * @since 3.0.0 - * - * @genericUse {Phaser.Structs.Set.} - [set,$return] - * - * @param {Phaser.Structs.Set} set - The Set to perform the difference with. - * - * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. - */ - difference: function (set) - { - var newSet = new Set(); - - this.entries.forEach(function (value) - { - if (!set.contains(value)) - { - newSet.set(value); - } - }); - - return newSet; - }, - - /** - * The size of this Set. This is the number of entries within it. - * Changing the size will truncate the Set if the given value is smaller than the current size. - * Increasing the size larger than the current size has no effect. - * - * @name Phaser.Structs.Set#size - * @type {integer} - * @since 3.0.0 - */ - size: { - - get: function () - { - return this.entries.length; - }, - - set: function (value) - { - if (value < this.entries.length) - { - return this.entries.length = value; - } - else - { - return this.entries.length; - } - } - - } - -}); - -module.exports = Set; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); + +/** + * @callback EachSetCallback + * + * @param {E} entry - The Set entry. + * @param {number} index - The index of the entry within the Set. + * + * @return {?boolean} The callback result. + */ + +/** + * @classdesc + * A Set is a collection of unique elements. + * + * @class Set + * @memberof Phaser.Structs + * @constructor + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [elements] + * + * @param {Array.<*>} [elements] - An optional array of elements to insert into this Set. + */ +var Set = new Class({ + + initialize: + + function Set (elements) + { + /** + * The entries of this Set. Stored internally as an array. + * + * @genericUse {T[]} - [$type] + * + * @name Phaser.Structs.Set#entries + * @type {Array.<*>} + * @default [] + * @since 3.0.0 + */ + this.entries = []; + + if (Array.isArray(elements)) + { + for (var i = 0; i < elements.length; i++) + { + this.set(elements[i]); + } + } + }, + + /** + * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. + * + * @method Phaser.Structs.Set#set + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to insert into this Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + set: function (value) + { + if (this.entries.indexOf(value) === -1) + { + this.entries.push(value); + } + + return this; + }, + + /** + * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. + * If no elements of this Set satisfy the condition then this method will return `null`. + * + * @method Phaser.Structs.Set#get + * @since 3.0.0 + * + * @genericUse {T} - [value,$return] + * + * @param {string} property - The property name to check on the elements of this Set. + * @param {*} value - The value to check for. + * + * @return {*} The first element of this Set that meets the required condition, or `null` if this Set contains no elements that meet the condition. + */ + get: function (property, value) + { + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + + if (entry[property] === value) + { + return entry; + } + } + }, + + /** + * Returns an array containing all the values in this Set. + * + * @method Phaser.Structs.Set#getArray + * @since 3.0.0 + * + * @genericUse {T[]} - [$return] + * + * @return {Array.<*>} An array containing all the values in this Set. + */ + getArray: function () + { + return this.entries.slice(0); + }, + + /** + * Removes the given value from this Set if this Set contains that value. + * + * @method Phaser.Structs.Set#delete + * @since 3.0.0 + * + * @genericUse {T} - [value] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {*} value - The value to remove from the Set. + * + * @return {Phaser.Structs.Set} This Set object. + */ + delete: function (value) + { + var index = this.entries.indexOf(value); + + if (index > -1) + { + this.entries.splice(index, 1); + } + + return this; + }, + + /** + * Dumps the contents of this Set to the console via `console.group`. + * + * @method Phaser.Structs.Set#dump + * @since 3.0.0 + */ + dump: function () + { + // eslint-disable-next-line no-console + console.group('Set'); + + for (var i = 0; i < this.entries.length; i++) + { + var entry = this.entries[i]; + console.log(entry); + } + + // eslint-disable-next-line no-console + console.groupEnd(); + }, + + /** + * Passes each value in this Set to the given callback. + * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. + * + * @method Phaser.Structs.Set#each + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + each: function (callback, callbackScope) + { + var i; + var temp = this.entries.slice(); + var len = temp.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, temp[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(temp[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Passes each value in this Set to the given callback. + * For when you absolutely know this Set won't be modified during the iteration. + * + * @method Phaser.Structs.Set#iterate + * @since 3.0.0 + * + * @genericUse {EachSetCallback.} - [callback] + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {EachSetCallback} callback - The callback to be invoked and passed each value this Set contains. + * @param {*} [callbackScope] - The scope of the callback. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterate: function (callback, callbackScope) + { + var i; + var len = this.entries.length; + + if (callbackScope) + { + for (i = 0; i < len; i++) + { + if (callback.call(callbackScope, this.entries[i], i) === false) + { + break; + } + } + } + else + { + for (i = 0; i < len; i++) + { + if (callback(this.entries[i], i) === false) + { + break; + } + } + } + + return this; + }, + + /** + * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. + * + * @method Phaser.Structs.Set#iterateLocal + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @param {string} callbackKey - The key of the function to be invoked on each Set entry. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {Phaser.Structs.Set} This Set object. + */ + iterateLocal: function (callbackKey) + { + var i; + var args = []; + + for (i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + var len = this.entries.length; + + for (i = 0; i < len; i++) + { + var entry = this.entries[i]; + + entry[callbackKey].apply(entry, args); + } + + return this; + }, + + /** + * Clears this Set so that it no longer contains any values. + * + * @method Phaser.Structs.Set#clear + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [$return] + * + * @return {Phaser.Structs.Set} This Set object. + */ + clear: function () + { + this.entries.length = 0; + + return this; + }, + + /** + * Returns `true` if this Set contains the given value, otherwise returns `false`. + * + * @method Phaser.Structs.Set#contains + * @since 3.0.0 + * + * @genericUse {T} - [value] + * + * @param {*} value - The value to check for in this Set. + * + * @return {boolean} `true` if the given value was found in this Set, otherwise `false`. + */ + contains: function (value) + { + return (this.entries.indexOf(value) > -1); + }, + + /** + * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. + * + * @method Phaser.Structs.Set#union + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the union with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set and the Set provided as an argument. + */ + union: function (set) + { + var newSet = new Set(); + + set.entries.forEach(function (value) + { + newSet.set(value); + }); + + this.entries.forEach(function (value) + { + newSet.set(value); + }); + + return newSet; + }, + + /** + * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. + * + * @method Phaser.Structs.Set#intersect + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to intersect this set with. + * + * @return {Phaser.Structs.Set} The result of the intersection, as a new Set. + */ + intersect: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * Returns a new Set containing all the values in this Set which are *not* also in the given Set. + * + * @method Phaser.Structs.Set#difference + * @since 3.0.0 + * + * @genericUse {Phaser.Structs.Set.} - [set,$return] + * + * @param {Phaser.Structs.Set} set - The Set to perform the difference with. + * + * @return {Phaser.Structs.Set} A new Set containing all the values in this Set that are not also in the Set provided as an argument to this method. + */ + difference: function (set) + { + var newSet = new Set(); + + this.entries.forEach(function (value) + { + if (!set.contains(value)) + { + newSet.set(value); + } + }); + + return newSet; + }, + + /** + * The size of this Set. This is the number of entries within it. + * Changing the size will truncate the Set if the given value is smaller than the current size. + * Increasing the size larger than the current size has no effect. + * + * @name Phaser.Structs.Set#size + * @type {integer} + * @since 3.0.0 + */ + size: { + + get: function () + { + return this.entries.length; + }, + + set: function (value) + { + if (value < this.entries.length) + { + return this.entries.length = value; + } + else + { + return this.entries.length; + } + } + + } + +}); + +module.exports = Set; diff --git a/src/structs/Size.js b/src/structs/Size.js index 97c895d5f..ebc87c144 100644 --- a/src/structs/Size.js +++ b/src/structs/Size.js @@ -1,772 +1,772 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clamp = require('../math/Clamp'); -var Class = require('../utils/Class'); -var SnapFloor = require('../math/snap/SnapFloor'); -var Vector2 = require('../math/Vector2'); - -/** - * @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 {integer} [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. - */ -var Size = new Class({ - - initialize: - - function Size (width, height, aspectMode, parent) - { - if (width === undefined) { width = 0; } - if (height === undefined) { height = width; } - if (aspectMode === undefined) { aspectMode = 0; } - if (parent === undefined) { parent = null; } - - /** - * Internal width value. - * - * @name Phaser.Structs.Size#_width - * @type {number} - * @private - * @since 3.16.0 - */ - this._width = width; - - /** - * Internal height value. - * - * @name Phaser.Structs.Size#_height - * @type {number} - * @private - * @since 3.16.0 - */ - this._height = height; - - /** - * Internal parent reference. - * - * @name Phaser.Structs.Size#_parent - * @type {any} - * @private - * @since 3.16.0 - */ - this._parent = parent; - - /** - * The aspect mode this Size component will use when calculating its dimensions. - * This property is read-only. To change it use the `setAspectMode` method. - * - * @name Phaser.Structs.Size#aspectMode - * @type {integer} - * @readonly - * @since 3.16.0 - */ - this.aspectMode = aspectMode; - - /** - * The proportional relationship between the width and height. - * - * This property is read-only and is updated automatically when either the `width` or `height` properties are changed, - * depending on the aspect mode. - * - * @name Phaser.Structs.Size#aspectRatio - * @type {number} - * @readonly - * @since 3.16.0 - */ - this.aspectRatio = (height === 0) ? 1 : width / height; - - /** - * The minimum allowed width. - * Cannot be less than zero. - * This value is read-only. To change it see the `setMin` method. - * - * @name Phaser.Structs.Size#minWidth - * @type {number} - * @readonly - * @since 3.16.0 - */ - this.minWidth = 0; - - /** - * The minimum allowed height. - * Cannot be less than zero. - * This value is read-only. To change it see the `setMin` method. - * - * @name Phaser.Structs.Size#minHeight - * @type {number} - * @readonly - * @since 3.16.0 - */ - this.minHeight = 0; - - /** - * The maximum allowed width. - * This value is read-only. To change it see the `setMax` method. - * - * @name Phaser.Structs.Size#maxWidth - * @type {number} - * @readonly - * @since 3.16.0 - */ - this.maxWidth = Number.MAX_VALUE; - - /** - * The maximum allowed height. - * This value is read-only. To change it see the `setMax` method. - * - * @name Phaser.Structs.Size#maxHeight - * @type {number} - * @readonly - * @since 3.16.0 - */ - this.maxHeight = Number.MAX_VALUE; - - /** - * A Vector2 containing the horizontal and vertical snap values, which the width and height are snapped to during resizing. - * - * By default this is disabled. - * - * This property is read-only. To change it see the `setSnap` method. - * - * @name Phaser.Structs.Size#snapTo - * @type {Phaser.Math.Vector2} - * @readonly - * @since 3.16.0 - */ - this.snapTo = new Vector2(); - }, - - /** - * 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 {integer} [value=0] - The aspect mode value. - * - * @return {this} This Size component instance. - */ - setAspectMode: function (value) - { - if (value === undefined) { value = 0; } - - this.aspectMode = value; - - return this.setSize(this._width, this._height); - }, - - /** - * By setting a Snap To value when this Size component is modified its dimensions will automatically - * by snapped to the nearest grid slice, using floor. For example, if you have snap value of 16, - * and the width changes to 68, then it will snap down to 64 (the closest multiple of 16 when floored) - * - * Note that snapping takes place before adjustments by the parent, or the min / max settings. If these - * values are not multiples of the given snap values, then this can result in un-snapped dimensions. - * - * Call this method with no arguments to reset the snap values. - * - * Calling this method automatically recalculates the `width` and the `height`, if required. - * - * @method Phaser.Structs.Size#setSnap - * @since 3.16.0 - * - * @param {number} [snapWidth=0] - The amount to snap the width to. If you don't want to snap the width, pass a value of zero. - * @param {number} [snapHeight=snapWidth] - The amount to snap the height to. If not provided it will use the `snapWidth` value. If you don't want to snap the height, pass a value of zero. - * - * @return {this} This Size component instance. - */ - setSnap: function (snapWidth, snapHeight) - { - if (snapWidth === undefined) { snapWidth = 0; } - if (snapHeight === undefined) { snapHeight = snapWidth; } - - this.snapTo.set(snapWidth, snapHeight); - - return this.setSize(this._width, this._height); - }, - - /** - * 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. - */ - setParent: function (parent) - { - this._parent = parent; - - return this.setSize(this._width, this._height); - }, - - /** - * 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 exceed 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. - */ - setMin: function (width, height) - { - if (width === undefined) { width = 0; } - if (height === undefined) { height = width; } - - this.minWidth = Clamp(width, 0, this.maxWidth); - this.minHeight = Clamp(height, 0, this.maxHeight); - - return this.setSize(this._width, this._height); - }, - - /** - * 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 exceed 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. - */ - setMax: function (width, height) - { - if (width === undefined) { width = Number.MAX_VALUE; } - if (height === undefined) { height = width; } - - this.maxWidth = Clamp(width, this.minWidth, Number.MAX_VALUE); - this.maxHeight = Clamp(height, this.minHeight, Number.MAX_VALUE); - - return this.setSize(this._width, this._height); - }, - - /** - * 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. - */ - setSize: function (width, height) - { - if (width === undefined) { width = 0; } - if (height === undefined) { height = width; } - - switch (this.aspectMode) - { - case Size.NONE: - this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); - this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); - this.aspectRatio = (this._height === 0) ? 1 : this._width / this._height; - break; - - case Size.WIDTH_CONTROLS_HEIGHT: - this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); - this._height = this.getNewHeight(this._width * (1 / this.aspectRatio), false); - break; - - case Size.HEIGHT_CONTROLS_WIDTH: - this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); - this._width = this.getNewWidth(this._height * this.aspectRatio, false); - break; - - case Size.FIT: - this.constrain(width, height, true); - break; - - case Size.ENVELOP: - this.constrain(width, height, false); - break; - } - - return this; - }, - - /** - * Sets a new aspect ratio, overriding what was there previously. - * - * It then calls `setSize` immediately using the current dimensions. - * - * @method Phaser.Structs.Size#setAspectRatio - * @since 3.16.0 - * - * @param {number} ratio - The new aspect ratio. - * - * @return {this} This Size component instance. - */ - setAspectRatio: function (ratio) - { - this.aspectRatio = ratio; - - return this.setSize(this._width, this._height); - }, - - /** - * 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. - */ - resize: function (width, height) - { - this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); - this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); - this.aspectRatio = (this._height === 0) ? 1 : this._width / this._height; - - return this; - }, - - /** - * Takes a new width and passes it through the min/max clamp and then checks it doesn't exceed the parent width. - * - * @method Phaser.Structs.Size#getNewWidth - * @since 3.16.0 - * - * @param {number} value - The value to clamp and check. - * @param {boolean} [checkParent=true] - Check the given value against the parent, if set. - * - * @return {number} The modified width value. - */ - getNewWidth: function (value, checkParent) - { - if (checkParent === undefined) { checkParent = true; } - - value = Clamp(value, this.minWidth, this.maxWidth); - - if (checkParent && this._parent && value > this._parent.width) - { - value = Math.max(this.minWidth, this._parent.width); - } - - return value; - }, - - /** - * Takes a new height and passes it through the min/max clamp and then checks it doesn't exceed the parent height. - * - * @method Phaser.Structs.Size#getNewHeight - * @since 3.16.0 - * - * @param {number} value - The value to clamp and check. - * @param {boolean} [checkParent=true] - Check the given value against the parent, if set. - * - * @return {number} The modified height value. - */ - getNewHeight: function (value, checkParent) - { - if (checkParent === undefined) { checkParent = true; } - - value = Clamp(value, this.minHeight, this.maxHeight); - - if (checkParent && this._parent && value > this._parent.height) - { - value = Math.max(this.minHeight, this._parent.height); - } - - return value; - }, - - /** - * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. - * - * If `fit` is true there may be some space inside the target area which is not covered if its aspect ratio differs. - * If `fit` is false the size may extend further out than the target area if the aspect ratios differ. - * - * If this Size component has a parent set, then the width and height passed to this method will be clamped so - * it cannot exceed that of the parent. - * - * @method Phaser.Structs.Size#constrain - * @since 3.16.0 - * - * @param {number} [width=0] - The new width of the Size component. - * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. - * @param {boolean} [fit=true] - Perform a `fit` (true) constraint, or an `envelop` (false) constraint. - * - * @return {this} This Size component instance. - */ - constrain: function (width, height, fit) - { - if (width === undefined) { width = 0; } - if (height === undefined) { height = width; } - if (fit === undefined) { fit = true; } - - width = this.getNewWidth(width); - height = this.getNewHeight(height); - - var snap = this.snapTo; - var newRatio = (height === 0) ? 1 : width / height; - - if ((fit && this.aspectRatio > newRatio) || (!fit && this.aspectRatio < newRatio)) - { - // We need to change the height to fit the width - - width = SnapFloor(width, snap.x); - - height = width / this.aspectRatio; - - if (snap.y > 0) - { - height = SnapFloor(height, snap.y); - - // Reduce the width accordingly - width = height * this.aspectRatio; - } - } - else if ((fit && this.aspectRatio < newRatio) || (!fit && this.aspectRatio > newRatio)) - { - // We need to change the width to fit the height - - height = SnapFloor(height, snap.y); - - width = height * this.aspectRatio; - - if (snap.x > 0) - { - width = SnapFloor(width, snap.x); - - // Reduce the height accordingly - height = width * (1 / this.aspectRatio); - } - } - - this._width = width; - this._height = height; - - return this; - }, - - /** - * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. - * - * There may be some space inside the target area which is not covered if its aspect ratio differs. - * - * If this Size component has a parent set, then the width and height passed to this method will be clamped so - * it cannot exceed that of the parent. - * - * @method Phaser.Structs.Size#fitTo - * @since 3.16.0 - * - * @param {number} [width=0] - The new width of the Size component. - * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. - * - * @return {this} This Size component instance. - */ - fitTo: function (width, height) - { - return this.constrain(width, height, true); - }, - - /** - * The current `width` and `height` are adjusted so that they fully envelope the given dimensions, while keeping the aspect ratio. - * - * The size may extend further out than the target area if the aspect ratios differ. - * - * If this Size component has a parent set, then the values are clamped so that it never exceeds the parent - * on the longest axis. - * - * @method Phaser.Structs.Size#envelop - * @since 3.16.0 - * - * @param {number} [width=0] - The new width of the Size component. - * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. - * - * @return {this} This Size component instance. - */ - envelop: function (width, height) - { - return this.constrain(width, height, false); - }, - - /** - * Sets the width of this Size component. - * - * Depending on the aspect mode, changing the width may also update the height and aspect ratio. - * - * @method Phaser.Structs.Size#setWidth - * @since 3.16.0 - * - * @param {number} width - The new width of the Size component. - * - * @return {this} This Size component instance. - */ - setWidth: function (value) - { - return this.setSize(value, this._height); - }, - - /** - * Sets the height of this Size component. - * - * Depending on the aspect mode, changing the height may also update the width and aspect ratio. - * - * @method Phaser.Structs.Size#setHeight - * @since 3.16.0 - * - * @param {number} height - The new height of the Size component. - * - * @return {this} This Size component instance. - */ - setHeight: function (value) - { - return this.setSize(this._width, value); - }, - - /** - * Returns a string representation of this Size component. - * - * @method Phaser.Structs.Size#toString - * @since 3.16.0 - * - * @return {string} A string representation of this Size component. - */ - toString: function () - { - return '[{ Size (width=' + this._width + ' height=' + this._height + ' aspectRatio=' + this.aspectRatio + ' aspectMode=' + this.aspectMode + ') }]'; - }, - - /** - * Sets the values of this Size component to the `element.style.width` and `height` - * properties of the given DOM Element. The properties are set as `px` values. - * - * @method Phaser.Structs.Size#setCSS - * @since 3.17.0 - * - * @param {HTMLElement} element - The DOM Element to set the CSS style on. - */ - setCSS: function (element) - { - if (element && element.style) - { - element.style.width = this._width + 'px'; - element.style.height = this._height + 'px'; - } - }, - - /** - * Copies the aspect mode, aspect ratio, width and height from this Size component - * to the given Size component. Note that the parent, if set, is not copied across. - * - * @method Phaser.Structs.Size#copy - * @since 3.16.0 - * - * @param {Phaser.Structs.Size} destination - The Size component to copy the values to. - * - * @return {Phaser.Structs.Size} The updated destination Size component. - */ - copy: function (destination) - { - destination.setAspectMode(this.aspectMode); - - destination.aspectRatio = this.aspectRatio; - - return destination.setSize(this.width, this.height); - }, - - /** - * Destroys this Size component. - * - * This clears the local properties and any parent object, if set. - * - * A destroyed Size component cannot be re-used. - * - * @method Phaser.Structs.Size#destroy - * @since 3.16.0 - */ - destroy: function () - { - this._parent = null; - this.snapTo = null; - }, - - /** - * The width of this Size component. - * - * This value is clamped to the range specified by `minWidth` and `maxWidth`, if enabled. - * - * A width can never be less than zero. - * - * Changing this value will automatically update the `height` if the aspect ratio lock is enabled. - * You can also use the `setWidth` and `getWidth` methods. - * - * @name Phaser.Structs.Size#width - * @type {number} - * @since 3.16.0 - */ - width: { - - get: function () - { - return this._width; - }, - - set: function (value) - { - this.setSize(value, this._height); - } - - }, - - /** - * The height of this Size component. - * - * This value is clamped to the range specified by `minHeight` and `maxHeight`, if enabled. - * - * A height can never be less than zero. - * - * Changing this value will automatically update the `width` if the aspect ratio lock is enabled. - * You can also use the `setHeight` and `getHeight` methods. - * - * @name Phaser.Structs.Size#height - * @type {number} - * @since 3.16.0 - */ - height: { - - get: function () - { - return this._height; - }, - - set: function (value) - { - this.setSize(this._width, value); - } - - } - -}); - -/** - * Do not make the size fit the aspect ratio. Change the ratio when the size changes. - * - * @name Phaser.Structs.Size.NONE - * @constant - * @type {integer} - * @since 3.16.0 - */ -Size.NONE = 0; - -/** - * The height is automatically adjusted based on the width. - * - * @name Phaser.Structs.Size.WIDTH_CONTROLS_HEIGHT - * @constant - * @type {integer} - * @since 3.16.0 - */ -Size.WIDTH_CONTROLS_HEIGHT = 1; - -/** - * The width is automatically adjusted based on the height. - * - * @name Phaser.Structs.Size.HEIGHT_CONTROLS_WIDTH - * @constant - * @type {integer} - * @since 3.16.0 - */ -Size.HEIGHT_CONTROLS_WIDTH = 2; - -/** - * 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. - * - * @name Phaser.Structs.Size.FIT - * @constant - * @type {integer} - * @since 3.16.0 - */ -Size.FIT = 3; - -/** - * 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. - * - * @name Phaser.Structs.Size.ENVELOP - * @constant - * @type {integer} - * @since 3.16.0 - */ -Size.ENVELOP = 4; - -module.exports = Size; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clamp = require('../math/Clamp'); +var Class = require('../utils/Class'); +var SnapFloor = require('../math/snap/SnapFloor'); +var Vector2 = require('../math/Vector2'); + +/** + * @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 {integer} [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. + */ +var Size = new Class({ + + initialize: + + function Size (width, height, aspectMode, parent) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + if (aspectMode === undefined) { aspectMode = 0; } + if (parent === undefined) { parent = null; } + + /** + * Internal width value. + * + * @name Phaser.Structs.Size#_width + * @type {number} + * @private + * @since 3.16.0 + */ + this._width = width; + + /** + * Internal height value. + * + * @name Phaser.Structs.Size#_height + * @type {number} + * @private + * @since 3.16.0 + */ + this._height = height; + + /** + * Internal parent reference. + * + * @name Phaser.Structs.Size#_parent + * @type {any} + * @private + * @since 3.16.0 + */ + this._parent = parent; + + /** + * The aspect mode this Size component will use when calculating its dimensions. + * This property is read-only. To change it use the `setAspectMode` method. + * + * @name Phaser.Structs.Size#aspectMode + * @type {integer} + * @readonly + * @since 3.16.0 + */ + this.aspectMode = aspectMode; + + /** + * The proportional relationship between the width and height. + * + * This property is read-only and is updated automatically when either the `width` or `height` properties are changed, + * depending on the aspect mode. + * + * @name Phaser.Structs.Size#aspectRatio + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.aspectRatio = (height === 0) ? 1 : width / height; + + /** + * The minimum allowed width. + * Cannot be less than zero. + * This value is read-only. To change it see the `setMin` method. + * + * @name Phaser.Structs.Size#minWidth + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.minWidth = 0; + + /** + * The minimum allowed height. + * Cannot be less than zero. + * This value is read-only. To change it see the `setMin` method. + * + * @name Phaser.Structs.Size#minHeight + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.minHeight = 0; + + /** + * The maximum allowed width. + * This value is read-only. To change it see the `setMax` method. + * + * @name Phaser.Structs.Size#maxWidth + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.maxWidth = Number.MAX_VALUE; + + /** + * The maximum allowed height. + * This value is read-only. To change it see the `setMax` method. + * + * @name Phaser.Structs.Size#maxHeight + * @type {number} + * @readonly + * @since 3.16.0 + */ + this.maxHeight = Number.MAX_VALUE; + + /** + * A Vector2 containing the horizontal and vertical snap values, which the width and height are snapped to during resizing. + * + * By default this is disabled. + * + * This property is read-only. To change it see the `setSnap` method. + * + * @name Phaser.Structs.Size#snapTo + * @type {Phaser.Math.Vector2} + * @readonly + * @since 3.16.0 + */ + this.snapTo = new Vector2(); + }, + + /** + * 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 {integer} [value=0] - The aspect mode value. + * + * @return {this} This Size component instance. + */ + setAspectMode: function (value) + { + if (value === undefined) { value = 0; } + + this.aspectMode = value; + + return this.setSize(this._width, this._height); + }, + + /** + * By setting a Snap To value when this Size component is modified its dimensions will automatically + * by snapped to the nearest grid slice, using floor. For example, if you have snap value of 16, + * and the width changes to 68, then it will snap down to 64 (the closest multiple of 16 when floored) + * + * Note that snapping takes place before adjustments by the parent, or the min / max settings. If these + * values are not multiples of the given snap values, then this can result in un-snapped dimensions. + * + * Call this method with no arguments to reset the snap values. + * + * Calling this method automatically recalculates the `width` and the `height`, if required. + * + * @method Phaser.Structs.Size#setSnap + * @since 3.16.0 + * + * @param {number} [snapWidth=0] - The amount to snap the width to. If you don't want to snap the width, pass a value of zero. + * @param {number} [snapHeight=snapWidth] - The amount to snap the height to. If not provided it will use the `snapWidth` value. If you don't want to snap the height, pass a value of zero. + * + * @return {this} This Size component instance. + */ + setSnap: function (snapWidth, snapHeight) + { + if (snapWidth === undefined) { snapWidth = 0; } + if (snapHeight === undefined) { snapHeight = snapWidth; } + + this.snapTo.set(snapWidth, snapHeight); + + return this.setSize(this._width, this._height); + }, + + /** + * 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. + */ + setParent: function (parent) + { + this._parent = parent; + + return this.setSize(this._width, this._height); + }, + + /** + * 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 exceed 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. + */ + setMin: function (width, height) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + + this.minWidth = Clamp(width, 0, this.maxWidth); + this.minHeight = Clamp(height, 0, this.maxHeight); + + return this.setSize(this._width, this._height); + }, + + /** + * 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 exceed 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. + */ + setMax: function (width, height) + { + if (width === undefined) { width = Number.MAX_VALUE; } + if (height === undefined) { height = width; } + + this.maxWidth = Clamp(width, this.minWidth, Number.MAX_VALUE); + this.maxHeight = Clamp(height, this.minHeight, Number.MAX_VALUE); + + return this.setSize(this._width, this._height); + }, + + /** + * 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. + */ + setSize: function (width, height) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + + switch (this.aspectMode) + { + case Size.NONE: + this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); + this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); + this.aspectRatio = (this._height === 0) ? 1 : this._width / this._height; + break; + + case Size.WIDTH_CONTROLS_HEIGHT: + this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); + this._height = this.getNewHeight(this._width * (1 / this.aspectRatio), false); + break; + + case Size.HEIGHT_CONTROLS_WIDTH: + this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); + this._width = this.getNewWidth(this._height * this.aspectRatio, false); + break; + + case Size.FIT: + this.constrain(width, height, true); + break; + + case Size.ENVELOP: + this.constrain(width, height, false); + break; + } + + return this; + }, + + /** + * Sets a new aspect ratio, overriding what was there previously. + * + * It then calls `setSize` immediately using the current dimensions. + * + * @method Phaser.Structs.Size#setAspectRatio + * @since 3.16.0 + * + * @param {number} ratio - The new aspect ratio. + * + * @return {this} This Size component instance. + */ + setAspectRatio: function (ratio) + { + this.aspectRatio = ratio; + + return this.setSize(this._width, this._height); + }, + + /** + * 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. + */ + resize: function (width, height) + { + this._width = this.getNewWidth(SnapFloor(width, this.snapTo.x)); + this._height = this.getNewHeight(SnapFloor(height, this.snapTo.y)); + this.aspectRatio = (this._height === 0) ? 1 : this._width / this._height; + + return this; + }, + + /** + * Takes a new width and passes it through the min/max clamp and then checks it doesn't exceed the parent width. + * + * @method Phaser.Structs.Size#getNewWidth + * @since 3.16.0 + * + * @param {number} value - The value to clamp and check. + * @param {boolean} [checkParent=true] - Check the given value against the parent, if set. + * + * @return {number} The modified width value. + */ + getNewWidth: function (value, checkParent) + { + if (checkParent === undefined) { checkParent = true; } + + value = Clamp(value, this.minWidth, this.maxWidth); + + if (checkParent && this._parent && value > this._parent.width) + { + value = Math.max(this.minWidth, this._parent.width); + } + + return value; + }, + + /** + * Takes a new height and passes it through the min/max clamp and then checks it doesn't exceed the parent height. + * + * @method Phaser.Structs.Size#getNewHeight + * @since 3.16.0 + * + * @param {number} value - The value to clamp and check. + * @param {boolean} [checkParent=true] - Check the given value against the parent, if set. + * + * @return {number} The modified height value. + */ + getNewHeight: function (value, checkParent) + { + if (checkParent === undefined) { checkParent = true; } + + value = Clamp(value, this.minHeight, this.maxHeight); + + if (checkParent && this._parent && value > this._parent.height) + { + value = Math.max(this.minHeight, this._parent.height); + } + + return value; + }, + + /** + * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. + * + * If `fit` is true there may be some space inside the target area which is not covered if its aspect ratio differs. + * If `fit` is false the size may extend further out than the target area if the aspect ratios differ. + * + * If this Size component has a parent set, then the width and height passed to this method will be clamped so + * it cannot exceed that of the parent. + * + * @method Phaser.Structs.Size#constrain + * @since 3.16.0 + * + * @param {number} [width=0] - The new width of the Size component. + * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. + * @param {boolean} [fit=true] - Perform a `fit` (true) constraint, or an `envelop` (false) constraint. + * + * @return {this} This Size component instance. + */ + constrain: function (width, height, fit) + { + if (width === undefined) { width = 0; } + if (height === undefined) { height = width; } + if (fit === undefined) { fit = true; } + + width = this.getNewWidth(width); + height = this.getNewHeight(height); + + var snap = this.snapTo; + var newRatio = (height === 0) ? 1 : width / height; + + if ((fit && this.aspectRatio > newRatio) || (!fit && this.aspectRatio < newRatio)) + { + // We need to change the height to fit the width + + width = SnapFloor(width, snap.x); + + height = width / this.aspectRatio; + + if (snap.y > 0) + { + height = SnapFloor(height, snap.y); + + // Reduce the width accordingly + width = height * this.aspectRatio; + } + } + else if ((fit && this.aspectRatio < newRatio) || (!fit && this.aspectRatio > newRatio)) + { + // We need to change the width to fit the height + + height = SnapFloor(height, snap.y); + + width = height * this.aspectRatio; + + if (snap.x > 0) + { + width = SnapFloor(width, snap.x); + + // Reduce the height accordingly + height = width * (1 / this.aspectRatio); + } + } + + this._width = width; + this._height = height; + + return this; + }, + + /** + * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. + * + * There may be some space inside the target area which is not covered if its aspect ratio differs. + * + * If this Size component has a parent set, then the width and height passed to this method will be clamped so + * it cannot exceed that of the parent. + * + * @method Phaser.Structs.Size#fitTo + * @since 3.16.0 + * + * @param {number} [width=0] - The new width of the Size component. + * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. + * + * @return {this} This Size component instance. + */ + fitTo: function (width, height) + { + return this.constrain(width, height, true); + }, + + /** + * The current `width` and `height` are adjusted so that they fully envelope the given dimensions, while keeping the aspect ratio. + * + * The size may extend further out than the target area if the aspect ratios differ. + * + * If this Size component has a parent set, then the values are clamped so that it never exceeds the parent + * on the longest axis. + * + * @method Phaser.Structs.Size#envelop + * @since 3.16.0 + * + * @param {number} [width=0] - The new width of the Size component. + * @param {number} [height] - The new height of the Size component. If not given, it will use the width value. + * + * @return {this} This Size component instance. + */ + envelop: function (width, height) + { + return this.constrain(width, height, false); + }, + + /** + * Sets the width of this Size component. + * + * Depending on the aspect mode, changing the width may also update the height and aspect ratio. + * + * @method Phaser.Structs.Size#setWidth + * @since 3.16.0 + * + * @param {number} width - The new width of the Size component. + * + * @return {this} This Size component instance. + */ + setWidth: function (value) + { + return this.setSize(value, this._height); + }, + + /** + * Sets the height of this Size component. + * + * Depending on the aspect mode, changing the height may also update the width and aspect ratio. + * + * @method Phaser.Structs.Size#setHeight + * @since 3.16.0 + * + * @param {number} height - The new height of the Size component. + * + * @return {this} This Size component instance. + */ + setHeight: function (value) + { + return this.setSize(this._width, value); + }, + + /** + * Returns a string representation of this Size component. + * + * @method Phaser.Structs.Size#toString + * @since 3.16.0 + * + * @return {string} A string representation of this Size component. + */ + toString: function () + { + return '[{ Size (width=' + this._width + ' height=' + this._height + ' aspectRatio=' + this.aspectRatio + ' aspectMode=' + this.aspectMode + ') }]'; + }, + + /** + * Sets the values of this Size component to the `element.style.width` and `height` + * properties of the given DOM Element. The properties are set as `px` values. + * + * @method Phaser.Structs.Size#setCSS + * @since 3.17.0 + * + * @param {HTMLElement} element - The DOM Element to set the CSS style on. + */ + setCSS: function (element) + { + if (element && element.style) + { + element.style.width = this._width + 'px'; + element.style.height = this._height + 'px'; + } + }, + + /** + * Copies the aspect mode, aspect ratio, width and height from this Size component + * to the given Size component. Note that the parent, if set, is not copied across. + * + * @method Phaser.Structs.Size#copy + * @since 3.16.0 + * + * @param {Phaser.Structs.Size} destination - The Size component to copy the values to. + * + * @return {Phaser.Structs.Size} The updated destination Size component. + */ + copy: function (destination) + { + destination.setAspectMode(this.aspectMode); + + destination.aspectRatio = this.aspectRatio; + + return destination.setSize(this.width, this.height); + }, + + /** + * Destroys this Size component. + * + * This clears the local properties and any parent object, if set. + * + * A destroyed Size component cannot be re-used. + * + * @method Phaser.Structs.Size#destroy + * @since 3.16.0 + */ + destroy: function () + { + this._parent = null; + this.snapTo = null; + }, + + /** + * The width of this Size component. + * + * This value is clamped to the range specified by `minWidth` and `maxWidth`, if enabled. + * + * A width can never be less than zero. + * + * Changing this value will automatically update the `height` if the aspect ratio lock is enabled. + * You can also use the `setWidth` and `getWidth` methods. + * + * @name Phaser.Structs.Size#width + * @type {number} + * @since 3.16.0 + */ + width: { + + get: function () + { + return this._width; + }, + + set: function (value) + { + this.setSize(value, this._height); + } + + }, + + /** + * The height of this Size component. + * + * This value is clamped to the range specified by `minHeight` and `maxHeight`, if enabled. + * + * A height can never be less than zero. + * + * Changing this value will automatically update the `width` if the aspect ratio lock is enabled. + * You can also use the `setHeight` and `getHeight` methods. + * + * @name Phaser.Structs.Size#height + * @type {number} + * @since 3.16.0 + */ + height: { + + get: function () + { + return this._height; + }, + + set: function (value) + { + this.setSize(this._width, value); + } + + } + +}); + +/** + * Do not make the size fit the aspect ratio. Change the ratio when the size changes. + * + * @name Phaser.Structs.Size.NONE + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.NONE = 0; + +/** + * The height is automatically adjusted based on the width. + * + * @name Phaser.Structs.Size.WIDTH_CONTROLS_HEIGHT + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.WIDTH_CONTROLS_HEIGHT = 1; + +/** + * The width is automatically adjusted based on the height. + * + * @name Phaser.Structs.Size.HEIGHT_CONTROLS_WIDTH + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.HEIGHT_CONTROLS_WIDTH = 2; + +/** + * 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. + * + * @name Phaser.Structs.Size.FIT + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.FIT = 3; + +/** + * 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. + * + * @name Phaser.Structs.Size.ENVELOP + * @constant + * @type {integer} + * @since 3.16.0 + */ +Size.ENVELOP = 4; + +module.exports = Size; diff --git a/src/structs/events/PROCESS_QUEUE_ADD_EVENT.js b/src/structs/events/PROCESS_QUEUE_ADD_EVENT.js index f3db6729e..716796c2e 100644 --- a/src/structs/events/PROCESS_QUEUE_ADD_EVENT.js +++ b/src/structs/events/PROCESS_QUEUE_ADD_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Process Queue Add Event. - * - * This event is dispatched by a Process Queue when a new item is successfully moved to its active list. - * - * You will most commonly see this used by a Scene's Update List when a new Game Object has been added. - * - * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('add', listener)`. - * - * @event Phaser.Structs.Events#PROCESS_QUEUE_ADD - * @since 3.20.0 - * - * @param {*} item - The item that was added to the Process Queue. - */ -module.exports = 'add'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Process Queue Add Event. + * + * This event is dispatched by a Process Queue when a new item is successfully moved to its active list. + * + * You will most commonly see this used by a Scene's Update List when a new Game Object has been added. + * + * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('add', listener)`. + * + * @event Phaser.Structs.Events#PROCESS_QUEUE_ADD + * @since 3.20.0 + * + * @param {*} item - The item that was added to the Process Queue. + */ +module.exports = 'add'; diff --git a/src/structs/events/PROCESS_QUEUE_REMOVE_EVENT.js b/src/structs/events/PROCESS_QUEUE_REMOVE_EVENT.js index 707f8ee63..f59e3f493 100644 --- a/src/structs/events/PROCESS_QUEUE_REMOVE_EVENT.js +++ b/src/structs/events/PROCESS_QUEUE_REMOVE_EVENT.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Process Queue Remove Event. - * - * This event is dispatched by a Process Queue when a new item is successfully removed from its active list. - * - * You will most commonly see this used by a Scene's Update List when a Game Object has been removed. - * - * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('remove', listener)`. - * - * @event Phaser.Structs.Events#PROCESS_QUEUE_REMOVE - * @since 3.20.0 - * - * @param {*} item - The item that was removed from the Process Queue. - */ -module.exports = 'remove'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Process Queue Remove Event. + * + * This event is dispatched by a Process Queue when a new item is successfully removed from its active list. + * + * You will most commonly see this used by a Scene's Update List when a Game Object has been removed. + * + * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('remove', listener)`. + * + * @event Phaser.Structs.Events#PROCESS_QUEUE_REMOVE + * @since 3.20.0 + * + * @param {*} item - The item that was removed from the Process Queue. + */ +module.exports = 'remove'; diff --git a/src/structs/events/index.js b/src/structs/events/index.js index 47aff897d..66ce08062 100644 --- a/src/structs/events/index.js +++ b/src/structs/events/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Structs.Events - */ - -module.exports = { - - PROCESS_QUEUE_ADD: require('./PROCESS_QUEUE_ADD_EVENT'), - PROCESS_QUEUE_REMOVE: require('./PROCESS_QUEUE_REMOVE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Structs.Events + */ + +module.exports = { + + PROCESS_QUEUE_ADD: require('./PROCESS_QUEUE_ADD_EVENT'), + PROCESS_QUEUE_REMOVE: require('./PROCESS_QUEUE_REMOVE_EVENT') + +}; diff --git a/src/structs/index.js b/src/structs/index.js index 5de1cb78a..baefe3dd0 100644 --- a/src/structs/index.js +++ b/src/structs/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Structs - */ - -module.exports = { - - List: require('./List'), - Map: require('./Map'), - ProcessQueue: require('./ProcessQueue'), - RTree: require('./RTree'), - Set: require('./Set'), - Size: require('./Size') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Structs + */ + +module.exports = { + + List: require('./List'), + Map: require('./Map'), + ProcessQueue: require('./ProcessQueue'), + RTree: require('./RTree'), + Set: require('./Set'), + Size: require('./Size') + +}; diff --git a/src/textures/CanvasTexture.js b/src/textures/CanvasTexture.js index fd85fa131..2b270e87d 100644 --- a/src/textures/CanvasTexture.js +++ b/src/textures/CanvasTexture.js @@ -1,625 +1,625 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Clamp = require('../math/Clamp'); -var Color = require('../display/color/Color'); -var CONST = require('../const'); -var IsSizePowerOfTwo = require('../math/pow2/IsSizePowerOfTwo'); -var Texture = require('./Texture'); - -/** - * @classdesc - * A Canvas Texture is a special kind of Texture that is backed by an HTML Canvas Element as its source. - * - * You can use the properties of this texture to draw to the canvas element directly, using all of the standard - * canvas operations available in the browser. Any Game Object can be given this texture and will render with it. - * - * Note: When running under WebGL the Canvas Texture needs to re-generate its base WebGLTexture and reupload it to - * the GPU every time you modify it, otherwise the changes you make to this texture will not be visible. To do this - * you should call `CanvasTexture.refresh()` once you are finished with your changes to the canvas. Try and keep - * this to a minimum, especially on large canvas sizes, or you may inadvertently thrash the GPU by constantly uploading - * texture data to it. This restriction does not apply if using the Canvas Renderer. - * - * It starts with only one frame that covers the whole of the canvas. You can add further frames, that specify - * sections of the canvas using the `add` method. - * - * Should you need to resize the canvas use the `setSize` method so that it accurately updates all of the underlying - * texture data as well. Forgetting to do this (i.e. by changing the canvas size directly from your code) could cause - * graphical errors. - * - * @class CanvasTexture - * @extends Phaser.Textures.Texture - * @memberof Phaser.Textures - * @constructor - * @since 3.7.0 - * - * @param {Phaser.Textures.TextureManager} manager - A reference to the Texture Manager this Texture belongs to. - * @param {string} key - The unique string-based key of this Texture. - * @param {HTMLCanvasElement} source - The canvas element that is used as the base of this texture. - * @param {integer} width - The width of the canvas. - * @param {integer} height - The height of the canvas. - */ -var CanvasTexture = new Class({ - - Extends: Texture, - - initialize: - - function CanvasTexture (manager, key, source, width, height) - { - Texture.call(this, manager, key, source, width, height); - - this.add('__BASE', 0, 0, 0, width, height); - - /** - * A reference to the Texture Source of this Canvas. - * - * @name Phaser.Textures.CanvasTexture#_source - * @type {Phaser.Textures.TextureSource} - * @private - * @since 3.7.0 - */ - this._source = this.frames['__BASE'].source; - - /** - * The source Canvas Element. - * - * @name Phaser.Textures.CanvasTexture#canvas - * @readonly - * @type {HTMLCanvasElement} - * @since 3.7.0 - */ - this.canvas = this._source.image; - - /** - * The 2D Canvas Rendering Context. - * - * @name Phaser.Textures.CanvasTexture#context - * @readonly - * @type {CanvasRenderingContext2D} - * @since 3.7.0 - */ - this.context = this.canvas.getContext('2d'); - - /** - * The width of the Canvas. - * This property is read-only, if you wish to change it use the `setSize` method. - * - * @name Phaser.Textures.CanvasTexture#width - * @readonly - * @type {integer} - * @since 3.7.0 - */ - this.width = width; - - /** - * The height of the Canvas. - * This property is read-only, if you wish to change it use the `setSize` method. - * - * @name Phaser.Textures.CanvasTexture#height - * @readonly - * @type {integer} - * @since 3.7.0 - */ - this.height = height; - - /** - * The context image data. - * Use the `update` method to populate this when the canvas changes. - * - * @name Phaser.Textures.CanvasTexture#imageData - * @type {ImageData} - * @since 3.13.0 - */ - this.imageData = this.context.getImageData(0, 0, width, height); - - /** - * A Uint8ClampedArray view into the `buffer`. - * Use the `update` method to populate this when the canvas changes. - * Note that this is unavailable in some browsers, such as Epic Browser, due to their security restrictions. - * - * @name Phaser.Textures.CanvasTexture#data - * @type {Uint8ClampedArray} - * @since 3.13.0 - */ - this.data = null; - - if (this.imageData) - { - this.data = this.imageData.data; - } - - /** - * An Uint32Array view into the `buffer`. - * - * @name Phaser.Textures.CanvasTexture#pixels - * @type {Uint32Array} - * @since 3.13.0 - */ - this.pixels = null; - - /** - * An ArrayBuffer the same size as the context ImageData. - * - * @name Phaser.Textures.CanvasTexture#buffer - * @type {ArrayBuffer} - * @since 3.13.0 - */ - this.buffer; - - if (this.data) - { - if (this.imageData.data.buffer) - { - this.buffer = this.imageData.data.buffer; - this.pixels = new Uint32Array(this.buffer); - } - else if (window.ArrayBuffer) - { - this.buffer = new ArrayBuffer(this.imageData.data.length); - this.pixels = new Uint32Array(this.buffer); - } - else - { - this.pixels = this.imageData.data; - } - } - }, - - /** - * This re-creates the `imageData` from the current context. - * It then re-builds the ArrayBuffer, the `data` Uint8ClampedArray reference and the `pixels` Int32Array. - * - * Warning: This is a very expensive operation, so use it sparingly. - * - * @method Phaser.Textures.CanvasTexture#update - * @since 3.13.0 - * - * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. - */ - update: function () - { - this.imageData = this.context.getImageData(0, 0, this.width, this.height); - - this.data = this.imageData.data; - - if (this.imageData.data.buffer) - { - this.buffer = this.imageData.data.buffer; - this.pixels = new Uint32Array(this.buffer); - } - else if (window.ArrayBuffer) - { - this.buffer = new ArrayBuffer(this.imageData.data.length); - this.pixels = new Uint32Array(this.buffer); - } - else - { - this.pixels = this.imageData.data; - } - - if (this.manager.game.config.renderType === CONST.WEBGL) - { - this.refresh(); - } - - return this; - }, - - /** - * Draws the given Image or Canvas element to this CanvasTexture, then updates the internal - * ImageData buffer and arrays. - * - * @method Phaser.Textures.CanvasTexture#draw - * @since 3.13.0 - * - * @param {integer} x - The x coordinate to draw the source at. - * @param {integer} y - The y coordinate to draw the source at. - * @param {(HTMLImageElement|HTMLCanvasElement)} source - The element to draw to this canvas. - * - * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. - */ - draw: function (x, y, source) - { - this.context.drawImage(source, x, y); - - return this.update(); - }, - - /** - * Draws the given texture frame to this CanvasTexture, then updates the internal - * ImageData buffer and arrays. - * - * @method Phaser.Textures.CanvasTexture#drawFrame - * @since 3.16.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. - * @param {integer} [x=0] - The x coordinate to draw the source at. - * @param {integer} [y=0] - The y coordinate to draw the source at. - * - * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. - */ - drawFrame: function (key, frame, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - var textureFrame = this.manager.getFrame(key, frame); - - if (textureFrame) - { - var cd = textureFrame.canvasData; - - var width = textureFrame.cutWidth; - var height = textureFrame.cutHeight; - var res = textureFrame.source.resolution; - - this.context.drawImage( - textureFrame.source.image, - cd.x, cd.y, - width, - height, - x, y, - width / res, - height / res - ); - - return this.update(); - } - else - { - return this; - } - }, - - /** - * Sets a pixel in the CanvasTexture to the given color and alpha values. - * - * This is an expensive operation to run in large quantities, so use sparingly. - * - * @method Phaser.Textures.CanvasTexture#setPixel - * @since 3.16.0 - * - * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} red - The red color value. A number between 0 and 255. - * @param {integer} green - The green color value. A number between 0 and 255. - * @param {integer} blue - The blue color value. A number between 0 and 255. - * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. - * - * @return {this} This CanvasTexture. - */ - setPixel: function (x, y, red, green, blue, alpha) - { - if (alpha === undefined) { alpha = 255; } - - x = Math.abs(Math.floor(x)); - y = Math.abs(Math.floor(y)); - - var index = this.getIndex(x, y); - - if (index > -1) - { - var imageData = this.context.getImageData(x, y, 1, 1); - - imageData.data[0] = red; - imageData.data[1] = green; - imageData.data[2] = blue; - imageData.data[3] = alpha; - - this.context.putImageData(imageData, x, y); - } - - return this; - }, - - /** - * Puts the ImageData into the context of this CanvasTexture at the given coordinates. - * - * @method Phaser.Textures.CanvasTexture#putData - * @since 3.16.0 - * - * @param {ImageData} imageData - The ImageData to put at the given location. - * @param {integer} x - The x coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} y - The y coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} [dirtyX=0] - Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. - * @param {integer} [dirtyY=0] - Vertical position (x coordinate) of the top-left corner from which the image data will be extracted. - * @param {integer} [dirtyWidth] - Width of the rectangle to be painted. Defaults to the width of the image data. - * @param {integer} [dirtyHeight] - Height of the rectangle to be painted. Defaults to the height of the image data. - * - * @return {this} This CanvasTexture. - */ - putData: function (imageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight) - { - if (dirtyX === undefined) { dirtyX = 0; } - if (dirtyY === undefined) { dirtyY = 0; } - if (dirtyWidth === undefined) { dirtyWidth = imageData.width; } - if (dirtyHeight === undefined) { dirtyHeight = imageData.height; } - - this.context.putImageData(imageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight); - - return this; - }, - - /** - * Gets an ImageData region from this CanvasTexture from the position and size specified. - * You can write this back using `CanvasTexture.putData`, or manipulate it. - * - * @method Phaser.Textures.CanvasTexture#getData - * @since 3.16.0 - * - * @param {integer} x - The x coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} y - The y coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} width - The width of the rectangle from which the ImageData will be extracted. Positive values are to the right, and negative to the left. - * @param {integer} height - The height of the rectangle from which the ImageData will be extracted. Positive values are down, and negative are up. - * - * @return {ImageData} The ImageData extracted from this CanvasTexture. - */ - getData: function (x, y, width, height) - { - x = Clamp(Math.floor(x), 0, this.width - 1); - y = Clamp(Math.floor(y), 0, this.height - 1); - width = Clamp(width, 1, this.width - x); - height = Clamp(height, 1, this.height - y); - - var imageData = this.context.getImageData(x, y, width, height); - - return imageData; - }, - - /** - * Get the color of a specific pixel from this texture and store it in a Color object. - * - * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * - * @method Phaser.Textures.CanvasTexture#getPixel - * @since 3.13.0 - * - * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {Phaser.Display.Color} [out] - A Color object to store the pixel values in. If not provided a new Color object will be created. - * - * @return {Phaser.Display.Color} An object with the red, green, blue and alpha values set in the r, g, b and a properties. - */ - getPixel: function (x, y, out) - { - if (!out) - { - out = new Color(); - } - - var index = this.getIndex(x, y); - - if (index > -1) - { - var data = this.data; - - var r = data[index + 0]; - var g = data[index + 1]; - var b = data[index + 2]; - var a = data[index + 3]; - - out.setTo(r, g, b, a); - } - - return out; - }, - - /** - * Returns an array containing all of the pixels in the given region. - * - * If the requested region extends outside the bounds of this CanvasTexture, - * the region is truncated to fit. - * - * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * - * @method Phaser.Textures.CanvasTexture#getPixels - * @since 3.16.0 - * - * @param {integer} [x=0] - The x coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} [y=0] - The y coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} [width] - The width of the region to get. Must be an integer. Defaults to the canvas width if not given. - * @param {integer} [height] - The height of the region to get. Must be an integer. If not given will be set to the `width`. - * - * @return {Phaser.Types.Textures.PixelConfig[]} An array of Pixel objects. - */ - getPixels: function (x, y, width, height) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.width; } - if (height === undefined) { height = width; } - - x = Math.abs(Math.round(x)); - y = Math.abs(Math.round(y)); - - var left = Clamp(x, 0, this.width); - var right = Clamp(x + width, 0, this.width); - var top = Clamp(y, 0, this.height); - var bottom = Clamp(y + height, 0, this.height); - - var pixel = new Color(); - - var out = []; - - for (var py = top; py < bottom; py++) - { - var row = []; - - for (var px = left; px < right; px++) - { - pixel = this.getPixel(px, py, pixel); - - row.push({ x: px, y: py, color: pixel.color, alpha: pixel.alphaGL }); - } - - out.push(row); - } - - return out; - }, - - /** - * Returns the Image Data index for the given pixel in this CanvasTexture. - * - * The index can be used to read directly from the `this.data` array. - * - * The index points to the red value in the array. The subsequent 3 indexes - * point to green, blue and alpha respectively. - * - * @method Phaser.Textures.CanvasTexture#getIndex - * @since 3.16.0 - * - * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * - * @return {integer} - */ - getIndex: function (x, y) - { - x = Math.abs(Math.round(x)); - y = Math.abs(Math.round(y)); - - if (x < this.width && y < this.height) - { - return (x + y * this.width) * 4; - } - else - { - return -1; - } - }, - - /** - * This should be called manually if you are running under WebGL. - * It will refresh the WebGLTexture from the Canvas source. Only call this if you know that the - * canvas has changed, as there is a significant GPU texture allocation cost involved in doing so. - * - * @method Phaser.Textures.CanvasTexture#refresh - * @since 3.7.0 - * - * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. - */ - refresh: function () - { - this._source.update(); - - return this; - }, - - /** - * Gets the Canvas Element. - * - * @method Phaser.Textures.CanvasTexture#getCanvas - * @since 3.7.0 - * - * @return {HTMLCanvasElement} The Canvas DOM element this texture is using. - */ - getCanvas: function () - { - return this.canvas; - }, - - /** - * Gets the 2D Canvas Rendering Context. - * - * @method Phaser.Textures.CanvasTexture#getContext - * @since 3.7.0 - * - * @return {CanvasRenderingContext2D} The Canvas Rendering Context this texture is using. - */ - getContext: function () - { - return this.context; - }, - - /** - * Clears the given region of this Canvas Texture, resetting it back to transparent. - * If no region is given, the whole Canvas Texture is cleared. - * - * @method Phaser.Textures.CanvasTexture#clear - * @since 3.7.0 - * - * @param {integer} [x=0] - The x coordinate of the top-left of the region to clear. - * @param {integer} [y=0] - The y coordinate of the top-left of the region to clear. - * @param {integer} [width] - The width of the region. - * @param {integer} [height] - The height of the region. - * - * @return {Phaser.Textures.CanvasTexture} The Canvas Texture. - */ - clear: function (x, y, width, height) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.width; } - if (height === undefined) { height = this.height; } - - this.context.clearRect(x, y, width, height); - - return this.update(); - }, - - /** - * Changes the size of this Canvas Texture. - * - * @method Phaser.Textures.CanvasTexture#setSize - * @since 3.7.0 - * - * @param {integer} width - The new width of the Canvas. - * @param {integer} [height] - The new height of the Canvas. If not given it will use the width as the height. - * - * @return {Phaser.Textures.CanvasTexture} The Canvas Texture. - */ - setSize: function (width, height) - { - if (height === undefined) { height = width; } - - if (width !== this.width || height !== this.height) - { - // Update the Canvas - this.canvas.width = width; - this.canvas.height = height; - - // Update the Texture Source - this._source.width = width; - this._source.height = height; - this._source.isPowerOf2 = IsSizePowerOfTwo(width, height); - - // Update the Frame - this.frames['__BASE'].setSize(width, height, 0, 0); - - this.refresh(); - } - - return this; - }, - - /** - * Destroys this Texture and releases references to its sources and frames. - * - * @method Phaser.Textures.CanvasTexture#destroy - * @since 3.16.0 - */ - destroy: function () - { - Texture.prototype.destroy.call(this); - - this._source = null; - this.canvas = null; - this.context = null; - this.imageData = null; - this.data = null; - this.pixels = null; - this.buffer = null; - } - -}); - -module.exports = CanvasTexture; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Clamp = require('../math/Clamp'); +var Color = require('../display/color/Color'); +var CONST = require('../const'); +var IsSizePowerOfTwo = require('../math/pow2/IsSizePowerOfTwo'); +var Texture = require('./Texture'); + +/** + * @classdesc + * A Canvas Texture is a special kind of Texture that is backed by an HTML Canvas Element as its source. + * + * You can use the properties of this texture to draw to the canvas element directly, using all of the standard + * canvas operations available in the browser. Any Game Object can be given this texture and will render with it. + * + * Note: When running under WebGL the Canvas Texture needs to re-generate its base WebGLTexture and reupload it to + * the GPU every time you modify it, otherwise the changes you make to this texture will not be visible. To do this + * you should call `CanvasTexture.refresh()` once you are finished with your changes to the canvas. Try and keep + * this to a minimum, especially on large canvas sizes, or you may inadvertently thrash the GPU by constantly uploading + * texture data to it. This restriction does not apply if using the Canvas Renderer. + * + * It starts with only one frame that covers the whole of the canvas. You can add further frames, that specify + * sections of the canvas using the `add` method. + * + * Should you need to resize the canvas use the `setSize` method so that it accurately updates all of the underlying + * texture data as well. Forgetting to do this (i.e. by changing the canvas size directly from your code) could cause + * graphical errors. + * + * @class CanvasTexture + * @extends Phaser.Textures.Texture + * @memberof Phaser.Textures + * @constructor + * @since 3.7.0 + * + * @param {Phaser.Textures.TextureManager} manager - A reference to the Texture Manager this Texture belongs to. + * @param {string} key - The unique string-based key of this Texture. + * @param {HTMLCanvasElement} source - The canvas element that is used as the base of this texture. + * @param {integer} width - The width of the canvas. + * @param {integer} height - The height of the canvas. + */ +var CanvasTexture = new Class({ + + Extends: Texture, + + initialize: + + function CanvasTexture (manager, key, source, width, height) + { + Texture.call(this, manager, key, source, width, height); + + this.add('__BASE', 0, 0, 0, width, height); + + /** + * A reference to the Texture Source of this Canvas. + * + * @name Phaser.Textures.CanvasTexture#_source + * @type {Phaser.Textures.TextureSource} + * @private + * @since 3.7.0 + */ + this._source = this.frames['__BASE'].source; + + /** + * The source Canvas Element. + * + * @name Phaser.Textures.CanvasTexture#canvas + * @readonly + * @type {HTMLCanvasElement} + * @since 3.7.0 + */ + this.canvas = this._source.image; + + /** + * The 2D Canvas Rendering Context. + * + * @name Phaser.Textures.CanvasTexture#context + * @readonly + * @type {CanvasRenderingContext2D} + * @since 3.7.0 + */ + this.context = this.canvas.getContext('2d'); + + /** + * The width of the Canvas. + * This property is read-only, if you wish to change it use the `setSize` method. + * + * @name Phaser.Textures.CanvasTexture#width + * @readonly + * @type {integer} + * @since 3.7.0 + */ + this.width = width; + + /** + * The height of the Canvas. + * This property is read-only, if you wish to change it use the `setSize` method. + * + * @name Phaser.Textures.CanvasTexture#height + * @readonly + * @type {integer} + * @since 3.7.0 + */ + this.height = height; + + /** + * The context image data. + * Use the `update` method to populate this when the canvas changes. + * + * @name Phaser.Textures.CanvasTexture#imageData + * @type {ImageData} + * @since 3.13.0 + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into the `buffer`. + * Use the `update` method to populate this when the canvas changes. + * Note that this is unavailable in some browsers, such as Epic Browser, due to their security restrictions. + * + * @name Phaser.Textures.CanvasTexture#data + * @type {Uint8ClampedArray} + * @since 3.13.0 + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * An Uint32Array view into the `buffer`. + * + * @name Phaser.Textures.CanvasTexture#pixels + * @type {Uint32Array} + * @since 3.13.0 + */ + this.pixels = null; + + /** + * An ArrayBuffer the same size as the context ImageData. + * + * @name Phaser.Textures.CanvasTexture#buffer + * @type {ArrayBuffer} + * @since 3.13.0 + */ + this.buffer; + + if (this.data) + { + if (this.imageData.data.buffer) + { + this.buffer = this.imageData.data.buffer; + this.pixels = new Uint32Array(this.buffer); + } + else if (window.ArrayBuffer) + { + this.buffer = new ArrayBuffer(this.imageData.data.length); + this.pixels = new Uint32Array(this.buffer); + } + else + { + this.pixels = this.imageData.data; + } + } + }, + + /** + * This re-creates the `imageData` from the current context. + * It then re-builds the ArrayBuffer, the `data` Uint8ClampedArray reference and the `pixels` Int32Array. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.Textures.CanvasTexture#update + * @since 3.13.0 + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + update: function () + { + this.imageData = this.context.getImageData(0, 0, this.width, this.height); + + this.data = this.imageData.data; + + if (this.imageData.data.buffer) + { + this.buffer = this.imageData.data.buffer; + this.pixels = new Uint32Array(this.buffer); + } + else if (window.ArrayBuffer) + { + this.buffer = new ArrayBuffer(this.imageData.data.length); + this.pixels = new Uint32Array(this.buffer); + } + else + { + this.pixels = this.imageData.data; + } + + if (this.manager.game.config.renderType === CONST.WEBGL) + { + this.refresh(); + } + + return this; + }, + + /** + * Draws the given Image or Canvas element to this CanvasTexture, then updates the internal + * ImageData buffer and arrays. + * + * @method Phaser.Textures.CanvasTexture#draw + * @since 3.13.0 + * + * @param {integer} x - The x coordinate to draw the source at. + * @param {integer} y - The y coordinate to draw the source at. + * @param {(HTMLImageElement|HTMLCanvasElement)} source - The element to draw to this canvas. + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + draw: function (x, y, source) + { + this.context.drawImage(source, x, y); + + return this.update(); + }, + + /** + * Draws the given texture frame to this CanvasTexture, then updates the internal + * ImageData buffer and arrays. + * + * @method Phaser.Textures.CanvasTexture#drawFrame + * @since 3.16.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. + * @param {integer} [x=0] - The x coordinate to draw the source at. + * @param {integer} [y=0] - The y coordinate to draw the source at. + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + drawFrame: function (key, frame, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + var textureFrame = this.manager.getFrame(key, frame); + + if (textureFrame) + { + var cd = textureFrame.canvasData; + + var width = textureFrame.cutWidth; + var height = textureFrame.cutHeight; + var res = textureFrame.source.resolution; + + this.context.drawImage( + textureFrame.source.image, + cd.x, cd.y, + width, + height, + x, y, + width / res, + height / res + ); + + return this.update(); + } + else + { + return this; + } + }, + + /** + * Sets a pixel in the CanvasTexture to the given color and alpha values. + * + * This is an expensive operation to run in large quantities, so use sparingly. + * + * @method Phaser.Textures.CanvasTexture#setPixel + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} red - The red color value. A number between 0 and 255. + * @param {integer} green - The green color value. A number between 0 and 255. + * @param {integer} blue - The blue color value. A number between 0 and 255. + * @param {integer} [alpha=255] - The alpha value. A number between 0 and 255. + * + * @return {this} This CanvasTexture. + */ + setPixel: function (x, y, red, green, blue, alpha) + { + if (alpha === undefined) { alpha = 255; } + + x = Math.abs(Math.floor(x)); + y = Math.abs(Math.floor(y)); + + var index = this.getIndex(x, y); + + if (index > -1) + { + var imageData = this.context.getImageData(x, y, 1, 1); + + imageData.data[0] = red; + imageData.data[1] = green; + imageData.data[2] = blue; + imageData.data[3] = alpha; + + this.context.putImageData(imageData, x, y); + } + + return this; + }, + + /** + * Puts the ImageData into the context of this CanvasTexture at the given coordinates. + * + * @method Phaser.Textures.CanvasTexture#putData + * @since 3.16.0 + * + * @param {ImageData} imageData - The ImageData to put at the given location. + * @param {integer} x - The x coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} [dirtyX=0] - Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. + * @param {integer} [dirtyY=0] - Vertical position (x coordinate) of the top-left corner from which the image data will be extracted. + * @param {integer} [dirtyWidth] - Width of the rectangle to be painted. Defaults to the width of the image data. + * @param {integer} [dirtyHeight] - Height of the rectangle to be painted. Defaults to the height of the image data. + * + * @return {this} This CanvasTexture. + */ + putData: function (imageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight) + { + if (dirtyX === undefined) { dirtyX = 0; } + if (dirtyY === undefined) { dirtyY = 0; } + if (dirtyWidth === undefined) { dirtyWidth = imageData.width; } + if (dirtyHeight === undefined) { dirtyHeight = imageData.height; } + + this.context.putImageData(imageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight); + + return this; + }, + + /** + * Gets an ImageData region from this CanvasTexture from the position and size specified. + * You can write this back using `CanvasTexture.putData`, or manipulate it. + * + * @method Phaser.Textures.CanvasTexture#getData + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} width - The width of the rectangle from which the ImageData will be extracted. Positive values are to the right, and negative to the left. + * @param {integer} height - The height of the rectangle from which the ImageData will be extracted. Positive values are down, and negative are up. + * + * @return {ImageData} The ImageData extracted from this CanvasTexture. + */ + getData: function (x, y, width, height) + { + x = Clamp(Math.floor(x), 0, this.width - 1); + y = Clamp(Math.floor(y), 0, this.height - 1); + width = Clamp(width, 1, this.width - x); + height = Clamp(height, 1, this.height - y); + + var imageData = this.context.getImageData(x, y, width, height); + + return imageData; + }, + + /** + * Get the color of a specific pixel from this texture and store it in a Color object. + * + * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.Textures.CanvasTexture#getPixel + * @since 3.13.0 + * + * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {Phaser.Display.Color} [out] - A Color object to store the pixel values in. If not provided a new Color object will be created. + * + * @return {Phaser.Display.Color} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) + { + if (!out) + { + out = new Color(); + } + + var index = this.getIndex(x, y); + + if (index > -1) + { + var data = this.data; + + var r = data[index + 0]; + var g = data[index + 1]; + var b = data[index + 2]; + var a = data[index + 3]; + + out.setTo(r, g, b, a); + } + + return out; + }, + + /** + * Returns an array containing all of the pixels in the given region. + * + * If the requested region extends outside the bounds of this CanvasTexture, + * the region is truncated to fit. + * + * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.Textures.CanvasTexture#getPixels + * @since 3.16.0 + * + * @param {integer} [x=0] - The x coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} [y=0] - The y coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} [width] - The width of the region to get. Must be an integer. Defaults to the canvas width if not given. + * @param {integer} [height] - The height of the region to get. Must be an integer. If not given will be set to the `width`. + * + * @return {Phaser.Types.Textures.PixelConfig[]} An array of Pixel objects. + */ + getPixels: function (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = width; } + + x = Math.abs(Math.round(x)); + y = Math.abs(Math.round(y)); + + var left = Clamp(x, 0, this.width); + var right = Clamp(x + width, 0, this.width); + var top = Clamp(y, 0, this.height); + var bottom = Clamp(y + height, 0, this.height); + + var pixel = new Color(); + + var out = []; + + for (var py = top; py < bottom; py++) + { + var row = []; + + for (var px = left; px < right; px++) + { + pixel = this.getPixel(px, py, pixel); + + row.push({ x: px, y: py, color: pixel.color, alpha: pixel.alphaGL }); + } + + out.push(row); + } + + return out; + }, + + /** + * Returns the Image Data index for the given pixel in this CanvasTexture. + * + * The index can be used to read directly from the `this.data` array. + * + * The index points to the red value in the array. The subsequent 3 indexes + * point to green, blue and alpha respectively. + * + * @method Phaser.Textures.CanvasTexture#getIndex + * @since 3.16.0 + * + * @param {integer} x - The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param {integer} y - The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * + * @return {integer} + */ + getIndex: function (x, y) + { + x = Math.abs(Math.round(x)); + y = Math.abs(Math.round(y)); + + if (x < this.width && y < this.height) + { + return (x + y * this.width) * 4; + } + else + { + return -1; + } + }, + + /** + * This should be called manually if you are running under WebGL. + * It will refresh the WebGLTexture from the Canvas source. Only call this if you know that the + * canvas has changed, as there is a significant GPU texture allocation cost involved in doing so. + * + * @method Phaser.Textures.CanvasTexture#refresh + * @since 3.7.0 + * + * @return {Phaser.Textures.CanvasTexture} This CanvasTexture. + */ + refresh: function () + { + this._source.update(); + + return this; + }, + + /** + * Gets the Canvas Element. + * + * @method Phaser.Textures.CanvasTexture#getCanvas + * @since 3.7.0 + * + * @return {HTMLCanvasElement} The Canvas DOM element this texture is using. + */ + getCanvas: function () + { + return this.canvas; + }, + + /** + * Gets the 2D Canvas Rendering Context. + * + * @method Phaser.Textures.CanvasTexture#getContext + * @since 3.7.0 + * + * @return {CanvasRenderingContext2D} The Canvas Rendering Context this texture is using. + */ + getContext: function () + { + return this.context; + }, + + /** + * Clears the given region of this Canvas Texture, resetting it back to transparent. + * If no region is given, the whole Canvas Texture is cleared. + * + * @method Phaser.Textures.CanvasTexture#clear + * @since 3.7.0 + * + * @param {integer} [x=0] - The x coordinate of the top-left of the region to clear. + * @param {integer} [y=0] - The y coordinate of the top-left of the region to clear. + * @param {integer} [width] - The width of the region. + * @param {integer} [height] - The height of the region. + * + * @return {Phaser.Textures.CanvasTexture} The Canvas Texture. + */ + clear: function (x, y, width, height) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + return this.update(); + }, + + /** + * Changes the size of this Canvas Texture. + * + * @method Phaser.Textures.CanvasTexture#setSize + * @since 3.7.0 + * + * @param {integer} width - The new width of the Canvas. + * @param {integer} [height] - The new height of the Canvas. If not given it will use the width as the height. + * + * @return {Phaser.Textures.CanvasTexture} The Canvas Texture. + */ + setSize: function (width, height) + { + if (height === undefined) { height = width; } + + if (width !== this.width || height !== this.height) + { + // Update the Canvas + this.canvas.width = width; + this.canvas.height = height; + + // Update the Texture Source + this._source.width = width; + this._source.height = height; + this._source.isPowerOf2 = IsSizePowerOfTwo(width, height); + + // Update the Frame + this.frames['__BASE'].setSize(width, height, 0, 0); + + this.refresh(); + } + + return this; + }, + + /** + * Destroys this Texture and releases references to its sources and frames. + * + * @method Phaser.Textures.CanvasTexture#destroy + * @since 3.16.0 + */ + destroy: function () + { + Texture.prototype.destroy.call(this); + + this._source = null; + this.canvas = null; + this.context = null; + this.imageData = null; + this.data = null; + this.pixels = null; + this.buffer = null; + } + +}); + +module.exports = CanvasTexture; diff --git a/src/textures/Frame.js b/src/textures/Frame.js index 24dd8e73b..2594d345c 100644 --- a/src/textures/Frame.js +++ b/src/textures/Frame.js @@ -1,813 +1,813 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Clamp = require('../math/Clamp'); -var Extend = require('../utils/object/Extend'); - -/** - * @classdesc - * A Frame is a section of a Texture. - * - * @class Frame - * @memberof Phaser.Textures - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture this Frame is a part of. - * @param {(integer|string)} name - The name of this Frame. The name is unique within the Texture. - * @param {integer} sourceIndex - The index of the TextureSource that this Frame is a part of. - * @param {number} x - The x coordinate of the top-left of this Frame. - * @param {number} y - The y coordinate of the top-left of this Frame. - * @param {number} width - The width of this Frame. - * @param {number} height - The height of this Frame. - */ -var Frame = new Class({ - - initialize: - - function Frame (texture, name, sourceIndex, x, y, width, height) - { - /** - * The Texture this Frame is a part of. - * - * @name Phaser.Textures.Frame#texture - * @type {Phaser.Textures.Texture} - * @since 3.0.0 - */ - this.texture = texture; - - /** - * The name of this Frame. - * The name is unique within the Texture. - * - * @name Phaser.Textures.Frame#name - * @type {string} - * @since 3.0.0 - */ - this.name = name; - - /** - * The TextureSource this Frame is part of. - * - * @name Phaser.Textures.Frame#source - * @type {Phaser.Textures.TextureSource} - * @since 3.0.0 - */ - this.source = texture.source[sourceIndex]; - - /** - * The index of the TextureSource in the Texture sources array. - * - * @name Phaser.Textures.Frame#sourceIndex - * @type {integer} - * @since 3.0.0 - */ - this.sourceIndex = sourceIndex; - - /** - * A reference to the Texture Source WebGL Texture that this Frame is using. - * - * @name Phaser.Textures.Frame#glTexture - * @type {?WebGLTexture} - * @default null - * @since 3.11.0 - */ - this.glTexture = this.source.glTexture; - - /** - * X position within the source image to cut from. - * - * @name Phaser.Textures.Frame#cutX - * @type {integer} - * @since 3.0.0 - */ - this.cutX; - - /** - * Y position within the source image to cut from. - * - * @name Phaser.Textures.Frame#cutY - * @type {integer} - * @since 3.0.0 - */ - this.cutY; - - /** - * The width of the area in the source image to cut. - * - * @name Phaser.Textures.Frame#cutWidth - * @type {integer} - * @since 3.0.0 - */ - this.cutWidth; - - /** - * The height of the area in the source image to cut. - * - * @name Phaser.Textures.Frame#cutHeight - * @type {integer} - * @since 3.0.0 - */ - this.cutHeight; - - /** - * The X rendering offset of this Frame, taking trim into account. - * - * @name Phaser.Textures.Frame#x - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.x = 0; - - /** - * The Y rendering offset of this Frame, taking trim into account. - * - * @name Phaser.Textures.Frame#y - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.y = 0; - - /** - * The rendering width of this Frame, taking trim into account. - * - * @name Phaser.Textures.Frame#width - * @type {integer} - * @since 3.0.0 - */ - this.width; - - /** - * The rendering height of this Frame, taking trim into account. - * - * @name Phaser.Textures.Frame#height - * @type {integer} - * @since 3.0.0 - */ - this.height; - - /** - * Half the width, floored. - * Precalculated for the renderer. - * - * @name Phaser.Textures.Frame#halfWidth - * @type {integer} - * @since 3.0.0 - */ - this.halfWidth; - - /** - * Half the height, floored. - * Precalculated for the renderer. - * - * @name Phaser.Textures.Frame#halfHeight - * @type {integer} - * @since 3.0.0 - */ - this.halfHeight; - - /** - * The x center of this frame, floored. - * - * @name Phaser.Textures.Frame#centerX - * @type {integer} - * @since 3.0.0 - */ - this.centerX; - - /** - * The y center of this frame, floored. - * - * @name Phaser.Textures.Frame#centerY - * @type {integer} - * @since 3.0.0 - */ - this.centerY; - - /** - * The horizontal pivot point of this Frame. - * - * @name Phaser.Textures.Frame#pivotX - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.pivotX = 0; - - /** - * The vertical pivot point of this Frame. - * - * @name Phaser.Textures.Frame#pivotY - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.pivotY = 0; - - /** - * Does this Frame have a custom pivot point? - * - * @name Phaser.Textures.Frame#customPivot - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.customPivot = false; - - /** - * **CURRENTLY UNSUPPORTED** - * - * Is this frame is rotated or not in the Texture? - * Rotation allows you to use rotated frames in texture atlas packing. - * It has nothing to do with Sprite rotation. - * - * @name Phaser.Textures.Frame#rotated - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.rotated = false; - - /** - * Over-rides the Renderer setting. - * -1 = use Renderer Setting - * 0 = No rounding - * 1 = Round - * - * @name Phaser.Textures.Frame#autoRound - * @type {integer} - * @default -1 - * @since 3.0.0 - */ - this.autoRound = -1; - - /** - * Any Frame specific custom data can be stored here. - * - * @name Phaser.Textures.Frame#customData - * @type {object} - * @since 3.0.0 - */ - this.customData = {}; - - /** - * WebGL UV u0 value. - * - * @name Phaser.Textures.Frame#u0 - * @type {number} - * @default 0 - * @since 3.11.0 - */ - this.u0 = 0; - - /** - * WebGL UV v0 value. - * - * @name Phaser.Textures.Frame#v0 - * @type {number} - * @default 0 - * @since 3.11.0 - */ - this.v0 = 0; - - /** - * WebGL UV u1 value. - * - * @name Phaser.Textures.Frame#u1 - * @type {number} - * @default 0 - * @since 3.11.0 - */ - this.u1 = 0; - - /** - * WebGL UV v1 value. - * - * @name Phaser.Textures.Frame#v1 - * @type {number} - * @default 0 - * @since 3.11.0 - */ - this.v1 = 0; - - /** - * The un-modified source frame, trim and UV data. - * - * @name Phaser.Textures.Frame#data - * @type {object} - * @private - * @since 3.0.0 - */ - this.data = { - cut: { - x: 0, - y: 0, - w: 0, - h: 0, - r: 0, - b: 0 - }, - trim: false, - sourceSize: { - w: 0, - h: 0 - }, - spriteSourceSize: { - x: 0, - y: 0, - w: 0, - h: 0, - r: 0, - b: 0 - }, - radius: 0, - drawImage: { - x: 0, - y: 0, - width: 0, - height: 0 - } - }; - - this.setSize(width, height, x, y); - }, - - /** - * Sets the width, height, x and y of this Frame. - * - * This is called automatically by the constructor - * and should rarely be changed on-the-fly. - * - * @method Phaser.Textures.Frame#setSize - * @since 3.7.0 - * - * @param {integer} width - The width of the frame before being trimmed. - * @param {integer} height - The height of the frame before being trimmed. - * @param {integer} [x=0] - The x coordinate of the top-left of this Frame. - * @param {integer} [y=0] - The y coordinate of the top-left of this Frame. - * - * @return {Phaser.Textures.Frame} This Frame object. - */ - setSize: function (width, height, x, y) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - - this.cutX = x; - this.cutY = y; - this.cutWidth = width; - this.cutHeight = height; - - this.width = width; - this.height = height; - - this.halfWidth = Math.floor(width * 0.5); - this.halfHeight = Math.floor(height * 0.5); - - this.centerX = Math.floor(width / 2); - this.centerY = Math.floor(height / 2); - - var data = this.data; - var cut = data.cut; - - cut.x = x; - cut.y = y; - cut.w = width; - cut.h = height; - cut.r = x + width; - cut.b = y + height; - - data.sourceSize.w = width; - data.sourceSize.h = height; - - data.spriteSourceSize.w = width; - data.spriteSourceSize.h = height; - - data.radius = 0.5 * Math.sqrt(width * width + height * height); - - var drawImage = data.drawImage; - - drawImage.x = x; - drawImage.y = y; - drawImage.width = width; - drawImage.height = height; - - return this.updateUVs(); - }, - - /** - * If the frame was trimmed when added to the Texture Atlas, this records the trim and source data. - * - * @method Phaser.Textures.Frame#setTrim - * @since 3.0.0 - * - * @param {number} actualWidth - The width of the frame before being trimmed. - * @param {number} actualHeight - The height of the frame before being trimmed. - * @param {number} destX - The destination X position of the trimmed frame for display. - * @param {number} destY - The destination Y position of the trimmed frame for display. - * @param {number} destWidth - The destination width of the trimmed frame for display. - * @param {number} destHeight - The destination height of the trimmed frame for display. - * - * @return {Phaser.Textures.Frame} This Frame object. - */ - setTrim: function (actualWidth, actualHeight, destX, destY, destWidth, destHeight) - { - var data = this.data; - var ss = data.spriteSourceSize; - - // Store actual values - - data.trim = true; - - data.sourceSize.w = actualWidth; - data.sourceSize.h = actualHeight; - - ss.x = destX; - ss.y = destY; - ss.w = destWidth; - ss.h = destHeight; - ss.r = destX + destWidth; - ss.b = destY + destHeight; - - // Adjust properties - this.x = destX; - this.y = destY; - - this.width = destWidth; - this.height = destHeight; - - this.halfWidth = destWidth * 0.5; - this.halfHeight = destHeight * 0.5; - - this.centerX = Math.floor(destWidth / 2); - this.centerY = Math.floor(destHeight / 2); - - return this.updateUVs(); - }, - - /** - * 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. - * - * 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. - */ - setCropUVs: function (crop, x, y, width, height, flipX, flipY) - { - // Clamp the input values - - var cx = this.cutX; - var cy = this.cutY; - var cw = this.cutWidth; - var ch = this.cutHeight; - var rw = this.realWidth; - var rh = this.realHeight; - - x = Clamp(x, 0, rw); - y = Clamp(y, 0, rh); - - width = Clamp(width, 0, rw - x); - height = Clamp(height, 0, rh - y); - - var ox = cx + x; - var oy = cy + y; - var ow = width; - var oh = height; - - var data = this.data; - - if (data.trim) - { - var ss = data.spriteSourceSize; - - // 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 - - width = Clamp(width, 0, cw - x); - height = Clamp(height, 0, ch - y); - - var cropRight = x + width; - var cropBottom = y + height; - - var intersects = !(ss.r < x || ss.b < y || ss.x > cropRight || ss.y > cropBottom); - - if (intersects) - { - var ix = Math.max(ss.x, x); - var iy = Math.max(ss.y, y); - var iw = Math.min(ss.r, cropRight) - ix; - var ih = Math.min(ss.b, cropBottom) - iy; - - ow = iw; - oh = ih; - - if (flipX) - { - ox = cx + (cw - (ix - ss.x) - iw); - } - else - { - ox = cx + (ix - ss.x); - } - - if (flipY) - { - oy = cy + (ch - (iy - ss.y) - ih); - } - else - { - oy = cy + (iy - ss.y); - } - - x = ix; - y = iy; - - width = iw; - height = ih; - } - else - { - ox = 0; - oy = 0; - ow = 0; - oh = 0; - } - } - else - { - if (flipX) - { - ox = cx + (cw - x - width); - } - - if (flipY) - { - oy = cy + (ch - y - height); - } - } - - var tw = this.source.width; - var th = this.source.height; - - // Map the given coordinates into UV space, clamping to the 0-1 range. - - crop.u0 = Math.max(0, ox / tw); - crop.v0 = Math.max(0, oy / th); - crop.u1 = Math.min(1, (ox + ow) / tw); - crop.v1 = Math.min(1, (oy + oh) / th); - - crop.x = x; - crop.y = y; - - crop.cx = ox; - crop.cy = oy; - crop.cw = ow; - crop.ch = oh; - - crop.width = width; - crop.height = height; - - crop.flipX = flipX; - crop.flipY = flipY; - - return crop; - }, - - /** - * 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. - */ - updateCropUVs: function (crop, flipX, flipY) - { - return this.setCropUVs(crop, crop.x, crop.y, crop.width, crop.height, flipX, flipY); - }, - - /** - * Updates the internal WebGL UV cache and the drawImage cache. - * - * @method Phaser.Textures.Frame#updateUVs - * @since 3.0.0 - * - * @return {Phaser.Textures.Frame} This Frame object. - */ - updateUVs: function () - { - var cx = this.cutX; - var cy = this.cutY; - var cw = this.cutWidth; - var ch = this.cutHeight; - - // Canvas data - - var cd = this.data.drawImage; - - cd.width = cw; - cd.height = ch; - - // WebGL data - - var tw = this.source.width; - var th = this.source.height; - - this.u0 = cx / tw; - this.v0 = cy / th; - - this.u1 = (cx + cw) / tw; - this.v1 = (cy + ch) / th; - - return this; - }, - - /** - * Updates the internal WebGL UV cache. - * - * @method Phaser.Textures.Frame#updateUVsInverted - * @since 3.0.0 - * - * @return {Phaser.Textures.Frame} This Frame object. - */ - updateUVsInverted: function () - { - var tw = this.source.width; - var th = this.source.height; - - this.u0 = (this.cutX + this.cutHeight) / tw; - this.v0 = this.cutY / th; - - this.u1 = this.cutX / tw; - this.v1 = (this.cutY + this.cutWidth) / th; - - return this; - }, - - /** - * Clones this Frame into a new Frame object. - * - * @method Phaser.Textures.Frame#clone - * @since 3.0.0 - * - * @return {Phaser.Textures.Frame} A clone of this Frame. - */ - clone: function () - { - var clone = new Frame(this.texture, this.name, this.sourceIndex); - - clone.cutX = this.cutX; - clone.cutY = this.cutY; - clone.cutWidth = this.cutWidth; - clone.cutHeight = this.cutHeight; - - clone.x = this.x; - clone.y = this.y; - - clone.width = this.width; - clone.height = this.height; - - clone.halfWidth = this.halfWidth; - clone.halfHeight = this.halfHeight; - - clone.centerX = this.centerX; - clone.centerY = this.centerY; - - clone.rotated = this.rotated; - - clone.data = Extend(true, clone.data, this.data); - - clone.updateUVs(); - - return clone; - }, - - /** - * Destroys this Frame by nulling its reference to the parent Texture and and data objects. - * - * @method Phaser.Textures.Frame#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.source = null; - this.texture = null; - this.glTexture = null; - this.customData = null; - this.data = null; - }, - - /** - * The width of the Frame in its un-trimmed, un-padded state, as prepared in the art package, - * before being packed. - * - * @name Phaser.Textures.Frame#realWidth - * @type {number} - * @readonly - * @since 3.0.0 - */ - realWidth: { - - get: function () - { - return this.data.sourceSize.w; - } - - }, - - /** - * The height of the Frame in its un-trimmed, un-padded state, as prepared in the art package, - * before being packed. - * - * @name Phaser.Textures.Frame#realHeight - * @type {number} - * @readonly - * @since 3.0.0 - */ - realHeight: { - - get: function () - { - return this.data.sourceSize.h; - } - - }, - - /** - * The radius of the Frame (derived from sqrt(w * w + h * h) / 2) - * - * @name Phaser.Textures.Frame#radius - * @type {number} - * @readonly - * @since 3.0.0 - */ - radius: { - - get: function () - { - return this.data.radius; - } - - }, - - /** - * Is the Frame trimmed or not? - * - * @name Phaser.Textures.Frame#trimmed - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - trimmed: { - - get: function () - { - return this.data.trim; - } - - }, - - /** - * The Canvas drawImage data object. - * - * @name Phaser.Textures.Frame#canvasData - * @type {object} - * @readonly - * @since 3.0.0 - */ - canvasData: { - - get: function () - { - return this.data.drawImage; - } - - } - -}); - -module.exports = Frame; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Clamp = require('../math/Clamp'); +var Extend = require('../utils/object/Extend'); + +/** + * @classdesc + * A Frame is a section of a Texture. + * + * @class Frame + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture this Frame is a part of. + * @param {(integer|string)} name - The name of this Frame. The name is unique within the Texture. + * @param {integer} sourceIndex - The index of the TextureSource that this Frame is a part of. + * @param {number} x - The x coordinate of the top-left of this Frame. + * @param {number} y - The y coordinate of the top-left of this Frame. + * @param {number} width - The width of this Frame. + * @param {number} height - The height of this Frame. + */ +var Frame = new Class({ + + initialize: + + function Frame (texture, name, sourceIndex, x, y, width, height) + { + /** + * The Texture this Frame is a part of. + * + * @name Phaser.Textures.Frame#texture + * @type {Phaser.Textures.Texture} + * @since 3.0.0 + */ + this.texture = texture; + + /** + * The name of this Frame. + * The name is unique within the Texture. + * + * @name Phaser.Textures.Frame#name + * @type {string} + * @since 3.0.0 + */ + this.name = name; + + /** + * The TextureSource this Frame is part of. + * + * @name Phaser.Textures.Frame#source + * @type {Phaser.Textures.TextureSource} + * @since 3.0.0 + */ + this.source = texture.source[sourceIndex]; + + /** + * The index of the TextureSource in the Texture sources array. + * + * @name Phaser.Textures.Frame#sourceIndex + * @type {integer} + * @since 3.0.0 + */ + this.sourceIndex = sourceIndex; + + /** + * A reference to the Texture Source WebGL Texture that this Frame is using. + * + * @name Phaser.Textures.Frame#glTexture + * @type {?WebGLTexture} + * @default null + * @since 3.11.0 + */ + this.glTexture = this.source.glTexture; + + /** + * X position within the source image to cut from. + * + * @name Phaser.Textures.Frame#cutX + * @type {integer} + * @since 3.0.0 + */ + this.cutX; + + /** + * Y position within the source image to cut from. + * + * @name Phaser.Textures.Frame#cutY + * @type {integer} + * @since 3.0.0 + */ + this.cutY; + + /** + * The width of the area in the source image to cut. + * + * @name Phaser.Textures.Frame#cutWidth + * @type {integer} + * @since 3.0.0 + */ + this.cutWidth; + + /** + * The height of the area in the source image to cut. + * + * @name Phaser.Textures.Frame#cutHeight + * @type {integer} + * @since 3.0.0 + */ + this.cutHeight; + + /** + * The X rendering offset of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#x + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.x = 0; + + /** + * The Y rendering offset of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#y + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.y = 0; + + /** + * The rendering width of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#width + * @type {integer} + * @since 3.0.0 + */ + this.width; + + /** + * The rendering height of this Frame, taking trim into account. + * + * @name Phaser.Textures.Frame#height + * @type {integer} + * @since 3.0.0 + */ + this.height; + + /** + * Half the width, floored. + * Precalculated for the renderer. + * + * @name Phaser.Textures.Frame#halfWidth + * @type {integer} + * @since 3.0.0 + */ + this.halfWidth; + + /** + * Half the height, floored. + * Precalculated for the renderer. + * + * @name Phaser.Textures.Frame#halfHeight + * @type {integer} + * @since 3.0.0 + */ + this.halfHeight; + + /** + * The x center of this frame, floored. + * + * @name Phaser.Textures.Frame#centerX + * @type {integer} + * @since 3.0.0 + */ + this.centerX; + + /** + * The y center of this frame, floored. + * + * @name Phaser.Textures.Frame#centerY + * @type {integer} + * @since 3.0.0 + */ + this.centerY; + + /** + * The horizontal pivot point of this Frame. + * + * @name Phaser.Textures.Frame#pivotX + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.pivotX = 0; + + /** + * The vertical pivot point of this Frame. + * + * @name Phaser.Textures.Frame#pivotY + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.pivotY = 0; + + /** + * Does this Frame have a custom pivot point? + * + * @name Phaser.Textures.Frame#customPivot + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.customPivot = false; + + /** + * **CURRENTLY UNSUPPORTED** + * + * Is this frame is rotated or not in the Texture? + * Rotation allows you to use rotated frames in texture atlas packing. + * It has nothing to do with Sprite rotation. + * + * @name Phaser.Textures.Frame#rotated + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.rotated = false; + + /** + * Over-rides the Renderer setting. + * -1 = use Renderer Setting + * 0 = No rounding + * 1 = Round + * + * @name Phaser.Textures.Frame#autoRound + * @type {integer} + * @default -1 + * @since 3.0.0 + */ + this.autoRound = -1; + + /** + * Any Frame specific custom data can be stored here. + * + * @name Phaser.Textures.Frame#customData + * @type {object} + * @since 3.0.0 + */ + this.customData = {}; + + /** + * WebGL UV u0 value. + * + * @name Phaser.Textures.Frame#u0 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.u0 = 0; + + /** + * WebGL UV v0 value. + * + * @name Phaser.Textures.Frame#v0 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.v0 = 0; + + /** + * WebGL UV u1 value. + * + * @name Phaser.Textures.Frame#u1 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.u1 = 0; + + /** + * WebGL UV v1 value. + * + * @name Phaser.Textures.Frame#v1 + * @type {number} + * @default 0 + * @since 3.11.0 + */ + this.v1 = 0; + + /** + * The un-modified source frame, trim and UV data. + * + * @name Phaser.Textures.Frame#data + * @type {object} + * @private + * @since 3.0.0 + */ + this.data = { + cut: { + x: 0, + y: 0, + w: 0, + h: 0, + r: 0, + b: 0 + }, + trim: false, + sourceSize: { + w: 0, + h: 0 + }, + spriteSourceSize: { + x: 0, + y: 0, + w: 0, + h: 0, + r: 0, + b: 0 + }, + radius: 0, + drawImage: { + x: 0, + y: 0, + width: 0, + height: 0 + } + }; + + this.setSize(width, height, x, y); + }, + + /** + * Sets the width, height, x and y of this Frame. + * + * This is called automatically by the constructor + * and should rarely be changed on-the-fly. + * + * @method Phaser.Textures.Frame#setSize + * @since 3.7.0 + * + * @param {integer} width - The width of the frame before being trimmed. + * @param {integer} height - The height of the frame before being trimmed. + * @param {integer} [x=0] - The x coordinate of the top-left of this Frame. + * @param {integer} [y=0] - The y coordinate of the top-left of this Frame. + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + setSize: function (width, height, x, y) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + this.cutX = x; + this.cutY = y; + this.cutWidth = width; + this.cutHeight = height; + + this.width = width; + this.height = height; + + this.halfWidth = Math.floor(width * 0.5); + this.halfHeight = Math.floor(height * 0.5); + + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + + var data = this.data; + var cut = data.cut; + + cut.x = x; + cut.y = y; + cut.w = width; + cut.h = height; + cut.r = x + width; + cut.b = y + height; + + data.sourceSize.w = width; + data.sourceSize.h = height; + + data.spriteSourceSize.w = width; + data.spriteSourceSize.h = height; + + data.radius = 0.5 * Math.sqrt(width * width + height * height); + + var drawImage = data.drawImage; + + drawImage.x = x; + drawImage.y = y; + drawImage.width = width; + drawImage.height = height; + + return this.updateUVs(); + }, + + /** + * If the frame was trimmed when added to the Texture Atlas, this records the trim and source data. + * + * @method Phaser.Textures.Frame#setTrim + * @since 3.0.0 + * + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + setTrim: function (actualWidth, actualHeight, destX, destY, destWidth, destHeight) + { + var data = this.data; + var ss = data.spriteSourceSize; + + // Store actual values + + data.trim = true; + + data.sourceSize.w = actualWidth; + data.sourceSize.h = actualHeight; + + ss.x = destX; + ss.y = destY; + ss.w = destWidth; + ss.h = destHeight; + ss.r = destX + destWidth; + ss.b = destY + destHeight; + + // Adjust properties + this.x = destX; + this.y = destY; + + this.width = destWidth; + this.height = destHeight; + + this.halfWidth = destWidth * 0.5; + this.halfHeight = destHeight * 0.5; + + this.centerX = Math.floor(destWidth / 2); + this.centerY = Math.floor(destHeight / 2); + + return this.updateUVs(); + }, + + /** + * 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. + * + * 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. + */ + setCropUVs: function (crop, x, y, width, height, flipX, flipY) + { + // Clamp the input values + + var cx = this.cutX; + var cy = this.cutY; + var cw = this.cutWidth; + var ch = this.cutHeight; + var rw = this.realWidth; + var rh = this.realHeight; + + x = Clamp(x, 0, rw); + y = Clamp(y, 0, rh); + + width = Clamp(width, 0, rw - x); + height = Clamp(height, 0, rh - y); + + var ox = cx + x; + var oy = cy + y; + var ow = width; + var oh = height; + + var data = this.data; + + if (data.trim) + { + var ss = data.spriteSourceSize; + + // 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 + + width = Clamp(width, 0, cw - x); + height = Clamp(height, 0, ch - y); + + var cropRight = x + width; + var cropBottom = y + height; + + var intersects = !(ss.r < x || ss.b < y || ss.x > cropRight || ss.y > cropBottom); + + if (intersects) + { + var ix = Math.max(ss.x, x); + var iy = Math.max(ss.y, y); + var iw = Math.min(ss.r, cropRight) - ix; + var ih = Math.min(ss.b, cropBottom) - iy; + + ow = iw; + oh = ih; + + if (flipX) + { + ox = cx + (cw - (ix - ss.x) - iw); + } + else + { + ox = cx + (ix - ss.x); + } + + if (flipY) + { + oy = cy + (ch - (iy - ss.y) - ih); + } + else + { + oy = cy + (iy - ss.y); + } + + x = ix; + y = iy; + + width = iw; + height = ih; + } + else + { + ox = 0; + oy = 0; + ow = 0; + oh = 0; + } + } + else + { + if (flipX) + { + ox = cx + (cw - x - width); + } + + if (flipY) + { + oy = cy + (ch - y - height); + } + } + + var tw = this.source.width; + var th = this.source.height; + + // Map the given coordinates into UV space, clamping to the 0-1 range. + + crop.u0 = Math.max(0, ox / tw); + crop.v0 = Math.max(0, oy / th); + crop.u1 = Math.min(1, (ox + ow) / tw); + crop.v1 = Math.min(1, (oy + oh) / th); + + crop.x = x; + crop.y = y; + + crop.cx = ox; + crop.cy = oy; + crop.cw = ow; + crop.ch = oh; + + crop.width = width; + crop.height = height; + + crop.flipX = flipX; + crop.flipY = flipY; + + return crop; + }, + + /** + * 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. + */ + updateCropUVs: function (crop, flipX, flipY) + { + return this.setCropUVs(crop, crop.x, crop.y, crop.width, crop.height, flipX, flipY); + }, + + /** + * Updates the internal WebGL UV cache and the drawImage cache. + * + * @method Phaser.Textures.Frame#updateUVs + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + updateUVs: function () + { + var cx = this.cutX; + var cy = this.cutY; + var cw = this.cutWidth; + var ch = this.cutHeight; + + // Canvas data + + var cd = this.data.drawImage; + + cd.width = cw; + cd.height = ch; + + // WebGL data + + var tw = this.source.width; + var th = this.source.height; + + this.u0 = cx / tw; + this.v0 = cy / th; + + this.u1 = (cx + cw) / tw; + this.v1 = (cy + ch) / th; + + return this; + }, + + /** + * Updates the internal WebGL UV cache. + * + * @method Phaser.Textures.Frame#updateUVsInverted + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} This Frame object. + */ + updateUVsInverted: function () + { + var tw = this.source.width; + var th = this.source.height; + + this.u0 = (this.cutX + this.cutHeight) / tw; + this.v0 = this.cutY / th; + + this.u1 = this.cutX / tw; + this.v1 = (this.cutY + this.cutWidth) / th; + + return this; + }, + + /** + * Clones this Frame into a new Frame object. + * + * @method Phaser.Textures.Frame#clone + * @since 3.0.0 + * + * @return {Phaser.Textures.Frame} A clone of this Frame. + */ + clone: function () + { + var clone = new Frame(this.texture, this.name, this.sourceIndex); + + clone.cutX = this.cutX; + clone.cutY = this.cutY; + clone.cutWidth = this.cutWidth; + clone.cutHeight = this.cutHeight; + + clone.x = this.x; + clone.y = this.y; + + clone.width = this.width; + clone.height = this.height; + + clone.halfWidth = this.halfWidth; + clone.halfHeight = this.halfHeight; + + clone.centerX = this.centerX; + clone.centerY = this.centerY; + + clone.rotated = this.rotated; + + clone.data = Extend(true, clone.data, this.data); + + clone.updateUVs(); + + return clone; + }, + + /** + * Destroys this Frame by nulling its reference to the parent Texture and and data objects. + * + * @method Phaser.Textures.Frame#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.source = null; + this.texture = null; + this.glTexture = null; + this.customData = null; + this.data = null; + }, + + /** + * The width of the Frame in its un-trimmed, un-padded state, as prepared in the art package, + * before being packed. + * + * @name Phaser.Textures.Frame#realWidth + * @type {number} + * @readonly + * @since 3.0.0 + */ + realWidth: { + + get: function () + { + return this.data.sourceSize.w; + } + + }, + + /** + * The height of the Frame in its un-trimmed, un-padded state, as prepared in the art package, + * before being packed. + * + * @name Phaser.Textures.Frame#realHeight + * @type {number} + * @readonly + * @since 3.0.0 + */ + realHeight: { + + get: function () + { + return this.data.sourceSize.h; + } + + }, + + /** + * The radius of the Frame (derived from sqrt(w * w + h * h) / 2) + * + * @name Phaser.Textures.Frame#radius + * @type {number} + * @readonly + * @since 3.0.0 + */ + radius: { + + get: function () + { + return this.data.radius; + } + + }, + + /** + * Is the Frame trimmed or not? + * + * @name Phaser.Textures.Frame#trimmed + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + trimmed: { + + get: function () + { + return this.data.trim; + } + + }, + + /** + * The Canvas drawImage data object. + * + * @name Phaser.Textures.Frame#canvasData + * @type {object} + * @readonly + * @since 3.0.0 + */ + canvasData: { + + get: function () + { + return this.data.drawImage; + } + + } + +}); + +module.exports = Frame; diff --git a/src/textures/Texture.js b/src/textures/Texture.js index f74626152..252f99433 100644 --- a/src/textures/Texture.js +++ b/src/textures/Texture.js @@ -1,514 +1,514 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var Frame = require('./Frame'); -var TextureSource = require('./TextureSource'); - -var TEXTURE_MISSING_ERROR = 'Texture.frame missing: '; - -/** - * @classdesc - * A Texture consists of a source, usually an Image from the Cache, and a collection of Frames. - * The Frames represent the different areas of the Texture. For example a texture atlas - * may have many Frames, one for each element within the atlas. Where-as a single image would have - * just one frame, that encompasses the whole image. - * - * Every Texture, no matter where it comes from, always has at least 1 frame called the `__BASE` frame. - * This frame represents the entirety of the source image. - * - * Textures are managed by the global TextureManager. This is a singleton class that is - * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. - * - * Sprites and other Game Objects get the texture data they need from the TextureManager. - * - * @class Texture - * @memberof Phaser.Textures - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Textures.TextureManager} manager - A reference to the Texture Manager this Texture belongs to. - * @param {string} key - The unique string-based key of this Texture. - * @param {(HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[])} source - An array of sources that are used to create the texture. Usually Images, but can also be a Canvas. - * @param {number} [width] - The width of the Texture. This is optional and automatically derived from the source images. - * @param {number} [height] - The height of the Texture. This is optional and automatically derived from the source images. - */ -var Texture = new Class({ - - initialize: - - function Texture (manager, key, source, width, height) - { - if (!Array.isArray(source)) - { - source = [ source ]; - } - - /** - * A reference to the Texture Manager this Texture belongs to. - * - * @name Phaser.Textures.Texture#manager - * @type {Phaser.Textures.TextureManager} - * @since 3.0.0 - */ - this.manager = manager; - - /** - * The unique string-based key of this Texture. - * - * @name Phaser.Textures.Texture#key - * @type {string} - * @since 3.0.0 - */ - this.key = key; - - /** - * An array of TextureSource instances. - * These are unique to this Texture and contain the actual Image (or Canvas) data. - * - * @name Phaser.Textures.Texture#source - * @type {Phaser.Textures.TextureSource[]} - * @since 3.0.0 - */ - this.source = []; - - /** - * An array of TextureSource data instances. - * Used to store additional data images, such as normal maps or specular maps. - * - * @name Phaser.Textures.Texture#dataSource - * @type {array} - * @since 3.0.0 - */ - this.dataSource = []; - - /** - * A key-value object pair associating the unique Frame keys with the Frames objects. - * - * @name Phaser.Textures.Texture#frames - * @type {object} - * @since 3.0.0 - */ - this.frames = {}; - - /** - * Any additional data that was set in the source JSON (if any), - * or any extra data you'd like to store relating to this texture - * - * @name Phaser.Textures.Texture#customData - * @type {object} - * @since 3.0.0 - */ - this.customData = {}; - - /** - * The name of the first frame of the Texture. - * - * @name Phaser.Textures.Texture#firstFrame - * @type {string} - * @since 3.0.0 - */ - this.firstFrame = '__BASE'; - - /** - * The total number of Frames in this Texture, including the `__BASE` frame. - * - * A Texture will always contain at least 1 frame because every Texture contains a `__BASE` frame by default, - * in addition to any extra frames that have been added to it, such as when parsing a Sprite Sheet or Texture Atlas. - * - * @name Phaser.Textures.Texture#frameTotal - * @type {integer} - * @default 0 - * @since 3.0.0 - */ - this.frameTotal = 0; - - // Load the Sources - for (var i = 0; i < source.length; i++) - { - this.source.push(new TextureSource(this, source[i], width, height)); - } - }, - - /** - * Adds a new Frame to this Texture. - * - * A Frame is a rectangular region of a TextureSource with a unique index or string-based key. - * - * The name given must be unique within this Texture. If it already exists, this method will return `null`. - * - * @method Phaser.Textures.Texture#add - * @since 3.0.0 - * - * @param {(integer|string)} name - The name of this Frame. The name is unique within the Texture. - * @param {integer} sourceIndex - The index of the TextureSource that this Frame is a part of. - * @param {number} x - The x coordinate of the top-left of this Frame. - * @param {number} y - The y coordinate of the top-left of this Frame. - * @param {number} width - The width of this Frame. - * @param {number} height - The height of this Frame. - * - * @return {?Phaser.Textures.Frame} The Frame that was added to this Texture, or `null` if the given name already exists. - */ - add: function (name, sourceIndex, x, y, width, height) - { - if (this.has(name)) - { - return null; - } - - var frame = new Frame(this, name, sourceIndex, x, y, width, height); - - this.frames[name] = frame; - - // 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 - if (this.firstFrame === '__BASE') - { - this.firstFrame = name; - } - - this.frameTotal++; - - return frame; - }, - - /** - * Removes the given Frame from this Texture. The Frame is destroyed immediately. - * - * Any Game Objects using this Frame should stop using it _before_ you remove it, - * as it does not happen automatically. - * - * @method Phaser.Textures.Texture#remove - * @since 3.19.0 - * - * @param {string} name - The key of the Frame to remove. - * - * @return {boolean} True if a Frame with the matching key was removed from this Texture. - */ - remove: function (name) - { - if (this.has(name)) - { - var frame = this.get(name); - - frame.destroy(); - - delete this.frames[name]; - - return true; - } - - return false; - }, - - /** - * Checks to see if a Frame matching the given key exists within this Texture. - * - * @method Phaser.Textures.Texture#has - * @since 3.0.0 - * - * @param {string} name - The key of the Frame to check for. - * - * @return {boolean} True if a Frame with the matching key exists in this Texture. - */ - has: function (name) - { - return (this.frames[name]); - }, - - /** - * 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|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. - * - * @return {Phaser.Textures.Frame} The Texture Frame. - */ - get: function (name) - { - // null, undefined, empty string, zero - if (!name) - { - name = this.firstFrame; - } - - var frame = this.frames[name]; - - if (!frame) - { - console.warn(TEXTURE_MISSING_ERROR + name); - - frame = this.frames[this.firstFrame]; - } - - return frame; - }, - - /** - * Takes the given TextureSource and returns the index of it within this Texture. - * If it's not in this Texture, it returns -1. - * Unless this Texture has multiple TextureSources, such as with a multi-atlas, this - * method will always return zero or -1. - * - * @method Phaser.Textures.Texture#getTextureSourceIndex - * @since 3.0.0 - * - * @param {Phaser.Textures.TextureSource} source - The TextureSource to check. - * - * @return {integer} The index of the TextureSource within this Texture, or -1 if not in this Texture. - */ - getTextureSourceIndex: function (source) - { - for (var i = 0; i < this.source.length; i++) - { - if (this.source[i] === source) - { - return i; - } - } - - return -1; - }, - - /** - * Returns an array of all the Frames in the given TextureSource. - * - * @method Phaser.Textures.Texture#getFramesFromTextureSource - * @since 3.0.0 - * - * @param {integer} sourceIndex - The index of the TextureSource to get the Frames from. - * @param {boolean} [includeBase=false] - Include the `__BASE` Frame in the output array? - * - * @return {Phaser.Textures.Frame[]} An array of Texture Frames. - */ - getFramesFromTextureSource: function (sourceIndex, includeBase) - { - if (includeBase === undefined) { includeBase = false; } - - var out = []; - - for (var frameName in this.frames) - { - if (frameName === '__BASE' && !includeBase) - { - continue; - } - - var frame = this.frames[frameName]; - - if (frame.sourceIndex === sourceIndex) - { - out.push(frame); - } - } - - return out; - }, - - /** - * Returns an array with all of the names of the Frames in this Texture. - * - * Useful if you want to randomly assign a Frame to a Game Object, as you can - * pick a random element from the returned array. - * - * @method Phaser.Textures.Texture#getFrameNames - * @since 3.0.0 - * - * @param {boolean} [includeBase=false] - Include the `__BASE` Frame in the output array? - * - * @return {string[]} An array of all Frame names in this Texture. - */ - getFrameNames: function (includeBase) - { - if (includeBase === undefined) { includeBase = false; } - - var out = Object.keys(this.frames); - - if (!includeBase) - { - var idx = out.indexOf('__BASE'); - - if (idx !== -1) - { - out.splice(idx, 1); - } - } - - return out; - }, - - /** - * Given a Frame name, return the source image it uses to render with. - * - * This will return the actual DOM Image or Canvas element. - * - * @method Phaser.Textures.Texture#getSourceImage - * @since 3.0.0 - * - * @param {(string|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. - * - * @return {(HTMLImageElement|HTMLCanvasElement|Phaser.GameObjects.RenderTexture)} The DOM Image, Canvas Element or Render Texture. - */ - getSourceImage: function (name) - { - if (name === undefined || name === null || this.frameTotal === 1) - { - name = '__BASE'; - } - - var frame = this.frames[name]; - - if (frame) - { - return frame.source.image; - } - else - { - console.warn(TEXTURE_MISSING_ERROR + name); - - return this.frames['__BASE'].source.image; - } - }, - - /** - * Given a Frame name, return the data source image it uses to render with. - * You can use this to get the normal map for an image for example. - * - * This will return the actual DOM Image. - * - * @method Phaser.Textures.Texture#getDataSourceImage - * @since 3.7.0 - * - * @param {(string|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. - * - * @return {(HTMLImageElement|HTMLCanvasElement)} The DOM Image or Canvas Element. - */ - getDataSourceImage: function (name) - { - if (name === undefined || name === null || this.frameTotal === 1) - { - name = '__BASE'; - } - - var frame = this.frames[name]; - var idx; - - if (!frame) - { - console.warn(TEXTURE_MISSING_ERROR + name); - - idx = this.frames['__BASE'].sourceIndex; - } - else - { - idx = frame.sourceIndex; - } - - return this.dataSource[idx].image; - }, - - /** - * Adds a data source image to this Texture. - * - * An example of a data source image would be a normal map, where all of the Frames for this Texture - * equally apply to the normal map. - * - * @method Phaser.Textures.Texture#setDataSource - * @since 3.0.0 - * - * @param {(HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[])} data - The source image. - */ - setDataSource: function (data) - { - if (!Array.isArray(data)) - { - data = [ data ]; - } - - for (var i = 0; i < data.length; i++) - { - var source = this.source[i]; - - this.dataSource.push(new TextureSource(this, data[i], source.width, source.height)); - } - }, - - /** - * Sets the Filter Mode for this Texture. - * - * The mode can be either Linear, the default, or Nearest. - * - * For pixel-art you should use Nearest. - * - * The mode applies to the entire Texture, not just a specific Frame of it. - * - * @method Phaser.Textures.Texture#setFilter - * @since 3.0.0 - * - * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode. - */ - setFilter: function (filterMode) - { - var i; - - for (i = 0; i < this.source.length; i++) - { - this.source[i].setFilter(filterMode); - } - - for (i = 0; i < this.dataSource.length; i++) - { - this.dataSource[i].setFilter(filterMode); - } - }, - - /** - * Destroys this Texture and releases references to its sources and frames. - * - * @method Phaser.Textures.Texture#destroy - * @since 3.0.0 - */ - destroy: function () - { - var i; - - for (i = 0; i < this.source.length; i++) - { - this.source[i].destroy(); - } - - for (i = 0; i < this.dataSource.length; i++) - { - this.dataSource[i].destroy(); - } - - for (var frameName in this.frames) - { - var frame = this.frames[frameName]; - - frame.destroy(); - } - - this.source = []; - this.dataSource = []; - this.frames = {}; - - this.manager.removeKey(this.key); - - this.manager = null; - } - -}); - -module.exports = Texture; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var Frame = require('./Frame'); +var TextureSource = require('./TextureSource'); + +var TEXTURE_MISSING_ERROR = 'Texture.frame missing: '; + +/** + * @classdesc + * A Texture consists of a source, usually an Image from the Cache, and a collection of Frames. + * The Frames represent the different areas of the Texture. For example a texture atlas + * may have many Frames, one for each element within the atlas. Where-as a single image would have + * just one frame, that encompasses the whole image. + * + * Every Texture, no matter where it comes from, always has at least 1 frame called the `__BASE` frame. + * This frame represents the entirety of the source image. + * + * Textures are managed by the global TextureManager. This is a singleton class that is + * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. + * + * Sprites and other Game Objects get the texture data they need from the TextureManager. + * + * @class Texture + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Textures.TextureManager} manager - A reference to the Texture Manager this Texture belongs to. + * @param {string} key - The unique string-based key of this Texture. + * @param {(HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[])} source - An array of sources that are used to create the texture. Usually Images, but can also be a Canvas. + * @param {number} [width] - The width of the Texture. This is optional and automatically derived from the source images. + * @param {number} [height] - The height of the Texture. This is optional and automatically derived from the source images. + */ +var Texture = new Class({ + + initialize: + + function Texture (manager, key, source, width, height) + { + if (!Array.isArray(source)) + { + source = [ source ]; + } + + /** + * A reference to the Texture Manager this Texture belongs to. + * + * @name Phaser.Textures.Texture#manager + * @type {Phaser.Textures.TextureManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * The unique string-based key of this Texture. + * + * @name Phaser.Textures.Texture#key + * @type {string} + * @since 3.0.0 + */ + this.key = key; + + /** + * An array of TextureSource instances. + * These are unique to this Texture and contain the actual Image (or Canvas) data. + * + * @name Phaser.Textures.Texture#source + * @type {Phaser.Textures.TextureSource[]} + * @since 3.0.0 + */ + this.source = []; + + /** + * An array of TextureSource data instances. + * Used to store additional data images, such as normal maps or specular maps. + * + * @name Phaser.Textures.Texture#dataSource + * @type {array} + * @since 3.0.0 + */ + this.dataSource = []; + + /** + * A key-value object pair associating the unique Frame keys with the Frames objects. + * + * @name Phaser.Textures.Texture#frames + * @type {object} + * @since 3.0.0 + */ + this.frames = {}; + + /** + * Any additional data that was set in the source JSON (if any), + * or any extra data you'd like to store relating to this texture + * + * @name Phaser.Textures.Texture#customData + * @type {object} + * @since 3.0.0 + */ + this.customData = {}; + + /** + * The name of the first frame of the Texture. + * + * @name Phaser.Textures.Texture#firstFrame + * @type {string} + * @since 3.0.0 + */ + this.firstFrame = '__BASE'; + + /** + * The total number of Frames in this Texture, including the `__BASE` frame. + * + * A Texture will always contain at least 1 frame because every Texture contains a `__BASE` frame by default, + * in addition to any extra frames that have been added to it, such as when parsing a Sprite Sheet or Texture Atlas. + * + * @name Phaser.Textures.Texture#frameTotal + * @type {integer} + * @default 0 + * @since 3.0.0 + */ + this.frameTotal = 0; + + // Load the Sources + for (var i = 0; i < source.length; i++) + { + this.source.push(new TextureSource(this, source[i], width, height)); + } + }, + + /** + * Adds a new Frame to this Texture. + * + * A Frame is a rectangular region of a TextureSource with a unique index or string-based key. + * + * The name given must be unique within this Texture. If it already exists, this method will return `null`. + * + * @method Phaser.Textures.Texture#add + * @since 3.0.0 + * + * @param {(integer|string)} name - The name of this Frame. The name is unique within the Texture. + * @param {integer} sourceIndex - The index of the TextureSource that this Frame is a part of. + * @param {number} x - The x coordinate of the top-left of this Frame. + * @param {number} y - The y coordinate of the top-left of this Frame. + * @param {number} width - The width of this Frame. + * @param {number} height - The height of this Frame. + * + * @return {?Phaser.Textures.Frame} The Frame that was added to this Texture, or `null` if the given name already exists. + */ + add: function (name, sourceIndex, x, y, width, height) + { + if (this.has(name)) + { + return null; + } + + var frame = new Frame(this, name, sourceIndex, x, y, width, height); + + this.frames[name] = frame; + + // 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 + if (this.firstFrame === '__BASE') + { + this.firstFrame = name; + } + + this.frameTotal++; + + return frame; + }, + + /** + * Removes the given Frame from this Texture. The Frame is destroyed immediately. + * + * Any Game Objects using this Frame should stop using it _before_ you remove it, + * as it does not happen automatically. + * + * @method Phaser.Textures.Texture#remove + * @since 3.19.0 + * + * @param {string} name - The key of the Frame to remove. + * + * @return {boolean} True if a Frame with the matching key was removed from this Texture. + */ + remove: function (name) + { + if (this.has(name)) + { + var frame = this.get(name); + + frame.destroy(); + + delete this.frames[name]; + + return true; + } + + return false; + }, + + /** + * Checks to see if a Frame matching the given key exists within this Texture. + * + * @method Phaser.Textures.Texture#has + * @since 3.0.0 + * + * @param {string} name - The key of the Frame to check for. + * + * @return {boolean} True if a Frame with the matching key exists in this Texture. + */ + has: function (name) + { + return (this.frames[name]); + }, + + /** + * 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|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. + * + * @return {Phaser.Textures.Frame} The Texture Frame. + */ + get: function (name) + { + // null, undefined, empty string, zero + if (!name) + { + name = this.firstFrame; + } + + var frame = this.frames[name]; + + if (!frame) + { + console.warn(TEXTURE_MISSING_ERROR + name); + + frame = this.frames[this.firstFrame]; + } + + return frame; + }, + + /** + * Takes the given TextureSource and returns the index of it within this Texture. + * If it's not in this Texture, it returns -1. + * Unless this Texture has multiple TextureSources, such as with a multi-atlas, this + * method will always return zero or -1. + * + * @method Phaser.Textures.Texture#getTextureSourceIndex + * @since 3.0.0 + * + * @param {Phaser.Textures.TextureSource} source - The TextureSource to check. + * + * @return {integer} The index of the TextureSource within this Texture, or -1 if not in this Texture. + */ + getTextureSourceIndex: function (source) + { + for (var i = 0; i < this.source.length; i++) + { + if (this.source[i] === source) + { + return i; + } + } + + return -1; + }, + + /** + * Returns an array of all the Frames in the given TextureSource. + * + * @method Phaser.Textures.Texture#getFramesFromTextureSource + * @since 3.0.0 + * + * @param {integer} sourceIndex - The index of the TextureSource to get the Frames from. + * @param {boolean} [includeBase=false] - Include the `__BASE` Frame in the output array? + * + * @return {Phaser.Textures.Frame[]} An array of Texture Frames. + */ + getFramesFromTextureSource: function (sourceIndex, includeBase) + { + if (includeBase === undefined) { includeBase = false; } + + var out = []; + + for (var frameName in this.frames) + { + if (frameName === '__BASE' && !includeBase) + { + continue; + } + + var frame = this.frames[frameName]; + + if (frame.sourceIndex === sourceIndex) + { + out.push(frame); + } + } + + return out; + }, + + /** + * Returns an array with all of the names of the Frames in this Texture. + * + * Useful if you want to randomly assign a Frame to a Game Object, as you can + * pick a random element from the returned array. + * + * @method Phaser.Textures.Texture#getFrameNames + * @since 3.0.0 + * + * @param {boolean} [includeBase=false] - Include the `__BASE` Frame in the output array? + * + * @return {string[]} An array of all Frame names in this Texture. + */ + getFrameNames: function (includeBase) + { + if (includeBase === undefined) { includeBase = false; } + + var out = Object.keys(this.frames); + + if (!includeBase) + { + var idx = out.indexOf('__BASE'); + + if (idx !== -1) + { + out.splice(idx, 1); + } + } + + return out; + }, + + /** + * Given a Frame name, return the source image it uses to render with. + * + * This will return the actual DOM Image or Canvas element. + * + * @method Phaser.Textures.Texture#getSourceImage + * @since 3.0.0 + * + * @param {(string|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. + * + * @return {(HTMLImageElement|HTMLCanvasElement|Phaser.GameObjects.RenderTexture)} The DOM Image, Canvas Element or Render Texture. + */ + getSourceImage: function (name) + { + if (name === undefined || name === null || this.frameTotal === 1) + { + name = '__BASE'; + } + + var frame = this.frames[name]; + + if (frame) + { + return frame.source.image; + } + else + { + console.warn(TEXTURE_MISSING_ERROR + name); + + return this.frames['__BASE'].source.image; + } + }, + + /** + * Given a Frame name, return the data source image it uses to render with. + * You can use this to get the normal map for an image for example. + * + * This will return the actual DOM Image. + * + * @method Phaser.Textures.Texture#getDataSourceImage + * @since 3.7.0 + * + * @param {(string|integer)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture. + * + * @return {(HTMLImageElement|HTMLCanvasElement)} The DOM Image or Canvas Element. + */ + getDataSourceImage: function (name) + { + if (name === undefined || name === null || this.frameTotal === 1) + { + name = '__BASE'; + } + + var frame = this.frames[name]; + var idx; + + if (!frame) + { + console.warn(TEXTURE_MISSING_ERROR + name); + + idx = this.frames['__BASE'].sourceIndex; + } + else + { + idx = frame.sourceIndex; + } + + return this.dataSource[idx].image; + }, + + /** + * Adds a data source image to this Texture. + * + * An example of a data source image would be a normal map, where all of the Frames for this Texture + * equally apply to the normal map. + * + * @method Phaser.Textures.Texture#setDataSource + * @since 3.0.0 + * + * @param {(HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[])} data - The source image. + */ + setDataSource: function (data) + { + if (!Array.isArray(data)) + { + data = [ data ]; + } + + for (var i = 0; i < data.length; i++) + { + var source = this.source[i]; + + this.dataSource.push(new TextureSource(this, data[i], source.width, source.height)); + } + }, + + /** + * Sets the Filter Mode for this Texture. + * + * The mode can be either Linear, the default, or Nearest. + * + * For pixel-art you should use Nearest. + * + * The mode applies to the entire Texture, not just a specific Frame of it. + * + * @method Phaser.Textures.Texture#setFilter + * @since 3.0.0 + * + * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode. + */ + setFilter: function (filterMode) + { + var i; + + for (i = 0; i < this.source.length; i++) + { + this.source[i].setFilter(filterMode); + } + + for (i = 0; i < this.dataSource.length; i++) + { + this.dataSource[i].setFilter(filterMode); + } + }, + + /** + * Destroys this Texture and releases references to its sources and frames. + * + * @method Phaser.Textures.Texture#destroy + * @since 3.0.0 + */ + destroy: function () + { + var i; + + for (i = 0; i < this.source.length; i++) + { + this.source[i].destroy(); + } + + for (i = 0; i < this.dataSource.length; i++) + { + this.dataSource[i].destroy(); + } + + for (var frameName in this.frames) + { + var frame = this.frames[frameName]; + + frame.destroy(); + } + + this.source = []; + this.dataSource = []; + this.frames = {}; + + this.manager.removeKey(this.key); + + this.manager = null; + } + +}); + +module.exports = Texture; diff --git a/src/textures/TextureManager.js b/src/textures/TextureManager.js index da04abff5..0b26d4db0 100644 --- a/src/textures/TextureManager.js +++ b/src/textures/TextureManager.js @@ -1,1196 +1,1196 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../display/canvas/CanvasPool'); -var CanvasTexture = require('./CanvasTexture'); -var Class = require('../utils/Class'); -var Color = require('../display/color/Color'); -var CONST = require('../const'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var GameEvents = require('../core/events'); -var GenerateTexture = require('../create/GenerateTexture'); -var GetValue = require('../utils/object/GetValue'); -var Parser = require('./parsers'); -var Texture = require('./Texture'); - -/** - * @callback EachTextureCallback - * - * @param {Phaser.Textures.Texture} texture - Each texture in Texture Manager. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - */ - -/** - * @classdesc - * Textures are managed by the global TextureManager. This is a singleton class that is - * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. - * - * Sprites and other Game Objects get the texture data they need from the TextureManager. - * - * Access it via `scene.textures`. - * - * @class TextureManager - * @extends Phaser.Events.EventEmitter - * @memberof Phaser.Textures - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Game} game - The Phaser.Game instance this Texture Manager belongs to. - */ -var TextureManager = new Class({ - - Extends: EventEmitter, - - initialize: - - function TextureManager (game) - { - EventEmitter.call(this); - - /** - * The Game that this TextureManager belongs to. - * - * @name Phaser.Textures.TextureManager#game - * @type {Phaser.Game} - * @since 3.0.0 - */ - this.game = game; - - /** - * The name of this manager. - * - * @name Phaser.Textures.TextureManager#name - * @type {string} - * @since 3.0.0 - */ - this.name = 'TextureManager'; - - /** - * An object that has all of textures that Texture Manager creates. - * Textures are assigned to keys so we can access to any texture that this object has directly by key value without iteration. - * - * @name Phaser.Textures.TextureManager#list - * @type {object} - * @default {} - * @since 3.0.0 - */ - this.list = {}; - - /** - * The temporary canvas element to save an pixel data of an arbitrary texture in getPixel() and getPixelAlpha() method. - * - * @name Phaser.Textures.TextureManager#_tempCanvas - * @type {HTMLCanvasElement} - * @private - * @since 3.0.0 - */ - this._tempCanvas = CanvasPool.create2D(this, 1, 1); - - /** - * The context of the temporary canvas element made to save an pixel data in getPixel() and getPixelAlpha() method. - * - * @name Phaser.Textures.TextureManager#_tempContext - * @type {CanvasRenderingContext2D} - * @private - * @since 3.0.0 - */ - this._tempContext = this._tempCanvas.getContext('2d'); - - /** - * An counting value used for emitting 'ready' event after all of managers in game is loaded. - * - * @name Phaser.Textures.TextureManager#_pending - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - this._pending = 0; - - game.events.once(GameEvents.BOOT, this.boot, this); - }, - - /** - * The Boot Handler called by Phaser.Game when it first starts up. - * - * @method Phaser.Textures.TextureManager#boot - * @private - * @since 3.0.0 - */ - boot: function () - { - this._pending = 2; - - this.on(Events.LOAD, this.updatePending, this); - this.on(Events.ERROR, this.updatePending, this); - - this.addBase64('__DEFAULT', this.game.config.defaultImage); - this.addBase64('__MISSING', this.game.config.missingImage); - - this.game.events.once(GameEvents.DESTROY, this.destroy, this); - }, - - /** - * After 'onload' or 'onerror' invoked twice, emit 'ready' event. - * - * @method Phaser.Textures.TextureManager#updatePending - * @private - * @since 3.0.0 - */ - updatePending: function () - { - this._pending--; - - if (this._pending === 0) - { - this.off(Events.LOAD); - this.off(Events.ERROR); - - this.emit(Events.READY); - } - }, - - /** - * Checks the given texture key and throws a console.warn if the key is already in use, then returns false. - * If you wish to avoid the console.warn then use `TextureManager.exists` instead. - * - * @method Phaser.Textures.TextureManager#checkKey - * @since 3.7.0 - * - * @param {string} key - The texture key to check. - * - * @return {boolean} `true` if it's safe to use the texture key, otherwise `false`. - */ - checkKey: function (key) - { - if (this.exists(key)) - { - // eslint-disable-next-line no-console - console.error('Texture key already in use: ' + key); - - return false; - } - - return true; - }, - - /** - * Removes a Texture from the Texture Manager and destroys it. This will immediately - * clear all references to it from the Texture Manager, and if it has one, destroy its - * WebGLTexture. This will emit a `removetexture` event. - * - * Note: If you have any Game Objects still using this texture they will start throwing - * errors the next time they try to render. Make sure that removing the texture is the final - * step when clearing down to avoid this. - * - * @method Phaser.Textures.TextureManager#remove - * @fires Phaser.Textures.Events#REMOVE - * @since 3.7.0 - * - * @param {(string|Phaser.Textures.Texture)} key - The key of the Texture to remove, or a reference to it. - * - * @return {Phaser.Textures.TextureManager} The Texture Manager. - */ - remove: function (key) - { - if (typeof key === 'string') - { - if (this.exists(key)) - { - key = this.get(key); - } - else - { - console.warn('No texture found matching key: ' + key); - return this; - } - } - - // By this point key should be a Texture, if not, the following fails anyway - if (this.list.hasOwnProperty(key.key)) - { - key.destroy(); - - this.emit(Events.REMOVE, key.key); - } - - return this; - }, - - /** - * Removes a key from the Texture Manager but does not destroy the Texture that was using the key. - * - * @method Phaser.Textures.TextureManager#removeKey - * @since 3.17.0 - * - * @param {string} key - The key to remove from the texture list. - * - * @return {Phaser.Textures.TextureManager} The Texture Manager. - */ - removeKey: function (key) - { - if (this.list.hasOwnProperty(key)) - { - delete this.list[key]; - } - - return this; - }, - - /** - * Adds a new Texture to the Texture Manager created from the given Base64 encoded data. - * - * @method Phaser.Textures.TextureManager#addBase64 - * @fires Phaser.Textures.Events#ADD - * @fires Phaser.Textures.Events#ERROR - * @fires Phaser.Textures.Events#LOAD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {*} data - The Base64 encoded data. - * - * @return {this} This Texture Manager instance. - */ - addBase64: function (key, data) - { - if (this.checkKey(key)) - { - var _this = this; - - var image = new Image(); - - image.onerror = function () - { - _this.emit(Events.ERROR, key); - }; - - image.onload = function () - { - var texture = _this.create(key, image); - - Parser.Image(texture, 0); - - _this.emit(Events.ADD, key, texture); - - _this.emit(Events.LOAD, key, texture); - }; - - image.src = data; - } - - return this; - }, - - /** - * Gets an existing texture frame and converts it into a base64 encoded image and returns the base64 data. - * - * You can also provide the image type and encoder options. - * - * This will only work with bitmap based texture frames, such as those created from Texture Atlases. - * It will not work with GL Texture objects, such as Shaders, or Render Textures. For those please - * see the WebGL Snapshot function instead. - * - * @method Phaser.Textures.TextureManager#getBase64 - * @since 3.12.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. - * @param {string} [type='image/png'] - A DOMString indicating the image format. The default format type is image/png. - * @param {number} [encoderOptions=0.92] - A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored. - * - * @return {string} The base64 encoded data, or an empty string if the texture frame could not be found. - */ - getBase64: function (key, frame, type, encoderOptions) - { - if (type === undefined) { type = 'image/png'; } - if (encoderOptions === undefined) { encoderOptions = 0.92; } - - var data = ''; - - var textureFrame = this.getFrame(key, frame); - - if (textureFrame && (textureFrame.source.isRenderTexture || textureFrame.source.isGLTexture)) - { - console.warn('Cannot getBase64 from WebGL Texture'); - } - else if (textureFrame) - { - var cd = textureFrame.canvasData; - - var canvas = CanvasPool.create2D(this, cd.width, cd.height); - var ctx = canvas.getContext('2d'); - - ctx.drawImage( - textureFrame.source.image, - cd.x, - cd.y, - cd.width, - cd.height, - 0, - 0, - cd.width, - cd.height - ); - - data = canvas.toDataURL(type, encoderOptions); - - CanvasPool.remove(canvas); - } - - return data; - }, - - /** - * Adds a new Texture to the Texture Manager created from the given Image element. - * - * @method Phaser.Textures.TextureManager#addImage - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {HTMLImageElement|HTMLCanvasElement} [dataSource] - An optional data Image element. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addImage: function (key, source, dataSource) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, source); - - Parser.Image(texture, 0); - - if (dataSource) - { - texture.setDataSource(dataSource); - } - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Takes a WebGL Texture and creates a Phaser Texture from it, which is added to the Texture Manager using the given key. - * - * This allows you to then use the Texture as a normal texture for texture based Game Objects like Sprites. - * - * This is a WebGL only feature. - * - * @method Phaser.Textures.TextureManager#addGLTexture - * @fires Phaser.Textures.Events#ADD - * @since 3.19.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {WebGLTexture} glTexture - The source Render Texture. - * @param {number} width - The new width of the Texture. - * @param {number} height - The new height of the Texture. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addGLTexture: function (key, glTexture, width, height) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, glTexture, width, height); - - texture.add('__BASE', 0, 0, 0, width, height); - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a Render Texture to the Texture Manager using the given key. - * This allows you to then use the Render Texture as a normal texture for texture based Game Objects like Sprites. - * - * @method Phaser.Textures.TextureManager#addRenderTexture - * @fires Phaser.Textures.Events#ADD - * @since 3.12.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {Phaser.GameObjects.RenderTexture} renderTexture - The source Render Texture. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addRenderTexture: function (key, renderTexture) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, renderTexture); - - texture.add('__BASE', 0, 0, 0, renderTexture.width, renderTexture.height); - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Creates a new Texture using the given config values. - * - * Generated textures consist of a Canvas element to which the texture data is drawn. - * - * Generates a texture based on the given Create configuration object. - * - * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the - * data cells map to a single color. For example, if the texture config looked like this: - * - * ```javascript - * var star = [ - * '.....828.....', - * '....72227....', - * '....82228....', - * '...7222227...', - * '2222222222222', - * '8222222222228', - * '.72222222227.', - * '..787777787..', - * '..877777778..', - * '.78778887787.', - * '.27887.78872.', - * '.787.....787.' - * ]; - * - * this.textures.generate('star', { data: star, pixelWidth: 4 }); - * ``` - * - * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array - * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color - * number 8 in the palette. If a cell contains a period character `.` then it is transparent. - * - * The default palette is Arne16, but you can specify your own using the `palette` property. - * - * @method Phaser.Textures.TextureManager#generate - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {Phaser.Types.Create.GenerateTextureConfig} config - The configuration object needed to generate the texture. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - generate: function (key, config) - { - if (this.checkKey(key)) - { - var canvas = CanvasPool.create(this, 1, 1); - - config.canvas = canvas; - - GenerateTexture(config); - - return this.addCanvas(key, canvas); - } - else - { - return null; - } - }, - - /** - * Creates a new Texture using a blank Canvas element of the size given. - * - * Canvas elements are automatically pooled and calling this method will - * extract a free canvas from the CanvasPool, or create one if none are available. - * - * @method Phaser.Textures.TextureManager#createCanvas - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {integer} [width=256] - The width of the Canvas element. - * @param {integer} [height=256] - The height of the Canvas element. - * - * @return {?Phaser.Textures.CanvasTexture} The Canvas Texture that was created, or `null` if the key is already in use. - */ - createCanvas: function (key, width, height) - { - if (width === undefined) { width = 256; } - if (height === undefined) { height = 256; } - - if (this.checkKey(key)) - { - var canvas = CanvasPool.create(this, width, height, CONST.CANVAS, true); - - return this.addCanvas(key, canvas); - } - - return null; - }, - - /** - * Creates a new Canvas Texture object from an existing Canvas element - * and adds it to this Texture Manager, unless `skipCache` is true. - * - * @method Phaser.Textures.TextureManager#addCanvas - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLCanvasElement} source - The Canvas element to form the base of the new Texture. - * @param {boolean} [skipCache=false] - Skip adding this Texture into the Cache? - * - * @return {?Phaser.Textures.CanvasTexture} The Canvas Texture that was created, or `null` if the key is already in use. - */ - addCanvas: function (key, source, skipCache) - { - if (skipCache === undefined) { skipCache = false; } - - var texture = null; - - if (skipCache) - { - texture = new CanvasTexture(this, key, source, source.width, source.height); - } - else if (this.checkKey(key)) - { - texture = new CanvasTexture(this, key, source, source.width, source.height); - - this.list[key] = texture; - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a new Texture Atlas to this Texture Manager. - * It can accept either JSON Array or JSON Hash formats, as exported by Texture Packer and similar software. - * - * @method Phaser.Textures.TextureManager#addAtlas - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {object} data - The Texture Atlas data. - * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addAtlas: function (key, source, data, dataSource) - { - // New Texture Packer format? - if (Array.isArray(data.textures) || Array.isArray(data.frames)) - { - return this.addAtlasJSONArray(key, source, data, dataSource); - } - else - { - return this.addAtlasJSONHash(key, source, data, dataSource); - } - }, - - /** - * Adds a Texture Atlas to this Texture Manager. - * The frame data of the atlas must be stored in an Array within the JSON. - * This is known as a JSON Array in software such as Texture Packer. - * - * @method Phaser.Textures.TextureManager#addAtlasJSONArray - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {(HTMLImageElement|HTMLImageElement[])} source - The source Image element/s. - * @param {(object|object[])} data - The Texture Atlas data/s. - * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addAtlasJSONArray: function (key, source, data, dataSource) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, source); - - // Multi-Atlas? - if (Array.isArray(data)) - { - var singleAtlasFile = (data.length === 1); // multi-pack with one atlas file for all images - - // !! Assumes the textures are in the same order in the source array as in the json data !! - for (var i = 0; i < texture.source.length; i++) - { - var atlasData = singleAtlasFile ? data[0] : data[i]; - - Parser.JSONArray(texture, i, atlasData); - } - } - else - { - Parser.JSONArray(texture, 0, data); - } - - if (dataSource) - { - texture.setDataSource(dataSource); - } - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a Texture Atlas to this Texture Manager. - * The frame data of the atlas must be stored in an Object within the JSON. - * This is known as a JSON Hash in software such as Texture Packer. - * - * @method Phaser.Textures.TextureManager#addAtlasJSONHash - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {object} data - The Texture Atlas data. - * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addAtlasJSONHash: function (key, source, data, dataSource) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, source); - - if (Array.isArray(data)) - { - for (var i = 0; i < data.length; i++) - { - Parser.JSONHash(texture, i, data[i]); - } - } - else - { - Parser.JSONHash(texture, 0, data); - } - - if (dataSource) - { - texture.setDataSource(dataSource); - } - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a Texture Atlas to this Texture Manager, where the atlas data is given - * in the XML format. - * - * @method Phaser.Textures.TextureManager#addAtlasXML - * @fires Phaser.Textures.Events#ADD - * @since 3.7.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {object} data - The Texture Atlas XML data. - * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addAtlasXML: function (key, source, data, dataSource) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, source); - - Parser.AtlasXML(texture, 0, data); - - if (dataSource) - { - texture.setDataSource(dataSource); - } - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a Unity Texture Atlas to this Texture Manager. - * The data must be in the form of a Unity YAML file. - * - * @method Phaser.Textures.TextureManager#addUnityAtlas - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {object} data - The Texture Atlas data. - * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addUnityAtlas: function (key, source, data, dataSource) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, source); - - Parser.UnityYAML(texture, 0, data); - - if (dataSource) - { - texture.setDataSource(dataSource); - } - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a Sprite Sheet to this Texture Manager. - * - * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact - * same size and cannot be trimmed or rotated. - * - * @method Phaser.Textures.TextureManager#addSpriteSheet - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {Phaser.Types.Textures.SpriteSheetConfig} config - The configuration object for this Sprite Sheet. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addSpriteSheet: function (key, source, config) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = this.create(key, source); - - var width = texture.source[0].width; - var height = texture.source[0].height; - - Parser.SpriteSheet(texture, 0, 0, 0, width, height, config); - - this.emit(Events.ADD, key, texture); - } - - return texture; - }, - - /** - * Adds a Sprite Sheet to this Texture Manager, where the Sprite Sheet exists as a Frame within a Texture Atlas. - * - * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact - * same size and cannot be trimmed or rotated. - * - * @method Phaser.Textures.TextureManager#addSpriteSheetFromAtlas - * @fires Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {Phaser.Types.Textures.SpriteSheetFromAtlasConfig} config - The configuration object for this Sprite Sheet. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - addSpriteSheetFromAtlas: function (key, config) - { - if (!this.checkKey(key)) - { - return null; - } - - var atlasKey = GetValue(config, 'atlas', null); - var atlasFrame = GetValue(config, 'frame', null); - - if (!atlasKey || !atlasFrame) - { - return; - } - - var atlas = this.get(atlasKey); - var sheet = atlas.get(atlasFrame); - - if (sheet) - { - var texture = this.create(key, sheet.source.image); - - if (sheet.trimmed) - { - // If trimmed we need to help the parser adjust - Parser.SpriteSheetFromAtlas(texture, sheet, config); - } - else - { - Parser.SpriteSheet(texture, 0, sheet.cutX, sheet.cutY, sheet.cutWidth, sheet.cutHeight, config); - } - - this.emit(Events.ADD, key, texture); - - return texture; - } - }, - - /** - * Creates a new Texture using the given source and dimensions. - * - * @method Phaser.Textures.TextureManager#create - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {HTMLImageElement} source - The source Image element. - * @param {integer} width - The width of the Texture. - * @param {integer} height - The height of the Texture. - * - * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. - */ - create: function (key, source, width, height) - { - var texture = null; - - if (this.checkKey(key)) - { - texture = new Texture(this, key, source, width, height); - - this.list[key] = texture; - } - - return texture; - }, - - /** - * Checks the given key to see if a Texture using it exists within this Texture Manager. - * - * @method Phaser.Textures.TextureManager#exists - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * - * @return {boolean} Returns `true` if a Texture matching the given key exists in this Texture Manager. - */ - exists: function (key) - { - return (this.list.hasOwnProperty(key)); - }, - - /** - * Returns a Texture from the Texture Manager that matches the given key. - * - * If the key is `undefined` it will return the `__DEFAULT` Texture. - * - * If the key is an instance of a Texture, it will return the key directly. - * - * Finally. if the key is given, but not found and not a Texture instance, it will return the `__MISSING` Texture. - * - * @method Phaser.Textures.TextureManager#get - * @since 3.0.0 - * - * @param {(string|Phaser.Textures.Texture)} key - The unique string-based key of the Texture, or a Texture instance. - * - * @return {Phaser.Textures.Texture} The Texture that was created. - */ - get: function (key) - { - if (key === undefined) { key = '__DEFAULT'; } - - if (this.list[key]) - { - return this.list[key]; - } - else if (key instanceof Texture) - { - return key; - } - else - { - return this.list['__MISSING']; - } - }, - - /** - * Takes a Texture key and Frame name and returns a clone of that Frame if found. - * - * @method Phaser.Textures.TextureManager#cloneFrame - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} frame - The string or index of the Frame to be cloned. - * - * @return {Phaser.Textures.Frame} A Clone of the given Frame. - */ - cloneFrame: function (key, frame) - { - if (this.list[key]) - { - return this.list[key].get(frame).clone(); - } - }, - - /** - * Takes a Texture key and Frame name and returns a reference to that Frame, if found. - * - * @method Phaser.Textures.TextureManager#getFrame - * @since 3.0.0 - * - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. - * - * @return {Phaser.Textures.Frame} A Texture Frame object. - */ - getFrame: function (key, frame) - { - if (this.list[key]) - { - return this.list[key].get(frame); - } - }, - - /** - * Returns an array with all of the keys of all Textures in this Texture Manager. - * The output array will exclude the `__DEFAULT` and `__MISSING` keys. - * - * @method Phaser.Textures.TextureManager#getTextureKeys - * @since 3.0.0 - * - * @return {string[]} An array containing all of the Texture keys stored in this Texture Manager. - */ - getTextureKeys: function () - { - var output = []; - - for (var key in this.list) - { - if (key !== '__DEFAULT' && key !== '__MISSING') - { - output.push(key); - } - } - - return output; - }, - - /** - * Given a Texture and an `x` and `y` coordinate this method will return a new - * Color object that has been populated with the color and alpha values of the pixel - * at that location in the Texture. - * - * @method Phaser.Textures.TextureManager#getPixel - * @since 3.0.0 - * - * @param {integer} x - The x coordinate of the pixel within the Texture. - * @param {integer} y - The y coordinate of the pixel within the Texture. - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} [frame] - The string or index of the Frame. - * - * @return {?Phaser.Display.Color} A Color object populated with the color values of the requested pixel, - * or `null` if the coordinates were out of bounds. - */ - getPixel: function (x, y, key, frame) - { - var textureFrame = this.getFrame(key, frame); - - if (textureFrame) - { - // Adjust for trim (if not trimmed x and y are just zero) - x -= textureFrame.x; - y -= textureFrame.y; - - var data = textureFrame.data.cut; - - x += data.x; - y += data.y; - - if (x >= data.x && x < data.r && y >= data.y && y < data.b) - { - var ctx = this._tempContext; - - ctx.clearRect(0, 0, 1, 1); - ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); - - var rgb = ctx.getImageData(0, 0, 1, 1); - - return new Color(rgb.data[0], rgb.data[1], rgb.data[2], rgb.data[3]); - } - } - - return null; - }, - - /** - * Given a Texture and an `x` and `y` coordinate this method will return a value between 0 and 255 - * corresponding to the alpha value of the pixel at that location in the Texture. If the coordinate - * is out of bounds it will return null. - * - * @method Phaser.Textures.TextureManager#getPixelAlpha - * @since 3.10.0 - * - * @param {integer} x - The x coordinate of the pixel within the Texture. - * @param {integer} y - The y coordinate of the pixel within the Texture. - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} [frame] - The string or index of the Frame. - * - * @return {integer} A value between 0 and 255, or `null` if the coordinates were out of bounds. - */ - getPixelAlpha: function (x, y, key, frame) - { - var textureFrame = this.getFrame(key, frame); - - if (textureFrame) - { - // Adjust for trim (if not trimmed x and y are just zero) - x -= textureFrame.x; - y -= textureFrame.y; - - var data = textureFrame.data.cut; - - x += data.x; - y += data.y; - - if (x >= data.x && x < data.r && y >= data.y && y < data.b) - { - var ctx = this._tempContext; - - ctx.clearRect(0, 0, 1, 1); - ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); - - var rgb = ctx.getImageData(0, 0, 1, 1); - - return rgb.data[3]; - } - } - - return null; - }, - - /** - * Sets the given Game Objects `texture` and `frame` properties so that it uses - * the Texture and Frame specified in the `key` and `frame` arguments to this method. - * - * @method Phaser.Textures.TextureManager#setTexture - * @since 3.0.0 - * - * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the texture would be set on. - * @param {string} key - The unique string-based key of the Texture. - * @param {(string|integer)} [frame] - The string or index of the Frame. - * - * @return {Phaser.GameObjects.GameObject} The Game Object the texture was set on. - */ - setTexture: function (gameObject, key, frame) - { - if (this.list[key]) - { - gameObject.texture = this.list[key]; - gameObject.frame = gameObject.texture.get(frame); - } - - return gameObject; - }, - - /** - * Changes the key being used by a Texture to the new key provided. - * - * The old key is removed, allowing it to be re-used. - * - * Game Objects are linked to Textures by a reference to the Texture object, so - * all existing references will be retained. - * - * @method Phaser.Textures.TextureManager#renameTexture - * @since 3.12.0 - * - * @param {string} currentKey - The current string-based key of the Texture you wish to rename. - * @param {string} newKey - The new unique string-based key to use for the Texture. - * - * @return {boolean} `true` if the Texture key was successfully renamed, otherwise `false`. - */ - renameTexture: function (currentKey, newKey) - { - var texture = this.get(currentKey); - - if (texture && currentKey !== newKey) - { - texture.key = newKey; - - this.list[newKey] = texture; - - delete this.list[currentKey]; - - return true; - } - - return false; - }, - - /** - * Passes all Textures to the given callback. - * - * @method Phaser.Textures.TextureManager#each - * @since 3.0.0 - * - * @param {EachTextureCallback} callback - The callback function to be sent the Textures. - * @param {object} scope - The value to use as `this` when executing the callback. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - */ - each: function (callback, scope) - { - var args = [ null ]; - - for (var i = 1; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (var texture in this.list) - { - args[0] = this.list[texture]; - - callback.apply(scope, args); - } - }, - - /** - * Destroys the Texture Manager and all Textures stored within it. - * - * @method Phaser.Textures.TextureManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - for (var texture in this.list) - { - this.list[texture].destroy(); - } - - this.list = {}; - - this.game = null; - - CanvasPool.remove(this._tempCanvas); - } - -}); - -module.exports = TextureManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../display/canvas/CanvasPool'); +var CanvasTexture = require('./CanvasTexture'); +var Class = require('../utils/Class'); +var Color = require('../display/color/Color'); +var CONST = require('../const'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var GameEvents = require('../core/events'); +var GenerateTexture = require('../create/GenerateTexture'); +var GetValue = require('../utils/object/GetValue'); +var Parser = require('./parsers'); +var Texture = require('./Texture'); + +/** + * @callback EachTextureCallback + * + * @param {Phaser.Textures.Texture} texture - Each texture in Texture Manager. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + +/** + * @classdesc + * Textures are managed by the global TextureManager. This is a singleton class that is + * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. + * + * Sprites and other Game Objects get the texture data they need from the TextureManager. + * + * Access it via `scene.textures`. + * + * @class TextureManager + * @extends Phaser.Events.EventEmitter + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Game} game - The Phaser.Game instance this Texture Manager belongs to. + */ +var TextureManager = new Class({ + + Extends: EventEmitter, + + initialize: + + function TextureManager (game) + { + EventEmitter.call(this); + + /** + * The Game that this TextureManager belongs to. + * + * @name Phaser.Textures.TextureManager#game + * @type {Phaser.Game} + * @since 3.0.0 + */ + this.game = game; + + /** + * The name of this manager. + * + * @name Phaser.Textures.TextureManager#name + * @type {string} + * @since 3.0.0 + */ + this.name = 'TextureManager'; + + /** + * An object that has all of textures that Texture Manager creates. + * Textures are assigned to keys so we can access to any texture that this object has directly by key value without iteration. + * + * @name Phaser.Textures.TextureManager#list + * @type {object} + * @default {} + * @since 3.0.0 + */ + this.list = {}; + + /** + * The temporary canvas element to save an pixel data of an arbitrary texture in getPixel() and getPixelAlpha() method. + * + * @name Phaser.Textures.TextureManager#_tempCanvas + * @type {HTMLCanvasElement} + * @private + * @since 3.0.0 + */ + this._tempCanvas = CanvasPool.create2D(this, 1, 1); + + /** + * The context of the temporary canvas element made to save an pixel data in getPixel() and getPixelAlpha() method. + * + * @name Phaser.Textures.TextureManager#_tempContext + * @type {CanvasRenderingContext2D} + * @private + * @since 3.0.0 + */ + this._tempContext = this._tempCanvas.getContext('2d'); + + /** + * An counting value used for emitting 'ready' event after all of managers in game is loaded. + * + * @name Phaser.Textures.TextureManager#_pending + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._pending = 0; + + game.events.once(GameEvents.BOOT, this.boot, this); + }, + + /** + * The Boot Handler called by Phaser.Game when it first starts up. + * + * @method Phaser.Textures.TextureManager#boot + * @private + * @since 3.0.0 + */ + boot: function () + { + this._pending = 2; + + this.on(Events.LOAD, this.updatePending, this); + this.on(Events.ERROR, this.updatePending, this); + + this.addBase64('__DEFAULT', this.game.config.defaultImage); + this.addBase64('__MISSING', this.game.config.missingImage); + + this.game.events.once(GameEvents.DESTROY, this.destroy, this); + }, + + /** + * After 'onload' or 'onerror' invoked twice, emit 'ready' event. + * + * @method Phaser.Textures.TextureManager#updatePending + * @private + * @since 3.0.0 + */ + updatePending: function () + { + this._pending--; + + if (this._pending === 0) + { + this.off(Events.LOAD); + this.off(Events.ERROR); + + this.emit(Events.READY); + } + }, + + /** + * Checks the given texture key and throws a console.warn if the key is already in use, then returns false. + * If you wish to avoid the console.warn then use `TextureManager.exists` instead. + * + * @method Phaser.Textures.TextureManager#checkKey + * @since 3.7.0 + * + * @param {string} key - The texture key to check. + * + * @return {boolean} `true` if it's safe to use the texture key, otherwise `false`. + */ + checkKey: function (key) + { + if (this.exists(key)) + { + // eslint-disable-next-line no-console + console.error('Texture key already in use: ' + key); + + return false; + } + + return true; + }, + + /** + * Removes a Texture from the Texture Manager and destroys it. This will immediately + * clear all references to it from the Texture Manager, and if it has one, destroy its + * WebGLTexture. This will emit a `removetexture` event. + * + * Note: If you have any Game Objects still using this texture they will start throwing + * errors the next time they try to render. Make sure that removing the texture is the final + * step when clearing down to avoid this. + * + * @method Phaser.Textures.TextureManager#remove + * @fires Phaser.Textures.Events#REMOVE + * @since 3.7.0 + * + * @param {(string|Phaser.Textures.Texture)} key - The key of the Texture to remove, or a reference to it. + * + * @return {Phaser.Textures.TextureManager} The Texture Manager. + */ + remove: function (key) + { + if (typeof key === 'string') + { + if (this.exists(key)) + { + key = this.get(key); + } + else + { + console.warn('No texture found matching key: ' + key); + return this; + } + } + + // By this point key should be a Texture, if not, the following fails anyway + if (this.list.hasOwnProperty(key.key)) + { + key.destroy(); + + this.emit(Events.REMOVE, key.key); + } + + return this; + }, + + /** + * Removes a key from the Texture Manager but does not destroy the Texture that was using the key. + * + * @method Phaser.Textures.TextureManager#removeKey + * @since 3.17.0 + * + * @param {string} key - The key to remove from the texture list. + * + * @return {Phaser.Textures.TextureManager} The Texture Manager. + */ + removeKey: function (key) + { + if (this.list.hasOwnProperty(key)) + { + delete this.list[key]; + } + + return this; + }, + + /** + * Adds a new Texture to the Texture Manager created from the given Base64 encoded data. + * + * @method Phaser.Textures.TextureManager#addBase64 + * @fires Phaser.Textures.Events#ADD + * @fires Phaser.Textures.Events#ERROR + * @fires Phaser.Textures.Events#LOAD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {*} data - The Base64 encoded data. + * + * @return {this} This Texture Manager instance. + */ + addBase64: function (key, data) + { + if (this.checkKey(key)) + { + var _this = this; + + var image = new Image(); + + image.onerror = function () + { + _this.emit(Events.ERROR, key); + }; + + image.onload = function () + { + var texture = _this.create(key, image); + + Parser.Image(texture, 0); + + _this.emit(Events.ADD, key, texture); + + _this.emit(Events.LOAD, key, texture); + }; + + image.src = data; + } + + return this; + }, + + /** + * Gets an existing texture frame and converts it into a base64 encoded image and returns the base64 data. + * + * You can also provide the image type and encoder options. + * + * This will only work with bitmap based texture frames, such as those created from Texture Atlases. + * It will not work with GL Texture objects, such as Shaders, or Render Textures. For those please + * see the WebGL Snapshot function instead. + * + * @method Phaser.Textures.TextureManager#getBase64 + * @since 3.12.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. + * @param {string} [type='image/png'] - A DOMString indicating the image format. The default format type is image/png. + * @param {number} [encoderOptions=0.92] - A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored. + * + * @return {string} The base64 encoded data, or an empty string if the texture frame could not be found. + */ + getBase64: function (key, frame, type, encoderOptions) + { + if (type === undefined) { type = 'image/png'; } + if (encoderOptions === undefined) { encoderOptions = 0.92; } + + var data = ''; + + var textureFrame = this.getFrame(key, frame); + + if (textureFrame && (textureFrame.source.isRenderTexture || textureFrame.source.isGLTexture)) + { + console.warn('Cannot getBase64 from WebGL Texture'); + } + else if (textureFrame) + { + var cd = textureFrame.canvasData; + + var canvas = CanvasPool.create2D(this, cd.width, cd.height); + var ctx = canvas.getContext('2d'); + + ctx.drawImage( + textureFrame.source.image, + cd.x, + cd.y, + cd.width, + cd.height, + 0, + 0, + cd.width, + cd.height + ); + + data = canvas.toDataURL(type, encoderOptions); + + CanvasPool.remove(canvas); + } + + return data; + }, + + /** + * Adds a new Texture to the Texture Manager created from the given Image element. + * + * @method Phaser.Textures.TextureManager#addImage + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {HTMLImageElement|HTMLCanvasElement} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addImage: function (key, source, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + Parser.Image(texture, 0); + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Takes a WebGL Texture and creates a Phaser Texture from it, which is added to the Texture Manager using the given key. + * + * This allows you to then use the Texture as a normal texture for texture based Game Objects like Sprites. + * + * This is a WebGL only feature. + * + * @method Phaser.Textures.TextureManager#addGLTexture + * @fires Phaser.Textures.Events#ADD + * @since 3.19.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {WebGLTexture} glTexture - The source Render Texture. + * @param {number} width - The new width of the Texture. + * @param {number} height - The new height of the Texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addGLTexture: function (key, glTexture, width, height) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, glTexture, width, height); + + texture.add('__BASE', 0, 0, 0, width, height); + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Render Texture to the Texture Manager using the given key. + * This allows you to then use the Render Texture as a normal texture for texture based Game Objects like Sprites. + * + * @method Phaser.Textures.TextureManager#addRenderTexture + * @fires Phaser.Textures.Events#ADD + * @since 3.12.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {Phaser.GameObjects.RenderTexture} renderTexture - The source Render Texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addRenderTexture: function (key, renderTexture) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, renderTexture); + + texture.add('__BASE', 0, 0, 0, renderTexture.width, renderTexture.height); + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Creates a new Texture using the given config values. + * + * Generated textures consist of a Canvas element to which the texture data is drawn. + * + * Generates a texture based on the given Create configuration object. + * + * The texture is drawn using a fixed-size indexed palette of 16 colors, where the hex value in the + * data cells map to a single color. For example, if the texture config looked like this: + * + * ```javascript + * var star = [ + * '.....828.....', + * '....72227....', + * '....82228....', + * '...7222227...', + * '2222222222222', + * '8222222222228', + * '.72222222227.', + * '..787777787..', + * '..877777778..', + * '.78778887787.', + * '.27887.78872.', + * '.787.....787.' + * ]; + * + * this.textures.generate('star', { data: star, pixelWidth: 4 }); + * ``` + * + * Then it would generate a texture that is 52 x 48 pixels in size, because each cell of the data array + * represents 1 pixel multiplied by the `pixelWidth` value. The cell values, such as `8`, maps to color + * number 8 in the palette. If a cell contains a period character `.` then it is transparent. + * + * The default palette is Arne16, but you can specify your own using the `palette` property. + * + * @method Phaser.Textures.TextureManager#generate + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {Phaser.Types.Create.GenerateTextureConfig} config - The configuration object needed to generate the texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + generate: function (key, config) + { + if (this.checkKey(key)) + { + var canvas = CanvasPool.create(this, 1, 1); + + config.canvas = canvas; + + GenerateTexture(config); + + return this.addCanvas(key, canvas); + } + else + { + return null; + } + }, + + /** + * Creates a new Texture using a blank Canvas element of the size given. + * + * Canvas elements are automatically pooled and calling this method will + * extract a free canvas from the CanvasPool, or create one if none are available. + * + * @method Phaser.Textures.TextureManager#createCanvas + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {integer} [width=256] - The width of the Canvas element. + * @param {integer} [height=256] - The height of the Canvas element. + * + * @return {?Phaser.Textures.CanvasTexture} The Canvas Texture that was created, or `null` if the key is already in use. + */ + createCanvas: function (key, width, height) + { + if (width === undefined) { width = 256; } + if (height === undefined) { height = 256; } + + if (this.checkKey(key)) + { + var canvas = CanvasPool.create(this, width, height, CONST.CANVAS, true); + + return this.addCanvas(key, canvas); + } + + return null; + }, + + /** + * Creates a new Canvas Texture object from an existing Canvas element + * and adds it to this Texture Manager, unless `skipCache` is true. + * + * @method Phaser.Textures.TextureManager#addCanvas + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLCanvasElement} source - The Canvas element to form the base of the new Texture. + * @param {boolean} [skipCache=false] - Skip adding this Texture into the Cache? + * + * @return {?Phaser.Textures.CanvasTexture} The Canvas Texture that was created, or `null` if the key is already in use. + */ + addCanvas: function (key, source, skipCache) + { + if (skipCache === undefined) { skipCache = false; } + + var texture = null; + + if (skipCache) + { + texture = new CanvasTexture(this, key, source, source.width, source.height); + } + else if (this.checkKey(key)) + { + texture = new CanvasTexture(this, key, source, source.width, source.height); + + this.list[key] = texture; + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a new Texture Atlas to this Texture Manager. + * It can accept either JSON Array or JSON Hash formats, as exported by Texture Packer and similar software. + * + * @method Phaser.Textures.TextureManager#addAtlas + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlas: function (key, source, data, dataSource) + { + // New Texture Packer format? + if (Array.isArray(data.textures) || Array.isArray(data.frames)) + { + return this.addAtlasJSONArray(key, source, data, dataSource); + } + else + { + return this.addAtlasJSONHash(key, source, data, dataSource); + } + }, + + /** + * Adds a Texture Atlas to this Texture Manager. + * The frame data of the atlas must be stored in an Array within the JSON. + * This is known as a JSON Array in software such as Texture Packer. + * + * @method Phaser.Textures.TextureManager#addAtlasJSONArray + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(HTMLImageElement|HTMLImageElement[])} source - The source Image element/s. + * @param {(object|object[])} data - The Texture Atlas data/s. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlasJSONArray: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + // Multi-Atlas? + if (Array.isArray(data)) + { + var singleAtlasFile = (data.length === 1); // multi-pack with one atlas file for all images + + // !! Assumes the textures are in the same order in the source array as in the json data !! + for (var i = 0; i < texture.source.length; i++) + { + var atlasData = singleAtlasFile ? data[0] : data[i]; + + Parser.JSONArray(texture, i, atlasData); + } + } + else + { + Parser.JSONArray(texture, 0, data); + } + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Texture Atlas to this Texture Manager. + * The frame data of the atlas must be stored in an Object within the JSON. + * This is known as a JSON Hash in software such as Texture Packer. + * + * @method Phaser.Textures.TextureManager#addAtlasJSONHash + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlasJSONHash: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + if (Array.isArray(data)) + { + for (var i = 0; i < data.length; i++) + { + Parser.JSONHash(texture, i, data[i]); + } + } + else + { + Parser.JSONHash(texture, 0, data); + } + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Texture Atlas to this Texture Manager, where the atlas data is given + * in the XML format. + * + * @method Phaser.Textures.TextureManager#addAtlasXML + * @fires Phaser.Textures.Events#ADD + * @since 3.7.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas XML data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addAtlasXML: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + Parser.AtlasXML(texture, 0, data); + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Unity Texture Atlas to this Texture Manager. + * The data must be in the form of a Unity YAML file. + * + * @method Phaser.Textures.TextureManager#addUnityAtlas + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {object} data - The Texture Atlas data. + * @param {HTMLImageElement|HTMLCanvasElement|HTMLImageElement[]|HTMLCanvasElement[]} [dataSource] - An optional data Image element. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addUnityAtlas: function (key, source, data, dataSource) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + Parser.UnityYAML(texture, 0, data); + + if (dataSource) + { + texture.setDataSource(dataSource); + } + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Sprite Sheet to this Texture Manager. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @method Phaser.Textures.TextureManager#addSpriteSheet + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {Phaser.Types.Textures.SpriteSheetConfig} config - The configuration object for this Sprite Sheet. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addSpriteSheet: function (key, source, config) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = this.create(key, source); + + var width = texture.source[0].width; + var height = texture.source[0].height; + + Parser.SpriteSheet(texture, 0, 0, 0, width, height, config); + + this.emit(Events.ADD, key, texture); + } + + return texture; + }, + + /** + * Adds a Sprite Sheet to this Texture Manager, where the Sprite Sheet exists as a Frame within a Texture Atlas. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @method Phaser.Textures.TextureManager#addSpriteSheetFromAtlas + * @fires Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {Phaser.Types.Textures.SpriteSheetFromAtlasConfig} config - The configuration object for this Sprite Sheet. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + addSpriteSheetFromAtlas: function (key, config) + { + if (!this.checkKey(key)) + { + return null; + } + + var atlasKey = GetValue(config, 'atlas', null); + var atlasFrame = GetValue(config, 'frame', null); + + if (!atlasKey || !atlasFrame) + { + return; + } + + var atlas = this.get(atlasKey); + var sheet = atlas.get(atlasFrame); + + if (sheet) + { + var texture = this.create(key, sheet.source.image); + + if (sheet.trimmed) + { + // If trimmed we need to help the parser adjust + Parser.SpriteSheetFromAtlas(texture, sheet, config); + } + else + { + Parser.SpriteSheet(texture, 0, sheet.cutX, sheet.cutY, sheet.cutWidth, sheet.cutHeight, config); + } + + this.emit(Events.ADD, key, texture); + + return texture; + } + }, + + /** + * Creates a new Texture using the given source and dimensions. + * + * @method Phaser.Textures.TextureManager#create + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {HTMLImageElement} source - The source Image element. + * @param {integer} width - The width of the Texture. + * @param {integer} height - The height of the Texture. + * + * @return {?Phaser.Textures.Texture} The Texture that was created, or `null` if the key is already in use. + */ + create: function (key, source, width, height) + { + var texture = null; + + if (this.checkKey(key)) + { + texture = new Texture(this, key, source, width, height); + + this.list[key] = texture; + } + + return texture; + }, + + /** + * Checks the given key to see if a Texture using it exists within this Texture Manager. + * + * @method Phaser.Textures.TextureManager#exists + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * + * @return {boolean} Returns `true` if a Texture matching the given key exists in this Texture Manager. + */ + exists: function (key) + { + return (this.list.hasOwnProperty(key)); + }, + + /** + * Returns a Texture from the Texture Manager that matches the given key. + * + * If the key is `undefined` it will return the `__DEFAULT` Texture. + * + * If the key is an instance of a Texture, it will return the key directly. + * + * Finally. if the key is given, but not found and not a Texture instance, it will return the `__MISSING` Texture. + * + * @method Phaser.Textures.TextureManager#get + * @since 3.0.0 + * + * @param {(string|Phaser.Textures.Texture)} key - The unique string-based key of the Texture, or a Texture instance. + * + * @return {Phaser.Textures.Texture} The Texture that was created. + */ + get: function (key) + { + if (key === undefined) { key = '__DEFAULT'; } + + if (this.list[key]) + { + return this.list[key]; + } + else if (key instanceof Texture) + { + return key; + } + else + { + return this.list['__MISSING']; + } + }, + + /** + * Takes a Texture key and Frame name and returns a clone of that Frame if found. + * + * @method Phaser.Textures.TextureManager#cloneFrame + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} frame - The string or index of the Frame to be cloned. + * + * @return {Phaser.Textures.Frame} A Clone of the given Frame. + */ + cloneFrame: function (key, frame) + { + if (this.list[key]) + { + return this.list[key].get(frame).clone(); + } + }, + + /** + * Takes a Texture key and Frame name and returns a reference to that Frame, if found. + * + * @method Phaser.Textures.TextureManager#getFrame + * @since 3.0.0 + * + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string-based name, or integer based index, of the Frame to get from the Texture. + * + * @return {Phaser.Textures.Frame} A Texture Frame object. + */ + getFrame: function (key, frame) + { + if (this.list[key]) + { + return this.list[key].get(frame); + } + }, + + /** + * Returns an array with all of the keys of all Textures in this Texture Manager. + * The output array will exclude the `__DEFAULT` and `__MISSING` keys. + * + * @method Phaser.Textures.TextureManager#getTextureKeys + * @since 3.0.0 + * + * @return {string[]} An array containing all of the Texture keys stored in this Texture Manager. + */ + getTextureKeys: function () + { + var output = []; + + for (var key in this.list) + { + if (key !== '__DEFAULT' && key !== '__MISSING') + { + output.push(key); + } + } + + return output; + }, + + /** + * Given a Texture and an `x` and `y` coordinate this method will return a new + * Color object that has been populated with the color and alpha values of the pixel + * at that location in the Texture. + * + * @method Phaser.Textures.TextureManager#getPixel + * @since 3.0.0 + * + * @param {integer} x - The x coordinate of the pixel within the Texture. + * @param {integer} y - The y coordinate of the pixel within the Texture. + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string or index of the Frame. + * + * @return {?Phaser.Display.Color} A Color object populated with the color values of the requested pixel, + * or `null` if the coordinates were out of bounds. + */ + getPixel: function (x, y, key, frame) + { + var textureFrame = this.getFrame(key, frame); + + if (textureFrame) + { + // Adjust for trim (if not trimmed x and y are just zero) + x -= textureFrame.x; + y -= textureFrame.y; + + var data = textureFrame.data.cut; + + x += data.x; + y += data.y; + + if (x >= data.x && x < data.r && y >= data.y && y < data.b) + { + var ctx = this._tempContext; + + ctx.clearRect(0, 0, 1, 1); + ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = ctx.getImageData(0, 0, 1, 1); + + return new Color(rgb.data[0], rgb.data[1], rgb.data[2], rgb.data[3]); + } + } + + return null; + }, + + /** + * Given a Texture and an `x` and `y` coordinate this method will return a value between 0 and 255 + * corresponding to the alpha value of the pixel at that location in the Texture. If the coordinate + * is out of bounds it will return null. + * + * @method Phaser.Textures.TextureManager#getPixelAlpha + * @since 3.10.0 + * + * @param {integer} x - The x coordinate of the pixel within the Texture. + * @param {integer} y - The y coordinate of the pixel within the Texture. + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string or index of the Frame. + * + * @return {integer} A value between 0 and 255, or `null` if the coordinates were out of bounds. + */ + getPixelAlpha: function (x, y, key, frame) + { + var textureFrame = this.getFrame(key, frame); + + if (textureFrame) + { + // Adjust for trim (if not trimmed x and y are just zero) + x -= textureFrame.x; + y -= textureFrame.y; + + var data = textureFrame.data.cut; + + x += data.x; + y += data.y; + + if (x >= data.x && x < data.r && y >= data.y && y < data.b) + { + var ctx = this._tempContext; + + ctx.clearRect(0, 0, 1, 1); + ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = ctx.getImageData(0, 0, 1, 1); + + return rgb.data[3]; + } + } + + return null; + }, + + /** + * Sets the given Game Objects `texture` and `frame` properties so that it uses + * the Texture and Frame specified in the `key` and `frame` arguments to this method. + * + * @method Phaser.Textures.TextureManager#setTexture + * @since 3.0.0 + * + * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object the texture would be set on. + * @param {string} key - The unique string-based key of the Texture. + * @param {(string|integer)} [frame] - The string or index of the Frame. + * + * @return {Phaser.GameObjects.GameObject} The Game Object the texture was set on. + */ + setTexture: function (gameObject, key, frame) + { + if (this.list[key]) + { + gameObject.texture = this.list[key]; + gameObject.frame = gameObject.texture.get(frame); + } + + return gameObject; + }, + + /** + * Changes the key being used by a Texture to the new key provided. + * + * The old key is removed, allowing it to be re-used. + * + * Game Objects are linked to Textures by a reference to the Texture object, so + * all existing references will be retained. + * + * @method Phaser.Textures.TextureManager#renameTexture + * @since 3.12.0 + * + * @param {string} currentKey - The current string-based key of the Texture you wish to rename. + * @param {string} newKey - The new unique string-based key to use for the Texture. + * + * @return {boolean} `true` if the Texture key was successfully renamed, otherwise `false`. + */ + renameTexture: function (currentKey, newKey) + { + var texture = this.get(currentKey); + + if (texture && currentKey !== newKey) + { + texture.key = newKey; + + this.list[newKey] = texture; + + delete this.list[currentKey]; + + return true; + } + + return false; + }, + + /** + * Passes all Textures to the given callback. + * + * @method Phaser.Textures.TextureManager#each + * @since 3.0.0 + * + * @param {EachTextureCallback} callback - The callback function to be sent the Textures. + * @param {object} scope - The value to use as `this` when executing the callback. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + */ + each: function (callback, scope) + { + var args = [ null ]; + + for (var i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var texture in this.list) + { + args[0] = this.list[texture]; + + callback.apply(scope, args); + } + }, + + /** + * Destroys the Texture Manager and all Textures stored within it. + * + * @method Phaser.Textures.TextureManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + for (var texture in this.list) + { + this.list[texture].destroy(); + } + + this.list = {}; + + this.game = null; + + CanvasPool.remove(this._tempCanvas); + } + +}); + +module.exports = TextureManager; diff --git a/src/textures/TextureSource.js b/src/textures/TextureSource.js index bba227cae..966b0815e 100644 --- a/src/textures/TextureSource.js +++ b/src/textures/TextureSource.js @@ -1,335 +1,335 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CanvasPool = require('../display/canvas/CanvasPool'); -var Class = require('../utils/Class'); -var IsSizePowerOfTwo = require('../math/pow2/IsSizePowerOfTwo'); -var ScaleModes = require('../renderer/ScaleModes'); - -/** - * @classdesc - * A Texture Source is the encapsulation of the actual source data for a Texture. - * - * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element. - * - * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded. - * - * @class TextureSource - * @memberof Phaser.Textures - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture this TextureSource belongs to. - * @param {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture)} source - The source image data. - * @param {integer} [width] - Optional width of the source image. If not given it's derived from the source itself. - * @param {integer} [height] - Optional height of the source image. If not given it's derived from the source itself. - * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. - */ -var TextureSource = new Class({ - - initialize: - - function TextureSource (texture, source, width, height, flipY) - { - if (flipY === undefined) { flipY = false; } - - var game = texture.manager.game; - - /** - * The Texture this TextureSource belongs to. - * - * @name Phaser.Textures.TextureSource#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @since 3.7.0 - */ - this.renderer = game.renderer; - - /** - * The Texture this TextureSource belongs to. - * - * @name Phaser.Textures.TextureSource#texture - * @type {Phaser.Textures.Texture} - * @since 3.0.0 - */ - this.texture = texture; - - /** - * The source of the image data. - * - * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture. - * - * @name Phaser.Textures.TextureSource#source - * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture)} - * @since 3.12.0 - */ - this.source = source; - - /** - * The image data. - * - * This is either an Image element, Canvas element or a Video Element. - * - * @name Phaser.Textures.TextureSource#image - * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement)} - * @since 3.0.0 - */ - this.image = source; - - /** - * Currently un-used. - * - * @name Phaser.Textures.TextureSource#compressionAlgorithm - * @type {integer} - * @default null - * @since 3.0.0 - */ - this.compressionAlgorithm = null; - - /** - * The resolution of the source image. - * - * @name Phaser.Textures.TextureSource#resolution - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.resolution = 1; - - /** - * The width of the source image. If not specified in the constructor it will check - * the `naturalWidth` and then `width` properties of the source image. - * - * @name Phaser.Textures.TextureSource#width - * @type {integer} - * @since 3.0.0 - */ - this.width = width || source.naturalWidth || source.videoWidth || source.width || 0; - - /** - * The height of the source image. If not specified in the constructor it will check - * the `naturalHeight` and then `height` properties of the source image. - * - * @name Phaser.Textures.TextureSource#height - * @type {integer} - * @since 3.0.0 - */ - this.height = height || source.naturalHeight || source.videoHeight || source.height || 0; - - /** - * The Scale Mode the image will use when rendering. - * Either Linear or Nearest. - * - * @name Phaser.Textures.TextureSource#scaleMode - * @type {number} - * @since 3.0.0 - */ - this.scaleMode = ScaleModes.DEFAULT; - - /** - * Is the source image a Canvas Element? - * - * @name Phaser.Textures.TextureSource#isCanvas - * @type {boolean} - * @since 3.0.0 - */ - this.isCanvas = (source instanceof HTMLCanvasElement); - - /** - * Is the source image a Video Element? - * - * @name Phaser.Textures.TextureSource#isVideo - * @type {boolean} - * @since 3.20.0 - */ - this.isVideo = (window.hasOwnProperty('HTMLVideoElement') && source instanceof HTMLVideoElement); - - /** - * Is the source image a Render Texture? - * - * @name Phaser.Textures.TextureSource#isRenderTexture - * @type {boolean} - * @since 3.12.0 - */ - this.isRenderTexture = (source.type === 'RenderTexture'); - - /** - * Is the source image a WebGLTexture? - * - * @name Phaser.Textures.TextureSource#isGLTexture - * @type {boolean} - * @since 3.19.0 - */ - this.isGLTexture = (window.hasOwnProperty('WebGLTexture') && source instanceof WebGLTexture); - - /** - * Are the source image dimensions a power of two? - * - * @name Phaser.Textures.TextureSource#isPowerOf2 - * @type {boolean} - * @since 3.0.0 - */ - this.isPowerOf2 = IsSizePowerOfTwo(this.width, this.height); - - /** - * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture - * already, then this is a reference to that WebGLTexture. - * - * @name Phaser.Textures.TextureSource#glTexture - * @type {?WebGLTexture} - * @default null - * @since 3.0.0 - */ - this.glTexture = null; - - /** - * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. - * - * @name Phaser.Textures.TextureSource#flipY - * @type {boolean} - * @since 3.20.0 - */ - this.flipY = flipY; - - this.init(game); - }, - - /** - * Creates a WebGL Texture, if required, and sets the Texture filter mode. - * - * @method Phaser.Textures.TextureSource#init - * @since 3.0.0 - * - * @param {Phaser.Game} game - A reference to the Phaser Game instance. - */ - init: function (game) - { - if (this.renderer) - { - if (this.renderer.gl) - { - if (this.isCanvas) - { - this.glTexture = this.renderer.createCanvasTexture(this.image, false, this.flipY); - } - else if (this.isVideo) - { - this.glTexture = this.renderer.createVideoTexture(this.image, false, this.flipY); - } - else if (this.isRenderTexture) - { - this.image = this.source.canvas; - - this.glTexture = this.renderer.createTextureFromSource(null, this.width, this.height, this.scaleMode); - } - else if (this.isGLTexture) - { - this.glTexture = this.source; - } - else - { - this.glTexture = this.renderer.createTextureFromSource(this.image, this.width, this.height, this.scaleMode); - } - } - else if (this.isRenderTexture) - { - this.image = this.source.canvas; - } - } - - if (!game.config.antialias) - { - this.setFilter(1); - } - }, - - /** - * Sets the Filter Mode for this Texture. - * - * The mode can be either Linear, the default, or Nearest. - * - * For pixel-art you should use Nearest. - * - * @method Phaser.Textures.TextureSource#setFilter - * @since 3.0.0 - * - * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode. - */ - setFilter: function (filterMode) - { - if (this.renderer.gl) - { - this.renderer.setTextureFilter(this.glTexture, filterMode); - } - - this.scaleMode = filterMode; - }, - - /** - * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload. - * - * @method Phaser.Textures.TextureSource#setFlipY - * @since 3.20.0 - * - * @param {boolean} [value=true] - Should the WebGL Texture be flipped on the Y axis on texture upload or not? - */ - setFlipY: function (value) - { - if (value === undefined) { value = true; } - - this.flipY = value; - - return this; - }, - - /** - * If this TextureSource is backed by a Canvas and is running under WebGL, - * it updates the WebGLTexture using the canvas data. - * - * @method Phaser.Textures.TextureSource#update - * @since 3.7.0 - */ - update: function () - { - var gl = this.renderer.gl; - - if (gl && this.isCanvas) - { - this.glTexture = this.renderer.updateCanvasTexture(this.image, this.glTexture, this.flipY); - } - else if (gl && this.isVideo) - { - this.glTexture = this.renderer.updateVideoTexture(this.image, this.glTexture, this.flipY); - } - }, - - /** - * Destroys this Texture Source and nulls the references. - * - * @method Phaser.Textures.TextureSource#destroy - * @since 3.0.0 - */ - destroy: function () - { - if (this.glTexture) - { - this.renderer.deleteTexture(this.glTexture); - } - - if (this.isCanvas) - { - CanvasPool.remove(this.image); - } - - this.renderer = null; - this.texture = null; - this.source = null; - this.image = null; - this.glTexture = null; - } - -}); - -module.exports = TextureSource; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CanvasPool = require('../display/canvas/CanvasPool'); +var Class = require('../utils/Class'); +var IsSizePowerOfTwo = require('../math/pow2/IsSizePowerOfTwo'); +var ScaleModes = require('../renderer/ScaleModes'); + +/** + * @classdesc + * A Texture Source is the encapsulation of the actual source data for a Texture. + * + * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element. + * + * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded. + * + * @class TextureSource + * @memberof Phaser.Textures + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture this TextureSource belongs to. + * @param {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture)} source - The source image data. + * @param {integer} [width] - Optional width of the source image. If not given it's derived from the source itself. + * @param {integer} [height] - Optional height of the source image. If not given it's derived from the source itself. + * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + */ +var TextureSource = new Class({ + + initialize: + + function TextureSource (texture, source, width, height, flipY) + { + if (flipY === undefined) { flipY = false; } + + var game = texture.manager.game; + + /** + * The Texture this TextureSource belongs to. + * + * @name Phaser.Textures.TextureSource#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @since 3.7.0 + */ + this.renderer = game.renderer; + + /** + * The Texture this TextureSource belongs to. + * + * @name Phaser.Textures.TextureSource#texture + * @type {Phaser.Textures.Texture} + * @since 3.0.0 + */ + this.texture = texture; + + /** + * The source of the image data. + * + * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture. + * + * @name Phaser.Textures.TextureSource#source + * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture)} + * @since 3.12.0 + */ + this.source = source; + + /** + * The image data. + * + * This is either an Image element, Canvas element or a Video Element. + * + * @name Phaser.Textures.TextureSource#image + * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement)} + * @since 3.0.0 + */ + this.image = source; + + /** + * Currently un-used. + * + * @name Phaser.Textures.TextureSource#compressionAlgorithm + * @type {integer} + * @default null + * @since 3.0.0 + */ + this.compressionAlgorithm = null; + + /** + * The resolution of the source image. + * + * @name Phaser.Textures.TextureSource#resolution + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.resolution = 1; + + /** + * The width of the source image. If not specified in the constructor it will check + * the `naturalWidth` and then `width` properties of the source image. + * + * @name Phaser.Textures.TextureSource#width + * @type {integer} + * @since 3.0.0 + */ + this.width = width || source.naturalWidth || source.videoWidth || source.width || 0; + + /** + * The height of the source image. If not specified in the constructor it will check + * the `naturalHeight` and then `height` properties of the source image. + * + * @name Phaser.Textures.TextureSource#height + * @type {integer} + * @since 3.0.0 + */ + this.height = height || source.naturalHeight || source.videoHeight || source.height || 0; + + /** + * The Scale Mode the image will use when rendering. + * Either Linear or Nearest. + * + * @name Phaser.Textures.TextureSource#scaleMode + * @type {number} + * @since 3.0.0 + */ + this.scaleMode = ScaleModes.DEFAULT; + + /** + * Is the source image a Canvas Element? + * + * @name Phaser.Textures.TextureSource#isCanvas + * @type {boolean} + * @since 3.0.0 + */ + this.isCanvas = (source instanceof HTMLCanvasElement); + + /** + * Is the source image a Video Element? + * + * @name Phaser.Textures.TextureSource#isVideo + * @type {boolean} + * @since 3.20.0 + */ + this.isVideo = (window.hasOwnProperty('HTMLVideoElement') && source instanceof HTMLVideoElement); + + /** + * Is the source image a Render Texture? + * + * @name Phaser.Textures.TextureSource#isRenderTexture + * @type {boolean} + * @since 3.12.0 + */ + this.isRenderTexture = (source.type === 'RenderTexture'); + + /** + * Is the source image a WebGLTexture? + * + * @name Phaser.Textures.TextureSource#isGLTexture + * @type {boolean} + * @since 3.19.0 + */ + this.isGLTexture = (window.hasOwnProperty('WebGLTexture') && source instanceof WebGLTexture); + + /** + * Are the source image dimensions a power of two? + * + * @name Phaser.Textures.TextureSource#isPowerOf2 + * @type {boolean} + * @since 3.0.0 + */ + this.isPowerOf2 = IsSizePowerOfTwo(this.width, this.height); + + /** + * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture + * already, then this is a reference to that WebGLTexture. + * + * @name Phaser.Textures.TextureSource#glTexture + * @type {?WebGLTexture} + * @default null + * @since 3.0.0 + */ + this.glTexture = null; + + /** + * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + * + * @name Phaser.Textures.TextureSource#flipY + * @type {boolean} + * @since 3.20.0 + */ + this.flipY = flipY; + + this.init(game); + }, + + /** + * Creates a WebGL Texture, if required, and sets the Texture filter mode. + * + * @method Phaser.Textures.TextureSource#init + * @since 3.0.0 + * + * @param {Phaser.Game} game - A reference to the Phaser Game instance. + */ + init: function (game) + { + if (this.renderer) + { + if (this.renderer.gl) + { + if (this.isCanvas) + { + this.glTexture = this.renderer.createCanvasTexture(this.image, false, this.flipY); + } + else if (this.isVideo) + { + this.glTexture = this.renderer.createVideoTexture(this.image, false, this.flipY); + } + else if (this.isRenderTexture) + { + this.image = this.source.canvas; + + this.glTexture = this.renderer.createTextureFromSource(null, this.width, this.height, this.scaleMode); + } + else if (this.isGLTexture) + { + this.glTexture = this.source; + } + else + { + this.glTexture = this.renderer.createTextureFromSource(this.image, this.width, this.height, this.scaleMode); + } + } + else if (this.isRenderTexture) + { + this.image = this.source.canvas; + } + } + + if (!game.config.antialias) + { + this.setFilter(1); + } + }, + + /** + * Sets the Filter Mode for this Texture. + * + * The mode can be either Linear, the default, or Nearest. + * + * For pixel-art you should use Nearest. + * + * @method Phaser.Textures.TextureSource#setFilter + * @since 3.0.0 + * + * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode. + */ + setFilter: function (filterMode) + { + if (this.renderer.gl) + { + this.renderer.setTextureFilter(this.glTexture, filterMode); + } + + this.scaleMode = filterMode; + }, + + /** + * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload. + * + * @method Phaser.Textures.TextureSource#setFlipY + * @since 3.20.0 + * + * @param {boolean} [value=true] - Should the WebGL Texture be flipped on the Y axis on texture upload or not? + */ + setFlipY: function (value) + { + if (value === undefined) { value = true; } + + this.flipY = value; + + return this; + }, + + /** + * If this TextureSource is backed by a Canvas and is running under WebGL, + * it updates the WebGLTexture using the canvas data. + * + * @method Phaser.Textures.TextureSource#update + * @since 3.7.0 + */ + update: function () + { + var gl = this.renderer.gl; + + if (gl && this.isCanvas) + { + this.glTexture = this.renderer.updateCanvasTexture(this.image, this.glTexture, this.flipY); + } + else if (gl && this.isVideo) + { + this.glTexture = this.renderer.updateVideoTexture(this.image, this.glTexture, this.flipY); + } + }, + + /** + * Destroys this Texture Source and nulls the references. + * + * @method Phaser.Textures.TextureSource#destroy + * @since 3.0.0 + */ + destroy: function () + { + if (this.glTexture) + { + this.renderer.deleteTexture(this.glTexture); + } + + if (this.isCanvas) + { + CanvasPool.remove(this.image); + } + + this.renderer = null; + this.texture = null; + this.source = null; + this.image = null; + this.glTexture = null; + } + +}); + +module.exports = TextureSource; diff --git a/src/textures/const.js b/src/textures/const.js index 1b7e56873..3e1f26869 100644 --- a/src/textures/const.js +++ b/src/textures/const.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Filter Types. - * - * @namespace Phaser.Textures.FilterMode - * @memberof Phaser.Textures - * @since 3.0.0 - */ -var CONST = { - - /** - * Linear filter type. - * - * @name Phaser.Textures.FilterMode.LINEAR - * @type {integer} - * @const - * @since 3.0.0 - */ - LINEAR: 0, - - /** - * Nearest neighbor filter type. - * - * @name Phaser.Textures.FilterMode.NEAREST - * @type {integer} - * @const - * @since 3.0.0 - */ - NEAREST: 1 - -}; - -module.exports = CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Filter Types. + * + * @namespace Phaser.Textures.FilterMode + * @memberof Phaser.Textures + * @since 3.0.0 + */ +var CONST = { + + /** + * Linear filter type. + * + * @name Phaser.Textures.FilterMode.LINEAR + * @type {integer} + * @const + * @since 3.0.0 + */ + LINEAR: 0, + + /** + * Nearest neighbor filter type. + * + * @name Phaser.Textures.FilterMode.NEAREST + * @type {integer} + * @const + * @since 3.0.0 + */ + NEAREST: 1 + +}; + +module.exports = CONST; diff --git a/src/textures/events/ADD_EVENT.js b/src/textures/events/ADD_EVENT.js index af6ffeb2f..c4faeeb20 100644 --- a/src/textures/events/ADD_EVENT.js +++ b/src/textures/events/ADD_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Texture Add Event. - * - * This event is dispatched by the Texture Manager when a texture is added to it. - * - * Listen to this event from within a Scene using: `this.textures.on('addtexture', listener)`. - * - * @event Phaser.Textures.Events#ADD - * @since 3.0.0 - * - * @param {string} key - The key of the Texture that was added to the Texture Manager. - * @param {Phaser.Textures.Texture} texture - A reference to the Texture that was added to the Texture Manager. - */ -module.exports = 'addtexture'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Add Event. + * + * This event is dispatched by the Texture Manager when a texture is added to it. + * + * Listen to this event from within a Scene using: `this.textures.on('addtexture', listener)`. + * + * @event Phaser.Textures.Events#ADD + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that was added to the Texture Manager. + * @param {Phaser.Textures.Texture} texture - A reference to the Texture that was added to the Texture Manager. + */ +module.exports = 'addtexture'; diff --git a/src/textures/events/ERROR_EVENT.js b/src/textures/events/ERROR_EVENT.js index 2c3cb4c33..04dc16ed3 100644 --- a/src/textures/events/ERROR_EVENT.js +++ b/src/textures/events/ERROR_EVENT.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Texture Load Error Event. - * - * This event is dispatched by the Texture Manager when a texture it requested to load failed. - * This only happens when base64 encoded textures fail. All other texture types are loaded via the Loader Plugin. - * - * Listen to this event from within a Scene using: `this.textures.on('onerror', listener)`. - * - * @event Phaser.Textures.Events#ERROR - * @since 3.0.0 - * - * @param {string} key - The key of the Texture that failed to load into the Texture Manager. - */ -module.exports = 'onerror'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Load Error Event. + * + * This event is dispatched by the Texture Manager when a texture it requested to load failed. + * This only happens when base64 encoded textures fail. All other texture types are loaded via the Loader Plugin. + * + * Listen to this event from within a Scene using: `this.textures.on('onerror', listener)`. + * + * @event Phaser.Textures.Events#ERROR + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that failed to load into the Texture Manager. + */ +module.exports = 'onerror'; diff --git a/src/textures/events/LOAD_EVENT.js b/src/textures/events/LOAD_EVENT.js index be11c553d..538fa509f 100644 --- a/src/textures/events/LOAD_EVENT.js +++ b/src/textures/events/LOAD_EVENT.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Texture Load Event. - * - * This event is dispatched by the Texture Manager when a texture has finished loading on it. - * This only happens for base64 encoded textures. All other texture types are loaded via the Loader Plugin. - * - * Listen to this event from within a Scene using: `this.textures.on('onload', listener)`. - * - * This event is dispatched after the [ADD]{@linkcode Phaser.Textures.Events#event:ADD} event. - * - * @event Phaser.Textures.Events#LOAD - * @since 3.0.0 - * - * @param {string} key - The key of the Texture that was loaded by the Texture Manager. - * @param {Phaser.Textures.Texture} texture - A reference to the Texture that was loaded by the Texture Manager. - */ -module.exports = 'onload'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Load Event. + * + * This event is dispatched by the Texture Manager when a texture has finished loading on it. + * This only happens for base64 encoded textures. All other texture types are loaded via the Loader Plugin. + * + * Listen to this event from within a Scene using: `this.textures.on('onload', listener)`. + * + * This event is dispatched after the [ADD]{@linkcode Phaser.Textures.Events#event:ADD} event. + * + * @event Phaser.Textures.Events#LOAD + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that was loaded by the Texture Manager. + * @param {Phaser.Textures.Texture} texture - A reference to the Texture that was loaded by the Texture Manager. + */ +module.exports = 'onload'; diff --git a/src/textures/events/READY_EVENT.js b/src/textures/events/READY_EVENT.js index cb99ee565..afae8bf1d 100644 --- a/src/textures/events/READY_EVENT.js +++ b/src/textures/events/READY_EVENT.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This internal event signifies that the Texture Manager is now ready and the Game can continue booting. - * - * When a Phaser Game instance is booting for the first time, the Texture Manager has to wait on a couple of non-blocking - * async events before it's fully ready to carry on. When those complete the Texture Manager emits this event via the Game - * instance, which tells the Game to carry on booting. - * - * @event Phaser.Textures.Events#READY - * @since 3.16.1 - */ -module.exports = 'ready'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This internal event signifies that the Texture Manager is now ready and the Game can continue booting. + * + * When a Phaser Game instance is booting for the first time, the Texture Manager has to wait on a couple of non-blocking + * async events before it's fully ready to carry on. When those complete the Texture Manager emits this event via the Game + * instance, which tells the Game to carry on booting. + * + * @event Phaser.Textures.Events#READY + * @since 3.16.1 + */ +module.exports = 'ready'; diff --git a/src/textures/events/REMOVE_EVENT.js b/src/textures/events/REMOVE_EVENT.js index 736ee1b3b..aa6cd2c0d 100644 --- a/src/textures/events/REMOVE_EVENT.js +++ b/src/textures/events/REMOVE_EVENT.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Texture Remove Event. - * - * This event is dispatched by the Texture Manager when a texture is removed from it. - * - * Listen to this event from within a Scene using: `this.textures.on('removetexture', listener)`. - * - * If you have any Game Objects still using the removed texture, they will start throwing - * errors the next time they try to render. Be sure to clear all use of the texture in this event handler. - * - * @event Phaser.Textures.Events#REMOVE - * @since 3.0.0 - * - * @param {string} key - The key of the Texture that was removed from the Texture Manager. - */ -module.exports = 'removetexture'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Texture Remove Event. + * + * This event is dispatched by the Texture Manager when a texture is removed from it. + * + * Listen to this event from within a Scene using: `this.textures.on('removetexture', listener)`. + * + * If you have any Game Objects still using the removed texture, they will start throwing + * errors the next time they try to render. Be sure to clear all use of the texture in this event handler. + * + * @event Phaser.Textures.Events#REMOVE + * @since 3.0.0 + * + * @param {string} key - The key of the Texture that was removed from the Texture Manager. + */ +module.exports = 'removetexture'; diff --git a/src/textures/events/index.js b/src/textures/events/index.js index d7040a71a..9ee1462a7 100644 --- a/src/textures/events/index.js +++ b/src/textures/events/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Textures.Events - */ - -module.exports = { - - ADD: require('./ADD_EVENT'), - ERROR: require('./ERROR_EVENT'), - LOAD: require('./LOAD_EVENT'), - READY: require('./READY_EVENT'), - REMOVE: require('./REMOVE_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Textures.Events + */ + +module.exports = { + + ADD: require('./ADD_EVENT'), + ERROR: require('./ERROR_EVENT'), + LOAD: require('./LOAD_EVENT'), + READY: require('./READY_EVENT'), + REMOVE: require('./REMOVE_EVENT') + +}; diff --git a/src/textures/index.js b/src/textures/index.js index 0c3e1c92a..0d2a5188f 100644 --- a/src/textures/index.js +++ b/src/textures/index.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Extend = require('../utils/object/Extend'); -var FilterMode = require('./const'); - -/** - * @namespace Phaser.Textures - */ - -/** - * Linear filter type. - * - * @name Phaser.Textures.LINEAR - * @type {integer} - * @const - * @since 3.0.0 - */ - -/** - * Nearest Neighbor filter type. - * - * @name Phaser.Textures.NEAREST - * @type {integer} - * @const - * @since 3.0.0 - */ - -var Textures = { - - CanvasTexture: require('./CanvasTexture'), - Events: require('./events'), - FilterMode: FilterMode, - Frame: require('./Frame'), - Parsers: require('./parsers'), - Texture: require('./Texture'), - TextureManager: require('./TextureManager'), - TextureSource: require('./TextureSource') - -}; - -Textures = Extend(false, Textures, FilterMode); - -module.exports = Textures; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = require('../utils/object/Extend'); +var FilterMode = require('./const'); + +/** + * @namespace Phaser.Textures + */ + +/** + * Linear filter type. + * + * @name Phaser.Textures.LINEAR + * @type {integer} + * @const + * @since 3.0.0 + */ + +/** + * Nearest Neighbor filter type. + * + * @name Phaser.Textures.NEAREST + * @type {integer} + * @const + * @since 3.0.0 + */ + +var Textures = { + + CanvasTexture: require('./CanvasTexture'), + Events: require('./events'), + FilterMode: FilterMode, + Frame: require('./Frame'), + Parsers: require('./parsers'), + Texture: require('./Texture'), + TextureManager: require('./TextureManager'), + TextureSource: require('./TextureSource') + +}; + +Textures = Extend(false, Textures, FilterMode); + +module.exports = Textures; diff --git a/src/textures/parsers/AtlasXML.js b/src/textures/parsers/AtlasXML.js index 18a1b3aae..ef0f72def 100644 --- a/src/textures/parsers/AtlasXML.js +++ b/src/textures/parsers/AtlasXML.js @@ -1,75 +1,75 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Parses an XML Texture Atlas object and adds all the Frames into a Texture. - * - * @function Phaser.Textures.Parsers.AtlasXML - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.7.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {integer} sourceIndex - The index of the TextureSource. - * @param {*} xml - The XML data. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var AtlasXML = function (texture, sourceIndex, xml) -{ - // Malformed? - if (!xml.getElementsByTagName('TextureAtlas')) - { - console.warn('Invalid Texture Atlas XML given'); - return; - } - - // Add in a __BASE entry (for the entire atlas) - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - // By this stage frames is a fully parsed array - var frames = xml.getElementsByTagName('SubTexture'); - - var newFrame; - - for (var i = 0; i < frames.length; i++) - { - var frame = frames[i].attributes; - - var name = frame.name.value; - var x = parseInt(frame.x.value, 10); - var y = parseInt(frame.y.value, 10); - var width = parseInt(frame.width.value, 10); - var height = parseInt(frame.height.value, 10); - - // The frame values are the exact coordinates to cut the frame out of the atlas from - newFrame = texture.add(name, sourceIndex, x, y, width, height); - - // These are the original (non-trimmed) sprite values - if (frame.frameX) - { - var frameX = Math.abs(parseInt(frame.frameX.value, 10)); - var frameY = Math.abs(parseInt(frame.frameY.value, 10)); - var frameWidth = parseInt(frame.frameWidth.value, 10); - var frameHeight = parseInt(frame.frameHeight.value, 10); - - newFrame.setTrim( - width, - height, - frameX, - frameY, - frameWidth, - frameHeight - ); - } - } - - return texture; -}; - -module.exports = AtlasXML; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Parses an XML Texture Atlas object and adds all the Frames into a Texture. + * + * @function Phaser.Textures.Parsers.AtlasXML + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.7.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {*} xml - The XML data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var AtlasXML = function (texture, sourceIndex, xml) +{ + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn('Invalid Texture Atlas XML given'); + return; + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + // By this stage frames is a fully parsed array + var frames = xml.getElementsByTagName('SubTexture'); + + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + var frame = frames[i].attributes; + + var name = frame.name.value; + var x = parseInt(frame.x.value, 10); + var y = parseInt(frame.y.value, 10); + var width = parseInt(frame.width.value, 10); + var height = parseInt(frame.height.value, 10); + + // The frame values are the exact coordinates to cut the frame out of the atlas from + newFrame = texture.add(name, sourceIndex, x, y, width, height); + + // These are the original (non-trimmed) sprite values + if (frame.frameX) + { + var frameX = Math.abs(parseInt(frame.frameX.value, 10)); + var frameY = Math.abs(parseInt(frame.frameY.value, 10)); + var frameWidth = parseInt(frame.frameWidth.value, 10); + var frameHeight = parseInt(frame.frameHeight.value, 10); + + newFrame.setTrim( + width, + height, + frameX, + frameY, + frameWidth, + frameHeight + ); + } + } + + return texture; +}; + +module.exports = AtlasXML; diff --git a/src/textures/parsers/Canvas.js b/src/textures/parsers/Canvas.js index 479e20a4d..7640c6d86 100644 --- a/src/textures/parsers/Canvas.js +++ b/src/textures/parsers/Canvas.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Adds a Canvas Element to a Texture. - * - * @function Phaser.Textures.Parsers.Canvas - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {integer} sourceIndex - The index of the TextureSource. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var Canvas = function (texture, sourceIndex) -{ - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - return texture; -}; - -module.exports = Canvas; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds a Canvas Element to a Texture. + * + * @function Phaser.Textures.Parsers.Canvas + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var Canvas = function (texture, sourceIndex) +{ + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + return texture; +}; + +module.exports = Canvas; diff --git a/src/textures/parsers/Image.js b/src/textures/parsers/Image.js index 16d497dbd..5f5286977 100644 --- a/src/textures/parsers/Image.js +++ b/src/textures/parsers/Image.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Adds an Image Element to a Texture. - * - * @function Phaser.Textures.Parsers.Image - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {integer} sourceIndex - The index of the TextureSource. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var Image = function (texture, sourceIndex) -{ - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - return texture; -}; - -module.exports = Image; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds an Image Element to a Texture. + * + * @function Phaser.Textures.Parsers.Image + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var Image = function (texture, sourceIndex) +{ + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + return texture; +}; + +module.exports = Image; diff --git a/src/textures/parsers/JSONArray.js b/src/textures/parsers/JSONArray.js index aac072b42..f6ec241a3 100644 --- a/src/textures/parsers/JSONArray.js +++ b/src/textures/parsers/JSONArray.js @@ -1,101 +1,101 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = require('../../utils/object/Clone'); - -/** - * Parses a Texture Atlas JSON Array and adds the Frames to the Texture. - * JSON format expected to match that defined by Texture Packer, with the frames property containing an array of Frames. - * - * @function Phaser.Textures.Parsers.JSONArray - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {integer} sourceIndex - The index of the TextureSource. - * @param {object} json - The JSON data. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var JSONArray = function (texture, sourceIndex, json) -{ - // Malformed? - if (!json['frames'] && !json['textures']) - { - console.warn('Invalid Texture Atlas JSON Array'); - return; - } - - // Add in a __BASE entry (for the entire atlas) - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - // By this stage frames is a fully parsed array - var frames = (Array.isArray(json.textures)) ? json.textures[sourceIndex].frames : json.frames; - - var newFrame; - - for (var i = 0; i < frames.length; i++) - { - var src = frames[i]; - - // The frame values are the exact coordinates to cut the frame out of the atlas from - newFrame = texture.add(src.filename, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); - - // These are the original (non-trimmed) sprite values - if (src.trimmed) - { - newFrame.setTrim( - src.sourceSize.w, - src.sourceSize.h, - src.spriteSourceSize.x, - src.spriteSourceSize.y, - src.spriteSourceSize.w, - src.spriteSourceSize.h - ); - } - - if (src.rotated) - { - newFrame.rotated = true; - newFrame.updateUVsInverted(); - } - - if (src.anchor) - { - newFrame.customPivot = true; - newFrame.pivotX = src.anchor.x; - newFrame.pivotY = src.anchor.y; - } - - // Copy over any extra data - newFrame.customData = Clone(src); - } - - // Copy over any additional data that was in the JSON to Texture.customData - for (var dataKey in json) - { - if (dataKey === 'frames') - { - continue; - } - - if (Array.isArray(json[dataKey])) - { - texture.customData[dataKey] = json[dataKey].slice(0); - } - else - { - texture.customData[dataKey] = json[dataKey]; - } - } - - return texture; -}; - -module.exports = JSONArray; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = require('../../utils/object/Clone'); + +/** + * Parses a Texture Atlas JSON Array and adds the Frames to the Texture. + * JSON format expected to match that defined by Texture Packer, with the frames property containing an array of Frames. + * + * @function Phaser.Textures.Parsers.JSONArray + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {object} json - The JSON data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var JSONArray = function (texture, sourceIndex, json) +{ + // Malformed? + if (!json['frames'] && !json['textures']) + { + console.warn('Invalid Texture Atlas JSON Array'); + return; + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + // By this stage frames is a fully parsed array + var frames = (Array.isArray(json.textures)) ? json.textures[sourceIndex].frames : json.frames; + + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + var src = frames[i]; + + // The frame values are the exact coordinates to cut the frame out of the atlas from + newFrame = texture.add(src.filename, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); + + // These are the original (non-trimmed) sprite values + if (src.trimmed) + { + newFrame.setTrim( + src.sourceSize.w, + src.sourceSize.h, + src.spriteSourceSize.x, + src.spriteSourceSize.y, + src.spriteSourceSize.w, + src.spriteSourceSize.h + ); + } + + if (src.rotated) + { + newFrame.rotated = true; + newFrame.updateUVsInverted(); + } + + if (src.anchor) + { + newFrame.customPivot = true; + newFrame.pivotX = src.anchor.x; + newFrame.pivotY = src.anchor.y; + } + + // Copy over any extra data + newFrame.customData = Clone(src); + } + + // Copy over any additional data that was in the JSON to Texture.customData + for (var dataKey in json) + { + if (dataKey === 'frames') + { + continue; + } + + if (Array.isArray(json[dataKey])) + { + texture.customData[dataKey] = json[dataKey].slice(0); + } + else + { + texture.customData[dataKey] = json[dataKey]; + } + } + + return texture; +}; + +module.exports = JSONArray; diff --git a/src/textures/parsers/JSONHash.js b/src/textures/parsers/JSONHash.js index 844e11558..3c9494651 100644 --- a/src/textures/parsers/JSONHash.js +++ b/src/textures/parsers/JSONHash.js @@ -1,93 +1,93 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = require('../../utils/object/Clone'); - -/** - * Parses a Texture Atlas JSON Hash and adds the Frames to the Texture. - * JSON format expected to match that defined by Texture Packer, with the frames property containing an object of Frames. - * - * @function Phaser.Textures.Parsers.JSONHash - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {integer} sourceIndex - The index of the TextureSource. - * @param {object} json - The JSON data. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var JSONHash = function (texture, sourceIndex, json) -{ - // Malformed? - if (!json['frames']) - { - console.warn('Invalid Texture Atlas JSON Hash given, missing \'frames\' Object'); - return; - } - - // Add in a __BASE entry (for the entire atlas) - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - // By this stage frames is a fully parsed Object - var frames = json['frames']; - var newFrame; - - for (var key in frames) - { - var src = frames[key]; - - // The frame values are the exact coordinates to cut the frame out of the atlas from - newFrame = texture.add(key, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); - - // These are the original (non-trimmed) sprite values - if (src.trimmed) - { - newFrame.setTrim( - src.sourceSize.w, - src.sourceSize.h, - src.spriteSourceSize.x, - src.spriteSourceSize.y, - src.spriteSourceSize.w, - src.spriteSourceSize.h - ); - } - - if (src.rotated) - { - newFrame.rotated = true; - newFrame.updateUVsInverted(); - } - - // Copy over any extra data - newFrame.customData = Clone(src); - } - - // Copy over any additional data that was in the JSON to Texture.customData - for (var dataKey in json) - { - if (dataKey === 'frames') - { - continue; - } - - if (Array.isArray(json[dataKey])) - { - texture.customData[dataKey] = json[dataKey].slice(0); - } - else - { - texture.customData[dataKey] = json[dataKey]; - } - } - - return texture; -}; - -module.exports = JSONHash; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = require('../../utils/object/Clone'); + +/** + * Parses a Texture Atlas JSON Hash and adds the Frames to the Texture. + * JSON format expected to match that defined by Texture Packer, with the frames property containing an object of Frames. + * + * @function Phaser.Textures.Parsers.JSONHash + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {object} json - The JSON data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var JSONHash = function (texture, sourceIndex, json) +{ + // Malformed? + if (!json['frames']) + { + console.warn('Invalid Texture Atlas JSON Hash given, missing \'frames\' Object'); + return; + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + // By this stage frames is a fully parsed Object + var frames = json['frames']; + var newFrame; + + for (var key in frames) + { + var src = frames[key]; + + // The frame values are the exact coordinates to cut the frame out of the atlas from + newFrame = texture.add(key, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); + + // These are the original (non-trimmed) sprite values + if (src.trimmed) + { + newFrame.setTrim( + src.sourceSize.w, + src.sourceSize.h, + src.spriteSourceSize.x, + src.spriteSourceSize.y, + src.spriteSourceSize.w, + src.spriteSourceSize.h + ); + } + + if (src.rotated) + { + newFrame.rotated = true; + newFrame.updateUVsInverted(); + } + + // Copy over any extra data + newFrame.customData = Clone(src); + } + + // Copy over any additional data that was in the JSON to Texture.customData + for (var dataKey in json) + { + if (dataKey === 'frames') + { + continue; + } + + if (Array.isArray(json[dataKey])) + { + texture.customData[dataKey] = json[dataKey].slice(0); + } + else + { + texture.customData[dataKey] = json[dataKey]; + } + } + + return texture; +}; + +module.exports = JSONHash; diff --git a/src/textures/parsers/SpriteSheet.js b/src/textures/parsers/SpriteSheet.js index d0d7e8b57..282b0e194 100644 --- a/src/textures/parsers/SpriteSheet.js +++ b/src/textures/parsers/SpriteSheet.js @@ -1,119 +1,119 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * Parses a Sprite Sheet and adds the Frames to the Texture. - * - * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact - * same size and cannot be trimmed or rotated. - * - * @function Phaser.Textures.Parsers.SpriteSheet - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {integer} sourceIndex - The index of the TextureSource. - * @param {integer} x - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. - * @param {integer} y - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. - * @param {integer} width - The width of the source image. - * @param {integer} height - The height of the source image. - * @param {object} config - An object describing how to parse the Sprite Sheet. - * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. - * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. - * @param {number} [config.startFrame=0] - The frame to start extracting from. Defaults to zero. - * @param {number} [config.endFrame=-1] - The frame to finish extracting at. Defaults to -1, which means 'all frames'. - * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. - * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var SpriteSheet = function (texture, sourceIndex, x, y, width, height, config) -{ - var frameWidth = GetFastValue(config, 'frameWidth', null); - var frameHeight = GetFastValue(config, 'frameHeight', frameWidth); - - // If missing we can't proceed - if (frameWidth === null) - { - throw new Error('TextureManager.SpriteSheet: Invalid frameWidth given.'); - } - - // Add in a __BASE entry (for the entire atlas) - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - var startFrame = GetFastValue(config, 'startFrame', 0); - var endFrame = GetFastValue(config, 'endFrame', -1); - var margin = GetFastValue(config, 'margin', 0); - var spacing = GetFastValue(config, 'spacing', 0); - - var row = Math.floor((width - margin + spacing) / (frameWidth + spacing)); - var column = Math.floor((height - margin + spacing) / (frameHeight + spacing)); - var total = row * column; - - if (total === 0) - { - console.warn('SpriteSheet frame dimensions will result in zero frames.'); - } - - if (startFrame > total || startFrame < -total) - { - startFrame = 0; - } - - if (startFrame < 0) - { - // Allow negative skipframes. - startFrame = total + startFrame; - } - - if (endFrame !== -1) - { - total = startFrame + (endFrame + 1); - } - - var fx = margin; - var fy = margin; - var ax = 0; - var ay = 0; - - for (var i = 0; i < total; i++) - { - ax = 0; - ay = 0; - - var w = fx + frameWidth; - var h = fy + frameHeight; - - if (w > width) - { - ax = w - width; - } - - if (h > height) - { - ay = h - height; - } - - texture.add(i, sourceIndex, x + fx, y + fy, frameWidth - ax, frameHeight - ay); - - fx += frameWidth + spacing; - - if (fx + frameWidth > width) - { - fx = margin; - fy += frameHeight + spacing; - } - } - - return texture; -}; - -module.exports = SpriteSheet; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * Parses a Sprite Sheet and adds the Frames to the Texture. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @function Phaser.Textures.Parsers.SpriteSheet + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {integer} sourceIndex - The index of the TextureSource. + * @param {integer} x - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. + * @param {integer} y - The top-left coordinate of the Sprite Sheet. Defaults to zero. Used when extracting sheets from atlases. + * @param {integer} width - The width of the source image. + * @param {integer} height - The height of the source image. + * @param {object} config - An object describing how to parse the Sprite Sheet. + * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. + * @param {number} [config.startFrame=0] - The frame to start extracting from. Defaults to zero. + * @param {number} [config.endFrame=-1] - The frame to finish extracting at. Defaults to -1, which means 'all frames'. + * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var SpriteSheet = function (texture, sourceIndex, x, y, width, height, config) +{ + var frameWidth = GetFastValue(config, 'frameWidth', null); + var frameHeight = GetFastValue(config, 'frameHeight', frameWidth); + + // If missing we can't proceed + if (frameWidth === null) + { + throw new Error('TextureManager.SpriteSheet: Invalid frameWidth given.'); + } + + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + var startFrame = GetFastValue(config, 'startFrame', 0); + var endFrame = GetFastValue(config, 'endFrame', -1); + var margin = GetFastValue(config, 'margin', 0); + var spacing = GetFastValue(config, 'spacing', 0); + + var row = Math.floor((width - margin + spacing) / (frameWidth + spacing)); + var column = Math.floor((height - margin + spacing) / (frameHeight + spacing)); + var total = row * column; + + if (total === 0) + { + console.warn('SpriteSheet frame dimensions will result in zero frames.'); + } + + if (startFrame > total || startFrame < -total) + { + startFrame = 0; + } + + if (startFrame < 0) + { + // Allow negative skipframes. + startFrame = total + startFrame; + } + + if (endFrame !== -1) + { + total = startFrame + (endFrame + 1); + } + + var fx = margin; + var fy = margin; + var ax = 0; + var ay = 0; + + for (var i = 0; i < total; i++) + { + ax = 0; + ay = 0; + + var w = fx + frameWidth; + var h = fy + frameHeight; + + if (w > width) + { + ax = w - width; + } + + if (h > height) + { + ay = h - height; + } + + texture.add(i, sourceIndex, x + fx, y + fy, frameWidth - ax, frameHeight - ay); + + fx += frameWidth + spacing; + + if (fx + frameWidth > width) + { + fx = margin; + fy += frameHeight + spacing; + } + } + + return texture; +}; + +module.exports = SpriteSheet; diff --git a/src/textures/parsers/SpriteSheetFromAtlas.js b/src/textures/parsers/SpriteSheetFromAtlas.js index 04d98d460..0a328133b 100644 --- a/src/textures/parsers/SpriteSheetFromAtlas.js +++ b/src/textures/parsers/SpriteSheetFromAtlas.js @@ -1,185 +1,185 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * Parses a Sprite Sheet and adds the Frames to the Texture, where the Sprite Sheet is stored as a frame within an Atlas. - * - * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact - * same size and cannot be trimmed or rotated. - * - * @function Phaser.Textures.Parsers.SpriteSheetFromAtlas - * @memberof Phaser.Textures.Parsers - * @private - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. - * @param {Phaser.Textures.Frame} frame - The Frame that contains the Sprite Sheet. - * @param {object} config - An object describing how to parse the Sprite Sheet. - * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. - * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. - * @param {number} [config.startFrame=0] - Index of the start frame in the sprite sheet - * @param {number} [config.endFrame=-1] - Index of the end frame in the sprite sheet. -1 mean all the rest of the frames - * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. - * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var SpriteSheetFromAtlas = function (texture, frame, config) -{ - var frameWidth = GetFastValue(config, 'frameWidth', null); - var frameHeight = GetFastValue(config, 'frameHeight', frameWidth); - - // If missing we can't proceed - if (!frameWidth) - { - throw new Error('TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.'); - } - - // Add in a __BASE entry (for the entire atlas frame) - var source = texture.source[0]; - texture.add('__BASE', 0, 0, 0, source.width, source.height); - - var startFrame = GetFastValue(config, 'startFrame', 0); - var endFrame = GetFastValue(config, 'endFrame', -1); - var margin = GetFastValue(config, 'margin', 0); - var spacing = GetFastValue(config, 'spacing', 0); - - var x = frame.cutX; - var y = frame.cutY; - - var cutWidth = frame.cutWidth; - var cutHeight = frame.cutHeight; - var sheetWidth = frame.realWidth; - var sheetHeight = frame.realHeight; - - var row = Math.floor((sheetWidth - margin + spacing) / (frameWidth + spacing)); - var column = Math.floor((sheetHeight - margin + spacing) / (frameHeight + spacing)); - var total = row * column; - - // trim offsets - - var leftPad = frame.x; - var leftWidth = frameWidth - leftPad; - - var rightWidth = frameWidth - ((sheetWidth - cutWidth) - leftPad); - - var topPad = frame.y; - var topHeight = frameHeight - topPad; - - var bottomHeight = frameHeight - ((sheetHeight - cutHeight) - topPad); - - if (startFrame > total || startFrame < -total) - { - startFrame = 0; - } - - if (startFrame < 0) - { - // Allow negative skipframes. - startFrame = total + startFrame; - } - - if (endFrame !== -1) - { - total = startFrame + (endFrame + 1); - } - - var sheetFrame; - var frameX = margin; - var frameY = margin; - var frameIndex = 0; - var sourceIndex = frame.sourceIndex; - - for (var sheetY = 0; sheetY < column; sheetY++) - { - var topRow = (sheetY === 0); - var bottomRow = (sheetY === column - 1); - - for (var sheetX = 0; sheetX < row; sheetX++) - { - var leftRow = (sheetX === 0); - var rightRow = (sheetX === row - 1); - - sheetFrame = texture.add(frameIndex, sourceIndex, x + frameX, y + frameY, frameWidth, frameHeight); - - if (leftRow || topRow || rightRow || bottomRow) - { - var destX = (leftRow) ? leftPad : 0; - var destY = (topRow) ? topPad : 0; - - var trimWidth = 0; - var trimHeight = 0; - - if (leftRow) - { - trimWidth += (frameWidth - leftWidth); - } - - if (rightRow) - { - trimWidth += (frameWidth - rightWidth); - } - - if (topRow) - { - trimHeight += (frameHeight - topHeight); - } - - if (bottomRow) - { - trimHeight += (frameHeight - bottomHeight); - } - - var destWidth = frameWidth - trimWidth; - var destHeight = frameHeight - trimHeight; - - sheetFrame.cutWidth = destWidth; - sheetFrame.cutHeight = destHeight; - - sheetFrame.setTrim(frameWidth, frameHeight, destX, destY, destWidth, destHeight); - } - - frameX += spacing; - - if (leftRow) - { - frameX += leftWidth; - } - else if (rightRow) - { - frameX += rightWidth; - } - else - { - frameX += frameWidth; - } - - frameIndex++; - } - - frameX = margin; - frameY += spacing; - - if (topRow) - { - frameY += topHeight; - } - else if (bottomRow) - { - frameY += bottomHeight; - } - else - { - frameY += frameHeight; - } - } - - return texture; -}; - -module.exports = SpriteSheetFromAtlas; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * Parses a Sprite Sheet and adds the Frames to the Texture, where the Sprite Sheet is stored as a frame within an Atlas. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * + * @function Phaser.Textures.Parsers.SpriteSheetFromAtlas + * @memberof Phaser.Textures.Parsers + * @private + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to. + * @param {Phaser.Textures.Frame} frame - The Frame that contains the Sprite Sheet. + * @param {object} config - An object describing how to parse the Sprite Sheet. + * @param {number} config.frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} [config.frameHeight] - Height in pixels of a single frame in the sprite sheet. Defaults to frameWidth if not provided. + * @param {number} [config.startFrame=0] - Index of the start frame in the sprite sheet + * @param {number} [config.endFrame=-1] - Index of the end frame in the sprite sheet. -1 mean all the rest of the frames + * @param {number} [config.margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [config.spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var SpriteSheetFromAtlas = function (texture, frame, config) +{ + var frameWidth = GetFastValue(config, 'frameWidth', null); + var frameHeight = GetFastValue(config, 'frameHeight', frameWidth); + + // If missing we can't proceed + if (!frameWidth) + { + throw new Error('TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.'); + } + + // Add in a __BASE entry (for the entire atlas frame) + var source = texture.source[0]; + texture.add('__BASE', 0, 0, 0, source.width, source.height); + + var startFrame = GetFastValue(config, 'startFrame', 0); + var endFrame = GetFastValue(config, 'endFrame', -1); + var margin = GetFastValue(config, 'margin', 0); + var spacing = GetFastValue(config, 'spacing', 0); + + var x = frame.cutX; + var y = frame.cutY; + + var cutWidth = frame.cutWidth; + var cutHeight = frame.cutHeight; + var sheetWidth = frame.realWidth; + var sheetHeight = frame.realHeight; + + var row = Math.floor((sheetWidth - margin + spacing) / (frameWidth + spacing)); + var column = Math.floor((sheetHeight - margin + spacing) / (frameHeight + spacing)); + var total = row * column; + + // trim offsets + + var leftPad = frame.x; + var leftWidth = frameWidth - leftPad; + + var rightWidth = frameWidth - ((sheetWidth - cutWidth) - leftPad); + + var topPad = frame.y; + var topHeight = frameHeight - topPad; + + var bottomHeight = frameHeight - ((sheetHeight - cutHeight) - topPad); + + if (startFrame > total || startFrame < -total) + { + startFrame = 0; + } + + if (startFrame < 0) + { + // Allow negative skipframes. + startFrame = total + startFrame; + } + + if (endFrame !== -1) + { + total = startFrame + (endFrame + 1); + } + + var sheetFrame; + var frameX = margin; + var frameY = margin; + var frameIndex = 0; + var sourceIndex = frame.sourceIndex; + + for (var sheetY = 0; sheetY < column; sheetY++) + { + var topRow = (sheetY === 0); + var bottomRow = (sheetY === column - 1); + + for (var sheetX = 0; sheetX < row; sheetX++) + { + var leftRow = (sheetX === 0); + var rightRow = (sheetX === row - 1); + + sheetFrame = texture.add(frameIndex, sourceIndex, x + frameX, y + frameY, frameWidth, frameHeight); + + if (leftRow || topRow || rightRow || bottomRow) + { + var destX = (leftRow) ? leftPad : 0; + var destY = (topRow) ? topPad : 0; + + var trimWidth = 0; + var trimHeight = 0; + + if (leftRow) + { + trimWidth += (frameWidth - leftWidth); + } + + if (rightRow) + { + trimWidth += (frameWidth - rightWidth); + } + + if (topRow) + { + trimHeight += (frameHeight - topHeight); + } + + if (bottomRow) + { + trimHeight += (frameHeight - bottomHeight); + } + + var destWidth = frameWidth - trimWidth; + var destHeight = frameHeight - trimHeight; + + sheetFrame.cutWidth = destWidth; + sheetFrame.cutHeight = destHeight; + + sheetFrame.setTrim(frameWidth, frameHeight, destX, destY, destWidth, destHeight); + } + + frameX += spacing; + + if (leftRow) + { + frameX += leftWidth; + } + else if (rightRow) + { + frameX += rightWidth; + } + else + { + frameX += frameWidth; + } + + frameIndex++; + } + + frameX = margin; + frameY += spacing; + + if (topRow) + { + frameY += topHeight; + } + else if (bottomRow) + { + frameY += bottomHeight; + } + else + { + frameY += frameHeight; + } + } + + return texture; +}; + +module.exports = SpriteSheetFromAtlas; diff --git a/src/textures/parsers/UnityYAML.js b/src/textures/parsers/UnityYAML.js index fdbb4ed80..3dd0d5b0a 100644 --- a/src/textures/parsers/UnityYAML.js +++ b/src/textures/parsers/UnityYAML.js @@ -1,164 +1,164 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var imageHeight = 0; - -/** - * @function addFrame - * @private - * @since 3.0.0 - */ -var addFrame = function (texture, sourceIndex, name, frame) -{ - // The frame values are the exact coordinates to cut the frame out of the atlas from - - var y = imageHeight - frame.y - frame.height; - - texture.add(name, sourceIndex, frame.x, y, frame.width, frame.height); - - // These are the original (non-trimmed) sprite values - /* - if (src.trimmed) - { - newFrame.setTrim( - src.sourceSize.w, - src.sourceSize.h, - src.spriteSourceSize.x, - src.spriteSourceSize.y, - src.spriteSourceSize.w, - src.spriteSourceSize.h - ); - } - */ -}; - -/** - * 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 {integer} sourceIndex - The index of the TextureSource. - * @param {object} yaml - The YAML data. - * - * @return {Phaser.Textures.Texture} The Texture modified by this parser. - */ -var UnityYAML = function (texture, sourceIndex, yaml) -{ - // Add in a __BASE entry (for the entire atlas) - var source = texture.source[sourceIndex]; - - texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); - - imageHeight = source.height; - - var data = yaml.split('\n'); - - var lineRegExp = /^[ ]*(- )*(\w+)+[: ]+(.*)/; - - var prevSprite = ''; - var currentSprite = ''; - var rect = { x: 0, y: 0, width: 0, height: 0 }; - - // var pivot = { x: 0, y: 0 }; - // var border = { x: 0, y: 0, z: 0, w: 0 }; - - for (var i = 0; i < data.length; i++) - { - var results = data[i].match(lineRegExp); - - if (!results) - { - continue; - } - - var isList = (results[1] === '- '); - var key = results[2]; - var value = results[3]; - - if (isList) - { - if (currentSprite !== prevSprite) - { - addFrame(texture, sourceIndex, currentSprite, rect); - - prevSprite = currentSprite; - } - - rect = { x: 0, y: 0, width: 0, height: 0 }; - } - - if (key === 'name') - { - // Start new list - currentSprite = value; - continue; - } - - switch (key) - { - case 'x': - case 'y': - case 'width': - case 'height': - rect[key] = parseInt(value, 10); - break; - - // case 'pivot': - // pivot = eval('var obj = ' + value); - // break; - - // case 'border': - // border = eval('var obj = ' + value); - // break; - } - } - - if (currentSprite !== prevSprite) - { - addFrame(texture, sourceIndex, currentSprite, rect); - } - - return texture; -}; - -module.exports = UnityYAML; - -/* -Example data: - -TextureImporter: - spritePivot: {x: .5, y: .5} - spriteBorder: {x: 0, y: 0, z: 0, w: 0} - spritePixelsToUnits: 100 - spriteSheet: - sprites: - - name: asteroids_0 - rect: - serializedVersion: 2 - x: 5 - y: 328 - width: 65 - height: 82 - alignment: 0 - pivot: {x: 0, y: 0} - border: {x: 0, y: 0, z: 0, w: 0} - - name: asteroids_1 - rect: - serializedVersion: 2 - x: 80 - y: 322 - width: 53 - height: 88 - alignment: 0 - pivot: {x: 0, y: 0} - border: {x: 0, y: 0, z: 0, w: 0} - spritePackingTag: Asteroids -*/ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var imageHeight = 0; + +/** + * @function addFrame + * @private + * @since 3.0.0 + */ +var addFrame = function (texture, sourceIndex, name, frame) +{ + // The frame values are the exact coordinates to cut the frame out of the atlas from + + var y = imageHeight - frame.y - frame.height; + + texture.add(name, sourceIndex, frame.x, y, frame.width, frame.height); + + // These are the original (non-trimmed) sprite values + /* + if (src.trimmed) + { + newFrame.setTrim( + src.sourceSize.w, + src.sourceSize.h, + src.spriteSourceSize.x, + src.spriteSourceSize.y, + src.spriteSourceSize.w, + src.spriteSourceSize.h + ); + } + */ +}; + +/** + * 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 {integer} sourceIndex - The index of the TextureSource. + * @param {object} yaml - The YAML data. + * + * @return {Phaser.Textures.Texture} The Texture modified by this parser. + */ +var UnityYAML = function (texture, sourceIndex, yaml) +{ + // Add in a __BASE entry (for the entire atlas) + var source = texture.source[sourceIndex]; + + texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height); + + imageHeight = source.height; + + var data = yaml.split('\n'); + + var lineRegExp = /^[ ]*(- )*(\w+)+[: ]+(.*)/; + + var prevSprite = ''; + var currentSprite = ''; + var rect = { x: 0, y: 0, width: 0, height: 0 }; + + // var pivot = { x: 0, y: 0 }; + // var border = { x: 0, y: 0, z: 0, w: 0 }; + + for (var i = 0; i < data.length; i++) + { + var results = data[i].match(lineRegExp); + + if (!results) + { + continue; + } + + var isList = (results[1] === '- '); + var key = results[2]; + var value = results[3]; + + if (isList) + { + if (currentSprite !== prevSprite) + { + addFrame(texture, sourceIndex, currentSprite, rect); + + prevSprite = currentSprite; + } + + rect = { x: 0, y: 0, width: 0, height: 0 }; + } + + if (key === 'name') + { + // Start new list + currentSprite = value; + continue; + } + + switch (key) + { + case 'x': + case 'y': + case 'width': + case 'height': + rect[key] = parseInt(value, 10); + break; + + // case 'pivot': + // pivot = eval('var obj = ' + value); + // break; + + // case 'border': + // border = eval('var obj = ' + value); + // break; + } + } + + if (currentSprite !== prevSprite) + { + addFrame(texture, sourceIndex, currentSprite, rect); + } + + return texture; +}; + +module.exports = UnityYAML; + +/* +Example data: + +TextureImporter: + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + spriteSheet: + sprites: + - name: asteroids_0 + rect: + serializedVersion: 2 + x: 5 + y: 328 + width: 65 + height: 82 + alignment: 0 + pivot: {x: 0, y: 0} + border: {x: 0, y: 0, z: 0, w: 0} + - name: asteroids_1 + rect: + serializedVersion: 2 + x: 80 + y: 322 + width: 53 + height: 88 + alignment: 0 + pivot: {x: 0, y: 0} + border: {x: 0, y: 0, z: 0, w: 0} + spritePackingTag: Asteroids +*/ diff --git a/src/textures/parsers/index.js b/src/textures/parsers/index.js index f8792146f..c6d507df9 100644 --- a/src/textures/parsers/index.js +++ b/src/textures/parsers/index.js @@ -1,22 +1,22 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Textures.Parsers - */ - -module.exports = { - - AtlasXML: require('./AtlasXML'), - Canvas: require('./Canvas'), - Image: require('./Image'), - JSONArray: require('./JSONArray'), - JSONHash: require('./JSONHash'), - SpriteSheet: require('./SpriteSheet'), - SpriteSheetFromAtlas: require('./SpriteSheetFromAtlas'), - UnityYAML: require('./UnityYAML') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Textures.Parsers + */ + +module.exports = { + + AtlasXML: require('./AtlasXML'), + Canvas: require('./Canvas'), + Image: require('./Image'), + JSONArray: require('./JSONArray'), + JSONHash: require('./JSONHash'), + SpriteSheet: require('./SpriteSheet'), + SpriteSheetFromAtlas: require('./SpriteSheetFromAtlas'), + UnityYAML: require('./UnityYAML') + +}; diff --git a/src/textures/typedefs/index.js b/src/textures/typedefs/index.js index 26dd8aa3c..cad2ba862 100644 --- a/src/textures/typedefs/index.js +++ b/src/textures/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Textures - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Textures + */ diff --git a/src/tilemaps/Formats.js b/src/tilemaps/Formats.js index 778df8922..be51de3b9 100644 --- a/src/tilemaps/Formats.js +++ b/src/tilemaps/Formats.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Formats - */ - -module.exports = { - - /** - * CSV Map Type - * - * @name Phaser.Tilemaps.Formats.CSV - * @type {number} - * @since 3.0.0 - */ - CSV: 0, - - /** - * Tiled JSON Map Type - * - * @name Phaser.Tilemaps.Formats.TILED_JSON - * @type {number} - * @since 3.0.0 - */ - TILED_JSON: 1, - - /** - * 2D Array Map Type - * - * @name Phaser.Tilemaps.Formats.ARRAY_2D - * @type {number} - * @since 3.0.0 - */ - ARRAY_2D: 2, - - /** - * Weltmeister (Impact.js) Map Type - * - * @name Phaser.Tilemaps.Formats.WELTMEISTER - * @type {number} - * @since 3.0.0 - */ - WELTMEISTER: 3 - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Formats + */ + +module.exports = { + + /** + * CSV Map Type + * + * @name Phaser.Tilemaps.Formats.CSV + * @type {number} + * @since 3.0.0 + */ + CSV: 0, + + /** + * Tiled JSON Map Type + * + * @name Phaser.Tilemaps.Formats.TILED_JSON + * @type {number} + * @since 3.0.0 + */ + TILED_JSON: 1, + + /** + * 2D Array Map Type + * + * @name Phaser.Tilemaps.Formats.ARRAY_2D + * @type {number} + * @since 3.0.0 + */ + ARRAY_2D: 2, + + /** + * Weltmeister (Impact.js) Map Type + * + * @name Phaser.Tilemaps.Formats.WELTMEISTER + * @type {number} + * @since 3.0.0 + */ + WELTMEISTER: 3 + +}; diff --git a/src/tilemaps/ImageCollection.js b/src/tilemaps/ImageCollection.js index aceb1ccde..3ca9e40a4 100644 --- a/src/tilemaps/ImageCollection.js +++ b/src/tilemaps/ImageCollection.js @@ -1,166 +1,166 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); - -/** - * @classdesc - * An Image Collection is a special Tile Set containing multiple images, with no slicing into each image. - * - * Image Collections are normally created automatically when Tiled data is loaded. - * - * @class ImageCollection - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.0 - * - * @param {string} name - The name of the image collection in the map data. - * @param {integer} firstgid - The first image index this image collection contains. - * @param {integer} [width=32] - Width of widest image (in pixels). - * @param {integer} [height=32] - Height of tallest image (in pixels). - * @param {integer} [margin=0] - The margin around all images in the collection (in pixels). - * @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). - * @param {object} [properties={}] - Custom Image Collection properties. - */ -var ImageCollection = new Class({ - - initialize: - - function ImageCollection (name, firstgid, width, height, margin, spacing, properties) - { - if (width === undefined || width <= 0) { width = 32; } - if (height === undefined || height <= 0) { height = 32; } - if (margin === undefined) { margin = 0; } - if (spacing === undefined) { spacing = 0; } - - /** - * The name of the Image Collection. - * - * @name Phaser.Tilemaps.ImageCollection#name - * @type {string} - * @since 3.0.0 - */ - this.name = name; - - /** - * The Tiled firstgid value. - * This is the starting index of the first image index this Image Collection contains. - * - * @name Phaser.Tilemaps.ImageCollection#firstgid - * @type {integer} - * @since 3.0.0 - */ - this.firstgid = firstgid | 0; - - /** - * The width of the widest image (in pixels). - * - * @name Phaser.Tilemaps.ImageCollection#imageWidth - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.imageWidth = width | 0; - - /** - * The height of the tallest image (in pixels). - * - * @name Phaser.Tilemaps.ImageCollection#imageHeight - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.imageHeight = height | 0; - - /** - * The margin around the images in the collection (in pixels). - * Use `setSpacing` to change. - * - * @name Phaser.Tilemaps.ImageCollection#imageMarge - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.imageMargin = margin | 0; - - /** - * The spacing between each image in the collection (in pixels). - * Use `setSpacing` to change. - * - * @name Phaser.Tilemaps.ImageCollection#imageSpacing - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.imageSpacing = spacing | 0; - - /** - * Image Collection-specific properties that are typically defined in the Tiled editor. - * - * @name Phaser.Tilemaps.ImageCollection#properties - * @type {object} - * @since 3.0.0 - */ - this.properties = properties || {}; - - /** - * The cached images that are a part of this collection. - * - * @name Phaser.Tilemaps.ImageCollection#images - * @type {array} - * @readonly - * @since 3.0.0 - */ - this.images = []; - - /** - * The total number of images in the image collection. - * - * @name Phaser.Tilemaps.ImageCollection#total - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.total = 0; - }, - - /** - * Returns true if and only if this image collection contains the given image index. - * - * @method Phaser.Tilemaps.ImageCollection#containsImageIndex - * @since 3.0.0 - * - * @param {integer} imageIndex - The image index to search for. - * - * @return {boolean} True if this Image Collection contains the given index. - */ - containsImageIndex: function (imageIndex) - { - return (imageIndex >= this.firstgid && imageIndex < (this.firstgid + this.total)); - }, - - /** - * Add an image to this Image Collection. - * - * @method Phaser.Tilemaps.ImageCollection#addImage - * @since 3.0.0 - * - * @param {integer} gid - The gid of the image in the Image Collection. - * @param {string} image - The the key of the image in the Image Collection and in the cache. - * - * @return {Phaser.Tilemaps.ImageCollection} This ImageCollection object. - */ - addImage: function (gid, image) - { - this.images.push({ gid: gid, image: image }); - this.total++; - - return this; - } - -}); - -module.exports = ImageCollection; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); + +/** + * @classdesc + * An Image Collection is a special Tile Set containing multiple images, with no slicing into each image. + * + * Image Collections are normally created automatically when Tiled data is loaded. + * + * @class ImageCollection + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {string} name - The name of the image collection in the map data. + * @param {integer} firstgid - The first image index this image collection contains. + * @param {integer} [width=32] - Width of widest image (in pixels). + * @param {integer} [height=32] - Height of tallest image (in pixels). + * @param {integer} [margin=0] - The margin around all images in the collection (in pixels). + * @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). + * @param {object} [properties={}] - Custom Image Collection properties. + */ +var ImageCollection = new Class({ + + initialize: + + function ImageCollection (name, firstgid, width, height, margin, spacing, properties) + { + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * + * @name Phaser.Tilemaps.ImageCollection#name + * @type {string} + * @since 3.0.0 + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * + * @name Phaser.Tilemaps.ImageCollection#firstgid + * @type {integer} + * @since 3.0.0 + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * + * @name Phaser.Tilemaps.ImageCollection#imageWidth + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * + * @name Phaser.Tilemaps.ImageCollection#imageHeight + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.ImageCollection#imageMarge + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.ImageCollection#imageSpacing + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * + * @name Phaser.Tilemaps.ImageCollection#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * + * @name Phaser.Tilemaps.ImageCollection#images + * @type {array} + * @readonly + * @since 3.0.0 + */ + this.images = []; + + /** + * The total number of images in the image collection. + * + * @name Phaser.Tilemaps.ImageCollection#total + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.total = 0; + }, + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.Tilemaps.ImageCollection#containsImageIndex + * @since 3.0.0 + * + * @param {integer} imageIndex - The image index to search for. + * + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) + { + return (imageIndex >= this.firstgid && imageIndex < (this.firstgid + this.total)); + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.Tilemaps.ImageCollection#addImage + * @since 3.0.0 + * + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + * + * @return {Phaser.Tilemaps.ImageCollection} This ImageCollection object. + */ + addImage: function (gid, image) + { + this.images.push({ gid: gid, image: image }); + this.total++; + + return this; + } + +}); + +module.exports = ImageCollection; diff --git a/src/tilemaps/ParseToTilemap.js b/src/tilemaps/ParseToTilemap.js index 851d13295..fa01e1b68 100644 --- a/src/tilemaps/ParseToTilemap.js +++ b/src/tilemaps/ParseToTilemap.js @@ -1,80 +1,80 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = require('./Formats'); -var MapData = require('./mapdata/MapData'); -var Parse = require('./parsers/Parse'); -var Tilemap = require('./Tilemap'); - -/** - * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When - * loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing from - * a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map data. For - * an empty map, you should specify tileWidth, tileHeight, width & height. - * - * @function Phaser.Tilemaps.ParseToTilemap - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene to which this Tilemap belongs. - * @param {string} [key] - The key in the Phaser cache that corresponds to the loaded tilemap data. - * @param {integer} [tileWidth=32] - The width of a tile in pixels. - * @param {integer} [tileHeight=32] - The height of a tile in pixels. - * @param {integer} [width=10] - The width of the map in tiles. - * @param {integer} [height=10] - The height of the map in tiles. - * @param {integer[][]} [data] - Instead of loading from the cache, you can also load directly from - * a 2D array of tile indexes. - * @param {boolean} [insertNull=false] - 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've 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.Tilemap} - */ -var ParseToTilemap = function (scene, key, tileWidth, tileHeight, width, height, data, insertNull) -{ - if (tileWidth === undefined) { tileWidth = 32; } - if (tileHeight === undefined) { tileHeight = 32; } - if (width === undefined) { width = 10; } - if (height === undefined) { height = 10; } - if (insertNull === undefined) { insertNull = false; } - - var mapData = null; - - if (Array.isArray(data)) - { - var name = key !== undefined ? key : 'map'; - mapData = Parse(name, Formats.ARRAY_2D, data, tileWidth, tileHeight, insertNull); - } - else if (key !== undefined) - { - var tilemapData = scene.cache.tilemap.get(key); - - if (!tilemapData) - { - console.warn('No map data found for key ' + key); - } - else - { - mapData = Parse(key, tilemapData.format, tilemapData.data, tileWidth, tileHeight, insertNull); - } - } - - if (mapData === null) - { - mapData = new MapData({ - tileWidth: tileWidth, - tileHeight: tileHeight, - width: width, - height: height - }); - } - - return new Tilemap(scene, mapData); -}; - -module.exports = ParseToTilemap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = require('./Formats'); +var MapData = require('./mapdata/MapData'); +var Parse = require('./parsers/Parse'); +var Tilemap = require('./Tilemap'); + +/** + * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When + * loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing from + * a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map data. For + * an empty map, you should specify tileWidth, tileHeight, width & height. + * + * @function Phaser.Tilemaps.ParseToTilemap + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene to which this Tilemap belongs. + * @param {string} [key] - The key in the Phaser cache that corresponds to the loaded tilemap data. + * @param {integer} [tileWidth=32] - The width of a tile in pixels. + * @param {integer} [tileHeight=32] - The height of a tile in pixels. + * @param {integer} [width=10] - The width of the map in tiles. + * @param {integer} [height=10] - The height of the map in tiles. + * @param {integer[][]} [data] - Instead of loading from the cache, you can also load directly from + * a 2D array of tile indexes. + * @param {boolean} [insertNull=false] - 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've 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.Tilemap} + */ +var ParseToTilemap = function (scene, key, tileWidth, tileHeight, width, height, data, insertNull) +{ + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + if (insertNull === undefined) { insertNull = false; } + + var mapData = null; + + if (Array.isArray(data)) + { + var name = key !== undefined ? key : 'map'; + mapData = Parse(name, Formats.ARRAY_2D, data, tileWidth, tileHeight, insertNull); + } + else if (key !== undefined) + { + var tilemapData = scene.cache.tilemap.get(key); + + if (!tilemapData) + { + console.warn('No map data found for key ' + key); + } + else + { + mapData = Parse(key, tilemapData.format, tilemapData.data, tileWidth, tileHeight, insertNull); + } + } + + if (mapData === null) + { + mapData = new MapData({ + tileWidth: tileWidth, + tileHeight: tileHeight, + width: width, + height: height + }); + } + + return new Tilemap(scene, mapData); +}; + +module.exports = ParseToTilemap; diff --git a/src/tilemaps/Tile.js b/src/tilemaps/Tile.js index 8f69338e8..9ca2245ca 100644 --- a/src/tilemaps/Tile.js +++ b/src/tilemaps/Tile.js @@ -1,853 +1,853 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../const.js'); -var Class = require('../utils/Class'); -var Components = require('../gameobjects/components'); -var Rectangle = require('../geom/rectangle'); - -/** - * @classdesc - * A Tile is a representation of a single tile within the Tilemap. This is a lightweight data - * representation, so its position information is stored without factoring in scroll, layer - * scale or layer position. - * - * @class Tile - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.0 - * - * @extends Phaser.GameObjects.Components.Alpha - * @extends Phaser.GameObjects.Components.Flip - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Tilemaps.LayerData} layer - The LayerData object in the Tilemap that this tile belongs to. - * @param {integer} index - The unique index of this tile within the map. - * @param {integer} x - The x coordinate of this tile in tile coordinates. - * @param {integer} y - The y coordinate of this tile in tile coordinates. - * @param {integer} width - Width of the tile in pixels. - * @param {integer} height - Height of the tile in pixels. - * @param {integer} baseWidth - The base width a tile in the map (in pixels). Tiled maps support - * multiple tileset sizes within one map, but they are still placed at intervals of the base - * tile width. - * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). Tiled maps - * support multiple tileset sizes within one map, but they are still placed at intervals of the - * base tile height. - */ -var Tile = new Class({ - - Mixins: [ - Components.Alpha, - Components.Flip, - Components.Visible - ], - - initialize: - - function Tile (layer, index, x, y, width, height, baseWidth, baseHeight) - { - /** - * The LayerData in the Tilemap data that this tile belongs to. - * - * @name Phaser.Tilemaps.Tile#layer - * @type {Phaser.Tilemaps.LayerData} - * @since 3.0.0 - */ - this.layer = layer; - - /** - * The index of this tile within the map data corresponding to the tileset, or -1 if this - * represents a blank tile. - * - * @name Phaser.Tilemaps.Tile#index - * @type {integer} - * @since 3.0.0 - */ - this.index = index; - - /** - * The x map coordinate of this tile in tile units. - * - * @name Phaser.Tilemaps.Tile#x - * @type {integer} - * @since 3.0.0 - */ - this.x = x; - - /** - * The y map coordinate of this tile in tile units. - * - * @name Phaser.Tilemaps.Tile#y - * @type {integer} - * @since 3.0.0 - */ - this.y = y; - - /** - * The width of the tile in pixels. - * - * @name Phaser.Tilemaps.Tile#width - * @type {integer} - * @since 3.0.0 - */ - this.width = width; - - /** - * The height of the tile in pixels. - * - * @name Phaser.Tilemaps.Tile#height - * @type {integer} - * @since 3.0.0 - */ - this.height = height; - - /** - * The map's base width of a tile in pixels. Tiled maps support multiple tileset sizes - * within one map, but they are still placed at intervals of the base tile size. - * - * @name Phaser.Tilemaps.Tile#baseWidth - * @type {integer} - * @since 3.0.0 - */ - this.baseWidth = (baseWidth !== undefined) ? baseWidth : width; - - /** - * The map's base height of a tile in pixels. Tiled maps support multiple tileset sizes - * within one map, but they are still placed at intervals of the base tile size. - * - * @name Phaser.Tilemaps.Tile#baseHeight - * @type {integer} - * @since 3.0.0 - */ - this.baseHeight = (baseHeight !== undefined) ? baseHeight : height; - - /** - * The x coordinate of the top left of this tile in pixels. This is relative to the top left - * of the layer this tile is being rendered within. This property does NOT factor in camera - * scroll, layer scale or layer position. - * - * @name Phaser.Tilemaps.Tile#pixelX - * @type {number} - * @since 3.0.0 - */ - this.pixelX = 0; - - /** - * The y coordinate of the top left of this tile in pixels. This is relative to the top left - * of the layer this tile is being rendered within. This property does NOT factor in camera - * scroll, layer scale or layer position. - * - * @name Phaser.Tilemaps.Tile#pixelY - * @type {number} - * @since 3.0.0 - */ - this.pixelY = 0; - - this.updatePixelXY(); - - /** - * Tile specific properties. These usually come from Tiled. - * - * @name Phaser.Tilemaps.Tile#properties - * @type {any} - * @since 3.0.0 - */ - this.properties = {}; - - /** - * The rotation angle of this tile. - * - * @name Phaser.Tilemaps.Tile#rotation - * @type {number} - * @since 3.0.0 - */ - this.rotation = 0; - - /** - * Whether the tile should collide with any object on the left side. - * - * @name Phaser.Tilemaps.Tile#collideLeft - * @type {boolean} - * @since 3.0.0 - */ - this.collideLeft = false; - - /** - * Whether the tile should collide with any object on the right side. - * - * @name Phaser.Tilemaps.Tile#collideRight - * @type {boolean} - * @since 3.0.0 - */ - this.collideRight = false; - - /** - * Whether the tile should collide with any object on the top side. - * - * @name Phaser.Tilemaps.Tile#collideUp - * @type {boolean} - * @since 3.0.0 - */ - this.collideUp = false; - - /** - * Whether the tile should collide with any object on the bottom side. - * - * @name Phaser.Tilemaps.Tile#collideDown - * @type {boolean} - * @since 3.0.0 - */ - this.collideDown = false; - - /** - * Whether the tile's left edge is interesting for collisions. - * - * @name Phaser.Tilemaps.Tile#faceLeft - * @type {boolean} - * @since 3.0.0 - */ - this.faceLeft = false; - - /** - * Whether the tile's right edge is interesting for collisions. - * - * @name Phaser.Tilemaps.Tile#faceRight - * @type {boolean} - * @since 3.0.0 - */ - this.faceRight = false; - - /** - * Whether the tile's top edge is interesting for collisions. - * - * @name Phaser.Tilemaps.Tile#faceTop - * @type {boolean} - * @since 3.0.0 - */ - this.faceTop = false; - - /** - * Whether the tile's bottom edge is interesting for collisions. - * - * @name Phaser.Tilemaps.Tile#faceBottom - * @type {boolean} - * @since 3.0.0 - */ - this.faceBottom = false; - - /** - * Tile collision callback. - * - * @name Phaser.Tilemaps.Tile#collisionCallback - * @type {function} - * @since 3.0.0 - */ - this.collisionCallback = null; - - /** - * The context in which the collision callback will be called. - * - * @name Phaser.Tilemaps.Tile#collisionCallbackContext - * @type {object} - * @since 3.0.0 - */ - this.collisionCallbackContext = this; - - /** - * The tint to apply to this tile. Note: tint is currently a single color value instead of - * the 4 corner tint component on other GameObjects. - * - * @name Phaser.Tilemaps.Tile#tint - * @type {number} - * @default - * @since 3.0.0 - */ - this.tint = 0xffffff; - - /** - * An empty object where physics-engine specific information (e.g. bodies) may be stored. - * - * @name Phaser.Tilemaps.Tile#physics - * @type {object} - * @since 3.0.0 - */ - this.physics = {}; - }, - - /** - * Check if the given x and y world coordinates are within this Tile. This does not factor in - * camera scroll, layer scale or layer position. - * - * @method Phaser.Tilemaps.Tile#containsPoint - * @since 3.0.0 - * - * @param {number} x - The x coordinate to test. - * @param {number} y - The y coordinate to test. - * - * @return {boolean} True if the coordinates are within this Tile, otherwise false. - */ - containsPoint: function (x, y) - { - return !(x < this.pixelX || y < this.pixelY || x > this.right || y > this.bottom); - }, - - /** - * Copies the tile data & properties from the given tile to this tile. This copies everything - * except for position and interesting faces. - * - * @method Phaser.Tilemaps.Tile#copy - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.Tile} tile - The tile to copy from. - * - * @return {Phaser.Tilemaps.Tile} This Tile object. - */ - copy: function (tile) - { - this.index = tile.index; - this.alpha = tile.alpha; - this.properties = tile.properties; - this.visible = tile.visible; - this.setFlip(tile.flipX, tile.flipY); - this.tint = tile.tint; - this.rotation = tile.rotation; - this.collideUp = tile.collideUp; - this.collideDown = tile.collideDown; - this.collideLeft = tile.collideLeft; - this.collideRight = tile.collideRight; - this.collisionCallback = tile.collisionCallback; - this.collisionCallbackContext = tile.collisionCallbackContext; - - return this; - }, - - /** - * The collision group for this Tile, defined within the Tileset. This returns a reference to - * the collision group stored within the Tileset, so any modification of the returned object - * will impact all tiles that have the same index as this tile. - * - * @method Phaser.Tilemaps.Tile#getCollisionGroup - * @since 3.0.0 - * - * @return {?object} tileset - */ - getCollisionGroup: function () - { - return this.tileset ? this.tileset.getTileCollisionGroup(this.index) : null; - }, - - /** - * The tile data for this Tile, defined within the Tileset. This typically contains Tiled - * collision data, tile animations and terrain information. This returns a reference to the tile - * data stored within the Tileset, so any modification of the returned object will impact all - * tiles that have the same index as this tile. - * - * @method Phaser.Tilemaps.Tile#getTileData - * @since 3.0.0 - * - * @return {?object} tileset - */ - getTileData: function () - { - return this.tileset ? this.tileset.getTileData(this.index) : null; - }, - - /** - * Gets the world X position of the left side of the tile, factoring in the layers position, - * scale and scroll. - * - * @method Phaser.Tilemaps.Tile#getLeft - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * - * @return {number} - */ - getLeft: function (camera) - { - var tilemapLayer = this.tilemapLayer; - - return (tilemapLayer) ? tilemapLayer.tileToWorldX(this.x, camera) : this.x * this.baseWidth; - }, - - /** - * Gets the world X position of the right side of the tile, factoring in the layer's position, - * scale and scroll. - * - * @method Phaser.Tilemaps.Tile#getRight - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * - * @return {number} - */ - getRight: function (camera) - { - var tilemapLayer = this.tilemapLayer; - - return (tilemapLayer) ? this.getLeft(camera) + this.width * tilemapLayer.scaleX : this.getLeft(camera) + this.width; - }, - - /** - * Gets the world Y position of the top side of the tile, factoring in the layer's position, - * scale and scroll. - * - * @method Phaser.Tilemaps.Tile#getTop - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * - * @return {number} - */ - getTop: function (camera) - { - var tilemapLayer = this.tilemapLayer; - - // 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. - return tilemapLayer - ? tilemapLayer.tileToWorldY(this.y, camera) - (this.height - this.baseHeight) * tilemapLayer.scaleY - : this.y * this.baseHeight - (this.height - this.baseHeight); - }, - - /** - * Gets the world Y position of the bottom side of the tile, factoring in the layer's position, - * scale and scroll. - - * @method Phaser.Tilemaps.Tile#getBottom - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * - * @return {number} - */ - getBottom: function (camera) - { - var tilemapLayer = this.tilemapLayer; - return tilemapLayer - ? this.getTop(camera) + this.height * tilemapLayer.scaleY - : this.getTop(camera) + this.height; - }, - - - /** - * Gets the world rectangle bounding box for the tile, factoring in the layers position, - * scale and scroll. - * - * @method Phaser.Tilemaps.Tile#getBounds - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * @param {object} [output] - [description] - * - * @return {(Phaser.Geom.Rectangle|object)} - */ - getBounds: function (camera, output) - { - if (output === undefined) { output = new Rectangle(); } - - output.x = this.getLeft(); - output.y = this.getTop(); - output.width = this.getRight() - output.x; - output.height = this.getBottom() - output.y; - - return output; - }, - - /** - * Gets the world X position of the center of the tile, factoring in the layer's position, - * scale and scroll. - * - * @method Phaser.Tilemaps.Tile#getCenterX - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * - * @return {number} - */ - getCenterX: function (camera) - { - return (this.getLeft(camera) + this.getRight(camera)) / 2; - }, - - /** - * Gets the world Y position of the center of the tile, factoring in the layer's position, - * scale and scroll. - * - * @method Phaser.Tilemaps.Tile#getCenterY - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. - * - * @return {number} - */ - getCenterY: function (camera) - { - return (this.getTop(camera) + this.getBottom(camera)) / 2; - }, - - /** - * Clean up memory. - * - * @method Phaser.Tilemaps.Tile#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.collisionCallback = undefined; - this.collisionCallbackContext = undefined; - this.properties = undefined; - }, - - /** - * Check for intersection with this tile. This does not factor in camera scroll, layer scale or - * layer position. - * - * @method Phaser.Tilemaps.Tile#intersects - * @since 3.0.0 - * - * @param {number} x - The x axis in pixels. - * @param {number} y - The y axis in pixels. - * @param {number} right - The right point. - * @param {number} bottom - The bottom point. - * - * @return {boolean} - */ - intersects: function (x, y, right, bottom) - { - return !( - right <= this.pixelX || bottom <= this.pixelY || - x >= this.right || y >= this.bottom - ); - }, - - /** - * Checks if the tile is interesting. - * - * @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. - */ - isInteresting: function (collides, faces) - { - if (collides && faces) { return (this.canCollide || this.hasInterestingFace); } - else if (collides) { return this.collides; } - else if (faces) { return this.hasInterestingFace; } - return false; - }, - - /** - * Reset collision status flags. - * - * @method Phaser.Tilemaps.Tile#resetCollision - * @since 3.0.0 - * - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate interesting faces for this tile and its neighbors. - * - * @return {Phaser.Tilemaps.Tile} This Tile object. - */ - resetCollision: function (recalculateFaces) - { - if (recalculateFaces === undefined) { recalculateFaces = true; } - - this.collideLeft = false; - this.collideRight = false; - this.collideUp = false; - this.collideDown = false; - - this.faceTop = false; - this.faceBottom = false; - this.faceLeft = false; - this.faceRight = false; - - if (recalculateFaces) - { - var tilemapLayer = this.tilemapLayer; - - if (tilemapLayer) - { - this.tilemapLayer.calculateFacesAt(this.x, this.y); - } - } - - return this; - }, - - /** - * Reset faces. - * - * @method Phaser.Tilemaps.Tile#resetFaces - * @since 3.0.0 - * - * @return {Phaser.Tilemaps.Tile} This Tile object. - */ - resetFaces: function () - { - this.faceTop = false; - this.faceBottom = false; - this.faceLeft = false; - this.faceRight = false; - - return this; - }, - - /** - * Sets the collision flags for each side of this tile and updates the interesting faces list. - * - * @method Phaser.Tilemaps.Tile#setCollision - * @since 3.0.0 - * - * @param {boolean} left - Indicating collide with any object on the left. - * @param {boolean} [right] - Indicating collide with any object on the right. - * @param {boolean} [up] - Indicating collide with any object on the top. - * @param {boolean} [down] - Indicating collide with any object on the bottom. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate interesting faces - * for this tile and its neighbors. - * - * @return {Phaser.Tilemaps.Tile} This Tile object. - */ - setCollision: function (left, right, up, down, recalculateFaces) - { - if (right === undefined) { right = left; } - if (up === undefined) { up = left; } - if (down === undefined) { down = left; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - this.collideLeft = left; - this.collideRight = right; - this.collideUp = up; - this.collideDown = down; - - this.faceLeft = left; - this.faceRight = right; - this.faceTop = up; - this.faceBottom = down; - - if (recalculateFaces) - { - var tilemapLayer = this.tilemapLayer; - - if (tilemapLayer) - { - this.tilemapLayer.calculateFacesAt(this.x, this.y); - } - } - - return this; - }, - - /** - * Set a callback to be called when this tile is hit by an object. The callback must true for - * collision processing to take place. - * - * @method Phaser.Tilemaps.Tile#setCollisionCallback - * @since 3.0.0 - * - * @param {function} callback - Callback function. - * @param {object} context - Callback will be called within this context. - * - * @return {Phaser.Tilemaps.Tile} This Tile object. - */ - setCollisionCallback: function (callback, context) - { - if (callback === null) - { - this.collisionCallback = undefined; - this.collisionCallbackContext = undefined; - } - else - { - this.collisionCallback = callback; - this.collisionCallbackContext = context; - } - - return this; - }, - - /** - * Sets the size of the tile and updates its pixelX and pixelY. - * - * @method Phaser.Tilemaps.Tile#setSize - * @since 3.0.0 - * - * @param {integer} tileWidth - The width of the tile in pixels. - * @param {integer} tileHeight - The height of the tile in pixels. - * @param {integer} baseWidth - The base width a tile in the map (in pixels). - * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). - * - * @return {Phaser.Tilemaps.Tile} This Tile object. - */ - setSize: function (tileWidth, tileHeight, baseWidth, baseHeight) - { - if (tileWidth !== undefined) { this.width = tileWidth; } - if (tileHeight !== undefined) { this.height = tileHeight; } - if (baseWidth !== undefined) { this.baseWidth = baseWidth; } - if (baseHeight !== undefined) { this.baseHeight = baseHeight; } - - this.updatePixelXY(); - - return this; - }, - - /** - * 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 {Phaser.Tilemaps.Tile} This Tile object. - */ - updatePixelXY: function () - { - if (this.layer.orientation === CONST.ISOMETRIC) - { - // 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. - this.pixelX = (this.x - this.y) * this.baseWidth * 0.5; - this.pixelY = (this.x + this.y) * this.baseHeight * 0.5; - } - else if (this.layer.orientation === CONST.STAGGERED) - { - this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); - this.pixelY = this.y * (this.baseHeight / 2); - } - else if (this.layer.orientation === CONST.HEXAGONAL) - { - var sidel = this.layer.hexSideLength; - var rowHeight = ((this.baseHeight - sidel) / 2 + sidel); - this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); - this.pixelY = this.y * rowHeight; - } - else if (this.layer.orientation === CONST.ORTHOGONAL) - { - // 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. - this.pixelX = this.x * this.baseWidth; - this.pixelY = this.y * this.baseHeight; - - } - return this; - }, - - /** - * True if this tile can collide on any of its faces or has a collision callback set. - * - * @name Phaser.Tilemaps.Tile#canCollide - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - canCollide: { - get: function () - { - return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); - } - }, - - /** - * True if this tile can collide on any of its faces. - * - * @name Phaser.Tilemaps.Tile#collides - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - collides: { - get: function () - { - return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); - } - }, - - /** - * True if this tile has any interesting faces. - * - * @name Phaser.Tilemaps.Tile#hasInterestingFace - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - hasInterestingFace: { - get: function () - { - return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); - } - }, - - /** - * The tileset that contains this Tile. This is null if accessed from a LayerData instance - * before the tile is placed in a StaticTilemapLayer or DynamicTilemapLayer, or if the tile has - * an index that doesn't correspond to any of the map's tilesets. - * - * @name Phaser.Tilemaps.Tile#tileset - * @type {?Phaser.Tilemaps.Tileset} - * @readonly - * @since 3.0.0 - */ - tileset: { - - get: function () - { - var tilemapLayer = this.layer.tilemapLayer; - - if (tilemapLayer) - { - var tileset = tilemapLayer.gidMap[this.index]; - - if (tileset) - { - return tileset; - } - } - - return null; - } - - }, - - /** - * The tilemap layer that contains this Tile. This will only return null if accessed from a - * LayerData instance before the tile is placed within a StaticTilemapLayer or - * DynamicTilemapLayer. - * - * @name Phaser.Tilemaps.Tile#tilemapLayer - * @type {?Phaser.Tilemaps.StaticTilemapLayer|Phaser.Tilemaps.DynamicTilemapLayer} - * @readonly - * @since 3.0.0 - */ - tilemapLayer: { - get: function () - { - return this.layer.tilemapLayer; - } - }, - - /** - * The tilemap that contains this Tile. This will only return null if accessed from a LayerData - * instance before the tile is placed within a StaticTilemapLayer or DynamicTilemapLayer. - * - * @name Phaser.Tilemaps.Tile#tilemap - * @type {?Phaser.Tilemaps.Tilemap} - * @readonly - * @since 3.0.0 - */ - tilemap: { - get: function () - { - var tilemapLayer = this.tilemapLayer; - return tilemapLayer ? tilemapLayer.tilemap : null; - } - } - -}); - -module.exports = Tile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../const.js'); +var Class = require('../utils/Class'); +var Components = require('../gameobjects/components'); +var Rectangle = require('../geom/rectangle'); + +/** + * @classdesc + * A Tile is a representation of a single tile within the Tilemap. This is a lightweight data + * representation, so its position information is stored without factoring in scroll, layer + * scale or layer position. + * + * @class Tile + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @extends Phaser.GameObjects.Components.Alpha + * @extends Phaser.GameObjects.Components.Flip + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Tilemaps.LayerData} layer - The LayerData object in the Tilemap that this tile belongs to. + * @param {integer} index - The unique index of this tile within the map. + * @param {integer} x - The x coordinate of this tile in tile coordinates. + * @param {integer} y - The y coordinate of this tile in tile coordinates. + * @param {integer} width - Width of the tile in pixels. + * @param {integer} height - Height of the tile in pixels. + * @param {integer} baseWidth - The base width a tile in the map (in pixels). Tiled maps support + * multiple tileset sizes within one map, but they are still placed at intervals of the base + * tile width. + * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). Tiled maps + * support multiple tileset sizes within one map, but they are still placed at intervals of the + * base tile height. + */ +var Tile = new Class({ + + Mixins: [ + Components.Alpha, + Components.Flip, + Components.Visible + ], + + initialize: + + function Tile (layer, index, x, y, width, height, baseWidth, baseHeight) + { + /** + * The LayerData in the Tilemap data that this tile belongs to. + * + * @name Phaser.Tilemaps.Tile#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + this.layer = layer; + + /** + * The index of this tile within the map data corresponding to the tileset, or -1 if this + * represents a blank tile. + * + * @name Phaser.Tilemaps.Tile#index + * @type {integer} + * @since 3.0.0 + */ + this.index = index; + + /** + * The x map coordinate of this tile in tile units. + * + * @name Phaser.Tilemaps.Tile#x + * @type {integer} + * @since 3.0.0 + */ + this.x = x; + + /** + * The y map coordinate of this tile in tile units. + * + * @name Phaser.Tilemaps.Tile#y + * @type {integer} + * @since 3.0.0 + */ + this.y = y; + + /** + * The width of the tile in pixels. + * + * @name Phaser.Tilemaps.Tile#width + * @type {integer} + * @since 3.0.0 + */ + this.width = width; + + /** + * The height of the tile in pixels. + * + * @name Phaser.Tilemaps.Tile#height + * @type {integer} + * @since 3.0.0 + */ + this.height = height; + + /** + * The map's base width of a tile in pixels. Tiled maps support multiple tileset sizes + * within one map, but they are still placed at intervals of the base tile size. + * + * @name Phaser.Tilemaps.Tile#baseWidth + * @type {integer} + * @since 3.0.0 + */ + this.baseWidth = (baseWidth !== undefined) ? baseWidth : width; + + /** + * The map's base height of a tile in pixels. Tiled maps support multiple tileset sizes + * within one map, but they are still placed at intervals of the base tile size. + * + * @name Phaser.Tilemaps.Tile#baseHeight + * @type {integer} + * @since 3.0.0 + */ + this.baseHeight = (baseHeight !== undefined) ? baseHeight : height; + + /** + * The x coordinate of the top left of this tile in pixels. This is relative to the top left + * of the layer this tile is being rendered within. This property does NOT factor in camera + * scroll, layer scale or layer position. + * + * @name Phaser.Tilemaps.Tile#pixelX + * @type {number} + * @since 3.0.0 + */ + this.pixelX = 0; + + /** + * The y coordinate of the top left of this tile in pixels. This is relative to the top left + * of the layer this tile is being rendered within. This property does NOT factor in camera + * scroll, layer scale or layer position. + * + * @name Phaser.Tilemaps.Tile#pixelY + * @type {number} + * @since 3.0.0 + */ + this.pixelY = 0; + + this.updatePixelXY(); + + /** + * Tile specific properties. These usually come from Tiled. + * + * @name Phaser.Tilemaps.Tile#properties + * @type {any} + * @since 3.0.0 + */ + this.properties = {}; + + /** + * The rotation angle of this tile. + * + * @name Phaser.Tilemaps.Tile#rotation + * @type {number} + * @since 3.0.0 + */ + this.rotation = 0; + + /** + * Whether the tile should collide with any object on the left side. + * + * @name Phaser.Tilemaps.Tile#collideLeft + * @type {boolean} + * @since 3.0.0 + */ + this.collideLeft = false; + + /** + * Whether the tile should collide with any object on the right side. + * + * @name Phaser.Tilemaps.Tile#collideRight + * @type {boolean} + * @since 3.0.0 + */ + this.collideRight = false; + + /** + * Whether the tile should collide with any object on the top side. + * + * @name Phaser.Tilemaps.Tile#collideUp + * @type {boolean} + * @since 3.0.0 + */ + this.collideUp = false; + + /** + * Whether the tile should collide with any object on the bottom side. + * + * @name Phaser.Tilemaps.Tile#collideDown + * @type {boolean} + * @since 3.0.0 + */ + this.collideDown = false; + + /** + * Whether the tile's left edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceLeft + * @type {boolean} + * @since 3.0.0 + */ + this.faceLeft = false; + + /** + * Whether the tile's right edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceRight + * @type {boolean} + * @since 3.0.0 + */ + this.faceRight = false; + + /** + * Whether the tile's top edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceTop + * @type {boolean} + * @since 3.0.0 + */ + this.faceTop = false; + + /** + * Whether the tile's bottom edge is interesting for collisions. + * + * @name Phaser.Tilemaps.Tile#faceBottom + * @type {boolean} + * @since 3.0.0 + */ + this.faceBottom = false; + + /** + * Tile collision callback. + * + * @name Phaser.Tilemaps.Tile#collisionCallback + * @type {function} + * @since 3.0.0 + */ + this.collisionCallback = null; + + /** + * The context in which the collision callback will be called. + * + * @name Phaser.Tilemaps.Tile#collisionCallbackContext + * @type {object} + * @since 3.0.0 + */ + this.collisionCallbackContext = this; + + /** + * The tint to apply to this tile. Note: tint is currently a single color value instead of + * the 4 corner tint component on other GameObjects. + * + * @name Phaser.Tilemaps.Tile#tint + * @type {number} + * @default + * @since 3.0.0 + */ + this.tint = 0xffffff; + + /** + * An empty object where physics-engine specific information (e.g. bodies) may be stored. + * + * @name Phaser.Tilemaps.Tile#physics + * @type {object} + * @since 3.0.0 + */ + this.physics = {}; + }, + + /** + * Check if the given x and y world coordinates are within this Tile. This does not factor in + * camera scroll, layer scale or layer position. + * + * @method Phaser.Tilemaps.Tile#containsPoint + * @since 3.0.0 + * + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) + { + return !(x < this.pixelX || y < this.pixelY || x > this.right || y > this.bottom); + }, + + /** + * Copies the tile data & properties from the given tile to this tile. This copies everything + * except for position and interesting faces. + * + * @method Phaser.Tilemaps.Tile#copy + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The tile to copy from. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + copy: function (tile) + { + this.index = tile.index; + this.alpha = tile.alpha; + this.properties = tile.properties; + this.visible = tile.visible; + this.setFlip(tile.flipX, tile.flipY); + this.tint = tile.tint; + this.rotation = tile.rotation; + this.collideUp = tile.collideUp; + this.collideDown = tile.collideDown; + this.collideLeft = tile.collideLeft; + this.collideRight = tile.collideRight; + this.collisionCallback = tile.collisionCallback; + this.collisionCallbackContext = tile.collisionCallbackContext; + + return this; + }, + + /** + * The collision group for this Tile, defined within the Tileset. This returns a reference to + * the collision group stored within the Tileset, so any modification of the returned object + * will impact all tiles that have the same index as this tile. + * + * @method Phaser.Tilemaps.Tile#getCollisionGroup + * @since 3.0.0 + * + * @return {?object} tileset + */ + getCollisionGroup: function () + { + return this.tileset ? this.tileset.getTileCollisionGroup(this.index) : null; + }, + + /** + * The tile data for this Tile, defined within the Tileset. This typically contains Tiled + * collision data, tile animations and terrain information. This returns a reference to the tile + * data stored within the Tileset, so any modification of the returned object will impact all + * tiles that have the same index as this tile. + * + * @method Phaser.Tilemaps.Tile#getTileData + * @since 3.0.0 + * + * @return {?object} tileset + */ + getTileData: function () + { + return this.tileset ? this.tileset.getTileData(this.index) : null; + }, + + /** + * Gets the world X position of the left side of the tile, factoring in the layers position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getLeft + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getLeft: function (camera) + { + var tilemapLayer = this.tilemapLayer; + + return (tilemapLayer) ? tilemapLayer.tileToWorldX(this.x, camera) : this.x * this.baseWidth; + }, + + /** + * Gets the world X position of the right side of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getRight + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getRight: function (camera) + { + var tilemapLayer = this.tilemapLayer; + + return (tilemapLayer) ? this.getLeft(camera) + this.width * tilemapLayer.scaleX : this.getLeft(camera) + this.width; + }, + + /** + * Gets the world Y position of the top side of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getTop + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getTop: function (camera) + { + var tilemapLayer = this.tilemapLayer; + + // 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. + return tilemapLayer + ? tilemapLayer.tileToWorldY(this.y, camera) - (this.height - this.baseHeight) * tilemapLayer.scaleY + : this.y * this.baseHeight - (this.height - this.baseHeight); + }, + + /** + * Gets the world Y position of the bottom side of the tile, factoring in the layer's position, + * scale and scroll. + + * @method Phaser.Tilemaps.Tile#getBottom + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getBottom: function (camera) + { + var tilemapLayer = this.tilemapLayer; + return tilemapLayer + ? this.getTop(camera) + this.height * tilemapLayer.scaleY + : this.getTop(camera) + this.height; + }, + + + /** + * Gets the world rectangle bounding box for the tile, factoring in the layers position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getBounds + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * @param {object} [output] - [description] + * + * @return {(Phaser.Geom.Rectangle|object)} + */ + getBounds: function (camera, output) + { + if (output === undefined) { output = new Rectangle(); } + + output.x = this.getLeft(); + output.y = this.getTop(); + output.width = this.getRight() - output.x; + output.height = this.getBottom() - output.y; + + return output; + }, + + /** + * Gets the world X position of the center of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getCenterX + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getCenterX: function (camera) + { + return (this.getLeft(camera) + this.getRight(camera)) / 2; + }, + + /** + * Gets the world Y position of the center of the tile, factoring in the layer's position, + * scale and scroll. + * + * @method Phaser.Tilemaps.Tile#getCenterY + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use to perform the check. + * + * @return {number} + */ + getCenterY: function (camera) + { + return (this.getTop(camera) + this.getBottom(camera)) / 2; + }, + + /** + * Clean up memory. + * + * @method Phaser.Tilemaps.Tile#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.collisionCallback = undefined; + this.collisionCallbackContext = undefined; + this.properties = undefined; + }, + + /** + * Check for intersection with this tile. This does not factor in camera scroll, layer scale or + * layer position. + * + * @method Phaser.Tilemaps.Tile#intersects + * @since 3.0.0 + * + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + * + * @return {boolean} + */ + intersects: function (x, y, right, bottom) + { + return !( + right <= this.pixelX || bottom <= this.pixelY || + x >= this.right || y >= this.bottom + ); + }, + + /** + * Checks if the tile is interesting. + * + * @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. + */ + isInteresting: function (collides, faces) + { + if (collides && faces) { return (this.canCollide || this.hasInterestingFace); } + else if (collides) { return this.collides; } + else if (faces) { return this.hasInterestingFace; } + return false; + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tilemaps.Tile#resetCollision + * @since 3.0.0 + * + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate interesting faces for this tile and its neighbors. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + resetCollision: function (recalculateFaces) + { + if (recalculateFaces === undefined) { recalculateFaces = true; } + + this.collideLeft = false; + this.collideRight = false; + this.collideUp = false; + this.collideDown = false; + + this.faceTop = false; + this.faceBottom = false; + this.faceLeft = false; + this.faceRight = false; + + if (recalculateFaces) + { + var tilemapLayer = this.tilemapLayer; + + if (tilemapLayer) + { + this.tilemapLayer.calculateFacesAt(this.x, this.y); + } + } + + return this; + }, + + /** + * Reset faces. + * + * @method Phaser.Tilemaps.Tile#resetFaces + * @since 3.0.0 + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + resetFaces: function () + { + this.faceTop = false; + this.faceBottom = false; + this.faceLeft = false; + this.faceRight = false; + + return this; + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tilemaps.Tile#setCollision + * @since 3.0.0 + * + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} [right] - Indicating collide with any object on the right. + * @param {boolean} [up] - Indicating collide with any object on the top. + * @param {boolean} [down] - Indicating collide with any object on the bottom. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate interesting faces + * for this tile and its neighbors. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + setCollision: function (left, right, up, down, recalculateFaces) + { + if (right === undefined) { right = left; } + if (up === undefined) { up = left; } + if (down === undefined) { down = left; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + if (recalculateFaces) + { + var tilemapLayer = this.tilemapLayer; + + if (tilemapLayer) + { + this.tilemapLayer.calculateFacesAt(this.x, this.y); + } + } + + return this; + }, + + /** + * Set a callback to be called when this tile is hit by an object. The callback must true for + * collision processing to take place. + * + * @method Phaser.Tilemaps.Tile#setCollisionCallback + * @since 3.0.0 + * + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + setCollisionCallback: function (callback, context) + { + if (callback === null) + { + this.collisionCallback = undefined; + this.collisionCallbackContext = undefined; + } + else + { + this.collisionCallback = callback; + this.collisionCallbackContext = context; + } + + return this; + }, + + /** + * Sets the size of the tile and updates its pixelX and pixelY. + * + * @method Phaser.Tilemaps.Tile#setSize + * @since 3.0.0 + * + * @param {integer} tileWidth - The width of the tile in pixels. + * @param {integer} tileHeight - The height of the tile in pixels. + * @param {integer} baseWidth - The base width a tile in the map (in pixels). + * @param {integer} baseHeight - The base height of the tile in pixels (in pixels). + * + * @return {Phaser.Tilemaps.Tile} This Tile object. + */ + setSize: function (tileWidth, tileHeight, baseWidth, baseHeight) + { + if (tileWidth !== undefined) { this.width = tileWidth; } + if (tileHeight !== undefined) { this.height = tileHeight; } + if (baseWidth !== undefined) { this.baseWidth = baseWidth; } + if (baseHeight !== undefined) { this.baseHeight = baseHeight; } + + this.updatePixelXY(); + + return this; + }, + + /** + * 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 {Phaser.Tilemaps.Tile} This Tile object. + */ + updatePixelXY: function () + { + if (this.layer.orientation === CONST.ISOMETRIC) + { + // 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. + this.pixelX = (this.x - this.y) * this.baseWidth * 0.5; + this.pixelY = (this.x + this.y) * this.baseHeight * 0.5; + } + else if (this.layer.orientation === CONST.STAGGERED) + { + this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); + this.pixelY = this.y * (this.baseHeight / 2); + } + else if (this.layer.orientation === CONST.HEXAGONAL) + { + var sidel = this.layer.hexSideLength; + var rowHeight = ((this.baseHeight - sidel) / 2 + sidel); + this.pixelX = this.x * this.baseWidth + this.y % 2 * (this.baseWidth / 2); + this.pixelY = this.y * rowHeight; + } + else if (this.layer.orientation === CONST.ORTHOGONAL) + { + // 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. + this.pixelX = this.x * this.baseWidth; + this.pixelY = this.y * this.baseHeight; + + } + return this; + }, + + /** + * True if this tile can collide on any of its faces or has a collision callback set. + * + * @name Phaser.Tilemaps.Tile#canCollide + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + canCollide: { + get: function () + { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + }, + + /** + * True if this tile can collide on any of its faces. + * + * @name Phaser.Tilemaps.Tile#collides + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + collides: { + get: function () + { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + }, + + /** + * True if this tile has any interesting faces. + * + * @name Phaser.Tilemaps.Tile#hasInterestingFace + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + hasInterestingFace: { + get: function () + { + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + }, + + /** + * The tileset that contains this Tile. This is null if accessed from a LayerData instance + * before the tile is placed in a StaticTilemapLayer or DynamicTilemapLayer, or if the tile has + * an index that doesn't correspond to any of the map's tilesets. + * + * @name Phaser.Tilemaps.Tile#tileset + * @type {?Phaser.Tilemaps.Tileset} + * @readonly + * @since 3.0.0 + */ + tileset: { + + get: function () + { + var tilemapLayer = this.layer.tilemapLayer; + + if (tilemapLayer) + { + var tileset = tilemapLayer.gidMap[this.index]; + + if (tileset) + { + return tileset; + } + } + + return null; + } + + }, + + /** + * The tilemap layer that contains this Tile. This will only return null if accessed from a + * LayerData instance before the tile is placed within a StaticTilemapLayer or + * DynamicTilemapLayer. + * + * @name Phaser.Tilemaps.Tile#tilemapLayer + * @type {?Phaser.Tilemaps.StaticTilemapLayer|Phaser.Tilemaps.DynamicTilemapLayer} + * @readonly + * @since 3.0.0 + */ + tilemapLayer: { + get: function () + { + return this.layer.tilemapLayer; + } + }, + + /** + * The tilemap that contains this Tile. This will only return null if accessed from a LayerData + * instance before the tile is placed within a StaticTilemapLayer or DynamicTilemapLayer. + * + * @name Phaser.Tilemaps.Tile#tilemap + * @type {?Phaser.Tilemaps.Tilemap} + * @readonly + * @since 3.0.0 + */ + tilemap: { + get: function () + { + var tilemapLayer = this.tilemapLayer; + return tilemapLayer ? tilemapLayer.tilemap : null; + } + } + +}); + +module.exports = Tile; diff --git a/src/tilemaps/Tilemap.js b/src/tilemaps/Tilemap.js index 96ca4a9c9..ad1810a36 100644 --- a/src/tilemaps/Tilemap.js +++ b/src/tilemaps/Tilemap.js @@ -1,2575 +1,2575 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var DegToRad = require('../math/DegToRad'); -var DynamicTilemapLayer = require('./dynamiclayer/DynamicTilemapLayer'); -var Extend = require('../utils/object/Extend'); -var Formats = require('./Formats'); -var LayerData = require('./mapdata/LayerData'); -var Rotate = require('../math/Rotate'); -var SpliceOne = require('../utils/array/SpliceOne'); -var StaticTilemapLayer = require('./staticlayer/StaticTilemapLayer'); -var Tile = require('./Tile'); -var TilemapComponents = require('./components'); -var Tileset = require('./Tileset'); - -/** - * @callback TilemapFilterCallback - * - * @param {Phaser.GameObjects.GameObject} value - An object found in the filtered area. - * @param {number} index - The index of the object within the array. - * @param {Phaser.GameObjects.GameObject[]} array - An array of all the objects found. - * - * @return {Phaser.GameObjects.GameObject} The object. - */ - -/** - * @callback TilemapFindCallback - * - * @param {Phaser.GameObjects.GameObject} value - An object found. - * @param {number} index - The index of the object within the array. - * @param {Phaser.GameObjects.GameObject[]} array - An array of all the objects found. - * - * @return {boolean} `true` if the callback should be invoked, otherwise `false`. - */ - -/** - * @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 (StaticTilemapLayer or DynamicTilemapLayer), which are the display - * objects that actually render tiles. - * - * The Tilemap data 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 - * - * A Tilemap has handy methods for getting & manipulating the tiles within a layer. You can only - * use the methods that change tiles (e.g. removeTileAt) on a DynamicTilemapLayer. - * - * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a - * StaticTilemapLayer or DynamicTilemapLayer may have its own unique tile size that overrides - * it. - * - * As of Phaser 3.21.0, if your tilemap includes layer groups (a feature of Tiled 1.2.0+) these - * will be traversed and the following properties will affect 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'. - * - * @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. - */ -var Tilemap = new Class({ - - initialize: - - function Tilemap (scene, mapData) - { - /** - * @name Phaser.Tilemaps.Tilemap#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The base width of a tile in pixels. Note that individual layers may have a different tile - * width. - * - * @name Phaser.Tilemaps.Tilemap#tileWidth - * @type {integer} - * @since 3.0.0 - */ - this.tileWidth = mapData.tileWidth; - - /** - * The base height of a tile in pixels. Note that individual layers may have a different - * tile height. - * - * @name Phaser.Tilemaps.Tilemap#tileHeight - * @type {integer} - * @since 3.0.0 - */ - this.tileHeight = mapData.tileHeight; - - /** - * The width of the map (in tiles). - * - * @name Phaser.Tilemaps.Tilemap#width - * @type {number} - * @since 3.0.0 - */ - this.width = mapData.width; - - /** - * The height of the map (in tiles). - * - * @name Phaser.Tilemaps.Tilemap#height - * @type {number} - * @since 3.0.0 - */ - this.height = mapData.height; - - /** - * The orientation of the map data (as specified in Tiled), usually 'orthogonal'. - * - * @name Phaser.Tilemaps.Tilemap#orientation - * @type {string} - * @since 3.0.0 - */ - this.orientation = mapData.orientation; - - /** - * The render (draw) order of the map data (as specified in Tiled), usually 'right-down'. - * - * The draw orders are: - * - * right-down - * left-down - * right-up - * left-up - * - * This can be changed via the `setRenderOrder` method. - * - * @name Phaser.Tilemaps.Tilemap#renderOrder - * @type {string} - * @since 3.12.0 - */ - this.renderOrder = mapData.renderOrder; - - /** - * The format of the map data. - * - * @name Phaser.Tilemaps.Tilemap#format - * @type {number} - * @since 3.0.0 - */ - this.format = mapData.format; - - /** - * The version of the map data (as specified in Tiled, usually 1). - * - * @name Phaser.Tilemaps.Tilemap#version - * @type {number} - * @since 3.0.0 - */ - this.version = mapData.version; - - /** - * Map specific properties as specified in Tiled. - * - * @name Phaser.Tilemaps.Tilemap#properties - * @type {object} - * @since 3.0.0 - */ - this.properties = mapData.properties; - - /** - * The width of the map in pixels based on width * tileWidth. - * - * @name Phaser.Tilemaps.Tilemap#widthInPixels - * @type {number} - * @since 3.0.0 - */ - this.widthInPixels = mapData.widthInPixels; - - /** - * The height of the map in pixels based on height * tileHeight. - * - * @name Phaser.Tilemaps.Tilemap#heightInPixels - * @type {number} - * @since 3.0.0 - */ - this.heightInPixels = mapData.heightInPixels; - - /** - * - * @name Phaser.Tilemaps.Tilemap#imageCollections - * @type {Phaser.Tilemaps.ImageCollection[]} - * @since 3.0.0 - */ - this.imageCollections = mapData.imageCollections; - - /** - * An array of Tiled Image Layers. - * - * @name Phaser.Tilemaps.Tilemap#images - * @type {array} - * @since 3.0.0 - */ - this.images = mapData.images; - - /** - * An array of Tilemap layer data. - * - * @name Phaser.Tilemaps.Tilemap#layers - * @type {Phaser.Tilemaps.LayerData[]} - * @since 3.0.0 - */ - this.layers = mapData.layers; - - /** - * An array of Tilesets used in the map. - * - * @name Phaser.Tilemaps.Tilemap#tilesets - * @type {Phaser.Tilemaps.Tileset[]} - * @since 3.0.0 - */ - this.tilesets = mapData.tilesets; - - /** - * An array of ObjectLayer instances parsed from Tiled object layers. - * - * @name Phaser.Tilemaps.Tilemap#objects - * @type {Phaser.Tilemaps.ObjectLayer[]} - * @since 3.0.0 - */ - this.objects = mapData.objects; - - /** - * The index of the currently selected LayerData object. - * - * @name Phaser.Tilemaps.Tilemap#currentLayerIndex - * @type {integer} - * @since 3.0.0 - */ - this.currentLayerIndex = 0; - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = mapData.hexSideLength; - - /** - * Components used for conversions between real world coordinates and tile coordinates, - * initialized here to prevent switching between them at runtime depending on map orientation. - * refer to the components themselves for documentation. - * @since 3.2.2 - */ - this.WorldToTileXY = TilemapComponents.WorldToTileXY(this.orientation); - this.WorldToTileX = TilemapComponents.WorldToTileX(this.orientation); - this.WorldToTileY = TilemapComponents.WorldToTileY(this.orientation); - this.TileToWorldXY = TilemapComponents.TileToWorldXY(this.orientation); - this.TileToWorldX = TilemapComponents.TileToWorldX(this.orientation); - this.TileToWorldY = TilemapComponents.TileToWorldY(this.orientation); - }, - - /** - * Sets the rendering (draw) order of the tiles in this map. - * - * The default is 'right-down', meaning it will order the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * Setting the render order does not change the tiles or how they are stored in the layer, - * it purely impacts the order in which they are rendered. - * - * You can provide either an integer (0 to 3), or the string version of the order. - * - * Calling this method _after_ creating Static or Dynamic Tilemap Layers will **not** automatically - * update them to use the new render order. If you call this method after creating layers, use their - * own `setRenderOrder` methods to change them as needed. - * - * @method Phaser.Tilemaps.Tilemap#setRenderOrder - * @since 3.12.0 - * - * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. - * - * @return {this} This Tilemap object. - */ - setRenderOrder: function (renderOrder) - { - var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; - - if (typeof renderOrder === 'number') - { - renderOrder = orders[renderOrder]; - } - - if (orders.indexOf(renderOrder) > -1) - { - this.renderOrder = renderOrder; - } - - return this; - }, - - /** - * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. - * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled - * editor. - * - * @method Phaser.Tilemaps.Tilemap#addTilesetImage - * @since 3.0.0 - * - * @param {string} tilesetName - The name of the tileset as specified in the map data. - * @param {string} [key] - The key of the Phaser.Cache image used for this tileset. If - * `undefined` or `null` it will look for an image with a key matching the tilesetName parameter. - * @param {integer} [tileWidth] - The width of the tile (in pixels) in the Tileset Image. If not - * given it will default to the map's tileWidth value, or the tileWidth specified in the Tiled - * JSON file. - * @param {integer} [tileHeight] - The height of the tiles (in pixels) in the Tileset Image. If - * not given it will default to the map's tileHeight value, or the tileHeight specified in the - * Tiled JSON file. - * @param {integer} [tileMargin] - The margin around the tiles in the sheet (in pixels). If not - * specified, it will default to 0 or the value specified in the Tiled JSON file. - * @param {integer} [tileSpacing] - The spacing between each the tile in the sheet (in pixels). - * If not specified, it will default to 0 or the value specified in the Tiled JSON file. - * @param {integer} [gid=0] - If adding multiple tilesets to a blank map, specify the starting - * GID this set will use here. - * - * @return {?Phaser.Tilemaps.Tileset} Returns the Tileset object that was created or updated, or null if it - * failed. - */ - addTilesetImage: function (tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) - { - if (tilesetName === undefined) { return null; } - if (key === undefined || key === null) { key = tilesetName; } - - if (!this.scene.sys.textures.exists(key)) - { - console.warn('Invalid Tileset Image: ' + key); - return null; - } - - var texture = this.scene.sys.textures.get(key); - - var index = this.getTilesetIndex(tilesetName); - - if (index === null && this.format === Formats.TILED_JSON) - { - console.warn('No data found for Tileset: ' + tilesetName); - return null; - } - - var tileset = this.tilesets[index]; - - if (tileset) - { - tileset.setTileSize(tileWidth, tileHeight); - tileset.setSpacing(tileMargin, tileSpacing); - tileset.setImage(texture); - - return tileset; - } - - if (tileWidth === undefined) { tileWidth = this.tileWidth; } - if (tileHeight === undefined) { tileHeight = this.tileHeight; } - if (tileMargin === undefined) { tileMargin = 0; } - if (tileSpacing === undefined) { tileSpacing = 0; } - if (gid === undefined) { gid = 0; } - - tileset = new Tileset(tilesetName, gid, tileWidth, tileHeight, tileMargin, tileSpacing); - - tileset.setImage(texture); - - this.tilesets.push(tileset); - - return tileset; - }, - - /** - * Turns the DynamicTilemapLayer associated with the given layer into a StaticTilemapLayer. If - * no layer specified, the map's current layer is used. This is useful if you want to manipulate - * a map at the start of a scene, but then make it non-manipulable and optimize it for speed. - * Note: the DynamicTilemapLayer passed in is destroyed, so make sure to store the value - * returned from this method if you want to manipulate the new StaticTilemapLayer. - * - * @method Phaser.Tilemaps.Tilemap#convertLayerToStatic - * @since 3.0.0 - * - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer)} [layer] - The name of the layer from Tiled, the - * index of the layer in the map, or a DynamicTilemapLayer. - * - * @return {?Phaser.Tilemaps.StaticTilemapLayer} Returns the new layer that was created, or null if it - * failed. - */ - convertLayerToStatic: function (layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - var dynamicLayer = layer.tilemapLayer; - - if (!dynamicLayer || !(dynamicLayer instanceof DynamicTilemapLayer)) - { - return null; - } - - var staticLayer = new StaticTilemapLayer( - dynamicLayer.scene, - dynamicLayer.tilemap, - dynamicLayer.layerIndex, - dynamicLayer.tileset, - dynamicLayer.x, - dynamicLayer.y - ); - - this.scene.sys.displayList.add(staticLayer); - - dynamicLayer.destroy(); - - return staticLayer; - }, - - /** - * Copies the tiles in the source rectangular area to a new destination (all specified in tile - * coordinates) within the layer. This copies all tile properties & recalculates collision - * information in the destination region. - * - * If no layer specified, the map's current layer is used. This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#copy - * @since 3.0.0 - * - * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. - * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. - * @param {integer} width - The width of the area to copy, in tiles, not pixels. - * @param {integer} height - The height of the area to copy, in tiles, not pixels. - * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. - * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - copy: function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'copy')) { return this; } - - if (layer !== null) - { - TilemapComponents.Copy( - srcTileX, srcTileY, - width, height, - destTileX, destTileY, - recalculateFaces, layer - ); - - return this; - } - else - { - return null; - } - }, - - /** - * Creates a new and empty DynamicTilemapLayer. The currently selected layer in the map is set to this new layer. - * - * @method Phaser.Tilemaps.Tilemap#createBlankDynamicLayer - * @since 3.0.0 - * - * @param {string} name - The name of this layer. Must be unique within the map. - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param {number} [x=0] - The world x position where the top left of this layer will be placed. - * @param {number} [y=0] - The world y position where the top left of this layer will be placed. - * @param {integer} [width] - The width of the layer in tiles. If not specified, it will default to the map's width. - * @param {integer} [height] - The height of the layer in tiles. If not specified, it will default to the map's height. - * @param {integer} [tileWidth] - The width of the tiles the layer uses for calculations. If not specified, it will default to the map's tileWidth. - * @param {integer} [tileHeight] - The height of the tiles the layer uses for calculations. If not specified, it will default to the map's tileHeight. - * - * @return {?Phaser.Tilemaps.DynamicTilemapLayer} Returns the new layer that was created, or `null` if it failed. - */ - createBlankDynamicLayer: function (name, tileset, x, y, width, height, tileWidth, tileHeight) - { - if (x === undefined) { x = 0; } - if (y === undefined) { y = 0; } - if (width === undefined) { width = this.width; } - if (height === undefined) { height = this.height; } - if (tileWidth === undefined) { tileWidth = this.tileWidth; } - if (tileHeight === undefined) { tileHeight = this.tileHeight; } - - var index = this.getLayerIndex(name); - - if (index !== null) - { - console.warn('Invalid Tilemap Layer ID: ' + name); - return null; - } - - var layerData = new LayerData({ - name: name, - tileWidth: tileWidth, - tileHeight: tileHeight, - width: width, - height: height, - orientation: this.orientation - }); - - var row; - - for (var tileY = 0; tileY < height; tileY++) - { - row = []; - - for (var tileX = 0; tileX < width; tileX++) - { - row.push(new Tile(layerData, -1, tileX, tileY, tileWidth, tileHeight, this.tileWidth, this.tileHeight)); - } - - layerData.data.push(row); - } - - this.layers.push(layerData); - - this.currentLayerIndex = this.layers.length - 1; - - var dynamicLayer = new DynamicTilemapLayer(this.scene, this, this.currentLayerIndex, tileset, x, y); - - dynamicLayer.setRenderOrder(this.renderOrder); - - this.scene.sys.displayList.add(dynamicLayer); - - return dynamicLayer; - }, - - /** - * Creates a new DynamicTilemapLayer that renders the LayerData associated with the given - * `layerID`. The currently selected layer in the map is set to this new layer. - * - * The `layerID` is important. If you've created your map in Tiled then you can get this by - * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and - * look at the layers[].name value. Either way it must match. - * - * Unlike a static layer, a dynamic layer can be modified. See DynamicTilemapLayer for more - * information. - * - * @method Phaser.Tilemaps.Tilemap#createDynamicLayer - * @since 3.0.0 - * - * @param {(integer|string)} layerID - The layer array index value, or if a string is given, the layer name from Tiled. - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param {number} [x=0] - The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. - * @param {number} [y=0] - The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. - * - * @return {?Phaser.Tilemaps.DynamicTilemapLayer} Returns the new layer was created, or null if it failed. - */ - createDynamicLayer: function (layerID, tileset, x, y) - { - var index = this.getLayerIndex(layerID); - - if (index === null) - { - console.warn('Invalid Tilemap Layer ID: ' + layerID); - - if (typeof layerID === 'string') - { - console.warn('Valid tilelayer names:\n\t' + this.getTileLayerNames().join(',\n\t')); - } - - return null; - } - - var layerData = this.layers[index]; - - // Check for an associated static or dynamic tilemap layer - if (layerData.tilemapLayer) - { - console.warn('Tilemap Layer ID already exists:' + layerID); - return null; - } - - this.currentLayerIndex = index; - - // Default the x/y position to match Tiled layer offset, if it exists. - - if (x === undefined) - { - x = layerData.x; - } - - if (y === undefined) - { - y = layerData.y; - } - - var layer = new DynamicTilemapLayer(this.scene, this, index, tileset, x, y); - - layer.setRenderOrder(this.renderOrder); - - this.scene.sys.displayList.add(layer); - - return layer; - }, - - /** - * Creates a Sprite for every object matching the given gid in the map data. All properties from - * the map data objectgroup are copied into the `spriteConfig`, so you can use this as an easy - * way to configure Sprite properties from within the map editor. For example giving an object a - * property of alpha: 0.5 in the map editor will duplicate that when the Sprite is created. - * - * Custom object properties not sharing names with the Sprite's own properties are copied to the - * Sprite's {@link Phaser.GameObjects.Sprite#data data store}. - * - * @method Phaser.Tilemaps.Tilemap#createFromObjects - * @since 3.0.0 - * - * @param {string} name - The name of the object layer (from Tiled) to create Sprites from. - * @param {(integer|string)} id - Either the id (object), gid (tile object) or name (object or - * tile object) from Tiled. Ids are unique in Tiled, but a gid is shared by all tile objects - * with the same graphic. The same name can be used on multiple objects. - * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. - * scene.make.sprite). - * @param {Phaser.Scene} [scene=the scene the map is within] - The Scene to create the Sprites within. - * - * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. - */ - createFromObjects: function (name, id, spriteConfig, scene) - { - if (spriteConfig === undefined) { spriteConfig = {}; } - if (scene === undefined) { scene = this.scene; } - - var objectLayer = this.getObjectLayer(name); - - if (!objectLayer) - { - console.warn('Cannot create from object. Invalid objectgroup name given: ' + name); - - if (typeof layerID === 'string') - { - console.warn('Valid objectgroup names:\n\t' + this.getObjectLayerNames().join(',\n\t')); - } - - return null; - } - - var objects = objectLayer.objects; - var sprites = []; - - for (var i = 0; i < objects.length; i++) - { - var found = false; - var obj = objects[i]; - - if (obj.gid !== undefined && typeof id === 'number' && obj.gid === id || - obj.id !== undefined && typeof id === 'number' && obj.id === id || - obj.name !== undefined && typeof id === 'string' && obj.name === id) - { - found = true; - } - - if (found) - { - var config = Extend({}, spriteConfig, obj.properties); - - config.x = obj.x; - config.y = obj.y; - - var sprite = scene.make.sprite(config); - - sprite.name = obj.name; - - if (obj.width) { sprite.displayWidth = obj.width; } - if (obj.height) { sprite.displayHeight = obj.height; } - - // Origin is (0, 1) in Tiled, so find the offset that matches the Sprite's origin. - var offset = { - x: sprite.originX * sprite.displayWidth, - y: (sprite.originY - 1) * sprite.displayHeight - }; - - // If the object is rotated, then the origin offset also needs to be rotated. - if (obj.rotation) - { - var angle = DegToRad(obj.rotation); - Rotate(offset, angle); - sprite.rotation = angle; - } - - sprite.x += offset.x; - sprite.y += offset.y; - - if (obj.flippedHorizontal !== undefined || obj.flippedVertical !== undefined) - { - sprite.setFlip(obj.flippedHorizontal, obj.flippedVertical); - } - - if (!obj.visible) { sprite.visible = false; } - - for (var key in obj.properties) - { - if (sprite.hasOwnProperty(key)) - { - continue; - } - - sprite.setData(key, obj.properties[key]); - } - - sprites.push(sprite); - } - } - - return sprites; - }, - - /** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * - * @method Phaser.Tilemaps.Tilemap#createFromTiles - * @since 3.0.0 - * - * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. - * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted - * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a - * one-to-one mapping with the indexes array. - * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. scene.make.sprite). - * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.GameObjects.Sprite[]} Returns an array of Tiles, or null if the layer given was invalid. - */ - createFromTiles: function (indexes, replacements, spriteConfig, scene, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, layer); - }, - - /** - * Creates a new StaticTilemapLayer that renders the LayerData associated with the given - * `layerID`. The currently selected layer in the map is set to this new layer. - * - * The `layerID` is important. If you've created your map in Tiled then you can get this by - * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and - * look at the layers[].name value. Either way it must match. - * - * It's important to remember that a static layer cannot be modified. See StaticTilemapLayer for - * more information. - * - * @method Phaser.Tilemaps.Tilemap#createStaticLayer - * @since 3.0.0 - * - * @param {(integer|string)} layerID - The layer array index value, or if a string is given, the layer name from Tiled. - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param {number} [x=0] - The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. - * @param {number} [y=0] - The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. - * - * @return {?Phaser.Tilemaps.StaticTilemapLayer} Returns the new layer was created, or null if it failed. - */ - createStaticLayer: function (layerID, tileset, x, y) - { - var index = this.getLayerIndex(layerID); - - if (index === null) - { - console.warn('Invalid Tilemap Layer ID: ' + layerID); - if (typeof layerID === 'string') - { - console.warn('Valid tilelayer names:\n\t' + this.getTileLayerNames().join(',\n\t')); - } - return null; - } - - var layerData = this.layers[index]; - - // Check for an associated static or dynamic tilemap layer - if (layerData.tilemapLayer) - { - console.warn('Tilemap Layer ID already exists:' + layerID); - return null; - } - - this.currentLayerIndex = index; - - // Default the x/y position to match Tiled layer offset, if it exists. - if (x === undefined && this.layers[index].x) { x = this.layers[index].x; } - if (y === undefined && this.layers[index].y) { y = this.layers[index].y; } - - var layer = new StaticTilemapLayer(this.scene, this, index, tileset, x, y); - - layer.setRenderOrder(this.renderOrder); - - this.scene.sys.displayList.add(layer); - - return layer; - }, - - /** - * Removes all layer data from this Tilemap and nulls the scene reference. This will destroy any - * StaticTilemapLayers or DynamicTilemapLayers that have been linked to LayerData. - * - * @method Phaser.Tilemaps.Tilemap#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.removeAllLayers(); - this.tilesets.length = 0; - this.objects.length = 0; - this.scene = undefined; - }, - - /** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * If no layer specified, the map's current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#fill - * @since 3.0.0 - * - * @param {integer} index - The tile index to fill the area with. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - fill: function (index, tileX, tileY, width, height, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - if (this._isStaticCall(layer, 'fill')) { return this; } - - TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, layer); - - return this; - }, - - /** - * For each object in the given object layer, run the given filter callback function. Any - * objects that pass the filter test (i.e. where the callback returns true) will returned as a - * new array. Similar to Array.prototype.Filter in vanilla JS. - * - * @method Phaser.Tilemaps.Tilemap#filterObjects - * @since 3.0.0 - * - * @param {(Phaser.Tilemaps.ObjectLayer|string)} objectLayer - The name of an object layer (from Tiled) or an ObjectLayer instance. - * @param {TilemapFilterCallback} callback - The callback. Each object in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * - * @return {?Phaser.GameObjects.GameObject[]} An array of object that match the search, or null if the objectLayer given was invalid. - */ - filterObjects: function (objectLayer, callback, context) - { - if (typeof objectLayer === 'string') - { - var name = objectLayer; - - objectLayer = this.getObjectLayer(objectLayer); - - if (!objectLayer) - { - console.warn('No object layer found with the name: ' + name); - return null; - } - } - - return objectLayer.objects.filter(callback, context); - }, - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#filterTiles - * @since 3.0.0 - * - * @param {function} callback - The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. - */ - filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, layer); - }, - - /** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#findByIndex - * @since 3.0.0 - * - * @param {integer} index - The tile index value to search for. - * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. - * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tiles, or null if the layer given was invalid. - */ - findByIndex: function (findIndex, skip, reverse, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.FindByIndex(findIndex, skip, reverse, layer); - }, - - /** - * Find the first object in the given object layer that satisfies the provided testing function. - * I.e. finds the first object for which `callback` returns true. Similar to - * Array.prototype.find in vanilla JS. - * - * @method Phaser.Tilemaps.Tilemap#findObject - * @since 3.0.0 - * - * @param {(Phaser.Tilemaps.ObjectLayer|string)} objectLayer - The name of an object layer (from Tiled) or an ObjectLayer instance. - * @param {TilemapFindCallback} callback - The callback. Each object in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * - * @return {?Phaser.GameObjects.GameObject} An object that matches the search, or null if no object found. - */ - findObject: function (objectLayer, callback, context) - { - if (typeof objectLayer === 'string') - { - var name = objectLayer; - - objectLayer = this.getObjectLayer(objectLayer); - - if (!objectLayer) - { - console.warn('No object layer found with the name: ' + name); - return null; - } - } - - return objectLayer.objects.find(callback, context) || null; - }, - - /** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#findTile - * @since 3.0.0 - * - * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The Tile layer to run the search on. If not provided will use the current layer. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tiles, or null if the layer given was invalid. - */ - findTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, layer); - }, - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#forEachTile - * @since 3.0.0 - * - * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The Tile layer to run the search on. If not provided will use the current layer. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, layer); - - return this; - }, - - /** - * 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 {integer} The index of the image in this tilemap, or null if not found. - */ - getImageIndex: function (name) - { - return this.getIndex(this.images, name); - }, - - /** - * Return a list of all valid imagelayer names loaded in this Tilemap. - * - * @method Phaser.Tilemaps.Tilemap#getImageLayerNames - * @since 3.21.0 - * - * @return {string[]} Array of valid imagelayer names / IDs loaded into this Tilemap. - */ - getImageLayerNames: function () - { - if (!this.images || !Array.isArray(this.images)) - { - return []; - } - - return this.images.map(function (image) - { - return image.name; - }); - }, - - /** - * Internally used. Returns the index of the object in one of the Tilemaps arrays whose name - * property matches the given `name`. - * - * @method Phaser.Tilemaps.Tilemap#getIndex - * @since 3.0.0 - * - * @param {array} location - The Tilemap array to search. - * @param {string} name - The name of the array element to get. - * - * @return {number} The index of the element in the array, or null if not found. - */ - getIndex: function (location, name) - { - for (var i = 0; i < location.length; i++) - { - if (location[i].name === name) - { - return i; - } - } - - return null; - }, - - /** - * Gets the LayerData from this.layers that is associated with `layer`, or null if an invalid - * `layer` is given. - * - * @method Phaser.Tilemaps.Tilemap#getLayer - * @since 3.0.0 - * - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the maps current layer index. - * - * @return {Phaser.Tilemaps.LayerData} The corresponding LayerData within this.layers. - */ - getLayer: function (layer) - { - var index = this.getLayerIndex(layer); - - return (index !== null) ? this.layers[index] : null; - }, - - /** - * Gets the ObjectLayer from this.objects that has the given `name`, or null if no ObjectLayer - * is found with that name. - * - * @method Phaser.Tilemaps.Tilemap#getObjectLayer - * @since 3.0.0 - * - * @param {string} [name] - The name of the object layer from Tiled. - * - * @return {?Phaser.Tilemaps.ObjectLayer} The corresponding ObjectLayer within this.objects or null. - */ - getObjectLayer: function (name) - { - var index = this.getIndex(this.objects, name); - - return (index !== null) ? this.objects[index] : null; - }, - - /** - * Return a list of all valid objectgroup names loaded in this Tilemap. - * - * @method Phaser.Tilemaps.Tilemap#getObjectLayerNames - * @since 3.21.0 - * - * @return {string[]} Array of valid objectgroup names / IDs loaded into this Tilemap. - */ - getObjectLayerNames: function () - { - if (!this.objects || !Array.isArray(this.objects)) - { - return []; - } - - return this.objects.map(function (object) - { - return object.name; - }); - }, - - /** - * Gets the LayerData index of the given `layer` within this.layers, or null if an invalid - * `layer` is given. - * - * @method Phaser.Tilemaps.Tilemap#getLayerIndex - * @since 3.0.0 - * - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the map's current layer index. - * - * @return {integer} The LayerData index within this.layers. - */ - getLayerIndex: function (layer) - { - if (layer === undefined) - { - return this.currentLayerIndex; - } - else if (typeof layer === 'string') - { - return this.getLayerIndexByName(layer); - } - else if (typeof layer === 'number' && layer < this.layers.length) - { - return layer; - } - else if (layer instanceof StaticTilemapLayer || layer instanceof DynamicTilemapLayer) - { - return layer.layerIndex; - } - else - { - return null; - } - }, - - /** - * Gets the index of the LayerData within this.layers that has the given `name`, or null if an - * invalid `name` is given. - * - * @method Phaser.Tilemaps.Tilemap#getLayerIndexByName - * @since 3.0.0 - * - * @param {string} name - The name of the layer to get. - * - * @return {integer} The LayerData index within this.layers. - */ - getLayerIndexByName: function (name) - { - return this.getIndex(this.layers, name); - }, - - /** - * Gets a tile at the given tile coordinates from the given layer. - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#getTileAt - * @since 3.0.0 - * - * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). - * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). - * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. - */ - getTileAt: function (tileX, tileY, nonNull, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.GetTileAt(tileX, tileY, nonNull, layer); - }, - - /** - * Gets a tile at the given world coordinates from the given layer. - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#getTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - X position to get the tile from (given in pixels) - * @param {number} worldY - Y position to get the tile from (given in pixels) - * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. - */ - getTileAtWorldXY: function (worldX, worldY, nonNull, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, layer); - }, - - /** - * Return a list of all valid tilelayer names loaded in this Tilemap. - * - * @method Phaser.Tilemaps.Tilemap#getTileLayerNames - * @since 3.21.0 - * - * @return {string[]} Array of valid tilelayer names / IDs loaded into this Tilemap. - */ - getTileLayerNames: function () - { - if (!this.layers || !Array.isArray(this.layers)) - { - return []; - } - - return this.layers.map(function (layer) - { - return layer.name; - }); - }, - - /** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#getTilesWithin - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. - */ - getTilesWithin: function (tileX, tileY, width, height, filteringOptions, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); - }, - - /** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#getTilesWithinShape - * @since 3.0.0 - * - * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. - */ - getTilesWithinShape: function (shape, filteringOptions, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, layer); - }, - - /** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#getTilesWithinWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The world x coordinate for the top-left of the area. - * @param {number} worldY - The world y coordinate for the top-left of the area. - * @param {number} width - The width of the area. - * @param {number} height - The height of the area. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. - */ - getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, layer); - }, - - /** - * Gets the Tileset that has the given `name`, or null if an invalid `name` is given. - * - * @method Phaser.Tilemaps.Tilemap#getTileset - * @since 3.14.0 - * - * @param {string} name - The name of the Tileset to get. - * - * @return {?Phaser.Tilemaps.Tileset} The Tileset, or `null` if no matching named tileset was found. - */ - getTileset: function (name) - { - var index = this.getIndex(this.tilesets, name); - - return (index !== null) ? this.tilesets[index] : null; - }, - - /** - * Gets the index of the Tileset within this.tilesets that has the given `name`, or null if an - * invalid `name` is given. - * - * @method Phaser.Tilemaps.Tilemap#getTilesetIndex - * @since 3.0.0 - * - * @param {string} name - The name of the Tileset to get. - * - * @return {integer} The Tileset index within this.tilesets. - */ - getTilesetIndex: function (name) - { - return this.getIndex(this.tilesets, name); - }, - - /** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#hasTileAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?boolean} Returns a boolean, or null if the layer given was invalid. - */ - hasTileAt: function (tileX, tileY, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.HasTileAt(tileX, tileY, layer); - }, - - /** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#hasTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?boolean} Returns a boolean, or null if the layer given was invalid. - */ - hasTileAtWorldXY: function (worldX, worldY, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, layer); - }, - - /** - * The LayerData object that is currently selected in the map. You can set this property using - * any type supported by setLayer. - * - * @name Phaser.Tilemaps.Tilemap#layer - * @type {Phaser.Tilemaps.LayerData} - * @since 3.0.0 - */ - layer: { - get: function () - { - return this.layers[this.currentLayerIndex]; - }, - - set: function (layer) - { - this.setLayer(layer); - } - }, - - /** - * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index - * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified - * location. If you pass in an index, only the index at the specified location will be changed. - * Collision information will be recalculated at the specified location. - * - * If no layer specified, the maps current layer is used. - * - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#putTileAt - * @since 3.0.0 - * - * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid or the coordinates were out of bounds. - */ - putTileAt: function (tile, tileX, tileY, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'putTileAt')) { return null; } - - if (layer === null) { return null; } - - return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, layer); - }, - - /** - * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either - * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the - * specified location. If you pass in an index, only the index at the specified location will be - * changed. Collision information will be recalculated at the specified location. - * - * If no layer specified, the maps current layer is used. This - * cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#putTileAtWorldXY - * @since 3.0.0 - * - * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. - */ - putTileAtWorldXY: function (tile, worldX, worldY, recalculateFaces, camera, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'putTileAtWorldXY')) { return null; } - - if (layer === null) { return null; } - - return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, layer); - }, - - /** - * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified - * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, - * all attributes will be copied over to the specified location. If you pass in an index, only the - * index at the specified location will be changed. Collision information will be recalculated - * within the region tiles were changed. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#putTilesAt - * @since 3.0.0 - * - * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - putTilesAt: function (tilesArray, tileX, tileY, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'putTilesAt')) { return this; } - - if (layer === null) { return null; } - - TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, layer); - - return this; - }, - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then - * those will be used for randomly assigning new tile indexes. If an array is not provided, the - * indexes found within the region (excluding -1) will be used for randomly assigning new tile - * indexes. This method only modifies tile indexes and does not change collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#randomize - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - randomize: function (tileX, tileY, width, height, indexes, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'randomize')) { return this; } - - if (layer === null) { return null; } - - TilemapComponents.Randomize(tileX, tileY, width, height, indexes, layer); - - return this; - }, - - /** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#calculateFacesAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - calculateFacesAt: function (tileX, tileY, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.CalculateFacesAt(tileX, tileY, layer); - - return this; - }, - - /** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#calculateFacesWithin - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - calculateFacesWithin: function (tileX, tileY, width, height, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, layer); - - return this; - }, - - /** - * Removes the given TilemapLayer from this Tilemap without destroying it. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#removeLayer - * @since 3.17.0 - * - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to be removed. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - removeLayer: function (layer) - { - var index = this.getLayerIndex(layer); - - if (index !== null) - { - SpliceOne(this.layers, index); - for (var i = index; i < this.layers.length; i++) - { - if (this.layers[i].tilemapLayer) - { - this.layers[i].tilemapLayer.layerIndex--; - } - } - - if (this.currentLayerIndex === index) - { - this.currentLayerIndex = 0; - } - - return this; - } - else - { - return null; - } - }, - - /** - * Destroys the given TilemapLayer and removes it from this Tilemap. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#destroyLayer - * @since 3.17.0 - * - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to be destroyed. - * - * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. - */ - destroyLayer: function (layer) - { - var index = this.getLayerIndex(layer); - - if (index !== null) - { - layer = this.layers[index]; - - layer.destroy(); - - SpliceOne(this.layers, index); - - if (this.currentLayerIndex === index) - { - this.currentLayerIndex = 0; - } - - return this; - } - else - { - return null; - } - }, - - /** - * Removes all layers from this Tilemap and destroys any associated StaticTilemapLayers or - * DynamicTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#removeAllLayers - * @since 3.0.0 - * - * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. - */ - removeAllLayers: function () - { - var layers = this.layers; - - // Destroy any StaticTilemapLayers or DynamicTilemapLayers that are stored in LayerData - for (var i = 0; i < layers.length; i++) - { - if (layers[i].tilemapLayer) - { - layers[i].tilemapLayer.destroy(false); - } - } - - layers.length = 0; - - this.currentLayerIndex = 0; - - return this; - }, - - /** - * Removes the given Tile, or an array of Tiles, from the layer to which they belong, - * and optionally recalculates the collision information. - * - * This cannot be applied to Tiles that belong to Static Tilemap Layers. - * - * @method Phaser.Tilemaps.Tilemap#removeTile - * @since 3.17.0 - * - * @param {(Phaser.Tilemaps.Tile|Phaser.Tilemaps.Tile[])} tiles - The Tile to remove, or an array of Tiles. - * @param {integer} [replaceIndex=-1] - After removing the Tile, insert a brand new Tile into its location with the given index. Leave as -1 to just remove the tile. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * - * @return {Phaser.Tilemaps.Tile[]} Returns an array of Tiles that were removed. - */ - removeTile: function (tiles, replaceIndex, recalculateFaces) - { - if (replaceIndex === undefined) { replaceIndex = -1; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - var removed = []; - - if (!Array.isArray(tiles)) - { - tiles = [ tiles ]; - } - - for (var i = 0; i < tiles.length; i++) - { - var tile = tiles[i]; - - removed.push(this.removeTileAt(tile.x, tile.y, true, recalculateFaces, tile.tilemapLayer)); - - if (replaceIndex > -1) - { - this.putTileAt(replaceIndex, tile.x, tile.y, recalculateFaces, tile.tilemapLayer); - } - } - - return removed; - }, - - /** - * Removes the tile at the given tile coordinates in the specified layer and updates the layer's - * collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#removeTileAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns the Tile that was removed, or null if the layer given was invalid. - */ - removeTileAt: function (tileX, tileY, replaceWithNull, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'removeTileAt')) { return null; } - - if (layer === null) { return null; } - - return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); - }, - - /** - * Removes the tile at the given world coordinates in the specified layer and updates the layer's - * collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#removeTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. - */ - removeTileAtWorldXY: function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'removeTileAtWorldXY')) { return null; } - - if (layer === null) { return null; } - - return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, layer); - }, - - /** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#renderDebug - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. - * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - renderDebug: function (graphics, styleConfig, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.RenderDebug(graphics, styleConfig, layer); - - return this; - }, - - /** - * Draws a debug representation of all layers within this Tilemap to the given Graphics object. - * - * This is helpful when you want to get a quick idea of which of your tiles are colliding and which - * have interesting faces. The tiles are drawn starting at (0, 0) in the Graphics, allowing you to - * place the debug representation wherever you want on the screen. - * - * @method Phaser.Tilemaps.Tilemap#renderDebugFull - * @since 3.17.0 - * - * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. - * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - renderDebugFull: function (graphics, styleConfig) - { - var layers = this.layers; - - // Destroy any StaticTilemapLayers or DynamicTilemapLayers that are stored in LayerData - for (var i = 0; i < layers.length; i++) - { - TilemapComponents.RenderDebug(graphics, styleConfig, layers[i]); - } - - return this; - }, - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does - * not change collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#replaceByIndex - * @since 3.0.0 - * - * @param {integer} findIndex - The index of the tile to search for. - * @param {integer} newIndex - The index of the tile to replace it with. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - replaceByIndex: function (findIndex, newIndex, tileX, tileY, width, height, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'replaceByIndex')) { return this; } - - if (layer === null) { return null; } - - TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, layer); - - return this; - }, - - /** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setCollision - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to false if no tiles have been placed for significant performance boost. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setCollision: function (indexes, collides, recalculateFaces, layer, updateLayer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetCollision(indexes, collides, recalculateFaces, layer, updateLayer); - - return this; - }, - - /** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setCollisionBetween - * @since 3.0.0 - * - * @param {integer} start - The first index of the tile to be set for collision. - * @param {integer} stop - The last index of the tile to be set for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setCollisionBetween: function (start, stop, collides, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, layer); - - return this; - }, - - /** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setCollisionByProperty - * @since 3.0.0 - * - * @param {object} properties - An object with tile properties and corresponding values that should be checked. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setCollisionByProperty: function (properties, collides, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, layer); - - return this; - }, - - /** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setCollisionByExclusion - * @since 3.0.0 - * - * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setCollisionByExclusion: function (indexes, collides, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, layer); - - return this; - }, - - /** - * Sets collision on the tiles within a layer by checking each tile's collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tile's collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setCollisionFromCollisionGroup - * @since 3.0.0 - * - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setCollisionFromCollisionGroup: function (collides, recalculateFaces, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, layer); - - return this; - }, - - /** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setTileIndexCallback - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} callbackContext - The context under which the callback is called. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setTileIndexCallback: function (indexes, callback, callbackContext, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, layer); - - return this; - }, - - /** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#setTileLocationCallback - * @since 3.0.0 - * - * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} width - How many tiles wide from the `tileX` index the area will be. - * @param {integer} height - How many tiles tall from the `tileY` index the area will be. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} [callbackContext] - The context under which the callback is called. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, layer); - - return this; - }, - - /** - * Sets the current layer to the LayerData associated with `layer`. - * - * @method Phaser.Tilemaps.Tilemap#setLayer - * @since 3.0.0 - * - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the map's current layer index. - * - * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. - */ - setLayer: function (layer) - { - var index = this.getLayerIndex(layer); - - if (index !== null) - { - this.currentLayerIndex = index; - } - - return this; - }, - - /** - * Sets the base tile size for the map. Note: this does not necessarily match the tileWidth and - * tileHeight for all layers. This also updates the base size on all tiles across all layers. - * - * @method Phaser.Tilemaps.Tilemap#setBaseTileSize - * @since 3.0.0 - * - * @param {integer} tileWidth - The width of the tiles the map uses for calculations. - * @param {integer} tileHeight - The height of the tiles the map uses for calculations. - * - * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. - */ - setBaseTileSize: function (tileWidth, tileHeight) - { - this.tileWidth = tileWidth; - this.tileHeight = tileHeight; - this.widthInPixels = this.width * tileWidth; - this.heightInPixels = this.height * tileHeight; - - // Update the base tile size on all layers & tiles - for (var i = 0; i < this.layers.length; i++) - { - this.layers[i].baseTileWidth = tileWidth; - this.layers[i].baseTileHeight = tileHeight; - - var mapData = this.layers[i].data; - var mapWidth = this.layers[i].width; - var mapHeight = this.layers[i].height; - - for (var row = 0; row < mapHeight; row++) - { - for (var col = 0; col < mapWidth; col++) - { - var tile = mapData[row][col]; - - if (tile !== null) - { - tile.setSize(undefined, undefined, tileWidth, tileHeight); - } - } - } - } - - return this; - }, - - /** - * Sets the tile size for a specific `layer`. Note: this does not necessarily match the map's - * tileWidth and tileHeight for all layers. This will set the tile size for the layer and any - * tiles the layer has. - * - * @method Phaser.Tilemaps.Tilemap#setLayerTileSize - * @since 3.0.0 - * - * @param {integer} tileWidth - The width of the tiles (in pixels) in the layer. - * @param {integer} tileHeight - The height of the tiles (in pixels) in the layer. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the map's current layer index. - * - * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. - */ - setLayerTileSize: function (tileWidth, tileHeight, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return this; } - - layer.tileWidth = tileWidth; - layer.tileHeight = tileHeight; - - var mapData = layer.data; - var mapWidth = layer.width; - var mapHeight = layer.height; - - for (var row = 0; row < mapHeight; row++) - { - for (var col = 0; col < mapWidth; col++) - { - var tile = mapData[row][col]; - - if (tile !== null) - { - tile.setSize(tileWidth, tileHeight); - } - } - } - - return this; - }, - - /** - * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given - * layer. It will only randomize the tiles in that area, so if they're all the same nothing will - * appear to have changed! This method only modifies tile indexes and does not change collision - * information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#shuffle - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - shuffle: function (tileX, tileY, width, height, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'shuffle')) { return this; } - - if (layer === null) { return null; } - - TilemapComponents.Shuffle(tileX, tileY, width, height, layer); - - return this; - }, - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision - * information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#swapByIndex - * @since 3.0.0 - * - * @param {integer} tileA - First tile index. - * @param {integer} tileB - Second tile index. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - swapByIndex: function (indexA, indexB, tileX, tileY, width, height, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'swapByIndex')) { return this; } - - if (layer === null) { return null; } - - TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, layer); - - return this; - }, - - /** - * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#tileToWorldX - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?number} Returns a number, or null if the layer given was invalid. - */ - tileToWorldX: function (tileX, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return this.TileToWorldX(tileX, camera, layer); - }, - - /** - * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#tileToWorldY - * @since 3.0.0 - * - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer - * to use. If not given the current layer is used. - * - * @return {?number} Returns a number, or null if the layer given was invalid. - */ - tileToWorldY: function (tileX, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return this.TileToWorldY(tileX, camera, layer); - }, - - /** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#tileToWorldXY - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. - */ - - tileToWorldXY: function (tileX, tileY, point, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return this.TileToWorldXY(tileX, tileY, point, camera, layer); - }, - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. New indexes are drawn from the given - * weightedIndexes array. An example weighted array: - * - * [ - * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 - * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 - * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 - * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 - * ] - * - * The probability of any index being choose is (the index's weight) / (sum of all weights). This - * method only modifies tile indexes and does not change collision information. - * - * If no layer specified, the map's current layer is used. This - * cannot be applied to StaticTilemapLayers. - * - * @method Phaser.Tilemaps.Tilemap#weightedRandomize - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during - * randomization. They should be in the form: { index: 0, weight: 4 } or - * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - weightedRandomize: function (tileX, tileY, width, height, weightedIndexes, layer) - { - layer = this.getLayer(layer); - - if (this._isStaticCall(layer, 'weightedRandomize')) { return this; } - - if (layer === null) { return null; } - - TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, layer); - - return this; - }, - - /** - * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#worldToTileX - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer - * to use. If not given the current layer is used. - * - * @return {?number} Returns a number, or null if the layer given was invalid. - */ - worldToTileX: function (worldX, snapToFloor, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return this.WorldToTileX(worldX, snapToFloor, camera, layer); - }, - - /** - * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#worldToTileY - * @since 3.0.0 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?number} Returns a number, or null if the layer given was invalid. - */ - worldToTileY: function (worldY, snapToFloor, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return this.WorldToTileY(worldY, snapToFloor, camera, layer); - }, - - /** - * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * If no layer specified, the maps current layer is used. - * - * @method Phaser.Tilemaps.Tilemap#worldToTileXY - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. - * - * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. - */ - worldToTileXY: function (worldX, worldY, snapToFloor, point, camera, layer) - { - layer = this.getLayer(layer); - - if (layer === null) { return null; } - - return this.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); - }, - - /** - * Used internally to check if a layer is static and prints out a warning. - * - * @method Phaser.Tilemaps.Tilemap#_isStaticCall - * @private - * @since 3.0.0 - * - * @return {boolean} - */ - _isStaticCall: function (layer, functionName) - { - if (layer.tilemapLayer instanceof StaticTilemapLayer) - { - console.warn(functionName + ': You cannot change the tiles in a static tilemap layer'); - return true; - } - else - { - return false; - } - } - -}); - -module.exports = Tilemap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var DegToRad = require('../math/DegToRad'); +var DynamicTilemapLayer = require('./dynamiclayer/DynamicTilemapLayer'); +var Extend = require('../utils/object/Extend'); +var Formats = require('./Formats'); +var LayerData = require('./mapdata/LayerData'); +var Rotate = require('../math/Rotate'); +var SpliceOne = require('../utils/array/SpliceOne'); +var StaticTilemapLayer = require('./staticlayer/StaticTilemapLayer'); +var Tile = require('./Tile'); +var TilemapComponents = require('./components'); +var Tileset = require('./Tileset'); + +/** + * @callback TilemapFilterCallback + * + * @param {Phaser.GameObjects.GameObject} value - An object found in the filtered area. + * @param {number} index - The index of the object within the array. + * @param {Phaser.GameObjects.GameObject[]} array - An array of all the objects found. + * + * @return {Phaser.GameObjects.GameObject} The object. + */ + +/** + * @callback TilemapFindCallback + * + * @param {Phaser.GameObjects.GameObject} value - An object found. + * @param {number} index - The index of the object within the array. + * @param {Phaser.GameObjects.GameObject[]} array - An array of all the objects found. + * + * @return {boolean} `true` if the callback should be invoked, otherwise `false`. + */ + +/** + * @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 (StaticTilemapLayer or DynamicTilemapLayer), which are the display + * objects that actually render tiles. + * + * The Tilemap data 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 + * + * A Tilemap has handy methods for getting & manipulating the tiles within a layer. You can only + * use the methods that change tiles (e.g. removeTileAt) on a DynamicTilemapLayer. + * + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a + * StaticTilemapLayer or DynamicTilemapLayer may have its own unique tile size that overrides + * it. + * + * As of Phaser 3.21.0, if your tilemap includes layer groups (a feature of Tiled 1.2.0+) these + * will be traversed and the following properties will affect 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'. + * + * @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. + */ +var Tilemap = new Class({ + + initialize: + + function Tilemap (scene, mapData) + { + /** + * @name Phaser.Tilemaps.Tilemap#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The base width of a tile in pixels. Note that individual layers may have a different tile + * width. + * + * @name Phaser.Tilemaps.Tilemap#tileWidth + * @type {integer} + * @since 3.0.0 + */ + this.tileWidth = mapData.tileWidth; + + /** + * The base height of a tile in pixels. Note that individual layers may have a different + * tile height. + * + * @name Phaser.Tilemaps.Tilemap#tileHeight + * @type {integer} + * @since 3.0.0 + */ + this.tileHeight = mapData.tileHeight; + + /** + * The width of the map (in tiles). + * + * @name Phaser.Tilemaps.Tilemap#width + * @type {number} + * @since 3.0.0 + */ + this.width = mapData.width; + + /** + * The height of the map (in tiles). + * + * @name Phaser.Tilemaps.Tilemap#height + * @type {number} + * @since 3.0.0 + */ + this.height = mapData.height; + + /** + * The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + * + * @name Phaser.Tilemaps.Tilemap#orientation + * @type {string} + * @since 3.0.0 + */ + this.orientation = mapData.orientation; + + /** + * The render (draw) order of the map data (as specified in Tiled), usually 'right-down'. + * + * The draw orders are: + * + * right-down + * left-down + * right-up + * left-up + * + * This can be changed via the `setRenderOrder` method. + * + * @name Phaser.Tilemaps.Tilemap#renderOrder + * @type {string} + * @since 3.12.0 + */ + this.renderOrder = mapData.renderOrder; + + /** + * The format of the map data. + * + * @name Phaser.Tilemaps.Tilemap#format + * @type {number} + * @since 3.0.0 + */ + this.format = mapData.format; + + /** + * The version of the map data (as specified in Tiled, usually 1). + * + * @name Phaser.Tilemaps.Tilemap#version + * @type {number} + * @since 3.0.0 + */ + this.version = mapData.version; + + /** + * Map specific properties as specified in Tiled. + * + * @name Phaser.Tilemaps.Tilemap#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = mapData.properties; + + /** + * The width of the map in pixels based on width * tileWidth. + * + * @name Phaser.Tilemaps.Tilemap#widthInPixels + * @type {number} + * @since 3.0.0 + */ + this.widthInPixels = mapData.widthInPixels; + + /** + * The height of the map in pixels based on height * tileHeight. + * + * @name Phaser.Tilemaps.Tilemap#heightInPixels + * @type {number} + * @since 3.0.0 + */ + this.heightInPixels = mapData.heightInPixels; + + /** + * + * @name Phaser.Tilemaps.Tilemap#imageCollections + * @type {Phaser.Tilemaps.ImageCollection[]} + * @since 3.0.0 + */ + this.imageCollections = mapData.imageCollections; + + /** + * An array of Tiled Image Layers. + * + * @name Phaser.Tilemaps.Tilemap#images + * @type {array} + * @since 3.0.0 + */ + this.images = mapData.images; + + /** + * An array of Tilemap layer data. + * + * @name Phaser.Tilemaps.Tilemap#layers + * @type {Phaser.Tilemaps.LayerData[]} + * @since 3.0.0 + */ + this.layers = mapData.layers; + + /** + * An array of Tilesets used in the map. + * + * @name Phaser.Tilemaps.Tilemap#tilesets + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tilesets = mapData.tilesets; + + /** + * An array of ObjectLayer instances parsed from Tiled object layers. + * + * @name Phaser.Tilemaps.Tilemap#objects + * @type {Phaser.Tilemaps.ObjectLayer[]} + * @since 3.0.0 + */ + this.objects = mapData.objects; + + /** + * The index of the currently selected LayerData object. + * + * @name Phaser.Tilemaps.Tilemap#currentLayerIndex + * @type {integer} + * @since 3.0.0 + */ + this.currentLayerIndex = 0; + + /** + * Optional : Only for hexagonal tilemaps. + * The length of the horizontal sides of the hexagon. + * @name Phaser.Tilemaps.MapData#tiles + * @type {integer} + * @since 3.0.0 + */ + this.hexSideLength = mapData.hexSideLength; + + /** + * Components used for conversions between real world coordinates and tile coordinates, + * initialized here to prevent switching between them at runtime depending on map orientation. + * refer to the components themselves for documentation. + * @since 3.2.2 + */ + this.WorldToTileXY = TilemapComponents.WorldToTileXY(this.orientation); + this.WorldToTileX = TilemapComponents.WorldToTileX(this.orientation); + this.WorldToTileY = TilemapComponents.WorldToTileY(this.orientation); + this.TileToWorldXY = TilemapComponents.TileToWorldXY(this.orientation); + this.TileToWorldX = TilemapComponents.TileToWorldX(this.orientation); + this.TileToWorldY = TilemapComponents.TileToWorldY(this.orientation); + }, + + /** + * Sets the rendering (draw) order of the tiles in this map. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * Calling this method _after_ creating Static or Dynamic Tilemap Layers will **not** automatically + * update them to use the new render order. If you call this method after creating layers, use their + * own `setRenderOrder` methods to change them as needed. + * + * @method Phaser.Tilemaps.Tilemap#setRenderOrder + * @since 3.12.0 + * + * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + * + * @return {this} This Tilemap object. + */ + setRenderOrder: function (renderOrder) + { + var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; + + if (typeof renderOrder === 'number') + { + renderOrder = orders[renderOrder]; + } + + if (orders.indexOf(renderOrder) > -1) + { + this.renderOrder = renderOrder; + } + + return this; + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled + * editor. + * + * @method Phaser.Tilemaps.Tilemap#addTilesetImage + * @since 3.0.0 + * + * @param {string} tilesetName - The name of the tileset as specified in the map data. + * @param {string} [key] - The key of the Phaser.Cache image used for this tileset. If + * `undefined` or `null` it will look for an image with a key matching the tilesetName parameter. + * @param {integer} [tileWidth] - The width of the tile (in pixels) in the Tileset Image. If not + * given it will default to the map's tileWidth value, or the tileWidth specified in the Tiled + * JSON file. + * @param {integer} [tileHeight] - The height of the tiles (in pixels) in the Tileset Image. If + * not given it will default to the map's tileHeight value, or the tileHeight specified in the + * Tiled JSON file. + * @param {integer} [tileMargin] - The margin around the tiles in the sheet (in pixels). If not + * specified, it will default to 0 or the value specified in the Tiled JSON file. + * @param {integer} [tileSpacing] - The spacing between each the tile in the sheet (in pixels). + * If not specified, it will default to 0 or the value specified in the Tiled JSON file. + * @param {integer} [gid=0] - If adding multiple tilesets to a blank map, specify the starting + * GID this set will use here. + * + * @return {?Phaser.Tilemaps.Tileset} Returns the Tileset object that was created or updated, or null if it + * failed. + */ + addTilesetImage: function (tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) + { + if (tilesetName === undefined) { return null; } + if (key === undefined || key === null) { key = tilesetName; } + + if (!this.scene.sys.textures.exists(key)) + { + console.warn('Invalid Tileset Image: ' + key); + return null; + } + + var texture = this.scene.sys.textures.get(key); + + var index = this.getTilesetIndex(tilesetName); + + if (index === null && this.format === Formats.TILED_JSON) + { + console.warn('No data found for Tileset: ' + tilesetName); + return null; + } + + var tileset = this.tilesets[index]; + + if (tileset) + { + tileset.setTileSize(tileWidth, tileHeight); + tileset.setSpacing(tileMargin, tileSpacing); + tileset.setImage(texture); + + return tileset; + } + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + tileset = new Tileset(tilesetName, gid, tileWidth, tileHeight, tileMargin, tileSpacing); + + tileset.setImage(texture); + + this.tilesets.push(tileset); + + return tileset; + }, + + /** + * Turns the DynamicTilemapLayer associated with the given layer into a StaticTilemapLayer. If + * no layer specified, the map's current layer is used. This is useful if you want to manipulate + * a map at the start of a scene, but then make it non-manipulable and optimize it for speed. + * Note: the DynamicTilemapLayer passed in is destroyed, so make sure to store the value + * returned from this method if you want to manipulate the new StaticTilemapLayer. + * + * @method Phaser.Tilemaps.Tilemap#convertLayerToStatic + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer)} [layer] - The name of the layer from Tiled, the + * index of the layer in the map, or a DynamicTilemapLayer. + * + * @return {?Phaser.Tilemaps.StaticTilemapLayer} Returns the new layer that was created, or null if it + * failed. + */ + convertLayerToStatic: function (layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + var dynamicLayer = layer.tilemapLayer; + + if (!dynamicLayer || !(dynamicLayer instanceof DynamicTilemapLayer)) + { + return null; + } + + var staticLayer = new StaticTilemapLayer( + dynamicLayer.scene, + dynamicLayer.tilemap, + dynamicLayer.layerIndex, + dynamicLayer.tileset, + dynamicLayer.x, + dynamicLayer.y + ); + + this.scene.sys.displayList.add(staticLayer); + + dynamicLayer.destroy(); + + return staticLayer; + }, + + /** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * If no layer specified, the map's current layer is used. This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#copy + * @since 3.0.0 + * + * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} width - The width of the area to copy, in tiles, not pixels. + * @param {integer} height - The height of the area to copy, in tiles, not pixels. + * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. + * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + copy: function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'copy')) { return this; } + + if (layer !== null) + { + TilemapComponents.Copy( + srcTileX, srcTileY, + width, height, + destTileX, destTileY, + recalculateFaces, layer + ); + + return this; + } + else + { + return null; + } + }, + + /** + * Creates a new and empty DynamicTilemapLayer. The currently selected layer in the map is set to this new layer. + * + * @method Phaser.Tilemaps.Tilemap#createBlankDynamicLayer + * @since 3.0.0 + * + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The world x position where the top left of this layer will be placed. + * @param {number} [y=0] - The world y position where the top left of this layer will be placed. + * @param {integer} [width] - The width of the layer in tiles. If not specified, it will default to the map's width. + * @param {integer} [height] - The height of the layer in tiles. If not specified, it will default to the map's height. + * @param {integer} [tileWidth] - The width of the tiles the layer uses for calculations. If not specified, it will default to the map's tileWidth. + * @param {integer} [tileHeight] - The height of the tiles the layer uses for calculations. If not specified, it will default to the map's tileHeight. + * + * @return {?Phaser.Tilemaps.DynamicTilemapLayer} Returns the new layer that was created, or `null` if it failed. + */ + createBlankDynamicLayer: function (name, tileset, x, y, width, height, tileWidth, tileHeight) + { + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + var index = this.getLayerIndex(name); + + if (index !== null) + { + console.warn('Invalid Tilemap Layer ID: ' + name); + return null; + } + + var layerData = new LayerData({ + name: name, + tileWidth: tileWidth, + tileHeight: tileHeight, + width: width, + height: height, + orientation: this.orientation + }); + + var row; + + for (var tileY = 0; tileY < height; tileY++) + { + row = []; + + for (var tileX = 0; tileX < width; tileX++) + { + row.push(new Tile(layerData, -1, tileX, tileY, tileWidth, tileHeight, this.tileWidth, this.tileHeight)); + } + + layerData.data.push(row); + } + + this.layers.push(layerData); + + this.currentLayerIndex = this.layers.length - 1; + + var dynamicLayer = new DynamicTilemapLayer(this.scene, this, this.currentLayerIndex, tileset, x, y); + + dynamicLayer.setRenderOrder(this.renderOrder); + + this.scene.sys.displayList.add(dynamicLayer); + + return dynamicLayer; + }, + + /** + * Creates a new DynamicTilemapLayer that renders the LayerData associated with the given + * `layerID`. The currently selected layer in the map is set to this new layer. + * + * The `layerID` is important. If you've created your map in Tiled then you can get this by + * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and + * look at the layers[].name value. Either way it must match. + * + * Unlike a static layer, a dynamic layer can be modified. See DynamicTilemapLayer for more + * information. + * + * @method Phaser.Tilemaps.Tilemap#createDynamicLayer + * @since 3.0.0 + * + * @param {(integer|string)} layerID - The layer array index value, or if a string is given, the layer name from Tiled. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * @param {number} [y=0] - The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * + * @return {?Phaser.Tilemaps.DynamicTilemapLayer} Returns the new layer was created, or null if it failed. + */ + createDynamicLayer: function (layerID, tileset, x, y) + { + var index = this.getLayerIndex(layerID); + + if (index === null) + { + console.warn('Invalid Tilemap Layer ID: ' + layerID); + + if (typeof layerID === 'string') + { + console.warn('Valid tilelayer names:\n\t' + this.getTileLayerNames().join(',\n\t')); + } + + return null; + } + + var layerData = this.layers[index]; + + // Check for an associated static or dynamic tilemap layer + if (layerData.tilemapLayer) + { + console.warn('Tilemap Layer ID already exists:' + layerID); + return null; + } + + this.currentLayerIndex = index; + + // Default the x/y position to match Tiled layer offset, if it exists. + + if (x === undefined) + { + x = layerData.x; + } + + if (y === undefined) + { + y = layerData.y; + } + + var layer = new DynamicTilemapLayer(this.scene, this, index, tileset, x, y); + + layer.setRenderOrder(this.renderOrder); + + this.scene.sys.displayList.add(layer); + + return layer; + }, + + /** + * Creates a Sprite for every object matching the given gid in the map data. All properties from + * the map data objectgroup are copied into the `spriteConfig`, so you can use this as an easy + * way to configure Sprite properties from within the map editor. For example giving an object a + * property of alpha: 0.5 in the map editor will duplicate that when the Sprite is created. + * + * Custom object properties not sharing names with the Sprite's own properties are copied to the + * Sprite's {@link Phaser.GameObjects.Sprite#data data store}. + * + * @method Phaser.Tilemaps.Tilemap#createFromObjects + * @since 3.0.0 + * + * @param {string} name - The name of the object layer (from Tiled) to create Sprites from. + * @param {(integer|string)} id - Either the id (object), gid (tile object) or name (object or + * tile object) from Tiled. Ids are unique in Tiled, but a gid is shared by all tile objects + * with the same graphic. The same name can be used on multiple objects. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param {Phaser.Scene} [scene=the scene the map is within] - The Scene to create the Sprites within. + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ + createFromObjects: function (name, id, spriteConfig, scene) + { + if (spriteConfig === undefined) { spriteConfig = {}; } + if (scene === undefined) { scene = this.scene; } + + var objectLayer = this.getObjectLayer(name); + + if (!objectLayer) + { + console.warn('Cannot create from object. Invalid objectgroup name given: ' + name); + + if (typeof layerID === 'string') + { + console.warn('Valid objectgroup names:\n\t' + this.getObjectLayerNames().join(',\n\t')); + } + + return null; + } + + var objects = objectLayer.objects; + var sprites = []; + + for (var i = 0; i < objects.length; i++) + { + var found = false; + var obj = objects[i]; + + if (obj.gid !== undefined && typeof id === 'number' && obj.gid === id || + obj.id !== undefined && typeof id === 'number' && obj.id === id || + obj.name !== undefined && typeof id === 'string' && obj.name === id) + { + found = true; + } + + if (found) + { + var config = Extend({}, spriteConfig, obj.properties); + + config.x = obj.x; + config.y = obj.y; + + var sprite = scene.make.sprite(config); + + sprite.name = obj.name; + + if (obj.width) { sprite.displayWidth = obj.width; } + if (obj.height) { sprite.displayHeight = obj.height; } + + // Origin is (0, 1) in Tiled, so find the offset that matches the Sprite's origin. + var offset = { + x: sprite.originX * sprite.displayWidth, + y: (sprite.originY - 1) * sprite.displayHeight + }; + + // If the object is rotated, then the origin offset also needs to be rotated. + if (obj.rotation) + { + var angle = DegToRad(obj.rotation); + Rotate(offset, angle); + sprite.rotation = angle; + } + + sprite.x += offset.x; + sprite.y += offset.y; + + if (obj.flippedHorizontal !== undefined || obj.flippedVertical !== undefined) + { + sprite.setFlip(obj.flippedHorizontal, obj.flippedVertical); + } + + if (!obj.visible) { sprite.visible = false; } + + for (var key in obj.properties) + { + if (sprite.hasOwnProperty(key)) + { + continue; + } + + sprite.setData(key, obj.properties[key]); + } + + sprites.push(sprite); + } + } + + return sprites; + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemaps.Tilemap#createFromTiles + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.GameObjects.Sprite[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + createFromTiles: function (indexes, replacements, spriteConfig, scene, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, layer); + }, + + /** + * Creates a new StaticTilemapLayer that renders the LayerData associated with the given + * `layerID`. The currently selected layer in the map is set to this new layer. + * + * The `layerID` is important. If you've created your map in Tiled then you can get this by + * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and + * look at the layers[].name value. Either way it must match. + * + * It's important to remember that a static layer cannot be modified. See StaticTilemapLayer for + * more information. + * + * @method Phaser.Tilemaps.Tilemap#createStaticLayer + * @since 3.0.0 + * + * @param {(integer|string)} layerID - The layer array index value, or if a string is given, the layer name from Tiled. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * @param {number} [y=0] - The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. + * + * @return {?Phaser.Tilemaps.StaticTilemapLayer} Returns the new layer was created, or null if it failed. + */ + createStaticLayer: function (layerID, tileset, x, y) + { + var index = this.getLayerIndex(layerID); + + if (index === null) + { + console.warn('Invalid Tilemap Layer ID: ' + layerID); + if (typeof layerID === 'string') + { + console.warn('Valid tilelayer names:\n\t' + this.getTileLayerNames().join(',\n\t')); + } + return null; + } + + var layerData = this.layers[index]; + + // Check for an associated static or dynamic tilemap layer + if (layerData.tilemapLayer) + { + console.warn('Tilemap Layer ID already exists:' + layerID); + return null; + } + + this.currentLayerIndex = index; + + // Default the x/y position to match Tiled layer offset, if it exists. + if (x === undefined && this.layers[index].x) { x = this.layers[index].x; } + if (y === undefined && this.layers[index].y) { y = this.layers[index].y; } + + var layer = new StaticTilemapLayer(this.scene, this, index, tileset, x, y); + + layer.setRenderOrder(this.renderOrder); + + this.scene.sys.displayList.add(layer); + + return layer; + }, + + /** + * Removes all layer data from this Tilemap and nulls the scene reference. This will destroy any + * StaticTilemapLayers or DynamicTilemapLayers that have been linked to LayerData. + * + * @method Phaser.Tilemaps.Tilemap#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.removeAllLayers(); + this.tilesets.length = 0; + this.objects.length = 0; + this.scene = undefined; + }, + + /** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * If no layer specified, the map's current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#fill + * @since 3.0.0 + * + * @param {integer} index - The tile index to fill the area with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + fill: function (index, tileX, tileY, width, height, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + if (this._isStaticCall(layer, 'fill')) { return this; } + + TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, layer); + + return this; + }, + + /** + * For each object in the given object layer, run the given filter callback function. Any + * objects that pass the filter test (i.e. where the callback returns true) will returned as a + * new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @method Phaser.Tilemaps.Tilemap#filterObjects + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.ObjectLayer|string)} objectLayer - The name of an object layer (from Tiled) or an ObjectLayer instance. + * @param {TilemapFilterCallback} callback - The callback. Each object in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * + * @return {?Phaser.GameObjects.GameObject[]} An array of object that match the search, or null if the objectLayer given was invalid. + */ + filterObjects: function (objectLayer, callback, context) + { + if (typeof objectLayer === 'string') + { + var name = objectLayer; + + objectLayer = this.getObjectLayer(objectLayer); + + if (!objectLayer) + { + console.warn('No object layer found with the name: ' + name); + return null; + } + } + + return objectLayer.objects.filter(callback, context); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#filterTiles + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, layer); + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#findByIndex + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tiles, or null if the layer given was invalid. + */ + findByIndex: function (findIndex, skip, reverse, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.FindByIndex(findIndex, skip, reverse, layer); + }, + + /** + * Find the first object in the given object layer that satisfies the provided testing function. + * I.e. finds the first object for which `callback` returns true. Similar to + * Array.prototype.find in vanilla JS. + * + * @method Phaser.Tilemaps.Tilemap#findObject + * @since 3.0.0 + * + * @param {(Phaser.Tilemaps.ObjectLayer|string)} objectLayer - The name of an object layer (from Tiled) or an ObjectLayer instance. + * @param {TilemapFindCallback} callback - The callback. Each object in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * + * @return {?Phaser.GameObjects.GameObject} An object that matches the search, or null if no object found. + */ + findObject: function (objectLayer, callback, context) + { + if (typeof objectLayer === 'string') + { + var name = objectLayer; + + objectLayer = this.getObjectLayer(objectLayer); + + if (!objectLayer) + { + console.warn('No object layer found with the name: ' + name); + return null; + } + } + + return objectLayer.objects.find(callback, context) || null; + }, + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#findTile + * @since 3.0.0 + * + * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The Tile layer to run the search on. If not provided will use the current layer. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tiles, or null if the layer given was invalid. + */ + findTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#forEachTile + * @since 3.0.0 + * + * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The Tile layer to run the search on. If not provided will use the current layer. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, layer); + + return this; + }, + + /** + * 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 {integer} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) + { + return this.getIndex(this.images, name); + }, + + /** + * Return a list of all valid imagelayer names loaded in this Tilemap. + * + * @method Phaser.Tilemaps.Tilemap#getImageLayerNames + * @since 3.21.0 + * + * @return {string[]} Array of valid imagelayer names / IDs loaded into this Tilemap. + */ + getImageLayerNames: function () + { + if (!this.images || !Array.isArray(this.images)) + { + return []; + } + + return this.images.map(function (image) + { + return image.name; + }); + }, + + /** + * Internally used. Returns the index of the object in one of the Tilemaps arrays whose name + * property matches the given `name`. + * + * @method Phaser.Tilemaps.Tilemap#getIndex + * @since 3.0.0 + * + * @param {array} location - The Tilemap array to search. + * @param {string} name - The name of the array element to get. + * + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) + { + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + }, + + /** + * Gets the LayerData from this.layers that is associated with `layer`, or null if an invalid + * `layer` is given. + * + * @method Phaser.Tilemaps.Tilemap#getLayer + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the maps current layer index. + * + * @return {Phaser.Tilemaps.LayerData} The corresponding LayerData within this.layers. + */ + getLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + return (index !== null) ? this.layers[index] : null; + }, + + /** + * Gets the ObjectLayer from this.objects that has the given `name`, or null if no ObjectLayer + * is found with that name. + * + * @method Phaser.Tilemaps.Tilemap#getObjectLayer + * @since 3.0.0 + * + * @param {string} [name] - The name of the object layer from Tiled. + * + * @return {?Phaser.Tilemaps.ObjectLayer} The corresponding ObjectLayer within this.objects or null. + */ + getObjectLayer: function (name) + { + var index = this.getIndex(this.objects, name); + + return (index !== null) ? this.objects[index] : null; + }, + + /** + * Return a list of all valid objectgroup names loaded in this Tilemap. + * + * @method Phaser.Tilemaps.Tilemap#getObjectLayerNames + * @since 3.21.0 + * + * @return {string[]} Array of valid objectgroup names / IDs loaded into this Tilemap. + */ + getObjectLayerNames: function () + { + if (!this.objects || !Array.isArray(this.objects)) + { + return []; + } + + return this.objects.map(function (object) + { + return object.name; + }); + }, + + /** + * Gets the LayerData index of the given `layer` within this.layers, or null if an invalid + * `layer` is given. + * + * @method Phaser.Tilemaps.Tilemap#getLayerIndex + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + * + * @return {integer} The LayerData index within this.layers. + */ + getLayerIndex: function (layer) + { + if (layer === undefined) + { + return this.currentLayerIndex; + } + else if (typeof layer === 'string') + { + return this.getLayerIndexByName(layer); + } + else if (typeof layer === 'number' && layer < this.layers.length) + { + return layer; + } + else if (layer instanceof StaticTilemapLayer || layer instanceof DynamicTilemapLayer) + { + return layer.layerIndex; + } + else + { + return null; + } + }, + + /** + * Gets the index of the LayerData within this.layers that has the given `name`, or null if an + * invalid `name` is given. + * + * @method Phaser.Tilemaps.Tilemap#getLayerIndexByName + * @since 3.0.0 + * + * @param {string} name - The name of the layer to get. + * + * @return {integer} The LayerData index within this.layers. + */ + getLayerIndexByName: function (name) + { + return this.getIndex(this.layers, name); + }, + + /** + * Gets a tile at the given tile coordinates from the given layer. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + getTileAt: function (tileX, tileY, nonNull, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTileAt(tileX, tileY, nonNull, layer); + }, + + /** + * Gets a tile at the given world coordinates from the given layer. + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + getTileAtWorldXY: function (worldX, worldY, nonNull, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, layer); + }, + + /** + * Return a list of all valid tilelayer names loaded in this Tilemap. + * + * @method Phaser.Tilemaps.Tilemap#getTileLayerNames + * @since 3.21.0 + * + * @return {string[]} Array of valid tilelayer names / IDs loaded into this Tilemap. + */ + getTileLayerNames: function () + { + if (!this.layers || !Array.isArray(this.layers)) + { + return []; + } + + return this.layers.map(function (layer) + { + return layer.name; + }); + }, + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTilesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + getTilesWithin: function (tileX, tileY, width, height, filteringOptions, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + }, + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTilesWithinShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + getTilesWithinShape: function (shape, filteringOptions, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, layer); + }, + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#getTilesWithinWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The world x coordinate for the top-left of the area. + * @param {number} worldY - The world y coordinate for the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile[]} Returns an array of Tiles, or null if the layer given was invalid. + */ + getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, layer); + }, + + /** + * Gets the Tileset that has the given `name`, or null if an invalid `name` is given. + * + * @method Phaser.Tilemaps.Tilemap#getTileset + * @since 3.14.0 + * + * @param {string} name - The name of the Tileset to get. + * + * @return {?Phaser.Tilemaps.Tileset} The Tileset, or `null` if no matching named tileset was found. + */ + getTileset: function (name) + { + var index = this.getIndex(this.tilesets, name); + + return (index !== null) ? this.tilesets[index] : null; + }, + + /** + * Gets the index of the Tileset within this.tilesets that has the given `name`, or null if an + * invalid `name` is given. + * + * @method Phaser.Tilemaps.Tilemap#getTilesetIndex + * @since 3.0.0 + * + * @param {string} name - The name of the Tileset to get. + * + * @return {integer} The Tileset index within this.tilesets. + */ + getTilesetIndex: function (name) + { + return this.getIndex(this.tilesets, name); + }, + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#hasTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ + hasTileAt: function (tileX, tileY, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.HasTileAt(tileX, tileY, layer); + }, + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#hasTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ + hasTileAtWorldXY: function (worldX, worldY, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, layer); + }, + + /** + * The LayerData object that is currently selected in the map. You can set this property using + * any type supported by setLayer. + * + * @name Phaser.Tilemaps.Tilemap#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + layer: { + get: function () + { + return this.layers[this.currentLayerIndex]; + }, + + set: function (layer) + { + this.setLayer(layer); + } + }, + + /** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * If no layer specified, the maps current layer is used. + * + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#putTileAt + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid or the coordinates were out of bounds. + */ + putTileAt: function (tile, tileX, tileY, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'putTileAt')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, layer); + }, + + /** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * If no layer specified, the maps current layer is used. This + * cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#putTileAtWorldXY + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + putTileAtWorldXY: function (tile, worldX, worldY, recalculateFaces, camera, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'putTileAtWorldXY')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, layer); + }, + + /** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#putTilesAt + * @since 3.0.0 + * + * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + putTilesAt: function (tilesArray, tileX, tileY, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'putTilesAt')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, layer); + + return this; + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#randomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + randomize: function (tileX, tileY, width, height, indexes, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'randomize')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.Randomize(tileX, tileY, width, height, indexes, layer); + + return this; + }, + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#calculateFacesAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + calculateFacesAt: function (tileX, tileY, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.CalculateFacesAt(tileX, tileY, layer); + + return this; + }, + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#calculateFacesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + calculateFacesWithin: function (tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Removes the given TilemapLayer from this Tilemap without destroying it. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#removeLayer + * @since 3.17.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to be removed. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + removeLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + if (index !== null) + { + SpliceOne(this.layers, index); + for (var i = index; i < this.layers.length; i++) + { + if (this.layers[i].tilemapLayer) + { + this.layers[i].tilemapLayer.layerIndex--; + } + } + + if (this.currentLayerIndex === index) + { + this.currentLayerIndex = 0; + } + + return this; + } + else + { + return null; + } + }, + + /** + * Destroys the given TilemapLayer and removes it from this Tilemap. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#destroyLayer + * @since 3.17.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to be destroyed. + * + * @return {?Phaser.Tilemaps.Tilemap} Returns this, or null if the layer given was invalid. + */ + destroyLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + if (index !== null) + { + layer = this.layers[index]; + + layer.destroy(); + + SpliceOne(this.layers, index); + + if (this.currentLayerIndex === index) + { + this.currentLayerIndex = 0; + } + + return this; + } + else + { + return null; + } + }, + + /** + * Removes all layers from this Tilemap and destroys any associated StaticTilemapLayers or + * DynamicTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#removeAllLayers + * @since 3.0.0 + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + removeAllLayers: function () + { + var layers = this.layers; + + // Destroy any StaticTilemapLayers or DynamicTilemapLayers that are stored in LayerData + for (var i = 0; i < layers.length; i++) + { + if (layers[i].tilemapLayer) + { + layers[i].tilemapLayer.destroy(false); + } + } + + layers.length = 0; + + this.currentLayerIndex = 0; + + return this; + }, + + /** + * Removes the given Tile, or an array of Tiles, from the layer to which they belong, + * and optionally recalculates the collision information. + * + * This cannot be applied to Tiles that belong to Static Tilemap Layers. + * + * @method Phaser.Tilemaps.Tilemap#removeTile + * @since 3.17.0 + * + * @param {(Phaser.Tilemaps.Tile|Phaser.Tilemaps.Tile[])} tiles - The Tile to remove, or an array of Tiles. + * @param {integer} [replaceIndex=-1] - After removing the Tile, insert a brand new Tile into its location with the given index. Leave as -1 to just remove the tile. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.Tile[]} Returns an array of Tiles that were removed. + */ + removeTile: function (tiles, replaceIndex, recalculateFaces) + { + if (replaceIndex === undefined) { replaceIndex = -1; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + var removed = []; + + if (!Array.isArray(tiles)) + { + tiles = [ tiles ]; + } + + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + removed.push(this.removeTileAt(tile.x, tile.y, true, recalculateFaces, tile.tilemapLayer)); + + if (replaceIndex > -1) + { + this.putTileAt(replaceIndex, tile.x, tile.y, recalculateFaces, tile.tilemapLayer); + } + } + + return removed; + }, + + /** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#removeTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns the Tile that was removed, or null if the layer given was invalid. + */ + removeTileAt: function (tileX, tileY, replaceWithNull, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'removeTileAt')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); + }, + + /** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#removeTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tile} Returns a Tile, or null if the layer given was invalid. + */ + removeTileAtWorldXY: function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'removeTileAtWorldXY')) { return null; } + + if (layer === null) { return null; } + + return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, layer); + }, + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#renderDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + renderDebug: function (graphics, styleConfig, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.RenderDebug(graphics, styleConfig, layer); + + return this; + }, + + /** + * Draws a debug representation of all layers within this Tilemap to the given Graphics object. + * + * This is helpful when you want to get a quick idea of which of your tiles are colliding and which + * have interesting faces. The tiles are drawn starting at (0, 0) in the Graphics, allowing you to + * place the debug representation wherever you want on the screen. + * + * @method Phaser.Tilemaps.Tilemap#renderDebugFull + * @since 3.17.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + renderDebugFull: function (graphics, styleConfig) + { + var layers = this.layers; + + // Destroy any StaticTilemapLayers or DynamicTilemapLayers that are stored in LayerData + for (var i = 0; i < layers.length; i++) + { + TilemapComponents.RenderDebug(graphics, styleConfig, layers[i]); + } + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#replaceByIndex + * @since 3.0.0 + * + * @param {integer} findIndex - The index of the tile to search for. + * @param {integer} newIndex - The index of the tile to replace it with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + replaceByIndex: function (findIndex, newIndex, tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'replaceByIndex')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollision + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to false if no tiles have been placed for significant performance boost. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollision: function (indexes, collides, recalculateFaces, layer, updateLayer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollision(indexes, collides, recalculateFaces, layer, updateLayer); + + return this; + }, + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionBetween + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionBetween: function (start, stop, collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionByProperty + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionByProperty: function (properties, collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionByExclusion + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionByExclusion: function (indexes, collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking each tile's collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tile's collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setCollisionFromCollisionGroup + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollisionFromCollisionGroup: function (collides, recalculateFaces, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, layer); + + return this; + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setTileIndexCallback + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, layer); + + return this; + }, + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#setTileLocationCallback + * @since 3.0.0 + * + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} [callbackContext] - The context under which the callback is called. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, layer); + + return this; + }, + + /** + * Sets the current layer to the LayerData associated with `layer`. + * + * @method Phaser.Tilemaps.Tilemap#setLayer + * @since 3.0.0 + * + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + setLayer: function (layer) + { + var index = this.getLayerIndex(layer); + + if (index !== null) + { + this.currentLayerIndex = index; + } + + return this; + }, + + /** + * Sets the base tile size for the map. Note: this does not necessarily match the tileWidth and + * tileHeight for all layers. This also updates the base size on all tiles across all layers. + * + * @method Phaser.Tilemaps.Tilemap#setBaseTileSize + * @since 3.0.0 + * + * @param {integer} tileWidth - The width of the tiles the map uses for calculations. + * @param {integer} tileHeight - The height of the tiles the map uses for calculations. + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + setBaseTileSize: function (tileWidth, tileHeight) + { + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + // Update the base tile size on all layers & tiles + for (var i = 0; i < this.layers.length; i++) + { + this.layers[i].baseTileWidth = tileWidth; + this.layers[i].baseTileHeight = tileHeight; + + var mapData = this.layers[i].data; + var mapWidth = this.layers[i].width; + var mapHeight = this.layers[i].height; + + for (var row = 0; row < mapHeight; row++) + { + for (var col = 0; col < mapWidth; col++) + { + var tile = mapData[row][col]; + + if (tile !== null) + { + tile.setSize(undefined, undefined, tileWidth, tileHeight); + } + } + } + } + + return this; + }, + + /** + * Sets the tile size for a specific `layer`. Note: this does not necessarily match the map's + * tileWidth and tileHeight for all layers. This will set the tile size for the layer and any + * tiles the layer has. + * + * @method Phaser.Tilemaps.Tilemap#setLayerTileSize + * @since 3.0.0 + * + * @param {integer} tileWidth - The width of the tiles (in pixels) in the layer. + * @param {integer} tileHeight - The height of the tiles (in pixels) in the layer. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + * + * @return {Phaser.Tilemaps.Tilemap} This Tilemap object. + */ + setLayerTileSize: function (tileWidth, tileHeight, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return this; } + + layer.tileWidth = tileWidth; + layer.tileHeight = tileHeight; + + var mapData = layer.data; + var mapWidth = layer.width; + var mapHeight = layer.height; + + for (var row = 0; row < mapHeight; row++) + { + for (var col = 0; col < mapWidth; col++) + { + var tile = mapData[row][col]; + + if (tile !== null) + { + tile.setSize(tileWidth, tileHeight); + } + } + } + + return this; + }, + + /** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#shuffle + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + shuffle: function (tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'shuffle')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.Shuffle(tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#swapByIndex + * @since 3.0.0 + * + * @param {integer} tileA - First tile index. + * @param {integer} tileB - Second tile index. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + swapByIndex: function (indexA, indexB, tileX, tileY, width, height, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'swapByIndex')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, layer); + + return this; + }, + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#tileToWorldX + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + tileToWorldX: function (tileX, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return this.TileToWorldX(tileX, camera, layer); + }, + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#tileToWorldY + * @since 3.0.0 + * + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer + * to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + tileToWorldY: function (tileX, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return this.TileToWorldY(tileX, camera, layer); + }, + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#tileToWorldXY + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. + */ + + tileToWorldXY: function (tileX, tileY, point, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return this.TileToWorldXY(tileX, tileY, point, camera, layer); + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * If no layer specified, the map's current layer is used. This + * cannot be applied to StaticTilemapLayers. + * + * @method Phaser.Tilemaps.Tilemap#weightedRandomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + weightedRandomize: function (tileX, tileY, width, height, weightedIndexes, layer) + { + layer = this.getLayer(layer); + + if (this._isStaticCall(layer, 'weightedRandomize')) { return this; } + + if (layer === null) { return null; } + + TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, layer); + + return this; + }, + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#worldToTileX + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer + * to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + worldToTileX: function (worldX, snapToFloor, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return this.WorldToTileX(worldX, snapToFloor, camera, layer); + }, + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#worldToTileY + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?number} Returns a number, or null if the layer given was invalid. + */ + worldToTileY: function (worldY, snapToFloor, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return this.WorldToTileY(worldY, snapToFloor, camera, layer); + }, + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * If no layer specified, the maps current layer is used. + * + * @method Phaser.Tilemaps.Tilemap#worldToTileXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {(string|integer|Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used. + * + * @return {?Phaser.Math.Vector2} Returns a point, or null if the layer given was invalid. + */ + worldToTileXY: function (worldX, worldY, snapToFloor, point, camera, layer) + { + layer = this.getLayer(layer); + + if (layer === null) { return null; } + + return this.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer); + }, + + /** + * Used internally to check if a layer is static and prints out a warning. + * + * @method Phaser.Tilemaps.Tilemap#_isStaticCall + * @private + * @since 3.0.0 + * + * @return {boolean} + */ + _isStaticCall: function (layer, functionName) + { + if (layer.tilemapLayer instanceof StaticTilemapLayer) + { + console.warn(functionName + ': You cannot change the tiles in a static tilemap layer'); + return true; + } + else + { + return false; + } + } + +}); + +module.exports = Tilemap; diff --git a/src/tilemaps/TilemapCreator.js b/src/tilemaps/TilemapCreator.js index 639301561..ddf28641a 100644 --- a/src/tilemaps/TilemapCreator.js +++ b/src/tilemaps/TilemapCreator.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectCreator = require('../gameobjects/GameObjectCreator'); -var ParseToTilemap = require('./ParseToTilemap'); - -/** - * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. - * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing - * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map - * data. For an empty map, you should specify tileWidth, tileHeight, width & height. - * - * @method Phaser.GameObjects.GameObjectCreator#tilemap - * @since 3.0.0 - * - * @param {Phaser.Types.Tilemaps.TilemapConfig} [config] - The config options for the Tilemap. - * - * @return {Phaser.Tilemaps.Tilemap} - */ -GameObjectCreator.register('tilemap', function (config) -{ - // Defaults are applied in ParseToTilemap - var c = (config !== undefined) ? config : {}; - - return ParseToTilemap( - this.scene, - c.key, - c.tileWidth, - c.tileHeight, - c.width, - c.height, - c.data, - c.insertNull - ); -}); +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectCreator = require('../gameobjects/GameObjectCreator'); +var ParseToTilemap = require('./ParseToTilemap'); + +/** + * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. + * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing + * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map + * data. For an empty map, you should specify tileWidth, tileHeight, width & height. + * + * @method Phaser.GameObjects.GameObjectCreator#tilemap + * @since 3.0.0 + * + * @param {Phaser.Types.Tilemaps.TilemapConfig} [config] - The config options for the Tilemap. + * + * @return {Phaser.Tilemaps.Tilemap} + */ +GameObjectCreator.register('tilemap', function (config) +{ + // Defaults are applied in ParseToTilemap + var c = (config !== undefined) ? config : {}; + + return ParseToTilemap( + this.scene, + c.key, + c.tileWidth, + c.tileHeight, + c.width, + c.height, + c.data, + c.insertNull + ); +}); diff --git a/src/tilemaps/TilemapFactory.js b/src/tilemaps/TilemapFactory.js index e61148b2c..acc069a85 100644 --- a/src/tilemaps/TilemapFactory.js +++ b/src/tilemaps/TilemapFactory.js @@ -1,60 +1,60 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GameObjectFactory = require('../gameobjects/GameObjectFactory'); -var ParseToTilemap = require('./ParseToTilemap'); - -/** - * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. - * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing - * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map - * data. For an empty map, you should specify tileWidth, tileHeight, width & height. - * - * @method Phaser.GameObjects.GameObjectFactory#tilemap - * @since 3.0.0 - * - * @param {string} [key] - The key in the Phaser cache that corresponds to the loaded tilemap data. - * @param {integer} [tileWidth=32] - The width of a tile in pixels. Pass in `null` to leave as the - * default. - * @param {integer} [tileHeight=32] - The height of a tile in pixels. Pass in `null` to leave as the - * default. - * @param {integer} [width=10] - The width of the map in tiles. Pass in `null` to leave as the - * default. - * @param {integer} [height=10] - The height of the map in tiles. Pass in `null` to leave as the - * default. - * @param {integer[][]} [data] - Instead of loading from the cache, you can also load directly from - * a 2D array of tile indexes. Pass in `null` for no data. - * @param {boolean} [insertNull=false] - 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've 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.Tilemap} - */ -GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, width, height, data, insertNull) -{ - // 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. - - if (key === null) { key = undefined; } - if (tileWidth === null) { tileWidth = undefined; } - if (tileHeight === null) { tileHeight = undefined; } - if (width === null) { width = undefined; } - if (height === null) { height = undefined; } - - return ParseToTilemap(this.scene, key, tileWidth, tileHeight, width, height, data, insertNull); -}); - -// 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 +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GameObjectFactory = require('../gameobjects/GameObjectFactory'); +var ParseToTilemap = require('./ParseToTilemap'); + +/** + * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. + * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing + * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map + * data. For an empty map, you should specify tileWidth, tileHeight, width & height. + * + * @method Phaser.GameObjects.GameObjectFactory#tilemap + * @since 3.0.0 + * + * @param {string} [key] - The key in the Phaser cache that corresponds to the loaded tilemap data. + * @param {integer} [tileWidth=32] - The width of a tile in pixels. Pass in `null` to leave as the + * default. + * @param {integer} [tileHeight=32] - The height of a tile in pixels. Pass in `null` to leave as the + * default. + * @param {integer} [width=10] - The width of the map in tiles. Pass in `null` to leave as the + * default. + * @param {integer} [height=10] - The height of the map in tiles. Pass in `null` to leave as the + * default. + * @param {integer[][]} [data] - Instead of loading from the cache, you can also load directly from + * a 2D array of tile indexes. Pass in `null` for no data. + * @param {boolean} [insertNull=false] - 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've 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.Tilemap} + */ +GameObjectFactory.register('tilemap', function (key, tileWidth, tileHeight, width, height, data, insertNull) +{ + // 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. + + if (key === null) { key = undefined; } + if (tileWidth === null) { tileWidth = undefined; } + if (tileHeight === null) { tileHeight = undefined; } + if (width === null) { width = undefined; } + if (height === null) { height = undefined; } + + return ParseToTilemap(this.scene, key, tileWidth, tileHeight, width, height, data, insertNull); +}); + +// 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 diff --git a/src/tilemaps/Tileset.js b/src/tilemaps/Tileset.js index 260720b33..98a936c0a 100644 --- a/src/tilemaps/Tileset.js +++ b/src/tilemaps/Tileset.js @@ -1,398 +1,398 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); - -/** - * @classdesc - * A Tileset is a combination of an image containing the tiles and a container for data about - * each tile. - * - * @class Tileset - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.0 - * - * @param {string} name - The name of the tileset in the map data. - * @param {integer} firstgid - The first tile index this tileset contains. - * @param {integer} [tileWidth=32] - Width of each tile (in pixels). - * @param {integer} [tileHeight=32] - Height of each tile (in pixels). - * @param {integer} [tileMargin=0] - The margin around all tiles in the sheet (in pixels). - * @param {integer} [tileSpacing=0] - The spacing between each tile in the sheet (in pixels). - * @param {object} [tileProperties={}] - Custom properties defined per tile in the Tileset. - * These typically are custom properties created in Tiled when editing a tileset. - * @param {object} [tileData={}] - Data stored per tile. These typically are created in Tiled - * when editing a tileset, e.g. from Tiled's tile collision editor or terrain editor. - */ -var Tileset = new Class({ - - initialize: - - function Tileset (name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, tileProperties, tileData) - { - if (tileWidth === undefined || tileWidth <= 0) { tileWidth = 32; } - if (tileHeight === undefined || tileHeight <= 0) { tileHeight = 32; } - if (tileMargin === undefined) { tileMargin = 0; } - if (tileSpacing === undefined) { tileSpacing = 0; } - if (tileProperties === undefined) { tileProperties = {}; } - if (tileData === undefined) { tileData = {}; } - - /** - * The name of the Tileset. - * - * @name Phaser.Tilemaps.Tileset#name - * @type {string} - * @since 3.0.0 - */ - this.name = name; - - /** - * The starting index of the first tile index this Tileset contains. - * - * @name Phaser.Tilemaps.Tileset#firstgid - * @type {integer} - * @since 3.0.0 - */ - this.firstgid = firstgid; - - /** - * The width of each tile (in pixels). Use setTileSize to change. - * - * @name Phaser.Tilemaps.Tileset#tileWidth - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.tileWidth = tileWidth; - - /** - * The height of each tile (in pixels). Use setTileSize to change. - * - * @name Phaser.Tilemaps.Tileset#tileHeight - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.tileHeight = tileHeight; - - /** - * The margin around the tiles in the sheet (in pixels). Use `setSpacing` to change. - * - * @name Phaser.Tilemaps.Tileset#tileMargin - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.tileMargin = tileMargin; - - /** - * The spacing between each the tile in the sheet (in pixels). Use `setSpacing` to change. - * - * @name Phaser.Tilemaps.Tileset#tileSpacing - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.tileSpacing = tileSpacing; - - /** - * Tileset-specific properties per tile that are typically defined in the Tiled editor in the - * Tileset editor. - * - * @name Phaser.Tilemaps.Tileset#tileProperties - * @type {object} - * @since 3.0.0 - */ - this.tileProperties = tileProperties; - - /** - * Tileset-specific data per tile that are typically defined in the Tiled editor, e.g. within - * the Tileset collision editor. This is where collision objects and terrain are stored. - * - * @name Phaser.Tilemaps.Tileset#tileData - * @type {object} - * @since 3.0.0 - */ - this.tileData = tileData; - - /** - * The cached image that contains the individual tiles. Use setImage to set. - * - * @name Phaser.Tilemaps.Tileset#image - * @type {?Phaser.Textures.Texture} - * @readonly - * @since 3.0.0 - */ - this.image = null; - - /** - * The gl texture used by the WebGL renderer. - * - * @name Phaser.Tilemaps.Tileset#glTexture - * @type {?WebGLTexture} - * @readonly - * @since 3.11.0 - */ - this.glTexture = null; - - /** - * The number of tile rows in the the tileset. - * - * @name Phaser.Tilemaps.Tileset#rows - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.rows = 0; - - /** - * The number of tile columns in the tileset. - * - * @name Phaser.Tilemaps.Tileset#columns - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.columns = 0; - - /** - * The total number of tiles in the tileset. - * - * @name Phaser.Tilemaps.Tileset#total - * @type {integer} - * @readonly - * @since 3.0.0 - */ - this.total = 0; - - /** - * The look-up table to specific tile image texture coordinates (UV in pixels). Each element - * contains the coordinates for a tile in an object of the form {x, y}. - * - * @name Phaser.Tilemaps.Tileset#texCoordinates - * @type {object[]} - * @readonly - * @since 3.0.0 - */ - this.texCoordinates = []; - }, - - /** - * Get a tiles properties that are stored in the Tileset. Returns null if tile index is not - * contained in this Tileset. This is typically defined in Tiled under the Tileset editor. - * - * @method Phaser.Tilemaps.Tileset#getTileProperties - * @since 3.0.0 - * - * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. - * - * @return {?(object|undefined)} - */ - getTileProperties: function (tileIndex) - { - if (!this.containsTileIndex(tileIndex)) { return null; } - - return this.tileProperties[tileIndex - this.firstgid]; - }, - - /** - * Get a tile's data that is stored in the Tileset. Returns null if tile index is not contained - * in this Tileset. This is typically defined in Tiled and will contain both Tileset collision - * info and terrain mapping. - * - * @method Phaser.Tilemaps.Tileset#getTileData - * @since 3.0.0 - * - * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. - * - * @return {?object|undefined} - */ - getTileData: function (tileIndex) - { - if (!this.containsTileIndex(tileIndex)) { return null; } - - return this.tileData[tileIndex - this.firstgid]; - }, - - /** - * Get a tile's collision group that is stored in the Tileset. Returns null if tile index is not - * contained in this Tileset. This is typically defined within Tiled's tileset collision editor. - * - * @method Phaser.Tilemaps.Tileset#getTileCollisionGroup - * @since 3.0.0 - * - * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. - * - * @return {?object} - */ - getTileCollisionGroup: function (tileIndex) - { - var data = this.getTileData(tileIndex); - - return (data && data.objectgroup) ? data.objectgroup : null; - }, - - /** - * Returns true if and only if this Tileset contains the given tile index. - * - * @method Phaser.Tilemaps.Tileset#containsTileIndex - * @since 3.0.0 - * - * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. - * - * @return {boolean} - */ - containsTileIndex: function (tileIndex) - { - return ( - tileIndex >= this.firstgid && - tileIndex < (this.firstgid + this.total) - ); - }, - - /** - * Returns the texture coordinates (UV in pixels) in the Tileset image for the given tile index. - * Returns null if tile index is not contained in this Tileset. - * - * @method Phaser.Tilemaps.Tileset#getTileTextureCoordinates - * @since 3.0.0 - * - * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. - * - * @return {?object} Object in the form { x, y } representing the top-left UV coordinate - * within the Tileset image. - */ - getTileTextureCoordinates: function (tileIndex) - { - if (!this.containsTileIndex(tileIndex)) { return null; } - - return this.texCoordinates[tileIndex - this.firstgid]; - }, - - /** - * Sets the image associated with this Tileset and updates the tile data (rows, columns, etc.). - * - * @method Phaser.Tilemaps.Tileset#setImage - * @since 3.0.0 - * - * @param {Phaser.Textures.Texture} texture - The image that contains the tiles. - * - * @return {Phaser.Tilemaps.Tileset} This Tileset object. - */ - setImage: function (texture) - { - this.image = texture; - - this.glTexture = texture.get().source.glTexture; - - this.updateTileData(this.image.source[0].width, this.image.source[0].height); - - return this; - }, - - /** - * Sets the tile width & height and updates the tile data (rows, columns, etc.). - * - * @method Phaser.Tilemaps.Tileset#setTileSize - * @since 3.0.0 - * - * @param {integer} [tileWidth] - The width of a tile in pixels. - * @param {integer} [tileHeight] - The height of a tile in pixels. - * - * @return {Phaser.Tilemaps.Tileset} This Tileset object. - */ - setTileSize: function (tileWidth, tileHeight) - { - if (tileWidth !== undefined) { this.tileWidth = tileWidth; } - if (tileHeight !== undefined) { this.tileHeight = tileHeight; } - - if (this.image) - { - this.updateTileData(this.image.source[0].width, this.image.source[0].height); - } - - return this; - }, - - /** - * Sets the tile margin & spacing and updates the tile data (rows, columns, etc.). - * - * @method Phaser.Tilemaps.Tileset#setSpacing - * @since 3.0.0 - * - * @param {integer} [margin] - The margin around the tiles in the sheet (in pixels). - * @param {integer} [spacing] - The spacing between the tiles in the sheet (in pixels). - * - * @return {Phaser.Tilemaps.Tileset} This Tileset object. - */ - setSpacing: function (margin, spacing) - { - if (margin !== undefined) { this.tileMargin = margin; } - if (spacing !== undefined) { this.tileSpacing = spacing; } - - if (this.image) - { - this.updateTileData(this.image.source[0].width, this.image.source[0].height); - } - - return this; - }, - - /** - * Updates tile texture coordinates and tileset data. - * - * @method Phaser.Tilemaps.Tileset#updateTileData - * @since 3.0.0 - * - * @param {integer} imageWidth - The (expected) width of the image to slice. - * @param {integer} imageHeight - The (expected) height of the image to slice. - * - * @return {Phaser.Tilemaps.Tileset} This Tileset object. - */ - updateTileData: function (imageWidth, imageHeight) - { - var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); - var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); - - if (rowCount % 1 !== 0 || colCount % 1 !== 0) - { - console.warn('Image tile area not tile size multiple in: ' + this.name); - } - - // 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. - rowCount = Math.floor(rowCount); - colCount = Math.floor(colCount); - - this.rows = rowCount; - this.columns = colCount; - - // In Tiled, "empty" spaces in a tileset count as tiles and hence count towards the gid - this.total = rowCount * colCount; - - this.texCoordinates.length = 0; - - var tx = this.tileMargin; - var ty = this.tileMargin; - - for (var y = 0; y < this.rows; y++) - { - for (var x = 0; x < this.columns; x++) - { - this.texCoordinates.push({ x: tx, y: ty }); - tx += this.tileWidth + this.tileSpacing; - } - - tx = this.tileMargin; - ty += this.tileHeight + this.tileSpacing; - } - - return this; - } - -}); - -module.exports = Tileset; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); + +/** + * @classdesc + * A Tileset is a combination of an image containing the tiles and a container for data about + * each tile. + * + * @class Tileset + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {string} name - The name of the tileset in the map data. + * @param {integer} firstgid - The first tile index this tileset contains. + * @param {integer} [tileWidth=32] - Width of each tile (in pixels). + * @param {integer} [tileHeight=32] - Height of each tile (in pixels). + * @param {integer} [tileMargin=0] - The margin around all tiles in the sheet (in pixels). + * @param {integer} [tileSpacing=0] - The spacing between each tile in the sheet (in pixels). + * @param {object} [tileProperties={}] - Custom properties defined per tile in the Tileset. + * These typically are custom properties created in Tiled when editing a tileset. + * @param {object} [tileData={}] - Data stored per tile. These typically are created in Tiled + * when editing a tileset, e.g. from Tiled's tile collision editor or terrain editor. + */ +var Tileset = new Class({ + + initialize: + + function Tileset (name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, tileProperties, tileData) + { + if (tileWidth === undefined || tileWidth <= 0) { tileWidth = 32; } + if (tileHeight === undefined || tileHeight <= 0) { tileHeight = 32; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (tileProperties === undefined) { tileProperties = {}; } + if (tileData === undefined) { tileData = {}; } + + /** + * The name of the Tileset. + * + * @name Phaser.Tilemaps.Tileset#name + * @type {string} + * @since 3.0.0 + */ + this.name = name; + + /** + * The starting index of the first tile index this Tileset contains. + * + * @name Phaser.Tilemaps.Tileset#firstgid + * @type {integer} + * @since 3.0.0 + */ + this.firstgid = firstgid; + + /** + * The width of each tile (in pixels). Use setTileSize to change. + * + * @name Phaser.Tilemaps.Tileset#tileWidth + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileWidth = tileWidth; + + /** + * The height of each tile (in pixels). Use setTileSize to change. + * + * @name Phaser.Tilemaps.Tileset#tileHeight + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileHeight = tileHeight; + + /** + * The margin around the tiles in the sheet (in pixels). Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.Tileset#tileMargin + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileMargin = tileMargin; + + /** + * The spacing between each the tile in the sheet (in pixels). Use `setSpacing` to change. + * + * @name Phaser.Tilemaps.Tileset#tileSpacing + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.tileSpacing = tileSpacing; + + /** + * Tileset-specific properties per tile that are typically defined in the Tiled editor in the + * Tileset editor. + * + * @name Phaser.Tilemaps.Tileset#tileProperties + * @type {object} + * @since 3.0.0 + */ + this.tileProperties = tileProperties; + + /** + * Tileset-specific data per tile that are typically defined in the Tiled editor, e.g. within + * the Tileset collision editor. This is where collision objects and terrain are stored. + * + * @name Phaser.Tilemaps.Tileset#tileData + * @type {object} + * @since 3.0.0 + */ + this.tileData = tileData; + + /** + * The cached image that contains the individual tiles. Use setImage to set. + * + * @name Phaser.Tilemaps.Tileset#image + * @type {?Phaser.Textures.Texture} + * @readonly + * @since 3.0.0 + */ + this.image = null; + + /** + * The gl texture used by the WebGL renderer. + * + * @name Phaser.Tilemaps.Tileset#glTexture + * @type {?WebGLTexture} + * @readonly + * @since 3.11.0 + */ + this.glTexture = null; + + /** + * The number of tile rows in the the tileset. + * + * @name Phaser.Tilemaps.Tileset#rows + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * + * @name Phaser.Tilemaps.Tileset#columns + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * + * @name Phaser.Tilemaps.Tileset#total + * @type {integer} + * @readonly + * @since 3.0.0 + */ + this.total = 0; + + /** + * The look-up table to specific tile image texture coordinates (UV in pixels). Each element + * contains the coordinates for a tile in an object of the form {x, y}. + * + * @name Phaser.Tilemaps.Tileset#texCoordinates + * @type {object[]} + * @readonly + * @since 3.0.0 + */ + this.texCoordinates = []; + }, + + /** + * Get a tiles properties that are stored in the Tileset. Returns null if tile index is not + * contained in this Tileset. This is typically defined in Tiled under the Tileset editor. + * + * @method Phaser.Tilemaps.Tileset#getTileProperties + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?(object|undefined)} + */ + getTileProperties: function (tileIndex) + { + if (!this.containsTileIndex(tileIndex)) { return null; } + + return this.tileProperties[tileIndex - this.firstgid]; + }, + + /** + * Get a tile's data that is stored in the Tileset. Returns null if tile index is not contained + * in this Tileset. This is typically defined in Tiled and will contain both Tileset collision + * info and terrain mapping. + * + * @method Phaser.Tilemaps.Tileset#getTileData + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?object|undefined} + */ + getTileData: function (tileIndex) + { + if (!this.containsTileIndex(tileIndex)) { return null; } + + return this.tileData[tileIndex - this.firstgid]; + }, + + /** + * Get a tile's collision group that is stored in the Tileset. Returns null if tile index is not + * contained in this Tileset. This is typically defined within Tiled's tileset collision editor. + * + * @method Phaser.Tilemaps.Tileset#getTileCollisionGroup + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?object} + */ + getTileCollisionGroup: function (tileIndex) + { + var data = this.getTileData(tileIndex); + + return (data && data.objectgroup) ? data.objectgroup : null; + }, + + /** + * Returns true if and only if this Tileset contains the given tile index. + * + * @method Phaser.Tilemaps.Tileset#containsTileIndex + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {boolean} + */ + containsTileIndex: function (tileIndex) + { + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + }, + + /** + * Returns the texture coordinates (UV in pixels) in the Tileset image for the given tile index. + * Returns null if tile index is not contained in this Tileset. + * + * @method Phaser.Tilemaps.Tileset#getTileTextureCoordinates + * @since 3.0.0 + * + * @param {integer} tileIndex - The unique id of the tile across all tilesets in the map. + * + * @return {?object} Object in the form { x, y } representing the top-left UV coordinate + * within the Tileset image. + */ + getTileTextureCoordinates: function (tileIndex) + { + if (!this.containsTileIndex(tileIndex)) { return null; } + + return this.texCoordinates[tileIndex - this.firstgid]; + }, + + /** + * Sets the image associated with this Tileset and updates the tile data (rows, columns, etc.). + * + * @method Phaser.Tilemaps.Tileset#setImage + * @since 3.0.0 + * + * @param {Phaser.Textures.Texture} texture - The image that contains the tiles. + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + setImage: function (texture) + { + this.image = texture; + + this.glTexture = texture.get().source.glTexture; + + this.updateTileData(this.image.source[0].width, this.image.source[0].height); + + return this; + }, + + /** + * Sets the tile width & height and updates the tile data (rows, columns, etc.). + * + * @method Phaser.Tilemaps.Tileset#setTileSize + * @since 3.0.0 + * + * @param {integer} [tileWidth] - The width of a tile in pixels. + * @param {integer} [tileHeight] - The height of a tile in pixels. + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + setTileSize: function (tileWidth, tileHeight) + { + if (tileWidth !== undefined) { this.tileWidth = tileWidth; } + if (tileHeight !== undefined) { this.tileHeight = tileHeight; } + + if (this.image) + { + this.updateTileData(this.image.source[0].width, this.image.source[0].height); + } + + return this; + }, + + /** + * Sets the tile margin & spacing and updates the tile data (rows, columns, etc.). + * + * @method Phaser.Tilemaps.Tileset#setSpacing + * @since 3.0.0 + * + * @param {integer} [margin] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing] - The spacing between the tiles in the sheet (in pixels). + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + setSpacing: function (margin, spacing) + { + if (margin !== undefined) { this.tileMargin = margin; } + if (spacing !== undefined) { this.tileSpacing = spacing; } + + if (this.image) + { + this.updateTileData(this.image.source[0].width, this.image.source[0].height); + } + + return this; + }, + + /** + * Updates tile texture coordinates and tileset data. + * + * @method Phaser.Tilemaps.Tileset#updateTileData + * @since 3.0.0 + * + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + * + * @return {Phaser.Tilemaps.Tileset} This Tileset object. + */ + updateTileData: function (imageWidth, imageHeight) + { + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn('Image tile area not tile size multiple in: ' + this.name); + } + + // 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. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + this.rows = rowCount; + this.columns = colCount; + + // In Tiled, "empty" spaces in a tileset count as tiles and hence count towards the gid + this.total = rowCount * colCount; + + this.texCoordinates.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.texCoordinates.push({ x: tx, y: ty }); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + return this; + } + +}); + +module.exports = Tileset; diff --git a/src/tilemaps/components/CalculateFacesAt.js b/src/tilemaps/components/CalculateFacesAt.js index 23fb2314d..3973ad63d 100644 --- a/src/tilemaps/components/CalculateFacesAt.js +++ b/src/tilemaps/components/CalculateFacesAt.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTileAt = require('./GetTileAt'); - -/** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * - * @function Phaser.Tilemaps.Components.CalculateFacesAt - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate. - * @param {integer} tileY - The y coordinate. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var CalculateFacesAt = function (tileX, tileY, layer) -{ - var tile = GetTileAt(tileX, tileY, true, layer); - var above = GetTileAt(tileX, tileY - 1, true, layer); - var below = GetTileAt(tileX, tileY + 1, true, layer); - var left = GetTileAt(tileX - 1, tileY, true, layer); - var right = GetTileAt(tileX + 1, tileY, true, layer); - var tileCollides = tile && tile.collides; - - // Assume the changed tile has all interesting edges - if (tileCollides) - { - tile.faceTop = true; - tile.faceBottom = true; - tile.faceLeft = true; - tile.faceRight = true; - } - - // Reset edges that are shared between tile and its neighbors - if (above && above.collides) - { - if (tileCollides) { tile.faceTop = false; } - above.faceBottom = !tileCollides; - } - - if (below && below.collides) - { - if (tileCollides) { tile.faceBottom = false; } - below.faceTop = !tileCollides; - } - - if (left && left.collides) - { - if (tileCollides) { tile.faceLeft = false; } - left.faceRight = !tileCollides; - } - - if (right && right.collides) - { - if (tileCollides) { tile.faceRight = false; } - right.faceLeft = !tileCollides; - } - - if (tile && !tile.collides) { tile.resetFaces(); } - - return tile; -}; - -module.exports = CalculateFacesAt; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTileAt = require('./GetTileAt'); + +/** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * @function Phaser.Tilemaps.Components.CalculateFacesAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var CalculateFacesAt = function (tileX, tileY, layer) +{ + var tile = GetTileAt(tileX, tileY, true, layer); + var above = GetTileAt(tileX, tileY - 1, true, layer); + var below = GetTileAt(tileX, tileY + 1, true, layer); + var left = GetTileAt(tileX - 1, tileY, true, layer); + var right = GetTileAt(tileX + 1, tileY, true, layer); + var tileCollides = tile && tile.collides; + + // Assume the changed tile has all interesting edges + if (tileCollides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + // Reset edges that are shared between tile and its neighbors + if (above && above.collides) + { + if (tileCollides) { tile.faceTop = false; } + above.faceBottom = !tileCollides; + } + + if (below && below.collides) + { + if (tileCollides) { tile.faceBottom = false; } + below.faceTop = !tileCollides; + } + + if (left && left.collides) + { + if (tileCollides) { tile.faceLeft = false; } + left.faceRight = !tileCollides; + } + + if (right && right.collides) + { + if (tileCollides) { tile.faceRight = false; } + right.faceLeft = !tileCollides; + } + + if (tile && !tile.collides) { tile.resetFaces(); } + + return tile; +}; + +module.exports = CalculateFacesAt; diff --git a/src/tilemaps/components/CalculateFacesWithin.js b/src/tilemaps/components/CalculateFacesWithin.js index 3bb10047a..6556cf7a1 100644 --- a/src/tilemaps/components/CalculateFacesWithin.js +++ b/src/tilemaps/components/CalculateFacesWithin.js @@ -1,60 +1,60 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTileAt = require('./GetTileAt'); -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * - * @function Phaser.Tilemaps.Components.CalculateFacesWithin - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} width - How many tiles wide from the `tileX` index the area will be. - * @param {integer} height - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var CalculateFacesWithin = function (tileX, tileY, width, height, layer) -{ - var above = null; - var below = null; - var left = null; - var right = null; - - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - for (var i = 0; i < tiles.length; i++) - { - var tile = tiles[i]; - - if (tile) - { - if (tile.collides) - { - above = GetTileAt(tile.x, tile.y - 1, true, layer); - below = GetTileAt(tile.x, tile.y + 1, true, layer); - left = GetTileAt(tile.x - 1, tile.y, true, layer); - right = GetTileAt(tile.x + 1, tile.y, true, layer); - - tile.faceTop = (above && above.collides) ? false : true; - tile.faceBottom = (below && below.collides) ? false : true; - tile.faceLeft = (left && left.collides) ? false : true; - tile.faceRight = (right && right.collides) ? false : true; - } - else - { - tile.resetFaces(); - } - } - } -}; - -module.exports = CalculateFacesWithin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTileAt = require('./GetTileAt'); +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * @function Phaser.Tilemaps.Components.CalculateFacesWithin + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var CalculateFacesWithin = function (tileX, tileY, width, height, layer) +{ + var above = null; + var below = null; + var left = null; + var right = null; + + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + if (tile) + { + if (tile.collides) + { + above = GetTileAt(tile.x, tile.y - 1, true, layer); + below = GetTileAt(tile.x, tile.y + 1, true, layer); + left = GetTileAt(tile.x - 1, tile.y, true, layer); + right = GetTileAt(tile.x + 1, tile.y, true, layer); + + tile.faceTop = (above && above.collides) ? false : true; + tile.faceBottom = (below && below.collides) ? false : true; + tile.faceLeft = (left && left.collides) ? false : true; + tile.faceRight = (right && right.collides) ? false : true; + } + else + { + tile.resetFaces(); + } + } + } +}; + +module.exports = CalculateFacesWithin; diff --git a/src/tilemaps/components/CheckIsoBounds.js b/src/tilemaps/components/CheckIsoBounds.js index e49864793..84b00e6be 100644 --- a/src/tilemaps/components/CheckIsoBounds.js +++ b/src/tilemaps/components/CheckIsoBounds.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * @function Phaser.Tilemaps.Components.CheckIsoBounds - * @private - * @since 3.2.3 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to check against. - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. - */ -var CheckIsoBounds = function (tileX,tileY,layer,camera) -{ - var tilemapLayer = layer.tilemapLayer; - var cullDistances = tilemapLayer.isoCullDistances; - var pos = tilemapLayer.tileToWorldXY(tileX,tileY,undefined,camera); - - // we always subtract 1/2 of the tile's height/width to make the culling distance start from the center of the tiles. - return pos.x > camera.worldView.x + tilemapLayer.scaleX * layer.tileWidth * (- cullDistances.x - 1 / 2) - && pos.x < camera.worldView.right + tilemapLayer.scaleX * layer.tileWidth * (cullDistances.x - 1 / 2) - && pos.y > camera.worldView.y + tilemapLayer.scaleY * layer.tileHeight * (- cullDistances.y - 1 / 2) - && pos.y < camera.worldView.bottom + tilemapLayer.scaleY * layer.tileHeight * (cullDistances.y - 1 / 2); -}; - -module.exports = CheckIsoBounds; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * @function Phaser.Tilemaps.Components.CheckIsoBounds + * @private + * @since 3.2.3 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to check against. + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + */ +var CheckIsoBounds = function (tileX,tileY,layer,camera) +{ + var tilemapLayer = layer.tilemapLayer; + var cullDistances = tilemapLayer.isoCullDistances; + var pos = tilemapLayer.tileToWorldXY(tileX,tileY,undefined,camera); + + // we always subtract 1/2 of the tile's height/width to make the culling distance start from the center of the tiles. + return pos.x > camera.worldView.x + tilemapLayer.scaleX * layer.tileWidth * (- cullDistances.x - 1 / 2) + && pos.x < camera.worldView.right + tilemapLayer.scaleX * layer.tileWidth * (cullDistances.x - 1 / 2) + && pos.y > camera.worldView.y + tilemapLayer.scaleY * layer.tileHeight * (- cullDistances.y - 1 / 2) + && pos.y < camera.worldView.bottom + tilemapLayer.scaleY * layer.tileHeight * (cullDistances.y - 1 / 2); +}; + +module.exports = CheckIsoBounds; diff --git a/src/tilemaps/components/Copy.js b/src/tilemaps/components/Copy.js index e28bff680..08e51ffbb 100644 --- a/src/tilemaps/components/Copy.js +++ b/src/tilemaps/components/Copy.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); - -/** - * Copies the tiles in the source rectangular area to a new destination (all specified in tile - * coordinates) within the layer. This copies all tile properties & recalculates collision - * information in the destination region. - * - * @function Phaser.Tilemaps.Components.Copy - * @private - * @since 3.0.0 - * - * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. - * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. - * @param {integer} width - The width of the area to copy, in tiles, not pixels. - * @param {integer} height - The height of the area to copy, in tiles, not pixels. - * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. - * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var Copy = function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) -{ - if (srcTileX < 0) { srcTileX = 0; } - if (srcTileY < 0) { srcTileY = 0; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - var srcTiles = GetTilesWithin(srcTileX, srcTileY, width, height, null, layer); - - var offsetX = destTileX - srcTileX; - var offsetY = destTileY - srcTileY; - - for (var i = 0; i < srcTiles.length; i++) - { - var tileX = srcTiles[i].x + offsetX; - var tileY = srcTiles[i].y + offsetY; - if (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height) - { - if (layer.data[tileY][tileX]) - { - layer.data[tileY][tileX].copy(srcTiles[i]); - } - } - } - - if (recalculateFaces) - { - // Recalculate the faces within the destination area and neighboring tiles - CalculateFacesWithin(destTileX - 1, destTileY - 1, width + 2, height + 2, layer); - } -}; - -module.exports = Copy; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); + +/** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * @function Phaser.Tilemaps.Components.Copy + * @private + * @since 3.0.0 + * + * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} width - The width of the area to copy, in tiles, not pixels. + * @param {integer} height - The height of the area to copy, in tiles, not pixels. + * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. + * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var Copy = function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) +{ + if (srcTileX < 0) { srcTileX = 0; } + if (srcTileY < 0) { srcTileY = 0; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + var srcTiles = GetTilesWithin(srcTileX, srcTileY, width, height, null, layer); + + var offsetX = destTileX - srcTileX; + var offsetY = destTileY - srcTileY; + + for (var i = 0; i < srcTiles.length; i++) + { + var tileX = srcTiles[i].x + offsetX; + var tileY = srcTiles[i].y + offsetY; + if (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height) + { + if (layer.data[tileY][tileX]) + { + layer.data[tileY][tileX].copy(srcTiles[i]); + } + } + } + + if (recalculateFaces) + { + // Recalculate the faces within the destination area and neighboring tiles + CalculateFacesWithin(destTileX - 1, destTileY - 1, width + 2, height + 2, layer); + } +}; + +module.exports = Copy; diff --git a/src/tilemaps/components/CreateFromTiles.js b/src/tilemaps/components/CreateFromTiles.js index a18918246..518fce1d3 100644 --- a/src/tilemaps/components/CreateFromTiles.js +++ b/src/tilemaps/components/CreateFromTiles.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - - -var GetTilesWithin = require('./GetTilesWithin'); -var ReplaceByIndex = require('./ReplaceByIndex'); - -/** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * - * @function Phaser.Tilemaps.Components.CreateFromTiles - * @private - * @since 3.0.0 - * - * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. - * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a one-to-one mapping with the indexes array. - * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. scene.make.sprite). - * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. - */ -var CreateFromTiles = function (indexes, replacements, spriteConfig, scene, camera, layer) -{ - if (spriteConfig === undefined) { spriteConfig = {}; } - - if (!Array.isArray(indexes)) { indexes = [ indexes ]; } - - var tilemapLayer = layer.tilemapLayer; - if (scene === undefined) { scene = tilemapLayer.scene; } - if (camera === undefined) { camera = scene.cameras.main; } - - var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); - var sprites = []; - var i; - - for (i = 0; i < tiles.length; i++) - { - var tile = tiles[i]; - - if (indexes.indexOf(tile.index) !== -1) - { - var point = tilemapLayer.tileToWorldXY(tile.x,tile.y, undefined, camera); - spriteConfig.x = point.x; - spriteConfig.y = point.y; - var sprite = scene.make.sprite(spriteConfig); - sprites.push(sprite); - } - } - - if (typeof replacements === 'number') - { - // Assume 1 replacement for all types of tile given - for (i = 0; i < indexes.length; i++) - { - ReplaceByIndex(indexes[i], replacements, 0, 0, layer.width, layer.height, layer); - } - } - else if (Array.isArray(replacements)) - { - // Assume 1 to 1 mapping with indexes array - for (i = 0; i < indexes.length; i++) - { - ReplaceByIndex(indexes[i], replacements[i], 0, 0, layer.width, layer.height, layer); - } - } - - return sprites; -}; - -module.exports = CreateFromTiles; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + + +var GetTilesWithin = require('./GetTilesWithin'); +var ReplaceByIndex = require('./ReplaceByIndex'); + +/** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @function Phaser.Tilemaps.Components.CreateFromTiles + * @private + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ +var CreateFromTiles = function (indexes, replacements, spriteConfig, scene, camera, layer) +{ + if (spriteConfig === undefined) { spriteConfig = {}; } + + if (!Array.isArray(indexes)) { indexes = [ indexes ]; } + + var tilemapLayer = layer.tilemapLayer; + if (scene === undefined) { scene = tilemapLayer.scene; } + if (camera === undefined) { camera = scene.cameras.main; } + + var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); + var sprites = []; + var i; + + for (i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + if (indexes.indexOf(tile.index) !== -1) + { + var point = tilemapLayer.tileToWorldXY(tile.x,tile.y, undefined, camera); + spriteConfig.x = point.x; + spriteConfig.y = point.y; + var sprite = scene.make.sprite(spriteConfig); + sprites.push(sprite); + } + } + + if (typeof replacements === 'number') + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < indexes.length; i++) + { + ReplaceByIndex(indexes[i], replacements, 0, 0, layer.width, layer.height, layer); + } + } + else if (Array.isArray(replacements)) + { + // Assume 1 to 1 mapping with indexes array + for (i = 0; i < indexes.length; i++) + { + ReplaceByIndex(indexes[i], replacements[i], 0, 0, layer.width, layer.height, layer); + } + } + + return sprites; +}; + +module.exports = CreateFromTiles; diff --git a/src/tilemaps/components/CullTiles.js b/src/tilemaps/components/CullTiles.js index cd730d933..9d7e1f0a4 100644 --- a/src/tilemaps/components/CullTiles.js +++ b/src/tilemaps/components/CullTiles.js @@ -1,277 +1,277 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); -var SnapFloor = require('../../math/snap/SnapFloor'); -var SnapCeil = require('../../math/snap/SnapCeil'); -var CheckIsoBounds = require('./CheckIsoBounds'); - -/** - * Returns the tiles in the given layer that are within the camera's viewport. This is used internally. - * - * @function Phaser.Tilemaps.Components.CullTiles - * @private - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. - * @param {array} [outputArray] - An optional array to store the Tile objects within. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ -var CullTiles = function (layer, camera, outputArray, renderOrder) -{ - if (outputArray === undefined) { outputArray = []; } - if (renderOrder === undefined) { renderOrder = 0; } - - outputArray.length = 0; - - var tilemap = layer.tilemapLayer.tilemap; - var tilemapLayer = layer.tilemapLayer; - - var mapData = layer.data; - var mapWidth = layer.width; - var mapHeight = layer.height; - - // 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. - var tileW = Math.floor(tilemap.tileWidth * tilemapLayer.scaleX); - var tileH = Math.floor(tilemap.tileHeight * tilemapLayer.scaleY); - - var drawLeft = 0; - var drawRight = mapWidth; - var drawTop = 0; - var drawBottom = mapHeight; - - if (!tilemapLayer.skipCull && tilemapLayer.scrollFactorX === 1 && tilemapLayer.scrollFactorY === 1) - { - if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) - { - // Camera world view bounds, snapped for scaled tile size - // Cull Padding values are given in tiles, not pixels - var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; - var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; - - var boundsTop; - var boundsBottom; - - if (layer.orientation === CONST.ORTHOGONAL) - { - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; - } - else if (layer.orientation === CONST.STAGGERED) - { - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH / 2, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH / 2, 0, true) + tilemapLayer.cullPaddingY; - } - else if (layer.orientation === CONST.HEXAGONAL) - { - var sidel = layer.hexSideLength; - var rowH = ((tileH - sidel) / 2 + sidel); - - boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, rowH, 0, true) - tilemapLayer.cullPaddingY; - boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, rowH, 0, true) + tilemapLayer.cullPaddingY; - } - - - - - drawLeft = Math.max(0, boundsLeft); - drawRight = Math.min(mapWidth, boundsRight); - drawTop = Math.max(0, boundsTop); - - drawBottom = Math.min(mapHeight, boundsBottom); - } - } - var x; - var y; - var tile; - - - if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) - { - - if (renderOrder === 0) - { - // right-down - - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 1) - { - // left-down - - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (layer.orientation === CONST.ISOMETRIC) - { - if (renderOrder === 0) - { - // right-down - - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - - } - } - } - else if (renderOrder === 1) - { - // left-down - - for (y = drawTop; y < drawBottom; y++) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawLeft; mapData[y] && x < drawRight; x++) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (y = drawBottom; y >= drawTop; y--) - { - for (x = drawRight; mapData[y] && x >= drawLeft; x--) - { - if (CheckIsoBounds(x,y,layer,camera)) - { - tile = mapData[y][x]; - - if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) - { - continue; - } - - outputArray.push(tile); - } - } - } - } - - } - - - tilemapLayer.tilesDrawn = outputArray.length; - tilemapLayer.tilesTotal = mapWidth * mapHeight; - - return outputArray; -}; - -module.exports = CullTiles; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); +var SnapFloor = require('../../math/snap/SnapFloor'); +var SnapCeil = require('../../math/snap/SnapCeil'); +var CheckIsoBounds = require('./CheckIsoBounds'); + +/** + * Returns the tiles in the given layer that are within the camera's viewport. This is used internally. + * + * @function Phaser.Tilemaps.Components.CullTiles + * @private + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + * @param {array} [outputArray] - An optional array to store the Tile objects within. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ +var CullTiles = function (layer, camera, outputArray, renderOrder) +{ + if (outputArray === undefined) { outputArray = []; } + if (renderOrder === undefined) { renderOrder = 0; } + + outputArray.length = 0; + + var tilemap = layer.tilemapLayer.tilemap; + var tilemapLayer = layer.tilemapLayer; + + var mapData = layer.data; + var mapWidth = layer.width; + var mapHeight = layer.height; + + // 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. + var tileW = Math.floor(tilemap.tileWidth * tilemapLayer.scaleX); + var tileH = Math.floor(tilemap.tileHeight * tilemapLayer.scaleY); + + var drawLeft = 0; + var drawRight = mapWidth; + var drawTop = 0; + var drawBottom = mapHeight; + + if (!tilemapLayer.skipCull && tilemapLayer.scrollFactorX === 1 && tilemapLayer.scrollFactorY === 1) + { + if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) + { + // Camera world view bounds, snapped for scaled tile size + // Cull Padding values are given in tiles, not pixels + var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; + var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; + + var boundsTop; + var boundsBottom; + + if (layer.orientation === CONST.ORTHOGONAL) + { + boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; + boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; + } + else if (layer.orientation === CONST.STAGGERED) + { + boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH / 2, 0, true) - tilemapLayer.cullPaddingY; + boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH / 2, 0, true) + tilemapLayer.cullPaddingY; + } + else if (layer.orientation === CONST.HEXAGONAL) + { + var sidel = layer.hexSideLength; + var rowH = ((tileH - sidel) / 2 + sidel); + + boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, rowH, 0, true) - tilemapLayer.cullPaddingY; + boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, rowH, 0, true) + tilemapLayer.cullPaddingY; + } + + + + + drawLeft = Math.max(0, boundsLeft); + drawRight = Math.min(mapWidth, boundsRight); + drawTop = Math.max(0, boundsTop); + + drawBottom = Math.min(mapHeight, boundsBottom); + } + } + var x; + var y; + var tile; + + + if (layer.orientation === CONST.ORTHOGONAL || layer.orientation === CONST.STAGGERED || layer.orientation === CONST.HEXAGONAL) + { + + if (renderOrder === 0) + { + // right-down + + for (y = drawTop; y < drawBottom; y++) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 1) + { + // left-down + + for (y = drawTop; y < drawBottom; y++) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 2) + { + // right-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + } + else if (layer.orientation === CONST.ISOMETRIC) + { + if (renderOrder === 0) + { + // right-down + + for (y = drawTop; y < drawBottom; y++) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + if (CheckIsoBounds(x,y,layer,camera)) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + + } + } + } + else if (renderOrder === 1) + { + // left-down + + for (y = drawTop; y < drawBottom; y++) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + if (CheckIsoBounds(x,y,layer,camera)) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + } + else if (renderOrder === 2) + { + // right-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawLeft; mapData[y] && x < drawRight; x++) + { + if (CheckIsoBounds(x,y,layer,camera)) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (y = drawBottom; y >= drawTop; y--) + { + for (x = drawRight; mapData[y] && x >= drawLeft; x--) + { + if (CheckIsoBounds(x,y,layer,camera)) + { + tile = mapData[y][x]; + + if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) + { + continue; + } + + outputArray.push(tile); + } + } + } + } + + } + + + tilemapLayer.tilesDrawn = outputArray.length; + tilemapLayer.tilesTotal = mapWidth * mapHeight; + + return outputArray; +}; + +module.exports = CullTiles; diff --git a/src/tilemaps/components/Fill.js b/src/tilemaps/components/Fill.js index 545d80a22..52b39181c 100644 --- a/src/tilemaps/components/Fill.js +++ b/src/tilemaps/components/Fill.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); -var SetTileCollision = require('./SetTileCollision'); - -/** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * @function Phaser.Tilemaps.Components.Fill - * @private - * @since 3.0.0 - * - * @param {integer} index - The tile index to fill the area with. - * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} width - How many tiles wide from the `tileX` index the area will be. - * @param {integer} height - How many tiles tall from the `tileY` index the area will be. - * @param {boolean} recalculateFaces - `true` if the faces data should be recalculated. - * @param {Phaser.Tilemaps.LayerData} layer - The tile layer to use. If not given the current layer is used. - */ -var Fill = function (index, tileX, tileY, width, height, recalculateFaces, layer) -{ - var doesIndexCollide = (layer.collideIndexes.indexOf(index) !== -1); - - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - for (var i = 0; i < tiles.length; i++) - { - tiles[i].index = index; - - SetTileCollision(tiles[i], doesIndexCollide); - } - - if (recalculateFaces) - { - // Recalculate the faces within the area and neighboring tiles - CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer); - } -}; - -module.exports = Fill; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); +var SetTileCollision = require('./SetTileCollision'); + +/** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * @function Phaser.Tilemaps.Components.Fill + * @private + * @since 3.0.0 + * + * @param {integer} index - The tile index to fill the area with. + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {boolean} recalculateFaces - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The tile layer to use. If not given the current layer is used. + */ +var Fill = function (index, tileX, tileY, width, height, recalculateFaces, layer) +{ + var doesIndexCollide = (layer.collideIndexes.indexOf(index) !== -1); + + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + tiles[i].index = index; + + SetTileCollision(tiles[i], doesIndexCollide); + } + + if (recalculateFaces) + { + // Recalculate the faces within the area and neighboring tiles + CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer); + } +}; + +module.exports = Fill; diff --git a/src/tilemaps/components/FilterTiles.js b/src/tilemaps/components/FilterTiles.js index a8ed61193..184e42754 100644 --- a/src/tilemaps/components/FilterTiles.js +++ b/src/tilemaps/components/FilterTiles.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * - * @function Phaser.Tilemaps.Components.FilterTiles - * @private - * @since 3.0.0 - * - * @param {function} callback - The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. - * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. - * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile[]} The filtered array of Tiles. - */ -var FilterTiles = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); - - return tiles.filter(callback, context); -}; - -module.exports = FilterTiles; - +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @function Phaser.Tilemaps.Components.FilterTiles + * @private + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} The filtered array of Tiles. + */ +var FilterTiles = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + + return tiles.filter(callback, context); +}; + +module.exports = FilterTiles; + diff --git a/src/tilemaps/components/FindByIndex.js b/src/tilemaps/components/FindByIndex.js index bb7ef8499..754aa9c34 100644 --- a/src/tilemaps/components/FindByIndex.js +++ b/src/tilemaps/components/FindByIndex.js @@ -1,82 +1,82 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * - * @function Phaser.Tilemaps.Components.FindByIndex - * @private - * @since 3.0.0 - * - * @param {integer} index - The tile index value to search for. - * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. - * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the - * bottom-right. Otherwise it scans from the top-left. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {?Phaser.Tilemaps.Tile} The first (or n skipped) tile with the matching index. - */ -var FindByIndex = function (findIndex, skip, reverse, layer) -{ - if (skip === undefined) { skip = 0; } - if (reverse === undefined) { reverse = false; } - - var count = 0; - var tx; - var ty; - var tile; - - if (reverse) - { - for (ty = layer.height - 1; ty >= 0; ty--) - { - for (tx = layer.width - 1; tx >= 0; tx--) - { - tile = layer.data[ty][tx]; - if (tile && tile.index === findIndex) - { - if (count === skip) - { - return tile; - } - else - { - count += 1; - } - } - } - } - } - else - { - for (ty = 0; ty < layer.height; ty++) - { - for (tx = 0; tx < layer.width; tx++) - { - tile = layer.data[ty][tx]; - if (tile && tile.index === findIndex) - { - if (count === skip) - { - return tile; - } - else - { - count += 1; - } - } - } - } - } - - return null; -}; - -module.exports = FindByIndex; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * + * @function Phaser.Tilemaps.Components.FindByIndex + * @private + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?Phaser.Tilemaps.Tile} The first (or n skipped) tile with the matching index. + */ +var FindByIndex = function (findIndex, skip, reverse, layer) +{ + if (skip === undefined) { skip = 0; } + if (reverse === undefined) { reverse = false; } + + var count = 0; + var tx; + var ty; + var tile; + + if (reverse) + { + for (ty = layer.height - 1; ty >= 0; ty--) + { + for (tx = layer.width - 1; tx >= 0; tx--) + { + tile = layer.data[ty][tx]; + if (tile && tile.index === findIndex) + { + if (count === skip) + { + return tile; + } + else + { + count += 1; + } + } + } + } + } + else + { + for (ty = 0; ty < layer.height; ty++) + { + for (tx = 0; tx < layer.width; tx++) + { + tile = layer.data[ty][tx]; + if (tile && tile.index === findIndex) + { + if (count === skip) + { + return tile; + } + else + { + count += 1; + } + } + } + } + } + + return null; +}; + +module.exports = FindByIndex; diff --git a/src/tilemaps/components/FindTile.js b/src/tilemaps/components/FindTile.js index d23229ea2..1fcf544e0 100644 --- a/src/tilemaps/components/FindTile.js +++ b/src/tilemaps/components/FindTile.js @@ -1,48 +1,48 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * @callback FindTileCallback - * - * @param {Phaser.Tilemaps.Tile} value - The Tile. - * @param {integer} index - The index of the tile. - * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. - * - * @return {boolean} Return `true` if the callback should run, otherwise `false`. - */ - -/** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * - * @function Phaser.Tilemaps.Components.FindTile - * @private - * @since 3.0.0 - * - * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. - * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. - * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {?Phaser.Tilemaps.Tile} A Tile that matches the search, or null if no Tile found - */ -var FindTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); - return tiles.find(callback, context) || null; -}; - -module.exports = FindTile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * @callback FindTileCallback + * + * @param {Phaser.Tilemaps.Tile} value - The Tile. + * @param {integer} index - The index of the tile. + * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. + * + * @return {boolean} Return `true` if the callback should run, otherwise `false`. + */ + +/** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * + * @function Phaser.Tilemaps.Components.FindTile + * @private + * @since 3.0.0 + * + * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?Phaser.Tilemaps.Tile} A Tile that matches the search, or null if no Tile found + */ +var FindTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + return tiles.find(callback, context) || null; +}; + +module.exports = FindTile; diff --git a/src/tilemaps/components/ForEachTile.js b/src/tilemaps/components/ForEachTile.js index 0ea6c0b10..3710e8347 100644 --- a/src/tilemaps/components/ForEachTile.js +++ b/src/tilemaps/components/ForEachTile.js @@ -1,44 +1,44 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * @callback EachTileCallback - * - * @param {Phaser.Tilemaps.Tile} value - The Tile. - * @param {integer} index - The index of the tile. - * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. - */ - -/** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * - * @function Phaser.Tilemaps.Components.ForEachTile - * @private - * @since 3.0.0 - * - * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. - * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. - * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var ForEachTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); - - tiles.forEach(callback, context); -}; - -module.exports = ForEachTile; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * @callback EachTileCallback + * + * @param {Phaser.Tilemaps.Tile} value - The Tile. + * @param {integer} index - The index of the tile. + * @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects. + */ + +/** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * @function Phaser.Tilemaps.Components.ForEachTile + * @private + * @since 3.0.0 + * + * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var ForEachTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); + + tiles.forEach(callback, context); +}; + +module.exports = ForEachTile; diff --git a/src/tilemaps/components/GetTileAt.js b/src/tilemaps/components/GetTileAt.js index 10bc3c657..133be8b1e 100644 --- a/src/tilemaps/components/GetTileAt.js +++ b/src/tilemaps/components/GetTileAt.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var IsInLayerBounds = require('./IsInLayerBounds'); - -/** - * Gets a tile at the given tile coordinates from the given layer. - * - * @function Phaser.Tilemaps.Components.GetTileAt - * @private - * @since 3.0.0 - * - * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). - * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). - * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates - * were invalid. - */ -var GetTileAt = function (tileX, tileY, nonNull, layer) -{ - if (nonNull === undefined) { nonNull = false; } - - if (IsInLayerBounds(tileX, tileY, layer)) - { - var tile = layer.data[tileY][tileX] || null; - if (tile === null) - { - return null; - } - else if (tile.index === -1) - { - return nonNull ? tile : null; - } - else - { - return tile; - } - } - else - { - return null; - } -}; - -module.exports = GetTileAt; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsInLayerBounds = require('./IsInLayerBounds'); + +/** + * Gets a tile at the given tile coordinates from the given layer. + * + * @function Phaser.Tilemaps.Components.GetTileAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ +var GetTileAt = function (tileX, tileY, nonNull, layer) +{ + if (nonNull === undefined) { nonNull = false; } + + if (IsInLayerBounds(tileX, tileY, layer)) + { + var tile = layer.data[tileY][tileX] || null; + if (tile === null) + { + return null; + } + else if (tile.index === -1) + { + return nonNull ? tile : null; + } + else + { + return tile; + } + } + else + { + return null; + } +}; + +module.exports = GetTileAt; diff --git a/src/tilemaps/components/GetTileAtWorldXY.js b/src/tilemaps/components/GetTileAtWorldXY.js index 9a17301e3..53c8036f3 100644 --- a/src/tilemaps/components/GetTileAtWorldXY.js +++ b/src/tilemaps/components/GetTileAtWorldXY.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTileAt = require('./GetTileAt'); - -/** - * Gets a tile at the given world coordinates from the given layer. - * - * @function Phaser.Tilemaps.Components.GetTileAtWorldXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - X position to get the tile from (given in pixels) - * @param {number} worldY - Y position to get the tile from (given in pixels) - * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates - * were invalid. - */ -var GetTileAtWorldXY = function (worldX, worldY, nonNull, camera, layer) -{ - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; - return GetTileAt(tileX, tileY, nonNull, layer); -}; - -module.exports = GetTileAtWorldXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTileAt = require('./GetTileAt'); + +/** + * Gets a tile at the given world coordinates from the given layer. + * + * @function Phaser.Tilemaps.Components.GetTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ +var GetTileAtWorldXY = function (worldX, worldY, nonNull, camera, layer) +{ + var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); + var tileX = point.x; + var tileY = point.y; + return GetTileAt(tileX, tileY, nonNull, layer); +}; + +module.exports = GetTileAtWorldXY; diff --git a/src/tilemaps/components/GetTilesWithin.js b/src/tilemaps/components/GetTilesWithin.js index 0a9e43b5e..3af56e31e 100644 --- a/src/tilemaps/components/GetTilesWithin.js +++ b/src/tilemaps/components/GetTilesWithin.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * - * @function Phaser.Tilemaps.Components.GetTilesWithin - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} width - How many tiles wide from the `tileX` index the area will be. - * @param {integer} height - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.GetTilesWithinFilteringOptions} GetTilesWithinFilteringOptions - Optional filters to apply when getting the tiles. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. - */ -var GetTilesWithin = function (tileX, tileY, width, height, filteringOptions, layer) -{ - if (tileX === undefined) { tileX = 0; } - if (tileY === undefined) { tileY = 0; } - if (width === undefined) { width = layer.width; } - if (height === undefined) { height = layer.height; } - - var isNotEmpty = GetFastValue(filteringOptions, 'isNotEmpty', false); - var isColliding = GetFastValue(filteringOptions, 'isColliding', false); - var hasInterestingFace = GetFastValue(filteringOptions, 'hasInterestingFace', false); - - // Clip x, y to top left of map, while shrinking width/height to match. - if (tileX < 0) - { - width += tileX; - tileX = 0; - } - if (tileY < 0) - { - height += tileY; - tileY = 0; - } - - // Clip width and height to bottom right of map. - if (tileX + width > layer.width) - { - width = Math.max(layer.width - tileX, 0); - } - if (tileY + height > layer.height) - { - height = Math.max(layer.height - tileY, 0); - } - - var results = []; - - for (var ty = tileY; ty < tileY + height; ty++) - { - for (var tx = tileX; tx < tileX + width; tx++) - { - var tile = layer.data[ty][tx]; - if (tile !== null) - { - if (isNotEmpty && tile.index === -1) { continue; } - if (isColliding && !tile.collides) { continue; } - if (hasInterestingFace && !tile.hasInterestingFace) { continue; } - results.push(tile); - } - } - } - - return results; -}; - -module.exports = GetTilesWithin; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * + * @function Phaser.Tilemaps.Components.GetTilesWithin + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.GetTilesWithinFilteringOptions} GetTilesWithinFilteringOptions - Optional filters to apply when getting the tiles. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. + */ +var GetTilesWithin = function (tileX, tileY, width, height, filteringOptions, layer) +{ + if (tileX === undefined) { tileX = 0; } + if (tileY === undefined) { tileY = 0; } + if (width === undefined) { width = layer.width; } + if (height === undefined) { height = layer.height; } + + var isNotEmpty = GetFastValue(filteringOptions, 'isNotEmpty', false); + var isColliding = GetFastValue(filteringOptions, 'isColliding', false); + var hasInterestingFace = GetFastValue(filteringOptions, 'hasInterestingFace', false); + + // Clip x, y to top left of map, while shrinking width/height to match. + if (tileX < 0) + { + width += tileX; + tileX = 0; + } + if (tileY < 0) + { + height += tileY; + tileY = 0; + } + + // Clip width and height to bottom right of map. + if (tileX + width > layer.width) + { + width = Math.max(layer.width - tileX, 0); + } + if (tileY + height > layer.height) + { + height = Math.max(layer.height - tileY, 0); + } + + var results = []; + + for (var ty = tileY; ty < tileY + height; ty++) + { + for (var tx = tileX; tx < tileX + width; tx++) + { + var tile = layer.data[ty][tx]; + if (tile !== null) + { + if (isNotEmpty && tile.index === -1) { continue; } + if (isColliding && !tile.collides) { continue; } + if (hasInterestingFace && !tile.hasInterestingFace) { continue; } + results.push(tile); + } + } + } + + return results; +}; + +module.exports = GetTilesWithin; diff --git a/src/tilemaps/components/GetTilesWithinShape.js b/src/tilemaps/components/GetTilesWithinShape.js index 36a7b6f36..f60aae8ca 100644 --- a/src/tilemaps/components/GetTilesWithinShape.js +++ b/src/tilemaps/components/GetTilesWithinShape.js @@ -1,91 +1,91 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Geom = require('../../geom/'); -var GetTilesWithin = require('./GetTilesWithin'); -var Intersects = require('../../geom/intersects/'); -var NOOP = require('../../utils/NOOP'); - - -var TriangleToRectangle = function (triangle, rect) -{ - return Intersects.RectangleToTriangle(rect, triangle); -}; - -// Note: Could possibly be optimized by copying the shape and shifting it into tilemapLayer -// coordinates instead of shifting the tiles. - -/** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * - * @function Phaser.Tilemaps.Components.GetTilesWithinShape - * @private - * @since 3.0.0 - * - * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates - * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. - * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. - * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. - */ -var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) -{ - if (shape === undefined) { return []; } - - // intersectTest is a function with parameters: shape, rect - var intersectTest = NOOP; - if (shape instanceof Geom.Circle) { intersectTest = Intersects.CircleToRectangle; } - else if (shape instanceof Geom.Rectangle) { intersectTest = Intersects.RectangleToRectangle; } - else if (shape instanceof Geom.Triangle) { intersectTest = TriangleToRectangle; } - else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle; } - - // Top left corner of the shapes's bounding box, rounded down to include partial tiles - var pointStart = layer.tilemapLayer.worldToTileXY(shape.left, shape.top, true, undefined, camera); - var xStart = pointStart.x; - var yStart = pointStart.y; - - // Bottom right corner of the shapes's bounding box, rounded up to include partial tiles - var pointEnd = layer.tilemapLayer.worldToTileXY(shape.right, shape.bottom, true, undefined, camera); - var xEnd = Math.ceil(pointEnd.x); - var yEnd = Math.ceil(pointEnd.y); - - // 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). - var width = Math.max(xEnd - xStart, 1); - var height = Math.max(yEnd - yStart, 1); - var tiles = GetTilesWithin(xStart, yStart, width, height, filteringOptions, layer); - - var tileWidth = layer.tileWidth; - var tileHeight = layer.tileHeight; - if (layer.tilemapLayer) - { - tileWidth *= layer.tilemapLayer.scaleX; - tileHeight *= layer.tilemapLayer.scaleY; - } - - var results = []; - var tileRect = new Geom.Rectangle(0, 0, tileWidth, tileHeight); - for (var i = 0; i < tiles.length; i++) - { - var tile = tiles[i]; - var point = layer.tilemapLayer.tileToWorldXY(tile.x, tile.y, undefined, camera); - tileRect.x = point.x; - tileRect.y = point.y; - if (intersectTest(shape, tileRect)) - { - results.push(tile); - } - } - - return results; -}; - -module.exports = GetTilesWithinShape; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Geom = require('../../geom/'); +var GetTilesWithin = require('./GetTilesWithin'); +var Intersects = require('../../geom/intersects/'); +var NOOP = require('../../utils/NOOP'); + + +var TriangleToRectangle = function (triangle, rect) +{ + return Intersects.RectangleToTriangle(rect, triangle); +}; + +// Note: Could possibly be optimized by copying the shape and shifting it into tilemapLayer +// coordinates instead of shifting the tiles. + +/** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * + * @function Phaser.Tilemaps.Components.GetTilesWithinShape + * @private + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. + */ +var GetTilesWithinShape = function (shape, filteringOptions, camera, layer) +{ + if (shape === undefined) { return []; } + + // intersectTest is a function with parameters: shape, rect + var intersectTest = NOOP; + if (shape instanceof Geom.Circle) { intersectTest = Intersects.CircleToRectangle; } + else if (shape instanceof Geom.Rectangle) { intersectTest = Intersects.RectangleToRectangle; } + else if (shape instanceof Geom.Triangle) { intersectTest = TriangleToRectangle; } + else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle; } + + // Top left corner of the shapes's bounding box, rounded down to include partial tiles + var pointStart = layer.tilemapLayer.worldToTileXY(shape.left, shape.top, true, undefined, camera); + var xStart = pointStart.x; + var yStart = pointStart.y; + + // Bottom right corner of the shapes's bounding box, rounded up to include partial tiles + var pointEnd = layer.tilemapLayer.worldToTileXY(shape.right, shape.bottom, true, undefined, camera); + var xEnd = Math.ceil(pointEnd.x); + var yEnd = Math.ceil(pointEnd.y); + + // 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). + var width = Math.max(xEnd - xStart, 1); + var height = Math.max(yEnd - yStart, 1); + var tiles = GetTilesWithin(xStart, yStart, width, height, filteringOptions, layer); + + var tileWidth = layer.tileWidth; + var tileHeight = layer.tileHeight; + if (layer.tilemapLayer) + { + tileWidth *= layer.tilemapLayer.scaleX; + tileHeight *= layer.tilemapLayer.scaleY; + } + + var results = []; + var tileRect = new Geom.Rectangle(0, 0, tileWidth, tileHeight); + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + var point = layer.tilemapLayer.tileToWorldXY(tile.x, tile.y, undefined, camera); + tileRect.x = point.x; + tileRect.y = point.y; + if (intersectTest(shape, tileRect)) + { + results.push(tile); + } + } + + return results; +}; + +module.exports = GetTilesWithinShape; diff --git a/src/tilemaps/components/GetTilesWithinWorldXY.js b/src/tilemaps/components/GetTilesWithinWorldXY.js index faddfa1aa..55d43dbed 100644 --- a/src/tilemaps/components/GetTilesWithinWorldXY.js +++ b/src/tilemaps/components/GetTilesWithinWorldXY.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * - * @function Phaser.Tilemaps.Components.GetTilesWithinWorldXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The world x coordinate for the top-left of the area. - * @param {number} worldY - The world y coordinate for the top-left of the area. - * @param {number} width - The width of the area. - * @param {number} height - The height of the area. - * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. - * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. - * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. - */ -var GetTilesWithinWorldXY = function (worldX, worldY, width, height, filteringOptions, camera, layer) -{ - - // Top left corner of the rect, rounded down to include partial tiles - var pointStart = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var xStart = pointStart.x; - var yStart = pointStart.y; - - // Bottom right corner of the rect, rounded up to include partial tiles - var pointEnd = layer.tilemapLayer.worldToTileXY(worldX + width, worldY + height, false, undefined, camera); - var xEnd = Math.ceil(pointEnd.x); - var yEnd = Math.ceil(pointEnd.y); - - return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer); -}; - -module.exports = GetTilesWithinWorldXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * + * @function Phaser.Tilemaps.Components.GetTilesWithinWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The world x coordinate for the top-left of the area. + * @param {number} worldY - The world y coordinate for the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {object} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index. + * @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side. + * @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile[]} Array of Tile objects. + */ +var GetTilesWithinWorldXY = function (worldX, worldY, width, height, filteringOptions, camera, layer) +{ + + // Top left corner of the rect, rounded down to include partial tiles + var pointStart = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); + var xStart = pointStart.x; + var yStart = pointStart.y; + + // Bottom right corner of the rect, rounded up to include partial tiles + var pointEnd = layer.tilemapLayer.worldToTileXY(worldX + width, worldY + height, false, undefined, camera); + var xEnd = Math.ceil(pointEnd.x); + var yEnd = Math.ceil(pointEnd.y); + + return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer); +}; + +module.exports = GetTilesWithinWorldXY; diff --git a/src/tilemaps/components/HasTileAt.js b/src/tilemaps/components/HasTileAt.js index a87e87fe8..b7160d4f5 100644 --- a/src/tilemaps/components/HasTileAt.js +++ b/src/tilemaps/components/HasTileAt.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var IsInLayerBounds = require('./IsInLayerBounds'); - -/** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * @function Phaser.Tilemaps.Components.HasTileAt - * @private - * @since 3.0.0 - * - * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). - * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {?boolean} Returns a boolean, or null if the layer given was invalid. - */ -var HasTileAt = function (tileX, tileY, layer) -{ - if (IsInLayerBounds(tileX, tileY, layer)) - { - var tile = layer.data[tileY][tileX]; - return (tile !== null && tile.index > -1); - } - else - { - return false; - } - -}; - -module.exports = HasTileAt; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsInLayerBounds = require('./IsInLayerBounds'); + +/** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @function Phaser.Tilemaps.Components.HasTileAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ +var HasTileAt = function (tileX, tileY, layer) +{ + if (IsInLayerBounds(tileX, tileY, layer)) + { + var tile = layer.data[tileY][tileX]; + return (tile !== null && tile.index > -1); + } + else + { + return false; + } + +}; + +module.exports = HasTileAt; diff --git a/src/tilemaps/components/HasTileAtWorldXY.js b/src/tilemaps/components/HasTileAtWorldXY.js index 4e8290008..96e057bc6 100644 --- a/src/tilemaps/components/HasTileAtWorldXY.js +++ b/src/tilemaps/components/HasTileAtWorldXY.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var HasTileAt = require('./HasTileAt'); - -/** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * @function Phaser.Tilemaps.Components.HasTileAtWorldXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The X coordinate of the world position. - * @param {number} worldY - The Y coordinate of the world position. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {?boolean} Returns a boolean, or null if the layer given was invalid. - */ -var HasTileAtWorldXY = function (worldX, worldY, camera, layer) -{ - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; - return HasTileAt(tileX, tileY, layer); -}; - -module.exports = HasTileAtWorldXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HasTileAt = require('./HasTileAt'); + +/** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @function Phaser.Tilemaps.Components.HasTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate of the world position. + * @param {number} worldY - The Y coordinate of the world position. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {?boolean} Returns a boolean, or null if the layer given was invalid. + */ +var HasTileAtWorldXY = function (worldX, worldY, camera, layer) +{ + var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); + var tileX = point.x; + var tileY = point.y; + return HasTileAt(tileX, tileY, layer); +}; + +module.exports = HasTileAtWorldXY; diff --git a/src/tilemaps/components/IsInLayerBounds.js b/src/tilemaps/components/IsInLayerBounds.js index fa2dd2428..84de2b7f2 100644 --- a/src/tilemaps/components/IsInLayerBounds.js +++ b/src/tilemaps/components/IsInLayerBounds.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if the given tile coordinates are within the bounds of the layer. - * - * @function Phaser.Tilemaps.Components.IsInLayerBounds - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {boolean} `true` if the tile coordinates are within the bounds of the layer, otherwise `false`. - */ -var IsInLayerBounds = function (tileX, tileY, layer) -{ - return (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height); -}; - -module.exports = IsInLayerBounds; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if the given tile coordinates are within the bounds of the layer. + * + * @function Phaser.Tilemaps.Components.IsInLayerBounds + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {boolean} `true` if the tile coordinates are within the bounds of the layer, otherwise `false`. + */ +var IsInLayerBounds = function (tileX, tileY, layer) +{ + return (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height); +}; + +module.exports = IsInLayerBounds; diff --git a/src/tilemaps/components/PutTileAt.js b/src/tilemaps/components/PutTileAt.js index 5930f8847..037b8db29 100644 --- a/src/tilemaps/components/PutTileAt.js +++ b/src/tilemaps/components/PutTileAt.js @@ -1,74 +1,74 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Tile = require('../Tile'); -var IsInLayerBounds = require('./IsInLayerBounds'); -var CalculateFacesAt = require('./CalculateFacesAt'); -var SetTileCollision = require('./SetTileCollision'); - -/** - * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index - * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified - * location. If you pass in an index, only the index at the specified location will be changed. - * Collision information will be recalculated at the specified location. - * - * @function Phaser.Tilemaps.Components.PutTileAt - * @private - * @since 3.0.0 - * - * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. - */ -var PutTileAt = function (tile, tileX, tileY, recalculateFaces, layer) -{ - if (!IsInLayerBounds(tileX, tileY, layer)) { return null; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - var oldTile = layer.data[tileY][tileX]; - var oldTileCollides = oldTile && oldTile.collides; - - if (tile instanceof Tile) - { - if (layer.data[tileY][tileX] === null) - { - layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, layer.tileWidth, layer.tileHeight); - } - layer.data[tileY][tileX].copy(tile); - } - else - { - var index = tile; - if (layer.data[tileY][tileX] === null) - { - layer.data[tileY][tileX] = new Tile(layer, index, tileX, tileY, layer.tileWidth, layer.tileHeight); - } - else - { - layer.data[tileY][tileX].index = index; - } - } - - // Updating colliding flag on the new tile - var newTile = layer.data[tileY][tileX]; - var collides = layer.collideIndexes.indexOf(newTile.index) !== -1; - SetTileCollision(newTile, collides); - - // Recalculate faces only if the colliding flag at (tileX, tileY) has changed - if (recalculateFaces && (oldTileCollides !== newTile.collides)) - { - CalculateFacesAt(tileX, tileY, layer); - } - - return newTile; -}; - -module.exports = PutTileAt; - +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tile = require('../Tile'); +var IsInLayerBounds = require('./IsInLayerBounds'); +var CalculateFacesAt = require('./CalculateFacesAt'); +var SetTileCollision = require('./SetTileCollision'); + +/** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * @function Phaser.Tilemaps.Components.PutTileAt + * @private + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. + */ +var PutTileAt = function (tile, tileX, tileY, recalculateFaces, layer) +{ + if (!IsInLayerBounds(tileX, tileY, layer)) { return null; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + var oldTile = layer.data[tileY][tileX]; + var oldTileCollides = oldTile && oldTile.collides; + + if (tile instanceof Tile) + { + if (layer.data[tileY][tileX] === null) + { + layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, layer.tileWidth, layer.tileHeight); + } + layer.data[tileY][tileX].copy(tile); + } + else + { + var index = tile; + if (layer.data[tileY][tileX] === null) + { + layer.data[tileY][tileX] = new Tile(layer, index, tileX, tileY, layer.tileWidth, layer.tileHeight); + } + else + { + layer.data[tileY][tileX].index = index; + } + } + + // Updating colliding flag on the new tile + var newTile = layer.data[tileY][tileX]; + var collides = layer.collideIndexes.indexOf(newTile.index) !== -1; + SetTileCollision(newTile, collides); + + // Recalculate faces only if the colliding flag at (tileX, tileY) has changed + if (recalculateFaces && (oldTileCollides !== newTile.collides)) + { + CalculateFacesAt(tileX, tileY, layer); + } + + return newTile; +}; + +module.exports = PutTileAt; + diff --git a/src/tilemaps/components/PutTileAtWorldXY.js b/src/tilemaps/components/PutTileAtWorldXY.js index 8df2a1144..acce051b4 100644 --- a/src/tilemaps/components/PutTileAtWorldXY.js +++ b/src/tilemaps/components/PutTileAtWorldXY.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var PutTileAt = require('./PutTileAt'); - -/** - * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either - * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the - * specified location. If you pass in an index, only the index at the specified location will be - * changed. Collision information will be recalculated at the specified location. - * - * @function Phaser.Tilemaps.Components.PutTileAtWorldXY - * @private - * @since 3.0.0 - * - * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. - */ -var PutTileAtWorldXY = function (tile, worldX, worldY, recalculateFaces, camera, layer) -{ - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; - return PutTileAt(tile, tileX, tileY, recalculateFaces, layer); -}; - -module.exports = PutTileAtWorldXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var PutTileAt = require('./PutTileAt'); + +/** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * @function Phaser.Tilemaps.Components.PutTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map. + */ +var PutTileAtWorldXY = function (tile, worldX, worldY, recalculateFaces, camera, layer) +{ + var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); + var tileX = point.x; + var tileY = point.y; + return PutTileAt(tile, tileX, tileY, recalculateFaces, layer); +}; + +module.exports = PutTileAtWorldXY; diff --git a/src/tilemaps/components/PutTilesAt.js b/src/tilemaps/components/PutTilesAt.js index d3334acc0..4bc323b13 100644 --- a/src/tilemaps/components/PutTilesAt.js +++ b/src/tilemaps/components/PutTilesAt.js @@ -1,59 +1,59 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CalculateFacesWithin = require('./CalculateFacesWithin'); -var PutTileAt = require('./PutTileAt'); - -/** - * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified - * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, - * all attributes will be copied over to the specified location. If you pass in an index, only the - * index at the specified location will be changed. Collision information will be recalculated - * within the region tiles were changed. - * - * @function Phaser.Tilemaps.Components.PutTilesAt - * @private - * @since 3.0.0 - * - * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - */ -var PutTilesAt = function (tilesArray, tileX, tileY, recalculateFaces, layer) -{ - if (!Array.isArray(tilesArray)) { return null; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - // Force the input array to be a 2D array - if (!Array.isArray(tilesArray[0])) - { - tilesArray = [ tilesArray ]; - } - - var height = tilesArray.length; - var width = tilesArray[0].length; - - for (var ty = 0; ty < height; ty++) - { - for (var tx = 0; tx < width; tx++) - { - var tile = tilesArray[ty][tx]; - PutTileAt(tile, tileX + tx, tileY + ty, false, layer); - } - } - - if (recalculateFaces) - { - // Recalculate the faces within the destination area and neighboring tiles - CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer); - } -}; - -module.exports = PutTilesAt; - +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CalculateFacesWithin = require('./CalculateFacesWithin'); +var PutTileAt = require('./PutTileAt'); + +/** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * @function Phaser.Tilemaps.Components.PutTilesAt + * @private + * @since 3.0.0 + * + * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + */ +var PutTilesAt = function (tilesArray, tileX, tileY, recalculateFaces, layer) +{ + if (!Array.isArray(tilesArray)) { return null; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + // Force the input array to be a 2D array + if (!Array.isArray(tilesArray[0])) + { + tilesArray = [ tilesArray ]; + } + + var height = tilesArray.length; + var width = tilesArray[0].length; + + for (var ty = 0; ty < height; ty++) + { + for (var tx = 0; tx < width; tx++) + { + var tile = tilesArray[ty][tx]; + PutTileAt(tile, tileX + tx, tileY + ty, false, layer); + } + } + + if (recalculateFaces) + { + // Recalculate the faces within the destination area and neighboring tiles + CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer); + } +}; + +module.exports = PutTilesAt; + diff --git a/src/tilemaps/components/Randomize.js b/src/tilemaps/components/Randomize.js index 84f835823..2fa0c2912 100644 --- a/src/tilemaps/components/Randomize.js +++ b/src/tilemaps/components/Randomize.js @@ -1,52 +1,52 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); -var GetRandom = require('../../utils/array/GetRandom'); - -/** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then - * those will be used for randomly assigning new tile indexes. If an array is not provided, the - * indexes found within the region (excluding -1) will be used for randomly assigning new tile - * indexes. This method only modifies tile indexes and does not change collision information. - * - * @function Phaser.Tilemaps.Components.Randomize - * @private - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var Randomize = function (tileX, tileY, width, height, indexes, layer) -{ - var i; - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - // If no indices are given, then find all the unique indexes within the specified region - if (indexes === undefined) - { - indexes = []; - for (i = 0; i < tiles.length; i++) - { - if (indexes.indexOf(tiles[i].index) === -1) - { - indexes.push(tiles[i].index); - } - } - } - - for (i = 0; i < tiles.length; i++) - { - tiles[i].index = GetRandom(indexes); - } -}; - -module.exports = Randomize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); +var GetRandom = require('../../utils/array/GetRandom'); + +/** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * @function Phaser.Tilemaps.Components.Randomize + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var Randomize = function (tileX, tileY, width, height, indexes, layer) +{ + var i; + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + // If no indices are given, then find all the unique indexes within the specified region + if (indexes === undefined) + { + indexes = []; + for (i = 0; i < tiles.length; i++) + { + if (indexes.indexOf(tiles[i].index) === -1) + { + indexes.push(tiles[i].index); + } + } + } + + for (i = 0; i < tiles.length; i++) + { + tiles[i].index = GetRandom(indexes); + } +}; + +module.exports = Randomize; diff --git a/src/tilemaps/components/RemoveTileAt.js b/src/tilemaps/components/RemoveTileAt.js index 09fdcb9df..c8d32269e 100644 --- a/src/tilemaps/components/RemoveTileAt.js +++ b/src/tilemaps/components/RemoveTileAt.js @@ -1,57 +1,57 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Tile = require('../Tile'); -var IsInLayerBounds = require('./IsInLayerBounds'); -var CalculateFacesAt = require('./CalculateFacesAt'); - -/** - * Removes the tile at the given tile coordinates in the specified layer and updates the layer's - * collision information. - * - * @function Phaser.Tilemaps.Components.RemoveTileAt - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate. - * @param {integer} tileY - The y coordinate. - * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. - */ -var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, layer) -{ - if (replaceWithNull === undefined) { replaceWithNull = false; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - if (!IsInLayerBounds(tileX, tileY, layer)) - { - return null; - } - - var tile = layer.data[tileY][tileX]; - - if (!tile) - { - return null; - } - else - { - layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, layer.tileWidth, layer.tileHeight); - } - - // Recalculate faces only if the removed tile was a colliding tile - if (recalculateFaces && tile && tile.collides) - { - CalculateFacesAt(tileX, tileY, layer); - } - - return tile; -}; - -module.exports = RemoveTileAt; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tile = require('../Tile'); +var IsInLayerBounds = require('./IsInLayerBounds'); +var CalculateFacesAt = require('./CalculateFacesAt'); + +/** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * @function Phaser.Tilemaps.Components.RemoveTileAt + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. + */ +var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, layer) +{ + if (replaceWithNull === undefined) { replaceWithNull = false; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + if (!IsInLayerBounds(tileX, tileY, layer)) + { + return null; + } + + var tile = layer.data[tileY][tileX]; + + if (!tile) + { + return null; + } + else + { + layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, layer.tileWidth, layer.tileHeight); + } + + // Recalculate faces only if the removed tile was a colliding tile + if (recalculateFaces && tile && tile.collides) + { + CalculateFacesAt(tileX, tileY, layer); + } + + return tile; +}; + +module.exports = RemoveTileAt; diff --git a/src/tilemaps/components/RemoveTileAtWorldXY.js b/src/tilemaps/components/RemoveTileAtWorldXY.js index de0f94b39..7407425de 100644 --- a/src/tilemaps/components/RemoveTileAtWorldXY.js +++ b/src/tilemaps/components/RemoveTileAtWorldXY.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RemoveTileAt = require('./RemoveTileAt'); - - -/** - * Removes the tile at the given world coordinates in the specified layer and updates the layer's - * collision information. - * - * @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. - */ -var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) -{ - var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); - var tileX = point.x; - var tileY = point.y; - return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); -}; - -module.exports = RemoveTileAtWorldXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RemoveTileAt = require('./RemoveTileAt'); + + +/** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. + */ +var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) +{ + var point = layer.tilemapLayer.worldToTileXY(worldX, worldY, true, undefined, camera); + var tileX = point.x; + var tileY = point.y; + return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); +}; + +module.exports = RemoveTileAtWorldXY; diff --git a/src/tilemaps/components/RenderDebug.js b/src/tilemaps/components/RenderDebug.js index 6d429772d..359865a12 100644 --- a/src/tilemaps/components/RenderDebug.js +++ b/src/tilemaps/components/RenderDebug.js @@ -1,83 +1,83 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); -var Color = require('../../display/color'); - -var defaultTileColor = new Color(105, 210, 231, 150); -var defaultCollidingTileColor = new Color(243, 134, 48, 200); -var defaultFaceColor = new Color(40, 39, 37, 150); - -/** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * - * @function Phaser.Tilemaps.Components.RenderDebug - * @private - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. - * @param {object} styleConfig - An object specifying the colors to use for the debug drawing. - * @param {?Phaser.Display.Color} [styleConfig.tileColor=blue] - Color to use for drawing a filled rectangle at - * non-colliding tile locations. If set to null, non-colliding tiles will not be drawn. - * @param {?Phaser.Display.Color} [styleConfig.collidingTileColor=orange] - Color to use for drawing a filled - * rectangle at colliding tile locations. If set to null, colliding tiles will not be drawn. - * @param {?Phaser.Display.Color} [styleConfig.faceColor=grey] - Color to use for drawing a line at interesting - * tile faces. If set to null, interesting tile faces will not be drawn. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var RenderDebug = function (graphics, styleConfig, layer) -{ - if (styleConfig === undefined) { styleConfig = {}; } - - // Default colors without needlessly creating Color objects - var tileColor = (styleConfig.tileColor !== undefined) ? styleConfig.tileColor : defaultTileColor; - var collidingTileColor = (styleConfig.collidingTileColor !== undefined) ? styleConfig.collidingTileColor : defaultCollidingTileColor; - var faceColor = (styleConfig.faceColor !== undefined) ? styleConfig.faceColor : defaultFaceColor; - - var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); - - graphics.translateCanvas(layer.tilemapLayer.x, layer.tilemapLayer.y); - graphics.scaleCanvas(layer.tilemapLayer.scaleX, layer.tilemapLayer.scaleY); - - for (var i = 0; i < tiles.length; i++) - { - var tile = tiles[i]; - - var tw = tile.width; - var th = tile.height; - var x = tile.pixelX; - var y = tile.pixelY; - - var color = tile.collides ? collidingTileColor : tileColor; - - if (color !== null) - { - graphics.fillStyle(color.color, color.alpha / 255); - graphics.fillRect(x, y, tw, th); - } - - // Inset the face line to prevent neighboring tile's lines from overlapping - x += 1; - y += 1; - tw -= 2; - th -= 2; - - if (faceColor !== null) - { - graphics.lineStyle(1, faceColor.color, faceColor.alpha / 255); - - if (tile.faceTop) { graphics.lineBetween(x, y, x + tw, y); } - if (tile.faceRight) { graphics.lineBetween(x + tw, y, x + tw, y + th); } - if (tile.faceBottom) { graphics.lineBetween(x, y + th, x + tw, y + th); } - if (tile.faceLeft) { graphics.lineBetween(x, y, x, y + th); } - } - } -}; - -module.exports = RenderDebug; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); +var Color = require('../../display/color'); + +var defaultTileColor = new Color(105, 210, 231, 150); +var defaultCollidingTileColor = new Color(243, 134, 48, 200); +var defaultFaceColor = new Color(40, 39, 37, 150); + +/** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * @function Phaser.Tilemaps.Components.RenderDebug + * @private + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {object} styleConfig - An object specifying the colors to use for the debug drawing. + * @param {?Phaser.Display.Color} [styleConfig.tileColor=blue] - Color to use for drawing a filled rectangle at + * non-colliding tile locations. If set to null, non-colliding tiles will not be drawn. + * @param {?Phaser.Display.Color} [styleConfig.collidingTileColor=orange] - Color to use for drawing a filled + * rectangle at colliding tile locations. If set to null, colliding tiles will not be drawn. + * @param {?Phaser.Display.Color} [styleConfig.faceColor=grey] - Color to use for drawing a line at interesting + * tile faces. If set to null, interesting tile faces will not be drawn. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var RenderDebug = function (graphics, styleConfig, layer) +{ + if (styleConfig === undefined) { styleConfig = {}; } + + // Default colors without needlessly creating Color objects + var tileColor = (styleConfig.tileColor !== undefined) ? styleConfig.tileColor : defaultTileColor; + var collidingTileColor = (styleConfig.collidingTileColor !== undefined) ? styleConfig.collidingTileColor : defaultCollidingTileColor; + var faceColor = (styleConfig.faceColor !== undefined) ? styleConfig.faceColor : defaultFaceColor; + + var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); + + graphics.translateCanvas(layer.tilemapLayer.x, layer.tilemapLayer.y); + graphics.scaleCanvas(layer.tilemapLayer.scaleX, layer.tilemapLayer.scaleY); + + for (var i = 0; i < tiles.length; i++) + { + var tile = tiles[i]; + + var tw = tile.width; + var th = tile.height; + var x = tile.pixelX; + var y = tile.pixelY; + + var color = tile.collides ? collidingTileColor : tileColor; + + if (color !== null) + { + graphics.fillStyle(color.color, color.alpha / 255); + graphics.fillRect(x, y, tw, th); + } + + // Inset the face line to prevent neighboring tile's lines from overlapping + x += 1; + y += 1; + tw -= 2; + th -= 2; + + if (faceColor !== null) + { + graphics.lineStyle(1, faceColor.color, faceColor.alpha / 255); + + if (tile.faceTop) { graphics.lineBetween(x, y, x + tw, y); } + if (tile.faceRight) { graphics.lineBetween(x + tw, y, x + tw, y + th); } + if (tile.faceBottom) { graphics.lineBetween(x, y + th, x + tw, y + th); } + if (tile.faceLeft) { graphics.lineBetween(x, y, x, y + th); } + } + } +}; + +module.exports = RenderDebug; diff --git a/src/tilemaps/components/ReplaceByIndex.js b/src/tilemaps/components/ReplaceByIndex.js index 6ecba2d35..47ab67b73 100644 --- a/src/tilemaps/components/ReplaceByIndex.js +++ b/src/tilemaps/components/ReplaceByIndex.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does - * not change collision information. - * - * @function Phaser.Tilemaps.Components.ReplaceByIndex - * @private - * @since 3.0.0 - * - * @param {integer} findIndex - The index of the tile to search for. - * @param {integer} newIndex - The index of the tile to replace it with. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var ReplaceByIndex = function (findIndex, newIndex, tileX, tileY, width, height, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - for (var i = 0; i < tiles.length; i++) - { - if (tiles[i] && tiles[i].index === findIndex) - { - tiles[i].index = newIndex; - } - } -}; - -module.exports = ReplaceByIndex; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * @function Phaser.Tilemaps.Components.ReplaceByIndex + * @private + * @since 3.0.0 + * + * @param {integer} findIndex - The index of the tile to search for. + * @param {integer} newIndex - The index of the tile to replace it with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var ReplaceByIndex = function (findIndex, newIndex, tileX, tileY, width, height, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + if (tiles[i] && tiles[i].index === findIndex) + { + tiles[i].index = newIndex; + } + } +}; + +module.exports = ReplaceByIndex; diff --git a/src/tilemaps/components/SetCollision.js b/src/tilemaps/components/SetCollision.js index 6d437e89a..97e3bde0a 100644 --- a/src/tilemaps/components/SetCollision.js +++ b/src/tilemaps/components/SetCollision.js @@ -1,63 +1,63 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTileCollision = require('./SetTileCollision'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); -var SetLayerCollisionIndex = require('./SetLayerCollisionIndex'); - -/** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * - * @function Phaser.Tilemaps.Components.SetCollision - * @private - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * @param {boolean} updateLayer - If true, updates the current tiles on the layer. Set to - * false if no tiles have been placed for significant performance boost. - */ -var SetCollision = function (indexes, collides, recalculateFaces, layer, updateLayer) -{ - if (collides === undefined) { collides = true; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - if (!Array.isArray(indexes)) { indexes = [ indexes ]; } - if (updateLayer === undefined) { updateLayer = true; } - - // Update the array of colliding indexes - for (var i = 0; i < indexes.length; i++) - { - SetLayerCollisionIndex(indexes[i], collides, layer); - } - - // Update the tiles - if (updateLayer) - { - for (var ty = 0; ty < layer.height; ty++) - { - for (var tx = 0; tx < layer.width; tx++) - { - var tile = layer.data[ty][tx]; - - if (tile && indexes.indexOf(tile.index) !== -1) - { - SetTileCollision(tile, collides); - } - } - } - } - - if (recalculateFaces) - { - CalculateFacesWithin(0, 0, layer.width, layer.height, layer); - } -}; - -module.exports = SetCollision; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = require('./SetTileCollision'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); +var SetLayerCollisionIndex = require('./SetLayerCollisionIndex'); + +/** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollision + * @private + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * @param {boolean} updateLayer - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + */ +var SetCollision = function (indexes, collides, recalculateFaces, layer, updateLayer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + if (!Array.isArray(indexes)) { indexes = [ indexes ]; } + if (updateLayer === undefined) { updateLayer = true; } + + // Update the array of colliding indexes + for (var i = 0; i < indexes.length; i++) + { + SetLayerCollisionIndex(indexes[i], collides, layer); + } + + // Update the tiles + if (updateLayer) + { + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (tile && indexes.indexOf(tile.index) !== -1) + { + SetTileCollision(tile, collides); + } + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollision; diff --git a/src/tilemaps/components/SetCollisionBetween.js b/src/tilemaps/components/SetCollisionBetween.js index 0781728a0..d8b7e27cb 100644 --- a/src/tilemaps/components/SetCollisionBetween.js +++ b/src/tilemaps/components/SetCollisionBetween.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTileCollision = require('./SetTileCollision'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); -var SetLayerCollisionIndex = require('./SetLayerCollisionIndex'); - -/** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * - * @function Phaser.Tilemaps.Components.SetCollisionBetween - * @private - * @since 3.0.0 - * - * @param {integer} start - The first index of the tile to be set for collision. - * @param {integer} stop - The last index of the tile to be set for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to - * false if no tiles have been placed for significant performance boost. - */ -var SetCollisionBetween = function (start, stop, collides, recalculateFaces, layer, updateLayer) -{ - if (collides === undefined) { collides = true; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - if (updateLayer === undefined) { updateLayer = true; } - - if (start > stop) { return; } - - // Update the array of colliding indexes - for (var index = start; index <= stop; index++) - { - SetLayerCollisionIndex(index, collides, layer); - } - - // Update the tiles - if (updateLayer) - { - for (var ty = 0; ty < layer.height; ty++) - { - for (var tx = 0; tx < layer.width; tx++) - { - var tile = layer.data[ty][tx]; - - if (tile) - { - if (tile.index >= start && tile.index <= stop) - { - SetTileCollision(tile, collides); - } - } - } - } - } - - if (recalculateFaces) - { - CalculateFacesWithin(0, 0, layer.width, layer.height, layer); - } -}; - -module.exports = SetCollisionBetween; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = require('./SetTileCollision'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); +var SetLayerCollisionIndex = require('./SetLayerCollisionIndex'); + +/** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollisionBetween + * @private + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + */ +var SetCollisionBetween = function (start, stop, collides, recalculateFaces, layer, updateLayer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + if (updateLayer === undefined) { updateLayer = true; } + + if (start > stop) { return; } + + // Update the array of colliding indexes + for (var index = start; index <= stop; index++) + { + SetLayerCollisionIndex(index, collides, layer); + } + + // Update the tiles + if (updateLayer) + { + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (tile) + { + if (tile.index >= start && tile.index <= stop) + { + SetTileCollision(tile, collides); + } + } + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionBetween; diff --git a/src/tilemaps/components/SetCollisionByExclusion.js b/src/tilemaps/components/SetCollisionByExclusion.js index 5bde401f8..d4609be5c 100644 --- a/src/tilemaps/components/SetCollisionByExclusion.js +++ b/src/tilemaps/components/SetCollisionByExclusion.js @@ -1,51 +1,51 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTileCollision = require('./SetTileCollision'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); -var SetLayerCollisionIndex = require('./SetLayerCollisionIndex'); - -/** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * - * @function Phaser.Tilemaps.Components.SetCollisionByExclusion - * @private - * @since 3.0.0 - * - * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SetCollisionByExclusion = function (indexes, collides, recalculateFaces, layer) -{ - if (collides === undefined) { collides = true; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - if (!Array.isArray(indexes)) { indexes = [ indexes ]; } - - // Note: this only updates layer.collideIndexes for tile indexes found currently in the layer - for (var ty = 0; ty < layer.height; ty++) - { - for (var tx = 0; tx < layer.width; tx++) - { - var tile = layer.data[ty][tx]; - if (tile && indexes.indexOf(tile.index) === -1) - { - SetTileCollision(tile, collides); - SetLayerCollisionIndex(tile.index, collides, layer); - } - } - } - - if (recalculateFaces) - { - CalculateFacesWithin(0, 0, layer.width, layer.height, layer); - } -}; - -module.exports = SetCollisionByExclusion; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = require('./SetTileCollision'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); +var SetLayerCollisionIndex = require('./SetLayerCollisionIndex'); + +/** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollisionByExclusion + * @private + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetCollisionByExclusion = function (indexes, collides, recalculateFaces, layer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + if (!Array.isArray(indexes)) { indexes = [ indexes ]; } + + // Note: this only updates layer.collideIndexes for tile indexes found currently in the layer + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + if (tile && indexes.indexOf(tile.index) === -1) + { + SetTileCollision(tile, collides); + SetLayerCollisionIndex(tile.index, collides, layer); + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionByExclusion; diff --git a/src/tilemaps/components/SetCollisionByProperty.js b/src/tilemaps/components/SetCollisionByProperty.js index b3b887d29..3c71c3b8e 100644 --- a/src/tilemaps/components/SetCollisionByProperty.js +++ b/src/tilemaps/components/SetCollisionByProperty.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTileCollision = require('./SetTileCollision'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); -var HasValue = require('../../utils/object/HasValue'); - -/** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * - * @function Phaser.Tilemaps.Components.SetCollisionByProperty - * @private - * @since 3.0.0 - * - * @param {object} properties - An object with tile properties and corresponding values that should be checked. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SetCollisionByProperty = function (properties, collides, recalculateFaces, layer) -{ - if (collides === undefined) { collides = true; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - for (var ty = 0; ty < layer.height; ty++) - { - for (var tx = 0; tx < layer.width; tx++) - { - var tile = layer.data[ty][tx]; - - if (!tile) { continue; } - - for (var property in properties) - { - if (!HasValue(tile.properties, property)) { continue; } - - var values = properties[property]; - if (!Array.isArray(values)) - { - values = [ values ]; - } - - for (var i = 0; i < values.length; i++) - { - if (tile.properties[property] === values[i]) - { - SetTileCollision(tile, collides); - } - } - } - } - } - - if (recalculateFaces) - { - CalculateFacesWithin(0, 0, layer.width, layer.height, layer); - } -}; - -module.exports = SetCollisionByProperty; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = require('./SetTileCollision'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); +var HasValue = require('../../utils/object/HasValue'); + +/** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * @function Phaser.Tilemaps.Components.SetCollisionByProperty + * @private + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetCollisionByProperty = function (properties, collides, recalculateFaces, layer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (!tile) { continue; } + + for (var property in properties) + { + if (!HasValue(tile.properties, property)) { continue; } + + var values = properties[property]; + if (!Array.isArray(values)) + { + values = [ values ]; + } + + for (var i = 0; i < values.length; i++) + { + if (tile.properties[property] === values[i]) + { + SetTileCollision(tile, collides); + } + } + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionByProperty; diff --git a/src/tilemaps/components/SetCollisionFromCollisionGroup.js b/src/tilemaps/components/SetCollisionFromCollisionGroup.js index a2e103365..d16430162 100644 --- a/src/tilemaps/components/SetCollisionFromCollisionGroup.js +++ b/src/tilemaps/components/SetCollisionFromCollisionGroup.js @@ -1,54 +1,54 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SetTileCollision = require('./SetTileCollision'); -var CalculateFacesWithin = require('./CalculateFacesWithin'); - -/** - * Sets collision on the tiles within a layer by checking each tile's collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tile's collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * - * @function Phaser.Tilemaps.Components.SetCollisionFromCollisionGroup - * @private - * @since 3.0.0 - * - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SetCollisionFromCollisionGroup = function (collides, recalculateFaces, layer) -{ - if (collides === undefined) { collides = true; } - if (recalculateFaces === undefined) { recalculateFaces = true; } - - for (var ty = 0; ty < layer.height; ty++) - { - for (var tx = 0; tx < layer.width; tx++) - { - var tile = layer.data[ty][tx]; - - if (!tile) { continue; } - - var collisionGroup = tile.getCollisionGroup(); - - // It's possible in Tiled to have a collision group without any shapes, e.g. create a - // shape and then delete the shape. - if (collisionGroup && collisionGroup.objects && collisionGroup.objects.length > 0) - { - SetTileCollision(tile, collides); - } - } - } - - if (recalculateFaces) - { - CalculateFacesWithin(0, 0, layer.width, layer.height, layer); - } -}; - -module.exports = SetCollisionFromCollisionGroup; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SetTileCollision = require('./SetTileCollision'); +var CalculateFacesWithin = require('./CalculateFacesWithin'); + +/** + * Sets collision on the tiles within a layer by checking each tile's collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tile's collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * @function Phaser.Tilemaps.Components.SetCollisionFromCollisionGroup + * @private + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetCollisionFromCollisionGroup = function (collides, recalculateFaces, layer) +{ + if (collides === undefined) { collides = true; } + if (recalculateFaces === undefined) { recalculateFaces = true; } + + for (var ty = 0; ty < layer.height; ty++) + { + for (var tx = 0; tx < layer.width; tx++) + { + var tile = layer.data[ty][tx]; + + if (!tile) { continue; } + + var collisionGroup = tile.getCollisionGroup(); + + // It's possible in Tiled to have a collision group without any shapes, e.g. create a + // shape and then delete the shape. + if (collisionGroup && collisionGroup.objects && collisionGroup.objects.length > 0) + { + SetTileCollision(tile, collides); + } + } + } + + if (recalculateFaces) + { + CalculateFacesWithin(0, 0, layer.width, layer.height, layer); + } +}; + +module.exports = SetCollisionFromCollisionGroup; diff --git a/src/tilemaps/components/SetLayerCollisionIndex.js b/src/tilemaps/components/SetLayerCollisionIndex.js index 6b1e4dd17..0cc282956 100644 --- a/src/tilemaps/components/SetLayerCollisionIndex.js +++ b/src/tilemaps/components/SetLayerCollisionIndex.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Internally used method to keep track of the tile indexes that collide within a layer. This - * updates LayerData.collideIndexes to either contain or not contain the given `tileIndex`. - * - * @function Phaser.Tilemaps.Components.SetLayerCollisionIndex - * @private - * @since 3.0.0 - * - * @param {integer} tileIndex - The tile index to set the collision boolean for. - * @param {boolean} [collides=true] - Should the tile index collide or not? - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SetLayerCollisionIndex = function (tileIndex, collides, layer) -{ - var loc = layer.collideIndexes.indexOf(tileIndex); - - if (collides && loc === -1) - { - layer.collideIndexes.push(tileIndex); - } - else if (!collides && loc !== -1) - { - layer.collideIndexes.splice(loc, 1); - } -}; - -module.exports = SetLayerCollisionIndex; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internally used method to keep track of the tile indexes that collide within a layer. This + * updates LayerData.collideIndexes to either contain or not contain the given `tileIndex`. + * + * @function Phaser.Tilemaps.Components.SetLayerCollisionIndex + * @private + * @since 3.0.0 + * + * @param {integer} tileIndex - The tile index to set the collision boolean for. + * @param {boolean} [collides=true] - Should the tile index collide or not? + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetLayerCollisionIndex = function (tileIndex, collides, layer) +{ + var loc = layer.collideIndexes.indexOf(tileIndex); + + if (collides && loc === -1) + { + layer.collideIndexes.push(tileIndex); + } + else if (!collides && loc !== -1) + { + layer.collideIndexes.splice(loc, 1); + } +}; + +module.exports = SetLayerCollisionIndex; diff --git a/src/tilemaps/components/SetTileCollision.js b/src/tilemaps/components/SetTileCollision.js index 94f13193b..ca7dfba83 100644 --- a/src/tilemaps/components/SetTileCollision.js +++ b/src/tilemaps/components/SetTileCollision.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Internally used method to set the colliding state of a tile. This does not recalculate - * interesting faces. - * - * @function Phaser.Tilemaps.Components.SetTileCollision - * @private - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.Tile} tile - The Tile to set the collision on. - * @param {boolean} [collides=true] - Should the tile index collide or not? - */ -var SetTileCollision = function (tile, collides) -{ - if (collides) - { - tile.setCollision(true, true, true, true, false); - } - else - { - tile.resetCollision(false); - } -}; - -module.exports = SetTileCollision; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internally used method to set the colliding state of a tile. This does not recalculate + * interesting faces. + * + * @function Phaser.Tilemaps.Components.SetTileCollision + * @private + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.Tile} tile - The Tile to set the collision on. + * @param {boolean} [collides=true] - Should the tile index collide or not? + */ +var SetTileCollision = function (tile, collides) +{ + if (collides) + { + tile.setCollision(true, true, true, true, false); + } + else + { + tile.resetCollision(false); + } +}; + +module.exports = SetTileCollision; diff --git a/src/tilemaps/components/SetTileIndexCallback.js b/src/tilemaps/components/SetTileIndexCallback.js index 0608641e6..b3947c52a 100644 --- a/src/tilemaps/components/SetTileIndexCallback.js +++ b/src/tilemaps/components/SetTileIndexCallback.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * - * @function Phaser.Tilemaps.Components.SetTileIndexCallback - * @private - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} callbackContext - The context under which the callback is called. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SetTileIndexCallback = function (indexes, callback, callbackContext, layer) -{ - if (typeof indexes === 'number') - { - layer.callbacks[indexes] = (callback !== null) - ? { callback: callback, callbackContext: callbackContext } - : undefined; - } - else - { - for (var i = 0, len = indexes.length; i < len; i++) - { - layer.callbacks[indexes[i]] = (callback !== null) - ? { callback: callback, callbackContext: callbackContext } - : undefined; - } - } -}; - -module.exports = SetTileIndexCallback; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * @function Phaser.Tilemaps.Components.SetTileIndexCallback + * @private + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetTileIndexCallback = function (indexes, callback, callbackContext, layer) +{ + if (typeof indexes === 'number') + { + layer.callbacks[indexes] = (callback !== null) + ? { callback: callback, callbackContext: callbackContext } + : undefined; + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + layer.callbacks[indexes[i]] = (callback !== null) + ? { callback: callback, callbackContext: callbackContext } + : undefined; + } + } +}; + +module.exports = SetTileIndexCallback; diff --git a/src/tilemaps/components/SetTileLocationCallback.js b/src/tilemaps/components/SetTileLocationCallback.js index c97eb9cc8..00864d529 100644 --- a/src/tilemaps/components/SetTileLocationCallback.js +++ b/src/tilemaps/components/SetTileLocationCallback.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * - * @function Phaser.Tilemaps.Components.SetTileLocationCallback - * @private - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} callbackContext - The context under which the callback is called. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SetTileLocationCallback = function (tileX, tileY, width, height, callback, callbackContext, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - for (var i = 0; i < tiles.length; i++) - { - tiles[i].setCollisionCallback(callback, callbackContext); - } - -}; - -module.exports = SetTileLocationCallback; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * @function Phaser.Tilemaps.Components.SetTileLocationCallback + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SetTileLocationCallback = function (tileX, tileY, width, height, callback, callbackContext, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + for (var i = 0; i < tiles.length; i++) + { + tiles[i].setCollisionCallback(callback, callbackContext); + } + +}; + +module.exports = SetTileLocationCallback; diff --git a/src/tilemaps/components/Shuffle.js b/src/tilemaps/components/Shuffle.js index ab51df45e..fe2c82080 100644 --- a/src/tilemaps/components/Shuffle.js +++ b/src/tilemaps/components/Shuffle.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); -var ShuffleArray = require('../../utils/array/Shuffle'); - -/** - * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given - * layer. It will only randomize the tiles in that area, so if they're all the same nothing will - * appear to have changed! This method only modifies tile indexes and does not change collision - * information. - * - * @function Phaser.Tilemaps.Components.Shuffle - * @private - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var Shuffle = function (tileX, tileY, width, height, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - var indexes = tiles.map(function (tile) { return tile.index; }); - ShuffleArray(indexes); - - for (var i = 0; i < tiles.length; i++) - { - tiles[i].index = indexes[i]; - } -}; - -module.exports = Shuffle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); +var ShuffleArray = require('../../utils/array/Shuffle'); + +/** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * @function Phaser.Tilemaps.Components.Shuffle + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var Shuffle = function (tileX, tileY, width, height, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + var indexes = tiles.map(function (tile) { return tile.index; }); + ShuffleArray(indexes); + + for (var i = 0; i < tiles.length; i++) + { + tiles[i].index = indexes[i]; + } +}; + +module.exports = Shuffle; diff --git a/src/tilemaps/components/SwapByIndex.js b/src/tilemaps/components/SwapByIndex.js index bd74cadde..81fa07a09 100644 --- a/src/tilemaps/components/SwapByIndex.js +++ b/src/tilemaps/components/SwapByIndex.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision - * information. - * - * @function Phaser.Tilemaps.Components.SwapByIndex - * @private - * @since 3.0.0 - * - * @param {integer} tileA - First tile index. - * @param {integer} tileB - Second tile index. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var SwapByIndex = function (indexA, indexB, tileX, tileY, width, height, layer) -{ - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - for (var i = 0; i < tiles.length; i++) - { - if (tiles[i]) - { - if (tiles[i].index === indexA) - { - tiles[i].index = indexB; - } - else if (tiles[i].index === indexB) - { - tiles[i].index = indexA; - } - } - } -}; - -module.exports = SwapByIndex; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * @function Phaser.Tilemaps.Components.SwapByIndex + * @private + * @since 3.0.0 + * + * @param {integer} tileA - First tile index. + * @param {integer} tileB - Second tile index. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var SwapByIndex = function (indexA, indexB, tileX, tileY, width, height, layer) +{ + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + for (var i = 0; i < tiles.length; i++) + { + if (tiles[i]) + { + if (tiles[i].index === indexA) + { + tiles[i].index = indexB; + } + else if (tiles[i].index === indexB) + { + tiles[i].index = indexA; + } + } + } +}; + +module.exports = SwapByIndex; diff --git a/src/tilemaps/components/TileToWorldX.js b/src/tilemaps/components/TileToWorldX.js index 5b84a774d..e795174fe 100644 --- a/src/tilemaps/components/TileToWorldX.js +++ b/src/tilemaps/components/TileToWorldX.js @@ -1,61 +1,61 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); - -/** - * Converts from orthogonal tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.TileToWorldX - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var OrthoTileToWorldX = function (tileX, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - var layerWorldX = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - - tileWidth *= tilemapLayer.scaleX; - } - - return layerWorldX + tileX * tileWidth; - - -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the TileToWorldXY function.'); - return null; -}; - -var TileToWorldX = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoTileToWorldX; - default: - return nullFunc; - } - -}; - -module.exports = TileToWorldX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); + +/** + * Converts from orthogonal tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldX + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var OrthoTileToWorldX = function (tileX, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + var layerWorldX = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + + tileWidth *= tilemapLayer.scaleX; + } + + return layerWorldX + tileX * tileWidth; + + +}; + +var nullFunc = function () +{ + console.warn('With the current map type you have to use the TileToWorldXY function.'); + return null; +}; + +var TileToWorldX = function (orientation) +{ + switch (orientation) + { + case CONST.ORTHOGONAL: + return OrthoTileToWorldX; + default: + return nullFunc; + } + +}; + +module.exports = TileToWorldX; diff --git a/src/tilemaps/components/TileToWorldXY.js b/src/tilemaps/components/TileToWorldXY.js index 7c989cf41..058d37c96 100644 --- a/src/tilemaps/components/TileToWorldXY.js +++ b/src/tilemaps/components/TileToWorldXY.js @@ -1,209 +1,209 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); -var Vector2 = require('../../math/Vector2'); - -/** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.OrthoTileToWorldXY - * @private - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var OrthoTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileHeight = layer.baseTileHeight; - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - - tileWidth *= tilemapLayer.scaleX; - - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - } - - point.x = layerWorldX + tileX * tileWidth; - point.y = layerWorldY + tileY * tileHeight; - - - - return point; -}; - -/** - * Converts from isometric tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.IsoTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var IsoTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - point.x = layerWorldX + (tileX - tileY) * (tileWidth / 2); - point.y = layerWorldY + (tileX + tileY) * (tileHeight / 2); - - - return point; -}; - -/** - * Converts from staggered tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.StagTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var StagTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); - point.y = layerWorldY + tileY * (tileHeight / 2); - - return point; -}; - -/** - * Converts from hexagonal tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.HexTileToWorldXY - * @private - * @since 3.2.2 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in world coordinates. - */ -var HexTileToWorldXY = function (tileX, tileY, point, camera, layer) -{ - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (point === undefined) { point = new Vector2(0, 0); } - var layerWorldX = 0; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); - tileWidth *= tilemapLayer.scaleX; - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // similar to staggered, because Tiled uses the oddr representation. - point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); - point.y = layerWorldY + tileY * rowHeight; - - return point; -}; - -var TileToWorldXY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagTileToWorldXY; - case CONST.ISOMETRIC: - return IsoTileToWorldXY; - case CONST.HEXAGONAL: - return HexTileToWorldXY; - default: - return OrthoTileToWorldXY; - } - -}; - -module.exports = TileToWorldXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); +var Vector2 = require('../../math/Vector2'); + +/** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.OrthoTileToWorldXY + * @private + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in world coordinates. + */ +var OrthoTileToWorldXY = function (tileX, tileY, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + var tileHeight = layer.baseTileHeight; + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + var layerWorldX = 0; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + + tileWidth *= tilemapLayer.scaleX; + + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + } + + point.x = layerWorldX + tileX * tileWidth; + point.y = layerWorldY + tileY * tileHeight; + + + + return point; +}; + +/** + * Converts from isometric tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.IsoTileToWorldXY + * @private + * @since 3.2.2 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in world coordinates. + */ +var IsoTileToWorldXY = function (tileX, tileY, point, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (point === undefined) { point = new Vector2(0, 0); } + + var layerWorldX = 0; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + tileWidth *= tilemapLayer.scaleX; + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + tileHeight *= tilemapLayer.scaleY; + } + + + point.x = layerWorldX + (tileX - tileY) * (tileWidth / 2); + point.y = layerWorldY + (tileX + tileY) * (tileHeight / 2); + + + return point; +}; + +/** + * Converts from staggered tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.StagTileToWorldXY + * @private + * @since 3.2.2 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in world coordinates. + */ +var StagTileToWorldXY = function (tileX, tileY, point, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (point === undefined) { point = new Vector2(0, 0); } + + var layerWorldX = 0; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + tileWidth *= tilemapLayer.scaleX; + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + tileHeight *= tilemapLayer.scaleY; + } + + + point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); + point.y = layerWorldY + tileY * (tileHeight / 2); + + return point; +}; + +/** + * Converts from hexagonal tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.HexTileToWorldXY + * @private + * @since 3.2.2 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in world coordinates. + */ +var HexTileToWorldXY = function (tileX, tileY, point, camera, layer) +{ + var tileWidth = layer.baseTileWidth; + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (point === undefined) { point = new Vector2(0, 0); } + var layerWorldX = 0; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); + tileWidth *= tilemapLayer.scaleX; + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + tileHeight *= tilemapLayer.scaleY; + } + + var sidel = layer.hexSideLength; + var rowHeight = ((tileHeight - sidel) / 2 + sidel); + + // similar to staggered, because Tiled uses the oddr representation. + point.x = layerWorldX + tileX * tileWidth + tileY % 2 * (tileWidth / 2); + point.y = layerWorldY + tileY * rowHeight; + + return point; +}; + +var TileToWorldXY = function (orientation) +{ + switch (orientation) + { + case CONST.STAGGERED: + return StagTileToWorldXY; + case CONST.ISOMETRIC: + return IsoTileToWorldXY; + case CONST.HEXAGONAL: + return HexTileToWorldXY; + default: + return OrthoTileToWorldXY; + } + +}; + +module.exports = TileToWorldXY; diff --git a/src/tilemaps/components/TileToWorldY.js b/src/tilemaps/components/TileToWorldY.js index 654114f0e..ac7321651 100644 --- a/src/tilemaps/components/TileToWorldY.js +++ b/src/tilemaps/components/TileToWorldY.js @@ -1,133 +1,133 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - - -var CONST = require('../../const.js'); - -/** - * Converts from orthogonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.TileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var OrthoTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - return layerWorldY + tileY * tileHeight; - -}; - - - -/** - * Converts from staggered tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.StagTileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var StagTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - - - return layerWorldY + tileY * (tileHeight / 2); - -}; - - -/** - * Converts from hexagonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.HexTileToWorldY - * @private - * @since 3.0.0 - * - * @param {integer} tileY - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} - */ -var HexTileToWorldY = function (tileY, camera, layer) -{ - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - var layerWorldY = 0; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - tileHeight *= tilemapLayer.scaleY; - } - var sidel = layer.tilemapLayer.tilemap.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // same as staggered - return layerWorldY + tileY * rowHeight; -}; - - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the TileToWorldXY function.'); - return null; -}; - -var TileToWorldY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagTileToWorldY; - case CONST.ISOMETRIC: - return nullFunc; - case CONST.HEXAGONAL: - return HexTileToWorldY; - default: - return OrthoTileToWorldY; - - } - -}; - -module.exports = TileToWorldY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + + +var CONST = require('../../const.js'); + +/** + * Converts from orthogonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.TileToWorldY + * @private + * @since 3.0.0 + * + * @param {integer} tileY - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var OrthoTileToWorldY = function (tileY, camera, layer) +{ + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + tileHeight *= tilemapLayer.scaleY; + } + + return layerWorldY + tileY * tileHeight; + +}; + + + +/** + * Converts from staggered tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.StagTileToWorldY + * @private + * @since 3.0.0 + * + * @param {integer} tileY - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var StagTileToWorldY = function (tileY, camera, layer) +{ + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + tileHeight *= tilemapLayer.scaleY; + } + + + return layerWorldY + tileY * (tileHeight / 2); + +}; + + +/** + * Converts from hexagonal tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.HexTileToWorldY + * @private + * @since 3.0.0 + * + * @param {integer} tileY - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} + */ +var HexTileToWorldY = function (tileY, camera, layer) +{ + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + var layerWorldY = 0; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + layerWorldY = (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + tileHeight *= tilemapLayer.scaleY; + } + var sidel = layer.tilemapLayer.tilemap.hexSideLength; + var rowHeight = ((tileHeight - sidel) / 2 + sidel); + + // same as staggered + return layerWorldY + tileY * rowHeight; +}; + + +var nullFunc = function () +{ + console.warn('With the current map type you have to use the TileToWorldXY function.'); + return null; +}; + +var TileToWorldY = function (orientation) +{ + switch (orientation) + { + case CONST.STAGGERED: + return StagTileToWorldY; + case CONST.ISOMETRIC: + return nullFunc; + case CONST.HEXAGONAL: + return HexTileToWorldY; + default: + return OrthoTileToWorldY; + + } + +}; + +module.exports = TileToWorldY; diff --git a/src/tilemaps/components/WeightedRandomize.js b/src/tilemaps/components/WeightedRandomize.js index 8dbd3d672..83043ed39 100644 --- a/src/tilemaps/components/WeightedRandomize.js +++ b/src/tilemaps/components/WeightedRandomize.js @@ -1,74 +1,74 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetTilesWithin = require('./GetTilesWithin'); - -/** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. New indexes are drawn from the given - * weightedIndexes array. An example weighted array: - * - * [ - * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 - * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 - * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 - * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 - * ] - * - * The probability of any index being choose is (the index's weight) / (sum of all weights). This - * method only modifies tile indexes and does not change collision information. - * - * @function Phaser.Tilemaps.Components.WeightedRandomize - * @private - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during - * randomization. They should be in the form: { index: 0, weight: 4 } or - * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - */ -var WeightedRandomize = function (tileX, tileY, width, height, weightedIndexes, layer) -{ - if (weightedIndexes === undefined) { return; } - - var i; - var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); - - var weightTotal = 0; - for (i = 0; i < weightedIndexes.length; i++) - { - weightTotal += weightedIndexes[i].weight; - } - - if (weightTotal <= 0) { return; } - - for (i = 0; i < tiles.length; i++) - { - var rand = Math.random() * weightTotal; - var sum = 0; - var randomIndex = -1; - for (var j = 0; j < weightedIndexes.length; j++) - { - sum += weightedIndexes[j].weight; - if (rand <= sum) - { - var chosen = weightedIndexes[j].index; - randomIndex = Array.isArray(chosen) - ? chosen[Math.floor(Math.random() * chosen.length)] - : chosen; - break; - } - } - - tiles[i].index = randomIndex; - } -}; - -module.exports = WeightedRandomize; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetTilesWithin = require('./GetTilesWithin'); + +/** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * @function Phaser.Tilemaps.Components.WeightedRandomize + * @private + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + */ +var WeightedRandomize = function (tileX, tileY, width, height, weightedIndexes, layer) +{ + if (weightedIndexes === undefined) { return; } + + var i; + var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); + + var weightTotal = 0; + for (i = 0; i < weightedIndexes.length; i++) + { + weightTotal += weightedIndexes[i].weight; + } + + if (weightTotal <= 0) { return; } + + for (i = 0; i < tiles.length; i++) + { + var rand = Math.random() * weightTotal; + var sum = 0; + var randomIndex = -1; + for (var j = 0; j < weightedIndexes.length; j++) + { + sum += weightedIndexes[j].weight; + if (rand <= sum) + { + var chosen = weightedIndexes[j].index; + randomIndex = Array.isArray(chosen) + ? chosen[Math.floor(Math.random() * chosen.length)] + : chosen; + break; + } + } + + tiles[i].index = randomIndex; + } +}; + +module.exports = WeightedRandomize; diff --git a/src/tilemaps/components/WorldToTileX.js b/src/tilemaps/components/WorldToTileX.js index 0294db9a6..575cf6c9a 100644 --- a/src/tilemaps/components/WorldToTileX.js +++ b/src/tilemaps/components/WorldToTileX.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); - -/** - * Converts from world X coordinates (pixels) to orthogonal tile X coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.WorldToTileX - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The X location in tile units. - */ -var OrthoWorldToTileX = function (worldX, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - - var tileWidth = layer.baseTileWidth; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - return snapToFloor - ? Math.floor(worldX / tileWidth) - : worldX / tileWidth; - -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the WorldToTileXY function.'); - return null; -}; - -var WorldToTileX = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoWorldToTileX; - - default: - return nullFunc; - - } - -}; - -module.exports = WorldToTileX; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); + +/** + * Converts from world X coordinates (pixels) to orthogonal tile X coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.WorldToTileX + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The X location in tile units. + */ +var OrthoWorldToTileX = function (worldX, snapToFloor, camera, layer) +{ + + if (snapToFloor === undefined) { snapToFloor = true; } + + var tileWidth = layer.baseTileWidth; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + } + + return snapToFloor + ? Math.floor(worldX / tileWidth) + : worldX / tileWidth; + +}; + +var nullFunc = function () +{ + console.warn('With the current map type you have to use the WorldToTileXY function.'); + return null; +}; + +var WorldToTileX = function (orientation) +{ + switch (orientation) + { + case CONST.ORTHOGONAL: + return OrthoWorldToTileX; + + default: + return nullFunc; + + } + +}; + +module.exports = WorldToTileX; diff --git a/src/tilemaps/components/WorldToTileXY.js b/src/tilemaps/components/WorldToTileXY.js index 0789254aa..a74e88cd7 100644 --- a/src/tilemaps/components/WorldToTileXY.js +++ b/src/tilemaps/components/WorldToTileXY.js @@ -1,231 +1,231 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); -var WorldToTileX = require('./WorldToTileX').func; -var WorldToTileY = require('./WorldToTileY').func; -var Vector2 = require('../../math/Vector2'); - -/** - * Converts from world XY coordinates (pixels) to orthogonal tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.OrthoWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var OrthoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - point.x = WorldToTileX(worldX, snapToFloor, camera, layer); - point.y = WorldToTileY(worldY, snapToFloor, camera, layer); - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to isometric tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.IsoWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var IsoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - point.x = snapToFloor - ? Math.floor((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2) - : ((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2); - - point.y = snapToFloor - ? Math.floor((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2) - : ((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2); - - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to hexagonal tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.HexWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var HexWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - } - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - - // similar to staggered, because Tiled uses the oddr representation. - point.y = snapToFloor - ? Math.floor((worldY / rowHeight)) - : (worldY / rowHeight); - point.x = snapToFloor - ? Math.floor((worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth) - : (worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth; - - return point; -}; - -/** - * Converts from world XY coordinates (pixels) to staggered tile XY coordinates (tile units), factoring in the - * layer's position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @function Phaser.Tilemaps.Components.StagWorldToTileXY - * @private - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {Phaser.Math.Vector2} The XY location in tile units. - */ -var StagWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) -{ - if (point === undefined) { point = new Vector2(0, 0); } - - var tileWidth = layer.baseTileWidth; - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - // console.log(1,worldY) - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - // console.log(worldY) - tileHeight *= tilemapLayer.scaleY; - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's horizontal scroll - worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); - - tileWidth *= tilemapLayer.scaleX; - - point.y = snapToFloor - ? Math.floor((worldY / (tileHeight / 2))) - : (worldY / (tileHeight / 2)); - point.x = snapToFloor - ? Math.floor((worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth) - : (worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth; - - - } - - return point; -}; - -var WorldToTileXY = function (orientation) -{ - switch (orientation) - { - case CONST.STAGGERED: - return StagWorldToTileXY; - - case CONST.ISOMETRIC: - return IsoWorldToTileXY; - - case CONST.HEXAGONAL: - return HexWorldToTileXY; - - default: - return OrthoWorldToTileXY; - - } - -}; - -module.exports = WorldToTileXY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); +var WorldToTileX = require('./WorldToTileX').func; +var WorldToTileY = require('./WorldToTileY').func; +var Vector2 = require('../../math/Vector2'); + +/** + * Converts from world XY coordinates (pixels) to orthogonal tile XY coordinates (tile units), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.OrthoWorldToTileXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in tile units. + */ +var OrthoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + point.x = WorldToTileX(worldX, snapToFloor, camera, layer); + point.y = WorldToTileY(worldY, snapToFloor, camera, layer); + return point; +}; + +/** + * Converts from world XY coordinates (pixels) to isometric tile XY coordinates (tile units), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.IsoWorldToTileXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in tile units. + */ +var IsoWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + var tileWidth = layer.baseTileWidth; + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + // console.log(1,worldY) + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + // console.log(worldY) + tileHeight *= tilemapLayer.scaleY; + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + } + + point.x = snapToFloor + ? Math.floor((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2) + : ((worldX / (tileWidth / 2) + worldY / (tileHeight / 2)) / 2); + + point.y = snapToFloor + ? Math.floor((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2) + : ((worldY / (tileHeight / 2) - worldX / (tileWidth / 2)) / 2); + + return point; +}; + +/** + * Converts from world XY coordinates (pixels) to hexagonal tile XY coordinates (tile units), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.HexWorldToTileXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in tile units. + */ +var HexWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + var tileWidth = layer.baseTileWidth; + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + // console.log(1,worldY) + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + // console.log(worldY) + tileHeight *= tilemapLayer.scaleY; + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + } + + var sidel = layer.hexSideLength; + var rowHeight = ((tileHeight - sidel) / 2 + sidel); + + // similar to staggered, because Tiled uses the oddr representation. + point.y = snapToFloor + ? Math.floor((worldY / rowHeight)) + : (worldY / rowHeight); + point.x = snapToFloor + ? Math.floor((worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth) + : (worldX - (point.y % 2) * 0.5 * tileWidth) / tileWidth; + + return point; +}; + +/** + * Converts from world XY coordinates (pixels) to staggered tile XY coordinates (tile units), factoring in the + * layer's position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @function Phaser.Tilemaps.Components.StagWorldToTileXY + * @private + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {Phaser.Math.Vector2} The XY location in tile units. + */ +var StagWorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer) +{ + if (point === undefined) { point = new Vector2(0, 0); } + + var tileWidth = layer.baseTileWidth; + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + // console.log(1,worldY) + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + // console.log(worldY) + tileHeight *= tilemapLayer.scaleY; + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's horizontal scroll + worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); + + tileWidth *= tilemapLayer.scaleX; + + point.y = snapToFloor + ? Math.floor((worldY / (tileHeight / 2))) + : (worldY / (tileHeight / 2)); + point.x = snapToFloor + ? Math.floor((worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth) + : (worldX + (point.y % 2) * 0.5 * tileWidth) / tileWidth; + + + } + + return point; +}; + +var WorldToTileXY = function (orientation) +{ + switch (orientation) + { + case CONST.STAGGERED: + return StagWorldToTileXY; + + case CONST.ISOMETRIC: + return IsoWorldToTileXY; + + case CONST.HEXAGONAL: + return HexWorldToTileXY; + + default: + return OrthoWorldToTileXY; + + } + +}; + +module.exports = WorldToTileXY; diff --git a/src/tilemaps/components/WorldToTileY.js b/src/tilemaps/components/WorldToTileY.js index b2ac73e1d..d5e8cefe1 100644 --- a/src/tilemaps/components/WorldToTileY.js +++ b/src/tilemaps/components/WorldToTileY.js @@ -1,156 +1,156 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); - -/** - * Converts from world Y coordinates (pixels) to orthogonal tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.OrthoWorldToTileY - * @private - * @since 3.0.0 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var OrthoWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - return snapToFloor - ? Math.floor(worldY / tileHeight) - : worldY / tileHeight; - -}; - -/** - * Converts from world Y coordinates (pixels) to staggered tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.StagWorldToTileY - * @private - * @since 3.2.2 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var StagWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - return snapToFloor - ? Math.floor(worldY / (tileHeight / 2)) - : worldY / (tileHeight / 2); -}; - -/** - * Converts from world Y coordinates (pixels) to hexagonal tile Y coordinates (tile units), factoring in the - * layer's position, scale and scroll. - * - * @function Phaser.Tilemaps.Components.HexWorldToTileY - * @private - * @since 3.2.2 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. - * - * @return {number} The Y location in tile units. - */ -var HexWorldToTileY = function (worldY, snapToFloor, camera, layer) -{ - - if (snapToFloor === undefined) { snapToFloor = true; } - var tileHeight = layer.baseTileHeight; - var tilemapLayer = layer.tilemapLayer; - - if (tilemapLayer) - { - if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } - - // Find the world position relative to the static or dynamic layer's top left origin, - // factoring in the camera's vertical scroll - worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); - - tileHeight *= tilemapLayer.scaleY; - - } - - - var sidel = layer.hexSideLength; - var rowHeight = ((tileHeight - sidel) / 2 + sidel); - return snapToFloor - ? Math.floor(worldY / rowHeight) - : worldY / rowHeight; -}; - -var nullFunc = function () -{ - console.warn('With the current map type you have to use the WorldToTileXY function.'); - return null; -}; - -var WorldToTileY = function (orientation) -{ - switch (orientation) - { - case CONST.ORTHOGONAL: - return OrthoWorldToTileY; - - case CONST.HEXAGONAL: - return HexWorldToTileY; - - case CONST.STAGGERED: - return StagWorldToTileY; - - default: - return nullFunc; - - } - -}; - -module.exports = WorldToTileY; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); + +/** + * Converts from world Y coordinates (pixels) to orthogonal tile Y coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.OrthoWorldToTileY + * @private + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The Y location in tile units. + */ +var OrthoWorldToTileY = function (worldY, snapToFloor, camera, layer) +{ + + if (snapToFloor === undefined) { snapToFloor = true; } + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + + } + + return snapToFloor + ? Math.floor(worldY / tileHeight) + : worldY / tileHeight; + +}; + +/** + * Converts from world Y coordinates (pixels) to staggered tile Y coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.StagWorldToTileY + * @private + * @since 3.2.2 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The Y location in tile units. + */ +var StagWorldToTileY = function (worldY, snapToFloor, camera, layer) +{ + + if (snapToFloor === undefined) { snapToFloor = true; } + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + + } + + return snapToFloor + ? Math.floor(worldY / (tileHeight / 2)) + : worldY / (tileHeight / 2); +}; + +/** + * Converts from world Y coordinates (pixels) to hexagonal tile Y coordinates (tile units), factoring in the + * layer's position, scale and scroll. + * + * @function Phaser.Tilemaps.Components.HexWorldToTileY + * @private + * @since 3.2.2 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. + * + * @return {number} The Y location in tile units. + */ +var HexWorldToTileY = function (worldY, snapToFloor, camera, layer) +{ + + if (snapToFloor === undefined) { snapToFloor = true; } + var tileHeight = layer.baseTileHeight; + var tilemapLayer = layer.tilemapLayer; + + if (tilemapLayer) + { + if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; } + + // Find the world position relative to the static or dynamic layer's top left origin, + // factoring in the camera's vertical scroll + worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); + + tileHeight *= tilemapLayer.scaleY; + + } + + + var sidel = layer.hexSideLength; + var rowHeight = ((tileHeight - sidel) / 2 + sidel); + return snapToFloor + ? Math.floor(worldY / rowHeight) + : worldY / rowHeight; +}; + +var nullFunc = function () +{ + console.warn('With the current map type you have to use the WorldToTileXY function.'); + return null; +}; + +var WorldToTileY = function (orientation) +{ + switch (orientation) + { + case CONST.ORTHOGONAL: + return OrthoWorldToTileY; + + case CONST.HEXAGONAL: + return HexWorldToTileY; + + case CONST.STAGGERED: + return StagWorldToTileY; + + default: + return nullFunc; + + } + +}; + +module.exports = WorldToTileY; diff --git a/src/tilemaps/components/index.js b/src/tilemaps/components/index.js index 8f16bcd4b..edea833d2 100644 --- a/src/tilemaps/components/index.js +++ b/src/tilemaps/components/index.js @@ -1,56 +1,56 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Components - */ - -module.exports = { - - CalculateFacesAt: require('./CalculateFacesAt'), - CalculateFacesWithin: require('./CalculateFacesWithin'), - Copy: require('./Copy'), - CreateFromTiles: require('./CreateFromTiles'), - CullTiles: require('./CullTiles'), - Fill: require('./Fill'), - FilterTiles: require('./FilterTiles'), - FindByIndex: require('./FindByIndex'), - FindTile: require('./FindTile'), - ForEachTile: require('./ForEachTile'), - GetTileAt: require('./GetTileAt'), - GetTileAtWorldXY: require('./GetTileAtWorldXY'), - GetTilesWithin: require('./GetTilesWithin'), - GetTilesWithinShape: require('./GetTilesWithinShape'), - GetTilesWithinWorldXY: require('./GetTilesWithinWorldXY'), - HasTileAt: require('./HasTileAt'), - HasTileAtWorldXY: require('./HasTileAtWorldXY'), - IsInLayerBounds: require('./IsInLayerBounds'), - PutTileAt: require('./PutTileAt'), - PutTileAtWorldXY: require('./PutTileAtWorldXY'), - PutTilesAt: require('./PutTilesAt'), - Randomize: require('./Randomize'), - RemoveTileAt: require('./RemoveTileAt'), - RemoveTileAtWorldXY: require('./RemoveTileAtWorldXY'), - RenderDebug: require('./RenderDebug'), - ReplaceByIndex: require('./ReplaceByIndex'), - SetCollision: require('./SetCollision'), - SetCollisionBetween: require('./SetCollisionBetween'), - SetCollisionByExclusion: require('./SetCollisionByExclusion'), - SetCollisionByProperty: require('./SetCollisionByProperty'), - SetCollisionFromCollisionGroup: require('./SetCollisionFromCollisionGroup'), - SetTileIndexCallback: require('./SetTileIndexCallback'), - SetTileLocationCallback: require('./SetTileLocationCallback'), - Shuffle: require('./Shuffle'), - SwapByIndex: require('./SwapByIndex'), - TileToWorldX: require('./TileToWorldX'), - TileToWorldXY: require('./TileToWorldXY'), - TileToWorldY: require('./TileToWorldY'), - WeightedRandomize: require('./WeightedRandomize'), - WorldToTileX: require('./WorldToTileX'), - WorldToTileXY: require('./WorldToTileXY'), - WorldToTileY: require('./WorldToTileY') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Components + */ + +module.exports = { + + CalculateFacesAt: require('./CalculateFacesAt'), + CalculateFacesWithin: require('./CalculateFacesWithin'), + Copy: require('./Copy'), + CreateFromTiles: require('./CreateFromTiles'), + CullTiles: require('./CullTiles'), + Fill: require('./Fill'), + FilterTiles: require('./FilterTiles'), + FindByIndex: require('./FindByIndex'), + FindTile: require('./FindTile'), + ForEachTile: require('./ForEachTile'), + GetTileAt: require('./GetTileAt'), + GetTileAtWorldXY: require('./GetTileAtWorldXY'), + GetTilesWithin: require('./GetTilesWithin'), + GetTilesWithinShape: require('./GetTilesWithinShape'), + GetTilesWithinWorldXY: require('./GetTilesWithinWorldXY'), + HasTileAt: require('./HasTileAt'), + HasTileAtWorldXY: require('./HasTileAtWorldXY'), + IsInLayerBounds: require('./IsInLayerBounds'), + PutTileAt: require('./PutTileAt'), + PutTileAtWorldXY: require('./PutTileAtWorldXY'), + PutTilesAt: require('./PutTilesAt'), + Randomize: require('./Randomize'), + RemoveTileAt: require('./RemoveTileAt'), + RemoveTileAtWorldXY: require('./RemoveTileAtWorldXY'), + RenderDebug: require('./RenderDebug'), + ReplaceByIndex: require('./ReplaceByIndex'), + SetCollision: require('./SetCollision'), + SetCollisionBetween: require('./SetCollisionBetween'), + SetCollisionByExclusion: require('./SetCollisionByExclusion'), + SetCollisionByProperty: require('./SetCollisionByProperty'), + SetCollisionFromCollisionGroup: require('./SetCollisionFromCollisionGroup'), + SetTileIndexCallback: require('./SetTileIndexCallback'), + SetTileLocationCallback: require('./SetTileLocationCallback'), + Shuffle: require('./Shuffle'), + SwapByIndex: require('./SwapByIndex'), + TileToWorldX: require('./TileToWorldX'), + TileToWorldXY: require('./TileToWorldXY'), + TileToWorldY: require('./TileToWorldY'), + WeightedRandomize: require('./WeightedRandomize'), + WorldToTileX: require('./WorldToTileX'), + WorldToTileXY: require('./WorldToTileXY'), + WorldToTileY: require('./WorldToTileY') + +}; diff --git a/src/tilemaps/dynamiclayer/DynamicTilemapLayer.js b/src/tilemaps/dynamiclayer/DynamicTilemapLayer.js index 76e3d5ffe..005878046 100644 --- a/src/tilemaps/dynamiclayer/DynamicTilemapLayer.js +++ b/src/tilemaps/dynamiclayer/DynamicTilemapLayer.js @@ -1,1328 +1,1328 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../../gameobjects/components'); -var DynamicTilemapLayerRender = require('./DynamicTilemapLayerRender'); -var GameObject = require('../../gameobjects/GameObject'); -var TilemapComponents = require('../components'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Dynamic Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination - * with one, or more, Tilesets. - * - * A Dynamic Tilemap Layer trades some speed for being able to apply powerful effects. Unlike a - * Static Tilemap Layer, you can apply per-tile effects like tint or alpha, and you can change the - * tiles in a DynamicTilemapLayer. - * - * Use this over a Static Tilemap Layer when you need those features. - * - * @class DynamicTilemapLayer - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.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.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.ScrollFactor - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * - * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. - * @param {Phaser.Tilemaps.Tilemap} tilemap - The Tilemap this layer is a part of. - * @param {integer} layerIndex - The index of the LayerData associated with this layer. - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param {number} [x=0] - The world x position where the top left of this layer will be placed. - * @param {number} [y=0] - The world y position where the top left of this layer will be placed. - */ -var DynamicTilemapLayer = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.ComputedSize, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Origin, - Components.Pipeline, - Components.Transform, - Components.Visible, - Components.ScrollFactor, - DynamicTilemapLayerRender - ], - - initialize: - - function DynamicTilemapLayer (scene, tilemap, layerIndex, tileset, x, y) - { - GameObject.call(this, scene, 'DynamicTilemapLayer'); - - /** - * Used internally by physics system to perform fast type checks. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#isTilemap - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - this.isTilemap = true; - - /** - * The Tilemap that this layer is a part of. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#tilemap - * @type {Phaser.Tilemaps.Tilemap} - * @since 3.0.0 - */ - this.tilemap = tilemap; - - /** - * The index of the LayerData associated with this layer. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#layerIndex - * @type {integer} - * @since 3.0.0 - */ - this.layerIndex = layerIndex; - - /** - * The LayerData associated with this layer. LayerData can only be associated with one - * tilemap layer. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#layer - * @type {Phaser.Tilemaps.LayerData} - * @since 3.0.0 - */ - this.layer = tilemap.layers[layerIndex]; - - // Link the LayerData with this static tilemap layer - this.layer.tilemapLayer = this; - - /** - * The Tileset/s associated with this layer. - * - * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#tileset - * @type {Phaser.Tilemaps.Tileset[]} - * @since 3.0.0 - */ - this.tileset = []; - - /** - * Used internally with the canvas render. This holds the tiles that are visible within the - * camera. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#culledTiles - * @type {array} - * @since 3.0.0 - */ - this.culledTiles = []; - - /** - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this, and toggling this flag allows - * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#skipCull - * @type {boolean} - * @since 3.11.0 - */ - this.skipCull = false; - - /** - * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. - * By default the camera will allow 1 full tile in all directions. - * - * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#isoCullDistances - * @type {Phaser.Math.Vector2} - * @since 3.23.0 - */ - this.isoCullDistances = new Vector2(1, 1); - - /** - * The total number of tiles drawn by the renderer in the last frame. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#tilesDrawn - * @type {integer} - * @readonly - * @since 3.11.0 - */ - this.tilesDrawn = 0; - - /** - * The total number of tiles in this layer. Updated every frame. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#tilesTotal - * @type {integer} - * @readonly - * @since 3.11.0 - */ - this.tilesTotal = this.layer.width * this.layer.height; - - /** - * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. - * - * See the method `setCullPadding` for more details. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#cullPaddingX - * @type {integer} - * @default 1 - * @since 3.11.0 - */ - this.cullPaddingX = 1; - - /** - * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. - * - * See the method `setCullPadding` for more details. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#cullPaddingY - * @type {integer} - * @default 1 - * @since 3.11.0 - */ - this.cullPaddingY = 1; - - /** - * The callback that is invoked when the tiles are culled. - * - * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. - * - * It will be sent 3 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. - * - * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#cullCallback - * @type {function} - * @since 3.11.0 - */ - this.cullCallback = TilemapComponents.CullTiles; - - /** - * The rendering (draw) order of the tiles in this layer. - * - * The default is 0 which is 'right-down', meaning it will draw the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * This can be changed via the `setRenderOrder` method. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#_renderOrder - * @type {integer} - * @default 0 - * @private - * @since 3.12.0 - */ - this._renderOrder = 0; - - /** - * An array holding the mapping between the tile indexes and the tileset they belong to. - * - * @name Phaser.Tilemaps.DynamicTilemapLayer#gidMap - * @type {Phaser.Tilemaps.Tileset[]} - * @since 3.14.0 - */ - this.gidMap = []; - - this.setTilesets(tileset); - this.setAlpha(this.layer.alpha); - this.setPosition(x, y); - this.setOrigin(); - this.setSize(tilemap.tileWidth * this.layer.width, tilemap.tileHeight * this.layer.height); - - this.initPipeline('TextureTintPipeline'); - }, - - /** - * Populates the internal `tileset` array with the Tileset references this Layer requires for rendering. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setTilesets - * @private - * @since 3.14.0 - * - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - */ - setTilesets: function (tilesets) - { - var gidMap = []; - var setList = []; - var map = this.tilemap; - - if (!Array.isArray(tilesets)) - { - tilesets = [ tilesets ]; - } - - for (var i = 0; i < tilesets.length; i++) - { - var tileset = tilesets[i]; - - if (typeof tileset === 'string') - { - tileset = map.getTileset(tileset); - } - - if (tileset) - { - setList.push(tileset); - - var s = tileset.firstgid; - - for (var t = 0; t < tileset.total; t++) - { - gidMap[s + t] = tileset; - } - } - } - - this.gidMap = gidMap; - this.tileset = setList; - }, - - /** - * Sets the rendering (draw) order of the tiles in this layer. - * - * The default is 'right-down', meaning it will order the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * Setting the render order does not change the tiles or how they are stored in the layer, - * it purely impacts the order in which they are rendered. - * - * You can provide either an integer (0 to 3), or the string version of the order. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setRenderOrder - * @since 3.12.0 - * - * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. - * - * @return {this} This Tilemap Layer object. - */ - setRenderOrder: function (renderOrder) - { - var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; - - if (typeof renderOrder === 'string') - { - renderOrder = orders.indexOf(renderOrder); - } - - if (renderOrder >= 0 && renderOrder < 4) - { - this._renderOrder = renderOrder; - } - - return this; - }, - - /** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#calculateFacesAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate. - * @param {integer} tileY - The y coordinate. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - calculateFacesAt: function (tileX, tileY) - { - TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); - - return this; - }, - - /** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#calculateFacesWithin - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - calculateFacesWithin: function (tileX, tileY, width, height) - { - TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); - - return this; - }, - - /** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#createFromTiles - * @since 3.0.0 - * - * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. - * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted - * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a - * one-to-one mapping with the indexes array. - * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. - * scene.make.sprite). - * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY - * - * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. - */ - createFromTiles: function (indexes, replacements, spriteConfig, scene, camera) - { - return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer); - }, - - /** - * Returns the tiles in the given layer that are within the cameras viewport. - * This is used internally. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#cull - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - cull: function (camera) - { - return this.cullCallback(this.layer, camera, this.culledTiles, this._renderOrder); - }, - - /** - * Copies the tiles in the source rectangular area to a new destination (all specified in tile - * coordinates) within the layer. This copies all tile properties & recalculates collision - * information in the destination region. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#copy - * @since 3.0.0 - * - * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. - * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. - * @param {integer} width - The width of the area to copy, in tiles, not pixels. - * @param {integer} height - The height of the area to copy, in tiles, not pixels. - * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. - * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - copy: function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces) - { - TilemapComponents.Copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, this.layer); - - return this; - }, - - /** - * Destroys this DynamicTilemapLayer and removes its link to the associated LayerData. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#destroy - * @since 3.0.0 - * - * @param {boolean} [removeFromTilemap=true] - Remove this layer from the parent Tilemap? - */ - destroy: function (removeFromTilemap) - { - if (removeFromTilemap === undefined) { removeFromTilemap = true; } - - if (!this.tilemap) - { - // Abort, we've already been destroyed - return; - } - - // Uninstall this layer only if it is still installed on the LayerData object - if (this.layer.tilemapLayer === this) - { - this.layer.tilemapLayer = undefined; - } - - if (removeFromTilemap) - { - this.tilemap.removeLayer(this); - } - - this.tilemap = undefined; - this.layer = undefined; - this.culledTiles.length = 0; - this.cullCallback = null; - - this.gidMap = []; - this.tileset = []; - - GameObject.prototype.destroy.call(this); - }, - - /** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#fill - * @since 3.0.0 - * - * @param {integer} index - The tile index to fill the area with. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - fill: function (index, tileX, tileY, width, height, recalculateFaces) - { - TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, this.layer); - - return this; - }, - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#filterTiles - * @since 3.0.0 - * - * @param {function} callback - The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions) - { - return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); - }, - - /** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#findByIndex - * @since 3.0.0 - * - * @param {integer} index - The tile index value to search for. - * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. - * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the - * bottom-right. Otherwise it scans from the top-left. - * - * @return {Phaser.Tilemaps.Tile} A Tile object. - */ - findByIndex: function (findIndex, skip, reverse) - { - return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer); - }, - - /** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#findTile - * @since 3.0.0 - * - * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {?Phaser.Tilemaps.Tile} - */ - findTile: function (callback, context, tileX, tileY, width, height, filteringOptions) - { - return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); - }, - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#forEachTile - * @since 3.0.0 - * - * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions) - { - TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); - - return this; - }, - - /** - * Gets a tile at the given tile coordinates from the given layer. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#getTileAt - * @since 3.0.0 - * - * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). - * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). - * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. - * - * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. - */ - getTileAt: function (tileX, tileY, nonNull) - { - return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer); - }, - - /** - * Gets a tile at the given world coordinates from the given layer. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#getTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - X position to get the tile from (given in pixels) - * @param {number} worldY - Y position to get the tile from (given in pixels) - * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates - * were invalid. - */ - getTileAtWorldXY: function (worldX, worldY, nonNull, camera) - { - return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer); - }, - - /** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithin - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - getTilesWithin: function (tileX, tileY, width, height, filteringOptions) - { - return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer); - }, - - /** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithinShape - * @since 3.0.0 - * - * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - getTilesWithinShape: function (shape, filteringOptions, camera) - { - return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer); - }, - - /** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithinWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The world x coordinate for the top-left of the area. - * @param {number} worldY - The world y coordinate for the top-left of the area. - * @param {number} width - The width of the area. - * @param {number} height - The height of the area. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera) - { - return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer); - }, - - /** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#hasTileAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * - * @return {boolean} `true` if a tile was found at the given location, otherwise `false`. - */ - hasTileAt: function (tileX, tileY) - { - return TilemapComponents.HasTileAt(tileX, tileY, this.layer); - }, - - /** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#hasTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * - * @return {boolean} `true` if a tile was found at the given location, otherwise `false`. - */ - hasTileAtWorldXY: function (worldX, worldY, camera) - { - return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer); - }, - - /** - * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index - * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified - * location. If you pass in an index, only the index at the specified location will be changed. - * Collision information will be recalculated at the specified location. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#putTileAt - * @since 3.0.0 - * - * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * - * @return {Phaser.Tilemaps.Tile} A Tile object. - */ - putTileAt: function (tile, tileX, tileY, recalculateFaces) - { - return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, this.layer); - }, - - /** - * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either - * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the - * specified location. If you pass in an index, only the index at the specified location will be - * changed. Collision information will be recalculated at the specified location. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#putTileAtWorldXY - * @since 3.0.0 - * - * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Tilemaps.Tile} A Tile object. - */ - putTileAtWorldXY: function (tile, worldX, worldY, recalculateFaces, camera) - { - return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, this.layer); - }, - - /** - * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified - * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, - * all attributes will be copied over to the specified location. If you pass in an index, only the - * index at the specified location will be changed. Collision information will be recalculated - * within the region tiles were changed. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#putTilesAt - * @since 3.0.0 - * - * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - putTilesAt: function (tilesArray, tileX, tileY, recalculateFaces) - { - TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, this.layer); - - return this; - }, - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then - * those will be used for randomly assigning new tile indexes. If an array is not provided, the - * indexes found within the region (excluding -1) will be used for randomly assigning new tile - * indexes. This method only modifies tile indexes and does not change collision information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#randomize - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - randomize: function (tileX, tileY, width, height, indexes) - { - TilemapComponents.Randomize(tileX, tileY, width, height, indexes, this.layer); - - return this; - }, - - /** - * Removes the tile at the given tile coordinates in the specified layer and updates the layer's - * collision information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#removeTileAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * - * @return {Phaser.Tilemaps.Tile} A Tile object. - */ - removeTileAt: function (tileX, tileY, replaceWithNull, recalculateFaces) - { - return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, this.layer); - }, - - /** - * Removes the tile at the given world coordinates in the specified layer and updates the layer's - * collision information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#removeTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate, in pixels. - * @param {number} worldY - The y coordinate, in pixels. - * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. - * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Tilemaps.Tile} A Tile object. - */ - removeTileAtWorldXY: function (worldX, worldY, replaceWithNull, recalculateFaces, camera) - { - return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, this.layer); - }, - - /** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#renderDebug - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. - * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - renderDebug: function (graphics, styleConfig) - { - TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); - - return this; - }, - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does - * not change collision information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#replaceByIndex - * @since 3.0.0 - * - * @param {integer} findIndex - The index of the tile to search for. - * @param {integer} newIndex - The index of the tile to replace it with. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - replaceByIndex: function (findIndex, newIndex, tileX, tileY, width, height) - { - TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, this.layer); - - return this; - }, - - /** - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setSkipCull - * @since 3.11.0 - * - * @param {boolean} [value=true] - Set to `true` to stop culling tiles. Set to `false` to enable culling again. - * - * @return {this} This Tilemap Layer object. - */ - setSkipCull: function (value) - { - if (value === undefined) { value = true; } - - this.skipCull = value; - - return this; - }, - - /** - * When a Camera culls the tiles in this layer it does so using its view into the world, building up a - * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size - * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so - * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px - * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setCullPadding - * @since 3.11.0 - * - * @param {integer} [paddingX=1] - The amount of extra horizontal tiles to add to the cull check padding. - * @param {integer} [paddingY=1] - The amount of extra vertical tiles to add to the cull check padding. - * - * @return {this} This Tilemap Layer object. - */ - setCullPadding: function (paddingX, paddingY) - { - if (paddingX === undefined) { paddingX = 1; } - if (paddingY === undefined) { paddingY = 1; } - - this.cullPaddingX = paddingX; - this.cullPaddingY = paddingY; - - return this; - }, - - /** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollision - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to - * false if no tiles have been placed for significant performance boost. - * - * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. - */ - setCollision: function (indexes, collides, recalculateFaces, updateLayer) - { - TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer, updateLayer); - - return this; - }, - - /** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionBetween - * @since 3.0.0 - * - * @param {integer} start - The first index of the tile to be set for collision. - * @param {integer} stop - The last index of the tile to be set for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - setCollisionBetween: function (start, stop, collides, recalculateFaces) - { - TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionByProperty - * @since 3.0.0 - * - * @param {object} properties - An object with tile properties and corresponding values that should be checked. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - setCollisionByProperty: function (properties, collides, recalculateFaces) - { - TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionByExclusion - * @since 3.0.0 - * - * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - setCollisionByExclusion: function (indexes, collides, recalculateFaces) - { - TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets collision on the tiles within a layer by checking each tiles collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tiles collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionFromCollisionGroup - * @since 3.0.0 - * - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - setCollisionFromCollisionGroup: function (collides, recalculateFaces) - { - TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setTileIndexCallback - * @since 3.0.0 - * - * @param {(integer|integer[])} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} callbackContext - The context under which the callback is called. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - setTileIndexCallback: function (indexes, callback, callbackContext) - { - TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); - - return this; - }, - - /** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#setTileLocationCallback - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {function} [callback] - The callback that will be invoked when the tile is collided with. - * @param {object} [callbackContext] - The context under which the callback is called. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext) - { - TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); - - return this; - }, - - /** - * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given - * layer. It will only randomize the tiles in that area, so if they're all the same nothing will - * appear to have changed! This method only modifies tile indexes and does not change collision - * information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#shuffle - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - shuffle: function (tileX, tileY, width, height) - { - TilemapComponents.Shuffle(tileX, tileY, width, height, this.layer); - - return this; - }, - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision - * information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#swapByIndex - * @since 3.0.0 - * - * @param {integer} tileA - First tile index. - * @param {integer} tileB - Second tile index. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - swapByIndex: function (indexA, indexB, tileX, tileY, width, height) - { - TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, this.layer); - - return this; - }, - - /** - * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldX - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {number} - */ - tileToWorldX: function (tileX, camera) - { - return this.tilemap.TileToWorldX(tileX, camera, this.layer); - }, - - /** - * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldY - * @since 3.0.0 - * - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {number} - */ - tileToWorldY: function (tileY, camera) - { - return this.tilemap.TileToWorldY(tileY, camera, this.layer); - }, - - /** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldXY - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate, in tiles, not pixels. - * @param {integer} tileY - The y coordinate, in tiles, not pixels. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Math.Vector2} - */ - tileToWorldXY: function (tileX, tileY, point, camera) - { - return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); - }, - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. New indexes are drawn from the given - * weightedIndexes array. An example weighted array: - * - * [ - * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 - * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 - * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 - * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 - * ] - * - * The probability of any index being choose is (the index's weight) / (sum of all weights). This - * method only modifies tile indexes and does not change collision information. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#weightedRandomize - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during - * randomization. They should be in the form: { index: 0, weight: 4 } or - * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. - * - * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. - */ - weightedRandomize: function (tileX, tileY, width, height, weightedIndexes) - { - TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, this.layer); - - return this; - }, - - /** - * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileX - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {number} - */ - worldToTileX: function (worldX, snapToFloor, camera) - { - return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); - }, - - /** - * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileY - * @since 3.0.0 - * - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {number} - */ - worldToTileY: function (worldY, snapToFloor, camera) - { - return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); - }, - - /** - * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileXY - * @since 3.0.0 - * - * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. - * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Math.Vector2} - */ - worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) - { - return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); - } - -}); - -module.exports = DynamicTilemapLayer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../../gameobjects/components'); +var DynamicTilemapLayerRender = require('./DynamicTilemapLayerRender'); +var GameObject = require('../../gameobjects/GameObject'); +var TilemapComponents = require('../components'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Dynamic Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination + * with one, or more, Tilesets. + * + * A Dynamic Tilemap Layer trades some speed for being able to apply powerful effects. Unlike a + * Static Tilemap Layer, you can apply per-tile effects like tint or alpha, and you can change the + * tiles in a DynamicTilemapLayer. + * + * Use this over a Static Tilemap Layer when you need those features. + * + * @class DynamicTilemapLayer + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.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.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.ScrollFactor + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. + * @param {Phaser.Tilemaps.Tilemap} tilemap - The Tilemap this layer is a part of. + * @param {integer} layerIndex - The index of the LayerData associated with this layer. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The world x position where the top left of this layer will be placed. + * @param {number} [y=0] - The world y position where the top left of this layer will be placed. + */ +var DynamicTilemapLayer = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Origin, + Components.Pipeline, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + DynamicTilemapLayerRender + ], + + initialize: + + function DynamicTilemapLayer (scene, tilemap, layerIndex, tileset, x, y) + { + GameObject.call(this, scene, 'DynamicTilemapLayer'); + + /** + * Used internally by physics system to perform fast type checks. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#isTilemap + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isTilemap = true; + + /** + * The Tilemap that this layer is a part of. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tilemap + * @type {Phaser.Tilemaps.Tilemap} + * @since 3.0.0 + */ + this.tilemap = tilemap; + + /** + * The index of the LayerData associated with this layer. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#layerIndex + * @type {integer} + * @since 3.0.0 + */ + this.layerIndex = layerIndex; + + /** + * The LayerData associated with this layer. LayerData can only be associated with one + * tilemap layer. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + this.layer = tilemap.layers[layerIndex]; + + // Link the LayerData with this static tilemap layer + this.layer.tilemapLayer = this; + + /** + * The Tileset/s associated with this layer. + * + * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tileset + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tileset = []; + + /** + * Used internally with the canvas render. This holds the tiles that are visible within the + * camera. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#culledTiles + * @type {array} + * @since 3.0.0 + */ + this.culledTiles = []; + + /** + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this, and toggling this flag allows + * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#skipCull + * @type {boolean} + * @since 3.11.0 + */ + this.skipCull = false; + + /** + * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. + * By default the camera will allow 1 full tile in all directions. + * + * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#isoCullDistances + * @type {Phaser.Math.Vector2} + * @since 3.23.0 + */ + this.isoCullDistances = new Vector2(1, 1); + + /** + * The total number of tiles drawn by the renderer in the last frame. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tilesDrawn + * @type {integer} + * @readonly + * @since 3.11.0 + */ + this.tilesDrawn = 0; + + /** + * The total number of tiles in this layer. Updated every frame. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#tilesTotal + * @type {integer} + * @readonly + * @since 3.11.0 + */ + this.tilesTotal = this.layer.width * this.layer.height; + + /** + * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#cullPaddingX + * @type {integer} + * @default 1 + * @since 3.11.0 + */ + this.cullPaddingX = 1; + + /** + * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#cullPaddingY + * @type {integer} + * @default 1 + * @since 3.11.0 + */ + this.cullPaddingY = 1; + + /** + * The callback that is invoked when the tiles are culled. + * + * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. + * + * It will be sent 3 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. + * + * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#cullCallback + * @type {function} + * @since 3.11.0 + */ + this.cullCallback = TilemapComponents.CullTiles; + + /** + * The rendering (draw) order of the tiles in this layer. + * + * The default is 0 which is 'right-down', meaning it will draw the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * This can be changed via the `setRenderOrder` method. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#_renderOrder + * @type {integer} + * @default 0 + * @private + * @since 3.12.0 + */ + this._renderOrder = 0; + + /** + * An array holding the mapping between the tile indexes and the tileset they belong to. + * + * @name Phaser.Tilemaps.DynamicTilemapLayer#gidMap + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.14.0 + */ + this.gidMap = []; + + this.setTilesets(tileset); + this.setAlpha(this.layer.alpha); + this.setPosition(x, y); + this.setOrigin(); + this.setSize(tilemap.tileWidth * this.layer.width, tilemap.tileHeight * this.layer.height); + + this.initPipeline('TextureTintPipeline'); + }, + + /** + * Populates the internal `tileset` array with the Tileset references this Layer requires for rendering. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setTilesets + * @private + * @since 3.14.0 + * + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + */ + setTilesets: function (tilesets) + { + var gidMap = []; + var setList = []; + var map = this.tilemap; + + if (!Array.isArray(tilesets)) + { + tilesets = [ tilesets ]; + } + + for (var i = 0; i < tilesets.length; i++) + { + var tileset = tilesets[i]; + + if (typeof tileset === 'string') + { + tileset = map.getTileset(tileset); + } + + if (tileset) + { + setList.push(tileset); + + var s = tileset.firstgid; + + for (var t = 0; t < tileset.total; t++) + { + gidMap[s + t] = tileset; + } + } + } + + this.gidMap = gidMap; + this.tileset = setList; + }, + + /** + * Sets the rendering (draw) order of the tiles in this layer. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setRenderOrder + * @since 3.12.0 + * + * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + * + * @return {this} This Tilemap Layer object. + */ + setRenderOrder: function (renderOrder) + { + var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; + + if (typeof renderOrder === 'string') + { + renderOrder = orders.indexOf(renderOrder); + } + + if (renderOrder >= 0 && renderOrder < 4) + { + this._renderOrder = renderOrder; + } + + return this; + }, + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#calculateFacesAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + calculateFacesAt: function (tileX, tileY) + { + TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); + + return this; + }, + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#calculateFacesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + calculateFacesWithin: function (tileX, tileY, width, height) + { + TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#createFromTiles + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ + createFromTiles: function (indexes, replacements, spriteConfig, scene, camera) + { + return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer); + }, + + /** + * Returns the tiles in the given layer that are within the cameras viewport. + * This is used internally. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#cull + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + cull: function (camera) + { + return this.cullCallback(this.layer, camera, this.culledTiles, this._renderOrder); + }, + + /** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#copy + * @since 3.0.0 + * + * @param {integer} srcTileX - The x coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} srcTileY - The y coordinate of the area to copy from, in tiles, not pixels. + * @param {integer} width - The width of the area to copy, in tiles, not pixels. + * @param {integer} height - The height of the area to copy, in tiles, not pixels. + * @param {integer} destTileX - The x coordinate of the area to copy to, in tiles, not pixels. + * @param {integer} destTileY - The y coordinate of the area to copy to, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + copy: function (srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces) + { + TilemapComponents.Copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, this.layer); + + return this; + }, + + /** + * Destroys this DynamicTilemapLayer and removes its link to the associated LayerData. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#destroy + * @since 3.0.0 + * + * @param {boolean} [removeFromTilemap=true] - Remove this layer from the parent Tilemap? + */ + destroy: function (removeFromTilemap) + { + if (removeFromTilemap === undefined) { removeFromTilemap = true; } + + if (!this.tilemap) + { + // Abort, we've already been destroyed + return; + } + + // Uninstall this layer only if it is still installed on the LayerData object + if (this.layer.tilemapLayer === this) + { + this.layer.tilemapLayer = undefined; + } + + if (removeFromTilemap) + { + this.tilemap.removeLayer(this); + } + + this.tilemap = undefined; + this.layer = undefined; + this.culledTiles.length = 0; + this.cullCallback = null; + + this.gidMap = []; + this.tileset = []; + + GameObject.prototype.destroy.call(this); + }, + + /** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#fill + * @since 3.0.0 + * + * @param {integer} index - The tile index to fill the area with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + fill: function (index, tileX, tileY, width, height, recalculateFaces) + { + TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, this.layer); + + return this; + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#filterTiles + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#findByIndex + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + findByIndex: function (findIndex, skip, reverse) + { + return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer); + }, + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#findTile + * @since 3.0.0 + * + * @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {?Phaser.Tilemaps.Tile} + */ + findTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#forEachTile + * @since 3.0.0 + * + * @param {EachTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to search. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + + return this; + }, + + /** + * Gets a tile at the given tile coordinates from the given layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTileAt: function (tileX, tileY, nonNull) + { + return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer); + }, + + /** + * Gets a tile at the given world coordinates from the given layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ + getTileAtWorldXY: function (worldX, worldY, nonNull, camera) + { + return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithin: function (tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithinShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinShape: function (shape, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#getTilesWithinWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The world x coordinate for the top-left of the area. + * @param {number} worldY - The world y coordinate for the top-left of the area. + * @param {number} width - The width of the area. + * @param {number} height - The height of the area. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#hasTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * + * @return {boolean} `true` if a tile was found at the given location, otherwise `false`. + */ + hasTileAt: function (tileX, tileY) + { + return TilemapComponents.HasTileAt(tileX, tileY, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#hasTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {boolean} `true` if a tile was found at the given location, otherwise `false`. + */ + hasTileAtWorldXY: function (worldX, worldY, camera) + { + return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer); + }, + + /** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#putTileAt + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + putTileAt: function (tile, tileX, tileY, recalculateFaces) + { + return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, this.layer); + }, + + /** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#putTileAtWorldXY + * @since 3.0.0 + * + * @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object. + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + putTileAtWorldXY: function (tile, worldX, worldY, recalculateFaces, camera) + { + return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, this.layer); + }, + + /** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#putTilesAt + * @since 3.0.0 + * + * @param {(integer[]|integer[][]|Phaser.Tilemaps.Tile[]|Phaser.Tilemaps.Tile[][])} tile - A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + putTilesAt: function (tilesArray, tileX, tileY, recalculateFaces) + { + TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, this.layer); + + return this; + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#randomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {integer[]} [indexes] - An array of indexes to randomly draw from during randomization. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + randomize: function (tileX, tileY, width, height, indexes) + { + TilemapComponents.Randomize(tileX, tileY, width, height, indexes, this.layer); + + return this; + }, + + /** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#removeTileAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + removeTileAt: function (tileX, tileY, replaceWithNull, recalculateFaces) + { + return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, this.layer); + }, + + /** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#removeTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate, in pixels. + * @param {number} worldY - The y coordinate, in pixels. + * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. + * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + removeTileAtWorldXY: function (worldX, worldY, replaceWithNull, recalculateFaces, camera) + { + return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, this.layer); + }, + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#renderDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + renderDebug: function (graphics, styleConfig) + { + TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#replaceByIndex + * @since 3.0.0 + * + * @param {integer} findIndex - The index of the tile to search for. + * @param {integer} newIndex - The index of the tile to replace it with. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + replaceByIndex: function (findIndex, newIndex, tileX, tileY, width, height) + { + TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setSkipCull + * @since 3.11.0 + * + * @param {boolean} [value=true] - Set to `true` to stop culling tiles. Set to `false` to enable culling again. + * + * @return {this} This Tilemap Layer object. + */ + setSkipCull: function (value) + { + if (value === undefined) { value = true; } + + this.skipCull = value; + + return this; + }, + + /** + * When a Camera culls the tiles in this layer it does so using its view into the world, building up a + * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size + * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so + * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px + * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCullPadding + * @since 3.11.0 + * + * @param {integer} [paddingX=1] - The amount of extra horizontal tiles to add to the cull check padding. + * @param {integer} [paddingY=1] - The amount of extra vertical tiles to add to the cull check padding. + * + * @return {this} This Tilemap Layer object. + */ + setCullPadding: function (paddingX, paddingY) + { + if (paddingX === undefined) { paddingX = 1; } + if (paddingY === undefined) { paddingY = 1; } + + this.cullPaddingX = paddingX; + this.cullPaddingY = paddingY; + + return this; + }, + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollision + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + * + * @return {?Phaser.Tilemaps.Tilemap} Return this Tilemap object, or null if the layer given was invalid. + */ + setCollision: function (indexes, collides, recalculateFaces, updateLayer) + { + TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer, updateLayer); + + return this; + }, + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionBetween + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionBetween: function (start, stop, collides, recalculateFaces) + { + TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionByProperty + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionByProperty: function (properties, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionByExclusion + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionByExclusion: function (indexes, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking each tiles collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tiles collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setCollisionFromCollisionGroup + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the update. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setCollisionFromCollisionGroup: function (collides, recalculateFaces) + { + TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setTileIndexCallback + * @since 3.0.0 + * + * @param {(integer|integer[])} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setTileIndexCallback: function (indexes, callback, callbackContext) + { + TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#setTileLocationCallback + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {function} [callback] - The callback that will be invoked when the tile is collided with. + * @param {object} [callbackContext] - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext) + { + TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#shuffle + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + shuffle: function (tileX, tileY, width, height) + { + TilemapComponents.Shuffle(tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#swapByIndex + * @since 3.0.0 + * + * @param {integer} tileA - First tile index. + * @param {integer} tileB - Second tile index. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + swapByIndex: function (indexA, indexB, tileX, tileY, width, height) + { + TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldX + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + tileToWorldX: function (tileX, camera) + { + return this.tilemap.TileToWorldX(tileX, camera, this.layer); + }, + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldY + * @since 3.0.0 + * + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + tileToWorldY: function (tileY, camera) + { + return this.tilemap.TileToWorldY(tileY, camera, this.layer); + }, + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#tileToWorldXY + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate, in tiles, not pixels. + * @param {integer} tileY - The y coordinate, in tiles, not pixels. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Math.Vector2} + */ + tileToWorldXY: function (tileX, tileY, point, camera) + { + return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); + }, + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#weightedRandomize + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {object[]} [weightedIndexes] - An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * + * @return {Phaser.Tilemaps.DynamicTilemapLayer} This Tilemap Layer object. + */ + weightedRandomize: function (tileX, tileY, width, height, weightedIndexes) + { + TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, this.layer); + + return this; + }, + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileX + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + worldToTileX: function (worldX, snapToFloor, camera) + { + return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileY + * @since 3.0.0 + * + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + worldToTileY: function (worldY, snapToFloor, camera) + { + return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#worldToTileXY + * @since 3.0.0 + * + * @param {number} worldX - The x coordinate to be converted, in pixels, not tiles. + * @param {number} worldY - The y coordinate to be converted, in pixels, not tiles. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Math.Vector2} + */ + worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) + { + return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + } + +}); + +module.exports = DynamicTilemapLayer; diff --git a/src/tilemaps/dynamiclayer/DynamicTilemapLayerCanvasRenderer.js b/src/tilemaps/dynamiclayer/DynamicTilemapLayerCanvasRenderer.js index 5dc681a68..1ccb17745 100644 --- a/src/tilemaps/dynamiclayer/DynamicTilemapLayerCanvasRenderer.js +++ b/src/tilemaps/dynamiclayer/DynamicTilemapLayerCanvasRenderer.js @@ -1,139 +1,139 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../const.js'); - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - src.cull(camera); - - var renderTiles = src.culledTiles; - var tileCount = renderTiles.length; - if (tileCount === 0) - { - return; - } - - var camMatrix = renderer._tempMatrix1; - var layerMatrix = renderer._tempMatrix2; - var calcMatrix = renderer._tempMatrix3; - - layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - var ctx = renderer.currentContext; - var gidMap = src.gidMap; - - ctx.save(); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - layerMatrix.e = src.x; - layerMatrix.f = src.y; - - // Multiply by the Sprite matrix, store result in calcMatrix - camMatrix.multiply(layerMatrix, calcMatrix); - - calcMatrix.copyToContext(ctx); - } - else - { - layerMatrix.e -= camera.scrollX * src.scrollFactorX; - layerMatrix.f -= camera.scrollY * src.scrollFactorY; - - layerMatrix.copyToContext(ctx); - } - - var alpha = camera.alpha * src.alpha; - - if (!renderer.antialias || src.scaleX > 1 || src.scaleY > 1) - { - ctx.imageSmoothingEnabled = false; - } - - for (var i = 0; i < tileCount; i++) - { - - var tile = renderTiles[i]; - var tileset = gidMap[tile.index]; - - if (!tileset) - { - continue; - } - - var image = tileset.image.getSourceImage(); - - var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); - - if (tileTexCoords) - { - var width = tile.width; - var height = tile.width; - - if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) - { - // we use the tileset width and height because in isometric and hexagonal maps the tileset's height is often different from the tilemap's. - width = tileset.tileWidth; - height = tileset.tileHeight; - } - - var halfWidth = width / 2; - var halfHeight = height / 2; - - ctx.save(); - - ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); - - if (tile.rotation !== 0) - { - ctx.rotate(tile.rotation); - } - - if (tile.flipX || tile.flipY) - { - ctx.scale((tile.flipX) ? -1 : 1, (tile.flipY) ? -1 : 1); - } - - ctx.globalAlpha = alpha * tile.alpha; - - ctx.drawImage( - image, - tileTexCoords.x, tileTexCoords.y, - tileset.tileWidth, tileset.tileHeight, - -halfWidth, -halfHeight, - width, height - ); - - ctx.restore(); - } - - } - - ctx.restore(); -}; - -module.exports = DynamicTilemapLayerCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../const.js'); + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var DynamicTilemapLayerCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.cull(camera); + + var renderTiles = src.culledTiles; + var tileCount = renderTiles.length; + if (tileCount === 0) + { + return; + } + + var camMatrix = renderer._tempMatrix1; + var layerMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + var ctx = renderer.currentContext; + var gidMap = src.gidMap; + + ctx.save(); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + layerMatrix.e = src.x; + layerMatrix.f = src.y; + + // Multiply by the Sprite matrix, store result in calcMatrix + camMatrix.multiply(layerMatrix, calcMatrix); + + calcMatrix.copyToContext(ctx); + } + else + { + layerMatrix.e -= camera.scrollX * src.scrollFactorX; + layerMatrix.f -= camera.scrollY * src.scrollFactorY; + + layerMatrix.copyToContext(ctx); + } + + var alpha = camera.alpha * src.alpha; + + if (!renderer.antialias || src.scaleX > 1 || src.scaleY > 1) + { + ctx.imageSmoothingEnabled = false; + } + + for (var i = 0; i < tileCount; i++) + { + + var tile = renderTiles[i]; + var tileset = gidMap[tile.index]; + + if (!tileset) + { + continue; + } + + var image = tileset.image.getSourceImage(); + + var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); + + if (tileTexCoords) + { + var width = tile.width; + var height = tile.width; + + if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) + { + // we use the tileset width and height because in isometric and hexagonal maps the tileset's height is often different from the tilemap's. + width = tileset.tileWidth; + height = tileset.tileHeight; + } + + var halfWidth = width / 2; + var halfHeight = height / 2; + + ctx.save(); + + ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); + + if (tile.rotation !== 0) + { + ctx.rotate(tile.rotation); + } + + if (tile.flipX || tile.flipY) + { + ctx.scale((tile.flipX) ? -1 : 1, (tile.flipY) ? -1 : 1); + } + + ctx.globalAlpha = alpha * tile.alpha; + + ctx.drawImage( + image, + tileTexCoords.x, tileTexCoords.y, + tileset.tileWidth, tileset.tileHeight, + -halfWidth, -halfHeight, + width, height + ); + + ctx.restore(); + } + + } + + ctx.restore(); +}; + +module.exports = DynamicTilemapLayerCanvasRenderer; diff --git a/src/tilemaps/dynamiclayer/DynamicTilemapLayerRender.js b/src/tilemaps/dynamiclayer/DynamicTilemapLayerRender.js index e0b9089c3..0b31d29c9 100644 --- a/src/tilemaps/dynamiclayer/DynamicTilemapLayerRender.js +++ b/src/tilemaps/dynamiclayer/DynamicTilemapLayerRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./DynamicTilemapLayerWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./DynamicTilemapLayerCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./DynamicTilemapLayerWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./DynamicTilemapLayerCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/tilemaps/dynamiclayer/DynamicTilemapLayerWebGLRenderer.js b/src/tilemaps/dynamiclayer/DynamicTilemapLayerWebGLRenderer.js index 747f6906c..2d771fbdf 100644 --- a/src/tilemaps/dynamiclayer/DynamicTilemapLayerWebGLRenderer.js +++ b/src/tilemaps/dynamiclayer/DynamicTilemapLayerWebGLRenderer.js @@ -1,125 +1,125 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - - -var Utils = require('../../renderer/webgl/Utils'); -var CONST = require('../../const.js'); - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.Tilemaps.DynamicTilemapLayer#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera) -{ - src.cull(camera); - - var renderTiles = src.culledTiles; - var tileCount = renderTiles.length; - var alpha = camera.alpha * src.alpha; - - if (tileCount === 0 || alpha <= 0) - { - return; - } - - var gidMap = src.gidMap; - var pipeline = src.pipeline; - - var getTint = Utils.getTintAppendFloatAlphaAndSwap; - - var scrollFactorX = src.scrollFactorX; - var scrollFactorY = src.scrollFactorY; - - var x = src.x; - var y = src.y; - - var sx = src.scaleX; - var sy = src.scaleY; - - var tilesets = src.tileset; - - // Loop through each tileset in this layer, drawing just the tiles that are in that set each time - // Doing it this way around allows us to batch tiles using the same tileset - for (var c = 0; c < tilesets.length; c++) - { - var currentSet = tilesets[c]; - var texture = currentSet.glTexture; - - for (var i = 0; i < tileCount; i++) - { - var tile = renderTiles[i]; - - var tileset = gidMap[tile.index]; - - if (tileset !== currentSet) - { - // Skip tiles that aren't in this set - continue; - } - - var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); - - if (tileTexCoords === null) - { - continue; - } - - var frameWidth = 0; - var frameHeight = 0; - - if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) - { - // we use the tileset width and height because in isometric maps the tileset's height is often different from the tilemap's. - frameWidth = tileset.tileWidth; - frameHeight = tileset.tileHeight; - } - else - { - frameWidth = tile.width; - frameHeight = tile.height; - } - - var frameX = tileTexCoords.x; - var frameY = tileTexCoords.y; - - var tw = frameWidth * 0.5; - var th = frameHeight * 0.5; - - var tint = getTint(tile.tint, alpha * tile.alpha); - - pipeline.batchTexture( - src, - texture, - texture.width, texture.height, - x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy), - frameWidth, frameHeight, - sx, sy, - tile.rotation, - tile.flipX, tile.flipY, - scrollFactorX, scrollFactorY, - tw, th, - frameX, frameY, frameWidth, frameHeight, - tint, tint, tint, tint, false, - 0, 0, - camera, - null, - true - ); - } - } -}; - -module.exports = DynamicTilemapLayerWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + + +var Utils = require('../../renderer/webgl/Utils'); +var CONST = require('../../const.js'); + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.Tilemaps.DynamicTilemapLayer#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var DynamicTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera) +{ + src.cull(camera); + + var renderTiles = src.culledTiles; + var tileCount = renderTiles.length; + var alpha = camera.alpha * src.alpha; + + if (tileCount === 0 || alpha <= 0) + { + return; + } + + var gidMap = src.gidMap; + var pipeline = src.pipeline; + + var getTint = Utils.getTintAppendFloatAlphaAndSwap; + + var scrollFactorX = src.scrollFactorX; + var scrollFactorY = src.scrollFactorY; + + var x = src.x; + var y = src.y; + + var sx = src.scaleX; + var sy = src.scaleY; + + var tilesets = src.tileset; + + // Loop through each tileset in this layer, drawing just the tiles that are in that set each time + // Doing it this way around allows us to batch tiles using the same tileset + for (var c = 0; c < tilesets.length; c++) + { + var currentSet = tilesets[c]; + var texture = currentSet.glTexture; + + for (var i = 0; i < tileCount; i++) + { + var tile = renderTiles[i]; + + var tileset = gidMap[tile.index]; + + if (tileset !== currentSet) + { + // Skip tiles that aren't in this set + continue; + } + + var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); + + if (tileTexCoords === null) + { + continue; + } + + var frameWidth = 0; + var frameHeight = 0; + + if (src.layer.orientation === CONST.ISOMETRIC || src.layer.orientation === CONST.STAGGERED || src.layer.orientation === CONST.HEXAGONAL) + { + // we use the tileset width and height because in isometric maps the tileset's height is often different from the tilemap's. + frameWidth = tileset.tileWidth; + frameHeight = tileset.tileHeight; + } + else + { + frameWidth = tile.width; + frameHeight = tile.height; + } + + var frameX = tileTexCoords.x; + var frameY = tileTexCoords.y; + + var tw = frameWidth * 0.5; + var th = frameHeight * 0.5; + + var tint = getTint(tile.tint, alpha * tile.alpha); + + pipeline.batchTexture( + src, + texture, + texture.width, texture.height, + x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy), + frameWidth, frameHeight, + sx, sy, + tile.rotation, + tile.flipX, tile.flipY, + scrollFactorX, scrollFactorY, + tw, th, + frameX, frameY, frameWidth, frameHeight, + tint, tint, tint, tint, false, + 0, 0, + camera, + null, + true + ); + } + } +}; + +module.exports = DynamicTilemapLayerWebGLRenderer; diff --git a/src/tilemaps/index.js b/src/tilemaps/index.js index 5f9b119c1..7185c020a 100644 --- a/src/tilemaps/index.js +++ b/src/tilemaps/index.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps - */ - -module.exports = { - - Components: require('./components'), - Parsers: require('./parsers'), - - Formats: require('./Formats'), - ImageCollection: require('./ImageCollection'), - ParseToTilemap: require('./ParseToTilemap'), - Tile: require('./Tile'), - Tilemap: require('./Tilemap'), - TilemapCreator: require('./TilemapCreator'), - TilemapFactory: require('./TilemapFactory'), - Tileset: require('./Tileset'), - - LayerData: require('./mapdata/LayerData'), - MapData: require('./mapdata/MapData'), - ObjectLayer: require('./mapdata/ObjectLayer'), - - DynamicTilemapLayer: require('./dynamiclayer/DynamicTilemapLayer'), - StaticTilemapLayer: require('./staticlayer/StaticTilemapLayer') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps + */ + +module.exports = { + + Components: require('./components'), + Parsers: require('./parsers'), + + Formats: require('./Formats'), + ImageCollection: require('./ImageCollection'), + ParseToTilemap: require('./ParseToTilemap'), + Tile: require('./Tile'), + Tilemap: require('./Tilemap'), + TilemapCreator: require('./TilemapCreator'), + TilemapFactory: require('./TilemapFactory'), + Tileset: require('./Tileset'), + + LayerData: require('./mapdata/LayerData'), + MapData: require('./mapdata/MapData'), + ObjectLayer: require('./mapdata/ObjectLayer'), + + DynamicTilemapLayer: require('./dynamiclayer/DynamicTilemapLayer'), + StaticTilemapLayer: require('./staticlayer/StaticTilemapLayer') + +}; diff --git a/src/tilemaps/mapdata/LayerData.js b/src/tilemaps/mapdata/LayerData.js index 77fbbd9b6..674785a14 100644 --- a/src/tilemaps/mapdata/LayerData.js +++ b/src/tilemaps/mapdata/LayerData.js @@ -1,234 +1,234 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var CONST = require('../../const.js'); - -/** - * @classdesc - * A class for representing data about about a layer in a map. Maps are parsed from CSV, Tiled, - * etc. into this format. Tilemap, StaticTilemapLayer and DynamicTilemapLayer have a reference - * to this data and use it to look up and perform operations on tiles. - * - * @class LayerData - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.0 - * - * @param {object} [config] - [description] - */ -var LayerData = new Class({ - - initialize: - - function LayerData (config) - { - if (config === undefined) { config = {}; } - - /** - * The name of the layer, if specified in Tiled. - * - * @name Phaser.Tilemaps.LayerData#name - * @type {string} - * @since 3.0.0 - */ - this.name = GetFastValue(config, 'name', 'layer'); - - /** - * The x offset of where to draw from the top left - * - * @name Phaser.Tilemaps.LayerData#x - * @type {number} - * @since 3.0.0 - */ - this.x = GetFastValue(config, 'x', 0); - - /** - * The y offset of where to draw from the top left - * - * @name Phaser.Tilemaps.LayerData#y - * @type {number} - * @since 3.0.0 - */ - this.y = GetFastValue(config, 'y', 0); - - /** - * The width in tile of the layer. - * - * @name Phaser.Tilemaps.LayerData#width - * @type {number} - * @since 3.0.0 - */ - this.width = GetFastValue(config, 'width', 0); - - /** - * The height in tiles of the layer. - * - * @name Phaser.Tilemaps.LayerData#height - * @type {number} - * @since 3.0.0 - */ - this.height = GetFastValue(config, 'height', 0); - - /** - * The pixel width of the tiles. - * - * @name Phaser.Tilemaps.LayerData#tileWidth - * @type {number} - * @since 3.0.0 - */ - this.tileWidth = GetFastValue(config, 'tileWidth', 0); - - /** - * The pixel height of the tiles. - * - * @name Phaser.Tilemaps.LayerData#tileHeight - * @type {number} - * @since 3.0.0 - */ - this.tileHeight = GetFastValue(config, 'tileHeight', 0); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#baseTileWidth - * @type {number} - * @since 3.0.0 - */ - this.baseTileWidth = GetFastValue(config, 'baseTileWidth', this.tileWidth); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#baseTileHeight - * @type {number} - * @since 3.0.0 - */ - this.baseTileHeight = GetFastValue(config, 'baseTileHeight', this.tileHeight); - - /** - * The layer's orientation, necessary to be able to determine a tile's pixelX and pixelY as well as the layer's width and height. - * - * @name Phaser.Tilemaps.LayerData#orientation - * @type {string} - * @since 3.23beta.PR_svipal - */ - this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); - - /** - * The width in pixels of the entire layer. - * - * @name Phaser.Tilemaps.LayerData#widthInPixels - * @type {number} - * @since 3.0.0 - */ - this.widthInPixels = GetFastValue(config, 'widthInPixels', this.width * this.baseTileWidth); - - /** - * The height in pixels of the entire layer. - * - * @name Phaser.Tilemaps.LayerData#heightInPixels - * @type {number} - * @since 3.0.0 - */ - this.heightInPixels = GetFastValue(config, 'heightInPixels', this.height * this.baseTileHeight); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#alpha - * @type {number} - * @since 3.0.0 - */ - this.alpha = GetFastValue(config, 'alpha', 1); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#visible - * @type {boolean} - * @since 3.0.0 - */ - this.visible = GetFastValue(config, 'visible', true); - - /** - * Layer specific properties (can be specified in Tiled) - * - * @name Phaser.Tilemaps.LayerData#properties - * @type {object} - * @since 3.0.0 - */ - this.properties = GetFastValue(config, 'properties', {}); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#indexes - * @type {array} - * @since 3.0.0 - */ - this.indexes = GetFastValue(config, 'indexes', []); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#collideIndexes - * @type {array} - * @since 3.0.0 - */ - this.collideIndexes = GetFastValue(config, 'collideIndexes', []); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#callbacks - * @type {array} - * @since 3.0.0 - */ - this.callbacks = GetFastValue(config, 'callbacks', []); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#bodies - * @type {array} - * @since 3.0.0 - */ - this.bodies = GetFastValue(config, 'bodies', []); - - /** - * An array of the tile indexes - * - * @name Phaser.Tilemaps.LayerData#data - * @type {Phaser.Tilemaps.Tile[][]} - * @since 3.0.0 - */ - this.data = GetFastValue(config, 'data', []); - - /** - * [description] - * - * @name Phaser.Tilemaps.LayerData#tilemapLayer - * @type {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} - * @since 3.0.0 - */ - this.tilemapLayer = GetFastValue(config, 'tilemapLayer', null); - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); - - } - -}); - -module.exports = LayerData; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var CONST = require('../../const.js'); + +/** + * @classdesc + * A class for representing data about about a layer in a map. Maps are parsed from CSV, Tiled, + * etc. into this format. Tilemap, StaticTilemapLayer and DynamicTilemapLayer have a reference + * to this data and use it to look up and perform operations on tiles. + * + * @class LayerData + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {object} [config] - [description] + */ +var LayerData = new Class({ + + initialize: + + function LayerData (config) + { + if (config === undefined) { config = {}; } + + /** + * The name of the layer, if specified in Tiled. + * + * @name Phaser.Tilemaps.LayerData#name + * @type {string} + * @since 3.0.0 + */ + this.name = GetFastValue(config, 'name', 'layer'); + + /** + * The x offset of where to draw from the top left + * + * @name Phaser.Tilemaps.LayerData#x + * @type {number} + * @since 3.0.0 + */ + this.x = GetFastValue(config, 'x', 0); + + /** + * The y offset of where to draw from the top left + * + * @name Phaser.Tilemaps.LayerData#y + * @type {number} + * @since 3.0.0 + */ + this.y = GetFastValue(config, 'y', 0); + + /** + * The width in tile of the layer. + * + * @name Phaser.Tilemaps.LayerData#width + * @type {number} + * @since 3.0.0 + */ + this.width = GetFastValue(config, 'width', 0); + + /** + * The height in tiles of the layer. + * + * @name Phaser.Tilemaps.LayerData#height + * @type {number} + * @since 3.0.0 + */ + this.height = GetFastValue(config, 'height', 0); + + /** + * The pixel width of the tiles. + * + * @name Phaser.Tilemaps.LayerData#tileWidth + * @type {number} + * @since 3.0.0 + */ + this.tileWidth = GetFastValue(config, 'tileWidth', 0); + + /** + * The pixel height of the tiles. + * + * @name Phaser.Tilemaps.LayerData#tileHeight + * @type {number} + * @since 3.0.0 + */ + this.tileHeight = GetFastValue(config, 'tileHeight', 0); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#baseTileWidth + * @type {number} + * @since 3.0.0 + */ + this.baseTileWidth = GetFastValue(config, 'baseTileWidth', this.tileWidth); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#baseTileHeight + * @type {number} + * @since 3.0.0 + */ + this.baseTileHeight = GetFastValue(config, 'baseTileHeight', this.tileHeight); + + /** + * The layer's orientation, necessary to be able to determine a tile's pixelX and pixelY as well as the layer's width and height. + * + * @name Phaser.Tilemaps.LayerData#orientation + * @type {string} + * @since 3.23beta.PR_svipal + */ + this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); + + /** + * The width in pixels of the entire layer. + * + * @name Phaser.Tilemaps.LayerData#widthInPixels + * @type {number} + * @since 3.0.0 + */ + this.widthInPixels = GetFastValue(config, 'widthInPixels', this.width * this.baseTileWidth); + + /** + * The height in pixels of the entire layer. + * + * @name Phaser.Tilemaps.LayerData#heightInPixels + * @type {number} + * @since 3.0.0 + */ + this.heightInPixels = GetFastValue(config, 'heightInPixels', this.height * this.baseTileHeight); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#alpha + * @type {number} + * @since 3.0.0 + */ + this.alpha = GetFastValue(config, 'alpha', 1); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#visible + * @type {boolean} + * @since 3.0.0 + */ + this.visible = GetFastValue(config, 'visible', true); + + /** + * Layer specific properties (can be specified in Tiled) + * + * @name Phaser.Tilemaps.LayerData#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = GetFastValue(config, 'properties', {}); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#indexes + * @type {array} + * @since 3.0.0 + */ + this.indexes = GetFastValue(config, 'indexes', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#collideIndexes + * @type {array} + * @since 3.0.0 + */ + this.collideIndexes = GetFastValue(config, 'collideIndexes', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#callbacks + * @type {array} + * @since 3.0.0 + */ + this.callbacks = GetFastValue(config, 'callbacks', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#bodies + * @type {array} + * @since 3.0.0 + */ + this.bodies = GetFastValue(config, 'bodies', []); + + /** + * An array of the tile indexes + * + * @name Phaser.Tilemaps.LayerData#data + * @type {Phaser.Tilemaps.Tile[][]} + * @since 3.0.0 + */ + this.data = GetFastValue(config, 'data', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.LayerData#tilemapLayer + * @type {(Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer)} + * @since 3.0.0 + */ + this.tilemapLayer = GetFastValue(config, 'tilemapLayer', null); + + /** + * Optional : Only for hexagonal tilemaps. + * The length of the horizontal sides of the hexagon. + * @name Phaser.Tilemaps.MapData#tiles + * @type {integer} + * @since 3.0.0 + */ + this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); + + } + +}); + +module.exports = LayerData; diff --git a/src/tilemaps/mapdata/MapData.js b/src/tilemaps/mapdata/MapData.js index c813e7edb..52a28c028 100644 --- a/src/tilemaps/mapdata/MapData.js +++ b/src/tilemaps/mapdata/MapData.js @@ -1,229 +1,229 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetFastValue = require('../../utils/object/GetFastValue'); -var CONST = require('../../const.js'); - -/** - * @classdesc - * A class for representing data about a map. Maps are parsed from CSV, Tiled, etc. into this - * format. A Tilemap object get a copy of this data and then unpacks the needed properties into - * itself. - * - * @class MapData - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.Tilemaps.MapDataConfig} [config] - The Map configuration object. - */ -var MapData = new Class({ - - initialize: - - function MapData (config) - { - if (config === undefined) { config = {}; } - - /** - * The key in the Phaser cache that corresponds to the loaded tilemap data. - * - * @name Phaser.Tilemaps.MapData#name - * @type {string} - * @since 3.0.0 - */ - this.name = GetFastValue(config, 'name', 'map'); - - /** - * The width of the entire tilemap. - * - * @name Phaser.Tilemaps.MapData#width - * @type {number} - * @since 3.0.0 - */ - this.width = GetFastValue(config, 'width', 0); - - /** - * The height of the entire tilemap. - * - * @name Phaser.Tilemaps.MapData#height - * @type {number} - * @since 3.0.0 - */ - this.height = GetFastValue(config, 'height', 0); - - /** - * If the map is infinite or not. - * - * @name Phaser.Tilemaps.MapData#infinite - * @type {boolean} - * @since 3.17.0 - */ - this.infinite = GetFastValue(config, 'infinite', false); - - /** - * The width of the tiles. - * - * @name Phaser.Tilemaps.MapData#tileWidth - * @type {number} - * @since 3.0.0 - */ - this.tileWidth = GetFastValue(config, 'tileWidth', 0); - - /** - * The height of the tiles. - * - * @name Phaser.Tilemaps.MapData#tileHeight - * @type {number} - * @since 3.0.0 - */ - this.tileHeight = GetFastValue(config, 'tileHeight', 0); - - /** - * The width in pixels of the entire tilemap. - * - * @name Phaser.Tilemaps.MapData#widthInPixels - * @type {number} - * @since 3.0.0 - */ - this.widthInPixels = GetFastValue(config, 'widthInPixels', this.width * this.tileWidth); - - /** - * The height in pixels of the entire tilemap. - * - * @name Phaser.Tilemaps.MapData#heightInPixels - * @type {number} - * @since 3.0.0 - */ - this.heightInPixels = GetFastValue(config, 'heightInPixels', this.height * this.tileHeight); - - /** - * [description] - * - * @name Phaser.Tilemaps.MapData#format - * @type {integer} - * @since 3.0.0 - */ - this.format = GetFastValue(config, 'format', null); - - /** - * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. - * - * @name Phaser.Tilemaps.MapData#orientation - * @type {string} - * @since 3.0.0 - */ - this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); - - /** - * Determines the draw order of tilemap. Default is right-down - * - * 0, or 'right-down' - * 1, or 'left-down' - * 2, or 'right-up' - * 3, or 'left-up' - * - * @name Phaser.Tilemaps.MapData#renderOrder - * @type {string} - * @since 3.12.0 - */ - this.renderOrder = GetFastValue(config, 'renderOrder', 'right-down'); - - /** - * The version of the map data (as specified in Tiled). - * - * @name Phaser.Tilemaps.MapData#version - * @type {string} - * @since 3.0.0 - */ - this.version = GetFastValue(config, 'version', '1'); - - /** - * Map specific properties (can be specified in Tiled) - * - * @name Phaser.Tilemaps.MapData#properties - * @type {object} - * @since 3.0.0 - */ - this.properties = GetFastValue(config, 'properties', {}); - - /** - * An array with all the layers configured to the MapData. - * - * @name Phaser.Tilemaps.MapData#layers - * @type {(Phaser.Tilemaps.LayerData[]|Phaser.Tilemaps.ObjectLayer)} - * @since 3.0.0 - */ - this.layers = GetFastValue(config, 'layers', []); - - /** - * An array of Tiled Image Layers. - * - * @name Phaser.Tilemaps.MapData#images - * @type {array} - * @since 3.0.0 - */ - this.images = GetFastValue(config, 'images', []); - - /** - * An object of Tiled Object Layers. - * - * @name Phaser.Tilemaps.MapData#objects - * @type {object} - * @since 3.0.0 - */ - this.objects = GetFastValue(config, 'objects', {}); - - /** - * An object of collision data. Must be created as physics object or will return undefined. - * - * @name Phaser.Tilemaps.MapData#collision - * @type {object} - * @since 3.0.0 - */ - this.collision = GetFastValue(config, 'collision', {}); - - /** - * An array of Tilesets. - * - * @name Phaser.Tilemaps.MapData#tilesets - * @type {Phaser.Tilemaps.Tileset[]} - * @since 3.0.0 - */ - this.tilesets = GetFastValue(config, 'tilesets', []); - - /** - * The collection of images the map uses(specified in Tiled) - * - * @name Phaser.Tilemaps.MapData#imageCollections - * @type {array} - * @since 3.0.0 - */ - this.imageCollections = GetFastValue(config, 'imageCollections', []); - - /** - * [description] - * - * @name Phaser.Tilemaps.MapData#tiles - * @type {array} - * @since 3.0.0 - */ - this.tiles = GetFastValue(config, 'tiles', []); - - /** - * Optional : Only for hexagonal tilemaps. - * The length of the horizontal sides of the hexagon. - * @name Phaser.Tilemaps.MapData#tiles - * @type {integer} - * @since 3.0.0 - */ - this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); - } - -}); - -module.exports = MapData; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetFastValue = require('../../utils/object/GetFastValue'); +var CONST = require('../../const.js'); + +/** + * @classdesc + * A class for representing data about a map. Maps are parsed from CSV, Tiled, etc. into this + * format. A Tilemap object get a copy of this data and then unpacks the needed properties into + * itself. + * + * @class MapData + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Tilemaps.MapDataConfig} [config] - The Map configuration object. + */ +var MapData = new Class({ + + initialize: + + function MapData (config) + { + if (config === undefined) { config = {}; } + + /** + * The key in the Phaser cache that corresponds to the loaded tilemap data. + * + * @name Phaser.Tilemaps.MapData#name + * @type {string} + * @since 3.0.0 + */ + this.name = GetFastValue(config, 'name', 'map'); + + /** + * The width of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#width + * @type {number} + * @since 3.0.0 + */ + this.width = GetFastValue(config, 'width', 0); + + /** + * The height of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#height + * @type {number} + * @since 3.0.0 + */ + this.height = GetFastValue(config, 'height', 0); + + /** + * If the map is infinite or not. + * + * @name Phaser.Tilemaps.MapData#infinite + * @type {boolean} + * @since 3.17.0 + */ + this.infinite = GetFastValue(config, 'infinite', false); + + /** + * The width of the tiles. + * + * @name Phaser.Tilemaps.MapData#tileWidth + * @type {number} + * @since 3.0.0 + */ + this.tileWidth = GetFastValue(config, 'tileWidth', 0); + + /** + * The height of the tiles. + * + * @name Phaser.Tilemaps.MapData#tileHeight + * @type {number} + * @since 3.0.0 + */ + this.tileHeight = GetFastValue(config, 'tileHeight', 0); + + /** + * The width in pixels of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#widthInPixels + * @type {number} + * @since 3.0.0 + */ + this.widthInPixels = GetFastValue(config, 'widthInPixels', this.width * this.tileWidth); + + /** + * The height in pixels of the entire tilemap. + * + * @name Phaser.Tilemaps.MapData#heightInPixels + * @type {number} + * @since 3.0.0 + */ + this.heightInPixels = GetFastValue(config, 'heightInPixels', this.height * this.tileHeight); + + /** + * [description] + * + * @name Phaser.Tilemaps.MapData#format + * @type {integer} + * @since 3.0.0 + */ + this.format = GetFastValue(config, 'format', null); + + /** + * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. + * + * @name Phaser.Tilemaps.MapData#orientation + * @type {string} + * @since 3.0.0 + */ + this.orientation = GetFastValue(config, 'orientation', CONST.ORTHOGONAL); + + /** + * Determines the draw order of tilemap. Default is right-down + * + * 0, or 'right-down' + * 1, or 'left-down' + * 2, or 'right-up' + * 3, or 'left-up' + * + * @name Phaser.Tilemaps.MapData#renderOrder + * @type {string} + * @since 3.12.0 + */ + this.renderOrder = GetFastValue(config, 'renderOrder', 'right-down'); + + /** + * The version of the map data (as specified in Tiled). + * + * @name Phaser.Tilemaps.MapData#version + * @type {string} + * @since 3.0.0 + */ + this.version = GetFastValue(config, 'version', '1'); + + /** + * Map specific properties (can be specified in Tiled) + * + * @name Phaser.Tilemaps.MapData#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = GetFastValue(config, 'properties', {}); + + /** + * An array with all the layers configured to the MapData. + * + * @name Phaser.Tilemaps.MapData#layers + * @type {(Phaser.Tilemaps.LayerData[]|Phaser.Tilemaps.ObjectLayer)} + * @since 3.0.0 + */ + this.layers = GetFastValue(config, 'layers', []); + + /** + * An array of Tiled Image Layers. + * + * @name Phaser.Tilemaps.MapData#images + * @type {array} + * @since 3.0.0 + */ + this.images = GetFastValue(config, 'images', []); + + /** + * An object of Tiled Object Layers. + * + * @name Phaser.Tilemaps.MapData#objects + * @type {object} + * @since 3.0.0 + */ + this.objects = GetFastValue(config, 'objects', {}); + + /** + * An object of collision data. Must be created as physics object or will return undefined. + * + * @name Phaser.Tilemaps.MapData#collision + * @type {object} + * @since 3.0.0 + */ + this.collision = GetFastValue(config, 'collision', {}); + + /** + * An array of Tilesets. + * + * @name Phaser.Tilemaps.MapData#tilesets + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tilesets = GetFastValue(config, 'tilesets', []); + + /** + * The collection of images the map uses(specified in Tiled) + * + * @name Phaser.Tilemaps.MapData#imageCollections + * @type {array} + * @since 3.0.0 + */ + this.imageCollections = GetFastValue(config, 'imageCollections', []); + + /** + * [description] + * + * @name Phaser.Tilemaps.MapData#tiles + * @type {array} + * @since 3.0.0 + */ + this.tiles = GetFastValue(config, 'tiles', []); + + /** + * Optional : Only for hexagonal tilemaps. + * The length of the horizontal sides of the hexagon. + * @name Phaser.Tilemaps.MapData#tiles + * @type {integer} + * @since 3.0.0 + */ + this.hexSideLength = GetFastValue(config, 'hexSideLength', 0); + } + +}); + +module.exports = MapData; diff --git a/src/tilemaps/mapdata/ObjectLayer.js b/src/tilemaps/mapdata/ObjectLayer.js index fe6c042b2..2f7068b66 100644 --- a/src/tilemaps/mapdata/ObjectLayer.js +++ b/src/tilemaps/mapdata/ObjectLayer.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var GetFastValue = require('../../utils/object/GetFastValue'); - -/** - * @classdesc - * A class for representing a Tiled object layer in a map. This mirrors the structure of a Tiled - * object layer, except: - * - "x" & "y" properties are ignored since these cannot be changed in Tiled. - * - "offsetx" & "offsety" are applied to the individual object coordinates directly, so they - * are ignored as well. - * - "draworder" is ignored. - * - * @class ObjectLayer - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Types.Tilemaps.ObjectLayerConfig} [config] - The data for the layer from the Tiled JSON object. - */ -var ObjectLayer = new Class({ - - initialize: - - function ObjectLayer (config) - { - if (config === undefined) { config = {}; } - - /** - * The name of the Object Layer. - * - * @name Phaser.Tilemaps.ObjectLayer#name - * @type {string} - * @since 3.0.0 - */ - this.name = GetFastValue(config, 'name', 'object layer'); - - /** - * The opacity of the layer, between 0 and 1. - * - * @name Phaser.Tilemaps.ObjectLayer#opacity - * @type {number} - * @since 3.0.0 - */ - this.opacity = GetFastValue(config, 'opacity', 1); - - /** - * The custom properties defined on the Object Layer, keyed by their name. - * - * @name Phaser.Tilemaps.ObjectLayer#properties - * @type {object} - * @since 3.0.0 - */ - this.properties = GetFastValue(config, 'properties', {}); - - /** - * The type of each custom property defined on the Object Layer, keyed by its name. - * - * @name Phaser.Tilemaps.ObjectLayer#propertyTypes - * @type {object} - * @since 3.0.0 - */ - this.propertyTypes = GetFastValue(config, 'propertytypes', {}); - - /** - * The type of the layer, which should be `objectgroup`. - * - * @name Phaser.Tilemaps.ObjectLayer#type - * @type {string} - * @since 3.0.0 - */ - this.type = GetFastValue(config, 'type', 'objectgroup'); - - /** - * Whether the layer is shown (`true`) or hidden (`false`). - * - * @name Phaser.Tilemaps.ObjectLayer#visible - * @type {boolean} - * @since 3.0.0 - */ - this.visible = GetFastValue(config, 'visible', true); - - /** - * 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 - */ - this.objects = GetFastValue(config, 'objects', []); - } - -}); - -module.exports = ObjectLayer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var GetFastValue = require('../../utils/object/GetFastValue'); + +/** + * @classdesc + * A class for representing a Tiled object layer in a map. This mirrors the structure of a Tiled + * object layer, except: + * - "x" & "y" properties are ignored since these cannot be changed in Tiled. + * - "offsetx" & "offsety" are applied to the individual object coordinates directly, so they + * are ignored as well. + * - "draworder" is ignored. + * + * @class ObjectLayer + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Types.Tilemaps.ObjectLayerConfig} [config] - The data for the layer from the Tiled JSON object. + */ +var ObjectLayer = new Class({ + + initialize: + + function ObjectLayer (config) + { + if (config === undefined) { config = {}; } + + /** + * The name of the Object Layer. + * + * @name Phaser.Tilemaps.ObjectLayer#name + * @type {string} + * @since 3.0.0 + */ + this.name = GetFastValue(config, 'name', 'object layer'); + + /** + * The opacity of the layer, between 0 and 1. + * + * @name Phaser.Tilemaps.ObjectLayer#opacity + * @type {number} + * @since 3.0.0 + */ + this.opacity = GetFastValue(config, 'opacity', 1); + + /** + * The custom properties defined on the Object Layer, keyed by their name. + * + * @name Phaser.Tilemaps.ObjectLayer#properties + * @type {object} + * @since 3.0.0 + */ + this.properties = GetFastValue(config, 'properties', {}); + + /** + * The type of each custom property defined on the Object Layer, keyed by its name. + * + * @name Phaser.Tilemaps.ObjectLayer#propertyTypes + * @type {object} + * @since 3.0.0 + */ + this.propertyTypes = GetFastValue(config, 'propertytypes', {}); + + /** + * The type of the layer, which should be `objectgroup`. + * + * @name Phaser.Tilemaps.ObjectLayer#type + * @type {string} + * @since 3.0.0 + */ + this.type = GetFastValue(config, 'type', 'objectgroup'); + + /** + * Whether the layer is shown (`true`) or hidden (`false`). + * + * @name Phaser.Tilemaps.ObjectLayer#visible + * @type {boolean} + * @since 3.0.0 + */ + this.visible = GetFastValue(config, 'visible', true); + + /** + * 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 + */ + this.objects = GetFastValue(config, 'objects', []); + } + +}); + +module.exports = ObjectLayer; diff --git a/src/tilemaps/parsers/Parse.js b/src/tilemaps/parsers/Parse.js index b40ae6b3a..0bce4f039 100644 --- a/src/tilemaps/parsers/Parse.js +++ b/src/tilemaps/parsers/Parse.js @@ -1,64 +1,64 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = require('../Formats'); -var Parse2DArray = require('./Parse2DArray'); -var ParseCSV = require('./ParseCSV'); -var ParseJSONTiled = require('./tiled/ParseJSONTiled'); -var ParseWeltmeister = require('./impact/ParseWeltmeister'); - -/** - * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format - * is found, returns `null`. When loading from CSV or a 2D array, you should specify the tileWidth & - * tileHeight. When parsing from a map from Tiled, the tileWidth & tileHeight will be pulled from - * the map data. - * - * @function Phaser.Tilemaps.Parsers.Parse - * @since 3.0.0 - * - * @param {string} name - The name of the tilemap, used to set the name on the MapData. - * @param {integer} mapFormat - See ../Formats.js. - * @param {(integer[][]|string|object)} data - 2D array, CSV string or Tiled JSON object. - * @param {integer} tileWidth - The width of a tile in pixels. Required for 2D array and CSV, but - * ignored for Tiled JSON. - * @param {integer} tileHeight - The height of a tile in pixels. Required for 2D array and CSV, but - * ignored for Tiled JSON. - * @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've 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. - */ -var Parse = function (name, mapFormat, data, tileWidth, tileHeight, insertNull) -{ - var newMap; - - switch (mapFormat) - { - case (Formats.ARRAY_2D): - newMap = Parse2DArray(name, data, tileWidth, tileHeight, insertNull); - break; - case (Formats.CSV): - newMap = ParseCSV(name, data, tileWidth, tileHeight, insertNull); - break; - case (Formats.TILED_JSON): - newMap = ParseJSONTiled(name, data, insertNull); - break; - case (Formats.WELTMEISTER): - newMap = ParseWeltmeister(name, data, insertNull); - break; - default: - console.warn('Unrecognized tilemap data format: ' + mapFormat); - newMap = null; - } - - return newMap; -}; - -module.exports = Parse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = require('../Formats'); +var Parse2DArray = require('./Parse2DArray'); +var ParseCSV = require('./ParseCSV'); +var ParseJSONTiled = require('./tiled/ParseJSONTiled'); +var ParseWeltmeister = require('./impact/ParseWeltmeister'); + +/** + * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format + * is found, returns `null`. When loading from CSV or a 2D array, you should specify the tileWidth & + * tileHeight. When parsing from a map from Tiled, the tileWidth & tileHeight will be pulled from + * the map data. + * + * @function Phaser.Tilemaps.Parsers.Parse + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {integer} mapFormat - See ../Formats.js. + * @param {(integer[][]|string|object)} data - 2D array, CSV string or Tiled JSON object. + * @param {integer} tileWidth - The width of a tile in pixels. Required for 2D array and CSV, but + * ignored for Tiled JSON. + * @param {integer} tileHeight - The height of a tile in pixels. Required for 2D array and CSV, but + * ignored for Tiled JSON. + * @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've 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. + */ +var Parse = function (name, mapFormat, data, tileWidth, tileHeight, insertNull) +{ + var newMap; + + switch (mapFormat) + { + case (Formats.ARRAY_2D): + newMap = Parse2DArray(name, data, tileWidth, tileHeight, insertNull); + break; + case (Formats.CSV): + newMap = ParseCSV(name, data, tileWidth, tileHeight, insertNull); + break; + case (Formats.TILED_JSON): + newMap = ParseJSONTiled(name, data, insertNull); + break; + case (Formats.WELTMEISTER): + newMap = ParseWeltmeister(name, data, insertNull); + break; + default: + console.warn('Unrecognized tilemap data format: ' + mapFormat); + newMap = null; + } + + return newMap; +}; + +module.exports = Parse; diff --git a/src/tilemaps/parsers/Parse2DArray.js b/src/tilemaps/parsers/Parse2DArray.js index f077b6935..000075e9c 100644 --- a/src/tilemaps/parsers/Parse2DArray.js +++ b/src/tilemaps/parsers/Parse2DArray.js @@ -1,85 +1,85 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = require('../Formats'); -var LayerData = require('../mapdata/LayerData'); -var MapData = require('../mapdata/MapData'); -var Tile = require('../Tile'); - -/** - * Parses a 2D array of tile indexes into a new MapData object with a single layer. - * - * @function Phaser.Tilemaps.Parsers.Parse2DArray - * @since 3.0.0 - * - * @param {string} name - The name of the tilemap, used to set the name on the MapData. - * @param {integer[][]} data - 2D array, CSV string or Tiled JSON object. - * @param {integer} tileWidth - The width of a tile in pixels. - * @param {integer} tileHeight - The height of a tile in pixels. - * @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've 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} [description] - */ -var Parse2DArray = function (name, data, tileWidth, tileHeight, insertNull) -{ - var layerData = new LayerData({ - tileWidth: tileWidth, - tileHeight: tileHeight - }); - var mapData = new MapData({ - name: name, - tileWidth: tileWidth, - tileHeight: tileHeight, - format: Formats.ARRAY_2D, - layers: [ layerData ] - }); - - var tiles = []; - var height = data.length; - var width = 0; - - for (var y = 0; y < data.length; y++) - { - tiles[y] = []; - var row = data[y]; - - for (var x = 0; x < row.length; x++) - { - var tileIndex = parseInt(row[x], 10); - - if (isNaN(tileIndex) || tileIndex === -1) - { - tiles[y][x] = insertNull - ? null - : new Tile(layerData, -1, x, y, tileWidth, tileHeight); - } - else - { - tiles[y][x] = new Tile(layerData, tileIndex, x, y, tileWidth, tileHeight); - } - } - - if (width === 0) - { - width = row.length; - } - } - - mapData.width = layerData.width = width; - mapData.height = layerData.height = height; - mapData.widthInPixels = layerData.widthInPixels = width * tileWidth; - mapData.heightInPixels = layerData.heightInPixels = height * tileHeight; - layerData.data = tiles; - - return mapData; -}; - -module.exports = Parse2DArray; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = require('../Formats'); +var LayerData = require('../mapdata/LayerData'); +var MapData = require('../mapdata/MapData'); +var Tile = require('../Tile'); + +/** + * Parses a 2D array of tile indexes into a new MapData object with a single layer. + * + * @function Phaser.Tilemaps.Parsers.Parse2DArray + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {integer[][]} data - 2D array, CSV string or Tiled JSON object. + * @param {integer} tileWidth - The width of a tile in pixels. + * @param {integer} tileHeight - The height of a tile in pixels. + * @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've 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} [description] + */ +var Parse2DArray = function (name, data, tileWidth, tileHeight, insertNull) +{ + var layerData = new LayerData({ + tileWidth: tileWidth, + tileHeight: tileHeight + }); + var mapData = new MapData({ + name: name, + tileWidth: tileWidth, + tileHeight: tileHeight, + format: Formats.ARRAY_2D, + layers: [ layerData ] + }); + + var tiles = []; + var height = data.length; + var width = 0; + + for (var y = 0; y < data.length; y++) + { + tiles[y] = []; + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var tileIndex = parseInt(row[x], 10); + + if (isNaN(tileIndex) || tileIndex === -1) + { + tiles[y][x] = insertNull + ? null + : new Tile(layerData, -1, x, y, tileWidth, tileHeight); + } + else + { + tiles[y][x] = new Tile(layerData, tileIndex, x, y, tileWidth, tileHeight); + } + } + + if (width === 0) + { + width = row.length; + } + } + + mapData.width = layerData.width = width; + mapData.height = layerData.height = height; + mapData.widthInPixels = layerData.widthInPixels = width * tileWidth; + mapData.heightInPixels = layerData.heightInPixels = height * tileHeight; + layerData.data = tiles; + + return mapData; +}; + +module.exports = Parse2DArray; diff --git a/src/tilemaps/parsers/ParseCSV.js b/src/tilemaps/parsers/ParseCSV.js index 8fafd5c1b..d6d30bb7b 100644 --- a/src/tilemaps/parsers/ParseCSV.js +++ b/src/tilemaps/parsers/ParseCSV.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = require('../Formats'); -var Parse2DArray = require('./Parse2DArray'); - -/** - * Parses a CSV string of tile indexes into a new MapData object with a single layer. - * - * @function Phaser.Tilemaps.Parsers.ParseCSV - * @since 3.0.0 - * - * @param {string} name - The name of the tilemap, used to set the name on the MapData. - * @param {string} data - CSV string of tile indexes. - * @param {integer} tileWidth - The width of a tile in pixels. - * @param {integer} tileHeight - The height of a tile in pixels. - * @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've 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 resulting MapData object. - */ -var ParseCSV = function (name, data, tileWidth, tileHeight, insertNull) -{ - var array2D = data - .trim() - .split('\n') - .map(function (row) { return row.split(','); }); - - var map = Parse2DArray(name, array2D, tileWidth, tileHeight, insertNull); - map.format = Formats.CSV; - - return map; -}; - -module.exports = ParseCSV; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = require('../Formats'); +var Parse2DArray = require('./Parse2DArray'); + +/** + * Parses a CSV string of tile indexes into a new MapData object with a single layer. + * + * @function Phaser.Tilemaps.Parsers.ParseCSV + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {string} data - CSV string of tile indexes. + * @param {integer} tileWidth - The width of a tile in pixels. + * @param {integer} tileHeight - The height of a tile in pixels. + * @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've 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 resulting MapData object. + */ +var ParseCSV = function (name, data, tileWidth, tileHeight, insertNull) +{ + var array2D = data + .trim() + .split('\n') + .map(function (row) { return row.split(','); }); + + var map = Parse2DArray(name, array2D, tileWidth, tileHeight, insertNull); + map.format = Formats.CSV; + + return map; +}; + +module.exports = ParseCSV; diff --git a/src/tilemaps/parsers/impact/ParseTileLayers.js b/src/tilemaps/parsers/impact/ParseTileLayers.js index 1368846ed..fbbbdde6f 100644 --- a/src/tilemaps/parsers/impact/ParseTileLayers.js +++ b/src/tilemaps/parsers/impact/ParseTileLayers.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var LayerData = require('../../mapdata/LayerData'); -var Tile = require('../../Tile'); - -/** - * [description] - * - * @function Phaser.Tilemaps.Parsers.Impact.ParseTileLayers - * @since 3.0.0 - * - * @param {object} json - [description] - * @param {boolean} insertNull - [description] - * - * @return {array} [description] - */ -var ParseTileLayers = function (json, insertNull) -{ - var tileLayers = []; - - for (var i = 0; i < json.layer.length; i++) - { - var layer = json.layer[i]; - - var layerData = new LayerData({ - name: layer.name, - width: layer.width, - height: layer.height, - tileWidth: layer.tilesize, - tileHeight: layer.tilesize, - visible: layer.visible === 1 - }); - - var row = []; - var tileGrid = []; - - // 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. - for (var y = 0; y < layer.data.length; y++) - { - for (var x = 0; x < layer.data[y].length; x++) - { - // In Weltmeister, 0 = no tile, but the Tilemap API expects -1 = no tile. - var index = layer.data[y][x] - 1; - - var tile; - - if (index > -1) - { - tile = new Tile(layerData, index, x, y, layer.tilesize, layer.tilesize); - } - else - { - tile = insertNull - ? null - : new Tile(layerData, -1, x, y, layer.tilesize, layer.tilesize); - } - - row.push(tile); - } - - tileGrid.push(row); - row = []; - } - - layerData.data = tileGrid; - - tileLayers.push(layerData); - } - - return tileLayers; -}; - -module.exports = ParseTileLayers; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var LayerData = require('../../mapdata/LayerData'); +var Tile = require('../../Tile'); + +/** + * [description] + * + * @function Phaser.Tilemaps.Parsers.Impact.ParseTileLayers + * @since 3.0.0 + * + * @param {object} json - [description] + * @param {boolean} insertNull - [description] + * + * @return {array} [description] + */ +var ParseTileLayers = function (json, insertNull) +{ + var tileLayers = []; + + for (var i = 0; i < json.layer.length; i++) + { + var layer = json.layer[i]; + + var layerData = new LayerData({ + name: layer.name, + width: layer.width, + height: layer.height, + tileWidth: layer.tilesize, + tileHeight: layer.tilesize, + visible: layer.visible === 1 + }); + + var row = []; + var tileGrid = []; + + // 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. + for (var y = 0; y < layer.data.length; y++) + { + for (var x = 0; x < layer.data[y].length; x++) + { + // In Weltmeister, 0 = no tile, but the Tilemap API expects -1 = no tile. + var index = layer.data[y][x] - 1; + + var tile; + + if (index > -1) + { + tile = new Tile(layerData, index, x, y, layer.tilesize, layer.tilesize); + } + else + { + tile = insertNull + ? null + : new Tile(layerData, -1, x, y, layer.tilesize, layer.tilesize); + } + + row.push(tile); + } + + tileGrid.push(row); + row = []; + } + + layerData.data = tileGrid; + + tileLayers.push(layerData); + } + + return tileLayers; +}; + +module.exports = ParseTileLayers; diff --git a/src/tilemaps/parsers/impact/ParseTilesets.js b/src/tilemaps/parsers/impact/ParseTilesets.js index c2d076afc..5511a73b5 100644 --- a/src/tilemaps/parsers/impact/ParseTilesets.js +++ b/src/tilemaps/parsers/impact/ParseTilesets.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Tileset = require('../../Tileset'); - -/** - * [description] - * - * @function Phaser.Tilemaps.Parsers.Impact.ParseTilesets - * @since 3.0.0 - * - * @param {object} json - [description] - * - * @return {array} [description] - */ -var ParseTilesets = function (json) -{ - var tilesets = []; - var tilesetsNames = []; - - for (var i = 0; i < json.layer.length; i++) - { - var layer = json.layer[i]; - - // A relative filepath to the source image (within Weltmeister) is used for the name - var tilesetName = layer.tilesetName; - - // Only add unique tilesets that have a valid name. Collision layers will have a blank name. - if (tilesetName !== '' && tilesetsNames.indexOf(tilesetName) === -1) - { - tilesetsNames.push(tilesetName); - - // 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. - tilesets.push(new Tileset(tilesetName, 0, layer.tilesize, layer.tilesize, 0, 0)); - } - } - - return tilesets; -}; - -module.exports = ParseTilesets; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tileset = require('../../Tileset'); + +/** + * [description] + * + * @function Phaser.Tilemaps.Parsers.Impact.ParseTilesets + * @since 3.0.0 + * + * @param {object} json - [description] + * + * @return {array} [description] + */ +var ParseTilesets = function (json) +{ + var tilesets = []; + var tilesetsNames = []; + + for (var i = 0; i < json.layer.length; i++) + { + var layer = json.layer[i]; + + // A relative filepath to the source image (within Weltmeister) is used for the name + var tilesetName = layer.tilesetName; + + // Only add unique tilesets that have a valid name. Collision layers will have a blank name. + if (tilesetName !== '' && tilesetsNames.indexOf(tilesetName) === -1) + { + tilesetsNames.push(tilesetName); + + // 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. + tilesets.push(new Tileset(tilesetName, 0, layer.tilesize, layer.tilesize, 0, 0)); + } + } + + return tilesets; +}; + +module.exports = ParseTilesets; diff --git a/src/tilemaps/parsers/impact/ParseWeltmeister.js b/src/tilemaps/parsers/impact/ParseWeltmeister.js index ccc0a4239..bc4715f43 100644 --- a/src/tilemaps/parsers/impact/ParseWeltmeister.js +++ b/src/tilemaps/parsers/impact/ParseWeltmeister.js @@ -1,61 +1,61 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Formats = require('../../Formats'); -var MapData = require('../../mapdata/MapData'); -var ParseTileLayers = require('./ParseTileLayers'); -var ParseTilesets = require('./ParseTilesets'); - -/** - * Parses a Weltmeister JSON object into a new MapData object. - * - * @function Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister - * @since 3.0.0 - * - * @param {string} name - The name of the tilemap, used to set the name on the MapData. - * @param {object} json - The Weltmeister JSON object. - * @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've 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 {?object} [description] - */ -var ParseWeltmeister = function (name, json, insertNull) -{ - if (json.layer.length === 0) - { - console.warn('No layers found in the Weltmeister map: ' + name); - return null; - } - - var width = 0; - var height = 0; - - for (var i = 0; i < json.layer.length; i++) - { - if (json.layer[i].width > width) { width = json.layer[i].width; } - if (json.layer[i].height > height) { height = json.layer[i].height; } - } - - var mapData = new MapData({ - width: width, - height: height, - name: name, - tileWidth: json.layer[0].tilesize, - tileHeight: json.layer[0].tilesize, - format: Formats.WELTMEISTER - }); - - mapData.layers = ParseTileLayers(json, insertNull); - mapData.tilesets = ParseTilesets(json); - - return mapData; -}; - -module.exports = ParseWeltmeister; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Formats = require('../../Formats'); +var MapData = require('../../mapdata/MapData'); +var ParseTileLayers = require('./ParseTileLayers'); +var ParseTilesets = require('./ParseTilesets'); + +/** + * Parses a Weltmeister JSON object into a new MapData object. + * + * @function Phaser.Tilemaps.Parsers.Impact.ParseWeltmeister + * @since 3.0.0 + * + * @param {string} name - The name of the tilemap, used to set the name on the MapData. + * @param {object} json - The Weltmeister JSON object. + * @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've 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 {?object} [description] + */ +var ParseWeltmeister = function (name, json, insertNull) +{ + if (json.layer.length === 0) + { + console.warn('No layers found in the Weltmeister map: ' + name); + return null; + } + + var width = 0; + var height = 0; + + for (var i = 0; i < json.layer.length; i++) + { + if (json.layer[i].width > width) { width = json.layer[i].width; } + if (json.layer[i].height > height) { height = json.layer[i].height; } + } + + var mapData = new MapData({ + width: width, + height: height, + name: name, + tileWidth: json.layer[0].tilesize, + tileHeight: json.layer[0].tilesize, + format: Formats.WELTMEISTER + }); + + mapData.layers = ParseTileLayers(json, insertNull); + mapData.tilesets = ParseTilesets(json); + + return mapData; +}; + +module.exports = ParseWeltmeister; diff --git a/src/tilemaps/parsers/impact/index.js b/src/tilemaps/parsers/impact/index.js index 685ac101b..f083c9efe 100644 --- a/src/tilemaps/parsers/impact/index.js +++ b/src/tilemaps/parsers/impact/index.js @@ -1,17 +1,17 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Parsers.Impact - */ - -module.exports = { - - ParseTileLayers: require('./ParseTileLayers'), - ParseTilesets: require('./ParseTilesets'), - ParseWeltmeister: require('./ParseWeltmeister') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Parsers.Impact + */ + +module.exports = { + + ParseTileLayers: require('./ParseTileLayers'), + ParseTilesets: require('./ParseTilesets'), + ParseWeltmeister: require('./ParseWeltmeister') + +}; diff --git a/src/tilemaps/parsers/index.js b/src/tilemaps/parsers/index.js index 08fd4064b..067261bca 100644 --- a/src/tilemaps/parsers/index.js +++ b/src/tilemaps/parsers/index.js @@ -1,20 +1,20 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Parsers - */ - -module.exports = { - - Parse: require('./Parse'), - Parse2DArray: require('./Parse2DArray'), - ParseCSV: require('./ParseCSV'), - - Impact: require('./impact/'), - Tiled: require('./tiled/') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Parsers + */ + +module.exports = { + + Parse: require('./Parse'), + Parse2DArray: require('./Parse2DArray'), + ParseCSV: require('./ParseCSV'), + + Impact: require('./impact/'), + Tiled: require('./tiled/') + +}; diff --git a/src/tilemaps/parsers/tiled/AssignTileProperties.js b/src/tilemaps/parsers/tiled/AssignTileProperties.js index 9b1de71dc..02efa37c4 100644 --- a/src/tilemaps/parsers/tiled/AssignTileProperties.js +++ b/src/tilemaps/parsers/tiled/AssignTileProperties.js @@ -1,67 +1,67 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Extend = require('../../../utils/object/Extend'); - -/** - * Copy properties from tileset to tiles. - * - * @function Phaser.Tilemaps.Parsers.Tiled.AssignTileProperties - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.MapData} mapData - [description] - */ -var AssignTileProperties = function (mapData) -{ - var layerData; - var tile; - var sid; - var set; - var row; - - // go through each of the map data layers - for (var i = 0; i < mapData.layers.length; i++) - { - layerData = mapData.layers[i]; - - set = null; - - // rows of tiles - for (var j = 0; j < layerData.data.length; j++) - { - row = layerData.data[j]; - - // individual tiles - for (var k = 0; k < row.length; k++) - { - tile = row[k]; - - if (tile === null || tile.index < 0) - { - continue; - } - - // find the relevant tileset - sid = mapData.tiles[tile.index][2]; - set = mapData.tilesets[sid]; - - // Ensure that a tile's size matches its tileset - tile.width = set.tileWidth; - tile.height = set.tileHeight; - - // if that tile type has any properties, add them to the tile object - if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) - { - tile.properties = Extend( - tile.properties, set.tileProperties[tile.index - set.firstgid] - ); - } - } - } - } -}; - -module.exports = AssignTileProperties; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Extend = require('../../../utils/object/Extend'); + +/** + * Copy properties from tileset to tiles. + * + * @function Phaser.Tilemaps.Parsers.Tiled.AssignTileProperties + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.MapData} mapData - [description] + */ +var AssignTileProperties = function (mapData) +{ + var layerData; + var tile; + var sid; + var set; + var row; + + // go through each of the map data layers + for (var i = 0; i < mapData.layers.length; i++) + { + layerData = mapData.layers[i]; + + set = null; + + // rows of tiles + for (var j = 0; j < layerData.data.length; j++) + { + row = layerData.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + sid = mapData.tiles[tile.index][2]; + set = mapData.tilesets[sid]; + + // Ensure that a tile's size matches its tileset + tile.width = set.tileWidth; + tile.height = set.tileHeight; + + // if that tile type has any properties, add them to the tile object + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Extend( + tile.properties, set.tileProperties[tile.index - set.firstgid] + ); + } + } + } + } +}; + +module.exports = AssignTileProperties; diff --git a/src/tilemaps/parsers/tiled/Base64Decode.js b/src/tilemaps/parsers/tiled/Base64Decode.js index dc04be944..271e21972 100644 --- a/src/tilemaps/parsers/tiled/Base64Decode.js +++ b/src/tilemaps/parsers/tiled/Base64Decode.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Decode base-64 encoded data, for example as exported by Tiled. - * - * @function Phaser.Tilemaps.Parsers.Tiled.Base64Decode - * @since 3.0.0 - * - * @param {object} data - Base-64 encoded data to decode. - * - * @return {array} Array containing the decoded bytes. - */ -var Base64Decode = function (data) -{ - var binaryString = window.atob(data); - var len = binaryString.length; - var bytes = new Array(len / 4); - - // Interpret binaryString as an array of bytes representing little-endian encoded uint32 values. - for (var i = 0; i < len; i += 4) - { - bytes[i / 4] = ( - binaryString.charCodeAt(i) | - binaryString.charCodeAt(i + 1) << 8 | - binaryString.charCodeAt(i + 2) << 16 | - binaryString.charCodeAt(i + 3) << 24 - ) >>> 0; - } - - return bytes; -}; - -module.exports = Base64Decode; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Decode base-64 encoded data, for example as exported by Tiled. + * + * @function Phaser.Tilemaps.Parsers.Tiled.Base64Decode + * @since 3.0.0 + * + * @param {object} data - Base-64 encoded data to decode. + * + * @return {array} Array containing the decoded bytes. + */ +var Base64Decode = function (data) +{ + var binaryString = window.atob(data); + var len = binaryString.length; + var bytes = new Array(len / 4); + + // Interpret binaryString as an array of bytes representing little-endian encoded uint32 values. + for (var i = 0; i < len; i += 4) + { + bytes[i / 4] = ( + binaryString.charCodeAt(i) | + binaryString.charCodeAt(i + 1) << 8 | + binaryString.charCodeAt(i + 2) << 16 | + binaryString.charCodeAt(i + 3) << 24 + ) >>> 0; + } + + return bytes; +}; + +module.exports = Base64Decode; diff --git a/src/tilemaps/parsers/tiled/BuildTilesetIndex.js b/src/tilemaps/parsers/tiled/BuildTilesetIndex.js index 8738af92d..f7919b324 100644 --- a/src/tilemaps/parsers/tiled/BuildTilesetIndex.js +++ b/src/tilemaps/parsers/tiled/BuildTilesetIndex.js @@ -1,67 +1,67 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Master list of tiles -> x, y, index in tileset. - * - * @function Phaser.Tilemaps.Parsers.Tiled.BuildTilesetIndex - * @since 3.0.0 - * - * @param {Phaser.Tilemaps.MapData} mapData - [description] - * - * @return {array} [description] - */ -var BuildTilesetIndex = function (mapData) -{ - var tiles = []; - - for (var i = 0; i < mapData.tilesets.length; i++) - { - var set = mapData.tilesets[i]; - - var x = set.tileMargin; - var y = set.tileMargin; - - var count = 0; - var countX = 0; - var countY = 0; - - for (var t = set.firstgid; t < set.firstgid + set.total; t++) - { - // Can add extra properties here as needed - tiles[t] = [ x, y, i ]; - - x += set.tileWidth + set.tileSpacing; - - count++; - - if (count === set.total) - { - break; - } - - countX++; - - if (countX === set.columns) - { - x = set.tileMargin; - y += set.tileHeight + set.tileSpacing; - - countX = 0; - countY++; - - if (countY === set.rows) - { - break; - } - } - } - } - - return tiles; -}; - -module.exports = BuildTilesetIndex; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Master list of tiles -> x, y, index in tileset. + * + * @function Phaser.Tilemaps.Parsers.Tiled.BuildTilesetIndex + * @since 3.0.0 + * + * @param {Phaser.Tilemaps.MapData} mapData - [description] + * + * @return {array} [description] + */ +var BuildTilesetIndex = function (mapData) +{ + var tiles = []; + + for (var i = 0; i < mapData.tilesets.length; i++) + { + var set = mapData.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + tiles[t] = [ x, y, i ]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + } + + return tiles; +}; + +module.exports = BuildTilesetIndex; diff --git a/src/tilemaps/parsers/tiled/CreateGroupLayer.js b/src/tilemaps/parsers/tiled/CreateGroupLayer.js index 2c7b11b2a..d2ba96e2c 100644 --- a/src/tilemaps/parsers/tiled/CreateGroupLayer.js +++ b/src/tilemaps/parsers/tiled/CreateGroupLayer.js @@ -1,55 +1,55 @@ -/** - * @author Seth Berrier - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../../../utils/object/GetFastValue'); - -/** - * Parse a Tiled group layer and create a state object for inheriting. - * - * @function Phaser.Tilemaps.Parsers.Tiled.CreateGroupLayer - * @since 3.21.0 - * - * @param {object} json - The Tiled JSON object. - * @param {object} [currentl] - The current group layer from the Tiled JSON file. - * @param {object} [parentstate] - The state of the parent group (if any). - * - * @return {object} A group state object with proper values for updating children layers. - */ -var CreateGroupLayer = function (json, groupl, parentstate) -{ - if (!groupl) - { - // Return a default group state object - return { - i: 0, // Current layer array iterator - layers: json.layers, // Current array of layers - - // Values inherited from parent group - name: '', - opacity: 1, - visible: true, - x: 0, - y: 0 - }; - } - - // Compute group layer x, y - var layerX = groupl.x + GetFastValue(groupl, 'startx', 0) * json.tilewidth + GetFastValue(groupl, 'offsetx', 0); - var layerY = groupl.y + GetFastValue(groupl, 'starty', 0) * json.tileheight + GetFastValue(groupl, 'offsety', 0); - - // Compute next state inherited from group - return { - i: 0, - layers: groupl.layers, - name: parentstate.name + groupl.name + '/', - opacity: parentstate.opacity * groupl.opacity, - visible: parentstate.visible && groupl.visible, - x: parentstate.x + layerX, - y: parentstate.y + layerY - }; -}; - -module.exports = CreateGroupLayer; +/** + * @author Seth Berrier + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../../../utils/object/GetFastValue'); + +/** + * Parse a Tiled group layer and create a state object for inheriting. + * + * @function Phaser.Tilemaps.Parsers.Tiled.CreateGroupLayer + * @since 3.21.0 + * + * @param {object} json - The Tiled JSON object. + * @param {object} [currentl] - The current group layer from the Tiled JSON file. + * @param {object} [parentstate] - The state of the parent group (if any). + * + * @return {object} A group state object with proper values for updating children layers. + */ +var CreateGroupLayer = function (json, groupl, parentstate) +{ + if (!groupl) + { + // Return a default group state object + return { + i: 0, // Current layer array iterator + layers: json.layers, // Current array of layers + + // Values inherited from parent group + name: '', + opacity: 1, + visible: true, + x: 0, + y: 0 + }; + } + + // Compute group layer x, y + var layerX = groupl.x + GetFastValue(groupl, 'startx', 0) * json.tilewidth + GetFastValue(groupl, 'offsetx', 0); + var layerY = groupl.y + GetFastValue(groupl, 'starty', 0) * json.tileheight + GetFastValue(groupl, 'offsety', 0); + + // Compute next state inherited from group + return { + i: 0, + layers: groupl.layers, + name: parentstate.name + groupl.name + '/', + opacity: parentstate.opacity * groupl.opacity, + visible: parentstate.visible && groupl.visible, + x: parentstate.x + layerX, + y: parentstate.y + layerY + }; +}; + +module.exports = CreateGroupLayer; diff --git a/src/tilemaps/parsers/tiled/ParseGID.js b/src/tilemaps/parsers/tiled/ParseGID.js index f32e295c6..e6d004c80 100644 --- a/src/tilemaps/parsers/tiled/ParseGID.js +++ b/src/tilemaps/parsers/tiled/ParseGID.js @@ -1,84 +1,84 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var FLIPPED_HORIZONTAL = 0x80000000; -var FLIPPED_VERTICAL = 0x40000000; -var FLIPPED_ANTI_DIAGONAL = 0x20000000; // Top-right is swapped with bottom-left corners - -/** - * See Tiled documentation on tile flipping: - * http://docs.mapeditor.org/en/latest/reference/tmx-map-format/ - * - * @function Phaser.Tilemaps.Parsers.Tiled.ParseGID - * @since 3.0.0 - * - * @param {number} gid - [description] - * - * @return {object} [description] - */ -var ParseGID = function (gid) -{ - var flippedHorizontal = Boolean(gid & FLIPPED_HORIZONTAL); - var flippedVertical = Boolean(gid & FLIPPED_VERTICAL); - var flippedAntiDiagonal = Boolean(gid & FLIPPED_ANTI_DIAGONAL); - gid = gid & ~(FLIPPED_HORIZONTAL | FLIPPED_VERTICAL | FLIPPED_ANTI_DIAGONAL); - - // Parse the flip flags into something Phaser can use - var rotation = 0; - var flipped = false; - - if (flippedHorizontal && flippedVertical && flippedAntiDiagonal) - { - rotation = Math.PI / 2; - flipped = true; - } - else if (flippedHorizontal && flippedVertical && !flippedAntiDiagonal) - { - rotation = Math.PI; - flipped = false; - } - else if (flippedHorizontal && !flippedVertical && flippedAntiDiagonal) - { - rotation = Math.PI / 2; - flipped = false; - } - else if (flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) - { - rotation = 0; - flipped = true; - } - else if (!flippedHorizontal && flippedVertical && flippedAntiDiagonal) - { - rotation = 3 * Math.PI / 2; - flipped = false; - } - else if (!flippedHorizontal && flippedVertical && !flippedAntiDiagonal) - { - rotation = Math.PI; - flipped = true; - } - else if (!flippedHorizontal && !flippedVertical && flippedAntiDiagonal) - { - rotation = 3 * Math.PI / 2; - flipped = true; - } - else if (!flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) - { - rotation = 0; - flipped = false; - } - - return { - gid: gid, - flippedHorizontal: flippedHorizontal, - flippedVertical: flippedVertical, - flippedAntiDiagonal: flippedAntiDiagonal, - rotation: rotation, - flipped: flipped - }; -}; - -module.exports = ParseGID; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var FLIPPED_HORIZONTAL = 0x80000000; +var FLIPPED_VERTICAL = 0x40000000; +var FLIPPED_ANTI_DIAGONAL = 0x20000000; // Top-right is swapped with bottom-left corners + +/** + * See Tiled documentation on tile flipping: + * http://docs.mapeditor.org/en/latest/reference/tmx-map-format/ + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseGID + * @since 3.0.0 + * + * @param {number} gid - [description] + * + * @return {object} [description] + */ +var ParseGID = function (gid) +{ + var flippedHorizontal = Boolean(gid & FLIPPED_HORIZONTAL); + var flippedVertical = Boolean(gid & FLIPPED_VERTICAL); + var flippedAntiDiagonal = Boolean(gid & FLIPPED_ANTI_DIAGONAL); + gid = gid & ~(FLIPPED_HORIZONTAL | FLIPPED_VERTICAL | FLIPPED_ANTI_DIAGONAL); + + // Parse the flip flags into something Phaser can use + var rotation = 0; + var flipped = false; + + if (flippedHorizontal && flippedVertical && flippedAntiDiagonal) + { + rotation = Math.PI / 2; + flipped = true; + } + else if (flippedHorizontal && flippedVertical && !flippedAntiDiagonal) + { + rotation = Math.PI; + flipped = false; + } + else if (flippedHorizontal && !flippedVertical && flippedAntiDiagonal) + { + rotation = Math.PI / 2; + flipped = false; + } + else if (flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) + { + rotation = 0; + flipped = true; + } + else if (!flippedHorizontal && flippedVertical && flippedAntiDiagonal) + { + rotation = 3 * Math.PI / 2; + flipped = false; + } + else if (!flippedHorizontal && flippedVertical && !flippedAntiDiagonal) + { + rotation = Math.PI; + flipped = true; + } + else if (!flippedHorizontal && !flippedVertical && flippedAntiDiagonal) + { + rotation = 3 * Math.PI / 2; + flipped = true; + } + else if (!flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) + { + rotation = 0; + flipped = false; + } + + return { + gid: gid, + flippedHorizontal: flippedHorizontal, + flippedVertical: flippedVertical, + flippedAntiDiagonal: flippedAntiDiagonal, + rotation: rotation, + flipped: flipped + }; +}; + +module.exports = ParseGID; diff --git a/src/tilemaps/parsers/tiled/ParseImageLayers.js b/src/tilemaps/parsers/tiled/ParseImageLayers.js index e8743f3a6..f77662e09 100644 --- a/src/tilemaps/parsers/tiled/ParseImageLayers.js +++ b/src/tilemaps/parsers/tiled/ParseImageLayers.js @@ -1,82 +1,82 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../../../utils/object/GetFastValue'); -var CreateGroupLayer = require('./CreateGroupLayer'); - -/** - * Parses a Tiled JSON object into an array of objects with details about the image layers. - * - * @function Phaser.Tilemaps.Parsers.Tiled.ParseImageLayers - * @since 3.0.0 - * - * @param {object} json - The Tiled JSON object. - * - * @return {array} Array of objects that include critical info about the map's image layers - */ -var ParseImageLayers = function (json) -{ - var images = []; - - // State inherited from a parent group - var groupStack = []; - var curGroupState = CreateGroupLayer(json); - - while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) - { - if (curGroupState.i >= curGroupState.layers.length) - { - // Ensure recursion stack is not empty first - if (groupStack.length < 1) - { - console.warn( - 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' - ); - break; - } - - // Return to previous recursive state - curGroupState = groupStack.pop(); - continue; - } - - // Get current layer and advance iterator - var curi = curGroupState.layers[curGroupState.i]; - curGroupState.i++; - - if (curi.type !== 'imagelayer') - { - if (curi.type === 'group') - { - // Compute next state inherited from group - var nextGroupState = CreateGroupLayer(json, curi, curGroupState); - - // Preserve current state before recursing - groupStack.push(curGroupState); - curGroupState = nextGroupState; - } - - // Skip this layer OR 'recurse' (iterative style) into the group - continue; - } - - var layerOffsetX = GetFastValue(curi, 'offsetx', 0) + GetFastValue(curi, 'startx', 0); - var layerOffsetY = GetFastValue(curi, 'offsety', 0) + GetFastValue(curi, 'starty', 0); - images.push({ - name: (curGroupState.name + curi.name), - image: curi.image, - x: (curGroupState.x + layerOffsetX + curi.x), - y: (curGroupState.y + layerOffsetY + curi.y), - alpha: (curGroupState.opacity * curi.opacity), - visible: (curGroupState.visible && curi.visible), - properties: GetFastValue(curi, 'properties', {}) - }); - } - - return images; -}; - -module.exports = ParseImageLayers; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../../../utils/object/GetFastValue'); +var CreateGroupLayer = require('./CreateGroupLayer'); + +/** + * Parses a Tiled JSON object into an array of objects with details about the image layers. + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseImageLayers + * @since 3.0.0 + * + * @param {object} json - The Tiled JSON object. + * + * @return {array} Array of objects that include critical info about the map's image layers + */ +var ParseImageLayers = function (json) +{ + var images = []; + + // State inherited from a parent group + var groupStack = []; + var curGroupState = CreateGroupLayer(json); + + while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) + { + if (curGroupState.i >= curGroupState.layers.length) + { + // Ensure recursion stack is not empty first + if (groupStack.length < 1) + { + console.warn( + 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' + ); + break; + } + + // Return to previous recursive state + curGroupState = groupStack.pop(); + continue; + } + + // Get current layer and advance iterator + var curi = curGroupState.layers[curGroupState.i]; + curGroupState.i++; + + if (curi.type !== 'imagelayer') + { + if (curi.type === 'group') + { + // Compute next state inherited from group + var nextGroupState = CreateGroupLayer(json, curi, curGroupState); + + // Preserve current state before recursing + groupStack.push(curGroupState); + curGroupState = nextGroupState; + } + + // Skip this layer OR 'recurse' (iterative style) into the group + continue; + } + + var layerOffsetX = GetFastValue(curi, 'offsetx', 0) + GetFastValue(curi, 'startx', 0); + var layerOffsetY = GetFastValue(curi, 'offsety', 0) + GetFastValue(curi, 'starty', 0); + images.push({ + name: (curGroupState.name + curi.name), + image: curi.image, + x: (curGroupState.x + layerOffsetX + curi.x), + y: (curGroupState.y + layerOffsetY + curi.y), + alpha: (curGroupState.opacity * curi.opacity), + visible: (curGroupState.visible && curi.visible), + properties: GetFastValue(curi, 'properties', {}) + }); + } + + return images; +}; + +module.exports = ParseImageLayers; diff --git a/src/tilemaps/parsers/tiled/ParseJSONTiled.js b/src/tilemaps/parsers/tiled/ParseJSONTiled.js index fad11a478..6dba55c0e 100644 --- a/src/tilemaps/parsers/tiled/ParseJSONTiled.js +++ b/src/tilemaps/parsers/tiled/ParseJSONTiled.js @@ -1,90 +1,90 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../../const.js'); -var Formats = require('../../Formats'); -var MapData = require('../../mapdata/MapData'); -var ParseTileLayers = require('./ParseTileLayers'); -var ParseImageLayers = require('./ParseImageLayers'); -var ParseTilesets = require('./ParseTilesets'); -var ParseObjectLayers = require('./ParseObjectLayers'); -var BuildTilesetIndex = require('./BuildTilesetIndex'); -var AssignTileProperties = require('./AssignTileProperties'); - -/** - * Parses a Tiled JSON object into a new MapData object. - * - * @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} json - The Tiled JSON object. - * @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've 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. - */ -var ParseJSONTiled = function (name, json, insertNull) -{ - if (json.orientation === 'isometric' || json.orientation === 'staggered') - { - console.warn('Isometric map types are WIP in this version of Phaser'); - } - else if (json.orientation === 'hexagonal') - { - console.warn('Hexagonal map types are WIP in this version of Phaser'); - } - else if (json.orientation !== 'orthogonal') - { - console.warn('Only orthogonal, hexagonal and isometric map types are supported in this version of Phaser'); - return null; - } - - - // Map data will consist of: layers, objects, images, tilesets, sizes - var mapData = new MapData({ - width: json.width, - height: json.height, - name: name, - tileWidth: json.tilewidth, - tileHeight: json.tileheight, - orientation: CONST.fromOrientationString(json.orientation), - format: Formats.TILED_JSON, - version: json.version, - properties: json.properties, - renderOrder: json.renderorder, - infinite: json.infinite - }); - - - - - if (mapData.orientation === CONST.HEXAGONAL) - { - mapData.hexSideLength = json.hexsidelength; - } - - mapData.layers = ParseTileLayers(json, insertNull); - mapData.images = ParseImageLayers(json); - - var sets = ParseTilesets(json); - mapData.tilesets = sets.tilesets; - mapData.imageCollections = sets.imageCollections; - - mapData.objects = ParseObjectLayers(json); - - mapData.tiles = BuildTilesetIndex(mapData); - - AssignTileProperties(mapData); - - return mapData; -}; - -module.exports = ParseJSONTiled; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../../const.js'); +var Formats = require('../../Formats'); +var MapData = require('../../mapdata/MapData'); +var ParseTileLayers = require('./ParseTileLayers'); +var ParseImageLayers = require('./ParseImageLayers'); +var ParseTilesets = require('./ParseTilesets'); +var ParseObjectLayers = require('./ParseObjectLayers'); +var BuildTilesetIndex = require('./BuildTilesetIndex'); +var AssignTileProperties = require('./AssignTileProperties'); + +/** + * Parses a Tiled JSON object into a new MapData object. + * + * @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} json - The Tiled JSON object. + * @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've 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. + */ +var ParseJSONTiled = function (name, json, insertNull) +{ + if (json.orientation === 'isometric' || json.orientation === 'staggered') + { + console.warn('Isometric map types are WIP in this version of Phaser'); + } + else if (json.orientation === 'hexagonal') + { + console.warn('Hexagonal map types are WIP in this version of Phaser'); + } + else if (json.orientation !== 'orthogonal') + { + console.warn('Only orthogonal, hexagonal and isometric map types are supported in this version of Phaser'); + return null; + } + + + // Map data will consist of: layers, objects, images, tilesets, sizes + var mapData = new MapData({ + width: json.width, + height: json.height, + name: name, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: CONST.fromOrientationString(json.orientation), + format: Formats.TILED_JSON, + version: json.version, + properties: json.properties, + renderOrder: json.renderorder, + infinite: json.infinite + }); + + + + + if (mapData.orientation === CONST.HEXAGONAL) + { + mapData.hexSideLength = json.hexsidelength; + } + + mapData.layers = ParseTileLayers(json, insertNull); + mapData.images = ParseImageLayers(json); + + var sets = ParseTilesets(json); + mapData.tilesets = sets.tilesets; + mapData.imageCollections = sets.imageCollections; + + mapData.objects = ParseObjectLayers(json); + + mapData.tiles = BuildTilesetIndex(mapData); + + AssignTileProperties(mapData); + + return mapData; +}; + +module.exports = ParseJSONTiled; diff --git a/src/tilemaps/parsers/tiled/ParseObject.js b/src/tilemaps/parsers/tiled/ParseObject.js index f067a99f3..2240fb76b 100644 --- a/src/tilemaps/parsers/tiled/ParseObject.js +++ b/src/tilemaps/parsers/tiled/ParseObject.js @@ -1,76 +1,76 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Pick = require('../../../utils/object/Pick'); -var ParseGID = require('./ParseGID'); - -var copyPoints = function (p) { return { x: p.x, y: p.y }; }; - -var commonObjectProps = [ 'id', 'name', 'type', 'rotation', 'properties', 'visible', 'x', 'y', 'width', 'height' ]; - -/** - * Convert a Tiled object to an internal parsed object normalising and copying properties over, while applying optional x and y offsets. The parsed object will always have the properties `id`, `name`, `type`, `rotation`, `properties`, `visible`, `x`, `y`, `width` and `height`. Other properties will be added according to the object type (such as text, polyline, gid etc.) - * - * @function Phaser.Tilemaps.Parsers.Tiled.ParseObject - * @since 3.0.0 - * - * @param {object} tiledObject - Tiled object to convert to an internal parsed object normalising and copying properties over. - * @param {number} [offsetX=0] - Optional additional offset to apply to the object's x property. Defaults to 0. - * @param {number} [offsetY=0] - Optional additional offset to apply to the object's y property. Defaults to 0. - * - * @return {object} The parsed object containing properties read from the Tiled object according to it's type with x and y values updated according to the given offsets. - */ -var ParseObject = function (tiledObject, offsetX, offsetY) -{ - if (offsetX === undefined) { offsetX = 0; } - if (offsetY === undefined) { offsetY = 0; } - - var parsedObject = Pick(tiledObject, commonObjectProps); - - parsedObject.x += offsetX; - parsedObject.y += offsetY; - - if (tiledObject.gid) - { - // Object tiles - var gidInfo = ParseGID(tiledObject.gid); - parsedObject.gid = gidInfo.gid; - parsedObject.flippedHorizontal = gidInfo.flippedHorizontal; - parsedObject.flippedVertical = gidInfo.flippedVertical; - parsedObject.flippedAntiDiagonal = gidInfo.flippedAntiDiagonal; - } - else if (tiledObject.polyline) - { - parsedObject.polyline = tiledObject.polyline.map(copyPoints); - } - else if (tiledObject.polygon) - { - parsedObject.polygon = tiledObject.polygon.map(copyPoints); - } - else if (tiledObject.ellipse) - { - parsedObject.ellipse = tiledObject.ellipse; - parsedObject.width = tiledObject.width; - parsedObject.height = tiledObject.height; - } - else if (tiledObject.text) - { - parsedObject.width = tiledObject.width; - parsedObject.height = tiledObject.height; - parsedObject.text = tiledObject.text; - } - else - { - // Otherwise, assume it is a rectangle - parsedObject.rectangle = true; - parsedObject.width = tiledObject.width; - parsedObject.height = tiledObject.height; - } - - return parsedObject; -}; - -module.exports = ParseObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Pick = require('../../../utils/object/Pick'); +var ParseGID = require('./ParseGID'); + +var copyPoints = function (p) { return { x: p.x, y: p.y }; }; + +var commonObjectProps = [ 'id', 'name', 'type', 'rotation', 'properties', 'visible', 'x', 'y', 'width', 'height' ]; + +/** + * Convert a Tiled object to an internal parsed object normalising and copying properties over, while applying optional x and y offsets. The parsed object will always have the properties `id`, `name`, `type`, `rotation`, `properties`, `visible`, `x`, `y`, `width` and `height`. Other properties will be added according to the object type (such as text, polyline, gid etc.) + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseObject + * @since 3.0.0 + * + * @param {object} tiledObject - Tiled object to convert to an internal parsed object normalising and copying properties over. + * @param {number} [offsetX=0] - Optional additional offset to apply to the object's x property. Defaults to 0. + * @param {number} [offsetY=0] - Optional additional offset to apply to the object's y property. Defaults to 0. + * + * @return {object} The parsed object containing properties read from the Tiled object according to it's type with x and y values updated according to the given offsets. + */ +var ParseObject = function (tiledObject, offsetX, offsetY) +{ + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + var parsedObject = Pick(tiledObject, commonObjectProps); + + parsedObject.x += offsetX; + parsedObject.y += offsetY; + + if (tiledObject.gid) + { + // Object tiles + var gidInfo = ParseGID(tiledObject.gid); + parsedObject.gid = gidInfo.gid; + parsedObject.flippedHorizontal = gidInfo.flippedHorizontal; + parsedObject.flippedVertical = gidInfo.flippedVertical; + parsedObject.flippedAntiDiagonal = gidInfo.flippedAntiDiagonal; + } + else if (tiledObject.polyline) + { + parsedObject.polyline = tiledObject.polyline.map(copyPoints); + } + else if (tiledObject.polygon) + { + parsedObject.polygon = tiledObject.polygon.map(copyPoints); + } + else if (tiledObject.ellipse) + { + parsedObject.ellipse = tiledObject.ellipse; + parsedObject.width = tiledObject.width; + parsedObject.height = tiledObject.height; + } + else if (tiledObject.text) + { + parsedObject.width = tiledObject.width; + parsedObject.height = tiledObject.height; + parsedObject.text = tiledObject.text; + } + else + { + // Otherwise, assume it is a rectangle + parsedObject.rectangle = true; + parsedObject.width = tiledObject.width; + parsedObject.height = tiledObject.height; + } + + return parsedObject; +}; + +module.exports = ParseObject; diff --git a/src/tilemaps/parsers/tiled/ParseObjectLayers.js b/src/tilemaps/parsers/tiled/ParseObjectLayers.js index 2492b47e0..ca095c0f7 100644 --- a/src/tilemaps/parsers/tiled/ParseObjectLayers.js +++ b/src/tilemaps/parsers/tiled/ParseObjectLayers.js @@ -1,93 +1,93 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetFastValue = require('../../../utils/object/GetFastValue'); -var ParseObject = require('./ParseObject'); -var ObjectLayer = require('../../mapdata/ObjectLayer'); -var CreateGroupLayer = require('./CreateGroupLayer'); - -/** - * Parses a Tiled JSON object into an array of ObjectLayer objects. - * - * @function Phaser.Tilemaps.Parsers.Tiled.ParseObjectLayers - * @since 3.0.0 - * - * @param {object} json - The Tiled JSON object. - * - * @return {array} An array of all object layers in the tilemap as `ObjectLayer`s. - */ -var ParseObjectLayers = function (json) -{ - var objectLayers = []; - - // State inherited from a parent group - var groupStack = []; - var curGroupState = CreateGroupLayer(json); - - while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) - { - if (curGroupState.i >= curGroupState.layers.length) - { - // Ensure recursion stack is not empty first - if (groupStack.length < 1) - { - console.warn( - 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' - ); - break; - } - - // Return to previous recursive state - curGroupState = groupStack.pop(); - continue; - } - - // Get current layer and advance iterator - var curo = curGroupState.layers[curGroupState.i]; - curGroupState.i++; - - // Modify inherited properties - curo.opacity *= curGroupState.opacity; - curo.visible = curGroupState.visible && curo.visible; - - if (curo.type !== 'objectgroup') - { - if (curo.type === 'group') - { - // Compute next state inherited from group - var nextGroupState = CreateGroupLayer(json, curo, curGroupState); - - // Preserve current state before recursing - groupStack.push(curGroupState); - curGroupState = nextGroupState; - } - - // Skip this layer OR 'recurse' (iterative style) into the group - continue; - } - - curo.name = curGroupState.name + curo.name; - var offsetX = curGroupState.x + GetFastValue(curo, 'startx', 0) + GetFastValue(curo, 'offsetx', 0); - var offsetY = curGroupState.y + GetFastValue(curo, 'starty', 0) + GetFastValue(curo, 'offsety', 0); - - var objects = []; - for (var j = 0; j < curo.objects.length; j++) - { - var parsedObject = ParseObject(curo.objects[j], offsetX, offsetY); - - objects.push(parsedObject); - } - - var objectLayer = new ObjectLayer(curo); - objectLayer.objects = objects; - - objectLayers.push(objectLayer); - } - - return objectLayers; -}; - -module.exports = ParseObjectLayers; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetFastValue = require('../../../utils/object/GetFastValue'); +var ParseObject = require('./ParseObject'); +var ObjectLayer = require('../../mapdata/ObjectLayer'); +var CreateGroupLayer = require('./CreateGroupLayer'); + +/** + * Parses a Tiled JSON object into an array of ObjectLayer objects. + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseObjectLayers + * @since 3.0.0 + * + * @param {object} json - The Tiled JSON object. + * + * @return {array} An array of all object layers in the tilemap as `ObjectLayer`s. + */ +var ParseObjectLayers = function (json) +{ + var objectLayers = []; + + // State inherited from a parent group + var groupStack = []; + var curGroupState = CreateGroupLayer(json); + + while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) + { + if (curGroupState.i >= curGroupState.layers.length) + { + // Ensure recursion stack is not empty first + if (groupStack.length < 1) + { + console.warn( + 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' + ); + break; + } + + // Return to previous recursive state + curGroupState = groupStack.pop(); + continue; + } + + // Get current layer and advance iterator + var curo = curGroupState.layers[curGroupState.i]; + curGroupState.i++; + + // Modify inherited properties + curo.opacity *= curGroupState.opacity; + curo.visible = curGroupState.visible && curo.visible; + + if (curo.type !== 'objectgroup') + { + if (curo.type === 'group') + { + // Compute next state inherited from group + var nextGroupState = CreateGroupLayer(json, curo, curGroupState); + + // Preserve current state before recursing + groupStack.push(curGroupState); + curGroupState = nextGroupState; + } + + // Skip this layer OR 'recurse' (iterative style) into the group + continue; + } + + curo.name = curGroupState.name + curo.name; + var offsetX = curGroupState.x + GetFastValue(curo, 'startx', 0) + GetFastValue(curo, 'offsetx', 0); + var offsetY = curGroupState.y + GetFastValue(curo, 'starty', 0) + GetFastValue(curo, 'offsety', 0); + + var objects = []; + for (var j = 0; j < curo.objects.length; j++) + { + var parsedObject = ParseObject(curo.objects[j], offsetX, offsetY); + + objects.push(parsedObject); + } + + var objectLayer = new ObjectLayer(curo); + objectLayer.objects = objects; + + objectLayers.push(objectLayer); + } + + return objectLayers; +}; + +module.exports = ParseObjectLayers; diff --git a/src/tilemaps/parsers/tiled/ParseTileLayers.js b/src/tilemaps/parsers/tiled/ParseTileLayers.js index dc7a24207..bfacadd9b 100644 --- a/src/tilemaps/parsers/tiled/ParseTileLayers.js +++ b/src/tilemaps/parsers/tiled/ParseTileLayers.js @@ -1,264 +1,264 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('../../../const.js'); -var Base64Decode = require('./Base64Decode'); -var GetFastValue = require('../../../utils/object/GetFastValue'); -var LayerData = require('../../mapdata/LayerData'); -var ParseGID = require('./ParseGID'); -var Tile = require('../../Tile'); -var CreateGroupLayer = require('./CreateGroupLayer'); - -/** - * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. - * - * @function Phaser.Tilemaps.Parsers.Tiled.ParseTileLayers - * @since 3.0.0 - * - * @param {object} json - The Tiled JSON object. - * @param {boolean} insertNull - Controls how empty tiles, tiles with an index of -1, in the map - * data are handled (see {@link Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled}). - * - * @return {Phaser.Tilemaps.LayerData[]} - An array of LayerData objects, one for each entry in - * json.layers with the type 'tilelayer'. - */ -var ParseTileLayers = function (json, insertNull) -{ - var infiniteMap = GetFastValue(json, 'infinite', false); - var tileLayers = []; - - // State inherited from a parent group - var groupStack = []; - var curGroupState = CreateGroupLayer(json); - - while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) - { - if (curGroupState.i >= curGroupState.layers.length) - { - // Ensure recursion stack is not empty first - if (groupStack.length < 1) - { - console.warn( - 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' - ); - break; - } - - // Return to previous recursive state - curGroupState = groupStack.pop(); - continue; - } - - var curl = curGroupState.layers[curGroupState.i]; - curGroupState.i++; - - if (curl.type !== 'tilelayer') - { - if (curl.type === 'group') - { - // Compute next state inherited from group - var nextGroupState = CreateGroupLayer(json, curl, curGroupState); - - // Preserve current state before recursing - groupStack.push(curGroupState); - curGroupState = nextGroupState; - } - - // Skip this layer OR 'recurse' (iterative style) into the group - continue; - } - - // Base64 decode data if necessary. NOTE: uncompressed base64 only. - if (curl.compression) - { - console.warn( - 'TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' - + curl.name + '\'' - ); - continue; - } - else if (curl.encoding && curl.encoding === 'base64') - { - // Chunks for an infinite map - if (curl.chunks) - { - for (var i = 0; i < curl.chunks.length; i++) - { - curl.chunks[i].data = Base64Decode(curl.chunks[i].data); - } - } - - // Non-infinite map data - if (curl.data) - { - curl.data = Base64Decode(curl.data); - } - - delete curl.encoding; // Allow the same map to be parsed multiple times - } - - // 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. - - var layerData; - var gidInfo; - var tile; - var blankTile; - - var output = []; - var x = 0; - - if (infiniteMap) - { - var layerOffsetX = (GetFastValue(curl, 'startx', 0) + curl.x); - var layerOffsetY = (GetFastValue(curl, 'starty', 0) + curl.y); - layerData = new LayerData({ - name: (curGroupState.name + curl.name), - x: (curGroupState.x + GetFastValue(curl, 'offsetx', 0) + layerOffsetX * json.tilewidth), - y: (curGroupState.y + GetFastValue(curl, 'offsety', 0) + layerOffsetY * json.tileheight), - width: curl.width, - height: curl.height, - tileWidth: json.tilewidth, - tileHeight: json.tileheight, - alpha: (curGroupState.opacity * curl.opacity), - visible: (curGroupState.visible && curl.visible), - properties: GetFastValue(curl, 'properties', {}), - orientation: CONST.fromOrientationString(json.orientation) - }); - - if (layerData.orientation === CONST.HEXAGONAL) - { - layerData.hexSideLength = json.hexsidelength; - } - - for (var c = 0; c < curl.height; c++) - { - output.push([ null ]); - - for (var j = 0; j < curl.width; j++) - { - output[c][j] = null; - } - } - - for (c = 0, len = curl.chunks.length; c < len; c++) - { - var chunk = curl.chunks[c]; - - var offsetX = (chunk.x - layerOffsetX); - var offsetY = (chunk.y - layerOffsetY); - - var y = 0; - - for (var t = 0, len2 = chunk.data.length; t < len2; t++) - { - var newOffsetX = x + offsetX; - var newOffsetY = y + offsetY; - - gidInfo = ParseGID(chunk.data[t]); - - // index, x, y, width, height - if (gidInfo.gid > 0) - { - tile = new Tile(layerData, gidInfo.gid, newOffsetX, newOffsetY, json.tilewidth, - json.tileheight); - - // Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal - // propeties into flipX, flipY and rotation - tile.rotation = gidInfo.rotation; - tile.flipX = gidInfo.flipped; - - output[newOffsetY][newOffsetX] = tile; - } - else - { - blankTile = insertNull - ? null - : new Tile(layerData, -1, newOffsetX, newOffsetY, json.tilewidth, json.tileheight); - - output[newOffsetY][newOffsetX] = blankTile; - } - - x++; - - if (x === chunk.width) - { - y++; - x = 0; - } - } - } - } - else - { - layerData = new LayerData({ - name: (curGroupState.name + curl.name), - x: (curGroupState.x + GetFastValue(curl, 'offsetx', 0) + curl.x), - y: (curGroupState.y + GetFastValue(curl, 'offsety', 0) + curl.y), - width: curl.width, - height: curl.height, - tileWidth: json.tilewidth, - tileHeight: json.tileheight, - alpha: (curGroupState.opacity * curl.opacity), - visible: (curGroupState.visible && curl.visible), - properties: GetFastValue(curl, 'properties', {}), - orientation: CONST.fromOrientationString(json.orientation) - }); - - if (layerData.orientation === CONST.HEXAGONAL) - { - layerData.hexSideLength = json.hexsidelength; - } - var row = []; - - // Loop through the data field in the JSON. - for (var k = 0, len = curl.data.length; k < len; k++) - { - gidInfo = ParseGID(curl.data[k]); - - // index, x, y, width, height - if (gidInfo.gid > 0) - { - tile = new Tile(layerData, gidInfo.gid, x, output.length, json.tilewidth, - json.tileheight); - - // Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal - // propeties into flipX, flipY and rotation - tile.rotation = gidInfo.rotation; - tile.flipX = gidInfo.flipped; - - row.push(tile); - } - else - { - blankTile = insertNull - ? null - : new Tile(layerData, -1, x, output.length, json.tilewidth, json.tileheight); - row.push(blankTile); - } - - x++; - - if (x === curl.width) - { - output.push(row); - x = 0; - row = []; - } - } - } - - layerData.data = output; - tileLayers.push(layerData); - } - - return tileLayers; -}; - -module.exports = ParseTileLayers; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('../../../const.js'); +var Base64Decode = require('./Base64Decode'); +var GetFastValue = require('../../../utils/object/GetFastValue'); +var LayerData = require('../../mapdata/LayerData'); +var ParseGID = require('./ParseGID'); +var Tile = require('../../Tile'); +var CreateGroupLayer = require('./CreateGroupLayer'); + +/** + * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseTileLayers + * @since 3.0.0 + * + * @param {object} json - The Tiled JSON object. + * @param {boolean} insertNull - Controls how empty tiles, tiles with an index of -1, in the map + * data are handled (see {@link Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled}). + * + * @return {Phaser.Tilemaps.LayerData[]} - An array of LayerData objects, one for each entry in + * json.layers with the type 'tilelayer'. + */ +var ParseTileLayers = function (json, insertNull) +{ + var infiniteMap = GetFastValue(json, 'infinite', false); + var tileLayers = []; + + // State inherited from a parent group + var groupStack = []; + var curGroupState = CreateGroupLayer(json); + + while (curGroupState.i < curGroupState.layers.length || groupStack.length > 0) + { + if (curGroupState.i >= curGroupState.layers.length) + { + // Ensure recursion stack is not empty first + if (groupStack.length < 1) + { + console.warn( + 'TilemapParser.parseTiledJSON - Invalid layer group hierarchy' + ); + break; + } + + // Return to previous recursive state + curGroupState = groupStack.pop(); + continue; + } + + var curl = curGroupState.layers[curGroupState.i]; + curGroupState.i++; + + if (curl.type !== 'tilelayer') + { + if (curl.type === 'group') + { + // Compute next state inherited from group + var nextGroupState = CreateGroupLayer(json, curl, curGroupState); + + // Preserve current state before recursing + groupStack.push(curGroupState); + curGroupState = nextGroupState; + } + + // Skip this layer OR 'recurse' (iterative style) into the group + continue; + } + + // Base64 decode data if necessary. NOTE: uncompressed base64 only. + if (curl.compression) + { + console.warn( + 'TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + + curl.name + '\'' + ); + continue; + } + else if (curl.encoding && curl.encoding === 'base64') + { + // Chunks for an infinite map + if (curl.chunks) + { + for (var i = 0; i < curl.chunks.length; i++) + { + curl.chunks[i].data = Base64Decode(curl.chunks[i].data); + } + } + + // Non-infinite map data + if (curl.data) + { + curl.data = Base64Decode(curl.data); + } + + delete curl.encoding; // Allow the same map to be parsed multiple times + } + + // 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. + + var layerData; + var gidInfo; + var tile; + var blankTile; + + var output = []; + var x = 0; + + if (infiniteMap) + { + var layerOffsetX = (GetFastValue(curl, 'startx', 0) + curl.x); + var layerOffsetY = (GetFastValue(curl, 'starty', 0) + curl.y); + layerData = new LayerData({ + name: (curGroupState.name + curl.name), + x: (curGroupState.x + GetFastValue(curl, 'offsetx', 0) + layerOffsetX * json.tilewidth), + y: (curGroupState.y + GetFastValue(curl, 'offsety', 0) + layerOffsetY * json.tileheight), + width: curl.width, + height: curl.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + alpha: (curGroupState.opacity * curl.opacity), + visible: (curGroupState.visible && curl.visible), + properties: GetFastValue(curl, 'properties', {}), + orientation: CONST.fromOrientationString(json.orientation) + }); + + if (layerData.orientation === CONST.HEXAGONAL) + { + layerData.hexSideLength = json.hexsidelength; + } + + for (var c = 0; c < curl.height; c++) + { + output.push([ null ]); + + for (var j = 0; j < curl.width; j++) + { + output[c][j] = null; + } + } + + for (c = 0, len = curl.chunks.length; c < len; c++) + { + var chunk = curl.chunks[c]; + + var offsetX = (chunk.x - layerOffsetX); + var offsetY = (chunk.y - layerOffsetY); + + var y = 0; + + for (var t = 0, len2 = chunk.data.length; t < len2; t++) + { + var newOffsetX = x + offsetX; + var newOffsetY = y + offsetY; + + gidInfo = ParseGID(chunk.data[t]); + + // index, x, y, width, height + if (gidInfo.gid > 0) + { + tile = new Tile(layerData, gidInfo.gid, newOffsetX, newOffsetY, json.tilewidth, + json.tileheight); + + // Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal + // propeties into flipX, flipY and rotation + tile.rotation = gidInfo.rotation; + tile.flipX = gidInfo.flipped; + + output[newOffsetY][newOffsetX] = tile; + } + else + { + blankTile = insertNull + ? null + : new Tile(layerData, -1, newOffsetX, newOffsetY, json.tilewidth, json.tileheight); + + output[newOffsetY][newOffsetX] = blankTile; + } + + x++; + + if (x === chunk.width) + { + y++; + x = 0; + } + } + } + } + else + { + layerData = new LayerData({ + name: (curGroupState.name + curl.name), + x: (curGroupState.x + GetFastValue(curl, 'offsetx', 0) + curl.x), + y: (curGroupState.y + GetFastValue(curl, 'offsety', 0) + curl.y), + width: curl.width, + height: curl.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + alpha: (curGroupState.opacity * curl.opacity), + visible: (curGroupState.visible && curl.visible), + properties: GetFastValue(curl, 'properties', {}), + orientation: CONST.fromOrientationString(json.orientation) + }); + + if (layerData.orientation === CONST.HEXAGONAL) + { + layerData.hexSideLength = json.hexsidelength; + } + var row = []; + + // Loop through the data field in the JSON. + for (var k = 0, len = curl.data.length; k < len; k++) + { + gidInfo = ParseGID(curl.data[k]); + + // index, x, y, width, height + if (gidInfo.gid > 0) + { + tile = new Tile(layerData, gidInfo.gid, x, output.length, json.tilewidth, + json.tileheight); + + // Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal + // propeties into flipX, flipY and rotation + tile.rotation = gidInfo.rotation; + tile.flipX = gidInfo.flipped; + + row.push(tile); + } + else + { + blankTile = insertNull + ? null + : new Tile(layerData, -1, x, output.length, json.tilewidth, json.tileheight); + row.push(blankTile); + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + } + + layerData.data = output; + tileLayers.push(layerData); + } + + return tileLayers; +}; + +module.exports = ParseTileLayers; diff --git a/src/tilemaps/parsers/tiled/ParseTilesets.js b/src/tilemaps/parsers/tiled/ParseTilesets.js index 491af546c..9e4cf6d01 100644 --- a/src/tilemaps/parsers/tiled/ParseTilesets.js +++ b/src/tilemaps/parsers/tiled/ParseTilesets.js @@ -1,163 +1,163 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Tileset = require('../../Tileset'); -var ImageCollection = require('../../ImageCollection'); -var ParseObject = require('./ParseObject'); - -/** - * Tilesets and Image Collections - * - * @function Phaser.Tilemaps.Parsers.Tiled.ParseTilesets - * @since 3.0.0 - * - * @param {object} json - [description] - * - * @return {object} [description] - */ -var ParseTilesets = function (json) -{ - var tilesets = []; - var imageCollections = []; - var lastSet = null; - var stringID; - - for (var i = 0; i < json.tilesets.length; i++) - { - // name, firstgid, width, height, margin, spacing, properties - var set = json.tilesets[i]; - - if (set.source) - { - console.warn('Phaser can\'t load external tilesets. Use the Embed Tileset button and then export the map again.'); - } - else if (set.image) - { - var newSet = new Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing); - - if (json.version > 1) - { - // Tiled 1.2+ - - if (Array.isArray(set.tiles)) - { - var tiles = {}; - var props = {}; - - for (var t = 0; t < set.tiles.length; t++) - { - var tile = set.tiles[t]; - - // Convert tileproperties - if (tile.properties) - { - var newPropData = {}; - - tile.properties.forEach(function (propData) - { - newPropData[propData['name']] = propData['value']; - }); - - props[tile.id] = newPropData; - } - - // Convert objectgroup - if (tile.objectgroup) - { - tiles[tile.id] = { objectgroup: tile.objectgroup }; - - if (tile.objectgroup.objects) - { - var parsedObjects2 = tile.objectgroup.objects.map( - function (obj) { return ParseObject(obj); } - ); - - tiles[tile.id].objectgroup.objects = parsedObjects2; - } - } - - // Copy animation data - if (tile.animation) - { - if (tiles.hasOwnProperty(tile.id)) - { - tiles[tile.id].animation = tile.animation; - } - else - { - tiles[tile.id] = { animation: tile.animation }; - } - } - } - - newSet.tileData = tiles; - newSet.tileProperties = props; - } - } - else - { - // Tiled 1 - - // Properties stored per-tile in object with string indexes starting at "0" - if (set.tileproperties) - { - newSet.tileProperties = set.tileproperties; - } - - // Object & terrain shapes stored per-tile in object with string indexes starting at "0" - if (set.tiles) - { - newSet.tileData = set.tiles; - - // Parse the objects into Phaser format to match handling of other Tiled objects - for (stringID in newSet.tileData) - { - var objectGroup = newSet.tileData[stringID].objectgroup; - if (objectGroup && objectGroup.objects) - { - var parsedObjects1 = objectGroup.objects.map( - function (obj) { return ParseObject(obj); } - ); - newSet.tileData[stringID].objectgroup.objects = parsedObjects1; - } - } - } - } - - // For a normal sliced tileset the row/count/size information is computed when updated. - // This is done (again) after the image is set. - newSet.updateTileData(set.imagewidth, set.imageheight); - - tilesets.push(newSet); - } - else - { - var newCollection = new ImageCollection(set.name, set.firstgid, set.tilewidth, - set.tileheight, set.margin, set.spacing, set.properties); - - for (stringID in set.tiles) - { - var image = set.tiles[stringID].image; - var gid = set.firstgid + parseInt(stringID, 10); - newCollection.addImage(gid, image); - } - - imageCollections.push(newCollection); - } - - // We've got a new Tileset, so set the lastgid into the previous one - if (lastSet) - { - lastSet.lastgid = set.firstgid - 1; - } - - lastSet = set; - } - - return { tilesets: tilesets, imageCollections: imageCollections }; -}; - -module.exports = ParseTilesets; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Tileset = require('../../Tileset'); +var ImageCollection = require('../../ImageCollection'); +var ParseObject = require('./ParseObject'); + +/** + * Tilesets and Image Collections + * + * @function Phaser.Tilemaps.Parsers.Tiled.ParseTilesets + * @since 3.0.0 + * + * @param {object} json - [description] + * + * @return {object} [description] + */ +var ParseTilesets = function (json) +{ + var tilesets = []; + var imageCollections = []; + var lastSet = null; + var stringID; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser can\'t load external tilesets. Use the Embed Tileset button and then export the map again.'); + } + else if (set.image) + { + var newSet = new Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing); + + if (json.version > 1) + { + // Tiled 1.2+ + + if (Array.isArray(set.tiles)) + { + var tiles = {}; + var props = {}; + + for (var t = 0; t < set.tiles.length; t++) + { + var tile = set.tiles[t]; + + // Convert tileproperties + if (tile.properties) + { + var newPropData = {}; + + tile.properties.forEach(function (propData) + { + newPropData[propData['name']] = propData['value']; + }); + + props[tile.id] = newPropData; + } + + // Convert objectgroup + if (tile.objectgroup) + { + tiles[tile.id] = { objectgroup: tile.objectgroup }; + + if (tile.objectgroup.objects) + { + var parsedObjects2 = tile.objectgroup.objects.map( + function (obj) { return ParseObject(obj); } + ); + + tiles[tile.id].objectgroup.objects = parsedObjects2; + } + } + + // Copy animation data + if (tile.animation) + { + if (tiles.hasOwnProperty(tile.id)) + { + tiles[tile.id].animation = tile.animation; + } + else + { + tiles[tile.id] = { animation: tile.animation }; + } + } + } + + newSet.tileData = tiles; + newSet.tileProperties = props; + } + } + else + { + // Tiled 1 + + // Properties stored per-tile in object with string indexes starting at "0" + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // Object & terrain shapes stored per-tile in object with string indexes starting at "0" + if (set.tiles) + { + newSet.tileData = set.tiles; + + // Parse the objects into Phaser format to match handling of other Tiled objects + for (stringID in newSet.tileData) + { + var objectGroup = newSet.tileData[stringID].objectgroup; + if (objectGroup && objectGroup.objects) + { + var parsedObjects1 = objectGroup.objects.map( + function (obj) { return ParseObject(obj); } + ); + newSet.tileData[stringID].objectgroup.objects = parsedObjects1; + } + } + } + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else + { + var newCollection = new ImageCollection(set.name, set.firstgid, set.tilewidth, + set.tileheight, set.margin, set.spacing, set.properties); + + for (stringID in set.tiles) + { + var image = set.tiles[stringID].image; + var gid = set.firstgid + parseInt(stringID, 10); + newCollection.addImage(gid, image); + } + + imageCollections.push(newCollection); + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + return { tilesets: tilesets, imageCollections: imageCollections }; +}; + +module.exports = ParseTilesets; diff --git a/src/tilemaps/parsers/tiled/index.js b/src/tilemaps/parsers/tiled/index.js index 9f047d9dd..3a7f11b19 100644 --- a/src/tilemaps/parsers/tiled/index.js +++ b/src/tilemaps/parsers/tiled/index.js @@ -1,24 +1,24 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tilemaps.Parsers.Tiled - */ - -module.exports = { - - AssignTileProperties: require('./AssignTileProperties'), - Base64Decode: require('./Base64Decode'), - BuildTilesetIndex: require('./BuildTilesetIndex'), - ParseGID: require('./ParseGID'), - ParseImageLayers: require('./ParseImageLayers'), - ParseJSONTiled: require('./ParseJSONTiled'), - ParseObject: require('./ParseObject'), - ParseObjectLayers: require('./ParseObjectLayers'), - ParseTileLayers: require('./ParseTileLayers'), - ParseTilesets: require('./ParseTilesets') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tilemaps.Parsers.Tiled + */ + +module.exports = { + + AssignTileProperties: require('./AssignTileProperties'), + Base64Decode: require('./Base64Decode'), + BuildTilesetIndex: require('./BuildTilesetIndex'), + ParseGID: require('./ParseGID'), + ParseImageLayers: require('./ParseImageLayers'), + ParseJSONTiled: require('./ParseJSONTiled'), + ParseObject: require('./ParseObject'), + ParseObjectLayers: require('./ParseObjectLayers'), + ParseTileLayers: require('./ParseTileLayers'), + ParseTilesets: require('./ParseTilesets') + +}; diff --git a/src/tilemaps/staticlayer/StaticTilemapLayer.js b/src/tilemaps/staticlayer/StaticTilemapLayer.js index f9ed9e023..855b62ec3 100644 --- a/src/tilemaps/staticlayer/StaticTilemapLayer.js +++ b/src/tilemaps/staticlayer/StaticTilemapLayer.js @@ -1,1502 +1,1502 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var Components = require('../../gameobjects/components'); -var GameEvents = require('../../core/events'); -var GameObject = require('../../gameobjects/GameObject'); -var StaticTilemapLayerRender = require('./StaticTilemapLayerRender'); -var TilemapComponents = require('../components'); -var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); -var Utils = require('../../renderer/webgl/Utils'); -var Vector2 = require('../../math/Vector2'); - -/** - * @classdesc - * A Static Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination - * with one, or more, Tilesets. - * - * A Static Tilemap Layer is optimized for rendering speed over flexibility. You cannot apply per-tile - * effects like tint or alpha, or change the tiles or tilesets the layer uses. - * - * Use a Static Tilemap Layer instead of a Dynamic Tilemap Layer when you don't need tile manipulation features. - * - * @class StaticTilemapLayer - * @extends Phaser.GameObjects.GameObject - * @memberof Phaser.Tilemaps - * @constructor - * @since 3.0.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.Origin - * @extends Phaser.GameObjects.Components.Pipeline - * @extends Phaser.GameObjects.Components.Transform - * @extends Phaser.GameObjects.Components.Visible - * @extends Phaser.GameObjects.Components.ScrollFactor - * - * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. - * @param {Phaser.Tilemaps.Tilemap} tilemap - The Tilemap this layer is a part of. - * @param {integer} layerIndex - The index of the LayerData associated with this layer. - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param {number} [x=0] - The world x position where the top left of this layer will be placed. - * @param {number} [y=0] - The world y position where the top left of this layer will be placed. - */ -var StaticTilemapLayer = new Class({ - - Extends: GameObject, - - Mixins: [ - Components.Alpha, - Components.BlendMode, - Components.ComputedSize, - Components.Depth, - Components.Flip, - Components.GetBounds, - Components.Origin, - Components.Pipeline, - Components.Transform, - Components.Visible, - Components.ScrollFactor, - StaticTilemapLayerRender - ], - - initialize: - - function StaticTilemapLayer (scene, tilemap, layerIndex, tileset, x, y) - { - GameObject.call(this, scene, 'StaticTilemapLayer'); - - /** - * Used internally by physics system to perform fast type checks. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#isTilemap - * @type {boolean} - * @readonly - * @since 3.0.0 - */ - this.isTilemap = true; - - /** - * The Tilemap that this layer is a part of. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#tilemap - * @type {Phaser.Tilemaps.Tilemap} - * @since 3.0.0 - */ - this.tilemap = tilemap; - - /** - * The index of the LayerData associated with this layer. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#layerIndex - * @type {integer} - * @since 3.0.0 - */ - this.layerIndex = layerIndex; - - /** - * The LayerData associated with this layer. LayerData can only be associated with one - * tilemap layer. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#layer - * @type {Phaser.Tilemaps.LayerData} - * @since 3.0.0 - */ - this.layer = tilemap.layers[layerIndex]; - - // Link the LayerData with this static tilemap layer - this.layer.tilemapLayer = this; - - /** - * The Tileset/s associated with this layer. - * - * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#tileset - * @type {Phaser.Tilemaps.Tileset[]} - * @since 3.0.0 - */ - this.tileset = []; - - /** - * Used internally by the Canvas renderer. - * This holds the tiles that are visible within the camera in the last frame. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#culledTiles - * @type {array} - * @since 3.0.0 - */ - this.culledTiles = []; - - /** - * Canvas only. - * - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this, and toggling this flag allows - * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#skipCull - * @type {boolean} - * @since 3.12.0 - */ - this.skipCull = false; - - /** - * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. - * By default the camera will allow 1 full tile in all directions. - * - * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#isoCullDistances - * @type {Phaser.Math.Vector2} - * @since 3.23.0 - */ - this.isoCullDistances = new Vector2(1, 1); - - /** - * Canvas only. - * - * The total number of tiles drawn by the renderer in the last frame. - * - * This only works when rending with Canvas. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#tilesDrawn - * @type {integer} - * @readonly - * @since 3.12.0 - */ - this.tilesDrawn = 0; - - /** - * Canvas only. - * - * The total number of tiles in this layer. Updated every frame. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#tilesTotal - * @type {integer} - * @readonly - * @since 3.12.0 - */ - this.tilesTotal = this.layer.width * this.layer.height; - - /** - * Canvas only. - * - * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. - * - * See the method `setCullPadding` for more details. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#cullPaddingX - * @type {integer} - * @default 1 - * @since 3.12.0 - */ - this.cullPaddingX = 1; - - /** - * Canvas only. - * - * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. - * - * See the method `setCullPadding` for more details. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#cullPaddingY - * @type {integer} - * @default 1 - * @since 3.12.0 - */ - this.cullPaddingY = 1; - - /** - * Canvas only. - * - * The callback that is invoked when the tiles are culled. - * - * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. - * - * It will be sent 3 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. - * - * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#cullCallback - * @type {function} - * @since 3.12.0 - */ - this.cullCallback = TilemapComponents.CullTiles; - - /** - * A reference to the renderer. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#renderer - * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} - * @private - * @since 3.0.0 - */ - this.renderer = scene.sys.game.renderer; - - /** - * An array of vertex buffer objects, used by the WebGL renderer. - * - * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#vertexBuffer - * @type {WebGLBuffer[]} - * @private - * @since 3.0.0 - */ - this.vertexBuffer = []; - - /** - * An array of ArrayBuffer objects, used by the WebGL renderer. - * - * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#bufferData - * @type {ArrayBuffer[]} - * @private - * @since 3.0.0 - */ - this.bufferData = []; - - /** - * An array of Float32 Array objects, used by the WebGL renderer. - * - * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#vertexViewF32 - * @type {Float32Array[]} - * @private - * @since 3.0.0 - */ - this.vertexViewF32 = []; - - /** - * An array of Uint32 Array objects, used by the WebGL renderer. - * - * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#vertexViewU32 - * @type {Uint32Array[]} - * @private - * @since 3.0.0 - */ - this.vertexViewU32 = []; - - /** - * An array of booleans, used by the WebGL renderer. - * - * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single boolean. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#dirty - * @type {boolean[]} - * @private - * @since 3.0.0 - */ - this.dirty = []; - - /** - * An array of integers, used by the WebGL renderer. - * - * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single integer. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#vertexCount - * @type {integer[]} - * @private - * @since 3.0.0 - */ - this.vertexCount = []; - - /** - * The rendering (draw) order of the tiles in this layer. - * - * The default is 0 which is 'right-down', meaning it will draw the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * This can be changed via the `setRenderOrder` method. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#_renderOrder - * @type {integer} - * @default 0 - * @private - * @since 3.12.0 - */ - this._renderOrder = 0; - - /** - * A temporary Transform Matrix, re-used internally during batching. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#_tempMatrix - * @private - * @type {Phaser.GameObjects.Components.TransformMatrix} - * @since 3.14.0 - */ - this._tempMatrix = new TransformMatrix(); - - /** - * An array holding the mapping between the tile indexes and the tileset they belong to. - * - * @name Phaser.Tilemaps.StaticTilemapLayer#gidMap - * @type {Phaser.Tilemaps.Tileset[]} - * @since 3.14.0 - */ - this.gidMap = []; - - this.setTilesets(tileset); - this.setAlpha(this.layer.alpha); - this.setPosition(x, y); - this.setOrigin(); - this.setSize(tilemap.tileWidth * this.layer.width, tilemap.tileHeight * this.layer.height); - - this.updateVBOData(); - - this.initPipeline('TextureTintPipeline'); - - scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function () - { - this.updateVBOData(); - }, this); - - }, - - /** - * Populates the internal `tileset` array with the Tileset references this Layer requires for rendering. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setTilesets - * @private - * @since 3.14.0 - * - * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - */ - setTilesets: function (tilesets) - { - var gidMap = []; - var setList = []; - var map = this.tilemap; - - if (!Array.isArray(tilesets)) - { - tilesets = [ tilesets ]; - } - - for (var i = 0; i < tilesets.length; i++) - { - var tileset = tilesets[i]; - - if (typeof tileset === 'string') - { - tileset = map.getTileset(tileset); - } - - if (tileset) - { - setList.push(tileset); - - var s = tileset.firstgid; - - for (var t = 0; t < tileset.total; t++) - { - gidMap[s + t] = tileset; - } - } - } - - this.gidMap = gidMap; - this.tileset = setList; - }, - - /** - * Prepares the VBO data arrays for population by the `upload` method. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#updateVBOData - * @private - * @since 3.14.0 - * - * @return {this} This Tilemap Layer object. - */ - updateVBOData: function () - { - for (var i = 0; i < this.tileset.length; i++) - { - this.dirty[i] = true; - this.vertexCount[i] = 0; - this.vertexBuffer[i] = null; - this.bufferData[i] = null; - this.vertexViewF32[i] = null; - this.vertexViewU32[i] = null; - } - - return this; - }, - - /** - * Upload the tile data to a VBO. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#upload - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to render to. - * @param {integer} tilesetIndex - The tileset index. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - upload: function (camera, tilesetIndex) - { - var renderer = this.renderer; - var gl = renderer.gl; - - var pipeline = renderer.pipelines.TextureTintPipeline; - - if (this.dirty[tilesetIndex]) - { - var tileset = this.tileset[tilesetIndex]; - var mapWidth = this.layer.width; - var mapHeight = this.layer.height; - var width = tileset.image.source[0].width; - var height = tileset.image.source[0].height; - var mapData = this.layer.data; - var tile; - var row; - var col; - var renderOrder = this._renderOrder; - var minTileIndex = tileset.firstgid; - var maxTileIndex = tileset.firstgid + tileset.total; - - var vertexBuffer = this.vertexBuffer[tilesetIndex]; - var bufferData = this.bufferData[tilesetIndex]; - var vOffset = -1; - var bufferSize = (mapWidth * mapHeight) * pipeline.vertexSize * 6; - - this.vertexCount[tilesetIndex] = 0; - - if (bufferData === null) - { - bufferData = new ArrayBuffer(bufferSize); - - this.bufferData[tilesetIndex] = bufferData; - - this.vertexViewF32[tilesetIndex] = new Float32Array(bufferData); - this.vertexViewU32[tilesetIndex] = new Uint32Array(bufferData); - } - - if (renderOrder === 0) - { - // right-down - - for (row = 0; row < mapHeight; row++) - { - for (col = 0; col < mapWidth; col++) - { - tile = mapData[row][col]; - - if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) - { - continue; - } - - vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); - } - } - } - else if (renderOrder === 1) - { - // left-down - - for (row = 0; row < mapHeight; row++) - { - for (col = mapWidth - 1; col >= 0; col--) - { - tile = mapData[row][col]; - - if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) - { - continue; - } - - vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); - } - } - } - else if (renderOrder === 2) - { - // right-up - - for (row = mapHeight - 1; row >= 0; row--) - { - for (col = 0; col < mapWidth; col++) - { - tile = mapData[row][col]; - - if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) - { - continue; - } - - vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); - } - } - } - else if (renderOrder === 3) - { - // left-up - - for (row = mapHeight - 1; row >= 0; row--) - { - for (col = mapWidth - 1; col >= 0; col--) - { - tile = mapData[row][col]; - - if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) - { - continue; - } - - vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); - } - } - } - - this.dirty[tilesetIndex] = false; - - if (vertexBuffer === null) - { - vertexBuffer = renderer.createVertexBuffer(bufferData, gl.STATIC_DRAW); - - this.vertexBuffer[tilesetIndex] = vertexBuffer; - } - else - { - renderer.setVertexBuffer(vertexBuffer); - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, bufferData); - } - } - - return this; - }, - - /** - * Add a single tile into the batch. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#batchTile - * @private - * @since 3.12.0 - * - * @param {integer} vOffset - The vertex offset. - * @param {any} tile - The tile being rendered. - * @param {any} tileset - The tileset being used for rendering. - * @param {integer} width - The width of the tileset image in pixels. - * @param {integer} height - The height of the tileset image in pixels. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the layer is being rendered with. - * @param {integer} tilesetIndex - The tileset index. - * - * @return {integer} The new vOffset value. - */ - batchTile: function (vOffset, tile, tileset, width, height, camera, tilesetIndex) - { - var texCoords = tileset.getTileTextureCoordinates(tile.index); - - if (!texCoords) - { - return vOffset; - } - - var tileWidth = tileset.tileWidth; - var tileHeight = tileset.tileHeight; - - var halfTileWidth = tileWidth / 2; - var halfTileHeight = tileHeight / 2; - - var u0 = texCoords.x / width; - var v0 = texCoords.y / height; - var u1 = (texCoords.x + tileWidth) / width; - var v1 = (texCoords.y + tileHeight) / height; - - var matrix = this._tempMatrix; - - var x = -halfTileWidth; - var y = -halfTileHeight; - - if (tile.flipX) - { - tileWidth *= -1; - x += tileset.tileWidth; - } - - if (tile.flipY) - { - tileHeight *= -1; - y += tileset.tileHeight; - } - - var xw = x + tileWidth; - var yh = y + tileHeight; - - matrix.applyITRS(halfTileWidth + tile.pixelX, halfTileHeight + tile.pixelY, tile.rotation, 1, 1); - - var tint = Utils.getTintAppendFloatAlpha(0xffffff, camera.alpha * this.alpha * tile.alpha); - - var tx0 = matrix.getX(x, y); - var ty0 = matrix.getY(x, y); - - var tx1 = matrix.getX(x, yh); - var ty1 = matrix.getY(x, yh); - - var tx2 = matrix.getX(xw, yh); - var ty2 = matrix.getY(xw, yh); - - var tx3 = matrix.getX(xw, y); - var ty3 = matrix.getY(xw, y); - - if (camera.roundPixels) - { - tx0 = Math.round(tx0); - ty0 = Math.round(ty0); - - tx1 = Math.round(tx1); - ty1 = Math.round(ty1); - - tx2 = Math.round(tx2); - ty2 = Math.round(ty2); - - tx3 = Math.round(tx3); - ty3 = Math.round(ty3); - } - - var vertexViewF32 = this.vertexViewF32[tilesetIndex]; - var vertexViewU32 = this.vertexViewU32[tilesetIndex]; - - vertexViewF32[++vOffset] = tx0; - vertexViewF32[++vOffset] = ty0; - vertexViewF32[++vOffset] = u0; - vertexViewF32[++vOffset] = v0; - vertexViewF32[++vOffset] = 0; - vertexViewU32[++vOffset] = tint; - - vertexViewF32[++vOffset] = tx1; - vertexViewF32[++vOffset] = ty1; - vertexViewF32[++vOffset] = u0; - vertexViewF32[++vOffset] = v1; - vertexViewF32[++vOffset] = 0; - vertexViewU32[++vOffset] = tint; - - vertexViewF32[++vOffset] = tx2; - vertexViewF32[++vOffset] = ty2; - vertexViewF32[++vOffset] = u1; - vertexViewF32[++vOffset] = v1; - vertexViewF32[++vOffset] = 0; - vertexViewU32[++vOffset] = tint; - - vertexViewF32[++vOffset] = tx0; - vertexViewF32[++vOffset] = ty0; - vertexViewF32[++vOffset] = u0; - vertexViewF32[++vOffset] = v0; - vertexViewF32[++vOffset] = 0; - vertexViewU32[++vOffset] = tint; - - vertexViewF32[++vOffset] = tx2; - vertexViewF32[++vOffset] = ty2; - vertexViewF32[++vOffset] = u1; - vertexViewF32[++vOffset] = v1; - vertexViewF32[++vOffset] = 0; - vertexViewU32[++vOffset] = tint; - - vertexViewF32[++vOffset] = tx3; - vertexViewF32[++vOffset] = ty3; - vertexViewF32[++vOffset] = u1; - vertexViewF32[++vOffset] = v0; - vertexViewF32[++vOffset] = 0; - vertexViewU32[++vOffset] = tint; - - this.vertexCount[tilesetIndex] += 6; - - return vOffset; - }, - - /** - * Sets the rendering (draw) order of the tiles in this layer. - * - * The default is 'right-down', meaning it will order the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * Setting the render order does not change the tiles or how they are stored in the layer, - * it purely impacts the order in which they are rendered. - * - * You can provide either an integer (0 to 3), or the string version of the order. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setRenderOrder - * @since 3.12.0 - * - * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. - * - * @return {this} This Tilemap Layer object. - */ - setRenderOrder: function (renderOrder) - { - var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; - - if (typeof renderOrder === 'string') - { - renderOrder = orders.indexOf(renderOrder); - } - - if (renderOrder >= 0 && renderOrder < 4) - { - this._renderOrder = renderOrder; - - for (var i = 0; i < this.tileset.length; i++) - { - this.dirty[i] = true; - } - } - - return this; - }, - - /** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#calculateFacesAt - * @since 3.0.0 - * - * @param {integer} tileX - The x coordinate. - * @param {integer} tileY - The y coordinate. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - calculateFacesAt: function (tileX, tileY) - { - TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); - - return this; - }, - - /** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#calculateFacesWithin - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - calculateFacesWithin: function (tileX, tileY, width, height) - { - TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); - - return this; - }, - - /** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#createFromTiles - * @since 3.0.0 - * - * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. - * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted - * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a - * one-to-one mapping with the indexes array. - * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. - * scene.make.sprite). - * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY - * - * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. - */ - createFromTiles: function (indexes, replacements, spriteConfig, scene, camera) - { - return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer); - }, - - /** - * Returns the tiles in the given layer that are within the cameras viewport. - * This is used internally. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#cull - * @since 3.0.0 - * - * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - cull: function (camera) - { - return this.cullCallback(this.layer, camera, this.culledTiles); - }, - - /** - * Canvas only. - * - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setSkipCull - * @since 3.12.0 - * - * @param {boolean} [value=true] - Set to `true` to stop culling tiles. Set to `false` to enable culling again. - * - * @return {this} This Tilemap Layer object. - */ - setSkipCull: function (value) - { - if (value === undefined) { value = true; } - - this.skipCull = value; - - return this; - }, - - /** - * Canvas only. - * - * When a Camera culls the tiles in this layer it does so using its view into the world, building up a - * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size - * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so - * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px - * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setCullPadding - * @since 3.12.0 - * - * @param {integer} [paddingX=1] - The amount of extra horizontal tiles to add to the cull check padding. - * @param {integer} [paddingY=1] - The amount of extra vertical tiles to add to the cull check padding. - * - * @return {this} This Tilemap Layer object. - */ - setCullPadding: function (paddingX, paddingY) - { - if (paddingX === undefined) { paddingX = 1; } - if (paddingY === undefined) { paddingY = 1; } - - this.cullPaddingX = paddingX; - this.cullPaddingY = paddingY; - - return this; - }, - - /** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#findByIndex - * @since 3.0.0 - * - * @param {integer} index - The tile index value to search for. - * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. - * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the - * bottom-right. Otherwise it scans from the top-left. - * - * @return {Phaser.Tilemaps.Tile} A Tile object. - */ - findByIndex: function (findIndex, skip, reverse) - { - return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer); - }, - - /** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#findTile - * @since 3.0.0 - * - * @param {function} callback - The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {?Phaser.Tilemaps.Tile} - */ - findTile: function (callback, context, tileX, tileY, width, height, filteringOptions) - { - return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); - }, - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#filterTiles - * @since 3.0.0 - * - * @param {function} callback - The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions) - { - return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); - }, - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#forEachTile - * @since 3.0.0 - * - * @param {function} callback - The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. - * @param {object} [context] - The context under which the callback should be run. - * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions) - { - TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); - - return this; - }, - - /** - * Gets a tile at the given tile coordinates from the given layer. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#getTileAt - * @since 3.0.0 - * - * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). - * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). - * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile - * object with an index of -1. - * - * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. - */ - getTileAt: function (tileX, tileY, nonNull) - { - return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer); - }, - - /** - * Gets a tile at the given world coordinates from the given layer. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#getTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - X position to get the tile from (given in pixels) - * @param {number} worldY - Y position to get the tile from (given in pixels) - * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile - * object with an index of -1. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates - * were invalid. - */ - getTileAtWorldXY: function (worldX, worldY, nonNull, camera) - { - return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer); - }, - - /** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithin - * @since 3.0.0 - * - * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. - * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - getTilesWithin: function (tileX, tileY, width, height, filteringOptions) - { - return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer); - }, - - /** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithinWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {number} worldY - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param {number} width - How many tiles wide from the `tileX` index the area will be. - * @param {number} height - How many tiles high from the `tileY` index the area will be. - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera) - { - return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer); - }, - - /** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithinShape - * @since 3.0.0 - * - * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates - * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. - */ - getTilesWithinShape: function (shape, filteringOptions, camera) - { - return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer); - }, - - /** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#hasTileAt - * @since 3.0.0 - * - * @param {integer} tileX - X position to get the tile from in tile coordinates. - * @param {integer} tileY - Y position to get the tile from in tile coordinates. - * - * @return {boolean} - */ - hasTileAt: function (tileX, tileY) - { - return TilemapComponents.HasTileAt(tileX, tileY, this.layer); - }, - - /** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#hasTileAtWorldXY - * @since 3.0.0 - * - * @param {number} worldX - The X coordinate of the world position. - * @param {number} worldY - The Y coordinate of the world position. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {boolean} - */ - hasTileAtWorldXY: function (worldX, worldY, camera) - { - return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer); - }, - - /** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#renderDebug - * @since 3.0.0 - * - * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. - * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - renderDebug: function (graphics, styleConfig) - { - TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); - - return this; - }, - - /** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setCollision - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear - * collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the - * update. - * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to - * false if no tiles have been placed for significant performance boost. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setCollision: function (indexes, collides, recalculateFaces, updateLayer) - { - TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer, updateLayer); - - return this; - }, - - /** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionBetween - * @since 3.0.0 - * - * @param {integer} start - The first index of the tile to be set for collision. - * @param {integer} stop - The last index of the tile to be set for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear - * collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the - * update. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setCollisionBetween: function (start, stop, collides, recalculateFaces) - { - TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionByProperty - * @since 3.0.0 - * - * @param {object} properties - An object with tile properties and corresponding values that should - * be checked. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear - * collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the - * update. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setCollisionByProperty: function (properties, collides, recalculateFaces) - { - TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionByExclusion - * @since 3.0.0 - * - * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear - * collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the - * update. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setCollisionByExclusion: function (indexes, collides, recalculateFaces) - { - TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setTileIndexCallback - * @since 3.0.0 - * - * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a - * collision callback set for. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} callbackContext - The context under which the callback is called. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setTileIndexCallback: function (indexes, callback, callbackContext) - { - TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); - - return this; - }, - - /** - * Sets collision on the tiles within a layer by checking each tiles collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tiles collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionFromCollisionGroup - * @since 3.0.0 - * - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear - * collision. - * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the - * update. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setCollisionFromCollisionGroup: function (collides, recalculateFaces) - { - TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); - - return this; - }, - - /** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#setTileLocationCallback - * @since 3.0.0 - * - * @param {integer} tileX - The leftmost tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} tileY - The topmost tile index (in tile coordinates) to use as the origin of the area. - * @param {integer} width - How many tiles wide from the `tileX` index the area will be. - * @param {integer} height - How many tiles tall from the `tileY` index the area will be. - * @param {function} callback - The callback that will be invoked when the tile is collided with. - * @param {object} [callbackContext] - The context under which the callback is called. - * - * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. - */ - setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext) - { - TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); - - return this; - }, - - /** - * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldX - * @since 3.0.0 - * - * @param {integer} tileX - The X coordinate, in tile coordinates. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. - * - * @return {number} - */ - tileToWorldX: function (tileX, camera) - { - return this.tilemap.TileToWorldX(tileX, camera, this.layer); - }, - - /** - * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldY - * @since 3.0.0 - * - * @param {integer} tileY - The Y coordinate, in tile coordinates. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. - * - * @return {number} - */ - tileToWorldY: function (tileY, camera) - { - return this.tilemap.TileToWorldY(tileY, camera, this.layer); - }, - - /** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldXY - * @since 3.0.0 - * - * @param {integer} tileX - The X coordinate, in tile coordinates. - * @param {integer} tileY - The Y coordinate, in tile coordinates. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given, a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. - * - * @return {Phaser.Math.Vector2} - */ - tileToWorldXY: function (tileX, tileY, point, camera) - { - return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); - }, - - /** - * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileX - * @since 3.0.0 - * - * @param {number} worldX - The X coordinate, in world pixels. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the - * nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values.] - * - * @return {number} - */ - worldToTileX: function (worldX, snapToFloor, camera) - { - return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); - }, - - /** - * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileY - * @since 3.0.0 - * - * @param {number} worldY - The Y coordinate, in world pixels. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the - * nearest integer. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {number} - */ - worldToTileY: function (worldY, snapToFloor, camera) - { - return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); - }, - - /** - * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileXY - * @since 3.0.0 - * - * @param {number} worldX - The X coordinate, in world pixels. - * @param {number} worldY - The Y coordinate, in world pixels. - * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the - * nearest integer. - * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given, a new Vector2 is created. - * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. - * - * @return {Phaser.Math.Vector2} - */ - worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) - { - return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); - }, - - /** - * Destroys this StaticTilemapLayer and removes its link to the associated LayerData. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#destroy - * @since 3.0.0 - * - * @param {boolean} [removeFromTilemap=true] - Remove this layer from the parent Tilemap? - */ - destroy: function (removeFromTilemap) - { - if (removeFromTilemap === undefined) { removeFromTilemap = true; } - - if (!this.tilemap) - { - // Abort, we've already been destroyed - return; - } - - // Uninstall this layer only if it is still installed on the LayerData object - if (this.layer.tilemapLayer === this) - { - this.layer.tilemapLayer = undefined; - } - - if (removeFromTilemap) - { - this.tilemap.removeLayer(this); - } - - this.tilemap = undefined; - this.layer = undefined; - this.culledTiles.length = 0; - this.cullCallback = null; - - for (var i = 0; i < this.tileset.length; i++) - { - this.dirty[i] = true; - this.vertexCount[i] = 0; - this.vertexBuffer[i] = null; - this.bufferData[i] = null; - this.vertexViewF32[i] = null; - this.vertexViewU32[i] = null; - } - - this.gidMap = []; - this.tileset = []; - - GameObject.prototype.destroy.call(this); - } - -}); - -module.exports = StaticTilemapLayer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var Components = require('../../gameobjects/components'); +var GameEvents = require('../../core/events'); +var GameObject = require('../../gameobjects/GameObject'); +var StaticTilemapLayerRender = require('./StaticTilemapLayerRender'); +var TilemapComponents = require('../components'); +var TransformMatrix = require('../../gameobjects/components/TransformMatrix'); +var Utils = require('../../renderer/webgl/Utils'); +var Vector2 = require('../../math/Vector2'); + +/** + * @classdesc + * A Static Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination + * with one, or more, Tilesets. + * + * A Static Tilemap Layer is optimized for rendering speed over flexibility. You cannot apply per-tile + * effects like tint or alpha, or change the tiles or tilesets the layer uses. + * + * Use a Static Tilemap Layer instead of a Dynamic Tilemap Layer when you don't need tile manipulation features. + * + * @class StaticTilemapLayer + * @extends Phaser.GameObjects.GameObject + * @memberof Phaser.Tilemaps + * @constructor + * @since 3.0.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.Origin + * @extends Phaser.GameObjects.Components.Pipeline + * @extends Phaser.GameObjects.Components.Transform + * @extends Phaser.GameObjects.Components.Visible + * @extends Phaser.GameObjects.Components.ScrollFactor + * + * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. + * @param {Phaser.Tilemaps.Tilemap} tilemap - The Tilemap this layer is a part of. + * @param {integer} layerIndex - The index of the LayerData associated with this layer. + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param {number} [x=0] - The world x position where the top left of this layer will be placed. + * @param {number} [y=0] - The world y position where the top left of this layer will be placed. + */ +var StaticTilemapLayer = new Class({ + + Extends: GameObject, + + Mixins: [ + Components.Alpha, + Components.BlendMode, + Components.ComputedSize, + Components.Depth, + Components.Flip, + Components.GetBounds, + Components.Origin, + Components.Pipeline, + Components.Transform, + Components.Visible, + Components.ScrollFactor, + StaticTilemapLayerRender + ], + + initialize: + + function StaticTilemapLayer (scene, tilemap, layerIndex, tileset, x, y) + { + GameObject.call(this, scene, 'StaticTilemapLayer'); + + /** + * Used internally by physics system to perform fast type checks. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#isTilemap + * @type {boolean} + * @readonly + * @since 3.0.0 + */ + this.isTilemap = true; + + /** + * The Tilemap that this layer is a part of. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tilemap + * @type {Phaser.Tilemaps.Tilemap} + * @since 3.0.0 + */ + this.tilemap = tilemap; + + /** + * The index of the LayerData associated with this layer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#layerIndex + * @type {integer} + * @since 3.0.0 + */ + this.layerIndex = layerIndex; + + /** + * The LayerData associated with this layer. LayerData can only be associated with one + * tilemap layer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#layer + * @type {Phaser.Tilemaps.LayerData} + * @since 3.0.0 + */ + this.layer = tilemap.layers[layerIndex]; + + // Link the LayerData with this static tilemap layer + this.layer.tilemapLayer = this; + + /** + * The Tileset/s associated with this layer. + * + * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tileset + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.0.0 + */ + this.tileset = []; + + /** + * Used internally by the Canvas renderer. + * This holds the tiles that are visible within the camera in the last frame. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#culledTiles + * @type {array} + * @since 3.0.0 + */ + this.culledTiles = []; + + /** + * Canvas only. + * + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this, and toggling this flag allows + * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#skipCull + * @type {boolean} + * @since 3.12.0 + */ + this.skipCull = false; + + /** + * In isometric mode, you can control the amount of distance (in tiles, from the cameras' borders) that the Cameras before culling. + * By default the camera will allow 1 full tile in all directions. + * + * However, there are some instances when you may wish to adjust this, and changing this variable allows you to do so. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#isoCullDistances + * @type {Phaser.Math.Vector2} + * @since 3.23.0 + */ + this.isoCullDistances = new Vector2(1, 1); + + /** + * Canvas only. + * + * The total number of tiles drawn by the renderer in the last frame. + * + * This only works when rending with Canvas. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tilesDrawn + * @type {integer} + * @readonly + * @since 3.12.0 + */ + this.tilesDrawn = 0; + + /** + * Canvas only. + * + * The total number of tiles in this layer. Updated every frame. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#tilesTotal + * @type {integer} + * @readonly + * @since 3.12.0 + */ + this.tilesTotal = this.layer.width * this.layer.height; + + /** + * Canvas only. + * + * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#cullPaddingX + * @type {integer} + * @default 1 + * @since 3.12.0 + */ + this.cullPaddingX = 1; + + /** + * Canvas only. + * + * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. + * + * See the method `setCullPadding` for more details. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#cullPaddingY + * @type {integer} + * @default 1 + * @since 3.12.0 + */ + this.cullPaddingY = 1; + + /** + * Canvas only. + * + * The callback that is invoked when the tiles are culled. + * + * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. + * + * It will be sent 3 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. + * + * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#cullCallback + * @type {function} + * @since 3.12.0 + */ + this.cullCallback = TilemapComponents.CullTiles; + + /** + * A reference to the renderer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#renderer + * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} + * @private + * @since 3.0.0 + */ + this.renderer = scene.sys.game.renderer; + + /** + * An array of vertex buffer objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexBuffer + * @type {WebGLBuffer[]} + * @private + * @since 3.0.0 + */ + this.vertexBuffer = []; + + /** + * An array of ArrayBuffer objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#bufferData + * @type {ArrayBuffer[]} + * @private + * @since 3.0.0 + */ + this.bufferData = []; + + /** + * An array of Float32 Array objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexViewF32 + * @type {Float32Array[]} + * @private + * @since 3.0.0 + */ + this.vertexViewF32 = []; + + /** + * An array of Uint32 Array objects, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single instance. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexViewU32 + * @type {Uint32Array[]} + * @private + * @since 3.0.0 + */ + this.vertexViewU32 = []; + + /** + * An array of booleans, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single boolean. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#dirty + * @type {boolean[]} + * @private + * @since 3.0.0 + */ + this.dirty = []; + + /** + * An array of integers, used by the WebGL renderer. + * + * As of Phaser 3.14 this property is now an array, where each element maps to a Tileset instance. Previously it was a single integer. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#vertexCount + * @type {integer[]} + * @private + * @since 3.0.0 + */ + this.vertexCount = []; + + /** + * The rendering (draw) order of the tiles in this layer. + * + * The default is 0 which is 'right-down', meaning it will draw the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * This can be changed via the `setRenderOrder` method. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#_renderOrder + * @type {integer} + * @default 0 + * @private + * @since 3.12.0 + */ + this._renderOrder = 0; + + /** + * A temporary Transform Matrix, re-used internally during batching. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#_tempMatrix + * @private + * @type {Phaser.GameObjects.Components.TransformMatrix} + * @since 3.14.0 + */ + this._tempMatrix = new TransformMatrix(); + + /** + * An array holding the mapping between the tile indexes and the tileset they belong to. + * + * @name Phaser.Tilemaps.StaticTilemapLayer#gidMap + * @type {Phaser.Tilemaps.Tileset[]} + * @since 3.14.0 + */ + this.gidMap = []; + + this.setTilesets(tileset); + this.setAlpha(this.layer.alpha); + this.setPosition(x, y); + this.setOrigin(); + this.setSize(tilemap.tileWidth * this.layer.width, tilemap.tileHeight * this.layer.height); + + this.updateVBOData(); + + this.initPipeline('TextureTintPipeline'); + + scene.sys.game.events.on(GameEvents.CONTEXT_RESTORED, function () + { + this.updateVBOData(); + }, this); + + }, + + /** + * Populates the internal `tileset` array with the Tileset references this Layer requires for rendering. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setTilesets + * @private + * @since 3.14.0 + * + * @param {(string|string[]|Phaser.Tilemaps.Tileset|Phaser.Tilemaps.Tileset[])} tileset - The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + */ + setTilesets: function (tilesets) + { + var gidMap = []; + var setList = []; + var map = this.tilemap; + + if (!Array.isArray(tilesets)) + { + tilesets = [ tilesets ]; + } + + for (var i = 0; i < tilesets.length; i++) + { + var tileset = tilesets[i]; + + if (typeof tileset === 'string') + { + tileset = map.getTileset(tileset); + } + + if (tileset) + { + setList.push(tileset); + + var s = tileset.firstgid; + + for (var t = 0; t < tileset.total; t++) + { + gidMap[s + t] = tileset; + } + } + } + + this.gidMap = gidMap; + this.tileset = setList; + }, + + /** + * Prepares the VBO data arrays for population by the `upload` method. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#updateVBOData + * @private + * @since 3.14.0 + * + * @return {this} This Tilemap Layer object. + */ + updateVBOData: function () + { + for (var i = 0; i < this.tileset.length; i++) + { + this.dirty[i] = true; + this.vertexCount[i] = 0; + this.vertexBuffer[i] = null; + this.bufferData[i] = null; + this.vertexViewF32[i] = null; + this.vertexViewU32[i] = null; + } + + return this; + }, + + /** + * Upload the tile data to a VBO. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#upload + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera to render to. + * @param {integer} tilesetIndex - The tileset index. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + upload: function (camera, tilesetIndex) + { + var renderer = this.renderer; + var gl = renderer.gl; + + var pipeline = renderer.pipelines.TextureTintPipeline; + + if (this.dirty[tilesetIndex]) + { + var tileset = this.tileset[tilesetIndex]; + var mapWidth = this.layer.width; + var mapHeight = this.layer.height; + var width = tileset.image.source[0].width; + var height = tileset.image.source[0].height; + var mapData = this.layer.data; + var tile; + var row; + var col; + var renderOrder = this._renderOrder; + var minTileIndex = tileset.firstgid; + var maxTileIndex = tileset.firstgid + tileset.total; + + var vertexBuffer = this.vertexBuffer[tilesetIndex]; + var bufferData = this.bufferData[tilesetIndex]; + var vOffset = -1; + var bufferSize = (mapWidth * mapHeight) * pipeline.vertexSize * 6; + + this.vertexCount[tilesetIndex] = 0; + + if (bufferData === null) + { + bufferData = new ArrayBuffer(bufferSize); + + this.bufferData[tilesetIndex] = bufferData; + + this.vertexViewF32[tilesetIndex] = new Float32Array(bufferData); + this.vertexViewU32[tilesetIndex] = new Uint32Array(bufferData); + } + + if (renderOrder === 0) + { + // right-down + + for (row = 0; row < mapHeight; row++) + { + for (col = 0; col < mapWidth; col++) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + else if (renderOrder === 1) + { + // left-down + + for (row = 0; row < mapHeight; row++) + { + for (col = mapWidth - 1; col >= 0; col--) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + else if (renderOrder === 2) + { + // right-up + + for (row = mapHeight - 1; row >= 0; row--) + { + for (col = 0; col < mapWidth; col++) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + else if (renderOrder === 3) + { + // left-up + + for (row = mapHeight - 1; row >= 0; row--) + { + for (col = mapWidth - 1; col >= 0; col--) + { + tile = mapData[row][col]; + + if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) + { + continue; + } + + vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex); + } + } + } + + this.dirty[tilesetIndex] = false; + + if (vertexBuffer === null) + { + vertexBuffer = renderer.createVertexBuffer(bufferData, gl.STATIC_DRAW); + + this.vertexBuffer[tilesetIndex] = vertexBuffer; + } + else + { + renderer.setVertexBuffer(vertexBuffer); + + gl.bufferSubData(gl.ARRAY_BUFFER, 0, bufferData); + } + } + + return this; + }, + + /** + * Add a single tile into the batch. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#batchTile + * @private + * @since 3.12.0 + * + * @param {integer} vOffset - The vertex offset. + * @param {any} tile - The tile being rendered. + * @param {any} tileset - The tileset being used for rendering. + * @param {integer} width - The width of the tileset image in pixels. + * @param {integer} height - The height of the tileset image in pixels. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera the layer is being rendered with. + * @param {integer} tilesetIndex - The tileset index. + * + * @return {integer} The new vOffset value. + */ + batchTile: function (vOffset, tile, tileset, width, height, camera, tilesetIndex) + { + var texCoords = tileset.getTileTextureCoordinates(tile.index); + + if (!texCoords) + { + return vOffset; + } + + var tileWidth = tileset.tileWidth; + var tileHeight = tileset.tileHeight; + + var halfTileWidth = tileWidth / 2; + var halfTileHeight = tileHeight / 2; + + var u0 = texCoords.x / width; + var v0 = texCoords.y / height; + var u1 = (texCoords.x + tileWidth) / width; + var v1 = (texCoords.y + tileHeight) / height; + + var matrix = this._tempMatrix; + + var x = -halfTileWidth; + var y = -halfTileHeight; + + if (tile.flipX) + { + tileWidth *= -1; + x += tileset.tileWidth; + } + + if (tile.flipY) + { + tileHeight *= -1; + y += tileset.tileHeight; + } + + var xw = x + tileWidth; + var yh = y + tileHeight; + + matrix.applyITRS(halfTileWidth + tile.pixelX, halfTileHeight + tile.pixelY, tile.rotation, 1, 1); + + var tint = Utils.getTintAppendFloatAlpha(0xffffff, camera.alpha * this.alpha * tile.alpha); + + var tx0 = matrix.getX(x, y); + var ty0 = matrix.getY(x, y); + + var tx1 = matrix.getX(x, yh); + var ty1 = matrix.getY(x, yh); + + var tx2 = matrix.getX(xw, yh); + var ty2 = matrix.getY(xw, yh); + + var tx3 = matrix.getX(xw, y); + var ty3 = matrix.getY(xw, y); + + if (camera.roundPixels) + { + tx0 = Math.round(tx0); + ty0 = Math.round(ty0); + + tx1 = Math.round(tx1); + ty1 = Math.round(ty1); + + tx2 = Math.round(tx2); + ty2 = Math.round(ty2); + + tx3 = Math.round(tx3); + ty3 = Math.round(ty3); + } + + var vertexViewF32 = this.vertexViewF32[tilesetIndex]; + var vertexViewU32 = this.vertexViewU32[tilesetIndex]; + + vertexViewF32[++vOffset] = tx0; + vertexViewF32[++vOffset] = ty0; + vertexViewF32[++vOffset] = u0; + vertexViewF32[++vOffset] = v0; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx1; + vertexViewF32[++vOffset] = ty1; + vertexViewF32[++vOffset] = u0; + vertexViewF32[++vOffset] = v1; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx2; + vertexViewF32[++vOffset] = ty2; + vertexViewF32[++vOffset] = u1; + vertexViewF32[++vOffset] = v1; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx0; + vertexViewF32[++vOffset] = ty0; + vertexViewF32[++vOffset] = u0; + vertexViewF32[++vOffset] = v0; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx2; + vertexViewF32[++vOffset] = ty2; + vertexViewF32[++vOffset] = u1; + vertexViewF32[++vOffset] = v1; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + vertexViewF32[++vOffset] = tx3; + vertexViewF32[++vOffset] = ty3; + vertexViewF32[++vOffset] = u1; + vertexViewF32[++vOffset] = v0; + vertexViewF32[++vOffset] = 0; + vertexViewU32[++vOffset] = tint; + + this.vertexCount[tilesetIndex] += 6; + + return vOffset; + }, + + /** + * Sets the rendering (draw) order of the tiles in this layer. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setRenderOrder + * @since 3.12.0 + * + * @param {(integer|string)} renderOrder - The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + * + * @return {this} This Tilemap Layer object. + */ + setRenderOrder: function (renderOrder) + { + var orders = [ 'right-down', 'left-down', 'right-up', 'left-up' ]; + + if (typeof renderOrder === 'string') + { + renderOrder = orders.indexOf(renderOrder); + } + + if (renderOrder >= 0 && renderOrder < 4) + { + this._renderOrder = renderOrder; + + for (var i = 0; i < this.tileset.length; i++) + { + this.dirty[i] = true; + } + } + + return this; + }, + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#calculateFacesAt + * @since 3.0.0 + * + * @param {integer} tileX - The x coordinate. + * @param {integer} tileY - The y coordinate. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + calculateFacesAt: function (tileX, tileY) + { + TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); + + return this; + }, + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#calculateFacesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + calculateFacesWithin: function (tileX, tileY, width, height) + { + TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); + + return this; + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#createFromTiles + * @since 3.0.0 + * + * @param {(integer|array)} indexes - The tile index, or array of indexes, to create Sprites from. + * @param {(integer|array)} replacements - The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param {Phaser.Types.GameObjects.Sprite.SpriteConfig} spriteConfig - The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param {Phaser.Scene} [scene=scene the map is within] - The Scene to create the Sprites within. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when determining the world XY + * + * @return {Phaser.GameObjects.Sprite[]} An array of the Sprites that were created. + */ + createFromTiles: function (indexes, replacements, spriteConfig, scene, camera) + { + return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer); + }, + + /** + * Returns the tiles in the given layer that are within the cameras viewport. + * This is used internally. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#cull + * @since 3.0.0 + * + * @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to run the cull check against. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + cull: function (camera) + { + return this.cullCallback(this.layer, camera, this.culledTiles); + }, + + /** + * Canvas only. + * + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setSkipCull + * @since 3.12.0 + * + * @param {boolean} [value=true] - Set to `true` to stop culling tiles. Set to `false` to enable culling again. + * + * @return {this} This Tilemap Layer object. + */ + setSkipCull: function (value) + { + if (value === undefined) { value = true; } + + this.skipCull = value; + + return this; + }, + + /** + * Canvas only. + * + * When a Camera culls the tiles in this layer it does so using its view into the world, building up a + * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size + * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so + * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px + * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCullPadding + * @since 3.12.0 + * + * @param {integer} [paddingX=1] - The amount of extra horizontal tiles to add to the cull check padding. + * @param {integer} [paddingY=1] - The amount of extra vertical tiles to add to the cull check padding. + * + * @return {this} This Tilemap Layer object. + */ + setCullPadding: function (paddingX, paddingY) + { + if (paddingX === undefined) { paddingX = 1; } + if (paddingY === undefined) { paddingY = 1; } + + this.cullPaddingX = paddingX; + this.cullPaddingY = paddingY; + + return this; + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#findByIndex + * @since 3.0.0 + * + * @param {integer} index - The tile index value to search for. + * @param {integer} [skip=0] - The number of times to skip a matching tile before returning. + * @param {boolean} [reverse=false] - If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. + * + * @return {Phaser.Tilemaps.Tile} A Tile object. + */ + findByIndex: function (findIndex, skip, reverse) + { + return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer); + }, + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#findTile + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {?Phaser.Tilemaps.Tile} + */ + findTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#filterTiles + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + filterTiles: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#forEachTile + * @since 3.0.0 + * + * @param {function} callback - The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. + * @param {object} [context] - The context under which the callback should be run. + * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions) + { + TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); + + return this; + }, + + /** + * Gets a tile at the given tile coordinates from the given layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from (given in tile units, not pixels). + * @param {integer} tileY - Y position to get the tile from (given in tile units, not pixels). + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile + * object with an index of -1. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTileAt: function (tileX, tileY, nonNull) + { + return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer); + }, + + /** + * Gets a tile at the given world coordinates from the given layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - X position to get the tile from (given in pixels) + * @param {number} worldY - Y position to get the tile from (given in pixels) + * @param {boolean} [nonNull=false] - If true, function won't return null for empty tiles, but a Tile + * object with an index of -1. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile} The tile at the given coordinates or null if no tile was found or the coordinates + * were invalid. + */ + getTileAtWorldXY: function (worldX, worldY, nonNull, camera) + { + return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithin + * @since 3.0.0 + * + * @param {integer} [tileX=0] - The leftmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [tileY=0] - The topmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be. + * @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithin: function (tileX, tileY, width, height, filteringOptions) + { + return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer); + }, + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithinWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {number} worldY - The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param {number} width - How many tiles wide from the `tileX` index the area will be. + * @param {number} height - How many tiles high from the `tileY` index the area will be. + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when factoring in which tiles to return. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer); + }, + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#getTilesWithinShape + * @since 3.0.0 + * + * @param {(Phaser.Geom.Circle|Phaser.Geom.Line|Phaser.Geom.Rectangle|Phaser.Geom.Triangle)} shape - A shape in world (pixel) coordinates + * @param {Phaser.Types.Tilemaps.FilteringOptions} [filteringOptions] - Optional filters to apply when getting the tiles. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Tilemaps.Tile[]} An array of Tile objects. + */ + getTilesWithinShape: function (shape, filteringOptions, camera) + { + return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#hasTileAt + * @since 3.0.0 + * + * @param {integer} tileX - X position to get the tile from in tile coordinates. + * @param {integer} tileY - Y position to get the tile from in tile coordinates. + * + * @return {boolean} + */ + hasTileAt: function (tileX, tileY) + { + return TilemapComponents.HasTileAt(tileX, tileY, this.layer); + }, + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#hasTileAtWorldXY + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate of the world position. + * @param {number} worldY - The Y coordinate of the world position. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {boolean} + */ + hasTileAtWorldXY: function (worldX, worldY, camera) + { + return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer); + }, + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#renderDebug + * @since 3.0.0 + * + * @param {Phaser.GameObjects.Graphics} graphics - The target Graphics object to draw upon. + * @param {Phaser.Types.Tilemaps.StyleConfig} styleConfig - An object specifying the colors to use for the debug drawing. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + renderDebug: function (graphics, styleConfig) + { + TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); + + return this; + }, + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollision + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * @param {boolean} [updateLayer=true] - If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollision: function (indexes, collides, recalculateFaces, updateLayer) + { + TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer, updateLayer); + + return this; + }, + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionBetween + * @since 3.0.0 + * + * @param {integer} start - The first index of the tile to be set for collision. + * @param {integer} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionBetween: function (start, stop, collides, recalculateFaces) + { + TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionByProperty + * @since 3.0.0 + * + * @param {object} properties - An object with tile properties and corresponding values that should + * be checked. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionByProperty: function (properties, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionByExclusion + * @since 3.0.0 + * + * @param {integer[]} indexes - An array of the tile indexes to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionByExclusion: function (indexes, collides, recalculateFaces) + { + TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setTileIndexCallback + * @since 3.0.0 + * + * @param {(integer|array)} indexes - Either a single tile index, or an array of tile indexes to have a + * collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} callbackContext - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setTileIndexCallback: function (indexes, callback, callbackContext) + { + TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Sets collision on the tiles within a layer by checking each tiles collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tiles collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setCollisionFromCollisionGroup + * @since 3.0.0 + * + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear + * collision. + * @param {boolean} [recalculateFaces=true] - Whether or not to recalculate the tile faces after the + * update. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setCollisionFromCollisionGroup: function (collides, recalculateFaces) + { + TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); + + return this; + }, + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#setTileLocationCallback + * @since 3.0.0 + * + * @param {integer} tileX - The leftmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} tileY - The topmost tile index (in tile coordinates) to use as the origin of the area. + * @param {integer} width - How many tiles wide from the `tileX` index the area will be. + * @param {integer} height - How many tiles tall from the `tileY` index the area will be. + * @param {function} callback - The callback that will be invoked when the tile is collided with. + * @param {object} [callbackContext] - The context under which the callback is called. + * + * @return {Phaser.Tilemaps.StaticTilemapLayer} This Tilemap Layer object. + */ + setTileLocationCallback: function (tileX, tileY, width, height, callback, callbackContext) + { + TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); + + return this; + }, + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldX + * @since 3.0.0 + * + * @param {integer} tileX - The X coordinate, in tile coordinates. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. + * + * @return {number} + */ + tileToWorldX: function (tileX, camera) + { + return this.tilemap.TileToWorldX(tileX, camera, this.layer); + }, + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldY + * @since 3.0.0 + * + * @param {integer} tileY - The Y coordinate, in tile coordinates. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. + * + * @return {number} + */ + tileToWorldY: function (tileY, camera) + { + return this.tilemap.TileToWorldY(tileY, camera, this.layer); + }, + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#tileToWorldXY + * @since 3.0.0 + * + * @param {integer} tileX - The X coordinate, in tile coordinates. + * @param {integer} tileY - The Y coordinate, in tile coordinates. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given, a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the world values from the tile index. + * + * @return {Phaser.Math.Vector2} + */ + tileToWorldXY: function (tileX, tileY, point, camera) + { + return this.tilemap.TileToWorldXY(tileX, tileY, point, camera, this.layer); + }, + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileX + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate, in world pixels. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the + * nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values.] + * + * @return {number} + */ + worldToTileX: function (worldX, snapToFloor, camera) + { + return this.tilemap.WorldToTileX(worldX, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileY + * @since 3.0.0 + * + * @param {number} worldY - The Y coordinate, in world pixels. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the + * nearest integer. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {number} + */ + worldToTileY: function (worldY, snapToFloor, camera) + { + return this.tilemap.WorldToTileY(worldY, snapToFloor, camera, this.layer); + }, + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#worldToTileXY + * @since 3.0.0 + * + * @param {number} worldX - The X coordinate, in world pixels. + * @param {number} worldY - The Y coordinate, in world pixels. + * @param {boolean} [snapToFloor=true] - Whether or not to round the tile coordinate down to the + * nearest integer. + * @param {Phaser.Math.Vector2} [point] - A Vector2 to store the coordinates in. If not given, a new Vector2 is created. + * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - The Camera to use when calculating the tile index from the world values. + * + * @return {Phaser.Math.Vector2} + */ + worldToTileXY: function (worldX, worldY, snapToFloor, point, camera) + { + return this.tilemap.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer); + }, + + /** + * Destroys this StaticTilemapLayer and removes its link to the associated LayerData. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#destroy + * @since 3.0.0 + * + * @param {boolean} [removeFromTilemap=true] - Remove this layer from the parent Tilemap? + */ + destroy: function (removeFromTilemap) + { + if (removeFromTilemap === undefined) { removeFromTilemap = true; } + + if (!this.tilemap) + { + // Abort, we've already been destroyed + return; + } + + // Uninstall this layer only if it is still installed on the LayerData object + if (this.layer.tilemapLayer === this) + { + this.layer.tilemapLayer = undefined; + } + + if (removeFromTilemap) + { + this.tilemap.removeLayer(this); + } + + this.tilemap = undefined; + this.layer = undefined; + this.culledTiles.length = 0; + this.cullCallback = null; + + for (var i = 0; i < this.tileset.length; i++) + { + this.dirty[i] = true; + this.vertexCount[i] = 0; + this.vertexBuffer[i] = null; + this.bufferData[i] = null; + this.vertexViewF32[i] = null; + this.vertexViewU32[i] = null; + } + + this.gidMap = []; + this.tileset = []; + + GameObject.prototype.destroy.call(this); + } + +}); + +module.exports = StaticTilemapLayer; diff --git a/src/tilemaps/staticlayer/StaticTilemapLayerCanvasRenderer.js b/src/tilemaps/staticlayer/StaticTilemapLayerCanvasRenderer.js index 2f2400f09..8bea7cf44 100644 --- a/src/tilemaps/staticlayer/StaticTilemapLayerCanvasRenderer.js +++ b/src/tilemaps/staticlayer/StaticTilemapLayerCanvasRenderer.js @@ -1,128 +1,128 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the Canvas Renderer to the given Camera. - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#renderCanvas - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. - * @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested - */ -var StaticTilemapLayerCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) -{ - src.cull(camera); - - var renderTiles = src.culledTiles; - var tileCount = renderTiles.length; - - if (tileCount === 0) - { - return; - } - - var camMatrix = renderer._tempMatrix1; - var layerMatrix = renderer._tempMatrix2; - var calcMatrix = renderer._tempMatrix3; - - layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); - - camMatrix.copyFrom(camera.matrix); - - var ctx = renderer.currentContext; - var gidMap = src.gidMap; - - ctx.save(); - - if (parentMatrix) - { - // Multiply the camera by the parent matrix - camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); - - // Undo the camera scroll - layerMatrix.e = src.x; - layerMatrix.f = src.y; - - camMatrix.multiply(layerMatrix, calcMatrix); - - calcMatrix.copyToContext(ctx); - } - else - { - // Undo the camera scroll - layerMatrix.e -= camera.scrollX * src.scrollFactorX; - layerMatrix.f -= camera.scrollY * src.scrollFactorY; - - layerMatrix.copyToContext(ctx); - } - - var alpha = camera.alpha * src.alpha; - - if (!renderer.antialias || src.scaleX > 1 || src.scaleY > 1) - { - ctx.imageSmoothingEnabled = false; - } - - for (var i = 0; i < tileCount; i++) - { - var tile = renderTiles[i]; - - var tileset = gidMap[tile.index]; - - if (!tileset) - { - continue; - } - - var image = tileset.image.getSourceImage(); - var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); - - if (tileTexCoords) - { - var tileWidth = tileset.tileWidth; - var tileHeight = tileset.tileHeight; - var halfWidth = tileWidth / 2; - var halfHeight = tileHeight / 2; - - ctx.save(); - - ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); - - if (tile.rotation !== 0) - { - ctx.rotate(tile.rotation); - } - - if (tile.flipX || tile.flipY) - { - ctx.scale((tile.flipX) ? -1 : 1, (tile.flipY) ? -1 : 1); - } - - ctx.globalAlpha = alpha * tile.alpha; - - ctx.drawImage( - image, - tileTexCoords.x, tileTexCoords.y, - tileWidth, tileHeight, - -halfWidth, -halfHeight, - tileWidth, tileHeight - ); - - ctx.restore(); - } - } - - ctx.restore(); -}; - -module.exports = StaticTilemapLayerCanvasRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the Canvas Renderer to the given Camera. + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#renderCanvas + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. + * @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested + */ +var StaticTilemapLayerCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) +{ + src.cull(camera); + + var renderTiles = src.culledTiles; + var tileCount = renderTiles.length; + + if (tileCount === 0) + { + return; + } + + var camMatrix = renderer._tempMatrix1; + var layerMatrix = renderer._tempMatrix2; + var calcMatrix = renderer._tempMatrix3; + + layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); + + camMatrix.copyFrom(camera.matrix); + + var ctx = renderer.currentContext; + var gidMap = src.gidMap; + + ctx.save(); + + if (parentMatrix) + { + // Multiply the camera by the parent matrix + camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); + + // Undo the camera scroll + layerMatrix.e = src.x; + layerMatrix.f = src.y; + + camMatrix.multiply(layerMatrix, calcMatrix); + + calcMatrix.copyToContext(ctx); + } + else + { + // Undo the camera scroll + layerMatrix.e -= camera.scrollX * src.scrollFactorX; + layerMatrix.f -= camera.scrollY * src.scrollFactorY; + + layerMatrix.copyToContext(ctx); + } + + var alpha = camera.alpha * src.alpha; + + if (!renderer.antialias || src.scaleX > 1 || src.scaleY > 1) + { + ctx.imageSmoothingEnabled = false; + } + + for (var i = 0; i < tileCount; i++) + { + var tile = renderTiles[i]; + + var tileset = gidMap[tile.index]; + + if (!tileset) + { + continue; + } + + var image = tileset.image.getSourceImage(); + var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); + + if (tileTexCoords) + { + var tileWidth = tileset.tileWidth; + var tileHeight = tileset.tileHeight; + var halfWidth = tileWidth / 2; + var halfHeight = tileHeight / 2; + + ctx.save(); + + ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); + + if (tile.rotation !== 0) + { + ctx.rotate(tile.rotation); + } + + if (tile.flipX || tile.flipY) + { + ctx.scale((tile.flipX) ? -1 : 1, (tile.flipY) ? -1 : 1); + } + + ctx.globalAlpha = alpha * tile.alpha; + + ctx.drawImage( + image, + tileTexCoords.x, tileTexCoords.y, + tileWidth, tileHeight, + -halfWidth, -halfHeight, + tileWidth, tileHeight + ); + + ctx.restore(); + } + } + + ctx.restore(); +}; + +module.exports = StaticTilemapLayerCanvasRenderer; diff --git a/src/tilemaps/staticlayer/StaticTilemapLayerRender.js b/src/tilemaps/staticlayer/StaticTilemapLayerRender.js index 765475025..cf0f7617b 100644 --- a/src/tilemaps/staticlayer/StaticTilemapLayerRender.js +++ b/src/tilemaps/staticlayer/StaticTilemapLayerRender.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var renderWebGL = require('../../utils/NOOP'); -var renderCanvas = require('../../utils/NOOP'); - -if (typeof WEBGL_RENDERER) -{ - renderWebGL = require('./StaticTilemapLayerWebGLRenderer'); -} - -if (typeof CANVAS_RENDERER) -{ - renderCanvas = require('./StaticTilemapLayerCanvasRenderer'); -} - -module.exports = { - - renderWebGL: renderWebGL, - renderCanvas: renderCanvas - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var renderWebGL = require('../../utils/NOOP'); +var renderCanvas = require('../../utils/NOOP'); + +if (typeof WEBGL_RENDERER) +{ + renderWebGL = require('./StaticTilemapLayerWebGLRenderer'); +} + +if (typeof CANVAS_RENDERER) +{ + renderCanvas = require('./StaticTilemapLayerCanvasRenderer'); +} + +module.exports = { + + renderWebGL: renderWebGL, + renderCanvas: renderCanvas + +}; diff --git a/src/tilemaps/staticlayer/StaticTilemapLayerWebGLRenderer.js b/src/tilemaps/staticlayer/StaticTilemapLayerWebGLRenderer.js index 97ce164bf..bfd05a86b 100644 --- a/src/tilemaps/staticlayer/StaticTilemapLayerWebGLRenderer.js +++ b/src/tilemaps/staticlayer/StaticTilemapLayerWebGLRenderer.js @@ -1,66 +1,66 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Renders this Game Object with the WebGL Renderer to the given Camera. - * - * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. - * This method should not be called directly. It is a utility function of the Render module. - * - * A Static Tilemap Layer renders immediately and does not use any batching. - * - * @method Phaser.Tilemaps.StaticTilemapLayer#renderWebGL - * @since 3.0.0 - * @private - * - * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. - * @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call. - * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. - * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. - */ -var StaticTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera) -{ - var tilesets = src.tileset; - - var pipeline = src.pipeline; - var pipelineVertexBuffer = pipeline.vertexBuffer; - - renderer.setPipeline(pipeline); - - pipeline.modelIdentity(); - pipeline.modelTranslate(src.x - (camera.scrollX * src.scrollFactorX), src.y - (camera.scrollY * src.scrollFactorY), 0); - pipeline.modelScale(src.scaleX, src.scaleY, 1); - pipeline.viewLoad2D(camera.matrix.matrix); - - for (var i = 0; i < tilesets.length; i++) - { - src.upload(camera, i); - - if (src.vertexCount[i] > 0) - { - if (renderer.currentPipeline && renderer.currentPipeline.vertexCount > 0) - { - renderer.flush(); - } - - pipeline.vertexBuffer = src.vertexBuffer[i]; - - renderer.setPipeline(pipeline); - - renderer.setTexture2D(tilesets[i].glTexture, 0); - - renderer.gl.drawArrays(pipeline.topology, 0, src.vertexCount[i]); - } - } - - // Restore the pipeline - pipeline.vertexBuffer = pipelineVertexBuffer; - - pipeline.viewIdentity(); - pipeline.modelIdentity(); -}; - -module.exports = StaticTilemapLayerWebGLRenderer; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Renders this Game Object with the WebGL Renderer to the given Camera. + * + * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. + * This method should not be called directly. It is a utility function of the Render module. + * + * A Static Tilemap Layer renders immediately and does not use any batching. + * + * @method Phaser.Tilemaps.StaticTilemapLayer#renderWebGL + * @since 3.0.0 + * @private + * + * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer. + * @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call. + * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. + * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. + */ +var StaticTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera) +{ + var tilesets = src.tileset; + + var pipeline = src.pipeline; + var pipelineVertexBuffer = pipeline.vertexBuffer; + + renderer.setPipeline(pipeline); + + pipeline.modelIdentity(); + pipeline.modelTranslate(src.x - (camera.scrollX * src.scrollFactorX), src.y - (camera.scrollY * src.scrollFactorY), 0); + pipeline.modelScale(src.scaleX, src.scaleY, 1); + pipeline.viewLoad2D(camera.matrix.matrix); + + for (var i = 0; i < tilesets.length; i++) + { + src.upload(camera, i); + + if (src.vertexCount[i] > 0) + { + if (renderer.currentPipeline && renderer.currentPipeline.vertexCount > 0) + { + renderer.flush(); + } + + pipeline.vertexBuffer = src.vertexBuffer[i]; + + renderer.setPipeline(pipeline); + + renderer.setTexture2D(tilesets[i].glTexture, 0); + + renderer.gl.drawArrays(pipeline.topology, 0, src.vertexCount[i]); + } + } + + // Restore the pipeline + pipeline.vertexBuffer = pipelineVertexBuffer; + + pipeline.viewIdentity(); + pipeline.modelIdentity(); +}; + +module.exports = StaticTilemapLayerWebGLRenderer; diff --git a/src/tilemaps/typedefs/index.js b/src/tilemaps/typedefs/index.js index 35db8d257..0d3eb9bbc 100644 --- a/src/tilemaps/typedefs/index.js +++ b/src/tilemaps/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Tilemaps - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Tilemaps + */ diff --git a/src/time/Clock.js b/src/time/Clock.js index 38613e440..8df285e5b 100644 --- a/src/time/Clock.js +++ b/src/time/Clock.js @@ -1,400 +1,400 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); -var TimerEvent = require('./TimerEvent'); - -/** - * @classdesc - * The Clock is a Scene plugin which creates and updates Timer Events for its Scene. - * - * @class Clock - * @memberof Phaser.Time - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene which owns this Clock. - */ -var Clock = new Class({ - - initialize: - - function Clock (scene) - { - /** - * The Scene which owns this Clock. - * - * @name Phaser.Time.Clock#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The Scene Systems object of the Scene which owns this Clock. - * - * @name Phaser.Time.Clock#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * The current time of the Clock, in milliseconds. - * - * If accessed externally, this is equivalent to the `time` parameter normally passed to a Scene's `update` method. - * - * @name Phaser.Time.Clock#now - * @type {number} - * @since 3.0.0 - */ - this.now = 0; - - // Scale the delta time coming into the Clock by this factor - // which then influences anything using this Clock for calculations, like TimerEvents - - /** - * The scale of the Clock's time delta. - * - * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Clock and anything which uses it, such as its Timer Events. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing the Clock. - * - * @name Phaser.Time.Clock#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * Whether the Clock is paused (`true`) or active (`false`). - * - * When paused, the Clock will not update any of its Timer Events, thus freezing time. - * - * @name Phaser.Time.Clock#paused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.paused = false; - - /** - * An array of all Timer Events whose delays haven't expired - these are actively updating Timer Events. - * - * @name Phaser.Time.Clock#_active - * @type {Phaser.Time.TimerEvent[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._active = []; - - /** - * An array of all Timer Events which will be added to the Clock at the start of the frame. - * - * @name Phaser.Time.Clock#_pendingInsertion - * @type {Phaser.Time.TimerEvent[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._pendingInsertion = []; - - /** - * An array of all Timer Events which will be removed from the Clock at the start of the frame. - * - * @name Phaser.Time.Clock#_pendingRemoval - * @type {Phaser.Time.TimerEvent[]} - * @private - * @default [] - * @since 3.0.0 - */ - this._pendingRemoval = []; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Time.Clock#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - // Sync with the TimeStep - this.now = this.systems.game.loop.time; - - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Time.Clock#start - * @private - * @since 3.5.0 - */ - start: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); - eventEmitter.on(SceneEvents.UPDATE, this.update, this); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * Creates a Timer Event and adds it to the Clock at the start of the frame. - * - * @method Phaser.Time.Clock#addEvent - * @since 3.0.0 - * - * @param {Phaser.Types.Time.TimerEventConfig} config - The configuration for the Timer Event. - * - * @return {Phaser.Time.TimerEvent} The Timer Event which was created. - */ - addEvent: function (config) - { - var event = new TimerEvent(config); - - this._pendingInsertion.push(event); - - return event; - }, - - /** - * Creates a Timer Event and adds it to the Clock at the start of the frame. - * - * This is a shortcut for {@link #addEvent} which can be shorter and is compatible with the syntax of the GreenSock Animation Platform (GSAP). - * - * @method Phaser.Time.Clock#delayedCall - * @since 3.0.0 - * - * @param {number} delay - The delay of the function call, in milliseconds. - * @param {function} callback - The function to call after the delay expires. - * @param {Array.<*>} [args] - The arguments to call the function with. - * @param {*} [callbackScope] - The scope (`this` object) to call the function with. - * - * @return {Phaser.Time.TimerEvent} The Timer Event which was created. - */ - delayedCall: function (delay, callback, args, callbackScope) - { - return this.addEvent({ delay: delay, callback: callback, args: args, callbackScope: callbackScope }); - }, - - /** - * Clears and recreates the array of pending Timer Events. - * - * @method Phaser.Time.Clock#clearPendingEvents - * @since 3.0.0 - * - * @return {Phaser.Time.Clock} This Clock object. - */ - clearPendingEvents: function () - { - this._pendingInsertion = []; - - return this; - }, - - /** - * Schedules all active Timer Events for removal at the start of the frame. - * - * @method Phaser.Time.Clock#removeAllEvents - * @since 3.0.0 - * - * @return {Phaser.Time.Clock} This Clock object. - */ - removeAllEvents: function () - { - this._pendingRemoval = this._pendingRemoval.concat(this._active); - - return this; - }, - - /** - * Updates the arrays of active and pending Timer Events. Called at the start of the frame. - * - * @method Phaser.Time.Clock#preUpdate - * @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. - */ - preUpdate: function () - { - var toRemove = this._pendingRemoval.length; - var toInsert = this._pendingInsertion.length; - - if (toRemove === 0 && toInsert === 0) - { - // Quick bail - return; - } - - var i; - var event; - - // Delete old events - for (i = 0; i < toRemove; i++) - { - event = this._pendingRemoval[i]; - - var index = this._active.indexOf(event); - - if (index > -1) - { - this._active.splice(index, 1); - } - - // Pool them? - event.destroy(); - } - - for (i = 0; i < toInsert; i++) - { - event = this._pendingInsertion[i]; - - this._active.push(event); - } - - // Clear the lists - this._pendingRemoval.length = 0; - this._pendingInsertion.length = 0; - }, - - /** - * 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. - */ - update: function (time, delta) - { - this.now = time; - - if (this.paused) - { - return; - } - - delta *= this.timeScale; - - for (var i = 0; i < this._active.length; i++) - { - var event = this._active[i]; - - if (event.paused) - { - continue; - } - - // Use delta time to increase elapsed. - // Avoids needing to adjust for pause / resume. - // Automatically smoothed by TimeStep class. - // In testing accurate to +- 1ms! - event.elapsed += delta * event.timeScale; - - if (event.elapsed >= event.delay) - { - var remainder = event.elapsed - event.delay; - - // Limit it, in case it's checked in the callback - event.elapsed = event.delay; - - // Process the event - if (!event.hasDispatched && event.callback) - { - event.hasDispatched = true; - event.callback.apply(event.callbackScope, event.args); - } - - if (event.repeatCount > 0) - { - event.repeatCount--; - - event.elapsed = remainder; - event.hasDispatched = false; - } - else - { - this._pendingRemoval.push(event); - } - } - } - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Time.Clock#shutdown - * @private - * @since 3.0.0 - */ - shutdown: function () - { - var i; - - for (i = 0; i < this._pendingInsertion.length; i++) - { - this._pendingInsertion[i].destroy(); - } - - for (i = 0; i < this._active.length; i++) - { - this._active[i].destroy(); - } - - for (i = 0; i < this._pendingRemoval.length; i++) - { - this._pendingRemoval[i].destroy(); - } - - this._active.length = 0; - this._pendingRemoval.length = 0; - this._pendingInsertion.length = 0; - - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); - eventEmitter.off(SceneEvents.UPDATE, this.update, this); - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Time.Clock#destroy - * @private - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('Clock', Clock, 'time'); - -module.exports = Clock; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); +var TimerEvent = require('./TimerEvent'); + +/** + * @classdesc + * The Clock is a Scene plugin which creates and updates Timer Events for its Scene. + * + * @class Clock + * @memberof Phaser.Time + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which owns this Clock. + */ +var Clock = new Class({ + + initialize: + + function Clock (scene) + { + /** + * The Scene which owns this Clock. + * + * @name Phaser.Time.Clock#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Scene Systems object of the Scene which owns this Clock. + * + * @name Phaser.Time.Clock#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The current time of the Clock, in milliseconds. + * + * If accessed externally, this is equivalent to the `time` parameter normally passed to a Scene's `update` method. + * + * @name Phaser.Time.Clock#now + * @type {number} + * @since 3.0.0 + */ + this.now = 0; + + // Scale the delta time coming into the Clock by this factor + // which then influences anything using this Clock for calculations, like TimerEvents + + /** + * The scale of the Clock's time delta. + * + * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Clock and anything which uses it, such as its Timer Events. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing the Clock. + * + * @name Phaser.Time.Clock#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Whether the Clock is paused (`true`) or active (`false`). + * + * When paused, the Clock will not update any of its Timer Events, thus freezing time. + * + * @name Phaser.Time.Clock#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * An array of all Timer Events whose delays haven't expired - these are actively updating Timer Events. + * + * @name Phaser.Time.Clock#_active + * @type {Phaser.Time.TimerEvent[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._active = []; + + /** + * An array of all Timer Events which will be added to the Clock at the start of the frame. + * + * @name Phaser.Time.Clock#_pendingInsertion + * @type {Phaser.Time.TimerEvent[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingInsertion = []; + + /** + * An array of all Timer Events which will be removed from the Clock at the start of the frame. + * + * @name Phaser.Time.Clock#_pendingRemoval + * @type {Phaser.Time.TimerEvent[]} + * @private + * @default [] + * @since 3.0.0 + */ + this._pendingRemoval = []; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Time.Clock#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + // Sync with the TimeStep + this.now = this.systems.game.loop.time; + + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Time.Clock#start + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.on(SceneEvents.UPDATE, this.update, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * Creates a Timer Event and adds it to the Clock at the start of the frame. + * + * @method Phaser.Time.Clock#addEvent + * @since 3.0.0 + * + * @param {Phaser.Types.Time.TimerEventConfig} config - The configuration for the Timer Event. + * + * @return {Phaser.Time.TimerEvent} The Timer Event which was created. + */ + addEvent: function (config) + { + var event = new TimerEvent(config); + + this._pendingInsertion.push(event); + + return event; + }, + + /** + * Creates a Timer Event and adds it to the Clock at the start of the frame. + * + * This is a shortcut for {@link #addEvent} which can be shorter and is compatible with the syntax of the GreenSock Animation Platform (GSAP). + * + * @method Phaser.Time.Clock#delayedCall + * @since 3.0.0 + * + * @param {number} delay - The delay of the function call, in milliseconds. + * @param {function} callback - The function to call after the delay expires. + * @param {Array.<*>} [args] - The arguments to call the function with. + * @param {*} [callbackScope] - The scope (`this` object) to call the function with. + * + * @return {Phaser.Time.TimerEvent} The Timer Event which was created. + */ + delayedCall: function (delay, callback, args, callbackScope) + { + return this.addEvent({ delay: delay, callback: callback, args: args, callbackScope: callbackScope }); + }, + + /** + * Clears and recreates the array of pending Timer Events. + * + * @method Phaser.Time.Clock#clearPendingEvents + * @since 3.0.0 + * + * @return {Phaser.Time.Clock} This Clock object. + */ + clearPendingEvents: function () + { + this._pendingInsertion = []; + + return this; + }, + + /** + * Schedules all active Timer Events for removal at the start of the frame. + * + * @method Phaser.Time.Clock#removeAllEvents + * @since 3.0.0 + * + * @return {Phaser.Time.Clock} This Clock object. + */ + removeAllEvents: function () + { + this._pendingRemoval = this._pendingRemoval.concat(this._active); + + return this; + }, + + /** + * Updates the arrays of active and pending Timer Events. Called at the start of the frame. + * + * @method Phaser.Time.Clock#preUpdate + * @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. + */ + preUpdate: function () + { + var toRemove = this._pendingRemoval.length; + var toInsert = this._pendingInsertion.length; + + if (toRemove === 0 && toInsert === 0) + { + // Quick bail + return; + } + + var i; + var event; + + // Delete old events + for (i = 0; i < toRemove; i++) + { + event = this._pendingRemoval[i]; + + var index = this._active.indexOf(event); + + if (index > -1) + { + this._active.splice(index, 1); + } + + // Pool them? + event.destroy(); + } + + for (i = 0; i < toInsert; i++) + { + event = this._pendingInsertion[i]; + + this._active.push(event); + } + + // Clear the lists + this._pendingRemoval.length = 0; + this._pendingInsertion.length = 0; + }, + + /** + * 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. + */ + update: function (time, delta) + { + this.now = time; + + if (this.paused) + { + return; + } + + delta *= this.timeScale; + + for (var i = 0; i < this._active.length; i++) + { + var event = this._active[i]; + + if (event.paused) + { + continue; + } + + // Use delta time to increase elapsed. + // Avoids needing to adjust for pause / resume. + // Automatically smoothed by TimeStep class. + // In testing accurate to +- 1ms! + event.elapsed += delta * event.timeScale; + + if (event.elapsed >= event.delay) + { + var remainder = event.elapsed - event.delay; + + // Limit it, in case it's checked in the callback + event.elapsed = event.delay; + + // Process the event + if (!event.hasDispatched && event.callback) + { + event.hasDispatched = true; + event.callback.apply(event.callbackScope, event.args); + } + + if (event.repeatCount > 0) + { + event.repeatCount--; + + event.elapsed = remainder; + event.hasDispatched = false; + } + else + { + this._pendingRemoval.push(event); + } + } + } + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Time.Clock#shutdown + * @private + * @since 3.0.0 + */ + shutdown: function () + { + var i; + + for (i = 0; i < this._pendingInsertion.length; i++) + { + this._pendingInsertion[i].destroy(); + } + + for (i = 0; i < this._active.length; i++) + { + this._active[i].destroy(); + } + + for (i = 0; i < this._pendingRemoval.length; i++) + { + this._pendingRemoval[i].destroy(); + } + + this._active.length = 0; + this._pendingRemoval.length = 0; + this._pendingInsertion.length = 0; + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.off(SceneEvents.UPDATE, this.update, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Time.Clock#destroy + * @private + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('Clock', Clock, 'time'); + +module.exports = Clock; diff --git a/src/time/TimerEvent.js b/src/time/TimerEvent.js index 5e47d649b..445d9c8b2 100644 --- a/src/time/TimerEvent.js +++ b/src/time/TimerEvent.js @@ -1,307 +1,307 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var GetFastValue = require('../utils/object/GetFastValue'); - -/** - * @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. - */ -var TimerEvent = new Class({ - - initialize: - - function TimerEvent (config) - { - /** - * The delay in ms at which this TimerEvent fires. - * - * @name Phaser.Time.TimerEvent#delay - * @type {number} - * @default 0 - * @readonly - * @since 3.0.0 - */ - this.delay = 0; - - /** - * The total number of times this TimerEvent will repeat before finishing. - * - * @name Phaser.Time.TimerEvent#repeat - * @type {number} - * @default 0 - * @readonly - * @since 3.0.0 - */ - this.repeat = 0; - - /** - * If repeating this contains the current repeat count. - * - * @name Phaser.Time.TimerEvent#repeatCount - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.repeatCount = 0; - - /** - * True if this TimerEvent loops, otherwise false. - * - * @name Phaser.Time.TimerEvent#loop - * @type {boolean} - * @default false - * @readonly - * @since 3.0.0 - */ - this.loop = false; - - /** - * The callback that will be called when the TimerEvent occurs. - * - * @name Phaser.Time.TimerEvent#callback - * @type {function} - * @since 3.0.0 - */ - this.callback; - - /** - * The scope in which the callback will be called. - * - * @name Phaser.Time.TimerEvent#callbackScope - * @type {object} - * @since 3.0.0 - */ - this.callbackScope; - - /** - * Additional arguments to be passed to the callback. - * - * @name Phaser.Time.TimerEvent#args - * @type {array} - * @since 3.0.0 - */ - this.args; - - /** - * Scale the time causing this TimerEvent to update. - * - * @name Phaser.Time.TimerEvent#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * Start this many MS into the elapsed (useful if you want a long duration with repeat, but for the first loop to fire quickly) - * - * @name Phaser.Time.TimerEvent#startAt - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.startAt = 0; - - /** - * The time in milliseconds which has elapsed since the Timer Event's creation. - * - * This value is local for the Timer Event and is relative to its Clock. As such, it's influenced by the Clock's time scale and paused state, the Timer Event's initial {@link #startAt} property, and the Timer Event's {@link #timeScale} and {@link #paused} state. - * - * @name Phaser.Time.TimerEvent#elapsed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.elapsed = 0; - - /** - * Whether or not this timer is paused. - * - * @name Phaser.Time.TimerEvent#paused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.paused = false; - - /** - * Whether the Timer Event's function has been called. - * - * When the Timer Event fires, this property will be set to `true` before the callback function is invoked and will be reset immediately afterward if the Timer Event should repeat. The value of this property does not directly influence whether the Timer Event will be removed from its Clock, but can prevent it from firing. - * - * @name Phaser.Time.TimerEvent#hasDispatched - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.hasDispatched = false; - - this.reset(config); - }, - - /** - * Completely reinitializes the Timer Event, regardless of its current state, according to a configuration object. - * - * @method Phaser.Time.TimerEvent#reset - * @since 3.0.0 - * - * @param {Phaser.Types.Time.TimerEventConfig} config - The new state for the Timer Event. - * - * @return {Phaser.Time.TimerEvent} This TimerEvent object. - */ - reset: function (config) - { - this.delay = GetFastValue(config, 'delay', 0); - - // Can also be set to -1 for an infinite loop (same as setting loop: true) - this.repeat = GetFastValue(config, 'repeat', 0); - - this.loop = GetFastValue(config, 'loop', false); - - this.callback = GetFastValue(config, 'callback', undefined); - - this.callbackScope = GetFastValue(config, 'callbackScope', this.callback); - - this.args = GetFastValue(config, 'args', []); - - this.timeScale = GetFastValue(config, 'timeScale', 1); - - this.startAt = GetFastValue(config, 'startAt', 0); - - this.paused = GetFastValue(config, 'paused', false); - - this.elapsed = this.startAt; - this.hasDispatched = false; - this.repeatCount = (this.repeat === -1 || this.loop) ? 999999999999 : this.repeat; - - return this; - }, - - /** - * Gets the progress of the current iteration, not factoring in repeats. - * - * @method Phaser.Time.TimerEvent#getProgress - * @since 3.0.0 - * - * @return {number} A number between 0 and 1 representing the current progress. - */ - getProgress: function () - { - return (this.elapsed / this.delay); - }, - - /** - * Gets the progress of the timer overall, factoring in repeats. - * - * @method Phaser.Time.TimerEvent#getOverallProgress - * @since 3.0.0 - * - * @return {number} The overall progress of the Timer Event, between 0 and 1. - */ - getOverallProgress: function () - { - if (this.repeat > 0) - { - var totalDuration = this.delay + (this.delay * this.repeat); - var totalElapsed = this.elapsed + (this.delay * (this.repeat - this.repeatCount)); - - return (totalElapsed / totalDuration); - } - else - { - return this.getProgress(); - } - }, - - /** - * Returns the number of times this Timer Event will repeat before finishing. - * - * This should not be confused with the number of times the Timer Event will fire before finishing. A return value of 0 doesn't indicate that the Timer Event has finished running - it indicates that it will not repeat after the next time it fires. - * - * @method Phaser.Time.TimerEvent#getRepeatCount - * @since 3.0.0 - * - * @return {number} How many times the Timer Event will repeat. - */ - getRepeatCount: function () - { - return this.repeatCount; - }, - - /** - * Returns the local elapsed time for the current iteration of the Timer Event. - * - * @method Phaser.Time.TimerEvent#getElapsed - * @since 3.0.0 - * - * @return {number} The local elapsed time in milliseconds. - */ - getElapsed: function () - { - return this.elapsed; - }, - - /** - * Returns the local elapsed time for the current iteration of the Timer Event in seconds. - * - * @method Phaser.Time.TimerEvent#getElapsedSeconds - * @since 3.0.0 - * - * @return {number} The local elapsed time in seconds. - */ - getElapsedSeconds: function () - { - return this.elapsed * 0.001; - }, - - /** - * Forces the Timer Event to immediately expire, thus scheduling its removal in the next frame. - * - * @method Phaser.Time.TimerEvent#remove - * @since 3.0.0 - * - * @param {boolean} [dispatchCallback=false] - If `true`, the function of the Timer Event will be called before its removal. - */ - remove: function (dispatchCallback) - { - if (dispatchCallback === undefined) { dispatchCallback = false; } - - this.elapsed = this.delay; - - this.hasDispatched = !dispatchCallback; - - this.repeatCount = 0; - }, - - /** - * Destroys all object references in the Timer Event, i.e. its callback, scope, and arguments. - * - * Normally, this method is only called by the Clock when it shuts down. As such, it doesn't stop the Timer Event. If called manually, the Timer Event will still be updated by the Clock, but it won't do anything when it fires. - * - * @method Phaser.Time.TimerEvent#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.callback = undefined; - this.callbackScope = undefined; - this.args = []; - } - -}); - -module.exports = TimerEvent; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var GetFastValue = require('../utils/object/GetFastValue'); + +/** + * @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. + */ +var TimerEvent = new Class({ + + initialize: + + function TimerEvent (config) + { + /** + * The delay in ms at which this TimerEvent fires. + * + * @name Phaser.Time.TimerEvent#delay + * @type {number} + * @default 0 + * @readonly + * @since 3.0.0 + */ + this.delay = 0; + + /** + * The total number of times this TimerEvent will repeat before finishing. + * + * @name Phaser.Time.TimerEvent#repeat + * @type {number} + * @default 0 + * @readonly + * @since 3.0.0 + */ + this.repeat = 0; + + /** + * If repeating this contains the current repeat count. + * + * @name Phaser.Time.TimerEvent#repeatCount + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.repeatCount = 0; + + /** + * True if this TimerEvent loops, otherwise false. + * + * @name Phaser.Time.TimerEvent#loop + * @type {boolean} + * @default false + * @readonly + * @since 3.0.0 + */ + this.loop = false; + + /** + * The callback that will be called when the TimerEvent occurs. + * + * @name Phaser.Time.TimerEvent#callback + * @type {function} + * @since 3.0.0 + */ + this.callback; + + /** + * The scope in which the callback will be called. + * + * @name Phaser.Time.TimerEvent#callbackScope + * @type {object} + * @since 3.0.0 + */ + this.callbackScope; + + /** + * Additional arguments to be passed to the callback. + * + * @name Phaser.Time.TimerEvent#args + * @type {array} + * @since 3.0.0 + */ + this.args; + + /** + * Scale the time causing this TimerEvent to update. + * + * @name Phaser.Time.TimerEvent#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Start this many MS into the elapsed (useful if you want a long duration with repeat, but for the first loop to fire quickly) + * + * @name Phaser.Time.TimerEvent#startAt + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.startAt = 0; + + /** + * The time in milliseconds which has elapsed since the Timer Event's creation. + * + * This value is local for the Timer Event and is relative to its Clock. As such, it's influenced by the Clock's time scale and paused state, the Timer Event's initial {@link #startAt} property, and the Timer Event's {@link #timeScale} and {@link #paused} state. + * + * @name Phaser.Time.TimerEvent#elapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.elapsed = 0; + + /** + * Whether or not this timer is paused. + * + * @name Phaser.Time.TimerEvent#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * Whether the Timer Event's function has been called. + * + * When the Timer Event fires, this property will be set to `true` before the callback function is invoked and will be reset immediately afterward if the Timer Event should repeat. The value of this property does not directly influence whether the Timer Event will be removed from its Clock, but can prevent it from firing. + * + * @name Phaser.Time.TimerEvent#hasDispatched + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.hasDispatched = false; + + this.reset(config); + }, + + /** + * Completely reinitializes the Timer Event, regardless of its current state, according to a configuration object. + * + * @method Phaser.Time.TimerEvent#reset + * @since 3.0.0 + * + * @param {Phaser.Types.Time.TimerEventConfig} config - The new state for the Timer Event. + * + * @return {Phaser.Time.TimerEvent} This TimerEvent object. + */ + reset: function (config) + { + this.delay = GetFastValue(config, 'delay', 0); + + // Can also be set to -1 for an infinite loop (same as setting loop: true) + this.repeat = GetFastValue(config, 'repeat', 0); + + this.loop = GetFastValue(config, 'loop', false); + + this.callback = GetFastValue(config, 'callback', undefined); + + this.callbackScope = GetFastValue(config, 'callbackScope', this.callback); + + this.args = GetFastValue(config, 'args', []); + + this.timeScale = GetFastValue(config, 'timeScale', 1); + + this.startAt = GetFastValue(config, 'startAt', 0); + + this.paused = GetFastValue(config, 'paused', false); + + this.elapsed = this.startAt; + this.hasDispatched = false; + this.repeatCount = (this.repeat === -1 || this.loop) ? 999999999999 : this.repeat; + + return this; + }, + + /** + * Gets the progress of the current iteration, not factoring in repeats. + * + * @method Phaser.Time.TimerEvent#getProgress + * @since 3.0.0 + * + * @return {number} A number between 0 and 1 representing the current progress. + */ + getProgress: function () + { + return (this.elapsed / this.delay); + }, + + /** + * Gets the progress of the timer overall, factoring in repeats. + * + * @method Phaser.Time.TimerEvent#getOverallProgress + * @since 3.0.0 + * + * @return {number} The overall progress of the Timer Event, between 0 and 1. + */ + getOverallProgress: function () + { + if (this.repeat > 0) + { + var totalDuration = this.delay + (this.delay * this.repeat); + var totalElapsed = this.elapsed + (this.delay * (this.repeat - this.repeatCount)); + + return (totalElapsed / totalDuration); + } + else + { + return this.getProgress(); + } + }, + + /** + * Returns the number of times this Timer Event will repeat before finishing. + * + * This should not be confused with the number of times the Timer Event will fire before finishing. A return value of 0 doesn't indicate that the Timer Event has finished running - it indicates that it will not repeat after the next time it fires. + * + * @method Phaser.Time.TimerEvent#getRepeatCount + * @since 3.0.0 + * + * @return {number} How many times the Timer Event will repeat. + */ + getRepeatCount: function () + { + return this.repeatCount; + }, + + /** + * Returns the local elapsed time for the current iteration of the Timer Event. + * + * @method Phaser.Time.TimerEvent#getElapsed + * @since 3.0.0 + * + * @return {number} The local elapsed time in milliseconds. + */ + getElapsed: function () + { + return this.elapsed; + }, + + /** + * Returns the local elapsed time for the current iteration of the Timer Event in seconds. + * + * @method Phaser.Time.TimerEvent#getElapsedSeconds + * @since 3.0.0 + * + * @return {number} The local elapsed time in seconds. + */ + getElapsedSeconds: function () + { + return this.elapsed * 0.001; + }, + + /** + * Forces the Timer Event to immediately expire, thus scheduling its removal in the next frame. + * + * @method Phaser.Time.TimerEvent#remove + * @since 3.0.0 + * + * @param {boolean} [dispatchCallback=false] - If `true`, the function of the Timer Event will be called before its removal. + */ + remove: function (dispatchCallback) + { + if (dispatchCallback === undefined) { dispatchCallback = false; } + + this.elapsed = this.delay; + + this.hasDispatched = !dispatchCallback; + + this.repeatCount = 0; + }, + + /** + * Destroys all object references in the Timer Event, i.e. its callback, scope, and arguments. + * + * Normally, this method is only called by the Clock when it shuts down. As such, it doesn't stop the Timer Event. If called manually, the Timer Event will still be updated by the Clock, but it won't do anything when it fires. + * + * @method Phaser.Time.TimerEvent#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.callback = undefined; + this.callbackScope = undefined; + this.args = []; + } + +}); + +module.exports = TimerEvent; diff --git a/src/time/index.js b/src/time/index.js index 82569d1b4..bf67db848 100644 --- a/src/time/index.js +++ b/src/time/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Time - */ - -module.exports = { - - Clock: require('./Clock'), - TimerEvent: require('./TimerEvent') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Time + */ + +module.exports = { + + Clock: require('./Clock'), + TimerEvent: require('./TimerEvent') + +}; diff --git a/src/time/typedefs/index.js b/src/time/typedefs/index.js index 5e7502821..ccfd377bf 100644 --- a/src/time/typedefs/index.js +++ b/src/time/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Time - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Time + */ diff --git a/src/tweens/Timeline.js b/src/tweens/Timeline.js index 977849a49..e7736fa7a 100644 --- a/src/tweens/Timeline.js +++ b/src/tweens/Timeline.js @@ -1,899 +1,899 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('./events'); -var TweenBuilder = require('./builders/TweenBuilder'); -var TWEEN_CONST = require('./tween/const'); - -/** - * @classdesc - * A Timeline combines multiple Tweens into one. Its overall behavior is otherwise similar to a single Tween. - * - * The Timeline updates all of its Tweens simultaneously. Its methods allow you to easily build a sequence - * of Tweens (each one starting after the previous one) or run multiple Tweens at once during given parts of the Timeline. - * - * @class Timeline - * @memberof Phaser.Tweens - * @extends Phaser.Events.EventEmitter - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Tweens.TweenManager} manager - The Tween Manager which owns this Timeline. - */ -var Timeline = new Class({ - - Extends: EventEmitter, - - initialize: - - function Timeline (manager) - { - EventEmitter.call(this); - - /** - * The Tween Manager which owns this Timeline. - * - * @name Phaser.Tweens.Timeline#manager - * @type {Phaser.Tweens.TweenManager} - * @since 3.0.0 - */ - this.manager = manager; - - /** - * A constant value which allows this Timeline to be easily identified as one. - * - * @name Phaser.Tweens.Timeline#isTimeline - * @type {boolean} - * @default true - * @since 3.0.0 - */ - this.isTimeline = true; - - /** - * An array of Tween objects, each containing a unique property and target being tweened. - * - * @name Phaser.Tweens.Timeline#data - * @type {array} - * @default [] - * @since 3.0.0 - */ - this.data = []; - - /** - * The cached size of the data array. - * - * @name Phaser.Tweens.Timeline#totalData - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalData = 0; - - /** - * If true then duration, delay, etc values are all frame totals, rather than ms. - * - * @name Phaser.Tweens.Timeline#useFrames - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.useFrames = false; - - /** - * Scales the time applied to this Timeline. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. - * Value isn't used when calculating total duration of the Timeline, it's a run-time delta adjustment only. - * - * @name Phaser.Tweens.Timeline#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * Loop this Timeline? Can be -1 for an infinite loop, or an integer. - * When enabled it will play through ALL Tweens again (use Tween.repeat to loop a single tween) - * - * @name Phaser.Tweens.Timeline#loop - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.loop = 0; - - /** - * Time in ms/frames before this Timeline loops. - * - * @name Phaser.Tweens.Timeline#loopDelay - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.loopDelay = 0; - - /** - * How many loops are left to run? - * - * @name Phaser.Tweens.Timeline#loopCounter - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.loopCounter = 0; - - /** - * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = true (as it never completes) - * - * @name Phaser.Tweens.Timeline#completeDelay - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.completeDelay = 0; - - /** - * Countdown timer value, as used by `loopDelay` and `completeDelay`. - * - * @name Phaser.Tweens.Timeline#countdown - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.countdown = 0; - - /** - * The current state of the Timeline. - * - * @name Phaser.Tweens.Timeline#state - * @type {integer} - * @since 3.0.0 - */ - this.state = TWEEN_CONST.PENDING_ADD; - - /** - * The state of the Timeline when it was paused (used by Resume) - * - * @name Phaser.Tweens.Timeline#_pausedState - * @type {integer} - * @private - * @since 3.0.0 - */ - this._pausedState = TWEEN_CONST.PENDING_ADD; - - /** - * Does the Timeline start off paused? (if so it needs to be started with Timeline.play) - * - * @name Phaser.Tweens.Timeline#paused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.paused = false; - - /** - * Elapsed time in ms/frames of this run through of the Timeline. - * - * @name Phaser.Tweens.Timeline#elapsed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.elapsed = 0; - - /** - * Total elapsed time in ms/frames of the entire Timeline, including looping. - * - * @name Phaser.Tweens.Timeline#totalElapsed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalElapsed = 0; - - /** - * Time in ms/frames for the whole Timeline to play through once, excluding loop amounts and loop delays. - * - * @name Phaser.Tweens.Timeline#duration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.duration = 0; - - /** - * Value between 0 and 1. The amount of progress through the Timeline, _excluding loops_. - * - * @name Phaser.Tweens.Timeline#progress - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.progress = 0; - - /** - * Time in ms/frames for all Tweens in this Timeline to complete (including looping) - * - * @name Phaser.Tweens.Timeline#totalDuration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalDuration = 0; - - /** - * Value between 0 and 1. The amount through the entire Timeline, including looping. - * - * @name Phaser.Tweens.Timeline#totalProgress - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalProgress = 0; - - /** - * An object containing the different Tween callback functions. - * - * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. - * - * `onComplete` When the Timeline finishes playback fully or `Timeline.stop` is called. Never invoked if timeline is set to repeat infinitely. - * `onLoop` When a Timeline loops. - * `onStart` When the Timeline starts playing. - * `onUpdate` When a Timeline updates a child Tween. - * `onYoyo` When a Timeline starts a yoyo. - * - * @name Phaser.Tweens.Timeline#callbacks - * @type {object} - * @since 3.0.0 - */ - this.callbacks = { - onComplete: null, - onLoop: null, - onStart: null, - onUpdate: null, - onYoyo: null - }; - - /** - * The context in which all callbacks are invoked. - * - * @name Phaser.Tweens.Timeline#callbackScope - * @type {any} - * @since 3.0.0 - */ - this.callbackScope; - }, - - /** - * Internal method that will emit a Timeline based Event and invoke the given callback. - * - * @method Phaser.Tweens.Timeline#dispatchTimelineEvent - * @since 3.19.0 - * - * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. - * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. - */ - dispatchTimelineEvent: function (event, callback) - { - this.emit(event, this); - - if (callback) - { - callback.func.apply(callback.scope, callback.params); - } - }, - - /** - * Sets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. - * A value of 0.5 runs 50% slower, and so on. - * - * The value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. - * - * @method Phaser.Tweens.Timeline#setTimeScale - * @since 3.0.0 - * - * @param {number} value - The time scale value to set. - * - * @return {this} This Timeline object. - */ - setTimeScale: function (value) - { - this.timeScale = value; - - return this; - }, - - /** - * Gets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. - * A value of 0.5 runs 50% slower, and so on. - * - * @method Phaser.Tweens.Timeline#getTimeScale - * @since 3.0.0 - * - * @return {number} The value of the time scale applied to this Timeline. - */ - getTimeScale: function () - { - return this.timeScale; - }, - - /** - * Check whether or not the Timeline is playing. - * - * @method Phaser.Tweens.Timeline#isPlaying - * @since 3.0.0 - * - * @return {boolean} `true` if this Timeline is active, otherwise `false`. - */ - isPlaying: function () - { - return (this.state === TWEEN_CONST.ACTIVE); - }, - - /** - * Creates a new Tween, based on the given Tween Config, and adds it to this Timeline. - * - * @method Phaser.Tweens.Timeline#add - * @since 3.0.0 - * - * @param {(Phaser.Types.Tweens.TweenBuilderConfig|object)} config - The configuration object for the Tween. - * - * @return {this} This Timeline object. - */ - add: function (config) - { - return this.queue(TweenBuilder(this, config)); - }, - - /** - * Adds an existing Tween to this Timeline. - * - * @method Phaser.Tweens.Timeline#queue - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to be added to this Timeline. - * - * @return {this} This Timeline object. - */ - queue: function (tween) - { - if (!this.isPlaying()) - { - tween.parent = this; - tween.parentIsTimeline = true; - - this.data.push(tween); - - this.totalData = this.data.length; - } - - return this; - }, - - /** - * Checks whether a Tween has an offset value. - * - * @method Phaser.Tweens.Timeline#hasOffset - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to check. - * - * @return {boolean} `true` if the tween has a non-null offset. - */ - hasOffset: function (tween) - { - return (tween.offset !== null); - }, - - /** - * Checks whether the offset value is a number or a directive that is relative to previous tweens. - * - * @method Phaser.Tweens.Timeline#isOffsetAbsolute - * @since 3.0.0 - * - * @param {number} value - The offset value to be evaluated. - * - * @return {boolean} `true` if the result is a number, `false` if it is a directive like " -= 1000". - */ - isOffsetAbsolute: function (value) - { - return (typeof(value) === 'number'); - }, - - /** - * Checks if the offset is a relative value rather than an absolute one. - * If the value is just a number, this returns false. - * - * @method Phaser.Tweens.Timeline#isOffsetRelative - * @since 3.0.0 - * - * @param {string} value - The offset value to be evaluated. - * - * @return {boolean} `true` if the value is relative, i.e " -= 1000". If `false`, the offset is absolute. - */ - isOffsetRelative: function (value) - { - var t = typeof(value); - - if (t === 'string') - { - var op = value[0]; - - if (op === '-' || op === '+') - { - return true; - } - } - - return false; - }, - - /** - * Parses the relative offset value, returning a positive or negative number. - * - * @method Phaser.Tweens.Timeline#getRelativeOffset - * @since 3.0.0 - * - * @param {string} value - The relative offset, in the format of '-=500', for example. The first character determines whether it will be a positive or negative number. Spacing matters here. - * @param {number} base - The value to use as the offset. - * - * @return {number} The parsed offset value. - */ - getRelativeOffset: function (value, base) - { - var op = value[0]; - var num = parseFloat(value.substr(2)); - var result = base; - - switch (op) - { - case '+': - result += num; - break; - - case '-': - result -= num; - break; - } - - // Cannot ever be < 0 - return Math.max(0, result); - }, - - /** - * Calculates the total duration of the timeline. - * - * Computes all tween durations and returns the full duration of the timeline. - * - * The resulting number is stored in the timeline, not as a return value. - * - * @method Phaser.Tweens.Timeline#calcDuration - * @since 3.0.0 - */ - calcDuration: function () - { - var prevEnd = 0; - var totalDuration = 0; - var offsetDuration = 0; - - for (var i = 0; i < this.totalData; i++) - { - var tween = this.data[i]; - - tween.init(); - - if (this.hasOffset(tween)) - { - if (this.isOffsetAbsolute(tween.offset)) - { - // An actual number, so it defines the start point from the beginning of the timeline - tween.calculatedOffset = tween.offset; - - if (tween.offset === 0) - { - offsetDuration = 0; - } - } - else if (this.isOffsetRelative(tween.offset)) - { - // A relative offset (i.e. '-=1000', so starts at 'offset' ms relative to the PREVIOUS Tweens ending time) - tween.calculatedOffset = this.getRelativeOffset(tween.offset, prevEnd); - } - } - else - { - // Sequential - tween.calculatedOffset = offsetDuration; - } - - prevEnd = tween.totalDuration + tween.calculatedOffset; - - totalDuration += tween.totalDuration; - offsetDuration += tween.totalDuration; - } - - // Excludes loop values - this.duration = totalDuration; - - this.loopCounter = (this.loop === -1) ? 999999999999 : this.loop; - - if (this.loopCounter > 0) - { - this.totalDuration = this.duration + this.completeDelay + ((this.duration + this.loopDelay) * this.loopCounter); - } - else - { - this.totalDuration = this.duration + this.completeDelay; - } - }, - - /** - * Initializes the timeline, which means all Tweens get their init() called, and the total duration will be computed. - * Returns a boolean indicating whether the timeline is auto-started or not. - * - * @method Phaser.Tweens.Timeline#init - * @since 3.0.0 - * - * @return {boolean} `true` if the Timeline is started. `false` if it is paused. - */ - init: function () - { - this.calcDuration(); - - this.progress = 0; - this.totalProgress = 0; - - if (this.paused) - { - this.state = TWEEN_CONST.PAUSED; - - return false; - } - else - { - return true; - } - }, - - /** - * Resets all of the timeline's tweens back to their initial states. - * The boolean parameter indicates whether tweens that are looping should reset as well, or not. - * - * @method Phaser.Tweens.Timeline#resetTweens - * @since 3.0.0 - * - * @param {boolean} resetFromLoop - If `true`, resets all looping tweens to their initial values. - */ - resetTweens: function (resetFromLoop) - { - for (var i = 0; i < this.totalData; i++) - { - var tween = this.data[i]; - - tween.play(resetFromLoop); - } - }, - - /** - * Sets a callback for the Timeline. - * - * @method Phaser.Tweens.Timeline#setCallback - * @since 3.0.0 - * - * @param {string} type - The internal type of callback to set. - * @param {function} callback - Timeline allows multiple tweens to be linked together to create a streaming sequence. - * @param {array} [params] - The parameters to pass to the callback. - * @param {object} [scope] - The context scope of the callback. - * - * @return {this} This Timeline object. - */ - setCallback: function (type, callback, params, scope) - { - if (Timeline.TYPES.indexOf(type) !== -1) - { - this.callbacks[type] = { func: callback, scope: scope, params: params }; - } - - return this; - }, - - /** - * Passed a Tween to the Tween Manager and requests it be made active. - * - * @method Phaser.Tweens.Timeline#makeActive - * @since 3.3.0 - * - * @param {Phaser.Tweens.Tween} tween - The tween object to make active. - * - * @return {Phaser.Tweens.TweenManager} The Timeline's Tween Manager reference. - */ - makeActive: function (tween) - { - return this.manager.makeActive(tween); - }, - - /** - * Starts playing the Timeline. - * - * @method Phaser.Tweens.Timeline#play - * @fires Phaser.Tweens.Events#TIMELINE_START - * @since 3.0.0 - */ - play: function () - { - if (this.state === TWEEN_CONST.ACTIVE) - { - return; - } - - if (this.paused) - { - this.paused = false; - - this.manager.makeActive(this); - - return; - } - else - { - this.resetTweens(false); - - this.state = TWEEN_CONST.ACTIVE; - } - - this.dispatchTimelineEvent(Events.TIMELINE_START, this.callbacks.onStart); - }, - - /** - * Updates the Timeline's `state` and fires callbacks and events. - * - * @method Phaser.Tweens.Timeline#nextState - * @fires Phaser.Tweens.Events#TIMELINE_COMPLETE - * @fires Phaser.Tweens.Events#TIMELINE_LOOP - * @since 3.0.0 - * - * @see Phaser.Tweens.Timeline#update - */ - nextState: function () - { - if (this.loopCounter > 0) - { - // Reset the elapsed time - this.elapsed = 0; - this.progress = 0; - - this.loopCounter--; - - this.resetTweens(true); - - if (this.loopDelay > 0) - { - this.countdown = this.loopDelay; - - this.state = TWEEN_CONST.LOOP_DELAY; - } - else - { - this.state = TWEEN_CONST.ACTIVE; - - this.dispatchTimelineEvent(Events.TIMELINE_LOOP, this.callbacks.onLoop); - } - } - else if (this.completeDelay > 0) - { - this.state = TWEEN_CONST.COMPLETE_DELAY; - - this.countdown = this.completeDelay; - } - else - { - this.state = TWEEN_CONST.PENDING_REMOVE; - - this.dispatchTimelineEvent(Events.TIMELINE_COMPLETE, this.callbacks.onComplete); - } - }, - - /** - * Returns 'true' if this Timeline has finished and should be removed from the Tween Manager. - * Otherwise, returns false. - * - * @method Phaser.Tweens.Timeline#update - * @fires Phaser.Tweens.Events#TIMELINE_COMPLETE - * @fires Phaser.Tweens.Events#TIMELINE_UPDATE - * @since 3.0.0 - * - * @param {number} timestamp - 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} Returns `true` if this Timeline has finished and should be removed from the Tween Manager. - */ - update: function (timestamp, delta) - { - if (this.state === TWEEN_CONST.PAUSED) - { - return; - } - - if (this.useFrames) - { - delta = 1 * this.manager.timeScale; - } - - delta *= this.timeScale; - - this.elapsed += delta; - this.progress = Math.min(this.elapsed / this.duration, 1); - - this.totalElapsed += delta; - this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); - - switch (this.state) - { - case TWEEN_CONST.ACTIVE: - - var stillRunning = this.totalData; - - for (var i = 0; i < this.totalData; i++) - { - var tween = this.data[i]; - - if (tween.update(timestamp, delta)) - { - stillRunning--; - } - } - - this.dispatchTimelineEvent(Events.TIMELINE_UPDATE, this.callbacks.onUpdate); - - // Anything still running? If not, we're done - if (stillRunning === 0) - { - this.nextState(); - } - - break; - - case TWEEN_CONST.LOOP_DELAY: - - this.countdown -= delta; - - if (this.countdown <= 0) - { - this.state = TWEEN_CONST.ACTIVE; - - this.dispatchTimelineEvent(Events.TIMELINE_LOOP, this.callbacks.onLoop); - } - - break; - - case TWEEN_CONST.COMPLETE_DELAY: - - this.countdown -= delta; - - if (this.countdown <= 0) - { - this.state = TWEEN_CONST.PENDING_REMOVE; - - this.dispatchTimelineEvent(Events.TIMELINE_COMPLETE, this.callbacks.onComplete); - } - - break; - } - - return (this.state === TWEEN_CONST.PENDING_REMOVE); - }, - - /** - * Stops the Timeline immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. - * - * @method Phaser.Tweens.Timeline#stop - * @since 3.0.0 - */ - stop: function () - { - this.state = TWEEN_CONST.PENDING_REMOVE; - }, - - /** - * Pauses the Timeline, retaining its internal state. - * - * Calling this on a Timeline that is already paused has no effect and fires no event. - * - * @method Phaser.Tweens.Timeline#pause - * @fires Phaser.Tweens.Events#TIMELINE_PAUSE - * @since 3.0.0 - * - * @return {this} This Timeline object. - */ - pause: function () - { - if (this.state === TWEEN_CONST.PAUSED) - { - return; - } - - this.paused = true; - - this._pausedState = this.state; - - this.state = TWEEN_CONST.PAUSED; - - this.emit(Events.TIMELINE_PAUSE, this); - - return this; - }, - - /** - * Resumes a paused Timeline from where it was when it was paused. - * - * Calling this on a Timeline that isn't paused has no effect and fires no event. - * - * @method Phaser.Tweens.Timeline#resume - * @fires Phaser.Tweens.Events#TIMELINE_RESUME - * @since 3.0.0 - * - * @return {this} This Timeline object. - */ - resume: function () - { - if (this.state === TWEEN_CONST.PAUSED) - { - this.paused = false; - - this.state = this._pausedState; - - this.emit(Events.TIMELINE_RESUME, this); - } - - return this; - }, - - /** - * Checks if any of the Tweens in this Timeline as operating on the target object. - * - * Returns `false` if no Tweens operate on the target object. - * - * @method Phaser.Tweens.Timeline#hasTarget - * @since 3.0.0 - * - * @param {object} target - The target to check all Tweens against. - * - * @return {boolean} `true` if there is at least a single Tween that operates on the target object, otherwise `false`. - */ - hasTarget: function (target) - { - for (var i = 0; i < this.data.length; i++) - { - if (this.data[i].hasTarget(target)) - { - return true; - } - } - - return false; - }, - - /** - * Stops all the Tweens in the Timeline immediately, whatever stage of progress they are at and flags - * them for removal by the TweenManager. - * - * @method Phaser.Tweens.Timeline#destroy - * @since 3.0.0 - */ - destroy: function () - { - for (var i = 0; i < this.data.length; i++) - { - this.data[i].stop(); - } - } - -}); - -Timeline.TYPES = [ 'onStart', 'onUpdate', 'onLoop', 'onComplete', 'onYoyo' ]; - -module.exports = Timeline; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('./events'); +var TweenBuilder = require('./builders/TweenBuilder'); +var TWEEN_CONST = require('./tween/const'); + +/** + * @classdesc + * A Timeline combines multiple Tweens into one. Its overall behavior is otherwise similar to a single Tween. + * + * The Timeline updates all of its Tweens simultaneously. Its methods allow you to easily build a sequence + * of Tweens (each one starting after the previous one) or run multiple Tweens at once during given parts of the Timeline. + * + * @class Timeline + * @memberof Phaser.Tweens + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Tweens.TweenManager} manager - The Tween Manager which owns this Timeline. + */ +var Timeline = new Class({ + + Extends: EventEmitter, + + initialize: + + function Timeline (manager) + { + EventEmitter.call(this); + + /** + * The Tween Manager which owns this Timeline. + * + * @name Phaser.Tweens.Timeline#manager + * @type {Phaser.Tweens.TweenManager} + * @since 3.0.0 + */ + this.manager = manager; + + /** + * A constant value which allows this Timeline to be easily identified as one. + * + * @name Phaser.Tweens.Timeline#isTimeline + * @type {boolean} + * @default true + * @since 3.0.0 + */ + this.isTimeline = true; + + /** + * An array of Tween objects, each containing a unique property and target being tweened. + * + * @name Phaser.Tweens.Timeline#data + * @type {array} + * @default [] + * @since 3.0.0 + */ + this.data = []; + + /** + * The cached size of the data array. + * + * @name Phaser.Tweens.Timeline#totalData + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalData = 0; + + /** + * If true then duration, delay, etc values are all frame totals, rather than ms. + * + * @name Phaser.Tweens.Timeline#useFrames + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.useFrames = false; + + /** + * Scales the time applied to this Timeline. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * Value isn't used when calculating total duration of the Timeline, it's a run-time delta adjustment only. + * + * @name Phaser.Tweens.Timeline#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Loop this Timeline? Can be -1 for an infinite loop, or an integer. + * When enabled it will play through ALL Tweens again (use Tween.repeat to loop a single tween) + * + * @name Phaser.Tweens.Timeline#loop + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loop = 0; + + /** + * Time in ms/frames before this Timeline loops. + * + * @name Phaser.Tweens.Timeline#loopDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopDelay = 0; + + /** + * How many loops are left to run? + * + * @name Phaser.Tweens.Timeline#loopCounter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopCounter = 0; + + /** + * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = true (as it never completes) + * + * @name Phaser.Tweens.Timeline#completeDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.completeDelay = 0; + + /** + * Countdown timer value, as used by `loopDelay` and `completeDelay`. + * + * @name Phaser.Tweens.Timeline#countdown + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.countdown = 0; + + /** + * The current state of the Timeline. + * + * @name Phaser.Tweens.Timeline#state + * @type {integer} + * @since 3.0.0 + */ + this.state = TWEEN_CONST.PENDING_ADD; + + /** + * The state of the Timeline when it was paused (used by Resume) + * + * @name Phaser.Tweens.Timeline#_pausedState + * @type {integer} + * @private + * @since 3.0.0 + */ + this._pausedState = TWEEN_CONST.PENDING_ADD; + + /** + * Does the Timeline start off paused? (if so it needs to be started with Timeline.play) + * + * @name Phaser.Tweens.Timeline#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * Elapsed time in ms/frames of this run through of the Timeline. + * + * @name Phaser.Tweens.Timeline#elapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.elapsed = 0; + + /** + * Total elapsed time in ms/frames of the entire Timeline, including looping. + * + * @name Phaser.Tweens.Timeline#totalElapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalElapsed = 0; + + /** + * Time in ms/frames for the whole Timeline to play through once, excluding loop amounts and loop delays. + * + * @name Phaser.Tweens.Timeline#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * Value between 0 and 1. The amount of progress through the Timeline, _excluding loops_. + * + * @name Phaser.Tweens.Timeline#progress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.progress = 0; + + /** + * Time in ms/frames for all Tweens in this Timeline to complete (including looping) + * + * @name Phaser.Tweens.Timeline#totalDuration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalDuration = 0; + + /** + * Value between 0 and 1. The amount through the entire Timeline, including looping. + * + * @name Phaser.Tweens.Timeline#totalProgress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalProgress = 0; + + /** + * An object containing the different Tween callback functions. + * + * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. + * + * `onComplete` When the Timeline finishes playback fully or `Timeline.stop` is called. Never invoked if timeline is set to repeat infinitely. + * `onLoop` When a Timeline loops. + * `onStart` When the Timeline starts playing. + * `onUpdate` When a Timeline updates a child Tween. + * `onYoyo` When a Timeline starts a yoyo. + * + * @name Phaser.Tweens.Timeline#callbacks + * @type {object} + * @since 3.0.0 + */ + this.callbacks = { + onComplete: null, + onLoop: null, + onStart: null, + onUpdate: null, + onYoyo: null + }; + + /** + * The context in which all callbacks are invoked. + * + * @name Phaser.Tweens.Timeline#callbackScope + * @type {any} + * @since 3.0.0 + */ + this.callbackScope; + }, + + /** + * Internal method that will emit a Timeline based Event and invoke the given callback. + * + * @method Phaser.Tweens.Timeline#dispatchTimelineEvent + * @since 3.19.0 + * + * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. + * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. + */ + dispatchTimelineEvent: function (event, callback) + { + this.emit(event, this); + + if (callback) + { + callback.func.apply(callback.scope, callback.params); + } + }, + + /** + * Sets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. + * A value of 0.5 runs 50% slower, and so on. + * + * The value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. + * + * @method Phaser.Tweens.Timeline#setTimeScale + * @since 3.0.0 + * + * @param {number} value - The time scale value to set. + * + * @return {this} This Timeline object. + */ + setTimeScale: function (value) + { + this.timeScale = value; + + return this; + }, + + /** + * Gets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. + * A value of 0.5 runs 50% slower, and so on. + * + * @method Phaser.Tweens.Timeline#getTimeScale + * @since 3.0.0 + * + * @return {number} The value of the time scale applied to this Timeline. + */ + getTimeScale: function () + { + return this.timeScale; + }, + + /** + * Check whether or not the Timeline is playing. + * + * @method Phaser.Tweens.Timeline#isPlaying + * @since 3.0.0 + * + * @return {boolean} `true` if this Timeline is active, otherwise `false`. + */ + isPlaying: function () + { + return (this.state === TWEEN_CONST.ACTIVE); + }, + + /** + * Creates a new Tween, based on the given Tween Config, and adds it to this Timeline. + * + * @method Phaser.Tweens.Timeline#add + * @since 3.0.0 + * + * @param {(Phaser.Types.Tweens.TweenBuilderConfig|object)} config - The configuration object for the Tween. + * + * @return {this} This Timeline object. + */ + add: function (config) + { + return this.queue(TweenBuilder(this, config)); + }, + + /** + * Adds an existing Tween to this Timeline. + * + * @method Phaser.Tweens.Timeline#queue + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to be added to this Timeline. + * + * @return {this} This Timeline object. + */ + queue: function (tween) + { + if (!this.isPlaying()) + { + tween.parent = this; + tween.parentIsTimeline = true; + + this.data.push(tween); + + this.totalData = this.data.length; + } + + return this; + }, + + /** + * Checks whether a Tween has an offset value. + * + * @method Phaser.Tweens.Timeline#hasOffset + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to check. + * + * @return {boolean} `true` if the tween has a non-null offset. + */ + hasOffset: function (tween) + { + return (tween.offset !== null); + }, + + /** + * Checks whether the offset value is a number or a directive that is relative to previous tweens. + * + * @method Phaser.Tweens.Timeline#isOffsetAbsolute + * @since 3.0.0 + * + * @param {number} value - The offset value to be evaluated. + * + * @return {boolean} `true` if the result is a number, `false` if it is a directive like " -= 1000". + */ + isOffsetAbsolute: function (value) + { + return (typeof(value) === 'number'); + }, + + /** + * Checks if the offset is a relative value rather than an absolute one. + * If the value is just a number, this returns false. + * + * @method Phaser.Tweens.Timeline#isOffsetRelative + * @since 3.0.0 + * + * @param {string} value - The offset value to be evaluated. + * + * @return {boolean} `true` if the value is relative, i.e " -= 1000". If `false`, the offset is absolute. + */ + isOffsetRelative: function (value) + { + var t = typeof(value); + + if (t === 'string') + { + var op = value[0]; + + if (op === '-' || op === '+') + { + return true; + } + } + + return false; + }, + + /** + * Parses the relative offset value, returning a positive or negative number. + * + * @method Phaser.Tweens.Timeline#getRelativeOffset + * @since 3.0.0 + * + * @param {string} value - The relative offset, in the format of '-=500', for example. The first character determines whether it will be a positive or negative number. Spacing matters here. + * @param {number} base - The value to use as the offset. + * + * @return {number} The parsed offset value. + */ + getRelativeOffset: function (value, base) + { + var op = value[0]; + var num = parseFloat(value.substr(2)); + var result = base; + + switch (op) + { + case '+': + result += num; + break; + + case '-': + result -= num; + break; + } + + // Cannot ever be < 0 + return Math.max(0, result); + }, + + /** + * Calculates the total duration of the timeline. + * + * Computes all tween durations and returns the full duration of the timeline. + * + * The resulting number is stored in the timeline, not as a return value. + * + * @method Phaser.Tweens.Timeline#calcDuration + * @since 3.0.0 + */ + calcDuration: function () + { + var prevEnd = 0; + var totalDuration = 0; + var offsetDuration = 0; + + for (var i = 0; i < this.totalData; i++) + { + var tween = this.data[i]; + + tween.init(); + + if (this.hasOffset(tween)) + { + if (this.isOffsetAbsolute(tween.offset)) + { + // An actual number, so it defines the start point from the beginning of the timeline + tween.calculatedOffset = tween.offset; + + if (tween.offset === 0) + { + offsetDuration = 0; + } + } + else if (this.isOffsetRelative(tween.offset)) + { + // A relative offset (i.e. '-=1000', so starts at 'offset' ms relative to the PREVIOUS Tweens ending time) + tween.calculatedOffset = this.getRelativeOffset(tween.offset, prevEnd); + } + } + else + { + // Sequential + tween.calculatedOffset = offsetDuration; + } + + prevEnd = tween.totalDuration + tween.calculatedOffset; + + totalDuration += tween.totalDuration; + offsetDuration += tween.totalDuration; + } + + // Excludes loop values + this.duration = totalDuration; + + this.loopCounter = (this.loop === -1) ? 999999999999 : this.loop; + + if (this.loopCounter > 0) + { + this.totalDuration = this.duration + this.completeDelay + ((this.duration + this.loopDelay) * this.loopCounter); + } + else + { + this.totalDuration = this.duration + this.completeDelay; + } + }, + + /** + * Initializes the timeline, which means all Tweens get their init() called, and the total duration will be computed. + * Returns a boolean indicating whether the timeline is auto-started or not. + * + * @method Phaser.Tweens.Timeline#init + * @since 3.0.0 + * + * @return {boolean} `true` if the Timeline is started. `false` if it is paused. + */ + init: function () + { + this.calcDuration(); + + this.progress = 0; + this.totalProgress = 0; + + if (this.paused) + { + this.state = TWEEN_CONST.PAUSED; + + return false; + } + else + { + return true; + } + }, + + /** + * Resets all of the timeline's tweens back to their initial states. + * The boolean parameter indicates whether tweens that are looping should reset as well, or not. + * + * @method Phaser.Tweens.Timeline#resetTweens + * @since 3.0.0 + * + * @param {boolean} resetFromLoop - If `true`, resets all looping tweens to their initial values. + */ + resetTweens: function (resetFromLoop) + { + for (var i = 0; i < this.totalData; i++) + { + var tween = this.data[i]; + + tween.play(resetFromLoop); + } + }, + + /** + * Sets a callback for the Timeline. + * + * @method Phaser.Tweens.Timeline#setCallback + * @since 3.0.0 + * + * @param {string} type - The internal type of callback to set. + * @param {function} callback - Timeline allows multiple tweens to be linked together to create a streaming sequence. + * @param {array} [params] - The parameters to pass to the callback. + * @param {object} [scope] - The context scope of the callback. + * + * @return {this} This Timeline object. + */ + setCallback: function (type, callback, params, scope) + { + if (Timeline.TYPES.indexOf(type) !== -1) + { + this.callbacks[type] = { func: callback, scope: scope, params: params }; + } + + return this; + }, + + /** + * Passed a Tween to the Tween Manager and requests it be made active. + * + * @method Phaser.Tweens.Timeline#makeActive + * @since 3.3.0 + * + * @param {Phaser.Tweens.Tween} tween - The tween object to make active. + * + * @return {Phaser.Tweens.TweenManager} The Timeline's Tween Manager reference. + */ + makeActive: function (tween) + { + return this.manager.makeActive(tween); + }, + + /** + * Starts playing the Timeline. + * + * @method Phaser.Tweens.Timeline#play + * @fires Phaser.Tweens.Events#TIMELINE_START + * @since 3.0.0 + */ + play: function () + { + if (this.state === TWEEN_CONST.ACTIVE) + { + return; + } + + if (this.paused) + { + this.paused = false; + + this.manager.makeActive(this); + + return; + } + else + { + this.resetTweens(false); + + this.state = TWEEN_CONST.ACTIVE; + } + + this.dispatchTimelineEvent(Events.TIMELINE_START, this.callbacks.onStart); + }, + + /** + * Updates the Timeline's `state` and fires callbacks and events. + * + * @method Phaser.Tweens.Timeline#nextState + * @fires Phaser.Tweens.Events#TIMELINE_COMPLETE + * @fires Phaser.Tweens.Events#TIMELINE_LOOP + * @since 3.0.0 + * + * @see Phaser.Tweens.Timeline#update + */ + nextState: function () + { + if (this.loopCounter > 0) + { + // Reset the elapsed time + this.elapsed = 0; + this.progress = 0; + + this.loopCounter--; + + this.resetTweens(true); + + if (this.loopDelay > 0) + { + this.countdown = this.loopDelay; + + this.state = TWEEN_CONST.LOOP_DELAY; + } + else + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTimelineEvent(Events.TIMELINE_LOOP, this.callbacks.onLoop); + } + } + else if (this.completeDelay > 0) + { + this.state = TWEEN_CONST.COMPLETE_DELAY; + + this.countdown = this.completeDelay; + } + else + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTimelineEvent(Events.TIMELINE_COMPLETE, this.callbacks.onComplete); + } + }, + + /** + * Returns 'true' if this Timeline has finished and should be removed from the Tween Manager. + * Otherwise, returns false. + * + * @method Phaser.Tweens.Timeline#update + * @fires Phaser.Tweens.Events#TIMELINE_COMPLETE + * @fires Phaser.Tweens.Events#TIMELINE_UPDATE + * @since 3.0.0 + * + * @param {number} timestamp - 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} Returns `true` if this Timeline has finished and should be removed from the Tween Manager. + */ + update: function (timestamp, delta) + { + if (this.state === TWEEN_CONST.PAUSED) + { + return; + } + + if (this.useFrames) + { + delta = 1 * this.manager.timeScale; + } + + delta *= this.timeScale; + + this.elapsed += delta; + this.progress = Math.min(this.elapsed / this.duration, 1); + + this.totalElapsed += delta; + this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); + + switch (this.state) + { + case TWEEN_CONST.ACTIVE: + + var stillRunning = this.totalData; + + for (var i = 0; i < this.totalData; i++) + { + var tween = this.data[i]; + + if (tween.update(timestamp, delta)) + { + stillRunning--; + } + } + + this.dispatchTimelineEvent(Events.TIMELINE_UPDATE, this.callbacks.onUpdate); + + // Anything still running? If not, we're done + if (stillRunning === 0) + { + this.nextState(); + } + + break; + + case TWEEN_CONST.LOOP_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTimelineEvent(Events.TIMELINE_LOOP, this.callbacks.onLoop); + } + + break; + + case TWEEN_CONST.COMPLETE_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTimelineEvent(Events.TIMELINE_COMPLETE, this.callbacks.onComplete); + } + + break; + } + + return (this.state === TWEEN_CONST.PENDING_REMOVE); + }, + + /** + * Stops the Timeline immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. + * + * @method Phaser.Tweens.Timeline#stop + * @since 3.0.0 + */ + stop: function () + { + this.state = TWEEN_CONST.PENDING_REMOVE; + }, + + /** + * Pauses the Timeline, retaining its internal state. + * + * Calling this on a Timeline that is already paused has no effect and fires no event. + * + * @method Phaser.Tweens.Timeline#pause + * @fires Phaser.Tweens.Events#TIMELINE_PAUSE + * @since 3.0.0 + * + * @return {this} This Timeline object. + */ + pause: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + return; + } + + this.paused = true; + + this._pausedState = this.state; + + this.state = TWEEN_CONST.PAUSED; + + this.emit(Events.TIMELINE_PAUSE, this); + + return this; + }, + + /** + * Resumes a paused Timeline from where it was when it was paused. + * + * Calling this on a Timeline that isn't paused has no effect and fires no event. + * + * @method Phaser.Tweens.Timeline#resume + * @fires Phaser.Tweens.Events#TIMELINE_RESUME + * @since 3.0.0 + * + * @return {this} This Timeline object. + */ + resume: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + this.paused = false; + + this.state = this._pausedState; + + this.emit(Events.TIMELINE_RESUME, this); + } + + return this; + }, + + /** + * Checks if any of the Tweens in this Timeline as operating on the target object. + * + * Returns `false` if no Tweens operate on the target object. + * + * @method Phaser.Tweens.Timeline#hasTarget + * @since 3.0.0 + * + * @param {object} target - The target to check all Tweens against. + * + * @return {boolean} `true` if there is at least a single Tween that operates on the target object, otherwise `false`. + */ + hasTarget: function (target) + { + for (var i = 0; i < this.data.length; i++) + { + if (this.data[i].hasTarget(target)) + { + return true; + } + } + + return false; + }, + + /** + * Stops all the Tweens in the Timeline immediately, whatever stage of progress they are at and flags + * them for removal by the TweenManager. + * + * @method Phaser.Tweens.Timeline#destroy + * @since 3.0.0 + */ + destroy: function () + { + for (var i = 0; i < this.data.length; i++) + { + this.data[i].stop(); + } + } + +}); + +Timeline.TYPES = [ 'onStart', 'onUpdate', 'onLoop', 'onComplete', 'onYoyo' ]; + +module.exports = Timeline; diff --git a/src/tweens/TweenManager.js b/src/tweens/TweenManager.js index e36d9c92e..ff868f2b6 100644 --- a/src/tweens/TweenManager.js +++ b/src/tweens/TweenManager.js @@ -1,766 +1,766 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var ArrayRemove = require('../utils/array/Remove'); -var Class = require('../utils/Class'); -var NumberTweenBuilder = require('./builders/NumberTweenBuilder'); -var PluginCache = require('../plugins/PluginCache'); -var SceneEvents = require('../scene/events'); -var StaggerBuilder = require('./builders/StaggerBuilder'); -var TimelineBuilder = require('./builders/TimelineBuilder'); -var TWEEN_CONST = require('./tween/const'); -var TweenBuilder = require('./builders/TweenBuilder'); - -/** - * @classdesc - * The Tween Manager is a default Scene Plugin which controls and updates Tweens and Timelines. - * - * @class TweenManager - * @memberof Phaser.Tweens - * @constructor - * @since 3.0.0 - * - * @param {Phaser.Scene} scene - The Scene which owns this Tween Manager. - */ -var TweenManager = new Class({ - - initialize: - - function TweenManager (scene) - { - /** - * The Scene which owns this Tween Manager. - * - * @name Phaser.Tweens.TweenManager#scene - * @type {Phaser.Scene} - * @since 3.0.0 - */ - this.scene = scene; - - /** - * The Systems object of the Scene which owns this Tween Manager. - * - * @name Phaser.Tweens.TweenManager#systems - * @type {Phaser.Scenes.Systems} - * @since 3.0.0 - */ - this.systems = scene.sys; - - /** - * The time scale of the Tween Manager. - * - * This value scales the time delta between two frames, thus influencing the speed of time for all Tweens owned by this Tween Manager. - * - * @name Phaser.Tweens.TweenManager#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * An array of Tweens and Timelines which will be added to the Tween Manager at the start of the frame. - * - * @name Phaser.Tweens.TweenManager#_add - * @type {array} - * @private - * @since 3.0.0 - */ - this._add = []; - - /** - * An array of Tweens and Timelines pending to be later added to the Tween Manager. - * - * @name Phaser.Tweens.TweenManager#_pending - * @type {array} - * @private - * @since 3.0.0 - */ - this._pending = []; - - /** - * An array of Tweens and Timelines which are still incomplete and are actively processed by the Tween Manager. - * - * @name Phaser.Tweens.TweenManager#_active - * @type {array} - * @private - * @since 3.0.0 - */ - this._active = []; - - /** - * An array of Tweens and Timelines which will be removed from the Tween Manager at the start of the frame. - * - * @name Phaser.Tweens.TweenManager#_destroy - * @type {array} - * @private - * @since 3.0.0 - */ - this._destroy = []; - - /** - * The number of Tweens and Timelines which need to be processed by the Tween Manager at the start of the frame. - * - * @name Phaser.Tweens.TweenManager#_toProcess - * @type {integer} - * @private - * @default 0 - * @since 3.0.0 - */ - this._toProcess = 0; - - scene.sys.events.once(SceneEvents.BOOT, this.boot, this); - scene.sys.events.on(SceneEvents.START, this.start, this); - }, - - /** - * This method is called automatically, only once, when the Scene is first created. - * Do not invoke it directly. - * - * @method Phaser.Tweens.TweenManager#boot - * @private - * @since 3.5.1 - */ - boot: function () - { - this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); - }, - - /** - * This method is called automatically by the Scene when it is starting up. - * It is responsible for creating local systems, properties and listening for Scene events. - * Do not invoke it directly. - * - * @method Phaser.Tweens.TweenManager#start - * @private - * @since 3.5.0 - */ - start: function () - { - var eventEmitter = this.systems.events; - - eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); - eventEmitter.on(SceneEvents.UPDATE, this.update, this); - eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); - - this.timeScale = 1; - }, - - /** - * Create a Tween Timeline and return it, but do NOT add it to the active or pending Tween lists. - * - * @method Phaser.Tweens.TweenManager#createTimeline - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TimelineBuilderConfig} [config] - The configuration object for the Timeline and its Tweens. - * - * @return {Phaser.Tweens.Timeline} The created Timeline object. - */ - createTimeline: function (config) - { - return TimelineBuilder(this, config); - }, - - /** - * Create a Tween Timeline and add it to the active Tween list/ - * - * @method Phaser.Tweens.TweenManager#timeline - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TimelineBuilderConfig} [config] - The configuration object for the Timeline and its Tweens. - * - * @return {Phaser.Tweens.Timeline} The created Timeline object. - */ - timeline: function (config) - { - var timeline = TimelineBuilder(this, config); - - if (!timeline.paused) - { - this._add.push(timeline); - - this._toProcess++; - } - - return timeline; - }, - - /** - * Create a Tween and return it, but do NOT add it to the active or pending Tween lists. - * - * @method Phaser.Tweens.TweenManager#create - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The configuration object for the Tween. - * - * @return {Phaser.Tweens.Tween} The created Tween object. - */ - create: function (config) - { - return TweenBuilder(this, config); - }, - - /** - * Create a Tween and add it to the active Tween list. - * - * @method Phaser.Tweens.TweenManager#add - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The configuration object for the Tween. - * - * @return {Phaser.Tweens.Tween} The created Tween. - */ - add: function (config) - { - var tween = TweenBuilder(this, config); - - this._add.push(tween); - - this._toProcess++; - - return tween; - }, - - /** - * Add an existing tween into the active Tween list. - * - * @method Phaser.Tweens.TweenManager#existing - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to add. - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager object. - */ - existing: function (tween) - { - this._add.push(tween); - - this._toProcess++; - - return this; - }, - - /** - * Create a Number Tween and add it to the active Tween list. - * - * @method Phaser.Tweens.TweenManager#addCounter - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.NumberTweenBuilderConfig} config - The configuration object for the Number Tween. - * - * @return {Phaser.Tweens.Tween} The created Number Tween. - */ - addCounter: function (config) - { - var tween = NumberTweenBuilder(this, config); - - this._add.push(tween); - - this._toProcess++; - - return tween; - }, - - /** - * 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' }) - * }); - * ``` - * - * @method Phaser.Tweens.TweenManager#stagger - * @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} config - The configuration object for the Stagger function. - * - * @return {function} The stagger function. - */ - stagger: function (value, options) - { - return StaggerBuilder(value, options); - }, - - /** - * Updates the Tween Manager's internal lists at the start of the frame. - * - * This method will return immediately if no changes have been indicated. - * - * @method Phaser.Tweens.TweenManager#preUpdate - * @since 3.0.0 - */ - preUpdate: function () - { - if (this._toProcess === 0) - { - // Quick bail - return; - } - - var list = this._destroy; - var active = this._active; - var pending = this._pending; - var i; - var tween; - - // Clear the 'destroy' list - for (i = 0; i < list.length; i++) - { - tween = list[i]; - - // Remove from the 'active' array - var idx = active.indexOf(tween); - - if (idx === -1) - { - // Not in the active array, is it in pending instead? - idx = pending.indexOf(tween); - - if (idx > -1) - { - tween.state = TWEEN_CONST.REMOVED; - pending.splice(idx, 1); - } - } - else - { - tween.state = TWEEN_CONST.REMOVED; - active.splice(idx, 1); - } - } - - list.length = 0; - - // Process the addition list - // This stops callbacks and out of sync events from populating the active array mid-way during the update - - list = this._add; - - for (i = 0; i < list.length; i++) - { - tween = list[i]; - - if (tween.state === TWEEN_CONST.PENDING_ADD) - { - // Return true if the Tween should be started right away, otherwise false - if (tween.init()) - { - tween.play(); - - this._active.push(tween); - } - else - { - this._pending.push(tween); - } - } - } - - list.length = 0; - - this._toProcess = 0; - }, - - /** - * Updates all Tweens and Timelines of the Tween Manager. - * - * @method Phaser.Tweens.TweenManager#update - * @since 3.0.0 - * - * @param {number} timestamp - The current time in milliseconds. - * @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update: function (timestamp, delta) - { - // Process active tweens - var list = this._active; - var tween; - - // Scale the delta - delta *= this.timeScale; - - for (var i = 0; i < list.length; i++) - { - tween = list[i]; - - // If Tween.update returns 'true' then it means it has completed, - // so move it to the destroy list - if (tween.update(timestamp, delta)) - { - this._destroy.push(tween); - this._toProcess++; - } - } - }, - - /** - * Removes the given tween from the Tween Manager, regardless of its state (pending or active). - * - * @method Phaser.Tweens.TweenManager#remove - * @since 3.17.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to be removed. - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager object. - */ - remove: function (tween) - { - ArrayRemove(this._add, tween); - ArrayRemove(this._pending, tween); - ArrayRemove(this._active, tween); - ArrayRemove(this._destroy, tween); - - tween.state = TWEEN_CONST.REMOVED; - - return this; - }, - - /** - * Checks if a Tween or Timeline is active and adds it to the Tween Manager at the start of the frame if it isn't. - * - * @method Phaser.Tweens.TweenManager#makeActive - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to check. - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager object. - */ - makeActive: function (tween) - { - if (this._add.indexOf(tween) !== -1 || this._active.indexOf(tween) !== -1) - { - return this; - } - - var idx = this._pending.indexOf(tween); - - if (idx !== -1) - { - this._pending.splice(idx, 1); - } - - this._add.push(tween); - - tween.state = TWEEN_CONST.PENDING_ADD; - - this._toProcess++; - - return this; - }, - - /** - * Passes all Tweens to the given callback. - * - * @method Phaser.Tweens.TweenManager#each - * @since 3.0.0 - * - * @param {function} callback - The function to call. - * @param {object} [scope] - The scope (`this` object) to call the function with. - * @param {...*} [args] - The arguments to pass into the function. Its first argument will always be the Tween currently being iterated. - */ - each: function (callback, scope) - { - var args = [ null ]; - - for (var i = 1; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (var texture in this.list) - { - args[0] = this.list[texture]; - - callback.apply(scope, args); - } - }, - - /** - * Returns an array of all active Tweens and Timelines in the Tween Manager. - * - * @method Phaser.Tweens.TweenManager#getAllTweens - * @since 3.0.0 - * - * @return {Phaser.Tweens.Tween[]} A new array containing references to all active Tweens and Timelines. - */ - getAllTweens: function () - { - var list = this._active; - var output = []; - - for (var i = 0; i < list.length; i++) - { - output.push(list[i]); - } - - return output; - }, - - /** - * Returns the scale of the time delta for all Tweens and Timelines owned by this Tween Manager. - * - * @method Phaser.Tweens.TweenManager#getGlobalTimeScale - * @since 3.0.0 - * - * @return {number} The scale of the time delta, usually 1. - */ - getGlobalTimeScale: function () - { - return this.timeScale; - }, - - /** - * Returns an array of all Tweens or Timelines in the Tween Manager which affect the given target or array of targets. - * - * @method Phaser.Tweens.TweenManager#getTweensOf - * @since 3.0.0 - * - * @param {(object|array)} target - The target to look for. Provide an array to look for multiple targets. - * - * @return {Phaser.Tweens.Tween[]} A new array containing all Tweens and Timelines which affect the given target(s). - */ - getTweensOf: function (target) - { - var list = this._active; - var tween; - var output = []; - var i; - - if (Array.isArray(target)) - { - for (i = 0; i < list.length; i++) - { - tween = list[i]; - - for (var t = 0; t < target.length; t++) - { - if (tween.hasTarget(target[t])) - { - output.push(tween); - } - } - } - } - else - { - for (i = 0; i < list.length; i++) - { - tween = list[i]; - - if (tween.hasTarget(target)) - { - output.push(tween); - } - } - } - - return output; - }, - - /** - * Checks if the given object is being affected by a playing Tween. - * - * @method Phaser.Tweens.TweenManager#isTweening - * @since 3.0.0 - * - * @param {object} target - target Phaser.Tweens.Tween object - * - * @return {boolean} returns if target tween object is active or not - */ - isTweening: function (target) - { - var list = this._active; - var tween; - - for (var i = 0; i < list.length; i++) - { - tween = list[i]; - - if (tween.hasTarget(target) && tween.isPlaying()) - { - return true; - } - } - - return false; - }, - - /** - * Stops all Tweens in this Tween Manager. They will be removed at the start of the frame. - * - * @method Phaser.Tweens.TweenManager#killAll - * @since 3.0.0 - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager. - */ - killAll: function () - { - var tweens = this.getAllTweens(); - - for (var i = 0; i < tweens.length; i++) - { - tweens[i].stop(); - } - - return this; - }, - - /** - * Stops all Tweens which affect the given target or array of targets. The Tweens will be removed from the Tween Manager at the start of the frame. - * - * @see {@link #getTweensOf} - * - * @method Phaser.Tweens.TweenManager#killTweensOf - * @since 3.0.0 - * - * @param {(object|array)} target - The target to look for. Provide an array to look for multiple targets. - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager. - */ - killTweensOf: function (target) - { - var tweens = this.getTweensOf(target); - - for (var i = 0; i < tweens.length; i++) - { - tweens[i].stop(); - } - - return this; - }, - - /** - * Pauses all Tweens in this Tween Manager. - * - * @method Phaser.Tweens.TweenManager#pauseAll - * @since 3.0.0 - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager. - */ - pauseAll: function () - { - var list = this._active; - - for (var i = 0; i < list.length; i++) - { - list[i].pause(); - } - - return this; - }, - - /** - * Resumes all Tweens in this Tween Manager. - * - * @method Phaser.Tweens.TweenManager#resumeAll - * @since 3.0.0 - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager. - */ - resumeAll: function () - { - var list = this._active; - - for (var i = 0; i < list.length; i++) - { - list[i].resume(); - } - - return this; - }, - - /** - * Sets a new scale of the time delta for this Tween Manager. - * - * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Tween Manager and all Tweens it owns. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing all Tweens. - * - * @method Phaser.Tweens.TweenManager#setGlobalTimeScale - * @since 3.0.0 - * - * @param {number} value - The new scale of the time delta, where 1 is the normal speed. - * - * @return {Phaser.Tweens.TweenManager} This Tween Manager. - */ - setGlobalTimeScale: function (value) - { - this.timeScale = value; - - return this; - }, - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - * - * @method Phaser.Tweens.TweenManager#shutdown - * @since 3.0.0 - */ - shutdown: function () - { - this.killAll(); - - this._add = []; - this._pending = []; - this._active = []; - this._destroy = []; - - this._toProcess = 0; - - var eventEmitter = this.systems.events; - - eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); - eventEmitter.off(SceneEvents.UPDATE, this.update, this); - eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); - }, - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - * - * @method Phaser.Tweens.TweenManager#destroy - * @since 3.0.0 - */ - destroy: function () - { - this.shutdown(); - - this.scene.sys.events.off(SceneEvents.START, this.start, this); - - this.scene = null; - this.systems = null; - } - -}); - -PluginCache.register('TweenManager', TweenManager, 'tweens'); - -module.exports = TweenManager; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var ArrayRemove = require('../utils/array/Remove'); +var Class = require('../utils/Class'); +var NumberTweenBuilder = require('./builders/NumberTweenBuilder'); +var PluginCache = require('../plugins/PluginCache'); +var SceneEvents = require('../scene/events'); +var StaggerBuilder = require('./builders/StaggerBuilder'); +var TimelineBuilder = require('./builders/TimelineBuilder'); +var TWEEN_CONST = require('./tween/const'); +var TweenBuilder = require('./builders/TweenBuilder'); + +/** + * @classdesc + * The Tween Manager is a default Scene Plugin which controls and updates Tweens and Timelines. + * + * @class TweenManager + * @memberof Phaser.Tweens + * @constructor + * @since 3.0.0 + * + * @param {Phaser.Scene} scene - The Scene which owns this Tween Manager. + */ +var TweenManager = new Class({ + + initialize: + + function TweenManager (scene) + { + /** + * The Scene which owns this Tween Manager. + * + * @name Phaser.Tweens.TweenManager#scene + * @type {Phaser.Scene} + * @since 3.0.0 + */ + this.scene = scene; + + /** + * The Systems object of the Scene which owns this Tween Manager. + * + * @name Phaser.Tweens.TweenManager#systems + * @type {Phaser.Scenes.Systems} + * @since 3.0.0 + */ + this.systems = scene.sys; + + /** + * The time scale of the Tween Manager. + * + * This value scales the time delta between two frames, thus influencing the speed of time for all Tweens owned by this Tween Manager. + * + * @name Phaser.Tweens.TweenManager#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * An array of Tweens and Timelines which will be added to the Tween Manager at the start of the frame. + * + * @name Phaser.Tweens.TweenManager#_add + * @type {array} + * @private + * @since 3.0.0 + */ + this._add = []; + + /** + * An array of Tweens and Timelines pending to be later added to the Tween Manager. + * + * @name Phaser.Tweens.TweenManager#_pending + * @type {array} + * @private + * @since 3.0.0 + */ + this._pending = []; + + /** + * An array of Tweens and Timelines which are still incomplete and are actively processed by the Tween Manager. + * + * @name Phaser.Tweens.TweenManager#_active + * @type {array} + * @private + * @since 3.0.0 + */ + this._active = []; + + /** + * An array of Tweens and Timelines which will be removed from the Tween Manager at the start of the frame. + * + * @name Phaser.Tweens.TweenManager#_destroy + * @type {array} + * @private + * @since 3.0.0 + */ + this._destroy = []; + + /** + * The number of Tweens and Timelines which need to be processed by the Tween Manager at the start of the frame. + * + * @name Phaser.Tweens.TweenManager#_toProcess + * @type {integer} + * @private + * @default 0 + * @since 3.0.0 + */ + this._toProcess = 0; + + scene.sys.events.once(SceneEvents.BOOT, this.boot, this); + scene.sys.events.on(SceneEvents.START, this.start, this); + }, + + /** + * This method is called automatically, only once, when the Scene is first created. + * Do not invoke it directly. + * + * @method Phaser.Tweens.TweenManager#boot + * @private + * @since 3.5.1 + */ + boot: function () + { + this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); + }, + + /** + * This method is called automatically by the Scene when it is starting up. + * It is responsible for creating local systems, properties and listening for Scene events. + * Do not invoke it directly. + * + * @method Phaser.Tweens.TweenManager#start + * @private + * @since 3.5.0 + */ + start: function () + { + var eventEmitter = this.systems.events; + + eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.on(SceneEvents.UPDATE, this.update, this); + eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); + + this.timeScale = 1; + }, + + /** + * Create a Tween Timeline and return it, but do NOT add it to the active or pending Tween lists. + * + * @method Phaser.Tweens.TweenManager#createTimeline + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} [config] - The configuration object for the Timeline and its Tweens. + * + * @return {Phaser.Tweens.Timeline} The created Timeline object. + */ + createTimeline: function (config) + { + return TimelineBuilder(this, config); + }, + + /** + * Create a Tween Timeline and add it to the active Tween list/ + * + * @method Phaser.Tweens.TweenManager#timeline + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} [config] - The configuration object for the Timeline and its Tweens. + * + * @return {Phaser.Tweens.Timeline} The created Timeline object. + */ + timeline: function (config) + { + var timeline = TimelineBuilder(this, config); + + if (!timeline.paused) + { + this._add.push(timeline); + + this._toProcess++; + } + + return timeline; + }, + + /** + * Create a Tween and return it, but do NOT add it to the active or pending Tween lists. + * + * @method Phaser.Tweens.TweenManager#create + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The configuration object for the Tween. + * + * @return {Phaser.Tweens.Tween} The created Tween object. + */ + create: function (config) + { + return TweenBuilder(this, config); + }, + + /** + * Create a Tween and add it to the active Tween list. + * + * @method Phaser.Tweens.TweenManager#add + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The configuration object for the Tween. + * + * @return {Phaser.Tweens.Tween} The created Tween. + */ + add: function (config) + { + var tween = TweenBuilder(this, config); + + this._add.push(tween); + + this._toProcess++; + + return tween; + }, + + /** + * Add an existing tween into the active Tween list. + * + * @method Phaser.Tweens.TweenManager#existing + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to add. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager object. + */ + existing: function (tween) + { + this._add.push(tween); + + this._toProcess++; + + return this; + }, + + /** + * Create a Number Tween and add it to the active Tween list. + * + * @method Phaser.Tweens.TweenManager#addCounter + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.NumberTweenBuilderConfig} config - The configuration object for the Number Tween. + * + * @return {Phaser.Tweens.Tween} The created Number Tween. + */ + addCounter: function (config) + { + var tween = NumberTweenBuilder(this, config); + + this._add.push(tween); + + this._toProcess++; + + return tween; + }, + + /** + * 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' }) + * }); + * ``` + * + * @method Phaser.Tweens.TweenManager#stagger + * @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} config - The configuration object for the Stagger function. + * + * @return {function} The stagger function. + */ + stagger: function (value, options) + { + return StaggerBuilder(value, options); + }, + + /** + * Updates the Tween Manager's internal lists at the start of the frame. + * + * This method will return immediately if no changes have been indicated. + * + * @method Phaser.Tweens.TweenManager#preUpdate + * @since 3.0.0 + */ + preUpdate: function () + { + if (this._toProcess === 0) + { + // Quick bail + return; + } + + var list = this._destroy; + var active = this._active; + var pending = this._pending; + var i; + var tween; + + // Clear the 'destroy' list + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + // Remove from the 'active' array + var idx = active.indexOf(tween); + + if (idx === -1) + { + // Not in the active array, is it in pending instead? + idx = pending.indexOf(tween); + + if (idx > -1) + { + tween.state = TWEEN_CONST.REMOVED; + pending.splice(idx, 1); + } + } + else + { + tween.state = TWEEN_CONST.REMOVED; + active.splice(idx, 1); + } + } + + list.length = 0; + + // Process the addition list + // This stops callbacks and out of sync events from populating the active array mid-way during the update + + list = this._add; + + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + if (tween.state === TWEEN_CONST.PENDING_ADD) + { + // Return true if the Tween should be started right away, otherwise false + if (tween.init()) + { + tween.play(); + + this._active.push(tween); + } + else + { + this._pending.push(tween); + } + } + } + + list.length = 0; + + this._toProcess = 0; + }, + + /** + * Updates all Tweens and Timelines of the Tween Manager. + * + * @method Phaser.Tweens.TweenManager#update + * @since 3.0.0 + * + * @param {number} timestamp - The current time in milliseconds. + * @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update: function (timestamp, delta) + { + // Process active tweens + var list = this._active; + var tween; + + // Scale the delta + delta *= this.timeScale; + + for (var i = 0; i < list.length; i++) + { + tween = list[i]; + + // If Tween.update returns 'true' then it means it has completed, + // so move it to the destroy list + if (tween.update(timestamp, delta)) + { + this._destroy.push(tween); + this._toProcess++; + } + } + }, + + /** + * Removes the given tween from the Tween Manager, regardless of its state (pending or active). + * + * @method Phaser.Tweens.TweenManager#remove + * @since 3.17.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to be removed. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager object. + */ + remove: function (tween) + { + ArrayRemove(this._add, tween); + ArrayRemove(this._pending, tween); + ArrayRemove(this._active, tween); + ArrayRemove(this._destroy, tween); + + tween.state = TWEEN_CONST.REMOVED; + + return this; + }, + + /** + * Checks if a Tween or Timeline is active and adds it to the Tween Manager at the start of the frame if it isn't. + * + * @method Phaser.Tweens.TweenManager#makeActive + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to check. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager object. + */ + makeActive: function (tween) + { + if (this._add.indexOf(tween) !== -1 || this._active.indexOf(tween) !== -1) + { + return this; + } + + var idx = this._pending.indexOf(tween); + + if (idx !== -1) + { + this._pending.splice(idx, 1); + } + + this._add.push(tween); + + tween.state = TWEEN_CONST.PENDING_ADD; + + this._toProcess++; + + return this; + }, + + /** + * Passes all Tweens to the given callback. + * + * @method Phaser.Tweens.TweenManager#each + * @since 3.0.0 + * + * @param {function} callback - The function to call. + * @param {object} [scope] - The scope (`this` object) to call the function with. + * @param {...*} [args] - The arguments to pass into the function. Its first argument will always be the Tween currently being iterated. + */ + each: function (callback, scope) + { + var args = [ null ]; + + for (var i = 1; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var texture in this.list) + { + args[0] = this.list[texture]; + + callback.apply(scope, args); + } + }, + + /** + * Returns an array of all active Tweens and Timelines in the Tween Manager. + * + * @method Phaser.Tweens.TweenManager#getAllTweens + * @since 3.0.0 + * + * @return {Phaser.Tweens.Tween[]} A new array containing references to all active Tweens and Timelines. + */ + getAllTweens: function () + { + var list = this._active; + var output = []; + + for (var i = 0; i < list.length; i++) + { + output.push(list[i]); + } + + return output; + }, + + /** + * Returns the scale of the time delta for all Tweens and Timelines owned by this Tween Manager. + * + * @method Phaser.Tweens.TweenManager#getGlobalTimeScale + * @since 3.0.0 + * + * @return {number} The scale of the time delta, usually 1. + */ + getGlobalTimeScale: function () + { + return this.timeScale; + }, + + /** + * Returns an array of all Tweens or Timelines in the Tween Manager which affect the given target or array of targets. + * + * @method Phaser.Tweens.TweenManager#getTweensOf + * @since 3.0.0 + * + * @param {(object|array)} target - The target to look for. Provide an array to look for multiple targets. + * + * @return {Phaser.Tweens.Tween[]} A new array containing all Tweens and Timelines which affect the given target(s). + */ + getTweensOf: function (target) + { + var list = this._active; + var tween; + var output = []; + var i; + + if (Array.isArray(target)) + { + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + for (var t = 0; t < target.length; t++) + { + if (tween.hasTarget(target[t])) + { + output.push(tween); + } + } + } + } + else + { + for (i = 0; i < list.length; i++) + { + tween = list[i]; + + if (tween.hasTarget(target)) + { + output.push(tween); + } + } + } + + return output; + }, + + /** + * Checks if the given object is being affected by a playing Tween. + * + * @method Phaser.Tweens.TweenManager#isTweening + * @since 3.0.0 + * + * @param {object} target - target Phaser.Tweens.Tween object + * + * @return {boolean} returns if target tween object is active or not + */ + isTweening: function (target) + { + var list = this._active; + var tween; + + for (var i = 0; i < list.length; i++) + { + tween = list[i]; + + if (tween.hasTarget(target) && tween.isPlaying()) + { + return true; + } + } + + return false; + }, + + /** + * Stops all Tweens in this Tween Manager. They will be removed at the start of the frame. + * + * @method Phaser.Tweens.TweenManager#killAll + * @since 3.0.0 + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + killAll: function () + { + var tweens = this.getAllTweens(); + + for (var i = 0; i < tweens.length; i++) + { + tweens[i].stop(); + } + + return this; + }, + + /** + * Stops all Tweens which affect the given target or array of targets. The Tweens will be removed from the Tween Manager at the start of the frame. + * + * @see {@link #getTweensOf} + * + * @method Phaser.Tweens.TweenManager#killTweensOf + * @since 3.0.0 + * + * @param {(object|array)} target - The target to look for. Provide an array to look for multiple targets. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + killTweensOf: function (target) + { + var tweens = this.getTweensOf(target); + + for (var i = 0; i < tweens.length; i++) + { + tweens[i].stop(); + } + + return this; + }, + + /** + * Pauses all Tweens in this Tween Manager. + * + * @method Phaser.Tweens.TweenManager#pauseAll + * @since 3.0.0 + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + pauseAll: function () + { + var list = this._active; + + for (var i = 0; i < list.length; i++) + { + list[i].pause(); + } + + return this; + }, + + /** + * Resumes all Tweens in this Tween Manager. + * + * @method Phaser.Tweens.TweenManager#resumeAll + * @since 3.0.0 + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + resumeAll: function () + { + var list = this._active; + + for (var i = 0; i < list.length; i++) + { + list[i].resume(); + } + + return this; + }, + + /** + * Sets a new scale of the time delta for this Tween Manager. + * + * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Tween Manager and all Tweens it owns. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing all Tweens. + * + * @method Phaser.Tweens.TweenManager#setGlobalTimeScale + * @since 3.0.0 + * + * @param {number} value - The new scale of the time delta, where 1 is the normal speed. + * + * @return {Phaser.Tweens.TweenManager} This Tween Manager. + */ + setGlobalTimeScale: function (value) + { + this.timeScale = value; + + return this; + }, + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + * + * @method Phaser.Tweens.TweenManager#shutdown + * @since 3.0.0 + */ + shutdown: function () + { + this.killAll(); + + this._add = []; + this._pending = []; + this._active = []; + this._destroy = []; + + this._toProcess = 0; + + var eventEmitter = this.systems.events; + + eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this); + eventEmitter.off(SceneEvents.UPDATE, this.update, this); + eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); + }, + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + * + * @method Phaser.Tweens.TweenManager#destroy + * @since 3.0.0 + */ + destroy: function () + { + this.shutdown(); + + this.scene.sys.events.off(SceneEvents.START, this.start, this); + + this.scene = null; + this.systems = null; + } + +}); + +PluginCache.register('TweenManager', TweenManager, 'tweens'); + +module.exports = TweenManager; diff --git a/src/tweens/builders/GetBoolean.js b/src/tweens/builders/GetBoolean.js index 7de2bd46e..ba95c1367 100644 --- a/src/tweens/builders/GetBoolean.js +++ b/src/tweens/builders/GetBoolean.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Retrieves the value of the given key from an object. - * - * @function Phaser.Tweens.Builders.GetBoolean - * @since 3.0.0 - * - * @param {object} source - The object to retrieve the value from. - * @param {string} key - The key to look for in the `source` object. - * @param {*} defaultValue - The default value to return if the `key` doesn't exist or if no `source` object is provided. - * - * @return {*} The retrieved value. - */ -var GetBoolean = function (source, key, defaultValue) -{ - if (!source) - { - return defaultValue; - } - else if (source.hasOwnProperty(key)) - { - return source[key]; - } - else - { - return defaultValue; - } -}; - -module.exports = GetBoolean; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Retrieves the value of the given key from an object. + * + * @function Phaser.Tweens.Builders.GetBoolean + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @param {string} key - The key to look for in the `source` object. + * @param {*} defaultValue - The default value to return if the `key` doesn't exist or if no `source` object is provided. + * + * @return {*} The retrieved value. + */ +var GetBoolean = function (source, key, defaultValue) +{ + if (!source) + { + return defaultValue; + } + else if (source.hasOwnProperty(key)) + { + return source[key]; + } + else + { + return defaultValue; + } +}; + +module.exports = GetBoolean; diff --git a/src/tweens/builders/GetEaseFunction.js b/src/tweens/builders/GetEaseFunction.js index 60fadae50..7497dcf46 100644 --- a/src/tweens/builders/GetEaseFunction.js +++ b/src/tweens/builders/GetEaseFunction.js @@ -1,103 +1,103 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var EaseMap = require('../../math/easing/EaseMap'); -var UppercaseFirst = require('../../utils/string/UppercaseFirst'); - -/** - * This internal function is used to return the correct ease function for a Tween. - * - * It can take a variety of input, including an EaseMap based string, or a custom function. - * - * @function Phaser.Tweens.Builders.GetEaseFunction - * @since 3.0.0 - * - * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. - * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. - * - * @return {function} The ease function. - */ -var GetEaseFunction = function (ease, easeParams) -{ - // Default ease function - var easeFunction = EaseMap.Power0; - - // Prepare ease function - if (typeof ease === 'string') - { - // String based look-up - - // 1) They specified it correctly - if (EaseMap.hasOwnProperty(ease)) - { - easeFunction = EaseMap[ease]; - } - else - { - // Do some string manipulation to try and find it - var direction = ''; - - if (ease.indexOf('.')) - { - // quad.in = Quad.easeIn - // quad.out = Quad.easeOut - // quad.inout = Quad.easeInOut - - direction = ease.substr(ease.indexOf('.') + 1); - - if (direction.toLowerCase() === 'in') - { - direction = 'easeIn'; - } - else if (direction.toLowerCase() === 'out') - { - direction = 'easeOut'; - } - else if (direction.toLowerCase() === 'inout') - { - direction = 'easeInOut'; - } - } - - ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); - - if (EaseMap.hasOwnProperty(ease)) - { - easeFunction = EaseMap[ease]; - } - } - } - else if (typeof ease === 'function') - { - // Custom function - easeFunction = ease; - } - else if (Array.isArray(ease) && ease.length === 4) - { - // Bezier function (TODO) - } - - // No custom ease parameters? - if (!easeParams) - { - // Return ease function - return easeFunction; - } - - var cloneParams = easeParams.slice(0); - - cloneParams.unshift(0); - - // Return ease function with custom ease parameters - return function (v) - { - cloneParams[0] = v; - - return easeFunction.apply(this, cloneParams); - }; -}; - -module.exports = GetEaseFunction; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var EaseMap = require('../../math/easing/EaseMap'); +var UppercaseFirst = require('../../utils/string/UppercaseFirst'); + +/** + * This internal function is used to return the correct ease function for a Tween. + * + * It can take a variety of input, including an EaseMap based string, or a custom function. + * + * @function Phaser.Tweens.Builders.GetEaseFunction + * @since 3.0.0 + * + * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function. + * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease. + * + * @return {function} The ease function. + */ +var GetEaseFunction = function (ease, easeParams) +{ + // Default ease function + var easeFunction = EaseMap.Power0; + + // Prepare ease function + if (typeof ease === 'string') + { + // String based look-up + + // 1) They specified it correctly + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + else + { + // Do some string manipulation to try and find it + var direction = ''; + + if (ease.indexOf('.')) + { + // quad.in = Quad.easeIn + // quad.out = Quad.easeOut + // quad.inout = Quad.easeInOut + + direction = ease.substr(ease.indexOf('.') + 1); + + if (direction.toLowerCase() === 'in') + { + direction = 'easeIn'; + } + else if (direction.toLowerCase() === 'out') + { + direction = 'easeOut'; + } + else if (direction.toLowerCase() === 'inout') + { + direction = 'easeInOut'; + } + } + + ease = UppercaseFirst(ease.substr(0, ease.indexOf('.') + 1) + direction); + + if (EaseMap.hasOwnProperty(ease)) + { + easeFunction = EaseMap[ease]; + } + } + } + else if (typeof ease === 'function') + { + // Custom function + easeFunction = ease; + } + else if (Array.isArray(ease) && ease.length === 4) + { + // Bezier function (TODO) + } + + // No custom ease parameters? + if (!easeParams) + { + // Return ease function + return easeFunction; + } + + var cloneParams = easeParams.slice(0); + + cloneParams.unshift(0); + + // Return ease function with custom ease parameters + return function (v) + { + cloneParams[0] = v; + + return easeFunction.apply(this, cloneParams); + }; +}; + +module.exports = GetEaseFunction; diff --git a/src/tweens/builders/GetNewValue.js b/src/tweens/builders/GetNewValue.js index 0db1a09a6..cf00aacdb 100644 --- a/src/tweens/builders/GetNewValue.js +++ b/src/tweens/builders/GetNewValue.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Internal function used by the Tween Builder to create a function that will return - * the given value from the source. - * - * @function Phaser.Tweens.Builders.GetNewValue - * @since 3.0.0 - * - * @param {any} source - The source object to get the value from. - * @param {string} key - The property to get from the source. - * @param {any} defaultValue - A default value to return should the source not have the property set. - * - * @return {function} A function which when called will return the property value from the source. - */ -var GetNewValue = function (source, key, defaultValue) -{ - var valueCallback; - - if (source.hasOwnProperty(key)) - { - var t = typeof(source[key]); - - if (t === 'function') - { - valueCallback = function (target, targetKey, value, targetIndex, totalTargets, tween) - { - return source[key](target, targetKey, value, targetIndex, totalTargets, tween); - }; - } - else - { - valueCallback = function () - { - return source[key]; - }; - } - } - else if (typeof defaultValue === 'function') - { - valueCallback = defaultValue; - } - else - { - valueCallback = function () - { - return defaultValue; - }; - } - - return valueCallback; -}; - -module.exports = GetNewValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Internal function used by the Tween Builder to create a function that will return + * the given value from the source. + * + * @function Phaser.Tweens.Builders.GetNewValue + * @since 3.0.0 + * + * @param {any} source - The source object to get the value from. + * @param {string} key - The property to get from the source. + * @param {any} defaultValue - A default value to return should the source not have the property set. + * + * @return {function} A function which when called will return the property value from the source. + */ +var GetNewValue = function (source, key, defaultValue) +{ + var valueCallback; + + if (source.hasOwnProperty(key)) + { + var t = typeof(source[key]); + + if (t === 'function') + { + valueCallback = function (target, targetKey, value, targetIndex, totalTargets, tween) + { + return source[key](target, targetKey, value, targetIndex, totalTargets, tween); + }; + } + else + { + valueCallback = function () + { + return source[key]; + }; + } + } + else if (typeof defaultValue === 'function') + { + valueCallback = defaultValue; + } + else + { + valueCallback = function () + { + return defaultValue; + }; + } + + return valueCallback; +}; + +module.exports = GetNewValue; diff --git a/src/tweens/builders/GetProps.js b/src/tweens/builders/GetProps.js index 805a31d8f..adee0a2f9 100644 --- a/src/tweens/builders/GetProps.js +++ b/src/tweens/builders/GetProps.js @@ -1,55 +1,55 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RESERVED = require('../tween/ReservedProps'); - -/** - * Internal function used by the Tween Builder to return an array of properties - * that the Tween will be operating on. It takes a tween configuration object - * and then checks that none of the `props` entries start with an underscore, or that - * none of the direct properties are on the Reserved list. - * - * @function Phaser.Tweens.Builders.GetProps - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TweenBuilderConfig} config - The configuration object of the Tween to get the properties from. - * - * @return {string[]} An array of all the properties the tween will operate on. - */ -var GetProps = function (config) -{ - var key; - var keys = []; - - // First see if we have a props object - - if (config.hasOwnProperty('props')) - { - for (key in config.props) - { - // Skip any property that starts with an underscore - if (key.substr(0, 1) !== '_') - { - keys.push({ key: key, value: config.props[key] }); - } - } - } - else - { - for (key in config) - { - // Skip any property that is in the ReservedProps list or that starts with an underscore - if (RESERVED.indexOf(key) === -1 && key.substr(0, 1) !== '_') - { - keys.push({ key: key, value: config[key] }); - } - } - } - - return keys; -}; - -module.exports = GetProps; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RESERVED = require('../tween/ReservedProps'); + +/** + * Internal function used by the Tween Builder to return an array of properties + * that the Tween will be operating on. It takes a tween configuration object + * and then checks that none of the `props` entries start with an underscore, or that + * none of the direct properties are on the Reserved list. + * + * @function Phaser.Tweens.Builders.GetProps + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig} config - The configuration object of the Tween to get the properties from. + * + * @return {string[]} An array of all the properties the tween will operate on. + */ +var GetProps = function (config) +{ + var key; + var keys = []; + + // First see if we have a props object + + if (config.hasOwnProperty('props')) + { + for (key in config.props) + { + // Skip any property that starts with an underscore + if (key.substr(0, 1) !== '_') + { + keys.push({ key: key, value: config.props[key] }); + } + } + } + else + { + for (key in config) + { + // Skip any property that is in the ReservedProps list or that starts with an underscore + if (RESERVED.indexOf(key) === -1 && key.substr(0, 1) !== '_') + { + keys.push({ key: key, value: config[key] }); + } + } + } + + return keys; +}; + +module.exports = GetProps; diff --git a/src/tweens/builders/GetTargets.js b/src/tweens/builders/GetTargets.js index d59a85d3a..d908e7ea9 100644 --- a/src/tweens/builders/GetTargets.js +++ b/src/tweens/builders/GetTargets.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetValue = require('../../utils/object/GetValue'); - -/** - * Extracts an array of targets from a Tween configuration object. - * - * The targets will be looked for in a `targets` property. If it's a function, its return value will be used as the result. - * - * @function Phaser.Tweens.Builders.GetTargets - * @since 3.0.0 - * - * @param {object} config - The configuration object to use. - * - * @return {array} An array of targets (may contain only one element), or `null` if no targets were specified. - */ -var GetTargets = function (config) -{ - var targets = GetValue(config, 'targets', null); - - if (targets === null) - { - return targets; - } - - if (typeof targets === 'function') - { - targets = targets.call(); - } - - if (!Array.isArray(targets)) - { - targets = [ targets ]; - } - - return targets; -}; - -module.exports = GetTargets; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = require('../../utils/object/GetValue'); + +/** + * Extracts an array of targets from a Tween configuration object. + * + * The targets will be looked for in a `targets` property. If it's a function, its return value will be used as the result. + * + * @function Phaser.Tweens.Builders.GetTargets + * @since 3.0.0 + * + * @param {object} config - The configuration object to use. + * + * @return {array} An array of targets (may contain only one element), or `null` if no targets were specified. + */ +var GetTargets = function (config) +{ + var targets = GetValue(config, 'targets', null); + + if (targets === null) + { + return targets; + } + + if (typeof targets === 'function') + { + targets = targets.call(); + } + + if (!Array.isArray(targets)) + { + targets = [ targets ]; + } + + return targets; +}; + +module.exports = GetTargets; diff --git a/src/tweens/builders/GetTweens.js b/src/tweens/builders/GetTweens.js index 2a22413bf..2703e1bae 100644 --- a/src/tweens/builders/GetTweens.js +++ b/src/tweens/builders/GetTweens.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetValue = require('../../utils/object/GetValue'); - -/** - * Internal function used by the Timeline Builder. - * - * It returns an array of all tweens in the given timeline config. - * - * @function Phaser.Tweens.Builders.GetTweens - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TimelineBuilderConfig} config - The configuration object for the Timeline. - * - * @return {Phaser.Tweens.Tween[]} An array of Tween instances that the Timeline will manage. - */ -var GetTweens = function (config) -{ - var tweens = GetValue(config, 'tweens', null); - - if (tweens === null) - { - return []; - } - else if (typeof tweens === 'function') - { - tweens = tweens.call(); - } - - if (!Array.isArray(tweens)) - { - tweens = [ tweens ]; - } - - return tweens; -}; - -module.exports = GetTweens; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = require('../../utils/object/GetValue'); + +/** + * Internal function used by the Timeline Builder. + * + * It returns an array of all tweens in the given timeline config. + * + * @function Phaser.Tweens.Builders.GetTweens + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} config - The configuration object for the Timeline. + * + * @return {Phaser.Tweens.Tween[]} An array of Tween instances that the Timeline will manage. + */ +var GetTweens = function (config) +{ + var tweens = GetValue(config, 'tweens', null); + + if (tweens === null) + { + return []; + } + else if (typeof tweens === 'function') + { + tweens = tweens.call(); + } + + if (!Array.isArray(tweens)) + { + tweens = [ tweens ]; + } + + return tweens; +}; + +module.exports = GetTweens; diff --git a/src/tweens/builders/GetValueOp.js b/src/tweens/builders/GetValueOp.js index 0ffea67bc..6a0127399 100644 --- a/src/tweens/builders/GetValueOp.js +++ b/src/tweens/builders/GetValueOp.js @@ -1,262 +1,262 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @ignore - */ -function hasGetActive (def) -{ - return (!!def.getActive && typeof def.getActive === 'function'); -} - -/** - * @ignore - */ -function hasGetStart (def) -{ - return (!!def.getStart && typeof def.getStart === 'function'); -} - -/** - * @ignore - */ -function hasGetEnd (def) -{ - return (!!def.getEnd && typeof def.getEnd === 'function'); -} - -/** - * @ignore - */ -function hasGetters (def) -{ - return hasGetStart(def) || hasGetEnd(def) || hasGetActive(def); -} - -/** - * 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. - * - * 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 array of functions, `getActive`, `getStart` and `getEnd`, which return the starting and the ending value of the property based on the provided value. - */ -var GetValueOp = function (key, propertyValue) -{ - var callbacks; - - // The returned value sets what the property will be at the END of the Tween (usually called at the start of the Tween) - var getEnd = function (target, key, value) { return value; }; - - // The returned value sets what the property will be at the START of the Tween (usually called at the end of the Tween) - var getStart = function (target, key, value) { return value; }; - - // What to set the property to the moment the TweenData is invoked - var getActive = null; - - var t = typeof(propertyValue); - - if (t === 'number') - { - // props: { - // x: 400, - // y: 300 - // } - - getEnd = function () - { - return propertyValue; - }; - } - else if (t === 'string') - { - // props: { - // x: '+=400', - // y: '-=300', - // z: '*=2', - // w: '/=2' - // } - - var op = propertyValue[0]; - var num = parseFloat(propertyValue.substr(2)); - - switch (op) - { - case '+': - getEnd = function (target, key, value) - { - return value + num; - }; - break; - - case '-': - getEnd = function (target, key, value) - { - return value - num; - }; - break; - - case '*': - getEnd = function (target, key, value) - { - return value * num; - }; - break; - - case '/': - getEnd = function (target, key, value) - { - return value / num; - }; - break; - - default: - getEnd = function () - { - return parseFloat(propertyValue); - }; - } - } - else if (t === 'function') - { - // The same as setting just the getEnd function and no getStart - - // props: { - // x: function (target, key, value, targetIndex, totalTargets, tween) { return value + 50); }, - // } - - getEnd = propertyValue; - } - else if (t === 'object') - { - if (hasGetters(propertyValue)) - { - /* - x: { - // Called the moment Tween is active. The returned value sets the property on the target immediately. - getActive: function (target, key, value, targetIndex, totalTargets, tween) - { - return value; - }, - - // Called at the start of the Tween. The returned value sets what the property will be at the END of the Tween. - getEnd: function (target, key, value, targetIndex, totalTargets, tween) - { - return value; - }, - - // Called at the end of the Tween. The returned value sets what the property will be at the START of the Tween. - getStart: function (target, key, value, targetIndex, totalTargets, tween) - { - return value; - } - } - */ - - if (hasGetActive(propertyValue)) - { - getActive = propertyValue.getActive; - } - - if (hasGetEnd(propertyValue)) - { - getEnd = propertyValue.getEnd; - } - - if (hasGetStart(propertyValue)) - { - getStart = propertyValue.getStart; - } - } - else if (propertyValue.hasOwnProperty('value')) - { - // 'value' may still be a string, function or a number - // props: { - // x: { value: 400, ... }, - // y: { value: 300, ... } - // } - - callbacks = GetValueOp(key, propertyValue.value); - } - else - { - // 'from' and 'to' may still be a string, function or a number - // props: { - // x: { from: 400, to: 600 }, - // y: { from: 300, to: 500 } - // } - - // Same as above, but the 'start' value is set immediately on the target - // props: { - // x: { start: 400, to: 600 }, - // y: { start: 300, to: 500 } - // } - - // 'start' value is set immediately, then it goes 'from' to 'to' during the tween - // props: { - // x: { start: 200, from: 400, to: 600 }, - // y: { start: 300, from: 300, to: 500 } - // } - - var hasTo = propertyValue.hasOwnProperty('to'); - var hasFrom = propertyValue.hasOwnProperty('from'); - var hasStart = propertyValue.hasOwnProperty('start'); - - if (hasTo && (hasFrom || hasStart)) - { - callbacks = GetValueOp(key, propertyValue.to); - - if (hasStart) - { - var startCallbacks = GetValueOp(key, propertyValue.start); - - callbacks.getActive = startCallbacks.getEnd; - } - - if (hasFrom) - { - var fromCallbacks = GetValueOp(key, propertyValue.from); - - callbacks.getStart = fromCallbacks.getEnd; - } - } - } - } - - // If callback not set by the else if block above then set it here and return it - if (!callbacks) - { - callbacks = { - getActive: getActive, - getEnd: getEnd, - getStart: getStart - }; - } - - return callbacks; -}; - -module.exports = GetValueOp; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function hasGetActive (def) +{ + return (!!def.getActive && typeof def.getActive === 'function'); +} + +/** + * @ignore + */ +function hasGetStart (def) +{ + return (!!def.getStart && typeof def.getStart === 'function'); +} + +/** + * @ignore + */ +function hasGetEnd (def) +{ + return (!!def.getEnd && typeof def.getEnd === 'function'); +} + +/** + * @ignore + */ +function hasGetters (def) +{ + return hasGetStart(def) || hasGetEnd(def) || hasGetActive(def); +} + +/** + * 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. + * + * 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 array of functions, `getActive`, `getStart` and `getEnd`, which return the starting and the ending value of the property based on the provided value. + */ +var GetValueOp = function (key, propertyValue) +{ + var callbacks; + + // The returned value sets what the property will be at the END of the Tween (usually called at the start of the Tween) + var getEnd = function (target, key, value) { return value; }; + + // The returned value sets what the property will be at the START of the Tween (usually called at the end of the Tween) + var getStart = function (target, key, value) { return value; }; + + // What to set the property to the moment the TweenData is invoked + var getActive = null; + + var t = typeof(propertyValue); + + if (t === 'number') + { + // props: { + // x: 400, + // y: 300 + // } + + getEnd = function () + { + return propertyValue; + }; + } + else if (t === 'string') + { + // props: { + // x: '+=400', + // y: '-=300', + // z: '*=2', + // w: '/=2' + // } + + var op = propertyValue[0]; + var num = parseFloat(propertyValue.substr(2)); + + switch (op) + { + case '+': + getEnd = function (target, key, value) + { + return value + num; + }; + break; + + case '-': + getEnd = function (target, key, value) + { + return value - num; + }; + break; + + case '*': + getEnd = function (target, key, value) + { + return value * num; + }; + break; + + case '/': + getEnd = function (target, key, value) + { + return value / num; + }; + break; + + default: + getEnd = function () + { + return parseFloat(propertyValue); + }; + } + } + else if (t === 'function') + { + // The same as setting just the getEnd function and no getStart + + // props: { + // x: function (target, key, value, targetIndex, totalTargets, tween) { return value + 50); }, + // } + + getEnd = propertyValue; + } + else if (t === 'object') + { + if (hasGetters(propertyValue)) + { + /* + x: { + // Called the moment Tween is active. The returned value sets the property on the target immediately. + getActive: function (target, key, value, targetIndex, totalTargets, tween) + { + return value; + }, + + // Called at the start of the Tween. The returned value sets what the property will be at the END of the Tween. + getEnd: function (target, key, value, targetIndex, totalTargets, tween) + { + return value; + }, + + // Called at the end of the Tween. The returned value sets what the property will be at the START of the Tween. + getStart: function (target, key, value, targetIndex, totalTargets, tween) + { + return value; + } + } + */ + + if (hasGetActive(propertyValue)) + { + getActive = propertyValue.getActive; + } + + if (hasGetEnd(propertyValue)) + { + getEnd = propertyValue.getEnd; + } + + if (hasGetStart(propertyValue)) + { + getStart = propertyValue.getStart; + } + } + else if (propertyValue.hasOwnProperty('value')) + { + // 'value' may still be a string, function or a number + // props: { + // x: { value: 400, ... }, + // y: { value: 300, ... } + // } + + callbacks = GetValueOp(key, propertyValue.value); + } + else + { + // 'from' and 'to' may still be a string, function or a number + // props: { + // x: { from: 400, to: 600 }, + // y: { from: 300, to: 500 } + // } + + // Same as above, but the 'start' value is set immediately on the target + // props: { + // x: { start: 400, to: 600 }, + // y: { start: 300, to: 500 } + // } + + // 'start' value is set immediately, then it goes 'from' to 'to' during the tween + // props: { + // x: { start: 200, from: 400, to: 600 }, + // y: { start: 300, from: 300, to: 500 } + // } + + var hasTo = propertyValue.hasOwnProperty('to'); + var hasFrom = propertyValue.hasOwnProperty('from'); + var hasStart = propertyValue.hasOwnProperty('start'); + + if (hasTo && (hasFrom || hasStart)) + { + callbacks = GetValueOp(key, propertyValue.to); + + if (hasStart) + { + var startCallbacks = GetValueOp(key, propertyValue.start); + + callbacks.getActive = startCallbacks.getEnd; + } + + if (hasFrom) + { + var fromCallbacks = GetValueOp(key, propertyValue.from); + + callbacks.getStart = fromCallbacks.getEnd; + } + } + } + } + + // If callback not set by the else if block above then set it here and return it + if (!callbacks) + { + callbacks = { + getActive: getActive, + getEnd: getEnd, + getStart: getStart + }; + } + + return callbacks; +}; + +module.exports = GetValueOp; diff --git a/src/tweens/builders/NumberTweenBuilder.js b/src/tweens/builders/NumberTweenBuilder.js index dce16f939..828b87988 100644 --- a/src/tweens/builders/NumberTweenBuilder.js +++ b/src/tweens/builders/NumberTweenBuilder.js @@ -1,124 +1,124 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Defaults = require('../tween/Defaults'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetBoolean = require('./GetBoolean'); -var GetEaseFunction = require('./GetEaseFunction'); -var GetNewValue = require('./GetNewValue'); -var GetValue = require('../../utils/object/GetValue'); -var GetValueOp = require('./GetValueOp'); -var Tween = require('../tween/Tween'); -var TweenData = require('../tween/TweenData'); - -/** - * Creates a new Number Tween. - * - * @function Phaser.Tweens.Builders.NumberTweenBuilder - * @since 3.0.0 - * - * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - The owner of the new Tween. - * @param {Phaser.Types.Tweens.NumberTweenBuilderConfig} config - Configuration for the new Tween. - * @param {Phaser.Types.Tweens.TweenConfigDefaults} defaults - Tween configuration defaults. - * - * @return {Phaser.Tweens.Tween} The new tween. - */ -var NumberTweenBuilder = function (parent, config, defaults) -{ - if (defaults === undefined) - { - defaults = Defaults; - } - - // var tween = this.tweens.addCounter({ - // from: 100, - // to: 200, - // ... (normal tween properties) - // }) - // - // Then use it in your game via: - // - // tween.getValue() - - var from = GetValue(config, 'from', 0); - var to = GetValue(config, 'to', 1); - - var targets = [ { value: from } ]; - - var delay = GetNewValue(config, 'delay', defaults.delay); - var duration = GetNewValue(config, 'duration', defaults.duration); - var easeParams = GetValue(config, 'easeParams', defaults.easeParams); - var ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), easeParams); - var hold = GetNewValue(config, 'hold', defaults.hold); - var repeat = GetNewValue(config, 'repeat', defaults.repeat); - var repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); - var yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); - - var data = []; - - var ops = GetValueOp('value', to); - - var tweenData = TweenData( - targets[0], - 0, - 'value', - ops.getEnd, - ops.getStart, - ops.getActive, - ease, - delay, - duration, - yoyo, - hold, - repeat, - repeatDelay, - false, - false - ); - - tweenData.start = from; - tweenData.current = from; - tweenData.to = to; - - data.push(tweenData); - - var tween = new Tween(parent, data, targets); - - tween.offset = GetAdvancedValue(config, 'offset', null); - tween.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); - tween.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); - tween.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); - tween.paused = GetBoolean(config, 'paused', false); - tween.useFrames = GetBoolean(config, 'useFrames', false); - - // Set the Callbacks - var scope = GetValue(config, 'callbackScope', tween); - - // Callback parameters: 0 = a reference to the Tween itself, 1 = the target/s of the Tween, ... your own params - var tweenArray = [ tween, null ]; - - var callbacks = Tween.TYPES; - - for (var i = 0; i < callbacks.length; i++) - { - var type = callbacks[i]; - - var callback = GetValue(config, type, false); - - if (callback) - { - var callbackScope = GetValue(config, type + 'Scope', scope); - var callbackParams = GetValue(config, type + 'Params', []); - - // The null is reset to be the Tween target - tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope); - } - } - - return tween; -}; - -module.exports = NumberTweenBuilder; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Defaults = require('../tween/Defaults'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetBoolean = require('./GetBoolean'); +var GetEaseFunction = require('./GetEaseFunction'); +var GetNewValue = require('./GetNewValue'); +var GetValue = require('../../utils/object/GetValue'); +var GetValueOp = require('./GetValueOp'); +var Tween = require('../tween/Tween'); +var TweenData = require('../tween/TweenData'); + +/** + * Creates a new Number Tween. + * + * @function Phaser.Tweens.Builders.NumberTweenBuilder + * @since 3.0.0 + * + * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - The owner of the new Tween. + * @param {Phaser.Types.Tweens.NumberTweenBuilderConfig} config - Configuration for the new Tween. + * @param {Phaser.Types.Tweens.TweenConfigDefaults} defaults - Tween configuration defaults. + * + * @return {Phaser.Tweens.Tween} The new tween. + */ +var NumberTweenBuilder = function (parent, config, defaults) +{ + if (defaults === undefined) + { + defaults = Defaults; + } + + // var tween = this.tweens.addCounter({ + // from: 100, + // to: 200, + // ... (normal tween properties) + // }) + // + // Then use it in your game via: + // + // tween.getValue() + + var from = GetValue(config, 'from', 0); + var to = GetValue(config, 'to', 1); + + var targets = [ { value: from } ]; + + var delay = GetNewValue(config, 'delay', defaults.delay); + var duration = GetNewValue(config, 'duration', defaults.duration); + var easeParams = GetValue(config, 'easeParams', defaults.easeParams); + var ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), easeParams); + var hold = GetNewValue(config, 'hold', defaults.hold); + var repeat = GetNewValue(config, 'repeat', defaults.repeat); + var repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); + var yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); + + var data = []; + + var ops = GetValueOp('value', to); + + var tweenData = TweenData( + targets[0], + 0, + 'value', + ops.getEnd, + ops.getStart, + ops.getActive, + ease, + delay, + duration, + yoyo, + hold, + repeat, + repeatDelay, + false, + false + ); + + tweenData.start = from; + tweenData.current = from; + tweenData.to = to; + + data.push(tweenData); + + var tween = new Tween(parent, data, targets); + + tween.offset = GetAdvancedValue(config, 'offset', null); + tween.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); + tween.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); + tween.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); + tween.paused = GetBoolean(config, 'paused', false); + tween.useFrames = GetBoolean(config, 'useFrames', false); + + // Set the Callbacks + var scope = GetValue(config, 'callbackScope', tween); + + // Callback parameters: 0 = a reference to the Tween itself, 1 = the target/s of the Tween, ... your own params + var tweenArray = [ tween, null ]; + + var callbacks = Tween.TYPES; + + for (var i = 0; i < callbacks.length; i++) + { + var type = callbacks[i]; + + var callback = GetValue(config, type, false); + + if (callback) + { + var callbackScope = GetValue(config, type + 'Scope', scope); + var callbackParams = GetValue(config, type + 'Params', []); + + // The null is reset to be the Tween target + tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope); + } + } + + return tween; +}; + +module.exports = NumberTweenBuilder; diff --git a/src/tweens/builders/StaggerBuilder.js b/src/tweens/builders/StaggerBuilder.js index 1ba8f1de8..0754377e3 100644 --- a/src/tweens/builders/StaggerBuilder.js +++ b/src/tweens/builders/StaggerBuilder.js @@ -1,240 +1,240 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetEaseFunction = require('./GetEaseFunction'); -var GetValue = require('../../utils/object/GetValue'); -var MATH_CONST = require('../../math/const'); - -/** - * 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} [config] - A Stagger Configuration object. - * - * @return {function} The stagger function. - */ -var StaggerBuilder = function (value, options) -{ - if (options === undefined) { options = {}; } - - var result; - - var start = GetValue(options, 'start', 0); - var ease = GetValue(options, 'ease', null); - var grid = GetValue(options, 'grid', null); - - var from = GetValue(options, 'from', 0); - - var fromFirst = (from === 'first'); - var fromCenter = (from === 'center'); - var fromLast = (from === 'last'); - var fromValue = (typeof(from) === 'number'); - - var isRange = (Array.isArray(value)); - var value1 = (isRange) ? parseFloat(value[0]) : parseFloat(value); - var value2 = (isRange) ? parseFloat(value[1]) : 0; - var maxValue = Math.max(value1, value2); - - if (isRange) - { - start += value1; - } - - if (grid) - { - // Pre-calc the grid to save doing it for ever tweendata update - var gridWidth = grid[0]; - var gridHeight = grid[1]; - - var fromX = 0; - var fromY = 0; - - var distanceX = 0; - var distanceY = 0; - - var gridValues = []; - - if (fromLast) - { - fromX = gridWidth - 1; - fromY = gridHeight - 1; - } - else if (fromValue) - { - fromX = from % gridWidth; - fromY = Math.floor(from / gridWidth); - } - else if (fromCenter) - { - fromX = (gridWidth - 1) / 2; - fromY = (gridHeight - 1) / 2; - } - - var gridMax = MATH_CONST.MIN_SAFE_INTEGER; - - for (var toY = 0; toY < gridHeight; toY++) - { - gridValues[toY] = []; - - for (var toX = 0; toX < gridWidth; toX++) - { - distanceX = fromX - toX; - distanceY = fromY - toY; - - var dist = Math.sqrt(distanceX * distanceX + distanceY * distanceY); - - if (dist > gridMax) - { - gridMax = dist; - } - - gridValues[toY][toX] = dist; - } - } - } - - var easeFunction = (ease) ? GetEaseFunction(ease) : null; - - if (grid) - { - result = function (target, key, value, index) - { - var gridSpace = 0; - var toX = index % gridWidth; - var toY = Math.floor(index / gridWidth); - - if (toX >= 0 && toX < gridWidth && toY >= 0 && toY < gridHeight) - { - gridSpace = gridValues[toY][toX]; - } - - var output; - - if (isRange) - { - var diff = (value2 - value1); - - if (easeFunction) - { - output = ((gridSpace / gridMax) * diff) * easeFunction(gridSpace / gridMax); - } - else - { - output = (gridSpace / gridMax) * diff; - } - } - else if (easeFunction) - { - output = (gridSpace * value1) * easeFunction(gridSpace / gridMax); - } - else - { - output = gridSpace * value1; - } - - return output + start; - }; - } - else - { - result = function (target, key, value, index, total) - { - // zero offset - total--; - - var fromIndex; - - if (fromFirst) - { - fromIndex = index; - } - else if (fromCenter) - { - fromIndex = Math.abs((total / 2) - index); - } - else if (fromLast) - { - fromIndex = total - index; - } - else if (fromValue) - { - fromIndex = Math.abs(from - index); - } - - var output; - - if (isRange) - { - var spacing; - - if (fromCenter) - { - spacing = ((value2 - value1) / total) * (fromIndex * 2); - } - else - { - spacing = ((value2 - value1) / total) * fromIndex; - } - - if (easeFunction) - { - output = spacing * easeFunction(fromIndex / total); - } - else - { - output = spacing; - } - } - else if (easeFunction) - { - output = (total * maxValue) * easeFunction(fromIndex / total); - } - else - { - output = fromIndex * value1; - } - - return output + start; - }; - } - - return result; -}; - -module.exports = StaggerBuilder; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetEaseFunction = require('./GetEaseFunction'); +var GetValue = require('../../utils/object/GetValue'); +var MATH_CONST = require('../../math/const'); + +/** + * 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} [config] - A Stagger Configuration object. + * + * @return {function} The stagger function. + */ +var StaggerBuilder = function (value, options) +{ + if (options === undefined) { options = {}; } + + var result; + + var start = GetValue(options, 'start', 0); + var ease = GetValue(options, 'ease', null); + var grid = GetValue(options, 'grid', null); + + var from = GetValue(options, 'from', 0); + + var fromFirst = (from === 'first'); + var fromCenter = (from === 'center'); + var fromLast = (from === 'last'); + var fromValue = (typeof(from) === 'number'); + + var isRange = (Array.isArray(value)); + var value1 = (isRange) ? parseFloat(value[0]) : parseFloat(value); + var value2 = (isRange) ? parseFloat(value[1]) : 0; + var maxValue = Math.max(value1, value2); + + if (isRange) + { + start += value1; + } + + if (grid) + { + // Pre-calc the grid to save doing it for ever tweendata update + var gridWidth = grid[0]; + var gridHeight = grid[1]; + + var fromX = 0; + var fromY = 0; + + var distanceX = 0; + var distanceY = 0; + + var gridValues = []; + + if (fromLast) + { + fromX = gridWidth - 1; + fromY = gridHeight - 1; + } + else if (fromValue) + { + fromX = from % gridWidth; + fromY = Math.floor(from / gridWidth); + } + else if (fromCenter) + { + fromX = (gridWidth - 1) / 2; + fromY = (gridHeight - 1) / 2; + } + + var gridMax = MATH_CONST.MIN_SAFE_INTEGER; + + for (var toY = 0; toY < gridHeight; toY++) + { + gridValues[toY] = []; + + for (var toX = 0; toX < gridWidth; toX++) + { + distanceX = fromX - toX; + distanceY = fromY - toY; + + var dist = Math.sqrt(distanceX * distanceX + distanceY * distanceY); + + if (dist > gridMax) + { + gridMax = dist; + } + + gridValues[toY][toX] = dist; + } + } + } + + var easeFunction = (ease) ? GetEaseFunction(ease) : null; + + if (grid) + { + result = function (target, key, value, index) + { + var gridSpace = 0; + var toX = index % gridWidth; + var toY = Math.floor(index / gridWidth); + + if (toX >= 0 && toX < gridWidth && toY >= 0 && toY < gridHeight) + { + gridSpace = gridValues[toY][toX]; + } + + var output; + + if (isRange) + { + var diff = (value2 - value1); + + if (easeFunction) + { + output = ((gridSpace / gridMax) * diff) * easeFunction(gridSpace / gridMax); + } + else + { + output = (gridSpace / gridMax) * diff; + } + } + else if (easeFunction) + { + output = (gridSpace * value1) * easeFunction(gridSpace / gridMax); + } + else + { + output = gridSpace * value1; + } + + return output + start; + }; + } + else + { + result = function (target, key, value, index, total) + { + // zero offset + total--; + + var fromIndex; + + if (fromFirst) + { + fromIndex = index; + } + else if (fromCenter) + { + fromIndex = Math.abs((total / 2) - index); + } + else if (fromLast) + { + fromIndex = total - index; + } + else if (fromValue) + { + fromIndex = Math.abs(from - index); + } + + var output; + + if (isRange) + { + var spacing; + + if (fromCenter) + { + spacing = ((value2 - value1) / total) * (fromIndex * 2); + } + else + { + spacing = ((value2 - value1) / total) * fromIndex; + } + + if (easeFunction) + { + output = spacing * easeFunction(fromIndex / total); + } + else + { + output = spacing; + } + } + else if (easeFunction) + { + output = (total * maxValue) * easeFunction(fromIndex / total); + } + else + { + output = fromIndex * value1; + } + + return output + start; + }; + } + + return result; +}; + +module.exports = StaggerBuilder; diff --git a/src/tweens/builders/TimelineBuilder.js b/src/tweens/builders/TimelineBuilder.js index 3a554a61f..ddbb66c7b 100644 --- a/src/tweens/builders/TimelineBuilder.js +++ b/src/tweens/builders/TimelineBuilder.js @@ -1,146 +1,146 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = require('../../utils/object/Clone'); -var Defaults = require('../tween/Defaults'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetBoolean = require('./GetBoolean'); -var GetEaseFunction = require('./GetEaseFunction'); -var GetNewValue = require('./GetNewValue'); -var GetTargets = require('./GetTargets'); -var GetTweens = require('./GetTweens'); -var GetValue = require('../../utils/object/GetValue'); -var Timeline = require('../Timeline'); -var TweenBuilder = require('./TweenBuilder'); - -/** - * Builds a Timeline of Tweens based on a configuration object. - * - * @function Phaser.Tweens.Builders.TimelineBuilder - * @since 3.0.0 - * - * @param {Phaser.Tweens.TweenManager} manager - The Tween Manager to which the Timeline will belong. - * @param {Phaser.Types.Tweens.TimelineBuilderConfig} config - The configuration object for the Timeline. - * - * @return {Phaser.Tweens.Timeline} The created Timeline. - */ -var TimelineBuilder = function (manager, config) -{ - var timeline = new Timeline(manager); - - var tweens = GetTweens(config); - - if (tweens.length === 0) - { - timeline.paused = true; - - return timeline; - } - - var defaults = Clone(Defaults); - - defaults.targets = GetTargets(config); - - // totalDuration: If specified each tween in the Timeline is given an equal portion of the totalDuration - - var totalDuration = GetAdvancedValue(config, 'totalDuration', 0); - - if (totalDuration > 0) - { - defaults.duration = Math.floor(totalDuration / tweens.length); - } - else - { - defaults.duration = GetNewValue(config, 'duration', defaults.duration); - } - - defaults.delay = GetNewValue(config, 'delay', defaults.delay); - defaults.easeParams = GetValue(config, 'easeParams', defaults.easeParams); - defaults.ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), defaults.easeParams); - defaults.hold = GetNewValue(config, 'hold', defaults.hold); - defaults.repeat = GetNewValue(config, 'repeat', defaults.repeat); - defaults.repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); - defaults.yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); - defaults.flipX = GetBoolean(config, 'flipX', defaults.flipX); - defaults.flipY = GetBoolean(config, 'flipY', defaults.flipY); - - // Create the Tweens - for (var i = 0; i < tweens.length; i++) - { - timeline.queue(TweenBuilder(timeline, tweens[i], defaults)); - } - - timeline.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); - timeline.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); - timeline.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); - timeline.paused = GetBoolean(config, 'paused', false); - timeline.useFrames = GetBoolean(config, 'useFrames', false); - - // Callbacks - - var scope = GetValue(config, 'callbackScope', timeline); - - var timelineArray = [ timeline ]; - - var onStart = GetValue(config, 'onStart', false); - - // The Start of the Timeline - if (onStart) - { - var onStartScope = GetValue(config, 'onStartScope', scope); - var onStartParams = GetValue(config, 'onStartParams', []); - - timeline.setCallback('onStart', onStart, timelineArray.concat(onStartParams), onStartScope); - } - - var onUpdate = GetValue(config, 'onUpdate', false); - - // Every time the Timeline updates (regardless which Tweens are running) - if (onUpdate) - { - var onUpdateScope = GetValue(config, 'onUpdateScope', scope); - var onUpdateParams = GetValue(config, 'onUpdateParams', []); - - timeline.setCallback('onUpdate', onUpdate, timelineArray.concat(onUpdateParams), onUpdateScope); - } - - var onLoop = GetValue(config, 'onLoop', false); - - // Called when the whole Timeline loops - if (onLoop) - { - var onLoopScope = GetValue(config, 'onLoopScope', scope); - var onLoopParams = GetValue(config, 'onLoopParams', []); - - timeline.setCallback('onLoop', onLoop, timelineArray.concat(onLoopParams), onLoopScope); - } - - var onYoyo = GetValue(config, 'onYoyo', false); - - // Called when a Timeline yoyos - if (onYoyo) - { - var onYoyoScope = GetValue(config, 'onYoyoScope', scope); - var onYoyoParams = GetValue(config, 'onYoyoParams', []); - - timeline.setCallback('onYoyo', onYoyo, timelineArray.concat(null, onYoyoParams), onYoyoScope); - } - - var onComplete = GetValue(config, 'onComplete', false); - - // Called when the Timeline completes, after the completeDelay, etc. - if (onComplete) - { - var onCompleteScope = GetValue(config, 'onCompleteScope', scope); - var onCompleteParams = GetValue(config, 'onCompleteParams', []); - - timeline.setCallback('onComplete', onComplete, timelineArray.concat(onCompleteParams), onCompleteScope); - } - - return timeline; -}; - -module.exports = TimelineBuilder; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = require('../../utils/object/Clone'); +var Defaults = require('../tween/Defaults'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetBoolean = require('./GetBoolean'); +var GetEaseFunction = require('./GetEaseFunction'); +var GetNewValue = require('./GetNewValue'); +var GetTargets = require('./GetTargets'); +var GetTweens = require('./GetTweens'); +var GetValue = require('../../utils/object/GetValue'); +var Timeline = require('../Timeline'); +var TweenBuilder = require('./TweenBuilder'); + +/** + * Builds a Timeline of Tweens based on a configuration object. + * + * @function Phaser.Tweens.Builders.TimelineBuilder + * @since 3.0.0 + * + * @param {Phaser.Tweens.TweenManager} manager - The Tween Manager to which the Timeline will belong. + * @param {Phaser.Types.Tweens.TimelineBuilderConfig} config - The configuration object for the Timeline. + * + * @return {Phaser.Tweens.Timeline} The created Timeline. + */ +var TimelineBuilder = function (manager, config) +{ + var timeline = new Timeline(manager); + + var tweens = GetTweens(config); + + if (tweens.length === 0) + { + timeline.paused = true; + + return timeline; + } + + var defaults = Clone(Defaults); + + defaults.targets = GetTargets(config); + + // totalDuration: If specified each tween in the Timeline is given an equal portion of the totalDuration + + var totalDuration = GetAdvancedValue(config, 'totalDuration', 0); + + if (totalDuration > 0) + { + defaults.duration = Math.floor(totalDuration / tweens.length); + } + else + { + defaults.duration = GetNewValue(config, 'duration', defaults.duration); + } + + defaults.delay = GetNewValue(config, 'delay', defaults.delay); + defaults.easeParams = GetValue(config, 'easeParams', defaults.easeParams); + defaults.ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), defaults.easeParams); + defaults.hold = GetNewValue(config, 'hold', defaults.hold); + defaults.repeat = GetNewValue(config, 'repeat', defaults.repeat); + defaults.repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); + defaults.yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); + defaults.flipX = GetBoolean(config, 'flipX', defaults.flipX); + defaults.flipY = GetBoolean(config, 'flipY', defaults.flipY); + + // Create the Tweens + for (var i = 0; i < tweens.length; i++) + { + timeline.queue(TweenBuilder(timeline, tweens[i], defaults)); + } + + timeline.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); + timeline.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); + timeline.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); + timeline.paused = GetBoolean(config, 'paused', false); + timeline.useFrames = GetBoolean(config, 'useFrames', false); + + // Callbacks + + var scope = GetValue(config, 'callbackScope', timeline); + + var timelineArray = [ timeline ]; + + var onStart = GetValue(config, 'onStart', false); + + // The Start of the Timeline + if (onStart) + { + var onStartScope = GetValue(config, 'onStartScope', scope); + var onStartParams = GetValue(config, 'onStartParams', []); + + timeline.setCallback('onStart', onStart, timelineArray.concat(onStartParams), onStartScope); + } + + var onUpdate = GetValue(config, 'onUpdate', false); + + // Every time the Timeline updates (regardless which Tweens are running) + if (onUpdate) + { + var onUpdateScope = GetValue(config, 'onUpdateScope', scope); + var onUpdateParams = GetValue(config, 'onUpdateParams', []); + + timeline.setCallback('onUpdate', onUpdate, timelineArray.concat(onUpdateParams), onUpdateScope); + } + + var onLoop = GetValue(config, 'onLoop', false); + + // Called when the whole Timeline loops + if (onLoop) + { + var onLoopScope = GetValue(config, 'onLoopScope', scope); + var onLoopParams = GetValue(config, 'onLoopParams', []); + + timeline.setCallback('onLoop', onLoop, timelineArray.concat(onLoopParams), onLoopScope); + } + + var onYoyo = GetValue(config, 'onYoyo', false); + + // Called when a Timeline yoyos + if (onYoyo) + { + var onYoyoScope = GetValue(config, 'onYoyoScope', scope); + var onYoyoParams = GetValue(config, 'onYoyoParams', []); + + timeline.setCallback('onYoyo', onYoyo, timelineArray.concat(null, onYoyoParams), onYoyoScope); + } + + var onComplete = GetValue(config, 'onComplete', false); + + // Called when the Timeline completes, after the completeDelay, etc. + if (onComplete) + { + var onCompleteScope = GetValue(config, 'onCompleteScope', scope); + var onCompleteParams = GetValue(config, 'onCompleteParams', []); + + timeline.setCallback('onComplete', onComplete, timelineArray.concat(onCompleteParams), onCompleteScope); + } + + return timeline; +}; + +module.exports = TimelineBuilder; diff --git a/src/tweens/builders/TweenBuilder.js b/src/tweens/builders/TweenBuilder.js index 3287eaa02..52a267bc3 100644 --- a/src/tweens/builders/TweenBuilder.js +++ b/src/tweens/builders/TweenBuilder.js @@ -1,127 +1,127 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Defaults = require('../tween/Defaults'); -var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); -var GetBoolean = require('./GetBoolean'); -var GetEaseFunction = require('./GetEaseFunction'); -var GetNewValue = require('./GetNewValue'); -var GetProps = require('./GetProps'); -var GetTargets = require('./GetTargets'); -var GetValue = require('../../utils/object/GetValue'); -var GetValueOp = require('./GetValueOp'); -var Tween = require('../tween/Tween'); -var TweenData = require('../tween/TweenData'); - -/** - * Creates a new Tween. - * - * @function Phaser.Tweens.Builders.TweenBuilder - * @since 3.0.0 - * - * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - The owner of the new Tween. - * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - Configuration for the new Tween. - * @param {Phaser.Types.Tweens.TweenConfigDefaults} defaults - Tween configuration defaults. - * - * @return {Phaser.Tweens.Tween} The new tween. - */ -var TweenBuilder = function (parent, config, defaults) -{ - if (defaults === undefined) - { - defaults = Defaults; - } - - // Create arrays of the Targets and the Properties - var targets = (defaults.targets) ? defaults.targets : GetTargets(config); - - // var props = (defaults.props) ? defaults.props : GetProps(config); - var props = GetProps(config); - - // Default Tween values - var delay = GetNewValue(config, 'delay', defaults.delay); - var duration = GetNewValue(config, 'duration', defaults.duration); - var easeParams = GetValue(config, 'easeParams', defaults.easeParams); - var ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), easeParams); - var hold = GetNewValue(config, 'hold', defaults.hold); - var repeat = GetNewValue(config, 'repeat', defaults.repeat); - var repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); - var yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); - var flipX = GetBoolean(config, 'flipX', defaults.flipX); - var flipY = GetBoolean(config, 'flipY', defaults.flipY); - - var data = []; - - // Loop through every property defined in the Tween, i.e.: props { x, y, alpha } - for (var p = 0; p < props.length; p++) - { - var key = props[p].key; - var value = props[p].value; - - // Create 1 TweenData per target, per property - for (var t = 0; t < targets.length; t++) - { - var ops = GetValueOp(key, value); - - var tweenData = TweenData( - targets[t], - t, - key, - ops.getEnd, - ops.getStart, - ops.getActive, - GetEaseFunction(GetValue(value, 'ease', ease), easeParams), - GetNewValue(value, 'delay', delay), - GetNewValue(value, 'duration', duration), - GetBoolean(value, 'yoyo', yoyo), - GetNewValue(value, 'hold', hold), - GetNewValue(value, 'repeat', repeat), - GetNewValue(value, 'repeatDelay', repeatDelay), - GetBoolean(value, 'flipX', flipX), - GetBoolean(value, 'flipY', flipY) - ); - - data.push(tweenData); - } - } - - var tween = new Tween(parent, data, targets); - - tween.offset = GetAdvancedValue(config, 'offset', null); - tween.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); - tween.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); - tween.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); - tween.paused = GetBoolean(config, 'paused', false); - tween.useFrames = GetBoolean(config, 'useFrames', false); - - // Set the Callbacks - var scope = GetValue(config, 'callbackScope', tween); - - // Callback parameters: 0 = a reference to the Tween itself, 1 = the target/s of the Tween, ... your own params - var tweenArray = [ tween, null ]; - - var callbacks = Tween.TYPES; - - for (var i = 0; i < callbacks.length; i++) - { - var type = callbacks[i]; - - var callback = GetValue(config, type, false); - - if (callback) - { - var callbackScope = GetValue(config, type + 'Scope', scope); - var callbackParams = GetValue(config, type + 'Params', []); - - // The null is reset to be the Tween target - tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope); - } - } - - return tween; -}; - -module.exports = TweenBuilder; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Defaults = require('../tween/Defaults'); +var GetAdvancedValue = require('../../utils/object/GetAdvancedValue'); +var GetBoolean = require('./GetBoolean'); +var GetEaseFunction = require('./GetEaseFunction'); +var GetNewValue = require('./GetNewValue'); +var GetProps = require('./GetProps'); +var GetTargets = require('./GetTargets'); +var GetValue = require('../../utils/object/GetValue'); +var GetValueOp = require('./GetValueOp'); +var Tween = require('../tween/Tween'); +var TweenData = require('../tween/TweenData'); + +/** + * Creates a new Tween. + * + * @function Phaser.Tweens.Builders.TweenBuilder + * @since 3.0.0 + * + * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - The owner of the new Tween. + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - Configuration for the new Tween. + * @param {Phaser.Types.Tweens.TweenConfigDefaults} defaults - Tween configuration defaults. + * + * @return {Phaser.Tweens.Tween} The new tween. + */ +var TweenBuilder = function (parent, config, defaults) +{ + if (defaults === undefined) + { + defaults = Defaults; + } + + // Create arrays of the Targets and the Properties + var targets = (defaults.targets) ? defaults.targets : GetTargets(config); + + // var props = (defaults.props) ? defaults.props : GetProps(config); + var props = GetProps(config); + + // Default Tween values + var delay = GetNewValue(config, 'delay', defaults.delay); + var duration = GetNewValue(config, 'duration', defaults.duration); + var easeParams = GetValue(config, 'easeParams', defaults.easeParams); + var ease = GetEaseFunction(GetValue(config, 'ease', defaults.ease), easeParams); + var hold = GetNewValue(config, 'hold', defaults.hold); + var repeat = GetNewValue(config, 'repeat', defaults.repeat); + var repeatDelay = GetNewValue(config, 'repeatDelay', defaults.repeatDelay); + var yoyo = GetBoolean(config, 'yoyo', defaults.yoyo); + var flipX = GetBoolean(config, 'flipX', defaults.flipX); + var flipY = GetBoolean(config, 'flipY', defaults.flipY); + + var data = []; + + // Loop through every property defined in the Tween, i.e.: props { x, y, alpha } + for (var p = 0; p < props.length; p++) + { + var key = props[p].key; + var value = props[p].value; + + // Create 1 TweenData per target, per property + for (var t = 0; t < targets.length; t++) + { + var ops = GetValueOp(key, value); + + var tweenData = TweenData( + targets[t], + t, + key, + ops.getEnd, + ops.getStart, + ops.getActive, + GetEaseFunction(GetValue(value, 'ease', ease), easeParams), + GetNewValue(value, 'delay', delay), + GetNewValue(value, 'duration', duration), + GetBoolean(value, 'yoyo', yoyo), + GetNewValue(value, 'hold', hold), + GetNewValue(value, 'repeat', repeat), + GetNewValue(value, 'repeatDelay', repeatDelay), + GetBoolean(value, 'flipX', flipX), + GetBoolean(value, 'flipY', flipY) + ); + + data.push(tweenData); + } + } + + var tween = new Tween(parent, data, targets); + + tween.offset = GetAdvancedValue(config, 'offset', null); + tween.completeDelay = GetAdvancedValue(config, 'completeDelay', 0); + tween.loop = Math.round(GetAdvancedValue(config, 'loop', 0)); + tween.loopDelay = Math.round(GetAdvancedValue(config, 'loopDelay', 0)); + tween.paused = GetBoolean(config, 'paused', false); + tween.useFrames = GetBoolean(config, 'useFrames', false); + + // Set the Callbacks + var scope = GetValue(config, 'callbackScope', tween); + + // Callback parameters: 0 = a reference to the Tween itself, 1 = the target/s of the Tween, ... your own params + var tweenArray = [ tween, null ]; + + var callbacks = Tween.TYPES; + + for (var i = 0; i < callbacks.length; i++) + { + var type = callbacks[i]; + + var callback = GetValue(config, type, false); + + if (callback) + { + var callbackScope = GetValue(config, type + 'Scope', scope); + var callbackParams = GetValue(config, type + 'Params', []); + + // The null is reset to be the Tween target + tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope); + } + } + + return tween; +}; + +module.exports = TweenBuilder; diff --git a/src/tweens/builders/index.js b/src/tweens/builders/index.js index 00c22a0fe..237e70165 100644 --- a/src/tweens/builders/index.js +++ b/src/tweens/builders/index.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tweens.Builders - */ - -module.exports = { - - GetBoolean: require('./GetBoolean'), - GetEaseFunction: require('./GetEaseFunction'), - GetNewValue: require('./GetNewValue'), - GetProps: require('./GetProps'), - GetTargets: require('./GetTargets'), - GetTweens: require('./GetTweens'), - GetValueOp: require('./GetValueOp'), - NumberTweenBuilder: require('./NumberTweenBuilder'), - StaggerBuilder: require('./StaggerBuilder'), - TimelineBuilder: require('./TimelineBuilder'), - TweenBuilder: require('./TweenBuilder') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tweens.Builders + */ + +module.exports = { + + GetBoolean: require('./GetBoolean'), + GetEaseFunction: require('./GetEaseFunction'), + GetNewValue: require('./GetNewValue'), + GetProps: require('./GetProps'), + GetTargets: require('./GetTargets'), + GetTweens: require('./GetTweens'), + GetValueOp: require('./GetValueOp'), + NumberTweenBuilder: require('./NumberTweenBuilder'), + StaggerBuilder: require('./StaggerBuilder'), + TimelineBuilder: require('./TimelineBuilder'), + TweenBuilder: require('./TweenBuilder') + +}; diff --git a/src/tweens/events/TIMELINE_COMPLETE_EVENT.js b/src/tweens/events/TIMELINE_COMPLETE_EVENT.js index 9d0b9b495..1047f505a 100644 --- a/src/tweens/events/TIMELINE_COMPLETE_EVENT.js +++ b/src/tweens/events/TIMELINE_COMPLETE_EVENT.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Timeline Complete Event. - * - * This event is dispatched by a Tween Timeline when it completes playback. - * - * Listen to it from a Timeline instance using `Timeline.on('complete', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('complete', listener); - * timeline.play(); - * ``` - * - * @event Phaser.Tweens.Events#TIMELINE_COMPLETE - * @since 3.0.0 - * - * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. - */ -module.exports = 'complete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Complete Event. + * + * This event is dispatched by a Tween Timeline when it completes playback. + * + * Listen to it from a Timeline instance using `Timeline.on('complete', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('complete', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_COMPLETE + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'complete'; diff --git a/src/tweens/events/TIMELINE_LOOP_EVENT.js b/src/tweens/events/TIMELINE_LOOP_EVENT.js index 402f4af89..8bbb94cfc 100644 --- a/src/tweens/events/TIMELINE_LOOP_EVENT.js +++ b/src/tweens/events/TIMELINE_LOOP_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Timeline Loop Event. - * - * This event is dispatched by a Tween Timeline every time it loops. - * - * Listen to it from a Timeline instance using `Timeline.on('loop', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * loop: 4, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('loop', listener); - * timeline.play(); - * ``` - * - * @event Phaser.Tweens.Events#TIMELINE_LOOP - * @since 3.0.0 - * - * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. - */ -module.exports = 'loop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Loop Event. + * + * This event is dispatched by a Tween Timeline every time it loops. + * + * Listen to it from a Timeline instance using `Timeline.on('loop', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * loop: 4, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('loop', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_LOOP + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'loop'; diff --git a/src/tweens/events/TIMELINE_PAUSE_EVENT.js b/src/tweens/events/TIMELINE_PAUSE_EVENT.js index b2e74994b..3e7627eb8 100644 --- a/src/tweens/events/TIMELINE_PAUSE_EVENT.js +++ b/src/tweens/events/TIMELINE_PAUSE_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Timeline Pause Event. - * - * This event is dispatched by a Tween Timeline when it is paused. - * - * Listen to it from a Timeline instance using `Timeline.on('pause', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('pause', listener); - * // At some point later ... - * timeline.pause(); - * ``` - * - * @event Phaser.Tweens.Events#TIMELINE_PAUSE - * @since 3.0.0 - * - * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. - */ -module.exports = 'pause'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Pause Event. + * + * This event is dispatched by a Tween Timeline when it is paused. + * + * Listen to it from a Timeline instance using `Timeline.on('pause', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('pause', listener); + * // At some point later ... + * timeline.pause(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_PAUSE + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'pause'; diff --git a/src/tweens/events/TIMELINE_RESUME_EVENT.js b/src/tweens/events/TIMELINE_RESUME_EVENT.js index e05896652..f26db9782 100644 --- a/src/tweens/events/TIMELINE_RESUME_EVENT.js +++ b/src/tweens/events/TIMELINE_RESUME_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Timeline Resume Event. - * - * This event is dispatched by a Tween Timeline when it is resumed from a paused state. - * - * Listen to it from a Timeline instance using `Timeline.on('resume', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('resume', listener); - * // At some point later ... - * timeline.resume(); - * ``` - * - * @event Phaser.Tweens.Events#TIMELINE_RESUME - * @since 3.0.0 - * - * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. - */ -module.exports = 'resume'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Resume Event. + * + * This event is dispatched by a Tween Timeline when it is resumed from a paused state. + * + * Listen to it from a Timeline instance using `Timeline.on('resume', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('resume', listener); + * // At some point later ... + * timeline.resume(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_RESUME + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'resume'; diff --git a/src/tweens/events/TIMELINE_START_EVENT.js b/src/tweens/events/TIMELINE_START_EVENT.js index 33f19bdca..844b4492c 100644 --- a/src/tweens/events/TIMELINE_START_EVENT.js +++ b/src/tweens/events/TIMELINE_START_EVENT.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Timeline Start Event. - * - * This event is dispatched by a Tween Timeline when it starts. - * - * Listen to it from a Timeline instance using `Timeline.on('start', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('start', listener); - * timeline.play(); - * ``` - * - * @event Phaser.Tweens.Events#TIMELINE_START - * @since 3.0.0 - * - * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. - */ -module.exports = 'start'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Start Event. + * + * This event is dispatched by a Tween Timeline when it starts. + * + * Listen to it from a Timeline instance using `Timeline.on('start', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('start', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_START + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'start'; diff --git a/src/tweens/events/TIMELINE_UPDATE_EVENT.js b/src/tweens/events/TIMELINE_UPDATE_EVENT.js index 0d6bccb69..937ac37eb 100644 --- a/src/tweens/events/TIMELINE_UPDATE_EVENT.js +++ b/src/tweens/events/TIMELINE_UPDATE_EVENT.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Timeline Update Event. - * - * This event is dispatched by a Tween Timeline every time it updates, which can happen a lot of times per second, - * so be careful about listening to this event unless you absolutely require it. - * - * Listen to it from a Timeline instance using `Timeline.on('update', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('update', listener); - * timeline.play(); - * ``` - * - * @event Phaser.Tweens.Events#TIMELINE_UPDATE - * @since 3.0.0 - * - * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. - */ -module.exports = 'update'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Timeline Update Event. + * + * This event is dispatched by a Tween Timeline every time it updates, which can happen a lot of times per second, + * so be careful about listening to this event unless you absolutely require it. + * + * Listen to it from a Timeline instance using `Timeline.on('update', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('update', listener); + * timeline.play(); + * ``` + * + * @event Phaser.Tweens.Events#TIMELINE_UPDATE + * @since 3.0.0 + * + * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event. + */ +module.exports = 'update'; diff --git a/src/tweens/events/TWEEN_ACTIVE_EVENT.js b/src/tweens/events/TWEEN_ACTIVE_EVENT.js index b7a0f9f47..550996d19 100644 --- a/src/tweens/events/TWEEN_ACTIVE_EVENT.js +++ b/src/tweens/events/TWEEN_ACTIVE_EVENT.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Active Event. - * - * This event is dispatched by a Tween when it becomes active within the Tween Manager. - * - * An 'active' Tween is one that is now progressing, although it may not yet be updating - * any target properties, due to settings such as `delay`. If you need an event for when - * the Tween starts actually updating its first property, see `TWEEN_START`. - * - * Listen to it from a Tween instance using `Tween.on('active', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000 - * }); - * tween.on('active', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_ACTIVE - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {any[]} targets - An array of references to the target/s the Tween is operating on. - */ -module.exports = 'active'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Active Event. + * + * This event is dispatched by a Tween when it becomes active within the Tween Manager. + * + * An 'active' Tween is one that is now progressing, although it may not yet be updating + * any target properties, due to settings such as `delay`. If you need an event for when + * the Tween starts actually updating its first property, see `TWEEN_START`. + * + * Listen to it from a Tween instance using `Tween.on('active', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('active', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_ACTIVE + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'active'; diff --git a/src/tweens/events/TWEEN_COMPLETE_EVENT.js b/src/tweens/events/TWEEN_COMPLETE_EVENT.js index e3f81d3c0..193cbb789 100644 --- a/src/tweens/events/TWEEN_COMPLETE_EVENT.js +++ b/src/tweens/events/TWEEN_COMPLETE_EVENT.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Complete Event. - * - * This event is dispatched by a Tween when it completes playback entirely, factoring in repeats and loops. - * - * If the Tween has been set to loop or repeat infinitely, this event will not be dispatched - * unless the `Tween.stop` method is called. - * - * If a Tween has a `completeDelay` set, this event will fire after that delay expires. - * - * Listen to it from a Tween instance using `Tween.on('complete', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000 - * }); - * tween.on('complete', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_COMPLETE - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {any[]} targets - An array of references to the target/s the Tween is operating on. - */ -module.exports = 'complete'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Complete Event. + * + * This event is dispatched by a Tween when it completes playback entirely, factoring in repeats and loops. + * + * If the Tween has been set to loop or repeat infinitely, this event will not be dispatched + * unless the `Tween.stop` method is called. + * + * If a Tween has a `completeDelay` set, this event will fire after that delay expires. + * + * Listen to it from a Tween instance using `Tween.on('complete', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('complete', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_COMPLETE + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'complete'; diff --git a/src/tweens/events/TWEEN_LOOP_EVENT.js b/src/tweens/events/TWEEN_LOOP_EVENT.js index bd08dcb55..7524f9415 100644 --- a/src/tweens/events/TWEEN_LOOP_EVENT.js +++ b/src/tweens/events/TWEEN_LOOP_EVENT.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Loop Event. - * - * This event is dispatched by a Tween when it loops. - * - * This event will only be dispatched if the Tween has a loop count set. - * - * If a Tween has a `loopDelay` set, this event will fire after that delay expires. - * - * The difference between `loop` and `repeat` is that `repeat` is a property setting, - * where-as `loop` applies to the entire Tween. - * - * Listen to it from a Tween instance using `Tween.on('loop', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * loop: 6 - * }); - * tween.on('loop', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_LOOP - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {any[]} targets - An array of references to the target/s the Tween is operating on. - */ -module.exports = 'loop'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Loop Event. + * + * This event is dispatched by a Tween when it loops. + * + * This event will only be dispatched if the Tween has a loop count set. + * + * If a Tween has a `loopDelay` set, this event will fire after that delay expires. + * + * The difference between `loop` and `repeat` is that `repeat` is a property setting, + * where-as `loop` applies to the entire Tween. + * + * Listen to it from a Tween instance using `Tween.on('loop', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * loop: 6 + * }); + * tween.on('loop', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_LOOP + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'loop'; diff --git a/src/tweens/events/TWEEN_REPEAT_EVENT.js b/src/tweens/events/TWEEN_REPEAT_EVENT.js index e45e49d7c..8b72de8be 100644 --- a/src/tweens/events/TWEEN_REPEAT_EVENT.js +++ b/src/tweens/events/TWEEN_REPEAT_EVENT.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Repeat Event. - * - * This event is dispatched by a Tween when one of the properties it is tweening repeats. - * - * This event will only be dispatched if the Tween has a property with a repeat count set. - * - * If a Tween has a `repeatDelay` set, this event will fire after that delay expires. - * - * The difference between `loop` and `repeat` is that `repeat` is a property setting, - * where-as `loop` applies to the entire Tween. - * - * Listen to it from a Tween instance using `Tween.on('repeat', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * repeat: 4 - * }); - * tween.on('repeat', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_REPEAT - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {string} key - The key of the property that just repeated. - * @param {any} target - The target that the property just repeated on. - */ -module.exports = 'repeat'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Repeat Event. + * + * This event is dispatched by a Tween when one of the properties it is tweening repeats. + * + * This event will only be dispatched if the Tween has a property with a repeat count set. + * + * If a Tween has a `repeatDelay` set, this event will fire after that delay expires. + * + * The difference between `loop` and `repeat` is that `repeat` is a property setting, + * where-as `loop` applies to the entire Tween. + * + * Listen to it from a Tween instance using `Tween.on('repeat', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * repeat: 4 + * }); + * tween.on('repeat', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_REPEAT + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {string} key - The key of the property that just repeated. + * @param {any} target - The target that the property just repeated on. + */ +module.exports = 'repeat'; diff --git a/src/tweens/events/TWEEN_START_EVENT.js b/src/tweens/events/TWEEN_START_EVENT.js index c2e140063..bbfe40ab5 100644 --- a/src/tweens/events/TWEEN_START_EVENT.js +++ b/src/tweens/events/TWEEN_START_EVENT.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Start Event. - * - * This event is dispatched by a Tween when it starts tweening its first property. - * - * A Tween will only emit this event once, as it can only start once. - * - * If a Tween has a `delay` set, this event will fire after that delay expires. - * - * Listen to it from a Tween instance using `Tween.on('start', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000 - * }); - * tween.on('start', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_START - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {any[]} targets - An array of references to the target/s the Tween is operating on. - */ -module.exports = 'start'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Start Event. + * + * This event is dispatched by a Tween when it starts tweening its first property. + * + * A Tween will only emit this event once, as it can only start once. + * + * If a Tween has a `delay` set, this event will fire after that delay expires. + * + * Listen to it from a Tween instance using `Tween.on('start', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('start', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_START + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {any[]} targets - An array of references to the target/s the Tween is operating on. + */ +module.exports = 'start'; diff --git a/src/tweens/events/TWEEN_UPDATE_EVENT.js b/src/tweens/events/TWEEN_UPDATE_EVENT.js index c128a7a15..d92e1aae4 100644 --- a/src/tweens/events/TWEEN_UPDATE_EVENT.js +++ b/src/tweens/events/TWEEN_UPDATE_EVENT.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Update Event. - * - * This event is dispatched by a Tween every time it updates _any_ of the properties it is tweening. - * - * A Tween that is changing 3 properties of a target will emit this event 3 times per change, once per property. - * - * **Note:** This is a very high frequency event and may be dispatched multiple times, every single frame. - * - * Listen to it from a Tween instance using `Tween.on('update', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * }); - * tween.on('update', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_UPDATE - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {string} key - The property that was updated, i.e. `x` or `scale`. - * @param {any} target - The target object that was updated. Usually a Game Object, but can be of any type. - * @param {number} current - The current value of the property that was tweened. - * @param {number} previous - The previous value of the property that was tweened, prior to this update. - */ -module.exports = 'update'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Update Event. + * + * This event is dispatched by a Tween every time it updates _any_ of the properties it is tweening. + * + * A Tween that is changing 3 properties of a target will emit this event 3 times per change, once per property. + * + * **Note:** This is a very high frequency event and may be dispatched multiple times, every single frame. + * + * Listen to it from a Tween instance using `Tween.on('update', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * }); + * tween.on('update', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_UPDATE + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {string} key - The property that was updated, i.e. `x` or `scale`. + * @param {any} target - The target object that was updated. Usually a Game Object, but can be of any type. + * @param {number} current - The current value of the property that was tweened. + * @param {number} previous - The previous value of the property that was tweened, prior to this update. + */ +module.exports = 'update'; diff --git a/src/tweens/events/TWEEN_YOYO_EVENT.js b/src/tweens/events/TWEEN_YOYO_EVENT.js index 75c3b967a..9405b58cb 100644 --- a/src/tweens/events/TWEEN_YOYO_EVENT.js +++ b/src/tweens/events/TWEEN_YOYO_EVENT.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * The Tween Yoyo Event. - * - * This event is dispatched by a Tween whenever a property it is tweening yoyos. - * - * This event will only be dispatched if the Tween has a property with `yoyo` set. - * - * If the Tween has a `hold` value, this event is dispatched when the hold expires. - * - * This event is dispatched for every property, and for every target, that yoyos. - * For example, if a Tween was updating 2 properties and had 10 targets, this event - * would be dispatched 20 times (twice per target). So be careful how you use it! - * - * Listen to it from a Tween instance using `Tween.on('yoyo', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * yoyo: true - * }); - * tween.on('yoyo', listener); - * ``` - * - * @event Phaser.Tweens.Events#TWEEN_YOYO - * @since 3.19.0 - * - * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. - * @param {string} key - The property that yoyo'd, i.e. `x` or `scale`. - * @param {any} target - The target object that was yoyo'd. Usually a Game Object, but can be of any type. - */ -module.exports = 'yoyo'; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * The Tween Yoyo Event. + * + * This event is dispatched by a Tween whenever a property it is tweening yoyos. + * + * This event will only be dispatched if the Tween has a property with `yoyo` set. + * + * If the Tween has a `hold` value, this event is dispatched when the hold expires. + * + * This event is dispatched for every property, and for every target, that yoyos. + * For example, if a Tween was updating 2 properties and had 10 targets, this event + * would be dispatched 20 times (twice per target). So be careful how you use it! + * + * Listen to it from a Tween instance using `Tween.on('yoyo', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * yoyo: true + * }); + * tween.on('yoyo', listener); + * ``` + * + * @event Phaser.Tweens.Events#TWEEN_YOYO + * @since 3.19.0 + * + * @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event. + * @param {string} key - The property that yoyo'd, i.e. `x` or `scale`. + * @param {any} target - The target object that was yoyo'd. Usually a Game Object, but can be of any type. + */ +module.exports = 'yoyo'; diff --git a/src/tweens/events/index.js b/src/tweens/events/index.js index 5822c6fa7..ce2215ab9 100644 --- a/src/tweens/events/index.js +++ b/src/tweens/events/index.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Tweens.Events - */ - -module.exports = { - - TIMELINE_COMPLETE: require('./TIMELINE_COMPLETE_EVENT'), - TIMELINE_LOOP: require('./TIMELINE_LOOP_EVENT'), - TIMELINE_PAUSE: require('./TIMELINE_PAUSE_EVENT'), - TIMELINE_RESUME: require('./TIMELINE_RESUME_EVENT'), - TIMELINE_START: require('./TIMELINE_START_EVENT'), - TIMELINE_UPDATE: require('./TIMELINE_UPDATE_EVENT'), - TWEEN_ACTIVE: require('./TWEEN_ACTIVE_EVENT'), - TWEEN_COMPLETE: require('./TWEEN_COMPLETE_EVENT'), - TWEEN_LOOP: require('./TWEEN_LOOP_EVENT'), - TWEEN_REPEAT: require('./TWEEN_REPEAT_EVENT'), - TWEEN_START: require('./TWEEN_START_EVENT'), - TWEEN_UPDATE: require('./TWEEN_UPDATE_EVENT'), - TWEEN_YOYO: require('./TWEEN_YOYO_EVENT') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Tweens.Events + */ + +module.exports = { + + TIMELINE_COMPLETE: require('./TIMELINE_COMPLETE_EVENT'), + TIMELINE_LOOP: require('./TIMELINE_LOOP_EVENT'), + TIMELINE_PAUSE: require('./TIMELINE_PAUSE_EVENT'), + TIMELINE_RESUME: require('./TIMELINE_RESUME_EVENT'), + TIMELINE_START: require('./TIMELINE_START_EVENT'), + TIMELINE_UPDATE: require('./TIMELINE_UPDATE_EVENT'), + TWEEN_ACTIVE: require('./TWEEN_ACTIVE_EVENT'), + TWEEN_COMPLETE: require('./TWEEN_COMPLETE_EVENT'), + TWEEN_LOOP: require('./TWEEN_LOOP_EVENT'), + TWEEN_REPEAT: require('./TWEEN_REPEAT_EVENT'), + TWEEN_START: require('./TWEEN_START_EVENT'), + TWEEN_UPDATE: require('./TWEEN_UPDATE_EVENT'), + TWEEN_YOYO: require('./TWEEN_YOYO_EVENT') + +}; diff --git a/src/tweens/index.js b/src/tweens/index.js index e6ddd953d..d5cdf8f54 100644 --- a/src/tweens/index.js +++ b/src/tweens/index.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CONST = require('./tween/const'); -var Extend = require('../utils/object/Extend'); - -/** - * @namespace Phaser.Tweens - */ - -var Tweens = { - - Builders: require('./builders'), - Events: require('./events'), - - TweenManager: require('./TweenManager'), - Tween: require('./tween/Tween'), - TweenData: require('./tween/TweenData'), - Timeline: require('./Timeline') - -}; - -// Merge in the consts -Tweens = Extend(false, Tweens, CONST); - -module.exports = Tweens; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CONST = require('./tween/const'); +var Extend = require('../utils/object/Extend'); + +/** + * @namespace Phaser.Tweens + */ + +var Tweens = { + + Builders: require('./builders'), + Events: require('./events'), + + TweenManager: require('./TweenManager'), + Tween: require('./tween/Tween'), + TweenData: require('./tween/TweenData'), + Timeline: require('./Timeline') + +}; + +// Merge in the consts +Tweens = Extend(false, Tweens, CONST); + +module.exports = Tweens; diff --git a/src/tweens/tween/Defaults.js b/src/tweens/tween/Defaults.js index 27fe29ab9..7ae2934ee 100644 --- a/src/tweens/tween/Defaults.js +++ b/src/tweens/tween/Defaults.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @typedef {object} Phaser.Types.Tweens.TweenConfigDefaults - * @since 3.0.0 - * - * @property {(object|object[])} targets - The object, or an array of objects, to run the tween on. - * @property {number} [delay=0] - The number of milliseconds to delay before the tween will start. - * @property {number} [duration=1000] - The duration of the tween in milliseconds. - * @property {string} [ease='Power0'] - The easing equation to use for the tween. - * @property {array} [easeParams] - Optional easing parameters. - * @property {number} [hold=0] - The number of milliseconds to hold the tween for before yoyo'ing. - * @property {number} [repeat=0] - The number of times to repeat the tween. - * @property {number} [repeatDelay=0] - The number of milliseconds to pause before a tween will repeat. - * @property {boolean} [yoyo=false] - Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. - * @property {boolean} [flipX=false] - Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. - * @property {boolean} [flipY=false] - Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. - */ - -var TWEEN_DEFAULTS = { - targets: null, - delay: 0, - duration: 1000, - ease: 'Power0', - easeParams: null, - hold: 0, - repeat: 0, - repeatDelay: 0, - yoyo: false, - flipX: false, - flipY: false -}; - -module.exports = TWEEN_DEFAULTS; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @typedef {object} Phaser.Types.Tweens.TweenConfigDefaults + * @since 3.0.0 + * + * @property {(object|object[])} targets - The object, or an array of objects, to run the tween on. + * @property {number} [delay=0] - The number of milliseconds to delay before the tween will start. + * @property {number} [duration=1000] - The duration of the tween in milliseconds. + * @property {string} [ease='Power0'] - The easing equation to use for the tween. + * @property {array} [easeParams] - Optional easing parameters. + * @property {number} [hold=0] - The number of milliseconds to hold the tween for before yoyo'ing. + * @property {number} [repeat=0] - The number of times to repeat the tween. + * @property {number} [repeatDelay=0] - The number of milliseconds to pause before a tween will repeat. + * @property {boolean} [yoyo=false] - Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. + * @property {boolean} [flipX=false] - Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. + * @property {boolean} [flipY=false] - Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. + */ + +var TWEEN_DEFAULTS = { + targets: null, + delay: 0, + duration: 1000, + ease: 'Power0', + easeParams: null, + hold: 0, + repeat: 0, + repeatDelay: 0, + yoyo: false, + flipX: false, + flipY: false +}; + +module.exports = TWEEN_DEFAULTS; diff --git a/src/tweens/tween/ReservedProps.js b/src/tweens/tween/ReservedProps.js index 8da523bf6..e3d950bed 100644 --- a/src/tweens/tween/ReservedProps.js +++ b/src/tweens/tween/ReservedProps.js @@ -1,69 +1,69 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// 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 -// 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: -// offset: Used when the Tween is part of a Timeline -// 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. -// useFrames: Use frames or milliseconds? -// yoyo: boolean - Does the tween reverse itself (yoyo) when it reaches the end? - -module.exports = [ - 'callbackScope', - 'completeDelay', - 'delay', - 'duration', - 'ease', - 'easeParams', - 'flipX', - 'flipY', - 'hold', - 'loop', - 'loopDelay', - 'offset', - 'onActive', - 'onActiveParams', - 'onActiveScope', - 'onComplete', - 'onCompleteParams', - 'onCompleteScope', - 'onLoop', - 'onLoopParams', - 'onLoopScope', - 'onRepeat', - 'onRepeatParams', - 'onRepeatScope', - 'onStart', - 'onStartParams', - 'onStartScope', - 'onUpdate', - 'onUpdateParams', - 'onUpdateScope', - 'onYoyo', - 'onYoyoParams', - 'onYoyoScope', - 'paused', - 'props', - 'repeat', - 'repeatDelay', - 'targets', - 'useFrames', - 'yoyo' -]; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// 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 +// 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: +// offset: Used when the Tween is part of a Timeline +// 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. +// useFrames: Use frames or milliseconds? +// yoyo: boolean - Does the tween reverse itself (yoyo) when it reaches the end? + +module.exports = [ + 'callbackScope', + 'completeDelay', + 'delay', + 'duration', + 'ease', + 'easeParams', + 'flipX', + 'flipY', + 'hold', + 'loop', + 'loopDelay', + 'offset', + 'onActive', + 'onActiveParams', + 'onActiveScope', + 'onComplete', + 'onCompleteParams', + 'onCompleteScope', + 'onLoop', + 'onLoopParams', + 'onLoopScope', + 'onRepeat', + 'onRepeatParams', + 'onRepeatScope', + 'onStart', + 'onStartParams', + 'onStartScope', + 'onUpdate', + 'onUpdateParams', + 'onUpdateScope', + 'onYoyo', + 'onYoyoParams', + 'onYoyoScope', + 'paused', + 'props', + 'repeat', + 'repeatDelay', + 'targets', + 'useFrames', + 'yoyo' +]; diff --git a/src/tweens/tween/Tween.js b/src/tweens/tween/Tween.js index 3e991516e..6e1f2bce4 100644 --- a/src/tweens/tween/Tween.js +++ b/src/tweens/tween/Tween.js @@ -1,1638 +1,1638 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Class = require('../../utils/Class'); -var EventEmitter = require('eventemitter3'); -var Events = require('../events'); -var GameObjectCreator = require('../../gameobjects/GameObjectCreator'); -var GameObjectFactory = require('../../gameobjects/GameObjectFactory'); -var TWEEN_CONST = require('./const'); -var MATH_CONST = require('../../math/const'); - -/** - * @classdesc - * A Tween is able to manipulate the properties of one or more objects to any given value, based - * on a duration and type of ease. They are rarely instantiated directly and instead should be - * created via the TweenManager. - * - * @class Tween - * @memberof Phaser.Tweens - * @extends Phaser.Events.EventEmitter - * @constructor - * @since 3.0.0 - * - * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - A reference to the parent of this Tween. Either the Tween Manager or a Tween Timeline instance. - * @param {Phaser.Types.Tweens.TweenDataConfig[]} data - An array of TweenData objects, each containing a unique property to be tweened. - * @param {array} targets - An array of targets to be tweened. - */ -var Tween = new Class({ - - Extends: EventEmitter, - - initialize: - - function Tween (parent, data, targets) - { - EventEmitter.call(this); - - /** - * A reference to the parent of this Tween. - * Either the Tween Manager or a Tween Timeline instance. - * - * @name Phaser.Tweens.Tween#parent - * @type {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} - * @since 3.0.0 - */ - this.parent = parent; - - /** - * Is the parent of this Tween a Timeline? - * - * @name Phaser.Tweens.Tween#parentIsTimeline - * @type {boolean} - * @since 3.0.0 - */ - this.parentIsTimeline = parent.hasOwnProperty('isTimeline'); - - /** - * An array of TweenData objects, each containing a unique property and target being tweened. - * - * @name Phaser.Tweens.Tween#data - * @type {Phaser.Types.Tweens.TweenDataConfig[]} - * @since 3.0.0 - */ - this.data = data; - - /** - * The cached length of the data array. - * - * @name Phaser.Tweens.Tween#totalData - * @type {integer} - * @since 3.0.0 - */ - this.totalData = data.length; - - /** - * An array of references to the target/s this Tween is operating on. - * - * @name Phaser.Tweens.Tween#targets - * @type {object[]} - * @since 3.0.0 - */ - this.targets = targets; - - /** - * Cached target total (not necessarily the same as the data total) - * - * @name Phaser.Tweens.Tween#totalTargets - * @type {integer} - * @since 3.0.0 - */ - this.totalTargets = targets.length; - - /** - * If `true` then duration, delay, etc values are all frame totals. - * - * @name Phaser.Tweens.Tween#useFrames - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.useFrames = false; - - /** - * Scales the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. - * Value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. - * - * @name Phaser.Tweens.Tween#timeScale - * @type {number} - * @default 1 - * @since 3.0.0 - */ - this.timeScale = 1; - - /** - * Loop this tween? Can be -1 for an infinite loop, or an integer. - * When enabled it will play through ALL TweenDatas again. Use TweenData.repeat to loop a single element. - * - * @name Phaser.Tweens.Tween#loop - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.loop = 0; - - /** - * Time in ms/frames before the tween loops. - * - * @name Phaser.Tweens.Tween#loopDelay - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.loopDelay = 0; - - /** - * How many loops are left to run? - * - * @name Phaser.Tweens.Tween#loopCounter - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.loopCounter = 0; - - /** - * Time in ms/frames before the 'onStart' event fires. - * This is the shortest `delay` value across all of the TweenDatas of this Tween. - * - * @name Phaser.Tweens.Tween#startDelay - * @type {number} - * @default 0 - * @since 3.19.0 - */ - this.startDelay = 0; - - /** - * Has this Tween started playback yet? - * This boolean is toggled when the Tween leaves the 'delayed' state and starts running. - * - * @name Phaser.Tweens.Tween#hasStarted - * @type {boolean} - * @readonly - * @since 3.19.0 - */ - this.hasStarted = false; - - /** - * Is this Tween currently seeking? - * This boolean is toggled in the `Tween.seek` method. - * When a tween is seeking it will not dispatch any events or callbacks. - * - * @name Phaser.Tweens.Tween#isSeeking - * @type {boolean} - * @readonly - * @since 3.19.0 - */ - this.isSeeking = false; - - /** - * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = -1 (as it never completes) - * - * @name Phaser.Tweens.Tween#completeDelay - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.completeDelay = 0; - - /** - * Countdown timer (used by timeline offset, loopDelay and completeDelay) - * - * @name Phaser.Tweens.Tween#countdown - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.countdown = 0; - - /** - * Set only if this Tween is part of a Timeline. - * - * @name Phaser.Tweens.Tween#offset - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.offset = 0; - - /** - * Set only if this Tween is part of a Timeline. The calculated offset amount. - * - * @name Phaser.Tweens.Tween#calculatedOffset - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.calculatedOffset = 0; - - /** - * The current state of the tween - * - * @name Phaser.Tweens.Tween#state - * @type {integer} - * @since 3.0.0 - */ - this.state = TWEEN_CONST.PENDING_ADD; - - /** - * The state of the tween when it was paused (used by Resume) - * - * @name Phaser.Tweens.Tween#_pausedState - * @type {integer} - * @private - * @since 3.0.0 - */ - this._pausedState = TWEEN_CONST.INIT; - - /** - * Does the Tween start off paused? (if so it needs to be started with Tween.play) - * - * @name Phaser.Tweens.Tween#paused - * @type {boolean} - * @default false - * @since 3.0.0 - */ - this.paused = false; - - /** - * Elapsed time in ms/frames of this run through the Tween. - * - * @name Phaser.Tweens.Tween#elapsed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.elapsed = 0; - - /** - * Total elapsed time in ms/frames of the entire Tween, including looping. - * - * @name Phaser.Tweens.Tween#totalElapsed - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalElapsed = 0; - - /** - * Time in ms/frames for the whole Tween to play through once, excluding loop amounts and loop delays. - * - * @name Phaser.Tweens.Tween#duration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.duration = 0; - - /** - * Value between 0 and 1. The amount through the Tween, excluding loops. - * - * @name Phaser.Tweens.Tween#progress - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.progress = 0; - - /** - * Time in ms/frames for the Tween to complete (including looping) - * - * @name Phaser.Tweens.Tween#totalDuration - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalDuration = 0; - - /** - * Value between 0 and 1. The amount through the entire Tween, including looping. - * - * @name Phaser.Tweens.Tween#totalProgress - * @type {number} - * @default 0 - * @since 3.0.0 - */ - this.totalProgress = 0; - - /** - * An object containing the different Tween callback functions. - * - * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. - * - * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. - * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. - * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. - * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. - * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. - * `onUpdate` When a TweenData updates a property on a source target during playback. - * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. - * - * @name Phaser.Tweens.Tween#callbacks - * @type {object} - * @since 3.0.0 - */ - this.callbacks = { - onActive: null, - onComplete: null, - onLoop: null, - onRepeat: null, - onStart: null, - onUpdate: null, - onYoyo: null - }; - - /** - * The context in which all callbacks are invoked. - * - * @name Phaser.Tweens.Tween#callbackScope - * @type {any} - * @since 3.0.0 - */ - this.callbackScope; - }, - - /** - * Returns the current value of the specified Tween Data. - * - * @method Phaser.Tweens.Tween#getValue - * @since 3.0.0 - * - * @param {integer} [index=0] - The Tween Data to return the value from. - * - * @return {number} The value of the requested Tween Data. - */ - getValue: function (index) - { - if (index === undefined) { index = 0; } - - return this.data[index].current; - }, - - /** - * Set the scale the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. - * - * @method Phaser.Tweens.Tween#setTimeScale - * @since 3.0.0 - * - * @param {number} value - The scale factor for timescale. - * - * @return {this} - This Tween instance. - */ - setTimeScale: function (value) - { - this.timeScale = value; - - return this; - }, - - /** - * Returns the scale of the time applied to this Tween. - * - * @method Phaser.Tweens.Tween#getTimeScale - * @since 3.0.0 - * - * @return {number} The timescale of this tween (between 0 and 1) - */ - getTimeScale: function () - { - return this.timeScale; - }, - - /** - * Checks if the Tween is currently active. - * - * @method Phaser.Tweens.Tween#isPlaying - * @since 3.0.0 - * - * @return {boolean} `true` if the Tween is active, otherwise `false`. - */ - isPlaying: function () - { - return (this.state === TWEEN_CONST.ACTIVE); - }, - - /** - * Checks if the Tween is currently paused. - * - * @method Phaser.Tweens.Tween#isPaused - * @since 3.0.0 - * - * @return {boolean} `true` if the Tween is paused, otherwise `false`. - */ - isPaused: function () - { - return (this.state === TWEEN_CONST.PAUSED); - }, - - /** - * See if this Tween is currently acting upon the given target. - * - * @method Phaser.Tweens.Tween#hasTarget - * @since 3.0.0 - * - * @param {object} target - The target to check against this Tween. - * - * @return {boolean} `true` if the given target is a target of this Tween, otherwise `false`. - */ - hasTarget: function (target) - { - return (this.targets.indexOf(target) !== -1); - }, - - /** - * Updates the 'end' value of the given property across all matching targets. - * - * Calling this does not adjust the duration of the tween, or the current progress. - * - * You can optionally tell it to set the 'start' value to be the current value (before the change). - * - * @method Phaser.Tweens.Tween#updateTo - * @since 3.0.0 - * - * @param {string} key - The property to set the new value for. - * @param {*} value - The new value of the property. - * @param {boolean} [startToCurrent=false] - Should this change set the start value to be the current value? - * - * @return {this} - This Tween instance. - */ - updateTo: function (key, value, startToCurrent) - { - if (startToCurrent === undefined) { startToCurrent = false; } - - for (var i = 0; i < this.totalData; i++) - { - var tweenData = this.data[i]; - - if (tweenData.key === key) - { - tweenData.end = value; - - if (startToCurrent) - { - tweenData.start = tweenData.current; - } - } - } - - return this; - }, - - /** - * Restarts the tween from the beginning. - * - * @method Phaser.Tweens.Tween#restart - * @since 3.0.0 - * - * @return {this} This Tween instance. - */ - restart: function () - { - // Reset these so they're ready for the next update - this.elapsed = 0; - this.progress = 0; - this.totalElapsed = 0; - this.totalProgress = 0; - - if (this.state === TWEEN_CONST.ACTIVE) - { - return this.seek(0); - } - else if (this.state === TWEEN_CONST.REMOVED) - { - this.seek(0); - this.parent.makeActive(this); - - return this; - } - else if (this.state === TWEEN_CONST.PENDING_ADD) - { - return this; - } - else - { - return this.play(); - } - }, - - /** - * Internal method that calculates the overall duration of the Tween. - * - * @method Phaser.Tweens.Tween#calcDuration - * @since 3.0.0 - */ - calcDuration: function () - { - var maxDuration = 0; - var minDelay = MATH_CONST.MAX_SAFE_INTEGER; - - var data = this.data; - - for (var i = 0; i < this.totalData; i++) - { - var tweenData = data[i]; - - // Set t1 (duration + hold + yoyo) - tweenData.t1 = tweenData.duration + tweenData.hold; - - if (tweenData.yoyo) - { - tweenData.t1 += tweenData.duration; - } - - // Set t2 (repeatDelay + duration + hold + yoyo) - tweenData.t2 = tweenData.t1 + tweenData.repeatDelay; - - // Total Duration - tweenData.totalDuration = tweenData.delay + tweenData.t1; - - if (tweenData.repeat === -1) - { - tweenData.totalDuration += (tweenData.t2 * 999999999999); - } - else if (tweenData.repeat > 0) - { - tweenData.totalDuration += (tweenData.t2 * tweenData.repeat); - } - - if (tweenData.totalDuration > maxDuration) - { - // Get the longest TweenData from the Tween, used to calculate the Tween TD - maxDuration = tweenData.totalDuration; - } - - if (tweenData.delay < minDelay) - { - minDelay = tweenData.delay; - } - } - - // Excludes loop values - - // If duration has been set to 0 then we give it a super-low value so that it always - // renders at least 1 frame, but no more, without causing divided by zero errors elsewhere. - this.duration = Math.max(maxDuration, 0.001); - - this.loopCounter = (this.loop === -1) ? 999999999999 : this.loop; - - if (this.loopCounter > 0) - { - this.totalDuration = this.duration + this.completeDelay + ((this.duration + this.loopDelay) * this.loopCounter); - } - else - { - this.totalDuration = this.duration + this.completeDelay; - } - - // How long before this Tween starts playback? - this.startDelay = minDelay; - }, - - /** - * Called by TweenManager.preUpdate as part of its loop to check pending and active tweens. - * Should not be called directly. - * - * @method Phaser.Tweens.Tween#init - * @since 3.0.0 - * - * @return {boolean} Returns `true` if this Tween should be moved from the pending list to the active list by the Tween Manager. - */ - init: function () - { - // You can't have a paused Tween if it's part of a Timeline - if (this.paused && !this.parentIsTimeline) - { - this.state = TWEEN_CONST.PENDING_ADD; - this._pausedState = TWEEN_CONST.INIT; - - return false; - } - - var data = this.data; - var totalTargets = this.totalTargets; - - for (var i = 0; i < this.totalData; i++) - { - var tweenData = data[i]; - var target = tweenData.target; - var gen = tweenData.gen; - var key = tweenData.key; - var targetIndex = tweenData.index; - - // Old function signature: i, totalTargets, target - // New function signature: target, key, value, index, total, tween - - tweenData.delay = gen.delay(target, key, 0, targetIndex, totalTargets, this); - tweenData.duration = Math.max(gen.duration(target, key, 0, targetIndex, totalTargets, this), 0.001); - tweenData.hold = gen.hold(target, key, 0, targetIndex, totalTargets, this); - tweenData.repeat = gen.repeat(target, key, 0, targetIndex, totalTargets, this); - tweenData.repeatDelay = gen.repeatDelay(target, key, 0, targetIndex, totalTargets, this); - } - - this.calcDuration(); - - this.progress = 0; - this.totalProgress = 0; - this.elapsed = 0; - this.totalElapsed = 0; - - this.state = TWEEN_CONST.INIT; - - return true; - }, - - /** - * Internal method that makes this Tween active within the TweenManager - * and emits the onActive event and callback. - * - * @method Phaser.Tweens.Tween#makeActive - * @fires Phaser.Tweens.Events#TWEEN_ACTIVE - * @since 3.19.0 - */ - makeActive: function () - { - this.parent.makeActive(this); - - this.dispatchTweenEvent(Events.TWEEN_ACTIVE, this.callbacks.onActive); - }, - - /** - * Internal method that advances to the next state of the Tween during playback. - * - * @method Phaser.Tweens.Tween#nextState - * @fires Phaser.Tweens.Events#TWEEN_COMPLETE - * @fires Phaser.Tweens.Events#TWEEN_LOOP - * @since 3.0.0 - */ - nextState: function () - { - if (this.loopCounter > 0) - { - this.elapsed = 0; - this.progress = 0; - this.loopCounter--; - - this.resetTweenData(true); - - if (this.loopDelay > 0) - { - this.countdown = this.loopDelay; - this.state = TWEEN_CONST.LOOP_DELAY; - } - else - { - this.state = TWEEN_CONST.ACTIVE; - - this.dispatchTweenEvent(Events.TWEEN_LOOP, this.callbacks.onLoop); - } - } - else if (this.completeDelay > 0) - { - this.state = TWEEN_CONST.COMPLETE_DELAY; - - this.countdown = this.completeDelay; - } - else - { - this.state = TWEEN_CONST.PENDING_REMOVE; - - this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); - } - }, - - /** - * Pauses the Tween immediately. Use `resume` to continue playback. - * - * @method Phaser.Tweens.Tween#pause - * @since 3.0.0 - * - * @return {this} - This Tween instance. - */ - pause: function () - { - if (this.state === TWEEN_CONST.PAUSED) - { - return this; - } - - this.paused = true; - - this._pausedState = this.state; - - this.state = TWEEN_CONST.PAUSED; - - return this; - }, - - /** - * Starts a Tween playing. - * - * You only need to call this method if you have configured the tween to be paused on creation. - * - * If the Tween is already playing, calling this method again will have no effect. If you wish to - * restart the Tween, use `Tween.restart` instead. - * - * Calling this method after the Tween has completed will start the Tween playing again from the start. - * This is the same as calling `Tween.seek(0)` and then `Tween.play()`. - * - * @method Phaser.Tweens.Tween#play - * @since 3.0.0 - * - * @param {boolean} [resetFromTimeline=false] - Is this Tween being played as part of a Timeline? - * - * @return {this} This Tween instance. - */ - play: function (resetFromTimeline) - { - if (resetFromTimeline === undefined) { resetFromTimeline = false; } - - var state = this.state; - - if (state === TWEEN_CONST.INIT && !this.parentIsTimeline) - { - this.resetTweenData(false); - - this.state = TWEEN_CONST.ACTIVE; - - return this; - } - else if (state === TWEEN_CONST.ACTIVE || (state === TWEEN_CONST.PENDING_ADD && this._pausedState === TWEEN_CONST.PENDING_ADD)) - { - return this; - } - else if (!this.parentIsTimeline && (state === TWEEN_CONST.PENDING_REMOVE || state === TWEEN_CONST.REMOVED)) - { - this.seek(0); - this.parent.makeActive(this); - - return this; - } - - if (this.parentIsTimeline) - { - this.resetTweenData(resetFromTimeline); - - if (this.calculatedOffset === 0) - { - this.state = TWEEN_CONST.ACTIVE; - } - else - { - this.countdown = this.calculatedOffset; - - this.state = TWEEN_CONST.OFFSET_DELAY; - } - } - else if (this.paused) - { - this.paused = false; - - this.makeActive(); - } - else - { - this.resetTweenData(resetFromTimeline); - - this.state = TWEEN_CONST.ACTIVE; - - this.makeActive(); - } - - return this; - }, - - /** - * Internal method that resets all of the Tween Data, including the progress and elapsed values. - * - * @method Phaser.Tweens.Tween#resetTweenData - * @since 3.0.0 - * - * @param {boolean} resetFromLoop - Has this method been called as part of a loop? - */ - resetTweenData: function (resetFromLoop) - { - var data = this.data; - var total = this.totalData; - var totalTargets = this.totalTargets; - - for (var i = 0; i < total; i++) - { - var tweenData = data[i]; - - var target = tweenData.target; - var key = tweenData.key; - var targetIndex = tweenData.index; - - tweenData.progress = 0; - tweenData.elapsed = 0; - - tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; - - if (resetFromLoop) - { - tweenData.start = tweenData.getStartValue(target, key, tweenData.start, targetIndex, totalTargets, this); - - tweenData.end = tweenData.getEndValue(target, key, tweenData.end, targetIndex, totalTargets, this); - - tweenData.current = tweenData.start; - - tweenData.state = TWEEN_CONST.PLAYING_FORWARD; - } - else - { - tweenData.state = TWEEN_CONST.PENDING_RENDER; - } - - if (tweenData.delay > 0) - { - tweenData.elapsed = tweenData.delay; - - tweenData.state = TWEEN_CONST.DELAY; - } - - if (tweenData.getActiveValue) - { - target[key] = tweenData.getActiveValue(tweenData.target, tweenData.key, tweenData.start); - } - } - }, - - /** - * Resumes the playback of a previously paused Tween. - * - * @method Phaser.Tweens.Tween#resume - * @since 3.0.0 - * - * @return {this} - This Tween instance. - */ - resume: function () - { - if (this.state === TWEEN_CONST.PAUSED) - { - this.paused = false; - - this.state = this._pausedState; - } - else - { - this.play(); - } - - return this; - }, - - /** - * Seeks to a specific point in the Tween. - * - * **Note:** You cannot seek a Tween that repeats or loops forever, or that has an unusually long total duration. - * - * The given position is a value between 0 and 1 which represents how far through the Tween to seek to. - * A value of 0.5 would seek to half-way through the Tween, where-as a value of zero would seek to the start. - * - * Note that the seek 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 0.5 would seek to 3 seconds into the Tween, as that's half-way through its _entire_ duration. - * - * 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. - * - * @method Phaser.Tweens.Tween#seek - * @since 3.0.0 - * - * @param {number} toPosition - A value between 0 and 1 which represents the progress point to seek to. - * @param {number} [delta=16.6] - The size of each step when seeking through the Tween. A higher value completes faster but at a cost of less precision. - * - * @return {this} This Tween instance. - */ - seek: function (toPosition, delta) - { - if (delta === undefined) { delta = 16.6; } - - if (this.totalDuration >= 3600000) - { - console.warn('Tween.seek duration too long'); - - return this; - } - - if (this.state === TWEEN_CONST.REMOVED) - { - this.makeActive(); - } - - this.elapsed = 0; - this.progress = 0; - this.totalElapsed = 0; - this.totalProgress = 0; - - var data = this.data; - var totalTargets = this.totalTargets; - - for (var i = 0; i < this.totalData; i++) - { - var tweenData = data[i]; - var target = tweenData.target; - var gen = tweenData.gen; - var key = tweenData.key; - var targetIndex = tweenData.index; - - tweenData.progress = 0; - tweenData.elapsed = 0; - - tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; - - // Old function signature: i, totalTargets, target - // New function signature: target, key, value, index, total, tween - - tweenData.delay = gen.delay(target, key, 0, targetIndex, totalTargets, this); - tweenData.duration = Math.max(gen.duration(target, key, 0, targetIndex, totalTargets, this), 0.001); - tweenData.hold = gen.hold(target, key, 0, targetIndex, totalTargets, this); - tweenData.repeat = gen.repeat(target, key, 0, targetIndex, totalTargets, this); - tweenData.repeatDelay = gen.repeatDelay(target, key, 0, targetIndex, totalTargets, this); - - tweenData.current = tweenData.start; - tweenData.state = TWEEN_CONST.PLAYING_FORWARD; - - this.updateTweenData(this, tweenData, 0, targetIndex, totalTargets); - - if (tweenData.delay > 0) - { - tweenData.elapsed = tweenData.delay; - tweenData.state = TWEEN_CONST.DELAY; - } - } - - this.calcDuration(); - - var wasPaused = false; - - if (this.state === TWEEN_CONST.PAUSED) - { - wasPaused = true; - - this.state = TWEEN_CONST.ACTIVE; - } - - this.isSeeking = true; - - do - { - this.update(0, delta); - - } while (this.totalProgress < toPosition); - - this.isSeeking = false; - - if (wasPaused) - { - this.state = TWEEN_CONST.PAUSED; - } - - return this; - }, - - /** - * Sets an event based callback to be invoked during playback. - * - * Calling this method will replace a previously set callback for the given type, if any exists. - * - * The types available are: - * - * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. - * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. - * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. - * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. - * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. - * `onUpdate` When a TweenData updates a property on a source target during playback. - * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. - * - * @method Phaser.Tweens.Tween#setCallback - * @since 3.0.0 - * - * @param {string} type - Type of the callback to set. - * @param {function} callback - The function to invoke when this callback happens. - * @param {array} [params] - An array of parameters for specified callbacks types. - * @param {any} [scope] - The context the callback will be invoked in. - * - * @return {this} This Tween instance. - */ - setCallback: function (type, callback, params, scope) - { - this.callbacks[type] = { func: callback, scope: scope, params: params }; - - return this; - }, - - /** - * Flags the Tween as being complete, whatever stage of progress it is at. - * - * If an onComplete callback has been defined it will automatically invoke it, unless a `delay` - * argument is provided, in which case the Tween will delay for that period of time before calling the callback. - * - * If you don't need a delay, or have an onComplete callback, then call `Tween.stop` instead. - * - * @method Phaser.Tweens.Tween#complete - * @fires Phaser.Tweens.Events#TWEEN_COMPLETE - * @since 3.2.0 - * - * @param {number} [delay=0] - The time to wait before invoking the complete callback. If zero it will fire immediately. - * - * @return {this} This Tween instance. - */ - complete: function (delay) - { - if (delay === undefined) { delay = 0; } - - if (delay) - { - this.state = TWEEN_CONST.COMPLETE_DELAY; - - this.countdown = delay; - } - else - { - this.state = TWEEN_CONST.PENDING_REMOVE; - - this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); - } - - return this; - }, - - /** - * Immediately removes this Tween from the TweenManager and all of its internal arrays, - * no matter what stage it as it. Then sets the tween state to `REMOVED`. - * - * You should dispose of your reference to this tween after calling this method, to - * free it from memory. - * - * @method Phaser.Tweens.Tween#remove - * @since 3.17.0 - * - * @return {this} This Tween instance. - */ - remove: function () - { - this.parent.remove(this); - - return this; - }, - - /** - * Stops the Tween immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. - * - * @method Phaser.Tweens.Tween#stop - * @since 3.0.0 - * - * @param {number} [resetTo] - If you want to seek the tween, provide a value between 0 and 1. - * - * @return {this} This Tween instance. - */ - stop: function (resetTo) - { - if (this.state === TWEEN_CONST.ACTIVE) - { - if (resetTo !== undefined) - { - this.seek(resetTo); - } - } - - if (this.state !== TWEEN_CONST.REMOVED) - { - if (this.state === TWEEN_CONST.PAUSED || this.state === TWEEN_CONST.PENDING_ADD) - { - if (this.parentIsTimeline) - { - this.parent.manager._destroy.push(this); - this.parent.manager._toProcess++; - } - else - { - this.parent._destroy.push(this); - this.parent._toProcess++; - } - } - - this.removeAllListeners(); - - this.state = TWEEN_CONST.PENDING_REMOVE; - } - - return this; - }, - - /** - * 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} timestamp - 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} Returns `true` if this Tween has finished and should be removed from the Tween Manager, otherwise returns `false`. - */ - update: function (timestamp, delta) - { - if (this.state === TWEEN_CONST.PAUSED) - { - return false; - } - - if (this.useFrames) - { - delta = 1 * this.parent.timeScale; - } - - delta *= this.timeScale; - - this.elapsed += delta; - this.progress = Math.min(this.elapsed / this.duration, 1); - - this.totalElapsed += delta; - this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); - - switch (this.state) - { - case TWEEN_CONST.ACTIVE: - - if (!this.hasStarted && !this.isSeeking) - { - this.startDelay -= delta; - - if (this.startDelay <= 0) - { - this.hasStarted = true; - - this.dispatchTweenEvent(Events.TWEEN_START, this.callbacks.onStart); - } - } - - var stillRunning = false; - - for (var i = 0; i < this.totalData; i++) - { - var tweenData = this.data[i]; - - if (this.updateTweenData(this, tweenData, delta)) - { - stillRunning = true; - } - } - - // Anything still running? If not, we're done - if (!stillRunning) - { - this.nextState(); - } - - break; - - case TWEEN_CONST.LOOP_DELAY: - - this.countdown -= delta; - - if (this.countdown <= 0) - { - this.state = TWEEN_CONST.ACTIVE; - - this.dispatchTweenEvent(Events.TWEEN_LOOP, this.callbacks.onLoop); - } - - break; - - case TWEEN_CONST.OFFSET_DELAY: - - this.countdown -= delta; - - if (this.countdown <= 0) - { - this.state = TWEEN_CONST.ACTIVE; - } - - break; - - case TWEEN_CONST.COMPLETE_DELAY: - - this.countdown -= delta; - - if (this.countdown <= 0) - { - this.state = TWEEN_CONST.PENDING_REMOVE; - - this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); - } - - break; - } - - return (this.state === TWEEN_CONST.PENDING_REMOVE); - }, - - /** - * Internal method that will emit a TweenData based Event and invoke the given callback. - * - * @method Phaser.Tweens.Tween#dispatchTweenDataEvent - * @since 3.19.0 - * - * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. - * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. - * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData object that caused this event. - */ - dispatchTweenDataEvent: function (event, callback, tweenData) - { - if (!this.isSeeking) - { - this.emit(event, this, tweenData.key, tweenData.target, tweenData.current, tweenData.previous); - - if (callback) - { - callback.params[1] = tweenData.target; - - callback.func.apply(callback.scope, callback.params); - } - } - }, - - /** - * Internal method that will emit a Tween based Event and invoke the given callback. - * - * @method Phaser.Tweens.Tween#dispatchTweenEvent - * @since 3.19.0 - * - * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. - * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. - */ - dispatchTweenEvent: function (event, callback) - { - if (!this.isSeeking) - { - this.emit(event, this, this.targets); - - if (callback) - { - callback.params[1] = this.targets; - - callback.func.apply(callback.scope, callback.params); - } - } - }, - - /** - * Internal method used as part of the playback process that sets a tween to play in reverse. - * - * @method Phaser.Tweens.Tween#setStateFromEnd - * @fires Phaser.Tweens.Events#TWEEN_REPEAT - * @fires Phaser.Tweens.Events#TWEEN_YOYO - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to update. - * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. - * @param {number} diff - Any extra time that needs to be accounted for in the elapsed and progress values. - * - * @return {integer} The state of this Tween. - */ - setStateFromEnd: function (tween, tweenData, diff) - { - if (tweenData.yoyo) - { - // We've hit the end of a Playing Forward TweenData and we have a yoyo - - // Account for any extra time we got from the previous frame - tweenData.elapsed = diff; - tweenData.progress = diff / tweenData.duration; - - if (tweenData.flipX) - { - tweenData.target.toggleFlipX(); - } - - if (tweenData.flipY) - { - tweenData.target.toggleFlipY(); - } - - this.dispatchTweenDataEvent(Events.TWEEN_YOYO, tween.callbacks.onYoyo, tweenData); - - tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); - - return TWEEN_CONST.PLAYING_BACKWARD; - } - else if (tweenData.repeatCounter > 0) - { - // We've hit the end of a Playing Forward TweenData and we have a Repeat. - // So we're going to go right back to the start to repeat it again. - - tweenData.repeatCounter--; - - // Account for any extra time we got from the previous frame - tweenData.elapsed = diff; - tweenData.progress = diff / tweenData.duration; - - if (tweenData.flipX) - { - tweenData.target.toggleFlipX(); - } - - if (tweenData.flipY) - { - tweenData.target.toggleFlipY(); - } - - tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); - - tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); - - // Delay? - if (tweenData.repeatDelay > 0) - { - tweenData.elapsed = tweenData.repeatDelay - diff; - - tweenData.current = tweenData.start; - - tweenData.target[tweenData.key] = tweenData.current; - - return TWEEN_CONST.REPEAT_DELAY; - } - else - { - this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); - - return TWEEN_CONST.PLAYING_FORWARD; - } - } - - return TWEEN_CONST.COMPLETE; - }, - - /** - * Internal method used as part of the playback process that sets a tween to play from the start. - * - * @method Phaser.Tweens.Tween#setStateFromStart - * @fires Phaser.Tweens.Events#TWEEN_REPEAT - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to update. - * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. - * @param {number} diff - Any extra time that needs to be accounted for in the elapsed and progress values. - * - * @return {integer} The state of this Tween. - */ - setStateFromStart: function (tween, tweenData, diff) - { - if (tweenData.repeatCounter > 0) - { - tweenData.repeatCounter--; - - // Account for any extra time we got from the previous frame - tweenData.elapsed = diff; - tweenData.progress = diff / tweenData.duration; - - if (tweenData.flipX) - { - tweenData.target.toggleFlipX(); - } - - if (tweenData.flipY) - { - tweenData.target.toggleFlipY(); - } - - tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); - - // Delay? - if (tweenData.repeatDelay > 0) - { - tweenData.elapsed = tweenData.repeatDelay - diff; - - tweenData.current = tweenData.start; - - tweenData.target[tweenData.key] = tweenData.current; - - return TWEEN_CONST.REPEAT_DELAY; - } - else - { - this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); - - return TWEEN_CONST.PLAYING_FORWARD; - } - } - - return TWEEN_CONST.COMPLETE; - }, - - /** - * Internal method that advances the TweenData based on the time value given. - * - * @method Phaser.Tweens.Tween#updateTweenData - * @fires Phaser.Tweens.Events#TWEEN_UPDATE - * @fires Phaser.Tweens.Events#TWEEN_REPEAT - * @since 3.0.0 - * - * @param {Phaser.Tweens.Tween} tween - The Tween to update. - * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. - * @param {number} delta - Either a value in ms, or 1 if Tween.useFrames is true. - * - * @return {boolean} True if the tween is not complete (e.g., playing), or false if the tween is complete. - */ - updateTweenData: function (tween, tweenData, delta) - { - var target = tweenData.target; - - switch (tweenData.state) - { - case TWEEN_CONST.PLAYING_FORWARD: - case TWEEN_CONST.PLAYING_BACKWARD: - - if (!target) - { - tweenData.state = TWEEN_CONST.COMPLETE; - break; - } - - var elapsed = tweenData.elapsed; - var duration = tweenData.duration; - var diff = 0; - - elapsed += delta; - - if (elapsed > duration) - { - diff = elapsed - duration; - elapsed = duration; - } - - var forward = (tweenData.state === TWEEN_CONST.PLAYING_FORWARD); - var progress = elapsed / duration; - - tweenData.elapsed = elapsed; - tweenData.progress = progress; - tweenData.previous = tweenData.current; - - if (progress === 1) - { - if (forward) - { - tweenData.current = tweenData.end; - target[tweenData.key] = tweenData.end; - - if (tweenData.hold > 0) - { - tweenData.elapsed = tweenData.hold - diff; - - tweenData.state = TWEEN_CONST.HOLD_DELAY; - } - else - { - tweenData.state = this.setStateFromEnd(tween, tweenData, diff); - } - } - else - { - tweenData.current = tweenData.start; - target[tweenData.key] = tweenData.start; - - tweenData.state = this.setStateFromStart(tween, tweenData, diff); - } - } - else - { - var v = (forward) ? tweenData.ease(progress) : tweenData.ease(1 - progress); - - tweenData.current = tweenData.start + ((tweenData.end - tweenData.start) * v); - - target[tweenData.key] = tweenData.current; - } - - this.dispatchTweenDataEvent(Events.TWEEN_UPDATE, tween.callbacks.onUpdate, tweenData); - - break; - - case TWEEN_CONST.DELAY: - - tweenData.elapsed -= delta; - - if (tweenData.elapsed <= 0) - { - tweenData.elapsed = Math.abs(tweenData.elapsed); - - tweenData.state = TWEEN_CONST.PENDING_RENDER; - } - - break; - - case TWEEN_CONST.REPEAT_DELAY: - - tweenData.elapsed -= delta; - - if (tweenData.elapsed <= 0) - { - tweenData.elapsed = Math.abs(tweenData.elapsed); - - tweenData.state = TWEEN_CONST.PLAYING_FORWARD; - - this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); - } - - break; - - case TWEEN_CONST.HOLD_DELAY: - - tweenData.elapsed -= delta; - - if (tweenData.elapsed <= 0) - { - tweenData.state = this.setStateFromEnd(tween, tweenData, Math.abs(tweenData.elapsed)); - } - - break; - - case TWEEN_CONST.PENDING_RENDER: - - if (target) - { - tweenData.start = tweenData.getStartValue(target, tweenData.key, target[tweenData.key], tweenData.index, tween.totalTargets, tween); - - tweenData.end = tweenData.getEndValue(target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); - - tweenData.current = tweenData.start; - - target[tweenData.key] = tweenData.start; - - tweenData.state = TWEEN_CONST.PLAYING_FORWARD; - } - else - { - tweenData.state = TWEEN_CONST.COMPLETE; - } - - break; - } - - // Return TRUE if this TweenData still playing, otherwise return FALSE - return (tweenData.state !== TWEEN_CONST.COMPLETE); - } - -}); - -// onActive = 'active' event = When the Tween is moved from the pending to the active list in the manager, even if playback delayed -// onStart = 'start' event = When the Tween starts playing from a delayed state (will happen same time as onActive if no delay) -// onYoyo = 'yoyo' event = When the Tween starts a yoyo -// onRepeat = 'repeat' event = When a TweenData repeats playback (if any) -// onComplete = 'complete' event = When the Tween finishes all playback (can sometimes never happen if repeat -1), also when 'stop' called -// onUpdate = 'update' event = When the Tween updates a TweenData during playback (expensive!) -// onLoop = 'loop' event = Used to loop ALL TweenDatas in a Tween - -Tween.TYPES = [ - 'onActive', - 'onComplete', - 'onLoop', - 'onRepeat', - 'onStart', - 'onUpdate', - 'onYoyo' -]; - -/** - * Creates a new Tween object. - * - * Note: This method will only be available if Tweens have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectFactory#tween - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The Tween configuration. - * - * @return {Phaser.Tweens.Tween} The Tween that was created. - */ -GameObjectFactory.register('tween', function (config) -{ - return this.scene.sys.tweens.add(config); -}); - -// 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 - -/** - * Creates a new Tween object and returns it. - * - * Note: This method will only be available if Tweens have been built into Phaser. - * - * @method Phaser.GameObjects.GameObjectCreator#tween - * @since 3.0.0 - * - * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The Tween configuration. - * - * @return {Phaser.Tweens.Tween} The Tween that was created. - */ -GameObjectCreator.register('tween', function (config) -{ - return this.scene.sys.tweens.create(config); -}); - -// When registering a factory function 'this' refers to the GameObjectCreator context. - -module.exports = Tween; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Class = require('../../utils/Class'); +var EventEmitter = require('eventemitter3'); +var Events = require('../events'); +var GameObjectCreator = require('../../gameobjects/GameObjectCreator'); +var GameObjectFactory = require('../../gameobjects/GameObjectFactory'); +var TWEEN_CONST = require('./const'); +var MATH_CONST = require('../../math/const'); + +/** + * @classdesc + * A Tween is able to manipulate the properties of one or more objects to any given value, based + * on a duration and type of ease. They are rarely instantiated directly and instead should be + * created via the TweenManager. + * + * @class Tween + * @memberof Phaser.Tweens + * @extends Phaser.Events.EventEmitter + * @constructor + * @since 3.0.0 + * + * @param {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} parent - A reference to the parent of this Tween. Either the Tween Manager or a Tween Timeline instance. + * @param {Phaser.Types.Tweens.TweenDataConfig[]} data - An array of TweenData objects, each containing a unique property to be tweened. + * @param {array} targets - An array of targets to be tweened. + */ +var Tween = new Class({ + + Extends: EventEmitter, + + initialize: + + function Tween (parent, data, targets) + { + EventEmitter.call(this); + + /** + * A reference to the parent of this Tween. + * Either the Tween Manager or a Tween Timeline instance. + * + * @name Phaser.Tweens.Tween#parent + * @type {(Phaser.Tweens.TweenManager|Phaser.Tweens.Timeline)} + * @since 3.0.0 + */ + this.parent = parent; + + /** + * Is the parent of this Tween a Timeline? + * + * @name Phaser.Tweens.Tween#parentIsTimeline + * @type {boolean} + * @since 3.0.0 + */ + this.parentIsTimeline = parent.hasOwnProperty('isTimeline'); + + /** + * An array of TweenData objects, each containing a unique property and target being tweened. + * + * @name Phaser.Tweens.Tween#data + * @type {Phaser.Types.Tweens.TweenDataConfig[]} + * @since 3.0.0 + */ + this.data = data; + + /** + * The cached length of the data array. + * + * @name Phaser.Tweens.Tween#totalData + * @type {integer} + * @since 3.0.0 + */ + this.totalData = data.length; + + /** + * An array of references to the target/s this Tween is operating on. + * + * @name Phaser.Tweens.Tween#targets + * @type {object[]} + * @since 3.0.0 + */ + this.targets = targets; + + /** + * Cached target total (not necessarily the same as the data total) + * + * @name Phaser.Tweens.Tween#totalTargets + * @type {integer} + * @since 3.0.0 + */ + this.totalTargets = targets.length; + + /** + * If `true` then duration, delay, etc values are all frame totals. + * + * @name Phaser.Tweens.Tween#useFrames + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.useFrames = false; + + /** + * Scales the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * Value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. + * + * @name Phaser.Tweens.Tween#timeScale + * @type {number} + * @default 1 + * @since 3.0.0 + */ + this.timeScale = 1; + + /** + * Loop this tween? Can be -1 for an infinite loop, or an integer. + * When enabled it will play through ALL TweenDatas again. Use TweenData.repeat to loop a single element. + * + * @name Phaser.Tweens.Tween#loop + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loop = 0; + + /** + * Time in ms/frames before the tween loops. + * + * @name Phaser.Tweens.Tween#loopDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopDelay = 0; + + /** + * How many loops are left to run? + * + * @name Phaser.Tweens.Tween#loopCounter + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.loopCounter = 0; + + /** + * Time in ms/frames before the 'onStart' event fires. + * This is the shortest `delay` value across all of the TweenDatas of this Tween. + * + * @name Phaser.Tweens.Tween#startDelay + * @type {number} + * @default 0 + * @since 3.19.0 + */ + this.startDelay = 0; + + /** + * Has this Tween started playback yet? + * This boolean is toggled when the Tween leaves the 'delayed' state and starts running. + * + * @name Phaser.Tweens.Tween#hasStarted + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this.hasStarted = false; + + /** + * Is this Tween currently seeking? + * This boolean is toggled in the `Tween.seek` method. + * When a tween is seeking it will not dispatch any events or callbacks. + * + * @name Phaser.Tweens.Tween#isSeeking + * @type {boolean} + * @readonly + * @since 3.19.0 + */ + this.isSeeking = false; + + /** + * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = -1 (as it never completes) + * + * @name Phaser.Tweens.Tween#completeDelay + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.completeDelay = 0; + + /** + * Countdown timer (used by timeline offset, loopDelay and completeDelay) + * + * @name Phaser.Tweens.Tween#countdown + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.countdown = 0; + + /** + * Set only if this Tween is part of a Timeline. + * + * @name Phaser.Tweens.Tween#offset + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.offset = 0; + + /** + * Set only if this Tween is part of a Timeline. The calculated offset amount. + * + * @name Phaser.Tweens.Tween#calculatedOffset + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.calculatedOffset = 0; + + /** + * The current state of the tween + * + * @name Phaser.Tweens.Tween#state + * @type {integer} + * @since 3.0.0 + */ + this.state = TWEEN_CONST.PENDING_ADD; + + /** + * The state of the tween when it was paused (used by Resume) + * + * @name Phaser.Tweens.Tween#_pausedState + * @type {integer} + * @private + * @since 3.0.0 + */ + this._pausedState = TWEEN_CONST.INIT; + + /** + * Does the Tween start off paused? (if so it needs to be started with Tween.play) + * + * @name Phaser.Tweens.Tween#paused + * @type {boolean} + * @default false + * @since 3.0.0 + */ + this.paused = false; + + /** + * Elapsed time in ms/frames of this run through the Tween. + * + * @name Phaser.Tweens.Tween#elapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.elapsed = 0; + + /** + * Total elapsed time in ms/frames of the entire Tween, including looping. + * + * @name Phaser.Tweens.Tween#totalElapsed + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalElapsed = 0; + + /** + * Time in ms/frames for the whole Tween to play through once, excluding loop amounts and loop delays. + * + * @name Phaser.Tweens.Tween#duration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.duration = 0; + + /** + * Value between 0 and 1. The amount through the Tween, excluding loops. + * + * @name Phaser.Tweens.Tween#progress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.progress = 0; + + /** + * Time in ms/frames for the Tween to complete (including looping) + * + * @name Phaser.Tweens.Tween#totalDuration + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalDuration = 0; + + /** + * Value between 0 and 1. The amount through the entire Tween, including looping. + * + * @name Phaser.Tweens.Tween#totalProgress + * @type {number} + * @default 0 + * @since 3.0.0 + */ + this.totalProgress = 0; + + /** + * An object containing the different Tween callback functions. + * + * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. + * + * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. + * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. + * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. + * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. + * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. + * `onUpdate` When a TweenData updates a property on a source target during playback. + * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. + * + * @name Phaser.Tweens.Tween#callbacks + * @type {object} + * @since 3.0.0 + */ + this.callbacks = { + onActive: null, + onComplete: null, + onLoop: null, + onRepeat: null, + onStart: null, + onUpdate: null, + onYoyo: null + }; + + /** + * The context in which all callbacks are invoked. + * + * @name Phaser.Tweens.Tween#callbackScope + * @type {any} + * @since 3.0.0 + */ + this.callbackScope; + }, + + /** + * Returns the current value of the specified Tween Data. + * + * @method Phaser.Tweens.Tween#getValue + * @since 3.0.0 + * + * @param {integer} [index=0] - The Tween Data to return the value from. + * + * @return {number} The value of the requested Tween Data. + */ + getValue: function (index) + { + if (index === undefined) { index = 0; } + + return this.data[index].current; + }, + + /** + * Set the scale the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * + * @method Phaser.Tweens.Tween#setTimeScale + * @since 3.0.0 + * + * @param {number} value - The scale factor for timescale. + * + * @return {this} - This Tween instance. + */ + setTimeScale: function (value) + { + this.timeScale = value; + + return this; + }, + + /** + * Returns the scale of the time applied to this Tween. + * + * @method Phaser.Tweens.Tween#getTimeScale + * @since 3.0.0 + * + * @return {number} The timescale of this tween (between 0 and 1) + */ + getTimeScale: function () + { + return this.timeScale; + }, + + /** + * Checks if the Tween is currently active. + * + * @method Phaser.Tweens.Tween#isPlaying + * @since 3.0.0 + * + * @return {boolean} `true` if the Tween is active, otherwise `false`. + */ + isPlaying: function () + { + return (this.state === TWEEN_CONST.ACTIVE); + }, + + /** + * Checks if the Tween is currently paused. + * + * @method Phaser.Tweens.Tween#isPaused + * @since 3.0.0 + * + * @return {boolean} `true` if the Tween is paused, otherwise `false`. + */ + isPaused: function () + { + return (this.state === TWEEN_CONST.PAUSED); + }, + + /** + * See if this Tween is currently acting upon the given target. + * + * @method Phaser.Tweens.Tween#hasTarget + * @since 3.0.0 + * + * @param {object} target - The target to check against this Tween. + * + * @return {boolean} `true` if the given target is a target of this Tween, otherwise `false`. + */ + hasTarget: function (target) + { + return (this.targets.indexOf(target) !== -1); + }, + + /** + * Updates the 'end' value of the given property across all matching targets. + * + * Calling this does not adjust the duration of the tween, or the current progress. + * + * You can optionally tell it to set the 'start' value to be the current value (before the change). + * + * @method Phaser.Tweens.Tween#updateTo + * @since 3.0.0 + * + * @param {string} key - The property to set the new value for. + * @param {*} value - The new value of the property. + * @param {boolean} [startToCurrent=false] - Should this change set the start value to be the current value? + * + * @return {this} - This Tween instance. + */ + updateTo: function (key, value, startToCurrent) + { + if (startToCurrent === undefined) { startToCurrent = false; } + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = this.data[i]; + + if (tweenData.key === key) + { + tweenData.end = value; + + if (startToCurrent) + { + tweenData.start = tweenData.current; + } + } + } + + return this; + }, + + /** + * Restarts the tween from the beginning. + * + * @method Phaser.Tweens.Tween#restart + * @since 3.0.0 + * + * @return {this} This Tween instance. + */ + restart: function () + { + // Reset these so they're ready for the next update + this.elapsed = 0; + this.progress = 0; + this.totalElapsed = 0; + this.totalProgress = 0; + + if (this.state === TWEEN_CONST.ACTIVE) + { + return this.seek(0); + } + else if (this.state === TWEEN_CONST.REMOVED) + { + this.seek(0); + this.parent.makeActive(this); + + return this; + } + else if (this.state === TWEEN_CONST.PENDING_ADD) + { + return this; + } + else + { + return this.play(); + } + }, + + /** + * Internal method that calculates the overall duration of the Tween. + * + * @method Phaser.Tweens.Tween#calcDuration + * @since 3.0.0 + */ + calcDuration: function () + { + var maxDuration = 0; + var minDelay = MATH_CONST.MAX_SAFE_INTEGER; + + var data = this.data; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = data[i]; + + // Set t1 (duration + hold + yoyo) + tweenData.t1 = tweenData.duration + tweenData.hold; + + if (tweenData.yoyo) + { + tweenData.t1 += tweenData.duration; + } + + // Set t2 (repeatDelay + duration + hold + yoyo) + tweenData.t2 = tweenData.t1 + tweenData.repeatDelay; + + // Total Duration + tweenData.totalDuration = tweenData.delay + tweenData.t1; + + if (tweenData.repeat === -1) + { + tweenData.totalDuration += (tweenData.t2 * 999999999999); + } + else if (tweenData.repeat > 0) + { + tweenData.totalDuration += (tweenData.t2 * tweenData.repeat); + } + + if (tweenData.totalDuration > maxDuration) + { + // Get the longest TweenData from the Tween, used to calculate the Tween TD + maxDuration = tweenData.totalDuration; + } + + if (tweenData.delay < minDelay) + { + minDelay = tweenData.delay; + } + } + + // Excludes loop values + + // If duration has been set to 0 then we give it a super-low value so that it always + // renders at least 1 frame, but no more, without causing divided by zero errors elsewhere. + this.duration = Math.max(maxDuration, 0.001); + + this.loopCounter = (this.loop === -1) ? 999999999999 : this.loop; + + if (this.loopCounter > 0) + { + this.totalDuration = this.duration + this.completeDelay + ((this.duration + this.loopDelay) * this.loopCounter); + } + else + { + this.totalDuration = this.duration + this.completeDelay; + } + + // How long before this Tween starts playback? + this.startDelay = minDelay; + }, + + /** + * Called by TweenManager.preUpdate as part of its loop to check pending and active tweens. + * Should not be called directly. + * + * @method Phaser.Tweens.Tween#init + * @since 3.0.0 + * + * @return {boolean} Returns `true` if this Tween should be moved from the pending list to the active list by the Tween Manager. + */ + init: function () + { + // You can't have a paused Tween if it's part of a Timeline + if (this.paused && !this.parentIsTimeline) + { + this.state = TWEEN_CONST.PENDING_ADD; + this._pausedState = TWEEN_CONST.INIT; + + return false; + } + + var data = this.data; + var totalTargets = this.totalTargets; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = data[i]; + var target = tweenData.target; + var gen = tweenData.gen; + var key = tweenData.key; + var targetIndex = tweenData.index; + + // Old function signature: i, totalTargets, target + // New function signature: target, key, value, index, total, tween + + tweenData.delay = gen.delay(target, key, 0, targetIndex, totalTargets, this); + tweenData.duration = Math.max(gen.duration(target, key, 0, targetIndex, totalTargets, this), 0.001); + tweenData.hold = gen.hold(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeat = gen.repeat(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeatDelay = gen.repeatDelay(target, key, 0, targetIndex, totalTargets, this); + } + + this.calcDuration(); + + this.progress = 0; + this.totalProgress = 0; + this.elapsed = 0; + this.totalElapsed = 0; + + this.state = TWEEN_CONST.INIT; + + return true; + }, + + /** + * Internal method that makes this Tween active within the TweenManager + * and emits the onActive event and callback. + * + * @method Phaser.Tweens.Tween#makeActive + * @fires Phaser.Tweens.Events#TWEEN_ACTIVE + * @since 3.19.0 + */ + makeActive: function () + { + this.parent.makeActive(this); + + this.dispatchTweenEvent(Events.TWEEN_ACTIVE, this.callbacks.onActive); + }, + + /** + * Internal method that advances to the next state of the Tween during playback. + * + * @method Phaser.Tweens.Tween#nextState + * @fires Phaser.Tweens.Events#TWEEN_COMPLETE + * @fires Phaser.Tweens.Events#TWEEN_LOOP + * @since 3.0.0 + */ + nextState: function () + { + if (this.loopCounter > 0) + { + this.elapsed = 0; + this.progress = 0; + this.loopCounter--; + + this.resetTweenData(true); + + if (this.loopDelay > 0) + { + this.countdown = this.loopDelay; + this.state = TWEEN_CONST.LOOP_DELAY; + } + else + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTweenEvent(Events.TWEEN_LOOP, this.callbacks.onLoop); + } + } + else if (this.completeDelay > 0) + { + this.state = TWEEN_CONST.COMPLETE_DELAY; + + this.countdown = this.completeDelay; + } + else + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); + } + }, + + /** + * Pauses the Tween immediately. Use `resume` to continue playback. + * + * @method Phaser.Tweens.Tween#pause + * @since 3.0.0 + * + * @return {this} - This Tween instance. + */ + pause: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + return this; + } + + this.paused = true; + + this._pausedState = this.state; + + this.state = TWEEN_CONST.PAUSED; + + return this; + }, + + /** + * Starts a Tween playing. + * + * You only need to call this method if you have configured the tween to be paused on creation. + * + * If the Tween is already playing, calling this method again will have no effect. If you wish to + * restart the Tween, use `Tween.restart` instead. + * + * Calling this method after the Tween has completed will start the Tween playing again from the start. + * This is the same as calling `Tween.seek(0)` and then `Tween.play()`. + * + * @method Phaser.Tweens.Tween#play + * @since 3.0.0 + * + * @param {boolean} [resetFromTimeline=false] - Is this Tween being played as part of a Timeline? + * + * @return {this} This Tween instance. + */ + play: function (resetFromTimeline) + { + if (resetFromTimeline === undefined) { resetFromTimeline = false; } + + var state = this.state; + + if (state === TWEEN_CONST.INIT && !this.parentIsTimeline) + { + this.resetTweenData(false); + + this.state = TWEEN_CONST.ACTIVE; + + return this; + } + else if (state === TWEEN_CONST.ACTIVE || (state === TWEEN_CONST.PENDING_ADD && this._pausedState === TWEEN_CONST.PENDING_ADD)) + { + return this; + } + else if (!this.parentIsTimeline && (state === TWEEN_CONST.PENDING_REMOVE || state === TWEEN_CONST.REMOVED)) + { + this.seek(0); + this.parent.makeActive(this); + + return this; + } + + if (this.parentIsTimeline) + { + this.resetTweenData(resetFromTimeline); + + if (this.calculatedOffset === 0) + { + this.state = TWEEN_CONST.ACTIVE; + } + else + { + this.countdown = this.calculatedOffset; + + this.state = TWEEN_CONST.OFFSET_DELAY; + } + } + else if (this.paused) + { + this.paused = false; + + this.makeActive(); + } + else + { + this.resetTweenData(resetFromTimeline); + + this.state = TWEEN_CONST.ACTIVE; + + this.makeActive(); + } + + return this; + }, + + /** + * Internal method that resets all of the Tween Data, including the progress and elapsed values. + * + * @method Phaser.Tweens.Tween#resetTweenData + * @since 3.0.0 + * + * @param {boolean} resetFromLoop - Has this method been called as part of a loop? + */ + resetTweenData: function (resetFromLoop) + { + var data = this.data; + var total = this.totalData; + var totalTargets = this.totalTargets; + + for (var i = 0; i < total; i++) + { + var tweenData = data[i]; + + var target = tweenData.target; + var key = tweenData.key; + var targetIndex = tweenData.index; + + tweenData.progress = 0; + tweenData.elapsed = 0; + + tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; + + if (resetFromLoop) + { + tweenData.start = tweenData.getStartValue(target, key, tweenData.start, targetIndex, totalTargets, this); + + tweenData.end = tweenData.getEndValue(target, key, tweenData.end, targetIndex, totalTargets, this); + + tweenData.current = tweenData.start; + + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + } + else + { + tweenData.state = TWEEN_CONST.PENDING_RENDER; + } + + if (tweenData.delay > 0) + { + tweenData.elapsed = tweenData.delay; + + tweenData.state = TWEEN_CONST.DELAY; + } + + if (tweenData.getActiveValue) + { + target[key] = tweenData.getActiveValue(tweenData.target, tweenData.key, tweenData.start); + } + } + }, + + /** + * Resumes the playback of a previously paused Tween. + * + * @method Phaser.Tweens.Tween#resume + * @since 3.0.0 + * + * @return {this} - This Tween instance. + */ + resume: function () + { + if (this.state === TWEEN_CONST.PAUSED) + { + this.paused = false; + + this.state = this._pausedState; + } + else + { + this.play(); + } + + return this; + }, + + /** + * Seeks to a specific point in the Tween. + * + * **Note:** You cannot seek a Tween that repeats or loops forever, or that has an unusually long total duration. + * + * The given position is a value between 0 and 1 which represents how far through the Tween to seek to. + * A value of 0.5 would seek to half-way through the Tween, where-as a value of zero would seek to the start. + * + * Note that the seek 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 0.5 would seek to 3 seconds into the Tween, as that's half-way through its _entire_ duration. + * + * 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. + * + * @method Phaser.Tweens.Tween#seek + * @since 3.0.0 + * + * @param {number} toPosition - A value between 0 and 1 which represents the progress point to seek to. + * @param {number} [delta=16.6] - The size of each step when seeking through the Tween. A higher value completes faster but at a cost of less precision. + * + * @return {this} This Tween instance. + */ + seek: function (toPosition, delta) + { + if (delta === undefined) { delta = 16.6; } + + if (this.totalDuration >= 3600000) + { + console.warn('Tween.seek duration too long'); + + return this; + } + + if (this.state === TWEEN_CONST.REMOVED) + { + this.makeActive(); + } + + this.elapsed = 0; + this.progress = 0; + this.totalElapsed = 0; + this.totalProgress = 0; + + var data = this.data; + var totalTargets = this.totalTargets; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = data[i]; + var target = tweenData.target; + var gen = tweenData.gen; + var key = tweenData.key; + var targetIndex = tweenData.index; + + tweenData.progress = 0; + tweenData.elapsed = 0; + + tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; + + // Old function signature: i, totalTargets, target + // New function signature: target, key, value, index, total, tween + + tweenData.delay = gen.delay(target, key, 0, targetIndex, totalTargets, this); + tweenData.duration = Math.max(gen.duration(target, key, 0, targetIndex, totalTargets, this), 0.001); + tweenData.hold = gen.hold(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeat = gen.repeat(target, key, 0, targetIndex, totalTargets, this); + tweenData.repeatDelay = gen.repeatDelay(target, key, 0, targetIndex, totalTargets, this); + + tweenData.current = tweenData.start; + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + + this.updateTweenData(this, tweenData, 0, targetIndex, totalTargets); + + if (tweenData.delay > 0) + { + tweenData.elapsed = tweenData.delay; + tweenData.state = TWEEN_CONST.DELAY; + } + } + + this.calcDuration(); + + var wasPaused = false; + + if (this.state === TWEEN_CONST.PAUSED) + { + wasPaused = true; + + this.state = TWEEN_CONST.ACTIVE; + } + + this.isSeeking = true; + + do + { + this.update(0, delta); + + } while (this.totalProgress < toPosition); + + this.isSeeking = false; + + if (wasPaused) + { + this.state = TWEEN_CONST.PAUSED; + } + + return this; + }, + + /** + * Sets an event based callback to be invoked during playback. + * + * Calling this method will replace a previously set callback for the given type, if any exists. + * + * The types available are: + * + * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. + * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. + * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. + * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. + * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. + * `onUpdate` When a TweenData updates a property on a source target during playback. + * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. + * + * @method Phaser.Tweens.Tween#setCallback + * @since 3.0.0 + * + * @param {string} type - Type of the callback to set. + * @param {function} callback - The function to invoke when this callback happens. + * @param {array} [params] - An array of parameters for specified callbacks types. + * @param {any} [scope] - The context the callback will be invoked in. + * + * @return {this} This Tween instance. + */ + setCallback: function (type, callback, params, scope) + { + this.callbacks[type] = { func: callback, scope: scope, params: params }; + + return this; + }, + + /** + * Flags the Tween as being complete, whatever stage of progress it is at. + * + * If an onComplete callback has been defined it will automatically invoke it, unless a `delay` + * argument is provided, in which case the Tween will delay for that period of time before calling the callback. + * + * If you don't need a delay, or have an onComplete callback, then call `Tween.stop` instead. + * + * @method Phaser.Tweens.Tween#complete + * @fires Phaser.Tweens.Events#TWEEN_COMPLETE + * @since 3.2.0 + * + * @param {number} [delay=0] - The time to wait before invoking the complete callback. If zero it will fire immediately. + * + * @return {this} This Tween instance. + */ + complete: function (delay) + { + if (delay === undefined) { delay = 0; } + + if (delay) + { + this.state = TWEEN_CONST.COMPLETE_DELAY; + + this.countdown = delay; + } + else + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); + } + + return this; + }, + + /** + * Immediately removes this Tween from the TweenManager and all of its internal arrays, + * no matter what stage it as it. Then sets the tween state to `REMOVED`. + * + * You should dispose of your reference to this tween after calling this method, to + * free it from memory. + * + * @method Phaser.Tweens.Tween#remove + * @since 3.17.0 + * + * @return {this} This Tween instance. + */ + remove: function () + { + this.parent.remove(this); + + return this; + }, + + /** + * Stops the Tween immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. + * + * @method Phaser.Tweens.Tween#stop + * @since 3.0.0 + * + * @param {number} [resetTo] - If you want to seek the tween, provide a value between 0 and 1. + * + * @return {this} This Tween instance. + */ + stop: function (resetTo) + { + if (this.state === TWEEN_CONST.ACTIVE) + { + if (resetTo !== undefined) + { + this.seek(resetTo); + } + } + + if (this.state !== TWEEN_CONST.REMOVED) + { + if (this.state === TWEEN_CONST.PAUSED || this.state === TWEEN_CONST.PENDING_ADD) + { + if (this.parentIsTimeline) + { + this.parent.manager._destroy.push(this); + this.parent.manager._toProcess++; + } + else + { + this.parent._destroy.push(this); + this.parent._toProcess++; + } + } + + this.removeAllListeners(); + + this.state = TWEEN_CONST.PENDING_REMOVE; + } + + return this; + }, + + /** + * 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} timestamp - 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} Returns `true` if this Tween has finished and should be removed from the Tween Manager, otherwise returns `false`. + */ + update: function (timestamp, delta) + { + if (this.state === TWEEN_CONST.PAUSED) + { + return false; + } + + if (this.useFrames) + { + delta = 1 * this.parent.timeScale; + } + + delta *= this.timeScale; + + this.elapsed += delta; + this.progress = Math.min(this.elapsed / this.duration, 1); + + this.totalElapsed += delta; + this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); + + switch (this.state) + { + case TWEEN_CONST.ACTIVE: + + if (!this.hasStarted && !this.isSeeking) + { + this.startDelay -= delta; + + if (this.startDelay <= 0) + { + this.hasStarted = true; + + this.dispatchTweenEvent(Events.TWEEN_START, this.callbacks.onStart); + } + } + + var stillRunning = false; + + for (var i = 0; i < this.totalData; i++) + { + var tweenData = this.data[i]; + + if (this.updateTweenData(this, tweenData, delta)) + { + stillRunning = true; + } + } + + // Anything still running? If not, we're done + if (!stillRunning) + { + this.nextState(); + } + + break; + + case TWEEN_CONST.LOOP_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.ACTIVE; + + this.dispatchTweenEvent(Events.TWEEN_LOOP, this.callbacks.onLoop); + } + + break; + + case TWEEN_CONST.OFFSET_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.ACTIVE; + } + + break; + + case TWEEN_CONST.COMPLETE_DELAY: + + this.countdown -= delta; + + if (this.countdown <= 0) + { + this.state = TWEEN_CONST.PENDING_REMOVE; + + this.dispatchTweenEvent(Events.TWEEN_COMPLETE, this.callbacks.onComplete); + } + + break; + } + + return (this.state === TWEEN_CONST.PENDING_REMOVE); + }, + + /** + * Internal method that will emit a TweenData based Event and invoke the given callback. + * + * @method Phaser.Tweens.Tween#dispatchTweenDataEvent + * @since 3.19.0 + * + * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. + * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData object that caused this event. + */ + dispatchTweenDataEvent: function (event, callback, tweenData) + { + if (!this.isSeeking) + { + this.emit(event, this, tweenData.key, tweenData.target, tweenData.current, tweenData.previous); + + if (callback) + { + callback.params[1] = tweenData.target; + + callback.func.apply(callback.scope, callback.params); + } + } + }, + + /** + * Internal method that will emit a Tween based Event and invoke the given callback. + * + * @method Phaser.Tweens.Tween#dispatchTweenEvent + * @since 3.19.0 + * + * @param {Phaser.Types.Tweens.Event} event - The Event to be dispatched. + * @param {function} callback - The callback to be invoked. Can be `null` or `undefined` to skip invocation. + */ + dispatchTweenEvent: function (event, callback) + { + if (!this.isSeeking) + { + this.emit(event, this, this.targets); + + if (callback) + { + callback.params[1] = this.targets; + + callback.func.apply(callback.scope, callback.params); + } + } + }, + + /** + * Internal method used as part of the playback process that sets a tween to play in reverse. + * + * @method Phaser.Tweens.Tween#setStateFromEnd + * @fires Phaser.Tweens.Events#TWEEN_REPEAT + * @fires Phaser.Tweens.Events#TWEEN_YOYO + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to update. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. + * @param {number} diff - Any extra time that needs to be accounted for in the elapsed and progress values. + * + * @return {integer} The state of this Tween. + */ + setStateFromEnd: function (tween, tweenData, diff) + { + if (tweenData.yoyo) + { + // We've hit the end of a Playing Forward TweenData and we have a yoyo + + // Account for any extra time we got from the previous frame + tweenData.elapsed = diff; + tweenData.progress = diff / tweenData.duration; + + if (tweenData.flipX) + { + tweenData.target.toggleFlipX(); + } + + if (tweenData.flipY) + { + tweenData.target.toggleFlipY(); + } + + this.dispatchTweenDataEvent(Events.TWEEN_YOYO, tween.callbacks.onYoyo, tweenData); + + tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + return TWEEN_CONST.PLAYING_BACKWARD; + } + else if (tweenData.repeatCounter > 0) + { + // We've hit the end of a Playing Forward TweenData and we have a Repeat. + // So we're going to go right back to the start to repeat it again. + + tweenData.repeatCounter--; + + // Account for any extra time we got from the previous frame + tweenData.elapsed = diff; + tweenData.progress = diff / tweenData.duration; + + if (tweenData.flipX) + { + tweenData.target.toggleFlipX(); + } + + if (tweenData.flipY) + { + tweenData.target.toggleFlipY(); + } + + tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + // Delay? + if (tweenData.repeatDelay > 0) + { + tweenData.elapsed = tweenData.repeatDelay - diff; + + tweenData.current = tweenData.start; + + tweenData.target[tweenData.key] = tweenData.current; + + return TWEEN_CONST.REPEAT_DELAY; + } + else + { + this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); + + return TWEEN_CONST.PLAYING_FORWARD; + } + } + + return TWEEN_CONST.COMPLETE; + }, + + /** + * Internal method used as part of the playback process that sets a tween to play from the start. + * + * @method Phaser.Tweens.Tween#setStateFromStart + * @fires Phaser.Tweens.Events#TWEEN_REPEAT + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to update. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. + * @param {number} diff - Any extra time that needs to be accounted for in the elapsed and progress values. + * + * @return {integer} The state of this Tween. + */ + setStateFromStart: function (tween, tweenData, diff) + { + if (tweenData.repeatCounter > 0) + { + tweenData.repeatCounter--; + + // Account for any extra time we got from the previous frame + tweenData.elapsed = diff; + tweenData.progress = diff / tweenData.duration; + + if (tweenData.flipX) + { + tweenData.target.toggleFlipX(); + } + + if (tweenData.flipY) + { + tweenData.target.toggleFlipY(); + } + + tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + // Delay? + if (tweenData.repeatDelay > 0) + { + tweenData.elapsed = tweenData.repeatDelay - diff; + + tweenData.current = tweenData.start; + + tweenData.target[tweenData.key] = tweenData.current; + + return TWEEN_CONST.REPEAT_DELAY; + } + else + { + this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); + + return TWEEN_CONST.PLAYING_FORWARD; + } + } + + return TWEEN_CONST.COMPLETE; + }, + + /** + * Internal method that advances the TweenData based on the time value given. + * + * @method Phaser.Tweens.Tween#updateTweenData + * @fires Phaser.Tweens.Events#TWEEN_UPDATE + * @fires Phaser.Tweens.Events#TWEEN_REPEAT + * @since 3.0.0 + * + * @param {Phaser.Tweens.Tween} tween - The Tween to update. + * @param {Phaser.Types.Tweens.TweenDataConfig} tweenData - The TweenData property to update. + * @param {number} delta - Either a value in ms, or 1 if Tween.useFrames is true. + * + * @return {boolean} True if the tween is not complete (e.g., playing), or false if the tween is complete. + */ + updateTweenData: function (tween, tweenData, delta) + { + var target = tweenData.target; + + switch (tweenData.state) + { + case TWEEN_CONST.PLAYING_FORWARD: + case TWEEN_CONST.PLAYING_BACKWARD: + + if (!target) + { + tweenData.state = TWEEN_CONST.COMPLETE; + break; + } + + var elapsed = tweenData.elapsed; + var duration = tweenData.duration; + var diff = 0; + + elapsed += delta; + + if (elapsed > duration) + { + diff = elapsed - duration; + elapsed = duration; + } + + var forward = (tweenData.state === TWEEN_CONST.PLAYING_FORWARD); + var progress = elapsed / duration; + + tweenData.elapsed = elapsed; + tweenData.progress = progress; + tweenData.previous = tweenData.current; + + if (progress === 1) + { + if (forward) + { + tweenData.current = tweenData.end; + target[tweenData.key] = tweenData.end; + + if (tweenData.hold > 0) + { + tweenData.elapsed = tweenData.hold - diff; + + tweenData.state = TWEEN_CONST.HOLD_DELAY; + } + else + { + tweenData.state = this.setStateFromEnd(tween, tweenData, diff); + } + } + else + { + tweenData.current = tweenData.start; + target[tweenData.key] = tweenData.start; + + tweenData.state = this.setStateFromStart(tween, tweenData, diff); + } + } + else + { + var v = (forward) ? tweenData.ease(progress) : tweenData.ease(1 - progress); + + tweenData.current = tweenData.start + ((tweenData.end - tweenData.start) * v); + + target[tweenData.key] = tweenData.current; + } + + this.dispatchTweenDataEvent(Events.TWEEN_UPDATE, tween.callbacks.onUpdate, tweenData); + + break; + + case TWEEN_CONST.DELAY: + + tweenData.elapsed -= delta; + + if (tweenData.elapsed <= 0) + { + tweenData.elapsed = Math.abs(tweenData.elapsed); + + tweenData.state = TWEEN_CONST.PENDING_RENDER; + } + + break; + + case TWEEN_CONST.REPEAT_DELAY: + + tweenData.elapsed -= delta; + + if (tweenData.elapsed <= 0) + { + tweenData.elapsed = Math.abs(tweenData.elapsed); + + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + + this.dispatchTweenDataEvent(Events.TWEEN_REPEAT, tween.callbacks.onRepeat, tweenData); + } + + break; + + case TWEEN_CONST.HOLD_DELAY: + + tweenData.elapsed -= delta; + + if (tweenData.elapsed <= 0) + { + tweenData.state = this.setStateFromEnd(tween, tweenData, Math.abs(tweenData.elapsed)); + } + + break; + + case TWEEN_CONST.PENDING_RENDER: + + if (target) + { + tweenData.start = tweenData.getStartValue(target, tweenData.key, target[tweenData.key], tweenData.index, tween.totalTargets, tween); + + tweenData.end = tweenData.getEndValue(target, tweenData.key, tweenData.start, tweenData.index, tween.totalTargets, tween); + + tweenData.current = tweenData.start; + + target[tweenData.key] = tweenData.start; + + tweenData.state = TWEEN_CONST.PLAYING_FORWARD; + } + else + { + tweenData.state = TWEEN_CONST.COMPLETE; + } + + break; + } + + // Return TRUE if this TweenData still playing, otherwise return FALSE + return (tweenData.state !== TWEEN_CONST.COMPLETE); + } + +}); + +// onActive = 'active' event = When the Tween is moved from the pending to the active list in the manager, even if playback delayed +// onStart = 'start' event = When the Tween starts playing from a delayed state (will happen same time as onActive if no delay) +// onYoyo = 'yoyo' event = When the Tween starts a yoyo +// onRepeat = 'repeat' event = When a TweenData repeats playback (if any) +// onComplete = 'complete' event = When the Tween finishes all playback (can sometimes never happen if repeat -1), also when 'stop' called +// onUpdate = 'update' event = When the Tween updates a TweenData during playback (expensive!) +// onLoop = 'loop' event = Used to loop ALL TweenDatas in a Tween + +Tween.TYPES = [ + 'onActive', + 'onComplete', + 'onLoop', + 'onRepeat', + 'onStart', + 'onUpdate', + 'onYoyo' +]; + +/** + * Creates a new Tween object. + * + * Note: This method will only be available if Tweens have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectFactory#tween + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The Tween configuration. + * + * @return {Phaser.Tweens.Tween} The Tween that was created. + */ +GameObjectFactory.register('tween', function (config) +{ + return this.scene.sys.tweens.add(config); +}); + +// 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 + +/** + * Creates a new Tween object and returns it. + * + * Note: This method will only be available if Tweens have been built into Phaser. + * + * @method Phaser.GameObjects.GameObjectCreator#tween + * @since 3.0.0 + * + * @param {Phaser.Types.Tweens.TweenBuilderConfig|object} config - The Tween configuration. + * + * @return {Phaser.Tweens.Tween} The Tween that was created. + */ +GameObjectCreator.register('tween', function (config) +{ + return this.scene.sys.tweens.create(config); +}); + +// When registering a factory function 'this' refers to the GameObjectCreator context. + +module.exports = Tween; diff --git a/src/tweens/tween/TweenData.js b/src/tweens/tween/TweenData.js index eeda85af7..68c0b3b17 100644 --- a/src/tweens/tween/TweenData.js +++ b/src/tweens/tween/TweenData.js @@ -1,121 +1,121 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns a TweenDataConfig object that describes the tween data for a unique property of a unique target. - * A single Tween consists of multiple TweenDatas, depending on how many properties are being changed by the Tween. - * - * This is an internal function used by the TweenBuilder and should not be accessed directly, instead, - * Tweens should be created using the GameObjectFactory or GameObjectCreator. - * - * @function Phaser.Tweens.TweenData - * @since 3.0.0 - * - * @param {any} target - The target to tween. - * @param {integer} index - The target index within the Tween targets array. - * @param {string} key - The property of the target to tween. - * @param {function} getEnd - What the property will be at the END of the Tween. - * @param {function} getStart - What the property will be at the START of the Tween. - * @param {?function} getActive - If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. - * @param {function} ease - The ease function this tween uses. - * @param {number} delay - Time in ms/frames before tween will start. - * @param {number} duration - Duration of the tween in ms/frames. - * @param {boolean} yoyo - Determines whether the tween should return back to its start value after hold has expired. - * @param {number} hold - Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. - * @param {number} repeat - Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - * @param {number} repeatDelay - Time in ms/frames before the repeat will start. - * @param {boolean} flipX - Should toggleFlipX be called when yoyo or repeat happens? - * @param {boolean} flipY - Should toggleFlipY be called when yoyo or repeat happens? - * - * @return {Phaser.Types.Tweens.TweenDataConfig} The config object describing this TweenData. - */ -var TweenData = function (target, index, key, getEnd, getStart, getActive, ease, delay, duration, yoyo, hold, repeat, repeatDelay, flipX, flipY) -{ - return { - - // The target to tween - target: target, - - // The index of the target within the tween targets array - index: index, - - // The property of the target to tween - key: key, - - // What to set the property to the moment the TweenData is invoked. - getActiveValue: getActive, - - // The returned value sets what the property will be at the END of the Tween. - getEndValue: getEnd, - - // The returned value sets what the property will be at the START of the Tween. - getStartValue: getStart, - - // The ease function this tween uses. - ease: ease, - - // Duration of the tween in ms/frames, excludes time for yoyo or repeats. - duration: 0, - - // The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) - totalDuration: 0, - - // Time in ms/frames before tween will start. - delay: 0, - - // Cause the tween to return back to its start value after hold has expired. - yoyo: yoyo, - - // Time in ms/frames the tween will pause before running the yoyo or starting a repeat. - hold: 0, - - // Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - repeat: 0, - - // Time in ms/frames before the repeat will start. - repeatDelay: 0, - - // Automatically call toggleFlipX when the TweenData yoyos or repeats - flipX: flipX, - - // Automatically call toggleFlipY when the TweenData yoyos or repeats - flipY: flipY, - - // Between 0 and 1 showing completion of this TweenData. - progress: 0, - - // Delta counter. - elapsed: 0, - - // How many repeats are left to run? - repeatCounter: 0, - - // Ease Value Data: - - start: 0, - previous: 0, - current: 0, - end: 0, - - // Time Durations - t1: 0, - t2: 0, - - // LoadValue generation functions - gen: { - delay: delay, - duration: duration, - hold: hold, - repeat: repeat, - repeatDelay: repeatDelay - }, - - // TWEEN_CONST.CREATED - state: 0 - }; -}; - -module.exports = TweenData; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns a TweenDataConfig object that describes the tween data for a unique property of a unique target. + * A single Tween consists of multiple TweenDatas, depending on how many properties are being changed by the Tween. + * + * This is an internal function used by the TweenBuilder and should not be accessed directly, instead, + * Tweens should be created using the GameObjectFactory or GameObjectCreator. + * + * @function Phaser.Tweens.TweenData + * @since 3.0.0 + * + * @param {any} target - The target to tween. + * @param {integer} index - The target index within the Tween targets array. + * @param {string} key - The property of the target to tween. + * @param {function} getEnd - What the property will be at the END of the Tween. + * @param {function} getStart - What the property will be at the START of the Tween. + * @param {?function} getActive - If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. + * @param {function} ease - The ease function this tween uses. + * @param {number} delay - Time in ms/frames before tween will start. + * @param {number} duration - Duration of the tween in ms/frames. + * @param {boolean} yoyo - Determines whether the tween should return back to its start value after hold has expired. + * @param {number} hold - Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. + * @param {number} repeat - Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + * @param {number} repeatDelay - Time in ms/frames before the repeat will start. + * @param {boolean} flipX - Should toggleFlipX be called when yoyo or repeat happens? + * @param {boolean} flipY - Should toggleFlipY be called when yoyo or repeat happens? + * + * @return {Phaser.Types.Tweens.TweenDataConfig} The config object describing this TweenData. + */ +var TweenData = function (target, index, key, getEnd, getStart, getActive, ease, delay, duration, yoyo, hold, repeat, repeatDelay, flipX, flipY) +{ + return { + + // The target to tween + target: target, + + // The index of the target within the tween targets array + index: index, + + // The property of the target to tween + key: key, + + // What to set the property to the moment the TweenData is invoked. + getActiveValue: getActive, + + // The returned value sets what the property will be at the END of the Tween. + getEndValue: getEnd, + + // The returned value sets what the property will be at the START of the Tween. + getStartValue: getStart, + + // The ease function this tween uses. + ease: ease, + + // Duration of the tween in ms/frames, excludes time for yoyo or repeats. + duration: 0, + + // The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) + totalDuration: 0, + + // Time in ms/frames before tween will start. + delay: 0, + + // Cause the tween to return back to its start value after hold has expired. + yoyo: yoyo, + + // Time in ms/frames the tween will pause before running the yoyo or starting a repeat. + hold: 0, + + // Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + repeat: 0, + + // Time in ms/frames before the repeat will start. + repeatDelay: 0, + + // Automatically call toggleFlipX when the TweenData yoyos or repeats + flipX: flipX, + + // Automatically call toggleFlipY when the TweenData yoyos or repeats + flipY: flipY, + + // Between 0 and 1 showing completion of this TweenData. + progress: 0, + + // Delta counter. + elapsed: 0, + + // How many repeats are left to run? + repeatCounter: 0, + + // Ease Value Data: + + start: 0, + previous: 0, + current: 0, + end: 0, + + // Time Durations + t1: 0, + t2: 0, + + // LoadValue generation functions + gen: { + delay: delay, + duration: duration, + hold: hold, + repeat: repeat, + repeatDelay: repeatDelay + }, + + // TWEEN_CONST.CREATED + state: 0 + }; +}; + +module.exports = TweenData; diff --git a/src/tweens/tween/const.js b/src/tweens/tween/const.js index abdbfd750..ed582ab8b 100644 --- a/src/tweens/tween/const.js +++ b/src/tweens/tween/const.js @@ -1,166 +1,166 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var TWEEN_CONST = { - - /** - * TweenData state. - * - * @name Phaser.Tweens.CREATED - * @type {integer} - * @since 3.0.0 - */ - CREATED: 0, - - /** - * TweenData state. - * - * @name Phaser.Tweens.INIT - * @type {integer} - * @since 3.0.0 - */ - INIT: 1, - - /** - * TweenData state. - * - * @name Phaser.Tweens.DELAY - * @type {integer} - * @since 3.0.0 - */ - DELAY: 2, - - /** - * TweenData state. - * - * @name Phaser.Tweens.OFFSET_DELAY - * @type {integer} - * @since 3.0.0 - */ - OFFSET_DELAY: 3, - - /** - * TweenData state. - * - * @name Phaser.Tweens.PENDING_RENDER - * @type {integer} - * @since 3.0.0 - */ - PENDING_RENDER: 4, - - /** - * TweenData state. - * - * @name Phaser.Tweens.PLAYING_FORWARD - * @type {integer} - * @since 3.0.0 - */ - PLAYING_FORWARD: 5, - - /** - * TweenData state. - * - * @name Phaser.Tweens.PLAYING_BACKWARD - * @type {integer} - * @since 3.0.0 - */ - PLAYING_BACKWARD: 6, - - /** - * TweenData state. - * - * @name Phaser.Tweens.HOLD_DELAY - * @type {integer} - * @since 3.0.0 - */ - HOLD_DELAY: 7, - - /** - * TweenData state. - * - * @name Phaser.Tweens.REPEAT_DELAY - * @type {integer} - * @since 3.0.0 - */ - REPEAT_DELAY: 8, - - /** - * TweenData state. - * - * @name Phaser.Tweens.COMPLETE - * @type {integer} - * @since 3.0.0 - */ - COMPLETE: 9, - - // Tween specific (starts from 20 to cleanly allow extra TweenData consts in the future) - - /** - * Tween state. - * - * @name Phaser.Tweens.PENDING_ADD - * @type {integer} - * @since 3.0.0 - */ - PENDING_ADD: 20, - - /** - * Tween state. - * - * @name Phaser.Tweens.PAUSED - * @type {integer} - * @since 3.0.0 - */ - PAUSED: 21, - - /** - * Tween state. - * - * @name Phaser.Tweens.LOOP_DELAY - * @type {integer} - * @since 3.0.0 - */ - LOOP_DELAY: 22, - - /** - * Tween state. - * - * @name Phaser.Tweens.ACTIVE - * @type {integer} - * @since 3.0.0 - */ - ACTIVE: 23, - - /** - * Tween state. - * - * @name Phaser.Tweens.COMPLETE_DELAY - * @type {integer} - * @since 3.0.0 - */ - COMPLETE_DELAY: 24, - - /** - * Tween state. - * - * @name Phaser.Tweens.PENDING_REMOVE - * @type {integer} - * @since 3.0.0 - */ - PENDING_REMOVE: 25, - - /** - * Tween state. - * - * @name Phaser.Tweens.REMOVED - * @type {integer} - * @since 3.0.0 - */ - REMOVED: 26 - -}; - -module.exports = TWEEN_CONST; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var TWEEN_CONST = { + + /** + * TweenData state. + * + * @name Phaser.Tweens.CREATED + * @type {integer} + * @since 3.0.0 + */ + CREATED: 0, + + /** + * TweenData state. + * + * @name Phaser.Tweens.INIT + * @type {integer} + * @since 3.0.0 + */ + INIT: 1, + + /** + * TweenData state. + * + * @name Phaser.Tweens.DELAY + * @type {integer} + * @since 3.0.0 + */ + DELAY: 2, + + /** + * TweenData state. + * + * @name Phaser.Tweens.OFFSET_DELAY + * @type {integer} + * @since 3.0.0 + */ + OFFSET_DELAY: 3, + + /** + * TweenData state. + * + * @name Phaser.Tweens.PENDING_RENDER + * @type {integer} + * @since 3.0.0 + */ + PENDING_RENDER: 4, + + /** + * TweenData state. + * + * @name Phaser.Tweens.PLAYING_FORWARD + * @type {integer} + * @since 3.0.0 + */ + PLAYING_FORWARD: 5, + + /** + * TweenData state. + * + * @name Phaser.Tweens.PLAYING_BACKWARD + * @type {integer} + * @since 3.0.0 + */ + PLAYING_BACKWARD: 6, + + /** + * TweenData state. + * + * @name Phaser.Tweens.HOLD_DELAY + * @type {integer} + * @since 3.0.0 + */ + HOLD_DELAY: 7, + + /** + * TweenData state. + * + * @name Phaser.Tweens.REPEAT_DELAY + * @type {integer} + * @since 3.0.0 + */ + REPEAT_DELAY: 8, + + /** + * TweenData state. + * + * @name Phaser.Tweens.COMPLETE + * @type {integer} + * @since 3.0.0 + */ + COMPLETE: 9, + + // Tween specific (starts from 20 to cleanly allow extra TweenData consts in the future) + + /** + * Tween state. + * + * @name Phaser.Tweens.PENDING_ADD + * @type {integer} + * @since 3.0.0 + */ + PENDING_ADD: 20, + + /** + * Tween state. + * + * @name Phaser.Tweens.PAUSED + * @type {integer} + * @since 3.0.0 + */ + PAUSED: 21, + + /** + * Tween state. + * + * @name Phaser.Tweens.LOOP_DELAY + * @type {integer} + * @since 3.0.0 + */ + LOOP_DELAY: 22, + + /** + * Tween state. + * + * @name Phaser.Tweens.ACTIVE + * @type {integer} + * @since 3.0.0 + */ + ACTIVE: 23, + + /** + * Tween state. + * + * @name Phaser.Tweens.COMPLETE_DELAY + * @type {integer} + * @since 3.0.0 + */ + COMPLETE_DELAY: 24, + + /** + * Tween state. + * + * @name Phaser.Tweens.PENDING_REMOVE + * @type {integer} + * @since 3.0.0 + */ + PENDING_REMOVE: 25, + + /** + * Tween state. + * + * @name Phaser.Tweens.REMOVED + * @type {integer} + * @since 3.0.0 + */ + REMOVED: 26 + +}; + +module.exports = TWEEN_CONST; diff --git a/src/tweens/typedefs/TweenBuilderConfig.js b/src/tweens/typedefs/TweenBuilderConfig.js index a764b5cce..03d7da521 100644 --- a/src/tweens/typedefs/TweenBuilderConfig.js +++ b/src/tweens/typedefs/TweenBuilderConfig.js @@ -1,60 +1,60 @@ -/** - * @typedef {object} Phaser.Types.Tweens.TweenBuilderConfig - * @since 3.18.0 - * - * @property {any} targets - The object, or an array of objects, to run the tween on. - * @property {(number|function)} [delay=0] - The number of milliseconds to delay before the tween will start. - * @property {number} [duration=1000] - The duration of the tween in milliseconds. - * @property {(string|function)} [ease='Power0'] - The easing equation to use for the tween. - * @property {array} [easeParams] - Optional easing parameters. - * @property {number} [hold=0] - The number of milliseconds to hold the tween for before yoyo'ing. - * @property {number} [repeat=0] - The number of times each property tween repeats. - * @property {number} [repeatDelay=0] - The number of milliseconds to pause before a repeat. - * @property {boolean} [yoyo=false] - Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. - * @property {boolean} [flipX=false] - Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. - * @property {boolean} [flipY=false] - Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. - * @property {number|function|object|array} [offset=null] - Used when the Tween is part of a Timeline. - * @property {number|function|object|array} [completeDelay=0] - The time the tween will wait before the onComplete event is dispatched once it has completed, in ms. - * @property {number|function|object|array} [loop=0] - The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once. - * @property {number|function|object|array} [loopDelay=0] - The time the tween will pause before starting either a yoyo or returning to the start for a repeat. - * @property {boolean} [paused=false] - Does the tween start in a paused state (true) or playing (false)? - * @property {Object.} [props] - The properties to tween. - * @property {boolean} [useFrames=false] - Use frames or milliseconds? - * @property {any} [callbackScope] - Scope (this) for the callbacks. The default scope is the tween. - * @property {Phaser.Types.Tweens.TweenOnCompleteCallback} [onComplete] - A function to call when the tween completes. - * @property {array} [onCompleteParams] - Additional parameters to pass to `onComplete`. - * @property {any} [onCompleteScope] - Scope (this) for `onComplete`. - * @property {Phaser.Types.Tweens.TweenOnLoopCallback} [onLoop] - A function to call each time the tween loops. - * @property {array} [onLoopParams] - Additional parameters to pass to `onLoop`. - * @property {any} [onLoopScope] - Scope (this) for `onLoop`. - * @property {Phaser.Types.Tweens.TweenOnRepeatCallback} [onRepeat] - A function to call each time the tween repeats. Called once per property per target. - * @property {array} [onRepeatParams] - Additional parameters to pass to `onRepeat`. - * @property {any} [onRepeatScope] - Scope (this) for `onRepeat`. - * @property {Phaser.Types.Tweens.TweenOnStartCallback} [onStart] - A function to call when the tween starts playback, after any delays have expired. - * @property {array} [onStartParams] - Additional parameters to pass to `onStart`. - * @property {any} [onStartScope] - Scope (this) for `onStart`. - * @property {Phaser.Types.Tweens.TweenOnUpdateCallback} [onUpdate] - A function to call each time the tween steps. Called once per property per target. - * @property {array} [onUpdateParams] - Additional parameters to pass to `onUpdate`. - * @property {any} [onUpdateScope] - Scope (this) for `onUpdate`. - * @property {Phaser.Types.Tweens.TweenOnYoyoCallback} [onYoyo] - A function to call each time the tween yoyos. Called once per property per target. - * @property {array} [onYoyoParams] - Additional parameters to pass to `onYoyo`. - * @property {any} [onYoyoScope] - Scope (this) for `onYoyo`. - * @property {Phaser.Types.Tweens.TweenOnActiveCallback} [onActive] - A function to call when the tween becomes active within the Tween Manager. - * @property {array} [onActiveParams] - Additional parameters to pass to `onActive`. - * @property {any} [onActiveScope] - Scope (this) for `onActive`. - * - * @example - * { - * targets: null, - * delay: 0, - * duration: 1000, - * ease: 'Power0', - * easeParams: null, - * hold: 0, - * repeat: 0, - * repeatDelay: 0, - * yoyo: false, - * flipX: false, - * flipY: false - * }; - */ +/** + * @typedef {object} Phaser.Types.Tweens.TweenBuilderConfig + * @since 3.18.0 + * + * @property {any} targets - The object, or an array of objects, to run the tween on. + * @property {(number|function)} [delay=0] - The number of milliseconds to delay before the tween will start. + * @property {number} [duration=1000] - The duration of the tween in milliseconds. + * @property {(string|function)} [ease='Power0'] - The easing equation to use for the tween. + * @property {array} [easeParams] - Optional easing parameters. + * @property {number} [hold=0] - The number of milliseconds to hold the tween for before yoyo'ing. + * @property {number} [repeat=0] - The number of times each property tween repeats. + * @property {number} [repeatDelay=0] - The number of milliseconds to pause before a repeat. + * @property {boolean} [yoyo=false] - Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. + * @property {boolean} [flipX=false] - Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. + * @property {boolean} [flipY=false] - Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. + * @property {number|function|object|array} [offset=null] - Used when the Tween is part of a Timeline. + * @property {number|function|object|array} [completeDelay=0] - The time the tween will wait before the onComplete event is dispatched once it has completed, in ms. + * @property {number|function|object|array} [loop=0] - The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once. + * @property {number|function|object|array} [loopDelay=0] - The time the tween will pause before starting either a yoyo or returning to the start for a repeat. + * @property {boolean} [paused=false] - Does the tween start in a paused state (true) or playing (false)? + * @property {Object.} [props] - The properties to tween. + * @property {boolean} [useFrames=false] - Use frames or milliseconds? + * @property {any} [callbackScope] - Scope (this) for the callbacks. The default scope is the tween. + * @property {Phaser.Types.Tweens.TweenOnCompleteCallback} [onComplete] - A function to call when the tween completes. + * @property {array} [onCompleteParams] - Additional parameters to pass to `onComplete`. + * @property {any} [onCompleteScope] - Scope (this) for `onComplete`. + * @property {Phaser.Types.Tweens.TweenOnLoopCallback} [onLoop] - A function to call each time the tween loops. + * @property {array} [onLoopParams] - Additional parameters to pass to `onLoop`. + * @property {any} [onLoopScope] - Scope (this) for `onLoop`. + * @property {Phaser.Types.Tweens.TweenOnRepeatCallback} [onRepeat] - A function to call each time the tween repeats. Called once per property per target. + * @property {array} [onRepeatParams] - Additional parameters to pass to `onRepeat`. + * @property {any} [onRepeatScope] - Scope (this) for `onRepeat`. + * @property {Phaser.Types.Tweens.TweenOnStartCallback} [onStart] - A function to call when the tween starts playback, after any delays have expired. + * @property {array} [onStartParams] - Additional parameters to pass to `onStart`. + * @property {any} [onStartScope] - Scope (this) for `onStart`. + * @property {Phaser.Types.Tweens.TweenOnUpdateCallback} [onUpdate] - A function to call each time the tween steps. Called once per property per target. + * @property {array} [onUpdateParams] - Additional parameters to pass to `onUpdate`. + * @property {any} [onUpdateScope] - Scope (this) for `onUpdate`. + * @property {Phaser.Types.Tweens.TweenOnYoyoCallback} [onYoyo] - A function to call each time the tween yoyos. Called once per property per target. + * @property {array} [onYoyoParams] - Additional parameters to pass to `onYoyo`. + * @property {any} [onYoyoScope] - Scope (this) for `onYoyo`. + * @property {Phaser.Types.Tweens.TweenOnActiveCallback} [onActive] - A function to call when the tween becomes active within the Tween Manager. + * @property {array} [onActiveParams] - Additional parameters to pass to `onActive`. + * @property {any} [onActiveScope] - Scope (this) for `onActive`. + * + * @example + * { + * targets: null, + * delay: 0, + * duration: 1000, + * ease: 'Power0', + * easeParams: null, + * hold: 0, + * repeat: 0, + * repeatDelay: 0, + * yoyo: false, + * flipX: false, + * flipY: false + * }; + */ diff --git a/src/tweens/typedefs/TweenDataConfig.js b/src/tweens/typedefs/TweenDataConfig.js index 7470ea1e0..c42e85d49 100644 --- a/src/tweens/typedefs/TweenDataConfig.js +++ b/src/tweens/typedefs/TweenDataConfig.js @@ -1,32 +1,32 @@ -/** - * @typedef {object} Phaser.Types.Tweens.TweenDataConfig - * @since 3.0.0 - * - * @property {any} target - The target to tween. - * @property {integer} index - The target index within the Tween targets array. - * @property {string} key - The property of the target being tweened. - * @property {?Phaser.Types.Tweens.GetActiveCallback} getActiveValue - If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. - * @property {Phaser.Types.Tweens.GetEndCallback} getEndValue - The returned value sets what the property will be at the END of the Tween. - * @property {Phaser.Types.Tweens.GetStartCallback} getStartValue - The returned value sets what the property will be at the START of the Tween. - * @property {function} ease - The ease function this tween uses. - * @property {number} [duration=0] - Duration of the tween in ms/frames, excludes time for yoyo or repeats. - * @property {number} [totalDuration=0] - The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) - * @property {number} [delay=0] - Time in ms/frames before tween will start. - * @property {boolean} [yoyo=false] - Cause the tween to return back to its start value after hold has expired. - * @property {number} [hold=0] - Time in ms/frames the tween will pause before running the yoyo or starting a repeat. - * @property {integer} [repeat=0] - Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - * @property {number} [repeatDelay=0] - Time in ms/frames before the repeat will start. - * @property {boolean} [flipX=false] - Automatically call toggleFlipX when the TweenData yoyos or repeats - * @property {boolean} [flipY=false] - Automatically call toggleFlipY when the TweenData yoyos or repeats - * @property {number} [progress=0] - Between 0 and 1 showing completion of this TweenData. - * @property {number} [elapsed=0] - Delta counter - * @property {integer} [repeatCounter=0] - How many repeats are left to run? - * @property {number} [start=0] - The property value at the start of the ease. - * @property {number} [current=0] - The current propety value. - * @property {number} [previous=0] - The previous property value. - * @property {number} [end=0] - The property value at the end of the ease. - * @property {number} [t1=0] - Time duration 1. - * @property {number} [t2=0] - Time duration 2. - * @property {Phaser.Types.Tweens.TweenDataGenConfig} [gen] - LoadValue generation functions. - * @property {integer} [state=0] - TWEEN_CONST.CREATED - */ +/** + * @typedef {object} Phaser.Types.Tweens.TweenDataConfig + * @since 3.0.0 + * + * @property {any} target - The target to tween. + * @property {integer} index - The target index within the Tween targets array. + * @property {string} key - The property of the target being tweened. + * @property {?Phaser.Types.Tweens.GetActiveCallback} getActiveValue - If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. + * @property {Phaser.Types.Tweens.GetEndCallback} getEndValue - The returned value sets what the property will be at the END of the Tween. + * @property {Phaser.Types.Tweens.GetStartCallback} getStartValue - The returned value sets what the property will be at the START of the Tween. + * @property {function} ease - The ease function this tween uses. + * @property {number} [duration=0] - Duration of the tween in ms/frames, excludes time for yoyo or repeats. + * @property {number} [totalDuration=0] - The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) + * @property {number} [delay=0] - Time in ms/frames before tween will start. + * @property {boolean} [yoyo=false] - Cause the tween to return back to its start value after hold has expired. + * @property {number} [hold=0] - Time in ms/frames the tween will pause before running the yoyo or starting a repeat. + * @property {integer} [repeat=0] - Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + * @property {number} [repeatDelay=0] - Time in ms/frames before the repeat will start. + * @property {boolean} [flipX=false] - Automatically call toggleFlipX when the TweenData yoyos or repeats + * @property {boolean} [flipY=false] - Automatically call toggleFlipY when the TweenData yoyos or repeats + * @property {number} [progress=0] - Between 0 and 1 showing completion of this TweenData. + * @property {number} [elapsed=0] - Delta counter + * @property {integer} [repeatCounter=0] - How many repeats are left to run? + * @property {number} [start=0] - The property value at the start of the ease. + * @property {number} [current=0] - The current propety value. + * @property {number} [previous=0] - The previous property value. + * @property {number} [end=0] - The property value at the end of the ease. + * @property {number} [t1=0] - Time duration 1. + * @property {number} [t2=0] - Time duration 2. + * @property {Phaser.Types.Tweens.TweenDataGenConfig} [gen] - LoadValue generation functions. + * @property {integer} [state=0] - TWEEN_CONST.CREATED + */ diff --git a/src/tweens/typedefs/index.js b/src/tweens/typedefs/index.js index 7bf3557e6..84aed7b8a 100644 --- a/src/tweens/typedefs/index.js +++ b/src/tweens/typedefs/index.js @@ -1,9 +1,9 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Types.Tweens - */ +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Types.Tweens + */ diff --git a/src/utils/Class.js b/src/utils/Class.js index b1d6eec83..062833518 100644 --- a/src/utils/Class.js +++ b/src/utils/Class.js @@ -1,248 +1,248 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Taken from klasse by mattdesl https://github.com/mattdesl/klasse - -function hasGetterOrSetter (def) -{ - return (!!def.get && typeof def.get === 'function') || (!!def.set && typeof def.set === 'function'); -} - -function getProperty (definition, k, isClassDescriptor) -{ - // 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. - var def = (isClassDescriptor) ? definition[k] : Object.getOwnPropertyDescriptor(definition, k); - - if (!isClassDescriptor && def.value && typeof def.value === 'object') - { - def = def.value; - } - - // This might be a regular property, or it may be a getter/setter the user defined in a class. - if (def && hasGetterOrSetter(def)) - { - if (typeof def.enumerable === 'undefined') - { - def.enumerable = true; - } - - if (typeof def.configurable === 'undefined') - { - def.configurable = true; - } - - return def; - } - else - { - return false; - } -} - -function hasNonConfigurable (obj, k) -{ - var prop = Object.getOwnPropertyDescriptor(obj, k); - - if (!prop) - { - return false; - } - - if (prop.value && typeof prop.value === 'object') - { - prop = prop.value; - } - - if (prop.configurable === false) - { - return true; - } - - return false; -} - -/** - * Extends the given `myClass` object's prototype with the properties of `definition`. - * - * @function extend - * @param {Object} ctor The constructor object to mix into. - * @param {Object} definition A dictionary of functions for the class. - * @param {boolean} isClassDescriptor Is the definition a class descriptor? - * @param {Object} [extend] The parent constructor object. - */ -function extend (ctor, definition, isClassDescriptor, extend) -{ - for (var k in definition) - { - if (!definition.hasOwnProperty(k)) - { - continue; - } - - var def = getProperty(definition, k, isClassDescriptor); - - if (def !== false) - { - // If Extends is used, we will check its prototype to see if the final variable exists. - - var parent = extend || ctor; - - if (hasNonConfigurable(parent.prototype, k)) - { - // Just skip the final property - if (Class.ignoreFinals) - { - continue; - } - - // 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. - throw new Error('cannot override final property \'' + k + '\', set Class.ignoreFinals = true to skip'); - } - - Object.defineProperty(ctor.prototype, k, def); - } - else - { - ctor.prototype[k] = definition[k]; - } - } -} - -/** - * Applies the given `mixins` to the prototype of `myClass`. - * - * @function mixin - * @param {Object} myClass The constructor object to mix into. - * @param {Object|Array} mixins The mixins to apply to the constructor. - */ -function mixin (myClass, mixins) -{ - if (!mixins) - { - return; - } - - if (!Array.isArray(mixins)) - { - mixins = [ mixins ]; - } - - for (var i = 0; i < mixins.length; i++) - { - extend(myClass, mixins[i].prototype || mixins[i]); - } -} - -/** - * Creates a new class with the given descriptor. - * The constructor, defined by the name `initialize`, - * is an optional function. If unspecified, an anonymous - * function will be used which calls the parent class (if - * one exists). - * - * You can also use `Extends` and `Mixins` to provide subclassing - * and inheritance. - * - * @class Phaser.Class - * @constructor - * @param {Object} definition a dictionary of functions for the class - * @example - * - * var MyClass = new Phaser.Class({ - * - * initialize: function() { - * this.foo = 2.0; - * }, - * - * bar: function() { - * return this.foo + 5; - * } - * }); - */ -function Class (definition) -{ - if (!definition) - { - definition = {}; - } - - // The variable name here dictates what we see in Chrome debugger - var initialize; - var Extends; - - if (definition.initialize) - { - if (typeof definition.initialize !== 'function') - { - throw new Error('initialize must be a function'); - } - - initialize = definition.initialize; - - // 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). - delete definition.initialize; - } - else if (definition.Extends) - { - var base = definition.Extends; - - initialize = function () - { - base.apply(this, arguments); - }; - } - else - { - initialize = function () {}; - } - - if (definition.Extends) - { - initialize.prototype = Object.create(definition.Extends.prototype); - initialize.prototype.constructor = initialize; - - // For getOwnPropertyDescriptor to work, we need to act directly on the Extends (or Mixin) - - Extends = definition.Extends; - - delete definition.Extends; - } - else - { - initialize.prototype.constructor = initialize; - } - - // Grab the mixins, if they are specified... - var mixins = null; - - if (definition.Mixins) - { - mixins = definition.Mixins; - delete definition.Mixins; - } - - // First, mixin if we can. - mixin(initialize, mixins); - - // Now we grab the actual definition which defines the overrides. - extend(initialize, definition, true, Extends); - - return initialize; -} - -Class.extend = extend; -Class.mixin = mixin; -Class.ignoreFinals = false; - -module.exports = Class; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Taken from klasse by mattdesl https://github.com/mattdesl/klasse + +function hasGetterOrSetter (def) +{ + return (!!def.get && typeof def.get === 'function') || (!!def.set && typeof def.set === 'function'); +} + +function getProperty (definition, k, isClassDescriptor) +{ + // 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. + var def = (isClassDescriptor) ? definition[k] : Object.getOwnPropertyDescriptor(definition, k); + + if (!isClassDescriptor && def.value && typeof def.value === 'object') + { + def = def.value; + } + + // This might be a regular property, or it may be a getter/setter the user defined in a class. + if (def && hasGetterOrSetter(def)) + { + if (typeof def.enumerable === 'undefined') + { + def.enumerable = true; + } + + if (typeof def.configurable === 'undefined') + { + def.configurable = true; + } + + return def; + } + else + { + return false; + } +} + +function hasNonConfigurable (obj, k) +{ + var prop = Object.getOwnPropertyDescriptor(obj, k); + + if (!prop) + { + return false; + } + + if (prop.value && typeof prop.value === 'object') + { + prop = prop.value; + } + + if (prop.configurable === false) + { + return true; + } + + return false; +} + +/** + * Extends the given `myClass` object's prototype with the properties of `definition`. + * + * @function extend + * @param {Object} ctor The constructor object to mix into. + * @param {Object} definition A dictionary of functions for the class. + * @param {boolean} isClassDescriptor Is the definition a class descriptor? + * @param {Object} [extend] The parent constructor object. + */ +function extend (ctor, definition, isClassDescriptor, extend) +{ + for (var k in definition) + { + if (!definition.hasOwnProperty(k)) + { + continue; + } + + var def = getProperty(definition, k, isClassDescriptor); + + if (def !== false) + { + // If Extends is used, we will check its prototype to see if the final variable exists. + + var parent = extend || ctor; + + if (hasNonConfigurable(parent.prototype, k)) + { + // Just skip the final property + if (Class.ignoreFinals) + { + continue; + } + + // 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. + throw new Error('cannot override final property \'' + k + '\', set Class.ignoreFinals = true to skip'); + } + + Object.defineProperty(ctor.prototype, k, def); + } + else + { + ctor.prototype[k] = definition[k]; + } + } +} + +/** + * Applies the given `mixins` to the prototype of `myClass`. + * + * @function mixin + * @param {Object} myClass The constructor object to mix into. + * @param {Object|Array} mixins The mixins to apply to the constructor. + */ +function mixin (myClass, mixins) +{ + if (!mixins) + { + return; + } + + if (!Array.isArray(mixins)) + { + mixins = [ mixins ]; + } + + for (var i = 0; i < mixins.length; i++) + { + extend(myClass, mixins[i].prototype || mixins[i]); + } +} + +/** + * Creates a new class with the given descriptor. + * The constructor, defined by the name `initialize`, + * is an optional function. If unspecified, an anonymous + * function will be used which calls the parent class (if + * one exists). + * + * You can also use `Extends` and `Mixins` to provide subclassing + * and inheritance. + * + * @class Phaser.Class + * @constructor + * @param {Object} definition a dictionary of functions for the class + * @example + * + * var MyClass = new Phaser.Class({ + * + * initialize: function() { + * this.foo = 2.0; + * }, + * + * bar: function() { + * return this.foo + 5; + * } + * }); + */ +function Class (definition) +{ + if (!definition) + { + definition = {}; + } + + // The variable name here dictates what we see in Chrome debugger + var initialize; + var Extends; + + if (definition.initialize) + { + if (typeof definition.initialize !== 'function') + { + throw new Error('initialize must be a function'); + } + + initialize = definition.initialize; + + // 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). + delete definition.initialize; + } + else if (definition.Extends) + { + var base = definition.Extends; + + initialize = function () + { + base.apply(this, arguments); + }; + } + else + { + initialize = function () {}; + } + + if (definition.Extends) + { + initialize.prototype = Object.create(definition.Extends.prototype); + initialize.prototype.constructor = initialize; + + // For getOwnPropertyDescriptor to work, we need to act directly on the Extends (or Mixin) + + Extends = definition.Extends; + + delete definition.Extends; + } + else + { + initialize.prototype.constructor = initialize; + } + + // Grab the mixins, if they are specified... + var mixins = null; + + if (definition.Mixins) + { + mixins = definition.Mixins; + delete definition.Mixins; + } + + // First, mixin if we can. + mixin(initialize, mixins); + + // Now we grab the actual definition which defines the overrides. + extend(initialize, definition, true, Extends); + + return initialize; +} + +Class.extend = extend; +Class.mixin = mixin; +Class.ignoreFinals = false; + +module.exports = Class; diff --git a/src/utils/NOOP.js b/src/utils/NOOP.js index f4a4bead6..cd5c43a8c 100644 --- a/src/utils/NOOP.js +++ b/src/utils/NOOP.js @@ -1,21 +1,21 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * A NOOP (No Operation) callback function. - * - * Used internally by Phaser when it's more expensive to determine if a callback exists - * than it is to just invoke an empty function. - * - * @function Phaser.Utils.NOOP - * @since 3.0.0 - */ -var NOOP = function () -{ - // NOOP -}; - -module.exports = NOOP; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * A NOOP (No Operation) callback function. + * + * Used internally by Phaser when it's more expensive to determine if a callback exists + * than it is to just invoke an empty function. + * + * @function Phaser.Utils.NOOP + * @since 3.0.0 + */ +var NOOP = function () +{ + // NOOP +}; + +module.exports = NOOP; diff --git a/src/utils/array/Add.js b/src/utils/array/Add.js index 8ad2ca732..7012619db 100644 --- a/src/utils/array/Add.js +++ b/src/utils/array/Add.js @@ -1,111 +1,111 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Adds the given item, or array of items, to the array. - * - * Each item must be unique within the array. - * - * The array is modified in-place and returned. - * - * You can optionally specify a limit to the maximum size of the array. If the quantity of items being - * added will take the array length over this limit, it will stop adding once the limit is reached. - * - * You can optionally specify a callback to be invoked for each item successfully added to the array. - * - * @function Phaser.Utils.Array.Add - * @since 3.4.0 - * - * @param {array} array - The array to be added to. - * @param {any|any[]} item - The item, or array of items, to add to the array. Each item must be unique within the array. - * @param {integer} [limit] - Optional limit which caps the size of the array. - * @param {function} [callback] - A callback to be invoked for each item successfully added to the array. - * @param {object} [context] - The context in which the callback is invoked. - * - * @return {array} The input array. - */ -var Add = function (array, item, limit, callback, context) -{ - if (context === undefined) { context = array; } - - if (limit > 0) - { - var remaining = limit - array.length; - - // There's nothing more we can do here, the array is full - if (remaining <= 0) - { - return null; - } - } - - // Fast path to avoid array mutation and iteration - if (!Array.isArray(item)) - { - if (array.indexOf(item) === -1) - { - array.push(item); - - if (callback) - { - callback.call(context, item); - } - - return item; - } - else - { - return null; - } - } - - // If we got this far, we have an array of items to insert - - // Ensure all the items are unique - var itemLength = item.length - 1; - - while (itemLength >= 0) - { - if (array.indexOf(item[itemLength]) !== -1) - { - // Already exists in array, so remove it - item.splice(itemLength, 1); - } - - itemLength--; - } - - // Anything left? - itemLength = item.length; - - if (itemLength === 0) - { - return null; - } - - if (limit > 0 && itemLength > remaining) - { - item.splice(remaining); - - itemLength = remaining; - } - - for (var i = 0; i < itemLength; i++) - { - var entry = item[i]; - - array.push(entry); - - if (callback) - { - callback.call(context, entry); - } - } - - return item; -}; - -module.exports = Add; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds the given item, or array of items, to the array. + * + * Each item must be unique within the array. + * + * The array is modified in-place and returned. + * + * You can optionally specify a limit to the maximum size of the array. If the quantity of items being + * added will take the array length over this limit, it will stop adding once the limit is reached. + * + * You can optionally specify a callback to be invoked for each item successfully added to the array. + * + * @function Phaser.Utils.Array.Add + * @since 3.4.0 + * + * @param {array} array - The array to be added to. + * @param {any|any[]} item - The item, or array of items, to add to the array. Each item must be unique within the array. + * @param {integer} [limit] - Optional limit which caps the size of the array. + * @param {function} [callback] - A callback to be invoked for each item successfully added to the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {array} The input array. + */ +var Add = function (array, item, limit, callback, context) +{ + if (context === undefined) { context = array; } + + if (limit > 0) + { + var remaining = limit - array.length; + + // There's nothing more we can do here, the array is full + if (remaining <= 0) + { + return null; + } + } + + // Fast path to avoid array mutation and iteration + if (!Array.isArray(item)) + { + if (array.indexOf(item) === -1) + { + array.push(item); + + if (callback) + { + callback.call(context, item); + } + + return item; + } + else + { + return null; + } + } + + // If we got this far, we have an array of items to insert + + // Ensure all the items are unique + var itemLength = item.length - 1; + + while (itemLength >= 0) + { + if (array.indexOf(item[itemLength]) !== -1) + { + // Already exists in array, so remove it + item.splice(itemLength, 1); + } + + itemLength--; + } + + // Anything left? + itemLength = item.length; + + if (itemLength === 0) + { + return null; + } + + if (limit > 0 && itemLength > remaining) + { + item.splice(remaining); + + itemLength = remaining; + } + + for (var i = 0; i < itemLength; i++) + { + var entry = item[i]; + + array.push(entry); + + if (callback) + { + callback.call(context, entry); + } + } + + return item; +}; + +module.exports = Add; diff --git a/src/utils/array/AddAt.js b/src/utils/array/AddAt.js index ff48f0237..adcd978ff 100644 --- a/src/utils/array/AddAt.js +++ b/src/utils/array/AddAt.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Adds the given item, or array of items, to the array starting at the index specified. - * - * Each item must be unique within the array. - * - * Existing elements in the array are shifted up. - * - * The array is modified in-place and returned. - * - * You can optionally specify a limit to the maximum size of the array. If the quantity of items being - * added will take the array length over this limit, it will stop adding once the limit is reached. - * - * You can optionally specify a callback to be invoked for each item successfully added to the array. - * - * @function Phaser.Utils.Array.AddAt - * @since 3.4.0 - * - * @param {array} array - The array to be added to. - * @param {any|any[]} item - The item, or array of items, to add to the array. - * @param {integer} [index=0] - The index in the array where the item will be inserted. - * @param {integer} [limit] - Optional limit which caps the size of the array. - * @param {function} [callback] - A callback to be invoked for each item successfully added to the array. - * @param {object} [context] - The context in which the callback is invoked. - * - * @return {array} The input array. - */ -var AddAt = function (array, item, index, limit, callback, context) -{ - if (index === undefined) { index = 0; } - if (context === undefined) { context = array; } - - if (limit > 0) - { - var remaining = limit - array.length; - - // There's nothing more we can do here, the array is full - if (remaining <= 0) - { - return null; - } - } - - // Fast path to avoid array mutation and iteration - if (!Array.isArray(item)) - { - if (array.indexOf(item) === -1) - { - array.splice(index, 0, item); - - if (callback) - { - callback.call(context, item); - } - - return item; - } - else - { - return null; - } - } - - // If we got this far, we have an array of items to insert - - // Ensure all the items are unique - var itemLength = item.length - 1; - - while (itemLength >= 0) - { - if (array.indexOf(item[itemLength]) !== -1) - { - // Already exists in array, so remove it - item.pop(); - } - - itemLength--; - } - - // Anything left? - itemLength = item.length; - - if (itemLength === 0) - { - return null; - } - - // Truncate to the limit - if (limit > 0 && itemLength > remaining) - { - item.splice(remaining); - - itemLength = remaining; - } - - for (var i = itemLength - 1; i >= 0; i--) - { - var entry = item[i]; - - array.splice(index, 0, entry); - - if (callback) - { - callback.call(context, entry); - } - } - - return item; -}; - -module.exports = AddAt; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Adds the given item, or array of items, to the array starting at the index specified. + * + * Each item must be unique within the array. + * + * Existing elements in the array are shifted up. + * + * The array is modified in-place and returned. + * + * You can optionally specify a limit to the maximum size of the array. If the quantity of items being + * added will take the array length over this limit, it will stop adding once the limit is reached. + * + * You can optionally specify a callback to be invoked for each item successfully added to the array. + * + * @function Phaser.Utils.Array.AddAt + * @since 3.4.0 + * + * @param {array} array - The array to be added to. + * @param {any|any[]} item - The item, or array of items, to add to the array. + * @param {integer} [index=0] - The index in the array where the item will be inserted. + * @param {integer} [limit] - Optional limit which caps the size of the array. + * @param {function} [callback] - A callback to be invoked for each item successfully added to the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {array} The input array. + */ +var AddAt = function (array, item, index, limit, callback, context) +{ + if (index === undefined) { index = 0; } + if (context === undefined) { context = array; } + + if (limit > 0) + { + var remaining = limit - array.length; + + // There's nothing more we can do here, the array is full + if (remaining <= 0) + { + return null; + } + } + + // Fast path to avoid array mutation and iteration + if (!Array.isArray(item)) + { + if (array.indexOf(item) === -1) + { + array.splice(index, 0, item); + + if (callback) + { + callback.call(context, item); + } + + return item; + } + else + { + return null; + } + } + + // If we got this far, we have an array of items to insert + + // Ensure all the items are unique + var itemLength = item.length - 1; + + while (itemLength >= 0) + { + if (array.indexOf(item[itemLength]) !== -1) + { + // Already exists in array, so remove it + item.pop(); + } + + itemLength--; + } + + // Anything left? + itemLength = item.length; + + if (itemLength === 0) + { + return null; + } + + // Truncate to the limit + if (limit > 0 && itemLength > remaining) + { + item.splice(remaining); + + itemLength = remaining; + } + + for (var i = itemLength - 1; i >= 0; i--) + { + var entry = item[i]; + + array.splice(index, 0, entry); + + if (callback) + { + callback.call(context, entry); + } + } + + return item; +}; + +module.exports = AddAt; diff --git a/src/utils/array/BringToTop.js b/src/utils/array/BringToTop.js index 49c257533..65aee6ab2 100644 --- a/src/utils/array/BringToTop.js +++ b/src/utils/array/BringToTop.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves the given element to the top of the array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.BringToTop - * @since 3.4.0 - * - * @param {array} array - The array. - * @param {*} item - The element to move. - * - * @return {*} The element that was moved. - */ -var BringToTop = function (array, item) -{ - var currentIndex = array.indexOf(item); - - if (currentIndex !== -1 && currentIndex < array.length) - { - array.splice(currentIndex, 1); - array.push(item); - } - - return item; -}; - -module.exports = BringToTop; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given element to the top of the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.BringToTop + * @since 3.4.0 + * + * @param {array} array - The array. + * @param {*} item - The element to move. + * + * @return {*} The element that was moved. + */ +var BringToTop = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex !== -1 && currentIndex < array.length) + { + array.splice(currentIndex, 1); + array.push(item); + } + + return item; +}; + +module.exports = BringToTop; diff --git a/src/utils/array/CountAllMatching.js b/src/utils/array/CountAllMatching.js index a5bac87cd..679e670ee 100644 --- a/src/utils/array/CountAllMatching.js +++ b/src/utils/array/CountAllMatching.js @@ -1,46 +1,46 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SafeRange = require('./SafeRange'); - -/** - * Returns the total number of elements in the array which have a property matching the given value. - * - * @function Phaser.Utils.Array.CountAllMatching - * @since 3.4.0 - * - * @param {array} array - The array to search. - * @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 {integer} [startIndex] - An optional start index to search from. - * @param {integer} [endIndex] - An optional end index to search to. - * - * @return {integer} The total number of elements with properties matching the given value. - */ -var CountAllMatching = function (array, property, value, startIndex, endIndex) -{ - if (startIndex === undefined) { startIndex = 0; } - if (endIndex === undefined) { endIndex = array.length; } - - var total = 0; - - if (SafeRange(array, startIndex, endIndex)) - { - for (var i = startIndex; i < endIndex; i++) - { - var child = array[i]; - - if (child[property] === value) - { - total++; - } - } - } - - return total; -}; - -module.exports = CountAllMatching; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = require('./SafeRange'); + +/** + * Returns the total number of elements in the array which have a property matching the given value. + * + * @function Phaser.Utils.Array.CountAllMatching + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @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 {integer} [startIndex] - An optional start index to search from. + * @param {integer} [endIndex] - An optional end index to search to. + * + * @return {integer} The total number of elements with properties matching the given value. + */ +var CountAllMatching = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + var total = 0; + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var child = array[i]; + + if (child[property] === value) + { + total++; + } + } + } + + return total; +}; + +module.exports = CountAllMatching; diff --git a/src/utils/array/Each.js b/src/utils/array/Each.js index bf3aa8a6e..0b08628b3 100644 --- a/src/utils/array/Each.js +++ b/src/utils/array/Each.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Passes each element in the array to the given callback. - * - * @function Phaser.Utils.Array.Each - * @since 3.4.0 - * - * @param {array} array - The array to search. - * @param {function} callback - A callback to be invoked for each item in the array. - * @param {object} context - The context in which the callback is invoked. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the current array item. - * - * @return {array} The input array. - */ -var Each = function (array, callback, context) -{ - var i; - var args = [ null ]; - - for (i = 3; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (i = 0; i < array.length; i++) - { - args[0] = array[i]; - - callback.apply(context, args); - } - - return array; -}; - -module.exports = Each; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Passes each element in the array to the given callback. + * + * @function Phaser.Utils.Array.Each + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @param {function} callback - A callback to be invoked for each item in the array. + * @param {object} context - The context in which the callback is invoked. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the current array item. + * + * @return {array} The input array. + */ +var Each = function (array, callback, context) +{ + var i; + var args = [ null ]; + + for (i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = 0; i < array.length; i++) + { + args[0] = array[i]; + + callback.apply(context, args); + } + + return array; +}; + +module.exports = Each; diff --git a/src/utils/array/EachInRange.js b/src/utils/array/EachInRange.js index 404a2ea61..fb10743c9 100644 --- a/src/utils/array/EachInRange.js +++ b/src/utils/array/EachInRange.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SafeRange = require('./SafeRange'); - -/** - * Passes each element in the array, between the start and end indexes, to the given callback. - * - * @function Phaser.Utils.Array.EachInRange - * @since 3.4.0 - * - * @param {array} array - The array to search. - * @param {function} callback - A callback to be invoked for each item in the array. - * @param {object} context - The context in which the callback is invoked. - * @param {integer} startIndex - The start index to search from. - * @param {integer} endIndex - The end index to search to. - * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. - * - * @return {array} The input array. - */ -var EachInRange = function (array, callback, context, startIndex, endIndex) -{ - if (startIndex === undefined) { startIndex = 0; } - if (endIndex === undefined) { endIndex = array.length; } - - if (SafeRange(array, startIndex, endIndex)) - { - var i; - var args = [ null ]; - - for (i = 5; i < arguments.length; i++) - { - args.push(arguments[i]); - } - - for (i = startIndex; i < endIndex; i++) - { - args[0] = array[i]; - - callback.apply(context, args); - } - } - - return array; -}; - -module.exports = EachInRange; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = require('./SafeRange'); + +/** + * Passes each element in the array, between the start and end indexes, to the given callback. + * + * @function Phaser.Utils.Array.EachInRange + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @param {function} callback - A callback to be invoked for each item in the array. + * @param {object} context - The context in which the callback is invoked. + * @param {integer} startIndex - The start index to search from. + * @param {integer} endIndex - The end index to search to. + * @param {...*} [args] - Additional arguments that will be passed to the callback, after the child. + * + * @return {array} The input array. + */ +var EachInRange = function (array, callback, context, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + if (SafeRange(array, startIndex, endIndex)) + { + var i; + var args = [ null ]; + + for (i = 5; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (i = startIndex; i < endIndex; i++) + { + args[0] = array[i]; + + callback.apply(context, args); + } + } + + return array; +}; + +module.exports = EachInRange; diff --git a/src/utils/array/FindClosestInSorted.js b/src/utils/array/FindClosestInSorted.js index 30ce0f5cb..5432352ba 100644 --- a/src/utils/array/FindClosestInSorted.js +++ b/src/utils/array/FindClosestInSorted.js @@ -1,78 +1,78 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Searches a pre-sorted array for the closet value to the given number. - * - * If the `key` argument is given it will assume the array contains objects that all have the required `key` property name, - * and will check for the closest value of those to the given number. - * - * @function Phaser.Utils.Array.FindClosestInSorted - * @since 3.0.0 - * - * @param {number} value - The value to search for in the array. - * @param {array} array - The array to search, which must be sorted. - * @param {string} [key] - An optional property key. If specified the array elements property will be checked against value. - * - * @return {(number|any)} The nearest value found in the array, or if a `key` was given, the nearest object with the matching property value. - */ -var FindClosestInSorted = function (value, array, key) -{ - if (!array.length) - { - return NaN; - } - else if (array.length === 1) - { - return array[0]; - } - - var i = 1; - var low; - var high; - - if (key) - { - if (value < array[0][key]) - { - return array[0]; - } - - while (array[i][key] < value) - { - i++; - } - } - else - { - while (array[i] < value) - { - i++; - } - } - - if (i > array.length) - { - i = array.length; - } - - if (key) - { - low = array[i - 1][key]; - high = array[i][key]; - - return ((high - value) <= (value - low)) ? array[i] : array[i - 1]; - } - else - { - low = array[i - 1]; - high = array[i]; - - return ((high - value) <= (value - low)) ? high : low; - } -}; - -module.exports = FindClosestInSorted; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Searches a pre-sorted array for the closet value to the given number. + * + * If the `key` argument is given it will assume the array contains objects that all have the required `key` property name, + * and will check for the closest value of those to the given number. + * + * @function Phaser.Utils.Array.FindClosestInSorted + * @since 3.0.0 + * + * @param {number} value - The value to search for in the array. + * @param {array} array - The array to search, which must be sorted. + * @param {string} [key] - An optional property key. If specified the array elements property will be checked against value. + * + * @return {(number|any)} The nearest value found in the array, or if a `key` was given, the nearest object with the matching property value. + */ +var FindClosestInSorted = function (value, array, key) +{ + if (!array.length) + { + return NaN; + } + else if (array.length === 1) + { + return array[0]; + } + + var i = 1; + var low; + var high; + + if (key) + { + if (value < array[0][key]) + { + return array[0]; + } + + while (array[i][key] < value) + { + i++; + } + } + else + { + while (array[i] < value) + { + i++; + } + } + + if (i > array.length) + { + i = array.length; + } + + if (key) + { + low = array[i - 1][key]; + high = array[i][key]; + + return ((high - value) <= (value - low)) ? array[i] : array[i - 1]; + } + else + { + low = array[i - 1]; + high = array[i]; + + return ((high - value) <= (value - low)) ? high : low; + } +}; + +module.exports = FindClosestInSorted; diff --git a/src/utils/array/GetAll.js b/src/utils/array/GetAll.js index f765c91f6..3ae0a9528 100644 --- a/src/utils/array/GetAll.js +++ b/src/utils/array/GetAll.js @@ -1,56 +1,56 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SafeRange = require('./SafeRange'); - -/** - * Returns all elements in the array. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('visible', true)` would return only elements that have their visible property set. - * - * Optionally you can specify a start and end index. For example if the array had 100 elements, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 elements. - * - * @function Phaser.Utils.Array.GetAll - * @since 3.4.0 - * - * @param {array} array - The array to search. - * @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 {integer} [startIndex] - An optional start index to search from. - * @param {integer} [endIndex] - An optional end index to search to. - * - * @return {array} All matching elements from the array. - */ -var GetAll = function (array, property, value, startIndex, endIndex) -{ - if (startIndex === undefined) { startIndex = 0; } - if (endIndex === undefined) { endIndex = array.length; } - - var output = []; - - if (SafeRange(array, startIndex, endIndex)) - { - for (var i = startIndex; i < endIndex; i++) - { - var child = array[i]; - - if (!property || - (property && value === undefined && child.hasOwnProperty(property)) || - (property && value !== undefined && child[property] === value)) - { - output.push(child); - } - } - } - - return output; -}; - -module.exports = GetAll; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = require('./SafeRange'); + +/** + * Returns all elements in the array. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('visible', true)` would return only elements that have their visible property set. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 elements. + * + * @function Phaser.Utils.Array.GetAll + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @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 {integer} [startIndex] - An optional start index to search from. + * @param {integer} [endIndex] - An optional end index to search to. + * + * @return {array} All matching elements from the array. + */ +var GetAll = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + var output = []; + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var child = array[i]; + + if (!property || + (property && value === undefined && child.hasOwnProperty(property)) || + (property && value !== undefined && child[property] === value)) + { + output.push(child); + } + } + } + + return output; +}; + +module.exports = GetAll; diff --git a/src/utils/array/GetFirst.js b/src/utils/array/GetFirst.js index 902bcf65b..abc07144c 100644 --- a/src/utils/array/GetFirst.js +++ b/src/utils/array/GetFirst.js @@ -1,53 +1,53 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SafeRange = require('./SafeRange'); - -/** - * Returns the first element in the array. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('visible', true)` would return the first element that had its `visible` property set. - * - * Optionally you can specify a start and end index. For example if the array had 100 elements, - * and you set `startIndex` to 0 and `endIndex` to 50, it would search only the first 50 elements. - * - * @function Phaser.Utils.Array.GetFirst - * @since 3.4.0 - * - * @param {array} array - The array to search. - * @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 {integer} [startIndex=0] - An optional start index to search from. - * @param {integer} [endIndex=array.length] - An optional end index to search up to (but not included) - * - * @return {object} The first matching element from the array, or `null` if no element could be found in the range given. - */ -var GetFirst = function (array, property, value, startIndex, endIndex) -{ - if (startIndex === undefined) { startIndex = 0; } - if (endIndex === undefined) { endIndex = array.length; } - - if (SafeRange(array, startIndex, endIndex)) - { - for (var i = startIndex; i < endIndex; i++) - { - var child = array[i]; - - if (!property || - (property && value === undefined && child.hasOwnProperty(property)) || - (property && value !== undefined && child[property] === value)) - { - return child; - } - } - } - - return null; -}; - -module.exports = GetFirst; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = require('./SafeRange'); + +/** + * Returns the first element in the array. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('visible', true)` would return the first element that had its `visible` property set. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would search only the first 50 elements. + * + * @function Phaser.Utils.Array.GetFirst + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @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 {integer} [startIndex=0] - An optional start index to search from. + * @param {integer} [endIndex=array.length] - An optional end index to search up to (but not included) + * + * @return {object} The first matching element from the array, or `null` if no element could be found in the range given. + */ +var GetFirst = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var child = array[i]; + + if (!property || + (property && value === undefined && child.hasOwnProperty(property)) || + (property && value !== undefined && child[property] === value)) + { + return child; + } + } + } + + return null; +}; + +module.exports = GetFirst; diff --git a/src/utils/array/GetRandom.js b/src/utils/array/GetRandom.js index 9c1564e75..8917bf154 100644 --- a/src/utils/array/GetRandom.js +++ b/src/utils/array/GetRandom.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Returns a Random element from the array. - * - * @function Phaser.Utils.Array.GetRandom - * @since 3.0.0 - * - * @param {array} array - The array to select the random entry from. - * @param {integer} [startIndex=0] - An optional start index. - * @param {integer} [length=array.length] - An optional length, the total number of elements (from the startIndex) to choose from. - * - * @return {*} A random element from the array, or `null` if no element could be found in the range given. - */ -var GetRandom = function (array, startIndex, length) -{ - if (startIndex === undefined) { startIndex = 0; } - if (length === undefined) { length = array.length; } - - var randomIndex = startIndex + Math.floor(Math.random() * length); - - return (array[randomIndex] === undefined) ? null : array[randomIndex]; -}; - -module.exports = GetRandom; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Returns a Random element from the array. + * + * @function Phaser.Utils.Array.GetRandom + * @since 3.0.0 + * + * @param {array} array - The array to select the random entry from. + * @param {integer} [startIndex=0] - An optional start index. + * @param {integer} [length=array.length] - An optional length, the total number of elements (from the startIndex) to choose from. + * + * @return {*} A random element from the array, or `null` if no element could be found in the range given. + */ +var GetRandom = function (array, startIndex, length) +{ + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = array.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return (array[randomIndex] === undefined) ? null : array[randomIndex]; +}; + +module.exports = GetRandom; diff --git a/src/utils/array/MoveDown.js b/src/utils/array/MoveDown.js index ca94cd0dd..52336a308 100644 --- a/src/utils/array/MoveDown.js +++ b/src/utils/array/MoveDown.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves the given array element down one place in the array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.MoveDown - * @since 3.4.0 - * - * @param {array} array - The input array. - * @param {*} item - The element to move down the array. - * - * @return {array} The input array. - */ -var MoveDown = function (array, item) -{ - var currentIndex = array.indexOf(item); - - if (currentIndex > 0) - { - var item2 = array[currentIndex - 1]; - - var index2 = array.indexOf(item2); - - array[currentIndex] = item2; - array[index2] = item; - } - - return array; -}; - -module.exports = MoveDown; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given array element down one place in the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.MoveDown + * @since 3.4.0 + * + * @param {array} array - The input array. + * @param {*} item - The element to move down the array. + * + * @return {array} The input array. + */ +var MoveDown = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex > 0) + { + var item2 = array[currentIndex - 1]; + + var index2 = array.indexOf(item2); + + array[currentIndex] = item2; + array[index2] = item; + } + + return array; +}; + +module.exports = MoveDown; diff --git a/src/utils/array/MoveTo.js b/src/utils/array/MoveTo.js index 885e2927d..697ccc84e 100644 --- a/src/utils/array/MoveTo.js +++ b/src/utils/array/MoveTo.js @@ -1,41 +1,41 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves an element in an array to a new position within the same array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.MoveTo - * @since 3.4.0 - * - * @param {array} array - The array. - * @param {*} item - The element to move. - * @param {integer} index - The new index that the element will be moved to. - * - * @return {*} The element that was moved. - */ -var MoveTo = function (array, item, index) -{ - var currentIndex = array.indexOf(item); - - if (currentIndex === -1 || index < 0 || index >= array.length) - { - throw new Error('Supplied index out of bounds'); - } - - if (currentIndex !== index) - { - // Remove - array.splice(currentIndex, 1); - - // Add in new location - array.splice(index, 0, item); - } - - return item; -}; - -module.exports = MoveTo; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves an element in an array to a new position within the same array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.MoveTo + * @since 3.4.0 + * + * @param {array} array - The array. + * @param {*} item - The element to move. + * @param {integer} index - The new index that the element will be moved to. + * + * @return {*} The element that was moved. + */ +var MoveTo = function (array, item, index) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex === -1 || index < 0 || index >= array.length) + { + throw new Error('Supplied index out of bounds'); + } + + if (currentIndex !== index) + { + // Remove + array.splice(currentIndex, 1); + + // Add in new location + array.splice(index, 0, item); + } + + return item; +}; + +module.exports = MoveTo; diff --git a/src/utils/array/MoveUp.js b/src/utils/array/MoveUp.js index 793608ade..293590aa2 100644 --- a/src/utils/array/MoveUp.js +++ b/src/utils/array/MoveUp.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves the given array element up one place in the array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.MoveUp - * @since 3.4.0 - * - * @param {array} array - The input array. - * @param {*} item - The element to move up the array. - * - * @return {array} The input array. - */ -var MoveUp = function (array, item) -{ - var currentIndex = array.indexOf(item); - - if (currentIndex !== -1 && currentIndex < array.length - 1) - { - // The element one above `item` in the array - var item2 = array[currentIndex + 1]; - var index2 = array.indexOf(item2); - - array[currentIndex] = item2; - array[index2] = item; - } - - return array; -}; - -module.exports = MoveUp; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given array element up one place in the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.MoveUp + * @since 3.4.0 + * + * @param {array} array - The input array. + * @param {*} item - The element to move up the array. + * + * @return {array} The input array. + */ +var MoveUp = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex !== -1 && currentIndex < array.length - 1) + { + // The element one above `item` in the array + var item2 = array[currentIndex + 1]; + var index2 = array.indexOf(item2); + + array[currentIndex] = item2; + array[index2] = item; + } + + return array; +}; + +module.exports = MoveUp; diff --git a/src/utils/array/NumberArray.js b/src/utils/array/NumberArray.js index 9e46efe8b..c1589acc6 100644 --- a/src/utils/array/NumberArray.js +++ b/src/utils/array/NumberArray.js @@ -1,58 +1,58 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Create an array representing the range of numbers (usually integers), between, and inclusive of, - * the given `start` and `end` arguments. For example: - * - * `var array = numberArray(2, 4); // array = [2, 3, 4]` - * `var array = numberArray(0, 9); // array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` - * - * This is equivalent to `numberArrayStep(start, end, 1)`. - * - * You can optionally provide a prefix and / or suffix string. If given the array will contain - * strings, not integers. For example: - * - * `var array = numberArray(1, 4, 'Level '); // array = ["Level 1", "Level 2", "Level 3", "Level 4"]` - * `var array = numberArray(5, 7, 'HD-', '.png'); // array = ["HD-5.png", "HD-6.png", "HD-7.png"]` - * - * @function Phaser.Utils.Array.NumberArray - * @since 3.0.0 - * - * @param {number} start - The minimum value the array starts with. - * @param {number} end - The maximum value the array contains. - * @param {string} [prefix] - Optional prefix to place before the number. If provided the array will contain strings, not integers. - * @param {string} [suffix] - Optional suffix to place after the number. If provided the array will contain strings, not integers. - * - * @return {(number[]|string[])} The array of number values, or strings if a prefix or suffix was provided. - */ -var NumberArray = function (start, end, prefix, suffix) -{ - var result = []; - - for (var i = start; i <= end; i++) - { - if (prefix || suffix) - { - var key = (prefix) ? prefix + i.toString() : i.toString(); - - if (suffix) - { - key = key.concat(suffix); - } - - result.push(key); - } - else - { - result.push(i); - } - } - - return result; -}; - -module.exports = NumberArray; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Create an array representing the range of numbers (usually integers), between, and inclusive of, + * the given `start` and `end` arguments. For example: + * + * `var array = numberArray(2, 4); // array = [2, 3, 4]` + * `var array = numberArray(0, 9); // array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` + * + * This is equivalent to `numberArrayStep(start, end, 1)`. + * + * You can optionally provide a prefix and / or suffix string. If given the array will contain + * strings, not integers. For example: + * + * `var array = numberArray(1, 4, 'Level '); // array = ["Level 1", "Level 2", "Level 3", "Level 4"]` + * `var array = numberArray(5, 7, 'HD-', '.png'); // array = ["HD-5.png", "HD-6.png", "HD-7.png"]` + * + * @function Phaser.Utils.Array.NumberArray + * @since 3.0.0 + * + * @param {number} start - The minimum value the array starts with. + * @param {number} end - The maximum value the array contains. + * @param {string} [prefix] - Optional prefix to place before the number. If provided the array will contain strings, not integers. + * @param {string} [suffix] - Optional suffix to place after the number. If provided the array will contain strings, not integers. + * + * @return {(number[]|string[])} The array of number values, or strings if a prefix or suffix was provided. + */ +var NumberArray = function (start, end, prefix, suffix) +{ + var result = []; + + for (var i = start; i <= end; i++) + { + if (prefix || suffix) + { + var key = (prefix) ? prefix + i.toString() : i.toString(); + + if (suffix) + { + key = key.concat(suffix); + } + + result.push(key); + } + else + { + result.push(i); + } + } + + return result; +}; + +module.exports = NumberArray; diff --git a/src/utils/array/NumberArrayStep.js b/src/utils/array/NumberArrayStep.js index a17bed252..82d87e01d 100644 --- a/src/utils/array/NumberArrayStep.js +++ b/src/utils/array/NumberArrayStep.js @@ -1,71 +1,71 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RoundAwayFromZero = require('../../math/RoundAwayFromZero'); - -/** - * Create an array of numbers (positive and/or negative) progressing from `start` - * up to but not including `end` by advancing by `step`. - * - * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. - * - * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; - * for forward compatibility make sure to pass in actual numbers. - * - * @example - * NumberArrayStep(4); - * // => [0, 1, 2, 3] - * - * NumberArrayStep(1, 5); - * // => [1, 2, 3, 4] - * - * NumberArrayStep(0, 20, 5); - * // => [0, 5, 10, 15] - * - * NumberArrayStep(0, -4, -1); - * // => [0, -1, -2, -3] - * - * NumberArrayStep(1, 4, 0); - * // => [1, 1, 1] - * - * NumberArrayStep(0); - * // => [] - * - * @function Phaser.Utils.Array.NumberArrayStep - * @since 3.0.0 - * - * @param {number} [start=0] - The start of the range. - * @param {number} [end=null] - The end of the range. - * @param {number} [step=1] - The value to increment or decrement by. - * - * @return {number[]} The array of number values. - */ -var NumberArrayStep = function (start, end, step) -{ - if (start === undefined) { start = 0; } - if (end === undefined) { end = null; } - if (step === undefined) { step = 1; } - - if (end === null) - { - end = start; - start = 0; - } - - var result = []; - - var total = Math.max(RoundAwayFromZero((end - start) / (step || 1)), 0); - - for (var i = 0; i < total; i++) - { - result.push(start); - start += step; - } - - return result; -}; - -module.exports = NumberArrayStep; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RoundAwayFromZero = require('../../math/RoundAwayFromZero'); + +/** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @example + * NumberArrayStep(4); + * // => [0, 1, 2, 3] + * + * NumberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * NumberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * NumberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * NumberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * NumberArrayStep(0); + * // => [] + * + * @function Phaser.Utils.Array.NumberArrayStep + * @since 3.0.0 + * + * @param {number} [start=0] - The start of the range. + * @param {number} [end=null] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * + * @return {number[]} The array of number values. + */ +var NumberArrayStep = function (start, end, step) +{ + if (start === undefined) { start = 0; } + if (end === undefined) { end = null; } + if (step === undefined) { step = 1; } + + if (end === null) + { + end = start; + start = 0; + } + + var result = []; + + var total = Math.max(RoundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; +}; + +module.exports = NumberArrayStep; diff --git a/src/utils/array/QuickSelect.js b/src/utils/array/QuickSelect.js index 1cd5e50cd..21a7a554d 100644 --- a/src/utils/array/QuickSelect.js +++ b/src/utils/array/QuickSelect.js @@ -1,116 +1,116 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @ignore - */ -function swap (arr, i, j) -{ - var tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; -} - -/** - * @ignore - */ -function defaultCompare (a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; -} - -/** - * 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 sort. - * @param {integer} k - The k-th element index. - * @param {integer} [left=0] - The index of the left part of the range. - * @param {integer} [right] - The index of the right part of the range. - * @param {function} [compare] - An optional comparison function. Is passed two elements and should return 0, 1 or -1. - */ -var QuickSelect = function (arr, k, left, right, compare) -{ - if (left === undefined) { left = 0; } - if (right === undefined) { right = arr.length - 1; } - if (compare === undefined) { compare = defaultCompare; } - - while (right > left) - { - if (right - left > 600) - { - var n = right - left + 1; - var m = k - left + 1; - var z = Math.log(n); - var s = 0.5 * Math.exp(2 * z / 3); - var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); - var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); - var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); - - QuickSelect(arr, k, newLeft, newRight, compare); - } - - var t = arr[k]; - var i = left; - var j = right; - - swap(arr, left, k); - - if (compare(arr[right], t) > 0) - { - swap(arr, left, right); - } - - while (i < j) - { - swap(arr, i, j); - - i++; - j--; - - while (compare(arr[i], t) < 0) - { - i++; - } - - while (compare(arr[j], t) > 0) - { - j--; - } - } - - if (compare(arr[left], t) === 0) - { - swap(arr, left, j); - } - else - { - j++; - swap(arr, j, right); - } - - if (j <= k) - { - left = j + 1; - } - - if (k <= j) - { - right = j - 1; - } - } -}; - -module.exports = QuickSelect; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @ignore + */ +function swap (arr, i, j) +{ + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +/** + * @ignore + */ +function defaultCompare (a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * 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 sort. + * @param {integer} k - The k-th element index. + * @param {integer} [left=0] - The index of the left part of the range. + * @param {integer} [right] - The index of the right part of the range. + * @param {function} [compare] - An optional comparison function. Is passed two elements and should return 0, 1 or -1. + */ +var QuickSelect = function (arr, k, left, right, compare) +{ + if (left === undefined) { left = 0; } + if (right === undefined) { right = arr.length - 1; } + if (compare === undefined) { compare = defaultCompare; } + + while (right > left) + { + if (right - left > 600) + { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + + QuickSelect(arr, k, newLeft, newRight, compare); + } + + var t = arr[k]; + var i = left; + var j = right; + + swap(arr, left, k); + + if (compare(arr[right], t) > 0) + { + swap(arr, left, right); + } + + while (i < j) + { + swap(arr, i, j); + + i++; + j--; + + while (compare(arr[i], t) < 0) + { + i++; + } + + while (compare(arr[j], t) > 0) + { + j--; + } + } + + if (compare(arr[left], t) === 0) + { + swap(arr, left, j); + } + else + { + j++; + swap(arr, j, right); + } + + if (j <= k) + { + left = j + 1; + } + + if (k <= j) + { + right = j - 1; + } + } +}; + +module.exports = QuickSelect; diff --git a/src/utils/array/Range.js b/src/utils/array/Range.js index 4ba2d804b..031de9201 100644 --- a/src/utils/array/Range.js +++ b/src/utils/array/Range.js @@ -1,132 +1,132 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetValue = require('../object/GetValue'); -var Shuffle = require('./Shuffle'); - -var BuildChunk = function (a, b, qty) -{ - var out = []; - - for (var aIndex = 0; aIndex < a.length; aIndex++) - { - for (var bIndex = 0; bIndex < b.length; bIndex++) - { - for (var i = 0; i < qty; i++) - { - out.push({ a: a[aIndex], b: b[bIndex] }); - } - } - } - - return out; -}; - -/** - * 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) = - * Maybe if max is set then repeat goes to -1 automatically? - * 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. Can contain: repeat, random, randomB, yoyo, max, qty. - * - * @return {array} An array of arranged elements. - */ -var Range = function (a, b, options) -{ - var max = GetValue(options, 'max', 0); - var qty = GetValue(options, 'qty', 1); - var random = GetValue(options, 'random', false); - var randomB = GetValue(options, 'randomB', false); - var repeat = GetValue(options, 'repeat', 0); - var yoyo = GetValue(options, 'yoyo', false); - - var out = []; - - if (randomB) - { - Shuffle(b); - } - - // Endless repeat, so limit by max - if (repeat === -1) - { - if (max === 0) - { - repeat = 0; - } - else - { - // Work out how many repeats we need - var total = (a.length * b.length) * qty; - - if (yoyo) - { - total *= 2; - } - - repeat = Math.ceil(max / total); - } - } - - for (var i = 0; i <= repeat; i++) - { - var chunk = BuildChunk(a, b, qty); - - if (random) - { - Shuffle(chunk); - } - - out = out.concat(chunk); - - if (yoyo) - { - chunk.reverse(); - - out = out.concat(chunk); - } - } - - if (max) - { - out.splice(max); - } - - return out; -}; - -module.exports = Range; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = require('../object/GetValue'); +var Shuffle = require('./Shuffle'); + +var BuildChunk = function (a, b, qty) +{ + var out = []; + + for (var aIndex = 0; aIndex < a.length; aIndex++) + { + for (var bIndex = 0; bIndex < b.length; bIndex++) + { + for (var i = 0; i < qty; i++) + { + out.push({ a: a[aIndex], b: b[bIndex] }); + } + } + } + + return out; +}; + +/** + * 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) = + * Maybe if max is set then repeat goes to -1 automatically? + * 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. Can contain: repeat, random, randomB, yoyo, max, qty. + * + * @return {array} An array of arranged elements. + */ +var Range = function (a, b, options) +{ + var max = GetValue(options, 'max', 0); + var qty = GetValue(options, 'qty', 1); + var random = GetValue(options, 'random', false); + var randomB = GetValue(options, 'randomB', false); + var repeat = GetValue(options, 'repeat', 0); + var yoyo = GetValue(options, 'yoyo', false); + + var out = []; + + if (randomB) + { + Shuffle(b); + } + + // Endless repeat, so limit by max + if (repeat === -1) + { + if (max === 0) + { + repeat = 0; + } + else + { + // Work out how many repeats we need + var total = (a.length * b.length) * qty; + + if (yoyo) + { + total *= 2; + } + + repeat = Math.ceil(max / total); + } + } + + for (var i = 0; i <= repeat; i++) + { + var chunk = BuildChunk(a, b, qty); + + if (random) + { + Shuffle(chunk); + } + + out = out.concat(chunk); + + if (yoyo) + { + chunk.reverse(); + + out = out.concat(chunk); + } + } + + if (max) + { + out.splice(max); + } + + return out; +}; + +module.exports = Range; diff --git a/src/utils/array/Remove.js b/src/utils/array/Remove.js index edaab09c6..43957ac11 100644 --- a/src/utils/array/Remove.js +++ b/src/utils/array/Remove.js @@ -1,85 +1,85 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SpliceOne = require('./SpliceOne'); - -/** - * Removes the given item, or array of items, from the array. - * - * The array is modified in-place. - * - * You can optionally specify a callback to be invoked for each item successfully removed from the array. - * - * @function Phaser.Utils.Array.Remove - * @since 3.4.0 - * - * @param {array} array - The array to be modified. - * @param {*|Array.<*>} item - The item, or array of items, to be removed from the array. - * @param {function} [callback] - A callback to be invoked for each item successfully removed from the array. - * @param {object} [context] - The context in which the callback is invoked. - * - * @return {*|Array.<*>} The item, or array of items, that were successfully removed from the array. - */ -var Remove = function (array, item, callback, context) -{ - if (context === undefined) { context = array; } - - var index; - - // Fast path to avoid array mutation and iteration - if (!Array.isArray(item)) - { - index = array.indexOf(item); - - if (index !== -1) - { - SpliceOne(array, index); - - if (callback) - { - callback.call(context, item); - } - - return item; - } - else - { - return null; - } - } - - // If we got this far, we have an array of items to remove - - var itemLength = item.length - 1; - - while (itemLength >= 0) - { - var entry = item[itemLength]; - - index = array.indexOf(entry); - - if (index !== -1) - { - SpliceOne(array, index); - - if (callback) - { - callback.call(context, entry); - } - } - else - { - // Item wasn't found in the array, so remove it from our return results - item.pop(); - } - - itemLength--; - } - - return item; -}; - -module.exports = Remove; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SpliceOne = require('./SpliceOne'); + +/** + * Removes the given item, or array of items, from the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for each item successfully removed from the array. + * + * @function Phaser.Utils.Array.Remove + * @since 3.4.0 + * + * @param {array} array - The array to be modified. + * @param {*|Array.<*>} item - The item, or array of items, to be removed from the array. + * @param {function} [callback] - A callback to be invoked for each item successfully removed from the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {*|Array.<*>} The item, or array of items, that were successfully removed from the array. + */ +var Remove = function (array, item, callback, context) +{ + if (context === undefined) { context = array; } + + var index; + + // Fast path to avoid array mutation and iteration + if (!Array.isArray(item)) + { + index = array.indexOf(item); + + if (index !== -1) + { + SpliceOne(array, index); + + if (callback) + { + callback.call(context, item); + } + + return item; + } + else + { + return null; + } + } + + // If we got this far, we have an array of items to remove + + var itemLength = item.length - 1; + + while (itemLength >= 0) + { + var entry = item[itemLength]; + + index = array.indexOf(entry); + + if (index !== -1) + { + SpliceOne(array, index); + + if (callback) + { + callback.call(context, entry); + } + } + else + { + // Item wasn't found in the array, so remove it from our return results + item.pop(); + } + + itemLength--; + } + + return item; +}; + +module.exports = Remove; diff --git a/src/utils/array/RemoveAt.js b/src/utils/array/RemoveAt.js index 83dca5c63..c892df332 100644 --- a/src/utils/array/RemoveAt.js +++ b/src/utils/array/RemoveAt.js @@ -1,45 +1,45 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SpliceOne = require('./SpliceOne'); - -/** - * Removes the item from the given position in the array. - * - * The array is modified in-place. - * - * You can optionally specify a callback to be invoked for the item if it is successfully removed from the array. - * - * @function Phaser.Utils.Array.RemoveAt - * @since 3.4.0 - * - * @param {array} array - The array to be modified. - * @param {integer} index - The array index to remove the item from. The index must be in bounds or it will throw an error. - * @param {function} [callback] - A callback to be invoked for the item removed from the array. - * @param {object} [context] - The context in which the callback is invoked. - * - * @return {*} The item that was removed. - */ -var RemoveAt = function (array, index, callback, context) -{ - if (context === undefined) { context = array; } - - if (index < 0 || index > array.length - 1) - { - throw new Error('Index out of bounds'); - } - - var item = SpliceOne(array, index); - - if (callback) - { - callback.call(context, item); - } - - return item; -}; - -module.exports = RemoveAt; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SpliceOne = require('./SpliceOne'); + +/** + * Removes the item from the given position in the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for the item if it is successfully removed from the array. + * + * @function Phaser.Utils.Array.RemoveAt + * @since 3.4.0 + * + * @param {array} array - The array to be modified. + * @param {integer} index - The array index to remove the item from. The index must be in bounds or it will throw an error. + * @param {function} [callback] - A callback to be invoked for the item removed from the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {*} The item that was removed. + */ +var RemoveAt = function (array, index, callback, context) +{ + if (context === undefined) { context = array; } + + if (index < 0 || index > array.length - 1) + { + throw new Error('Index out of bounds'); + } + + var item = SpliceOne(array, index); + + if (callback) + { + callback.call(context, item); + } + + return item; +}; + +module.exports = RemoveAt; diff --git a/src/utils/array/RemoveBetween.js b/src/utils/array/RemoveBetween.js index 5ef45c2eb..ee41871ef 100644 --- a/src/utils/array/RemoveBetween.js +++ b/src/utils/array/RemoveBetween.js @@ -1,57 +1,57 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SafeRange = require('./SafeRange'); - -/** - * Removes the item within the given range in the array. - * - * The array is modified in-place. - * - * You can optionally specify a callback to be invoked for the item/s successfully removed from the array. - * - * @function Phaser.Utils.Array.RemoveBetween - * @since 3.4.0 - * - * @param {array} array - The array to be modified. - * @param {integer} startIndex - The start index to remove from. - * @param {integer} endIndex - The end index to remove to. - * @param {function} [callback] - A callback to be invoked for the item removed from the array. - * @param {object} [context] - The context in which the callback is invoked. - * - * @return {Array.<*>} An array of items that were removed. - */ -var RemoveBetween = function (array, startIndex, endIndex, callback, context) -{ - if (startIndex === undefined) { startIndex = 0; } - if (endIndex === undefined) { endIndex = array.length; } - if (context === undefined) { context = array; } - - if (SafeRange(array, startIndex, endIndex)) - { - var size = endIndex - startIndex; - - var removed = array.splice(startIndex, size); - - if (callback) - { - for (var i = 0; i < removed.length; i++) - { - var entry = removed[i]; - - callback.call(context, entry); - } - } - - return removed; - } - else - { - return []; - } -}; - -module.exports = RemoveBetween; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = require('./SafeRange'); + +/** + * Removes the item within the given range in the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for the item/s successfully removed from the array. + * + * @function Phaser.Utils.Array.RemoveBetween + * @since 3.4.0 + * + * @param {array} array - The array to be modified. + * @param {integer} startIndex - The start index to remove from. + * @param {integer} endIndex - The end index to remove to. + * @param {function} [callback] - A callback to be invoked for the item removed from the array. + * @param {object} [context] - The context in which the callback is invoked. + * + * @return {Array.<*>} An array of items that were removed. + */ +var RemoveBetween = function (array, startIndex, endIndex, callback, context) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + if (context === undefined) { context = array; } + + if (SafeRange(array, startIndex, endIndex)) + { + var size = endIndex - startIndex; + + var removed = array.splice(startIndex, size); + + if (callback) + { + for (var i = 0; i < removed.length; i++) + { + var entry = removed[i]; + + callback.call(context, entry); + } + } + + return removed; + } + else + { + return []; + } +}; + +module.exports = RemoveBetween; diff --git a/src/utils/array/RemoveRandomElement.js b/src/utils/array/RemoveRandomElement.js index 113243f52..ffc162176 100644 --- a/src/utils/array/RemoveRandomElement.js +++ b/src/utils/array/RemoveRandomElement.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SpliceOne = require('./SpliceOne'); - -/** - * Removes a random object from the given array and returns it. - * Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. - * - * @function Phaser.Utils.Array.RemoveRandomElement - * @since 3.0.0 - * - * @param {array} array - The array to removed a random element from. - * @param {integer} [start=0] - The array index to start the search from. - * @param {integer} [length=array.length] - Optional restriction on the number of elements to randomly select from. - * - * @return {object} The random element that was removed, or `null` if there were no array elements that fell within the given range. - */ -var RemoveRandomElement = function (array, start, length) -{ - if (start === undefined) { start = 0; } - if (length === undefined) { length = array.length; } - - var randomIndex = start + Math.floor(Math.random() * length); - - return SpliceOne(array, randomIndex); -}; - -module.exports = RemoveRandomElement; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SpliceOne = require('./SpliceOne'); + +/** + * Removes a random object from the given array and returns it. + * Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. + * + * @function Phaser.Utils.Array.RemoveRandomElement + * @since 3.0.0 + * + * @param {array} array - The array to removed a random element from. + * @param {integer} [start=0] - The array index to start the search from. + * @param {integer} [length=array.length] - Optional restriction on the number of elements to randomly select from. + * + * @return {object} The random element that was removed, or `null` if there were no array elements that fell within the given range. + */ +var RemoveRandomElement = function (array, start, length) +{ + if (start === undefined) { start = 0; } + if (length === undefined) { length = array.length; } + + var randomIndex = start + Math.floor(Math.random() * length); + + return SpliceOne(array, randomIndex); +}; + +module.exports = RemoveRandomElement; diff --git a/src/utils/array/Replace.js b/src/utils/array/Replace.js index aab5fd2e9..6212ccdd5 100644 --- a/src/utils/array/Replace.js +++ b/src/utils/array/Replace.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Replaces an element of the array with the new element. - * The new element cannot already be a member of the array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.Replace - * @since 3.4.0 - * - * @param {array} array - The array to search within. - * @param {*} oldChild - The element in the array that will be replaced. - * @param {*} newChild - The element to be inserted into the array at the position of `oldChild`. - * - * @return {boolean} Returns true if the oldChild was successfully replaced, otherwise returns false. - */ -var Replace = function (array, oldChild, newChild) -{ - var index1 = array.indexOf(oldChild); - var index2 = array.indexOf(newChild); - - if (index1 !== -1 && index2 === -1) - { - array[index1] = newChild; - - return true; - } - else - { - return false; - } -}; - -module.exports = Replace; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Replaces an element of the array with the new element. + * The new element cannot already be a member of the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.Replace + * @since 3.4.0 + * + * @param {array} array - The array to search within. + * @param {*} oldChild - The element in the array that will be replaced. + * @param {*} newChild - The element to be inserted into the array at the position of `oldChild`. + * + * @return {boolean} Returns true if the oldChild was successfully replaced, otherwise returns false. + */ +var Replace = function (array, oldChild, newChild) +{ + var index1 = array.indexOf(oldChild); + var index2 = array.indexOf(newChild); + + if (index1 !== -1 && index2 === -1) + { + array[index1] = newChild; + + return true; + } + else + { + return false; + } +}; + +module.exports = Replace; diff --git a/src/utils/array/RotateLeft.js b/src/utils/array/RotateLeft.js index 9e706c4c7..3b034c56c 100644 --- a/src/utils/array/RotateLeft.js +++ b/src/utils/array/RotateLeft.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves the element at the start of the array to the end, shifting all items in the process. - * The "rotation" happens to the left. - * - * @function Phaser.Utils.Array.RotateLeft - * @since 3.0.0 - * - * @param {array} array - The array to shift to the left. This array is modified in place. - * @param {integer} [total=1] - The number of times to shift the array. - * - * @return {*} The most recently shifted element. - */ -var RotateLeft = function (array, total) -{ - if (total === undefined) { total = 1; } - - var element = null; - - for (var i = 0; i < total; i++) - { - element = array.shift(); - array.push(element); - } - - return element; -}; - -module.exports = RotateLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the element at the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * @function Phaser.Utils.Array.RotateLeft + * @since 3.0.0 + * + * @param {array} array - The array to shift to the left. This array is modified in place. + * @param {integer} [total=1] - The number of times to shift the array. + * + * @return {*} The most recently shifted element. + */ +var RotateLeft = function (array, total) +{ + if (total === undefined) { total = 1; } + + var element = null; + + for (var i = 0; i < total; i++) + { + element = array.shift(); + array.push(element); + } + + return element; +}; + +module.exports = RotateLeft; diff --git a/src/utils/array/RotateRight.js b/src/utils/array/RotateRight.js index 783495688..b1d99aae5 100644 --- a/src/utils/array/RotateRight.js +++ b/src/utils/array/RotateRight.js @@ -1,34 +1,34 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves the element at the end of the array to the start, shifting all items in the process. - * The "rotation" happens to the right. - * - * @function Phaser.Utils.Array.RotateRight - * @since 3.0.0 - * - * @param {array} array - The array to shift to the right. This array is modified in place. - * @param {integer} [total=1] - The number of times to shift the array. - * - * @return {*} The most recently shifted element. - */ -var RotateRight = function (array, total) -{ - if (total === undefined) { total = 1; } - - var element = null; - - for (var i = 0; i < total; i++) - { - element = array.pop(); - array.unshift(element); - } - - return element; -}; - -module.exports = RotateRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the element at the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * @function Phaser.Utils.Array.RotateRight + * @since 3.0.0 + * + * @param {array} array - The array to shift to the right. This array is modified in place. + * @param {integer} [total=1] - The number of times to shift the array. + * + * @return {*} The most recently shifted element. + */ +var RotateRight = function (array, total) +{ + if (total === undefined) { total = 1; } + + var element = null; + + for (var i = 0; i < total; i++) + { + element = array.pop(); + array.unshift(element); + } + + return element; +}; + +module.exports = RotateRight; diff --git a/src/utils/array/SafeRange.js b/src/utils/array/SafeRange.js index 6a7400305..0c2c2f9e6 100644 --- a/src/utils/array/SafeRange.js +++ b/src/utils/array/SafeRange.js @@ -1,43 +1,43 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Tests if the start and end indexes are a safe range for the given array. - * - * @function Phaser.Utils.Array.SafeRange - * @since 3.4.0 - * - * @param {array} array - The array to check. - * @param {integer} startIndex - The start index. - * @param {integer} endIndex - The end index. - * @param {boolean} [throwError=true] - Throw an error if the range is out of bounds. - * - * @return {boolean} True if the range is safe, otherwise false. - */ -var SafeRange = function (array, startIndex, endIndex, throwError) -{ - var len = array.length; - - if (startIndex < 0 || - startIndex > len || - startIndex >= endIndex || - endIndex > len || - startIndex + endIndex > len) - { - if (throwError) - { - throw new Error('Range Error: Values outside acceptable range'); - } - - return false; - } - else - { - return true; - } -}; - -module.exports = SafeRange; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Tests if the start and end indexes are a safe range for the given array. + * + * @function Phaser.Utils.Array.SafeRange + * @since 3.4.0 + * + * @param {array} array - The array to check. + * @param {integer} startIndex - The start index. + * @param {integer} endIndex - The end index. + * @param {boolean} [throwError=true] - Throw an error if the range is out of bounds. + * + * @return {boolean} True if the range is safe, otherwise false. + */ +var SafeRange = function (array, startIndex, endIndex, throwError) +{ + var len = array.length; + + if (startIndex < 0 || + startIndex > len || + startIndex >= endIndex || + endIndex > len || + startIndex + endIndex > len) + { + if (throwError) + { + throw new Error('Range Error: Values outside acceptable range'); + } + + return false; + } + else + { + return true; + } +}; + +module.exports = SafeRange; diff --git a/src/utils/array/SendToBack.js b/src/utils/array/SendToBack.js index 97834c3b1..1f5a7b7c6 100644 --- a/src/utils/array/SendToBack.js +++ b/src/utils/array/SendToBack.js @@ -1,32 +1,32 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Moves the given element to the bottom of the array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.SendToBack - * @since 3.4.0 - * - * @param {array} array - The array. - * @param {*} item - The element to move. - * - * @return {*} The element that was moved. - */ -var SendToBack = function (array, item) -{ - var currentIndex = array.indexOf(item); - - if (currentIndex !== -1 && currentIndex > 0) - { - array.splice(currentIndex, 1); - array.unshift(item); - } - - return item; -}; - -module.exports = SendToBack; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Moves the given element to the bottom of the array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.SendToBack + * @since 3.4.0 + * + * @param {array} array - The array. + * @param {*} item - The element to move. + * + * @return {*} The element that was moved. + */ +var SendToBack = function (array, item) +{ + var currentIndex = array.indexOf(item); + + if (currentIndex !== -1 && currentIndex > 0) + { + array.splice(currentIndex, 1); + array.unshift(item); + } + + return item; +}; + +module.exports = SendToBack; diff --git a/src/utils/array/SetAll.js b/src/utils/array/SetAll.js index db1e3b4f1..0342b5357 100644 --- a/src/utils/array/SetAll.js +++ b/src/utils/array/SetAll.js @@ -1,49 +1,49 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var SafeRange = require('./SafeRange'); - -/** - * Scans the array for elements with the given property. If found, the property is set to the `value`. - * - * For example: `SetAll('visible', true)` would set all elements that have a `visible` property to `false`. - * - * Optionally you can specify a start and end index. For example if the array had 100 elements, - * and you set `startIndex` to 0 and `endIndex` to 50, it would update only the first 50 elements. - * - * @function Phaser.Utils.Array.SetAll - * @since 3.4.0 - * - * @param {array} array - The array to search. - * @param {string} property - The property to test for on each array element. - * @param {*} value - The value to set the property to. - * @param {integer} [startIndex] - An optional start index to search from. - * @param {integer} [endIndex] - An optional end index to search to. - * - * @return {array} The input array. - */ -var SetAll = function (array, property, value, startIndex, endIndex) -{ - if (startIndex === undefined) { startIndex = 0; } - if (endIndex === undefined) { endIndex = array.length; } - - if (SafeRange(array, startIndex, endIndex)) - { - for (var i = startIndex; i < endIndex; i++) - { - var entry = array[i]; - - if (entry.hasOwnProperty(property)) - { - entry[property] = value; - } - } - } - - return array; -}; - -module.exports = SetAll; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var SafeRange = require('./SafeRange'); + +/** + * Scans the array for elements with the given property. If found, the property is set to the `value`. + * + * For example: `SetAll('visible', true)` would set all elements that have a `visible` property to `false`. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would update only the first 50 elements. + * + * @function Phaser.Utils.Array.SetAll + * @since 3.4.0 + * + * @param {array} array - The array to search. + * @param {string} property - The property to test for on each array element. + * @param {*} value - The value to set the property to. + * @param {integer} [startIndex] - An optional start index to search from. + * @param {integer} [endIndex] - An optional end index to search to. + * + * @return {array} The input array. + */ +var SetAll = function (array, property, value, startIndex, endIndex) +{ + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = array.length; } + + if (SafeRange(array, startIndex, endIndex)) + { + for (var i = startIndex; i < endIndex; i++) + { + var entry = array[i]; + + if (entry.hasOwnProperty(property)) + { + entry[property] = value; + } + } + } + + return array; +}; + +module.exports = SetAll; diff --git a/src/utils/array/Shuffle.js b/src/utils/array/Shuffle.js index 6ee815587..90e0f023b 100644 --- a/src/utils/array/Shuffle.js +++ b/src/utils/array/Shuffle.js @@ -1,35 +1,35 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Shuffles the contents of the given array using the Fisher-Yates implementation. - * - * The original array is modified directly and returned. - * - * @function Phaser.Utils.Array.Shuffle - * @since 3.0.0 - * - * @generic T - * @genericUse {T[]} - [array,$return] - * - * @param {T[]} array - The array to shuffle. This array is modified in place. - * - * @return {T[]} The shuffled array. - */ -var Shuffle = function (array) -{ - for (var i = array.length - 1; i > 0; i--) - { - var j = Math.floor(Math.random() * (i + 1)); - var temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - return array; -}; - -module.exports = Shuffle; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Shuffles the contents of the given array using the Fisher-Yates implementation. + * + * The original array is modified directly and returned. + * + * @function Phaser.Utils.Array.Shuffle + * @since 3.0.0 + * + * @generic T + * @genericUse {T[]} - [array,$return] + * + * @param {T[]} array - The array to shuffle. This array is modified in place. + * + * @return {T[]} The shuffled array. + */ +var Shuffle = function (array) +{ + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; +}; + +module.exports = Shuffle; diff --git a/src/utils/array/SpliceOne.js b/src/utils/array/SpliceOne.js index 4ac0175d2..6fa92b96a 100644 --- a/src/utils/array/SpliceOne.js +++ b/src/utils/array/SpliceOne.js @@ -1,40 +1,40 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * 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 {integer} index - The index of the item which should be spliced. - * - * @return {*} The item which was spliced (removed). - */ -var SpliceOne = function (array, index) -{ - if (index >= array.length) - { - return; - } - - var len = array.length - 1; - - var item = array[index]; - - for (var i = index; i < len; i++) - { - array[i] = array[i + 1]; - } - - array.length = len; - - return item; -}; - -module.exports = SpliceOne; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * 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 {integer} index - The index of the item which should be spliced. + * + * @return {*} The item which was spliced (removed). + */ +var SpliceOne = function (array, index) +{ + if (index >= array.length) + { + return; + } + + var len = array.length - 1; + + var item = array[index]; + + for (var i = index; i < len; i++) + { + array[i] = array[i + 1]; + } + + array.length = len; + + return item; +}; + +module.exports = SpliceOne; diff --git a/src/utils/array/StableSort.js b/src/utils/array/StableSort.js index 7a7812bcb..eb799218a 100644 --- a/src/utils/array/StableSort.js +++ b/src/utils/array/StableSort.js @@ -1,142 +1,142 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -//! stable.js 0.1.6, https://github.com/Two-Screen/stable -//! © 2017 Angry Bytes and contributors. MIT licensed. - -/** - * @namespace Phaser.Utils.Array.StableSortFunctions - */ - -(function() { - - /** - * A stable array sort, because `Array#sort()` is not guaranteed stable. - * This is an implementation of merge sort, without recursion. - * - * @function Phaser.Utils.Array.StableSort - * @since 3.0.0 - * - * @param {array} arr - The input array to be sorted. - * @param {function} comp - The comparison handler. - * - * @return {array} The sorted result. - */ -var stable = function(arr, comp) { - return exec(arr.slice(), comp); -}; - - /** - * Sort the input array and simply copy it back if the result isn't in the original array, which happens on an odd number of passes. - * - * @function Phaser.Utils.Array.StableSortFunctions.inplace - * @memberof Phaser.Utils.Array.StableSortFunctions - * @since 3.0.0 - * - * @param {array} arr - The input array. - * @param {function} comp - The comparison handler. - * - * @return {array} The sorted array. - */ -stable.inplace = function(arr, comp) { - var result = exec(arr, comp); - - // This simply copies back if the result isn't in the original array, - // which happens on an odd number of passes. - if (result !== arr) { - pass(result, null, arr.length, arr); - } - - return arr; -}; - -// Execute the sort using the input array and a second buffer as work space. -// Returns one of those two, containing the final result. -function exec(arr, comp) { - if (typeof(comp) !== 'function') { - comp = function(a, b) { - return String(a).localeCompare(b); - }; - } - - // Short-circuit when there's nothing to sort. - var len = arr.length; - if (len <= 1) { - return arr; - } - - // 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. - var buffer = new Array(len); - for (var chk = 1; chk < len; chk *= 2) { - pass(arr, comp, chk, buffer); - - var tmp = arr; - arr = buffer; - buffer = tmp; - } - - return arr; -} - -// Run a single pass with the given chunk size. -var pass = function(arr, comp, chk, result) { - var len = arr.length; - var i = 0; - // Step size / double chunk size. - var dbl = chk * 2; - // Bounds of the left and right chunks. - var l, r, e; - // Iterators over the left and right chunk. - var li, ri; - - // Iterate over pairs of chunks. - for (l = 0; l < len; l += dbl) { - r = l + chk; - e = r + chk; - if (r > len) r = len; - if (e > len) e = len; - - // Iterate both chunks in parallel. - li = l; - ri = r; - while (true) { - // Compare the chunks. - if (li < r && ri < e) { - // This works for a regular `sort()` compatible comparator, - // but also for a simple comparator like: `a > b` - if (comp(arr[li], arr[ri]) <= 0) { - result[i++] = arr[li++]; - } - else { - result[i++] = arr[ri++]; - } - } - // Nothing to compare, just flush what's left. - else if (li < r) { - result[i++] = arr[li++]; - } - else if (ri < e) { - result[i++] = arr[ri++]; - } - // Both iterators are at the chunk ends. - else { - break; - } - } - } -}; - -// Export using CommonJS or to the window. -if (typeof(module) !== 'undefined') { - module.exports = stable; -} -else { - window.stable = stable; -} - +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +//! stable.js 0.1.6, https://github.com/Two-Screen/stable +//! © 2017 Angry Bytes and contributors. MIT licensed. + +/** + * @namespace Phaser.Utils.Array.StableSortFunctions + */ + +(function() { + + /** + * A stable array sort, because `Array#sort()` is not guaranteed stable. + * This is an implementation of merge sort, without recursion. + * + * @function Phaser.Utils.Array.StableSort + * @since 3.0.0 + * + * @param {array} arr - The input array to be sorted. + * @param {function} comp - The comparison handler. + * + * @return {array} The sorted result. + */ +var stable = function(arr, comp) { + return exec(arr.slice(), comp); +}; + + /** + * Sort the input array and simply copy it back if the result isn't in the original array, which happens on an odd number of passes. + * + * @function Phaser.Utils.Array.StableSortFunctions.inplace + * @memberof Phaser.Utils.Array.StableSortFunctions + * @since 3.0.0 + * + * @param {array} arr - The input array. + * @param {function} comp - The comparison handler. + * + * @return {array} The sorted array. + */ +stable.inplace = function(arr, comp) { + var result = exec(arr, comp); + + // This simply copies back if the result isn't in the original array, + // which happens on an odd number of passes. + if (result !== arr) { + pass(result, null, arr.length, arr); + } + + return arr; +}; + +// Execute the sort using the input array and a second buffer as work space. +// Returns one of those two, containing the final result. +function exec(arr, comp) { + if (typeof(comp) !== 'function') { + comp = function(a, b) { + return String(a).localeCompare(b); + }; + } + + // Short-circuit when there's nothing to sort. + var len = arr.length; + if (len <= 1) { + return arr; + } + + // 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. + var buffer = new Array(len); + for (var chk = 1; chk < len; chk *= 2) { + pass(arr, comp, chk, buffer); + + var tmp = arr; + arr = buffer; + buffer = tmp; + } + + return arr; +} + +// Run a single pass with the given chunk size. +var pass = function(arr, comp, chk, result) { + var len = arr.length; + var i = 0; + // Step size / double chunk size. + var dbl = chk * 2; + // Bounds of the left and right chunks. + var l, r, e; + // Iterators over the left and right chunk. + var li, ri; + + // Iterate over pairs of chunks. + for (l = 0; l < len; l += dbl) { + r = l + chk; + e = r + chk; + if (r > len) r = len; + if (e > len) e = len; + + // Iterate both chunks in parallel. + li = l; + ri = r; + while (true) { + // Compare the chunks. + if (li < r && ri < e) { + // This works for a regular `sort()` compatible comparator, + // but also for a simple comparator like: `a > b` + if (comp(arr[li], arr[ri]) <= 0) { + result[i++] = arr[li++]; + } + else { + result[i++] = arr[ri++]; + } + } + // Nothing to compare, just flush what's left. + else if (li < r) { + result[i++] = arr[li++]; + } + else if (ri < e) { + result[i++] = arr[ri++]; + } + // Both iterators are at the chunk ends. + else { + break; + } + } + } +}; + +// Export using CommonJS or to the window. +if (typeof(module) !== 'undefined') { + module.exports = stable; +} +else { + window.stable = stable; +} + })(); \ No newline at end of file diff --git a/src/utils/array/Swap.js b/src/utils/array/Swap.js index 3b95f33e3..7749fe1c9 100644 --- a/src/utils/array/Swap.js +++ b/src/utils/array/Swap.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Swaps the position of two elements in the given array. - * The elements must exist in the same array. - * The array is modified in-place. - * - * @function Phaser.Utils.Array.Swap - * @since 3.4.0 - * - * @param {array} array - The input array. - * @param {*} item1 - The first element to swap. - * @param {*} item2 - The second element to swap. - * - * @return {array} The input array. - */ -var Swap = function (array, item1, item2) -{ - if (item1 === item2) - { - return; - } - - var index1 = array.indexOf(item1); - var index2 = array.indexOf(item2); - - if (index1 < 0 || index2 < 0) - { - throw new Error('Supplied items must be elements of the same array'); - } - - array[index1] = item2; - array[index2] = item1; - - return array; -}; - -module.exports = Swap; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Swaps the position of two elements in the given array. + * The elements must exist in the same array. + * The array is modified in-place. + * + * @function Phaser.Utils.Array.Swap + * @since 3.4.0 + * + * @param {array} array - The input array. + * @param {*} item1 - The first element to swap. + * @param {*} item2 - The second element to swap. + * + * @return {array} The input array. + */ +var Swap = function (array, item1, item2) +{ + if (item1 === item2) + { + return; + } + + var index1 = array.indexOf(item1); + var index2 = array.indexOf(item2); + + if (index1 < 0 || index2 < 0) + { + throw new Error('Supplied items must be elements of the same array'); + } + + array[index1] = item2; + array[index2] = item1; + + return array; +}; + +module.exports = Swap; diff --git a/src/utils/array/index.js b/src/utils/array/index.js index 035f62ebd..ac45f4fe5 100644 --- a/src/utils/array/index.js +++ b/src/utils/array/index.js @@ -1,47 +1,47 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Utils.Array - */ - -module.exports = { - - Matrix: require('./matrix'), - - Add: require('./Add'), - AddAt: require('./AddAt'), - BringToTop: require('./BringToTop'), - CountAllMatching: require('./CountAllMatching'), - Each: require('./Each'), - EachInRange: require('./EachInRange'), - FindClosestInSorted: require('./FindClosestInSorted'), - GetAll: require('./GetAll'), - GetFirst: require('./GetFirst'), - GetRandom: require('./GetRandom'), - MoveDown: require('./MoveDown'), - MoveTo: require('./MoveTo'), - MoveUp: require('./MoveUp'), - NumberArray: require('./NumberArray'), - NumberArrayStep: require('./NumberArrayStep'), - QuickSelect: require('./QuickSelect'), - Range: require('./Range'), - Remove: require('./Remove'), - RemoveAt: require('./RemoveAt'), - RemoveBetween: require('./RemoveBetween'), - RemoveRandomElement: require('./RemoveRandomElement'), - Replace: require('./Replace'), - RotateLeft: require('./RotateLeft'), - RotateRight: require('./RotateRight'), - SafeRange: require('./SafeRange'), - SendToBack: require('./SendToBack'), - SetAll: require('./SetAll'), - Shuffle: require('./Shuffle'), - SpliceOne: require('./SpliceOne'), - StableSort: require('./StableSort'), - Swap: require('./Swap') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Array + */ + +module.exports = { + + Matrix: require('./matrix'), + + Add: require('./Add'), + AddAt: require('./AddAt'), + BringToTop: require('./BringToTop'), + CountAllMatching: require('./CountAllMatching'), + Each: require('./Each'), + EachInRange: require('./EachInRange'), + FindClosestInSorted: require('./FindClosestInSorted'), + GetAll: require('./GetAll'), + GetFirst: require('./GetFirst'), + GetRandom: require('./GetRandom'), + MoveDown: require('./MoveDown'), + MoveTo: require('./MoveTo'), + MoveUp: require('./MoveUp'), + NumberArray: require('./NumberArray'), + NumberArrayStep: require('./NumberArrayStep'), + QuickSelect: require('./QuickSelect'), + Range: require('./Range'), + Remove: require('./Remove'), + RemoveAt: require('./RemoveAt'), + RemoveBetween: require('./RemoveBetween'), + RemoveRandomElement: require('./RemoveRandomElement'), + Replace: require('./Replace'), + RotateLeft: require('./RotateLeft'), + RotateRight: require('./RotateRight'), + SafeRange: require('./SafeRange'), + SendToBack: require('./SendToBack'), + SetAll: require('./SetAll'), + Shuffle: require('./Shuffle'), + SpliceOne: require('./SpliceOne'), + StableSort: require('./StableSort'), + Swap: require('./Swap') + +}; diff --git a/src/utils/array/matrix/CheckMatrix.js b/src/utils/array/matrix/CheckMatrix.js index 82b63ac6a..64486870d 100644 --- a/src/utils/array/matrix/CheckMatrix.js +++ b/src/utils/array/matrix/CheckMatrix.js @@ -1,55 +1,55 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Checks if an array can be used as a matrix. - * - * 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: - * - * ``` - * [ - * [ 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.CheckMatrix - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix] - * - * @param {T[][]} [matrix] - The array to check. - * - * @return {boolean} `true` if the given `matrix` array is a valid matrix. - */ -var CheckMatrix = function (matrix) -{ - if (!Array.isArray(matrix) || matrix.length < 2 || !Array.isArray(matrix[0])) - { - return false; - } - - // How long is the first row? - var size = matrix[0].length; - - // Validate the rest of the rows are the same length - for (var i = 1; i < matrix.length; i++) - { - if (matrix[i].length !== size) - { - return false; - } - } - - return true; -}; - -module.exports = CheckMatrix; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Checks if an array can be used as a matrix. + * + * 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: + * + * ``` + * [ + * [ 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.CheckMatrix + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix] + * + * @param {T[][]} [matrix] - The array to check. + * + * @return {boolean} `true` if the given `matrix` array is a valid matrix. + */ +var CheckMatrix = function (matrix) +{ + if (!Array.isArray(matrix) || matrix.length < 2 || !Array.isArray(matrix[0])) + { + return false; + } + + // How long is the first row? + var size = matrix[0].length; + + // Validate the rest of the rows are the same length + for (var i = 1; i < matrix.length; i++) + { + if (matrix[i].length !== size) + { + return false; + } + } + + return true; +}; + +module.exports = CheckMatrix; diff --git a/src/utils/array/matrix/MatrixToString.js b/src/utils/array/matrix/MatrixToString.js index 0b2602cd0..c55ee3306 100644 --- a/src/utils/array/matrix/MatrixToString.js +++ b/src/utils/array/matrix/MatrixToString.js @@ -1,75 +1,75 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Pad = require('../../string/Pad'); -var CheckMatrix = require('./CheckMatrix'); - -/** - * Generates a string (which you can pass to console.log) from the given Array Matrix. - * - * @function Phaser.Utils.Array.Matrix.MatrixToString - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix] - * - * @param {T[][]} [matrix] - A 2-dimensional array. - * - * @return {string} A string representing the matrix. - */ -var MatrixToString = function (matrix) -{ - var str = ''; - - if (!CheckMatrix(matrix)) - { - return str; - } - - for (var r = 0; r < matrix.length; r++) - { - for (var c = 0; c < matrix[r].length; c++) - { - var cell = matrix[r][c].toString(); - - if (cell !== 'undefined') - { - str += Pad(cell, 2); - } - else - { - str += '?'; - } - - if (c < matrix[r].length - 1) - { - str += ' |'; - } - } - - if (r < matrix.length - 1) - { - str += '\n'; - - for (var i = 0; i < matrix[r].length; i++) - { - str += '---'; - - if (i < matrix[r].length - 1) - { - str += '+'; - } - } - - str += '\n'; - } - - } - - return str; -}; - -module.exports = MatrixToString; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Pad = require('../../string/Pad'); +var CheckMatrix = require('./CheckMatrix'); + +/** + * Generates a string (which you can pass to console.log) from the given Array Matrix. + * + * @function Phaser.Utils.Array.Matrix.MatrixToString + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix] + * + * @param {T[][]} [matrix] - A 2-dimensional array. + * + * @return {string} A string representing the matrix. + */ +var MatrixToString = function (matrix) +{ + var str = ''; + + if (!CheckMatrix(matrix)) + { + return str; + } + + for (var r = 0; r < matrix.length; r++) + { + for (var c = 0; c < matrix[r].length; c++) + { + var cell = matrix[r][c].toString(); + + if (cell !== 'undefined') + { + str += Pad(cell, 2); + } + else + { + str += '?'; + } + + if (c < matrix[r].length - 1) + { + str += ' |'; + } + } + + if (r < matrix.length - 1) + { + str += '\n'; + + for (var i = 0; i < matrix[r].length; i++) + { + str += '---'; + + if (i < matrix[r].length - 1) + { + str += '+'; + } + } + + str += '\n'; + } + + } + + return str; +}; + +module.exports = MatrixToString; diff --git a/src/utils/array/matrix/ReverseColumns.js b/src/utils/array/matrix/ReverseColumns.js index b9aebed49..d7c71ff38 100644 --- a/src/utils/array/matrix/ReverseColumns.js +++ b/src/utils/array/matrix/ReverseColumns.js @@ -1,25 +1,25 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Reverses the columns in the given Array Matrix. - * - * @function Phaser.Utils.Array.Matrix.ReverseColumns - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix,$return] - * - * @param {T[][]} [matrix] - The array matrix to reverse the columns for. - * - * @return {T[][]} The column reversed matrix. - */ -var ReverseColumns = function (matrix) -{ - return matrix.reverse(); -}; - -module.exports = ReverseColumns; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Reverses the columns in the given Array Matrix. + * + * @function Phaser.Utils.Array.Matrix.ReverseColumns + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array matrix to reverse the columns for. + * + * @return {T[][]} The column reversed matrix. + */ +var ReverseColumns = function (matrix) +{ + return matrix.reverse(); +}; + +module.exports = ReverseColumns; diff --git a/src/utils/array/matrix/ReverseRows.js b/src/utils/array/matrix/ReverseRows.js index 7488ed5c1..411fe23c0 100644 --- a/src/utils/array/matrix/ReverseRows.js +++ b/src/utils/array/matrix/ReverseRows.js @@ -1,30 +1,30 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Reverses the rows in the given Array Matrix. - * - * @function Phaser.Utils.Array.Matrix.ReverseRows - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix,$return] - * - * @param {T[][]} [matrix] - The array matrix to reverse the rows for. - * - * @return {T[][]} The column reversed matrix. - */ -var ReverseRows = function (matrix) -{ - for (var i = 0; i < matrix.length; i++) - { - matrix[i].reverse(); - } - - return matrix; -}; - -module.exports = ReverseRows; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Reverses the rows in the given Array Matrix. + * + * @function Phaser.Utils.Array.Matrix.ReverseRows + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array matrix to reverse the rows for. + * + * @return {T[][]} The column reversed matrix. + */ +var ReverseRows = function (matrix) +{ + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + return matrix; +}; + +module.exports = ReverseRows; diff --git a/src/utils/array/matrix/Rotate180.js b/src/utils/array/matrix/Rotate180.js index 88455978f..86a3f15c2 100644 --- a/src/utils/array/matrix/Rotate180.js +++ b/src/utils/array/matrix/Rotate180.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateMatrix = require('./RotateMatrix'); - -/** - * Rotates the array matrix 180 degrees. - * - * @function Phaser.Utils.Array.Matrix.Rotate180 - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix,$return] - * - * @param {T[][]} [matrix] - The array to rotate. - * - * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. - */ -var Rotate180 = function (matrix) -{ - return RotateMatrix(matrix, 180); -}; - -module.exports = Rotate180; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateMatrix = require('./RotateMatrix'); + +/** + * Rotates the array matrix 180 degrees. + * + * @function Phaser.Utils.Array.Matrix.Rotate180 + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array to rotate. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var Rotate180 = function (matrix) +{ + return RotateMatrix(matrix, 180); +}; + +module.exports = Rotate180; diff --git a/src/utils/array/matrix/RotateLeft.js b/src/utils/array/matrix/RotateLeft.js index d42599ec0..f62610604 100644 --- a/src/utils/array/matrix/RotateLeft.js +++ b/src/utils/array/matrix/RotateLeft.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateMatrix = require('./RotateMatrix'); - -/** - * Rotates the array matrix to the left (or 90 degrees) - * - * @function Phaser.Utils.Array.Matrix.RotateLeft - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix,$return] - * - * @param {T[][]} [matrix] - The array to rotate. - * - * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. - */ -var RotateLeft = function (matrix) -{ - return RotateMatrix(matrix, 90); -}; - -module.exports = RotateLeft; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateMatrix = require('./RotateMatrix'); + +/** + * Rotates the array matrix to the left (or 90 degrees) + * + * @function Phaser.Utils.Array.Matrix.RotateLeft + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array to rotate. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var RotateLeft = function (matrix) +{ + return RotateMatrix(matrix, 90); +}; + +module.exports = RotateLeft; diff --git a/src/utils/array/matrix/RotateMatrix.js b/src/utils/array/matrix/RotateMatrix.js index 696b32bcd..f072973f5 100644 --- a/src/utils/array/matrix/RotateMatrix.js +++ b/src/utils/array/matrix/RotateMatrix.js @@ -1,66 +1,66 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var CheckMatrix = require('./CheckMatrix'); -var TransposeMatrix = require('./TransposeMatrix'); - -/** - * Rotates the array matrix based on the given rotation value. - * - * The value can be given in degrees: 90, -90, 270, -270 or 180, - * or a string command: `rotateLeft`, `rotateRight` or `rotate180`. - * - * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. - * - * @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. - * - * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. - */ -var RotateMatrix = function (matrix, direction) -{ - if (direction === undefined) { direction = 90; } - - if (!CheckMatrix(matrix)) - { - return null; - } - - if (typeof direction !== 'string') - { - direction = ((direction % 360) + 360) % 360; - } - - if (direction === 90 || direction === -270 || direction === 'rotateLeft') - { - matrix = TransposeMatrix(matrix); - matrix.reverse(); - } - else if (direction === -90 || direction === 270 || direction === 'rotateRight') - { - matrix.reverse(); - matrix = TransposeMatrix(matrix); - } - else if (Math.abs(direction) === 180 || direction === 'rotate180') - { - for (var i = 0; i < matrix.length; i++) - { - matrix[i].reverse(); - } - - matrix.reverse(); - } - - return matrix; -}; - -module.exports = RotateMatrix; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var CheckMatrix = require('./CheckMatrix'); +var TransposeMatrix = require('./TransposeMatrix'); + +/** + * Rotates the array matrix based on the given rotation value. + * + * The value can be given in degrees: 90, -90, 270, -270 or 180, + * or a string command: `rotateLeft`, `rotateRight` or `rotate180`. + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @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. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var RotateMatrix = function (matrix, direction) +{ + if (direction === undefined) { direction = 90; } + + if (!CheckMatrix(matrix)) + { + return null; + } + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = TransposeMatrix(matrix); + matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix.reverse(); + matrix = TransposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix.reverse(); + } + + return matrix; +}; + +module.exports = RotateMatrix; diff --git a/src/utils/array/matrix/RotateRight.js b/src/utils/array/matrix/RotateRight.js index f88a16eec..3396ef999 100644 --- a/src/utils/array/matrix/RotateRight.js +++ b/src/utils/array/matrix/RotateRight.js @@ -1,27 +1,27 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var RotateMatrix = require('./RotateMatrix'); - -/** - * Rotates the array matrix to the left (or -90 degrees) - * - * @function Phaser.Utils.Array.Matrix.RotateRight - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [matrix,$return] - * - * @param {T[][]} [matrix] - The array to rotate. - * - * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. - */ -var RotateRight = function (matrix) -{ - return RotateMatrix(matrix, -90); -}; - -module.exports = RotateRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var RotateMatrix = require('./RotateMatrix'); + +/** + * Rotates the array matrix to the left (or -90 degrees) + * + * @function Phaser.Utils.Array.Matrix.RotateRight + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [matrix,$return] + * + * @param {T[][]} [matrix] - The array to rotate. + * + * @return {T[][]} The rotated matrix array. The source matrix should be discard for the returned matrix. + */ +var RotateRight = function (matrix) +{ + return RotateMatrix(matrix, -90); +}; + +module.exports = RotateRight; diff --git a/src/utils/array/matrix/TransposeMatrix.js b/src/utils/array/matrix/TransposeMatrix.js index ec8326995..ba9c8076c 100644 --- a/src/utils/array/matrix/TransposeMatrix.js +++ b/src/utils/array/matrix/TransposeMatrix.js @@ -1,42 +1,42 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Transposes the elements of the given matrix (array of arrays). - * - * The transpose of a matrix is a new matrix whose rows are the columns of the original. - * - * @function Phaser.Utils.Array.Matrix.TransposeMatrix - * @since 3.0.0 - * - * @generic T - * @genericUse {T[][]} - [array,$return] - * - * @param {T[][]} [array] - The array matrix to transpose. - * - * @return {T[][]} A new array matrix which is a transposed version of the given array. - */ -var TransposeMatrix = function (array) -{ - var sourceRowCount = array.length; - var sourceColCount = array[0].length; - - var result = new Array(sourceColCount); - - for (var i = 0; i < sourceColCount; i++) - { - result[i] = new Array(sourceRowCount); - - for (var j = sourceRowCount - 1; j > -1; j--) - { - result[i][j] = array[j][i]; - } - } - - return result; -}; - -module.exports = TransposeMatrix; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Transposes the elements of the given matrix (array of arrays). + * + * The transpose of a matrix is a new matrix whose rows are the columns of the original. + * + * @function Phaser.Utils.Array.Matrix.TransposeMatrix + * @since 3.0.0 + * + * @generic T + * @genericUse {T[][]} - [array,$return] + * + * @param {T[][]} [array] - The array matrix to transpose. + * + * @return {T[][]} A new array matrix which is a transposed version of the given array. + */ +var TransposeMatrix = function (array) +{ + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; +}; + +module.exports = TransposeMatrix; diff --git a/src/utils/array/matrix/index.js b/src/utils/array/matrix/index.js index 85ce156f8..57b86d65f 100644 --- a/src/utils/array/matrix/index.js +++ b/src/utils/array/matrix/index.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Utils.Array.Matrix - */ - -module.exports = { - - CheckMatrix: require('./CheckMatrix'), - MatrixToString: require('./MatrixToString'), - ReverseColumns: require('./ReverseColumns'), - ReverseRows: require('./ReverseRows'), - Rotate180: require('./Rotate180'), - RotateLeft: require('./RotateLeft'), - RotateMatrix: require('./RotateMatrix'), - RotateRight: require('./RotateRight'), - TransposeMatrix: require('./TransposeMatrix') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Array.Matrix + */ + +module.exports = { + + CheckMatrix: require('./CheckMatrix'), + MatrixToString: require('./MatrixToString'), + ReverseColumns: require('./ReverseColumns'), + ReverseRows: require('./ReverseRows'), + Rotate180: require('./Rotate180'), + RotateLeft: require('./RotateLeft'), + RotateMatrix: require('./RotateMatrix'), + RotateRight: require('./RotateRight'), + TransposeMatrix: require('./TransposeMatrix') + +}; diff --git a/src/utils/base64/ArrayBufferToBase64.js b/src/utils/base64/ArrayBufferToBase64.js index 79ee1768f..2bdd06804 100644 --- a/src/utils/base64/ArrayBufferToBase64.js +++ b/src/utils/base64/ArrayBufferToBase64.js @@ -1,52 +1,52 @@ -/** - * @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer) - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -/** - * 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. - */ -var ArrayBufferToBase64 = function (arrayBuffer, mediaType) -{ - var bytes = new Uint8Array(arrayBuffer); - var len = bytes.length; - - var base64 = (mediaType) ? 'data:' + mediaType + ';base64,' : ''; - - for (var i = 0; i < len; i += 3) - { - base64 += chars[bytes[i] >> 2]; - base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += chars[bytes[i + 2] & 63]; - } - - if ((len % 3) === 2) - { - base64 = base64.substring(0, base64.length - 1) + '='; - } - else if (len % 3 === 1) - { - base64 = base64.substring(0, base64.length - 2) + '=='; - } - - return base64; -}; - -module.exports = ArrayBufferToBase64; +/** + * @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer) + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +/** + * 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. + */ +var ArrayBufferToBase64 = function (arrayBuffer, mediaType) +{ + var bytes = new Uint8Array(arrayBuffer); + var len = bytes.length; + + var base64 = (mediaType) ? 'data:' + mediaType + ';base64,' : ''; + + for (var i = 0; i < len; i += 3) + { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + + if ((len % 3) === 2) + { + base64 = base64.substring(0, base64.length - 1) + '='; + } + else if (len % 3 === 1) + { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + + return base64; +}; + +module.exports = ArrayBufferToBase64; diff --git a/src/utils/base64/Base64ToArrayBuffer.js b/src/utils/base64/Base64ToArrayBuffer.js index 0a9b97110..f00d25654 100644 --- a/src/utils/base64/Base64ToArrayBuffer.js +++ b/src/utils/base64/Base64ToArrayBuffer.js @@ -1,69 +1,69 @@ -/** - * @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer) - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -// Use a lookup table to find the index. -var lookup = new Uint8Array(256); - -for (var i = 0; i < chars.length; i++) -{ - lookup[chars.charCodeAt(i)] = i; -} - -/** - * Converts a base64 string, either with or without a data uri, into an Array Buffer. - * - * @function Phaser.Utils.Base64.Base64ToArrayBuffer - * @since 3.18.0 - * - * @param {string} base64 - The base64 string to be decoded. Can optionally contain a data URI header, which will be stripped out prior to decoding. - * - * @return {ArrayBuffer} An ArrayBuffer decoded from the base64 data. - */ -var Base64ToArrayBuffer = function (base64) -{ - // Is it a data uri? if so, strip the header away - base64 = base64.substr(base64.indexOf(',') + 1); - - var len = base64.length; - var bufferLength = len * 0.75; - var p = 0; - var encoded1; - var encoded2; - var encoded3; - var encoded4; - - if (base64[len - 1] === '=') - { - bufferLength--; - - if (base64[len - 2] === '=') - { - bufferLength--; - } - } - - var arrayBuffer = new ArrayBuffer(bufferLength); - var bytes = new Uint8Array(arrayBuffer); - - for (var i = 0; i < len; i += 4) - { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i + 1)]; - encoded3 = lookup[base64.charCodeAt(i + 2)]; - encoded4 = lookup[base64.charCodeAt(i + 3)]; - - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - - return arrayBuffer; -}; - -module.exports = Base64ToArrayBuffer; +/** + * @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer) + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +// Use a lookup table to find the index. +var lookup = new Uint8Array(256); + +for (var i = 0; i < chars.length; i++) +{ + lookup[chars.charCodeAt(i)] = i; +} + +/** + * Converts a base64 string, either with or without a data uri, into an Array Buffer. + * + * @function Phaser.Utils.Base64.Base64ToArrayBuffer + * @since 3.18.0 + * + * @param {string} base64 - The base64 string to be decoded. Can optionally contain a data URI header, which will be stripped out prior to decoding. + * + * @return {ArrayBuffer} An ArrayBuffer decoded from the base64 data. + */ +var Base64ToArrayBuffer = function (base64) +{ + // Is it a data uri? if so, strip the header away + base64 = base64.substr(base64.indexOf(',') + 1); + + var len = base64.length; + var bufferLength = len * 0.75; + var p = 0; + var encoded1; + var encoded2; + var encoded3; + var encoded4; + + if (base64[len - 1] === '=') + { + bufferLength--; + + if (base64[len - 2] === '=') + { + bufferLength--; + } + } + + var arrayBuffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(arrayBuffer); + + for (var i = 0; i < len; i += 4) + { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return arrayBuffer; +}; + +module.exports = Base64ToArrayBuffer; diff --git a/src/utils/base64/index.js b/src/utils/base64/index.js index d52ccece2..acbb72282 100644 --- a/src/utils/base64/index.js +++ b/src/utils/base64/index.js @@ -1,16 +1,16 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Utils.Base64 - */ - -module.exports = { - - ArrayBufferToBase64: require('./ArrayBufferToBase64'), - Base64ToArrayBuffer: require('./Base64ToArrayBuffer') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Base64 + */ + +module.exports = { + + ArrayBufferToBase64: require('./ArrayBufferToBase64'), + Base64ToArrayBuffer: require('./Base64ToArrayBuffer') + +}; diff --git a/src/utils/index.js b/src/utils/index.js index 8f34d0e3f..e9b836c36 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -1,18 +1,18 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Utils - */ - -module.exports = { - - Array: require('./array/'), - Base64: require('./base64/'), - Objects: require('./object/'), - String: require('./string/') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils + */ + +module.exports = { + + Array: require('./array/'), + Base64: require('./base64/'), + Objects: require('./object/'), + String: require('./string/') + +}; diff --git a/src/utils/object/Clone.js b/src/utils/object/Clone.js index f82b161a4..b89cab211 100644 --- a/src/utils/object/Clone.js +++ b/src/utils/object/Clone.js @@ -1,36 +1,36 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Shallow Object Clone. Will not clone nested objects. - * - * @function Phaser.Utils.Objects.Clone - * @since 3.0.0 - * - * @param {object} obj - the object from which to clone - * - * @return {object} a new object with the same properties as the input obj - */ -var Clone = function (obj) -{ - var clone = {}; - - for (var key in obj) - { - if (Array.isArray(obj[key])) - { - clone[key] = obj[key].slice(0); - } - else - { - clone[key] = obj[key]; - } - } - - return clone; -}; - -module.exports = Clone; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Shallow Object Clone. Will not clone nested objects. + * + * @function Phaser.Utils.Objects.Clone + * @since 3.0.0 + * + * @param {object} obj - the object from which to clone + * + * @return {object} a new object with the same properties as the input obj + */ +var Clone = function (obj) +{ + var clone = {}; + + for (var key in obj) + { + if (Array.isArray(obj[key])) + { + clone[key] = obj[key].slice(0); + } + else + { + clone[key] = obj[key]; + } + } + + return clone; +}; + +module.exports = Clone; diff --git a/src/utils/object/Extend.js b/src/utils/object/Extend.js index 53641ee0f..f2bf28fb7 100644 --- a/src/utils/object/Extend.js +++ b/src/utils/object/Extend.js @@ -1,93 +1,93 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var IsPlainObject = require('./IsPlainObject'); - -// @param {boolean} deep - Perform a deep copy? -// @param {object} target - The target object to copy to. -// @return {object} The extended object. - -/** - * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ - * - * @function Phaser.Utils.Objects.Extend - * @since 3.0.0 - * - * @return {object} The extended object. - */ -var Extend = function () -{ - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if (typeof target === 'boolean') - { - deep = target; - target = arguments[1] || {}; - - // skip the boolean and the target - i = 2; - } - - // extend Phaser if only one argument is passed - if (length === i) - { - target = this; - --i; - } - - for (; i < length; i++) - { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) - { - // Extend the base object - for (name in options) - { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) - { - continue; - } - - // Recurse if we're merging plain objects or arrays - if (deep && copy && (IsPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) - { - if (copyIsArray) - { - copyIsArray = false; - clone = src && Array.isArray(src) ? src : []; - } - else - { - clone = src && IsPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[name] = Extend(deep, clone, copy); - - // Don't bring in undefined values - } - else if (copy !== undefined) - { - target[name] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -module.exports = Extend; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var IsPlainObject = require('./IsPlainObject'); + +// @param {boolean} deep - Perform a deep copy? +// @param {object} target - The target object to copy to. +// @return {object} The extended object. + +/** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @function Phaser.Utils.Objects.Extend + * @since 3.0.0 + * + * @return {object} The extended object. + */ +var Extend = function () +{ + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') + { + deep = target; + target = arguments[1] || {}; + + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (IsPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && IsPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +module.exports = Extend; diff --git a/src/utils/object/GetAdvancedValue.js b/src/utils/object/GetAdvancedValue.js index 222362729..72f61ede3 100644 --- a/src/utils/object/GetAdvancedValue.js +++ b/src/utils/object/GetAdvancedValue.js @@ -1,81 +1,81 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var MATH = require('../../math'); -var GetValue = require('./GetValue'); - -/** - * Retrieves a value from an object. Allows for more advanced selection options, including: - * - * Allowed types: - * - * Implicit - * { - * x: 4 - * } - * - * From function - * { - * x: function () - * } - * - * Randomly pick one element from the array - * { - * x: [a, b, c, d, e, f] - * } - * - * Random integer between min and max: - * { - * x: { randInt: [min, max] } - * } - * - * Random float between min and max: - * { - * x: { randFloat: [min, max] } - * } - * - * - * @function Phaser.Utils.Objects.GetAdvancedValue - * @since 3.0.0 - * - * @param {object} source - The object to retrieve the value from. - * @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. - * - * @return {*} The value of the requested key. - */ -var GetAdvancedValue = function (source, key, defaultValue) -{ - var value = GetValue(source, key, null); - - if (value === null) - { - return defaultValue; - } - else if (Array.isArray(value)) - { - return MATH.RND.pick(value); - } - else if (typeof value === 'object') - { - if (value.hasOwnProperty('randInt')) - { - return MATH.RND.integerInRange(value.randInt[0], value.randInt[1]); - } - else if (value.hasOwnProperty('randFloat')) - { - return MATH.RND.realInRange(value.randFloat[0], value.randFloat[1]); - } - } - else if (typeof value === 'function') - { - return value(key); - } - - return value; -}; - -module.exports = GetAdvancedValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var MATH = require('../../math'); +var GetValue = require('./GetValue'); + +/** + * Retrieves a value from an object. Allows for more advanced selection options, including: + * + * Allowed types: + * + * Implicit + * { + * x: 4 + * } + * + * From function + * { + * x: function () + * } + * + * Randomly pick one element from the array + * { + * x: [a, b, c, d, e, f] + * } + * + * Random integer between min and max: + * { + * x: { randInt: [min, max] } + * } + * + * Random float between min and max: + * { + * x: { randFloat: [min, max] } + * } + * + * + * @function Phaser.Utils.Objects.GetAdvancedValue + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @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. + * + * @return {*} The value of the requested key. + */ +var GetAdvancedValue = function (source, key, defaultValue) +{ + var value = GetValue(source, key, null); + + if (value === null) + { + return defaultValue; + } + else if (Array.isArray(value)) + { + return MATH.RND.pick(value); + } + else if (typeof value === 'object') + { + if (value.hasOwnProperty('randInt')) + { + return MATH.RND.integerInRange(value.randInt[0], value.randInt[1]); + } + else if (value.hasOwnProperty('randFloat')) + { + return MATH.RND.realInRange(value.randFloat[0], value.randFloat[1]); + } + } + else if (typeof value === 'function') + { + return value(key); + } + + return value; +}; + +module.exports = GetAdvancedValue; diff --git a/src/utils/object/GetFastValue.js b/src/utils/object/GetFastValue.js index c7163b06d..6309db72b 100644 --- a/src/utils/object/GetFastValue.js +++ b/src/utils/object/GetFastValue.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Finds the key within the top level of the {@link source} object, or returns {@link defaultValue} - * - * @function Phaser.Utils.Objects.GetFastValue - * @since 3.0.0 - * - * @param {object} source - The object to search - * @param {string} key - The key for the property on source. Must exist at the top level of the source object (no periods) - * @param {*} [defaultValue] - The default value to use if the key does not exist. - * - * @return {*} The value if found; otherwise, defaultValue (null if none provided) - */ -var GetFastValue = function (source, key, defaultValue) -{ - var t = typeof(source); - - if (!source || t === 'number' || t === 'string') - { - return defaultValue; - } - else if (source.hasOwnProperty(key) && source[key] !== undefined) - { - return source[key]; - } - else - { - return defaultValue; - } -}; - -module.exports = GetFastValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Finds the key within the top level of the {@link source} object, or returns {@link defaultValue} + * + * @function Phaser.Utils.Objects.GetFastValue + * @since 3.0.0 + * + * @param {object} source - The object to search + * @param {string} key - The key for the property on source. Must exist at the top level of the source object (no periods) + * @param {*} [defaultValue] - The default value to use if the key does not exist. + * + * @return {*} The value if found; otherwise, defaultValue (null if none provided) + */ +var GetFastValue = function (source, key, defaultValue) +{ + var t = typeof(source); + + if (!source || t === 'number' || t === 'string') + { + return defaultValue; + } + else if (source.hasOwnProperty(key) && source[key] !== undefined) + { + return source[key]; + } + else + { + return defaultValue; + } +}; + +module.exports = GetFastValue; diff --git a/src/utils/object/GetMinMaxValue.js b/src/utils/object/GetMinMaxValue.js index 9bc49d7a4..ae074b187 100644 --- a/src/utils/object/GetMinMaxValue.js +++ b/src/utils/object/GetMinMaxValue.js @@ -1,33 +1,33 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var GetValue = require('./GetValue'); -var Clamp = require('../../math/Clamp'); - -/** - * Retrieves and clamps a numerical value from an object. - * - * @function Phaser.Utils.Objects.GetMinMaxValue - * @since 3.0.0 - * - * @param {object} source - The object to retrieve the value from. - * @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 (`.`). - * @param {number} min - The minimum value which can be returned. - * @param {number} max - The maximum value which can be returned. - * @param {number} defaultValue - The value to return if the property doesn't exist. It's also constrained to the given bounds. - * - * @return {number} The clamped value from the `source` object. - */ -var GetMinMaxValue = function (source, key, min, max, defaultValue) -{ - if (defaultValue === undefined) { defaultValue = min; } - - var value = GetValue(source, key, defaultValue); - - return Clamp(value, min, max); -}; - -module.exports = GetMinMaxValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var GetValue = require('./GetValue'); +var Clamp = require('../../math/Clamp'); + +/** + * Retrieves and clamps a numerical value from an object. + * + * @function Phaser.Utils.Objects.GetMinMaxValue + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @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 (`.`). + * @param {number} min - The minimum value which can be returned. + * @param {number} max - The maximum value which can be returned. + * @param {number} defaultValue - The value to return if the property doesn't exist. It's also constrained to the given bounds. + * + * @return {number} The clamped value from the `source` object. + */ +var GetMinMaxValue = function (source, key, min, max, defaultValue) +{ + if (defaultValue === undefined) { defaultValue = min; } + + var value = GetValue(source, key, defaultValue); + + return Clamp(value, min, max); +}; + +module.exports = GetMinMaxValue; diff --git a/src/utils/object/GetValue.js b/src/utils/object/GetValue.js index 26ff0ba5a..e35013ed0 100644 --- a/src/utils/object/GetValue.js +++ b/src/utils/object/GetValue.js @@ -1,65 +1,65 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -// Source object -// The key as a string, or an array of keys, i.e. 'banner', or 'banner.hideBanner' -// The default value to use if the key doesn't exist - -/** - * Retrieves a value from an object. - * - * @function Phaser.Utils.Objects.GetValue - * @since 3.0.0 - * - * @param {object} source - The object to retrieve the value from. - * @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. - * - * @return {*} The value of the requested key. - */ -var GetValue = function (source, key, defaultValue) -{ - if (!source || typeof source === 'number') - { - return defaultValue; - } - else if (source.hasOwnProperty(key)) - { - return source[key]; - } - else if (key.indexOf('.') !== -1) - { - var keys = key.split('.'); - var parent = source; - var value = defaultValue; - - // Use for loop here so we can break early - for (var i = 0; i < keys.length; i++) - { - if (parent.hasOwnProperty(keys[i])) - { - // Yes it has a key property, let's carry on down - value = parent[keys[i]]; - - parent = parent[keys[i]]; - } - else - { - // Can't go any further, so reset to default - value = defaultValue; - break; - } - } - - return value; - } - else - { - return defaultValue; - } -}; - -module.exports = GetValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +// Source object +// The key as a string, or an array of keys, i.e. 'banner', or 'banner.hideBanner' +// The default value to use if the key doesn't exist + +/** + * Retrieves a value from an object. + * + * @function Phaser.Utils.Objects.GetValue + * @since 3.0.0 + * + * @param {object} source - The object to retrieve the value from. + * @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. + * + * @return {*} The value of the requested key. + */ +var GetValue = function (source, key, defaultValue) +{ + if (!source || typeof source === 'number') + { + return defaultValue; + } + else if (source.hasOwnProperty(key)) + { + return source[key]; + } + else if (key.indexOf('.') !== -1) + { + var keys = key.split('.'); + var parent = source; + var value = defaultValue; + + // Use for loop here so we can break early + for (var i = 0; i < keys.length; i++) + { + if (parent.hasOwnProperty(keys[i])) + { + // Yes it has a key property, let's carry on down + value = parent[keys[i]]; + + parent = parent[keys[i]]; + } + else + { + // Can't go any further, so reset to default + value = defaultValue; + break; + } + } + + return value; + } + else + { + return defaultValue; + } +}; + +module.exports = GetValue; diff --git a/src/utils/object/HasAll.js b/src/utils/object/HasAll.js index 4ddd97106..965a12d77 100644 --- a/src/utils/object/HasAll.js +++ b/src/utils/object/HasAll.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Verifies that an object contains all requested keys - * - * @function Phaser.Utils.Objects.HasAll - * @since 3.0.0 - * - * @param {object} source - an object on which to check for key existence - * @param {string[]} keys - an array of keys to ensure the source object contains - * - * @return {boolean} true if the source object contains all keys, false otherwise. - */ -var HasAll = function (source, keys) -{ - for (var i = 0; i < keys.length; i++) - { - if (!source.hasOwnProperty(keys[i])) - { - return false; - } - } - - return true; -}; - -module.exports = HasAll; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Verifies that an object contains all requested keys + * + * @function Phaser.Utils.Objects.HasAll + * @since 3.0.0 + * + * @param {object} source - an object on which to check for key existence + * @param {string[]} keys - an array of keys to ensure the source object contains + * + * @return {boolean} true if the source object contains all keys, false otherwise. + */ +var HasAll = function (source, keys) +{ + for (var i = 0; i < keys.length; i++) + { + if (!source.hasOwnProperty(keys[i])) + { + return false; + } + } + + return true; +}; + +module.exports = HasAll; diff --git a/src/utils/object/HasAny.js b/src/utils/object/HasAny.js index f7dfa93d0..3beebb1b5 100644 --- a/src/utils/object/HasAny.js +++ b/src/utils/object/HasAny.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Verifies that an object contains at least one of the requested keys - * - * @function Phaser.Utils.Objects.HasAny - * @since 3.0.0 - * - * @param {object} source - an object on which to check for key existence - * @param {string[]} keys - an array of keys to search the object for - * - * @return {boolean} true if the source object contains at least one of the keys, false otherwise - */ -var HasAny = function (source, keys) -{ - for (var i = 0; i < keys.length; i++) - { - if (source.hasOwnProperty(keys[i])) - { - return true; - } - } - - return false; -}; - -module.exports = HasAny; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Verifies that an object contains at least one of the requested keys + * + * @function Phaser.Utils.Objects.HasAny + * @since 3.0.0 + * + * @param {object} source - an object on which to check for key existence + * @param {string[]} keys - an array of keys to search the object for + * + * @return {boolean} true if the source object contains at least one of the keys, false otherwise + */ +var HasAny = function (source, keys) +{ + for (var i = 0; i < keys.length; i++) + { + if (source.hasOwnProperty(keys[i])) + { + return true; + } + } + + return false; +}; + +module.exports = HasAny; diff --git a/src/utils/object/HasValue.js b/src/utils/object/HasValue.js index 9a8085774..f19a58225 100644 --- a/src/utils/object/HasValue.js +++ b/src/utils/object/HasValue.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Determine whether the source object has a property with the specified key. - * - * @function Phaser.Utils.Objects.HasValue - * @since 3.0.0 - * - * @param {object} source - The source object to be checked. - * @param {string} key - The property to check for within the object - * - * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. - */ -var HasValue = function (source, key) -{ - return (source.hasOwnProperty(key)); -}; - -module.exports = HasValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Determine whether the source object has a property with the specified key. + * + * @function Phaser.Utils.Objects.HasValue + * @since 3.0.0 + * + * @param {object} source - The source object to be checked. + * @param {string} key - The property to check for within the object + * + * @return {boolean} `true` if the provided `key` exists on the `source` object, otherwise `false`. + */ +var HasValue = function (source, key) +{ + return (source.hasOwnProperty(key)); +}; + +module.exports = HasValue; diff --git a/src/utils/object/IsPlainObject.js b/src/utils/object/IsPlainObject.js index 9ab025365..066250c81 100644 --- a/src/utils/object/IsPlainObject.js +++ b/src/utils/object/IsPlainObject.js @@ -1,50 +1,50 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * This is a slightly modified version of jQuery.isPlainObject. - * A plain object is an object whose internal class property is [object Object]. - * - * @function Phaser.Utils.Objects.IsPlainObject - * @since 3.0.0 - * - * @param {object} obj - The object to inspect. - * - * @return {boolean} `true` if the object is plain, otherwise `false`. - */ -var IsPlainObject = function (obj) -{ - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if (typeof(obj) !== 'object' || obj.nodeType || obj === obj.window) - { - return false; - } - - // 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 - try - { - if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) - { - return false; - } - } - catch (e) - { - return false; - } - - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; -}; - -module.exports = IsPlainObject; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * + * @function Phaser.Utils.Objects.IsPlainObject + * @since 3.0.0 + * + * @param {object} obj - The object to inspect. + * + * @return {boolean} `true` if the object is plain, otherwise `false`. + */ +var IsPlainObject = function (obj) +{ + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== 'object' || obj.nodeType || obj === obj.window) + { + return false; + } + + // 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 + try + { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) + { + return false; + } + } + catch (e) + { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; +}; + +module.exports = IsPlainObject; diff --git a/src/utils/object/Merge.js b/src/utils/object/Merge.js index 48aa963d9..69384e98e 100644 --- a/src/utils/object/Merge.js +++ b/src/utils/object/Merge.js @@ -1,39 +1,39 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = require('./Clone'); - -/** - * Creates a new Object using all values from obj1 and obj2. - * If a value exists in both obj1 and obj2, the value in obj1 is used. - * - * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this - * function on shallow objects. - * - * @function Phaser.Utils.Objects.Merge - * @since 3.0.0 - * - * @param {object} obj1 - The first object. - * @param {object} obj2 - The second object. - * - * @return {object} A new object containing the union of obj1's and obj2's properties. - */ -var Merge = function (obj1, obj2) -{ - var clone = Clone(obj1); - - for (var key in obj2) - { - if (!clone.hasOwnProperty(key)) - { - clone[key] = obj2[key]; - } - } - - return clone; -}; - -module.exports = Merge; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = require('./Clone'); + +/** + * Creates a new Object using all values from obj1 and obj2. + * If a value exists in both obj1 and obj2, the value in obj1 is used. + * + * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this + * function on shallow objects. + * + * @function Phaser.Utils.Objects.Merge + * @since 3.0.0 + * + * @param {object} obj1 - The first object. + * @param {object} obj2 - The second object. + * + * @return {object} A new object containing the union of obj1's and obj2's properties. + */ +var Merge = function (obj1, obj2) +{ + var clone = Clone(obj1); + + for (var key in obj2) + { + if (!clone.hasOwnProperty(key)) + { + clone[key] = obj2[key]; + } + } + + return clone; +}; + +module.exports = Merge; diff --git a/src/utils/object/MergeRight.js b/src/utils/object/MergeRight.js index ce5825b26..456e3dd8c 100644 --- a/src/utils/object/MergeRight.js +++ b/src/utils/object/MergeRight.js @@ -1,37 +1,37 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var Clone = require('./Clone'); - -/** - * Creates a new Object using all values from obj1. - * - * Then scans obj2. If a property is found in obj2 that *also* exists in obj1, the value from obj2 is used, otherwise the property is skipped. - * - * @function Phaser.Utils.Objects.MergeRight - * @since 3.0.0 - * - * @param {object} obj1 - The first object to merge. - * @param {object} obj2 - The second object to merge. Keys from this object which also exist in `obj1` will be copied to `obj1`. - * - * @return {object} The merged object. `obj1` and `obj2` are not modified. - */ -var MergeRight = function (obj1, obj2) -{ - var clone = Clone(obj1); - - for (var key in obj2) - { - if (clone.hasOwnProperty(key)) - { - clone[key] = obj2[key]; - } - } - - return clone; -}; - -module.exports = MergeRight; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var Clone = require('./Clone'); + +/** + * Creates a new Object using all values from obj1. + * + * Then scans obj2. If a property is found in obj2 that *also* exists in obj1, the value from obj2 is used, otherwise the property is skipped. + * + * @function Phaser.Utils.Objects.MergeRight + * @since 3.0.0 + * + * @param {object} obj1 - The first object to merge. + * @param {object} obj2 - The second object to merge. Keys from this object which also exist in `obj1` will be copied to `obj1`. + * + * @return {object} The merged object. `obj1` and `obj2` are not modified. + */ +var MergeRight = function (obj1, obj2) +{ + var clone = Clone(obj1); + + for (var key in obj2) + { + if (clone.hasOwnProperty(key)) + { + clone[key] = obj2[key]; + } + } + + return clone; +}; + +module.exports = MergeRight; diff --git a/src/utils/object/Pick.js b/src/utils/object/Pick.js index 5bd377c26..493892232 100644 --- a/src/utils/object/Pick.js +++ b/src/utils/object/Pick.js @@ -1,38 +1,38 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -var HasValue = require('./HasValue'); - -/** - * Returns a new object that only contains the `keys` that were found on the object provided. - * If no `keys` are found, an empty object is returned. - * - * @function Phaser.Utils.Objects.Pick - * @since 3.18.0 - * - * @param {object} object - The object to pick the provided keys from. - * @param {array} keys - An array of properties to retrieve from the provided object. - * - * @return {object} A new object that only contains the `keys` that were found on the provided object. If no `keys` were found, an empty object will be returned. - */ -var Pick = function (object, keys) -{ - var obj = {}; - - for (var i = 0; i < keys.length; i++) - { - var key = keys[i]; - - if (HasValue(object, key)) - { - obj[key] = object[key]; - } - } - - return obj; -}; - -module.exports = Pick; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +var HasValue = require('./HasValue'); + +/** + * Returns a new object that only contains the `keys` that were found on the object provided. + * If no `keys` are found, an empty object is returned. + * + * @function Phaser.Utils.Objects.Pick + * @since 3.18.0 + * + * @param {object} object - The object to pick the provided keys from. + * @param {array} keys - An array of properties to retrieve from the provided object. + * + * @return {object} A new object that only contains the `keys` that were found on the provided object. If no `keys` were found, an empty object will be returned. + */ +var Pick = function (object, keys) +{ + var obj = {}; + + for (var i = 0; i < keys.length; i++) + { + var key = keys[i]; + + if (HasValue(object, key)) + { + obj[key] = object[key]; + } + } + + return obj; +}; + +module.exports = Pick; diff --git a/src/utils/object/SetValue.js b/src/utils/object/SetValue.js index c62157081..a204b63d9 100644 --- a/src/utils/object/SetValue.js +++ b/src/utils/object/SetValue.js @@ -1,77 +1,77 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Sets a value in an object, allowing for dot notation to control the depth of the property. - * - * For example: - * - * ```javascript - * var data = { - * world: { - * position: { - * x: 200, - * y: 100 - * } - * } - * }; - * - * SetValue(data, 'world.position.y', 300); - * - * console.log(data.world.position.y); // 300 - * ``` - * - * @function Phaser.Utils.Objects.SetValue - * @since 3.17.0 - * - * @param {object} source - The object to set the value in. - * @param {string} key - The name of the property in the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) - * @param {any} value - The value to set into the property, if found in the source object. - * - * @return {boolean} `true` if the property key was valid and the value was set, otherwise `false`. - */ -var SetValue = function (source, key, value) -{ - if (!source || typeof source === 'number') - { - return false; - } - else if (source.hasOwnProperty(key)) - { - source[key] = value; - - return true; - } - else if (key.indexOf('.') !== -1) - { - var keys = key.split('.'); - var parent = source; - var prev = source; - - // Use for loop here so we can break early - for (var i = 0; i < keys.length; i++) - { - if (parent.hasOwnProperty(keys[i])) - { - // Yes it has a key property, let's carry on down - prev = parent; - parent = parent[keys[i]]; - } - else - { - return false; - } - } - - prev[keys[keys.length - 1]] = value; - - return true; - } - - return false; -}; - -module.exports = SetValue; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Sets a value in an object, allowing for dot notation to control the depth of the property. + * + * For example: + * + * ```javascript + * var data = { + * world: { + * position: { + * x: 200, + * y: 100 + * } + * } + * }; + * + * SetValue(data, 'world.position.y', 300); + * + * console.log(data.world.position.y); // 300 + * ``` + * + * @function Phaser.Utils.Objects.SetValue + * @since 3.17.0 + * + * @param {object} source - The object to set the value in. + * @param {string} key - The name of the property in the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) + * @param {any} value - The value to set into the property, if found in the source object. + * + * @return {boolean} `true` if the property key was valid and the value was set, otherwise `false`. + */ +var SetValue = function (source, key, value) +{ + if (!source || typeof source === 'number') + { + return false; + } + else if (source.hasOwnProperty(key)) + { + source[key] = value; + + return true; + } + else if (key.indexOf('.') !== -1) + { + var keys = key.split('.'); + var parent = source; + var prev = source; + + // Use for loop here so we can break early + for (var i = 0; i < keys.length; i++) + { + if (parent.hasOwnProperty(keys[i])) + { + // Yes it has a key property, let's carry on down + prev = parent; + parent = parent[keys[i]]; + } + else + { + return false; + } + } + + prev[keys[keys.length - 1]] = value; + + return true; + } + + return false; +}; + +module.exports = SetValue; diff --git a/src/utils/object/index.js b/src/utils/object/index.js index 2e27dadbe..24427b9d6 100644 --- a/src/utils/object/index.js +++ b/src/utils/object/index.js @@ -1,28 +1,28 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Utils.Objects - */ - -module.exports = { - - Clone: require('./Clone'), - Extend: require('./Extend'), - GetAdvancedValue: require('./GetAdvancedValue'), - GetFastValue: require('./GetFastValue'), - GetMinMaxValue: require('./GetMinMaxValue'), - GetValue: require('./GetValue'), - HasAll: require('./HasAll'), - HasAny: require('./HasAny'), - HasValue: require('./HasValue'), - IsPlainObject: require('./IsPlainObject'), - Merge: require('./Merge'), - MergeRight: require('./MergeRight'), - Pick: require('./Pick'), - SetValue: require('./SetValue') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.Objects + */ + +module.exports = { + + Clone: require('./Clone'), + Extend: require('./Extend'), + GetAdvancedValue: require('./GetAdvancedValue'), + GetFastValue: require('./GetFastValue'), + GetMinMaxValue: require('./GetMinMaxValue'), + GetValue: require('./GetValue'), + HasAll: require('./HasAll'), + HasAny: require('./HasAny'), + HasValue: require('./HasValue'), + IsPlainObject: require('./IsPlainObject'), + Merge: require('./Merge'), + MergeRight: require('./MergeRight'), + Pick: require('./Pick'), + SetValue: require('./SetValue') + +}; diff --git a/src/utils/string/Format.js b/src/utils/string/Format.js index 0aaae0993..1571f2767 100644 --- a/src/utils/string/Format.js +++ b/src/utils/string/Format.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes a string and replaces instances of markers with values in the given array. - * The markers take the form of `%1`, `%2`, etc. I.e.: - * - * `Format("The %1 is worth %2 gold", [ 'Sword', 500 ])` - * - * @function Phaser.Utils.String.Format - * @since 3.0.0 - * - * @param {string} string - The string containing the replacement markers. - * @param {array} values - An array containing values that will replace the markers. If no value exists an empty string is inserted instead. - * - * @return {string} The string containing replaced values. - */ -var Format = function (string, values) -{ - return string.replace(/%([0-9]+)/g, function (s, n) - { - return values[Number(n) - 1]; - }); -}; - -module.exports = Format; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes a string and replaces instances of markers with values in the given array. + * The markers take the form of `%1`, `%2`, etc. I.e.: + * + * `Format("The %1 is worth %2 gold", [ 'Sword', 500 ])` + * + * @function Phaser.Utils.String.Format + * @since 3.0.0 + * + * @param {string} string - The string containing the replacement markers. + * @param {array} values - An array containing values that will replace the markers. If no value exists an empty string is inserted instead. + * + * @return {string} The string containing replaced values. + */ +var Format = function (string, values) +{ + return string.replace(/%([0-9]+)/g, function (s, n) + { + return values[Number(n) - 1]; + }); +}; + +module.exports = Format; diff --git a/src/utils/string/Pad.js b/src/utils/string/Pad.js index d8e5c609e..d4ba651fd 100644 --- a/src/utils/string/Pad.js +++ b/src/utils/string/Pad.js @@ -1,70 +1,70 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes the given string and pads it out, to the length required, using the character - * specified. For example if you need a string to be 6 characters long, you can call: - * - * `pad('bob', 6, '-', 2)` - * - * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. - * - * You can also use it to pad numbers (they are always returned as strings): - * - * `pad(512, 6, '0', 1)` - * - * Would return: `000512` with the string padded to the left. - * - * If you don't specify a direction it'll pad to both sides: - * - * `pad('c64', 7, '*')` - * - * Would return: `**c64**` - * - * @function Phaser.Utils.String.Pad - * @since 3.0.0 - * - * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. - * @param {integer} [len=0] - The number of characters to be added. - * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). - * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). - * - * @return {string} The padded string. - */ -var Pad = function (str, len, pad, dir) -{ - if (len === undefined) { len = 0; } - if (pad === undefined) { pad = ' '; } - if (dir === undefined) { dir = 3; } - - str = str.toString(); - - var padlen = 0; - - if (len + 1 >= str.length) - { - switch (dir) - { - case 1: - str = new Array(len + 1 - str.length).join(pad) + str; - break; - - case 3: - var right = Math.ceil((padlen = len - str.length) / 2); - var left = padlen - right; - str = new Array(left + 1).join(pad) + str + new Array(right + 1).join(pad); - break; - - default: - str = str + new Array(len + 1 - str.length).join(pad); - break; - } - } - - return str; -}; - -module.exports = Pad; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @function Phaser.Utils.String.Pad + * @since 3.0.0 + * + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * + * @return {string} The padded string. + */ +var Pad = function (str, len, pad, dir) +{ + if (len === undefined) { len = 0; } + if (pad === undefined) { pad = ' '; } + if (dir === undefined) { dir = 3; } + + str = str.toString(); + + var padlen = 0; + + if (len + 1 >= str.length) + { + switch (dir) + { + case 1: + str = new Array(len + 1 - str.length).join(pad) + str; + break; + + case 3: + var right = Math.ceil((padlen = len - str.length) / 2); + var left = padlen - right; + str = new Array(left + 1).join(pad) + str + new Array(right + 1).join(pad); + break; + + default: + str = str + new Array(len + 1 - str.length).join(pad); + break; + } + } + + return str; +}; + +module.exports = Pad; diff --git a/src/utils/string/Reverse.js b/src/utils/string/Reverse.js index 22bfeba63..632561a48 100644 --- a/src/utils/string/Reverse.js +++ b/src/utils/string/Reverse.js @@ -1,23 +1,23 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Takes the given string and reverses it, returning the reversed string. - * For example if given the string `Atari 520ST` it would return `TS025 iratA`. - * - * @function Phaser.Utils.String.Reverse - * @since 3.0.0 - * - * @param {string} string - The string to be reversed. - * - * @return {string} The reversed string. - */ -var Reverse = function (string) -{ - return string.split('').reverse().join(''); -}; - -module.exports = Reverse; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @function Phaser.Utils.String.Reverse + * @since 3.0.0 + * + * @param {string} string - The string to be reversed. + * + * @return {string} The reversed string. + */ +var Reverse = function (string) +{ + return string.split('').reverse().join(''); +}; + +module.exports = Reverse; diff --git a/src/utils/string/UUID.js b/src/utils/string/UUID.js index 37c2518be..5731e42fb 100644 --- a/src/utils/string/UUID.js +++ b/src/utils/string/UUID.js @@ -1,29 +1,29 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Creates and returns an RFC4122 version 4 compliant UUID. - * - * The string is in the form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` where each `x` is replaced with a random - * hexadecimal digit from 0 to f, and `y` is replaced with a random hexadecimal digit from 8 to b. - * - * @function Phaser.Utils.String.UUID - * @since 3.12.0 - * - * @return {string} The UUID string. - */ -var UUID = function () -{ - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) - { - var r = Math.random() * 16 | 0; - var v = (c === 'x') ? r : (r & 0x3 | 0x8); - - return v.toString(16); - }); -}; - -module.exports = UUID; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Creates and returns an RFC4122 version 4 compliant UUID. + * + * The string is in the form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` where each `x` is replaced with a random + * hexadecimal digit from 0 to f, and `y` is replaced with a random hexadecimal digit from 8 to b. + * + * @function Phaser.Utils.String.UUID + * @since 3.12.0 + * + * @return {string} The UUID string. + */ +var UUID = function () +{ + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) + { + var r = Math.random() * 16 | 0; + var v = (c === 'x') ? r : (r & 0x3 | 0x8); + + return v.toString(16); + }); +}; + +module.exports = UUID; diff --git a/src/utils/string/UppercaseFirst.js b/src/utils/string/UppercaseFirst.js index e19e3b36d..c099a3246 100644 --- a/src/utils/string/UppercaseFirst.js +++ b/src/utils/string/UppercaseFirst.js @@ -1,31 +1,31 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * Capitalizes the first letter of a string if there is one. - * @example - * UppercaseFirst('abc'); - * // returns 'Abc' - * @example - * UppercaseFirst('the happy family'); - * // returns 'The happy family' - * @example - * UppercaseFirst(''); - * // returns '' - * - * @function Phaser.Utils.String.UppercaseFirst - * @since 3.0.0 - * - * @param {string} str - The string to capitalize. - * - * @return {string} A new string, same as the first, but with the first letter capitalized. - */ -var UppercaseFirst = function (str) -{ - return str && str[0].toUpperCase() + str.slice(1); -}; - -module.exports = UppercaseFirst; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * Capitalizes the first letter of a string if there is one. + * @example + * UppercaseFirst('abc'); + * // returns 'Abc' + * @example + * UppercaseFirst('the happy family'); + * // returns 'The happy family' + * @example + * UppercaseFirst(''); + * // returns '' + * + * @function Phaser.Utils.String.UppercaseFirst + * @since 3.0.0 + * + * @param {string} str - The string to capitalize. + * + * @return {string} A new string, same as the first, but with the first letter capitalized. + */ +var UppercaseFirst = function (str) +{ + return str && str[0].toUpperCase() + str.slice(1); +}; + +module.exports = UppercaseFirst; diff --git a/src/utils/string/index.js b/src/utils/string/index.js index 94ed8e12f..8b7fbe2d4 100644 --- a/src/utils/string/index.js +++ b/src/utils/string/index.js @@ -1,19 +1,19 @@ -/** - * @author Richard Davey - * @copyright 2020 Photon Storm Ltd. - * @license {@link https://opensource.org/licenses/MIT|MIT License} - */ - -/** - * @namespace Phaser.Utils.String - */ - -module.exports = { - - Format: require('./Format'), - Pad: require('./Pad'), - Reverse: require('./Reverse'), - UppercaseFirst: require('./UppercaseFirst'), - UUID: require('./UUID') - -}; +/** + * @author Richard Davey + * @copyright 2020 Photon Storm Ltd. + * @license {@link https://opensource.org/licenses/MIT|MIT License} + */ + +/** + * @namespace Phaser.Utils.String + */ + +module.exports = { + + Format: require('./Format'), + Pad: require('./Pad'), + Reverse: require('./Reverse'), + UppercaseFirst: require('./UppercaseFirst'), + UUID: require('./UUID') + +}; diff --git a/types/SpineFile.d.ts b/types/SpineFile.d.ts index 1a06f8bb6..6c6e63617 100644 --- a/types/SpineFile.d.ts +++ b/types/SpineFile.d.ts @@ -1,18 +1,18 @@ -declare namespace Phaser.Loader.FileTypes { - interface SpineFileConfig { - key: string; - textureURL?: string; - textureExtension?: string; - textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - normalMap?: string; - atlasURL?: string; - atlasExtension?: string; - atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - } - - class SpineFile extends Phaser.Loader.MultiFile { - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Loader.FileTypes.SpineFileConfig, jsonURL: string | string[], atlasURL: string, preMultipliedAlpha: boolean, jsonXhrSettings: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings: Phaser.Types.Loader.XHRSettingsObject) - - addToCache(); - } -} +declare namespace Phaser.Loader.FileTypes { + interface SpineFileConfig { + key: string; + textureURL?: string; + textureExtension?: string; + textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + normalMap?: string; + atlasURL?: string; + atlasExtension?: string; + atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + } + + class SpineFile extends Phaser.Loader.MultiFile { + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Loader.FileTypes.SpineFileConfig, jsonURL: string | string[], atlasURL: string, preMultipliedAlpha: boolean, jsonXhrSettings: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings: Phaser.Types.Loader.XHRSettingsObject) + + addToCache(); + } +} diff --git a/types/SpineGameObject.d.ts b/types/SpineGameObject.d.ts index 90fe56476..529d50cee 100644 --- a/types/SpineGameObject.d.ts +++ b/types/SpineGameObject.d.ts @@ -1,125 +1,125 @@ -/// -/// - -declare class SpineGameObject extends Phaser.GameObjects.GameObject implements Omit, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - constructor(scene: Phaser.Scene, pluginManager: SpinePlugin, x: number, y: number, key?: string, animationName?: string, loop?: boolean); - - alpha: number; - angle: integer; - - readonly blendMode: number; - - blue: number; - bounds: any; - displayOriginX: number; - displayOriginY: number; - drawDebug: boolean; - depth: number; - displayWidth: number; - displayHeight: number; - flipX: boolean; - flipY: boolean; - green: number; - height: number; - plugin: SpinePlugin; - preMultipliedAlpha: boolean; - red: number; - root: spine.Bone; - rotation: number; - scale: number; - scaleX: number - scaleY: number - scrollFactorX: number; - scrollFactorY: number; - skeleton: spine.Skeleton; - skeletonData: spine.SkeletonData; - // @ts-ignore - spine.AnimationState significantly different than GameObject.state - state: spine.AnimationState; - stateData: spine.AnimationStateData; - timeScale: number; - visible: boolean; - x: number; - y: number; - z: number; - w: number; - width: number; - - addAnimation(trackIndex: integer, animationName: string, loop?: boolean, delay?: integer): spine.TrackEntry; - angleBoneToXY(bone: spine.Bone, worldX: number, worldY: number, offset?: number, minAngle?: number, maxAngle?: number): SpineGameObject; - clearTrack(trackIndex: integer): SpineGameObject; - clearTracks(): SpineGameObject; - findAnimation(animationName: string): spine.Animation; - findBone(boneName: string): spine.Bone; - findBoneIndex(boneName: string): number; - findEvent(eventDataName: string): spine.EventData; - findIkConstraint(constraintName: string): spine.IkConstraintData; - findPathConstraint(constraintName: string): spine.PathConstraintData; - findPathConstraintIndex(constraintName: string): number; - findSkin(skinName: string): spine.Skin; - findSlot(slotName: string): spine.Slot; - findSlotIndex(slotName: string): number; - findTransformConstraint(constraintName: string): spine.TransformConstraintData; - getAnimationList(): string[]; - getAttachment(slotIndex: integer, attachmentName: string): spine.Attachment; - getAttachmentByName(slotName: string, attachmentName: string): spine.Attachment; - getBoneList(): string[]; - getBounds(): any; - getCurrentAnimation(trackIndex?: integer): spine.Animation; - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - getParentRotation(): number; - getRootBone(): spine.Bone; - getSkinList(): string[]; - getSlotList(): string[]; - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - play(animationName: string, loop?: boolean, ignoreIfPlaying?: boolean): SpineGameObject; - - protected preUpdate(time: number, delta: number): void; - protected preDestroy(): void; - - refresh(): SpineGameObject; - resetFlip(): this; - setAlpha(value?: number): SpineGameObject; - setAngle(degrees?: number): this; - setAnimation(trackIndex: integer, animationName: string, loop?: boolean, ignoreIfPlaying?: boolean): spine.TrackEntry; - setAttachment(slotName: string, attachmentName: string): SpineGameObject; - setBonesToSetupPose(): SpineGameObject; - setColor(color?: integer, slotName?: string): SpineGameObject; - setDepth(value: integer): this; - setDisplaySize(width: number, height: number): this; - setEmptyAnimation(trackIndex: integer, mixDuration?: integer): spine.TrackEntry; - setFlipX(value: boolean): this; - setFlipY(value: boolean): this; - setFlip(x: boolean, y: boolean): this; - setMix(fromName: string, toName: string, duration?: number): SpineGameObject; - setOffset(offsetX?: number, offsetY?: number): SpineGameObject; - setPosition(x?: number, y?: number, z?: number, w?: number): this; - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - setRotation(radians?: number): this; - setScale(x: number, y?: number): this; - setScrollFactor(x: number, y?: number): this; - setSize(width?: number, height?: number, offsetX?: number, offsetY?: number): SpineGameObject; - setSkeleton(atlasDataKey: string, skeletonJSON: object, animationName?: string, loop?: boolean): SpineGameObject; - setSkeletonFromJSON(atlasDataKey: string, skeletonJSON: object, animationName?: string, loop?: boolean): SpineGameObject; - setSkin(newSkin: spine.Skin): SpineGameObject; - setSkinByName(skinName: string): SpineGameObject; - setSlotsToSetupPose(): SpineGameObject; - setToSetupPose(): SpineGameObject; - setVisible(value: boolean): this; - setX(value?: number): this; - setY(value?: number): this; - setZ(value?: number): this; - setW(value?: number): this; - toggleFlipX(): this; - toggleFlipY(): this; - updateSize(): SpineGameObject; - willRender(): boolean; -} - -declare interface SpineGameObjectConfig extends Phaser.Types.GameObjects.GameObjectConfig { - key?: string; - animationName?: string; - loop?: boolean; - skinName?: string; - slotName?: string; - attachmentName?: string; -} +/// +/// + +declare class SpineGameObject extends Phaser.GameObjects.GameObject implements Omit, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + constructor(scene: Phaser.Scene, pluginManager: SpinePlugin, x: number, y: number, key?: string, animationName?: string, loop?: boolean); + + alpha: number; + angle: integer; + + readonly blendMode: number; + + blue: number; + bounds: any; + displayOriginX: number; + displayOriginY: number; + drawDebug: boolean; + depth: number; + displayWidth: number; + displayHeight: number; + flipX: boolean; + flipY: boolean; + green: number; + height: number; + plugin: SpinePlugin; + preMultipliedAlpha: boolean; + red: number; + root: spine.Bone; + rotation: number; + scale: number; + scaleX: number + scaleY: number + scrollFactorX: number; + scrollFactorY: number; + skeleton: spine.Skeleton; + skeletonData: spine.SkeletonData; + // @ts-ignore - spine.AnimationState significantly different than GameObject.state + state: spine.AnimationState; + stateData: spine.AnimationStateData; + timeScale: number; + visible: boolean; + x: number; + y: number; + z: number; + w: number; + width: number; + + addAnimation(trackIndex: integer, animationName: string, loop?: boolean, delay?: integer): spine.TrackEntry; + angleBoneToXY(bone: spine.Bone, worldX: number, worldY: number, offset?: number, minAngle?: number, maxAngle?: number): SpineGameObject; + clearTrack(trackIndex: integer): SpineGameObject; + clearTracks(): SpineGameObject; + findAnimation(animationName: string): spine.Animation; + findBone(boneName: string): spine.Bone; + findBoneIndex(boneName: string): number; + findEvent(eventDataName: string): spine.EventData; + findIkConstraint(constraintName: string): spine.IkConstraintData; + findPathConstraint(constraintName: string): spine.PathConstraintData; + findPathConstraintIndex(constraintName: string): number; + findSkin(skinName: string): spine.Skin; + findSlot(slotName: string): spine.Slot; + findSlotIndex(slotName: string): number; + findTransformConstraint(constraintName: string): spine.TransformConstraintData; + getAnimationList(): string[]; + getAttachment(slotIndex: integer, attachmentName: string): spine.Attachment; + getAttachmentByName(slotName: string, attachmentName: string): spine.Attachment; + getBoneList(): string[]; + getBounds(): any; + getCurrentAnimation(trackIndex?: integer): spine.Animation; + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + getParentRotation(): number; + getRootBone(): spine.Bone; + getSkinList(): string[]; + getSlotList(): string[]; + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + play(animationName: string, loop?: boolean, ignoreIfPlaying?: boolean): SpineGameObject; + + protected preUpdate(time: number, delta: number): void; + protected preDestroy(): void; + + refresh(): SpineGameObject; + resetFlip(): this; + setAlpha(value?: number): SpineGameObject; + setAngle(degrees?: number): this; + setAnimation(trackIndex: integer, animationName: string, loop?: boolean, ignoreIfPlaying?: boolean): spine.TrackEntry; + setAttachment(slotName: string, attachmentName: string): SpineGameObject; + setBonesToSetupPose(): SpineGameObject; + setColor(color?: integer, slotName?: string): SpineGameObject; + setDepth(value: integer): this; + setDisplaySize(width: number, height: number): this; + setEmptyAnimation(trackIndex: integer, mixDuration?: integer): spine.TrackEntry; + setFlipX(value: boolean): this; + setFlipY(value: boolean): this; + setFlip(x: boolean, y: boolean): this; + setMix(fromName: string, toName: string, duration?: number): SpineGameObject; + setOffset(offsetX?: number, offsetY?: number): SpineGameObject; + setPosition(x?: number, y?: number, z?: number, w?: number): this; + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + setRotation(radians?: number): this; + setScale(x: number, y?: number): this; + setScrollFactor(x: number, y?: number): this; + setSize(width?: number, height?: number, offsetX?: number, offsetY?: number): SpineGameObject; + setSkeleton(atlasDataKey: string, skeletonJSON: object, animationName?: string, loop?: boolean): SpineGameObject; + setSkeletonFromJSON(atlasDataKey: string, skeletonJSON: object, animationName?: string, loop?: boolean): SpineGameObject; + setSkin(newSkin: spine.Skin): SpineGameObject; + setSkinByName(skinName: string): SpineGameObject; + setSlotsToSetupPose(): SpineGameObject; + setToSetupPose(): SpineGameObject; + setVisible(value: boolean): this; + setX(value?: number): this; + setY(value?: number): this; + setZ(value?: number): this; + setW(value?: number): this; + toggleFlipX(): this; + toggleFlipY(): this; + updateSize(): SpineGameObject; + willRender(): boolean; +} + +declare interface SpineGameObjectConfig extends Phaser.Types.GameObjects.GameObjectConfig { + key?: string; + animationName?: string; + loop?: boolean; + skinName?: string; + slotName?: string; + attachmentName?: string; +} diff --git a/types/SpinePlugin.d.ts b/types/SpinePlugin.d.ts index e65e578db..6c5122fc0 100644 --- a/types/SpinePlugin.d.ts +++ b/types/SpinePlugin.d.ts @@ -1,59 +1,59 @@ -/// -/// -/// - -declare namespace Phaser.Loader { - interface LoaderPlugin extends Phaser.Events.EventEmitter { - spine(key: string | Phaser.Loader.FileTypes.SpineFileConfig | Phaser.Loader.FileTypes.SpineFileConfig[], jsonURL: string, atlasURL: string | string[], preMultipliedAlpha?: boolean, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): LoaderPlugin; - } -} - -declare namespace Phaser.GameObjects { - interface GameObjectFactory { - spine(x: number, y: number, key?: string, aimationName?: string, loop?: boolean): SpineGameObject; - } - - interface GameObjectCreator { - spine(config: SpineGameObjectConfig, addToScene?: boolean): SpineGameObject; - } -} - -declare class SpinePlugin extends Phaser.Plugins.ScenePlugin { - constructor(scene: Phaser.Scene, pluginManager: Phaser.Plugins.PluginManager); - - readonly isWebGL: boolean; - - cache: Phaser.Cache.BaseCache; - spineTextures: Phaser.Cache.BaseCache; - json: Phaser.Cache.BaseCache; - textures: Phaser.Textures.TextureManager; - drawDebug: boolean; - gl: WebGLRenderingContext; - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - sceneRenderer: spine.webgl.SceneRenderer; - skeletonRenderer: spine.canvas.SkeletonRenderer | spine.webgl.SkeletonRenderer; - skeletonDebugRenderer: spine.webgl.SkeletonDebugRenderer; - - plugin: typeof spine; - - getAtlasCanvas(key: string): spine.TextureAtlas; - getAtlasWebGL(key: string): spine.TextureAtlas; - worldToLocal(x: number, y: number, skeleton: spine.Skeleton, bone?: spine.Bone): spine.Vector2; - getVector2(x: number, y: number): spine.Vector2; - getVector3(x: number, y: number, z: number): spine.Vector2; - setDebugBones(value?: boolean): SpinePlugin; - setDebugRegionAttachments(value?: boolean): SpinePlugin; - setDebugBoundingBoxes(value?: boolean): SpinePlugin; - setDebugMeshHull(value?: boolean): SpinePlugin; - setDebugMeshTriangles(value?: boolean): SpinePlugin; - setDebugPaths(value?: boolean): SpinePlugin; - setDebugSkeletonXY(value?: boolean): SpinePlugin; - setDebugClipping(value?: boolean): SpinePlugin; - setEffect(effect?: spine.VertexEffect): SpinePlugin; - createSkeleton(key: string, skeletonJSON?: object): any | null; - createAnimationState(skeleton: spine.Skeleton): any; - getBounds(skeleton: spine.Skeleton): any; - onResize(): void; - add(x: number, y: number, key?: string, animationName?: string, loop?: boolean): SpineGameObject; - make(config: SpineGameObjectConfig, addToScene?: boolean): SpineGameObject; -} +/// +/// +/// + +declare namespace Phaser.Loader { + interface LoaderPlugin extends Phaser.Events.EventEmitter { + spine(key: string | Phaser.Loader.FileTypes.SpineFileConfig | Phaser.Loader.FileTypes.SpineFileConfig[], jsonURL: string, atlasURL: string | string[], preMultipliedAlpha?: boolean, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): LoaderPlugin; + } +} + +declare namespace Phaser.GameObjects { + interface GameObjectFactory { + spine(x: number, y: number, key?: string, aimationName?: string, loop?: boolean): SpineGameObject; + } + + interface GameObjectCreator { + spine(config: SpineGameObjectConfig, addToScene?: boolean): SpineGameObject; + } +} + +declare class SpinePlugin extends Phaser.Plugins.ScenePlugin { + constructor(scene: Phaser.Scene, pluginManager: Phaser.Plugins.PluginManager); + + readonly isWebGL: boolean; + + cache: Phaser.Cache.BaseCache; + spineTextures: Phaser.Cache.BaseCache; + json: Phaser.Cache.BaseCache; + textures: Phaser.Textures.TextureManager; + drawDebug: boolean; + gl: WebGLRenderingContext; + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + sceneRenderer: spine.webgl.SceneRenderer; + skeletonRenderer: spine.canvas.SkeletonRenderer | spine.webgl.SkeletonRenderer; + skeletonDebugRenderer: spine.webgl.SkeletonDebugRenderer; + + plugin: typeof spine; + + getAtlasCanvas(key: string): spine.TextureAtlas; + getAtlasWebGL(key: string): spine.TextureAtlas; + worldToLocal(x: number, y: number, skeleton: spine.Skeleton, bone?: spine.Bone): spine.Vector2; + getVector2(x: number, y: number): spine.Vector2; + getVector3(x: number, y: number, z: number): spine.Vector2; + setDebugBones(value?: boolean): SpinePlugin; + setDebugRegionAttachments(value?: boolean): SpinePlugin; + setDebugBoundingBoxes(value?: boolean): SpinePlugin; + setDebugMeshHull(value?: boolean): SpinePlugin; + setDebugMeshTriangles(value?: boolean): SpinePlugin; + setDebugPaths(value?: boolean): SpinePlugin; + setDebugSkeletonXY(value?: boolean): SpinePlugin; + setDebugClipping(value?: boolean): SpinePlugin; + setEffect(effect?: spine.VertexEffect): SpinePlugin; + createSkeleton(key: string, skeletonJSON?: object): any | null; + createAnimationState(skeleton: spine.Skeleton): any; + getBounds(skeleton: spine.Skeleton): any; + onResize(): void; + add(x: number, y: number, key?: string, animationName?: string, loop?: boolean): SpineGameObject; + make(config: SpineGameObjectConfig, addToScene?: boolean): SpineGameObject; +} diff --git a/types/matter.d.ts b/types/matter.d.ts index 49e02eeb0..9cc28d429 100644 --- a/types/matter.d.ts +++ b/types/matter.d.ts @@ -1,5021 +1,5021 @@ -// Type definitions specifically for Matter.js as used by Phaser 3 -// -// Definitions by: Ivane Gegia , -// David Asmuth , -// Piotr Pietrzak , -// Richard Davey - -declare namespace MatterJS { - - // -------------------------------------------------------------- - // Interfaces - // -------------------------------------------------------------- - - interface IChamfer { - - radius?: number | Array; - quality?: number; - qualityMin?: number; - qualityMax?: number; - - } - - interface IChamferableBodyDefinition extends IBodyDefinition { - - chamfer?: IChamfer; - - } - - interface IBodyDefinition { - - /** - * A `Number` specifying the angle of the body, in radians. - * - * @property angle - * @type number - * @default 0 - */ - angle?: number; - - /** - * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). - * - * @readOnly - * @property angularSpeed - * @type number - * @default 0 - */ - angularSpeed?: number; - - /** - * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. - * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). - * - * @readOnly - * @property angularVelocity - * @type number - * @default 0 - */ - angularVelocity?: number; - - /** - * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. - * - * @property area - * @type string - * @default - */ - area?: number; - - /** - * An array of unique axis vectors (edge normals) used for collision detection. - * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. - * They are constantly updated by `Body.update` during the simulation. - * - * @property axes - * @type vector[] - */ - axes?: Array; - - /** - * A `Bounds` object that defines the AABB region for the body. - * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. - * - * @property bounds - * @type bounds - */ - bounds?: IBound; - - /** - * 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 - */ - density?: number; - - /** - * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. - * - * @property force - * @type vector - * @default { x: 0, y: 0 } - */ - force?: Vector; - - /** - * 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 - */ - friction?: number; - - /** - * A `Number` that defines the air friction of the body (air resistance). - * A value of `0` means the body will never slow as it moves through space. - * The higher the value, the faster a body slows when moving through space. - * The effects of the value are non-linear. - * - * @property frictionAir - * @type number - * @default 0.01 - */ - frictionAir?: number; - - /** - * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. - * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. - * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). - * - * @property inertia - * @type number - */ - inertia?: number; - - /** - * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). - * If you modify this value, you must also modify the `body.inertia` property. - * - * @property inverseInertia - * @type number - */ - inverseInertia?: number; - - /** - * A `Number` that defines the inverse mass of the body (`1 / mass`). - * If you modify this value, you must also modify the `body.mass` property. - * - * @property inverseMass - * @type number - */ - inverseMass?: number; - - /** - * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. - * - * @property isSensor - * @type boolean - * @default false - */ - isSensor?: boolean; - - /** - * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. - * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. - * - * @property isSleeping - * @type boolean - * @default false - */ - isSleeping?: boolean; - - /** - * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. - * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. - * - * @property isStatic - * @type boolean - * @default false - */ - isStatic?: boolean; - - /** - * An arbitrary `String` name to help the user identify and manage bodies. - * - * @property label - * @type string - * @default "Body" - */ - label?: string; - - /** - * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. - * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). - * - * @property mass - * @type number - */ - mass?: number; - - /** - * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. - * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. - * - * @readOnly - * @property motion - * @type number - * @default 0 - */ - motion?: number; - - /** - * A `Vector` that specifies the current world-space position of the body. - * - * @property position - * @type vector - */ - position?: Vector; - - /** - * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. - * - * @property render - * @type object - */ - render?: IBodyRenderOptions; - - /** - * 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 - */ - restitution?: number; - - /** - * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). - * - * @property sleepThreshold - * @type number - * @default 60 - */ - sleepThreshold?: number; - - /** - * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. - * Avoid changing this value unless you understand the purpose of `slop` in physics engines. - * The default should generally suffice, although very large bodies may require larger values for stable stacking. - * - * @property slop - * @type number - * @default 0.05 - */ - slop?: number; - - /** - * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). - * - * @readOnly - * @property speed - * @type number - * @default 0 - */ - speed?: number; - - /** - * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - * - * @property timeScale - * @type number - * @default 1 - */ - timeScale?: number; - - /** - * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. - * - * @property torque - * @type number - * @default 0 - */ - torque?: number; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "body" - */ - type?: string; - - /** - * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. - * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). - * - * @readOnly - * @property velocity - * @type vector - * @default { x: 0, y: 0 } - */ - velocity?: Vector; - - /** - * An array of `Vector` objects that specify the convex hull of the rigid body. - * These should be provided about the origin `(0, 0)`. E.g. - * - * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] - * - * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). - * The `Vector` objects are also augmented with additional properties required for efficient collision detection. - * - * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). - * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. - * - * @property vertices - * @type vector[] - */ - vertices?: Array; - - /** - * An array of bodies that make up this body. - * The first body in the array must always be a self reference to the current body instance. - * All bodies in the `parts` array together form a single rigid compound body. - * Parts are allowed to overlap, have gaps or holes or even form concave bodies. - * Parts themselves should never be added to a `World`, only the parent body should be. - * Use `Body.setParts` when setting parts to ensure correct updates of all properties. - * - * @property parts - * @type body[] - */ - parts?: Array; - - /** - * A self reference if the body is _not_ a part of another body. - * Otherwise this is a reference to the body that this is a part of. - * See `body.parts`. - * - * @property parent - * @type body - */ - parent?: BodyType; - - /** - * A `Number` that defines the static friction of the body (in the Coulomb friction model). - * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. - * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. - * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. - * - * @property frictionStatic - * @type number - * @default 0.5 - */ - frictionStatic?: number; - - /** - * An `Object` that specifies the collision filtering properties of this body. - * - * Collisions between two bodies will obey the following rules: - * - If the two bodies have the same non-zero value of `collisionFilter.group`, - * they will always collide if the value is positive, and they will never collide - * if the value is negative. - * - If the two bodies have different values of `collisionFilter.group` or if one - * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: - * - * Each body belongs to a collision category, given by `collisionFilter.category`. This - * value is used as a bit field and the category should have only one bit set, meaning that - * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 - * different collision categories available. - * - * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies - * the categories it collides with (the value is the bitwise AND value of all these categories). - * - * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's - * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` - * are both true. - * - * @property collisionFilter - * @type object - */ - collisionFilter?: ICollisionFilter; - - /** - * A reference to the Phaser Game Object this body belongs to, if any. - * - * @property gameObject - * @type Phaser.GameObjects.GameObject - */ - gameObject?: any; - - /** - * Scale the influence of World gravity when applied to this body. - * - * @property gravityScale - * @type vector - * @default { x: 1, y: 1 } - */ - gravityScale?: Vector; - - /** - * Will this Body ignore World gravity during the Engine update? - * - * @property ignoreGravity - * @type boolean - * @default false - */ - ignoreGravity?: boolean; - - /** - * Will this Body ignore Phaser Pointer input events? - * - * @property ignorePointer - * @type boolean - * @default false - */ - ignorePointer?: boolean; - - /** - * A callback that is invoked when this Body starts colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideCallback - * @type function - * @default null - */ - onCollideCallback?: Function; - - /** - * A callback that is invoked when this Body stops colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideEndCallback - * @type function - * @default null - */ - onCollideEndCallback?: Function; - - /** - * A callback that is invoked for the duration that this Body is colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideActiveCallback - * @type function - * @default null - */ - onCollideActiveCallback?: Function; - - /** - * A collision callback dictionary used by the `Body.setOnCollideWith` function. - * - * @property onCollideWith - * @type object - * @default null - */ - onCollideWith?: any; - - } - - interface IBodyRenderOptions { - - /** - * A flag that indicates if the body should be rendered. - * - * @property visible - * @type boolean - * @default true - */ - visible?: boolean; - - /** - * Sets the opacity. 1.0 is fully opaque. 0.0 is fully translucent. - * - * @property opacity - * @type number - * @default 1 - */ - opacity?: number; - - /** - * An `Object` that defines the sprite properties to use when rendering, if any. - * - * @property sprite - * @type object - */ - sprite?: IBodyRenderOptionsSprite; - - /** - * A hex color value that defines the fill color to use when rendering the body. - * - * @property fillColor - * @type number - */ - fillColor?: number; - - /** - * A value that defines the fill opacity to use when rendering the body. - * - * @property fillOpacity - * @type number - */ - fillOpacity?: number; - - /** - * A hex color value that defines the line color to use when rendering the body. - * - * @property lineColor - * @type number - */ - lineColor?: number; - - /** - * A value that defines the line opacity to use when rendering the body. - * - * @property lineOpacity - * @type number - */ - lineOpacity?: number; - - /** - * A `Number` that defines the line width to use when rendering the body outline. - * - * @property lineThickness - * @type number - */ - lineThickness?: number; - - } - - interface IBodyRenderOptionsSprite { - - /** - * A `Number` that defines the scaling in the x-axis for the sprite, if any. - * - * @property xOffset - * @type number - * @default 0 - */ - xOffset: number; - - /** - * A `Number` that defines the scaling in the y-axis for the sprite, if any. - * - * @property yOffset - * @type number - * @default 0 - */ - yOffset: number; - } - - interface IBound { - - min: { x: number, y: number } - max: { x: number, y: number } - - } - - interface ICompositeDefinition { - - /** - * An array of `Body` that are _direct_ children of this composite. - * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. - * - * @property bodies - * @type body[] - * @default [] - */ - bodies?: Array; - - /** - * An array of `Composite` that are _direct_ children of this composite. - * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. - * - * @property composites - * @type composite[] - * @default [] - */ - composites?: Array; - - /** - * An array of `Constraint` that are _direct_ children of this composite. - * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. - * - * @property constraints - * @type constraint[] - * @default [] - */ - constraints?: Array; - - /** - * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. - * - * @property id - * @type number - */ - id?: number; - - /** - * A flag that specifies whether the composite has been modified during the current step. - * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. - * If you need to change it manually, you should use the `Composite.setModified` method. - * - * @property isModified - * @type boolean - * @default false - */ - isModified?: boolean; - - /** - * An arbitrary `String` name to help the user identify and manage composites. - * - * @property label - * @type string - * @default "Composite" - */ - label?: string; - - /** - * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. - * - * @property parent - * @type composite - * @default null - */ - parent?: CompositeType; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "composite" - */ - type?: string; - - } - - interface IConstraintDefinition { - - /** - * The first possible `Body` that this constraint is attached to. - * - * @property bodyA - * @type body - * @default null - */ - bodyA?: IBodyDefinition; - - /** - * The second possible `Body` that this constraint is attached to. - * - * @property bodyB - * @type body - * @default null - */ - bodyB?: IBodyDefinition; - - /** - * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. - * - * @property id - * @type number - */ - id?: number; - - /** - * An arbitrary `String` name to help the user identify and manage bodies. - * - * @property label - * @type string - * @default "Constraint" - */ - label?: string; - - /** - * A `Number` that specifies the target resting length of the constraint. - * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * - * @property length - * @type number - */ - length?: number; - - /** - * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. - * - * @property pointA - * @type vector - * @default { x: 0, y: 0 } - */ - pointA?: Vector; - - /** - * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. - * - * @property pointB - * @type vector - * @default { x: 0, y: 0 } - */ - pointB?: Vector; - - /** - * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. - * - * @property render - * @type object - */ - render?: IConstraintRenderDefinition; - - /** - * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. - * A value of `1` means the constraint should be very stiff. - * A value of `0.2` means the constraint acts like a soft spring. - * - * @property stiffness - * @type number - * @default 1 - */ - stiffness?: number; - - /** - * 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 - */ - damping?: number; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "constraint" - */ - type?: string; - - } - - interface IConstraintRenderDefinition { - - /** - * A flag that indicates if the constraint should be rendered. - * - * @property visible - * @type boolean - * @default true - */ - visible?: boolean; - - /** - * The type of constraint. - * - * @property type - * @type string - * @default 'line' - */ - type?: string; - - /** - * A flag that indicates if the constraint anchors should be rendered. - * - * @property anchors - * @type boolean - * @default true - */ - anchors?: boolean; - - /** - * A hex color value that defines the line color to use when rendering the body. - * - * @property lineColor - * @type number - */ - lineColor?: number; - - /** - * A value that defines the line opacity to use when rendering the body. - * - * @property lineOpacity - * @type number - */ - lineOpacity?: number; - - /** - * A `Number` that defines the line width to use when rendering the body outline. - * - * @property lineThickness - * @type number - */ - lineThickness?: number; - - /** - * The size of the pins during rendering. - * - * @property pinSize - * @type number - */ - pinSize?: number; - - /** - * A hex color value that defines the color to use when rendering the anchors. - * - * @property anchorColor - * @type number - */ - anchorColor?: number; - - /** - * The size of the anchors during rendering. - * - * @property anchorSize - * @type number - */ - anchorSize?: number; - - } - - interface IEngineDefinition { - - /** - * An integer `Number` that specifies the number of position iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * - * @property positionIterations - * @type number - * @default 6 - */ - positionIterations?: number; - - /** - * An integer `Number` that specifies the number of velocity iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * - * @property velocityIterations - * @type number - * @default 4 - */ - velocityIterations?: number; - - /** - * An integer `Number` that specifies the number of constraint iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * The default value of `2` is usually very adequate. - * - * @property constraintIterations - * @type number - * @default 2 - */ - constraintIterations?: number; - - /** - * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. - * Sleeping can improve stability and performance, but often at the expense of accuracy. - * - * @property enableSleeping - * @type boolean - * @default false - */ - enableSleeping?: boolean; - - /** - * An `Object` containing properties regarding the timing systems of the engine. - * - * @property timing - * @type object - */ - timing?: IEngineTimingOptions; - - /** - * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. - * - * @property broadphase - * @type grid - * @default a Matter.Grid instance - */ - grid?: Grid; - - /** - * A `World` composite object that will contain all simulated bodies and constraints. - * - * @property world - * @type world - * @default a Matter.World instance - */ - world?: World; - - } - - interface IEngineTimingOptions { - - /** - * A `Number` that specifies the global scaling factor of time for all bodies. - * A value of `0` freezes the simulation. - * A value of `0.1` gives a slow-motion effect. - * A value of `1.2` gives a speed-up effect. - * - * @property timing.timeScale - * @type number - * @default 1 - */ - timeScale: number; - - /** - * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. - * It is incremented on every `Engine.update` by the given `delta` argument. - * - * @property timing.timestamp - * @type number - * @default 0 - */ - timestamp: number; - - } - - interface IMouseConstraintDefinition { - - /** - * The `Constraint` object that is used to move the body during interaction. - * - * @property constraint - * @type constraint - */ - constraint?: ConstraintType; - - /** - * An `Object` that specifies the collision filter properties. - * The collision filter allows the user to define which types of body this mouse constraint can interact with. - * See `body.collisionFilter` for more information. - * - * @property collisionFilter - * @type object - */ - collisionFilter?: ICollisionFilter; - - /** - * The `Body` that is currently being moved by the user, or `null` if no body. - * - * @property body - * @type body - * @default null - */ - body?: BodyType; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "constraint" - */ - type?: string; - - } - - interface IGridDefinition {} - - interface IPair { - - id: number; - bodyA: Body; - bodyB: Body; - contacts: any; - activeContacts: any; - separation: number; - isActive: boolean; - timeCreated: number; - timeUpdated: number, - inverseMass: number; - friction: number; - frictionStatic: number; - restitution: number; - slop: number; - - } - - interface ICollisionData { - - collided: boolean; - bodyA: Body; - bodyB: Body; - axisBody: Body; - axisNumber: number; - depth: number; - parentA: Body; - parentB: Body; - normal: Vector; - tangent: Vector; - penetration: Vector; - supports: Vector[]; - inverseMass: number; - friction: number; - frictionStatic: number; - restitution: number; - slop: number; - - } - - interface ICollisionPair { - - id: string; - bodyA: Body; - bodyB: Body; - activeContacts: Vector[]; - separation: number; - isActive: boolean; - confirmedActive: boolean; - isSensor: boolean; - timeCreated: number; - timeUpdated: number; - collision: ICollisionData; - inverseMass: number; - friction: number; - frictionStatic: number; - restitution: number; - slop: number; - - } - - interface ICollisionFilter { - - category: number; - mask: number; - group: number; - - } - - interface IRunnerOptions { - - /** - * A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable). - * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). - * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). - * - * @property isFixed - * @type boolean - * @default false - */ - isFixed?: boolean; - - /** - * A `Number` that specifies the time step between updates in milliseconds. - * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. - * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. - * - * @property delta - * @type number - * @default 1000 / 60 - */ - delta?: number; - } - - interface IWorldDefinition extends ICompositeDefinition { - - gravity?: Gravity; - bounds?: IBound; - - } - - interface Gravity extends Vector { - - scale: number; - - } - - interface IEvent { - - /** - * The name of the event - */ - name: string; - - /** - * The source object of the event - */ - source: T; - - } - - interface IEventComposite extends IEvent { - - /** - * EventObjects (may be a single body, constraint, composite or a mixed array of these) - */ - object: any; - - } - - interface IEventTimestamped extends IEvent { - - /** - * The engine.timing.timestamp of the event - */ - timestamp: number; - - } - - interface IEventCollision extends IEventTimestamped { - - /** - * The collision pair - */ - pairs: Array; - - } - - // -------------------------------------------------------------- - // Types - // -------------------------------------------------------------- - - type CompositeType = { - - /** - * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. - * - * @property id - * @type number - */ - id: number; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "composite" - */ - type: string; - - /** - * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. - * - * @property parent - * @type composite - * @default null - */ - parent?: CompositeType; - - /** - * A flag that specifies whether the composite has been modified during the current step. - * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. - * If you need to change it manually, you should use the `Composite.setModified` method. - * - * @property isModified - * @type boolean - * @default false - */ - isModified: boolean; - - /** - * An array of `Body` that are _direct_ children of this composite. - * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. - * - * @property bodies - * @type body[] - * @default [] - */ - bodies: Array; - - /** - * An array of `Constraint` that are _direct_ children of this composite. - * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. - * - * @property constraints - * @type constraint[] - * @default [] - */ - constraints: Array; - - /** - * An array of `Composite` that are _direct_ children of this composite. - * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. - * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. - * - * @property composites - * @type composite[] - * @default [] - */ - composites: Array; - - /** - * An arbitrary `String` name to help the user identify and manage composites. - * - * @property label - * @type string - * @default "Composite" - */ - label: string; - - /** - * An object reserved for storing plugin-specific properties. - * - * @property plugin - * @type {} - */ - plugin: any; - - } - - type ConstraintType = { - - /** - * The first possible `Body` that this constraint is attached to. - * - * @property bodyA - * @type body - * @default null - */ - bodyA?: BodyType; - - /** - * The second possible `Body` that this constraint is attached to. - * - * @property bodyB - * @type body - * @default null - */ - bodyB?: BodyType; - - /** - * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. - * - * @property pointA - * @type vector - * @default { x: 0, y: 0 } - */ - pointA: Vector; - - /** - * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. - * - * @property pointB - * @type vector - * @default { x: 0, y: 0 } - */ - pointB: Vector; - - /** - * A `Number` that specifies the target resting length of the constraint. - * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * - * @property length - * @type number - */ - length: number; - - /** - * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. - * - * @property id - * @type number - */ - id: number; - - /** - * An arbitrary `String` name to help the user identify and manage bodies. - * - * @property label - * @type string - * @default "Constraint" - */ - label: string; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "constraint" - * @readOnly - */ - type: string; - - /** - * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. - * A value of `1` means the constraint should be very stiff. - * A value of `0.2` means the constraint acts like a soft spring. - * - * @property stiffness - * @type number - * @default 1 - */ - stiffness: number; - - /** - * 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 - */ - damping: number; - - /** - * A `Number` that specifies the angular stiffness of the constraint. - * - * @property angularStiffness - * @type number - * @default 0 - */ - angularStiffness: number; - - /** - * Either the angle of BodyA, or a config value. - * - * @property angleA - * @type number - * @default 0 - */ - angleA: number; - - /** - * Either the angle of BodyB, or a config value. - * - * @property angleB - * @type number - * @default 0 - */ - angleB: number; - - /** - * An object reserved for storing plugin-specific properties. - * - * @property plugin - * @type {} - */ - plugin: any; - - /** - * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. - * - * @property render - * @type object - */ - render: IConstraintRenderDefinition; - - }; - - type BodyType = { - - /** - * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`. - * - * @property id - * @type number - */ - id: number; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "body" - * @readOnly - */ - type: string; - - /** - * An arbitrary `String` name to help the user identify and manage bodies. - * - * @property label - * @type string - * @default "Body" - */ - label: string; - - /** - * An array of bodies that make up this body. - * The first body in the array must always be a self reference to the current body instance. - * All bodies in the `parts` array together form a single rigid compound body. - * Parts are allowed to overlap, have gaps or holes or even form concave bodies. - * Parts themselves should never be added to a `World`, only the parent body should be. - * Use `Body.setParts` when setting parts to ensure correct updates of all properties. - * - * @property parts - * @type body[] - */ - parts: BodyType[]; - - /** - * An object reserved for storing plugin-specific properties. - * - * @property plugin - * @type {} - */ - plugin: any; - - /** - * A `Number` specifying the angle of the body, in radians. - * - * @property angle - * @type number - * @default 0 - */ - angle: number; - - /** - * An array of `Vector` objects that specify the convex hull of the rigid body. - * These should be provided about the origin `(0, 0)`. E.g. - * - * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] - * - * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). - * The `Vector` objects are also augmented with additional properties required for efficient collision detection. - * - * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). - * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. - * - * @property vertices - * @type vector[] - */ - vertices?: Vector[]; - - /** - * A `Vector` that specifies the current world-space position of the body. - * - * @property position - * @type vector - * @default { x: 0, y: 0 } - */ - position: Vector; - - /** - * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. - * - * @property force - * @type vector - * @default { x: 0, y: 0 } - */ - force: Vector; - - /** - * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. - * - * @property torque - * @type number - * @default 0 - */ - torque: number; - - /** - * A `Vector` that specifies the position impulse. - * - * @property positionImpulse - * @type vector - * @default { x: 0, y: 0 } - */ - positionImpulse: Vector; - - /** - * A `Vector` that specifies the previous position impulse. - * - * @property previousPositionImpulse - * @type vector - * @default { x: 0, y: 0 } - */ - previousPositionImpulse: Vector; - - /** - * A `Vector` that specifies the constraint impulse. - * - * @property constraintImpulse - * @type vector - * @default { x: 0, y: 0 } - */ - constraintImpulse: Vector; - - /** - * The total number of contacts. - * - * @property totalContacts - * @type number - * @default 0 - */ - totalContacts: number; - - /** - * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). - * - * @readOnly - * @property speed - * @type number - * @default 0 - */ - speed: number; - - /** - * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). - * - * @readOnly - * @property angularSpeed - * @type number - * @default 0 - */ - angularSpeed: number; - - /** - * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. - * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). - * - * @readOnly - * @property velocity - * @type vector - * @default { x: 0, y: 0 } - */ - velocity: Vector; - - /** - * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. - * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). - * - * @readOnly - * @property angularVelocity - * @type number - * @default 0 - */ - angularVelocity: number; - - /** - * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. - * - * @property isSensor - * @type boolean - * @default false - */ - isSensor: boolean; - - /** - * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. - * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. - * - * @property isStatic - * @type boolean - * @default false - */ - isStatic: boolean; - - /** - * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. - * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. - * - * @property isSleeping - * @type boolean - * @default false - */ - isSleeping: boolean; - - /** - * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. - * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. - * - * @readOnly - * @property motion - * @type number - * @default 0 - */ - motion: number; - - /** - * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). - * - * @property sleepThreshold - * @type number - * @default 60 - */ - sleepThreshold: number; - - /** - * 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 - */ - density: number; - - /** - * 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 - */ - restitution: number; - - /** - * 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 - */ - friction: number; - - /** - * A `Number` that defines the static friction of the body (in the Coulomb friction model). - * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. - * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. - * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. - * - * @property frictionStatic - * @type number - * @default 0.5 - */ - frictionStatic: number; - - /** - * A `Number` that defines the air friction of the body (air resistance). - * A value of `0` means the body will never slow as it moves through space. - * The higher the value, the faster a body slows when moving through space. - * The effects of the value are non-linear. - * - * @property frictionAir - * @type number - * @default 0.01 - */ - frictionAir: number; - - /** - * An `Object` that specifies the collision filtering properties of this body. - * - * Collisions between two bodies will obey the following rules: - * - If the two bodies have the same non-zero value of `collisionFilter.group`, - * they will always collide if the value is positive, and they will never collide - * if the value is negative. - * - If the two bodies have different values of `collisionFilter.group` or if one - * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: - * - * Each body belongs to a collision category, given by `collisionFilter.category`. This - * value is used as a bit field and the category should have only one bit set, meaning that - * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 - * different collision categories available. - * - * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies - * the categories it collides with (the value is the bitwise AND value of all these categories). - * - * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's - * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` - * are both true. - * - * @property collisionFilter - * @type object - */ - collisionFilter: ICollisionFilter; - - /** - * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. - * Avoid changing this value unless you understand the purpose of `slop` in physics engines. - * The default should generally suffice, although very large bodies may require larger values for stable stacking. - * - * @property slop - * @type number - * @default 0.05 - */ - slop: number; - - /** - * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - * - * @property timeScale - * @type number - * @default 1 - */ - timeScale: number; - - /** - * Holds Body event handlers. - * - * @property events - * @type any - */ - events?: any; - - /** - * A `Bounds` object that defines the AABB region for the body. - * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. - * - * @property bounds - * @type bounds - */ - bounds: IBound; - - /** - * A Chamfer object, if this Body has them. - * - * @property chamfer - * @type any - */ - chamfer?: IChamfer; - - /** - * The radius of this Body, if it's a circle. - * - * @property circleRadius - * @type number - * @default 0 - */ - circleRadius: number; - - /** - * A `Vector` that specifies the previous position. - * - * @property positionPrev - * @type vector - * @default { x: 0, y: 0 } - */ - positionPrev: Vector; - - /** - * The previous angle. - * - * @property anglePrev - * @type number - * @default 0 - */ - anglePrev: number; - - /** - * A self reference if the body is _not_ a part of another body. - * Otherwise this is a reference to the body that this is a part of. - * See `body.parts`. - * - * @property parent - * @type body - */ - parent: BodyType; - - /** - * An array of unique axis vectors (edge normals) used for collision detection. - * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. - * They are constantly updated by `Body.update` during the simulation. - * - * @property axes - * @type vector[] - */ - axes?: Array; - - /** - * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. - * - * @property area - * @type number - * @default - */ - area: number; - - /** - * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. - * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). - * - * @property mass - * @type number - */ - mass: number; - - /** - * A `Number` that defines the inverse mass of the body (`1 / mass`). - * If you modify this value, you must also modify the `body.mass` property. - * - * @property inverseMass - * @type number - */ - inverseMass: number; - - /** - * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. - * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. - * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). - * - * @property inertia - * @type number - */ - inertia: number; - - /** - * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). - * If you modify this value, you must also modify the `body.inertia` property. - * - * @property inverseInertia - * @type number - */ - inverseInertia: number; - - /** - * Holds the original friction, mass, etc values from when this Body was made static. - * - * @property _original - * @type any - */ - _original: any; - - /** - * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. - * - * @property render - * @type object - */ - render: IBodyRenderOptions; - - /** - * A reference to the Phaser Game Object this body belongs to, if any. - * - * @property gameObject - * @type Phaser.GameObjects.GameObject - */ - gameObject?: any; - - /** - * The scale of the Body. - * - * @property scale - * @readonly - * @type vector - * @default { x: 1, y: 1 } - */ - scale: Vector; - - /** - * The center of mass of the Body. - * - * @property centerOfMass - * @type vector - * @default { x: 0, y: 0 } - */ - centerOfMass: Vector; - - /** - * The center of the body in pixel values. - * Used by Phaser for texture aligment. - * - * @property centerOffset - * @type vector - * @default { x: 0, y: 0 } - */ - centerOffset: Vector; - - /** - * Scale the influence of World gravity when applied to this body. - * - * @property gravityScale - * @type vector - * @default { x: 1, y: 1 } - */ - gravityScale: Vector; - - /** - * Will this Body ignore World gravity during the Engine update? - * - * @property ignoreGravity - * @type boolean - * @default false - */ - ignoreGravity: boolean; - - /** - * Will this Body ignore Phaser Pointer input events? - * - * @property ignorePointer - * @type boolean - * @default false - */ - ignorePointer: boolean; - - /** - * A callback that is invoked when this Body starts colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideCallback - * @type function - * @default null - */ - onCollideCallback?: Function; - - /** - * A callback that is invoked when this Body stops colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideEndCallback - * @type function - * @default null - */ - onCollideEndCallback?: Function; - - /** - * A callback that is invoked for the duration that this Body is colliding with any other Body. - * - * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - * - * @property onCollideActiveCallback - * @type function - * @default null - */ - onCollideActiveCallback?: Function; - - /** - * A collision callback dictionary used by the `Body.setOnCollideWith` function. - * - * @property onCollideWith - * @type object - * @default null - */ - onCollideWith?: any; - - /** - * Sets the onCollideWith callback. - * - * @property setOnCollideWith - * @type Function - */ - setOnCollideWith: (body: BodyType, callback: Function) => BodyType; - - }; - - // -------------------------------------------------------------- - // Modules - // -------------------------------------------------------------- - - /** - * Installs the given plugins on the `Matter` namespace. - * This is a short-hand for `Plugin.use`, see it for more information. - * Call this function once at the start of your code, with all of the plugins you wish to install as arguments. - * Avoid calling this function multiple times unless you intend to manually control installation order. - * @method use - * @param ...plugin {Function} The plugin(s) to install on `base` (multi-argument). - */ - function use (...plugins: (Plugin | string)[]): void; - - /** - * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. - * - * @class Axes - */ - class Axes { - - /** - * Creates a new set of axes from the given vertices. - * @method fromVertices - * @param {vertices} vertices - * @return {axes} A new axes from the given vertices - */ - static fromVertices (vertices: Array): Array; - - /** - * Rotates a set of axes by the given angle. - * @method rotate - * @param {axes} axes - * @param {number} angle - */ - static rotate (axes: Array, angle: number): void; - - } - - class AxesFactory { - - /** - * Creates a new set of axes from the given vertices. - * @method fromVertices - * @param {vertices} vertices - * @return {axes} A new axes from the given vertices - */ - fromVertices (vertices: Array): Array; - - /** - * Rotates a set of axes by the given angle. - * @method rotate - * @param {axes} axes - * @param {number} angle - */ - rotate (axes: Array, angle: number): void; - - } - - /** - * 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 { - - /** - * Creates a new rigid body model with a circle hull. - * The options parameter is an object that specifies any 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 circle - * @param {number} x - * @param {number} y - * @param {number} radius - * @param {object} [options] - * @param {number} [maxSides] - * @return {body} A new circle body - */ - static circle (x: number, y: number, radius: number, options?: IBodyDefinition, maxSides?: number): BodyType; - - /** - * Creates a new rigid body model with a regular polygon hull with the given number of sides. - * The options parameter is an object that specifies any 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 polygon - * @param {number} x - * @param {number} y - * @param {number} sides - * @param {number} radius - * @param {object} [options] - * @return {body} A new regular polygon body - */ - static polygon (x: number, y: number, sides: number, radius: number, options?: IChamferableBodyDefinition): BodyType; - - /** - * Creates a new rigid body model with a rectangle hull. - * The options parameter is an object that specifies any 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 rectangle - * @param {number} x - * @param {number} y - * @param {number} width - * @param {number} height - * @param {object} [options] - * @return {body} A new rectangle body - */ - static rectangle (x: number, y: number, width: number, height: number, options?: IChamferableBodyDefinition): BodyType; - - /** - * Creates a new rigid body model with a trapezoid hull. - * The options parameter is an object that specifies any 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 trapezoid - * @param {number} x - * @param {number} y - * @param {number} width - * @param {number} height - * @param {number} slope - * @param {object} [options] - * @return {body} A new trapezoid body - */ - static trapezoid (x: number, y: number, width: number, height: number, slope: number, options?: IChamferableBodyDefinition): BodyType; - - /** - * Creates a body using the supplied vertices (or an array containing multiple sets of vertices). - * If the vertices are convex, they will pass through as supplied. - * Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available. - * Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail). - * By default the decomposition will discard collinear edges (to improve performance). - * It can also optionally discard any parts that have an area less than `minimumArea`. - * If the vertices can not be decomposed, the result will fall back to using the convex hull. - * The options parameter is an object that 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 [[vector]] vertexSets - * @param {object} [options] - * @param {bool} [flagInternal=false] - * @param {number} [removeCollinear=0.01] - * @param {number} [minimumArea=10] - * @return {body} - */ - static fromVertices (x: number, y: number, vertexSets: Array>, options?: IBodyDefinition, flagInternal?: boolean, removeCollinear?: number, minimumArea?: number): BodyType; - } - - class BodiesFactory { - - /** - * Creates a new rigid body model with a circle hull. - * The options parameter is an object that specifies any 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 circle - * @param {number} x - * @param {number} y - * @param {number} radius - * @param {object} [options] - * @param {number} [maxSides] - * @return {body} A new circle body - */ - circle (x: number, y: number, radius: number, options?: IBodyDefinition, maxSides?: number): BodyType; - - /** - * Creates a new rigid body model with a regular polygon hull with the given number of sides. - * The options parameter is an object that specifies any 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 polygon - * @param {number} x - * @param {number} y - * @param {number} sides - * @param {number} radius - * @param {object} [options] - * @return {body} A new regular polygon body - */ - polygon (x: number, y: number, sides: number, radius: number, options?: IChamferableBodyDefinition): BodyType; - - /** - * Creates a new rigid body model with a rectangle hull. - * The options parameter is an object that specifies any 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 rectangle - * @param {number} x - * @param {number} y - * @param {number} width - * @param {number} height - * @param {object} [options] - * @return {body} A new rectangle body - */ - rectangle (x: number, y: number, width: number, height: number, options?: IChamferableBodyDefinition): BodyType; - - /** - * Creates a new rigid body model with a trapezoid hull. - * The options parameter is an object that specifies any 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 trapezoid - * @param {number} x - * @param {number} y - * @param {number} width - * @param {number} height - * @param {number} slope - * @param {object} [options] - * @return {body} A new trapezoid body - */ - trapezoid (x: number, y: number, width: number, height: number, slope: number, options?: IChamferableBodyDefinition): BodyType; - - /** - * Creates a body using the supplied vertices (or an array containing multiple sets of vertices). - * If the vertices are convex, they will pass through as supplied. - * Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available. - * Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail). - * By default the decomposition will discard collinear edges (to improve performance). - * It can also optionally discard any parts that have an area less than `minimumArea`. - * If the vertices can not be decomposed, the result will fall back to using the convex hull. - * The options parameter is an object that 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 [[vector]] vertexSets - * @param {object} [options] - * @param {bool} [flagInternal=false] - * @param {number} [removeCollinear=0.01] - * @param {number} [minimumArea=10] - * @return {body} - */ - fromVertices (x: number, y: number, vertexSets: Array>, options?: IBodyDefinition, flagInternal?: boolean, removeCollinear?: number, minimumArea?: number): BodyType; - } - - /** - * 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 - */ - class Body { - - /** - * Applies a force to a body from a given world-space position, including resulting torque. - * @method applyForce - * @param {body} body - * @param {vector} position - * @param {vector} force - */ - static applyForce (body: BodyType, position: Vector, force: Vector): void; - - /** - * 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. - * See the properties section below for detailed information on what you can pass via the `options` object. - * @method create - * @param {} options - * @return {body} body - */ - static create (options: IChamferableBodyDefinition): Body; - - /** - * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. - * @method rotate - * @param {body} body - * @param {number} rotation - */ - static rotate (body: BodyType, rotation: number): void; - - /** - * Returns the next unique group index for which bodies will collide. - * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. - * See `body.collisionFilter` for more information. - * @method nextGroup - * @param {bool} [isNonColliding=false] - * @return {Number} Unique group index - */ - static nextGroup (isNonColliding: boolean): number; - - /** - * Returns the next unique category bitfield (starting after the initial default category `0x0001`). - * There are 32 available. See `body.collisionFilter` for more information. - * @method nextCategory - * @return {Number} Unique category bitfield - */ - static nextCategory (): number; - - /** - * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. - * Prefer to use the actual setter functions in performance critical situations. - * @method set - * @param {body} body - * @param {} settings A property name (or map of properties and values) to set on the body. - * @param {} value The value to set if `settings` is a single property name. - */ - static set (body: BodyType, settings: any, value?: any): void; - - /** - * Sets the mass of the body. Inverse mass and density are automatically updated to reflect the change. - * @method setMass - * @param {body} body - * @param {number} mass - */ - static setMass (body: BodyType, mass: number): void; - - /** - * Sets the density of the body. Mass is automatically updated to reflect the change. - * @method setDensity - * @param {body} body - * @param {number} density - */ - static setDensity (body: BodyType, density: number): void; - - /** - * Sets the moment of inertia (i.e. second moment of area) of the body of the body. - * Inverse inertia is automatically updated to reflect the change. Mass is not changed. - * @method setInertia - * @param {body} body - * @param {number} inertia - */ - static setInertia (body: BodyType, inertia: number): void; - - /** - * 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 - */ - static setVertices (body: BodyType, vertices: Array): void; - - /** - * Sets the parts of the `body` and updates mass, inertia and centroid. - * Each part will have its parent set to `body`. - * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` - * Note that this method will ensure that the first part in `body.parts` will always be the `body`. - * @method setParts - * @param {body} body - * @param [body] parts - * @param {bool} [autoHull=true] - */ - static setParts (body: BodyType, parts: BodyType[], autoHull?: boolean): void; - - /** - * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. - * @method setPosition - * @param {body} body - * @param {vector} position - */ - static setPosition (body: BodyType, position: Vector): void; - - /** - * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. - * @method setAngle - * @param {body} body - * @param {number} angle - */ - static setAngle (body: BodyType, angle: number): void; - - /** - * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. - * @method setVelocity - * @param {body} body - * @param {vector} velocity - */ - static setVelocity (body: BodyType, velocity: Vector): void; - - /** - * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. - * @method setAngularVelocity - * @param {body} body - * @param {number} velocity - */ - static setAngularVelocity (body: BodyType, velocity: number): void; - - /** - * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. - * @method setStatic - * @param {body} body - * @param {bool} isStatic - */ - static setStatic (body: BodyType, isStatic: boolean): void; - - /** - * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). - * @method scale - * @param {body} body - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} [point] - */ - static scale (body: BodyType, scaleX: number, scaleY: number, point?: Vector): void; - - /** - * Moves a body by a given vector relative to its current position, without imparting any velocity. - * @method translate - * @param {body} body - * @param {vector} translation - */ - static translate (body: BodyType, translation: Vector): void; - - /** - * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. - * @method update - * @param {body} body - * @param {number} deltaTime - * @param {number} timeScale - * @param {number} correction - */ - static update (body: BodyType, deltaTime: number, timeScale: number, correction: number): void; - - } - - class BodyFactory { - - /** - * Applies a force to a body from a given world-space position, including resulting torque. - * @method applyForce - * @param {body} body - * @param {vector} position - * @param {vector} force - */ - applyForce (body: BodyType, position: Vector, force: Vector): void; - - /** - * 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. - * See the properties section below for detailed information on what you can pass via the `options` object. - * @method create - * @param {} options - * @return {body} body - */ - create (options: IChamferableBodyDefinition): BodyType; - - /** - * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. - * @method rotate - * @param {body} body - * @param {number} rotation - */ - rotate (body: BodyType, rotation: number): void; - - /** - * Returns the next unique group index for which bodies will collide. - * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. - * See `body.collisionFilter` for more information. - * @method nextGroup - * @param {bool} [isNonColliding=false] - * @return {Number} Unique group index - */ - nextGroup (isNonColliding: boolean): number; - - /** - * Returns the next unique category bitfield (starting after the initial default category `0x0001`). - * There are 32 available. See `body.collisionFilter` for more information. - * @method nextCategory - * @return {Number} Unique category bitfield - */ - nextCategory (): number; - - /** - * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. - * Prefer to use the actual setter functions in performance critical situations. - * @method set - * @param {body} body - * @param {} settings A property name (or map of properties and values) to set on the body. - * @param {} value The value to set if `settings` is a single property name. - */ - set (body: BodyType, settings: any, value?: any): void; - - /** - * Sets the mass of the body. Inverse mass and density are automatically updated to reflect the change. - * @method setMass - * @param {body} body - * @param {number} mass - */ - setMass (body: BodyType, mass: number): void; - - /** - * Sets the density of the body. Mass is automatically updated to reflect the change. - * @method setDensity - * @param {body} body - * @param {number} density - */ - setDensity (body: BodyType, density: number): void; - - /** - * Sets the moment of inertia (i.e. second moment of area) of the body of the body. - * Inverse inertia is automatically updated to reflect the change. Mass is not changed. - * @method setInertia - * @param {body} body - * @param {number} inertia - */ - setInertia (body: BodyType, inertia: number): void; - - /** - * 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 - */ - setVertices (body: BodyType, vertices: Array): void; - - /** - * Sets the parts of the `body` and updates mass, inertia and centroid. - * Each part will have its parent set to `body`. - * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` - * Note that this method will ensure that the first part in `body.parts` will always be the `body`. - * @method setParts - * @param {body} body - * @param [body] parts - * @param {bool} [autoHull=true] - */ - setParts (body: BodyType, parts: BodyType[], autoHull?: boolean): void; - - /** - * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. - * @method setPosition - * @param {body} body - * @param {vector} position - */ - setPosition (body: BodyType, position: Vector): void; - - /** - * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. - * @method setAngle - * @param {body} body - * @param {number} angle - */ - setAngle (body: BodyType, angle: number): void; - - /** - * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. - * @method setVelocity - * @param {body} body - * @param {vector} velocity - */ - setVelocity (body: BodyType, velocity: Vector): void; - - /** - * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. - * @method setAngularVelocity - * @param {body} body - * @param {number} velocity - */ - setAngularVelocity (body: BodyType, velocity: number): void; - - /** - * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. - * @method setStatic - * @param {body} body - * @param {bool} isStatic - */ - setStatic (body: BodyType, isStatic: boolean): void; - - /** - * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). - * @method scale - * @param {body} body - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} [point] - */ - scale (body: BodyType, scaleX: number, scaleY: number, point?: Vector): void; - - /** - * Moves a body by a given vector relative to its current position, without imparting any velocity. - * @method translate - * @param {body} body - * @param {vector} translation - */ - translate (body: BodyType, translation: Vector): void; - - /** - * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. - * @method update - * @param {body} body - * @param {number} deltaTime - * @param {number} timeScale - * @param {number} correction - */ - update (body: BodyType, deltaTime: number, timeScale: number, correction: number): void; - - } - - /** - * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). - * - * @class Bounds - */ - class Bounds { - - /** - * Creates a new axis-aligned bounding box (AABB) for the given vertices. - * @method create - * @param {vertices} vertices - * @return {IBound} A new bounds object - */ - static create (vertices: Vertices): IBound; - - /** - * Updates bounds using the given vertices and extends the bounds given a velocity. - * @method update - * @param {IBound} bounds - * @param {vertices} vertices - * @param {vector} velocity - */ - static update (bounds: IBound, vertices: Vertices, velocity: Vector): void; - - /** - * Returns true if the bounds contains the given point. - * @method contains - * @param {IBound} bounds - * @param {vector} point - * @return {boolean} True if the bounds contain the point, otherwise false - */ - static contains (bounds: IBound, point: Vector): boolean; - - /** - * Returns true if the two bounds intersect. - * @method overlaps - * @param {IBound} boundsA - * @param {IBound} boundsB - * @return {boolean} True if the bounds overlap, otherwise false - */ - static overlaps (boundsA: IBound, boundsB: IBound): boolean; - - /** - * Translates the bounds by the given vector. - * @method translate - * @param {IBound} bounds - * @param {vector} vector - */ - static translate (bounds: IBound, vector: Vector): void; - - /** - * Shifts the bounds to the given position. - * @method shift - * @param {IBound} bounds - * @param {vector} position - */ - static shift (bounds: IBound, position: Vector): void; - - } - - class BoundsFactory { - - /** - * Creates a new axis-aligned bounding box (AABB) for the given vertices. - * @method create - * @param {vertices} vertices - * @return {IBound} A new bounds object - */ - create (vertices: Vertices): IBound; - - /** - * Updates bounds using the given vertices and extends the bounds given a velocity. - * @method update - * @param {IBound} bounds - * @param {vertices} vertices - * @param {vector} velocity - */ - update (bounds: IBound, vertices: Vertices, velocity: Vector): void; - - /** - * Returns true if the bounds contains the given point. - * @method contains - * @param {IBound} bounds - * @param {vector} point - * @return {boolean} True if the bounds contain the point, otherwise false - */ - contains (bounds: IBound, point: Vector): boolean; - - /** - * Returns true if the two bounds intersect. - * @method overlaps - * @param {IBound} boundsA - * @param {IBound} boundsB - * @return {boolean} True if the bounds overlap, otherwise false - */ - overlaps (boundsA: IBound, boundsB: IBound): boolean; - - /** - * Translates the bounds by the given vector. - * @method translate - * @param {IBound} bounds - * @param {vector} vector - */ - translate (bounds: IBound, vector: Vector): void; - - /** - * Shifts the bounds to the given position. - * @method shift - * @param {IBound} bounds - * @param {vector} position - */ - shift (bounds: IBound, position: Vector): void; - - } - - /** - * 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 - */ - class Composite { - - /** - * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. - * Triggers `beforeAdd` and `afterAdd` events on the `composite`. - * @method add - * @param {ICompositeDefinition} composite - * @param {} object - * @return {composite} The original composite with the objects added - */ - static add (composite: CompositeType, object: BodyType | CompositeType | ConstraintType): CompositeType; - - /** - * Returns all bodies in the given composite, including all bodies in its children, recursively. - * @method allBodies - * @param {composite} composite - * @return {body[]} All the bodies - */ - static allBodies (composite: CompositeType): Array; - - /** - * Returns all composites in the given composite, including all composites in its children, recursively. - * @method allComposites - * @param {composite} composite - * @return {composite[]} All the composites - */ - static allComposites (composite: CompositeType): Array; - - /** - * Returns all constraints in the given composite, including all constraints in its children, recursively. - * @method allConstraints - * @param {composite} composite - * @return {constraint[]} All the constraints - */ - static allConstraints (composite: CompositeType): Array; - - /** - * Removes all bodies, constraints and composites from the given composite. - * Optionally clearing its children recursively. - * @method clear - * @param {composite} composite - * @param {boolean} keepStatic - * @param {boolean} [deep=false] - */ - static clear (composite: CompositeType, keepStatic: boolean, deep?: boolean): void; - - /** - * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. - * See the properites section below for detailed information on what you can pass via the `options` object. - * @method create - * @param {} [options] - * @return {composite} A new composite - */ - static create (options?: ICompositeDefinition): CompositeType; - - /** - * Searches the composite recursively for an object matching the type and id supplied, null if not found. - * @method get - * @param {composite} composite - * @param {number} id - * @param {string} type - * @return {object} The requested object, if found - */ - static get (composite: CompositeType, id: number, type: string): BodyType | CompositeType | ConstraintType; - - /** - * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). - * @method move - * @param {compositeA} compositeA - * @param {object[]} objects - * @param {compositeB} compositeB - * @return {composite} Returns compositeA - */ - static move (compositeA: CompositeType, objects: Array, compositeB: CompositeType): CompositeType; - - /** - * Assigns new ids for all objects in the composite, recursively. - * @method rebase - * @param {composite} composite - * @return {composite} Returns composite - */ - static rebase (composite: CompositeType): CompositeType; - - /** - * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. - * Optionally searching its children recursively. - * Triggers `beforeRemove` and `afterRemove` events on the `composite`. - * @method remove - * @param {composite} composite - * @param {} object - * @param {boolean} [deep=false] - * @return {composite} The original composite with the objects removed - */ - static remove (composite: CompositeType, object: BodyType | CompositeType | ConstraintType, deep?: boolean): CompositeType; - - /** - * Sets the composite's `isModified` flag. - * If `updateParents` is true, all parents will be set (default: false). - * If `updateChildren` is true, all children will be set (default: false). - * @method setModified - * @param {composite} composite - * @param {boolean} isModified - * @param {boolean} [updateParents=false] - * @param {boolean} [updateChildren=false] - */ - static setModified (composite: CompositeType, isModified: boolean, updateParents?: boolean, updateChildren?: boolean): void; - - /** - * Translates all children in the composite by a given vector relative to their current positions, - * without imparting any velocity. - * @method translate - * @param {composite} composite - * @param {vector} translation - * @param {bool} [recursive=true] - */ - static translate (composite: CompositeType, translation: Vector, recursive?: boolean): void; - - /** - * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. - * @method rotate - * @param {composite} composite - * @param {number} rotation - * @param {vector} point - * @param {bool} [recursive=true] - */ - static rotate (composite: CompositeType, rotation: number, point: Vector, recursive?: boolean): void; - - /** - * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. - * @method scale - * @param {composite} composite - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} point - * @param {bool} [recursive=true] - */ - static scale (composite: CompositeType, scaleX: number, scaleY: number, point: Vector, recursive?: boolean): void; - - } - - class CompositeFactory { - - /** - * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. - * Triggers `beforeAdd` and `afterAdd` events on the `composite`. - * @method add - * @param {ICompositeDefinition} composite - * @param {} object - * @return {composite} The original composite with the objects added - */ - add (composite: CompositeType, object: BodyType | CompositeType | ConstraintType): CompositeType; - - /** - * Returns all bodies in the given composite, including all bodies in its children, recursively. - * @method allBodies - * @param {composite} composite - * @return {body[]} All the bodies - */ - allBodies (composite: CompositeType): Array; - - /** - * Returns all composites in the given composite, including all composites in its children, recursively. - * @method allComposites - * @param {composite} composite - * @return {composite[]} All the composites - */ - allComposites (composite: CompositeType): Array; - - /** - * Returns all constraints in the given composite, including all constraints in its children, recursively. - * @method allConstraints - * @param {composite} composite - * @return {constraint[]} All the constraints - */ - allConstraints (composite: CompositeType): Array; - - /** - * Removes all bodies, constraints and composites from the given composite. - * Optionally clearing its children recursively. - * @method clear - * @param {composite} composite - * @param {boolean} keepStatic - * @param {boolean} [deep=false] - */ - clear (composite: CompositeType, keepStatic: boolean, deep?: boolean): void; - - /** - * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. - * See the properites section below for detailed information on what you can pass via the `options` object. - * @method create - * @param {} [options] - * @return {composite} A new composite - */ - create (options?: ICompositeDefinition): CompositeType; - - /** - * Searches the composite recursively for an object matching the type and id supplied, null if not found. - * @method get - * @param {composite} composite - * @param {number} id - * @param {string} type - * @return {object} The requested object, if found - */ - get (composite: CompositeType, id: number, type: string): BodyType | CompositeType | ConstraintType; - - /** - * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). - * @method move - * @param {compositeA} compositeA - * @param {object[]} objects - * @param {compositeB} compositeB - * @return {composite} Returns compositeA - */ - move (compositeA: CompositeType, objects: Array, compositeB: CompositeType): CompositeType; - - /** - * Assigns new ids for all objects in the composite, recursively. - * @method rebase - * @param {composite} composite - * @return {composite} Returns composite - */ - rebase (composite: CompositeType): CompositeType; - - /** - * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. - * Optionally searching its children recursively. - * Triggers `beforeRemove` and `afterRemove` events on the `composite`. - * @method remove - * @param {composite} composite - * @param {} object - * @param {boolean} [deep=false] - * @return {composite} The original composite with the objects removed - */ - remove (composite: CompositeType, object: BodyType | CompositeType | ConstraintType, deep?: boolean): CompositeType; - - /** - * Sets the composite's `isModified` flag. - * If `updateParents` is true, all parents will be set (default: false). - * If `updateChildren` is true, all children will be set (default: false). - * @method setModified - * @param {composite} composite - * @param {boolean} isModified - * @param {boolean} [updateParents=false] - * @param {boolean} [updateChildren=false] - */ - setModified (composite: CompositeType, isModified: boolean, updateParents?: boolean, updateChildren?: boolean): void; - - /** - * Translates all children in the composite by a given vector relative to their current positions, - * without imparting any velocity. - * @method translate - * @param {composite} composite - * @param {vector} translation - * @param {bool} [recursive=true] - */ - translate (composite: CompositeType, translation: Vector, recursive?: boolean): void; - - /** - * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. - * @method rotate - * @param {composite} composite - * @param {number} rotation - * @param {vector} point - * @param {bool} [recursive=true] - */ - rotate (composite: CompositeType, rotation: number, point: Vector, recursive?: boolean): void; - - /** - * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. - * @method scale - * @param {composite} composite - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} point - * @param {bool} [recursive=true] - */ - scale (composite: CompositeType, scaleX: number, scaleY: number, point: Vector, recursive?: boolean): void; - - } - - /** - * 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 - */ - class Composites { - - /** - * Creates a composite with simple car setup of bodies and constraints. - * @method car - * @param {number} xx - * @param {number} yy - * @param {number} width - * @param {number} height - * @param {number} wheelSize - * @return {composite} A new composite car body - */ - static car (xx: number, yy: number, width: number, height: number, wheelSize: number): CompositeType; - - /** - * Chains all bodies in the given composite together using constraints. - * @method chain - * @param {composite} composite - * @param {number} xOffsetA - * @param {number} yOffsetA - * @param {number} xOffsetB - * @param {number} yOffsetB - * @param {object} options - * @return {composite} A new composite containing objects chained together with constraints - */ - static chain (composite: CompositeType, xOffsetA: number, yOffsetA: number, xOffsetB: number, yOffsetB: number, options: any): CompositeType; - - /** - * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. - * @method mesh - * @param {composite} composite - * @param {number} columns - * @param {number} rows - * @param {boolean} crossBrace - * @param {object} options - * @return {composite} The composite containing objects meshed together with constraints - */ - static mesh (composite: CompositeType, columns: number, rows: number, crossBrace: boolean, options: any): CompositeType; - - /** - * Creates a composite with a Newton's Cradle setup of bodies and constraints. - * @method newtonsCradle - * @param {number} xx - * @param {number} yy - * @param {number} number - * @param {number} size - * @param {number} length - * @return {composite} A new composite newtonsCradle body - */ - static newtonsCradle (xx: number, yy: number, number: number, size: number, length: number): CompositeType; - - /** - * Create a new composite containing bodies created in the callback in a pyramid arrangement. - * This function uses the body's bounds to prevent overlaps. - * @method pyramid - * @param {number} xx - * @param {number} yy - * @param {number} columns - * @param {number} rows - * @param {number} columnGap - * @param {number} rowGap - * @param {function} callback - * @return {composite} A new composite containing objects created in the callback - */ - static pyramid (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; - - /** - * Creates a simple soft body like object. - * @method softBody - * @param {number} xx - * @param {number} yy - * @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 - */ - static softBody (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, crossBrace: boolean, particleRadius: number, particleOptions: any, constraintOptions: any): CompositeType; - - /** - * Create a new composite containing bodies created in the callback in a grid arrangement. - * This function uses the body's bounds to prevent overlaps. - * @method stack - * @param {number} xx - * @param {number} yy - * @param {number} columns - * @param {number} rows - * @param {number} columnGap - * @param {number} rowGap - * @param {function} callback - * @return {composite} A new composite containing objects created in the callback - */ - static stack (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; - - } - - class CompositesFactory { - - /** - * Creates a composite with simple car setup of bodies and constraints. - * @method car - * @param {number} xx - * @param {number} yy - * @param {number} width - * @param {number} height - * @param {number} wheelSize - * @return {composite} A new composite car body - */ - car (xx: number, yy: number, width: number, height: number, wheelSize: number): CompositeType; - - /** - * Chains all bodies in the given composite together using constraints. - * @method chain - * @param {composite} composite - * @param {number} xOffsetA - * @param {number} yOffsetA - * @param {number} xOffsetB - * @param {number} yOffsetB - * @param {object} options - * @return {composite} A new composite containing objects chained together with constraints - */ - chain (composite: CompositeType, xOffsetA: number, yOffsetA: number, xOffsetB: number, yOffsetB: number, options: any): CompositeType; - - /** - * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. - * @method mesh - * @param {composite} composite - * @param {number} columns - * @param {number} rows - * @param {boolean} crossBrace - * @param {object} options - * @return {composite} The composite containing objects meshed together with constraints - */ - mesh (composite: CompositeType, columns: number, rows: number, crossBrace: boolean, options: any): CompositeType; - - /** - * Creates a composite with a Newton's Cradle setup of bodies and constraints. - * @method newtonsCradle - * @param {number} xx - * @param {number} yy - * @param {number} number - * @param {number} size - * @param {number} length - * @return {composite} A new composite newtonsCradle body - */ - newtonsCradle (xx: number, yy: number, number: number, size: number, length: number): CompositeType; - - /** - * Create a new composite containing bodies created in the callback in a pyramid arrangement. - * This function uses the body's bounds to prevent overlaps. - * @method pyramid - * @param {number} xx - * @param {number} yy - * @param {number} columns - * @param {number} rows - * @param {number} columnGap - * @param {number} rowGap - * @param {function} callback - * @return {composite} A new composite containing objects created in the callback - */ - pyramid (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; - - /** - * Creates a simple soft body like object. - * @method softBody - * @param {number} xx - * @param {number} yy - * @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 - */ - softBody (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, crossBrace: boolean, particleRadius: number, particleOptions: any, constraintOptions: any): CompositeType; - - /** - * Create a new composite containing bodies created in the callback in a grid arrangement. - * This function uses the body's bounds to prevent overlaps. - * @method stack - * @param {number} xx - * @param {number} yy - * @param {number} columns - * @param {number} rows - * @param {number} columnGap - * @param {number} rowGap - * @param {function} callback - * @return {composite} A new composite containing objects created in the callback - */ - stack (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; - - } - - /** - * 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 - */ - class Constraint { - - /** - * Creates a new constraint. - * 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 {} options - * @return {constraint} constraint - */ - static create (options: IConstraintDefinition): ConstraintType; - - } - - class ConstraintFactory { - - /** - * Creates a new constraint. - * 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 {} options - * @return {constraint} constraint - */ - create (options: IConstraintDefinition): ConstraintType; - - } - - /** - * 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 - */ - class Engine { - - /** - * Clears the engine including the world, pairs and broadphase. - * @method clear - * @param {engine} engine - */ - static clear (engine: Engine): void; - - /** - * 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 {HTMLElement} element - * @param {object} [options] - * @return {engine} engine - * @deprecated - */ - static create (element?: HTMLElement | IEngineDefinition, options?: IEngineDefinition): 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 - * @deprecated - */ - static create (options?: IEngineDefinition): Engine; - - /** - * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. - * @method merge - * @param {engine} engineA - * @param {engine} engineB - */ - static merge (engineA: Engine, engineB: Engine): void; - - /** - * Moves the simulation forward in time by `delta` ms. - * The `correction` argument is 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` 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. - * @method update - * @param {engine} engine - * @param {number} [delta=16.666] - * @param {number} [correction=1] - */ - static update (engine: Engine, delta?: number, correction?: number): Engine; - - /** - * An alias for `Runner.run`, see `Matter.Runner` for more information. - * @method run - * @param {engine} engine - */ - static run (engine: Engine): void; - - /** - * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. - * - * @property broadphase - * @type grid - * @default a Matter.Grid instance - */ - broadphase: Grid; - - /** - * An integer `Number` that specifies the number of constraint iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * The default value of `2` is usually very adequate. - * - * @property constraintIterations - * @type number - * @default 2 - */ - constraintIterations: number; - - /** - * A flag that specifies whether the engine is running or not. - */ - enabled: boolean; - - /** - * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. - * Sleeping can improve stability and performance, but often at the expense of accuracy. - * - * @property enableSleeping - * @type boolean - * @default false - */ - enableSleeping: boolean; - - /** - * Collision pair set for this `Engine`. - */ - pairs: any; - - /** - * An integer `Number` that specifies the number of position iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * - * @property positionIterations - * @type number - * @default 6 - */ - positionIterations: number; - - /** - * An `Object` containing properties regarding the timing systems of the engine. - * - * @property timing - * @type object - */ - timing: IEngineTimingOptions; - - /** - * An integer `Number` that specifies the number of velocity iterations to perform each update. - * The higher the value, the higher quality the simulation will be at the expense of performance. - * - * @property velocityIterations - * @type number - * @default 4 - */ - velocityIterations: number; - - /** - * A `World` composite object that will contain all simulated bodies and constraints. - * - * @property world - * @type world - * @default a Matter.World instance - */ - world: World; - - } - - /** - * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. - * - * @class Grid - */ - class Grid { - - /** - * Creates a new grid. - * @method create - * @param {} options - * @return {grid} A new grid - */ - static create (options?: IGridDefinition): Grid; - - /** - * Updates the grid. - * @method update - * @param {grid} grid - * @param {body[]} bodies - * @param {engine} engine - * @param {boolean} forceUpdate - */ - static update (grid: Grid, bodies: Array, engine: Engine, forceUpdate: boolean): void; - - /** - * Clears the grid. - * @method clear - * @param {grid} grid - */ - static clear (grid: Grid): void; - - } - - class GridFactory { - - /** - * Creates a new grid. - * @method create - * @param {} options - * @return {grid} A new grid - */ - create (options?: IGridDefinition): Grid; - - /** - * Updates the grid. - * @method update - * @param {grid} grid - * @param {body[]} bodies - * @param {engine} engine - * @param {boolean} forceUpdate - */ - update (grid: Grid, bodies: Array, engine: Engine, forceUpdate: boolean): void; - - /** - * Clears the grid. - * @method clear - * @param {grid} grid - */ - clear (grid: Grid): void; - - } - - /** - * The `Matter.MouseConstraint` module contains methods for creating mouse constraints. - * Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch. - * - * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). - * - * @class MouseConstraint - */ - class MouseConstraint { - - /** - * Creates a new mouse constraint. - * 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 {engine} engine - * @param {} options - * @return {MouseConstraint} A new MouseConstraint - */ - static create (engine: Engine, options?: IMouseConstraintDefinition): MouseConstraint; - - /** - * The `Constraint` object that is used to move the body during interaction. - * - * @property constraint - * @type constraint - */ - constraint: ConstraintType; - - /** - * An `Object` that specifies the collision filter properties. - * The collision filter allows the user to define which types of body this mouse constraint can interact with. - * See `body.collisionFilter` for more information. - * - * @property collisionFilter - * @type object - */ - collisionFilter: ICollisionFilter; - - /** - * The `Body` that is currently being moved by the user, or `null` if no body. - * - * @property body - * @type body - * @default null - */ - body: BodyType; - - /** - * A `String` denoting the type of object. - * - * @property type - * @type string - * @default "constraint" - */ - type: string; - - } - - /** - * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. - * - * @class Pairs - */ - class Pairs { - - /** - * Clears the given pairs structure. - * @method clear - * @param {pairs} pairs - * @return {pairs} pairs - */ - static clear (pairs: any): any; - } - - class PairsFactory { - - /** - * Clears the given pairs structure. - * @method clear - * @param {pairs} pairs - * @return {pairs} pairs - */ - clear (pairs: any): any; - } - - /** - * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. - * - * @class Pair - */ - class Pair { - - /** - * Creates a pair. - * @method create - * @param {ICollisionData} collision - * @param {number} timestamp - * @return {IPair} A new pair - */ - static create (collision: ICollisionData, timestamp: number): IPair; - - /** - * Updates a pair given a collision. - * @method update - * @param {IPair} pair - * @param {ICollisionData} collision - * @param {number} timestamp - */ - static update (pair: IPair, collision: ICollisionData, timestamp: number): void; - - /** - * Set a pair as active or inactive. - * @method setActive - * @param {IPair} pair - * @param {boolean} isActive - * @param {number} timestamp - */ - static setActive (pair: IPair, isActive: boolean, timestamp: number): void; - - /** - * Get the id for the given pair. - * @method id - * @param {Body} bodyA - * @param {Body} bodyB - * @return {string} Unique pairId - */ - static id (bodyA: BodyType, bodyB: BodyType): string; - - } - - class PairFactory { - - /** - * Creates a pair. - * @method create - * @param {ICollisionData} collision - * @param {number} timestamp - * @return {IPair} A new pair - */ - create (collision: ICollisionData, timestamp: number): IPair; - - /** - * Updates a pair given a collision. - * @method update - * @param {IPair} pair - * @param {ICollisionData} collision - * @param {number} timestamp - */ - update (pair: IPair, collision: ICollisionData, timestamp: number): void; - - /** - * Set a pair as active or inactive. - * @method setActive - * @param {IPair} pair - * @param {boolean} isActive - * @param {number} timestamp - */ - setActive (pair: IPair, isActive: boolean, timestamp: number): void; - - /** - * Get the id for the given pair. - * @method id - * @param {Body} bodyA - * @param {Body} bodyB - * @return {string} Unique pairId - */ - id (bodyA: BodyType, bodyB: BodyType): string; - - } - - /** - * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. - * - * @class Detector - */ - class Detector { - - /** - * Finds all collisions given a list of pairs. - * @method collisions - * @param {pair[]} broadphasePairs - * @param {engine} engine - * @return {ICollisionData[]} collisions - */ - static collisions (broadphasePairs: IPair[], engine: Engine): ICollisionData[]; - - /** - * Returns `true` if both supplied collision filters will allow a collision to occur. - * See `body.collisionFilter` for more information. - * @method canCollide - * @param {} filterA - * @param {} filterB - * @return {bool} `true` if collision can occur - */ - static canCollide (filterA: ICollisionFilter, filterB: ICollisionFilter): boolean; - - } - - class DetectorFactory { - - /** - * Finds all collisions given a list of pairs. - * @method collisions - * @param {pair[]} broadphasePairs - * @param {engine} engine - * @return {ICollisionData[]} collisions - */ - collisions (broadphasePairs: IPair[], engine: Engine): ICollisionData[]; - - /** - * Returns `true` if both supplied collision filters will allow a collision to occur. - * See `body.collisionFilter` for more information. - * @method canCollide - * @param {} filterA - * @param {} filterB - * @return {bool} `true` if collision can occur - */ - canCollide (filterA: ICollisionFilter, filterB: ICollisionFilter): boolean; - - } - - /** - * The `Matter.Resolver` module contains methods for resolving collision pairs. - * - * @class Resolver - */ - class Resolver { - - /** - * Prepare pairs for position solving. - * @method preSolvePosition - * @param {pair[]} pairs - */ - static preSolvePosition (pairs: IPair[]): void; - - /** - * Find a solution for pair positions. - * @method solvePosition - * @param {pair[]} pairs - * @param {body[]} bodies - * @param {number} timeScale - */ - static solvePosition (pairs: IPair[], bodies: BodyType[], timeScale: number): void; - - /** - * Apply position resolution. - * @method postSolvePosition - * @param {body[]} bodies - */ - static postSolvePosition (bodies: BodyType[]): void; - - /** - * Prepare pairs for velocity solving. - * @method preSolveVelocity - * @param {pair[]} pairs - */ - static preSolveVelocity (pairs: IPair[]): void; - - /** - * Find a solution for pair velocities. - * @method solveVelocity - * @param {pair[]} pairs - * @param {number} timeScale - */ - static solveVelocity (pairs: IPair[], timeScale: number): void; - - } - - class ResolverFactory { - - /** - * Prepare pairs for position solving. - * @method preSolvePosition - * @param {pair[]} pairs - */ - preSolvePosition (pairs: IPair[]): void; - - /** - * Find a solution for pair positions. - * @method solvePosition - * @param {pair[]} pairs - * @param {body[]} bodies - * @param {number} timeScale - */ - solvePosition (pairs: IPair[], bodies: BodyType[], timeScale: number): void; - - /** - * Apply position resolution. - * @method postSolvePosition - * @param {body[]} bodies - */ - postSolvePosition (bodies: BodyType[]): void; - - /** - * Prepare pairs for velocity solving. - * @method preSolveVelocity - * @param {pair[]} pairs - */ - preSolveVelocity (pairs: IPair[]): void; - - /** - * Find a solution for pair velocities. - * @method solveVelocity - * @param {pair[]} pairs - * @param {number} timeScale - */ - solveVelocity (pairs: IPair[], timeScale: number): void; - - } - - /** - * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. - * - * @class SAT - */ - class SAT { - - /** - * Detect collision between two bodies using the Separating Axis Theorem. - * @method collides - * @param {body} bodyA - * @param {body} bodyB - * @param {ICollisionData} previousCollision - * @return {ICollisionData} collision - */ - static collides (bodyA: BodyType, bodyB: BodyType, previousCollision: ICollisionData): ICollisionData; - - } - - class SATFactory { - - /** - * Detect collision between two bodies using the Separating Axis Theorem. - * @method collides - * @param {body} bodyA - * @param {body} bodyB - * @param {ICollisionData} previousCollision - * @return {ICollisionData} collision - */ - collides (bodyA: BodyType, bodyB: BodyType, previousCollision: ICollisionData): ICollisionData; - - } - - /** - * 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 - */ - class Query { - - /** - * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. - * @method ray - * @param {body[]} bodies - * @param {vector} startPoint - * @param {vector} endPoint - * @param {number} [rayWidth] - * @return {object[]} Collisions - */ - static ray (bodies: Array, startPoint: Vector, endPoint: Vector, rayWidth?: number): Array; - - /** - * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. - * @method region - * @param {body[]} bodies - * @param {bounds} bounds - * @param {bool} [outside=false] - * @return {body[]} The bodies matching the query - */ - static region (bodies: Array, bounds: Bounds, outside?: boolean): Array; - - /** - * Returns all bodies whose vertices contain the given point, from the given set of bodies. - * @method point - * @param {body[]} bodies - * @param {vector} point - * @return {body[]} The bodies matching the query - */ - static point (bodies: Array, point: Vector): Array; - - } - - class QueryFactory { - - /** - * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. - * @method ray - * @param {body[]} bodies - * @param {vector} startPoint - * @param {vector} endPoint - * @param {number} [rayWidth] - * @return {object[]} Collisions - */ - ray (bodies: Array, startPoint: Vector, endPoint: Vector, rayWidth?: number): Array; - - /** - * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. - * @method region - * @param {body[]} bodies - * @param {bounds} bounds - * @param {bool} [outside=false] - * @return {body[]} The bodies matching the query - */ - region (bodies: Array, bounds: Bounds, outside?: boolean): Array; - - /** - * Returns all bodies whose vertices contain the given point, from the given set of bodies. - * @method point - * @param {body[]} bodies - * @param {vector} point - * @return {body[]} The bodies matching the query - */ - point (bodies: Array, point: Vector): Array; - - } - - /** - * The `Matter.Runner` module is an optional utility which provides a game loop, - * that handles updating and rendering a `Matter.Engine` for you within a browser. - * It is intended for demo and testing purposes, but may be adequate 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. - * Note that the method `Engine.run` is an alias for `Runner.run`. - * - * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). - * - * @class Runner - */ - class Runner { - - /** - * Creates a new Runner. The options parameter is an object that specifies any properties you wish to override the defaults. - * @method create - * @param {} options - */ - static create (options: IRunnerOptions): Runner; - - /** - * Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event. - * @method run - * @param {engine} engine - */ - static run (runner: Runner, engine: Engine): Runner; - - /** - * Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event. - * @method run - * @param {engine} engine - */ - static run (engine: Engine): Runner; - - /** - * A game loop utility that updates the engine and renderer by one step (a 'tick'). - * Features delta smoothing, time correction and fixed or dynamic timing. - * Triggers `beforeTick`, `tick` and `afterTick` events on the engine. - * Consider just `Engine.update(engine, delta)` if you're using your own loop. - * @method tick - * @param {runner} runner - * @param {engine} engine - * @param {number} time - */ - static tick (runner: Runner, engine: Engine, time: number): void; - - /** - * Ends execution of `Runner.run` on the given `runner`, by canceling the animation frame request event loop. - * If you wish to only temporarily pause the engine, see `engine.enabled` instead. - * @method stop - * @param {runner} runner - */ - static stop (runner: Runner): void; - - /** - * Alias for `Runner.run`. - * @method start - * @param {runner} runner - * @param {engine} engine - */ - static start (runner: Runner, engine: Engine): void; - - /** - * A flag that specifies whether the runner is running or not. - * - * @property enabled - * @type boolean - * @default true - */ - enabled: boolean; - - /** - * A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable). - * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). - * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). - * - * @property isFixed - * @type boolean - * @default false - */ - isFixed: boolean; - - /** - * A `Number` that specifies the time step between updates in milliseconds. - * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. - * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. - * - * @property delta - * @type number - * @default 1000 / 60 - */ - delta: number; - - } - - /** - * The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies. - * - * @class Sleeping - */ - class Sleeping { - - static set (body: BodyType, isSleeping: boolean): void; - - } - - class SleepingFactory { - - set (body: BodyType, isSleeping: boolean): void; - - } - - /** - * The `Matter.Svg` module contains methods for converting SVG images into an array of vector points. - * - * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). - * - * @class Svg - */ - class Svg { - - /** - * Converts an SVG path into an array of vector points. - * If the input path forms a concave shape, you must decompose the result into convex parts before use. - * See `Bodies.fromVertices` which provides support for this. - * Note that this function is not guaranteed to support complex paths (such as those with holes). - * @method pathToVertices - * @param {SVGPathElement} path - * @param {Number} [sampleLength=15] - * @return {Vector[]} points - */ - static pathToVertices (path: SVGPathElement, sampleLength: number): Array; - - } - - class SvgFactory { - - /** - * Converts an SVG path into an array of vector points. - * If the input path forms a concave shape, you must decompose the result into convex parts before use. - * See `Bodies.fromVertices` which provides support for this. - * Note that this function is not guaranteed to support complex paths (such as those with holes). - * @method pathToVertices - * @param {SVGPathElement} path - * @param {Number} [sampleLength=15] - * @return {Vector[]} points - */ - pathToVertices (path: SVGPathElement, sampleLength: number): Array; - - } - - /** - * 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 - */ - class Vector { - - x: number; - y: number; - - /** - * Creates a new vector. - * @method create - * @param {number} x - * @param {number} y - * @return {vector} A new vector - */ - static create (x?: number, y?: number): Vector; - - /** - * Returns a new vector with `x` and `y` copied from the given `vector`. - * @method clone - * @param {vector} vector - * @return {vector} A new cloned vector - */ - static clone (vector: Vector): Vector; - - /** - * Returns the cross-product of three vectors. - * @method cross3 - * @param {vector} vectorA - * @param {vector} vectorB - * @param {vector} vectorC - * @return {number} The cross product of the three vectors - */ - static cross3 (vectorA: Vector, vectorB: Vector, vectorC: Vector): number; - - /** - * Adds the two vectors. - * @method add - * @param {vector} vectorA - * @param {vector} vectorB - * @param {vector} [output] - * @return {vector} A new vector of vectorA and vectorB added - */ - static add (vectorA: Vector, vectorB: Vector, output?: Vector): Vector; - - /** - * Returns the angle in radians between the two vectors relative to the x-axis. - * @method angle - * @param {vector} vectorA - * @param {vector} vectorB - * @return {number} The angle in radians - */ - static angle (vectorA: Vector, vectorB: Vector): number; - - /** - * Returns the cross-product of two vectors. - * @method cross - * @param {vector} vectorA - * @param {vector} vectorB - * @return {number} The cross product of the two vectors - */ - static cross (vectorA: Vector, vectorB: Vector): number; - - /** - * Divides a vector and a scalar. - * @method div - * @param {vector} vector - * @param {number} scalar - * @return {vector} A new vector divided by scalar - */ - static div (vector: Vector, scalar: number): Vector; - - /** - * Returns the dot-product of two vectors. - * @method dot - * @param {vector} vectorA - * @param {vector} vectorB - * @return {number} The dot product of the two vectors - */ - static dot (vectorA: Vector, vectorB: Vector): Number; - - /** - * Returns the magnitude (length) of a vector. - * @method magnitude - * @param {vector} vector - * @return {number} The magnitude of the vector - */ - static magnitude (vector: Vector): number; - - /** - * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation). - * @method magnitudeSquared - * @param {vector} vector - * @return {number} The squared magnitude of the vector - */ - static magnitudeSquared (vector: Vector): number; - - /** - * Multiplies a vector and a scalar. - * @method mult - * @param {vector} vector - * @param {number} scalar - * @return {vector} A new vector multiplied by scalar - */ - static mult (vector: Vector, scalar: number): Vector; - - /** - * Negates both components of a vector such that it points in the opposite direction. - * @method neg - * @param {vector} vector - * @return {vector} The negated vector - */ - static neg (vector: Vector): Vector; - - /** - * Normalises a vector (such that its magnitude is `1`). - * @method normalise - * @param {vector} vector - * @return {vector} A new vector normalised - */ - static normalise (vector: Vector): Vector; - - /** - * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction. - * @method perp - * @param {vector} vector - * @param {bool} [negate=false] - * @return {vector} The perpendicular vector - */ - static perp (vector: Vector, negate?: boolean): Vector; - - /** - * Rotates the vector about (0, 0) by specified angle. - * @method rotate - * @param {vector} vector - * @param {number} angle - * @return {vector} A new vector rotated about (0, 0) - */ - static rotate (vector: Vector, angle: number): Vector; - - /** - * Rotates the vector about a specified point by specified angle. - * @method rotateAbout - * @param {vector} vector - * @param {number} angle - * @param {vector} point - * @param {vector} [output] - * @return {vector} A new vector rotated about the point - */ - static rotateAbout (vector: Vector, angle: number, point: Vector, output?: Vector): Vector; - - /** - * Subtracts the two vectors. - * @method sub - * @param {vector} vectorA - * @param {vector} vectorB - * @param {vector} [output] - * @return {vector} A new vector of vectorA and vectorB subtracted - */ - static sub (vectorA: Vector, vectorB: Vector, optional?: Vector): Vector; - - } - - class VectorFactory { - - /** - * Creates a new vector. - * @method create - * @param {number} x - * @param {number} y - * @return {vector} A new vector - */ - create (x?: number, y?: number): Vector; - - /** - * Returns a new vector with `x` and `y` copied from the given `vector`. - * @method clone - * @param {vector} vector - * @return {vector} A new cloned vector - */ - clone (vector: Vector): Vector; - - /** - * Returns the cross-product of three vectors. - * @method cross3 - * @param {vector} vectorA - * @param {vector} vectorB - * @param {vector} vectorC - * @return {number} The cross product of the three vectors - */ - cross3 (vectorA: Vector, vectorB: Vector, vectorC: Vector): number; - - /** - * Adds the two vectors. - * @method add - * @param {vector} vectorA - * @param {vector} vectorB - * @param {vector} [output] - * @return {vector} A new vector of vectorA and vectorB added - */ - add (vectorA: Vector, vectorB: Vector, output?: Vector): Vector; - - /** - * Returns the angle in radians between the two vectors relative to the x-axis. - * @method angle - * @param {vector} vectorA - * @param {vector} vectorB - * @return {number} The angle in radians - */ - angle (vectorA: Vector, vectorB: Vector): number; - - /** - * Returns the cross-product of two vectors. - * @method cross - * @param {vector} vectorA - * @param {vector} vectorB - * @return {number} The cross product of the two vectors - */ - cross (vectorA: Vector, vectorB: Vector): number; - - /** - * Divides a vector and a scalar. - * @method div - * @param {vector} vector - * @param {number} scalar - * @return {vector} A new vector divided by scalar - */ - div (vector: Vector, scalar: number): Vector; - - /** - * Returns the dot-product of two vectors. - * @method dot - * @param {vector} vectorA - * @param {vector} vectorB - * @return {number} The dot product of the two vectors - */ - dot (vectorA: Vector, vectorB: Vector): number; - - /** - * Returns the magnitude (length) of a vector. - * @method magnitude - * @param {vector} vector - * @return {number} The magnitude of the vector - */ - magnitude (vector: Vector): number; - - /** - * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation). - * @method magnitudeSquared - * @param {vector} vector - * @return {number} The squared magnitude of the vector - */ - magnitudeSquared (vector: Vector): number; - - /** - * Multiplies a vector and a scalar. - * @method mult - * @param {vector} vector - * @param {number} scalar - * @return {vector} A new vector multiplied by scalar - */ - mult (vector: Vector, scalar: number): Vector; - - /** - * Negates both components of a vector such that it points in the opposite direction. - * @method neg - * @param {vector} vector - * @return {vector} The negated vector - */ - neg (vector: Vector): Vector; - - /** - * Normalises a vector (such that its magnitude is `1`). - * @method normalise - * @param {vector} vector - * @return {vector} A new vector normalised - */ - normalise (vector: Vector): Vector; - - /** - * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction. - * @method perp - * @param {vector} vector - * @param {bool} [negate=false] - * @return {vector} The perpendicular vector - */ - perp (vector: Vector, negate?: boolean): Vector; - - /** - * Rotates the vector about (0, 0) by specified angle. - * @method rotate - * @param {vector} vector - * @param {number} angle - * @return {vector} A new vector rotated about (0, 0) - */ - rotate (vector: Vector, angle: number): Vector; - - /** - * Rotates the vector about a specified point by specified angle. - * @method rotateAbout - * @param {vector} vector - * @param {number} angle - * @param {vector} point - * @param {vector} [output] - * @return {vector} A new vector rotated about the point - */ - rotateAbout (vector: Vector, angle: number, point: Vector, output?: Vector): Vector; - - /** - * Subtracts the two vectors. - * @method sub - * @param {vector} vectorA - * @param {vector} vectorB - * @param {vector} [output] - * @return {vector} A new vector of vectorA and vectorB subtracted - */ - sub (vectorA: Vector, vectorB: Vector, optional?: Vector): 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 - */ - class Vertices { - - /** - * Returns the average (mean) of the set of vertices. - * @method mean - * @param {vertices} vertices - * @return {vector} The average point - */ - static mean (vertices: Array): Array; - - /** - * Sorts the input vertices into clockwise order in place. - * @method clockwiseSort - * @param {vertices} vertices - * @return {vertices} vertices - */ - static clockwiseSort (vertices: Array): Array; - - /** - * Returns true if the vertices form a convex shape (vertices must be in clockwise order). - * @method isConvex - * @param {vertices} vertices - * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable). - */ - static isConvex (vertices: Array): boolean; - - /** - * Returns the convex hull of the input vertices as a new array of points. - * @method hull - * @param {vertices} vertices - * @return [vertex] vertices - */ - static hull (vertices: Array): Array; - - /** - * Returns the area of the set of vertices. - * @method area - * @param {vertices} vertices - * @param {bool} signed - * @return {number} The area - */ - static area (vertices: Array, signed: boolean): number; - - /** - * Returns the centre (centroid) of the set of vertices. - * @method centre - * @param {vertices} vertices - * @return {vector} The centre point - */ - static centre (vertices: Array): Vector; - - /** - * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. - * The radius parameter is a single number or an array to specify the radius for each vertex. - * @method chamfer - * @param {vertices} vertices - * @param {number[]} radius - * @param {number} quality - * @param {number} qualityMin - * @param {number} qualityMax - */ - static chamfer (vertices: Array, radius: number | Array, quality: number, qualityMin: number, qualityMax: number): void; - - /** - * Returns `true` if the `point` is inside the set of `vertices`. - * @method contains - * @param {vertices} vertices - * @param {vector} point - * @return {boolean} True if the vertices contains point, otherwise false - */ - static contains (vertices: Array, point: Vector): boolean; - - /** - * Creates a new set of `Matter.Body` compatible vertices. - * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example: - * - * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] - * - * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects, - * but with some additional references required for efficient collision detection routines. - * - * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided. - * - * @method create - * @param {vector[]} points - * @param {body} body - */ - static create (points: Array, body: BodyType): Array; - - /** - * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), - * into a `Matter.Vertices` object for the given `Matter.Body`. - * For parsing SVG paths, see `Svg.pathToVertices`. - * @method fromPath - * @param {string} path - * @param {body} body - * @return {vertices} vertices - */ - static fromPath (path: string, body: BodyType): Array; - - /** - * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. - * @method inertia - * @param {vertices} vertices - * @param {number} mass - * @return {number} The polygon's moment of inertia - */ - static inertia (vertices: Array, mass: number): number; - - /** - * Rotates the set of vertices in-place. - * @method rotate - * @param {vertices} vertices - * @param {number} angle - * @param {vector} point - */ - static rotate (vertices: Array, angle: number, point: Vector): void; - - /** - * Scales the vertices from a point (default is centre) in-place. - * @method scale - * @param {vertices} vertices - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} point - */ - static scale (vertices: Array, scaleX: number, scaleY: number, point: Vector): void; - - /** - * Translates the set of vertices in-place. - * @method translate - * @param {vertices} vertices - * @param {vector} vector - * @param {number} scalar - */ - static translate (vertices: Array, vector: Vector, scalar: number): void; - - } - - class VerticesFactory { - - /** - * Returns the average (mean) of the set of vertices. - * @method mean - * @param {vertices} vertices - * @return {vector} The average point - */ - mean (vertices: Array): Array; - - /** - * Sorts the input vertices into clockwise order in place. - * @method clockwiseSort - * @param {vertices} vertices - * @return {vertices} vertices - */ - clockwiseSort (vertices: Array): Array; - - /** - * Returns true if the vertices form a convex shape (vertices must be in clockwise order). - * @method isConvex - * @param {vertices} vertices - * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable). - */ - isConvex (vertices: Array): boolean; - - /** - * Returns the convex hull of the input vertices as a new array of points. - * @method hull - * @param {vertices} vertices - * @return [vertex] vertices - */ - hull (vertices: Array): Array; - - /** - * Returns the area of the set of vertices. - * @method area - * @param {vertices} vertices - * @param {bool} signed - * @return {number} The area - */ - area (vertices: Array, signed: boolean): number; - - /** - * Returns the centre (centroid) of the set of vertices. - * @method centre - * @param {vertices} vertices - * @return {vector} The centre point - */ - centre (vertices: Array): Vector; - - /** - * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. - * The radius parameter is a single number or an array to specify the radius for each vertex. - * @method chamfer - * @param {vertices} vertices - * @param {number[]} radius - * @param {number} quality - * @param {number} qualityMin - * @param {number} qualityMax - */ - chamfer (vertices: Array, radius: number | Array, quality: number, qualityMin: number, qualityMax: number): void; - - /** - * Returns `true` if the `point` is inside the set of `vertices`. - * @method contains - * @param {vertices} vertices - * @param {vector} point - * @return {boolean} True if the vertices contains point, otherwise false - */ - contains (vertices: Array, point: Vector): boolean; - - /** - * Creates a new set of `Matter.Body` compatible vertices. - * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example: - * - * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] - * - * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects, - * but with some additional references required for efficient collision detection routines. - * - * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided. - * - * @method create - * @param {vector[]} points - * @param {body} body - */ - create (points: Array, body: BodyType): Array; - - /** - * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), - * into a `Matter.Vertices` object for the given `Matter.Body`. - * For parsing SVG paths, see `Svg.pathToVertices`. - * @method fromPath - * @param {string} path - * @param {body} body - * @return {vertices} vertices - */ - fromPath (path: string, body: BodyType): Array; - - /** - * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. - * @method inertia - * @param {vertices} vertices - * @param {number} mass - * @return {number} The polygon's moment of inertia - */ - inertia (vertices: Array, mass: number): number; - - /** - * Rotates the set of vertices in-place. - * @method rotate - * @param {vertices} vertices - * @param {number} angle - * @param {vector} point - */ - rotate (vertices: Array, angle: number, point: Vector): void; - - /** - * Scales the vertices from a point (default is centre) in-place. - * @method scale - * @param {vertices} vertices - * @param {number} scaleX - * @param {number} scaleY - * @param {vector} point - */ - scale (vertices: Array, scaleX: number, scaleY: number, point: Vector): void; - - /** - * Translates the set of vertices in-place. - * @method translate - * @param {vertices} vertices - * @param {vector} vector - * @param {number} scalar - */ - translate (vertices: Array, vector: Vector, scalar: number): void; - - } - - /** - * The `Matter.World` module contains methods for creating and manipulating the world composite. - * A `Matter.World` is a `Matter.Composite` body, which is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`. - * A `Matter.World` has a few additional properties including `gravity` and `bounds`. - * It is important to use the functions in the `Matter.Composite` module to modify the world composite, rather than directly modifying its properties. - * There are also a few methods here that alias those in `Matter.Composite` for easier readability. - * - * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). - * - * @class World - * @extends Composite - */ - class World { - - /** - * Add objects or arrays of objects of types: Body, Constraint, Composite - * @param world - * @param body - * @returns world - */ - static add (world: World, body: BodyType | Array | CompositeType | Array | ConstraintType | Array | MouseConstraint): World; - - /** - * An alias for Composite.addBody since World is also a Composite - * @method addBody - * @param {world} world - * @param {body} body - * @return {world} The original world with the body added - */ - static addBody (world: World, body: BodyType): World; - - /** - * An alias for Composite.add since World is also a Composite - * @method addComposite - * @param {world} world - * @param {composite} composite - * @return {world} The original world with the objects from composite added - */ - static addComposite (world: World, composite: CompositeType): World; - - /** - * An alias for Composite.addConstraint since World is also a Composite - * @method addConstraint - * @param {world} world - * @param {constraint} constraint - * @return {world} The original world with the constraint added - */ - static addConstraint (world: World, constraint: ConstraintType): World; - - /** - * An alias for Composite.clear since World is also a Composite - * @method clear - * @param {world} world - * @param {boolean} keepStatic - */ - static clear (world: World, keepStatic: boolean): void; - - /** - * Creates a new world composite. The options parameter is an object that specifies any properties you wish to override the defaults. - * See the properties section below for detailed information on what you can pass via the `options` object. - * @method create - * @constructor - * @param {} options - * @return {world} A new world - */ - static create (options: IWorldDefinition): World; - - gravity: Gravity; - - bounds: Bounds; - - } - - class Events { - - /** - * Fired when a body starts sleeping (where `this` is the body). - * - * @event sleepStart - * @this {body} The body that has started sleeping - * @param {} event An event object - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: BodyType, name: "sleepStart", callback: (e: IEvent) => void): void; - - /** - * Fired when a body ends sleeping (where `this` is the body). - * - * @event sleepEnd - * @this {body} The body that has ended sleeping - * @param {} event An event object - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: BodyType, name: "sleepEnd", callback: (e: IEvent) => void): void; - - /** - * Fired when a call to `Composite.add` is made, before objects have been added. - * - * @event beforeAdd - * @param {} event An event object - * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "beforeAdd", callback: (e: IEventComposite) => void): void; - - /** - * Fired when a call to `Composite.add` is made, after objects have been added. - * - * @event afterAdd - * @param {} event An event object - * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "afterAdd", callback: (e: IEventComposite) => void): void; - - /** - * Fired when a call to `Composite.remove` is made, before objects have been removed. - * - * @event beforeRemove - * @param {} event An event object - * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "beforeRemove", callback: (e: IEventComposite) => void): void; - - /** - * Fired when a call to `Composite.remove` is made, after objects have been removed. - * - * @event afterRemove - * @param {} event An event object - * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these) - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "afterRemove", callback: (e: IEventComposite) => void): void; - - /** - * Fired after engine update and all collision events - * - * @event afterUpdate - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "afterUpdate", callback: (e: IEventTimestamped) => void): void; - - /** - * Fired just before an update - * - * @event beforeUpdate - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "beforeUpdate", callback: (e: IEventTimestamped) => void): void; - - /** - * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) - * - * @event collisionActive - * @param {} event An event object - * @param {} event.pairs List of affected pairs - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "collisionActive", callback: (e: IEventCollision) => void): void; - - /** - * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) - * - * @event collisionEnd - * @param {} event An event object - * @param {} event.pairs List of affected pairs - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "collisionEnd", callback: (e: IEventCollision) => void): void; - - /** - * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) - * - * @event collisionStart - * @param {} event An event object - * @param {} event.pairs List of affected pairs - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "collisionStart", callback: (e: IEventCollision) => void): void; - - /** - * Fired at the start of a tick, before any updates to the engine or timing - * - * @event beforeTick - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "beforeTick", callback: (e: IEventTimestamped) => void): void; - - /** - * Fired after engine timing updated, but just before update - * - * @event tick - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "tick", callback: (e: IEventTimestamped) => void): void; - - /** - * Fired at the end of a tick, after engine update and after rendering - * - * @event afterTick - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "afterTick", callback: (e: IEventTimestamped) => void): void; - - /** - * Fired before rendering - * - * @event beforeRender - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "beforeRender", callback: (e: IEventTimestamped) => void): void; - - /** - * Fired after rendering - * - * @event afterRender - * @param {} event An event object - * @param {number} event.timestamp The engine.timing.timestamp of the event - * @param {} event.source The source object of the event - * @param {} event.name The name of the event - */ - static on (obj: Engine, name: "afterRender", callback: (e: IEventTimestamped) => void): void; - - static on (obj: any, name: string, callback: (e: any) => void): void; - - /** - * Removes the given event callback. If no callback, clears all callbacks in eventNames. If no eventNames, clears all events. - * - * @param obj - * @param eventName - * @param callback - */ - static off(obj: any, eventName: string, callback: (e: any) => void): void; - - /** - * Fires all the callbacks subscribed to the given object's eventName, in the order they subscribed, if any. - * - * @param object - * @param eventNames - * @param event - */ - static trigger(object: any, eventNames: string, event?: (e: any) => void): void; - - } - - type Dependency = {name: string, range: string} | {name: string, version: string} | string; - - class Plugin { - - name: string; - version: string; - install: () => void; - for?: string; - - /** - * Registers a plugin object so it can be resolved later by name. - * @method register - * @param plugin {} The plugin to register. - * @return {object} The plugin. - */ - static register (plugin: Plugin): Plugin; - - /** - * Resolves a dependency to a plugin object from the registry if it exists. - * The `dependency` may contain a version, but only the name matters when resolving. - * @method resolve - * @param dependency {string} The dependency. - * @return {object} The plugin if resolved, otherwise `undefined`. - */ - static resolve (dependency: string): Plugin | undefined; - - /** - * Returns `true` if the object meets the minimum standard to be considered a plugin. - * This means it must define the following properties: - * - `name` - * - `version` - * - `install` - * @method isPlugin - * @param obj {} The obj to test. - * @return {boolean} `true` if the object can be considered a plugin otherwise `false`. - */ - static isPlugin (obj: {}): boolean; - - /** - * Returns a pretty printed plugin name and version. - * @method toString - * @param plugin {} The plugin. - * @return {string} Pretty printed plugin name and version. - */ - static toString (plugin: string | Plugin): string; - - /** - * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`. - * If `plugin.for` is not specified then it is assumed to be applicable. - * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`. - * @method isFor - * @param plugin {} The plugin. - * @param module {} The module. - * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`. - */ - static isFor (plugin: Plugin, module: {name?: string, [_: string]: any}): boolean; - - /** - * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`. - * For installing plugins on `Matter` see the convenience function `Matter.use`. - * Plugins may be specified either by their name or a reference to the plugin object. - * Plugins themselves may specify further dependencies, but each plugin is installed only once. - * Order is important, a topological sort is performed to find the best resulting order of installation. - * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases. - * This function logs the resulting status of each dependency in the console, along with any warnings. - * - A green tick ✅ indicates a dependency was resolved and installed. - * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies. - * - A red cross ❌ indicates a dependency could not be resolved. - * Avoid calling this function multiple times on the same module unless you intend to manually control installation order. - * @method use - * @param module {} The module install plugins on. - * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`). - */ - static use (module: {uses?: (Plugin | string)[]; [_: string]: any}, plugins: (Plugin | string)[]): void; - - /** - * Recursively finds all of a module's dependencies and returns a flat dependency graph. - * @method dependencies - * @param module {} The module. - * @return {object} A dependency graph. - */ - static dependencies (module: Dependency, tracked?: {[_: string]: string[]}): {[_: string]: string[]} | string | undefined; - - /** - * Parses a dependency string into its components. - * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`. - * See documentation for `Plugin.versionParse` for a description of the format. - * This function can also handle dependencies that are already resolved (e.g. a module object). - * @method dependencyParse - * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`. - * @return {object} The dependency parsed into its components. - */ - static dependencyParse (dependency: Dependency) : {name: string, range: string}; - - /** - * 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` - * - 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. - */ - static versionParse (range: string) : { - isRange: boolean, - version: string, - range: string, - operator: string - parts: number[], - prerelease: string, - number: number - }; - - /** - * Returns `true` if `version` satisfies the given `range`. - * See documentation for `Plugin.versionParse` for a description of the format. - * If a version or range is not specified, then any version (`*`) is assumed to satisfy. - * @method versionSatisfies - * @param version {string} The version string. - * @param range {string} The range string. - * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`. - */ - static versionSatisfies (version: string, range: string): boolean; - - } -} - -declare module 'matter' { - export = MatterJS; -} +// Type definitions specifically for Matter.js as used by Phaser 3 +// +// Definitions by: Ivane Gegia , +// David Asmuth , +// Piotr Pietrzak , +// Richard Davey + +declare namespace MatterJS { + + // -------------------------------------------------------------- + // Interfaces + // -------------------------------------------------------------- + + interface IChamfer { + + radius?: number | Array; + quality?: number; + qualityMin?: number; + qualityMax?: number; + + } + + interface IChamferableBodyDefinition extends IBodyDefinition { + + chamfer?: IChamfer; + + } + + interface IBodyDefinition { + + /** + * A `Number` specifying the angle of the body, in radians. + * + * @property angle + * @type number + * @default 0 + */ + angle?: number; + + /** + * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). + * + * @readOnly + * @property angularSpeed + * @type number + * @default 0 + */ + angularSpeed?: number; + + /** + * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property angularVelocity + * @type number + * @default 0 + */ + angularVelocity?: number; + + /** + * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. + * + * @property area + * @type string + * @default + */ + area?: number; + + /** + * An array of unique axis vectors (edge normals) used for collision detection. + * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. + * They are constantly updated by `Body.update` during the simulation. + * + * @property axes + * @type vector[] + */ + axes?: Array; + + /** + * A `Bounds` object that defines the AABB region for the body. + * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. + * + * @property bounds + * @type bounds + */ + bounds?: IBound; + + /** + * 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 + */ + density?: number; + + /** + * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. + * + * @property force + * @type vector + * @default { x: 0, y: 0 } + */ + force?: Vector; + + /** + * 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 + */ + friction?: number; + + /** + * A `Number` that defines the air friction of the body (air resistance). + * A value of `0` means the body will never slow as it moves through space. + * The higher the value, the faster a body slows when moving through space. + * The effects of the value are non-linear. + * + * @property frictionAir + * @type number + * @default 0.01 + */ + frictionAir?: number; + + /** + * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. + * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. + * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). + * + * @property inertia + * @type number + */ + inertia?: number; + + /** + * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). + * If you modify this value, you must also modify the `body.inertia` property. + * + * @property inverseInertia + * @type number + */ + inverseInertia?: number; + + /** + * A `Number` that defines the inverse mass of the body (`1 / mass`). + * If you modify this value, you must also modify the `body.mass` property. + * + * @property inverseMass + * @type number + */ + inverseMass?: number; + + /** + * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + * + * @property isSensor + * @type boolean + * @default false + */ + isSensor?: boolean; + + /** + * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. + * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. + * + * @property isSleeping + * @type boolean + * @default false + */ + isSleeping?: boolean; + + /** + * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. + * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. + * + * @property isStatic + * @type boolean + * @default false + */ + isStatic?: boolean; + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Body" + */ + label?: string; + + /** + * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. + * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). + * + * @property mass + * @type number + */ + mass?: number; + + /** + * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. + * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. + * + * @readOnly + * @property motion + * @type number + * @default 0 + */ + motion?: number; + + /** + * A `Vector` that specifies the current world-space position of the body. + * + * @property position + * @type vector + */ + position?: Vector; + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + render?: IBodyRenderOptions; + + /** + * 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 + */ + restitution?: number; + + /** + * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). + * + * @property sleepThreshold + * @type number + * @default 60 + */ + sleepThreshold?: number; + + /** + * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. + * Avoid changing this value unless you understand the purpose of `slop` in physics engines. + * The default should generally suffice, although very large bodies may require larger values for stable stacking. + * + * @property slop + * @type number + * @default 0.05 + */ + slop?: number; + + /** + * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). + * + * @readOnly + * @property speed + * @type number + * @default 0 + */ + speed?: number; + + /** + * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + * + * @property timeScale + * @type number + * @default 1 + */ + timeScale?: number; + + /** + * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. + * + * @property torque + * @type number + * @default 0 + */ + torque?: number; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "body" + */ + type?: string; + + /** + * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property velocity + * @type vector + * @default { x: 0, y: 0 } + */ + velocity?: Vector; + + /** + * An array of `Vector` objects that specify the convex hull of the rigid body. + * These should be provided about the origin `(0, 0)`. E.g. + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). + * The `Vector` objects are also augmented with additional properties required for efficient collision detection. + * + * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). + * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. + * + * @property vertices + * @type vector[] + */ + vertices?: Array; + + /** + * An array of bodies that make up this body. + * The first body in the array must always be a self reference to the current body instance. + * All bodies in the `parts` array together form a single rigid compound body. + * Parts are allowed to overlap, have gaps or holes or even form concave bodies. + * Parts themselves should never be added to a `World`, only the parent body should be. + * Use `Body.setParts` when setting parts to ensure correct updates of all properties. + * + * @property parts + * @type body[] + */ + parts?: Array; + + /** + * A self reference if the body is _not_ a part of another body. + * Otherwise this is a reference to the body that this is a part of. + * See `body.parts`. + * + * @property parent + * @type body + */ + parent?: BodyType; + + /** + * A `Number` that defines the static friction of the body (in the Coulomb friction model). + * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. + * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. + * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. + * + * @property frictionStatic + * @type number + * @default 0.5 + */ + frictionStatic?: number; + + /** + * An `Object` that specifies the collision filtering properties of this body. + * + * Collisions between two bodies will obey the following rules: + * - If the two bodies have the same non-zero value of `collisionFilter.group`, + * they will always collide if the value is positive, and they will never collide + * if the value is negative. + * - If the two bodies have different values of `collisionFilter.group` or if one + * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: + * + * Each body belongs to a collision category, given by `collisionFilter.category`. This + * value is used as a bit field and the category should have only one bit set, meaning that + * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 + * different collision categories available. + * + * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies + * the categories it collides with (the value is the bitwise AND value of all these categories). + * + * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's + * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` + * are both true. + * + * @property collisionFilter + * @type object + */ + collisionFilter?: ICollisionFilter; + + /** + * A reference to the Phaser Game Object this body belongs to, if any. + * + * @property gameObject + * @type Phaser.GameObjects.GameObject + */ + gameObject?: any; + + /** + * Scale the influence of World gravity when applied to this body. + * + * @property gravityScale + * @type vector + * @default { x: 1, y: 1 } + */ + gravityScale?: Vector; + + /** + * Will this Body ignore World gravity during the Engine update? + * + * @property ignoreGravity + * @type boolean + * @default false + */ + ignoreGravity?: boolean; + + /** + * Will this Body ignore Phaser Pointer input events? + * + * @property ignorePointer + * @type boolean + * @default false + */ + ignorePointer?: boolean; + + /** + * A callback that is invoked when this Body starts colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideCallback + * @type function + * @default null + */ + onCollideCallback?: Function; + + /** + * A callback that is invoked when this Body stops colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideEndCallback + * @type function + * @default null + */ + onCollideEndCallback?: Function; + + /** + * A callback that is invoked for the duration that this Body is colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideActiveCallback + * @type function + * @default null + */ + onCollideActiveCallback?: Function; + + /** + * A collision callback dictionary used by the `Body.setOnCollideWith` function. + * + * @property onCollideWith + * @type object + * @default null + */ + onCollideWith?: any; + + } + + interface IBodyRenderOptions { + + /** + * A flag that indicates if the body should be rendered. + * + * @property visible + * @type boolean + * @default true + */ + visible?: boolean; + + /** + * Sets the opacity. 1.0 is fully opaque. 0.0 is fully translucent. + * + * @property opacity + * @type number + * @default 1 + */ + opacity?: number; + + /** + * An `Object` that defines the sprite properties to use when rendering, if any. + * + * @property sprite + * @type object + */ + sprite?: IBodyRenderOptionsSprite; + + /** + * A hex color value that defines the fill color to use when rendering the body. + * + * @property fillColor + * @type number + */ + fillColor?: number; + + /** + * A value that defines the fill opacity to use when rendering the body. + * + * @property fillOpacity + * @type number + */ + fillOpacity?: number; + + /** + * A hex color value that defines the line color to use when rendering the body. + * + * @property lineColor + * @type number + */ + lineColor?: number; + + /** + * A value that defines the line opacity to use when rendering the body. + * + * @property lineOpacity + * @type number + */ + lineOpacity?: number; + + /** + * A `Number` that defines the line width to use when rendering the body outline. + * + * @property lineThickness + * @type number + */ + lineThickness?: number; + + } + + interface IBodyRenderOptionsSprite { + + /** + * A `Number` that defines the scaling in the x-axis for the sprite, if any. + * + * @property xOffset + * @type number + * @default 0 + */ + xOffset: number; + + /** + * A `Number` that defines the scaling in the y-axis for the sprite, if any. + * + * @property yOffset + * @type number + * @default 0 + */ + yOffset: number; + } + + interface IBound { + + min: { x: number, y: number } + max: { x: number, y: number } + + } + + interface ICompositeDefinition { + + /** + * An array of `Body` that are _direct_ children of this composite. + * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. + * + * @property bodies + * @type body[] + * @default [] + */ + bodies?: Array; + + /** + * An array of `Composite` that are _direct_ children of this composite. + * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. + * + * @property composites + * @type composite[] + * @default [] + */ + composites?: Array; + + /** + * An array of `Constraint` that are _direct_ children of this composite. + * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. + * + * @property constraints + * @type constraint[] + * @default [] + */ + constraints?: Array; + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + id?: number; + + /** + * A flag that specifies whether the composite has been modified during the current step. + * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. + * If you need to change it manually, you should use the `Composite.setModified` method. + * + * @property isModified + * @type boolean + * @default false + */ + isModified?: boolean; + + /** + * An arbitrary `String` name to help the user identify and manage composites. + * + * @property label + * @type string + * @default "Composite" + */ + label?: string; + + /** + * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. + * + * @property parent + * @type composite + * @default null + */ + parent?: CompositeType; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "composite" + */ + type?: string; + + } + + interface IConstraintDefinition { + + /** + * The first possible `Body` that this constraint is attached to. + * + * @property bodyA + * @type body + * @default null + */ + bodyA?: IBodyDefinition; + + /** + * The second possible `Body` that this constraint is attached to. + * + * @property bodyB + * @type body + * @default null + */ + bodyB?: IBodyDefinition; + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + id?: number; + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Constraint" + */ + label?: string; + + /** + * A `Number` that specifies the target resting length of the constraint. + * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * + * @property length + * @type number + */ + length?: number; + + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. + * + * @property pointA + * @type vector + * @default { x: 0, y: 0 } + */ + pointA?: Vector; + + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. + * + * @property pointB + * @type vector + * @default { x: 0, y: 0 } + */ + pointB?: Vector; + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + render?: IConstraintRenderDefinition; + + /** + * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. + * A value of `1` means the constraint should be very stiff. + * A value of `0.2` means the constraint acts like a soft spring. + * + * @property stiffness + * @type number + * @default 1 + */ + stiffness?: number; + + /** + * 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 + */ + damping?: number; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "constraint" + */ + type?: string; + + } + + interface IConstraintRenderDefinition { + + /** + * A flag that indicates if the constraint should be rendered. + * + * @property visible + * @type boolean + * @default true + */ + visible?: boolean; + + /** + * The type of constraint. + * + * @property type + * @type string + * @default 'line' + */ + type?: string; + + /** + * A flag that indicates if the constraint anchors should be rendered. + * + * @property anchors + * @type boolean + * @default true + */ + anchors?: boolean; + + /** + * A hex color value that defines the line color to use when rendering the body. + * + * @property lineColor + * @type number + */ + lineColor?: number; + + /** + * A value that defines the line opacity to use when rendering the body. + * + * @property lineOpacity + * @type number + */ + lineOpacity?: number; + + /** + * A `Number` that defines the line width to use when rendering the body outline. + * + * @property lineThickness + * @type number + */ + lineThickness?: number; + + /** + * The size of the pins during rendering. + * + * @property pinSize + * @type number + */ + pinSize?: number; + + /** + * A hex color value that defines the color to use when rendering the anchors. + * + * @property anchorColor + * @type number + */ + anchorColor?: number; + + /** + * The size of the anchors during rendering. + * + * @property anchorSize + * @type number + */ + anchorSize?: number; + + } + + interface IEngineDefinition { + + /** + * An integer `Number` that specifies the number of position iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property positionIterations + * @type number + * @default 6 + */ + positionIterations?: number; + + /** + * An integer `Number` that specifies the number of velocity iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property velocityIterations + * @type number + * @default 4 + */ + velocityIterations?: number; + + /** + * An integer `Number` that specifies the number of constraint iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * The default value of `2` is usually very adequate. + * + * @property constraintIterations + * @type number + * @default 2 + */ + constraintIterations?: number; + + /** + * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. + * Sleeping can improve stability and performance, but often at the expense of accuracy. + * + * @property enableSleeping + * @type boolean + * @default false + */ + enableSleeping?: boolean; + + /** + * An `Object` containing properties regarding the timing systems of the engine. + * + * @property timing + * @type object + */ + timing?: IEngineTimingOptions; + + /** + * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. + * + * @property broadphase + * @type grid + * @default a Matter.Grid instance + */ + grid?: Grid; + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + * + * @property world + * @type world + * @default a Matter.World instance + */ + world?: World; + + } + + interface IEngineTimingOptions { + + /** + * A `Number` that specifies the global scaling factor of time for all bodies. + * A value of `0` freezes the simulation. + * A value of `0.1` gives a slow-motion effect. + * A value of `1.2` gives a speed-up effect. + * + * @property timing.timeScale + * @type number + * @default 1 + */ + timeScale: number; + + /** + * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. + * It is incremented on every `Engine.update` by the given `delta` argument. + * + * @property timing.timestamp + * @type number + * @default 0 + */ + timestamp: number; + + } + + interface IMouseConstraintDefinition { + + /** + * The `Constraint` object that is used to move the body during interaction. + * + * @property constraint + * @type constraint + */ + constraint?: ConstraintType; + + /** + * An `Object` that specifies the collision filter properties. + * The collision filter allows the user to define which types of body this mouse constraint can interact with. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter + * @type object + */ + collisionFilter?: ICollisionFilter; + + /** + * The `Body` that is currently being moved by the user, or `null` if no body. + * + * @property body + * @type body + * @default null + */ + body?: BodyType; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "constraint" + */ + type?: string; + + } + + interface IGridDefinition {} + + interface IPair { + + id: number; + bodyA: Body; + bodyB: Body; + contacts: any; + activeContacts: any; + separation: number; + isActive: boolean; + timeCreated: number; + timeUpdated: number, + inverseMass: number; + friction: number; + frictionStatic: number; + restitution: number; + slop: number; + + } + + interface ICollisionData { + + collided: boolean; + bodyA: Body; + bodyB: Body; + axisBody: Body; + axisNumber: number; + depth: number; + parentA: Body; + parentB: Body; + normal: Vector; + tangent: Vector; + penetration: Vector; + supports: Vector[]; + inverseMass: number; + friction: number; + frictionStatic: number; + restitution: number; + slop: number; + + } + + interface ICollisionPair { + + id: string; + bodyA: Body; + bodyB: Body; + activeContacts: Vector[]; + separation: number; + isActive: boolean; + confirmedActive: boolean; + isSensor: boolean; + timeCreated: number; + timeUpdated: number; + collision: ICollisionData; + inverseMass: number; + friction: number; + frictionStatic: number; + restitution: number; + slop: number; + + } + + interface ICollisionFilter { + + category: number; + mask: number; + group: number; + + } + + interface IRunnerOptions { + + /** + * A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable). + * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). + * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). + * + * @property isFixed + * @type boolean + * @default false + */ + isFixed?: boolean; + + /** + * A `Number` that specifies the time step between updates in milliseconds. + * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. + * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. + * + * @property delta + * @type number + * @default 1000 / 60 + */ + delta?: number; + } + + interface IWorldDefinition extends ICompositeDefinition { + + gravity?: Gravity; + bounds?: IBound; + + } + + interface Gravity extends Vector { + + scale: number; + + } + + interface IEvent { + + /** + * The name of the event + */ + name: string; + + /** + * The source object of the event + */ + source: T; + + } + + interface IEventComposite extends IEvent { + + /** + * EventObjects (may be a single body, constraint, composite or a mixed array of these) + */ + object: any; + + } + + interface IEventTimestamped extends IEvent { + + /** + * The engine.timing.timestamp of the event + */ + timestamp: number; + + } + + interface IEventCollision extends IEventTimestamped { + + /** + * The collision pair + */ + pairs: Array; + + } + + // -------------------------------------------------------------- + // Types + // -------------------------------------------------------------- + + type CompositeType = { + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + id: number; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "composite" + */ + type: string; + + /** + * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. + * + * @property parent + * @type composite + * @default null + */ + parent?: CompositeType; + + /** + * A flag that specifies whether the composite has been modified during the current step. + * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. + * If you need to change it manually, you should use the `Composite.setModified` method. + * + * @property isModified + * @type boolean + * @default false + */ + isModified: boolean; + + /** + * An array of `Body` that are _direct_ children of this composite. + * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. + * + * @property bodies + * @type body[] + * @default [] + */ + bodies: Array; + + /** + * An array of `Constraint` that are _direct_ children of this composite. + * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. + * + * @property constraints + * @type constraint[] + * @default [] + */ + constraints: Array; + + /** + * An array of `Composite` that are _direct_ children of this composite. + * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. + * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. + * + * @property composites + * @type composite[] + * @default [] + */ + composites: Array; + + /** + * An arbitrary `String` name to help the user identify and manage composites. + * + * @property label + * @type string + * @default "Composite" + */ + label: string; + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + plugin: any; + + } + + type ConstraintType = { + + /** + * The first possible `Body` that this constraint is attached to. + * + * @property bodyA + * @type body + * @default null + */ + bodyA?: BodyType; + + /** + * The second possible `Body` that this constraint is attached to. + * + * @property bodyB + * @type body + * @default null + */ + bodyB?: BodyType; + + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. + * + * @property pointA + * @type vector + * @default { x: 0, y: 0 } + */ + pointA: Vector; + + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. + * + * @property pointB + * @type vector + * @default { x: 0, y: 0 } + */ + pointB: Vector; + + /** + * A `Number` that specifies the target resting length of the constraint. + * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * + * @property length + * @type number + */ + length: number; + + /** + * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. + * + * @property id + * @type number + */ + id: number; + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Constraint" + */ + label: string; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "constraint" + * @readOnly + */ + type: string; + + /** + * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. + * A value of `1` means the constraint should be very stiff. + * A value of `0.2` means the constraint acts like a soft spring. + * + * @property stiffness + * @type number + * @default 1 + */ + stiffness: number; + + /** + * 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 + */ + damping: number; + + /** + * A `Number` that specifies the angular stiffness of the constraint. + * + * @property angularStiffness + * @type number + * @default 0 + */ + angularStiffness: number; + + /** + * Either the angle of BodyA, or a config value. + * + * @property angleA + * @type number + * @default 0 + */ + angleA: number; + + /** + * Either the angle of BodyB, or a config value. + * + * @property angleB + * @type number + * @default 0 + */ + angleB: number; + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + plugin: any; + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + render: IConstraintRenderDefinition; + + }; + + type BodyType = { + + /** + * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`. + * + * @property id + * @type number + */ + id: number; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "body" + * @readOnly + */ + type: string; + + /** + * An arbitrary `String` name to help the user identify and manage bodies. + * + * @property label + * @type string + * @default "Body" + */ + label: string; + + /** + * An array of bodies that make up this body. + * The first body in the array must always be a self reference to the current body instance. + * All bodies in the `parts` array together form a single rigid compound body. + * Parts are allowed to overlap, have gaps or holes or even form concave bodies. + * Parts themselves should never be added to a `World`, only the parent body should be. + * Use `Body.setParts` when setting parts to ensure correct updates of all properties. + * + * @property parts + * @type body[] + */ + parts: BodyType[]; + + /** + * An object reserved for storing plugin-specific properties. + * + * @property plugin + * @type {} + */ + plugin: any; + + /** + * A `Number` specifying the angle of the body, in radians. + * + * @property angle + * @type number + * @default 0 + */ + angle: number; + + /** + * An array of `Vector` objects that specify the convex hull of the rigid body. + * These should be provided about the origin `(0, 0)`. E.g. + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). + * The `Vector` objects are also augmented with additional properties required for efficient collision detection. + * + * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). + * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. + * + * @property vertices + * @type vector[] + */ + vertices?: Vector[]; + + /** + * A `Vector` that specifies the current world-space position of the body. + * + * @property position + * @type vector + * @default { x: 0, y: 0 } + */ + position: Vector; + + /** + * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. + * + * @property force + * @type vector + * @default { x: 0, y: 0 } + */ + force: Vector; + + /** + * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. + * + * @property torque + * @type number + * @default 0 + */ + torque: number; + + /** + * A `Vector` that specifies the position impulse. + * + * @property positionImpulse + * @type vector + * @default { x: 0, y: 0 } + */ + positionImpulse: Vector; + + /** + * A `Vector` that specifies the previous position impulse. + * + * @property previousPositionImpulse + * @type vector + * @default { x: 0, y: 0 } + */ + previousPositionImpulse: Vector; + + /** + * A `Vector` that specifies the constraint impulse. + * + * @property constraintImpulse + * @type vector + * @default { x: 0, y: 0 } + */ + constraintImpulse: Vector; + + /** + * The total number of contacts. + * + * @property totalContacts + * @type number + * @default 0 + */ + totalContacts: number; + + /** + * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). + * + * @readOnly + * @property speed + * @type number + * @default 0 + */ + speed: number; + + /** + * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). + * + * @readOnly + * @property angularSpeed + * @type number + * @default 0 + */ + angularSpeed: number; + + /** + * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property velocity + * @type vector + * @default { x: 0, y: 0 } + */ + velocity: Vector; + + /** + * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. + * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). + * + * @readOnly + * @property angularVelocity + * @type number + * @default 0 + */ + angularVelocity: number; + + /** + * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + * + * @property isSensor + * @type boolean + * @default false + */ + isSensor: boolean; + + /** + * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. + * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. + * + * @property isStatic + * @type boolean + * @default false + */ + isStatic: boolean; + + /** + * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. + * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. + * + * @property isSleeping + * @type boolean + * @default false + */ + isSleeping: boolean; + + /** + * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. + * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. + * + * @readOnly + * @property motion + * @type number + * @default 0 + */ + motion: number; + + /** + * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). + * + * @property sleepThreshold + * @type number + * @default 60 + */ + sleepThreshold: number; + + /** + * 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 + */ + density: number; + + /** + * 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 + */ + restitution: number; + + /** + * 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 + */ + friction: number; + + /** + * A `Number` that defines the static friction of the body (in the Coulomb friction model). + * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. + * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. + * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. + * + * @property frictionStatic + * @type number + * @default 0.5 + */ + frictionStatic: number; + + /** + * A `Number` that defines the air friction of the body (air resistance). + * A value of `0` means the body will never slow as it moves through space. + * The higher the value, the faster a body slows when moving through space. + * The effects of the value are non-linear. + * + * @property frictionAir + * @type number + * @default 0.01 + */ + frictionAir: number; + + /** + * An `Object` that specifies the collision filtering properties of this body. + * + * Collisions between two bodies will obey the following rules: + * - If the two bodies have the same non-zero value of `collisionFilter.group`, + * they will always collide if the value is positive, and they will never collide + * if the value is negative. + * - If the two bodies have different values of `collisionFilter.group` or if one + * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: + * + * Each body belongs to a collision category, given by `collisionFilter.category`. This + * value is used as a bit field and the category should have only one bit set, meaning that + * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 + * different collision categories available. + * + * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies + * the categories it collides with (the value is the bitwise AND value of all these categories). + * + * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's + * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` + * are both true. + * + * @property collisionFilter + * @type object + */ + collisionFilter: ICollisionFilter; + + /** + * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. + * Avoid changing this value unless you understand the purpose of `slop` in physics engines. + * The default should generally suffice, although very large bodies may require larger values for stable stacking. + * + * @property slop + * @type number + * @default 0.05 + */ + slop: number; + + /** + * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + * + * @property timeScale + * @type number + * @default 1 + */ + timeScale: number; + + /** + * Holds Body event handlers. + * + * @property events + * @type any + */ + events?: any; + + /** + * A `Bounds` object that defines the AABB region for the body. + * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. + * + * @property bounds + * @type bounds + */ + bounds: IBound; + + /** + * A Chamfer object, if this Body has them. + * + * @property chamfer + * @type any + */ + chamfer?: IChamfer; + + /** + * The radius of this Body, if it's a circle. + * + * @property circleRadius + * @type number + * @default 0 + */ + circleRadius: number; + + /** + * A `Vector` that specifies the previous position. + * + * @property positionPrev + * @type vector + * @default { x: 0, y: 0 } + */ + positionPrev: Vector; + + /** + * The previous angle. + * + * @property anglePrev + * @type number + * @default 0 + */ + anglePrev: number; + + /** + * A self reference if the body is _not_ a part of another body. + * Otherwise this is a reference to the body that this is a part of. + * See `body.parts`. + * + * @property parent + * @type body + */ + parent: BodyType; + + /** + * An array of unique axis vectors (edge normals) used for collision detection. + * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. + * They are constantly updated by `Body.update` during the simulation. + * + * @property axes + * @type vector[] + */ + axes?: Array; + + /** + * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. + * + * @property area + * @type number + * @default + */ + area: number; + + /** + * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. + * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). + * + * @property mass + * @type number + */ + mass: number; + + /** + * A `Number` that defines the inverse mass of the body (`1 / mass`). + * If you modify this value, you must also modify the `body.mass` property. + * + * @property inverseMass + * @type number + */ + inverseMass: number; + + /** + * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. + * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. + * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). + * + * @property inertia + * @type number + */ + inertia: number; + + /** + * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). + * If you modify this value, you must also modify the `body.inertia` property. + * + * @property inverseInertia + * @type number + */ + inverseInertia: number; + + /** + * Holds the original friction, mass, etc values from when this Body was made static. + * + * @property _original + * @type any + */ + _original: any; + + /** + * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. + * + * @property render + * @type object + */ + render: IBodyRenderOptions; + + /** + * A reference to the Phaser Game Object this body belongs to, if any. + * + * @property gameObject + * @type Phaser.GameObjects.GameObject + */ + gameObject?: any; + + /** + * The scale of the Body. + * + * @property scale + * @readonly + * @type vector + * @default { x: 1, y: 1 } + */ + scale: Vector; + + /** + * The center of mass of the Body. + * + * @property centerOfMass + * @type vector + * @default { x: 0, y: 0 } + */ + centerOfMass: Vector; + + /** + * The center of the body in pixel values. + * Used by Phaser for texture aligment. + * + * @property centerOffset + * @type vector + * @default { x: 0, y: 0 } + */ + centerOffset: Vector; + + /** + * Scale the influence of World gravity when applied to this body. + * + * @property gravityScale + * @type vector + * @default { x: 1, y: 1 } + */ + gravityScale: Vector; + + /** + * Will this Body ignore World gravity during the Engine update? + * + * @property ignoreGravity + * @type boolean + * @default false + */ + ignoreGravity: boolean; + + /** + * Will this Body ignore Phaser Pointer input events? + * + * @property ignorePointer + * @type boolean + * @default false + */ + ignorePointer: boolean; + + /** + * A callback that is invoked when this Body starts colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideCallback + * @type function + * @default null + */ + onCollideCallback?: Function; + + /** + * A callback that is invoked when this Body stops colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideEndCallback + * @type function + * @default null + */ + onCollideEndCallback?: Function; + + /** + * A callback that is invoked for the duration that this Body is colliding with any other Body. + * + * You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + * + * @property onCollideActiveCallback + * @type function + * @default null + */ + onCollideActiveCallback?: Function; + + /** + * A collision callback dictionary used by the `Body.setOnCollideWith` function. + * + * @property onCollideWith + * @type object + * @default null + */ + onCollideWith?: any; + + /** + * Sets the onCollideWith callback. + * + * @property setOnCollideWith + * @type Function + */ + setOnCollideWith: (body: BodyType, callback: Function) => BodyType; + + }; + + // -------------------------------------------------------------- + // Modules + // -------------------------------------------------------------- + + /** + * Installs the given plugins on the `Matter` namespace. + * This is a short-hand for `Plugin.use`, see it for more information. + * Call this function once at the start of your code, with all of the plugins you wish to install as arguments. + * Avoid calling this function multiple times unless you intend to manually control installation order. + * @method use + * @param ...plugin {Function} The plugin(s) to install on `base` (multi-argument). + */ + function use (...plugins: (Plugin | string)[]): void; + + /** + * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. + * + * @class Axes + */ + class Axes { + + /** + * Creates a new set of axes from the given vertices. + * @method fromVertices + * @param {vertices} vertices + * @return {axes} A new axes from the given vertices + */ + static fromVertices (vertices: Array): Array; + + /** + * Rotates a set of axes by the given angle. + * @method rotate + * @param {axes} axes + * @param {number} angle + */ + static rotate (axes: Array, angle: number): void; + + } + + class AxesFactory { + + /** + * Creates a new set of axes from the given vertices. + * @method fromVertices + * @param {vertices} vertices + * @return {axes} A new axes from the given vertices + */ + fromVertices (vertices: Array): Array; + + /** + * Rotates a set of axes by the given angle. + * @method rotate + * @param {axes} axes + * @param {number} angle + */ + rotate (axes: Array, angle: number): void; + + } + + /** + * 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 { + + /** + * Creates a new rigid body model with a circle hull. + * The options parameter is an object that specifies any 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 circle + * @param {number} x + * @param {number} y + * @param {number} radius + * @param {object} [options] + * @param {number} [maxSides] + * @return {body} A new circle body + */ + static circle (x: number, y: number, radius: number, options?: IBodyDefinition, maxSides?: number): BodyType; + + /** + * Creates a new rigid body model with a regular polygon hull with the given number of sides. + * The options parameter is an object that specifies any 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 polygon + * @param {number} x + * @param {number} y + * @param {number} sides + * @param {number} radius + * @param {object} [options] + * @return {body} A new regular polygon body + */ + static polygon (x: number, y: number, sides: number, radius: number, options?: IChamferableBodyDefinition): BodyType; + + /** + * Creates a new rigid body model with a rectangle hull. + * The options parameter is an object that specifies any 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 rectangle + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {object} [options] + * @return {body} A new rectangle body + */ + static rectangle (x: number, y: number, width: number, height: number, options?: IChamferableBodyDefinition): BodyType; + + /** + * Creates a new rigid body model with a trapezoid hull. + * The options parameter is an object that specifies any 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 trapezoid + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {number} slope + * @param {object} [options] + * @return {body} A new trapezoid body + */ + static trapezoid (x: number, y: number, width: number, height: number, slope: number, options?: IChamferableBodyDefinition): BodyType; + + /** + * Creates a body using the supplied vertices (or an array containing multiple sets of vertices). + * If the vertices are convex, they will pass through as supplied. + * Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available. + * Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail). + * By default the decomposition will discard collinear edges (to improve performance). + * It can also optionally discard any parts that have an area less than `minimumArea`. + * If the vertices can not be decomposed, the result will fall back to using the convex hull. + * The options parameter is an object that 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 [[vector]] vertexSets + * @param {object} [options] + * @param {bool} [flagInternal=false] + * @param {number} [removeCollinear=0.01] + * @param {number} [minimumArea=10] + * @return {body} + */ + static fromVertices (x: number, y: number, vertexSets: Array>, options?: IBodyDefinition, flagInternal?: boolean, removeCollinear?: number, minimumArea?: number): BodyType; + } + + class BodiesFactory { + + /** + * Creates a new rigid body model with a circle hull. + * The options parameter is an object that specifies any 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 circle + * @param {number} x + * @param {number} y + * @param {number} radius + * @param {object} [options] + * @param {number} [maxSides] + * @return {body} A new circle body + */ + circle (x: number, y: number, radius: number, options?: IBodyDefinition, maxSides?: number): BodyType; + + /** + * Creates a new rigid body model with a regular polygon hull with the given number of sides. + * The options parameter is an object that specifies any 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 polygon + * @param {number} x + * @param {number} y + * @param {number} sides + * @param {number} radius + * @param {object} [options] + * @return {body} A new regular polygon body + */ + polygon (x: number, y: number, sides: number, radius: number, options?: IChamferableBodyDefinition): BodyType; + + /** + * Creates a new rigid body model with a rectangle hull. + * The options parameter is an object that specifies any 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 rectangle + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {object} [options] + * @return {body} A new rectangle body + */ + rectangle (x: number, y: number, width: number, height: number, options?: IChamferableBodyDefinition): BodyType; + + /** + * Creates a new rigid body model with a trapezoid hull. + * The options parameter is an object that specifies any 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 trapezoid + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {number} slope + * @param {object} [options] + * @return {body} A new trapezoid body + */ + trapezoid (x: number, y: number, width: number, height: number, slope: number, options?: IChamferableBodyDefinition): BodyType; + + /** + * Creates a body using the supplied vertices (or an array containing multiple sets of vertices). + * If the vertices are convex, they will pass through as supplied. + * Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available. + * Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail). + * By default the decomposition will discard collinear edges (to improve performance). + * It can also optionally discard any parts that have an area less than `minimumArea`. + * If the vertices can not be decomposed, the result will fall back to using the convex hull. + * The options parameter is an object that 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 [[vector]] vertexSets + * @param {object} [options] + * @param {bool} [flagInternal=false] + * @param {number} [removeCollinear=0.01] + * @param {number} [minimumArea=10] + * @return {body} + */ + fromVertices (x: number, y: number, vertexSets: Array>, options?: IBodyDefinition, flagInternal?: boolean, removeCollinear?: number, minimumArea?: number): BodyType; + } + + /** + * 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 + */ + class Body { + + /** + * Applies a force to a body from a given world-space position, including resulting torque. + * @method applyForce + * @param {body} body + * @param {vector} position + * @param {vector} force + */ + static applyForce (body: BodyType, position: Vector, force: Vector): void; + + /** + * 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. + * See the properties section below for detailed information on what you can pass via the `options` object. + * @method create + * @param {} options + * @return {body} body + */ + static create (options: IChamferableBodyDefinition): Body; + + /** + * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. + * @method rotate + * @param {body} body + * @param {number} rotation + */ + static rotate (body: BodyType, rotation: number): void; + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. + * See `body.collisionFilter` for more information. + * @method nextGroup + * @param {bool} [isNonColliding=false] + * @return {Number} Unique group index + */ + static nextGroup (isNonColliding: boolean): number; + + /** + * Returns the next unique category bitfield (starting after the initial default category `0x0001`). + * There are 32 available. See `body.collisionFilter` for more information. + * @method nextCategory + * @return {Number} Unique category bitfield + */ + static nextCategory (): number; + + /** + * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. + * Prefer to use the actual setter functions in performance critical situations. + * @method set + * @param {body} body + * @param {} settings A property name (or map of properties and values) to set on the body. + * @param {} value The value to set if `settings` is a single property name. + */ + static set (body: BodyType, settings: any, value?: any): void; + + /** + * Sets the mass of the body. Inverse mass and density are automatically updated to reflect the change. + * @method setMass + * @param {body} body + * @param {number} mass + */ + static setMass (body: BodyType, mass: number): void; + + /** + * Sets the density of the body. Mass is automatically updated to reflect the change. + * @method setDensity + * @param {body} body + * @param {number} density + */ + static setDensity (body: BodyType, density: number): void; + + /** + * Sets the moment of inertia (i.e. second moment of area) of the body of the body. + * Inverse inertia is automatically updated to reflect the change. Mass is not changed. + * @method setInertia + * @param {body} body + * @param {number} inertia + */ + static setInertia (body: BodyType, inertia: number): void; + + /** + * 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 + */ + static setVertices (body: BodyType, vertices: Array): void; + + /** + * Sets the parts of the `body` and updates mass, inertia and centroid. + * Each part will have its parent set to `body`. + * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` + * Note that this method will ensure that the first part in `body.parts` will always be the `body`. + * @method setParts + * @param {body} body + * @param [body] parts + * @param {bool} [autoHull=true] + */ + static setParts (body: BodyType, parts: BodyType[], autoHull?: boolean): void; + + /** + * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. + * @method setPosition + * @param {body} body + * @param {vector} position + */ + static setPosition (body: BodyType, position: Vector): void; + + /** + * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. + * @method setAngle + * @param {body} body + * @param {number} angle + */ + static setAngle (body: BodyType, angle: number): void; + + /** + * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setVelocity + * @param {body} body + * @param {vector} velocity + */ + static setVelocity (body: BodyType, velocity: Vector): void; + + /** + * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setAngularVelocity + * @param {body} body + * @param {number} velocity + */ + static setAngularVelocity (body: BodyType, velocity: number): void; + + /** + * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. + * @method setStatic + * @param {body} body + * @param {bool} isStatic + */ + static setStatic (body: BodyType, isStatic: boolean): void; + + /** + * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). + * @method scale + * @param {body} body + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} [point] + */ + static scale (body: BodyType, scaleX: number, scaleY: number, point?: Vector): void; + + /** + * Moves a body by a given vector relative to its current position, without imparting any velocity. + * @method translate + * @param {body} body + * @param {vector} translation + */ + static translate (body: BodyType, translation: Vector): void; + + /** + * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. + * @method update + * @param {body} body + * @param {number} deltaTime + * @param {number} timeScale + * @param {number} correction + */ + static update (body: BodyType, deltaTime: number, timeScale: number, correction: number): void; + + } + + class BodyFactory { + + /** + * Applies a force to a body from a given world-space position, including resulting torque. + * @method applyForce + * @param {body} body + * @param {vector} position + * @param {vector} force + */ + applyForce (body: BodyType, position: Vector, force: Vector): void; + + /** + * 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. + * See the properties section below for detailed information on what you can pass via the `options` object. + * @method create + * @param {} options + * @return {body} body + */ + create (options: IChamferableBodyDefinition): BodyType; + + /** + * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. + * @method rotate + * @param {body} body + * @param {number} rotation + */ + rotate (body: BodyType, rotation: number): void; + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide. + * See `body.collisionFilter` for more information. + * @method nextGroup + * @param {bool} [isNonColliding=false] + * @return {Number} Unique group index + */ + nextGroup (isNonColliding: boolean): number; + + /** + * Returns the next unique category bitfield (starting after the initial default category `0x0001`). + * There are 32 available. See `body.collisionFilter` for more information. + * @method nextCategory + * @return {Number} Unique category bitfield + */ + nextCategory (): number; + + /** + * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. + * Prefer to use the actual setter functions in performance critical situations. + * @method set + * @param {body} body + * @param {} settings A property name (or map of properties and values) to set on the body. + * @param {} value The value to set if `settings` is a single property name. + */ + set (body: BodyType, settings: any, value?: any): void; + + /** + * Sets the mass of the body. Inverse mass and density are automatically updated to reflect the change. + * @method setMass + * @param {body} body + * @param {number} mass + */ + setMass (body: BodyType, mass: number): void; + + /** + * Sets the density of the body. Mass is automatically updated to reflect the change. + * @method setDensity + * @param {body} body + * @param {number} density + */ + setDensity (body: BodyType, density: number): void; + + /** + * Sets the moment of inertia (i.e. second moment of area) of the body of the body. + * Inverse inertia is automatically updated to reflect the change. Mass is not changed. + * @method setInertia + * @param {body} body + * @param {number} inertia + */ + setInertia (body: BodyType, inertia: number): void; + + /** + * 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 + */ + setVertices (body: BodyType, vertices: Array): void; + + /** + * Sets the parts of the `body` and updates mass, inertia and centroid. + * Each part will have its parent set to `body`. + * By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.` + * Note that this method will ensure that the first part in `body.parts` will always be the `body`. + * @method setParts + * @param {body} body + * @param [body] parts + * @param {bool} [autoHull=true] + */ + setParts (body: BodyType, parts: BodyType[], autoHull?: boolean): void; + + /** + * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. + * @method setPosition + * @param {body} body + * @param {vector} position + */ + setPosition (body: BodyType, position: Vector): void; + + /** + * Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged. + * @method setAngle + * @param {body} body + * @param {number} angle + */ + setAngle (body: BodyType, angle: number): void; + + /** + * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setVelocity + * @param {body} body + * @param {vector} velocity + */ + setVelocity (body: BodyType, velocity: Vector): void; + + /** + * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. + * @method setAngularVelocity + * @param {body} body + * @param {number} velocity + */ + setAngularVelocity (body: BodyType, velocity: number): void; + + /** + * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. + * @method setStatic + * @param {body} body + * @param {bool} isStatic + */ + setStatic (body: BodyType, isStatic: boolean): void; + + /** + * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). + * @method scale + * @param {body} body + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} [point] + */ + scale (body: BodyType, scaleX: number, scaleY: number, point?: Vector): void; + + /** + * Moves a body by a given vector relative to its current position, without imparting any velocity. + * @method translate + * @param {body} body + * @param {vector} translation + */ + translate (body: BodyType, translation: Vector): void; + + /** + * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. + * @method update + * @param {body} body + * @param {number} deltaTime + * @param {number} timeScale + * @param {number} correction + */ + update (body: BodyType, deltaTime: number, timeScale: number, correction: number): void; + + } + + /** + * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). + * + * @class Bounds + */ + class Bounds { + + /** + * Creates a new axis-aligned bounding box (AABB) for the given vertices. + * @method create + * @param {vertices} vertices + * @return {IBound} A new bounds object + */ + static create (vertices: Vertices): IBound; + + /** + * Updates bounds using the given vertices and extends the bounds given a velocity. + * @method update + * @param {IBound} bounds + * @param {vertices} vertices + * @param {vector} velocity + */ + static update (bounds: IBound, vertices: Vertices, velocity: Vector): void; + + /** + * Returns true if the bounds contains the given point. + * @method contains + * @param {IBound} bounds + * @param {vector} point + * @return {boolean} True if the bounds contain the point, otherwise false + */ + static contains (bounds: IBound, point: Vector): boolean; + + /** + * Returns true if the two bounds intersect. + * @method overlaps + * @param {IBound} boundsA + * @param {IBound} boundsB + * @return {boolean} True if the bounds overlap, otherwise false + */ + static overlaps (boundsA: IBound, boundsB: IBound): boolean; + + /** + * Translates the bounds by the given vector. + * @method translate + * @param {IBound} bounds + * @param {vector} vector + */ + static translate (bounds: IBound, vector: Vector): void; + + /** + * Shifts the bounds to the given position. + * @method shift + * @param {IBound} bounds + * @param {vector} position + */ + static shift (bounds: IBound, position: Vector): void; + + } + + class BoundsFactory { + + /** + * Creates a new axis-aligned bounding box (AABB) for the given vertices. + * @method create + * @param {vertices} vertices + * @return {IBound} A new bounds object + */ + create (vertices: Vertices): IBound; + + /** + * Updates bounds using the given vertices and extends the bounds given a velocity. + * @method update + * @param {IBound} bounds + * @param {vertices} vertices + * @param {vector} velocity + */ + update (bounds: IBound, vertices: Vertices, velocity: Vector): void; + + /** + * Returns true if the bounds contains the given point. + * @method contains + * @param {IBound} bounds + * @param {vector} point + * @return {boolean} True if the bounds contain the point, otherwise false + */ + contains (bounds: IBound, point: Vector): boolean; + + /** + * Returns true if the two bounds intersect. + * @method overlaps + * @param {IBound} boundsA + * @param {IBound} boundsB + * @return {boolean} True if the bounds overlap, otherwise false + */ + overlaps (boundsA: IBound, boundsB: IBound): boolean; + + /** + * Translates the bounds by the given vector. + * @method translate + * @param {IBound} bounds + * @param {vector} vector + */ + translate (bounds: IBound, vector: Vector): void; + + /** + * Shifts the bounds to the given position. + * @method shift + * @param {IBound} bounds + * @param {vector} position + */ + shift (bounds: IBound, position: Vector): void; + + } + + /** + * 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 + */ + class Composite { + + /** + * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. + * Triggers `beforeAdd` and `afterAdd` events on the `composite`. + * @method add + * @param {ICompositeDefinition} composite + * @param {} object + * @return {composite} The original composite with the objects added + */ + static add (composite: CompositeType, object: BodyType | CompositeType | ConstraintType): CompositeType; + + /** + * Returns all bodies in the given composite, including all bodies in its children, recursively. + * @method allBodies + * @param {composite} composite + * @return {body[]} All the bodies + */ + static allBodies (composite: CompositeType): Array; + + /** + * Returns all composites in the given composite, including all composites in its children, recursively. + * @method allComposites + * @param {composite} composite + * @return {composite[]} All the composites + */ + static allComposites (composite: CompositeType): Array; + + /** + * Returns all constraints in the given composite, including all constraints in its children, recursively. + * @method allConstraints + * @param {composite} composite + * @return {constraint[]} All the constraints + */ + static allConstraints (composite: CompositeType): Array; + + /** + * Removes all bodies, constraints and composites from the given composite. + * Optionally clearing its children recursively. + * @method clear + * @param {composite} composite + * @param {boolean} keepStatic + * @param {boolean} [deep=false] + */ + static clear (composite: CompositeType, keepStatic: boolean, deep?: boolean): void; + + /** + * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. + * See the properites section below for detailed information on what you can pass via the `options` object. + * @method create + * @param {} [options] + * @return {composite} A new composite + */ + static create (options?: ICompositeDefinition): CompositeType; + + /** + * Searches the composite recursively for an object matching the type and id supplied, null if not found. + * @method get + * @param {composite} composite + * @param {number} id + * @param {string} type + * @return {object} The requested object, if found + */ + static get (composite: CompositeType, id: number, type: string): BodyType | CompositeType | ConstraintType; + + /** + * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). + * @method move + * @param {compositeA} compositeA + * @param {object[]} objects + * @param {compositeB} compositeB + * @return {composite} Returns compositeA + */ + static move (compositeA: CompositeType, objects: Array, compositeB: CompositeType): CompositeType; + + /** + * Assigns new ids for all objects in the composite, recursively. + * @method rebase + * @param {composite} composite + * @return {composite} Returns composite + */ + static rebase (composite: CompositeType): CompositeType; + + /** + * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. + * Optionally searching its children recursively. + * Triggers `beforeRemove` and `afterRemove` events on the `composite`. + * @method remove + * @param {composite} composite + * @param {} object + * @param {boolean} [deep=false] + * @return {composite} The original composite with the objects removed + */ + static remove (composite: CompositeType, object: BodyType | CompositeType | ConstraintType, deep?: boolean): CompositeType; + + /** + * Sets the composite's `isModified` flag. + * If `updateParents` is true, all parents will be set (default: false). + * If `updateChildren` is true, all children will be set (default: false). + * @method setModified + * @param {composite} composite + * @param {boolean} isModified + * @param {boolean} [updateParents=false] + * @param {boolean} [updateChildren=false] + */ + static setModified (composite: CompositeType, isModified: boolean, updateParents?: boolean, updateChildren?: boolean): void; + + /** + * Translates all children in the composite by a given vector relative to their current positions, + * without imparting any velocity. + * @method translate + * @param {composite} composite + * @param {vector} translation + * @param {bool} [recursive=true] + */ + static translate (composite: CompositeType, translation: Vector, recursive?: boolean): void; + + /** + * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. + * @method rotate + * @param {composite} composite + * @param {number} rotation + * @param {vector} point + * @param {bool} [recursive=true] + */ + static rotate (composite: CompositeType, rotation: number, point: Vector, recursive?: boolean): void; + + /** + * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. + * @method scale + * @param {composite} composite + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + * @param {bool} [recursive=true] + */ + static scale (composite: CompositeType, scaleX: number, scaleY: number, point: Vector, recursive?: boolean): void; + + } + + class CompositeFactory { + + /** + * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. + * Triggers `beforeAdd` and `afterAdd` events on the `composite`. + * @method add + * @param {ICompositeDefinition} composite + * @param {} object + * @return {composite} The original composite with the objects added + */ + add (composite: CompositeType, object: BodyType | CompositeType | ConstraintType): CompositeType; + + /** + * Returns all bodies in the given composite, including all bodies in its children, recursively. + * @method allBodies + * @param {composite} composite + * @return {body[]} All the bodies + */ + allBodies (composite: CompositeType): Array; + + /** + * Returns all composites in the given composite, including all composites in its children, recursively. + * @method allComposites + * @param {composite} composite + * @return {composite[]} All the composites + */ + allComposites (composite: CompositeType): Array; + + /** + * Returns all constraints in the given composite, including all constraints in its children, recursively. + * @method allConstraints + * @param {composite} composite + * @return {constraint[]} All the constraints + */ + allConstraints (composite: CompositeType): Array; + + /** + * Removes all bodies, constraints and composites from the given composite. + * Optionally clearing its children recursively. + * @method clear + * @param {composite} composite + * @param {boolean} keepStatic + * @param {boolean} [deep=false] + */ + clear (composite: CompositeType, keepStatic: boolean, deep?: boolean): void; + + /** + * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. + * See the properites section below for detailed information on what you can pass via the `options` object. + * @method create + * @param {} [options] + * @return {composite} A new composite + */ + create (options?: ICompositeDefinition): CompositeType; + + /** + * Searches the composite recursively for an object matching the type and id supplied, null if not found. + * @method get + * @param {composite} composite + * @param {number} id + * @param {string} type + * @return {object} The requested object, if found + */ + get (composite: CompositeType, id: number, type: string): BodyType | CompositeType | ConstraintType; + + /** + * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). + * @method move + * @param {compositeA} compositeA + * @param {object[]} objects + * @param {compositeB} compositeB + * @return {composite} Returns compositeA + */ + move (compositeA: CompositeType, objects: Array, compositeB: CompositeType): CompositeType; + + /** + * Assigns new ids for all objects in the composite, recursively. + * @method rebase + * @param {composite} composite + * @return {composite} Returns composite + */ + rebase (composite: CompositeType): CompositeType; + + /** + * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. + * Optionally searching its children recursively. + * Triggers `beforeRemove` and `afterRemove` events on the `composite`. + * @method remove + * @param {composite} composite + * @param {} object + * @param {boolean} [deep=false] + * @return {composite} The original composite with the objects removed + */ + remove (composite: CompositeType, object: BodyType | CompositeType | ConstraintType, deep?: boolean): CompositeType; + + /** + * Sets the composite's `isModified` flag. + * If `updateParents` is true, all parents will be set (default: false). + * If `updateChildren` is true, all children will be set (default: false). + * @method setModified + * @param {composite} composite + * @param {boolean} isModified + * @param {boolean} [updateParents=false] + * @param {boolean} [updateChildren=false] + */ + setModified (composite: CompositeType, isModified: boolean, updateParents?: boolean, updateChildren?: boolean): void; + + /** + * Translates all children in the composite by a given vector relative to their current positions, + * without imparting any velocity. + * @method translate + * @param {composite} composite + * @param {vector} translation + * @param {bool} [recursive=true] + */ + translate (composite: CompositeType, translation: Vector, recursive?: boolean): void; + + /** + * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. + * @method rotate + * @param {composite} composite + * @param {number} rotation + * @param {vector} point + * @param {bool} [recursive=true] + */ + rotate (composite: CompositeType, rotation: number, point: Vector, recursive?: boolean): void; + + /** + * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. + * @method scale + * @param {composite} composite + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + * @param {bool} [recursive=true] + */ + scale (composite: CompositeType, scaleX: number, scaleY: number, point: Vector, recursive?: boolean): void; + + } + + /** + * 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 + */ + class Composites { + + /** + * Creates a composite with simple car setup of bodies and constraints. + * @method car + * @param {number} xx + * @param {number} yy + * @param {number} width + * @param {number} height + * @param {number} wheelSize + * @return {composite} A new composite car body + */ + static car (xx: number, yy: number, width: number, height: number, wheelSize: number): CompositeType; + + /** + * Chains all bodies in the given composite together using constraints. + * @method chain + * @param {composite} composite + * @param {number} xOffsetA + * @param {number} yOffsetA + * @param {number} xOffsetB + * @param {number} yOffsetB + * @param {object} options + * @return {composite} A new composite containing objects chained together with constraints + */ + static chain (composite: CompositeType, xOffsetA: number, yOffsetA: number, xOffsetB: number, yOffsetB: number, options: any): CompositeType; + + /** + * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. + * @method mesh + * @param {composite} composite + * @param {number} columns + * @param {number} rows + * @param {boolean} crossBrace + * @param {object} options + * @return {composite} The composite containing objects meshed together with constraints + */ + static mesh (composite: CompositeType, columns: number, rows: number, crossBrace: boolean, options: any): CompositeType; + + /** + * Creates a composite with a Newton's Cradle setup of bodies and constraints. + * @method newtonsCradle + * @param {number} xx + * @param {number} yy + * @param {number} number + * @param {number} size + * @param {number} length + * @return {composite} A new composite newtonsCradle body + */ + static newtonsCradle (xx: number, yy: number, number: number, size: number, length: number): CompositeType; + + /** + * Create a new composite containing bodies created in the callback in a pyramid arrangement. + * This function uses the body's bounds to prevent overlaps. + * @method pyramid + * @param {number} xx + * @param {number} yy + * @param {number} columns + * @param {number} rows + * @param {number} columnGap + * @param {number} rowGap + * @param {function} callback + * @return {composite} A new composite containing objects created in the callback + */ + static pyramid (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; + + /** + * Creates a simple soft body like object. + * @method softBody + * @param {number} xx + * @param {number} yy + * @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 + */ + static softBody (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, crossBrace: boolean, particleRadius: number, particleOptions: any, constraintOptions: any): CompositeType; + + /** + * Create a new composite containing bodies created in the callback in a grid arrangement. + * This function uses the body's bounds to prevent overlaps. + * @method stack + * @param {number} xx + * @param {number} yy + * @param {number} columns + * @param {number} rows + * @param {number} columnGap + * @param {number} rowGap + * @param {function} callback + * @return {composite} A new composite containing objects created in the callback + */ + static stack (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; + + } + + class CompositesFactory { + + /** + * Creates a composite with simple car setup of bodies and constraints. + * @method car + * @param {number} xx + * @param {number} yy + * @param {number} width + * @param {number} height + * @param {number} wheelSize + * @return {composite} A new composite car body + */ + car (xx: number, yy: number, width: number, height: number, wheelSize: number): CompositeType; + + /** + * Chains all bodies in the given composite together using constraints. + * @method chain + * @param {composite} composite + * @param {number} xOffsetA + * @param {number} yOffsetA + * @param {number} xOffsetB + * @param {number} yOffsetB + * @param {object} options + * @return {composite} A new composite containing objects chained together with constraints + */ + chain (composite: CompositeType, xOffsetA: number, yOffsetA: number, xOffsetB: number, yOffsetB: number, options: any): CompositeType; + + /** + * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. + * @method mesh + * @param {composite} composite + * @param {number} columns + * @param {number} rows + * @param {boolean} crossBrace + * @param {object} options + * @return {composite} The composite containing objects meshed together with constraints + */ + mesh (composite: CompositeType, columns: number, rows: number, crossBrace: boolean, options: any): CompositeType; + + /** + * Creates a composite with a Newton's Cradle setup of bodies and constraints. + * @method newtonsCradle + * @param {number} xx + * @param {number} yy + * @param {number} number + * @param {number} size + * @param {number} length + * @return {composite} A new composite newtonsCradle body + */ + newtonsCradle (xx: number, yy: number, number: number, size: number, length: number): CompositeType; + + /** + * Create a new composite containing bodies created in the callback in a pyramid arrangement. + * This function uses the body's bounds to prevent overlaps. + * @method pyramid + * @param {number} xx + * @param {number} yy + * @param {number} columns + * @param {number} rows + * @param {number} columnGap + * @param {number} rowGap + * @param {function} callback + * @return {composite} A new composite containing objects created in the callback + */ + pyramid (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; + + /** + * Creates a simple soft body like object. + * @method softBody + * @param {number} xx + * @param {number} yy + * @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 + */ + softBody (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, crossBrace: boolean, particleRadius: number, particleOptions: any, constraintOptions: any): CompositeType; + + /** + * Create a new composite containing bodies created in the callback in a grid arrangement. + * This function uses the body's bounds to prevent overlaps. + * @method stack + * @param {number} xx + * @param {number} yy + * @param {number} columns + * @param {number} rows + * @param {number} columnGap + * @param {number} rowGap + * @param {function} callback + * @return {composite} A new composite containing objects created in the callback + */ + stack (xx: number, yy: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): CompositeType; + + } + + /** + * 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 + */ + class Constraint { + + /** + * Creates a new constraint. + * 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 {} options + * @return {constraint} constraint + */ + static create (options: IConstraintDefinition): ConstraintType; + + } + + class ConstraintFactory { + + /** + * Creates a new constraint. + * 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 {} options + * @return {constraint} constraint + */ + create (options: IConstraintDefinition): ConstraintType; + + } + + /** + * 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 + */ + class Engine { + + /** + * Clears the engine including the world, pairs and broadphase. + * @method clear + * @param {engine} engine + */ + static clear (engine: Engine): void; + + /** + * 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 {HTMLElement} element + * @param {object} [options] + * @return {engine} engine + * @deprecated + */ + static create (element?: HTMLElement | IEngineDefinition, options?: IEngineDefinition): 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 + * @deprecated + */ + static create (options?: IEngineDefinition): Engine; + + /** + * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. + * @method merge + * @param {engine} engineA + * @param {engine} engineB + */ + static merge (engineA: Engine, engineB: Engine): void; + + /** + * Moves the simulation forward in time by `delta` ms. + * The `correction` argument is 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` 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. + * @method update + * @param {engine} engine + * @param {number} [delta=16.666] + * @param {number} [correction=1] + */ + static update (engine: Engine, delta?: number, correction?: number): Engine; + + /** + * An alias for `Runner.run`, see `Matter.Runner` for more information. + * @method run + * @param {engine} engine + */ + static run (engine: Engine): void; + + /** + * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. + * + * @property broadphase + * @type grid + * @default a Matter.Grid instance + */ + broadphase: Grid; + + /** + * An integer `Number` that specifies the number of constraint iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * The default value of `2` is usually very adequate. + * + * @property constraintIterations + * @type number + * @default 2 + */ + constraintIterations: number; + + /** + * A flag that specifies whether the engine is running or not. + */ + enabled: boolean; + + /** + * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. + * Sleeping can improve stability and performance, but often at the expense of accuracy. + * + * @property enableSleeping + * @type boolean + * @default false + */ + enableSleeping: boolean; + + /** + * Collision pair set for this `Engine`. + */ + pairs: any; + + /** + * An integer `Number` that specifies the number of position iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property positionIterations + * @type number + * @default 6 + */ + positionIterations: number; + + /** + * An `Object` containing properties regarding the timing systems of the engine. + * + * @property timing + * @type object + */ + timing: IEngineTimingOptions; + + /** + * An integer `Number` that specifies the number of velocity iterations to perform each update. + * The higher the value, the higher quality the simulation will be at the expense of performance. + * + * @property velocityIterations + * @type number + * @default 4 + */ + velocityIterations: number; + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + * + * @property world + * @type world + * @default a Matter.World instance + */ + world: World; + + } + + /** + * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. + * + * @class Grid + */ + class Grid { + + /** + * Creates a new grid. + * @method create + * @param {} options + * @return {grid} A new grid + */ + static create (options?: IGridDefinition): Grid; + + /** + * Updates the grid. + * @method update + * @param {grid} grid + * @param {body[]} bodies + * @param {engine} engine + * @param {boolean} forceUpdate + */ + static update (grid: Grid, bodies: Array, engine: Engine, forceUpdate: boolean): void; + + /** + * Clears the grid. + * @method clear + * @param {grid} grid + */ + static clear (grid: Grid): void; + + } + + class GridFactory { + + /** + * Creates a new grid. + * @method create + * @param {} options + * @return {grid} A new grid + */ + create (options?: IGridDefinition): Grid; + + /** + * Updates the grid. + * @method update + * @param {grid} grid + * @param {body[]} bodies + * @param {engine} engine + * @param {boolean} forceUpdate + */ + update (grid: Grid, bodies: Array, engine: Engine, forceUpdate: boolean): void; + + /** + * Clears the grid. + * @method clear + * @param {grid} grid + */ + clear (grid: Grid): void; + + } + + /** + * The `Matter.MouseConstraint` module contains methods for creating mouse constraints. + * Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch. + * + * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). + * + * @class MouseConstraint + */ + class MouseConstraint { + + /** + * Creates a new mouse constraint. + * 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 {engine} engine + * @param {} options + * @return {MouseConstraint} A new MouseConstraint + */ + static create (engine: Engine, options?: IMouseConstraintDefinition): MouseConstraint; + + /** + * The `Constraint` object that is used to move the body during interaction. + * + * @property constraint + * @type constraint + */ + constraint: ConstraintType; + + /** + * An `Object` that specifies the collision filter properties. + * The collision filter allows the user to define which types of body this mouse constraint can interact with. + * See `body.collisionFilter` for more information. + * + * @property collisionFilter + * @type object + */ + collisionFilter: ICollisionFilter; + + /** + * The `Body` that is currently being moved by the user, or `null` if no body. + * + * @property body + * @type body + * @default null + */ + body: BodyType; + + /** + * A `String` denoting the type of object. + * + * @property type + * @type string + * @default "constraint" + */ + type: string; + + } + + /** + * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. + * + * @class Pairs + */ + class Pairs { + + /** + * Clears the given pairs structure. + * @method clear + * @param {pairs} pairs + * @return {pairs} pairs + */ + static clear (pairs: any): any; + } + + class PairsFactory { + + /** + * Clears the given pairs structure. + * @method clear + * @param {pairs} pairs + * @return {pairs} pairs + */ + clear (pairs: any): any; + } + + /** + * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. + * + * @class Pair + */ + class Pair { + + /** + * Creates a pair. + * @method create + * @param {ICollisionData} collision + * @param {number} timestamp + * @return {IPair} A new pair + */ + static create (collision: ICollisionData, timestamp: number): IPair; + + /** + * Updates a pair given a collision. + * @method update + * @param {IPair} pair + * @param {ICollisionData} collision + * @param {number} timestamp + */ + static update (pair: IPair, collision: ICollisionData, timestamp: number): void; + + /** + * Set a pair as active or inactive. + * @method setActive + * @param {IPair} pair + * @param {boolean} isActive + * @param {number} timestamp + */ + static setActive (pair: IPair, isActive: boolean, timestamp: number): void; + + /** + * Get the id for the given pair. + * @method id + * @param {Body} bodyA + * @param {Body} bodyB + * @return {string} Unique pairId + */ + static id (bodyA: BodyType, bodyB: BodyType): string; + + } + + class PairFactory { + + /** + * Creates a pair. + * @method create + * @param {ICollisionData} collision + * @param {number} timestamp + * @return {IPair} A new pair + */ + create (collision: ICollisionData, timestamp: number): IPair; + + /** + * Updates a pair given a collision. + * @method update + * @param {IPair} pair + * @param {ICollisionData} collision + * @param {number} timestamp + */ + update (pair: IPair, collision: ICollisionData, timestamp: number): void; + + /** + * Set a pair as active or inactive. + * @method setActive + * @param {IPair} pair + * @param {boolean} isActive + * @param {number} timestamp + */ + setActive (pair: IPair, isActive: boolean, timestamp: number): void; + + /** + * Get the id for the given pair. + * @method id + * @param {Body} bodyA + * @param {Body} bodyB + * @return {string} Unique pairId + */ + id (bodyA: BodyType, bodyB: BodyType): string; + + } + + /** + * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. + * + * @class Detector + */ + class Detector { + + /** + * Finds all collisions given a list of pairs. + * @method collisions + * @param {pair[]} broadphasePairs + * @param {engine} engine + * @return {ICollisionData[]} collisions + */ + static collisions (broadphasePairs: IPair[], engine: Engine): ICollisionData[]; + + /** + * Returns `true` if both supplied collision filters will allow a collision to occur. + * See `body.collisionFilter` for more information. + * @method canCollide + * @param {} filterA + * @param {} filterB + * @return {bool} `true` if collision can occur + */ + static canCollide (filterA: ICollisionFilter, filterB: ICollisionFilter): boolean; + + } + + class DetectorFactory { + + /** + * Finds all collisions given a list of pairs. + * @method collisions + * @param {pair[]} broadphasePairs + * @param {engine} engine + * @return {ICollisionData[]} collisions + */ + collisions (broadphasePairs: IPair[], engine: Engine): ICollisionData[]; + + /** + * Returns `true` if both supplied collision filters will allow a collision to occur. + * See `body.collisionFilter` for more information. + * @method canCollide + * @param {} filterA + * @param {} filterB + * @return {bool} `true` if collision can occur + */ + canCollide (filterA: ICollisionFilter, filterB: ICollisionFilter): boolean; + + } + + /** + * The `Matter.Resolver` module contains methods for resolving collision pairs. + * + * @class Resolver + */ + class Resolver { + + /** + * Prepare pairs for position solving. + * @method preSolvePosition + * @param {pair[]} pairs + */ + static preSolvePosition (pairs: IPair[]): void; + + /** + * Find a solution for pair positions. + * @method solvePosition + * @param {pair[]} pairs + * @param {body[]} bodies + * @param {number} timeScale + */ + static solvePosition (pairs: IPair[], bodies: BodyType[], timeScale: number): void; + + /** + * Apply position resolution. + * @method postSolvePosition + * @param {body[]} bodies + */ + static postSolvePosition (bodies: BodyType[]): void; + + /** + * Prepare pairs for velocity solving. + * @method preSolveVelocity + * @param {pair[]} pairs + */ + static preSolveVelocity (pairs: IPair[]): void; + + /** + * Find a solution for pair velocities. + * @method solveVelocity + * @param {pair[]} pairs + * @param {number} timeScale + */ + static solveVelocity (pairs: IPair[], timeScale: number): void; + + } + + class ResolverFactory { + + /** + * Prepare pairs for position solving. + * @method preSolvePosition + * @param {pair[]} pairs + */ + preSolvePosition (pairs: IPair[]): void; + + /** + * Find a solution for pair positions. + * @method solvePosition + * @param {pair[]} pairs + * @param {body[]} bodies + * @param {number} timeScale + */ + solvePosition (pairs: IPair[], bodies: BodyType[], timeScale: number): void; + + /** + * Apply position resolution. + * @method postSolvePosition + * @param {body[]} bodies + */ + postSolvePosition (bodies: BodyType[]): void; + + /** + * Prepare pairs for velocity solving. + * @method preSolveVelocity + * @param {pair[]} pairs + */ + preSolveVelocity (pairs: IPair[]): void; + + /** + * Find a solution for pair velocities. + * @method solveVelocity + * @param {pair[]} pairs + * @param {number} timeScale + */ + solveVelocity (pairs: IPair[], timeScale: number): void; + + } + + /** + * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. + * + * @class SAT + */ + class SAT { + + /** + * Detect collision between two bodies using the Separating Axis Theorem. + * @method collides + * @param {body} bodyA + * @param {body} bodyB + * @param {ICollisionData} previousCollision + * @return {ICollisionData} collision + */ + static collides (bodyA: BodyType, bodyB: BodyType, previousCollision: ICollisionData): ICollisionData; + + } + + class SATFactory { + + /** + * Detect collision between two bodies using the Separating Axis Theorem. + * @method collides + * @param {body} bodyA + * @param {body} bodyB + * @param {ICollisionData} previousCollision + * @return {ICollisionData} collision + */ + collides (bodyA: BodyType, bodyB: BodyType, previousCollision: ICollisionData): ICollisionData; + + } + + /** + * 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 + */ + class Query { + + /** + * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. + * @method ray + * @param {body[]} bodies + * @param {vector} startPoint + * @param {vector} endPoint + * @param {number} [rayWidth] + * @return {object[]} Collisions + */ + static ray (bodies: Array, startPoint: Vector, endPoint: Vector, rayWidth?: number): Array; + + /** + * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. + * @method region + * @param {body[]} bodies + * @param {bounds} bounds + * @param {bool} [outside=false] + * @return {body[]} The bodies matching the query + */ + static region (bodies: Array, bounds: Bounds, outside?: boolean): Array; + + /** + * Returns all bodies whose vertices contain the given point, from the given set of bodies. + * @method point + * @param {body[]} bodies + * @param {vector} point + * @return {body[]} The bodies matching the query + */ + static point (bodies: Array, point: Vector): Array; + + } + + class QueryFactory { + + /** + * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. + * @method ray + * @param {body[]} bodies + * @param {vector} startPoint + * @param {vector} endPoint + * @param {number} [rayWidth] + * @return {object[]} Collisions + */ + ray (bodies: Array, startPoint: Vector, endPoint: Vector, rayWidth?: number): Array; + + /** + * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. + * @method region + * @param {body[]} bodies + * @param {bounds} bounds + * @param {bool} [outside=false] + * @return {body[]} The bodies matching the query + */ + region (bodies: Array, bounds: Bounds, outside?: boolean): Array; + + /** + * Returns all bodies whose vertices contain the given point, from the given set of bodies. + * @method point + * @param {body[]} bodies + * @param {vector} point + * @return {body[]} The bodies matching the query + */ + point (bodies: Array, point: Vector): Array; + + } + + /** + * The `Matter.Runner` module is an optional utility which provides a game loop, + * that handles updating and rendering a `Matter.Engine` for you within a browser. + * It is intended for demo and testing purposes, but may be adequate 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. + * Note that the method `Engine.run` is an alias for `Runner.run`. + * + * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). + * + * @class Runner + */ + class Runner { + + /** + * Creates a new Runner. The options parameter is an object that specifies any properties you wish to override the defaults. + * @method create + * @param {} options + */ + static create (options: IRunnerOptions): Runner; + + /** + * Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event. + * @method run + * @param {engine} engine + */ + static run (runner: Runner, engine: Engine): Runner; + + /** + * Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event. + * @method run + * @param {engine} engine + */ + static run (engine: Engine): Runner; + + /** + * A game loop utility that updates the engine and renderer by one step (a 'tick'). + * Features delta smoothing, time correction and fixed or dynamic timing. + * Triggers `beforeTick`, `tick` and `afterTick` events on the engine. + * Consider just `Engine.update(engine, delta)` if you're using your own loop. + * @method tick + * @param {runner} runner + * @param {engine} engine + * @param {number} time + */ + static tick (runner: Runner, engine: Engine, time: number): void; + + /** + * Ends execution of `Runner.run` on the given `runner`, by canceling the animation frame request event loop. + * If you wish to only temporarily pause the engine, see `engine.enabled` instead. + * @method stop + * @param {runner} runner + */ + static stop (runner: Runner): void; + + /** + * Alias for `Runner.run`. + * @method start + * @param {runner} runner + * @param {engine} engine + */ + static start (runner: Runner, engine: Engine): void; + + /** + * A flag that specifies whether the runner is running or not. + * + * @property enabled + * @type boolean + * @default true + */ + enabled: boolean; + + /** + * A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable). + * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). + * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). + * + * @property isFixed + * @type boolean + * @default false + */ + isFixed: boolean; + + /** + * A `Number` that specifies the time step between updates in milliseconds. + * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. + * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. + * + * @property delta + * @type number + * @default 1000 / 60 + */ + delta: number; + + } + + /** + * The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies. + * + * @class Sleeping + */ + class Sleeping { + + static set (body: BodyType, isSleeping: boolean): void; + + } + + class SleepingFactory { + + set (body: BodyType, isSleeping: boolean): void; + + } + + /** + * The `Matter.Svg` module contains methods for converting SVG images into an array of vector points. + * + * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). + * + * @class Svg + */ + class Svg { + + /** + * Converts an SVG path into an array of vector points. + * If the input path forms a concave shape, you must decompose the result into convex parts before use. + * See `Bodies.fromVertices` which provides support for this. + * Note that this function is not guaranteed to support complex paths (such as those with holes). + * @method pathToVertices + * @param {SVGPathElement} path + * @param {Number} [sampleLength=15] + * @return {Vector[]} points + */ + static pathToVertices (path: SVGPathElement, sampleLength: number): Array; + + } + + class SvgFactory { + + /** + * Converts an SVG path into an array of vector points. + * If the input path forms a concave shape, you must decompose the result into convex parts before use. + * See `Bodies.fromVertices` which provides support for this. + * Note that this function is not guaranteed to support complex paths (such as those with holes). + * @method pathToVertices + * @param {SVGPathElement} path + * @param {Number} [sampleLength=15] + * @return {Vector[]} points + */ + pathToVertices (path: SVGPathElement, sampleLength: number): Array; + + } + + /** + * 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 + */ + class Vector { + + x: number; + y: number; + + /** + * Creates a new vector. + * @method create + * @param {number} x + * @param {number} y + * @return {vector} A new vector + */ + static create (x?: number, y?: number): Vector; + + /** + * Returns a new vector with `x` and `y` copied from the given `vector`. + * @method clone + * @param {vector} vector + * @return {vector} A new cloned vector + */ + static clone (vector: Vector): Vector; + + /** + * Returns the cross-product of three vectors. + * @method cross3 + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} vectorC + * @return {number} The cross product of the three vectors + */ + static cross3 (vectorA: Vector, vectorB: Vector, vectorC: Vector): number; + + /** + * Adds the two vectors. + * @method add + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} [output] + * @return {vector} A new vector of vectorA and vectorB added + */ + static add (vectorA: Vector, vectorB: Vector, output?: Vector): Vector; + + /** + * Returns the angle in radians between the two vectors relative to the x-axis. + * @method angle + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The angle in radians + */ + static angle (vectorA: Vector, vectorB: Vector): number; + + /** + * Returns the cross-product of two vectors. + * @method cross + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The cross product of the two vectors + */ + static cross (vectorA: Vector, vectorB: Vector): number; + + /** + * Divides a vector and a scalar. + * @method div + * @param {vector} vector + * @param {number} scalar + * @return {vector} A new vector divided by scalar + */ + static div (vector: Vector, scalar: number): Vector; + + /** + * Returns the dot-product of two vectors. + * @method dot + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The dot product of the two vectors + */ + static dot (vectorA: Vector, vectorB: Vector): Number; + + /** + * Returns the magnitude (length) of a vector. + * @method magnitude + * @param {vector} vector + * @return {number} The magnitude of the vector + */ + static magnitude (vector: Vector): number; + + /** + * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation). + * @method magnitudeSquared + * @param {vector} vector + * @return {number} The squared magnitude of the vector + */ + static magnitudeSquared (vector: Vector): number; + + /** + * Multiplies a vector and a scalar. + * @method mult + * @param {vector} vector + * @param {number} scalar + * @return {vector} A new vector multiplied by scalar + */ + static mult (vector: Vector, scalar: number): Vector; + + /** + * Negates both components of a vector such that it points in the opposite direction. + * @method neg + * @param {vector} vector + * @return {vector} The negated vector + */ + static neg (vector: Vector): Vector; + + /** + * Normalises a vector (such that its magnitude is `1`). + * @method normalise + * @param {vector} vector + * @return {vector} A new vector normalised + */ + static normalise (vector: Vector): Vector; + + /** + * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction. + * @method perp + * @param {vector} vector + * @param {bool} [negate=false] + * @return {vector} The perpendicular vector + */ + static perp (vector: Vector, negate?: boolean): Vector; + + /** + * Rotates the vector about (0, 0) by specified angle. + * @method rotate + * @param {vector} vector + * @param {number} angle + * @return {vector} A new vector rotated about (0, 0) + */ + static rotate (vector: Vector, angle: number): Vector; + + /** + * Rotates the vector about a specified point by specified angle. + * @method rotateAbout + * @param {vector} vector + * @param {number} angle + * @param {vector} point + * @param {vector} [output] + * @return {vector} A new vector rotated about the point + */ + static rotateAbout (vector: Vector, angle: number, point: Vector, output?: Vector): Vector; + + /** + * Subtracts the two vectors. + * @method sub + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} [output] + * @return {vector} A new vector of vectorA and vectorB subtracted + */ + static sub (vectorA: Vector, vectorB: Vector, optional?: Vector): Vector; + + } + + class VectorFactory { + + /** + * Creates a new vector. + * @method create + * @param {number} x + * @param {number} y + * @return {vector} A new vector + */ + create (x?: number, y?: number): Vector; + + /** + * Returns a new vector with `x` and `y` copied from the given `vector`. + * @method clone + * @param {vector} vector + * @return {vector} A new cloned vector + */ + clone (vector: Vector): Vector; + + /** + * Returns the cross-product of three vectors. + * @method cross3 + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} vectorC + * @return {number} The cross product of the three vectors + */ + cross3 (vectorA: Vector, vectorB: Vector, vectorC: Vector): number; + + /** + * Adds the two vectors. + * @method add + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} [output] + * @return {vector} A new vector of vectorA and vectorB added + */ + add (vectorA: Vector, vectorB: Vector, output?: Vector): Vector; + + /** + * Returns the angle in radians between the two vectors relative to the x-axis. + * @method angle + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The angle in radians + */ + angle (vectorA: Vector, vectorB: Vector): number; + + /** + * Returns the cross-product of two vectors. + * @method cross + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The cross product of the two vectors + */ + cross (vectorA: Vector, vectorB: Vector): number; + + /** + * Divides a vector and a scalar. + * @method div + * @param {vector} vector + * @param {number} scalar + * @return {vector} A new vector divided by scalar + */ + div (vector: Vector, scalar: number): Vector; + + /** + * Returns the dot-product of two vectors. + * @method dot + * @param {vector} vectorA + * @param {vector} vectorB + * @return {number} The dot product of the two vectors + */ + dot (vectorA: Vector, vectorB: Vector): number; + + /** + * Returns the magnitude (length) of a vector. + * @method magnitude + * @param {vector} vector + * @return {number} The magnitude of the vector + */ + magnitude (vector: Vector): number; + + /** + * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation). + * @method magnitudeSquared + * @param {vector} vector + * @return {number} The squared magnitude of the vector + */ + magnitudeSquared (vector: Vector): number; + + /** + * Multiplies a vector and a scalar. + * @method mult + * @param {vector} vector + * @param {number} scalar + * @return {vector} A new vector multiplied by scalar + */ + mult (vector: Vector, scalar: number): Vector; + + /** + * Negates both components of a vector such that it points in the opposite direction. + * @method neg + * @param {vector} vector + * @return {vector} The negated vector + */ + neg (vector: Vector): Vector; + + /** + * Normalises a vector (such that its magnitude is `1`). + * @method normalise + * @param {vector} vector + * @return {vector} A new vector normalised + */ + normalise (vector: Vector): Vector; + + /** + * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction. + * @method perp + * @param {vector} vector + * @param {bool} [negate=false] + * @return {vector} The perpendicular vector + */ + perp (vector: Vector, negate?: boolean): Vector; + + /** + * Rotates the vector about (0, 0) by specified angle. + * @method rotate + * @param {vector} vector + * @param {number} angle + * @return {vector} A new vector rotated about (0, 0) + */ + rotate (vector: Vector, angle: number): Vector; + + /** + * Rotates the vector about a specified point by specified angle. + * @method rotateAbout + * @param {vector} vector + * @param {number} angle + * @param {vector} point + * @param {vector} [output] + * @return {vector} A new vector rotated about the point + */ + rotateAbout (vector: Vector, angle: number, point: Vector, output?: Vector): Vector; + + /** + * Subtracts the two vectors. + * @method sub + * @param {vector} vectorA + * @param {vector} vectorB + * @param {vector} [output] + * @return {vector} A new vector of vectorA and vectorB subtracted + */ + sub (vectorA: Vector, vectorB: Vector, optional?: Vector): 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 + */ + class Vertices { + + /** + * Returns the average (mean) of the set of vertices. + * @method mean + * @param {vertices} vertices + * @return {vector} The average point + */ + static mean (vertices: Array): Array; + + /** + * Sorts the input vertices into clockwise order in place. + * @method clockwiseSort + * @param {vertices} vertices + * @return {vertices} vertices + */ + static clockwiseSort (vertices: Array): Array; + + /** + * Returns true if the vertices form a convex shape (vertices must be in clockwise order). + * @method isConvex + * @param {vertices} vertices + * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable). + */ + static isConvex (vertices: Array): boolean; + + /** + * Returns the convex hull of the input vertices as a new array of points. + * @method hull + * @param {vertices} vertices + * @return [vertex] vertices + */ + static hull (vertices: Array): Array; + + /** + * Returns the area of the set of vertices. + * @method area + * @param {vertices} vertices + * @param {bool} signed + * @return {number} The area + */ + static area (vertices: Array, signed: boolean): number; + + /** + * Returns the centre (centroid) of the set of vertices. + * @method centre + * @param {vertices} vertices + * @return {vector} The centre point + */ + static centre (vertices: Array): Vector; + + /** + * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. + * The radius parameter is a single number or an array to specify the radius for each vertex. + * @method chamfer + * @param {vertices} vertices + * @param {number[]} radius + * @param {number} quality + * @param {number} qualityMin + * @param {number} qualityMax + */ + static chamfer (vertices: Array, radius: number | Array, quality: number, qualityMin: number, qualityMax: number): void; + + /** + * Returns `true` if the `point` is inside the set of `vertices`. + * @method contains + * @param {vertices} vertices + * @param {vector} point + * @return {boolean} True if the vertices contains point, otherwise false + */ + static contains (vertices: Array, point: Vector): boolean; + + /** + * Creates a new set of `Matter.Body` compatible vertices. + * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example: + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects, + * but with some additional references required for efficient collision detection routines. + * + * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided. + * + * @method create + * @param {vector[]} points + * @param {body} body + */ + static create (points: Array, body: BodyType): Array; + + /** + * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), + * into a `Matter.Vertices` object for the given `Matter.Body`. + * For parsing SVG paths, see `Svg.pathToVertices`. + * @method fromPath + * @param {string} path + * @param {body} body + * @return {vertices} vertices + */ + static fromPath (path: string, body: BodyType): Array; + + /** + * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. + * @method inertia + * @param {vertices} vertices + * @param {number} mass + * @return {number} The polygon's moment of inertia + */ + static inertia (vertices: Array, mass: number): number; + + /** + * Rotates the set of vertices in-place. + * @method rotate + * @param {vertices} vertices + * @param {number} angle + * @param {vector} point + */ + static rotate (vertices: Array, angle: number, point: Vector): void; + + /** + * Scales the vertices from a point (default is centre) in-place. + * @method scale + * @param {vertices} vertices + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + */ + static scale (vertices: Array, scaleX: number, scaleY: number, point: Vector): void; + + /** + * Translates the set of vertices in-place. + * @method translate + * @param {vertices} vertices + * @param {vector} vector + * @param {number} scalar + */ + static translate (vertices: Array, vector: Vector, scalar: number): void; + + } + + class VerticesFactory { + + /** + * Returns the average (mean) of the set of vertices. + * @method mean + * @param {vertices} vertices + * @return {vector} The average point + */ + mean (vertices: Array): Array; + + /** + * Sorts the input vertices into clockwise order in place. + * @method clockwiseSort + * @param {vertices} vertices + * @return {vertices} vertices + */ + clockwiseSort (vertices: Array): Array; + + /** + * Returns true if the vertices form a convex shape (vertices must be in clockwise order). + * @method isConvex + * @param {vertices} vertices + * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable). + */ + isConvex (vertices: Array): boolean; + + /** + * Returns the convex hull of the input vertices as a new array of points. + * @method hull + * @param {vertices} vertices + * @return [vertex] vertices + */ + hull (vertices: Array): Array; + + /** + * Returns the area of the set of vertices. + * @method area + * @param {vertices} vertices + * @param {bool} signed + * @return {number} The area + */ + area (vertices: Array, signed: boolean): number; + + /** + * Returns the centre (centroid) of the set of vertices. + * @method centre + * @param {vertices} vertices + * @return {vector} The centre point + */ + centre (vertices: Array): Vector; + + /** + * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. + * The radius parameter is a single number or an array to specify the radius for each vertex. + * @method chamfer + * @param {vertices} vertices + * @param {number[]} radius + * @param {number} quality + * @param {number} qualityMin + * @param {number} qualityMax + */ + chamfer (vertices: Array, radius: number | Array, quality: number, qualityMin: number, qualityMax: number): void; + + /** + * Returns `true` if the `point` is inside the set of `vertices`. + * @method contains + * @param {vertices} vertices + * @param {vector} point + * @return {boolean} True if the vertices contains point, otherwise false + */ + contains (vertices: Array, point: Vector): boolean; + + /** + * Creates a new set of `Matter.Body` compatible vertices. + * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example: + * + * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + * + * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects, + * but with some additional references required for efficient collision detection routines. + * + * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided. + * + * @method create + * @param {vector[]} points + * @param {body} body + */ + create (points: Array, body: BodyType): Array; + + /** + * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), + * into a `Matter.Vertices` object for the given `Matter.Body`. + * For parsing SVG paths, see `Svg.pathToVertices`. + * @method fromPath + * @param {string} path + * @param {body} body + * @return {vertices} vertices + */ + fromPath (path: string, body: BodyType): Array; + + /** + * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. + * @method inertia + * @param {vertices} vertices + * @param {number} mass + * @return {number} The polygon's moment of inertia + */ + inertia (vertices: Array, mass: number): number; + + /** + * Rotates the set of vertices in-place. + * @method rotate + * @param {vertices} vertices + * @param {number} angle + * @param {vector} point + */ + rotate (vertices: Array, angle: number, point: Vector): void; + + /** + * Scales the vertices from a point (default is centre) in-place. + * @method scale + * @param {vertices} vertices + * @param {number} scaleX + * @param {number} scaleY + * @param {vector} point + */ + scale (vertices: Array, scaleX: number, scaleY: number, point: Vector): void; + + /** + * Translates the set of vertices in-place. + * @method translate + * @param {vertices} vertices + * @param {vector} vector + * @param {number} scalar + */ + translate (vertices: Array, vector: Vector, scalar: number): void; + + } + + /** + * The `Matter.World` module contains methods for creating and manipulating the world composite. + * A `Matter.World` is a `Matter.Composite` body, which is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`. + * A `Matter.World` has a few additional properties including `gravity` and `bounds`. + * It is important to use the functions in the `Matter.Composite` module to modify the world composite, rather than directly modifying its properties. + * There are also a few methods here that alias those in `Matter.Composite` for easier readability. + * + * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). + * + * @class World + * @extends Composite + */ + class World { + + /** + * Add objects or arrays of objects of types: Body, Constraint, Composite + * @param world + * @param body + * @returns world + */ + static add (world: World, body: BodyType | Array | CompositeType | Array | ConstraintType | Array | MouseConstraint): World; + + /** + * An alias for Composite.addBody since World is also a Composite + * @method addBody + * @param {world} world + * @param {body} body + * @return {world} The original world with the body added + */ + static addBody (world: World, body: BodyType): World; + + /** + * An alias for Composite.add since World is also a Composite + * @method addComposite + * @param {world} world + * @param {composite} composite + * @return {world} The original world with the objects from composite added + */ + static addComposite (world: World, composite: CompositeType): World; + + /** + * An alias for Composite.addConstraint since World is also a Composite + * @method addConstraint + * @param {world} world + * @param {constraint} constraint + * @return {world} The original world with the constraint added + */ + static addConstraint (world: World, constraint: ConstraintType): World; + + /** + * An alias for Composite.clear since World is also a Composite + * @method clear + * @param {world} world + * @param {boolean} keepStatic + */ + static clear (world: World, keepStatic: boolean): void; + + /** + * Creates a new world composite. The options parameter is an object that specifies any properties you wish to override the defaults. + * See the properties section below for detailed information on what you can pass via the `options` object. + * @method create + * @constructor + * @param {} options + * @return {world} A new world + */ + static create (options: IWorldDefinition): World; + + gravity: Gravity; + + bounds: Bounds; + + } + + class Events { + + /** + * Fired when a body starts sleeping (where `this` is the body). + * + * @event sleepStart + * @this {body} The body that has started sleeping + * @param {} event An event object + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: BodyType, name: "sleepStart", callback: (e: IEvent) => void): void; + + /** + * Fired when a body ends sleeping (where `this` is the body). + * + * @event sleepEnd + * @this {body} The body that has ended sleeping + * @param {} event An event object + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: BodyType, name: "sleepEnd", callback: (e: IEvent) => void): void; + + /** + * Fired when a call to `Composite.add` is made, before objects have been added. + * + * @event beforeAdd + * @param {} event An event object + * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "beforeAdd", callback: (e: IEventComposite) => void): void; + + /** + * Fired when a call to `Composite.add` is made, after objects have been added. + * + * @event afterAdd + * @param {} event An event object + * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "afterAdd", callback: (e: IEventComposite) => void): void; + + /** + * Fired when a call to `Composite.remove` is made, before objects have been removed. + * + * @event beforeRemove + * @param {} event An event object + * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "beforeRemove", callback: (e: IEventComposite) => void): void; + + /** + * Fired when a call to `Composite.remove` is made, after objects have been removed. + * + * @event afterRemove + * @param {} event An event object + * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these) + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "afterRemove", callback: (e: IEventComposite) => void): void; + + /** + * Fired after engine update and all collision events + * + * @event afterUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "afterUpdate", callback: (e: IEventTimestamped) => void): void; + + /** + * Fired just before an update + * + * @event beforeUpdate + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "beforeUpdate", callback: (e: IEventTimestamped) => void): void; + + /** + * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) + * + * @event collisionActive + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "collisionActive", callback: (e: IEventCollision) => void): void; + + /** + * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) + * + * @event collisionEnd + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "collisionEnd", callback: (e: IEventCollision) => void): void; + + /** + * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) + * + * @event collisionStart + * @param {} event An event object + * @param {} event.pairs List of affected pairs + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "collisionStart", callback: (e: IEventCollision) => void): void; + + /** + * Fired at the start of a tick, before any updates to the engine or timing + * + * @event beforeTick + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "beforeTick", callback: (e: IEventTimestamped) => void): void; + + /** + * Fired after engine timing updated, but just before update + * + * @event tick + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "tick", callback: (e: IEventTimestamped) => void): void; + + /** + * Fired at the end of a tick, after engine update and after rendering + * + * @event afterTick + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "afterTick", callback: (e: IEventTimestamped) => void): void; + + /** + * Fired before rendering + * + * @event beforeRender + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "beforeRender", callback: (e: IEventTimestamped) => void): void; + + /** + * Fired after rendering + * + * @event afterRender + * @param {} event An event object + * @param {number} event.timestamp The engine.timing.timestamp of the event + * @param {} event.source The source object of the event + * @param {} event.name The name of the event + */ + static on (obj: Engine, name: "afterRender", callback: (e: IEventTimestamped) => void): void; + + static on (obj: any, name: string, callback: (e: any) => void): void; + + /** + * Removes the given event callback. If no callback, clears all callbacks in eventNames. If no eventNames, clears all events. + * + * @param obj + * @param eventName + * @param callback + */ + static off(obj: any, eventName: string, callback: (e: any) => void): void; + + /** + * Fires all the callbacks subscribed to the given object's eventName, in the order they subscribed, if any. + * + * @param object + * @param eventNames + * @param event + */ + static trigger(object: any, eventNames: string, event?: (e: any) => void): void; + + } + + type Dependency = {name: string, range: string} | {name: string, version: string} | string; + + class Plugin { + + name: string; + version: string; + install: () => void; + for?: string; + + /** + * Registers a plugin object so it can be resolved later by name. + * @method register + * @param plugin {} The plugin to register. + * @return {object} The plugin. + */ + static register (plugin: Plugin): Plugin; + + /** + * Resolves a dependency to a plugin object from the registry if it exists. + * The `dependency` may contain a version, but only the name matters when resolving. + * @method resolve + * @param dependency {string} The dependency. + * @return {object} The plugin if resolved, otherwise `undefined`. + */ + static resolve (dependency: string): Plugin | undefined; + + /** + * Returns `true` if the object meets the minimum standard to be considered a plugin. + * This means it must define the following properties: + * - `name` + * - `version` + * - `install` + * @method isPlugin + * @param obj {} The obj to test. + * @return {boolean} `true` if the object can be considered a plugin otherwise `false`. + */ + static isPlugin (obj: {}): boolean; + + /** + * Returns a pretty printed plugin name and version. + * @method toString + * @param plugin {} The plugin. + * @return {string} Pretty printed plugin name and version. + */ + static toString (plugin: string | Plugin): string; + + /** + * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`. + * If `plugin.for` is not specified then it is assumed to be applicable. + * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`. + * @method isFor + * @param plugin {} The plugin. + * @param module {} The module. + * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`. + */ + static isFor (plugin: Plugin, module: {name?: string, [_: string]: any}): boolean; + + /** + * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`. + * For installing plugins on `Matter` see the convenience function `Matter.use`. + * Plugins may be specified either by their name or a reference to the plugin object. + * Plugins themselves may specify further dependencies, but each plugin is installed only once. + * Order is important, a topological sort is performed to find the best resulting order of installation. + * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases. + * This function logs the resulting status of each dependency in the console, along with any warnings. + * - A green tick ✅ indicates a dependency was resolved and installed. + * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies. + * - A red cross ❌ indicates a dependency could not be resolved. + * Avoid calling this function multiple times on the same module unless you intend to manually control installation order. + * @method use + * @param module {} The module install plugins on. + * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`). + */ + static use (module: {uses?: (Plugin | string)[]; [_: string]: any}, plugins: (Plugin | string)[]): void; + + /** + * Recursively finds all of a module's dependencies and returns a flat dependency graph. + * @method dependencies + * @param module {} The module. + * @return {object} A dependency graph. + */ + static dependencies (module: Dependency, tracked?: {[_: string]: string[]}): {[_: string]: string[]} | string | undefined; + + /** + * Parses a dependency string into its components. + * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`. + * See documentation for `Plugin.versionParse` for a description of the format. + * This function can also handle dependencies that are already resolved (e.g. a module object). + * @method dependencyParse + * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`. + * @return {object} The dependency parsed into its components. + */ + static dependencyParse (dependency: Dependency) : {name: string, range: string}; + + /** + * 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` + * - 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. + */ + static versionParse (range: string) : { + isRange: boolean, + version: string, + range: string, + operator: string + parts: number[], + prerelease: string, + number: number + }; + + /** + * Returns `true` if `version` satisfies the given `range`. + * See documentation for `Plugin.versionParse` for a description of the format. + * If a version or range is not specified, then any version (`*`) is assumed to satisfy. + * @method versionSatisfies + * @param version {string} The version string. + * @param range {string} The range string. + * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`. + */ + static versionSatisfies (version: string, range: string): boolean; + + } +} + +declare module 'matter' { + export = MatterJS; +} diff --git a/types/phaser.d.ts b/types/phaser.d.ts index 67d6b1f41..8f6ef1a25 100644 --- a/types/phaser.d.ts +++ b/types/phaser.d.ts @@ -1,88961 +1,88961 @@ -/// - -declare type DataEachCallback = (parent: any, key: string, value: any, ...args: any[])=>void; - -declare type ContentLoadedCallback = ()=>void; - -declare type CreateCallback = (bob: Phaser.GameObjects.Bob, index: integer)=>void; - -declare type EachContainerCallback = (item: any, ...args: any[])=>void; - -declare type LightForEach = (light: Phaser.GameObjects.Light)=>void; - -/** - * A custom function that will be responsible for wrapping the text. - */ -declare type TextStyleWordWrapCallback = (text: string, textObject: Phaser.GameObjects.Text)=>void; - -declare type CenterFunction = (triangle: Phaser.Geom.Triangle)=>void; - -declare namespace Phaser { - namespace Actions { - /** - * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. - * - * The first item isn't moved. The second item is aligned next to the first, then the third next to the second, and so on. - * @param items The array of items to be updated by this action. - * @param position The position to align the items with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function AlignTo(items: G, position: integer, offsetX?: number, offsetY?: number): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `angle` property, - * and then adds the given value to each of their `angle` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `Angle(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `angle` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function Angle(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of objects and passes each of them to the given callback. - * @param items The array of items to be updated by this action. - * @param callback The callback to be invoked. It will be passed just one argument: the item from the array. - * @param context The scope in which the callback will be invoked. - */ - function Call(items: G, callback: Phaser.Types.Actions.CallCallback, context: any): G; - - /** - * Takes an array of objects and returns the first element in the array that has properties which match - * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` - * then it would return the first item which had the property `scaleX` set to 0.5 and `alpha` set to 1. - * - * To use this with a Group: `GetFirst(group.getChildren(), compare, index)` - * @param items The array of items to be searched by this action. - * @param compare The comparison object. Each property in this object will be checked against the items of the array. - * @param index An optional offset to start searching from within the items array. Default 0. - */ - function GetFirst(items: G, compare: object, index?: integer): object | Phaser.GameObjects.GameObject; - - /** - * Takes an array of objects and returns the last element in the array that has properties which match - * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` - * then it would return the last item which had the property `scaleX` set to 0.5 and `alpha` set to 1. - * - * To use this with a Group: `GetLast(group.getChildren(), compare, index)` - * @param items The array of items to be searched by this action. - * @param compare The comparison object. Each property in this object will be checked against the items of the array. - * @param index An optional offset to start searching from within the items array. Default 0. - */ - function GetLast(items: G, compare: object, index?: integer): object | Phaser.GameObjects.GameObject; - - /** - * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, - * and then aligns them based on the grid configuration given to this action. - * @param items The array of items to be updated by this action. - * @param options The GridAlign Configuration object. - */ - function GridAlign(items: G, options: Phaser.Types.Actions.GridAlignConfig): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `alpha` property, - * and then adds the given value to each of their `alpha` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncAlpha(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `alpha` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function IncAlpha(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `x` property, - * and then adds the given value to each of their `x` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncX(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `x` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function IncX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, - * and then adds the given value to each of them. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncXY(group.getChildren(), x, y, stepX, stepY)` - * @param items The array of items to be updated by this action. - * @param x The amount to be added to the `x` property. - * @param y The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. Default x. - * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function IncXY(items: G, x: number, y?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `y` property, - * and then adds the given value to each of their `y` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `IncY(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `y` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function IncY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Circle. - * - * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param circle The Circle to position the Game Objects on. - * @param startAngle Optional angle to start position from, in radians. Default 0. - * @param endAngle Optional angle to stop position at, in radians. Default 6.28. - */ - function PlaceOnCircle(items: G, circle: Phaser.Geom.Circle, startAngle?: number, endAngle?: number): G; - - /** - * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of an Ellipse. - * - * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param ellipse The Ellipse to position the Game Objects on. - * @param startAngle Optional angle to start position from, in radians. Default 0. - * @param endAngle Optional angle to stop position at, in radians. Default 6.28. - */ - function PlaceOnEllipse(items: G, ellipse: Phaser.Geom.Ellipse, startAngle?: number, endAngle?: number): G; - - /** - * Positions an array of Game Objects on evenly spaced points of a Line. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param line The Line to position the Game Objects on. - */ - function PlaceOnLine(items: G, line: Phaser.Geom.Line): G; - - /** - * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. - * - * Placement starts from the top-left of the rectangle, and proceeds in a clockwise direction. - * If the `shift` parameter is given you can offset where placement begins. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param rect The Rectangle to position the Game Objects on. - * @param shift An optional positional offset. Default 1. - */ - function PlaceOnRectangle(items: G, rect: Phaser.Geom.Rectangle, shift?: integer): G; - - /** - * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. - * - * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param triangle The Triangle to position the Game Objects on. - * @param stepRate An optional step rate, to increase or decrease the packing of the Game Objects on the lines. Default 1. - */ - function PlaceOnTriangle(items: G, triangle: Phaser.Geom.Triangle, stepRate?: number): G; - - /** - * Play an animation with the given key, starting at the given startFrame on all Game Objects in items. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param key The name of the animation to play. - * @param startFrame The starting frame of the animation with the given key. - */ - function PlayAnimation(items: G, key: string, startFrame?: string | integer): G; - - /** - * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, - * and then adds the given value to it. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `PropertyValueInc(group.getChildren(), key, value, step)` - * @param items The array of items to be updated by this action. - * @param key The property to be updated. - * @param value The amount to be added to the property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function PropertyValueInc(items: G, key: string, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `PropertyValueSet(group.getChildren(), key, value, step)` - * @param items The array of items to be updated by this action. - * @param key The property to be updated. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function PropertyValueSet(items: G, key: string, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects and positions them at random locations within the Circle. - * - * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param circle The Circle to position the Game Objects within. - */ - function RandomCircle(items: G, circle: Phaser.Geom.Circle): G; - - /** - * Takes an array of Game Objects and positions them at random locations within the Ellipse. - * - * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param ellipse The Ellipse to position the Game Objects within. - */ - function RandomEllipse(items: G, ellipse: Phaser.Geom.Ellipse): G; - - /** - * Takes an array of Game Objects and positions them at random locations on the Line. - * - * If you wish to pass a `Phaser.GameObjects.Line` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param line The Line to position the Game Objects randomly on. - */ - function RandomLine(items: G, line: Phaser.Geom.Line): G; - - /** - * Takes an array of Game Objects and positions them at random locations within the Rectangle. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param rect The Rectangle to position the Game Objects within. - */ - function RandomRectangle(items: G, rect: Phaser.Geom.Rectangle): G; - - /** - * Takes an array of Game Objects and positions them at random locations within the Triangle. - * - * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param triangle The Triangle to position the Game Objects within. - */ - function RandomTriangle(items: G, triangle: Phaser.Geom.Triangle): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `rotation` property, - * and then adds the given value to each of their `rotation` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `Rotate(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `rotation` property (in radians). - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function Rotate(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Rotates each item around the given point by the given angle. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param point Any object with public `x` and `y` properties. - * @param angle The angle to rotate by, in radians. - */ - function RotateAround(items: G, point: object, angle: number): G; - - /** - * Rotates an array of Game Objects around a point by the given angle and distance. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param point Any object with public `x` and `y` properties. - * @param angle The angle to rotate by, in radians. - * @param distance The distance from the point of rotation in pixels. - */ - function RotateAroundDistance(items: G, point: object, angle: number, distance: number): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `scaleX` property, - * and then adds the given value to each of their `scaleX` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `ScaleX(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `scaleX` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function ScaleX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have public `scaleX` and `scaleY` properties, - * and then adds the given value to each of them. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `ScaleXY(group.getChildren(), scaleX, scaleY, stepX, stepY)` - * @param items The array of items to be updated by this action. - * @param scaleX The amount to be added to the `scaleX` property. - * @param scaleY The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. - * @param stepX This is added to the `scaleX` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `scaleY` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function ScaleXY(items: G, scaleX: number, scaleY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have a public `scaleY` property, - * and then adds the given value to each of their `scaleY` properties. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `ScaleY(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to be added to the `scaleY` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function ScaleY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `alpha` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetAlpha(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetAlpha(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `blendMode` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetBlendMode(group.getChildren(), value)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetBlendMode(items: G, value: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `depth` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetDepth(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetDepth(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Passes all provided Game Objects to the Input Manager to enable them for input with identical areas and callbacks. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param 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 hitAreaCallback A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. - */ - function SetHitArea(items: G, hitArea: any, hitAreaCallback: Phaser.Types.Input.HitAreaCallback): G; - - /** - * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetOrigin(group.getChildren(), originX, originY, stepX, stepY)` - * @param items The array of items to be updated by this action. - * @param originX The amount to set the `originX` property to. - * @param originY The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. - * @param stepX This is added to the `originX` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `originY` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetOrigin(items: G, originX: number, originY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `rotation` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetRotation(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetRotation(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScale(group.getChildren(), scaleX, scaleY, stepX, stepY)` - * @param items The array of items to be updated by this action. - * @param scaleX The amount to set the `scaleX` property to. - * @param scaleY The amount to set the `scaleY` property to. If `undefined` or `null` it uses the `scaleX` value. - * @param stepX This is added to the `scaleX` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `scaleY` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetScale(items: G, scaleX: number, scaleY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `scaleX` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScaleX(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetScaleX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `scaleY` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScaleY(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetScaleY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScrollFactor(group.getChildren(), scrollFactorX, scrollFactorY, stepX, stepY)` - * @param items The array of items to be updated by this action. - * @param scrollFactorX The amount to set the `scrollFactorX` property to. - * @param scrollFactorY The amount to set the `scrollFactorY` property to. If `undefined` or `null` it uses the `scrollFactorX` value. - * @param stepX This is added to the `scrollFactorX` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `scrollFactorY` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetScrollFactor(items: G, scrollFactorX: number, scrollFactorY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScrollFactorX(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetScrollFactorX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetScrollFactorY(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetScrollFactorY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public method setTint() and then updates it to the given value(s). You can specify tint color per corner or provide only one color value for `topLeft` parameter, in which case whole item will be tinted with that color. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param topLeft The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. - * @param topRight The tint to be applied to top-right corner of item. - * @param bottomLeft The tint to be applied to the bottom-left corner of item. - * @param bottomRight The tint to be applied to the bottom-right corner of item. - */ - function SetTint(items: G, topLeft: number, topRight?: number, bottomLeft?: number, bottomRight?: number): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `visible` - * and then sets it to the given value. - * - * To use this with a Group: `SetVisible(group.getChildren(), value)` - * @param items The array of items to be updated by this action. - * @param value The value to set the property to. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetVisible(items: G, value: boolean, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `x` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetX(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` - * and then sets them to the given values. - * - * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetXY(group.getChildren(), x, y, stepX, stepY)` - * @param items The array of items to be updated by this action. - * @param x The amount to set the `x` property to. - * @param y The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. Default x. - * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetXY(items: G, x: number, y?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; - - /** - * Takes an array of Game Objects, or any objects that have the public property `y` - * and then sets it to the given value. - * - * The optional `step` property is applied incrementally, multiplied by each item in the array. - * - * To use this with a Group: `SetY(group.getChildren(), value, step)` - * @param items The array of items to be updated by this action. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - function SetY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; - - /** - * Iterate through the items array changing the position of each element to be that of the element that came before - * it in the array (or after it if direction = 1) - * - * The first items position is set to x/y. - * - * The final x/y coords are returned - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param x The x coordinate to place the first item in the array at. - * @param y The y coordinate to place the first item in the array at. - * @param direction The iteration direction. 0 = first to last and 1 = last to first. Default 0. - * @param output An optional objec to store the final objects position in. - */ - function ShiftPosition(items: G, x: number, y: number, direction?: integer, output?: O): O; - - /** - * Shuffles the array in place. The shuffled array is both modified and returned. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - */ - function Shuffle(items: G): G; - - /** - * 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 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. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param property The property of the Game Object to interpolate. - * @param min The minimum interpolation value. - * @param max The maximum interpolation value. - * @param inc Should the values be incremented? `true` or set (`false`) Default false. - */ - function SmootherStep(items: G, property: string, min: number, max: number, inc?: boolean): G; - - /** - * 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. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param property The property of the Game Object to interpolate. - * @param min The minimum interpolation value. - * @param max The maximum interpolation value. - * @param inc Should the values be incremented? `true` or set (`false`) Default false. - */ - function SmoothStep(items: G, property: string, min: number, max: number, inc?: boolean): G; - - /** - * Takes an array of Game Objects and then modifies their `property` so the value equals, or is incremented, by the - * calculated spread value. - * - * The spread value is derived from the given `min` and `max` values and the total number of items in the array. - * - * For example, to cause an array of Sprites to change in alpha from 0 to 1 you could call: - * - * ```javascript - * Phaser.Actions.Spread(itemsArray, 'alpha', 0, 1); - * ``` - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param property The property of the Game Object to spread. - * @param min The minimum value. - * @param max The maximum value. - * @param inc Should the values be incremented? `true` or set (`false`) Default false. - */ - function Spread(items: G, property: string, min: number, max: number, inc?: boolean): G; - - /** - * Takes an array of Game Objects and toggles the visibility of each one. - * Those previously `visible = false` will become `visible = true`, and vice versa. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - */ - function ToggleVisible(items: G): G; - - /** - * Wrap each item's coordinates within a rectangle's area. - * @param items An array of Game Objects. The contents of this array are updated by this Action. - * @param rect The rectangle. - * @param padding An amount added to each side of the rectangle during the operation. Default 0. - */ - function WrapInRectangle(items: G, rect: Phaser.Geom.Rectangle, padding?: number): G; - - } - - namespace Animations { - /** - * A Frame based Animation. - * - * This consists of a key, some default values (like the frame rate) and a bunch of Frame objects. - * - * The Animation Manager creates these. Game Objects don't own an instance of these directly. - * Game Objects have the Animation Component, which are like playheads to global Animations (these objects) - * So multiple Game Objects can have playheads all pointing to this one Animation instance. - */ - class Animation extends Phaser.Events.EventEmitter { - /** - * - * @param manager A reference to the global Animation Manager - * @param key The unique identifying string for this animation. - * @param config The Animation configuration. - */ - constructor(manager: Phaser.Animations.AnimationManager, key: string, config: Phaser.Types.Animations.Animation); - - /** - * A reference to the global Animation Manager. - */ - manager: Phaser.Animations.AnimationManager; - - /** - * The unique identifying string for this animation. - */ - key: string; - - /** - * A frame based animation (as opposed to a bone based animation) - */ - type: string; - - /** - * Extract all the frame data into the frames array. - */ - frames: Phaser.Animations.AnimationFrame[]; - - /** - * The frame rate of playback in frames per second (default 24 if duration is null) - */ - frameRate: integer; - - /** - * How long the animation should play for, in milliseconds. - * If the `frameRate` property has been set then it overrides this value, - * otherwise the `frameRate` is derived from `duration`. - */ - duration: integer; - - /** - * How many ms per frame, not including frame specific modifiers. - */ - msPerFrame: integer; - - /** - * Skip frames if the time lags, or always advanced anyway? - */ - skipMissedFrames: boolean; - - /** - * The delay in ms before the playback will begin. - */ - delay: integer; - - /** - * Number of times to repeat the animation. Set to -1 to repeat forever. - */ - repeat: integer; - - /** - * The delay in ms before the a repeat play starts. - */ - repeatDelay: integer; - - /** - * Should the animation yoyo (reverse back down to the start) before repeating? - */ - yoyo: boolean; - - /** - * Should the GameObject's `visible` property be set to `true` when the animation starts to play? - */ - showOnStart: boolean; - - /** - * Should the GameObject's `visible` property be set to `false` when the animation finishes? - */ - hideOnComplete: boolean; - - /** - * Global pause. All Game Objects using this Animation instance are impacted by this property. - */ - paused: boolean; - - /** - * Add frames to the end of the animation. - * @param config [description] - */ - addFrame(config: string | Phaser.Types.Animations.AnimationFrame[]): Phaser.Animations.Animation; - - /** - * Add frame/s into the animation. - * @param index The index to insert the frame at within the animation. - * @param config [description] - */ - addFrameAt(index: integer, config: string | Phaser.Types.Animations.AnimationFrame[]): Phaser.Animations.Animation; - - /** - * Check if the given frame index is valid. - * @param index The index to be checked. - */ - checkFrame(index: integer): boolean; - - /** - * [description] - * @param component [description] - */ - protected completeAnimation(component: Phaser.GameObjects.Components.Animation): void; - - /** - * [description] - * @param component [description] - * @param includeDelay [description] Default true. - */ - protected getFirstTick(component: Phaser.GameObjects.Components.Animation, includeDelay?: boolean): void; - - /** - * Returns the AnimationFrame at the provided index - * @param index The index in the AnimationFrame array - */ - protected getFrameAt(index: integer): Phaser.Animations.AnimationFrame; - - /** - * [description] - * @param textureManager [description] - * @param frames [description] - * @param defaultTextureKey [description] - */ - getFrames(textureManager: Phaser.Textures.TextureManager, frames: string | Phaser.Types.Animations.AnimationFrame[], defaultTextureKey?: string): Phaser.Animations.AnimationFrame[]; - - /** - * [description] - * @param component [description] - */ - getNextTick(component: Phaser.GameObjects.Components.Animation): void; - - /** - * Returns the frame closest to the given progress value between 0 and 1. - * @param value A value between 0 and 1. - */ - getFrameByProgress(value: number): Phaser.Animations.AnimationFrame; - - /** - * Advance the animation frame. - * @param component The Animation Component to advance. - */ - nextFrame(component: Phaser.GameObjects.Components.Animation): void; - - /** - * Returns the animation last frame. - */ - getLastFrame(): Phaser.Animations.AnimationFrame; - - /** - * [description] - * @param component [description] - */ - previousFrame(component: Phaser.GameObjects.Components.Animation): void; - - /** - * [description] - * @param frame [description] - */ - removeFrame(frame: Phaser.Animations.AnimationFrame): Phaser.Animations.Animation; - - /** - * Removes a frame from the AnimationFrame array at the provided index - * and updates the animation accordingly. - * @param index The index in the AnimationFrame array - */ - removeFrameAt(index: integer): Phaser.Animations.Animation; - - /** - * [description] - * @param component [description] - */ - repeatAnimation(component: Phaser.GameObjects.Components.Animation): void; - - /** - * Sets the texture frame the animation uses for rendering. - * @param component [description] - */ - setFrame(component: Phaser.GameObjects.Components.Animation): void; - - /** - * Converts the animation data to JSON. - */ - toJSON(): Phaser.Types.Animations.JSONAnimation; - - /** - * [description] - */ - updateFrameSequence(): Phaser.Animations.Animation; - - /** - * [description] - */ - pause(): Phaser.Animations.Animation; - - /** - * [description] - */ - resume(): Phaser.Animations.Animation; - - /** - * [description] - */ - destroy(): void; - - } - - /** - * A single frame in an Animation sequence. - * - * An AnimationFrame consists of a reference to the Texture it uses for rendering, references to other - * frames in the animation, and index data. It also has the ability to modify the animation timing. - * - * AnimationFrames are generated automatically by the Animation class. - */ - class AnimationFrame { - /** - * - * @param textureKey The key of the Texture this AnimationFrame uses. - * @param textureFrame The key of the Frame within the Texture that this AnimationFrame uses. - * @param index The index of this AnimationFrame within the Animation sequence. - * @param frame A reference to the Texture Frame this AnimationFrame uses for rendering. - */ - constructor(textureKey: string, textureFrame: string | integer, index: integer, frame: Phaser.Textures.Frame); - - /** - * The key of the Texture this AnimationFrame uses. - */ - textureKey: string; - - /** - * The key of the Frame within the Texture that this AnimationFrame uses. - */ - textureFrame: string | integer; - - /** - * The index of this AnimationFrame within the Animation sequence. - */ - index: integer; - - /** - * A reference to the Texture Frame this AnimationFrame uses for rendering. - */ - frame: Phaser.Textures.Frame; - - /** - * Is this the first frame in an animation sequence? - */ - readonly isFirst: boolean; - - /** - * Is this the last frame in an animation sequence? - */ - readonly isLast: boolean; - - /** - * A reference to the AnimationFrame that comes before this one in the animation, if any. - */ - readonly prevFrame: Phaser.Animations.AnimationFrame; - - /** - * A reference to the AnimationFrame that comes after this one in the animation, if any. - */ - readonly nextFrame: Phaser.Animations.AnimationFrame; - - /** - * Additional time (in ms) that this frame should appear for during playback. - * The value is added onto the msPerFrame set by the animation. - */ - duration: number; - - /** - * What % through the animation does this frame come? - * This value is generated when the animation is created and cached here. - */ - readonly progress: number; - - /** - * Generates a JavaScript object suitable for converting to JSON. - */ - toJSON(): Phaser.Types.Animations.JSONAnimationFrame; - - /** - * Destroys this object by removing references to external resources and callbacks. - */ - destroy(): void; - - } - - /** - * The Animation Manager. - * - * Animations are managed by the global Animation Manager. This is a singleton class that is - * responsible for creating and delivering animations and their corresponding data to all Game Objects. - * Unlike plugins it is owned by the Game instance, not the Scene. - * - * Sprites and other Game Objects get the data they need from the AnimationManager. - */ - class AnimationManager extends Phaser.Events.EventEmitter { - /** - * - * @param game A reference to the Phaser.Game instance. - */ - constructor(game: Phaser.Game); - - /** - * A reference to the Phaser.Game instance. - */ - protected game: Phaser.Game; - - /** - * A reference to the Texture Manager. - */ - protected textureManager: Phaser.Textures.TextureManager; - - /** - * The global time scale of the Animation Manager. - * - * This scales the time delta between two frames, thus influencing the speed of time for the Animation Manager. - */ - globalTimeScale: number; - - /** - * The Animations registered in the Animation Manager. - * - * This map should be modified with the {@link #add} and {@link #create} methods of the Animation Manager. - */ - protected anims: Phaser.Structs.Map; - - /** - * Whether the Animation Manager is paused along with all of its Animations. - */ - paused: boolean; - - /** - * The name of this Animation Manager. - */ - name: string; - - /** - * Registers event listeners after the Game boots. - */ - boot(): void; - - /** - * Adds an existing Animation to the Animation Manager. - * @param key The key under which the Animation should be added. The Animation will be updated with it. Must be unique. - * @param animation The Animation which should be added to the Animation Manager. - */ - add(key: string, animation: Phaser.Animations.Animation): Phaser.Animations.AnimationManager; - - /** - * Checks to see if the given key is already in use within the Animation Manager or not. - * - * Animations are global. Keys created in one scene can be used from any other Scene in your game. They are not Scene specific. - * @param key The key of the Animation to check. - */ - exists(key: string): boolean; - - /** - * Creates a new Animation and adds it to the Animation Manager. - * - * Animations are global. Once created, you can use them in any Scene in your game. They are not Scene specific. - * - * If an invalid key is given this method will return `false`. - * - * If you pass the key of an animation that already exists in the Animation Manager, that animation will be returned. - * - * A brand new animation is only created if the key is valid and not already in use. - * - * If you wish to re-use an existing key, call `AnimationManager.remove` first, then this method. - * @param config The configuration settings for the Animation. - */ - create(config: Phaser.Types.Animations.Animation): Phaser.Animations.Animation | false; - - /** - * Loads this Animation Manager's Animations and settings from a JSON object. - * @param data The JSON object to parse. - * @param clearCurrentAnimations If set to `true`, the current animations will be removed (`anims.clear()`). If set to `false` (default), the animations in `data` will be added. Default false. - */ - fromJSON(data: string | Phaser.Types.Animations.JSONAnimations | Phaser.Types.Animations.JSONAnimation, clearCurrentAnimations?: boolean): Phaser.Animations.Animation[]; - - /** - * [description] - * @param key The key for the texture containing the animation frames. - * @param config The configuration object for the animation frame names. - */ - generateFrameNames(key: string, config?: Phaser.Types.Animations.GenerateFrameNames): Phaser.Types.Animations.AnimationFrame[]; - - /** - * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. - * - * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. - * @param key The key for the texture containing the animation frames. - * @param config The configuration object for the animation frames. - */ - generateFrameNumbers(key: string, config: Phaser.Types.Animations.GenerateFrameNumbers): Phaser.Types.Animations.AnimationFrame[]; - - /** - * Get an Animation. - * @param key The key of the Animation to retrieve. - */ - get(key: string): Phaser.Animations.Animation; - - /** - * Load an Animation into a Game Object's Animation Component. - * @param child The Game Object to load the animation into. - * @param key The key of the animation to load. - * @param startFrame The name of a start frame to set on the loaded animation. - */ - load(child: Phaser.GameObjects.GameObject, key: string, startFrame?: string | integer): Phaser.GameObjects.GameObject; - - /** - * Pause all animations. - */ - pauseAll(): Phaser.Animations.AnimationManager; - - /** - * Play an animation on the given Game Objects that have an Animation Component. - * @param key The key of the animation to play on the Game Object. - * @param child The Game Objects to play the animation on. - */ - play(key: string, child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[]): Phaser.Animations.AnimationManager; - - /** - * Remove an animation. - * @param key The key of the animation to remove. - */ - remove(key: string): Phaser.Animations.Animation; - - /** - * Resume all paused animations. - */ - resumeAll(): Phaser.Animations.AnimationManager; - - /** - * Takes an array of Game Objects that have an Animation Component and then - * starts the given animation playing on them, each one offset by the - * `stagger` amount given to this method. - * @param key The key of the animation to play on the Game Objects. - * @param children An array of Game Objects to play the animation on. They must have an Animation Component. - * @param stagger The amount of time, in milliseconds, to offset each play time by. Default 0. - */ - staggerPlay(key: string, children: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], stagger?: number): G; - - /** - * Get the animation data as javascript object by giving key, or get the data of all animations as array of objects, if key wasn't provided. - * @param key [description] - */ - toJSON(key: string): Phaser.Types.Animations.JSONAnimations; - - /** - * Destroy this Animation Manager and clean up animation definitions and references to other objects. - * This method should not be called directly. It will be called automatically as a response to a `destroy` event from the Phaser.Game instance. - */ - destroy(): void; - - } - - namespace Events { - /** - * The Add Animation Event. - * - * This event is dispatched when a new animation is added to the global Animation Manager. - * - * This can happen either as a result of an animation instance being added to the Animation Manager, - * or the Animation Manager creating a new animation directly. - */ - const ADD_ANIMATION: any; - - /** - * The Animation Complete Event. - * - * This event is dispatched by an Animation instance when it completes, i.e. finishes playing or is manually stopped. - * - * Be careful with the volume of events this could generate. If a group of Sprites all complete the same - * animation at the same time, this event will invoke its handler for each one of them. - */ - const ANIMATION_COMPLETE: any; - - /** - * The Animation Repeat Event. - * - * This event is dispatched when a currently playing animation repeats. - * - * The event is dispatched directly from the Animation object itself. Which means that listeners - * bound to this event will be invoked every time the Animation repeats, for every Game Object that may have it. - */ - const ANIMATION_REPEAT: any; - - /** - * The Animation Restart Event. - * - * This event is dispatched by an Animation instance when it restarts. - * - * Be careful with the volume of events this could generate. If a group of Sprites all restart the same - * animation at the same time, this event will invoke its handler for each one of them. - */ - const ANIMATION_RESTART: any; - - /** - * The Animation Start Event. - * - * This event is dispatched by an Animation instance when it starts playing. - * - * Be careful with the volume of events this could generate. If a group of Sprites all play the same - * animation at the same time, this event will invoke its handler for each one of them. - */ - const ANIMATION_START: any; - - /** - * The Pause All Animations Event. - * - * This event is dispatched when the global Animation Manager is told to pause. - * - * When this happens all current animations will stop updating, although it doesn't necessarily mean - * that the game has paused as well. - */ - const PAUSE_ALL: any; - - /** - * The Remove Animation Event. - * - * This event is dispatched when an animation is removed from the global Animation Manager. - */ - const REMOVE_ANIMATION: any; - - /** - * The Resume All Animations Event. - * - * This event is dispatched when the global Animation Manager resumes, having been previously paused. - * - * When this happens all current animations will continue updating again. - */ - const RESUME_ALL: any; - - /** - * The Sprite Animation Complete Event. - * - * This event is dispatched by a Sprite when an animation finishes playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationcomplete', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_COMPLETE` event. - */ - const SPRITE_ANIMATION_COMPLETE: any; - - /** - * The Sprite Animation Key Complete Event. - * - * This event is dispatched by a Sprite when a specific animation finishes playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationcomplete-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationcomplete-explode`. - */ - const SPRITE_ANIMATION_KEY_COMPLETE: any; - - /** - * The Sprite Animation Key Repeat Event. - * - * This event is dispatched by a Sprite when a specific animation repeats playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrepeat-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrepeat-explode`. - */ - const SPRITE_ANIMATION_KEY_REPEAT: any; - - /** - * The Sprite Animation Key Restart Event. - * - * This event is dispatched by a Sprite when a specific animation restarts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrestart-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrestart-explode`. - */ - const SPRITE_ANIMATION_KEY_RESTART: any; - - /** - * The Sprite Animation Key Start Event. - * - * This event is dispatched by a Sprite when a specific animation starts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationstart-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationstart-explode`. - */ - const SPRITE_ANIMATION_KEY_START: any; - - /** - * The Sprite Animation Key Update Event. - * - * This event is dispatched by a Sprite when a specific animation playing on it updates. This happens when the animation changes frame, - * based on the animation frame rate and other factors like `timeScale` and `delay`. - * - * Listen for it on the Sprite using `sprite.on('animationupdate-key', listener)` where `key` is the key of - * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationupdate-explode`. - */ - const SPRITE_ANIMATION_KEY_UPDATE: any; - - /** - * The Sprite Animation Repeat Event. - * - * This event is dispatched by a Sprite when an animation repeats playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrepeat', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_REPEAT` event. - */ - const SPRITE_ANIMATION_REPEAT: any; - - /** - * The Sprite Animation Restart Event. - * - * This event is dispatched by a Sprite when an animation restarts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationrestart', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_RESTART` event. - */ - const SPRITE_ANIMATION_RESTART: any; - - /** - * The Sprite Animation Start Event. - * - * This event is dispatched by a Sprite when an animation starts playing on it. - * - * Listen for it on the Sprite using `sprite.on('animationstart', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_START` event. - */ - const SPRITE_ANIMATION_START: any; - - /** - * The Sprite Animation Update Event. - * - * This event is dispatched by a Sprite when an animation playing on it updates. This happens when the animation changes frame, - * based on the animation frame rate and other factors like `timeScale` and `delay`. - * - * Listen for it on the Sprite using `sprite.on('animationupdate', listener)` - * - * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_UPDATE` event. - */ - const SPRITE_ANIMATION_UPDATE: any; - - } - - } - - namespace Cache { - /** - * The BaseCache is a base Cache class that can be used for storing references to any kind of data. - * - * Data can be added, retrieved and removed based on the given keys. - * - * Keys are string-based. - */ - class BaseCache { - /** - * The Map in which the cache objects are stored. - * - * You can query the Map directly or use the BaseCache methods. - */ - entries: Phaser.Structs.Map; - - /** - * An instance of EventEmitter used by the cache to emit related events. - */ - events: Phaser.Events.EventEmitter; - - /** - * Adds an item to this cache. The item is referenced by a unique string, which you are responsible - * for setting and keeping track of. The item can only be retrieved by using this string. - * @param key The unique key by which the data added to the cache will be referenced. - * @param data The data to be stored in the cache. - */ - add(key: string, data: any): Phaser.Cache.BaseCache; - - /** - * Checks if this cache contains an item matching the given key. - * This performs the same action as `BaseCache.exists`. - * @param key The unique key of the item to be checked in this cache. - */ - has(key: string): boolean; - - /** - * Checks if this cache contains an item matching the given key. - * This performs the same action as `BaseCache.has` and is called directly by the Loader. - * @param key The unique key of the item to be checked in this cache. - */ - exists(key: string): boolean; - - /** - * Gets an item from this cache based on the given key. - * @param key The unique key of the item to be retrieved from this cache. - */ - get(key: string): any; - - /** - * Removes and 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. - * @param key The unique key of the item to remove from the cache. - */ - remove(key: string): Phaser.Cache.BaseCache; - - /** - * Returns all keys in use in this cache. - */ - getKeys(): string[]; - - /** - * Destroys this cache and all items within it. - */ - destroy(): void; - - } - - /** - * The Cache Manager is the global cache owned and maintained by the Game instance. - * - * Various systems, such as the file Loader, rely on this cache in order to store the files - * it has loaded. The manager itself doesn't store any files, but instead owns multiple BaseCache - * instances, one per type of file. You can also add your own custom caches. - */ - class CacheManager { - /** - * - * @param game A reference to the Phaser.Game instance that owns this CacheManager. - */ - constructor(game: Phaser.Game); - - /** - * A reference to the Phaser.Game instance that owns this CacheManager. - */ - protected game: Phaser.Game; - - /** - * A Cache storing all binary files, typically added via the Loader. - */ - binary: Phaser.Cache.BaseCache; - - /** - * A Cache storing all bitmap font data files, typically added via the Loader. - * Only the font data is stored in this cache, the textures are part of the Texture Manager. - */ - bitmapFont: Phaser.Cache.BaseCache; - - /** - * A Cache storing all JSON data files, typically added via the Loader. - */ - json: Phaser.Cache.BaseCache; - - /** - * A Cache storing all physics data files, typically added via the Loader. - */ - physics: Phaser.Cache.BaseCache; - - /** - * A Cache storing all shader source files, typically added via the Loader. - */ - shader: Phaser.Cache.BaseCache; - - /** - * A Cache storing all non-streaming audio files, typically added via the Loader. - */ - audio: Phaser.Cache.BaseCache; - - /** - * A Cache storing all non-streaming video files, typically added via the Loader. - */ - video: Phaser.Cache.BaseCache; - - /** - * A Cache storing all text files, typically added via the Loader. - */ - text: Phaser.Cache.BaseCache; - - /** - * A Cache storing all html files, typically added via the Loader. - */ - html: Phaser.Cache.BaseCache; - - /** - * A Cache storing all WaveFront OBJ files, typically added via the Loader. - */ - obj: Phaser.Cache.BaseCache; - - /** - * A Cache storing all tilemap data files, typically added via the Loader. - * Only the data is stored in this cache, the textures are part of the Texture Manager. - */ - tilemap: Phaser.Cache.BaseCache; - - /** - * A Cache storing all xml data files, typically added via the Loader. - */ - xml: Phaser.Cache.BaseCache; - - /** - * An object that contains your own custom BaseCache entries. - * Add to this via the `addCustom` method. - */ - custom: {[key: string]: Phaser.Cache.BaseCache}; - - /** - * Add your own custom Cache for storing your own files. - * The cache will be available under `Cache.custom.key`. - * The cache will only be created if the key is not already in use. - * @param key The unique key of your custom cache. - */ - addCustom(key: string): Phaser.Cache.BaseCache; - - /** - * Removes all entries from all BaseCaches and destroys all custom caches. - */ - destroy(): void; - - } - - namespace Events { - /** - * The Cache Add Event. - * - * This event is dispatched by any Cache that extends the BaseCache each time a new object is added to it. - */ - const ADD: any; - - /** - * The Cache Remove Event. - * - * This event is dispatched by any Cache that extends the BaseCache each time an object is removed from it. - */ - const REMOVE: any; - - } - - } - - namespace Cameras { - namespace Scene2D { - /** - * A Base Camera class. - * - * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, - * and can be positioned, rotated, zoomed and scrolled accordingly. - * - * A Camera consists of two elements: The viewport and the scroll values. - * - * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are - * created the same size as your game, but their position and size can be set to anything. This means if you - * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, - * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). - * - * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this - * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the - * viewport, and changing the viewport has no impact on the scrolling. - * - * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, - * allowing you to filter Game Objects out on a per-Camera basis. - * - * The Base Camera is extended by the Camera class, which adds in special effects including Fade, - * Flash and Camera Shake, as well as the ability to follow Game Objects. - * - * The Base Camera was introduced in Phaser 3.12. It was split off from the Camera class, to allow - * you to isolate special effects as needed. Therefore the 'since' values for properties of this class relate - * to when they were added to the Camera class. - */ - class BaseCamera extends Phaser.Events.EventEmitter implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.Visible { - /** - * - * @param x The x position of the Camera, relative to the top-left of the game canvas. - * @param y The y position of the Camera, relative to the top-left of the game canvas. - * @param width The width of the Camera, in pixels. - * @param height The height of the Camera, in pixels. - */ - constructor(x: number, y: number, width: number, height: number); - - /** - * A reference to the Scene this camera belongs to. - */ - scene: Phaser.Scene; - - /** - * A reference to the Game Scene Manager. - */ - sceneManager: Phaser.Scenes.SceneManager; - - /** - * A reference to the Game Scale Manager. - */ - scaleManager: Phaser.Scale.ScaleManager; - - /** - * A reference to the Scene's Camera Manager to which this Camera belongs. - */ - cameraManager: Phaser.Cameras.Scene2D.CameraManager; - - /** - * The Camera ID. Assigned by the Camera Manager and used to handle camera exclusion. - * This value is a bitmask. - */ - readonly id: integer; - - /** - * The name of the Camera. This is left empty for your own use. - */ - name: string; - - /** - * This property is un-used in v3.16. - * - * The resolution of the Game, used in most Camera calculations. - */ - readonly resolution: number; - - /** - * Should this camera round its pixel values to integers? - */ - roundPixels: boolean; - - /** - * Is this Camera visible or not? - * - * A visible camera will render and perform input tests. - * An invisible camera will not render anything and will skip input tests. - */ - visible: boolean; - - /** - * Is this Camera using a bounds to restrict scrolling movement? - * - * Set this property along with the bounds via `Camera.setBounds`. - */ - useBounds: boolean; - - /** - * The World View is a Rectangle that defines the area of the 'world' the Camera is currently looking at. - * This factors in the Camera viewport size, zoom and scroll position and is updated in the Camera preRender step. - * If you have enabled Camera bounds the worldview will be clamped to those bounds accordingly. - * You can use it for culling or intersection checks. - */ - readonly worldView: Phaser.Geom.Rectangle; - - /** - * Is this Camera dirty? - * - * A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. - * - * This flag is cleared during the `postRenderCamera` method of the renderer. - */ - dirty: boolean; - - /** - * Does this Camera have a transparent background? - */ - transparent: boolean; - - /** - * The background color of this Camera. Only used if `transparent` is `false`. - */ - backgroundColor: Phaser.Display.Color; - - /** - * The Camera alpha value. Setting this property impacts every single object that this Camera - * renders. You can either set the property directly, i.e. via a Tween, to fade a Camera in or out, - * or via the chainable `setAlpha` method instead. - */ - alpha: number; - - /** - * Should the camera cull Game Objects before checking them for input hit tests? - * In some special cases it may be beneficial to disable this. - */ - disableCull: boolean; - - /** - * The mid-point of the Camera in 'world' coordinates. - * - * Use it to obtain exactly where in the world the center of the camera is currently looking. - * - * This value is updated in the preRender method, after the scroll values and follower - * have been processed. - */ - readonly midPoint: Phaser.Math.Vector2; - - /** - * The horizontal origin of rotation for this Camera. - * - * By default the camera rotates around the center of the viewport. - * - * Changing the origin allows you to adjust the point in the viewport from which rotation happens. - * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. - * - * See `setOrigin` to set both origins in a single, chainable call. - */ - originX: number; - - /** - * The vertical origin of rotation for this Camera. - * - * By default the camera rotates around the center of the viewport. - * - * Changing the origin allows you to adjust the point in the viewport from which rotation happens. - * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. - * - * See `setOrigin` to set both origins in a single, chainable call. - */ - originY: number; - - /** - * The Mask this Camera is using during render. - * Set the mask using the `setMask` method. Remove the mask using the `clearMask` method. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Set the Alpha level of this Camera. The alpha controls the opacity of the Camera as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The Camera alpha value. Default 1. - */ - setAlpha(value?: number): this; - - /** - * Sets the rotation origin of this Camera. - * - * The values are given in the range 0 to 1 and are only used when calculating Camera rotation. - * - * By default the camera rotates around the center of the viewport. - * - * Changing the origin allows you to adjust the point in the viewport from which rotation happens. - * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * 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. - * @param x The horizontal coordinate to center on. - * @param y The vertical coordinate to center on. - * @param out A Vector2 to store the values in. If not given a new Vector2 is created. - */ - getScroll(x: number, y: number, out?: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Moves the Camera horizontally so that it is centered on the given x coordinate, bounds allowing. - * Calling this does not change the scrollY value. - * @param x The horizontal coordinate to center on. - */ - centerOnX(x: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Moves the Camera vertically so that it is centered on the given y coordinate, bounds allowing. - * Calling this does not change the scrollX value. - * @param y The vertical coordinate to center on. - */ - centerOnY(y: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Moves the Camera so that it is centered on the given coordinates, bounds allowing. - * @param x The horizontal coordinate to center on. - * @param y The vertical coordinate to center on. - */ - centerOn(x: number, y: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Moves the Camera so that it is looking at the center of the Camera Bounds, if enabled. - */ - centerToBounds(): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Moves the Camera so that it is re-centered based on its viewport size. - */ - centerToSize(): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Takes an array of Game Objects and returns a new array featuring only those objects - * visible by this camera. - * @param renderableObjects An array of Game Objects to cull. - */ - cull(renderableObjects: G): G; - - /** - * 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. - * @param x The x position to convert to world space. - * @param y The y position to convert to world space. - * @param output An optional object to store the results in. If not provided a new Vector2 will be created. - */ - getWorldPoint(x: number, y: number, output?: O): O; - - /** - * Given a Game Object, or an array of Game Objects, it will update all of their camera filter settings - * so that they are ignored by this Camera. This means they will not be rendered by this Camera. - * @param entries The Game Object, or array of Game Objects, to be ignored by this Camera. - */ - ignore(entries: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Internal preRender step. - * @param resolution The game resolution, as set in the Scale Manager. - */ - protected preRender(resolution: number): void; - - /** - * Takes an x value and checks it's within the range of the Camera bounds, adjusting if required. - * Do not call this method if you are not using camera bounds. - * @param x The value to horizontally scroll clamp. - */ - clampX(x: number): number; - - /** - * Takes a y value and checks it's within the range of the Camera bounds, adjusting if required. - * Do not call this method if you are not using camera bounds. - * @param y The value to vertically scroll clamp. - */ - clampY(y: number): number; - - /** - * If this Camera has previously had movement bounds set on it, this will remove them. - */ - removeBounds(): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the rotation of this Camera. This causes everything it renders to appear rotated. - * - * Rotating a camera does not rotate the viewport itself, it is applied during rendering. - * @param value The cameras angle of rotation, given in degrees. Default 0. - */ - setAngle(value?: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Sets the background color for this Camera. - * - * By default a Camera has a transparent background but it can be given a solid color, with any level - * of transparency, via this method. - * - * The color value can be specified using CSS color notation, hex or numbers. - * @param color The color value. In CSS, hex or numeric color notation. Default 'rgba(0,0,0,0)'. - */ - setBackgroundColor(color?: string | number | Phaser.Types.Display.InputColorObject): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the bounds of the Camera. The bounds are an axis-aligned rectangle. - * - * The Camera bounds controls where the Camera can scroll to, stopping it from scrolling off the - * edges and into blank space. It does not limit the placement of Game Objects, or where - * the Camera viewport can be positioned. - * - * Temporarily disable the bounds by changing the boolean `Camera.useBounds`. - * - * Clear the bounds entirely by calling `Camera.removeBounds`. - * - * If you set bounds that are smaller than the viewport it will stop the Camera from being - * able to scroll. The bounds can be positioned where-ever you wish. By default they are from - * 0x0 to the canvas width x height. This means that the coordinate 0x0 is the top left of - * the Camera bounds. However, you can position them anywhere. So if you wanted a game world - * that was 2048x2048 in size, with 0x0 being the center of it, you can set the bounds x/y - * to be -1024, -1024, with a width and height of 2048. Depending on your game you may find - * it easier for 0x0 to be the top-left of the bounds, or you may wish 0x0 to be the middle. - * @param x The top-left x coordinate of the bounds. - * @param y The top-left y coordinate of the bounds. - * @param width The width of the bounds, in pixels. - * @param height The height of the bounds, in pixels. - * @param centerOn If `true` the Camera will automatically be centered on the new bounds. Default false. - */ - setBounds(x: integer, y: integer, width: integer, height: integer, centerOn?: boolean): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Returns a rectangle containing the bounds of the Camera. - * - * If the Camera does not have any bounds the rectangle will be empty. - * - * The rectangle is a copy of the bounds, so is safe to modify. - * @param out An optional Rectangle to store the bounds in. If not given, a new Rectangle will be created. - */ - getBounds(out?: Phaser.Geom.Rectangle): Phaser.Geom.Rectangle; - - /** - * Sets the name of this Camera. - * This value is for your own use and isn't used internally. - * @param value The name of the Camera. Default ''. - */ - setName(value?: string): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the position of the Camera viewport within the game. - * - * This does not change where the camera is 'looking'. See `setScroll` to control that. - * @param x The top-left x coordinate of the Camera viewport. - * @param y The top-left y coordinate of the Camera viewport. Default x. - */ - setPosition(x: number, y?: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the rotation of this Camera. This causes everything it renders to appear rotated. - * - * Rotating a camera does not rotate the viewport itself, it is applied during rendering. - * @param value The rotation of the Camera, in radians. Default 0. - */ - setRotation(value?: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Should the Camera round pixel values to whole integers when rendering Game Objects? - * - * In some types of game, especially with pixel art, this is required to prevent sub-pixel aliasing. - * @param value `true` to round Camera pixels, `false` to not. - */ - setRoundPixels(value: boolean): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Sets the Scene the Camera is bound to. - * - * Also populates the `resolution` property and updates the internal size values. - * @param scene The Scene the camera is bound to. - */ - setScene(scene: Phaser.Scene): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the position of where the Camera is looking within the game. - * You can also modify the properties `Camera.scrollX` and `Camera.scrollY` directly. - * Use this method, or the scroll properties, to move your camera around the game world. - * - * This does not change where the camera viewport is placed. See `setPosition` to control that. - * @param x The x coordinate of the Camera in the game world. - * @param y The y coordinate of the Camera in the game world. Default x. - */ - setScroll(x: number, y?: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the size of the Camera viewport. - * - * By default a Camera is the same size as the game, but can be made smaller via this method, - * allowing you to create mini-cam style effects by creating and positioning a smaller Camera - * viewport within your game. - * @param width The width of the Camera viewport. - * @param height The height of the Camera viewport. Default width. - */ - setSize(width: integer, height?: integer): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * This method sets the position and size of the Camera viewport in a single call. - * - * If you're trying to change where the Camera is looking at in your game, then see - * the method `Camera.setScroll` instead. This method is for changing the viewport - * itself, not what the camera can see. - * - * By default a Camera is the same size as the game, but can be made smaller via this method, - * allowing you to create mini-cam style effects by creating and positioning a smaller Camera - * viewport within your game. - * @param x The top-left x coordinate of the Camera viewport. - * @param y The top-left y coordinate of the Camera viewport. - * @param width The width of the Camera viewport. - * @param height The height of the Camera viewport. Default width. - */ - setViewport(x: number, y: number, width: integer, height?: integer): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Set the zoom value of the Camera. - * - * Changing to a smaller value, such as 0.5, will cause the camera to 'zoom out'. - * Changing to a larger value, such as 2, will cause the camera to 'zoom in'. - * - * A value of 1 means 'no zoom' and is the default. - * - * Changing the zoom does not impact the Camera viewport in any way, it is only applied during rendering. - * @param value The zoom value of the Camera. The minimum it can be is 0.001. Default 1. - */ - setZoom(value?: number): Phaser.Cameras.Scene2D.BaseCamera; - - /** - * Sets the mask to be applied to this Camera during rendering. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * - * Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Camera it will be immediately replaced. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * - * Note: You cannot mask a Camera that has `renderToTexture` set. - * @param mask The mask this Camera will use when rendering. - * @param fixedPosition Should the mask translate along with the Camera, or be fixed in place and not impacted by the Cameras transform? Default true. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask, fixedPosition?: boolean): this; - - /** - * Clears the mask that this Camera was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Sets the visibility of this Camera. - * - * An invisible Camera will skip rendering and input tests of everything it can see. - * @param value The visible state of the Camera. - */ - setVisible(value: boolean): this; - - /** - * Returns an Object suitable for JSON storage containing all of the Camera viewport and rendering properties. - */ - toJSON(): Phaser.Types.Cameras.Scene2D.JSONCamera; - - /** - * Internal method called automatically by the Camera Manager. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - protected update(time: integer, delta: number): void; - - /** - * Destroys this Camera instance and its internal properties and references. - * Once destroyed you cannot use this Camera again, even if re-added to a Camera Manager. - * - * This method is called automatically by `CameraManager.remove` if that methods `runDestroy` argument is `true`, which is the default. - * - * Unless you have a specific reason otherwise, always use `CameraManager.remove` and allow it to handle the camera destruction, - * rather than calling this method directly. - */ - destroy(): void; - - /** - * The x position of the Camera viewport, relative to the top-left of the game canvas. - * The viewport is the area into which the camera renders. - * To adjust the position the camera is looking at in the game world, see the `scrollX` value. - */ - x: number; - - /** - * The y position of the Camera viewport, relative to the top-left of the game canvas. - * The viewport is the area into which the camera renders. - * To adjust the position the camera is looking at in the game world, see the `scrollY` value. - */ - y: number; - - /** - * The width of the Camera viewport, in pixels. - * - * The viewport is the area into which the Camera renders. Setting the viewport does - * not restrict where the Camera can scroll to. - */ - width: number; - - /** - * The height of the Camera viewport, in pixels. - * - * The viewport is the area into which the Camera renders. Setting the viewport does - * not restrict where the Camera can scroll to. - */ - height: number; - - /** - * The horizontal scroll position of this Camera. - * - * Change this value to cause the Camera to scroll around your Scene. - * - * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, - * will automatically adjust the Camera scroll values accordingly. - * - * You can set the bounds within which the Camera can scroll via the `setBounds` method. - */ - scrollX: number; - - /** - * The vertical scroll position of this Camera. - * - * Change this value to cause the Camera to scroll around your Scene. - * - * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, - * will automatically adjust the Camera scroll values accordingly. - * - * You can set the bounds within which the Camera can scroll via the `setBounds` method. - */ - scrollY: number; - - /** - * The Camera zoom value. Change this value to zoom in, or out of, a Scene. - * - * A value of 0.5 would zoom the Camera out, so you can now see twice as much - * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel - * now takes up 2 pixels when rendered. - * - * Set to 1 to return to the default zoom level. - * - * Be careful to never set this value to zero. - */ - zoom: number; - - /** - * The horizontal position of the center of the Camera's viewport, relative to the left of the game canvas. - */ - readonly centerX: number; - - /** - * The vertical position of the center of the Camera's viewport, relative to the top of the game canvas. - */ - readonly centerY: number; - - /** - * The displayed width of the camera viewport, factoring in the camera zoom level. - * - * If a camera has a viewport width of 800 and a zoom of 0.5 then its display width - * would be 1600, as it's displaying twice as many pixels as zoom level 1. - * - * Equally, a camera with a width of 800 and zoom of 2 would have a display width - * of 400 pixels. - */ - readonly displayWidth: number; - - /** - * The displayed height of the camera viewport, factoring in the camera zoom level. - * - * If a camera has a viewport height of 600 and a zoom of 0.5 then its display height - * would be 1200, as it's displaying twice as many pixels as zoom level 1. - * - * Equally, a camera with a height of 600 and zoom of 2 would have a display height - * of 300 pixels. - */ - readonly displayHeight: number; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - } - - /** - * A Camera. - * - * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, - * and can be positioned, rotated, zoomed and scrolled accordingly. - * - * A Camera consists of two elements: The viewport and the scroll values. - * - * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are - * created the same size as your game, but their position and size can be set to anything. This means if you - * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, - * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). - * - * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this - * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the - * viewport, and changing the viewport has no impact on the scrolling. - * - * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, - * allowing you to filter Game Objects out on a per-Camera basis. - * - * A Camera also has built-in special effects including Fade, Flash and Camera Shake. - */ - class Camera extends Phaser.Cameras.Scene2D.BaseCamera implements Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.Tint { - /** - * - * @param x The x position of the Camera, relative to the top-left of the game canvas. - * @param y The y position of the Camera, relative to the top-left of the game canvas. - * @param width The width of the Camera, in pixels. - * @param height The height of the Camera, in pixels. - */ - constructor(x: number, y: number, width: number, height: number); - - /** - * Does this Camera allow the Game Objects it renders to receive input events? - */ - inputEnabled: boolean; - - /** - * The Camera Fade effect handler. - * To fade this camera see the `Camera.fade` methods. - */ - fadeEffect: Phaser.Cameras.Scene2D.Effects.Fade; - - /** - * The Camera Flash effect handler. - * To flash this camera see the `Camera.flash` method. - */ - flashEffect: Phaser.Cameras.Scene2D.Effects.Flash; - - /** - * The Camera Shake effect handler. - * To shake this camera see the `Camera.shake` method. - */ - shakeEffect: Phaser.Cameras.Scene2D.Effects.Shake; - - /** - * The Camera Pan effect handler. - * To pan this camera see the `Camera.pan` method. - */ - panEffect: Phaser.Cameras.Scene2D.Effects.Pan; - - /** - * The Camera Zoom effect handler. - * To zoom this camera see the `Camera.zoom` method. - */ - zoomEffect: Phaser.Cameras.Scene2D.Effects.Zoom; - - /** - * The linear interpolation value to use when following a target. - * - * Can also be set via `setLerp` or as part of the `startFollow` call. - * - * The default values of 1 means the camera will instantly snap to the target coordinates. - * A lower value, such as 0.1 means the camera will more slowly track the target, giving - * a smooth transition. You can set the horizontal and vertical values independently, and also - * adjust this value in real-time during your game. - * - * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. - */ - lerp: Phaser.Math.Vector2; - - /** - * The values stored in this property are subtracted from the Camera targets position, allowing you to - * offset the camera from the actual target x/y coordinates by this amount. - * Can also be set via `setFollowOffset` or as part of the `startFollow` call. - */ - followOffset: Phaser.Math.Vector2; - - /** - * The Camera dead zone. - * - * The deadzone is only used when the camera is following a target. - * - * It defines a rectangular region within which if the target is present, the camera will not scroll. - * If the target moves outside of this area, the camera will begin scrolling in order to follow it. - * - * The `lerp` values that you can set for a follower target also apply when using a deadzone. - * - * You can directly set this property to be an instance of a Rectangle. Or, you can use the - * `setDeadzone` method for a chainable approach. - * - * The rectangle you provide can have its dimensions adjusted dynamically, however, please - * note that its position is updated every frame, as it is constantly re-centered on the cameras mid point. - * - * Calling `setDeadzone` with no arguments will reset an active deadzone, as will setting this property - * to `null`. - */ - deadzone: Phaser.Geom.Rectangle; - - /** - * Is this Camera rendering directly to the canvas or to a texture? - * - * Enable rendering to texture with the method `setRenderToTexture` (just enabling this boolean won't be enough) - * - * Once enabled you can toggle it by switching this property. - * - * To properly remove a render texture you should call the `clearRenderToTexture()` method. - */ - renderToTexture: boolean; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the HTML Canvas Element that the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only populated if Phaser is running with the Canvas Renderer. - */ - canvas: HTMLCanvasElement; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the Rendering Context belonging to the Canvas element the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only populated if Phaser is running with the Canvas Renderer. - */ - context: CanvasRenderingContext2D; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the GL Texture belonging the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only set if Phaser is running with the WebGL Renderer. - */ - glTexture: WebGLTexture; - - /** - * If this Camera has been set to render to a texture then this holds a reference - * to the GL Frame Buffer belonging the Camera is drawing to. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only set if Phaser is running with the WebGL Renderer. - */ - framebuffer: WebGLFramebuffer; - - /** - * If this Camera has been set to render to a texture and to use a custom pipeline, - * then this holds a reference to the pipeline the Camera is drawing with. - * - * Enable texture rendering using the method `setRenderToTexture`. - * - * This is only set if Phaser is running with the WebGL Renderer. - */ - pipeline: any; - - /** - * Sets the Camera to render to a texture instead of to the main canvas. - * - * The Camera will redirect all Game Objects it's asked to render to this texture. - * - * During the render sequence, the texture itself will then be rendered to the main canvas. - * - * Doing this gives you the ability to modify the texture before this happens, - * allowing for special effects such as Camera specific shaders, or post-processing - * on the texture. - * - * If running under Canvas the Camera will render to its `canvas` property. - * - * If running under WebGL the Camera will create a frame buffer, which is stored in its `framebuffer` and `glTexture` properties. - * - * If you set a camera to render to a texture then it will emit 2 events during the render loop: - * - * First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. - * - * Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the - * Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before - * it appears in-game. - * - * You should not enable this unless you plan on actually using the texture it creates - * somehow, otherwise you're just doubling the work required to render your game. - * - * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. - * - * If you no longer require the Camera to render to a texture, call the `clearRenderToTexture` method, - * which will delete the respective textures and free-up resources. - * @param pipeline An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. - */ - setRenderToTexture(pipeline?: string | Phaser.Renderer.WebGL.WebGLPipeline): Phaser.Cameras.Scene2D.Camera; - - /** - * Sets the WebGL pipeline this Camera is using when rendering to a texture. - * - * You can pass either the string-based name of the pipeline, or a reference to the pipeline itself. - * - * Call this method with no arguments to clear any previously set pipeline. - * @param pipeline The WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. Or if left empty it will clear the pipeline. - */ - setPipeline(pipeline?: string | Phaser.Renderer.WebGL.WebGLPipeline): Phaser.Cameras.Scene2D.Camera; - - /** - * If this Camera was set to render to a texture, this will clear the resources it was using and - * redirect it to render back to the primary Canvas again. - * - * If you only wish to temporarily disable rendering to a texture then you can toggle the - * property `renderToTexture` instead. - */ - clearRenderToTexture(): Phaser.Cameras.Scene2D.Camera; - - /** - * Sets the Camera dead zone. - * - * The deadzone is only used when the camera is following a target. - * - * It defines a rectangular region within which if the target is present, the camera will not scroll. - * If the target moves outside of this area, the camera will begin scrolling in order to follow it. - * - * The deadzone rectangle is re-positioned every frame so that it is centered on the mid-point - * of the camera. This allows you to use the object for additional game related checks, such as - * testing if an object is within it or not via a Rectangle.contains call. - * - * The `lerp` values that you can set for a follower target also apply when using a deadzone. - * - * Calling this method with no arguments will reset an active deadzone. - * @param width The width of the deadzone rectangle in pixels. If not specified the deadzone is removed. - * @param height The height of the deadzone rectangle in pixels. - */ - setDeadzone(width?: number, height?: number): Phaser.Cameras.Scene2D.Camera; - - /** - * Fades the Camera in from the given color over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - fadeIn(duration?: integer, red?: integer, green?: integer, blue?: integer, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * Fades the Camera out to the given color over the duration specified. - * This is an alias for Camera.fade that forces the fade to start, regardless of existing fades. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - fadeOut(duration?: integer, red?: integer, green?: integer, blue?: integer, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * Fades the Camera from the given color to transparent over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. - * @param force Force the effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - fadeFrom(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * Fades the Camera from transparent to the given color over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. - * @param force Force the effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - fade(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * Flashes the Camera by setting it to the given color immediately and then fading it away again quickly over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 250. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 255. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 255. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 255. - * @param force Force the effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - flash(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * Shakes the Camera by the given intensity over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 100. - * @param intensity The intensity of the shake. Default 0.05. - * @param force Force the shake effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - shake(duration?: integer, intensity?: number | Phaser.Math.Vector2, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, - * over the duration and with the ease specified. - * @param x The destination x coordinate to scroll the center of the Camera viewport to. - * @param y The destination y coordinate to scroll the center of the Camera viewport to. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param ease The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. - * @param force Force the pan effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * the current camera scroll x coordinate and the current camera scroll y coordinate. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - pan(x: number, y: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraPanCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. - * @param zoom The target Camera zoom value. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param ease The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. - * @param force Force the pan effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * the current camera scroll x coordinate and the current camera scroll y coordinate. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - zoomTo(zoom: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraPanCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * Internal preRender step. - * @param resolution The game resolution, as set in the Scale Manager. - */ - protected preRender(resolution: number): void; - - /** - * Sets the linear interpolation value to use when following a target. - * - * The default values of 1 means the camera will instantly snap to the target coordinates. - * A lower value, such as 0.1 means the camera will more slowly track the target, giving - * a smooth transition. You can set the horizontal and vertical values independently, and also - * adjust this value in real-time during your game. - * - * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. - * @param x The amount added to the horizontal linear interpolation of the follow target. Default 1. - * @param y The amount added to the vertical linear interpolation of the follow target. Default 1. - */ - setLerp(x?: number, y?: number): this; - - /** - * Sets the horizontal and vertical offset of the camera from its follow target. - * The values are subtracted from the targets position during the Cameras update step. - * @param x The horizontal offset from the camera follow target.x position. Default 0. - * @param y The vertical offset from the camera follow target.y position. Default 0. - */ - setFollowOffset(x?: number, y?: number): this; - - /** - * Sets the Camera to follow a Game Object. - * - * When enabled the Camera will automatically adjust its scroll position to keep the target Game Object - * in its center. - * - * You can set the linear interpolation value used in the follow code. - * Use low lerp values (such as 0.1) to automatically smooth the camera motion. - * - * If you find you're getting a slight "jitter" effect when following an object it's probably to do with sub-pixel - * rendering of the targets position. This can be rounded by setting the `roundPixels` argument to `true` to - * force full pixel rounding rendering. Note that this can still be broken if you have specified a non-integer zoom - * value on the camera. So be sure to keep the camera zoom to integers. - * @param target The target for the Camera to follow. - * @param roundPixels Round the camera position to whole integers to avoid sub-pixel rendering? Default false. - * @param lerpX A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. Default 1. - * @param lerpY A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. Default 1. - * @param offsetX The horizontal offset from the camera follow target.x position. Default 0. - * @param offsetY The vertical offset from the camera follow target.y position. Default 0. - */ - startFollow(target: Phaser.GameObjects.GameObject | object, roundPixels?: boolean, lerpX?: number, lerpY?: number, offsetX?: number, offsetY?: number): this; - - /** - * Stops a Camera from following a Game Object, if previously set via `Camera.startFollow`. - */ - stopFollow(): Phaser.Cameras.Scene2D.Camera; - - /** - * Resets any active FX, such as a fade, flash or shake. Useful to call after a fade in order to - * remove the fade. - */ - resetFX(): Phaser.Cameras.Scene2D.Camera; - - /** - * Internal method called automatically by the Camera Manager. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - protected update(time: integer, delta: number): void; - - /** - * Destroys this Camera instance. You rarely need to call this directly. - * - * Called by the Camera Manager. If you wish to destroy a Camera please use `CameraManager.remove` as - * cameras are stored in a pool, ready for recycling later, and calling this directly will prevent that. - */ - destroy(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - } - - /** - * The Camera Manager is a plugin that belongs to a Scene and is responsible for managing all of the Scene Cameras. - * - * By default you can access the Camera Manager from within a Scene using `this.cameras`, although this can be changed - * in your game config. - * - * Create new Cameras using the `add` method. Or extend the Camera class with your own addition code and then add - * the new Camera in using the `addExisting` method. - * - * Cameras provide a view into your game world, and can be positioned, rotated, zoomed and scrolled accordingly. - * - * A Camera consists of two elements: The viewport and the scroll values. - * - * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are - * created the same size as your game, but their position and size can be set to anything. This means if you - * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, - * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). - * - * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this - * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the - * viewport, and changing the viewport has no impact on the scrolling. - * - * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, - * allowing you to filter Game Objects out on a per-Camera basis. The Camera Manager can manage up to 31 unique - * 'Game Object ignore capable' Cameras. Any Cameras beyond 31 that you create will all be given a Camera ID of - * zero, meaning that they cannot be used for Game Object exclusion. This means if you need your Camera to ignore - * Game Objects, make sure it's one of the first 31 created. - * - * A Camera also has built-in special effects including Fade, Flash, Camera Shake, Pan and Zoom. - */ - class CameraManager { - /** - * - * @param scene The Scene that owns the Camera Manager plugin. - */ - constructor(scene: Phaser.Scene); - - /** - * The Scene that owns the Camera Manager plugin. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene.Systems handler for the Scene that owns the Camera Manager. - */ - systems: Phaser.Scenes.Systems; - - /** - * All Cameras created by, or added to, this Camera Manager, will have their `roundPixels` - * property set to match this value. By default it is set to match the value set in the - * game configuration, but can be changed at any point. Equally, individual cameras can - * also be changed as needed. - */ - roundPixels: boolean; - - /** - * An Array of the Camera objects being managed by this Camera Manager. - * The Cameras are updated and rendered in the same order in which they appear in this array. - * Do not directly add or remove entries to this array. However, you can move the contents - * around the array should you wish to adjust the display order. - */ - cameras: Phaser.Cameras.Scene2D.Camera[]; - - /** - * A handy reference to the 'main' camera. By default this is the first Camera the - * Camera Manager creates. You can also set it directly, or use the `makeMain` argument - * in the `add` and `addExisting` methods. It allows you to access it from your game: - * - * ```javascript - * var cam = this.cameras.main; - * ``` - * - * Also see the properties `camera1`, `camera2` and so on. - */ - main: Phaser.Cameras.Scene2D.Camera; - - /** - * A default un-transformed Camera that doesn't exist on the camera list and doesn't - * count towards the total number of cameras being managed. It exists for other - * systems, as well as your own code, should they require a basic un-transformed - * camera instance from which to calculate a view matrix. - */ - default: Phaser.Cameras.Scene2D.Camera; - - /** - * 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. - * @param x The horizontal position of the Camera viewport. Default 0. - * @param y The vertical position of the Camera viewport. Default 0. - * @param width The width of the Camera viewport. If not given it'll be the game config size. - * @param height The height of the Camera viewport. If not given it'll be the game config size. - * @param makeMain Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. Default false. - * @param name The name of the Camera. Default ''. - */ - add(x?: integer, y?: integer, width?: integer, height?: integer, makeMain?: boolean, name?: string): Phaser.Cameras.Scene2D.Camera; - - /** - * Adds an existing Camera into the Camera Manager. - * - * The Camera should either be a `Phaser.Cameras.Scene2D.Camera` instance, or a class that extends from it. - * - * The Camera will have its `roundPixels` property set to whatever `CameraManager.roundPixels` is. You can change - * it after addition if required. - * - * The Camera will be assigned an ID, which is used for Game Object exclusion and then added to the - * manager. As long as it doesn't already exist in the manager it will be added then returned. - * - * If this method returns `null` then the Camera already exists in this Camera Manager. - * @param camera The Camera to be added to the Camera Manager. - * @param makeMain Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. Default false. - */ - addExisting(camera: Phaser.Cameras.Scene2D.Camera, makeMain?: boolean): Phaser.Cameras.Scene2D.Camera; - - /** - * Gets the total number of Cameras in this Camera Manager. - * - * If the optional `isVisible` argument is set it will only count Cameras that are currently visible. - * @param isVisible Set the `true` to only include visible Cameras in the total. Default false. - */ - getTotal(isVisible?: boolean): integer; - - /** - * 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. - * @param config A Camera configuration object, or an array of them, to be added to this Camera Manager. - */ - fromJSON(config: Phaser.Types.Cameras.Scene2D.CameraConfig | Phaser.Types.Cameras.Scene2D.CameraConfig[]): Phaser.Cameras.Scene2D.CameraManager; - - /** - * 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. - * @param name The name of the Camera. - */ - getCamera(name: string): Phaser.Cameras.Scene2D.Camera; - - /** - * Returns an array of all cameras below the given Pointer. - * - * The first camera in the array is the top-most camera in the camera list. - * @param pointer The Pointer to check against. - */ - getCamerasBelowPointer(pointer: Phaser.Input.Pointer): Phaser.Cameras.Scene2D.Camera[]; - - /** - * Removes the given Camera, or an array of Cameras, from this Camera Manager. - * - * If found in the Camera Manager it will be immediately removed from the local cameras array. - * If also currently the 'main' camera, 'main' will be reset to be camera 0. - * - * The removed Cameras are automatically destroyed if the `runDestroy` argument is `true`, which is the default. - * If you wish to re-use the cameras then set this to `false`, but know that they will retain their references - * and internal data until destroyed or re-added to a Camera Manager. - * @param camera The Camera, or an array of Cameras, to be removed from this Camera Manager. - * @param runDestroy Automatically call `Camera.destroy` on each Camera removed from this Camera Manager. Default true. - */ - remove(camera: Phaser.Cameras.Scene2D.Camera | Phaser.Cameras.Scene2D.Camera[], runDestroy?: boolean): integer; - - /** - * The internal render method. This is called automatically by the Scene and should not be invoked directly. - * - * It will iterate through all local cameras and render them in turn, as long as they're visible and have - * an alpha level > 0. - * @param renderer The Renderer that will render the children to this camera. - * @param children An array of renderable Game Objects. - * @param interpolation Interpolation value. Reserved for future use. - */ - protected render(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer, children: Phaser.GameObjects.GameObject[], interpolation: number): void; - - /** - * Resets this Camera Manager. - * - * This will iterate through all current Cameras, destroying them all, then it will reset the - * cameras array, reset the ID counter and create 1 new single camera using the default values. - */ - resetAll(): Phaser.Cameras.Scene2D.Camera; - - /** - * The main update loop. Called automatically when the Scene steps. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - protected update(time: integer, delta: number): void; - - /** - * The event handler that manages the `resize` event dispatched by the Scale Manager. - * @param gameSize The default Game Size object. This is the un-modified game dimensions. - * @param baseSize The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. - */ - onResize(gameSize: Phaser.Structs.Size, baseSize: Phaser.Structs.Size): void; - - /** - * Resizes all cameras to the given dimensions. - * @param width The new width of the camera. - * @param height The new height of the camera. - */ - resize(width: number, height: number): void; - - } - - namespace Effects { - /** - * A Camera Fade effect. - * - * This effect will fade the camera viewport to the given color, over the duration specified. - * - * Only the camera viewport is faded. None of the objects it is displaying are impacted, i.e. their colors 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 Fade { - /** - * - * @param camera The camera this effect is acting upon. - */ - constructor(camera: Phaser.Cameras.Scene2D.Camera); - - /** - * The Camera this effect belongs to. - */ - readonly camera: Phaser.Cameras.Scene2D.Camera; - - /** - * Is this effect actively running? - */ - readonly isRunning: boolean; - - /** - * Has this effect finished running? - * - * This is different from `isRunning` because it remains set to `true` when the effect is over, - * until the effect is either reset or started again. - */ - readonly isComplete: boolean; - - /** - * The direction of the fade. - * `true` = fade out (transparent to color), `false` = fade in (color to transparent) - */ - readonly direction: boolean; - - /** - * The duration of the effect, in milliseconds. - */ - readonly duration: integer; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - */ - progress: number; - - /** - * Fades the Camera to or from the given color over the duration specified. - * @param direction The direction of the fade. `true` = fade out (transparent to color), `false` = fade in (color to transparent) Default true. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. - * @param force Force the effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - start(direction?: boolean, duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraFadeCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * The main update loop for this effect. Called automatically by the Camera. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - update(time: integer, delta: number): void; - - /** - * Called internally by the Canvas Renderer. - * @param ctx The Canvas context to render to. - */ - postRenderCanvas(ctx: CanvasRenderingContext2D): boolean; - - /** - * Called internally by the WebGL Renderer. - * @param pipeline The WebGL Pipeline to render to. - * @param getTintFunction A function that will return the gl safe tint colors. - */ - postRenderWebGL(pipeline: Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline, getTintFunction: Function): boolean; - - /** - * Called internally when the effect completes. - */ - effectComplete(): void; - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - */ - reset(): void; - - /** - * Destroys this effect, releasing it from the Camera. - */ - destroy(): void; - - } - - /** - * A Camera Flash effect. - * - * This effect will flash the camera viewport to the given color, over the duration specified. - * - * Only the camera viewport is flashed. None of the objects it is displaying are impacted, i.e. their colors 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 Flash { - /** - * - * @param camera The camera this effect is acting upon. - */ - constructor(camera: Phaser.Cameras.Scene2D.Camera); - - /** - * The Camera this effect belongs to. - */ - readonly camera: Phaser.Cameras.Scene2D.Camera; - - /** - * Is this effect actively running? - */ - readonly isRunning: boolean; - - /** - * The duration of the effect, in milliseconds. - */ - readonly duration: integer; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - */ - progress: number; - - /** - * Flashes the Camera to or from the given color over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 250. - * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 255. - * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 255. - * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 255. - * @param force Force the effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - start(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraFlashCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * The main update loop for this effect. Called automatically by the Camera. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - update(time: integer, delta: number): void; - - /** - * Called internally by the Canvas Renderer. - * @param ctx The Canvas context to render to. - */ - postRenderCanvas(ctx: CanvasRenderingContext2D): boolean; - - /** - * Called internally by the WebGL Renderer. - * @param pipeline The WebGL Pipeline to render to. - * @param getTintFunction A function that will return the gl safe tint colors. - */ - postRenderWebGL(pipeline: Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline, getTintFunction: Function): boolean; - - /** - * Called internally when the effect completes. - */ - effectComplete(): void; - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - */ - reset(): void; - - /** - * Destroys this effect, releasing it from the Camera. - */ - destroy(): void; - - } - - /** - * A Camera Pan effect. - * - * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, - * over the duration and with the ease specified. - * - * Only the camera scroll is moved. 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 Pan { - /** - * - * @param camera The camera this effect is acting upon. - */ - constructor(camera: Phaser.Cameras.Scene2D.Camera); - - /** - * The Camera this effect belongs to. - */ - readonly camera: Phaser.Cameras.Scene2D.Camera; - - /** - * Is this effect actively running? - */ - readonly isRunning: boolean; - - /** - * The duration of the effect, in milliseconds. - */ - readonly duration: integer; - - /** - * The starting scroll coordinates to pan the camera from. - */ - source: Phaser.Math.Vector2; - - /** - * The constantly updated value based on zoom. - */ - current: Phaser.Math.Vector2; - - /** - * The destination scroll coordinates to pan the camera to. - */ - destination: Phaser.Math.Vector2; - - /** - * The ease function to use during the pan. - */ - ease: Function; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - */ - progress: number; - - /** - * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, - * over the duration and with the ease specified. - * @param x The destination x coordinate to scroll the center of the Camera viewport to. - * @param y The destination y coordinate to scroll the center of the Camera viewport to. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param ease The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. - * @param force Force the pan effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * the current camera scroll x coordinate and the current camera scroll y coordinate. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - start(x: number, y: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraPanCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * The main update loop for this effect. Called automatically by the Camera. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - update(time: integer, delta: number): void; - - /** - * Called internally when the effect completes. - */ - effectComplete(): void; - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - */ - reset(): void; - - /** - * Destroys this effect, releasing it from the Camera. - */ - destroy(): void; - - } - - /** - * A Camera Shake effect. - * - * This effect will shake the camera viewport by a random amount, bounded by the specified intensity, each frame. - * - * Only the camera viewport is moved. 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 Shake { - /** - * - * @param camera The camera this effect is acting upon. - */ - constructor(camera: Phaser.Cameras.Scene2D.Camera); - - /** - * The Camera this effect belongs to. - */ - readonly camera: Phaser.Cameras.Scene2D.Camera; - - /** - * Is this effect actively running? - */ - readonly isRunning: boolean; - - /** - * The duration of the effect, in milliseconds. - */ - readonly duration: integer; - - /** - * The intensity of the effect. Use small float values. The default when the effect starts is 0.05. - * This is a Vector2 object, allowing you to control the shake intensity independently across x and y. - * You can modify this value while the effect is active to create more varied shake effects. - */ - intensity: Phaser.Math.Vector2; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - */ - progress: number; - - /** - * Shakes the Camera by the given intensity over the duration specified. - * @param duration The duration of the effect in milliseconds. Default 100. - * @param intensity The intensity of the shake. Default 0.05. - * @param force Force the shake effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - start(duration?: integer, intensity?: number | Phaser.Math.Vector2, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraShakeCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * The pre-render step for this effect. Called automatically by the Camera. - */ - preRender(): void; - - /** - * The main update loop for this effect. Called automatically by the Camera. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - update(time: integer, delta: number): void; - - /** - * Called internally when the effect completes. - */ - effectComplete(): void; - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - */ - reset(): void; - - /** - * Destroys this effect, releasing it from the Camera. - */ - destroy(): void; - - } - - /** - * A Camera Zoom effect. - * - * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. - * - * 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 Zoom { - /** - * - * @param camera The camera this effect is acting upon. - */ - constructor(camera: Phaser.Cameras.Scene2D.Camera); - - /** - * The Camera this effect belongs to. - */ - readonly camera: Phaser.Cameras.Scene2D.Camera; - - /** - * Is this effect actively running? - */ - readonly isRunning: boolean; - - /** - * The duration of the effect, in milliseconds. - */ - readonly duration: integer; - - /** - * The starting zoom value; - */ - source: number; - - /** - * The destination zoom value. - */ - destination: number; - - /** - * The ease function to use during the zoom. - */ - ease: Function; - - /** - * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. - */ - progress: number; - - /** - * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. - * @param zoom The target Camera zoom value. - * @param duration The duration of the effect in milliseconds. Default 1000. - * @param ease The ease to use for the Zoom. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. - * @param force Force the zoom effect to start immediately, even if already running. Default false. - * @param callback This callback will be invoked every frame for the duration of the effect. - * It is sent three arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, - * and the current camera zoom value. - * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. - */ - start(zoom: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraZoomCallback, context?: any): Phaser.Cameras.Scene2D.Camera; - - /** - * The main update loop for this effect. Called automatically by the Camera. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - update(time: integer, delta: number): void; - - /** - * Called internally when the effect completes. - */ - effectComplete(): void; - - /** - * Resets this camera effect. - * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. - */ - reset(): void; - - /** - * Destroys this effect, releasing it from the Camera. - */ - destroy(): void; - - } - - } - - namespace Events { - /** - * The Destroy Camera Event. - * - * This event is dispatched by a Camera instance when it is destroyed by the Camera Manager. - */ - const DESTROY: any; - - /** - * The Camera Fade In Complete Event. - * - * This event is dispatched by a Camera instance when the Fade In Effect completes. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeincomplete', listener)`. - */ - const FADE_IN_COMPLETE: any; - - /** - * The Camera Fade In Start Event. - * - * This event is dispatched by a Camera instance when the Fade In Effect starts. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeinstart', listener)`. - */ - const FADE_IN_START: any; - - /** - * The Camera Fade Out Complete Event. - * - * This event is dispatched by a Camera instance when the Fade Out Effect completes. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeoutcomplete', listener)`. - */ - const FADE_OUT_COMPLETE: any; - - /** - * The Camera Fade Out Start Event. - * - * This event is dispatched by a Camera instance when the Fade Out Effect starts. - * - * Listen to it from a Camera instance using `Camera.on('camerafadeoutstart', listener)`. - */ - const FADE_OUT_START: any; - - /** - * The Camera Flash Complete Event. - * - * This event is dispatched by a Camera instance when the Flash Effect completes. - */ - const FLASH_COMPLETE: any; - - /** - * The Camera Flash Start Event. - * - * This event is dispatched by a Camera instance when the Flash Effect starts. - */ - const FLASH_START: any; - - /** - * The Camera Pan Complete Event. - * - * This event is dispatched by a Camera instance when the Pan Effect completes. - */ - const PAN_COMPLETE: any; - - /** - * The Camera Pan Start Event. - * - * This event is dispatched by a Camera instance when the Pan Effect starts. - */ - const PAN_START: any; - - /** - * The Camera Post-Render Event. - * - * This event is dispatched by a Camera instance after is has finished rendering. - * It is only dispatched if the Camera is rendering to a texture. - * - * Listen to it from a Camera instance using: `camera.on('postrender', listener)`. - */ - const POST_RENDER: any; - - /** - * The Camera Pre-Render Event. - * - * This event is dispatched by a Camera instance when it is about to render. - * It is only dispatched if the Camera is rendering to a texture. - * - * Listen to it from a Camera instance using: `camera.on('prerender', listener)`. - */ - const PRE_RENDER: any; - - /** - * The Camera Shake Complete Event. - * - * This event is dispatched by a Camera instance when the Shake Effect completes. - */ - const SHAKE_COMPLETE: any; - - /** - * The Camera Shake Start Event. - * - * This event is dispatched by a Camera instance when the Shake Effect starts. - */ - const SHAKE_START: any; - - /** - * The Camera Zoom Complete Event. - * - * This event is dispatched by a Camera instance when the Zoom Effect completes. - */ - const ZOOM_COMPLETE: any; - - /** - * The Camera Zoom Start Event. - * - * This event is dispatched by a Camera instance when the Zoom Effect starts. - */ - const ZOOM_START: any; - - } - - } - - namespace Controls { - /** - * A Fixed Key Camera Control. - * - * This allows you to control the movement and zoom of a camera using the defined keys. - * - * ```javascript - * var camControl = new FixedKeyControl({ - * camera: this.cameras.main, - * left: cursors.left, - * right: cursors.right, - * speed: float OR { x: 0, y: 0 } - * }); - * ``` - * - * Movement is precise and has no 'smoothing' applied to it. - * - * You must call the `update` method of this controller every frame. - */ - class FixedKeyControl { - /** - * - * @param config The Fixed Key Control configuration object. - */ - constructor(config: Phaser.Types.Cameras.Controls.FixedKeyControlConfig); - - /** - * The Camera that this Control will update. - */ - camera: Phaser.Cameras.Scene2D.Camera; - - /** - * The Key to be pressed that will move the Camera left. - */ - left: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will move the Camera right. - */ - right: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will move the Camera up. - */ - up: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will move the Camera down. - */ - down: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will zoom the Camera in. - */ - zoomIn: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will zoom the Camera out. - */ - zoomOut: Phaser.Input.Keyboard.Key; - - /** - * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. - */ - zoomSpeed: number; - - /** - * The horizontal speed the camera will move. - */ - speedX: number; - - /** - * The vertical speed the camera will move. - */ - speedY: number; - - /** - * A flag controlling if the Controls will update the Camera or not. - */ - active: boolean; - - /** - * Starts the Key Control running, providing it has been linked to a camera. - */ - start(): Phaser.Cameras.Controls.FixedKeyControl; - - /** - * Stops this Key Control from running. Call `start` to start it again. - */ - stop(): Phaser.Cameras.Controls.FixedKeyControl; - - /** - * Binds this Key Control to a camera. - * @param camera The camera to bind this Key Control to. - */ - setCamera(camera: Phaser.Cameras.Scene2D.Camera): Phaser.Cameras.Controls.FixedKeyControl; - - /** - * Applies the results of pressing the control keys to the Camera. - * - * You must call this every step, it is not called automatically. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(delta: number): void; - - /** - * Destroys this Key Control. - */ - destroy(): void; - - } - - /** - * A Smoothed Key Camera Control. - * - * This allows you to control the movement and zoom of a camera using the defined keys. - * Unlike the Fixed Camera Control you can also provide physics values for acceleration, drag and maxSpeed for smoothing effects. - * - * ```javascript - * var controlConfig = { - * camera: this.cameras.main, - * left: cursors.left, - * right: cursors.right, - * up: cursors.up, - * down: cursors.down, - * zoomIn: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q), - * zoomOut: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.E), - * zoomSpeed: 0.02, - * acceleration: 0.06, - * drag: 0.0005, - * maxSpeed: 1.0 - * }; - * ``` - * - * You must call the `update` method of this controller every frame. - */ - class SmoothedKeyControl { - /** - * - * @param config The Smoothed Key Control configuration object. - */ - constructor(config: Phaser.Types.Cameras.Controls.SmoothedKeyControlConfig); - - /** - * The Camera that this Control will update. - */ - camera: Phaser.Cameras.Scene2D.Camera; - - /** - * The Key to be pressed that will move the Camera left. - */ - left: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will move the Camera right. - */ - right: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will move the Camera up. - */ - up: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will move the Camera down. - */ - down: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will zoom the Camera in. - */ - zoomIn: Phaser.Input.Keyboard.Key; - - /** - * The Key to be pressed that will zoom the Camera out. - */ - zoomOut: Phaser.Input.Keyboard.Key; - - /** - * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. - */ - zoomSpeed: number; - - /** - * The horizontal acceleration the camera will move. - */ - accelX: number; - - /** - * The vertical acceleration the camera will move. - */ - accelY: number; - - /** - * The horizontal drag applied to the camera when it is moving. - */ - dragX: number; - - /** - * The vertical drag applied to the camera when it is moving. - */ - dragY: number; - - /** - * The maximum horizontal speed the camera will move. - */ - maxSpeedX: number; - - /** - * The maximum vertical speed the camera will move. - */ - maxSpeedY: number; - - /** - * A flag controlling if the Controls will update the Camera or not. - */ - active: boolean; - - /** - * Starts the Key Control running, providing it has been linked to a camera. - */ - start(): Phaser.Cameras.Controls.SmoothedKeyControl; - - /** - * Stops this Key Control from running. Call `start` to start it again. - */ - stop(): Phaser.Cameras.Controls.SmoothedKeyControl; - - /** - * Binds this Key Control to a camera. - * @param camera The camera to bind this Key Control to. - */ - setCamera(camera: Phaser.Cameras.Scene2D.Camera): Phaser.Cameras.Controls.SmoothedKeyControl; - - /** - * Applies the results of pressing the control keys to the Camera. - * - * You must call this every step, it is not called automatically. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(delta: number): void; - - /** - * Destroys this Key Control. - */ - destroy(): void; - - } - - } - - } - - /** - * Phaser Release Version - */ - const VERSION: string; - - /** - * AUTO Detect Renderer. - */ - const AUTO: integer; - - /** - * Canvas Renderer. - */ - const CANVAS: integer; - - /** - * WebGL Renderer. - */ - const WEBGL: integer; - - /** - * Headless Renderer. - */ - const HEADLESS: integer; - - /** - * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead - * to help you remember what the value is doing in your code. - */ - const FOREVER: integer; - - /** - * Direction constant. - */ - const NONE: integer; - - /** - * Direction constant. - */ - const UP: integer; - - /** - * Direction constant. - */ - const DOWN: integer; - - /** - * Direction constant. - */ - const LEFT: integer; - - /** - * Direction constant. - */ - const RIGHT: integer; - - /** - * The Phaser.Game instance is the main controller for the entire Phaser game. It is responsible - * for handling the boot process, parsing the configuration values, creating the renderer, - * and setting-up all of the global Phaser systems, such as sound and input. - * Once that is complete it will start the Scene Manager and then begin the main game loop. - * - * You should generally avoid accessing any of the systems created by Game, and instead use those - * made available to you via the Phaser.Scene Systems class instead. - */ - class Game { - /** - * - * @param GameConfig The configuration object for your Phaser Game instance. - */ - constructor(GameConfig?: Phaser.Types.Core.GameConfig); - - /** - * The parsed Game Configuration object. - * - * The values stored within this object are read-only and should not be changed at run-time. - */ - readonly config: Phaser.Core.Config; - - /** - * A reference to either the Canvas or WebGL Renderer that this Game is using. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * A reference to an HTML Div Element used as the DOM Element Container. - * - * Only set if `createDOMContainer` is `true` in the game config (by default it is `false`) and - * if you provide a parent element to insert the Phaser Game inside. - * - * See the DOM Element Game Object for more details. - */ - domContainer: HTMLDivElement; - - /** - * A reference to the HTML Canvas Element that Phaser uses to render the game. - * This is created automatically by Phaser unless you provide a `canvas` property - * in your Game Config. - */ - canvas: HTMLCanvasElement; - - /** - * A reference to the Rendering Context belonging to the Canvas Element this game is rendering to. - * If the game is running under Canvas it will be a 2d Canvas Rendering Context. - * If the game is running under WebGL it will be a WebGL Rendering Context. - * This context is created automatically by Phaser unless you provide a `context` property - * in your Game Config. - */ - context: CanvasRenderingContext2D | WebGLRenderingContext; - - /** - * A flag indicating when this Game instance has finished its boot process. - */ - readonly isBooted: boolean; - - /** - * A flag indicating if this Game is currently running its game step or not. - */ - readonly isRunning: boolean; - - /** - * An Event Emitter which is used to broadcast game-level events from the global systems. - */ - events: Phaser.Events.EventEmitter; - - /** - * An instance of the Animation Manager. - * - * The Animation Manager is a global system responsible for managing all animations used within your game. - */ - anims: Phaser.Animations.AnimationManager; - - /** - * An instance of the Texture Manager. - * - * The Texture Manager is a global system responsible for managing all textures being used by your game. - */ - textures: Phaser.Textures.TextureManager; - - /** - * An instance of the Cache Manager. - * - * The Cache Manager is a global system responsible for caching, accessing and releasing external game assets. - */ - cache: Phaser.Cache.CacheManager; - - /** - * An instance of the Data Manager - */ - registry: Phaser.Data.DataManager; - - /** - * An instance of the Input Manager. - * - * The Input Manager is a global system responsible for the capture of browser-level input events. - */ - input: Phaser.Input.InputManager; - - /** - * An instance of the Scene Manager. - * - * The Scene Manager is a global system responsible for creating, modifying and updating the Scenes in your game. - */ - scene: Phaser.Scenes.SceneManager; - - /** - * A reference to the Device inspector. - * - * Contains information about the device running this game, such as OS, browser vendor and feature support. - * Used by various systems to determine capabilities and code paths. - */ - device: Phaser.DeviceConf; - - /** - * An instance of the Scale Manager. - * - * The Scale Manager is a global system responsible for handling scaling of the game canvas. - */ - scale: Phaser.Scale.ScaleManager; - - /** - * An instance of the base Sound Manager. - * - * The Sound Manager is a global system responsible for the playback and updating of all audio in your game. - * - * You can disable the inclusion of the Sound Manager in your build by toggling the webpack `FEATURE_SOUND` flag. - */ - sound: Phaser.Sound.NoAudioSoundManager | Phaser.Sound.HTML5AudioSoundManager | Phaser.Sound.WebAudioSoundManager; - - /** - * An instance of the Time Step. - * - * The Time Step is a global system responsible for setting-up and responding to the browser frame events, processing - * them and calculating delta values. It then automatically calls the game step. - */ - loop: Phaser.Core.TimeStep; - - /** - * An instance of the Plugin Manager. - * - * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install - * those plugins into Scenes as required. - */ - plugins: Phaser.Plugins.PluginManager; - - /** - * An instance of the Facebook Instant Games Plugin. - * - * This will only be available if the plugin has been built into Phaser, - * or you're using the special Facebook Instant Games custom build. - */ - facebook: Phaser.FacebookInstantGamesPlugin; - - /** - * Does the window the game is running in currently have focus or not? - * This is modified by the VisibilityHandler. - */ - readonly hasFocus: boolean; - - /** - * This method is called automatically when the DOM is ready. It is responsible for creating the renderer, - * displaying the Debug Header, adding the game canvas to the DOM and emitting the 'boot' event. - * It listens for a 'ready' event from the base systems and once received it will call `Game.start`. - */ - protected boot(): void; - - /** - * Called automatically by Game.boot once all of the global systems have finished setting themselves up. - * By this point the Game is now ready to start the main loop running. - * It will also enable the Visibility Handler. - */ - protected start(): void; - - /** - * 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. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - step(time: number, delta: number): void; - - /** - * 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. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - headlessStep(time: number, delta: number): void; - - /** - * Called automatically by the Visibility Handler. - * This will pause the main loop and then emit a pause event. - */ - protected onHidden(): void; - - /** - * Called automatically by the Visibility Handler. - * This will resume the main loop and then emit a resume event. - */ - protected onVisible(): void; - - /** - * Called automatically by the Visibility Handler. - * This will set the main loop into a 'blurred' state, which pauses it. - */ - protected onBlur(): void; - - /** - * Called automatically by the Visibility Handler. - * This will set the main loop into a 'focused' state, which resumes it. - */ - protected onFocus(): void; - - /** - * Returns the current game frame. - * - * When the game starts running, the frame is incremented every time Request Animation Frame, or Set Timeout, fires. - */ - getFrame(): number; - - /** - * Returns the time that the current game step started at, as based on `performance.now`. - */ - getTime(): number; - - /** - * Flags this Game instance as needing to be destroyed on the _next frame_, making this an asynchronous operation. - * - * It will wait until the current frame has completed and then call `runDestroy` internally. - * - * If you need to react to the games eventual destruction, listen for the `DESTROY` event. - * - * If you **do not** need to run Phaser again on the same web page you can set the `noReturn` argument to `true` and it will free-up - * memory being held by the core Phaser plugins. If you do need to create another game instance on the same page, leave this as `false`. - * @param removeCanvas Set to `true` if you would like the parent canvas element removed from the DOM, or `false` to leave it in place. - * @param noReturn If `true` all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this. Default false. - */ - destroy(removeCanvas: boolean, noReturn?: boolean): void; - - } - - namespace Core { - /** - * The active game configuration settings, parsed from a {@link Phaser.Types.Core.GameConfig} object. - */ - class Config { - /** - * - * @param GameConfig The configuration object for your Phaser Game instance. - */ - constructor(GameConfig?: Phaser.Types.Core.GameConfig); - - /** - * The width of the underlying canvas, in pixels. - */ - readonly width: integer | string; - - /** - * The height of the underlying canvas, in pixels. - */ - readonly height: integer | string; - - /** - * The zoom factor, as used by the Scale Manager. - */ - readonly zoom: Phaser.Scale.ZoomType | integer; - - /** - * The canvas device pixel resolution. Currently un-used. - */ - readonly resolution: number; - - /** - * A parent DOM element into which the canvas created by the renderer will be injected. - */ - readonly parent: any; - - /** - * The scale mode as used by the Scale Manager. The default is zero, which is no scaling. - */ - readonly scaleMode: Phaser.Scale.ScaleModeType; - - /** - * Is the Scale Manager allowed to adjust the CSS height property of the parent to be 100%? - */ - readonly expandParent: boolean; - - /** - * Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. - */ - readonly autoRound: integer; - - /** - * Automatically center the canvas within the parent? - */ - readonly autoCenter: Phaser.Scale.CenterType; - - /** - * How many ms should elapse before checking if the browser size has changed? - */ - readonly resizeInterval: integer; - - /** - * The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. - */ - readonly fullscreenTarget: HTMLElement | string; - - /** - * The minimum width, in pixels, the canvas will scale down to. A value of zero means no minimum. - */ - readonly minWidth: integer; - - /** - * The maximum width, in pixels, the canvas will scale up to. A value of zero means no maximum. - */ - readonly maxWidth: integer; - - /** - * The minimum height, in pixels, the canvas will scale down to. A value of zero means no minimum. - */ - readonly minHeight: integer; - - /** - * The maximum height, in pixels, the canvas will scale up to. A value of zero means no maximum. - */ - readonly maxHeight: integer; - - /** - * Force Phaser to use a specific renderer. Can be `CONST.CANVAS`, `CONST.WEBGL`, `CONST.HEADLESS` or `CONST.AUTO` (default) - */ - readonly renderType: number; - - /** - * Force Phaser to use your own Canvas element instead of creating one. - */ - readonly canvas: HTMLCanvasElement; - - /** - * Force Phaser to use your own Canvas context instead of creating one. - */ - readonly context: CanvasRenderingContext2D | WebGLRenderingContext; - - /** - * Optional CSS attributes to be set on the canvas object created by the renderer. - */ - readonly canvasStyle: string; - - /** - * Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. - */ - readonly customEnvironment: boolean; - - /** - * The default Scene configuration object. - */ - readonly sceneConfig: object; - - /** - * A seed which the Random Data Generator will use. If not given, a dynamic seed based on the time is used. - */ - readonly seed: string[]; - - /** - * The title of the game. - */ - readonly gameTitle: string; - - /** - * The URL of the game. - */ - readonly gameURL: string; - - /** - * The version of the game. - */ - readonly gameVersion: string; - - /** - * If `true` the window will automatically be given focus immediately and on any future mousedown event. - */ - readonly autoFocus: boolean; - - /** - * Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. - */ - readonly domCreateContainer: boolean; - - /** - * Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? - */ - readonly domBehindCanvas: boolean; - - /** - * Enable the Keyboard Plugin. This can be disabled in games that don't need keyboard input. - */ - readonly inputKeyboard: boolean; - - /** - * The DOM Target to listen for keyboard events on. Defaults to `window` if not specified. - */ - readonly inputKeyboardEventTarget: any; - - /** - * `preventDefault` will be called on every non-modified key which has a key code in this array. By default, it is empty. - */ - readonly inputKeyboardCapture: integer[]; - - /** - * Enable the Mouse Plugin. This can be disabled in games that don't need mouse input. - */ - readonly inputMouse: boolean | object; - - /** - * The DOM Target to listen for mouse events on. Defaults to the game canvas if not specified. - */ - readonly inputMouseEventTarget: any; - - /** - * Should mouse events be captured? I.e. have prevent default called on them. - */ - readonly inputMouseCapture: boolean; - - /** - * Enable the Touch Plugin. This can be disabled in games that don't need touch input. - */ - readonly inputTouch: boolean; - - /** - * The DOM Target to listen for touch events on. Defaults to the game canvas if not specified. - */ - readonly inputTouchEventTarget: any; - - /** - * Should touch events be captured? I.e. have prevent default called on them. - */ - readonly inputTouchCapture: boolean; - - /** - * The number of Pointer objects created by default. In a mouse-only, or non-multi touch game, you can leave this as 1. - */ - readonly inputActivePointers: integer; - - /** - * The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. - */ - readonly inputSmoothFactor: integer; - - /** - * Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. - */ - readonly inputWindowEvents: boolean; - - /** - * Enable the Gamepad Plugin. This can be disabled in games that don't need gamepad input. - */ - readonly inputGamepad: boolean; - - /** - * The DOM Target to listen for gamepad events on. Defaults to `window` if not specified. - */ - readonly inputGamepadEventTarget: any; - - /** - * Set to `true` to disable the right-click context menu. - */ - readonly disableContextMenu: boolean; - - /** - * The Audio Configuration object. - */ - readonly audio: Phaser.Types.Core.AudioConfig; - - /** - * Don't write the banner line to the console.log. - */ - readonly hideBanner: boolean; - - /** - * Omit Phaser's name and version from the banner. - */ - readonly hidePhaser: boolean; - - /** - * The color of the banner text. - */ - readonly bannerTextColor: string; - - /** - * The background colors of the banner. - */ - readonly bannerBackgroundColor: string[]; - - /** - * The Frame Rate Configuration object, as parsed by the Timestep class. - */ - readonly fps: Phaser.Types.Core.FPSConfig; - - /** - * When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. - */ - readonly antialias: boolean; - - /** - * Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. - */ - readonly antialiasGL: boolean; - - /** - * Sets the `mipmapFilter` property when the WebGL renderer is created. - */ - readonly mipmapFilter: string; - - /** - * 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. - */ - readonly desynchronized: boolean; - - /** - * Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. - */ - readonly roundPixels: boolean; - - /** - * Prevent pixel art from becoming blurred when scaled. It will remain crisp (tells the WebGL renderer to automatically create textures using a linear filter mode). - */ - readonly pixelArt: boolean; - - /** - * Whether the game canvas will have a transparent background. - */ - readonly transparent: boolean; - - /** - * Whether the game canvas will be cleared between each rendering frame. You can disable this if you have a full-screen background image or game object. - */ - readonly clearBeforeRender: boolean; - - /** - * In WebGL mode, sets the drawing buffer to contain colors with pre-multiplied alpha. - */ - readonly premultipliedAlpha: boolean; - - /** - * Let the browser abort creating a WebGL context if it judges performance would be unacceptable. - */ - readonly failIfMajorPerformanceCaveat: boolean; - - /** - * "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. - */ - readonly powerPreference: string; - - /** - * The default WebGL Batch size. - */ - readonly batchSize: integer; - - /** - * The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. - */ - readonly maxLights: integer; - - /** - * The background color of the game canvas. The default is black. This value is ignored if `transparent` is set to `true`. - */ - readonly backgroundColor: Phaser.Display.Color; - - /** - * Called before Phaser boots. Useful for initializing anything not related to Phaser that Phaser may require while booting. - */ - readonly preBoot: Phaser.Types.Core.BootCallback; - - /** - * A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. - */ - readonly postBoot: Phaser.Types.Core.BootCallback; - - /** - * The Physics Configuration object. - */ - readonly physics: Phaser.Types.Core.PhysicsConfig; - - /** - * The default physics system. It will be started for each scene. Either 'arcade', 'impact' or 'matter'. - */ - readonly defaultPhysicsSystem: boolean | string; - - /** - * A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. - */ - readonly loaderBaseURL: string; - - /** - * A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. - */ - readonly loaderPath: string; - - /** - * Maximum parallel downloads allowed for resources (Default to 32). - */ - readonly loaderMaxParallelDownloads: integer; - - /** - * '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}. - */ - readonly loaderCrossOrigin: string | undefined; - - /** - * The response type of the XHR request, e.g. `blob`, `text`, etc. - */ - readonly loaderResponseType: string; - - /** - * Should the XHR request use async or not? - */ - readonly loaderAsync: boolean; - - /** - * Optional username for all XHR requests. - */ - readonly loaderUser: string; - - /** - * Optional password for all XHR requests. - */ - readonly loaderPassword: string; - - /** - * Optional XHR timeout value, in ms. - */ - readonly loaderTimeout: integer; - - /** - * An array of global plugins to be installed. - */ - readonly installGlobalPlugins: any; - - /** - * An array of Scene level plugins to be installed. - */ - readonly installScenePlugins: any; - - /** - * The plugins installed into every Scene (in addition to CoreScene and Global). - */ - readonly defaultPlugins: any; - - /** - * A base64 encoded PNG that will be used as the default blank texture. - */ - readonly defaultImage: string; - - /** - * A base64 encoded PNG that will be used as the default texture when a texture is assigned that is missing or not loaded. - */ - readonly missingImage: string; - - } - - /** - * Called automatically by Phaser.Game and responsible for creating the renderer it will use. - * - * Relies upon two webpack global flags to be defined: `WEBGL_RENDERER` and `CANVAS_RENDERER` during build time, but not at run-time. - * @param game The Phaser.Game instance on which the renderer will be set. - */ - function CreateRenderer(game: Phaser.Game): void; - - /** - * Called automatically by Phaser.Game and responsible for creating the console.log debug header. - * - * You can customize or disable the header via the Game Config object. - * @param game The Phaser.Game instance which will output this debug header. - */ - function DebugHeader(game: Phaser.Game): void; - - namespace Events { - /** - * The Game Blur Event. - * - * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded - * enters a blurred state. The blur event is raised when the window loses focus. This can happen if a user swaps - * tab, or if they simply remove focus from the browser to another app. - */ - const BLUR: any; - - /** - * The Game Boot Event. - * - * This event is dispatched when the Phaser Game instance has finished booting, but before it is ready to start running. - * The global systems use this event to know when to set themselves up, dispatching their own `ready` events as required. - */ - const BOOT: any; - - /** - * The Game Context Lost Event. - * - * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Lost event from the browser. - * - * The partner event is `CONTEXT_RESTORED`. - */ - const CONTEXT_LOST: any; - - /** - * The Game Context Restored Event. - * - * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Restored event from the browser. - * - * The partner event is `CONTEXT_LOST`. - */ - const CONTEXT_RESTORED: any; - - /** - * The Game Destroy Event. - * - * This event is dispatched when the game instance has been told to destroy itself. - * Lots of internal systems listen to this event in order to clear themselves out. - * Custom plugins and game code should also do the same. - */ - const DESTROY: any; - - /** - * The Game Focus Event. - * - * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded - * enters a focused state. The focus event is raised when the window re-gains focus, having previously lost it. - */ - const FOCUS: any; - - /** - * The Game Hidden Event. - * - * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded - * enters a hidden state. Only browsers that support the Visibility API will cause this event to be emitted. - * - * In most modern browsers, when the document enters a hidden state, the Request Animation Frame and setTimeout, which - * control the main game loop, will automatically pause. There is no way to stop this from happening. It is something - * your game should account for in its own code, should the pause be an issue (i.e. for multiplayer games) - */ - const HIDDEN: any; - - /** - * The Game Pause Event. - * - * This event is dispatched when the Game loop enters a paused state, usually as a result of the Visibility Handler. - */ - const PAUSE: any; - - /** - * The Game Post-Render Event. - * - * This event is dispatched right at the end of the render process. - * - * Every Scene will have rendered and been drawn to the canvas by the time this event is fired. - * Use it for any last minute post-processing before the next game step begins. - */ - const POST_RENDER: any; - - /** - * 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. - */ - const POST_STEP: any; - - /** - * The Game Pre-Render Event. - * - * This event is dispatched immediately before any of the Scenes have started to render. - * - * The renderer will already have been initialized this frame, clearing itself and preparing to receive the Scenes for rendering, but it won't have actually drawn anything yet. - */ - const PRE_RENDER: any; - - /** - * 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. - */ - const PRE_STEP: any; - - /** - * The Game Ready Event. - * - * This event is dispatched when the Phaser Game instance has finished booting, the Texture Manager is fully ready, - * and all local systems are now able to start. - */ - const READY: any; - - /** - * The Game Resume Event. - * - * This event is dispatched when the game loop leaves a paused state and resumes running. - */ - const RESUME: any; - - /** - * 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. - */ - const STEP: any; - - /** - * The Game Visible Event. - * - * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded - * enters a visible state, previously having been hidden. - * - * Only browsers that support the Visibility API will cause this event to be emitted. - */ - const VISIBLE: any; - - } - - /** - * 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 { - /** - * - * @param game A reference to the Phaser.Game instance that owns this Time Step. - */ - constructor(game: Phaser.Game, config: Phaser.Types.Core.FPSConfig); - - /** - * A reference to the Phaser.Game instance. - */ - readonly game: Phaser.Game; - - /** - * The Request Animation Frame DOM Event handler. - */ - readonly raf: Phaser.DOM.RequestAnimationFrame; - - /** - * A flag that is set once the TimeStep has started running and toggled when it stops. - */ - readonly started: boolean; - - /** - * A flag that is set once the TimeStep has started running and toggled when it stops. - * The difference between this value and `started` is that `running` is toggled when - * the TimeStep is sent to sleep, where-as `started` remains `true`, only changing if - * the TimeStep is actually stopped, not just paused. - */ - readonly running: boolean; - - /** - * The minimum fps rate you want the Time Step to run at. - */ - minFps: integer; - - /** - * The target fps rate for the Time Step to run at. - * - * Setting this value will not actually change the speed at which the browser runs, that is beyond - * the control of Phaser. Instead, it allows you to determine performance issues and if the Time Step - * is spiraling out of control. - */ - targetFps: integer; - - /** - * An exponential moving average of the frames per second. - */ - readonly actualFps: integer; - - /** - * The time at which the next fps rate update will take place. - * When an fps update happens, the `framesThisSecond` value is reset. - */ - readonly nextFpsUpdate: integer; - - /** - * The number of frames processed this second. - */ - readonly framesThisSecond: integer; - - /** - * A callback to be invoked each time the Time Step steps. - */ - callback: Phaser.Types.Core.TimeStepCallback; - - /** - * You can force the Time Step to use Set Timeout instead of Request Animation Frame by setting - * the `forceSetTimeOut` property to `true` in the Game Configuration object. It cannot be changed at run-time. - */ - readonly forceSetTimeOut: boolean; - - /** - * The time, calculated at the start of the current step, as smoothed by the delta value. - */ - time: number; - - /** - * The time at which the game started running. This value is adjusted if the game is then - * paused and resumes. - */ - startTime: number; - - /** - * The time, as returned by `performance.now` of the previous step. - */ - lastTime: number; - - /** - * The current frame the game is on. This counter is incremented once every game step, regardless of how much - * time has passed and is unaffected by delta smoothing. - */ - readonly frame: integer; - - /** - * Is the browser currently considered in focus by the Page Visibility API? - * This value is set in the `blur` method, which is called automatically by the Game instance. - */ - readonly inFocus: boolean; - - /** - * The delta time, in ms, since the last game step. This is a clamped and smoothed average value. - */ - delta: integer; - - /** - * Internal index of the delta history position. - */ - deltaIndex: integer; - - /** - * Internal array holding the previous delta values, used for delta smoothing. - */ - deltaHistory: integer[]; - - /** - * The maximum number of delta values that are retained in order to calculate a smoothed moving average. - * - * This can be changed in the Game Config via the `fps.deltaHistory` property. The default is 10. - */ - deltaSmoothingMax: integer; - - /** - * The number of frames that the cooldown is set to after the browser panics over the FPS rate, usually - * as a result of switching tabs and regaining focus. - * - * This can be changed in the Game Config via the `fps.panicMax` property. The default is 120. - */ - panicMax: integer; - - /** - * The actual elapsed time in ms between one update and the next. - * - * Unlike with `delta`, no smoothing, capping, or averaging is applied to this value. - * So please be careful when using this value in math calculations. - */ - rawDelta: number; - - /** - * The time, as returned by `performance.now` at the very start of the current step. - * This can differ from the `time` value in that it isn't calculated based on the delta value. - */ - now: number; - - /** - * Apply smoothing to the delta value used within Phasers internal calculations? - * - * This can be changed in the Game Config via the `fps.smoothStep` property. The default is `true`. - * - * Smoothing helps settle down the delta values after browser tab switches, or other situations - * which could cause significant delta spikes or dips. By default it has been enabled in Phaser 3 - * since the first version, but is now exposed under this property (and the corresponding game config - * `smoothStep` value), to allow you to easily disable it, should you require. - */ - smoothStep: boolean; - - /** - * Called by the Game instance when the DOM window.onBlur event triggers. - */ - blur(): void; - - /** - * Called by the Game instance when the DOM window.onFocus event triggers. - */ - focus(): void; - - /** - * Called when the visibility API says the game is 'hidden' (tab switch out of view, etc) - */ - pause(): void; - - /** - * Called when the visibility API says the game is 'visible' again (tab switch back into view, etc) - */ - resume(): void; - - /** - * Resets the time, lastTime, fps averages and delta history. - * Called automatically when a browser sleeps them resumes. - */ - resetDelta(): void; - - /** - * Starts the Time Step running, if it is not already doing so. - * Called automatically by the Game Boot process. - * @param callback The callback to be invoked each time the Time Step steps. - */ - start(callback: Phaser.Types.Core.TimeStepCallback): void; - - /** - * The main step method. This is called each time the browser updates, either by Request Animation Frame, - * or by Set Timeout. It is responsible for calculating the delta values, frame totals, cool down history and more. - * You generally should never call this method directly. - */ - step(): void; - - /** - * Manually calls `TimeStep.step`. - */ - tick(): void; - - /** - * Sends the TimeStep to sleep, stopping Request Animation Frame (or SetTimeout) and toggling the `running` flag to false. - */ - sleep(): void; - - /** - * 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. - * @param seamless Adjust the startTime based on the lastTime values. Default false. - */ - wake(seamless?: boolean): void; - - /** - * Gets the duration which the game has been running, in seconds. - */ - getDuration(): number; - - /** - * Gets the duration which the game has been running, in ms. - */ - getDurationMS(): number; - - /** - * Stops the TimeStep running. - */ - stop(): this; - - /** - * Destroys the TimeStep. This will stop Request Animation Frame, stop the step, clear the callbacks and null - * any objects. - */ - destroy(): void; - - } - - /** - * The Visibility Handler is responsible for listening out for document level visibility change events. - * This includes `visibilitychange` if the browser supports it, and blur and focus events. It then uses - * the provided Event Emitter and fires the related events. - * @param game The Game instance this Visibility Handler is working on. - */ - function VisibilityHandler(game: Phaser.Game): void; - - } - - namespace Create { - /** - * [description] - * @param config [description] - */ - function GenerateTexture(config: Phaser.Types.Create.GenerateTextureConfig): HTMLCanvasElement; - - namespace Palettes { - /** - * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) - */ - var ARNE16: Phaser.Types.Create.Palette; - - /** - * A 16 color palette inspired by the Commodore 64. - */ - var C64: Phaser.Types.Create.Palette; - - /** - * A 16 color CGA inspired palette by [Arne](http://androidarts.com/palette/16pal.htm) - */ - var CGA: Phaser.Types.Create.Palette; - - /** - * A 16 color JMP palette by [Arne](http://androidarts.com/palette/16pal.htm) - */ - var JMP: Phaser.Types.Create.Palette; - - /** - * A 16 color palette inspired by Japanese computers like the MSX. - */ - var MSX: Phaser.Types.Create.Palette; - - } - - } - - namespace Curves { - /** - * A higher-order Bézier curve constructed of four points. - */ - class CubicBezier extends Phaser.Curves.Curve { - /** - * - * @param p0 Start point, or an array of point pairs. - * @param p1 Control Point 1. - * @param p2 Control Point 2. - * @param p3 End Point. - */ - constructor(p0: Phaser.Math.Vector2 | Phaser.Math.Vector2[], p1: Phaser.Math.Vector2, p2: Phaser.Math.Vector2, p3: Phaser.Math.Vector2); - - /** - * The start point of this curve. - */ - p0: Phaser.Math.Vector2; - - /** - * The first control point of this curve. - */ - p1: Phaser.Math.Vector2; - - /** - * The second control point of this curve. - */ - p2: Phaser.Math.Vector2; - - /** - * The end point of this curve. - */ - p3: Phaser.Math.Vector2; - - /** - * Gets the starting point on the curve. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getStartPoint(out?: O): O; - - /** - * Returns the resolution of this curve. - * @param divisions The amount of divisions used by this curve. - */ - getResolution(divisions: number): number; - - /** - * Get point at relative position in curve according to length. - * @param t The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPoint(t: number, out?: O): O; - - /** - * Draws this curve to the specified graphics object. - * @param graphics The graphics object this curve should be drawn to. - * @param pointsTotal The number of intermediary points that make up this curve. A higher number of points will result in a smoother curve. Default 32. - */ - draw(graphics: G, pointsTotal?: integer): G; - - /** - * Returns a JSON object that describes this curve. - */ - toJSON(): Phaser.Types.Curves.JSONCurve; - - /** - * Generates a curve from a JSON object. - * @param data The JSON object containing this curve data. - */ - static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.CubicBezier; - - } - - /** - * A Base Curve class, which all other curve types extend. - * - * Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) - */ - class Curve { - /** - * - * @param type The curve type. - */ - constructor(type: string); - - /** - * String based identifier for the type of curve. - */ - type: string; - - /** - * The default number of divisions within the curve. - */ - defaultDivisions: integer; - - /** - * The quantity of arc length divisions within the curve. - */ - arcLengthDivisions: integer; - - /** - * An array of cached arc length values. - */ - cacheArcLengths: number[]; - - /** - * Does the data of this curve need updating? - */ - needsUpdate: boolean; - - /** - * For a curve on a Path, `false` means the Path will ignore this curve. - */ - active: boolean; - - /** - * Draws this curve on the given Graphics object. - * - * The curve is drawn using `Graphics.strokePoints` so will be drawn at whatever the present Graphics stroke color is. - * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. - * @param graphics The Graphics instance onto which this curve will be drawn. - * @param pointsTotal The resolution of the curve. The higher the value the smoother it will render, at the cost of rendering performance. Default 32. - */ - draw(graphics: G, pointsTotal?: integer): G; - - /** - * Returns a Rectangle where the position and dimensions match the bounds of this Curve. - * - * You can control the accuracy of the bounds. The value given is used to work out how many points - * to plot across the curve. Higher values are more accurate at the cost of calculation speed. - * @param out The Rectangle to store the bounds in. If falsey a new object will be created. - * @param accuracy The accuracy of the bounds calculations. Default 16. - */ - getBounds(out?: Phaser.Geom.Rectangle, accuracy?: integer): Phaser.Geom.Rectangle; - - /** - * Returns an array of points, spaced out X distance pixels apart. - * The smaller the distance, the larger the array will be. - * @param distance The distance, in pixels, between each point along the curve. - */ - getDistancePoints(distance: integer): Phaser.Geom.Point[]; - - /** - * Get a point at the end of the curve. - * @param out Optional Vector object to store the result in. - */ - getEndPoint(out?: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Get total curve arc length - */ - getLength(): number; - - /** - * Get a list of cumulative segment lengths. - * - * These lengths are - * - * - [0] 0 - * - [1] The first segment - * - [2] The first and second segment - * - ... - * - [divisions] All segments - * @param divisions The number of divisions or segments. - */ - getLengths(divisions?: integer): number[]; - - /** - * Get a point at a relative position on the curve, by arc length. - * @param u The relative position, [0..1]. - * @param out A point to store the result in. - */ - getPointAt(u: number, out?: O): O; - - /** - * Get a sequence of evenly spaced points from the curve. - * - * You can pass `divisions`, `stepRate`, or neither. - * - * The number of divisions will be - * - * 1. `divisions`, if `divisions` > 0; or - * 2. `this.getLength / stepRate`, if `stepRate` > 0; or - * 3. `this.defaultDivisions` - * - * `1 + divisions` points will be returned. - * @param divisions The number of divisions to make. - * @param stepRate The curve distance between points, implying `divisions`. - * @param out An optional array to store the points in. - */ - getPoints(divisions?: integer, stepRate?: number, out?: O): O; - - /** - * Get a random point from the curve. - * @param out A point object to store the result in. - */ - getRandomPoint(out?: O): O; - - /** - * Get a sequence of equally spaced points (by arc distance) from the curve. - * - * `1 + divisions` points will be returned. - * @param divisions The number of divisions to make. Default this.defaultDivisions. - * @param stepRate Step between points. Used to calculate the number of points to return when divisions is falsy. Ignored if divisions is positive. - * @param out An optional array to store the points in. - */ - getSpacedPoints(divisions?: integer, stepRate?: number, out?: any[] | Phaser.Math.Vector2[]): Phaser.Math.Vector2[]; - - /** - * Get a point at the start of the curve. - * @param out A point to store the result in. - */ - getStartPoint(out?: O): O; - - /** - * Get a unit vector tangent at a relative position on the curve. - * In case any sub curve does not implement its tangent derivation, - * 2 points a small delta apart will be used to find its gradient - * which seems to give a reasonable approximation - * @param t The relative position on the curve, [0..1]. - * @param out A vector to store the result in. - */ - getTangent(t: number, out?: O): O; - - /** - * Get a unit vector tangent at a relative position on the curve, by arc length. - * @param u The relative position on the curve, [0..1]. - * @param out A vector to store the result in. - */ - getTangentAt(u: number, out?: O): O; - - /** - * [description] - * @param distance [description] - * @param divisions [description] - */ - getTFromDistance(distance: integer, divisions?: integer): number; - - /** - * [description] - * @param u [description] - * @param distance [description] - * @param divisions [description] - */ - getUtoTmapping(u: number, distance: integer, divisions?: integer): number; - - /** - * Calculate and cache the arc lengths. - */ - updateArcLengths(): void; - - } - - /** - * An Elliptical Curve derived from the Base Curve class. - * - * See https://en.wikipedia.org/wiki/Elliptic_curve for more details. - */ - class Ellipse extends Phaser.Curves.Curve { - /** - * - * @param x The x coordinate of the ellipse, or an Ellipse Curve configuration object. Default 0. - * @param y The y coordinate of the ellipse. Default 0. - * @param xRadius The horizontal radius of ellipse. Default 0. - * @param yRadius The vertical radius of ellipse. Default 0. - * @param startAngle The start angle of the ellipse, in degrees. Default 0. - * @param endAngle The end angle of the ellipse, in degrees. Default 360. - * @param clockwise Whether the ellipse angles are given as clockwise (`true`) or counter-clockwise (`false`). Default false. - * @param rotation The rotation of the ellipse, in degrees. Default 0. - */ - constructor(x?: number | Phaser.Types.Curves.EllipseCurveConfig, y?: number, xRadius?: number, yRadius?: number, startAngle?: integer, endAngle?: integer, clockwise?: boolean, rotation?: integer); - - /** - * The center point of the ellipse. Used for calculating rotation. - */ - p0: Phaser.Math.Vector2; - - /** - * Gets the starting point on the curve. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getStartPoint(out?: O): O; - - /** - * [description] - * @param divisions [description] - */ - getResolution(divisions: number): number; - - /** - * Get point at relative position in curve according to length. - * @param t The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPoint(t: number, out?: O): O; - - /** - * Sets the horizontal radius of this curve. - * @param value The horizontal radius of this curve. - */ - setXRadius(value: number): Phaser.Curves.Ellipse; - - /** - * Sets the vertical radius of this curve. - * @param value The vertical radius of this curve. - */ - setYRadius(value: number): Phaser.Curves.Ellipse; - - /** - * Sets the width of this curve. - * @param value The width of this curve. - */ - setWidth(value: number): Phaser.Curves.Ellipse; - - /** - * Sets the height of this curve. - * @param value The height of this curve. - */ - setHeight(value: number): Phaser.Curves.Ellipse; - - /** - * Sets the start angle of this curve. - * @param value The start angle of this curve, in radians. - */ - setStartAngle(value: number): Phaser.Curves.Ellipse; - - /** - * Sets the end angle of this curve. - * @param value The end angle of this curve, in radians. - */ - setEndAngle(value: number): Phaser.Curves.Ellipse; - - /** - * Sets if this curve extends clockwise or anti-clockwise. - * @param value The clockwise state of this curve. - */ - setClockwise(value: boolean): Phaser.Curves.Ellipse; - - /** - * Sets the rotation of this curve. - * @param value The rotation of this curve, in radians. - */ - setRotation(value: number): Phaser.Curves.Ellipse; - - /** - * The x coordinate of the center of the ellipse. - */ - x: number; - - /** - * The y coordinate of the center of the ellipse. - */ - y: number; - - /** - * The horizontal radius of the ellipse. - */ - xRadius: number; - - /** - * The vertical radius of the ellipse. - */ - yRadius: number; - - /** - * The start angle of the ellipse in degrees. - */ - startAngle: number; - - /** - * The end angle of the ellipse in degrees. - */ - endAngle: number; - - /** - * `true` if the ellipse rotation is clockwise or `false` if anti-clockwise. - */ - clockwise: boolean; - - /** - * The rotation of the ellipse, relative to the center, in degrees. - */ - angle: number; - - /** - * The rotation of the ellipse, relative to the center, in radians. - */ - rotation: number; - - /** - * JSON serialization of the curve. - */ - toJSON(): Phaser.Types.Curves.JSONEllipseCurve; - - /** - * Creates a curve from the provided Ellipse Curve Configuration object. - * @param data The JSON object containing this curve data. - */ - static fromJSON(data: Phaser.Types.Curves.JSONEllipseCurve): Phaser.Curves.Ellipse; - - } - - /** - * A LineCurve is a "curve" comprising exactly two points (a line segment). - */ - class Line extends Phaser.Curves.Curve { - /** - * - * @param p0 The first endpoint. - * @param p1 The second endpoint. - */ - constructor(p0: Phaser.Math.Vector2 | number[], p1?: Phaser.Math.Vector2); - - /** - * The first endpoint. - */ - p0: Phaser.Math.Vector2; - - /** - * The second endpoint. - */ - p1: Phaser.Math.Vector2; - - /** - * The quantity of arc length divisions within the curve. - */ - arcLengthDivisions: integer; - - /** - * Returns a Rectangle where the position and dimensions match the bounds of this Curve. - * @param out A Rectangle object to store the bounds in. If not given a new Rectangle will be created. - */ - getBounds(out?: O): O; - - /** - * Gets the starting point on the curve. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getStartPoint(out?: O): O; - - /** - * Gets the resolution of the line. - * @param divisions The number of divisions to consider. Default 1. - */ - getResolution(divisions?: number): number; - - /** - * Get point at relative position in curve according to length. - * @param t The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPoint(t: number, out?: O): O; - - /** - * Gets a point at a given position on the line. - * @param u The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPointAt(u: number, out?: O): O; - - /** - * Gets the slope of the line as a unit vector. - */ - getTangent(): O; - - /** - * [description] - * @param u [description] - * @param distance [description] - * @param divisions [description] - */ - getUtoTmapping(u: number, distance: integer, divisions?: integer): number; - - /** - * Draws this curve on the given Graphics object. - * - * The curve is drawn using `Graphics.lineBetween` so will be drawn at whatever the present Graphics line color is. - * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. - * @param graphics The Graphics instance onto which this curve will be drawn. - */ - draw(graphics: G): G; - - /** - * Gets a JSON representation of the line. - */ - toJSON(): Phaser.Types.Curves.JSONCurve; - - /** - * Configures this line from a JSON representation. - * @param data The JSON object containing this curve data. - */ - static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.Line; - - } - - /** - * A MoveTo Curve is a very simple curve consisting of only a single point. Its intended use is to move the ending point in a Path. - */ - class MoveTo { - /** - * - * @param x `x` pixel coordinate. - * @param y `y` pixel coordinate. - */ - constructor(x?: number, y?: number); - - /** - * Denotes that this Curve does not influence the bounds, points, and drawing of its parent Path. Must be `false` or some methods in the parent Path will throw errors. - */ - active: boolean; - - /** - * The lone point which this curve consists of. - */ - p0: Phaser.Math.Vector2; - - /** - * Get point at relative position in curve according to length. - * @param t The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPoint(t: number, out?: O): O; - - /** - * Retrieves the point at given position in the curve. This will always return this curve's only point. - * @param u The position in the path to retrieve, between 0 and 1. Not used. - * @param out An optional vector in which to store the point. - */ - getPointAt(u: number, out?: O): O; - - /** - * Gets the resolution of this curve. - */ - getResolution(): number; - - /** - * Gets the length of this curve. - */ - getLength(): number; - - /** - * Converts this curve into a JSON-serializable object. - */ - toJSON(): Phaser.Types.Curves.JSONCurve; - - } - - /** - * A Path combines multiple Curves into one continuous compound curve. - * It does not matter how many Curves are in the Path or what type they are. - * - * A Curve in a Path does not have to start where the previous Curve ends - that is to say, a Path does not - * have to be an uninterrupted curve. Only the order of the Curves influences the actual points on the Path. - */ - class Path { - /** - * - * @param x The X coordinate of the Path's starting point or a {@link Phaser.Types.Curves.JSONPath}. Default 0. - * @param y The Y coordinate of the Path's starting point. Default 0. - */ - constructor(x?: number, y?: number); - - /** - * The name of this Path. - * Empty by default and never populated by Phaser, this is left for developers to use. - */ - name: string; - - /** - * The list of Curves which make up this Path. - */ - curves: Phaser.Curves.Curve[]; - - /** - * The cached length of each Curve in the Path. - * - * Used internally by {@link #getCurveLengths}. - */ - cacheLengths: number[]; - - /** - * Automatically closes the path. - */ - autoClose: boolean; - - /** - * The starting point of the Path. - * - * This is not necessarily equivalent to the starting point of the first Curve in the Path. In an empty Path, it's also treated as the ending point. - */ - startPoint: Phaser.Math.Vector2; - - /** - * Appends a Curve to the end of the Path. - * - * The Curve does not have to start where the Path ends or, for an empty Path, at its defined starting point. - * @param curve The Curve to append. - */ - add(curve: Phaser.Curves.Curve): Phaser.Curves.Path; - - /** - * Creates a circular Ellipse Curve positioned at the end of the Path. - * @param radius The radius of the circle. - * @param clockwise `true` to create a clockwise circle as opposed to a counter-clockwise circle. Default false. - * @param rotation The rotation of the circle in degrees. Default 0. - */ - circleTo(radius: number, clockwise?: boolean, rotation?: number): Phaser.Curves.Path; - - /** - * Ensures that the Path is closed. - * - * A closed Path starts and ends at the same point. If the Path is not closed, a straight Line Curve will be created from the ending point directly to the starting point. During the check, the actual starting point of the Path, i.e. the starting point of the first Curve, will be used as opposed to the Path's defined {@link startPoint}, which could differ. - * - * Calling this method on an empty Path will result in an error. - */ - closePath(): Phaser.Curves.Path; - - /** - * Creates a cubic bezier curve starting at the previous end point and ending at p3, using p1 and p2 as control points. - * @param x The x coordinate of the end point. Or, if a Vector2, the p1 value. - * @param y The y coordinate of the end point. Or, if a Vector2, the p2 value. - * @param control1X The x coordinate of the first control point. Or, if a Vector2, the p3 value. - * @param control1Y The y coordinate of the first control point. Not used if Vector2s are provided as the first 3 arguments. - * @param control2X The x coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. - * @param control2Y The y coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. - */ - cubicBezierTo(x: number | Phaser.Math.Vector2, y: number | Phaser.Math.Vector2, control1X: number | Phaser.Math.Vector2, control1Y?: number, control2X?: number, control2Y?: number): Phaser.Curves.Path; - - /** - * Creates a Quadratic Bezier Curve starting at the ending point of the Path. - * @param x The X coordinate of the second control point or, if it's a `Vector2`, the first control point. - * @param y The Y coordinate of the second control point or, if `x` is a `Vector2`, the second control point. - * @param controlX If `x` is not a `Vector2`, the X coordinate of the first control point. - * @param controlY If `x` is not a `Vector2`, the Y coordinate of the first control point. - */ - quadraticBezierTo(x: number | Phaser.Math.Vector2[], y?: number, controlX?: number, controlY?: number): Phaser.Curves.Path; - - /** - * Draws all Curves in the Path to a Graphics Game Object. - * @param graphics The Graphics Game Object to draw to. - * @param pointsTotal The number of points to draw for each Curve. Higher numbers result in a smoother curve but require more processing. Default 32. - */ - draw(graphics: Phaser.GameObjects.Graphics, pointsTotal?: integer): G; - - /** - * Creates an ellipse curve positioned at the previous end point, using the given parameters. - * @param xRadius The horizontal radius of ellipse. Default 0. - * @param yRadius The vertical radius of ellipse. Default 0. - * @param startAngle The start angle of the ellipse, in degrees. Default 0. - * @param endAngle The end angle of the ellipse, in degrees. Default 360. - * @param clockwise Whether the ellipse angles are given as clockwise (`true`) or counter-clockwise (`false`). Default false. - * @param rotation The rotation of the ellipse, in degrees. Default 0. - */ - ellipseTo(xRadius?: number, yRadius?: number, startAngle?: integer, endAngle?: integer, clockwise?: boolean, rotation?: number): Phaser.Curves.Path; - - /** - * Creates a Path from a Path Configuration object. - * - * The provided object should be a {@link Phaser.Types.Curves.JSONPath}, as returned by {@link #toJSON}. Providing a malformed object may cause errors. - * @param data The JSON object containing the Path data. - */ - fromJSON(data: Phaser.Types.Curves.JSONPath): Phaser.Curves.Path; - - /** - * Returns a Rectangle with a position and size matching the bounds of this Path. - * @param out The Rectangle to store the bounds in. - * @param accuracy The accuracy of the bounds calculations. Higher values are more accurate at the cost of calculation speed. Default 16. - */ - getBounds(out?: O, accuracy?: integer): O; - - /** - * Returns an array containing the length of the Path at the end of each Curve. - * - * The result of this method will be cached to avoid recalculating it in subsequent calls. The cache is only invalidated when the {@link #curves} array changes in length, leading to potential inaccuracies if a Curve in the Path is changed, or if a Curve is removed and another is added in its place. - */ - getCurveLengths(): number[]; - - /** - * Returns the ending point of the Path. - * - * A Path's ending point is equivalent to the ending point of the last Curve in the Path. For an empty Path, the ending point is at the Path's defined {@link #startPoint}. - * @param out The object to store the point in. - */ - getEndPoint(out?: O): O; - - /** - * Returns the total length of the Path. - */ - getLength(): number; - - /** - * Calculates the coordinates of the point at the given normalized location (between 0 and 1) on the Path. - * - * The location is relative to the entire Path, not to an individual Curve. A location of 0.5 is always in the middle of the Path and is thus an equal distance away from both its starting and ending points. In a Path with one Curve, it would be in the middle of the Curve; in a Path with two Curves, it could be anywhere on either one of them depending on their lengths. - * @param t The location of the point to return, between 0 and 1. - * @param out The object in which to store the calculated point. - */ - getPoint(t: number, out?: O): O; - - /** - * Get a sequence of points on the path. - * @param divisions The number of divisions per resolution per curve. Default 12. - */ - getPoints(divisions?: integer): Phaser.Math.Vector2[]; - - /** - * Returns a randomly chosen point anywhere on the path. This follows the same rules as `getPoint` in that it may return a point on any Curve inside this path. - * - * When calling this method multiple times, the points are not guaranteed to be equally spaced spatially. - * @param out `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. - */ - getRandomPoint(out?: O): O; - - /** - * Divides this Path into a set of equally spaced points, - * - * The resulting points are equally spaced with respect to the points' position on the path, but not necessarily equally spaced spatially. - * @param divisions The amount of points to divide this Path into. Default 40. - */ - getSpacedPoints(divisions?: integer): Phaser.Math.Vector2[]; - - /** - * Returns the starting point of the Path. - * @param out `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. - */ - getStartPoint(out?: O): O; - - /** - * Creates a line curve from the previous end point to x/y. - * @param x The X coordinate of the line's end point, or a `Vector2` containing the entire end point. - * @param y The Y coordinate of the line's end point, if a number was passed as the X parameter. - */ - lineTo(x: number | Phaser.Math.Vector2, y?: number): Phaser.Curves.Path; - - /** - * Creates a spline curve starting at the previous end point, using the given points on the curve. - * @param points The points the newly created spline curve should consist of. - */ - splineTo(points: Phaser.Math.Vector2[]): Phaser.Curves.Path; - - /** - * Creates a "gap" in this path from the path's current end point to the given coordinates. - * - * After calling this function, this Path's end point will be equal to the given coordinates - * @param x The X coordinate of the position to move the path's end point to, or a `Vector2` containing the entire new end point. - * @param y The Y coordinate of the position to move the path's end point to, if a number was passed as the X coordinate. - */ - moveTo(x: number | Phaser.Math.Vector2, y: number): Phaser.Curves.Path; - - /** - * Converts this Path to a JSON object containing the path information and its constituent curves. - */ - toJSON(): Phaser.Types.Curves.JSONPath; - - /** - * cacheLengths must be recalculated. - */ - updateArcLengths(): void; - - /** - * Disposes of this Path, clearing its internal references to objects so they can be garbage-collected. - */ - destroy(): void; - - } - - /** - * [description] - */ - class QuadraticBezier extends Phaser.Curves.Curve { - /** - * - * @param p0 Start point, or an array of point pairs. - * @param p1 Control Point 1. - * @param p2 Control Point 2. - */ - constructor(p0: Phaser.Math.Vector2 | number[], p1: Phaser.Math.Vector2, p2: Phaser.Math.Vector2); - - /** - * [description] - */ - p0: Phaser.Math.Vector2; - - /** - * [description] - */ - p1: Phaser.Math.Vector2; - - /** - * [description] - */ - p2: Phaser.Math.Vector2; - - /** - * Gets the starting point on the curve. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getStartPoint(out?: O): O; - - /** - * [description] - * @param divisions [description] - */ - getResolution(divisions: number): number; - - /** - * Get point at relative position in curve according to length. - * @param t The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPoint(t: number, out?: O): O; - - /** - * [description] - * @param graphics `Graphics` object to draw onto. - * @param pointsTotal Number of points to be used for drawing the curve. Higher numbers result in smoother curve but require more processing. Default 32. - */ - draw(graphics: G, pointsTotal?: integer): G; - - /** - * Converts the curve into a JSON compatible object. - */ - toJSON(): Phaser.Types.Curves.JSONCurve; - - /** - * Creates a curve from a JSON object, e. g. created by `toJSON`. - * @param data The JSON object containing this curve data. - */ - static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.QuadraticBezier; - - } - - /** - * Create a smooth 2d spline curve from a series of points. - */ - class Spline extends Phaser.Curves.Curve { - /** - * - * @param points The points that configure the curve. - */ - constructor(points?: Phaser.Math.Vector2[] | number[] | number[][]); - - /** - * The Vector2 points that configure the curve. - */ - points: Phaser.Math.Vector2[]; - - /** - * Add a list of points to the current list of Vector2 points of the curve. - * @param points The points that configure the curve. - */ - addPoints(points: Phaser.Math.Vector2[] | number[] | number[][]): Phaser.Curves.Spline; - - /** - * Add a point to the current list of Vector2 points of the curve. - * @param x The x coordinate of this curve - * @param y The y coordinate of this curve - */ - addPoint(x: number, y: number): Phaser.Math.Vector2; - - /** - * Gets the starting point on the curve. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getStartPoint(out?: O): O; - - /** - * [description] - * @param divisions [description] - */ - getResolution(divisions: number): number; - - /** - * Get point at relative position in curve according to length. - * @param t The position along the curve to return. Where 0 is the start and 1 is the end. - * @param out A Vector2 object to store the result in. If not given will be created. - */ - getPoint(t: number, out?: O): O; - - /** - * Exports a JSON object containing this curve data. - */ - toJSON(): Phaser.Types.Curves.JSONCurve; - - /** - * Imports a JSON object containing this curve data. - * @param data The JSON object containing this curve data. - */ - static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.Spline; - - } - - } - - namespace Data { - /** - * The Data Manager Component features a means to store pieces of data specific to a Game Object, System or Plugin. - * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, - * or have a property called `events` that is an instance of it. - */ - class DataManager { - /** - * - * @param parent The object that this DataManager belongs to. - * @param eventEmitter The DataManager's event emitter. - */ - constructor(parent: object, eventEmitter: Phaser.Events.EventEmitter); - - /** - * The object that this DataManager belongs to. - */ - parent: any; - - /** - * The DataManager's event emitter. - */ - events: Phaser.Events.EventEmitter; - - /** - * The data list. - */ - list: {[key: string]: any}; - - /** - * The public values list. You can use this to access anything you have stored - * in this Data Manager. For example, if you set a value called `gold` you can - * access it via: - * - * ```javascript - * this.data.values.gold; - * ``` - * - * You can also modify it directly: - * - * ```javascript - * this.data.values.gold += 1000; - * ``` - * - * Doing so will emit a `setdata` event from the parent of this Data Manager. - * - * Do not modify this object directly. Adding properties directly to this object will not - * emit any events. Always use `DataManager.set` to create new items the first time around. - */ - values: {[key: string]: any}; - - /** - * Retrieves the value for the given key, or undefined if it doesn't exist. - * - * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: - * - * ```javascript - * this.data.get('gold'); - * ``` - * - * Or access the value directly: - * - * ```javascript - * this.data.values.gold; - * ``` - * - * You can also pass in an array of keys, in which case an array of values will be returned: - * - * ```javascript - * this.data.get([ 'gold', 'armor', 'health' ]); - * ``` - * - * This approach is useful for destructuring arrays in ES6. - * @param key The key of the value to retrieve, or an array of keys. - */ - get(key: string | string[]): any; - - /** - * Retrieves all data values in a new object. - */ - getAll(): {[key: string]: any}; - - /** - * Queries the DataManager for the values of keys matching the given regular expression. - * @param search A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). - */ - query(search: RegExp): {[key: string]: any}; - - /** - * Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created. - * - * ```javascript - * data.set('name', 'Red Gem Stone'); - * ``` - * - * You can also pass in an object of key value pairs as the first argument: - * - * ```javascript - * data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); - * ``` - * - * To get a value back again you can call `get`: - * - * ```javascript - * data.get('gold'); - * ``` - * - * Or you can access the value directly via the `values` property, where it works like any other variable: - * - * ```javascript - * data.values.gold += 50; - * ``` - * - * When the value is first set, a `setdata` event is emitted. - * - * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. - * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. - * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. - * - * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. - * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. - * @param key The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored. - * @param data The value to set for the given key. If an object is provided as the key this argument is ignored. - */ - set(key: string | object, data: any): Phaser.Data.DataManager; - - /** - * Passes all data entries to the given callback. - * @param callback The function to call. - * @param context Value to use as `this` when executing callback. - * @param args Additional arguments that will be passed to the callback, after the game object, key, and data. - */ - each(callback: DataEachCallback, context?: any, ...args: any[]): Phaser.Data.DataManager; - - /** - * Merge the given object of key value pairs into this DataManager. - * - * Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument) - * will emit a `changedata` event. - * @param data The data to merge. - * @param overwrite Whether to overwrite existing data. Defaults to true. Default true. - */ - merge(data: {[key: string]: any}, overwrite?: boolean): Phaser.Data.DataManager; - - /** - * Remove the value for the given key. - * - * If the key is found in this Data Manager it is removed from the internal lists and a - * `removedata` event is emitted. - * - * You can also pass in an array of keys, in which case all keys in the array will be removed: - * - * ```javascript - * this.data.remove([ 'gold', 'armor', 'health' ]); - * ``` - * @param key The key to remove, or an array of keys to remove. - */ - remove(key: string | string[]): Phaser.Data.DataManager; - - /** - * Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it. - * @param key The key of the value to retrieve and delete. - */ - pop(key: string): any; - - /** - * Determines whether the given key is set in this Data Manager. - * - * Please note that the keys are case-sensitive and must be valid JavaScript Object property strings. - * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. - * @param key The key to check. - */ - has(key: string): boolean; - - /** - * Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts - * to create new values or update existing ones. - * @param value Whether to freeze or unfreeze the Data Manager. - */ - setFreeze(value: boolean): Phaser.Data.DataManager; - - /** - * Delete all data in this Data Manager and unfreeze it. - */ - reset(): Phaser.Data.DataManager; - - /** - * Destroy this data manager. - */ - destroy(): void; - - /** - * Gets or sets the frozen state of this Data Manager. - * A frozen Data Manager will block all attempts to create new values or update existing ones. - */ - freeze: boolean; - - /** - * Return the total number of entries in this Data Manager. - */ - count: integer; - - } - - /** - * The Data Component features a means to store pieces of data specific to a Game Object, System or Plugin. - * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, - * or have a property called `events` that is an instance of it. - */ - class DataManagerPlugin extends Phaser.Data.DataManager { - /** - * - * @param scene A reference to the Scene that this DataManager belongs to. - */ - constructor(scene: Phaser.Scene); - - /** - * A reference to the Scene that this DataManager belongs to. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene's Systems. - */ - systems: Phaser.Scenes.Systems; - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - */ - destroy(): void; - - } - - namespace Events { - /** - * The Change Data Event. - * - * This event is dispatched by a Data Manager when an item in the data store is changed. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * a change data event from a Game Object you would use: `sprite.data.on('changedata', listener)`. - * - * This event is dispatched for all items that change in the Data Manager. - * To listen for the change of a specific item, use the `CHANGE_DATA_KEY_EVENT` event. - */ - const CHANGE_DATA: any; - - /** - * The Change Data Key Event. - * - * This event is dispatched by a Data Manager when an item in the data store is changed. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * the change of a specific data item from a Game Object you would use: `sprite.data.on('changedata-key', listener)`, - * where `key` is the unique string key of the data item. For example, if you have a data item stored called `gold` - * then you can listen for `sprite.data.on('changedata-gold')`. - */ - const CHANGE_DATA_KEY: any; - - /** - * The Remove Data Event. - * - * This event is dispatched by a Data Manager when an item is removed from it. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * the removal of a data item on a Game Object you would use: `sprite.data.on('removedata', listener)`. - */ - const REMOVE_DATA: any; - - /** - * The Set Data Event. - * - * This event is dispatched by a Data Manager when a new item is added to the data store. - * - * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for - * the addition of a new data item on a Game Object you would use: `sprite.data.on('setdata', listener)`. - */ - const SET_DATA: any; - - } - - } - - namespace Device { - /** - * Determines the audio playback capabilities of the device 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.audio` from within any Scene. - */ - type Audio = { - /** - * Can this device play HTML Audio tags? - */ - audioData: boolean; - /** - * Can this device play EC-3 Dolby Digital Plus files? - */ - dolby: boolean; - /** - * Can this device can play m4a files. - */ - m4a: boolean; - /** - * Can this device play mp3 files? - */ - mp3: boolean; - /** - * Can this device play ogg files? - */ - ogg: boolean; - /** - * Can this device play opus files? - */ - opus: boolean; - /** - * Can this device play wav files? - */ - wav: boolean; - /** - * Does this device have the Web Audio API? - */ - webAudio: boolean; - /** - * Can this device play webm files? - */ - webm: boolean; - }; - - /** - * 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. - */ - type Browser = { - /** - * Set to true if running in Chrome. - */ - chrome: boolean; - /** - * Set to true if running in Microsoft Edge browser. - */ - edge: boolean; - /** - * Set to true if running in Firefox. - */ - firefox: boolean; - /** - * Set to true if running in Internet Explorer 11 or less (not Edge). - */ - ie: boolean; - /** - * Set to true if running in Mobile Safari. - */ - mobileSafari: boolean; - /** - * Set to true if running in Opera. - */ - opera: boolean; - /** - * Set to true if running in Safari. - */ - safari: boolean; - /** - * Set to true if running in the Silk browser (as used on the Amazon Kindle) - */ - silk: boolean; - /** - * Set to true if running a Trident version of Internet Explorer (IE11+) - */ - trident: boolean; - /** - * If running in Chrome this will contain the major version number. - */ - chromeVersion: number; - /** - * If running in Firefox this will contain the major version number. - */ - firefoxVersion: number; - /** - * If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Browser.trident and Browser.tridentVersion. - */ - ieVersion: number; - /** - * If running in Safari this will contain the major version number. - */ - safariVersion: number; - /** - * 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} - */ - tridentVersion: number; - }; - - /** - * Determines the canvas features of the browser 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.canvasFeatures` from within any Scene. - */ - type CanvasFeatures = { - /** - * Set to true if the browser supports inversed alpha. - */ - supportInverseAlpha: boolean; - /** - * Set to true if the browser supports new canvas blend modes. - */ - supportNewBlendModes: boolean; - }; - - /** - * Determines the features of the browser 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.features` from within any Scene. - */ - type Features = { - /** - * True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. - */ - canvasBitBltShift: boolean; - /** - * Is canvas available? - */ - canvas: boolean; - /** - * Is file available? - */ - file: boolean; - /** - * Is fileSystem available? - */ - fileSystem: boolean; - /** - * Does the device support the getUserMedia API? - */ - getUserMedia: boolean; - /** - * Is the device big or little endian? (only detected if the browser supports TypedArrays) - */ - littleEndian: boolean; - /** - * Is localStorage available? - */ - localStorage: boolean; - /** - * Is Pointer Lock available? - */ - pointerLock: boolean; - /** - * Does the device context support 32bit pixel manipulation using array buffer views? - */ - support32bit: boolean; - /** - * Does the device support the Vibration API? - */ - vibration: boolean; - /** - * Is webGL available? - */ - webGL: boolean; - /** - * Is worker available? - */ - worker: boolean; - }; - - /** - * Determines the full screen support of the browser 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.fullscreen` from within any Scene. - */ - type Fullscreen = { - /** - * Does the browser support the Full Screen API? - */ - available: boolean; - /** - * Does the browser support access to the Keyboard during Full Screen mode? - */ - keyboard: boolean; - /** - * If the browser supports the Full Screen API this holds the call you need to use to cancel it. - */ - cancel: string; - /** - * If the browser supports the Full Screen API this holds the call you need to use to activate it. - */ - request: string; - }; - - /** - * Determines the input support of the browser 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.input` from within any Scene. - */ - type Input = { - /** - * The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' - */ - wheelType: string; - /** - * Is navigator.getGamepads available? - */ - gamepads: boolean; - /** - * Is mspointer available? - */ - mspointer: boolean; - /** - * Is touch available? - */ - touch: boolean; - }; - - /** - * Determines the operating system of the device 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.os` from within any Scene. - */ - type OS = { - /** - * Is running on android? - */ - android: boolean; - /** - * Is running on chromeOS? - */ - chromeOS: boolean; - /** - * Is the game running under Apache Cordova? - */ - cordova: boolean; - /** - * Is the game running under the Intel Crosswalk XDK? - */ - crosswalk: boolean; - /** - * Is running on a desktop? - */ - desktop: boolean; - /** - * Is the game running under Ejecta? - */ - ejecta: boolean; - /** - * Is the game running under GitHub Electron? - */ - electron: boolean; - /** - * Is running on iOS? - */ - iOS: boolean; - /** - * Is running on iPad? - */ - iPad: boolean; - /** - * Is running on iPhone? - */ - iPhone: boolean; - /** - * Is running on an Amazon Kindle? - */ - kindle: boolean; - /** - * Is running on linux? - */ - linux: boolean; - /** - * Is running on macOS? - */ - macOS: boolean; - /** - * Is the game running under Node.js? - */ - node: boolean; - /** - * Is the game running under Node-Webkit? - */ - nodeWebkit: boolean; - /** - * Set to true if running as a WebApp, i.e. within a WebView - */ - webApp: boolean; - /** - * Is running on windows? - */ - windows: boolean; - /** - * Is running on a Windows Phone? - */ - windowsPhone: boolean; - /** - * If running in iOS this will contain the major version number. - */ - iOSVersion: number; - /** - * PixelRatio of the host device? - */ - pixelRatio: number; - }; - - /** - * Determines the video support of the browser 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.video` from within any Scene. - * - * In Phaser 3.20 the properties were renamed to drop the 'Video' suffix. - */ - type Video = { - /** - * Can this device play h264 mp4 video files? - */ - h264: boolean; - /** - * Can this device play hls video files? - */ - hls: boolean; - /** - * Can this device play h264 mp4 video files? - */ - mp4: boolean; - /** - * Can this device play ogg video files? - */ - ogg: boolean; - /** - * Can this device play vp9 video files? - */ - vp9: boolean; - /** - * Can this device play webm video files? - */ - webm: boolean; - }; - - } - - type DeviceConf = { - /** - * The OS Device functions. - */ - os: Phaser.Device.OS; - /** - * The Browser Device functions. - */ - browser: Phaser.Device.Browser; - /** - * The Features Device functions. - */ - features: Phaser.Device.Features; - /** - * The Input Device functions. - */ - input: Phaser.Device.Input; - /** - * The Audio Device functions. - */ - audio: Phaser.Device.Audio; - /** - * The Video Device functions. - */ - video: Phaser.Device.Video; - /** - * The Fullscreen Device functions. - */ - fullscreen: Phaser.Device.Fullscreen; - /** - * The Canvas Device functions. - */ - canvasFeatures: Phaser.Device.CanvasFeatures; - }; - - namespace Display { - namespace Align { - /** - * A constant representing a top-left alignment or position. - */ - const TOP_LEFT: integer; - - /** - * A constant representing a top-center alignment or position. - */ - const TOP_CENTER: integer; - - /** - * A constant representing a top-right alignment or position. - */ - const TOP_RIGHT: integer; - - /** - * A constant representing a left-top alignment or position. - */ - const LEFT_TOP: integer; - - /** - * A constant representing a left-center alignment or position. - */ - const LEFT_CENTER: integer; - - /** - * A constant representing a left-bottom alignment or position. - */ - const LEFT_BOTTOM: integer; - - /** - * A constant representing a center alignment or position. - */ - const CENTER: integer; - - /** - * A constant representing a right-top alignment or position. - */ - const RIGHT_TOP: integer; - - /** - * A constant representing a right-center alignment or position. - */ - const RIGHT_CENTER: integer; - - /** - * A constant representing a right-bottom alignment or position. - */ - const RIGHT_BOTTOM: integer; - - /** - * A constant representing a bottom-left alignment or position. - */ - const BOTTOM_LEFT: integer; - - /** - * A constant representing a bottom-center alignment or position. - */ - const BOTTOM_CENTER: integer; - - /** - * A constant representing a bottom-right alignment or position. - */ - const BOTTOM_RIGHT: integer; - - namespace In { - /** - * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function BottomCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the bottom left of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function BottomLeft(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the bottom right of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function BottomRight(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the center of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function Center(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the left center of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function LeftCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned relative to the other. - * The alignment used is based on the `position` argument, which is an `ALIGN_CONST` value, such as `LEFT_CENTER` or `TOP_RIGHT`. - * @param child The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param position The position to align the Game Object with. This is an align constant, such as `ALIGN_CONST.LEFT_CENTER`. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function QuickSet(child: G, alignIn: Phaser.GameObjects.GameObject, position: integer, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the right center of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function RightCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the top center of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function TopCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the top left of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function TopLeft(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned in the top right of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignIn The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function TopRight(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - } - - namespace To { - /** - * Takes given Game Object and aligns it so that it is positioned next to the bottom center position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function BottomCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the bottom left position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function BottomLeft(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the bottom right position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function BottomRight(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the left bottom position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function LeftBottom(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the left center position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function LeftCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the left top position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function LeftTop(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * 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`. - * @param child The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param position The position to align the Game Object with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function QuickSet(child: G, alignTo: Phaser.GameObjects.GameObject, position: integer, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the right bottom position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function RightBottom(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the right center position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function RightCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the right top position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function RightTop(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function TopCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the top left position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function TopLeft(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - /** - * Takes given Game Object and aligns it so that it is positioned next to the top right position of the other. - * @param gameObject The Game Object that will be positioned. - * @param alignTo The Game Object to base the alignment position on. - * @param offsetX Optional horizontal offset from the position. Default 0. - * @param offsetY Optional vertical offset from the position. Default 0. - */ - function TopRight(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; - - } - - } - - namespace Bounds { - /** - * Positions the Game Object so that it is centered on the given coordinates. - * @param gameObject The Game Object that will be re-positioned. - * @param x The horizontal coordinate to position the Game Object on. - * @param y The vertical coordinate to position the Game Object on. - */ - function CenterOn(gameObject: G, x: number, y: number): G; - - /** - * Returns the bottom coordinate from the bounds of the Game Object. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetBottom(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the center x coordinate from the bounds of the Game Object. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetCenterX(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the center y coordinate from the bounds of the Game Object. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetCenterY(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the left coordinate from the bounds of the Game Object. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetLeft(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the amount the Game Object is visually offset from its x coordinate. - * This is the same as `width * origin.x`. - * This value will only be > 0 if `origin.x` is not equal to zero. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetOffsetX(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the amount the Game Object is visually offset from its y coordinate. - * This is the same as `width * origin.y`. - * This value will only be > 0 if `origin.y` is not equal to zero. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetOffsetY(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the right coordinate from the bounds of the Game Object. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetRight(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Returns the top coordinate from the bounds of the Game Object. - * @param gameObject The Game Object to get the bounds value from. - */ - function GetTop(gameObject: Phaser.GameObjects.GameObject): number; - - /** - * Positions the Game Object so that the bottom of its bounds aligns with the given coordinate. - * @param gameObject The Game Object that will be re-positioned. - * @param value The coordinate to position the Game Object bounds on. - */ - function SetBottom(gameObject: G, value: number): G; - - /** - * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. - * @param gameObject The Game Object that will be re-positioned. - * @param x The coordinate to position the Game Object bounds on. - */ - function SetCenterX(gameObject: G, x: number): G; - - /** - * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. - * @param gameObject The Game Object that will be re-positioned. - * @param y The coordinate to position the Game Object bounds on. - */ - function SetCenterY(gameObject: G, y: number): G; - - /** - * Positions the Game Object so that the left of its bounds aligns with the given coordinate. - * @param gameObject The Game Object that will be re-positioned. - * @param value The coordinate to position the Game Object bounds on. - */ - function SetLeft(gameObject: G, value: number): G; - - /** - * Positions the Game Object so that the left of its bounds aligns with the given coordinate. - * @param gameObject The Game Object that will be re-positioned. - * @param value The coordinate to position the Game Object bounds on. - */ - function SetRight(gameObject: G, value: number): G; - - /** - * Positions the Game Object so that the top of its bounds aligns with the given coordinate. - * @param gameObject The Game Object that will be re-positioned. - * @param value The coordinate to position the Game Object bounds on. - */ - function SetTop(gameObject: G, value: number): G; - - } - - namespace Canvas { - namespace CanvasInterpolation { - /** - * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit). - * @param canvas The canvas object to have the style set on. - */ - function setCrisp(canvas: HTMLCanvasElement): HTMLCanvasElement; - - /** - * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). - * @param canvas The canvas object to have the style set on. - */ - function setBicubic(canvas: HTMLCanvasElement): HTMLCanvasElement; - - } - - /** - * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. - * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, - * which is useless for some of the Phaser pipelines / renderer. - * - * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. - * Which means all instances of Phaser Games on the same page can share the one single pool. - */ - namespace CanvasPool { - /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * @param parent The parent of the Canvas object. - * @param width The width of the Canvas. Default 1. - * @param height The height of the Canvas. Default 1. - * @param canvasType The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. Default Phaser.CANVAS. - * @param selfParent Use the generated Canvas element as the parent? Default false. - */ - function create(parent: any, width?: integer, height?: integer, canvasType?: integer, selfParent?: boolean): HTMLCanvasElement; - - /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * @param parent The parent of the Canvas object. - * @param width The width of the Canvas. Default 1. - * @param height The height of the Canvas. Default 1. - */ - function create2D(parent: any, width?: integer, height?: integer): HTMLCanvasElement; - - /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * @param parent The parent of the Canvas object. - * @param width The width of the Canvas. Default 1. - * @param height The height of the Canvas. Default 1. - */ - function createWebGL(parent: any, width?: integer, height?: integer): HTMLCanvasElement; - - /** - * Gets the first free canvas index from the pool. - * @param canvasType The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. Default Phaser.CANVAS. - */ - function first(canvasType?: integer): HTMLCanvasElement; - - /** - * 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. - * @param parent The canvas or the parent of the canvas to free. - */ - function remove(parent: any): void; - - /** - * Gets the total number of used canvas elements in the pool. - */ - function total(): integer; - - /** - * Gets the total number of free canvas elements in the pool. - */ - function free(): integer; - - /** - * Disable context smoothing on any new Canvas element created. - */ - function disableSmoothing(): void; - - /** - * Enable context smoothing on any new Canvas element created. - */ - function enableSmoothing(): void; - - } - - namespace Smoothing { - /** - * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. - * @param context The canvas context to check. - */ - function getPrefix(context: CanvasRenderingContext2D | WebGLRenderingContext): string; - - /** - * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. - * By default browsers have image smoothing enabled, which isn't always what you visually want, especially - * when using pixel art in a game. Note that this sets the property on the context itself, so that any image - * drawn to the context will be affected. This sets the property across all current browsers but support is - * patchy on earlier browsers, especially on mobile. - * @param context The context on which to enable smoothing. - */ - function enable(context: CanvasRenderingContext2D | WebGLRenderingContext): CanvasRenderingContext2D | WebGLRenderingContext; - - /** - * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. - * By default browsers have image smoothing enabled, which isn't always what you visually want, especially - * when using pixel art in a game. Note that this sets the property on the context itself, so that any image - * drawn to the context will be affected. This sets the property across all current browsers but support is - * patchy on earlier browsers, especially on mobile. - * @param context The context on which to disable smoothing. - */ - function disable(context: CanvasRenderingContext2D | WebGLRenderingContext): CanvasRenderingContext2D | WebGLRenderingContext; - - /** - * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. - * Returns null if no smoothing prefix is available. - * @param context The context to check. - */ - function isEnabled(context: CanvasRenderingContext2D | WebGLRenderingContext): boolean; - - } - - /** - * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. - * @param canvas The canvas element to have the style applied to. - * @param value The touch action value to set on the canvas. Set to `none` to disable touch actions. Default 'none'. - */ - function TouchAction(canvas: HTMLCanvasElement, value?: string): HTMLCanvasElement; - - /** - * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. - * @param canvas The canvas element to have the style applied to. - * @param value The touch callout value to set on the canvas. Set to `none` to disable touch callouts. Default 'none'. - */ - function UserSelect(canvas: HTMLCanvasElement, value?: string): HTMLCanvasElement; - - } - - namespace Color { - namespace Interpolate { - /** - * Interpolates between the two given color ranges over the length supplied. - * @param r1 Red value. - * @param g1 Blue value. - * @param b1 Green value. - * @param r2 Red value. - * @param g2 Blue value. - * @param b2 Green value. - * @param length Distance to interpolate over. Default 100. - * @param index Index to start from. Default 0. - */ - function RGBWithRGB(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number, length?: number, index?: number): Phaser.Types.Display.ColorObject; - - /** - * Interpolates between the two given color objects over the length supplied. - * @param color1 The first Color object. - * @param color2 The second Color object. - * @param length Distance to interpolate over. Default 100. - * @param index Index to start from. Default 0. - */ - function ColorWithColor(color1: Phaser.Display.Color, color2: Phaser.Display.Color, length?: number, index?: number): Phaser.Types.Display.ColorObject; - - /** - * Interpolates between the Color object and color values over the length supplied. - * @param color1 The first Color object. - * @param r Red value. - * @param g Blue value. - * @param b Green value. - * @param length Distance to interpolate over. Default 100. - * @param index Index to start from. Default 0. - */ - function ColorWithRGB(color1: Phaser.Display.Color, r: number, g: number, b: number, length?: number, index?: number): Phaser.Types.Display.ColorObject; - - } - - } - - /** - * The Color class holds a single color value and allows for easy modification and reading of it. - */ - class Color { - /** - * - * @param red The red color value. A number between 0 and 255. Default 0. - * @param green The green color value. A number between 0 and 255. Default 0. - * @param blue The blue color value. A number between 0 and 255. Default 0. - * @param alpha The alpha value. A number between 0 and 255. Default 255. - */ - constructor(red?: integer, green?: integer, blue?: integer, alpha?: integer); - - /** - * An array containing the calculated color values for WebGL use. - */ - gl: number[]; - - /** - * Sets this color to be transparent. Sets all values to zero. - */ - transparent(): Phaser.Display.Color; - - /** - * Sets the color of this Color component. - * @param red The red color value. A number between 0 and 255. - * @param green The green color value. A number between 0 and 255. - * @param blue The blue color value. A number between 0 and 255. - * @param alpha The alpha value. A number between 0 and 255. Default 255. - * @param updateHSV Update the HSV values after setting the RGB values? Default true. - */ - setTo(red: integer, green: integer, blue: integer, alpha?: integer, updateHSV?: boolean): Phaser.Display.Color; - - /** - * Sets the red, green, blue and alpha GL values of this Color component. - * @param red The red color value. A number between 0 and 1. - * @param green The green color value. A number between 0 and 1. - * @param blue The blue color value. A number between 0 and 1. - * @param alpha The alpha value. A number between 0 and 1. Default 1. - */ - setGLTo(red: number, green: number, blue: number, alpha?: number): Phaser.Display.Color; - - /** - * Sets the color based on the color object given. - * @param color An object containing `r`, `g`, `b` and optionally `a` values in the range 0 to 255. - */ - setFromRGB(color: Phaser.Types.Display.InputColorObject): Phaser.Display.Color; - - /** - * Sets the color based on the hue, saturation and lightness values given. - * @param h The hue, in the range 0 - 1. This is the base color. - * @param 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 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. - */ - setFromHSV(h: number, s: number, v: number): Phaser.Display.Color; - - /** - * Returns a new Color component using the values from this one. - */ - clone(): Phaser.Display.Color; - - /** - * Sets this Color object to be grayscaled based on the shade value given. - * @param shade A value between 0 and 255. - */ - gray(shade: integer): Phaser.Display.Color; - - /** - * Sets this Color object to be a random color between the `min` and `max` values given. - * @param min The minimum random color value. Between 0 and 255. Default 0. - * @param max The maximum random color value. Between 0 and 255. Default 255. - */ - random(min?: integer, max?: integer): Phaser.Display.Color; - - /** - * Sets this Color object to be a random grayscale color between the `min` and `max` values given. - * @param min The minimum random color value. Between 0 and 255. Default 0. - * @param max The maximum random color value. Between 0 and 255. Default 255. - */ - randomGray(min?: integer, max?: integer): Phaser.Display.Color; - - /** - * Increase the saturation of this Color by the percentage amount given. - * The saturation is the amount of the base color in the hue. - * @param amount The percentage amount to change this color by. A value between 0 and 100. - */ - saturate(amount: integer): Phaser.Display.Color; - - /** - * Decrease the saturation of this Color by the percentage amount given. - * The saturation is the amount of the base color in the hue. - * @param amount The percentage amount to change this color by. A value between 0 and 100. - */ - desaturate(amount: integer): Phaser.Display.Color; - - /** - * Increase the lightness of this Color by the percentage amount given. - * @param amount The percentage amount to change this color by. A value between 0 and 100. - */ - lighten(amount: integer): Phaser.Display.Color; - - /** - * Decrease the lightness of this Color by the percentage amount given. - * @param amount The percentage amount to change this color by. A value between 0 and 100. - */ - darken(amount: integer): Phaser.Display.Color; - - /** - * Brighten this Color by the percentage amount given. - * @param amount The percentage amount to change this color by. A value between 0 and 100. - */ - brighten(amount: integer): Phaser.Display.Color; - - /** - * The color of this Color component, not including the alpha channel. - */ - readonly color: number; - - /** - * The color of this Color component, including the alpha channel. - */ - readonly color32: number; - - /** - * The color of this Color component as a string which can be used in CSS color values. - */ - readonly rgba: string; - - /** - * The red color value, normalized to the range 0 to 1. - */ - redGL: number; - - /** - * The green color value, normalized to the range 0 to 1. - */ - greenGL: number; - - /** - * The blue color value, normalized to the range 0 to 1. - */ - blueGL: number; - - /** - * The alpha color value, normalized to the range 0 to 1. - */ - alphaGL: number; - - /** - * The red color value, normalized to the range 0 to 255. - */ - red: number; - - /** - * The green color value, normalized to the range 0 to 255. - */ - green: number; - - /** - * The blue color value, normalized to the range 0 to 255. - */ - blue: number; - - /** - * The alpha color value, normalized to the range 0 to 255. - */ - alpha: number; - - /** - * The hue color value. A number between 0 and 1. - * This is the base color. - */ - h: number; - - /** - * The saturation color value. A number between 0 and 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. - */ - s: number; - - /** - * The lightness color value. A number between 0 and 1. - * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. - */ - v: number; - - /** - * Converts the given color value into an Object containing r,g,b and a properties. - * @param color A color value, optionally including the alpha value. - */ - static ColorToRGBA(color: number): Phaser.Types.Display.ColorObject; - - /** - * Returns a string containing a hex representation of the given color component. - * @param color The color channel to get the hex value for, must be a value between 0 and 255. - */ - static ComponentToHex(color: integer): string; - - /** - * Given 3 separate color values this will return an integer representation of it. - * @param red The red color value. A number between 0 and 255. - * @param green The green color value. A number between 0 and 255. - * @param blue The blue color value. A number between 0 and 255. - */ - static GetColor(red: integer, green: integer, blue: integer): number; - - /** - * Given an alpha and 3 color values this will return an integer representation of it. - * @param red The red color value. A number between 0 and 255. - * @param green The green color value. A number between 0 and 255. - * @param blue The blue color value. A number between 0 and 255. - * @param alpha The alpha color value. A number between 0 and 255. - */ - static GetColor32(red: integer, green: integer, blue: integer, alpha: integer): number; - - /** - * Converts a hex string into a Phaser Color object. - * - * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. - * - * An alpha channel is _not_ supported. - * @param hex The hex color value to convert, such as `#0033ff` or the short-hand format: `#03f`. - */ - static HexStringToColor(hex: string): Phaser.Display.Color; - - /** - * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. - * @param h The hue value in the range 0 to 1. - * @param s The saturation value in the range 0 to 1. - * @param l The lightness value in the range 0 to 1. - */ - static HSLToColor(h: number, s: number, l: number): Phaser.Display.Color; - - /** - * Get HSV color wheel values in an array which will be 360 elements in size. - * @param s The saturation, in the range 0 - 1. Default 1. - * @param v The value, in the range 0 - 1. Default 1. - */ - static HSVColorWheel(s?: number, v?: number): Phaser.Types.Display.ColorObject[]; - - /** - * Converts an HSV (hue, saturation and value) color value to RGB. - * Conversion formula from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes HSV values are contained in the set [0, 1]. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * @param h The hue, in the range 0 - 1. This is the base color. - * @param 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 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. - * @param out A Color object to store the results in. If not given a new ColorObject will be created. - */ - static HSVToRGB(h: number, s: number, v: number, out?: Phaser.Types.Display.ColorObject | Phaser.Display.Color): Phaser.Types.Display.ColorObject | Phaser.Display.Color; - - /** - * Converts a hue to an RGB color. - * Based on code by Michael Jackson (https://github.com/mjijackson) - */ - static HueToComponent(p: number, q: number, t: number): number; - - /** - * Converts the given color value into an instance of a Color object. - * @param input The color value to convert into a Color object. - */ - static IntegerToColor(input: integer): Phaser.Display.Color; - - /** - * Return the component parts of a color as an Object with the properties alpha, red, green, blue. - * - * Alpha will only be set if it exists in the given color (0xAARRGGBB) - * @param input The color value to convert into a Color object. - */ - static IntegerToRGB(input: integer): Phaser.Types.Display.ColorObject; - - /** - * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. - * @param input An object containing `r`, `g`, `b` and `a` properties in the range 0 to 255. - */ - static ObjectToColor(input: Phaser.Types.Display.InputColorObject): Phaser.Display.Color; - - /** - * 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. - * @param min The minimum value to set the random range from (between 0 and 255) Default 0. - * @param max The maximum value to set the random range from (between 0 and 255) Default 255. - */ - static RandomRGB(min?: integer, max?: integer): Phaser.Display.Color; - - /** - * Converts a CSS 'web' string into a Phaser Color object. - * - * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. - * @param rgb The CSS format color string, using the `rgb` or `rgba` format. - */ - static RGBStringToColor(rgb: string): Phaser.Display.Color; - - /** - * 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) - * @param r The red color value. A number between 0 and 255. - * @param g The green color value. A number between 0 and 255. - * @param b The blue color value. A number between 0 and 255. - * @param out An object to store the color values in. If not given an HSV Color Object will be created. - */ - static RGBToHSV(r: integer, g: integer, b: integer, out?: Phaser.Types.Display.HSVColorObject | Phaser.Display.Color): Phaser.Types.Display.HSVColorObject | Phaser.Display.Color; - - /** - * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. - * @param r The red color value. A number between 0 and 255. - * @param g The green color value. A number between 0 and 255. - * @param b The blue color value. A number between 0 and 255. - * @param a The alpha value. A number between 0 and 255. Default 255. - * @param prefix The prefix of the string. Either `#` or `0x`. Default #. - */ - static RGBToString(r: integer, g: integer, b: integer, a?: integer, prefix?: string): string; - - /** - * Converts the given source color value into an instance of a Color class. - * The value can be either a string, prefixed with `rgb` or a hex string, a number or an Object. - * @param input The source color value to convert. - */ - static ValueToColor(input: string | number | Phaser.Types.Display.InputColorObject): Phaser.Display.Color; - - } - - namespace Masks { - /** - * A Bitmap Mask combines the alpha (opacity) of a masked pixel with the alpha of another pixel. - * Unlike the Geometry Mask, which is a clipping path, a Bitmap Mask behaves like an alpha mask, - * not a clipping path. It is only available when using the WebGL Renderer. - * - * A Bitmap Mask can use any Game Object to determine the alpha of each pixel of the masked Game Object(s). - * For any given point of a masked Game Object's texture, the pixel's alpha will be multiplied by the alpha - * of the pixel at the same position in the Bitmap Mask's Game Object. The color of the pixel from the - * Bitmap Mask doesn't matter. - * - * For example, if a pure blue pixel with an alpha of 0.95 is masked with a pure red pixel with an - * alpha of 0.5, the resulting pixel will be pure blue with an alpha of 0.475. Naturally, this means - * that a pixel in the mask with an alpha of 0 will hide the corresponding pixel in all masked Game Objects - * A pixel with an alpha of 1 in the masked Game Object will receive the same alpha as the - * corresponding pixel in the mask. - * - * The Bitmap Mask's location matches the location of its Game Object, not the location of the - * masked objects. Moving or transforming the underlying Game Object will change the mask - * (and affect the visibility of any masked objects), whereas moving or transforming a masked object - * will not affect the mask. - * - * The Bitmap Mask will not render its Game Object by itself. If the Game Object is not in a - * Scene's display list, it will only be used for the mask and its full texture will not be directly - * visible. Adding the underlying Game Object to a Scene will not cause any problems - it will - * render as a normal Game Object and will also serve as a mask. - */ - class BitmapMask { - /** - * - * @param scene The Scene which this Bitmap Mask will be used in. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - constructor(scene: Phaser.Scene, renderable: Phaser.GameObjects.GameObject); - - /** - * A reference to either the Canvas or WebGL Renderer that this Mask is using. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * A renderable Game Object that uses a texture, such as a Sprite. - */ - bitmapMask: Phaser.GameObjects.GameObject; - - /** - * The texture used for the mask's framebuffer. - */ - maskTexture: WebGLTexture; - - /** - * The texture used for the main framebuffer. - */ - mainTexture: WebGLTexture; - - /** - * Whether the Bitmap Mask is dirty and needs to be updated. - */ - dirty: boolean; - - /** - * The framebuffer to which a masked Game Object is rendered. - */ - mainFramebuffer: WebGLFramebuffer; - - /** - * The framebuffer to which the Bitmap Mask's masking Game Object is rendered. - */ - maskFramebuffer: WebGLFramebuffer; - - /** - * The previous framebuffer set in the renderer before this one was enabled. - */ - prevFramebuffer: WebGLFramebuffer; - - /** - * Whether to invert the masks alpha. - * - * If `true`, the alpha of the masking pixel will be inverted before it's multiplied with the masked pixel. Essentially, this means that a masked area will be visible only if the corresponding area in the mask is invisible. - */ - invertAlpha: boolean; - - /** - * Is this mask a stencil mask? - */ - readonly isStencil: boolean; - - /** - * Sets a new masking Game Object for the Bitmap Mask. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - setBitmap(renderable: Phaser.GameObjects.GameObject): void; - - /** - * Prepares the WebGL Renderer to render a Game Object with this mask applied. - * - * This renders the masking Game Object to the mask framebuffer and switches to the main framebuffer so that the masked Game Object will be rendered to it instead of being rendered directly to the frame. - * @param renderer The WebGL Renderer to prepare. - * @param maskedObject The masked Game Object which will be drawn. - * @param camera The Camera to render to. - */ - preRenderWebGL(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer, maskedObject: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * Finalizes rendering of a masked Game Object. - * - * This resets the previously bound framebuffer and switches the WebGL Renderer to the Bitmap Mask Pipeline, which uses a special fragment shader to apply the masking effect. - * @param renderer The WebGL Renderer to clean up. - */ - postRenderWebGL(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; - - /** - * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. - * @param renderer The Canvas Renderer which would be rendered to. - * @param mask The masked Game Object which would be rendered. - * @param camera The Camera to render to. - */ - preRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer, mask: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. - * @param renderer The Canvas Renderer which would be rendered to. - */ - postRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; - - /** - * Destroys this BitmapMask and nulls any references it holds. - * - * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, - * so be sure to call `clearMask` on any Game Object using it, before destroying it. - */ - destroy(): void; - - } - - /** - * A Geometry Mask can be applied to a Game Object to hide any pixels of it which don't intersect - * a visible pixel from the geometry mask. The mask is essentially a clipping path which can only - * make a masked pixel fully visible or fully invisible without changing its alpha (opacity). - * - * A Geometry Mask uses a Graphics Game Object to determine which pixels of the masked Game Object(s) - * should be clipped. For any given point of a masked Game Object's texture, the pixel will only be displayed - * if the Graphics Game Object of the Geometry Mask has a visible pixel at the same position. The color and - * alpha of the pixel from the Geometry Mask do not matter. - * - * The Geometry Mask's location matches the location of its Graphics object, not the location of the masked objects. - * Moving or transforming the underlying Graphics object will change the mask (and affect the visibility - * of any masked objects), whereas moving or transforming a masked object will not affect the mask. - * You can think of the Geometry Mask (or rather, of its Graphics object) as an invisible curtain placed - * in front of all masked objects which has its own visual properties and, naturally, respects the camera's - * visual properties, but isn't affected by and doesn't follow the masked objects by itself. - */ - class GeometryMask { - /** - * - * @param scene This parameter is not used. - * @param graphicsGeometry The Graphics Game Object to use for the Geometry Mask. Doesn't have to be in the Display List. - */ - constructor(scene: Phaser.Scene, graphicsGeometry: Phaser.GameObjects.Graphics); - - /** - * The Graphics object which describes the Geometry Mask. - */ - geometryMask: Phaser.GameObjects.Graphics; - - /** - * Similar to the BitmapMasks invertAlpha setting this to true will then hide all pixels - * drawn to the Geometry Mask. - */ - invertAlpha: boolean; - - /** - * Is this mask a stencil mask? - */ - readonly isStencil: boolean; - - /** - * Sets a new Graphics object for the Geometry Mask. - * @param graphicsGeometry The Graphics object which will be used for the Geometry Mask. - */ - setShape(graphicsGeometry: Phaser.GameObjects.Graphics): this; - - /** - * Sets the `invertAlpha` property of this Geometry Mask. - * Inverting the alpha essentially flips the way the mask works. - * @param value Invert the alpha of this mask? Default true. - */ - setInvertAlpha(value?: boolean): this; - - /** - * Renders the Geometry Mask's underlying Graphics object to the OpenGL stencil buffer and enables the stencil test, which clips rendered pixels according to the mask. - * @param renderer The WebGL Renderer instance to draw to. - * @param child The Game Object being rendered. - * @param camera The camera the Game Object is being rendered through. - */ - preRenderWebGL(renderer: Phaser.Renderer.WebGL.WebGLRenderer, child: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * Applies the current stencil mask to the renderer. - * @param renderer The WebGL Renderer instance to draw to. - * @param camera The camera the Game Object is being rendered through. - * @param inc Is this an INCR stencil or a DECR stencil? - */ - applyStencil(renderer: Phaser.Renderer.WebGL.WebGLRenderer, camera: Phaser.Cameras.Scene2D.Camera, inc: boolean): void; - - /** - * Flushes all rendered pixels and disables the stencil test of a WebGL context, thus disabling the mask for it. - * @param renderer The WebGL Renderer instance to draw flush. - */ - postRenderWebGL(renderer: Phaser.Renderer.WebGL.WebGLRenderer): void; - - /** - * Sets the clipping path of a 2D canvas context to the Geometry Mask's underlying Graphics object. - * @param renderer The Canvas Renderer instance to set the clipping path on. - * @param mask The Game Object being rendered. - * @param camera The camera the Game Object is being rendered through. - */ - preRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer, mask: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * Restore the canvas context's previous clipping path, thus turning off the mask for it. - * @param renderer The Canvas Renderer instance being restored. - */ - postRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer): void; - - /** - * Destroys this GeometryMask and nulls any references it holds. - * - * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, - * so be sure to call `clearMask` on any Game Object using it, before destroying it. - */ - destroy(): void; - - } - - } - - /** - * A BaseShader is a small resource class that contains the data required for a WebGL Shader to be created. - * - * It contains the raw source code to the fragment and vertex shader, as well as an object that defines - * the uniforms the shader requires, if any. - * - * BaseShaders are stored in the Shader Cache, available in a Scene via `this.cache.shaders` and are referenced - * by a unique key-based string. Retrieve them via `this.cache.shaders.get(key)`. - * - * BaseShaders are created automatically by the GLSL File Loader when loading an external shader resource. - * They can also be created at runtime, allowing you to use dynamically generated shader source code. - * - * Default fragment and vertex source is used if not provided in the constructor, setting-up a basic shader, - * suitable for debug rendering. - */ - class BaseShader { - /** - * - * @param key The key of this shader. Must be unique within the shader cache. - * @param fragmentSrc The fragment source for the shader. - * @param vertexSrc The vertex source for the shader. - * @param uniforms Optional object defining the uniforms the shader uses. - */ - constructor(key: string, fragmentSrc?: string, vertexSrc?: string, uniforms?: any); - - /** - * The key of this shader, unique within the shader cache of this Phaser game instance. - */ - key: string; - - /** - * The source code, as a string, of the fragment shader being used. - */ - fragmentSrc: string; - - /** - * The source code, as a string, of the vertex shader being used. - */ - vertexSrc: string; - - /** - * The default uniforms for this shader. - */ - uniforms: any; - - } - - } - - namespace DOM { - /** - * Adds the given element to the DOM. If a parent is provided the element is added as a child of the parent, providing it was able to access it. - * If no parent was given it falls back to using `document.body`. - * @param element The element to be added to the DOM. Usually a Canvas object. - * @param parent The parent in which to add the element. Can be a string which is passed to `getElementById` or an actual DOM object. - */ - function AddToDOM(element: HTMLElement, parent?: string | HTMLElement): HTMLElement; - - /** - * Inspects the readyState of the document. If the document is already complete then it invokes the given callback. - * If not complete it sets up several event listeners such as `deviceready`, and once those fire, it invokes the callback. - * Called automatically by the Phaser.Game instance. Should not usually be accessed directly. - * @param callback The callback to be invoked when the device is ready and the DOM content is loaded. - */ - function DOMContentLoaded(callback: ContentLoadedCallback): void; - - /** - * Attempts to determine the document inner height across iOS and standard devices. - * Based on code by @tylerjpeterson - * @param iOS Is this running on iOS? - */ - function GetInnerHeight(iOS: boolean): number; - - /** - * Attempts to determine the screen orientation using the Orientation API. - * @param width The width of the viewport. - * @param height The height of the viewport. - */ - function GetScreenOrientation(width: number, height: number): string; - - /** - * 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. - * @param element The DOM element to look-up. - */ - function GetTarget(element: HTMLElement): void; - - /** - * Takes the given data string and parses it as XML. - * First tries to use the window.DOMParser and reverts to the Microsoft.XMLDOM if that fails. - * The parsed XML object is returned, or `null` if there was an error while parsing the data. - * @param data The XML source stored in a string. - */ - function ParseXML(data: string): DOMParser | ActiveXObject; - - /** - * Attempts to remove the element from its parentNode in the DOM. - * @param element The DOM element to remove from its parent node. - */ - function RemoveFromDOM(element: HTMLElement): void; - - /** - * Abstracts away the use of RAF or setTimeOut for the core game update loop. - * This is invoked automatically by the Phaser.Game instance. - */ - class RequestAnimationFrame { - /** - * True if RequestAnimationFrame is running, otherwise false. - */ - isRunning: boolean; - - /** - * The callback to be invoked each step. - */ - callback: FrameRequestCallback; - - /** - * The most recent timestamp. Either a DOMHighResTimeStamp under RAF or `Date.now` under SetTimeout. - */ - tick: number; - - /** - * True if the step is using setTimeout instead of RAF. - */ - isSetTimeOut: boolean; - - /** - * The setTimeout or RAF callback ID used when canceling them. - */ - timeOutID: number; - - /** - * The previous time the step was called. - */ - lastTime: number; - - /** - * The target FPS rate in ms. - * Only used when setTimeout is used instead of RAF. - */ - target: number; - - /** - * The RAF step function. - * Updates the local tick value, invokes the callback and schedules another call to requestAnimationFrame. - */ - step: FrameRequestCallback; - - /** - * The SetTimeout step function. - * Updates the local tick value, invokes the callback and schedules another call to setTimeout. - */ - stepTimeout: Function; - - /** - * Starts the requestAnimationFrame or setTimeout process running. - * @param callback The callback to invoke each step. - * @param forceSetTimeOut Should it use SetTimeout, even if RAF is available? - * @param targetFPS The target fps rate (in ms). Only used when setTimeout is used. - */ - start(callback: FrameRequestCallback, forceSetTimeOut: boolean, targetFPS: number): void; - - /** - * Stops the requestAnimationFrame or setTimeout from running. - */ - stop(): void; - - /** - * Stops the step from running and clears the callback reference. - */ - destroy(): void; - - } - - } - - namespace Events { - /** - * EventEmitter is a Scene Systems plugin compatible version of eventemitter3. - */ - class EventEmitter { - /** - * Removes all listeners. - */ - shutdown(): void; - - /** - * Removes all listeners. - */ - destroy(): void; - - /** - * Return an array listing the events for which the emitter has registered listeners. - */ - eventNames(): (string|symbol)[]; - - /** - * Return the listeners registered for a given event. - * @param event The event name. - */ - listeners(event: string | symbol): Function[]; - - /** - * Return the number of listeners listening to a given event. - * @param event The event name. - */ - listenerCount(event: string | symbol): number; - - /** - * Calls each of the listeners registered for a given event. - * @param event The event name. - * @param args Additional arguments that will be passed to the event handler. - */ - emit(event: string | symbol, ...args: any[]): boolean; - - /** - * Add a listener for a given event. - * @param event The event name. - * @param fn The listener function. - * @param context The context to invoke the listener with. Default this. - */ - on(event: string | symbol, fn: Function, context?: any): this; - - /** - * Add a listener for a given event. - * @param event The event name. - * @param fn The listener function. - * @param context The context to invoke the listener with. Default this. - */ - addListener(event: string | symbol, fn: Function, context?: any): this; - - /** - * Add a one-time listener for a given event. - * @param event The event name. - * @param fn The listener function. - * @param context The context to invoke the listener with. Default this. - */ - once(event: string | symbol, fn: Function, context?: any): this; - - /** - * Remove the listeners of a given event. - * @param event The event name. - * @param fn Only remove the listeners that match this function. - * @param context Only remove the listeners that have this context. - * @param once Only remove one-time listeners. - */ - removeListener(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; - - /** - * Remove the listeners of a given event. - * @param event The event name. - * @param fn Only remove the listeners that match this function. - * @param context Only remove the listeners that have this context. - * @param once Only remove one-time listeners. - */ - off(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; - - /** - * Remove all listeners, or those of the specified event. - * @param event The event name. - */ - removeAllListeners(event?: string | symbol): this; - - } - - } - - /** - * Phaser Blend Modes to CSS Blend Modes Map. - */ - enum CSSBlendModes { - } - - namespace GameObjects { - /** - * 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. - * - * 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): 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 - */ - class DynamicBitmapText extends Phaser.GameObjects.BitmapText { - /** - * - * @param scene The Scene to which this Game Object belongs. It can only belong to one Scene at any given time. - * @param x The x coordinate of this Game Object in world space. - * @param y The y coordinate of this Game Object in world space. - * @param font The key of the font to use from the Bitmap Font cache. - * @param text The string, or array of strings, to be set as the content of this Bitmap Text. - * @param size The font size of this Bitmap Text. - * @param align The alignment of the text in a multi-line BitmapText object. Default 0. - */ - constructor(scene: Phaser.Scene, x: number, y: number, font: string, text?: string | string[], size?: number, align?: integer); - - /** - * The horizontal scroll position of the Bitmap Text. - */ - scrollX: number; - - /** - * The vertical scroll position of the Bitmap Text. - */ - scrollY: number; - - /** - * The crop width of the Bitmap Text. - */ - cropWidth: number; - - /** - * The crop height of the Bitmap Text. - */ - cropHeight: number; - - /** - * A callback that alters how each character of the Bitmap Text is rendered. - */ - displayCallback: Phaser.Types.GameObjects.BitmapText.DisplayCallback; - - /** - * The data object that is populated during rendering, then passed to the displayCallback. - * You should modify this object then return it back from the callback. It's updated values - * will be used to render the specific glyph. - * - * Please note that if you need a reference to this object locally in your game code then you - * should shallow copy it, as it's updated and re-used for every glyph in the text. - */ - callbackData: Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig; - - /** - * Set the crop size of this Bitmap Text. - * @param width The width of the crop. - * @param height The height of the crop. - */ - setSize(width: number, height: number): Phaser.GameObjects.DynamicBitmapText; - - /** - * Set a callback that alters how each character of the Bitmap Text is rendered. - * - * The callback receives a {@link Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} object that contains information about the character that's - * about to be rendered. - * - * It should return an object with `x`, `y`, `scale` and `rotation` properties that will be used instead of the - * usual values when rendering. - * @param callback The display callback to set. - */ - setDisplayCallback(callback: Phaser.Types.GameObjects.BitmapText.DisplayCallback): Phaser.GameObjects.DynamicBitmapText; - - /** - * Set the horizontal scroll position of this Bitmap Text. - * @param value The horizontal scroll position to set. - */ - setScrollX(value: number): Phaser.GameObjects.DynamicBitmapText; - - /** - * Set the vertical scroll position of this Bitmap Text. - * @param value The vertical scroll position to set. - */ - setScrollY(value: number): Phaser.GameObjects.DynamicBitmapText; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - namespace RetroFont { - /** - * Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ - */ - var TEXT_SET1: string; - - /** - * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ - */ - var TEXT_SET2: string; - - /** - * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 - */ - var TEXT_SET3: string; - - /** - * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 - */ - var TEXT_SET4: string; - - /** - * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 - */ - var TEXT_SET5: string; - - /** - * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' - */ - var TEXT_SET6: string; - - /** - * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 - */ - var TEXT_SET7: string; - - /** - * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ - */ - var TEXT_SET8: string; - - /** - * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! - */ - var TEXT_SET9: string; - - /** - * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ - */ - var TEXT_SET10: string; - - /** - * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 - */ - var TEXT_SET11: string; - - /** - * Parses a Retro Font configuration object so you can pass it to the BitmapText constructor - * and create a BitmapText object using a fixed-width retro font. - * @param scene A reference to the Phaser Scene. - * @param config The font configuration object. - */ - function Parse(scene: Phaser.Scene, config: Phaser.Types.GameObjects.BitmapText.RetroFontConfig): object; - - } - - /** - * 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} - * Littera (Web-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 implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. It can only belong to one Scene at any given time. - * @param x The x coordinate of this Game Object in world space. - * @param y The y coordinate of this Game Object in world space. - * @param font The key of the font to use from the Bitmap Font cache. - * @param text The string, or array of strings, to be set as the content of this Bitmap Text. - * @param size The font size of this Bitmap Text. - * @param align The alignment of the text in a multi-line BitmapText object. Default 0. - */ - constructor(scene: Phaser.Scene, x: number, y: number, font: string, text?: string | string[], size?: number, align?: integer); - - /** - * The key of the Bitmap Font used by this Bitmap Text. - * To change the font after creation please use `setFont`. - */ - readonly font: string; - - /** - * The data of the Bitmap Font used by this Bitmap Text. - */ - readonly fontData: Phaser.Types.GameObjects.BitmapText.BitmapFontData; - - /** - * The character code used to detect for word wrapping. - * Defaults to 32 (a space character). - */ - wordWrapCharCode: number; - - /** - * Set the lines of text in this BitmapText to be left-aligned. - * This only has any effect if this BitmapText contains more than one line of text. - */ - setLeftAlign(): this; - - /** - * Set the lines of text in this BitmapText to be center-aligned. - * This only has any effect if this BitmapText contains more than one line of text. - */ - setCenterAlign(): this; - - /** - * Set the lines of text in this BitmapText to be right-aligned. - * This only has any effect if this BitmapText contains more than one line of text. - */ - setRightAlign(): this; - - /** - * Set the font size of this Bitmap Text. - * @param size The font size to set. - */ - setFontSize(size: number): this; - - /** - * Sets the letter spacing between each character of this Bitmap Text. - * Can be a positive value to increase the space, or negative to reduce it. - * Spacing is applied after the kerning values have been set. - * @param spacing The amount of horizontal space to add between each character. Default 0. - */ - setLetterSpacing(spacing?: number): this; - - /** - * Set the textual content of this BitmapText. - * - * An array of strings will be converted into multi-line text. Use the align methods to change multi-line alignment. - * @param value The string, or array of strings, to be set as the content of this BitmapText. - */ - setText(value: string | string[]): this; - - /** - * 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. - * @param round Whether to round the results to the nearest integer. - */ - getTextBounds(round?: boolean): Phaser.Types.GameObjects.BitmapText.BitmapTextSize; - - /** - * Changes the font this BitmapText is using to render. - * - * The new texture is loaded and applied to the BitmapText. The existing test, size and alignment are preserved, - * unless overridden via the arguments. - * @param font The key of the font to use from the Bitmap Font cache. - * @param size The font size of this Bitmap Text. If not specified the current size will be used. - * @param align The alignment of the text in a multi-line BitmapText object. If not specified the current alignment will be used. Default 0. - */ - setFont(font: string, size?: number, align?: integer): this; - - /** - * 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. - * @param value The maximum display width of this BitmapText in pixels. Set to zero to disable. - * @param wordWrapCharCode The character code to check for when word wrapping. Defaults to 32 (the space character). - */ - setMaxWidth(value: number, wordWrapCharCode?: number): this; - - /** - * 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. - */ - align: integer; - - /** - * The text that this Bitmap Text object displays. - * - * You can also use the method `setText` if you want a chainable way to change the text content. - */ - text: string; - - /** - * The font size of this Bitmap Text. - * - * You can also use the method `setFontSize` if you want a chainable way to change the font size. - */ - fontSize: number; - - /** - * Adds / Removes spacing between characters. - * - * Can be a negative or positive number. - * - * You can also use the method `setLetterSpacing` if you want a chainable way to change the letter spacing. - */ - letterSpacing: number; - - /** - * 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. - */ - maxWidth: number; - - /** - * The width of this Bitmap Text. - */ - readonly width: number; - - /** - * The height of this bitmap text. - */ - readonly height: number; - - /** - * Build a JSON representation of this Bitmap Text. - */ - toJSON(): Phaser.Types.GameObjects.BitmapText.JSONBitmapText; - - /** - * Left align the text characters in a multi-line BitmapText object. - */ - static ALIGN_LEFT: integer; - - /** - * Center align the text characters in a multi-line BitmapText object. - */ - static ALIGN_CENTER: integer; - - /** - * Right align the text characters in a multi-line BitmapText object. - */ - static ALIGN_RIGHT: integer; - - /** - * Parse an XML Bitmap Font from an Atlas. - * - * Adds the parsed Bitmap Font data to the cache with the `fontName` key. - * @param scene The Scene to parse the Bitmap Font for. - * @param fontName The key of the font to add to the Bitmap Font cache. - * @param textureKey The key of the BitmapFont's texture. - * @param frameKey The key of the BitmapFont texture's frame. - * @param xmlKey The key of the XML data of the font to parse. - * @param xSpacing The x-axis spacing to add between each letter. - * @param ySpacing The y-axis spacing to add to the line height. - */ - static ParseFromAtlas(scene: Phaser.Scene, fontName: string, textureKey: string, frameKey: string, xmlKey: string, xSpacing?: integer, ySpacing?: integer): boolean; - - /** - * Parse an XML font to Bitmap Font data for the Bitmap Font cache. - * @param xml The XML Document to parse the font from. - * @param xSpacing The x-axis spacing to add between each letter. Default 0. - * @param ySpacing The y-axis spacing to add to the line height. Default 0. - * @param frame The texture frame to take into account while parsing. - */ - static ParseXMLBitmapFont(xml: XMLDocument, xSpacing?: integer, ySpacing?: integer, frame?: Phaser.Textures.Frame): Phaser.Types.GameObjects.BitmapText.BitmapFontData; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A Blitter Game Object. - * - * The Blitter Game Object is a special kind of container that creates, updates and manages Bob objects. - * Bobs are designed for rendering speed rather than flexibility. They consist of a texture, or frame from a texture, - * a position and an alpha value. You cannot scale or rotate them. They use a batched drawing method for speed - * during rendering. - * - * A Blitter Game Object has one texture bound to it. Bobs created by the Blitter can use any Frame from this - * Texture to render with, but they cannot use any other Texture. It is this single texture-bind that allows - * them their speed. - * - * If you have a need to blast a large volume of frames around the screen then Blitter objects are well worth - * investigating. They are especially useful for using as a base for your own special effects systems. - */ - class Blitter extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. It can only belong to one Scene at any given time. - * @param x The x coordinate of this Game Object in world space. Default 0. - * @param y The y coordinate of this Game Object in world space. Default 0. - * @param texture The key of the texture this Game Object will use for rendering. The Texture must already exist in the Texture Manager. Default '__DEFAULT'. - * @param frame The Frame of the Texture that this Game Object will use. Only set if the Texture has multiple frames, such as a Texture Atlas or Sprite Sheet. Default 0. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, texture?: string, frame?: string | integer); - - /** - * The children of this Blitter. - * This List contains all of the Bob objects created by the Blitter. - */ - children: Phaser.Structs.List; - - /** - * Is the Blitter considered dirty? - * A 'dirty' Blitter has had its child count changed since the last frame. - */ - dirty: boolean; - - /** - * Creates a new Bob in this Blitter. - * - * The Bob is created at the given coordinates, relative to the Blitter and uses the given frame. - * A Bob can use any frame belonging to the texture bound to the Blitter. - * @param x The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param y The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param frame The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. - * @param visible Should the created Bob render or not? Default true. - * @param index The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list. - */ - create(x: number, y: number, frame?: string | integer | Phaser.Textures.Frame, visible?: boolean, index?: integer): Phaser.GameObjects.Bob; - - /** - * Creates multiple Bob objects within this Blitter and then passes each of them to the specified callback. - * @param callback The callback to invoke after creating a bob. It will be sent two arguments: The Bob and the index of the Bob. - * @param quantity The quantity of Bob objects to create. - * @param frame The Frame the Bobs will use. It must be part of the Blitter Texture. - * @param visible Should the created Bob render or not? Default true. - */ - createFromCallback(callback: CreateCallback, quantity: integer, frame?: string | integer | Phaser.Textures.Frame | string[] | integer[] | Phaser.Textures.Frame[], visible?: boolean): Phaser.GameObjects.Bob[]; - - /** - * Creates multiple Bobs in one call. - * - * The amount created is controlled by a combination of the `quantity` argument and the number of frames provided. - * - * If the quantity is set to 10 and you provide 2 frames, then 20 Bobs will be created. 10 with the first - * frame and 10 with the second. - * @param quantity The quantity of Bob objects to create. - * @param frame The Frame the Bobs will use. It must be part of the Blitter Texture. - * @param visible Should the created Bob render or not? Default true. - */ - createMultiple(quantity: integer, frame?: string | integer | Phaser.Textures.Frame | string[] | integer[] | Phaser.Textures.Frame[], visible?: boolean): Phaser.GameObjects.Bob[]; - - /** - * Checks if the given child can render or not, by checking its `visible` and `alpha` values. - * @param child The Bob to check for rendering. - */ - childCanRender(child: Phaser.GameObjects.Bob): boolean; - - /** - * Returns an array of Bobs to be rendered. - * If the Blitter is dirty then a new list is generated and stored in `renderList`. - */ - getRenderList(): Phaser.GameObjects.Bob[]; - - /** - * Removes all Bobs from the children List and clears the dirty flag. - */ - clear(): void; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A Bob Game Object. - * - * A Bob belongs to a Blitter Game Object. The Blitter is responsible for managing and rendering this object. - * - * A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle - * the flipped and visible state of the Bob. The Frame the Bob uses to render can be changed dynamically, but it - * must be a Frame within the Texture used by the parent Blitter. - * - * Bob positions are relative to the Blitter parent. So if you move the Blitter parent, all Bob children will - * have their positions impacted by this change as well. - * - * You can manipulate Bob objects directly from your game code, but the creation and destruction of them should be - * handled via the Blitter parent. - */ - class Bob { - /** - * - * @param blitter The parent Blitter object is responsible for updating this Bob. - * @param x The horizontal position of this Game Object in the world, relative to the parent Blitter position. - * @param y The vertical position of this Game Object in the world, relative to the parent Blitter position. - * @param frame The Frame this Bob will render with, as defined in the Texture the parent Blitter is using. - * @param visible Should the Bob render visible or not to start with? - */ - constructor(blitter: Phaser.GameObjects.Blitter, x: number, y: number, frame: string | integer, visible: boolean); - - /** - * The Blitter object that this Bob belongs to. - */ - parent: Phaser.GameObjects.Blitter; - - /** - * The x position of this Bob, relative to the x position of the Blitter. - */ - x: number; - - /** - * The y position of this Bob, relative to the y position of the Blitter. - */ - y: number; - - /** - * The frame that the Bob uses to render with. - * To change the frame use the `Bob.setFrame` method. - */ - protected frame: Phaser.Textures.Frame; - - /** - * A blank object which can be used to store data related to this Bob in. - */ - data: object; - - /** - * The tint value of this Bob. - */ - tint: number; - - /** - * The horizontally flipped state of the Bob. - * A Bob that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Bob. - * A Bob that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture. - */ - flipY: boolean; - - /** - * Changes the Texture Frame being used by this Bob. - * The frame must be part of the Texture the parent Blitter is using. - * If no value is given it will use the default frame of the Blitter parent. - * @param frame The frame to be used during rendering. - */ - setFrame(frame?: string | integer | Phaser.Textures.Frame): Phaser.GameObjects.Bob; - - /** - * Resets the horizontal and vertical flipped state of this Bob back to their default un-flipped state. - */ - resetFlip(): Phaser.GameObjects.Bob; - - /** - * Resets this Bob. - * - * Changes the position to the values given, and optionally changes the frame. - * - * Also resets the flipX and flipY values, sets alpha back to 1 and visible to true. - * @param x The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param y The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param frame The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. - */ - reset(x: number, y: number, frame?: string | integer | Phaser.Textures.Frame): Phaser.GameObjects.Bob; - - /** - * Changes the position of this Bob to the values given. - * @param x The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. - * @param y The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. - */ - setPosition(x: number, y: number): Phaser.GameObjects.Bob; - - /** - * Sets the horizontal flipped state of this Bob. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): Phaser.GameObjects.Bob; - - /** - * Sets the vertical flipped state of this Bob. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): Phaser.GameObjects.Bob; - - /** - * Sets the horizontal and vertical flipped state of this Bob. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): Phaser.GameObjects.Bob; - - /** - * Sets the visibility of this Bob. - * - * An invisible Bob will skip rendering. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): Phaser.GameObjects.Bob; - - /** - * Set the Alpha level of this Bob. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * A Bob with alpha 0 will skip rendering. - * @param value The alpha value used for this Bob. Between 0 and 1. - */ - setAlpha(value: number): Phaser.GameObjects.Bob; - - /** - * Sets the tint of this Bob. - * @param value The tint value used for this Bob. Between 0 and 0xffffff. - */ - setTint(value: number): Phaser.GameObjects.Bob; - - /** - * Destroys this Bob instance. - * Removes itself from the Blitter and clears the parent, frame and data properties. - */ - destroy(): void; - - /** - * The visible state of the Bob. - * - * An invisible Bob will skip rendering. - */ - visible: boolean; - - /** - * The alpha value of the Bob, between 0 and 1. - * - * A Bob with alpha 0 will skip rendering. - */ - alpha: number; - - } - - /** - * Builds a Game Object using the provided configuration object. - * @param scene A reference to the Scene. - * @param gameObject The initial GameObject. - * @param config The config to build the GameObject with. - */ - function BuildGameObject(scene: Phaser.Scene, gameObject: Phaser.GameObjects.GameObject, config: Phaser.Types.GameObjects.GameObjectConfig): Phaser.GameObjects.GameObject; - - /** - * Adds an Animation component to a Sprite and populates it based on the given config. - * @param sprite The sprite to add an Animation component to. - * @param config The animation config. - */ - function BuildGameObjectAnimation(sprite: Phaser.GameObjects.Sprite, config: object): Phaser.GameObjects.Sprite; - - namespace Components { - /** - * Provides methods used for setting the alpha properties of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Alpha { - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - } - - /** - * Provides methods used for setting the alpha property of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface AlphaSingle { - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - } - - interface Animation { - /** - * The Game Object to which this animation controller belongs. - */ - parent: Phaser.GameObjects.GameObject; - /** - * A reference to the global Animation Manager. - */ - animationManager: Phaser.Animations.AnimationManager; - /** - * Is an animation currently playing or not? - */ - isPlaying: boolean; - /** - * The current Animation loaded into this Animation Controller. - */ - currentAnim: Phaser.Animations.Animation; - /** - * The current AnimationFrame being displayed by this Animation Controller. - */ - currentFrame: Phaser.Animations.AnimationFrame; - /** - * The key of the next Animation to be loaded into this Animation Controller when the current animation completes. - */ - nextAnim: string; - /** - * The frame rate of playback in frames per second. - * The default is 24 if the `duration` property is `null`. - */ - frameRate: number; - /** - * How long the animation should play for, in milliseconds. - * If the `frameRate` property has been set then it overrides this value, - * otherwise the `frameRate` is derived from `duration`. - */ - duration: number; - /** - * ms per frame, not including frame specific modifiers that may be present in the Animation data. - */ - msPerFrame: number; - /** - * Skip frames if the time lags, or always advanced anyway? - */ - skipMissedFrames: boolean; - /** - * Will the playhead move forwards (`true`) or in reverse (`false`). - */ - forward: boolean; - /** - * Internal time overflow accumulator. - */ - accumulator: number; - /** - * The time point at which the next animation frame will change. - */ - nextTick: number; - /** - * An internal counter keeping track of how many repeats are left to play. - */ - repeatCounter: number; - /** - * An internal flag keeping track of pending repeats. - */ - pendingRepeat: boolean; - /** - * Sets an animation to be played immediately after the current one completes. - * - * The current animation must enter a 'completed' state for this to happen, i.e. finish all of its repeats, delays, etc, or have the `stop` method called directly on it. - * - * An animation set to repeat forever will never enter a completed state. - * - * You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). - * Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. - * - * Call this method with no arguments to reset the chained animation. - * @param key The string-based key of the animation to play next, as defined previously in the Animation Manager. Or an Animation instance. - */ - chain(key?: string | Phaser.Animations.Animation): Phaser.GameObjects.GameObject; - /** - * Sets the amount of time, in milliseconds, that the animation will be delayed before starting playback. - * @param value The amount of time, in milliseconds, to wait before starting playback. Default 0. - */ - setDelay(value?: integer): Phaser.GameObjects.GameObject; - /** - * Gets the amount of time, in milliseconds that the animation will be delayed before starting playback. - */ - getDelay(): integer; - /** - * Waits for the specified delay, in milliseconds, then starts playback of the requested animation. - * @param delay The delay, in milliseconds, to wait before starting the animation playing. - * @param key The key of the animation to play. - * @param startFrame The frame of the animation to start from. Default 0. - */ - delayedPlay(delay: integer, key: string, startFrame?: integer): Phaser.GameObjects.GameObject; - /** - * Returns the key of the animation currently loaded into this component. - */ - getCurrentKey(): string; - /** - * Internal method used to load an animation into this component. - * @param key The key of the animation to load. - * @param startFrame The start frame of the animation to load. Default 0. - */ - load(key: string, startFrame?: integer): Phaser.GameObjects.GameObject; - /** - * Pause the current animation and set the `isPlaying` property to `false`. - * You can optionally pause it at a specific frame. - * @param atFrame An optional frame to set after pausing the animation. - */ - pause(atFrame?: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; - /** - * Resumes playback of a paused animation and sets the `isPlaying` property to `true`. - * You can optionally tell it to start playback from a specific frame. - * @param fromFrame An optional frame to set before restarting playback. - */ - resume(fromFrame?: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; - /** - * `true` if the current animation is paused, otherwise `false`. - */ - readonly isPaused: boolean; - /** - * Plays an Animation on a Game Object that has the Animation component, such as a Sprite. - * - * Animations are stored in the global Animation Manager and are referenced by a unique string-based key. - * @param key The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. - * @param ignoreIfPlaying If this animation is already playing then ignore this call. Default false. - * @param startFrame Optionally start the animation playing from this frame index. Default 0. - */ - play(key: string | Phaser.Animations.Animation, ignoreIfPlaying?: boolean, startFrame?: integer): Phaser.GameObjects.GameObject; - /** - * Plays an Animation (in reverse mode) on the Game Object that owns this Animation Component. - * @param key The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. - * @param ignoreIfPlaying If an animation is already playing then ignore this call. Default false. - * @param startFrame Optionally start the animation playing from this frame index. Default 0. - */ - playReverse(key: string | Phaser.Animations.Animation, ignoreIfPlaying?: boolean, startFrame?: integer): Phaser.GameObjects.GameObject; - /** - * Load an Animation and fires 'onStartEvent' event, extracted from 'play' method. - * @param key The string-based key of the animation to play, as defined previously in the Animation Manager. - * @param startFrame Optionally start the animation playing from this frame index. Default 0. - */ - _startAnimation(key: string, startFrame?: integer): Phaser.GameObjects.GameObject; - /** - * Reverse the Animation that is already playing on the Game Object. - */ - reverse(): Phaser.GameObjects.GameObject; - /** - * Returns a value between 0 and 1 indicating how far this animation is through, ignoring repeats and yoyos. - * If the animation has a non-zero repeat defined, `getProgress` and `getTotalProgress` will be different - * because `getProgress` doesn't include any repeats or repeat delays, whereas `getTotalProgress` does. - */ - getProgress(): number; - /** - * 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. - * @param value The progress value, between 0 and 1. Default 0. - */ - setProgress(value?: number): Phaser.GameObjects.GameObject; - /** - * Handle the removal of an animation from the Animation Manager. - * @param key The key of the removed Animation. - * @param animation The removed Animation. - */ - remove(key?: string, animation?: Phaser.Animations.Animation): void; - /** - * Gets the number of times that the animation will repeat - * after its first iteration. For example, if returns 1, the animation will - * play a total of twice (the initial play plus 1 repeat). - * A value of -1 means the animation will repeat indefinitely. - */ - getRepeat(): integer; - /** - * Sets the number of times that the animation should repeat - * after its first iteration. For example, if repeat is 1, the animation will - * play a total of twice (the initial play plus 1 repeat). - * To repeat indefinitely, use -1. repeat should always be an integer. - * @param value The number of times that the animation should repeat. - */ - setRepeat(value: integer): Phaser.GameObjects.GameObject; - /** - * Gets the amount of delay between repeats, if any. - */ - getRepeatDelay(): number; - /** - * Sets the amount of time in seconds between repeats. - * For example, if `repeat` is 2 and `repeatDelay` is 10, the animation will play initially, - * then wait for 10 seconds before repeating, then play again, then wait another 10 seconds - * before doing its final repeat. - * @param value The delay to wait between repeats, in seconds. - */ - setRepeatDelay(value: number): Phaser.GameObjects.GameObject; - /** - * Restarts the current animation from its beginning, optionally including its delay value. - * @param includeDelay Whether to include the delay value of the animation when restarting. Default false. - */ - restart(includeDelay?: boolean): Phaser.GameObjects.GameObject; - /** - * Immediately stops the current animation from playing and dispatches the `animationcomplete` event. - * - * If no animation is set, no event will be dispatched. - * - * If there is another animation queued (via the `chain` method) then it will start playing immediately. - */ - stop(): Phaser.GameObjects.GameObject; - /** - * Stops the current animation from playing after the specified time delay, given in milliseconds. - * @param delay The number of milliseconds to wait before stopping this animation. - */ - stopAfterDelay(delay: integer): Phaser.GameObjects.GameObject; - /** - * Stops the current animation from playing when it next repeats. - */ - stopOnRepeat(): Phaser.GameObjects.GameObject; - /** - * Stops the current animation from playing when it next sets the given frame. - * If this frame doesn't exist within the animation it will not stop it from playing. - * @param frame The frame to check before stopping this animation. - */ - stopOnFrame(frame: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; - /** - * Sets the Time Scale factor, allowing you to make the animation go go faster or slower than default. - * Where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. - * @param value The time scale factor, where 1 is no change, 0.5 is half speed, etc. Default 1. - */ - setTimeScale(value?: number): Phaser.GameObjects.GameObject; - /** - * Gets the Time Scale factor. - */ - getTimeScale(): number; - /** - * Returns the total number of frames in this animation. - */ - getTotalFrames(): integer; - /** - * The internal update loop for the Animation Component. - * @param time The current timestamp. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - update(time: number, delta: number): void; - /** - * Sets the given Animation Frame as being the current frame - * and applies it to the parent Game Object, adjusting its size and origin as needed. - * @param animationFrame The Animation Frame to set as being current. - */ - setCurrentFrame(animationFrame: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; - /** - * Advances the animation to the next frame, regardless of the time or animation state. - * If the animation is set to repeat, or yoyo, this will still take effect. - * - * Calling this does not change the direction of the animation. I.e. if it was currently - * playing in reverse, calling this method doesn't then change the direction to forwards. - */ - nextFrame(): Phaser.GameObjects.GameObject; - /** - * Advances the animation to the previous frame, regardless of the time or animation state. - * If the animation is set to repeat, or yoyo, this will still take effect. - * - * Calling this does not change the direction of the animation. I.e. if it was currently - * playing in forwards, calling this method doesn't then change the direction to backwards. - */ - previousFrame(): Phaser.GameObjects.GameObject; - /** - * Sets if the current Animation will yoyo when it reaches the end. - * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. - * @param value `true` if the animation should yoyo, `false` to not. Default false. - */ - setYoyo(value?: boolean): Phaser.GameObjects.GameObject; - /** - * Gets if the current Animation will yoyo when it reaches the end. - * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. - */ - getYoyo(): boolean; - /** - * Destroy this Animation component. - * - * Unregisters event listeners and cleans up its references. - */ - destroy(): void; - } - - /** - * Provides methods used for setting the blend mode of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface BlendMode { - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - } - - /** - * Provides methods used for calculating and setting the size of a non-Frame based Game Object. - * Should be applied as a mixin and not used directly. - */ - interface ComputedSize { - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - } - - /** - * Provides methods used for getting and setting the texture of a Game Object. - */ - interface Crop { - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - } - - /** - * Provides methods used for setting the depth of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Depth { - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - } - - /** - * Provides methods used for visually flipping a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Flip { - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - } - - /** - * Provides methods used for obtaining the bounds of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface GetBounds { - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - } - - /** - * Provides methods used for getting and setting the mask of a Game Object. - */ - interface Mask { - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - } - - /** - * Provides methods used for getting and setting the origin of a Game Object. - * Values are normalized, given in the range 0 to 1. - * Display values contain the calculated pixel values. - * Should be applied as a mixin and not used directly. - */ - interface Origin { - /** - * 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. - */ - originX: number; - /** - * 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. - */ - originY: number; - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - } - - /** - * Provides methods used for managing a Game Object following a Path. - * Should be applied as a mixin and not used directly. - */ - interface PathFollower { - /** - * The Path this PathFollower is following. It can only follow one Path at a time. - */ - path: Phaser.Curves.Path; - /** - * Should the PathFollower automatically rotate to point in the direction of the Path? - */ - rotateToPath: boolean; - /** - * Set the Path that this PathFollower should follow. - * - * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. - * @param path The Path this PathFollower is following. It can only follow one Path at a time. - * @param config Settings for the PathFollower. - */ - setPath(path: Phaser.Curves.Path, config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig): Phaser.GameObjects.PathFollower; - /** - * Set whether the PathFollower should automatically rotate to point in the direction of the Path. - * @param value Whether the PathFollower should automatically rotate to point in the direction of the Path. - * @param offset Rotation offset in degrees. Default 0. - */ - setRotateToPath(value: boolean, offset?: number): Phaser.GameObjects.PathFollower; - /** - * Is this PathFollower actively following a Path or not? - * - * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. - */ - isFollowing(): boolean; - /** - * Starts this PathFollower following its given Path. - * @param config The duration of the follow, or a PathFollower config object. Default {}. - * @param startAt Optional start position of the follow, between 0 and 1. Default 0. - */ - startFollow(config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig, startAt?: number): Phaser.GameObjects.PathFollower; - /** - * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the - * point on the Path at which you paused it. - */ - pauseFollow(): Phaser.GameObjects.PathFollower; - /** - * Resumes a previously paused PathFollower. - * - * If the PathFollower was not paused this has no effect. - */ - resumeFollow(): Phaser.GameObjects.PathFollower; - /** - * Stops this PathFollower from following the path any longer. - * - * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. - */ - stopFollow(): Phaser.GameObjects.PathFollower; - /** - * Internal update handler that advances this PathFollower along the path. - * - * Called automatically by the Scene step, should not typically be called directly. - */ - pathUpdate(): void; - } - - /** - * Provides methods used for setting the WebGL rendering pipeline of a Game Object. - */ - interface Pipeline { - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - } - - /** - * Provides methods used for getting and setting the Scroll Factor of a Game Object. - */ - interface ScrollFactor { - /** - * 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 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. - */ - scrollFactorX: number; - /** - * 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 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. - */ - scrollFactorY: number; - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - } - - /** - * Provides methods used for getting and setting the size of a Game Object. - */ - interface Size { - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - } - - /** - * Provides methods used for getting and setting the texture of a Game Object. - */ - interface Texture { - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - } - - /** - * Provides methods used for getting and setting the texture of a Game Object. - */ - interface TextureCrop { - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - } - - /** - * Provides methods used for setting the tint of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Tint { - /** - * Fill or additive? - */ - tintFill: boolean; - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - } - - /** - * Build a JSON representation of the given Game Object. - * - * This is typically extended further by Game Object specific implementations. - */ - interface ToJSON { - } - - /** - * Provides methods used for getting and setting the position, scale and rotation of a Game Object. - */ - interface Transform { - /** - * The x position of this Game Object. - */ - x: number; - /** - * The y position of this Game Object. - */ - y: number; - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - /** - * The w position of this Game Object. - */ - w: number; - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - } - - /** - * A Matrix used for display transformations for rendering. - * - * It is represented like so: - * - * ``` - * | a | c | tx | - * | b | d | ty | - * | 0 | 0 | 1 | - * ``` - */ - class TransformMatrix { - /** - * - * @param a The Scale X value. Default 1. - * @param b The Skew Y value. Default 0. - * @param c The Skew X value. Default 0. - * @param d The Scale Y value. Default 1. - * @param tx The Translate X value. Default 0. - * @param ty The Translate Y value. Default 0. - */ - constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number); - - /** - * The matrix values. - */ - matrix: Float32Array; - - /** - * The decomposed matrix. - */ - decomposedMatrix: object; - - /** - * The Scale X value. - */ - a: number; - - /** - * The Skew Y value. - */ - b: number; - - /** - * The Skew X value. - */ - c: number; - - /** - * The Scale Y value. - */ - d: number; - - /** - * The Translate X value. - */ - e: number; - - /** - * The Translate Y value. - */ - f: number; - - /** - * The Translate X value. - */ - tx: number; - - /** - * The Translate Y value. - */ - ty: number; - - /** - * The rotation of the Matrix. Value is in radians. - */ - readonly rotation: number; - - /** - * The rotation of the Matrix, normalized to be within the Phaser right-handed - * clockwise rotation space. Value is in radians. - */ - readonly rotationNormalized: number; - - /** - * The decomposed horizontal scale of the Matrix. This value is always positive. - */ - readonly scaleX: number; - - /** - * The decomposed vertical scale of the Matrix. This value is always positive. - */ - readonly scaleY: number; - - /** - * Reset the Matrix to an identity matrix. - */ - loadIdentity(): this; - - /** - * Translate the Matrix. - * @param x The horizontal translation value. - * @param y The vertical translation value. - */ - translate(x: number, y: number): this; - - /** - * Scale the Matrix. - * @param x The horizontal scale value. - * @param y The vertical scale value. - */ - scale(x: number, y: number): this; - - /** - * Rotate the Matrix. - * @param angle The angle of rotation in radians. - */ - rotate(angle: number): this; - - /** - * Multiply this Matrix by the given Matrix. - * - * If an `out` Matrix is given then the results will be stored in it. - * If it is not given, this matrix will be updated in place instead. - * Use an `out` Matrix if you do not wish to mutate this matrix. - * @param rhs The Matrix to multiply by. - * @param out An optional Matrix to store the results in. - */ - multiply(rhs: Phaser.GameObjects.Components.TransformMatrix, out?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Multiply this Matrix by the matrix given, including the offset. - * - * The offsetX is added to the tx value: `offsetX * a + offsetY * c + tx`. - * The offsetY is added to the ty value: `offsetY * b + offsetY * d + ty`. - * @param src The source Matrix to copy from. - * @param offsetX Horizontal offset to factor in to the multiplication. - * @param offsetY Vertical offset to factor in to the multiplication. - */ - multiplyWithOffset(src: Phaser.GameObjects.Components.TransformMatrix, offsetX: number, offsetY: number): this; - - /** - * Transform the Matrix. - * @param a The Scale X value. - * @param b The Shear Y value. - * @param c The Shear X value. - * @param d The Scale Y value. - * @param tx The Translate X value. - * @param ty The Translate Y value. - */ - transform(a: number, b: number, c: number, d: number, tx: number, ty: number): this; - - /** - * Transform a point using this Matrix. - * @param x The x coordinate of the point to transform. - * @param y The y coordinate of the point to transform. - * @param point The Point object to store the transformed coordinates. - */ - transformPoint(x: number, y: number, point: Phaser.Geom.Point | Phaser.Math.Vector2 | object): Phaser.Geom.Point | Phaser.Math.Vector2 | object; - - /** - * Invert the Matrix. - */ - invert(): this; - - /** - * Set the values of this Matrix to copy those of the matrix given. - * @param src The source Matrix to copy from. - */ - copyFrom(src: Phaser.GameObjects.Components.TransformMatrix): this; - - /** - * Set the values of this Matrix to copy those of the array given. - * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. - * @param src The array of values to set into this matrix. - */ - copyFromArray(src: any[]): this; - - /** - * Copy the values from this Matrix to the given Canvas Rendering Context. - * This will use the Context.transform method. - * @param ctx The Canvas Rendering Context to copy the matrix values to. - */ - copyToContext(ctx: CanvasRenderingContext2D): CanvasRenderingContext2D; - - /** - * Copy the values from this Matrix to the given Canvas Rendering Context. - * This will use the Context.setTransform method. - * @param ctx The Canvas Rendering Context to copy the matrix values to. - */ - setToContext(ctx: CanvasRenderingContext2D): CanvasRenderingContext2D; - - /** - * Copy the values in this Matrix to the array given. - * - * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. - * @param out The array to copy the matrix values in to. - */ - copyToArray(out?: any[]): any[]; - - /** - * Set the values of this Matrix. - * @param a The Scale X value. - * @param b The Shear Y value. - * @param c The Shear X value. - * @param d The Scale Y value. - * @param tx The Translate X value. - * @param ty The Translate Y value. - */ - setTransform(a: number, b: number, c: number, d: number, tx: number, ty: number): this; - - /** - * Decompose this Matrix into its translation, scale and rotation values using QR decomposition. - * - * The result must be applied in the following order to reproduce the current matrix: - * - * translate -> rotate -> scale - */ - decomposeMatrix(): object; - - /** - * Apply the identity, translate, rotate and scale operations on the Matrix. - * @param x The horizontal translation. - * @param y The vertical translation. - * @param rotation The angle of rotation in radians. - * @param scaleX The horizontal scale. - * @param scaleY The vertical scale. - */ - applyITRS(x: number, y: number, rotation: number, scaleX: number, scaleY: number): this; - - /** - * Takes the `x` and `y` values and returns a new position in the `output` vector that is the inverse of - * the current matrix with its transformation applied. - * - * Can be used to translate points from world to local space. - * @param x The x position to translate. - * @param y The y position to translate. - * @param output A Vector2, or point-like object, to store the results in. - */ - applyInverse(x: number, y: number, output?: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Returns the X component of this matrix multiplied by the given values. - * This is the same as `x * a + y * c + e`. - * @param x The x value. - * @param y The y value. - */ - getX(x: number, y: number): number; - - /** - * Returns the Y component of this matrix multiplied by the given values. - * This is the same as `x * b + y * d + f`. - * @param x The x value. - * @param y The y value. - */ - getY(x: number, y: number): number; - - /** - * Returns a string that can be used in a CSS Transform call as a `matrix` property. - */ - getCSSMatrix(): string; - - /** - * Destroys this Transform Matrix. - */ - destroy(): void; - - } - - /** - * Provides methods used for setting the visibility of a Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Visible { - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - } - - } - - /** - * A Container Game Object. - * - * A Container, as the name implies, can 'contain' other types of Game Object. - * When a Game Object is added to a Container, the Container becomes responsible for the rendering of it. - * By default it will be removed from the Display List and instead added to the Containers own internal list. - * - * The position of the Game Object automatically becomes relative to the position of the Container. - * - * When the Container is rendered, all of its children are rendered as well, in the order in which they exist - * within the Container. Container children can be repositioned using methods such as `MoveUp`, `MoveDown` and `SendToBack`. - * - * If you modify a transform property of the Container, such as `Container.x` or `Container.rotation` then it will - * automatically influence all children as well. - * - * Containers can include other Containers for deeply nested transforms. - * - * Containers can have masks set on them and can be used as a mask too. However, Container children cannot be masked. - * The masks do not 'stack up'. Only a Container on the root of the display list will use its mask. - * - * Containers can be enabled for input. Because they do not have a texture you need to provide a shape for them - * to use as their hit area. Container children can also be enabled for input, independent of the Container. - * - * Containers can be given a physics body for either Arcade Physics, Impact Physics or Matter Physics. However, - * if Container _children_ are enabled for physics you may get unexpected results, such as offset bodies, - * if the Container itself, or any of its ancestors, is positioned anywhere other than at 0 x 0. Container children - * with physics do not factor in the Container due to the excessive extra calculations needed. Please structure - * your game to work around this. - * - * It's important to understand the impact of using Containers. They add additional processing overhead into - * every one of their children. The deeper you nest them, the more the cost escalates. This is especially true - * for input events. You also loose the ability to set the display depth of Container children in the same - * flexible manner as those not within them. In short, don't use them for the sake of it. You pay a small cost - * every time you create one, try to structure your game around avoiding that where possible. - */ - class Container extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param children An optional array of Game Objects to add to this Container. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, children?: Phaser.GameObjects.GameObject[]); - - /** - * An array holding the children of this Container. - */ - list: Phaser.GameObjects.GameObject[]; - - /** - * Does this Container exclusively manage its children? - * - * The default is `true` which means a child added to this Container cannot - * belong in another Container, which includes the Scene display list. - * - * If you disable this then this Container will no longer exclusively manage its children. - * This allows you to create all kinds of interesting graphical effects, such as replicating - * Game Objects without reparenting them all over the Scene. - * However, doing so will prevent children from receiving any kind of input event or have - * their physics bodies work by default, as they're no longer a single entity on the - * display list, but are being replicated where-ever this Container is. - */ - exclusive: boolean; - - /** - * Containers can have an optional maximum size. If set to anything above 0 it - * will constrict the addition of new Game Objects into the Container, capping off - * the maximum limit the Container can grow in size to. - */ - maxSize: integer; - - /** - * The cursor position. - */ - position: integer; - - /** - * Internal Transform Matrix used for local space conversion. - */ - localTransform: Phaser.GameObjects.Components.TransformMatrix; - - /** - * 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. - */ - scrollFactorX: number; - - /** - * 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. - */ - scrollFactorY: number; - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - */ - readonly originX: number; - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - */ - readonly originY: number; - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - */ - readonly displayOriginX: number; - - /** - * Internal value to allow Containers to be used for input and physics. - * Do not change this value. It has no effect other than to break things. - */ - readonly displayOriginY: number; - - /** - * Does this Container exclusively manage its children? - * - * The default is `true` which means a child added to this Container cannot - * belong in another Container, which includes the Scene display list. - * - * If you disable this then this Container will no longer exclusively manage its children. - * This allows you to create all kinds of interesting graphical effects, such as replicating - * Game Objects without reparenting them all over the Scene. - * However, doing so will prevent children from receiving any kind of input event or have - * their physics bodies work by default, as they're no longer a single entity on the - * display list, but are being replicated where-ever this Container is. - * @param value The exclusive state of this Container. Default true. - */ - setExclusive(value?: boolean): Phaser.GameObjects.Container; - - /** - * Gets the bounds of this Container. It works by iterating all children of the Container, - * getting their respective bounds, and then working out a min-max rectangle from that. - * It does not factor in if the children render or not, all are included. - * - * Some children are unable to return their bounds, such as Graphics objects, in which case - * they are skipped. - * - * Depending on the quantity of children in this Container it could be a really expensive call, - * so cache it and only poll it as needed. - * - * The values are stored and returned in a Rectangle object. - * @param output A Geom.Rectangle object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: Phaser.Geom.Rectangle): Phaser.Geom.Rectangle; - - /** - * Takes a Point-like object, such as a Vector2, Geom.Point or object with public x and y properties, - * and transforms it into the space of this Container, then returns it in the output object. - * @param source The Source Point to be transformed. - * @param output A destination object to store the transformed point in. If none given a Vector2 will be created and returned. - */ - pointToContainer(source: object | Phaser.Geom.Point | Phaser.Math.Vector2, output?: object | Phaser.Geom.Point | Phaser.Math.Vector2): object | Phaser.Geom.Point | Phaser.Math.Vector2; - - /** - * Returns the world transform matrix as used for Bounds checks. - * - * The returned matrix is temporal and shouldn't be stored. - */ - getBoundsTransformMatrix(): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Adds the given Game Object, or array of Game Objects, to this Container. - * - * Each Game Object must be unique within the Container. - * @param child The Game Object, or array of Game Objects, to add to the Container. - */ - add(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[]): Phaser.GameObjects.Container; - - /** - * Adds the given Game Object, or array of Game Objects, to this Container at the specified position. - * - * Existing Game Objects in the Container are shifted up. - * - * Each Game Object must be unique within the Container. - * @param child The Game Object, or array of Game Objects, to add to the Container. - * @param index The position to insert the Game Object/s at. Default 0. - */ - addAt(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], index?: integer): Phaser.GameObjects.Container; - - /** - * Returns the Game Object at the given position in this Container. - * @param index The position to get the Game Object from. - */ - getAt(index: integer): Phaser.GameObjects.GameObject; - - /** - * Returns the index of the given Game Object in this Container. - * @param child The Game Object to search for in this Container. - */ - getIndex(child: Phaser.GameObjects.GameObject): integer; - - /** - * 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. - * @param property The property to lexically sort by. - * @param handler Provide your own custom handler function. Will receive 2 children which it should compare and return a boolean. - */ - sort(property: string, handler?: Function): Phaser.GameObjects.Container; - - /** - * Searches for the first instance of a child with its `name` property matching the given argument. - * Should more than one child have the same name only the first is returned. - * @param name The name to search for. - */ - getByName(name: string): Phaser.GameObjects.GameObject; - - /** - * Returns a random Game Object from this Container. - * @param startIndex An optional start index. Default 0. - * @param length An optional length, the total number of elements (from the startIndex) to choose from. - */ - getRandom(startIndex?: integer, length?: integer): Phaser.GameObjects.GameObject; - - /** - * Gets the first Game Object in this Container. - * - * You can also specify a property and value to search for, in which case it will return the first - * Game Object in this Container with a matching property and / or value. - * - * For example: `getFirst('visible', true)` would return the first Game Object that had its `visible` property set. - * - * You can limit the search to the `startIndex` - `endIndex` range. - * @param property The property to test on each Game Object in the Container. - * @param value The value to test the property against. Must pass a strict (`===`) comparison check. - * @param startIndex An optional start index to search from. Default 0. - * @param endIndex An optional end index to search up to (but not included) Default Container.length. - */ - getFirst(property: string, value: any, startIndex?: integer, endIndex?: integer): Phaser.GameObjects.GameObject; - - /** - * Returns all Game Objects in this Container. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('body')` would return only Game Objects that have a body property. - * - * You can also specify a value to compare the property to: - * - * `getAll('visible', true)` would return only Game Objects that have their visible property set to `true`. - * - * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 Game Objects. - * @param property The property to test on each Game Object in the Container. - * @param value If property is set then the `property` must strictly equal this value to be included in the results. - * @param startIndex An optional start index to search from. Default 0. - * @param endIndex An optional end index to search up to (but not included) Default Container.length. - */ - getAll(property?: string, value?: any, startIndex?: integer, endIndex?: integer): Phaser.GameObjects.GameObject[]; - - /** - * Returns the total number of Game Objects in this Container that have a property - * matching the given value. - * - * For example: `count('visible', true)` would count all the elements that have their visible property set. - * - * You can optionally limit the operation to the `startIndex` - `endIndex` range. - * @param property The property to check. - * @param value The value to check. - * @param startIndex An optional start index to search from. Default 0. - * @param endIndex An optional end index to search up to (but not included) Default Container.length. - */ - count(property: string, value: any, startIndex?: integer, endIndex?: integer): integer; - - /** - * Swaps the position of two Game Objects in this Container. - * Both Game Objects must belong to this Container. - * @param child1 The first Game Object to swap. - * @param child2 The second Game Object to swap. - */ - swap(child1: Phaser.GameObjects.GameObject, child2: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; - - /** - * Moves a Game Object to a new position within this Container. - * - * The Game Object must already be a child of this Container. - * - * The Game Object is removed from its old position and inserted into the new one. - * Therefore the Container size does not change. Other children will change position accordingly. - * @param child The Game Object to move. - * @param index The new position of the Game Object in this Container. - */ - moveTo(child: Phaser.GameObjects.GameObject, index: integer): Phaser.GameObjects.Container; - - /** - * Removes the given Game Object, or array of Game Objects, from this Container. - * - * The Game Objects must already be children of this Container. - * - * You can also optionally call `destroy` on each Game Object that is removed from the Container. - * @param child The Game Object, or array of Game Objects, to be removed from the Container. - * @param destroyChild Optionally call `destroy` on each child successfully removed from this Container. Default false. - */ - remove(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], destroyChild?: boolean): Phaser.GameObjects.Container; - - /** - * Removes the Game Object at the given position in this Container. - * - * You can also optionally call `destroy` on the Game Object, if one is found. - * @param index The index of the Game Object to be removed. - * @param destroyChild Optionally call `destroy` on the Game Object if successfully removed from this Container. Default false. - */ - removeAt(index: integer, destroyChild?: boolean): Phaser.GameObjects.Container; - - /** - * Removes the Game Objects between the given positions in this Container. - * - * You can also optionally call `destroy` on each Game Object that is removed from the Container. - * @param startIndex An optional start index to search from. Default 0. - * @param endIndex An optional end index to search up to (but not included) Default Container.length. - * @param destroyChild Optionally call `destroy` on each Game Object successfully removed from this Container. Default false. - */ - removeBetween(startIndex?: integer, endIndex?: integer, destroyChild?: boolean): Phaser.GameObjects.Container; - - /** - * Removes all Game Objects from this Container. - * - * You can also optionally call `destroy` on each Game Object that is removed from the Container. - * @param destroyChild Optionally call `destroy` on each Game Object successfully removed from this Container. Default false. - */ - removeAll(destroyChild?: boolean): Phaser.GameObjects.Container; - - /** - * Brings the given Game Object to the top of this Container. - * This will cause it to render on-top of any other objects in the Container. - * @param child The Game Object to bring to the top of the Container. - */ - bringToTop(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; - - /** - * Sends the given Game Object to the bottom of this Container. - * This will cause it to render below any other objects in the Container. - * @param child The Game Object to send to the bottom of the Container. - */ - sendToBack(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; - - /** - * Moves the given Game Object up one place in this Container, unless it's already at the top. - * @param child The Game Object to be moved in the Container. - */ - moveUp(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; - - /** - * Moves the given Game Object down one place in this Container, unless it's already at the bottom. - * @param child The Game Object to be moved in the Container. - */ - moveDown(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; - - /** - * Reverses the order of all Game Objects in this Container. - */ - reverse(): Phaser.GameObjects.Container; - - /** - * Shuffles the all Game Objects in this Container using the Fisher-Yates implementation. - */ - shuffle(): Phaser.GameObjects.Container; - - /** - * Replaces a Game Object in this Container with the new Game Object. - * The new Game Object cannot already be a child of this Container. - * @param oldChild The Game Object in this Container that will be replaced. - * @param newChild The Game Object to be added to this Container. - * @param destroyChild Optionally call `destroy` on the Game Object if successfully removed from this Container. Default false. - */ - replace(oldChild: Phaser.GameObjects.GameObject, newChild: Phaser.GameObjects.GameObject, destroyChild?: boolean): Phaser.GameObjects.Container; - - /** - * Returns `true` if the given Game Object is a direct child of this Container. - * - * This check does not scan nested Containers. - * @param child The Game Object to check for within this Container. - */ - exists(child: Phaser.GameObjects.GameObject): boolean; - - /** - * Sets the property to the given value on all Game Objects in this Container. - * - * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 Game Objects. - * @param property The property that must exist on the Game Object. - * @param value The value to get the property to. - * @param startIndex An optional start index to search from. Default 0. - * @param endIndex An optional end index to search up to (but not included) Default Container.length. - */ - setAll(property: string, value: any, startIndex?: integer, endIndex?: integer): Phaser.GameObjects.Container; - - /** - * Passes all Game Objects in this Container to the given callback. - * - * A copy of the Container is made before passing each entry to your callback. - * This protects against the callback itself modifying the Container. - * - * If you know for sure that the callback will not change the size of this Container - * then you can use the more performant `Container.iterate` method instead. - * @param callback The function to call. - * @param context Value to use as `this` when executing callback. - * @param args Additional arguments that will be passed to the callback, after the child. - */ - each(callback: Function, context?: object, ...args: any[]): Phaser.GameObjects.Container; - - /** - * Passes all Game Objects in this Container to the given callback. - * - * Only use this method when you absolutely know that the Container will not be modified during - * the iteration, i.e. by removing or adding to its contents. - * @param callback The function to call. - * @param context Value to use as `this` when executing callback. - * @param args Additional arguments that will be passed to the callback, after the child. - */ - iterate(callback: Function, context?: object, ...args: any[]): Phaser.GameObjects.Container; - - /** - * 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - * @param updateChildren Apply this scrollFactor to all Container children as well? Default false. - */ - setScrollFactor(x: number, y?: number, updateChildren?: boolean): this; - - /** - * The number of Game Objects inside this Container. - */ - readonly length: integer; - - /** - * Returns the first Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - */ - readonly first: Phaser.GameObjects.GameObject; - - /** - * Returns the last Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - */ - readonly last: Phaser.GameObjects.GameObject; - - /** - * Returns the next Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - */ - readonly next: Phaser.GameObjects.GameObject; - - /** - * Returns the previous Game Object within the Container, or `null` if it is empty. - * - * You can move the cursor by calling `Container.next` and `Container.previous`. - */ - readonly previous: Phaser.GameObjects.GameObject; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Display List plugin. - * - * Display Lists belong to a Scene and maintain the list of Game Objects to render every frame. - * - * Some of these Game Objects may also be part of the Scene's [Update List]{@link Phaser.GameObjects.UpdateList}, for updating. - */ - class DisplayList extends Phaser.Structs.List { - /** - * - * @param scene The Scene that this Display List belongs to. - */ - constructor(scene: Phaser.Scene); - - /** - * The flag the determines whether Game Objects should be sorted when `depthSort()` is called. - */ - sortChildrenFlag: boolean; - - /** - * The Scene that this Display List belongs to. - */ - scene: Phaser.Scene; - - /** - * The Scene's Systems. - */ - systems: Phaser.Scenes.Systems; - - /** - * Force a sort of the display list on the next call to depthSort. - */ - queueDepthSort(): void; - - /** - * Immediately sorts the display list if the flag is set. - */ - depthSort(): void; - - /** - * Compare the depth of two Game Objects. - * @param childA The first Game Object. - * @param childB The second Game Object. - */ - sortByDepth(childA: Phaser.GameObjects.GameObject, childB: Phaser.GameObjects.GameObject): integer; - - /** - * Returns an array which contains all objects currently on the Display List. - * This is a reference to the main list array, not a copy of it, so be careful not to modify it. - */ - getChildren(): Phaser.GameObjects.GameObject[]; - - } - - /** - * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. - * - * In order for DOM Elements to display you have to enable them by adding the following to your game - * configuration object: - * - * ```javascript - * dom { - * createContainer: true - * } - * ``` - * - * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top - * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of - * settings within the Scale Manager, the dom container is resized accordingly. - * - * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing - * Element that you wish to be placed under the control of Phaser. For example: - * - * ```javascript - * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); - * ``` - * - * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in - * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, - * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. - * - * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control - * alignment and positioning of the elements next to regular game content. - * - * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the - * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other - * methods available in this class to help construct your elements. - * - * Once the element has been created you can then control it like you would any other Game Object. You can set its - * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped - * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that - * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have - * a DOM Element, then a Sprite, then another DOM Element behind it. - * - * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event - * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas - * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you - * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. - * - * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. - * - * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert - * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. - * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and - * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top - * of your game, and should treat it accordingly. - */ - class DOMElement extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this DOM Element in the world. Default 0. - * @param y The vertical position of this DOM Element in the world. Default 0. - * @param element An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. - * @param style If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. - * @param innerText If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, element?: Element | string, style?: string | any, innerText?: string); - - /** - * A reference to the parent DOM Container that the Game instance created when it started. - */ - parent: Element; - - /** - * A reference to the HTML Cache. - */ - cache: Phaser.Cache.BaseCache; - - /** - * The actual DOM Element that this Game Object is bound to. For example, if you've created a `
` - * then this property is a direct reference to that element within the dom. - */ - node: Element; - - /** - * By default a DOM Element will have its transform, display, opacity, zIndex and blend mode properties - * updated when its rendered. If, for some reason, you don't want any of these changed other than the - * CSS transform, then set this flag to `true`. When `true` only the CSS Transform is applied and it's - * up to you to keep track of and set the other properties as required. - * - * This can be handy if, for example, you've a nested DOM Element and you don't want the opacity to be - * picked-up by any of its children. - */ - transformOnly: boolean; - - /** - * 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 - */ - skewX: number; - - /** - * 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 - */ - skewY: number; - - /** - * A Vector4 that contains the 3D rotation of this DOM Element around a fixed axis in 3D space. - * - * All values in the Vector4 are treated as degrees, unless the `rotate3dAngle` property is changed. - * - * For more details see the following MDN page: - * - * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d - */ - rotate3d: Phaser.Math.Vector4; - - /** - * 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 - */ - rotate3dAngle: string; - - /** - * The native (un-scaled) width of this Game Object. - * - * For a DOM Element this property is read-only. - * - * The property `displayWidth` holds the computed bounds of this DOM Element, factoring in scaling. - */ - readonly width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * For a DOM Element this property is read-only. - * - * The property `displayHeight` holds the computed bounds of this DOM Element, factoring in scaling. - */ - readonly height: number; - - /** - * 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. - */ - readonly displayWidth: number; - - /** - * 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. - */ - readonly displayHeight: number; - - /** - * 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 - * @param x The angle, in radians, by which to skew the DOM Element on the horizontal axis. Default 0. - * @param y The angle, in radians, by which to skew the DOM Element on the vertical axis. Default x. - */ - setSkew(x?: number, y?: number): this; - - /** - * 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.** - * @param value The perspective value, in pixels, that determines the distance between the z plane and the user. - */ - setPerspective(value: number): this; - - /** - * 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.** - */ - perspective: number; - - /** - * Adds one or more native DOM event listeners onto the underlying Element of this Game Object. - * The event is then dispatched via this Game Objects standard event emitter. - * - * For example: - * - * ```javascript - * var div = this.add.dom(x, y, element); - * - * div.addListener('click'); - * - * div.on('click', handler); - * ``` - * @param events The DOM event/s to listen for. You can specify multiple events by separating them with spaces. - */ - addListener(events: string): this; - - /** - * Removes one or more native DOM event listeners from the underlying Element of this Game Object. - * @param events The DOM event/s to stop listening for. You can specify multiple events by separating them with spaces. - */ - removeListener(events: string): this; - - /** - * 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. - * @param 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 style Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be ready from. - * @param innerText A DOMString that holds the text that will be set as the innerText of the created element. - */ - createElement(tagName: string, style?: string | any, innerText?: string): this; - - /** - * Binds a new DOM Element to this Game Object. 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 on the new element. - * - * The `element` argument you pass to this method can be either a string tagName: - * - * ```javascript - *

Phaser

- * - * this.add.dom().setElement('heading'); - * ``` - * - * Or a reference to an Element instance: - * - * ```javascript - *

Phaser

- * - * var h1 = document.getElementById('heading'); - * - * this.add.dom().setElement(h1); - * ``` - * - * 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().setElement(h1, '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().setElement(h1, style, 'Phaser'); - * ``` - * @param element If a string it is passed to `getElementById()`, or it should be a reference to an existing Element. - * @param style Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be ready from. - * @param innerText A DOMString that holds the text that will be set as the innerText of the created element. - */ - setElement(element: string | Element, style?: string | any, innerText?: string): this; - - /** - * Takes a block of html from the HTML Cache, that has previously been preloaded into the game, and then - * creates a DOM Element from it. The loaded HTML is set as the `innerHTML` property of the created - * element. - * - * Assume the following html is stored in a file called `loginform.html`: - * - * ```html - * - * - * ``` - * - * Which is loaded into your game using the cache key 'login': - * - * ```javascript - * this.load.html('login', 'assets/loginform.html'); - * ``` - * - * You can create a DOM Element from it using the cache key: - * - * ```javascript - * this.add.dom().createFromCache('login'); - * ``` - * - * The optional `elementType` argument controls the container that is created, into which the loaded html is inserted. - * The default is a plain `div` object, but any valid tagName can be given. - * - * 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. - * @param The key of the html cache entry to use for this DOM Element. - * @param tagName The tag name of the element into which all of the loaded html will be inserted. Defaults to a plain div tag. Default 'div'. - */ - createFromCache(The: string, tagName?: string): this; - - /** - * Takes a string of html and then creates a DOM Element from it. The HTML is set as the `innerHTML` - * property of the created element. - * - * ```javascript - * let form = ` - * - * - * `; - * ``` - * - * You can create a DOM Element from it using the string: - * - * ```javascript - * this.add.dom().createFromHTML(form); - * ``` - * - * The optional `elementType` argument controls the type of container that is created, into which the html is inserted. - * The default is a plain `div` object, but any valid tagName can be given. - * - * 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. - * @param A string of html to be set as the `innerHTML` property of the created element. - * @param tagName The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag. Default 'div'. - */ - createFromHTML(A: string, tagName?: string): this; - - /** - * Removes the current DOM Element bound to this Game Object from the DOM entirely and resets the - * `node` property of this Game Object to be `null`. - */ - removeElement(): this; - - /** - * Internal method that calls `getBoundingClientRect` on the `node` and then sets the bounds width - * and height into the `displayWidth` and `displayHeight` properties, and the `clientWidth` and `clientHeight` - * values into the `width` and `height` properties respectively. - * - * This is called automatically whenever a new element is created or set. - */ - updateSize(): this; - - /** - * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through - * them, looking for the first one that has a property matching the given key and value. It then returns this child - * if found, or `null` if not. - * @param property The property to search the children for. - * @param value The value the property must strictly equal. - */ - getChildByProperty(property: string, value: string): Element; - - /** - * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through - * them, looking for the first one that has a matching id. It then returns this child if found, or `null` if not. - * - * Be aware that class and id names are case-sensitive. - * @param id The id to search the children for. - */ - getChildByID(id: string): Element; - - /** - * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through - * them, looking for the first one that has a matching name. It then returns this child if found, or `null` if not. - * - * Be aware that class and id names are case-sensitive. - * @param name The name to search the children for. - */ - getChildByName(name: string): Element; - - /** - * Sets the `className` property of the DOM Element node and updates the internal sizes. - * @param className A string representing the class or space-separated classes of the element. - */ - setClassName(className: string): this; - - /** - * Sets the `innerText` property of the DOM Element node and updates the internal sizes. - * - * Note that only certain types of Elements can have `innerText` set on them. - * @param text A DOMString representing the rendered text content of the element. - */ - setText(text: string): this; - - /** - * Sets the `innerHTML` property of the DOM Element node and updates the internal sizes. - * @param html A DOMString of html to be set as the `innerHTML` property of the element. - */ - setHTML(html: string): this; - - /** - * Compares the renderMask with the renderFlags to see if this Game Object will render or not. - * - * DOMElements always return `true` as they need to still set values during the render pass, even if not visible. - */ - willRender(): boolean; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - namespace Events { - /** - * The Game Object Destroy Event. - * - * This event is dispatched when a Game Object instance is being destroyed. - * - * Listen for it on a Game Object instance using `GameObject.on('destroy', listener)`. - */ - const DESTROY: any; - - /** - * The Video Game Object Complete Event. - * - * This event is dispatched when a Video finishes playback by reaching the end of its duration. It - * is also dispatched if a video marker sequence is being played and reaches the end. - * - * Note that not all videos can fire this event. Live streams, for example, have no fixed duration, - * so never technically 'complete'. - * - * If a video is stopped from playback, via the `Video.stop` method, it will emit the - * `VIDEO_STOP` event instead of this one. - * - * Listen for it from a Video Game Object instance using `Video.on('complete', listener)`. - */ - const VIDEO_COMPLETE: any; - - /** - * The Video Game Object Created Event. - * - * This event is dispatched when the texture for a Video has been created. This happens - * when enough of the video source has been loaded that the browser is able to render a - * frame from it. - * - * Listen for it from a Video Game Object instance using `Video.on('created', listener)`. - */ - const VIDEO_CREATED: any; - - /** - * The Video Game Object Error Event. - * - * This event is dispatched when a Video tries to play a source that does not exist, or is the wrong file type. - * - * Listen for it from a Video Game Object instance using `Video.on('error', listener)`. - */ - const VIDEO_ERROR: any; - - /** - * 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)`. - */ - const VIDEO_LOOP: any; - - /** - * The Video Game Object Play Event. - * - * This event is dispatched when a Video begins playback. For videos that do not require - * interaction unlocking, this is usually as soon as the `Video.play` method is called. - * However, for videos that require unlocking, it is fired once playback begins after - * they've been unlocked. - * - * Listen for it from a Video Game Object instance using `Video.on('play', listener)`. - */ - const VIDEO_PLAY: any; - - /** - * The Video Game Object Seeked Event. - * - * This event is dispatched when a Video completes seeking to a new point in its timeline. - * - * Listen for it from a Video Game Object instance using `Video.on('seeked', listener)`. - */ - const VIDEO_SEEKED: any; - - /** - * The Video Game Object Seeking Event. - * - * This event is dispatched when a Video _begins_ seeking to a new point in its timeline. - * When the seek is complete, it will dispatch the `VIDEO_SEEKED` event to conclude. - * - * Listen for it from a Video Game Object instance using `Video.on('seeking', listener)`. - */ - const VIDEO_SEEKING: any; - - /** - * The Video Game Object Stopped Event. - * - * This event is dispatched when a Video is stopped from playback via a call to the `Video.stop` method, - * either directly via game code, or indirectly as the result of changing a video source or destroying it. - * - * Listen for it from a Video Game Object instance using `Video.on('stop', listener)`. - */ - const VIDEO_STOP: any; - - /** - * The Video Game Object Timeout Event. - * - * This event is dispatched when a Video has exhausted its allocated time while trying to connect to a video - * source to start playback. - * - * Listen for it from a Video Game Object instance using `Video.on('timeout', listener)`. - */ - const VIDEO_TIMEOUT: any; - - /** - * The Video Game Object Unlocked Event. - * - * This event is dispatched when a Video that was prevented from playback due to the browsers - * Media Engagement Interaction policy, is unlocked by a user gesture. - * - * Listen for it from a Video Game Object instance using `Video.on('unlocked', listener)`. - */ - const VIDEO_UNLOCKED: any; - - } - - /** - * An Extern Game Object is a special type of Game Object that allows you to pass - * rendering off to a 3rd party. - * - * When you create an Extern and place it in the display list of a Scene, the renderer will - * process the list as usual. When it finds an Extern it will flush the current batch, - * clear down the pipeline and prepare a transform matrix which your render function can - * take advantage of, if required. - * - * The WebGL context is then left is a 'clean' state, ready for you to bind your own shaders, - * or draw to it, whatever you wish to do. Once you've finished, you should free-up any - * of your resources. The Extern will then rebind the Phaser pipeline and carry on - * rendering the display list. - * - * Although this object has lots of properties such as Alpha, Blend Mode and Tint, none of - * them are used during rendering unless you take advantage of them in your own render code. - */ - class Extern extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - */ - constructor(scene: Phaser.Scene); - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The base class that all Game Objects extend. - * You don't create GameObjects directly and they cannot be added to the display list. - * Instead, use them as the base for your own custom classes. - */ - class GameObject extends Phaser.Events.EventEmitter { - /** - * - * @param scene The Scene to which this Game Object belongs. - * @param type A textual representation of the type of Game Object, i.e. `sprite`. - */ - constructor(scene: Phaser.Scene, type: string); - - /** - * The Scene to which this Game Object belongs. - * Game Objects can only belong to one Scene. - */ - protected scene: Phaser.Scene; - - /** - * A textual representation of this Game Object, i.e. `sprite`. - * Used internally by Phaser but is available for your own custom classes to populate. - */ - type: string; - - /** - * The current state of this Game Object. - * - * Phaser itself will never modify this value, although plugins may do so. - * - * Use this property to track the state of a Game Object during its lifetime. For example, it could change from - * a state of 'moving', to 'attacking', to 'dead'. The state value should be an integer (ideally mapped to a constant - * in your game code), or a string. These are recommended to keep it light and simple, with fast comparisons. - * If you need to store complex data about your Game Object, look at using the Data Component instead. - */ - state: integer | string; - - /** - * The parent Container of this Game Object, if it has one. - */ - parentContainer: Phaser.GameObjects.Container; - - /** - * The name of this Game Object. - * Empty by default and never populated by Phaser, this is left for developers to use. - */ - name: string; - - /** - * The active state of this Game Object. - * A Game Object with an active state of `true` is processed by the Scenes UpdateList, if added to it. - * An active object is one which is having its logic and internal systems updated. - */ - active: boolean; - - /** - * The Tab Index of the Game Object. - * Reserved for future use by plugins and the Input Manager. - */ - tabIndex: integer; - - /** - * A Data Manager. - * It allows you to store, query and get key/value paired information specific to this Game Object. - * `null` by default. Automatically created if you use `getData` or `setData` or `setDataEnabled`. - */ - data: Phaser.Data.DataManager; - - /** - * The flags that are compared against `RENDER_MASK` to determine if this Game Object will render or not. - * The bits are 0001 | 0010 | 0100 | 1000 set by the components Visible, Alpha, Transform and Texture respectively. - * If those components are not used by your custom class then you can use this bitmask as you wish. - */ - renderFlags: integer; - - /** - * A bitmask that controls if this Game Object is drawn by a Camera or not. - * Not usually set directly, instead call `Camera.ignore`, however you can - * set this property directly using the Camera.id property: - */ - cameraFilter: number; - - /** - * If this Game Object is enabled for input then this property will contain an InteractiveObject instance. - * Not usually set directly. Instead call `GameObject.setInteractive()`. - */ - input: Phaser.Types.Input.InteractiveObject; - - /** - * If this Game Object is enabled for physics then this property will contain a reference to a Physics Body. - */ - body: object | Phaser.Physics.Arcade.Body | Phaser.Physics.Impact.Body; - - /** - * This Game Object will ignore all calls made to its destroy method if this flag is set to `true`. - * This includes calls that may come from a Group, Container or the Scene itself. - * While it allows you to persist a Game Object across Scenes, please understand you are entirely - * responsible for managing references to and from this Game Object. - */ - ignoreDestroy: boolean; - - /** - * Sets the `active` property of this Game Object and returns this Game Object for further chaining. - * A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. - * @param value True if this Game Object should be set as active, false if not. - */ - setActive(value: boolean): this; - - /** - * Sets the `name` property of this Game Object and returns this Game Object for further chaining. - * The `name` property is not populated by Phaser and is presented for your own use. - * @param value The name to be given to this Game Object. - */ - setName(value: string): this; - - /** - * Sets the current state of this Game Object. - * - * Phaser itself will never modify the State of a Game Object, although plugins may do so. - * - * For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. - * The state value should typically be an integer (ideally mapped to a constant - * in your game code), but could also be a string. It is recommended to keep it light and simple. - * If you need to store complex data about your Game Object, look at using the Data Component instead. - * @param value The state of the Game Object. - */ - setState(value: integer | string): this; - - /** - * Adds a Data Manager component to this Game Object. - */ - setDataEnabled(): this; - - /** - * Allows you to store a key value pair within this Game Objects Data Manager. - * - * If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled - * before setting the value. - * - * If the key doesn't already exist in the Data Manager then it is created. - * - * ```javascript - * sprite.setData('name', 'Red Gem Stone'); - * ``` - * - * You can also pass in an object of key value pairs as the first argument: - * - * ```javascript - * sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); - * ``` - * - * To get a value back again you can call `getData`: - * - * ```javascript - * sprite.getData('gold'); - * ``` - * - * Or you can access the value directly via the `values` property, where it works like any other variable: - * - * ```javascript - * sprite.data.values.gold += 50; - * ``` - * - * When the value is first set, a `setdata` event is emitted from this Game Object. - * - * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. - * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. - * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. - * - * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. - * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. - * @param key The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. - * @param data The value to set for the given key. If an object is provided as the key this argument is ignored. - */ - setData(key: string | object, data?: any): this; - - /** - * Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. - * - * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: - * - * ```javascript - * sprite.getData('gold'); - * ``` - * - * Or access the value directly: - * - * ```javascript - * sprite.data.values.gold; - * ``` - * - * You can also pass in an array of keys, in which case an array of values will be returned: - * - * ```javascript - * sprite.getData([ 'gold', 'armor', 'health' ]); - * ``` - * - * This approach is useful for destructuring arrays in ES6. - * @param key The key of the value to retrieve, or an array of keys. - */ - getData(key: string | string[]): any; - - /** - * 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. - * @param shape 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 callback A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. - * @param dropZone Should this Game Object be treated as a drop zone target? Default false. - */ - setInteractive(shape?: Phaser.Types.Input.InputConfiguration | any, callback?: Phaser.Types.Input.HitAreaCallback, dropZone?: boolean): this; - - /** - * If this Game Object has previously been enabled for input, this will disable it. - * - * An object that is disabled for input stops processing or being considered for - * input events, but can be turned back on again at any time by simply calling - * `setInteractive()` with no arguments provided. - * - * If want to completely remove interaction from this Game Object then use `removeInteractive` instead. - */ - disableInteractive(): this; - - /** - * If this Game Object has previously been enabled for input, this will queue it - * for removal, causing it to no longer be interactive. The removal happens on - * the next game step, it is not immediate. - * - * The Interactive Object that was assigned to this Game Object will be destroyed, - * removed from the Input Manager and cleared from this Game Object. - * - * If you wish to re-enable this Game Object at a later date you will need to - * re-create its InteractiveObject by calling `setInteractive` again. - * - * If you wish to only temporarily stop an object from receiving input then use - * `disableInteractive` instead, as that toggles the interactive state, where-as - * this erases it completely. - * - * If you wish to resize a hit area, don't remove and then set it as being - * interactive. Instead, access the hitarea object directly and resize the shape - * being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the - * shape is a Rectangle, which it is by default.) - */ - removeInteractive(): this; - - /** - * To be overridden by custom GameObjects. Allows base objects to be used in a Pool. - * @param args args - */ - update(...args: any[]): void; - - /** - * Returns a JSON representation of the Game Object. - */ - toJSON(): Phaser.Types.GameObjects.JSONGameObject; - - /** - * Compares the renderMask with the renderFlags to see if this Game Object will render or not. - * Also checks the Game Object against the given Cameras exclusion list. - * @param camera The Camera to check against this Game Object. - */ - willRender(camera: Phaser.Cameras.Scene2D.Camera): boolean; - - /** - * Returns an array containing the display list index of either this Game Object, or if it has one, - * its parent Container. It then iterates up through all of the parent containers until it hits the - * root of the display list (which is index 0 in the returned array). - * - * Used internally by the InputPlugin but also useful if you wish to find out the display depth of - * this Game Object and all of its ancestors. - */ - getIndexList(): integer[]; - - /** - * Destroys this Game Object removing it from the Display List and Update List and - * severing all ties to parent resources. - * - * Also removes itself from the Input Manager and Physics Manager if previously enabled. - * - * Use this to remove a Game Object from your game if you don't ever plan to use it again. - * As long as no reference to it exists within your own code it should become free for - * garbage collection by the browser. - * - * If you just want to temporarily disable an object then look at using the - * Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. - * @param fromScene Is this Game Object being destroyed as the result of a Scene shutdown? Default false. - */ - destroy(fromScene?: boolean): void; - - /** - * The bitmask that `GameObject.renderFlags` is compared against to determine if the Game Object will render or not. - */ - static readonly RENDER_MASK: integer; - - } - - /** - * The Game Object Creator is a Scene plugin that allows you to quickly create many common - * types of Game Objects and return them. Unlike the Game Object Factory, they are not automatically - * added to the Scene. - * - * Game Objects directly register themselves with the Creator and inject their own creation - * methods into the class. - */ - class GameObjectCreator { - /** - * - * @param scene The Scene to which this Game Object Factory belongs. - */ - constructor(scene: Phaser.Scene); - - /** - * Creates a new Dynamic Bitmap Text Game Object and returns it. - * - * Note: This method will only be available if the Dynamic Bitmap Text Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - dynamicBitmapText(config: Phaser.Types.GameObjects.BitmapText.BitmapTextConfig, addToScene?: boolean): Phaser.GameObjects.DynamicBitmapText; - - /** - * Creates a new Bitmap Text Game Object and returns it. - * - * Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - bitmapText(config: Phaser.Types.GameObjects.BitmapText.BitmapTextConfig, addToScene?: boolean): Phaser.GameObjects.BitmapText; - - /** - * Creates a new Blitter Game Object and returns it. - * - * Note: This method will only be available if the Blitter Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - blitter(config: object, addToScene?: boolean): Phaser.GameObjects.Blitter; - - /** - * Creates a new Container Game Object and returns it. - * - * Note: This method will only be available if the Container Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - container(config: object, addToScene?: boolean): Phaser.GameObjects.Container; - - /** - * The Scene to which this Game Object Creator belongs. - */ - protected scene: Phaser.Scene; - - /** - * A reference to the Scene.Systems. - */ - protected systems: Phaser.Scenes.Systems; - - /** - * A reference to the Scene Display List. - */ - protected displayList: Phaser.GameObjects.DisplayList; - - /** - * A reference to the Scene Update List. - */ - protected updateList: Phaser.GameObjects.UpdateList; - - /** - * Creates a new Graphics Game Object and returns it. - * - * Note: This method will only be available if the Graphics Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - graphics(config: object, addToScene?: boolean): Phaser.GameObjects.Graphics; - - /** - * Creates a new Group Game Object and returns it. - * - * Note: This method will only be available if the Group Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - */ - group(config: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.GameObjects.Group; - - /** - * Creates a new Image Game Object and returns it. - * - * Note: This method will only be available if the Image Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - image(config: object, addToScene?: boolean): Phaser.GameObjects.Image; - - /** - * Creates a new Mesh Game Object and returns it. - * - * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - mesh(config: object, addToScene?: boolean): Phaser.GameObjects.Mesh; - - /** - * Creates a new Particle Emitter Manager Game Object and returns it. - * - * Note: This method will only be available if the Particles Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - particles(config: object, addToScene?: boolean): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Creates a new Quad Game Object and returns it. - * - * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - quad(config: object, addToScene?: boolean): Phaser.GameObjects.Quad; - - /** - * Creates a new Render Texture Game Object and returns it. - * - * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - renderTexture(config: Phaser.Types.GameObjects.RenderTexture.RenderTextureConfig, addToScene?: boolean): Phaser.GameObjects.RenderTexture; - - /** - * Creates a new Shader Game Object and returns it. - * - * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - shader(config: object, addToScene?: boolean): Phaser.GameObjects.Shader; - - /** - * Creates a new Sprite Game Object and returns it. - * - * Note: This method will only be available if the Sprite Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - sprite(config: Phaser.Types.GameObjects.Sprite.SpriteConfig, addToScene?: boolean): Phaser.GameObjects.Sprite; - - /** - * Creates a new Text Game Object and returns it. - * - * Note: This method will only be available if the Text Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - text(config: object, addToScene?: boolean): Phaser.GameObjects.Text; - - /** - * Creates a new TileSprite Game Object and returns it. - * - * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - tileSprite(config: Phaser.Types.GameObjects.TileSprite.TileSpriteConfig, addToScene?: boolean): Phaser.GameObjects.TileSprite; - - /** - * Creates a new Video Game Object and returns it. - * - * Note: This method will only be available if the Video Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. - */ - video(config: object, addToScene?: boolean): Phaser.GameObjects.Video; - - /** - * Creates a new Zone Game Object and returns it. - * - * Note: This method will only be available if the Zone Game Object has been built into Phaser. - * @param config The configuration object this Game Object will use to create itself. - */ - zone(config: object): Phaser.GameObjects.Zone; - - /** - * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. - * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing - * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map - * data. For an empty map, you should specify tileWidth, tileHeight, width & height. - * @param config The config options for the Tilemap. - */ - tilemap(config?: Phaser.Types.Tilemaps.TilemapConfig): Phaser.Tilemaps.Tilemap; - - /** - * Creates a new Tween object and returns it. - * - * Note: This method will only be available if Tweens have been built into Phaser. - * @param config The Tween configuration. - */ - tween(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; - - } - - /** - * The Game Object Factory is a Scene plugin that allows you to quickly create many common - * types of Game Objects and have them automatically registered with the Scene. - * - * Game Objects directly register themselves with the Factory and inject their own creation - * methods into the class. - */ - class GameObjectFactory { - /** - * - * @param scene The Scene to which this Game Object Factory belongs. - */ - constructor(scene: Phaser.Scene); - - /** - * Creates a new Path Object. - * @param x The horizontal position of this Path. - * @param y The vertical position of this Path. - */ - path(x: number, y: number): Phaser.Curves.Path; - - /** - * 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 for 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): 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. - * @param x The x position of the Game Object. - * @param y The y position of the Game Object. - * @param font The key of the font to use from the BitmapFont cache. - * @param text The string, or array of strings, to be set as the content of this Bitmap Text. - * @param size The font size to set. - */ - dynamicBitmapText(x: number, y: number, font: string, text?: string | string[], size?: number): Phaser.GameObjects.DynamicBitmapText; - - /** - * 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 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): 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. - * @param x The x position of the Game Object. - * @param y The y position of the Game Object. - * @param font The key of the font to use from the BitmapFont cache. - * @param text The string, or array of strings, to be set as the content of this Bitmap Text. - * @param size The font size to set. - * @param align The alignment of the text in a multi-line BitmapText object. Default 0. - */ - bitmapText(x: number, y: number, font: string, text?: string | string[], size?: number, align?: integer): Phaser.GameObjects.BitmapText; - - /** - * Creates a new Blitter Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Blitter Game Object has been built into Phaser. - * @param x The x position of the Game Object. - * @param y The y position of the Game Object. - * @param key The key of the Texture the Blitter object will use. - * @param frame The default Frame children of the Blitter will use. - */ - blitter(x: number, y: number, key: string, frame?: string | integer): Phaser.GameObjects.Blitter; - - /** - * Creates a new Container Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Container Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param children An optional array of Game Objects to add to this Container. - */ - container(x: number, y: number, children?: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[]): Phaser.GameObjects.Container; - - /** - * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. - * - * In order for DOM Elements to display you have to enable them by adding the following to your game - * configuration object: - * - * ```javascript - * dom { - * createContainer: true - * } - * ``` - * - * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top - * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of - * settings within the Scale Manager, the dom container is resized accordingly. - * - * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing - * Element that you wish to be placed under the control of Phaser. For example: - * - * ```javascript - * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); - * ``` - * - * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in - * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, - * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. - * - * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control - * alignment and positioning of the elements next to regular game content. - * - * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the - * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other - * methods available in this class to help construct your elements. - * - * Once the element has been created you can then control it like you would any other Game Object. You can set its - * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped - * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that - * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have - * a DOM Element, then a Sprite, then another DOM Element behind it. - * - * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event - * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas - * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you - * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. - * - * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. - * - * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert - * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. - * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and - * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top - * of your game, and should treat it accordingly. - * - * Note: This method will only be available if the DOM Element Game Object has been built into Phaser. - * @param x The horizontal position of this DOM Element in the world. - * @param y The vertical position of this DOM Element in the world. - * @param element An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. - * @param style If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. - * @param innerText If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. - */ - dom(x: number, y: number, element?: HTMLElement | string, style?: string | any, innerText?: string): Phaser.GameObjects.DOMElement; - - /** - * Creates a new Extern Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Extern Game Object has been built into Phaser. - */ - extern(): Phaser.GameObjects.Extern; - - /** - * The Scene to which this Game Object Factory belongs. - */ - protected scene: Phaser.Scene; - - /** - * A reference to the Scene.Systems. - */ - protected systems: Phaser.Scenes.Systems; - - /** - * A reference to the Scene Display List. - */ - protected displayList: Phaser.GameObjects.DisplayList; - - /** - * A reference to the Scene Update List. - */ - protected updateList: Phaser.GameObjects.UpdateList; - - /** - * Adds an existing Game Object to this Scene. - * - * If the Game Object renders, it will be added to the Display List. - * If it has a `preUpdate` method, it will be added to the Update List. - * @param child The child to be added to this Scene. - */ - existing(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.Group): Phaser.GameObjects.GameObject; - - /** - * Static method called directly by the Game Object factory functions. - * With this method you can register a custom GameObject factory in the GameObjectFactory, - * providing a name (`factoryType`) and the constructor (`factoryFunction`) in order - * to be called when you call to Phaser.Scene.add[ factoryType ] method. - * @param factoryType The key of the factory that you will use to call to Phaser.Scene.add[ factoryType ] method. - * @param factoryFunction The constructor function to be called when you invoke to the Phaser.Scene.add method. - */ - static register(factoryType: string, factoryFunction: Function): void; - - /** - * Static method called directly by the Game Object factory functions. - * With this method you can remove a custom GameObject factory registered in the GameObjectFactory, - * providing a its `factoryType`. - * @param factoryType The key of the factory that you want to remove from the GameObjectFactory. - */ - static remove(factoryType: string): void; - - /** - * Creates a new Graphics Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Graphics Game Object has been built into Phaser. - * @param config The Graphics configuration. - */ - graphics(config?: Phaser.Types.GameObjects.Graphics.Options): Phaser.GameObjects.Graphics; - - /** - * Creates a new Group Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Group Game Object has been built into Phaser. - * @param children Game Objects to add to this Group; or the `config` argument. - * @param config A Group Configuration object. - */ - group(children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupConfig[], config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.GameObjects.Group; - - /** - * Creates a new Image Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Image Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - image(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Image; - - /** - * Creates a new Mesh Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param vertices An array containing the vertices data for this Mesh. - * @param uv An array containing the uv data for this Mesh. - * @param colors An array containing the color data for this Mesh. - * @param alphas An array containing the alpha data for this Mesh. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - mesh(x: number, y: number, vertices: number[], uv: number[], colors: number[], alphas: number[], texture: string, frame?: string | integer): Phaser.GameObjects.Mesh; - - /** - * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Particles Game Object has been built into Phaser. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - * @param emitters Configuration settings for one or more emitters to create. - */ - particles(texture: string, frame?: string | integer | object, emitters?: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Creates a new PathFollower Game Object and adds it to the Scene. - * - * Note: This method will only be available if the PathFollower Game Object has been built into Phaser. - * @param path The Path this PathFollower is connected to. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - follower(path: Phaser.Curves.Path, x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.PathFollower; - - /** - * Creates a new Quad Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - quad(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Quad; - - /** - * Creates a new Render Texture Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. - * - * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and - * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic - * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param width The width of the Render Texture. Default 32. - * @param height The height of the Render Texture. Default 32. - */ - renderTexture(x: number, y: number, width?: integer, height?: integer): Phaser.GameObjects.RenderTexture; - - /** - * Creates a new Shader Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. - * @param key The key of the shader to use from the shader cache, or a BaseShader instance. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the Game Object. Default 128. - * @param height The height of the Game Object. Default 128. - * @param textures Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. - * @param textureData Optional additional texture data. - */ - shader(key: string | Phaser.Display.BaseShader, x?: number, y?: number, width?: number, height?: number, textures?: string[], textureData?: object): Phaser.GameObjects.Shader; - - /** - * Creates a new Arc Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Arc Game Object has been built into Phaser. - * - * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an arc shape. You can control the start and end angles of the arc, - * as well as if the angles are winding clockwise or anti-clockwise. With the default settings - * it renders as a complete circle. By changing the angles you can create other arc shapes, - * such as half-circles. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param radius The radius of the arc. Default 128. - * @param startAngle The start angle of the arc, in degrees. Default 0. - * @param endAngle The end angle of the arc, in degrees. Default 360. - * @param anticlockwise The winding order of the start and end angles. Default false. - * @param fillColor The color the arc will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - arc(x?: number, y?: number, radius?: number, startAngle?: integer, endAngle?: integer, anticlockwise?: boolean, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Arc; - - /** - * Creates a new Circle Shape Game Object and adds it to the Scene. - * - * A Circle is an Arc with no defined start and end angle, making it render as a complete circle. - * - * Note: This method will only be available if the Arc Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param radius The radius of the circle. Default 128. - * @param fillColor The color the circle will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the circle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - circle(x?: number, y?: number, radius?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Arc; - - /** - * Creates a new Curve Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Curve Game Object has been built into Phaser. - * - * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to - * the Curve Shape in the constructor. - * - * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param curve The Curve object to use to create the Shape. - * @param fillColor The color the curve will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - curve(x?: number, y?: number, curve?: Phaser.Curves.Curve, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Curve; - - /** - * Creates a new Ellipse Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Ellipse Game Object has been built into Phaser. - * - * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. - * If the width and height match it will render as a circle. If the width is less than the height, - * it will look more like an egg shape. - * - * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. - * @param height The height of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. - * @param fillColor The color the ellipse will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - ellipse(x?: number, y?: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Ellipse; - - /** - * Creates a new Grid Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Grid Game Object has been built into Phaser. - * - * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * A Grid Shape allows you to display a grid in your game, where you can control the size of the - * grid as well as the width and height of the grid cells. You can set a fill color for each grid - * cell as well as an alternate fill color. When the alternate fill color is set then the grid - * cells will alternate the fill colors as they render, creating a chess-board effect. You can - * also optionally have an outline fill color. If set, this draws lines between the grid cells - * in the given color. If you specify an outline color with an alpha of zero, then it will draw - * the cells spaced out, but without the lines between them. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the grid. Default 128. - * @param height The height of the grid. Default 128. - * @param cellWidth The width of one cell in the grid. Default 32. - * @param cellHeight The height of one cell in the grid. Default 32. - * @param fillColor The color the grid cells will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * @param outlineFillColor The color of the lines between the grid cells. - * @param outlineFillAlpha The alpha of the lines between the grid cells. - */ - grid(x?: number, y?: number, width?: number, height?: number, cellWidth?: number, cellHeight?: number, fillColor?: number, fillAlpha?: number, outlineFillColor?: number, outlineFillAlpha?: number): Phaser.GameObjects.Grid; - - /** - * Creates a new IsoBox Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the IsoBox Game Object has been built into Phaser. - * - * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set - * the color of the top, left and right faces of the rectangle respectively. You can also choose - * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting - * the `projection` property. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param size The width of the iso box in pixels. The left and right faces will be exactly half this value. Default 48. - * @param height The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. Default 32. - * @param fillTop The fill color of the top face of the iso box. Default 0xeeeeee. - * @param fillLeft The fill color of the left face of the iso box. Default 0x999999. - * @param fillRight The fill color of the right face of the iso box. Default 0xcccccc. - */ - isobox(x?: number, y?: number, size?: number, height?: number, fillTop?: number, fillLeft?: number, fillRight?: number): Phaser.GameObjects.IsoBox; - - /** - * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser. - * - * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different - * fill color. You can set the color of the top, left and right faces of the triangle respectively - * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting - * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside - * down or not. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param size The width of the iso triangle in pixels. The left and right faces will be exactly half this value. Default 48. - * @param height The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. Default 32. - * @param reversed Is the iso triangle upside down? Default false. - * @param fillTop The fill color of the top face of the iso triangle. Default 0xeeeeee. - * @param fillLeft The fill color of the left face of the iso triangle. Default 0x999999. - * @param fillRight The fill color of the right face of the iso triangle. Default 0xcccccc. - */ - isotriangle(x?: number, y?: number, size?: number, height?: number, reversed?: boolean, fillTop?: number, fillLeft?: number, fillRight?: number): Phaser.GameObjects.IsoTriangle; - - /** - * Creates a new Line Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Line Game Object has been built into Phaser. - * - * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only stroke colors and cannot be filled. - * - * A Line Shape allows you to draw a line between two points in your game. You can control the - * stroke color and thickness of the line. In WebGL only you can also specify a different - * thickness for the start and end of the line, allowing you to render lines that taper-off. - * - * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param x1 The horizontal position of the start of the line. Default 0. - * @param y1 The vertical position of the start of the line. Default 0. - * @param x2 The horizontal position of the end of the line. Default 128. - * @param y2 The vertical position of the end of the line. Default 0. - * @param strokeColor The color the line will be drawn in, i.e. 0xff0000 for red. - * @param strokeAlpha The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. - */ - line(x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, strokeColor?: number, strokeAlpha?: number): Phaser.GameObjects.Line; - - /** - * Creates a new Polygon Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Polygon Game Object has been built into Phaser. - * - * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Polygon Shape is created by providing a list of points, which are then used to create an - * internal Polygon geometry object. The points can be set from a variety of formats: - * - * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` - * - An array of objects with public x/y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - * - * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending - * on the coordinates of the points provided, the final shape may be rendered offset from its origin. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param points The points that make up the polygon. - * @param fillColor The color the polygon will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - polygon(x?: number, y?: number, points?: any, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Polygon; - - /** - * Creates a new Rectangle Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Rectangle Game Object has been built into Phaser. - * - * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * You can change the size of the rectangle by changing the `width` and `height` properties. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the rectangle. Default 128. - * @param height The height of the rectangle. Default 128. - * @param fillColor The color the rectangle will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - rectangle(x?: number, y?: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Rectangle; - - /** - * Creates a new Star Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Star Game Object has been built into Phaser. - * - * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * As the name implies, the Star shape will display a star in your game. You can control several - * aspects of it including the number of points that constitute the star. The default is 5. If - * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky - * star shape. - * - * You can also control the inner and outer radius, which is how 'long' each point of the star is. - * Modify these values to create more interesting shapes. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param points The number of points on the star. Default 5. - * @param innerRadius The inner radius of the star. Default 32. - * @param outerRadius The outer radius of the star. Default 64. - * @param fillColor The color the star will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - star(x?: number, y?: number, points?: number, innerRadius?: number, outerRadius?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Star; - - /** - * Creates a new Triangle Shape Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Triangle Game Object has been built into Phaser. - * - * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the - * position of each point of these lines. The triangle is always closed and cannot have an open - * face. If you require that, consider using a Polygon instead. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param x1 The horizontal position of the first point in the triangle. Default 0. - * @param y1 The vertical position of the first point in the triangle. Default 128. - * @param x2 The horizontal position of the second point in the triangle. Default 64. - * @param y2 The vertical position of the second point in the triangle. Default 0. - * @param x3 The horizontal position of the third point in the triangle. Default 128. - * @param y3 The vertical position of the third point in the triangle. Default 128. - * @param fillColor The color the triangle will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - triangle(x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Triangle; - - /** - * Creates a new Sprite Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Sprite Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - sprite(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Sprite; - - /** - * Creates a new Text Game Object and adds it to the Scene. - * - * 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. - * - * You can only display fonts that are currently loaded and available to the browser: therefore fonts must - * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, - * or have the fonts ready 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. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param text The text this Text object will display. - * @param style The Text style configuration object. - */ - text(x: number, y: number, text: string | string[], style?: object): Phaser.GameObjects.Text; - - /** - * Creates a new TileSprite Game Object and adds it to the Scene. - * - * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param width The width of the Game Object. If zero it will use the size of the texture frame. - * @param height The height of the Game Object. If zero it will use the size of the texture frame. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - tileSprite(x: number, y: number, width: integer, height: integer, texture: string, frame?: string | integer): Phaser.GameObjects.TileSprite; - - /** - * Creates a new Image Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Image Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - video(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Image; - - /** - * Creates a new Zone Game Object and adds it to the Scene. - * - * Note: This method will only be available if the Zone Game Object has been built into Phaser. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param width The width of the Game Object. - * @param height The height of the Game Object. - */ - zone(x: number, y: number, width: number, height: number): Phaser.GameObjects.Zone; - - /** - * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. - * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing - * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map - * data. For an empty map, you should specify tileWidth, tileHeight, width & height. - * @param key The key in the Phaser cache that corresponds to the loaded tilemap data. - * @param tileWidth The width of a tile in pixels. Pass in `null` to leave as the - * default. Default 32. - * @param tileHeight The height of a tile in pixels. Pass in `null` to leave as the - * default. Default 32. - * @param width The width of the map in tiles. Pass in `null` to leave as the - * default. Default 10. - * @param height The height of the map in tiles. Pass in `null` to leave as the - * default. Default 10. - * @param data Instead of loading from the cache, you can also load directly from - * a 2D array of tile indexes. Pass in `null` for no data. - * @param 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've 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. Default false. - */ - tilemap(key?: string, tileWidth?: integer, tileHeight?: integer, width?: integer, height?: integer, data?: integer[][], insertNull?: boolean): Phaser.Tilemaps.Tilemap; - - /** - * Creates a new Tween object. - * - * Note: This method will only be available if Tweens have been built into Phaser. - * @param config The Tween configuration. - */ - tween(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; - - } - - /** - * 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. - * - * 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 implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible, Phaser.GameObjects.Components.ScrollFactor { - /** - * - * @param scene The Scene to which this Graphics object belongs. - * @param options Options that set the position and default style of this Graphics object. - */ - constructor(scene: Phaser.Scene, options?: Phaser.Types.GameObjects.Graphics.Options); - - /** - * The horizontal display origin of the Graphics. - */ - displayOriginX: number; - - /** - * The vertical display origin of the Graphics. - */ - displayOriginY: number; - - /** - * The array of commands used to render the Graphics. - */ - commandBuffer: any[]; - - /** - * The default fill color for shapes rendered by this Graphics object. - */ - defaultFillColor: number; - - /** - * The default fill alpha for shapes rendered by this Graphics object. - */ - defaultFillAlpha: number; - - /** - * The default stroke width for shapes rendered by this Graphics object. - */ - defaultStrokeWidth: number; - - /** - * The default stroke color for shapes rendered by this Graphics object. - */ - defaultStrokeColor: number; - - /** - * The default stroke alpha for shapes rendered by this Graphics object. - */ - defaultStrokeAlpha: number; - - /** - * Set the default style settings for this Graphics object. - * @param options The styles to set as defaults. - */ - setDefaultStyles(options: Phaser.Types.GameObjects.Graphics.Styles): Phaser.GameObjects.Graphics; - - /** - * Set the current line style. - * @param lineWidth The stroke width. - * @param color The stroke color. - * @param alpha The stroke alpha. Default 1. - */ - lineStyle(lineWidth: number, color: number, alpha?: number): Phaser.GameObjects.Graphics; - - /** - * Set the current fill style. - * @param color The fill color. - * @param alpha The fill alpha. Default 1. - */ - fillStyle(color: number, alpha?: number): Phaser.GameObjects.Graphics; - - /** - * Sets a gradient fill style. This is a WebGL only feature. - * - * The gradient color values represent the 4 corners of an untransformed rectangle. - * The gradient is used to color all filled shapes and paths drawn after calling this method. - * If you wish to turn a gradient off, call `fillStyle` and provide a new single fill color. - * - * When filling a triangle only the first 3 color values provided are used for the 3 points of a triangle. - * - * This feature is best used only on rectangles and triangles. All other shapes will give strange results. - * - * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used - * will be filled with a gradient on its own. There is no ability to gradient fill a shape or path as a single - * entity at this time. - * @param topLeft The tint being applied to the top-left of the Game Object. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - * @param alpha The fill alpha. Default 1. - */ - fillGradientStyle(topLeft: integer, topRight: integer, bottomLeft: integer, bottomRight: integer, alpha?: number): Phaser.GameObjects.Graphics; - - /** - * Sets a gradient line style. This is a WebGL only feature. - * - * The gradient color values represent the 4 corners of an untransformed rectangle. - * The gradient is used to color all stroked shapes and paths drawn after calling this method. - * If you wish to turn a gradient off, call `lineStyle` and provide a new single line color. - * - * This feature is best used only on single lines. All other shapes will give strange results. - * - * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used - * will be filled with a gradient on its own. There is no ability to gradient stroke a shape or path as a single - * entity at this time. - * @param lineWidth The stroke width. - * @param topLeft The tint being applied to the top-left of the Game Object. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - * @param alpha The fill alpha. Default 1. - */ - lineGradientStyle(lineWidth: number, topLeft: integer, topRight: integer, bottomLeft: integer, bottomRight: integer, alpha?: number): Phaser.GameObjects.Graphics; - - /** - * Sets the texture frame this Graphics Object will use when drawing all shapes defined after calling this. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * Once set, all shapes will use this texture. Call this method with no arguments to clear it. - * - * The textures are not tiled. They are stretched to the dimensions of the shapes being rendered. For this reason, - * it works best with seamless / tileable textures. - * - * The mode argument controls how the textures are combined with the fill colors. The default value (0) will - * multiply the texture by the fill color. A value of 1 will use just the fill color, but the alpha data from the texture, - * and a value of 2 will use just the texture and no fill color at all. - * @param key The key of the texture to be used, as stored in the Texture Manager. Leave blank to clear a previously set texture. - * @param frame The name or index of the frame within the Texture. - * @param mode The texture tint mode. 0 is multiply, 1 is alpha only and 2 is texture only. Default 0. - */ - setTexture(key?: string, frame?: string | integer, mode?: number): this; - - /** - * Start a new shape path. - */ - beginPath(): Phaser.GameObjects.Graphics; - - /** - * Close the current path. - */ - closePath(): Phaser.GameObjects.Graphics; - - /** - * Fill the current path. - */ - fillPath(): Phaser.GameObjects.Graphics; - - /** - * Fill the current path. - * - * This is an alias for `Graphics.fillPath` and does the same thing. - * It was added to match the CanvasRenderingContext 2D API. - */ - fill(): Phaser.GameObjects.Graphics; - - /** - * Stroke the current path. - */ - strokePath(): Phaser.GameObjects.Graphics; - - /** - * Stroke the current path. - * - * This is an alias for `Graphics.strokePath` and does the same thing. - * It was added to match the CanvasRenderingContext 2D API. - */ - stroke(): Phaser.GameObjects.Graphics; - - /** - * Fill the given circle. - * @param circle The circle to fill. - */ - fillCircleShape(circle: Phaser.Geom.Circle): Phaser.GameObjects.Graphics; - - /** - * Stroke the given circle. - * @param circle The circle to stroke. - */ - strokeCircleShape(circle: Phaser.Geom.Circle): Phaser.GameObjects.Graphics; - - /** - * Fill a circle with the given position and radius. - * @param x The x coordinate of the center of the circle. - * @param y The y coordinate of the center of the circle. - * @param radius The radius of the circle. - */ - fillCircle(x: number, y: number, radius: number): Phaser.GameObjects.Graphics; - - /** - * Stroke a circle with the given position and radius. - * @param x The x coordinate of the center of the circle. - * @param y The y coordinate of the center of the circle. - * @param radius The radius of the circle. - */ - strokeCircle(x: number, y: number, radius: number): Phaser.GameObjects.Graphics; - - /** - * Fill the given rectangle. - * @param rect The rectangle to fill. - */ - fillRectShape(rect: Phaser.Geom.Rectangle): Phaser.GameObjects.Graphics; - - /** - * Stroke the given rectangle. - * @param rect The rectangle to stroke. - */ - strokeRectShape(rect: Phaser.Geom.Rectangle): Phaser.GameObjects.Graphics; - - /** - * Fill a rectangle with the given position and size. - * @param x The x coordinate of the top-left of the rectangle. - * @param y The y coordinate of the top-left of the rectangle. - * @param width The width of the rectangle. - * @param height The height of the rectangle. - */ - fillRect(x: number, y: number, width: number, height: number): Phaser.GameObjects.Graphics; - - /** - * Stroke a rectangle with the given position and size. - * @param x The x coordinate of the top-left of the rectangle. - * @param y The y coordinate of the top-left of the rectangle. - * @param width The width of the rectangle. - * @param height The height of the rectangle. - */ - strokeRect(x: number, y: number, width: number, height: number): Phaser.GameObjects.Graphics; - - /** - * Fill a rounded rectangle with the given position, size and radius. - * @param x The x coordinate of the top-left of the rectangle. - * @param y The y coordinate of the top-left of the rectangle. - * @param width The width of the rectangle. - * @param height The height of the rectangle. - * @param radius The corner radius; It can also be an object to specify different radii for corners. Default 20. - */ - fillRoundedRect(x: number, y: number, width: number, height: number, radius?: Phaser.Types.GameObjects.Graphics.RoundedRectRadius | number): Phaser.GameObjects.Graphics; - - /** - * Stroke a rounded rectangle with the given position, size and radius. - * @param x The x coordinate of the top-left of the rectangle. - * @param y The y coordinate of the top-left of the rectangle. - * @param width The width of the rectangle. - * @param height The height of the rectangle. - * @param radius The corner radius; It can also be an object to specify different radii for corners. Default 20. - */ - strokeRoundedRect(x: number, y: number, width: number, height: number, radius?: Phaser.Types.GameObjects.Graphics.RoundedRectRadius | number): Phaser.GameObjects.Graphics; - - /** - * Fill the given point. - * - * Draws a square at the given position, 1 pixel in size by default. - * @param point The point to fill. - * @param size The size of the square to draw. Default 1. - */ - fillPointShape(point: Phaser.Geom.Point | Phaser.Math.Vector2 | object, size?: number): Phaser.GameObjects.Graphics; - - /** - * Fill a point at the given position. - * - * Draws a square at the given position, 1 pixel in size by default. - * @param x The x coordinate of the point. - * @param y The y coordinate of the point. - * @param size The size of the square to draw. Default 1. - */ - fillPoint(x: number, y: number, size?: number): Phaser.GameObjects.Graphics; - - /** - * Fill the given triangle. - * @param triangle The triangle to fill. - */ - fillTriangleShape(triangle: Phaser.Geom.Triangle): Phaser.GameObjects.Graphics; - - /** - * Stroke the given triangle. - * @param triangle The triangle to stroke. - */ - strokeTriangleShape(triangle: Phaser.Geom.Triangle): Phaser.GameObjects.Graphics; - - /** - * Fill a triangle with the given points. - * @param x0 The x coordinate of the first point. - * @param y0 The y coordinate of the first point. - * @param x1 The x coordinate of the second point. - * @param y1 The y coordinate of the second point. - * @param x2 The x coordinate of the third point. - * @param y2 The y coordinate of the third point. - */ - fillTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): Phaser.GameObjects.Graphics; - - /** - * Stroke a triangle with the given points. - * @param x0 The x coordinate of the first point. - * @param y0 The y coordinate of the first point. - * @param x1 The x coordinate of the second point. - * @param y1 The y coordinate of the second point. - * @param x2 The x coordinate of the third point. - * @param y2 The y coordinate of the third point. - */ - strokeTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): Phaser.GameObjects.Graphics; - - /** - * Draw the given line. - * @param line The line to stroke. - */ - strokeLineShape(line: Phaser.Geom.Line): Phaser.GameObjects.Graphics; - - /** - * Draw a line between the given points. - * @param x1 The x coordinate of the start point of the line. - * @param y1 The y coordinate of the start point of the line. - * @param x2 The x coordinate of the end point of the line. - * @param y2 The y coordinate of the end point of the line. - */ - lineBetween(x1: number, y1: number, x2: number, y2: number): Phaser.GameObjects.Graphics; - - /** - * Draw a line from the current drawing position to the given position. - * - * Moves the current drawing position to the given position. - * @param x The x coordinate to draw the line to. - * @param y The y coordinate to draw the line to. - */ - lineTo(x: number, y: number): Phaser.GameObjects.Graphics; - - /** - * Move the current drawing position to the given position. - * @param x The x coordinate to move to. - * @param y The y coordinate to move to. - */ - moveTo(x: number, y: number): Phaser.GameObjects.Graphics; - - /** - * Stroke the shape represented by the given array of points. - * - * Pass `closeShape` to automatically close the shape by joining the last to the first point. - * - * Pass `closePath` to automatically close the path before it is stroked. - * @param points The points to stroke. - * @param closeShape When `true`, the shape is closed by joining the last point to the first point. Default false. - * @param closePath When `true`, the path is closed before being stroked. Default false. - * @param endIndex The index of `points` to stop drawing at. Defaults to `points.length`. - */ - strokePoints(points: any[] | Phaser.Geom.Point[], closeShape?: boolean, closePath?: boolean, endIndex?: integer): Phaser.GameObjects.Graphics; - - /** - * Fill the shape represented by the given array of points. - * - * Pass `closeShape` to automatically close the shape by joining the last to the first point. - * - * Pass `closePath` to automatically close the path before it is filled. - * @param points The points to fill. - * @param closeShape When `true`, the shape is closed by joining the last point to the first point. Default false. - * @param closePath When `true`, the path is closed before being stroked. Default false. - * @param endIndex The index of `points` to stop at. Defaults to `points.length`. - */ - fillPoints(points: any[] | Phaser.Geom.Point[], closeShape?: boolean, closePath?: boolean, endIndex?: integer): Phaser.GameObjects.Graphics; - - /** - * Stroke the given ellipse. - * @param ellipse The ellipse to stroke. - * @param smoothness The number of points to draw the ellipse with. Default 32. - */ - strokeEllipseShape(ellipse: Phaser.Geom.Ellipse, smoothness?: integer): Phaser.GameObjects.Graphics; - - /** - * Stroke an ellipse with the given position and size. - * @param x The x coordinate of the center of the ellipse. - * @param y The y coordinate of the center of the ellipse. - * @param width The width of the ellipse. - * @param height The height of the ellipse. - * @param smoothness The number of points to draw the ellipse with. Default 32. - */ - strokeEllipse(x: number, y: number, width: number, height: number, smoothness?: integer): Phaser.GameObjects.Graphics; - - /** - * Fill the given ellipse. - * @param ellipse The ellipse to fill. - * @param smoothness The number of points to draw the ellipse with. Default 32. - */ - fillEllipseShape(ellipse: Phaser.Geom.Ellipse, smoothness?: integer): Phaser.GameObjects.Graphics; - - /** - * Fill an ellipse with the given position and size. - * @param x The x coordinate of the center of the ellipse. - * @param y The y coordinate of the center of the ellipse. - * @param width The width of the ellipse. - * @param height The height of the ellipse. - * @param smoothness The number of points to draw the ellipse with. Default 32. - */ - fillEllipse(x: number, y: number, width: number, height: number, smoothness?: integer): Phaser.GameObjects.Graphics; - - /** - * Draw an arc. - * - * This method can be used to create circles, or parts of circles. - * - * Make sure you call `beginPath` before starting the arc unless you wish for the arc to automatically - * close when filled or stroked. - * - * Use the optional `overshoot` argument increase the number of iterations that take place when - * the arc is rendered in WebGL. This is useful if you're drawing an arc with an especially thick line, - * as it will allow the arc to fully join-up. Try small values at first, i.e. 0.01. - * - * Call {@link Phaser.GameObjects.Graphics#fillPath} or {@link Phaser.GameObjects.Graphics#strokePath} after calling - * this method to draw the arc. - * @param x The x coordinate of the center of the circle. - * @param y The y coordinate of the center of the circle. - * @param radius The radius of the circle. - * @param startAngle The starting angle, in radians. - * @param endAngle The ending angle, in radians. - * @param anticlockwise Whether the drawing should be anticlockwise or clockwise. Default false. - * @param overshoot This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. Default 0. - */ - arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean, overshoot?: number): Phaser.GameObjects.Graphics; - - /** - * Creates a pie-chart slice shape centered at `x`, `y` with the given radius. - * You must define the start and end angle of the slice. - * - * Setting the `anticlockwise` argument to `true` creates a shape similar to Pacman. - * Setting it to `false` creates a shape like a slice of pie. - * - * This method will begin a new path and close the path at the end of it. - * To display the actual slice you need to call either `strokePath` or `fillPath` after it. - * @param x The horizontal center of the slice. - * @param y The vertical center of the slice. - * @param radius The radius of the slice. - * @param startAngle The start angle of the slice, given in radians. - * @param endAngle The end angle of the slice, given in radians. - * @param anticlockwise Whether the drawing should be anticlockwise or clockwise. Default false. - * @param overshoot This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Default 0. - */ - slice(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean, overshoot?: number): Phaser.GameObjects.Graphics; - - /** - * Saves the state of the Graphics by pushing the current state onto a stack. - * - * The most recently saved state can then be restored with {@link Phaser.GameObjects.Graphics#restore}. - */ - save(): Phaser.GameObjects.Graphics; - - /** - * Restores the most recently saved state of the Graphics by popping from the state stack. - * - * Use {@link Phaser.GameObjects.Graphics#save} to save the current state, and call this afterwards to restore that state. - * - * If there is no saved state, this command does nothing. - */ - restore(): Phaser.GameObjects.Graphics; - - /** - * Inserts a translation command into this Graphics objects command buffer. - * - * All objects drawn _after_ calling this method will be translated - * by the given amount. - * - * This does not change the position of the Graphics object itself, - * only of the objects drawn by it after calling this method. - * @param x The horizontal translation to apply. - * @param y The vertical translation to apply. - */ - translateCanvas(x: number, y: number): Phaser.GameObjects.Graphics; - - /** - * Inserts a scale command into this Graphics objects command buffer. - * - * All objects drawn _after_ calling this method will be scaled - * by the given amount. - * - * This does not change the scale of the Graphics object itself, - * only of the objects drawn by it after calling this method. - * @param x The horizontal scale to apply. - * @param y The vertical scale to apply. - */ - scaleCanvas(x: number, y: number): Phaser.GameObjects.Graphics; - - /** - * Inserts a rotation command into this Graphics objects command buffer. - * - * All objects drawn _after_ calling this method will be rotated - * by the given amount. - * - * This does not change the rotation of the Graphics object itself, - * only of the objects drawn by it after calling this method. - * @param radians The rotation angle, in radians. - */ - rotateCanvas(radians: number): Phaser.GameObjects.Graphics; - - /** - * Clear the command buffer and reset the fill style and line style to their defaults. - */ - clear(): Phaser.GameObjects.Graphics; - - /** - * Generate a texture from this Graphics object. - * - * If `key` is a string it'll generate a new texture using it and add it into the - * Texture Manager (assuming no key conflict happens). - * - * If `key` is a Canvas it will draw the texture to that canvas context. Note that it will NOT - * automatically upload it to the GPU in WebGL mode. - * @param key The key to store the texture with in the Texture Manager, or a Canvas to draw to. - * @param width The width of the graphics to generate. - * @param height The height of the graphics to generate. - */ - generateTexture(key: string | HTMLCanvasElement, width?: integer, height?: integer): Phaser.GameObjects.Graphics; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * A Camera used specifically by the Graphics system for rendering to textures. - */ - static TargetCamera: Phaser.Cameras.Scene2D.Camera; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - } - - /** - * A Group is a way for you to create, manipulate, or recycle similar Game Objects. - * - * Group membership is non-exclusive. A Game Object can belong to several groups, one group, or none. - * - * Groups themselves aren't displayable, and can't be positioned, rotated, scaled, or hidden. - */ - class Group { - /** - * - * @param scene The scene this group belongs to. - * @param children Game Objects to add to this group; or the `config` argument. - * @param config Settings for this group. If `key` is set, Phaser.GameObjects.Group#createMultiple is also called with these settings. - */ - constructor(scene: Phaser.Scene, children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig); - - /** - * This scene this group belongs to. - */ - scene: Phaser.Scene; - - /** - * Members of this group. - */ - children: Phaser.Structs.Set; - - /** - * A flag identifying this object as a group. - */ - isParent: boolean; - - /** - * A textual representation of this Game Object. - * Used internally by Phaser but is available for your own custom classes to populate. - */ - type: string; - - /** - * The class to create new group members from. - */ - classType: Function; - - /** - * The name of this group. - * Empty by default and never populated by Phaser, this is left for developers to use. - */ - name: string; - - /** - * Whether this group runs its {@link Phaser.GameObjects.Group#preUpdate} method - * (which may update any members). - */ - active: boolean; - - /** - * The maximum size of this group, if used as a pool. -1 is no limit. - */ - maxSize: integer; - - /** - * A default texture key to use when creating new group members. - * - * This is used in {@link Phaser.GameObjects.Group#create} - * but not in {@link Phaser.GameObjects.Group#createMultiple}. - */ - defaultKey: string; - - /** - * A default texture frame to use when creating new group members. - */ - defaultFrame: string | integer; - - /** - * Whether to call the update method of any members. - */ - runChildUpdate: boolean; - - /** - * A function to be called when adding or creating group members. - */ - createCallback: Phaser.Types.GameObjects.Group.GroupCallback; - - /** - * A function to be called when removing group members. - */ - removeCallback: Phaser.Types.GameObjects.Group.GroupCallback; - - /** - * A function to be called when creating several group members at once. - */ - createMultipleCallback: Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback; - - /** - * Creates a new Game Object and adds it to this group, unless the group {@link Phaser.GameObjects.Group#isFull is full}. - * - * Calls {@link Phaser.GameObjects.Group#createCallback}. - * @param x The horizontal position of the new Game Object in the world. Default 0. - * @param y The vertical position of the new Game Object in the world. Default 0. - * @param key The texture key of the new Game Object. Default defaultKey. - * @param frame The texture frame of the new Game Object. Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of the new Game Object. Default true. - * @param active The {@link Phaser.GameObjects.GameObject#active} state of the new Game Object. Default true. - */ - create(x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean, active?: boolean): any; - - /** - * Creates several Game Objects and adds them to this group. - * - * If the group becomes {@link Phaser.GameObjects.Group#isFull}, no further Game Objects are created. - * - * Calls {@link Phaser.GameObjects.Group#createMultipleCallback} and {@link Phaser.GameObjects.Group#createCallback}. - * @param config Creation settings. This can be a single configuration object or an array of such objects, which will be applied in turn. - */ - createMultiple(config: Phaser.Types.GameObjects.Group.GroupCreateConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig[]): any[]; - - /** - * A helper for {@link Phaser.GameObjects.Group#createMultiple}. - * @param options Creation settings. - */ - createFromConfig(options: Phaser.Types.GameObjects.Group.GroupCreateConfig): any[]; - - /** - * Updates any group members, if {@link Phaser.GameObjects.Group#runChildUpdate} is enabled. - * @param time The current timestamp. - * @param delta The delta time elapsed since the last frame. - */ - preUpdate(time: number, delta: number): void; - - /** - * Adds a Game Object to this group. - * - * Calls {@link Phaser.GameObjects.Group#createCallback}. - * @param child The Game Object to add. - * @param addToScene Also add the Game Object to the scene. Default false. - */ - add(child: Phaser.GameObjects.GameObject, addToScene?: boolean): Phaser.GameObjects.Group; - - /** - * Adds several Game Objects to this group. - * - * Calls {@link Phaser.GameObjects.Group#createCallback}. - * @param children The Game Objects to add. - * @param addToScene Also add the Game Objects to the scene. Default false. - */ - addMultiple(children: Phaser.GameObjects.GameObject[], addToScene?: boolean): Phaser.GameObjects.Group; - - /** - * Removes a member of this Group and optionally removes it from the Scene and / or destroys it. - * - * Calls {@link Phaser.GameObjects.Group#removeCallback}. - * @param child The Game Object to remove. - * @param removeFromScene Optionally remove the Group member from the Scene it belongs to. Default false. - * @param destroyChild Optionally call destroy on the removed Group member. Default false. - */ - remove(child: Phaser.GameObjects.GameObject, removeFromScene?: boolean, destroyChild?: boolean): Phaser.GameObjects.Group; - - /** - * Removes all members of this Group and optionally removes them from the Scene and / or destroys them. - * - * Does not call {@link Phaser.GameObjects.Group#removeCallback}. - * @param removeFromScene Optionally remove each Group member from the Scene. Default false. - * @param destroyChild Optionally call destroy on the removed Group members. Default false. - */ - clear(removeFromScene?: boolean, destroyChild?: boolean): Phaser.GameObjects.Group; - - /** - * Tests if a Game Object is a member of this group. - * @param child A Game Object. - */ - contains(child: Phaser.GameObjects.GameObject): boolean; - - /** - * All members of the group. - */ - getChildren(): Phaser.GameObjects.GameObject[]; - - /** - * The number of members of the group. - */ - getLength(): integer; - - /** - * Scans the Group, from top to bottom, for the first member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. - * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - getFirst(state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * Scans the Group, from top to bottom, for the nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param nth The nth matching Group member to search for. - * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. - * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - getFirstNth(nth: integer, state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * Scans the Group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. - * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - getLast(state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * Scans the Group for the last nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, - * assigns `x` and `y`, and returns the member. - * - * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param nth The nth matching Group member to search for. - * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. - * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - getLastNth(nth: integer, state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, - * assigns `x` and `y`, and returns the member. - * - * If no inactive member is found and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. - * The new Game Object will have its active state set to `true`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - get(x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `true`, - * assigns `x` and `y`, and returns the member. - * - * If no active member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - getFirstAlive(createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, - * assigns `x` and `y`, and returns the member. - * - * If no inactive member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. - * The new Game Object will have an active state set to `true`. - * Unless a new member is created, `key`, `frame`, and `visible` are ignored. - * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. - * @param x The horizontal position of the Game Object in the world. - * @param y The vertical position of the Game Object in the world. - * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. - * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. - * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. - */ - getFirstDead(createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; - - /** - * {@link Phaser.GameObjects.Components.Animation#play Plays} an animation for all members of this group. - * @param key The string-based key of the animation to play. - * @param startFrame Optionally start the animation playing from this frame index. Default 0. - */ - playAnimation(key: string, startFrame?: string): Phaser.GameObjects.Group; - - /** - * Whether this group's size at its {@link Phaser.GameObjects.Group#maxSize maximum}. - */ - isFull(): boolean; - - /** - * Counts the number of active (or inactive) group members. - * @param value Count active (true) or inactive (false) group members. Default true. - */ - countActive(value?: boolean): integer; - - /** - * Counts the number of in-use (active) group members. - */ - getTotalUsed(): integer; - - /** - * The difference of {@link Phaser.GameObjects.Group#maxSize} and the number of active group members. - * - * This represents the number of group members that could be created or reactivated before reaching the size limit. - */ - getTotalFree(): integer; - - /** - * Sets the property as defined in `key` of each group member to the given value. - * @param key The property to be updated. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - propertyValueSet(key: string, value: number, step?: number, index?: integer, direction?: integer): Phaser.GameObjects.Group; - - /** - * Adds the given value to the property as defined in `key` of each group member. - * @param key The property to be updated. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - propertyValueInc(key: string, value: number, step?: number, index?: integer, direction?: integer): Phaser.GameObjects.Group; - - /** - * Sets the x of each group member. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - setX(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the y of each group member. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - setY(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the x, y of each group member. - * @param x The amount to set the `x` property to. - * @param y The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. Default x. - * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. - */ - setXY(x: number, y?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; - - /** - * Adds the given value to the x of each group member. - * @param value The amount to be added to the `x` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - incX(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Adds the given value to the y of each group member. - * @param value The amount to be added to the `y` property. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - incY(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Adds the given value to the x, y of each group member. - * @param x The amount to be added to the `x` property. - * @param y The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. Default x. - * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. - */ - incXY(x: number, y?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; - - /** - * Iterate through the group members changing the position of each element to be that of the element that came before - * it in the array (or after it if direction = 1) - * - * The first group member position is set to x/y. - * @param x The x coordinate to place the first item in the array at. - * @param y The y coordinate to place the first item in the array at. - * @param direction The iteration direction. 0 = first to last and 1 = last to first. Default 0. - */ - shiftPosition(x: number, y: number, direction?: integer): Phaser.GameObjects.Group; - - /** - * Sets the angle of each group member. - * @param value The amount to set the angle to, in degrees. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - angle(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the rotation of each group member. - * @param value The amount to set the rotation to, in radians. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - rotate(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Rotates each group member around the given point by the given angle. - * @param point Any object with public `x` and `y` properties. - * @param angle The angle to rotate by, in radians. - */ - rotateAround(point: Phaser.Types.Math.Vector2Like, angle: number): Phaser.GameObjects.Group; - - /** - * Rotates each group member around the given point by the given angle and distance. - * @param point Any object with public `x` and `y` properties. - * @param angle The angle to rotate by, in radians. - * @param distance The distance from the point of rotation in pixels. - */ - rotateAroundDistance(point: Phaser.Types.Math.Vector2Like, angle: number, distance: number): Phaser.GameObjects.Group; - - /** - * Sets the alpha of each group member. - * @param value The amount to set the alpha to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - setAlpha(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the tint of each group member. - * @param topLeft The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. - * @param topRight The tint to be applied to top-right corner of item. - * @param bottomLeft The tint to be applied to the bottom-left corner of item. - * @param bottomRight The tint to be applied to the bottom-right corner of item. - */ - setTint(topLeft: number, topRight?: number, bottomLeft?: number, bottomRight?: number): Phaser.GameObjects.Group; - - /** - * Sets the originX, originY of each group member. - * @param originX The amount to set the `originX` property to. - * @param originY The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. - * @param stepX This is added to the `originX` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `originY` amount, multiplied by the iteration counter. Default 0. - */ - setOrigin(originX: number, originY?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; - - /** - * Sets the scaleX of each group member. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - scaleX(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the scaleY of each group member. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - scaleY(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the scaleX, scaleY of each group member. - * @param scaleX The amount to be added to the `scaleX` property. - * @param scaleY The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. - * @param stepX This is added to the `scaleX` amount, multiplied by the iteration counter. Default 0. - * @param stepY This is added to the `scaleY` amount, multiplied by the iteration counter. Default 0. - */ - scaleXY(scaleX: number, scaleY?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; - - /** - * Sets the depth of each group member. - * @param value The amount to set the property to. - * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. - */ - setDepth(value: number, step?: number): Phaser.GameObjects.Group; - - /** - * Sets the blendMode of each group member. - * @param value The amount to set the property to. - */ - setBlendMode(value: number): Phaser.GameObjects.Group; - - /** - * Passes all group members to the Input Manager to enable them for input with identical areas and callbacks. - * @param 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 hitAreaCallback A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. - */ - setHitArea(hitArea: any, hitAreaCallback: Phaser.Types.Input.HitAreaCallback): Phaser.GameObjects.Group; - - /** - * Shuffles the group members in place. - */ - shuffle(): Phaser.GameObjects.Group; - - /** - * Deactivates a member of this group. - * @param gameObject A member of this group. - */ - kill(gameObject: Phaser.GameObjects.GameObject): void; - - /** - * Deactivates and hides a member of this group. - * @param gameObject A member of this group. - */ - killAndHide(gameObject: Phaser.GameObjects.GameObject): void; - - /** - * Sets the visible of each group member. - * @param value The value to set the property to. - * @param index An optional offset to start searching from within the items array. Default 0. - * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. - */ - setVisible(value: boolean, index?: integer, direction?: integer): Phaser.GameObjects.Group; - - /** - * Toggles (flips) the visible state of each member of this group. - */ - toggleVisible(): Phaser.GameObjects.Group; - - /** - * Empties this group and removes it from the Scene. - * - * Does not call {@link Phaser.GameObjects.Group#removeCallback}. - * @param destroyChildren Also {@link Phaser.GameObjects.GameObject#destroy} each group member. Default false. - */ - destroy(destroyChildren?: boolean): void; - - } - - /** - * An Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - */ - class Image extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.TextureCrop, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A 2D point light. - * - * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`. - * - * Any Game Objects using the Light2D pipeline will then be affected by these Lights. - * - * They can also simply be used to represent a point light for your own purposes. - */ - class Light { - /** - * - * @param x The horizontal position of the light. - * @param y The vertical position of the light. - * @param radius The radius of the light. - * @param r The red color of the light. A value between 0 and 1. - * @param g The green color of the light. A value between 0 and 1. - * @param b The blue color of the light. A value between 0 and 1. - * @param intensity The intensity of the light. - */ - constructor(x: number, y: number, radius: number, r: number, g: number, b: number, intensity: number); - - /** - * The horizontal position of the light. - */ - x: number; - - /** - * The vertical position of the light. - */ - y: number; - - /** - * The radius of the light. - */ - radius: number; - - /** - * The red color of the light. A value between 0 and 1. - */ - r: number; - - /** - * The green color of the light. A value between 0 and 1. - */ - g: number; - - /** - * The blue color of the light. A value between 0 and 1. - */ - b: number; - - /** - * The intensity of the light. - */ - intensity: number; - - /** - * The horizontal scroll factor of the light. - */ - scrollFactorX: number; - - /** - * The vertical scroll factor of the light. - */ - scrollFactorY: number; - - /** - * Set the properties of the light. - * - * Sets both horizontal and vertical scroll factor to 1. Use {@link Phaser.GameObjects.Light#setScrollFactor} to set - * the scroll factor. - * @param x The horizontal position of the light. - * @param y The vertical position of the light. - * @param radius The radius of the light. - * @param r The red color. A value between 0 and 1. - * @param g The green color. A value between 0 and 1. - * @param b The blue color. A value between 0 and 1. - * @param intensity The intensity of the light. - */ - set(x: number, y: number, radius: number, r: number, g: number, b: number, intensity: number): Phaser.GameObjects.Light; - - /** - * Set the scroll factor of the light. - * @param x The horizontal scroll factor of the light. - * @param y The vertical scroll factor of the light. - */ - setScrollFactor(x: number, y: number): Phaser.GameObjects.Light; - - /** - * Set the color of the light from a single integer RGB value. - * @param rgb The integer RGB color of the light. - */ - setColor(rgb: number): Phaser.GameObjects.Light; - - /** - * Set the intensity of the light. - * @param intensity The intensity of the light. - */ - setIntensity(intensity: number): Phaser.GameObjects.Light; - - /** - * Set the position of the light. - * @param x The horizontal position of the light. - * @param y The vertical position of the light. - */ - setPosition(x: number, y: number): Phaser.GameObjects.Light; - - /** - * Set the radius of the light. - * @param radius The radius of the light. - */ - setRadius(radius: number): Phaser.GameObjects.Light; - - } - - /** - * Manages Lights for a Scene. - * - * Affects the rendering of Game Objects using the `Light2D` pipeline. - */ - class LightsManager { - /** - * The pool of Lights. - * - * Used to recycle removed Lights for a more efficient use of memory. - */ - lightPool: Phaser.GameObjects.Light[]; - - /** - * The Lights in the Scene. - */ - lights: Phaser.GameObjects.Light[]; - - /** - * Lights that have been culled from a Camera's viewport. - * - * Lights in this list will not be rendered. - */ - culledLights: Phaser.GameObjects.Light[]; - - /** - * The ambient color. - */ - ambientColor: Object; - - /** - * Whether the Lights Manager is enabled. - */ - active: boolean; - - /** - * The maximum number of lights that a single Camera and the lights shader can process. - * Change this via the `maxLights` property in your game config, as it cannot be changed at runtime. - */ - readonly maxLights: integer; - - /** - * Enable the Lights Manager. - */ - enable(): Phaser.GameObjects.LightsManager; - - /** - * Disable the Lights Manager. - */ - disable(): Phaser.GameObjects.LightsManager; - - /** - * Cull any Lights that aren't visible to the given Camera. - * - * Culling Lights improves performance by ensuring that only Lights within a Camera's viewport are rendered. - * @param camera The Camera to cull Lights for. - */ - cull(camera: Phaser.Cameras.Scene2D.Camera): Phaser.GameObjects.Light[]; - - /** - * Iterate over each Light with a callback. - * @param callback The callback that is called with each Light. - */ - forEachLight(callback: LightForEach): Phaser.GameObjects.LightsManager; - - /** - * Set the ambient light color. - * @param rgb The integer RGB color of the ambient light. - */ - setAmbientColor(rgb: number): Phaser.GameObjects.LightsManager; - - /** - * Returns the maximum number of Lights allowed to appear at once. - */ - getMaxVisibleLights(): integer; - - /** - * Get the number of Lights managed by this Lights Manager. - */ - getLightCount(): integer; - - /** - * Add a Light. - * @param x The horizontal position of the Light. Default 0. - * @param y The vertical position of the Light. Default 0. - * @param radius The radius of the Light. Default 100. - * @param rgb The integer RGB color of the light. Default 0xffffff. - * @param intensity The intensity of the Light. Default 1. - */ - addLight(x?: number, y?: number, radius?: number, rgb?: number, intensity?: number): Phaser.GameObjects.Light; - - /** - * Remove a Light. - * @param light The Light to remove. - */ - removeLight(light: Phaser.GameObjects.Light): Phaser.GameObjects.LightsManager; - - /** - * Shut down the Lights Manager. - * - * Recycles all active Lights into the Light pool, resets ambient light color and clears the lists of Lights and - * culled Lights. - */ - shutdown(): void; - - /** - * Destroy the Lights Manager. - * - * Cleans up all references by calling {@link Phaser.GameObjects.LightsManager#shutdown}. - */ - destroy(): void; - - } - - /** - * A Scene plugin that provides a {@link Phaser.GameObjects.LightsManager} for the Light2D pipeline. - * - * Available from within a Scene via `this.lights`. - * - * Add Lights using the {@link Phaser.GameObjects.LightsManager#addLight} method: - * - * ```javascript - * // Enable the Lights Manager because it is disabled by default - * this.lights.enable(); - * - * // Create a Light at [400, 300] with a radius of 200 - * this.lights.addLight(400, 300, 200); - * ``` - * - * For Game Objects to be affected by the Lights when rendered, you will need to set them to use the `Light2D` pipeline like so: - * - * ```javascript - * sprite.setPipeline('Light2D'); - * ``` - */ - class LightsPlugin extends Phaser.GameObjects.LightsManager { - /** - * - * @param scene The Scene that this Lights Plugin belongs to. - */ - constructor(scene: Phaser.Scene); - - /** - * A reference to the Scene that this Lights Plugin belongs to. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene's systems. - */ - systems: Phaser.Scenes.Systems; - - /** - * Boot the Lights Plugin. - */ - boot(): void; - - /** - * Destroy the Lights Plugin. - * - * Cleans up all references. - */ - destroy(): void; - - } - - /** - * A Mesh Game Object. - */ - class Mesh extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible, Phaser.GameObjects.Components.ScrollFactor { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param vertices An array containing the vertices data for this Mesh. - * @param uv An array containing the uv data for this Mesh. - * @param colors An array containing the color data for this Mesh. - * @param alphas An array containing the alpha data for this Mesh. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, vertices: number[], uv: number[], colors: number[], alphas: number[], texture: string, frame?: string | integer); - - /** - * An array containing the vertices data for this Mesh. - */ - vertices: Float32Array; - - /** - * An array containing the uv data for this Mesh. - */ - uv: Float32Array; - - /** - * An array containing the color data for this Mesh. - */ - colors: Uint32Array; - - /** - * An array containing the alpha data for this Mesh. - */ - alphas: Float32Array; - - /** - * Fill or additive mode used when blending the color values? - */ - tintFill: boolean; - - /** - * This method is left intentionally empty and does not do anything. - * It is retained to allow a Mesh or Quad to be added to a Container. - */ - setAlpha(): void; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - } - - namespace Particles { - /** - * A Particle Emitter property. - * - * Facilitates changing Particle properties as they are emitted and throughout their lifetime. - */ - class EmitterOp { - /** - * - * @param config Settings for the Particle Emitter that owns this property. - * @param key The name of the property. - * @param defaultValue The default value of the property. - * @param emitOnly Whether the property can only be modified when a Particle is emitted. Default false. - */ - constructor(config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig, key: string, defaultValue: number, emitOnly?: boolean); - - /** - * The name of this property. - */ - propertyKey: string; - - /** - * The value of this property. - */ - propertyValue: number; - - /** - * The default value of this property. - */ - defaultValue: number; - - /** - * The number of steps for stepped easing between {@link Phaser.GameObjects.Particles.EmitterOp#start} and - * {@link Phaser.GameObjects.Particles.EmitterOp#end} values, per emit. - */ - steps: number; - - /** - * The step counter for stepped easing, per emit. - */ - counter: number; - - /** - * The start value for this property to ease between. - */ - start: number; - - /** - * The end value for this property to ease between. - */ - end: number; - - /** - * The easing function to use for updating this property. - */ - ease: Function; - - /** - * Whether this property can only be modified when a Particle is emitted. - * - * Set to `true` to allow only {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} callbacks to be set and - * affect this property. - * - * Set to `false` to allow both {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and - * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks to be set and affect this property. - */ - emitOnly: boolean; - - /** - * The callback to run for Particles when they are emitted from the Particle Emitter. - */ - onEmit: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback; - - /** - * The callback to run for Particles when they are updated. - */ - onUpdate: Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback; - - /** - * Load the property from a Particle Emitter configuration object. - * - * Optionally accepts a new property key to use, replacing the current one. - * @param config Settings for the Particle Emitter that owns this property. - * @param newKey The new key to use for this property, if any. - */ - loadConfig(config?: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig, newKey?: string): void; - - /** - * Build a JSON representation of this Particle Emitter property. - */ - toJSON(): object; - - /** - * Change the current value of the property and update its callback methods. - * @param value The value of the property. - */ - onChange(value: number): Phaser.GameObjects.Particles.EmitterOp; - - /** - * Update the {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and - * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks based on the type of the current - * {@link Phaser.GameObjects.Particles.EmitterOp#propertyValue}. - */ - setMethods(): Phaser.GameObjects.Particles.EmitterOp; - - /** - * Check whether an object has the given property. - * @param object The object to check. - * @param key The key of the property to look for in the object. - */ - has(object: object, key: string): boolean; - - /** - * Check whether an object has both of the given properties. - * @param object The object to check. - * @param key1 The key of the first property to check the object for. - * @param key2 The key of the second property to check the object for. - */ - hasBoth(object: object, key1: string, key2: string): boolean; - - /** - * Check whether an object has at least one of the given properties. - * @param object The object to check. - * @param key1 The key of the first property to check the object for. - * @param key2 The key of the second property to check the object for. - */ - hasEither(object: object, key1: string, key2: string): boolean; - - /** - * The returned value sets what the property will be at the START of the particles life, on emit. - * @param particle The particle. - * @param key The name of the property. - * @param value The current value of the property. - */ - defaultEmit(particle: Phaser.GameObjects.Particles.Particle, key: string, value?: number): number; - - /** - * The returned value updates the property for the duration of the particles life. - * @param particle The particle. - * @param key The name of the property. - * @param t The T value (between 0 and 1) - * @param value The current value of the property. - */ - defaultUpdate(particle: Phaser.GameObjects.Particles.Particle, key: string, t: number, value: number): number; - - /** - * An `onEmit` callback that returns the current value of the property. - */ - staticValueEmit(): number; - - /** - * An `onUpdate` callback that returns the current value of the property. - */ - staticValueUpdate(): number; - - /** - * An `onEmit` callback that returns a random value from the current value array. - */ - randomStaticValueEmit(): number; - - /** - * An `onEmit` callback that returns a value between the {@link Phaser.GameObjects.Particles.EmitterOp#start} and - * {@link Phaser.GameObjects.Particles.EmitterOp#end} range. - * @param particle The particle. - * @param key The key of the property. - */ - randomRangedValueEmit(particle: Phaser.GameObjects.Particles.Particle, key: string): number; - - /** - * An `onEmit` callback that returns a stepped value between the - * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} - * range. - */ - steppedEmit(): number; - - /** - * An `onEmit` callback for an eased property. - * - * It prepares the particle for easing by {@link Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate}. - * @param particle The particle. - * @param key The name of the property. - */ - easedValueEmit(particle: Phaser.GameObjects.Particles.Particle, key: string): number; - - /** - * An `onUpdate` callback that returns an eased value between the - * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} - * range. - * @param particle The particle. - * @param key The name of the property. - * @param t The T value (between 0 and 1) - */ - easeValueUpdate(particle: Phaser.GameObjects.Particles.Particle, key: string, t: number): number; - - } - - /** - * The GravityWell action applies a force on the particle to draw it towards, or repel it from, a single point. - * - * The force applied is inversely proportional to the square of the distance from the particle to the point, in accordance with Newton's law of gravity. - * - * This simulates the effect of gravity over large distances (as between planets, for example). - */ - class GravityWell { - /** - * - * @param x The x coordinate of the Gravity Well, in world space. Default 0. - * @param y The y coordinate of the Gravity Well, in world space. Default 0. - * @param power The strength of the gravity force - larger numbers produce a stronger force. Default 0. - * @param epsilon The minimum distance for which the gravity force is calculated. Default 100. - * @param gravity The gravitational force of this Gravity Well. Default 50. - */ - constructor(x?: number | Phaser.Types.GameObjects.Particles.GravityWellConfig, y?: number, power?: number, epsilon?: number, gravity?: number); - - /** - * The x coordinate of the Gravity Well, in world space. - */ - x: number; - - /** - * The y coordinate of the Gravity Well, in world space. - */ - y: number; - - /** - * The active state of the Gravity Well. An inactive Gravity Well will not influence any particles. - */ - active: boolean; - - /** - * The strength of the gravity force - larger numbers produce a stronger force. - */ - power: number; - - /** - * The minimum distance for which the gravity force is calculated. - */ - epsilon: number; - - /** - * Takes a Particle and updates it based on the properties of this Gravity Well. - * @param particle The Particle to update. - * @param delta The delta time in ms. - * @param step The delta value divided by 1000. - */ - update(particle: Phaser.GameObjects.Particles.Particle, delta: number, step: number): void; - - } - - /** - * A Particle is a simple Game Object controlled by a Particle Emitter and Manager, and rendered by the Manager. - * It uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. - */ - class Particle { - /** - * - * @param emitter The Emitter to which this Particle belongs. - */ - constructor(emitter: Phaser.GameObjects.Particles.ParticleEmitter); - - /** - * The Emitter to which this Particle belongs. - * - * A Particle can only belong to a single Emitter and is created, updated and destroyed via it. - */ - emitter: Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * The texture frame used to render this Particle. - */ - frame: Phaser.Textures.Frame; - - /** - * The x coordinate of this Particle. - */ - x: number; - - /** - * The y coordinate of this Particle. - */ - y: number; - - /** - * The x velocity of this Particle. - */ - velocityX: number; - - /** - * The y velocity of this Particle. - */ - velocityY: number; - - /** - * The x acceleration of this Particle. - */ - accelerationX: number; - - /** - * The y acceleration of this Particle. - */ - accelerationY: number; - - /** - * The maximum horizontal velocity this Particle can travel at. - */ - maxVelocityX: number; - - /** - * The maximum vertical velocity this Particle can travel at. - */ - maxVelocityY: number; - - /** - * The bounciness, or restitution, of this Particle. - */ - bounce: number; - - /** - * The horizontal scale of this Particle. - */ - scaleX: number; - - /** - * The vertical scale of this Particle. - */ - scaleY: number; - - /** - * The alpha value of this Particle. - */ - alpha: number; - - /** - * The angle of this Particle in degrees. - */ - angle: number; - - /** - * The angle of this Particle in radians. - */ - rotation: number; - - /** - * The tint applied to this Particle. - */ - tint: integer; - - /** - * The lifespan of this Particle in ms. - */ - life: number; - - /** - * The current life of this Particle in ms. - */ - lifeCurrent: number; - - /** - * The delay applied to this Particle upon emission, in ms. - */ - delayCurrent: number; - - /** - * The normalized lifespan T value, where 0 is the start and 1 is the end. - */ - lifeT: number; - - /** - * The data used by the ease equation. - */ - data: object; - - /** - * Checks to see if this Particle is alive and updating. - */ - isAlive(): boolean; - - /** - * Resets the position of this particle back to zero. - */ - resetPosition(): void; - - /** - * Starts this Particle from the given coordinates. - * @param x The x coordinate to launch this Particle from. - * @param y The y coordinate to launch this Particle from. - */ - fire(x: number, y: number): void; - - /** - * An internal method that calculates the velocity of the Particle. - * @param emitter The Emitter that is updating this Particle. - * @param delta The delta time in ms. - * @param step The delta value divided by 1000. - * @param processors Particle processors (gravity wells). - */ - computeVelocity(emitter: Phaser.GameObjects.Particles.ParticleEmitter, delta: number, step: number, processors: any[]): void; - - /** - * Checks if this Particle is still within the bounds defined by the given Emitter. - * - * If not, and depending on the Emitter collision flags, the Particle may either stop or rebound. - * @param emitter The Emitter to check the bounds against. - */ - checkBounds(emitter: Phaser.GameObjects.Particles.ParticleEmitter): void; - - /** - * The main update method for this Particle. - * - * Updates its life values, computes the velocity and repositions the Particle. - * @param delta The delta time in ms. - * @param step The delta value divided by 1000. - * @param processors An optional array of update processors. - */ - update(delta: number, step: number, processors: any[]): boolean; - - } - - /** - * A particle emitter represents a single particle stream. - * It controls a pool of {@link Phaser.GameObjects.Particles.Particle Particles} and is controlled by a {@link Phaser.GameObjects.Particles.ParticleEmitterManager Particle Emitter Manager}. - */ - class ParticleEmitter implements Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Visible { - /** - * - * @param manager The Emitter Manager this Emitter belongs to. - * @param config Settings for this emitter. - */ - constructor(manager: Phaser.GameObjects.Particles.ParticleEmitterManager, config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig); - - /** - * The Emitter Manager this Emitter belongs to. - */ - manager: Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * The texture assigned to particles. - */ - texture: Phaser.Textures.Texture; - - /** - * The texture frames assigned to particles. - */ - frames: Phaser.Textures.Frame[]; - - /** - * The default texture frame assigned to particles. - */ - defaultFrame: Phaser.Textures.Frame; - - /** - * Names of simple configuration properties. - */ - configFastMap: object; - - /** - * Names of complex configuration properties. - */ - configOpMap: object; - - /** - * The name of this Particle Emitter. - * - * Empty by default and never populated by Phaser, this is left for developers to use. - */ - name: string; - - /** - * The Particle Class which will be emitted by this Emitter. - */ - particleClass: Phaser.GameObjects.Particles.Particle; - - /** - * The x-coordinate of the particle origin (where particles will be emitted). - */ - x: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The y-coordinate of the particle origin (where particles will be emitted). - */ - y: Phaser.GameObjects.Particles.EmitterOp; - - /** - * A radial emitter will emit particles in all directions between angle min and max, - * using {@link Phaser.GameObjects.Particles.ParticleEmitter#speed} as the value. If set to false then this acts as a point Emitter. - * A point emitter will emit particles only in the direction derived from the speedX and speedY values. - */ - radial: boolean; - - /** - * Horizontal acceleration applied to emitted particles, in pixels per second squared. - */ - gravityX: number; - - /** - * Vertical acceleration applied to emitted particles, in pixels per second squared. - */ - gravityY: number; - - /** - * Whether accelerationX and accelerationY are non-zero. Set automatically during configuration. - */ - acceleration: boolean; - - /** - * Horizontal acceleration applied to emitted particles, in pixels per second squared. - */ - accelerationX: Phaser.GameObjects.Particles.EmitterOp; - - /** - * Vertical acceleration applied to emitted particles, in pixels per second squared. - */ - accelerationY: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The maximum horizontal velocity of emitted particles, in pixels per second squared. - */ - maxVelocityX: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The maximum vertical velocity of emitted particles, in pixels per second squared. - */ - maxVelocityY: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The initial horizontal speed of emitted particles, in pixels per second. - */ - speedX: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The initial vertical speed of emitted particles, in pixels per second. - */ - speedY: Phaser.GameObjects.Particles.EmitterOp; - - /** - * Whether moveToX and moveToY are nonzero. Set automatically during configuration. - */ - moveTo: boolean; - - /** - * The x-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. - */ - moveToX: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The y-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. - */ - moveToY: Phaser.GameObjects.Particles.EmitterOp; - - /** - * Whether particles will rebound when they meet the emitter bounds. - */ - bounce: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The horizontal scale of emitted particles. - */ - scaleX: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The vertical scale of emitted particles. - */ - scaleY: Phaser.GameObjects.Particles.EmitterOp; - - /** - * Color tint applied to emitted particles. Any alpha component (0xAA000000) is ignored. - */ - tint: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The alpha (transparency) of emitted particles. - */ - alpha: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The lifespan of emitted particles, in ms. - */ - lifespan: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The angle of the initial velocity of emitted particles, in degrees. - */ - angle: Phaser.GameObjects.Particles.EmitterOp; - - /** - * The rotation of emitted particles, in degrees. - */ - rotate: Phaser.GameObjects.Particles.EmitterOp; - - /** - * A function to call when a particle is emitted. - */ - emitCallback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback; - - /** - * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. - */ - emitCallbackScope: any; - - /** - * A function to call when a particle dies. - */ - deathCallback: Phaser.Types.GameObjects.Particles.ParticleDeathCallback; - - /** - * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. - */ - deathCallbackScope: any; - - /** - * Set to hard limit the amount of particle objects this emitter is allowed to create. - * 0 means unlimited. - */ - maxParticles: integer; - - /** - * How many particles are emitted each time particles are emitted (one explosion or one flow cycle). - */ - quantity: Phaser.GameObjects.Particles.EmitterOp; - - /** - * How many ms to wait after emission before the particles start updating. - */ - delay: Phaser.GameObjects.Particles.EmitterOp; - - /** - * For a flow emitter, the time interval (>= 0) between particle flow cycles in ms. - * A value of 0 means there is one particle flow cycle for each logic update (the maximum flow frequency). This is the default setting. - * For an exploding emitter, this value will be -1. - * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} also puts the emitter in flow mode (frequency >= 0). - * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} also puts the emitter in explode mode (frequency = -1). - */ - frequency: number; - - /** - * Controls if the emitter is currently emitting a particle flow (when frequency >= 0). - * Already alive particles will continue to update until they expire. - * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#start} and {@link Phaser.GameObjects.Particles.ParticleEmitter#stop}. - */ - on: boolean; - - /** - * Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. - * Set to false to send them to the back. - */ - particleBringToTop: boolean; - - /** - * The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal. - */ - timeScale: number; - - /** - * An object describing a shape to emit particles from. - */ - emitZone: Phaser.GameObjects.Particles.Zones.EdgeZone | Phaser.GameObjects.Particles.Zones.RandomZone; - - /** - * An object describing a shape that deactivates particles when they interact with it. - */ - deathZone: Phaser.GameObjects.Particles.Zones.DeathZone; - - /** - * A rectangular boundary constraining particle movement. - */ - bounds: Phaser.Geom.Rectangle; - - /** - * Whether particles interact with the left edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - */ - collideLeft: boolean; - - /** - * Whether particles interact with the right edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - */ - collideRight: boolean; - - /** - * Whether particles interact with the top edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - */ - collideTop: boolean; - - /** - * Whether particles interact with the bottom edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. - */ - collideBottom: boolean; - - /** - * Whether this emitter updates itself and its particles. - * - * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#pause} - * and {@link Phaser.GameObjects.Particles.ParticleEmitter#resume}. - */ - active: boolean; - - /** - * Set this to false to hide any active particles. - */ - visible: boolean; - - /** - * The blend mode of this emitter's particles. - */ - blendMode: integer; - - /** - * A Game Object whose position is used as the particle origin. - */ - follow: Phaser.GameObjects.GameObject; - - /** - * The offset of the particle origin from the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target. - */ - followOffset: Phaser.Math.Vector2; - - /** - * Whether the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#visible} state will track - * the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target's visibility state. - */ - trackVisible: boolean; - - /** - * The current texture frame, as an index of {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. - */ - currentFrame: integer; - - /** - * Whether texture {@link Phaser.GameObjects.Particles.ParticleEmitter#frames} are selected at random. - */ - randomFrame: boolean; - - /** - * The number of consecutive particles that receive a single texture frame (per frame cycle). - */ - frameQuantity: integer; - - /** - * Merges configuration settings into the emitter's current settings. - * @param config Settings for this emitter. - */ - fromJSON(config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Creates a description of this emitter suitable for JSON serialization. - * @param output An object to copy output into. - */ - toJSON(output?: object): object; - - /** - * Continuously moves the particle origin to follow a Game Object's position. - * @param target The Game Object to follow. - * @param offsetX Horizontal offset of the particle origin from the Game Object. Default 0. - * @param offsetY Vertical offset of the particle origin from the Game Object. Default 0. - * @param trackVisible Whether the emitter's visible state will track the target's visible state. Default false. - */ - startFollow(target: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number, trackVisible?: boolean): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Stops following a Game Object. - */ - stopFollow(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Chooses a texture frame from {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. - */ - getFrame(): Phaser.Textures.Frame; - - /** - * Sets a pattern for assigning texture frames to emitted particles. - * @param frames One or more texture frames, or a configuration object. - * @param pickRandom Whether frames should be assigned at random from `frames`. Default true. - * @param quantity The number of consecutive particles that will receive each frame. Default 1. - */ - setFrame(frames: any[] | string | integer | Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig, pickRandom?: boolean, quantity?: integer): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle movement on or off. - * @param value Radial mode (true) or point mode (true). Default true. - */ - setRadial(value?: boolean): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the position of the emitter's particle origin. - * New particles will be emitted here. - * @param x The x-coordinate of the particle origin. - * @param y The y-coordinate of the particle origin. - */ - setPosition(x: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType, y: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets or modifies a rectangular boundary constraining the particles. - * - * To remove the boundary, set {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds} to null. - * @param x The x-coordinate of the left edge of the boundary, or an object representing a rectangle. - * @param y The y-coordinate of the top edge of the boundary. - * @param width The width of the boundary. - * @param height The height of the boundary. - */ - setBounds(x: number | Phaser.Types.GameObjects.Particles.ParticleEmitterBounds | Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt, y: number, width: number, height: number): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the initial horizontal speed of emitted particles. - * Changes the emitter to point mode. - * @param value The speed, in pixels per second. - */ - setSpeedX(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the initial vertical speed of emitted particles. - * Changes the emitter to point mode. - * @param value The speed, in pixels per second. - */ - setSpeedY(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the initial radial speed of emitted particles. - * Changes the emitter to radial mode. - * @param value The speed, in pixels per second. - */ - setSpeed(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the horizontal scale of emitted particles. - * @param value The scale, relative to 1. - */ - setScaleX(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the vertical scale of emitted particles. - * @param value The scale, relative to 1. - */ - setScaleY(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the scale of emitted particles. - * @param value The scale, relative to 1. - */ - setScale(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the horizontal gravity applied to emitted particles. - * @param value Acceleration due to gravity, in pixels per second squared. - */ - setGravityX(value: number): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the vertical gravity applied to emitted particles. - * @param value Acceleration due to gravity, in pixels per second squared. - */ - setGravityY(value: number): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the gravity applied to emitted particles. - * @param x Horizontal acceleration due to gravity, in pixels per second squared. - * @param y Vertical acceleration due to gravity, in pixels per second squared. - */ - setGravity(x: number, y: number): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the opacity of emitted particles. - * @param value A value between 0 (transparent) and 1 (opaque). - */ - setAlpha(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the color tint of emitted particles. - * @param value A value between 0 and 0xffffff. - */ - setTint(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. - * @param value The angle of the initial velocity of emitted particles. - */ - setEmitterAngle(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. - * @param value The angle of the initial velocity of emitted particles. - */ - setAngle(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the lifespan of newly emitted particles. - * @param value The particle lifespan, in ms. - */ - setLifespan(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the number of particles released at each flow cycle or explosion. - * @param quantity The number of particles to release at each flow cycle or explosion. - */ - setQuantity(quantity: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency} - * and {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. - * @param frequency The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. - * @param quantity The number of particles to release at each flow cycle or explosion. - */ - setFrequency(frequency: number, quantity?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#emitZone}. - * - * An {@link Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig EdgeZone} places particles on its edges. Its {@link Phaser.Types.GameObjects.Particles.EdgeZoneSource source} can be a Curve, Path, Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback getPoints} method. - * - * A {@link Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig RandomZone} places randomly within its interior. Its {@link RandomZoneSource source} can be a Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback getRandomPoint} method. - * @param zoneConfig An object describing the zone, or `undefined` to remove any current emit zone. - */ - setEmitZone(zoneConfig?: Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig | Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#deathZone}. - * @param zoneConfig An object describing the zone, or `undefined` to remove any current death zone. - */ - setDeathZone(zoneConfig?: Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Creates inactive particles and adds them to this emitter's pool. - * @param particleCount The number of particles to create. - */ - reserve(particleCount: integer): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Gets the number of active (in-use) particles in this emitter. - */ - getAliveParticleCount(): integer; - - /** - * Gets the number of inactive (available) particles in this emitter. - */ - getDeadParticleCount(): integer; - - /** - * Gets the total number of particles in this emitter. - */ - getParticleCount(): integer; - - /** - * Whether this emitter is at its limit (if set). - */ - atLimit(): boolean; - - /** - * Sets a function to call for each newly emitted particle. - * @param callback The function. - * @param context The calling context. - */ - onParticleEmit(callback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback, context?: any): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sets a function to call for each particle death. - * @param callback The function. - * @param context The function's calling context. - */ - onParticleDeath(callback: Phaser.Types.GameObjects.Particles.ParticleDeathCallback, context?: any): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Deactivates every particle in this emitter. - */ - killAll(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Calls a function for each active particle in this emitter. - * @param callback The function. - * @param context The function's calling context. - */ - forEachAlive(callback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback, context: any): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Calls a function for each inactive particle in this emitter. - * @param callback The function. - * @param context The function's calling context. - */ - forEachDead(callback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback, context: any): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on} the emitter and resets the flow counter. - * - * If this emitter is in flow mode (frequency >= 0; the default), the particle flow will start (or restart). - * - * If this emitter is in explode mode (frequency = -1), nothing will happen. - * Use {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} or {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} instead. - */ - start(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on off} the emitter. - */ - stop(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Deactivates} the emitter. - */ - pause(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Activates} the emitter. - */ - resume(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Removes the emitter from its manager and the scene. - */ - remove(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Sorts active particles with {@link Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback}. - */ - depthSort(): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Puts the emitter in flow mode (frequency >= 0) and starts (or restarts) a particle flow. - * - * To resume a flow at the current frequency and quantity, use {@link Phaser.GameObjects.Particles.ParticleEmitter#start} instead. - * @param frequency The time interval (>= 0) of each flow cycle, in ms. - * @param count The number of particles to emit at each flow cycle. Default 1. - */ - flow(frequency: number, count?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once. - * @param count The amount of Particles to emit. - * @param x The x coordinate to emit the Particles from. - * @param y The y coordinate to emit the Particles from. - */ - explode(count: integer, x: number, y: number): Phaser.GameObjects.Particles.Particle; - - /** - * Emits particles at a given position (or the emitter's current position). - * @param x The x coordinate to emit the Particles from. Default this.x. - * @param y The y coordinate to emit the Particles from. Default this.x. - * @param count The number of Particles to emit. Default this.quantity. - */ - emitParticleAt(x?: number, y?: number, count?: integer): Phaser.GameObjects.Particles.Particle; - - /** - * Emits particles at a given position (or the emitter's current position). - * @param count The number of Particles to emit. Default this.quantity. - * @param x The x coordinate to emit the Particles from. Default this.x. - * @param y The y coordinate to emit the Particles from. Default this.x. - */ - emitParticle(count?: integer, x?: number, y?: number): Phaser.GameObjects.Particles.Particle; - - /** - * Updates this emitter and its particles. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - preUpdate(time: integer, delta: number): void; - - /** - * Calculates the difference of two particles, for sorting them by depth. - * @param a The first particle. - * @param b The second particle. - */ - depthSortCallback(a: object, b: object): integer; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A Particle Emitter Manager creates and controls {@link Phaser.GameObjects.Particles.ParticleEmitter Particle Emitters} and {@link Phaser.GameObjects.Particles.GravityWell Gravity Wells}. - */ - class ParticleEmitterManager extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Emitter Manager belongs. - * @param texture The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Emitter Manager will use to render particles. - * @param emitters Configuration settings for one or more emitters to create. - */ - constructor(scene: Phaser.Scene, texture: string, frame?: string | integer, emitters?: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]); - - /** - * The time scale applied to all emitters and particles, affecting flow rate, lifespan, and movement. - * Values larger than 1 are faster than normal. - * This is multiplied with any timeScale set on each individual emitter. - */ - timeScale: number; - - /** - * The texture used to render this Emitter Manager's particles. - */ - texture: Phaser.Textures.Texture; - - /** - * The texture frame used to render this Emitter Manager's particles. - */ - frame: Phaser.Textures.Frame; - - /** - * Names of this Emitter Manager's texture frames. - */ - frameNames: string[]; - - /** - * A list of Emitters being managed by this Emitter Manager. - */ - emitters: Phaser.Structs.List; - - /** - * A list of Gravity Wells being managed by this Emitter Manager. - */ - wells: Phaser.Structs.List; - - /** - * Sets the texture and frame this Emitter Manager will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Sets the frame this Emitter Manager will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * @param frame The name or index of the frame within the Texture. - */ - setFrame(frame?: string | integer): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Assigns texture frames to an emitter. - * @param frames The texture frames. - * @param emitter The particle emitter to modify. - */ - setEmitterFrames(frames: Phaser.Textures.Frame | Phaser.Textures.Frame[], emitter: Phaser.GameObjects.Particles.ParticleEmitter): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Adds an existing Particle Emitter to this Emitter Manager. - * @param emitter The Particle Emitter to add to this Emitter Manager. - */ - addEmitter(emitter: Phaser.GameObjects.Particles.ParticleEmitter): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it. - * @param config Configuration settings for the Particle Emitter to create. - */ - createEmitter(config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Removes a Particle Emitter from this Emitter Manager, if the Emitter belongs to this Manager. - */ - removeEmitter(emitter: Phaser.GameObjects.Particles.ParticleEmitter): Phaser.GameObjects.Particles.ParticleEmitter; - - /** - * Adds an existing Gravity Well object to this Emitter Manager. - * @param well The Gravity Well to add to this Emitter Manager. - */ - addGravityWell(well: Phaser.GameObjects.Particles.GravityWell): Phaser.GameObjects.Particles.GravityWell; - - /** - * Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it. - * @param config Configuration settings for the Gravity Well to create. - */ - createGravityWell(config: Phaser.Types.GameObjects.Particles.GravityWellConfig): Phaser.GameObjects.Particles.GravityWell; - - /** - * Emits particles from each active emitter. - * @param count The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. - * @param x The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. - * @param y The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. - */ - emitParticle(count?: integer, x?: number, y?: number): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Emits particles from each active emitter. - * @param x The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. - * @param y The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. - * @param count The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. - */ - emitParticleAt(x?: number, y?: number, count?: integer): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Pauses this Emitter Manager. - * - * This has the effect of pausing all emitters, and all particles of those emitters, currently under its control. - * - * The particles will still render, but they will not have any of their logic updated. - */ - pause(): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Resumes this Emitter Manager, should it have been previously paused. - */ - resume(): Phaser.GameObjects.Particles.ParticleEmitterManager; - - /** - * Gets all active particle processors (gravity wells). - */ - getProcessors(): Phaser.GameObjects.Particles.GravityWell[]; - - /** - * Updates all active emitters. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - preUpdate(time: integer, delta: number): void; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - namespace Zones { - /** - * A Death Zone. - * - * A Death Zone is a special type of zone that will kill a Particle as soon as it either enters, or leaves, the zone. - * - * The zone consists of a `source` which could be a Geometric shape, such as a Rectangle or Ellipse, or your own - * object as long as it includes a `contains` method for which the Particles can be tested against. - */ - class DeathZone { - /** - * - * @param source An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. - * @param killOnEnter Should the Particle be killed when it enters the zone? `true` or leaves it? `false` - */ - constructor(source: Phaser.Types.GameObjects.Particles.DeathZoneSource, killOnEnter: boolean); - - /** - * An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. - * This could be a Geometry shape, such as `Phaser.Geom.Circle`, or your own custom object. - */ - source: Phaser.Types.GameObjects.Particles.DeathZoneSource; - - /** - * Set to `true` if the Particle should be killed if it enters this zone. - * Set to `false` to kill the Particle if it leaves this zone. - */ - killOnEnter: boolean; - - /** - * Checks if the given Particle will be killed or not by this zone. - * @param particle The Particle to be checked against this zone. - */ - willKill(particle: Phaser.GameObjects.Particles.Particle): boolean; - - } - - /** - * A zone that places particles on a shape's edges. - */ - class EdgeZone { - /** - * - * @param source An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. - * @param quantity The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. - * @param stepRate The distance between each particle. When set, `quantity` is implied and should be set to 0. - * @param yoyo Whether particles are placed from start to end and then end to start. Default false. - * @param seamless Whether one endpoint will be removed if it's identical to the other. Default true. - */ - constructor(source: Phaser.Types.GameObjects.Particles.EdgeZoneSource, quantity: integer, stepRate: number, yoyo?: boolean, seamless?: boolean); - - /** - * An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. - */ - source: Phaser.Types.GameObjects.Particles.EdgeZoneSource | Phaser.Types.GameObjects.Particles.RandomZoneSource; - - /** - * The points placed on the source edge. - */ - points: Phaser.Geom.Point[]; - - /** - * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. - */ - quantity: integer; - - /** - * The distance between each particle. When set, `quantity` is implied and should be set to 0. - */ - stepRate: number; - - /** - * Whether particles are placed from start to end and then end to start. - */ - yoyo: boolean; - - /** - * The counter used for iterating the EdgeZone's points. - */ - counter: number; - - /** - * Whether one endpoint will be removed if it's identical to the other. - */ - seamless: boolean; - - /** - * Update the {@link Phaser.GameObjects.Particles.Zones.EdgeZone#points} from the EdgeZone's - * {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. - * - * Also updates internal properties. - */ - updateSource(): Phaser.GameObjects.Particles.Zones.EdgeZone; - - /** - * Change the source of the EdgeZone. - * @param source An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. - */ - changeSource(source: Phaser.Types.GameObjects.Particles.EdgeZoneSource): Phaser.GameObjects.Particles.Zones.EdgeZone; - - /** - * Get the next point in the Zone and set its coordinates on the given Particle. - * @param particle The Particle. - */ - getPoint(particle: Phaser.GameObjects.Particles.Particle): void; - - } - - /** - * A zone that places particles randomly within a shape's area. - */ - class RandomZone { - /** - * - * @param source An object instance with a `getRandomPoint(point)` method. - */ - constructor(source: Phaser.Types.GameObjects.Particles.RandomZoneSource); - - /** - * An object instance with a `getRandomPoint(point)` method. - */ - source: Phaser.Types.GameObjects.Particles.RandomZoneSource; - - /** - * Get the next point in the Zone and set its coordinates on the given Particle. - * @param particle The Particle. - */ - getPoint(particle: Phaser.GameObjects.Particles.Particle): void; - - } - - } - - } - - /** - * A PathFollower Game Object. - * - * A PathFollower is a Sprite Game Object with some extra helpers to allow it to follow a Path automatically. - * - * Anything you can do with a standard Sprite can be done with this PathFollower, such as animate it, tint it, - * scale it and so on. - * - * PathFollowers are bound to a single Path at any one time and can traverse the length of the Path, from start - * to finish, forwards or backwards, or from any given point on the Path to its end. They can optionally rotate - * to face the direction of the path, be offset from the path coordinates or rotate independently of the Path. - */ - class PathFollower extends Phaser.GameObjects.Sprite implements Phaser.GameObjects.Components.PathFollower { - /** - * - * @param scene The Scene to which this PathFollower belongs. - * @param path The Path this PathFollower is following. It can only follow one Path at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, path: Phaser.Curves.Path, x: number, y: number, texture: string, frame?: string | integer); - - /** - * If the PathFollower is rotating to match the Path (@see Phaser.GameObjects.PathFollower#rotateToPath) - * this value is added to the rotation value. This allows you to rotate objects to a path but control - * the angle of the rotation as well. - */ - pathRotationOffset: number; - - /** - * An additional vector to add to the PathFollowers position, allowing you to offset it from the - * Path coordinates. - */ - pathOffset: Phaser.Math.Vector2; - - /** - * A Vector2 that stores the current point of the path the follower is on. - */ - pathVector: Phaser.Math.Vector2; - - /** - * The Tween used for following the Path. - */ - pathTween: Phaser.Tweens.Tween; - - /** - * Settings for the PathFollower. - */ - pathConfig: Phaser.Types.GameObjects.PathFollower.PathConfig; - - /** - * Internal update handler that advances this PathFollower along the path. - * - * Called automatically by the Scene step, should not typically be called directly. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - protected preUpdate(time: integer, delta: number): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * The Path this PathFollower is following. It can only follow one Path at a time. - */ - path: Phaser.Curves.Path; - - /** - * Should the PathFollower automatically rotate to point in the direction of the Path? - */ - rotateToPath: boolean; - - /** - * Set the Path that this PathFollower should follow. - * - * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. - * @param path The Path this PathFollower is following. It can only follow one Path at a time. - * @param config Settings for the PathFollower. - */ - setPath(path: Phaser.Curves.Path, config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig): Phaser.GameObjects.PathFollower; - - /** - * Set whether the PathFollower should automatically rotate to point in the direction of the Path. - * @param value Whether the PathFollower should automatically rotate to point in the direction of the Path. - * @param offset Rotation offset in degrees. Default 0. - */ - setRotateToPath(value: boolean, offset?: number): Phaser.GameObjects.PathFollower; - - /** - * Is this PathFollower actively following a Path or not? - * - * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. - */ - isFollowing(): boolean; - - /** - * Starts this PathFollower following its given Path. - * @param config The duration of the follow, or a PathFollower config object. Default {}. - * @param startAt Optional start position of the follow, between 0 and 1. Default 0. - */ - startFollow(config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig, startAt?: number): Phaser.GameObjects.PathFollower; - - /** - * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the - * point on the Path at which you paused it. - */ - pauseFollow(): Phaser.GameObjects.PathFollower; - - /** - * Resumes a previously paused PathFollower. - * - * If the PathFollower was not paused this has no effect. - */ - resumeFollow(): Phaser.GameObjects.PathFollower; - - /** - * Stops this PathFollower from following the path any longer. - * - * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. - */ - stopFollow(): Phaser.GameObjects.PathFollower; - - /** - * Internal update handler that advances this PathFollower along the path. - * - * Called automatically by the Scene step, should not typically be called directly. - */ - pathUpdate(): void; - - } - - /** - * A Quad Game Object. - * - * A Quad is a Mesh Game Object pre-configured with two triangles arranged into a rectangle, with a single - * texture spread across them. - * - * You can manipulate the corner points of the quad via the getters and setters such as `topLeftX`, and also - * change their alpha and color values. The quad itself can be moved by adjusting the `x` and `y` properties. - */ - class Quad extends Phaser.GameObjects.Mesh { - /** - * - * @param scene The Scene to which this Quad belongs. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - */ - setFrame(frame: string | integer): this; - - /** - * The top-left x vertex of this Quad. - */ - topLeftX: number; - - /** - * The top-left y vertex of this Quad. - */ - topLeftY: number; - - /** - * The top-right x vertex of this Quad. - */ - topRightX: number; - - /** - * The top-right y vertex of this Quad. - */ - topRightY: number; - - /** - * The bottom-left x vertex of this Quad. - */ - bottomLeftX: number; - - /** - * The bottom-left y vertex of this Quad. - */ - bottomLeftY: number; - - /** - * The bottom-right x vertex of this Quad. - */ - bottomRightX: number; - - /** - * The bottom-right y vertex of this Quad. - */ - bottomRightY: number; - - /** - * The top-left alpha value of this Quad. - */ - topLeftAlpha: number; - - /** - * The top-right alpha value of this Quad. - */ - topRightAlpha: number; - - /** - * The bottom-left alpha value of this Quad. - */ - bottomLeftAlpha: number; - - /** - * The bottom-right alpha value of this Quad. - */ - bottomRightAlpha: number; - - /** - * The top-left color value of this Quad. - */ - topLeftColor: number; - - /** - * The top-right color value of this Quad. - */ - topRightColor: number; - - /** - * The bottom-left color value of this Quad. - */ - bottomLeftColor: number; - - /** - * The bottom-right color value of this Quad. - */ - bottomRightColor: number; - - /** - * Sets the top-left vertex position of this Quad. - * @param x The horizontal coordinate of the vertex. - * @param y The vertical coordinate of the vertex. - */ - setTopLeft(x: number, y: number): Phaser.GameObjects.Quad; - - /** - * Sets the top-right vertex position of this Quad. - * @param x The horizontal coordinate of the vertex. - * @param y The vertical coordinate of the vertex. - */ - setTopRight(x: number, y: number): Phaser.GameObjects.Quad; - - /** - * Sets the bottom-left vertex position of this Quad. - * @param x The horizontal coordinate of the vertex. - * @param y The vertical coordinate of the vertex. - */ - setBottomLeft(x: number, y: number): Phaser.GameObjects.Quad; - - /** - * Sets the bottom-right vertex position of this Quad. - * @param x The horizontal coordinate of the vertex. - * @param y The vertical coordinate of the vertex. - */ - setBottomRight(x: number, y: number): Phaser.GameObjects.Quad; - - /** - * Resets the positions of the four corner vertices of this Quad. - */ - resetPosition(): Phaser.GameObjects.Quad; - - /** - * Resets the alpha values used by this Quad back to 1. - */ - resetAlpha(): Phaser.GameObjects.Quad; - - /** - * Resets the color values used by this Quad back to 0xffffff. - */ - resetColors(): Phaser.GameObjects.Quad; - - /** - * Resets the position, alpha and color values used by this Quad. - */ - reset(): Phaser.GameObjects.Quad; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - } - - /** - * A Render Texture. - * - * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and - * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic - * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. - * - * Note that under WebGL a FrameBuffer, which is what the Render Texture uses internally, cannot be anti-aliased. This means - * that when drawing objects such as Shapes to a Render Texture they will appear to be drawn with no aliasing, however this - * is a technical limitation of WebGL. To get around it, create your shape as a texture in an art package, then draw that - * to the Render Texture. - */ - class RenderTexture extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Crop, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the Render Texture. Default 32. - * @param height The height of the Render Texture. Default 32. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, width?: integer, height?: integer); - - /** - * A reference to either the Canvas or WebGL Renderer that the Game instance is using. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * A reference to the Texture Manager. - */ - textureManager: Phaser.Textures.TextureManager; - - /** - * The tint of the Render Texture when rendered. - */ - globalTint: number; - - /** - * The alpha of the Render Texture when rendered. - */ - globalAlpha: number; - - /** - * The HTML Canvas Element that the Render Texture is drawing to when using the Canvas Renderer. - */ - canvas: HTMLCanvasElement; - - /** - * A reference to the GL Frame Buffer this Render Texture is drawing to. - * This is only set if Phaser is running with the WebGL Renderer. - */ - framebuffer: WebGLFramebuffer; - - /** - * Is this Render Texture dirty or not? If not it won't spend time clearing or filling itself. - */ - dirty: boolean; - - /** - * The Texture corresponding to this Render Texture. - */ - texture: Phaser.Textures.Texture; - - /** - * The Frame corresponding to this Render Texture. - */ - frame: Phaser.Textures.Frame; - - /** - * A reference to the Rendering Context belonging to the Canvas Element this Render Texture is drawing to. - */ - context: CanvasRenderingContext2D; - - /** - * An internal Camera that can be used to move around the Render Texture. - * Control it just like you would any Scene Camera. The difference is that it only impacts the placement of what - * is drawn to the Render Texture. You can scroll, zoom and rotate this Camera. - */ - camera: Phaser.Cameras.Scene2D.BaseCamera; - - /** - * A reference to the WebGL Rendering Context. - */ - gl: WebGLRenderingContext; - - /** - * A reference to the WebGLTexture that is being rendered to in a WebGL Context. - */ - readonly glTexture: WebGLTexture; - - /** - * Sets the size of this Game Object. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Resizes the Render Texture to the new dimensions given. - * - * If Render Texture was created from specific frame, only the size of the frame will be changed. The size of the source - * texture will not change. - * - * If Render Texture was not created from specific frame, the following will happen: - * In WebGL it will destroy and then re-create the frame buffer being used by the Render Texture. - * In Canvas it will resize the underlying canvas element. - * Both approaches will erase everything currently drawn to the Render Texture. - * - * If the dimensions given are the same as those already being used, calling this method will do nothing. - * @param width The new width of the Render Texture. - * @param height The new height of the Render Texture. If not specified, will be set the same as the `width`. Default width. - */ - resize(width: number, height?: number): this; - - /** - * Set the tint to use when rendering this Render Texture. - * @param tint The tint value. - */ - setGlobalTint(tint: integer): this; - - /** - * Set the alpha to use when rendering this Render Texture. - * @param alpha The alpha value. - */ - setGlobalAlpha(alpha: number): this; - - /** - * Stores a copy of this Render Texture in the Texture Manager using the given key. - * - * After doing this, any texture based Game Object, such as a Sprite, can use the contents of this - * Render Texture by using the texture key: - * - * ```javascript - * var rt = this.add.renderTexture(0, 0, 128, 128); - * - * // Draw something to the Render Texture - * - * rt.saveTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * Updating the contents of this Render Texture will automatically update _any_ Game Object - * that is using it as a texture. Calling `saveTexture` again will not save another copy - * of the same texture, it will just rename the key of the existing copy. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame from a Render Texture. - * @param key The unique key to store the texture as within the global Texture Manager. - */ - saveTexture(key: string): Phaser.Textures.Texture; - - /** - * Fills the Render Texture with the given color. - * @param rgb The color to fill the Render Texture with. - * @param alpha The alpha value used by the fill. Default 1. - * @param x The left coordinate of the fill rectangle. Default 0. - * @param y The top coordinate of the fill rectangle. Default 0. - * @param width The width of the fill rectangle. Default this.frame.cutWidth. - * @param height The height of the fill rectangle. Default this.frame.cutHeight. - */ - fill(rgb: number, alpha?: number, x?: number, y?: number, width?: number, height?: number): this; - - /** - * Clears the Render Texture. - */ - clear(): this; - - /** - * Draws the given object, or an array of objects, to this Render Texture using a blend mode of ERASE. - * This has the effect of erasing any filled pixels in the objects from this Render Texture. - * - * It can accept any of the following: - * - * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. - * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. - * * Another Render Texture. - * * A Texture Frame instance. - * * A string. This is used to look-up a texture from the Texture Manager. - * - * Note: You cannot erase a Render Texture from itself. - * - * 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. - * - * 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. - * - * Calling this method causes the WebGL batch to flush, so it can write the texture - * data to the framebuffer being used internally. The batch is flushed at the end, - * after the entries have been iterated. So if you've a bunch of objects to draw, - * try and pass them in an array in one single call, rather than making lots of - * separate calls. - * @param entries Any renderable Game Object, or Group, Container, Display List, other Render Texture, Texture Frame or an array of any of these. - * @param x The x position to draw the Frame at, or the offset applied to the object. - * @param y The y position to draw the Frame at, or the offset applied to the object. - */ - erase(entries: any, x?: number, y?: number): this; - - /** - * Draws the given object, or an array of objects, to this Render Texture. - * - * It can accept any of the following: - * - * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. - * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. - * * Another Render Texture. - * * A Texture Frame instance. - * * A string. This is used to look-up a texture from the Texture Manager. - * - * Note: You cannot draw a Render Texture to itself. - * - * 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. - * - * The `alpha` and `tint` values are only used by Texture Frames. - * Game Objects use their own alpha and tint values when being drawn. - * - * Calling this method causes the WebGL batch to flush, so it can write the texture - * data to the framebuffer being used internally. The batch is flushed at the end, - * after the entries have been iterated. So if you've a bunch of objects to draw, - * try and pass them in an array in one single call, rather than making lots of - * separate calls. - * @param entries Any renderable Game Object, or Group, Container, Display List, other Render Texture, Texture Frame or an array of any of these. - * @param x The x position to draw the Frame at, or the offset applied to the object. - * @param y The y position to draw the Frame at, or the offset applied to the object. - * @param alpha The alpha value. Only used for Texture Frames and if not specified defaults to the `globalAlpha` property. Game Objects use their own current alpha value. - * @param tint WebGL only. The tint color value. Only used for Texture Frames and if not specified defaults to the `globalTint` property. Game Objects use their own current tint value. - */ - draw(entries: any, x?: number, y?: number, alpha?: number, tint?: number): this; - - /** - * Draws the Texture Frame to the Render Texture at the given position. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * - * ```javascript - * var rt = this.add.renderTexture(0, 0, 800, 600); - * rt.drawFrame(key, frame); - * ``` - * - * You can optionally provide a position, alpha and tint value to apply to the frame - * before it is drawn. - * - * Calling this method will cause a batch flush, so if you've got a stack of things to draw - * in a tight loop, try using the `draw` method instead. - * - * If you need to draw a Sprite to this Render Texture, use the `draw` method instead. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - * @param x The x position to draw the frame at. Default 0. - * @param y The y position to draw the frame at. Default 0. - * @param alpha The alpha to use. If not specified it uses the `globalAlpha` property. - * @param tint WebGL only. The tint color to use. If not specified it uses the `globalTint` property. - */ - drawFrame(key: string, frame?: string | integer, x?: number, y?: number, alpha?: number, tint?: number): this; - - /** - * Takes a snapshot of the given area of this Render Texture. - * - * The snapshot is taken immediately. - * - * To capture the whole Render Texture see the `snapshot` method. To capture a specific pixel, see `snapshotPixel`. - * - * 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. - * @param x The x coordinate to grab from. - * @param y The y coordinate to grab from. - * @param width The width of the area to grab. - * @param height The height of the area to grab. - * @param callback The Function to invoke after the snapshot image is created. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshotArea(x: integer, y: integer, width: integer, height: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; - - /** - * Takes a snapshot of the whole of this Render Texture. - * - * The snapshot is taken immediately. - * - * To capture just a portion of the Render Texture see the `snapshotArea` method. To capture a specific pixel, see `snapshotPixel`. - * - * 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. - * @param callback The Function to invoke after the snapshot image is created. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshot(callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; - - /** - * Takes a snapshot of the given pixel from this Render Texture. - * - * The snapshot is taken immediately. - * - * To capture the whole Render Texture see the `snapshot` method. To capture a specific portion, see `snapshotArea`. - * - * Unlike the other two snapshot methods, this one will send your callback 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, than the other snapshot methods. - * @param x The x coordinate of the pixel to get. - * @param y The y coordinate of the pixel to get. - * @param callback The Function to invoke after the snapshot pixel data is extracted. - */ - snapshotPixel(x: integer, y: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback): this; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A Shader Game Object. - * - * This Game Object allows you to easily add a quad with its own shader into the display list, and manipulate it - * as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders - * can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other - * Game Object. They can also be made interactive and used for input events. - * - * It works by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can - * be created dynamically at runtime, or loaded in via the GLSL File Loader: - * - * ```javascript - * function preload () - * { - * this.load.glsl('fire', 'shaders/fire.glsl.js'); - * } - * - * function create () - * { - * this.add.shader('fire', 400, 300, 512, 512); - * } - * ``` - * - * Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. - * - * Due to the way in which they work, you cannot directly change the alpha or blend mode of a Shader. This should - * be handled via exposed uniforms in the shader code itself. - * - * By default a Shader will be created with a standard set of uniforms. These were added to match those - * found on sites such as ShaderToy or GLSLSandbox, and provide common functionality a shader may need, - * such as the timestamp, resolution or pointer position. You can replace them by specifying your own uniforms - * in the Base Shader. - * - * These Shaders work by halting the current pipeline during rendering, creating a viewport matched to the - * size of this Game Object and then renders a quad using the bound shader. At the end, the pipeline is restored. - * - * Because it blocks the pipeline it means it will interrupt any batching that is currently going on, so you should - * use these Game Objects sparingly. If you need to have a fully batched custom shader, then please look at using - * a custom pipeline instead. However, for background or special masking effects, they are extremely effective. - */ - class Shader extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param key The key of the shader to use from the shader cache, or a BaseShader instance. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the Game Object. Default 128. - * @param height The height of the Game Object. Default 128. - * @param textures Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. - * @param textureData Additional texture data if you want to create shader with none NPOT textures. - */ - constructor(scene: Phaser.Scene, key: string | Phaser.Display.BaseShader, x?: number, y?: number, width?: number, height?: number, textures?: string[], textureData?: any); - - /** - * The underlying shader object being used. - * Empty by default and set during a call to the `setShader` method. - */ - shader: Phaser.Display.BaseShader; - - /** - * A reference to the current renderer. - * Shaders only work with the WebGL Renderer. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * The WebGL context belonging to the renderer. - */ - gl: WebGLRenderingContext; - - /** - * Raw byte buffer of vertices this Shader uses. - */ - vertexData: ArrayBuffer; - - /** - * The WebGL vertex buffer object this shader uses. - */ - vertexBuffer: WebGLBuffer; - - /** - * The WebGL shader program this shader uses. - */ - program: WebGLProgram; - - /** - * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources to the GPU. - */ - bytes: Uint8Array; - - /** - * Float32 view of the array buffer containing the shaders vertices. - */ - vertexViewF32: Float32Array; - - /** - * The view matrix the shader uses during rendering. - */ - readonly viewMatrix: Float32Array; - - /** - * The projection matrix the shader uses during rendering. - */ - readonly projectionMatrix: Float32Array; - - /** - * The default uniform mappings. These can be added to (or replaced) by specifying your own uniforms when - * creating this shader game object. The uniforms are updated automatically during the render step. - * - * The defaults are: - * - * `resolution` (2f) - Set to the size of this shader. - * `time` (1f) - The elapsed game time, in seconds. - * `mouse` (2f) - If a pointer has been bound (with `setPointer`), this uniform contains its position each frame. - * `date` (4fv) - A vec4 containing the year, month, day and time in seconds. - * `sampleRate` (1f) - Sound sample rate. 44100 by default. - * `iChannel0...3` (sampler2D) - Input channels 0 to 3. `null` by default. - */ - uniforms: any; - - /** - * The pointer bound to this shader, if any. - * Set via the chainable `setPointer` method, or by modifying this property directly. - */ - pointer: Phaser.Input.Pointer; - - /** - * A reference to the GL Frame Buffer this Shader is drawing to. - * This property is only set if you have called `Shader.setRenderToTexture`. - */ - framebuffer: WebGLFramebuffer; - - /** - * A reference to the WebGLTexture this Shader is rendering to. - * This property is only set if you have called `Shader.setRenderToTexture`. - */ - glTexture: WebGLTexture; - - /** - * A flag that indicates if this Shader has been set to render to a texture instead of the display list. - * - * This property is `true` if you have called `Shader.setRenderToTexture`, otherwise it's `false`. - * - * A Shader that is rendering to a texture _does not_ appear on the display list. - */ - readonly renderToTexture: boolean; - - /** - * A reference to the Phaser.Textures.Texture that has been stored in the Texture Manager for this Shader. - * - * This property is only set if you have called `Shader.setRenderToTexture`, otherwise it is `null`. - */ - texture: Phaser.Textures.Texture; - - /** - * Compares the renderMask with the renderFlags to see if this Game Object will render or not. - * Also checks the Game Object against the given Cameras exclusion list. - * @param camera The Camera to check against this Game Object. - */ - willRender(camera: Phaser.Cameras.Scene2D.Camera): boolean; - - /** - * Changes this Shader so instead of rendering to the display list it renders to a - * WebGL Framebuffer and WebGL Texture instead. This allows you to use the output - * of this shader as an input for another shader, by mapping a sampler2D uniform - * to it. - * - * After calling this method the `Shader.framebuffer` and `Shader.glTexture` properties - * are populated. - * - * Additionally, you can provide a key to this method. Doing so will create a Phaser Texture - * from this Shader and save it into the Texture Manager, allowing you to then use it for - * any texture-based Game Object, such as a Sprite or Image: - * - * ```javascript - * var shader = this.add.shader('myShader', x, y, width, height); - * - * shader.setRenderToTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * Note that it stores an active reference to this Shader. That means as this shader updates, - * so does the texture and any object using it to render with. Also, if you destroy this - * shader, be sure to clear any objects that may have been using it as a texture too. - * - * You can access the Phaser Texture that is created via the `Shader.texture` property. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame from a Render Texture. - * @param key The unique key to store the texture as within the global Texture Manager. - * @param flipY Does this texture need vertically flipping before rendering? This should usually be set to `true` if being fed from a buffer. Default false. - */ - setRenderToTexture(key?: string, flipY?: boolean): this; - - /** - * Sets the fragment and, optionally, the vertex shader source code that this Shader will use. - * This will immediately delete the active shader program, if set, and then create a new one - * with the given source. Finally, the shader uniforms are initialized. - * @param key The key of the shader to use from the shader cache, or a BaseShader instance. - * @param textures Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. - * @param textureData Additional texture data. - */ - setShader(key: string | Phaser.Display.BaseShader, textures?: string[], textureData?: any): this; - - /** - * Binds a Phaser Pointer object to this Shader. - * - * The screen position of the pointer will be set in to the shaders `mouse` uniform - * automatically every frame. Call this method with no arguments to unbind the pointer. - * @param pointer The Pointer to bind to this shader. - */ - setPointer(pointer?: Phaser.Input.Pointer): this; - - /** - * Sets this shader to use an orthographic projection matrix. - * This matrix is stored locally in the `projectionMatrix` property, - * as well as being bound to the `uProjectionMatrix` uniform. - * @param left The left value. - * @param right The right value. - * @param bottom The bottom value. - * @param top The top value. - */ - projOrtho(left: number, right: number, bottom: number, top: number): void; - - /** - * Sets a sampler2D uniform on this shader where the source texture is a WebGLTexture. - * - * This allows you to feed the output from one Shader into another: - * - * ```javascript - * let shader1 = this.add.shader(baseShader1, 0, 0, 512, 512).setRenderToTexture(); - * let shader2 = this.add.shader(baseShader2, 0, 0, 512, 512).setRenderToTexture('output'); - * - * shader1.setSampler2DBuffer('iChannel0', shader2.glTexture, 512, 512); - * shader2.setSampler2DBuffer('iChannel0', shader1.glTexture, 512, 512); - * ``` - * - * In the above code, the result of baseShader1 is fed into Shader2 as the `iChannel0` sampler2D uniform. - * The result of baseShader2 is then fed back into shader1 again, creating a feedback loop. - * - * If you wish to use an image from the Texture Manager as a sampler2D input for this shader, - * see the `Shader.setSampler2D` method. - * @param uniformKey The key of the sampler2D uniform to be updated, i.e. `iChannel0`. - * @param texture A WebGLTexture reference. - * @param width The width of the texture. - * @param height The height of the texture. - * @param textureIndex The texture index. Default 0. - * @param textureData Additional texture data. - */ - setSampler2DBuffer(uniformKey: string, texture: WebGLTexture, width: integer, height: integer, textureIndex?: integer, textureData?: any): this; - - /** - * Sets a sampler2D uniform on this shader. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * - * If you wish to use another Shader as a sampler2D input for this shader, see the `Shader.setSampler2DBuffer` method. - * @param uniformKey The key of the sampler2D uniform to be updated, i.e. `iChannel0`. - * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param textureIndex The texture index. Default 0. - * @param textureData Additional texture data. - */ - setSampler2D(uniformKey: string, textureKey: string, textureIndex?: integer, textureData?: any): this; - - /** - * Sets a property of a uniform already present on this shader. - * - * To modify the value of a uniform such as a 1f or 1i use the `value` property directly: - * - * ```javascript - * shader.setUniform('size.value', 16); - * ``` - * - * You can use dot notation to access deeper values, for example: - * - * ```javascript - * shader.setUniform('resolution.value.x', 512); - * ``` - * - * The change to the uniform will take effect the next time the shader is rendered. - * @param key The key of the uniform to modify. Use dots for deep properties, i.e. `resolution.value.x`. - * @param value The value to set into the uniform. - */ - setUniform(key: string, value: any): this; - - /** - * Returns the uniform object for the given key, or `null` if the uniform couldn't be found. - * @param key The key of the uniform to return the value for. - */ - getUniform(key: string): any; - - /** - * A short-cut method that will directly set the texture being used by the `iChannel0` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param textureData Additional texture data. - */ - setChannel0(textureKey: string, textureData?: any): this; - - /** - * A short-cut method that will directly set the texture being used by the `iChannel1` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param textureData Additional texture data. - */ - setChannel1(textureKey: string, textureData?: any): this; - - /** - * A short-cut method that will directly set the texture being used by the `iChannel2` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param textureData Additional texture data. - */ - setChannel2(textureKey: string, textureData?: any): this; - - /** - * A short-cut method that will directly set the texture being used by the `iChannel3` sampler2D uniform. - * - * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame - * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. - * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. - * @param textureData Additional texture data. - */ - setChannel3(textureKey: string, textureData?: any): this; - - /** - * Called automatically during render. - * - * This method performs matrix ITRS and then stores the resulting value in the `uViewMatrix` uniform. - * It then sets up the vertex buffer and shader, updates and syncs the uniforms ready - * for flush to be called. - * @param matrix2D The transform matrix to use during rendering. - */ - load(matrix2D?: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Called automatically during render. - * - * Sets the active shader, loads the vertex buffer and then draws. - */ - flush(): void; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an arc shape. You can control the start and end angles of the arc, - * as well as if the angles are winding clockwise or anti-clockwise. With the default settings - * it renders as a complete circle. By changing the angles you can create other arc shapes, - * such as half-circles. - * - * Arcs also have an `iterations` property and corresponding `setIterations` method. This allows - * you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. - */ - class Arc extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param radius The radius of the arc. Default 128. - * @param startAngle The start angle of the arc, in degrees. Default 0. - * @param endAngle The end angle of the arc, in degrees. Default 360. - * @param anticlockwise The winding order of the start and end angles. Default false. - * @param fillColor The color the arc will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, radius?: number, startAngle?: integer, endAngle?: integer, anticlockwise?: boolean, fillColor?: number, fillAlpha?: number); - - /** - * The number of iterations used when drawing the arc. - * Increase this value for smoother arcs, at the cost of more polygons being rendered. - * Modify this value by small amounts, such as 0.01. - */ - iterations: number; - - /** - * The radius of the arc. - */ - radius: number; - - /** - * The start angle of the arc, in degrees. - */ - startAngle: integer; - - /** - * The end angle of the arc, in degrees. - */ - endAngle: integer; - - /** - * The winding order of the start and end angles. - */ - anticlockwise: boolean; - - /** - * Sets the radius of the arc. - * This call can be chained. - * @param value The value to set the radius to. - */ - setRadius(value: number): this; - - /** - * Sets the number of iterations used when drawing the arc. - * Increase this value for smoother arcs, at the cost of more polygons being rendered. - * Modify this value by small amounts, such as 0.01. - * This call can be chained. - * @param value The value to set the iterations to. - */ - setIterations(value: number): this; - - /** - * Sets the starting angle of the arc, in degrees. - * This call can be chained. - * @param value The value to set the starting angle to. - */ - setStartAngle(value: integer): this; - - /** - * Sets the ending angle of the arc, in degrees. - * This call can be chained. - * @param value The value to set the ending angle to. - */ - setEndAngle(value: integer): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to - * the Curve Shape in the constructor. - * - * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - */ - class Curve extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param curve The Curve object to use to create the Shape. - * @param fillColor The color the curve will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, curve?: Phaser.Curves.Curve, fillColor?: number, fillAlpha?: number); - - /** - * The smoothness of the curve. The number of points used when rendering it. - * Increase this value for smoother curves, at the cost of more polygons being rendered. - */ - smoothness: integer; - - /** - * Sets the smoothness of the curve. The number of points used when rendering it. - * Increase this value for smoother curves, at the cost of more polygons being rendered. - * This call can be chained. - * @param value The value to set the smoothness to. - */ - setSmoothness(value: integer): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. - * If the width and height match it will render as a circle. If the width is less than the height, - * it will look more like an egg shape. - * - * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. - * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations - * that take place during construction. Increase and decrease the default value for smoother, or more - * jagged, shapes. - */ - class Ellipse extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. - * @param height The height of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. - * @param fillColor The color the ellipse will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number); - - /** - * The smoothness of the ellipse. The number of points used when rendering it. - * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. - */ - smoothness: integer; - - /** - * Sets the size of the ellipse by changing the underlying geometry data, rather than scaling the object. - * This call can be chained. - * @param width The width of the ellipse. - * @param height The height of the ellipse. - */ - setSize(width: number, height: number): this; - - /** - * Sets the smoothness of the ellipse. The number of points used when rendering it. - * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. - * This call can be chained. - * @param value The value to set the smoothness to. - */ - setSmoothness(value: integer): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * A Grid Shape allows you to display a grid in your game, where you can control the size of the - * grid as well as the width and height of the grid cells. You can set a fill color for each grid - * cell as well as an alternate fill color. When the alternate fill color is set then the grid - * cells will alternate the fill colors as they render, creating a chess-board effect. You can - * also optionally have an outline fill color. If set, this draws lines between the grid cells - * in the given color. If you specify an outline color with an alpha of zero, then it will draw - * the cells spaced out, but without the lines between them. - */ - class Grid extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param width The width of the grid. Default 128. - * @param height The height of the grid. Default 128. - * @param cellWidth The width of one cell in the grid. Default 32. - * @param cellHeight The height of one cell in the grid. Default 32. - * @param fillColor The color the grid cells will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - * @param outlineFillColor The color of the lines between the grid cells. See the `setOutline` method. - * @param outlineFillAlpha The alpha of the lines between the grid cells. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, width?: number, height?: number, cellWidth?: number, cellHeight?: number, fillColor?: number, fillAlpha?: number, outlineFillColor?: number, outlineFillAlpha?: number); - - /** - * The width of each grid cell. - * Must be a positive value. - */ - cellWidth: number; - - /** - * The height of each grid cell. - * Must be a positive value. - */ - cellHeight: number; - - /** - * Will the grid render its cells in the `fillColor`? - */ - showCells: boolean; - - /** - * The color of the lines between each grid cell. - */ - outlineFillColor: number; - - /** - * The alpha value for the color of the lines between each grid cell. - */ - outlineFillAlpha: number; - - /** - * Will the grid display the lines between each cell when it renders? - */ - showOutline: boolean; - - /** - * Will the grid render the alternating cells in the `altFillColor`? - */ - showAltCells: boolean; - - /** - * The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. - */ - altFillColor: number; - - /** - * The alpha the alternating grid cells will be filled with. - * You can also set the alpha of the overall Shape using its `alpha` property. - */ - altFillAlpha: number; - - /** - * Sets the fill color and alpha level the grid cells will use when rendering. - * - * If this method is called with no values then the grid cells will not be rendered, - * however the grid lines and alternating cells may still be. - * - * Also see the `setOutlineStyle` and `setAltFillStyle` methods. - * - * This call can be chained. - * @param fillColor The color the grid cells will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. Default 1. - */ - setFillStyle(fillColor?: number, fillAlpha?: number): this; - - /** - * Sets the fill color and alpha level that the alternating grid cells will use. - * - * If this method is called with no values then alternating grid cells will not be rendered in a different color. - * - * Also see the `setOutlineStyle` and `setFillStyle` methods. - * - * This call can be chained. - * @param fillColor The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the alternating grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. Default 1. - */ - setAltFillStyle(fillColor?: number, fillAlpha?: number): this; - - /** - * Sets the fill color and alpha level that the lines between each grid cell will use. - * - * If this method is called with no values then the grid lines will not be rendered at all, however - * the cells themselves may still be if they have colors set. - * - * Also see the `setFillStyle` and `setAltFillStyle` methods. - * - * This call can be chained. - * @param fillColor The color the lines between the grid cells will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the lines between the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. Default 1. - */ - setOutlineStyle(fillColor?: number, fillAlpha?: number): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set - * the color of the top, left and right faces of the rectangle respectively. You can also choose - * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting - * the `projection` property. - */ - class IsoBox extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param size The width of the iso box in pixels. The left and right faces will be exactly half this value. Default 48. - * @param height The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. Default 32. - * @param fillTop The fill color of the top face of the iso box. Default 0xeeeeee. - * @param fillLeft The fill color of the left face of the iso box. Default 0x999999. - * @param fillRight The fill color of the right face of the iso box. Default 0xcccccc. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, size?: number, height?: number, fillTop?: number, fillLeft?: number, fillRight?: number); - - /** - * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. - */ - projection: integer; - - /** - * The color used to fill in the top of the iso box. - */ - fillTop: number; - - /** - * The color used to fill in the left-facing side of the iso box. - */ - fillLeft: number; - - /** - * The color used to fill in the right-facing side of the iso box. - */ - fillRight: number; - - /** - * Controls if the top-face of the iso box be rendered. - */ - showTop: boolean; - - /** - * Controls if the left-face of the iso box be rendered. - */ - showLeft: boolean; - - /** - * Controls if the right-face of the iso box be rendered. - */ - showRight: boolean; - - /** - * Sets the projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. - * This call can be chained. - * @param value The value to set the projection to. - */ - setProjection(value: integer): this; - - /** - * Sets which faces of the iso box will be rendered. - * This call can be chained. - * @param showTop Show the top-face of the iso box. Default true. - * @param showLeft Show the left-face of the iso box. Default true. - * @param showRight Show the right-face of the iso box. Default true. - */ - setFaces(showTop?: boolean, showLeft?: boolean, showRight?: boolean): this; - - /** - * Sets the fill colors for each face of the iso box. - * This call can be chained. - * @param fillTop The color used to fill the top of the iso box. - * @param fillLeft The color used to fill in the left-facing side of the iso box. - * @param fillRight The color used to fill in the right-facing side of the iso box. - */ - setFillStyle(fillTop?: number, fillLeft?: number, fillRight?: number): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only fill colors and cannot be stroked. - * - * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different - * fill color. You can set the color of the top, left and right faces of the triangle respectively - * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. - * - * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting - * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside - * down or not. - */ - class IsoTriangle extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param size The width of the iso triangle in pixels. The left and right faces will be exactly half this value. Default 48. - * @param height The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. Default 32. - * @param reversed Is the iso triangle upside down? Default false. - * @param fillTop The fill color of the top face of the iso triangle. Default 0xeeeeee. - * @param fillLeft The fill color of the left face of the iso triangle. Default 0x999999. - * @param fillRight The fill color of the right face of the iso triangle. Default 0xcccccc. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, size?: number, height?: number, reversed?: boolean, fillTop?: number, fillLeft?: number, fillRight?: number); - - /** - * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. - */ - projection: integer; - - /** - * The color used to fill in the top of the iso triangle. This is only used if the triangle is reversed. - */ - fillTop: number; - - /** - * The color used to fill in the left-facing side of the iso triangle. - */ - fillLeft: number; - - /** - * The color used to fill in the right-facing side of the iso triangle. - */ - fillRight: number; - - /** - * Controls if the top-face of the iso triangle be rendered. - */ - showTop: boolean; - - /** - * Controls if the left-face of the iso triangle be rendered. - */ - showLeft: boolean; - - /** - * Controls if the right-face of the iso triangle be rendered. - */ - showRight: boolean; - - /** - * Sets if the iso triangle will be rendered upside down or not. - */ - isReversed: boolean; - - /** - * Sets the projection level of the iso triangle. Change this to change the 'angle' at which you are looking at the pyramid. - * This call can be chained. - * @param value The value to set the projection to. - */ - setProjection(value: integer): this; - - /** - * Sets if the iso triangle will be rendered upside down or not. - * This call can be chained. - * @param reversed Sets if the iso triangle will be rendered upside down or not. - */ - setReversed(reversed: boolean): this; - - /** - * Sets which faces of the iso triangle will be rendered. - * This call can be chained. - * @param showTop Show the top-face of the iso triangle (only if `reversed` is true) Default true. - * @param showLeft Show the left-face of the iso triangle. Default true. - * @param showRight Show the right-face of the iso triangle. Default true. - */ - setFaces(showTop?: boolean, showLeft?: boolean, showRight?: boolean): this; - - /** - * Sets the fill colors for each face of the iso triangle. - * This call can be chained. - * @param fillTop The color used to fill the top of the iso triangle. - * @param fillLeft The color used to fill in the left-facing side of the iso triangle. - * @param fillRight The color used to fill in the right-facing side of the iso triangle. - */ - setFillStyle(fillTop?: number, fillLeft?: number, fillRight?: number): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports only stroke colors and cannot be filled. - * - * A Line Shape allows you to draw a line between two points in your game. You can control the - * stroke color and thickness of the line. In WebGL only you can also specify a different - * thickness for the start and end of the line, allowing you to render lines that taper-off. - * - * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. - * - * Be aware that as with all Game Objects the default origin is 0.5. If you need to draw a Line - * between two points and want the x1/y1 values to match the x/y values, then set the origin to 0. - */ - class Line extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param x1 The horizontal position of the start of the line. Default 0. - * @param y1 The vertical position of the start of the line. Default 0. - * @param x2 The horizontal position of the end of the line. Default 128. - * @param y2 The vertical position of the end of the line. Default 0. - * @param strokeColor The color the line will be drawn in, i.e. 0xff0000 for red. - * @param strokeAlpha The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, strokeColor?: number, strokeAlpha?: number); - - /** - * The width (or thickness) of the line. - * See the setLineWidth method for extra details on changing this on WebGL. - */ - lineWidth: number; - - /** - * Sets the width of the line. - * - * When using the WebGL renderer you can have different start and end widths. - * When using the Canvas renderer only the `startWidth` value is used. The `endWidth` is ignored. - * - * This call can be chained. - * @param startWidth The start width of the line. - * @param endWidth The end width of the line. Only used in WebGL. - */ - setLineWidth(startWidth: number, endWidth?: number): this; - - /** - * Sets the start and end coordinates of this Line. - * @param x1 The horizontal position of the start of the line. Default 0. - * @param y1 The vertical position of the start of the line. Default 0. - * @param x2 The horizontal position of the end of the line. Default 0. - * @param y2 The vertical position of the end of the line. Default 0. - */ - setTo(x1?: number, y1?: number, x2?: number, y2?: number): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Polygon Shape is created by providing a list of points, which are then used to create an - * internal Polygon geometry object. The points can be set from a variety of formats: - * - * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` - * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` - * - An array of objects with public x/y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - * - * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending - * on the coordinates of the points provided, the final shape may be rendered offset from its origin. - */ - class Polygon extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param points The points that make up the polygon. - * @param fillColor The color the polygon will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, points?: any, fillColor?: number, fillAlpha?: number); - - /** - * Smooths the polygon over the number of iterations specified. - * The base polygon data will be updated and replaced with the smoothed values. - * This call can be chained. - * @param iterations The number of times to apply the polygon smoothing. Default 1. - */ - smooth(iterations?: integer): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * You can change the size of the rectangle by changing the `width` and `height` properties. - */ - class Rectangle extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param width The width of the rectangle. Default 128. - * @param height The height of the rectangle. Default 128. - * @param fillColor The color the rectangle will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x: number, y: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number); - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. - * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. - */ - class Shape extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param type The internal type of the Shape. - * @param data The data of the source shape geometry, if any. - */ - constructor(scene: Phaser.Scene, type?: string, data?: any); - - /** - * The source Shape data. Typically a geometry object. - * You should not manipulate this directly. - */ - readonly data: any; - - /** - * Holds the polygon path data for filled rendering. - */ - readonly pathData: number[]; - - /** - * Holds the earcut polygon path index data for filled rendering. - */ - readonly pathIndexes: integer[]; - - /** - * The fill color used by this Shape. - */ - fillColor: number; - - /** - * The fill alpha value used by this Shape. - */ - fillAlpha: number; - - /** - * The stroke color used by this Shape. - */ - strokeColor: number; - - /** - * The stroke alpha value used by this Shape. - */ - strokeAlpha: number; - - /** - * The stroke line width used by this Shape. - */ - lineWidth: number; - - /** - * Controls if this Shape is filled or not. - * Note that some Shapes do not support being filled (such as Line shapes) - */ - isFilled: boolean; - - /** - * Controls if this Shape is stroked or not. - * Note that some Shapes do not support being stroked (such as Iso Box shapes) - */ - isStroked: boolean; - - /** - * Controls if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - */ - closePath: boolean; - - /** - * Sets the fill color and alpha for this Shape. - * - * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. - * - * Note that some Shapes do not support fill colors, such as the Line shape. - * - * This call can be chained. - * @param color The color used to fill this shape. If not provided the Shape will not be filled. - * @param alpha The alpha value used when filling this shape, if a fill color is given. Default 1. - */ - setFillStyle(color?: number, alpha?: number): this; - - /** - * Sets the stroke color and alpha for this Shape. - * - * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. - * - * Note that some Shapes do not support being stroked, such as the Iso Box shape. - * - * This call can be chained. - * @param lineWidth The width of line to stroke with. If not provided or undefined the Shape will not be stroked. - * @param color The color used to stroke this shape. If not provided the Shape will not be stroked. - * @param alpha The alpha value used when stroking this shape, if a stroke color is given. Default 1. - */ - setStrokeStyle(lineWidth?: number, color?: number, alpha?: number): this; - - /** - * Sets if this Shape path is closed during rendering when stroked. - * Note that some Shapes are always closed when stroked (such as Ellipse shapes) - * - * This call can be chained. - * @param value Set to `true` if the Shape should be closed when stroked, otherwise `false`. - */ - setClosePath(value: boolean): this; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * As the name implies, the Star shape will display a star in your game. You can control several - * aspects of it including the number of points that constitute the star. The default is 5. If - * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky - * star shape. - * - * You can also control the inner and outer radius, which is how 'long' each point of the star is. - * Modify these values to create more interesting shapes. - */ - class Star extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param points The number of points on the star. Default 5. - * @param innerRadius The inner radius of the star. Default 32. - * @param outerRadius The outer radius of the star. Default 64. - * @param fillColor The color the star will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, points?: number, innerRadius?: number, outerRadius?: number, fillColor?: number, fillAlpha?: number); - - /** - * Sets the number of points that make up the Star shape. - * This call can be chained. - * @param value The amount of points the Star will have. - */ - setPoints(value: integer): this; - - /** - * Sets the inner radius of the Star shape. - * This call can be chained. - * @param value The amount to set the inner radius to. - */ - setInnerRadius(value: number): this; - - /** - * Sets the outer radius of the Star shape. - * This call can be chained. - * @param value The amount to set the outer radius to. - */ - setOuterRadius(value: number): this; - - /** - * The number of points that make up the Star shape. - */ - points: integer; - - /** - * The inner radius of the Star shape. - */ - innerRadius: number; - - /** - * The outer radius of the Star shape. - */ - outerRadius: number; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can - * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling - * it for input or physics. It provides a quick and easy way for you to render this shape in your - * game without using a texture, while still taking advantage of being fully batched in WebGL. - * - * This shape supports both fill and stroke colors. - * - * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the - * position of each point of these lines. The triangle is always closed and cannot have an open - * face. If you require that, consider using a Polygon instead. - */ - class Triangle extends Phaser.GameObjects.Shape { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. Default 0. - * @param y The vertical position of this Game Object in the world. Default 0. - * @param x1 The horizontal position of the first point in the triangle. Default 0. - * @param y1 The vertical position of the first point in the triangle. Default 128. - * @param x2 The horizontal position of the second point in the triangle. Default 64. - * @param y2 The vertical position of the second point in the triangle. Default 0. - * @param x3 The horizontal position of the third point in the triangle. Default 128. - * @param y3 The vertical position of the third point in the triangle. Default 128. - * @param fillColor The color the triangle will be filled with, i.e. 0xff0000 for red. - * @param fillAlpha The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. - */ - constructor(scene: Phaser.Scene, x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number, fillColor?: number, fillAlpha?: number); - - /** - * Sets the data for the lines that make up this Triangle shape. - * @param x1 The horizontal position of the first point in the triangle. Default 0. - * @param y1 The vertical position of the first point in the triangle. Default 0. - * @param x2 The horizontal position of the second point in the triangle. Default 0. - * @param y2 The vertical position of the second point in the triangle. Default 0. - * @param x3 The horizontal position of the third point in the triangle. Default 0. - * @param y3 The vertical position of the third point in the triangle. Default 0. - */ - setTo(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number): this; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * @param value The alpha value applied across the whole Game Object. Default 1. - */ - setAlpha(value?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - */ - class Sprite extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.TextureCrop, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); - - /** - * The Animation Controller of this Sprite. - */ - anims: Phaser.GameObjects.Components.Animation; - - /** - * Update this Sprite's animations. - * @param time The current timestamp. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - protected preUpdate(time: number, delta: number): void; - - /** - * Start playing the given animation. - * @param key The string-based key of the animation to play. - * @param ignoreIfPlaying If an animation is already playing then ignore this call. Default false. - * @param startFrame Optionally start the animation playing from this frame index. Default 0. - */ - play(key: string, ignoreIfPlaying?: boolean, startFrame?: integer): Phaser.GameObjects.Sprite; - - /** - * Build a JSON representation of this Sprite. - */ - toJSON(): Phaser.Types.GameObjects.JSONGameObject; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * 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:** If the font you wish to use has a space or digit in its name, such as - * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes, either - * when creating the Text object, or when setting the font via `setFont` or `setFontFamily`. I.e.: - * - * ```javascript - * this.add.text(0, 0, 'Hello World', { fontFamily: '"Roboto Condensed"' }); - * ``` - * - * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all - * quoted properly, too: - * - * ```javascript - * this.add.text(0, 0, 'Hello World', { fontFamily: 'Verdana, "Times New Roman", Tahoma, serif' }); - * ``` - * - * You can only display fonts that are currently loaded and available to the browser: therefore fonts must - * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, - * or have the fonts ready 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 implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Crop, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param text The text this Text object will display. - * @param style The text style configuration object. - */ - constructor(scene: Phaser.Scene, x: number, y: number, text: string | string[], style: Phaser.Types.GameObjects.Text.TextStyle); - - /** - * Returns an object containing dimensions of the Text object. - * @param text The Text object to calculate the size from. - * @param size The Text metrics to use when calculating the size. - * @param lines The lines of text to calculate the size from. - */ - static GetTextSize(text: Phaser.GameObjects.Text, size: Phaser.Types.GameObjects.Text.TextMetrics, lines: any[]): object; - - /** - * Calculates the ascent, descent and fontSize of a given font style. - * @param textStyle The TextStyle object to measure. - */ - static MeasureText(textStyle: Phaser.GameObjects.TextStyle): Phaser.Types.GameObjects.Text.TextMetrics; - - /** - * The renderer in use by this Text object. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * The canvas element that the text is rendered to. - */ - canvas: HTMLCanvasElement; - - /** - * The context of the canvas element that the text is rendered to. - */ - context: CanvasRenderingContext2D; - - /** - * The Text Style object. - * - * Manages the style of this Text object. - */ - style: Phaser.GameObjects.TextStyle; - - /** - * Whether to automatically round line positions. - */ - autoRound: boolean; - - /** - * The Regular Expression that is used to split the text up into lines, in - * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. - * You can change this RegExp to be anything else that you may need. - */ - splitRegExp: object; - - /** - * Specify a padding value which is added to the line width and height when calculating the Text size. - * Allows you to add extra spacing if the browser is unable to accurately determine the true font dimensions. - */ - padding: Object; - - /** - * The width of this Text object. - */ - width: number; - - /** - * The height of this Text object. - */ - height: number; - - /** - * The line spacing value. - * This value is added to the font height to calculate the overall line height. - * Only has an effect if this Text object contains multiple lines of text. - * - * If you update this property directly, instead of using the `setLineSpacing` method, then - * be sure to call `updateText` after, or you won't see the change reflected in the Text object. - */ - lineSpacing: number; - - /** - * Whether the text or its settings have changed and need updating. - */ - dirty: boolean; - - /** - * Initialize right to left text. - */ - initRTL(): void; - - /** - * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal - * bounds. - * @param text The text to perform word wrap detection against. - */ - runWordWrap(text: string): string; - - /** - * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal - * bounds. Consecutive spaces will be collapsed and replaced with a single space. Lines will be - * trimmed of white space before processing. Throws an error if wordWrapWidth is less than a - * single character. - * @param text The text to perform word wrap detection against. - * @param context The Canvas Rendering Context. - * @param wordWrapWidth The word wrap width. - */ - advancedWordWrap(text: string, context: CanvasRenderingContext2D, wordWrapWidth: number): string; - - /** - * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal - * bounds. Spaces are not collapsed and whitespace is not trimmed. - * @param text The text to perform word wrap detection against. - * @param context The Canvas Rendering Context. - * @param wordWrapWidth The word wrap width. - */ - basicWordWrap(text: string, context: CanvasRenderingContext2D, wordWrapWidth: number): string; - - /** - * Runs the given text through this Text objects word wrapping and returns the results as an - * array, where each element of the array corresponds to a wrapped line of text. - * @param text The text for which the wrapping will be calculated. If unspecified, the Text objects current text will be used. - */ - getWrappedText(text: string): string[]; - - /** - * Set the text to display. - * - * An array of strings will be joined with `\n` line breaks. - * @param value The string, or array of strings, to be set as the content of this Text object. - */ - setText(value: string | string[]): Phaser.GameObjects.Text; - - /** - * Set the text style. - * @param style The style settings to set. - */ - setStyle(style: object): Phaser.GameObjects.Text; - - /** - * 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:** If the font you wish to use has a space or digit in its name, such as - * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: - * - * ```javascript - * Text.setFont('"Roboto Condensed"'); - * ``` - * - * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all - * quoted properly, too: - * - * ```javascript - * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); - * ``` - * @param font The font family or font settings to set. - */ - setFont(font: string): Phaser.GameObjects.Text; - - /** - * Set the font family. - * - * **Important:** If the font you wish to use has a space or digit in its name, such as - * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: - * - * ```javascript - * Text.setFont('"Roboto Condensed"'); - * ``` - * - * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all - * quoted properly, too: - * - * ```javascript - * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); - * ``` - * @param family The font family. - */ - setFontFamily(family: string): Phaser.GameObjects.Text; - - /** - * Set the font size. - * @param size The font size. - */ - setFontSize(size: number): Phaser.GameObjects.Text; - - /** - * Set the font style. - * @param style The font style. - */ - setFontStyle(style: string): Phaser.GameObjects.Text; - - /** - * Set a fixed width and height for the text. - * - * Pass in `0` for either of these parameters to disable fixed width or height respectively. - * @param width The fixed width to set. `0` disables fixed width. - * @param height The fixed height to set. `0` disables fixed height. - */ - setFixedSize(width: number, height: number): Phaser.GameObjects.Text; - - /** - * Set the background color. - * @param color The background color. - */ - setBackgroundColor(color: string): Phaser.GameObjects.Text; - - /** - * 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. - * @param color The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. - */ - setFill(color: string | any): Phaser.GameObjects.Text; - - /** - * Set the text fill color. - * @param color The text fill color. - */ - setColor(color: string): Phaser.GameObjects.Text; - - /** - * Set the stroke settings. - * @param color The stroke color. - * @param thickness The stroke thickness. - */ - setStroke(color: string, thickness: number): Phaser.GameObjects.Text; - - /** - * Set the shadow settings. - * @param x The horizontal shadow offset. Default 0. - * @param y The vertical shadow offset. Default 0. - * @param color The shadow color. Default '#000'. - * @param blur The shadow blur radius. Default 0. - * @param shadowStroke Whether to stroke the shadow. Default false. - * @param shadowFill Whether to fill the shadow. Default true. - */ - setShadow(x?: number, y?: number, color?: string, blur?: number, shadowStroke?: boolean, shadowFill?: boolean): Phaser.GameObjects.Text; - - /** - * Set the shadow offset. - * @param x The horizontal shadow offset. - * @param y The vertical shadow offset. - */ - setShadowOffset(x: number, y: number): Phaser.GameObjects.Text; - - /** - * Set the shadow color. - * @param color The shadow color. - */ - setShadowColor(color: string): Phaser.GameObjects.Text; - - /** - * Set the shadow blur radius. - * @param blur The shadow blur radius. - */ - setShadowBlur(blur: number): Phaser.GameObjects.Text; - - /** - * Enable or disable shadow stroke. - * @param enabled Whether shadow stroke is enabled or not. - */ - setShadowStroke(enabled: boolean): Phaser.GameObjects.Text; - - /** - * Enable or disable shadow fill. - * @param enabled Whether shadow fill is enabled or not. - */ - setShadowFill(enabled: boolean): Phaser.GameObjects.Text; - - /** - * Set the width (in pixels) to use for wrapping lines. Pass in null to remove wrapping by width. - * @param width The maximum width of a line in pixels. Set to null to remove wrapping. - * @param useAdvancedWrap Whether or not to use the advanced wrapping - * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, - * spaces and whitespace are left as is. Default false. - */ - setWordWrapWidth(width: number, useAdvancedWrap?: boolean): Phaser.GameObjects.Text; - - /** - * Set a custom callback for wrapping lines. Pass in null to remove wrapping by callback. - * @param callback A custom function that will be responsible for wrapping the - * text. It will receive two arguments: text (the string to wrap), textObject (this Text - * instance). It should return the wrapped lines either as an array of lines or as a string with - * newline characters in place to indicate where breaks should happen. - * @param scope The scope that will be applied when the callback is invoked. Default null. - */ - setWordWrapCallback(callback: TextStyleWordWrapCallback, scope?: object): Phaser.GameObjects.Text; - - /** - * Set the alignment of the text in this Text object. - * - * The argument can be one of: `left`, `right`, `center` or `justify`. - * - * Alignment only works if the Text object has more than one line of text. - * @param align The text alignment for multi-line text. Default 'left'. - */ - setAlign(align?: string): Phaser.GameObjects.Text; - - /** - * Set the resolution used by this Text object. - * - * By default it will be set to match the resolution set in the Game Config, - * but you can override it via this method, or by specifying it in the Text style configuration object. - * - * It allows for much clearer text on High DPI devices, at the cost of memory because it uses larger - * internal Canvas textures for the Text. - * - * Therefore, please use with caution, as the more high res Text you have, the more memory it uses. - * @param value The resolution for this Text object to use. - */ - setResolution(value: number): Phaser.GameObjects.Text; - - /** - * Sets the line spacing value. - * - * This value is _added_ to the height of the font when calculating the overall line height. - * This only has an effect if this Text object consists of multiple lines of text. - * @param value The amount to add to the font height to achieve the overall line height. - */ - setLineSpacing(value: number): Phaser.GameObjects.Text; - - /** - * Set the text padding. - * - * 'left' can be an object. - * - * If only 'left' and 'top' are given they are treated as 'x' and 'y'. - * @param left The left padding value, or a padding config object. - * @param top The top padding value. - * @param right The right padding value. - * @param bottom The bottom padding value. - */ - setPadding(left: number | Phaser.Types.GameObjects.Text.TextPadding, top: number, right: number, bottom: number): Phaser.GameObjects.Text; - - /** - * Set the maximum number of lines to draw. - * @param max The maximum number of lines to draw. Default 0. - */ - setMaxLines(max?: integer): Phaser.GameObjects.Text; - - /** - * Update the displayed text. - */ - updateText(): Phaser.GameObjects.Text; - - /** - * Get the current text metrics. - */ - getTextMetrics(): object; - - /** - * The text string being rendered by this Text Game Object. - */ - text: string; - - /** - * Build a JSON representation of the Text object. - */ - toJSON(): Phaser.Types.GameObjects.JSONGameObject; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A TextStyle class manages all of the style settings for a Text object. - * - * Text Game Objects create a TextStyle instance automatically, which is - * accessed via the `Text.style` property. You do not normally need to - * instantiate one yourself. - */ - class TextStyle { - /** - * - * @param text The Text object that this TextStyle is styling. - * @param style The style settings to set. - */ - constructor(text: Phaser.GameObjects.Text, style: Phaser.Types.GameObjects.Text.TextStyle); - - /** - * The Text object that this TextStyle is styling. - */ - parent: Phaser.GameObjects.Text; - - /** - * The font family. - */ - fontFamily: string; - - /** - * The font size. - */ - fontSize: string; - - /** - * The font style. - */ - fontStyle: string; - - /** - * The background color. - */ - backgroundColor: string; - - /** - * The text fill color. - */ - color: string; - - /** - * The text stroke color. - */ - stroke: string; - - /** - * The text stroke thickness. - */ - strokeThickness: number; - - /** - * The horizontal shadow offset. - */ - shadowOffsetX: number; - - /** - * The vertical shadow offset. - */ - shadowOffsetY: number; - - /** - * The shadow color. - */ - shadowColor: string; - - /** - * The shadow blur radius. - */ - shadowBlur: number; - - /** - * Whether shadow stroke is enabled or not. - */ - shadowStroke: boolean; - - /** - * Whether shadow fill is enabled or not. - */ - shadowFill: boolean; - - /** - * The text alignment. - */ - align: string; - - /** - * The maximum number of lines to draw. - */ - maxLines: integer; - - /** - * The fixed width of the text. - * - * `0` means no fixed with. - */ - fixedWidth: number; - - /** - * The fixed height of the text. - * - * `0` means no fixed height. - */ - fixedHeight: number; - - /** - * The resolution the text is rendered to its internal canvas at. - * The default is 0, which means it will use the resolution set in the Game Config. - */ - resolution: number; - - /** - * Whether the text should render right to left. - */ - rtl: boolean; - - /** - * The test string to use when measuring the font. - */ - testString: string; - - /** - * The amount of horizontal padding added to the width of the text when calculating the font metrics. - */ - baselineX: number; - - /** - * The amount of vertical padding added to the height of the text when calculating the font metrics. - */ - baselineY: number; - - /** - * Set the text style. - * @param style The style settings to set. - * @param updateText Whether to update the text immediately. Default true. - * @param setDefaults Use the default values is not set, or the local values. Default false. - */ - setStyle(style: Phaser.Types.GameObjects.Text.TextStyle, updateText?: boolean, setDefaults?: boolean): Phaser.GameObjects.Text; - - /** - * Synchronize the font settings to the given Canvas Rendering Context. - * @param canvas The Canvas Element. - * @param context The Canvas Rendering Context. - */ - syncFont(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): void; - - /** - * Synchronize the text style settings to the given Canvas Rendering Context. - * @param canvas The Canvas Element. - * @param context The Canvas Rendering Context. - */ - syncStyle(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): void; - - /** - * Synchronize the shadow settings to the given Canvas Rendering Context. - * @param context The Canvas Rendering Context. - * @param enabled Whether shadows are enabled or not. - */ - syncShadow(context: CanvasRenderingContext2D, enabled: boolean): void; - - /** - * Update the style settings for the parent Text object. - * @param recalculateMetrics Whether to recalculate font and text metrics. - */ - update(recalculateMetrics: boolean): Phaser.GameObjects.Text; - - /** - * 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. - * @param font The font family or font settings to set. - * @param updateText Whether to update the text immediately. Default true. - */ - setFont(font: string | object, updateText?: boolean): Phaser.GameObjects.Text; - - /** - * Set the font family. - * @param family The font family. - */ - setFontFamily(family: string): Phaser.GameObjects.Text; - - /** - * Set the font style. - * @param style The font style. - */ - setFontStyle(style: string): Phaser.GameObjects.Text; - - /** - * Set the font size. - * @param size The font size. - */ - setFontSize(size: number | string): Phaser.GameObjects.Text; - - /** - * Set the test string to use when measuring the font. - * @param string The test string to use when measuring the font. - */ - setTestString(string: string): Phaser.GameObjects.Text; - - /** - * Set a fixed width and height for the text. - * - * Pass in `0` for either of these parameters to disable fixed width or height respectively. - * @param width The fixed width to set. - * @param height The fixed height to set. - */ - setFixedSize(width: number, height: number): Phaser.GameObjects.Text; - - /** - * Set the background color. - * @param color The background color. - */ - setBackgroundColor(color: string): Phaser.GameObjects.Text; - - /** - * Set the text fill color. - * @param color The text fill color. - */ - setFill(color: string): Phaser.GameObjects.Text; - - /** - * Set the text fill color. - * @param color The text fill color. - */ - setColor(color: string): Phaser.GameObjects.Text; - - /** - * Set the resolution used by the Text object. - * - * By default it will be set to match the resolution set in the Game Config, - * but you can override it via this method. It allows for much clearer text on High DPI devices, - * at the cost of memory because it uses larger internal Canvas textures for the Text. - * - * Please use with caution, as the more high res Text you have, the more memory it uses up. - * @param value The resolution for this Text object to use. - */ - setResolution(value: number): Phaser.GameObjects.Text; - - /** - * Set the stroke settings. - * @param color The stroke color. - * @param thickness The stroke thickness. - */ - setStroke(color: string, thickness: number): Phaser.GameObjects.Text; - - /** - * Set the shadow settings. - * - * Calling this method always re-measures the parent Text object, - * so only call it when you actually change the shadow settings. - * @param x The horizontal shadow offset. Default 0. - * @param y The vertical shadow offset. Default 0. - * @param color The shadow color. Default '#000'. - * @param blur The shadow blur radius. Default 0. - * @param shadowStroke Whether to stroke the shadow. Default false. - * @param shadowFill Whether to fill the shadow. Default true. - */ - setShadow(x?: number, y?: number, color?: string, blur?: number, shadowStroke?: boolean, shadowFill?: boolean): Phaser.GameObjects.Text; - - /** - * Set the shadow offset. - * @param x The horizontal shadow offset. Default 0. - * @param y The vertical shadow offset. Default 0. - */ - setShadowOffset(x?: number, y?: number): Phaser.GameObjects.Text; - - /** - * Set the shadow color. - * @param color The shadow color. Default '#000'. - */ - setShadowColor(color?: string): Phaser.GameObjects.Text; - - /** - * Set the shadow blur radius. - * @param blur The shadow blur radius. Default 0. - */ - setShadowBlur(blur?: number): Phaser.GameObjects.Text; - - /** - * Enable or disable shadow stroke. - * @param enabled Whether shadow stroke is enabled or not. - */ - setShadowStroke(enabled: boolean): Phaser.GameObjects.Text; - - /** - * Enable or disable shadow fill. - * @param enabled Whether shadow fill is enabled or not. - */ - setShadowFill(enabled: boolean): Phaser.GameObjects.Text; - - /** - * Set the width (in pixels) to use for wrapping lines. - * - * Pass in null to remove wrapping by width. - * @param width The maximum width of a line in pixels. Set to null to remove wrapping. - * @param useAdvancedWrap Whether or not to use the advanced wrapping - * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, - * spaces and whitespace are left as is. Default false. - */ - setWordWrapWidth(width: number, useAdvancedWrap?: boolean): Phaser.GameObjects.Text; - - /** - * Set a custom callback for wrapping lines. - * - * Pass in null to remove wrapping by callback. - * @param callback A custom function that will be responsible for wrapping the - * text. It will receive two arguments: text (the string to wrap), textObject (this Text - * instance). It should return the wrapped lines either as an array of lines or as a string with - * newline characters in place to indicate where breaks should happen. - * @param scope The scope that will be applied when the callback is invoked. Default null. - */ - setWordWrapCallback(callback: TextStyleWordWrapCallback, scope?: object): Phaser.GameObjects.Text; - - /** - * Set the alignment of the text in this Text object. - * - * The argument can be one of: `left`, `right`, `center` or `justify`. - * - * Alignment only works if the Text object has more than one line of text. - * @param align The text alignment for multi-line text. Default 'left'. - */ - setAlign(align?: string): Phaser.GameObjects.Text; - - /** - * Set the maximum number of lines to draw. - * @param max The maximum number of lines to draw. Default 0. - */ - setMaxLines(max?: integer): Phaser.GameObjects.Text; - - /** - * Get the current text metrics. - */ - getTextMetrics(): Phaser.Types.GameObjects.Text.TextMetrics; - - /** - * Build a JSON representation of this Text Style. - */ - toJSON(): object; - - /** - * Destroy this Text Style. - */ - destroy(): void; - - } - - /** - * A TileSprite is a Sprite that has a repeating texture. - * - * The texture can be scrolled and scaled independently of the TileSprite itself. Textures will automatically wrap and - * are designed so that you can create game backdrops using seamless textures as a source. - * - * You shouldn't ever create a TileSprite any larger than your actual canvas size. If you want to create a large repeating background - * that scrolls across the whole map of your game, then you create a TileSprite that fits the canvas size and then use the `tilePosition` - * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will - * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to - * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. - * - * An important note about Tile Sprites and NPOT textures: Internally, TileSprite textures use GL_REPEAT to provide - * seamless repeating of the textures. This, combined with the way in which the textures are handled in WebGL, means - * they need to be POT (power-of-two) sizes in order to wrap. If you provide a NPOT (non power-of-two) texture to a - * TileSprite it will generate a POT sized canvas and draw your texture to it, scaled up to the POT size. It's then - * scaled back down again during rendering to the original dimensions. While this works, in that it allows you to use - * any size texture for a Tile Sprite, it does mean that NPOT textures are going to appear anti-aliased when rendered, - * due to the interpolation that took place when it was resized into a POT texture. This is especially visible in - * pixel art graphics. If you notice it and it becomes an issue, the only way to avoid it is to ensure that you - * provide POT textures for Tile Sprites. - */ - class TileSprite extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Crop, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param width The width of the Game Object. If zero it will use the size of the texture frame. - * @param height The height of the Game Object. If zero it will use the size of the texture frame. - * @param textureKey The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frameKey An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, width: integer, height: integer, textureKey: string, frameKey?: string | integer); - - /** - * Whether the Tile Sprite has changed in some way, requiring an re-render of its tile texture. - * - * Such changes include the texture frame and scroll position of the Tile Sprite. - */ - dirty: boolean; - - /** - * The renderer in use by this Tile Sprite. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * The Canvas element that the TileSprite renders its fill pattern in to. - * Only used in Canvas mode. - */ - canvas: HTMLCanvasElement; - - /** - * The Context of the Canvas element that the TileSprite renders its fill pattern in to. - * Only used in Canvas mode. - */ - context: CanvasRenderingContext2D; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * The next power of two value from the width of the Fill Pattern frame. - */ - potWidth: integer; - - /** - * The next power of two value from the height of the Fill Pattern frame. - */ - potHeight: integer; - - /** - * The Canvas that the TileSprites texture is rendered to. - * This is used to create a WebGL texture from. - */ - fillCanvas: HTMLCanvasElement; - - /** - * The Canvas Context used to render the TileSprites texture. - */ - fillContext: CanvasRenderingContext2D; - - /** - * The texture that the Tile Sprite is rendered to, which is then rendered to a Scene. - * In WebGL this is a WebGLTexture. In Canvas it's a Canvas Fill Pattern. - */ - fillPattern: WebGLTexture | CanvasPattern; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * @param frame The name or index of the frame within the Texture. - */ - setFrame(frame: string | integer): this; - - /** - * Sets {@link Phaser.GameObjects.TileSprite#tilePositionX} and {@link Phaser.GameObjects.TileSprite#tilePositionY}. - * @param x The x position of this sprite's tiling texture. - * @param y The y position of this sprite's tiling texture. - */ - setTilePosition(x?: number, y?: number): this; - - /** - * Sets {@link Phaser.GameObjects.TileSprite#tileScaleX} and {@link Phaser.GameObjects.TileSprite#tileScaleY}. - * @param x The horizontal scale of the tiling texture. If not given it will use the current `tileScaleX` value. - * @param y The vertical scale of the tiling texture. If not given it will use the `x` value. Default x. - */ - setTileScale(x?: number, y?: number): this; - - /** - * Internal destroy handler, called as part of the destroy process. - */ - protected preDestroy(): void; - - /** - * The horizontal scroll position of the Tile Sprite. - */ - tilePositionX: number; - - /** - * The vertical scroll position of the Tile Sprite. - */ - tilePositionY: number; - - /** - * The horizontal scale of the Tile Sprite texture. - */ - tileScaleX: number; - - /** - * The vertical scale of the Tile Sprite texture. - */ - tileScaleY: number; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * The Update List plugin. - * - * Update Lists belong to a Scene and maintain the list Game Objects to be updated every frame. - * - * Some or all of these Game Objects may also be part of the Scene's [Display List]{@link Phaser.GameObjects.DisplayList}, for Rendering. - */ - class UpdateList extends Phaser.Structs.ProcessQueue { - /** - * - * @param scene The Scene that the Update List belongs to. - */ - constructor(scene: Phaser.Scene); - - /** - * The Scene that the Update List belongs to. - */ - scene: Phaser.Scene; - - /** - * The Scene's Systems. - */ - systems: Phaser.Scenes.Systems; - - /** - * The update step. - * - * Pre-updates every active Game Object in the list. - * @param time The current timestamp. - * @param delta The delta time elapsed since the last frame. - */ - sceneUpdate(time: number, delta: number): void; - - /** - * The Scene that owns this plugin is shutting down. - * - * We need to kill and reset all internal properties as well as stop listening to Scene events. - */ - shutdown(): void; - - /** - * The Scene that owns this plugin is being destroyed. - * - * We need to shutdown and then kill off all external references. - */ - destroy(): void; - - } - - /** - * A Video Game Object. - * - * This Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, - * or playing a video based on a given URL. Videos can be either local, or streamed. - * - * ```javascript - * preload () { - * this.load.video('pixar', 'nemo.mp4'); - * } - * - * create () { - * this.add.video(400, 300, 'pixar'); - * } - * ``` - * - * 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. - * - * ### 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, ahd 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', 'loadeddata', false, true); - * } - * ``` - * - * The 5th 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. - * - * Note that due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. - * - * 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 implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.TextureCrop, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param key Optional key of the Video this Game Object will play, as stored in the Video Cache. - */ - constructor(scene: Phaser.Scene, x: number, y: number, key?: string); - - /** - * A reference to the HTML Video Element this Video Game Object is playing. - * Will be `null` until a video is loaded for playback. - */ - video: HTMLVideoElement; - - /** - * The Phaser Texture this Game Object is using to render the video to. - * Will be `null` until a video is loaded for playback. - */ - videoTexture: Phaser.Textures.Texture; - - /** - * A reference to the TextureSource belong to the `videoTexture` Texture object. - * Will be `null` until a video is loaded for playback. - */ - videoTextureSource: Phaser.Textures.TextureSource; - - /** - * A Phaser CanvasTexture instance that holds the most recent snapshot taken from the video. - * This will only be set if `snapshot` or `snapshotArea` have been called, and will be `null` until that point. - */ - snapshotTexture: Phaser.Textures.CanvasTexture; - - /** - * If you have saved this video to a texture via the `saveTexture` method, this controls if the video - * is rendered with `flipY` in WebGL or not. You often need to set this if you wish to use the video texture - * as the input source for a shader. If you find your video is appearing upside down within a shader or - * custom pipeline, flip this property. - */ - flipY: boolean; - - /** - * An internal flag holding the current state of the video lock, should document interaction be required - * before playback can begin. - */ - touchLocked: boolean; - - /** - * Should the video auto play when document interaction is required and happens? - */ - playWhenUnlocked: boolean; - - /** - * When starting playback of a video Phaser will monitor its `readyState` using a `setTimeout` call. - * The `setTimeout` happens once every `Video.retryInterval` ms. It will carry on monitoring the video - * state in this manner until the `retryLimit` is reached and then abort. - */ - retryLimit: integer; - - /** - * The current retry attempt. - */ - retry: integer; - - /** - * The number of ms between each retry while monitoring the ready state of a downloading video. - */ - retryInterval: integer; - - /** - * An object containing in and out markers for sequence playback. - */ - markers: any; - - /** - * Should the Video element that this Video is using, be removed from the DOM - * when this Video is destroyed? - */ - removeVideoElementOnDestroy: boolean; - - /** - * 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', 'loadeddata', false, true); - * } - * ``` - * - * The 5th 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. - * @param loop Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats. Default false. - * @param markerIn Optional in marker time, in seconds, for playback of a sequence of the video. - * @param markerOut Optional out marker time, in seconds, for playback of a sequence of the video. - */ - play(loop?: boolean, markerIn?: integer, markerOut?: integer): this; - - /** - * This method allows you to change the source of the current video element. It works by first stopping the - * current video, if playing. Then deleting the video texture, if one has been created. Finally, it makes a - * new video texture and starts playback of the new source through the existing video element. - * - * The reason you may wish to do this is because videos that require interaction to unlock, remain in an unlocked - * state, even if you change the source of the video. By changing the source to a new video you avoid having to - * go through the unlock process again. - * @param key The key of the Video this Game Object will swap to playing, as stored in the Video Cache. - * @param autoplay Should the video start playing immediately, once the swap is complete? Default true. - * @param loop Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats. Default false. - * @param markerIn Optional in marker time, in seconds, for playback of a sequence of the video. - * @param markerOut Optional out marker time, in seconds, for playback of a sequence of the video. - */ - changeSource(key: string, autoplay?: boolean, loop?: boolean, markerIn?: integer, markerOut?: integer): this; - - /** - * 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. - * @param key A unique name to give this marker. - * @param markerIn The time, in seconds, representing the start of this marker. - * @param markerOut The time, in seconds, representing the end of this marker. - */ - addMarker(key: string, markerIn: integer, markerOut: integer): this; - - /** - * 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. - * @param key The name of the marker sequence to play. - * @param loop Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats. Default false. - */ - playMarker(key: string, loop?: boolean): this; - - /** - * Removes a previously set marker from this video. - * - * If the marker is currently playing it will _not_ stop playback. - * @param key The name of the marker to remove. - */ - removeMarker(key: string): this; - - /** - * Takes a snapshot of the current frame of the video and renders it to a CanvasTexture object, - * which is then returned. You can optionally resize the grab by passing a width and height. - * - * This method returns a reference to the `Video.snapshotTexture` object. Calling this method - * multiple times will overwrite the previous snapshot with the most recent one. - * @param width The width of the resulting CanvasTexture. - * @param height The height of the resulting CanvasTexture. - */ - snapshot(width?: integer, height?: integer): Phaser.Textures.CanvasTexture; - - /** - * Takes a snapshot of the specified area of the current frame of the video and renders it to a CanvasTexture object, - * which is then returned. You can optionally resize the grab by passing a different `destWidth` and `destHeight`. - * - * This method returns a reference to the `Video.snapshotTexture` object. Calling this method - * multiple times will overwrite the previous snapshot with the most recent one. - * @param x The horizontal location of the top-left of the area to grab from. Default 0. - * @param y The vertical location of the top-left of the area to grab from. Default 0. - * @param srcWidth The width of area to grab from the video. If not given it will grab the full video dimensions. - * @param srcHeight The height of area to grab from the video. If not given it will grab the full video dimensions. - * @param destWidth The destination width of the grab, allowing you to resize it. - * @param destHeight The destination height of the grab, allowing you to resize it. - */ - snapshotArea(x?: integer, y?: integer, srcWidth?: integer, srcHeight?: integer, destWidth?: integer, destHeight?: integer): Phaser.Textures.CanvasTexture; - - /** - * Stores a copy of this Videos `snapshotTexture` in the Texture Manager using the given key. - * - * This texture is created when the `snapshot` or `snapshotArea` methods are called. - * - * After doing this, any texture based Game Object, such as a Sprite, can use the contents of the - * snapshot by using the texture key: - * - * ```javascript - * var vid = this.add.video(0, 0, 'intro'); - * - * vid.snapshot(); - * - * vid.saveSnapshotTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * Updating the contents of the `snapshotTexture`, for example by calling `snapshot` again, - * will automatically update _any_ Game Object that is using it as a texture. - * Calling `saveSnapshotTexture` again will not save another copy of the same texture, - * it will just rename the existing one. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame. - * @param key The unique key to store the texture as within the global Texture Manager. - */ - saveSnapshotTexture(key: string): Phaser.Textures.CanvasTexture; - - /** - * Loads a Video from the given URL, ready for playback with the `Video.play` method. - * - * You can control at what point the browser determines the video as being ready for playback via - * the `loadEvent` parameter. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement - * for more details. - * @param url The URL of the video to load or be streamed. - * @param loadEvent The load event to listen for. Either `loadeddata`, `canplay` or `canplaythrough`. Default 'loadeddata'. - * @param noAudio Does the video have an audio track? If not you can enable auto-playing on it. Default false. - */ - loadURL(url: string, loadEvent?: string, noAudio?: boolean): this; - - /** - * Called when the video emits a `playing` event during load. - * - * This is only listened for if the browser doesn't support Promises. - */ - playHandler(): void; - - /** - * Called when the video completes playback, i.e. reaches an `ended` state. - * - * This will never happen if the video is coming from a live stream, where the duration is `Infinity`. - */ - completeHandler(): void; - - /** - * Called when the video emits a `timeUpdate` event during playback. - * - * This event is too slow and irregular to be used for actual video timing or texture updating, - * but we can use it to determine if a video has looped. - */ - timeUpdateHandler(): void; - - /** - * Internal method that is called when enough video data has been received in order to create a texture - * from it. The texture is assigned to the `Video.videoTexture` property and given a base frame that - * encompases the whole video size. - */ - updateTexture(): void; - - /** - * Returns the key of the currently played video, as stored in the Video Cache. - * If the video did not come from the cache this will return an empty string. - */ - getVideoKey(): string; - - /** - * 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. - * @param value The point in the video to seek to. A value between 0 and 1. - */ - seekTo(value: number): this; - - /** - * A double-precision floating-point value indicating the current playback time in seconds. - * If the media has not started to play and has not been seeked, this value is the media's initial playback time. - */ - getCurrentTime(): number; - - /** - * 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. - * @param 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. - */ - setCurrentTime(value: string | number): this; - - /** - * Returns a boolean indicating if this Video is currently seeking, or not. - */ - isSeeking(): boolean; - - /** - * Returns the current progress of the video. Progress is defined as a value between 0 (the start) - * and 1 (the end). - * - * Progress can only be returned if the video has a duration, otherwise it will always return zero. - */ - getProgress(): number; - - /** - * A double-precision floating-point value which indicates the duration (total length) of the media in seconds, - * on the media's timeline. If no media is present on the element, or the media is not valid, the returned value is NaN. - * - * If the media has no known end (such as for live streams of unknown duration, web radio, media incoming from WebRTC, - * and so forth), this value is +Infinity. - */ - getDuration(): number; - - /** - * Sets the muted state of the currently playing video, if one is loaded. - * @param value The mute value. `true` if the video should be muted, otherwise `false`. Default true. - */ - setMute(value?: boolean): this; - - /** - * Returns a boolean indicating if this Video is currently muted. - */ - isMuted(): boolean; - - /** - * Sets the paused state of the currently loaded video. - * - * If the video is playing, calling this method with `true` will pause playback. - * If the video is paused, calling this method with `false` will resume playback. - * - * If no video is loaded, this method does nothing. - * @param value The paused value. `true` if the video should be paused, `false` to resume it. Default true. - */ - setPaused(value?: boolean): this; - - /** - * Returns a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). - */ - getVolume(): number; - - /** - * Sets the volume of the currently playing video. - * - * The value given is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). - * @param value A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). Default 1. - */ - setVolume(value?: number): this; - - /** - * Returns a double that indicates the rate at which the media is being played back. - */ - getPlaybackRate(): number; - - /** - * Sets the playback rate of the current video. - * - * The value given is a double that indicates the rate at which the media is being played back. - * @param rate A double that indicates the rate at which the media is being played back. - */ - setPlaybackRate(rate?: number): this; - - /** - * Returns a boolean which indicates whether the media element should start over when it reaches the end. - */ - getLoop(): boolean; - - /** - * Sets the loop state of the current video. - * - * The value given is a boolean which indicates whether the media element will start over when it reaches the end. - * - * Not all videos can loop, for example live streams. - * - * Please note that not all browsers support _seamless_ video looping for all encoding formats. - * @param value A boolean which indicates whether the media element will start over when it reaches the end. Default true. - */ - setLoop(value?: boolean): this; - - /** - * Returns a boolean which indicates whether the video is currently playing. - */ - isPlaying(): boolean; - - /** - * Returns a boolean which indicates whether the video is currently paused. - */ - isPaused(): boolean; - - /** - * Stores this Video in the Texture Manager using the given key as a dynamic texture, - * which any texture-based Game Object, such as a Sprite, can use as its texture: - * - * ```javascript - * var vid = this.add.video(0, 0, 'intro'); - * - * vid.play(); - * - * vid.saveTexture('doodle'); - * - * this.add.image(400, 300, 'doodle'); - * ``` - * - * The saved texture is automatically updated as the video plays. If you pause this video, - * or change its source, then the saved texture updates instantly. - * - * Calling `saveTexture` again will not save another copy of the same texture, it will just rename the existing one. - * - * By default it will create a single base texture. You can add frames to the texture - * by using the `Texture.add` method. After doing this, you can then allow Game Objects - * to use a specific frame. - * - * If you intend to save the texture so you can use it as the input for a Shader, you may need to set the - * `flipY` parameter to `true` if you find the video renders upside down in your shader. - * @param key The unique key to store the texture as within the global Texture Manager. - * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y` during upload? Default false. - */ - saveTexture(key: string, flipY?: boolean): Phaser.Textures.Texture; - - /** - * Stops the video playing and clears all internal event listeners. - * - * If you only wish to pause playback of the video, and resume it a later time, use the `Video.pause` method instead. - * - * If the video hasn't finished downloading, calling this method will not abort the download. To do that you need to - * call `destroy` instead. - */ - stop(): this; - - /** - * Removes the Video element from the DOM by calling parentNode.removeChild on itself. - * - * Also removes the autoplay and src attributes and nulls the Video reference. - * - * You should not call this method if you were playing a video from the Video Cache that - * you wish to play again in your game, or if another Video object is also using the same - * video. - * - * If you loaded an external video via `Video.loadURL` then you should call this function - * to clear up once you are done with the instance. - */ - removeVideoElement(): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * A Zone Game Object. - * - * A Zone is a non-rendering rectangular Game Object that has a position and size. - * It has no texture and never displays, but does live on the display list and - * can be moved, scaled and rotated like any other Game Object. - * - * Its primary use is for creating Drop Zones and Input Hit Areas and it has a couple of helper methods - * specifically for this. It is also useful for object overlap checks, or as a base for your own - * non-displaying Game Objects. - * The default origin is 0.5, the center of the Zone, the same as with Game Objects. - */ - class Zone extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param width The width of the Game Object. Default 1. - * @param height The height of the Game Object. Default 1. - */ - constructor(scene: Phaser.Scene, x: number, y: number, width?: number, height?: number); - - /** - * The native (un-scaled) width of this Game Object. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - */ - height: number; - - /** - * The Blend Mode of the Game Object. - * Although a Zone never renders, it still has a blend mode to allow it to fit seamlessly into - * display lists without causing a batch flush. - */ - blendMode: integer; - - /** - * The displayed width of this Game Object. - * This value takes into account the scale factor. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * This value takes into account the scale factor. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - * @param resizeInput If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. Default true. - */ - setSize(width: number, height: number, resizeInput?: boolean): Phaser.GameObjects.Zone; - - /** - * Sets the display size of this Game Object. - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): Phaser.GameObjects.Zone; - - /** - * Sets this Zone to be a Circular Drop Zone. - * The circle is centered on this Zones `x` and `y` coordinates. - * @param radius The radius of the Circle that will form the Drop Zone. - */ - setCircleDropZone(radius: number): Phaser.GameObjects.Zone; - - /** - * Sets this Zone to be a Rectangle Drop Zone. - * The rectangle is centered on this Zones `x` and `y` coordinates. - * @param width The width of the rectangle drop zone. - * @param height The height of the rectangle drop zone. - */ - setRectangleDropZone(width: number, height: number): Phaser.GameObjects.Zone; - - /** - * Allows you to define your own Geometry shape to be used as a Drop Zone. - * @param shape A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. - * @param callback A function that will return `true` if the given x/y coords it is sent are within the shape. - */ - setDropZone(shape: object, callback: Phaser.Types.Input.HitAreaCallback): Phaser.GameObjects.Zone; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - } - - namespace Geom { - /** - * A Circle object. - * - * This is a geometry object, containing numerical values and related methods to inspect and modify them. - * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. - * To render a Circle you should look at the capabilities of the Graphics class. - */ - class Circle { - /** - * - * @param x The x position of the center of the circle. Default 0. - * @param y The y position of the center of the circle. Default 0. - * @param radius The radius of the circle. Default 0. - */ - constructor(x?: number, y?: number, radius?: number); - - /** - * Calculates the area of the circle. - * @param circle The Circle to get the area of. - */ - static Area(circle: Phaser.Geom.Circle): number; - - /** - * The geometry constant type of this object: `GEOM_CONST.CIRCLE`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * The x position of the center of the circle. - */ - x: number; - - /** - * The y position of the center of the circle. - */ - y: number; - - /** - * Check to see if the Circle contains the given x / y coordinates. - * @param x The x coordinate to check within the circle. - * @param y The y coordinate to check within the circle. - */ - contains(x: number, y: number): boolean; - - /** - * 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. - * @param 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 out An object to store the return values in. If not given a Point object will be created. - */ - getPoint(position: number, out?: O): O; - - /** - * 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. - * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. - * @param stepRate Sets the quantity by getting the circumference of the circle and dividing it by the stepRate. - * @param output An array to insert the points in to. If not provided a new array will be created. - */ - getPoints(quantity: integer, stepRate?: number, output?: O): O; - - /** - * Returns a uniformly distributed random point from anywhere within the Circle. - * @param point A Point or point-like object to set the random `x` and `y` values in. - */ - getRandomPoint(point?: O): O; - - /** - * Sets the x, y and radius of this circle. - * @param x The x position of the center of the circle. Default 0. - * @param y The y position of the center of the circle. Default 0. - * @param radius The radius of the circle. Default 0. - */ - setTo(x?: number, y?: number, radius?: number): Phaser.Geom.Circle; - - /** - * Sets this Circle to be empty with a radius of zero. - * Does not change its position. - */ - setEmpty(): Phaser.Geom.Circle; - - /** - * Sets the position of this Circle. - * @param x The x position of the center of the circle. Default 0. - * @param y The y position of the center of the circle. Default 0. - */ - setPosition(x?: number, y?: number): Phaser.Geom.Circle; - - /** - * Checks to see if the Circle is empty: has a radius of zero. - */ - isEmpty(): boolean; - - /** - * The radius of the Circle. - */ - radius: number; - - /** - * The diameter of the Circle. - */ - diameter: number; - - /** - * The left position of the Circle. - */ - left: number; - - /** - * The right position of the Circle. - */ - right: number; - - /** - * The top position of the Circle. - */ - top: number; - - /** - * The bottom position of the Circle. - */ - bottom: number; - - /** - * Returns the circumference of the given Circle. - * @param circle The Circle to get the circumference of. - */ - static Circumference(circle: Phaser.Geom.Circle): number; - - /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @param circle The Circle to get the circumference point on. - * @param angle The angle from the center of the Circle to the circumference to return the point from. Given in radians. - * @param out A Point, or point-like object, to store the results in. If not given a Point will be created. - */ - static CircumferencePoint(circle: Phaser.Geom.Circle, angle: number, out?: O): O; - - /** - * Creates a new Circle instance based on the values contained in the given source. - * @param source The Circle to be cloned. Can be an instance of a Circle or a circle-like object, with x, y and radius properties. - */ - static Clone(source: Phaser.Geom.Circle | object): Phaser.Geom.Circle; - - /** - * Check to see if the Circle contains the given x / y coordinates. - * @param circle The Circle to check. - * @param x The x coordinate to check within the circle. - * @param y The y coordinate to check within the circle. - */ - static Contains(circle: Phaser.Geom.Circle, x: number, y: number): boolean; - - /** - * Check to see if the Circle contains the given Point object. - * @param circle The Circle to check. - * @param point The Point object to check if it's within the Circle or not. - */ - static ContainsPoint(circle: Phaser.Geom.Circle, point: Phaser.Geom.Point | object): boolean; - - /** - * Check to see if the Circle contains all four points of the given Rectangle object. - * @param circle The Circle to check. - * @param rect The Rectangle object to check if it's within the Circle or not. - */ - static ContainsRect(circle: Phaser.Geom.Circle, rect: Phaser.Geom.Rectangle | object): boolean; - - /** - * Copies the `x`, `y` and `radius` properties from the `source` Circle - * into the given `dest` Circle, then returns the `dest` Circle. - * @param source The source Circle to copy the values from. - * @param dest The destination Circle to copy the values to. - */ - static CopyFrom(source: Phaser.Geom.Circle, dest: O): O; - - /** - * Compares the `x`, `y` and `radius` properties of the two given Circles. - * Returns `true` if they all match, otherwise returns `false`. - * @param circle The first Circle to compare. - * @param toCompare The second Circle to compare. - */ - static Equals(circle: Phaser.Geom.Circle, toCompare: Phaser.Geom.Circle): boolean; - - /** - * Returns the bounds of the Circle object. - * @param circle The Circle to get the bounds from. - * @param out A Rectangle, or rectangle-like object, to store the circle bounds in. If not given a new Rectangle will be created. - */ - static GetBounds(circle: Phaser.Geom.Circle, out?: O): O; - - /** - * 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. - * @param circle The Circle to get the circumference point on. - * @param 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 out An object to store the return values in. If not given a Point object will be created. - */ - static GetPoint(circle: Phaser.Geom.Circle, position: number, out?: O): O; - - /** - * 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. - * @param circle The Circle to get the points from. - * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. - * @param stepRate Sets the quantity by getting the circumference of the circle and dividing it by the stepRate. - * @param output An array to insert the points in to. If not provided a new array will be created. - */ - static GetPoints(circle: Phaser.Geom.Circle, quantity: integer, stepRate?: number, output?: any[]): Phaser.Geom.Point[]; - - /** - * Offsets the Circle by the values given. - * @param circle The Circle to be offset (translated.) - * @param x The amount to horizontally offset the Circle by. - * @param y The amount to vertically offset the Circle by. - */ - static Offset(circle: O, x: number, y: number): O; - - /** - * Offsets the Circle by the values given in the `x` and `y` properties of the Point object. - * @param circle The Circle to be offset (translated.) - * @param point The Point object containing the values to offset the Circle by. - */ - static OffsetPoint(circle: O, point: Phaser.Geom.Point | object): O; - - /** - * Returns a uniformly distributed random point from anywhere within the given Circle. - * @param circle The Circle to get a random point from. - * @param out A Point or point-like object to set the random `x` and `y` values in. - */ - static Random(circle: Phaser.Geom.Circle, out?: O): O; - - } - - /** - * A Circle Geometry object type. - */ - var CIRCLE: integer; - - /** - * An Ellipse Geometry object type. - */ - var ELLIPSE: integer; - - /** - * A Line Geometry object type. - */ - var LINE: integer; - - /** - * A Point Geometry object type. - */ - var POINT: integer; - - /** - * A Polygon Geometry object type. - */ - var POLYGON: integer; - - /** - * A Rectangle Geometry object type. - */ - var RECTANGLE: integer; - - /** - * A Triangle Geometry object type. - */ - var TRIANGLE: integer; - - /** - * An Ellipse object. - * - * This is a geometry object, containing numerical values and related methods to inspect and modify them. - * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. - * To render an Ellipse you should look at the capabilities of the Graphics class. - */ - class Ellipse { - /** - * - * @param x The x position of the center of the ellipse. Default 0. - * @param y The y position of the center of the ellipse. Default 0. - * @param width The width of the ellipse. Default 0. - * @param height The height of the ellipse. Default 0. - */ - constructor(x?: number, y?: number, width?: number, height?: number); - - /** - * Calculates the area of the Ellipse. - * @param ellipse The Ellipse to get the area of. - */ - static Area(ellipse: Phaser.Geom.Ellipse): number; - - /** - * Returns the circumference of the given Ellipse. - * @param ellipse The Ellipse to get the circumference of. - */ - static Circumference(ellipse: Phaser.Geom.Ellipse): number; - - /** - * Returns a Point object containing the coordinates of a point on the circumference of the Ellipse based on the given angle. - * @param ellipse The Ellipse to get the circumference point on. - * @param angle The angle from the center of the Ellipse to the circumference to return the point from. Given in radians. - * @param out A Point, or point-like object, to store the results in. If not given a Point will be created. - */ - static CircumferencePoint(ellipse: Phaser.Geom.Ellipse, angle: number, out?: O): O; - - /** - * Creates a new Ellipse instance based on the values contained in the given source. - * @param source The Ellipse to be cloned. Can be an instance of an Ellipse or a ellipse-like object, with x, y, width and height properties. - */ - static Clone(source: Phaser.Geom.Ellipse): Phaser.Geom.Ellipse; - - /** - * Check to see if the Ellipse contains the given x / y coordinates. - * @param ellipse The Ellipse to check. - * @param x The x coordinate to check within the ellipse. - * @param y The y coordinate to check within the ellipse. - */ - static Contains(ellipse: Phaser.Geom.Ellipse, x: number, y: number): boolean; - - /** - * Check to see if the Ellipse contains the given Point object. - * @param ellipse The Ellipse to check. - * @param point The Point object to check if it's within the Circle or not. - */ - static ContainsPoint(ellipse: Phaser.Geom.Ellipse, point: Phaser.Geom.Point | object): boolean; - - /** - * Check to see if the Ellipse contains all four points of the given Rectangle object. - * @param ellipse The Ellipse to check. - * @param rect The Rectangle object to check if it's within the Ellipse or not. - */ - static ContainsRect(ellipse: Phaser.Geom.Ellipse, rect: Phaser.Geom.Rectangle | object): boolean; - - /** - * Copies the `x`, `y`, `width` and `height` properties from the `source` Ellipse - * into the given `dest` Ellipse, then returns the `dest` Ellipse. - * @param source The source Ellipse to copy the values from. - * @param dest The destination Ellipse to copy the values to. - */ - static CopyFrom(source: Phaser.Geom.Ellipse, dest: O): O; - - /** - * The geometry constant type of this object: `GEOM_CONST.ELLIPSE`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * The x position of the center of the ellipse. - */ - x: number; - - /** - * The y position of the center of the ellipse. - */ - y: number; - - /** - * The width of the ellipse. - */ - width: number; - - /** - * The height of the ellipse. - */ - height: number; - - /** - * Check to see if the Ellipse contains the given x / y coordinates. - * @param x The x coordinate to check within the ellipse. - * @param y The y coordinate to check within the ellipse. - */ - contains(x: number, y: number): boolean; - - /** - * Returns a Point 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 circle. - * @param 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 out An object to store the return values in. If not given a Point object will be created. - */ - getPoint(position: number, out?: O): O; - - /** - * Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse, - * based on the given quantity or stepRate values. - * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. - * @param stepRate Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate. - * @param output An array to insert the points in to. If not provided a new array will be created. - */ - getPoints(quantity: integer, stepRate?: number, output?: O): O; - - /** - * Returns a uniformly distributed random point from anywhere within the given Ellipse. - * @param point A Point or point-like object to set the random `x` and `y` values in. - */ - getRandomPoint(point?: O): O; - - /** - * Sets the x, y, width and height of this ellipse. - * @param x The x position of the center of the ellipse. - * @param y The y position of the center of the ellipse. - * @param width The width of the ellipse. - * @param height The height of the ellipse. - */ - setTo(x: number, y: number, width: number, height: number): Phaser.Geom.Ellipse; - - /** - * Sets this Ellipse to be empty with a width and height of zero. - * Does not change its position. - */ - setEmpty(): Phaser.Geom.Ellipse; - - /** - * Sets the position of this Ellipse. - * @param x The x position of the center of the ellipse. - * @param y The y position of the center of the ellipse. - */ - setPosition(x: number, y: number): Phaser.Geom.Ellipse; - - /** - * Sets the size of this Ellipse. - * Does not change its position. - * @param width The width of the ellipse. - * @param height The height of the ellipse. Default width. - */ - setSize(width: number, height?: number): Phaser.Geom.Ellipse; - - /** - * Checks to see if the Ellipse is empty: has a width or height equal to zero. - */ - isEmpty(): boolean; - - /** - * Returns the minor radius of the ellipse. Also known as the Semi Minor Axis. - */ - getMinorRadius(): number; - - /** - * Returns the major radius of the ellipse. Also known as the Semi Major Axis. - */ - getMajorRadius(): number; - - /** - * The left position of the Ellipse. - */ - left: number; - - /** - * The right position of the Ellipse. - */ - right: number; - - /** - * The top position of the Ellipse. - */ - top: number; - - /** - * The bottom position of the Ellipse. - */ - bottom: number; - - /** - * Compares the `x`, `y`, `width` and `height` properties of the two given Ellipses. - * Returns `true` if they all match, otherwise returns `false`. - * @param ellipse The first Ellipse to compare. - * @param toCompare The second Ellipse to compare. - */ - static Equals(ellipse: Phaser.Geom.Ellipse, toCompare: Phaser.Geom.Ellipse): boolean; - - /** - * Returns the bounds of the Ellipse object. - * @param ellipse The Ellipse to get the bounds from. - * @param out A Rectangle, or rectangle-like object, to store the ellipse bounds in. If not given a new Rectangle will be created. - */ - static GetBounds(ellipse: Phaser.Geom.Ellipse, out?: O): O; - - /** - * Returns a Point 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 circle. - * @param ellipse The Ellipse to get the circumference point on. - * @param 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 out An object to store the return values in. If not given a Point object will be created. - */ - static GetPoint(ellipse: Phaser.Geom.Ellipse, position: number, out?: O): O; - - /** - * Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse, - * based on the given quantity or stepRate values. - * @param ellipse The Ellipse to get the points from. - * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. - * @param stepRate Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate. - * @param out An array to insert the points in to. If not provided a new array will be created. - */ - static GetPoints(ellipse: Phaser.Geom.Ellipse, quantity: integer, stepRate?: number, out?: O): O; - - /** - * Offsets the Ellipse by the values given. - * @param ellipse The Ellipse to be offset (translated.) - * @param x The amount to horizontally offset the Ellipse by. - * @param y The amount to vertically offset the Ellipse by. - */ - static Offset(ellipse: O, x: number, y: number): O; - - /** - * Offsets the Ellipse by the values given in the `x` and `y` properties of the Point object. - * @param ellipse The Ellipse to be offset (translated.) - * @param point The Point object containing the values to offset the Ellipse by. - */ - static OffsetPoint(ellipse: O, point: Phaser.Geom.Point | object): O; - - /** - * Returns a uniformly distributed random point from anywhere within the given Ellipse. - * @param ellipse The Ellipse to get a random point from. - * @param out A Point or point-like object to set the random `x` and `y` values in. - */ - static Random(ellipse: Phaser.Geom.Ellipse, out?: O): O; - - } - - namespace Intersects { - /** - * Checks if two Circles intersect. - * @param circleA The first Circle to check for intersection. - * @param circleB The second Circle to check for intersection. - */ - function CircleToCircle(circleA: Phaser.Geom.Circle, circleB: Phaser.Geom.Circle): boolean; - - /** - * Checks for intersection between a circle and a rectangle. - * @param circle The circle to be checked. - * @param rect The rectangle to be checked. - */ - function CircleToRectangle(circle: Phaser.Geom.Circle, rect: Phaser.Geom.Rectangle): boolean; - - /** - * Checks if two Circles intersect and returns the intersection points as a Point object array. - * @param circleA The first Circle to check for intersection. - * @param circleB The second Circle to check for intersection. - * @param out An optional array in which to store the points of intersection. - */ - function GetCircleToCircle(circleA: Phaser.Geom.Circle, circleB: Phaser.Geom.Circle, out?: any[]): any[]; - - /** - * Checks for intersection between a circle and a rectangle, - * and returns the intersection points as a Point object array. - * @param circle The circle to be checked. - * @param rect The rectangle to be checked. - * @param out An optional array in which to store the points of intersection. - */ - function GetCircleToRectangle(circle: Phaser.Geom.Circle, rect: Phaser.Geom.Rectangle, out?: any[]): any[]; - - /** - * Checks for intersection between the line segment and circle, - * and returns the intersection points as a Point object array. - * @param line The line segment to check. - * @param circle The circle to check against the line. - * @param out An optional array in which to store the points of intersection. - */ - function GetLineToCircle(line: Phaser.Geom.Line, circle: Phaser.Geom.Circle, out?: any[]): any[]; - - /** - * Checks for intersection between the Line and a Rectangle shape, - * and returns the intersection points as a Point object array. - * @param line The Line to check for intersection. - * @param rect The Rectangle to check for intersection. - * @param out An optional array in which to store the points of intersection. - */ - function GetLineToRectangle(line: Phaser.Geom.Line, rect: Phaser.Geom.Rectangle | object, out?: any[]): any[]; - - /** - * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. - * - * If optional `output` parameter is omitted, new Rectangle object is created and returned. If there is intersection, it will contain intersection area. If there is no intersection, it wil be empty Rectangle (all values set to zero). - * - * If Rectangle object is passed as `output` and there is intersection, then intersection area data will be loaded into it and it will be returned. If there is no intersection, it will be returned without any change. - * @param rectA The first Rectangle object. - * @param rectB The second Rectangle object. - * @param output Optional Rectangle object. If given, the intersection data will be loaded into it (in case of no intersection, it will be left unchanged). Otherwise, new Rectangle object will be created and returned with either intersection data or empty (all values set to zero), if there is no intersection. - */ - function GetRectangleIntersection(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, output?: O): O; - - /** - * Checks if two Rectangles intersect and returns the intersection points as a Point object array. - * - * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. As such, the two Rectangles are considered "solid". A Rectangle with no width or no height will never intersect another Rectangle. - * @param rectA The first Rectangle to check for intersection. - * @param rectB The second Rectangle to check for intersection. - * @param out An optional array in which to store the points of intersection. - */ - function GetRectangleToRectangle(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, out?: any[]): any[]; - - /** - * Checks for intersection between Rectangle shape and Triangle shape, - * and returns the intersection points as a Point object array. - * @param rect Rectangle object to test. - * @param triangle Triangle object to test. - * @param out An optional array in which to store the points of intersection. - */ - function GetRectangleToTriangle(rect: Phaser.Geom.Rectangle, triangle: Phaser.Geom.Triangle, out?: any[]): any[]; - - /** - * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. - * - * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. - * @param triangle The Triangle to check for intersection. - * @param circle The Circle to check for intersection. - * @param out An optional array in which to store the points of intersection. - */ - function GetTriangleToCircle(triangle: Phaser.Geom.Triangle, circle: Phaser.Geom.Circle, out?: any[]): any[]; - - /** - * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. - * - * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". - * @param triangle The Triangle to check with. - * @param line The Line to check with. - * @param out An optional array in which to store the points of intersection. - */ - function GetTriangleToLine(triangle: Phaser.Geom.Triangle, line: Phaser.Geom.Line, out?: any[]): any[]; - - /** - * Checks if two Triangles intersect, and returns the intersection points as a Point object array. - * - * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". - * @param triangleA The first Triangle to check for intersection. - * @param triangleB The second Triangle to check for intersection. - * @param out An optional array in which to store the points of intersection. - */ - function GetTriangleToTriangle(triangleA: Phaser.Geom.Triangle, triangleB: Phaser.Geom.Triangle, out?: any[]): any[]; - - /** - * 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). - * @param line The line segment to check. - * @param circle The circle to check against the line. - * @param nearest An optional Point-like object. If given the closest point on the Line where the circle intersects will be stored in this object. - */ - function LineToCircle(line: Phaser.Geom.Line, circle: Phaser.Geom.Circle, nearest?: Phaser.Geom.Point | any): boolean; - - /** - * Checks if two Lines intersect. If the Lines are identical, they will be treated as parallel and thus non-intersecting. - * @param line1 The first Line to check. - * @param line2 The second Line to check. - * @param out A Point in which to optionally store the point of intersection. - */ - function LineToLine(line1: Phaser.Geom.Line, line2: Phaser.Geom.Line, out?: Phaser.Geom.Point): boolean; - - /** - * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like - * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. - * - * An intersection is considered valid if: - * - * The line starts within, or ends within, the Rectangle. - * The line segment intersects one of the 4 rectangle edges. - * - * The for the purposes of this function rectangles are considered 'solid'. - * @param line The Line to check for intersection. - * @param rect The Rectangle to check for intersection. - */ - function LineToRectangle(line: Phaser.Geom.Line, rect: Phaser.Geom.Rectangle | object): boolean; - - /** - * Checks if the 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. - * @param point The point, or point-like object to check. - * @param line The line segment to test for intersection on. - * @param lineThickness The line thickness. Assumes that the line end points are circular. Default 1. - */ - function PointToLine(point: Phaser.Geom.Point | any, line: Phaser.Geom.Line, lineThickness?: number): boolean; - - /** - * Checks if a Point is located on the given line segment. - * @param point The Point to check for intersection. - * @param line The line segment to check for intersection. - */ - function PointToLineSegment(point: Phaser.Geom.Point, line: Phaser.Geom.Line): boolean; - - /** - * Checks if two Rectangles intersect. - * - * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. - * As such, the two Rectangles are considered "solid". - * A Rectangle with no width or no height will never intersect another Rectangle. - * @param rectA The first Rectangle to check for intersection. - * @param rectB The second Rectangle to check for intersection. - */ - function RectangleToRectangle(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle): boolean; - - /** - * Checks for intersection between Rectangle shape and Triangle shape. - * @param rect Rectangle object to test. - * @param triangle Triangle object to test. - */ - function RectangleToTriangle(rect: Phaser.Geom.Rectangle, triangle: Phaser.Geom.Triangle): boolean; - - /** - * Check if rectangle intersects with values. - * @param rect The rectangle object - * @param left The x coordinate of the left of the Rectangle. - * @param right The x coordinate of the right of the Rectangle. - * @param top The y coordinate of the top of the Rectangle. - * @param bottom The y coordinate of the bottom of the Rectangle. - * @param tolerance Tolerance allowed in the calculation, expressed in pixels. Default 0. - */ - function RectangleToValues(rect: Phaser.Geom.Rectangle, left: number, right: number, top: number, bottom: number, tolerance?: number): boolean; - - /** - * Checks if a Triangle and a Circle intersect. - * - * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. - * @param triangle The Triangle to check for intersection. - * @param circle The Circle to check for intersection. - */ - function TriangleToCircle(triangle: Phaser.Geom.Triangle, circle: Phaser.Geom.Circle): boolean; - - /** - * Checks if a Triangle and a Line intersect. - * - * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". - * @param triangle The Triangle to check with. - * @param line The Line to check with. - */ - function TriangleToLine(triangle: Phaser.Geom.Triangle, line: Phaser.Geom.Line): boolean; - - /** - * Checks if two Triangles intersect. - * - * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". - * @param triangleA The first Triangle to check for intersection. - * @param triangleB The second Triangle to check for intersection. - */ - function TriangleToTriangle(triangleA: Phaser.Geom.Triangle, triangleB: Phaser.Geom.Triangle): boolean; - - } - - /** - * Defines a Line segment, a part of a line between two endpoints. - */ - class Line { - /** - * - * @param x1 The x coordinate of the lines starting point. Default 0. - * @param y1 The y coordinate of the lines starting point. Default 0. - * @param x2 The x coordinate of the lines ending point. Default 0. - * @param y2 The y coordinate of the lines ending point. Default 0. - */ - constructor(x1?: number, y1?: number, x2?: number, y2?: number); - - /** - * Calculate the angle of the line in radians. - * @param line The line to calculate the angle of. - */ - static Angle(line: Phaser.Geom.Line): number; - - /** - * Using Bresenham's line algorithm this will return an array of all coordinates on this line. - * - * The `start` and `end` points are rounded before this runs as the algorithm works on integers. - * @param line The line. - * @param stepRate The optional step rate for the points on the line. Default 1. - * @param results An optional array to push the resulting coordinates into. - */ - static BresenhamPoints(line: Phaser.Geom.Line, stepRate?: integer, results?: Phaser.Types.Math.Vector2Like[]): Phaser.Types.Math.Vector2Like[]; - - /** - * Center a line on the given coordinates. - * @param line The line to center. - * @param x The horizontal coordinate to center the line on. - * @param y The vertical coordinate to center the line on. - */ - static CenterOn(line: Phaser.Geom.Line, x: number, y: number): Phaser.Geom.Line; - - /** - * Clone the given line. - * @param source The source line to clone. - */ - static Clone(source: Phaser.Geom.Line): Phaser.Geom.Line; - - /** - * Copy the values of one line to a destination line. - * @param source The source line to copy the values from. - * @param dest The destination line to copy the values to. - */ - static CopyFrom(source: Phaser.Geom.Line, dest: O): O; - - /** - * Compare two lines for strict equality. - * @param line The first line to compare. - * @param toCompare The second line to compare. - */ - static Equals(line: Phaser.Geom.Line, toCompare: Phaser.Geom.Line): boolean; - - /** - * Extends the start and end points of a Line by the given amounts. - * - * The amounts can be positive or negative. Positive points will increase the length of the line, - * while negative ones will decrease it. - * - * If no `right` value is provided it will extend the length of the line equally in both directions. - * - * Pass a value of zero to leave the start or end point unchanged. - * @param line The line instance to extend. - * @param left The amount to extend the start of the line by. - * @param right The amount to extend the end of the line by. If not given it will be set to the `left` value. - */ - static Extend(line: Phaser.Geom.Line, left: number, right?: number): Phaser.Geom.Line; - - /** - * Get the midpoint of the given line. - * @param line The line to get the midpoint of. - * @param out An optional point object to store the midpoint in. - */ - static GetMidPoint(line: Phaser.Geom.Line, out?: O): O; - - /** - * Get the nearest point on a line perpendicular to the given point. - * @param line The line to get the nearest point on. - * @param point The point to get the nearest point to. - * @param out An optional point, or point-like object, to store the coordinates of the nearest point on the line. - */ - static GetNearestPoint(line: Phaser.Geom.Line, point: Phaser.Geom.Point | object, out?: O): O; - - /** - * Calculate the normal of the given line. - * - * The normal of a line is a vector that points perpendicular from it. - * @param line The line to calculate the normal of. - * @param out An optional point object to store the normal in. - */ - static GetNormal(line: Phaser.Geom.Line, out?: O): O; - - /** - * Get a point on a line that's a given percentage along its length. - * @param line The line. - * @param position A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. - * @param out An optional point, or point-like object, to store the coordinates of the point on the line. - */ - static GetPoint(line: Phaser.Geom.Line, position: number, out?: O): O; - - /** - * Get a number of points along a line's length. - * - * Provide a `quantity` to get an exact number of points along the line. - * - * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when - * providing a `stepRate`. - * @param line The line. - * @param quantity The number of points to place on the line. Set to `0` to use `stepRate` instead. - * @param stepRate The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. - * @param out An optional array of Points, or point-like objects, to store the coordinates of the points on the line. - */ - static GetPoints(line: Phaser.Geom.Line, quantity: integer, stepRate?: number, out?: O): O; - - /** - * Get the shortest distance from a Line to the given Point. - * @param line The line to get the distance from. - * @param point The point to get the shortest distance to. - */ - static GetShortestDistance(line: Phaser.Geom.Line, point: Phaser.Geom.Point | object): O; - - /** - * Calculate the height of the given line. - * @param line The line to calculate the height of. - */ - static Height(line: Phaser.Geom.Line): number; - - /** - * Calculate the length of the given line. - * @param line The line to calculate the length of. - */ - static Length(line: Phaser.Geom.Line): number; - - /** - * The geometry constant type of this object: `GEOM_CONST.LINE`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * The x coordinate of the lines starting point. - */ - x1: number; - - /** - * The y coordinate of the lines starting point. - */ - y1: number; - - /** - * The x coordinate of the lines ending point. - */ - x2: number; - - /** - * The y coordinate of the lines ending point. - */ - y2: number; - - /** - * Get a point on a line that's a given percentage along its length. - * @param position A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. - * @param output An optional point, or point-like object, to store the coordinates of the point on the line. - */ - getPoint(position: number, output?: O): O; - - /** - * Get a number of points along a line's length. - * - * Provide a `quantity` to get an exact number of points along the line. - * - * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when - * providing a `stepRate`. - * @param quantity The number of points to place on the line. Set to `0` to use `stepRate` instead. - * @param stepRate The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. - * @param output An optional array of Points, or point-like objects, to store the coordinates of the points on the line. - */ - getPoints(quantity: integer, stepRate?: integer, output?: O): O; - - /** - * Get a random Point on the Line. - * @param point An instance of a Point to be modified. - */ - getRandomPoint(point?: O): O; - - /** - * Set new coordinates for the line endpoints. - * @param x1 The x coordinate of the lines starting point. Default 0. - * @param y1 The y coordinate of the lines starting point. Default 0. - * @param x2 The x coordinate of the lines ending point. Default 0. - * @param y2 The y coordinate of the lines ending point. Default 0. - */ - setTo(x1?: number, y1?: number, x2?: number, y2?: number): Phaser.Geom.Line; - - /** - * Returns a Vector2 object that corresponds to the start of this Line. - * @param vec2 A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. - */ - getPointA(vec2?: O): O; - - /** - * Returns a Vector2 object that corresponds to the end of this Line. - * @param vec2 A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. - */ - getPointB(vec2?: O): O; - - /** - * The left position of the Line. - */ - left: number; - - /** - * The right position of the Line. - */ - right: number; - - /** - * The top position of the Line. - */ - top: number; - - /** - * The bottom position of the Line. - */ - bottom: number; - - /** - * Get the angle of the normal of the given line in radians. - * @param line The line to calculate the angle of the normal of. - */ - static NormalAngle(line: Phaser.Geom.Line): number; - - /** - * [description] - * @param line The Line object to get the normal value from. - */ - static NormalX(line: Phaser.Geom.Line): number; - - /** - * The Y value of the normal of the given line. - * The normal of a line is a vector that points perpendicular from it. - * @param line The line to calculate the normal of. - */ - static NormalY(line: Phaser.Geom.Line): number; - - /** - * Offset a line by the given amount. - * @param line The line to offset. - * @param x The horizontal offset to add to the line. - * @param y The vertical offset to add to the line. - */ - static Offset(line: O, x: number, y: number): O; - - /** - * Calculate the perpendicular slope of the given line. - * @param line The line to calculate the perpendicular slope of. - */ - static PerpSlope(line: Phaser.Geom.Line): number; - - /** - * Returns a random point on a given Line. - * @param line The Line to calculate the random Point on. - * @param out An instance of a Point to be modified. - */ - static Random(line: Phaser.Geom.Line, out?: O): O; - - /** - * Calculate the reflected angle between two lines. - * - * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. - * @param lineA The first line. - * @param lineB The second line. - */ - static ReflectAngle(lineA: Phaser.Geom.Line, lineB: Phaser.Geom.Line): number; - - /** - * Rotate a line around its midpoint by the given angle in radians. - * @param line The line to rotate. - * @param angle The angle of rotation in radians. - */ - static Rotate(line: O, angle: number): O; - - /** - * Rotate a line around a point by the given angle in radians. - * @param line The line to rotate. - * @param point The point to rotate the line around. - * @param angle The angle of rotation in radians. - */ - static RotateAroundPoint(line: O, point: Phaser.Geom.Point | object, angle: number): O; - - /** - * Rotate a line around the given coordinates by the given angle in radians. - * @param line The line to rotate. - * @param x The horizontal coordinate to rotate the line around. - * @param y The vertical coordinate to rotate the line around. - * @param angle The angle of rotation in radians. - */ - static RotateAroundXY(line: O, x: number, y: number, angle: number): O; - - /** - * Set a line to a given position, angle and length. - * @param line The line to set. - * @param x The horizontal start position of the line. - * @param y The vertical start position of the line. - * @param angle The angle of the line in radians. - * @param length The length of the line. - */ - static SetToAngle(line: O, x: number, y: number, angle: number, length: number): O; - - /** - * Calculate the slope of the given line. - * @param line The line to calculate the slope of. - */ - static Slope(line: Phaser.Geom.Line): number; - - /** - * Calculate the width of the given line. - * @param line The line to calculate the width of. - */ - static Width(line: Phaser.Geom.Line): number; - - } - - /** - * Defines a Point in 2D space, with an x and y component. - */ - class Point { - /** - * - * @param x The x coordinate of this Point. Default 0. - * @param y The y coordinate of this Point. Default x. - */ - constructor(x?: number, y?: number); - - /** - * Apply `Math.ceil()` to each coordinate of the given Point. - * @param point The Point to ceil. - */ - static Ceil(point: O): O; - - /** - * Clone the given Point. - * @param source The source Point to clone. - */ - static Clone(source: Phaser.Geom.Point): Phaser.Geom.Point; - - /** - * Copy the values of one Point to a destination Point. - * @param source The source Point to copy the values from. - * @param dest The destination Point to copy the values to. - */ - static CopyFrom(source: Phaser.Geom.Point, dest: O): O; - - /** - * A comparison of two `Point` objects to see if they are equal. - * @param point The original `Point` to compare against. - * @param toCompare The second `Point` to compare. - */ - static Equals(point: Phaser.Geom.Point, toCompare: Phaser.Geom.Point): boolean; - - /** - * Apply `Math.ceil()` to each coordinate of the given Point. - * @param point The Point to floor. - */ - static Floor(point: O): O; - - /** - * Get the centroid or geometric center of a plane figure (the arithmetic mean position of all the points in the figure). - * Informally, it is the point at which a cutout of the shape could be perfectly balanced on the tip of a pin. - * @param points [description] - * @param out [description] - */ - static GetCentroid(points: Phaser.Geom.Point[], out?: O): O; - - /** - * Calculate the magnitude of the point, which equivalent to the length of the line from the origin to this point. - * @param point The point to calculate the magnitude for - */ - static GetMagnitude(point: Phaser.Geom.Point): number; - - /** - * Calculates the square of magnitude of given point.(Can be used for fast magnitude calculation of point) - * @param point Returns square of the magnitude/length of given point. - */ - static GetMagnitudeSq(point: Phaser.Geom.Point): number; - - /** - * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. - * @param points [description] - * @param out [description] - */ - static GetRectangleFromPoints(points: Phaser.Geom.Point[], out?: O): O; - - /** - * [description] - * @param pointA The starting `Point` for the interpolation. - * @param pointB The target `Point` for the interpolation. - * @param t The amount to interpolate between the two points. Generally, a value between 0 (returns the starting `Point`) and 1 (returns the target `Point`). If omitted, 0 is used. Default 0. - * @param out An optional `Point` object whose `x` and `y` values will be set to the result of the interpolation (can also be any object with `x` and `y` properties). If omitted, a new `Point` created and returned. - */ - static Interpolate(pointA: Phaser.Geom.Point, pointB: Phaser.Geom.Point, t?: number, out?: O): O; - - /** - * Swaps the X and the Y coordinate of a point. - * @param point The Point to modify. - */ - static Invert(point: O): O; - - /** - * Inverts a Point's coordinates. - * @param point The Point to invert. - * @param out The Point to return the inverted coordinates in. - */ - static Negative(point: Phaser.Geom.Point, out?: O): O; - - /** - * The geometry constant type of this object: `GEOM_CONST.POINT`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * The x coordinate of this Point. - */ - x: number; - - /** - * The y coordinate of this Point. - */ - y: number; - - /** - * Set the x and y coordinates of the point to the given values. - * @param x The x coordinate of this Point. Default 0. - * @param y The y coordinate of this Point. Default x. - */ - setTo(x?: number, y?: number): Phaser.Geom.Point; - - /** - * [description] - * @param pointA [description] - * @param pointB [description] - * @param out [description] - */ - static Project(pointA: Phaser.Geom.Point, pointB: Phaser.Geom.Point, out?: O): O; - - /** - * [description] - * @param pointA [description] - * @param pointB [description] - * @param out [description] - */ - static ProjectUnit(pointA: Phaser.Geom.Point, pointB: Phaser.Geom.Point, out?: O): O; - - /** - * Changes the magnitude (length) of a two-dimensional vector without changing its direction. - * @param point The Point to treat as the end point of the vector. - * @param magnitude The new magnitude of the vector. - */ - static SetMagnitude(point: O, magnitude: number): O; - - } - - /** - * A Polygon object - * - * The polygon is a closed shape consists of a series of connected straight lines defined by list of ordered points. - * Several formats are supported to define the list of points, check the setTo method for details. - * This is a geometry object allowing you to define and inspect the shape. - * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. - * To render a Polygon you should look at the capabilities of the Graphics class. - */ - class Polygon { - /** - * - * @param points List of points defining the perimeter of this Polygon. Several formats are supported: - * - A string containing paired x y values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` - * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` - * - An array of objects with public x y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - */ - constructor(points?: Phaser.Geom.Point[]); - - /** - * Create a new polygon which is a copy of the specified polygon - * @param polygon The polygon to create a clone of - */ - static Clone(polygon: Phaser.Geom.Polygon): Phaser.Geom.Polygon; - - /** - * Checks if a point is within the bounds of a Polygon. - * @param polygon The Polygon to check against. - * @param x The X coordinate of the point to check. - * @param y The Y coordinate of the point to check. - */ - static Contains(polygon: Phaser.Geom.Polygon, x: number, y: number): boolean; - - /** - * [description] - * @param polygon [description] - * @param point [description] - */ - static ContainsPoint(polygon: Phaser.Geom.Polygon, point: Phaser.Geom.Point): boolean; - - /** - * Calculates the bounding AABB rectangle of a polygon. - * @param polygon The polygon that should be calculated. - * @param out The rectangle or object that has x, y, width, and height properties to store the result. Optional. - */ - static GetAABB(polygon: Phaser.Geom.Polygon, out?: O): O; - - /** - * Stores all of the points of a Polygon into a flat array of numbers following the sequence [ x,y, x,y, x,y ], - * i.e. each point of the Polygon, in the order it's defined, corresponds to two elements of the resultant - * array for the point's X and Y coordinate. - * @param polygon The Polygon whose points to export. - * @param output An array to which the points' coordinates should be appended. - */ - static GetNumberArray(polygon: Phaser.Geom.Polygon, output?: O): O; - - /** - * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, - * based on the given quantity or stepRate values. - * @param polygon The Polygon to get the points from. - * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. - * @param stepRate Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate. - * @param output An array to insert the points in to. If not provided a new array will be created. - */ - static GetPoints(polygon: Phaser.Geom.Polygon, quantity: integer, stepRate?: number, output?: any[]): Phaser.Geom.Point[]; - - /** - * Returns the perimeter of the given Polygon. - * @param polygon The Polygon to get the perimeter of. - */ - static Perimeter(polygon: Phaser.Geom.Polygon): number; - - /** - * The geometry constant type of this object: `GEOM_CONST.POLYGON`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * The area of this Polygon. - */ - area: number; - - /** - * An array of number pair objects that make up this polygon. I.e. [ {x,y}, {x,y}, {x,y} ] - */ - points: Phaser.Geom.Point[]; - - /** - * Check to see if the Polygon contains the given x / y coordinates. - * @param x The x coordinate to check within the polygon. - * @param y The y coordinate to check within the polygon. - */ - contains(x: number, y: number): boolean; - - /** - * Sets this Polygon to the given points. - * - * The points can be set from a variety of formats: - * - * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` - * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` - * - An array of objects with public x/y properties: `[obj1, obj2, ...]` - * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` - * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` - * - * `setTo` may also be called without any arguments to remove all points. - * @param points Points defining the perimeter of this polygon. Please check function description above for the different supported formats. - */ - setTo(points: any[]): Phaser.Geom.Polygon; - - /** - * Calculates the area of the Polygon. This is available in the property Polygon.area - */ - calculateArea(): number; - - /** - * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, - * based on the given quantity or stepRate values. - * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. - * @param stepRate Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate. - * @param output An array to insert the points in to. If not provided a new array will be created. - */ - getPoints(quantity: integer, stepRate?: number, output?: O): O; - - /** - * Reverses the order of the points of a Polygon. - * @param polygon The Polygon to modify. - */ - static Reverse(polygon: O): O; - - /** - * Takes a Polygon object and applies Chaikin's smoothing algorithm on its points. - * @param polygon The polygon to be smoothed. The polygon will be modified in-place and returned. - */ - static Smooth(polygon: O): O; - - } - - /** - * Encapsulates a 2D rectangle defined by its corner point in the top-left and its extends in x (width) and y (height) - */ - class Rectangle { - /** - * - * @param x The X coordinate of the top left corner of the Rectangle. Default 0. - * @param y The Y coordinate of the top left corner of the Rectangle. Default 0. - * @param width The width of the Rectangle. Default 0. - * @param height The height of the Rectangle. Default 0. - */ - constructor(x?: number, y?: number, width?: number, height?: number); - - /** - * Calculates the area of the given Rectangle object. - * @param rect The rectangle to calculate the area of. - */ - static Area(rect: Phaser.Geom.Rectangle): number; - - /** - * Rounds a Rectangle's position up to the smallest integer greater than or equal to each current coordinate. - * @param rect The Rectangle to adjust. - */ - static Ceil(rect: O): O; - - /** - * Rounds a Rectangle's position and size up to the smallest integer greater than or equal to each respective value. - * @param rect The Rectangle to modify. - */ - static CeilAll(rect: O): O; - - /** - * Moves the top-left corner of a Rectangle so that its center is at the given coordinates. - * @param rect The Rectangle to be centered. - * @param x The X coordinate of the Rectangle's center. - * @param y The Y coordinate of the Rectangle's center. - */ - static CenterOn(rect: O, x: number, y: number): O; - - /** - * Creates a new Rectangle which is identical to the given one. - * @param source The Rectangle to clone. - */ - static Clone(source: Phaser.Geom.Rectangle): Phaser.Geom.Rectangle; - - /** - * Checks if a given point is inside a Rectangle's bounds. - * @param rect The Rectangle to check. - * @param x The X coordinate of the point to check. - * @param y The Y coordinate of the point to check. - */ - static Contains(rect: Phaser.Geom.Rectangle, x: number, y: number): boolean; - - /** - * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. - * @param rect The Rectangle object. - * @param point The point object to be checked. Can be a Phaser Point object or any object with x and y values. - */ - static ContainsPoint(rect: Phaser.Geom.Rectangle, point: Phaser.Geom.Point): boolean; - - /** - * Tests if one rectangle fully contains another. - * @param rectA The first rectangle. - * @param rectB The second rectangle. - */ - static ContainsRect(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle): boolean; - - /** - * Copy the values of one Rectangle to a destination Rectangle. - * @param source The source Rectangle to copy the values from. - * @param dest The destination Rectangle to copy the values to. - */ - static CopyFrom(source: Phaser.Geom.Rectangle, dest: O): O; - - /** - * Create an array of points for each corner of a Rectangle - * If an array is specified, each point object will be added to the end of the array, otherwise a new array will be created. - * @param rect The Rectangle object to be decomposed. - * @param out If provided, each point will be added to this array. - */ - static Decompose(rect: Phaser.Geom.Rectangle, out?: any[]): any[]; - - /** - * Compares the `x`, `y`, `width` and `height` properties of two rectangles. - * @param rect Rectangle A - * @param toCompare Rectangle B - */ - static Equals(rect: Phaser.Geom.Rectangle, toCompare: Phaser.Geom.Rectangle): boolean; - - /** - * Adjusts the target rectangle, changing its width, height and position, - * so that it fits inside the area of the source rectangle, while maintaining its original - * aspect ratio. - * - * Unlike the `FitOutside` function, there may be some space inside the source area not covered. - * @param target The target rectangle to adjust. - * @param source The source rectangle to envelop the target in. - */ - static FitInside(target: O, source: Phaser.Geom.Rectangle): O; - - /** - * Adjusts the target rectangle, changing its width, height and position, - * so that it fully covers the area of the source rectangle, while maintaining its original - * aspect ratio. - * - * Unlike the `FitInside` function, the target rectangle may extend further out than the source. - * @param target The target rectangle to adjust. - * @param source The source rectangle to envelope the target in. - */ - static FitOutside(target: O, source: Phaser.Geom.Rectangle): O; - - /** - * Rounds down (floors) the top left X and Y coordinates of the given Rectangle to the largest integer less than or equal to them - * @param rect The rectangle to floor the top left X and Y coordinates of - */ - static Floor(rect: O): O; - - /** - * Rounds a Rectangle's position and size down to the largest integer less than or equal to each current coordinate or dimension. - * @param rect The Rectangle to adjust. - */ - static FloorAll(rect: O): O; - - /** - * Constructs new Rectangle or repositions and resizes an existing Rectangle so that all of the given points are on or within its bounds. - * @param points An array of points (either arrays with two elements corresponding to the X and Y coordinate or an object with public `x` and `y` properties) which should be surrounded by the Rectangle. - * @param out Optional Rectangle to adjust. - */ - static FromPoints(points: any[], out?: O): O; - - /** - * Calculates the width/height ratio of a rectangle. - * @param rect The rectangle. - */ - static GetAspectRatio(rect: Phaser.Geom.Rectangle): number; - - /** - * Returns the center of a Rectangle as a Point. - * @param rect The Rectangle to get the center of. - * @param out Optional point-like object to update with the center coordinates. - */ - static GetCenter(rect: Phaser.Geom.Rectangle, out?: O): O; - - /** - * Position is a value between 0 and 1 where 0 = the top-left of the rectangle and 0.5 = the bottom right. - * @param rectangle [description] - * @param position [description] - * @param out [description] - */ - static GetPoint(rectangle: Phaser.Geom.Rectangle, position: number, out?: O): O; - - /** - * Return an array of points from the perimeter of the rectangle, each spaced out based on the quantity or step required. - * @param rectangle The Rectangle object to get the points from. - * @param step Step between points. Used to calculate the number of points to return when quantity is falsey. Ignored if quantity is positive. - * @param quantity The number of evenly spaced points from the rectangles perimeter to return. If falsey, step param will be used to calculate the number of points. - * @param out An optional array to store the points in. - */ - static GetPoints(rectangle: Phaser.Geom.Rectangle, step: number, quantity: integer, out?: O): O; - - /** - * The size of the Rectangle object, expressed as a Point object - * with the values of the width and height properties. - * @param rect [description] - * @param out [description] - */ - static GetSize(rect: Phaser.Geom.Rectangle, out?: O): O; - - /** - * Increases the size of a Rectangle by a specified amount. - * - * The center of the Rectangle stays the same. The amounts are added to each side, so the actual increase in width or height is two times bigger than the respective argument. - * @param rect The Rectangle to inflate. - * @param x How many pixels the left and the right side should be moved by horizontally. - * @param y How many pixels the top and the bottom side should be moved by vertically. - */ - static Inflate(rect: O, x: number, y: number): O; - - /** - * Takes two Rectangles and first checks to see if they intersect. - * If they intersect it will return the area of intersection in the `out` Rectangle. - * If they do not intersect, the `out` Rectangle will have a width and height of zero. - * @param rectA The first Rectangle to get the intersection from. - * @param rectB The second Rectangle to get the intersection from. - * @param out A Rectangle to store the intersection results in. - */ - static Intersection(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, out?: Phaser.Geom.Rectangle): O; - - /** - * Return an array of points from the perimeter of the rectangle - * each spaced out based on the quantity or step required - * @param rect [description] - * @param step [description] - * @param quantity [description] - * @param out [description] - */ - static MarchingAnts(rect: Phaser.Geom.Rectangle, step: number, quantity: integer, out?: O): O; - - /** - * Merges a Rectangle with a list of points by repositioning and/or resizing it such that all points are located on or within its bounds. - * @param target The Rectangle which should be merged. - * @param points An array of Points (or any object with public `x` and `y` properties) which should be merged with the Rectangle. - */ - static MergePoints(target: O, points: Phaser.Geom.Point[]): O; - - /** - * Merges the source rectangle into the target rectangle and returns the target. - * Neither rectangle should have a negative width or height. - * @param target Target rectangle. Will be modified to include source rectangle. - * @param source Rectangle that will be merged into target rectangle. - */ - static MergeRect(target: O, source: Phaser.Geom.Rectangle): O; - - /** - * Merges a Rectangle with a point by repositioning and/or resizing it so that the point is on or within its bounds. - * @param target The Rectangle which should be merged and modified. - * @param x The X coordinate of the point which should be merged. - * @param y The Y coordinate of the point which should be merged. - */ - static MergeXY(target: O, x: number, y: number): O; - - /** - * Nudges (translates) the top left corner of a Rectangle by a given offset. - * @param rect The Rectangle to adjust. - * @param x The distance to move the Rectangle horizontally. - * @param y The distance to move the Rectangle vertically. - */ - static Offset(rect: O, x: number, y: number): O; - - /** - * Nudges (translates) the top-left corner of a Rectangle by the coordinates of a point (translation vector). - * @param rect The Rectangle to adjust. - * @param point The point whose coordinates should be used as an offset. - */ - static OffsetPoint(rect: O, point: Phaser.Geom.Point | Phaser.Math.Vector2): O; - - /** - * Checks if two Rectangles overlap. If a Rectangle is within another Rectangle, the two will be considered overlapping. Thus, the Rectangles are treated as "solid". - * @param rectA The first Rectangle to check. - * @param rectB The second Rectangle to check. - */ - static Overlaps(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle): boolean; - - /** - * Calculates the perimeter of a Rectangle. - * @param rect The Rectangle to use. - */ - static Perimeter(rect: Phaser.Geom.Rectangle): number; - - /** - * [description] - * @param rectangle [description] - * @param angle [description] - * @param out [description] - */ - static PerimeterPoint(rectangle: Phaser.Geom.Rectangle, angle: integer, out?: O): O; - - /** - * Returns a random point within a Rectangle. - * @param rect The Rectangle to return a point from. - * @param out The object to update with the point's coordinates. - */ - static Random(rect: Phaser.Geom.Rectangle, out: O): O; - - /** - * Calculates a random point that lies within the `outer` Rectangle, but outside of the `inner` Rectangle. - * The inner Rectangle must be fully contained within the outer rectangle. - * @param outer The outer Rectangle to get the random point within. - * @param inner The inner Rectangle to exclude from the returned point. - * @param out A Point, or Point-like object to store the result in. If not specified, a new Point will be created. - */ - static RandomOutside(outer: Phaser.Geom.Rectangle, inner: Phaser.Geom.Rectangle, out?: O): O; - - /** - * The geometry constant type of this object: `GEOM_CONST.RECTANGLE`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * The X coordinate of the top left corner of the Rectangle. - */ - x: number; - - /** - * The Y coordinate of the top left corner of the Rectangle. - */ - y: number; - - /** - * The width of the Rectangle, i.e. the distance between its left side (defined by `x`) and its right side. - */ - width: number; - - /** - * The height of the Rectangle, i.e. the distance between its top side (defined by `y`) and its bottom side. - */ - height: number; - - /** - * Checks if the given point is inside the Rectangle's bounds. - * @param x The X coordinate of the point to check. - * @param y The Y coordinate of the point to check. - */ - contains(x: number, y: number): boolean; - - /** - * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. - * - * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. - * - * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. - * @param position The normalized distance into the Rectangle's perimeter to return. - * @param output An object to update with the `x` and `y` coordinates of the point. - */ - getPoint(position: number, output?: O): O; - - /** - * Returns an array of points from the perimeter of the Rectangle, each spaced out based on the quantity or step required. - * @param 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 stepRate If `quantity` is 0, determines the normalized distance between each returned point. - * @param output An array to which to append the points. - */ - getPoints(quantity: integer, stepRate?: number, output?: O): O; - - /** - * Returns a random point within the Rectangle's bounds. - * @param point The object in which to store the `x` and `y` coordinates of the point. - */ - getRandomPoint(point?: O): O; - - /** - * Sets the position, width, and height of the Rectangle. - * @param x The X coordinate of the top left corner of the Rectangle. - * @param y The Y coordinate of the top left corner of the Rectangle. - * @param width The width of the Rectangle. - * @param height The height of the Rectangle. - */ - setTo(x: number, y: number, width: number, height: number): Phaser.Geom.Rectangle; - - /** - * Resets the position, width, and height of the Rectangle to 0. - */ - setEmpty(): Phaser.Geom.Rectangle; - - /** - * Sets the position of the Rectangle. - * @param x The X coordinate of the top left corner of the Rectangle. - * @param y The Y coordinate of the top left corner of the Rectangle. Default x. - */ - setPosition(x: number, y?: number): Phaser.Geom.Rectangle; - - /** - * Sets the width and height of the Rectangle. - * @param width The width to set the Rectangle to. - * @param height The height to set the Rectangle to. Default width. - */ - setSize(width: number, height?: number): Phaser.Geom.Rectangle; - - /** - * Determines if the Rectangle is empty. A Rectangle is empty if its width or height is less than or equal to 0. - */ - isEmpty(): boolean; - - /** - * Returns a Line object that corresponds to the top of this Rectangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineA(line?: O): O; - - /** - * Returns a Line object that corresponds to the right of this Rectangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineB(line?: O): O; - - /** - * Returns a Line object that corresponds to the bottom of this Rectangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineC(line?: O): O; - - /** - * Returns a Line object that corresponds to the left of this Rectangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineD(line?: O): O; - - /** - * The x coordinate of the left of the Rectangle. - * Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. - */ - left: number; - - /** - * The sum of the x and width properties. - * Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. - */ - right: number; - - /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - */ - top: number; - - /** - * The sum of the y and height properties. - * Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - */ - bottom: number; - - /** - * The x coordinate of the center of the Rectangle. - */ - centerX: number; - - /** - * The y coordinate of the center of the Rectangle. - */ - centerY: number; - - /** - * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. - * @param rect The first Rectangle object. - * @param toCompare The second Rectangle object. - */ - static SameDimensions(rect: Phaser.Geom.Rectangle, toCompare: Phaser.Geom.Rectangle): boolean; - - /** - * Scales the width and height of this Rectangle by the given amounts. - * @param rect The `Rectangle` object that will be scaled by the specified amount(s). - * @param x The factor by which to scale the rectangle horizontally. - * @param y The amount by which to scale the rectangle vertically. If this is not specified, the rectangle will be scaled by the factor `x` in both directions. - */ - static Scale(rect: O, x: number, y: number): O; - - /** - * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. - * @param rectA The first Rectangle to use. - * @param rectB The second Rectangle to use. - * @param out The Rectangle to store the union in. - */ - static Union(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, out?: O): O; - - } - - /** - * A triangle is a plane created by connecting three points. - * The first two arguments specify the first point, the middle two arguments - * specify the second point, and the last two arguments specify the third point. - */ - class Triangle { - /** - * - * @param x1 `x` coordinate of the first point. Default 0. - * @param y1 `y` coordinate of the first point. Default 0. - * @param x2 `x` coordinate of the second point. Default 0. - * @param y2 `y` coordinate of the second point. Default 0. - * @param x3 `x` coordinate of the third point. Default 0. - * @param y3 `y` coordinate of the third point. Default 0. - */ - constructor(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number); - - /** - * Returns the area of a Triangle. - * @param triangle The Triangle to use. - */ - static Area(triangle: Phaser.Geom.Triangle): number; - - /** - * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). - * The x/y specifies the top-middle of the triangle (x1/y1) and length is the length of each side. - * @param x x coordinate of the top point of the triangle. - * @param y y coordinate of the top point of the triangle. - * @param length Length of each side of the triangle. - */ - static BuildEquilateral(x: number, y: number, length: number): Phaser.Geom.Triangle; - - /** - * [description] - * @param data A flat array of vertex coordinates like [x0,y0, x1,y1, x2,y2, ...] - * @param holes 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). Default null. - * @param scaleX [description] Default 1. - * @param scaleY [description] Default 1. - * @param out [description] - */ - static BuildFromPolygon(data: any[], holes?: any[], scaleX?: number, scaleY?: number, out?: O): O; - - /** - * Builds a right triangle, i.e. one which has a 90-degree angle and two acute angles. - * @param x The X coordinate of the right angle, which will also be the first X coordinate of the constructed Triangle. - * @param y The Y coordinate of the right angle, which will also be the first Y coordinate of the constructed Triangle. - * @param width The length of the side which is to the left or to the right of the right angle. - * @param height The length of the side which is above or below the right angle. - */ - static BuildRight(x: number, y: number, width: number, height: number): Phaser.Geom.Triangle; - - /** - * Positions the Triangle so that it is centered on the given coordinates. - * @param triangle The triangle to be positioned. - * @param x The horizontal coordinate to center on. - * @param y The vertical coordinate to center on. - * @param centerFunc The function used to center the triangle. Defaults to Centroid centering. - */ - static CenterOn(triangle: O, x: number, y: number, centerFunc?: CenterFunction): O; - - /** - * Calculates the position of a Triangle's centroid, which is also its center of mass (center of gravity). - * - * The centroid is the point in a Triangle at which its three medians (the lines drawn from the vertices to the bisectors of the opposite sides) meet. It divides each one in a 2:1 ratio. - * @param triangle The Triangle to use. - * @param out An object to store the coordinates in. - */ - static Centroid(triangle: Phaser.Geom.Triangle, out?: O): O; - - /** - * Computes the circumcentre of a triangle. The circumcentre is the centre of - * the circumcircle, the smallest circle which encloses 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. - * @param triangle [description] - * @param out [description] - */ - static CircumCenter(triangle: Phaser.Geom.Triangle, out?: O): O; - - /** - * Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices. - * @param triangle The Triangle to use as input. - * @param out An optional Circle to store the result in. - */ - static CircumCircle(triangle: Phaser.Geom.Triangle, out?: O): O; - - /** - * Clones a Triangle object. - * @param source The Triangle to clone. - */ - static Clone(source: Phaser.Geom.Triangle): Phaser.Geom.Triangle; - - /** - * Checks if a point (as a pair of coordinates) is inside a Triangle's bounds. - * @param triangle The Triangle to check. - * @param x The X coordinate of the point to check. - * @param y The Y coordinate of the point to check. - */ - static Contains(triangle: Phaser.Geom.Triangle, x: number, y: number): boolean; - - /** - * Filters an array of point-like objects to only those contained within a triangle. - * If `returnFirst` is true, will return an array containing only the first point in the provided array that is within the triangle (or an empty array if there are no such points). - * @param triangle The triangle that the points are being checked in. - * @param points An array of point-like objects (objects that have an `x` and `y` property) - * @param returnFirst If `true`, return an array containing only the first point found that is within the triangle. Default false. - * @param out If provided, the points that are within the triangle will be appended to this array instead of being added to a new array. If `returnFirst` is true, only the first point found within the triangle will be appended. This array will also be returned by this function. - */ - static ContainsArray(triangle: Phaser.Geom.Triangle, points: Phaser.Geom.Point[], returnFirst?: boolean, out?: any[]): Phaser.Geom.Point[]; - - /** - * Tests if a triangle contains a point. - * @param triangle The triangle. - * @param point The point to test, or any point-like object with public `x` and `y` properties. - */ - static ContainsPoint(triangle: Phaser.Geom.Triangle, point: Phaser.Geom.Point | Phaser.Math.Vector2 | any): boolean; - - /** - * Copy the values of one Triangle to a destination Triangle. - * @param source The source Triangle to copy the values from. - * @param dest The destination Triangle to copy the values to. - */ - static CopyFrom(source: Phaser.Geom.Triangle, dest: O): O; - - /** - * Decomposes a Triangle into an array of its points. - * @param triangle The Triangle to decompose. - * @param out An array to store the points into. - */ - static Decompose(triangle: Phaser.Geom.Triangle, out?: any[]): any[]; - - /** - * Returns true if two triangles have the same coordinates. - * @param triangle The first triangle to check. - * @param toCompare The second triangle to check. - */ - static Equals(triangle: Phaser.Geom.Triangle, toCompare: Phaser.Geom.Triangle): boolean; - - /** - * Returns a Point from around the perimeter of a Triangle. - * @param triangle The Triangle to get the point on its perimeter from. - * @param position The position along the perimeter of the triangle. A value between 0 and 1. - * @param out An option Point, or Point-like object to store the value in. If not given a new Point will be created. - */ - static GetPoint(triangle: Phaser.Geom.Triangle, position: number, out?: O): O; - - /** - * Returns an array of evenly spaced points on the perimeter of a Triangle. - * @param triangle The Triangle to get the points from. - * @param quantity The number of evenly spaced points to return. Set to 0 to return an arbitrary number of points based on the `stepRate`. - * @param stepRate If `quantity` is 0, the distance between each returned point. - * @param out An array to which the points should be appended. - */ - static GetPoints(triangle: Phaser.Geom.Triangle, quantity: integer, stepRate: number, out?: O): O; - - /** - * Calculates the position of the incenter of a Triangle object. This is the point where its three angle bisectors meet and it's also the center of the incircle, which is the circle inscribed in the triangle. - * @param triangle The Triangle to find the incenter of. - * @param out An optional Point in which to store the coordinates. - */ - static InCenter(triangle: Phaser.Geom.Triangle, out?: O): O; - - /** - * Moves each point (vertex) of a Triangle by a given offset, thus moving the entire Triangle by that offset. - * @param triangle The Triangle to move. - * @param x The horizontal offset (distance) by which to move each point. Can be positive or negative. - * @param y The vertical offset (distance) by which to move each point. Can be positive or negative. - */ - static Offset(triangle: O, x: number, y: number): O; - - /** - * Gets the length of the perimeter of the given triangle. - * @param triangle [description] - */ - static Perimeter(triangle: Phaser.Geom.Triangle): number; - - /** - * [description] - * @param triangle [description] - * @param out [description] - */ - static Random(triangle: Phaser.Geom.Triangle, out?: O): O; - - /** - * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. - * @param triangle The Triangle to rotate. - * @param angle The angle by which to rotate the Triangle, in radians. - */ - static Rotate(triangle: O, angle: number): O; - - /** - * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. - * @param triangle The Triangle to rotate. - * @param point The Point to rotate the Triangle about. - * @param angle The angle by which to rotate the Triangle, in radians. - */ - static RotateAroundPoint(triangle: O, point: Phaser.Geom.Point, angle: number): O; - - /** - * Rotates an entire Triangle at a given angle about a specific point. - * @param triangle The Triangle to rotate. - * @param x The X coordinate of the point to rotate the Triangle about. - * @param y The Y coordinate of the point to rotate the Triangle about. - * @param angle The angle by which to rotate the Triangle, in radians. - */ - static RotateAroundXY(triangle: O, x: number, y: number, angle: number): O; - - /** - * The geometry constant type of this object: `GEOM_CONST.TRIANGLE`. - * Used for fast type comparisons. - */ - readonly type: integer; - - /** - * `x` coordinate of the first point. - */ - x1: number; - - /** - * `y` coordinate of the first point. - */ - y1: number; - - /** - * `x` coordinate of the second point. - */ - x2: number; - - /** - * `y` coordinate of the second point. - */ - y2: number; - - /** - * `x` coordinate of the third point. - */ - x3: number; - - /** - * `y` coordinate of the third point. - */ - y3: number; - - /** - * Checks whether a given points lies within the triangle. - * @param x The x coordinate of the point to check. - * @param y The y coordinate of the point to check. - */ - contains(x: number, y: number): boolean; - - /** - * Returns a specific point on the triangle. - * @param position Position as float within `0` and `1`. `0` equals the first point. - * @param output Optional Point, or point-like object, that the calculated point will be written to. - */ - getPoint(position: number, output?: O): O; - - /** - * Calculates a list of evenly distributed points on the triangle. It is either possible to pass an amount of points to be generated (`quantity`) or the distance between two points (`stepRate`). - * @param quantity Number of points to be generated. Can be falsey when `stepRate` should be used. All points have the same distance along the triangle. - * @param stepRate Distance between two points. Will only be used when `quantity` is falsey. - * @param output Optional Array for writing the calculated points into. Otherwise a new array will be created. - */ - getPoints(quantity: integer, stepRate?: number, output?: O): O; - - /** - * Returns a random point along the triangle. - * @param point Optional `Point` that should be modified. Otherwise a new one will be created. - */ - getRandomPoint(point?: O): O; - - /** - * Sets all three points of the triangle. Leaving out any coordinate sets it to be `0`. - * @param x1 `x` coordinate of the first point. Default 0. - * @param y1 `y` coordinate of the first point. Default 0. - * @param x2 `x` coordinate of the second point. Default 0. - * @param y2 `y` coordinate of the second point. Default 0. - * @param x3 `x` coordinate of the third point. Default 0. - * @param y3 `y` coordinate of the third point. Default 0. - */ - setTo(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number): Phaser.Geom.Triangle; - - /** - * Returns a Line object that corresponds to Line A of this Triangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineA(line?: O): O; - - /** - * Returns a Line object that corresponds to Line B of this Triangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineB(line?: O): O; - - /** - * Returns a Line object that corresponds to Line C of this Triangle. - * @param line A Line object to set the results in. If `undefined` a new Line will be created. - */ - getLineC(line?: O): O; - - /** - * Left most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. - */ - left: number; - - /** - * Right most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. - */ - right: number; - - /** - * Top most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. - */ - top: number; - - /** - * Bottom most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. - */ - bottom: number; - - } - - } - - namespace Input { - /** - * The mouse pointer is being held down. - */ - var MOUSE_DOWN: integer; - - /** - * The mouse pointer is being moved. - */ - var MOUSE_MOVE: integer; - - /** - * The mouse pointer is released. - */ - var MOUSE_UP: integer; - - /** - * A touch pointer has been started. - */ - var TOUCH_START: integer; - - /** - * A touch pointer has been started. - */ - var TOUCH_MOVE: integer; - - /** - * A touch pointer has been started. - */ - var TOUCH_END: integer; - - /** - * The pointer lock has changed. - */ - var POINTER_LOCK_CHANGE: integer; - - /** - * A touch pointer has been been cancelled by the browser. - */ - var TOUCH_CANCEL: integer; - - /** - * The mouse wheel changes. - */ - var MOUSE_WHEEL: integer; - - /** - * Creates a new Interactive Object. - * - * This is called automatically by the Input Manager when you enable a Game Object for input. - * - * The resulting Interactive Object is mapped to the Game Object's `input` property. - * @param gameObject The Game Object to which this Interactive Object is bound. - * @param hitArea The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. - * @param hitAreaCallback The 'contains' check callback that the hit area shape will use for all hit tests. - */ - function CreateInteractiveObject(gameObject: Phaser.GameObjects.GameObject, hitArea: any, hitAreaCallback: Phaser.Types.Input.HitAreaCallback): Phaser.Types.Input.InteractiveObject; - - /** - * Creates a new Pixel Perfect Handler function. - * - * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. - * @param textureManager A reference to the Texture Manager. - * @param alphaTolerance The alpha level that the pixel should be above to be included as a successful interaction. - */ - function CreatePixelPerfectHandler(textureManager: Phaser.Textures.TextureManager, alphaTolerance: integer): Function; - - namespace Events { - /** - * The Input Plugin Boot Event. - * - * This internal event is dispatched by the Input Plugin when it boots, signalling to all of its systems to create themselves. - */ - const BOOT: any; - - /** - * The Input Plugin Destroy Event. - * - * This internal event is dispatched by the Input Plugin when it is destroyed, signalling to all of its systems to destroy themselves. - */ - const DESTROY: any; - - /** - * The Pointer Drag End Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer stops dragging a Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('dragend', listener)`. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_END]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_END} event instead. - */ - const DRAG_END: any; - - /** - * The Pointer Drag Enter Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object into a Drag Target. - * - * Listen to this event from within a Scene using: `this.input.on('dragenter', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_ENTER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_ENTER} event instead. - */ - const DRAG_ENTER: any; - - /** - * The Pointer Drag Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves while dragging a Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('drag', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG} event instead. - */ - const DRAG: any; - - /** - * The Pointer Drag Leave Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object out of a Drag Target. - * - * Listen to this event from within a Scene using: `this.input.on('dragleave', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_LEAVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_LEAVE} event instead. - */ - const DRAG_LEAVE: any; - - /** - * The Pointer Drag Over Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object over a Drag Target. - * - * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within - * the drag target, it will emit this event instead. - * - * Listen to this event from within a Scene using: `this.input.on('dragover', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_OVER} event instead. - */ - const DRAG_OVER: any; - - /** - * The Pointer Drag Start Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer starts to drag any Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('dragstart', listener)`. - * - * A Pointer can only drag a single Game Object at once. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_START]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_START} event instead. - */ - const DRAG_START: any; - - /** - * The Pointer Drop Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drops a Game Object on a Drag Target. - * - * Listen to this event from within a Scene using: `this.input.on('drop', listener)`. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DROP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DROP} event instead. - */ - const DROP: any; - - /** - * The Game Object Down Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down on _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectdown', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_DOWN: any; - - /** - * The Game Object Drag End Event. - * - * This event is dispatched by an interactive Game Object if a pointer stops dragging it. - * - * Listen to this event from a Game Object using: `gameObject.on('dragend', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive](Phaser.GameObjects.GameObject#setInteractive) for more details. - */ - const GAMEOBJECT_DRAG_END: any; - - /** - * The Game Object Drag Enter Event. - * - * This event is dispatched by an interactive Game Object if a pointer drags it into a drag target. - * - * Listen to this event from a Game Object using: `gameObject.on('dragenter', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - */ - const GAMEOBJECT_DRAG_ENTER: any; - - /** - * The Game Object Drag Event. - * - * This event is dispatched by an interactive Game Object if a pointer moves while dragging it. - * - * Listen to this event from a Game Object using: `gameObject.on('drag', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - */ - const GAMEOBJECT_DRAG: any; - - /** - * The Game Object Drag Leave Event. - * - * This event is dispatched by an interactive Game Object if a pointer drags it out of a drag target. - * - * Listen to this event from a Game Object using: `gameObject.on('dragleave', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - */ - const GAMEOBJECT_DRAG_LEAVE: any; - - /** - * The Game Object Drag Over Event. - * - * This event is dispatched by an interactive Game Object if a pointer drags it over a drag target. - * - * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within - * the drag target, it will emit this event instead. - * - * Listen to this event from a Game Object using: `gameObject.on('dragover', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - */ - const GAMEOBJECT_DRAG_OVER: any; - - /** - * The Game Object Drag Start Event. - * - * This event is dispatched by an interactive Game Object if a pointer starts to drag it. - * - * Listen to this event from a Game Object using: `gameObject.on('dragstart', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * There are lots of useful drag related properties that are set within the Game Object when dragging occurs. - * For example, `gameObject.input.dragStartX`, `dragStartY` and so on. - */ - const GAMEOBJECT_DRAG_START: any; - - /** - * The Game Object Drop Event. - * - * This event is dispatched by an interactive Game Object if a pointer drops it on a Drag Target. - * - * Listen to this event from a Game Object using: `gameObject.on('drop', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive and enabled for drag. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - */ - const GAMEOBJECT_DROP: any; - - /** - * The Game Object Move Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved across _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectmove', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} - * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} - * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_MOVE: any; - - /** - * The Game Object Out Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectout', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} - * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} - * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_OUT: any; - - /** - * The Game Object Over Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectover', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} - * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} - * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_OVER: any; - - /** - * The Game Object Pointer Down Event. - * - * This event is dispatched by an interactive Game Object if a pointer is pressed down on it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerdown', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_POINTER_DOWN: any; - - /** - * The Game Object Pointer Move Event. - * - * This event is dispatched by an interactive Game Object if a pointer is moved while over it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointermove', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} - * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} - * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_POINTER_MOVE: any; - - /** - * The Game Object Pointer Out Event. - * - * This event is dispatched by an interactive Game Object if a pointer moves out of it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerout', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} - * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} - * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_POINTER_OUT: any; - - /** - * The Game Object Pointer Over Event. - * - * This event is dispatched by an interactive Game Object if a pointer moves over it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerover', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} - * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} - * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_POINTER_OVER: any; - - /** - * The Game Object Pointer Up Event. - * - * This event is dispatched by an interactive Game Object if a pointer is released while over it. - * - * Listen to this event from a Game Object using: `gameObject.on('pointerup', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_POINTER_UP: any; - - /** - * The Game Object Pointer Wheel Event. - * - * This event is dispatched by an interactive Game Object if a pointer has its wheel moved while over it. - * - * Listen to this event from a Game Object using: `gameObject.on('wheel', listener)`. - * Note that the scope of the listener is automatically set to be the Game Object instance itself. - * - * To receive this event, the Game Object must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} - * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} - * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_POINTER_WHEEL: any; - - /** - * The Game Object Up Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released while over _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectup', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_UP: any; - - /** - * The Game Object Wheel Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel moved while over _any_ interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('gameobjectwheel', listener)`. - * - * To receive this event, the Game Objects must have been set as interactive. - * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. - * - * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} event instead. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} - * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} - * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const GAMEOBJECT_WHEEL: any; - - /** - * The Input Plugin Game Out Event. - * - * This event is dispatched by the Input Plugin if the active pointer leaves the game canvas and is now - * outside of it, elsewhere on the web page. - * - * Listen to this event from within a Scene using: `this.input.on('gameout', listener)`. - */ - const GAME_OUT: any; - - /** - * The Input Plugin Game Over Event. - * - * This event is dispatched by the Input Plugin if the active pointer enters the game canvas and is now - * over of it, having previously been elsewhere on the web page. - * - * Listen to this event from within a Scene using: `this.input.on('gameover', listener)`. - */ - const GAME_OVER: any; - - /** - * The Input Manager Boot Event. - * - * This internal event is dispatched by the Input Manager when it boots. - */ - const MANAGER_BOOT: any; - - /** - * 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. - */ - const MANAGER_PROCESS: any; - - /** - * The Input Manager Update Event. - * - * This internal event is dispatched by the Input Manager as part of its update step. - */ - const MANAGER_UPDATE: any; - - /** - * The Input Manager Pointer Lock Change Event. - * - * This event is dispatched by the Input Manager when it is processing a native Pointer Lock Change DOM Event. - */ - const POINTERLOCK_CHANGE: any; - - /** - * The Pointer Down Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere. - * - * Listen to this event from within a Scene using: `this.input.on('pointerdown', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_DOWN: any; - - /** - * The Pointer Down Outside Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere outside of the game canvas. - * - * Listen to this event from within a Scene using: `this.input.on('pointerdownoutside', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} - * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} - * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_DOWN_OUTSIDE: any; - - /** - * The Pointer Move Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved anywhere. - * - * Listen to this event from within a Scene using: `this.input.on('pointermove', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} - * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} - * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_MOVE: any; - - /** - * The Pointer Out Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of any interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('pointerout', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} - * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} - * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_OUT: any; - - /** - * The Pointer Over Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over any interactive Game Object. - * - * Listen to this event from within a Scene using: `this.input.on('pointerover', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} - * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} - * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_OVER: any; - - /** - * The Pointer Up Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere. - * - * Listen to this event from within a Scene using: `this.input.on('pointerup', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_UP: any; - - /** - * The Pointer Up Outside Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere outside of the game canvas. - * - * Listen to this event from within a Scene using: `this.input.on('pointerupoutside', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} - * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} - * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_UP_OUTSIDE: any; - - /** - * The Pointer Wheel Input Event. - * - * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel updated. - * - * Listen to this event from within a Scene using: `this.input.on('wheel', listener)`. - * - * The event hierarchy is as follows: - * - * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} - * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} - * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} - * - * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop - * the propagation of this event. - */ - const POINTER_WHEEL: any; - - /** - * The Input Plugin Pre-Update Event. - * - * This internal event is dispatched by the Input Plugin at the start of its `preUpdate` method. - * This hook is designed specifically for input plugins, but can also be listened to from user-land code. - */ - const PRE_UPDATE: any; - - /** - * The Input Plugin Shutdown Event. - * - * This internal event is dispatched by the Input Plugin when it shuts down, signalling to all of its systems to shut themselves down. - */ - const SHUTDOWN: any; - - /** - * The Input Plugin Start Event. - * - * This internal event is dispatched by the Input Plugin when it has finished setting-up, - * signalling to all of its internal systems to start. - */ - const START: any; - - /** - * 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. - */ - const UPDATE: any; - - } - - namespace Gamepad { - /** - * Contains information about a specific Gamepad Axis. - * Axis objects are created automatically by the Gamepad as they are needed. - */ - class Axis { - /** - * - * @param pad A reference to the Gamepad that this Axis belongs to. - * @param index The index of this Axis. - */ - constructor(pad: Phaser.Input.Gamepad.Gamepad, index: integer); - - /** - * A reference to the Gamepad that this Axis belongs to. - */ - pad: Phaser.Input.Gamepad.Gamepad; - - /** - * An event emitter to use to emit the axis events. - */ - events: Phaser.Events.EventEmitter; - - /** - * The index of this Axis. - */ - index: integer; - - /** - * The raw axis value, between -1 and 1 with 0 being dead center. - * Use the method `getValue` to get a normalized value with the threshold applied. - */ - value: number; - - /** - * Movement tolerance threshold below which axis values are ignored in `getValue`. - */ - threshold: number; - - /** - * Applies the `threshold` value to the axis and returns it. - */ - getValue(): number; - - /** - * Destroys this Axis instance and releases external references it holds. - */ - destroy(): void; - - } - - /** - * Contains information about a specific button on a Gamepad. - * Button objects are created automatically by the Gamepad as they are needed. - */ - class Button { - /** - * - * @param pad A reference to the Gamepad that this Button belongs to. - * @param index The index of this Button. - */ - constructor(pad: Phaser.Input.Gamepad.Gamepad, index: integer); - - /** - * A reference to the Gamepad that this Button belongs to. - */ - pad: Phaser.Input.Gamepad.Gamepad; - - /** - * An event emitter to use to emit the button events. - */ - events: Phaser.Events.EventEmitter; - - /** - * The index of this Button. - */ - index: integer; - - /** - * Between 0 and 1. - */ - value: number; - - /** - * Can be set for analogue buttons to enable a 'pressure' threshold, - * before a button is considered as being 'pressed'. - */ - threshold: number; - - /** - * Is the Button being pressed down or not? - */ - pressed: boolean; - - /** - * Destroys this Button instance and releases external references it holds. - */ - destroy(): void; - - } - - namespace Configs { - /** - * Tatar SNES USB Controller Gamepad Configuration. - * USB Gamepad (STANDARD GAMEPAD Vendor: 0079 Product: 0011) - */ - var SNES_USB: object; - - /** - * PlayStation DualShock 4 Gamepad Configuration. - * Sony PlayStation DualShock 4 (v2) wireless controller - */ - var DUALSHOCK_4: object; - - /** - * XBox 360 Gamepad Configuration. - */ - var XBOX_360: object; - - } - - namespace Events { - /** - * The Gamepad Button Down Event. - * - * This event is dispatched by the Gamepad Plugin when a button has been pressed on any active Gamepad. - * - * Listen to this event from within a Scene using: `this.input.gamepad.on('down', listener)`. - * - * You can also listen for a DOWN event from a Gamepad instance. See the [GAMEPAD_BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_DOWN} event for details. - */ - const BUTTON_DOWN: any; - - /** - * The Gamepad Button Up Event. - * - * This event is dispatched by the Gamepad Plugin when a button has been released on any active Gamepad. - * - * Listen to this event from within a Scene using: `this.input.gamepad.on('up', listener)`. - * - * You can also listen for an UP event from a Gamepad instance. See the [GAMEPAD_BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_UP} event for details. - */ - const BUTTON_UP: any; - - /** - * The Gamepad Connected Event. - * - * This event is dispatched by the Gamepad Plugin when a Gamepad has been connected. - * - * Listen to this event from within a Scene using: `this.input.gamepad.once('connected', listener)`. - * - * 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. - */ - const CONNECTED: any; - - /** - * The Gamepad Disconnected Event. - * - * This event is dispatched by the Gamepad Plugin when a Gamepad has been disconnected. - * - * Listen to this event from within a Scene using: `this.input.gamepad.once('disconnected', listener)`. - */ - const DISCONNECTED: any; - - /** - * The Gamepad Button Down Event. - * - * This event is dispatched by a Gamepad instance when a button has been pressed on it. - * - * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: - * `this.input.gamepad.pad1.on('down', listener)`. - * - * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. - * - * You can also listen for a DOWN event from the Gamepad Plugin. See the [BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_DOWN} event for details. - */ - const GAMEPAD_BUTTON_DOWN: any; - - /** - * The Gamepad Button Up Event. - * - * This event is dispatched by a Gamepad instance when a button has been released on it. - * - * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: - * `this.input.gamepad.pad1.on('up', listener)`. - * - * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. - * - * You can also listen for an UP event from the Gamepad Plugin. See the [BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_UP} event for details. - */ - const GAMEPAD_BUTTON_UP: any; - - } - - /** - * A single Gamepad. - * - * These are created, updated and managed by the Gamepad Plugin. - */ - class Gamepad extends Phaser.Events.EventEmitter { - /** - * - * @param manager A reference to the Gamepad Plugin. - * @param pad The Gamepad object, as extracted from GamepadEvent. - */ - constructor(manager: Phaser.Input.Gamepad.GamepadPlugin, pad: Phaser.Types.Input.Gamepad.Pad); - - /** - * A reference to the Gamepad Plugin. - */ - manager: Phaser.Input.Gamepad.GamepadPlugin; - - /** - * A reference to the native Gamepad object that is connected to the browser. - */ - pad: any; - - /** - * A string containing some information about the controller. - * - * This is not strictly specified, but in Firefox it will contain three pieces of information - * separated by dashes (-): two 4-digit hexadecimal strings containing the USB vendor and - * product id of the controller, and the name of the controller as provided by the driver. - * In Chrome it will contain the name of the controller as provided by the driver, - * followed by vendor and product 4-digit hexadecimal strings. - */ - id: string; - - /** - * An integer that is unique for each Gamepad currently connected to the system. - * This can be used to distinguish multiple controllers. - * Note that disconnecting a device and then connecting a new device may reuse the previous index. - */ - index: number; - - /** - * An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad. - */ - buttons: Phaser.Input.Gamepad.Button[]; - - /** - * An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any. - */ - axes: Phaser.Input.Gamepad.Axis[]; - - /** - * The Gamepad's Haptic Actuator (Vibration / Rumble support). - * This is highly experimental and only set if both present on the device, - * and exposed by both the hardware and browser. - */ - vibration: GamepadHapticActuator; - - /** - * 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. - */ - leftStick: Phaser.Math.Vector2; - - /** - * 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. - */ - rightStick: Phaser.Math.Vector2; - - /** - * Gets the total number of axis this Gamepad claims to support. - */ - getAxisTotal(): integer; - - /** - * 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 0 and 1. - * @param index The index of the axes to get the value for. - */ - getAxisValue(index: integer): number; - - /** - * Sets the threshold value of all axis on this Gamepad. - * The value is a float between 0 and 1 and is the amount below which the axis is considered as not having been moved. - * @param value A value between 0 and 1. - */ - setAxisThreshold(value: number): void; - - /** - * Gets the total number of buttons this Gamepad claims to have. - */ - getButtonTotal(): integer; - - /** - * 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 an analogue button, or a float between 0 and 1 - * for a pressure-sensitive digital button, such as the shoulder buttons on a Dual Shock. - * @param index The index of the button to get the value for. - */ - getButtonValue(index: integer): number; - - /** - * Returns if the button is pressed down or not. - * The index must be valid within the range of buttons supported by this Gamepad. - * @param index The index of the button to get the value for. - */ - isButtonDown(index: integer): boolean; - - /** - * Destroys this Gamepad instance, its buttons and axes, and releases external references it holds. - */ - destroy(): void; - - /** - * Is this Gamepad currently connected or not? - */ - connected: boolean; - - /** - * A timestamp containing the most recent time this Gamepad was updated. - */ - timestamp: number; - - /** - * Is the Gamepad's Left button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad left button under standard Gamepad mapping. - */ - left: boolean; - - /** - * Is the Gamepad's Right button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad right button under standard Gamepad mapping. - */ - right: boolean; - - /** - * Is the Gamepad's Up button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad up button under standard Gamepad mapping. - */ - up: boolean; - - /** - * Is the Gamepad's Down button being pressed? - * If the Gamepad doesn't have this button it will always return false. - * This is the d-pad down button under standard Gamepad mapping. - */ - down: boolean; - - /** - * Is the Gamepad's bottom button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the X button. - * On an XBox controller it's the A button. - */ - A: boolean; - - /** - * Is the Gamepad's top button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the Triangle button. - * On an XBox controller it's the Y button. - */ - Y: boolean; - - /** - * Is the Gamepad's left button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the Square button. - * On an XBox controller it's the X button. - */ - X: boolean; - - /** - * Is the Gamepad's right button in the right button cluster being pressed? - * If the Gamepad doesn't have this button it will always return false. - * On a Dual Shock controller it's the Circle button. - * On an XBox controller it's the B button. - */ - B: boolean; - - /** - * Returns the value of the Gamepad's top left shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the L1 button. - * On an XBox controller it's the LB button. - */ - L1: number; - - /** - * Returns the value of the Gamepad's bottom left shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the L2 button. - * On an XBox controller it's the LT button. - */ - L2: number; - - /** - * Returns the value of the Gamepad's top right shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the R1 button. - * On an XBox controller it's the RB button. - */ - R1: number; - - /** - * Returns the value of the Gamepad's bottom right shoulder button. - * If the Gamepad doesn't have this button it will always return zero. - * The value is a float between 0 and 1, corresponding to how depressed the button is. - * On a Dual Shock controller it's the R2 button. - * On an XBox controller it's the RT button. - */ - R2: number; - - } - - /** - * 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. - * - * 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 { - /** - * - * @param sceneInputPlugin A reference to the Scene Input Plugin that the KeyboardPlugin belongs to. - */ - constructor(sceneInputPlugin: Phaser.Input.InputPlugin); - - /** - * A reference to the Scene that this Input Plugin is responsible for. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene Systems Settings. - */ - settings: Phaser.Types.Scenes.SettingsObject; - - /** - * A reference to the Scene Input Plugin that created this Keyboard Plugin. - */ - sceneInputPlugin: Phaser.Input.InputPlugin; - - /** - * A boolean that controls if the Gamepad Manager is enabled or not. - * Can be toggled on the fly. - */ - enabled: boolean; - - /** - * The Gamepad Event target, as defined in the Game Config. - * Typically the browser window, but can be any interactive DOM element. - */ - target: any; - - /** - * An array of the connected Gamepads. - */ - gamepads: Phaser.Input.Gamepad.Gamepad[]; - - /** - * Checks to see if both this plugin and the Scene to which it belongs is active. - */ - isActive(): boolean; - - /** - * Disconnects all current Gamepads. - */ - disconnectAll(): void; - - /** - * Returns an array of all currently connected Gamepads. - */ - getAll(): Phaser.Input.Gamepad.Gamepad[]; - - /** - * Looks-up a single Gamepad based on the given index value. - * @param index The index of the Gamepad to get. - */ - getPad(index: number): Phaser.Input.Gamepad.Gamepad; - - /** - * The total number of connected game pads. - */ - total: integer; - - /** - * A reference to the first connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - */ - pad1: Phaser.Input.Gamepad.Gamepad; - - /** - * A reference to the second connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - */ - pad2: Phaser.Input.Gamepad.Gamepad; - - /** - * A reference to the third connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - */ - pad3: Phaser.Input.Gamepad.Gamepad; - - /** - * A reference to the fourth connected Gamepad. - * - * This will be undefined if either no pads are connected, or the browser - * has not yet issued a gamepadconnect, which can happen even if a Gamepad - * is plugged in, but hasn't yet had any buttons pressed on it. - */ - pad4: Phaser.Input.Gamepad.Gamepad; - - } - - } - - /** - * 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 { - /** - * - * @param game The Game instance that owns the Input Manager. - * @param config The Input Configuration object, as set in the Game Config. - */ - constructor(game: Phaser.Game, config: object); - - /** - * The Game instance that owns the Input Manager. - * A Game only maintains on instance of the Input Manager at any time. - */ - readonly game: Phaser.Game; - - /** - * A reference to the global Game Scale Manager. - * Used for all bounds checks and pointer scaling. - */ - scaleManager: Phaser.Scale.ScaleManager; - - /** - * The Canvas that is used for all DOM event input listeners. - */ - canvas: HTMLCanvasElement; - - /** - * The Game Configuration object, as set during the game boot. - */ - config: Phaser.Core.Config; - - /** - * If set, the Input Manager will run its update loop every frame. - */ - enabled: boolean; - - /** - * The Event Emitter instance that the Input Manager uses to emit events from. - */ - events: Phaser.Events.EventEmitter; - - /** - * Are any mouse or touch pointers currently over the game canvas? - * This is updated automatically by the canvas over and out handlers. - */ - readonly isOver: boolean; - - /** - * The default CSS cursor to be used when interacting with your game. - * - * See the `setDefaultCursor` method for more details. - */ - defaultCursor: string; - - /** - * A reference to the Keyboard Manager class, if enabled via the `input.keyboard` Game Config property. - */ - keyboard: Phaser.Input.Keyboard.KeyboardManager; - - /** - * A reference to the Mouse Manager class, if enabled via the `input.mouse` Game Config property. - */ - mouse: Phaser.Input.Mouse.MouseManager; - - /** - * A reference to the Touch Manager class, if enabled via the `input.touch` Game Config property. - */ - touch: Phaser.Input.Touch.TouchManager; - - /** - * An array of Pointers that have been added to the game. - * The first entry is reserved for the Mouse Pointer, the rest are Touch Pointers. - * - * By default there is 1 touch pointer enabled. If you need more use the `addPointer` method to start them, - * or set the `input.activePointers` property in the Game Config. - */ - pointers: Phaser.Input.Pointer[]; - - /** - * The number of touch objects activated and being processed each update. - * - * You can change this by either calling `addPointer` at run-time, or by - * setting the `input.activePointers` property in the Game Config. - */ - readonly pointersTotal: integer; - - /** - * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. - * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` - * which will always map to the most recently interacted pointer. - */ - mousePointer: Phaser.Input.Pointer; - - /** - * 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. - */ - activePointer: Phaser.Input.Pointer; - - /** - * If the top-most Scene in the Scene List receives an input it will stop input from - * propagating any lower down the scene list, i.e. if you have a UI Scene at the top - * and click something on it, that click will not then be passed down to any other - * Scene below. Disable this to have input events passed through all Scenes, all the time. - */ - globalTopOnly: boolean; - - /** - * The time this Input Manager was last updated. - * This value is populated by the Game Step each frame. - */ - readonly time: number; - - /** - * The Boot handler is called by Phaser.Game when it first starts up. - * The renderer is available by now. - */ - protected boot(): void; - - /** - * 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. - * @param cursor The CSS to be used when setting the default cursor. - */ - setDefaultCursor(cursor: string): void; - - /** - * Adds new Pointer objects to the Input Manager. - * - * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. - * - * You can create more either by calling this method, or by setting the `input.activePointers` property - * in the Game Config, up to a maximum of 10 pointers. - * - * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added - * via this method. - * @param quantity The number of new Pointers to create. A maximum of 10 is allowed in total. Default 1. - */ - addPointer(quantity?: integer): Phaser.Input.Pointer[]; - - /** - * Internal method that gets a list of all the active Input Plugins in the game - * and updates each of them in turn, in reverse order (top to bottom), to allow - * for DOM top-level event handling simulation. - * @param type The type of event to process. - * @param pointers An array of Pointers on which the event occurred. - */ - updateInputPlugins(type: integer, pointers: Phaser.Input.Pointer[]): void; - - /** - * Performs a hit test using the given Pointer and camera, against an array of interactive Game Objects. - * - * The Game Objects are culled against the camera, and then the coordinates are translated into the local camera space - * and used to determine if they fall within the remaining Game Objects hit areas or not. - * - * If nothing is matched an empty array is returned. - * - * This method is called automatically by InputPlugin.hitTestPointer and doesn't usually need to be invoked directly. - * @param pointer The Pointer to test against. - * @param gameObjects An array of interactive Game Objects to check. - * @param camera The Camera which is being tested against. - * @param output An array to store the results in. If not given, a new empty array is created. - */ - hitTest(pointer: Phaser.Input.Pointer, gameObjects: any[], camera: Phaser.Cameras.Scene2D.Camera, output?: any[]): any[]; - - /** - * Checks if the given x and y coordinate are within the hit area of the Game Object. - * - * This method assumes that the coordinate values have already been translated into the space of the Game Object. - * - * If the coordinates are within the hit area they are set into the Game Objects Input `localX` and `localY` properties. - * @param gameObject The interactive Game Object to check against. - * @param x The translated x coordinate for the hit test. - * @param y The translated y coordinate for the hit test. - */ - pointWithinHitArea(gameObject: Phaser.GameObjects.GameObject, x: number, y: number): boolean; - - /** - * Checks if the given x and y coordinate are within the hit area of the Interactive Object. - * - * This method assumes that the coordinate values have already been translated into the space of the Interactive Object. - * - * If the coordinates are within the hit area they are set into the Interactive Objects Input `localX` and `localY` properties. - * @param object The Interactive Object to check against. - * @param x The translated x coordinate for the hit test. - * @param y The translated y coordinate for the hit test. - */ - pointWithinInteractiveObject(object: Phaser.Types.Input.InteractiveObject, x: number, y: number): boolean; - - /** - * Transforms the pageX and pageY values of a Pointer into the scaled coordinate space of the Input Manager. - * @param pointer The Pointer to transform the values for. - * @param pageX The Page X value. - * @param pageY The Page Y value. - * @param wasMove Are we transforming the Pointer from a move event, or an up / down event? - */ - transformPointer(pointer: Phaser.Input.Pointer, pageX: number, pageY: number, wasMove: boolean): void; - - /** - * Destroys the Input Manager and all of its systems. - * - * There is no way to recover from doing this. - */ - destroy(): void; - - } - - /** - * The Input Plugin belongs to a Scene and handles all input related events and operations for it. - * - * You can access it from within a Scene using `this.input`. - * - * It emits events directly. For example, you can do: - * - * ```javascript - * this.input.on('pointerdown', callback, context); - * ``` - * - * To listen for a pointer down event anywhere on the game canvas. - * - * Game Objects can be enabled for input by calling their `setInteractive` method. After which they - * will directly emit input events: - * - * ```javascript - * var sprite = this.add.sprite(x, y, texture); - * sprite.setInteractive(); - * sprite.on('pointerdown', callback, context); - * ``` - * - * There are lots of game configuration options available relating to input. - * See the [Input Config object]{@linkcode Phaser.Types.Core.InputConfig} for more details, including how to deal with Phaser - * listening for input events outside of the canvas, how to set a default number of pointers, input - * capture settings and more. - * - * Please also see the Input examples and tutorials for further information. - */ - class InputPlugin extends Phaser.Events.EventEmitter { - /** - * - * @param scene A reference to the Scene that this Input Plugin is responsible for. - */ - constructor(scene: Phaser.Scene); - - /** - * An instance of the Gamepad Plugin class, if enabled via the `input.gamepad` Scene or Game Config property. - * Use this to create access Gamepads connected to the browser and respond to gamepad buttons. - */ - gamepad: Phaser.Input.Gamepad.GamepadPlugin; - - /** - * A reference to the Scene that this Input Plugin is responsible for. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene Systems class. - */ - systems: Phaser.Scenes.Systems; - - /** - * A reference to the Scene Systems Settings. - */ - settings: Phaser.Types.Scenes.SettingsObject; - - /** - * A reference to the Game Input Manager. - */ - manager: Phaser.Input.InputManager; - - /** - * If `true` this Input Plugin will process DOM input events. - */ - enabled: boolean; - - /** - * A reference to the Scene Display List. This property is set during the `boot` method. - */ - displayList: Phaser.GameObjects.DisplayList; - - /** - * A reference to the Scene Cameras Manager. This property is set during the `boot` method. - */ - cameras: Phaser.Cameras.Scene2D.CameraManager; - - /** - * A reference to the Mouse Manager. - * - * This property is only set if Mouse support has been enabled in your Game Configuration file. - * - * If you just wish to get access to the mouse pointer, use the `mousePointer` property instead. - */ - mouse: Phaser.Input.Mouse.MouseManager; - - /** - * When set to `true` (the default) the Input Plugin will emulate DOM behavior by only emitting events from - * the top-most Game Objects in the Display List. - * - * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. - */ - topOnly: boolean; - - /** - * How often should the Pointers be checked? - * - * The value is a time, given in ms, and is the time that must have elapsed between game steps before - * the Pointers will be polled again. When a pointer is polled it runs a hit test to see which Game - * Objects are currently below it, or being interacted with it. - * - * Pointers will *always* be checked if they have been moved by the user, or press or released. - * - * This property only controls how often they will be polled if they have not been updated. - * You should set this if you want to have Game Objects constantly check against the pointers, even - * if the pointer didn't itself move. - * - * Set to 0 to poll constantly. Set to -1 to only poll on user movement. - */ - pollRate: integer; - - /** - * The distance, in pixels, a pointer has to move while being held down, before it thinks it is being dragged. - */ - dragDistanceThreshold: number; - - /** - * The amount of time, in ms, a pointer has to be held down before it thinks it is dragging. - * - * The default polling rate is to poll only on move so once the time threshold is reached the - * drag event will not start until you move the mouse. If you want it to start immediately - * when the time threshold is reached, you must increase the polling rate by calling - * [setPollAlways]{@linkcode Phaser.Input.InputPlugin#setPollAlways} or - * [setPollRate]{@linkcode Phaser.Input.InputPlugin#setPollRate}. - */ - dragTimeThreshold: number; - - /** - * Checks to see if both this plugin and the Scene to which it belongs is active. - */ - isActive(): boolean; - - /** - * This is called automatically by the Input Manager. - * It emits events for plugins to listen to and also handles polling updates, if enabled. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - updatePoll(time: number, delta: number): boolean; - - /** - * Clears a Game Object so it no longer has an Interactive Object associated with it. - * The Game Object is then queued for removal from the Input Plugin on the next update. - * @param gameObject The Game Object that will have its Interactive Object removed. - * @param skipQueue Skip adding this Game Object into the removal queue? Default false. - */ - clear(gameObject: Phaser.GameObjects.GameObject, skipQueue?: boolean): Phaser.GameObjects.GameObject; - - /** - * Disables Input on a single Game Object. - * - * An input disabled Game Object still retains its Interactive Object component and can be re-enabled - * at any time, by passing it to `InputPlugin.enable`. - * @param gameObject The Game Object to have its input system disabled. - */ - disable(gameObject: Phaser.GameObjects.GameObject): void; - - /** - * 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. - * @param gameObject The Game Object to be enabled for input. - * @param shape 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 callback The 'contains' function to invoke to check if the pointer is within the hit area. - * @param dropZone Is this Game Object a drop zone or not? Default false. - */ - enable(gameObject: Phaser.GameObjects.GameObject, shape?: Phaser.Types.Input.InputConfiguration | any, callback?: Phaser.Types.Input.HitAreaCallback, dropZone?: boolean): Phaser.Input.InputPlugin; - - /** - * Takes the given Pointer and performs a hit test against it, to see which interactive Game Objects - * it is currently above. - * - * The hit test is performed against which-ever Camera the Pointer is over. If it is over multiple - * cameras, it starts checking the camera at the top of the camera list, and if nothing is found, iterates down the list. - * @param pointer The Pointer to check against the Game Objects. - */ - hitTestPointer(pointer: Phaser.Input.Pointer): Phaser.GameObjects.GameObject[]; - - /** - * Returns the drag state of the given Pointer for this Input Plugin. - * - * The state will be one of the following: - * - * 0 = Not dragging anything - * 1 = Primary button down and objects below, so collect a draglist - * 2 = Pointer being checked if meets drag criteria - * 3 = Pointer meets criteria, notify the draglist - * 4 = Pointer actively dragging the draglist and has moved - * 5 = Pointer actively dragging but has been released, notify draglist - * @param pointer The Pointer to get the drag state for. - */ - getDragState(pointer: Phaser.Input.Pointer): integer; - - /** - * Sets the drag state of the given Pointer for this Input Plugin. - * - * The state must be one of the following values: - * - * 0 = Not dragging anything - * 1 = Primary button down and objects below, so collect a draglist - * 2 = Pointer being checked if meets drag criteria - * 3 = Pointer meets criteria, notify the draglist - * 4 = Pointer actively dragging the draglist and has moved - * 5 = Pointer actively dragging but has been released, notify draglist - * @param pointer The Pointer to set the drag state for. - * @param state The drag state value. An integer between 0 and 5. - */ - setDragState(pointer: Phaser.Input.Pointer, state: integer): void; - - /** - * Sets the draggable state of the given array of Game Objects. - * - * They can either be set to be draggable, or can have their draggable state removed by passing `false`. - * - * A Game Object will not fire drag events unless it has been specifically enabled for drag. - * @param gameObjects An array of Game Objects to change the draggable state on. - * @param value Set to `true` if the Game Objects should be made draggable, `false` if they should be unset. Default true. - */ - setDraggable(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], value?: boolean): Phaser.Input.InputPlugin; - - /** - * Creates a function that can be passed to `setInteractive`, `enable` or `setHitArea` that will handle - * pixel-perfect input detection on an Image or Sprite based Game Object, or any custom class that extends them. - * - * The following will create a sprite that is clickable on any pixel that has an alpha value >= 1. - * - * ```javascript - * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect()); - * ``` - * - * The following will create a sprite that is clickable on any pixel that has an alpha value >= 150. - * - * ```javascript - * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect(150)); - * ``` - * - * Once you have made an Interactive Object pixel perfect it impacts all input related events for it: down, up, - * dragstart, drag, etc. - * - * As a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from - * the given coordinates and checking its color values. This is an expensive process, so should only be enabled on - * Game Objects that really need it. - * - * You cannot make non-texture based Game Objects pixel perfect. So this will not work on Graphics, BitmapText, - * Render Textures, Text, Tilemaps, Containers or Particles. - * @param alphaTolerance The alpha level that the pixel should be above to be included as a successful interaction. Default 1. - */ - makePixelPerfect(alphaTolerance?: integer): Function; - - /** - * 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`. - * @param gameObjects An array of Game Objects to set the hit area on. - * @param shape 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 callback The 'contains' function to invoke to check if the pointer is within the hit area. - */ - setHitArea(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], shape?: Phaser.Types.Input.InputConfiguration | any, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Circle` shape, using - * the given coordinates and radius to control its position and size. - * @param gameObjects An array of Game Objects to set as having a circle hit area. - * @param x The center of the circle. - * @param y The center of the circle. - * @param radius The radius of the circle. - * @param callback The hit area callback. If undefined it uses Circle.Contains. - */ - setHitAreaCircle(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x: number, y: number, radius: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Ellipse` shape, using - * the given coordinates and dimensions to control its position and size. - * @param gameObjects An array of Game Objects to set as having an ellipse hit area. - * @param x The center of the ellipse. - * @param y The center of the ellipse. - * @param width The width of the ellipse. - * @param height The height of the ellipse. - * @param callback The hit area callback. If undefined it uses Ellipse.Contains. - */ - setHitAreaEllipse(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x: number, y: number, width: number, height: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; - - /** - * 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. - * @param gameObjects An array of Game Objects to set as having an ellipse hit area. - * @param callback The hit area callback. If undefined it uses Rectangle.Contains. - */ - setHitAreaFromTexture(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Rectangle` shape, using - * the given coordinates and dimensions to control its position and size. - * @param gameObjects An array of Game Objects to set as having a rectangular hit area. - * @param x The top-left of the rectangle. - * @param y The top-left of the rectangle. - * @param width The width of the rectangle. - * @param height The height of the rectangle. - * @param callback The hit area callback. If undefined it uses Rectangle.Contains. - */ - setHitAreaRectangle(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x: number, y: number, width: number, height: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; - - /** - * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Triangle` shape, using - * the given coordinates to control the position of its points. - * @param gameObjects An array of Game Objects to set as having a triangular hit area. - * @param x1 The x coordinate of the first point of the triangle. - * @param y1 The y coordinate of the first point of the triangle. - * @param x2 The x coordinate of the second point of the triangle. - * @param y2 The y coordinate of the second point of the triangle. - * @param x3 The x coordinate of the third point of the triangle. - * @param y3 The y coordinate of the third point of the triangle. - * @param callback The hit area callback. If undefined it uses Triangle.Contains. - */ - setHitAreaTriangle(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; - - /** - * Creates an Input Debug Shape for the given Game Object. - * - * The Game Object must have _already_ been enabled for input prior to calling this method. - * - * This is intended to assist you during development and debugging. - * - * Debug Shapes can only be created for Game Objects that are using standard Phaser Geometry for input, - * including: Circle, Ellipse, Line, Polygon, Rectangle and Triangle. - * - * Game Objects that are using their automatic hit areas are using Rectangles by default, so will also work. - * - * The Debug Shape is created and added to the display list and is then kept in sync with the Game Object - * it is connected with. Should you need to modify it yourself, such as to hide it, you can access it via - * the Game Object property: `GameObject.input.hitAreaDebug`. - * - * Calling this method on a Game Object that already has a Debug Shape will first destroy the old shape, - * before creating a new one. If you wish to remove the Debug Shape entirely, you should call the - * method `InputPlugin.removeDebug`. - * - * Note that the debug shape will only show the outline of the input area. If the input test is using a - * pixel perfect check, for example, then this is not displayed. If you are using a custom shape, that - * doesn't extend one of the base Phaser Geometry objects, as your hit area, then this method will not - * work. - * @param gameObject The Game Object to create the input debug shape for. - * @param color The outline color of the debug shape. Default 0x00ff00. - */ - enableDebug(gameObject: Phaser.GameObjects.GameObject, color?: number): Phaser.Input.InputPlugin; - - /** - * Removes an Input Debug Shape from the given Game Object. - * - * The shape is destroyed immediately and the `hitAreaDebug` property is set to `null`. - * @param gameObject The Game Object to remove the input debug shape from. - */ - removeDebug(gameObject: Phaser.GameObjects.GameObject): Phaser.Input.InputPlugin; - - /** - * Sets the Pointers to always poll. - * - * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, - * or being interacted with it, regardless if the Pointer has actually moved or not. - * - * You should enable this if you want objects in your game to fire over / out events, and the objects - * are constantly moving, but the pointer may not have. Polling every frame has additional computation - * costs, especially if there are a large number of interactive objects in your game. - */ - setPollAlways(): Phaser.Input.InputPlugin; - - /** - * Sets the Pointers to only poll when they are moved or updated. - * - * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, - * or being interacted with it. - */ - setPollOnMove(): Phaser.Input.InputPlugin; - - /** - * Sets the poll rate value. This is the amount of time that should have elapsed before a pointer - * will be polled again. See the `setPollAlways` and `setPollOnMove` methods. - * @param value The amount of time, in ms, that should elapsed before re-polling the pointers. - */ - setPollRate(value: number): Phaser.Input.InputPlugin; - - /** - * When set to `true` the global Input Manager will emulate DOM behavior by only emitting events from - * the top-most Scene in the Scene List. By default, if a Scene receives an input event it will then stop the event - * from flowing down to any Scenes below it in the Scene list. To disable this behavior call this method with `false`. - * @param value Set to `true` to stop processing input events on the Scene that receives it, or `false` to let the event continue down the Scene list. - */ - setGlobalTopOnly(value: boolean): Phaser.Input.InputPlugin; - - /** - * When set to `true` this Input Plugin will emulate DOM behavior by only emitting events from - * the top-most Game Objects in the Display List. - * - * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. - * @param value `true` to only include the top-most Game Object, or `false` to include all Game Objects in a hit test. - */ - setTopOnly(value: boolean): Phaser.Input.InputPlugin; - - /** - * Given an array of Game Objects, sort the array and return it, so that the objects are in depth index order - * with the lowest at the bottom. - * @param gameObjects An array of Game Objects to be sorted. - */ - sortGameObjects(gameObjects: Phaser.GameObjects.GameObject[]): Phaser.GameObjects.GameObject[]; - - /** - * This method should be called from within an input event handler, such as `pointerdown`. - * - * When called, it stops the Input Manager from allowing _this specific event_ to be processed by any other Scene - * not yet handled in the scene list. - */ - stopPropagation(): Phaser.Input.InputPlugin; - - /** - * Adds new Pointer objects to the Input Manager. - * - * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. - * - * You can create more either by calling this method, or by setting the `input.activePointers` property - * in the Game Config, up to a maximum of 10 pointers. - * - * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added - * via this method. - * @param quantity The number of new Pointers to create. A maximum of 10 is allowed in total. Default 1. - */ - addPointer(quantity?: integer): Phaser.Input.Pointer[]; - - /** - * 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. - * @param cursor The CSS to be used when setting the default cursor. - */ - setDefaultCursor(cursor: string): Phaser.Input.InputPlugin; - - /** - * The x coordinates 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. - */ - readonly x: number; - - /** - * The y coordinates 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. - */ - readonly y: number; - - /** - * Are any mouse or touch pointers currently over the game canvas? - */ - readonly isOver: boolean; - - /** - * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. - * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` - * which will always map to the most recently interacted pointer. - */ - readonly mousePointer: Phaser.Input.Pointer; - - /** - * The current active input Pointer. - */ - readonly activePointer: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer1: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer2: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer3: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer4: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer5: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer6: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer7: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer8: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer9: Phaser.Input.Pointer; - - /** - * A touch-based Pointer object. - * This will be `undefined` by default unless you add a new Pointer using `addPointer`. - */ - readonly pointer10: Phaser.Input.Pointer; - - /** - * An instance of the Keyboard Plugin class, if enabled via the `input.keyboard` Scene or Game Config property. - * Use this to create Key objects and listen for keyboard specific events. - */ - keyboard: Phaser.Input.Keyboard.KeyboardPlugin; - - } - - namespace InputPluginCache { - /** - * Static method called directly by the Core internal Plugins. - * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) - * Plugin is the object to instantiate to create the plugin - * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) - * @param key A reference used to get this plugin from the plugin cache. - * @param plugin The plugin to be stored. Should be the core object, not instantiated. - * @param mapping If this plugin is to be injected into the Input Plugin, this is the property key used. - * @param settingsKey The key in the Scene Settings to check to see if this plugin should install or not. - * @param configKey The key in the Game Config to check to see if this plugin should install or not. - */ - function register(key: string, plugin: Function, mapping: string, settingsKey: string, configKey: string): void; - - /** - * Returns the input plugin object from the cache based on the given key. - * @param key The key of the input plugin to get. - */ - function getCore(key: string): Phaser.Types.Input.InputPluginContainer; - - /** - * Installs all of the registered Input Plugins into the given target. - * @param target The target InputPlugin to install the plugins into. - */ - function install(target: Phaser.Input.InputPlugin): void; - - /** - * Removes an input plugin based on the given key. - * @param key The key of the input plugin to remove. - */ - function remove(key: string): void; - - } - - namespace Keyboard { - /** - * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them - * it will emit a `keycombomatch` event from the Keyboard Manager. - * - * The keys to be listened for can be defined as: - * - * A string (i.e. 'ATARI') - * An array of either integers (key codes) or strings, or a mixture of both - * An array of objects (such as Key objects) with a public 'keyCode' property - * - * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) - * you could pass the following array of key codes: - * - * ```javascript - * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); - * - * this.input.keyboard.on('keycombomatch', function (event) { - * console.log('Konami Code entered!'); - * }); - * ``` - * - * Or, to listen for the user entering the word PHASER: - * - * ```javascript - * this.input.keyboard.createCombo('PHASER'); - * ``` - */ - class KeyCombo { - /** - * - * @param keyboardPlugin A reference to the Keyboard Plugin. - * @param keys The keys that comprise this combo. - * @param config A Key Combo configuration object. - */ - constructor(keyboardPlugin: Phaser.Input.Keyboard.KeyboardPlugin, keys: string | integer[] | object[], config?: Phaser.Types.Input.Keyboard.KeyComboConfig); - - /** - * A reference to the Keyboard Manager - */ - manager: Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * A flag that controls if this Key Combo is actively processing keys or not. - */ - enabled: boolean; - - /** - * An array of the keycodes that comprise this combo. - */ - keyCodes: any[]; - - /** - * The current keyCode the combo is waiting for. - */ - current: integer; - - /** - * The current index of the key being waited for in the 'keys' string. - */ - index: integer; - - /** - * The length of this combo (in keycodes) - */ - size: number; - - /** - * The time the previous key in the combo was matched. - */ - timeLastMatched: number; - - /** - * Has this Key Combo been matched yet? - */ - matched: boolean; - - /** - * The time the entire combo was matched. - */ - timeMatched: number; - - /** - * If they press the wrong key do we reset the combo? - */ - resetOnWrongKey: boolean; - - /** - * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. - */ - maxKeyDelay: integer; - - /** - * If previously matched and they press the first key of the combo again, will it reset? - */ - resetOnMatch: boolean; - - /** - * If the combo matches, will it delete itself? - */ - deleteOnMatch: boolean; - - /** - * How far complete is this combo? A value between 0 and 1. - */ - readonly progress: number; - - /** - * Destroys this Key Combo and all of its references. - */ - destroy(): void; - - } - - namespace Events { - /** - * 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. - */ - const ANY_KEY_DOWN: any; - - /** - * The Global Key Up Event. - * - * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. - * - * Listen to this event from within a Scene using: `this.input.keyboard.on('keyup', listener)`. - * - * You can also listen for a specific key being released. See [Keyboard.Events.KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:KEY_UP} for details. - * - * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. - */ - const ANY_KEY_UP: any; - - /** - * The Key Combo Match Event. - * - * This event is dispatched by the Keyboard Plugin when a [Key Combo]{@link Phaser.Input.Keyboard.KeyCombo} is matched. - * - * Listen for this event from the Key Plugin after a combo has been created: - * - * ```javascript - * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); - * - * this.input.keyboard.on('keycombomatch', function (event) { - * console.log('Konami Code entered!'); - * }); - * ``` - */ - const COMBO_MATCH: any; - - /** - * The Key Down Event. - * - * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is pressed. - * - * Listen for this event from the Key object instance directly: - * - * ```javascript - * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); - * - * spaceBar.on('down', 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. - */ - const DOWN: any; - - /** - * 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. - */ - const KEY_DOWN: any; - - /** - * The Key Up Event. - * - * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. - * - * Unlike the `ANY_KEY_UP` event, this one has a special dynamic event name. For example, to listen for the `A` key being released - * use the following from within a Scene: `this.input.keyboard.on('keyup-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('keyup-SPACE', listener)`. - * - * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. - * - * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. - */ - const KEY_UP: any; - - /** - * The Key Up Event. - * - * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is released. - * - * Listen for this event from the Key object instance directly: - * - * ```javascript - * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); - * - * spaceBar.on('up', listener) - * ``` - * - * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. - */ - const UP: any; - - } - - /** - * The Keyboard Manager is a helper class that belongs to the global Input Manager. - * - * Its role is to listen for native DOM Keyboard Events and then store them for further processing by the Keyboard Plugin. - * - * You do not need to create this class directly, the Input Manager will create an instance of it automatically if keyboard - * input has been enabled in the Game Config. - */ - class KeyboardManager { - /** - * - * @param inputManager A reference to the Input Manager. - */ - constructor(inputManager: Phaser.Input.InputManager); - - /** - * A reference to the Input Manager. - */ - manager: Phaser.Input.InputManager; - - /** - * A flag that controls if the non-modified keys, matching those stored in the `captures` array, - * have `preventDefault` called on them or not. - * - * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are - * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). - * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. - * However, if the user presses just the r key on its own, it will have its event prevented. - * - * If you wish to stop capturing the keys, for example switching out to a DOM based element, then - * you can toggle this property at run-time. - */ - preventDefault: boolean; - - /** - * An array of Key Code values that will automatically have `preventDefault` called on them, - * as long as the `KeyboardManager.preventDefault` boolean is set to `true`. - * - * By default the array is empty. - * - * The key must be non-modified when pressed in order to be captured. - * - * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are - * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). - * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. - * However, if the user presses just the r key on its own, it will have its event prevented. - * - * If you wish to stop capturing the keys, for example switching out to a DOM based element, then - * you can toggle the `KeyboardManager.preventDefault` boolean at run-time. - * - * If you need more specific control, you can create Key objects and set the flag on each of those instead. - * - * This array can be populated via the Game Config by setting the `input.keyboard.capture` array, or you - * can call the `addCapture` method. See also `removeCapture` and `clearCaptures`. - */ - captures: integer[]; - - /** - * A boolean that controls if the Keyboard Manager is enabled or not. - * Can be toggled on the fly. - */ - enabled: boolean; - - /** - * The Keyboard Event target, as defined in the Game Config. - * Typically the window in which the game is rendering, but can be any interactive DOM element. - */ - target: any; - - /** - * The Key Down Event handler. - * This function is sent the native DOM KeyEvent. - * Initially empty and bound in the `startListeners` method. - */ - onKeyDown: Function; - - /** - * The Key Up Event handler. - * This function is sent the native DOM KeyEvent. - * Initially empty and bound in the `startListeners` method. - */ - onKeyUp: Function; - - /** - * Starts the Keyboard Event listeners running. - * This is called automatically and does not need to be manually invoked. - */ - startListeners(): void; - - /** - * Stops the Key Event listeners. - * This is called automatically and does not need to be manually invoked. - */ - stopListeners(): void; - - /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * - * This `addCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser - * and cause the default browser behavior. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent - * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. - * - * You can pass in a single key code value, or an array of key codes, or a string: - * - * ```javascript - * this.input.keyboard.addCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.addCapture([ 62, 63, 64 ]); - * ``` - * - * Or a string: - * - * ```javascript - * this.input.keyboard.addCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * - * If there are active captures after calling this method, the `preventDefault` property is set to `true`. - * @param keycode The Key Codes to enable capture for, preventing them reaching the browser. - */ - addCapture(keycode: string | integer | integer[] | any[]): void; - - /** - * Removes an existing key capture. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove - * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. - * - * You can pass in a single key code value, or an array of key codes, or a string: - * - * ```javascript - * this.input.keyboard.removeCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.removeCapture([ 62, 63, 64 ]); - * ``` - * - * Or a string: - * - * ```javascript - * this.input.keyboard.removeCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * - * If there are no captures left after calling this method, the `preventDefault` property is set to `false`. - * @param keycode The Key Codes to disable capture for, allowing them reaching the browser again. - */ - removeCapture(keycode: string | integer | integer[] | any[]): void; - - /** - * Removes all keyboard captures and sets the `preventDefault` property to `false`. - */ - clearCaptures(): void; - - /** - * Destroys this Keyboard Manager instance. - */ - destroy(): void; - - } - - /** - * 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. - * - * 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 { - /** - * - * @param sceneInputPlugin A reference to the Scene Input Plugin that the KeyboardPlugin belongs to. - */ - constructor(sceneInputPlugin: Phaser.Input.InputPlugin); - - /** - * A reference to the core game, so we can listen for visibility events. - */ - game: Phaser.Game; - - /** - * A reference to the Scene that this Input Plugin is responsible for. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene Systems Settings. - */ - settings: Phaser.Types.Scenes.SettingsObject; - - /** - * A reference to the Scene Input Plugin that created this Keyboard Plugin. - */ - sceneInputPlugin: Phaser.Input.InputPlugin; - - /** - * A reference to the global Keyboard Manager. - */ - manager: Phaser.Input.InputPlugin; - - /** - * A boolean that controls if this Keyboard Plugin is enabled or not. - * Can be toggled on the fly. - */ - enabled: boolean; - - /** - * An array of Key objects to process. - */ - keys: Phaser.Input.Keyboard.Key[]; - - /** - * An array of KeyCombo objects to process. - */ - combos: Phaser.Input.Keyboard.KeyCombo[]; - - /** - * Checks to see if both this plugin and the Scene to which it belongs is active. - */ - isActive(): boolean; - - /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * - * This `addCapture` method enables consuming keyboard events for specific keys, so they don't bubble up the browser - * and cause the default behaviors. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent - * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. - * - * You can pass a single key code value: - * - * ```javascript - * this.input.keyboard.addCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.addCapture([ 62, 63, 64 ]); - * ``` - * - * Or, a comma-delimited string: - * - * ```javascript - * this.input.keyboard.addCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * @param keycode The Key Codes to enable event capture for. - */ - addCapture(keycode: string | integer | integer[] | any[]): Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * Removes an existing key capture. - * - * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove - * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. - * - * You can pass a single key code value: - * - * ```javascript - * this.input.keyboard.removeCapture(62); - * ``` - * - * An array of key codes: - * - * ```javascript - * this.input.keyboard.removeCapture([ 62, 63, 64 ]); - * ``` - * - * Or, a comma-delimited string: - * - * ```javascript - * this.input.keyboard.removeCapture('W,S,A,D'); - * ``` - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * - * You can also provide an array mixing both strings and key code integers. - * @param keycode The Key Codes to disable event capture for. - */ - removeCapture(keycode: string | integer | integer[] | any[]): Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * Returns an array that contains all of the keyboard captures currently enabled. - */ - getCaptures(): integer[]; - - /** - * Allows Phaser to prevent any key captures you may have defined from bubbling up the browser. - * You can use this to re-enable event capturing if you had paused it via `disableGlobalCapture`. - */ - enableGlobalCapture(): Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * Disables Phaser from preventing any key captures you may have defined, without actually removing them. - * You can use this to temporarily disable event capturing if, for example, you swap to a DOM element. - */ - disableGlobalCapture(): Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * Removes all keyboard captures. - * - * Note that this is a global change. It will clear all event captures across your game, not just for this specific Scene. - */ - clearCaptures(): Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right, and also Space Bar and shift. - */ - createCursorKeys(): Phaser.Types.Input.Keyboard.CursorKeys; - - /** - * A practical way to create an object containing user selected hotkeys. - * - * For example: - * - * ```javascript - * this.input.keyboard.addKeys({ 'up': Phaser.Input.Keyboard.KeyCodes.W, 'down': Phaser.Input.Keyboard.KeyCodes.S }); - * ``` - * - * would return an object containing the properties (`up` and `down`) mapped to W and S {@link Phaser.Input.Keyboard.Key} objects. - * - * You can also pass in a comma-separated string: - * - * ```javascript - * this.input.keyboard.addKeys('W,S,A,D'); - * ``` - * - * Which will return an object with the properties W, S, A and D mapped to the relevant Key objects. - * - * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. - * @param keys An object containing Key Codes, or a comma-separated string. - * @param enableCapture Automatically call `preventDefault` on the native DOM browser event for the key codes being added. Default true. - * @param emitOnRepeat Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). Default false. - */ - addKeys(keys: object | string, enableCapture?: boolean, emitOnRepeat?: boolean): object; - - /** - * Adds a Key object to this Keyboard Plugin. - * - * The given argument can be either an existing Key object, a string, such as `A` or `SPACE`, or a key code value. - * - * If a Key object is given, and one already exists matching the same key code, the existing one is replaced with the new one. - * @param key Either a Key object, a string, such as `A` or `SPACE`, or a key code value. - * @param enableCapture Automatically call `preventDefault` on the native DOM browser event for the key codes being added. Default true. - * @param emitOnRepeat Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). Default false. - */ - addKey(key: Phaser.Input.Keyboard.Key | string | integer, enableCapture?: boolean, emitOnRepeat?: boolean): Phaser.Input.Keyboard.Key; - - /** - * Removes a Key object from this Keyboard Plugin. - * - * The given argument can be either a Key object, a string, such as `A` or `SPACE`, or a key code value. - * @param key Either a Key object, a string, such as `A` or `SPACE`, or a key code value. - * @param destroy Call `Key.destroy` on the removed Key object? Default false. - */ - removeKey(key: Phaser.Input.Keyboard.Key | string | integer, destroy?: boolean): Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * Creates a new KeyCombo. - * - * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them - * it will emit a `keycombomatch` event from this Keyboard Plugin. - * - * The keys to be listened for can be defined as: - * - * A string (i.e. 'ATARI') - * An array of either integers (key codes) or strings, or a mixture of both - * An array of objects (such as Key objects) with a public 'keyCode' property - * - * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) - * you could pass the following array of key codes: - * - * ```javascript - * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); - * - * this.input.keyboard.on('keycombomatch', function (event) { - * console.log('Konami Code entered!'); - * }); - * ``` - * - * Or, to listen for the user entering the word PHASER: - * - * ```javascript - * this.input.keyboard.createCombo('PHASER'); - * ``` - * @param keys The keys that comprise this combo. - * @param config A Key Combo configuration object. - */ - createCombo(keys: string | integer[] | object[], config?: Phaser.Types.Input.Keyboard.KeyComboConfig): Phaser.Input.Keyboard.KeyCombo; - - /** - * Checks if the given Key object is currently being held down. - * - * The difference between this method and checking the `Key.isDown` property directly is that you can provide - * a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted - * it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it - * will only return `true` every 100ms. - * - * If the Keyboard Plugin has been disabled, this method will always return `false`. - * @param key A Key object. - * @param duration The duration which must have elapsed before this Key is considered as being down. Default 0. - */ - checkDown(key: Phaser.Input.Keyboard.Key, duration?: number): boolean; - - /** - * Resets all Key objects created by _this_ Keyboard Plugin back to their default un-pressed states. - * This can only reset keys created via the `addKey`, `addKeys` or `createCursorKeys` methods. - * If you have created a Key object directly you'll need to reset it yourself. - * - * This method is called automatically when the Keyboard Plugin shuts down, but can be - * invoked directly at any time you require. - */ - resetKeys(): Phaser.Input.Keyboard.KeyboardPlugin; - - } - - /** - * 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. - * @param key The Key object to test. - * @param duration The duration, in ms, within which the key must have been pressed down. Default 50. - */ - function DownDuration(key: Phaser.Input.Keyboard.Key, duration?: integer): boolean; - - /** - * The justDown value allows you to test if this Key has just been pressed down or not. - * - * When you check this value it will return `true` if the Key is down, otherwise `false`. - * - * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. - * This allows you to use it in situations where you want to check if this key is down without using an event, such as in a core game loop. - * @param key The Key to check to see if it's just down or not. - */ - function JustDown(key: Phaser.Input.Keyboard.Key): boolean; - - /** - * The justUp value allows you to test if this Key has just been released or not. - * - * When you check this value it will return `true` if the Key is up, otherwise `false`. - * - * You can only call JustUp once per key release. It will only return `true` once, until the Key is pressed down and released again. - * This allows you to use it in situations where you want to check if this key is up without using an event, such as in a core game loop. - * @param key The Key to check to see if it's just up or not. - */ - function JustUp(key: Phaser.Input.Keyboard.Key): boolean; - - /** - * A generic Key object which can be passed to the Process functions (and so on) - * keycode must be an integer - */ - class Key extends Phaser.Events.EventEmitter { - /** - * - * @param plugin The Keyboard Plugin instance that owns this Key object. - * @param keyCode The keycode of this key. - */ - constructor(plugin: Phaser.Input.Keyboard.KeyboardPlugin, keyCode: integer); - - /** - * The Keyboard Plugin instance that owns this Key object. - */ - plugin: Phaser.Input.Keyboard.KeyboardPlugin; - - /** - * The keycode of this key. - */ - keyCode: integer; - - /** - * The original DOM event. - */ - originalEvent: KeyboardEvent; - - /** - * Can this Key be processed? - */ - enabled: boolean; - - /** - * The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. - */ - isDown: boolean; - - /** - * The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. - */ - isUp: boolean; - - /** - * The down state of the ALT key, if pressed at the same time as this key. - */ - altKey: boolean; - - /** - * The down state of the CTRL key, if pressed at the same time as this key. - */ - ctrlKey: boolean; - - /** - * The down state of the SHIFT key, if pressed at the same time as this key. - */ - shiftKey: boolean; - - /** - * The down state of the Meta key, if pressed at the same time as this key. - * On a Mac the Meta Key is the Command key. On Windows keyboards, it's the Windows key. - */ - metaKey: boolean; - - /** - * The location of the modifier key. 0 for standard (or unknown), 1 for left, 2 for right, 3 for numpad. - */ - location: number; - - /** - * The timestamp when the key was last pressed down. - */ - timeDown: number; - - /** - * The number of milliseconds this key was held down for in the previous down - up sequence. - * This value isn't updated every game step, only when the Key changes state. - * To get the current duration use the `getDuration` method. - */ - duration: number; - - /** - * The timestamp when the key was last released. - */ - timeUp: number; - - /** - * When a key is held down should it continuously fire the `down` event each time it repeats? - * - * By default it will emit the `down` event just once, but if you wish to receive the event - * for each repeat as well, enable this property. - */ - emitOnRepeat: boolean; - - /** - * If a key is held down this holds down the number of times the key has 'repeated'. - */ - repeats: number; - - /** - * Controls if this Key will continuously emit a `down` event while being held down (true), - * or emit the event just once, on first press, and then skip future events (false). - * @param value Emit `down` events on repeated key down actions, or just once? - */ - setEmitOnRepeat(value: boolean): Phaser.Input.Keyboard.Key; - - /** - * Processes the Key Down action for this Key. - * Called automatically by the Keyboard Plugin. - * @param event The native DOM Keyboard event. - */ - onDown(event: KeyboardEvent): void; - - /** - * Processes the Key Up action for this Key. - * Called automatically by the Keyboard Plugin. - * @param event The native DOM Keyboard event. - */ - onUp(event: KeyboardEvent): void; - - /** - * Resets this Key object back to its default un-pressed state. - */ - reset(): Phaser.Input.Keyboard.Key; - - /** - * Returns the duration, in ms, that the Key has been held down for. - * - * If the key is not currently down it will return zero. - * - * The get the duration the Key was held down for in the previous up-down cycle, - * use the `Key.duration` property value instead. - */ - getDuration(): number; - - /** - * Removes any bound event handlers and removes local references. - */ - destroy(): void; - - } - - /** - * Keyboard Codes. - */ - namespace KeyCodes { - /** - * The BACKSPACE key. - */ - var BACKSPACE: integer; - - /** - * The TAB key. - */ - var TAB: integer; - - /** - * The ENTER key. - */ - var ENTER: integer; - - /** - * The SHIFT key. - */ - var SHIFT: integer; - - /** - * The CTRL key. - */ - var CTRL: integer; - - /** - * The ALT key. - */ - var ALT: integer; - - /** - * The PAUSE key. - */ - var PAUSE: integer; - - /** - * The CAPS_LOCK key. - */ - var CAPS_LOCK: integer; - - /** - * The ESC key. - */ - var ESC: integer; - - /** - * The SPACE key. - */ - var SPACE: integer; - - /** - * The PAGE_UP key. - */ - var PAGE_UP: integer; - - /** - * The PAGE_DOWN key. - */ - var PAGE_DOWN: integer; - - /** - * The END key. - */ - var END: integer; - - /** - * The HOME key. - */ - var HOME: integer; - - /** - * The LEFT key. - */ - var LEFT: integer; - - /** - * The UP key. - */ - var UP: integer; - - /** - * The RIGHT key. - */ - var RIGHT: integer; - - /** - * The DOWN key. - */ - var DOWN: integer; - - /** - * The PRINT_SCREEN key. - */ - var PRINT_SCREEN: integer; - - /** - * The INSERT key. - */ - var INSERT: integer; - - /** - * The DELETE key. - */ - var DELETE: integer; - - /** - * The ZERO key. - */ - var ZERO: integer; - - /** - * The ONE key. - */ - var ONE: integer; - - /** - * The TWO key. - */ - var TWO: integer; - - /** - * The THREE key. - */ - var THREE: integer; - - /** - * The FOUR key. - */ - var FOUR: integer; - - /** - * The FIVE key. - */ - var FIVE: integer; - - /** - * The SIX key. - */ - var SIX: integer; - - /** - * The SEVEN key. - */ - var SEVEN: integer; - - /** - * The EIGHT key. - */ - var EIGHT: integer; - - /** - * The NINE key. - */ - var NINE: integer; - - /** - * The NUMPAD_ZERO key. - */ - var NUMPAD_ZERO: integer; - - /** - * The NUMPAD_ONE key. - */ - var NUMPAD_ONE: integer; - - /** - * The NUMPAD_TWO key. - */ - var NUMPAD_TWO: integer; - - /** - * The NUMPAD_THREE key. - */ - var NUMPAD_THREE: integer; - - /** - * The NUMPAD_FOUR key. - */ - var NUMPAD_FOUR: integer; - - /** - * The NUMPAD_FIVE key. - */ - var NUMPAD_FIVE: integer; - - /** - * The NUMPAD_SIX key. - */ - var NUMPAD_SIX: integer; - - /** - * The NUMPAD_SEVEN key. - */ - var NUMPAD_SEVEN: integer; - - /** - * The NUMPAD_EIGHT key. - */ - var NUMPAD_EIGHT: integer; - - /** - * The NUMPAD_NINE key. - */ - var NUMPAD_NINE: integer; - - /** - * The Numpad Addition (+) key. - */ - var NUMPAD_ADD: integer; - - /** - * The Numpad Subtraction (-) key. - */ - var NUMPAD_SUBTRACT: integer; - - /** - * The A key. - */ - var A: integer; - - /** - * The B key. - */ - var B: integer; - - /** - * The C key. - */ - var C: integer; - - /** - * The D key. - */ - var D: integer; - - /** - * The E key. - */ - var E: integer; - - /** - * The F key. - */ - var F: integer; - - /** - * The G key. - */ - var G: integer; - - /** - * The H key. - */ - var H: integer; - - /** - * The I key. - */ - var I: integer; - - /** - * The J key. - */ - var J: integer; - - /** - * The K key. - */ - var K: integer; - - /** - * The L key. - */ - var L: integer; - - /** - * The M key. - */ - var M: integer; - - /** - * The N key. - */ - var N: integer; - - /** - * The O key. - */ - var O: integer; - - /** - * The P key. - */ - var P: integer; - - /** - * The Q key. - */ - var Q: integer; - - /** - * The R key. - */ - var R: integer; - - /** - * The S key. - */ - var S: integer; - - /** - * The T key. - */ - var T: integer; - - /** - * The U key. - */ - var U: integer; - - /** - * The V key. - */ - var V: integer; - - /** - * The W key. - */ - var W: integer; - - /** - * The X key. - */ - var X: integer; - - /** - * The Y key. - */ - var Y: integer; - - /** - * The Z key. - */ - var Z: integer; - - /** - * The F1 key. - */ - var F1: integer; - - /** - * The F2 key. - */ - var F2: integer; - - /** - * The F3 key. - */ - var F3: integer; - - /** - * The F4 key. - */ - var F4: integer; - - /** - * The F5 key. - */ - var F5: integer; - - /** - * The F6 key. - */ - var F6: integer; - - /** - * The F7 key. - */ - var F7: integer; - - /** - * The F8 key. - */ - var F8: integer; - - /** - * The F9 key. - */ - var F9: integer; - - /** - * The F10 key. - */ - var F10: integer; - - /** - * The F11 key. - */ - var F11: integer; - - /** - * The F12 key. - */ - var F12: integer; - - /** - * The SEMICOLON key. - */ - var SEMICOLON: integer; - - /** - * The PLUS key. - */ - var PLUS: integer; - - /** - * The COMMA key. - */ - var COMMA: integer; - - /** - * The MINUS key. - */ - var MINUS: integer; - - /** - * The PERIOD key. - */ - var PERIOD: integer; - - /** - * The FORWARD_SLASH key. - */ - var FORWARD_SLASH: integer; - - /** - * The BACK_SLASH key. - */ - var BACK_SLASH: integer; - - /** - * The QUOTES key. - */ - var QUOTES: integer; - - /** - * The BACKTICK key. - */ - var BACKTICK: integer; - - /** - * The OPEN_BRACKET key. - */ - var OPEN_BRACKET: integer; - - /** - * The CLOSED_BRACKET key. - */ - var CLOSED_BRACKET: integer; - - /** - * The SEMICOLON_FIREFOX key. - */ - var SEMICOLON_FIREFOX: integer; - - /** - * The COLON key. - */ - var COLON: integer; - - /** - * The COMMA_FIREFOX_WINDOWS key. - */ - var COMMA_FIREFOX_WINDOWS: integer; - - /** - * The COMMA_FIREFOX key. - */ - var COMMA_FIREFOX: integer; - - /** - * The BRACKET_RIGHT_FIREFOX key. - */ - var BRACKET_RIGHT_FIREFOX: integer; - - /** - * The BRACKET_LEFT_FIREFOX key. - */ - var BRACKET_LEFT_FIREFOX: integer; - - } - - /** - * 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. - * @param key The Key object to test. - * @param duration The duration, in ms, within which the key must have been released. Default 50. - */ - function UpDuration(key: Phaser.Input.Keyboard.Key, duration?: integer): boolean; - - } - - namespace Mouse { - /** - * The Mouse Manager is a helper class that belongs to the Input Manager. - * - * Its role is to listen for native DOM Mouse Events and then pass them onto the Input Manager for further processing. - * - * You do not need to create this class directly, the Input Manager will create an instance of it automatically. - */ - class MouseManager { - /** - * - * @param inputManager A reference to the Input Manager. - */ - constructor(inputManager: Phaser.Input.InputManager); - - /** - * A reference to the Input Manager. - */ - manager: Phaser.Input.InputManager; - - /** - * If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. - */ - capture: boolean; - - /** - * A boolean that controls if the Mouse Manager is enabled or not. - * Can be toggled on the fly. - */ - enabled: boolean; - - /** - * The Mouse target, as defined in the Game Config. - * Typically the canvas to which the game is rendering, but can be any interactive DOM element. - */ - target: any; - - /** - * If the mouse has been pointer locked successfully this will be set to true. - */ - locked: boolean; - - /** - * The Mouse Move Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseMove: Function; - - /** - * The Mouse Down Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseDown: Function; - - /** - * The Mouse Up Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseUp: Function; - - /** - * The Mouse Down Event handler specifically for events on the Window. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseDownWindow: Function; - - /** - * The Mouse Up Event handler specifically for events on the Window. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseUpWindow: Function; - - /** - * The Mouse Over Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseOver: Function; - - /** - * The Mouse Out Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseOut: Function; - - /** - * The Mouse Wheel Event handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - onMouseWheel: Function; - - /** - * Internal pointerLockChange handler. - * This function is sent the native DOM MouseEvent. - * Initially empty and bound in the `startListeners` method. - */ - pointerLockChange: Function; - - /** - * Attempts to disable the context menu from appearing if you right-click on the browser. - * - * Works by listening for the `contextmenu` event and prevent defaulting it. - * - * Use this if you need to enable right-button mouse support in your game, and the browser - * menu keeps getting in the way. - */ - disableContextMenu(): Phaser.Input.Mouse.MouseManager; - - /** - * 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. - */ - requestPointerLock(): void; - - /** - * If the browser supports pointer lock, this will request that the pointer lock is released. If - * the browser successfully enters a locked state, a 'POINTER_LOCK_CHANGE_EVENT' will be - * dispatched - from the game's input manager - with an `isPointerLocked` property. - */ - releasePointerLock(): void; - - /** - * Starts the Mouse Event listeners running. - * This is called automatically and does not need to be manually invoked. - */ - startListeners(): void; - - /** - * Stops the Mouse Event listeners. - * This is called automatically and does not need to be manually invoked. - */ - stopListeners(): void; - - /** - * Destroys this Mouse Manager instance. - */ - destroy(): void; - - } - - } - - /** - * A Pointer object encapsulates both mouse and touch input within Phaser. - * - * By default, Phaser will create 2 pointers for your game to use. If you require more, i.e. for a multi-touch - * game, then use the `InputPlugin.addPointer` method to do so, rather than instantiating this class directly, - * otherwise it won't be managed by the input system. - * - * You can reference the current active pointer via `InputPlugin.activePointer`. You can also use the properties - * `InputPlugin.pointer1` through to `pointer10`, for each pointer you have enabled in your game. - * - * The properties of this object are set by the Input Plugin during processing. This object is then sent in all - * input related events that the Input Plugin emits, so you can reference properties from it directly in your - * callbacks. - */ - class Pointer { - /** - * - * @param manager A reference to the Input Manager. - * @param id The internal ID of this Pointer. - */ - constructor(manager: Phaser.Input.InputManager, id: integer); - - /** - * A reference to the Input Manager. - */ - manager: Phaser.Input.InputManager; - - /** - * The internal ID of this Pointer. - */ - readonly id: integer; - - /** - * The most recent native DOM Event this Pointer has processed. - */ - event: TouchEvent | MouseEvent; - - /** - * 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. - */ - readonly downElement: any; - - /** - * 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. - */ - readonly upElement: any; - - /** - * The camera the Pointer interacted with during its last update. - * - * A Pointer can only ever interact with one camera at once, which will be the top-most camera - * in the list should multiple cameras be positioned on-top of each other. - */ - camera: Phaser.Cameras.Scene2D.Camera; - - /** - * A read-only property that indicates which button was pressed, or released, on the pointer - * during the most recent event. It is only set during `up` and `down` events. - * - * On Touch devices the value is always 0. - * - * Users may change the configuration of buttons on their pointing device so that if an event's button property - * is zero, it may not have been caused by the button that is physically left–most on the pointing device; - * however, it should behave as if the left button was clicked in the standard button layout. - */ - readonly button: integer; - - /** - * 0: No button or un-initialized - * 1: Left button - * 2: Right button - * 4: Wheel button or middle button - * 8: 4th button (typically the "Browser Back" button) - * 16: 5th button (typically the "Browser Forward" button) - * - * For a mouse configured for left-handed use, the button actions are reversed. - * In this case, the values are read from right to left. - */ - buttons: integer; - - /** - * The position of the Pointer in screen space. - */ - readonly position: Phaser.Math.Vector2; - - /** - * The previous position of the Pointer in screen space. - * - * The old x and y values are stored in here during the InputManager.transformPointer call. - * - * Use the properties `velocity`, `angle` and `distance` to create your own gesture recognition. - */ - readonly prevPosition: Phaser.Math.Vector2; - - /** - * 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. - */ - readonly velocity: Phaser.Math.Vector2; - - /** - * 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. - */ - readonly angle: number; - - /** - * 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 buttons was pressed down, - * then use the `Pointer.getDistance` method. - */ - readonly distance: number; - - /** - * The smoothing factor to apply to the Pointer position. - * - * Due to their nature, pointer positions are inherently noisy. While this is fine for lots of games, if you need cleaner positions - * then you can set this value to apply an automatic smoothing to the positions as they are recorded. - * - * The default value of zero means 'no smoothing'. - * Set to a small value, such as 0.2, to apply an average level of smoothing between positions. You can do this by changing this - * value directly, or by setting the `input.smoothFactor` property in the Game Config. - * - * Positions are only smoothed when the pointer moves. If the primary button on this Pointer enters an Up or Down state, then the position - * is always precise, and not smoothed. - */ - smoothFactor: number; - - /** - * The factor applied to the motion smoothing each frame. - * - * This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, - * angle and distance of the Pointer. It's applied every frame, until the midPoint reaches the current - * position of the Pointer. 0.2 provides a good average but can be increased if you need a - * quicker update and are working in a high performance environment. Never set this value to - * zero. - */ - motionFactor: number; - - /** - * The x position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. - * - * If you wish to use this value _outside_ of an input event handler then you should update it first by calling - * the `Pointer.updateWorldPoint` method. - */ - worldX: number; - - /** - * The y position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. - * - * If you wish to use this value _outside_ of an input event handler then you should update it first by calling - * the `Pointer.updateWorldPoint` method. - */ - worldY: number; - - /** - * Time when this Pointer was most recently moved (regardless of the state of its buttons, if any) - */ - moveTime: number; - - /** - * X coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. - */ - downX: number; - - /** - * Y coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. - */ - downY: number; - - /** - * Time when Button 1 (left button), or Touch, was pressed, used for dragging objects. - */ - downTime: number; - - /** - * X coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. - */ - upX: number; - - /** - * Y coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. - */ - upY: number; - - /** - * Time when Button 1 (left button), or Touch, was released, used for dragging objects. - */ - upTime: number; - - /** - * Is the primary button down? (usually button 0, the left mouse button) - */ - primaryDown: boolean; - - /** - * Is _any_ button on this pointer considered as being down? - */ - isDown: boolean; - - /** - * Did the previous input event come from a Touch input (true) or Mouse? (false) - */ - wasTouch: boolean; - - /** - * Did this Pointer get canceled by a touchcancel event? - * - * Note: "canceled" is the American-English spelling of "cancelled". Please don't submit PRs correcting it! - */ - wasCanceled: boolean; - - /** - * If the mouse is locked, the horizontal relative movement of the Pointer in pixels since last frame. - */ - movementX: number; - - /** - * If the mouse is locked, the vertical relative movement of the Pointer in pixels since last frame. - */ - movementY: number; - - /** - * The identifier property of the Pointer as set by the DOM event when this Pointer is started. - */ - identifier: number; - - /** - * The pointerId property of the Pointer as set by the DOM event when this Pointer is started. - * The browser can and will recycle this value. - */ - pointerId: number; - - /** - * An active Pointer is one that is currently pressed down on the display. - * A Mouse is always considered as active. - */ - active: boolean; - - /** - * Is this pointer Pointer Locked? - * - * Only a mouse pointer can be locked and it only becomes locked when requested via - * the browsers Pointer Lock API. - * - * You can request this by calling the `this.input.mouse.requestPointerLock()` method from - * a `pointerdown` or `pointerup` event handler. - */ - readonly locked: boolean; - - /** - * The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. - */ - deltaX: number; - - /** - * The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. - * This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. - */ - deltaY: number; - - /** - * The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. - */ - deltaZ: number; - - /** - * Takes a Camera and updates this Pointer's `worldX` and `worldY` values so they are - * the result of a translation through the given Camera. - * - * Note that the values will be automatically replaced the moment the Pointer is - * updated by an input event, such as a mouse move, so should be used immediately. - * @param camera The Camera which is being tested against. - */ - updateWorldPoint(camera: Phaser.Cameras.Scene2D.Camera): this; - - /** - * 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. - * @param camera The Camera to use for the translation. - * @param output A Vector2-like object in which to store the translated position. - */ - positionToCamera(camera: Phaser.Cameras.Scene2D.Camera, output?: Phaser.Math.Vector2 | object): Phaser.Math.Vector2 | object; - - /** - * Checks to see if any buttons are being held down on this Pointer. - */ - noButtonDown(): boolean; - - /** - * Checks to see if the left button is being held down on this Pointer. - */ - leftButtonDown(): boolean; - - /** - * Checks to see if the right button is being held down on this Pointer. - */ - rightButtonDown(): boolean; - - /** - * Checks to see if the middle button is being held down on this Pointer. - */ - middleButtonDown(): boolean; - - /** - * Checks to see if the back button is being held down on this Pointer. - */ - backButtonDown(): boolean; - - /** - * Checks to see if the forward button is being held down on this Pointer. - */ - forwardButtonDown(): boolean; - - /** - * Checks to see if the left button was just released on this Pointer. - */ - leftButtonReleased(): boolean; - - /** - * Checks to see if the right button was just released on this Pointer. - */ - rightButtonReleased(): boolean; - - /** - * Checks to see if the middle button was just released on this Pointer. - */ - middleButtonReleased(): boolean; - - /** - * Checks to see if the back button was just released on this Pointer. - */ - backButtonReleased(): boolean; - - /** - * Checks to see if the forward button was just released on this Pointer. - */ - forwardButtonReleased(): boolean; - - /** - * 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. - */ - getDistance(): number; - - /** - * 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` and `downY` values and the current 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. - */ - getDistanceX(): number; - - /** - * 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 `downX` and `downY` values and the current 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. - */ - getDistanceY(): number; - - /** - * 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 Pointer button was released. - */ - getDuration(): number; - - /** - * 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. - */ - getAngle(): number; - - /** - * Takes the previous and current Pointer positions and then generates an array of interpolated values between - * the two. The array will be populated up to the size of the `steps` argument. - * - * ```javaScript - * var points = pointer.getInterpolatedPosition(4); - * - * // points[0] = { x: 0, y: 0 } - * // points[1] = { x: 2, y: 1 } - * // points[2] = { x: 3, y: 2 } - * // points[3] = { x: 6, y: 3 } - * ``` - * - * Use this if you need to get smoothed values between the previous and current pointer positions. DOM pointer - * events can often fire faster than the main browser loop, and this will help you avoid janky movement - * especially if you have an object following a Pointer. - * - * Note that if you provide an output array it will only be populated up to the number of steps provided. - * It will not clear any previous data that may have existed beyond the range of the steps count. - * - * Internally it uses the Smooth Step interpolation calculation. - * @param steps The number of interpolation steps to use. Default 10. - * @param out An array to store the results in. If not provided a new one will be created. - */ - getInterpolatedPosition(steps?: integer, out?: any[]): any[]; - - /** - * Destroys this Pointer instance and resets its external references. - */ - destroy(): void; - - /** - * The x position of this Pointer. - * The value is in screen space. - * See `worldX` to get a camera converted position. - */ - x: number; - - /** - * The y position of this Pointer. - * The value is in screen space. - * See `worldY` to get a camera converted position. - */ - y: number; - - /** - * Time when this Pointer was most recently updated by a DOM Event. - * This comes directly from the `event.timeStamp` property. - * If no event has yet taken place, it will return zero. - */ - readonly time: number; - - } - - namespace Touch { - /** - * The Touch Manager is a helper class that belongs to the Input Manager. - * - * Its role is to listen for native DOM Touch Events and then pass them onto the Input Manager for further processing. - * - * You do not need to create this class directly, the Input Manager will create an instance of it automatically. - */ - class TouchManager { - /** - * - * @param inputManager A reference to the Input Manager. - */ - constructor(inputManager: Phaser.Input.InputManager); - - /** - * A reference to the Input Manager. - */ - manager: Phaser.Input.InputManager; - - /** - * If true the DOM events will have event.preventDefault applied to them, if false they will propagate fully. - */ - capture: boolean; - - /** - * A boolean that controls if the Touch Manager is enabled or not. - * Can be toggled on the fly. - */ - enabled: boolean; - - /** - * The Touch Event target, as defined in the Game Config. - * Typically the canvas to which the game is rendering, but can be any interactive DOM element. - */ - target: any; - - /** - * The Touch Start event handler function. - * Initially empty and bound in the `startListeners` method. - */ - onTouchStart: Function; - - /** - * The Touch Start event handler function specifically for events on the Window. - * Initially empty and bound in the `startListeners` method. - */ - onTouchStartWindow: Function; - - /** - * The Touch Move event handler function. - * Initially empty and bound in the `startListeners` method. - */ - onTouchMove: Function; - - /** - * The Touch End event handler function. - * Initially empty and bound in the `startListeners` method. - */ - onTouchEnd: Function; - - /** - * The Touch End event handler function specifically for events on the Window. - * Initially empty and bound in the `startListeners` method. - */ - onTouchEndWindow: Function; - - /** - * The Touch Cancel event handler function. - * Initially empty and bound in the `startListeners` method. - */ - onTouchCancel: Function; - - /** - * The Touch Cancel event handler function specifically for events on the Window. - * Initially empty and bound in the `startListeners` method. - */ - onTouchCancelWindow: Function; - - /** - * The Touch Over event handler function. - * Initially empty and bound in the `startListeners` method. - */ - onTouchOver: Function; - - /** - * The Touch Out event handler function. - * Initially empty and bound in the `startListeners` method. - */ - onTouchOut: Function; - - /** - * Attempts to disable the context menu from appearing if you touch-hold on the browser. - * - * Works by listening for the `contextmenu` event and prevent defaulting it. - * - * Use this if you need to disable the OS context menu on mobile. - */ - disableContextMenu(): Phaser.Input.Touch.TouchManager; - - /** - * Starts the Touch Event listeners running as long as an input target is set. - * - * This method is called automatically if Touch Input is enabled in the game config, - * which it is by default. However, you can call it manually should you need to - * delay input capturing until later in the game. - */ - startListeners(): void; - - /** - * Stops the Touch Event listeners. - * This is called automatically and does not need to be manually invoked. - */ - stopListeners(): void; - - /** - * Destroys this Touch Manager instance. - */ - destroy(): void; - - } - - } - - } - - namespace Loader { - /** - * The Loader is idle. - */ - var LOADER_IDLE: integer; - - /** - * The Loader is actively loading. - */ - var LOADER_LOADING: integer; - - /** - * The Loader is processing files is has loaded. - */ - var LOADER_PROCESSING: integer; - - /** - * The Loader has completed loading and processing. - */ - var LOADER_COMPLETE: integer; - - /** - * The Loader is shutting down. - */ - var LOADER_SHUTDOWN: integer; - - /** - * The Loader has been destroyed. - */ - var LOADER_DESTROYED: integer; - - /** - * File is in the load queue but not yet started - */ - var FILE_PENDING: integer; - - /** - * File has been started to load by the loader (onLoad called) - */ - var FILE_LOADING: integer; - - /** - * File has loaded successfully, awaiting processing - */ - var FILE_LOADED: integer; - - /** - * File failed to load - */ - var FILE_FAILED: integer; - - /** - * File is being processed (onProcess callback) - */ - var FILE_PROCESSING: integer; - - /** - * The File has errored somehow during processing. - */ - var FILE_ERRORED: integer; - - /** - * File has finished processing. - */ - var FILE_COMPLETE: integer; - - /** - * File has been destroyed - */ - var FILE_DESTROYED: integer; - - /** - * File was populated from local data and doesn't need an HTTP request - */ - var FILE_POPULATED: integer; - - namespace Events { - /** - * The Loader Plugin Add File Event. - * - * This event is dispatched when a new file is successfully added to the Loader and placed into the load queue. - * - * Listen to it from a Scene using: `this.load.on('addfile', listener)`. - * - * If you add lots of files to a Loader from a `preload` method, it will dispatch this event for each one of them. - */ - const ADD: any; - - /** - * The Loader Plugin Complete Event. - * - * This event is dispatched when the Loader has fully processed everything in the load queue. - * By this point every loaded file will now be in its associated cache and ready for use. - * - * Listen to it from a Scene using: `this.load.on('complete', listener)`. - */ - const COMPLETE: any; - - /** - * The File Load Complete Event. - * - * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. - * - * Listen to it from a Scene using: `this.load.on('filecomplete', listener)`. - * - * You can also listen for the completion of a specific file. See the [FILE_KEY_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_KEY_COMPLETE} event. - */ - const FILE_COMPLETE: any; - - /** - * The File Load Complete Event. - * - * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. - * - * It uses a special dynamic event name constructed from the key and type of the file. - * - * For example, if you have loaded an `image` with a key of `monster`, you can listen for it - * using the following: - * - * ```javascript - * this.load.on('filecomplete-image-monster', function (key, type, data) { - * // Your handler code - * }); - * ``` - * - * Or, if you have loaded a texture `atlas` with a key of `Level1`: - * - * ```javascript - * this.load.on('filecomplete-atlas-Level1', function (key, type, data) { - * // Your handler code - * }); - * ``` - * - * Or, if you have loaded a sprite sheet with a key of `Explosion` and a prefix of `GAMEOVER`: - * - * ```javascript - * this.load.on('filecomplete-spritesheet-GAMEOVERExplosion', function (key, type, data) { - * // Your handler code - * }); - * ``` - * - * You can also listen for the generic completion of files. See the [FILE_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_COMPLETE} event. - */ - const FILE_KEY_COMPLETE: any; - - /** - * The File Load Error Event. - * - * This event is dispatched by the Loader Plugin when a file fails to load. - * - * Listen to it from a Scene using: `this.load.on('loaderror', listener)`. - */ - const FILE_LOAD_ERROR: any; - - /** - * The File Load Event. - * - * This event is dispatched by the Loader Plugin when a file finishes loading, - * but _before_ it is processed and added to the internal Phaser caches. - * - * Listen to it from a Scene using: `this.load.on('load', listener)`. - */ - const FILE_LOAD: any; - - /** - * The File Load Progress Event. - * - * This event is dispatched by the Loader Plugin during the load of a file, if the browser receives a DOM ProgressEvent and - * the `lengthComputable` event property is true. Depending on the size of the file and browser in use, this may, or may not happen. - * - * Listen to it from a Scene using: `this.load.on('fileprogress', listener)`. - */ - const FILE_PROGRESS: any; - - /** - * The Loader Plugin Post Process Event. - * - * This event is dispatched by the Loader Plugin when the Loader has finished loading everything in the load queue. - * It is dispatched before the internal lists are cleared and each File is destroyed. - * - * Use this hook to perform any last minute processing of files that can only happen once the - * Loader has completed, but prior to it emitting the `complete` event. - * - * Listen to it from a Scene using: `this.load.on('postprocess', listener)`. - */ - const POST_PROCESS: any; - - /** - * The Loader Plugin Progress Event. - * - * This event is dispatched when the Loader updates its load progress, typically as a result of a file having completed loading. - * - * Listen to it from a Scene using: `this.load.on('progress', listener)`. - */ - const PROGRESS: any; - - /** - * The Loader Plugin Start Event. - * - * This event is dispatched when the Loader starts running. At this point load progress is zero. - * - * This event is dispatched even if there aren't any files in the load queue. - * - * Listen to it from a Scene using: `this.load.on('start', listener)`. - */ - const START: any; - - } - - /** - * The base File class used by all File Types that the Loader can support. - * You shouldn't create an instance of a File directly, but should extend it with your own class, setting a custom type and processing methods. - */ - class File { - /** - * - * @param loader The Loader that is going to load this File. - * @param fileConfig The file configuration object, as created by the file type. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, fileConfig: Phaser.Types.Loader.FileConfig); - - /** - * A reference to the Loader that is going to load this file. - */ - loader: Phaser.Loader.LoaderPlugin; - - /** - * A reference to the Cache, or Texture Manager, that is going to store this file if it loads. - */ - cache: Phaser.Cache.BaseCache | Phaser.Textures.TextureManager; - - /** - * The file type string (image, json, etc) for sorting within the Loader. - */ - type: string; - - /** - * Unique cache key (unique within its file type) - */ - key: string; - - /** - * The URL of the file, not including baseURL. - * Automatically has Loader.path prepended to it. - */ - url: string; - - /** - * The final URL this file will load from, including baseURL and path. - * Set automatically when the Loader calls 'load' on this file. - */ - src: string; - - /** - * The merged XHRSettings for this file. - */ - xhrSettings: Phaser.Types.Loader.XHRSettingsObject; - - /** - * The XMLHttpRequest instance (as created by XHR Loader) that is loading this File. - */ - xhrLoader: XMLHttpRequest; - - /** - * The current state of the file. One of the FILE_CONST values. - */ - state: integer; - - /** - * The total size of this file. - * Set by onProgress and only if loading via XHR. - */ - bytesTotal: number; - - /** - * Updated as the file loads. - * Only set if loading via XHR. - */ - bytesLoaded: number; - - /** - * A percentage value between 0 and 1 indicating how much of this file has loaded. - * Only set if loading via XHR. - */ - percentComplete: number; - - /** - * For CORs based loading. - * If this is undefined then the File will check BaseLoader.crossOrigin and use that (if set) - */ - crossOrigin: string | undefined; - - /** - * The processed file data, stored here after the file has loaded. - */ - data: any; - - /** - * A config object that can be used by file types to store transitional data. - */ - config: any; - - /** - * If this is a multipart file, i.e. an atlas and its json together, then this is a reference - * to the parent MultiFile. Set and used internally by the Loader or specific file types. - */ - multiFile: Phaser.Loader.MultiFile; - - /** - * Does this file have an associated linked file? Such as an image and a normal map. - * Atlases and Bitmap Fonts use the multiFile, because those files need loading together but aren't - * actually bound by data, where-as a linkFile is. - */ - linkFile: Phaser.Loader.File; - - /** - * Links this File with another, so they depend upon each other for loading and processing. - * @param fileB The file to link to this one. - */ - setLink(fileB: Phaser.Loader.File): void; - - /** - * Resets the XHRLoader instance this file is using. - */ - resetXHR(): void; - - /** - * 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. - */ - load(): void; - - /** - * Called when the file finishes loading, is sent a DOM ProgressEvent. - * @param xhr The XMLHttpRequest that caused this onload event. - * @param event The DOM ProgressEvent that resulted from this load. - */ - onLoad(xhr: XMLHttpRequest, event: ProgressEvent): void; - - /** - * Called if the file errors while loading, is sent a DOM ProgressEvent. - * @param xhr The XMLHttpRequest that caused this onload event. - * @param event The DOM ProgressEvent that resulted from this error. - */ - onError(xhr: XMLHttpRequest, event: ProgressEvent): void; - - /** - * Called during the file load progress. Is sent a DOM ProgressEvent. - * @param event The DOM ProgressEvent. - */ - onProgress(event: ProgressEvent): void; - - /** - * Usually overridden by the FileTypes and is called by Loader.nextFile. - * This method controls what extra work this File does with its loaded data, for example a JSON file will parse itself during this stage. - */ - onProcess(): void; - - /** - * Called when the File has completed processing. - * Checks on the state of its multifile, if set. - */ - onProcessComplete(): void; - - /** - * Called when the File has completed processing but it generated an error. - * Checks on the state of its multifile, if set. - */ - onProcessError(): void; - - /** - * Checks if a key matching the one used by this file exists in the target Cache or not. - * This is called automatically by the LoaderPlugin to decide if the file can be safely - * loaded or will conflict. - */ - hasCacheConflict(): boolean; - - /** - * Adds this file to its target cache upon successful loading and processing. - * This method is often overridden by specific file types. - */ - addToCache(): void; - - /** - * Called once the file has been added to its cache and is now ready for deletion from the Loader. - * It will emit a `filecomplete` event from the LoaderPlugin. - */ - pendingDestroy(): void; - - /** - * Destroy this File and any references it holds. - */ - destroy(): void; - - /** - * Static method for creating object URL using URL API and setting it as image 'src' attribute. - * If URL API is not supported (usually on old browsers) it falls back to creating Base64 encoded url using FileReader. - * @param image Image object which 'src' attribute should be set to object URL. - * @param blob A Blob object to create an object URL for. - * @param defaultType Default mime type used if blob type is not available. - */ - static createObjectURL(image: HTMLImageElement, blob: Blob, defaultType: string): void; - - /** - * Static method for releasing an existing object URL which was previously created - * by calling {@link File#createObjectURL} method. - * @param image Image object which 'src' attribute should be revoked. - */ - static revokeObjectURL(image: HTMLImageElement): void; - - } - - namespace FileTypes { - /** - * A single Animation JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#animation method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#animation. - */ - class AnimationJSONFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings Extra XHR Settings specifically for this file. - * @param dataKey When the JSON file loads only this property will be stored in the Cache. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataKey?: string); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Called at the end of the load process, after the Loader has finished all files in its queue. - */ - onLoadComplete(): void; - - } - - /** - * 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. - * - * https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm - */ - class AtlasJSONFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param atlasURL The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig, textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single XML based Texture Atlas File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#atlasXML method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#atlasXML. - */ - class AtlasXMLFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param atlasURL The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas xml file. Used in replacement of the Loaders default XHR Settings. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig, textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Audio File suitable for loading by the Loader. - * - * 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 { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param urlConfig The absolute or relative URL to load this file from in a config object. - * @param xhrSettings Extra XHR Settings specifically for this file. - * @param audioContext The AudioContext this file will use to process itself. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AudioFileConfig, urlConfig?: any, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, audioContext?: AudioContext); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * An Audio Sprite File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#audioSprite method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audioSprite. - */ - class AudioSpriteFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param jsonURL The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead. - * @param audioURL The absolute or relative URL to load the audio file from. If empty it will be obtained by parsing the JSON file. - * @param audioConfig The audio configuration options. - * @param audioXhrSettings An XHR Settings configuration object for the audio file. Used in replacement of the Loaders default XHR Settings. - * @param jsonXhrSettings An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig, jsonURL: string, audioURL?: Object, audioConfig?: any, audioXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, jsonXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called by each File when it finishes loading. - * @param file The File that has completed processing. - */ - onFileComplete(file: Phaser.Loader.File): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Binary File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#binary method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#binary. - */ - class BinaryFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". - * @param xhrSettings Extra XHR Settings specifically for this file. - * @param dataType Optional type to cast the binary file to once loaded. For example, `Uint8Array`. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.BinaryFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataType?: any); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single Bitmap Font based File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#bitmapFont method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#bitmapFont. - */ - class BitmapFontFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param textureURL The absolute or relative URL to load the font image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param fontDataURL The absolute or relative URL to load the font xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param textureXhrSettings An XHR Settings configuration object for the font image file. Used in replacement of the Loaders default XHR Settings. - * @param fontDataXhrSettings An XHR Settings configuration object for the font data xml file. Used in replacement of the Loaders default XHR Settings. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.BitmapFontFileConfig, textureURL?: string | string[], fontDataURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, fontDataXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single CSS File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#css method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#css. - */ - class CSSFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.CSSFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single GLSL File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#glsl method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#glsl. - */ - class GLSLFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param shaderType The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. Default 'fragment'. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.GLSLFileConfig, url?: string, shaderType?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - /** - * Returns the name of the shader from the header block. - * @param headerSource The header data. - */ - getShaderName(headerSource: string[]): string; - - /** - * Returns the type of the shader from the header block. - * @param headerSource The header data. - */ - getShaderType(headerSource: string[]): string; - - /** - * Returns the shader uniforms from the header block. - * @param headerSource The header data. - */ - getShaderUniforms(headerSource: string[]): any; - - } - - /** - * A single Audio File suitable for loading by the Loader. - * - * 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 HTML5AudioFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param urlConfig The absolute or relative URL to load this file from. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AudioFileConfig, urlConfig?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called when the file finishes loading. - */ - onLoad(): void; - - /** - * Called if the file errors while loading. - */ - onError(): void; - - /** - * Called during the file load progress. Is sent a DOM ProgressEvent. - */ - onProgress(): void; - - /** - * 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. - */ - load(): void; - - } - - /** - * A single HTML File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#html method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#html. - */ - class HTMLFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.html". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.HTMLFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single HTML File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#htmlTexture method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#htmlTexture. - */ - class HTMLTextureFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param width The width of the texture the HTML will be rendered to. - * @param height The height of the texture the HTML will be rendered to. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig, url?: string, width?: integer, height?: integer, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Image File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#image method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#image. - */ - class ImageFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param xhrSettings Extra XHR Settings specifically for this file. - * @param frameConfig The frame configuration object. Only provided for, and used by, Sprite Sheets. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.ImageFileConfig, url?: string | string[], xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#json method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#json. - */ - class JSONFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings Extra XHR Settings specifically for this file. - * @param dataKey When the JSON file loads only this property will be stored in the Cache. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataKey?: string); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single Multi Texture Atlas File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#multiatlas method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#multiatlas. - */ - class MultiAtlasFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key of the file. Must be unique within both the Loader and the Texture Manager. Or a config object. - * @param atlasURL The absolute or relative URL to load the multi atlas json file from. - * @param path Optional path to use when loading the textures defined in the atlas data. - * @param baseURL Optional Base URL to use when loading the textures defined in the atlas data. - * @param atlasXhrSettings Extra XHR Settings specifically for the atlas json file. - * @param textureXhrSettings Extra XHR Settings specifically for the texture files. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig, atlasURL?: string, path?: string, baseURL?: string, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called by each File when it finishes loading. - * @param file The File that has completed processing. - */ - onFileComplete(file: Phaser.Loader.File): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A Multi Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#scripts method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scripts. - */ - class MultiScriptFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. - * @param xhrSettings An XHR Settings configuration object for the script files. Used in replacement of the Loaders default XHR Settings. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.MultiScriptFileConfig, url?: string[], xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single JSON Pack File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#pack method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#pack. - */ - class PackFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings Extra XHR Settings specifically for this file. - * @param dataKey When the JSON file loads only this property will be stored in the Cache. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.PackFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataKey?: string); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single Plugin Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#plugin method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#plugin. - */ - class PluginFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param start Automatically start the plugin after loading? Default false. - * @param mapping If this plugin is to be injected into the Scene, this is the property key used. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.PluginFileConfig, url?: string, start?: boolean, mapping?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * An external Scene JavaScript File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#sceneFile method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#sceneFile. - */ - class SceneFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.SceneFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Scene Plugin Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#scenePlugin method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scenePlugin. - */ - class ScenePluginFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param systemKey If this plugin is to be added to Scene.Systems, this is the property key for it. - * @param sceneKey If this plugin is to be added to the Scene, this is the property key for it. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.ScenePluginFileConfig, url?: string, systemKey?: string, sceneKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single Script File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#script method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#script. - */ - class ScriptFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.ScriptFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single Sprite Sheet Image File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#spritesheet method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spritesheet. - */ - class SpriteSheetFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param frameConfig The frame configuration object. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig, url?: string | string[], frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single SVG File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#svg method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#svg. - */ - class SVGFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". - * @param svgConfig The svg size configuration object. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.SVGFileConfig, url?: string, svgConfig?: Phaser.Types.Loader.FileTypes.SVGSizeConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Text File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#text method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#text. - */ - class TextFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TextFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - /** - * A single Tilemap CSV File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapCSV method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapCSV. - */ - class TilemapCSVFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Impact.js Tilemap JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapImpact method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapImpact. - */ - class TilemapImpactFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Tiled Tilemap JSON File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapTiledJSON method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapTiledJSON. - */ - class TilemapJSONFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single text file based Unity Texture Atlas File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#unityAtlas method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#unityAtlas. - */ - class UnityAtlasFile extends Phaser.Loader.MultiFile { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param atlasURL The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig, textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Adds this file to its target cache upon successful loading and processing. - */ - addToCache(): void; - - } - - /** - * A single Video File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#video method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#video. - */ - class VideoFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param urlConfig The absolute or relative URL to load this file from in a config object. - * @param loadEvent The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. - * @param asBlob Load the video as a data blob, or via the Video element? - * @param noAudio Does the video have an audio track? If not you can enable auto-playing on it. - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.VideoFileConfig, urlConfig?: any, loadEvent?: string, asBlob?: boolean, noAudio?: boolean, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - /** - * 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. - */ - load(): void; - - } - - /** - * A single XML File suitable for loading by the Loader. - * - * These are created when you use the Phaser.Loader.LoaderPlugin#xml method and are not typically created directly. - * - * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#xml. - */ - class XMLFile extends Phaser.Loader.File { - /** - * - * @param loader A reference to the Loader that is responsible for this file. - * @param key The key to use for this file, or a file configuration object. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param xhrSettings Extra XHR Settings specifically for this file. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.XMLFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); - - /** - * Called automatically by Loader.nextFile. - * This method controls what extra work this File does with its loaded data. - */ - onProcess(): void; - - } - - } - - namespace FileTypesManager { - /** - * Static method called when a LoaderPlugin is created. - * - * Loops through the local types object and injects all of them as - * properties into the LoaderPlugin instance. - * @param loader The LoaderPlugin to install the types into. - */ - function install(loader: Phaser.Loader.LoaderPlugin): void; - - /** - * Static method called directly by the File Types. - * - * The key is a reference to the function used to load the files via the Loader, i.e. `image`. - * @param key The key that will be used as the method name in the LoaderPlugin. - * @param factoryFunction The function that will be called when LoaderPlugin.key is invoked. - */ - function register(key: string, factoryFunction: Function): void; - - /** - * Removed all associated file types. - */ - function destroy(): void; - - } - - /** - * Given a File and a baseURL value this returns the URL the File will use to download from. - * @param file The File object. - * @param baseURL A default base URL. - */ - function GetURL(file: Phaser.Loader.File, baseURL: string): string; - - /** - * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. - * You typically interact with it via `this.load` in your Scene. Scenes can have a `preload` method, which is always - * called before the Scenes `create` method, allowing you to preload assets that the Scene may need. - * - * If you call any `this.load` methods from outside of `Scene.preload` then you need to start the Loader going - * yourself by calling `Loader.start()`. It's only automatically started during the Scene preload. - * - * The Loader uses a combination of tag loading (eg. Audio elements) and XHR and provides progress and completion events. - * Files are loaded in parallel by default. The amount of concurrent connections can be controlled in your Game Configuration. - * - * Once the Loader has started loading you are still able to add files to it. These can be injected as a result of a loader - * event, the type of file being loaded (such as a pack file) or other external events. As long as the Loader hasn't finished - * simply adding a new file to it, while running, will ensure it's added into the current queue. - * - * Every Scene has its own instance of the Loader and they are bound to the Scene in which they are created. However, - * assets loaded by the Loader are placed into global game-level caches. For example, loading an XML file will place that - * file inside `Game.cache.xml`, which is accessible from every Scene in your game, no matter who was responsible - * for loading it. The same is true of Textures. A texture loaded in one Scene is instantly available to all other Scenes - * in your game. - * - * The Loader works by using custom File Types. These are stored in the FileTypesManager, which injects them into the Loader - * when it's instantiated. You can create your own custom file types by extending either the File or MultiFile classes. - * See those files for more details. - */ - class LoaderPlugin extends Phaser.Events.EventEmitter { - /** - * - * @param scene The Scene which owns this Loader instance. - */ - constructor(scene: Phaser.Scene); - - /** - * Adds an Animation JSON Data file, or array of Animation JSON 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.animation('baddieAnims', 'files/BaddieAnims.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 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.animation({ - * key: 'baddieAnims', - * url: 'files/BaddieAnims.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. - * - * Once the file has finished loading it will automatically be passed to the global Animation Managers `fromJSON` method. - * This will parse all of the JSON data and create animation data from it. This process happens at the very end - * of the Loader, once every other file in the load queue has finished. The reason for this is to allow you to load - * both animation data and the images it relies upon in the same load call. - * - * Once the animation data has been parsed you will be able to play animations using that data. - * Please see the Animation Manager `fromJSON` method for more details about the format and playback. - * - * You can also access the raw animation data from its Cache using its key: - * - * ```javascript - * this.load.animation('baddieAnims', 'files/BaddieAnims.json'); - * // and later in your game ... - * var data = this.cache.json.get('baddieAnims'); - * ``` - * - * 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 if you only wanted to create animations from the `boss` data, 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 JSON File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param dataKey When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - animation(key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig | Phaser.Types.Loader.FileTypes.JSONFileConfig[], url?: string, dataKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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, Shoebox and Adobe Flash / Animate. - * 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. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param atlasURL The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings. - */ - atlas(key: string | Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig | Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig[], textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an XML 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.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 atlas data to be provided in an XML file format. - * These files are created by software such as Shoebox and Adobe Flash / Animate. - * - * 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.atlasXML({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * atlasURL: 'images/MainMenu.xml' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig` for more details. - * - * 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.xml'); - * // 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.atlasXML('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.xml'); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.atlasXML({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * normalMap: 'images/MainMenu-n.png', - * atlasURL: 'images/MainMenu.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 Atlas XML File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param atlasURL The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas xml file. Used in replacement of the Loaders default XHR Settings. - */ - atlasXML(key: string | Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig | Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig[], textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param urls The absolute or relative URL to load the audio files from. - * @param config An object containing an `instances` property for HTML5Audio. Defaults to 1. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - audio(key: string | Phaser.Types.Loader.FileTypes.AudioFileConfig | Phaser.Types.Loader.FileTypes.AudioFileConfig[], urls?: string | string[], config?: any, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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 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. - * - * 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. - * @param key The key to use for this file, or a file configuration object, or an array of objects. - * @param jsonURL The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead. - * @param audioURL The absolute or relative URL to load the audio file from. If empty it will be obtained by parsing the JSON file. - * @param audioConfig The audio configuration options. - * @param audioXhrSettings An XHR Settings configuration object for the audio file. Used in replacement of the Loaders default XHR Settings. - * @param jsonXhrSettings An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings. - */ - audioSprite(key: string | Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig | Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig[], jsonURL: string, audioURL?: string | string[], audioConfig?: any, audioXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, jsonXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Binary file, or array of Binary 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.binary('doom', 'files/Doom.wad'); - * } - * ``` - * - * 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 Binary Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Binary 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 Binary Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.binary({ - * key: 'doom', - * url: 'files/Doom.wad', - * dataType: Uint8Array - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.BinaryFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.binary('doom', 'files/Doom.wad'); - * // and later in your game ... - * var data = this.cache.binary.get('doom'); - * ``` - * - * 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 `Data` the final key will be `LEVEL1.Data` and - * this is what you would use to retrieve the text from the Binary 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 "doom" - * and no URL is given then the Loader will set the URL to be "doom.bin". It will always add `.bin` 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 Binary File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". - * @param dataType Optional type to cast the binary file to once loaded. For example, `Uint8Array`. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - binary(key: string | Phaser.Types.Loader.FileTypes.BinaryFileConfig | Phaser.Types.Loader.FileTypes.BinaryFileConfig[], url?: string, dataType?: any, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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 atlas has finished loading you can use 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. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param textureURL The absolute or relative URL to load the font image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param fontDataURL The absolute or relative URL to load the font xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param textureXhrSettings An XHR Settings configuration object for the font image file. Used in replacement of the Loaders default XHR Settings. - * @param fontDataXhrSettings An XHR Settings configuration object for the font data xml file. Used in replacement of the Loaders default XHR Settings. - */ - bitmapFont(key: string | Phaser.Types.Loader.FileTypes.BitmapFontFileConfig | Phaser.Types.Loader.FileTypes.BitmapFontFileConfig[], textureURL?: string | string[], fontDataURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, fontDataXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a CSS file, or array of CSS 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.css('headers', 'styles/headers.css'); - * } - * ``` - * - * 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.css({ - * key: 'headers', - * url: 'styles/headers.css' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.CSSFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a style DOM element - * via `document.createElement('style')`. It will have its `defer` property set to false and then the - * resulting element will be appended to `document.head`. The CSS styles are then applied to the current document. - * - * 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.css". It will always add `.css` 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 CSS File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - css(key: string | Phaser.Types.Loader.FileTypes.CSSFileConfig | Phaser.Types.Loader.FileTypes.CSSFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a GLSL file, or array of GLSL files, to the current load queue. - * In Phaser 3 GLSL files are just plain Text files at the current moment in time. - * - * 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.glsl('plasma', 'shaders/Plasma.glsl'); - * } - * ``` - * - * 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 Shader Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Shader 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 Shader Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.glsl({ - * key: 'plasma', - * shaderType: 'fragment', - * url: 'shaders/Plasma.glsl' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.GLSLFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.glsl('plasma', 'shaders/Plasma.glsl'); - * // and later in your game ... - * var data = this.cache.shader.get('plasma'); - * ``` - * - * 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 `FX.` and the key was `Plasma` the final key will be `FX.Plasma` and - * this is what you would use to retrieve the text from the Shader 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 "plasma" - * and no URL is given then the Loader will set the URL to be "plasma.glsl". It will always add `.glsl` 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 GLSL File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.glsl`, i.e. if `key` was "alien" then the URL will be "alien.glsl". - * @param shaderType The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. Default 'fragment'. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - glsl(key: string | Phaser.Types.Loader.FileTypes.GLSLFileConfig | Phaser.Types.Loader.FileTypes.GLSLFileConfig[], url?: string, shaderType?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an HTML file, or array of HTML 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.html('story', 'files/LoginForm.html'); - * } - * ``` - * - * 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 HTML Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the HTML 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 HTML Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.html({ - * key: 'login', - * url: 'files/LoginForm.html' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.HTMLFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.html('login', 'files/LoginForm.html'); - * // and later in your game ... - * var data = this.cache.html.get('login'); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the html from the HTML 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 "story" - * and no URL is given then the Loader will set the URL to be "story.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. - * - * Note: The ability to load this type of file will only be available if the HTML File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - html(key: string | Phaser.Types.Loader.FileTypes.HTMLFileConfig | Phaser.Types.Loader.FileTypes.HTMLFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". - * @param width The width of the texture the HTML will be rendered to. Default 512. - * @param height The height of the texture the HTML will be rendered to. Default 512. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - htmlTexture(key: string | Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig | Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig[], url?: string, width?: integer, height?: integer, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an Image, or array of Images, 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.image('logo', 'images/phaserLogo.png'); - * } - * ``` - * - * 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. - * - * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. - * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback - * of animated gifs to Canvas elements. - * - * 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.image({ - * key: 'logo', - * url: 'images/AtariLogo.png' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.ImageFileConfig` 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.image('logo', 'images/AtariLogo.png'); - * // and later in your game ... - * this.add.image(x, y, 'logo'); - * ``` - * - * 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.image('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ]); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.image({ - * key: 'logo', - * url: 'images/AtariLogo.png', - * normalMap: 'images/AtariLogo-n.png' - * }); - * ``` - * - * 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 Image File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - image(key: string | Phaser.Types.Loader.FileTypes.ImageFileConfig | Phaser.Types.Loader.FileTypes.ImageFileConfig[], url?: string | string[], xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a JSON file, or array of JSON 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.json('wavedata', 'files/AlienWaveData.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. - * - * 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.json({ - * key: 'wavedata', - * url: 'files/AlienWaveData.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.json('wavedata', 'files/AlienWaveData.json'); - * // and later in your game ... - * var data = this.cache.json.get('wavedata'); - * ``` - * - * 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 JSON File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param dataKey When the JSON file loads only this property will be stored in the Cache. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - json(key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig | Phaser.Types.Loader.FileTypes.JSONFileConfig[], url?: string, dataKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Multi Texture Atlas, or array of multi 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.multiatlas('level1', 'images/Level1.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 as exported from the application Texture Packer, - * version 4.6.3 or above, where you have made sure to use the Phaser 3 Export option. - * - * The way it works internally is that you provide a URL to the JSON file. Phaser then loads this JSON, parses it and - * extracts which texture files it also needs to load to complete the process. If the JSON also defines normal maps, - * Phaser will load those as well. - * - * 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.multiatlas({ - * key: 'level1', - * atlasURL: 'images/Level1.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig` 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.multiatlas('level1', 'images/Level1.json'); - * // and later in your game ... - * this.add.image(x, y, 'level1', '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. - * - * Note: The ability to load this type of file will only be available if the Multi Atlas File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param atlasURL The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param path Optional path to use when loading the textures defined in the atlas data. - * @param baseURL Optional Base URL to use when loading the textures defined in the atlas data. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings. - */ - multiatlas(key: string | Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig | Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig[], atlasURL?: string, path?: string, baseURL?: string, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an array of Script files to the current load queue. - * - * The difference between this and the `ScriptFile` file type is that you give an array of scripts to this method, - * and the scripts are then processed _exactly_ in that order. This allows you to load a bunch of scripts that - * may have dependencies on each other without worrying about the async nature of traditional script loading. - * - * 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.scripts('PostProcess', [ - * 'libs/shaders/CopyShader.js', - * 'libs/postprocessing/EffectComposer.js', - * 'libs/postprocessing/RenderPass.js', - * 'libs/postprocessing/MaskPass.js', - * 'libs/postprocessing/ShaderPass.js', - * 'libs/postprocessing/AfterimagePass.js' - * ]); - * } - * ``` - * - * In the code above the script files will all be loaded in parallel but only processed (i.e. invoked) in the exact - * order given in the array. - * - * The files are **not** loaded right away. They are 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 files are queued - * it means you cannot use the files immediately after calling this method, but must wait for the files 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.scripts({ - * key: 'PostProcess', - * url: [ - * 'libs/shaders/CopyShader.js', - * 'libs/postprocessing/EffectComposer.js', - * 'libs/postprocessing/RenderPass.js', - * 'libs/postprocessing/MaskPass.js', - * 'libs/postprocessing/ShaderPass.js', - * 'libs/postprocessing/AfterimagePass.js' - * ] - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.MultiScriptFileConfig` for more details. - * - * Once all the files have finished loading they will automatically be converted into a script element - * via `document.createElement('script')`. They will have their language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. This is done in the exact order the files are specified in the url array. - * - * The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them. - * - * Note: The ability to load this type of file will only be available if the MultiScript File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. - * @param extension The default file extension to use if no url is provided. Default 'js'. - * @param xhrSettings Extra XHR Settings specifically for these files. - */ - scripts(key: string | Phaser.Types.Loader.FileTypes.MultiScriptFileConfig | Phaser.Types.Loader.FileTypes.MultiScriptFileConfig[], url?: string[], extension?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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. - * - * 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. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param dataKey When the JSON file loads only this property will be stored in the Cache. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - pack(key: string | Phaser.Types.Loader.FileTypes.PackFileConfig | Phaser.Types.Loader.FileTypes.PackFileConfig[], url?: string, dataKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Plugin Script file, or array of plugin 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.plugin('modplayer', 'plugins/ModPlayer.js'); - * } - * ``` - * - * 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.plugin({ - * key: 'modplayer', - * url: 'plugins/ModPlayer.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.PluginFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a script element - * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. It will then be passed to the Phaser PluginCache.register method. - * - * 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.js". It will always add `.js` 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 Plugin File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, a plugin function. - * @param start Automatically start the plugin after loading? - * @param mapping If this plugin is to be injected into the Scene, this is the property key used. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - plugin(key: string | Phaser.Types.Loader.FileTypes.PluginFileConfig | Phaser.Types.Loader.FileTypes.PluginFileConfig[], url?: string | Function, start?: boolean, mapping?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an external Scene file, or array of Scene 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.sceneFile('Level1', 'src/Level1.js'); - * } - * ``` - * - * 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 Scene Manager upon a successful load. - * - * For a Scene File it's vitally important that the key matches the class name in the JavaScript file. - * - * For example here is the source file: - * - * ```javascript - * class ExternalScene extends Phaser.Scene { - * - * constructor () - * { - * super('myScene'); - * } - * - * } - * ``` - * - * Because the class is called `ExternalScene` that is the exact same key you must use when loading it: - * - * ```javascript - * function preload () - * { - * this.load.sceneFile('ExternalScene', 'src/yourScene.js'); - * } - * ``` - * - * The key that is used within the Scene Manager can either be set to the same, or you can override it in the Scene - * constructor, as we've done in the example above, where the Scene key was changed to `myScene`. - * - * The key should be unique both in terms of files being loaded and Scenes already present in the Scene 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 Scene Manager first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.sceneFile({ - * key: 'Level1', - * url: 'src/Level1.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.SceneFileConfig` for more details. - * - * Once the file has finished loading it will be added to the Scene Manager. - * - * ```javascript - * this.load.sceneFile('Level1', 'src/Level1.js'); - * // and later in your game ... - * this.scene.start('Level1'); - * ``` - * - * 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 `WORLD1.` and the key was `Story` the final key will be `WORLD1.Story` and - * this is what you would use to retrieve the text from the Scene 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 "story" - * and no URL is given then the Loader will set the URL to be "story.js". It will always add `.js` 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 Scene File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - sceneFile(key: string | Phaser.Types.Loader.FileTypes.SceneFileConfig | Phaser.Types.Loader.FileTypes.SceneFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Scene Plugin Script file, or array of plugin 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.scenePlugin('ModPlayer', 'plugins/ModPlayer.js', 'modPlayer', 'mods'); - * } - * ``` - * - * 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.scenePlugin({ - * key: 'modplayer', - * url: 'plugins/ModPlayer.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.ScenePluginFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a script element - * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. It will then be passed to the Phaser PluginCache.register method. - * - * 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.js". It will always add `.js` 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 Script File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, set to a plugin function. - * @param systemKey If this plugin is to be added to Scene.Systems, this is the property key for it. - * @param sceneKey If this plugin is to be added to the Scene, this is the property key for it. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - scenePlugin(key: string | Phaser.Types.Loader.FileTypes.ScenePluginFileConfig | Phaser.Types.Loader.FileTypes.ScenePluginFileConfig[], url?: string | Function, systemKey?: string, sceneKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Script file, or array of Script 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.script('aliens', 'lib/aliens.js'); - * } - * ``` - * - * 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.script({ - * key: 'aliens', - * url: 'lib/aliens.js' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.ScriptFileConfig` for more details. - * - * Once the file has finished loading it will automatically be converted into a script element - * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to - * false and then the resulting element will be appended to `document.head`. Any code then in the - * script will be executed. - * - * 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.js". It will always add `.js` 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 Script File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - script(key: string | Phaser.Types.Loader.FileTypes.ScriptFileConfig | Phaser.Types.Loader.FileTypes.ScriptFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Sprite Sheet Image, or array of Sprite Sheet Images, to the current load queue. - * - * The term 'Sprite Sheet' in Phaser means a fixed-size sheet. Where every frame in the sheet is the exact same size, - * and you reference those frames using numbers, not frame names. This is not the same thing as a Texture Atlas, where - * the frames are packed in a way where they take up the least amount of space, and are referenced by their names, - * not numbers. Some articles and software use the term 'Sprite Sheet' to mean Texture Atlas, so please be aware of - * what sort of file you're actually trying to load. - * - * 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); - * } - * ``` - * - * 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. - * - * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. - * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback - * of animated gifs to Canvas elements. - * - * 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.spritesheet({ - * key: 'bot', - * url: 'images/robot.png', - * frameConfig: { - * frameWidth: 32, - * frameHeight: 38, - * startFrame: 0, - * endFrame: 8 - * } - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig` 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); - * // and later in your game ... - * this.add.image(x, y, 'bot', 0); - * ``` - * - * 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 `PLAYER.` and the key was `Running` the final key will be `PLAYER.Running` 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.spritesheet('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ], { frameWidth: 256, frameHeight: 80 }); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.spritesheet({ - * key: 'logo', - * url: 'images/AtariLogo.png', - * normalMap: 'images/AtariLogo-n.png', - * frameConfig: { - * frameWidth: 256, - * frameHeight: 80 - * } - * }); - * ``` - * - * 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 Sprite Sheet File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param frameConfig The frame configuration object. At a minimum it should have a `frameWidth` property. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - spritesheet(key: string | Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig | Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig[], url?: string, frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an SVG File, or array of SVG Files, to the current load queue. When the files are loaded they - * will be rendered to bitmap 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.svg('morty', 'images/Morty.svg'); - * } - * ``` - * - * 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.svg({ - * key: 'morty', - * url: 'images/Morty.svg' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.SVGFileConfig` 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.svg('morty', 'images/Morty.svg'); - * // and later in your game ... - * this.add.image(x, y, 'morty'); - * ``` - * - * 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. - * - * You can optionally pass an SVG Resize Configuration object when you load an SVG file. By default the SVG will be rendered to a texture - * at the same size defined in the SVG file attributes. However, this isn't always desirable. You may wish to resize the SVG (either down - * or up) to improve texture clarity, or reduce texture memory consumption. You can either specify an exact width and height to resize - * the SVG to: - * - * ```javascript - * function preload () - * { - * this.load.svg('morty', 'images/Morty.svg', { width: 300, height: 600 }); - * } - * ``` - * - * Or when using a configuration object: - * - * ```javascript - * this.load.svg({ - * key: 'morty', - * url: 'images/Morty.svg', - * svgConfig: { - * width: 300, - * height: 600 - * } - * }); - * ``` - * - * Alternatively, you can just provide a scale factor instead: - * - * ```javascript - * function preload () - * { - * this.load.svg('morty', 'images/Morty.svg', { scale: 2.5 }); - * } - * ``` - * - * Or when using a configuration object: - * - * ```javascript - * this.load.svg({ - * key: 'morty', - * url: 'images/Morty.svg', - * svgConfig: { - * scale: 2.5 - * } - * }); - * ``` - * - * If scale, width and height values are all given, the scale has priority and the width and height values are ignored. - * - * Note: The ability to load this type of file will only be available if the SVG File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". - * @param svgConfig The svg size configuration object. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - svg(key: string | Phaser.Types.Loader.FileTypes.SVGFileConfig | Phaser.Types.Loader.FileTypes.SVGFileConfig[], url?: string, svgConfig?: Phaser.Types.Loader.FileTypes.SVGSizeConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Text file, or array of Text 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.text('story', 'files/IntroStory.txt'); - * } - * ``` - * - * 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 Text Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Text 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.text({ - * key: 'story', - * url: 'files/IntroStory.txt' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TextFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.text('story', 'files/IntroStory.txt'); - * // and later in your game ... - * var data = this.cache.text.get('story'); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Text 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 "story" - * and no URL is given then the Loader will set the URL to be "story.txt". It will always add `.txt` 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 Text File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - text(key: string | Phaser.Types.Loader.FileTypes.TextFileConfig | Phaser.Types.Loader.FileTypes.TextFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a CSV Tilemap file, or array of CSV 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.tilemapCSV('level1', 'maps/Level1.csv'); - * } - * ``` - * - * Tilemap CSV data can be created in a text editor, or a 3rd party app that exports as CSV. - * - * 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 Tilemap Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.tilemapCSV({ - * key: 'level1', - * url: 'maps/Level1.csv' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.tilemapCSV('level1', 'maps/Level1.csv'); - * // and later in your game ... - * var map = this.make.tilemap({ key: 'level1' }); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Tilemap 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 "level" - * and no URL is given then the Loader will set the URL to be "level.csv". It will always add `.csv` 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 Tilemap CSV File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - tilemapCSV(key: string | Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig | Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an Impact.js Tilemap file, or array of map 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.tilemapImpact('level1', 'maps/Level1.json'); - * } - * ``` - * - * Impact Tilemap data is created the Impact.js Map Editor called Weltmeister. - * - * 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 Tilemap Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.tilemapImpact({ - * key: 'level1', - * url: 'maps/Level1.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.tilemapImpact('level1', 'maps/Level1.json'); - * // and later in your game ... - * var map = this.make.tilemap({ key: 'level1' }); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Tilemap 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 "level" - * and no URL is given then the Loader will set the URL to be "level.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. - * - * Note: The ability to load this type of file will only be available if the Tilemap Impact File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - tilemapImpact(key: string | Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig | Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Tiled JSON Tilemap file, or array of map 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.tilemapTiledJSON('level1', 'maps/Level1.json'); - * } - * ``` - * - * The Tilemap data is created using the Tiled Map Editor and selecting JSON as the export format. - * - * 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 Tilemap Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.tilemapTiledJSON({ - * key: 'level1', - * url: 'maps/Level1.json' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.tilemapTiledJSON('level1', 'maps/Level1.json'); - * // and later in your game ... - * var map = this.make.tilemap({ key: 'level1' }); - * ``` - * - * 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 `Story` the final key will be `LEVEL1.Story` and - * this is what you would use to retrieve the text from the Tilemap 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 "level" - * and no URL is given then the Loader will set the URL to be "level.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. - * - * Note: The ability to load this type of file will only be available if the Tilemap JSON File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - tilemapTiledJSON(key: string | Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig | Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds a Unity YAML 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.unityAtlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.txt'); - * } - * ``` - * - * 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 YAML formatted text file as exported from Unity. - * - * 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.unityAtlas({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * atlasURL: 'images/MainMenu.txt' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig` for more details. - * - * 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.unityAtlas('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.unityAtlas('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.txt'); - * ``` - * - * Or, if you are using a config object use the `normalMap` property: - * - * ```javascript - * this.load.unityAtlas({ - * key: 'mainmenu', - * textureURL: 'images/MainMenu.png', - * normalMap: 'images/MainMenu-n.png', - * atlasURL: 'images/MainMenu.txt' - * }); - * ``` - * - * 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 Unity Atlas File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param atlasURL The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. - * @param atlasXhrSettings An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings. - */ - unityAtlas(key: string | Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig | Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig[], textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * 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' ], - * asBlob: false, - * 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. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param urls The absolute or relative URL to load the video files from. - * @param loadEvent The load event to listen for when _not_ loading as a blob. Either `loadeddata`, `canplay` or `canplaythrough`. Default 'loadeddata'. - * @param asBlob Load the video as a data blob, or stream it via the Video element? Default false. - * @param noAudio Does the video have an audio track? If not you can enable auto-playing on it. Default false. - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - video(key: string | Phaser.Types.Loader.FileTypes.VideoFileConfig | Phaser.Types.Loader.FileTypes.VideoFileConfig[], urls?: string | string[], loadEvent?: string, asBlob?: boolean, noAudio?: boolean, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * Adds an XML file, or array of XML 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.xml('wavedata', 'files/AlienWaveData.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. - * - * The key must be a unique String. It is used to add the file to the global XML Cache upon a successful load. - * The key should be unique both in terms of files being loaded and files already present in the XML 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 XML Cache first, before loading a new one. - * - * Instead of passing arguments you can pass a configuration object, such as: - * - * ```javascript - * this.load.xml({ - * key: 'wavedata', - * url: 'files/AlienWaveData.xml' - * }); - * ``` - * - * See the documentation for `Phaser.Types.Loader.FileTypes.XMLFileConfig` for more details. - * - * Once the file has finished loading you can access it from its Cache using its key: - * - * ```javascript - * this.load.xml('wavedata', 'files/AlienWaveData.xml'); - * // and later in your game ... - * var data = this.cache.xml.get('wavedata'); - * ``` - * - * 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 XML 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.xml". It will always add `.xml` 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 XML File type has been built into Phaser. - * It is available in the default build but can be excluded from custom builds. - * @param key The key to use for this file, or a file configuration object, or array of them. - * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. - */ - xml(key: string | Phaser.Types.Loader.FileTypes.XMLFileConfig | Phaser.Types.Loader.FileTypes.XMLFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; - - /** - * The Scene which owns this Loader instance. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene Systems. - */ - systems: Phaser.Scenes.Systems; - - /** - * A reference to the global Cache Manager. - */ - cacheManager: Phaser.Cache.CacheManager; - - /** - * A reference to the global Texture Manager. - */ - textureManager: Phaser.Textures.TextureManager; - - /** - * A reference to the global Scene Manager. - */ - protected sceneManager: Phaser.Scenes.SceneManager; - - /** - * An optional prefix that is automatically prepended to the start of every file key. - * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. - * You can set this directly, or call `Loader.setPrefix()`. 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. - */ - prefix: string; - - /** - * 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. - */ - path: string; - - /** - * If you want to append a URL before the path of any asset you can set this here. - * - * Useful if allowing the asset base url to be configured outside of the game code. - * - * If you set this property directly then it _must_ end with a "/". Alternatively, call `setBaseURL()` and it'll do it for you. - */ - baseURL: string; - - /** - * The number of concurrent / parallel resources to try and fetch at once. - * - * Old browsers limit 6 requests per domain; modern ones, especially those with HTTP/2 don't limit it at all. - * - * The default is 32 but you can change this in your Game Config, or by changing this property before the Loader starts. - */ - maxParallelDownloads: integer; - - /** - * xhr specific global settings (can be overridden on a per-file basis) - */ - xhr: Phaser.Types.Loader.XHRSettingsObject; - - /** - * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. - */ - crossOrigin: string; - - /** - * The total number of files to load. It may not always be accurate because you may add to the Loader during the process - * of loading, especially if you load a Pack File. Therefore this value can change, but in most cases remains static. - */ - totalToLoad: integer; - - /** - * The progress of the current load queue, as a float value between 0 and 1. - * This is updated automatically as files complete loading. - * Note that it is possible for this value to go down again if you add content to the current load queue during a load. - */ - progress: number; - - /** - * Files are placed in this Set when they're added to the Loader via `addFile`. - * - * They are moved to the `inflight` Set when they start loading, and assuming a successful - * load, to the `queue` Set for further processing. - * - * By the end of the load process this Set will be empty. - */ - list: Phaser.Structs.Set; - - /** - * Files are stored in this Set while they're in the process of being loaded. - * - * Upon a successful load they are moved to the `queue` Set. - * - * By the end of the load process this Set will be empty. - */ - inflight: Phaser.Structs.Set; - - /** - * Files are stored in this Set while they're being processed. - * - * If the process is successful they are moved to their final destination, which could be - * a Cache or the Texture Manager. - * - * At the end of the load process this Set will be empty. - */ - queue: Phaser.Structs.Set; - - /** - * The total number of files that failed to load during the most recent load. - * This value is reset when you call `Loader.start`. - */ - totalFailed: integer; - - /** - * The total number of files that successfully loaded during the most recent load. - * This value is reset when you call `Loader.start`. - */ - totalComplete: integer; - - /** - * The current state of the Loader. - */ - readonly state: integer; - - /** - * If you want to append a URL before the path of any asset you can set this here. - * - * Useful if allowing the asset base url to be configured outside of the game code. - * - * Once a base URL is set it will affect every file loaded by the Loader from that point on. It does _not_ change any - * file _already_ being loaded. To reset it, call this method with no arguments. - * @param url The URL to use. Leave empty to reset. - */ - setBaseURL(url?: string): Phaser.Loader.LoaderPlugin; - - /** - * 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. - * @param path The path to use. Leave empty to reset. - */ - setPath(path?: string): Phaser.Loader.LoaderPlugin; - - /** - * An optional prefix that is automatically prepended to the start of every file key. - * - * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. - * - * Once a prefix 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. - * @param prefix The prefix to use. Leave empty to reset. - */ - setPrefix(prefix?: string): Phaser.Loader.LoaderPlugin; - - /** - * 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 - * @param crossOrigin The value to use for the `crossOrigin` property in the load request. - */ - setCORS(crossOrigin?: string): Phaser.Loader.LoaderPlugin; - - /** - * Adds a file, or array of files, into the load queue. - * - * The file must be an instance of `Phaser.Loader.File`, or a class that extends it. The Loader will check that the key - * used by the file won't conflict with any other key either in the loader, the inflight queue or the target cache. - * If allowed it will then add the file into the pending list, read for the load to start. Or, if the load has already - * started, ready for the next batch of files to be pulled from the list to the inflight queue. - * - * You should not normally call this method directly, but rather use one of the Loader methods like `image` or `atlas`, - * however you can call this as long as the file given to it is well formed. - * @param file The file, or array of files, to be added to the load queue. - */ - addFile(file: Phaser.Loader.File | Phaser.Loader.File[]): void; - - /** - * Checks the key and type of the given file to see if it will conflict with anything already - * in a Cache, the Texture Manager, or the list or inflight queues. - * @param file The file to check the key of. - */ - keyExists(file: Phaser.Loader.File): boolean; - - /** - * Takes a well formed, fully parsed pack file object and adds its entries into the load queue. Usually you do not call - * this method directly, but instead use `Loader.pack` and supply a path to a JSON file that holds the - * pack data. However, if you've got the data prepared you can pass it to this method. - * - * You can also provide an optional key. If you do then it will only add the entries from that part of the pack into - * to the load queue. If not specified it will add all entries it finds. For more details about the pack file format - * see the `LoaderPlugin.pack` method. - * @param data The Pack File data to be parsed and each entry of it to added to the load queue. - * @param packKey An optional key to use from the pack file data. - */ - addPack(data: any, packKey?: string): boolean; - - /** - * Is the Loader actively loading, or processing loaded files? - */ - isLoading(): boolean; - - /** - * Is the Loader ready to start a new load? - */ - isReady(): boolean; - - /** - * Starts the Loader running. This will reset the progress and totals and then emit a `start` event. - * If there is nothing in the queue the Loader will immediately complete, otherwise it will start - * loading the first batch of files. - * - * The Loader is started automatically if the queue is populated within your Scenes `preload` method. - * - * However, outside of this, you need to call this method to start it. - * - * If the Loader is already running this method will simply return. - */ - start(): void; - - /** - * Called automatically during the load process. - * It updates the `progress` value and then emits a progress event, which you can use to - * display a loading bar in your game. - */ - updateProgress(): void; - - /** - * Called automatically during the load process. - */ - update(): void; - - /** - * An internal method called automatically by the XHRLoader belong to a File. - * - * This method will remove the given file from the inflight Set and update the load progress. - * If the file was successful its `onProcess` method is called, otherwise it is added to the delete queue. - * @param file The File that just finished loading, or errored during load. - * @param success `true` if the file loaded successfully, otherwise `false`. - */ - nextFile(file: Phaser.Loader.File, success: boolean): void; - - /** - * An internal method that is called automatically by the File when it has finished processing. - * - * If the process was successful, and the File isn't part of a MultiFile, its `addToCache` method is called. - * - * It this then removed from the queue. If there are no more files to load `loadComplete` is called. - * @param file The file that has finished processing. - */ - fileProcessComplete(file: Phaser.Loader.File): void; - - /** - * Called at the end when the load queue is exhausted and all files have either loaded or errored. - * By this point every loaded file will now be in its associated cache and ready for use. - * - * Also clears down the Sets, puts progress to 1 and clears the deletion queue. - */ - loadComplete(): void; - - /** - * Adds a File into the pending-deletion queue. - * @param file The File to be queued for deletion when the Loader completes. - */ - flagForRemoval(file: Phaser.Loader.File): void; - - /** - * Converts the given JSON data into a file that the browser then prompts you to download so you can save it locally. - * - * The data must be well formed JSON and ready-parsed, not a JavaScript object. - * @param data The JSON data, ready parsed. - * @param filename The name to save the JSON file as. Default file.json. - */ - saveJSON(data: any, filename?: string): Phaser.Loader.LoaderPlugin; - - /** - * 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. - * @param data The data to be saved. Will be passed through URL.createObjectURL. - * @param filename The filename to save the file as. Default file.json. - * @param filetype The file type to use when saving the file. Defaults to JSON. Default application/json. - */ - save(data: any, filename?: string, filetype?: string): Phaser.Loader.LoaderPlugin; - - /** - * Resets the Loader. - * - * This will clear all lists and reset the base URL, path and prefix. - * - * Warning: If the Loader is currently downloading files, or has files in its queue, they will be aborted. - */ - reset(): void; - - } - - /** - * Takes two XHRSettings Objects and creates a new XHRSettings object from them. - * - * The new object is seeded by the values given in the global settings, but any setting in - * the local object overrides the global ones. - * @param global The global XHRSettings object. - * @param local The local XHRSettings object. - */ - function MergeXHRSettings(global: Phaser.Types.Loader.XHRSettingsObject, local: Phaser.Types.Loader.XHRSettingsObject): Phaser.Types.Loader.XHRSettingsObject; - - /** - * A MultiFile is a special kind of parent that contains two, or more, Files as children and looks after - * the loading and processing of them all. It is commonly extended and used as a base class for file types such as AtlasJSON or BitmapFont. - * - * You shouldn't create an instance of a MultiFile directly, but should extend it with your own class, setting a custom type and processing methods. - */ - class MultiFile { - /** - * - * @param loader The Loader that is going to load this File. - * @param type The file type string for sorting within the Loader. - * @param key The key of the file within the loader. - * @param files An array of Files that make-up this MultiFile. - */ - constructor(loader: Phaser.Loader.LoaderPlugin, type: string, key: string, files: Phaser.Loader.File[]); - - /** - * A reference to the Loader that is going to load this file. - */ - loader: Phaser.Loader.LoaderPlugin; - - /** - * The file type string for sorting within the Loader. - */ - type: string; - - /** - * Unique cache key (unique within its file type) - */ - key: string; - - /** - * Array of files that make up this MultiFile. - */ - files: Phaser.Loader.File[]; - - /** - * The completion status of this MultiFile. - */ - complete: boolean; - - /** - * The number of files to load. - */ - pending: integer; - - /** - * The number of files that failed to load. - */ - failed: integer; - - /** - * A storage container for transient data that the loading files need. - */ - config: any; - - /** - * A reference to the Loaders baseURL at the time this MultiFile was created. - * Used to populate child-files. - */ - baseURL: string; - - /** - * A reference to the Loaders path at the time this MultiFile was created. - * Used to populate child-files. - */ - path: string; - - /** - * A reference to the Loaders prefix at the time this MultiFile was created. - * Used to populate child-files. - */ - prefix: string; - - /** - * Checks if this MultiFile is ready to process its children or not. - */ - isReadyToProcess(): boolean; - - /** - * Adds another child to this MultiFile, increases the pending count and resets the completion status. - * @param files The File to add to this MultiFile. - */ - addToMultiFile(files: Phaser.Loader.File): Phaser.Loader.MultiFile; - - /** - * Called by each File when it finishes loading. - * @param file The File that has completed processing. - */ - onFileComplete(file: Phaser.Loader.File): void; - - /** - * Called by each File that fails to load. - * @param file The File that has failed to load. - */ - onFileFailed(file: Phaser.Loader.File): void; - - } - - /** - * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings - * and starts the download of it. It uses the Files own XHRSettings and merges them - * with the global XHRSettings object to set the xhr values before download. - * @param file The File to download. - * @param globalXHRSettings The global XHRSettings object. - */ - function XHRLoader(file: Phaser.Loader.File, globalXHRSettings: Phaser.Types.Loader.XHRSettingsObject): XMLHttpRequest; - - /** - * Creates an XHRSettings Object with default values. - * @param responseType The responseType, such as 'text'. Default ''. - * @param async Should the XHR request use async or not? Default true. - * @param user Optional username for the XHR request. Default ''. - * @param password Optional password for the XHR request. Default ''. - * @param timeout Optional XHR timeout value. Default 0. - */ - function XHRSettings(responseType?: XMLHttpRequestResponseType, async?: boolean, user?: string, password?: string, timeout?: integer): Phaser.Types.Loader.XHRSettingsObject; - - } - - namespace Math { - namespace Angle { - /** - * Find the angle of a segment from (x1, y1) -> (x2, y2). - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - */ - function Between(x1: number, y1: number, x2: number, y2: number): number; - - /** - * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). - * - * Calculates the angle of the vector from the first point to the second point. - * @param point1 The first point. - * @param point2 The second point. - */ - function BetweenPoints(point1: Phaser.Geom.Point | object, point2: Phaser.Geom.Point | object): number; - - /** - * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). - * - * The difference between this method and {@link Phaser.Math.Angle.BetweenPoints} is that this assumes the y coordinate - * travels down the screen. - * @param point1 The first point. - * @param point2 The second point. - */ - function BetweenPointsY(point1: Phaser.Geom.Point | object, point2: Phaser.Geom.Point | object): number; - - /** - * Find the angle of a segment from (x1, y1) -> (x2, y2). - * - * The difference between this method and {@link Phaser.Math.Angle.Between} is that this assumes the y coordinate - * travels down the screen. - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - */ - function BetweenY(x1: number, y1: number, x2: number, y2: number): number; - - /** - * Takes an angle in Phasers default clockwise format and converts it so that - * 0 is North, 90 is West, 180 is South and 270 is East, - * therefore running counter-clockwise instead of clockwise. - * - * You can pass in the angle from a Game Object using: - * - * ```javascript - * var converted = CounterClockwise(gameobject.rotation); - * ``` - * - * All values for this function are in radians. - * @param angle The angle to convert, in radians. - */ - function CounterClockwise(angle: number): number; - - /** - * Normalize an angle to the [0, 2pi] range. - * @param angle The angle to normalize, in radians. - */ - function Normalize(angle: number): number; - - /** - * Reverse the given angle. - * @param angle The angle to reverse, in radians. - */ - function Reverse(angle: number): number; - - /** - * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. - * @param currentAngle The current angle, in radians. - * @param targetAngle The target angle to rotate to, in radians. - * @param lerp The lerp value to add to the current angle. Default 0.05. - */ - function RotateTo(currentAngle: number, targetAngle: number, lerp?: number): number; - - /** - * Gets the shortest angle between `angle1` and `angle2`. - * - * Both angles must be in the range -180 to 180, which is the same clamped - * range that `sprite.angle` uses, so you can pass in two sprite angles to - * this method and get the shortest angle back between the two of them. - * - * The angle returned will be in the same range. If the returned angle is - * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's - * a clockwise rotation. - * - * TODO: Wrap the angles in this function? - * @param angle1 The first angle in the range -180 to 180. - * @param angle2 The second angle in the range -180 to 180. - */ - function ShortestBetween(angle1: number, angle2: number): number; - - /** - * Wrap an angle. - * - * Wraps the angle to a value in the range of -PI to PI. - * @param angle The angle to wrap, in radians. - */ - function Wrap(angle: number): number; - - /** - * Wrap an angle in degrees. - * - * Wraps the angle to a value in the range of -180 to 180. - * @param angle The angle to wrap, in degrees. - */ - function WrapDegrees(angle: number): number; - - } - - /** - * Calculate the mean average of the given values. - * @param values The values to average. - */ - function Average(values: number[]): number; - - /** - * [description] - * @param n [description] - * @param i [description] - */ - function Bernstein(n: number, i: number): number; - - /** - * Compute a random integer between the `min` and `max` values, inclusive. - * @param min The minimum value. - * @param max The maximum value. - */ - function Between(min: integer, max: integer): integer; - - /** - * Calculates a Catmull-Rom value. - * @param t [description] - * @param p0 [description] - * @param p1 [description] - * @param p2 [description] - * @param p3 [description] - */ - function CatmullRom(t: number, p0: number, p1: number, p2: number, p3: number): number; - - /** - * Ceils to some place comparative to a `base`, default is 10 for decimal place. - * - * The `place` is represented by the power applied to `base` to get that place. - * @param value The value to round. - * @param place The place to round to. Default 0. - * @param base The base to round in. Default is 10 for decimal. Default 10. - */ - function CeilTo(value: number, place?: number, base?: integer): number; - - /** - * Force a value within the boundaries by clamping it to the range `min`, `max`. - * @param value The value to be clamped. - * @param min The minimum bounds. - * @param max The maximum bounds. - */ - function Clamp(value: number, min: number, max: number): number; - - /** - * The value of PI * 2. - */ - var PI2: number; - - /** - * The value of PI * 0.5. - */ - var TAU: number; - - /** - * An epsilon value (1.0e-6) - */ - var EPSILON: number; - - /** - * For converting degrees to radians (PI / 180) - */ - var DEG_TO_RAD: number; - - /** - * For converting radians to degrees (180 / PI) - */ - var RAD_TO_DEG: number; - - /** - * An instance of the Random Number Generator. - * This is not set until the Game boots. - */ - var RND: Phaser.Math.RandomDataGenerator; - - /** - * The minimum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - */ - var MIN_SAFE_INTEGER: number; - - /** - * The maximum safe integer this browser supports. - * We use a const for backward compatibility with Internet Explorer. - */ - var MAX_SAFE_INTEGER: number; - - /** - * Convert the given angle from degrees, to the equivalent angle in radians. - * @param degrees The angle (in degrees) to convert to radians. - */ - function DegToRad(degrees: integer): number; - - /** - * Calculates the positive difference of two given numbers. - * @param a The first number in the calculation. - * @param b The second number in the calculation. - */ - function Difference(a: number, b: number): number; - - namespace Distance { - /** - * Calculate the distance between two sets of coordinates (points). - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - */ - function Between(x1: number, y1: number, x2: number, y2: number): number; - - /** - * Calculate the distance between two points. - * @param a The first point. - * @param b The second point. - */ - function BetweenPoints(a: Phaser.Types.Math.Vector2Like, b: Phaser.Types.Math.Vector2Like): number; - - /** - * Calculate the squared distance between two points. - * @param a The first point. - * @param b The second point. - */ - function BetweenPointsSquared(a: Phaser.Types.Math.Vector2Like, b: Phaser.Types.Math.Vector2Like): number; - - /** - * Calculate the Chebyshev distance between two sets of coordinates (points). - * - * Chebyshev distance (or chessboard distance) is the maximum of the horizontal and vertical distances. - * It's the effective distance when movement can be horizontal, vertical, or diagonal. - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - */ - function Chebyshev(x1: number, y1: number, x2: number, y2: number): number; - - /** - * Calculate the distance between two sets of coordinates (points) to the power of `pow`. - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - * @param pow The exponent. - */ - function Power(x1: number, y1: number, x2: number, y2: number, pow: number): number; - - /** - * Calculate the snake distance between two sets of coordinates (points). - * - * Snake distance (rectilinear distance, Manhattan distance) is the sum of the horizontal and vertical distances. - * It's the effective distance when movement is allowed only horizontally or vertically (but not both). - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - */ - function Snake(x1: number, y1: number, x2: number, y2: number): number; - - /** - * Calculate the distance between two sets of coordinates (points), squared. - * @param x1 The x coordinate of the first point. - * @param y1 The y coordinate of the first point. - * @param x2 The x coordinate of the second point. - * @param y2 The y coordinate of the second point. - */ - function Squared(x1: number, y1: number, x2: number, y2: number): number; - - } - - namespace Easing { - namespace Back { - /** - * Back ease-in. - * @param v The value to be tweened. - * @param overshoot The overshoot amount. Default 1.70158. - */ - function In(v: number, overshoot?: number): number; - - /** - * Back ease-in/out. - * @param v The value to be tweened. - * @param overshoot The overshoot amount. Default 1.70158. - */ - function InOut(v: number, overshoot?: number): number; - - /** - * Back ease-out. - * @param v The value to be tweened. - * @param overshoot The overshoot amount. Default 1.70158. - */ - function Out(v: number, overshoot?: number): number; - - } - - namespace Bounce { - /** - * Bounce ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Bounce ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Bounce ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Circular { - /** - * Circular ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Circular ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Circular ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Cubic { - /** - * Cubic ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Cubic ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Cubic ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Elastic { - /** - * Elastic ease-in. - * @param v The value to be tweened. - * @param amplitude The amplitude of the elastic ease. Default 0.1. - * @param period Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. Default 0.1. - */ - function In(v: number, amplitude?: number, period?: number): number; - - /** - * Elastic ease-in/out. - * @param v The value to be tweened. - * @param amplitude The amplitude of the elastic ease. Default 0.1. - * @param period Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. Default 0.1. - */ - function InOut(v: number, amplitude?: number, period?: number): number; - - /** - * Elastic ease-out. - * @param v The value to be tweened. - * @param amplitude The amplitude of the elastic ease. Default 0.1. - * @param period Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. Default 0.1. - */ - function Out(v: number, amplitude?: number, period?: number): number; - - } - - namespace Expo { - /** - * Exponential ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Exponential ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Exponential ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Linear { - /** - * Linear easing (no variation). - * @param v The value to be tweened. - */ - function Linear(v: number): number; - - } - - namespace Quadratic { - /** - * Quadratic ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Quadratic ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Quadratic ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Quartic { - /** - * Quartic ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Quartic ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Quartic ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Quintic { - /** - * Quintic ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Quintic ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Quintic ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Sine { - /** - * Sinusoidal ease-in. - * @param v The value to be tweened. - */ - function In(v: number): number; - - /** - * Sinusoidal ease-in/out. - * @param v The value to be tweened. - */ - function InOut(v: number): number; - - /** - * Sinusoidal ease-out. - * @param v The value to be tweened. - */ - function Out(v: number): number; - - } - - namespace Stepped { - /** - * Stepped easing. - * @param v The value to be tweened. - * @param steps The number of steps in the ease. Default 1. - */ - function Stepped(v: number, steps?: number): number; - - } - - } - - /** - * Calculates the factorial of a given number for integer values greater than 0. - * @param value A positive integer to calculate the factorial of. - */ - function Factorial(value: number): number; - - /** - * Generate a random floating point number between the two given bounds, minimum inclusive, maximum exclusive. - * @param min The lower bound for the float, inclusive. - * @param max The upper bound for the float exclusive. - */ - function FloatBetween(min: number, max: number): number; - - /** - * Floors to some place comparative to a `base`, default is 10 for decimal place. - * - * The `place` is represented by the power applied to `base` to get that place. - * @param value The value to round. - * @param place The place to round to. Default 0. - * @param base The base to round in. Default is 10 for decimal. Default 10. - */ - function FloorTo(value: number, place?: integer, base?: integer): number; - - /** - * Return a value based on the range between `min` and `max` and the percentage given. - * @param percent A value between 0 and 1 representing the percentage. - * @param min The minimum value. - * @param max The maximum value. - */ - function FromPercent(percent: number, min: number, max?: number): number; - - namespace Fuzzy { - /** - * Calculate the fuzzy ceiling of the given value. - * @param value The value. - * @param epsilon The epsilon. Default 0.0001. - */ - function Ceil(value: number, epsilon?: number): number; - - /** - * Check whether the given values are fuzzily equal. - * - * Two numbers are fuzzily equal if their difference is less than `epsilon`. - * @param a The first value. - * @param b The second value. - * @param epsilon The epsilon. Default 0.0001. - */ - function Equal(a: number, b: number, epsilon?: number): boolean; - - /** - * Calculate the fuzzy floor of the given value. - * @param value The value. - * @param epsilon The epsilon. Default 0.0001. - */ - function Floor(value: number, epsilon?: number): number; - - /** - * Check whether `a` is fuzzily greater than `b`. - * - * `a` is fuzzily greater than `b` if it is more than `b - epsilon`. - * @param a The first value. - * @param b The second value. - * @param epsilon The epsilon. Default 0.0001. - */ - function GreaterThan(a: number, b: number, epsilon?: number): boolean; - - /** - * Check whether `a` is fuzzily less than `b`. - * - * `a` is fuzzily less than `b` if it is less than `b + epsilon`. - * @param a The first value. - * @param b The second value. - * @param epsilon The epsilon. Default 0.0001. - */ - function LessThan(a: number, b: number, epsilon?: number): boolean; - - } - - /** - * Calculate a per-ms speed from a distance and time (given in seconds). - * @param distance The distance. - * @param time The time, in seconds. - */ - function GetSpeed(distance: number, time: integer): number; - - namespace Interpolation { - /** - * A bezier interpolation method. - * @param v The input array of values to interpolate between. - * @param k The percentage of interpolation, between 0 and 1. - */ - function Bezier(v: number[], k: number): number; - - /** - * A Catmull-Rom interpolation method. - * @param v The input array of values to interpolate between. - * @param k The percentage of interpolation, between 0 and 1. - */ - function CatmullRom(v: number[], k: number): number; - - /** - * A cubic bezier interpolation method. - * - * https://medium.com/@adrian_cooney/bezier-interpolation-13b68563313a - * @param t The percentage of interpolation, between 0 and 1. - * @param p0 The start point. - * @param p1 The first control point. - * @param p2 The second control point. - * @param p3 The end point. - */ - function CubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - - /** - * A linear interpolation method. - * @param v The input array of values to interpolate between. - * @param k The percentage of interpolation, between 0 and 1. - */ - function Linear(v: number[], k: number): number; - - /** - * A quadratic bezier interpolation method. - * @param t The percentage of interpolation, between 0 and 1. - * @param p0 The start point. - * @param p1 The control point. - * @param p2 The end point. - */ - function QuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - - /** - * A Smoother Step interpolation method. - * @param t The percentage of interpolation, between 0 and 1. - * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. - * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. - */ - function SmootherStep(t: number, min: number, max: number): number; - - /** - * A Smooth Step interpolation method. - * @param t The percentage of interpolation, between 0 and 1. - * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. - * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. - */ - function SmoothStep(t: number, min: number, max: number): number; - - } - - /** - * Check if a given value is an even number. - * @param value The number to perform the check with. - */ - function IsEven(value: number): boolean; - - /** - * Check if a given value is an even number using a strict type check. - * @param value The number to perform the check with. - */ - function IsEvenStrict(value: number): boolean; - - /** - * Calculates a linear (interpolation) value over t. - * @param p0 The first point. - * @param p1 The second point. - * @param t The percentage between p0 and p1 to return, represented as a number between 0 and 1. - */ - function Linear(p0: number, p1: number, t: number): number; - - /** - * A three-dimensional matrix. - * - * Defaults to the identity matrix when instantiated. - */ - class Matrix3 { - /** - * - * @param m Optional Matrix3 to copy values from. - */ - constructor(m?: Phaser.Math.Matrix3); - - /** - * The matrix values. - */ - val: Float32Array; - - /** - * Make a clone of this Matrix3. - */ - clone(): Phaser.Math.Matrix3; - - /** - * This method is an alias for `Matrix3.copy`. - * @param src The Matrix to set the values of this Matrix's from. - */ - set(src: Phaser.Math.Matrix3): Phaser.Math.Matrix3; - - /** - * Copy the values of a given Matrix into this Matrix. - * @param src The Matrix to copy the values from. - */ - copy(src: Phaser.Math.Matrix3): Phaser.Math.Matrix3; - - /** - * Copy the values of a given Matrix4 into this Matrix3. - * @param m The Matrix4 to copy the values from. - */ - fromMat4(m: Phaser.Math.Matrix4): Phaser.Math.Matrix3; - - /** - * Set the values of this Matrix from the given array. - * @param a The array to copy the values from. - */ - fromArray(a: any[]): Phaser.Math.Matrix3; - - /** - * Reset this Matrix to an identity (default) matrix. - */ - identity(): Phaser.Math.Matrix3; - - /** - * Transpose this Matrix. - */ - transpose(): Phaser.Math.Matrix3; - - /** - * Invert this Matrix. - */ - invert(): Phaser.Math.Matrix3; - - /** - * Calculate the adjoint, or adjugate, of this Matrix. - */ - adjoint(): Phaser.Math.Matrix3; - - /** - * Calculate the determinant of this Matrix. - */ - determinant(): number; - - /** - * Multiply this Matrix by the given Matrix. - * @param src The Matrix to multiply this Matrix by. - */ - multiply(src: Phaser.Math.Matrix3): Phaser.Math.Matrix3; - - /** - * Translate this Matrix using the given Vector. - * @param v The Vector to translate this Matrix with. - */ - translate(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix3; - - /** - * Apply a rotation transformation to this Matrix. - * @param rad The angle in radians to rotate by. - */ - rotate(rad: number): Phaser.Math.Matrix3; - - /** - * Apply a scale transformation to this Matrix. - * - * Uses the `x` and `y` components of the given Vector to scale the Matrix. - * @param v The Vector to scale this Matrix with. - */ - scale(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix3; - - /** - * Set the values of this Matrix from the given Quaternion. - * @param q The Quaternion to set the values of this Matrix from. - */ - fromQuat(q: Phaser.Math.Quaternion): Phaser.Math.Matrix3; - - /** - * [description] - * @param m [description] - */ - normalFromMat4(m: Phaser.Math.Matrix4): Phaser.Math.Matrix3; - - } - - /** - * A four-dimensional matrix. - */ - class Matrix4 { - /** - * - * @param m Optional Matrix4 to copy values from. - */ - constructor(m?: Phaser.Math.Matrix4); - - /** - * The matrix values. - */ - val: Float32Array; - - /** - * Make a clone of this Matrix4. - */ - clone(): Phaser.Math.Matrix4; - - /** - * This method is an alias for `Matrix4.copy`. - * @param src The Matrix to set the values of this Matrix's from. - */ - set(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; - - /** - * Copy the values of a given Matrix into this Matrix. - * @param src The Matrix to copy the values from. - */ - copy(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; - - /** - * Set the values of this Matrix from the given array. - * @param a The array to copy the values from. - */ - fromArray(a: any[]): Phaser.Math.Matrix4; - - /** - * Reset this Matrix. - * - * Sets all values to `0`. - */ - zero(): Phaser.Math.Matrix4; - - /** - * Set the `x`, `y` and `z` values of this Matrix. - * @param x The x value. - * @param y The y value. - * @param z The z value. - */ - xyz(x: number, y: number, z: number): Phaser.Math.Matrix4; - - /** - * Set the scaling values of this Matrix. - * @param x The x scaling value. - * @param y The y scaling value. - * @param z The z scaling value. - */ - scaling(x: number, y: number, z: number): Phaser.Math.Matrix4; - - /** - * Reset this Matrix to an identity (default) matrix. - */ - identity(): Phaser.Math.Matrix4; - - /** - * Transpose this Matrix. - */ - transpose(): Phaser.Math.Matrix4; - - /** - * Invert this Matrix. - */ - invert(): Phaser.Math.Matrix4; - - /** - * Calculate the adjoint, or adjugate, of this Matrix. - */ - adjoint(): Phaser.Math.Matrix4; - - /** - * Calculate the determinant of this Matrix. - */ - determinant(): number; - - /** - * Multiply this Matrix by the given Matrix. - * @param src The Matrix to multiply this Matrix by. - */ - multiply(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; - - /** - * [description] - * @param src [description] - */ - multiplyLocal(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; - - /** - * Translate this Matrix using the given Vector. - * @param v The Vector to translate this Matrix with. - */ - translate(v: Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix4; - - /** - * Translate this Matrix using the given values. - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - translateXYZ(x: number, y: number, z: number): Phaser.Math.Matrix4; - - /** - * Apply a scale transformation to this Matrix. - * - * Uses the `x`, `y` and `z` components of the given Vector to scale the Matrix. - * @param v The Vector to scale this Matrix with. - */ - scale(v: Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix4; - - /** - * Apply a scale transformation to this Matrix. - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - scaleXYZ(x: number, y: number, z: number): Phaser.Math.Matrix4; - - /** - * Derive a rotation matrix around the given axis. - * @param axis The rotation axis. - * @param angle The rotation angle in radians. - */ - makeRotationAxis(axis: Phaser.Math.Vector3 | Phaser.Math.Vector4, angle: number): Phaser.Math.Matrix4; - - /** - * Apply a rotation transformation to this Matrix. - * @param rad The angle in radians to rotate by. - * @param axis The axis to rotate upon. - */ - rotate(rad: number, axis: Phaser.Math.Vector3): Phaser.Math.Matrix4; - - /** - * Rotate this matrix on its X axis. - * @param rad The angle in radians to rotate by. - */ - rotateX(rad: number): Phaser.Math.Matrix4; - - /** - * Rotate this matrix on its Y axis. - * @param rad The angle to rotate by, in radians. - */ - rotateY(rad: number): Phaser.Math.Matrix4; - - /** - * Rotate this matrix on its Z axis. - * @param rad The angle to rotate by, in radians. - */ - rotateZ(rad: number): Phaser.Math.Matrix4; - - /** - * Set the values of this Matrix from the given rotation Quaternion and translation Vector. - * @param q The Quaternion to set rotation from. - * @param v The Vector to set translation from. - */ - fromRotationTranslation(q: Phaser.Math.Quaternion, v: Phaser.Math.Vector3): Phaser.Math.Matrix4; - - /** - * Set the values of this Matrix from the given Quaternion. - * @param q The Quaternion to set the values of this Matrix from. - */ - fromQuat(q: Phaser.Math.Quaternion): Phaser.Math.Matrix4; - - /** - * Generate a frustum matrix with the given bounds. - * @param left The left bound of the frustum. - * @param right The right bound of the frustum. - * @param bottom The bottom bound of the frustum. - * @param top The top bound of the frustum. - * @param near The near bound of the frustum. - * @param far The far bound of the frustum. - */ - frustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Phaser.Math.Matrix4; - - /** - * Generate a perspective projection matrix with the given bounds. - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. Typically viewport width /height. - * @param near Near bound of the frustum. - * @param far Far bound of the frustum. - */ - perspective(fovy: number, aspect: number, near: number, far: number): Phaser.Math.Matrix4; - - /** - * Generate a perspective projection matrix with the given bounds. - * @param width The width of the frustum. - * @param height The height of the frustum. - * @param near Near bound of the frustum. - * @param far Far bound of the frustum. - */ - perspectiveLH(width: number, height: number, near: number, far: number): Phaser.Math.Matrix4; - - /** - * Generate an orthogonal projection matrix with the given bounds. - * @param left The left bound of the frustum. - * @param right The right bound of the frustum. - * @param bottom The bottom bound of the frustum. - * @param top The top bound of the frustum. - * @param near The near bound of the frustum. - * @param far The far bound of the frustum. - */ - ortho(left: number, right: number, bottom: number, top: number, near: number, far: number): Phaser.Math.Matrix4; - - /** - * Generate a look-at matrix with the given eye position, focal point, and up axis. - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up. - */ - lookAt(eye: Phaser.Math.Vector3, center: Phaser.Math.Vector3, up: Phaser.Math.Vector3): Phaser.Math.Matrix4; - - /** - * Set the values of this matrix from the given `yaw`, `pitch` and `roll` values. - * @param yaw [description] - * @param pitch [description] - * @param roll [description] - */ - yawPitchRoll(yaw: number, pitch: number, roll: number): Phaser.Math.Matrix4; - - /** - * Generate a world matrix from the given rotation, position, scale, view matrix and projection matrix. - * @param rotation The rotation of the world matrix. - * @param position The position of the world matrix. - * @param scale The scale of the world matrix. - * @param viewMatrix The view matrix. - * @param projectionMatrix The projection matrix. - */ - setWorldMatrix(rotation: Phaser.Math.Vector3, position: Phaser.Math.Vector3, scale: Phaser.Math.Vector3, viewMatrix?: Phaser.Math.Matrix4, projectionMatrix?: Phaser.Math.Matrix4): Phaser.Math.Matrix4; - - } - - /** - * Add an `amount` to a `value`, limiting the maximum result to `max`. - * @param value The value to add to. - * @param amount The amount to add. - * @param max The maximum value to return. - */ - function MaxAdd(value: number, amount: number, max: number): number; - - /** - * Subtract an `amount` from `value`, limiting the minimum result to `min`. - * @param value The value to subtract from. - * @param amount The amount to subtract. - * @param min The minimum value to return. - */ - function MinSub(value: number, amount: number, min: number): number; - - /** - * Work out what percentage `value` is of the range between `min` and `max`. - * If `max` isn't given then it will return the percentage of `value` to `min`. - * - * You can optionally specify an `upperMax` value, which is a mid-way point in the range that represents 100%, after which the % starts to go down to zero again. - * @param value The value to determine the percentage of. - * @param min The minimum value. - * @param max The maximum value. - * @param upperMax The mid-way point in the range that represents 100%. - */ - function Percent(value: number, min: number, max?: number, upperMax?: number): number; - - namespace Pow2 { - /** - * Returns the nearest power of 2 to the given `value`. - * @param value The value. - */ - function GetNext(value: number): integer; - - /** - * Checks if the given `width` and `height` are a power of two. - * Useful for checking texture dimensions. - * @param width The width. - * @param height The height. - */ - function IsSize(width: number, height: number): boolean; - - /** - * Tests the value and returns `true` if it is a power of two. - * @param value The value to check if it's a power of two. - */ - function IsValue(value: number): boolean; - - } - - /** - * A quaternion. - */ - class Quaternion { - /** - * - * @param x The x component. - * @param y The y component. - * @param z The z component. - * @param w The w component. - */ - constructor(x?: number, y?: number, z?: number, w?: number); - - /** - * The x component of this Quaternion. - */ - x: number; - - /** - * The y component of this Quaternion. - */ - y: number; - - /** - * The z component of this Quaternion. - */ - z: number; - - /** - * The w component of this Quaternion. - */ - w: number; - - /** - * Copy the components of a given Quaternion or Vector into this Quaternion. - * @param src The Quaternion or Vector to copy the components from. - */ - copy(src: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; - - /** - * Set the components of this Quaternion. - * @param x The x component, or an object containing x, y, z, and w components. Default 0. - * @param y The y component. Default 0. - * @param z The z component. Default 0. - * @param w The w component. Default 0. - */ - set(x?: number | object, y?: number, z?: number, w?: number): Phaser.Math.Quaternion; - - /** - * Add a given Quaternion or Vector to this Quaternion. Addition is component-wise. - * @param v The Quaternion or Vector to add to this Quaternion. - */ - add(v: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; - - /** - * Subtract a given Quaternion or Vector from this Quaternion. Subtraction is component-wise. - * @param v The Quaternion or Vector to subtract from this Quaternion. - */ - subtract(v: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; - - /** - * Scale this Quaternion by the given value. - * @param scale The value to scale this Quaternion by. - */ - scale(scale: number): Phaser.Math.Quaternion; - - /** - * Calculate the length of this Quaternion. - */ - length(): number; - - /** - * Calculate the length of this Quaternion squared. - */ - lengthSq(): number; - - /** - * Normalize this Quaternion. - */ - normalize(): Phaser.Math.Quaternion; - - /** - * Calculate the dot product of this Quaternion and the given Quaternion or Vector. - * @param v The Quaternion or Vector to dot product with this Quaternion. - */ - dot(v: Phaser.Math.Quaternion | Phaser.Math.Vector4): number; - - /** - * Linearly interpolate this Quaternion towards the given Quaternion or Vector. - * @param v The Quaternion or Vector to interpolate towards. - * @param t The percentage of interpolation. Default 0. - */ - lerp(v: Phaser.Math.Quaternion | Phaser.Math.Vector4, t?: number): Phaser.Math.Quaternion; - - /** - * [description] - * @param a [description] - * @param b [description] - */ - rotationTo(a: Phaser.Math.Vector3, b: Phaser.Math.Vector3): Phaser.Math.Quaternion; - - /** - * Set the axes of this Quaternion. - * @param view The view axis. - * @param right The right axis. - * @param up The upwards axis. - */ - setAxes(view: Phaser.Math.Vector3, right: Phaser.Math.Vector3, up: Phaser.Math.Vector3): Phaser.Math.Quaternion; - - /** - * Reset this Matrix to an identity (default) Quaternion. - */ - identity(): Phaser.Math.Quaternion; - - /** - * Set the axis angle of this Quaternion. - * @param axis The axis. - * @param rad The angle in radians. - */ - setAxisAngle(axis: Phaser.Math.Vector3, rad: number): Phaser.Math.Quaternion; - - /** - * Multiply this Quaternion by the given Quaternion or Vector. - * @param b The Quaternion or Vector to multiply this Quaternion by. - */ - multiply(b: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; - - /** - * Smoothly linearly interpolate this Quaternion towards the given Quaternion or Vector. - * @param b The Quaternion or Vector to interpolate towards. - * @param t The percentage of interpolation. - */ - slerp(b: Phaser.Math.Quaternion | Phaser.Math.Vector4, t: number): Phaser.Math.Quaternion; - - /** - * Invert this Quaternion. - */ - invert(): Phaser.Math.Quaternion; - - /** - * Convert this Quaternion into its conjugate. - * - * Sets the x, y and z components. - */ - conjugate(): Phaser.Math.Quaternion; - - /** - * Rotate this Quaternion on the X axis. - * @param rad The rotation angle in radians. - */ - rotateX(rad: number): Phaser.Math.Quaternion; - - /** - * Rotate this Quaternion on the Y axis. - * @param rad The rotation angle in radians. - */ - rotateY(rad: number): Phaser.Math.Quaternion; - - /** - * Rotate this Quaternion on the Z axis. - * @param rad The rotation angle in radians. - */ - rotateZ(rad: number): Phaser.Math.Quaternion; - - /** - * Create a unit (or rotation) Quaternion from its x, y, and z components. - * - * Sets the w component. - */ - calculateW(): Phaser.Math.Quaternion; - - /** - * Convert the given Matrix into this Quaternion. - * @param mat The Matrix to convert from. - */ - fromMat3(mat: Phaser.Math.Matrix3): Phaser.Math.Quaternion; - - } - - /** - * Convert the given angle in radians, to the equivalent angle in degrees. - * @param radians The angle in radians to convert ot degrees. - */ - function RadToDeg(radians: number): integer; - - /** - * 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 { - /** - * - * @param seeds The seeds to use for the random number generator. - */ - constructor(seeds?: string | string[]); - - /** - * Signs to choose from. - */ - signs: number[]; - - /** - * Initialize the state of the random data generator. - * @param seeds The seeds to initialize the random data generator with. - */ - init(seeds: string | string[]): void; - - /** - * Reset the seed of the random data generator. - * - * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. - * @param seeds The array of seeds: the `toString()` of each value is used. - */ - sow(seeds: string[]): void; - - /** - * Returns a random integer between 0 and 2^32. - */ - integer(): number; - - /** - * Returns a random real number between 0 and 1. - */ - frac(): number; - - /** - * Returns a random real number between 0 and 2^32. - */ - real(): number; - - /** - * Returns a random integer between and including min and max. - * @param min The minimum value in the range. - * @param max The maximum value in the range. - */ - integerInRange(min: number, max: number): number; - - /** - * Returns a random integer between and including min and max. - * This method is an alias for RandomDataGenerator.integerInRange. - * @param min The minimum value in the range. - * @param max The maximum value in the range. - */ - between(min: number, max: number): number; - - /** - * Returns a random real number between min and max. - * @param min The minimum value in the range. - * @param max The maximum value in the range. - */ - realInRange(min: number, max: number): number; - - /** - * Returns a random real number between -1 and 1. - */ - normal(): number; - - /** - * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 - */ - uuid(): string; - - /** - * Returns a random element from within the given array. - * @param array The array to pick a random element from. - */ - pick(array: T[]): T; - - /** - * Returns a sign to be used with multiplication operator. - */ - sign(): number; - - /** - * Returns a random element from within the given array, favoring the earlier entries. - * @param array The array to pick a random element from. - */ - weightedPick(array: T[]): T; - - /** - * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. - * @param min The minimum value in the range. - * @param max The maximum value in the range. - */ - timestamp(min: number, max: number): number; - - /** - * Returns a random angle between -180 and 180. - */ - angle(): number; - - /** - * Returns a random rotation in radians, between -3.141 and 3.141 - */ - rotation(): number; - - /** - * Gets or Sets the state of the generator. This allows you to retain the values - * that the generator is using between games, i.e. in a game save file. - * - * To seed this generator with a previously saved state you can pass it as the - * `seed` value in your game config, or call this method directly after Phaser has booted. - * - * Call this method with no parameters to return the current state. - * - * If providing a state it should match the same format that this method - * returns, which is a string with a header `!rnd` followed by the `c`, - * `s0`, `s1` and `s2` values respectively, each comma-delimited. - * @param state Generator state to be set. - */ - state(state?: string): string; - - /** - * Shuffles the given array, using the current seed. - * @param array The array to be shuffled. - */ - shuffle(array?: T[]): T[]; - - } - - /** - * Compute a random unit vector. - * - * Computes random values for the given vector between -1 and 1 that can be used to represent a direction. - * - * Optionally accepts a scale value to scale the resulting vector by. - * @param vector The Vector to compute random values for. - * @param scale The scale of the random values. Default 1. - */ - function RandomXY(vector: Phaser.Math.Vector2, scale?: number): Phaser.Math.Vector2; - - /** - * Compute a random position vector in a spherical area, optionally defined by the given radius. - * @param vec3 The Vector to compute random values for. - * @param radius The radius. Default 1. - */ - function RandomXYZ(vec3: Phaser.Math.Vector3, radius?: number): Phaser.Math.Vector3; - - /** - * Compute a random four-dimensional vector. - * @param vec4 The Vector to compute random values for. - * @param scale The scale of the random values. Default 1. - */ - function RandomXYZW(vec4: Phaser.Math.Vector4, scale?: number): Phaser.Math.Vector4; - - /** - * Rotate a given point by a given angle around the origin (0, 0), in an anti-clockwise direction. - * @param point The point to be rotated. - * @param angle The angle to be rotated by in an anticlockwise direction. - */ - function Rotate(point: Phaser.Geom.Point | object, angle: number): Phaser.Geom.Point; - - /** - * Rotate a `point` around `x` and `y` by the given `angle`. - * @param point The point to be rotated. - * @param x The horizontal coordinate to rotate around. - * @param y The vertical coordinate to rotate around. - * @param angle The angle of rotation in radians. - */ - function RotateAround(point: Phaser.Geom.Point | object, x: number, y: number, angle: number): Phaser.Geom.Point; - - /** - * Rotate a `point` around `x` and `y` by the given `angle` and `distance`. - * @param point The point to be rotated. - * @param x The horizontal coordinate to rotate around. - * @param y The vertical coordinate to rotate around. - * @param angle The angle of rotation in radians. - * @param distance The distance from (x, y) to place the point at. - */ - function RotateAroundDistance(point: Phaser.Geom.Point | object, x: number, y: number, angle: number, distance: number): Phaser.Geom.Point; - - /** - * Rotates a vector in place by axis angle. - * - * This is the same as transforming a point by an - * axis-angle quaternion, but it has higher precision. - * @param vec The vector to be rotated. - * @param axis The axis to rotate around. - * @param radians The angle of rotation in radians. - */ - function RotateVec3(vec: Phaser.Math.Vector3, axis: Phaser.Math.Vector3, radians: number): Phaser.Math.Vector3; - - /** - * Round a given number so it is further away from zero. That is, positive numbers are rounded up, and negative numbers are rounded down. - * @param value The number to round. - */ - function RoundAwayFromZero(value: number): number; - - /** - * Round a value to the given precision. - * - * For example: - * - * ```javascript - * RoundTo(123.456, 0) = 123 - * RoundTo(123.456, 1) = 120 - * RoundTo(123.456, 2) = 100 - * ``` - * - * To round the decimal, i.e. to round to precision, pass in a negative `place`: - * - * ```javascript - * RoundTo(123.456789, 0) = 123 - * RoundTo(123.456789, -1) = 123.5 - * RoundTo(123.456789, -2) = 123.46 - * RoundTo(123.456789, -3) = 123.457 - * ``` - * @param value The value to round. - * @param place The place to round to. Positive to round the units, negative to round the decimal. Default 0. - * @param base The base to round in. Default is 10 for decimal. Default 10. - */ - function RoundTo(value: number, place?: integer, base?: integer): number; - - /** - * Generate a series of sine and cosine values. - * @param length The number of values to generate. - * @param sinAmp The sine value amplitude. Default 1. - * @param cosAmp The cosine value amplitude. Default 1. - * @param frequency The frequency of the values. Default 1. - */ - function SinCosTableGenerator(length: number, sinAmp?: number, cosAmp?: number, frequency?: number): Phaser.Types.Math.SinCosTable; - - /** - * 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}. - * @param x The input value. - * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. - * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. - */ - function SmootherStep(x: number, min: number, max: number): number; - - /** - * 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. - * @param x The input value. - * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. - * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. - */ - function SmoothStep(x: number, min: number, max: number): number; - - namespace Snap { - /** - * Snap a value to nearest grid slice, using ceil. - * - * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `15`. - * As will `14` snap to `15`... but `16` will snap to `20`. - * @param value The value to snap. - * @param gap The interval gap of the grid. - * @param start Optional starting offset for gap. Default 0. - * @param divide If `true` it will divide the snapped value by the gap before returning. Default false. - */ - function Ceil(value: number, gap: number, start?: number, divide?: boolean): number; - - /** - * Snap a value to nearest grid slice, using floor. - * - * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10`. - * As will `14` snap to `10`... but `16` will snap to `15`. - * @param value The value to snap. - * @param gap The interval gap of the grid. - * @param start Optional starting offset for gap. Default 0. - * @param divide If `true` it will divide the snapped value by the gap before returning. Default false. - */ - function Floor(value: number, gap: number, start?: number, divide?: boolean): number; - - /** - * Snap a value to nearest grid slice, using rounding. - * - * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10` whereas `14` will snap to `15`. - * @param value The value to snap. - * @param gap The interval gap of the grid. - * @param start Optional starting offset for gap. Default 0. - * @param divide If `true` it will divide the snapped value by the gap before returning. Default false. - */ - function To(value: number, gap: number, start?: number, divide?: boolean): number; - - } - - /** - * Returns a Vector2 containing the x and y position of the given index in a `width` x `height` sized grid. - * - * For example, in a 6 x 4 grid, index 16 would equal x: 4 y: 2. - * - * If the given index is out of range an empty Vector2 is returned. - * @param index The position within the grid to get the x/y value for. - * @param width The width of the grid. - * @param height The height of the grid. - * @param out An optional Vector2 to store the result in. If not given, a new Vector2 instance will be created. - */ - function ToXY(index: integer, width: integer, height: integer, out?: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Takes the `x` and `y` coordinates and transforms them into the same space as - * defined by the position, rotation and scale values. - * @param x The x coordinate to be transformed. - * @param y The y coordinate to be transformed. - * @param positionX Horizontal position of the transform point. - * @param positionY Vertical position of the transform point. - * @param rotation Rotation of the transform point, in radians. - * @param scaleX Horizontal scale of the transform point. - * @param scaleY Vertical scale of the transform point. - * @param output The output vector, point or object for the translated coordinates. - */ - function TransformXY(x: number, y: number, positionX: number, positionY: number, rotation: number, scaleX: number, scaleY: number, output?: Phaser.Math.Vector2 | Phaser.Geom.Point | object): Phaser.Math.Vector2 | Phaser.Geom.Point | object; - - /** - * A representation of a vector in 2D space. - * - * A two-component vector. - */ - class Vector2 { - /** - * - * @param x The x component, or an object with `x` and `y` properties. - * @param y The y component. - */ - constructor(x?: number | Phaser.Types.Math.Vector2Like, y?: number); - - /** - * The x component of this Vector. - */ - x: number; - - /** - * The y component of this Vector. - */ - y: number; - - /** - * Make a clone of this Vector2. - */ - clone(): Phaser.Math.Vector2; - - /** - * Copy the components of a given Vector into this Vector. - * @param src The Vector to copy the components from. - */ - copy(src: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Set the component values of this Vector from a given Vector2Like object. - * @param obj The object containing the component values to set for this Vector. - */ - setFromObject(obj: Phaser.Types.Math.Vector2Like): Phaser.Math.Vector2; - - /** - * Set the `x` and `y` components of the this Vector to the given `x` and `y` values. - * @param x The x value to set for this Vector. - * @param y The y value to set for this Vector. Default x. - */ - set(x: number, y?: number): Phaser.Math.Vector2; - - /** - * This method is an alias for `Vector2.set`. - * @param x The x value to set for this Vector. - * @param y The y value to set for this Vector. Default x. - */ - setTo(x: number, y?: number): Phaser.Math.Vector2; - - /** - * Sets the `x` and `y` values of this object from a given polar coordinate. - * @param azimuth The angular coordinate, in radians. - * @param radius The radial coordinate (length). Default 1. - */ - setToPolar(azimuth: number, radius?: number): Phaser.Math.Vector2; - - /** - * Check whether this Vector is equal to a given Vector. - * - * Performs a strict equality check against each Vector's components. - * @param v The vector to compare with this Vector. - */ - equals(v: Phaser.Math.Vector2): boolean; - - /** - * Calculate the angle between this Vector and the positive x-axis, in radians. - */ - angle(): number; - - /** - * Add a given Vector to this Vector. Addition is component-wise. - * @param src The Vector to add to this Vector. - */ - add(src: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Subtract the given Vector from this Vector. Subtraction is component-wise. - * @param src The Vector to subtract from this Vector. - */ - subtract(src: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Perform a component-wise multiplication between this Vector and the given Vector. - * - * Multiplies this Vector by the given Vector. - * @param src The Vector to multiply this Vector by. - */ - multiply(src: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Scale this Vector by the given value. - * @param value The value to scale this Vector by. - */ - scale(value: number): Phaser.Math.Vector2; - - /** - * Perform a component-wise division between this Vector and the given Vector. - * - * Divides this Vector by the given Vector. - * @param src The Vector to divide this Vector by. - */ - divide(src: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Negate the `x` and `y` components of this Vector. - */ - negate(): Phaser.Math.Vector2; - - /** - * Calculate the distance between this Vector and the given Vector. - * @param src The Vector to calculate the distance to. - */ - distance(src: Phaser.Math.Vector2): number; - - /** - * Calculate the distance between this Vector and the given Vector, squared. - * @param src The Vector to calculate the distance to. - */ - distanceSq(src: Phaser.Math.Vector2): number; - - /** - * Calculate the length (or magnitude) of this Vector. - */ - length(): number; - - /** - * Calculate the length of this Vector squared. - */ - lengthSq(): number; - - /** - * Normalize this Vector. - * - * Makes the vector a unit length vector (magnitude of 1) in the same direction. - */ - normalize(): Phaser.Math.Vector2; - - /** - * Right-hand normalize (make unit length) this Vector. - */ - normalizeRightHand(): Phaser.Math.Vector2; - - /** - * Calculate the dot product of this Vector and the given Vector. - * @param src The Vector2 to dot product with this Vector2. - */ - dot(src: Phaser.Math.Vector2): number; - - /** - * Calculate the cross product of this Vector and the given Vector. - * @param src The Vector2 to cross with this Vector2. - */ - cross(src: Phaser.Math.Vector2): number; - - /** - * Linearly interpolate between this Vector and the given Vector. - * - * Interpolates this Vector towards the given Vector. - * @param src The Vector2 to interpolate towards. - * @param t The interpolation percentage, between 0 and 1. Default 0. - */ - lerp(src: Phaser.Math.Vector2, t?: number): Phaser.Math.Vector2; - - /** - * Transform this Vector with the given Matrix. - * @param mat The Matrix3 to transform this Vector2 with. - */ - transformMat3(mat: Phaser.Math.Matrix3): Phaser.Math.Vector2; - - /** - * Transform this Vector with the given Matrix. - * @param mat The Matrix4 to transform this Vector2 with. - */ - transformMat4(mat: Phaser.Math.Matrix4): Phaser.Math.Vector2; - - /** - * Make this Vector the zero vector (0, 0). - */ - reset(): Phaser.Math.Vector2; - - /** - * A static zero Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly ZERO: Phaser.Math.Vector2; - - /** - * A static right Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly RIGHT: Phaser.Math.Vector2; - - /** - * A static left Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly LEFT: Phaser.Math.Vector2; - - /** - * A static up Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly UP: Phaser.Math.Vector2; - - /** - * A static down Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly DOWN: Phaser.Math.Vector2; - - /** - * A static one Vector2 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly ONE: Phaser.Math.Vector2; - - } - - /** - * A representation of a vector in 3D space. - * - * A three-component vector. - */ - class Vector3 { - /** - * - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - constructor(x?: number, y?: number, z?: number); - - /** - * The x component of this Vector. - */ - x: number; - - /** - * The y component of this Vector. - */ - y: number; - - /** - * The z component of this Vector. - */ - z: number; - - /** - * Set this Vector to point up. - * - * Sets the y component of the vector to 1, and the others to 0. - */ - up(): Phaser.Math.Vector3; - - /** - * Make a clone of this Vector3. - */ - clone(): Phaser.Math.Vector3; - - /** - * Calculate the cross (vector) product of two given Vectors. - * @param a The first Vector to multiply. - * @param b The second Vector to multiply. - */ - crossVectors(a: Phaser.Math.Vector3, b: Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Check whether this Vector is equal to a given Vector. - * - * Performs a strict equality check against each Vector's components. - * @param v The Vector3 to compare against. - */ - equals(v: Phaser.Math.Vector3): boolean; - - /** - * Copy the components of a given Vector into this Vector. - * @param src The Vector to copy the components from. - */ - copy(src: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Set the `x`, `y`, and `z` components of this Vector to the given `x`, `y`, and `z` values. - * @param x The x value to set for this Vector, or an object containing x, y and z components. - * @param y The y value to set for this Vector. - * @param z The z value to set for this Vector. - */ - set(x: number | object, y?: number, z?: number): Phaser.Math.Vector3; - - /** - * Add a given Vector to this Vector. Addition is component-wise. - * @param v The Vector to add to this Vector. - */ - add(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Subtract the given Vector from this Vector. Subtraction is component-wise. - * @param v The Vector to subtract from this Vector. - */ - subtract(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Perform a component-wise multiplication between this Vector and the given Vector. - * - * Multiplies this Vector by the given Vector. - * @param v The Vector to multiply this Vector by. - */ - multiply(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Scale this Vector by the given value. - * @param scale The value to scale this Vector by. - */ - scale(scale: number): Phaser.Math.Vector3; - - /** - * Perform a component-wise division between this Vector and the given Vector. - * - * Divides this Vector by the given Vector. - * @param v The Vector to divide this Vector by. - */ - divide(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Negate the `x`, `y` and `z` components of this Vector. - */ - negate(): Phaser.Math.Vector3; - - /** - * Calculate the distance between this Vector and the given Vector. - * @param v The Vector to calculate the distance to. - */ - distance(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): number; - - /** - * Calculate the distance between this Vector and the given Vector, squared. - * @param v The Vector to calculate the distance to. - */ - distanceSq(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): number; - - /** - * Calculate the length (or magnitude) of this Vector. - */ - length(): number; - - /** - * Calculate the length of this Vector squared. - */ - lengthSq(): number; - - /** - * Normalize this Vector. - * - * Makes the vector a unit length vector (magnitude of 1) in the same direction. - */ - normalize(): Phaser.Math.Vector3; - - /** - * Calculate the dot product of this Vector and the given Vector. - * @param v The Vector3 to dot product with this Vector3. - */ - dot(v: Phaser.Math.Vector3): number; - - /** - * Calculate the cross (vector) product of this Vector (which will be modified) and the given Vector. - * @param v The Vector to cross product with. - */ - cross(v: Phaser.Math.Vector3): Phaser.Math.Vector3; - - /** - * Linearly interpolate between this Vector and the given Vector. - * - * Interpolates this Vector towards the given Vector. - * @param v The Vector3 to interpolate towards. - * @param t The interpolation percentage, between 0 and 1. Default 0. - */ - lerp(v: Phaser.Math.Vector3, t?: number): Phaser.Math.Vector3; - - /** - * Transform this Vector with the given Matrix. - * @param mat The Matrix3 to transform this Vector3 with. - */ - transformMat3(mat: Phaser.Math.Matrix3): Phaser.Math.Vector3; - - /** - * Transform this Vector with the given Matrix. - * @param mat The Matrix4 to transform this Vector3 with. - */ - transformMat4(mat: Phaser.Math.Matrix4): Phaser.Math.Vector3; - - /** - * Transforms the coordinates of this Vector3 with the given Matrix4. - * @param mat The Matrix4 to transform this Vector3 with. - */ - transformCoordinates(mat: Phaser.Math.Matrix4): Phaser.Math.Vector3; - - /** - * Transform this Vector with the given Quaternion. - * @param q The Quaternion to transform this Vector with. - */ - transformQuat(q: Phaser.Math.Quaternion): Phaser.Math.Vector3; - - /** - * Multiplies this Vector3 by the specified matrix, applying a W divide. This is useful for projection, - * e.g. unprojecting a 2D point into 3D space. - * @param mat The Matrix4 to multiply this Vector3 with. - */ - project(mat: Phaser.Math.Matrix4): Phaser.Math.Vector3; - - /** - * Unproject this point from 2D space to 3D space. - * The point should have its x and y properties set to - * 2D screen space, and the z either at 0 (near plane) - * or 1 (far plane). The provided matrix is assumed to already - * be combined, i.e. projection * view * model. - * - * After this operation, this vector's (x, y, z) components will - * represent the unprojected 3D coordinate. - * @param viewport Screen x, y, width and height in pixels. - * @param invProjectionView Combined projection and view matrix. - */ - unproject(viewport: Phaser.Math.Vector4, invProjectionView: Phaser.Math.Matrix4): Phaser.Math.Vector3; - - /** - * Make this Vector the zero vector (0, 0, 0). - */ - reset(): Phaser.Math.Vector3; - - /** - * A static zero Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly ZERO: Phaser.Math.Vector3; - - /** - * A static right Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly RIGHT: Phaser.Math.Vector3; - - /** - * A static left Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly LEFT: Phaser.Math.Vector3; - - /** - * A static up Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly UP: Phaser.Math.Vector3; - - /** - * A static down Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly DOWN: Phaser.Math.Vector3; - - /** - * A static forward Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly FORWARD: Phaser.Math.Vector3; - - /** - * A static back Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly BACK: Phaser.Math.Vector3; - - /** - * A static one Vector3 for use by reference. - * - * This constant is meant for comparison operations and should not be modified directly. - */ - static readonly ONE: Phaser.Math.Vector3; - - } - - /** - * A representation of a vector in 4D space. - * - * A four-component vector. - */ - class Vector4 { - /** - * - * @param x The x component. - * @param y The y component. - * @param z The z component. - * @param w The w component. - */ - constructor(x?: number, y?: number, z?: number, w?: number); - - /** - * The x component of this Vector. - */ - x: number; - - /** - * The y component of this Vector. - */ - y: number; - - /** - * The z component of this Vector. - */ - z: number; - - /** - * The w component of this Vector. - */ - w: number; - - /** - * Make a clone of this Vector4. - */ - clone(): Phaser.Math.Vector4; - - /** - * Copy the components of a given Vector into this Vector. - * @param src The Vector to copy the components from. - */ - copy(src: Phaser.Math.Vector4): Phaser.Math.Vector4; - - /** - * Check whether this Vector is equal to a given Vector. - * - * Performs a strict quality check against each Vector's components. - * @param v The vector to check equality with. - */ - equals(v: Phaser.Math.Vector4): boolean; - - /** - * Set the `x`, `y`, `z` and `w` components of the this Vector to the given `x`, `y`, `z` and `w` values. - * @param x The x value to set for this Vector, or an object containing x, y, z and w components. - * @param y The y value to set for this Vector. - * @param z The z value to set for this Vector. - * @param w The z value to set for this Vector. - */ - set(x: number | object, y: number, z: number, w: number): Phaser.Math.Vector4; - - /** - * Add a given Vector to this Vector. Addition is component-wise. - * @param v The Vector to add to this Vector. - */ - add(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; - - /** - * Subtract the given Vector from this Vector. Subtraction is component-wise. - * @param v The Vector to subtract from this Vector. - */ - subtract(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; - - /** - * Scale this Vector by the given value. - * @param scale The value to scale this Vector by. - */ - scale(scale: number): Phaser.Math.Vector4; - - /** - * Calculate the length (or magnitude) of this Vector. - */ - length(): number; - - /** - * Calculate the length of this Vector squared. - */ - lengthSq(): number; - - /** - * Normalize this Vector. - * - * Makes the vector a unit length vector (magnitude of 1) in the same direction. - */ - normalize(): Phaser.Math.Vector4; - - /** - * Calculate the dot product of this Vector and the given Vector. - * @param v The Vector4 to dot product with this Vector4. - */ - dot(v: Phaser.Math.Vector4): number; - - /** - * Linearly interpolate between this Vector and the given Vector. - * - * Interpolates this Vector towards the given Vector. - * @param v The Vector4 to interpolate towards. - * @param t The interpolation percentage, between 0 and 1. Default 0. - */ - lerp(v: Phaser.Math.Vector4, t?: number): Phaser.Math.Vector4; - - /** - * Perform a component-wise multiplication between this Vector and the given Vector. - * - * Multiplies this Vector by the given Vector. - * @param v The Vector to multiply this Vector by. - */ - multiply(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; - - /** - * Perform a component-wise division between this Vector and the given Vector. - * - * Divides this Vector by the given Vector. - * @param v The Vector to divide this Vector by. - */ - divide(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; - - /** - * Calculate the distance between this Vector and the given Vector. - * @param v The Vector to calculate the distance to. - */ - distance(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): number; - - /** - * Calculate the distance between this Vector and the given Vector, squared. - * @param v The Vector to calculate the distance to. - */ - distanceSq(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): number; - - /** - * Negate the `x`, `y`, `z` and `w` components of this Vector. - */ - negate(): Phaser.Math.Vector4; - - /** - * Transform this Vector with the given Matrix. - * @param mat The Matrix4 to transform this Vector4 with. - */ - transformMat4(mat: Phaser.Math.Matrix4): Phaser.Math.Vector4; - - /** - * Transform this Vector with the given Quaternion. - * @param q The Quaternion to transform this Vector with. - */ - transformQuat(q: Phaser.Math.Quaternion): Phaser.Math.Vector4; - - /** - * Make this Vector the zero vector (0, 0, 0, 0). - */ - reset(): Phaser.Math.Vector4; - - } - - /** - * Checks if the two values are within the given `tolerance` of each other. - * @param a The first value to use in the calculation. - * @param b The second value to use in the calculation. - * @param tolerance The tolerance. Anything equal to or less than this value is considered as being within range. - */ - function Within(a: number, b: number, tolerance: number): boolean; - - /** - * Wrap the given `value` between `min` and `max. - * @param value The value to wrap. - * @param min The minimum value. - * @param max The maximum value. - */ - function Wrap(value: number, min: number, max: number): number; - - } - - /** - * The root types namespace. - */ - namespace Types { - namespace Actions { - type CallCallback = (item: Phaser.GameObjects.GameObject)=>void; - - type GridAlignConfig = { - /** - * The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity. - * If both this value and height are set to -1 then this value overrides it and the `height` value is ignored. - */ - width?: integer; - /** - * The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity. - * If both this value and `width` are set to -1 then `width` overrides it and this value is ignored. - */ - height?: integer; - /** - * The width of the cell, in pixels, in which the item is positioned. - */ - cellWidth?: integer; - /** - * The height of the cell, in pixels, in which the item is positioned. - */ - cellHeight?: integer; - /** - * The alignment position. One of the Phaser.Display.Align consts such as `TOP_LEFT` or `RIGHT_CENTER`. - */ - position?: integer; - /** - * Optionally place the top-left of the final grid at this coordinate. - */ - x?: number; - /** - * Optionally place the top-left of the final grid at this coordinate. - */ - y?: number; - }; - - } - - namespace Animations { - type Animation = { - /** - * The key that the animation will be associated with. i.e. sprite.animations.play(key) - */ - key?: string; - /** - * An object containing data used to generate the frames for the animation - */ - frames?: Phaser.Types.Animations.AnimationFrame[]; - /** - * The key of the texture all frames of the animation will use. Can be overridden on a per frame basis. - */ - defaultTextureKey?: string; - /** - * The frame rate of playback in frames per second (default 24 if duration is null) - */ - frameRate?: integer; - /** - * How long the animation should play for in milliseconds. If not given its derived from frameRate. - */ - duration?: integer; - /** - * Skip frames if the time lags, or always advanced anyway? - */ - skipMissedFrames?: boolean; - /** - * Delay before starting playback. Value given in milliseconds. - */ - delay?: integer; - /** - * Number of times to repeat the animation (-1 for infinity) - */ - repeat?: integer; - /** - * Delay before the animation repeats. Value given in milliseconds. - */ - repeatDelay?: integer; - /** - * Should the animation yoyo? (reverse back down to the start) before repeating? - */ - yoyo?: boolean; - /** - * Should sprite.visible = true when the animation starts to play? - */ - showOnStart?: boolean; - /** - * Should sprite.visible = false when the animation finishes? - */ - hideOnComplete?: boolean; - }; - - type AnimationFrame = { - /** - * The key that the animation will be associated with. i.e. sprite.animations.play(key) - */ - key: string; - /** - * [description] - */ - frame: string | number; - /** - * [description] - */ - duration?: number; - /** - * [description] - */ - visible?: boolean; - }; - - type GenerateFrameNames = { - /** - * The string to append to every resulting frame name if using a range or an array of `frames`. - */ - prefix?: string; - /** - * If `frames` is not provided, the number of the first frame to return. - */ - start?: integer; - /** - * If `frames` is not provided, the number of the last frame to return. - */ - end?: integer; - /** - * The string to append to every resulting frame name if using a range or an array of `frames`. - */ - suffix?: string; - /** - * The minimum expected lengths of each resulting frame's number. Numbers will be left-padded with zeroes until they are this long, then prepended and appended to create the resulting frame name. - */ - zeroPad?: integer; - /** - * The array to append the created configuration objects to. - */ - outputArray?: Phaser.Types.Animations.AnimationFrame[]; - /** - * If provided as an array, the range defined by `start` and `end` will be ignored and these frame numbers will be used. - */ - frames?: boolean | integer[]; - }; - - type GenerateFrameNumbers = { - /** - * The starting frame of the animation. - */ - start?: integer; - /** - * The ending frame of the animation. - */ - end?: integer; - /** - * A frame to put at the beginning of the animation, before `start` or `outputArray` or `frames`. - */ - first?: boolean | integer; - /** - * An array to concatenate the output onto. - */ - outputArray?: Phaser.Types.Animations.AnimationFrame[]; - /** - * A custom sequence of frames. - */ - frames?: boolean | integer[]; - }; - - type JSONAnimation = { - /** - * The key that the animation will be associated with. i.e. sprite.animations.play(key) - */ - key: string; - /** - * A frame based animation (as opposed to a bone based animation) - */ - type: string; - /** - * [description] - */ - frames: Phaser.Types.Animations.JSONAnimationFrame[]; - /** - * The frame rate of playback in frames per second (default 24 if duration is null) - */ - frameRate: integer; - /** - * How long the animation should play for in milliseconds. If not given its derived from frameRate. - */ - duration: integer; - /** - * Skip frames if the time lags, or always advanced anyway? - */ - skipMissedFrames: boolean; - /** - * Delay before starting playback. Value given in milliseconds. - */ - delay: integer; - /** - * Number of times to repeat the animation (-1 for infinity) - */ - repeat: integer; - /** - * Delay before the animation repeats. Value given in milliseconds. - */ - repeatDelay: integer; - /** - * Should the animation yoyo? (reverse back down to the start) before repeating? - */ - yoyo: boolean; - /** - * Should sprite.visible = true when the animation starts to play? - */ - showOnStart: boolean; - /** - * Should sprite.visible = false when the animation finishes? - */ - hideOnComplete: boolean; - }; - - type JSONAnimationFrame = { - /** - * The key of the Texture this AnimationFrame uses. - */ - key: string; - /** - * The key of the Frame within the Texture that this AnimationFrame uses. - */ - frame: string | integer; - /** - * Additional time (in ms) that this frame should appear for during playback. - */ - duration: number; - }; - - type JSONAnimations = { - /** - * An array of all Animations added to the Animation Manager. - */ - anims: Phaser.Types.Animations.JSONAnimation[]; - /** - * The global time scale of the Animation Manager. - */ - globalTimeScale: number; - }; - - } - - namespace Cameras { - namespace Scene2D { - type CameraConfig = { - /** - * The name of the Camera. - */ - name?: string; - /** - * The horizontal position of the Camera viewport. - */ - x?: integer; - /** - * The vertical position of the Camera viewport. - */ - y?: integer; - /** - * The width of the Camera viewport. - */ - width?: integer; - /** - * The height of the Camera viewport. - */ - height?: integer; - /** - * The default zoom level of the Camera. - */ - zoom?: number; - /** - * The rotation of the Camera, in radians. - */ - rotation?: number; - /** - * Should the Camera round pixels before rendering? - */ - roundPixels?: boolean; - /** - * The horizontal scroll position of the Camera. - */ - scrollX?: number; - /** - * The vertical scroll position of the Camera. - */ - scrollY?: number; - /** - * A CSS color string controlling the Camera background color. - */ - backgroundColor?: false | string; - /** - * Defines the Camera bounds. - */ - bounds?: object; - /** - * The top-left extent of the Camera bounds. - */ - "bounds.x"?: number; - /** - * The top-left extent of the Camera bounds. - */ - "bounds.y"?: number; - /** - * The width of the Camera bounds. - */ - "bounds.width"?: number; - /** - * The height of the Camera bounds. - */ - "bounds.height"?: number; - }; - - type CameraFadeCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number)=>void; - - type CameraFlashCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number)=>void; - - type CameraPanCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number, x: number, y: number)=>void; - - type CameraShakeCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number)=>void; - - type CameraZoomCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number, zoom: number)=>void; - - type JSONCamera = { - /** - * The name of the camera - */ - name: string; - /** - * The horizontal position of camera - */ - x: number; - /** - * The vertical position of camera - */ - y: number; - /** - * The width size of camera - */ - width: number; - /** - * The height size of camera - */ - height: number; - /** - * The zoom of camera - */ - zoom: number; - /** - * The rotation of camera - */ - rotation: number; - /** - * The round pixels st status of camera - */ - roundPixels: boolean; - /** - * The horizontal scroll of camera - */ - scrollX: number; - /** - * The vertical scroll of camera - */ - scrollY: number; - /** - * The background color of camera - */ - backgroundColor: string; - /** - * The bounds of camera - */ - bounds?: Phaser.Types.Cameras.Scene2D.JSONCameraBounds | undefined; - }; - - type JSONCameraBounds = { - /** - * The horizontal position of camera - */ - x: number; - /** - * The vertical position of camera - */ - y: number; - /** - * The width size of camera - */ - width: number; - /** - * The height size of camera - */ - height: number; - }; - - } - - namespace Controls { - type FixedKeyControlConfig = { - /** - * The Camera that this Control will update. - */ - camera?: Phaser.Cameras.Scene2D.Camera; - /** - * The Key to be pressed that will move the Camera left. - */ - left?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will move the Camera right. - */ - right?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will move the Camera up. - */ - up?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will move the Camera down. - */ - down?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will zoom the Camera in. - */ - zoomIn?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will zoom the Camera out. - */ - zoomOut?: Phaser.Input.Keyboard.Key; - /** - * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. - */ - zoomSpeed?: number; - /** - * The horizontal and vertical speed the camera will move. - */ - speed?: number | Object; - }; - - type SmoothedKeyControlConfig = { - /** - * The Camera that this Control will update. - */ - camera?: Phaser.Cameras.Scene2D.Camera; - /** - * The Key to be pressed that will move the Camera left. - */ - left?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will move the Camera right. - */ - right?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will move the Camera up. - */ - up?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will zoom the Camera in. - */ - zoomIn?: Phaser.Input.Keyboard.Key; - /** - * The Key to be pressed that will zoom the Camera out. - */ - zoomOut?: Phaser.Input.Keyboard.Key; - /** - * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. - */ - zoomSpeed?: number; - /** - * The horizontal and vertical acceleration the camera will move. - */ - acceleration?: number | Object; - /** - * The horizontal and vertical drag applied to the camera when it is moving. - */ - drag?: number | Object; - /** - * The maximum horizontal and vertical speed the camera will move. - */ - maxSpeed?: number | Object; - }; - - } - - } - - namespace Core { - /** - * Config object containing various sound settings. - */ - type AudioConfig = { - /** - * Use HTML5 Audio instead of Web Audio. - */ - disableWebAudio?: boolean; - /** - * An existing Web Audio context. - */ - context?: AudioContext; - /** - * Disable all audio output. - */ - noAudio?: boolean; - }; - - type BannerConfig = { - /** - * Omit Phaser's name and version from the banner. - */ - hidePhaser?: boolean; - /** - * The color of the banner text. - */ - text?: string; - /** - * The background colors of the banner. - */ - background?: string[]; - }; - - type BootCallback = (game: Phaser.Game)=>void; - - type CallbacksConfig = { - /** - * A function to run at the start of the boot sequence. - */ - preBoot?: Phaser.Types.Core.BootCallback; - /** - * A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. - */ - postBoot?: Phaser.Types.Core.BootCallback; - }; - - type DOMContainerConfig = { - /** - * Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. - */ - createContainer?: boolean; - /** - * Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? - */ - behindCanvas?: boolean; - }; - - type FPSConfig = { - /** - * The minimum acceptable rendering rate, in frames per second. - */ - min?: integer; - /** - * The optimum rendering rate, in frames per second. - */ - target?: integer; - /** - * Use setTimeout instead of requestAnimationFrame to run the game loop. - */ - forceSetTimeOut?: boolean; - /** - * Calculate the average frame delta from this many consecutive frame intervals. - */ - deltaHistory?: integer; - /** - * The amount of frames the time step counts before we trust the delta values again. - */ - panicMax?: integer; - /** - * Apply delta smoothing during the game update to help avoid spikes? - */ - smoothStep?: boolean; - }; - - type GameConfig = { - /** - * The width of the game, in game pixels. - */ - width?: integer | string; - /** - * The height of the game, in game pixels. - */ - height?: integer | string; - /** - * Simple scale applied to the game canvas. 2 is double size, 0.5 is half size, etc. - */ - zoom?: number; - /** - * The size of each game pixel, in canvas pixels. Values larger than 1 are "high" resolution. - */ - resolution?: number; - /** - * Which renderer to use. Phaser.AUTO, Phaser.CANVAS, Phaser.HEADLESS, or Phaser.WEBGL. AUTO picks WEBGL if available, otherwise CANVAS. - */ - type?: number; - /** - * The DOM element that will contain the game canvas, or its `id`. If undefined or if the named element doesn't exist, the game canvas is inserted directly into the document body. If `null` no parent will be used and you are responsible for adding the canvas to your environment. - */ - parent?: HTMLElement | string; - /** - * Provide your own Canvas element for Phaser to use instead of creating one. - */ - canvas?: HTMLCanvasElement; - /** - * CSS styles to apply to the game canvas instead of Phasers default styles. - */ - canvasStyle?: string; - /** - * Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. - */ - customEnvironment?: boolean; - /** - * Provide your own Canvas Context for Phaser to use, instead of creating one. - */ - context?: CanvasRenderingContext2D; - /** - * A scene or scenes to add to the game. If several are given, the first is started; the remainder are started only if they have `{ active: true }`. See the `sceneConfig` argument in `Phaser.Scenes.SceneManager#add`. - */ - scene?: Phaser.Scene | Phaser.Scene[] | Phaser.Types.Scenes.SettingsConfig | Phaser.Types.Scenes.SettingsConfig[] | Phaser.Types.Scenes.CreateSceneFromObjectConfig | Phaser.Types.Scenes.CreateSceneFromObjectConfig[] | Function | Function[]; - /** - * Seed for the random number generator. - */ - seed?: string[]; - /** - * The title of the game. Shown in the browser console. - */ - title?: string; - /** - * The URL of the game. Shown in the browser console. - */ - url?: string; - /** - * The version of the game. Shown in the browser console. - */ - version?: string; - /** - * Automatically call window.focus() when the game boots. Usually necessary to capture input events if the game is in a separate frame. - */ - autoFocus?: boolean; - /** - * Input configuration, or `false` to disable all game input. - */ - input?: boolean | Phaser.Types.Core.InputConfig; - /** - * Disable the browser's default 'contextmenu' event (usually triggered by a right-button mouse click). - */ - disableContextMenu?: boolean; - /** - * Whether the game canvas will have a transparent background. - */ - transparent?: boolean; - /** - * Configuration for the banner printed in the browser console when the game starts. - */ - banner?: boolean | Phaser.Types.Core.BannerConfig; - /** - * The DOM Container configuration object. - */ - dom?: Phaser.Types.Core.DOMContainerConfig; - /** - * Game loop configuration. - */ - fps?: Phaser.Types.Core.FPSConfig; - /** - * Game renderer configuration. - */ - render?: Phaser.Types.Core.RenderConfig; - /** - * The background color of the game canvas. The default is black. - */ - backgroundColor?: string | number; - /** - * Optional callbacks to run before or after game boot. - */ - callbacks?: Phaser.Types.Core.CallbacksConfig; - /** - * Loader configuration. - */ - loader?: Phaser.Types.Core.LoaderConfig; - /** - * Images configuration. - */ - images?: Phaser.Types.Core.ImagesConfig; - /** - * Physics configuration. - */ - physics?: Phaser.Types.Core.PhysicsConfig; - /** - * Plugins to install. - */ - plugins?: Phaser.Types.Core.PluginObject | Phaser.Types.Core.PluginObjectItem[]; - /** - * The Scale Manager configuration. - */ - scale?: Phaser.Types.Core.ScaleConfig; - /** - * The Audio Configuration object. - */ - audio?: Phaser.Types.Core.AudioConfig; - }; - - type GamepadInputConfig = { - /** - * Where the Gamepad Manager listens for gamepad input events. - */ - target?: any; - }; - - type ImagesConfig = { - /** - * URL to use for the 'default' texture. - */ - default?: string; - /** - * URL to use for the 'missing' texture. - */ - missing?: string; - }; - - type InputConfig = { - /** - * Keyboard input configuration. `true` uses the default configuration and `false` disables keyboard input. - */ - keyboard?: boolean | Phaser.Types.Core.KeyboardInputConfig; - /** - * Mouse input configuration. `true` uses the default configuration and `false` disables mouse input. - */ - mouse?: boolean | Phaser.Types.Core.MouseInputConfig; - /** - * Touch input configuration. `true` uses the default configuration and `false` disables touch input. - */ - touch?: boolean | Phaser.Types.Core.TouchInputConfig; - /** - * Gamepad input configuration. `true` enables gamepad input. - */ - gamepad?: boolean | Phaser.Types.Core.GamepadInputConfig; - /** - * The maximum number of touch pointers. See {@link Phaser.Input.InputManager#pointers}. - */ - activePointers?: integer; - /** - * The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. - */ - smoothFactor?: number; - /** - * Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. - */ - windowEvents?: boolean; - }; - - type KeyboardInputConfig = { - /** - * Where the Keyboard Manager listens for keyboard input events. - */ - target?: any; - /** - * `preventDefault` will be called on every non-modified key which has a key code in this array. By default it is empty. - */ - capture?: integer[]; - }; - - type LoaderConfig = { - /** - * A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. - */ - baseURL?: string; - /** - * A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. - */ - path?: string; - /** - * The maximum number of resources the loader will start loading at once. - */ - maxParallelDownloads?: integer; - /** - * '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}. - */ - crossOrigin?: string | undefined; - /** - * The response type of the XHR request, e.g. `blob`, `text`, etc. - */ - responseType?: string; - /** - * Should the XHR request use async or not? - */ - async?: boolean; - /** - * Optional username for all XHR requests. - */ - user?: string; - /** - * Optional password for all XHR requests. - */ - password?: string; - /** - * Optional XHR timeout value, in ms. - */ - timeout?: integer; - }; - - type MouseInputConfig = { - /** - * Where the Mouse Manager listens for mouse input events. The default is the game canvas. - */ - target?: any; - /** - * Whether mouse input events have `preventDefault` called on them. - */ - capture?: boolean; - }; - - /** - * This callback type is completely empty, a no-operation. - */ - type NOOP = ()=>void; - - type PhysicsConfig = { - /** - * The default physics system. It will be started for each scene. Phaser provides 'arcade', 'impact', and 'matter'. - */ - default?: string; - /** - * Arcade Physics configuration. - */ - arcade?: Phaser.Types.Physics.Arcade.ArcadeWorldConfig; - /** - * Impact Physics configuration. - */ - impact?: Phaser.Types.Physics.Impact.WorldConfig; - /** - * Matter Physics configuration. - */ - matter?: Phaser.Types.Physics.Matter.MatterWorldConfig; - }; - - type PluginObject = { - /** - * Global plugins to install. - */ - global?: Phaser.Types.Core.PluginObjectItem[]; - /** - * Scene plugins to install. - */ - scene?: Phaser.Types.Core.PluginObjectItem[]; - /** - * The default set of scene plugins (names). - */ - default?: string[]; - /** - * Plugins to *add* to the default set of scene plugins. - */ - defaultMerge?: string[]; - }; - - type PluginObjectItem = { - /** - * A key to identify the plugin in the Plugin Manager. - */ - key?: string; - /** - * The plugin itself. Usually a class/constructor. - */ - plugin?: any; - /** - * Whether the plugin should be started automatically. - */ - start?: boolean; - /** - * For a scene plugin, add the plugin to the scene's systems object under this key (`this.sys.KEY`, from the scene). - */ - systemKey?: string; - /** - * For a scene plugin, add the plugin to the scene object under this key (`this.KEY`, from the scene). - */ - sceneKey?: string; - /** - * If this plugin is to be injected into the Scene Systems, this is the property key map used. - */ - mapping?: string; - /** - * Arbitrary data passed to the plugin's init() method. - */ - data?: any; - }; - - type RenderConfig = { - /** - * When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. - */ - antialias?: boolean; - /** - * Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. - */ - antialiasGL?: boolean; - /** - * 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. - */ - desynchronized?: boolean; - /** - * Sets `antialias` and `roundPixels` to true. This is the best setting for pixel-art games. - */ - pixelArt?: boolean; - /** - * Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. - */ - roundPixels?: boolean; - /** - * Whether the game canvas will be transparent. Boolean that indicates if the canvas contains an alpha channel. If set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images. - */ - transparent?: boolean; - /** - * Whether the game canvas will be cleared between each rendering frame. - */ - clearBeforeRender?: boolean; - /** - * In WebGL mode, the drawing buffer contains colors with pre-multiplied alpha. - */ - premultipliedAlpha?: boolean; - /** - * Let the browser abort creating a WebGL context if it judges performance would be unacceptable. - */ - failIfMajorPerformanceCaveat?: boolean; - /** - * "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. - */ - powerPreference?: string; - /** - * The default WebGL batch size. - */ - batchSize?: integer; - /** - * The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. - */ - maxLights?: integer; - /** - * The mipmap magFilter to be used when creating WebGL textures. - */ - mipmapFilter?: string; - }; - - type ScaleConfig = { - /** - * The base width of your game. Can be an integer or a string: '100%'. If a string it will only work if you have set a parent element that has a size. - */ - width?: integer | string; - /** - * The base height of your game. Can be an integer or a string: '100%'. If a string it will only work if you have set a parent element that has a size. - */ - height?: integer | string; - /** - * The zoom value of the game canvas. - */ - zoom?: Phaser.Scale.ZoomType | integer; - /** - * The rendering resolution of the canvas. This is reserved for future use and is currently ignored. - */ - resolution?: number; - /** - * The DOM element that will contain the game canvas, or its `id`. If undefined, or if the named element doesn't exist, the game canvas is inserted directly into the document body. If `null` no parent will be used and you are responsible for adding the canvas to your environment. - */ - parent?: HTMLElement | string; - /** - * Is the Scale Manager allowed to adjust the CSS height property of the parent and/or document body to be 100%? - */ - expandParent?: boolean; - /** - * The scale mode. - */ - mode?: Phaser.Scale.ScaleModeType; - /** - * The minimum width and height the canvas can be scaled down to. - */ - min?: WidthHeight; - /** - * The maximum width the canvas can be scaled up to. - */ - max?: WidthHeight; - /** - * Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. - */ - autoRound?: boolean; - /** - * Automatically center the canvas within the parent? - */ - autoCenter?: Phaser.Scale.CenterType; - /** - * How many ms should elapse before checking if the browser size has changed? - */ - resizeInterval?: integer; - /** - * The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. - */ - fullscreenTarget?: HTMLElement | string; - }; - - type TimeStepCallback = (time: number, average: number, interpolation: number)=>void; - - type TouchInputConfig = { - /** - * Where the Touch Manager listens for touch input events. The default is the game canvas. - */ - target?: any; - /** - * Whether touch input events have preventDefault() called on them. - */ - capture?: boolean; - }; - - type WidthHeight = { - /** - * The width. - */ - width?: integer; - /** - * The height. - */ - height?: integer; - }; - - } - - namespace Create { - type GenerateTextureCallback = (canvas: HTMLCanvasElement, context: CanvasRenderingContext2D)=>void; - - type GenerateTextureConfig = { - /** - * [description] - */ - data?: any[]; - /** - * [description] - */ - canvas?: HTMLCanvasElement; - /** - * [description] - */ - palette?: Phaser.Types.Create.Palette; - /** - * The width of each 'pixel' in the generated texture. - */ - pixelWidth?: number; - /** - * The height of each 'pixel' in the generated texture. - */ - pixelHeight?: number; - /** - * [description] - */ - resizeCanvas?: boolean; - /** - * [description] - */ - clearCanvas?: boolean; - /** - * [description] - */ - preRender?: Phaser.Types.Create.GenerateTextureCallback; - /** - * [description] - */ - postRender?: Phaser.Types.Create.GenerateTextureCallback; - }; - - type Palette = { - /** - * Color value 1. - */ - "0": string; - /** - * Color value 2. - */ - "1": string; - /** - * Color value 3. - */ - "2": string; - /** - * Color value 4. - */ - "3": string; - /** - * Color value 5. - */ - "4": string; - /** - * Color value 6. - */ - "5": string; - /** - * Color value 7. - */ - "6": string; - /** - * Color value 8. - */ - "7": string; - /** - * Color value 9. - */ - "8": string; - /** - * Color value 10. - */ - "9": string; - /** - * Color value 11. - */ - A: string; - /** - * Color value 12. - */ - B: string; - /** - * Color value 13. - */ - C: string; - /** - * Color value 14. - */ - D: string; - /** - * Color value 15. - */ - E: string; - /** - * Color value 16. - */ - F: string; - }; - - } - - namespace Curves { - type EllipseCurveConfig = { - /** - * The x coordinate of the ellipse. - */ - x?: number; - /** - * The y coordinate of the ellipse. - */ - y?: number; - /** - * The horizontal radius of the ellipse. - */ - xRadius?: number; - /** - * The vertical radius of the ellipse. - */ - yRadius?: number; - /** - * The start angle of the ellipse, in degrees. - */ - startAngle?: integer; - /** - * The end angle of the ellipse, in degrees. - */ - endAngle?: integer; - /** - * Sets if the the ellipse rotation is clockwise (true) or anti-clockwise (false) - */ - clockwise?: boolean; - /** - * The rotation of the ellipse, in degrees. - */ - rotation?: integer; - }; - - type JSONCurve = { - /** - * The of the curve - */ - type: string; - /** - * The arrays of points like `[x1, y1, x2, y2]` - */ - points: number[]; - }; - - type JSONEllipseCurve = { - /** - * The of the curve. - */ - type: string; - /** - * The x coordinate of the ellipse. - */ - x: number; - /** - * The y coordinate of the ellipse. - */ - y: number; - /** - * The horizontal radius of ellipse. - */ - xRadius: number; - /** - * The vertical radius of ellipse. - */ - yRadius: number; - /** - * The start angle of the ellipse, in degrees. - */ - startAngle: integer; - /** - * The end angle of the ellipse, in degrees. - */ - endAngle: integer; - /** - * Sets if the the ellipse rotation is clockwise (true) or anti-clockwise (false) - */ - clockwise: boolean; - /** - * The rotation of ellipse, in degrees. - */ - rotation: integer; - }; - - type JSONPath = { - /** - * The of the curve. - */ - type: string; - /** - * The X coordinate of the curve's starting point. - */ - x: number; - /** - * The Y coordinate of the path's starting point. - */ - y: number; - /** - * The path is auto closed. - */ - autoClose: boolean; - /** - * The list of the curves - */ - curves: Phaser.Types.Curves.JSONCurve[]; - }; - - } - - namespace Display { - type ColorObject = { - /** - * The red color value in the range 0 to 255. - */ - r: number; - /** - * The green color value in the range 0 to 255. - */ - g: number; - /** - * The blue color value in the range 0 to 255. - */ - b: number; - /** - * The alpha color value in the range 0 to 255. - */ - a: number; - }; - - type HSVColorObject = { - /** - * The hue color value. A number between 0 and 1 - */ - h: number; - /** - * The saturation color value. A number between 0 and 1 - */ - s: number; - /** - * The lightness color value. A number between 0 and 1 - */ - v: number; - }; - - type InputColorObject = { - /** - * The red color value in the range 0 to 255. - */ - r?: number; - /** - * The green color value in the range 0 to 255. - */ - g?: number; - /** - * The blue color value in the range 0 to 255. - */ - b?: number; - /** - * The alpha color value in the range 0 to 255. - */ - a?: number; - }; - - } - - namespace GameObjects { - namespace BitmapText { - /** - * The font data for an individual character of a Bitmap Font. - * - * Describes the character's position, size, offset and kerning. - */ - type BitmapFontCharacterData = { - /** - * The x position of the character. - */ - x: number; - /** - * The y position of the character. - */ - y: number; - /** - * The width of the character. - */ - width: number; - /** - * The height of the character. - */ - height: number; - /** - * The center x position of the character. - */ - centerX: number; - /** - * The center y position of the character. - */ - centerY: number; - /** - * The x offset of the character. - */ - xOffset: number; - /** - * The y offset of the character. - */ - yOffset: number; - /** - * Extra data for the character. - */ - data: object; - /** - * Kerning values, keyed by character code. - */ - kerning: {[key: string]: number}; - }; - - /** - * Bitmap Font data that can be used by a BitmapText Game Object. - */ - type BitmapFontData = { - /** - * The name of the font. - */ - font: string; - /** - * The size of the font. - */ - size: number; - /** - * The line height of the font. - */ - lineHeight: number; - /** - * Whether this font is a retro font (monospace). - */ - retroFont: boolean; - /** - * The character data of the font, keyed by character code. Each character datum includes a position, size, offset and more. - */ - chars: {[key: number]: Phaser.Types.GameObjects.BitmapText.BitmapFontCharacterData}; - }; - - type BitmapTextConfig = Phaser.Types.GameObjects.GameObjectConfig & { - /** - * The key of the font to use from the BitmapFont cache. - */ - font?: string; - /** - * The string, or array of strings, to be set as the content of this Bitmap Text. - */ - text?: string; - /** - * The font size to set. - */ - size?: number | false; - }; - - type BitmapTextSize = { - /** - * The position and size of the BitmapText, taking into account the position and scale of the Game Object. - */ - global: Phaser.Types.GameObjects.BitmapText.GlobalBitmapTextSize; - /** - * The position and size of the BitmapText, taking just the font size into account. - */ - local: Phaser.Types.GameObjects.BitmapText.LocalBitmapTextSize; - }; - - type DisplayCallbackConfig = { - /** - * The Dynamic Bitmap Text object that owns this character being rendered. - */ - parent: Phaser.GameObjects.DynamicBitmapText; - /** - * The tint of the character being rendered. Always zero in Canvas. - */ - tint: Phaser.Types.GameObjects.BitmapText.TintConfig; - /** - * The index of the character being rendered. - */ - index: number; - /** - * The character code of the character being rendered. - */ - charCode: number; - /** - * The x position of the character being rendered. - */ - x: number; - /** - * The y position of the character being rendered. - */ - y: number; - /** - * The scale of the character being rendered. - */ - scale: number; - /** - * The rotation of the character being rendered. - */ - rotation: number; - /** - * Custom data stored with the character being rendered. - */ - data: any; - }; - - type DisplayCallback = (display: Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig)=>void; - - /** - * The position and size of the Bitmap Text in global space, taking into account the Game Object's scale and world position. - */ - type GlobalBitmapTextSize = { - /** - * The x position of the BitmapText, taking into account the x position and scale of the Game Object. - */ - x: number; - /** - * The y position of the BitmapText, taking into account the y position and scale of the Game Object. - */ - y: number; - /** - * The width of the BitmapText, taking into account the x scale of the Game Object. - */ - width: number; - /** - * The height of the BitmapText, taking into account the y scale of the Game Object. - */ - height: number; - }; - - type JSONBitmapText = Phaser.Types.GameObjects.JSONGameObject & { - /** - * The name of the font. - */ - font: string; - /** - * The text that this Bitmap Text displays. - */ - text: string; - /** - * The size of the font. - */ - fontSize: number; - /** - * Adds / Removes spacing between characters. - */ - letterSpacing: number; - /** - * The alignment of the text in a multi-line BitmapText object. - */ - align: integer; - }; - - /** - * The position and size of the Bitmap Text in local space, taking just the font size into account. - */ - type LocalBitmapTextSize = { - /** - * The x position of the BitmapText. - */ - x: number; - /** - * The y position of the BitmapText. - */ - y: number; - /** - * The width of the BitmapText. - */ - width: number; - /** - * The height of the BitmapText. - */ - height: number; - }; - - type RetroFontConfig = { - /** - * The key of the image containing the font. - */ - image: string; - /** - * If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. - */ - "offset.x": number; - /** - * If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. - */ - "offset.y": number; - /** - * The width of each character in the font set. - */ - width: number; - /** - * The height of each character in the font set. - */ - height: number; - /** - * The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. - */ - chars: string; - /** - * The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. - */ - charsPerRow: number; - /** - * If the characters in the font set have horizontal spacing between them set the required amount here. - */ - "spacing.x": number; - /** - * If the characters in the font set have vertical spacing between them set the required amount here. - */ - "spacing.y": number; - /** - * The amount of vertical space to add to the line height of the font. - */ - lineSpacing: number; - }; - - type TintConfig = { - /** - * The top left tint value. Always zero in canvas. - */ - topLeft: number; - /** - * The top right tint value. Always zero in canvas. - */ - topRight: number; - /** - * The bottom left tint value. Always zero in canvas. - */ - bottomLeft: number; - /** - * The bottom right tint value. Always zero in canvas. - */ - bottomRight: number; - }; - - } - - namespace Graphics { - /** - * Graphics fill style settings. - */ - type FillStyle = { - /** - * The fill color. - */ - color?: number; - /** - * The fill alpha. - */ - alpha?: number; - }; - - /** - * Graphics line style (or stroke style) settings. - */ - type LineStyle = { - /** - * The stroke width. - */ - width?: number; - /** - * The stroke color. - */ - color?: number; - /** - * The stroke alpha. - */ - alpha?: number; - }; - - /** - * Options for the Graphics game Object. - */ - type Options = Phaser.Types.GameObjects.Graphics.Styles & { - /** - * The x coordinate of the Graphics. - */ - x?: number; - /** - * The y coordinate of the Graphics. - */ - y?: number; - }; - - type RoundedRectRadius = { - /** - * Top left - */ - tl?: number; - /** - * Top right - */ - tr?: number; - /** - * Bottom right - */ - br?: number; - /** - * Bottom left - */ - bl?: number; - }; - - /** - * Graphics style settings. - */ - type Styles = { - /** - * The style applied to shape outlines. - */ - lineStyle?: Phaser.Types.GameObjects.Graphics.LineStyle; - /** - * The style applied to shape areas. - */ - fillStyle?: Phaser.Types.GameObjects.Graphics.FillStyle; - }; - - } - - namespace Group { - type GroupCallback = (item: Phaser.GameObjects.GameObject)=>void; - - type GroupConfig = { - /** - * Sets {@link Phaser.GameObjects.Group#classType}. - */ - classType?: Function; - /** - * Sets {@link Phaser.GameObjects.Group#name}. - */ - name?: string; - /** - * Sets {@link Phaser.GameObjects.Group#active}. - */ - active?: boolean; - /** - * Sets {@link Phaser.GameObjects.Group#maxSize}. - */ - maxSize?: number; - /** - * Sets {@link Phaser.GameObjects.Group#defaultKey}. - */ - defaultKey?: string; - /** - * Sets {@link Phaser.GameObjects.Group#defaultFrame}. - */ - defaultFrame?: string | integer; - /** - * Sets {@link Phaser.GameObjects.Group#runChildUpdate}. - */ - runChildUpdate?: boolean; - /** - * Sets {@link Phaser.GameObjects.Group#createCallback}. - */ - createCallback?: Phaser.Types.GameObjects.Group.GroupCallback; - /** - * Sets {@link Phaser.GameObjects.Group#removeCallback}. - */ - removeCallback?: Phaser.Types.GameObjects.Group.GroupCallback; - /** - * Sets {@link Phaser.GameObjects.Group#createMultipleCallback}. - */ - createMultipleCallback?: Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback; - }; - - /** - * The total number of objects created will be - * - * key.length * frame.length * frameQuantity * (yoyo ? 2 : 1) * (1 + repeat) - * - * If `max` is nonzero, then the total created will not exceed `max`. - * - * `key` is required. {@link Phaser.GameObjects.Group#defaultKey} is not used. - */ - type GroupCreateConfig = { - /** - * The class of each new Game Object. - */ - classType?: Function; - /** - * The texture key of each new Game Object. - */ - key?: string | string[]; - /** - * The texture frame of each new Game Object. - */ - frame?: string | string[] | integer | integer[]; - /** - * The number of Game Objects to create. If set, this overrides the `frameQuantity` value. Use `frameQuantity` for more advanced control. - */ - quantity?: integer; - /** - * The visible state of each new Game Object. - */ - visible?: boolean; - /** - * The active state of each new Game Object. - */ - active?: boolean; - /** - * The number of times each `key` × `frame` combination will be *repeated* (after the first combination). - */ - repeat?: integer; - /** - * Select a `key` at random. - */ - randomKey?: boolean; - /** - * Select a `frame` at random. - */ - randomFrame?: boolean; - /** - * Select keys and frames by moving forward then backward through `key` and `frame`. - */ - yoyo?: boolean; - /** - * The number of times each `frame` should be combined with one `key`. - */ - frameQuantity?: integer; - /** - * The maximum number of new Game Objects to create. 0 is no maximum. - */ - max?: integer; - setXY?: object; - /** - * The horizontal position of each new Game Object. - */ - "setXY.x"?: number; - /** - * The vertical position of each new Game Object. - */ - "setXY.y"?: number; - /** - * Increment each Game Object's horizontal position from the previous by this amount, starting from `setXY.x`. - */ - "setXY.stepX"?: number; - /** - * Increment each Game Object's vertical position from the previous by this amount, starting from `setXY.y`. - */ - "setXY.stepY"?: number; - setRotation?: object; - /** - * Rotation of each new Game Object. - */ - "setRotation.value"?: number; - /** - * Increment each Game Object's rotation from the previous by this amount, starting at `setRotation.value`. - */ - "setRotation.step"?: number; - setScale?: object; - /** - * The horizontal scale of each new Game Object. - */ - "setScale.x"?: number; - /** - * The vertical scale of each new Game Object. - */ - "setScale.y"?: number; - /** - * Increment each Game Object's horizontal scale from the previous by this amount, starting from `setScale.x`. - */ - "setScale.stepX"?: number; - /** - * Increment each Game object's vertical scale from the previous by this amount, starting from `setScale.y`. - */ - "setScale.stepY"?: number; - setAlpha?: object; - /** - * The alpha value of each new Game Object. - */ - "setAlpha.value"?: number; - /** - * Increment each Game Object's alpha from the previous by this amount, starting from `setAlpha.value`. - */ - "setAlpha.step"?: number; - setDepth?: object; - /** - * The depth value of each new Game Object. - */ - "setDepth.value"?: number; - /** - * Increment each Game Object's depth from the previous by this amount, starting from `setDepth.value`. - */ - "setDepth.step"?: number; - setScrollFactor?: object; - /** - * The horizontal scroll factor of each new Game Object. - */ - "setScrollFactor.x"?: number; - /** - * The vertical scroll factor of each new Game Object. - */ - "setScrollFactor.y"?: number; - /** - * Increment each Game Object's horizontal scroll factor from the previous by this amount, starting from `setScrollFactor.x`. - */ - "setScrollFactor.stepX"?: number; - /** - * Increment each Game object's vertical scroll factor from the previous by this amount, starting from `setScrollFactor.y`. - */ - "setScrollFactor.stepY"?: number; - /** - * A geometric shape that defines the hit area for the Game Object. - */ - hitArea?: any; - /** - * A callback to be invoked when the Game Object is interacted with. - */ - hitAreaCallback?: Phaser.Types.Input.HitAreaCallback; - /** - * Align the new Game Objects in a grid using these settings. - */ - gridAlign?: false | Phaser.Types.Actions.GridAlignConfig; - }; - - type GroupMultipleCreateCallback = (items: Phaser.GameObjects.GameObject[])=>void; - - } - - namespace Particles { - type DeathZoneSource = { - contains: Phaser.Types.GameObjects.Particles.DeathZoneSourceCallback; - }; - - type DeathZoneSourceCallback = (x: number, y: number)=>void; - - type EdgeZoneSource = { - /** - * A function placing points on the sources edge or edges. - */ - getPoints: Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback; - }; - - type EdgeZoneSourceCallback = (quantity: integer, stepRate?: number)=>void; - - type EmitterOpCustomEmitConfig = { - /** - * A callback that is invoked each time the emitter emits a particle. - */ - onEmit: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback; - }; - - type EmitterOpCustomUpdateConfig = { - /** - * A callback that is invoked each time the emitter emits a particle. - */ - onEmit?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback; - /** - * A callback that is invoked each time the emitter updates. - */ - onUpdate: Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback; - }; - - /** - * Defines an operation yielding a value incremented continuously across a range. - */ - type EmitterOpEaseConfig = { - /** - * The starting value. - */ - start: number; - /** - * The ending value. - */ - end: number; - /** - * The name of the easing function. - */ - ease?: string; - }; - - /** - * The returned value sets what the property will be at the START of the particle's life, on emit. - */ - type EmitterOpOnEmitCallback = (particle: Phaser.GameObjects.Particles.Particle, key: string, value: number)=>void; - - type EmitterOpOnEmitType = number | number[] | Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback | Phaser.Types.GameObjects.Particles.EmitterOpRandomConfig | Phaser.Types.GameObjects.Particles.EmitterOpRandomMinMaxConfig | Phaser.Types.GameObjects.Particles.EmitterOpRandomStartEndConfig | Phaser.Types.GameObjects.Particles.EmitterOpSteppedConfig | Phaser.Types.GameObjects.Particles.EmitterOpCustomEmitConfig; - - /** - * The returned value updates the property for the duration of the particle's life. - */ - type EmitterOpOnUpdateCallback = (particle: Phaser.GameObjects.Particles.Particle, key: string, t: number, value: number)=>void; - - type EmitterOpOnUpdateType = Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback | Phaser.Types.GameObjects.Particles.EmitterOpEaseConfig | Phaser.Types.GameObjects.Particles.EmitterOpCustomUpdateConfig; - - /** - * Defines an operation yielding a random value within a range. - */ - type EmitterOpRandomConfig = { - /** - * The minimum and maximum values, as [min, max]. - */ - random: number[]; - }; - - /** - * Defines an operation yielding a random value within a range. - */ - type EmitterOpRandomMinMaxConfig = { - /** - * The minimum value. - */ - min: number; - /** - * The maximum value. - */ - max: number; - }; - - /** - * Defines an operation yielding a random value within a range. - */ - type EmitterOpRandomStartEndConfig = { - /** - * The starting value. - */ - start: number; - /** - * The ending value. - */ - end: number; - /** - * If false, this becomes {@link EmitterOpEaseConfig}. - */ - random: boolean; - }; - - /** - * Defines an operation yielding a value incremented by steps across a range. - */ - type EmitterOpSteppedConfig = { - /** - * The starting value. - */ - start: number; - /** - * The ending value. - */ - end: number; - /** - * The number of steps between start and end. - */ - steps: number; - }; - - type GravityWellConfig = { - /** - * The x coordinate of the Gravity Well, in world space. - */ - x?: number; - /** - * The y coordinate of the Gravity Well, in world space. - */ - y?: number; - /** - * The strength of the gravity force - larger numbers produce a stronger force. - */ - power?: number; - /** - * The minimum distance for which the gravity force is calculated. - */ - epsilon?: number; - /** - * The gravitational force of this Gravity Well. - */ - gravity?: number; - }; - - type ParticleDeathCallback = (particle: Phaser.GameObjects.Particles.Particle)=>void; - - type ParticleEmitterBounds = { - /** - * The left edge of the rectangle. - */ - x: number; - /** - * The top edge of the rectangle. - */ - y: number; - /** - * The width of the rectangle. - */ - width: number; - /** - * The height of the rectangle. - */ - height: number; - }; - - type ParticleEmitterBoundsAlt = { - /** - * The left edge of the rectangle. - */ - x: number; - /** - * The top edge of the rectangle. - */ - y: number; - /** - * The width of the rectangle. - */ - w: number; - /** - * The height of the rectangle. - */ - h: number; - }; - - type ParticleEmitterCallback = (particle: Phaser.GameObjects.Particles.Particle, emitter: Phaser.GameObjects.Particles.ParticleEmitter)=>void; - - type ParticleEmitterConfig = { - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#active}. - */ - active?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#blendMode}. - */ - blendMode?: Phaser.BlendModes | string; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope} and {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope}. - */ - callbackScope?: any; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideBottom}. - */ - collideBottom?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideLeft}. - */ - collideLeft?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideRight}. - */ - collideRight?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideTop}. - */ - collideTop?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. - */ - deathCallback?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope}. - */ - deathCallbackScope?: any; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. - */ - emitCallback?: Function; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope}. - */ - emitCallbackScope?: any; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#follow}. - */ - follow?: Phaser.GameObjects.GameObject; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency}. - */ - frequency?: number; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#gravityX}. - */ - gravityX?: number; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#gravityY}. - */ - gravityY?: number; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#maxParticles}. - */ - maxParticles?: integer; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#name}. - */ - name?: string; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#on}. - */ - on?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#particleBringToTop}. - */ - particleBringToTop?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#particleClass}. - */ - particleClass?: Phaser.GameObjects.Particles.Particle; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#radial}. - */ - radial?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#timeScale}. - */ - timeScale?: number; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#trackVisible}. - */ - trackVisible?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#visible}. - */ - visible?: boolean; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#accelerationX} (emit only). - */ - accelerationX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#accelerationY} (emit only). - */ - accelerationY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#alpha}. - */ - alpha?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#angle} (emit only). - */ - angle?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#bounce} (emit only). - */ - bounce?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#delay} (emit only). - */ - delay?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#lifespan} (emit only). - */ - lifespan?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityX} (emit only). - */ - maxVelocityX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityY} (emit only). - */ - maxVelocityY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#moveToX} (emit only). - */ - moveToX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#moveToY} (emit only). - */ - moveToY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity} (emit only). - */ - quantity?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#rotate}. - */ - rotate?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; - /** - * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setScale}. - */ - scale?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#scaleX}. - */ - scaleX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#scaleY}. - */ - scaleY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; - /** - * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setSpeed} (emit only). - */ - speed?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#speedX} (emit only). - */ - speedX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#speedY} (emit only). - */ - speedY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#tint}. - */ - tint?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#x} (emit only). - */ - x?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#y} (emit only). - */ - y?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; - /** - * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone}. - */ - emitZone?: object; - /** - * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setBounds}. - */ - bounds?: Phaser.Types.GameObjects.Particles.ParticleEmitterBounds | Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt; - /** - * Assigns to {@link Phaser.GameObjects.Particles.ParticleEmitter#followOffset}. - */ - followOffset?: object; - /** - * x-coordinate of the offset. - */ - "followOffset.x"?: number; - /** - * y-coordinate of the offset. - */ - "followOffset.y"?: number; - /** - * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. - */ - frame?: number | number[] | string | string[] | Phaser.Textures.Frame | Phaser.Textures.Frame[] | Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig; - }; - - type ParticleEmitterDeathZoneConfig = { - /** - * A shape representing the zone. See {@link Phaser.GameObjects.Particles.Zones.DeathZone#source}. - */ - source: Phaser.Types.GameObjects.Particles.DeathZoneSource; - /** - * 'onEnter' or 'onLeave'. - */ - type?: string; - }; - - type ParticleEmitterEdgeZoneConfig = { - /** - * A shape representing the zone. See {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. - */ - source: Phaser.Types.GameObjects.Particles.EdgeZoneSource; - /** - * 'edge'. - */ - type: string; - /** - * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. - */ - quantity: integer; - /** - * The distance between each particle. When set, `quantity` is implied and should be set to 0. - */ - stepRate?: number; - /** - * Whether particles are placed from start to end and then end to start. - */ - yoyo?: boolean; - /** - * Whether one endpoint will be removed if it's identical to the other. - */ - seamless?: boolean; - }; - - type ParticleEmitterFrameConfig = { - /** - * One or more texture frames. - */ - frames?: number | number[] | string | string[] | Phaser.Textures.Frame | Phaser.Textures.Frame[]; - /** - * Whether texture frames will be assigned consecutively (true) or at random (false). - */ - cycle?: boolean; - /** - * The number of consecutive particles receiving each texture frame, when `cycle` is true. - */ - quantity?: integer; - }; - - type ParticleEmitterRandomZoneConfig = { - /** - * A shape representing the zone. See {@link Phaser.GameObjects.Particles.Zones.RandomZone#source}. - */ - source: Phaser.Types.GameObjects.Particles.RandomZoneSource; - /** - * 'random'. - */ - type?: string; - }; - - type RandomZoneSource = { - /** - * A function modifying its point argument. - */ - getRandomPoint: Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback; - }; - - type RandomZoneSourceCallback = (point: Phaser.Math.Vector2)=>void; - - } - - namespace PathFollower { - /** - * Settings for a PathFollower. - */ - type PathConfig = { - /** - * The duration of the path follow in ms. Must be `> 0`. - */ - duration?: number; - /** - * The start position of the path follow, between 0 and 1. Must be less than `to`. - */ - from?: number; - /** - * The end position of the path follow, between 0 and 1. Must be more than `from`. - */ - to?: number; - /** - * Whether to position the PathFollower on the Path using its path offset. - */ - positionOnPath?: boolean; - /** - * Should the PathFollower automatically rotate to point in the direction of the Path? - */ - rotateToPath?: boolean; - /** - * If the PathFollower is rotating to match the Path, this value is added to the rotation value. This allows you to rotate objects to a path but control the angle of the rotation as well. - */ - rotationOffset?: number; - /** - * Current start position of the path follow, must be between `from` and `to`. - */ - startAt?: number; - }; - - } - - namespace RenderTexture { - type RenderTextureConfig = { - /** - * The x coordinate of the RenderTextures position. - */ - x?: number; - /** - * The y coordinate of the RenderTextures position. - */ - y?: number; - /** - * The width of the RenderTexture. - */ - width?: number; - /** - * The height of the RenderTexture. - */ - height?: number; - /** - * The texture key to make the RenderTexture from. - */ - key?: string; - /** - * the frame to make the RenderTexture from. - */ - frame?: string; - }; - - } - - namespace Sprite { - type SpriteConfig = Phaser.Types.GameObjects.GameObjectConfig & { - /** - * The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - */ - key?: string; - /** - * An optional frame from the Texture this Game Object is rendering with. - */ - frame?: number | string; - }; - - } - - namespace Text { - /** - * Font metrics for a Text Style object. - */ - type TextMetrics = { - /** - * The ascent of the font. - */ - ascent: number; - /** - * The descent of the font. - */ - descent: number; - /** - * The size of the font. - */ - fontSize: number; - }; - - /** - * A Text Padding configuration object as used by the Text Style. - */ - type TextPadding = { - /** - * If set this value is used for both the left and right padding. - */ - x?: number; - /** - * If set this value is used for both the top and bottom padding. - */ - y?: number; - /** - * The amount of padding added to the left of the Text object. - */ - left?: number; - /** - * The amount of padding added to the right of the Text object. - */ - right?: number; - /** - * The amount of padding added to the top of the Text object. - */ - top?: number; - /** - * The amount of padding added to the bottom of the Text object. - */ - bottom?: number; - }; - - /** - * A Text Shadow configuration object as used by the Text Style. - */ - type TextShadow = { - /** - * The horizontal offset of the shadow. - */ - offsetX?: number; - /** - * The vertical offset of the shadow. - */ - offsetY?: number; - /** - * The color of the shadow, given as a CSS string value. - */ - color?: string; - /** - * The amount of blur applied to the shadow. Leave as zero for a hard shadow. - */ - blur?: number; - /** - * Apply the shadow to the stroke effect on the Text object? - */ - stroke?: boolean; - /** - * Apply the shadow to the fill effect on the Text object? - */ - fill?: boolean; - }; - - /** - * A Text Style configuration object as used by the Text Game Object. - */ - type TextStyle = { - /** - * The font the Text object will render with. This is a Canvas style font string. - */ - fontFamily?: string; - /** - * The font size, as a CSS size string. - */ - fontSize?: string; - /** - * Any addition font styles, such as 'strong'. - */ - fontStyle?: string; - /** - * A solid fill color that is rendered behind the Text object. Given as a CSS string color such as `#ff0`. - */ - backgroundColor?: string; - /** - * The color the Text is drawn in. Given as a CSS string color such as `#fff` or `rgb()`. - */ - color?: string; - /** - * The color used to stroke the Text if the `strokeThickness` property is greater than zero. - */ - stroke?: string; - /** - * The thickness of the stroke around the Text. Set to zero for no stroke. - */ - strokeThickness?: number; - /** - * The Text shadow configuration object. - */ - shadow?: Phaser.Types.GameObjects.Text.TextShadow; - /** - * A Text Padding object. - */ - padding?: Phaser.Types.GameObjects.Text.TextPadding; - /** - * The alignment of the Text. This only impacts multi-line text. Either `left`, `right`, `center` or `justify`. - */ - align?: string; - /** - * The maximum number of lines to display within the Text object. - */ - maxLines?: integer; - /** - * Force the Text object to have the exact width specified in this property. Leave as zero for it to change accordingly to content. - */ - fixedWidth?: number; - /** - * Force the Text object to have the exact height specified in this property. Leave as zero for it to change accordingly to content. - */ - fixedHeight?: number; - /** - * Sets the resolution (DPI setting) of the Text object. Leave at zero for it to use the game resolution. - */ - resolution?: number; - /** - * Set to `true` if this Text object should render from right-to-left. - */ - rtl?: boolean; - /** - * This is the string used to aid Canvas in calculating the height of the font. - */ - testString?: string; - /** - * The amount of horizontal padding added to the width of the text when calculating the font metrics. - */ - baselineX?: number; - /** - * The amount of vertical padding added to the height of the text when calculating the font metrics. - */ - baselineY?: number; - /** - * The Text Word wrap configuration object. - */ - wordWrap?: Phaser.Types.GameObjects.Text.TextWordWrap; - /** - * A Text Metrics object. Use this to avoid expensive font size calculations in text heavy games. - */ - metrics?: Phaser.Types.GameObjects.Text.TextMetrics; - }; - - /** - * A Text Word Wrap configuration object as used by the Text Style configuration. - */ - type TextWordWrap = { - /** - * The width at which text should be considered for word-wrapping. - */ - width?: number; - /** - * Provide a custom callback when word wrapping is enabled. - */ - callback?: TextStyleWordWrapCallback; - /** - * The context in which the word wrap callback is invoked. - */ - callbackScope?: any; - /** - * Use basic or advanced word wrapping? - */ - useAdvancedWrap?: boolean; - }; - - } - - namespace TileSprite { - type TileSpriteConfig = Phaser.Types.GameObjects.GameObjectConfig & { - /** - * The x coordinate of the Tile Sprite. - */ - x?: number; - /** - * The y coordinate of the Tile Sprite. - */ - y?: number; - /** - * The width of the Tile Sprite. If zero it will use the size of the texture frame. - */ - width?: integer; - /** - * The height of the Tile Sprite. If zero it will use the size of the texture frame. - */ - height?: integer; - /** - * The key of the Texture this Tile Sprite will use to render with, as stored in the Texture Manager. - */ - key?: string; - /** - * An optional frame from the Texture this Tile Sprite is rendering with. - */ - frame?: string; - }; - - } - - type GameObjectConfig = { - /** - * The x position of the Game Object. - */ - x?: number; - /** - * The y position of the Game Object. - */ - y?: number; - /** - * The depth of the GameObject. - */ - depth?: number; - /** - * The horizontally flipped state of the Game Object. - */ - flipX?: boolean; - /** - * The vertically flipped state of the Game Object. - */ - flipY?: boolean; - /** - * The scale of the GameObject. - */ - scale?: number | object; - /** - * The scroll factor of the GameObject. - */ - scrollFactor?: number | object; - /** - * The rotation angle of the Game Object, in radians. - */ - rotation?: number; - /** - * The rotation angle of the Game Object, in degrees. - */ - angle?: number; - /** - * The alpha (opacity) of the Game Object. - */ - alpha?: number; - /** - * The origin of the Game Object. - */ - origin?: number | object; - /** - * The scale mode of the GameObject. - */ - scaleMode?: number; - /** - * The blend mode of the GameObject. - */ - blendMode?: number; - /** - * The visible state of the Game Object. - */ - visible?: boolean; - /** - * Add the GameObject to the scene. - */ - add?: boolean; - }; - - type JSONGameObject = { - /** - * The name of this Game Object. - */ - name: string; - /** - * A textual representation of this Game Object, i.e. `sprite`. - */ - type: string; - /** - * The x position of this Game Object. - */ - x: number; - /** - * The y position of this Game Object. - */ - y: number; - /** - * The scale of this Game Object - */ - scale: object; - /** - * The horizontal scale of this Game Object. - */ - "scale.x": number; - /** - * The vertical scale of this Game Object. - */ - "scale.y": number; - /** - * The origin of this Game Object. - */ - origin: object; - /** - * The horizontal origin of this Game Object. - */ - "origin.x": number; - /** - * The vertical origin of this Game Object. - */ - "origin.y": number; - /** - * The horizontally flipped state of the Game Object. - */ - flipX: boolean; - /** - * The vertically flipped state of the Game Object. - */ - flipY: boolean; - /** - * The angle of this Game Object in radians. - */ - rotation: number; - /** - * The alpha value of the Game Object. - */ - alpha: number; - /** - * The visible state of the Game Object. - */ - visible: boolean; - /** - * The Scale Mode being used by this Game Object. - */ - scaleMode: integer; - /** - * Sets the Blend Mode being used by this Game Object. - */ - blendMode: integer | string; - /** - * The texture key of this Game Object. - */ - textureKey: string; - /** - * The frame key of this Game Object. - */ - frameKey: string; - /** - * The data of this Game Object. - */ - data: object; - }; - - } - - namespace Input { - namespace Gamepad { - /** - * The Gamepad object, as extracted from GamepadEvent. - */ - type Pad = { - /** - * The ID of the Gamepad. - */ - id: string; - /** - * The index of the Gamepad. - */ - index: integer; - }; - - } - - namespace Keyboard { - type CursorKeys = { - /** - * A Key object mapping to the UP arrow key. - */ - up?: Phaser.Input.Keyboard.Key; - /** - * A Key object mapping to the DOWN arrow key. - */ - down?: Phaser.Input.Keyboard.Key; - /** - * A Key object mapping to the LEFT arrow key. - */ - left?: Phaser.Input.Keyboard.Key; - /** - * A Key object mapping to the RIGHT arrow key. - */ - right?: Phaser.Input.Keyboard.Key; - /** - * A Key object mapping to the SPACE BAR key. - */ - space?: Phaser.Input.Keyboard.Key; - /** - * A Key object mapping to the SHIFT key. - */ - shift?: Phaser.Input.Keyboard.Key; - }; - - type KeyboardKeydownCallback = (event: KeyboardEvent)=>void; - - type KeyComboConfig = { - /** - * If they press the wrong key do we reset the combo? - */ - resetOnWrongKey?: boolean; - /** - * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. - */ - maxKeyDelay?: number; - /** - * If previously matched and they press the first key of the combo again, will it reset? - */ - resetOnMatch?: boolean; - /** - * If the combo matches, will it delete itself? - */ - deleteOnMatch?: boolean; - }; - - } - - /** - * A Phaser Input Event Data object. - * - * This object is passed to the registered event listeners and allows you to stop any further propagation. - */ - type EventData = { - /** - * The cancelled state of this Event. - */ - cancelled?: boolean; - /** - * Call this method to stop this event from passing any further down the event chain. - */ - stopPropagation: Function; - }; - - type HitAreaCallback = (hitArea: any, x: number, y: number, gameObject: Phaser.GameObjects.GameObject)=>void; - - type InputConfiguration = { - /** - * The object / shape to use as the Hit Area. If not given it will try to create a Rectangle based on the texture frame. - */ - hitArea?: any; - /** - * The callback that determines if the pointer is within the Hit Area shape or not. - */ - hitAreaCallback?: Function; - /** - * If `true` the Interactive Object will be set to be draggable and emit drag events. - */ - draggable?: boolean; - /** - * If `true` the Interactive Object will be set to be a drop zone for draggable objects. - */ - dropZone?: boolean; - /** - * If `true` the Interactive Object will set the `pointer` hand cursor when a pointer is over it. This is a short-cut for setting `cursor: 'pointer'`. - */ - useHandCursor?: boolean; - /** - * The CSS string to be used when the cursor is over this Interactive Object. - */ - cursor?: string; - /** - * If `true` the a pixel perfect function will be set for the hit area callback. Only works with texture based Game Objects. - */ - pixelPerfect?: boolean; - /** - * If `pixelPerfect` is set, this is the alpha tolerance threshold value used in the callback. - */ - alphaTolerance?: integer; - }; - - type InputPluginContainer = { - /** - * The unique name of this plugin in the input plugin cache. - */ - key: string; - /** - * The plugin to be stored. Should be the source object, not instantiated. - */ - plugin: Function; - /** - * If this plugin is to be injected into the Input Plugin, this is the property key map used. - */ - mapping?: string; - }; - - type InteractiveObject = { - /** - * The Game Object to which this Interactive Object is bound. - */ - gameObject: Phaser.GameObjects.GameObject; - /** - * Is this Interactive Object currently enabled for input events? - */ - enabled: boolean; - /** - * An Interactive Object that is 'always enabled' will receive input even if the parent object is invisible or won't render. - */ - alwaysEnabled: boolean; - /** - * Is this Interactive Object draggable? Enable with `InputPlugin.setDraggable`. - */ - draggable: boolean; - /** - * Is this Interactive Object a drag-targets drop zone? Set when the object is created. - */ - dropZone: boolean; - /** - * Should this Interactive Object change the cursor (via css) when over? (desktop only) - */ - cursor: boolean | string; - /** - * An optional drop target for a draggable Interactive Object. - */ - target: Phaser.GameObjects.GameObject; - /** - * The most recent Camera to be tested against this Interactive Object. - */ - camera: Phaser.Cameras.Scene2D.Camera; - /** - * The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. - */ - hitArea: any; - /** - * The 'contains' check callback that the hit area shape will use for all hit tests. - */ - hitAreaCallback: Phaser.Types.Input.HitAreaCallback; - /** - * If this Interactive Object has been enabled for debug, via `InputPlugin.enableDebug` then this property holds its debug shape. - */ - hitAreaDebug: Phaser.GameObjects.Shape; - /** - * Was the hitArea for this Interactive Object created based on texture size (false), or a custom shape? (true) - */ - customHitArea: boolean; - /** - * The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - */ - localX: number; - /** - * The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. - */ - localY: number; - /** - * The current drag state of this Interactive Object. 0 = Not being dragged, 1 = being checked for drag, or 2 = being actively dragged. - */ - dragState: 0 | 1 | 2; - /** - * The x coordinate of the Game Object that owns this Interactive Object when the drag started. - */ - dragStartX: number; - /** - * The y coordinate of the Game Object that owns this Interactive Object when the drag started. - */ - dragStartY: number; - /** - * The x coordinate that the Pointer started dragging this Interactive Object from. - */ - dragStartXGlobal: number; - /** - * The y coordinate that the Pointer started dragging this Interactive Object from. - */ - dragStartYGlobal: number; - /** - * The x coordinate that this Interactive Object is currently being dragged to. - */ - dragX: number; - /** - * The y coordinate that this Interactive Object is currently being dragged to. - */ - dragY: number; - }; - - } - - namespace Loader { - namespace FileTypes { - type AtlasJSONFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the texture image file from. - */ - textureURL?: string; - /** - * The default file extension to use for the image texture if no url is provided. - */ - textureExtension?: string; - /** - * Extra XHR Settings specifically for the texture image file. - */ - textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The filename of an associated normal map. It uses the same path and url to load as the texture image. - */ - normalMap?: string; - /** - * The absolute or relative URL to load the atlas json file from. Or a well formed JSON object to use instead. - */ - atlasURL?: string; - /** - * The default file extension to use for the atlas json if no url is provided. - */ - atlasExtension?: string; - /** - * Extra XHR Settings specifically for the atlas json file. - */ - atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type AtlasXMLFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the texture image file from. - */ - textureURL?: string; - /** - * The default file extension to use for the image texture if no url is provided. - */ - textureExtension?: string; - /** - * Extra XHR Settings specifically for the texture image file. - */ - textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The filename of an associated normal map. It uses the same path and url to load as the texture image. - */ - normalMap?: string; - /** - * The absolute or relative URL to load the atlas xml file from. - */ - atlasURL?: string; - /** - * The default file extension to use for the atlas xml if no url is provided. - */ - atlasExtension?: string; - /** - * Extra XHR Settings specifically for the atlas xml file. - */ - atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type AudioFileConfig = { - /** - * The key of the file. Must be unique within the Loader and Audio Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - urlConfig?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The AudioContext this file will use to process itself. - */ - audioContext?: AudioContext; - }; - - type AudioSpriteFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Audio Cache. - */ - key: string; - /** - * The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead. - */ - jsonURL: string; - /** - * Extra XHR Settings specifically for the json file. - */ - jsonXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The absolute or relative URL to load the audio file from. - */ - audioURL?: Object; - /** - * The audio configuration options. - */ - audioConfig?: any; - /** - * Extra XHR Settings specifically for the audio file. - */ - audioXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type BinaryFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Binary Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * Optional type to cast the binary file to once loaded. For example, `Uint8Array`. - */ - dataType?: any; - }; - - type BitmapFontFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the texture image file from. - */ - textureURL?: string; - /** - * The default file extension to use for the image texture if no url is provided. - */ - textureExtension?: string; - /** - * Extra XHR Settings specifically for the texture image file. - */ - textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The filename of an associated normal map. It uses the same path and url to load as the texture image. - */ - normalMap?: string; - /** - * The absolute or relative URL to load the font data xml file from. - */ - fontDataURL?: string; - /** - * The default file extension to use for the font data xml if no url is provided. - */ - fontDataExtension?: string; - /** - * Extra XHR Settings specifically for the font data xml file. - */ - fontDataXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type CSSFileConfig = { - /** - * The key of the file. Must be unique within the Loader. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type GLSLFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Text Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. - */ - shaderType?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type HTMLFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Text Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type HTMLTextureFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The width of the texture the HTML will be rendered to. - */ - width?: integer; - /** - * The height of the texture the HTML will be rendered to. - */ - height?: integer; - }; - - type ImageFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * The filename of an associated normal map. It uses the same path and url to load as the image. - */ - normalMap?: string; - /** - * The frame configuration object. Only provided for, and used by, Sprite Sheets. - */ - frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type ImageFrameConfig = { - /** - * The width of the frame in pixels. - */ - frameWidth: integer; - /** - * The height of the frame in pixels. Uses the `frameWidth` value if not provided. - */ - frameHeight?: integer; - /** - * The first frame to start parsing from. - */ - startFrame?: integer; - /** - * The frame to stop parsing at. If not provided it will calculate the value based on the image and frame dimensions. - */ - endFrame?: integer; - /** - * The margin in the image. This is the space around the edge of the frames. - */ - margin?: integer; - /** - * The spacing between each frame in the image. - */ - spacing?: integer; - }; - - type JSONFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the JSON Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. Or can be a ready formed JSON object, in which case it will be directly added to the Cache. - */ - url?: string | any; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * If specified instead of the whole JSON file being parsed and added to the Cache, only the section corresponding to this property key will be added. If the property you want to extract is nested, use periods to divide it. - */ - dataKey?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type MultiAtlasFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the multi atlas json file from. Or, a well formed JSON object. - */ - atlasURL?: string; - /** - * An alias for 'atlasURL'. If given, it overrides anything set in 'atlasURL'. - */ - url?: string; - /** - * The default file extension to use for the atlas json if no url is provided. - */ - atlasExtension?: string; - /** - * Extra XHR Settings specifically for the atlas json file. - */ - atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * Optional path to use when loading the textures defined in the atlas data. - */ - path?: string; - /** - * Optional Base URL to use when loading the textures defined in the atlas data. - */ - baseURL?: string; - /** - * Extra XHR Settings specifically for the texture files. - */ - textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type MultiScriptFileConfig = { - /** - * The key of the file. Must be unique within the Loader. - */ - key: string; - /** - * An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. - */ - url?: string[]; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for these files. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type PackFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the JSON Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. Or can be a ready formed JSON object, in which case it will be directly processed. - */ - url?: string | any; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * If specified instead of the whole JSON file being parsed, only the section corresponding to this property key will be added. If the property you want to extract is nested, use periods to divide it. - */ - dataKey?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type PluginFileConfig = { - /** - * The key of the file. Must be unique within the Loader. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Automatically start the plugin after loading? - */ - start?: boolean; - /** - * If this plugin is to be injected into the Scene, this is the property key used. - */ - mapping?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type SceneFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Text Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type ScenePluginFileConfig = { - /** - * The key of the file. Must be unique within the Loader. - */ - key: string; - /** - * The absolute or relative URL to load the file from. Or, a Scene Plugin. - */ - url?: string | Function; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * If this plugin is to be added to Scene.Systems, this is the property key for it. - */ - systemKey?: string; - /** - * If this plugin is to be added to the Scene, this is the property key for it. - */ - sceneKey?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type ScriptFileConfig = { - /** - * The key of the file. Must be unique within the Loader. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type SpriteSheetFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * The filename of an associated normal map. It uses the same path and url to load as the image. - */ - normalMap?: string; - /** - * The frame configuration object. - */ - frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type SVGFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The svg size configuration object. - */ - svgConfig?: Phaser.Types.Loader.FileTypes.SVGSizeConfig; - }; - - type SVGSizeConfig = { - /** - * An optional width. The SVG will be resized to this size before being rendered to a texture. - */ - width?: integer; - /** - * An optional height. The SVG will be resized to this size before being rendered to a texture. - */ - height?: integer; - /** - * An optional scale. If given it overrides the width / height properties. The SVG is scaled by the scale factor before being rendered to a texture. - */ - scale?: number; - }; - - type TextFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Text Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type TilemapCSVFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Tilemap Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type TilemapImpactFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Tilemap Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type TilemapJSONFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Tilemap Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type UnityAtlasFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Texture Manager. - */ - key: string; - /** - * The absolute or relative URL to load the texture image file from. - */ - textureURL?: string; - /** - * The default file extension to use for the image texture if no url is provided. - */ - textureExtension?: string; - /** - * Extra XHR Settings specifically for the texture image file. - */ - textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - /** - * The filename of an associated normal map. It uses the same path and url to load as the texture image. - */ - normalMap?: string; - /** - * The absolute or relative URL to load the atlas data file from. - */ - atlasURL?: string; - /** - * The default file extension to use for the atlas data if no url is provided. - */ - atlasExtension?: string; - /** - * Extra XHR Settings specifically for the atlas data file. - */ - atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type VideoFileConfig = { - /** - * The key to use for this file, or a file configuration object. - */ - key: string | Phaser.Types.Loader.FileTypes.VideoFileConfig; - /** - * The absolute or relative URL to load this file from in a config object. - */ - urlConfig?: any; - /** - * The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. - */ - loadEvent?: string; - /** - * Load the video as a data blob, or via the Video element? - */ - asBlob?: boolean; - /** - * Does the video have an audio track? If not you can enable auto-playing on it. - */ - noAudio?: boolean; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - type XMLFileConfig = { - /** - * The key of the file. Must be unique within both the Loader and the Text Cache. - */ - key: string; - /** - * The absolute or relative URL to load the file from. - */ - url?: string; - /** - * The default file extension to use if no url is provided. - */ - extension?: string; - /** - * Extra XHR Settings specifically for this file. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; - }; - - } - - type FileConfig = { - /** - * The file type string (image, json, etc) for sorting within the Loader. - */ - type: string; - /** - * Unique cache key (unique within its file type) - */ - key: string; - /** - * The URL of the file, not including baseURL. - */ - url?: string; - /** - * The path of the file, not including the baseURL. - */ - path?: string; - /** - * The default extension this file uses. - */ - extension?: string; - /** - * The responseType to be used by the XHR request. - */ - responseType?: XMLHttpRequestResponseType; - /** - * Custom XHR Settings specific to this file and merged with the Loader defaults. - */ - xhrSettings?: Phaser.Types.Loader.XHRSettingsObject | false; - /** - * A config object that can be used by file types to store transitional data. - */ - config?: any; - }; - - type XHRSettingsObject = { - /** - * The response type of the XHR request, i.e. `blob`, `text`, etc. - */ - responseType: XMLHttpRequestResponseType; - /** - * Should the XHR request use async or not? - */ - async?: boolean; - /** - * Optional username for the XHR request. - */ - user?: string; - /** - * Optional password for the XHR request. - */ - password?: string; - /** - * Optional XHR timeout value. - */ - timeout?: integer; - /** - * This value is used to populate the XHR `setRequestHeader` and is undefined by default. - */ - header?: string | undefined; - /** - * This value is used to populate the XHR `setRequestHeader` and is undefined by default. - */ - headerValue?: string | undefined; - /** - * This value is used to populate the XHR `setRequestHeader` and is undefined by default. - */ - requestedWith?: string | undefined; - /** - * Provide a custom mime-type to use instead of the default. - */ - overrideMimeType?: string | undefined; - }; - - } - - namespace Math { - type SinCosTable = { - /** - * The sine value. - */ - sin: number; - /** - * The cosine value. - */ - cos: number; - /** - * The length. - */ - length: number; - }; - - type Vector2Like = { - /** - * The x component. - */ - x?: number; - /** - * The y component. - */ - y?: number; - }; - - } - - namespace Physics { - namespace Arcade { - type ArcadeBodyBounds = { - /** - * The left edge. - */ - x: number; - /** - * The upper edge. - */ - y: number; - /** - * The right edge. - */ - right: number; - /** - * The lower edge. - */ - bottom: number; - }; - - type ArcadeBodyCollision = { - /** - * True if the Body is not colliding. - */ - none: boolean; - /** - * True if the Body is colliding on its upper edge. - */ - up: boolean; - /** - * True if the Body is colliding on its lower edge. - */ - down: boolean; - /** - * True if the Body is colliding on its left edge. - */ - left: boolean; - /** - * True if the Body is colliding on its right edge. - */ - right: boolean; - }; - - /** - * An Arcade Physics Collider Type. - */ - type ArcadeColliderType = Phaser.GameObjects.GameObject | Phaser.GameObjects.Group | Phaser.Physics.Arcade.Sprite | Phaser.Physics.Arcade.Image | Phaser.Physics.Arcade.StaticGroup | Phaser.Physics.Arcade.Group | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer | Phaser.GameObjects.GameObject[] | Phaser.Physics.Arcade.Sprite[] | Phaser.Physics.Arcade.Image[] | Phaser.Physics.Arcade.StaticGroup[] | Phaser.Physics.Arcade.Group[] | Phaser.Tilemaps.DynamicTilemapLayer[] | Phaser.Tilemaps.StaticTilemapLayer[]; - - type ArcadeWorldConfig = { - /** - * Sets {@link Phaser.Physics.Arcade.World#fps}. - */ - fps?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#timeScale}. - */ - timeScale?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#gravity}. - */ - gravity?: Phaser.Types.Math.Vector2Like; - /** - * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.x}. - */ - x?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.y}. - */ - y?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.width}. - */ - width?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.height}. - */ - height?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#checkCollision}. - */ - checkCollision?: Phaser.Types.Physics.Arcade.CheckCollisionObject; - /** - * Sets {@link Phaser.Physics.Arcade.World#OVERLAP_BIAS}. - */ - overlapBias?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#TILE_BIAS}. - */ - tileBias?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#forceX}. - */ - forceX?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.World#isPaused}. - */ - isPaused?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.World#debug}. - */ - debug?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.World#defaults debugShowBody}. - */ - debugShowBody?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.World#defaults debugShowStaticBody}. - */ - debugShowStaticBody?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.World#defaults debugShowStaticBody}. - */ - debugShowVelocity?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.World#defaults debugBodyColor}. - */ - debugBodyColor?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#defaults debugStaticBodyColor}. - */ - debugStaticBodyColor?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#defaults debugVelocityColor}. - */ - debugVelocityColor?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#maxEntries}. - */ - maxEntries?: number; - /** - * Sets {@link Phaser.Physics.Arcade.World#useTree}. - */ - useTree?: boolean; - }; - - type ArcadeWorldDefaults = { - /** - * Set to `true` to render dynamic body outlines to the debug display. - */ - debugShowBody: boolean; - /** - * Set to `true` to render static body outlines to the debug display. - */ - debugShowStaticBody: boolean; - /** - * Set to `true` to render body velocity markers to the debug display. - */ - debugShowVelocity: boolean; - /** - * The color of dynamic body outlines when rendered to the debug display. - */ - bodyDebugColor: number; - /** - * The color of static body outlines when rendered to the debug display. - */ - staticBodyDebugColor: number; - /** - * The color of the velocity markers when rendered to the debug display. - */ - velocityDebugColor: number; - }; - - type ArcadeWorldTreeMinMax = { - /** - * The minimum x value used in RTree searches. - */ - minX: number; - /** - * The minimum y value used in RTree searches. - */ - minY: number; - /** - * The maximum x value used in RTree searches. - */ - maxX: number; - /** - * The maximum y value used in RTree searches. - */ - maxY: number; - }; - - type CheckCollisionObject = { - /** - * Will bodies collide with the top side of the world bounds? - */ - up: boolean; - /** - * Will bodies collide with the bottom side of the world bounds? - */ - down: boolean; - /** - * Will bodies collide with the left side of the world bounds? - */ - left: boolean; - /** - * Will bodies collide with the right side of the world bounds? - */ - right: boolean; - }; - - type PhysicsGroupConfig = Phaser.Types.GameObjects.Group.GroupConfig & { - /** - * Sets {@link Phaser.Physics.Arcade.Body#collideWorldBounds}. - */ - collideWorldBounds?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.Body#setBoundsRectangle setBoundsRectangle}. - */ - customBoundsRectangle?: Phaser.Geom.Rectangle; - /** - * Sets {@link Phaser.Physics.Arcade.Body#acceleration acceleration.x}. - */ - accelerationX?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#acceleration acceleration.y}. - */ - accelerationY?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#allowDrag}. - */ - allowDrag?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.Body#allowGravity}. - */ - allowGravity?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.Body#allowRotation}. - */ - allowRotation?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.Body#bounce bounce.x}. - */ - bounceX?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#bounce bounce.y}. - */ - bounceY?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#drag drag.x}. - */ - dragX?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#drag drag.y}. - */ - dragY?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#enable enable}. - */ - enable?: boolean; - /** - * Sets {@link Phaser.Physics.Arcade.Body#gravity gravity.x}. - */ - gravityX?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#gravity gravity.y}. - */ - gravityY?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#friction friction.x}. - */ - frictionX?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#friction friction.y}. - */ - frictionY?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#velocity velocity.x}. - */ - velocityX?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#velocity velocity.y}. - */ - velocityY?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#angularVelocity}. - */ - angularVelocity?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#angularAcceleration}. - */ - angularAcceleration?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#angularDrag}. - */ - angularDrag?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#mass}. - */ - mass?: number; - /** - * Sets {@link Phaser.Physics.Arcade.Body#immovable}. - */ - immovable?: boolean; - }; - - type PhysicsGroupDefaults = { - /** - * As {@link Phaser.Physics.Arcade.Body#setCollideWorldBounds}. - */ - setCollideWorldBounds: boolean; - /** - * As {@link Phaser.Physics.Arcade.Body#setBoundsRectangle}. - */ - setBoundsRectangle: Phaser.Geom.Rectangle; - /** - * As {@link Phaser.Physics.Arcade.Body#setAccelerationX}. - */ - setAccelerationX: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setAccelerationY}. - */ - setAccelerationY: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setAllowDrag}. - */ - setAllowDrag: boolean; - /** - * As {@link Phaser.Physics.Arcade.Body#setAllowGravity}. - */ - setAllowGravity: boolean; - /** - * As {@link Phaser.Physics.Arcade.Body#setAllowRotation}. - */ - setAllowRotation: boolean; - /** - * As {@link Phaser.Physics.Arcade.Body#setBounceX}. - */ - setBounceX: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setBounceY}. - */ - setBounceY: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setDragX}. - */ - setDragX: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setDragY}. - */ - setDragY: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setEnable}. - */ - setEnable: boolean; - /** - * As {@link Phaser.Physics.Arcade.Body#setGravityX}. - */ - setGravityX: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setGravityY}. - */ - setGravityY: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setFrictionX}. - */ - setFrictionX: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setFrictionY}. - */ - setFrictionY: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setVelocityX}. - */ - setVelocityX: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setVelocityY}. - */ - setVelocityY: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setAngularVelocity}. - */ - setAngularVelocity: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setAngularAcceleration}. - */ - setAngularAcceleration: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setAngularDrag}. - */ - setAngularDrag: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setMass}. - */ - setMass: number; - /** - * As {@link Phaser.Physics.Arcade.Body#setImmovable}. - */ - setImmovable: boolean; - }; - - } - - namespace Impact { - type BodyUpdateCallback = (body: Phaser.Physics.Impact.Body)=>void; - - type CollisionOptions = { - /** - * Slope IDs can be stored on tiles directly - * using Impacts tileset editor. If a tile has a property with the given slopeTileProperty string - * name, the value of that property for the tile will be used for its slope mapping. E.g. a 45 - * degree slope upward could be given a "slope" property with a value of 2. - */ - slopeTileProperty?: string; - /** - * A tile index to slope definition map. - */ - slopeMap?: object; - /** - * If specified, the default slope ID to - * assign to a colliding tile. If not specified, the tile's index is used. - */ - defaultCollidingSlope?: integer; - /** - * The default slope ID to assign to a - * non-colliding tile. - */ - defaultNonCollidingSlope?: integer; - }; - - type JSONImpactBody = { - /** - * [description] - */ - name: string; - /** - * [description] - */ - size: Phaser.Types.Math.Vector2Like; - /** - * The entity's position in the game world. - */ - pos: Phaser.Types.Math.Vector2Like; - /** - * Current velocity in pixels per second. - */ - vel: Phaser.Types.Math.Vector2Like; - /** - * Current acceleration to be added to the entity's velocity per second. E.g. an entity with a `vel.x` of 0 and `accel.x` of 10 will have a `vel.x` of 100 ten seconds later. - */ - accel: Phaser.Types.Math.Vector2Like; - /** - * Deceleration to be subtracted from the entity's velocity per second. Only applies if `accel` is 0. - */ - friction: Phaser.Types.Math.Vector2Like; - /** - * The maximum velocity a body can move. - */ - maxVel: Phaser.Types.Math.Vector2Like; - /** - * [description] - */ - gravityFactor: number; - /** - * [description] - */ - bounciness: number; - /** - * [description] - */ - minBounceVelocity: number; - /** - * [description] - */ - type: Phaser.Physics.Impact.TYPE; - /** - * [description] - */ - checkAgainst: Phaser.Physics.Impact.TYPE; - /** - * [description] - */ - collides: Phaser.Physics.Impact.COLLIDES; - }; - - type WorldConfig = { - /** - * Sets {@link Phaser.Physics.Impact.World#gravity} - */ - gravity?: number; - /** - * The size of the cells used for the broadphase pass. Increase this value if you have lots of large objects in the world. - */ - cellSize?: number; - /** - * A number that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - */ - timeScale?: number; - /** - * [description] - */ - maxStep?: number; - /** - * Sets {@link Phaser.Physics.Impact.World#debug}. - */ - debug?: boolean; - /** - * The maximum velocity a body can move. - */ - maxVelocity?: number; - /** - * Whether the Body's boundary is drawn to the debug display. - */ - debugShowBody?: boolean; - /** - * Whether the Body's velocity is drawn to the debug display. - */ - debugShowVelocity?: boolean; - /** - * The color of this Body on the debug display. - */ - debugBodyColor?: number; - /** - * The color of the Body's velocity on the debug display. - */ - debugVelocityColor?: number; - /** - * Maximum X velocity objects can move. - */ - maxVelocityX?: number; - /** - * Maximum Y velocity objects can move. - */ - maxVelocityY?: number; - /** - * The minimum velocity an object can be moving at to be considered for bounce. - */ - minBounceVelocity?: number; - /** - * Gravity multiplier. Set to 0 for no gravity. - */ - gravityFactor?: number; - /** - * The default bounce, or restitution, of bodies in the world. - */ - bounciness?: number; - /** - * Should the world have bounds enabled by default? - */ - setBounds?: object | boolean; - /** - * The x coordinate of the world bounds. - */ - "setBounds.x"?: number; - /** - * The y coordinate of the world bounds. - */ - "setBounds.y"?: number; - /** - * The width of the world bounds. - */ - "setBounds.width"?: number; - /** - * The height of the world bounds. - */ - "setBounds.height"?: number; - /** - * The thickness of the walls of the world bounds. - */ - "setBounds.thickness"?: number; - /** - * Should the left-side world bounds wall be created? - */ - "setBounds.left"?: boolean; - /** - * Should the right-side world bounds wall be created? - */ - "setBounds.right"?: boolean; - /** - * Should the top world bounds wall be created? - */ - "setBounds.top"?: boolean; - /** - * Should the bottom world bounds wall be created? - */ - "setBounds.bottom"?: boolean; - }; - - /** - * An object containing the 4 wall bodies that bound the physics world. - */ - type WorldDefaults = { - /** - * Whether the Body's boundary is drawn to the debug display. - */ - debugShowBody: boolean; - /** - * Whether the Body's velocity is drawn to the debug display. - */ - debugShowVelocity: boolean; - /** - * The color of this Body on the debug display. - */ - bodyDebugColor: number; - /** - * The color of the Body's velocity on the debug display. - */ - velocityDebugColor: number; - /** - * Maximum X velocity objects can move. - */ - maxVelocityX: number; - /** - * Maximum Y velocity objects can move. - */ - maxVelocityY: number; - /** - * The minimum velocity an object can be moving at to be considered for bounce. - */ - minBounceVelocity: number; - /** - * Gravity multiplier. Set to 0 for no gravity. - */ - gravityFactor: number; - /** - * The default bounce, or restitution, of bodies in the world. - */ - bounciness: number; - }; - - type WorldWalls = { - /** - * The left-side wall of the world bounds. - */ - left: Phaser.Physics.Impact.Body; - /** - * The right-side wall of the world bounds. - */ - right: Phaser.Physics.Impact.Body; - /** - * The top wall of the world bounds. - */ - top: Phaser.Physics.Impact.Body; - /** - * The bottom wall of the world bounds. - */ - bottom: Phaser.Physics.Impact.Body; - }; - - } - - namespace Matter { - type MatterBody = MatterJS.BodyType | Phaser.GameObjects.GameObject | Phaser.Physics.Matter.Image | Phaser.Physics.Matter.Sprite | Phaser.Physics.Matter.TileBody; - - type MatterBodyConfig = { - /** - * An arbitrary string-based name to help identify this body. - */ - label?: string; - /** - * An array of bodies that make up this body. The first body in the array must always be a self reference to the current body instance. All bodies in the `parts` array together form a single rigid compound body. - */ - parts?: MatterJS.BodyType[]; - /** - * An object reserved for storing plugin-specific properties. - */ - plugin?: any; - /** - * A number specifying the angle of the body, in radians. - */ - angle?: number; - /** - * An array of `Vector` objects that specify the convex hull of the rigid body. These should be provided about the origin `(0, 0)`. - */ - vertices?: Phaser.Types.Math.Vector2Like[]; - /** - * A `Vector` that specifies the current world-space position of the body. - */ - position?: Phaser.Types.Math.Vector2Like; - /** - * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. - */ - force?: Phaser.Types.Math.Vector2Like; - /** - * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. - */ - torque?: number; - /** - * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. - */ - isSensor?: boolean; - /** - * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. - */ - isStatic?: boolean; - /** - * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). - */ - sleepThreshold?: number; - /** - * 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). - */ - density?: number; - /** - * A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`. - */ - restitution?: number; - /** - * 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. - */ - friction?: number; - /** - * A `Number` that defines the static friction of the body (in the Coulomb friction model). A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. - */ - frictionStatic?: number; - /** - * A `Number` that defines the air friction of the body (air resistance). A value of `0` means the body will never slow as it moves through space. The higher the value, the faster a body slows when moving through space. - */ - frictionAir?: number; - /** - * An `Object` that specifies the collision filtering properties of this body. - */ - collisionFilter?: Phaser.Types.Physics.Matter.MatterCollisionFilter; - /** - * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. Avoid changing this value unless you understand the purpose of `slop` in physics engines. The default should generally suffice, although very large bodies may require larger values for stable stacking. - */ - slop?: number; - /** - * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. - */ - timeScale?: number; - /** - * A number, or array of numbers, to chamfer the vertices of the body, or a full Chamfer configuration object. - */ - chamfer?: number | number[] | Phaser.Types.Physics.Matter.MatterChamferConfig; - /** - * The radius of this body if a circle. - */ - circleRadius?: number; - /** - * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). - */ - mass?: number; - /** - * A `Number` that defines the inverse mass of the body (`1 / mass`). If you modify this value, you must also modify the `body.mass` property. - */ - inverseMass?: number; - /** - * A `Vector` that specifies the initial scale of the body. - */ - scale?: Phaser.Types.Math.Vector2Like; - /** - * A `Vector` that scales the influence of World gravity when applied to this body. - */ - gravityScale?: Phaser.Types.Math.Vector2Like; - /** - * A boolean that toggles if this body should ignore world gravity or not. - */ - ignoreGravity?: boolean; - /** - * A boolean that toggles if this body should ignore pointer / mouse constraints or not. - */ - ignorePointer?: boolean; - /** - * The Debug Render configuration object for this body. - */ - render?: Phaser.Types.Physics.Matter.MatterBodyRenderConfig; - /** - * A callback that is invoked when this Body starts colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - */ - onCollideCallback?: Function; - /** - * A callback that is invoked when this Body stops colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - */ - onCollideEndCallback?: Function; - /** - * A callback that is invoked for the duration that this Body is colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. - */ - onCollideActiveCallback?: Function; - /** - * A collision callback dictionary used by the `Body.setOnCollideWith` function. - */ - onCollideWith?: any; - }; - - type MatterBodyRenderConfig = { - /** - * Should this body be rendered by the Debug Renderer? - */ - visible?: boolean; - /** - * The opacity of the body and all parts within it. - */ - opacity?: number; - /** - * The color value of the fill when rendering this body. - */ - fillColor?: number; - /** - * The opacity of the fill when rendering this body, a value between 0 and 1. - */ - fillOpacity?: number; - /** - * The color value of the line stroke when rendering this body. - */ - lineColor?: number; - /** - * The opacity of the line when rendering this body, a value between 0 and 1. - */ - lineOpacity?: number; - /** - * If rendering lines, the thickness of the line. - */ - lineThickness?: number; - /** - * Controls the offset between the body and the parent Game Object, if it has one. - */ - sprite?: object; - /** - * The horizontal offset between the body and the parent Game Object texture, if it has one. - */ - "sprite.xOffset"?: number; - /** - * The vertical offset between the body and the parent Game Object texture, if it has one. - */ - "sprite.yOffset"?: number; - }; - - type MatterBodyTileOptions = { - /** - * Whether or not the newly created body should be made static. This defaults to true since typically tiles should not be moved. - */ - isStatic?: boolean; - /** - * Whether or not to add the newly created body (or existing body if options.body is used) to the Matter world. - */ - addToWorld?: boolean; - }; - - type MatterChamferConfig = { - /** - * A single number, or an array, to specify the radius for each vertex. - */ - radius?: number | number[]; - /** - * The quality of the chamfering. -1 means 'auto'. - */ - quality?: number; - /** - * The minimum quality of the chamfering. The higher this value, the more vertices are created. - */ - qualityMin?: number; - /** - * The maximum quality of the chamfering. The higher this value, the more vertices are created. - */ - qualityMax?: number; - }; - - type MatterCollisionData = { - /** - * Have the pair collided or not? - */ - collided: boolean; - /** - * A reference to the first body involved in the collision. - */ - bodyA: MatterJS.BodyType; - /** - * A reference to the second body involved in the collision. - */ - bodyB: MatterJS.BodyType; - /** - * A reference to the dominant axis body. - */ - axisBody: MatterJS.BodyType; - /** - * The index of the dominant collision axis vector (edge normal) - */ - axisNumber: number; - /** - * The depth of the collision on the minimum overlap. - */ - depth: number; - /** - * A reference to the parent of Body A, or to Body A itself if it has no parent. - */ - parentA: MatterJS.BodyType; - /** - * A reference to the parent of Body B, or to Body B itself if it has no parent. - */ - parentB: MatterJS.BodyType; - /** - * The collision normal, facing away from Body A. - */ - normal: MatterJS.Vector; - /** - * The tangent of the collision normal. - */ - tangent: MatterJS.Vector; - /** - * The penetration distances between the two bodies. - */ - penetration: MatterJS.Vector; - /** - * An array of support points, either exactly one or two points. - */ - supports: MatterJS.Vector[]; - /** - * The resulting inverse mass from the collision. - */ - inverseMass: number; - /** - * The resulting friction from the collision. - */ - friction: number; - /** - * The resulting static friction from the collision. - */ - frictionStatic: number; - /** - * The resulting restitution from the collision. - */ - restitution: number; - /** - * The resulting slop from the collision. - */ - slop: number; - }; - - /** - * An `Object` that specifies the collision filtering properties of this body. - * - * Collisions between two bodies will obey the following rules: - * - If the two bodies have the same non-zero value of `collisionFilter.group`, - * they will always collide if the value is positive, and they will never collide - * if the value is negative. - * - If the two bodies have different values of `collisionFilter.group` or if one - * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: - * - * Each body belongs to a collision category, given by `collisionFilter.category`. This - * value is used as a bit field and the category should have only one bit set, meaning that - * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 - * different collision categories available. - * - * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies - * the categories it collides with (the value is the bitwise AND value of all these categories). - * - * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's - * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` - * are both true. - */ - type MatterCollisionFilter = { - /** - * A bit field that specifies the collision category this body belongs to. The category value should have only one bit set, for example `0x0001`. This means there are up to 32 unique collision categories available. - */ - category?: number; - /** - * A bit mask that specifies the collision categories this body may collide with. - */ - mask?: number; - /** - * An Integer `Number`, that specifies the collision group this body belongs to. - */ - group?: number; - }; - - type MatterCollisionPair = { - /** - * The unique auto-generated collision pair id. A combination of the body A and B IDs. - */ - id: string; - /** - * A reference to the first body involved in the collision. - */ - bodyA: MatterJS.BodyType; - /** - * A reference to the second body involved in the collision. - */ - bodyB: MatterJS.BodyType; - /** - * An array containing all of the active contacts between bodies A and B. - */ - activeContacts: MatterJS.Vector[]; - /** - * The amount of separation that occured between bodies A and B. - */ - separation: number; - /** - * Is the collision still active or not? - */ - isActive: boolean; - /** - * Has Matter determined the collision are being active yet? - */ - confirmedActive: boolean; - /** - * Is either body A or B a sensor? - */ - isSensor: boolean; - /** - * The timestamp when the collision pair was created. - */ - timeCreated: number; - /** - * The timestamp when the collision pair was most recently updated. - */ - timeUpdated: number; - /** - * The collision data object. - */ - collision: Phaser.Types.Physics.Matter.MatterCollisionData; - /** - * The resulting inverse mass from the collision. - */ - inverseMass: number; - /** - * The resulting friction from the collision. - */ - friction: number; - /** - * The resulting static friction from the collision. - */ - frictionStatic: number; - /** - * The resulting restitution from the collision. - */ - restitution: number; - /** - * The resulting slop from the collision. - */ - slop: number; - }; - - type MatterConstraintConfig = { - /** - * An arbitrary string-based name to help identify this constraint. - */ - label?: string; - /** - * The first possible `Body` that this constraint is attached to. - */ - bodyA?: MatterJS.BodyType; - /** - * The second possible `Body` that this constraint is attached to. - */ - bodyB?: MatterJS.BodyType; - /** - * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. - */ - pointA?: Phaser.Types.Math.Vector2Like; - /** - * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. - */ - pointB?: Phaser.Types.Math.Vector2Like; - /** - * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts like a soft spring. - */ - stiffness?: number; - /** - * A `Number` that specifies the angular stiffness of the constraint. - */ - angularStiffness?: number; - /** - * The angleA of the constraint. If bodyA is set, the angle of bodyA is used instead. - */ - angleA?: number; - /** - * The angleB of the constraint. If bodyB is set, the angle of bodyB is used instead. - */ - angleB?: number; - /** - * 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. - */ - damping?: number; - /** - * A `Number` that specifies the target resting length of the constraint. It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - */ - length?: number; - /** - * An object reserved for storing plugin-specific properties. - */ - plugin?: any; - /** - * The Debug Render configuration object for this constraint. - */ - render?: Phaser.Types.Physics.Matter.MatterConstraintRenderConfig; - }; - - type MatterConstraintRenderConfig = { - /** - * Should this constraint be rendered by the Debug Renderer? - */ - visible?: boolean; - /** - * If this constraint has anchors, should they be rendered? Pin constraints never have anchors. - */ - anchors?: boolean; - /** - * The color value of the line stroke when rendering this constraint. - */ - lineColor?: number; - /** - * The opacity of the line when rendering this constraint, a value between 0 and 1. - */ - lineOpacity?: number; - /** - * If rendering lines, the thickness of the line. - */ - lineThickness?: number; - /** - * The size of the circles drawn when rendering pin constraints. - */ - pinSize?: number; - /** - * The size of the circles drawn as the constraint anchors. - */ - anchorSize?: number; - /** - * The color value of constraint anchors. - */ - anchorColor?: number; - }; - - type MatterDebugConfig = { - /** - * Render all of the body axes? - */ - showAxes?: boolean; - /** - * Render just a single body axis? - */ - showAngleIndicator?: boolean; - /** - * The color of the body angle / axes lines. - */ - angleColor?: boolean; - /** - * Render the broadphase grid? - */ - showBroadphase?: boolean; - /** - * The color of the broadphase grid. - */ - broadphaseColor?: boolean; - /** - * Render the bounds of the bodies in the world? - */ - showBounds?: boolean; - /** - * The color of the body bounds. - */ - boundsColor?: boolean; - /** - * Render the velocity of the bodies in the world? - */ - showVelocity?: boolean; - /** - * The color of the body velocity line. - */ - velocityColor?: boolean; - /** - * Render the collision points and normals for colliding pairs. - */ - showCollisions?: boolean; - /** - * The color of the collision points. - */ - collisionColor?: boolean; - /** - * Render lines showing the separation between bodies. - */ - showSeparation?: boolean; - /** - * The color of the body separation line. - */ - separationColor?: boolean; - /** - * Render the dynamic bodies in the world to the Graphics object? - */ - showBody?: boolean; - /** - * Render the static bodies in the world to the Graphics object? - */ - showStaticBody?: boolean; - /** - * When rendering bodies, render the internal edges as well? - */ - showInternalEdges?: boolean; - /** - * Render the bodies using a fill color. - */ - renderFill?: boolean; - /** - * Render the bodies using a line stroke. - */ - renderLine?: boolean; - /** - * The color value of the fill when rendering dynamic bodies. - */ - fillColor?: number; - /** - * The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. - */ - fillOpacity?: number; - /** - * The color value of the line stroke when rendering dynamic bodies. - */ - lineColor?: number; - /** - * The opacity of the line when rendering dynamic bodies, a value between 0 and 1. - */ - lineOpacity?: number; - /** - * If rendering lines, the thickness of the line. - */ - lineThickness?: number; - /** - * The color value of the fill when rendering static bodies. - */ - staticFillColor?: number; - /** - * The color value of the line stroke when rendering static bodies. - */ - staticLineColor?: number; - /** - * Render any sleeping bodies (dynamic or static) in the world to the Graphics object? - */ - showSleeping?: boolean; - /** - * The amount to multiply the opacity of sleeping static bodies by. - */ - staticBodySleepOpacity?: number; - /** - * The color value of the fill when rendering sleeping dynamic bodies. - */ - sleepFillColor?: number; - /** - * The color value of the line stroke when rendering sleeping dynamic bodies. - */ - sleepLineColor?: number; - /** - * Render bodies or body parts that are flagged as being a sensor? - */ - showSensors?: boolean; - /** - * The fill color when rendering body sensors. - */ - sensorFillColor?: number; - /** - * The line color when rendering body sensors. - */ - sensorLineColor?: number; - /** - * Render the position of non-static bodies? - */ - showPositions?: boolean; - /** - * The size of the rectangle drawn when rendering the body position. - */ - positionSize?: number; - /** - * The color value of the rectangle drawn when rendering the body position. - */ - positionColor?: number; - /** - * Render all world constraints to the Graphics object? - */ - showJoint?: boolean; - /** - * The color value of joints when `showJoint` is set. - */ - jointColor?: number; - /** - * The line opacity when rendering joints, a value between 0 and 1. - */ - jointLineOpacity?: number; - /** - * The line thickness when rendering joints. - */ - jointLineThickness?: number; - /** - * The size of the circles drawn when rendering pin constraints. - */ - pinSize?: number; - /** - * The color value of the circles drawn when rendering pin constraints. - */ - pinColor?: number; - /** - * The color value of spring constraints. - */ - springColor?: number; - /** - * The color value of constraint anchors. - */ - anchorColor?: number; - /** - * The size of the circles drawn as the constraint anchors. - */ - anchorSize?: number; - /** - * When rendering polygon bodies, render the convex hull as well? - */ - showConvexHulls?: boolean; - /** - * The color value of hulls when `showConvexHulls` is set. - */ - hullColor?: number; - }; - - type MatterRunnerConfig = { - /** - * A boolean that specifies if the runner should use a fixed timestep (otherwise it is variable). If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). - */ - isFixed?: boolean; - /** - * A number that specifies the frame rate in seconds. If you don't specify this, but do specify `delta`, those values set the fps rate. - */ - fps?: number; - /** - * A 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. - */ - correction?: number; - /** - * The size of the delta smoothing array when `isFixed` is `false`. - */ - deltaSampleSize?: number; - /** - * A number that specifies the time step between updates in milliseconds. If you set the `fps` property, this value is set based on that. If `isFixed` is set to `true`, then `delta` is fixed. If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. - */ - delta?: number; - /** - * A number that specifies the minimum time step between updates in milliseconds. - */ - deltaMin?: number; - /** - * A number that specifies the maximum time step between updates in milliseconds. - */ - deltaMax?: number; - }; - - type MatterSetBodyConfig = { - /** - * The shape type. Either `rectangle`, `circle`, `trapezoid`, `polygon`, `fromVertices`, `fromVerts` or `fromPhysicsEditor`. - */ - type?: string; - /** - * The horizontal world position to place the body at. - */ - x?: number; - /** - * The vertical world position to place the body at. - */ - y?: number; - /** - * The width of the body. - */ - width?: number; - /** - * The height of the body. - */ - height?: number; - /** - * The radius of the body. Used by `circle` and `polygon` shapes. - */ - radius?: number; - /** - * The max sizes of the body. Used by the `circle` shape. - */ - maxSides?: number; - /** - * Used by the `trapezoid` shape. The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - */ - slope?: number; - /** - * Used by the `polygon` shape. The number of sides the polygon will have. - */ - sides?: number; - /** - * Used by the `fromVerts` shape. The vertices data. Either a path string or an array of vertices. - */ - verts?: string | any[]; - /** - * Used by the `fromVerts` shape. Flag internal edges (coincident part edges) - */ - flagInternal?: boolean; - /** - * Used by the `fromVerts` shape. Whether Matter.js will discard collinear edges (to improve performance). - */ - removeCollinear?: number; - /** - * Used by the `fromVerts` shape. During decomposition discard parts that have an area less than this. - */ - minimumArea?: number; - /** - * Should the new body be automatically added to the world? - */ - addToWorld?: boolean; - }; - - type MatterTileOptions = { - /** - * An existing Matter body to be used instead of creating a new one. - */ - body?: MatterJS.BodyType; - /** - * Whether or not the newly created body should be made static. This defaults to true since typically tiles should not be moved. - */ - isStatic?: boolean; - /** - * Whether or not to add the newly created body (or existing body if options.body is used) to the Matter world. - */ - addToWorld?: boolean; - }; - - type MatterWorldConfig = { - /** - * Sets {@link Phaser.Physics.Matter.World#gravity}. If `false` Gravity will be set to zero. - */ - gravity?: Phaser.Types.Math.Vector2Like | boolean; - /** - * Should the world have bounds enabled by default? - */ - setBounds?: object | boolean; - /** - * The x coordinate of the world bounds. - */ - "setBounds.x"?: number; - /** - * The y coordinate of the world bounds. - */ - "setBounds.y"?: number; - /** - * The width of the world bounds. - */ - "setBounds.width"?: number; - /** - * The height of the world bounds. - */ - "setBounds.height"?: number; - /** - * The thickness of the walls of the world bounds. - */ - "setBounds.thickness"?: number; - /** - * Should the left-side world bounds wall be created? - */ - "setBounds.left"?: boolean; - /** - * Should the right-side world bounds wall be created? - */ - "setBounds.right"?: boolean; - /** - * Should the top world bounds wall be created? - */ - "setBounds.top"?: boolean; - /** - * Should the bottom world bounds wall be created? - */ - "setBounds.bottom"?: boolean; - /** - * The number of position iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. - */ - positionIterations?: number; - /** - * The number of velocity iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. - */ - velocityIterations?: number; - /** - * The number of constraint iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. - */ - constraintIterations?: number; - /** - * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. Sleeping can improve stability and performance, but often at the expense of accuracy. - */ - enableSleeping?: boolean; - /** - * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. It is incremented on every `Engine.update` by the given `delta` argument. - */ - "timing.timestamp"?: number; - /** - * A `Number` that specifies the global scaling factor of time for all bodies. A value of `0` freezes the simulation. A value of `0.1` gives a slow-motion effect. A value of `1.2` gives a speed-up effect. - */ - "timing.timeScale"?: number; - /** - * Should the Matter Attractor Plugin be enabled? An attractors plugin that makes it easy to apply continual forces on bodies. It's possible to simulate effects such as wind, gravity and magnetism. - */ - "plugins.attractors"?: boolean; - /** - * Should the Matter Wrap Plugin be enabled? A coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, while maintaining its velocity. - */ - "plugins.wrap"?: boolean; - /** - * Should the Matter Collision Events Plugin be enabled? - */ - "plugins.collisionevents"?: boolean; - /** - * Toggles if the world is enabled or not. - */ - enabled?: boolean; - /** - * An optional Number that specifies the time correction factor to apply to the update. - */ - correction?: number; - /** - * This function is called every time the core game loop steps, which is bound to the Request Animation Frame frequency unless otherwise modified. - */ - getDelta?: Function; - /** - * Automatically call Engine.update every time the game steps. - */ - autoUpdate?: boolean; - /** - * Sets the Resolver resting threshold property. - */ - restingThresh?: number; - /** - * Sets the Resolver resting threshold tangent property. - */ - restingThreshTangent?: number; - /** - * Sets the Resolver position dampen property. - */ - positionDampen?: number; - /** - * Sets the Resolver position warming property. - */ - positionWarming?: number; - /** - * Sets the Resolver friction normal multiplier property. - */ - frictionNormalMultiplier?: number; - /** - * Controls the Matter Debug Rendering options. If a boolean it will use the default values, otherwise, specify a Debug Config object. - */ - debug?: boolean | Phaser.Types.Physics.Matter.MatterDebugConfig; - /** - * Sets the Matter Runner options. - */ - runner?: Phaser.Types.Physics.Matter.MatterRunnerConfig; - }; - - } - - } - - namespace Plugins { - type CorePluginContainer = { - /** - * The unique name of this plugin in the core plugin cache. - */ - key: string; - /** - * The plugin to be stored. Should be the source object, not instantiated. - */ - plugin: Function; - /** - * If this plugin is to be injected into the Scene Systems, this is the property key map used. - */ - mapping?: string; - /** - * Core Scene plugin or a Custom Scene plugin? - */ - custom?: boolean; - }; - - type CustomPluginContainer = { - /** - * The unique name of this plugin in the custom plugin cache. - */ - key: string; - /** - * The plugin to be stored. Should be the source object, not instantiated. - */ - plugin: Function; - }; - - type GlobalPlugin = { - /** - * The unique name of this plugin within the plugin cache. - */ - key: string; - /** - * An instance of the plugin. - */ - plugin: Function; - /** - * Is the plugin active or not? - */ - active?: boolean; - /** - * If this plugin is to be injected into the Scene Systems, this is the property key map used. - */ - mapping?: string; - }; - - } - - namespace Renderer { - namespace Snapshot { - type SnapshotCallback = (snapshot: Phaser.Display.Color | HTMLImageElement)=>void; - - type SnapshotState = { - /** - * The function to call after the snapshot is taken. - */ - callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback; - /** - * The format of the image to create, usually `image/png` or `image/jpeg`. - */ - type?: string; - /** - * The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. - */ - encoderOptions?: number; - /** - * The x coordinate to start the snapshot from. - */ - x?: integer; - /** - * The y coordinate to start the snapshot from. - */ - y?: integer; - /** - * The width of the snapshot. - */ - width?: integer; - /** - * The height of the snapshot. - */ - height?: integer; - /** - * Is this a snapshot to get a single pixel, or an area? - */ - getPixel?: boolean; - /** - * Is this snapshot grabbing from a frame buffer or a canvas? - */ - isFramebuffer?: boolean; - /** - * The width of the frame buffer, if a frame buffer grab. - */ - bufferWidth?: integer; - /** - * The height of the frame buffer, if a frame buffer grab. - */ - bufferHeight?: integer; - }; - - } - - } - - namespace Scenes { - type CreateSceneFromObjectConfig = { - /** - * The scene's init callback. - */ - init?: Phaser.Types.Scenes.SceneInitCallback; - /** - * The scene's preload callback. - */ - preload?: Phaser.Types.Scenes.ScenePreloadCallback; - /** - * The scene's create callback. - */ - create?: Phaser.Types.Scenes.SceneCreateCallback; - /** - * The scene's update callback. See {@link Phaser.Scene#update}. - */ - update?: Function; - /** - * Any additional properties, which will be copied to the Scene after it's created (except `data` or `sys`). - */ - extend?: any; - /** - * Any values, which will be merged into the Scene's Data Manager store. - */ - "extend.data"?: any; - }; - - /** - * Can be defined on your own Scenes. Use it to create your game objects. - * This method is called by the Scene Manager when the scene starts, after `init()` and `preload()`. - * If the LoaderPlugin started after `preload()`, then this method is called only after loading is complete. - */ - type SceneCreateCallback = (data: object)=>void; - - /** - * Can be defined on your own Scenes. - * This method is called by the Scene Manager when the scene starts, before `preload()` and `create()`. - */ - type SceneInitCallback = (data: object)=>void; - - /** - * Can be defined on your own Scenes. Use it to load assets. - * This method is called by the Scene Manager, after `init()` and before `create()`, only if the Scene has a LoaderPlugin. - * After this method completes, if the LoaderPlugin's queue isn't empty, the LoaderPlugin will start automatically. - */ - type ScenePreloadCallback = ()=>void; - - type SceneTransitionConfig = { - /** - * The Scene key to transition to. - */ - target: string; - /** - * The duration, in ms, for the transition to last. - */ - duration?: integer; - /** - * Will the Scene responsible for the transition be sent to sleep on completion (`true`), or stopped? (`false`) - */ - sleep?: boolean; - /** - * Will the Scenes Input system be able to process events while it is transitioning in or out? - */ - allowInput?: boolean; - /** - * Move the target Scene to be above this one before the transition starts. - */ - moveAbove?: boolean; - /** - * Move the target Scene to be below this one before the transition starts. - */ - moveBelow?: boolean; - /** - * This callback is invoked every frame for the duration of the transition. - */ - onUpdate?: Function; - /** - * The context in which the callback is invoked. - */ - onUpdateScope?: any; - /** - * An object containing any data you wish to be passed to the target Scenes init / create methods. - */ - data?: any; - }; - - type SettingsConfig = { - /** - * The unique key of this Scene. Must be unique within the entire Game instance. - */ - key?: string; - /** - * Does the Scene start as active or not? An active Scene updates each step. - */ - active?: boolean; - /** - * Does the Scene start as visible or not? A visible Scene renders each step. - */ - visible?: boolean; - /** - * An optional Loader Packfile to be loaded before the Scene begins. - */ - pack?: false | Phaser.Types.Loader.FileTypes.PackFileConfig; - /** - * An optional Camera configuration object. - */ - cameras?: Phaser.Types.Cameras.Scene2D.JSONCamera | Phaser.Types.Cameras.Scene2D.JSONCamera[]; - /** - * Overwrites the default injection map for a scene. - */ - map?: {[key: string]: string}; - /** - * Extends the injection map for a scene. - */ - mapAdd?: {[key: string]: string}; - /** - * The physics configuration object for the Scene. - */ - physics?: Phaser.Types.Core.PhysicsConfig; - /** - * The loader configuration object for the Scene. - */ - loader?: Phaser.Types.Core.LoaderConfig; - /** - * The plugin configuration object for the Scene. - */ - plugins?: false | any; - }; - - type SettingsObject = { - /** - * The current status of the Scene. Maps to the Scene constants. - */ - status: number; - /** - * The unique key of this Scene. Unique within the entire Game instance. - */ - key: string; - /** - * The active state of this Scene. An active Scene updates each step. - */ - active: boolean; - /** - * The visible state of this Scene. A visible Scene renders each step. - */ - visible: boolean; - /** - * Has the Scene finished booting? - */ - isBooted: boolean; - /** - * Is the Scene in a state of transition? - */ - isTransition: boolean; - /** - * The Scene this Scene is transitioning from, if set. - */ - transitionFrom: Phaser.Scene; - /** - * The duration of the transition, if set. - */ - transitionDuration: integer; - /** - * Is this Scene allowed to receive input during transitions? - */ - transitionAllowInput: boolean; - /** - * a data bundle passed to this Scene from the Scene Manager. - */ - data: object; - /** - * The Loader Packfile to be loaded before the Scene begins. - */ - pack: false | Phaser.Types.Loader.FileTypes.PackFileConfig; - /** - * The Camera configuration object. - */ - cameras: Phaser.Types.Cameras.Scene2D.JSONCamera | Phaser.Types.Cameras.Scene2D.JSONCamera[]; - /** - * The Scene's Injection Map. - */ - map: {[key: string]: string}; - /** - * The physics configuration object for the Scene. - */ - physics: Phaser.Types.Core.PhysicsConfig; - /** - * The loader configuration object for the Scene. - */ - loader: Phaser.Types.Core.LoaderConfig; - /** - * The plugin configuration object for the Scene. - */ - plugins: false | any; - }; - - } - - namespace Sound { - /** - * Audio sprite sound type. - */ - type AudioSpriteSound = { - /** - * Local reference to 'spritemap' object form json file generated by audiosprite tool. - */ - spritemap: object; - }; - - /** - * A Audio Data object. - * - * You can pass an array of these objects to the WebAudioSoundManager `decodeAudio` method to have it decode - * them all at once. - */ - type DecodeAudioConfig = { - /** - * The string-based key to be used to reference the decoded audio in the audio cache. - */ - key: string; - /** - * The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. - */ - data: ArrayBuffer | string; - }; - - type EachActiveSoundCallback = (manager: Phaser.Sound.BaseSoundManager, sound: Phaser.Sound.BaseSound, index: number, sounds: Phaser.Sound.BaseSound[])=>void; - - /** - * Config object containing various sound settings. - */ - type SoundConfig = { - /** - * Boolean indicating whether the sound should be muted or not. - */ - mute?: boolean; - /** - * A value between 0 (silence) and 1 (full volume). - */ - volume?: number; - /** - * Defines the speed at which the sound should be played. - */ - rate?: number; - /** - * Represents detuning of sound in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29). - */ - detune?: number; - /** - * Position of playback for this sound, in seconds. - */ - seek?: number; - /** - * Whether or not the sound or current sound marker should loop. - */ - loop?: boolean; - /** - * Time, in seconds, that should elapse before the sound actually starts its playback. - */ - delay?: number; - }; - - /** - * Marked section of a sound represented by name, and optionally start time, duration, and config object. - */ - type SoundMarker = { - /** - * Unique identifier of a sound marker. - */ - name: string; - /** - * Sound position offset at witch playback should start. - */ - start?: number; - /** - * Playback duration of this marker. - */ - duration?: number; - /** - * An optional config object containing default marker settings. - */ - config?: Phaser.Types.Sound.SoundConfig; - }; - - } - - namespace Textures { - /** - * An object containing the position and color data for a single pixel in a CanvasTexture. - */ - type PixelConfig = { - /** - * The x-coordinate of the pixel. - */ - x: integer; - /** - * The y-coordinate of the pixel. - */ - y: integer; - /** - * The color of the pixel, not including the alpha channel. - */ - color: integer; - /** - * The alpha of the pixel, between 0 and 1. - */ - alpha: number; - }; - - type SpriteSheetConfig = { - /** - * The fixed width of each frame. - */ - frameWidth: integer; - /** - * The fixed height of each frame. If not set it will use the frameWidth as the height. - */ - frameHeight?: integer; - /** - * Skip a number of frames. Useful when there are multiple sprite sheets in one Texture. - */ - startFrame?: integer; - /** - * The total number of frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". - */ - endFrame?: integer; - /** - * If the frames have been drawn with a margin, specify the amount here. - */ - margin?: integer; - /** - * If the frames have been drawn with spacing between them, specify the amount here. - */ - spacing?: integer; - }; - - type SpriteSheetFromAtlasConfig = { - /** - * The key of the Texture Atlas in which this Sprite Sheet can be found. - */ - atlas: string; - /** - * The key of the Texture Atlas Frame in which this Sprite Sheet can be found. - */ - frame: string; - /** - * The fixed width of each frame. - */ - frameWidth: integer; - /** - * The fixed height of each frame. If not set it will use the frameWidth as the height. - */ - frameHeight?: integer; - /** - * Skip a number of frames. Useful when there are multiple sprite sheets in one Texture. - */ - startFrame?: integer; - /** - * The total number of frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". - */ - endFrame?: integer; - /** - * If the frames have been drawn with a margin, specify the amount here. - */ - margin?: integer; - /** - * If the frames have been drawn with spacing between them, specify the amount here. - */ - spacing?: integer; - }; - - } - - namespace Tilemaps { - type FilteringOptions = { - /** - * If true, only return tiles that don't have -1 for an index. - */ - isNotEmpty?: boolean; - /** - * If true, only return tiles that collide on at least one side. - */ - isColliding?: boolean; - /** - * If true, only return tiles that have at least one interesting face. - */ - hasInterestingFace?: boolean; - }; - - type GetTilesWithinFilteringOptions = { - /** - * If true, only return tiles that don't have -1 for an index. - */ - isNotEmpty?: boolean; - /** - * If true, only return tiles that collide on at least one side. - */ - isColliding?: boolean; - /** - * If true, only return tiles that have at least one interesting face. - */ - hasInterestingFace?: boolean; - }; - - type MapDataConfig = { - /** - * The key in the Phaser cache that corresponds to the loaded tilemap data. - */ - name?: string; - /** - * The width of the entire tilemap. - */ - width?: number; - /** - * The height of the entire tilemap. - */ - height?: number; - /** - * The width of the tiles. - */ - tileWidth?: number; - /** - * The height of the tiles. - */ - tileHeight?: number; - /** - * The width in pixels of the entire tilemap. - */ - widthInPixels?: number; - /** - * The height in pixels of the entire tilemap. - */ - heightInPixels?: number; - /** - * The format of the Tilemap, as defined in Tiled. - */ - format?: integer; - /** - * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. - */ - orientation?: string; - /** - * Determines the draw order of tilemap. Default is right-down. - */ - renderOrder?: string; - /** - * The version of Tiled the map uses. - */ - version?: number; - /** - * Map specific properties (can be specified in Tiled). - */ - properties?: number; - /** - * The layers of the tilemap. - */ - layers?: Phaser.Tilemaps.LayerData[]; - /** - * An array with all the layers configured to the MapData. - */ - images?: any[]; - /** - * An array of Tiled Image Layers. - */ - objects?: object; - /** - * An object of Tiled Object Layers. - */ - collision?: object; - /** - * The tilesets the map uses. - */ - tilesets?: Phaser.Tilemaps.Tileset[]; - /** - * The collection of images the map uses(specified in Tiled). - */ - imageCollections?: any[]; - /** - * [description] - */ - tiles?: any[]; - }; - - type ObjectLayerConfig = { - /** - * The name of the Object Layer. - */ - name?: string; - /** - * The opacity of the layer, between 0 and 1. - */ - opacity?: number; - /** - * The custom properties defined on the Object Layer, keyed by their name. - */ - properties?: any; - /** - * The type of each custom property defined on the Object Layer, keyed by its name. - */ - propertytypes?: any; - /** - * The type of the layer, which should be `objectgroup`. - */ - type?: string; - /** - * Whether the layer is shown (`true`) or hidden (`false`). - */ - visible?: boolean; - /** - * An array of all objects on this Object Layer. - */ - objects?: any[]; - }; - - type StyleConfig = { - /** - * Color to use for drawing a filled rectangle at non-colliding tile locations. If set to null, non-colliding tiles will not be drawn. - */ - tileColor?: Phaser.Display.Color | number | null; - /** - * Color to use for drawing a filled rectangle at colliding tile locations. If set to null, colliding tiles will not be drawn. - */ - collidingTileColor?: Phaser.Display.Color | number | null; - /** - * Color to use for drawing a line at interesting tile faces. If set to null, interesting tile faces will not be drawn. - */ - faceColor?: Phaser.Display.Color | number | null; - }; - - type TiledObject = { - /** - * The unique object ID. - */ - id: integer; - /** - * The name this object was assigned in Tiled. - */ - name: string; - /** - * The type, as assigned in Tiled. - */ - type: string; - /** - * The visible state of this object. - */ - visible?: boolean; - /** - * The horizontal position of this object, in pixels, relative to the tilemap. - */ - x?: number; - /** - * The vertical position of this object, in pixels, relative to the tilemap. - */ - y?: number; - /** - * The width of this object, in pixels. - */ - width?: number; - /** - * The height of this object, in pixels. - */ - height?: number; - /** - * The rotation of the object in clockwise degrees. - */ - rotation?: number; - /** - * Custom properties object. - */ - properties?: any; - /** - * Only set if of type 'tile'. - */ - gid?: integer; - /** - * Only set if a tile object. The horizontal flip value. - */ - flippedHorizontal?: boolean; - /** - * Only set if a tile object. The vertical flip value. - */ - flippedVertical?: boolean; - /** - * Only set if a tile object. The diagonal flip value. - */ - flippedAntiDiagonal?: boolean; - /** - * Only set if a polyline object. An array of objects corresponding to points, where each point has an `x` property and a `y` property. - */ - polyline?: Phaser.Types.Math.Vector2Like[]; - /** - * Only set if a polygon object. An array of objects corresponding to points, where each point has an `x` property and a `y` property. - */ - polygon?: Phaser.Types.Math.Vector2Like[]; - /** - * Only set if a text object. Contains the text objects properties. - */ - text?: any; - /** - * Only set, and set to `true`, if a rectangle object. - */ - rectangle?: boolean; - /** - * Only set, and set to `true`, if a ellipse object. - */ - ellipse?: boolean; - }; - - type TilemapConfig = { - /** - * The key in the Phaser cache that corresponds to the loaded tilemap data. - */ - key?: string; - /** - * Instead of loading from the cache, you can also load directly from a 2D array of tile indexes. - */ - data?: integer[][]; - /** - * The width of a tile in pixels. - */ - tileWidth?: integer; - /** - * The height of a tile in pixels. - */ - tileHeight?: integer; - /** - * The width of the map in tiles. - */ - width?: integer; - /** - * The height of the map in tiles. - */ - height?: integer; - /** - * 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've 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. - */ - insertNull?: boolean; - }; - - } - - namespace Time { - type TimerEventConfig = { - /** - * The delay after which the Timer Event should fire, in milliseconds. - */ - delay?: number; - /** - * The total number of times the Timer Event will repeat before finishing. - */ - repeat?: number; - /** - * `true` if the Timer Event should repeat indefinitely. - */ - loop?: boolean; - /** - * The callback which will be called when the Timer Event fires. - */ - callback?: Function; - /** - * The scope (`this` object) with which to invoke the `callback`. - */ - callbackScope?: any; - /** - * Additional arguments to be passed to the `callback`. - */ - args?: any[]; - /** - * The scale of the elapsed time. - */ - timeScale?: number; - /** - * The initial elapsed time in milliseconds. Useful if you want a long duration with repeat, but for the first loop to fire quickly. - */ - startAt?: number; - /** - * `true` if the Timer Event should be paused. - */ - paused?: boolean; - }; - - } - - namespace Tweens { - type TweenConfigDefaults = { - /** - * The object, or an array of objects, to run the tween on. - */ - targets: object | object[]; - /** - * The number of milliseconds to delay before the tween will start. - */ - delay?: number; - /** - * The duration of the tween in milliseconds. - */ - duration?: number; - /** - * The easing equation to use for the tween. - */ - ease?: string; - /** - * Optional easing parameters. - */ - easeParams?: any[]; - /** - * The number of milliseconds to hold the tween for before yoyo'ing. - */ - hold?: number; - /** - * The number of times to repeat the tween. - */ - repeat?: number; - /** - * The number of milliseconds to pause before a tween will repeat. - */ - repeatDelay?: number; - /** - * Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. - */ - yoyo?: boolean; - /** - * Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. - */ - flipX?: boolean; - /** - * Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. - */ - flipY?: boolean; - }; - - /** - * A Tween Event. - */ - type Event = string; - - type GetActiveCallback = (target: any, key: string, value: number, targetIndex: integer, totalTargets: integer, tween: Phaser.Tweens.Tween)=>void; - - type GetEndCallback = (target: any, key: string, value: number, targetIndex: integer, totalTargets: integer, tween: Phaser.Tweens.Tween)=>void; - - type GetStartCallback = (target: any, key: string, value: number, targetIndex: integer, totalTargets: integer, tween: Phaser.Tweens.Tween)=>void; - - type NumberTweenBuilderConfig = { - /** - * The start number. - */ - from?: number; - /** - * The end number. - */ - to?: number; - /** - * The number of milliseconds to delay before the tween will start. - */ - delay?: number; - /** - * The duration of the tween in milliseconds. - */ - duration?: number; - /** - * The easing equation to use for the tween. - */ - ease?: string | Function; - /** - * Optional easing parameters. - */ - easeParams?: any[]; - /** - * The number of milliseconds to hold the tween for before yoyo'ing. - */ - hold?: number; - /** - * The number of times to repeat the tween. - */ - repeat?: number; - /** - * The number of milliseconds to pause before a tween will repeat. - */ - repeatDelay?: number; - /** - * Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. - */ - yoyo?: boolean; - /** - * Used when the Tween is part of a Timeline. - */ - offset?: number | Function | object | any[]; - /** - * The time the tween will wait before the onComplete event is dispatched once it has completed, in ms. - */ - completeDelay?: number | Function | object | any[]; - /** - * The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once. - */ - loop?: number | Function | object | any[]; - /** - * The time the tween will pause before starting either a yoyo or returning to the start for a repeat. - */ - loopDelay?: number | Function | object | any[]; - /** - * Does the tween start in a paused state (true) or playing (false)? - */ - paused?: boolean; - /** - * Use frames or milliseconds? - */ - useFrames?: boolean; - /** - * Scope (this) for the callbacks. The default scope is the tween. - */ - callbackScope?: any; - /** - * A function to call when the tween completes. - */ - onComplete?: Phaser.Types.Tweens.TweenOnCompleteCallback; - /** - * Additional parameters to pass to `onComplete`. - */ - onCompleteParams?: any[]; - /** - * Scope (this) for `onComplete`. - */ - onCompleteScope?: any; - /** - * A function to call each time the tween loops. - */ - onLoop?: Phaser.Types.Tweens.TweenOnLoopCallback; - /** - * Additional parameters to pass to `onLoop`. - */ - onLoopParams?: any[]; - /** - * Scope (this) for `onLoop`. - */ - onLoopScope?: any; - /** - * A function to call each time the tween repeats. Called once per property per target. - */ - onRepeat?: Phaser.Types.Tweens.TweenOnRepeatCallback; - /** - * Additional parameters to pass to `onRepeat`. - */ - onRepeatParams?: any[]; - /** - * Scope (this) for `onRepeat`. - */ - onRepeatScope?: any; - /** - * A function to call when the tween starts. - */ - onStart?: Phaser.Types.Tweens.TweenOnStartCallback; - /** - * Additional parameters to pass to `onStart`. - */ - onStartParams?: any[]; - /** - * Scope (this) for `onStart`. - */ - onStartScope?: any; - /** - * A function to call each time the tween steps. Called once per property per target. - */ - onUpdate?: Phaser.Types.Tweens.TweenOnUpdateCallback; - /** - * Additional parameters to pass to `onUpdate`. - */ - onUpdateParams?: any[]; - /** - * Scope (this) for `onUpdate`. - */ - onUpdateScope?: any; - /** - * A function to call each time the tween yoyos. Called once per property per target. - */ - onYoyo?: Phaser.Types.Tweens.TweenOnYoyoCallback; - /** - * Additional parameters to pass to `onYoyo`. - */ - onYoyoParams?: any[]; - /** - * Scope (this) for `onYoyo`. - */ - onYoyoScope?: any; - }; - - type StaggerConfig = { - /** - * The value to start the stagger from. Can be used as a way to offset the stagger while still using a range for the value. - */ - start?: number; - /** - * An ease to apply across the staggered values. Can either be a string, such as 'sine.inout', or a function. - */ - ease?: string | Function; - /** - * The index to start the stagger from. Can be the strings `first`, `last` or `center`, or an integer representing the stagger position. - */ - from?: string | integer; - /** - * Set the stagger to run across a grid by providing an array where element 0 is the width of the grid and element 1 is the height. Combine with the 'from' property to control direction. - */ - grid?: integer[]; - }; - - type TimelineBuilderConfig = { - /** - * An array of tween configuration objects to create and add into the new Timeline. If this doesn't exist or is empty, the Timeline will start off paused and none of the other configuration settings will be read. If it's a function, it will be called and its return value will be used as the array. - */ - tweens?: Phaser.Types.Tweens.TweenBuilderConfig[] | object[] | Function; - /** - * An array (or function which returns one) of default targets to which to apply the Timeline. Each individual Tween configuration can override this value. - */ - targets?: any; - /** - * If specified, each Tween in the Timeline will get an equal portion of this duration, usually in milliseconds, by default. Each individual Tween configuration can override the Tween's duration. - */ - totalDuration?: number; - /** - * If `totalDuration` is not specified, the default duration, usually in milliseconds, of each Tween which will be created. Each individual Tween configuration can override the Tween's duration. - */ - duration?: number; - /** - * The number of milliseconds to delay before the tween will start. Each individual Tween configuration can override this value. - */ - delay?: number; - /** - * Optional easing parameters. Each individual Tween configuration can override this value. - */ - easeParams?: any[]; - /** - * The easing equation to use for each tween. Each individual Tween configuration can override this value. - */ - ease?: string | Function; - /** - * The number of milliseconds to hold each tween before yoyo'ing. Each individual Tween configuration can override this value. - */ - hold?: number; - /** - * The number of times to repeat each tween. Each individual Tween configuration can override this value. - */ - repeat?: integer; - /** - * The number of milliseconds to pause before each tween will repeat. Each individual Tween configuration can override this value. - */ - repeatDelay?: number; - /** - * Should each tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. Each individual Tween configuration can override this value. - */ - yoyo?: boolean; - /** - * Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. Each individual Tween configuration can override this value. - */ - flipX?: boolean; - /** - * Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. Each individual Tween configuration can override this value. - */ - flipY?: boolean; - /** - * If specified, the time to wait, usually in milliseconds, before the Timeline completes. - */ - completeDelay?: number | Function | object | any[]; - /** - * How many times the Timeline should loop, or -1 to loop indefinitely. - */ - loop?: number | Function | object | any[]; - /** - * The time, usually in milliseconds, between each loop. - */ - loopDelay?: number | Function | object | any[]; - /** - * If `true`, the Timeline will start paused. - */ - paused?: boolean; - /** - * If `true`, all duration in the Timeline will be in frames instead of milliseconds. - */ - useFrames?: boolean; - /** - * The default scope (`this` value) to use for each callback registered by the Timeline Builder. If not specified, the Timeline itself will be used. - */ - callbackScope?: any; - /** - * If specified, the `onStart` callback for the Timeline, called every time it starts playing. - */ - onStart?: Phaser.Types.Tweens.TimelineOnStartCallback; - /** - * The scope (`this` value) to use for the `onStart` callback. If not specified, the `callbackScope` will be used. - */ - onStartScope?: any; - /** - * Additional arguments to pass to the `onStart` callback. The Timeline will always be the first argument. - */ - onStartParams?: any[]; - /** - * If specified, the `onUpdate` callback for the Timeline, called every frame it's active, regardless of its Tweens. - */ - onUpdate?: Phaser.Types.Tweens.TimelineOnUpdateCallback; - /** - * The scope (`this` value) to use for the `onUpdate` callback. If not specified, the `callbackScope` will be used. - */ - onUpdateScope?: any; - /** - * Additional arguments to pass to the `onUpdate` callback. The Timeline will always be the first argument. - */ - onUpdateParams?: any[]; - /** - * If specified, the `onLoop` callback for the Timeline, called every time it loops. - */ - onLoop?: Phaser.Types.Tweens.TimelineOnLoopCallback; - /** - * The scope (`this` value) to use for the `onLoop` callback. If not specified, the `callbackScope` will be used. - */ - onLoopScope?: any; - /** - * Additional arguments to pass to the `onLoop` callback. The Timeline will always be the first argument. - */ - onLoopParams?: any[]; - /** - * If specified, the `onYoyo` callback for the Timeline, called every time it yoyos. - */ - onYoyo?: Phaser.Types.Tweens.TimelineOnYoyoCallback; - /** - * The scope (`this` value) to use for the `onYoyo` callback. If not specified, the `callbackScope` will be used. - */ - onYoyoScope?: any; - /** - * Additional arguments to pass to the `onYoyo` callback. The first argument will always be `null`, while the Timeline will always be the second argument. - */ - onYoyoParams?: any[]; - /** - * If specified, the `onComplete` callback for the Timeline, called after it completes. - */ - onComplete?: Phaser.Types.Tweens.TimelineOnCompleteCallback; - /** - * The scope (`this` value) to use for the `onComplete` callback. If not specified, the `callbackScope` will be used. - */ - onCompleteScope?: any; - /** - * Additional arguments to pass to the `onComplete` callback. The Timeline will always be the first argument. - */ - onCompleteParams?: any[]; - }; - - type TimelineOnCompleteCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; - - type TimelineOnLoopCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; - - type TimelineOnStartCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; - - type TimelineOnUpdateCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; - - type TimelineOnYoyoCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; - - type TweenBuilderConfig = { - /** - * The object, or an array of objects, to run the tween on. - */ - targets: any; - /** - * The number of milliseconds to delay before the tween will start. - */ - delay?: number | Function; - /** - * The duration of the tween in milliseconds. - */ - duration?: number; - /** - * The easing equation to use for the tween. - */ - ease?: string | Function; - /** - * Optional easing parameters. - */ - easeParams?: any[]; - /** - * The number of milliseconds to hold the tween for before yoyo'ing. - */ - hold?: number; - /** - * The number of times each property tween repeats. - */ - repeat?: number; - /** - * The number of milliseconds to pause before a repeat. - */ - repeatDelay?: number; - /** - * Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. - */ - yoyo?: boolean; - /** - * Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. - */ - flipX?: boolean; - /** - * Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. - */ - flipY?: boolean; - /** - * Used when the Tween is part of a Timeline. - */ - offset?: number | Function | object | any[]; - /** - * The time the tween will wait before the onComplete event is dispatched once it has completed, in ms. - */ - completeDelay?: number | Function | object | any[]; - /** - * The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once. - */ - loop?: number | Function | object | any[]; - /** - * The time the tween will pause before starting either a yoyo or returning to the start for a repeat. - */ - loopDelay?: number | Function | object | any[]; - /** - * Does the tween start in a paused state (true) or playing (false)? - */ - paused?: boolean; - /** - * The properties to tween. - */ - props?: {[key: string]: (number|string|Phaser.Types.Tweens.GetEndCallback|Phaser.Types.Tweens.TweenPropConfig)}; - /** - * Use frames or milliseconds? - */ - useFrames?: boolean; - /** - * Scope (this) for the callbacks. The default scope is the tween. - */ - callbackScope?: any; - /** - * A function to call when the tween completes. - */ - onComplete?: Phaser.Types.Tweens.TweenOnCompleteCallback; - /** - * Additional parameters to pass to `onComplete`. - */ - onCompleteParams?: any[]; - /** - * Scope (this) for `onComplete`. - */ - onCompleteScope?: any; - /** - * A function to call each time the tween loops. - */ - onLoop?: Phaser.Types.Tweens.TweenOnLoopCallback; - /** - * Additional parameters to pass to `onLoop`. - */ - onLoopParams?: any[]; - /** - * Scope (this) for `onLoop`. - */ - onLoopScope?: any; - /** - * A function to call each time the tween repeats. Called once per property per target. - */ - onRepeat?: Phaser.Types.Tweens.TweenOnRepeatCallback; - /** - * Additional parameters to pass to `onRepeat`. - */ - onRepeatParams?: any[]; - /** - * Scope (this) for `onRepeat`. - */ - onRepeatScope?: any; - /** - * A function to call when the tween starts playback, after any delays have expired. - */ - onStart?: Phaser.Types.Tweens.TweenOnStartCallback; - /** - * Additional parameters to pass to `onStart`. - */ - onStartParams?: any[]; - /** - * Scope (this) for `onStart`. - */ - onStartScope?: any; - /** - * A function to call each time the tween steps. Called once per property per target. - */ - onUpdate?: Phaser.Types.Tweens.TweenOnUpdateCallback; - /** - * Additional parameters to pass to `onUpdate`. - */ - onUpdateParams?: any[]; - /** - * Scope (this) for `onUpdate`. - */ - onUpdateScope?: any; - /** - * A function to call each time the tween yoyos. Called once per property per target. - */ - onYoyo?: Phaser.Types.Tweens.TweenOnYoyoCallback; - /** - * Additional parameters to pass to `onYoyo`. - */ - onYoyoParams?: any[]; - /** - * Scope (this) for `onYoyo`. - */ - onYoyoScope?: any; - /** - * A function to call when the tween becomes active within the Tween Manager. - */ - onActive?: Phaser.Types.Tweens.TweenOnActiveCallback; - /** - * Additional parameters to pass to `onActive`. - */ - onActiveParams?: any[]; - /** - * Scope (this) for `onActive`. - */ - onActiveScope?: any; - }; - - type TweenDataConfig = { - /** - * The target to tween. - */ - target: any; - /** - * The target index within the Tween targets array. - */ - index: integer; - /** - * The property of the target being tweened. - */ - key: string; - /** - * If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. - */ - getActiveValue: Phaser.Types.Tweens.GetActiveCallback; - /** - * The returned value sets what the property will be at the END of the Tween. - */ - getEndValue: Phaser.Types.Tweens.GetEndCallback; - /** - * The returned value sets what the property will be at the START of the Tween. - */ - getStartValue: Phaser.Types.Tweens.GetStartCallback; - /** - * The ease function this tween uses. - */ - ease: Function; - /** - * Duration of the tween in ms/frames, excludes time for yoyo or repeats. - */ - duration?: number; - /** - * The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) - */ - totalDuration?: number; - /** - * Time in ms/frames before tween will start. - */ - delay?: number; - /** - * Cause the tween to return back to its start value after hold has expired. - */ - yoyo?: boolean; - /** - * Time in ms/frames the tween will pause before running the yoyo or starting a repeat. - */ - hold?: number; - /** - * Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - */ - repeat?: integer; - /** - * Time in ms/frames before the repeat will start. - */ - repeatDelay?: number; - /** - * Automatically call toggleFlipX when the TweenData yoyos or repeats - */ - flipX?: boolean; - /** - * Automatically call toggleFlipY when the TweenData yoyos or repeats - */ - flipY?: boolean; - /** - * Between 0 and 1 showing completion of this TweenData. - */ - progress?: number; - /** - * Delta counter - */ - elapsed?: number; - /** - * How many repeats are left to run? - */ - repeatCounter?: integer; - /** - * The property value at the start of the ease. - */ - start?: number; - /** - * The current propety value. - */ - current?: number; - /** - * The previous property value. - */ - previous?: number; - /** - * The property value at the end of the ease. - */ - end?: number; - /** - * Time duration 1. - */ - t1?: number; - /** - * Time duration 2. - */ - t2?: number; - /** - * LoadValue generation functions. - */ - gen?: Phaser.Types.Tweens.TweenDataGenConfig; - /** - * TWEEN_CONST.CREATED - */ - state?: integer; - }; - - type TweenDataGenConfig = { - /** - * Time in ms/frames before tween will start. - */ - delay: Function; - /** - * Duration of the tween in ms/frames, excludes time for yoyo or repeats. - */ - duration: Function; - /** - * Time in ms/frames the tween will pause before running the yoyo or starting a repeat. - */ - hold: Function; - /** - * Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - */ - repeat: Function; - /** - * Time in ms/frames before the repeat will start. - */ - repeatDelay: Function; - }; - - type TweenOnActiveCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; - - type TweenOnCompleteCallback = (tween: Phaser.Tweens.Tween, targets: any[], ...param: any[])=>void; - - type TweenOnLoopCallback = (tween: Phaser.Tweens.Tween, targets: any[], ...param: any[])=>void; - - type TweenOnRepeatCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; - - type TweenOnStartCallback = (tween: Phaser.Tweens.Tween, targets: any[], ...param: any[])=>void; - - type TweenOnUpdateCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; - - type TweenOnYoyoCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; - - type TweenPropConfig = { - /** - * What the property will be at the END of the Tween. - */ - value?: number | string | Phaser.Types.Tweens.GetEndCallback | Phaser.Types.Tweens.TweenPropConfig; - /** - * What the property will be set to immediately when this tween becomes active. - */ - getActive?: Phaser.Types.Tweens.GetActiveCallback; - /** - * What the property will be at the END of the Tween. - */ - getEnd?: Phaser.Types.Tweens.GetEndCallback; - /** - * What the property will be at the START of the Tween. - */ - getStart?: Phaser.Types.Tweens.GetStartCallback; - /** - * The ease function this tween uses. - */ - ease?: string | Function; - /** - * Time in ms/frames before tween will start. - */ - delay?: number; - /** - * Duration of the tween in ms/frames. - */ - duration?: number; - /** - * Determines whether the tween should return back to its start value after hold has expired. - */ - yoyo?: boolean; - /** - * Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. - */ - hold?: number; - /** - * Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - */ - repeat?: number; - /** - * Time in ms/frames before the repeat will start. - */ - repeatDelay?: number; - /** - * Should toggleFlipX be called when yoyo or repeat happens? - */ - flipX?: boolean; - /** - * Should toggleFlipY be called when yoyo or repeat happens? - */ - flipY?: boolean; - }; - - } - - } - - namespace Physics { - namespace Arcade { - /** - * An Arcade Physics Image is an Image with an Arcade Physics body and related components. - * The body can be dynamic or static. - * - * The main difference between an Arcade Image and an Arcade Sprite is that you cannot animate an Arcade Image. - */ - class Image extends Phaser.GameObjects.Image implements Phaser.Physics.Arcade.Components.Acceleration, Phaser.Physics.Arcade.Components.Angular, Phaser.Physics.Arcade.Components.Bounce, Phaser.Physics.Arcade.Components.Debug, Phaser.Physics.Arcade.Components.Drag, Phaser.Physics.Arcade.Components.Enable, Phaser.Physics.Arcade.Components.Friction, Phaser.Physics.Arcade.Components.Gravity, Phaser.Physics.Arcade.Components.Immovable, Phaser.Physics.Arcade.Components.Mass, Phaser.Physics.Arcade.Components.Size, Phaser.Physics.Arcade.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); - - /** - * This Game Object's Physics Body. - */ - body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. - * @param x The horizontal acceleration - * @param y The vertical acceleration Default x. - */ - setAcceleration(x: number, y?: number): this; - - /** - * Sets the body's horizontal acceleration. - * @param value The horizontal acceleration - */ - setAccelerationX(value: number): this; - - /** - * Sets the body's vertical acceleration. - * @param value The vertical acceleration - */ - setAccelerationY(value: number): this; - - /** - * Sets the angular velocity of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * @param value The amount of angular velocity. - */ - setAngularVelocity(value: number): this; - - /** - * Sets the angular acceleration of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * @param value The amount of angular acceleration. - */ - setAngularAcceleration(value: number): this; - - /** - * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. - * @param value The amount of drag. - */ - setAngularDrag(value: number): this; - - /** - * Sets the bounce values of this body. - * - * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. - * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. - * @param x The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - * @param y The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. Default x. - */ - setBounce(x: number, y?: number): this; - - /** - * Sets the horizontal bounce value for this body. - * @param value The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - */ - setBounceX(value: number): this; - - /** - * Sets the vertical bounce value for this body. - * @param value The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. - */ - setBounceY(value: number): this; - - /** - * Sets whether this Body collides with the world boundary. - * - * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. - * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. - * @param bounceX If given this will be replace the `worldBounce.x` value. - * @param bounceY If given this will be replace the `worldBounce.y` value. - */ - setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): this; - - /** - * Sets the debug values of this body. - * - * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. - * Note that there is a performance cost in drawing debug displays. It should never be used in production. - * @param showBody Set to `true` to have this body render its outline to the debug display. - * @param showVelocity Set to `true` to have this body render a velocity marker to the debug display. - * @param bodyColor The color of the body outline when rendered to the debug display. - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): this; - - /** - * Sets the color of the body outline when it renders to the debug display. - * @param value The color of the body outline when rendered to the debug display. - */ - setDebugBodyColor(value: number): this; - - /** - * Set to `true` to have this body render its outline to the debug display. - */ - debugShowBody: boolean; - - /** - * Set to `true` to have this body render a velocity marker to the debug display. - */ - debugShowVelocity: boolean; - - /** - * The color of the body outline when it renders to the debug display. - */ - debugBodyColor: number; - - /** - * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param x The amount of horizontal drag to apply. - * @param y The amount of vertical drag to apply. Default x. - */ - setDrag(x: number, y?: number): this; - - /** - * Sets the body's horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param value The amount of horizontal drag to apply. - */ - setDragX(value: number): this; - - /** - * Sets the body's vertical drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param value The amount of vertical drag to apply. - */ - setDragY(value: number): this; - - /** - * If this Body is using `drag` for deceleration this function controls how the drag is applied. - * If set to `true` drag will use a damping effect rather than a linear approach. If you are - * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in - * the game Asteroids) then you will get a far smoother and more visually correct deceleration - * by using damping, avoiding the axis-drift that is prone with linear deceleration. - * - * If you enable this property then you should use far smaller `drag` values than with linear, as - * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow - * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. - * @param value `true` to use damping for deceleration, or `false` to use linear deceleration. - */ - setDamping(value: boolean): this; - - /** - * Enables this Game Object's Body. - * @param reset Also reset the Body and place it at (x, y). - * @param x The horizontal position to place the Game Object and Body. - * @param y The horizontal position to place the Game Object and Body. - * @param enableGameObject Also activate this Game Object. - * @param showGameObject Also show this Game Object. - */ - enableBody(reset: boolean, x: number, y: number, enableGameObject: boolean, showGameObject: boolean): this; - - /** - * Stops and disables this Game Object's Body. - * @param disableGameObject Also deactivate this Game Object. Default false. - * @param hideGameObject Also hide this Game Object. Default false. - */ - disableBody(disableGameObject?: boolean, hideGameObject?: boolean): this; - - /** - * 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. - */ - refreshBody(): this; - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of horizontal friction to apply. - * @param y The amount of vertical friction to apply. Default x. - */ - setFriction(x: number, y?: number): this; - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of friction to apply. - */ - setFrictionX(x: number): this; - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of friction to apply. - */ - setFrictionY(x: number): this; - - /** - * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. - * - * If only one value is provided, this value will be used for both the X and Y axis. - * @param x The gravitational force to be applied to the X-axis. - * @param y The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. Default x. - */ - setGravity(x: number, y?: number): this; - - /** - * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. - * @param x The gravitational force to be applied to the X-axis. - */ - setGravityX(x: number): this; - - /** - * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. - * @param y The gravitational force to be applied to the Y-axis. - */ - setGravityY(y: number): this; - - /** - * Sets Whether this Body can be moved by collisions with another Body. - * @param value Sets if this body can be moved by collisions with another Body. Default true. - */ - setImmovable(value?: boolean): this; - - /** - * Sets the mass of the physics body - * @param value New value for the mass of the body. - */ - setMass(value: number): this; - - /** - * Sets the body offset. This allows you to adjust the difference between the center of the body - * and the x and y coordinates of the parent Game Object. - * @param x The amount to offset the body from the parent Game Object along the x-axis. - * @param y The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. Default x. - */ - setOffset(x: number, y?: number): this; - - /** - * Sets this physics body to use a circle for collision instead of a rectangle. - * @param radius The radius of the physics body, in pixels. - * @param offsetX The amount to offset the body from the parent Game Object along the x-axis. - * @param offsetY The amount to offset the body from the parent Game Object along the y-axis. - */ - setCircle(radius: number, offsetX?: number, offsetY?: number): this; - - /** - * Sets the velocity of the Body. - * @param x The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. - * @param y The vertical velocity of the body. Positive values move the body down, while negative values move it up. Default x. - */ - setVelocity(x: number, y?: number): this; - - /** - * Sets the horizontal component of the body's velocity. - * - * Positive values move the body to the right, while negative values move it to the left. - * @param x The new horizontal velocity. - */ - setVelocityX(x: number): this; - - /** - * Sets the vertical component of the body's velocity. - * - * Positive values move the body down, while negative values move it up. - * @param y The new vertical velocity of the body. - */ - setVelocityY(y: number): this; - - /** - * Sets the maximum velocity of the body. - * @param x The new maximum horizontal velocity. - * @param y The new maximum vertical velocity. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - - } - - /** - * The Arcade Physics Plugin belongs to a Scene and sets up and manages the Scene's physics simulation. - * It also holds some useful methods for moving and rotating Arcade Physics Bodies. - * - * You can access it from within a Scene using `this.physics`. - * - * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable - * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. - * The separation that stops two objects penetrating may create a new penetration against a different object. If you - * require a high level of stability please consider using an alternative physics system, such as Matter.js. - */ - class ArcadePhysics { - /** - * - * @param scene The Scene that this Plugin belongs to. - */ - constructor(scene: Phaser.Scene); - - /** - * The Scene that this Plugin belongs to. - */ - scene: Phaser.Scene; - - /** - * The Scene's Systems. - */ - systems: Phaser.Scenes.Systems; - - /** - * A configuration object. Union of the `physics.arcade.*` properties of the GameConfig and SceneConfig objects. - */ - config: object; - - /** - * The physics simulation. - */ - world: Phaser.Physics.Arcade.World; - - /** - * An object holding the Arcade Physics factory methods. - */ - add: Phaser.Physics.Arcade.Factory; - - /** - * Creates the physics configuration for the current Scene. - */ - getConfig(): object; - - /** - * Tests if Game Objects overlap. See {@link Phaser.Physics.Arcade.World#overlap} - * @param object1 The first object or array of objects to check. - * @param object2 The second object or array of objects to check, or `undefined`. - * @param collideCallback An optional callback function that is called if the objects collide. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - overlap(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * Performs a collision check and separation between the two physics enabled objects given, which can be single - * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. - * - * If you don't require separation then use {@link #overlap} instead. - * - * If two Groups or arrays are passed, each member of one will be tested against each member of the other. - * - * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. - * - * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. - * - * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding - * objects are passed to it. - * - * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable - * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. - * The separation that stops two objects penetrating may create a new penetration against a different object. If you - * require a high level of stability please consider using an alternative physics system, such as Matter.js. - * @param object1 The first object or array of objects to check. - * @param object2 The second object or array of objects to check, or `undefined`. - * @param collideCallback An optional callback function that is called if the objects collide. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - collide(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. - * - * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for collision with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions - * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * - * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have - * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the - * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on - * dynamic maps, this method can prove very useful. - * @param sprite The first object to check for collision. - * @param tiles An array of Tiles to check for collision against. - * @param collideCallback An optional callback function that is called if the objects collide. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - collideTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. - * - * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap - * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * @param sprite The first object to check for collision. - * @param tiles An array of Tiles to check for collision against. - * @param collideCallback An optional callback function that is called if the objects overlap. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - overlapTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * Pauses the simulation. - */ - pause(): Phaser.Physics.Arcade.World; - - /** - * Resumes the simulation (if paused). - */ - resume(): Phaser.Physics.Arcade.World; - - /** - * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) - * - * You must give a maximum speed value, beyond which the game object won't go any faster. - * - * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. - * Note: The game object doesn't stop moving once it reaches the destination coordinates. - * @param gameObject Any Game Object with an Arcade Physics body. - * @param x The x coordinate to accelerate towards. - * @param y The y coordinate to accelerate towards. - * @param speed The acceleration (change in speed) in pixels per second squared. Default 60. - * @param xSpeedMax The maximum x velocity the game object can reach. Default 500. - * @param ySpeedMax The maximum y velocity the game object can reach. Default 500. - */ - accelerateTo(gameObject: Phaser.GameObjects.GameObject, x: number, y: number, speed?: number, xSpeedMax?: number, ySpeedMax?: number): number; - - /** - * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) - * - * You must give a maximum speed value, beyond which the game object won't go any faster. - * - * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. - * Note: The game object doesn't stop moving once it reaches the destination coordinates. - * @param gameObject Any Game Object with an Arcade Physics body. - * @param destination The Game Object to move towards. Can be any object but must have visible x/y properties. - * @param speed The acceleration (change in speed) in pixels per second squared. Default 60. - * @param xSpeedMax The maximum x velocity the game object can reach. Default 500. - * @param ySpeedMax The maximum y velocity the game object can reach. Default 500. - */ - accelerateToObject(gameObject: Phaser.GameObjects.GameObject, destination: Phaser.GameObjects.GameObject, speed?: number, xSpeedMax?: number, ySpeedMax?: number): number; - - /** - * Finds the Body or Game Object closest to a source point or object. - * - * If a `targets` argument is passed, this method finds the closest of those. - * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. - * - * If no `targets` argument is passed, this method finds the closest Dynamic Body. - * - * If two or more targets are the exact same distance from the source point, only the first target - * is returned. - * @param source Any object with public `x` and `y` properties, such as a Game Object or Geometry object. - * @param targets The targets. - */ - closest(source: any, targets?: Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[] | Phaser.GameObjects.GameObject[]): Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody | Phaser.GameObjects.GameObject; - - /** - * Finds the Body or Game Object farthest from a source point or object. - * - * If a `targets` argument is passed, this method finds the farthest of those. - * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. - * - * If no `targets` argument is passed, this method finds the farthest Dynamic Body. - * - * If two or more targets are the exact same distance from the source point, only the first target - * is returned. - * @param source Any object with public `x` and `y` properties, such as a Game Object or Geometry object. - * @param targets The targets. - */ - furthest(source: any, targets?: Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[] | Phaser.GameObjects.GameObject[]): Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody | Phaser.GameObjects.GameObject; - - /** - * Move the given display object towards the x/y coordinates at a steady velocity. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * @param gameObject Any Game Object with an Arcade Physics body. - * @param x The x coordinate to move towards. - * @param y The y coordinate to move towards. - * @param speed The speed it will move, in pixels per second (default is 60 pixels/sec) Default 60. - * @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. Default 0. - */ - moveTo(gameObject: Phaser.GameObjects.GameObject, x: number, y: number, speed?: number, maxTime?: number): number; - - /** - * Move the given display object towards the destination object at a steady velocity. - * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * @param gameObject Any Game Object with an Arcade Physics body. - * @param destination Any object with public `x` and `y` properties, such as a Game Object or Geometry object. - * @param speed The speed it will move, in pixels per second (default is 60 pixels/sec) Default 60. - * @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. Default 0. - */ - moveToObject(gameObject: Phaser.GameObjects.GameObject, destination: object, speed?: number, maxTime?: number): number; - - /** - * Given the angle (in degrees) and speed calculate the velocity and return it as a vector, or set it to the given vector object. - * One way to use this is: velocityFromAngle(angle, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. - * @param angle The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * @param speed The speed it will move, in pixels per second squared. Default 60. - * @param vec2 The Vector2 in which the x and y properties will be set to the calculated velocity. - */ - velocityFromAngle(angle: number, speed?: number, vec2?: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * Given the rotation (in radians) and speed calculate the velocity and return it as a vector, or set it to the given vector object. - * One way to use this is: velocityFromRotation(rotation, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. - * @param rotation The angle in radians. - * @param speed The speed it will move, in pixels per second squared Default 60. - * @param vec2 The Vector2 in which the x and y properties will be set to the calculated velocity. - */ - velocityFromRotation(rotation: number, speed?: number, vec2?: Phaser.Math.Vector2): Phaser.Math.Vector2; - - /** - * This method will search the given rectangular area and return an array of all physics bodies that - * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. - * - * A body only has to intersect with the search area to be considered, it doesn't have to be fully - * contained within it. - * - * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, - * otherwise the search is O(N) for Dynamic Bodies. - * @param x The top-left x coordinate of the area to search within. - * @param y The top-left y coordinate of the area to search within. - * @param width The width of the area to search within. - * @param height The height of the area to search within. - * @param includeDynamic Should the search include Dynamic Bodies? Default true. - * @param includeStatic Should the search include Static Bodies? Default false. - */ - overlapRect(x: number, y: number, width: number, height: number, includeDynamic?: boolean, includeStatic?: boolean): Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[]; - - /** - * This method will search the given circular area and return an array of all physics bodies that - * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. - * - * A body only has to intersect with the search area to be considered, it doesn't have to be fully - * contained within it. - * - * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, - * otherwise the search is O(N) for Dynamic Bodies. - * @param x The x coordinate of the center of the area to search within. - * @param y The y coordinate of the center of the area to search within. - * @param radius The radius of the area to search within. - * @param includeDynamic Should the search include Dynamic Bodies? Default true. - * @param includeStatic Should the search include Static Bodies? Default false. - */ - overlapCirc(x: number, y: number, radius: number, includeDynamic?: boolean, includeStatic?: boolean): Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[]; - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - */ - shutdown(): void; - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - */ - destroy(): void; - - } - - /** - * An Arcade Physics Sprite is a Sprite with an Arcade Physics body and related components. - * The body can be dynamic or static. - * - * The main difference between an Arcade Sprite and an Arcade Image is that you cannot animate an Arcade Image. - * If you do not require animation then you can safely use Arcade Images instead of Arcade Sprites. - */ - class Sprite extends Phaser.GameObjects.Sprite implements Phaser.Physics.Arcade.Components.Acceleration, Phaser.Physics.Arcade.Components.Angular, Phaser.Physics.Arcade.Components.Bounce, Phaser.Physics.Arcade.Components.Debug, Phaser.Physics.Arcade.Components.Drag, Phaser.Physics.Arcade.Components.Enable, Phaser.Physics.Arcade.Components.Friction, Phaser.Physics.Arcade.Components.Gravity, Phaser.Physics.Arcade.Components.Immovable, Phaser.Physics.Arcade.Components.Mass, Phaser.Physics.Arcade.Components.Size, Phaser.Physics.Arcade.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); - - /** - * This Game Object's Physics Body. - */ - body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. - * @param x The horizontal acceleration - * @param y The vertical acceleration Default x. - */ - setAcceleration(x: number, y?: number): this; - - /** - * Sets the body's horizontal acceleration. - * @param value The horizontal acceleration - */ - setAccelerationX(value: number): this; - - /** - * Sets the body's vertical acceleration. - * @param value The vertical acceleration - */ - setAccelerationY(value: number): this; - - /** - * Sets the angular velocity of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * @param value The amount of angular velocity. - */ - setAngularVelocity(value: number): this; - - /** - * Sets the angular acceleration of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * @param value The amount of angular acceleration. - */ - setAngularAcceleration(value: number): this; - - /** - * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. - * @param value The amount of drag. - */ - setAngularDrag(value: number): this; - - /** - * Sets the bounce values of this body. - * - * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. - * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. - * @param x The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - * @param y The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. Default x. - */ - setBounce(x: number, y?: number): this; - - /** - * Sets the horizontal bounce value for this body. - * @param value The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - */ - setBounceX(value: number): this; - - /** - * Sets the vertical bounce value for this body. - * @param value The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. - */ - setBounceY(value: number): this; - - /** - * Sets whether this Body collides with the world boundary. - * - * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. - * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. - * @param bounceX If given this will be replace the `worldBounce.x` value. - * @param bounceY If given this will be replace the `worldBounce.y` value. - */ - setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): this; - - /** - * Sets the debug values of this body. - * - * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. - * Note that there is a performance cost in drawing debug displays. It should never be used in production. - * @param showBody Set to `true` to have this body render its outline to the debug display. - * @param showVelocity Set to `true` to have this body render a velocity marker to the debug display. - * @param bodyColor The color of the body outline when rendered to the debug display. - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): this; - - /** - * Sets the color of the body outline when it renders to the debug display. - * @param value The color of the body outline when rendered to the debug display. - */ - setDebugBodyColor(value: number): this; - - /** - * Set to `true` to have this body render its outline to the debug display. - */ - debugShowBody: boolean; - - /** - * Set to `true` to have this body render a velocity marker to the debug display. - */ - debugShowVelocity: boolean; - - /** - * The color of the body outline when it renders to the debug display. - */ - debugBodyColor: number; - - /** - * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param x The amount of horizontal drag to apply. - * @param y The amount of vertical drag to apply. Default x. - */ - setDrag(x: number, y?: number): this; - - /** - * Sets the body's horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param value The amount of horizontal drag to apply. - */ - setDragX(value: number): this; - - /** - * Sets the body's vertical drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param value The amount of vertical drag to apply. - */ - setDragY(value: number): this; - - /** - * If this Body is using `drag` for deceleration this function controls how the drag is applied. - * If set to `true` drag will use a damping effect rather than a linear approach. If you are - * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in - * the game Asteroids) then you will get a far smoother and more visually correct deceleration - * by using damping, avoiding the axis-drift that is prone with linear deceleration. - * - * If you enable this property then you should use far smaller `drag` values than with linear, as - * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow - * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. - * @param value `true` to use damping for deceleration, or `false` to use linear deceleration. - */ - setDamping(value: boolean): this; - - /** - * Enables this Game Object's Body. - * @param reset Also reset the Body and place it at (x, y). - * @param x The horizontal position to place the Game Object and Body. - * @param y The horizontal position to place the Game Object and Body. - * @param enableGameObject Also activate this Game Object. - * @param showGameObject Also show this Game Object. - */ - enableBody(reset: boolean, x: number, y: number, enableGameObject: boolean, showGameObject: boolean): this; - - /** - * Stops and disables this Game Object's Body. - * @param disableGameObject Also deactivate this Game Object. Default false. - * @param hideGameObject Also hide this Game Object. Default false. - */ - disableBody(disableGameObject?: boolean, hideGameObject?: boolean): this; - - /** - * 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. - */ - refreshBody(): this; - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of horizontal friction to apply. - * @param y The amount of vertical friction to apply. Default x. - */ - setFriction(x: number, y?: number): this; - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of friction to apply. - */ - setFrictionX(x: number): this; - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of friction to apply. - */ - setFrictionY(x: number): this; - - /** - * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. - * - * If only one value is provided, this value will be used for both the X and Y axis. - * @param x The gravitational force to be applied to the X-axis. - * @param y The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. Default x. - */ - setGravity(x: number, y?: number): this; - - /** - * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. - * @param x The gravitational force to be applied to the X-axis. - */ - setGravityX(x: number): this; - - /** - * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. - * @param y The gravitational force to be applied to the Y-axis. - */ - setGravityY(y: number): this; - - /** - * Sets Whether this Body can be moved by collisions with another Body. - * @param value Sets if this body can be moved by collisions with another Body. Default true. - */ - setImmovable(value?: boolean): this; - - /** - * Sets the mass of the physics body - * @param value New value for the mass of the body. - */ - setMass(value: number): this; - - /** - * Sets the body offset. This allows you to adjust the difference between the center of the body - * and the x and y coordinates of the parent Game Object. - * @param x The amount to offset the body from the parent Game Object along the x-axis. - * @param y The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. Default x. - */ - setOffset(x: number, y?: number): this; - - /** - * Sets this physics body to use a circle for collision instead of a rectangle. - * @param radius The radius of the physics body, in pixels. - * @param offsetX The amount to offset the body from the parent Game Object along the x-axis. - * @param offsetY The amount to offset the body from the parent Game Object along the y-axis. - */ - setCircle(radius: number, offsetX?: number, offsetY?: number): this; - - /** - * Sets the velocity of the Body. - * @param x The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. - * @param y The vertical velocity of the body. Positive values move the body down, while negative values move it up. Default x. - */ - setVelocity(x: number, y?: number): this; - - /** - * Sets the horizontal component of the body's velocity. - * - * Positive values move the body to the right, while negative values move it to the left. - * @param x The new horizontal velocity. - */ - setVelocityX(x: number): this; - - /** - * Sets the vertical component of the body's velocity. - * - * Positive values move the body down, while negative values move it up. - * @param y The new vertical velocity of the body. - */ - setVelocityY(y: number): this; - - /** - * Sets the maximum velocity of the body. - * @param x The new maximum horizontal velocity. - * @param y The new maximum vertical velocity. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - - } - - /** - * A Dynamic Arcade Body. - * - * Its static counterpart is {@link Phaser.Physics.Arcade.StaticBody}. - */ - class Body { - /** - * - * @param world The Arcade Physics simulation this Body belongs to. - * @param gameObject The Game Object this Body belongs to. - */ - constructor(world: Phaser.Physics.Arcade.World, gameObject: Phaser.GameObjects.GameObject); - - /** - * The Arcade Physics simulation this Body belongs to. - */ - world: Phaser.Physics.Arcade.World; - - /** - * The Game Object this Body belongs to. - */ - gameObject: Phaser.GameObjects.GameObject; - - /** - * Transformations applied to this Body. - */ - transform: object; - - /** - * Whether the Body's boundary is drawn to the debug display. - */ - debugShowBody: boolean; - - /** - * Whether the Body's velocity is drawn to the debug display. - */ - debugShowVelocity: boolean; - - /** - * The color of this Body on the debug display. - */ - debugBodyColor: integer; - - /** - * Whether this Body is updated by the physics simulation. - */ - enable: boolean; - - /** - * Whether this Body's boundary is circular (true) or rectangular (false). - */ - isCircle: boolean; - - /** - * If this Body is circular, this is the unscaled radius of the Body's boundary, as set by setCircle(), in source pixels. - * The true radius is equal to `halfWidth`. - */ - radius: number; - - /** - * The offset of this Body's position from its Game Object's position, in source pixels. - */ - offset: Phaser.Math.Vector2; - - /** - * The position of this Body within the simulation. - */ - position: Phaser.Math.Vector2; - - /** - * The position of this Body during the previous step. - */ - prev: Phaser.Math.Vector2; - - /** - * The position of this Body during the previous frame. - */ - prevFrame: Phaser.Math.Vector2; - - /** - * Whether this Body's `rotation` is affected by its angular acceleration and angular velocity. - */ - allowRotation: boolean; - - /** - * 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 boundary, which is always an axis-aligned rectangle or a circle. - */ - rotation: number; - - /** - * The Body rotation, in degrees, during the previous step. - */ - preRotation: number; - - /** - * The width of the Body boundary, in pixels. - * If the Body is circular, this is also the diameter. - * If you wish to change the width use the `Body.setSize` method. - */ - readonly width: number; - - /** - * The height of the Body boundary, in pixels. - * If the Body is circular, this is also the diameter. - * If you wish to change the height use the `Body.setSize` method. - */ - readonly height: number; - - /** - * The unscaled width of the Body, in source pixels, as set by setSize(). - * The default is the width of the Body's Game Object's texture frame. - */ - sourceWidth: number; - - /** - * The unscaled height of the Body, in source pixels, as set by setSize(). - * The default is the height of the Body's Game Object's texture frame. - */ - sourceHeight: number; - - /** - * Half the Body's width, in pixels. - */ - halfWidth: number; - - /** - * Half the Body's height, in pixels. - */ - halfHeight: number; - - /** - * The center of the Body's boundary. - * The midpoint of its `position` (top-left corner) and its bottom-right corner. - */ - center: Phaser.Math.Vector2; - - /** - * The Body's velocity, in pixels per second. - */ - velocity: Phaser.Math.Vector2; - - /** - * The Body's change in position (due to velocity) at the last step, in pixels. - * - * The size of this value depends on the simulation's step rate. - */ - readonly newVelocity: Phaser.Math.Vector2; - - /** - * The Body's absolute maximum change in position, in pixels per step. - */ - deltaMax: Phaser.Math.Vector2; - - /** - * The Body's change in velocity, in pixels per second squared. - */ - acceleration: Phaser.Math.Vector2; - - /** - * Whether this Body's velocity is affected by its `drag`. - */ - allowDrag: boolean; - - /** - * Absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - */ - drag: Phaser.Math.Vector2 | number; - - /** - * Whether this Body's position is affected by gravity (local or world). - */ - allowGravity: boolean; - - /** - * Acceleration due to gravity (specific to this Body), in pixels per second squared. - * Total gravity is the sum of this vector and the simulation's `gravity`. - */ - gravity: Phaser.Math.Vector2; - - /** - * Rebound following a collision, relative to 1. - */ - bounce: Phaser.Math.Vector2; - - /** - * Rebound following a collision with the world boundary, relative to 1. - * If null, `bounce` is used instead. - */ - worldBounce: Phaser.Math.Vector2; - - /** - * The rectangle used for world boundary collisions. - * - * By default it is set to the world boundary rectangle. Or, if this Body was - * created by a Physics Group, then whatever rectangle that Group defined. - * - * You can also change it by using the `Body.setBoundsRectangle` method. - */ - customBoundsRectangle: Phaser.Geom.Rectangle; - - /** - * Whether the simulation emits a `worldbounds` event when this Body collides with the world boundary (and `collideWorldBounds` is also true). - */ - onWorldBounds: boolean; - - /** - * Whether the simulation emits a `collide` event when this Body collides with another. - */ - onCollide: boolean; - - /** - * Whether the simulation emits an `overlap` event when this Body overlaps with another. - */ - onOverlap: boolean; - - /** - * The Body's absolute maximum velocity, in pixels per second. - * The horizontal and vertical components are applied separately. - */ - maxVelocity: Phaser.Math.Vector2; - - /** - * The maximum speed this Body is allowed to reach, in pixels per second. - * - * If not negative it limits the scalar value of speed. - * - * Any negative value means no maximum is being applied (the default). - */ - maxSpeed: number; - - /** - * If this Body is `immovable` and in motion, `friction` is the proportion of this Body's motion received by the riding Body on each axis, relative to 1. - * The horizontal component (x) is applied only when two colliding Bodies are separated vertically. - * The vertical component (y) is applied only when two colliding Bodies are separated horizontally. - * The default value (1, 0) moves the riding Body horizontally in equal proportion to this Body and vertically not at all. - */ - friction: Phaser.Math.Vector2; - - /** - * If this Body is using `drag` for deceleration this property controls how the drag is applied. - * If set to `true` drag will use a damping effect rather than a linear approach. If you are - * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in - * the game Asteroids) then you will get a far smoother and more visually correct deceleration - * by using damping, avoiding the axis-drift that is prone with linear deceleration. - * - * If you enable this property then you should use far smaller `drag` values than with linear, as - * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow - * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. - */ - useDamping: boolean; - - /** - * The rate of change of this Body's `rotation`, in degrees per second. - */ - angularVelocity: number; - - /** - * The Body's angular acceleration (change in angular velocity), in degrees per second squared. - */ - angularAcceleration: number; - - /** - * Loss of angular velocity due to angular movement, in degrees per second. - * - * Angular drag is applied only when angular acceleration is zero. - */ - angularDrag: number; - - /** - * The Body's maximum angular velocity, in degrees per second. - */ - maxAngular: number; - - /** - * The Body's inertia, relative to a default unit (1). - * With `bounce`, this affects the exchange of momentum (velocities) during collisions. - */ - mass: number; - - /** - * The calculated angle of this Body's velocity vector, in radians, during the last step. - */ - angle: number; - - /** - * The calculated magnitude of the Body's velocity, in pixels per second, during the last step. - */ - speed: number; - - /** - * The direction of the Body's velocity, as calculated during the last step. - * If the Body is moving on both axes (diagonally), this describes motion on the vertical axis only. - */ - facing: integer; - - /** - * Whether this Body can be moved by collisions with another Body. - */ - immovable: boolean; - - /** - * Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity. - */ - moves: boolean; - - /** - * A flag disabling the default horizontal separation of colliding bodies. - * Pass your own `collideCallback` to the collider. - */ - customSeparateX: boolean; - - /** - * A flag disabling the default vertical separation of colliding bodies. - * Pass your own `collideCallback` to the collider. - */ - customSeparateY: boolean; - - /** - * The amount of horizontal overlap (before separation), if this Body is colliding with another. - */ - overlapX: number; - - /** - * The amount of vertical overlap (before separation), if this Body is colliding with another. - */ - overlapY: number; - - /** - * The amount of overlap (before separation), if this Body is circular and colliding with another circular body. - */ - overlapR: number; - - /** - * Whether this Body is overlapped with another and both are not moving, on at least one axis. - */ - embedded: boolean; - - /** - * Whether this Body interacts with the world boundary. - */ - collideWorldBounds: boolean; - - /** - * Whether this Body is checked for collisions and for which directions. - * You can set `checkCollision.none = true` to disable collision checks. - */ - checkCollision: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * Whether this Body is colliding with a Body or Static Body and in which direction. - * In a collision where both bodies have zero velocity, `embedded` will be set instead. - */ - touching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * This Body's `touching` value during the previous step. - */ - wasTouching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * Whether this Body is colliding with a Static Body, a tile, or the world boundary. - * In a collision with a Static Body, if this Body has zero velocity then `embedded` will be set instead. - */ - blocked: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * Whether to automatically synchronize this Body's dimensions to the dimensions of its Game Object's visual bounds. - */ - syncBounds: boolean; - - /** - * The Body's physics type (dynamic or static). - */ - readonly physicsType: integer; - - /** - * Updates the Body's `transform`, `width`, `height`, and `center` from its Game Object. - * The Body's `position` isn't changed. - */ - updateBounds(): void; - - /** - * Updates the Body's `center` from its `position`, `width`, and `height`. - */ - updateCenter(): void; - - /** - * Prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. - * - * This method is only called if the physics world is going to run a step this frame. - */ - resetFlags(): void; - - /** - * Syncs the position body position with the parent Game Object. - * - * This method is called every game frame, regardless if the world steps or not. - * @param willStep Will this Body run an update as well? - * @param delta The delta time, in seconds, elapsed since the last frame. - */ - preUpdate(willStep: boolean, delta: number): void; - - /** - * Performs a single physics step and updates the body velocity, angle, speed and other properties. - * - * This method can be called multiple times per game frame, depending on the physics step rate. - * - * The results are synced back to the Game Object in `postUpdate`. - * @param delta The delta time, in seconds, elapsed since the last frame. - */ - update(delta: number): void; - - /** - * Feeds the Body results back into the parent Game Object. - * - * This method is called every game frame, regardless if the world steps or not. - */ - postUpdate(): void; - - /** - * Sets a custom collision boundary rectangle. Use if you want to have a custom - * boundary instead of the world boundaries. - * @param bounds The new boundary rectangle. Pass `null` to use the World bounds. - */ - setBoundsRectangle(bounds?: Phaser.Geom.Rectangle): this; - - /** - * Checks for collisions between this Body and the world boundary and separates them. - */ - checkWorldBounds(): boolean; - - /** - * Sets the offset of the Body's position from its Game Object's position. - * @param x The horizontal offset, in source pixels. - * @param y The vertical offset, in source pixels. Default x. - */ - setOffset(x: number, y?: number): Phaser.Physics.Arcade.Body; - - /** - * Sizes and positions this Body's boundary, as a rectangle. - * Modifies the Body `offset` if `center` is true (the default). - * Resets the width and height to match current frame, if no width and height provided and a frame is found. - * @param width The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. - * @param height The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. - * @param center Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. Default true. - */ - setSize(width?: integer, height?: integer, center?: boolean): Phaser.Physics.Arcade.Body; - - /** - * Sizes and positions this Body's boundary, as a circle. - * @param radius The radius of the Body, in source pixels. - * @param offsetX The horizontal offset of the Body from its Game Object, in source pixels. - * @param offsetY The vertical offset of the Body from its Game Object, in source pixels. - */ - setCircle(radius: number, offsetX?: number, offsetY?: number): Phaser.Physics.Arcade.Body; - - /** - * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. - * If the Body had any velocity or acceleration it is lost as a result of calling this. - * @param x The horizontal position to place the Game Object and Body. - * @param y The vertical position to place the Game Object and Body. - */ - reset(x: number, y: number): void; - - /** - * Sets acceleration, velocity, and speed to zero. - */ - stop(): Phaser.Physics.Arcade.Body; - - /** - * Copies the coordinates of this Body's edges into an object. - * @param obj An object to copy the values into. - */ - getBounds(obj: Phaser.Types.Physics.Arcade.ArcadeBodyBounds): Phaser.Types.Physics.Arcade.ArcadeBodyBounds; - - /** - * Tests if the coordinates are within this Body's boundary. - * @param x The horizontal coordinate. - * @param y The vertical coordinate. - */ - hitTest(x: number, y: number): boolean; - - /** - * Whether this Body is touching a tile or the world boundary while moving down. - */ - onFloor(): boolean; - - /** - * Whether this Body is touching a tile or the world boundary while moving up. - */ - onCeiling(): boolean; - - /** - * Whether this Body is touching a tile or the world boundary while moving left or right. - */ - onWall(): boolean; - - /** - * The absolute (non-negative) change in this Body's horizontal position from the previous step. - */ - deltaAbsX(): number; - - /** - * The absolute (non-negative) change in this Body's vertical position from the previous step. - */ - deltaAbsY(): number; - - /** - * The change in this Body's horizontal position from the previous step. - * This value is set during the Body's update phase. - * - * As a Body can update multiple times per step this may not hold the final - * delta value for the Body. In this case, please see the `deltaXFinal` method. - */ - deltaX(): number; - - /** - * The change in this Body's vertical position from the previous step. - * This value is set during the Body's update phase. - * - * As a Body can update multiple times per step this may not hold the final - * delta value for the Body. In this case, please see the `deltaYFinal` method. - */ - deltaY(): number; - - /** - * The change in this Body's horizontal position from the previous game update. - * - * This value is set during the `postUpdate` phase and takes into account the - * `deltaMax` and final position of the Body. - * - * Because this value is not calculated until `postUpdate`, you must listen for it - * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will - * not be calculated by that point. If you _do_ use these values in `update` they - * will represent the delta from the _previous_ game frame. - */ - deltaXFinal(): number; - - /** - * The change in this Body's vertical position from the previous game update. - * - * This value is set during the `postUpdate` phase and takes into account the - * `deltaMax` and final position of the Body. - * - * Because this value is not calculated until `postUpdate`, you must listen for it - * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will - * not be calculated by that point. If you _do_ use these values in `update` they - * will represent the delta from the _previous_ game frame. - */ - deltaYFinal(): number; - - /** - * The change in this Body's rotation from the previous step, in degrees. - */ - deltaZ(): number; - - /** - * Disables this Body and marks it for deletion by the simulation. - */ - destroy(): void; - - /** - * Draws this Body's boundary and velocity, if enabled. - * @param graphic The Graphics object to draw on. - */ - drawDebug(graphic: Phaser.GameObjects.Graphics): void; - - /** - * Whether this Body will be drawn to the debug display. - */ - willDrawDebug(): boolean; - - /** - * Sets whether this Body collides with the world boundary. - * - * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. - * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. - * @param bounceX If given this will be replace the `worldBounce.x` value. - * @param bounceY If given this will be replace the `worldBounce.y` value. - */ - setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's velocity. - * @param x The horizontal velocity, in pixels per second. - * @param y The vertical velocity, in pixels per second. Default x. - */ - setVelocity(x: number, y?: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's horizontal velocity. - * @param value The velocity, in pixels per second. - */ - setVelocityX(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's vertical velocity. - * @param value The velocity, in pixels per second. - */ - setVelocityY(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's maximum velocity. - * @param x The horizontal velocity, in pixels per second. - * @param y The vertical velocity, in pixels per second. Default x. - */ - setMaxVelocity(x: number, y?: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the maximum speed the Body can move. - * @param value The maximum speed value, in pixels per second. Set to a negative value to disable. - */ - setMaxSpeed(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's bounce. - * @param x The horizontal bounce, relative to 1. - * @param y The vertical bounce, relative to 1. - */ - setBounce(x: number, y: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's horizontal bounce. - * @param value The bounce, relative to 1. - */ - setBounceX(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's vertical bounce. - * @param value The bounce, relative to 1. - */ - setBounceY(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's acceleration. - * @param x The horizontal component, in pixels per second squared. - * @param y The vertical component, in pixels per second squared. - */ - setAcceleration(x: number, y: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's horizontal acceleration. - * @param value The acceleration, in pixels per second squared. - */ - setAccelerationX(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's vertical acceleration. - * @param value The acceleration, in pixels per second squared. - */ - setAccelerationY(value: number): Phaser.Physics.Arcade.Body; - - /** - * Enables or disables drag. - * @param value `true` to allow drag on this body, or `false` to disable it. Default true. - */ - setAllowDrag(value?: boolean): Phaser.Physics.Arcade.Body; - - /** - * Enables or disables gravity's effect on this Body. - * @param value `true` to allow gravity on this body, or `false` to disable it. Default true. - */ - setAllowGravity(value?: boolean): Phaser.Physics.Arcade.Body; - - /** - * Enables or disables rotation. - * @param value `true` to allow rotation on this body, or `false` to disable it. Default true. - */ - setAllowRotation(value?: boolean): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's drag. - * @param x The horizontal component, in pixels per second squared. - * @param y The vertical component, in pixels per second squared. - */ - setDrag(x: number, y: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's horizontal drag. - * @param value The drag, in pixels per second squared. - */ - setDragX(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's vertical drag. - * @param value The drag, in pixels per second squared. - */ - setDragY(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's gravity. - * @param x The horizontal component, in pixels per second squared. - * @param y The vertical component, in pixels per second squared. - */ - setGravity(x: number, y: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's horizontal gravity. - * @param value The gravity, in pixels per second squared. - */ - setGravityX(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's vertical gravity. - * @param value The gravity, in pixels per second squared. - */ - setGravityY(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's friction. - * @param x The horizontal component, relative to 1. - * @param y The vertical component, relative to 1. - */ - setFriction(x: number, y: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's horizontal friction. - * @param value The friction value, relative to 1. - */ - setFrictionX(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's vertical friction. - * @param value The friction value, relative to 1. - */ - setFrictionY(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's angular velocity. - * @param value The velocity, in degrees per second. - */ - setAngularVelocity(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's angular acceleration. - * @param value The acceleration, in degrees per second squared. - */ - setAngularAcceleration(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's angular drag. - * @param value The drag, in degrees per second squared. - */ - setAngularDrag(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's mass. - * @param value The mass value, relative to 1. - */ - setMass(value: number): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's `immovable` property. - * @param value The value to assign to `immovable`. Default true. - */ - setImmovable(value?: boolean): Phaser.Physics.Arcade.Body; - - /** - * Sets the Body's `enable` property. - * @param value The value to assign to `enable`. Default true. - */ - setEnable(value?: boolean): Phaser.Physics.Arcade.Body; - - /** - * The Body's horizontal position (left edge). - */ - x: number; - - /** - * The Body's vertical position (top edge). - */ - y: number; - - /** - * The left edge of the Body's boundary. Identical to x. - */ - readonly left: number; - - /** - * The right edge of the Body's boundary. - */ - readonly right: number; - - /** - * The top edge of the Body's boundary. Identical to y. - */ - readonly top: number; - - /** - * The bottom edge of this Body's boundary. - */ - readonly bottom: number; - - } - - /** - * An Arcade Physics Collider will automatically check for collision, or overlaps, between two objects - * every step. If a collision, or overlap, occurs it will invoke the given callbacks. - */ - class Collider { - /** - * - * @param world The Arcade physics World that will manage the collisions. - * @param overlapOnly Whether to check for collisions or overlap. - * @param object1 The first object to check for collision. - * @param object2 The second object to check for collision. - * @param collideCallback The callback to invoke when the two objects collide. - * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. - * @param callbackContext The scope in which to call the callbacks. - */ - constructor(world: Phaser.Physics.Arcade.World, overlapOnly: boolean, object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback: ArcadePhysicsCallback, processCallback: ArcadePhysicsCallback, callbackContext: any); - - /** - * The world in which the bodies will collide. - */ - world: Phaser.Physics.Arcade.World; - - /** - * The name of the collider (unused by Phaser). - */ - name: string; - - /** - * Whether the collider is active. - */ - active: boolean; - - /** - * Whether to check for collisions or overlaps. - */ - overlapOnly: boolean; - - /** - * The first object to check for collision. - */ - object1: Phaser.Types.Physics.Arcade.ArcadeColliderType; - - /** - * The second object to check for collision. - */ - object2: Phaser.Types.Physics.Arcade.ArcadeColliderType; - - /** - * The callback to invoke when the two objects collide. - */ - collideCallback: ArcadePhysicsCallback; - - /** - * If a processCallback exists it must return true or collision checking will be skipped. - */ - processCallback: ArcadePhysicsCallback; - - /** - * The context the collideCallback and processCallback will run in. - */ - callbackContext: object; - - /** - * A name for the Collider. - * - * Phaser does not use this value, it's for your own reference. - * @param name The name to assign to the Collider. - */ - setName(name: string): Phaser.Physics.Arcade.Collider; - - /** - * Called by World as part of its step processing, initial operation of collision checking. - */ - update(): void; - - /** - * Removes Collider from World and disposes of its resources. - */ - destroy(): void; - - } - - namespace Components { - /** - * Provides methods used for setting the acceleration properties of an Arcade Physics Body. - */ - interface Acceleration { - /** - * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. - * @param x The horizontal acceleration - * @param y The vertical acceleration Default x. - */ - setAcceleration(x: number, y?: number): this; - /** - * Sets the body's horizontal acceleration. - * @param value The horizontal acceleration - */ - setAccelerationX(value: number): this; - /** - * Sets the body's vertical acceleration. - * @param value The vertical acceleration - */ - setAccelerationY(value: number): this; - } - - /** - * Provides methods used for setting the angular acceleration properties of an Arcade Physics Body. - */ - interface Angular { - /** - * Sets the angular velocity of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * @param value The amount of angular velocity. - */ - setAngularVelocity(value: number): this; - /** - * Sets the angular acceleration of the body. - * - * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. - * However, they can have angular motion, which is passed on to the Game Object bound to the body, - * causing them to visually rotate, even though the body remains axis-aligned. - * @param value The amount of angular acceleration. - */ - setAngularAcceleration(value: number): this; - /** - * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. - * @param value The amount of drag. - */ - setAngularDrag(value: number): this; - } - - /** - * Provides methods used for setting the bounce properties of an Arcade Physics Body. - */ - interface Bounce { - /** - * Sets the bounce values of this body. - * - * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. - * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. - * @param x The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - * @param y The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. Default x. - */ - setBounce(x: number, y?: number): this; - /** - * Sets the horizontal bounce value for this body. - * @param value The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. - */ - setBounceX(value: number): this; - /** - * Sets the vertical bounce value for this body. - * @param value The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. - */ - setBounceY(value: number): this; - /** - * Sets whether this Body collides with the world boundary. - * - * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. - * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. - * @param bounceX If given this will be replace the `worldBounce.x` value. - * @param bounceY If given this will be replace the `worldBounce.y` value. - */ - setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): this; - } - - /** - * Provides methods used for setting the debug properties of an Arcade Physics Body. - */ - interface Debug { - /** - * Sets the debug values of this body. - * - * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. - * Note that there is a performance cost in drawing debug displays. It should never be used in production. - * @param showBody Set to `true` to have this body render its outline to the debug display. - * @param showVelocity Set to `true` to have this body render a velocity marker to the debug display. - * @param bodyColor The color of the body outline when rendered to the debug display. - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): this; - /** - * Sets the color of the body outline when it renders to the debug display. - * @param value The color of the body outline when rendered to the debug display. - */ - setDebugBodyColor(value: number): this; - /** - * Set to `true` to have this body render its outline to the debug display. - */ - debugShowBody: boolean; - /** - * Set to `true` to have this body render a velocity marker to the debug display. - */ - debugShowVelocity: boolean; - /** - * The color of the body outline when it renders to the debug display. - */ - debugBodyColor: number; - } - - /** - * Provides methods used for setting the drag properties of an Arcade Physics Body. - */ - interface Drag { - /** - * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param x The amount of horizontal drag to apply. - * @param y The amount of vertical drag to apply. Default x. - */ - setDrag(x: number, y?: number): this; - /** - * Sets the body's horizontal drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param value The amount of horizontal drag to apply. - */ - setDragX(value: number): this; - /** - * Sets the body's vertical drag. - * - * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. - * It is the absolute loss of velocity due to movement, in pixels per second squared. - * The x and y components are applied separately. - * - * When `useDamping` is true, this is 1 minus the damping factor. - * A value of 1 means the Body loses no velocity. - * A value of 0.95 means the Body loses 5% of its velocity per step. - * A value of 0.5 means the Body loses 50% of its velocity per step. - * - * Drag is applied only when `acceleration` is zero. - * @param value The amount of vertical drag to apply. - */ - setDragY(value: number): this; - /** - * If this Body is using `drag` for deceleration this function controls how the drag is applied. - * If set to `true` drag will use a damping effect rather than a linear approach. If you are - * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in - * the game Asteroids) then you will get a far smoother and more visually correct deceleration - * by using damping, avoiding the axis-drift that is prone with linear deceleration. - * - * If you enable this property then you should use far smaller `drag` values than with linear, as - * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow - * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. - * @param value `true` to use damping for deceleration, or `false` to use linear deceleration. - */ - setDamping(value: boolean): this; - } - - /** - * Provides methods used for setting the enable properties of an Arcade Physics Body. - */ - interface Enable { - /** - * Enables this Game Object's Body. - * @param reset Also reset the Body and place it at (x, y). - * @param x The horizontal position to place the Game Object and Body. - * @param y The horizontal position to place the Game Object and Body. - * @param enableGameObject Also activate this Game Object. - * @param showGameObject Also show this Game Object. - */ - enableBody(reset: boolean, x: number, y: number, enableGameObject: boolean, showGameObject: boolean): this; - /** - * Stops and disables this Game Object's Body. - * @param disableGameObject Also deactivate this Game Object. Default false. - * @param hideGameObject Also hide this Game Object. Default false. - */ - disableBody(disableGameObject?: boolean, hideGameObject?: boolean): this; - /** - * 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. - */ - refreshBody(): this; - } - - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. The higher than friction, the faster the body will slow down once force stops being applied to it. - */ - interface Friction { - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of horizontal friction to apply. - * @param y The amount of vertical friction to apply. Default x. - */ - setFriction(x: number, y?: number): this; - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of friction to apply. - */ - setFrictionX(x: number): this; - /** - * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. - * The higher than friction, the faster the body will slow down once force stops being applied to it. - * @param x The amount of friction to apply. - */ - setFrictionY(x: number): this; - } - - /** - * Provides methods for setting the gravity properties of an Arcade Physics Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Gravity { - /** - * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. - * - * If only one value is provided, this value will be used for both the X and Y axis. - * @param x The gravitational force to be applied to the X-axis. - * @param y The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. Default x. - */ - setGravity(x: number, y?: number): this; - /** - * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. - * @param x The gravitational force to be applied to the X-axis. - */ - setGravityX(x: number): this; - /** - * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. - * @param y The gravitational force to be applied to the Y-axis. - */ - setGravityY(y: number): this; - } - - /** - * Provides methods used for setting the immovable properties of an Arcade Physics Body. - */ - interface Immovable { - /** - * Sets Whether this Body can be moved by collisions with another Body. - * @param value Sets if this body can be moved by collisions with another Body. Default true. - */ - setImmovable(value?: boolean): this; - } - - /** - * Provides methods used for setting the mass properties of an Arcade Physics Body. - */ - interface Mass { - /** - * Sets the mass of the physics body - * @param value New value for the mass of the body. - */ - setMass(value: number): this; - } - - /** - * This method will search the given circular area and return an array of all physics bodies that - * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. - * - * A body only has to intersect with the search area to be considered, it doesn't have to be fully - * contained within it. - * - * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, - * otherwise the search is O(N) for Dynamic Bodies. - */ - interface OverlapCirc { - } - - /** - * This method will search the given rectangular area and return an array of all physics bodies that - * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. - * - * A body only has to intersect with the search area to be considered, it doesn't have to be fully - * contained within it. - * - * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, - * otherwise the search is O(N) for Dynamic Bodies. - */ - interface OverlapRect { - } - - /** - * Provides methods for setting the size of an Arcade Physics Game Object. - * Should be applied as a mixin and not used directly. - */ - interface Size { - /** - * Sets the body offset. This allows you to adjust the difference between the center of the body - * and the x and y coordinates of the parent Game Object. - * @param x The amount to offset the body from the parent Game Object along the x-axis. - * @param y The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. Default x. - */ - setOffset(x: number, y?: number): this; - /** - * Sets the size of this physics body. Setting the size does not adjust the dimensions - * of the parent Game Object. - * @param width The new width of the physics body, in pixels. - * @param height The new height of the physics body, in pixels. - * @param center Should the body be re-positioned so its center aligns with the parent Game Object? Default true. - */ - setSize(width: number, height: number, center?: boolean): this; - /** - * Sets this physics body to use a circle for collision instead of a rectangle. - * @param radius The radius of the physics body, in pixels. - * @param offsetX The amount to offset the body from the parent Game Object along the x-axis. - * @param offsetY The amount to offset the body from the parent Game Object along the y-axis. - */ - setCircle(radius: number, offsetX?: number, offsetY?: number): this; - } - - /** - * Provides methods for modifying the velocity of an Arcade Physics body. - * - * Should be applied as a mixin and not used directly. - */ - interface Velocity { - /** - * Sets the velocity of the Body. - * @param x The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. - * @param y The vertical velocity of the body. Positive values move the body down, while negative values move it up. Default x. - */ - setVelocity(x: number, y?: number): this; - /** - * Sets the horizontal component of the body's velocity. - * - * Positive values move the body to the right, while negative values move it to the left. - * @param x The new horizontal velocity. - */ - setVelocityX(x: number): this; - /** - * Sets the vertical component of the body's velocity. - * - * Positive values move the body down, while negative values move it up. - * @param y The new vertical velocity of the body. - */ - setVelocityY(y: number): this; - /** - * Sets the maximum velocity of the body. - * @param x The new maximum horizontal velocity. - * @param y The new maximum vertical velocity. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - } - - } - - /** - * Dynamic Body. - */ - var DYNAMIC_BODY: number; - - /** - * Static Body. - */ - var STATIC_BODY: number; - - /** - * Arcade Physics Group containing Dynamic Bodies. - */ - var GROUP: number; - - /** - * A Tilemap Layer. - */ - var TILEMAPLAYER: number; - - /** - * Facing no direction (initial value). - */ - var FACING_NONE: number; - - /** - * Facing up. - */ - var FACING_UP: number; - - /** - * Facing down. - */ - var FACING_DOWN: number; - - /** - * Facing left. - */ - var FACING_LEFT: number; - - /** - * Facing right. - */ - var FACING_RIGHT: number; - - namespace Events { - /** - * The Arcade Physics World Collide Event. - * - * This event is dispatched by an Arcade Physics World instance if two bodies collide _and_ at least - * one of them has their [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. - * - * It provides an alternative means to handling collide events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('collide', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - */ - const COLLIDE: any; - - /** - * The Arcade Physics World Overlap Event. - * - * This event is dispatched by an Arcade Physics World instance if two bodies overlap _and_ at least - * one of them has their [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. - * - * It provides an alternative means to handling overlap events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('overlap', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - */ - const OVERLAP: any; - - /** - * The Arcade Physics World Pause Event. - * - * This event is dispatched by an Arcade Physics World instance when it is paused. - * - * Listen to it from a Scene using: `this.physics.world.on('pause', listener)`. - */ - const PAUSE: any; - - /** - * The Arcade Physics World Resume Event. - * - * This event is dispatched by an Arcade Physics World instance when it resumes from a paused state. - * - * Listen to it from a Scene using: `this.physics.world.on('resume', listener)`. - */ - const RESUME: any; - - /** - * The Arcade Physics Tile Collide Event. - * - * This event is dispatched by an Arcade Physics World instance if a body collides with a Tile _and_ - * has its [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. - * - * It provides an alternative means to handling collide events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('tilecollide', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - */ - const TILE_COLLIDE: any; - - /** - * The Arcade Physics Tile Overlap Event. - * - * This event is dispatched by an Arcade Physics World instance if a body overlaps with a Tile _and_ - * has its [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. - * - * It provides an alternative means to handling overlap events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('tileoverlap', listener)`. - * - * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. - */ - const TILE_OVERLAP: any; - - /** - * The Arcade Physics World Bounds Event. - * - * This event is dispatched by an Arcade Physics World instance if a body makes contact with the world bounds _and_ - * it has its [onWorldBounds]{@link Phaser.Physics.Arcade.Body#onWorldBounds} property set to `true`. - * - * It provides an alternative means to handling collide events rather than using the callback approach. - * - * Listen to it from a Scene using: `this.physics.world.on('worldbounds', listener)`. - */ - const WORLD_BOUNDS: any; - - /** - * The Arcade Physics World Step Event. - * - * This event is dispatched by an Arcade Physics World instance whenever a physics step is run. - * It is emitted _after_ the bodies and colliders have been updated. - * - * In high framerate settings this can be multiple times per game frame. - * - * Listen to it from a Scene using: `this.physics.world.on('worldstep', listener)`. - */ - const WORLD_STEP: any; - - } - - /** - * The Arcade Physics Factory allows you to easily create Arcade Physics enabled Game Objects. - * Objects that are created by this Factory are automatically added to the physics world. - */ - class Factory { - /** - * - * @param world The Arcade Physics World instance. - */ - constructor(world: Phaser.Physics.Arcade.World); - - /** - * A reference to the Arcade Physics World. - */ - world: Phaser.Physics.Arcade.World; - - /** - * A reference to the Scene this Arcade Physics instance belongs to. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene.Systems this Arcade Physics instance belongs to. - */ - sys: Phaser.Scenes.Systems; - - /** - * Creates a new Arcade Physics Collider object. - * @param object1 The first object to check for collision. - * @param object2 The second object to check for collision. - * @param collideCallback The callback to invoke when the two objects collide. - * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. - * @param callbackContext The scope in which to call the callbacks. - */ - collider(object1: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], object2: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; - - /** - * Creates a new Arcade Physics Collider Overlap object. - * @param object1 The first object to check for overlap. - * @param object2 The second object to check for overlap. - * @param collideCallback The callback to invoke when the two objects collide. - * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. - * @param callbackContext The scope in which to call the callbacks. - */ - overlap(object1: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], object2: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; - - /** - * Adds an Arcade Physics Body to the given Game Object. - * @param gameObject A Game Object. - * @param isStatic Create a Static body (true) or Dynamic body (false). Default false. - */ - existing(gameObject: Phaser.GameObjects.GameObject, isStatic?: boolean): Phaser.GameObjects.GameObject; - - /** - * Creates a new Arcade Image object with a Static body. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - staticImage(x: number, y: number, texture: string, frame?: string | integer): Phaser.Physics.Arcade.Image; - - /** - * Creates a new Arcade Image object with a Dynamic body. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - image(x: number, y: number, texture: string, frame?: string | integer): Phaser.Physics.Arcade.Image; - - /** - * Creates a new Arcade Sprite object with a Static body. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - staticSprite(x: number, y: number, texture: string, frame?: string | integer): Phaser.Physics.Arcade.Sprite; - - /** - * Creates a new Arcade Sprite object with a Dynamic body. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - sprite(x: number, y: number, key: string, frame?: string | integer): Phaser.Physics.Arcade.Sprite; - - /** - * Creates a Static Physics Group object. - * All Game Objects created by this Group will automatically be static Arcade Physics objects. - * @param children Game Objects to add to this group; or the `config` argument. - * @param config Settings for this group. - */ - staticGroup(children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.Physics.Arcade.StaticGroup; - - /** - * Creates a Physics Group object. - * All Game Objects created by this Group will automatically be dynamic Arcade Physics objects. - * @param children Game Objects to add to this group; or the `config` argument. - * @param config Settings for this group. - */ - group(children?: Phaser.GameObjects.GameObject[] | Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.Physics.Arcade.Group; - - /** - * Destroys this Factory. - */ - destroy(): void; - - } - - /** - * Calculates and returns the horizontal overlap between two arcade physics bodies and sets their properties - * accordingly, including: `touching.left`, `touching.right`, `touching.none` and `overlapX'. - * @param body1 The first Body to separate. - * @param body2 The second Body to separate. - * @param overlapOnly Is this an overlap only check, or part of separation? - * @param bias A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). - */ - function GetOverlapX(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): number; - - /** - * Calculates and returns the vertical overlap between two arcade physics bodies and sets their properties - * accordingly, including: `touching.up`, `touching.down`, `touching.none` and `overlapY'. - * @param body1 The first Body to separate. - * @param body2 The second Body to separate. - * @param overlapOnly Is this an overlap only check, or part of separation? - * @param bias A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). - */ - function GetOverlapY(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): number; - - /** - * An Arcade Physics Group object. - * - * All Game Objects created by this Group will automatically be given dynamic Arcade Physics bodies. - * - * Its static counterpart is {@link Phaser.Physics.Arcade.StaticGroup}. - */ - class Group extends Phaser.GameObjects.Group { - /** - * - * @param world The physics simulation. - * @param scene The scene this group belongs to. - * @param children Game Objects to add to this group; or the `config` argument. - * @param config Settings for this group. - */ - constructor(world: Phaser.Physics.Arcade.World, scene: Phaser.Scene, children?: Phaser.GameObjects.GameObject[] | Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig); - - /** - * The physics simulation. - */ - world: Phaser.Physics.Arcade.World; - - /** - * The class to create new Group members from. - * - * This should be either `Phaser.Physics.Arcade.Image`, `Phaser.Physics.Arcade.Sprite`, or a class extending one of those. - */ - classType: Function; - - /** - * The physics type of the Group's members. - */ - physicsType: integer; - - /** - * Default physics properties applied to Game Objects added to the Group or created by the Group. Derived from the `config` argument. - */ - defaults: Phaser.Types.Physics.Arcade.PhysicsGroupDefaults; - - /** - * A textual representation of this Game Object. - * Used internally by Phaser but is available for your own custom classes to populate. - */ - type: string; - - /** - * Enables a Game Object's Body and assigns `defaults`. Called when a Group member is added or created. - * @param child The Game Object being added. - */ - createCallbackHandler(child: Phaser.GameObjects.GameObject): void; - - /** - * Disables a Game Object's Body. Called when a Group member is removed. - * @param child The Game Object being removed. - */ - removeCallbackHandler(child: Phaser.GameObjects.GameObject): void; - - /** - * Sets the velocity of each Group member. - * @param x The horizontal velocity. - * @param y The vertical velocity. - * @param step The velocity increment. When set, the first member receives velocity (x, y), the second (x + step, y + step), and so on. Default 0. - */ - setVelocity(x: number, y: number, step?: number): Phaser.Physics.Arcade.Group; - - /** - * Sets the horizontal velocity of each Group member. - * @param value The velocity value. - * @param step The velocity increment. When set, the first member receives velocity (x), the second (x + step), and so on. Default 0. - */ - setVelocityX(value: number, step?: number): Phaser.Physics.Arcade.Group; - - /** - * Sets the vertical velocity of each Group member. - * @param value The velocity value. - * @param step The velocity increment. When set, the first member receives velocity (y), the second (y + step), and so on. Default 0. - */ - setVelocityY(value: number, step?: number): Phaser.Physics.Arcade.Group; - - } - - /** - * 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 they are static, or if either one uses custom logic for its separation. - * @param body1 The first Body to separate. - * @param body2 The second Body to separate. - * @param overlapOnly If `true`, the bodies will only have their overlap data set and no separation will take place. - * @param bias A value to add to the delta value during overlap checking. Used to prevent sprite tunneling. - */ - function SeparateX(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): boolean; - - /** - * 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. - * @param body1 The first Body to separate. - * @param body2 The second Body to separate. - * @param overlapOnly If `true`, the bodies will only have their overlap data set and no separation will take place. - * @param bias A value to add to the delta value during overlap checking. Used to prevent sprite tunneling. - */ - function SeparateY(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): boolean; - - /** - * A Static Arcade Physics Body. - * - * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. - * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Body manually. - * - * A Static Body can collide with other Bodies, but is never moved by collisions. - * - * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Body}. - */ - class StaticBody { - /** - * - * @param world The Arcade Physics simulation this Static Body belongs to. - * @param gameObject The Game Object this Static Body belongs to. - */ - constructor(world: Phaser.Physics.Arcade.World, gameObject: Phaser.GameObjects.GameObject); - - /** - * The Arcade Physics simulation this Static Body belongs to. - */ - world: Phaser.Physics.Arcade.World; - - /** - * The Game Object this Static Body belongs to. - */ - gameObject: Phaser.GameObjects.GameObject; - - /** - * Whether the Static Body's boundary is drawn to the debug display. - */ - debugShowBody: boolean; - - /** - * The color of this Static Body on the debug display. - */ - debugBodyColor: integer; - - /** - * Whether this Static Body is updated by the physics simulation. - */ - enable: boolean; - - /** - * Whether this Static Body's boundary is circular (`true`) or rectangular (`false`). - */ - isCircle: boolean; - - /** - * If this Static Body is circular, this is the unscaled radius of the Static Body's boundary, as set by {@link #setCircle}, in source pixels. - * The true radius is equal to `halfWidth`. - */ - radius: number; - - /** - * The offset of this Static Body's actual position from any updated position. - * - * Unlike a dynamic Body, a Static Body does not follow its Game Object. As such, this offset is only applied when resizing the Static Body. - */ - offset: Phaser.Math.Vector2; - - /** - * The position of this Static Body within the simulation. - */ - position: Phaser.Math.Vector2; - - /** - * The width of the Static Body's boundary, in pixels. - * If the Static Body is circular, this is also the Static Body's diameter. - */ - width: number; - - /** - * The height of the Static Body's boundary, in pixels. - * If the Static Body is circular, this is also the Static Body's diameter. - */ - height: number; - - /** - * Half the Static Body's width, in pixels. - * If the Static Body is circular, this is also the Static Body's radius. - */ - halfWidth: number; - - /** - * Half the Static Body's height, in pixels. - * If the Static Body is circular, this is also the Static Body's radius. - */ - halfHeight: number; - - /** - * The center of the Static Body's boundary. - * This is the midpoint of its `position` (top-left corner) and its bottom-right corner. - */ - center: Phaser.Math.Vector2; - - /** - * A constant zero velocity used by the Arcade Physics simulation for calculations. - */ - readonly velocity: Phaser.Math.Vector2; - - /** - * A constant `false` value expected by the Arcade Physics simulation. - */ - readonly allowGravity: boolean; - - /** - * Gravitational force applied specifically to this Body. Values are in pixels per second squared. Always zero for a Static Body. - */ - readonly gravity: Phaser.Math.Vector2; - - /** - * Rebound, or restitution, following a collision, relative to 1. Always zero for a Static Body. - */ - readonly bounce: Phaser.Math.Vector2; - - /** - * Whether the simulation emits a `worldbounds` event when this StaticBody collides with the world boundary. - * Always false for a Static Body. (Static Bodies never collide with the world boundary and never trigger a `worldbounds` event.) - */ - readonly onWorldBounds: boolean; - - /** - * Whether the simulation emits a `collide` event when this StaticBody collides with another. - */ - onCollide: boolean; - - /** - * Whether the simulation emits an `overlap` event when this StaticBody overlaps with another. - */ - onOverlap: boolean; - - /** - * The StaticBody's inertia, relative to a default unit (1). With `bounce`, this affects the exchange of momentum (velocities) during collisions. - */ - mass: number; - - /** - * Whether this object can be moved by collisions with another body. - */ - immovable: boolean; - - /** - * A flag disabling the default horizontal separation of colliding bodies. Pass your own `collideHandler` to the collider. - */ - customSeparateX: boolean; - - /** - * A flag disabling the default vertical separation of colliding bodies. Pass your own `collideHandler` to the collider. - */ - customSeparateY: boolean; - - /** - * The amount of horizontal overlap (before separation), if this Body is colliding with another. - */ - overlapX: number; - - /** - * The amount of vertical overlap (before separation), if this Body is colliding with another. - */ - overlapY: number; - - /** - * The amount of overlap (before separation), if this StaticBody is circular and colliding with another circular body. - */ - overlapR: number; - - /** - * Whether this StaticBody has ever overlapped with another while both were not moving. - */ - embedded: boolean; - - /** - * Whether this StaticBody interacts with the world boundary. - * Always false for a Static Body. (Static Bodies never collide with the world boundary.) - */ - readonly collideWorldBounds: boolean; - - /** - * Whether this StaticBody is checked for collisions and for which directions. You can set `checkCollision.none = false` to disable collision checks. - */ - checkCollision: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * Whether this StaticBody has ever collided with another body and in which direction. - */ - touching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * Whether this StaticBody was colliding with another body during the last step or any previous step, and in which direction. - */ - wasTouching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * Whether this StaticBody has ever collided with a tile or the world boundary. - */ - blocked: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; - - /** - * The StaticBody's physics type (static by default). - */ - physicsType: integer; - - /** - * Changes the Game Object this Body is bound to. - * First it removes its reference from the old Game Object, then sets the new one. - * You can optionally update the position and dimensions of this Body to reflect that of the new Game Object. - * @param gameObject The new Game Object that will own this Body. - * @param update Reposition and resize this Body to match the new Game Object? Default true. - */ - setGameObject(gameObject: Phaser.GameObjects.GameObject, update?: boolean): Phaser.Physics.Arcade.StaticBody; - - /** - * Syncs the Body's position and size with its parent Game Object. - */ - updateFromGameObject(): Phaser.Physics.Arcade.StaticBody; - - /** - * Sets the offset of the body. - * @param x The horizontal offset of the Body from the Game Object's center. - * @param y The vertical offset of the Body from the Game Object's center. - */ - setOffset(x: number, y: number): Phaser.Physics.Arcade.StaticBody; - - /** - * Sets the size of the body. - * Resets the width and height to match current frame, if no width and height provided and a frame is found. - * @param width The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. - * @param height The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. - * @param center Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. Default true. - */ - setSize(width?: integer, height?: integer, center?: boolean): Phaser.Physics.Arcade.StaticBody; - - /** - * Sets this Static Body to have a circular body and sets its sizes and position. - * @param radius The radius of the StaticBody, in pixels. - * @param offsetX The horizontal offset of the StaticBody from its Game Object, in pixels. - * @param offsetY The vertical offset of the StaticBody from its Game Object, in pixels. - */ - setCircle(radius: number, offsetX?: number, offsetY?: number): Phaser.Physics.Arcade.StaticBody; - - /** - * Updates the StaticBody's `center` from its `position` and dimensions. - */ - updateCenter(): void; - - /** - * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. - * @param x The x coordinate to reset the body to. If not given will use the parent Game Object's coordinate. - * @param y The y coordinate to reset the body to. If not given will use the parent Game Object's coordinate. - */ - reset(x?: number, y?: number): void; - - /** - * NOOP function. A Static Body cannot be stopped. - */ - stop(): Phaser.Physics.Arcade.StaticBody; - - /** - * Returns the x and y coordinates of the top left and bottom right points of the StaticBody. - * @param obj The object which will hold the coordinates of the bounds. - */ - getBounds(obj: Phaser.Types.Physics.Arcade.ArcadeBodyBounds): Phaser.Types.Physics.Arcade.ArcadeBodyBounds; - - /** - * Checks to see if a given x,y coordinate is colliding with this Static Body. - * @param x The x coordinate to check against this body. - * @param y The y coordinate to check against this body. - */ - hitTest(x: number, y: number): boolean; - - /** - * NOOP - */ - postUpdate(): void; - - /** - * The absolute (non-negative) change in this StaticBody's horizontal position from the previous step. Always zero. - */ - deltaAbsX(): number; - - /** - * The absolute (non-negative) change in this StaticBody's vertical position from the previous step. Always zero. - */ - deltaAbsY(): number; - - /** - * The change in this StaticBody's horizontal position from the previous step. Always zero. - */ - deltaX(): number; - - /** - * The change in this StaticBody's vertical position from the previous step. Always zero. - */ - deltaY(): number; - - /** - * The change in this StaticBody's rotation from the previous step. Always zero. - */ - deltaZ(): number; - - /** - * Disables this Body and marks it for destruction during the next step. - */ - destroy(): void; - - /** - * Draws a graphical representation of the StaticBody for visual debugging purposes. - * @param graphic The Graphics object to use for the debug drawing of the StaticBody. - */ - drawDebug(graphic: Phaser.GameObjects.Graphics): void; - - /** - * Indicates whether the StaticBody is going to be showing a debug visualization during postUpdate. - */ - willDrawDebug(): boolean; - - /** - * Sets the Mass of the StaticBody. Will set the Mass to 0.1 if the value passed is less than or equal to zero. - * @param value The value to set the Mass to. Values of zero or less are changed to 0.1. - */ - setMass(value: number): Phaser.Physics.Arcade.StaticBody; - - /** - * The x coordinate of the StaticBody. - */ - x: number; - - /** - * The y coordinate of the StaticBody. - */ - y: number; - - /** - * Returns the left-most x coordinate of the area of the StaticBody. - */ - readonly left: number; - - /** - * The right-most x coordinate of the area of the StaticBody. - */ - readonly right: number; - - /** - * The highest y coordinate of the area of the StaticBody. - */ - readonly top: number; - - /** - * The lowest y coordinate of the area of the StaticBody. (y + height) - */ - readonly bottom: number; - - } - - /** - * An Arcade Physics Static Group object. - * - * All Game Objects created by this Group will automatically be given static Arcade Physics bodies. - * - * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Group}. - */ - class StaticGroup extends Phaser.GameObjects.Group { - /** - * - * @param world The physics simulation. - * @param scene The scene this group belongs to. - * @param children Game Objects to add to this group; or the `config` argument. - * @param config Settings for this group. - */ - constructor(world: Phaser.Physics.Arcade.World, scene: Phaser.Scene, children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig); - - /** - * The physics simulation. - */ - world: Phaser.Physics.Arcade.World; - - /** - * The scene this group belongs to. - */ - physicsType: integer; - - /** - * A textual representation of this Game Object. - * Used internally by Phaser but is available for your own custom classes to populate. - */ - type: string; - - /** - * Adds a static physics body to the new group member (if it lacks one) and adds it to the simulation. - * @param child The new group member. - */ - createCallbackHandler(child: Phaser.GameObjects.GameObject): void; - - /** - * Disables the group member's physics body, removing it from the simulation. - * @param child The group member being removed. - */ - removeCallbackHandler(child: Phaser.GameObjects.GameObject): void; - - /** - * Refreshes the group. - * @param entries The newly created group members. - */ - createMultipleCallbackHandler(entries: Phaser.GameObjects.GameObject[]): void; - - /** - * Resets each Body to the position of its parent Game Object. - * Body sizes aren't changed (use {@link Phaser.Physics.Arcade.Components.Enable#refreshBody} for that). - */ - refresh(): Phaser.Physics.Arcade.StaticGroup; - - } - - namespace Tilemap { - /** - * A function to process the collision callbacks between a single tile and an Arcade Physics enabled Game Object. - * @param tile The Tile to process. - * @param sprite The Game Object to process with the Tile. - */ - function ProcessTileCallbacks(tile: Phaser.Tilemaps.Tile, sprite: Phaser.GameObjects.Sprite): boolean; - - /** - * Internal function to process the separation of a physics body from a tile. - * @param body The Body object to separate. - * @param x The x separation amount. - */ - function ProcessTileSeparationX(body: Phaser.Physics.Arcade.Body, x: number): void; - - /** - * Internal function to process the separation of a physics body from a tile. - * @param body The Body object to separate. - * @param y The y separation amount. - */ - function ProcessTileSeparationY(body: Phaser.Physics.Arcade.Body, y: number): void; - - /** - * The core separation function to separate a physics body and a tile. - * @param i The index of the tile within the map data. - * @param body The Body object to separate. - * @param tile The tile to collide against. - * @param tileWorldRect A rectangle-like object defining the dimensions of the tile. - * @param tilemapLayer The tilemapLayer to collide against. - * @param tileBias The tile bias value. Populated by the `World.TILE_BIAS` constant. - * @param isLayer Is this check coming from a TilemapLayer or an array of tiles? - */ - function SeparateTile(i: number, body: Phaser.Physics.Arcade.Body, tile: Phaser.Tilemaps.Tile, tileWorldRect: Phaser.Geom.Rectangle, tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, tileBias: number, isLayer: boolean): boolean; - - /** - * Check the body against the given tile on the X axis. - * Used internally by the SeparateTile function. - * @param body The Body object to separate. - * @param tile The tile to check. - * @param tileLeft The left position of the tile within the tile world. - * @param tileRight The right position of the tile within the tile world. - * @param tileBias The tile bias value. Populated by the `World.TILE_BIAS` constant. - * @param isLayer Is this check coming from a TilemapLayer or an array of tiles? - */ - function TileCheckX(body: Phaser.Physics.Arcade.Body, tile: Phaser.Tilemaps.Tile, tileLeft: number, tileRight: number, tileBias: number, isLayer: boolean): number; - - /** - * Check the body against the given tile on the Y axis. - * Used internally by the SeparateTile function. - * @param body The Body object to separate. - * @param tile The tile to check. - * @param tileTop The top position of the tile within the tile world. - * @param tileBottom The bottom position of the tile within the tile world. - * @param tileBias The tile bias value. Populated by the `World.TILE_BIAS` constant. - * @param isLayer Is this check coming from a TilemapLayer or an array of tiles? - */ - function TileCheckY(body: Phaser.Physics.Arcade.Body, tile: Phaser.Tilemaps.Tile, tileTop: number, tileBottom: number, tileBias: number, isLayer: boolean): number; - - /** - * Checks for intersection between the given tile rectangle-like object and an Arcade Physics body. - * @param tileWorldRect A rectangle object that defines the tile placement in the world. - * @param body The body to check for intersection against. - */ - function TileIntersectsBody(tileWorldRect: Object, body: Phaser.Physics.Arcade.Body): boolean; - - } - - /** - * The Arcade Physics World. - * - * The World is responsible for creating, managing, colliding and updating all of the bodies within it. - * - * An instance of the World belongs to a Phaser.Scene and is accessed via the property `physics.world`. - */ - class World extends Phaser.Events.EventEmitter { - /** - * - * @param scene The Scene to which this World instance belongs. - * @param config An Arcade Physics Configuration object. - */ - constructor(scene: Phaser.Scene, config: Phaser.Types.Physics.Arcade.ArcadeWorldConfig); - - /** - * The Scene this simulation belongs to. - */ - scene: Phaser.Scene; - - /** - * Dynamic Bodies in this simulation. - */ - bodies: Phaser.Structs.Set; - - /** - * Static Bodies in this simulation. - */ - staticBodies: Phaser.Structs.Set; - - /** - * Static Bodies marked for deletion. - */ - pendingDestroy: Phaser.Structs.Set<(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)>; - - /** - * This simulation's collision processors. - */ - colliders: Phaser.Structs.ProcessQueue; - - /** - * Acceleration of Bodies due to gravity, in pixels per second. - */ - gravity: Phaser.Math.Vector2; - - /** - * A boundary constraining Bodies. - */ - bounds: Phaser.Geom.Rectangle; - - /** - * The boundary edges that Bodies can collide with. - */ - checkCollision: Phaser.Types.Physics.Arcade.CheckCollisionObject; - - /** - * The number of physics steps to be taken per second. - * - * This property is read-only. Use the `setFPS` method to modify it at run-time. - */ - readonly fps: number; - - /** - * The number of steps that took place in the last frame. - */ - readonly stepsLastFrame: number; - - /** - * Scaling factor applied to the frame rate. - * - * - 1.0 = normal speed - * - 2.0 = half speed - * - 0.5 = double speed - */ - timeScale: number; - - /** - * The maximum absolute difference of a Body's per-step velocity and its overlap with another Body that will result in separation on *each axis*. - * Larger values favor separation. - * Smaller values favor no separation. - */ - OVERLAP_BIAS: number; - - /** - * The maximum absolute value of a Body's overlap with a tile that will result in separation on *each axis*. - * Larger values favor separation. - * Smaller values favor no separation. - * The optimum value may be similar to the tile size. - */ - TILE_BIAS: number; - - /** - * Always separate overlapping Bodies horizontally before vertically. - * False (the default) means Bodies are first separated on the axis of greater gravity, or the vertical axis if neither is greater. - */ - forceX: boolean; - - /** - * Whether the simulation advances with the game loop. - */ - isPaused: boolean; - - /** - * Enables the debug display. - */ - drawDebug: boolean; - - /** - * The graphics object drawing the debug display. - */ - debugGraphic: Phaser.GameObjects.Graphics; - - /** - * Default debug display settings for new Bodies. - */ - defaults: Phaser.Types.Physics.Arcade.ArcadeWorldDefaults; - - /** - * The maximum number of items per node on the RTree. - * - * This is ignored if `useTree` is `false`. If you have a large number of bodies in - * your world then you may find search performance improves by increasing this value, - * to allow more items per node and less node division. - */ - maxEntries: integer; - - /** - * Should this Arcade Physics World use an RTree for Dynamic and Static Physics bodies? - * - * An RTree is a fast way of spatially sorting of all the bodies in the world. - * However, at certain limits, the cost of clearing and inserting the bodies into the - * tree every frame becomes more expensive than the search speed gains it provides. - * - * If you have a large number of dynamic bodies in your world then it may be best to - * disable the use of the RTree by setting this property to `false` in the physics config. - * - * The number it can cope with depends on browser and device, but a conservative estimate - * of around 5,000 bodies should be considered the max before disabling it. - * - * This only applies to dynamic bodies. Static bodies are always kept in an RTree, - * because they don't have to be cleared every frame, so you benefit from the - * massive search speeds all the time. - */ - useTree: boolean; - - /** - * The spatial index of Dynamic Bodies. - */ - tree: Phaser.Structs.RTree; - - /** - * The spatial index of Static Bodies. - */ - staticTree: Phaser.Structs.RTree; - - /** - * Recycled input for tree searches. - */ - treeMinMax: Phaser.Types.Physics.Arcade.ArcadeWorldTreeMinMax; - - /** - * Adds an Arcade Physics Body to a Game Object, an array of Game Objects, or the children of a Group. - * - * The difference between this and the `enableBody` method is that you can pass arrays or Groups - * to this method. - * - * You can specify if the bodies are to be Dynamic or Static. A dynamic body can move via velocity and - * acceleration. A static body remains fixed in place and as such is able to use an optimized search - * tree, making it ideal for static elements such as level objects. You can still collide and overlap - * with static bodies. - * - * Normally, rather than calling this method directly, you'd use the helper methods available in the - * Arcade Physics Factory, such as: - * - * ```javascript - * this.physics.add.image(x, y, textureKey); - * this.physics.add.sprite(x, y, textureKey); - * ``` - * - * Calling factory methods encapsulates the creation of a Game Object and the creation of its - * body at the same time. If you are creating custom classes then you can pass them to this - * method to have their bodies created. - * @param object The object, or objects, on which to create the bodies. - * @param bodyType The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. - */ - enable(object: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], bodyType?: integer): void; - - /** - * Creates an Arcade Physics Body on a single Game Object. - * - * If the Game Object already has a body, this method will simply add it back into the simulation. - * - * You can specify if the body is Dynamic or Static. A dynamic body can move via velocity and - * acceleration. A static body remains fixed in place and as such is able to use an optimized search - * tree, making it ideal for static elements such as level objects. You can still collide and overlap - * with static bodies. - * - * Normally, rather than calling this method directly, you'd use the helper methods available in the - * Arcade Physics Factory, such as: - * - * ```javascript - * this.physics.add.image(x, y, textureKey); - * this.physics.add.sprite(x, y, textureKey); - * ``` - * - * Calling factory methods encapsulates the creation of a Game Object and the creation of its - * body at the same time. If you are creating custom classes then you can pass them to this - * method to have their bodies created. - * @param object The Game Object on which to create the body. - * @param bodyType The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. - */ - enableBody(object: Phaser.GameObjects.GameObject, bodyType?: integer): Phaser.GameObjects.GameObject; - - /** - * Adds an existing Arcade Physics Body or StaticBody to the simulation. - * - * The body is enabled and added to the local search trees. - * @param body The Body to be added to the simulation. - */ - add(body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody): Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody; - - /** - * Disables the Arcade Physics Body of a Game Object, an array of Game Objects, or the children of a Group. - * - * The difference between this and the `disableBody` method is that you can pass arrays or Groups - * to this method. - * - * The body itself is not deleted, it just has its `enable` property set to false, which - * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. - * @param object The object, or objects, on which to disable the bodies. - */ - disable(object: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[]): void; - - /** - * Disables an existing Arcade Physics Body or StaticBody and removes it from the simulation. - * - * The body is disabled and removed from the local search trees. - * - * The body itself is not deleted, it just has its `enable` property set to false, which - * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. - * @param body The Body to be disabled. - */ - disableBody(body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody): void; - - /** - * Removes an existing Arcade Physics Body or StaticBody from the simulation. - * - * The body is disabled and removed from the local search trees. - * - * The body itself is not deleted, it just has its `enabled` property set to false, which - * means you can re-enable it again at any point by passing it to enable `enable` or `add`. - * @param body The body to be removed from the simulation. - */ - remove(body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody): void; - - /** - * Creates a Graphics Game Object that the world will use to render the debug display to. - * - * This is called automatically when the World is instantiated if the `debug` config property - * was set to `true`. However, you can call it at any point should you need to display the - * debug Graphic from a fixed point. - * - * You can control which objects are drawn to the Graphics object, and the colors they use, - * by setting the debug properties in the physics config. - * - * You should not typically use this in a production game. Use it to aid during debugging. - */ - createDebugGraphic(): Phaser.GameObjects.Graphics; - - /** - * Sets the position, size and properties of the World boundary. - * - * The World boundary is an invisible rectangle that defines the edges of the World. - * If a Body is set to collide with the world bounds then it will automatically stop - * when it reaches any of the edges. You can optionally set which edges of the boundary - * should be checked against. - * @param x The top-left x coordinate of the boundary. - * @param y The top-left y coordinate of the boundary. - * @param width The width of the boundary. - * @param height The height of the boundary. - * @param checkLeft Should bodies check against the left edge of the boundary? - * @param checkRight Should bodies check against the right edge of the boundary? - * @param checkUp Should bodies check against the top edge of the boundary? - * @param checkDown Should bodies check against the bottom edge of the boundary? - */ - setBounds(x: number, y: number, width: number, height: number, checkLeft?: boolean, checkRight?: boolean, checkUp?: boolean, checkDown?: boolean): Phaser.Physics.Arcade.World; - - /** - * Enables or disables collisions on each edge of the World boundary. - * @param left Should bodies check against the left edge of the boundary? Default true. - * @param right Should bodies check against the right edge of the boundary? Default true. - * @param up Should bodies check against the top edge of the boundary? Default true. - * @param down Should bodies check against the bottom edge of the boundary? Default true. - */ - setBoundsCollision(left?: boolean, right?: boolean, up?: boolean, down?: boolean): Phaser.Physics.Arcade.World; - - /** - * Pauses the simulation. - * - * A paused simulation does not update any existing bodies, or run any Colliders. - * - * However, you can still enable and disable bodies within it, or manually run collide or overlap - * checks. - */ - pause(): Phaser.Physics.Arcade.World; - - /** - * Resumes the simulation, if paused. - */ - resume(): Phaser.Physics.Arcade.World; - - /** - * Creates a new Collider object and adds it to the simulation. - * - * A Collider is a way to automatically perform collision checks between two objects, - * calling the collide and process callbacks if they occur. - * - * Colliders are run as part of the World update, after all of the Bodies have updated. - * - * By creating a Collider you don't need then call `World.collide` in your `update` loop, - * as it will be handled for you automatically. - * @param object1 The first object to check for collision. - * @param object2 The second object to check for collision. - * @param collideCallback The callback to invoke when the two objects collide. - * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. - * @param callbackContext The scope in which to call the callbacks. - */ - addCollider(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; - - /** - * Creates a new Overlap Collider object and adds it to the simulation. - * - * A Collider is a way to automatically perform overlap checks between two objects, - * calling the collide and process callbacks if they occur. - * - * Colliders are run as part of the World update, after all of the Bodies have updated. - * - * By creating a Collider you don't need then call `World.overlap` in your `update` loop, - * as it will be handled for you automatically. - * @param object1 The first object to check for overlap. - * @param object2 The second object to check for overlap. - * @param collideCallback The callback to invoke when the two objects overlap. - * @param processCallback The callback to invoke when the two objects overlap. Must return a boolean. - * @param callbackContext The scope in which to call the callbacks. - */ - addOverlap(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; - - /** - * Removes a Collider from the simulation so it is no longer processed. - * - * This method does not destroy the Collider. If you wish to add it back at a later stage you can call - * `World.colliders.add(Collider)`. - * - * If you no longer need the Collider you can call the `Collider.destroy` method instead, which will - * automatically clear all of its references and then remove it from the World. If you call destroy on - * a Collider you _don't_ need to pass it to this method too. - * @param collider The Collider to remove from the simulation. - */ - removeCollider(collider: Phaser.Physics.Arcade.Collider): Phaser.Physics.Arcade.World; - - /** - * Sets the frame rate to run the simulation at. - * - * The frame rate value is used to simulate a fixed update time step. This fixed - * time step allows for a straightforward implementation of a deterministic game state. - * - * This frame rate is independent of the frequency at which the game is rendering. The - * higher you set the fps, the more physics simulation steps will occur per game step. - * Conversely, the lower you set it, the less will take place. - * - * You can optionally advance the simulation directly yourself by calling the `step` method. - * @param framerate The frame rate to advance the simulation at. - */ - setFPS(framerate: integer): this; - - /** - * 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. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time, in ms, elapsed since the last frame. - */ - protected update(time: number, delta: number): void; - - /** - * Advances the simulation by a time increment. - * @param delta The delta time amount, in seconds, by which to advance the simulation. - */ - step(delta: number): void; - - /** - * Updates bodies, draws the debug display, and handles pending queue operations. - */ - postUpdate(): void; - - /** - * Calculates a Body's velocity and updates its position. - * @param body The Body to be updated. - * @param delta The delta value to be used in the motion calculations, in seconds. - */ - updateMotion(body: Phaser.Physics.Arcade.Body, delta: number): void; - - /** - * Calculates a Body's angular velocity. - * @param body The Body to compute the velocity for. - * @param delta The delta value to be used in the calculation, in seconds. - */ - computeAngularVelocity(body: Phaser.Physics.Arcade.Body, delta: number): void; - - /** - * Calculates a Body's per-axis velocity. - * @param body The Body to compute the velocity for. - * @param delta The delta value to be used in the calculation, in seconds. - */ - computeVelocity(body: Phaser.Physics.Arcade.Body, delta: number): void; - - /** - * Separates two Bodies. - * @param body1 The first Body to be separated. - * @param body2 The second Body to be separated. - * @param processCallback The process callback. - * @param callbackContext The context in which to invoke the callback. - * @param overlapOnly If this a collide or overlap check? - */ - separate(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, processCallback?: ArcadePhysicsCallback, callbackContext?: any, overlapOnly?: boolean): boolean; - - /** - * Separates two Bodies, when both are circular. - * @param body1 The first Body to be separated. - * @param body2 The second Body to be separated. - * @param overlapOnly If this a collide or overlap check? - * @param bias A small value added to the calculations. - */ - separateCircle(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly?: boolean, bias?: number): boolean; - - /** - * Checks to see if two Bodies intersect at all. - * @param body1 The first body to check. - * @param body2 The second body to check. - */ - intersects(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body): boolean; - - /** - * Tests if a circular Body intersects with another Body. - * @param circle The circular body to test. - * @param body The rectangular body to test. - */ - circleBodyIntersects(circle: Phaser.Physics.Arcade.Body, body: Phaser.Physics.Arcade.Body): boolean; - - /** - * Tests if Game Objects overlap. - * @param object1 The first object or array of objects to check. - * @param object2 The second object or array of objects to check, or `undefined`. - * @param overlapCallback An optional callback function that is called if the objects overlap. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - overlap(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, overlapCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * Performs a collision check and separation between the two physics enabled objects given, which can be single - * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. - * - * If you don't require separation then use {@link #overlap} instead. - * - * If two Groups or arrays are passed, each member of one will be tested against each member of the other. - * - * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. - * - * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. - * - * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding - * objects are passed to it. - * - * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable - * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. - * The separation that stops two objects penetrating may create a new penetration against a different object. If you - * require a high level of stability please consider using an alternative physics system, such as Matter.js. - * @param object1 The first object or array of objects to check. - * @param object2 The second object or array of objects to check, or `undefined`. - * @param collideCallback An optional callback function that is called if the objects collide. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - collide(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. - * - * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for collision with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions - * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * - * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have - * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the - * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on - * dynamic maps, this method can prove very useful. - * @param sprite The first object to check for collision. - * @param tiles An array of Tiles to check for collision against. - * @param collideCallback An optional callback function that is called if the objects collide. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - collideTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. - * - * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform - * tile filtering and culling for you, as well as handle the interesting face collision automatically. - * - * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without - * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap - * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, - * you should filter them before passing them to this method. - * @param sprite The first object to check for collision. - * @param tiles An array of Tiles to check for collision against. - * @param collideCallback An optional callback function that is called if the objects overlap. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - */ - overlapTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * Internal handler for Sprite vs. Tilemap collisions. - * Please use Phaser.Physics.Arcade.World#collide instead. - * @param sprite The first object to check for collision. - * @param tilemapLayer The second object to check for collision. - * @param collideCallback An optional callback function that is called if the objects collide. - * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. - * @param callbackContext The context in which to run the callbacks. - * @param overlapOnly Whether this is a collision or overlap check. - */ - collideSpriteVsTilemapLayer(sprite: Phaser.GameObjects.GameObject, tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any, overlapOnly?: boolean): boolean; - - /** - * Wrap an object's coordinates (or several objects' coordinates) within {@link Phaser.Physics.Arcade.World#bounds}. - * - * If the object is outside any boundary edge (left, top, right, bottom), it will be moved to the same offset from the opposite edge (the interior). - * @param object A Game Object, a Group, an object with `x` and `y` coordinates, or an array of such objects. - * @param padding An amount added to each boundary edge during the operation. Default 0. - */ - wrap(object: any, padding?: number): void; - - /** - * Wrap each object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. - * @param objects An array of objects to be wrapped. - * @param padding An amount added to the boundary. Default 0. - */ - wrapArray(objects: any[], padding?: number): void; - - /** - * Wrap an object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. - * @param object A Game Object, a Physics Body, or any object with `x` and `y` coordinates - * @param padding An amount added to the boundary. Default 0. - */ - wrapObject(object: any, padding?: number): void; - - /** - * Shuts down the simulation, clearing physics data and removing listeners. - */ - shutdown(): void; - - /** - * Shuts down the simulation and disconnects it from the current scene. - */ - destroy(): void; - - } - - } - - /** - * An Impact.js compatible physics world, body and solver, for those who are used - * to the Impact way of defining and controlling physics bodies. Also works with - * the new Loader support for Weltmeister map data. - * - * World updated to run off the Phaser main loop. - * Body extended to support additional setter functions. - * - * To create the map data you'll need Weltmeister, which comes with Impact - * and can be purchased from http://impactjs.com - * - * My thanks to Dominic Szablewski for his permission to support Impact in Phaser. - */ - namespace Impact { - /** - * An Impact.js compatible physics body. - * This re-creates the properties you'd get on an Entity and the math needed to update them. - */ - class Body { - /** - * - * @param world [description] - * @param x [description] - * @param y [description] - * @param sx [description] Default 16. - * @param sy [description] Default 16. - */ - constructor(world: Phaser.Physics.Impact.World, x: number, y: number, sx?: number, sy?: number); - - /** - * [description] - */ - world: Phaser.Physics.Impact.World; - - /** - * [description] - */ - gameObject: Phaser.GameObjects.GameObject; - - /** - * [description] - */ - enabled: boolean; - - /** - * The ImpactBody, ImpactSprite or ImpactImage object that owns this Body, if any. - */ - parent: Phaser.Physics.Impact.ImpactBody | Phaser.Physics.Impact.ImpactImage | Phaser.Physics.Impact.ImpactSprite; - - /** - * [description] - */ - id: integer; - - /** - * [description] - */ - name: string; - - /** - * [description] - */ - size: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - offset: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - pos: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - last: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - vel: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - accel: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - friction: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - maxVel: Phaser.Types.Math.Vector2Like; - - /** - * [description] - */ - standing: boolean; - - /** - * [description] - */ - gravityFactor: number; - - /** - * [description] - */ - bounciness: number; - - /** - * [description] - */ - minBounceVelocity: number; - - /** - * [description] - */ - accelGround: number; - - /** - * [description] - */ - accelAir: number; - - /** - * [description] - */ - jumpSpeed: number; - - /** - * [description] - */ - type: Phaser.Physics.Impact.TYPE; - - /** - * [description] - */ - checkAgainst: Phaser.Physics.Impact.TYPE; - - /** - * [description] - */ - collides: Phaser.Physics.Impact.COLLIDES; - - /** - * [description] - */ - debugShowBody: boolean; - - /** - * [description] - */ - debugShowVelocity: boolean; - - /** - * [description] - */ - debugBodyColor: integer; - - /** - * [description] - */ - updateCallback: Phaser.Types.Physics.Impact.BodyUpdateCallback; - - /** - * min 44 deg, max 136 deg - */ - slopeStanding: Object; - - /** - * [description] - * @param x [description] - * @param y [description] - */ - reset(x: number, y: number): void; - - /** - * [description] - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(delta: number): void; - - /** - * [description] - * @param graphic [description] - */ - drawDebug(graphic: Phaser.GameObjects.Graphics): void; - - /** - * [description] - */ - willDrawDebug(): boolean; - - /** - * [description] - */ - skipHash(): boolean; - - /** - * Determines whether the body collides with the `other` one or not. - * @param other [description] - */ - touches(other: Phaser.Physics.Impact.Body): boolean; - - /** - * Reset the size and position of the physics body. - * @param x The x coordinate to position the body. - * @param y The y coordinate to position the body. - * @param width The width of the body. - * @param height The height of the body. - */ - resetSize(x: number, y: number, width: number, height: number): Phaser.Physics.Impact.Body; - - /** - * Export this body object to JSON. - */ - toJSON(): Phaser.Types.Physics.Impact.JSONImpactBody; - - /** - * [description] - * @param config [description] - */ - fromJSON(config: object): void; - - /** - * Can be overridden by user code - * @param other [description] - */ - check(other: Phaser.Physics.Impact.Body): void; - - /** - * Can be overridden by user code - * @param other [description] - * @param axis [description] - */ - collideWith(other: Phaser.Physics.Impact.Body, axis: string): void; - - /** - * Can be overridden by user code but must return a boolean. - * @param res [description] - */ - handleMovementTrace(res: number): boolean; - - /** - * [description] - */ - destroy(): void; - - } - - /** - * Collision Types - Determine if and how entities collide with each other. - * - * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, - * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE - * collisions, both entities are moved. LITE or PASSIVE entities don't collide - * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. - * FIXED collisions is undefined. - */ - enum COLLIDES { - /** - * Never collides. - */ - NEVER, - /** - * Lite collision. - */ - LITE, - /** - * Passive collision. - */ - PASSIVE, - /** - * Active collision. - */ - ACTIVE, - /** - * Fixed collision. - */ - FIXED, - } - - /** - * [description] - */ - class CollisionMap { - /** - * - * @param tilesize [description] Default 32. - * @param data [description] - */ - constructor(tilesize?: integer, data?: any[]); - - /** - * [description] - */ - tilesize: integer; - - /** - * [description] - */ - data: any[]; - - /** - * [description] - */ - width: number; - - /** - * [description] - */ - height: number; - - /** - * [description] - */ - lastSlope: integer; - - /** - * [description] - */ - tiledef: object; - - /** - * [description] - * @param x [description] - * @param y [description] - * @param vx [description] - * @param vy [description] - * @param objectWidth [description] - * @param objectHeight [description] - */ - trace(x: number, y: number, vx: number, vy: number, objectWidth: number, objectHeight: number): boolean; - - /** - * [description] - * @param res [description] - * @param x [description] - * @param y [description] - * @param vx [description] - * @param vy [description] - * @param width [description] - * @param height [description] - * @param rvx [description] - * @param rvy [description] - * @param step [description] - */ - step(res: object, x: number, y: number, vx: number, vy: number, width: number, height: number, rvx: number, rvy: number, step: number): void; - - /** - * [description] - * @param res [description] - * @param t [description] - * @param x [description] - * @param y [description] - * @param vx [description] - * @param vy [description] - * @param width [description] - * @param height [description] - * @param tileX [description] - * @param tileY [description] - */ - checkDef(res: object, t: number, x: number, y: number, vx: number, vy: number, width: number, height: number, tileX: number, tileY: number): boolean; - - } - - namespace Components { - /** - * The Impact Acceleration component. - * Should be applied as a mixin. - */ - interface Acceleration { - /** - * Sets the horizontal acceleration of this body. - * @param x The amount of acceleration to apply. - */ - setAccelerationX(x: number): this; - /** - * Sets the vertical acceleration of this body. - * @param y The amount of acceleration to apply. - */ - setAccelerationY(y: number): this; - /** - * Sets the horizontal and vertical acceleration of this body. - * @param x The amount of horizontal acceleration to apply. - * @param y The amount of vertical acceleration to apply. - */ - setAcceleration(x: number, y: number): this; - } - - /** - * The Impact Body Scale component. - * Should be applied as a mixin. - */ - interface BodyScale { - /** - * Sets the size of the physics body. - * @param width The width of the body in pixels. - * @param height The height of the body in pixels. Default width. - */ - setBodySize(width: number, height?: number): this; - /** - * Sets the scale of the physics body. - * @param scaleX The horizontal scale of the body. - * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. - */ - setBodyScale(scaleX: number, scaleY?: number): this; - } - - /** - * The Impact Body Type component. - * Should be applied as a mixin. - */ - interface BodyType { - /** - * [description] - */ - getBodyType(): number; - /** - * [description] - */ - setTypeNone(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setTypeA(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setTypeB(): Phaser.GameObjects.GameObject; - } - - /** - * The Impact Bounce component. - * Should be applied as a mixin. - */ - interface Bounce { - /** - * Sets the impact physics bounce, or restitution, value. - * @param value A value between 0 (no rebound) and 1 (full rebound) - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - /** - * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. - * @param value The minimum allowed velocity. - */ - setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; - /** - * The bounce, or restitution, value of this body. - * A value between 0 (no rebound) and 1 (full rebound) - */ - bounce: number; - } - - /** - * The Impact Check Against component. - * Should be applied as a mixin. - */ - interface CheckAgainst { - /** - * [description] - */ - setAvsB(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setBvsA(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setCheckAgainstNone(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setCheckAgainstA(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setCheckAgainstB(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - checkAgainst: number; - } - - /** - * The Impact Collides component. - * Should be applied as a mixin. - */ - interface Collides { - /** - * [description] - * @param callback [description] - * @param scope [description] - */ - setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setCollidesNever(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setLiteCollision(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setPassiveCollision(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setActiveCollision(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - setFixedCollision(): Phaser.GameObjects.GameObject; - /** - * [description] - */ - collides: number; - } - - /** - * The Impact Debug component. - * Should be applied as a mixin. - */ - interface Debug { - /** - * [description] - * @param showBody [description] - * @param showVelocity [description] - * @param bodyColor [description] - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; - /** - * [description] - * @param value [description] - */ - setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; - /** - * [description] - */ - debugShowBody: boolean; - /** - * [description] - */ - debugShowVelocity: boolean; - /** - * [description] - */ - debugBodyColor: number; - } - - /** - * The Impact Friction component. - * Should be applied as a mixin. - */ - interface Friction { - /** - * [description] - * @param x [description] - */ - setFrictionX(x: number): Phaser.GameObjects.GameObject; - /** - * [description] - * @param y [description] - */ - setFrictionY(y: number): Phaser.GameObjects.GameObject; - /** - * [description] - * @param x [description] - * @param y [description] - */ - setFriction(x: number, y: number): Phaser.GameObjects.GameObject; - } - - /** - * The Impact Gravity component. - * Should be applied as a mixin. - */ - interface Gravity { - /** - * [description] - * @param value [description] - */ - setGravity(value: number): Phaser.GameObjects.GameObject; - /** - * [description] - */ - gravity: number; - } - - /** - * The Impact Offset component. - * Should be applied as a mixin. - */ - interface Offset { - /** - * [description] - * @param x [description] - * @param y [description] - * @param width [description] - * @param height [description] - */ - setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; - } - - /** - * The Impact Set Game Object component. - * Should be applied as a mixin. - */ - interface SetGameObject { - /** - * [description] - * @param gameObject [description] - * @param sync [description] Default true. - */ - setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; - /** - * [description] - */ - syncGameObject(): Phaser.GameObjects.GameObject; - } - - /** - * The Impact Velocity component. - * Should be applied as a mixin. - */ - interface Velocity { - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): this; - /** - * Sets the vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): this; - /** - * Sets the horizontal and vertical velocities of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. - */ - setVelocity(x: number, y?: number): this; - /** - * Sets the maximum velocity this body can travel at. - * @param x The maximum allowed horizontal velocity. - * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - } - - } - - namespace Events { - /** - * The Impact Physics World Collide Event. - * - * This event is dispatched by an Impact Physics World instance if two bodies collide. - * - * Listen to it from a Scene using: `this.impact.world.on('collide', listener)`. - */ - const COLLIDE: any; - - /** - * The Impact Physics World Pause Event. - * - * This event is dispatched by an Impact Physics World instance when it is paused. - * - * Listen to it from a Scene using: `this.impact.world.on('pause', listener)`. - */ - const PAUSE: any; - - /** - * The Impact Physics World Resume Event. - * - * This event is dispatched by an Impact Physics World instance when it resumes from a paused state. - * - * Listen to it from a Scene using: `this.impact.world.on('resume', listener)`. - */ - const RESUME: any; - - } - - /** - * The Impact Physics Factory allows you to easily create Impact Physics enabled Game Objects. - * Objects that are created by this Factory are automatically added to the physics world. - */ - class Factory { - /** - * - * @param world A reference to the Impact Physics world. - */ - constructor(world: Phaser.Physics.Impact.World); - - /** - * A reference to the Impact Physics world. - */ - world: Phaser.Physics.Impact.World; - - /** - * A reference to the Scene.Systems this Impact Physics instance belongs to. - */ - sys: Phaser.Scenes.Systems; - - /** - * Creates a new ImpactBody object and adds it to the physics simulation. - * @param x The horizontal position of the body in the physics world. - * @param y The vertical position of the body in the physics world. - * @param width The width of the body. - * @param height The height of the body. - */ - body(x: number, y: number, width: number, height: number): Phaser.Physics.Impact.ImpactBody; - - /** - * Adds an Impact Physics Body to the given Game Object. - * @param gameObject The Game Object to receive the physics body. - */ - existing(gameObject: Phaser.GameObjects.GameObject): Phaser.GameObjects.GameObject; - - /** - * Creates a new ImpactImage object and adds it to the physics world. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - image(x: number, y: number, key: string, frame?: string | integer): Phaser.Physics.Impact.ImpactImage; - - /** - * Creates a new ImpactSprite object and adds it to the physics world. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - sprite(x: number, y: number, key: string, frame?: string | integer): Phaser.Physics.Impact.ImpactSprite; - - /** - * Destroys this Factory. - */ - destroy(): void; - - } - - /** - * [description] - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - * @param vel [description] - * @param accel [description] - * @param friction [description] - * @param max [description] - */ - function GetVelocity(delta: number, vel: number, accel: number, friction: number, max: number): number; - - /** - * [description] - */ - class ImpactBody implements Phaser.Physics.Impact.Components.Acceleration, Phaser.Physics.Impact.Components.BodyScale, Phaser.Physics.Impact.Components.BodyType, Phaser.Physics.Impact.Components.Bounce, Phaser.Physics.Impact.Components.CheckAgainst, Phaser.Physics.Impact.Components.Collides, Phaser.Physics.Impact.Components.Debug, Phaser.Physics.Impact.Components.Friction, Phaser.Physics.Impact.Components.Gravity, Phaser.Physics.Impact.Components.Offset, Phaser.Physics.Impact.Components.SetGameObject, Phaser.Physics.Impact.Components.Velocity { - /** - * - * @param world [description] - * @param x x - The horizontal position of this physics body in the world. - * @param y y - The vertical position of this physics body in the world. - * @param width The width of the physics body in the world. - * @param height [description] - */ - constructor(world: Phaser.Physics.Impact.World, x: number, y: number, width: number, height: number); - - /** - * [description] - */ - body: Phaser.Physics.Impact.Body; - - /** - * [description] - */ - size: Object; - - /** - * [description] - */ - offset: Object; - - /** - * [description] - */ - vel: Object; - - /** - * [description] - */ - accel: Object; - - /** - * [description] - */ - friction: Object; - - /** - * [description] - */ - maxVel: Object; - - /** - * Sets the horizontal acceleration of this body. - * @param x The amount of acceleration to apply. - */ - setAccelerationX(x: number): this; - - /** - * Sets the vertical acceleration of this body. - * @param y The amount of acceleration to apply. - */ - setAccelerationY(y: number): this; - - /** - * Sets the horizontal and vertical acceleration of this body. - * @param x The amount of horizontal acceleration to apply. - * @param y The amount of vertical acceleration to apply. - */ - setAcceleration(x: number, y: number): this; - - /** - * Sets the size of the physics body. - * @param width The width of the body in pixels. - * @param height The height of the body in pixels. Default width. - */ - setBodySize(width: number, height?: number): this; - - /** - * Sets the scale of the physics body. - * @param scaleX The horizontal scale of the body. - * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. - */ - setBodyScale(scaleX: number, scaleY?: number): this; - - /** - * [description] - */ - getBodyType(): number; - - /** - * [description] - */ - setTypeNone(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setTypeA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setTypeB(): Phaser.GameObjects.GameObject; - - /** - * Sets the impact physics bounce, or restitution, value. - * @param value A value between 0 (no rebound) and 1 (full rebound) - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. - * @param value The minimum allowed velocity. - */ - setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; - - /** - * The bounce, or restitution, value of this body. - * A value between 0 (no rebound) and 1 (full rebound) - */ - bounce: number; - - /** - * [description] - */ - setAvsB(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setBvsA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstNone(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstB(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - checkAgainst: number; - - /** - * [description] - * @param callback [description] - * @param scope [description] - */ - setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCollidesNever(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setLiteCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setPassiveCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setActiveCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setFixedCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - collides: number; - - /** - * [description] - * @param showBody [description] - * @param showVelocity [description] - * @param bodyColor [description] - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param value [description] - */ - setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - debugShowBody: boolean; - - /** - * [description] - */ - debugShowVelocity: boolean; - - /** - * [description] - */ - debugBodyColor: number; - - /** - * [description] - * @param x [description] - */ - setFrictionX(x: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param y [description] - */ - setFrictionY(y: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param x [description] - * @param y [description] - */ - setFriction(x: number, y: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param value [description] - */ - setGravity(value: number): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - gravity: number; - - /** - * [description] - * @param x [description] - * @param y [description] - * @param width [description] - * @param height [description] - */ - setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param gameObject [description] - * @param sync [description] Default true. - */ - setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - syncGameObject(): Phaser.GameObjects.GameObject; - - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): this; - - /** - * Sets the vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): this; - - /** - * Sets the horizontal and vertical velocities of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. - */ - setVelocity(x: number, y?: number): this; - - /** - * Sets the maximum velocity this body can travel at. - * @param x The maximum allowed horizontal velocity. - * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - - } - - /** - * An Impact Physics Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - */ - class ImpactImage extends Phaser.GameObjects.Image implements Phaser.Physics.Impact.Components.Acceleration, Phaser.Physics.Impact.Components.BodyScale, Phaser.Physics.Impact.Components.BodyType, Phaser.Physics.Impact.Components.Bounce, Phaser.Physics.Impact.Components.CheckAgainst, Phaser.Physics.Impact.Components.Collides, Phaser.Physics.Impact.Components.Debug, Phaser.Physics.Impact.Components.Friction, Phaser.Physics.Impact.Components.Gravity, Phaser.Physics.Impact.Components.Offset, Phaser.Physics.Impact.Components.SetGameObject, Phaser.Physics.Impact.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param world The physics world of the Impact physics system. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(world: Phaser.Physics.Impact.World, x: number, y: number, texture: string, frame?: string | integer); - - /** - * The Physics Body linked to an ImpactImage. - */ - body: Phaser.Physics.Impact.Body; - - /** - * The size of the physics Body. - */ - size: Object; - - /** - * The X and Y offset of the Body from the left and top of the Image. - */ - offset: Object; - - /** - * The velocity, or rate of change the Body's position. Measured in pixels per second. - */ - vel: Object; - - /** - * The acceleration is the rate of change of the velocity. Measured in pixels per second squared. - */ - accel: Object; - - /** - * Friction between colliding bodies. - */ - friction: Object; - - /** - * The maximum velocity of the body. - */ - maxVel: Object; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * Sets the horizontal acceleration of this body. - * @param x The amount of acceleration to apply. - */ - setAccelerationX(x: number): this; - - /** - * Sets the vertical acceleration of this body. - * @param y The amount of acceleration to apply. - */ - setAccelerationY(y: number): this; - - /** - * Sets the horizontal and vertical acceleration of this body. - * @param x The amount of horizontal acceleration to apply. - * @param y The amount of vertical acceleration to apply. - */ - setAcceleration(x: number, y: number): this; - - /** - * Sets the size of the physics body. - * @param width The width of the body in pixels. - * @param height The height of the body in pixels. Default width. - */ - setBodySize(width: number, height?: number): this; - - /** - * Sets the scale of the physics body. - * @param scaleX The horizontal scale of the body. - * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. - */ - setBodyScale(scaleX: number, scaleY?: number): this; - - /** - * [description] - */ - getBodyType(): number; - - /** - * [description] - */ - setTypeNone(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setTypeA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setTypeB(): Phaser.GameObjects.GameObject; - - /** - * Sets the impact physics bounce, or restitution, value. - * @param value A value between 0 (no rebound) and 1 (full rebound) - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. - * @param value The minimum allowed velocity. - */ - setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; - - /** - * The bounce, or restitution, value of this body. - * A value between 0 (no rebound) and 1 (full rebound) - */ - bounce: number; - - /** - * [description] - */ - setAvsB(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setBvsA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstNone(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstB(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - checkAgainst: number; - - /** - * [description] - * @param callback [description] - * @param scope [description] - */ - setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCollidesNever(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setLiteCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setPassiveCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setActiveCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setFixedCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - collides: number; - - /** - * [description] - * @param showBody [description] - * @param showVelocity [description] - * @param bodyColor [description] - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param value [description] - */ - setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - debugShowBody: boolean; - - /** - * [description] - */ - debugShowVelocity: boolean; - - /** - * [description] - */ - debugBodyColor: number; - - /** - * [description] - * @param x [description] - */ - setFrictionX(x: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param y [description] - */ - setFrictionY(y: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param x [description] - * @param y [description] - */ - setFriction(x: number, y: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param value [description] - */ - setGravity(value: number): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - gravity: number; - - /** - * [description] - * @param x [description] - * @param y [description] - * @param width [description] - * @param height [description] - */ - setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param gameObject [description] - * @param sync [description] Default true. - */ - setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - syncGameObject(): Phaser.GameObjects.GameObject; - - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): this; - - /** - * Sets the vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): this; - - /** - * Sets the horizontal and vertical velocities of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. - */ - setVelocity(x: number, y?: number): this; - - /** - * Sets the maximum velocity this body can travel at. - * @param x The maximum allowed horizontal velocity. - * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - - } - - /** - * [description] - */ - class ImpactPhysics { - /** - * - * @param scene [description] - */ - constructor(scene: Phaser.Scene); - - /** - * [description] - */ - scene: Phaser.Scene; - - /** - * [description] - */ - systems: Phaser.Scenes.Systems; - - /** - * [description] - */ - config: object; - - /** - * [description] - */ - world: Phaser.Physics.Impact.World; - - /** - * [description] - */ - add: Phaser.Physics.Impact.Factory; - - /** - * [description] - */ - getConfig(): object; - - /** - * [description] - */ - pause(): Phaser.Physics.Impact.World; - - /** - * [description] - */ - resume(): Phaser.Physics.Impact.World; - - } - - /** - * An Impact Physics Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - */ - class ImpactSprite extends Phaser.GameObjects.Sprite implements Phaser.Physics.Impact.Components.Acceleration, Phaser.Physics.Impact.Components.BodyScale, Phaser.Physics.Impact.Components.BodyType, Phaser.Physics.Impact.Components.Bounce, Phaser.Physics.Impact.Components.CheckAgainst, Phaser.Physics.Impact.Components.Collides, Phaser.Physics.Impact.Components.Debug, Phaser.Physics.Impact.Components.Friction, Phaser.Physics.Impact.Components.Gravity, Phaser.Physics.Impact.Components.Offset, Phaser.Physics.Impact.Components.SetGameObject, Phaser.Physics.Impact.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param world [description] - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - */ - constructor(world: Phaser.Physics.Impact.World, x: number, y: number, texture: string, frame?: string | integer); - - /** - * [description] - */ - body: Phaser.Physics.Impact.Body; - - /** - * [description] - */ - size: Object; - - /** - * [description] - */ - offset: Object; - - /** - * [description] - */ - vel: Object; - - /** - * [description] - */ - accel: Object; - - /** - * [description] - */ - friction: Object; - - /** - * [description] - */ - maxVel: Object; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * Sets the horizontal acceleration of this body. - * @param x The amount of acceleration to apply. - */ - setAccelerationX(x: number): this; - - /** - * Sets the vertical acceleration of this body. - * @param y The amount of acceleration to apply. - */ - setAccelerationY(y: number): this; - - /** - * Sets the horizontal and vertical acceleration of this body. - * @param x The amount of horizontal acceleration to apply. - * @param y The amount of vertical acceleration to apply. - */ - setAcceleration(x: number, y: number): this; - - /** - * Sets the size of the physics body. - * @param width The width of the body in pixels. - * @param height The height of the body in pixels. Default width. - */ - setBodySize(width: number, height?: number): this; - - /** - * Sets the scale of the physics body. - * @param scaleX The horizontal scale of the body. - * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. - */ - setBodyScale(scaleX: number, scaleY?: number): this; - - /** - * [description] - */ - getBodyType(): number; - - /** - * [description] - */ - setTypeNone(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setTypeA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setTypeB(): Phaser.GameObjects.GameObject; - - /** - * Sets the impact physics bounce, or restitution, value. - * @param value A value between 0 (no rebound) and 1 (full rebound) - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. - * @param value The minimum allowed velocity. - */ - setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; - - /** - * The bounce, or restitution, value of this body. - * A value between 0 (no rebound) and 1 (full rebound) - */ - bounce: number; - - /** - * [description] - */ - setAvsB(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setBvsA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstNone(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstA(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCheckAgainstB(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - checkAgainst: number; - - /** - * [description] - * @param callback [description] - * @param scope [description] - */ - setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setCollidesNever(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setLiteCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setPassiveCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setActiveCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - setFixedCollision(): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - collides: number; - - /** - * [description] - * @param showBody [description] - * @param showVelocity [description] - * @param bodyColor [description] - */ - setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param value [description] - */ - setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - debugShowBody: boolean; - - /** - * [description] - */ - debugShowVelocity: boolean; - - /** - * [description] - */ - debugBodyColor: number; - - /** - * [description] - * @param x [description] - */ - setFrictionX(x: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param y [description] - */ - setFrictionY(y: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param x [description] - * @param y [description] - */ - setFriction(x: number, y: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param value [description] - */ - setGravity(value: number): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - gravity: number; - - /** - * [description] - * @param x [description] - * @param y [description] - * @param width [description] - * @param height [description] - */ - setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; - - /** - * [description] - * @param gameObject [description] - * @param sync [description] Default true. - */ - setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; - - /** - * [description] - */ - syncGameObject(): Phaser.GameObjects.GameObject; - - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): this; - - /** - * Sets the vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): this; - - /** - * Sets the horizontal and vertical velocities of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. - */ - setVelocity(x: number, y?: number): this; - - /** - * Sets the maximum velocity this body can travel at. - * @param x The maximum allowed horizontal velocity. - * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. - */ - setMaxVelocity(x: number, y?: number): this; - - } - - /** - * [description] - * @param world [description] - * @param left [description] - * @param right [description] - * @param weak [description] - */ - function SeparateX(world: Phaser.Physics.Impact.World, left: Phaser.Physics.Impact.Body, right: Phaser.Physics.Impact.Body, weak?: Phaser.Physics.Impact.Body): void; - - /** - * [description] - * @param world [description] - * @param top [description] - * @param bottom [description] - * @param weak [description] - */ - function SeparateY(world: Phaser.Physics.Impact.World, top: Phaser.Physics.Impact.Body, bottom: Phaser.Physics.Impact.Body, weak?: Phaser.Physics.Impact.Body): void; - - /** - * Impact Physics Solver - * @param world The Impact simulation to run the solver in. - * @param bodyA The first body in the collision. - * @param bodyB The second body in the collision. - */ - function Solver(world: Phaser.Physics.Impact.World, bodyA: Phaser.Physics.Impact.Body, bodyB: Phaser.Physics.Impact.Body): void; - - /** - * Collision Types - Determine if and how entities collide with each other. - * - * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, - * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE - * collisions, both entities are moved. LITE or PASSIVE entities don't collide - * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. - * FIXED collisions is undefined. - */ - enum TYPE { - /** - * Collides with nothing. - */ - NONE, - /** - * Type A. Collides with Type B. - */ - A, - /** - * Type B. Collides with Type A. - */ - B, - /** - * Collides with both types A and B. - */ - BOTH, - } - - /** - * Set up the trace-result - * var res = { - * collision: {x: false, y: false, slope: false}, - * pos: {x: x, y: y}, - * tile: {x: 0, y: 0} - * }; - * @param body [description] - * @param res [description] - */ - function UpdateMotion(body: Phaser.Physics.Impact.Body, res: object): void; - - /** - * [description] - */ - class World extends Phaser.Events.EventEmitter { - /** - * - * @param scene The Scene to which this Impact World instance belongs. - * @param config [description] - */ - constructor(scene: Phaser.Scene, config: Phaser.Types.Physics.Impact.WorldConfig); - - /** - * [description] - */ - scene: Phaser.Scene; - - /** - * [description] - */ - bodies: Phaser.Structs.Set; - - /** - * [description] - */ - gravity: number; - - /** - * Spatial hash cell dimensions - */ - cellSize: integer; - - /** - * [description] - */ - collisionMap: Phaser.Physics.Impact.CollisionMap; - - /** - * [description] - */ - timeScale: number; - - /** - * Impacts maximum time step is 20 fps. - */ - maxStep: number; - - /** - * [description] - */ - enabled: boolean; - - /** - * [description] - */ - drawDebug: boolean; - - /** - * [description] - */ - debugGraphic: Phaser.GameObjects.Graphics; - - /** - * [description] - */ - defaults: Phaser.Types.Physics.Impact.WorldDefaults; - - /** - * An object containing the 4 wall bodies that bound the physics world. - */ - walls: Phaser.Types.Physics.Impact.WorldWalls; - - /** - * [description] - */ - delta: number; - - /** - * Sets the collision map for the world either from a Weltmeister JSON level in the cache or from - * a 2D array. If loading from a Weltmeister level, the map must have a layer called "collision". - * @param key Either a string key that corresponds to a Weltmeister level - * in the cache, or a 2D array of collision IDs. - * @param tileSize The size of a tile. This is optional if loading from a Weltmeister - * level in the cache. - */ - setCollisionMap(key: string | integer[][], tileSize: integer): Phaser.Physics.Impact.CollisionMap; - - /** - * Sets the collision map for the world from a tilemap layer. Only tiles that are marked as - * colliding will be used. You can specify the mapping from tiles to slope IDs in a couple of - * ways. The easiest is to use Tiled and the slopeTileProperty option. Alternatively, you can - * manually create a slopeMap that stores the mapping between tile indices and slope IDs. - * @param tilemapLayer The tilemap layer to use. - * @param options Options for controlling the mapping from tiles to slope IDs. - */ - setCollisionMapFromTilemapLayer(tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, options?: Phaser.Types.Physics.Impact.CollisionOptions): Phaser.Physics.Impact.CollisionMap; - - /** - * Sets the bounds of the Physics world to match the given world pixel dimensions. - * You can optionally set which 'walls' to create: left, right, top or bottom. - * If none of the walls are given it will default to use the walls settings it had previously. - * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size - * the newly created bounds will also not have the left and right walls. - * Explicitly state them in the parameters to override this. - * @param x The x coordinate of the top-left corner of the bounds. - * @param y The y coordinate of the top-left corner of the bounds. - * @param width The width of the bounds. - * @param height The height of the bounds. - * @param thickness [description] Default 64. - * @param left If true will create the left bounds wall. Default true. - * @param right If true will create the right bounds wall. Default true. - * @param top If true will create the top bounds wall. Default true. - * @param bottom If true will create the bottom bounds wall. Default true. - */ - setBounds(x?: number, y?: number, width?: number, height?: number, thickness?: number, left?: boolean, right?: boolean, top?: boolean, bottom?: boolean): Phaser.Physics.Impact.World; - - /** - * position = 'left', 'right', 'top' or 'bottom' - * @param add [description] - * @param position [description] - * @param x [description] - * @param y [description] - * @param width [description] - * @param height [description] - */ - updateWall(add: boolean, position: string, x: number, y: number, width: number, height: number): void; - - /** - * Creates a Graphics Game Object used for debug display and enables the world for debug drawing. - */ - createDebugGraphic(): Phaser.GameObjects.Graphics; - - /** - * [description] - */ - getNextID(): integer; - - /** - * [description] - * @param x [description] - * @param y [description] - * @param sizeX [description] - * @param sizeY [description] - */ - create(x: number, y: number, sizeX: number, sizeY: number): Phaser.Physics.Impact.Body; - - /** - * [description] - * @param object The Body to remove from this World. - */ - remove(object: Phaser.Physics.Impact.Body): void; - - /** - * [description] - */ - pause(): Phaser.Physics.Impact.World; - - /** - * [description] - */ - resume(): Phaser.Physics.Impact.World; - - /** - * [description] - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(time: number, delta: number): void; - - /** - * Check the body against the spatial hash. - * @param body [description] - * @param hash [description] - * @param size [description] - */ - checkHash(body: Phaser.Physics.Impact.Body, hash: object, size: number): void; - - /** - * [description] - * @param bodyA [description] - * @param bodyB [description] - */ - checkBodies(bodyA: Phaser.Physics.Impact.Body, bodyB: Phaser.Physics.Impact.Body): void; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the collides value on. - */ - setCollidesNever(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the collides value on. - */ - setLite(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the collides value on. - */ - setPassive(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the collides value on. - */ - setActive(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the collides value on. - */ - setFixed(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setTypeNone(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setTypeA(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setTypeB(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setAvsB(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setBvsA(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setCheckAgainstNone(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setCheckAgainstA(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - * @param bodies An Array of Impact Bodies to set the type value on. - */ - setCheckAgainstB(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; - - /** - * [description] - */ - shutdown(): void; - - /** - * [description] - */ - destroy(): void; - - } - - } - - namespace Matter { - /** - * 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 { - /** - * A Vector2 that stores the temporary bounds center value during calculations by methods in this class. - */ - boundsCenter: Phaser.Math.Vector2; - - /** - * A Vector2 that stores the temporary center diff values during calculations by methods in this class. - */ - centerDiff: Phaser.Math.Vector2; - - /** - * Parses the given body to get the bounds diff values from it. - * - * They're stored in this class in the temporary properties `boundsCenter` and `centerDiff`. - * - * This method is called automatically by all other methods in this class. - * @param body The Body to get the bounds position from. - */ - parseBody(body: Phaser.Types.Physics.Matter.MatterBody): boolean; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getTopLeft(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getTopCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getTopRight(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getLeftCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getRightCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getBottomLeft(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getBottomCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - /** - * 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 bodies _current_ position and bounds. - * @param body The Body to get the position from. - * @param x Optional horizontal offset to add to the returned coordinates. Default 0. - * @param y Optional vertical offset to add to the returned coordinates. Default 0. - */ - getBottomRight(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; - - } - - namespace Components { - /** - * A component to set restitution on objects. - */ - interface Bounce { - /** - * Sets the restitution on the physics object. - * @param 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)` - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - } - - /** - * Contains methods for changing the collision filter of a Matter Body. Should be used as a mixin and not called directly. - */ - interface Collision { - /** - * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. - * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * @param value Unique category bitfield. - */ - setCollisionCategory(value: number): Phaser.GameObjects.GameObject; - /** - * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, - * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, - * they will never collide. - * @param value Unique group index. - */ - setCollisionGroup(value: number): Phaser.GameObjects.GameObject; - /** - * 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. - * @param categories A unique category bitfield, or an array of them. - */ - setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body starts colliding with another. - */ - setOnCollide(callback: Function): Phaser.GameObjects.GameObject; - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body stops colliding with another. - */ - setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke for the duration of this body colliding with another. - */ - setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; - /** - * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param body The body, or an array of bodies, to test for collisions with. - * @param callback The callback to invoke when this body collides with the given body or bodies. - */ - setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; - } - - /** - * A component to apply force to Matter.js bodies. - */ - interface Force { - /** - * Applies a force to a body. - * @param force A Vector that specifies the force to apply. - */ - applyForce(force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; - /** - * Applies a force to a body from a given position. - * @param position The position in which the force comes from. - * @param force A Vector that specifies the force to apply. - */ - applyForceFrom(position: Phaser.Math.Vector2, force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; - /** - * Apply thrust to the forward position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrust(speed: number): Phaser.GameObjects.GameObject; - /** - * Apply thrust to the left position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustLeft(speed: number): Phaser.GameObjects.GameObject; - /** - * Apply thrust to the right position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustRight(speed: number): Phaser.GameObjects.GameObject; - /** - * Apply thrust to the back position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustBack(speed: number): Phaser.GameObjects.GameObject; - } - - /** - * Contains methods for changing the friction of a Game Object's Matter Body. Should be used a mixin, not called directly. - */ - interface Friction { - /** - * Sets new friction values for this Game Object's Matter Body. - * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. - * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. - * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. - */ - setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; - /** - * Sets a new air resistance for this Game Object's Matter Body. - * A value of 0 means the Body will never slow as it moves through space. - * The higher the value, the faster a Body slows when moving through space. - * @param value The new air resistance for the Body. - */ - setFrictionAir(value: number): Phaser.GameObjects.GameObject; - /** - * Sets a new static friction for this Game Object's Matter Body. - * A value of 0 means the Body will never "stick" when it is nearly stationary. - * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. - * @param value The new static friction for the Body. - */ - setFrictionStatic(value: number): Phaser.GameObjects.GameObject; - } - - /** - * A component to manipulate world gravity for Matter.js bodies. - */ - interface Gravity { - /** - * A togglable function for ignoring world gravity in real-time on the current body. - * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. - */ - setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; - } - - /** - * Allows accessing the mass, density, and center of mass of a Matter-enabled Game Object. Should be used as a mixin and not directly. - */ - interface Mass { - /** - * Sets the mass of the Game Object's Matter Body. - * @param value The new mass of the body. - */ - setMass(value: number): Phaser.GameObjects.GameObject; - /** - * Sets density of the body. - * @param value The new density of the body. - */ - setDensity(value: number): Phaser.GameObjects.GameObject; - /** - * The body's center of mass. - * - * Calling this creates a new `Vector2 each time to avoid mutation. - * - * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. - */ - readonly centerOfMass: Phaser.Math.Vector2; - } - - /** - * Enables a Matter-enabled Game Object to be a sensor. Should be used as a mixin and not directly. - */ - interface Sensor { - /** - * Set the body belonging to this Game Object to be a sensor. - * Sensors trigger collision events, but don't react with colliding body physically. - * @param value `true` to set the body as a sensor, or `false` to disable it. - */ - setSensor(value: boolean): Phaser.GameObjects.GameObject; - /** - * Is the body belonging to this Game Object a sensor or not? - */ - isSensor(): boolean; - } - - /** - * Enables a Matter-enabled Game Object to set its Body. Should be used as a mixin and not directly. - */ - interface SetBody { - /** - * Set the body on a Game Object to a rectangle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param width Width of the rectangle. - * @param height Height of the rectangle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setRectangle(width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - /** - * Set the body on a Game Object to a circle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param radius The radius of the circle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setCircle(radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - /** - * Set the body on the Game Object to a polygon shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param sides The number of sides the polygon will have. - * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setPolygon(sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - /** - * Set the body on the Game Object to a trapezoid shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param width The width of the trapezoid Body. - * @param height The height of the trapezoid Body. - * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setTrapezoid(width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - /** - * Set this Game Object to use the given existing Matter Body. - * - * The body is first removed from the world before being added to this Game Object. - * @param body The Body this Game Object should use. - * @param addToWorld Should the body be immediately added to the World? Default true. - */ - setExistingBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.GameObjects.GameObject; - /** - * Set this Game Object to create and use a new Body based on the configuration object given. - * - * Calling this method resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param config Either a string, such as `circle`, or a Matter Set Body Configuration object. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setBody(config: string | Phaser.Types.Physics.Matter.MatterSetBodyConfig, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - } - - /** - * Enables a Matter-enabled Game Object to be able to go to sleep. Should be used as a mixin and not directly. - */ - interface Sleep { - /** - * Sets this Body to sleep. - */ - setToSleep(): this; - /** - * Wakes this Body if asleep. - */ - setAwake(): this; - /** - * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). - * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. - */ - setSleepThreshold(value?: number): this; - /** - * Enable sleep and wake events for this body. - * - * By default when a body goes to sleep, or wakes up, it will not emit any events. - * - * The events are emitted by the Matter World instance and can be listened to via - * the `SLEEP_START` and `SLEEP_END` events. - * @param start `true` if you want the sleep start event to be emitted for this body. - * @param end `true` if you want the sleep end event to be emitted for this body. - */ - setSleepEvents(start: boolean, end: boolean): this; - /** - * Enables or disables the Sleep Start event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepStartEvent(value: boolean): this; - /** - * Enables or disables the Sleep End event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepEndEvent(value: boolean): this; - } - - /** - * Provides methods used for getting and setting the static state of a physics body. - */ - interface Static { - /** - * Changes the physics body to be either static `true` or dynamic `false`. - * @param value `true` to set the body as being static, or `false` to make it dynamic. - */ - setStatic(value: boolean): Phaser.GameObjects.GameObject; - /** - * Returns `true` if the body is static, otherwise `false` for a dynamic body. - */ - isStatic(): boolean; - } - - /** - * Provides methods used for getting and setting the position, scale and rotation of a Game Object. - */ - interface Transform { - /** - * The x position of this Game Object. - */ - x: number; - /** - * The y position of this Game Object. - */ - y: number; - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - /** - * Use `angle` to set or get rotation of the physics body associated to this GameObject. - * Unlike rotation, when using set the value can be in degrees, which will be converted to radians internally. - */ - angle: number; - /** - * Use `rotation` to set or get the rotation of the physics body associated with this GameObject. - * The value when set must be in radians. - */ - rotation: number; - /** - * Sets the position of the physics body along x and y axes. - * Both the parameters to this function are optional and if not passed any they default to 0. - * Velocity, angle, force etc. are unchanged. - * @param x The horizontal position of the body. Default 0. - * @param y The vertical position of the body. Default x. - */ - setPosition(x?: number, y?: number): this; - /** - * Immediately sets the angle of the Body. - * Angular velocity, position, force etc. are unchanged. - * @param radians The angle of the body, in radians. Default 0. - */ - setRotation(radians?: number): this; - /** - * Setting fixed rotation sets the Body inertia to Infinity, which stops it - * from being able to rotate when forces are applied to it. - */ - setFixedRotation(): this; - /** - * Immediately sets the angle of the Body. - * Angular velocity, position, force etc. are unchanged. - * @param degrees The angle to set, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. Default 1. - * @param y The vertical scale of this Game Object. If not set it will use the x value. Default x. - * @param point The point (Vector2) from which scaling will occur. - */ - setScale(x?: number, y?: number, point?: Phaser.Math.Vector2): this; - } - - /** - * Contains methods for changing the velocity of a Matter Body. Should be used as a mixin and not called directly. - */ - interface Velocity { - /** - * Sets the angular velocity of the body instantly. - * Position, angle, force etc. are unchanged. - * @param value The angular velocity. - */ - setAngularVelocity(value: number): Phaser.GameObjects.GameObject; - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): Phaser.GameObjects.GameObject; - /** - * Sets vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): Phaser.GameObjects.GameObject; - /** - * Sets both the horizontal and vertical velocity of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. Default x. - */ - setVelocity(x: number, y?: number): Phaser.GameObjects.GameObject; - } - - } - - namespace Matter { - } - - namespace Events { - type AfterAddEvent = { - /** - * An array of the object(s) that have been added. May be a single body, constraint, composite or a mixture of these. - */ - object: any[]; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics After Add Event. - * - * This event is dispatched by a Matter Physics World instance at the end of the process when a new Body - * or Constraint has just been added to the world. - * - * Listen to it from a Scene using: `this.matter.world.on('afteradd', listener)`. - */ - const AFTER_ADD: any; - - type AfterRemoveEvent = { - /** - * An array of the object(s) that were removed. May be a single body, constraint, composite or a mixture of these. - */ - object: any[]; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics After Remove Event. - * - * This event is dispatched by a Matter Physics World instance at the end of the process when a - * Body or Constraint was removed from the world. - * - * Listen to it from a Scene using: `this.matter.world.on('afterremove', listener)`. - */ - const AFTER_REMOVE: any; - - type AfterUpdateEvent = { - /** - * The Matter Engine `timing.timestamp` value for the event. - */ - timestamp: number; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics After Update Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated and all collision events have resolved. - * - * Listen to it from a Scene using: `this.matter.world.on('afterupdate', listener)`. - */ - const AFTER_UPDATE: any; - - type BeforeAddEvent = { - /** - * An array of the object(s) to be added. May be a single body, constraint, composite or a mixture of these. - */ - object: any[]; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Before Add Event. - * - * This event is dispatched by a Matter Physics World instance at the start of the process when a new Body - * or Constraint is being added to the world. - * - * Listen to it from a Scene using: `this.matter.world.on('beforeadd', listener)`. - */ - const BEFORE_ADD: any; - - type BeforeRemoveEvent = { - /** - * An array of the object(s) to be removed. May be a single body, constraint, composite or a mixture of these. - */ - object: any[]; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Before Remove Event. - * - * This event is dispatched by a Matter Physics World instance at the start of the process when a - * Body or Constraint is being removed from the world. - * - * Listen to it from a Scene using: `this.matter.world.on('beforeremove', listener)`. - */ - const BEFORE_REMOVE: any; - - type BeforeUpdateEvent = { - /** - * The Matter Engine `timing.timestamp` value for the event. - */ - timestamp: number; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Before Update Event. - * - * This event is dispatched by a Matter Physics World instance right before all the collision processing takes place. - * - * Listen to it from a Scene using: `this.matter.world.on('beforeupdate', listener)`. - */ - const BEFORE_UPDATE: any; - - type CollisionActiveEvent = { - /** - * A list of all affected pairs in the collision. - */ - pairs: Phaser.Types.Physics.Matter.MatterCollisionData[]; - /** - * The Matter Engine `timing.timestamp` value for the event. - */ - timestamp: number; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Collision Active Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated. - * It provides a list of all pairs that are colliding in the current tick (if any). - * - * Listen to it from a Scene using: `this.matter.world.on('collisionactive', listener)`. - */ - const COLLISION_ACTIVE: any; - - type CollisionEndEvent = { - /** - * A list of all affected pairs in the collision. - */ - pairs: Phaser.Types.Physics.Matter.MatterCollisionData[]; - /** - * The Matter Engine `timing.timestamp` value for the event. - */ - timestamp: number; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Collision End Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated. - * It provides a list of all pairs that have finished colliding in the current tick (if any). - * - * Listen to it from a Scene using: `this.matter.world.on('collisionend', listener)`. - */ - const COLLISION_END: any; - - type CollisionStartEvent = { - /** - * A list of all affected pairs in the collision. - */ - pairs: Phaser.Types.Physics.Matter.MatterCollisionData[]; - /** - * The Matter Engine `timing.timestamp` value for the event. - */ - timestamp: number; - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Collision Start Event. - * - * This event is dispatched by a Matter Physics World instance after the engine has updated. - * It provides a list of all pairs that have started to collide in the current tick (if any). - * - * Listen to it from a Scene using: `this.matter.world.on('collisionstart', listener)`. - */ - const COLLISION_START: any; - - /** - * The Matter Physics Drag End Event. - * - * This event is dispatched by a Matter Physics World instance when a Pointer Constraint - * stops dragging a body. - * - * Listen to it from a Scene using: `this.matter.world.on('dragend', listener)`. - */ - const DRAG_END: any; - - /** - * The Matter Physics Drag Event. - * - * This event is dispatched by a Matter Physics World instance when a Pointer Constraint - * is actively dragging a body. It is emitted each time the pointer moves. - * - * Listen to it from a Scene using: `this.matter.world.on('drag', listener)`. - */ - const DRAG: any; - - /** - * The Matter Physics Drag Start Event. - * - * This event is dispatched by a Matter Physics World instance when a Pointer Constraint - * starts dragging a body. - * - * Listen to it from a Scene using: `this.matter.world.on('dragstart', listener)`. - */ - const DRAG_START: any; - - /** - * The Matter Physics World Pause Event. - * - * This event is dispatched by an Matter Physics World instance when it is paused. - * - * Listen to it from a Scene using: `this.matter.world.on('pause', listener)`. - */ - const PAUSE: any; - - /** - * The Matter Physics World Resume Event. - * - * This event is dispatched by an Matter Physics World instance when it resumes from a paused state. - * - * Listen to it from a Scene using: `this.matter.world.on('resume', listener)`. - */ - const RESUME: any; - - type SleepEndEvent = { - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Sleep End Event. - * - * This event is dispatched by a Matter Physics World instance when a Body stop sleeping. - * - * Listen to it from a Scene using: `this.matter.world.on('sleepend', listener)`. - */ - const SLEEP_END: any; - - type SleepStartEvent = { - /** - * The source object of the event. - */ - source: any; - /** - * The name of the event. - */ - name: string; - }; - - /** - * The Matter Physics Sleep Start Event. - * - * This event is dispatched by a Matter Physics World instance when a Body goes to sleep. - * - * Listen to it from a Scene using: `this.matter.world.on('sleepstart', listener)`. - */ - const SLEEP_START: any; - - } - - /** - * The Matter Factory is responsible for quickly creating a variety of different types of - * bodies, constraints and Game Objects and adding them into the physics world. - * - * You access the factory from within a Scene using `add`: - * - * ```javascript - * this.matter.add.rectangle(x, y, width, height); - * ``` - * - * Use of the Factory is optional. All of the objects it creates can also be created - * directly via your own code or constructors. It is provided as a means to keep your - * code concise. - */ - class Factory { - /** - * - * @param world The Matter World which this Factory adds to. - */ - constructor(world: Phaser.Physics.Matter.World); - - /** - * The Matter World which this Factory adds to. - */ - world: Phaser.Physics.Matter.World; - - /** - * The Scene which this Factory's Matter World belongs to. - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene.Systems this Matter Physics instance belongs to. - */ - sys: Phaser.Scenes.Systems; - - /** - * Creates a new rigid rectangular Body and adds it to the World. - * @param x The X coordinate of the center of the Body. - * @param y The Y coordinate of the center of the Body. - * @param width The width of the Body. - * @param height The height of the Body. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - rectangle(x: number, y: number, width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; - - /** - * Creates a new rigid trapezoidal Body and adds it to the World. - * @param x The X coordinate of the center of the Body. - * @param y The Y coordinate of the center of the Body. - * @param width The width of the trapezoid Body. - * @param height The height of the trapezoid Body. - * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - trapezoid(x: number, y: number, width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; - - /** - * Creates a new rigid circular Body and adds it to the World. - * @param x The X coordinate of the center of the Body. - * @param y The Y coordinate of the center of the Body. - * @param radius The radius of the circle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - * @param maxSides The maximum amount of sides to use for the polygon which will approximate this circle. - */ - circle(x: number, y: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, maxSides?: number): MatterJS.BodyType; - - /** - * Creates a new rigid polygonal Body and adds it to the World. - * @param x The X coordinate of the center of the Body. - * @param y The Y coordinate of the center of the Body. - * @param sides The number of sides the polygon will have. - * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - polygon(x: number, y: number, sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; - - /** - * Creates a body using the supplied vertices (or an array containing multiple sets of vertices) and adds it to the World. - * If the vertices are convex, they will pass through as supplied. Otherwise, if the vertices are concave, they will be decomposed. Note that this process is not guaranteed to support complex sets of vertices, e.g. ones with holes. - * @param x The X coordinate of the center of the Body. - * @param y The Y coordinate of the center of the Body. - * @param vertexSets The vertices data. Either a path string or an array of vertices. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - * @param flagInternal Flag internal edges (coincident part edges) Default false. - * @param removeCollinear Whether Matter.js will discard collinear edges (to improve performance). Default 0.01. - * @param minimumArea During decomposition discard parts that have an area less than this. Default 10. - */ - fromVertices(x: number, y: number, vertexSets: string | any[], options?: Phaser.Types.Physics.Matter.MatterBodyConfig, flagInternal?: boolean, removeCollinear?: number, minimumArea?: number): MatterJS.BodyType; - - /** - * 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 pas in an `options` object, any settings in there will override those in the PhysicsEditor config object. - * @param x The horizontal world location of the body. - * @param y The vertical world location of the body. - * @param config The JSON data exported from PhysicsEditor. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - * @param addToWorld Should the newly created body be immediately added to the World? Default true. - */ - fromPhysicsEditor(x: number, y: number, config: any, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, addToWorld?: boolean): MatterJS.BodyType; - - /** - * 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')); - * } - * ``` - * @param x The X coordinate of the body. - * @param y The Y coordinate of the body. - * @param xml The SVG Path data. - * @param scale Scale the vertices by this amount after creation. Default 1. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - * @param addToWorld Should the newly created body be immediately added to the World? Default true. - */ - fromSVG(x: number, y: number, xml: object, scale?: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, addToWorld?: boolean): MatterJS.BodyType; - - /** - * Creates a body using the supplied physics data, as provided by a JSON file. - * - * The data file should be loaded as JSON: - * - * ```javascript - * preload () - * { - * this.load.json('ninjas', 'assets/ninjas.json); - * } - * - * create () - * { - * const ninjaShapes = this.cache.json.get('ninjas'); - * - * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); - * } - * ``` - * - * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. - * - * If you pas in an `options` object, any settings in there will override those in the config object. - * - * The structure of the JSON file is as follows: - * - * ```text - * { - * 'generator_info': // The name of the application that created the JSON data - * 'shapeName': { - * 'type': // The type of body - * 'label': // Optional body label - * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs - * } - * } - * ``` - * - * At the time of writing, only the Phaser Physics Tracer App exports in this format. - * @param x The X coordinate of the body. - * @param y The Y coordinate of the body. - * @param config The JSON physics data. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - * @param addToWorld Should the newly created body be immediately added to the World? Default true. - */ - fromJSON(x: number, y: number, config: any, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, addToWorld?: boolean): MatterJS.BodyType; - - /** - * Create a new composite containing Matter Image objects created in a grid arrangement. - * This function uses the body bounds to prevent overlaps. - * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. - * @param x The horizontal position of this composite in the world. - * @param y The vertical position of this composite in the world. - * @param columns The number of columns in the grid. - * @param rows The number of rows in the grid. - * @param columnGap The distance between each column. Default 0. - * @param rowGap The distance between each row. Default 0. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - imageStack(key: string, frame: string | integer, x: number, y: number, columns: number, rows: number, columnGap?: number, rowGap?: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.CompositeType; - - /** - * Create a new composite containing bodies created in the callback in a grid arrangement. - * - * This function uses the body bounds to prevent overlaps. - * @param x The horizontal position of this composite in the world. - * @param y The vertical position of this composite in the world. - * @param columns The number of columns in the grid. - * @param rows The number of rows in the grid. - * @param columnGap The distance between each column. - * @param rowGap The distance between each row. - * @param callback The callback that creates the stack. - */ - stack(x: number, y: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): MatterJS.CompositeType; - - /** - * Create a new composite containing bodies created in the callback in a pyramid arrangement. - * This function uses the body bounds to prevent overlaps. - * @param x The horizontal position of this composite in the world. - * @param y The vertical position of this composite in the world. - * @param columns The number of columns in the pyramid. - * @param rows The number of rows in the pyramid. - * @param columnGap The distance between each column. - * @param rowGap The distance between each row. - * @param callback The callback function to be invoked. - */ - pyramid(x: number, y: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): MatterJS.CompositeType; - - /** - * Chains all bodies in the given composite together using constraints. - * @param composite The composite in which all bodies will be chained together sequentially. - * @param xOffsetA The horizontal offset of the BodyA constraint. This is a percentage based on the body size, not a world position. - * @param yOffsetA The vertical offset of the BodyA constraint. This is a percentage based on the body size, not a world position. - * @param xOffsetB The horizontal offset of the BodyB constraint. This is a percentage based on the body size, not a world position. - * @param yOffsetB The vertical offset of the BodyB constraint. This is a percentage based on the body size, not a world position. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - chain(composite: MatterJS.CompositeType, xOffsetA: number, yOffsetA: number, xOffsetB: number, yOffsetB: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.CompositeType; - - /** - * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. - * @param composite The composite in which all bodies will be chained together. - * @param columns The number of columns in the mesh. - * @param rows The number of rows in the mesh. - * @param crossBrace Create cross braces for the mesh as well? - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - mesh(composite: MatterJS.CompositeType, columns: number, rows: number, crossBrace: boolean, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.CompositeType; - - /** - * Creates a composite with a Newton's Cradle setup of bodies and constraints. - * @param x The horizontal position of the start of the cradle. - * @param y The vertical position of the start of the cradle. - * @param number The number of balls in the cradle. - * @param size The radius of each ball in the cradle. - * @param length The length of the 'string' the balls hang from. - */ - newtonsCradle(x: number, y: number, number: number, size: number, length: number): MatterJS.CompositeType; - - /** - * Creates a composite with simple car setup of bodies and constraints. - * @param x The horizontal position of the car in the world. - * @param y The vertical position of the car in the world. - * @param width The width of the car chasis. - * @param height The height of the car chasis. - * @param wheelSize The radius of the car wheels. - */ - car(x: number, y: number, width: number, height: number, wheelSize: number): MatterJS.CompositeType; - - /** - * Creates a simple soft body like object. - * @param x The horizontal position of this composite in the world. - * @param y The vertical position of this composite in the world. - * @param columns The number of columns in the Composite. - * @param rows The number of rows in the Composite. - * @param columnGap The distance between each column. - * @param rowGap The distance between each row. - * @param crossBrace `true` to create cross braces between the bodies, or `false` to create just straight braces. - * @param particleRadius The radius of this circlular composite. - * @param particleOptions An optional Body configuration object that is used to set initial Body properties on creation. - * @param constraintOptions An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - softBody(x: number, y: number, columns: number, rows: number, columnGap: number, rowGap: number, crossBrace: boolean, particleRadius: number, particleOptions?: Phaser.Types.Physics.Matter.MatterBodyConfig, constraintOptions?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.CompositeType; - - /** - * This method is an alias for `Factory.constraint`. - * - * Constraints (or joints) 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. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * @param bodyA The first possible `Body` that this constraint is attached to. - * @param bodyB The second possible `Body` that this constraint is attached to. - * @param length A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - joint(bodyA: MatterJS.BodyType, bodyB: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; - - /** - * This method is an alias for `Factory.constraint`. - * - * Constraints (or joints) 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. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * @param bodyA The first possible `Body` that this constraint is attached to. - * @param bodyB The second possible `Body` that this constraint is attached to. - * @param length A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - spring(bodyA: MatterJS.BodyType, bodyB: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; - - /** - * Constraints (or joints) 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. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * @param bodyA The first possible `Body` that this constraint is attached to. - * @param bodyB The second possible `Body` that this constraint is attached to. - * @param length A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - constraint(bodyA: MatterJS.BodyType, bodyB: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; - - /** - * Constraints (or joints) are used for specifying that a fixed distance must be maintained - * between two bodies, or a body and a fixed world-space position. - * - * A world constraint has only one body, you should specify a `pointA` position in - * the constraint options parameter to attach the constraint to the world. - * - * The stiffness of constraints can be modified to create springs or elastic. - * - * 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 - * `constraintIterations` within the Matter Config. - * - * For compound bodies, constraints must be applied to the parent body and not one of its parts. - * @param body The Matter `Body` that this constraint is attached to. - * @param length A number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. - * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - worldConstraint(body: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; - - /** - * This method is an alias for `Factory.pointerConstraint`. - * - * A Pointer Constraint is a special type of constraint that allows you to click - * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, - * and when one is pressed down it checks to see if that hit any part of any active - * body in the world. If it did, and the body has input enabled, it will begin to - * drag it until either released, or you stop it via the `stopDrag` method. - * - * You can adjust the stiffness, length and other properties of the constraint via - * the `options` object on creation. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - mouseSpring(options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; - - /** - * A Pointer Constraint is a special type of constraint that allows you to click - * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, - * and when one is pressed down it checks to see if that hit any part of any active - * body in the world. If it did, and the body has input enabled, it will begin to - * drag it until either released, or you stop it via the `stopDrag` method. - * - * You can adjust the stiffness, length and other properties of the constraint via - * the `options` object on creation. - * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. - */ - pointerConstraint(options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; - - /** - * Creates a Matter Physics Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - image(x: number, y: number, key: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.Physics.Matter.Image; - - /** - * Creates a wrapper around a Tile that provides access to a corresponding Matter body. A tile can only - * have one Matter body associated with it. You can either pass in an existing Matter body for - * the tile or allow the constructor to create the corresponding body for you. If the Tile has a - * collision group (defined in Tiled), those shapes will be used to create the body. If not, the - * tile's rectangle bounding box will be used. - * - * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. - * - * Note: not all Tiled collision shapes are supported. See - * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. - * @param tile The target tile that should have a Matter body. - * @param options Options to be used when creating the Matter body. - */ - tileBody(tile: Phaser.Tilemaps.Tile, options?: Phaser.Types.Physics.Matter.MatterTileOptions): Phaser.Physics.Matter.TileBody; - - /** - * Creates a Matter Physics Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - sprite(x: number, y: number, key: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.Physics.Matter.Sprite; - - /** - * Takes an existing Game Object and injects all of the Matter Components into it. - * - * This enables you to use component methods such as `setVelocity` or `isSensor` directly from - * this Game Object. - * - * You can also pass in either a Matter Body Configuration object, or a Matter Body instance - * to link with this Game Object. - * @param gameObject The Game Object to inject the Matter Components in to. - * @param options A Matter Body configuration object, or an instance of a Matter Body. - * @param addToWorld Add this Matter Body to the World? Default true. - */ - gameObject(gameObject: Phaser.GameObjects.GameObject, options?: Phaser.Types.Physics.Matter.MatterBodyConfig | MatterJS.Body, addToWorld?: boolean): Phaser.GameObjects.GameObject; - - /** - * Destroys this Factory. - */ - destroy(): void; - - } - - /** - * A Matter Game Object is a generic object that allows you to combine any Phaser Game Object, - * including those you have extended or created yourself, with all of the Matter Components. - * - * This enables you to use component methods such as `setVelocity` or `isSensor` directly from - * this Game Object. - * @param world The Matter world to add the body to. - * @param gameObject The Game Object that will have the Matter body applied to it. - * @param options A Matter Body configuration object, or an instance of a Matter Body. - * @param addToWorld Should the newly created body be immediately added to the World? Default true. - */ - function MatterGameObject(world: Phaser.Physics.Matter.World, gameObject: Phaser.GameObjects.GameObject, options?: Phaser.Types.Physics.Matter.MatterBodyConfig | MatterJS.Body, addToWorld?: boolean): Phaser.GameObjects.GameObject; - - /** - * A Matter Physics Image Game Object. - * - * An Image is a light-weight Game Object useful for the display of static images in your game, - * such as logos, backgrounds, scenery or other non-animated elements. Images can have input - * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an - * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. - */ - class Image extends Phaser.GameObjects.Image implements Phaser.Physics.Matter.Components.Bounce, Phaser.Physics.Matter.Components.Collision, Phaser.Physics.Matter.Components.Force, Phaser.Physics.Matter.Components.Friction, Phaser.Physics.Matter.Components.Gravity, Phaser.Physics.Matter.Components.Mass, Phaser.Physics.Matter.Components.Sensor, Phaser.Physics.Matter.Components.SetBody, Phaser.Physics.Matter.Components.Sleep, Phaser.Physics.Matter.Components.Static, Phaser.Physics.Matter.Components.Transform, Phaser.Physics.Matter.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param world A reference to the Matter.World instance that this body belongs to. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - constructor(world: Phaser.Physics.Matter.World, x: number, y: number, texture: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig); - - /** - * A reference to the Matter.World instance that this body belongs to. - */ - world: Phaser.Physics.Matter.World; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * Sets the restitution on the physics object. - * @param 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)` - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. - * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * @param value Unique category bitfield. - */ - setCollisionCategory(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, - * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, - * they will never collide. - * @param value Unique group index. - */ - setCollisionGroup(value: number): Phaser.GameObjects.GameObject; - - /** - * 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. - * @param categories A unique category bitfield, or an array of them. - */ - setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body starts colliding with another. - */ - setOnCollide(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body stops colliding with another. - */ - setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke for the duration of this body colliding with another. - */ - setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param body The body, or an array of bodies, to test for collisions with. - * @param callback The callback to invoke when this body collides with the given body or bodies. - */ - setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; - - /** - * Applies a force to a body. - * @param force A Vector that specifies the force to apply. - */ - applyForce(force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; - - /** - * Applies a force to a body from a given position. - * @param position The position in which the force comes from. - * @param force A Vector that specifies the force to apply. - */ - applyForceFrom(position: Phaser.Math.Vector2, force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the forward position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrust(speed: number): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the left position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustLeft(speed: number): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the right position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustRight(speed: number): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the back position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustBack(speed: number): Phaser.GameObjects.GameObject; - - /** - * Sets new friction values for this Game Object's Matter Body. - * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. - * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. - * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. - */ - setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; - - /** - * Sets a new air resistance for this Game Object's Matter Body. - * A value of 0 means the Body will never slow as it moves through space. - * The higher the value, the faster a Body slows when moving through space. - * @param value The new air resistance for the Body. - */ - setFrictionAir(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets a new static friction for this Game Object's Matter Body. - * A value of 0 means the Body will never "stick" when it is nearly stationary. - * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. - * @param value The new static friction for the Body. - */ - setFrictionStatic(value: number): Phaser.GameObjects.GameObject; - - /** - * A togglable function for ignoring world gravity in real-time on the current body. - * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. - */ - setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Sets the mass of the Game Object's Matter Body. - * @param value The new mass of the body. - */ - setMass(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets density of the body. - * @param value The new density of the body. - */ - setDensity(value: number): Phaser.GameObjects.GameObject; - - /** - * The body's center of mass. - * - * Calling this creates a new `Vector2 each time to avoid mutation. - * - * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. - */ - readonly centerOfMass: Phaser.Math.Vector2; - - /** - * Set the body belonging to this Game Object to be a sensor. - * Sensors trigger collision events, but don't react with colliding body physically. - * @param value `true` to set the body as a sensor, or `false` to disable it. - */ - setSensor(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Is the body belonging to this Game Object a sensor or not? - */ - isSensor(): boolean; - - /** - * Set the body on a Game Object to a rectangle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param width Width of the rectangle. - * @param height Height of the rectangle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setRectangle(width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set the body on a Game Object to a circle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param radius The radius of the circle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setCircle(radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set the body on the Game Object to a polygon shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param sides The number of sides the polygon will have. - * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setPolygon(sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set the body on the Game Object to a trapezoid shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param width The width of the trapezoid Body. - * @param height The height of the trapezoid Body. - * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setTrapezoid(width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set this Game Object to use the given existing Matter Body. - * - * The body is first removed from the world before being added to this Game Object. - * @param body The Body this Game Object should use. - * @param addToWorld Should the body be immediately added to the World? Default true. - */ - setExistingBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.GameObjects.GameObject; - - /** - * Set this Game Object to create and use a new Body based on the configuration object given. - * - * Calling this method resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param config Either a string, such as `circle`, or a Matter Set Body Configuration object. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setBody(config: string | Phaser.Types.Physics.Matter.MatterSetBodyConfig, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Sets this Body to sleep. - */ - setToSleep(): this; - - /** - * Wakes this Body if asleep. - */ - setAwake(): this; - - /** - * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). - * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. - */ - setSleepThreshold(value?: number): this; - - /** - * Enable sleep and wake events for this body. - * - * By default when a body goes to sleep, or wakes up, it will not emit any events. - * - * The events are emitted by the Matter World instance and can be listened to via - * the `SLEEP_START` and `SLEEP_END` events. - * @param start `true` if you want the sleep start event to be emitted for this body. - * @param end `true` if you want the sleep end event to be emitted for this body. - */ - setSleepEvents(start: boolean, end: boolean): this; - - /** - * Enables or disables the Sleep Start event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepStartEvent(value: boolean): this; - - /** - * Enables or disables the Sleep End event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepEndEvent(value: boolean): this; - - /** - * Changes the physics body to be either static `true` or dynamic `false`. - * @param value `true` to set the body as being static, or `false` to make it dynamic. - */ - setStatic(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Returns `true` if the body is static, otherwise `false` for a dynamic body. - */ - isStatic(): boolean; - - /** - * Setting fixed rotation sets the Body inertia to Infinity, which stops it - * from being able to rotate when forces are applied to it. - */ - setFixedRotation(): this; - - /** - * Sets the angular velocity of the body instantly. - * Position, angle, force etc. are unchanged. - * @param value The angular velocity. - */ - setAngularVelocity(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): Phaser.GameObjects.GameObject; - - /** - * Sets vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): Phaser.GameObjects.GameObject; - - /** - * Sets both the horizontal and vertical velocity of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. Default x. - */ - setVelocity(x: number, y?: number): Phaser.GameObjects.GameObject; - - } - - /** - * 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 { - /** - * - * @param scene The Phaser Scene that owns this Matter Physics instance. - */ - constructor(scene: Phaser.Scene); - - /** - * The Phaser Scene that owns this Matter Physics instance - */ - scene: Phaser.Scene; - - /** - * A reference to the Scene Systems that belong to the Scene owning this Matter Physics instance. - */ - systems: Phaser.Scenes.Systems; - - /** - * The parsed Matter Configuration object. - */ - config: Phaser.Types.Physics.Matter.MatterWorldConfig; - - /** - * An instance of the Matter World class. This class is responsible for the updating of the - * Matter Physics world, as well as handling debug drawing functions. - */ - world: Phaser.Physics.Matter.World; - - /** - * An instance of the Matter Factory. This class provides lots of functions for creating a - * wide variety of physics objects and adds them automatically to the Matter World. - * - * You can use this class to cut-down on the amount of code required in your game, however, - * use of the Factory is entirely optional and should be seen as a development aid. It's - * perfectly possible to create and add components to the Matter world without using it. - */ - add: Phaser.Physics.Matter.Factory; - - /** - * An instance of the Body Bounds class. This class contains functions used for getting the - * world position from various points around the bounds of a physics body. - */ - bodyBounds: Phaser.Physics.Matter.BodyBounds; - - /** - * A reference to the `Matter.Body` module. - * - * 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 `Bodies` module. - */ - body: MatterJS.BodyFactory; - - /** - * A reference to the `Matter.Composite` module. - * - * 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`. - */ - composite: MatterJS.CompositeFactory; - - /** - * A reference to the `Matter.Detector` module. - * - * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. - */ - detector: MatterJS.DetectorFactory; - - /** - * A reference to the `Matter.Grid` module. - * - * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. - */ - grid: MatterJS.GridFactory; - - /** - * A reference to the `Matter.Pair` module. - * - * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. - */ - pair: MatterJS.PairFactory; - - /** - * A reference to the `Matter.Pairs` module. - * - * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. - */ - pairs: MatterJS.PairsFactory; - - /** - * A reference to the `Matter.Query` module. - * - * The `Matter.Query` module contains methods for performing collision queries. - */ - query: MatterJS.QueryFactory; - - /** - * A reference to the `Matter.Resolver` module. - * - * The `Matter.Resolver` module contains methods for resolving collision pairs. - */ - resolver: MatterJS.ResolverFactory; - - /** - * A reference to the `Matter.SAT` module. - * - * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. - */ - sat: MatterJS.SATFactory; - - /** - * A reference to the `Matter.Constraint` module. - * - * 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. - */ - constraint: MatterJS.ConstraintFactory; - - /** - * A reference to the `Matter.Bodies` module. - * - * The `Matter.Bodies` module contains factory methods for creating rigid bodies - * with commonly used body configurations (such as rectangles, circles and other polygons). - */ - bodies: MatterJS.BodiesFactory; - - /** - * A reference to the `Matter.Composites` module. - * - * The `Matter.Composites` module contains factory methods for creating composite bodies - * with commonly used configurations (such as stacks and chains). - */ - composites: MatterJS.CompositesFactory; - - /** - * A reference to the `Matter.Axes` module. - * - * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. - */ - axes: MatterJS.AxesFactory; - - /** - * A reference to the `Matter.Bounds` module. - * - * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). - */ - bounds: MatterJS.BoundsFactory; - - /** - * 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 - */ - svg: MatterJS.SvgFactory; - - /** - * A reference to the `Matter.Vector` module. - * - * 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 }`. - */ - vector: MatterJS.VectorFactory; - - /** - * A reference to the `Matter.Vertices` module. - * - * 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). - */ - vertices: MatterJS.VerticesFactory; - - /** - * A reference to the `Matter.Vertices` module. - * - * 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). - */ - verts: MatterJS.VerticesFactory; - - /** - * This internal method is called when this class starts and retrieves the final Matter World Config. - */ - getConfig(): Phaser.Types.Physics.Matter.MatterWorldConfig; - - /** - * Enables the Matter Attractors Plugin. - * - * The attractors plugin that makes it easy to apply continual forces on bodies. - * It's possible to simulate effects such as wind, gravity and magnetism. - * - * https://github.com/liabru/matter-attractors - * - * This method is called automatically if `plugins.attractors` is set in the Matter World Config. - * However, you can also call it directly from within your game. - */ - enableAttractorPlugin(): this; - - /** - * Enables the Matter Wrap Plugin. - * - * The coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay - * within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, - * while maintaining its velocity. - * - * https://github.com/liabru/matter-wrap - * - * This method is called automatically if `plugins.wrap` is set in the Matter World Config. - * However, you can also call it directly from within your game. - */ - enableWrapPlugin(): this; - - /** - * Enables the Matter Collision Events Plugin. - * - * Note that this plugin is enabled by default. So you should only ever need to call this - * method if you have specifically disabled the plugin in your Matter World Config. - * You can disable it by setting `plugins.collisionevents: false` in your Matter World Config. - * - * This plugin triggers three new events on Matter.Body: - * - * 1. `onCollide` - * 2. `onCollideEnd` - * 3. `onCollideActive` - * - * These events correspond to the Matter.js events `collisionStart`, `collisionActive` and `collisionEnd`, respectively. - * You can listen to these events via Matter.Events or they will also be emitted from the Matter World. - * - * This plugin also extends Matter.Body with three convenience functions: - * - * `Matter.Body.setOnCollide(callback)` - * `Matter.Body.setOnCollideEnd(callback)` - * `Matter.Body.setOnCollideActive(callback)` - * - * You can register event callbacks by providing a function of type (pair: Matter.Pair) => void - * - * https://github.com/dxu/matter-collision-events - */ - enableCollisionEventsPlugin(): this; - - /** - * Pauses the Matter World instance and sets `enabled` to `false`. - * - * A paused world will not run any simulations for the duration it is paused. - */ - pause(): Phaser.Physics.Matter.World; - - /** - * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. - */ - resume(): Phaser.Physics.Matter.World; - - /** - * Sets the Matter Engine to run at fixed timestep of 60Hz and enables `autoUpdate`. - * If you have set a custom `getDelta` function then this will override it. - */ - set60Hz(): this; - - /** - * Sets the Matter Engine to run at fixed timestep of 30Hz and enables `autoUpdate`. - * If you have set a custom `getDelta` function then this will override it. - */ - set30Hz(): this; - - /** - * Manually advances the physics simulation by one iteration. - * - * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. - * If undefined they use the Matter defaults of 60Hz and no correction. - * - * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. - * - * It also ignores any custom `getDelta` functions, as you should be passing the delta - * value in to this call. - * - * You can adjust the number of iterations that Engine.update performs internally. - * Use the Scene Matter Physics config object to set the following properties: - * - * positionIterations (defaults to 6) - * velocityIterations (defaults to 4) - * constraintIterations (defaults to 2) - * - * Adjusting these values can help performance in certain situations, depending on the physics requirements - * of your game. - * @param delta The delta value. Default 16.666. - * @param correction Optional delta correction value. Default 1. - */ - step(delta?: number, correction?: number): void; - - /** - * Checks if the vertices of the given body, or an array of bodies, contains the given point, or not. - * - * You can pass in either a single body, or an array of bodies to be checked. This method will - * return `true` if _any_ of the bodies in the array contain the point. See the `intersectPoint` method if you need - * to get a list of intersecting bodies. - * - * The point should be transformed into the Matter World coordinate system in advance. This happens by - * default with Input Pointers, but if you wish to use points from another system you may need to - * transform them before passing them. - * @param body The body, or an array of bodies, to check against the point. - * @param x The horizontal coordinate of the point. - * @param y The vertical coordinate of the point. - */ - containsPoint(body: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], x: number, y: number): boolean; - - /** - * Checks the given coordinates to see if any vertices of the given bodies contain it. - * - * If no bodies are provided it will search all bodies in the Matter World, including within Composites. - * - * The coordinates should be transformed into the Matter World coordinate system in advance. This happens by - * default with Input Pointers, but if you wish to use coordinates from another system you may need to - * transform them before passing them. - * @param x The horizontal coordinate of the point. - * @param y The vertical coordinate of the point. - * @param bodies An array of bodies to check. If not provided it will search all bodies in the world. - */ - intersectPoint(x: number, y: number, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; - - /** - * Checks the given rectangular area to see if any vertices of the given bodies intersect with it. - * Or, if the `outside` parameter is set to `true`, it checks to see which bodies do not - * intersect with it. - * - * If no bodies are provided it will search all bodies in the Matter World, including within Composites. - * @param x The horizontal coordinate of the top-left of the area. - * @param y The vertical coordinate of the top-left of the area. - * @param width The width of the area. - * @param height The height of the area. - * @param outside If `false` it checks for vertices inside the area, if `true` it checks for vertices outside the area. Default false. - * @param bodies An array of bodies to check. If not provided it will search all bodies in the world. - */ - intersectRect(x: number, y: number, width: number, height: number, outside?: boolean, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; - - /** - * Checks the given ray segment to see if any vertices of the given bodies intersect with it. - * - * If no bodies are provided it will search all bodies in the Matter World. - * - * The width of the ray can be specified via the `rayWidth` parameter. - * @param x1 The horizontal coordinate of the start of the ray segment. - * @param y1 The vertical coordinate of the start of the ray segment. - * @param x2 The horizontal coordinate of the end of the ray segment. - * @param y2 The vertical coordinate of the end of the ray segment. - * @param rayWidth The width of the ray segment. Default 1. - * @param bodies An array of bodies to check. If not provided it will search all bodies in the world. - */ - intersectRay(x1: number, y1: number, x2: number, y2: number, rayWidth?: number, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; - - /** - * Checks the given Matter Body to see if it intersects with any of the given bodies. - * - * If no bodies are provided it will check against all bodies in the Matter World. - * @param body The target body. - * @param bodies An array of bodies to check the target body against. If not provided it will search all bodies in the world. - */ - intersectBody(body: Phaser.Types.Physics.Matter.MatterBody, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; - - /** - * Checks to see if the target body, or an array of target bodies, intersects with any of the given bodies. - * - * If intersection occurs this method will return `true` and, if provided, invoke the callbacks. - * - * If no bodies are provided for the second parameter the target will check again all bodies in the Matter World. - * - * Note that bodies can only overlap if they are in non-colliding collision groups or categories. - * - * If you provide a `processCallback` then the two bodies that overlap are sent to it. This callback - * must return a boolean and is used to allow you to perform additional processing tests before a final - * outcome is decided. If it returns `true` then the bodies are finally passed to the `overlapCallback`, if set. - * - * If you provide an `overlapCallback` then the matching pairs of overlapping bodies will be sent to it. - * - * Both callbacks have the following signature: `function (bodyA, bodyB, collisionInfo)` where `bodyA` is always - * the target body. The `collisionInfo` object contains additional data, such as the angle and depth of penetration. - * @param target The target body, or array of target bodies, to check. - * @param bodies The second body, or array of bodies, to check. If falsey it will check against all bodies in the world. - * @param overlapCallback An optional callback function that is called if the bodies overlap. - * @param processCallback An optional callback function that lets you perform additional checks against the two bodies if they overlap. If this is set then `overlapCallback` will only be invoked if this callback returns `true`. - * @param callbackContext The context, or scope, in which to run the callbacks. - */ - overlap(target: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], bodies?: Phaser.Types.Physics.Matter.MatterBody[], overlapCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; - - /** - * Sets the collision filter category of all given Matter Bodies to the given value. - * - * This number must be a power of two between 2^0 (= 1) and 2^31. - * - * Bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * @param bodies An array of bodies to update. If falsey it will use all bodies in the world. - * @param value Unique category bitfield. - */ - setCollisionCategory(bodies: Phaser.Types.Physics.Matter.MatterBody[], value: number): this; - - /** - * Sets the collision filter group of all given Matter Bodies to the given value. - * - * If the group value is zero, or if two Matter Bodies have different group values, - * they will collide according to the usual collision filter rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * - * If two Matter Bodies have the same positive group value, they will always collide; - * if they have the same negative group value they will never collide. - * @param bodies An array of bodies to update. If falsey it will use all bodies in the world. - * @param value Unique group index. - */ - setCollisionGroup(bodies: Phaser.Types.Physics.Matter.MatterBody[], value: number): this; - - /** - * 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. - * @param bodies An array of bodies to update. If falsey it will use all bodies in the world. - * @param categories A unique category bitfield, or an array of them. - */ - setCollidesWith(bodies: Phaser.Types.Physics.Matter.MatterBody[], categories: number | number[]): this; - - /** - * Takes an array and returns a new array made from all of the Matter Bodies found in the original array. - * - * For example, passing in Matter Game Objects, such as a bunch of Matter Sprites, to this method, would - * return an array containing all of their native Matter Body objects. - * - * If the `bodies` argument is falsey, it will return all bodies in the world. - * @param bodies An array of objects to extract the bodies from. If falsey, it will return all bodies in the world. - */ - getMatterBodies(bodies?: any[]): MatterJS.BodyType[]; - - /** - * Sets both the horizontal and vertical linear velocity of the physics bodies. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param x The horizontal linear velocity value. - * @param y The vertical linear velocity value. - */ - setVelocity(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], x: number, y: number): this; - - /** - * Sets just the horizontal linear velocity of the physics bodies. - * The vertical velocity of the body is unchanged. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param x The horizontal linear velocity value. - */ - setVelocityX(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], x: number): this; - - /** - * Sets just the vertical linear velocity of the physics bodies. - * The horizontal velocity of the body is unchanged. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param y The vertical linear velocity value. - */ - setVelocityY(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], y: number): this; - - /** - * Sets the angular velocity of the bodies instantly. - * Position, angle, force etc. are unchanged. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param value The angular velocity. - */ - setAngularVelocity(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], value: number): this; - - /** - * Applies a force to a body, at the bodies current position, including resulting torque. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param force A Vector that specifies the force to apply. - */ - applyForce(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], force: Phaser.Types.Math.Vector2Like): this; - - /** - * Applies a force to a body, from the given world position, including resulting torque. - * 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. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param position A Vector that specifies the world-space position to apply the force at. - * @param speed A speed value to be applied to a directional force. - * @param angle The angle, in radians, to apply the force from. Leave undefined to use the current body angle. - */ - applyForceFromPosition(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], position: Phaser.Types.Math.Vector2Like, speed: number, angle?: number): this; - - /** - * 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. - * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. - * @param speed A speed value to be applied to a directional force. - * @param angle The angle, in radians, to apply the force from. Leave undefined to use the current body angle. - */ - applyForceFromAngle(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], speed: number, angle?: number): this; - - /** - * Returns the length of the given constraint, which is the distance between the two points. - * @param constraint The constraint to get the length from. - */ - getConstraintLength(constraint: MatterJS.ConstraintType): number; - - /** - * 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. - * @param body The Body to align. - * @param x The horizontal position to align the body to. - * @param y The vertical position to align the body to. - * @param align One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`. - */ - alignBody(body: Phaser.Types.Physics.Matter.MatterBody, x: number, y: number, align: integer): this; - - } - - /** - * A Matter Physics Sprite Game Object. - * - * A Sprite Game Object is used for the display of both static and animated images in your game. - * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled - * and animated. - * - * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. - * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation - * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. - */ - class Sprite extends Phaser.GameObjects.Sprite implements Phaser.Physics.Matter.Components.Bounce, Phaser.Physics.Matter.Components.Collision, Phaser.Physics.Matter.Components.Force, Phaser.Physics.Matter.Components.Friction, Phaser.Physics.Matter.Components.Gravity, Phaser.Physics.Matter.Components.Mass, Phaser.Physics.Matter.Components.Sensor, Phaser.Physics.Matter.Components.SetBody, Phaser.Physics.Matter.Components.Sleep, Phaser.Physics.Matter.Components.Static, Phaser.Physics.Matter.Components.Transform, Phaser.Physics.Matter.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param world A reference to the Matter.World instance that this body belongs to. - * @param x The horizontal position of this Game Object in the world. - * @param y The vertical position of this Game Object in the world. - * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. - * @param frame An optional frame from the Texture this Game Object is rendering with. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - constructor(world: Phaser.Physics.Matter.World, x: number, y: number, texture: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig); - - /** - * A reference to the Matter.World instance that this body belongs to. - */ - world: Phaser.Physics.Matter.World; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * The Mask this Game Object is using during render. - */ - mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; - - /** - * Sets the mask that this Game Object will use to render with. - * - * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. - * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. - * - * If a mask is already set on this Game Object it will be immediately replaced. - * - * Masks are positioned in global space and are not relative to the Game Object to which they - * are applied. The reason for this is that multiple Game Objects can all share the same mask. - * - * Masks have no impact on physics or input detection. They are purely a rendering component - * that allows you to limit what is visible during the render pass. - * @param mask The mask this Game Object will use when rendering. - */ - setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; - - /** - * Clears the mask that this Game Object was using. - * @param destroyMask Destroy the mask before clearing it? Default false. - */ - clearMask(destroyMask?: boolean): this; - - /** - * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a renderable Game Object. - * A renderable Game Object is one that uses a texture to render with, such as an - * Image, Sprite, Render Texture or BitmapText. - * - * If you do not provide a renderable object, and this Game Object has a texture, - * it will use itself as the object. This means you can call this method to create - * a Bitmap Mask from any renderable Game Object. - * @param renderable A renderable Game Object that uses a texture, such as a Sprite. - */ - createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; - - /** - * Creates and returns a Geometry Mask. This mask can be used by any Game Object, - * including this one. - * - * To create the mask you need to pass in a reference to a Graphics Game Object. - * - * If you do not provide a graphics object, and this Game Object is an instance - * of a Graphics object, then it will use itself to create the mask. - * - * This means you can call this method to create a Geometry Mask from any Graphics Game Object. - * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. - */ - createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the size of this Game Object to be that of the given Frame. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param frame The frame to base the size of this Game Object on. - */ - setSizeToFrame(frame: Phaser.Textures.Frame): this; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The Texture this Game Object is using to render with. - */ - texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; - - /** - * The Texture Frame this Game Object is using to render with. - */ - frame: Phaser.Textures.Frame; - - /** - * A boolean flag indicating if this Game Object is being cropped or not. - * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. - * Equally, calling `setCrop` with no arguments will reset the crop and disable it. - */ - isCropped: boolean; - - /** - * Applies a crop to a texture based Game Object, such as a Sprite or Image. - * - * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. - * - * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just - * changes what is shown when rendered. - * - * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. - * - * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left - * half of it, you could call `setCrop(0, 0, 400, 600)`. - * - * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop - * an area of 200x100 when applied to a Game Object that had a scale factor of 2. - * - * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. - * - * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. - * - * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow - * the renderer to skip several internal calculations. - * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. - * @param y The y coordinate to start the crop from. - * @param width The width of the crop rectangle in pixels. - * @param height The height of the crop rectangle in pixels. - */ - setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; - - /** - * Sets the texture and frame this Game Object will use to render with. - * - * Textures are referenced by their string-based keys, as stored in the Texture Manager. - * @param key The key of the texture to be used, as stored in the Texture Manager. - * @param frame The name or index of the frame within the Texture. - */ - setTexture(key: string, frame?: string | integer): this; - - /** - * Sets the frame this Game Object will use to render with. - * - * The Frame has to belong to the current Texture being used. - * - * It can be either a string or an index. - * - * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. - * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. - * @param frame The name or index of the frame within the Texture. - * @param updateSize Should this call adjust the size of the Game Object? Default true. - * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. - */ - setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; - - /** - * Fill or additive? - */ - tintFill: boolean; - - /** - * Clears all tint values associated with this Game Object. - * - * Immediately sets the color values back to 0xffffff and the tint type to 'additive', - * which results in no visible change to the texture. - */ - clearTint(): this; - - /** - * Sets an additive tint on this Game Object. - * - * The tint works by taking the pixel color values from the Game Objects texture, and then - * multiplying it by the color value of the tint. You can provide either one color value, - * in which case the whole Game Object will be tinted in that color. Or you can provide a color - * per corner. The colors are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. - * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * Sets a fill-based tint on this Game Object. - * - * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture - * with those in the tint. You can use this for effects such as making a player flash 'white' - * if hit by something. You can provide either one color value, in which case the whole - * Game Object will be rendered in that color. Or you can provide a color per corner. The colors - * are blended together across the extent of the Game Object. - * - * To modify the tint color once set, either call this method again with new values or use the - * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, - * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. - * - * To remove a tint call `clearTint`. - * - * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. - * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. - * @param topRight The tint being applied to the top-right of the Game Object. - * @param bottomLeft The tint being applied to the bottom-left of the Game Object. - * @param bottomRight The tint being applied to the bottom-right of the Game Object. - */ - setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; - - /** - * The tint value being applied to the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopLeft: integer; - - /** - * The tint value being applied to the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintTopRight: integer; - - /** - * The tint value being applied to the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomLeft: integer; - - /** - * The tint value being applied to the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - tintBottomRight: integer; - - /** - * The tint value being applied to the whole of the Game Object. - * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. - */ - tint: integer; - - /** - * Does this Game Object have a tint applied to it or not? - */ - readonly isTinted: boolean; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * Sets the restitution on the physics object. - * @param 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)` - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. - * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * @param value Unique category bitfield. - */ - setCollisionCategory(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, - * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, - * they will never collide. - * @param value Unique group index. - */ - setCollisionGroup(value: number): Phaser.GameObjects.GameObject; - - /** - * 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. - * @param categories A unique category bitfield, or an array of them. - */ - setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body starts colliding with another. - */ - setOnCollide(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body stops colliding with another. - */ - setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke for the duration of this body colliding with another. - */ - setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param body The body, or an array of bodies, to test for collisions with. - * @param callback The callback to invoke when this body collides with the given body or bodies. - */ - setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; - - /** - * Applies a force to a body. - * @param force A Vector that specifies the force to apply. - */ - applyForce(force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; - - /** - * Applies a force to a body from a given position. - * @param position The position in which the force comes from. - * @param force A Vector that specifies the force to apply. - */ - applyForceFrom(position: Phaser.Math.Vector2, force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the forward position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrust(speed: number): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the left position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustLeft(speed: number): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the right position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustRight(speed: number): Phaser.GameObjects.GameObject; - - /** - * Apply thrust to the back position of the body. - * - * Use very small values, such as 0.1, depending on the mass and required speed. - * @param speed A speed value to be applied to a directional force. - */ - thrustBack(speed: number): Phaser.GameObjects.GameObject; - - /** - * Sets new friction values for this Game Object's Matter Body. - * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. - * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. - * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. - */ - setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; - - /** - * Sets a new air resistance for this Game Object's Matter Body. - * A value of 0 means the Body will never slow as it moves through space. - * The higher the value, the faster a Body slows when moving through space. - * @param value The new air resistance for the Body. - */ - setFrictionAir(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets a new static friction for this Game Object's Matter Body. - * A value of 0 means the Body will never "stick" when it is nearly stationary. - * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. - * @param value The new static friction for the Body. - */ - setFrictionStatic(value: number): Phaser.GameObjects.GameObject; - - /** - * A togglable function for ignoring world gravity in real-time on the current body. - * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. - */ - setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Sets the mass of the Game Object's Matter Body. - * @param value The new mass of the body. - */ - setMass(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets density of the body. - * @param value The new density of the body. - */ - setDensity(value: number): Phaser.GameObjects.GameObject; - - /** - * The body's center of mass. - * - * Calling this creates a new `Vector2 each time to avoid mutation. - * - * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. - */ - readonly centerOfMass: Phaser.Math.Vector2; - - /** - * Set the body belonging to this Game Object to be a sensor. - * Sensors trigger collision events, but don't react with colliding body physically. - * @param value `true` to set the body as a sensor, or `false` to disable it. - */ - setSensor(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Is the body belonging to this Game Object a sensor or not? - */ - isSensor(): boolean; - - /** - * Set the body on a Game Object to a rectangle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param width Width of the rectangle. - * @param height Height of the rectangle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setRectangle(width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set the body on a Game Object to a circle. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param radius The radius of the circle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setCircle(radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set the body on the Game Object to a polygon shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param sides The number of sides the polygon will have. - * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setPolygon(sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set the body on the Game Object to a trapezoid shape. - * - * Calling this methods resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param width The width of the trapezoid Body. - * @param height The height of the trapezoid Body. - * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setTrapezoid(width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Set this Game Object to use the given existing Matter Body. - * - * The body is first removed from the world before being added to this Game Object. - * @param body The Body this Game Object should use. - * @param addToWorld Should the body be immediately added to the World? Default true. - */ - setExistingBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.GameObjects.GameObject; - - /** - * Set this Game Object to create and use a new Body based on the configuration object given. - * - * Calling this method resets previous properties you may have set on the body, including - * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. - * @param config Either a string, such as `circle`, or a Matter Set Body Configuration object. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - setBody(config: string | Phaser.Types.Physics.Matter.MatterSetBodyConfig, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; - - /** - * Sets this Body to sleep. - */ - setToSleep(): this; - - /** - * Wakes this Body if asleep. - */ - setAwake(): this; - - /** - * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). - * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. - */ - setSleepThreshold(value?: number): this; - - /** - * Enable sleep and wake events for this body. - * - * By default when a body goes to sleep, or wakes up, it will not emit any events. - * - * The events are emitted by the Matter World instance and can be listened to via - * the `SLEEP_START` and `SLEEP_END` events. - * @param start `true` if you want the sleep start event to be emitted for this body. - * @param end `true` if you want the sleep end event to be emitted for this body. - */ - setSleepEvents(start: boolean, end: boolean): this; - - /** - * Enables or disables the Sleep Start event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepStartEvent(value: boolean): this; - - /** - * Enables or disables the Sleep End event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepEndEvent(value: boolean): this; - - /** - * Changes the physics body to be either static `true` or dynamic `false`. - * @param value `true` to set the body as being static, or `false` to make it dynamic. - */ - setStatic(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Returns `true` if the body is static, otherwise `false` for a dynamic body. - */ - isStatic(): boolean; - - /** - * Setting fixed rotation sets the Body inertia to Infinity, which stops it - * from being able to rotate when forces are applied to it. - */ - setFixedRotation(): this; - - /** - * Sets the angular velocity of the body instantly. - * Position, angle, force etc. are unchanged. - * @param value The angular velocity. - */ - setAngularVelocity(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the horizontal velocity of the physics body. - * @param x The horizontal velocity value. - */ - setVelocityX(x: number): Phaser.GameObjects.GameObject; - - /** - * Sets vertical velocity of the physics body. - * @param y The vertical velocity value. - */ - setVelocityY(y: number): Phaser.GameObjects.GameObject; - - /** - * Sets both the horizontal and vertical velocity of the physics body. - * @param x The horizontal velocity value. - * @param y The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. Default x. - */ - setVelocity(x: number, y?: number): Phaser.GameObjects.GameObject; - - } - - /** - * A wrapper around a Tile that provides access to a corresponding Matter body. A tile can only - * have one Matter body associated with it. You can either pass in an existing Matter body for - * the tile or allow the constructor to create the corresponding body for you. If the Tile has a - * collision group (defined in Tiled), those shapes will be used to create the body. If not, the - * tile's rectangle bounding box will be used. - * - * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. - * - * Note: not all Tiled collision shapes are supported. See - * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. - */ - class TileBody implements Phaser.Physics.Matter.Components.Bounce, Phaser.Physics.Matter.Components.Collision, Phaser.Physics.Matter.Components.Friction, Phaser.Physics.Matter.Components.Gravity, Phaser.Physics.Matter.Components.Mass, Phaser.Physics.Matter.Components.Sensor, Phaser.Physics.Matter.Components.Sleep, Phaser.Physics.Matter.Components.Static { - /** - * - * @param world The Matter world instance this body belongs to. - * @param tile The target tile that should have a Matter body. - * @param options Options to be used when creating the Matter body. - */ - constructor(world: Phaser.Physics.Matter.World, tile: Phaser.Tilemaps.Tile, options?: Phaser.Types.Physics.Matter.MatterTileOptions); - - /** - * The tile object the body is associated with. - */ - tile: Phaser.Tilemaps.Tile; - - /** - * The Matter world the body exists within. - */ - world: Phaser.Physics.Matter.World; - - /** - * Sets the current body to a rectangle that matches the bounds of the tile. - * @param options Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. - */ - setFromTileRectangle(options?: Phaser.Types.Physics.Matter.MatterBodyTileOptions): Phaser.Physics.Matter.TileBody; - - /** - * Sets the current body from the collision group associated with the Tile. This is typically - * set up in Tiled's collision editor. - * - * Note: Matter doesn't support all shapes from Tiled. Rectangles and polygons are directly - * supported. Ellipses are converted into circle bodies. Polylines are treated as if they are - * closed polygons. If a tile has multiple shapes, a multi-part body will be created. Concave - * shapes are supported if poly-decomp library is included. Decomposition is not guaranteed to - * work for complex shapes (e.g. holes), so it's often best to manually decompose a concave - * polygon into multiple convex polygons yourself. - * @param options Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. - */ - setFromTileCollision(options?: Phaser.Types.Physics.Matter.MatterBodyTileOptions): Phaser.Physics.Matter.TileBody; - - /** - * Sets the current body to the given body. This will remove the previous body, if one already - * exists. - * @param body The new Matter body to use. - * @param addToWorld Whether or not to add the body to the Matter world. Default true. - */ - setBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.Physics.Matter.TileBody; - - /** - * Removes the current body from the TileBody and from the Matter world - */ - removeBody(): Phaser.Physics.Matter.TileBody; - - /** - * Removes the current body from the tile and the world. - */ - destroy(): Phaser.Physics.Matter.TileBody; - - /** - * Sets the restitution on the physics object. - * @param 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)` - */ - setBounce(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. - * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision - * categories are included in their collision masks (see {@link #setCollidesWith}). - * @param value Unique category bitfield. - */ - setCollisionCategory(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, - * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). - * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, - * they will never collide. - * @param value Unique group index. - */ - setCollisionGroup(value: number): Phaser.GameObjects.GameObject; - - /** - * 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. - * @param categories A unique category bitfield, or an array of them. - */ - setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body starts colliding with another. - */ - setOnCollide(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke when this body stops colliding with another. - */ - setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param callback The callback to invoke for the duration of this body colliding with another. - */ - setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; - - /** - * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. - * - * This does not change the bodies collision category, group or filter. Those must be set in addition - * to the callback. - * @param body The body, or an array of bodies, to test for collisions with. - * @param callback The callback to invoke when this body collides with the given body or bodies. - */ - setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; - - /** - * Sets new friction values for this Game Object's Matter Body. - * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. - * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. - * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. - */ - setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; - - /** - * Sets a new air resistance for this Game Object's Matter Body. - * A value of 0 means the Body will never slow as it moves through space. - * The higher the value, the faster a Body slows when moving through space. - * @param value The new air resistance for the Body. - */ - setFrictionAir(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets a new static friction for this Game Object's Matter Body. - * A value of 0 means the Body will never "stick" when it is nearly stationary. - * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. - * @param value The new static friction for the Body. - */ - setFrictionStatic(value: number): Phaser.GameObjects.GameObject; - - /** - * A togglable function for ignoring world gravity in real-time on the current body. - * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. - */ - setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Sets the mass of the Game Object's Matter Body. - * @param value The new mass of the body. - */ - setMass(value: number): Phaser.GameObjects.GameObject; - - /** - * Sets density of the body. - * @param value The new density of the body. - */ - setDensity(value: number): Phaser.GameObjects.GameObject; - - /** - * The body's center of mass. - * - * Calling this creates a new `Vector2 each time to avoid mutation. - * - * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. - */ - readonly centerOfMass: Phaser.Math.Vector2; - - /** - * Set the body belonging to this Game Object to be a sensor. - * Sensors trigger collision events, but don't react with colliding body physically. - * @param value `true` to set the body as a sensor, or `false` to disable it. - */ - setSensor(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Is the body belonging to this Game Object a sensor or not? - */ - isSensor(): boolean; - - /** - * Sets this Body to sleep. - */ - setToSleep(): this; - - /** - * Wakes this Body if asleep. - */ - setAwake(): this; - - /** - * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). - * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. - */ - setSleepThreshold(value?: number): this; - - /** - * Enable sleep and wake events for this body. - * - * By default when a body goes to sleep, or wakes up, it will not emit any events. - * - * The events are emitted by the Matter World instance and can be listened to via - * the `SLEEP_START` and `SLEEP_END` events. - * @param start `true` if you want the sleep start event to be emitted for this body. - * @param end `true` if you want the sleep end event to be emitted for this body. - */ - setSleepEvents(start: boolean, end: boolean): this; - - /** - * Enables or disables the Sleep Start event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepStartEvent(value: boolean): this; - - /** - * Enables or disables the Sleep End event for this body. - * @param value `true` to enable the sleep event, or `false` to disable it. - */ - setSleepEndEvent(value: boolean): this; - - /** - * Changes the physics body to be either static `true` or dynamic `false`. - * @param value `true` to set the body as being static, or `false` to make it dynamic. - */ - setStatic(value: boolean): Phaser.GameObjects.GameObject; - - /** - * Returns `true` if the body is static, otherwise `false` for a dynamic body. - */ - isStatic(): boolean; - - } - - /** - * Use PhysicsEditorParser.parseBody() to build a Matter body object, based on a physics data file - * created and exported with PhysicsEditor (https://www.codeandweb.com/physicseditor). - */ - namespace PhysicsEditorParser { - /** - * Parses a body element exported by PhysicsEditor. - * @param x The horizontal world location of the body. - * @param y The vertical world location of the body. - * @param config The body configuration and fixture (child body) definitions, as exported by PhysicsEditor. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - function parseBody(x: number, y: number, config: object, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; - - /** - * Parses an element of the "fixtures" list exported by PhysicsEditor - * @param fixtureConfig The fixture object to parse. - */ - function parseFixture(fixtureConfig: object): MatterJS.BodyType[]; - - /** - * Parses the "vertices" lists exported by PhysicsEditor. - * @param vertexSets The vertex lists to parse. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - function parseVertices(vertexSets: any[], options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType[]; - - } - - /** - * Creates a body using the supplied physics data, as provided by a JSON file. - * - * The data file should be loaded as JSON: - * - * ```javascript - * preload () - * { - * this.load.json('ninjas', 'assets/ninjas.json); - * } - * - * create () - * { - * const ninjaShapes = this.cache.json.get('ninjas'); - * - * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); - * } - * ``` - * - * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. - * - * If you pas in an `options` object, any settings in there will override those in the config object. - * - * The structure of the JSON file is as follows: - * - * ```text - * { - * 'generator_info': // The name of the application that created the JSON data - * 'shapeName': { - * 'type': // The type of body - * 'label': // Optional body label - * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs - * } - * } - * ``` - * - * At the time of writing, only the Phaser Physics Tracer App exports in this format. - */ - namespace PhysicsJSONParser { - /** - * Parses a body element from the given JSON data. - * @param x The horizontal world location of the body. - * @param y The vertical world location of the body. - * @param config The body configuration data. - * @param options An optional Body configuration object that is used to set initial Body properties on creation. - */ - function parseBody(x: number, y: number, config: object, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; - - } - - /** - * A Pointer Constraint is a special type of constraint that allows you to click - * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, - * and when one is pressed down it checks to see if that hit any part of any active - * body in the world. If it did, and the body has input enabled, it will begin to - * drag it until either released, or you stop it via the `stopDrag` method. - * - * You can adjust the stiffness, length and other properties of the constraint via - * the `options` object on creation. - */ - class PointerConstraint { - /** - * - * @param scene A reference to the Scene to which this Pointer Constraint belongs. - * @param world A reference to the Matter World instance to which this Constraint belongs. - * @param options A Constraint configuration object. - */ - constructor(scene: Phaser.Scene, world: Phaser.Physics.Matter.World, options?: object); - - /** - * A reference to the Scene to which this Pointer Constraint belongs. - * This is the same Scene as the Matter World instance. - */ - scene: Phaser.Scene; - - /** - * A reference to the Matter World instance to which this Constraint belongs. - */ - world: Phaser.Physics.Matter.World; - - /** - * The Camera the Pointer was interacting with when the input - * down event was processed. - */ - camera: Phaser.Cameras.Scene2D.Camera; - - /** - * A reference to the Input Pointer that activated this Constraint. - * This is set in the `onDown` handler. - */ - pointer: Phaser.Input.Pointer; - - /** - * Is this Constraint active or not? - * - * An active constraint will be processed each update. An inactive one will be skipped. - * Use this to toggle a Pointer Constraint on and off. - */ - active: boolean; - - /** - * The internal transformed position. - */ - position: Phaser.Math.Vector2; - - /** - * The body that is currently being dragged, if any. - */ - body: MatterJS.BodyType; - - /** - * The part of the body that was clicked on to start the drag. - */ - part: MatterJS.BodyType; - - /** - * The native Matter Constraint that is used to attach to bodies. - */ - constraint: MatterJS.ConstraintType; - - /** - * A Pointer has been pressed down onto the Scene. - * - * If this Constraint doesn't have an active Pointer then a hit test is set to - * run against all active bodies in the world during the _next_ call to `update`. - * If a body is found, it is bound to this constraint and the drag begins. - * @param pointer A reference to the Pointer that was pressed. - */ - onDown(pointer: Phaser.Input.Pointer): void; - - /** - * A Pointer has been released from the Scene. If it was the one this constraint was using, it's cleared. - * @param pointer A reference to the Pointer that was pressed. - */ - onUp(pointer: Phaser.Input.Pointer): void; - - /** - * Scans all active bodies in the current Matter World to see if any of them - * are hit by the Pointer. The _first one_ found to hit is set as the active contraint - * body. - */ - getBody(): boolean; - - /** - * Scans the current body to determine if a part of it was clicked on. - * If a part is found the body is set as the `constraint.bodyB` property, - * as well as the `body` property of this class. The part is also set. - * @param body The Matter Body to check. - * @param position A translated hit test position. - */ - hitTestBody(body: MatterJS.BodyType, position: Phaser.Math.Vector2): boolean; - - /** - * Internal update handler. Called in the Matter BEFORE_UPDATE step. - */ - update(): void; - - /** - * Stops the Pointer Constraint from dragging the body any further. - * - * This is called automatically if the Pointer is released while actively - * dragging a body. Or, you can call it manually to release a body from a - * constraint without having to first release the pointer. - */ - stopDrag(): void; - - /** - * Destroys this Pointer Constraint instance and all of its references. - */ - destroy(): void; - - } - - /** - * The Matter World class is responsible for managing one single instance of a Matter Physics World for Phaser. - * - * Access this via `this.matter.world` from within a Scene. - * - * This class creates a Matter JS World Composite along with the Matter JS Engine during instantiation. It also - * handles delta timing, bounds, body and constraint creation and debug drawing. - * - * If you wish to access the Matter JS World object directly, see the `localWorld` property. - * If you wish to access the Matter Engine directly, see the `engine` property. - * - * This class is an Event Emitter and will proxy _all_ Matter JS events, as they are received. - */ - class World extends Phaser.Events.EventEmitter { - /** - * - * @param scene The Scene to which this Matter World instance belongs. - * @param config The Matter World configuration object. - */ - constructor(scene: Phaser.Scene, config: Phaser.Types.Physics.Matter.MatterWorldConfig); - - /** - * The Scene to which this Matter World instance belongs. - */ - scene: Phaser.Scene; - - /** - * An instance of the MatterJS Engine. - */ - engine: MatterJS.Engine; - - /** - * A `World` composite object that will contain all simulated bodies and constraints. - */ - localWorld: MatterJS.World; - - /** - * An object containing the 4 wall bodies that bound the physics world. - */ - walls: object; - - /** - * A flag that toggles if the world is enabled or not. - */ - enabled: boolean; - - /** - * The correction argument is 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. - */ - correction: number; - - /** - * This function is called every time the core game loop steps, which is bound to the - * Request Animation Frame frequency unless otherwise modified. - * - * The function is passed two values: `time` and `delta`, both of which come from the game step values. - * - * It must return a number. This number is used as the delta value passed to Matter.Engine.update. - * - * You can override this function with your own to define your own timestep. - * - * If you need to update the Engine multiple times in a single game step then call - * `World.update` as many times as required. Each call will trigger the `getDelta` function. - * If you wish to have full control over when the Engine updates then see the property `autoUpdate`. - * - * You can also adjust the number of iterations that Engine.update performs. - * Use the Scene Matter Physics config object to set the following properties: - * - * positionIterations (defaults to 6) - * velocityIterations (defaults to 4) - * constraintIterations (defaults to 2) - * - * Adjusting these values can help performance in certain situations, depending on the physics requirements - * of your game. - */ - getDelta: Function; - - /** - * The Matter JS Runner Configuration object. - * - * This object is populated via the Matter Configuration object's `runner` property and is - * updated constantly during the game step. - */ - runner: Phaser.Types.Physics.Matter.MatterRunnerConfig; - - /** - * Automatically call Engine.update every time the game steps. - * If you disable this then you are responsible for calling `World.step` directly from your game. - * If you call `set60Hz` or `set30Hz` then `autoUpdate` is reset to `true`. - */ - autoUpdate: boolean; - - /** - * A flag that controls if the debug graphics will be drawn to or not. - */ - drawDebug: boolean; - - /** - * An instance of the Graphics object the debug bodies are drawn to, if enabled. - */ - debugGraphic: Phaser.GameObjects.Graphics; - - /** - * The debug configuration object. - * - * The values stored in this object are read from the Matter World Config `debug` property. - * - * When a new Body or Constraint is _added to the World_, they are given the values stored in this object, - * unless they have their own `render` object set that will override them. - * - * Note that while you can modify the values of properties in this object at run-time, it will not change - * any of the Matter objects _already added_. It will only impact objects newly added to the world, or one - * that is removed and then re-added at a later time. - */ - debugConfig: Phaser.Types.Physics.Matter.MatterDebugConfig; - - /** - * Sets the debug render style for the children of the given Matter Composite. - * - * Composites themselves do not render, but they can contain bodies, constraints and other composites that may do. - * So the children of this composite are passed to the `setBodyRenderStyle`, `setCompositeRenderStyle` and - * `setConstraintRenderStyle` methods accordingly. - * @param composite The Matter Composite to set the render style on. - */ - setCompositeRenderStyle(composite: MatterJS.CompositeType): this; - - /** - * Sets the debug render style for the given Matter Body. - * - * If you are using this on a Phaser Game Object, such as a Matter Sprite, then pass in the body property - * to this method, not the Game Object itself. - * - * If you wish to skip a parameter, so it retains its current value, pass `false` for it. - * - * If you wish to reset the Body render colors to the defaults found in the World Debug Config, then call - * this method with just the `body` parameter provided and no others. - * @param body The Matter Body to set the render style on. - * @param lineColor The line color. If `null` it will use the World Debug Config value. - * @param lineOpacity The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. - * @param lineThickness The line thickness. If `null` it will use the World Debug Config value. - * @param fillColor The fill color. If `null` it will use the World Debug Config value. - * @param fillOpacity The fill opacity, between 0 and 1. If `null` it will use the World Debug Config value. - */ - setBodyRenderStyle(body: MatterJS.BodyType, lineColor?: number, lineOpacity?: number, lineThickness?: number, fillColor?: number, fillOpacity?: number): this; - - /** - * Sets the debug render style for the given Matter Constraint. - * - * If you are using this on a Phaser Game Object, then pass in the body property - * to this method, not the Game Object itself. - * - * If you wish to skip a parameter, so it retains its current value, pass `false` for it. - * - * If you wish to reset the Constraint render colors to the defaults found in the World Debug Config, then call - * this method with just the `constraint` parameter provided and no others. - * @param constraint The Matter Constraint to set the render style on. - * @param lineColor The line color. If `null` it will use the World Debug Config value. - * @param lineOpacity The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. - * @param lineThickness The line thickness. If `null` it will use the World Debug Config value. - * @param pinSize If this constraint is a pin, this sets the size of the pin circle. If `null` it will use the World Debug Config value. - * @param anchorColor The color used when rendering this constraints anchors. If `null` it will use the World Debug Config value. - * @param anchorSize The size of the anchor circle, if this constraint has anchors. If `null` it will use the World Debug Config value. - */ - setConstraintRenderStyle(constraint: MatterJS.ConstraintType, lineColor?: number, lineOpacity?: number, lineThickness?: number, pinSize?: number, anchorColor?: number, anchorSize?: number): this; - - /** - * This internal method acts as a proxy between all of the Matter JS events and then re-emits them - * via this class. - */ - setEventsProxy(): void; - - /** - * Sets the bounds of the Physics world to match the given world pixel dimensions. - * You can optionally set which 'walls' to create: left, right, top or bottom. - * If none of the walls are given it will default to use the walls settings it had previously. - * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size - * the newly created bounds will also not have the left and right walls. - * Explicitly state them in the parameters to override this. - * @param x The x coordinate of the top-left corner of the bounds. Default 0. - * @param y The y coordinate of the top-left corner of the bounds. Default 0. - * @param width The width of the bounds. - * @param height The height of the bounds. - * @param thickness The thickness of each wall, in pixels. Default 64. - * @param left If true will create the left bounds wall. Default true. - * @param right If true will create the right bounds wall. Default true. - * @param top If true will create the top bounds wall. Default true. - * @param bottom If true will create the bottom bounds wall. Default true. - */ - setBounds(x?: number, y?: number, width?: number, height?: number, thickness?: number, left?: boolean, right?: boolean, top?: boolean, bottom?: boolean): Phaser.Physics.Matter.World; - - /** - * Updates the 4 rectangle bodies that were created, if `setBounds` was set in the Matter config, to use - * the new positions and sizes. This method is usually only called internally via the `setBounds` method. - * @param add `true` if the walls are being added or updated, `false` to remove them from the world. - * @param position Either `left`, `right`, `top` or `bottom`. Only optional if `add` is `false`. - * @param x The horizontal position to place the walls at. Only optional if `add` is `false`. - * @param y The vertical position to place the walls at. Only optional if `add` is `false`. - * @param width The width of the walls, in pixels. Only optional if `add` is `false`. - * @param height The height of the walls, in pixels. Only optional if `add` is `false`. - */ - updateWall(add: boolean, position?: string, x?: number, y?: number, width?: number, height?: number): void; - - /** - * Creates a Phaser.GameObjects.Graphics object that is used to render all of the debug bodies and joints to. - * - * This method is called automatically by the constructor, if debugging has been enabled. - * - * The created Graphics object is automatically added to the Scene at 0x0 and given a depth of `Number.MAX_VALUE`, - * so it renders above all else in the Scene. - * - * The Graphics object is assigned to the `debugGraphic` property of this class and `drawDebug` is enabled. - */ - createDebugGraphic(): Phaser.GameObjects.Graphics; - - /** - * Sets the world gravity and gravity scale to 0. - */ - disableGravity(): this; - - /** - * Sets the worlds gravity to the values given. - * - * Gravity effects all bodies in the world, unless they have the `ignoreGravity` flag set. - * @param x The world gravity x component. Default 0. - * @param y The world gravity y component. Default 1. - * @param scale The gravity scale factor. Default 0.001. - */ - setGravity(x?: number, y?: number, scale?: number): this; - - /** - * Creates a rectangle Matter body and adds it to the world. - * @param x The horizontal position of the body in the world. - * @param y The vertical position of the body in the world. - * @param width The width of the body. - * @param height The height of the body. - * @param options Optional Matter configuration object. - */ - create(x: number, y: number, width: number, height: number, options: object): MatterJS.BodyType; - - /** - * Adds a Matter JS object, or array of objects, to the world. - * - * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. - * - * Triggers `beforeAdd` and `afterAdd` events. - * @param object Can be single object, or an array, and can be a body, composite or constraint. - */ - add(object: object | object[]): this; - - /** - * Removes a Matter JS object, or array of objects, from the world. - * - * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. - * - * Triggers `beforeRemove` and `afterRemove` events. - * @param object Can be single object, or an array, and can be a body, composite or constraint. - * @param deep Optionally search the objects children and recursively remove those as well. Default false. - */ - remove(object: object | object[], deep?: boolean): this; - - /** - * Removes a Matter JS constraint, or array of constraints, from the world. - * - * Triggers `beforeRemove` and `afterRemove` events. - * @param constraint A Matter JS Constraint, or an array of constraints, to be removed. - * @param deep Optionally search the objects children and recursively remove those as well. Default false. - */ - removeConstraint(constraint: MatterJS.ConstraintType | MatterJS.ConstraintType[], deep?: boolean): this; - - /** - * Adds `MatterTileBody` instances for all the colliding tiles within the given tilemap layer. - * - * Set the appropriate tiles in your layer to collide before calling this method! - * @param tilemapLayer An array of tiles. - * @param options Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} - */ - convertTilemapLayer(tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, options?: object): this; - - /** - * Adds `MatterTileBody` instances for the given tiles. This adds bodies regardless of whether the - * tiles are set to collide or not. - * @param tiles An array of tiles. - * @param options Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} - */ - convertTiles(tiles: Phaser.Tilemaps.Tile[], options?: object): this; - - /** - * Returns the next unique group index for which bodies will collide. - * If `isNonColliding` is `true`, returns the next unique group index for which bodies will not collide. - * @param isNonColliding If `true`, returns the next unique group index for which bodies will _not_ collide. Default false. - */ - nextGroup(isNonColliding?: boolean): number; - - /** - * Returns the next unique category bitfield (starting after the initial default category 0x0001). - * There are 32 available. - */ - nextCategory(): number; - - /** - * Pauses this Matter World instance and sets `enabled` to `false`. - * - * A paused world will not run any simulations for the duration it is paused. - */ - pause(): this; - - /** - * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. - */ - resume(): this; - - /** - * 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. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(time: number, delta: number): void; - - /** - * Manually advances the physics simulation by one iteration. - * - * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. - * If undefined they use the Matter defaults of 60Hz and no correction. - * - * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. - * - * It also ignores any custom `getDelta` functions, as you should be passing the delta - * value in to this call. - * - * You can adjust the number of iterations that Engine.update performs internally. - * Use the Scene Matter Physics config object to set the following properties: - * - * positionIterations (defaults to 6) - * velocityIterations (defaults to 4) - * constraintIterations (defaults to 2) - * - * Adjusting these values can help performance in certain situations, depending on the physics requirements - * of your game. - * @param delta The delta value. Default 16.666. - * @param correction Optional delta correction value. Default 1. - */ - step(delta?: number, correction?: number): void; - - /** - * Runs the Matter Engine.update at a fixed timestep of 60Hz. - */ - update60Hz(): number; - - /** - * Runs the Matter Engine.update at a fixed timestep of 30Hz. - */ - update30Hz(): number; - - /** - * Returns `true` if the given body can be found within the World. - * @param body The Matter Body, or Game Object, to search for within the world. - */ - has(body: MatterJS.Body | Phaser.GameObjects.GameObject): MatterJS.BodyType[]; - - /** - * Returns all the bodies in the Matter World, including all bodies in children, recursively. - */ - getAllBodies(): MatterJS.BodyType[]; - - /** - * Returns all the constraints in the Matter World, including all constraints in children, recursively. - */ - getAllConstraints(): MatterJS.ConstraintType[]; - - /** - * Returns all the composites in the Matter World, including all composites in children, recursively. - */ - getAllComposites(): MatterJS.CompositeType[]; - - /** - * Renders the Engine Broadphase Controller Grid to the given Graphics instance. - * - * The debug renderer calls this method if the `showBroadphase` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render the Grid to your own Graphics instance. - * @param grid The Matter Grid to be rendered. - * @param graphics The Graphics object to render to. - * @param lineColor The line color. - * @param lineOpacity The line opacity, between 0 and 1. - */ - renderGrid(grid: MatterJS.Grid, graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number): this; - - /** - * Renders the list of Pair separations to the given Graphics instance. - * - * The debug renderer calls this method if the `showSeparations` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render the Grid to your own Graphics instance. - * @param pairs An array of Matter Pairs to be rendered. - * @param graphics The Graphics object to render to. - * @param lineColor The line color. - */ - renderSeparations(pairs: MatterJS.Pair[], graphics: Phaser.GameObjects.Graphics, lineColor: number): this; - - /** - * Renders the list of collision points and normals to the given Graphics instance. - * - * The debug renderer calls this method if the `showCollisions` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render the Grid to your own Graphics instance. - * @param pairs An array of Matter Pairs to be rendered. - * @param graphics The Graphics object to render to. - * @param lineColor The line color. - */ - renderCollisions(pairs: MatterJS.Pair[], graphics: Phaser.GameObjects.Graphics, lineColor: number): this; - - /** - * Renders the bounds of an array of Bodies to the given Graphics instance. - * - * If the body is a compound body, it will render the bounds for the parent compound. - * - * The debug renderer calls this method if the `showBounds` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render bounds to your own Graphics instance. - * @param bodies An array of bodies from the localWorld. - * @param graphics The Graphics object to render to. - * @param lineColor The line color. - * @param lineOpacity The line opacity, between 0 and 1. - */ - renderBodyBounds(bodies: any[], graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number): void; - - /** - * Renders either all axes, or a single axis indicator, for an array of Bodies, to the given Graphics instance. - * - * The debug renderer calls this method if the `showAxes` or `showAngleIndicator` config values are set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render bounds to your own Graphics instance. - * @param bodies An array of bodies from the localWorld. - * @param graphics The Graphics object to render to. - * @param showAxes If `true` it will render all body axes. If `false` it will render a single axis indicator. - * @param lineColor The line color. - * @param lineOpacity The line opacity, between 0 and 1. - */ - renderBodyAxes(bodies: any[], graphics: Phaser.GameObjects.Graphics, showAxes: boolean, lineColor: number, lineOpacity: number): void; - - /** - * Renders a velocity indicator for an array of Bodies, to the given Graphics instance. - * - * The debug renderer calls this method if the `showVelocity` config value is set. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render bounds to your own Graphics instance. - * @param bodies An array of bodies from the localWorld. - * @param graphics The Graphics object to render to. - * @param lineColor The line color. - * @param lineOpacity The line opacity, between 0 and 1. - * @param lineThickness The line thickness. - */ - renderBodyVelocity(bodies: any[], graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number, lineThickness: number): void; - - /** - * Renders a single Matter Body to the given Phaser Graphics Game Object. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render a Body to your own Graphics instance. - * - * If you don't wish to render a line around the body, set the `lineColor` parameter to `null`. - * Equally, if you don't wish to render a fill, set the `fillColor` parameter to `null`. - * @param body The Matter Body to be rendered. - * @param graphics The Graphics object to render to. - * @param showInternalEdges Render internal edges of the polygon? - * @param lineColor The line color. - * @param lineOpacity The line opacity, between 0 and 1. - * @param lineThickness The line thickness. Default 1. - * @param fillColor The fill color. - * @param fillOpacity The fill opacity, between 0 and 1. - */ - renderBody(body: MatterJS.BodyType, graphics: Phaser.GameObjects.Graphics, showInternalEdges: boolean, lineColor?: number, lineOpacity?: number, lineThickness?: number, fillColor?: number, fillOpacity?: number): this; - - /** - * Renders the Convex Hull for a single Matter Body to the given Phaser Graphics Game Object. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render a Body hull to your own Graphics instance. - * @param body The Matter Body to be rendered. - * @param graphics The Graphics object to render to. - * @param hullColor The color used to render the hull. - * @param lineThickness The hull line thickness. Default 1. - */ - renderConvexHull(body: MatterJS.BodyType, graphics: Phaser.GameObjects.Graphics, hullColor: number, lineThickness?: number): this; - - /** - * Renders a single Matter Constraint, such as a Pin or a Spring, to the given Phaser Graphics Game Object. - * - * This method is used internally by the Matter Debug Renderer, but is also exposed publically should - * you wish to render a Constraint to your own Graphics instance. - * @param constraint The Matter Constraint to render. - * @param graphics The Graphics object to render to. - * @param lineColor The line color. - * @param lineOpacity The line opacity, between 0 and 1. - * @param lineThickness The line thickness. - * @param pinSize If this constraint is a pin, this sets the size of the pin circle. - * @param anchorColor The color used when rendering this constraints anchors. Set to `null` to not render anchors. - * @param anchorSize The size of the anchor circle, if this constraint has anchors and is rendering them. - */ - renderConstraint(constraint: MatterJS.ConstraintType, graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number, lineThickness: number, pinSize: number, anchorColor: number, anchorSize: number): this; - - /** - * Resets the internal collision IDs that Matter.JS uses for Body collision groups. - * - * You should call this before destroying your game if you need to restart the game - * again on the same page, without first reloading the page. Or, if you wish to - * consistently destroy a Scene that contains Matter.js and then run it again - * later in the same game. - */ - resetCollisionIDs(): void; - - /** - * Will remove all Matter physics event listeners and clear the matter physics world, - * engine and any debug graphics, if any. - */ - shutdown(): void; - - /** - * Will remove all Matter physics event listeners and clear the matter physics world, - * engine and any debug graphics, if any. - * - * After destroying the world it cannot be re-used again. - */ - destroy(): void; - - } - - } - - } - - namespace Plugins { - /** - * A Global Plugin is installed just once into the Game owned Plugin Manager. - * It can listen for Game events and respond to them. - */ - class BasePlugin { - /** - * - * @param pluginManager A reference to the Plugin Manager. - */ - constructor(pluginManager: Phaser.Plugins.PluginManager); - - /** - * A handy reference to the Plugin Manager that is responsible for this plugin. - * Can be used as a route to gain access to game systems and events. - */ - protected pluginManager: Phaser.Plugins.PluginManager; - - /** - * A reference to the Game instance this plugin is running under. - */ - protected game: Phaser.Game; - - /** - * The PluginManager calls this method on a Global Plugin when the plugin is first instantiated. - * It will never be called again on this instance. - * In here you can set-up whatever you need for this plugin to run. - * If a plugin is set to automatically start then `BasePlugin.start` will be called immediately after this. - * On a Scene Plugin, this method is never called. Use {@link Phaser.Plugins.ScenePlugin#boot} instead. - * @param data A value specified by the user, if any, from the `data` property of the plugin's configuration object (if started at game boot) or passed in the PluginManager's `install` method (if started manually). - */ - init(data?: any): void; - - /** - * The PluginManager calls this method on a Global Plugin when the plugin is started. - * If a plugin is stopped, and then started again, this will get called again. - * Typically called immediately after `BasePlugin.init`. - * On a Scene Plugin, this method is never called. - */ - start(): void; - - /** - * The PluginManager calls this method on a Global Plugin when the plugin is stopped. - * The game code has requested that your plugin stop doing whatever it does. - * It is now considered as 'inactive' by the PluginManager. - * Handle that process here (i.e. stop listening for events, etc) - * If the plugin is started again then `BasePlugin.start` will be called again. - * On a Scene Plugin, this method is never called. - */ - stop(): void; - - /** - * Game instance has been destroyed. - * You must release everything in here, all references, all objects, free it all up. - */ - destroy(): void; - - } - - type DefaultPlugins = { - /** - * These are the Global Managers that are created by the Phaser.Game instance. - */ - Global: any[]; - /** - * These are the core plugins that are installed into every Scene.Systems instance, no matter what. - */ - CoreScene: any[]; - /** - * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. - */ - DefaultScene: any[]; - }; - - /** - * These are the Global Managers that are created by the Phaser.Game instance. - * They are referenced from Scene.Systems so that plugins can use them. - */ - var Global: any[]; - - /** - * These are the core plugins that are installed into every Scene.Systems instance, no matter what. - * They are optionally exposed in the Scene as well (see the InjectionMap for details) - * - * They are created in the order in which they appear in this array and EventEmitter is always first. - */ - var CoreScene: any[]; - - /** - * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. - * - * You can elect not to have these plugins by either creating a DefaultPlugins object as part - * of the Game Config, by creating a Plugins object as part of a Scene Config, or by modifying this array - * and building your own bundle. - * - * They are optionally exposed in the Scene as well (see the InjectionMap for details) - * - * They are always created in the order in which they appear in the array. - */ - var DefaultScene: any[]; - - namespace PluginCache { - /** - * Static method called directly by the Core internal Plugins. - * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) - * Plugin is the object to instantiate to create the plugin - * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) - * @param key A reference used to get this plugin from the plugin cache. - * @param plugin The plugin to be stored. Should be the core object, not instantiated. - * @param mapping If this plugin is to be injected into the Scene Systems, this is the property key map used. - * @param custom Core Scene plugin or a Custom Scene plugin? Default false. - */ - function register(key: string, plugin: Function, mapping: string, custom?: boolean): void; - - /** - * Stores a custom plugin in the global plugin cache. - * The key must be unique, within the scope of the cache. - * @param key A reference used to get this plugin from the plugin cache. - * @param plugin The plugin to be stored. Should be the core object, not instantiated. - * @param mapping If this plugin is to be injected into the Scene Systems, this is the property key map used. - * @param data A value to be passed to the plugin's `init` method. - */ - function registerCustom(key: string, plugin: Function, mapping: string, data: any): void; - - /** - * Checks if the given key is already being used in the core plugin cache. - * @param key The key to check for. - */ - function hasCore(key: string): boolean; - - /** - * Checks if the given key is already being used in the custom plugin cache. - * @param key The key to check for. - */ - function hasCustom(key: string): boolean; - - /** - * Returns the core plugin object from the cache based on the given key. - * @param key The key of the core plugin to get. - */ - function getCore(key: string): Phaser.Types.Plugins.CorePluginContainer; - - /** - * Returns the custom plugin object from the cache based on the given key. - * @param key The key of the custom plugin to get. - */ - function getCustom(key: string): Phaser.Types.Plugins.CustomPluginContainer; - - /** - * Returns an object from the custom cache based on the given key that can be instantiated. - * @param key The key of the custom plugin to get. - */ - function getCustomClass(key: string): Function; - - /** - * Removes a core plugin based on the given key. - * @param key The key of the core plugin to remove. - */ - function remove(key: string): void; - - /** - * Removes a custom plugin based on the given key. - * @param key The key of the custom plugin to remove. - */ - function removeCustom(key: string): void; - - /** - * Removes all Core Plugins. - * - * This includes all of the internal system plugins that Phaser needs, like the Input Plugin and Loader Plugin. - * So be sure you only call this if you do not wish to run Phaser again. - */ - function destroyCorePlugins(): void; - - /** - * Removes all Custom Plugins. - */ - function destroyCustomPlugins(): void; - - } - - /** - * The PluginManager is responsible for installing and adding plugins to Phaser. - * - * It is a global system and therefore belongs to the Game instance, not a specific Scene. - * - * It works in conjunction with the PluginCache. Core internal plugins automatically register themselves - * with the Cache, but it's the Plugin Manager that is responsible for injecting them into the Scenes. - * - * There are two types of plugin: - * - * 1. A Global Plugin - * 2. A Scene Plugin - * - * A Global Plugin is a plugin that lives within the Plugin Manager rather than a Scene. You can get - * access to it by calling `PluginManager.get` and providing a key. Any Scene that requests a plugin in - * this way will all get access to the same plugin instance, allowing you to use a single plugin across - * multiple Scenes. - * - * A Scene Plugin is a plugin dedicated to running within a Scene. These are different to Global Plugins - * in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. - * And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene - * Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. - * - * You can add a plugin to Phaser in three different ways: - * - * 1. Preload it - * 2. Include it in your source code and install it via the Game Config - * 3. Include it in your source code and install it within a Scene - * - * For examples of all of these approaches please see the Phaser 3 Examples Repo `plugins` folder. - * - * For information on creating your own plugin please see the Phaser 3 Plugin Template. - */ - class PluginManager { - /** - * - * @param game The game instance that owns this Plugin Manager. - */ - constructor(game: Phaser.Game); - - /** - * The game instance that owns this Plugin Manager. - */ - game: Phaser.Game; - - /** - * The global plugins currently running and managed by this Plugin Manager. - * A plugin must have been started at least once in order to appear in this list. - */ - plugins: Phaser.Types.Plugins.GlobalPlugin[]; - - /** - * A list of plugin keys that should be installed into Scenes as well as the Core Plugins. - */ - scenePlugins: string[]; - - /** - * Run once the game has booted and installs all of the plugins configured in the Game Config. - */ - protected boot(): void; - - /** - * Called by the Scene Systems class. Tells the plugin manager to install all Scene plugins into it. - * - * First it will install global references, i.e. references from the Game systems into the Scene Systems (and Scene if mapped.) - * Then it will install Core Scene Plugins followed by Scene Plugins registered with the PluginManager. - * Finally it will install any references to Global Plugins that have a Scene mapping property into the Scene itself. - * @param sys The Scene Systems class to install all the plugins in to. - * @param globalPlugins An array of global plugins to install. - * @param scenePlugins An array of scene plugins to install. - */ - protected addToScene(sys: Phaser.Scenes.Systems, globalPlugins: any[], scenePlugins: any[]): void; - - /** - * Called by the Scene Systems class. Returns a list of plugins to be installed. - */ - protected getDefaultScenePlugins(): string[]; - - /** - * Installs a new Scene Plugin into the Plugin Manager and optionally adds it - * to the given Scene as well. A Scene Plugin added to the manager in this way - * will be automatically installed into all new Scenes using the key and mapping given. - * - * The `key` property is what the plugin is injected into Scene.Systems as. - * The `mapping` property is optional, and if specified is what the plugin is installed into - * the Scene as. For example: - * - * ```javascript - * this.plugins.installScenePlugin('powerupsPlugin', pluginCode, 'powerups'); - * - * // and from within the scene: - * this.sys.powerupsPlugin; // key value - * this.powerups; // mapping value - * ``` - * - * This method is called automatically by Phaser if you install your plugins using either the - * Game Configuration object, or by preloading them via the Loader. - * @param key The property key that will be used to add this plugin to Scene.Systems. - * @param plugin The plugin code. This should be the non-instantiated version. - * @param mapping If this plugin is injected into the Phaser.Scene class, this is the property key to use. - * @param addToScene Optionally automatically add this plugin to the given Scene. - * @param fromLoader Is this being called by the Loader? Default false. - */ - installScenePlugin(key: string, plugin: Function, mapping?: string, addToScene?: Phaser.Scene, fromLoader?: boolean): void; - - /** - * Installs a new Global Plugin into the Plugin Manager and optionally starts it running. - * A global plugin belongs to the Plugin Manager, rather than a specific Scene, and can be accessed - * and used by all Scenes in your game. - * - * The `key` property is what you use to access this plugin from the Plugin Manager. - * - * ```javascript - * this.plugins.install('powerupsPlugin', pluginCode); - * - * // and from within the scene: - * this.plugins.get('powerupsPlugin'); - * ``` - * - * This method is called automatically by Phaser if you install your plugins using either the - * Game Configuration object, or by preloading them via the Loader. - * - * The same plugin can be installed multiple times into the Plugin Manager by simply giving each - * instance its own unique key. - * @param key The unique handle given to this plugin within the Plugin Manager. - * @param plugin The plugin code. This should be the non-instantiated version. - * @param start Automatically start the plugin running? This is always `true` if you provide a mapping value. Default false. - * @param mapping If this plugin is injected into the Phaser.Scene class, this is the property key to use. - * @param data A value passed to the plugin's `init` method. - */ - install(key: string, plugin: Function, start?: boolean, mapping?: string, data?: any): Phaser.Plugins.BasePlugin; - - /** - * Gets an index of a global plugin based on the given key. - * @param key The unique plugin key. - */ - protected getIndex(key: string): integer; - - /** - * Gets a global plugin based on the given key. - * @param key The unique plugin key. - */ - protected getEntry(key: string): Phaser.Types.Plugins.GlobalPlugin; - - /** - * Checks if the given global plugin, based on its key, is active or not. - * @param key The unique plugin key. - */ - isActive(key: string): boolean; - - /** - * Starts a global plugin running. - * - * If the plugin was previously active then calling `start` will reset it to an active state and then - * call its `start` method. - * - * If the plugin has never been run before a new instance of it will be created within the Plugin Manager, - * its active state set and then both of its `init` and `start` methods called, in that order. - * - * If the plugin is already running under the given key then nothing happens. - * @param key The key of the plugin to start. - * @param runAs Run the plugin under a new key. This allows you to run one plugin multiple times. - */ - start(key: string, runAs?: string): Phaser.Plugins.BasePlugin; - - /** - * Stops a global plugin from running. - * - * If the plugin is active then its active state will be set to false and the plugins `stop` method - * will be called. - * - * If the plugin is not already running, nothing will happen. - * @param key The key of the plugin to stop. - */ - stop(key: string): Phaser.Plugins.PluginManager; - - /** - * 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. - * @param key The key of the plugin to get. - * @param autoStart Automatically start a new instance of the plugin if found in the cache, but not actively running. Default true. - */ - get(key: string, autoStart?: boolean): Phaser.Plugins.BasePlugin | Function; - - /** - * Returns the plugin class from the cache. - * Used internally by the Plugin Manager. - * @param key The key of the plugin to get. - */ - getClass(key: string): Phaser.Plugins.BasePlugin; - - /** - * Removes a global plugin from the Plugin Manager and Plugin Cache. - * - * It is up to you to remove all references to this plugin that you may hold within your game code. - * @param key The key of the plugin to remove. - */ - removeGlobalPlugin(key: string): void; - - /** - * Removes a scene plugin from the Plugin Manager and Plugin Cache. - * - * This will not remove the plugin from any active Scenes that are already using it. - * - * It is up to you to remove all references to this plugin that you may hold within your game code. - * @param key The key of the plugin to remove. - */ - removeScenePlugin(key: string): void; - - /** - * Registers a new type of Game Object with the global Game Object Factory and / or Creator. - * This is usually called from within your Plugin code and is a helpful short-cut for creating - * new Game Objects. - * - * The key is the property that will be injected into the factories and used to create the - * Game Object. For example: - * - * ```javascript - * this.plugins.registerGameObject('clown', clownFactoryCallback, clownCreatorCallback); - * // later in your game code: - * this.add.clown(); - * this.make.clown(); - * ``` - * - * The callbacks are what are called when the factories try to create a Game Object - * matching the given key. It's important to understand that the callbacks are invoked within - * the context of the GameObjectFactory. In this 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. - * - * See the GameObjectFactory and GameObjectCreator classes for more details. - * Any public property or method listed is available from your callbacks under `this`. - * @param key The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. - * @param factoryCallback The callback to invoke when the Game Object Factory is called. - * @param creatorCallback The callback to invoke when the Game Object Creator is called. - */ - registerGameObject(key: string, factoryCallback?: Function, creatorCallback?: Function): void; - - /** - * Removes a previously registered Game Object from the global Game Object Factory and / or Creator. - * This is usually called from within your Plugin destruction code to help clean-up after your plugin has been removed. - * @param key The key of the Game Object to be removed from the factories. - * @param removeFromFactory Should the Game Object be removed from the Game Object Factory? Default true. - * @param removeFromCreator Should the Game Object be removed from the Game Object Creator? Default true. - */ - removeGameObject(key: string, removeFromFactory?: boolean, removeFromCreator?: boolean): void; - - /** - * Registers a new file type with the global File Types Manager, making it available to all Loader - * Plugins created after this. - * - * This is usually called from within your Plugin code and is a helpful short-cut for creating - * new loader file types. - * - * The key is the property that will be injected into the Loader Plugin and used to load the - * files. For example: - * - * ```javascript - * this.plugins.registerFileType('wad', doomWadLoaderCallback); - * // later in your preload code: - * this.load.wad(); - * ``` - * - * The callback is what is called when the loader tries to load a file matching the given key. - * It's important to understand that the callback is invoked within - * the context of the LoaderPlugin. In this context there are several properties / methods available - * to use: - * - * this.addFile - A method to add the new file to the load queue. - * this.scene - The Scene that owns the Loader Plugin instance. - * - * See the LoaderPlugin class for more details. Any public property or method listed is available from - * your callback under `this`. - * @param key The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. - * @param callback The callback to invoke when the Game Object Factory is called. - * @param addToScene Optionally add this file type into the Loader Plugin owned by the given Scene. - */ - registerFileType(key: string, callback: Function, addToScene?: Phaser.Scene): void; - - /** - * Destroys this Plugin Manager and all associated plugins. - * It will iterate all plugins found and call their `destroy` methods. - * - * The PluginCache will remove all custom plugins. - */ - destroy(): void; - - } - - /** - * A Scene Level Plugin is installed into every Scene and belongs to that Scene. - * It can listen for Scene events and respond to them. - * It can map itself to a Scene property, or into the Scene Systems, or both. - */ - class ScenePlugin extends Phaser.Plugins.BasePlugin { - /** - * - * @param scene A reference to the Scene that has installed this plugin. - * @param pluginManager A reference to the Plugin Manager. - */ - constructor(scene: Phaser.Scene, pluginManager: Phaser.Plugins.PluginManager); - - /** - * A reference to the Scene that has installed this plugin. - * Only set if it's a Scene Plugin, otherwise `null`. - * This property is only set when the plugin is instantiated and added to the Scene, not before. - * You can use it during the `boot` method. - */ - protected scene: Phaser.Scene; - - /** - * A reference to the Scene Systems of the Scene that has installed this plugin. - * Only set if it's a Scene Plugin, otherwise `null`. - * This property is only set when the plugin is instantiated and added to the Scene, not before. - * You can use it during the `boot` method. - */ - protected systems: Phaser.Scenes.Systems; - - /** - * This method is called when the Scene boots. It is only ever called once. - * - * By this point the plugin properties `scene` and `systems` will have already been set. - * - * In here you can listen for {@link Phaser.Scenes.Events Scene events} and set-up whatever you need for this plugin to run. - * Here are the Scene events you can listen to: - * - * - start - * - ready - * - preupdate - * - update - * - postupdate - * - resize - * - pause - * - resume - * - sleep - * - wake - * - transitioninit - * - transitionstart - * - transitioncomplete - * - transitionout - * - shutdown - * - destroy - * - * At the very least you should offer a destroy handler for when the Scene closes down, i.e: - * - * ```javascript - * var eventEmitter = this.systems.events; - * eventEmitter.once('destroy', this.sceneDestroy, this); - * ``` - */ - boot(): void; - - /** - * Game instance has been destroyed. - * - * You must release everything in here, all references, all objects, free it all up. - */ - destroy(): void; - - } - - } - - /** - * Phaser Blend Modes. - */ - enum BlendModes { - /** - * Skips the Blend Mode check in the renderer. - */ - SKIP_CHECK, - /** - * Normal blend mode. For Canvas and WebGL. - * This is the default setting and draws new shapes on top of the existing canvas content. - */ - NORMAL, - /** - * Add blend mode. For Canvas and WebGL. - * Where both shapes overlap the color is determined by adding color values. - */ - ADD, - /** - * Multiply blend mode. For Canvas and WebGL. - * The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result. - */ - MULTIPLY, - /** - * Screen blend mode. For Canvas and WebGL. - * The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply) - */ - SCREEN, - /** - * Overlay blend mode. For Canvas only. - * A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter. - */ - OVERLAY, - /** - * Darken blend mode. For Canvas only. - * Retains the darkest pixels of both layers. - */ - DARKEN, - /** - * Lighten blend mode. For Canvas only. - * Retains the lightest pixels of both layers. - */ - LIGHTEN, - /** - * Color Dodge blend mode. For Canvas only. - * Divides the bottom layer by the inverted top layer. - */ - COLOR_DODGE, - /** - * Color Burn blend mode. For Canvas only. - * Divides the inverted bottom layer by the top layer, and then inverts the result. - */ - COLOR_BURN, - /** - * Hard Light blend mode. For Canvas only. - * A combination of multiply and screen like overlay, but with top and bottom layer swapped. - */ - HARD_LIGHT, - /** - * Soft Light blend mode. For Canvas only. - * A softer version of hard-light. Pure black or white does not result in pure black or white. - */ - SOFT_LIGHT, - /** - * Difference blend mode. For Canvas only. - * Subtracts the bottom layer from the top layer or the other way round to always get a positive value. - */ - DIFFERENCE, - /** - * Exclusion blend mode. For Canvas only. - * Like difference, but with lower contrast. - */ - EXCLUSION, - /** - * Hue blend mode. For Canvas only. - * Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer. - */ - HUE, - /** - * Saturation blend mode. For Canvas only. - * Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer. - */ - SATURATION, - /** - * Color blend mode. For Canvas only. - * Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer. - */ - COLOR, - /** - * Luminosity blend mode. For Canvas only. - * Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer. - */ - LUMINOSITY, - /** - * Alpha erase blend mode. For Canvas and WebGL. - */ - ERASE, - /** - * Source-in blend mode. For Canvas only. - * The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent. - */ - SOURCE_IN, - /** - * Source-out blend mode. For Canvas only. - * The new shape is drawn where it doesn't overlap the existing canvas content. - */ - SOURCE_OUT, - /** - * Source-out blend mode. For Canvas only. - * The new shape is only drawn where it overlaps the existing canvas content. - */ - SOURCE_ATOP, - /** - * Destination-over blend mode. For Canvas only. - * New shapes are drawn behind the existing canvas content. - */ - DESTINATION_OVER, - /** - * Destination-in blend mode. For Canvas only. - * The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent. - */ - DESTINATION_IN, - /** - * Destination-out blend mode. For Canvas only. - * The existing content is kept where it doesn't overlap the new shape. - */ - DESTINATION_OUT, - /** - * Destination-out blend mode. For Canvas only. - * The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content. - */ - DESTINATION_ATOP, - /** - * Lighten blend mode. For Canvas only. - * Where both shapes overlap the color is determined by adding color values. - */ - LIGHTER, - /** - * Copy blend mode. For Canvas only. - * Only the new shape is shown. - */ - COPY, - /** - * Xor blend mode. For Canvas only. - * Shapes are made transparent where both overlap and drawn normal everywhere else. - */ - XOR, - } - - namespace Renderer { - namespace Canvas { - /** - * The Canvas Renderer is responsible for managing 2D canvas rendering contexts, including the one used by the Game's canvas. It tracks the internal state of a given context and can renderer textured Game Objects to it, taking into account alpha, blending, and scaling. - */ - class CanvasRenderer { - /** - * - * @param game The Phaser Game instance that owns this renderer. - */ - constructor(game: Phaser.Game); - - /** - * The Phaser Game instance that owns this renderer. - */ - game: Phaser.Game; - - /** - * A constant which allows the renderer to be easily identified as a Canvas Renderer. - */ - type: integer; - - /** - * The total number of Game Objects which were rendered in a frame. - */ - drawCount: number; - - /** - * The width of the canvas being rendered to. - */ - width: integer; - - /** - * The height of the canvas being rendered to. - */ - height: integer; - - /** - * The local configuration settings of the CanvasRenderer. - */ - config: object; - - /** - * The canvas element which the Game uses. - */ - gameCanvas: HTMLCanvasElement; - - /** - * The canvas context used to render all Cameras in all Scenes during the game loop. - */ - gameContext: CanvasRenderingContext2D; - - /** - * The canvas context currently used by the CanvasRenderer for all rendering operations. - */ - currentContext: CanvasRenderingContext2D; - - /** - * Should the Canvas use Image Smoothing or not when drawing Sprites? - */ - antialias: boolean; - - /** - * The blend modes supported by the Canvas Renderer. - * - * This object maps the {@link Phaser.BlendModes} to canvas compositing operations. - */ - blendModes: any[]; - - /** - * Details about the currently scheduled snapshot. - * - * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. - */ - snapshotState: Phaser.Types.Renderer.Snapshot.SnapshotState; - - /** - * Prepares the game canvas for rendering. - */ - init(): void; - - /** - * The event handler that manages the `resize` event dispatched by the Scale Manager. - * @param gameSize The default Game Size object. This is the un-modified game dimensions. - * @param baseSize The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. - * @param displaySize The display Size object. The size of the canvas style width / height attributes. - * @param resolution The Scale Manager resolution setting. - */ - onResize(gameSize: Phaser.Structs.Size, baseSize: Phaser.Structs.Size, displaySize: Phaser.Structs.Size, resolution?: number): void; - - /** - * Resize the main game canvas. - * @param width The new width of the renderer. - * @param height The new height of the renderer. - */ - resize(width?: number, height?: number): void; - - /** - * Resets the transformation matrix of the current context to the identity matrix, thus resetting any transformation. - */ - resetTransform(): void; - - /** - * Sets the blend mode (compositing operation) of the current context. - * @param blendMode The new blend mode which should be used. - */ - setBlendMode(blendMode: string): this; - - /** - * Changes the Canvas Rendering Context that all draw operations are performed against. - * @param ctx The new Canvas Rendering Context to draw everything to. Leave empty to reset to the Game Canvas. - */ - setContext(ctx?: CanvasRenderingContext2D): this; - - /** - * Sets the global alpha of the current context. - * @param alpha The new alpha to use, where 0 is fully transparent and 1 is fully opaque. - */ - setAlpha(alpha: number): this; - - /** - * Called at the start of the render loop. - */ - preRender(): void; - - /** - * Renders the Scene to the given Camera. - * @param scene The Scene to render. - * @param children The Game Objects within the Scene to be rendered. - * @param interpolationPercentage The interpolation percentage to apply. Currently unused. - * @param camera The Scene Camera to render with. - */ - render(scene: Phaser.Scene, children: Phaser.GameObjects.DisplayList, interpolationPercentage: number, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * Restores the game context's global settings and takes a snapshot if one is scheduled. - * - * The post-render step happens after all Cameras in all Scenes have been rendered. - */ - postRender(): void; - - /** - * Takes a snapshot of the given area of the given canvas. - * - * Unlike the other snapshot methods, this one is processed immediately and doesn't wait for the next render. - * - * Snapshots work by creating an Image object from the canvas data, this is a blocking process, which gets - * more expensive the larger the canvas size gets, so please be careful how you employ this in your game. - * @param canvas The canvas to grab from. - * @param callback The Function to invoke after the snapshot image is created. - * @param getPixel Grab a single pixel as a Color object, or an area as an Image object? Default false. - * @param x The x coordinate to grab from. Default 0. - * @param y The y coordinate to grab from. Default 0. - * @param width The width of the area to grab. Default canvas.width. - * @param height The height of the area to grab. Default canvas.height. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshotCanvas(canvas: HTMLCanvasElement, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, getPixel?: boolean, x?: integer, y?: integer, width?: integer, height?: integer, type?: string, encoderOptions?: number): this; - - /** - * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. - * - * To capture a specific area see the `snapshotArea` 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 creating an Image object from the canvas data, this is a blocking process, which gets - * more expensive the larger the canvas size gets, so please be careful how you employ this in your game. - * @param callback The Function to invoke after the snapshot image is created. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshot(callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; - - /** - * 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 creating an Image object from the canvas data, this is a blocking process, which gets - * more expensive the larger the canvas size gets, so please be careful how you employ this in your game. - * @param x The x coordinate to grab from. - * @param y The y coordinate to grab from. - * @param width The width of the area to grab. - * @param height The height of the area to grab. - * @param callback The Function to invoke after the snapshot image is created. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshotArea(x: integer, y: integer, width: integer, height: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; - - /** - * 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. - * @param x The x coordinate of the pixel to get. - * @param y The y coordinate of the pixel to get. - * @param callback The Function to invoke after the snapshot pixel data is extracted. - */ - snapshotPixel(x: integer, y: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback): this; - - /** - * Takes a Sprite Game Object, or any object that extends it, and draws it to the current context. - * @param sprite The texture based Game Object to draw. - * @param frame The frame to draw, doesn't have to be that owned by the Game Object. - * @param camera The Camera to use for the rendering transform. - * @param parentTransformMatrix The transform matrix of the parent container, if set. - */ - batchSprite(sprite: Phaser.GameObjects.GameObject, frame: Phaser.Textures.Frame, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix?: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Destroys all object references in the Canvas Renderer. - */ - destroy(): void; - - } - - /** - * Returns an array which maps the default blend modes to supported Canvas blend modes. - * - * If the browser doesn't support a blend mode, it will default to the normal `source-over` blend mode. - */ - function GetBlendModes(): any[]; - - /** - * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. - * - * This function is only meant to be used internally. Most of the Canvas Renderer classes use it. - * @param renderer A reference to the current active Canvas renderer. - * @param ctx The canvas context to set the transform on. - * @param src The Game Object being rendered. Can be any type that extends the base class. - * @param camera The Camera that is rendering the Game Object. - * @param parentMatrix A parent transform matrix to apply to the Game Object before rendering. - */ - function SetTransform(renderer: Phaser.Renderer.Canvas.CanvasRenderer, ctx: CanvasRenderingContext2D, src: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): boolean; - - } - - namespace Snapshot { - /** - * Takes a snapshot of an area from the current frame displayed by a canvas. - * - * This is then copied to an Image object. When this loads, the results are sent - * to the callback provided in the Snapshot Configuration object. - * @param sourceCanvas The canvas to take a snapshot of. - * @param config The snapshot configuration object. - */ - function Canvas(sourceCanvas: HTMLCanvasElement, config: Phaser.Types.Renderer.Snapshot.SnapshotState): void; - - /** - * Takes a snapshot of an area from the current frame displayed by a WebGL canvas. - * - * This is then copied to an Image object. When this loads, the results are sent - * to the callback provided in the Snapshot Configuration object. - * @param sourceCanvas The canvas to take a snapshot of. - * @param config The snapshot configuration object. - */ - function WebGL(sourceCanvas: HTMLCanvasElement, config: Phaser.Types.Renderer.Snapshot.SnapshotState): void; - - } - - namespace WebGL { - namespace Pipelines { - /** - * BitmapMaskPipeline handles all bitmap masking rendering in WebGL. It works by using - * sampling two texture on the fragment shader and using the fragment's alpha to clip the region. - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - */ - class BitmapMaskPipeline extends Phaser.Renderer.WebGL.WebGLPipeline { - /** - * - * @param config Used for overriding shader an pipeline properties if extending this pipeline. - */ - constructor(config: object); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - */ - vertexViewF32: Float32Array; - - /** - * Size of the batch. - */ - maxQuads: number; - - /** - * Dirty flag to check if resolution properties need to be updated on the - * masking shader. - */ - resolutionDirty: boolean; - - /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - */ - onBind(): this; - - /** - * [description] - * @param width [description] - * @param height [description] - * @param resolution [description] - */ - resize(width: number, height: number, resolution: number): this; - - /** - * Binds necessary resources and renders the mask to a separated framebuffer. - * The framebuffer for the masked object is also bound for further use. - * @param mask GameObject used as mask. - * @param maskedObject GameObject masked by the mask GameObject. - * @param camera [description] - */ - beginMask(mask: Phaser.GameObjects.GameObject, maskedObject: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * The masked game objects framebuffer is unbound and its texture - * is bound together with the mask texture and the mask shader and - * a draw call with a single quad is processed. Here is where the - * masking effect is applied. - * @param mask GameObject used as a mask. - */ - endMask(mask: Phaser.GameObjects.GameObject): void; - - } - - /** - * Implements a model view projection matrices. - * Pipelines can implement this for doing 2D and 3D rendering. - */ - interface ModelViewProjection { - /** - * Dirty flag for checking if model matrix needs to be updated on GPU. - */ - modelMatrixDirty: boolean; - /** - * Dirty flag for checking if view matrix needs to be updated on GPU. - */ - viewMatrixDirty: boolean; - /** - * Dirty flag for checking if projection matrix needs to be updated on GPU. - */ - projectionMatrixDirty: boolean; - /** - * Model matrix - */ - modelMatrix: Float32Array; - /** - * View matrix - */ - viewMatrix: Float32Array; - /** - * Projection matrix - */ - projectionMatrix: Float32Array; - /** - * Initializes MVP matrices with an identity matrix - */ - mvpInit(): void; - /** - * If dirty flags are set then the matrices are uploaded to the GPU. - */ - mvpUpdate(): void; - /** - * Loads an identity matrix to the model matrix - */ - modelIdentity(): void; - /** - * Scale model matrix - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - modelScale(x: number, y: number, z: number): this; - /** - * Translate model matrix - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - modelTranslate(x: number, y: number, z: number): this; - /** - * Rotates the model matrix in the X axis. - * @param radians The amount to rotate by. - */ - modelRotateX(radians: number): this; - /** - * Rotates the model matrix in the Y axis. - * @param radians The amount to rotate by. - */ - modelRotateY(radians: number): this; - /** - * Rotates the model matrix in the Z axis. - * @param radians The amount to rotate by. - */ - modelRotateZ(radians: number): this; - /** - * Loads identity matrix into the view matrix - */ - viewIdentity(): this; - /** - * Scales view matrix - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - viewScale(x: number, y: number, z: number): this; - /** - * Translates view matrix - * @param x The x component. - * @param y The y component. - * @param z The z component. - */ - viewTranslate(x: number, y: number, z: number): this; - /** - * Rotates view matrix in the X axis. - * @param radians The amount to rotate by. - */ - viewRotateX(radians: number): this; - /** - * Rotates view matrix in the Y axis. - * @param radians The amount to rotate by. - */ - viewRotateY(radians: number): this; - /** - * Rotates view matrix in the Z axis. - * @param radians The amount to rotate by. - */ - viewRotateZ(radians: number): this; - /** - * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix - * @param matrix2D The Matrix2D. - */ - viewLoad2D(matrix2D: Float32Array): this; - /** - * Copies a 4x4 matrix into the view matrix - * @param matrix The Matrix2D. - */ - viewLoad(matrix: Float32Array): this; - /** - * Loads identity matrix into the projection matrix. - */ - projIdentity(): this; - /** - * Sets up an orthographic projection matrix - * @param left The left value. - * @param right The right value. - * @param bottom The bottom value. - * @param top The top value. - * @param near The near value. - * @param far The far value. - */ - projOrtho(left: number, right: number, bottom: number, top: number, near: number, far: number): this; - /** - * Sets up a perspective projection matrix - * @param fovY The fov value. - * @param aspectRatio The aspectRatio value. - * @param near The near value. - * @param far The far value. - */ - projPersp(fovY: number, aspectRatio: number, near: number, far: number): this; - } - - /** - * ForwardDiffuseLightPipeline implements a forward rendering approach for 2D lights. - * This pipeline extends TextureTintPipeline so it implements all it's rendering functions - * and batching system. - */ - class ForwardDiffuseLightPipeline extends Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline { - /** - * - * @param config The configuration of the pipeline, same as the {@link Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline}. The fragment shader will be replaced with the lighting shader. - */ - constructor(config: object); - - /** - * This function sets all the needed resources for each camera pass. - * @param scene The Scene being rendered. - * @param camera The Scene Camera being rendered with. - */ - onRender(scene: Phaser.Scene, camera: Phaser.Cameras.Scene2D.Camera): this; - - /** - * Generic function for batching a textured quad - * @param gameObject Source GameObject - * @param texture Raw WebGLTexture associated with the quad - * @param textureWidth Real texture width - * @param textureHeight Real texture height - * @param srcX X coordinate of the quad - * @param srcY Y coordinate of the quad - * @param srcWidth Width of the quad - * @param srcHeight Height of the quad - * @param scaleX X component of scale - * @param scaleY Y component of scale - * @param rotation Rotation of the quad - * @param flipX Indicates if the quad is horizontally flipped - * @param flipY Indicates if the quad is vertically flipped - * @param scrollFactorX By which factor is the quad affected by the camera horizontal scroll - * @param scrollFactorY By which factor is the quad effected by the camera vertical scroll - * @param displayOriginX Horizontal origin in pixels - * @param displayOriginY Vertical origin in pixels - * @param frameX X coordinate of the texture frame - * @param frameY Y coordinate of the texture frame - * @param frameWidth Width of the texture frame - * @param frameHeight Height of the texture frame - * @param tintTL Tint for top left - * @param tintTR Tint for top right - * @param tintBL Tint for bottom left - * @param tintBR Tint for bottom right - * @param tintEffect The tint effect (0 for additive, 1 for replacement) - * @param uOffset Horizontal offset on texture coordinate - * @param vOffset Vertical offset on texture coordinate - * @param camera Current used camera - * @param parentTransformMatrix Parent container - */ - batchTexture(gameObject: Phaser.GameObjects.GameObject, texture: WebGLTexture, textureWidth: integer, textureHeight: integer, srcX: number, srcY: number, srcWidth: number, srcHeight: number, scaleX: number, scaleY: number, rotation: number, flipX: boolean, flipY: boolean, scrollFactorX: number, scrollFactorY: number, displayOriginX: number, displayOriginY: number, frameX: number, frameY: number, frameWidth: number, frameHeight: number, tintTL: integer, tintTR: integer, tintBL: integer, tintBR: integer, tintEffect: number, uOffset: number, vOffset: number, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Sets the Game Objects normal map as the active texture. - * @param gameObject The Game Object to update. - */ - setNormalMap(gameObject: Phaser.GameObjects.GameObject): void; - - /** - * Rotates the normal map vectors inversely by the given angle. - * Only works in 2D space. - * @param rotation The angle of rotation in radians. - */ - setNormalMapRotation(rotation: number): void; - - /** - * Takes a Sprite Game Object, or any object that extends it, which has a normal texture and adds it to the batch. - * @param sprite The texture-based Game Object to add to the batch. - * @param camera The Camera to use for the rendering transform. - * @param parentTransformMatrix The transform matrix of the parent container, if set. - */ - batchSprite(sprite: Phaser.GameObjects.Sprite, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - } - - /** - * TextureTintPipeline implements the rendering infrastructure - * for displaying textured objects - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - */ - class TextureTintPipeline extends Phaser.Renderer.WebGL.WebGLPipeline { - /** - * - * @param config The configuration options for this Texture Tint Pipeline, as described above. - */ - constructor(config: object); - - /** - * Float32 view of the array buffer containing the pipeline's vertices. - */ - vertexViewF32: Float32Array; - - /** - * Uint32 view of the array buffer containing the pipeline's vertices. - */ - vertexViewU32: Uint32Array; - - /** - * Size of the batch. - */ - maxQuads: integer; - - /** - * Collection of batch information - */ - batches: any[]; - - /** - * Called every time the pipeline needs to be used. - * It binds all necessary resources. - */ - onBind(): this; - - /** - * Resizes this pipeline and updates the projection. - * @param width The new width. - * @param height The new height. - * @param resolution The resolution. - */ - resize(width: number, height: number, resolution: number): this; - - /** - * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. - * @param texture WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param unit Texture unit to which the texture needs to be bound. Default 0. - */ - setTexture2D(texture?: WebGLTexture, unit?: integer): Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline; - - /** - * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. - * @param texture WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. - * @param unit Texture unit to which the texture needs to be bound. - */ - requireTextureBatch(texture: WebGLTexture, unit: integer): boolean; - - /** - * Creates a new batch object and pushes it to a batch array. - * The batch object contains information relevant to the current - * vertex batch like the offset in the vertex buffer, vertex count and - * the textures used by that batch. - * @param texture Optional WebGLTexture that will be assigned to the created batch. - * @param unit Texture unit to which the texture needs to be bound. - */ - pushBatch(texture: WebGLTexture, unit: integer): void; - - /** - * Uploads the vertex data and emits a draw call for the current batch of vertices. - */ - flush(): this; - - /** - * Takes a Sprite Game Object, or any object that extends it, and adds it to the batch. - * @param sprite The texture based Game Object to add to the batch. - * @param camera The Camera to use for the rendering transform. - * @param parentTransformMatrix The transform matrix of the parent container, if set. - */ - batchSprite(sprite: Phaser.GameObjects.Image | Phaser.GameObjects.Sprite, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix?: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Adds the vertices data into the batch and flushes if full. - * - * Assumes 6 vertices in the following arrangement: - * - * ``` - * 0----3 - * |\ B| - * | \ | - * | \ | - * | A \| - * | \ - * 1----2 - * ``` - * - * Where tx0/ty0 = 0, tx1/ty1 = 1, tx2/ty2 = 2 and tx3/ty3 = 3 - * @param x0 The top-left x position. - * @param y0 The top-left y position. - * @param x1 The bottom-left x position. - * @param y1 The bottom-left y position. - * @param x2 The bottom-right x position. - * @param y2 The bottom-right y position. - * @param x3 The top-right x position. - * @param y3 The top-right y position. - * @param u0 UV u0 value. - * @param v0 UV v0 value. - * @param u1 UV u1 value. - * @param v1 UV v1 value. - * @param tintTL The top-left tint color value. - * @param tintTR The top-right tint color value. - * @param tintBL The bottom-left tint color value. - * @param tintBR The bottom-right tint color value. - * @param tintEffect The tint effect for the shader to use. - * @param texture WebGLTexture that will be assigned to the current batch if a flush occurs. - * @param unit Texture unit to which the texture needs to be bound. Default 0. - */ - batchQuad(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, u0: number, v0: number, u1: number, v1: number, tintTL: number, tintTR: number, tintBL: number, tintBR: number, tintEffect: number | boolean, texture?: WebGLTexture, unit?: integer): boolean; - - /** - * Adds the vertices data into the batch and flushes if full. - * - * Assumes 3 vertices in the following arrangement: - * - * ``` - * 0 - * |\ - * | \ - * | \ - * | \ - * | \ - * 1-----2 - * ``` - * @param x1 The bottom-left x position. - * @param y1 The bottom-left y position. - * @param x2 The bottom-right x position. - * @param y2 The bottom-right y position. - * @param x3 The top-right x position. - * @param y3 The top-right y position. - * @param u0 UV u0 value. - * @param v0 UV v0 value. - * @param u1 UV u1 value. - * @param v1 UV v1 value. - * @param tintTL The top-left tint color value. - * @param tintTR The top-right tint color value. - * @param tintBL The bottom-left tint color value. - * @param tintEffect The tint effect for the shader to use. - * @param texture WebGLTexture that will be assigned to the current batch if a flush occurs. - * @param unit Texture unit to which the texture needs to be bound. Default 0. - */ - batchTri(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, u0: number, v0: number, u1: number, v1: number, tintTL: number, tintTR: number, tintBL: number, tintEffect: number | boolean, texture?: WebGLTexture, unit?: integer): boolean; - - /** - * Generic function for batching a textured quad using argument values instead of a Game Object. - * @param gameObject Source GameObject. - * @param texture Raw WebGLTexture associated with the quad. - * @param textureWidth Real texture width. - * @param textureHeight Real texture height. - * @param srcX X coordinate of the quad. - * @param srcY Y coordinate of the quad. - * @param srcWidth Width of the quad. - * @param srcHeight Height of the quad. - * @param scaleX X component of scale. - * @param scaleY Y component of scale. - * @param rotation Rotation of the quad. - * @param flipX Indicates if the quad is horizontally flipped. - * @param flipY Indicates if the quad is vertically flipped. - * @param scrollFactorX By which factor is the quad affected by the camera horizontal scroll. - * @param scrollFactorY By which factor is the quad effected by the camera vertical scroll. - * @param displayOriginX Horizontal origin in pixels. - * @param displayOriginY Vertical origin in pixels. - * @param frameX X coordinate of the texture frame. - * @param frameY Y coordinate of the texture frame. - * @param frameWidth Width of the texture frame. - * @param frameHeight Height of the texture frame. - * @param tintTL Tint for top left. - * @param tintTR Tint for top right. - * @param tintBL Tint for bottom left. - * @param tintBR Tint for bottom right. - * @param tintEffect The tint effect. - * @param uOffset Horizontal offset on texture coordinate. - * @param vOffset Vertical offset on texture coordinate. - * @param camera Current used camera. - * @param parentTransformMatrix Parent container. - * @param skipFlip Skip the renderTexture check. Default false. - */ - batchTexture(gameObject: Phaser.GameObjects.GameObject, texture: WebGLTexture, textureWidth: integer, textureHeight: integer, srcX: number, srcY: number, srcWidth: number, srcHeight: number, scaleX: number, scaleY: number, rotation: number, flipX: boolean, flipY: boolean, scrollFactorX: number, scrollFactorY: number, displayOriginX: number, displayOriginY: number, frameX: number, frameY: number, frameWidth: number, frameHeight: number, tintTL: integer, tintTR: integer, tintBL: integer, tintBR: integer, tintEffect: number, uOffset: number, vOffset: number, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix: Phaser.GameObjects.Components.TransformMatrix, skipFlip?: boolean): void; - - /** - * Adds a Texture Frame into the batch for rendering. - * @param frame The Texture Frame to be rendered. - * @param x The horizontal position to render the texture at. - * @param y The vertical position to render the texture at. - * @param tint The tint color. - * @param alpha The alpha value. - * @param transformMatrix The Transform Matrix to use for the texture. - * @param parentTransformMatrix A parent Transform Matrix. - */ - batchTextureFrame(frame: Phaser.Textures.Frame, x: number, y: number, tint: number, alpha: number, transformMatrix: Phaser.GameObjects.Components.TransformMatrix, parentTransformMatrix?: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Pushes a filled rectangle into the vertex batch. - * Rectangle has no transform values and isn't transformed into the local space. - * Used for directly batching untransformed rectangles, such as Camera background colors. - * @param x Horizontal top left coordinate of the rectangle. - * @param y Vertical top left coordinate of the rectangle. - * @param width Width of the rectangle. - * @param height Height of the rectangle. - * @param color Color of the rectangle to draw. - * @param alpha Alpha value of the rectangle to draw. - */ - drawFillRect(x: number, y: number, width: number, height: number, color: number, alpha: number): void; - - /** - * Pushes a filled rectangle into the vertex batch. - * Rectangle factors in the given transform matrices before adding to the batch. - * @param x Horizontal top left coordinate of the rectangle. - * @param y Vertical top left coordinate of the rectangle. - * @param width Width of the rectangle. - * @param height Height of the rectangle. - * @param currentMatrix The current transform. - * @param parentMatrix The parent transform. - */ - batchFillRect(x: number, y: number, width: number, height: number, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Pushes a filled triangle into the vertex batch. - * Triangle factors in the given transform matrices before adding to the batch. - * @param x0 Point 0 x coordinate. - * @param y0 Point 0 y coordinate. - * @param x1 Point 1 x coordinate. - * @param y1 Point 1 y coordinate. - * @param x2 Point 2 x coordinate. - * @param y2 Point 2 y coordinate. - * @param currentMatrix The current transform. - * @param parentMatrix The parent transform. - */ - batchFillTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Pushes a stroked triangle into the vertex batch. - * Triangle factors in the given transform matrices before adding to the batch. - * The triangle is created from 3 lines and drawn using the `batchStrokePath` method. - * @param x0 Point 0 x coordinate. - * @param y0 Point 0 y coordinate. - * @param x1 Point 1 x coordinate. - * @param y1 Point 1 y coordinate. - * @param x2 Point 2 x coordinate. - * @param y2 Point 2 y coordinate. - * @param lineWidth The width of the line in pixels. - * @param currentMatrix The current transform. - * @param parentMatrix The parent transform. - */ - batchStrokeTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, lineWidth: number, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Adds the given path to the vertex batch for rendering. - * - * It works by taking the array of path data and then passing it through Earcut, which - * creates a list of polygons. Each polygon is then added to the batch. - * - * The path is always automatically closed because it's filled. - * @param path Collection of points that represent the path. - * @param currentMatrix The current transform. - * @param parentMatrix The parent transform. - */ - batchFillPath(path: any[], currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Adds the given path to the vertex batch for rendering. - * - * It works by taking the array of path data and calling `batchLine` for each section - * of the path. - * - * The path is optionally closed at the end. - * @param path Collection of points that represent the path. - * @param lineWidth The width of the line segments in pixels. - * @param pathOpen Indicates if the path should be closed or left open. - * @param currentMatrix The current transform. - * @param parentMatrix The parent transform. - */ - batchStrokePath(path: any[], lineWidth: number, pathOpen: boolean, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; - - /** - * Creates a quad and adds it to the vertex batch based on the given line values. - * @param ax X coordinate to the start of the line - * @param ay Y coordinate to the start of the line - * @param bx X coordinate to the end of the line - * @param by Y coordinate to the end of the line - * @param aLineWidth Width of the start of the line - * @param bLineWidth Width of the end of the line - * @param currentMatrix Parent matrix, generally used by containers - */ - batchLine(ax: number, ay: number, bx: number, by: number, aLineWidth: number, bLineWidth: number, currentMatrix: Float32Array): void; - - } - - } - - namespace Utils { - /** - * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 - * @param r Red component in a range from 0.0 to 1.0 - * @param g Green component in a range from 0.0 to 1.0 - * @param b Blue component in a range from 0.0 to 1.0 - * @param a Alpha component in a range from 0.0 to 1.0 - */ - function getTintFromFloats(r: number, g: number, b: number, a: number): number; - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 - * @param rgb Uint24 representing RGB components - * @param a Float32 representing Alpha component - */ - function getTintAppendFloatAlpha(rgb: number, a: number): number; - - /** - * Packs a Uint24, representing RGB components, with a Float32, representing - * the alpha component, with a range between 0.0 and 1.0 and return a - * swizzled Uint32 - * @param rgb Uint24 representing RGB components - * @param a Float32 representing Alpha component - */ - function getTintAppendFloatAlphaAndSwap(rgb: number, a: number): number; - - /** - * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 - * @param rgb RGB packed as a Uint24 - */ - function getFloatsFromUintRGB(rgb: number): any[]; - - /** - * Counts how many attributes of 32 bits a vertex has - * @param attributes Array of attributes - * @param glContext WebGLContext used for check types - */ - function getComponentCount(attributes: any[], glContext: WebGLRenderingContext): number; - - } - - /** - * WebGLPipeline is a class that describes the way elements will be renderered - * in WebGL, specially focused on batching vertices (batching is not provided). - * Pipelines are mostly used for describing 2D rendering passes but it's - * flexible enough to be used for any type of rendering including 3D. - * Internally WebGLPipeline will handle things like compiling shaders, - * creating vertex buffers, assigning primitive topology and binding - * vertex attributes. - * - * The config properties are: - * - game: Current game instance. - * - renderer: Current WebGL renderer. - * - gl: Current WebGL context. - * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. - * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). - * - vertShader: Source for vertex shader as a string. - * - fragShader: Source for fragment shader as a string. - * - vertexCapacity: The amount of vertices that shall be allocated - * - vertexSize: The size of a single vertex in bytes. - * - vertices: An optional buffer of vertices - * - attributes: An array describing the vertex attributes - * - * The vertex attributes properties are: - * - name : String - Name of the attribute in the vertex shader - * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 - * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) - * - normalized : boolean - Is the attribute normalized - * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C - * Here you can find more information of how to describe an attribute: - * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer - */ - class WebGLPipeline { - /** - * - * @param config The configuration object for this WebGL Pipeline, as described above. - */ - constructor(config: object); - - /** - * Name of the Pipeline. Used for identifying - */ - name: string; - - /** - * The Game which owns this WebGL Pipeline. - */ - game: Phaser.Game; - - /** - * The canvas which this WebGL Pipeline renders to. - */ - view: HTMLCanvasElement; - - /** - * Used to store the current game resolution - */ - resolution: number; - - /** - * Width of the current viewport - */ - width: number; - - /** - * Height of the current viewport - */ - height: number; - - /** - * The WebGL context this WebGL Pipeline uses. - */ - gl: WebGLRenderingContext; - - /** - * How many vertices have been fed to the current pipeline. - */ - vertexCount: number; - - /** - * The limit of vertices that the pipeline can hold - */ - vertexCapacity: integer; - - /** - * The WebGL Renderer which owns this WebGL Pipeline. - */ - renderer: Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * Raw byte buffer of vertices. - */ - vertexData: ArrayBuffer; - - /** - * The handle to a WebGL vertex buffer object. - */ - vertexBuffer: WebGLBuffer; - - /** - * The handle to a WebGL program - */ - program: WebGLProgram; - - /** - * Array of objects that describe the vertex attributes - */ - attributes: object; - - /** - * The size in bytes of the vertex - */ - vertexSize: integer; - - /** - * The primitive topology which the pipeline will use to submit draw calls - */ - topology: integer; - - /** - * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources - * to the GPU. - */ - bytes: Uint8Array; - - /** - * This will store the amount of components of 32 bit length - */ - vertexComponentCount: integer; - - /** - * Indicates if the current pipeline is flushing the contents to the GPU. - * When the variable is set the flush function will be locked. - */ - flushLocked: boolean; - - /** - * Indicates if the current pipeline is active or not for this frame only. - * Reset in the onRender method. - */ - active: boolean; - - /** - * Called when the Game has fully booted and the Renderer has finished setting up. - * - * By this stage all Game level systems are now in place and you can perform any final - * tasks that the pipeline may need that relied on game systems such as the Texture Manager. - */ - boot(): void; - - /** - * Adds a description of vertex attribute to the pipeline - * @param name Name of the vertex attribute - * @param size Vertex component size - * @param type Type of the attribute - * @param normalized Is the value normalized to a range - * @param offset Byte offset to the beginning of the first element in the vertex - */ - addAttribute(name: string, size: integer, type: integer, normalized: boolean, offset: integer): this; - - /** - * Check if the current batch of vertices is full. - */ - shouldFlush(): boolean; - - /** - * Resizes the properties used to describe the viewport - * @param width The new width of this WebGL Pipeline. - * @param height The new height of this WebGL Pipeline. - * @param resolution The resolution this WebGL Pipeline should be resized to. - */ - resize(width: number, height: number, resolution: number): this; - - /** - * Binds the pipeline resources, including programs, vertex buffers and binds attributes - */ - bind(): this; - - /** - * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. - * - * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. - */ - onBind(): this; - - /** - * Called before each frame is rendered, but after the canvas has been cleared. - */ - onPreRender(): this; - - /** - * Called before a Scene's Camera is rendered. - * @param scene The Scene being rendered. - * @param camera The Scene Camera being rendered with. - */ - onRender(scene: Phaser.Scene, camera: Phaser.Cameras.Scene2D.Camera): this; - - /** - * Called after each frame has been completely rendered and snapshots have been taken. - */ - onPostRender(): this; - - /** - * Uploads the vertex data and emits a draw call - * for the current batch of vertices. - */ - flush(): this; - - /** - * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. - */ - destroy(): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x The new value of the `float` uniform. - */ - setFloat1(name: string, x: number): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x The new X component of the `vec2` uniform. - * @param y The new Y component of the `vec2` uniform. - */ - setFloat2(name: string, x: number, y: number): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x The new X component of the `vec3` uniform. - * @param y The new Y component of the `vec3` uniform. - * @param z The new Z component of the `vec3` uniform. - */ - setFloat3(name: string, x: number, y: number, z: number): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x X component of the uniform - * @param y Y component of the uniform - * @param z Z component of the uniform - * @param w W component of the uniform - */ - setFloat4(name: string, x: number, y: number, z: number, w: number): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat1v(name: string, arr: Float32Array): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat2v(name: string, arr: Float32Array): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat3v(name: string, arr: Float32Array): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat4v(name: string, arr: Float32Array): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x The new value of the `int` uniform. - */ - setInt1(name: string, x: integer): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x The new X component of the `ivec2` uniform. - * @param y The new Y component of the `ivec2` uniform. - */ - setInt2(name: string, x: integer, y: integer): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x The new X component of the `ivec3` uniform. - * @param y The new Y component of the `ivec3` uniform. - * @param z The new Z component of the `ivec3` uniform. - */ - setInt3(name: string, x: integer, y: integer, z: integer): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param x X component of the uniform - * @param y Y component of the uniform - * @param z Z component of the uniform - * @param w W component of the uniform - */ - setInt4(name: string, x: integer, y: integer, z: integer, w: integer): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param transpose Whether to transpose the matrix. Should be `false`. - * @param matrix The new values for the `mat2` uniform. - */ - setMatrix2(name: string, transpose: boolean, matrix: Float32Array): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param transpose Whether to transpose the matrix. Should be `false`. - * @param matrix The new values for the `mat3` uniform. - */ - setMatrix3(name: string, transpose: boolean, matrix: Float32Array): this; - - /** - * Set a uniform value of the current pipeline program. - * @param name The name of the uniform to look-up and modify. - * @param transpose Should the matrix be transpose - * @param matrix Matrix data - */ - setMatrix4(name: string, transpose: boolean, matrix: Float32Array): this; - - } - - /** - * WebGLRenderer is a class that contains the needed functionality to keep the - * WebGLRenderingContext state clean. The main idea of the WebGLRenderer is to keep track of - * any context change that happens for WebGL rendering inside of Phaser. This means - * if raw webgl functions are called outside the WebGLRenderer of the Phaser WebGL - * rendering ecosystem they might pollute the current WebGLRenderingContext state producing - * unexpected behavior. It's recommended that WebGL interaction is done through - * WebGLRenderer and/or WebGLPipeline. - */ - class WebGLRenderer { - /** - * - * @param game The Game instance which owns this WebGL Renderer. - */ - constructor(game: Phaser.Game); - - /** - * The local configuration settings of this WebGL Renderer. - */ - config: object; - - /** - * The Game instance which owns this WebGL Renderer. - */ - game: Phaser.Game; - - /** - * A constant which allows the renderer to be easily identified as a WebGL Renderer. - */ - type: integer; - - /** - * The width of the canvas being rendered to. - * This is populated in the onResize event handler. - */ - width: integer; - - /** - * The height of the canvas being rendered to. - * This is populated in the onResize event handler. - */ - height: integer; - - /** - * The canvas which this WebGL Renderer draws to. - */ - canvas: HTMLCanvasElement; - - /** - * An array of blend modes supported by the WebGL Renderer. - * - * This array includes the default blend modes as well as any custom blend modes added through {@link #addBlendMode}. - */ - blendModes: any[]; - - /** - * Keeps track of any WebGLTexture created with the current WebGLRenderingContext - */ - nativeTextures: any[]; - - /** - * This property is set to `true` if the WebGL context of the renderer is lost. - */ - contextLost: boolean; - - /** - * This object will store all pipelines created through addPipeline - */ - pipelines: object; - - /** - * Details about the currently scheduled snapshot. - * - * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. - */ - snapshotState: Phaser.Types.Renderer.Snapshot.SnapshotState; - - /** - * Cached value for the last texture unit that was used - */ - currentActiveTextureUnit: integer; - - /** - * An array of the last texture handles that were bound to the WebGLRenderingContext - */ - currentTextures: any[]; - - /** - * Current framebuffer in use - */ - currentFramebuffer: WebGLFramebuffer; - - /** - * Current WebGLPipeline in use - */ - currentPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Current WebGLProgram in use - */ - currentProgram: WebGLProgram; - - /** - * Current WebGLBuffer (Vertex buffer) in use - */ - currentVertexBuffer: WebGLBuffer; - - /** - * Current WebGLBuffer (Index buffer) in use - */ - currentIndexBuffer: WebGLBuffer; - - /** - * Current blend mode in use - */ - currentBlendMode: integer; - - /** - * Indicates if the the scissor state is enabled in WebGLRenderingContext - */ - currentScissorEnabled: boolean; - - /** - * Stores the current scissor data - */ - currentScissor: Uint32Array; - - /** - * Stack of scissor data - */ - scissorStack: Uint32Array; - - /** - * The handler to invoke when the context is lost. - * This should not be changed and is set in the boot method. - */ - contextLostHandler: Function; - - /** - * The handler to invoke when the context is restored. - * This should not be changed and is set in the boot method. - */ - contextRestoredHandler: Function; - - /** - * The underlying WebGL context of the renderer. - */ - gl: WebGLRenderingContext; - - /** - * Array of strings that indicate which WebGL extensions are supported by the browser - */ - supportedExtensions: object; - - /** - * Extensions loaded into the current context - */ - extensions: object; - - /** - * Stores the current WebGL component formats for further use - */ - glFormats: any[]; - - /** - * Stores the supported WebGL texture compression formats. - */ - compression: any[]; - - /** - * Cached drawing buffer height to reduce gl calls. - */ - readonly drawingBufferHeight: number; - - /** - * A blank 32x32 transparent texture, as used by the Graphics system where needed. - * This is set in the `boot` method. - */ - readonly blankTexture: WebGLTexture; - - /** - * A default Camera used in calls when no other camera has been provided. - */ - defaultCamera: Phaser.Cameras.Scene2D.BaseCamera; - - /** - * The total number of masks currently stacked. - */ - maskCount: integer; - - /** - * The mask stack. - */ - maskStack: Phaser.Display.Masks.GeometryMask[]; - - /** - * Internal property that tracks the currently set mask. - */ - currentMask: any; - - /** - * Internal property that tracks the currently set camera mask. - */ - currentCameraMask: any; - - /** - * Internal gl function mapping for uniform look-up. - * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform - */ - glFuncMap: any; - - /** - * The `type` of the Game Object being currently rendered. - * This can be used by advanced render functions for batching look-ahead. - */ - currentType: string; - - /** - * Is the `type` of the Game Object being currently rendered different than the - * type of the object before it in the display list? I.e. it's a 'new' type. - */ - newType: boolean; - - /** - * Does the `type` of the next Game Object in the display list match that - * of the object being currently rendered? - */ - nextTypeMatch: boolean; - - /** - * The mipmap magFilter to be used when creating textures. - * - * You can specify this as a string in the game config, i.e.: - * - * `renderer: { 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 - */ - mipmapFilter: GLenum; - - /** - * Creates a new WebGLRenderingContext and initializes all internal state. - * @param config The configuration object for the renderer. - */ - init(config: object): this; - - /** - * The event handler that manages the `resize` event dispatched by the Scale Manager. - * @param gameSize The default Game Size object. This is the un-modified game dimensions. - * @param baseSize The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. - * @param displaySize The display Size object. The size of the canvas style width / height attributes. - * @param resolution The Scale Manager resolution setting. - */ - onResize(gameSize: Phaser.Structs.Size, baseSize: Phaser.Structs.Size, displaySize: Phaser.Structs.Size, resolution?: number): void; - - /** - * Resizes the drawing buffer to match that required by the Scale Manager. - * @param width The new width of the renderer. - * @param height The new height of the renderer. - * @param resolution The new resolution of the renderer. - */ - resize(width?: number, height?: number, resolution?: number): this; - - /** - * Checks if a WebGL extension is supported - * @param extensionName Name of the WebGL extension - */ - hasExtension(extensionName: string): boolean; - - /** - * Loads a WebGL extension - * @param extensionName The name of the extension to load. - */ - getExtension(extensionName: string): object; - - /** - * Flushes the current pipeline if the pipeline is bound - */ - flush(): void; - - /** - * Checks if a pipeline is present in the current WebGLRenderer - * @param pipelineName The name of the pipeline. - */ - hasPipeline(pipelineName: string): boolean; - - /** - * Returns the pipeline by name if the pipeline exists - * @param pipelineName The name of the pipeline. - */ - getPipeline(pipelineName: string): Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Removes a pipeline by name. - * @param pipelineName The name of the pipeline to be removed. - */ - removePipeline(pipelineName: string): this; - - /** - * Adds a pipeline instance into the collection of pipelines - * @param pipelineName A unique string-based key for the pipeline. - * @param pipelineInstance A pipeline instance which must extend WebGLPipeline. - */ - addPipeline(pipelineName: string, pipelineInstance: Phaser.Renderer.WebGL.WebGLPipeline): Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Pushes a new scissor state. This is used to set nested scissor states. - * @param x The x position of the scissor. - * @param y The y position of the scissor. - * @param width The width of the scissor. - * @param height The height of the scissor. - * @param drawingBufferHeight Optional drawingBufferHeight override value. - */ - pushScissor(x: integer, y: integer, width: integer, height: integer, drawingBufferHeight?: integer): integer[]; - - /** - * Sets the current scissor state. - * @param x The x position of the scissor. - * @param y The y position of the scissor. - * @param width The width of the scissor. - * @param height The height of the scissor. - * @param drawingBufferHeight Optional drawingBufferHeight override value. - */ - setScissor(x: integer, y: integer, width: integer, height: integer, drawingBufferHeight?: integer): void; - - /** - * Pops the last scissor state and sets it. - */ - popScissor(): void; - - /** - * Binds a WebGLPipeline and sets it as the current pipeline to be used. - * @param pipelineInstance The pipeline instance to be activated. - * @param gameObject The Game Object that invoked this pipeline, if any. - */ - setPipeline(pipelineInstance: Phaser.Renderer.WebGL.WebGLPipeline, gameObject?: Phaser.GameObjects.GameObject): Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Is there an active stencil mask? - */ - hasActiveStencilMask(): boolean; - - /** - * Use this to reset the gl context to the state that Phaser requires to continue rendering. - * Calling this will: - * - * * Disable `DEPTH_TEST`, `CULL_FACE` and `STENCIL_TEST`. - * * Clear the depth buffer and stencil buffers. - * * Reset the viewport size. - * * Reset the blend mode. - * * Bind a blank texture as the active texture on texture unit zero. - * * Rebinds the given pipeline instance. - * - * You should call this having previously called `clearPipeline` and then wishing to return - * control to Phaser again. - * @param pipelineInstance The pipeline instance to be activated. - */ - rebindPipeline(pipelineInstance: Phaser.Renderer.WebGL.WebGLPipeline): void; - - /** - * Flushes the current WebGLPipeline being used and then clears it, along with the - * the current shader program and vertex buffer. Then resets the blend mode to NORMAL. - * Call this before jumping to your own gl context handler, and then call `rebindPipeline` when - * you wish to return control to Phaser again. - */ - clearPipeline(): void; - - /** - * Sets the blend mode to the value given. - * - * If the current blend mode is different from the one given, the pipeline is flushed and the new - * blend mode is enabled. - * @param blendModeId The blend mode to be set. Can be a `BlendModes` const or an integer value. - * @param force Force the blend mode to be set, regardless of the currently set blend mode. Default false. - */ - setBlendMode(blendModeId: integer, force?: boolean): boolean; - - /** - * Creates a new custom blend mode for the renderer. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants#Blending_modes - * @param 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 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()}. - */ - addBlendMode(func: GLenum[], equation: GLenum): integer; - - /** - * Updates the function bound to a given custom blend mode. - * @param index The index of the custom blend mode. - * @param func The function to use for the blend mode. - * @param equation The equation to use for the blend mode. - */ - updateBlendMode(index: integer, func: Function, equation: Function): this; - - /** - * Removes a custom blend mode from the renderer. - * Any Game Objects still using this blend mode will error, so be sure to clear them first. - * @param index The index of the custom blend mode to be removed. - */ - removeBlendMode(index: integer): this; - - /** - * Binds a texture at a texture unit. If a texture is already - * bound to that unit it will force a flush on the current pipeline. - * @param texture The WebGL texture that needs to be bound. - * @param textureUnit The texture unit to which the texture will be bound. - * @param flush Will the current pipeline be flushed if this is a new texture, or not? Default true. - */ - setTexture2D(texture: WebGLTexture, textureUnit: integer, flush?: boolean): this; - - /** - * Binds a framebuffer. If there was another framebuffer already bound it will force a pipeline flush. - * @param framebuffer The framebuffer that needs to be bound. - * @param updateScissor If a framebuffer is given, set the gl scissor to match the frame buffer size? Or, if `null` given, pop the scissor from the stack. Default false. - */ - setFramebuffer(framebuffer: WebGLFramebuffer, updateScissor?: boolean): this; - - /** - * Binds a program. If there was another program already bound it will force a pipeline flush. - * @param program The program that needs to be bound. - */ - setProgram(program: WebGLProgram): this; - - /** - * Bounds a vertex buffer. If there is a vertex buffer already bound it'll force a pipeline flush. - * @param vertexBuffer The buffer that needs to be bound. - */ - setVertexBuffer(vertexBuffer: WebGLBuffer): this; - - /** - * Bounds a index buffer. If there is a index buffer already bound it'll force a pipeline flush. - * @param indexBuffer The buffer the needs to be bound. - */ - setIndexBuffer(indexBuffer: WebGLBuffer): this; - - /** - * Creates a texture from an image source. If the source is not valid it creates an empty texture. - * @param source The source of the texture. - * @param width The width of the texture. - * @param height The height of the texture. - * @param scaleMode The scale mode to be used by the texture. - */ - createTextureFromSource(source: object, width: integer, height: integer, scaleMode: integer): WebGLTexture; - - /** - * A wrapper for creating a WebGLTexture. If no pixel data is passed it will create an empty texture. - * @param mipLevel Mip level of the texture. - * @param minFilter Filtering of the texture. - * @param magFilter Filtering of the texture. - * @param wrapT Wrapping mode of the texture. - * @param wrapS Wrapping mode of the texture. - * @param format Which format does the texture use. - * @param pixels pixel data. - * @param width Width of the texture in pixels. - * @param height Height of the texture in pixels. - * @param pma Does the texture have premultiplied alpha? Default true. - * @param forceSize If `true` it will use the width and height passed to this method, regardless of the pixels dimension. Default false. - * @param flipY Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. Default false. - */ - createTexture2D(mipLevel: integer, minFilter: integer, magFilter: integer, wrapT: integer, wrapS: integer, format: integer, pixels: object, width: integer, height: integer, pma?: boolean, forceSize?: boolean, flipY?: boolean): WebGLTexture; - - /** - * Wrapper for creating WebGLFramebuffer. - * @param width Width in pixels of the framebuffer - * @param height Height in pixels of the framebuffer - * @param renderTexture The color texture to where the color pixels are written - * @param addDepthStencilBuffer Indicates if the current framebuffer support depth and stencil buffers - */ - createFramebuffer(width: integer, height: integer, renderTexture: WebGLTexture, addDepthStencilBuffer: boolean): WebGLFramebuffer; - - /** - * Wrapper for creating a WebGLProgram - * @param vertexShader Source to the vertex shader - * @param fragmentShader Source to the fragment shader - */ - createProgram(vertexShader: string, fragmentShader: string): WebGLProgram; - - /** - * Wrapper for creating a vertex buffer. - * @param initialDataOrSize It's either ArrayBuffer or an integer indicating the size of the vbo - * @param bufferUsage How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW - */ - createVertexBuffer(initialDataOrSize: ArrayBuffer, bufferUsage: integer): WebGLBuffer; - - /** - * Wrapper for creating a vertex buffer. - * @param initialDataOrSize Either ArrayBuffer or an integer indicating the size of the vbo. - * @param bufferUsage How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW. - */ - createIndexBuffer(initialDataOrSize: ArrayBuffer, bufferUsage: integer): WebGLBuffer; - - /** - * Removes the given texture from the nativeTextures array and then deletes it from the GPU. - * @param texture The WebGL Texture to be deleted. - */ - deleteTexture(texture: WebGLTexture): this; - - /** - * Deletes a WebGLFramebuffer from the GL instance. - * @param framebuffer The Framebuffer to be deleted. - */ - deleteFramebuffer(framebuffer: WebGLFramebuffer): this; - - /** - * Deletes a WebGLProgram from the GL instance. - * @param program The shader program to be deleted. - */ - deleteProgram(program: WebGLProgram): this; - - /** - * Deletes a WebGLBuffer from the GL instance. - * @param vertexBuffer The WebGLBuffer to be deleted. - */ - deleteBuffer(vertexBuffer: WebGLBuffer): this; - - /** - * Controls the pre-render operations for the given camera. - * Handles any clipping needed by the camera and renders the background color if a color is visible. - * @param camera The Camera to pre-render. - */ - preRenderCamera(camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * Controls the post-render operations for the given camera. - * Renders the foreground camera effects like flash and fading. It resets the current scissor state. - * @param camera The Camera to post-render. - */ - postRenderCamera(camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * Clears the current vertex buffer and updates pipelines. - */ - preRender(): void; - - /** - * The core render step for a Scene Camera. - * - * Iterates through the given Game Object's array and renders them with the given Camera. - * - * This is called by the `CameraManager.render` method. The Camera Manager instance belongs to a Scene, and is invoked - * by the Scene Systems.render method. - * - * This method is not called if `Camera.visible` is `false`, or `Camera.alpha` is zero. - * @param scene The Scene to render. - * @param children The Game Object's within the Scene to be rendered. - * @param interpolationPercentage The interpolation percentage to apply. Currently un-used. - * @param camera The Scene Camera to render with. - */ - render(scene: Phaser.Scene, children: Phaser.GameObjects.GameObject, interpolationPercentage: number, camera: Phaser.Cameras.Scene2D.Camera): void; - - /** - * The post-render step happens after all Cameras in all Scenes have been rendered. - */ - postRender(): void; - - /** - * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. - * - * To capture a specific area see the `snapshotArea` 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. - * @param callback The Function to invoke after the snapshot image is created. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshot(callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; - - /** - * 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. - * @param x The x coordinate to grab from. - * @param y The y coordinate to grab from. - * @param width The width of the area to grab. - * @param height The height of the area to grab. - * @param callback The Function to invoke after the snapshot image is created. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshotArea(x: integer, y: integer, width: integer, height: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; - - /** - * 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. - * @param x The x coordinate of the pixel to get. - * @param y The y coordinate of the pixel to get. - * @param callback The Function to invoke after the snapshot pixel data is extracted. - */ - snapshotPixel(x: integer, y: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback): this; - - /** - * 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. - * @param framebuffer The framebuffer to grab from. - * @param bufferWidth The width of the framebuffer. - * @param bufferHeight The height of the framebuffer. - * @param callback The Function to invoke after the snapshot image is created. - * @param getPixel Grab a single pixel as a Color object, or an area as an Image object? Default false. - * @param x The x coordinate to grab from. Default 0. - * @param y The y coordinate to grab from. Default 0. - * @param width The width of the area to grab. Default bufferWidth. - * @param height The height of the area to grab. Default bufferHeight. - * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. - * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. - */ - snapshotFramebuffer(framebuffer: WebGLFramebuffer, bufferWidth: integer, bufferHeight: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, getPixel?: boolean, x?: integer, y?: integer, width?: integer, height?: integer, type?: string, encoderOptions?: number): this; - - /** - * 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. - * @param srcCanvas The Canvas to create the WebGL Texture from - * @param dstTexture The destination WebGL Texture to set. - * @param noRepeat Should this canvas be allowed to set `REPEAT` (such as for Text objects?) Default false. - * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. - */ - canvasToTexture(srcCanvas: HTMLCanvasElement, dstTexture?: WebGLTexture, noRepeat?: boolean, flipY?: boolean): WebGLTexture; - - /** - * Creates a new WebGL Texture based on the given Canvas Element. - * @param srcCanvas The Canvas to create the WebGL Texture from - * @param noRepeat Should this canvas be allowed to set `REPEAT` (such as for Text objects?) Default false. - * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. - */ - createCanvasTexture(srcCanvas: HTMLCanvasElement, noRepeat?: boolean, flipY?: boolean): WebGLTexture; - - /** - * Updates a WebGL Texture based on the given Canvas Element. - * @param srcCanvas The Canvas to update the WebGL Texture from. - * @param dstTexture The destination WebGL Texture to update. - * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. - */ - updateCanvasTexture(srcCanvas: HTMLCanvasElement, dstTexture: WebGLTexture, flipY?: boolean): WebGLTexture; - - /** - * Creates a new WebGL Texture based on the given HTML Video Element. - * @param srcVideo The Video to create the WebGL Texture from - * @param noRepeat Should this canvas be allowed to set `REPEAT`? Default false. - * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. - */ - createVideoTexture(srcVideo: HTMLVideoElement, noRepeat?: boolean, flipY?: boolean): WebGLTexture; - - /** - * Updates a WebGL Texture based on the given HTML Video Element. - * @param srcVideo The Video to update the WebGL Texture with. - * @param dstTexture The destination WebGL Texture to update. - * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. - */ - updateVideoTexture(srcVideo: HTMLVideoElement, dstTexture: WebGLTexture, flipY?: boolean): WebGLTexture; - - /** - * Sets the minification and magnification filter for a texture. - * @param texture The texture to set the filter for. - * @param filter The filter to set. 0 for linear filtering, 1 for nearest neighbor (blocky) filtering. - */ - setTextureFilter(texture: integer, filter: integer): this; - - /** - * [description] - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x [description] - */ - setFloat1(program: WebGLProgram, name: string, x: number): this; - - /** - * [description] - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x [description] - * @param y [description] - */ - setFloat2(program: WebGLProgram, name: string, x: number, y: number): this; - - /** - * [description] - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x [description] - * @param y [description] - * @param z [description] - */ - setFloat3(program: WebGLProgram, name: string, x: number, y: number, z: number): this; - - /** - * Sets uniform of a WebGLProgram - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - */ - setFloat4(program: WebGLProgram, name: string, x: number, y: number, z: number, w: number): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat1v(program: WebGLProgram, name: string, arr: Float32Array): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat2v(program: WebGLProgram, name: string, arr: Float32Array): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat3v(program: WebGLProgram, name: string, arr: Float32Array): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param arr The new value to be used for the uniform variable. - */ - setFloat4v(program: WebGLProgram, name: string, arr: Float32Array): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x [description] - */ - setInt1(program: WebGLProgram, name: string, x: integer): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x The new X component - * @param y The new Y component - */ - setInt2(program: WebGLProgram, name: string, x: integer, y: integer): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x The new X component - * @param y The new Y component - * @param z The new Z component - */ - setInt3(program: WebGLProgram, name: string, x: integer, y: integer, z: integer): this; - - /** - * Sets the value of a uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - */ - setInt4(program: WebGLProgram, name: string, x: integer, y: integer, z: integer, w: integer): this; - - /** - * Sets the value of a 2x2 matrix uniform variable in the given WebGLProgram. - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param transpose The value indicating whether to transpose the matrix. Must be false. - * @param matrix The new matrix value. - */ - setMatrix2(program: WebGLProgram, name: string, transpose: boolean, matrix: Float32Array): this; - - /** - * [description] - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param transpose [description] - * @param matrix [description] - */ - setMatrix3(program: WebGLProgram, name: string, transpose: boolean, matrix: Float32Array): this; - - /** - * Sets uniform of a WebGLProgram - * @param program The target WebGLProgram from which the uniform location will be looked-up. - * @param name The name of the uniform to look-up and modify. - * @param transpose Is the matrix transposed - * @param matrix Matrix data - */ - setMatrix4(program: WebGLProgram, name: string, transpose: boolean, matrix: Float32Array): this; - - /** - * Returns the maximum number of texture units that can be used in a fragment shader. - */ - getMaxTextures(): integer; - - /** - * Returns the largest texture size (either width or height) that can be created. - * Note that VRAM may not allow a texture of any given size, it just expresses - * hardware / driver support for a given size. - */ - getMaxTextureSize(): integer; - - /** - * Destroy this WebGLRenderer, cleaning up all related resources such as pipelines, native textures, etc. - */ - destroy(): void; - - } - - } - - } - - /** - * Phaser Scale Modes. - */ - enum ScaleModes { - /** - * Default Scale Mode (Linear). - */ - DEFAULT, - /** - * Linear Scale Mode. - */ - LINEAR, - /** - * Nearest Scale Mode. - */ - NEAREST, - } - - namespace Scale { - /** - * Phaser Scale Manager constants for centering the game canvas. - */ - enum Center { - /** - * The game canvas is not centered within the parent by Phaser. - * You can still center it yourself via CSS. - */ - NO_CENTER, - /** - * The game canvas is centered both horizontally and vertically within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - */ - CENTER_BOTH, - /** - * The game canvas is centered horizontally within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - */ - CENTER_HORIZONTALLY, - /** - * The game canvas is centered both vertically within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - */ - CENTER_VERTICALLY, - } - - /** - * Phaser Scale Manager constants for centering the game canvas. - * - * To find out what each mode does please see [Phaser.Scale.Center]{@link Phaser.Scale.Center}. - */ - type CenterType = Phaser.Scale.Center; - - /** - * Phaser Scale Manager constants for orientation. - */ - enum Orientation { - /** - * A landscape orientation. - */ - LANDSCAPE, - /** - * A portrait orientation. - */ - PORTRAIT, - } - - /** - * Phaser Scale Manager constants for orientation. - * - * To find out what each mode does please see [Phaser.Scale.Orientation]{@link Phaser.Scale.Orientation}. - */ - type OrientationType = Phaser.Scale.Orientation; - - /** - * Phaser Scale Manager constants for the different scale modes available. - */ - enum ScaleModes { - /** - * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it - * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need - * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. - */ - NONE, - /** - * The height is automatically adjusted based on the width. - */ - WIDTH_CONTROLS_HEIGHT, - /** - * The width is automatically adjusted based on the height. - */ - HEIGHT_CONTROLS_WIDTH, - /** - * 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. - */ - FIT, - /** - * 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. - */ - ENVELOP, - /** - * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. - */ - RESIZE, - } - - /** - * Phaser Scale Manager constants for the different scale modes available. - * - * To find out what each mode does please see [Phaser.Scale.ScaleModes]{@link Phaser.Scale.ScaleModes}. - */ - type ScaleModeType = Phaser.Scale.ScaleModes; - - /** - * Phaser Scale Manager constants for zoom modes. - */ - enum Zoom { - /** - * The game canvas will not be zoomed by Phaser. - */ - NO_ZOOM, - /** - * The game canvas will be 2x zoomed by Phaser. - */ - ZOOM_2X, - /** - * The game canvas will be 4x zoomed by Phaser. - */ - ZOOM_4X, - /** - * 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. - */ - MAX_ZOOM, - } - - /** - * Phaser Scale Manager constants for zoom modes. - * - * To find out what each mode does please see [Phaser.Scale.Zoom]{@link Phaser.Scale.Zoom}. - */ - type ZoomType = Phaser.Scale.Zoom; - - namespace Events { - /** - * The Scale Manager has successfully entered fullscreen mode. - */ - const ENTER_FULLSCREEN: any; - - /** - * The Scale Manager tried to enter fullscreen mode but failed. - */ - const FULLSCREEN_FAILED: any; - - /** - * The Scale Manager tried to enter fullscreen mode, but it is unsupported by the browser. - */ - const FULLSCREEN_UNSUPPORTED: any; - - /** - * The Scale Manager was in fullscreen mode, but has since left, either directly via game code, - * or via a user gestured, such as pressing the ESC key. - */ - const LEAVE_FULLSCREEN: any; - - /** - * The Scale Manager Orientation Change Event. - */ - const ORIENTATION_CHANGE: any; - - /** - * The Scale Manager Resize Event. - * - * This event is dispatched whenever the Scale Manager detects a resize event from the browser. - * It sends three parameters to the callback, each of them being Size components. You can read - * the `width`, `height`, `aspectRatio` and other properties of these components to help with - * scaling your own game content. - */ - const RESIZE: any; - - } - - /** - * 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 extends Phaser.Events.EventEmitter { - /** - * - * @param game A reference to the Phaser.Game instance. - */ - constructor(game: Phaser.Game); - - /** - * A reference to the Phaser.Game instance. - */ - readonly game: Phaser.Game; - - /** - * A reference to the HTML Canvas Element that Phaser uses to render the game. - */ - canvas: HTMLCanvasElement; - - /** - * The DOM bounds of the canvas element. - */ - canvasBounds: Phaser.Geom.Rectangle; - - /** - * The parent object of the Canvas. Often a div, or the browser window, or nothing in non-browser environments. - * - * This is set in the Game Config as the `parent` property. If undefined (or just not present), it will default - * to use the document body. If specifically set to `null` Phaser will ignore all parent operations. - */ - parent: any; - - /** - * Is the parent element the browser window? - */ - parentIsWindow: boolean; - - /** - * The Parent Size component. - */ - parentSize: Phaser.Structs.Size; - - /** - * The Game Size component. - * - * The un-modified game size, as requested in the game config (the raw width / height), - * as used for world bounds, cameras, etc - */ - gameSize: Phaser.Structs.Size; - - /** - * The Base Size component. - * - * The modified game size, which is the gameSize * resolution, used to set the canvas width and height - * (but not the CSS style) - */ - baseSize: Phaser.Structs.Size; - - /** - * The Display Size component. - * - * The size used for the canvas style, factoring in the scale mode, parent and other values. - */ - displaySize: Phaser.Structs.Size; - - /** - * The game scale mode. - */ - scaleMode: Phaser.Scale.ScaleModeType; - - /** - * The canvas resolution. - * - * This is hard-coded to a value of 1 in the 3.16 release of Phaser and will be enabled at a later date. - */ - resolution: number; - - /** - * The game zoom factor. - * - * This value allows you to multiply your games base size by the given zoom factor. - * This is then used when calculating the display size, even in `NONE` situations. - * If you don't want Phaser to touch the canvas style at all, this value should be 1. - * - * Can also be set to `MAX_ZOOM` in which case the zoom value will be derived based - * on the game size and available space within the parent. - */ - zoom: number; - - /** - * Internal flag set when the game zoom factor is modified. - */ - readonly _resetZoom: boolean; - - /** - * The scale factor between the baseSize and the canvasBounds. - */ - displayScale: Phaser.Math.Vector2; - - /** - * If set, the canvas sizes will be automatically passed through Math.floor. - * This results in rounded pixel display values, which is important for performance on legacy - * and low powered devices, but at the cost of not achieving a 'perfect' fit in some browser windows. - */ - autoRound: boolean; - - /** - * Automatically center the canvas within the parent? The different centering modes are: - * - * 1. No centering. - * 2. Center both horizontally and vertically. - * 3. Center horizontally. - * 4. Center vertically. - * - * Please be aware that in order to center the game canvas, you must have specified a parent - * that has a size set, or the canvas parent is the document.body. - */ - autoCenter: Phaser.Scale.CenterType; - - /** - * The current device orientation. - * - * Orientation events are dispatched via the Device Orientation API, typically only on mobile browsers. - */ - orientation: Phaser.Scale.OrientationType; - - /** - * A reference to the Device.Fullscreen object. - */ - fullscreen: Phaser.Device.Fullscreen; - - /** - * The DOM Element which is sent into fullscreen mode. - */ - fullscreenTarget: any; - - /** - * The dirty state of the Scale Manager. - * Set if there is a change between the parent size and the current size. - */ - dirty: boolean; - - /** - * 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. - */ - resizeInterval: integer; - - /** - * Called _before_ the canvas object is created and added to the DOM. - */ - protected preBoot(): void; - - /** - * The Boot handler is called by Phaser.Game when it first starts up. - * The renderer is available by now and the canvas has been added to the DOM. - */ - protected boot(): void; - - /** - * Parses the game configuration to set-up the scale defaults. - * @param config The Game configuration object. - */ - protected parseConfig(config: Phaser.Types.Core.GameConfig): void; - - /** - * Determines the parent element of the game canvas, if any, based on the game configuration. - * @param config The Game configuration object. - */ - getParent(config: Phaser.Types.Core.GameConfig): void; - - /** - * Calculates the size of the parent bounds and updates the `parentSize` component, if the canvas has a dom parent. - */ - getParentBounds(): boolean; - - /** - * 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. - * @param orientation The orientation you'd like to lock the browser in. Should be an API string such as 'landscape', 'landscape-primary', 'portrait', etc. - */ - lockOrientation(orientation: string): boolean; - - /** - * This method will set the size of the Parent Size component, which is used in scaling - * and centering calculations. You only need to call this method if you have explicitly - * disabled the use of a parent in your game config, but still wish to take advantage of - * other Scale Manager features. - * @param width The new width of the parent. - * @param height The new height of the parent. - */ - setParentSize(width: number, height: number): this; - - /** - * This method will set a new size for your game. - * - * It should only be used if you're looking to change the base size of your game and are using - * one of the Scale Manager scaling modes, i.e. `FIT`. If you're using `NONE` and wish to - * change the game and canvas size directly, then please use the `resize` method instead. - * @param width The new width of the game. - * @param height The new height of the game. - */ - setGameSize(width: number, height: number): this; - - /** - * 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. - * @param width The new width of the game. - * @param height The new height of the game. - */ - resize(width: number, height: number): this; - - /** - * Sets the zoom value of the Scale Manager. - * @param value The new zoom value of the game. - */ - setZoom(value: integer): this; - - /** - * Sets the zoom to be the maximum possible based on the _current_ parent size. - */ - setMaxZoom(): this; - - /** - * Refreshes the internal scale values, bounds sizes and orientation checks. - * - * Once finished, dispatches the resize event. - * - * This is called automatically by the Scale Manager when the browser window size changes, - * as long as it is using a Scale Mode other than 'NONE'. - * @param previousWidth The previous width of the game. Only set if the gameSize has changed. - * @param previousHeight The previous height of the game. Only set if the gameSize has changed. - */ - refresh(previousWidth?: number, previousHeight?: number): this; - - /** - * Internal method that checks the current screen orientation, only if the internal check flag is set. - * - * If the orientation has changed it updates the orientation property and then dispatches the orientation change event. - */ - updateOrientation(): void; - - /** - * Internal method that manages updating the size components based on the scale mode. - */ - updateScale(): void; - - /** - * 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) - */ - getMaxZoom(): integer; - - /** - * Calculates and updates the canvas CSS style in order to center it within the - * bounds of its parent. If you have explicitly set parent to be `null` in your - * game config then this method will likely give incorrect results unless you have called the - * `setParentSize` method first. - * - * It works by modifying the canvas CSS `marginLeft` and `marginTop` properties. - * - * If they have already been set by your own style sheet, or code, this will overwrite them. - * - * To prevent the Scale Manager from centering the canvas, either do not set the - * `autoCenter` property in your game config, or make sure it is set to `NO_CENTER`. - */ - updateCenter(): void; - - /** - * Updates the `canvasBounds` rectangle to match the bounding client rectangle of the - * canvas element being used to track input events. - */ - updateBounds(): void; - - /** - * Transforms the pageX value into the scaled coordinate space of the Scale Manager. - * @param pageX The DOM pageX value. - */ - transformX(pageX: number): number; - - /** - * Transforms the pageY value into the scaled coordinate space of the Scale Manager. - * @param pageY The DOM pageY value. - */ - transformY(pageY: number): number; - - /** - * 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 user-input gesture, such as `pointerup`. 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 `
` element and move the canvas into it, before going fullscreen. - * When it leaves fullscreen, the div will be removed. - * @param fullscreenOptions The FullscreenOptions dictionary is used to provide configuration options when entering full screen. - */ - startFullscreen(fullscreenOptions?: object): void; - - /** - * An internal method that gets the target element that is used when entering fullscreen mode. - */ - getFullscreenTarget(): object; - - /** - * Removes the fullscreen target that was added to the DOM. - */ - removeFullscreenTarget(): void; - - /** - * Calling this method will cancel fullscreen mode, if the browser has entered it. - */ - stopFullscreen(): void; - - /** - * Toggles the fullscreen mode. If already in fullscreen, calling this will cancel it. - * If not in fullscreen, this will request the browser to enter fullscreen mode. - * - * If the browser does not support this, a `FULLSCREEN_UNSUPPORTED` event will be emitted. - * - * This method _must_ be called from a user-input gesture, such as `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. - * @param fullscreenOptions The FullscreenOptions dictionary is used to provide configuration options when entering full screen. - */ - toggleFullscreen(fullscreenOptions?: object): void; - - /** - * An internal method that starts the different DOM event listeners running. - */ - startListeners(): void; - - /** - * Triggered when a fullscreenchange event is dispatched by the DOM. - */ - onFullScreenChange(): void; - - /** - * Triggered when a fullscreenerror event is dispatched by the DOM. - */ - onFullScreenError(): void; - - /** - * Internal method, called automatically by the game step. - * Monitors the elapsed time and resize interval to see if a parent bounds check needs to take place. - * @param time The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). - * @param delta The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. - */ - step(time: number, delta: number): void; - - /** - * Stops all DOM event listeners. - */ - stopListeners(): void; - - /** - * Destroys this Scale Manager, releasing all references to external resources. - * Once destroyed, the Scale Manager cannot be used again. - */ - destroy(): void; - - /** - * Is the browser currently in fullscreen mode or not? - */ - readonly isFullscreen: boolean; - - /** - * The game width. - * - * This is typically the size given in the game configuration. - */ - readonly width: number; - - /** - * The game height. - * - * This is typically the size given in the game configuration. - */ - readonly height: number; - - /** - * Is the device in a portrait orientation as reported by the Orientation API? - * This value is usually only available on mobile devices. - */ - readonly isPortrait: boolean; - - /** - * Is the device in a landscape orientation as reported by the Orientation API? - * This value is usually only available on mobile devices. - */ - readonly isLandscape: boolean; - - /** - * Are the game dimensions portrait? (i.e. taller than they are wide) - * - * This is different to the device itself being in a portrait orientation. - */ - readonly isGamePortrait: boolean; - - /** - * Are the game dimensions landscape? (i.e. wider than they are tall) - * - * This is different to the device itself being in a landscape orientation. - */ - readonly isGameLandscape: boolean; - - } - - /** - * The game canvas is not centered within the parent by Phaser. - * You can still center it yourself via CSS. - */ - const NO_CENTER: integer; - - /** - * The game canvas is centered both horizontally and vertically within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - */ - const CENTER_BOTH: integer; - - /** - * The game canvas is centered horizontally within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - */ - const CENTER_HORIZONTALLY: integer; - - /** - * The game canvas is centered both vertically within the parent. - * To do this, the parent has to have a bounds that can be calculated and not be empty. - * - * Centering is achieved by setting the margin left and top properties of the - * game canvas, and does not factor in any other CSS styles you may have applied. - */ - const CENTER_VERTICALLY: integer; - - /** - * A landscape orientation. - */ - const LANDSCAPE: string; - - /** - * A portrait orientation. - */ - const PORTRAIT: string; - - /** - * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it - * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need - * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. - */ - const NONE: integer; - - /** - * The height is automatically adjusted based on the width. - */ - const WIDTH_CONTROLS_HEIGHT: integer; - - /** - * The width is automatically adjusted based on the height. - */ - const HEIGHT_CONTROLS_WIDTH: integer; - - /** - * 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. - */ - const FIT: integer; - - /** - * 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. - */ - const ENVELOP: integer; - - /** - * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. - */ - const RESIZE: integer; - - /** - * The game canvas will not be zoomed by Phaser. - */ - const NO_ZOOM: integer; - - /** - * The game canvas will be 2x zoomed by Phaser. - */ - const ZOOM_2X: integer; - - /** - * The game canvas will be 4x zoomed by Phaser. - */ - const ZOOM_4X: integer; - - /** - * 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. - */ - const MAX_ZOOM: integer; - - } - - namespace Scenes { - /** - * Scene state. - */ - var PENDING: integer; - - /** - * Scene state. - */ - var INIT: integer; - - /** - * Scene state. - */ - var START: integer; - - /** - * Scene state. - */ - var LOADING: integer; - - /** - * Scene state. - */ - var CREATING: integer; - - /** - * Scene state. - */ - var RUNNING: integer; - - /** - * Scene state. - */ - var PAUSED: integer; - - /** - * Scene state. - */ - var SLEEPING: integer; - - /** - * Scene state. - */ - var SHUTDOWN: integer; - - /** - * Scene state. - */ - var DESTROYED: integer; - - namespace Events { - /** - * The Scene Systems Boot Event. - * - * This event is dispatched by a Scene during the Scene Systems boot process. Primarily used by Scene Plugins. - * - * Listen to it from a Scene using `this.scene.events.on('boot', listener)`. - */ - const BOOT: any; - - /** - * The Scene Create Event. - * - * This event is dispatched by a Scene after it has been created by the Scene Manager. - * - * If a Scene has a `create` method then this event is emitted _after_ that has run. - * - * If there is a transition, this event will be fired after the `TRANSITION_START` event. - * - * Listen to it from a Scene using `this.scene.events.on('create', listener)`. - */ - const CREATE: any; - - /** - * The Scene Systems Destroy Event. - * - * This event is dispatched by a Scene during the Scene Systems destroy process. - * - * Listen to it from a Scene using `this.scene.events.on('destroy', listener)`. - * - * You should destroy any resources that may be in use by your Scene in this event handler. - */ - const DESTROY: any; - - /** - * The Scene Systems Pause Event. - * - * This event is dispatched by a Scene when it is paused, either directly via the `pause` method, or as an - * action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('pause', listener)`. - */ - const PAUSE: any; - - /** - * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('postupdate', listener)`. - * - * A Scene will only run its step if it is active. - */ - const POST_UPDATE: any; - - /** - * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('preupdate', listener)`. - * - * A Scene will only run its step if it is active. - */ - const PRE_UPDATE: any; - - /** - * The Scene Systems Ready Event. - * - * This event is dispatched by a Scene during the Scene Systems start process. - * By this point in the process the Scene is now fully active and rendering. - * This event is meant for your game code to use, as all plugins have responded to the earlier 'start' event. - * - * Listen to it from a Scene using `this.scene.events.on('ready', listener)`. - */ - const READY: any; - - /** - * The Scene Systems Render 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('render', listener)`. - * - * A Scene will only render if it is visible and active. - * By the time this event is dispatched, the Scene will have already been rendered. - */ - const RENDER: any; - - /** - * The Scene Systems Resume Event. - * - * This event is dispatched by a Scene when it is resumed from a paused state, either directly via the `resume` method, - * or as an action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('resume', listener)`. - */ - const RESUME: any; - - /** - * The Scene Systems Shutdown Event. - * - * This event is dispatched by a Scene during the Scene Systems shutdown process. - * - * Listen to it from a Scene using `this.scene.events.on('shutdown', listener)`. - * - * You should free-up any resources that may be in use by your Scene in this event handler, on the understanding - * that the Scene may, at any time, become active again. A shutdown Scene is not 'destroyed', it's simply not - * currently active. Use the [DESTROY]{@linkcode Phaser.Scenes.Events#event:DESTROY} event to completely clear resources. - */ - const SHUTDOWN: any; - - /** - * The Scene Systems Sleep Event. - * - * This event is dispatched by a Scene when it is sent to sleep, either directly via the `sleep` method, - * or as an action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('sleep', listener)`. - */ - const SLEEP: any; - - /** - * The Scene Systems Start Event. - * - * This event is dispatched by a Scene during the Scene Systems start process. Primarily used by Scene Plugins. - * - * Listen to it from a Scene using `this.scene.events.on('start', listener)`. - */ - const START: any; - - /** - * The Scene Transition Complete Event. - * - * This event is dispatched by the Target Scene of a transition. - * - * It happens when the transition process has completed. This occurs when the duration timer equals or exceeds the duration - * of the transition. - * - * Listen to it from a Scene using `this.scene.events.on('transitioncomplete', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - */ - const TRANSITION_COMPLETE: any; - - /** - * The Scene Transition Init Event. - * - * This event is dispatched by the Target Scene of a transition. - * - * It happens immediately after the `Scene.init` method is called. If the Scene does not have an `init` method, - * this event is not dispatched. - * - * Listen to it from a Scene using `this.scene.events.on('transitioninit', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - */ - const TRANSITION_INIT: any; - - /** - * The Scene Transition Out Event. - * - * This event is dispatched by a Scene when it initiates a transition to another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('transitionout', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - */ - const TRANSITION_OUT: any; - - /** - * The Scene Transition Start Event. - * - * This event is dispatched by the Target Scene of a transition, only if that Scene was not asleep. - * - * It happens immediately after the `Scene.create` method is called. If the Scene does not have a `create` method, - * this event is dispatched anyway. - * - * If the Target Scene was sleeping then the [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} event is - * dispatched instead of this event. - * - * Listen to it from a Scene using `this.scene.events.on('transitionstart', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - */ - const TRANSITION_START: any; - - /** - * The Scene Transition Wake Event. - * - * This event is dispatched by the Target Scene of a transition, only if that Scene was asleep before - * the transition began. If the Scene was not asleep the [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} event is dispatched instead. - * - * Listen to it from a Scene using `this.scene.events.on('transitionwake', listener)`. - * - * The Scene Transition event flow is as follows: - * - * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. - * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. - * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... - * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. - * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. - */ - const TRANSITION_WAKE: any; - - /** - * 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 - * 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE} - * 5. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} - * - * Listen to it from a Scene using `this.scene.events.on('update', listener)`. - * - * A Scene will only run its step if it is active. - */ - const UPDATE: any; - - /** - * The Scene Systems Wake Event. - * - * This event is dispatched by a Scene when it is woken from sleep, either directly via the `wake` method, - * or as an action from another Scene. - * - * Listen to it from a Scene using `this.scene.events.on('wake', listener)`. - */ - const WAKE: any; - - } - - /** - * Builds an array of which physics plugins should be activated for the given Scene. - * @param sys The scene system to get the physics systems of. - */ - function GetPhysicsPlugins(sys: Phaser.Scenes.Systems): any[]; - - /** - * Builds an array of which plugins (not including physics plugins) should be activated for the given Scene. - * @param sys The Scene Systems object to check for plugins. - */ - function GetScenePlugins(sys: Phaser.Scenes.Systems): any[]; - - /** - * The Scene Manager. - * - * The Scene Manager is a Game level system, responsible for creating, processing and updating all of the - * Scenes in a Game instance. - */ - class SceneManager { - /** - * - * @param game The Phaser.Game instance this Scene Manager belongs to. - * @param sceneConfig Scene specific configuration settings. - */ - constructor(game: Phaser.Game, sceneConfig: object); - - /** - * The Game that this SceneManager belongs to. - */ - game: Phaser.Game; - - /** - * An object that maps the keys to the scene so we can quickly get a scene from a key without iteration. - */ - keys: object; - - /** - * The array in which all of the scenes are kept. - */ - scenes: any[]; - - /** - * Is the Scene Manager actively processing the Scenes list? - */ - readonly isProcessing: boolean; - - /** - * Has the Scene Manager properly started? - */ - readonly isBooted: boolean; - - /** - * Do any of the Cameras in any of the Scenes require a custom viewport? - * If not we can skip scissor tests. - */ - customViewports: number; - - /** - * Process the Scene operations queue. - */ - processQueue(): void; - - /** - * Adds a new Scene into the SceneManager. - * You must give each Scene a unique key by which you'll identify it. - * - * The `sceneConfig` can be: - * - * * A `Phaser.Scene` object, or an object that extends it. - * * A plain JavaScript object - * * A JavaScript ES6 Class that extends `Phaser.Scene` - * * A JavaScript ES5 prototype based Class - * * A JavaScript function - * - * If a function is given then a new Scene will be created by calling it. - * @param key A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. - * @param sceneConfig The config for the Scene - * @param autoStart If `true` the Scene will be started immediately after being added. Default false. - * @param data Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. - */ - add(key: string, sceneConfig: Phaser.Scene | Phaser.Types.Scenes.SettingsConfig | Phaser.Types.Scenes.CreateSceneFromObjectConfig | Function, autoStart?: boolean, data?: object): Phaser.Scene; - - /** - * Removes a Scene from the SceneManager. - * - * The Scene is removed from the local scenes array, it's key is cleared from the keys - * cache and Scene.Systems.destroy is then called on it. - * - * If the SceneManager is processing the Scenes when this method is called it will - * queue the operation for the next update sequence. - * @param key A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. - */ - remove(key: string): Phaser.Scenes.SceneManager; - - /** - * Updates the Scenes. - * @param time Time elapsed. - * @param delta Delta time from the last update. - */ - update(time: number, delta: number): void; - - /** - * Renders the Scenes. - * @param renderer The renderer to use. - */ - render(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; - - /** - * Returns an array of all the current Scenes being managed by this Scene Manager. - * - * You can filter the output by the active state of the Scene and choose to have - * the array returned in normal or reversed order. - * @param isActive Only include Scene's that are currently active? Default true. - * @param inReverse Return the array of Scenes in reverse? Default false. - */ - getScenes(isActive?: boolean, inReverse?: boolean): Phaser.Scene[]; - - /** - * Retrieves a Scene. - * @param key The Scene to retrieve. - */ - getScene(key: string | Phaser.Scene): Phaser.Scene; - - /** - * Determines whether a Scene is running. - * @param key The Scene to check. - */ - isActive(key: string): boolean; - - /** - * Determines whether a Scene is paused. - * @param key The Scene to check. - */ - isPaused(key: string): boolean; - - /** - * Determines whether a Scene is visible. - * @param key The Scene to check. - */ - isVisible(key: string): boolean; - - /** - * Determines whether a Scene is sleeping. - * @param key The Scene to check. - */ - isSleeping(key: string): boolean; - - /** - * Pauses the given Scene. - * @param key The Scene to pause. - * @param data An optional data object that will be passed to the Scene and emitted by its pause event. - */ - pause(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Resumes the given Scene. - * @param key The Scene to resume. - * @param data An optional data object that will be passed to the Scene and emitted by its resume event. - */ - resume(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Puts the given Scene to sleep. - * @param key The Scene to put to sleep. - * @param data An optional data object that will be passed to the Scene and emitted by its sleep event. - */ - sleep(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Awakens the given Scene. - * @param key The Scene to wake up. - * @param data An optional data object that will be passed to the Scene and emitted by its wake event. - */ - wake(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Runs the given Scene. - * - * If the given Scene is paused, it will resume it. If sleeping, it will wake it. - * If not running at all, it will be started. - * - * Use this if you wish to open a modal Scene by calling `pause` on the current - * Scene, then `run` on the modal Scene. - * @param key The Scene to run. - * @param data A data object that will be passed to the Scene on start, wake, or resume. - */ - run(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Starts the given Scene. - * @param key The Scene to start. - * @param data Optional data object to pass to Scene.Settings and Scene.init. - */ - start(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Stops the given Scene. - * @param key The Scene to stop. - * @param data Optional data object to pass to Scene.shutdown. - */ - stop(key: string, data?: object): Phaser.Scenes.SceneManager; - - /** - * Sleeps one one Scene and starts the other. - * @param from The Scene to sleep. - * @param to The Scene to start. - */ - switch(from: string, to: string): Phaser.Scenes.SceneManager; - - /** - * Retrieves a Scene by numeric index. - * @param index The index of the Scene to retrieve. - */ - getAt(index: integer): Phaser.Scene | undefined; - - /** - * Retrieves the numeric index of a Scene. - * @param key The key of the Scene. - */ - getIndex(key: string | Phaser.Scene): integer; - - /** - * Brings a Scene to the top of the Scenes list. - * - * This means it will render above all other Scenes. - * @param key The Scene to move. - */ - bringToTop(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Sends a Scene to the back of the Scenes list. - * - * This means it will render below all other Scenes. - * @param key The Scene to move. - */ - sendToBack(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Moves a Scene down one position in the Scenes list. - * @param key The Scene to move. - */ - moveDown(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Moves a Scene up one position in the Scenes list. - * @param key The Scene to move. - */ - moveUp(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Moves a Scene so it is immediately above another Scene in the Scenes list. - * - * This means it will render over the top of the other Scene. - * @param keyA The Scene that Scene B will be moved above. - * @param keyB The Scene to be moved. - */ - moveAbove(keyA: string | Phaser.Scene, keyB: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Moves a Scene so it is immediately below another Scene in the Scenes list. - * - * This means it will render behind the other Scene. - * @param keyA The Scene that Scene B will be moved above. - * @param keyB The Scene to be moved. - */ - moveBelow(keyA: string | Phaser.Scene, keyB: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Swaps the positions of two Scenes in the Scenes list. - * @param keyA The first Scene to swap. - * @param keyB The second Scene to swap. - */ - swapPosition(keyA: string | Phaser.Scene, keyB: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Dumps debug information about each Scene to the developer console. - */ - dump(): void; - - /** - * Destroy the SceneManager and all of its Scene's systems. - */ - destroy(): void; - - } - - /** - * A proxy class to the Global Scene Manager. - */ - class ScenePlugin { - /** - * - * @param scene The Scene that this ScenePlugin belongs to. - */ - constructor(scene: Phaser.Scene); - - /** - * The Scene that this ScenePlugin belongs to. - */ - scene: Phaser.Scene; - - /** - * The Scene Systems instance of the Scene that this ScenePlugin belongs to. - */ - systems: Phaser.Scenes.Systems; - - /** - * The settings of the Scene this ScenePlugin belongs to. - */ - settings: Phaser.Types.Scenes.SettingsObject; - - /** - * The key of the Scene this ScenePlugin belongs to. - */ - key: string; - - /** - * The Game's SceneManager. - */ - manager: Phaser.Scenes.SceneManager; - - /** - * If this Scene is currently transitioning to another, this holds - * the current percentage of the transition progress, between 0 and 1. - */ - transitionProgress: number; - - /** - * Shutdown this Scene and run the given one. - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to start. - * @param data The Scene data. - */ - start(key?: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Restarts this Scene. - * - * This will happen at the next Scene Manager update, not immediately. - * @param data The Scene data. - */ - restart(data?: object): Phaser.Scenes.ScenePlugin; - - /** - * This will start a transition from the current Scene to the target Scene given. - * - * The transition will last for the duration specified in milliseconds. - * - * You can have the target Scene moved above or below this one in the display list. - * - * You can specify an update callback. This callback will be invoked _every frame_ for the duration - * of the transition. - * - * This Scene can either be sent to sleep at the end of the transition, or stopped. The default is to stop. - * - * There are also 5 transition related events: This scene will emit the event `transitionout` when - * the transition begins, which is typically the frame after calling this method. - * - * The target Scene will emit the event `transitioninit` when that Scene's `init` method is called. - * It will then emit the event `transitionstart` when its `create` method is called. - * If the Scene was sleeping and has been woken up, it will emit the event `transitionwake` instead of these two, - * as the Scenes `init` and `create` methods are not invoked when a Scene wakes up. - * - * When the duration of the transition has elapsed it will emit the event `transitioncomplete`. - * These events are cleared of all listeners when the Scene shuts down, but not if it is sent to sleep. - * - * It's important to understand that the duration of the transition begins the moment you call this method. - * If the Scene you are transitioning to includes delayed processes, such as waiting for files to load, the - * time still counts down even while that is happening. If the game itself pauses, or something else causes - * this Scenes update loop to stop, then the transition will also pause for that duration. There are - * checks in place to prevent you accidentally stopping a transitioning Scene but if you've got code to - * override this understand that until the target Scene completes it might never be unlocked for input events. - * @param config The transition configuration object. - */ - transition(config: Phaser.Types.Scenes.SceneTransitionConfig): boolean; - - /** - * Add the Scene into the Scene Manager and start it if 'autoStart' is true or the Scene config 'active' property is set. - * @param key The Scene key. - * @param sceneConfig The config for the Scene. - * @param autoStart Whether to start the Scene after it's added. - * @param data Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. - */ - add(key: string, sceneConfig: Phaser.Scene | Phaser.Types.Scenes.SettingsConfig | Phaser.Types.Scenes.CreateSceneFromObjectConfig | Function, autoStart: boolean, data?: object): Phaser.Scene; - - /** - * Launch the given Scene and run it in parallel with this one. - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to launch. - * @param data The Scene data. - */ - launch(key: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Runs the given Scene, but does not change the state of this Scene. - * - * This will happen at the next Scene Manager update, not immediately. - * - * If the given Scene is paused, it will resume it. If sleeping, it will wake it. - * If not running at all, it will be started. - * - * Use this if you wish to open a modal Scene by calling `pause` on the current - * Scene, then `run` on the modal Scene. - * @param key The Scene to run. - * @param data A data object that will be passed to the Scene and emitted in its ready, wake, or resume events. - */ - run(key: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Pause the Scene - this stops the update step from happening but it still renders. - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to pause. - * @param data An optional data object that will be passed to the Scene and emitted in its pause event. - */ - pause(key?: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Resume the Scene - starts the update loop again. - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to resume. - * @param data An optional data object that will be passed to the Scene and emitted in its resume event. - */ - resume(key?: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Makes the Scene sleep (no update, no render) but doesn't shutdown. - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to put to sleep. - * @param data An optional data object that will be passed to the Scene and emitted in its sleep event. - */ - sleep(key?: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Makes the Scene wake-up (starts update and render) - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to wake up. - * @param data An optional data object that will be passed to the Scene and emitted in its wake event. - */ - wake(key?: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Makes this Scene sleep then starts the Scene given. - * - * This will happen at the next Scene Manager update, not immediately. - * @param key The Scene to start. - */ - switch(key: string): Phaser.Scenes.ScenePlugin; - - /** - * Shutdown the Scene, clearing display list, timers, etc. - * - * This happens at the next Scene Manager update, not immediately. - * @param key The Scene to stop. - * @param data Optional data object to pass to Scene.Systems.shutdown. - */ - stop(key?: string, data?: any): Phaser.Scenes.ScenePlugin; - - /** - * Sets the active state of the given Scene. - * @param value If `true` the Scene will be resumed. If `false` it will be paused. - * @param key The Scene to set the active state of. - * @param data An optional data object that will be passed to the Scene and emitted with its events. - */ - setActive(value: boolean, key?: string, data?: object): Phaser.Scenes.ScenePlugin; - - /** - * Sets the visible state of the given Scene. - * @param value The visible value. - * @param key The Scene to set the visible state for. - */ - setVisible(value: boolean, key?: string): Phaser.Scenes.ScenePlugin; - - /** - * Checks if the given Scene is sleeping or not? - * @param key The Scene to check. - */ - isSleeping(key?: string): boolean; - - /** - * Checks if the given Scene is running or not? - * @param key The Scene to check. - */ - isActive(key?: string): boolean; - - /** - * Checks if the given Scene is paused or not? - * @param key The Scene to check. - */ - isPaused(key?: string): boolean; - - /** - * Checks if the given Scene is visible or not? - * @param key The Scene to check. - */ - isVisible(key?: string): boolean; - - /** - * Swaps the position of two scenes in the Scenes list. - * - * This controls the order in which they are rendered and updated. - * @param keyA The first Scene to swap. - * @param keyB The second Scene to swap. If none is given it defaults to this Scene. - */ - swapPosition(keyA: string, keyB?: string): Phaser.Scenes.ScenePlugin; - - /** - * Swaps the position of two scenes in the Scenes list, so that Scene B is directly above Scene A. - * - * This controls the order in which they are rendered and updated. - * @param keyA The Scene that Scene B will be moved to be above. - * @param keyB The Scene to be moved. If none is given it defaults to this Scene. - */ - moveAbove(keyA: string, keyB?: string): Phaser.Scenes.ScenePlugin; - - /** - * Swaps the position of two scenes in the Scenes list, so that Scene B is directly below Scene A. - * - * This controls the order in which they are rendered and updated. - * @param keyA The Scene that Scene B will be moved to be below. - * @param keyB The Scene to be moved. If none is given it defaults to this Scene. - */ - moveBelow(keyA: string, keyB?: string): Phaser.Scenes.ScenePlugin; - - /** - * Removes a Scene from the SceneManager. - * - * The Scene is removed from the local scenes array, it's key is cleared from the keys - * cache and Scene.Systems.destroy is then called on it. - * - * If the SceneManager is processing the Scenes when this method is called it will - * queue the operation for the next update sequence. - * @param key The Scene to be removed. - */ - remove(key?: string | Phaser.Scene): Phaser.Scenes.SceneManager; - - /** - * Moves a Scene up one position in the Scenes list. - * @param key The Scene to move. - */ - moveUp(key?: string): Phaser.Scenes.ScenePlugin; - - /** - * Moves a Scene down one position in the Scenes list. - * @param key The Scene to move. - */ - moveDown(key?: string): Phaser.Scenes.ScenePlugin; - - /** - * Brings a Scene to the top of the Scenes list. - * - * This means it will render above all other Scenes. - * @param key The Scene to move. - */ - bringToTop(key?: string): Phaser.Scenes.ScenePlugin; - - /** - * Sends a Scene to the back of the Scenes list. - * - * This means it will render below all other Scenes. - * @param key The Scene to move. - */ - sendToBack(key?: string): Phaser.Scenes.ScenePlugin; - - /** - * Retrieve a Scene. - * @param key The Scene to retrieve. - */ - get(key: string): Phaser.Scene; - - /** - * Retrieves the numeric index of a Scene in the Scenes list. - * @param key The Scene to get the index of. - */ - getIndex(key?: string | Phaser.Scene): integer; - - } - - namespace Settings { - /** - * Takes a Scene configuration object and returns a fully formed System Settings object. - * @param config The Scene configuration object used to create this Scene Settings. - */ - function create(config: string | Phaser.Types.Scenes.SettingsConfig): Phaser.Types.Scenes.SettingsObject; - - } - - /** - * The Scene Systems class. - * - * This class is available from within a Scene under the property `sys`. - * It is responsible for managing all of the plugins a Scene has running, including the display list, and - * handling the update step and renderer. It also contains references to global systems belonging to Game. - */ - class Systems { - /** - * - * @param scene The Scene that owns this Systems instance. - * @param config Scene specific configuration settings. - */ - constructor(scene: Phaser.Scene, config: string | Phaser.Types.Scenes.SettingsConfig); - - /** - * A reference to the Scene that these Systems belong to. - */ - scene: Phaser.Scene; - - /** - * A reference to the Phaser Game instance. - */ - game: Phaser.Game; - - /** - * A reference to either the Canvas or WebGL Renderer that this Game is using. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * The Facebook Instant Games Plugin. - */ - facebook: Phaser.FacebookInstantGamesPlugin; - - /** - * The Scene Configuration object, as passed in when creating the Scene. - */ - config: string | Phaser.Types.Scenes.SettingsConfig; - - /** - * The Scene Settings. This is the parsed output based on the Scene configuration. - */ - settings: Phaser.Types.Scenes.SettingsObject; - - /** - * A handy reference to the Scene canvas / context. - */ - canvas: HTMLCanvasElement; - - /** - * A reference to the Canvas Rendering Context being used by the renderer. - */ - context: CanvasRenderingContext2D; - - /** - * A reference to the global Animations Manager. - * - * In the default set-up you can access this from within a Scene via the `this.anims` property. - */ - anims: Phaser.Animations.AnimationManager; - - /** - * A reference to the global Cache. The Cache stores all files bought in to Phaser via - * the Loader, with the exception of images. Images are stored in the Texture Manager. - * - * In the default set-up you can access this from within a Scene via the `this.cache` property. - */ - cache: Phaser.Cache.CacheManager; - - /** - * A reference to the global Plugins Manager. - * - * In the default set-up you can access this from within a Scene via the `this.plugins` property. - */ - plugins: Phaser.Plugins.PluginManager; - - /** - * A reference to the global registry. This is a game-wide instance of the Data Manager, allowing - * you to exchange data between Scenes via a universal and shared point. - * - * In the default set-up you can access this from within a Scene via the `this.registry` property. - */ - registry: Phaser.Data.DataManager; - - /** - * A reference to the global Scale Manager. - * - * In the default set-up you can access this from within a Scene via the `this.scale` property. - */ - scale: Phaser.Scale.ScaleManager; - - /** - * A reference to the global Sound Manager. - * - * In the default set-up you can access this from within a Scene via the `this.sound` property. - */ - sound: Phaser.Sound.NoAudioSoundManager | Phaser.Sound.HTML5AudioSoundManager | Phaser.Sound.WebAudioSoundManager; - - /** - * A reference to the global Texture Manager. - * - * In the default set-up you can access this from within a Scene via the `this.textures` property. - */ - textures: Phaser.Textures.TextureManager; - - /** - * A reference to the Scene's Game Object Factory. - * - * Use this to quickly and easily create new Game Object's. - * - * In the default set-up you can access this from within a Scene via the `this.add` property. - */ - add: Phaser.GameObjects.GameObjectFactory; - - /** - * A reference to the Scene's Camera Manager. - * - * Use this to manipulate and create Cameras for this specific Scene. - * - * In the default set-up you can access this from within a Scene via the `this.cameras` property. - */ - cameras: Phaser.Cameras.Scene2D.CameraManager; - - /** - * A reference to the Scene's Display List. - * - * Use this to organize the children contained in the display list. - * - * In the default set-up you can access this from within a Scene via the `this.children` property. - */ - displayList: Phaser.GameObjects.DisplayList; - - /** - * A reference to the Scene's Event Manager. - * - * Use this to listen for Scene specific events, such as `pause` and `shutdown`. - * - * In the default set-up you can access this from within a Scene via the `this.events` property. - */ - events: Phaser.Events.EventEmitter; - - /** - * A reference to the Scene's Game Object Creator. - * - * Use this to quickly and easily create new Game Object's. The difference between this and the - * Game Object Factory, is that the Creator just creates and returns Game Object instances, it - * doesn't then add them to the Display List or Update List. - * - * In the default set-up you can access this from within a Scene via the `this.make` property. - */ - make: Phaser.GameObjects.GameObjectCreator; - - /** - * A reference to the Scene Manager Plugin. - * - * Use this to manipulate both this and other Scene's in your game, for example to launch a parallel Scene, - * or pause or resume a Scene, or switch from this Scene to another. - * - * In the default set-up you can access this from within a Scene via the `this.scene` property. - */ - scenePlugin: Phaser.Scenes.ScenePlugin; - - /** - * A reference to the Scene's Update List. - * - * Use this to organize the children contained in the update list. - * - * The Update List is responsible for managing children that need their `preUpdate` methods called, - * in order to process so internal components, such as Sprites with Animations. - * - * In the default set-up there is no reference to this from within the Scene itself. - */ - updateList: Phaser.GameObjects.UpdateList; - - /** - * This method is called only once by the Scene Manager when the Scene is instantiated. - * It is responsible for setting up all of the Scene plugins and references. - * It should never be called directly. - * @param game A reference to the Phaser Game instance. - */ - protected init(game: Phaser.Game): void; - - /** - * A single game step. Called automatically by the Scene Manager as a result of a Request Animation - * Frame or Set Timeout call to the main Game instance. - * @param time The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). - * @param delta The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. - */ - step(time: number, delta: number): void; - - /** - * Called automatically by the Scene Manager. - * Instructs the Scene to render itself via its Camera Manager to the renderer given. - * @param renderer The renderer that invoked the render call. - */ - render(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; - - /** - * Force a sort of the display list on the next render. - */ - queueDepthSort(): void; - - /** - * Immediately sorts the display list if the flag is set. - */ - depthSort(): void; - - /** - * Pause this Scene. - * A paused Scene still renders, it just doesn't run ANY of its update handlers or systems. - * @param data A data object that will be passed in the 'pause' event. - */ - pause(data?: object): Phaser.Scenes.Systems; - - /** - * Resume this Scene from a paused state. - * @param data A data object that will be passed in the 'resume' event. - */ - resume(data?: object): Phaser.Scenes.Systems; - - /** - * Send this Scene to sleep. - * - * A sleeping Scene doesn't run its update step or render anything, but it also isn't shut down - * or has any of its systems or children removed, meaning it can be re-activated at any point and - * will carry on from where it left off. It also keeps everything in memory and events and callbacks - * from other Scenes may still invoke changes within it, so be careful what is left active. - * @param data A data object that will be passed in the 'sleep' event. - */ - sleep(data?: object): Phaser.Scenes.Systems; - - /** - * Wake-up this Scene if it was previously asleep. - * @param data A data object that will be passed in the 'wake' event. - */ - wake(data?: object): Phaser.Scenes.Systems; - - /** - * Returns any data that was sent to this Scene by another Scene. - * - * The data is also passed to `Scene.init` and in various Scene events, but - * you can access it at any point via this method. - */ - getData(): any; - - /** - * Is this Scene sleeping? - */ - isSleeping(): boolean; - - /** - * Is this Scene running? - */ - isActive(): boolean; - - /** - * Is this Scene paused? - */ - isPaused(): boolean; - - /** - * Is this Scene currently transitioning out to, or in from another Scene? - */ - isTransitioning(): boolean; - - /** - * Is this Scene currently transitioning out from itself to another Scene? - */ - isTransitionOut(): boolean; - - /** - * Is this Scene currently transitioning in from another Scene? - */ - isTransitionIn(): boolean; - - /** - * Is this Scene visible and rendering? - */ - isVisible(): boolean; - - /** - * Sets the visible state of this Scene. - * An invisible Scene will not render, but will still process updates. - * @param value `true` to render this Scene, otherwise `false`. - */ - setVisible(value: boolean): Phaser.Scenes.Systems; - - /** - * Set the active state of this Scene. - * - * An active Scene will run its core update loop. - * @param value If `true` the Scene will be resumed, if previously paused. If `false` it will be paused. - * @param data A data object that will be passed in the 'resume' or 'pause' events. - */ - setActive(value: boolean, data?: object): Phaser.Scenes.Systems; - - /** - * Start this Scene running and rendering. - * Called automatically by the SceneManager. - * @param data Optional data object that may have been passed to this Scene from another. - */ - start(data: object): void; - - /** - * Shutdown this Scene and send a shutdown event to all of its systems. - * A Scene that has been shutdown will not run its update loop or render, but it does - * not destroy any of its plugins or references. It is put into hibernation for later use. - * If you don't ever plan to use this Scene again, then it should be destroyed instead - * to free-up resources. - * @param data A data object that will be passed in the 'shutdown' event. - */ - shutdown(data?: object): void; - - } - - } - - /** - * A base Phaser.Scene class which can be extended for your own use. - * - * You can also define the optional methods {@link Phaser.Types.Scenes.SceneInitCallback init()}, {@link Phaser.Types.Scenes.ScenePreloadCallback preload()}, and {@link Phaser.Types.Scenes.SceneCreateCallback create()}. - */ - class Scene { - /** - * - * @param config Scene specific configuration settings. - */ - constructor(config: string | Phaser.Types.Scenes.SettingsConfig); - - /** - * The Scene Systems. You must never overwrite this property, or all hell will break lose. - */ - sys: Phaser.Scenes.Systems; - - /** - * A reference to the Phaser.Game instance. - * This property will only be available if defined in the Scene Injection Map. - */ - game: Phaser.Game; - - /** - * A reference to the global Animation Manager. - * This property will only be available if defined in the Scene Injection Map. - */ - anims: Phaser.Animations.AnimationManager; - - /** - * A reference to the global Cache. - * This property will only be available if defined in the Scene Injection Map. - */ - cache: Phaser.Cache.CacheManager; - - /** - * A reference to the game level Data Manager. - * This property will only be available if defined in the Scene Injection Map. - */ - registry: Phaser.Data.DataManager; - - /** - * A reference to the Sound Manager. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - sound: Phaser.Sound.BaseSoundManager; - - /** - * A reference to the Texture Manager. - * This property will only be available if defined in the Scene Injection Map. - */ - textures: Phaser.Textures.TextureManager; - - /** - * A scene level Event Emitter. - * This property will only be available if defined in the Scene Injection Map. - */ - events: Phaser.Events.EventEmitter; - - /** - * A scene level Camera System. - * This property will only be available if defined in the Scene Injection Map. - */ - cameras: Phaser.Cameras.Scene2D.CameraManager; - - /** - * A scene level Game Object Factory. - * This property will only be available if defined in the Scene Injection Map. - */ - add: Phaser.GameObjects.GameObjectFactory; - - /** - * A scene level Game Object Creator. - * This property will only be available if defined in the Scene Injection Map. - */ - make: Phaser.GameObjects.GameObjectCreator; - - /** - * A reference to the Scene Manager Plugin. - * This property will only be available if defined in the Scene Injection Map. - */ - scene: Phaser.Scenes.ScenePlugin; - - /** - * A scene level Game Object Display List. - * This property will only be available if defined in the Scene Injection Map. - */ - children: Phaser.GameObjects.DisplayList; - - /** - * A scene level Lights Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - lights: Phaser.GameObjects.LightsManager; - - /** - * A scene level Data Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - data: Phaser.Data.DataManager; - - /** - * A scene level Input Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - input: Phaser.Input.InputPlugin; - - /** - * A scene level Loader Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - load: Phaser.Loader.LoaderPlugin; - - /** - * A scene level Time and Clock Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - time: Phaser.Time.Clock; - - /** - * A scene level Tween Manager Plugin. - * This property will only be available if defined in the Scene Injection Map and the plugin is installed. - */ - tweens: Phaser.Tweens.TweenManager; - - /** - * A scene level Arcade Physics Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - */ - physics: Phaser.Physics.Arcade.ArcadePhysics; - - /** - * A scene level Impact Physics Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - */ - impact: Phaser.Physics.Impact.ImpactPhysics; - - /** - * A scene level Matter Physics Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - */ - matter: Phaser.Physics.Matter.MatterPhysics; - - /** - * A scene level Facebook Instant Games Plugin. - * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. - */ - facebook: Phaser.FacebookInstantGamesPlugin; - - /** - * A reference to the global Scale Manager. - * This property will only be available if defined in the Scene Injection Map. - */ - scale: Phaser.Scale.ScaleManager; - - /** - * A reference to the Plugin Manager. - * - * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install - * those plugins into Scenes as required. - */ - plugins: Phaser.Plugins.PluginManager; - - /** - * Should be overridden by your own Scenes. - * This method is called once per game step while the scene is running. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(time: number, delta: number): void; - - } - - namespace Sound { - /** - * Class containing all the shared state and behavior of a sound object, independent of the implementation. - */ - class BaseSound extends Phaser.Events.EventEmitter { - /** - * - * @param manager Reference to the current sound manager instance. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. - */ - constructor(manager: Phaser.Sound.BaseSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); - - /** - * Asset key for the sound. - */ - readonly key: string; - - /** - * Flag indicating if sound is currently playing. - */ - readonly isPlaying: boolean; - - /** - * Flag indicating if sound is currently paused. - */ - readonly isPaused: boolean; - - /** - * A property that holds the value of sound's actual playback rate, - * after its rate and detune values has been combined with global - * rate and detune values. - */ - readonly totalRate: number; - - /** - * A value representing the duration, in seconds. - * It could be total sound duration or a marker duration. - */ - readonly duration: number; - - /** - * The total duration of the sound in seconds. - */ - readonly totalDuration: number; - - /** - * Object containing markers definitions. - */ - readonly markers: {[key: string]: Phaser.Types.Sound.SoundMarker}; - - /** - * Currently playing marker. - * 'null' if whole sound is playing. - */ - readonly currentMarker: Phaser.Types.Sound.SoundMarker; - - /** - * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object. - * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. - * @param marker Marker object. - */ - addMarker(marker: Phaser.Types.Sound.SoundMarker): boolean; - - /** - * Updates previously added marker. - * @param marker Marker object with updated values. - */ - updateMarker(marker: Phaser.Types.Sound.SoundMarker): boolean; - - /** - * Removes a marker from the sound. - * @param markerName The name of the marker to remove. - */ - removeMarker(markerName: string): Phaser.Types.Sound.SoundMarker; - - /** - * Play this sound, or a marked section of it. - * It always plays the sound from the start. If you want to start playback from a specific time - * you can set 'seek' setting of the config object, provided to this call, to that value. - * @param markerName If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. Default ''. - * @param config Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. - */ - play(markerName?: string | Phaser.Types.Sound.SoundConfig, config?: Phaser.Types.Sound.SoundConfig): boolean; - - /** - * Pauses the sound. - */ - pause(): boolean; - - /** - * Resumes the sound. - */ - resume(): boolean; - - /** - * Stop playing this sound. - */ - stop(): boolean; - - /** - * Method used internally for applying config values to some of the sound properties. - */ - protected applyConfig(): void; - - /** - * Method used internally for resetting values of some of the config properties. - */ - protected resetConfig(): void; - - /** - * Update method called automatically by sound manager on every game step. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time elapsed since the last frame. - */ - protected update(time: number, delta: number): void; - - /** - * Method used internally to calculate total playback rate of the sound. - */ - protected calculateRate(): void; - - /** - * Destroys this sound and all associated events and marks it for removal from the sound manager. - */ - destroy(): void; - - } - - /** - * The sound manager is responsible for playing back audio via Web Audio API or HTML Audio tag as fallback. - * The audio file type and the encoding of those files are extremely important. - * - * Not all browsers can play all audio formats. - * - * There is a good guide to what's supported [here](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support). - */ - class BaseSoundManager extends Phaser.Events.EventEmitter { - /** - * - * @param game Reference to the current game instance. - */ - constructor(game: Phaser.Game); - - /** - * Local reference to game. - */ - readonly game: Phaser.Game; - - /** - * Local reference to the JSON Cache, as used by Audio Sprites. - */ - readonly jsonCache: Phaser.Cache.BaseCache; - - /** - * Global mute setting. - */ - mute: boolean; - - /** - * Global volume setting. - */ - volume: number; - - /** - * Flag indicating if sounds should be paused when game looses focus, - * for instance when user switches to another tab/program/app. - */ - pauseOnBlur: boolean; - - /** - * Mobile devices require sounds to be triggered from an explicit user action, - * such as a tap, before any sound can be loaded/played on a web page. - * Set to true if the audio system is currently locked awaiting user interaction. - */ - readonly locked: boolean; - - /** - * Adds a new sound into the sound manager. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. - */ - add(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.BaseSound; - - /** - * 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 - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. - */ - addAudioSprite(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.HTML5AudioSound | Phaser.Sound.WebAudioSound; - - /** - * Adds a new sound to the sound manager and plays it. - * The sound will be automatically removed (destroyed) once playback ends. - * This lets you play a new sound on the fly without the need to keep a reference to it. - * @param key Asset key for the sound. - * @param extra An optional additional object containing settings to be applied to the sound. It could be either config or marker object. - */ - play(key: string, extra?: Phaser.Types.Sound.SoundConfig | Phaser.Types.Sound.SoundMarker): boolean; - - /** - * Enables playing audio sprite sound on the fly without the need to keep a reference to it. - * Sound will auto destroy once its playback ends. - * @param key Asset key for the sound. - * @param spriteName The name of the sound sprite to play. - * @param config An optional config object containing default sound settings. - */ - playAudioSprite(key: string, spriteName: string, config?: Phaser.Types.Sound.SoundConfig): boolean; - - /** - * Removes a sound from the sound manager. - * The removed sound is destroyed before removal. - * @param sound The sound object to remove. - */ - remove(sound: Phaser.Sound.BaseSound): boolean; - - /** - * Removes all sounds from the sound manager that have an asset key matching the given value. - * The removed sounds are destroyed before removal. - * @param key The key to match when removing sound objects. - */ - removeByKey(key: string): number; - - /** - * Pauses all the sounds in the game. - */ - pauseAll(): void; - - /** - * Resumes all the sounds in the game. - */ - resumeAll(): void; - - /** - * Stops all the sounds in the game. - */ - stopAll(): void; - - /** - * 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). - */ - protected unlock(): void; - - /** - * Method used internally for pausing sound manager if - * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. - */ - protected onBlur(): void; - - /** - * Method used internally for resuming sound manager if - * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. - */ - protected onFocus(): void; - - /** - * Update method called on every game step. - * Removes destroyed sounds and updates every active sound in the game. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time elapsed since the last frame. - */ - protected update(time: number, delta: number): void; - - /** - * Destroys all the sounds in the game and all associated events. - */ - destroy(): void; - - /** - * Sets the global playback rate at which all the sounds will be played. - * - * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * @param value Global playback rate at which all the sounds will be played. - */ - setRate(value: number): Phaser.Sound.BaseSoundManager; - - /** - * Global playback rate at which all the sounds will be played. - * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audio's playback speed. - */ - rate: number; - - /** - * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - * @param value The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - */ - setDetune(value: number): Phaser.Sound.BaseSoundManager; - - /** - * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - */ - detune: number; - - } - - namespace Events { - /** - * The Sound Complete Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they complete playback. - * - * Listen to it from a Sound instance using `Sound.on('complete', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('complete', listener); - * music.play(); - * ``` - */ - const COMPLETE: any; - - /** - * The Audio Data Decoded All Event. - * - * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method, - * once all files passed to the method have been decoded (or errored). - * - * Use `Phaser.Sound.Events#DECODED` to listen for single sounds being decoded, and `DECODED_ALL` to - * listen for them all completing. - * - * Listen to it from the Sound Manager in a Scene using `this.sound.on('decodedall', listener)`, i.e.: - * - * ```javascript - * this.sound.once('decodedall', handler); - * this.sound.decodeAudio([ audioFiles ]); - * ``` - */ - const DECODED_ALL: any; - - /** - * The Audio Data Decoded Event. - * - * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method. - * - * Listen to it from the Sound Manager in a Scene using `this.sound.on('decoded', listener)`, i.e.: - * - * ```javascript - * this.sound.on('decoded', handler); - * this.sound.decodeAudio(key, audioData); - * ``` - */ - const DECODED: any; - - /** - * The Sound Destroy Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are destroyed, either - * directly or via a Sound Manager. - * - * Listen to it from a Sound instance using `Sound.on('destroy', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('destroy', listener); - * music.destroy(); - * ``` - */ - const DESTROY: any; - - /** - * The Sound Detune Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their detune value changes. - * - * Listen to it from a Sound instance using `Sound.on('detune', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('detune', listener); - * music.play(); - * music.setDetune(200); - * ``` - */ - const DETUNE: any; - - /** - * The Sound Manager Global Detune Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `detune` property of the Sound Manager is changed, which globally - * adjusts the detuning of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('rate', listener)`. - */ - const GLOBAL_DETUNE: any; - - /** - * The Sound Manager Global Mute Event. - * - * This event is dispatched by the Sound Manager when its `mute` property is changed, either directly - * or via the `setMute` method. This changes the mute state of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('mute', listener)`. - */ - const GLOBAL_MUTE: any; - - /** - * The Sound Manager Global Rate Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `rate` property of the Sound Manager is changed, which globally - * adjusts the playback rate of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('rate', listener)`. - */ - const GLOBAL_RATE: any; - - /** - * The Sound Manager Global Volume Event. - * - * This event is dispatched by the Sound Manager when its `volume` property is changed, either directly - * or via the `setVolume` method. This changes the volume of all active sounds. - * - * Listen to it from a Scene using: `this.sound.on('volume', listener)`. - */ - const GLOBAL_VOLUME: any; - - /** - * The Sound Looped Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they loop during playback. - * - * Listen to it from a Sound instance using `Sound.on('looped', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('looped', listener); - * music.setLoop(true); - * music.play(); - * ``` - * - * This is not to be confused with the [LOOP]{@linkcode Phaser.Sound.Events#event:LOOP} event, which only emits when the loop state of a Sound is changed. - */ - const LOOPED: any; - - /** - * The Sound Loop Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their loop state is changed. - * - * Listen to it from a Sound instance using `Sound.on('loop', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('loop', listener); - * music.setLoop(true); - * ``` - * - * This is not to be confused with the [LOOPED]{@linkcode Phaser.Sound.Events#event:LOOPED} event, which emits each time a Sound loops during playback. - */ - const LOOP: any; - - /** - * The Sound Mute Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their mute state changes. - * - * Listen to it from a Sound instance using `Sound.on('mute', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('mute', listener); - * music.play(); - * music.setMute(true); - * ``` - */ - const MUTE: any; - - /** - * The Pause All Sounds Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `pauseAll` method is invoked and after all current Sounds - * have been paused. - * - * Listen to it from a Scene using: `this.sound.on('pauseall', listener)`. - */ - const PAUSE_ALL: any; - - /** - * The Sound Pause Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are paused. - * - * Listen to it from a Sound instance using `Sound.on('pause', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('pause', listener); - * music.play(); - * music.pause(); - * ``` - */ - const PAUSE: any; - - /** - * The Sound Play Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are played. - * - * Listen to it from a Sound instance using `Sound.on('play', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('play', listener); - * music.play(); - * ``` - */ - const PLAY: any; - - /** - * The Sound Rate Change Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their rate changes. - * - * Listen to it from a Sound instance using `Sound.on('rate', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('rate', listener); - * music.play(); - * music.setRate(0.5); - * ``` - */ - const RATE: any; - - /** - * The Resume All Sounds Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `resumeAll` method is invoked and after all current Sounds - * have been resumed. - * - * Listen to it from a Scene using: `this.sound.on('resumeall', listener)`. - */ - const RESUME_ALL: any; - - /** - * The Sound Resume Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are resumed from a paused state. - * - * Listen to it from a Sound instance using `Sound.on('resume', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('resume', listener); - * music.play(); - * music.pause(); - * music.resume(); - * ``` - */ - const RESUME: any; - - /** - * The Sound Seek Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are seeked to a new position. - * - * Listen to it from a Sound instance using `Sound.on('seek', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('seek', listener); - * music.play(); - * music.setSeek(5000); - * ``` - */ - const SEEK: any; - - /** - * The Stop All Sounds Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched when the `stopAll` method is invoked and after all current Sounds - * have been stopped. - * - * Listen to it from a Scene using: `this.sound.on('stopall', listener)`. - */ - const STOP_ALL: any; - - /** - * The Sound Stop Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are stopped. - * - * Listen to it from a Sound instance using `Sound.on('stop', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('stop', listener); - * music.play(); - * music.stop(); - * ``` - */ - const STOP: any; - - /** - * The Sound Manager Unlocked Event. - * - * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, - * or the HTML5 Audio Manager. It is dispatched during the update loop when the Sound Manager becomes unlocked. For - * Web Audio this is on the first user gesture on the page. - * - * Listen to it from a Scene using: `this.sound.on('unlocked', listener)`. - */ - const UNLOCKED: any; - - /** - * The Sound Volume Event. - * - * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their volume changes. - * - * Listen to it from a Sound instance using `Sound.on('volume', listener)`, i.e.: - * - * ```javascript - * var music = this.sound.add('key'); - * music.on('volume', listener); - * music.play(); - * music.setVolume(0.5); - * ``` - */ - const VOLUME: any; - - } - - /** - * HTML5 Audio implementation of the sound. - */ - class HTML5AudioSound extends Phaser.Sound.BaseSound { - /** - * - * @param manager Reference to the current sound manager instance. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. Default {}. - */ - constructor(manager: Phaser.Sound.HTML5AudioSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); - - /** - * Play this sound, or a marked section of it. - * It always plays the sound from the start. If you want to start playback from a specific time - * you can set 'seek' setting of the config object, provided to this call, to that value. - * @param markerName If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. Default ''. - * @param config Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. - */ - play(markerName?: string | Phaser.Types.Sound.SoundConfig, config?: Phaser.Types.Sound.SoundConfig): boolean; - - /** - * Pauses the sound. - */ - pause(): boolean; - - /** - * Resumes the sound. - */ - resume(): boolean; - - /** - * Stop playing this sound. - */ - stop(): boolean; - - /** - * Update method called automatically by sound manager on every game step. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time elapsed since the last frame. - */ - protected update(time: number, delta: number): void; - - /** - * Calls Phaser.Sound.BaseSound#destroy method - * and cleans up all HTML5 Audio related stuff. - */ - destroy(): void; - - /** - * Method used internally to calculate total playback rate of the sound. - */ - protected calculateRate(): void; - - /** - * Boolean indicating whether the sound is muted or not. - * Gets or sets the muted state of this sound. - */ - mute: boolean; - - /** - * Sets the muted state of this Sound. - * @param value `true` to mute this sound, `false` to unmute it. - */ - setMute(value: boolean): Phaser.Sound.HTML5AudioSound; - - /** - * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). - */ - volume: number; - - /** - * Sets the volume of this Sound. - * @param value The volume of the sound. - */ - setVolume(value: number): Phaser.Sound.HTML5AudioSound; - - /** - * Rate at which this Sound will be played. - * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - */ - rate: number; - - /** - * Sets the playback rate of this Sound. - * - * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * @param value The playback rate at of this Sound. - */ - setRate(value: number): Phaser.Sound.HTML5AudioSound; - - /** - * 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). - */ - detune: number; - - /** - * 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). - * @param value The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - */ - setDetune(value: number): Phaser.Sound.HTML5AudioSound; - - /** - * Property representing the position of playback for this sound, in seconds. - * Setting it to a specific value moves current playback to that position. - * The value given is clamped to the range 0 to current marker duration. - * Setting seek of a stopped sound has no effect. - */ - seek: number; - - /** - * Seeks to a specific point in this sound. - * @param value The point in the sound to seek to. - */ - setSeek(value: number): Phaser.Sound.HTML5AudioSound; - - /** - * Flag indicating whether or not the sound or current sound marker will loop. - */ - loop: boolean; - - /** - * Sets the loop state of this Sound. - * @param value `true` to loop this sound, `false` to not loop it. - */ - setLoop(value: boolean): Phaser.Sound.HTML5AudioSound; - - } - - /** - * HTML5AudioSoundManager - */ - class HTML5AudioSoundManager extends Phaser.Sound.BaseSoundManager { - /** - * - * @param game Reference to the current game instance. - */ - constructor(game: Phaser.Game); - - /** - * Flag indicating whether if there are no idle instances of HTML5 Audio tag, - * for any particular sound, if one of the used tags should be hijacked and used - * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play - * call should be ignored. - */ - override: boolean; - - /** - * Value representing time difference, in seconds, between calling - * play method on an audio tag and when it actually starts playing. - * It is used to achieve more accurate delayed sound playback. - * - * You might need to tweak this value to get the desired results - * since audio play delay varies depending on the browser/platform. - */ - audioPlayDelay: number; - - /** - * A value by which we should offset the loop end marker of the - * looping sound to compensate for lag, caused by changing audio - * tag playback position, in order to achieve gapless looping. - * - * You might need to tweak this value to get the desired results - * since loop lag varies depending on the browser/platform. - */ - loopEndOffset: number; - - /** - * Adds a new sound into the sound manager. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. - */ - add(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.HTML5AudioSound; - - /** - * Unlocks HTML5 Audio loading and playback on mobile - * devices on the initial explicit user interaction. - */ - unlock(): void; - - /** - * Method used internally for pausing sound manager if - * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. - */ - protected onBlur(): void; - - /** - * Method used internally for resuming sound manager if - * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. - */ - protected onFocus(): void; - - /** - * Calls Phaser.Sound.BaseSoundManager#destroy method - * and cleans up all HTML5 Audio related stuff. - */ - destroy(): void; - - /** - * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters - * to check if sound manager is locked and then either perform action immediately or queue it - * to be performed once the sound manager gets unlocked. - * @param sound Sound object on which to perform queued action. - * @param prop Name of the method to be called or property to be assigned a value to. - * @param value An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property. - */ - protected isLocked(sound: Phaser.Sound.HTML5AudioSound, prop: string, value?: any): boolean; - - /** - * Sets the muted state of all this Sound Manager. - * @param value `true` to mute all sounds, `false` to unmute them. - */ - setMute(value: boolean): Phaser.Sound.HTML5AudioSoundManager; - - mute: boolean; - - /** - * Sets the volume of this Sound Manager. - * @param value The global volume of this Sound Manager. - */ - setVolume(value: number): Phaser.Sound.HTML5AudioSoundManager; - - volume: number; - - } - - /** - * No audio implementation of the sound. It is used if audio has been - * disabled in the game config or the device doesn't support any audio. - * - * It represents a graceful degradation of sound logic that provides - * minimal functionality and prevents Phaser projects that use audio from - * breaking on devices that don't support any audio playback technologies. - */ - class NoAudioSound extends Phaser.Sound.BaseSound { - /** - * - * @param manager Reference to the current sound manager instance. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. Default {}. - */ - constructor(manager: Phaser.Sound.NoAudioSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); - - } - - /** - * No audio implementation of the sound manager. It is used if audio has been - * disabled in the game config or the device doesn't support any audio. - * - * It represents a graceful degradation of sound manager logic that provides - * minimal functionality and prevents Phaser projects that use audio from - * breaking on devices that don't support any audio playback technologies. - */ - class NoAudioSoundManager extends Phaser.Sound.BaseSoundManager { - /** - * - * @param game Reference to the current game instance. - */ - constructor(game: Phaser.Game); - - } - - /** - * 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 - * @param game Reference to the current game instance. - */ - function SoundManagerCreator(game: Phaser.Game): Phaser.Sound.HTML5AudioSoundManager | Phaser.Sound.WebAudioSoundManager | Phaser.Sound.NoAudioSoundManager; - - /** - * Web Audio API implementation of the sound. - */ - class WebAudioSound extends Phaser.Sound.BaseSound { - /** - * - * @param manager Reference to the current sound manager instance. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. Default {}. - */ - constructor(manager: Phaser.Sound.WebAudioSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); - - /** - * Play this sound, or a marked section of it. - * - * It always plays the sound from the start. If you want to start playback from a specific time - * you can set 'seek' setting of the config object, provided to this call, to that value. - * @param markerName If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. Default ''. - * @param config Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. - */ - play(markerName?: string | Phaser.Types.Sound.SoundConfig, config?: Phaser.Types.Sound.SoundConfig): boolean; - - /** - * Pauses the sound. - */ - pause(): boolean; - - /** - * Resumes the sound. - */ - resume(): boolean; - - /** - * Stop playing this sound. - */ - stop(): boolean; - - /** - * Method used internally for applying config values to some of the sound properties. - */ - protected applyConfig(): void; - - /** - * Update method called automatically by sound manager on every game step. - * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. - * @param delta The delta time elapsed since the last frame. - */ - protected update(time: number, delta: number): void; - - /** - * Calls Phaser.Sound.BaseSound#destroy method - * and cleans up all Web Audio API related stuff. - */ - destroy(): void; - - /** - * Method used internally to calculate total playback rate of the sound. - */ - protected calculateRate(): void; - - /** - * Rate at which this Sound will be played. - * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - */ - rate: number; - - /** - * Sets the playback rate of this Sound. - * - * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed - * and 2.0 doubles the audios playback speed. - * @param value The playback rate at of this Sound. - */ - setRate(value: number): Phaser.Sound.WebAudioSound; - - /** - * 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). - */ - detune: number; - - /** - * 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). - * @param value The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). - */ - setDetune(value: number): Phaser.Sound.WebAudioSound; - - /** - * Boolean indicating whether the sound is muted or not. - * Gets or sets the muted state of this sound. - */ - mute: boolean; - - /** - * Sets the muted state of this Sound. - * @param value `true` to mute this sound, `false` to unmute it. - */ - setMute(value: boolean): Phaser.Sound.WebAudioSound; - - /** - * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). - */ - volume: number; - - /** - * Sets the volume of this Sound. - * @param value The volume of the sound. - */ - setVolume(value: number): Phaser.Sound.WebAudioSound; - - /** - * Property representing the position of playback for this sound, in seconds. - * Setting it to a specific value moves current playback to that position. - * The value given is clamped to the range 0 to current marker duration. - * Setting seek of a stopped sound has no effect. - */ - seek: number; - - /** - * Seeks to a specific point in this sound. - * @param value The point in the sound to seek to. - */ - setSeek(value: number): Phaser.Sound.WebAudioSound; - - /** - * Flag indicating whether or not the sound or current sound marker will loop. - */ - loop: boolean; - - /** - * Sets the loop state of this Sound. - * @param value `true` to loop this sound, `false` to not loop it. - */ - setLoop(value: boolean): Phaser.Sound.WebAudioSound; - - } - - /** - * Web Audio API implementation of the sound manager. - */ - class WebAudioSoundManager extends Phaser.Sound.BaseSoundManager { - /** - * - * @param game Reference to the current game instance. - */ - constructor(game: Phaser.Game); - - /** - * This method takes a new AudioContext reference and then sets - * this Sound Manager to use that context for all playback. - * - * As part of this call it also disconnects the master mute and volume - * nodes and then re-creates them on the new given context. - * @param context Reference to an already created AudioContext instance. - */ - setAudioContext(context: AudioContext): this; - - /** - * Adds a new sound into the sound manager. - * @param key Asset key for the sound. - * @param config An optional config object containing default sound settings. - */ - add(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.WebAudioSound; - - /** - * Decode audio data into a format ready for playback via Web Audio. - * - * The audio data can be a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. - * - * The `audioKey` is the key that will be used to save the decoded audio to the audio cache. - * - * Instead of passing a single entry you can instead pass an array of `Phaser.Types.Sound.DecodeAudioConfig` - * objects as the first and only argument. - * - * Decoding is an async process, so be sure to listen for the events to know when decoding has completed. - * - * Once the audio has decoded it can be added to the Sound Manager or played via its key. - * @param audioKey The string-based key to be used to reference the decoded audio in the audio cache, or an array of audio config objects. - * @param audioData The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. - */ - decodeAudio(audioKey?: Phaser.Types.Sound.DecodeAudioConfig[] | string, audioData?: ArrayBuffer | string): void; - - /** - * 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). - */ - unlock(): void; - - /** - * Method used internally for pausing sound manager if - * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. - */ - protected onBlur(): void; - - /** - * Method used internally for resuming sound manager if - * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. - */ - protected onFocus(): void; - - /** - * Calls Phaser.Sound.BaseSoundManager#destroy method - * and cleans up all Web Audio API related stuff. - */ - destroy(): void; - - /** - * Sets the muted state of all this Sound Manager. - * @param value `true` to mute all sounds, `false` to unmute them. - */ - setMute(value: boolean): Phaser.Sound.WebAudioSoundManager; - - mute: boolean; - - /** - * Sets the volume of this Sound Manager. - * @param value The global volume of this Sound Manager. - */ - setVolume(value: number): Phaser.Sound.WebAudioSoundManager; - - volume: number; - - } - - } - - namespace Structs { - namespace Events { - /** - * The Process Queue Add Event. - * - * This event is dispatched by a Process Queue when a new item is successfully moved to its active list. - * - * You will most commonly see this used by a Scene's Update List when a new Game Object has been added. - * - * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('add', listener)`. - */ - const PROCESS_QUEUE_ADD: any; - - /** - * The Process Queue Remove Event. - * - * This event is dispatched by a Process Queue when a new item is successfully removed from its active list. - * - * You will most commonly see this used by a Scene's Update List when a Game Object has been removed. - * - * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('remove', listener)`. - */ - const PROCESS_QUEUE_REMOVE: any; - - } - - /** - * List is a generic implementation of an ordered list which contains utility methods for retrieving, manipulating, and iterating items. - */ - class List { - /** - * - * @param parent The parent of this list. - */ - constructor(parent: any); - - /** - * The parent of this list. - */ - parent: any; - - /** - * The objects that belong to this collection. - */ - list: T[]; - - /** - * The index of the current element. - * - * This is used internally when iterating through the list with the {@link #first}, {@link #last}, {@link #get}, and {@link #previous} properties. - */ - position: integer; - - /** - * A callback that is invoked every time a child is added to this list. - */ - addCallback: Function; - - /** - * A callback that is invoked every time a child is removed from this list. - */ - removeCallback: Function; - - /** - * The property key to sort by. - */ - _sortKey: string; - - /** - * Adds the given item to the end of the list. Each item must be unique. - * @param child The item, or array of items, to add to the list. - * @param skipCallback Skip calling the List.addCallback if this child is added successfully. Default false. - */ - add(child: T, skipCallback?: boolean): T; - - /** - * Adds an item to list, starting at a specified index. Each item must be unique within the list. - * @param child The item, or array of items, to add to the list. - * @param index The index in the list at which the element(s) will be inserted. Default 0. - * @param skipCallback Skip calling the List.addCallback if this child is added successfully. Default false. - */ - addAt(child: T, index?: integer, skipCallback?: boolean): T; - - /** - * Retrieves the item at a given position inside the List. - * @param index The index of the item. - */ - getAt(index: integer): T; - - /** - * Locates an item within the List and returns its index. - * @param child The item to locate. - */ - getIndex(child: T): integer; - - /** - * 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. - * @param property The property to lexically sort by. - * @param handler Provide your own custom handler function. Will receive 2 children which it should compare and return a boolean. - */ - sort(property: string, handler?: Function): T[]; - - /** - * Searches for the first instance of a child with its `name` - * property matching the given argument. Should more than one child have - * the same name only the first is returned. - * @param name The name to search for. - */ - getByName(name: string): T | null; - - /** - * Returns a random child from the group. - * @param startIndex Offset from the front of the group (lowest child). Default 0. - * @param length Restriction on the number of values you want to randomly select from. Default (to top). - */ - getRandom(startIndex?: integer, length?: integer): T | null; - - /** - * Returns the first element in a given part of the List which matches a specific criterion. - * @param property The name of the property to test or a falsey value to have no criterion. - * @param value The value to test the `property` against, or `undefined` to allow any value and only check for existence. - * @param startIndex The position in the List to start the search at. Default 0. - * @param endIndex The position in the List to optionally stop the search at. It won't be checked. - */ - getFirst(property: string, value: any, startIndex?: number, endIndex?: number): T | null; - - /** - * Returns all children in this List. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('parent')` would return only children that have a property called `parent`. - * - * You can also specify a value to compare the property to: - * - * `getAll('visible', true)` would return only children that have their visible property set to `true`. - * - * Optionally you can specify a start and end index. For example if this List had 100 children, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 children in the List. - * @param property An optional property to test against the value argument. - * @param value If property is set then Child.property must strictly equal this value to be included in the results. - * @param startIndex The first child index to start the search from. - * @param endIndex The last child index to search up until. - */ - getAll(property?: string, value?: T, startIndex?: integer, endIndex?: integer): T[]; - - /** - * Returns the total number of items in the List which have a property matching the given value. - * @param property The property to test on each item. - * @param value The value to test the property against. - */ - count(property: string, value: T): integer; - - /** - * Swaps the positions of two items in the list. - * @param child1 The first item to swap. - * @param child2 The second item to swap. - */ - swap(child1: T, child2: T): void; - - /** - * Moves an item in the List to a new position. - * @param child The item to move. - * @param index Moves an item in the List to a new position. - */ - moveTo(child: T, index: integer): T; - - /** - * Removes one or many items from the List. - * @param child The item, or array of items, to remove. - * @param skipCallback Skip calling the List.removeCallback. Default false. - */ - remove(child: T, skipCallback?: boolean): T; - - /** - * Removes the item at the given position in the List. - * @param index The position to remove the item from. - * @param skipCallback Skip calling the List.removeCallback. Default false. - */ - removeAt(index: integer, skipCallback?: boolean): T; - - /** - * Removes the items within the given range in the List. - * @param startIndex The index to start removing from. Default 0. - * @param endIndex The position to stop removing at. The item at this position won't be removed. - * @param skipCallback Skip calling the List.removeCallback. Default false. - */ - removeBetween(startIndex?: integer, endIndex?: integer, skipCallback?: boolean): T[]; - - /** - * Removes all the items. - * @param skipCallback Skip calling the List.removeCallback. Default false. - */ - removeAll(skipCallback?: boolean): Phaser.Structs.List; - - /** - * Brings the given child to the top of this List. - * @param child The item to bring to the top of the List. - */ - bringToTop(child: T): T; - - /** - * Sends the given child to the bottom of this List. - * @param child The item to send to the back of the list. - */ - sendToBack(child: T): T; - - /** - * Moves the given child up one place in this group unless it's already at the top. - * @param child The item to move up. - */ - moveUp(child: T): T; - - /** - * Moves the given child down one place in this group unless it's already at the bottom. - * @param child The item to move down. - */ - moveDown(child: T): T; - - /** - * Reverses the order of all children in this List. - */ - reverse(): Phaser.Structs.List; - - /** - * Shuffles the items in the list. - */ - shuffle(): Phaser.Structs.List; - - /** - * Replaces a child of this List with the given newChild. The newChild cannot be a member of this List. - * @param oldChild The child in this List that will be replaced. - * @param newChild The child to be inserted into this List. - */ - replace(oldChild: T, newChild: T): T; - - /** - * Checks if an item exists within the List. - * @param child The item to check for the existence of. - */ - exists(child: T): boolean; - - /** - * Sets the property `key` to the given value on all members of this List. - * @param property The name of the property to set. - * @param value The value to set the property to. - * @param startIndex The first child index to start the search from. - * @param endIndex The last child index to search up until. - */ - setAll(property: string, value: T, startIndex?: integer, endIndex?: integer): void; - - /** - * Passes all children to the given callback. - * @param callback The function to call. - * @param context Value to use as `this` when executing callback. - * @param args Additional arguments that will be passed to the callback, after the child. - */ - each(callback: EachListCallback, context?: any, ...args: any[]): void; - - /** - * Clears the List and recreates its internal array. - */ - shutdown(): void; - - /** - * Destroys this List. - */ - destroy(): void; - - /** - * The number of items inside the List. - */ - readonly length: integer; - - /** - * The first item in the List or `null` for an empty List. - */ - readonly first: T; - - /** - * The last item in the List, or `null` for an empty List. - */ - readonly last: T; - - /** - * The next item in the List, or `null` if the entire List has been traversed. - * - * This property can be read successively after reading {@link #first} or manually setting the {@link #position} to iterate the List. - */ - readonly next: T; - - /** - * The previous item in the List, or `null` if the entire List has been traversed. - * - * This property can be read successively after reading {@link #last} or manually setting the {@link #position} to iterate the List backwards. - */ - readonly previous: T; - - } - - /** - * The keys of a Map can be arbitrary values. - * - * ```javascript - * var map = new Map([ - * [ 1, 'one' ], - * [ 2, 'two' ], - * [ 3, 'three' ] - * ]); - * ``` - */ - class Map { - /** - * - * @param elements An optional array of key-value pairs to populate this Map with. - */ - constructor(elements: V[]); - - /** - * The entries in this Map. - */ - entries: {[key: string]: V}; - - /** - * The number of key / value pairs in this Map. - */ - size: number; - - /** - * Adds an element with a specified `key` and `value` to this Map. - * If the `key` already exists, the value will be replaced. - * @param key The key of the element to be added to this Map. - * @param value The value of the element to be added to this Map. - */ - set(key: K, value: V): Phaser.Structs.Map; - - /** - * Returns the value associated to the `key`, or `undefined` if there is none. - * @param key The key of the element to return from the `Map` object. - */ - get(key: K): V; - - /** - * Returns an `Array` of all the values stored in this Map. - */ - getArray(): V[]; - - /** - * Returns a boolean indicating whether an element with the specified key exists or not. - * @param key The key of the element to test for presence of in this Map. - */ - has(key: K): boolean; - - /** - * Delete the specified element from this Map. - * @param key The key of the element to delete from this Map. - */ - delete(key: K): Phaser.Structs.Map; - - /** - * Delete all entries from this Map. - */ - clear(): Phaser.Structs.Map; - - /** - * Returns all entries keys in this Map. - */ - keys(): K[]; - - /** - * Returns an `Array` of all entries. - */ - values(): V[]; - - /** - * Dumps the contents of this Map to the console via `console.group`. - */ - dump(): void; - - /** - * Passes all entries in this Map to the given callback. - * @param callback The callback which will receive the keys and entries held in this Map. - */ - each(callback: EachMapCallback): Phaser.Structs.Map; - - /** - * Returns `true` if the value exists within this Map. Otherwise, returns `false`. - * @param value The value to search for. - */ - contains(value: V): boolean; - - /** - * Merges all new keys from the given Map into this one. - * If it encounters a key that already exists it will be skipped unless override is set to `true`. - * @param map The Map to merge in to this Map. - * @param override Set to `true` to replace values in this Map with those from the source map, or `false` to skip them. Default false. - */ - merge(map: Phaser.Structs.Map, override?: boolean): Phaser.Structs.Map; - - } - - /** - * A Process Queue maintains three internal lists. - * - * The `pending` list is a selection of items which are due to be made 'active' in the next update. - * The `active` list is a selection of items which are considered active and should be updated. - * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. - * - * When new items are added to a Process Queue they are put in the pending list, rather than being added - * immediately the active list. Equally, items that are removed are put into the destroy list, rather than - * being destroyed immediately. This allows the Process Queue to carefully process each item at a specific, fixed - * time, rather than at the time of the request from the API. - */ - class ProcessQueue extends Phaser.Events.EventEmitter { - /** - * Adds a new item to the Process Queue. - * - * The item is added to the pending list and made active in the next update. - * @param item The item to add to the queue. - */ - add(item: T): Phaser.Structs.ProcessQueue; - - /** - * Removes an item from the Process Queue. - * - * The item is added to the pending destroy and fully removed in the next update. - * @param item The item to be removed from the queue. - */ - remove(item: T): Phaser.Structs.ProcessQueue; - - /** - * Removes all active items from this Process Queue. - * - * All the items are marked as 'pending destroy' and fully removed in the next update. - */ - removeAll(): this; - - /** - * Update this queue. First it will process any items awaiting destruction, and remove them. - * - * Then it will check to see if there are any items pending insertion, and move them to an - * active state. Finally, it will return a list of active items for further processing. - */ - update(): T[]; - - /** - * Returns the current list of active items. - * - * This method returns a reference to the active list array, not a copy of it. - * Therefore, be careful to not modify this array outside of the ProcessQueue. - */ - getActive(): T[]; - - /** - * The number of entries in the active list. - */ - readonly length: integer; - - /** - * Immediately destroys this process queue, clearing all of its internal arrays and resetting the process totals. - */ - destroy(): void; - - } - - /** - * 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 { - } - - /** - * A Set is a collection of unique elements. - */ - class Set { - /** - * - * @param elements An optional array of elements to insert into this Set. - */ - constructor(elements?: T[]); - - /** - * The entries of this Set. Stored internally as an array. - */ - entries: T[]; - - /** - * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. - * @param value The value to insert into this Set. - */ - set(value: T): Phaser.Structs.Set; - - /** - * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. - * If no elements of this Set satisfy the condition then this method will return `null`. - * @param property The property name to check on the elements of this Set. - * @param value The value to check for. - */ - get(property: string, value: T): T; - - /** - * Returns an array containing all the values in this Set. - */ - getArray(): T[]; - - /** - * Removes the given value from this Set if this Set contains that value. - * @param value The value to remove from the Set. - */ - delete(value: T): Phaser.Structs.Set; - - /** - * Dumps the contents of this Set to the console via `console.group`. - */ - dump(): void; - - /** - * Passes each value in this Set to the given callback. - * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. - * @param callback The callback to be invoked and passed each value this Set contains. - * @param callbackScope The scope of the callback. - */ - each(callback: EachSetCallback, callbackScope?: any): Phaser.Structs.Set; - - /** - * Passes each value in this Set to the given callback. - * For when you absolutely know this Set won't be modified during the iteration. - * @param callback The callback to be invoked and passed each value this Set contains. - * @param callbackScope The scope of the callback. - */ - iterate(callback: EachSetCallback, callbackScope?: any): Phaser.Structs.Set; - - /** - * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. - * @param callbackKey The key of the function to be invoked on each Set entry. - * @param args Additional arguments that will be passed to the callback, after the child. - */ - iterateLocal(callbackKey: string, ...args: any[]): Phaser.Structs.Set; - - /** - * Clears this Set so that it no longer contains any values. - */ - clear(): Phaser.Structs.Set; - - /** - * Returns `true` if this Set contains the given value, otherwise returns `false`. - * @param value The value to check for in this Set. - */ - contains(value: T): boolean; - - /** - * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. - * @param set The Set to perform the union with. - */ - union(set: Phaser.Structs.Set): Phaser.Structs.Set; - - /** - * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. - * @param set The Set to intersect this set with. - */ - intersect(set: Phaser.Structs.Set): Phaser.Structs.Set; - - /** - * Returns a new Set containing all the values in this Set which are *not* also in the given Set. - * @param set The Set to perform the difference with. - */ - difference(set: Phaser.Structs.Set): Phaser.Structs.Set; - - /** - * The size of this Set. This is the number of entries within it. - * Changing the size will truncate the Set if the given value is smaller than the current size. - * Increasing the size larger than the current size has no effect. - */ - size: integer; - - } - - /** - * 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 { - /** - * - * @param width The width of the Size component. Default 0. - * @param height The height of the Size component. If not given, it will use the `width`. Default width. - * @param aspectMode The aspect mode of the Size component. Defaults to 0, no mode. Default 0. - * @param parent 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. Default null. - */ - constructor(width?: number, height?: number, aspectMode?: integer, parent?: any); - - /** - * The aspect mode this Size component will use when calculating its dimensions. - * This property is read-only. To change it use the `setAspectMode` method. - */ - readonly aspectMode: integer; - - /** - * The proportional relationship between the width and height. - * - * This property is read-only and is updated automatically when either the `width` or `height` properties are changed, - * depending on the aspect mode. - */ - readonly aspectRatio: number; - - /** - * The minimum allowed width. - * Cannot be less than zero. - * This value is read-only. To change it see the `setMin` method. - */ - readonly minWidth: number; - - /** - * The minimum allowed height. - * Cannot be less than zero. - * This value is read-only. To change it see the `setMin` method. - */ - readonly minHeight: number; - - /** - * The maximum allowed width. - * This value is read-only. To change it see the `setMax` method. - */ - readonly maxWidth: number; - - /** - * The maximum allowed height. - * This value is read-only. To change it see the `setMax` method. - */ - readonly maxHeight: number; - - /** - * A Vector2 containing the horizontal and vertical snap values, which the width and height are snapped to during resizing. - * - * By default this is disabled. - * - * This property is read-only. To change it see the `setSnap` method. - */ - readonly snapTo: Phaser.Math.Vector2; - - /** - * 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. - * @param value The aspect mode value. Default 0. - */ - setAspectMode(value?: integer): this; - - /** - * By setting a Snap To value when this Size component is modified its dimensions will automatically - * by snapped to the nearest grid slice, using floor. For example, if you have snap value of 16, - * and the width changes to 68, then it will snap down to 64 (the closest multiple of 16 when floored) - * - * Note that snapping takes place before adjustments by the parent, or the min / max settings. If these - * values are not multiples of the given snap values, then this can result in un-snapped dimensions. - * - * Call this method with no arguments to reset the snap values. - * - * Calling this method automatically recalculates the `width` and the `height`, if required. - * @param snapWidth The amount to snap the width to. If you don't want to snap the width, pass a value of zero. Default 0. - * @param snapHeight The amount to snap the height to. If not provided it will use the `snapWidth` value. If you don't want to snap the height, pass a value of zero. Default snapWidth. - */ - setSnap(snapWidth?: number, snapHeight?: number): this; - - /** - * 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`. - * @param parent Sets the parent of this Size component. Don't provide a value to clear an existing parent. - */ - setParent(parent?: any): this; - - /** - * 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 exceed in some situations. - * @param width The minimum allowed width of the Size component. Default 0. - * @param height The minimum allowed height of the Size component. If not given, it will use the `width`. Default width. - */ - setMin(width?: number, height?: number): this; - - /** - * 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 exceed in some situations. - * @param width The maximum allowed width of the Size component. Default Number.MAX_VALUE. - * @param height The maximum allowed height of the Size component. If not given, it will use the `width`. Default width. - */ - setMax(width?: number, height?: number): this; - - /** - * 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. - * @param width The new width of the Size component. Default 0. - * @param height The new height of the Size component. If not given, it will use the `width`. Default width. - */ - setSize(width?: number, height?: number): this; - - /** - * Sets a new aspect ratio, overriding what was there previously. - * - * It then calls `setSize` immediately using the current dimensions. - * @param ratio The new aspect ratio. - */ - setAspectRatio(ratio: number): this; - - /** - * 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. - * @param width The new width of the Size component. - * @param height The new height of the Size component. If not given, it will use the `width`. Default width. - */ - resize(width: number, height?: number): this; - - /** - * Takes a new width and passes it through the min/max clamp and then checks it doesn't exceed the parent width. - * @param value The value to clamp and check. - * @param checkParent Check the given value against the parent, if set. Default true. - */ - getNewWidth(value: number, checkParent?: boolean): number; - - /** - * Takes a new height and passes it through the min/max clamp and then checks it doesn't exceed the parent height. - * @param value The value to clamp and check. - * @param checkParent Check the given value against the parent, if set. Default true. - */ - getNewHeight(value: number, checkParent?: boolean): number; - - /** - * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. - * - * If `fit` is true there may be some space inside the target area which is not covered if its aspect ratio differs. - * If `fit` is false the size may extend further out than the target area if the aspect ratios differ. - * - * If this Size component has a parent set, then the width and height passed to this method will be clamped so - * it cannot exceed that of the parent. - * @param width The new width of the Size component. Default 0. - * @param height The new height of the Size component. If not given, it will use the width value. - * @param fit Perform a `fit` (true) constraint, or an `envelop` (false) constraint. Default true. - */ - constrain(width?: number, height?: number, fit?: boolean): this; - - /** - * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. - * - * There may be some space inside the target area which is not covered if its aspect ratio differs. - * - * If this Size component has a parent set, then the width and height passed to this method will be clamped so - * it cannot exceed that of the parent. - * @param width The new width of the Size component. Default 0. - * @param height The new height of the Size component. If not given, it will use the width value. - */ - fitTo(width?: number, height?: number): this; - - /** - * The current `width` and `height` are adjusted so that they fully envelope the given dimensions, while keeping the aspect ratio. - * - * The size may extend further out than the target area if the aspect ratios differ. - * - * If this Size component has a parent set, then the values are clamped so that it never exceeds the parent - * on the longest axis. - * @param width The new width of the Size component. Default 0. - * @param height The new height of the Size component. If not given, it will use the width value. - */ - envelop(width?: number, height?: number): this; - - /** - * Sets the width of this Size component. - * - * Depending on the aspect mode, changing the width may also update the height and aspect ratio. - * @param width The new width of the Size component. - */ - setWidth(width: number): this; - - /** - * Sets the height of this Size component. - * - * Depending on the aspect mode, changing the height may also update the width and aspect ratio. - * @param height The new height of the Size component. - */ - setHeight(height: number): this; - - /** - * Returns a string representation of this Size component. - */ - toString(): string; - - /** - * Sets the values of this Size component to the `element.style.width` and `height` - * properties of the given DOM Element. The properties are set as `px` values. - * @param element The DOM Element to set the CSS style on. - */ - setCSS(element: HTMLElement): void; - - /** - * Copies the aspect mode, aspect ratio, width and height from this Size component - * to the given Size component. Note that the parent, if set, is not copied across. - * @param destination The Size component to copy the values to. - */ - copy(destination: Phaser.Structs.Size): Phaser.Structs.Size; - - /** - * Destroys this Size component. - * - * This clears the local properties and any parent object, if set. - * - * A destroyed Size component cannot be re-used. - */ - destroy(): void; - - /** - * The width of this Size component. - * - * This value is clamped to the range specified by `minWidth` and `maxWidth`, if enabled. - * - * A width can never be less than zero. - * - * Changing this value will automatically update the `height` if the aspect ratio lock is enabled. - * You can also use the `setWidth` and `getWidth` methods. - */ - width: number; - - /** - * The height of this Size component. - * - * This value is clamped to the range specified by `minHeight` and `maxHeight`, if enabled. - * - * A height can never be less than zero. - * - * Changing this value will automatically update the `width` if the aspect ratio lock is enabled. - * You can also use the `setHeight` and `getHeight` methods. - */ - height: number; - - /** - * Do not make the size fit the aspect ratio. Change the ratio when the size changes. - */ - static readonly NONE: integer; - - /** - * The height is automatically adjusted based on the width. - */ - static readonly WIDTH_CONTROLS_HEIGHT: integer; - - /** - * The width is automatically adjusted based on the height. - */ - static readonly HEIGHT_CONTROLS_WIDTH: integer; - - /** - * 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. - */ - static readonly FIT: integer; - - /** - * 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. - */ - static readonly ENVELOP: integer; - - } - - } - - namespace Textures { - /** - * A Canvas Texture is a special kind of Texture that is backed by an HTML Canvas Element as its source. - * - * You can use the properties of this texture to draw to the canvas element directly, using all of the standard - * canvas operations available in the browser. Any Game Object can be given this texture and will render with it. - * - * Note: When running under WebGL the Canvas Texture needs to re-generate its base WebGLTexture and reupload it to - * the GPU every time you modify it, otherwise the changes you make to this texture will not be visible. To do this - * you should call `CanvasTexture.refresh()` once you are finished with your changes to the canvas. Try and keep - * this to a minimum, especially on large canvas sizes, or you may inadvertently thrash the GPU by constantly uploading - * texture data to it. This restriction does not apply if using the Canvas Renderer. - * - * It starts with only one frame that covers the whole of the canvas. You can add further frames, that specify - * sections of the canvas using the `add` method. - * - * Should you need to resize the canvas use the `setSize` method so that it accurately updates all of the underlying - * texture data as well. Forgetting to do this (i.e. by changing the canvas size directly from your code) could cause - * graphical errors. - */ - class CanvasTexture extends Phaser.Textures.Texture { - /** - * - * @param manager A reference to the Texture Manager this Texture belongs to. - * @param key The unique string-based key of this Texture. - * @param source The canvas element that is used as the base of this texture. - * @param width The width of the canvas. - * @param height The height of the canvas. - */ - constructor(manager: Phaser.Textures.TextureManager, key: string, source: HTMLCanvasElement, width: integer, height: integer); - - /** - * The source Canvas Element. - */ - readonly canvas: HTMLCanvasElement; - - /** - * The 2D Canvas Rendering Context. - */ - readonly context: CanvasRenderingContext2D; - - /** - * The width of the Canvas. - * This property is read-only, if you wish to change it use the `setSize` method. - */ - readonly width: integer; - - /** - * The height of the Canvas. - * This property is read-only, if you wish to change it use the `setSize` method. - */ - readonly height: integer; - - /** - * The context image data. - * Use the `update` method to populate this when the canvas changes. - */ - imageData: ImageData; - - /** - * A Uint8ClampedArray view into the `buffer`. - * Use the `update` method to populate this when the canvas changes. - * Note that this is unavailable in some browsers, such as Epic Browser, due to their security restrictions. - */ - data: Uint8ClampedArray; - - /** - * An Uint32Array view into the `buffer`. - */ - pixels: Uint32Array; - - /** - * An ArrayBuffer the same size as the context ImageData. - */ - buffer: ArrayBuffer; - - /** - * This re-creates the `imageData` from the current context. - * It then re-builds the ArrayBuffer, the `data` Uint8ClampedArray reference and the `pixels` Int32Array. - * - * Warning: This is a very expensive operation, so use it sparingly. - */ - update(): Phaser.Textures.CanvasTexture; - - /** - * Draws the given Image or Canvas element to this CanvasTexture, then updates the internal - * ImageData buffer and arrays. - * @param x The x coordinate to draw the source at. - * @param y The y coordinate to draw the source at. - * @param source The element to draw to this canvas. - */ - draw(x: integer, y: integer, source: HTMLImageElement | HTMLCanvasElement): Phaser.Textures.CanvasTexture; - - /** - * Draws the given texture frame to this CanvasTexture, then updates the internal - * ImageData buffer and arrays. - * @param key The unique string-based key of the Texture. - * @param frame The string-based name, or integer based index, of the Frame to get from the Texture. - * @param x The x coordinate to draw the source at. Default 0. - * @param y The y coordinate to draw the source at. Default 0. - */ - drawFrame(key: string, frame?: string | integer, x?: integer, y?: integer): Phaser.Textures.CanvasTexture; - - /** - * Sets a pixel in the CanvasTexture to the given color and alpha values. - * - * This is an expensive operation to run in large quantities, so use sparingly. - * @param x The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param y The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param red The red color value. A number between 0 and 255. - * @param green The green color value. A number between 0 and 255. - * @param blue The blue color value. A number between 0 and 255. - * @param alpha The alpha value. A number between 0 and 255. Default 255. - */ - setPixel(x: integer, y: integer, red: integer, green: integer, blue: integer, alpha?: integer): this; - - /** - * Puts the ImageData into the context of this CanvasTexture at the given coordinates. - * @param imageData The ImageData to put at the given location. - * @param x The x coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param y The y coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param dirtyX Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. Default 0. - * @param dirtyY Vertical position (x coordinate) of the top-left corner from which the image data will be extracted. Default 0. - * @param dirtyWidth Width of the rectangle to be painted. Defaults to the width of the image data. - * @param dirtyHeight Height of the rectangle to be painted. Defaults to the height of the image data. - */ - putData(imageData: ImageData, x: integer, y: integer, dirtyX?: integer, dirtyY?: integer, dirtyWidth?: integer, dirtyHeight?: integer): this; - - /** - * Gets an ImageData region from this CanvasTexture from the position and size specified. - * You can write this back using `CanvasTexture.putData`, or manipulate it. - * @param x The x coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param y The y coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param width The width of the rectangle from which the ImageData will be extracted. Positive values are to the right, and negative to the left. - * @param height The height of the rectangle from which the ImageData will be extracted. Positive values are down, and negative are up. - */ - getData(x: integer, y: integer, width: integer, height: integer): ImageData; - - /** - * Get the color of a specific pixel from this texture and store it in a Color object. - * - * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * @param x The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param y The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param out A Color object to store the pixel values in. If not provided a new Color object will be created. - */ - getPixel(x: integer, y: integer, out?: Phaser.Display.Color): Phaser.Display.Color; - - /** - * Returns an array containing all of the pixels in the given region. - * - * If the requested region extends outside the bounds of this CanvasTexture, - * the region is truncated to fit. - * - * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * @param x The x coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. Default 0. - * @param y The y coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. Default 0. - * @param width The width of the region to get. Must be an integer. Defaults to the canvas width if not given. - * @param height The height of the region to get. Must be an integer. If not given will be set to the `width`. - */ - getPixels(x?: integer, y?: integer, width?: integer, height?: integer): Phaser.Types.Textures.PixelConfig[]; - - /** - * Returns the Image Data index for the given pixel in this CanvasTexture. - * - * The index can be used to read directly from the `this.data` array. - * - * The index points to the red value in the array. The subsequent 3 indexes - * point to green, blue and alpha respectively. - * @param x The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - * @param y The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. - */ - getIndex(x: integer, y: integer): integer; - - /** - * This should be called manually if you are running under WebGL. - * It will refresh the WebGLTexture from the Canvas source. Only call this if you know that the - * canvas has changed, as there is a significant GPU texture allocation cost involved in doing so. - */ - refresh(): Phaser.Textures.CanvasTexture; - - /** - * Gets the Canvas Element. - */ - getCanvas(): HTMLCanvasElement; - - /** - * Gets the 2D Canvas Rendering Context. - */ - getContext(): CanvasRenderingContext2D; - - /** - * Clears the given region of this Canvas Texture, resetting it back to transparent. - * If no region is given, the whole Canvas Texture is cleared. - * @param x The x coordinate of the top-left of the region to clear. Default 0. - * @param y The y coordinate of the top-left of the region to clear. Default 0. - * @param width The width of the region. - * @param height The height of the region. - */ - clear(x?: integer, y?: integer, width?: integer, height?: integer): Phaser.Textures.CanvasTexture; - - /** - * Changes the size of this Canvas Texture. - * @param width The new width of the Canvas. - * @param height The new height of the Canvas. If not given it will use the width as the height. - */ - setSize(width: integer, height?: integer): Phaser.Textures.CanvasTexture; - - /** - * Destroys this Texture and releases references to its sources and frames. - */ - destroy(): void; - - } - - /** - * Filter Types. - */ - enum FilterMode { - /** - * Linear filter type. - */ - LINEAR, - /** - * Nearest neighbor filter type. - */ - NEAREST, - } - - namespace Events { - /** - * The Texture Add Event. - * - * This event is dispatched by the Texture Manager when a texture is added to it. - * - * Listen to this event from within a Scene using: `this.textures.on('addtexture', listener)`. - */ - const ADD: any; - - /** - * The Texture Load Error Event. - * - * This event is dispatched by the Texture Manager when a texture it requested to load failed. - * This only happens when base64 encoded textures fail. All other texture types are loaded via the Loader Plugin. - * - * Listen to this event from within a Scene using: `this.textures.on('onerror', listener)`. - */ - const ERROR: any; - - /** - * The Texture Load Event. - * - * This event is dispatched by the Texture Manager when a texture has finished loading on it. - * This only happens for base64 encoded textures. All other texture types are loaded via the Loader Plugin. - * - * Listen to this event from within a Scene using: `this.textures.on('onload', listener)`. - * - * This event is dispatched after the [ADD]{@linkcode Phaser.Textures.Events#event:ADD} event. - */ - const LOAD: any; - - /** - * This internal event signifies that the Texture Manager is now ready and the Game can continue booting. - * - * When a Phaser Game instance is booting for the first time, the Texture Manager has to wait on a couple of non-blocking - * async events before it's fully ready to carry on. When those complete the Texture Manager emits this event via the Game - * instance, which tells the Game to carry on booting. - */ - const READY: any; - - /** - * The Texture Remove Event. - * - * This event is dispatched by the Texture Manager when a texture is removed from it. - * - * Listen to this event from within a Scene using: `this.textures.on('removetexture', listener)`. - * - * If you have any Game Objects still using the removed texture, they will start throwing - * errors the next time they try to render. Be sure to clear all use of the texture in this event handler. - */ - const REMOVE: any; - - } - - /** - * A Frame is a section of a Texture. - */ - class Frame { - /** - * - * @param texture The Texture this Frame is a part of. - * @param name The name of this Frame. The name is unique within the Texture. - * @param sourceIndex The index of the TextureSource that this Frame is a part of. - * @param x The x coordinate of the top-left of this Frame. - * @param y The y coordinate of the top-left of this Frame. - * @param width The width of this Frame. - * @param height The height of this Frame. - */ - constructor(texture: Phaser.Textures.Texture, name: integer | string, sourceIndex: integer, x: number, y: number, width: number, height: number); - - /** - * The Texture this Frame is a part of. - */ - texture: Phaser.Textures.Texture; - - /** - * The name of this Frame. - * The name is unique within the Texture. - */ - name: string; - - /** - * The TextureSource this Frame is part of. - */ - source: Phaser.Textures.TextureSource; - - /** - * The index of the TextureSource in the Texture sources array. - */ - sourceIndex: integer; - - /** - * A reference to the Texture Source WebGL Texture that this Frame is using. - */ - glTexture: WebGLTexture; - - /** - * X position within the source image to cut from. - */ - cutX: integer; - - /** - * Y position within the source image to cut from. - */ - cutY: integer; - - /** - * The width of the area in the source image to cut. - */ - cutWidth: integer; - - /** - * The height of the area in the source image to cut. - */ - cutHeight: integer; - - /** - * The X rendering offset of this Frame, taking trim into account. - */ - x: integer; - - /** - * The Y rendering offset of this Frame, taking trim into account. - */ - y: integer; - - /** - * The rendering width of this Frame, taking trim into account. - */ - width: integer; - - /** - * The rendering height of this Frame, taking trim into account. - */ - height: integer; - - /** - * Half the width, floored. - * Precalculated for the renderer. - */ - halfWidth: integer; - - /** - * Half the height, floored. - * Precalculated for the renderer. - */ - halfHeight: integer; - - /** - * The x center of this frame, floored. - */ - centerX: integer; - - /** - * The y center of this frame, floored. - */ - centerY: integer; - - /** - * The horizontal pivot point of this Frame. - */ - pivotX: number; - - /** - * The vertical pivot point of this Frame. - */ - pivotY: number; - - /** - * Does this Frame have a custom pivot point? - */ - customPivot: boolean; - - /** - * **CURRENTLY UNSUPPORTED** - * - * Is this frame is rotated or not in the Texture? - * Rotation allows you to use rotated frames in texture atlas packing. - * It has nothing to do with Sprite rotation. - */ - rotated: boolean; - - /** - * Over-rides the Renderer setting. - * -1 = use Renderer Setting - * 0 = No rounding - * 1 = Round - */ - autoRound: integer; - - /** - * Any Frame specific custom data can be stored here. - */ - customData: object; - - /** - * WebGL UV u0 value. - */ - u0: number; - - /** - * WebGL UV v0 value. - */ - v0: number; - - /** - * WebGL UV u1 value. - */ - u1: number; - - /** - * WebGL UV v1 value. - */ - v1: number; - - /** - * Sets the width, height, x and y of this Frame. - * - * This is called automatically by the constructor - * and should rarely be changed on-the-fly. - * @param width The width of the frame before being trimmed. - * @param height The height of the frame before being trimmed. - * @param x The x coordinate of the top-left of this Frame. Default 0. - * @param y The y coordinate of the top-left of this Frame. Default 0. - */ - setSize(width: integer, height: integer, x?: integer, y?: integer): Phaser.Textures.Frame; - - /** - * If the frame was trimmed when added to the Texture Atlas, this records the trim and source data. - * @param actualWidth The width of the frame before being trimmed. - * @param actualHeight The height of the frame before being trimmed. - * @param destX The destination X position of the trimmed frame for display. - * @param destY The destination Y position of the trimmed frame for display. - * @param destWidth The destination width of the trimmed frame for display. - * @param destHeight The destination height of the trimmed frame for display. - */ - setTrim(actualWidth: number, actualHeight: number, destX: number, destY: number, destWidth: number, destHeight: number): Phaser.Textures.Frame; - - /** - * 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. - * - * This is called directly by the Game Object Texture Components `setCrop` method. - * Please use that method to crop a Game Object. - * @param crop The crop data object. This is the `GameObject._crop` property. - * @param x The x coordinate to start the crop from. Cannot be negative or exceed the Frame width. - * @param y The y coordinate to start the crop from. Cannot be negative or exceed the Frame height. - * @param width The width of the crop rectangle. Cannot exceed the Frame width. - * @param height The height of the crop rectangle. Cannot exceed the Frame height. - * @param flipX Does the parent Game Object have flipX set? - * @param flipY Does the parent Game Object have flipY set? - */ - setCropUVs(crop: object, x: number, y: number, width: number, height: number, flipX: boolean, flipY: boolean): object; - - /** - * Takes a crop data object and recalculates the UVs based on the dimensions inside the crop object. - * Called automatically by `setFrame`. - * @param crop The crop data object. This is the `GameObject._crop` property. - * @param flipX Does the parent Game Object have flipX set? - * @param flipY Does the parent Game Object have flipY set? - */ - updateCropUVs(crop: object, flipX: boolean, flipY: boolean): object; - - /** - * Updates the internal WebGL UV cache and the drawImage cache. - */ - updateUVs(): Phaser.Textures.Frame; - - /** - * Updates the internal WebGL UV cache. - */ - updateUVsInverted(): Phaser.Textures.Frame; - - /** - * Clones this Frame into a new Frame object. - */ - clone(): Phaser.Textures.Frame; - - /** - * Destroys this Frame by nulling its reference to the parent Texture and and data objects. - */ - destroy(): void; - - /** - * The width of the Frame in its un-trimmed, un-padded state, as prepared in the art package, - * before being packed. - */ - readonly realWidth: number; - - /** - * The height of the Frame in its un-trimmed, un-padded state, as prepared in the art package, - * before being packed. - */ - readonly realHeight: number; - - /** - * The radius of the Frame (derived from sqrt(w * w + h * h) / 2) - */ - readonly radius: number; - - /** - * Is the Frame trimmed or not? - */ - readonly trimmed: boolean; - - /** - * The Canvas drawImage data object. - */ - readonly canvasData: object; - - } - - /** - * Linear filter type. - */ - const LINEAR: integer; - - /** - * Nearest Neighbor filter type. - */ - const NEAREST: integer; - - namespace Parsers { - } - - /** - * A Texture consists of a source, usually an Image from the Cache, and a collection of Frames. - * The Frames represent the different areas of the Texture. For example a texture atlas - * may have many Frames, one for each element within the atlas. Where-as a single image would have - * just one frame, that encompasses the whole image. - * - * Every Texture, no matter where it comes from, always has at least 1 frame called the `__BASE` frame. - * This frame represents the entirety of the source image. - * - * Textures are managed by the global TextureManager. This is a singleton class that is - * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. - * - * Sprites and other Game Objects get the texture data they need from the TextureManager. - */ - class Texture { - /** - * - * @param manager A reference to the Texture Manager this Texture belongs to. - * @param key The unique string-based key of this Texture. - * @param source An array of sources that are used to create the texture. Usually Images, but can also be a Canvas. - * @param width The width of the Texture. This is optional and automatically derived from the source images. - * @param height The height of the Texture. This is optional and automatically derived from the source images. - */ - constructor(manager: Phaser.Textures.TextureManager, key: string, source: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[], width?: number, height?: number); - - /** - * A reference to the Texture Manager this Texture belongs to. - */ - manager: Phaser.Textures.TextureManager; - - /** - * The unique string-based key of this Texture. - */ - key: string; - - /** - * An array of TextureSource instances. - * These are unique to this Texture and contain the actual Image (or Canvas) data. - */ - source: Phaser.Textures.TextureSource[]; - - /** - * An array of TextureSource data instances. - * Used to store additional data images, such as normal maps or specular maps. - */ - dataSource: any[]; - - /** - * A key-value object pair associating the unique Frame keys with the Frames objects. - */ - frames: object; - - /** - * Any additional data that was set in the source JSON (if any), - * or any extra data you'd like to store relating to this texture - */ - customData: object; - - /** - * The name of the first frame of the Texture. - */ - firstFrame: string; - - /** - * The total number of Frames in this Texture, including the `__BASE` frame. - * - * A Texture will always contain at least 1 frame because every Texture contains a `__BASE` frame by default, - * in addition to any extra frames that have been added to it, such as when parsing a Sprite Sheet or Texture Atlas. - */ - frameTotal: integer; - - /** - * Adds a new Frame to this Texture. - * - * A Frame is a rectangular region of a TextureSource with a unique index or string-based key. - * - * The name given must be unique within this Texture. If it already exists, this method will return `null`. - * @param name The name of this Frame. The name is unique within the Texture. - * @param sourceIndex The index of the TextureSource that this Frame is a part of. - * @param x The x coordinate of the top-left of this Frame. - * @param y The y coordinate of the top-left of this Frame. - * @param width The width of this Frame. - * @param height The height of this Frame. - */ - add(name: integer | string, sourceIndex: integer, x: number, y: number, width: number, height: number): Phaser.Textures.Frame; - - /** - * Removes the given Frame from this Texture. The Frame is destroyed immediately. - * - * Any Game Objects using this Frame should stop using it _before_ you remove it, - * as it does not happen automatically. - * @param name The key of the Frame to remove. - */ - remove(name: string): boolean; - - /** - * Checks to see if a Frame matching the given key exists within this Texture. - * @param name The key of the Frame to check for. - */ - has(name: string): boolean; - - /** - * 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. - * @param name The string-based name, or integer based index, of the Frame to get from this Texture. - */ - get(name?: string | integer): Phaser.Textures.Frame; - - /** - * Takes the given TextureSource and returns the index of it within this Texture. - * If it's not in this Texture, it returns -1. - * Unless this Texture has multiple TextureSources, such as with a multi-atlas, this - * method will always return zero or -1. - * @param source The TextureSource to check. - */ - getTextureSourceIndex(source: Phaser.Textures.TextureSource): integer; - - /** - * Returns an array of all the Frames in the given TextureSource. - * @param sourceIndex The index of the TextureSource to get the Frames from. - * @param includeBase Include the `__BASE` Frame in the output array? Default false. - */ - getFramesFromTextureSource(sourceIndex: integer, includeBase?: boolean): Phaser.Textures.Frame[]; - - /** - * Returns an array with all of the names of the Frames in this Texture. - * - * Useful if you want to randomly assign a Frame to a Game Object, as you can - * pick a random element from the returned array. - * @param includeBase Include the `__BASE` Frame in the output array? Default false. - */ - getFrameNames(includeBase?: boolean): string[]; - - /** - * Given a Frame name, return the source image it uses to render with. - * - * This will return the actual DOM Image or Canvas element. - * @param name The string-based name, or integer based index, of the Frame to get from this Texture. - */ - getSourceImage(name?: string | integer): HTMLImageElement | HTMLCanvasElement | Phaser.GameObjects.RenderTexture; - - /** - * Given a Frame name, return the data source image it uses to render with. - * You can use this to get the normal map for an image for example. - * - * This will return the actual DOM Image. - * @param name The string-based name, or integer based index, of the Frame to get from this Texture. - */ - getDataSourceImage(name?: string | integer): HTMLImageElement | HTMLCanvasElement; - - /** - * Adds a data source image to this Texture. - * - * An example of a data source image would be a normal map, where all of the Frames for this Texture - * equally apply to the normal map. - * @param data The source image. - */ - setDataSource(data: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): void; - - /** - * Sets the Filter Mode for this Texture. - * - * The mode can be either Linear, the default, or Nearest. - * - * For pixel-art you should use Nearest. - * - * The mode applies to the entire Texture, not just a specific Frame of it. - * @param filterMode The Filter Mode. - */ - setFilter(filterMode: Phaser.Textures.FilterMode): void; - - /** - * Destroys this Texture and releases references to its sources and frames. - */ - destroy(): void; - - } - - /** - * Textures are managed by the global TextureManager. This is a singleton class that is - * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. - * - * Sprites and other Game Objects get the texture data they need from the TextureManager. - * - * Access it via `scene.textures`. - */ - class TextureManager extends Phaser.Events.EventEmitter { - /** - * - * @param game The Phaser.Game instance this Texture Manager belongs to. - */ - constructor(game: Phaser.Game); - - /** - * The Game that this TextureManager belongs to. - */ - game: Phaser.Game; - - /** - * The name of this manager. - */ - name: string; - - /** - * An object that has all of textures that Texture Manager creates. - * Textures are assigned to keys so we can access to any texture that this object has directly by key value without iteration. - */ - list: object; - - /** - * Checks the given texture key and throws a console.warn if the key is already in use, then returns false. - * If you wish to avoid the console.warn then use `TextureManager.exists` instead. - * @param key The texture key to check. - */ - checkKey(key: string): boolean; - - /** - * Removes a Texture from the Texture Manager and destroys it. This will immediately - * clear all references to it from the Texture Manager, and if it has one, destroy its - * WebGLTexture. This will emit a `removetexture` event. - * - * Note: If you have any Game Objects still using this texture they will start throwing - * errors the next time they try to render. Make sure that removing the texture is the final - * step when clearing down to avoid this. - * @param key The key of the Texture to remove, or a reference to it. - */ - remove(key: string | Phaser.Textures.Texture): Phaser.Textures.TextureManager; - - /** - * Removes a key from the Texture Manager but does not destroy the Texture that was using the key. - * @param key The key to remove from the texture list. - */ - removeKey(key: string): Phaser.Textures.TextureManager; - - /** - * Adds a new Texture to the Texture Manager created from the given Base64 encoded data. - * @param key The unique string-based key of the Texture. - * @param data The Base64 encoded data. - */ - addBase64(key: string, data: any): this; - - /** - * Gets an existing texture frame and converts it into a base64 encoded image and returns the base64 data. - * - * You can also provide the image type and encoder options. - * - * This will only work with bitmap based texture frames, such as those created from Texture Atlases. - * It will not work with GL Texture objects, such as Shaders, or Render Textures. For those please - * see the WebGL Snapshot function instead. - * @param key The unique string-based key of the Texture. - * @param frame The string-based name, or integer based index, of the Frame to get from the Texture. - * @param type [description] Default 'image/png'. - * @param encoderOptions [description] Default 0.92. - */ - getBase64(key: string, frame?: string | integer, type?: string, encoderOptions?: number): string; - - /** - * Adds a new Texture to the Texture Manager created from the given Image element. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param dataSource An optional data Image element. - */ - addImage(key: string, source: HTMLImageElement, dataSource?: HTMLImageElement | HTMLCanvasElement): Phaser.Textures.Texture; - - /** - * Takes a WebGL Texture and creates a Phaser Texture from it, which is added to the Texture Manager using the given key. - * - * This allows you to then use the Texture as a normal texture for texture based Game Objects like Sprites. - * - * This is a WebGL only feature. - * @param key The unique string-based key of the Texture. - * @param glTexture The source Render Texture. - * @param width The new width of the Texture. - * @param height The new height of the Texture. - */ - addGLTexture(key: string, glTexture: WebGLTexture, width: number, height: number): Phaser.Textures.Texture; - - /** - * Adds a Render Texture to the Texture Manager using the given key. - * This allows you to then use the Render Texture as a normal texture for texture based Game Objects like Sprites. - * @param key The unique string-based key of the Texture. - * @param renderTexture The source Render Texture. - */ - addRenderTexture(key: string, renderTexture: Phaser.GameObjects.RenderTexture): Phaser.Textures.Texture; - - /** - * Creates a new Texture using the given config values. - * Generated textures consist of a Canvas element to which the texture data is drawn. - * See the Phaser.Create function for the more direct way to create textures. - * @param key The unique string-based key of the Texture. - * @param config The configuration object needed to generate the texture. - */ - generate(key: string, config: object): Phaser.Textures.Texture; - - /** - * Creates a new Texture using a blank Canvas element of the size given. - * - * Canvas elements are automatically pooled and calling this method will - * extract a free canvas from the CanvasPool, or create one if none are available. - * @param key The unique string-based key of the Texture. - * @param width The width of the Canvas element. Default 256. - * @param height The height of the Canvas element. Default 256. - */ - createCanvas(key: string, width?: integer, height?: integer): Phaser.Textures.CanvasTexture; - - /** - * Creates a new Canvas Texture object from an existing Canvas element - * and adds it to this Texture Manager, unless `skipCache` is true. - * @param key The unique string-based key of the Texture. - * @param source The Canvas element to form the base of the new Texture. - * @param skipCache Skip adding this Texture into the Cache? Default false. - */ - addCanvas(key: string, source: HTMLCanvasElement, skipCache?: boolean): Phaser.Textures.CanvasTexture; - - /** - * Adds a new Texture Atlas to this Texture Manager. - * It can accept either JSON Array or JSON Hash formats, as exported by Texture Packer and similar software. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param data The Texture Atlas data. - * @param dataSource An optional data Image element. - */ - addAtlas(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; - - /** - * Adds a Texture Atlas to this Texture Manager. - * The frame data of the atlas must be stored in an Array within the JSON. - * This is known as a JSON Array in software such as Texture Packer. - * @param key The unique string-based key of the Texture. - * @param source The source Image element/s. - * @param data The Texture Atlas data/s. - * @param dataSource An optional data Image element. - */ - addAtlasJSONArray(key: string, source: HTMLImageElement | HTMLImageElement[], data: object | object[], dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; - - /** - * Adds a Texture Atlas to this Texture Manager. - * The frame data of the atlas must be stored in an Object within the JSON. - * This is known as a JSON Hash in software such as Texture Packer. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param data The Texture Atlas data. - * @param dataSource An optional data Image element. - */ - addAtlasJSONHash(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; - - /** - * Adds a Texture Atlas to this Texture Manager, where the atlas data is given - * in the XML format. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param data The Texture Atlas XML data. - * @param dataSource An optional data Image element. - */ - addAtlasXML(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; - - /** - * Adds a Unity Texture Atlas to this Texture Manager. - * The data must be in the form of a Unity YAML file. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param data The Texture Atlas data. - * @param dataSource An optional data Image element. - */ - addUnityAtlas(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; - - /** - * Adds a Sprite Sheet to this Texture Manager. - * - * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact - * same size and cannot be trimmed or rotated. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param config The configuration object for this Sprite Sheet. - */ - addSpriteSheet(key: string, source: HTMLImageElement, config: Phaser.Types.Textures.SpriteSheetConfig): Phaser.Textures.Texture; - - /** - * Adds a Sprite Sheet to this Texture Manager, where the Sprite Sheet exists as a Frame within a Texture Atlas. - * - * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact - * same size and cannot be trimmed or rotated. - * @param key The unique string-based key of the Texture. - * @param config The configuration object for this Sprite Sheet. - */ - addSpriteSheetFromAtlas(key: string, config: Phaser.Types.Textures.SpriteSheetFromAtlasConfig): Phaser.Textures.Texture; - - /** - * Creates a new Texture using the given source and dimensions. - * @param key The unique string-based key of the Texture. - * @param source The source Image element. - * @param width The width of the Texture. - * @param height The height of the Texture. - */ - create(key: string, source: HTMLImageElement, width: integer, height: integer): Phaser.Textures.Texture; - - /** - * Checks the given key to see if a Texture using it exists within this Texture Manager. - * @param key The unique string-based key of the Texture. - */ - exists(key: string): boolean; - - /** - * Returns a Texture from the Texture Manager that matches the given key. - * - * If the key is `undefined` it will return the `__DEFAULT` Texture. - * - * If the key is an instance of a Texture, it will return the key directly. - * - * Finally. if the key is given, but not found and not a Texture instance, it will return the `__MISSING` Texture. - * @param key The unique string-based key of the Texture, or a Texture instance. - */ - get(key: string | Phaser.Textures.Texture): Phaser.Textures.Texture; - - /** - * Takes a Texture key and Frame name and returns a clone of that Frame if found. - * @param key The unique string-based key of the Texture. - * @param frame The string or index of the Frame to be cloned. - */ - cloneFrame(key: string, frame: string | integer): Phaser.Textures.Frame; - - /** - * Takes a Texture key and Frame name and returns a reference to that Frame, if found. - * @param key The unique string-based key of the Texture. - * @param frame The string-based name, or integer based index, of the Frame to get from the Texture. - */ - getFrame(key: string, frame?: string | integer): Phaser.Textures.Frame; - - /** - * Returns an array with all of the keys of all Textures in this Texture Manager. - * The output array will exclude the `__DEFAULT` and `__MISSING` keys. - */ - getTextureKeys(): string[]; - - /** - * Given a Texture and an `x` and `y` coordinate this method will return a new - * Color object that has been populated with the color and alpha values of the pixel - * at that location in the Texture. - * @param x The x coordinate of the pixel within the Texture. - * @param y The y coordinate of the pixel within the Texture. - * @param key The unique string-based key of the Texture. - * @param frame The string or index of the Frame. - */ - getPixel(x: integer, y: integer, key: string, frame?: string | integer): Phaser.Display.Color; - - /** - * Given a Texture and an `x` and `y` coordinate this method will return a value between 0 and 255 - * corresponding to the alpha value of the pixel at that location in the Texture. If the coordinate - * is out of bounds it will return null. - * @param x The x coordinate of the pixel within the Texture. - * @param y The y coordinate of the pixel within the Texture. - * @param key The unique string-based key of the Texture. - * @param frame The string or index of the Frame. - */ - getPixelAlpha(x: integer, y: integer, key: string, frame?: string | integer): integer; - - /** - * Sets the given Game Objects `texture` and `frame` properties so that it uses - * the Texture and Frame specified in the `key` and `frame` arguments to this method. - * @param gameObject The Game Object the texture would be set on. - * @param key The unique string-based key of the Texture. - * @param frame The string or index of the Frame. - */ - setTexture(gameObject: Phaser.GameObjects.GameObject, key: string, frame?: string | integer): Phaser.GameObjects.GameObject; - - /** - * Changes the key being used by a Texture to the new key provided. - * - * The old key is removed, allowing it to be re-used. - * - * Game Objects are linked to Textures by a reference to the Texture object, so - * all existing references will be retained. - * @param currentKey The current string-based key of the Texture you wish to rename. - * @param newKey The new unique string-based key to use for the Texture. - */ - renameTexture(currentKey: string, newKey: string): boolean; - - /** - * Passes all Textures to the given callback. - * @param callback The callback function to be sent the Textures. - * @param scope The value to use as `this` when executing the callback. - * @param args Additional arguments that will be passed to the callback, after the child. - */ - each(callback: EachTextureCallback, scope: object, ...args: any[]): void; - - /** - * Destroys the Texture Manager and all Textures stored within it. - */ - destroy(): void; - - } - - /** - * A Texture Source is the encapsulation of the actual source data for a Texture. - * - * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element. - * - * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded. - */ - class TextureSource { - /** - * - * @param texture The Texture this TextureSource belongs to. - * @param source The source image data. - * @param width Optional width of the source image. If not given it's derived from the source itself. - * @param height Optional height of the source image. If not given it's derived from the source itself. - * @param flipY Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. Default false. - */ - constructor(texture: Phaser.Textures.Texture, source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | Phaser.GameObjects.RenderTexture | WebGLTexture, width?: integer, height?: integer, flipY?: boolean); - - /** - * The Texture this TextureSource belongs to. - */ - renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; - - /** - * The Texture this TextureSource belongs to. - */ - texture: Phaser.Textures.Texture; - - /** - * The source of the image data. - * - * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture. - */ - source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | Phaser.GameObjects.RenderTexture | WebGLTexture; - - /** - * The image data. - * - * This is either an Image element, Canvas element or a Video Element. - */ - image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; - - /** - * Currently un-used. - */ - compressionAlgorithm: integer; - - /** - * The resolution of the source image. - */ - resolution: number; - - /** - * The width of the source image. If not specified in the constructor it will check - * the `naturalWidth` and then `width` properties of the source image. - */ - width: integer; - - /** - * The height of the source image. If not specified in the constructor it will check - * the `naturalHeight` and then `height` properties of the source image. - */ - height: integer; - - /** - * The Scale Mode the image will use when rendering. - * Either Linear or Nearest. - */ - scaleMode: number; - - /** - * Is the source image a Canvas Element? - */ - isCanvas: boolean; - - /** - * Is the source image a Video Element? - */ - isVideo: boolean; - - /** - * Is the source image a Render Texture? - */ - isRenderTexture: boolean; - - /** - * Is the source image a WebGLTexture? - */ - isGLTexture: boolean; - - /** - * Are the source image dimensions a power of two? - */ - isPowerOf2: boolean; - - /** - * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture - * already, then this is a reference to that WebGLTexture. - */ - glTexture: WebGLTexture; - - /** - * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. - */ - flipY: boolean; - - /** - * Creates a WebGL Texture, if required, and sets the Texture filter mode. - * @param game A reference to the Phaser Game instance. - */ - init(game: Phaser.Game): void; - - /** - * Sets the Filter Mode for this Texture. - * - * The mode can be either Linear, the default, or Nearest. - * - * For pixel-art you should use Nearest. - * @param filterMode The Filter Mode. - */ - setFilter(filterMode: Phaser.Textures.FilterMode): void; - - /** - * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload. - * @param value Should the WebGL Texture be flipped on the Y axis on texture upload or not? Default true. - */ - setFlipY(value?: boolean): void; - - /** - * If this TextureSource is backed by a Canvas and is running under WebGL, - * it updates the WebGLTexture using the canvas data. - */ - update(): void; - - /** - * Destroys this Texture Source and nulls the references. - */ - destroy(): void; - - } - - } - - namespace Tilemaps { - namespace Components { - } - - /** - * A Dynamic Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination - * with one, or more, Tilesets. - * - * A Dynamic Tilemap Layer trades some speed for being able to apply powerful effects. Unlike a - * Static Tilemap Layer, you can apply per-tile effects like tint or alpha, and you can change the - * tiles in a DynamicTilemapLayer. - * - * Use this over a Static Tilemap Layer when you need those features. - */ - class DynamicTilemapLayer extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { - /** - * - * @param scene The Scene to which this Game Object belongs. - * @param tilemap The Tilemap this layer is a part of. - * @param layerIndex The index of the LayerData associated with this layer. - * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param x The world x position where the top left of this layer will be placed. Default 0. - * @param y The world y position where the top left of this layer will be placed. Default 0. - */ - constructor(scene: Phaser.Scene, tilemap: Phaser.Tilemaps.Tilemap, layerIndex: integer, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number); - - /** - * Used internally by physics system to perform fast type checks. - */ - readonly isTilemap: boolean; - - /** - * The Tilemap that this layer is a part of. - */ - tilemap: Phaser.Tilemaps.Tilemap; - - /** - * The index of the LayerData associated with this layer. - */ - layerIndex: integer; - - /** - * The LayerData associated with this layer. LayerData can only be associated with one - * tilemap layer. - */ - layer: Phaser.Tilemaps.LayerData; - - /** - * The Tileset/s associated with this layer. - * - * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. - */ - tileset: Phaser.Tilemaps.Tileset[]; - - /** - * Used internally with the canvas render. This holds the tiles that are visible within the - * camera. - */ - culledTiles: any[]; - - /** - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this, and toggling this flag allows - * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. - */ - skipCull: boolean; - - /** - * The total number of tiles drawn by the renderer in the last frame. - */ - readonly tilesDrawn: integer; - - /** - * The total number of tiles in this layer. Updated every frame. - */ - readonly tilesTotal: integer; - - /** - * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. - * - * See the method `setCullPadding` for more details. - */ - cullPaddingX: integer; - - /** - * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. - * - * See the method `setCullPadding` for more details. - */ - cullPaddingY: integer; - - /** - * The callback that is invoked when the tiles are culled. - * - * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. - * - * It will be sent 3 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. - * - * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. - */ - cullCallback: Function; - - /** - * An array holding the mapping between the tile indexes and the tileset they belong to. - */ - gidMap: Phaser.Tilemaps.Tileset[]; - - /** - * Sets the rendering (draw) order of the tiles in this layer. - * - * The default is 'right-down', meaning it will order the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * Setting the render order does not change the tiles or how they are stored in the layer, - * it purely impacts the order in which they are rendered. - * - * You can provide either an integer (0 to 3), or the string version of the order. - * @param renderOrder The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. - */ - setRenderOrder(renderOrder: integer | string): this; - - /** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * @param tileX The x coordinate. - * @param tileY The y coordinate. - */ - calculateFacesAt(tileX: integer, tileY: integer): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - */ - calculateFacesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * @param indexes The tile index, or array of indexes, to create Sprites from. - * @param replacements The tile index, or array of indexes, to change a converted - * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a - * one-to-one mapping with the indexes array. - * @param spriteConfig The config object to pass into the Sprite creator (i.e. - * scene.make.sprite). - * @param scene The Scene to create the Sprites within. Default scene the map is within. - * @param camera The Camera to use when determining the world XY Default main camera. - */ - createFromTiles(indexes: integer | any[], replacements: integer | any[], spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.GameObjects.Sprite[]; - - /** - * Returns the tiles in the given layer that are within the cameras viewport. - * This is used internally. - * @param camera The Camera to run the cull check against. - */ - cull(camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; - - /** - * Copies the tiles in the source rectangular area to a new destination (all specified in tile - * coordinates) within the layer. This copies all tile properties & recalculates collision - * information in the destination region. - * @param srcTileX The x coordinate of the area to copy from, in tiles, not pixels. - * @param srcTileY The y coordinate of the area to copy from, in tiles, not pixels. - * @param width The width of the area to copy, in tiles, not pixels. - * @param height The height of the area to copy, in tiles, not pixels. - * @param destTileX The x coordinate of the area to copy to, in tiles, not pixels. - * @param destTileY The y coordinate of the area to copy to, in tiles, not pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - */ - copy(srcTileX: integer, srcTileY: integer, width: integer, height: integer, destTileX: integer, destTileY: integer, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Destroys this DynamicTilemapLayer and removes its link to the associated LayerData. - * @param removeFromTilemap Remove this layer from the parent Tilemap? Default true. - */ - destroy(removeFromTilemap?: boolean): void; - - /** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * @param index The tile index to fill the area with. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - */ - fill(index: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * @param callback The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - filterTiles(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; - - /** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * @param index The tile index value to search for. - * @param skip The number of times to skip a matching tile before returning. Default 0. - * @param reverse If true it will scan the layer in reverse, starting at the - * bottom-right. Otherwise it scans from the top-left. Default false. - */ - findByIndex(index: integer, skip?: integer, reverse?: boolean): Phaser.Tilemaps.Tile; - - /** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - findTile(callback: FindTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile; - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - forEachTile(callback: EachTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Gets a tile at the given tile coordinates from the given layer. - * @param tileX X position to get the tile from (given in tile units, not pixels). - * @param tileY Y position to get the tile from (given in tile units, not pixels). - * @param nonNull If true getTile won't return null for empty tiles, but a Tile object with an index of -1. Default false. - */ - getTileAt(tileX: integer, tileY: integer, nonNull?: boolean): Phaser.Tilemaps.Tile; - - /** - * Gets a tile at the given world coordinates from the given layer. - * @param worldX X position to get the tile from (given in pixels) - * @param worldY Y position to get the tile from (given in pixels) - * @param nonNull If true, function won't return null for empty tiles, but a Tile object with an index of -1. Default false. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - getTileAtWorldXY(worldX: number, worldY: number, nonNull?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; - - /** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - getTilesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; - - /** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * @param shape A shape in world (pixel) coordinates - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - */ - getTilesWithinShape(shape: Phaser.Geom.Circle | Phaser.Geom.Line | Phaser.Geom.Rectangle | Phaser.Geom.Triangle, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; - - /** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * @param worldX The world x coordinate for the top-left of the area. - * @param worldY The world y coordinate for the top-left of the area. - * @param width The width of the area. - * @param height The height of the area. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - */ - getTilesWithinWorldXY(worldX: number, worldY: number, width: number, height: number, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; - - /** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - */ - hasTileAt(tileX: integer, tileY: integer): boolean; - - /** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * @param worldX The x coordinate, in pixels. - * @param worldY The y coordinate, in pixels. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - */ - hasTileAtWorldXY(worldX: number, worldY: number, camera?: Phaser.Cameras.Scene2D.Camera): boolean; - - /** - * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index - * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified - * location. If you pass in an index, only the index at the specified location will be changed. - * Collision information will be recalculated at the specified location. - * @param tile The index of this tile to set or a Tile object. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - */ - putTileAt(tile: integer | Phaser.Tilemaps.Tile, tileX: integer, tileY: integer, recalculateFaces?: boolean): Phaser.Tilemaps.Tile; - - /** - * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either - * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the - * specified location. If you pass in an index, only the index at the specified location will be - * changed. Collision information will be recalculated at the specified location. - * @param tile The index of this tile to set or a Tile object. - * @param worldX The x coordinate, in pixels. - * @param worldY The y coordinate, in pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - putTileAtWorldXY(tile: integer | Phaser.Tilemaps.Tile, worldX: number, worldY: number, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; - - /** - * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified - * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, - * all attributes will be copied over to the specified location. If you pass in an index, only the - * index at the specified location will be changed. Collision information will be recalculated - * within the region tiles were changed. - * @param tile A row (array) or grid (2D array) of Tiles or tile indexes to place. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - */ - putTilesAt(tile: integer[] | integer[][] | Phaser.Tilemaps.Tile[] | Phaser.Tilemaps.Tile[][], tileX: integer, tileY: integer, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then - * those will be used for randomly assigning new tile indexes. If an array is not provided, the - * indexes found within the region (excluding -1) will be used for randomly assigning new tile - * indexes. This method only modifies tile indexes and does not change collision information. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param indexes An array of indexes to randomly draw from during randomization. - */ - randomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, indexes?: integer[]): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Removes the tile at the given tile coordinates in the specified layer and updates the layer's - * collision information. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - */ - removeTileAt(tileX: integer, tileY: integer, replaceWithNull?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.Tile; - - /** - * Removes the tile at the given world coordinates in the specified layer and updates the layer's - * collision information. - * @param worldX The x coordinate, in pixels. - * @param worldY The y coordinate, in pixels. - * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - removeTileAtWorldXY(worldX: number, worldY: number, replaceWithNull?: boolean, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; - - /** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * @param graphics The target Graphics object to draw upon. - * @param styleConfig An object specifying the colors to use for the debug drawing. - */ - renderDebug(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does - * not change collision information. - * @param findIndex The index of the tile to search for. - * @param newIndex The index of the tile to replace it with. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - */ - replaceByIndex(findIndex: integer, newIndex: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this. - * @param value Set to `true` to stop culling tiles. Set to `false` to enable culling again. Default true. - */ - setSkipCull(value?: boolean): this; - - /** - * When a Camera culls the tiles in this layer it does so using its view into the world, building up a - * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size - * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so - * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px - * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) - * @param paddingX The amount of extra horizontal tiles to add to the cull check padding. Default 1. - * @param paddingY The amount of extra vertical tiles to add to the cull check padding. Default 1. - */ - setCullPadding(paddingX?: integer, paddingY?: integer): this; - - /** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * @param indexes Either a single tile index, or an array of tile indexes. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - * @param updateLayer If true, updates the current tiles on the layer. Set to - * false if no tiles have been placed for significant performance boost. Default true. - */ - setCollision(indexes: integer | any[], collides?: boolean, recalculateFaces?: boolean, updateLayer?: boolean): Phaser.Tilemaps.Tilemap; - - /** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * @param start The first index of the tile to be set for collision. - * @param stop The last index of the tile to be set for collision. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - */ - setCollisionBetween(start: integer, stop: integer, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * @param properties An object with tile properties and corresponding values that should be checked. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - */ - setCollisionByProperty(properties: object, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * @param indexes An array of the tile indexes to not be counted for collision. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - */ - setCollisionByExclusion(indexes: integer[], collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Sets collision on the tiles within a layer by checking each tiles collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tiles collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - */ - setCollisionFromCollisionGroup(collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * @param indexes Either a single tile index, or an array of tile indexes to have a collision callback set for. - * @param callback The callback that will be invoked when the tile is collided with. - * @param callbackContext The context under which the callback is called. - */ - setTileIndexCallback(indexes: integer | integer[], callback: Function, callbackContext: object): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param callback The callback that will be invoked when the tile is collided with. - * @param callbackContext The context under which the callback is called. - */ - setTileLocationCallback(tileX?: integer, tileY?: integer, width?: integer, height?: integer, callback?: Function, callbackContext?: object): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given - * layer. It will only randomize the tiles in that area, so if they're all the same nothing will - * appear to have changed! This method only modifies tile indexes and does not change collision - * information. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - */ - shuffle(tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision - * information. - * @param tileA First tile index. - * @param tileB Second tile index. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - */ - swapByIndex(tileA: integer, tileB: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layers position, scale and scroll. - * @param tileX The x coordinate, in tiles, not pixels. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - tileToWorldX(tileX: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layers position, scale and scroll. - * @param tileY The y coordinate, in tiles, not pixels. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - tileToWorldY(tileY: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - tileToWorldXY(tileX: integer, tileY: integer, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. New indexes are drawn from the given - * weightedIndexes array. An example weighted array: - * - * [ - * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 - * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 - * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 - * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 - * ] - * - * The probability of any index being choose is (the index's weight) / (sum of all weights). This - * method only modifies tile indexes and does not change collision information. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param weightedIndexes An array of objects to randomly draw from during - * randomization. They should be in the form: { index: 0, weight: 4 } or - * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. - */ - weightedRandomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, weightedIndexes?: object[]): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the - * layers position, scale and scroll. - * @param worldX The x coordinate to be converted, in pixels, not tiles. - * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - worldToTileX(worldX: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the - * layers position, scale and scroll. - * @param worldY The y coordinate to be converted, in pixels, not tiles. - * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - worldToTileY(worldY: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * @param worldX The x coordinate to be converted, in pixels, not tiles. - * @param worldY The y coordinate to be converted, in pixels, not tiles. - * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. - * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - worldToTileXY(worldX: number, worldY: number, snapToFloor?: boolean, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - namespace Formats { - /** - * CSV Map Type - */ - var CSV: number; - - /** - * Tiled JSON Map Type - */ - var TILED_JSON: number; - - /** - * 2D Array Map Type - */ - var ARRAY_2D: number; - - /** - * Weltmeister (Impact.js) Map Type - */ - var WELTMEISTER: number; - - } - - /** - * An Image Collection is a special Tile Set containing multiple images, with no slicing into each image. - * - * Image Collections are normally created automatically when Tiled data is loaded. - */ - class ImageCollection { - /** - * - * @param name The name of the image collection in the map data. - * @param firstgid The first image index this image collection contains. - * @param width Width of widest image (in pixels). Default 32. - * @param height Height of tallest image (in pixels). Default 32. - * @param margin The margin around all images in the collection (in pixels). Default 0. - * @param spacing The spacing between each image in the collection (in pixels). Default 0. - * @param properties Custom Image Collection properties. Default {}. - */ - constructor(name: string, firstgid: integer, width?: integer, height?: integer, margin?: integer, spacing?: integer, properties?: object); - - /** - * The name of the Image Collection. - */ - name: string; - - /** - * The Tiled firstgid value. - * This is the starting index of the first image index this Image Collection contains. - */ - firstgid: integer; - - /** - * The width of the widest image (in pixels). - */ - readonly imageWidth: integer; - - /** - * The height of the tallest image (in pixels). - */ - readonly imageHeight: integer; - - /** - * The margin around the images in the collection (in pixels). - * Use `setSpacing` to change. - */ - readonly imageMarge: integer; - - /** - * The spacing between each image in the collection (in pixels). - * Use `setSpacing` to change. - */ - readonly imageSpacing: integer; - - /** - * Image Collection-specific properties that are typically defined in the Tiled editor. - */ - properties: object; - - /** - * The cached images that are a part of this collection. - */ - readonly images: any[]; - - /** - * The total number of images in the image collection. - */ - readonly total: integer; - - /** - * Returns true if and only if this image collection contains the given image index. - * @param imageIndex The image index to search for. - */ - containsImageIndex(imageIndex: integer): boolean; - - /** - * Add an image to this Image Collection. - * @param gid The gid of the image in the Image Collection. - * @param image The the key of the image in the Image Collection and in the cache. - */ - addImage(gid: integer, image: string): Phaser.Tilemaps.ImageCollection; - - } - - /** - * A class for representing data about about a layer in a map. Maps are parsed from CSV, Tiled, - * etc. into this format. Tilemap, StaticTilemapLayer and DynamicTilemapLayer have a reference - * to this data and use it to look up and perform operations on tiles. - */ - class LayerData { - /** - * - * @param config [description] - */ - constructor(config?: object); - - /** - * The name of the layer, if specified in Tiled. - */ - name: string; - - /** - * The x offset of where to draw from the top left - */ - x: number; - - /** - * The y offset of where to draw from the top left - */ - y: number; - - /** - * The width in tile of the layer. - */ - width: number; - - /** - * The height in tiles of the layer. - */ - height: number; - - /** - * The pixel width of the tiles. - */ - tileWidth: number; - - /** - * The pixel height of the tiles. - */ - tileHeight: number; - - /** - * [description] - */ - baseTileWidth: number; - - /** - * [description] - */ - baseTileHeight: number; - - /** - * The width in pixels of the entire layer. - */ - widthInPixels: number; - - /** - * The height in pixels of the entire layer. - */ - heightInPixels: number; - - /** - * [description] - */ - alpha: number; - - /** - * [description] - */ - visible: boolean; - - /** - * Layer specific properties (can be specified in Tiled) - */ - properties: object; - - /** - * [description] - */ - indexes: any[]; - - /** - * [description] - */ - collideIndexes: any[]; - - /** - * [description] - */ - callbacks: any[]; - - /** - * [description] - */ - bodies: any[]; - - /** - * An array of the tile indexes - */ - data: Phaser.Tilemaps.Tile[][]; - - /** - * [description] - */ - tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer; - - } - - /** - * A class for representing data about a map. Maps are parsed from CSV, Tiled, etc. into this - * format. A Tilemap object get a copy of this data and then unpacks the needed properties into - * itself. - */ - class MapData { - /** - * - * @param config The Map configuration object. - */ - constructor(config?: Phaser.Types.Tilemaps.MapDataConfig); - - /** - * The key in the Phaser cache that corresponds to the loaded tilemap data. - */ - name: string; - - /** - * The width of the entire tilemap. - */ - width: number; - - /** - * The height of the entire tilemap. - */ - height: number; - - /** - * If the map is infinite or not. - */ - infinite: boolean; - - /** - * The width of the tiles. - */ - tileWidth: number; - - /** - * The height of the tiles. - */ - tileHeight: number; - - /** - * The width in pixels of the entire tilemap. - */ - widthInPixels: number; - - /** - * The height in pixels of the entire tilemap. - */ - heightInPixels: number; - - /** - * [description] - */ - format: integer; - - /** - * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. - */ - orientation: string; - - /** - * Determines the draw order of tilemap. Default is right-down - * - * 0, or 'right-down' - * 1, or 'left-down' - * 2, or 'right-up' - * 3, or 'left-up' - */ - renderOrder: string; - - /** - * The version of the map data (as specified in Tiled). - */ - version: string; - - /** - * Map specific properties (can be specified in Tiled) - */ - properties: object; - - /** - * An array with all the layers configured to the MapData. - */ - layers: Phaser.Tilemaps.LayerData[] | Phaser.Tilemaps.ObjectLayer; - - /** - * An array of Tiled Image Layers. - */ - images: any[]; - - /** - * An object of Tiled Object Layers. - */ - objects: object; - - /** - * An object of collision data. Must be created as physics object or will return undefined. - */ - collision: object; - - /** - * An array of Tilesets. - */ - tilesets: Phaser.Tilemaps.Tileset[]; - - /** - * The collection of images the map uses(specified in Tiled) - */ - imageCollections: any[]; - - /** - * [description] - */ - tiles: any[]; - - } - - /** - * A class for representing a Tiled object layer in a map. This mirrors the structure of a Tiled - * object layer, except: - * - "x" & "y" properties are ignored since these cannot be changed in Tiled. - * - "offsetx" & "offsety" are applied to the individual object coordinates directly, so they - * are ignored as well. - * - "draworder" is ignored. - */ - class ObjectLayer { - /** - * - * @param config The data for the layer from the Tiled JSON object. - */ - constructor(config?: Phaser.Types.Tilemaps.ObjectLayerConfig); - - /** - * The name of the Object Layer. - */ - name: string; - - /** - * The opacity of the layer, between 0 and 1. - */ - opacity: number; - - /** - * The custom properties defined on the Object Layer, keyed by their name. - */ - properties: object; - - /** - * The type of each custom property defined on the Object Layer, keyed by its name. - */ - propertyTypes: object; - - /** - * The type of the layer, which should be `objectgroup`. - */ - type: string; - - /** - * Whether the layer is shown (`true`) or hidden (`false`). - */ - visible: boolean; - - /** - * 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`. - */ - objects: Phaser.Types.Tilemaps.TiledObject[]; - - } - - namespace Parsers { - namespace Impact { - /** - * [description] - * @param json [description] - * @param insertNull [description] - */ - function ParseTileLayers(json: object, insertNull: boolean): any[]; - - /** - * [description] - * @param json [description] - */ - function ParseTilesets(json: object): any[]; - - /** - * Parses a Weltmeister JSON object into a new MapData object. - * @param name The name of the tilemap, used to set the name on the MapData. - * @param json The Weltmeister JSON object. - * @param 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've 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. - */ - function ParseWeltmeister(name: string, json: object, insertNull: boolean): object; - - } - - /** - * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format - * is found, returns `null`. When loading from CSV or a 2D array, you should specify the tileWidth & - * tileHeight. When parsing from a map from Tiled, the tileWidth & tileHeight will be pulled from - * the map data. - * @param name The name of the tilemap, used to set the name on the MapData. - * @param mapFormat See ../Formats.js. - * @param data 2D array, CSV string or Tiled JSON object. - * @param tileWidth The width of a tile in pixels. Required for 2D array and CSV, but - * ignored for Tiled JSON. - * @param tileHeight The height of a tile in pixels. Required for 2D array and CSV, but - * ignored for Tiled JSON. - * @param 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've 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. - */ - function Parse(name: string, mapFormat: integer, data: integer[][] | string | object, tileWidth: integer, tileHeight: integer, insertNull: boolean): Phaser.Tilemaps.MapData; - - /** - * Parses a 2D array of tile indexes into a new MapData object with a single layer. - * @param name The name of the tilemap, used to set the name on the MapData. - * @param data 2D array, CSV string or Tiled JSON object. - * @param tileWidth The width of a tile in pixels. - * @param tileHeight The height of a tile in pixels. - * @param 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've 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. - */ - function Parse2DArray(name: string, data: integer[][], tileWidth: integer, tileHeight: integer, insertNull: boolean): Phaser.Tilemaps.MapData; - - /** - * Parses a CSV string of tile indexes into a new MapData object with a single layer. - * @param name The name of the tilemap, used to set the name on the MapData. - * @param data CSV string of tile indexes. - * @param tileWidth The width of a tile in pixels. - * @param tileHeight The height of a tile in pixels. - * @param 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've 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. - */ - function ParseCSV(name: string, data: string, tileWidth: integer, tileHeight: integer, insertNull: boolean): Phaser.Tilemaps.MapData; - - namespace Tiled { - /** - * Copy properties from tileset to tiles. - * @param mapData [description] - */ - function AssignTileProperties(mapData: Phaser.Tilemaps.MapData): void; - - /** - * Decode base-64 encoded data, for example as exported by Tiled. - * @param data Base-64 encoded data to decode. - */ - function Base64Decode(data: object): any[]; - - /** - * Master list of tiles -> x, y, index in tileset. - * @param mapData [description] - */ - function BuildTilesetIndex(mapData: Phaser.Tilemaps.MapData): any[]; - - /** - * Parse a Tiled group layer and create a state object for inheriting. - * @param json The Tiled JSON object. - * @param currentl The current group layer from the Tiled JSON file. - * @param parentstate The state of the parent group (if any). - */ - function CreateGroupLayer(json: object, currentl?: object, parentstate?: object): object; - - /** - * See Tiled documentation on tile flipping: - * http://docs.mapeditor.org/en/latest/reference/tmx-map-format/ - * @param gid [description] - */ - function ParseGID(gid: number): object; - - /** - * Parses a Tiled JSON object into an array of objects with details about the image layers. - * @param json The Tiled JSON object. - */ - function ParseImageLayers(json: object): any[]; - - /** - * Parses a Tiled JSON object into a new MapData object. - * @param name The name of the tilemap, used to set the name on the MapData. - * @param json The Tiled JSON object. - * @param 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've 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. - */ - function ParseJSONTiled(name: string, json: object, insertNull: boolean): Phaser.Tilemaps.MapData; - - /** - * Convert a Tiled object to an internal parsed object normalising and copying properties over, while applying optional x and y offsets. The parsed object will always have the properties `id`, `name`, `type`, `rotation`, `properties`, `visible`, `x`, `y`, `width` and `height`. Other properties will be added according to the object type (such as text, polyline, gid etc.) - * @param tiledObject Tiled object to convert to an internal parsed object normalising and copying properties over. - * @param offsetX Optional additional offset to apply to the object's x property. Defaults to 0. Default 0. - * @param offsetY Optional additional offset to apply to the object's y property. Defaults to 0. Default 0. - */ - function ParseObject(tiledObject: object, offsetX?: number, offsetY?: number): object; - - /** - * Parses a Tiled JSON object into an array of ObjectLayer objects. - * @param json The Tiled JSON object. - */ - function ParseObjectLayers(json: object): any[]; - - /** - * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. - * @param json The Tiled JSON object. - * @param insertNull Controls how empty tiles, tiles with an index of -1, in the map - * data are handled (see {@link Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled}). - */ - function ParseTileLayers(json: object, insertNull: boolean): Phaser.Tilemaps.LayerData[]; - - /** - * Tilesets and Image Collections - * @param json [description] - */ - function ParseTilesets(json: object): object; - - } - - } - - /** - * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When - * loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing from - * a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map data. For - * an empty map, you should specify tileWidth, tileHeight, width & height. - * @param scene The Scene to which this Tilemap belongs. - * @param key The key in the Phaser cache that corresponds to the loaded tilemap data. - * @param tileWidth The width of a tile in pixels. Default 32. - * @param tileHeight The height of a tile in pixels. Default 32. - * @param width The width of the map in tiles. Default 10. - * @param height The height of the map in tiles. Default 10. - * @param data Instead of loading from the cache, you can also load directly from - * a 2D array of tile indexes. - * @param 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've 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. Default false. - */ - function ParseToTilemap(scene: Phaser.Scene, key?: string, tileWidth?: integer, tileHeight?: integer, width?: integer, height?: integer, data?: integer[][], insertNull?: boolean): Phaser.Tilemaps.Tilemap; - - /** - * A Static Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination - * with one, or more, Tilesets. - * - * A Static Tilemap Layer is optimized for rendering speed over flexibility. You cannot apply per-tile - * effects like tint or alpha, or change the tiles or tilesets the layer uses. - * - * Use a Static Tilemap Layer instead of a Dynamic Tilemap Layer when you don't need tile manipulation features. - */ - class StaticTilemapLayer extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible, Phaser.GameObjects.Components.ScrollFactor { - /** - * - * @param scene The Scene to which this Game Object belongs. - * @param tilemap The Tilemap this layer is a part of. - * @param layerIndex The index of the LayerData associated with this layer. - * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param x The world x position where the top left of this layer will be placed. Default 0. - * @param y The world y position where the top left of this layer will be placed. Default 0. - */ - constructor(scene: Phaser.Scene, tilemap: Phaser.Tilemaps.Tilemap, layerIndex: integer, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number); - - /** - * Used internally by physics system to perform fast type checks. - */ - readonly isTilemap: boolean; - - /** - * The Tilemap that this layer is a part of. - */ - tilemap: Phaser.Tilemaps.Tilemap; - - /** - * The index of the LayerData associated with this layer. - */ - layerIndex: integer; - - /** - * The LayerData associated with this layer. LayerData can only be associated with one - * tilemap layer. - */ - layer: Phaser.Tilemaps.LayerData; - - /** - * The Tileset/s associated with this layer. - * - * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. - */ - tileset: Phaser.Tilemaps.Tileset[]; - - /** - * Used internally by the Canvas renderer. - * This holds the tiles that are visible within the camera in the last frame. - */ - culledTiles: any[]; - - /** - * Canvas only. - * - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this, and toggling this flag allows - * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. - */ - skipCull: boolean; - - /** - * Canvas only. - * - * The total number of tiles drawn by the renderer in the last frame. - * - * This only works when rending with Canvas. - */ - readonly tilesDrawn: integer; - - /** - * Canvas only. - * - * The total number of tiles in this layer. Updated every frame. - */ - readonly tilesTotal: integer; - - /** - * Canvas only. - * - * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. - * - * See the method `setCullPadding` for more details. - */ - cullPaddingX: integer; - - /** - * Canvas only. - * - * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. - * - * See the method `setCullPadding` for more details. - */ - cullPaddingY: integer; - - /** - * Canvas only. - * - * The callback that is invoked when the tiles are culled. - * - * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. - * - * It will be sent 3 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. - * - * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. - */ - cullCallback: Function; - - /** - * An array holding the mapping between the tile indexes and the tileset they belong to. - */ - gidMap: Phaser.Tilemaps.Tileset[]; - - /** - * Upload the tile data to a VBO. - * @param camera The camera to render to. - * @param tilesetIndex The tileset index. - */ - upload(camera: Phaser.Cameras.Scene2D.Camera, tilesetIndex: integer): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets the rendering (draw) order of the tiles in this layer. - * - * The default is 'right-down', meaning it will order the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * Setting the render order does not change the tiles or how they are stored in the layer, - * it purely impacts the order in which they are rendered. - * - * You can provide either an integer (0 to 3), or the string version of the order. - * @param renderOrder The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. - */ - setRenderOrder(renderOrder: integer | string): this; - - /** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * @param tileX The x coordinate. - * @param tileY The y coordinate. - */ - calculateFacesAt(tileX: integer, tileY: integer): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - */ - calculateFacesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * @param indexes The tile index, or array of indexes, to create Sprites from. - * @param replacements The tile index, or array of indexes, to change a converted - * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a - * one-to-one mapping with the indexes array. - * @param spriteConfig The config object to pass into the Sprite creator (i.e. - * scene.make.sprite). - * @param scene The Scene to create the Sprites within. Default scene the map is within. - * @param camera The Camera to use when determining the world XY Default main camera. - */ - createFromTiles(indexes: integer | any[], replacements: integer | any[], spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.GameObjects.Sprite[]; - - /** - * Returns the tiles in the given layer that are within the cameras viewport. - * This is used internally. - * @param camera The Camera to run the cull check against. - */ - cull(camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; - - /** - * Canvas only. - * - * You can control if the Cameras should cull tiles before rendering them or not. - * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. - * - * However, there are some instances when you may wish to disable this. - * @param value Set to `true` to stop culling tiles. Set to `false` to enable culling again. Default true. - */ - setSkipCull(value?: boolean): this; - - /** - * Canvas only. - * - * When a Camera culls the tiles in this layer it does so using its view into the world, building up a - * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size - * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so - * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px - * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) - * @param paddingX The amount of extra horizontal tiles to add to the cull check padding. Default 1. - * @param paddingY The amount of extra vertical tiles to add to the cull check padding. Default 1. - */ - setCullPadding(paddingX?: integer, paddingY?: integer): this; - - /** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * @param index The tile index value to search for. - * @param skip The number of times to skip a matching tile before returning. Default 0. - * @param reverse If true it will scan the layer in reverse, starting at the - * bottom-right. Otherwise it scans from the top-left. Default false. - */ - findByIndex(index: integer, skip?: integer, reverse?: boolean): Phaser.Tilemaps.Tile; - - /** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * @param callback The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - findTile(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile; - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * @param callback The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param context The context under which the callback should be run. - * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - filterTiles(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * @param callback The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. - * @param context The context under which the callback should be run. - * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - forEachTile(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Gets a tile at the given tile coordinates from the given layer. - * @param tileX X position to get the tile from (given in tile units, not pixels). - * @param tileY Y position to get the tile from (given in tile units, not pixels). - * @param nonNull If true getTile won't return null for empty tiles, but a Tile - * object with an index of -1. Default false. - */ - getTileAt(tileX: integer, tileY: integer, nonNull?: boolean): Phaser.Tilemaps.Tile; - - /** - * Gets a tile at the given world coordinates from the given layer. - * @param worldX X position to get the tile from (given in pixels) - * @param worldY Y position to get the tile from (given in pixels) - * @param nonNull If true, function won't return null for empty tiles, but a Tile - * object with an index of -1. Default false. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - getTileAtWorldXY(worldX: number, worldY: number, nonNull?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; - - /** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - */ - getTilesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; - - /** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * @param worldX The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param worldY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. - * @param width How many tiles wide from the `tileX` index the area will be. - * @param height How many tiles high from the `tileY` index the area will be. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - */ - getTilesWithinWorldXY(worldX: number, worldY: number, width: number, height: number, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; - - /** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * @param shape A shape in world (pixel) coordinates - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - getTilesWithinShape(shape: Phaser.Geom.Circle | Phaser.Geom.Line | Phaser.Geom.Rectangle | Phaser.Geom.Triangle, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; - - /** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * @param tileX X position to get the tile from in tile coordinates. - * @param tileY Y position to get the tile from in tile coordinates. - */ - hasTileAt(tileX: integer, tileY: integer): boolean; - - /** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * @param worldX The X coordinate of the world position. - * @param worldY The Y coordinate of the world position. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - hasTileAtWorldXY(worldX: number, worldY: number, camera?: Phaser.Cameras.Scene2D.Camera): boolean; - - /** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * @param graphics The target Graphics object to draw upon. - * @param styleConfig An object specifying the colors to use for the debug drawing. - */ - renderDebug(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * @param indexes Either a single tile index, or an array of tile indexes. - * @param collides If true it will enable collision. If false it will clear - * collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the - * update. Default true. - * @param updateLayer If true, updates the current tiles on the layer. Set to - * false if no tiles have been placed for significant performance boost. Default true. - */ - setCollision(indexes: integer | any[], collides?: boolean, recalculateFaces?: boolean, updateLayer?: boolean): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * @param start The first index of the tile to be set for collision. - * @param stop The last index of the tile to be set for collision. - * @param collides If true it will enable collision. If false it will clear - * collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the - * update. Default true. - */ - setCollisionBetween(start: integer, stop: integer, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * @param properties An object with tile properties and corresponding values that should - * be checked. - * @param collides If true it will enable collision. If false it will clear - * collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the - * update. Default true. - */ - setCollisionByProperty(properties: object, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * @param indexes An array of the tile indexes to not be counted for collision. - * @param collides If true it will enable collision. If false it will clear - * collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the - * update. Default true. - */ - setCollisionByExclusion(indexes: integer[], collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * @param indexes Either a single tile index, or an array of tile indexes to have a - * collision callback set for. - * @param callback The callback that will be invoked when the tile is collided with. - * @param callbackContext The context under which the callback is called. - */ - setTileIndexCallback(indexes: integer | any[], callback: Function, callbackContext: object): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets collision on the tiles within a layer by checking each tiles collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tiles collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * @param collides If true it will enable collision. If false it will clear - * collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the - * update. Default true. - */ - setCollisionFromCollisionGroup(collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area. - * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area. - * @param width How many tiles wide from the `tileX` index the area will be. - * @param height How many tiles tall from the `tileY` index the area will be. - * @param callback The callback that will be invoked when the tile is collided with. - * @param callbackContext The context under which the callback is called. - */ - setTileLocationCallback(tileX: integer, tileY: integer, width: integer, height: integer, callback: Function, callbackContext?: object): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layers position, scale and scroll. - * @param tileX The X coordinate, in tile coordinates. - * @param camera The Camera to use when calculating the world values from the tile index. Default main camera. - */ - tileToWorldX(tileX: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layers position, scale and scroll. - * @param tileY The Y coordinate, in tile coordinates. - * @param camera The Camera to use when calculating the world values from the tile index. Default main camera. - */ - tileToWorldY(tileY: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * @param tileX The X coordinate, in tile coordinates. - * @param tileY The Y coordinate, in tile coordinates. - * @param point A Vector2 to store the coordinates in. If not given, a new Vector2 is created. - * @param camera The Camera to use when calculating the world values from the tile index. Default main camera. - */ - tileToWorldXY(tileX: integer, tileY: integer, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; - - /** - * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the - * layers position, scale and scroll. - * @param worldX The X coordinate, in world pixels. - * @param snapToFloor Whether or not to round the tile coordinate down to the - * nearest integer. Default true. - * @param camera The Camera to use when calculating the tile index from the world values.] Default main camera. - */ - worldToTileX(worldX: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the - * layers position, scale and scroll. - * @param worldY The Y coordinate, in world pixels. - * @param snapToFloor Whether or not to round the tile coordinate down to the - * nearest integer. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - worldToTileY(worldY: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * @param worldX The X coordinate, in world pixels. - * @param worldY The Y coordinate, in world pixels. - * @param snapToFloor Whether or not to round the tile coordinate down to the - * nearest integer. Default true. - * @param point A Vector2 to store the coordinates in. If not given, a new Vector2 is created. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - */ - worldToTileXY(worldX: number, worldY: number, snapToFloor?: boolean, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; - - /** - * Destroys this StaticTilemapLayer and removes its link to the associated LayerData. - * @param removeFromTilemap Remove this layer from the parent Tilemap? Default true. - */ - destroy(removeFromTilemap?: boolean): void; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency of which blend modes - * are used. - */ - blendMode: Phaser.BlendModes | string; - - /** - * Sets the Blend Mode being used by this Game Object. - * - * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) - * - * Under WebGL only the following Blend Modes are available: - * - * * ADD - * * MULTIPLY - * * SCREEN - * * ERASE (only works when rendering to a framebuffer, like a Render Texture) - * - * Canvas has more available depending on browser support. - * - * You can also create your own custom Blend Modes in WebGL. - * - * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending - * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these - * reasons try to be careful about the construction of your Scene and the frequency in which blend modes - * are used. - * @param value The BlendMode value. Either a string or a CONST. - */ - setBlendMode(value: string | Phaser.BlendModes): this; - - /** - * The native (un-scaled) width of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayWidth` property. - */ - width: number; - - /** - * The native (un-scaled) height of this Game Object. - * - * Changing this value will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or use - * the `displayHeight` property. - */ - height: number; - - /** - * The displayed width of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayWidth: number; - - /** - * The displayed height of this Game Object. - * - * This value takes into account the scale factor. - * - * Setting this value will adjust the Game Object's scale property. - */ - displayHeight: number; - - /** - * Sets the internal size of this Game Object, as used for frame or physics body creation. - * - * This will not change the size that the Game Object is rendered in-game. - * For that you need to either set the scale of the Game Object (`setScale`) or call the - * `setDisplaySize` method, which is the same thing as changing the scale but allows you - * to do so by giving pixel values. - * - * If you have enabled this Game Object for input, changing the size will _not_ change the - * size of the hit area. To do this you should adjust the `input.hitArea` object directly. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setSize(width: number, height: number): this; - - /** - * Sets the display size of this Game Object. - * - * Calling this will adjust the scale. - * @param width The width of this Game Object. - * @param height The height of this Game Object. - */ - setDisplaySize(width: number, height: number): this; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - */ - depth: number; - - /** - * The depth of this Game Object within the Scene. - * - * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order - * of Game Objects, without actually moving their position in the display list. - * - * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth - * value will always render in front of one with a lower value. - * - * Setting the depth will queue a depth sort event within the Scene. - * @param value The depth of this Game Object. - */ - setDepth(value: integer): this; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * Gets the center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - */ - getCenter(output?: O): O; - - /** - * Gets the top-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the top-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getTopRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the left-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getLeftCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the right-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getRightCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomLeft(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-center coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomCenter(output?: O, includeParent?: boolean): O; - - /** - * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. - * The returned point is calculated in local space and does not factor in any parent containers - * @param output An object to store the values in. If not provided a new Vector2 will be created. - * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. - */ - getBottomRight(output?: O, includeParent?: boolean): O; - - /** - * Gets the bounds of this Game Object, regardless of origin. - * The values are stored and returned in a Rectangle, or Rectangle-like, object. - * @param output An object to store the values in. If not provided a new Rectangle will be created. - */ - getBounds(output?: O): O; - - /** - * 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. - */ - originX: number; - - /** - * 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. - */ - originY: number; - - /** - * The horizontal display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginX: number; - - /** - * The vertical display origin of this Game Object. - * The origin is a normalized value between 0 and 1. - * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. - */ - displayOriginY: number; - - /** - * Sets the origin of this Game Object. - * - * The values are given in the range 0 to 1. - * @param x The horizontal origin value. Default 0.5. - * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. - */ - setOrigin(x?: number, y?: number): this; - - /** - * Sets the origin of this Game Object based on the Pivot values in its Frame. - */ - setOriginFromFrame(): this; - - /** - * Sets the display origin of this Game Object. - * The difference between this and setting the origin is that you can use pixel values for setting the display origin. - * @param x The horizontal display origin value. Default 0. - * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. - */ - setDisplayOrigin(x?: number, y?: number): this; - - /** - * Updates the Display Origin cached values internally stored on this Game Object. - * You don't usually call this directly, but it is exposed for edge-cases where you may. - */ - updateDisplayOrigin(): this; - - /** - * The initial WebGL pipeline of this Game Object. - */ - defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * The current WebGL pipeline of this Game Object. - */ - pipeline: Phaser.Renderer.WebGL.WebGLPipeline; - - /** - * Sets the initial WebGL Pipeline of this Game Object. - * This should only be called during the instantiation of the Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. - */ - initPipeline(pipelineName?: string): boolean; - - /** - * Sets the active WebGL Pipeline of this Game Object. - * @param pipelineName The name of the pipeline to set on this Game Object. - */ - setPipeline(pipelineName: string): this; - - /** - * Resets the WebGL Pipeline of this Game Object back to the default it was created with. - */ - resetPipeline(): boolean; - - /** - * Gets the name of the WebGL Pipeline this Game Object is currently using. - */ - getPipelineName(): string; - - /** - * The x position of this Game Object. - */ - x: number; - - /** - * The y position of this Game Object. - */ - y: number; - - /** - * The z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#depth} instead. - */ - z: number; - - /** - * The w position of this Game Object. - */ - w: number; - - /** - * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object - * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. - * - * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this - * isn't the case, use the `scaleX` or `scaleY` properties instead. - */ - scale: number; - - /** - * The horizontal scale of this Game Object. - */ - scaleX: number; - - /** - * The vertical scale of this Game Object. - */ - scaleY: number; - - /** - * The angle of this Game Object as expressed in degrees. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in radians, see the `rotation` property instead. - */ - angle: integer; - - /** - * The angle of this Game Object in radians. - * - * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left - * and -90 is up. - * - * If you prefer to work in degrees, see the `angle` property instead. - */ - rotation: number; - - /** - * Sets the position of this Game Object. - * @param x The x position of this Game Object. Default 0. - * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. - * @param z The z position of this Game Object. Default 0. - * @param w The w position of this Game Object. Default 0. - */ - setPosition(x?: number, y?: number, z?: number, w?: number): this; - - /** - * Sets the position of this Game Object to be a random position within the confines of - * the given area. - * - * If no area is specified a random position between 0 x 0 and the game width x height is used instead. - * - * The position does not factor in the size of this Game Object, meaning that only the origin is - * guaranteed to be within the area. - * @param x The x position of the top-left of the random area. Default 0. - * @param y The y position of the top-left of the random area. Default 0. - * @param width The width of the random area. - * @param height The height of the random area. - */ - setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; - - /** - * Sets the rotation of this Game Object. - * @param radians The rotation of this Game Object, in radians. Default 0. - */ - setRotation(radians?: number): this; - - /** - * Sets the angle of this Game Object. - * @param degrees The rotation of this Game Object, in degrees. Default 0. - */ - setAngle(degrees?: number): this; - - /** - * Sets the scale of this Game Object. - * @param x The horizontal scale of this Game Object. - * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. - */ - setScale(x: number, y?: number): this; - - /** - * Sets the x position of this Game Object. - * @param value The x position of this Game Object. Default 0. - */ - setX(value?: number): this; - - /** - * Sets the y position of this Game Object. - * @param value The y position of this Game Object. Default 0. - */ - setY(value?: number): this; - - /** - * Sets the z position of this Game Object. - * - * Note: The z position does not control the rendering order of 2D Game Objects. Use - * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. - * @param value The z position of this Game Object. Default 0. - */ - setZ(value?: number): this; - - /** - * Sets the w position of this Game Object. - * @param value The w position of this Game Object. Default 0. - */ - setW(value?: number): this; - - /** - * Gets the local transform matrix for this Game Object. - * @param tempMatrix The matrix to populate with the values from this Game Object. - */ - getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the world transform matrix for this Game Object, factoring in any parent Containers. - * @param tempMatrix The matrix to populate with the values from this Game Object. - * @param parentMatrix A temporary matrix to hold parent values during the calculations. - */ - getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; - - /** - * Gets the sum total rotation of all of this Game Objects parent Containers. - * - * The returned value is in radians and will be zero if this Game Object has no parent container. - */ - getParentRotation(): number; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - /** - * 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 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. - */ - scrollFactorX: number; - - /** - * 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 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. - */ - scrollFactorY: number; - - /** - * Sets the 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 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. - * @param x The horizontal scroll factor of this Game Object. - * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. - */ - setScrollFactor(x: number, y?: number): this; - - } - - /** - * A Tile is a representation of a single tile within the Tilemap. This is a lightweight data - * representation, so its position information is stored without factoring in scroll, layer - * scale or layer position. - */ - class Tile implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.Visible { - /** - * - * @param layer The LayerData object in the Tilemap that this tile belongs to. - * @param index The unique index of this tile within the map. - * @param x The x coordinate of this tile in tile coordinates. - * @param y The y coordinate of this tile in tile coordinates. - * @param width Width of the tile in pixels. - * @param height Height of the tile in pixels. - * @param baseWidth The base width a tile in the map (in pixels). Tiled maps support - * multiple tileset sizes within one map, but they are still placed at intervals of the base - * tile width. - * @param baseHeight The base height of the tile in pixels (in pixels). Tiled maps - * support multiple tileset sizes within one map, but they are still placed at intervals of the - * base tile height. - */ - constructor(layer: Phaser.Tilemaps.LayerData, index: integer, x: integer, y: integer, width: integer, height: integer, baseWidth: integer, baseHeight: integer); - - /** - * The LayerData in the Tilemap data that this tile belongs to. - */ - layer: Phaser.Tilemaps.LayerData; - - /** - * The index of this tile within the map data corresponding to the tileset, or -1 if this - * represents a blank tile. - */ - index: integer; - - /** - * The x map coordinate of this tile in tile units. - */ - x: integer; - - /** - * The y map coordinate of this tile in tile units. - */ - y: integer; - - /** - * The width of the tile in pixels. - */ - width: integer; - - /** - * The height of the tile in pixels. - */ - height: integer; - - /** - * The map's base width of a tile in pixels. Tiled maps support multiple tileset sizes - * within one map, but they are still placed at intervals of the base tile size. - */ - baseWidth: integer; - - /** - * The map's base height of a tile in pixels. Tiled maps support multiple tileset sizes - * within one map, but they are still placed at intervals of the base tile size. - */ - baseHeight: integer; - - /** - * The x coordinate of the top left of this tile in pixels. This is relative to the top left - * of the layer this tile is being rendered within. This property does NOT factor in camera - * scroll, layer scale or layer position. - */ - pixelX: number; - - /** - * The y coordinate of the top left of this tile in pixels. This is relative to the top left - * of the layer this tile is being rendered within. This property does NOT factor in camera - * scroll, layer scale or layer position. - */ - pixelY: number; - - /** - * Tile specific properties. These usually come from Tiled. - */ - properties: any; - - /** - * The rotation angle of this tile. - */ - rotation: number; - - /** - * Whether the tile should collide with any object on the left side. - */ - collideLeft: boolean; - - /** - * Whether the tile should collide with any object on the right side. - */ - collideRight: boolean; - - /** - * Whether the tile should collide with any object on the top side. - */ - collideUp: boolean; - - /** - * Whether the tile should collide with any object on the bottom side. - */ - collideDown: boolean; - - /** - * Whether the tile's left edge is interesting for collisions. - */ - faceLeft: boolean; - - /** - * Whether the tile's right edge is interesting for collisions. - */ - faceRight: boolean; - - /** - * Whether the tile's top edge is interesting for collisions. - */ - faceTop: boolean; - - /** - * Whether the tile's bottom edge is interesting for collisions. - */ - faceBottom: boolean; - - /** - * Tile collision callback. - */ - collisionCallback: Function; - - /** - * The context in which the collision callback will be called. - */ - collisionCallbackContext: object; - - /** - * The tint to apply to this tile. Note: tint is currently a single color value instead of - * the 4 corner tint component on other GameObjects. - */ - tint: number; - - /** - * An empty object where physics-engine specific information (e.g. bodies) may be stored. - */ - physics: object; - - /** - * Check if the given x and y world coordinates are within this Tile. This does not factor in - * camera scroll, layer scale or layer position. - * @param x The x coordinate to test. - * @param y The y coordinate to test. - */ - containsPoint(x: number, y: number): boolean; - - /** - * Copies the tile data & properties from the given tile to this tile. This copies everything - * except for position and interesting faces. - * @param tile The tile to copy from. - */ - copy(tile: Phaser.Tilemaps.Tile): Phaser.Tilemaps.Tile; - - /** - * The collision group for this Tile, defined within the Tileset. This returns a reference to - * the collision group stored within the Tileset, so any modification of the returned object - * will impact all tiles that have the same index as this tile. - */ - getCollisionGroup(): object; - - /** - * The tile data for this Tile, defined within the Tileset. This typically contains Tiled - * collision data, tile animations and terrain information. This returns a reference to the tile - * data stored within the Tileset, so any modification of the returned object will impact all - * tiles that have the same index as this tile. - */ - getTileData(): object; - - /** - * Gets the world X position of the left side of the tile, factoring in the layers position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - */ - getLeft(camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Gets the world X position of the right side of the tile, factoring in the layer's position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - */ - getRight(camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Gets the world Y position of the top side of the tile, factoring in the layer's position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - */ - getTop(camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Gets the world Y position of the bottom side of the tile, factoring in the layer's position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - */ - getBottom(camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Gets the world rectangle bounding box for the tile, factoring in the layers position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - * @param output [description] - */ - getBounds(camera?: Phaser.Cameras.Scene2D.Camera, output?: object): Phaser.Geom.Rectangle | object; - - /** - * Gets the world X position of the center of the tile, factoring in the layer's position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - */ - getCenterX(camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Gets the world Y position of the center of the tile, factoring in the layer's position, - * scale and scroll. - * @param camera The Camera to use to perform the check. - */ - getCenterY(camera?: Phaser.Cameras.Scene2D.Camera): number; - - /** - * Clean up memory. - */ - destroy(): void; - - /** - * Check for intersection with this tile. This does not factor in camera scroll, layer scale or - * layer position. - * @param x The x axis in pixels. - * @param y The y axis in pixels. - * @param right The right point. - * @param bottom The bottom point. - */ - intersects(x: number, y: number, right: number, bottom: number): boolean; - - /** - * Checks if the tile is interesting. - * @param collides If true, will consider the tile interesting if it collides on any side. - * @param faces If true, will consider the tile interesting if it has an interesting face. - */ - isInteresting(collides: boolean, faces: boolean): boolean; - - /** - * Reset collision status flags. - * @param recalculateFaces Whether or not to recalculate interesting faces for this tile and its neighbors. Default true. - */ - resetCollision(recalculateFaces?: boolean): Phaser.Tilemaps.Tile; - - /** - * Reset faces. - */ - resetFaces(): Phaser.Tilemaps.Tile; - - /** - * Sets the collision flags for each side of this tile and updates the interesting faces list. - * @param left Indicating collide with any object on the left. - * @param right Indicating collide with any object on the right. - * @param up Indicating collide with any object on the top. - * @param down Indicating collide with any object on the bottom. - * @param recalculateFaces Whether or not to recalculate interesting faces - * for this tile and its neighbors. Default true. - */ - setCollision(left: boolean, right?: boolean, up?: boolean, down?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.Tile; - - /** - * Set a callback to be called when this tile is hit by an object. The callback must true for - * collision processing to take place. - * @param callback Callback function. - * @param context Callback will be called within this context. - */ - setCollisionCallback(callback: Function, context: object): Phaser.Tilemaps.Tile; - - /** - * Sets the size of the tile and updates its pixelX and pixelY. - * @param tileWidth The width of the tile in pixels. - * @param tileHeight The height of the tile in pixels. - * @param baseWidth The base width a tile in the map (in pixels). - * @param baseHeight The base height of the tile in pixels (in pixels). - */ - setSize(tileWidth: integer, tileHeight: integer, baseWidth: integer, baseHeight: integer): Phaser.Tilemaps.Tile; - - /** - * Used internally. Updates the tile's world XY position based on the current tile size. - */ - updatePixelXY(): Phaser.Tilemaps.Tile; - - /** - * True if this tile can collide on any of its faces or has a collision callback set. - */ - readonly canCollide: boolean; - - /** - * True if this tile can collide on any of its faces. - */ - readonly collides: boolean; - - /** - * True if this tile has any interesting faces. - */ - readonly hasInterestingFace: boolean; - - /** - * The tileset that contains this Tile. This is null if accessed from a LayerData instance - * before the tile is placed in a StaticTilemapLayer or DynamicTilemapLayer, or if the tile has - * an index that doesn't correspond to any of the map's tilesets. - */ - readonly tileset: Phaser.Tilemaps.Tileset; - - /** - * The tilemap layer that contains this Tile. This will only return null if accessed from a - * LayerData instance before the tile is placed within a StaticTilemapLayer or - * DynamicTilemapLayer. - */ - readonly tilemapLayer: Phaser.Tilemaps.StaticTilemapLayer | Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * The tilemap that contains this Tile. This will only return null if accessed from a LayerData - * instance before the tile is placed within a StaticTilemapLayer or DynamicTilemapLayer. - */ - readonly tilemap: Phaser.Tilemaps.Tilemap; - - /** - * Clears all alpha values associated with this Game Object. - * - * Immediately sets the alpha levels back to 1 (fully opaque). - */ - clearAlpha(): this; - - /** - * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. - * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. - * - * If your game is running under WebGL you can optionally specify four different alpha values, each of which - * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. - * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. - * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. - * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. - * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. - */ - setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; - - /** - * The alpha value of the Game Object. - * - * This is a global value, impacting the entire Game Object, not just a region of it. - */ - alpha: number; - - /** - * The alpha value starting from the top-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopLeft: number; - - /** - * The alpha value starting from the top-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaTopRight: number; - - /** - * The alpha value starting from the bottom-left of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomLeft: number; - - /** - * The alpha value starting from the bottom-right of the Game Object. - * This value is interpolated from the corner to the center of the Game Object. - */ - alphaBottomRight: number; - - /** - * The horizontally flipped state of the Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipX: boolean; - - /** - * The vertically flipped state of the Game Object. - * - * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - flipY: boolean; - - /** - * Toggles the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - */ - toggleFlipX(): this; - - /** - * Toggles the vertical flipped state of this Game Object. - */ - toggleFlipY(): this; - - /** - * Sets the horizontal flipped state of this Game Object. - * - * A Game Object that is flipped horizontally will render inversed on the horizontal axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipX(value: boolean): this; - - /** - * Sets the vertical flipped state of this Game Object. - * @param value The flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlipY(value: boolean): this; - - /** - * Sets the horizontal and vertical flipped state of this Game Object. - * - * A Game Object that is flipped will render inversed on the flipped axis. - * Flipping always takes place from the middle of the texture and does not impact the scale value. - * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. - * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. - * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. - */ - setFlip(x: boolean, y: boolean): this; - - /** - * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. - */ - resetFlip(): this; - - /** - * The visible state of the Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - */ - visible: boolean; - - /** - * Sets the visibility of this Game Object. - * - * An invisible Game Object will skip rendering, but will still process update logic. - * @param value The visible state of the Game Object. - */ - setVisible(value: boolean): this; - - } - - /** - * 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 (StaticTilemapLayer or DynamicTilemapLayer), which are the display - * objects that actually render tiles. - * - * The Tilemap data 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 - * - * A Tilemap has handy methods for getting & manipulating the tiles within a layer. You can only - * use the methods that change tiles (e.g. removeTileAt) on a DynamicTilemapLayer. - * - * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a - * StaticTilemapLayer or DynamicTilemapLayer may have its own unique tile size that overrides - * it. - * - * As of Phaser 3.21.0, if your tilemap includes layer groups (a feature of Tiled 1.2.0+) these - * will be traversed and the following properties will affect 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'. - */ - class Tilemap { - /** - * - * @param scene The Scene to which this Tilemap belongs. - * @param mapData A MapData instance containing Tilemap data. - */ - constructor(scene: Phaser.Scene, mapData: Phaser.Tilemaps.MapData); - - scene: Phaser.Scene; - - /** - * The base width of a tile in pixels. Note that individual layers may have a different tile - * width. - */ - tileWidth: integer; - - /** - * The base height of a tile in pixels. Note that individual layers may have a different - * tile height. - */ - tileHeight: integer; - - /** - * The width of the map (in tiles). - */ - width: number; - - /** - * The height of the map (in tiles). - */ - height: number; - - /** - * The orientation of the map data (as specified in Tiled), usually 'orthogonal'. - */ - orientation: string; - - /** - * The render (draw) order of the map data (as specified in Tiled), usually 'right-down'. - * - * The draw orders are: - * - * right-down - * left-down - * right-up - * left-up - * - * This can be changed via the `setRenderOrder` method. - */ - renderOrder: string; - - /** - * The format of the map data. - */ - format: number; - - /** - * The version of the map data (as specified in Tiled, usually 1). - */ - version: number; - - /** - * Map specific properties as specified in Tiled. - */ - properties: object; - - /** - * The width of the map in pixels based on width * tileWidth. - */ - widthInPixels: number; - - /** - * The height of the map in pixels based on height * tileHeight. - */ - heightInPixels: number; - - imageCollections: Phaser.Tilemaps.ImageCollection[]; - - /** - * An array of Tiled Image Layers. - */ - images: any[]; - - /** - * An array of Tilemap layer data. - */ - layers: Phaser.Tilemaps.LayerData[]; - - /** - * An array of Tilesets used in the map. - */ - tilesets: Phaser.Tilemaps.Tileset[]; - - /** - * An array of ObjectLayer instances parsed from Tiled object layers. - */ - objects: Phaser.Tilemaps.ObjectLayer[]; - - /** - * The index of the currently selected LayerData object. - */ - currentLayerIndex: integer; - - /** - * Sets the rendering (draw) order of the tiles in this map. - * - * The default is 'right-down', meaning it will order the tiles starting from the top-left, - * drawing to the right and then moving down to the next row. - * - * The draw orders are: - * - * 0 = right-down - * 1 = left-down - * 2 = right-up - * 3 = left-up - * - * Setting the render order does not change the tiles or how they are stored in the layer, - * it purely impacts the order in which they are rendered. - * - * You can provide either an integer (0 to 3), or the string version of the order. - * - * Calling this method _after_ creating Static or Dynamic Tilemap Layers will **not** automatically - * update them to use the new render order. If you call this method after creating layers, use their - * own `setRenderOrder` methods to change them as needed. - * @param renderOrder The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. - */ - setRenderOrder(renderOrder: integer | string): this; - - /** - * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. - * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled - * editor. - * @param tilesetName The name of the tileset as specified in the map data. - * @param key The key of the Phaser.Cache image used for this tileset. If - * `undefined` or `null` it will look for an image with a key matching the tilesetName parameter. - * @param tileWidth The width of the tile (in pixels) in the Tileset Image. If not - * given it will default to the map's tileWidth value, or the tileWidth specified in the Tiled - * JSON file. - * @param tileHeight The height of the tiles (in pixels) in the Tileset Image. If - * not given it will default to the map's tileHeight value, or the tileHeight specified in the - * Tiled JSON file. - * @param tileMargin The margin around the tiles in the sheet (in pixels). If not - * specified, it will default to 0 or the value specified in the Tiled JSON file. - * @param tileSpacing The spacing between each the tile in the sheet (in pixels). - * If not specified, it will default to 0 or the value specified in the Tiled JSON file. - * @param gid If adding multiple tilesets to a blank map, specify the starting - * GID this set will use here. Default 0. - */ - addTilesetImage(tilesetName: string, key?: string, tileWidth?: integer, tileHeight?: integer, tileMargin?: integer, tileSpacing?: integer, gid?: integer): Phaser.Tilemaps.Tileset; - - /** - * Turns the DynamicTilemapLayer associated with the given layer into a StaticTilemapLayer. If - * no layer specified, the map's current layer is used. This is useful if you want to manipulate - * a map at the start of a scene, but then make it non-manipulable and optimize it for speed. - * Note: the DynamicTilemapLayer passed in is destroyed, so make sure to store the value - * returned from this method if you want to manipulate the new StaticTilemapLayer. - * @param layer The name of the layer from Tiled, the - * index of the layer in the map, or a DynamicTilemapLayer. - */ - convertLayerToStatic(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Copies the tiles in the source rectangular area to a new destination (all specified in tile - * coordinates) within the layer. This copies all tile properties & recalculates collision - * information in the destination region. - * - * If no layer specified, the map's current layer is used. This cannot be applied to StaticTilemapLayers. - * @param srcTileX The x coordinate of the area to copy from, in tiles, not pixels. - * @param srcTileY The y coordinate of the area to copy from, in tiles, not pixels. - * @param width The width of the area to copy, in tiles, not pixels. - * @param height The height of the area to copy, in tiles, not pixels. - * @param destTileX The x coordinate of the area to copy to, in tiles, not pixels. - * @param destTileY The y coordinate of the area to copy to, in tiles, not pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - copy(srcTileX: integer, srcTileY: integer, width: integer, height: integer, destTileX: integer, destTileY: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Creates a new and empty DynamicTilemapLayer. The currently selected layer in the map is set to this new layer. - * @param name The name of this layer. Must be unique within the map. - * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param x The world x position where the top left of this layer will be placed. Default 0. - * @param y The world y position where the top left of this layer will be placed. Default 0. - * @param width The width of the layer in tiles. If not specified, it will default to the map's width. - * @param height The height of the layer in tiles. If not specified, it will default to the map's height. - * @param tileWidth The width of the tiles the layer uses for calculations. If not specified, it will default to the map's tileWidth. - * @param tileHeight The height of the tiles the layer uses for calculations. If not specified, it will default to the map's tileHeight. - */ - createBlankDynamicLayer(name: string, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number, width?: integer, height?: integer, tileWidth?: integer, tileHeight?: integer): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Creates a new DynamicTilemapLayer that renders the LayerData associated with the given - * `layerID`. The currently selected layer in the map is set to this new layer. - * - * The `layerID` is important. If you've created your map in Tiled then you can get this by - * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and - * look at the layers[].name value. Either way it must match. - * - * Unlike a static layer, a dynamic layer can be modified. See DynamicTilemapLayer for more - * information. - * @param layerID The layer array index value, or if a string is given, the layer name from Tiled. - * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param x The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. - * @param y The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. - */ - createDynamicLayer(layerID: integer | string, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number): Phaser.Tilemaps.DynamicTilemapLayer; - - /** - * Creates a Sprite for every object matching the given gid in the map data. All properties from - * the map data objectgroup are copied into the `spriteConfig`, so you can use this as an easy - * way to configure Sprite properties from within the map editor. For example giving an object a - * property of alpha: 0.5 in the map editor will duplicate that when the Sprite is created. - * - * Custom object properties not sharing names with the Sprite's own properties are copied to the - * Sprite's {@link Phaser.GameObjects.Sprite#data data store}. - * @param name The name of the object layer (from Tiled) to create Sprites from. - * @param id Either the id (object), gid (tile object) or name (object or - * tile object) from Tiled. Ids are unique in Tiled, but a gid is shared by all tile objects - * with the same graphic. The same name can be used on multiple objects. - * @param spriteConfig The config object to pass into the Sprite creator (i.e. - * scene.make.sprite). - * @param scene The Scene to create the Sprites within. Default the scene the map is within. - */ - createFromObjects(name: string, id: integer | string, spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene): Phaser.GameObjects.Sprite[]; - - /** - * Creates a Sprite for every object matching the given tile indexes in the layer. You can - * optionally specify if each tile will be replaced with a new tile after the Sprite has been - * created. This is useful if you want to lay down special tiles in a level that are converted to - * Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * @param indexes The tile index, or array of indexes, to create Sprites from. - * @param replacements The tile index, or array of indexes, to change a converted - * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a - * one-to-one mapping with the indexes array. - * @param spriteConfig The config object to pass into the Sprite creator (i.e. scene.make.sprite). - * @param scene The Scene to create the Sprites within. Default scene the map is within. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - createFromTiles(indexes: integer | any[], replacements: integer | any[], spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.GameObjects.Sprite[]; - - /** - * Creates a new StaticTilemapLayer that renders the LayerData associated with the given - * `layerID`. The currently selected layer in the map is set to this new layer. - * - * The `layerID` is important. If you've created your map in Tiled then you can get this by - * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and - * look at the layers[].name value. Either way it must match. - * - * It's important to remember that a static layer cannot be modified. See StaticTilemapLayer for - * more information. - * @param layerID The layer array index value, or if a string is given, the layer name from Tiled. - * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. - * @param x The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. - * @param y The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. - */ - createStaticLayer(layerID: integer | string, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number): Phaser.Tilemaps.StaticTilemapLayer; - - /** - * Removes all layer data from this Tilemap and nulls the scene reference. This will destroy any - * StaticTilemapLayers or DynamicTilemapLayers that have been linked to LayerData. - */ - destroy(): void; - - /** - * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the - * specified index. Tiles will be set to collide if the given index is a colliding index. - * Collision information in the region will be recalculated. - * - * If no layer specified, the map's current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param index The tile index to fill the area with. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - fill(index: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * For each object in the given object layer, run the given filter callback function. Any - * objects that pass the filter test (i.e. where the callback returns true) will returned as a - * new array. Similar to Array.prototype.Filter in vanilla JS. - * @param objectLayer The name of an object layer (from Tiled) or an ObjectLayer instance. - * @param callback The callback. Each object in the given area will be passed to this callback as the first and only parameter. - * @param context The context under which the callback should be run. - */ - filterObjects(objectLayer: Phaser.Tilemaps.ObjectLayer | string, callback: TilemapFilterCallback, context?: object): Phaser.GameObjects.GameObject[]; - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns - * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. - * If no layer specified, the map's current layer is used. - * @param callback The callback. Each tile in the given area will be passed to this - * callback as the first and only parameter. The callback should return true for tiles that pass the - * filter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param layer The tile layer to use. If not given the current layer is used. - */ - filterTiles(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; - - /** - * Searches the entire map layer for the first tile matching the given index, then returns that Tile - * object. If no match is found, it returns null. The search starts from the top-left tile and - * continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to - * the top-left. - * If no layer specified, the map's current layer is used. - * @param index The tile index value to search for. - * @param skip The number of times to skip a matching tile before returning. Default 0. - * @param reverse If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. Default false. - * @param layer The tile layer to use. If not given the current layer is used. - */ - findByIndex(index: integer, skip?: integer, reverse?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Find the first object in the given object layer that satisfies the provided testing function. - * I.e. finds the first object for which `callback` returns true. Similar to - * Array.prototype.find in vanilla JS. - * @param objectLayer The name of an object layer (from Tiled) or an ObjectLayer instance. - * @param callback The callback. Each object in the given area will be passed to this callback as the first and only parameter. - * @param context The context under which the callback should be run. - */ - findObject(objectLayer: Phaser.Tilemaps.ObjectLayer | string, callback: TilemapFindCallback, context?: object): Phaser.GameObjects.GameObject; - - /** - * Find the first tile in the given rectangular area (in tile coordinates) of the layer that - * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns - * true. Similar to Array.prototype.find in vanilla JS. - * If no layer specified, the maps current layer is used. - * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param layer The Tile layer to run the search on. If not provided will use the current layer. - */ - findTile(callback: FindTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given - * callback. Similar to Array.prototype.forEach in vanilla JS. - * - * If no layer specified, the map's current layer is used. - * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param context The context under which the callback should be run. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param layer The Tile layer to run the search on. If not provided will use the current layer. - */ - forEachTile(callback: EachTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Gets the image layer index based on its name. - * @param name The name of the image to get. - */ - getImageIndex(name: string): integer; - - /** - * Return a list of all valid imagelayer names loaded in this Tilemap. - */ - getImageLayerNames(): string[]; - - /** - * Internally used. Returns the index of the object in one of the Tilemaps arrays whose name - * property matches the given `name`. - * @param location The Tilemap array to search. - * @param name The name of the array element to get. - */ - getIndex(location: any[], name: string): number; - - /** - * Gets the LayerData from this.layers that is associated with `layer`, or null if an invalid - * `layer` is given. - * @param layer The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the maps current layer index. - */ - getLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.LayerData; - - /** - * Gets the ObjectLayer from this.objects that has the given `name`, or null if no ObjectLayer - * is found with that name. - * @param name The name of the object layer from Tiled. - */ - getObjectLayer(name?: string): Phaser.Tilemaps.ObjectLayer; - - /** - * Return a list of all valid objectgroup names loaded in this Tilemap. - */ - getObjectLayerNames(): string[]; - - /** - * Gets the LayerData index of the given `layer` within this.layers, or null if an invalid - * `layer` is given. - * @param layer The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the map's current layer index. - */ - getLayerIndex(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): integer; - - /** - * Gets the index of the LayerData within this.layers that has the given `name`, or null if an - * invalid `name` is given. - * @param name The name of the layer to get. - */ - getLayerIndexByName(name: string): integer; - - /** - * Gets a tile at the given tile coordinates from the given layer. - * If no layer specified, the map's current layer is used. - * @param tileX X position to get the tile from (given in tile units, not pixels). - * @param tileY Y position to get the tile from (given in tile units, not pixels). - * @param nonNull If true getTile won't return null for empty tiles, but a Tile object with an index of -1. Default false. - * @param layer The tile layer to use. If not given the current layer is used. - */ - getTileAt(tileX: integer, tileY: integer, nonNull?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Gets a tile at the given world coordinates from the given layer. - * If no layer specified, the map's current layer is used. - * @param worldX X position to get the tile from (given in pixels) - * @param worldY Y position to get the tile from (given in pixels) - * @param nonNull If true, function won't return null for empty tiles, but a Tile object with an index of -1. Default false. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - getTileAtWorldXY(worldX: number, worldY: number, nonNull?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Return a list of all valid tilelayer names loaded in this Tilemap. - */ - getTileLayerNames(): string[]; - - /** - * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. - * If no layer specified, the maps current layer is used. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param layer The tile layer to use. If not given the current layer is used. - */ - getTilesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; - - /** - * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, - * Line, Rectangle or Triangle. The shape should be in world coordinates. - * If no layer specified, the maps current layer is used. - * @param shape A shape in world (pixel) coordinates - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - getTilesWithinShape(shape: Phaser.Geom.Circle | Phaser.Geom.Line | Phaser.Geom.Rectangle | Phaser.Geom.Triangle, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; - - /** - * Gets the tiles in the given rectangular area (in world coordinates) of the layer. - * If no layer specified, the maps current layer is used. - * @param worldX The world x coordinate for the top-left of the area. - * @param worldY The world y coordinate for the top-left of the area. - * @param width The width of the area. - * @param height The height of the area. - * @param filteringOptions Optional filters to apply when getting the tiles. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - getTilesWithinWorldXY(worldX: number, worldY: number, width: number, height: number, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; - - /** - * Gets the Tileset that has the given `name`, or null if an invalid `name` is given. - * @param name The name of the Tileset to get. - */ - getTileset(name: string): Phaser.Tilemaps.Tileset; - - /** - * Gets the index of the Tileset within this.tilesets that has the given `name`, or null if an - * invalid `name` is given. - * @param name The name of the Tileset to get. - */ - getTilesetIndex(name: string): integer; - - /** - * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * If no layer specified, the map's current layer is used. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param layer The tile layer to use. If not given the current layer is used. - */ - hasTileAt(tileX: integer, tileY: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): boolean; - - /** - * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns - * false if there is no tile or if the tile at that location has an index of -1. - * - * If no layer specified, the maps current layer is used. - * @param worldX The x coordinate, in pixels. - * @param worldY The y coordinate, in pixels. - * @param camera The Camera to use when factoring in which tiles to return. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - hasTileAtWorldXY(worldX: number, worldY: number, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): boolean; - - /** - * The LayerData object that is currently selected in the map. You can set this property using - * any type supported by setLayer. - */ - layer: Phaser.Tilemaps.LayerData; - - /** - * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index - * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified - * location. If you pass in an index, only the index at the specified location will be changed. - * Collision information will be recalculated at the specified location. - * - * If no layer specified, the maps current layer is used. - * - * This cannot be applied to StaticTilemapLayers. - * @param tile The index of this tile to set or a Tile object. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - putTileAt(tile: integer | Phaser.Tilemaps.Tile, tileX: integer, tileY: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either - * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the - * specified location. If you pass in an index, only the index at the specified location will be - * changed. Collision information will be recalculated at the specified location. - * - * If no layer specified, the maps current layer is used. This - * cannot be applied to StaticTilemapLayers. - * @param tile The index of this tile to set or a Tile object. - * @param worldX The x coordinate, in pixels. - * @param worldY The y coordinate, in pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - putTileAtWorldXY(tile: integer | Phaser.Tilemaps.Tile, worldX: number, worldY: number, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified - * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, - * all attributes will be copied over to the specified location. If you pass in an index, only the - * index at the specified location will be changed. Collision information will be recalculated - * within the region tiles were changed. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param tile A row (array) or grid (2D array) of Tiles or tile indexes to place. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - putTilesAt(tile: integer[] | integer[][] | Phaser.Tilemaps.Tile[] | Phaser.Tilemaps.Tile[][], tileX: integer, tileY: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then - * those will be used for randomly assigning new tile indexes. If an array is not provided, the - * indexes found within the region (excluding -1) will be used for randomly assigning new tile - * indexes. This method only modifies tile indexes and does not change collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param indexes An array of indexes to randomly draw from during randomization. - * @param layer The tile layer to use. If not given the current layer is used. - */ - randomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, indexes?: integer[], layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting - * faces are used internally for optimizing collisions against tiles. This method is mostly used - * internally to optimize recalculating faces when only one tile has been changed. - * - * If no layer specified, the maps current layer is used. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param layer The tile layer to use. If not given the current layer is used. - */ - calculateFacesAt(tileX: integer, tileY: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the - * layer. Interesting faces are used internally for optimizing collisions against tiles. This method - * is mostly used internally. - * - * If no layer specified, the map's current layer is used. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param layer The tile layer to use. If not given the current layer is used. - */ - calculateFacesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Removes the given TilemapLayer from this Tilemap without destroying it. - * - * If no layer specified, the map's current layer is used. - * @param layer The tile layer to be removed. - */ - removeLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Destroys the given TilemapLayer and removes it from this Tilemap. - * - * If no layer specified, the map's current layer is used. - * @param layer The tile layer to be destroyed. - */ - destroyLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Removes all layers from this Tilemap and destroys any associated StaticTilemapLayers or - * DynamicTilemapLayers. - */ - removeAllLayers(): Phaser.Tilemaps.Tilemap; - - /** - * Removes the given Tile, or an array of Tiles, from the layer to which they belong, - * and optionally recalculates the collision information. - * - * This cannot be applied to Tiles that belong to Static Tilemap Layers. - * @param tiles The Tile to remove, or an array of Tiles. - * @param replaceIndex After removing the Tile, insert a brand new Tile into its location with the given index. Leave as -1 to just remove the tile. Default -1. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - */ - removeTile(tiles: Phaser.Tilemaps.Tile | Phaser.Tilemaps.Tile[], replaceIndex?: integer, recalculateFaces?: boolean): Phaser.Tilemaps.Tile[]; - - /** - * Removes the tile at the given tile coordinates in the specified layer and updates the layer's - * collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - removeTileAt(tileX: integer, tileY: integer, replaceWithNull?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Removes the tile at the given world coordinates in the specified layer and updates the layer's - * collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param worldX The x coordinate, in pixels. - * @param worldY The y coordinate, in pixels. - * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. - * @param recalculateFaces `true` if the faces data should be recalculated. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - removeTileAtWorldXY(worldX: number, worldY: number, replaceWithNull?: boolean, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; - - /** - * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to - * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles - * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation - * wherever you want on the screen. - * - * If no layer specified, the maps current layer is used. - * @param graphics The target Graphics object to draw upon. - * @param styleConfig An object specifying the colors to use for the debug drawing. - * @param layer The tile layer to use. If not given the current layer is used. - */ - renderDebug(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Draws a debug representation of all layers within this Tilemap to the given Graphics object. - * - * This is helpful when you want to get a quick idea of which of your tiles are colliding and which - * have interesting faces. The tiles are drawn starting at (0, 0) in the Graphics, allowing you to - * place the debug representation wherever you want on the screen. - * @param graphics The target Graphics object to draw upon. - * @param styleConfig An object specifying the colors to use for the debug drawing. - * @param layer The tile layer to use. If not given the current layer is used. - */ - renderDebugFull(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does - * not change collision information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param findIndex The index of the tile to search for. - * @param newIndex The index of the tile to replace it with. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param layer The tile layer to use. If not given the current layer is used. - */ - replaceByIndex(findIndex: integer, newIndex: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets collision on the given tile or tiles within a layer by index. You can pass in either a - * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if - * collision will be enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * @param indexes Either a single tile index, or an array of tile indexes. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - * @param updateLayer If true, updates the current tiles on the layer. Set to false if no tiles have been placed for significant performance boost. Default true. - */ - setCollision(indexes: integer | any[], collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, updateLayer?: boolean): Phaser.Tilemaps.Tilemap; - - /** - * Sets collision on a range of tiles in a layer whose index is between the specified `start` and - * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set - * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be - * enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * @param start The first index of the tile to be set for collision. - * @param stop The last index of the tile to be set for collision. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - setCollisionBetween(start: integer, stop: integer, collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property - * that matches the given properties object, its collision flag will be set. The `collides` - * parameter controls if collision will be enabled (true) or disabled (false). Passing in - * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that - * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can - * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a - * "types" property that matches any of those values, its collision flag will be updated. - * - * If no layer specified, the map's current layer is used. - * @param properties An object with tile properties and corresponding values that should be checked. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - setCollisionByProperty(properties: object, collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets collision on all tiles in the given layer, except for tiles that have an index specified in - * the given array. The `collides` parameter controls if collision will be enabled (true) or - * disabled (false). - * - * If no layer specified, the map's current layer is used. - * @param indexes An array of the tile indexes to not be counted for collision. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - setCollisionByExclusion(indexes: integer[], collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets collision on the tiles within a layer by checking each tile's collision group data - * (typically defined in Tiled within the tileset collision editor). If any objects are found within - * a tile's collision group, the tile's colliding information will be set. The `collides` parameter - * controls if collision will be enabled (true) or disabled (false). - * - * If no layer specified, the map's current layer is used. - * @param collides If true it will enable collision. If false it will clear collision. Default true. - * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. - * @param layer The tile layer to use. If not given the current layer is used. - */ - setCollisionFromCollisionGroup(collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets a global collision callback for the given tile index within the layer. This will affect all - * tiles on this layer that have the same index. If a callback is already set for the tile index it - * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile - * at a specific location on the map then see setTileLocationCallback. - * - * If no layer specified, the map's current layer is used. - * @param indexes Either a single tile index, or an array of tile indexes to have a collision callback set for. - * @param callback The callback that will be invoked when the tile is collided with. - * @param callbackContext The context under which the callback is called. - * @param layer The tile layer to use. If not given the current layer is used. - */ - setTileIndexCallback(indexes: integer | any[], callback: Function, callbackContext: object, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to - * remove it. - * - * If no layer specified, the map's current layer is used. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. - * @param width How many tiles wide from the `tileX` index the area will be. - * @param height How many tiles tall from the `tileY` index the area will be. - * @param callback The callback that will be invoked when the tile is collided with. - * @param callbackContext The context under which the callback is called. - * @param layer The tile layer to use. If not given the current layer is used. - */ - setTileLocationCallback(tileX: integer, tileY: integer, width: integer, height: integer, callback: Function, callbackContext?: object, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets the current layer to the LayerData associated with `layer`. - * @param layer The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the map's current layer index. - */ - setLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Sets the base tile size for the map. Note: this does not necessarily match the tileWidth and - * tileHeight for all layers. This also updates the base size on all tiles across all layers. - * @param tileWidth The width of the tiles the map uses for calculations. - * @param tileHeight The height of the tiles the map uses for calculations. - */ - setBaseTileSize(tileWidth: integer, tileHeight: integer): Phaser.Tilemaps.Tilemap; - - /** - * Sets the tile size for a specific `layer`. Note: this does not necessarily match the map's - * tileWidth and tileHeight for all layers. This will set the tile size for the layer and any - * tiles the layer has. - * @param tileWidth The width of the tiles (in pixels) in the layer. - * @param tileHeight The height of the tiles (in pixels) in the layer. - * @param layer The name of the - * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a - * StaticTilemapLayer. If not given will default to the map's current layer index. - */ - setLayerTileSize(tileWidth: integer, tileHeight: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given - * layer. It will only randomize the tiles in that area, so if they're all the same nothing will - * appear to have changed! This method only modifies tile indexes and does not change collision - * information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param layer The tile layer to use. If not given the current layer is used. - */ - shuffle(tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching - * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision - * information. - * - * If no layer specified, the maps current layer is used. - * This cannot be applied to StaticTilemapLayers. - * @param tileA First tile index. - * @param tileB Second tile index. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param layer The tile layer to use. If not given the current layer is used. - */ - swapByIndex(tileA: integer, tileB: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * @param tileX The x coordinate, in tiles, not pixels. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - tileToWorldX(tileX: integer, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; - - /** - * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * @param tileY The y coordinate, in tiles, not pixels. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer - * to use. If not given the current layer is used. - */ - tileToWorldY(tileY: integer, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; - - /** - * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * If no layer specified, the maps current layer is used. - * @param tileX The x coordinate, in tiles, not pixels. - * @param tileY The y coordinate, in tiles, not pixels. - * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - tileToWorldXY(tileX: integer, tileY: integer, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Math.Vector2; - - /** - * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the - * specified layer. Each tile will receive a new index. New indexes are drawn from the given - * weightedIndexes array. An example weighted array: - * - * [ - * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 - * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 - * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 - * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 - * ] - * - * The probability of any index being choose is (the index's weight) / (sum of all weights). This - * method only modifies tile indexes and does not change collision information. - * - * If no layer specified, the map's current layer is used. This - * cannot be applied to StaticTilemapLayers. - * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. - * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. - * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. - * @param weightedIndexes An array of objects to randomly draw from during - * randomization. They should be in the form: { index: 0, weight: 4 } or - * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. - * @param layer The tile layer to use. If not given the current layer is used. - */ - weightedRandomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, weightedIndexes?: object[], layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; - - /** - * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * @param worldX The x coordinate to be converted, in pixels, not tiles. - * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer - * to use. If not given the current layer is used. - */ - worldToTileX(worldX: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; - - /** - * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the - * layers position, scale and scroll. - * - * If no layer specified, the maps current layer is used. - * @param worldY The y coordinate to be converted, in pixels, not tiles. - * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - worldToTileY(worldY: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; - - /** - * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the - * layers position, scale and scroll. This will return a new Vector2 object or update the given - * `point` object. - * - * If no layer specified, the maps current layer is used. - * @param worldX The x coordinate to be converted, in pixels, not tiles. - * @param worldY The y coordinate to be converted, in pixels, not tiles. - * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. - * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. - * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. - * @param layer The tile layer to use. If not given the current layer is used. - */ - worldToTileXY(worldX: number, worldY: number, snapToFloor?: boolean, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Math.Vector2; - - } - - /** - * A Tileset is a combination of an image containing the tiles and a container for data about - * each tile. - */ - class Tileset { - /** - * - * @param name The name of the tileset in the map data. - * @param firstgid The first tile index this tileset contains. - * @param tileWidth Width of each tile (in pixels). Default 32. - * @param tileHeight Height of each tile (in pixels). Default 32. - * @param tileMargin The margin around all tiles in the sheet (in pixels). Default 0. - * @param tileSpacing The spacing between each tile in the sheet (in pixels). Default 0. - * @param tileProperties Custom properties defined per tile in the Tileset. - * These typically are custom properties created in Tiled when editing a tileset. Default {}. - * @param tileData Data stored per tile. These typically are created in Tiled - * when editing a tileset, e.g. from Tiled's tile collision editor or terrain editor. Default {}. - */ - constructor(name: string, firstgid: integer, tileWidth?: integer, tileHeight?: integer, tileMargin?: integer, tileSpacing?: integer, tileProperties?: object, tileData?: object); - - /** - * The name of the Tileset. - */ - name: string; - - /** - * The starting index of the first tile index this Tileset contains. - */ - firstgid: integer; - - /** - * The width of each tile (in pixels). Use setTileSize to change. - */ - readonly tileWidth: integer; - - /** - * The height of each tile (in pixels). Use setTileSize to change. - */ - readonly tileHeight: integer; - - /** - * The margin around the tiles in the sheet (in pixels). Use `setSpacing` to change. - */ - readonly tileMargin: integer; - - /** - * The spacing between each the tile in the sheet (in pixels). Use `setSpacing` to change. - */ - readonly tileSpacing: integer; - - /** - * Tileset-specific properties per tile that are typically defined in the Tiled editor in the - * Tileset editor. - */ - tileProperties: object; - - /** - * Tileset-specific data per tile that are typically defined in the Tiled editor, e.g. within - * the Tileset collision editor. This is where collision objects and terrain are stored. - */ - tileData: object; - - /** - * The cached image that contains the individual tiles. Use setImage to set. - */ - readonly image: Phaser.Textures.Texture; - - /** - * The gl texture used by the WebGL renderer. - */ - readonly glTexture: WebGLTexture; - - /** - * The number of tile rows in the the tileset. - */ - readonly rows: integer; - - /** - * The number of tile columns in the tileset. - */ - readonly columns: integer; - - /** - * The total number of tiles in the tileset. - */ - readonly total: integer; - - /** - * The look-up table to specific tile image texture coordinates (UV in pixels). Each element - * contains the coordinates for a tile in an object of the form {x, y}. - */ - readonly texCoordinates: object[]; - - /** - * Get a tiles properties that are stored in the Tileset. Returns null if tile index is not - * contained in this Tileset. This is typically defined in Tiled under the Tileset editor. - * @param tileIndex The unique id of the tile across all tilesets in the map. - */ - getTileProperties(tileIndex: integer): object | undefined; - - /** - * Get a tile's data that is stored in the Tileset. Returns null if tile index is not contained - * in this Tileset. This is typically defined in Tiled and will contain both Tileset collision - * info and terrain mapping. - * @param tileIndex The unique id of the tile across all tilesets in the map. - */ - getTileData(tileIndex: integer): object | undefined; - - /** - * Get a tile's collision group that is stored in the Tileset. Returns null if tile index is not - * contained in this Tileset. This is typically defined within Tiled's tileset collision editor. - * @param tileIndex The unique id of the tile across all tilesets in the map. - */ - getTileCollisionGroup(tileIndex: integer): object; - - /** - * Returns true if and only if this Tileset contains the given tile index. - * @param tileIndex The unique id of the tile across all tilesets in the map. - */ - containsTileIndex(tileIndex: integer): boolean; - - /** - * Returns the texture coordinates (UV in pixels) in the Tileset image for the given tile index. - * Returns null if tile index is not contained in this Tileset. - * @param tileIndex The unique id of the tile across all tilesets in the map. - */ - getTileTextureCoordinates(tileIndex: integer): object; - - /** - * Sets the image associated with this Tileset and updates the tile data (rows, columns, etc.). - * @param texture The image that contains the tiles. - */ - setImage(texture: Phaser.Textures.Texture): Phaser.Tilemaps.Tileset; - - /** - * Sets the tile width & height and updates the tile data (rows, columns, etc.). - * @param tileWidth The width of a tile in pixels. - * @param tileHeight The height of a tile in pixels. - */ - setTileSize(tileWidth?: integer, tileHeight?: integer): Phaser.Tilemaps.Tileset; - - /** - * Sets the tile margin & spacing and updates the tile data (rows, columns, etc.). - * @param margin The margin around the tiles in the sheet (in pixels). - * @param spacing The spacing between the tiles in the sheet (in pixels). - */ - setSpacing(margin?: integer, spacing?: integer): Phaser.Tilemaps.Tileset; - - /** - * Updates tile texture coordinates and tileset data. - * @param imageWidth The (expected) width of the image to slice. - * @param imageHeight The (expected) height of the image to slice. - */ - updateTileData(imageWidth: integer, imageHeight: integer): Phaser.Tilemaps.Tileset; - - } - - } - - namespace Time { - /** - * The Clock is a Scene plugin which creates and updates Timer Events for its Scene. - */ - class Clock { - /** - * - * @param scene The Scene which owns this Clock. - */ - constructor(scene: Phaser.Scene); - - /** - * The Scene which owns this Clock. - */ - scene: Phaser.Scene; - - /** - * The Scene Systems object of the Scene which owns this Clock. - */ - systems: Phaser.Scenes.Systems; - - /** - * The current time of the Clock, in milliseconds. - * - * If accessed externally, this is equivalent to the `time` parameter normally passed to a Scene's `update` method. - */ - now: number; - - /** - * The scale of the Clock's time delta. - * - * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Clock and anything which uses it, such as its Timer Events. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing the Clock. - */ - timeScale: number; - - /** - * Whether the Clock is paused (`true`) or active (`false`). - * - * When paused, the Clock will not update any of its Timer Events, thus freezing time. - */ - paused: boolean; - - /** - * Creates a Timer Event and adds it to the Clock at the start of the frame. - * @param config The configuration for the Timer Event. - */ - addEvent(config: Phaser.Types.Time.TimerEventConfig): Phaser.Time.TimerEvent; - - /** - * Creates a Timer Event and adds it to the Clock at the start of the frame. - * - * This is a shortcut for {@link #addEvent} which can be shorter and is compatible with the syntax of the GreenSock Animation Platform (GSAP). - * @param delay The delay of the function call, in milliseconds. - * @param callback The function to call after the delay expires. - * @param args The arguments to call the function with. - * @param callbackScope The scope (`this` object) to call the function with. - */ - delayedCall(delay: number, callback: Function, args?: any[], callbackScope?: any): Phaser.Time.TimerEvent; - - /** - * Clears and recreates the array of pending Timer Events. - */ - clearPendingEvents(): Phaser.Time.Clock; - - /** - * Schedules all active Timer Events for removal at the start of the frame. - */ - removeAllEvents(): Phaser.Time.Clock; - - /** - * Updates the arrays of active and pending Timer Events. Called at the start of the frame. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - preUpdate(time: number, delta: number): void; - - /** - * Updates the Clock's internal time and all of its Timer Events. - * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(time: number, delta: number): void; - - } - - /** - * 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 { - /** - * - * @param config The configuration for the Timer Event, including its delay and callback. - */ - constructor(config: Phaser.Types.Time.TimerEventConfig); - - /** - * The delay in ms at which this TimerEvent fires. - */ - readonly delay: number; - - /** - * The total number of times this TimerEvent will repeat before finishing. - */ - readonly repeat: number; - - /** - * If repeating this contains the current repeat count. - */ - repeatCount: number; - - /** - * True if this TimerEvent loops, otherwise false. - */ - readonly loop: boolean; - - /** - * The callback that will be called when the TimerEvent occurs. - */ - callback: Function; - - /** - * The scope in which the callback will be called. - */ - callbackScope: object; - - /** - * Additional arguments to be passed to the callback. - */ - args: any[]; - - /** - * Scale the time causing this TimerEvent to update. - */ - timeScale: number; - - /** - * Start this many MS into the elapsed (useful if you want a long duration with repeat, but for the first loop to fire quickly) - */ - startAt: number; - - /** - * The time in milliseconds which has elapsed since the Timer Event's creation. - * - * This value is local for the Timer Event and is relative to its Clock. As such, it's influenced by the Clock's time scale and paused state, the Timer Event's initial {@link #startAt} property, and the Timer Event's {@link #timeScale} and {@link #paused} state. - */ - elapsed: number; - - /** - * Whether or not this timer is paused. - */ - paused: boolean; - - /** - * Whether the Timer Event's function has been called. - * - * When the Timer Event fires, this property will be set to `true` before the callback function is invoked and will be reset immediately afterward if the Timer Event should repeat. The value of this property does not directly influence whether the Timer Event will be removed from its Clock, but can prevent it from firing. - */ - hasDispatched: boolean; - - /** - * Completely reinitializes the Timer Event, regardless of its current state, according to a configuration object. - * @param config The new state for the Timer Event. - */ - reset(config: Phaser.Types.Time.TimerEventConfig): Phaser.Time.TimerEvent; - - /** - * Gets the progress of the current iteration, not factoring in repeats. - */ - getProgress(): number; - - /** - * Gets the progress of the timer overall, factoring in repeats. - */ - getOverallProgress(): number; - - /** - * Returns the number of times this Timer Event will repeat before finishing. - * - * This should not be confused with the number of times the Timer Event will fire before finishing. A return value of 0 doesn't indicate that the Timer Event has finished running - it indicates that it will not repeat after the next time it fires. - */ - getRepeatCount(): number; - - /** - * Returns the local elapsed time for the current iteration of the Timer Event. - */ - getElapsed(): number; - - /** - * Returns the local elapsed time for the current iteration of the Timer Event in seconds. - */ - getElapsedSeconds(): number; - - /** - * Forces the Timer Event to immediately expire, thus scheduling its removal in the next frame. - * @param dispatchCallback If `true`, the function of the Timer Event will be called before its removal. Default false. - */ - remove(dispatchCallback?: boolean): void; - - /** - * Destroys all object references in the Timer Event, i.e. its callback, scope, and arguments. - * - * Normally, this method is only called by the Clock when it shuts down. As such, it doesn't stop the Timer Event. If called manually, the Timer Event will still be updated by the Clock, but it won't do anything when it fires. - */ - destroy(): void; - - } - - } - - namespace Tweens { - namespace Builders { - /** - * Retrieves the value of the given key from an object. - * @param source The object to retrieve the value from. - * @param key The key to look for in the `source` object. - * @param defaultValue The default value to return if the `key` doesn't exist or if no `source` object is provided. - */ - function GetBoolean(source: object, key: string, defaultValue: any): any; - - /** - * This internal function is used to return the correct ease function for a Tween. - * - * It can take a variety of input, including an EaseMap based string, or a custom function. - * @param ease The ease to find. This can be either a string from the EaseMap, or a custom function. - * @param easeParams An optional array of ease parameters to go with the ease. - */ - function GetEaseFunction(ease: string | Function, easeParams?: number[]): Function; - - /** - * Internal function used by the Tween Builder to create a function that will return - * the given value from the source. - * @param source The source object to get the value from. - * @param key The property to get from the source. - * @param defaultValue A default value to return should the source not have the property set. - */ - function GetNewValue(source: any, key: string, defaultValue: any): Function; - - /** - * Internal function used by the Tween Builder to return an array of properties - * that the Tween will be operating on. It takes a tween configuration object - * and then checks that none of the `props` entries start with an underscore, or that - * none of the direct properties are on the Reserved list. - * @param config The configuration object of the Tween to get the properties from. - */ - function GetProps(config: Phaser.Types.Tweens.TweenBuilderConfig): string[]; - - /** - * Extracts an array of targets from a Tween configuration object. - * - * The targets will be looked for in a `targets` property. If it's a function, its return value will be used as the result. - * @param config The configuration object to use. - */ - function GetTargets(config: object): any[]; - - /** - * Internal function used by the Timeline Builder. - * - * It returns an array of all tweens in the given timeline config. - * @param config The configuration object for the Timeline. - */ - function GetTweens(config: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Tween[]; - - /** - * 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. - * - * 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. - * @param key The name of the property to modify. - * @param propertyValue The ending value of the property, as described above. - */ - function GetValueOp(key: string, propertyValue: any): Function; - - /** - * Creates a new Number Tween. - * @param parent The owner of the new Tween. - * @param config Configuration for the new Tween. - * @param defaults Tween configuration defaults. - */ - function NumberTweenBuilder(parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline, config: Phaser.Types.Tweens.NumberTweenBuilderConfig, defaults: Phaser.Types.Tweens.TweenConfigDefaults): Phaser.Tweens.Tween; - - /** - * 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' }) - * }); - * ``` - * @param value The amount to stagger by, or an array containing two elements representing the min and max values to stagger between. - * @param config A Stagger Configuration object. - */ - function StaggerBuilder(value: number | number[], config?: Phaser.Types.Tweens.StaggerConfig): Function; - - /** - * Builds a Timeline of Tweens based on a configuration object. - * @param manager The Tween Manager to which the Timeline will belong. - * @param config The configuration object for the Timeline. - */ - function TimelineBuilder(manager: Phaser.Tweens.TweenManager, config: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Timeline; - - /** - * Creates a new Tween. - * @param parent The owner of the new Tween. - * @param config Configuration for the new Tween. - * @param defaults Tween configuration defaults. - */ - function TweenBuilder(parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline, config: Phaser.Types.Tweens.TweenBuilderConfig | object, defaults: Phaser.Types.Tweens.TweenConfigDefaults): Phaser.Tweens.Tween; - - } - - namespace Events { - /** - * The Timeline Complete Event. - * - * This event is dispatched by a Tween Timeline when it completes playback. - * - * Listen to it from a Timeline instance using `Timeline.on('complete', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('complete', listener); - * timeline.play(); - * ``` - */ - const TIMELINE_COMPLETE: any; - - /** - * The Timeline Loop Event. - * - * This event is dispatched by a Tween Timeline every time it loops. - * - * Listen to it from a Timeline instance using `Timeline.on('loop', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * loop: 4, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('loop', listener); - * timeline.play(); - * ``` - */ - const TIMELINE_LOOP: any; - - /** - * The Timeline Pause Event. - * - * This event is dispatched by a Tween Timeline when it is paused. - * - * Listen to it from a Timeline instance using `Timeline.on('pause', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('pause', listener); - * // At some point later ... - * timeline.pause(); - * ``` - */ - const TIMELINE_PAUSE: any; - - /** - * The Timeline Resume Event. - * - * This event is dispatched by a Tween Timeline when it is resumed from a paused state. - * - * Listen to it from a Timeline instance using `Timeline.on('resume', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('resume', listener); - * // At some point later ... - * timeline.resume(); - * ``` - */ - const TIMELINE_RESUME: any; - - /** - * The Timeline Start Event. - * - * This event is dispatched by a Tween Timeline when it starts. - * - * Listen to it from a Timeline instance using `Timeline.on('start', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('start', listener); - * timeline.play(); - * ``` - */ - const TIMELINE_START: any; - - /** - * The Timeline Update Event. - * - * This event is dispatched by a Tween Timeline every time it updates, which can happen a lot of times per second, - * so be careful about listening to this event unless you absolutely require it. - * - * Listen to it from a Timeline instance using `Timeline.on('update', listener)`, i.e.: - * - * ```javascript - * var timeline = this.tweens.timeline({ - * targets: image, - * ease: 'Power1', - * duration: 3000, - * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] - * }); - * timeline.on('update', listener); - * timeline.play(); - * ``` - */ - const TIMELINE_UPDATE: any; - - /** - * The Tween Active Event. - * - * This event is dispatched by a Tween when it becomes active within the Tween Manager. - * - * An 'active' Tween is one that is now progressing, although it may not yet be updating - * any target properties, due to settings such as `delay`. If you need an event for when - * the Tween starts actually updating its first property, see `TWEEN_START`. - * - * Listen to it from a Tween instance using `Tween.on('active', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000 - * }); - * tween.on('active', listener); - * ``` - */ - const TWEEN_ACTIVE: any; - - /** - * The Tween Complete Event. - * - * This event is dispatched by a Tween when it completes playback entirely, factoring in repeats and loops. - * - * If the Tween has been set to loop or repeat infinitely, this event will not be dispatched - * unless the `Tween.stop` method is called. - * - * If a Tween has a `completeDelay` set, this event will fire after that delay expires. - * - * Listen to it from a Tween instance using `Tween.on('complete', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000 - * }); - * tween.on('complete', listener); - * ``` - */ - const TWEEN_COMPLETE: any; - - /** - * The Tween Loop Event. - * - * This event is dispatched by a Tween when it loops. - * - * This event will only be dispatched if the Tween has a loop count set. - * - * If a Tween has a `loopDelay` set, this event will fire after that delay expires. - * - * The difference between `loop` and `repeat` is that `repeat` is a property setting, - * where-as `loop` applies to the entire Tween. - * - * Listen to it from a Tween instance using `Tween.on('loop', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * loop: 6 - * }); - * tween.on('loop', listener); - * ``` - */ - const TWEEN_LOOP: any; - - /** - * The Tween Repeat Event. - * - * This event is dispatched by a Tween when one of the properties it is tweening repeats. - * - * This event will only be dispatched if the Tween has a property with a repeat count set. - * - * If a Tween has a `repeatDelay` set, this event will fire after that delay expires. - * - * The difference between `loop` and `repeat` is that `repeat` is a property setting, - * where-as `loop` applies to the entire Tween. - * - * Listen to it from a Tween instance using `Tween.on('repeat', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * repeat: 4 - * }); - * tween.on('repeat', listener); - * ``` - */ - const TWEEN_REPEAT: any; - - /** - * The Tween Start Event. - * - * This event is dispatched by a Tween when it starts tweening its first property. - * - * A Tween will only emit this event once, as it can only start once. - * - * If a Tween has a `delay` set, this event will fire after that delay expires. - * - * Listen to it from a Tween instance using `Tween.on('start', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000 - * }); - * tween.on('start', listener); - * ``` - */ - const TWEEN_START: any; - - /** - * The Tween Update Event. - * - * This event is dispatched by a Tween every time it updates _any_ of the properties it is tweening. - * - * A Tween that is changing 3 properties of a target will emit this event 3 times per change, once per property. - * - * **Note:** This is a very high frequency event and may be dispatched multiple times, every single frame. - * - * Listen to it from a Tween instance using `Tween.on('update', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * }); - * tween.on('update', listener); - * ``` - */ - const TWEEN_UPDATE: any; - - /** - * The Tween Yoyo Event. - * - * This event is dispatched by a Tween whenever a property it is tweening yoyos. - * - * This event will only be dispatched if the Tween has a property with `yoyo` set. - * - * If the Tween has a `hold` value, this event is dispatched when the hold expires. - * - * This event is dispatched for every property, and for every target, that yoyos. - * For example, if a Tween was updating 2 properties and had 10 targets, this event - * would be dispatched 20 times (twice per target). So be careful how you use it! - * - * Listen to it from a Tween instance using `Tween.on('yoyo', listener)`, i.e.: - * - * ```javascript - * var tween = this.tweens.add({ - * targets: image, - * x: 500, - * ease: 'Power1', - * duration: 3000, - * yoyo: true - * }); - * tween.on('yoyo', listener); - * ``` - */ - const TWEEN_YOYO: any; - - } - - /** - * A Timeline combines multiple Tweens into one. Its overall behavior is otherwise similar to a single Tween. - * - * The Timeline updates all of its Tweens simultaneously. Its methods allow you to easily build a sequence - * of Tweens (each one starting after the previous one) or run multiple Tweens at once during given parts of the Timeline. - */ - class Timeline extends Phaser.Events.EventEmitter { - /** - * - * @param manager The Tween Manager which owns this Timeline. - */ - constructor(manager: Phaser.Tweens.TweenManager); - - /** - * The Tween Manager which owns this Timeline. - */ - manager: Phaser.Tweens.TweenManager; - - /** - * A constant value which allows this Timeline to be easily identified as one. - */ - isTimeline: boolean; - - /** - * An array of Tween objects, each containing a unique property and target being tweened. - */ - data: any[]; - - /** - * The cached size of the data array. - */ - totalData: number; - - /** - * If true then duration, delay, etc values are all frame totals, rather than ms. - */ - useFrames: boolean; - - /** - * Scales the time applied to this Timeline. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. - * Value isn't used when calculating total duration of the Timeline, it's a run-time delta adjustment only. - */ - timeScale: number; - - /** - * Loop this Timeline? Can be -1 for an infinite loop, or an integer. - * When enabled it will play through ALL Tweens again (use Tween.repeat to loop a single tween) - */ - loop: number; - - /** - * Time in ms/frames before this Timeline loops. - */ - loopDelay: number; - - /** - * How many loops are left to run? - */ - loopCounter: number; - - /** - * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = true (as it never completes) - */ - completeDelay: number; - - /** - * Countdown timer value, as used by `loopDelay` and `completeDelay`. - */ - countdown: number; - - /** - * The current state of the Timeline. - */ - state: integer; - - /** - * Does the Timeline start off paused? (if so it needs to be started with Timeline.play) - */ - paused: boolean; - - /** - * Elapsed time in ms/frames of this run through of the Timeline. - */ - elapsed: number; - - /** - * Total elapsed time in ms/frames of the entire Timeline, including looping. - */ - totalElapsed: number; - - /** - * Time in ms/frames for the whole Timeline to play through once, excluding loop amounts and loop delays. - */ - duration: number; - - /** - * Value between 0 and 1. The amount of progress through the Timeline, _excluding loops_. - */ - progress: number; - - /** - * Time in ms/frames for all Tweens in this Timeline to complete (including looping) - */ - totalDuration: number; - - /** - * Value between 0 and 1. The amount through the entire Timeline, including looping. - */ - totalProgress: number; - - /** - * An object containing the different Tween callback functions. - * - * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. - * - * `onComplete` When the Timeline finishes playback fully or `Timeline.stop` is called. Never invoked if timeline is set to repeat infinitely. - * `onLoop` When a Timeline loops. - * `onStart` When the Timeline starts playing. - * `onUpdate` When a Timeline updates a child Tween. - * `onYoyo` When a Timeline starts a yoyo. - */ - callbacks: object; - - /** - * The context in which all callbacks are invoked. - */ - callbackScope: any; - - /** - * Internal method that will emit a Timeline based Event and invoke the given callback. - * @param event The Event to be dispatched. - * @param callback The callback to be invoked. Can be `null` or `undefined` to skip invocation. - */ - dispatchTimelineEvent(event: Phaser.Types.Tweens.Event, callback: Function): void; - - /** - * Sets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. - * A value of 0.5 runs 50% slower, and so on. - * - * The value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. - * @param value The time scale value to set. - */ - setTimeScale(value: number): this; - - /** - * Gets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. - * A value of 0.5 runs 50% slower, and so on. - */ - getTimeScale(): number; - - /** - * Check whether or not the Timeline is playing. - */ - isPlaying(): boolean; - - /** - * Creates a new Tween, based on the given Tween Config, and adds it to this Timeline. - * @param config The configuration object for the Tween. - */ - add(config: Phaser.Types.Tweens.TweenBuilderConfig | object): this; - - /** - * Adds an existing Tween to this Timeline. - * @param tween The Tween to be added to this Timeline. - */ - queue(tween: Phaser.Tweens.Tween): this; - - /** - * Checks whether a Tween has an offset value. - * @param tween The Tween to check. - */ - hasOffset(tween: Phaser.Tweens.Tween): boolean; - - /** - * Checks whether the offset value is a number or a directive that is relative to previous tweens. - * @param value The offset value to be evaluated. - */ - isOffsetAbsolute(value: number): boolean; - - /** - * Checks if the offset is a relative value rather than an absolute one. - * If the value is just a number, this returns false. - * @param value The offset value to be evaluated. - */ - isOffsetRelative(value: string): boolean; - - /** - * Parses the relative offset value, returning a positive or negative number. - * @param value The relative offset, in the format of '-=500', for example. The first character determines whether it will be a positive or negative number. Spacing matters here. - * @param base The value to use as the offset. - */ - getRelativeOffset(value: string, base: number): number; - - /** - * Calculates the total duration of the timeline. - * - * Computes all tween durations and returns the full duration of the timeline. - * - * The resulting number is stored in the timeline, not as a return value. - */ - calcDuration(): void; - - /** - * Initializes the timeline, which means all Tweens get their init() called, and the total duration will be computed. - * Returns a boolean indicating whether the timeline is auto-started or not. - */ - init(): boolean; - - /** - * Resets all of the timeline's tweens back to their initial states. - * The boolean parameter indicates whether tweens that are looping should reset as well, or not. - * @param resetFromLoop If `true`, resets all looping tweens to their initial values. - */ - resetTweens(resetFromLoop: boolean): void; - - /** - * Sets a callback for the Timeline. - * @param type The internal type of callback to set. - * @param callback Timeline allows multiple tweens to be linked together to create a streaming sequence. - * @param params The parameters to pass to the callback. - * @param scope The context scope of the callback. - */ - setCallback(type: string, callback: Function, params?: any[], scope?: object): this; - - /** - * Passed a Tween to the Tween Manager and requests it be made active. - * @param tween The tween object to make active. - */ - makeActive(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; - - /** - * Starts playing the Timeline. - */ - play(): void; - - /** - * Updates the Timeline's `state` and fires callbacks and events. - */ - nextState(): void; - - /** - * Returns 'true' if this Timeline has finished and should be removed from the Tween Manager. - * Otherwise, returns false. - * @param timestamp The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(timestamp: number, delta: number): boolean; - - /** - * Stops the Timeline immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. - */ - stop(): void; - - /** - * Pauses the Timeline, retaining its internal state. - * - * Calling this on a Timeline that is already paused has no effect and fires no event. - */ - pause(): this; - - /** - * Resumes a paused Timeline from where it was when it was paused. - * - * Calling this on a Timeline that isn't paused has no effect and fires no event. - */ - resume(): this; - - /** - * Checks if any of the Tweens in this Timeline as operating on the target object. - * - * Returns `false` if no Tweens operate on the target object. - * @param target The target to check all Tweens against. - */ - hasTarget(target: object): boolean; - - /** - * Stops all the Tweens in the Timeline immediately, whatever stage of progress they are at and flags - * them for removal by the TweenManager. - */ - destroy(): void; - - } - - /** - * TweenData state. - */ - var CREATED: integer; - - /** - * TweenData state. - */ - var INIT: integer; - - /** - * TweenData state. - */ - var DELAY: integer; - - /** - * TweenData state. - */ - var OFFSET_DELAY: integer; - - /** - * TweenData state. - */ - var PENDING_RENDER: integer; - - /** - * TweenData state. - */ - var PLAYING_FORWARD: integer; - - /** - * TweenData state. - */ - var PLAYING_BACKWARD: integer; - - /** - * TweenData state. - */ - var HOLD_DELAY: integer; - - /** - * TweenData state. - */ - var REPEAT_DELAY: integer; - - /** - * TweenData state. - */ - var COMPLETE: integer; - - /** - * Tween state. - */ - var PENDING_ADD: integer; - - /** - * Tween state. - */ - var PAUSED: integer; - - /** - * Tween state. - */ - var LOOP_DELAY: integer; - - /** - * Tween state. - */ - var ACTIVE: integer; - - /** - * Tween state. - */ - var COMPLETE_DELAY: integer; - - /** - * Tween state. - */ - var PENDING_REMOVE: integer; - - /** - * Tween state. - */ - var REMOVED: integer; - - /** - * A Tween is able to manipulate the properties of one or more objects to any given value, based - * on a duration and type of ease. They are rarely instantiated directly and instead should be - * created via the TweenManager. - */ - class Tween extends Phaser.Events.EventEmitter { - /** - * - * @param parent A reference to the parent of this Tween. Either the Tween Manager or a Tween Timeline instance. - * @param data An array of TweenData objects, each containing a unique property to be tweened. - * @param targets An array of targets to be tweened. - */ - constructor(parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline, data: Phaser.Types.Tweens.TweenDataConfig[], targets: any[]); - - /** - * A reference to the parent of this Tween. - * Either the Tween Manager or a Tween Timeline instance. - */ - parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline; - - /** - * Is the parent of this Tween a Timeline? - */ - parentIsTimeline: boolean; - - /** - * An array of TweenData objects, each containing a unique property and target being tweened. - */ - data: Phaser.Types.Tweens.TweenDataConfig[]; - - /** - * The cached length of the data array. - */ - totalData: integer; - - /** - * An array of references to the target/s this Tween is operating on. - */ - targets: object[]; - - /** - * Cached target total (not necessarily the same as the data total) - */ - totalTargets: integer; - - /** - * If `true` then duration, delay, etc values are all frame totals. - */ - useFrames: boolean; - - /** - * Scales the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. - * Value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. - */ - timeScale: number; - - /** - * Loop this tween? Can be -1 for an infinite loop, or an integer. - * When enabled it will play through ALL TweenDatas again. Use TweenData.repeat to loop a single element. - */ - loop: number; - - /** - * Time in ms/frames before the tween loops. - */ - loopDelay: number; - - /** - * How many loops are left to run? - */ - loopCounter: number; - - /** - * Time in ms/frames before the 'onStart' event fires. - * This is the shortest `delay` value across all of the TweenDatas of this Tween. - */ - startDelay: number; - - /** - * Has this Tween started playback yet? - * This boolean is toggled when the Tween leaves the 'delayed' state and starts running. - */ - readonly hasStarted: boolean; - - /** - * Is this Tween currently seeking? - * This boolean is toggled in the `Tween.seek` method. - * When a tween is seeking it will not dispatch any events or callbacks. - */ - readonly isSeeking: boolean; - - /** - * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = -1 (as it never completes) - */ - completeDelay: number; - - /** - * Countdown timer (used by timeline offset, loopDelay and completeDelay) - */ - countdown: number; - - /** - * Set only if this Tween is part of a Timeline. - */ - offset: number; - - /** - * Set only if this Tween is part of a Timeline. The calculated offset amount. - */ - calculatedOffset: number; - - /** - * The current state of the tween - */ - state: integer; - - /** - * Does the Tween start off paused? (if so it needs to be started with Tween.play) - */ - paused: boolean; - - /** - * Elapsed time in ms/frames of this run through the Tween. - */ - elapsed: number; - - /** - * Total elapsed time in ms/frames of the entire Tween, including looping. - */ - totalElapsed: number; - - /** - * Time in ms/frames for the whole Tween to play through once, excluding loop amounts and loop delays. - */ - duration: number; - - /** - * Value between 0 and 1. The amount through the Tween, excluding loops. - */ - progress: number; - - /** - * Time in ms/frames for the Tween to complete (including looping) - */ - totalDuration: number; - - /** - * Value between 0 and 1. The amount through the entire Tween, including looping. - */ - totalProgress: number; - - /** - * An object containing the different Tween callback functions. - * - * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. - * - * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. - * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. - * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. - * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. - * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. - * `onUpdate` When a TweenData updates a property on a source target during playback. - * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. - */ - callbacks: object; - - /** - * The context in which all callbacks are invoked. - */ - callbackScope: any; - - /** - * Returns the current value of the specified Tween Data. - * @param index The Tween Data to return the value from. Default 0. - */ - getValue(index?: integer): number; - - /** - * Set the scale the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. - * @param value The scale factor for timescale. - */ - setTimeScale(value: number): this; - - /** - * Returns the scale of the time applied to this Tween. - */ - getTimeScale(): number; - - /** - * Checks if the Tween is currently active. - */ - isPlaying(): boolean; - - /** - * Checks if the Tween is currently paused. - */ - isPaused(): boolean; - - /** - * See if this Tween is currently acting upon the given target. - * @param target The target to check against this Tween. - */ - hasTarget(target: object): boolean; - - /** - * Updates the 'end' value of the given property across all matching targets. - * - * Calling this does not adjust the duration of the tween, or the current progress. - * - * You can optionally tell it to set the 'start' value to be the current value (before the change). - * @param key The property to set the new value for. - * @param value The new value of the property. - * @param startToCurrent Should this change set the start value to be the current value? Default false. - */ - updateTo(key: string, value: any, startToCurrent?: boolean): this; - - /** - * Restarts the tween from the beginning. - */ - restart(): this; - - /** - * Internal method that calculates the overall duration of the Tween. - */ - calcDuration(): void; - - /** - * Called by TweenManager.preUpdate as part of its loop to check pending and active tweens. - * Should not be called directly. - */ - init(): boolean; - - /** - * Internal method that makes this Tween active within the TweenManager - * and emits the onActive event and callback. - */ - makeActive(): void; - - /** - * Internal method that advances to the next state of the Tween during playback. - */ - nextState(): void; - - /** - * Pauses the Tween immediately. Use `resume` to continue playback. - */ - pause(): this; - - /** - * Starts a Tween playing. - * - * You only need to call this method if you have configured the tween to be paused on creation. - * - * If the Tween is already playing, calling this method again will have no effect. If you wish to - * restart the Tween, use `Tween.restart` instead. - * - * Calling this method after the Tween has completed will start the Tween playing again from the start. - * This is the same as calling `Tween.seek(0)` and then `Tween.play()`. - * @param resetFromTimeline Is this Tween being played as part of a Timeline? Default false. - */ - play(resetFromTimeline?: boolean): this; - - /** - * Internal method that resets all of the Tween Data, including the progress and elapsed values. - * @param resetFromLoop Has this method been called as part of a loop? - */ - resetTweenData(resetFromLoop: boolean): void; - - /** - * Resumes the playback of a previously paused Tween. - */ - resume(): this; - - /** - * Seeks to a specific point in the Tween. - * - * **Note:** You cannot seek a Tween that repeats or loops forever, or that has an unusually long total duration. - * - * The given position is a value between 0 and 1 which represents how far through the Tween to seek to. - * A value of 0.5 would seek to half-way through the Tween, where-as a value of zero would seek to the start. - * - * Note that the seek 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 0.5 would seek to 3 seconds into the Tween, as that's half-way through its _entire_ duration. - * - * 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. - * @param toPosition A value between 0 and 1 which represents the progress point to seek to. - * @param delta The size of each step when seeking through the Tween. A higher value completes faster but at a cost of less precision. Default 16.6. - */ - seek(toPosition: number, delta?: number): this; - - /** - * Sets an event based callback to be invoked during playback. - * - * Calling this method will replace a previously set callback for the given type, if any exists. - * - * The types available are: - * - * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. - * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. - * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. - * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. - * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. - * `onUpdate` When a TweenData updates a property on a source target during playback. - * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. - * @param type Type of the callback to set. - * @param callback The function to invoke when this callback happens. - * @param params An array of parameters for specified callbacks types. - * @param scope The context the callback will be invoked in. - */ - setCallback(type: string, callback: Function, params?: any[], scope?: any): this; - - /** - * Flags the Tween as being complete, whatever stage of progress it is at. - * - * If an onComplete callback has been defined it will automatically invoke it, unless a `delay` - * argument is provided, in which case the Tween will delay for that period of time before calling the callback. - * - * If you don't need a delay, or have an onComplete callback, then call `Tween.stop` instead. - * @param delay The time to wait before invoking the complete callback. If zero it will fire immediately. Default 0. - */ - complete(delay?: number): this; - - /** - * Immediately removes this Tween from the TweenManager and all of its internal arrays, - * no matter what stage it as it. Then sets the tween state to `REMOVED`. - * - * You should dispose of your reference to this tween after calling this method, to - * free it from memory. - */ - remove(): this; - - /** - * Stops the Tween immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. - * @param resetTo If you want to seek the tween, provide a value between 0 and 1. - */ - stop(resetTo?: number): this; - - /** - * Internal method that advances the Tween based on the time values. - * @param timestamp The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(timestamp: number, delta: number): boolean; - - /** - * Internal method that will emit a TweenData based Event and invoke the given callback. - * @param event The Event to be dispatched. - * @param callback The callback to be invoked. Can be `null` or `undefined` to skip invocation. - * @param tweenData The TweenData object that caused this event. - */ - dispatchTweenDataEvent(event: Phaser.Types.Tweens.Event, callback: Function, tweenData: Phaser.Types.Tweens.TweenDataConfig): void; - - /** - * Internal method that will emit a Tween based Event and invoke the given callback. - * @param event The Event to be dispatched. - * @param callback The callback to be invoked. Can be `null` or `undefined` to skip invocation. - */ - dispatchTweenEvent(event: Phaser.Types.Tweens.Event, callback: Function): void; - - /** - * Internal method used as part of the playback process that sets a tween to play in reverse. - * @param tween The Tween to update. - * @param tweenData The TweenData property to update. - * @param diff Any extra time that needs to be accounted for in the elapsed and progress values. - */ - setStateFromEnd(tween: Phaser.Tweens.Tween, tweenData: Phaser.Types.Tweens.TweenDataConfig, diff: number): integer; - - /** - * Internal method used as part of the playback process that sets a tween to play from the start. - * @param tween The Tween to update. - * @param tweenData The TweenData property to update. - * @param diff Any extra time that needs to be accounted for in the elapsed and progress values. - */ - setStateFromStart(tween: Phaser.Tweens.Tween, tweenData: Phaser.Types.Tweens.TweenDataConfig, diff: number): integer; - - /** - * Internal method that advances the TweenData based on the time value given. - * @param tween The Tween to update. - * @param tweenData The TweenData property to update. - * @param delta Either a value in ms, or 1 if Tween.useFrames is true. - */ - updateTweenData(tween: Phaser.Tweens.Tween, tweenData: Phaser.Types.Tweens.TweenDataConfig, delta: number): boolean; - - } - - /** - * Returns a TweenDataConfig object that describes the tween data for a unique property of a unique target. - * A single Tween consists of multiple TweenDatas, depending on how many properties are being changed by the Tween. - * - * This is an internal function used by the TweenBuilder and should not be accessed directly, instead, - * Tweens should be created using the GameObjectFactory or GameObjectCreator. - * @param target The target to tween. - * @param index The target index within the Tween targets array. - * @param key The property of the target to tween. - * @param getEnd What the property will be at the END of the Tween. - * @param getStart What the property will be at the START of the Tween. - * @param getActive If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. - * @param ease The ease function this tween uses. - * @param delay Time in ms/frames before tween will start. - * @param duration Duration of the tween in ms/frames. - * @param yoyo Determines whether the tween should return back to its start value after hold has expired. - * @param hold Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. - * @param repeat Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. - * @param repeatDelay Time in ms/frames before the repeat will start. - * @param flipX Should toggleFlipX be called when yoyo or repeat happens? - * @param flipY Should toggleFlipY be called when yoyo or repeat happens? - */ - function TweenData(target: any, index: integer, key: string, getEnd: Function, getStart: Function, getActive: Function, ease: Function, delay: number, duration: number, yoyo: boolean, hold: number, repeat: number, repeatDelay: number, flipX: boolean, flipY: boolean): Phaser.Types.Tweens.TweenDataConfig; - - /** - * The Tween Manager is a default Scene Plugin which controls and updates Tweens and Timelines. - */ - class TweenManager { - /** - * - * @param scene The Scene which owns this Tween Manager. - */ - constructor(scene: Phaser.Scene); - - /** - * The Scene which owns this Tween Manager. - */ - scene: Phaser.Scene; - - /** - * The Systems object of the Scene which owns this Tween Manager. - */ - systems: Phaser.Scenes.Systems; - - /** - * The time scale of the Tween Manager. - * - * This value scales the time delta between two frames, thus influencing the speed of time for all Tweens owned by this Tween Manager. - */ - timeScale: number; - - /** - * Create a Tween Timeline and return it, but do NOT add it to the active or pending Tween lists. - * @param config The configuration object for the Timeline and its Tweens. - */ - createTimeline(config?: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Timeline; - - /** - * Create a Tween Timeline and add it to the active Tween list/ - * @param config The configuration object for the Timeline and its Tweens. - */ - timeline(config?: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Timeline; - - /** - * Create a Tween and return it, but do NOT add it to the active or pending Tween lists. - * @param config The configuration object for the Tween. - */ - create(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; - - /** - * Create a Tween and add it to the active Tween list. - * @param config The configuration object for the Tween. - */ - add(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; - - /** - * Add an existing tween into the active Tween list. - * @param tween The Tween to add. - */ - existing(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; - - /** - * Create a Number Tween and add it to the active Tween list. - * @param config The configuration object for the Number Tween. - */ - addCounter(config: Phaser.Types.Tweens.NumberTweenBuilderConfig): Phaser.Tweens.Tween; - - /** - * 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' }) - * }); - * ``` - * @param value The amount to stagger by, or an array containing two elements representing the min and max values to stagger between. - * @param config The configuration object for the Stagger function. - */ - stagger(value: number | number[], config: Phaser.Types.Tweens.StaggerConfig): Function; - - /** - * Updates the Tween Manager's internal lists at the start of the frame. - * - * This method will return immediately if no changes have been indicated. - */ - preUpdate(): void; - - /** - * Updates all Tweens and Timelines of the Tween Manager. - * @param timestamp The current time in milliseconds. - * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. - */ - update(timestamp: number, delta: number): void; - - /** - * Removes the given tween from the Tween Manager, regardless of its state (pending or active). - * @param tween The Tween to be removed. - */ - remove(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; - - /** - * Checks if a Tween or Timeline is active and adds it to the Tween Manager at the start of the frame if it isn't. - * @param tween The Tween to check. - */ - makeActive(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; - - /** - * Passes all Tweens to the given callback. - * @param callback The function to call. - * @param scope The scope (`this` object) to call the function with. - * @param args The arguments to pass into the function. Its first argument will always be the Tween currently being iterated. - */ - each(callback: Function, scope?: object, ...args: any[]): void; - - /** - * Returns an array of all active Tweens and Timelines in the Tween Manager. - */ - getAllTweens(): Phaser.Tweens.Tween[]; - - /** - * Returns the scale of the time delta for all Tweens and Timelines owned by this Tween Manager. - */ - getGlobalTimeScale(): number; - - /** - * Returns an array of all Tweens or Timelines in the Tween Manager which affect the given target or array of targets. - * @param target The target to look for. Provide an array to look for multiple targets. - */ - getTweensOf(target: object | any[]): Phaser.Tweens.Tween[]; - - /** - * Checks if the given object is being affected by a playing Tween. - * @param target target Phaser.Tweens.Tween object - */ - isTweening(target: object): boolean; - - /** - * Stops all Tweens in this Tween Manager. They will be removed at the start of the frame. - */ - killAll(): Phaser.Tweens.TweenManager; - - /** - * Stops all Tweens which affect the given target or array of targets. The Tweens will be removed from the Tween Manager at the start of the frame. - * @param target The target to look for. Provide an array to look for multiple targets. - */ - killTweensOf(target: object | any[]): Phaser.Tweens.TweenManager; - - /** - * Pauses all Tweens in this Tween Manager. - */ - pauseAll(): Phaser.Tweens.TweenManager; - - /** - * Resumes all Tweens in this Tween Manager. - */ - resumeAll(): Phaser.Tweens.TweenManager; - - /** - * Sets a new scale of the time delta for this Tween Manager. - * - * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Tween Manager and all Tweens it owns. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing all Tweens. - * @param value The new scale of the time delta, where 1 is the normal speed. - */ - setGlobalTimeScale(value: number): Phaser.Tweens.TweenManager; - - /** - * The Scene that owns this plugin is shutting down. - * We need to kill and reset all internal properties as well as stop listening to Scene events. - */ - shutdown(): void; - - /** - * The Scene that owns this plugin is being destroyed. - * We need to shutdown and then kill off all external references. - */ - destroy(): void; - - } - - } - - namespace Utils { - namespace Array { - /** - * Adds the given item, or array of items, to the array. - * - * Each item must be unique within the array. - * - * The array is modified in-place and returned. - * - * You can optionally specify a limit to the maximum size of the array. If the quantity of items being - * added will take the array length over this limit, it will stop adding once the limit is reached. - * - * You can optionally specify a callback to be invoked for each item successfully added to the array. - * @param array The array to be added to. - * @param item The item, or array of items, to add to the array. Each item must be unique within the array. - * @param limit Optional limit which caps the size of the array. - * @param callback A callback to be invoked for each item successfully added to the array. - * @param context The context in which the callback is invoked. - */ - function Add(array: any[], item: any | any[], limit?: integer, callback?: Function, context?: object): any[]; - - /** - * Adds the given item, or array of items, to the array starting at the index specified. - * - * Each item must be unique within the array. - * - * Existing elements in the array are shifted up. - * - * The array is modified in-place and returned. - * - * You can optionally specify a limit to the maximum size of the array. If the quantity of items being - * added will take the array length over this limit, it will stop adding once the limit is reached. - * - * You can optionally specify a callback to be invoked for each item successfully added to the array. - * @param array The array to be added to. - * @param item The item, or array of items, to add to the array. - * @param index The index in the array where the item will be inserted. Default 0. - * @param limit Optional limit which caps the size of the array. - * @param callback A callback to be invoked for each item successfully added to the array. - * @param context The context in which the callback is invoked. - */ - function AddAt(array: any[], item: any | any[], index?: integer, limit?: integer, callback?: Function, context?: object): any[]; - - /** - * Moves the given element to the top of the array. - * The array is modified in-place. - * @param array The array. - * @param item The element to move. - */ - function BringToTop(array: any[], item: any): any; - - /** - * Returns the total number of elements in the array which have a property matching the given value. - * @param array The array to search. - * @param 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 startIndex An optional start index to search from. - * @param endIndex An optional end index to search to. - */ - function CountAllMatching(array: any[], property: string, value: any, startIndex?: integer, endIndex?: integer): integer; - - /** - * Passes each element in the array to the given callback. - * @param array The array to search. - * @param callback A callback to be invoked for each item in the array. - * @param context The context in which the callback is invoked. - * @param args Additional arguments that will be passed to the callback, after the current array item. - */ - function Each(array: any[], callback: Function, context: object, ...args: any[]): any[]; - - /** - * Passes each element in the array, between the start and end indexes, to the given callback. - * @param array The array to search. - * @param callback A callback to be invoked for each item in the array. - * @param context The context in which the callback is invoked. - * @param startIndex The start index to search from. - * @param endIndex The end index to search to. - * @param args Additional arguments that will be passed to the callback, after the child. - */ - function EachInRange(array: any[], callback: Function, context: object, startIndex: integer, endIndex: integer, ...args: any[]): any[]; - - /** - * Searches a pre-sorted array for the closet value to the given number. - * - * If the `key` argument is given it will assume the array contains objects that all have the required `key` property name, - * and will check for the closest value of those to the given number. - * @param value The value to search for in the array. - * @param array The array to search, which must be sorted. - * @param key An optional property key. If specified the array elements property will be checked against value. - */ - function FindClosestInSorted(value: number, array: any[], key?: string): number | any; - - /** - * Returns all elements in the array. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('visible', true)` would return only elements that have their visible property set. - * - * Optionally you can specify a start and end index. For example if the array had 100 elements, - * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only - * the first 50 elements. - * @param array The array to search. - * @param 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 startIndex An optional start index to search from. - * @param endIndex An optional end index to search to. - */ - function GetAll(array: any[], property?: string, value?: any, startIndex?: integer, endIndex?: integer): any[]; - - /** - * Returns the first element in the array. - * - * You can optionally specify a matching criteria using the `property` and `value` arguments. - * - * For example: `getAll('visible', true)` would return the first element that had its `visible` property set. - * - * Optionally you can specify a start and end index. For example if the array had 100 elements, - * and you set `startIndex` to 0 and `endIndex` to 50, it would search only the first 50 elements. - * @param array The array to search. - * @param 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 startIndex An optional start index to search from. Default 0. - * @param endIndex An optional end index to search up to (but not included) Default array.length. - */ - function GetFirst(array: any[], property?: string, value?: any, startIndex?: integer, endIndex?: integer): object; - - /** - * Returns a Random element from the array. - * @param array The array to select the random entry from. - * @param startIndex An optional start index. Default 0. - * @param length An optional length, the total number of elements (from the startIndex) to choose from. Default array.length. - */ - function GetRandom(array: any[], startIndex?: integer, length?: integer): any; - - namespace Matrix { - /** - * Checks if an array can be used as a matrix. - * - * 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: - * - * ``` - * [ - * [ 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 ] - * ] - * ``` - * @param matrix The array to check. - */ - function CheckMatrix(matrix?: T[][]): boolean; - - /** - * Generates a string (which you can pass to console.log) from the given Array Matrix. - * @param matrix A 2-dimensional array. - */ - function MatrixToString(matrix?: T[][]): string; - - /** - * Reverses the columns in the given Array Matrix. - * @param matrix The array matrix to reverse the columns for. - */ - function ReverseColumns(matrix?: T[][]): T[][]; - - /** - * Reverses the rows in the given Array Matrix. - * @param matrix The array matrix to reverse the rows for. - */ - function ReverseRows(matrix?: T[][]): T[][]; - - /** - * Rotates the array matrix 180 degrees. - * @param matrix The array to rotate. - */ - function Rotate180(matrix?: T[][]): T[][]; - - /** - * Rotates the array matrix to the left (or 90 degrees) - * @param matrix The array to rotate. - */ - function RotateLeft(matrix?: T[][]): T[][]; - - /** - * Rotates the array matrix based on the given rotation value. - * - * The value can be given in degrees: 90, -90, 270, -270 or 180, - * or a string command: `rotateLeft`, `rotateRight` or `rotate180`. - * - * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. - * @param matrix The array to rotate. - * @param direction The amount to rotate the matrix by. Default 90. - */ - function RotateMatrix(matrix?: T[][], direction?: number | string): T[][]; - - /** - * Rotates the array matrix to the left (or -90 degrees) - * @param matrix The array to rotate. - */ - function RotateRight(matrix?: T[][]): T[][]; - - /** - * Transposes the elements of the given matrix (array of arrays). - * - * The transpose of a matrix is a new matrix whose rows are the columns of the original. - * @param array The array matrix to transpose. - */ - function TransposeMatrix(array?: T[][]): T[][]; - - } - - /** - * Moves the given array element down one place in the array. - * The array is modified in-place. - * @param array The input array. - * @param item The element to move down the array. - */ - function MoveDown(array: any[], item: any): any[]; - - /** - * Moves an element in an array to a new position within the same array. - * The array is modified in-place. - * @param array The array. - * @param item The element to move. - * @param index The new index that the element will be moved to. - */ - function MoveTo(array: any[], item: any, index: integer): any; - - /** - * Moves the given array element up one place in the array. - * The array is modified in-place. - * @param array The input array. - * @param item The element to move up the array. - */ - function MoveUp(array: any[], item: any): any[]; - - /** - * Create an array representing the range of numbers (usually integers), between, and inclusive of, - * the given `start` and `end` arguments. For example: - * - * `var array = numberArray(2, 4); // array = [2, 3, 4]` - * `var array = numberArray(0, 9); // array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` - * - * This is equivalent to `numberArrayStep(start, end, 1)`. - * - * You can optionally provide a prefix and / or suffix string. If given the array will contain - * strings, not integers. For example: - * - * `var array = numberArray(1, 4, 'Level '); // array = ["Level 1", "Level 2", "Level 3", "Level 4"]` - * `var array = numberArray(5, 7, 'HD-', '.png'); // array = ["HD-5.png", "HD-6.png", "HD-7.png"]` - * @param start The minimum value the array starts with. - * @param end The maximum value the array contains. - * @param prefix Optional prefix to place before the number. If provided the array will contain strings, not integers. - * @param suffix Optional suffix to place after the number. If provided the array will contain strings, not integers. - */ - function NumberArray(start: number, end: number, prefix?: string, suffix?: string): number[] | string[]; - - /** - * Create an array of numbers (positive and/or negative) progressing from `start` - * up to but not including `end` by advancing by `step`. - * - * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. - * - * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; - * for forward compatibility make sure to pass in actual numbers. - * @param start The start of the range. Default 0. - * @param end The end of the range. Default null. - * @param step The value to increment or decrement by. Default 1. - */ - function NumberArrayStep(start?: number, end?: number, step?: number): number[]; - - /** - * 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) - * @param arr The array to sort. - * @param k The k-th element index. - * @param left The index of the left part of the range. Default 0. - * @param right The index of the right part of the range. - * @param compare An optional comparison function. Is passed two elements and should return 0, 1 or -1. - */ - function QuickSelect(arr: any[], k: integer, left?: integer, right?: integer, compare?: Function): void; - - /** - * 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) = - * Maybe if max is set then repeat goes to -1 automatically? - * 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 - * @param a The first array of range elements. - * @param b The second array of range elements. - * @param options A range configuration object. Can contain: repeat, random, randomB, yoyo, max, qty. - */ - function Range(a: any[], b: any[], options?: object): any[]; - - /** - * Removes the given item, or array of items, from the array. - * - * The array is modified in-place. - * - * You can optionally specify a callback to be invoked for each item successfully removed from the array. - * @param array The array to be modified. - * @param item The item, or array of items, to be removed from the array. - * @param callback A callback to be invoked for each item successfully removed from the array. - * @param context The context in which the callback is invoked. - */ - function Remove(array: any[], item: any | any[], callback?: Function, context?: object): any | any[]; - - /** - * Removes the item from the given position in the array. - * - * The array is modified in-place. - * - * You can optionally specify a callback to be invoked for the item if it is successfully removed from the array. - * @param array The array to be modified. - * @param index The array index to remove the item from. The index must be in bounds or it will throw an error. - * @param callback A callback to be invoked for the item removed from the array. - * @param context The context in which the callback is invoked. - */ - function RemoveAt(array: any[], index: integer, callback?: Function, context?: object): any; - - /** - * Removes the item within the given range in the array. - * - * The array is modified in-place. - * - * You can optionally specify a callback to be invoked for the item/s successfully removed from the array. - * @param array The array to be modified. - * @param startIndex The start index to remove from. - * @param endIndex The end index to remove to. - * @param callback A callback to be invoked for the item removed from the array. - * @param context The context in which the callback is invoked. - */ - function RemoveBetween(array: any[], startIndex: integer, endIndex: integer, callback?: Function, context?: object): any[]; - - /** - * Removes a random object from the given array and returns it. - * Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. - * @param array The array to removed a random element from. - * @param start The array index to start the search from. Default 0. - * @param length Optional restriction on the number of elements to randomly select from. Default array.length. - */ - function RemoveRandomElement(array: any[], start?: integer, length?: integer): object; - - /** - * Replaces an element of the array with the new element. - * The new element cannot already be a member of the array. - * The array is modified in-place. - * @param array The array to search within. - * @param oldChild The element in the array that will be replaced. - * @param newChild The element to be inserted into the array at the position of `oldChild`. - */ - function Replace(array: any[], oldChild: any, newChild: any): boolean; - - /** - * Moves the element at the start of the array to the end, shifting all items in the process. - * The "rotation" happens to the left. - * @param array The array to shift to the left. This array is modified in place. - * @param total The number of times to shift the array. Default 1. - */ - function RotateLeft(array: any[], total?: integer): any; - - /** - * Moves the element at the end of the array to the start, shifting all items in the process. - * The "rotation" happens to the right. - * @param array The array to shift to the right. This array is modified in place. - * @param total The number of times to shift the array. Default 1. - */ - function RotateRight(array: any[], total?: integer): any; - - /** - * Tests if the start and end indexes are a safe range for the given array. - * @param array The array to check. - * @param startIndex The start index. - * @param endIndex The end index. - * @param throwError Throw an error if the range is out of bounds. Default true. - */ - function SafeRange(array: any[], startIndex: integer, endIndex: integer, throwError?: boolean): boolean; - - /** - * Moves the given element to the bottom of the array. - * The array is modified in-place. - * @param array The array. - * @param item The element to move. - */ - function SendToBack(array: any[], item: any): any; - - /** - * Scans the array for elements with the given property. If found, the property is set to the `value`. - * - * For example: `SetAll('visible', true)` would set all elements that have a `visible` property to `false`. - * - * Optionally you can specify a start and end index. For example if the array had 100 elements, - * and you set `startIndex` to 0 and `endIndex` to 50, it would update only the first 50 elements. - * @param array The array to search. - * @param property The property to test for on each array element. - * @param value The value to set the property to. - * @param startIndex An optional start index to search from. - * @param endIndex An optional end index to search to. - */ - function SetAll(array: any[], property: string, value: any, startIndex?: integer, endIndex?: integer): any[]; - - /** - * Shuffles the contents of the given array using the Fisher-Yates implementation. - * - * The original array is modified directly and returned. - * @param array The array to shuffle. This array is modified in place. - */ - function Shuffle(array: T[]): T[]; - - /** - * Removes a single item from an array and returns it without creating gc, like the native splice does. - * Based on code by Mike Reinstein. - * @param array The array to splice from. - * @param index The index of the item which should be spliced. - */ - function SpliceOne(array: any[], index: integer): any; - - namespace StableSortFunctions { - /** - * Sort the input array and simply copy it back if the result isn't in the original array, which happens on an odd number of passes. - * @param arr The input array. - * @param comp The comparison handler. - */ - function inplace(arr: any[], comp: Function): any[]; - - } - - /** - * A stable array sort, because `Array#sort()` is not guaranteed stable. - * This is an implementation of merge sort, without recursion. - * @param arr The input array to be sorted. - * @param comp The comparison handler. - */ - function StableSort(arr: any[], comp: Function): any[]; - - /** - * Swaps the position of two elements in the given array. - * The elements must exist in the same array. - * The array is modified in-place. - * @param array The input array. - * @param item1 The first element to swap. - * @param item2 The second element to swap. - */ - function Swap(array: any[], item1: any, item2: any): any[]; - - } - - namespace Base64 { - /** - * 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. - * @param arrayBuffer The Array Buffer to encode. - * @param mediaType An optional media type, i.e. `audio/ogg` or `image/jpeg`. If included the resulting string will be a data URI. - */ - function ArrayBufferToBase64(arrayBuffer: ArrayBuffer, mediaType?: string): string; - - /** - * Converts a base64 string, either with or without a data uri, into an Array Buffer. - * @param base64 The base64 string to be decoded. Can optionally contain a data URI header, which will be stripped out prior to decoding. - */ - function Base64ToArrayBuffer(base64: string): ArrayBuffer; - - } - - /** - * A NOOP (No Operation) callback function. - * - * Used internally by Phaser when it's more expensive to determine if a callback exists - * than it is to just invoke an empty function. - */ - function NOOP(): void; - - namespace Objects { - /** - * Shallow Object Clone. Will not clone nested objects. - * @param obj the object from which to clone - */ - function Clone(obj: object): object; - - /** - * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ - */ - function Extend(): object; - - /** - * Retrieves a value from an object. Allows for more advanced selection options, including: - * - * Allowed types: - * - * Implicit - * { - * x: 4 - * } - * - * From function - * { - * x: function () - * } - * - * Randomly pick one element from the array - * { - * x: [a, b, c, d, e, f] - * } - * - * Random integer between min and max: - * { - * x: { randInt: [min, max] } - * } - * - * Random float between min and max: - * { - * x: { randFloat: [min, max] } - * } - * @param source The object to retrieve the value from. - * @param 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. - */ - function GetAdvancedValue(source: object, key: string, defaultValue: any): any; - - /** - * Finds the key within the top level of the {@link source} object, or returns {@link defaultValue} - * @param source The object to search - * @param key The key for the property on source. Must exist at the top level of the source object (no periods) - * @param defaultValue The default value to use if the key does not exist. - */ - function GetFastValue(source: object, key: string, defaultValue?: any): any; - - /** - * Retrieves and clamps a numerical value from an object. - * @param source The object to retrieve the value from. - * @param 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 (`.`). - * @param min The minimum value which can be returned. - * @param max The maximum value which can be returned. - * @param defaultValue The value to return if the property doesn't exist. It's also constrained to the given bounds. - */ - function GetMinMaxValue(source: object, key: string, min: number, max: number, defaultValue: number): number; - - /** - * Retrieves a value from an object. - * @param source The object to retrieve the value from. - * @param 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. - */ - function GetValue(source: object, key: string, defaultValue: any): any; - - /** - * Verifies that an object contains all requested keys - * @param source an object on which to check for key existence - * @param keys an array of keys to ensure the source object contains - */ - function HasAll(source: object, keys: string[]): boolean; - - /** - * Verifies that an object contains at least one of the requested keys - * @param source an object on which to check for key existence - * @param keys an array of keys to search the object for - */ - function HasAny(source: object, keys: string[]): boolean; - - /** - * Determine whether the source object has a property with the specified key. - * @param source The source object to be checked. - * @param key The property to check for within the object - */ - function HasValue(source: object, key: string): boolean; - - /** - * This is a slightly modified version of jQuery.isPlainObject. - * A plain object is an object whose internal class property is [object Object]. - * @param obj The object to inspect. - */ - function IsPlainObject(obj: object): boolean; - - /** - * Creates a new Object using all values from obj1 and obj2. - * If a value exists in both obj1 and obj2, the value in obj1 is used. - * - * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this - * function on shallow objects. - * @param obj1 The first object. - * @param obj2 The second object. - */ - function Merge(obj1: object, obj2: object): object; - - /** - * Creates a new Object using all values from obj1. - * - * Then scans obj2. If a property is found in obj2 that *also* exists in obj1, the value from obj2 is used, otherwise the property is skipped. - * @param obj1 The first object to merge. - * @param obj2 The second object to merge. Keys from this object which also exist in `obj1` will be copied to `obj1`. - */ - function MergeRight(obj1: object, obj2: object): object; - - /** - * Returns a new object that only contains the `keys` that were found on the object provided. - * If no `keys` are found, an empty object is returned. - * @param object The object to pick the provided keys from. - * @param keys An array of properties to retrieve from the provided object. - */ - function Pick(object: object, keys: any[]): object; - - /** - * Sets a value in an object, allowing for dot notation to control the depth of the property. - * - * For example: - * - * ```javascript - * var data = { - * world: { - * position: { - * x: 200, - * y: 100 - * } - * } - * }; - * - * SetValue(data, 'world.position.y', 300); - * - * console.log(data.world.position.y); // 300 - * ``` - * @param source The object to set the value in. - * @param key The name of the property in the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) - * @param value The value to set into the property, if found in the source object. - */ - function SetValue(source: object, key: string, value: any): boolean; - - } - - namespace String { - /** - * Takes a string and replaces instances of markers with values in the given array. - * The markers take the form of `%1`, `%2`, etc. I.e.: - * - * `Format("The %1 is worth %2 gold", [ 'Sword', 500 ])` - * @param string The string containing the replacement markers. - * @param values An array containing values that will replace the markers. If no value exists an empty string is inserted instead. - */ - function Format(string: string, values: any[]): string; - - /** - * Takes the given string and pads it out, to the length required, using the character - * specified. For example if you need a string to be 6 characters long, you can call: - * - * `pad('bob', 6, '-', 2)` - * - * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. - * - * You can also use it to pad numbers (they are always returned as strings): - * - * `pad(512, 6, '0', 1)` - * - * Would return: `000512` with the string padded to the left. - * - * If you don't specify a direction it'll pad to both sides: - * - * `pad('c64', 7, '*')` - * - * Would return: `**c64**` - * @param str The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. - * @param len The number of characters to be added. Default 0. - * @param pad The string to pad it out with (defaults to a space). Default " ". - * @param dir The direction dir = 1 (left), 2 (right), 3 (both). Default 3. - */ - function Pad(str: string, len?: integer, pad?: string, dir?: integer): string; - - /** - * Takes the given string and reverses it, returning the reversed string. - * For example if given the string `Atari 520ST` it would return `TS025 iratA`. - * @param string The string to be reversed. - */ - function Reverse(string: string): string; - - /** - * Capitalizes the first letter of a string if there is one. - * @param str The string to capitalize. - */ - function UppercaseFirst(str: string): string; - - /** - * Creates and returns an RFC4122 version 4 compliant UUID. - * - * The string is in the form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` where each `x` is replaced with a random - * hexadecimal digit from 0 to f, and `y` is replaced with a random hexadecimal digit from 8 to b. - */ - function UUID(): string; - - } - - } - - /** - * The Facebook Instant Games Plugin for Phaser 3 provides a seamless bridge between Phaser - * and the Facebook Instant Games API version 6.2. - * - * You can access this plugin via the `facebook` property in a Scene, i.e: - * - * ```javascript - * this.facebook.getPlatform(); - * ``` - * - * If this is unavailable please check to make sure you're using a build of Phaser that has - * this plugin within it. You can quickly check this by looking at the dev tools console - * header - the Phaser version number will have `-FB` after it if this plugin is loaded. - * - * If you are building your own version of Phaser then use this Webpack DefinePlugin flag: - * - * `"typeof PLUGIN_FBINSTANT": JSON.stringify(true)` - * - * You will find that every Instant Games API method has a mapping in this plugin. - * For a full list please consult either the plugin documentation, or the 6.2 SDK documentation - * at https://developers.facebook.com/docs/games/instant-games/sdk/fbinstant6.2 - * - * Internally this plugin uses its own Data Manager to handle seamless user data updates and provides - * handy functions for advertisement displaying, opening share dialogs, logging, leaderboards, purchase API requests, - * loader integration and more. - * - * To get started with Facebook Instant Games you will need to register on Facebook and create a new Instant - * Game app that has its own unique app ID. Facebook have also provided a dashboard interface for setting up - * various features for your game, including leaderboards, ad requests and the payments API. There are lots - * of guides on the Facebook Developers portal to assist with setting these - * various systems up: https://developers.facebook.com/docs/games/instant-games/guides - * - * For more details follow the Quick Start guide here: https://developers.facebook.com/docs/games/instant-games - */ - class FacebookInstantGamesPlugin extends Phaser.Events.EventEmitter { - /** - * - * @param game A reference to the Phaser.Game instance. - */ - constructor(game: Phaser.Game); - - /** - * A reference to the Phaser.Game instance. - */ - readonly game: Phaser.Game; - - /** - * A Data Manager instance. - * It allows you to store, query and retrieve any key/value data you may need to store. - * It's also used internally by the plugin to store FBIG API data. - */ - data: Phaser.Data.DataManager; - - /** - * Has the Facebook Instant Games API loaded yet? - * This is set automatically during the boot process. - */ - hasLoaded: boolean; - - /** - * Is the Data Manager currently locked? - */ - dataLocked: boolean; - - /** - * A list of the Facebook Instant Games APIs that are available, - * based on the given platform, context and user privacy settings. - * This value is populated automatically during boot. - */ - supportedAPIs: string[]; - - /** - * Holds the entry point that the game was launched from. - * This value is populated automatically during boot. - */ - entryPoint: string; - - /** - * An object that contains any data associated with the entry point that the game was launched from. - * The contents of the object are developer-defined, and can occur from entry points on different platforms. - * This will return null for older mobile clients, as well as when there is no data associated with the particular entry point. - * This value is populated automatically during boot. - */ - entryPointData: any; - - /** - * A unique identifier for the current game context. This represents a specific context - * that the game is being played in (for example, a particular messenger conversation or facebook post). - * The identifier will be null if game is being played in a solo context. - * This value is populated automatically during boot. - */ - contextID: string; - - /** - * The current context in which your game is running. This can be either `null` or - * one of: - * - * `POST` - The game is running inside of a Facebook post. - * `THREAD` - The game is running inside a Facebook Messenger thread. - * `GROUP` - The game is running inside a Facebook Group. - * `SOLO` - This is the default context, the player is the only participant. - * - * This value is populated automatically during boot. - */ - contextType: string; - - /** - * The current locale. - * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. - * Use this to determine what languages the current game should be localized with. - * This value is populated automatically during boot. - */ - locale: string; - - /** - * The platform on which the game is currently running, i.e. `IOS`. - * This value is populated automatically during boot. - */ - platform: string; - - /** - * The string representation of the Facebook Instant Games SDK version being used. - * This value is populated automatically during boot. - */ - version: string; - - /** - * Holds the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. - * This value is populated automatically during boot if the API is supported. - */ - playerID: string; - - /** - * The player's localized display name. - * This value is populated automatically during boot if the API is supported. - */ - playerName: string; - - /** - * A url to the player's public profile photo. The photo will always be a square, and with dimensions - * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. - * It's recommended to always scale the image to a desired size before rendering. - * This value is populated automatically during boot if the API is supported. - */ - playerPhotoURL: string; - - /** - * Whether a player can subscribe to the game bot or not. - */ - playerCanSubscribeBot: boolean; - - /** - * Does the current platform and context allow for use of the payments API? - * Currently this is only available on Facebook.com and Android 6+. - */ - paymentsReady: boolean; - - /** - * The set of products that are registered to the game. - */ - catalog: Product[]; - - /** - * Contains all of the player's unconsumed purchases. - * The game must fetch the current player's purchases as soon as the client indicates that it is ready to perform payments-related operations, - * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. - */ - purchases: Purchase[]; - - /** - * Contains all of the leaderboard data, as populated by the `getLeaderboard()` method. - */ - leaderboards: Phaser.FacebookInstantGamesLeaderboard[]; - - /** - * Contains AdInstance objects, as created by the `preloadAds()` method. - */ - ads: AdInstance[]; - - /** - * Call this method from your `Scene.preload` in order to sync the load progress - * of the Phaser Loader with the Facebook Instant Games loader display, i.e.: - * - * ```javascript - * this.facebook.showLoadProgress(this); - * this.facebook.once('startgame', this.startGame, this); - * ``` - * @param scene The Scene for which you want to show loader progress for. - */ - showLoadProgress(scene: Phaser.Scene): this; - - /** - * This method is called automatically when the game has finished loading, - * if you used the `showLoadProgress` method. If your game doesn't need to - * load any assets, or you're managing the load yourself, then call this - * method directly to start the API running. - * - * When the API has finished starting this plugin will emit a `startgame` event - * which you should listen for. - */ - gameStarted(): void; - - /** - * Checks to see if a given Facebook Instant Games API is available or not. - * @param api The API to check for, i.e. `player.getID`. - */ - checkAPI(api: string): boolean; - - /** - * Returns the unique identifier for the current game context. This represents a specific context - * that the game is being played in (for example, a particular messenger conversation or facebook post). - * The identifier will be null if game is being played in a solo context. - * - * It is only populated if `contextGetID` is in the list of supported APIs. - */ - getID(): string; - - /** - * Returns the current context in which your game is running. This can be either `null` or one of: - * - * `POST` - The game is running inside of a Facebook post. - * `THREAD` - The game is running inside a Facebook Messenger thread. - * `GROUP` - The game is running inside a Facebook Group. - * `SOLO` - This is the default context, the player is the only participant. - * - * It is only populated if `contextGetType` is in the list of supported APIs. - */ - getType(): string; - - /** - * Returns the current locale. - * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. - * Use this to determine what languages the current game should be localized with. - * It is only populated if `getLocale` is in the list of supported APIs. - */ - getLocale(): string; - - /** - * Returns the platform on which the game is currently running, i.e. `IOS`. - * It is only populated if `getPlatform` is in the list of supported APIs. - */ - getPlatform(): string; - - /** - * Returns the string representation of the Facebook Instant Games SDK version being used. - * It is only populated if `getSDKVersion` is in the list of supported APIs. - */ - getSDKVersion(): string; - - /** - * Returns the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. - * It is only populated if `playerGetID` is in the list of supported APIs. - */ - getPlayerID(): string; - - /** - * Returns the player's localized display name. - * It is only populated if `playerGetName` is in the list of supported APIs. - */ - getPlayerName(): string; - - /** - * Returns the url to the player's public profile photo. The photo will always be a square, and with dimensions - * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. - * It's recommended to always scale the image to a desired size before rendering. - * It is only populated if `playerGetPhoto` is in the list of supported APIs. - */ - getPlayerPhotoURL(): string; - - /** - * Load the player's photo and store it in the Texture Manager, ready for use in-game. - * - * This method works by using a Scene Loader instance and then asking the Loader to - * retrieve the image. - * - * When complete the plugin will emit a `photocomplete` event, along with the key of the photo. - * - * ```javascript - * this.facebook.loadPlayerPhoto(this, 'player').once('photocomplete', function (key) { - * this.add.image(x, y, 'player'); - * }, this); - * ``` - * @param scene The Scene that will be responsible for loading this photo. - * @param key The key to use when storing the photo in the Texture Manager. - */ - loadPlayerPhoto(scene: Phaser.Scene, key: string): this; - - /** - * Checks if the current player can subscribe to the game bot. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they can subscribe, the `playerCanSubscribeBot` property is set to `true` - * and this plugin will emit the `cansubscribebot` event. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `cansubscribebotfail` event instead. - */ - canSubscribeBot(): this; - - /** - * Subscribes the current player to the game bot. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `subscribebot` event. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `subscribebotfail` event instead. - */ - subscribeBot(): this; - - /** - * Gets the associated data from the player based on the given key, or array of keys. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the data is set into this plugins Data Manager and the - * `getdata` event will be emitted. - * @param keys The key/s of the data to retrieve. - */ - getData(keys: string | string[]): this; - - /** - * Set data to be saved to the designated cloud storage of the current player. The game can store up to 1MB of data for each unique player. - * - * The data save is requested in an async call, so the result isn't available immediately. - * - * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this - * method directly if you need to replace the data object directly. - * - * When the APIs `setDataAsync` call resolves it will emit the `savedata` event from this plugin. If the call fails for some - * reason it will emit `savedatafail` instead. - * - * The call resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was valid and - * has been scheduled to be saved. It also guarantees that all values that were set are now available in `getData`. - * @param data An object containing a set of key-value pairs that should be persisted to cloud storage. - * The object must contain only serializable values - any non-serializable values will cause the entire modification to be rejected. - */ - saveData(data: object): this; - - /** - * Immediately flushes any changes to the player data to the designated cloud storage. - * This function is expensive, and should primarily be used for critical changes where persistence needs to be immediate - * and known by the game. Non-critical changes should rely on the platform to persist them in the background. - * NOTE: Calls to player.setDataAsync will be rejected while this function's result is pending. - * - * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this - * method directly if you need to flush the data directly. - * - * When the APIs `flushDataAsync` call resolves it will emit the `flushdata` event from this plugin. If the call fails for some - * reason it will emit `flushdatafail` instead. - */ - flushData(): this; - - /** - * Retrieve stats from the designated cloud storage of the current player. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `getstats` event will be emitted along with the data object returned. - * - * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, - * it will emit a `getstatsfail` event instead. - * @param keys An optional array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats. - */ - getStats(keys?: string[]): this; - - /** - * Save the stats of the current player to the designated cloud storage. - * - * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, - * all other data types will be ignored. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `savestats` event will be emitted along with the data object returned. - * - * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, - * it will emit a `savestatsfail` event instead. - * @param data An object containing a set of key-value pairs that should be persisted to cloud storage as stats. Note that only numerical values are stored. - */ - saveStats(data: object): this; - - /** - * Increment the stats of the current player and save them to the designated cloud storage. - * - * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, - * all other data types will be ignored. - * - * The data object provided for this call should contain offsets for how much to modify the stats by: - * - * ```javascript - * this.facebook.incStats({ - * level: 1, - * zombiesSlain: 17, - * rank: -1 - * }); - * ``` - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `incstats` event will be emitted along with the data object returned. - * - * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, - * it will emit a `incstatsfail` event instead. - * @param data An object containing a set of key-value pairs indicating how much to increment each stat in cloud storage. Note that only numerical values are processed. - */ - incStats(data: object): this; - - /** - * Sets the data associated with the individual gameplay session for the current context. - * - * This function should be called whenever the game would like to update the current session data. - * - * This session data may be used to populate a variety of payloads, such as game play webhooks. - * @param data An arbitrary data object, which must be less than or equal to 1000 characters when stringified. - */ - saveSession(data: object): this; - - /** - * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * @param text A text message to be shared. - * @param key The key of the texture to use as the share image. - * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param sessionData A blob of data to attach to the share. - */ - openShare(text: string, key: string, frame?: string, sessionData?: object): this; - - /** - * This invokes a dialog to let the user invite a friend to play this game, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * @param text A text message to be shared. - * @param key The key of the texture to use as the share image. - * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param sessionData A blob of data to attach to the share. - */ - openInvite(text: string, key: string, frame?: string, sessionData?: object): this; - - /** - * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * @param text A text message to be shared. - * @param key The key of the texture to use as the share image. - * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param sessionData A blob of data to attach to the share. - */ - openRequest(text: string, key: string, frame?: string, sessionData?: object): this; - - /** - * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. - * - * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. - * - * This data must be less than or equal to 1000 characters when stringified. - * - * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. - * - * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. - * @param text A text message to be shared. - * @param key The key of the texture to use as the share image. - * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param sessionData A blob of data to attach to the share. - */ - openChallenge(text: string, key: string, frame?: string, sessionData?: object): this; - - /** - * This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. - * If one of the bounds is null only the other bound will be checked against. - * It will always return the original result for the first call made in a context in a given game play session. - * Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset. - * @param min The minimum bound of the context size query. - * @param max The maximum bound of the context size query. - */ - isSizeBetween(min?: integer, max?: integer): object; - - /** - * Request a switch into a specific context. If the player does not have permission to enter that context, - * or if the player does not provide permission for the game to enter that context, this will emit a `switchfail` event. - * - * Otherwise, the plugin will emit the `switch` event when the game has switched into the specified context. - * @param contextID The ID of the desired context. - */ - switchContext(contextID: string): this; - - /** - * Opens a context selection dialog for the player. If the player selects an available context, - * the client will attempt to switch into that context, and emit the `choose` event if successful. - * Otherwise, if the player exits the menu or the client fails to switch into the new context, the `choosefail` event will be emitted. - * @param options An object specifying conditions on the contexts that should be offered. - */ - chooseContext(options?: ChooseContextConfig): this; - - /** - * Attempts to create or switch into a context between a specified player and the current player. - * This plugin will emit the `create` event once the context switch is completed. - * If the API call fails, such as if the player listed is not a Connected Player of the current player or if the - * player does not provide permission to enter the new context, then the plugin will emit a 'createfail' event. - * @param playerID ID of the player. - */ - createContext(playerID: string): this; - - /** - * Fetches an array of ConnectedPlayer objects containing information about active players - * (people who played the game in the last 90 days) that are connected to the current player. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `players` event along - * with the player data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `playersfail` event instead. - */ - getPlayers(): this; - - /** - * Fetches the game's product catalog. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `getcatalog` event along - * with the catalog data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `getcatalogfail` event instead. - */ - getCatalog(): this; - - /** - * Fetches a single Product from the game's product catalog. - * - * The product catalog must have been populated using `getCatalog` prior to calling this method. - * - * Use this to look-up product details based on a purchase list. - * @param productID The Product ID of the item to get from the catalog. - */ - getProduct(productID: string): Product; - - /** - * Begins the purchase flow for a specific product. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `purchase` event along - * with the purchase data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `purchasefail` event instead. - * @param productID The identifier of the product to purchase. - * @param developerPayload An optional developer-specified payload, to be included in the returned purchase's signed request. - */ - purchase(productID: string, developerPayload?: string): this; - - /** - * Fetches all of the player's unconsumed purchases. The game must fetch the current player's purchases - * as soon as the client indicates that it is ready to perform payments-related operations, - * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `getpurchases` event along - * with the purchase data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `getpurchasesfail` event instead. - */ - getPurchases(): this; - - /** - * Consumes a specific purchase belonging to the current player. Before provisioning a product's effects to the player, - * the game should request the consumption of the purchased product. Once the purchase is successfully consumed, - * the game should immediately provide the player with the effects of their purchase. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If they are successfully subscribed this plugin will emit the `consumepurchase` event along - * with the purchase data. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `consumepurchasefail` event instead. - * @param purchaseToken The purchase token of the purchase that should be consumed. - */ - consumePurchase(purchaseToken: string): this; - - /** - * Informs Facebook of a custom update that occurred in the game. - * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. - * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * The `text` parameter is an update payload with the following structure: - * - * ``` - * text: { - * default: 'X just invaded Y\'s village!', - * localizations: { - * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + - * '\u0642\u0631\u064A\u0629 Y!', - * en_US: 'X just invaded Y\'s village!', - * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', - * } - * } - * ``` - * @param cta The call to action text. - * @param text The text object. - * @param key The key of the texture to use as the share image. - * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param template The update template key. - * @param updateData The update data object payload. - */ - update(cta: string, text: object, key: string, frame: string | integer, template: string, updateData: object): this; - - /** - * Informs Facebook of a leaderboard update that occurred in the game. - * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. - * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * The `text` parameter is an update payload with the following structure: - * - * ``` - * text: { - * default: 'X just invaded Y\'s village!', - * localizations: { - * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + - * '\u0642\u0631\u064A\u0629 Y!', - * en_US: 'X just invaded Y\'s village!', - * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', - * } - * } - * ``` - * @param cta The call to action text. - * @param text The text object. - * @param key The key of the texture to use as the share image. - * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. - * @param template The update template key. - * @param updateData The update data object payload. - */ - updateLeaderboard(cta: string, text: object, key: string, frame: string | integer, template: string, updateData: object): this; - - /** - * Request that the client switch to a different Instant Game. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If the game switches successfully this plugin will emit the `switchgame` event and the client will load the new game. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `switchgamefail` event instead. - * @param appID The Application ID of the Instant Game to switch to. The application must be an Instant Game, and must belong to the same business as the current game. - * @param data An optional data payload. This will be set as the entrypoint data for the game being switched to. Must be less than or equal to 1000 characters when stringified. - */ - switchGame(appID: string, data?: object): this; - - /** - * Prompts the user to create a shortcut to the game if they are eligible to. - * Can only be called once per session. - * - * It makes an async call to the API, so the result isn't available immediately. - * - * If the user choose to create a shortcut this plugin will emit the `shortcutcreated` event. - * - * If they cannot, i.e. it's not in the list of supported APIs, or the request - * was rejected, it will emit a `shortcutcreatedfail` event instead. - */ - createShortcut(): this; - - /** - * Quits the game. - */ - quit(): void; - - /** - * Log an app event with FB Analytics. - * - * See https://developers.facebook.com/docs/javascript/reference/v2.8#app_events for more details about FB Analytics. - * @param name Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. - * @param value An optional numeric value that FB Analytics can calculate a sum with. - * @param params An optional object that can contain up to 25 key-value pairs to be logged with the event. Keys must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. Values must be less than 100 characters in length. - */ - log(name: string, value?: number, params?: object): this; - - /** - * Attempt to create an instance of an interstitial ad. - * - * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showAd()`. - * - * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. - * - * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. - * @param placementID The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. - */ - preloadAds(placementID: string | string[]): this; - - /** - * Attempt to create an instance of an rewarded video ad. - * - * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showVideo()`. - * - * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. - * - * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. - * @param placementID The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. - */ - preloadVideoAds(placementID: string | string[]): this; - - /** - * Displays a previously loaded interstitial ad. - * - * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. - * - * If the ad cannot be displayed, it will emit the `adsnotloaded` event. - * @param placementID The ad placement ID to display. - */ - showAd(placementID: string): this; - - /** - * Displays a previously loaded interstitial video ad. - * - * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. - * - * If the ad cannot be displayed, it will emit the `adsnotloaded` event. - * @param placementID The ad placement ID to display. - */ - showVideo(placementID: string): this; - - /** - * Attempts to match the current player with other users looking for people to play with. - * If successful, a new Messenger group thread will be created containing the matched players and the player will - * be context switched to that thread. This plugin will also dispatch the `matchplayer` event, containing the new context ID and Type. - * - * The default minimum and maximum number of players in one matched thread are 2 and 20 respectively, - * depending on how many players are trying to get matched around the same time. - * - * The values can be changed in `fbapp-config.json`. See the Bundle Config documentation for documentation about `fbapp-config.json`. - * @param matchTag Optional extra information about the player used to group them with similar players. Players will only be grouped with other players with exactly the same tag. The tag must only include letters, numbers, and underscores and be 100 characters or less in length. - * @param switchImmediately Optional extra parameter that specifies whether the player should be immediately switched to the new context when a match is found. By default this will be false which will mean the player needs explicitly press play after being matched to switch to the new context. Default false. - */ - matchPlayer(matchTag?: string, switchImmediately?: boolean): this; - - /** - * Fetch a specific leaderboard belonging to this Instant Game. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes the `getleaderboard` event will be emitted along with a Leaderboard object instance. - * @param name The name of the leaderboard. Each leaderboard for an Instant Game must have its own distinct name. - */ - getLeaderboard(name: string): this; - - /** - * Quits the Facebook API and then destroys this plugin. - */ - destroy(): void; - - } - - /** - * This class represents one single Leaderboard that belongs to a Facebook Instant Game. - * - * You do not need to instantiate this class directly, it will be created when you use the - * `getLeaderboard()` method of the main plugin. - */ - class FacebookInstantGamesLeaderboard extends Phaser.Events.EventEmitter { - /** - * - * @param plugin A reference to the Facebook Instant Games Plugin. - * @param data An Instant Game leaderboard instance. - */ - constructor(plugin: Phaser.FacebookInstantGamesPlugin, data: any); - - /** - * A reference to the Facebook Instant Games Plugin. - */ - plugin: Phaser.FacebookInstantGamesPlugin; - - /** - * An Instant Game leaderboard instance. - */ - ref: any; - - /** - * The name of the leaderboard. - */ - name: string; - - /** - * The ID of the context that the leaderboard is associated with, or null if the leaderboard is not tied to a particular context. - */ - contextID: string; - - /** - * The total number of player entries in the leaderboard. - * This value defaults to zero. Populate it via the `getEntryCount()` method. - */ - entryCount: integer; - - /** - * The players score object. - * This value defaults to `null`. Populate it via the `getPlayerScore()` method. - */ - playerScore: LeaderboardScore; - - /** - * The scores in the Leaderboard from the currently requested range. - * This value defaults to an empty array. Populate it via the `getScores()` method. - * The contents of this array are reset each time `getScores()` is called. - */ - scores: LeaderboardScore[]; - - /** - * Fetches the total number of player entries in the leaderboard. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes this Leaderboard will emit the `getentrycount` event along with the count and name of the Leaderboard. - */ - getEntryCount(): this; - - /** - * Updates the player's score. If the player has an existing score, the old score will only be replaced if the new score is better than it. - * NOTE: If the leaderboard is associated with a specific context, the game must be in that context to set a score for the player. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes this Leaderboard will emit the `setscore` event along with the LeaderboardScore object and the name of the Leaderboard. - * - * If the save fails the event will send `null` as the score value. - * @param score The new score for the player. Must be a 64-bit integer number. - * @param data Metadata to associate with the stored score. Must be less than 2KB in size. If an object is given it will be passed to `JSON.stringify`. - */ - setScore(score: integer, data?: string | any): this; - - /** - * Gets the players leaderboard entry and stores it in the `playerScore` property. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes this Leaderboard will emit the `getplayerscore` event along with the score and the name of the Leaderboard. - * - * If the player has not yet saved a score, the event will send `null` as the score value, and `playerScore` will be set to `null` as well. - */ - getPlayerScore(): this; - - /** - * Retrieves a set of leaderboard entries, ordered by score ranking in the leaderboard. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes this Leaderboard will emit the `getscores` event along with an array of LeaderboardScore entries and the name of the Leaderboard. - * @param count The number of entries to attempt to fetch from the leaderboard. Currently, up to a maximum of 100 entries may be fetched per query. Default 10. - * @param offset The offset from the top of the leaderboard that entries will be fetched from. Default 0. - */ - getScores(count?: integer, offset?: integer): this; - - /** - * Retrieves a set of leaderboard entries, based on the current player's connected players (including the current player), ordered by local rank within the set of connected players. - * - * The data is requested in an async call, so the result isn't available immediately. - * - * When the call completes this Leaderboard will emit the `getconnectedscores` event along with an array of LeaderboardScore entries and the name of the Leaderboard. - */ - getConnectedScores(): this; - - } - -} - -declare type ArcadePhysicsCallback = (object1: Phaser.GameObjects.GameObject, object2: Phaser.GameObjects.GameObject)=>void; - -declare type CollideCallback = (body: Phaser.Physics.Impact.Body, other: Phaser.Physics.Impact.Body, axis: string)=>void; - -declare type WebGLContextCallback = (renderer: Phaser.Renderer.WebGL.WebGLRenderer)=>void; - -declare type EachListCallback = (item: I, ...args: any[])=>void; - -declare type EachMapCallback = (key: string, entry: E)=>void; - -declare type EachSetCallback = (entry: E, index: number)=>void; - -declare type EachTextureCallback = (texture: Phaser.Textures.Texture, ...args: any[])=>void; - -declare type FindTileCallback = (value: Phaser.Tilemaps.Tile, index: integer, array: Phaser.Tilemaps.Tile[])=>void; - -declare type EachTileCallback = (value: Phaser.Tilemaps.Tile, index: integer, array: Phaser.Tilemaps.Tile[])=>void; - -declare type TilemapFilterCallback = (value: Phaser.GameObjects.GameObject, index: number, array: Phaser.GameObjects.GameObject[])=>void; - -declare type TilemapFindCallback = (value: Phaser.GameObjects.GameObject, index: number, array: Phaser.GameObjects.GameObject[])=>void; - -/** - * Extends the given `myClass` object's prototype with the properties of `definition`. - * @param ctor The constructor object to mix into. - * @param definition A dictionary of functions for the class. - * @param isClassDescriptor Is the definition a class descriptor? - * @param extend The parent constructor object. - */ -declare function extend(ctor: Object, definition: Object, isClassDescriptor: boolean, extend?: Object): void; - -/** - * Applies the given `mixins` to the prototype of `myClass`. - * @param myClass The constructor object to mix into. - * @param mixins The mixins to apply to the constructor. - */ -declare function mixin(myClass: Object, mixins: Object | Object[]): void; - -/** - * Phaser.Class - */ -declare class Class { - /** - * - * @param definition a dictionary of functions for the class - */ - constructor(definition: Object); - -} - -declare type AdInstance = { - /** - * Represents an instance of an ad. - */ - instance: any; - /** - * The Audience Network placement ID of this ad instance. - */ - placementID: string; - /** - * Has this ad already been shown in-game? - */ - shown: boolean; - /** - * Is this a video ad? - */ - video: boolean; -}; - -/** - * A filter that may be applied to a Context Choose operation. - * - * 'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been played in before. - * 'INCLUDE_EXISTING_CHALLENGES' - Include the "Existing Challenges" section, which surfaces actively played-in contexts that the player is a part of. - * 'NEW_PLAYERS_ONLY' - In sections containing individuals, prefer people who have not played the game. - */ -declare type ContextFilter = string; - -/** - * A configuration object that may be applied to a Context Choose operation. - */ -declare type ChooseContextConfig = { - /** - * The set of filters to apply to the context suggestions: 'NEW_CONTEXT_ONLY', 'INCLUDE_EXISTING_CHALLENGES' or 'NEW_PLAYERS_ONLY'. - */ - filters?: ContextFilter[]; - /** - * The maximum number of participants that a suggested context should ideally have. - */ - maxSize?: number; - /** - * The minimum number of participants that a suggested context should ideally have. - */ - minSize?: number; -}; - -declare type LeaderboardScore = { - /** - * An integer score value. - */ - score: integer; - /** - * The score value, formatted with the score format associated with the leaderboard. - */ - scoreFormatted: string; - /** - * The Unix timestamp of when the leaderboard entry was last updated. - */ - timestamp: integer; - /** - * The entry's leaderboard ranking. - */ - rank: integer; - /** - * The developer-specified payload associated with the score, or null if one was not set. - */ - data: string; - /** - * The player's localized display name. - */ - playerName: string; - /** - * A url to the player's public profile photo. - */ - playerPhotoURL: string; - /** - * The game's unique identifier for the player. - */ - playerID: string; -}; - -declare type Product = { - /** - * The title of the product. - */ - title?: string; - /** - * The product's game-specified identifier. - */ - productID?: string; - /** - * The product description. - */ - description?: string; - /** - * A link to the product's associated image. - */ - imageURI?: string; - /** - * The price of the product. - */ - price?: string; - /** - * The currency code for the product. - */ - priceCurrencyCode?: string; -}; - -declare type Purchase = { - /** - * A developer-specified string, provided during the purchase of the product. - */ - developerPayload?: string; - /** - * The identifier for the purchase transaction. - */ - paymentID?: string; - /** - * The product's game-specified identifier. - */ - productID?: string; - /** - * Unix timestamp of when the purchase occurred. - */ - purchaseTime?: string; - /** - * A token representing the purchase that may be used to consume the purchase. - */ - purchaseToken?: string; - /** - * Server-signed encoding of the purchase request. - */ - signedRequest?: string; -}; - -declare type integer = number; - -declare module 'phaser' { - export = Phaser; - -} - +/// + +declare type DataEachCallback = (parent: any, key: string, value: any, ...args: any[])=>void; + +declare type ContentLoadedCallback = ()=>void; + +declare type CreateCallback = (bob: Phaser.GameObjects.Bob, index: integer)=>void; + +declare type EachContainerCallback = (item: any, ...args: any[])=>void; + +declare type LightForEach = (light: Phaser.GameObjects.Light)=>void; + +/** + * A custom function that will be responsible for wrapping the text. + */ +declare type TextStyleWordWrapCallback = (text: string, textObject: Phaser.GameObjects.Text)=>void; + +declare type CenterFunction = (triangle: Phaser.Geom.Triangle)=>void; + +declare namespace Phaser { + namespace Actions { + /** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, and aligns them next to each other. + * + * The first item isn't moved. The second item is aligned next to the first, then the third next to the second, and so on. + * @param items The array of items to be updated by this action. + * @param position The position to align the items with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function AlignTo(items: G, position: integer, offsetX?: number, offsetY?: number): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `angle` property, + * and then adds the given value to each of their `angle` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `Angle(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `angle` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function Angle(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of objects and passes each of them to the given callback. + * @param items The array of items to be updated by this action. + * @param callback The callback to be invoked. It will be passed just one argument: the item from the array. + * @param context The scope in which the callback will be invoked. + */ + function Call(items: G, callback: Phaser.Types.Actions.CallCallback, context: any): G; + + /** + * Takes an array of objects and returns the first element in the array that has properties which match + * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` + * then it would return the first item which had the property `scaleX` set to 0.5 and `alpha` set to 1. + * + * To use this with a Group: `GetFirst(group.getChildren(), compare, index)` + * @param items The array of items to be searched by this action. + * @param compare The comparison object. Each property in this object will be checked against the items of the array. + * @param index An optional offset to start searching from within the items array. Default 0. + */ + function GetFirst(items: G, compare: object, index?: integer): object | Phaser.GameObjects.GameObject; + + /** + * Takes an array of objects and returns the last element in the array that has properties which match + * all of those specified in the `compare` object. For example, if the compare object was: `{ scaleX: 0.5, alpha: 1 }` + * then it would return the last item which had the property `scaleX` set to 0.5 and `alpha` set to 1. + * + * To use this with a Group: `GetLast(group.getChildren(), compare, index)` + * @param items The array of items to be searched by this action. + * @param compare The comparison object. Each property in this object will be checked against the items of the array. + * @param index An optional offset to start searching from within the items array. Default 0. + */ + function GetLast(items: G, compare: object, index?: integer): object | Phaser.GameObjects.GameObject; + + /** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, + * and then aligns them based on the grid configuration given to this action. + * @param items The array of items to be updated by this action. + * @param options The GridAlign Configuration object. + */ + function GridAlign(items: G, options: Phaser.Types.Actions.GridAlignConfig): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `alpha` property, + * and then adds the given value to each of their `alpha` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncAlpha(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `alpha` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function IncAlpha(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `x` property, + * and then adds the given value to each of their `x` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncX(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `x` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function IncX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have public `x` and `y` properties, + * and then adds the given value to each of them. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncXY(group.getChildren(), x, y, stepX, stepY)` + * @param items The array of items to be updated by this action. + * @param x The amount to be added to the `x` property. + * @param y The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. Default x. + * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function IncXY(items: G, x: number, y?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `y` property, + * and then adds the given value to each of their `y` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `IncY(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `y` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function IncY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Circle. + * + * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param circle The Circle to position the Game Objects on. + * @param startAngle Optional angle to start position from, in radians. Default 0. + * @param endAngle Optional angle to stop position at, in radians. Default 6.28. + */ + function PlaceOnCircle(items: G, circle: Phaser.Geom.Circle, startAngle?: number, endAngle?: number): G; + + /** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of an Ellipse. + * + * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param ellipse The Ellipse to position the Game Objects on. + * @param startAngle Optional angle to start position from, in radians. Default 0. + * @param endAngle Optional angle to stop position at, in radians. Default 6.28. + */ + function PlaceOnEllipse(items: G, ellipse: Phaser.Geom.Ellipse, startAngle?: number, endAngle?: number): G; + + /** + * Positions an array of Game Objects on evenly spaced points of a Line. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param line The Line to position the Game Objects on. + */ + function PlaceOnLine(items: G, line: Phaser.Geom.Line): G; + + /** + * Takes an array of Game Objects and positions them on evenly spaced points around the perimeter of a Rectangle. + * + * Placement starts from the top-left of the rectangle, and proceeds in a clockwise direction. + * If the `shift` parameter is given you can offset where placement begins. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param rect The Rectangle to position the Game Objects on. + * @param shift An optional positional offset. Default 1. + */ + function PlaceOnRectangle(items: G, rect: Phaser.Geom.Rectangle, shift?: integer): G; + + /** + * Takes an array of Game Objects and positions them on evenly spaced points around the edges of a Triangle. + * + * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param triangle The Triangle to position the Game Objects on. + * @param stepRate An optional step rate, to increase or decrease the packing of the Game Objects on the lines. Default 1. + */ + function PlaceOnTriangle(items: G, triangle: Phaser.Geom.Triangle, stepRate?: number): G; + + /** + * Play an animation with the given key, starting at the given startFrame on all Game Objects in items. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param key The name of the animation to play. + * @param startFrame The starting frame of the animation with the given key. + */ + function PlayAnimation(items: G, key: string, startFrame?: string | integer): G; + + /** + * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, + * and then adds the given value to it. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `PropertyValueInc(group.getChildren(), key, value, step)` + * @param items The array of items to be updated by this action. + * @param key The property to be updated. + * @param value The amount to be added to the property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function PropertyValueInc(items: G, key: string, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have a public property as defined in `key`, + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `PropertyValueSet(group.getChildren(), key, value, step)` + * @param items The array of items to be updated by this action. + * @param key The property to be updated. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function PropertyValueSet(items: G, key: string, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects and positions them at random locations within the Circle. + * + * If you wish to pass a `Phaser.GameObjects.Circle` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param circle The Circle to position the Game Objects within. + */ + function RandomCircle(items: G, circle: Phaser.Geom.Circle): G; + + /** + * Takes an array of Game Objects and positions them at random locations within the Ellipse. + * + * If you wish to pass a `Phaser.GameObjects.Ellipse` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param ellipse The Ellipse to position the Game Objects within. + */ + function RandomEllipse(items: G, ellipse: Phaser.Geom.Ellipse): G; + + /** + * Takes an array of Game Objects and positions them at random locations on the Line. + * + * If you wish to pass a `Phaser.GameObjects.Line` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param line The Line to position the Game Objects randomly on. + */ + function RandomLine(items: G, line: Phaser.Geom.Line): G; + + /** + * Takes an array of Game Objects and positions them at random locations within the Rectangle. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param rect The Rectangle to position the Game Objects within. + */ + function RandomRectangle(items: G, rect: Phaser.Geom.Rectangle): G; + + /** + * Takes an array of Game Objects and positions them at random locations within the Triangle. + * + * If you wish to pass a `Phaser.GameObjects.Triangle` Shape to this function, you should pass its `geom` property. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param triangle The Triangle to position the Game Objects within. + */ + function RandomTriangle(items: G, triangle: Phaser.Geom.Triangle): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `rotation` property, + * and then adds the given value to each of their `rotation` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `Rotate(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `rotation` property (in radians). + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function Rotate(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Rotates each item around the given point by the given angle. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param point Any object with public `x` and `y` properties. + * @param angle The angle to rotate by, in radians. + */ + function RotateAround(items: G, point: object, angle: number): G; + + /** + * Rotates an array of Game Objects around a point by the given angle and distance. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param point Any object with public `x` and `y` properties. + * @param angle The angle to rotate by, in radians. + * @param distance The distance from the point of rotation in pixels. + */ + function RotateAroundDistance(items: G, point: object, angle: number, distance: number): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `scaleX` property, + * and then adds the given value to each of their `scaleX` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleX(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `scaleX` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function ScaleX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have public `scaleX` and `scaleY` properties, + * and then adds the given value to each of them. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleXY(group.getChildren(), scaleX, scaleY, stepX, stepY)` + * @param items The array of items to be updated by this action. + * @param scaleX The amount to be added to the `scaleX` property. + * @param scaleY The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. + * @param stepX This is added to the `scaleX` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `scaleY` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function ScaleXY(items: G, scaleX: number, scaleY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have a public `scaleY` property, + * and then adds the given value to each of their `scaleY` properties. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `ScaleY(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to be added to the `scaleY` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function ScaleY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `alpha` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetAlpha(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetAlpha(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `blendMode` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetBlendMode(group.getChildren(), value)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetBlendMode(items: G, value: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `depth` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetDepth(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetDepth(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Passes all provided Game Objects to the Input Manager to enable them for input with identical areas and callbacks. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param 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 hitAreaCallback A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. + */ + function SetHitArea(items: G, hitArea: any, hitAreaCallback: Phaser.Types.Input.HitAreaCallback): G; + + /** + * Takes an array of Game Objects, or any objects that have the public properties `originX` and `originY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetOrigin(group.getChildren(), originX, originY, stepX, stepY)` + * @param items The array of items to be updated by this action. + * @param originX The amount to set the `originX` property to. + * @param originY The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. + * @param stepX This is added to the `originX` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `originY` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetOrigin(items: G, originX: number, originY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `rotation` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetRotation(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetRotation(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public properties `scaleX` and `scaleY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScale(group.getChildren(), scaleX, scaleY, stepX, stepY)` + * @param items The array of items to be updated by this action. + * @param scaleX The amount to set the `scaleX` property to. + * @param scaleY The amount to set the `scaleY` property to. If `undefined` or `null` it uses the `scaleX` value. + * @param stepX This is added to the `scaleX` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `scaleY` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetScale(items: G, scaleX: number, scaleY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `scaleX` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScaleX(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetScaleX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `scaleY` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScaleY(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetScaleY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public properties `scrollFactorX` and `scrollFactorY` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactor(group.getChildren(), scrollFactorX, scrollFactorY, stepX, stepY)` + * @param items The array of items to be updated by this action. + * @param scrollFactorX The amount to set the `scrollFactorX` property to. + * @param scrollFactorY The amount to set the `scrollFactorY` property to. If `undefined` or `null` it uses the `scrollFactorX` value. + * @param stepX This is added to the `scrollFactorX` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `scrollFactorY` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetScrollFactor(items: G, scrollFactorX: number, scrollFactorY?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `scrollFactorX` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactorX(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetScrollFactorX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `scrollFactorY` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetScrollFactorY(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetScrollFactorY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public method setTint() and then updates it to the given value(s). You can specify tint color per corner or provide only one color value for `topLeft` parameter, in which case whole item will be tinted with that color. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param topLeft The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. + * @param topRight The tint to be applied to top-right corner of item. + * @param bottomLeft The tint to be applied to the bottom-left corner of item. + * @param bottomRight The tint to be applied to the bottom-right corner of item. + */ + function SetTint(items: G, topLeft: number, topRight?: number, bottomLeft?: number, bottomRight?: number): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `visible` + * and then sets it to the given value. + * + * To use this with a Group: `SetVisible(group.getChildren(), value)` + * @param items The array of items to be updated by this action. + * @param value The value to set the property to. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetVisible(items: G, value: boolean, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `x` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetX(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetX(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public properties `x` and `y` + * and then sets them to the given values. + * + * The optional `stepX` and `stepY` properties are applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetXY(group.getChildren(), x, y, stepX, stepY)` + * @param items The array of items to be updated by this action. + * @param x The amount to set the `x` property to. + * @param y The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. Default x. + * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetXY(items: G, x: number, y?: number, stepX?: number, stepY?: number, index?: integer, direction?: integer): G; + + /** + * Takes an array of Game Objects, or any objects that have the public property `y` + * and then sets it to the given value. + * + * The optional `step` property is applied incrementally, multiplied by each item in the array. + * + * To use this with a Group: `SetY(group.getChildren(), value, step)` + * @param items The array of items to be updated by this action. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + function SetY(items: G, value: number, step?: number, index?: integer, direction?: integer): G; + + /** + * Iterate through the items array changing the position of each element to be that of the element that came before + * it in the array (or after it if direction = 1) + * + * The first items position is set to x/y. + * + * The final x/y coords are returned + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param x The x coordinate to place the first item in the array at. + * @param y The y coordinate to place the first item in the array at. + * @param direction The iteration direction. 0 = first to last and 1 = last to first. Default 0. + * @param output An optional objec to store the final objects position in. + */ + function ShiftPosition(items: G, x: number, y: number, direction?: integer, output?: O): O; + + /** + * Shuffles the array in place. The shuffled array is both modified and returned. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + */ + function Shuffle(items: G): G; + + /** + * 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 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. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param property The property of the Game Object to interpolate. + * @param min The minimum interpolation value. + * @param max The maximum interpolation value. + * @param inc Should the values be incremented? `true` or set (`false`) Default false. + */ + function SmootherStep(items: G, property: string, min: number, max: number, inc?: boolean): G; + + /** + * 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. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param property The property of the Game Object to interpolate. + * @param min The minimum interpolation value. + * @param max The maximum interpolation value. + * @param inc Should the values be incremented? `true` or set (`false`) Default false. + */ + function SmoothStep(items: G, property: string, min: number, max: number, inc?: boolean): G; + + /** + * Takes an array of Game Objects and then modifies their `property` so the value equals, or is incremented, by the + * calculated spread value. + * + * The spread value is derived from the given `min` and `max` values and the total number of items in the array. + * + * For example, to cause an array of Sprites to change in alpha from 0 to 1 you could call: + * + * ```javascript + * Phaser.Actions.Spread(itemsArray, 'alpha', 0, 1); + * ``` + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param property The property of the Game Object to spread. + * @param min The minimum value. + * @param max The maximum value. + * @param inc Should the values be incremented? `true` or set (`false`) Default false. + */ + function Spread(items: G, property: string, min: number, max: number, inc?: boolean): G; + + /** + * Takes an array of Game Objects and toggles the visibility of each one. + * Those previously `visible = false` will become `visible = true`, and vice versa. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + */ + function ToggleVisible(items: G): G; + + /** + * Wrap each item's coordinates within a rectangle's area. + * @param items An array of Game Objects. The contents of this array are updated by this Action. + * @param rect The rectangle. + * @param padding An amount added to each side of the rectangle during the operation. Default 0. + */ + function WrapInRectangle(items: G, rect: Phaser.Geom.Rectangle, padding?: number): G; + + } + + namespace Animations { + /** + * A Frame based Animation. + * + * This consists of a key, some default values (like the frame rate) and a bunch of Frame objects. + * + * The Animation Manager creates these. Game Objects don't own an instance of these directly. + * Game Objects have the Animation Component, which are like playheads to global Animations (these objects) + * So multiple Game Objects can have playheads all pointing to this one Animation instance. + */ + class Animation extends Phaser.Events.EventEmitter { + /** + * + * @param manager A reference to the global Animation Manager + * @param key The unique identifying string for this animation. + * @param config The Animation configuration. + */ + constructor(manager: Phaser.Animations.AnimationManager, key: string, config: Phaser.Types.Animations.Animation); + + /** + * A reference to the global Animation Manager. + */ + manager: Phaser.Animations.AnimationManager; + + /** + * The unique identifying string for this animation. + */ + key: string; + + /** + * A frame based animation (as opposed to a bone based animation) + */ + type: string; + + /** + * Extract all the frame data into the frames array. + */ + frames: Phaser.Animations.AnimationFrame[]; + + /** + * The frame rate of playback in frames per second (default 24 if duration is null) + */ + frameRate: integer; + + /** + * How long the animation should play for, in milliseconds. + * If the `frameRate` property has been set then it overrides this value, + * otherwise the `frameRate` is derived from `duration`. + */ + duration: integer; + + /** + * How many ms per frame, not including frame specific modifiers. + */ + msPerFrame: integer; + + /** + * Skip frames if the time lags, or always advanced anyway? + */ + skipMissedFrames: boolean; + + /** + * The delay in ms before the playback will begin. + */ + delay: integer; + + /** + * Number of times to repeat the animation. Set to -1 to repeat forever. + */ + repeat: integer; + + /** + * The delay in ms before the a repeat play starts. + */ + repeatDelay: integer; + + /** + * Should the animation yoyo (reverse back down to the start) before repeating? + */ + yoyo: boolean; + + /** + * Should the GameObject's `visible` property be set to `true` when the animation starts to play? + */ + showOnStart: boolean; + + /** + * Should the GameObject's `visible` property be set to `false` when the animation finishes? + */ + hideOnComplete: boolean; + + /** + * Global pause. All Game Objects using this Animation instance are impacted by this property. + */ + paused: boolean; + + /** + * Add frames to the end of the animation. + * @param config [description] + */ + addFrame(config: string | Phaser.Types.Animations.AnimationFrame[]): Phaser.Animations.Animation; + + /** + * Add frame/s into the animation. + * @param index The index to insert the frame at within the animation. + * @param config [description] + */ + addFrameAt(index: integer, config: string | Phaser.Types.Animations.AnimationFrame[]): Phaser.Animations.Animation; + + /** + * Check if the given frame index is valid. + * @param index The index to be checked. + */ + checkFrame(index: integer): boolean; + + /** + * [description] + * @param component [description] + */ + protected completeAnimation(component: Phaser.GameObjects.Components.Animation): void; + + /** + * [description] + * @param component [description] + * @param includeDelay [description] Default true. + */ + protected getFirstTick(component: Phaser.GameObjects.Components.Animation, includeDelay?: boolean): void; + + /** + * Returns the AnimationFrame at the provided index + * @param index The index in the AnimationFrame array + */ + protected getFrameAt(index: integer): Phaser.Animations.AnimationFrame; + + /** + * [description] + * @param textureManager [description] + * @param frames [description] + * @param defaultTextureKey [description] + */ + getFrames(textureManager: Phaser.Textures.TextureManager, frames: string | Phaser.Types.Animations.AnimationFrame[], defaultTextureKey?: string): Phaser.Animations.AnimationFrame[]; + + /** + * [description] + * @param component [description] + */ + getNextTick(component: Phaser.GameObjects.Components.Animation): void; + + /** + * Returns the frame closest to the given progress value between 0 and 1. + * @param value A value between 0 and 1. + */ + getFrameByProgress(value: number): Phaser.Animations.AnimationFrame; + + /** + * Advance the animation frame. + * @param component The Animation Component to advance. + */ + nextFrame(component: Phaser.GameObjects.Components.Animation): void; + + /** + * Returns the animation last frame. + */ + getLastFrame(): Phaser.Animations.AnimationFrame; + + /** + * [description] + * @param component [description] + */ + previousFrame(component: Phaser.GameObjects.Components.Animation): void; + + /** + * [description] + * @param frame [description] + */ + removeFrame(frame: Phaser.Animations.AnimationFrame): Phaser.Animations.Animation; + + /** + * Removes a frame from the AnimationFrame array at the provided index + * and updates the animation accordingly. + * @param index The index in the AnimationFrame array + */ + removeFrameAt(index: integer): Phaser.Animations.Animation; + + /** + * [description] + * @param component [description] + */ + repeatAnimation(component: Phaser.GameObjects.Components.Animation): void; + + /** + * Sets the texture frame the animation uses for rendering. + * @param component [description] + */ + setFrame(component: Phaser.GameObjects.Components.Animation): void; + + /** + * Converts the animation data to JSON. + */ + toJSON(): Phaser.Types.Animations.JSONAnimation; + + /** + * [description] + */ + updateFrameSequence(): Phaser.Animations.Animation; + + /** + * [description] + */ + pause(): Phaser.Animations.Animation; + + /** + * [description] + */ + resume(): Phaser.Animations.Animation; + + /** + * [description] + */ + destroy(): void; + + } + + /** + * A single frame in an Animation sequence. + * + * An AnimationFrame consists of a reference to the Texture it uses for rendering, references to other + * frames in the animation, and index data. It also has the ability to modify the animation timing. + * + * AnimationFrames are generated automatically by the Animation class. + */ + class AnimationFrame { + /** + * + * @param textureKey The key of the Texture this AnimationFrame uses. + * @param textureFrame The key of the Frame within the Texture that this AnimationFrame uses. + * @param index The index of this AnimationFrame within the Animation sequence. + * @param frame A reference to the Texture Frame this AnimationFrame uses for rendering. + */ + constructor(textureKey: string, textureFrame: string | integer, index: integer, frame: Phaser.Textures.Frame); + + /** + * The key of the Texture this AnimationFrame uses. + */ + textureKey: string; + + /** + * The key of the Frame within the Texture that this AnimationFrame uses. + */ + textureFrame: string | integer; + + /** + * The index of this AnimationFrame within the Animation sequence. + */ + index: integer; + + /** + * A reference to the Texture Frame this AnimationFrame uses for rendering. + */ + frame: Phaser.Textures.Frame; + + /** + * Is this the first frame in an animation sequence? + */ + readonly isFirst: boolean; + + /** + * Is this the last frame in an animation sequence? + */ + readonly isLast: boolean; + + /** + * A reference to the AnimationFrame that comes before this one in the animation, if any. + */ + readonly prevFrame: Phaser.Animations.AnimationFrame; + + /** + * A reference to the AnimationFrame that comes after this one in the animation, if any. + */ + readonly nextFrame: Phaser.Animations.AnimationFrame; + + /** + * Additional time (in ms) that this frame should appear for during playback. + * The value is added onto the msPerFrame set by the animation. + */ + duration: number; + + /** + * What % through the animation does this frame come? + * This value is generated when the animation is created and cached here. + */ + readonly progress: number; + + /** + * Generates a JavaScript object suitable for converting to JSON. + */ + toJSON(): Phaser.Types.Animations.JSONAnimationFrame; + + /** + * Destroys this object by removing references to external resources and callbacks. + */ + destroy(): void; + + } + + /** + * The Animation Manager. + * + * Animations are managed by the global Animation Manager. This is a singleton class that is + * responsible for creating and delivering animations and their corresponding data to all Game Objects. + * Unlike plugins it is owned by the Game instance, not the Scene. + * + * Sprites and other Game Objects get the data they need from the AnimationManager. + */ + class AnimationManager extends Phaser.Events.EventEmitter { + /** + * + * @param game A reference to the Phaser.Game instance. + */ + constructor(game: Phaser.Game); + + /** + * A reference to the Phaser.Game instance. + */ + protected game: Phaser.Game; + + /** + * A reference to the Texture Manager. + */ + protected textureManager: Phaser.Textures.TextureManager; + + /** + * The global time scale of the Animation Manager. + * + * This scales the time delta between two frames, thus influencing the speed of time for the Animation Manager. + */ + globalTimeScale: number; + + /** + * The Animations registered in the Animation Manager. + * + * This map should be modified with the {@link #add} and {@link #create} methods of the Animation Manager. + */ + protected anims: Phaser.Structs.Map; + + /** + * Whether the Animation Manager is paused along with all of its Animations. + */ + paused: boolean; + + /** + * The name of this Animation Manager. + */ + name: string; + + /** + * Registers event listeners after the Game boots. + */ + boot(): void; + + /** + * Adds an existing Animation to the Animation Manager. + * @param key The key under which the Animation should be added. The Animation will be updated with it. Must be unique. + * @param animation The Animation which should be added to the Animation Manager. + */ + add(key: string, animation: Phaser.Animations.Animation): Phaser.Animations.AnimationManager; + + /** + * Checks to see if the given key is already in use within the Animation Manager or not. + * + * Animations are global. Keys created in one scene can be used from any other Scene in your game. They are not Scene specific. + * @param key The key of the Animation to check. + */ + exists(key: string): boolean; + + /** + * Creates a new Animation and adds it to the Animation Manager. + * + * Animations are global. Once created, you can use them in any Scene in your game. They are not Scene specific. + * + * If an invalid key is given this method will return `false`. + * + * If you pass the key of an animation that already exists in the Animation Manager, that animation will be returned. + * + * A brand new animation is only created if the key is valid and not already in use. + * + * If you wish to re-use an existing key, call `AnimationManager.remove` first, then this method. + * @param config The configuration settings for the Animation. + */ + create(config: Phaser.Types.Animations.Animation): Phaser.Animations.Animation | false; + + /** + * Loads this Animation Manager's Animations and settings from a JSON object. + * @param data The JSON object to parse. + * @param clearCurrentAnimations If set to `true`, the current animations will be removed (`anims.clear()`). If set to `false` (default), the animations in `data` will be added. Default false. + */ + fromJSON(data: string | Phaser.Types.Animations.JSONAnimations | Phaser.Types.Animations.JSONAnimation, clearCurrentAnimations?: boolean): Phaser.Animations.Animation[]; + + /** + * [description] + * @param key The key for the texture containing the animation frames. + * @param config The configuration object for the animation frame names. + */ + generateFrameNames(key: string, config?: Phaser.Types.Animations.GenerateFrameNames): Phaser.Types.Animations.AnimationFrame[]; + + /** + * Generate an array of {@link Phaser.Types.Animations.AnimationFrame} objects from a texture key and configuration object. + * + * Generates objects with numbered frame names, as configured by the given {@link Phaser.Types.Animations.GenerateFrameNumbers}. + * @param key The key for the texture containing the animation frames. + * @param config The configuration object for the animation frames. + */ + generateFrameNumbers(key: string, config: Phaser.Types.Animations.GenerateFrameNumbers): Phaser.Types.Animations.AnimationFrame[]; + + /** + * Get an Animation. + * @param key The key of the Animation to retrieve. + */ + get(key: string): Phaser.Animations.Animation; + + /** + * Load an Animation into a Game Object's Animation Component. + * @param child The Game Object to load the animation into. + * @param key The key of the animation to load. + * @param startFrame The name of a start frame to set on the loaded animation. + */ + load(child: Phaser.GameObjects.GameObject, key: string, startFrame?: string | integer): Phaser.GameObjects.GameObject; + + /** + * Pause all animations. + */ + pauseAll(): Phaser.Animations.AnimationManager; + + /** + * Play an animation on the given Game Objects that have an Animation Component. + * @param key The key of the animation to play on the Game Object. + * @param child The Game Objects to play the animation on. + */ + play(key: string, child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[]): Phaser.Animations.AnimationManager; + + /** + * Remove an animation. + * @param key The key of the animation to remove. + */ + remove(key: string): Phaser.Animations.Animation; + + /** + * Resume all paused animations. + */ + resumeAll(): Phaser.Animations.AnimationManager; + + /** + * Takes an array of Game Objects that have an Animation Component and then + * starts the given animation playing on them, each one offset by the + * `stagger` amount given to this method. + * @param key The key of the animation to play on the Game Objects. + * @param children An array of Game Objects to play the animation on. They must have an Animation Component. + * @param stagger The amount of time, in milliseconds, to offset each play time by. Default 0. + */ + staggerPlay(key: string, children: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], stagger?: number): G; + + /** + * Get the animation data as javascript object by giving key, or get the data of all animations as array of objects, if key wasn't provided. + * @param key [description] + */ + toJSON(key: string): Phaser.Types.Animations.JSONAnimations; + + /** + * Destroy this Animation Manager and clean up animation definitions and references to other objects. + * This method should not be called directly. It will be called automatically as a response to a `destroy` event from the Phaser.Game instance. + */ + destroy(): void; + + } + + namespace Events { + /** + * The Add Animation Event. + * + * This event is dispatched when a new animation is added to the global Animation Manager. + * + * This can happen either as a result of an animation instance being added to the Animation Manager, + * or the Animation Manager creating a new animation directly. + */ + const ADD_ANIMATION: any; + + /** + * The Animation Complete Event. + * + * This event is dispatched by an Animation instance when it completes, i.e. finishes playing or is manually stopped. + * + * Be careful with the volume of events this could generate. If a group of Sprites all complete the same + * animation at the same time, this event will invoke its handler for each one of them. + */ + const ANIMATION_COMPLETE: any; + + /** + * The Animation Repeat Event. + * + * This event is dispatched when a currently playing animation repeats. + * + * The event is dispatched directly from the Animation object itself. Which means that listeners + * bound to this event will be invoked every time the Animation repeats, for every Game Object that may have it. + */ + const ANIMATION_REPEAT: any; + + /** + * The Animation Restart Event. + * + * This event is dispatched by an Animation instance when it restarts. + * + * Be careful with the volume of events this could generate. If a group of Sprites all restart the same + * animation at the same time, this event will invoke its handler for each one of them. + */ + const ANIMATION_RESTART: any; + + /** + * The Animation Start Event. + * + * This event is dispatched by an Animation instance when it starts playing. + * + * Be careful with the volume of events this could generate. If a group of Sprites all play the same + * animation at the same time, this event will invoke its handler for each one of them. + */ + const ANIMATION_START: any; + + /** + * The Pause All Animations Event. + * + * This event is dispatched when the global Animation Manager is told to pause. + * + * When this happens all current animations will stop updating, although it doesn't necessarily mean + * that the game has paused as well. + */ + const PAUSE_ALL: any; + + /** + * The Remove Animation Event. + * + * This event is dispatched when an animation is removed from the global Animation Manager. + */ + const REMOVE_ANIMATION: any; + + /** + * The Resume All Animations Event. + * + * This event is dispatched when the global Animation Manager resumes, having been previously paused. + * + * When this happens all current animations will continue updating again. + */ + const RESUME_ALL: any; + + /** + * The Sprite Animation Complete Event. + * + * This event is dispatched by a Sprite when an animation finishes playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationcomplete', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_COMPLETE` event. + */ + const SPRITE_ANIMATION_COMPLETE: any; + + /** + * The Sprite Animation Key Complete Event. + * + * This event is dispatched by a Sprite when a specific animation finishes playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationcomplete-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationcomplete-explode`. + */ + const SPRITE_ANIMATION_KEY_COMPLETE: any; + + /** + * The Sprite Animation Key Repeat Event. + * + * This event is dispatched by a Sprite when a specific animation repeats playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrepeat-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrepeat-explode`. + */ + const SPRITE_ANIMATION_KEY_REPEAT: any; + + /** + * The Sprite Animation Key Restart Event. + * + * This event is dispatched by a Sprite when a specific animation restarts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrestart-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationrestart-explode`. + */ + const SPRITE_ANIMATION_KEY_RESTART: any; + + /** + * The Sprite Animation Key Start Event. + * + * This event is dispatched by a Sprite when a specific animation starts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationstart-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationstart-explode`. + */ + const SPRITE_ANIMATION_KEY_START: any; + + /** + * The Sprite Animation Key Update Event. + * + * This event is dispatched by a Sprite when a specific animation playing on it updates. This happens when the animation changes frame, + * based on the animation frame rate and other factors like `timeScale` and `delay`. + * + * Listen for it on the Sprite using `sprite.on('animationupdate-key', listener)` where `key` is the key of + * the animation. For example, if you had an animation with the key 'explode' you should listen for `animationupdate-explode`. + */ + const SPRITE_ANIMATION_KEY_UPDATE: any; + + /** + * The Sprite Animation Repeat Event. + * + * This event is dispatched by a Sprite when an animation repeats playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrepeat', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_REPEAT` event. + */ + const SPRITE_ANIMATION_REPEAT: any; + + /** + * The Sprite Animation Restart Event. + * + * This event is dispatched by a Sprite when an animation restarts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationrestart', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_RESTART` event. + */ + const SPRITE_ANIMATION_RESTART: any; + + /** + * The Sprite Animation Start Event. + * + * This event is dispatched by a Sprite when an animation starts playing on it. + * + * Listen for it on the Sprite using `sprite.on('animationstart', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_START` event. + */ + const SPRITE_ANIMATION_START: any; + + /** + * The Sprite Animation Update Event. + * + * This event is dispatched by a Sprite when an animation playing on it updates. This happens when the animation changes frame, + * based on the animation frame rate and other factors like `timeScale` and `delay`. + * + * Listen for it on the Sprite using `sprite.on('animationupdate', listener)` + * + * This same event is dispatched for all animations. To listen for a specific animation, use the `SPRITE_ANIMATION_KEY_UPDATE` event. + */ + const SPRITE_ANIMATION_UPDATE: any; + + } + + } + + namespace Cache { + /** + * The BaseCache is a base Cache class that can be used for storing references to any kind of data. + * + * Data can be added, retrieved and removed based on the given keys. + * + * Keys are string-based. + */ + class BaseCache { + /** + * The Map in which the cache objects are stored. + * + * You can query the Map directly or use the BaseCache methods. + */ + entries: Phaser.Structs.Map; + + /** + * An instance of EventEmitter used by the cache to emit related events. + */ + events: Phaser.Events.EventEmitter; + + /** + * Adds an item to this cache. The item is referenced by a unique string, which you are responsible + * for setting and keeping track of. The item can only be retrieved by using this string. + * @param key The unique key by which the data added to the cache will be referenced. + * @param data The data to be stored in the cache. + */ + add(key: string, data: any): Phaser.Cache.BaseCache; + + /** + * Checks if this cache contains an item matching the given key. + * This performs the same action as `BaseCache.exists`. + * @param key The unique key of the item to be checked in this cache. + */ + has(key: string): boolean; + + /** + * Checks if this cache contains an item matching the given key. + * This performs the same action as `BaseCache.has` and is called directly by the Loader. + * @param key The unique key of the item to be checked in this cache. + */ + exists(key: string): boolean; + + /** + * Gets an item from this cache based on the given key. + * @param key The unique key of the item to be retrieved from this cache. + */ + get(key: string): any; + + /** + * Removes and 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. + * @param key The unique key of the item to remove from the cache. + */ + remove(key: string): Phaser.Cache.BaseCache; + + /** + * Returns all keys in use in this cache. + */ + getKeys(): string[]; + + /** + * Destroys this cache and all items within it. + */ + destroy(): void; + + } + + /** + * The Cache Manager is the global cache owned and maintained by the Game instance. + * + * Various systems, such as the file Loader, rely on this cache in order to store the files + * it has loaded. The manager itself doesn't store any files, but instead owns multiple BaseCache + * instances, one per type of file. You can also add your own custom caches. + */ + class CacheManager { + /** + * + * @param game A reference to the Phaser.Game instance that owns this CacheManager. + */ + constructor(game: Phaser.Game); + + /** + * A reference to the Phaser.Game instance that owns this CacheManager. + */ + protected game: Phaser.Game; + + /** + * A Cache storing all binary files, typically added via the Loader. + */ + binary: Phaser.Cache.BaseCache; + + /** + * A Cache storing all bitmap font data files, typically added via the Loader. + * Only the font data is stored in this cache, the textures are part of the Texture Manager. + */ + bitmapFont: Phaser.Cache.BaseCache; + + /** + * A Cache storing all JSON data files, typically added via the Loader. + */ + json: Phaser.Cache.BaseCache; + + /** + * A Cache storing all physics data files, typically added via the Loader. + */ + physics: Phaser.Cache.BaseCache; + + /** + * A Cache storing all shader source files, typically added via the Loader. + */ + shader: Phaser.Cache.BaseCache; + + /** + * A Cache storing all non-streaming audio files, typically added via the Loader. + */ + audio: Phaser.Cache.BaseCache; + + /** + * A Cache storing all non-streaming video files, typically added via the Loader. + */ + video: Phaser.Cache.BaseCache; + + /** + * A Cache storing all text files, typically added via the Loader. + */ + text: Phaser.Cache.BaseCache; + + /** + * A Cache storing all html files, typically added via the Loader. + */ + html: Phaser.Cache.BaseCache; + + /** + * A Cache storing all WaveFront OBJ files, typically added via the Loader. + */ + obj: Phaser.Cache.BaseCache; + + /** + * A Cache storing all tilemap data files, typically added via the Loader. + * Only the data is stored in this cache, the textures are part of the Texture Manager. + */ + tilemap: Phaser.Cache.BaseCache; + + /** + * A Cache storing all xml data files, typically added via the Loader. + */ + xml: Phaser.Cache.BaseCache; + + /** + * An object that contains your own custom BaseCache entries. + * Add to this via the `addCustom` method. + */ + custom: {[key: string]: Phaser.Cache.BaseCache}; + + /** + * Add your own custom Cache for storing your own files. + * The cache will be available under `Cache.custom.key`. + * The cache will only be created if the key is not already in use. + * @param key The unique key of your custom cache. + */ + addCustom(key: string): Phaser.Cache.BaseCache; + + /** + * Removes all entries from all BaseCaches and destroys all custom caches. + */ + destroy(): void; + + } + + namespace Events { + /** + * The Cache Add Event. + * + * This event is dispatched by any Cache that extends the BaseCache each time a new object is added to it. + */ + const ADD: any; + + /** + * The Cache Remove Event. + * + * This event is dispatched by any Cache that extends the BaseCache each time an object is removed from it. + */ + const REMOVE: any; + + } + + } + + namespace Cameras { + namespace Scene2D { + /** + * A Base Camera class. + * + * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, + * and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. + * + * The Base Camera is extended by the Camera class, which adds in special effects including Fade, + * Flash and Camera Shake, as well as the ability to follow Game Objects. + * + * The Base Camera was introduced in Phaser 3.12. It was split off from the Camera class, to allow + * you to isolate special effects as needed. Therefore the 'since' values for properties of this class relate + * to when they were added to the Camera class. + */ + class BaseCamera extends Phaser.Events.EventEmitter implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.Visible { + /** + * + * @param x The x position of the Camera, relative to the top-left of the game canvas. + * @param y The y position of the Camera, relative to the top-left of the game canvas. + * @param width The width of the Camera, in pixels. + * @param height The height of the Camera, in pixels. + */ + constructor(x: number, y: number, width: number, height: number); + + /** + * A reference to the Scene this camera belongs to. + */ + scene: Phaser.Scene; + + /** + * A reference to the Game Scene Manager. + */ + sceneManager: Phaser.Scenes.SceneManager; + + /** + * A reference to the Game Scale Manager. + */ + scaleManager: Phaser.Scale.ScaleManager; + + /** + * A reference to the Scene's Camera Manager to which this Camera belongs. + */ + cameraManager: Phaser.Cameras.Scene2D.CameraManager; + + /** + * The Camera ID. Assigned by the Camera Manager and used to handle camera exclusion. + * This value is a bitmask. + */ + readonly id: integer; + + /** + * The name of the Camera. This is left empty for your own use. + */ + name: string; + + /** + * This property is un-used in v3.16. + * + * The resolution of the Game, used in most Camera calculations. + */ + readonly resolution: number; + + /** + * Should this camera round its pixel values to integers? + */ + roundPixels: boolean; + + /** + * Is this Camera visible or not? + * + * A visible camera will render and perform input tests. + * An invisible camera will not render anything and will skip input tests. + */ + visible: boolean; + + /** + * Is this Camera using a bounds to restrict scrolling movement? + * + * Set this property along with the bounds via `Camera.setBounds`. + */ + useBounds: boolean; + + /** + * The World View is a Rectangle that defines the area of the 'world' the Camera is currently looking at. + * This factors in the Camera viewport size, zoom and scroll position and is updated in the Camera preRender step. + * If you have enabled Camera bounds the worldview will be clamped to those bounds accordingly. + * You can use it for culling or intersection checks. + */ + readonly worldView: Phaser.Geom.Rectangle; + + /** + * Is this Camera dirty? + * + * A dirty Camera has had either its viewport size, bounds, scroll, rotation or zoom levels changed since the last frame. + * + * This flag is cleared during the `postRenderCamera` method of the renderer. + */ + dirty: boolean; + + /** + * Does this Camera have a transparent background? + */ + transparent: boolean; + + /** + * The background color of this Camera. Only used if `transparent` is `false`. + */ + backgroundColor: Phaser.Display.Color; + + /** + * The Camera alpha value. Setting this property impacts every single object that this Camera + * renders. You can either set the property directly, i.e. via a Tween, to fade a Camera in or out, + * or via the chainable `setAlpha` method instead. + */ + alpha: number; + + /** + * Should the camera cull Game Objects before checking them for input hit tests? + * In some special cases it may be beneficial to disable this. + */ + disableCull: boolean; + + /** + * The mid-point of the Camera in 'world' coordinates. + * + * Use it to obtain exactly where in the world the center of the camera is currently looking. + * + * This value is updated in the preRender method, after the scroll values and follower + * have been processed. + */ + readonly midPoint: Phaser.Math.Vector2; + + /** + * The horizontal origin of rotation for this Camera. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * See `setOrigin` to set both origins in a single, chainable call. + */ + originX: number; + + /** + * The vertical origin of rotation for this Camera. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * + * See `setOrigin` to set both origins in a single, chainable call. + */ + originY: number; + + /** + * The Mask this Camera is using during render. + * Set the mask using the `setMask` method. Remove the mask using the `clearMask` method. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Set the Alpha level of this Camera. The alpha controls the opacity of the Camera as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The Camera alpha value. Default 1. + */ + setAlpha(value?: number): this; + + /** + * Sets the rotation origin of this Camera. + * + * The values are given in the range 0 to 1 and are only used when calculating Camera rotation. + * + * By default the camera rotates around the center of the viewport. + * + * Changing the origin allows you to adjust the point in the viewport from which rotation happens. + * A value of 0 would rotate from the top-left of the viewport. A value of 1 from the bottom right. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * 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. + * @param x The horizontal coordinate to center on. + * @param y The vertical coordinate to center on. + * @param out A Vector2 to store the values in. If not given a new Vector2 is created. + */ + getScroll(x: number, y: number, out?: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Moves the Camera horizontally so that it is centered on the given x coordinate, bounds allowing. + * Calling this does not change the scrollY value. + * @param x The horizontal coordinate to center on. + */ + centerOnX(x: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Moves the Camera vertically so that it is centered on the given y coordinate, bounds allowing. + * Calling this does not change the scrollX value. + * @param y The vertical coordinate to center on. + */ + centerOnY(y: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Moves the Camera so that it is centered on the given coordinates, bounds allowing. + * @param x The horizontal coordinate to center on. + * @param y The vertical coordinate to center on. + */ + centerOn(x: number, y: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Moves the Camera so that it is looking at the center of the Camera Bounds, if enabled. + */ + centerToBounds(): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Moves the Camera so that it is re-centered based on its viewport size. + */ + centerToSize(): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Takes an array of Game Objects and returns a new array featuring only those objects + * visible by this camera. + * @param renderableObjects An array of Game Objects to cull. + */ + cull(renderableObjects: G): G; + + /** + * 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. + * @param x The x position to convert to world space. + * @param y The y position to convert to world space. + * @param output An optional object to store the results in. If not provided a new Vector2 will be created. + */ + getWorldPoint(x: number, y: number, output?: O): O; + + /** + * Given a Game Object, or an array of Game Objects, it will update all of their camera filter settings + * so that they are ignored by this Camera. This means they will not be rendered by this Camera. + * @param entries The Game Object, or array of Game Objects, to be ignored by this Camera. + */ + ignore(entries: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Internal preRender step. + * @param resolution The game resolution, as set in the Scale Manager. + */ + protected preRender(resolution: number): void; + + /** + * Takes an x value and checks it's within the range of the Camera bounds, adjusting if required. + * Do not call this method if you are not using camera bounds. + * @param x The value to horizontally scroll clamp. + */ + clampX(x: number): number; + + /** + * Takes a y value and checks it's within the range of the Camera bounds, adjusting if required. + * Do not call this method if you are not using camera bounds. + * @param y The value to vertically scroll clamp. + */ + clampY(y: number): number; + + /** + * If this Camera has previously had movement bounds set on it, this will remove them. + */ + removeBounds(): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the rotation of this Camera. This causes everything it renders to appear rotated. + * + * Rotating a camera does not rotate the viewport itself, it is applied during rendering. + * @param value The cameras angle of rotation, given in degrees. Default 0. + */ + setAngle(value?: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Sets the background color for this Camera. + * + * By default a Camera has a transparent background but it can be given a solid color, with any level + * of transparency, via this method. + * + * The color value can be specified using CSS color notation, hex or numbers. + * @param color The color value. In CSS, hex or numeric color notation. Default 'rgba(0,0,0,0)'. + */ + setBackgroundColor(color?: string | number | Phaser.Types.Display.InputColorObject): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the bounds of the Camera. The bounds are an axis-aligned rectangle. + * + * The Camera bounds controls where the Camera can scroll to, stopping it from scrolling off the + * edges and into blank space. It does not limit the placement of Game Objects, or where + * the Camera viewport can be positioned. + * + * Temporarily disable the bounds by changing the boolean `Camera.useBounds`. + * + * Clear the bounds entirely by calling `Camera.removeBounds`. + * + * If you set bounds that are smaller than the viewport it will stop the Camera from being + * able to scroll. The bounds can be positioned where-ever you wish. By default they are from + * 0x0 to the canvas width x height. This means that the coordinate 0x0 is the top left of + * the Camera bounds. However, you can position them anywhere. So if you wanted a game world + * that was 2048x2048 in size, with 0x0 being the center of it, you can set the bounds x/y + * to be -1024, -1024, with a width and height of 2048. Depending on your game you may find + * it easier for 0x0 to be the top-left of the bounds, or you may wish 0x0 to be the middle. + * @param x The top-left x coordinate of the bounds. + * @param y The top-left y coordinate of the bounds. + * @param width The width of the bounds, in pixels. + * @param height The height of the bounds, in pixels. + * @param centerOn If `true` the Camera will automatically be centered on the new bounds. Default false. + */ + setBounds(x: integer, y: integer, width: integer, height: integer, centerOn?: boolean): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Returns a rectangle containing the bounds of the Camera. + * + * If the Camera does not have any bounds the rectangle will be empty. + * + * The rectangle is a copy of the bounds, so is safe to modify. + * @param out An optional Rectangle to store the bounds in. If not given, a new Rectangle will be created. + */ + getBounds(out?: Phaser.Geom.Rectangle): Phaser.Geom.Rectangle; + + /** + * Sets the name of this Camera. + * This value is for your own use and isn't used internally. + * @param value The name of the Camera. Default ''. + */ + setName(value?: string): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the position of the Camera viewport within the game. + * + * This does not change where the camera is 'looking'. See `setScroll` to control that. + * @param x The top-left x coordinate of the Camera viewport. + * @param y The top-left y coordinate of the Camera viewport. Default x. + */ + setPosition(x: number, y?: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the rotation of this Camera. This causes everything it renders to appear rotated. + * + * Rotating a camera does not rotate the viewport itself, it is applied during rendering. + * @param value The rotation of the Camera, in radians. Default 0. + */ + setRotation(value?: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Should the Camera round pixel values to whole integers when rendering Game Objects? + * + * In some types of game, especially with pixel art, this is required to prevent sub-pixel aliasing. + * @param value `true` to round Camera pixels, `false` to not. + */ + setRoundPixels(value: boolean): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Sets the Scene the Camera is bound to. + * + * Also populates the `resolution` property and updates the internal size values. + * @param scene The Scene the camera is bound to. + */ + setScene(scene: Phaser.Scene): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the position of where the Camera is looking within the game. + * You can also modify the properties `Camera.scrollX` and `Camera.scrollY` directly. + * Use this method, or the scroll properties, to move your camera around the game world. + * + * This does not change where the camera viewport is placed. See `setPosition` to control that. + * @param x The x coordinate of the Camera in the game world. + * @param y The y coordinate of the Camera in the game world. Default x. + */ + setScroll(x: number, y?: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the size of the Camera viewport. + * + * By default a Camera is the same size as the game, but can be made smaller via this method, + * allowing you to create mini-cam style effects by creating and positioning a smaller Camera + * viewport within your game. + * @param width The width of the Camera viewport. + * @param height The height of the Camera viewport. Default width. + */ + setSize(width: integer, height?: integer): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * This method sets the position and size of the Camera viewport in a single call. + * + * If you're trying to change where the Camera is looking at in your game, then see + * the method `Camera.setScroll` instead. This method is for changing the viewport + * itself, not what the camera can see. + * + * By default a Camera is the same size as the game, but can be made smaller via this method, + * allowing you to create mini-cam style effects by creating and positioning a smaller Camera + * viewport within your game. + * @param x The top-left x coordinate of the Camera viewport. + * @param y The top-left y coordinate of the Camera viewport. + * @param width The width of the Camera viewport. + * @param height The height of the Camera viewport. Default width. + */ + setViewport(x: number, y: number, width: integer, height?: integer): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Set the zoom value of the Camera. + * + * Changing to a smaller value, such as 0.5, will cause the camera to 'zoom out'. + * Changing to a larger value, such as 2, will cause the camera to 'zoom in'. + * + * A value of 1 means 'no zoom' and is the default. + * + * Changing the zoom does not impact the Camera viewport in any way, it is only applied during rendering. + * @param value The zoom value of the Camera. The minimum it can be is 0.001. Default 1. + */ + setZoom(value?: number): Phaser.Cameras.Scene2D.BaseCamera; + + /** + * Sets the mask to be applied to this Camera during rendering. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * + * Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Camera it will be immediately replaced. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * + * Note: You cannot mask a Camera that has `renderToTexture` set. + * @param mask The mask this Camera will use when rendering. + * @param fixedPosition Should the mask translate along with the Camera, or be fixed in place and not impacted by the Cameras transform? Default true. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask, fixedPosition?: boolean): this; + + /** + * Clears the mask that this Camera was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Sets the visibility of this Camera. + * + * An invisible Camera will skip rendering and input tests of everything it can see. + * @param value The visible state of the Camera. + */ + setVisible(value: boolean): this; + + /** + * Returns an Object suitable for JSON storage containing all of the Camera viewport and rendering properties. + */ + toJSON(): Phaser.Types.Cameras.Scene2D.JSONCamera; + + /** + * Internal method called automatically by the Camera Manager. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + protected update(time: integer, delta: number): void; + + /** + * Destroys this Camera instance and its internal properties and references. + * Once destroyed you cannot use this Camera again, even if re-added to a Camera Manager. + * + * This method is called automatically by `CameraManager.remove` if that methods `runDestroy` argument is `true`, which is the default. + * + * Unless you have a specific reason otherwise, always use `CameraManager.remove` and allow it to handle the camera destruction, + * rather than calling this method directly. + */ + destroy(): void; + + /** + * The x position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollX` value. + */ + x: number; + + /** + * The y position of the Camera viewport, relative to the top-left of the game canvas. + * The viewport is the area into which the camera renders. + * To adjust the position the camera is looking at in the game world, see the `scrollY` value. + */ + y: number; + + /** + * The width of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + */ + width: number; + + /** + * The height of the Camera viewport, in pixels. + * + * The viewport is the area into which the Camera renders. Setting the viewport does + * not restrict where the Camera can scroll to. + */ + height: number; + + /** + * The horizontal scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + */ + scrollX: number; + + /** + * The vertical scroll position of this Camera. + * + * Change this value to cause the Camera to scroll around your Scene. + * + * Alternatively, setting the Camera to follow a Game Object, via the `startFollow` method, + * will automatically adjust the Camera scroll values accordingly. + * + * You can set the bounds within which the Camera can scroll via the `setBounds` method. + */ + scrollY: number; + + /** + * The Camera zoom value. Change this value to zoom in, or out of, a Scene. + * + * A value of 0.5 would zoom the Camera out, so you can now see twice as much + * of the Scene as before. A value of 2 would zoom the Camera in, so every pixel + * now takes up 2 pixels when rendered. + * + * Set to 1 to return to the default zoom level. + * + * Be careful to never set this value to zero. + */ + zoom: number; + + /** + * The horizontal position of the center of the Camera's viewport, relative to the left of the game canvas. + */ + readonly centerX: number; + + /** + * The vertical position of the center of the Camera's viewport, relative to the top of the game canvas. + */ + readonly centerY: number; + + /** + * The displayed width of the camera viewport, factoring in the camera zoom level. + * + * If a camera has a viewport width of 800 and a zoom of 0.5 then its display width + * would be 1600, as it's displaying twice as many pixels as zoom level 1. + * + * Equally, a camera with a width of 800 and zoom of 2 would have a display width + * of 400 pixels. + */ + readonly displayWidth: number; + + /** + * The displayed height of the camera viewport, factoring in the camera zoom level. + * + * If a camera has a viewport height of 600 and a zoom of 0.5 then its display height + * would be 1200, as it's displaying twice as many pixels as zoom level 1. + * + * Equally, a camera with a height of 600 and zoom of 2 would have a display height + * of 300 pixels. + */ + readonly displayHeight: number; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + } + + /** + * A Camera. + * + * The Camera is the way in which all games are rendered in Phaser. They provide a view into your game world, + * and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. + * + * A Camera also has built-in special effects including Fade, Flash and Camera Shake. + */ + class Camera extends Phaser.Cameras.Scene2D.BaseCamera implements Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.Tint { + /** + * + * @param x The x position of the Camera, relative to the top-left of the game canvas. + * @param y The y position of the Camera, relative to the top-left of the game canvas. + * @param width The width of the Camera, in pixels. + * @param height The height of the Camera, in pixels. + */ + constructor(x: number, y: number, width: number, height: number); + + /** + * Does this Camera allow the Game Objects it renders to receive input events? + */ + inputEnabled: boolean; + + /** + * The Camera Fade effect handler. + * To fade this camera see the `Camera.fade` methods. + */ + fadeEffect: Phaser.Cameras.Scene2D.Effects.Fade; + + /** + * The Camera Flash effect handler. + * To flash this camera see the `Camera.flash` method. + */ + flashEffect: Phaser.Cameras.Scene2D.Effects.Flash; + + /** + * The Camera Shake effect handler. + * To shake this camera see the `Camera.shake` method. + */ + shakeEffect: Phaser.Cameras.Scene2D.Effects.Shake; + + /** + * The Camera Pan effect handler. + * To pan this camera see the `Camera.pan` method. + */ + panEffect: Phaser.Cameras.Scene2D.Effects.Pan; + + /** + * The Camera Zoom effect handler. + * To zoom this camera see the `Camera.zoom` method. + */ + zoomEffect: Phaser.Cameras.Scene2D.Effects.Zoom; + + /** + * The linear interpolation value to use when following a target. + * + * Can also be set via `setLerp` or as part of the `startFollow` call. + * + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * + * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. + */ + lerp: Phaser.Math.Vector2; + + /** + * The values stored in this property are subtracted from the Camera targets position, allowing you to + * offset the camera from the actual target x/y coordinates by this amount. + * Can also be set via `setFollowOffset` or as part of the `startFollow` call. + */ + followOffset: Phaser.Math.Vector2; + + /** + * The Camera dead zone. + * + * The deadzone is only used when the camera is following a target. + * + * It defines a rectangular region within which if the target is present, the camera will not scroll. + * If the target moves outside of this area, the camera will begin scrolling in order to follow it. + * + * The `lerp` values that you can set for a follower target also apply when using a deadzone. + * + * You can directly set this property to be an instance of a Rectangle. Or, you can use the + * `setDeadzone` method for a chainable approach. + * + * The rectangle you provide can have its dimensions adjusted dynamically, however, please + * note that its position is updated every frame, as it is constantly re-centered on the cameras mid point. + * + * Calling `setDeadzone` with no arguments will reset an active deadzone, as will setting this property + * to `null`. + */ + deadzone: Phaser.Geom.Rectangle; + + /** + * Is this Camera rendering directly to the canvas or to a texture? + * + * Enable rendering to texture with the method `setRenderToTexture` (just enabling this boolean won't be enough) + * + * Once enabled you can toggle it by switching this property. + * + * To properly remove a render texture you should call the `clearRenderToTexture()` method. + */ + renderToTexture: boolean; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the HTML Canvas Element that the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only populated if Phaser is running with the Canvas Renderer. + */ + canvas: HTMLCanvasElement; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the Rendering Context belonging to the Canvas element the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only populated if Phaser is running with the Canvas Renderer. + */ + context: CanvasRenderingContext2D; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the GL Texture belonging the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + */ + glTexture: WebGLTexture; + + /** + * If this Camera has been set to render to a texture then this holds a reference + * to the GL Frame Buffer belonging the Camera is drawing to. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + */ + framebuffer: WebGLFramebuffer; + + /** + * If this Camera has been set to render to a texture and to use a custom pipeline, + * then this holds a reference to the pipeline the Camera is drawing with. + * + * Enable texture rendering using the method `setRenderToTexture`. + * + * This is only set if Phaser is running with the WebGL Renderer. + */ + pipeline: any; + + /** + * Sets the Camera to render to a texture instead of to the main canvas. + * + * The Camera will redirect all Game Objects it's asked to render to this texture. + * + * During the render sequence, the texture itself will then be rendered to the main canvas. + * + * Doing this gives you the ability to modify the texture before this happens, + * allowing for special effects such as Camera specific shaders, or post-processing + * on the texture. + * + * If running under Canvas the Camera will render to its `canvas` property. + * + * If running under WebGL the Camera will create a frame buffer, which is stored in its `framebuffer` and `glTexture` properties. + * + * If you set a camera to render to a texture then it will emit 2 events during the render loop: + * + * First, it will emit the event `prerender`. This happens right before any Game Object's are drawn to the Camera texture. + * + * Then, it will emit the event `postrender`. This happens after all Game Object's have been drawn, but right before the + * Camera texture is rendered to the main game canvas. It's the final point at which you can manipulate the texture before + * it appears in-game. + * + * You should not enable this unless you plan on actually using the texture it creates + * somehow, otherwise you're just doubling the work required to render your game. + * + * To temporarily disable rendering to a texture, toggle the `renderToTexture` boolean. + * + * If you no longer require the Camera to render to a texture, call the `clearRenderToTexture` method, + * which will delete the respective textures and free-up resources. + * @param pipeline An optional WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. + */ + setRenderToTexture(pipeline?: string | Phaser.Renderer.WebGL.WebGLPipeline): Phaser.Cameras.Scene2D.Camera; + + /** + * Sets the WebGL pipeline this Camera is using when rendering to a texture. + * + * You can pass either the string-based name of the pipeline, or a reference to the pipeline itself. + * + * Call this method with no arguments to clear any previously set pipeline. + * @param pipeline The WebGL Pipeline to render with, can be either a string which is the name of the pipeline, or a pipeline reference. Or if left empty it will clear the pipeline. + */ + setPipeline(pipeline?: string | Phaser.Renderer.WebGL.WebGLPipeline): Phaser.Cameras.Scene2D.Camera; + + /** + * If this Camera was set to render to a texture, this will clear the resources it was using and + * redirect it to render back to the primary Canvas again. + * + * If you only wish to temporarily disable rendering to a texture then you can toggle the + * property `renderToTexture` instead. + */ + clearRenderToTexture(): Phaser.Cameras.Scene2D.Camera; + + /** + * Sets the Camera dead zone. + * + * The deadzone is only used when the camera is following a target. + * + * It defines a rectangular region within which if the target is present, the camera will not scroll. + * If the target moves outside of this area, the camera will begin scrolling in order to follow it. + * + * The deadzone rectangle is re-positioned every frame so that it is centered on the mid-point + * of the camera. This allows you to use the object for additional game related checks, such as + * testing if an object is within it or not via a Rectangle.contains call. + * + * The `lerp` values that you can set for a follower target also apply when using a deadzone. + * + * Calling this method with no arguments will reset an active deadzone. + * @param width The width of the deadzone rectangle in pixels. If not specified the deadzone is removed. + * @param height The height of the deadzone rectangle in pixels. + */ + setDeadzone(width?: number, height?: number): Phaser.Cameras.Scene2D.Camera; + + /** + * Fades the Camera in from the given color over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + fadeIn(duration?: integer, red?: integer, green?: integer, blue?: integer, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * Fades the Camera out to the given color over the duration specified. + * This is an alias for Camera.fade that forces the fade to start, regardless of existing fades. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + fadeOut(duration?: integer, red?: integer, green?: integer, blue?: integer, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * Fades the Camera from the given color to transparent over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. + * @param force Force the effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + fadeFrom(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * Fades the Camera from transparent to the given color over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. + * @param force Force the effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + fade(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * Flashes the Camera by setting it to the given color immediately and then fading it away again quickly over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 250. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 255. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 255. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 255. + * @param force Force the effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + flash(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * Shakes the Camera by the given intensity over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 100. + * @param intensity The intensity of the shake. Default 0.05. + * @param force Force the shake effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + shake(duration?: integer, intensity?: number | Phaser.Math.Vector2, force?: boolean, callback?: Function, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * @param x The destination x coordinate to scroll the center of the Camera viewport to. + * @param y The destination y coordinate to scroll the center of the Camera viewport to. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param ease The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. + * @param force Force the pan effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + pan(x: number, y: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraPanCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * @param zoom The target Camera zoom value. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param ease The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. + * @param force Force the pan effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + zoomTo(zoom: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraPanCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * Internal preRender step. + * @param resolution The game resolution, as set in the Scale Manager. + */ + protected preRender(resolution: number): void; + + /** + * Sets the linear interpolation value to use when following a target. + * + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * + * Be sure to keep the value between 0 and 1. A value of zero will disable tracking on that axis. + * @param x The amount added to the horizontal linear interpolation of the follow target. Default 1. + * @param y The amount added to the vertical linear interpolation of the follow target. Default 1. + */ + setLerp(x?: number, y?: number): this; + + /** + * Sets the horizontal and vertical offset of the camera from its follow target. + * The values are subtracted from the targets position during the Cameras update step. + * @param x The horizontal offset from the camera follow target.x position. Default 0. + * @param y The vertical offset from the camera follow target.y position. Default 0. + */ + setFollowOffset(x?: number, y?: number): this; + + /** + * Sets the Camera to follow a Game Object. + * + * When enabled the Camera will automatically adjust its scroll position to keep the target Game Object + * in its center. + * + * You can set the linear interpolation value used in the follow code. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following an object it's probably to do with sub-pixel + * rendering of the targets position. This can be rounded by setting the `roundPixels` argument to `true` to + * force full pixel rounding rendering. Note that this can still be broken if you have specified a non-integer zoom + * value on the camera. So be sure to keep the camera zoom to integers. + * @param target The target for the Camera to follow. + * @param roundPixels Round the camera position to whole integers to avoid sub-pixel rendering? Default false. + * @param lerpX A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. Default 1. + * @param lerpY A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. Default 1. + * @param offsetX The horizontal offset from the camera follow target.x position. Default 0. + * @param offsetY The vertical offset from the camera follow target.y position. Default 0. + */ + startFollow(target: Phaser.GameObjects.GameObject | object, roundPixels?: boolean, lerpX?: number, lerpY?: number, offsetX?: number, offsetY?: number): this; + + /** + * Stops a Camera from following a Game Object, if previously set via `Camera.startFollow`. + */ + stopFollow(): Phaser.Cameras.Scene2D.Camera; + + /** + * Resets any active FX, such as a fade, flash or shake. Useful to call after a fade in order to + * remove the fade. + */ + resetFX(): Phaser.Cameras.Scene2D.Camera; + + /** + * Internal method called automatically by the Camera Manager. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + protected update(time: integer, delta: number): void; + + /** + * Destroys this Camera instance. You rarely need to call this directly. + * + * Called by the Camera Manager. If you wish to destroy a Camera please use `CameraManager.remove` as + * cameras are stored in a pool, ready for recycling later, and calling this directly will prevent that. + */ + destroy(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + } + + /** + * The Camera Manager is a plugin that belongs to a Scene and is responsible for managing all of the Scene Cameras. + * + * By default you can access the Camera Manager from within a Scene using `this.cameras`, although this can be changed + * in your game config. + * + * Create new Cameras using the `add` method. Or extend the Camera class with your own addition code and then add + * the new Camera in using the `addExisting` method. + * + * Cameras provide a view into your game world, and can be positioned, rotated, zoomed and scrolled accordingly. + * + * A Camera consists of two elements: The viewport and the scroll values. + * + * The viewport is the physical position and size of the Camera within your game. Cameras, by default, are + * created the same size as your game, but their position and size can be set to anything. This means if you + * wanted to create a camera that was 320x200 in size, positioned in the bottom-right corner of your game, + * you'd adjust the viewport to do that (using methods like `setViewport` and `setSize`). + * + * If you wish to change where the Camera is looking in your game, then you scroll it. You can do this + * via the properties `scrollX` and `scrollY` or the method `setScroll`. Scrolling has no impact on the + * viewport, and changing the viewport has no impact on the scrolling. + * + * By default a Camera will render all Game Objects it can see. You can change this using the `ignore` method, + * allowing you to filter Game Objects out on a per-Camera basis. The Camera Manager can manage up to 31 unique + * 'Game Object ignore capable' Cameras. Any Cameras beyond 31 that you create will all be given a Camera ID of + * zero, meaning that they cannot be used for Game Object exclusion. This means if you need your Camera to ignore + * Game Objects, make sure it's one of the first 31 created. + * + * A Camera also has built-in special effects including Fade, Flash, Camera Shake, Pan and Zoom. + */ + class CameraManager { + /** + * + * @param scene The Scene that owns the Camera Manager plugin. + */ + constructor(scene: Phaser.Scene); + + /** + * The Scene that owns the Camera Manager plugin. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene.Systems handler for the Scene that owns the Camera Manager. + */ + systems: Phaser.Scenes.Systems; + + /** + * All Cameras created by, or added to, this Camera Manager, will have their `roundPixels` + * property set to match this value. By default it is set to match the value set in the + * game configuration, but can be changed at any point. Equally, individual cameras can + * also be changed as needed. + */ + roundPixels: boolean; + + /** + * An Array of the Camera objects being managed by this Camera Manager. + * The Cameras are updated and rendered in the same order in which they appear in this array. + * Do not directly add or remove entries to this array. However, you can move the contents + * around the array should you wish to adjust the display order. + */ + cameras: Phaser.Cameras.Scene2D.Camera[]; + + /** + * A handy reference to the 'main' camera. By default this is the first Camera the + * Camera Manager creates. You can also set it directly, or use the `makeMain` argument + * in the `add` and `addExisting` methods. It allows you to access it from your game: + * + * ```javascript + * var cam = this.cameras.main; + * ``` + * + * Also see the properties `camera1`, `camera2` and so on. + */ + main: Phaser.Cameras.Scene2D.Camera; + + /** + * A default un-transformed Camera that doesn't exist on the camera list and doesn't + * count towards the total number of cameras being managed. It exists for other + * systems, as well as your own code, should they require a basic un-transformed + * camera instance from which to calculate a view matrix. + */ + default: Phaser.Cameras.Scene2D.Camera; + + /** + * 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. + * @param x The horizontal position of the Camera viewport. Default 0. + * @param y The vertical position of the Camera viewport. Default 0. + * @param width The width of the Camera viewport. If not given it'll be the game config size. + * @param height The height of the Camera viewport. If not given it'll be the game config size. + * @param makeMain Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. Default false. + * @param name The name of the Camera. Default ''. + */ + add(x?: integer, y?: integer, width?: integer, height?: integer, makeMain?: boolean, name?: string): Phaser.Cameras.Scene2D.Camera; + + /** + * Adds an existing Camera into the Camera Manager. + * + * The Camera should either be a `Phaser.Cameras.Scene2D.Camera` instance, or a class that extends from it. + * + * The Camera will have its `roundPixels` property set to whatever `CameraManager.roundPixels` is. You can change + * it after addition if required. + * + * The Camera will be assigned an ID, which is used for Game Object exclusion and then added to the + * manager. As long as it doesn't already exist in the manager it will be added then returned. + * + * If this method returns `null` then the Camera already exists in this Camera Manager. + * @param camera The Camera to be added to the Camera Manager. + * @param makeMain Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it. Default false. + */ + addExisting(camera: Phaser.Cameras.Scene2D.Camera, makeMain?: boolean): Phaser.Cameras.Scene2D.Camera; + + /** + * Gets the total number of Cameras in this Camera Manager. + * + * If the optional `isVisible` argument is set it will only count Cameras that are currently visible. + * @param isVisible Set the `true` to only include visible Cameras in the total. Default false. + */ + getTotal(isVisible?: boolean): integer; + + /** + * 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. + * @param config A Camera configuration object, or an array of them, to be added to this Camera Manager. + */ + fromJSON(config: Phaser.Types.Cameras.Scene2D.CameraConfig | Phaser.Types.Cameras.Scene2D.CameraConfig[]): Phaser.Cameras.Scene2D.CameraManager; + + /** + * 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. + * @param name The name of the Camera. + */ + getCamera(name: string): Phaser.Cameras.Scene2D.Camera; + + /** + * Returns an array of all cameras below the given Pointer. + * + * The first camera in the array is the top-most camera in the camera list. + * @param pointer The Pointer to check against. + */ + getCamerasBelowPointer(pointer: Phaser.Input.Pointer): Phaser.Cameras.Scene2D.Camera[]; + + /** + * Removes the given Camera, or an array of Cameras, from this Camera Manager. + * + * If found in the Camera Manager it will be immediately removed from the local cameras array. + * If also currently the 'main' camera, 'main' will be reset to be camera 0. + * + * The removed Cameras are automatically destroyed if the `runDestroy` argument is `true`, which is the default. + * If you wish to re-use the cameras then set this to `false`, but know that they will retain their references + * and internal data until destroyed or re-added to a Camera Manager. + * @param camera The Camera, or an array of Cameras, to be removed from this Camera Manager. + * @param runDestroy Automatically call `Camera.destroy` on each Camera removed from this Camera Manager. Default true. + */ + remove(camera: Phaser.Cameras.Scene2D.Camera | Phaser.Cameras.Scene2D.Camera[], runDestroy?: boolean): integer; + + /** + * The internal render method. This is called automatically by the Scene and should not be invoked directly. + * + * It will iterate through all local cameras and render them in turn, as long as they're visible and have + * an alpha level > 0. + * @param renderer The Renderer that will render the children to this camera. + * @param children An array of renderable Game Objects. + * @param interpolation Interpolation value. Reserved for future use. + */ + protected render(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer, children: Phaser.GameObjects.GameObject[], interpolation: number): void; + + /** + * Resets this Camera Manager. + * + * This will iterate through all current Cameras, destroying them all, then it will reset the + * cameras array, reset the ID counter and create 1 new single camera using the default values. + */ + resetAll(): Phaser.Cameras.Scene2D.Camera; + + /** + * The main update loop. Called automatically when the Scene steps. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + protected update(time: integer, delta: number): void; + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * @param gameSize The default Game Size object. This is the un-modified game dimensions. + * @param baseSize The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + */ + onResize(gameSize: Phaser.Structs.Size, baseSize: Phaser.Structs.Size): void; + + /** + * Resizes all cameras to the given dimensions. + * @param width The new width of the camera. + * @param height The new height of the camera. + */ + resize(width: number, height: number): void; + + } + + namespace Effects { + /** + * A Camera Fade effect. + * + * This effect will fade the camera viewport to the given color, over the duration specified. + * + * Only the camera viewport is faded. None of the objects it is displaying are impacted, i.e. their colors 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 Fade { + /** + * + * @param camera The camera this effect is acting upon. + */ + constructor(camera: Phaser.Cameras.Scene2D.Camera); + + /** + * The Camera this effect belongs to. + */ + readonly camera: Phaser.Cameras.Scene2D.Camera; + + /** + * Is this effect actively running? + */ + readonly isRunning: boolean; + + /** + * Has this effect finished running? + * + * This is different from `isRunning` because it remains set to `true` when the effect is over, + * until the effect is either reset or started again. + */ + readonly isComplete: boolean; + + /** + * The direction of the fade. + * `true` = fade out (transparent to color), `false` = fade in (color to transparent) + */ + readonly direction: boolean; + + /** + * The duration of the effect, in milliseconds. + */ + readonly duration: integer; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + */ + progress: number; + + /** + * Fades the Camera to or from the given color over the duration specified. + * @param direction The direction of the fade. `true` = fade out (transparent to color), `false` = fade in (color to transparent) Default true. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 0. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 0. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 0. + * @param force Force the effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + start(direction?: boolean, duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraFadeCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * The main update loop for this effect. Called automatically by the Camera. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + update(time: integer, delta: number): void; + + /** + * Called internally by the Canvas Renderer. + * @param ctx The Canvas context to render to. + */ + postRenderCanvas(ctx: CanvasRenderingContext2D): boolean; + + /** + * Called internally by the WebGL Renderer. + * @param pipeline The WebGL Pipeline to render to. + * @param getTintFunction A function that will return the gl safe tint colors. + */ + postRenderWebGL(pipeline: Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline, getTintFunction: Function): boolean; + + /** + * Called internally when the effect completes. + */ + effectComplete(): void; + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + */ + reset(): void; + + /** + * Destroys this effect, releasing it from the Camera. + */ + destroy(): void; + + } + + /** + * A Camera Flash effect. + * + * This effect will flash the camera viewport to the given color, over the duration specified. + * + * Only the camera viewport is flashed. None of the objects it is displaying are impacted, i.e. their colors 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 Flash { + /** + * + * @param camera The camera this effect is acting upon. + */ + constructor(camera: Phaser.Cameras.Scene2D.Camera); + + /** + * The Camera this effect belongs to. + */ + readonly camera: Phaser.Cameras.Scene2D.Camera; + + /** + * Is this effect actively running? + */ + readonly isRunning: boolean; + + /** + * The duration of the effect, in milliseconds. + */ + readonly duration: integer; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + */ + progress: number; + + /** + * Flashes the Camera to or from the given color over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 250. + * @param red The amount to fade the red channel towards. A value between 0 and 255. Default 255. + * @param green The amount to fade the green channel towards. A value between 0 and 255. Default 255. + * @param blue The amount to fade the blue channel towards. A value between 0 and 255. Default 255. + * @param force Force the effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + start(duration?: integer, red?: integer, green?: integer, blue?: integer, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraFlashCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * The main update loop for this effect. Called automatically by the Camera. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + update(time: integer, delta: number): void; + + /** + * Called internally by the Canvas Renderer. + * @param ctx The Canvas context to render to. + */ + postRenderCanvas(ctx: CanvasRenderingContext2D): boolean; + + /** + * Called internally by the WebGL Renderer. + * @param pipeline The WebGL Pipeline to render to. + * @param getTintFunction A function that will return the gl safe tint colors. + */ + postRenderWebGL(pipeline: Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline, getTintFunction: Function): boolean; + + /** + * Called internally when the effect completes. + */ + effectComplete(): void; + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + */ + reset(): void; + + /** + * Destroys this effect, releasing it from the Camera. + */ + destroy(): void; + + } + + /** + * A Camera Pan effect. + * + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * + * Only the camera scroll is moved. 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 Pan { + /** + * + * @param camera The camera this effect is acting upon. + */ + constructor(camera: Phaser.Cameras.Scene2D.Camera); + + /** + * The Camera this effect belongs to. + */ + readonly camera: Phaser.Cameras.Scene2D.Camera; + + /** + * Is this effect actively running? + */ + readonly isRunning: boolean; + + /** + * The duration of the effect, in milliseconds. + */ + readonly duration: integer; + + /** + * The starting scroll coordinates to pan the camera from. + */ + source: Phaser.Math.Vector2; + + /** + * The constantly updated value based on zoom. + */ + current: Phaser.Math.Vector2; + + /** + * The destination scroll coordinates to pan the camera to. + */ + destination: Phaser.Math.Vector2; + + /** + * The ease function to use during the pan. + */ + ease: Function; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + */ + progress: number; + + /** + * This effect will scroll the Camera so that the center of its viewport finishes at the given destination, + * over the duration and with the ease specified. + * @param x The destination x coordinate to scroll the center of the Camera viewport to. + * @param y The destination y coordinate to scroll the center of the Camera viewport to. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param ease The ease to use for the pan. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. + * @param force Force the pan effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent four arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * the current camera scroll x coordinate and the current camera scroll y coordinate. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + start(x: number, y: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraPanCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * The main update loop for this effect. Called automatically by the Camera. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + update(time: integer, delta: number): void; + + /** + * Called internally when the effect completes. + */ + effectComplete(): void; + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + */ + reset(): void; + + /** + * Destroys this effect, releasing it from the Camera. + */ + destroy(): void; + + } + + /** + * A Camera Shake effect. + * + * This effect will shake the camera viewport by a random amount, bounded by the specified intensity, each frame. + * + * Only the camera viewport is moved. 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 Shake { + /** + * + * @param camera The camera this effect is acting upon. + */ + constructor(camera: Phaser.Cameras.Scene2D.Camera); + + /** + * The Camera this effect belongs to. + */ + readonly camera: Phaser.Cameras.Scene2D.Camera; + + /** + * Is this effect actively running? + */ + readonly isRunning: boolean; + + /** + * The duration of the effect, in milliseconds. + */ + readonly duration: integer; + + /** + * The intensity of the effect. Use small float values. The default when the effect starts is 0.05. + * This is a Vector2 object, allowing you to control the shake intensity independently across x and y. + * You can modify this value while the effect is active to create more varied shake effects. + */ + intensity: Phaser.Math.Vector2; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + */ + progress: number; + + /** + * Shakes the Camera by the given intensity over the duration specified. + * @param duration The duration of the effect in milliseconds. Default 100. + * @param intensity The intensity of the shake. Default 0.05. + * @param force Force the shake effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent two arguments: A reference to the camera and a progress amount between 0 and 1 indicating how complete the effect is. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + start(duration?: integer, intensity?: number | Phaser.Math.Vector2, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraShakeCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * The pre-render step for this effect. Called automatically by the Camera. + */ + preRender(): void; + + /** + * The main update loop for this effect. Called automatically by the Camera. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + update(time: integer, delta: number): void; + + /** + * Called internally when the effect completes. + */ + effectComplete(): void; + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + */ + reset(): void; + + /** + * Destroys this effect, releasing it from the Camera. + */ + destroy(): void; + + } + + /** + * A Camera Zoom effect. + * + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * + * 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 Zoom { + /** + * + * @param camera The camera this effect is acting upon. + */ + constructor(camera: Phaser.Cameras.Scene2D.Camera); + + /** + * The Camera this effect belongs to. + */ + readonly camera: Phaser.Cameras.Scene2D.Camera; + + /** + * Is this effect actively running? + */ + readonly isRunning: boolean; + + /** + * The duration of the effect, in milliseconds. + */ + readonly duration: integer; + + /** + * The starting zoom value; + */ + source: number; + + /** + * The destination zoom value. + */ + destination: number; + + /** + * The ease function to use during the zoom. + */ + ease: Function; + + /** + * If this effect is running this holds the current percentage of the progress, a value between 0 and 1. + */ + progress: number; + + /** + * This effect will zoom the Camera to the given scale, over the duration and with the ease specified. + * @param zoom The target Camera zoom value. + * @param duration The duration of the effect in milliseconds. Default 1000. + * @param ease The ease to use for the Zoom. Can be any of the Phaser Easing constants or a custom function. Default 'Linear'. + * @param force Force the zoom effect to start immediately, even if already running. Default false. + * @param callback This callback will be invoked every frame for the duration of the effect. + * It is sent three arguments: A reference to the camera, a progress amount between 0 and 1 indicating how complete the effect is, + * and the current camera zoom value. + * @param context The context in which the callback is invoked. Defaults to the Scene to which the Camera belongs. + */ + start(zoom: number, duration?: integer, ease?: string | Function, force?: boolean, callback?: Phaser.Types.Cameras.Scene2D.CameraZoomCallback, context?: any): Phaser.Cameras.Scene2D.Camera; + + /** + * The main update loop for this effect. Called automatically by the Camera. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + update(time: integer, delta: number): void; + + /** + * Called internally when the effect completes. + */ + effectComplete(): void; + + /** + * Resets this camera effect. + * If it was previously running, it stops instantly without calling its onComplete callback or emitting an event. + */ + reset(): void; + + /** + * Destroys this effect, releasing it from the Camera. + */ + destroy(): void; + + } + + } + + namespace Events { + /** + * The Destroy Camera Event. + * + * This event is dispatched by a Camera instance when it is destroyed by the Camera Manager. + */ + const DESTROY: any; + + /** + * The Camera Fade In Complete Event. + * + * This event is dispatched by a Camera instance when the Fade In Effect completes. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeincomplete', listener)`. + */ + const FADE_IN_COMPLETE: any; + + /** + * The Camera Fade In Start Event. + * + * This event is dispatched by a Camera instance when the Fade In Effect starts. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeinstart', listener)`. + */ + const FADE_IN_START: any; + + /** + * The Camera Fade Out Complete Event. + * + * This event is dispatched by a Camera instance when the Fade Out Effect completes. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeoutcomplete', listener)`. + */ + const FADE_OUT_COMPLETE: any; + + /** + * The Camera Fade Out Start Event. + * + * This event is dispatched by a Camera instance when the Fade Out Effect starts. + * + * Listen to it from a Camera instance using `Camera.on('camerafadeoutstart', listener)`. + */ + const FADE_OUT_START: any; + + /** + * The Camera Flash Complete Event. + * + * This event is dispatched by a Camera instance when the Flash Effect completes. + */ + const FLASH_COMPLETE: any; + + /** + * The Camera Flash Start Event. + * + * This event is dispatched by a Camera instance when the Flash Effect starts. + */ + const FLASH_START: any; + + /** + * The Camera Pan Complete Event. + * + * This event is dispatched by a Camera instance when the Pan Effect completes. + */ + const PAN_COMPLETE: any; + + /** + * The Camera Pan Start Event. + * + * This event is dispatched by a Camera instance when the Pan Effect starts. + */ + const PAN_START: any; + + /** + * The Camera Post-Render Event. + * + * This event is dispatched by a Camera instance after is has finished rendering. + * It is only dispatched if the Camera is rendering to a texture. + * + * Listen to it from a Camera instance using: `camera.on('postrender', listener)`. + */ + const POST_RENDER: any; + + /** + * The Camera Pre-Render Event. + * + * This event is dispatched by a Camera instance when it is about to render. + * It is only dispatched if the Camera is rendering to a texture. + * + * Listen to it from a Camera instance using: `camera.on('prerender', listener)`. + */ + const PRE_RENDER: any; + + /** + * The Camera Shake Complete Event. + * + * This event is dispatched by a Camera instance when the Shake Effect completes. + */ + const SHAKE_COMPLETE: any; + + /** + * The Camera Shake Start Event. + * + * This event is dispatched by a Camera instance when the Shake Effect starts. + */ + const SHAKE_START: any; + + /** + * The Camera Zoom Complete Event. + * + * This event is dispatched by a Camera instance when the Zoom Effect completes. + */ + const ZOOM_COMPLETE: any; + + /** + * The Camera Zoom Start Event. + * + * This event is dispatched by a Camera instance when the Zoom Effect starts. + */ + const ZOOM_START: any; + + } + + } + + namespace Controls { + /** + * A Fixed Key Camera Control. + * + * This allows you to control the movement and zoom of a camera using the defined keys. + * + * ```javascript + * var camControl = new FixedKeyControl({ + * camera: this.cameras.main, + * left: cursors.left, + * right: cursors.right, + * speed: float OR { x: 0, y: 0 } + * }); + * ``` + * + * Movement is precise and has no 'smoothing' applied to it. + * + * You must call the `update` method of this controller every frame. + */ + class FixedKeyControl { + /** + * + * @param config The Fixed Key Control configuration object. + */ + constructor(config: Phaser.Types.Cameras.Controls.FixedKeyControlConfig); + + /** + * The Camera that this Control will update. + */ + camera: Phaser.Cameras.Scene2D.Camera; + + /** + * The Key to be pressed that will move the Camera left. + */ + left: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will move the Camera right. + */ + right: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will move the Camera up. + */ + up: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will move the Camera down. + */ + down: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will zoom the Camera in. + */ + zoomIn: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will zoom the Camera out. + */ + zoomOut: Phaser.Input.Keyboard.Key; + + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + */ + zoomSpeed: number; + + /** + * The horizontal speed the camera will move. + */ + speedX: number; + + /** + * The vertical speed the camera will move. + */ + speedY: number; + + /** + * A flag controlling if the Controls will update the Camera or not. + */ + active: boolean; + + /** + * Starts the Key Control running, providing it has been linked to a camera. + */ + start(): Phaser.Cameras.Controls.FixedKeyControl; + + /** + * Stops this Key Control from running. Call `start` to start it again. + */ + stop(): Phaser.Cameras.Controls.FixedKeyControl; + + /** + * Binds this Key Control to a camera. + * @param camera The camera to bind this Key Control to. + */ + setCamera(camera: Phaser.Cameras.Scene2D.Camera): Phaser.Cameras.Controls.FixedKeyControl; + + /** + * Applies the results of pressing the control keys to the Camera. + * + * You must call this every step, it is not called automatically. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(delta: number): void; + + /** + * Destroys this Key Control. + */ + destroy(): void; + + } + + /** + * A Smoothed Key Camera Control. + * + * This allows you to control the movement and zoom of a camera using the defined keys. + * Unlike the Fixed Camera Control you can also provide physics values for acceleration, drag and maxSpeed for smoothing effects. + * + * ```javascript + * var controlConfig = { + * camera: this.cameras.main, + * left: cursors.left, + * right: cursors.right, + * up: cursors.up, + * down: cursors.down, + * zoomIn: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q), + * zoomOut: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.E), + * zoomSpeed: 0.02, + * acceleration: 0.06, + * drag: 0.0005, + * maxSpeed: 1.0 + * }; + * ``` + * + * You must call the `update` method of this controller every frame. + */ + class SmoothedKeyControl { + /** + * + * @param config The Smoothed Key Control configuration object. + */ + constructor(config: Phaser.Types.Cameras.Controls.SmoothedKeyControlConfig); + + /** + * The Camera that this Control will update. + */ + camera: Phaser.Cameras.Scene2D.Camera; + + /** + * The Key to be pressed that will move the Camera left. + */ + left: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will move the Camera right. + */ + right: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will move the Camera up. + */ + up: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will move the Camera down. + */ + down: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will zoom the Camera in. + */ + zoomIn: Phaser.Input.Keyboard.Key; + + /** + * The Key to be pressed that will zoom the Camera out. + */ + zoomOut: Phaser.Input.Keyboard.Key; + + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + */ + zoomSpeed: number; + + /** + * The horizontal acceleration the camera will move. + */ + accelX: number; + + /** + * The vertical acceleration the camera will move. + */ + accelY: number; + + /** + * The horizontal drag applied to the camera when it is moving. + */ + dragX: number; + + /** + * The vertical drag applied to the camera when it is moving. + */ + dragY: number; + + /** + * The maximum horizontal speed the camera will move. + */ + maxSpeedX: number; + + /** + * The maximum vertical speed the camera will move. + */ + maxSpeedY: number; + + /** + * A flag controlling if the Controls will update the Camera or not. + */ + active: boolean; + + /** + * Starts the Key Control running, providing it has been linked to a camera. + */ + start(): Phaser.Cameras.Controls.SmoothedKeyControl; + + /** + * Stops this Key Control from running. Call `start` to start it again. + */ + stop(): Phaser.Cameras.Controls.SmoothedKeyControl; + + /** + * Binds this Key Control to a camera. + * @param camera The camera to bind this Key Control to. + */ + setCamera(camera: Phaser.Cameras.Scene2D.Camera): Phaser.Cameras.Controls.SmoothedKeyControl; + + /** + * Applies the results of pressing the control keys to the Camera. + * + * You must call this every step, it is not called automatically. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(delta: number): void; + + /** + * Destroys this Key Control. + */ + destroy(): void; + + } + + } + + } + + /** + * Phaser Release Version + */ + const VERSION: string; + + /** + * AUTO Detect Renderer. + */ + const AUTO: integer; + + /** + * Canvas Renderer. + */ + const CANVAS: integer; + + /** + * WebGL Renderer. + */ + const WEBGL: integer; + + /** + * Headless Renderer. + */ + const HEADLESS: integer; + + /** + * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead + * to help you remember what the value is doing in your code. + */ + const FOREVER: integer; + + /** + * Direction constant. + */ + const NONE: integer; + + /** + * Direction constant. + */ + const UP: integer; + + /** + * Direction constant. + */ + const DOWN: integer; + + /** + * Direction constant. + */ + const LEFT: integer; + + /** + * Direction constant. + */ + const RIGHT: integer; + + /** + * The Phaser.Game instance is the main controller for the entire Phaser game. It is responsible + * for handling the boot process, parsing the configuration values, creating the renderer, + * and setting-up all of the global Phaser systems, such as sound and input. + * Once that is complete it will start the Scene Manager and then begin the main game loop. + * + * You should generally avoid accessing any of the systems created by Game, and instead use those + * made available to you via the Phaser.Scene Systems class instead. + */ + class Game { + /** + * + * @param GameConfig The configuration object for your Phaser Game instance. + */ + constructor(GameConfig?: Phaser.Types.Core.GameConfig); + + /** + * The parsed Game Configuration object. + * + * The values stored within this object are read-only and should not be changed at run-time. + */ + readonly config: Phaser.Core.Config; + + /** + * A reference to either the Canvas or WebGL Renderer that this Game is using. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * A reference to an HTML Div Element used as the DOM Element Container. + * + * Only set if `createDOMContainer` is `true` in the game config (by default it is `false`) and + * if you provide a parent element to insert the Phaser Game inside. + * + * See the DOM Element Game Object for more details. + */ + domContainer: HTMLDivElement; + + /** + * A reference to the HTML Canvas Element that Phaser uses to render the game. + * This is created automatically by Phaser unless you provide a `canvas` property + * in your Game Config. + */ + canvas: HTMLCanvasElement; + + /** + * A reference to the Rendering Context belonging to the Canvas Element this game is rendering to. + * If the game is running under Canvas it will be a 2d Canvas Rendering Context. + * If the game is running under WebGL it will be a WebGL Rendering Context. + * This context is created automatically by Phaser unless you provide a `context` property + * in your Game Config. + */ + context: CanvasRenderingContext2D | WebGLRenderingContext; + + /** + * A flag indicating when this Game instance has finished its boot process. + */ + readonly isBooted: boolean; + + /** + * A flag indicating if this Game is currently running its game step or not. + */ + readonly isRunning: boolean; + + /** + * An Event Emitter which is used to broadcast game-level events from the global systems. + */ + events: Phaser.Events.EventEmitter; + + /** + * An instance of the Animation Manager. + * + * The Animation Manager is a global system responsible for managing all animations used within your game. + */ + anims: Phaser.Animations.AnimationManager; + + /** + * An instance of the Texture Manager. + * + * The Texture Manager is a global system responsible for managing all textures being used by your game. + */ + textures: Phaser.Textures.TextureManager; + + /** + * An instance of the Cache Manager. + * + * The Cache Manager is a global system responsible for caching, accessing and releasing external game assets. + */ + cache: Phaser.Cache.CacheManager; + + /** + * An instance of the Data Manager + */ + registry: Phaser.Data.DataManager; + + /** + * An instance of the Input Manager. + * + * The Input Manager is a global system responsible for the capture of browser-level input events. + */ + input: Phaser.Input.InputManager; + + /** + * An instance of the Scene Manager. + * + * The Scene Manager is a global system responsible for creating, modifying and updating the Scenes in your game. + */ + scene: Phaser.Scenes.SceneManager; + + /** + * A reference to the Device inspector. + * + * Contains information about the device running this game, such as OS, browser vendor and feature support. + * Used by various systems to determine capabilities and code paths. + */ + device: Phaser.DeviceConf; + + /** + * An instance of the Scale Manager. + * + * The Scale Manager is a global system responsible for handling scaling of the game canvas. + */ + scale: Phaser.Scale.ScaleManager; + + /** + * An instance of the base Sound Manager. + * + * The Sound Manager is a global system responsible for the playback and updating of all audio in your game. + * + * You can disable the inclusion of the Sound Manager in your build by toggling the webpack `FEATURE_SOUND` flag. + */ + sound: Phaser.Sound.NoAudioSoundManager | Phaser.Sound.HTML5AudioSoundManager | Phaser.Sound.WebAudioSoundManager; + + /** + * An instance of the Time Step. + * + * The Time Step is a global system responsible for setting-up and responding to the browser frame events, processing + * them and calculating delta values. It then automatically calls the game step. + */ + loop: Phaser.Core.TimeStep; + + /** + * An instance of the Plugin Manager. + * + * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install + * those plugins into Scenes as required. + */ + plugins: Phaser.Plugins.PluginManager; + + /** + * An instance of the Facebook Instant Games Plugin. + * + * This will only be available if the plugin has been built into Phaser, + * or you're using the special Facebook Instant Games custom build. + */ + facebook: Phaser.FacebookInstantGamesPlugin; + + /** + * Does the window the game is running in currently have focus or not? + * This is modified by the VisibilityHandler. + */ + readonly hasFocus: boolean; + + /** + * This method is called automatically when the DOM is ready. It is responsible for creating the renderer, + * displaying the Debug Header, adding the game canvas to the DOM and emitting the 'boot' event. + * It listens for a 'ready' event from the base systems and once received it will call `Game.start`. + */ + protected boot(): void; + + /** + * Called automatically by Game.boot once all of the global systems have finished setting themselves up. + * By this point the Game is now ready to start the main loop running. + * It will also enable the Visibility Handler. + */ + protected start(): void; + + /** + * 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. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + step(time: number, delta: number): void; + + /** + * 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. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + headlessStep(time: number, delta: number): void; + + /** + * Called automatically by the Visibility Handler. + * This will pause the main loop and then emit a pause event. + */ + protected onHidden(): void; + + /** + * Called automatically by the Visibility Handler. + * This will resume the main loop and then emit a resume event. + */ + protected onVisible(): void; + + /** + * Called automatically by the Visibility Handler. + * This will set the main loop into a 'blurred' state, which pauses it. + */ + protected onBlur(): void; + + /** + * Called automatically by the Visibility Handler. + * This will set the main loop into a 'focused' state, which resumes it. + */ + protected onFocus(): void; + + /** + * Returns the current game frame. + * + * When the game starts running, the frame is incremented every time Request Animation Frame, or Set Timeout, fires. + */ + getFrame(): number; + + /** + * Returns the time that the current game step started at, as based on `performance.now`. + */ + getTime(): number; + + /** + * Flags this Game instance as needing to be destroyed on the _next frame_, making this an asynchronous operation. + * + * It will wait until the current frame has completed and then call `runDestroy` internally. + * + * If you need to react to the games eventual destruction, listen for the `DESTROY` event. + * + * If you **do not** need to run Phaser again on the same web page you can set the `noReturn` argument to `true` and it will free-up + * memory being held by the core Phaser plugins. If you do need to create another game instance on the same page, leave this as `false`. + * @param removeCanvas Set to `true` if you would like the parent canvas element removed from the DOM, or `false` to leave it in place. + * @param noReturn If `true` all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this. Default false. + */ + destroy(removeCanvas: boolean, noReturn?: boolean): void; + + } + + namespace Core { + /** + * The active game configuration settings, parsed from a {@link Phaser.Types.Core.GameConfig} object. + */ + class Config { + /** + * + * @param GameConfig The configuration object for your Phaser Game instance. + */ + constructor(GameConfig?: Phaser.Types.Core.GameConfig); + + /** + * The width of the underlying canvas, in pixels. + */ + readonly width: integer | string; + + /** + * The height of the underlying canvas, in pixels. + */ + readonly height: integer | string; + + /** + * The zoom factor, as used by the Scale Manager. + */ + readonly zoom: Phaser.Scale.ZoomType | integer; + + /** + * The canvas device pixel resolution. Currently un-used. + */ + readonly resolution: number; + + /** + * A parent DOM element into which the canvas created by the renderer will be injected. + */ + readonly parent: any; + + /** + * The scale mode as used by the Scale Manager. The default is zero, which is no scaling. + */ + readonly scaleMode: Phaser.Scale.ScaleModeType; + + /** + * Is the Scale Manager allowed to adjust the CSS height property of the parent to be 100%? + */ + readonly expandParent: boolean; + + /** + * Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. + */ + readonly autoRound: integer; + + /** + * Automatically center the canvas within the parent? + */ + readonly autoCenter: Phaser.Scale.CenterType; + + /** + * How many ms should elapse before checking if the browser size has changed? + */ + readonly resizeInterval: integer; + + /** + * The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. + */ + readonly fullscreenTarget: HTMLElement | string; + + /** + * The minimum width, in pixels, the canvas will scale down to. A value of zero means no minimum. + */ + readonly minWidth: integer; + + /** + * The maximum width, in pixels, the canvas will scale up to. A value of zero means no maximum. + */ + readonly maxWidth: integer; + + /** + * The minimum height, in pixels, the canvas will scale down to. A value of zero means no minimum. + */ + readonly minHeight: integer; + + /** + * The maximum height, in pixels, the canvas will scale up to. A value of zero means no maximum. + */ + readonly maxHeight: integer; + + /** + * Force Phaser to use a specific renderer. Can be `CONST.CANVAS`, `CONST.WEBGL`, `CONST.HEADLESS` or `CONST.AUTO` (default) + */ + readonly renderType: number; + + /** + * Force Phaser to use your own Canvas element instead of creating one. + */ + readonly canvas: HTMLCanvasElement; + + /** + * Force Phaser to use your own Canvas context instead of creating one. + */ + readonly context: CanvasRenderingContext2D | WebGLRenderingContext; + + /** + * Optional CSS attributes to be set on the canvas object created by the renderer. + */ + readonly canvasStyle: string; + + /** + * Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. + */ + readonly customEnvironment: boolean; + + /** + * The default Scene configuration object. + */ + readonly sceneConfig: object; + + /** + * A seed which the Random Data Generator will use. If not given, a dynamic seed based on the time is used. + */ + readonly seed: string[]; + + /** + * The title of the game. + */ + readonly gameTitle: string; + + /** + * The URL of the game. + */ + readonly gameURL: string; + + /** + * The version of the game. + */ + readonly gameVersion: string; + + /** + * If `true` the window will automatically be given focus immediately and on any future mousedown event. + */ + readonly autoFocus: boolean; + + /** + * Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. + */ + readonly domCreateContainer: boolean; + + /** + * Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? + */ + readonly domBehindCanvas: boolean; + + /** + * Enable the Keyboard Plugin. This can be disabled in games that don't need keyboard input. + */ + readonly inputKeyboard: boolean; + + /** + * The DOM Target to listen for keyboard events on. Defaults to `window` if not specified. + */ + readonly inputKeyboardEventTarget: any; + + /** + * `preventDefault` will be called on every non-modified key which has a key code in this array. By default, it is empty. + */ + readonly inputKeyboardCapture: integer[]; + + /** + * Enable the Mouse Plugin. This can be disabled in games that don't need mouse input. + */ + readonly inputMouse: boolean | object; + + /** + * The DOM Target to listen for mouse events on. Defaults to the game canvas if not specified. + */ + readonly inputMouseEventTarget: any; + + /** + * Should mouse events be captured? I.e. have prevent default called on them. + */ + readonly inputMouseCapture: boolean; + + /** + * Enable the Touch Plugin. This can be disabled in games that don't need touch input. + */ + readonly inputTouch: boolean; + + /** + * The DOM Target to listen for touch events on. Defaults to the game canvas if not specified. + */ + readonly inputTouchEventTarget: any; + + /** + * Should touch events be captured? I.e. have prevent default called on them. + */ + readonly inputTouchCapture: boolean; + + /** + * The number of Pointer objects created by default. In a mouse-only, or non-multi touch game, you can leave this as 1. + */ + readonly inputActivePointers: integer; + + /** + * The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. + */ + readonly inputSmoothFactor: integer; + + /** + * Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. + */ + readonly inputWindowEvents: boolean; + + /** + * Enable the Gamepad Plugin. This can be disabled in games that don't need gamepad input. + */ + readonly inputGamepad: boolean; + + /** + * The DOM Target to listen for gamepad events on. Defaults to `window` if not specified. + */ + readonly inputGamepadEventTarget: any; + + /** + * Set to `true` to disable the right-click context menu. + */ + readonly disableContextMenu: boolean; + + /** + * The Audio Configuration object. + */ + readonly audio: Phaser.Types.Core.AudioConfig; + + /** + * Don't write the banner line to the console.log. + */ + readonly hideBanner: boolean; + + /** + * Omit Phaser's name and version from the banner. + */ + readonly hidePhaser: boolean; + + /** + * The color of the banner text. + */ + readonly bannerTextColor: string; + + /** + * The background colors of the banner. + */ + readonly bannerBackgroundColor: string[]; + + /** + * The Frame Rate Configuration object, as parsed by the Timestep class. + */ + readonly fps: Phaser.Types.Core.FPSConfig; + + /** + * When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. + */ + readonly antialias: boolean; + + /** + * Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. + */ + readonly antialiasGL: boolean; + + /** + * Sets the `mipmapFilter` property when the WebGL renderer is created. + */ + readonly mipmapFilter: string; + + /** + * 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. + */ + readonly desynchronized: boolean; + + /** + * Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. + */ + readonly roundPixels: boolean; + + /** + * Prevent pixel art from becoming blurred when scaled. It will remain crisp (tells the WebGL renderer to automatically create textures using a linear filter mode). + */ + readonly pixelArt: boolean; + + /** + * Whether the game canvas will have a transparent background. + */ + readonly transparent: boolean; + + /** + * Whether the game canvas will be cleared between each rendering frame. You can disable this if you have a full-screen background image or game object. + */ + readonly clearBeforeRender: boolean; + + /** + * In WebGL mode, sets the drawing buffer to contain colors with pre-multiplied alpha. + */ + readonly premultipliedAlpha: boolean; + + /** + * Let the browser abort creating a WebGL context if it judges performance would be unacceptable. + */ + readonly failIfMajorPerformanceCaveat: boolean; + + /** + * "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. + */ + readonly powerPreference: string; + + /** + * The default WebGL Batch size. + */ + readonly batchSize: integer; + + /** + * The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. + */ + readonly maxLights: integer; + + /** + * The background color of the game canvas. The default is black. This value is ignored if `transparent` is set to `true`. + */ + readonly backgroundColor: Phaser.Display.Color; + + /** + * Called before Phaser boots. Useful for initializing anything not related to Phaser that Phaser may require while booting. + */ + readonly preBoot: Phaser.Types.Core.BootCallback; + + /** + * A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. + */ + readonly postBoot: Phaser.Types.Core.BootCallback; + + /** + * The Physics Configuration object. + */ + readonly physics: Phaser.Types.Core.PhysicsConfig; + + /** + * The default physics system. It will be started for each scene. Either 'arcade', 'impact' or 'matter'. + */ + readonly defaultPhysicsSystem: boolean | string; + + /** + * A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. + */ + readonly loaderBaseURL: string; + + /** + * A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. + */ + readonly loaderPath: string; + + /** + * Maximum parallel downloads allowed for resources (Default to 32). + */ + readonly loaderMaxParallelDownloads: integer; + + /** + * '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}. + */ + readonly loaderCrossOrigin: string | undefined; + + /** + * The response type of the XHR request, e.g. `blob`, `text`, etc. + */ + readonly loaderResponseType: string; + + /** + * Should the XHR request use async or not? + */ + readonly loaderAsync: boolean; + + /** + * Optional username for all XHR requests. + */ + readonly loaderUser: string; + + /** + * Optional password for all XHR requests. + */ + readonly loaderPassword: string; + + /** + * Optional XHR timeout value, in ms. + */ + readonly loaderTimeout: integer; + + /** + * An array of global plugins to be installed. + */ + readonly installGlobalPlugins: any; + + /** + * An array of Scene level plugins to be installed. + */ + readonly installScenePlugins: any; + + /** + * The plugins installed into every Scene (in addition to CoreScene and Global). + */ + readonly defaultPlugins: any; + + /** + * A base64 encoded PNG that will be used as the default blank texture. + */ + readonly defaultImage: string; + + /** + * A base64 encoded PNG that will be used as the default texture when a texture is assigned that is missing or not loaded. + */ + readonly missingImage: string; + + } + + /** + * Called automatically by Phaser.Game and responsible for creating the renderer it will use. + * + * Relies upon two webpack global flags to be defined: `WEBGL_RENDERER` and `CANVAS_RENDERER` during build time, but not at run-time. + * @param game The Phaser.Game instance on which the renderer will be set. + */ + function CreateRenderer(game: Phaser.Game): void; + + /** + * Called automatically by Phaser.Game and responsible for creating the console.log debug header. + * + * You can customize or disable the header via the Game Config object. + * @param game The Phaser.Game instance which will output this debug header. + */ + function DebugHeader(game: Phaser.Game): void; + + namespace Events { + /** + * The Game Blur Event. + * + * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded + * enters a blurred state. The blur event is raised when the window loses focus. This can happen if a user swaps + * tab, or if they simply remove focus from the browser to another app. + */ + const BLUR: any; + + /** + * The Game Boot Event. + * + * This event is dispatched when the Phaser Game instance has finished booting, but before it is ready to start running. + * The global systems use this event to know when to set themselves up, dispatching their own `ready` events as required. + */ + const BOOT: any; + + /** + * The Game Context Lost Event. + * + * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Lost event from the browser. + * + * The partner event is `CONTEXT_RESTORED`. + */ + const CONTEXT_LOST: any; + + /** + * The Game Context Restored Event. + * + * This event is dispatched by the Game if the WebGL Renderer it is using encounters a WebGL Context Restored event from the browser. + * + * The partner event is `CONTEXT_LOST`. + */ + const CONTEXT_RESTORED: any; + + /** + * The Game Destroy Event. + * + * This event is dispatched when the game instance has been told to destroy itself. + * Lots of internal systems listen to this event in order to clear themselves out. + * Custom plugins and game code should also do the same. + */ + const DESTROY: any; + + /** + * The Game Focus Event. + * + * This event is dispatched by the Game Visibility Handler when the window in which the Game instance is embedded + * enters a focused state. The focus event is raised when the window re-gains focus, having previously lost it. + */ + const FOCUS: any; + + /** + * The Game Hidden Event. + * + * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded + * enters a hidden state. Only browsers that support the Visibility API will cause this event to be emitted. + * + * In most modern browsers, when the document enters a hidden state, the Request Animation Frame and setTimeout, which + * control the main game loop, will automatically pause. There is no way to stop this from happening. It is something + * your game should account for in its own code, should the pause be an issue (i.e. for multiplayer games) + */ + const HIDDEN: any; + + /** + * The Game Pause Event. + * + * This event is dispatched when the Game loop enters a paused state, usually as a result of the Visibility Handler. + */ + const PAUSE: any; + + /** + * The Game Post-Render Event. + * + * This event is dispatched right at the end of the render process. + * + * Every Scene will have rendered and been drawn to the canvas by the time this event is fired. + * Use it for any last minute post-processing before the next game step begins. + */ + const POST_RENDER: any; + + /** + * 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. + */ + const POST_STEP: any; + + /** + * The Game Pre-Render Event. + * + * This event is dispatched immediately before any of the Scenes have started to render. + * + * The renderer will already have been initialized this frame, clearing itself and preparing to receive the Scenes for rendering, but it won't have actually drawn anything yet. + */ + const PRE_RENDER: any; + + /** + * 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. + */ + const PRE_STEP: any; + + /** + * The Game Ready Event. + * + * This event is dispatched when the Phaser Game instance has finished booting, the Texture Manager is fully ready, + * and all local systems are now able to start. + */ + const READY: any; + + /** + * The Game Resume Event. + * + * This event is dispatched when the game loop leaves a paused state and resumes running. + */ + const RESUME: any; + + /** + * 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. + */ + const STEP: any; + + /** + * The Game Visible Event. + * + * This event is dispatched by the Game Visibility Handler when the document in which the Game instance is embedded + * enters a visible state, previously having been hidden. + * + * Only browsers that support the Visibility API will cause this event to be emitted. + */ + const VISIBLE: any; + + } + + /** + * 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 { + /** + * + * @param game A reference to the Phaser.Game instance that owns this Time Step. + */ + constructor(game: Phaser.Game, config: Phaser.Types.Core.FPSConfig); + + /** + * A reference to the Phaser.Game instance. + */ + readonly game: Phaser.Game; + + /** + * The Request Animation Frame DOM Event handler. + */ + readonly raf: Phaser.DOM.RequestAnimationFrame; + + /** + * A flag that is set once the TimeStep has started running and toggled when it stops. + */ + readonly started: boolean; + + /** + * A flag that is set once the TimeStep has started running and toggled when it stops. + * The difference between this value and `started` is that `running` is toggled when + * the TimeStep is sent to sleep, where-as `started` remains `true`, only changing if + * the TimeStep is actually stopped, not just paused. + */ + readonly running: boolean; + + /** + * The minimum fps rate you want the Time Step to run at. + */ + minFps: integer; + + /** + * The target fps rate for the Time Step to run at. + * + * Setting this value will not actually change the speed at which the browser runs, that is beyond + * the control of Phaser. Instead, it allows you to determine performance issues and if the Time Step + * is spiraling out of control. + */ + targetFps: integer; + + /** + * An exponential moving average of the frames per second. + */ + readonly actualFps: integer; + + /** + * The time at which the next fps rate update will take place. + * When an fps update happens, the `framesThisSecond` value is reset. + */ + readonly nextFpsUpdate: integer; + + /** + * The number of frames processed this second. + */ + readonly framesThisSecond: integer; + + /** + * A callback to be invoked each time the Time Step steps. + */ + callback: Phaser.Types.Core.TimeStepCallback; + + /** + * You can force the Time Step to use Set Timeout instead of Request Animation Frame by setting + * the `forceSetTimeOut` property to `true` in the Game Configuration object. It cannot be changed at run-time. + */ + readonly forceSetTimeOut: boolean; + + /** + * The time, calculated at the start of the current step, as smoothed by the delta value. + */ + time: number; + + /** + * The time at which the game started running. This value is adjusted if the game is then + * paused and resumes. + */ + startTime: number; + + /** + * The time, as returned by `performance.now` of the previous step. + */ + lastTime: number; + + /** + * The current frame the game is on. This counter is incremented once every game step, regardless of how much + * time has passed and is unaffected by delta smoothing. + */ + readonly frame: integer; + + /** + * Is the browser currently considered in focus by the Page Visibility API? + * This value is set in the `blur` method, which is called automatically by the Game instance. + */ + readonly inFocus: boolean; + + /** + * The delta time, in ms, since the last game step. This is a clamped and smoothed average value. + */ + delta: integer; + + /** + * Internal index of the delta history position. + */ + deltaIndex: integer; + + /** + * Internal array holding the previous delta values, used for delta smoothing. + */ + deltaHistory: integer[]; + + /** + * The maximum number of delta values that are retained in order to calculate a smoothed moving average. + * + * This can be changed in the Game Config via the `fps.deltaHistory` property. The default is 10. + */ + deltaSmoothingMax: integer; + + /** + * The number of frames that the cooldown is set to after the browser panics over the FPS rate, usually + * as a result of switching tabs and regaining focus. + * + * This can be changed in the Game Config via the `fps.panicMax` property. The default is 120. + */ + panicMax: integer; + + /** + * The actual elapsed time in ms between one update and the next. + * + * Unlike with `delta`, no smoothing, capping, or averaging is applied to this value. + * So please be careful when using this value in math calculations. + */ + rawDelta: number; + + /** + * The time, as returned by `performance.now` at the very start of the current step. + * This can differ from the `time` value in that it isn't calculated based on the delta value. + */ + now: number; + + /** + * Apply smoothing to the delta value used within Phasers internal calculations? + * + * This can be changed in the Game Config via the `fps.smoothStep` property. The default is `true`. + * + * Smoothing helps settle down the delta values after browser tab switches, or other situations + * which could cause significant delta spikes or dips. By default it has been enabled in Phaser 3 + * since the first version, but is now exposed under this property (and the corresponding game config + * `smoothStep` value), to allow you to easily disable it, should you require. + */ + smoothStep: boolean; + + /** + * Called by the Game instance when the DOM window.onBlur event triggers. + */ + blur(): void; + + /** + * Called by the Game instance when the DOM window.onFocus event triggers. + */ + focus(): void; + + /** + * Called when the visibility API says the game is 'hidden' (tab switch out of view, etc) + */ + pause(): void; + + /** + * Called when the visibility API says the game is 'visible' again (tab switch back into view, etc) + */ + resume(): void; + + /** + * Resets the time, lastTime, fps averages and delta history. + * Called automatically when a browser sleeps them resumes. + */ + resetDelta(): void; + + /** + * Starts the Time Step running, if it is not already doing so. + * Called automatically by the Game Boot process. + * @param callback The callback to be invoked each time the Time Step steps. + */ + start(callback: Phaser.Types.Core.TimeStepCallback): void; + + /** + * The main step method. This is called each time the browser updates, either by Request Animation Frame, + * or by Set Timeout. It is responsible for calculating the delta values, frame totals, cool down history and more. + * You generally should never call this method directly. + */ + step(): void; + + /** + * Manually calls `TimeStep.step`. + */ + tick(): void; + + /** + * Sends the TimeStep to sleep, stopping Request Animation Frame (or SetTimeout) and toggling the `running` flag to false. + */ + sleep(): void; + + /** + * 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. + * @param seamless Adjust the startTime based on the lastTime values. Default false. + */ + wake(seamless?: boolean): void; + + /** + * Gets the duration which the game has been running, in seconds. + */ + getDuration(): number; + + /** + * Gets the duration which the game has been running, in ms. + */ + getDurationMS(): number; + + /** + * Stops the TimeStep running. + */ + stop(): this; + + /** + * Destroys the TimeStep. This will stop Request Animation Frame, stop the step, clear the callbacks and null + * any objects. + */ + destroy(): void; + + } + + /** + * The Visibility Handler is responsible for listening out for document level visibility change events. + * This includes `visibilitychange` if the browser supports it, and blur and focus events. It then uses + * the provided Event Emitter and fires the related events. + * @param game The Game instance this Visibility Handler is working on. + */ + function VisibilityHandler(game: Phaser.Game): void; + + } + + namespace Create { + /** + * [description] + * @param config [description] + */ + function GenerateTexture(config: Phaser.Types.Create.GenerateTextureConfig): HTMLCanvasElement; + + namespace Palettes { + /** + * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) + */ + var ARNE16: Phaser.Types.Create.Palette; + + /** + * A 16 color palette inspired by the Commodore 64. + */ + var C64: Phaser.Types.Create.Palette; + + /** + * A 16 color CGA inspired palette by [Arne](http://androidarts.com/palette/16pal.htm) + */ + var CGA: Phaser.Types.Create.Palette; + + /** + * A 16 color JMP palette by [Arne](http://androidarts.com/palette/16pal.htm) + */ + var JMP: Phaser.Types.Create.Palette; + + /** + * A 16 color palette inspired by Japanese computers like the MSX. + */ + var MSX: Phaser.Types.Create.Palette; + + } + + } + + namespace Curves { + /** + * A higher-order Bézier curve constructed of four points. + */ + class CubicBezier extends Phaser.Curves.Curve { + /** + * + * @param p0 Start point, or an array of point pairs. + * @param p1 Control Point 1. + * @param p2 Control Point 2. + * @param p3 End Point. + */ + constructor(p0: Phaser.Math.Vector2 | Phaser.Math.Vector2[], p1: Phaser.Math.Vector2, p2: Phaser.Math.Vector2, p3: Phaser.Math.Vector2); + + /** + * The start point of this curve. + */ + p0: Phaser.Math.Vector2; + + /** + * The first control point of this curve. + */ + p1: Phaser.Math.Vector2; + + /** + * The second control point of this curve. + */ + p2: Phaser.Math.Vector2; + + /** + * The end point of this curve. + */ + p3: Phaser.Math.Vector2; + + /** + * Gets the starting point on the curve. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getStartPoint(out?: O): O; + + /** + * Returns the resolution of this curve. + * @param divisions The amount of divisions used by this curve. + */ + getResolution(divisions: number): number; + + /** + * Get point at relative position in curve according to length. + * @param t The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPoint(t: number, out?: O): O; + + /** + * Draws this curve to the specified graphics object. + * @param graphics The graphics object this curve should be drawn to. + * @param pointsTotal The number of intermediary points that make up this curve. A higher number of points will result in a smoother curve. Default 32. + */ + draw(graphics: G, pointsTotal?: integer): G; + + /** + * Returns a JSON object that describes this curve. + */ + toJSON(): Phaser.Types.Curves.JSONCurve; + + /** + * Generates a curve from a JSON object. + * @param data The JSON object containing this curve data. + */ + static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.CubicBezier; + + } + + /** + * A Base Curve class, which all other curve types extend. + * + * Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog) + */ + class Curve { + /** + * + * @param type The curve type. + */ + constructor(type: string); + + /** + * String based identifier for the type of curve. + */ + type: string; + + /** + * The default number of divisions within the curve. + */ + defaultDivisions: integer; + + /** + * The quantity of arc length divisions within the curve. + */ + arcLengthDivisions: integer; + + /** + * An array of cached arc length values. + */ + cacheArcLengths: number[]; + + /** + * Does the data of this curve need updating? + */ + needsUpdate: boolean; + + /** + * For a curve on a Path, `false` means the Path will ignore this curve. + */ + active: boolean; + + /** + * Draws this curve on the given Graphics object. + * + * The curve is drawn using `Graphics.strokePoints` so will be drawn at whatever the present Graphics stroke color is. + * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. + * @param graphics The Graphics instance onto which this curve will be drawn. + * @param pointsTotal The resolution of the curve. The higher the value the smoother it will render, at the cost of rendering performance. Default 32. + */ + draw(graphics: G, pointsTotal?: integer): G; + + /** + * Returns a Rectangle where the position and dimensions match the bounds of this Curve. + * + * You can control the accuracy of the bounds. The value given is used to work out how many points + * to plot across the curve. Higher values are more accurate at the cost of calculation speed. + * @param out The Rectangle to store the bounds in. If falsey a new object will be created. + * @param accuracy The accuracy of the bounds calculations. Default 16. + */ + getBounds(out?: Phaser.Geom.Rectangle, accuracy?: integer): Phaser.Geom.Rectangle; + + /** + * Returns an array of points, spaced out X distance pixels apart. + * The smaller the distance, the larger the array will be. + * @param distance The distance, in pixels, between each point along the curve. + */ + getDistancePoints(distance: integer): Phaser.Geom.Point[]; + + /** + * Get a point at the end of the curve. + * @param out Optional Vector object to store the result in. + */ + getEndPoint(out?: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Get total curve arc length + */ + getLength(): number; + + /** + * Get a list of cumulative segment lengths. + * + * These lengths are + * + * - [0] 0 + * - [1] The first segment + * - [2] The first and second segment + * - ... + * - [divisions] All segments + * @param divisions The number of divisions or segments. + */ + getLengths(divisions?: integer): number[]; + + /** + * Get a point at a relative position on the curve, by arc length. + * @param u The relative position, [0..1]. + * @param out A point to store the result in. + */ + getPointAt(u: number, out?: O): O; + + /** + * Get a sequence of evenly spaced points from the curve. + * + * You can pass `divisions`, `stepRate`, or neither. + * + * The number of divisions will be + * + * 1. `divisions`, if `divisions` > 0; or + * 2. `this.getLength / stepRate`, if `stepRate` > 0; or + * 3. `this.defaultDivisions` + * + * `1 + divisions` points will be returned. + * @param divisions The number of divisions to make. + * @param stepRate The curve distance between points, implying `divisions`. + * @param out An optional array to store the points in. + */ + getPoints(divisions?: integer, stepRate?: number, out?: O): O; + + /** + * Get a random point from the curve. + * @param out A point object to store the result in. + */ + getRandomPoint(out?: O): O; + + /** + * Get a sequence of equally spaced points (by arc distance) from the curve. + * + * `1 + divisions` points will be returned. + * @param divisions The number of divisions to make. Default this.defaultDivisions. + * @param stepRate Step between points. Used to calculate the number of points to return when divisions is falsy. Ignored if divisions is positive. + * @param out An optional array to store the points in. + */ + getSpacedPoints(divisions?: integer, stepRate?: number, out?: any[] | Phaser.Math.Vector2[]): Phaser.Math.Vector2[]; + + /** + * Get a point at the start of the curve. + * @param out A point to store the result in. + */ + getStartPoint(out?: O): O; + + /** + * Get a unit vector tangent at a relative position on the curve. + * In case any sub curve does not implement its tangent derivation, + * 2 points a small delta apart will be used to find its gradient + * which seems to give a reasonable approximation + * @param t The relative position on the curve, [0..1]. + * @param out A vector to store the result in. + */ + getTangent(t: number, out?: O): O; + + /** + * Get a unit vector tangent at a relative position on the curve, by arc length. + * @param u The relative position on the curve, [0..1]. + * @param out A vector to store the result in. + */ + getTangentAt(u: number, out?: O): O; + + /** + * [description] + * @param distance [description] + * @param divisions [description] + */ + getTFromDistance(distance: integer, divisions?: integer): number; + + /** + * [description] + * @param u [description] + * @param distance [description] + * @param divisions [description] + */ + getUtoTmapping(u: number, distance: integer, divisions?: integer): number; + + /** + * Calculate and cache the arc lengths. + */ + updateArcLengths(): void; + + } + + /** + * An Elliptical Curve derived from the Base Curve class. + * + * See https://en.wikipedia.org/wiki/Elliptic_curve for more details. + */ + class Ellipse extends Phaser.Curves.Curve { + /** + * + * @param x The x coordinate of the ellipse, or an Ellipse Curve configuration object. Default 0. + * @param y The y coordinate of the ellipse. Default 0. + * @param xRadius The horizontal radius of ellipse. Default 0. + * @param yRadius The vertical radius of ellipse. Default 0. + * @param startAngle The start angle of the ellipse, in degrees. Default 0. + * @param endAngle The end angle of the ellipse, in degrees. Default 360. + * @param clockwise Whether the ellipse angles are given as clockwise (`true`) or counter-clockwise (`false`). Default false. + * @param rotation The rotation of the ellipse, in degrees. Default 0. + */ + constructor(x?: number | Phaser.Types.Curves.EllipseCurveConfig, y?: number, xRadius?: number, yRadius?: number, startAngle?: integer, endAngle?: integer, clockwise?: boolean, rotation?: integer); + + /** + * The center point of the ellipse. Used for calculating rotation. + */ + p0: Phaser.Math.Vector2; + + /** + * Gets the starting point on the curve. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getStartPoint(out?: O): O; + + /** + * [description] + * @param divisions [description] + */ + getResolution(divisions: number): number; + + /** + * Get point at relative position in curve according to length. + * @param t The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPoint(t: number, out?: O): O; + + /** + * Sets the horizontal radius of this curve. + * @param value The horizontal radius of this curve. + */ + setXRadius(value: number): Phaser.Curves.Ellipse; + + /** + * Sets the vertical radius of this curve. + * @param value The vertical radius of this curve. + */ + setYRadius(value: number): Phaser.Curves.Ellipse; + + /** + * Sets the width of this curve. + * @param value The width of this curve. + */ + setWidth(value: number): Phaser.Curves.Ellipse; + + /** + * Sets the height of this curve. + * @param value The height of this curve. + */ + setHeight(value: number): Phaser.Curves.Ellipse; + + /** + * Sets the start angle of this curve. + * @param value The start angle of this curve, in radians. + */ + setStartAngle(value: number): Phaser.Curves.Ellipse; + + /** + * Sets the end angle of this curve. + * @param value The end angle of this curve, in radians. + */ + setEndAngle(value: number): Phaser.Curves.Ellipse; + + /** + * Sets if this curve extends clockwise or anti-clockwise. + * @param value The clockwise state of this curve. + */ + setClockwise(value: boolean): Phaser.Curves.Ellipse; + + /** + * Sets the rotation of this curve. + * @param value The rotation of this curve, in radians. + */ + setRotation(value: number): Phaser.Curves.Ellipse; + + /** + * The x coordinate of the center of the ellipse. + */ + x: number; + + /** + * The y coordinate of the center of the ellipse. + */ + y: number; + + /** + * The horizontal radius of the ellipse. + */ + xRadius: number; + + /** + * The vertical radius of the ellipse. + */ + yRadius: number; + + /** + * The start angle of the ellipse in degrees. + */ + startAngle: number; + + /** + * The end angle of the ellipse in degrees. + */ + endAngle: number; + + /** + * `true` if the ellipse rotation is clockwise or `false` if anti-clockwise. + */ + clockwise: boolean; + + /** + * The rotation of the ellipse, relative to the center, in degrees. + */ + angle: number; + + /** + * The rotation of the ellipse, relative to the center, in radians. + */ + rotation: number; + + /** + * JSON serialization of the curve. + */ + toJSON(): Phaser.Types.Curves.JSONEllipseCurve; + + /** + * Creates a curve from the provided Ellipse Curve Configuration object. + * @param data The JSON object containing this curve data. + */ + static fromJSON(data: Phaser.Types.Curves.JSONEllipseCurve): Phaser.Curves.Ellipse; + + } + + /** + * A LineCurve is a "curve" comprising exactly two points (a line segment). + */ + class Line extends Phaser.Curves.Curve { + /** + * + * @param p0 The first endpoint. + * @param p1 The second endpoint. + */ + constructor(p0: Phaser.Math.Vector2 | number[], p1?: Phaser.Math.Vector2); + + /** + * The first endpoint. + */ + p0: Phaser.Math.Vector2; + + /** + * The second endpoint. + */ + p1: Phaser.Math.Vector2; + + /** + * The quantity of arc length divisions within the curve. + */ + arcLengthDivisions: integer; + + /** + * Returns a Rectangle where the position and dimensions match the bounds of this Curve. + * @param out A Rectangle object to store the bounds in. If not given a new Rectangle will be created. + */ + getBounds(out?: O): O; + + /** + * Gets the starting point on the curve. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getStartPoint(out?: O): O; + + /** + * Gets the resolution of the line. + * @param divisions The number of divisions to consider. Default 1. + */ + getResolution(divisions?: number): number; + + /** + * Get point at relative position in curve according to length. + * @param t The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPoint(t: number, out?: O): O; + + /** + * Gets a point at a given position on the line. + * @param u The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPointAt(u: number, out?: O): O; + + /** + * Gets the slope of the line as a unit vector. + */ + getTangent(): O; + + /** + * [description] + * @param u [description] + * @param distance [description] + * @param divisions [description] + */ + getUtoTmapping(u: number, distance: integer, divisions?: integer): number; + + /** + * Draws this curve on the given Graphics object. + * + * The curve is drawn using `Graphics.lineBetween` so will be drawn at whatever the present Graphics line color is. + * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it. + * @param graphics The Graphics instance onto which this curve will be drawn. + */ + draw(graphics: G): G; + + /** + * Gets a JSON representation of the line. + */ + toJSON(): Phaser.Types.Curves.JSONCurve; + + /** + * Configures this line from a JSON representation. + * @param data The JSON object containing this curve data. + */ + static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.Line; + + } + + /** + * A MoveTo Curve is a very simple curve consisting of only a single point. Its intended use is to move the ending point in a Path. + */ + class MoveTo { + /** + * + * @param x `x` pixel coordinate. + * @param y `y` pixel coordinate. + */ + constructor(x?: number, y?: number); + + /** + * Denotes that this Curve does not influence the bounds, points, and drawing of its parent Path. Must be `false` or some methods in the parent Path will throw errors. + */ + active: boolean; + + /** + * The lone point which this curve consists of. + */ + p0: Phaser.Math.Vector2; + + /** + * Get point at relative position in curve according to length. + * @param t The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPoint(t: number, out?: O): O; + + /** + * Retrieves the point at given position in the curve. This will always return this curve's only point. + * @param u The position in the path to retrieve, between 0 and 1. Not used. + * @param out An optional vector in which to store the point. + */ + getPointAt(u: number, out?: O): O; + + /** + * Gets the resolution of this curve. + */ + getResolution(): number; + + /** + * Gets the length of this curve. + */ + getLength(): number; + + /** + * Converts this curve into a JSON-serializable object. + */ + toJSON(): Phaser.Types.Curves.JSONCurve; + + } + + /** + * A Path combines multiple Curves into one continuous compound curve. + * It does not matter how many Curves are in the Path or what type they are. + * + * A Curve in a Path does not have to start where the previous Curve ends - that is to say, a Path does not + * have to be an uninterrupted curve. Only the order of the Curves influences the actual points on the Path. + */ + class Path { + /** + * + * @param x The X coordinate of the Path's starting point or a {@link Phaser.Types.Curves.JSONPath}. Default 0. + * @param y The Y coordinate of the Path's starting point. Default 0. + */ + constructor(x?: number, y?: number); + + /** + * The name of this Path. + * Empty by default and never populated by Phaser, this is left for developers to use. + */ + name: string; + + /** + * The list of Curves which make up this Path. + */ + curves: Phaser.Curves.Curve[]; + + /** + * The cached length of each Curve in the Path. + * + * Used internally by {@link #getCurveLengths}. + */ + cacheLengths: number[]; + + /** + * Automatically closes the path. + */ + autoClose: boolean; + + /** + * The starting point of the Path. + * + * This is not necessarily equivalent to the starting point of the first Curve in the Path. In an empty Path, it's also treated as the ending point. + */ + startPoint: Phaser.Math.Vector2; + + /** + * Appends a Curve to the end of the Path. + * + * The Curve does not have to start where the Path ends or, for an empty Path, at its defined starting point. + * @param curve The Curve to append. + */ + add(curve: Phaser.Curves.Curve): Phaser.Curves.Path; + + /** + * Creates a circular Ellipse Curve positioned at the end of the Path. + * @param radius The radius of the circle. + * @param clockwise `true` to create a clockwise circle as opposed to a counter-clockwise circle. Default false. + * @param rotation The rotation of the circle in degrees. Default 0. + */ + circleTo(radius: number, clockwise?: boolean, rotation?: number): Phaser.Curves.Path; + + /** + * Ensures that the Path is closed. + * + * A closed Path starts and ends at the same point. If the Path is not closed, a straight Line Curve will be created from the ending point directly to the starting point. During the check, the actual starting point of the Path, i.e. the starting point of the first Curve, will be used as opposed to the Path's defined {@link startPoint}, which could differ. + * + * Calling this method on an empty Path will result in an error. + */ + closePath(): Phaser.Curves.Path; + + /** + * Creates a cubic bezier curve starting at the previous end point and ending at p3, using p1 and p2 as control points. + * @param x The x coordinate of the end point. Or, if a Vector2, the p1 value. + * @param y The y coordinate of the end point. Or, if a Vector2, the p2 value. + * @param control1X The x coordinate of the first control point. Or, if a Vector2, the p3 value. + * @param control1Y The y coordinate of the first control point. Not used if Vector2s are provided as the first 3 arguments. + * @param control2X The x coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. + * @param control2Y The y coordinate of the second control point. Not used if Vector2s are provided as the first 3 arguments. + */ + cubicBezierTo(x: number | Phaser.Math.Vector2, y: number | Phaser.Math.Vector2, control1X: number | Phaser.Math.Vector2, control1Y?: number, control2X?: number, control2Y?: number): Phaser.Curves.Path; + + /** + * Creates a Quadratic Bezier Curve starting at the ending point of the Path. + * @param x The X coordinate of the second control point or, if it's a `Vector2`, the first control point. + * @param y The Y coordinate of the second control point or, if `x` is a `Vector2`, the second control point. + * @param controlX If `x` is not a `Vector2`, the X coordinate of the first control point. + * @param controlY If `x` is not a `Vector2`, the Y coordinate of the first control point. + */ + quadraticBezierTo(x: number | Phaser.Math.Vector2[], y?: number, controlX?: number, controlY?: number): Phaser.Curves.Path; + + /** + * Draws all Curves in the Path to a Graphics Game Object. + * @param graphics The Graphics Game Object to draw to. + * @param pointsTotal The number of points to draw for each Curve. Higher numbers result in a smoother curve but require more processing. Default 32. + */ + draw(graphics: Phaser.GameObjects.Graphics, pointsTotal?: integer): G; + + /** + * Creates an ellipse curve positioned at the previous end point, using the given parameters. + * @param xRadius The horizontal radius of ellipse. Default 0. + * @param yRadius The vertical radius of ellipse. Default 0. + * @param startAngle The start angle of the ellipse, in degrees. Default 0. + * @param endAngle The end angle of the ellipse, in degrees. Default 360. + * @param clockwise Whether the ellipse angles are given as clockwise (`true`) or counter-clockwise (`false`). Default false. + * @param rotation The rotation of the ellipse, in degrees. Default 0. + */ + ellipseTo(xRadius?: number, yRadius?: number, startAngle?: integer, endAngle?: integer, clockwise?: boolean, rotation?: number): Phaser.Curves.Path; + + /** + * Creates a Path from a Path Configuration object. + * + * The provided object should be a {@link Phaser.Types.Curves.JSONPath}, as returned by {@link #toJSON}. Providing a malformed object may cause errors. + * @param data The JSON object containing the Path data. + */ + fromJSON(data: Phaser.Types.Curves.JSONPath): Phaser.Curves.Path; + + /** + * Returns a Rectangle with a position and size matching the bounds of this Path. + * @param out The Rectangle to store the bounds in. + * @param accuracy The accuracy of the bounds calculations. Higher values are more accurate at the cost of calculation speed. Default 16. + */ + getBounds(out?: O, accuracy?: integer): O; + + /** + * Returns an array containing the length of the Path at the end of each Curve. + * + * The result of this method will be cached to avoid recalculating it in subsequent calls. The cache is only invalidated when the {@link #curves} array changes in length, leading to potential inaccuracies if a Curve in the Path is changed, or if a Curve is removed and another is added in its place. + */ + getCurveLengths(): number[]; + + /** + * Returns the ending point of the Path. + * + * A Path's ending point is equivalent to the ending point of the last Curve in the Path. For an empty Path, the ending point is at the Path's defined {@link #startPoint}. + * @param out The object to store the point in. + */ + getEndPoint(out?: O): O; + + /** + * Returns the total length of the Path. + */ + getLength(): number; + + /** + * Calculates the coordinates of the point at the given normalized location (between 0 and 1) on the Path. + * + * The location is relative to the entire Path, not to an individual Curve. A location of 0.5 is always in the middle of the Path and is thus an equal distance away from both its starting and ending points. In a Path with one Curve, it would be in the middle of the Curve; in a Path with two Curves, it could be anywhere on either one of them depending on their lengths. + * @param t The location of the point to return, between 0 and 1. + * @param out The object in which to store the calculated point. + */ + getPoint(t: number, out?: O): O; + + /** + * Get a sequence of points on the path. + * @param divisions The number of divisions per resolution per curve. Default 12. + */ + getPoints(divisions?: integer): Phaser.Math.Vector2[]; + + /** + * Returns a randomly chosen point anywhere on the path. This follows the same rules as `getPoint` in that it may return a point on any Curve inside this path. + * + * When calling this method multiple times, the points are not guaranteed to be equally spaced spatially. + * @param out `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. + */ + getRandomPoint(out?: O): O; + + /** + * Divides this Path into a set of equally spaced points, + * + * The resulting points are equally spaced with respect to the points' position on the path, but not necessarily equally spaced spatially. + * @param divisions The amount of points to divide this Path into. Default 40. + */ + getSpacedPoints(divisions?: integer): Phaser.Math.Vector2[]; + + /** + * Returns the starting point of the Path. + * @param out `Vector2` instance that should be used for storing the result. If `undefined` a new `Vector2` will be created. + */ + getStartPoint(out?: O): O; + + /** + * Creates a line curve from the previous end point to x/y. + * @param x The X coordinate of the line's end point, or a `Vector2` containing the entire end point. + * @param y The Y coordinate of the line's end point, if a number was passed as the X parameter. + */ + lineTo(x: number | Phaser.Math.Vector2, y?: number): Phaser.Curves.Path; + + /** + * Creates a spline curve starting at the previous end point, using the given points on the curve. + * @param points The points the newly created spline curve should consist of. + */ + splineTo(points: Phaser.Math.Vector2[]): Phaser.Curves.Path; + + /** + * Creates a "gap" in this path from the path's current end point to the given coordinates. + * + * After calling this function, this Path's end point will be equal to the given coordinates + * @param x The X coordinate of the position to move the path's end point to, or a `Vector2` containing the entire new end point. + * @param y The Y coordinate of the position to move the path's end point to, if a number was passed as the X coordinate. + */ + moveTo(x: number | Phaser.Math.Vector2, y: number): Phaser.Curves.Path; + + /** + * Converts this Path to a JSON object containing the path information and its constituent curves. + */ + toJSON(): Phaser.Types.Curves.JSONPath; + + /** + * cacheLengths must be recalculated. + */ + updateArcLengths(): void; + + /** + * Disposes of this Path, clearing its internal references to objects so they can be garbage-collected. + */ + destroy(): void; + + } + + /** + * [description] + */ + class QuadraticBezier extends Phaser.Curves.Curve { + /** + * + * @param p0 Start point, or an array of point pairs. + * @param p1 Control Point 1. + * @param p2 Control Point 2. + */ + constructor(p0: Phaser.Math.Vector2 | number[], p1: Phaser.Math.Vector2, p2: Phaser.Math.Vector2); + + /** + * [description] + */ + p0: Phaser.Math.Vector2; + + /** + * [description] + */ + p1: Phaser.Math.Vector2; + + /** + * [description] + */ + p2: Phaser.Math.Vector2; + + /** + * Gets the starting point on the curve. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getStartPoint(out?: O): O; + + /** + * [description] + * @param divisions [description] + */ + getResolution(divisions: number): number; + + /** + * Get point at relative position in curve according to length. + * @param t The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPoint(t: number, out?: O): O; + + /** + * [description] + * @param graphics `Graphics` object to draw onto. + * @param pointsTotal Number of points to be used for drawing the curve. Higher numbers result in smoother curve but require more processing. Default 32. + */ + draw(graphics: G, pointsTotal?: integer): G; + + /** + * Converts the curve into a JSON compatible object. + */ + toJSON(): Phaser.Types.Curves.JSONCurve; + + /** + * Creates a curve from a JSON object, e. g. created by `toJSON`. + * @param data The JSON object containing this curve data. + */ + static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.QuadraticBezier; + + } + + /** + * Create a smooth 2d spline curve from a series of points. + */ + class Spline extends Phaser.Curves.Curve { + /** + * + * @param points The points that configure the curve. + */ + constructor(points?: Phaser.Math.Vector2[] | number[] | number[][]); + + /** + * The Vector2 points that configure the curve. + */ + points: Phaser.Math.Vector2[]; + + /** + * Add a list of points to the current list of Vector2 points of the curve. + * @param points The points that configure the curve. + */ + addPoints(points: Phaser.Math.Vector2[] | number[] | number[][]): Phaser.Curves.Spline; + + /** + * Add a point to the current list of Vector2 points of the curve. + * @param x The x coordinate of this curve + * @param y The y coordinate of this curve + */ + addPoint(x: number, y: number): Phaser.Math.Vector2; + + /** + * Gets the starting point on the curve. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getStartPoint(out?: O): O; + + /** + * [description] + * @param divisions [description] + */ + getResolution(divisions: number): number; + + /** + * Get point at relative position in curve according to length. + * @param t The position along the curve to return. Where 0 is the start and 1 is the end. + * @param out A Vector2 object to store the result in. If not given will be created. + */ + getPoint(t: number, out?: O): O; + + /** + * Exports a JSON object containing this curve data. + */ + toJSON(): Phaser.Types.Curves.JSONCurve; + + /** + * Imports a JSON object containing this curve data. + * @param data The JSON object containing this curve data. + */ + static fromJSON(data: Phaser.Types.Curves.JSONCurve): Phaser.Curves.Spline; + + } + + } + + namespace Data { + /** + * The Data Manager Component features a means to store pieces of data specific to a Game Object, System or Plugin. + * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, + * or have a property called `events` that is an instance of it. + */ + class DataManager { + /** + * + * @param parent The object that this DataManager belongs to. + * @param eventEmitter The DataManager's event emitter. + */ + constructor(parent: object, eventEmitter: Phaser.Events.EventEmitter); + + /** + * The object that this DataManager belongs to. + */ + parent: any; + + /** + * The DataManager's event emitter. + */ + events: Phaser.Events.EventEmitter; + + /** + * The data list. + */ + list: {[key: string]: any}; + + /** + * The public values list. You can use this to access anything you have stored + * in this Data Manager. For example, if you set a value called `gold` you can + * access it via: + * + * ```javascript + * this.data.values.gold; + * ``` + * + * You can also modify it directly: + * + * ```javascript + * this.data.values.gold += 1000; + * ``` + * + * Doing so will emit a `setdata` event from the parent of this Data Manager. + * + * Do not modify this object directly. Adding properties directly to this object will not + * emit any events. Always use `DataManager.set` to create new items the first time around. + */ + values: {[key: string]: any}; + + /** + * Retrieves the value for the given key, or undefined if it doesn't exist. + * + * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: + * + * ```javascript + * this.data.get('gold'); + * ``` + * + * Or access the value directly: + * + * ```javascript + * this.data.values.gold; + * ``` + * + * You can also pass in an array of keys, in which case an array of values will be returned: + * + * ```javascript + * this.data.get([ 'gold', 'armor', 'health' ]); + * ``` + * + * This approach is useful for destructuring arrays in ES6. + * @param key The key of the value to retrieve, or an array of keys. + */ + get(key: string | string[]): any; + + /** + * Retrieves all data values in a new object. + */ + getAll(): {[key: string]: any}; + + /** + * Queries the DataManager for the values of keys matching the given regular expression. + * @param search A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). + */ + query(search: RegExp): {[key: string]: any}; + + /** + * Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created. + * + * ```javascript + * data.set('name', 'Red Gem Stone'); + * ``` + * + * You can also pass in an object of key value pairs as the first argument: + * + * ```javascript + * data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); + * ``` + * + * To get a value back again you can call `get`: + * + * ```javascript + * data.get('gold'); + * ``` + * + * Or you can access the value directly via the `values` property, where it works like any other variable: + * + * ```javascript + * data.values.gold += 50; + * ``` + * + * When the value is first set, a `setdata` event is emitted. + * + * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. + * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. + * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. + * + * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * @param key The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored. + * @param data The value to set for the given key. If an object is provided as the key this argument is ignored. + */ + set(key: string | object, data: any): Phaser.Data.DataManager; + + /** + * Passes all data entries to the given callback. + * @param callback The function to call. + * @param context Value to use as `this` when executing callback. + * @param args Additional arguments that will be passed to the callback, after the game object, key, and data. + */ + each(callback: DataEachCallback, context?: any, ...args: any[]): Phaser.Data.DataManager; + + /** + * Merge the given object of key value pairs into this DataManager. + * + * Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument) + * will emit a `changedata` event. + * @param data The data to merge. + * @param overwrite Whether to overwrite existing data. Defaults to true. Default true. + */ + merge(data: {[key: string]: any}, overwrite?: boolean): Phaser.Data.DataManager; + + /** + * Remove the value for the given key. + * + * If the key is found in this Data Manager it is removed from the internal lists and a + * `removedata` event is emitted. + * + * You can also pass in an array of keys, in which case all keys in the array will be removed: + * + * ```javascript + * this.data.remove([ 'gold', 'armor', 'health' ]); + * ``` + * @param key The key to remove, or an array of keys to remove. + */ + remove(key: string | string[]): Phaser.Data.DataManager; + + /** + * Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it. + * @param key The key of the value to retrieve and delete. + */ + pop(key: string): any; + + /** + * Determines whether the given key is set in this Data Manager. + * + * Please note that the keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * @param key The key to check. + */ + has(key: string): boolean; + + /** + * Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts + * to create new values or update existing ones. + * @param value Whether to freeze or unfreeze the Data Manager. + */ + setFreeze(value: boolean): Phaser.Data.DataManager; + + /** + * Delete all data in this Data Manager and unfreeze it. + */ + reset(): Phaser.Data.DataManager; + + /** + * Destroy this data manager. + */ + destroy(): void; + + /** + * Gets or sets the frozen state of this Data Manager. + * A frozen Data Manager will block all attempts to create new values or update existing ones. + */ + freeze: boolean; + + /** + * Return the total number of entries in this Data Manager. + */ + count: integer; + + } + + /** + * The Data Component features a means to store pieces of data specific to a Game Object, System or Plugin. + * You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, + * or have a property called `events` that is an instance of it. + */ + class DataManagerPlugin extends Phaser.Data.DataManager { + /** + * + * @param scene A reference to the Scene that this DataManager belongs to. + */ + constructor(scene: Phaser.Scene); + + /** + * A reference to the Scene that this DataManager belongs to. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene's Systems. + */ + systems: Phaser.Scenes.Systems; + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + */ + destroy(): void; + + } + + namespace Events { + /** + * The Change Data Event. + * + * This event is dispatched by a Data Manager when an item in the data store is changed. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * a change data event from a Game Object you would use: `sprite.data.on('changedata', listener)`. + * + * This event is dispatched for all items that change in the Data Manager. + * To listen for the change of a specific item, use the `CHANGE_DATA_KEY_EVENT` event. + */ + const CHANGE_DATA: any; + + /** + * The Change Data Key Event. + * + * This event is dispatched by a Data Manager when an item in the data store is changed. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the change of a specific data item from a Game Object you would use: `sprite.data.on('changedata-key', listener)`, + * where `key` is the unique string key of the data item. For example, if you have a data item stored called `gold` + * then you can listen for `sprite.data.on('changedata-gold')`. + */ + const CHANGE_DATA_KEY: any; + + /** + * The Remove Data Event. + * + * This event is dispatched by a Data Manager when an item is removed from it. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the removal of a data item on a Game Object you would use: `sprite.data.on('removedata', listener)`. + */ + const REMOVE_DATA: any; + + /** + * The Set Data Event. + * + * This event is dispatched by a Data Manager when a new item is added to the data store. + * + * Game Objects with data enabled have an instance of a Data Manager under the `data` property. So, to listen for + * the addition of a new data item on a Game Object you would use: `sprite.data.on('setdata', listener)`. + */ + const SET_DATA: any; + + } + + } + + namespace Device { + /** + * Determines the audio playback capabilities of the device 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.audio` from within any Scene. + */ + type Audio = { + /** + * Can this device play HTML Audio tags? + */ + audioData: boolean; + /** + * Can this device play EC-3 Dolby Digital Plus files? + */ + dolby: boolean; + /** + * Can this device can play m4a files. + */ + m4a: boolean; + /** + * Can this device play mp3 files? + */ + mp3: boolean; + /** + * Can this device play ogg files? + */ + ogg: boolean; + /** + * Can this device play opus files? + */ + opus: boolean; + /** + * Can this device play wav files? + */ + wav: boolean; + /** + * Does this device have the Web Audio API? + */ + webAudio: boolean; + /** + * Can this device play webm files? + */ + webm: boolean; + }; + + /** + * 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. + */ + type Browser = { + /** + * Set to true if running in Chrome. + */ + chrome: boolean; + /** + * Set to true if running in Microsoft Edge browser. + */ + edge: boolean; + /** + * Set to true if running in Firefox. + */ + firefox: boolean; + /** + * Set to true if running in Internet Explorer 11 or less (not Edge). + */ + ie: boolean; + /** + * Set to true if running in Mobile Safari. + */ + mobileSafari: boolean; + /** + * Set to true if running in Opera. + */ + opera: boolean; + /** + * Set to true if running in Safari. + */ + safari: boolean; + /** + * Set to true if running in the Silk browser (as used on the Amazon Kindle) + */ + silk: boolean; + /** + * Set to true if running a Trident version of Internet Explorer (IE11+) + */ + trident: boolean; + /** + * If running in Chrome this will contain the major version number. + */ + chromeVersion: number; + /** + * If running in Firefox this will contain the major version number. + */ + firefoxVersion: number; + /** + * If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Browser.trident and Browser.tridentVersion. + */ + ieVersion: number; + /** + * If running in Safari this will contain the major version number. + */ + safariVersion: number; + /** + * 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} + */ + tridentVersion: number; + }; + + /** + * Determines the canvas features of the browser 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.canvasFeatures` from within any Scene. + */ + type CanvasFeatures = { + /** + * Set to true if the browser supports inversed alpha. + */ + supportInverseAlpha: boolean; + /** + * Set to true if the browser supports new canvas blend modes. + */ + supportNewBlendModes: boolean; + }; + + /** + * Determines the features of the browser 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.features` from within any Scene. + */ + type Features = { + /** + * True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + */ + canvasBitBltShift: boolean; + /** + * Is canvas available? + */ + canvas: boolean; + /** + * Is file available? + */ + file: boolean; + /** + * Is fileSystem available? + */ + fileSystem: boolean; + /** + * Does the device support the getUserMedia API? + */ + getUserMedia: boolean; + /** + * Is the device big or little endian? (only detected if the browser supports TypedArrays) + */ + littleEndian: boolean; + /** + * Is localStorage available? + */ + localStorage: boolean; + /** + * Is Pointer Lock available? + */ + pointerLock: boolean; + /** + * Does the device context support 32bit pixel manipulation using array buffer views? + */ + support32bit: boolean; + /** + * Does the device support the Vibration API? + */ + vibration: boolean; + /** + * Is webGL available? + */ + webGL: boolean; + /** + * Is worker available? + */ + worker: boolean; + }; + + /** + * Determines the full screen support of the browser 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.fullscreen` from within any Scene. + */ + type Fullscreen = { + /** + * Does the browser support the Full Screen API? + */ + available: boolean; + /** + * Does the browser support access to the Keyboard during Full Screen mode? + */ + keyboard: boolean; + /** + * If the browser supports the Full Screen API this holds the call you need to use to cancel it. + */ + cancel: string; + /** + * If the browser supports the Full Screen API this holds the call you need to use to activate it. + */ + request: string; + }; + + /** + * Determines the input support of the browser 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.input` from within any Scene. + */ + type Input = { + /** + * The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + */ + wheelType: string; + /** + * Is navigator.getGamepads available? + */ + gamepads: boolean; + /** + * Is mspointer available? + */ + mspointer: boolean; + /** + * Is touch available? + */ + touch: boolean; + }; + + /** + * Determines the operating system of the device 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.os` from within any Scene. + */ + type OS = { + /** + * Is running on android? + */ + android: boolean; + /** + * Is running on chromeOS? + */ + chromeOS: boolean; + /** + * Is the game running under Apache Cordova? + */ + cordova: boolean; + /** + * Is the game running under the Intel Crosswalk XDK? + */ + crosswalk: boolean; + /** + * Is running on a desktop? + */ + desktop: boolean; + /** + * Is the game running under Ejecta? + */ + ejecta: boolean; + /** + * Is the game running under GitHub Electron? + */ + electron: boolean; + /** + * Is running on iOS? + */ + iOS: boolean; + /** + * Is running on iPad? + */ + iPad: boolean; + /** + * Is running on iPhone? + */ + iPhone: boolean; + /** + * Is running on an Amazon Kindle? + */ + kindle: boolean; + /** + * Is running on linux? + */ + linux: boolean; + /** + * Is running on macOS? + */ + macOS: boolean; + /** + * Is the game running under Node.js? + */ + node: boolean; + /** + * Is the game running under Node-Webkit? + */ + nodeWebkit: boolean; + /** + * Set to true if running as a WebApp, i.e. within a WebView + */ + webApp: boolean; + /** + * Is running on windows? + */ + windows: boolean; + /** + * Is running on a Windows Phone? + */ + windowsPhone: boolean; + /** + * If running in iOS this will contain the major version number. + */ + iOSVersion: number; + /** + * PixelRatio of the host device? + */ + pixelRatio: number; + }; + + /** + * Determines the video support of the browser 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.video` from within any Scene. + * + * In Phaser 3.20 the properties were renamed to drop the 'Video' suffix. + */ + type Video = { + /** + * Can this device play h264 mp4 video files? + */ + h264: boolean; + /** + * Can this device play hls video files? + */ + hls: boolean; + /** + * Can this device play h264 mp4 video files? + */ + mp4: boolean; + /** + * Can this device play ogg video files? + */ + ogg: boolean; + /** + * Can this device play vp9 video files? + */ + vp9: boolean; + /** + * Can this device play webm video files? + */ + webm: boolean; + }; + + } + + type DeviceConf = { + /** + * The OS Device functions. + */ + os: Phaser.Device.OS; + /** + * The Browser Device functions. + */ + browser: Phaser.Device.Browser; + /** + * The Features Device functions. + */ + features: Phaser.Device.Features; + /** + * The Input Device functions. + */ + input: Phaser.Device.Input; + /** + * The Audio Device functions. + */ + audio: Phaser.Device.Audio; + /** + * The Video Device functions. + */ + video: Phaser.Device.Video; + /** + * The Fullscreen Device functions. + */ + fullscreen: Phaser.Device.Fullscreen; + /** + * The Canvas Device functions. + */ + canvasFeatures: Phaser.Device.CanvasFeatures; + }; + + namespace Display { + namespace Align { + /** + * A constant representing a top-left alignment or position. + */ + const TOP_LEFT: integer; + + /** + * A constant representing a top-center alignment or position. + */ + const TOP_CENTER: integer; + + /** + * A constant representing a top-right alignment or position. + */ + const TOP_RIGHT: integer; + + /** + * A constant representing a left-top alignment or position. + */ + const LEFT_TOP: integer; + + /** + * A constant representing a left-center alignment or position. + */ + const LEFT_CENTER: integer; + + /** + * A constant representing a left-bottom alignment or position. + */ + const LEFT_BOTTOM: integer; + + /** + * A constant representing a center alignment or position. + */ + const CENTER: integer; + + /** + * A constant representing a right-top alignment or position. + */ + const RIGHT_TOP: integer; + + /** + * A constant representing a right-center alignment or position. + */ + const RIGHT_CENTER: integer; + + /** + * A constant representing a right-bottom alignment or position. + */ + const RIGHT_BOTTOM: integer; + + /** + * A constant representing a bottom-left alignment or position. + */ + const BOTTOM_LEFT: integer; + + /** + * A constant representing a bottom-center alignment or position. + */ + const BOTTOM_CENTER: integer; + + /** + * A constant representing a bottom-right alignment or position. + */ + const BOTTOM_RIGHT: integer; + + namespace In { + /** + * Takes given Game Object and aligns it so that it is positioned in the bottom center of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function BottomCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the bottom left of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function BottomLeft(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the bottom right of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function BottomRight(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the center of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function Center(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the left center of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function LeftCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned relative to the other. + * The alignment used is based on the `position` argument, which is an `ALIGN_CONST` value, such as `LEFT_CENTER` or `TOP_RIGHT`. + * @param child The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param position The position to align the Game Object with. This is an align constant, such as `ALIGN_CONST.LEFT_CENTER`. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function QuickSet(child: G, alignIn: Phaser.GameObjects.GameObject, position: integer, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the right center of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function RightCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the top center of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function TopCenter(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the top left of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function TopLeft(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned in the top right of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignIn The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function TopRight(gameObject: G, alignIn: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + } + + namespace To { + /** + * Takes given Game Object and aligns it so that it is positioned next to the bottom center position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function BottomCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the bottom left position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function BottomLeft(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the bottom right position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function BottomRight(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the left bottom position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function LeftBottom(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the left center position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function LeftCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the left top position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function LeftTop(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * 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`. + * @param child The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param position The position to align the Game Object with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function QuickSet(child: G, alignTo: Phaser.GameObjects.GameObject, position: integer, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the right bottom position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function RightBottom(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the right center position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function RightCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the right top position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function RightTop(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the top center position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function TopCenter(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the top left position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function TopLeft(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + /** + * Takes given Game Object and aligns it so that it is positioned next to the top right position of the other. + * @param gameObject The Game Object that will be positioned. + * @param alignTo The Game Object to base the alignment position on. + * @param offsetX Optional horizontal offset from the position. Default 0. + * @param offsetY Optional vertical offset from the position. Default 0. + */ + function TopRight(gameObject: G, alignTo: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number): G; + + } + + } + + namespace Bounds { + /** + * Positions the Game Object so that it is centered on the given coordinates. + * @param gameObject The Game Object that will be re-positioned. + * @param x The horizontal coordinate to position the Game Object on. + * @param y The vertical coordinate to position the Game Object on. + */ + function CenterOn(gameObject: G, x: number, y: number): G; + + /** + * Returns the bottom coordinate from the bounds of the Game Object. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetBottom(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the center x coordinate from the bounds of the Game Object. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetCenterX(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the center y coordinate from the bounds of the Game Object. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetCenterY(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the left coordinate from the bounds of the Game Object. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetLeft(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * origin.x`. + * This value will only be > 0 if `origin.x` is not equal to zero. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetOffsetX(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the amount the Game Object is visually offset from its y coordinate. + * This is the same as `width * origin.y`. + * This value will only be > 0 if `origin.y` is not equal to zero. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetOffsetY(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the right coordinate from the bounds of the Game Object. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetRight(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Returns the top coordinate from the bounds of the Game Object. + * @param gameObject The Game Object to get the bounds value from. + */ + function GetTop(gameObject: Phaser.GameObjects.GameObject): number; + + /** + * Positions the Game Object so that the bottom of its bounds aligns with the given coordinate. + * @param gameObject The Game Object that will be re-positioned. + * @param value The coordinate to position the Game Object bounds on. + */ + function SetBottom(gameObject: G, value: number): G; + + /** + * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. + * @param gameObject The Game Object that will be re-positioned. + * @param x The coordinate to position the Game Object bounds on. + */ + function SetCenterX(gameObject: G, x: number): G; + + /** + * Positions the Game Object so that the center top of its bounds aligns with the given coordinate. + * @param gameObject The Game Object that will be re-positioned. + * @param y The coordinate to position the Game Object bounds on. + */ + function SetCenterY(gameObject: G, y: number): G; + + /** + * Positions the Game Object so that the left of its bounds aligns with the given coordinate. + * @param gameObject The Game Object that will be re-positioned. + * @param value The coordinate to position the Game Object bounds on. + */ + function SetLeft(gameObject: G, value: number): G; + + /** + * Positions the Game Object so that the left of its bounds aligns with the given coordinate. + * @param gameObject The Game Object that will be re-positioned. + * @param value The coordinate to position the Game Object bounds on. + */ + function SetRight(gameObject: G, value: number): G; + + /** + * Positions the Game Object so that the top of its bounds aligns with the given coordinate. + * @param gameObject The Game Object that will be re-positioned. + * @param value The coordinate to position the Game Object bounds on. + */ + function SetTop(gameObject: G, value: number): G; + + } + + namespace Canvas { + namespace CanvasInterpolation { + /** + * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit). + * @param canvas The canvas object to have the style set on. + */ + function setCrisp(canvas: HTMLCanvasElement): HTMLCanvasElement; + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * @param canvas The canvas object to have the style set on. + */ + function setBicubic(canvas: HTMLCanvasElement): HTMLCanvasElement; + + } + + /** + * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. + * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, + * which is useless for some of the Phaser pipelines / renderer. + * + * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. + * Which means all instances of Phaser Games on the same page can share the one single pool. + */ + namespace CanvasPool { + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * @param parent The parent of the Canvas object. + * @param width The width of the Canvas. Default 1. + * @param height The height of the Canvas. Default 1. + * @param canvasType The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. Default Phaser.CANVAS. + * @param selfParent Use the generated Canvas element as the parent? Default false. + */ + function create(parent: any, width?: integer, height?: integer, canvasType?: integer, selfParent?: boolean): HTMLCanvasElement; + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * @param parent The parent of the Canvas object. + * @param width The width of the Canvas. Default 1. + * @param height The height of the Canvas. Default 1. + */ + function create2D(parent: any, width?: integer, height?: integer): HTMLCanvasElement; + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * @param parent The parent of the Canvas object. + * @param width The width of the Canvas. Default 1. + * @param height The height of the Canvas. Default 1. + */ + function createWebGL(parent: any, width?: integer, height?: integer): HTMLCanvasElement; + + /** + * Gets the first free canvas index from the pool. + * @param canvasType The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. Default Phaser.CANVAS. + */ + function first(canvasType?: integer): HTMLCanvasElement; + + /** + * 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. + * @param parent The canvas or the parent of the canvas to free. + */ + function remove(parent: any): void; + + /** + * Gets the total number of used canvas elements in the pool. + */ + function total(): integer; + + /** + * Gets the total number of free canvas elements in the pool. + */ + function free(): integer; + + /** + * Disable context smoothing on any new Canvas element created. + */ + function disableSmoothing(): void; + + /** + * Enable context smoothing on any new Canvas element created. + */ + function enableSmoothing(): void; + + } + + namespace Smoothing { + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * @param context The canvas context to check. + */ + function getPrefix(context: CanvasRenderingContext2D | WebGLRenderingContext): string; + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * @param context The context on which to enable smoothing. + */ + function enable(context: CanvasRenderingContext2D | WebGLRenderingContext): CanvasRenderingContext2D | WebGLRenderingContext; + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * @param context The context on which to disable smoothing. + */ + function disable(context: CanvasRenderingContext2D | WebGLRenderingContext): CanvasRenderingContext2D | WebGLRenderingContext; + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * Returns null if no smoothing prefix is available. + * @param context The context to check. + */ + function isEnabled(context: CanvasRenderingContext2D | WebGLRenderingContext): boolean; + + } + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * @param canvas The canvas element to have the style applied to. + * @param value The touch action value to set on the canvas. Set to `none` to disable touch actions. Default 'none'. + */ + function TouchAction(canvas: HTMLCanvasElement, value?: string): HTMLCanvasElement; + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * @param canvas The canvas element to have the style applied to. + * @param value The touch callout value to set on the canvas. Set to `none` to disable touch callouts. Default 'none'. + */ + function UserSelect(canvas: HTMLCanvasElement, value?: string): HTMLCanvasElement; + + } + + namespace Color { + namespace Interpolate { + /** + * Interpolates between the two given color ranges over the length supplied. + * @param r1 Red value. + * @param g1 Blue value. + * @param b1 Green value. + * @param r2 Red value. + * @param g2 Blue value. + * @param b2 Green value. + * @param length Distance to interpolate over. Default 100. + * @param index Index to start from. Default 0. + */ + function RGBWithRGB(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number, length?: number, index?: number): Phaser.Types.Display.ColorObject; + + /** + * Interpolates between the two given color objects over the length supplied. + * @param color1 The first Color object. + * @param color2 The second Color object. + * @param length Distance to interpolate over. Default 100. + * @param index Index to start from. Default 0. + */ + function ColorWithColor(color1: Phaser.Display.Color, color2: Phaser.Display.Color, length?: number, index?: number): Phaser.Types.Display.ColorObject; + + /** + * Interpolates between the Color object and color values over the length supplied. + * @param color1 The first Color object. + * @param r Red value. + * @param g Blue value. + * @param b Green value. + * @param length Distance to interpolate over. Default 100. + * @param index Index to start from. Default 0. + */ + function ColorWithRGB(color1: Phaser.Display.Color, r: number, g: number, b: number, length?: number, index?: number): Phaser.Types.Display.ColorObject; + + } + + } + + /** + * The Color class holds a single color value and allows for easy modification and reading of it. + */ + class Color { + /** + * + * @param red The red color value. A number between 0 and 255. Default 0. + * @param green The green color value. A number between 0 and 255. Default 0. + * @param blue The blue color value. A number between 0 and 255. Default 0. + * @param alpha The alpha value. A number between 0 and 255. Default 255. + */ + constructor(red?: integer, green?: integer, blue?: integer, alpha?: integer); + + /** + * An array containing the calculated color values for WebGL use. + */ + gl: number[]; + + /** + * Sets this color to be transparent. Sets all values to zero. + */ + transparent(): Phaser.Display.Color; + + /** + * Sets the color of this Color component. + * @param red The red color value. A number between 0 and 255. + * @param green The green color value. A number between 0 and 255. + * @param blue The blue color value. A number between 0 and 255. + * @param alpha The alpha value. A number between 0 and 255. Default 255. + * @param updateHSV Update the HSV values after setting the RGB values? Default true. + */ + setTo(red: integer, green: integer, blue: integer, alpha?: integer, updateHSV?: boolean): Phaser.Display.Color; + + /** + * Sets the red, green, blue and alpha GL values of this Color component. + * @param red The red color value. A number between 0 and 1. + * @param green The green color value. A number between 0 and 1. + * @param blue The blue color value. A number between 0 and 1. + * @param alpha The alpha value. A number between 0 and 1. Default 1. + */ + setGLTo(red: number, green: number, blue: number, alpha?: number): Phaser.Display.Color; + + /** + * Sets the color based on the color object given. + * @param color An object containing `r`, `g`, `b` and optionally `a` values in the range 0 to 255. + */ + setFromRGB(color: Phaser.Types.Display.InputColorObject): Phaser.Display.Color; + + /** + * Sets the color based on the hue, saturation and lightness values given. + * @param h The hue, in the range 0 - 1. This is the base color. + * @param 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 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. + */ + setFromHSV(h: number, s: number, v: number): Phaser.Display.Color; + + /** + * Returns a new Color component using the values from this one. + */ + clone(): Phaser.Display.Color; + + /** + * Sets this Color object to be grayscaled based on the shade value given. + * @param shade A value between 0 and 255. + */ + gray(shade: integer): Phaser.Display.Color; + + /** + * Sets this Color object to be a random color between the `min` and `max` values given. + * @param min The minimum random color value. Between 0 and 255. Default 0. + * @param max The maximum random color value. Between 0 and 255. Default 255. + */ + random(min?: integer, max?: integer): Phaser.Display.Color; + + /** + * Sets this Color object to be a random grayscale color between the `min` and `max` values given. + * @param min The minimum random color value. Between 0 and 255. Default 0. + * @param max The maximum random color value. Between 0 and 255. Default 255. + */ + randomGray(min?: integer, max?: integer): Phaser.Display.Color; + + /** + * Increase the saturation of this Color by the percentage amount given. + * The saturation is the amount of the base color in the hue. + * @param amount The percentage amount to change this color by. A value between 0 and 100. + */ + saturate(amount: integer): Phaser.Display.Color; + + /** + * Decrease the saturation of this Color by the percentage amount given. + * The saturation is the amount of the base color in the hue. + * @param amount The percentage amount to change this color by. A value between 0 and 100. + */ + desaturate(amount: integer): Phaser.Display.Color; + + /** + * Increase the lightness of this Color by the percentage amount given. + * @param amount The percentage amount to change this color by. A value between 0 and 100. + */ + lighten(amount: integer): Phaser.Display.Color; + + /** + * Decrease the lightness of this Color by the percentage amount given. + * @param amount The percentage amount to change this color by. A value between 0 and 100. + */ + darken(amount: integer): Phaser.Display.Color; + + /** + * Brighten this Color by the percentage amount given. + * @param amount The percentage amount to change this color by. A value between 0 and 100. + */ + brighten(amount: integer): Phaser.Display.Color; + + /** + * The color of this Color component, not including the alpha channel. + */ + readonly color: number; + + /** + * The color of this Color component, including the alpha channel. + */ + readonly color32: number; + + /** + * The color of this Color component as a string which can be used in CSS color values. + */ + readonly rgba: string; + + /** + * The red color value, normalized to the range 0 to 1. + */ + redGL: number; + + /** + * The green color value, normalized to the range 0 to 1. + */ + greenGL: number; + + /** + * The blue color value, normalized to the range 0 to 1. + */ + blueGL: number; + + /** + * The alpha color value, normalized to the range 0 to 1. + */ + alphaGL: number; + + /** + * The red color value, normalized to the range 0 to 255. + */ + red: number; + + /** + * The green color value, normalized to the range 0 to 255. + */ + green: number; + + /** + * The blue color value, normalized to the range 0 to 255. + */ + blue: number; + + /** + * The alpha color value, normalized to the range 0 to 255. + */ + alpha: number; + + /** + * The hue color value. A number between 0 and 1. + * This is the base color. + */ + h: number; + + /** + * The saturation color value. A number between 0 and 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. + */ + s: number; + + /** + * The lightness color value. A number between 0 and 1. + * This controls how dark the color is. Where 1 is as bright as possible and 0 is black. + */ + v: number; + + /** + * Converts the given color value into an Object containing r,g,b and a properties. + * @param color A color value, optionally including the alpha value. + */ + static ColorToRGBA(color: number): Phaser.Types.Display.ColorObject; + + /** + * Returns a string containing a hex representation of the given color component. + * @param color The color channel to get the hex value for, must be a value between 0 and 255. + */ + static ComponentToHex(color: integer): string; + + /** + * Given 3 separate color values this will return an integer representation of it. + * @param red The red color value. A number between 0 and 255. + * @param green The green color value. A number between 0 and 255. + * @param blue The blue color value. A number between 0 and 255. + */ + static GetColor(red: integer, green: integer, blue: integer): number; + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * @param red The red color value. A number between 0 and 255. + * @param green The green color value. A number between 0 and 255. + * @param blue The blue color value. A number between 0 and 255. + * @param alpha The alpha color value. A number between 0 and 255. + */ + static GetColor32(red: integer, green: integer, blue: integer, alpha: integer): number; + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * @param hex The hex color value to convert, such as `#0033ff` or the short-hand format: `#03f`. + */ + static HexStringToColor(hex: string): Phaser.Display.Color; + + /** + * Converts HSL (hue, saturation and lightness) values to a Phaser Color object. + * @param h The hue value in the range 0 to 1. + * @param s The saturation value in the range 0 to 1. + * @param l The lightness value in the range 0 to 1. + */ + static HSLToColor(h: number, s: number, l: number): Phaser.Display.Color; + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * @param s The saturation, in the range 0 - 1. Default 1. + * @param v The value, in the range 0 - 1. Default 1. + */ + static HSVColorWheel(s?: number, v?: number): Phaser.Types.Display.ColorObject[]; + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion formula from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * @param h The hue, in the range 0 - 1. This is the base color. + * @param 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 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. + * @param out A Color object to store the results in. If not given a new ColorObject will be created. + */ + static HSVToRGB(h: number, s: number, v: number, out?: Phaser.Types.Display.ColorObject | Phaser.Display.Color): Phaser.Types.Display.ColorObject | Phaser.Display.Color; + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + */ + static HueToComponent(p: number, q: number, t: number): number; + + /** + * Converts the given color value into an instance of a Color object. + * @param input The color value to convert into a Color object. + */ + static IntegerToColor(input: integer): Phaser.Display.Color; + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exists in the given color (0xAARRGGBB) + * @param input The color value to convert into a Color object. + */ + static IntegerToRGB(input: integer): Phaser.Types.Display.ColorObject; + + /** + * Converts an object containing `r`, `g`, `b` and `a` properties into a Color class instance. + * @param input An object containing `r`, `g`, `b` and `a` properties in the range 0 to 255. + */ + static ObjectToColor(input: Phaser.Types.Display.InputColorObject): Phaser.Display.Color; + + /** + * 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. + * @param min The minimum value to set the random range from (between 0 and 255) Default 0. + * @param max The maximum value to set the random range from (between 0 and 255) Default 255. + */ + static RandomRGB(min?: integer, max?: integer): Phaser.Display.Color; + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * @param rgb The CSS format color string, using the `rgb` or `rgba` format. + */ + static RGBStringToColor(rgb: string): Phaser.Display.Color; + + /** + * 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) + * @param r The red color value. A number between 0 and 255. + * @param g The green color value. A number between 0 and 255. + * @param b The blue color value. A number between 0 and 255. + * @param out An object to store the color values in. If not given an HSV Color Object will be created. + */ + static RGBToHSV(r: integer, g: integer, b: integer, out?: Phaser.Types.Display.HSVColorObject | Phaser.Display.Color): Phaser.Types.Display.HSVColorObject | Phaser.Display.Color; + + /** + * Converts the color values into an HTML compatible color string, prefixed with either `#` or `0x`. + * @param r The red color value. A number between 0 and 255. + * @param g The green color value. A number between 0 and 255. + * @param b The blue color value. A number between 0 and 255. + * @param a The alpha value. A number between 0 and 255. Default 255. + * @param prefix The prefix of the string. Either `#` or `0x`. Default #. + */ + static RGBToString(r: integer, g: integer, b: integer, a?: integer, prefix?: string): string; + + /** + * Converts the given source color value into an instance of a Color class. + * The value can be either a string, prefixed with `rgb` or a hex string, a number or an Object. + * @param input The source color value to convert. + */ + static ValueToColor(input: string | number | Phaser.Types.Display.InputColorObject): Phaser.Display.Color; + + } + + namespace Masks { + /** + * A Bitmap Mask combines the alpha (opacity) of a masked pixel with the alpha of another pixel. + * Unlike the Geometry Mask, which is a clipping path, a Bitmap Mask behaves like an alpha mask, + * not a clipping path. It is only available when using the WebGL Renderer. + * + * A Bitmap Mask can use any Game Object to determine the alpha of each pixel of the masked Game Object(s). + * For any given point of a masked Game Object's texture, the pixel's alpha will be multiplied by the alpha + * of the pixel at the same position in the Bitmap Mask's Game Object. The color of the pixel from the + * Bitmap Mask doesn't matter. + * + * For example, if a pure blue pixel with an alpha of 0.95 is masked with a pure red pixel with an + * alpha of 0.5, the resulting pixel will be pure blue with an alpha of 0.475. Naturally, this means + * that a pixel in the mask with an alpha of 0 will hide the corresponding pixel in all masked Game Objects + * A pixel with an alpha of 1 in the masked Game Object will receive the same alpha as the + * corresponding pixel in the mask. + * + * The Bitmap Mask's location matches the location of its Game Object, not the location of the + * masked objects. Moving or transforming the underlying Game Object will change the mask + * (and affect the visibility of any masked objects), whereas moving or transforming a masked object + * will not affect the mask. + * + * The Bitmap Mask will not render its Game Object by itself. If the Game Object is not in a + * Scene's display list, it will only be used for the mask and its full texture will not be directly + * visible. Adding the underlying Game Object to a Scene will not cause any problems - it will + * render as a normal Game Object and will also serve as a mask. + */ + class BitmapMask { + /** + * + * @param scene The Scene which this Bitmap Mask will be used in. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + constructor(scene: Phaser.Scene, renderable: Phaser.GameObjects.GameObject); + + /** + * A reference to either the Canvas or WebGL Renderer that this Mask is using. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * A renderable Game Object that uses a texture, such as a Sprite. + */ + bitmapMask: Phaser.GameObjects.GameObject; + + /** + * The texture used for the mask's framebuffer. + */ + maskTexture: WebGLTexture; + + /** + * The texture used for the main framebuffer. + */ + mainTexture: WebGLTexture; + + /** + * Whether the Bitmap Mask is dirty and needs to be updated. + */ + dirty: boolean; + + /** + * The framebuffer to which a masked Game Object is rendered. + */ + mainFramebuffer: WebGLFramebuffer; + + /** + * The framebuffer to which the Bitmap Mask's masking Game Object is rendered. + */ + maskFramebuffer: WebGLFramebuffer; + + /** + * The previous framebuffer set in the renderer before this one was enabled. + */ + prevFramebuffer: WebGLFramebuffer; + + /** + * Whether to invert the masks alpha. + * + * If `true`, the alpha of the masking pixel will be inverted before it's multiplied with the masked pixel. Essentially, this means that a masked area will be visible only if the corresponding area in the mask is invisible. + */ + invertAlpha: boolean; + + /** + * Is this mask a stencil mask? + */ + readonly isStencil: boolean; + + /** + * Sets a new masking Game Object for the Bitmap Mask. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + setBitmap(renderable: Phaser.GameObjects.GameObject): void; + + /** + * Prepares the WebGL Renderer to render a Game Object with this mask applied. + * + * This renders the masking Game Object to the mask framebuffer and switches to the main framebuffer so that the masked Game Object will be rendered to it instead of being rendered directly to the frame. + * @param renderer The WebGL Renderer to prepare. + * @param maskedObject The masked Game Object which will be drawn. + * @param camera The Camera to render to. + */ + preRenderWebGL(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer, maskedObject: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * Finalizes rendering of a masked Game Object. + * + * This resets the previously bound framebuffer and switches the WebGL Renderer to the Bitmap Mask Pipeline, which uses a special fragment shader to apply the masking effect. + * @param renderer The WebGL Renderer to clean up. + */ + postRenderWebGL(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; + + /** + * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. + * @param renderer The Canvas Renderer which would be rendered to. + * @param mask The masked Game Object which would be rendered. + * @param camera The Camera to render to. + */ + preRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer, mask: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * This is a NOOP method. Bitmap Masks are not supported by the Canvas Renderer. + * @param renderer The Canvas Renderer which would be rendered to. + */ + postRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; + + /** + * Destroys this BitmapMask and nulls any references it holds. + * + * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, + * so be sure to call `clearMask` on any Game Object using it, before destroying it. + */ + destroy(): void; + + } + + /** + * A Geometry Mask can be applied to a Game Object to hide any pixels of it which don't intersect + * a visible pixel from the geometry mask. The mask is essentially a clipping path which can only + * make a masked pixel fully visible or fully invisible without changing its alpha (opacity). + * + * A Geometry Mask uses a Graphics Game Object to determine which pixels of the masked Game Object(s) + * should be clipped. For any given point of a masked Game Object's texture, the pixel will only be displayed + * if the Graphics Game Object of the Geometry Mask has a visible pixel at the same position. The color and + * alpha of the pixel from the Geometry Mask do not matter. + * + * The Geometry Mask's location matches the location of its Graphics object, not the location of the masked objects. + * Moving or transforming the underlying Graphics object will change the mask (and affect the visibility + * of any masked objects), whereas moving or transforming a masked object will not affect the mask. + * You can think of the Geometry Mask (or rather, of its Graphics object) as an invisible curtain placed + * in front of all masked objects which has its own visual properties and, naturally, respects the camera's + * visual properties, but isn't affected by and doesn't follow the masked objects by itself. + */ + class GeometryMask { + /** + * + * @param scene This parameter is not used. + * @param graphicsGeometry The Graphics Game Object to use for the Geometry Mask. Doesn't have to be in the Display List. + */ + constructor(scene: Phaser.Scene, graphicsGeometry: Phaser.GameObjects.Graphics); + + /** + * The Graphics object which describes the Geometry Mask. + */ + geometryMask: Phaser.GameObjects.Graphics; + + /** + * Similar to the BitmapMasks invertAlpha setting this to true will then hide all pixels + * drawn to the Geometry Mask. + */ + invertAlpha: boolean; + + /** + * Is this mask a stencil mask? + */ + readonly isStencil: boolean; + + /** + * Sets a new Graphics object for the Geometry Mask. + * @param graphicsGeometry The Graphics object which will be used for the Geometry Mask. + */ + setShape(graphicsGeometry: Phaser.GameObjects.Graphics): this; + + /** + * Sets the `invertAlpha` property of this Geometry Mask. + * Inverting the alpha essentially flips the way the mask works. + * @param value Invert the alpha of this mask? Default true. + */ + setInvertAlpha(value?: boolean): this; + + /** + * Renders the Geometry Mask's underlying Graphics object to the OpenGL stencil buffer and enables the stencil test, which clips rendered pixels according to the mask. + * @param renderer The WebGL Renderer instance to draw to. + * @param child The Game Object being rendered. + * @param camera The camera the Game Object is being rendered through. + */ + preRenderWebGL(renderer: Phaser.Renderer.WebGL.WebGLRenderer, child: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * Applies the current stencil mask to the renderer. + * @param renderer The WebGL Renderer instance to draw to. + * @param camera The camera the Game Object is being rendered through. + * @param inc Is this an INCR stencil or a DECR stencil? + */ + applyStencil(renderer: Phaser.Renderer.WebGL.WebGLRenderer, camera: Phaser.Cameras.Scene2D.Camera, inc: boolean): void; + + /** + * Flushes all rendered pixels and disables the stencil test of a WebGL context, thus disabling the mask for it. + * @param renderer The WebGL Renderer instance to draw flush. + */ + postRenderWebGL(renderer: Phaser.Renderer.WebGL.WebGLRenderer): void; + + /** + * Sets the clipping path of a 2D canvas context to the Geometry Mask's underlying Graphics object. + * @param renderer The Canvas Renderer instance to set the clipping path on. + * @param mask The Game Object being rendered. + * @param camera The camera the Game Object is being rendered through. + */ + preRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer, mask: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * Restore the canvas context's previous clipping path, thus turning off the mask for it. + * @param renderer The Canvas Renderer instance being restored. + */ + postRenderCanvas(renderer: Phaser.Renderer.Canvas.CanvasRenderer): void; + + /** + * Destroys this GeometryMask and nulls any references it holds. + * + * Note that if a Game Object is currently using this mask it will _not_ automatically detect you have destroyed it, + * so be sure to call `clearMask` on any Game Object using it, before destroying it. + */ + destroy(): void; + + } + + } + + /** + * A BaseShader is a small resource class that contains the data required for a WebGL Shader to be created. + * + * It contains the raw source code to the fragment and vertex shader, as well as an object that defines + * the uniforms the shader requires, if any. + * + * BaseShaders are stored in the Shader Cache, available in a Scene via `this.cache.shaders` and are referenced + * by a unique key-based string. Retrieve them via `this.cache.shaders.get(key)`. + * + * BaseShaders are created automatically by the GLSL File Loader when loading an external shader resource. + * They can also be created at runtime, allowing you to use dynamically generated shader source code. + * + * Default fragment and vertex source is used if not provided in the constructor, setting-up a basic shader, + * suitable for debug rendering. + */ + class BaseShader { + /** + * + * @param key The key of this shader. Must be unique within the shader cache. + * @param fragmentSrc The fragment source for the shader. + * @param vertexSrc The vertex source for the shader. + * @param uniforms Optional object defining the uniforms the shader uses. + */ + constructor(key: string, fragmentSrc?: string, vertexSrc?: string, uniforms?: any); + + /** + * The key of this shader, unique within the shader cache of this Phaser game instance. + */ + key: string; + + /** + * The source code, as a string, of the fragment shader being used. + */ + fragmentSrc: string; + + /** + * The source code, as a string, of the vertex shader being used. + */ + vertexSrc: string; + + /** + * The default uniforms for this shader. + */ + uniforms: any; + + } + + } + + namespace DOM { + /** + * Adds the given element to the DOM. If a parent is provided the element is added as a child of the parent, providing it was able to access it. + * If no parent was given it falls back to using `document.body`. + * @param element The element to be added to the DOM. Usually a Canvas object. + * @param parent The parent in which to add the element. Can be a string which is passed to `getElementById` or an actual DOM object. + */ + function AddToDOM(element: HTMLElement, parent?: string | HTMLElement): HTMLElement; + + /** + * Inspects the readyState of the document. If the document is already complete then it invokes the given callback. + * If not complete it sets up several event listeners such as `deviceready`, and once those fire, it invokes the callback. + * Called automatically by the Phaser.Game instance. Should not usually be accessed directly. + * @param callback The callback to be invoked when the device is ready and the DOM content is loaded. + */ + function DOMContentLoaded(callback: ContentLoadedCallback): void; + + /** + * Attempts to determine the document inner height across iOS and standard devices. + * Based on code by @tylerjpeterson + * @param iOS Is this running on iOS? + */ + function GetInnerHeight(iOS: boolean): number; + + /** + * Attempts to determine the screen orientation using the Orientation API. + * @param width The width of the viewport. + * @param height The height of the viewport. + */ + function GetScreenOrientation(width: number, height: number): string; + + /** + * 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. + * @param element The DOM element to look-up. + */ + function GetTarget(element: HTMLElement): void; + + /** + * Takes the given data string and parses it as XML. + * First tries to use the window.DOMParser and reverts to the Microsoft.XMLDOM if that fails. + * The parsed XML object is returned, or `null` if there was an error while parsing the data. + * @param data The XML source stored in a string. + */ + function ParseXML(data: string): DOMParser | ActiveXObject; + + /** + * Attempts to remove the element from its parentNode in the DOM. + * @param element The DOM element to remove from its parent node. + */ + function RemoveFromDOM(element: HTMLElement): void; + + /** + * Abstracts away the use of RAF or setTimeOut for the core game update loop. + * This is invoked automatically by the Phaser.Game instance. + */ + class RequestAnimationFrame { + /** + * True if RequestAnimationFrame is running, otherwise false. + */ + isRunning: boolean; + + /** + * The callback to be invoked each step. + */ + callback: FrameRequestCallback; + + /** + * The most recent timestamp. Either a DOMHighResTimeStamp under RAF or `Date.now` under SetTimeout. + */ + tick: number; + + /** + * True if the step is using setTimeout instead of RAF. + */ + isSetTimeOut: boolean; + + /** + * The setTimeout or RAF callback ID used when canceling them. + */ + timeOutID: number; + + /** + * The previous time the step was called. + */ + lastTime: number; + + /** + * The target FPS rate in ms. + * Only used when setTimeout is used instead of RAF. + */ + target: number; + + /** + * The RAF step function. + * Updates the local tick value, invokes the callback and schedules another call to requestAnimationFrame. + */ + step: FrameRequestCallback; + + /** + * The SetTimeout step function. + * Updates the local tick value, invokes the callback and schedules another call to setTimeout. + */ + stepTimeout: Function; + + /** + * Starts the requestAnimationFrame or setTimeout process running. + * @param callback The callback to invoke each step. + * @param forceSetTimeOut Should it use SetTimeout, even if RAF is available? + * @param targetFPS The target fps rate (in ms). Only used when setTimeout is used. + */ + start(callback: FrameRequestCallback, forceSetTimeOut: boolean, targetFPS: number): void; + + /** + * Stops the requestAnimationFrame or setTimeout from running. + */ + stop(): void; + + /** + * Stops the step from running and clears the callback reference. + */ + destroy(): void; + + } + + } + + namespace Events { + /** + * EventEmitter is a Scene Systems plugin compatible version of eventemitter3. + */ + class EventEmitter { + /** + * Removes all listeners. + */ + shutdown(): void; + + /** + * Removes all listeners. + */ + destroy(): void; + + /** + * Return an array listing the events for which the emitter has registered listeners. + */ + eventNames(): (string|symbol)[]; + + /** + * Return the listeners registered for a given event. + * @param event The event name. + */ + listeners(event: string | symbol): Function[]; + + /** + * Return the number of listeners listening to a given event. + * @param event The event name. + */ + listenerCount(event: string | symbol): number; + + /** + * Calls each of the listeners registered for a given event. + * @param event The event name. + * @param args Additional arguments that will be passed to the event handler. + */ + emit(event: string | symbol, ...args: any[]): boolean; + + /** + * Add a listener for a given event. + * @param event The event name. + * @param fn The listener function. + * @param context The context to invoke the listener with. Default this. + */ + on(event: string | symbol, fn: Function, context?: any): this; + + /** + * Add a listener for a given event. + * @param event The event name. + * @param fn The listener function. + * @param context The context to invoke the listener with. Default this. + */ + addListener(event: string | symbol, fn: Function, context?: any): this; + + /** + * Add a one-time listener for a given event. + * @param event The event name. + * @param fn The listener function. + * @param context The context to invoke the listener with. Default this. + */ + once(event: string | symbol, fn: Function, context?: any): this; + + /** + * Remove the listeners of a given event. + * @param event The event name. + * @param fn Only remove the listeners that match this function. + * @param context Only remove the listeners that have this context. + * @param once Only remove one-time listeners. + */ + removeListener(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + + /** + * Remove the listeners of a given event. + * @param event The event name. + * @param fn Only remove the listeners that match this function. + * @param context Only remove the listeners that have this context. + * @param once Only remove one-time listeners. + */ + off(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + + /** + * Remove all listeners, or those of the specified event. + * @param event The event name. + */ + removeAllListeners(event?: string | symbol): this; + + } + + } + + /** + * Phaser Blend Modes to CSS Blend Modes Map. + */ + enum CSSBlendModes { + } + + namespace GameObjects { + /** + * 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. + * + * 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): 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 + */ + class DynamicBitmapText extends Phaser.GameObjects.BitmapText { + /** + * + * @param scene The Scene to which this Game Object belongs. It can only belong to one Scene at any given time. + * @param x The x coordinate of this Game Object in world space. + * @param y The y coordinate of this Game Object in world space. + * @param font The key of the font to use from the Bitmap Font cache. + * @param text The string, or array of strings, to be set as the content of this Bitmap Text. + * @param size The font size of this Bitmap Text. + * @param align The alignment of the text in a multi-line BitmapText object. Default 0. + */ + constructor(scene: Phaser.Scene, x: number, y: number, font: string, text?: string | string[], size?: number, align?: integer); + + /** + * The horizontal scroll position of the Bitmap Text. + */ + scrollX: number; + + /** + * The vertical scroll position of the Bitmap Text. + */ + scrollY: number; + + /** + * The crop width of the Bitmap Text. + */ + cropWidth: number; + + /** + * The crop height of the Bitmap Text. + */ + cropHeight: number; + + /** + * A callback that alters how each character of the Bitmap Text is rendered. + */ + displayCallback: Phaser.Types.GameObjects.BitmapText.DisplayCallback; + + /** + * The data object that is populated during rendering, then passed to the displayCallback. + * You should modify this object then return it back from the callback. It's updated values + * will be used to render the specific glyph. + * + * Please note that if you need a reference to this object locally in your game code then you + * should shallow copy it, as it's updated and re-used for every glyph in the text. + */ + callbackData: Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig; + + /** + * Set the crop size of this Bitmap Text. + * @param width The width of the crop. + * @param height The height of the crop. + */ + setSize(width: number, height: number): Phaser.GameObjects.DynamicBitmapText; + + /** + * Set a callback that alters how each character of the Bitmap Text is rendered. + * + * The callback receives a {@link Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} object that contains information about the character that's + * about to be rendered. + * + * It should return an object with `x`, `y`, `scale` and `rotation` properties that will be used instead of the + * usual values when rendering. + * @param callback The display callback to set. + */ + setDisplayCallback(callback: Phaser.Types.GameObjects.BitmapText.DisplayCallback): Phaser.GameObjects.DynamicBitmapText; + + /** + * Set the horizontal scroll position of this Bitmap Text. + * @param value The horizontal scroll position to set. + */ + setScrollX(value: number): Phaser.GameObjects.DynamicBitmapText; + + /** + * Set the vertical scroll position of this Bitmap Text. + * @param value The vertical scroll position to set. + */ + setScrollY(value: number): Phaser.GameObjects.DynamicBitmapText; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + namespace RetroFont { + /** + * Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ + */ + var TEXT_SET1: string; + + /** + * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ + */ + var TEXT_SET2: string; + + /** + * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 + */ + var TEXT_SET3: string; + + /** + * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 + */ + var TEXT_SET4: string; + + /** + * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 + */ + var TEXT_SET5: string; + + /** + * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' + */ + var TEXT_SET6: string; + + /** + * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 + */ + var TEXT_SET7: string; + + /** + * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ + */ + var TEXT_SET8: string; + + /** + * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! + */ + var TEXT_SET9: string; + + /** + * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ + */ + var TEXT_SET10: string; + + /** + * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 + */ + var TEXT_SET11: string; + + /** + * Parses a Retro Font configuration object so you can pass it to the BitmapText constructor + * and create a BitmapText object using a fixed-width retro font. + * @param scene A reference to the Phaser Scene. + * @param config The font configuration object. + */ + function Parse(scene: Phaser.Scene, config: Phaser.Types.GameObjects.BitmapText.RetroFontConfig): object; + + } + + /** + * 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} + * Littera (Web-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 implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. It can only belong to one Scene at any given time. + * @param x The x coordinate of this Game Object in world space. + * @param y The y coordinate of this Game Object in world space. + * @param font The key of the font to use from the Bitmap Font cache. + * @param text The string, or array of strings, to be set as the content of this Bitmap Text. + * @param size The font size of this Bitmap Text. + * @param align The alignment of the text in a multi-line BitmapText object. Default 0. + */ + constructor(scene: Phaser.Scene, x: number, y: number, font: string, text?: string | string[], size?: number, align?: integer); + + /** + * The key of the Bitmap Font used by this Bitmap Text. + * To change the font after creation please use `setFont`. + */ + readonly font: string; + + /** + * The data of the Bitmap Font used by this Bitmap Text. + */ + readonly fontData: Phaser.Types.GameObjects.BitmapText.BitmapFontData; + + /** + * The character code used to detect for word wrapping. + * Defaults to 32 (a space character). + */ + wordWrapCharCode: number; + + /** + * Set the lines of text in this BitmapText to be left-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + */ + setLeftAlign(): this; + + /** + * Set the lines of text in this BitmapText to be center-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + */ + setCenterAlign(): this; + + /** + * Set the lines of text in this BitmapText to be right-aligned. + * This only has any effect if this BitmapText contains more than one line of text. + */ + setRightAlign(): this; + + /** + * Set the font size of this Bitmap Text. + * @param size The font size to set. + */ + setFontSize(size: number): this; + + /** + * Sets the letter spacing between each character of this Bitmap Text. + * Can be a positive value to increase the space, or negative to reduce it. + * Spacing is applied after the kerning values have been set. + * @param spacing The amount of horizontal space to add between each character. Default 0. + */ + setLetterSpacing(spacing?: number): this; + + /** + * Set the textual content of this BitmapText. + * + * An array of strings will be converted into multi-line text. Use the align methods to change multi-line alignment. + * @param value The string, or array of strings, to be set as the content of this BitmapText. + */ + setText(value: string | string[]): this; + + /** + * 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. + * @param round Whether to round the results to the nearest integer. + */ + getTextBounds(round?: boolean): Phaser.Types.GameObjects.BitmapText.BitmapTextSize; + + /** + * Changes the font this BitmapText is using to render. + * + * The new texture is loaded and applied to the BitmapText. The existing test, size and alignment are preserved, + * unless overridden via the arguments. + * @param font The key of the font to use from the Bitmap Font cache. + * @param size The font size of this Bitmap Text. If not specified the current size will be used. + * @param align The alignment of the text in a multi-line BitmapText object. If not specified the current alignment will be used. Default 0. + */ + setFont(font: string, size?: number, align?: integer): this; + + /** + * 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. + * @param value The maximum display width of this BitmapText in pixels. Set to zero to disable. + * @param wordWrapCharCode The character code to check for when word wrapping. Defaults to 32 (the space character). + */ + setMaxWidth(value: number, wordWrapCharCode?: number): this; + + /** + * 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. + */ + align: integer; + + /** + * The text that this Bitmap Text object displays. + * + * You can also use the method `setText` if you want a chainable way to change the text content. + */ + text: string; + + /** + * The font size of this Bitmap Text. + * + * You can also use the method `setFontSize` if you want a chainable way to change the font size. + */ + fontSize: number; + + /** + * Adds / Removes spacing between characters. + * + * Can be a negative or positive number. + * + * You can also use the method `setLetterSpacing` if you want a chainable way to change the letter spacing. + */ + letterSpacing: number; + + /** + * 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. + */ + maxWidth: number; + + /** + * The width of this Bitmap Text. + */ + readonly width: number; + + /** + * The height of this bitmap text. + */ + readonly height: number; + + /** + * Build a JSON representation of this Bitmap Text. + */ + toJSON(): Phaser.Types.GameObjects.BitmapText.JSONBitmapText; + + /** + * Left align the text characters in a multi-line BitmapText object. + */ + static ALIGN_LEFT: integer; + + /** + * Center align the text characters in a multi-line BitmapText object. + */ + static ALIGN_CENTER: integer; + + /** + * Right align the text characters in a multi-line BitmapText object. + */ + static ALIGN_RIGHT: integer; + + /** + * Parse an XML Bitmap Font from an Atlas. + * + * Adds the parsed Bitmap Font data to the cache with the `fontName` key. + * @param scene The Scene to parse the Bitmap Font for. + * @param fontName The key of the font to add to the Bitmap Font cache. + * @param textureKey The key of the BitmapFont's texture. + * @param frameKey The key of the BitmapFont texture's frame. + * @param xmlKey The key of the XML data of the font to parse. + * @param xSpacing The x-axis spacing to add between each letter. + * @param ySpacing The y-axis spacing to add to the line height. + */ + static ParseFromAtlas(scene: Phaser.Scene, fontName: string, textureKey: string, frameKey: string, xmlKey: string, xSpacing?: integer, ySpacing?: integer): boolean; + + /** + * Parse an XML font to Bitmap Font data for the Bitmap Font cache. + * @param xml The XML Document to parse the font from. + * @param xSpacing The x-axis spacing to add between each letter. Default 0. + * @param ySpacing The y-axis spacing to add to the line height. Default 0. + * @param frame The texture frame to take into account while parsing. + */ + static ParseXMLBitmapFont(xml: XMLDocument, xSpacing?: integer, ySpacing?: integer, frame?: Phaser.Textures.Frame): Phaser.Types.GameObjects.BitmapText.BitmapFontData; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A Blitter Game Object. + * + * The Blitter Game Object is a special kind of container that creates, updates and manages Bob objects. + * Bobs are designed for rendering speed rather than flexibility. They consist of a texture, or frame from a texture, + * a position and an alpha value. You cannot scale or rotate them. They use a batched drawing method for speed + * during rendering. + * + * A Blitter Game Object has one texture bound to it. Bobs created by the Blitter can use any Frame from this + * Texture to render with, but they cannot use any other Texture. It is this single texture-bind that allows + * them their speed. + * + * If you have a need to blast a large volume of frames around the screen then Blitter objects are well worth + * investigating. They are especially useful for using as a base for your own special effects systems. + */ + class Blitter extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. It can only belong to one Scene at any given time. + * @param x The x coordinate of this Game Object in world space. Default 0. + * @param y The y coordinate of this Game Object in world space. Default 0. + * @param texture The key of the texture this Game Object will use for rendering. The Texture must already exist in the Texture Manager. Default '__DEFAULT'. + * @param frame The Frame of the Texture that this Game Object will use. Only set if the Texture has multiple frames, such as a Texture Atlas or Sprite Sheet. Default 0. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, texture?: string, frame?: string | integer); + + /** + * The children of this Blitter. + * This List contains all of the Bob objects created by the Blitter. + */ + children: Phaser.Structs.List; + + /** + * Is the Blitter considered dirty? + * A 'dirty' Blitter has had its child count changed since the last frame. + */ + dirty: boolean; + + /** + * Creates a new Bob in this Blitter. + * + * The Bob is created at the given coordinates, relative to the Blitter and uses the given frame. + * A Bob can use any frame belonging to the texture bound to the Blitter. + * @param x The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param y The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param frame The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. + * @param visible Should the created Bob render or not? Default true. + * @param index The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list. + */ + create(x: number, y: number, frame?: string | integer | Phaser.Textures.Frame, visible?: boolean, index?: integer): Phaser.GameObjects.Bob; + + /** + * Creates multiple Bob objects within this Blitter and then passes each of them to the specified callback. + * @param callback The callback to invoke after creating a bob. It will be sent two arguments: The Bob and the index of the Bob. + * @param quantity The quantity of Bob objects to create. + * @param frame The Frame the Bobs will use. It must be part of the Blitter Texture. + * @param visible Should the created Bob render or not? Default true. + */ + createFromCallback(callback: CreateCallback, quantity: integer, frame?: string | integer | Phaser.Textures.Frame | string[] | integer[] | Phaser.Textures.Frame[], visible?: boolean): Phaser.GameObjects.Bob[]; + + /** + * Creates multiple Bobs in one call. + * + * The amount created is controlled by a combination of the `quantity` argument and the number of frames provided. + * + * If the quantity is set to 10 and you provide 2 frames, then 20 Bobs will be created. 10 with the first + * frame and 10 with the second. + * @param quantity The quantity of Bob objects to create. + * @param frame The Frame the Bobs will use. It must be part of the Blitter Texture. + * @param visible Should the created Bob render or not? Default true. + */ + createMultiple(quantity: integer, frame?: string | integer | Phaser.Textures.Frame | string[] | integer[] | Phaser.Textures.Frame[], visible?: boolean): Phaser.GameObjects.Bob[]; + + /** + * Checks if the given child can render or not, by checking its `visible` and `alpha` values. + * @param child The Bob to check for rendering. + */ + childCanRender(child: Phaser.GameObjects.Bob): boolean; + + /** + * Returns an array of Bobs to be rendered. + * If the Blitter is dirty then a new list is generated and stored in `renderList`. + */ + getRenderList(): Phaser.GameObjects.Bob[]; + + /** + * Removes all Bobs from the children List and clears the dirty flag. + */ + clear(): void; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A Bob Game Object. + * + * A Bob belongs to a Blitter Game Object. The Blitter is responsible for managing and rendering this object. + * + * A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle + * the flipped and visible state of the Bob. The Frame the Bob uses to render can be changed dynamically, but it + * must be a Frame within the Texture used by the parent Blitter. + * + * Bob positions are relative to the Blitter parent. So if you move the Blitter parent, all Bob children will + * have their positions impacted by this change as well. + * + * You can manipulate Bob objects directly from your game code, but the creation and destruction of them should be + * handled via the Blitter parent. + */ + class Bob { + /** + * + * @param blitter The parent Blitter object is responsible for updating this Bob. + * @param x The horizontal position of this Game Object in the world, relative to the parent Blitter position. + * @param y The vertical position of this Game Object in the world, relative to the parent Blitter position. + * @param frame The Frame this Bob will render with, as defined in the Texture the parent Blitter is using. + * @param visible Should the Bob render visible or not to start with? + */ + constructor(blitter: Phaser.GameObjects.Blitter, x: number, y: number, frame: string | integer, visible: boolean); + + /** + * The Blitter object that this Bob belongs to. + */ + parent: Phaser.GameObjects.Blitter; + + /** + * The x position of this Bob, relative to the x position of the Blitter. + */ + x: number; + + /** + * The y position of this Bob, relative to the y position of the Blitter. + */ + y: number; + + /** + * The frame that the Bob uses to render with. + * To change the frame use the `Bob.setFrame` method. + */ + protected frame: Phaser.Textures.Frame; + + /** + * A blank object which can be used to store data related to this Bob in. + */ + data: object; + + /** + * The tint value of this Bob. + */ + tint: number; + + /** + * The horizontally flipped state of the Bob. + * A Bob that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Bob. + * A Bob that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture. + */ + flipY: boolean; + + /** + * Changes the Texture Frame being used by this Bob. + * The frame must be part of the Texture the parent Blitter is using. + * If no value is given it will use the default frame of the Blitter parent. + * @param frame The frame to be used during rendering. + */ + setFrame(frame?: string | integer | Phaser.Textures.Frame): Phaser.GameObjects.Bob; + + /** + * Resets the horizontal and vertical flipped state of this Bob back to their default un-flipped state. + */ + resetFlip(): Phaser.GameObjects.Bob; + + /** + * Resets this Bob. + * + * Changes the position to the values given, and optionally changes the frame. + * + * Also resets the flipX and flipY values, sets alpha back to 1 and visible to true. + * @param x The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param y The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param frame The Frame the Bob will use. It _must_ be part of the Texture the parent Blitter object is using. + */ + reset(x: number, y: number, frame?: string | integer | Phaser.Textures.Frame): Phaser.GameObjects.Bob; + + /** + * Changes the position of this Bob to the values given. + * @param x The x position of the Bob. Bob coordinate are relative to the position of the Blitter object. + * @param y The y position of the Bob. Bob coordinate are relative to the position of the Blitter object. + */ + setPosition(x: number, y: number): Phaser.GameObjects.Bob; + + /** + * Sets the horizontal flipped state of this Bob. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): Phaser.GameObjects.Bob; + + /** + * Sets the vertical flipped state of this Bob. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): Phaser.GameObjects.Bob; + + /** + * Sets the horizontal and vertical flipped state of this Bob. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): Phaser.GameObjects.Bob; + + /** + * Sets the visibility of this Bob. + * + * An invisible Bob will skip rendering. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): Phaser.GameObjects.Bob; + + /** + * Set the Alpha level of this Bob. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * A Bob with alpha 0 will skip rendering. + * @param value The alpha value used for this Bob. Between 0 and 1. + */ + setAlpha(value: number): Phaser.GameObjects.Bob; + + /** + * Sets the tint of this Bob. + * @param value The tint value used for this Bob. Between 0 and 0xffffff. + */ + setTint(value: number): Phaser.GameObjects.Bob; + + /** + * Destroys this Bob instance. + * Removes itself from the Blitter and clears the parent, frame and data properties. + */ + destroy(): void; + + /** + * The visible state of the Bob. + * + * An invisible Bob will skip rendering. + */ + visible: boolean; + + /** + * The alpha value of the Bob, between 0 and 1. + * + * A Bob with alpha 0 will skip rendering. + */ + alpha: number; + + } + + /** + * Builds a Game Object using the provided configuration object. + * @param scene A reference to the Scene. + * @param gameObject The initial GameObject. + * @param config The config to build the GameObject with. + */ + function BuildGameObject(scene: Phaser.Scene, gameObject: Phaser.GameObjects.GameObject, config: Phaser.Types.GameObjects.GameObjectConfig): Phaser.GameObjects.GameObject; + + /** + * Adds an Animation component to a Sprite and populates it based on the given config. + * @param sprite The sprite to add an Animation component to. + * @param config The animation config. + */ + function BuildGameObjectAnimation(sprite: Phaser.GameObjects.Sprite, config: object): Phaser.GameObjects.Sprite; + + namespace Components { + /** + * Provides methods used for setting the alpha properties of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Alpha { + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + } + + /** + * Provides methods used for setting the alpha property of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface AlphaSingle { + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + } + + interface Animation { + /** + * The Game Object to which this animation controller belongs. + */ + parent: Phaser.GameObjects.GameObject; + /** + * A reference to the global Animation Manager. + */ + animationManager: Phaser.Animations.AnimationManager; + /** + * Is an animation currently playing or not? + */ + isPlaying: boolean; + /** + * The current Animation loaded into this Animation Controller. + */ + currentAnim: Phaser.Animations.Animation; + /** + * The current AnimationFrame being displayed by this Animation Controller. + */ + currentFrame: Phaser.Animations.AnimationFrame; + /** + * The key of the next Animation to be loaded into this Animation Controller when the current animation completes. + */ + nextAnim: string; + /** + * The frame rate of playback in frames per second. + * The default is 24 if the `duration` property is `null`. + */ + frameRate: number; + /** + * How long the animation should play for, in milliseconds. + * If the `frameRate` property has been set then it overrides this value, + * otherwise the `frameRate` is derived from `duration`. + */ + duration: number; + /** + * ms per frame, not including frame specific modifiers that may be present in the Animation data. + */ + msPerFrame: number; + /** + * Skip frames if the time lags, or always advanced anyway? + */ + skipMissedFrames: boolean; + /** + * Will the playhead move forwards (`true`) or in reverse (`false`). + */ + forward: boolean; + /** + * Internal time overflow accumulator. + */ + accumulator: number; + /** + * The time point at which the next animation frame will change. + */ + nextTick: number; + /** + * An internal counter keeping track of how many repeats are left to play. + */ + repeatCounter: number; + /** + * An internal flag keeping track of pending repeats. + */ + pendingRepeat: boolean; + /** + * Sets an animation to be played immediately after the current one completes. + * + * The current animation must enter a 'completed' state for this to happen, i.e. finish all of its repeats, delays, etc, or have the `stop` method called directly on it. + * + * An animation set to repeat forever will never enter a completed state. + * + * You can chain a new animation at any point, including before the current one starts playing, during it, or when it ends (via its `animationcomplete` callback). + * Chained animations are specific to a Game Object, meaning different Game Objects can have different chained animations without impacting the global animation they're playing. + * + * Call this method with no arguments to reset the chained animation. + * @param key The string-based key of the animation to play next, as defined previously in the Animation Manager. Or an Animation instance. + */ + chain(key?: string | Phaser.Animations.Animation): Phaser.GameObjects.GameObject; + /** + * Sets the amount of time, in milliseconds, that the animation will be delayed before starting playback. + * @param value The amount of time, in milliseconds, to wait before starting playback. Default 0. + */ + setDelay(value?: integer): Phaser.GameObjects.GameObject; + /** + * Gets the amount of time, in milliseconds that the animation will be delayed before starting playback. + */ + getDelay(): integer; + /** + * Waits for the specified delay, in milliseconds, then starts playback of the requested animation. + * @param delay The delay, in milliseconds, to wait before starting the animation playing. + * @param key The key of the animation to play. + * @param startFrame The frame of the animation to start from. Default 0. + */ + delayedPlay(delay: integer, key: string, startFrame?: integer): Phaser.GameObjects.GameObject; + /** + * Returns the key of the animation currently loaded into this component. + */ + getCurrentKey(): string; + /** + * Internal method used to load an animation into this component. + * @param key The key of the animation to load. + * @param startFrame The start frame of the animation to load. Default 0. + */ + load(key: string, startFrame?: integer): Phaser.GameObjects.GameObject; + /** + * Pause the current animation and set the `isPlaying` property to `false`. + * You can optionally pause it at a specific frame. + * @param atFrame An optional frame to set after pausing the animation. + */ + pause(atFrame?: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; + /** + * Resumes playback of a paused animation and sets the `isPlaying` property to `true`. + * You can optionally tell it to start playback from a specific frame. + * @param fromFrame An optional frame to set before restarting playback. + */ + resume(fromFrame?: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; + /** + * `true` if the current animation is paused, otherwise `false`. + */ + readonly isPaused: boolean; + /** + * Plays an Animation on a Game Object that has the Animation component, such as a Sprite. + * + * Animations are stored in the global Animation Manager and are referenced by a unique string-based key. + * @param key The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. + * @param ignoreIfPlaying If this animation is already playing then ignore this call. Default false. + * @param startFrame Optionally start the animation playing from this frame index. Default 0. + */ + play(key: string | Phaser.Animations.Animation, ignoreIfPlaying?: boolean, startFrame?: integer): Phaser.GameObjects.GameObject; + /** + * Plays an Animation (in reverse mode) on the Game Object that owns this Animation Component. + * @param key The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. + * @param ignoreIfPlaying If an animation is already playing then ignore this call. Default false. + * @param startFrame Optionally start the animation playing from this frame index. Default 0. + */ + playReverse(key: string | Phaser.Animations.Animation, ignoreIfPlaying?: boolean, startFrame?: integer): Phaser.GameObjects.GameObject; + /** + * Load an Animation and fires 'onStartEvent' event, extracted from 'play' method. + * @param key The string-based key of the animation to play, as defined previously in the Animation Manager. + * @param startFrame Optionally start the animation playing from this frame index. Default 0. + */ + _startAnimation(key: string, startFrame?: integer): Phaser.GameObjects.GameObject; + /** + * Reverse the Animation that is already playing on the Game Object. + */ + reverse(): Phaser.GameObjects.GameObject; + /** + * Returns a value between 0 and 1 indicating how far this animation is through, ignoring repeats and yoyos. + * If the animation has a non-zero repeat defined, `getProgress` and `getTotalProgress` will be different + * because `getProgress` doesn't include any repeats or repeat delays, whereas `getTotalProgress` does. + */ + getProgress(): number; + /** + * 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. + * @param value The progress value, between 0 and 1. Default 0. + */ + setProgress(value?: number): Phaser.GameObjects.GameObject; + /** + * Handle the removal of an animation from the Animation Manager. + * @param key The key of the removed Animation. + * @param animation The removed Animation. + */ + remove(key?: string, animation?: Phaser.Animations.Animation): void; + /** + * Gets the number of times that the animation will repeat + * after its first iteration. For example, if returns 1, the animation will + * play a total of twice (the initial play plus 1 repeat). + * A value of -1 means the animation will repeat indefinitely. + */ + getRepeat(): integer; + /** + * Sets the number of times that the animation should repeat + * after its first iteration. For example, if repeat is 1, the animation will + * play a total of twice (the initial play plus 1 repeat). + * To repeat indefinitely, use -1. repeat should always be an integer. + * @param value The number of times that the animation should repeat. + */ + setRepeat(value: integer): Phaser.GameObjects.GameObject; + /** + * Gets the amount of delay between repeats, if any. + */ + getRepeatDelay(): number; + /** + * Sets the amount of time in seconds between repeats. + * For example, if `repeat` is 2 and `repeatDelay` is 10, the animation will play initially, + * then wait for 10 seconds before repeating, then play again, then wait another 10 seconds + * before doing its final repeat. + * @param value The delay to wait between repeats, in seconds. + */ + setRepeatDelay(value: number): Phaser.GameObjects.GameObject; + /** + * Restarts the current animation from its beginning, optionally including its delay value. + * @param includeDelay Whether to include the delay value of the animation when restarting. Default false. + */ + restart(includeDelay?: boolean): Phaser.GameObjects.GameObject; + /** + * Immediately stops the current animation from playing and dispatches the `animationcomplete` event. + * + * If no animation is set, no event will be dispatched. + * + * If there is another animation queued (via the `chain` method) then it will start playing immediately. + */ + stop(): Phaser.GameObjects.GameObject; + /** + * Stops the current animation from playing after the specified time delay, given in milliseconds. + * @param delay The number of milliseconds to wait before stopping this animation. + */ + stopAfterDelay(delay: integer): Phaser.GameObjects.GameObject; + /** + * Stops the current animation from playing when it next repeats. + */ + stopOnRepeat(): Phaser.GameObjects.GameObject; + /** + * Stops the current animation from playing when it next sets the given frame. + * If this frame doesn't exist within the animation it will not stop it from playing. + * @param frame The frame to check before stopping this animation. + */ + stopOnFrame(frame: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; + /** + * Sets the Time Scale factor, allowing you to make the animation go go faster or slower than default. + * Where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. + * @param value The time scale factor, where 1 is no change, 0.5 is half speed, etc. Default 1. + */ + setTimeScale(value?: number): Phaser.GameObjects.GameObject; + /** + * Gets the Time Scale factor. + */ + getTimeScale(): number; + /** + * Returns the total number of frames in this animation. + */ + getTotalFrames(): integer; + /** + * The internal update loop for the Animation Component. + * @param time The current timestamp. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + update(time: number, delta: number): void; + /** + * Sets the given Animation Frame as being the current frame + * and applies it to the parent Game Object, adjusting its size and origin as needed. + * @param animationFrame The Animation Frame to set as being current. + */ + setCurrentFrame(animationFrame: Phaser.Animations.AnimationFrame): Phaser.GameObjects.GameObject; + /** + * Advances the animation to the next frame, regardless of the time or animation state. + * If the animation is set to repeat, or yoyo, this will still take effect. + * + * Calling this does not change the direction of the animation. I.e. if it was currently + * playing in reverse, calling this method doesn't then change the direction to forwards. + */ + nextFrame(): Phaser.GameObjects.GameObject; + /** + * Advances the animation to the previous frame, regardless of the time or animation state. + * If the animation is set to repeat, or yoyo, this will still take effect. + * + * Calling this does not change the direction of the animation. I.e. if it was currently + * playing in forwards, calling this method doesn't then change the direction to backwards. + */ + previousFrame(): Phaser.GameObjects.GameObject; + /** + * Sets if the current Animation will yoyo when it reaches the end. + * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. + * @param value `true` if the animation should yoyo, `false` to not. Default false. + */ + setYoyo(value?: boolean): Phaser.GameObjects.GameObject; + /** + * Gets if the current Animation will yoyo when it reaches the end. + * A yoyo'ing animation will play through consecutively, and then reverse-play back to the start again. + */ + getYoyo(): boolean; + /** + * Destroy this Animation component. + * + * Unregisters event listeners and cleans up its references. + */ + destroy(): void; + } + + /** + * Provides methods used for setting the blend mode of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface BlendMode { + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + } + + /** + * Provides methods used for calculating and setting the size of a non-Frame based Game Object. + * Should be applied as a mixin and not used directly. + */ + interface ComputedSize { + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + } + + /** + * Provides methods used for getting and setting the texture of a Game Object. + */ + interface Crop { + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + } + + /** + * Provides methods used for setting the depth of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Depth { + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + } + + /** + * Provides methods used for visually flipping a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Flip { + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + } + + /** + * Provides methods used for obtaining the bounds of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface GetBounds { + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + } + + /** + * Provides methods used for getting and setting the mask of a Game Object. + */ + interface Mask { + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + } + + /** + * Provides methods used for getting and setting the origin of a Game Object. + * Values are normalized, given in the range 0 to 1. + * Display values contain the calculated pixel values. + * Should be applied as a mixin and not used directly. + */ + interface Origin { + /** + * 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. + */ + originX: number; + /** + * 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. + */ + originY: number; + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + } + + /** + * Provides methods used for managing a Game Object following a Path. + * Should be applied as a mixin and not used directly. + */ + interface PathFollower { + /** + * The Path this PathFollower is following. It can only follow one Path at a time. + */ + path: Phaser.Curves.Path; + /** + * Should the PathFollower automatically rotate to point in the direction of the Path? + */ + rotateToPath: boolean; + /** + * Set the Path that this PathFollower should follow. + * + * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. + * @param path The Path this PathFollower is following. It can only follow one Path at a time. + * @param config Settings for the PathFollower. + */ + setPath(path: Phaser.Curves.Path, config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig): Phaser.GameObjects.PathFollower; + /** + * Set whether the PathFollower should automatically rotate to point in the direction of the Path. + * @param value Whether the PathFollower should automatically rotate to point in the direction of the Path. + * @param offset Rotation offset in degrees. Default 0. + */ + setRotateToPath(value: boolean, offset?: number): Phaser.GameObjects.PathFollower; + /** + * Is this PathFollower actively following a Path or not? + * + * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. + */ + isFollowing(): boolean; + /** + * Starts this PathFollower following its given Path. + * @param config The duration of the follow, or a PathFollower config object. Default {}. + * @param startAt Optional start position of the follow, between 0 and 1. Default 0. + */ + startFollow(config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig, startAt?: number): Phaser.GameObjects.PathFollower; + /** + * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the + * point on the Path at which you paused it. + */ + pauseFollow(): Phaser.GameObjects.PathFollower; + /** + * Resumes a previously paused PathFollower. + * + * If the PathFollower was not paused this has no effect. + */ + resumeFollow(): Phaser.GameObjects.PathFollower; + /** + * Stops this PathFollower from following the path any longer. + * + * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. + */ + stopFollow(): Phaser.GameObjects.PathFollower; + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + */ + pathUpdate(): void; + } + + /** + * Provides methods used for setting the WebGL rendering pipeline of a Game Object. + */ + interface Pipeline { + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + } + + /** + * Provides methods used for getting and setting the Scroll Factor of a Game Object. + */ + interface ScrollFactor { + /** + * 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 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. + */ + scrollFactorX: number; + /** + * 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 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. + */ + scrollFactorY: number; + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + } + + /** + * Provides methods used for getting and setting the size of a Game Object. + */ + interface Size { + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + } + + /** + * Provides methods used for getting and setting the texture of a Game Object. + */ + interface Texture { + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + } + + /** + * Provides methods used for getting and setting the texture of a Game Object. + */ + interface TextureCrop { + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + } + + /** + * Provides methods used for setting the tint of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Tint { + /** + * Fill or additive? + */ + tintFill: boolean; + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + } + + /** + * Build a JSON representation of the given Game Object. + * + * This is typically extended further by Game Object specific implementations. + */ + interface ToJSON { + } + + /** + * Provides methods used for getting and setting the position, scale and rotation of a Game Object. + */ + interface Transform { + /** + * The x position of this Game Object. + */ + x: number; + /** + * The y position of this Game Object. + */ + y: number; + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + /** + * The w position of this Game Object. + */ + w: number; + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + } + + /** + * A Matrix used for display transformations for rendering. + * + * It is represented like so: + * + * ``` + * | a | c | tx | + * | b | d | ty | + * | 0 | 0 | 1 | + * ``` + */ + class TransformMatrix { + /** + * + * @param a The Scale X value. Default 1. + * @param b The Skew Y value. Default 0. + * @param c The Skew X value. Default 0. + * @param d The Scale Y value. Default 1. + * @param tx The Translate X value. Default 0. + * @param ty The Translate Y value. Default 0. + */ + constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number); + + /** + * The matrix values. + */ + matrix: Float32Array; + + /** + * The decomposed matrix. + */ + decomposedMatrix: object; + + /** + * The Scale X value. + */ + a: number; + + /** + * The Skew Y value. + */ + b: number; + + /** + * The Skew X value. + */ + c: number; + + /** + * The Scale Y value. + */ + d: number; + + /** + * The Translate X value. + */ + e: number; + + /** + * The Translate Y value. + */ + f: number; + + /** + * The Translate X value. + */ + tx: number; + + /** + * The Translate Y value. + */ + ty: number; + + /** + * The rotation of the Matrix. Value is in radians. + */ + readonly rotation: number; + + /** + * The rotation of the Matrix, normalized to be within the Phaser right-handed + * clockwise rotation space. Value is in radians. + */ + readonly rotationNormalized: number; + + /** + * The decomposed horizontal scale of the Matrix. This value is always positive. + */ + readonly scaleX: number; + + /** + * The decomposed vertical scale of the Matrix. This value is always positive. + */ + readonly scaleY: number; + + /** + * Reset the Matrix to an identity matrix. + */ + loadIdentity(): this; + + /** + * Translate the Matrix. + * @param x The horizontal translation value. + * @param y The vertical translation value. + */ + translate(x: number, y: number): this; + + /** + * Scale the Matrix. + * @param x The horizontal scale value. + * @param y The vertical scale value. + */ + scale(x: number, y: number): this; + + /** + * Rotate the Matrix. + * @param angle The angle of rotation in radians. + */ + rotate(angle: number): this; + + /** + * Multiply this Matrix by the given Matrix. + * + * If an `out` Matrix is given then the results will be stored in it. + * If it is not given, this matrix will be updated in place instead. + * Use an `out` Matrix if you do not wish to mutate this matrix. + * @param rhs The Matrix to multiply by. + * @param out An optional Matrix to store the results in. + */ + multiply(rhs: Phaser.GameObjects.Components.TransformMatrix, out?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Multiply this Matrix by the matrix given, including the offset. + * + * The offsetX is added to the tx value: `offsetX * a + offsetY * c + tx`. + * The offsetY is added to the ty value: `offsetY * b + offsetY * d + ty`. + * @param src The source Matrix to copy from. + * @param offsetX Horizontal offset to factor in to the multiplication. + * @param offsetY Vertical offset to factor in to the multiplication. + */ + multiplyWithOffset(src: Phaser.GameObjects.Components.TransformMatrix, offsetX: number, offsetY: number): this; + + /** + * Transform the Matrix. + * @param a The Scale X value. + * @param b The Shear Y value. + * @param c The Shear X value. + * @param d The Scale Y value. + * @param tx The Translate X value. + * @param ty The Translate Y value. + */ + transform(a: number, b: number, c: number, d: number, tx: number, ty: number): this; + + /** + * Transform a point using this Matrix. + * @param x The x coordinate of the point to transform. + * @param y The y coordinate of the point to transform. + * @param point The Point object to store the transformed coordinates. + */ + transformPoint(x: number, y: number, point: Phaser.Geom.Point | Phaser.Math.Vector2 | object): Phaser.Geom.Point | Phaser.Math.Vector2 | object; + + /** + * Invert the Matrix. + */ + invert(): this; + + /** + * Set the values of this Matrix to copy those of the matrix given. + * @param src The source Matrix to copy from. + */ + copyFrom(src: Phaser.GameObjects.Components.TransformMatrix): this; + + /** + * Set the values of this Matrix to copy those of the array given. + * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. + * @param src The array of values to set into this matrix. + */ + copyFromArray(src: any[]): this; + + /** + * Copy the values from this Matrix to the given Canvas Rendering Context. + * This will use the Context.transform method. + * @param ctx The Canvas Rendering Context to copy the matrix values to. + */ + copyToContext(ctx: CanvasRenderingContext2D): CanvasRenderingContext2D; + + /** + * Copy the values from this Matrix to the given Canvas Rendering Context. + * This will use the Context.setTransform method. + * @param ctx The Canvas Rendering Context to copy the matrix values to. + */ + setToContext(ctx: CanvasRenderingContext2D): CanvasRenderingContext2D; + + /** + * Copy the values in this Matrix to the array given. + * + * Where array indexes 0, 1, 2, 3, 4 and 5 are mapped to a, b, c, d, e and f. + * @param out The array to copy the matrix values in to. + */ + copyToArray(out?: any[]): any[]; + + /** + * Set the values of this Matrix. + * @param a The Scale X value. + * @param b The Shear Y value. + * @param c The Shear X value. + * @param d The Scale Y value. + * @param tx The Translate X value. + * @param ty The Translate Y value. + */ + setTransform(a: number, b: number, c: number, d: number, tx: number, ty: number): this; + + /** + * Decompose this Matrix into its translation, scale and rotation values using QR decomposition. + * + * The result must be applied in the following order to reproduce the current matrix: + * + * translate -> rotate -> scale + */ + decomposeMatrix(): object; + + /** + * Apply the identity, translate, rotate and scale operations on the Matrix. + * @param x The horizontal translation. + * @param y The vertical translation. + * @param rotation The angle of rotation in radians. + * @param scaleX The horizontal scale. + * @param scaleY The vertical scale. + */ + applyITRS(x: number, y: number, rotation: number, scaleX: number, scaleY: number): this; + + /** + * Takes the `x` and `y` values and returns a new position in the `output` vector that is the inverse of + * the current matrix with its transformation applied. + * + * Can be used to translate points from world to local space. + * @param x The x position to translate. + * @param y The y position to translate. + * @param output A Vector2, or point-like object, to store the results in. + */ + applyInverse(x: number, y: number, output?: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Returns the X component of this matrix multiplied by the given values. + * This is the same as `x * a + y * c + e`. + * @param x The x value. + * @param y The y value. + */ + getX(x: number, y: number): number; + + /** + * Returns the Y component of this matrix multiplied by the given values. + * This is the same as `x * b + y * d + f`. + * @param x The x value. + * @param y The y value. + */ + getY(x: number, y: number): number; + + /** + * Returns a string that can be used in a CSS Transform call as a `matrix` property. + */ + getCSSMatrix(): string; + + /** + * Destroys this Transform Matrix. + */ + destroy(): void; + + } + + /** + * Provides methods used for setting the visibility of a Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Visible { + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + } + + } + + /** + * A Container Game Object. + * + * A Container, as the name implies, can 'contain' other types of Game Object. + * When a Game Object is added to a Container, the Container becomes responsible for the rendering of it. + * By default it will be removed from the Display List and instead added to the Containers own internal list. + * + * The position of the Game Object automatically becomes relative to the position of the Container. + * + * When the Container is rendered, all of its children are rendered as well, in the order in which they exist + * within the Container. Container children can be repositioned using methods such as `MoveUp`, `MoveDown` and `SendToBack`. + * + * If you modify a transform property of the Container, such as `Container.x` or `Container.rotation` then it will + * automatically influence all children as well. + * + * Containers can include other Containers for deeply nested transforms. + * + * Containers can have masks set on them and can be used as a mask too. However, Container children cannot be masked. + * The masks do not 'stack up'. Only a Container on the root of the display list will use its mask. + * + * Containers can be enabled for input. Because they do not have a texture you need to provide a shape for them + * to use as their hit area. Container children can also be enabled for input, independent of the Container. + * + * Containers can be given a physics body for either Arcade Physics, Impact Physics or Matter Physics. However, + * if Container _children_ are enabled for physics you may get unexpected results, such as offset bodies, + * if the Container itself, or any of its ancestors, is positioned anywhere other than at 0 x 0. Container children + * with physics do not factor in the Container due to the excessive extra calculations needed. Please structure + * your game to work around this. + * + * It's important to understand the impact of using Containers. They add additional processing overhead into + * every one of their children. The deeper you nest them, the more the cost escalates. This is especially true + * for input events. You also loose the ability to set the display depth of Container children in the same + * flexible manner as those not within them. In short, don't use them for the sake of it. You pay a small cost + * every time you create one, try to structure your game around avoiding that where possible. + */ + class Container extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param children An optional array of Game Objects to add to this Container. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, children?: Phaser.GameObjects.GameObject[]); + + /** + * An array holding the children of this Container. + */ + list: Phaser.GameObjects.GameObject[]; + + /** + * Does this Container exclusively manage its children? + * + * The default is `true` which means a child added to this Container cannot + * belong in another Container, which includes the Scene display list. + * + * If you disable this then this Container will no longer exclusively manage its children. + * This allows you to create all kinds of interesting graphical effects, such as replicating + * Game Objects without reparenting them all over the Scene. + * However, doing so will prevent children from receiving any kind of input event or have + * their physics bodies work by default, as they're no longer a single entity on the + * display list, but are being replicated where-ever this Container is. + */ + exclusive: boolean; + + /** + * Containers can have an optional maximum size. If set to anything above 0 it + * will constrict the addition of new Game Objects into the Container, capping off + * the maximum limit the Container can grow in size to. + */ + maxSize: integer; + + /** + * The cursor position. + */ + position: integer; + + /** + * Internal Transform Matrix used for local space conversion. + */ + localTransform: Phaser.GameObjects.Components.TransformMatrix; + + /** + * 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. + */ + scrollFactorX: number; + + /** + * 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. + */ + scrollFactorY: number; + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + */ + readonly originX: number; + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + */ + readonly originY: number; + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + */ + readonly displayOriginX: number; + + /** + * Internal value to allow Containers to be used for input and physics. + * Do not change this value. It has no effect other than to break things. + */ + readonly displayOriginY: number; + + /** + * Does this Container exclusively manage its children? + * + * The default is `true` which means a child added to this Container cannot + * belong in another Container, which includes the Scene display list. + * + * If you disable this then this Container will no longer exclusively manage its children. + * This allows you to create all kinds of interesting graphical effects, such as replicating + * Game Objects without reparenting them all over the Scene. + * However, doing so will prevent children from receiving any kind of input event or have + * their physics bodies work by default, as they're no longer a single entity on the + * display list, but are being replicated where-ever this Container is. + * @param value The exclusive state of this Container. Default true. + */ + setExclusive(value?: boolean): Phaser.GameObjects.Container; + + /** + * Gets the bounds of this Container. It works by iterating all children of the Container, + * getting their respective bounds, and then working out a min-max rectangle from that. + * It does not factor in if the children render or not, all are included. + * + * Some children are unable to return their bounds, such as Graphics objects, in which case + * they are skipped. + * + * Depending on the quantity of children in this Container it could be a really expensive call, + * so cache it and only poll it as needed. + * + * The values are stored and returned in a Rectangle object. + * @param output A Geom.Rectangle object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: Phaser.Geom.Rectangle): Phaser.Geom.Rectangle; + + /** + * Takes a Point-like object, such as a Vector2, Geom.Point or object with public x and y properties, + * and transforms it into the space of this Container, then returns it in the output object. + * @param source The Source Point to be transformed. + * @param output A destination object to store the transformed point in. If none given a Vector2 will be created and returned. + */ + pointToContainer(source: object | Phaser.Geom.Point | Phaser.Math.Vector2, output?: object | Phaser.Geom.Point | Phaser.Math.Vector2): object | Phaser.Geom.Point | Phaser.Math.Vector2; + + /** + * Returns the world transform matrix as used for Bounds checks. + * + * The returned matrix is temporal and shouldn't be stored. + */ + getBoundsTransformMatrix(): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Adds the given Game Object, or array of Game Objects, to this Container. + * + * Each Game Object must be unique within the Container. + * @param child The Game Object, or array of Game Objects, to add to the Container. + */ + add(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[]): Phaser.GameObjects.Container; + + /** + * Adds the given Game Object, or array of Game Objects, to this Container at the specified position. + * + * Existing Game Objects in the Container are shifted up. + * + * Each Game Object must be unique within the Container. + * @param child The Game Object, or array of Game Objects, to add to the Container. + * @param index The position to insert the Game Object/s at. Default 0. + */ + addAt(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], index?: integer): Phaser.GameObjects.Container; + + /** + * Returns the Game Object at the given position in this Container. + * @param index The position to get the Game Object from. + */ + getAt(index: integer): Phaser.GameObjects.GameObject; + + /** + * Returns the index of the given Game Object in this Container. + * @param child The Game Object to search for in this Container. + */ + getIndex(child: Phaser.GameObjects.GameObject): integer; + + /** + * 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. + * @param property The property to lexically sort by. + * @param handler Provide your own custom handler function. Will receive 2 children which it should compare and return a boolean. + */ + sort(property: string, handler?: Function): Phaser.GameObjects.Container; + + /** + * Searches for the first instance of a child with its `name` property matching the given argument. + * Should more than one child have the same name only the first is returned. + * @param name The name to search for. + */ + getByName(name: string): Phaser.GameObjects.GameObject; + + /** + * Returns a random Game Object from this Container. + * @param startIndex An optional start index. Default 0. + * @param length An optional length, the total number of elements (from the startIndex) to choose from. + */ + getRandom(startIndex?: integer, length?: integer): Phaser.GameObjects.GameObject; + + /** + * Gets the first Game Object in this Container. + * + * You can also specify a property and value to search for, in which case it will return the first + * Game Object in this Container with a matching property and / or value. + * + * For example: `getFirst('visible', true)` would return the first Game Object that had its `visible` property set. + * + * You can limit the search to the `startIndex` - `endIndex` range. + * @param property The property to test on each Game Object in the Container. + * @param value The value to test the property against. Must pass a strict (`===`) comparison check. + * @param startIndex An optional start index to search from. Default 0. + * @param endIndex An optional end index to search up to (but not included) Default Container.length. + */ + getFirst(property: string, value: any, startIndex?: integer, endIndex?: integer): Phaser.GameObjects.GameObject; + + /** + * Returns all Game Objects in this Container. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('body')` would return only Game Objects that have a body property. + * + * You can also specify a value to compare the property to: + * + * `getAll('visible', true)` would return only Game Objects that have their visible property set to `true`. + * + * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 Game Objects. + * @param property The property to test on each Game Object in the Container. + * @param value If property is set then the `property` must strictly equal this value to be included in the results. + * @param startIndex An optional start index to search from. Default 0. + * @param endIndex An optional end index to search up to (but not included) Default Container.length. + */ + getAll(property?: string, value?: any, startIndex?: integer, endIndex?: integer): Phaser.GameObjects.GameObject[]; + + /** + * Returns the total number of Game Objects in this Container that have a property + * matching the given value. + * + * For example: `count('visible', true)` would count all the elements that have their visible property set. + * + * You can optionally limit the operation to the `startIndex` - `endIndex` range. + * @param property The property to check. + * @param value The value to check. + * @param startIndex An optional start index to search from. Default 0. + * @param endIndex An optional end index to search up to (but not included) Default Container.length. + */ + count(property: string, value: any, startIndex?: integer, endIndex?: integer): integer; + + /** + * Swaps the position of two Game Objects in this Container. + * Both Game Objects must belong to this Container. + * @param child1 The first Game Object to swap. + * @param child2 The second Game Object to swap. + */ + swap(child1: Phaser.GameObjects.GameObject, child2: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; + + /** + * Moves a Game Object to a new position within this Container. + * + * The Game Object must already be a child of this Container. + * + * The Game Object is removed from its old position and inserted into the new one. + * Therefore the Container size does not change. Other children will change position accordingly. + * @param child The Game Object to move. + * @param index The new position of the Game Object in this Container. + */ + moveTo(child: Phaser.GameObjects.GameObject, index: integer): Phaser.GameObjects.Container; + + /** + * Removes the given Game Object, or array of Game Objects, from this Container. + * + * The Game Objects must already be children of this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * @param child The Game Object, or array of Game Objects, to be removed from the Container. + * @param destroyChild Optionally call `destroy` on each child successfully removed from this Container. Default false. + */ + remove(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], destroyChild?: boolean): Phaser.GameObjects.Container; + + /** + * Removes the Game Object at the given position in this Container. + * + * You can also optionally call `destroy` on the Game Object, if one is found. + * @param index The index of the Game Object to be removed. + * @param destroyChild Optionally call `destroy` on the Game Object if successfully removed from this Container. Default false. + */ + removeAt(index: integer, destroyChild?: boolean): Phaser.GameObjects.Container; + + /** + * Removes the Game Objects between the given positions in this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * @param startIndex An optional start index to search from. Default 0. + * @param endIndex An optional end index to search up to (but not included) Default Container.length. + * @param destroyChild Optionally call `destroy` on each Game Object successfully removed from this Container. Default false. + */ + removeBetween(startIndex?: integer, endIndex?: integer, destroyChild?: boolean): Phaser.GameObjects.Container; + + /** + * Removes all Game Objects from this Container. + * + * You can also optionally call `destroy` on each Game Object that is removed from the Container. + * @param destroyChild Optionally call `destroy` on each Game Object successfully removed from this Container. Default false. + */ + removeAll(destroyChild?: boolean): Phaser.GameObjects.Container; + + /** + * Brings the given Game Object to the top of this Container. + * This will cause it to render on-top of any other objects in the Container. + * @param child The Game Object to bring to the top of the Container. + */ + bringToTop(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; + + /** + * Sends the given Game Object to the bottom of this Container. + * This will cause it to render below any other objects in the Container. + * @param child The Game Object to send to the bottom of the Container. + */ + sendToBack(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; + + /** + * Moves the given Game Object up one place in this Container, unless it's already at the top. + * @param child The Game Object to be moved in the Container. + */ + moveUp(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; + + /** + * Moves the given Game Object down one place in this Container, unless it's already at the bottom. + * @param child The Game Object to be moved in the Container. + */ + moveDown(child: Phaser.GameObjects.GameObject): Phaser.GameObjects.Container; + + /** + * Reverses the order of all Game Objects in this Container. + */ + reverse(): Phaser.GameObjects.Container; + + /** + * Shuffles the all Game Objects in this Container using the Fisher-Yates implementation. + */ + shuffle(): Phaser.GameObjects.Container; + + /** + * Replaces a Game Object in this Container with the new Game Object. + * The new Game Object cannot already be a child of this Container. + * @param oldChild The Game Object in this Container that will be replaced. + * @param newChild The Game Object to be added to this Container. + * @param destroyChild Optionally call `destroy` on the Game Object if successfully removed from this Container. Default false. + */ + replace(oldChild: Phaser.GameObjects.GameObject, newChild: Phaser.GameObjects.GameObject, destroyChild?: boolean): Phaser.GameObjects.Container; + + /** + * Returns `true` if the given Game Object is a direct child of this Container. + * + * This check does not scan nested Containers. + * @param child The Game Object to check for within this Container. + */ + exists(child: Phaser.GameObjects.GameObject): boolean; + + /** + * Sets the property to the given value on all Game Objects in this Container. + * + * Optionally you can specify a start and end index. For example if this Container had 100 Game Objects, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 Game Objects. + * @param property The property that must exist on the Game Object. + * @param value The value to get the property to. + * @param startIndex An optional start index to search from. Default 0. + * @param endIndex An optional end index to search up to (but not included) Default Container.length. + */ + setAll(property: string, value: any, startIndex?: integer, endIndex?: integer): Phaser.GameObjects.Container; + + /** + * Passes all Game Objects in this Container to the given callback. + * + * A copy of the Container is made before passing each entry to your callback. + * This protects against the callback itself modifying the Container. + * + * If you know for sure that the callback will not change the size of this Container + * then you can use the more performant `Container.iterate` method instead. + * @param callback The function to call. + * @param context Value to use as `this` when executing callback. + * @param args Additional arguments that will be passed to the callback, after the child. + */ + each(callback: Function, context?: object, ...args: any[]): Phaser.GameObjects.Container; + + /** + * Passes all Game Objects in this Container to the given callback. + * + * Only use this method when you absolutely know that the Container will not be modified during + * the iteration, i.e. by removing or adding to its contents. + * @param callback The function to call. + * @param context Value to use as `this` when executing callback. + * @param args Additional arguments that will be passed to the callback, after the child. + */ + iterate(callback: Function, context?: object, ...args: any[]): Phaser.GameObjects.Container; + + /** + * 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + * @param updateChildren Apply this scrollFactor to all Container children as well? Default false. + */ + setScrollFactor(x: number, y?: number, updateChildren?: boolean): this; + + /** + * The number of Game Objects inside this Container. + */ + readonly length: integer; + + /** + * Returns the first Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + */ + readonly first: Phaser.GameObjects.GameObject; + + /** + * Returns the last Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + */ + readonly last: Phaser.GameObjects.GameObject; + + /** + * Returns the next Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + */ + readonly next: Phaser.GameObjects.GameObject; + + /** + * Returns the previous Game Object within the Container, or `null` if it is empty. + * + * You can move the cursor by calling `Container.next` and `Container.previous`. + */ + readonly previous: Phaser.GameObjects.GameObject; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Display List plugin. + * + * Display Lists belong to a Scene and maintain the list of Game Objects to render every frame. + * + * Some of these Game Objects may also be part of the Scene's [Update List]{@link Phaser.GameObjects.UpdateList}, for updating. + */ + class DisplayList extends Phaser.Structs.List { + /** + * + * @param scene The Scene that this Display List belongs to. + */ + constructor(scene: Phaser.Scene); + + /** + * The flag the determines whether Game Objects should be sorted when `depthSort()` is called. + */ + sortChildrenFlag: boolean; + + /** + * The Scene that this Display List belongs to. + */ + scene: Phaser.Scene; + + /** + * The Scene's Systems. + */ + systems: Phaser.Scenes.Systems; + + /** + * Force a sort of the display list on the next call to depthSort. + */ + queueDepthSort(): void; + + /** + * Immediately sorts the display list if the flag is set. + */ + depthSort(): void; + + /** + * Compare the depth of two Game Objects. + * @param childA The first Game Object. + * @param childB The second Game Object. + */ + sortByDepth(childA: Phaser.GameObjects.GameObject, childB: Phaser.GameObjects.GameObject): integer; + + /** + * Returns an array which contains all objects currently on the Display List. + * This is a reference to the main list array, not a copy of it, so be careful not to modify it. + */ + getChildren(): Phaser.GameObjects.GameObject[]; + + } + + /** + * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. + * + * In order for DOM Elements to display you have to enable them by adding the following to your game + * configuration object: + * + * ```javascript + * dom { + * createContainer: true + * } + * ``` + * + * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top + * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of + * settings within the Scale Manager, the dom container is resized accordingly. + * + * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing + * Element that you wish to be placed under the control of Phaser. For example: + * + * ```javascript + * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); + * ``` + * + * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in + * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, + * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + * + * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control + * alignment and positioning of the elements next to regular game content. + * + * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the + * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other + * methods available in this class to help construct your elements. + * + * Once the element has been created you can then control it like you would any other Game Object. You can set its + * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped + * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that + * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have + * a DOM Element, then a Sprite, then another DOM Element behind it. + * + * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event + * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas + * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you + * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. + * + * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. + * + * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert + * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. + * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and + * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top + * of your game, and should treat it accordingly. + */ + class DOMElement extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this DOM Element in the world. Default 0. + * @param y The vertical position of this DOM Element in the world. Default 0. + * @param element An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. + * @param style If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. + * @param innerText If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, element?: Element | string, style?: string | any, innerText?: string); + + /** + * A reference to the parent DOM Container that the Game instance created when it started. + */ + parent: Element; + + /** + * A reference to the HTML Cache. + */ + cache: Phaser.Cache.BaseCache; + + /** + * The actual DOM Element that this Game Object is bound to. For example, if you've created a `
` + * then this property is a direct reference to that element within the dom. + */ + node: Element; + + /** + * By default a DOM Element will have its transform, display, opacity, zIndex and blend mode properties + * updated when its rendered. If, for some reason, you don't want any of these changed other than the + * CSS transform, then set this flag to `true`. When `true` only the CSS Transform is applied and it's + * up to you to keep track of and set the other properties as required. + * + * This can be handy if, for example, you've a nested DOM Element and you don't want the opacity to be + * picked-up by any of its children. + */ + transformOnly: boolean; + + /** + * 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 + */ + skewX: number; + + /** + * 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 + */ + skewY: number; + + /** + * A Vector4 that contains the 3D rotation of this DOM Element around a fixed axis in 3D space. + * + * All values in the Vector4 are treated as degrees, unless the `rotate3dAngle` property is changed. + * + * For more details see the following MDN page: + * + * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d + */ + rotate3d: Phaser.Math.Vector4; + + /** + * 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 + */ + rotate3dAngle: string; + + /** + * The native (un-scaled) width of this Game Object. + * + * For a DOM Element this property is read-only. + * + * The property `displayWidth` holds the computed bounds of this DOM Element, factoring in scaling. + */ + readonly width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * For a DOM Element this property is read-only. + * + * The property `displayHeight` holds the computed bounds of this DOM Element, factoring in scaling. + */ + readonly height: number; + + /** + * 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. + */ + readonly displayWidth: number; + + /** + * 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. + */ + readonly displayHeight: number; + + /** + * 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 + * @param x The angle, in radians, by which to skew the DOM Element on the horizontal axis. Default 0. + * @param y The angle, in radians, by which to skew the DOM Element on the vertical axis. Default x. + */ + setSkew(x?: number, y?: number): this; + + /** + * 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.** + * @param value The perspective value, in pixels, that determines the distance between the z plane and the user. + */ + setPerspective(value: number): this; + + /** + * 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.** + */ + perspective: number; + + /** + * Adds one or more native DOM event listeners onto the underlying Element of this Game Object. + * The event is then dispatched via this Game Objects standard event emitter. + * + * For example: + * + * ```javascript + * var div = this.add.dom(x, y, element); + * + * div.addListener('click'); + * + * div.on('click', handler); + * ``` + * @param events The DOM event/s to listen for. You can specify multiple events by separating them with spaces. + */ + addListener(events: string): this; + + /** + * Removes one or more native DOM event listeners from the underlying Element of this Game Object. + * @param events The DOM event/s to stop listening for. You can specify multiple events by separating them with spaces. + */ + removeListener(events: string): this; + + /** + * 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. + * @param 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 style Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be ready from. + * @param innerText A DOMString that holds the text that will be set as the innerText of the created element. + */ + createElement(tagName: string, style?: string | any, innerText?: string): this; + + /** + * Binds a new DOM Element to this Game Object. 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 on the new element. + * + * The `element` argument you pass to this method can be either a string tagName: + * + * ```javascript + *

Phaser

+ * + * this.add.dom().setElement('heading'); + * ``` + * + * Or a reference to an Element instance: + * + * ```javascript + *

Phaser

+ * + * var h1 = document.getElementById('heading'); + * + * this.add.dom().setElement(h1); + * ``` + * + * 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().setElement(h1, '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().setElement(h1, style, 'Phaser'); + * ``` + * @param element If a string it is passed to `getElementById()`, or it should be a reference to an existing Element. + * @param style Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be ready from. + * @param innerText A DOMString that holds the text that will be set as the innerText of the created element. + */ + setElement(element: string | Element, style?: string | any, innerText?: string): this; + + /** + * Takes a block of html from the HTML Cache, that has previously been preloaded into the game, and then + * creates a DOM Element from it. The loaded HTML is set as the `innerHTML` property of the created + * element. + * + * Assume the following html is stored in a file called `loginform.html`: + * + * ```html + * + * + * ``` + * + * Which is loaded into your game using the cache key 'login': + * + * ```javascript + * this.load.html('login', 'assets/loginform.html'); + * ``` + * + * You can create a DOM Element from it using the cache key: + * + * ```javascript + * this.add.dom().createFromCache('login'); + * ``` + * + * The optional `elementType` argument controls the container that is created, into which the loaded html is inserted. + * The default is a plain `div` object, but any valid tagName can be given. + * + * 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. + * @param The key of the html cache entry to use for this DOM Element. + * @param tagName The tag name of the element into which all of the loaded html will be inserted. Defaults to a plain div tag. Default 'div'. + */ + createFromCache(The: string, tagName?: string): this; + + /** + * Takes a string of html and then creates a DOM Element from it. The HTML is set as the `innerHTML` + * property of the created element. + * + * ```javascript + * let form = ` + * + * + * `; + * ``` + * + * You can create a DOM Element from it using the string: + * + * ```javascript + * this.add.dom().createFromHTML(form); + * ``` + * + * The optional `elementType` argument controls the type of container that is created, into which the html is inserted. + * The default is a plain `div` object, but any valid tagName can be given. + * + * 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. + * @param A string of html to be set as the `innerHTML` property of the created element. + * @param tagName The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag. Default 'div'. + */ + createFromHTML(A: string, tagName?: string): this; + + /** + * Removes the current DOM Element bound to this Game Object from the DOM entirely and resets the + * `node` property of this Game Object to be `null`. + */ + removeElement(): this; + + /** + * Internal method that calls `getBoundingClientRect` on the `node` and then sets the bounds width + * and height into the `displayWidth` and `displayHeight` properties, and the `clientWidth` and `clientHeight` + * values into the `width` and `height` properties respectively. + * + * This is called automatically whenever a new element is created or set. + */ + updateSize(): this; + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a property matching the given key and value. It then returns this child + * if found, or `null` if not. + * @param property The property to search the children for. + * @param value The value the property must strictly equal. + */ + getChildByProperty(property: string, value: string): Element; + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a matching id. It then returns this child if found, or `null` if not. + * + * Be aware that class and id names are case-sensitive. + * @param id The id to search the children for. + */ + getChildByID(id: string): Element; + + /** + * Gets all children from this DOM Elements node, using `querySelectorAll('*')` and then iterates through + * them, looking for the first one that has a matching name. It then returns this child if found, or `null` if not. + * + * Be aware that class and id names are case-sensitive. + * @param name The name to search the children for. + */ + getChildByName(name: string): Element; + + /** + * Sets the `className` property of the DOM Element node and updates the internal sizes. + * @param className A string representing the class or space-separated classes of the element. + */ + setClassName(className: string): this; + + /** + * Sets the `innerText` property of the DOM Element node and updates the internal sizes. + * + * Note that only certain types of Elements can have `innerText` set on them. + * @param text A DOMString representing the rendered text content of the element. + */ + setText(text: string): this; + + /** + * Sets the `innerHTML` property of the DOM Element node and updates the internal sizes. + * @param html A DOMString of html to be set as the `innerHTML` property of the element. + */ + setHTML(html: string): this; + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * + * DOMElements always return `true` as they need to still set values during the render pass, even if not visible. + */ + willRender(): boolean; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + namespace Events { + /** + * The Game Object Destroy Event. + * + * This event is dispatched when a Game Object instance is being destroyed. + * + * Listen for it on a Game Object instance using `GameObject.on('destroy', listener)`. + */ + const DESTROY: any; + + /** + * The Video Game Object Complete Event. + * + * This event is dispatched when a Video finishes playback by reaching the end of its duration. It + * is also dispatched if a video marker sequence is being played and reaches the end. + * + * Note that not all videos can fire this event. Live streams, for example, have no fixed duration, + * so never technically 'complete'. + * + * If a video is stopped from playback, via the `Video.stop` method, it will emit the + * `VIDEO_STOP` event instead of this one. + * + * Listen for it from a Video Game Object instance using `Video.on('complete', listener)`. + */ + const VIDEO_COMPLETE: any; + + /** + * The Video Game Object Created Event. + * + * This event is dispatched when the texture for a Video has been created. This happens + * when enough of the video source has been loaded that the browser is able to render a + * frame from it. + * + * Listen for it from a Video Game Object instance using `Video.on('created', listener)`. + */ + const VIDEO_CREATED: any; + + /** + * The Video Game Object Error Event. + * + * This event is dispatched when a Video tries to play a source that does not exist, or is the wrong file type. + * + * Listen for it from a Video Game Object instance using `Video.on('error', listener)`. + */ + const VIDEO_ERROR: any; + + /** + * 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)`. + */ + const VIDEO_LOOP: any; + + /** + * The Video Game Object Play Event. + * + * This event is dispatched when a Video begins playback. For videos that do not require + * interaction unlocking, this is usually as soon as the `Video.play` method is called. + * However, for videos that require unlocking, it is fired once playback begins after + * they've been unlocked. + * + * Listen for it from a Video Game Object instance using `Video.on('play', listener)`. + */ + const VIDEO_PLAY: any; + + /** + * The Video Game Object Seeked Event. + * + * This event is dispatched when a Video completes seeking to a new point in its timeline. + * + * Listen for it from a Video Game Object instance using `Video.on('seeked', listener)`. + */ + const VIDEO_SEEKED: any; + + /** + * The Video Game Object Seeking Event. + * + * This event is dispatched when a Video _begins_ seeking to a new point in its timeline. + * When the seek is complete, it will dispatch the `VIDEO_SEEKED` event to conclude. + * + * Listen for it from a Video Game Object instance using `Video.on('seeking', listener)`. + */ + const VIDEO_SEEKING: any; + + /** + * The Video Game Object Stopped Event. + * + * This event is dispatched when a Video is stopped from playback via a call to the `Video.stop` method, + * either directly via game code, or indirectly as the result of changing a video source or destroying it. + * + * Listen for it from a Video Game Object instance using `Video.on('stop', listener)`. + */ + const VIDEO_STOP: any; + + /** + * The Video Game Object Timeout Event. + * + * This event is dispatched when a Video has exhausted its allocated time while trying to connect to a video + * source to start playback. + * + * Listen for it from a Video Game Object instance using `Video.on('timeout', listener)`. + */ + const VIDEO_TIMEOUT: any; + + /** + * The Video Game Object Unlocked Event. + * + * This event is dispatched when a Video that was prevented from playback due to the browsers + * Media Engagement Interaction policy, is unlocked by a user gesture. + * + * Listen for it from a Video Game Object instance using `Video.on('unlocked', listener)`. + */ + const VIDEO_UNLOCKED: any; + + } + + /** + * An Extern Game Object is a special type of Game Object that allows you to pass + * rendering off to a 3rd party. + * + * When you create an Extern and place it in the display list of a Scene, the renderer will + * process the list as usual. When it finds an Extern it will flush the current batch, + * clear down the pipeline and prepare a transform matrix which your render function can + * take advantage of, if required. + * + * The WebGL context is then left is a 'clean' state, ready for you to bind your own shaders, + * or draw to it, whatever you wish to do. Once you've finished, you should free-up any + * of your resources. The Extern will then rebind the Phaser pipeline and carry on + * rendering the display list. + * + * Although this object has lots of properties such as Alpha, Blend Mode and Tint, none of + * them are used during rendering unless you take advantage of them in your own render code. + */ + class Extern extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + */ + constructor(scene: Phaser.Scene); + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The base class that all Game Objects extend. + * You don't create GameObjects directly and they cannot be added to the display list. + * Instead, use them as the base for your own custom classes. + */ + class GameObject extends Phaser.Events.EventEmitter { + /** + * + * @param scene The Scene to which this Game Object belongs. + * @param type A textual representation of the type of Game Object, i.e. `sprite`. + */ + constructor(scene: Phaser.Scene, type: string); + + /** + * The Scene to which this Game Object belongs. + * Game Objects can only belong to one Scene. + */ + protected scene: Phaser.Scene; + + /** + * A textual representation of this Game Object, i.e. `sprite`. + * Used internally by Phaser but is available for your own custom classes to populate. + */ + type: string; + + /** + * The current state of this Game Object. + * + * Phaser itself will never modify this value, although plugins may do so. + * + * Use this property to track the state of a Game Object during its lifetime. For example, it could change from + * a state of 'moving', to 'attacking', to 'dead'. The state value should be an integer (ideally mapped to a constant + * in your game code), or a string. These are recommended to keep it light and simple, with fast comparisons. + * If you need to store complex data about your Game Object, look at using the Data Component instead. + */ + state: integer | string; + + /** + * The parent Container of this Game Object, if it has one. + */ + parentContainer: Phaser.GameObjects.Container; + + /** + * The name of this Game Object. + * Empty by default and never populated by Phaser, this is left for developers to use. + */ + name: string; + + /** + * The active state of this Game Object. + * A Game Object with an active state of `true` is processed by the Scenes UpdateList, if added to it. + * An active object is one which is having its logic and internal systems updated. + */ + active: boolean; + + /** + * The Tab Index of the Game Object. + * Reserved for future use by plugins and the Input Manager. + */ + tabIndex: integer; + + /** + * A Data Manager. + * It allows you to store, query and get key/value paired information specific to this Game Object. + * `null` by default. Automatically created if you use `getData` or `setData` or `setDataEnabled`. + */ + data: Phaser.Data.DataManager; + + /** + * The flags that are compared against `RENDER_MASK` to determine if this Game Object will render or not. + * The bits are 0001 | 0010 | 0100 | 1000 set by the components Visible, Alpha, Transform and Texture respectively. + * If those components are not used by your custom class then you can use this bitmask as you wish. + */ + renderFlags: integer; + + /** + * A bitmask that controls if this Game Object is drawn by a Camera or not. + * Not usually set directly, instead call `Camera.ignore`, however you can + * set this property directly using the Camera.id property: + */ + cameraFilter: number; + + /** + * If this Game Object is enabled for input then this property will contain an InteractiveObject instance. + * Not usually set directly. Instead call `GameObject.setInteractive()`. + */ + input: Phaser.Types.Input.InteractiveObject; + + /** + * If this Game Object is enabled for physics then this property will contain a reference to a Physics Body. + */ + body: object | Phaser.Physics.Arcade.Body | Phaser.Physics.Impact.Body; + + /** + * This Game Object will ignore all calls made to its destroy method if this flag is set to `true`. + * This includes calls that may come from a Group, Container or the Scene itself. + * While it allows you to persist a Game Object across Scenes, please understand you are entirely + * responsible for managing references to and from this Game Object. + */ + ignoreDestroy: boolean; + + /** + * Sets the `active` property of this Game Object and returns this Game Object for further chaining. + * A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. + * @param value True if this Game Object should be set as active, false if not. + */ + setActive(value: boolean): this; + + /** + * Sets the `name` property of this Game Object and returns this Game Object for further chaining. + * The `name` property is not populated by Phaser and is presented for your own use. + * @param value The name to be given to this Game Object. + */ + setName(value: string): this; + + /** + * Sets the current state of this Game Object. + * + * Phaser itself will never modify the State of a Game Object, although plugins may do so. + * + * For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. + * The state value should typically be an integer (ideally mapped to a constant + * in your game code), but could also be a string. It is recommended to keep it light and simple. + * If you need to store complex data about your Game Object, look at using the Data Component instead. + * @param value The state of the Game Object. + */ + setState(value: integer | string): this; + + /** + * Adds a Data Manager component to this Game Object. + */ + setDataEnabled(): this; + + /** + * Allows you to store a key value pair within this Game Objects Data Manager. + * + * If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled + * before setting the value. + * + * If the key doesn't already exist in the Data Manager then it is created. + * + * ```javascript + * sprite.setData('name', 'Red Gem Stone'); + * ``` + * + * You can also pass in an object of key value pairs as the first argument: + * + * ```javascript + * sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); + * ``` + * + * To get a value back again you can call `getData`: + * + * ```javascript + * sprite.getData('gold'); + * ``` + * + * Or you can access the value directly via the `values` property, where it works like any other variable: + * + * ```javascript + * sprite.data.values.gold += 50; + * ``` + * + * When the value is first set, a `setdata` event is emitted from this Game Object. + * + * If the key already exists, a `changedata` event is emitted instead, along an event named after the key. + * For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. + * These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. + * + * Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. + * This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. + * @param key The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. + * @param data The value to set for the given key. If an object is provided as the key this argument is ignored. + */ + setData(key: string | object, data?: any): this; + + /** + * Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. + * + * You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: + * + * ```javascript + * sprite.getData('gold'); + * ``` + * + * Or access the value directly: + * + * ```javascript + * sprite.data.values.gold; + * ``` + * + * You can also pass in an array of keys, in which case an array of values will be returned: + * + * ```javascript + * sprite.getData([ 'gold', 'armor', 'health' ]); + * ``` + * + * This approach is useful for destructuring arrays in ES6. + * @param key The key of the value to retrieve, or an array of keys. + */ + getData(key: string | string[]): any; + + /** + * 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. + * @param shape 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 callback A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. + * @param dropZone Should this Game Object be treated as a drop zone target? Default false. + */ + setInteractive(shape?: Phaser.Types.Input.InputConfiguration | any, callback?: Phaser.Types.Input.HitAreaCallback, dropZone?: boolean): this; + + /** + * If this Game Object has previously been enabled for input, this will disable it. + * + * An object that is disabled for input stops processing or being considered for + * input events, but can be turned back on again at any time by simply calling + * `setInteractive()` with no arguments provided. + * + * If want to completely remove interaction from this Game Object then use `removeInteractive` instead. + */ + disableInteractive(): this; + + /** + * If this Game Object has previously been enabled for input, this will queue it + * for removal, causing it to no longer be interactive. The removal happens on + * the next game step, it is not immediate. + * + * The Interactive Object that was assigned to this Game Object will be destroyed, + * removed from the Input Manager and cleared from this Game Object. + * + * If you wish to re-enable this Game Object at a later date you will need to + * re-create its InteractiveObject by calling `setInteractive` again. + * + * If you wish to only temporarily stop an object from receiving input then use + * `disableInteractive` instead, as that toggles the interactive state, where-as + * this erases it completely. + * + * If you wish to resize a hit area, don't remove and then set it as being + * interactive. Instead, access the hitarea object directly and resize the shape + * being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the + * shape is a Rectangle, which it is by default.) + */ + removeInteractive(): this; + + /** + * To be overridden by custom GameObjects. Allows base objects to be used in a Pool. + * @param args args + */ + update(...args: any[]): void; + + /** + * Returns a JSON representation of the Game Object. + */ + toJSON(): Phaser.Types.GameObjects.JSONGameObject; + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * Also checks the Game Object against the given Cameras exclusion list. + * @param camera The Camera to check against this Game Object. + */ + willRender(camera: Phaser.Cameras.Scene2D.Camera): boolean; + + /** + * Returns an array containing the display list index of either this Game Object, or if it has one, + * its parent Container. It then iterates up through all of the parent containers until it hits the + * root of the display list (which is index 0 in the returned array). + * + * Used internally by the InputPlugin but also useful if you wish to find out the display depth of + * this Game Object and all of its ancestors. + */ + getIndexList(): integer[]; + + /** + * Destroys this Game Object removing it from the Display List and Update List and + * severing all ties to parent resources. + * + * Also removes itself from the Input Manager and Physics Manager if previously enabled. + * + * Use this to remove a Game Object from your game if you don't ever plan to use it again. + * As long as no reference to it exists within your own code it should become free for + * garbage collection by the browser. + * + * If you just want to temporarily disable an object then look at using the + * Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. + * @param fromScene Is this Game Object being destroyed as the result of a Scene shutdown? Default false. + */ + destroy(fromScene?: boolean): void; + + /** + * The bitmask that `GameObject.renderFlags` is compared against to determine if the Game Object will render or not. + */ + static readonly RENDER_MASK: integer; + + } + + /** + * The Game Object Creator is a Scene plugin that allows you to quickly create many common + * types of Game Objects and return them. Unlike the Game Object Factory, they are not automatically + * added to the Scene. + * + * Game Objects directly register themselves with the Creator and inject their own creation + * methods into the class. + */ + class GameObjectCreator { + /** + * + * @param scene The Scene to which this Game Object Factory belongs. + */ + constructor(scene: Phaser.Scene); + + /** + * Creates a new Dynamic Bitmap Text Game Object and returns it. + * + * Note: This method will only be available if the Dynamic Bitmap Text Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + dynamicBitmapText(config: Phaser.Types.GameObjects.BitmapText.BitmapTextConfig, addToScene?: boolean): Phaser.GameObjects.DynamicBitmapText; + + /** + * Creates a new Bitmap Text Game Object and returns it. + * + * Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + bitmapText(config: Phaser.Types.GameObjects.BitmapText.BitmapTextConfig, addToScene?: boolean): Phaser.GameObjects.BitmapText; + + /** + * Creates a new Blitter Game Object and returns it. + * + * Note: This method will only be available if the Blitter Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + blitter(config: object, addToScene?: boolean): Phaser.GameObjects.Blitter; + + /** + * Creates a new Container Game Object and returns it. + * + * Note: This method will only be available if the Container Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + container(config: object, addToScene?: boolean): Phaser.GameObjects.Container; + + /** + * The Scene to which this Game Object Creator belongs. + */ + protected scene: Phaser.Scene; + + /** + * A reference to the Scene.Systems. + */ + protected systems: Phaser.Scenes.Systems; + + /** + * A reference to the Scene Display List. + */ + protected displayList: Phaser.GameObjects.DisplayList; + + /** + * A reference to the Scene Update List. + */ + protected updateList: Phaser.GameObjects.UpdateList; + + /** + * Creates a new Graphics Game Object and returns it. + * + * Note: This method will only be available if the Graphics Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + graphics(config: object, addToScene?: boolean): Phaser.GameObjects.Graphics; + + /** + * Creates a new Group Game Object and returns it. + * + * Note: This method will only be available if the Group Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + */ + group(config: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.GameObjects.Group; + + /** + * Creates a new Image Game Object and returns it. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + image(config: object, addToScene?: boolean): Phaser.GameObjects.Image; + + /** + * Creates a new Mesh Game Object and returns it. + * + * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + mesh(config: object, addToScene?: boolean): Phaser.GameObjects.Mesh; + + /** + * Creates a new Particle Emitter Manager Game Object and returns it. + * + * Note: This method will only be available if the Particles Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + particles(config: object, addToScene?: boolean): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Creates a new Quad Game Object and returns it. + * + * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + quad(config: object, addToScene?: boolean): Phaser.GameObjects.Quad; + + /** + * Creates a new Render Texture Game Object and returns it. + * + * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + renderTexture(config: Phaser.Types.GameObjects.RenderTexture.RenderTextureConfig, addToScene?: boolean): Phaser.GameObjects.RenderTexture; + + /** + * Creates a new Shader Game Object and returns it. + * + * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + shader(config: object, addToScene?: boolean): Phaser.GameObjects.Shader; + + /** + * Creates a new Sprite Game Object and returns it. + * + * Note: This method will only be available if the Sprite Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + sprite(config: Phaser.Types.GameObjects.Sprite.SpriteConfig, addToScene?: boolean): Phaser.GameObjects.Sprite; + + /** + * Creates a new Text Game Object and returns it. + * + * Note: This method will only be available if the Text Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + text(config: object, addToScene?: boolean): Phaser.GameObjects.Text; + + /** + * Creates a new TileSprite Game Object and returns it. + * + * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + tileSprite(config: Phaser.Types.GameObjects.TileSprite.TileSpriteConfig, addToScene?: boolean): Phaser.GameObjects.TileSprite; + + /** + * Creates a new Video Game Object and returns it. + * + * Note: This method will only be available if the Video Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + * @param addToScene Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object. + */ + video(config: object, addToScene?: boolean): Phaser.GameObjects.Video; + + /** + * Creates a new Zone Game Object and returns it. + * + * Note: This method will only be available if the Zone Game Object has been built into Phaser. + * @param config The configuration object this Game Object will use to create itself. + */ + zone(config: object): Phaser.GameObjects.Zone; + + /** + * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. + * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing + * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map + * data. For an empty map, you should specify tileWidth, tileHeight, width & height. + * @param config The config options for the Tilemap. + */ + tilemap(config?: Phaser.Types.Tilemaps.TilemapConfig): Phaser.Tilemaps.Tilemap; + + /** + * Creates a new Tween object and returns it. + * + * Note: This method will only be available if Tweens have been built into Phaser. + * @param config The Tween configuration. + */ + tween(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; + + } + + /** + * The Game Object Factory is a Scene plugin that allows you to quickly create many common + * types of Game Objects and have them automatically registered with the Scene. + * + * Game Objects directly register themselves with the Factory and inject their own creation + * methods into the class. + */ + class GameObjectFactory { + /** + * + * @param scene The Scene to which this Game Object Factory belongs. + */ + constructor(scene: Phaser.Scene); + + /** + * Creates a new Path Object. + * @param x The horizontal position of this Path. + * @param y The vertical position of this Path. + */ + path(x: number, y: number): Phaser.Curves.Path; + + /** + * 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 for 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): 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. + * @param x The x position of the Game Object. + * @param y The y position of the Game Object. + * @param font The key of the font to use from the BitmapFont cache. + * @param text The string, or array of strings, to be set as the content of this Bitmap Text. + * @param size The font size to set. + */ + dynamicBitmapText(x: number, y: number, font: string, text?: string | string[], size?: number): Phaser.GameObjects.DynamicBitmapText; + + /** + * 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 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): 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. + * @param x The x position of the Game Object. + * @param y The y position of the Game Object. + * @param font The key of the font to use from the BitmapFont cache. + * @param text The string, or array of strings, to be set as the content of this Bitmap Text. + * @param size The font size to set. + * @param align The alignment of the text in a multi-line BitmapText object. Default 0. + */ + bitmapText(x: number, y: number, font: string, text?: string | string[], size?: number, align?: integer): Phaser.GameObjects.BitmapText; + + /** + * Creates a new Blitter Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Blitter Game Object has been built into Phaser. + * @param x The x position of the Game Object. + * @param y The y position of the Game Object. + * @param key The key of the Texture the Blitter object will use. + * @param frame The default Frame children of the Blitter will use. + */ + blitter(x: number, y: number, key: string, frame?: string | integer): Phaser.GameObjects.Blitter; + + /** + * Creates a new Container Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Container Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param children An optional array of Game Objects to add to this Container. + */ + container(x: number, y: number, children?: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[]): Phaser.GameObjects.Container; + + /** + * DOM Element Game Objects are a way to control and manipulate HTML Elements over the top of your game. + * + * In order for DOM Elements to display you have to enable them by adding the following to your game + * configuration object: + * + * ```javascript + * dom { + * createContainer: true + * } + * ``` + * + * When this is added, Phaser will automatically create a DOM Container div that is positioned over the top + * of the game canvas. This div is sized to match the canvas, and if the canvas size changes, as a result of + * settings within the Scale Manager, the dom container is resized accordingly. + * + * You can create a DOM Element by either passing in DOMStrings, or by passing in a reference to an existing + * Element that you wish to be placed under the control of Phaser. For example: + * + * ```javascript + * this.add.dom(x, y, 'div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser'); + * ``` + * + * The above code will insert a div element into the DOM Container at the given x/y coordinate. The DOMString in + * the 4th argument sets the initial CSS style of the div and the final argument is the inner text. In this case, + * it will create a lime colored div that is 220px by 100px in size with the text Phaser in it, in an Arial font. + * + * You should nearly always, without exception, use explicitly sized HTML Elements, in order to fully control + * alignment and positioning of the elements next to regular game content. + * + * Rather than specify the CSS and HTML directly you can use the `load.html` File Loader to load it into the + * cache and then use the `createFromCache` method instead. You can also use `createFromHTML` and various other + * methods available in this class to help construct your elements. + * + * Once the element has been created you can then control it like you would any other Game Object. You can set its + * position, scale, rotation, alpha and other properties. It will move as the main Scene Camera moves and be clipped + * at the edge of the canvas. It's important to remember some limitations of DOM Elements: The obvious one is that + * they appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have + * a DOM Element, then a Sprite, then another DOM Element behind it. + * + * They also cannot be enabled for input. To do that, you have to use the `addListener` method to add native event + * listeners directly. The final limitation is to do with cameras. The DOM Container is sized to match the game canvas + * entirely and clipped accordingly. DOM Elements respect camera scrolling and scrollFactor settings, but if you + * change the size of the camera so it no longer matches the size of the canvas, they won't be clipped accordingly. + * + * Also, all DOM Elements are inserted into the same DOM Container, regardless of which Scene they are created in. + * + * DOM Elements are a powerful way to align native HTML with your Phaser Game Objects. For example, you can insert + * a login form for a multiplayer game directly into your title screen. Or a text input box for a highscore table. + * Or a banner ad from a 3rd party service. Or perhaps you'd like to use them for high resolution text display and + * UI. The choice is up to you, just remember that you're dealing with standard HTML and CSS floating over the top + * of your game, and should treat it accordingly. + * + * Note: This method will only be available if the DOM Element Game Object has been built into Phaser. + * @param x The horizontal position of this DOM Element in the world. + * @param y The vertical position of this DOM Element in the world. + * @param element An existing DOM element, or a string. If a string starting with a # it will do a `getElementById` look-up on the string (minus the hash). Without a hash, it represents the type of element to create, i.e. 'div'. + * @param style If a string, will be set directly as the elements `style` property value. If a plain object, will be iterated and the values transferred. In both cases the values replacing whatever CSS styles may have been previously set. + * @param innerText If given, will be set directly as the elements `innerText` property value, replacing whatever was there before. + */ + dom(x: number, y: number, element?: HTMLElement | string, style?: string | any, innerText?: string): Phaser.GameObjects.DOMElement; + + /** + * Creates a new Extern Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Extern Game Object has been built into Phaser. + */ + extern(): Phaser.GameObjects.Extern; + + /** + * The Scene to which this Game Object Factory belongs. + */ + protected scene: Phaser.Scene; + + /** + * A reference to the Scene.Systems. + */ + protected systems: Phaser.Scenes.Systems; + + /** + * A reference to the Scene Display List. + */ + protected displayList: Phaser.GameObjects.DisplayList; + + /** + * A reference to the Scene Update List. + */ + protected updateList: Phaser.GameObjects.UpdateList; + + /** + * Adds an existing Game Object to this Scene. + * + * If the Game Object renders, it will be added to the Display List. + * If it has a `preUpdate` method, it will be added to the Update List. + * @param child The child to be added to this Scene. + */ + existing(child: Phaser.GameObjects.GameObject | Phaser.GameObjects.Group): Phaser.GameObjects.GameObject; + + /** + * Static method called directly by the Game Object factory functions. + * With this method you can register a custom GameObject factory in the GameObjectFactory, + * providing a name (`factoryType`) and the constructor (`factoryFunction`) in order + * to be called when you call to Phaser.Scene.add[ factoryType ] method. + * @param factoryType The key of the factory that you will use to call to Phaser.Scene.add[ factoryType ] method. + * @param factoryFunction The constructor function to be called when you invoke to the Phaser.Scene.add method. + */ + static register(factoryType: string, factoryFunction: Function): void; + + /** + * Static method called directly by the Game Object factory functions. + * With this method you can remove a custom GameObject factory registered in the GameObjectFactory, + * providing a its `factoryType`. + * @param factoryType The key of the factory that you want to remove from the GameObjectFactory. + */ + static remove(factoryType: string): void; + + /** + * Creates a new Graphics Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Graphics Game Object has been built into Phaser. + * @param config The Graphics configuration. + */ + graphics(config?: Phaser.Types.GameObjects.Graphics.Options): Phaser.GameObjects.Graphics; + + /** + * Creates a new Group Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Group Game Object has been built into Phaser. + * @param children Game Objects to add to this Group; or the `config` argument. + * @param config A Group Configuration object. + */ + group(children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupConfig[], config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.GameObjects.Group; + + /** + * Creates a new Image Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + image(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Image; + + /** + * Creates a new Mesh Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Mesh Game Object and WebGL support have been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param vertices An array containing the vertices data for this Mesh. + * @param uv An array containing the uv data for this Mesh. + * @param colors An array containing the color data for this Mesh. + * @param alphas An array containing the alpha data for this Mesh. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + mesh(x: number, y: number, vertices: number[], uv: number[], colors: number[], alphas: number[], texture: string, frame?: string | integer): Phaser.GameObjects.Mesh; + + /** + * Creates a new Particle Emitter Manager Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Particles Game Object has been built into Phaser. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + * @param emitters Configuration settings for one or more emitters to create. + */ + particles(texture: string, frame?: string | integer | object, emitters?: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Creates a new PathFollower Game Object and adds it to the Scene. + * + * Note: This method will only be available if the PathFollower Game Object has been built into Phaser. + * @param path The Path this PathFollower is connected to. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + follower(path: Phaser.Curves.Path, x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.PathFollower; + + /** + * Creates a new Quad Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Quad Game Object and WebGL support have been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + quad(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Quad; + + /** + * Creates a new Render Texture Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Render Texture Game Object has been built into Phaser. + * + * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and + * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic + * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param width The width of the Render Texture. Default 32. + * @param height The height of the Render Texture. Default 32. + */ + renderTexture(x: number, y: number, width?: integer, height?: integer): Phaser.GameObjects.RenderTexture; + + /** + * Creates a new Shader Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Shader Game Object and WebGL support have been built into Phaser. + * @param key The key of the shader to use from the shader cache, or a BaseShader instance. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the Game Object. Default 128. + * @param height The height of the Game Object. Default 128. + * @param textures Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param textureData Optional additional texture data. + */ + shader(key: string | Phaser.Display.BaseShader, x?: number, y?: number, width?: number, height?: number, textures?: string[], textureData?: object): Phaser.GameObjects.Shader; + + /** + * Creates a new Arc Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Arc Game Object has been built into Phaser. + * + * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an arc shape. You can control the start and end angles of the arc, + * as well as if the angles are winding clockwise or anti-clockwise. With the default settings + * it renders as a complete circle. By changing the angles you can create other arc shapes, + * such as half-circles. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param radius The radius of the arc. Default 128. + * @param startAngle The start angle of the arc, in degrees. Default 0. + * @param endAngle The end angle of the arc, in degrees. Default 360. + * @param anticlockwise The winding order of the start and end angles. Default false. + * @param fillColor The color the arc will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + arc(x?: number, y?: number, radius?: number, startAngle?: integer, endAngle?: integer, anticlockwise?: boolean, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Arc; + + /** + * Creates a new Circle Shape Game Object and adds it to the Scene. + * + * A Circle is an Arc with no defined start and end angle, making it render as a complete circle. + * + * Note: This method will only be available if the Arc Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param radius The radius of the circle. Default 128. + * @param fillColor The color the circle will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the circle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + circle(x?: number, y?: number, radius?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Arc; + + /** + * Creates a new Curve Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Curve Game Object has been built into Phaser. + * + * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to + * the Curve Shape in the constructor. + * + * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param curve The Curve object to use to create the Shape. + * @param fillColor The color the curve will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + curve(x?: number, y?: number, curve?: Phaser.Curves.Curve, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Curve; + + /** + * Creates a new Ellipse Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Ellipse Game Object has been built into Phaser. + * + * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. + * If the width and height match it will render as a circle. If the width is less than the height, + * it will look more like an egg shape. + * + * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. + * @param height The height of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. + * @param fillColor The color the ellipse will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + ellipse(x?: number, y?: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Ellipse; + + /** + * Creates a new Grid Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Grid Game Object has been built into Phaser. + * + * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * A Grid Shape allows you to display a grid in your game, where you can control the size of the + * grid as well as the width and height of the grid cells. You can set a fill color for each grid + * cell as well as an alternate fill color. When the alternate fill color is set then the grid + * cells will alternate the fill colors as they render, creating a chess-board effect. You can + * also optionally have an outline fill color. If set, this draws lines between the grid cells + * in the given color. If you specify an outline color with an alpha of zero, then it will draw + * the cells spaced out, but without the lines between them. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the grid. Default 128. + * @param height The height of the grid. Default 128. + * @param cellWidth The width of one cell in the grid. Default 32. + * @param cellHeight The height of one cell in the grid. Default 32. + * @param fillColor The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * @param outlineFillColor The color of the lines between the grid cells. + * @param outlineFillAlpha The alpha of the lines between the grid cells. + */ + grid(x?: number, y?: number, width?: number, height?: number, cellWidth?: number, cellHeight?: number, fillColor?: number, fillAlpha?: number, outlineFillColor?: number, outlineFillAlpha?: number): Phaser.GameObjects.Grid; + + /** + * Creates a new IsoBox Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the IsoBox Game Object has been built into Phaser. + * + * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set + * the color of the top, left and right faces of the rectangle respectively. You can also choose + * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting + * the `projection` property. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param size The width of the iso box in pixels. The left and right faces will be exactly half this value. Default 48. + * @param height The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. Default 32. + * @param fillTop The fill color of the top face of the iso box. Default 0xeeeeee. + * @param fillLeft The fill color of the left face of the iso box. Default 0x999999. + * @param fillRight The fill color of the right face of the iso box. Default 0xcccccc. + */ + isobox(x?: number, y?: number, size?: number, height?: number, fillTop?: number, fillLeft?: number, fillRight?: number): Phaser.GameObjects.IsoBox; + + /** + * Creates a new IsoTriangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser. + * + * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different + * fill color. You can set the color of the top, left and right faces of the triangle respectively + * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting + * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside + * down or not. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param size The width of the iso triangle in pixels. The left and right faces will be exactly half this value. Default 48. + * @param height The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. Default 32. + * @param reversed Is the iso triangle upside down? Default false. + * @param fillTop The fill color of the top face of the iso triangle. Default 0xeeeeee. + * @param fillLeft The fill color of the left face of the iso triangle. Default 0x999999. + * @param fillRight The fill color of the right face of the iso triangle. Default 0xcccccc. + */ + isotriangle(x?: number, y?: number, size?: number, height?: number, reversed?: boolean, fillTop?: number, fillLeft?: number, fillRight?: number): Phaser.GameObjects.IsoTriangle; + + /** + * Creates a new Line Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Line Game Object has been built into Phaser. + * + * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only stroke colors and cannot be filled. + * + * A Line Shape allows you to draw a line between two points in your game. You can control the + * stroke color and thickness of the line. In WebGL only you can also specify a different + * thickness for the start and end of the line, allowing you to render lines that taper-off. + * + * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param x1 The horizontal position of the start of the line. Default 0. + * @param y1 The vertical position of the start of the line. Default 0. + * @param x2 The horizontal position of the end of the line. Default 128. + * @param y2 The vertical position of the end of the line. Default 0. + * @param strokeColor The color the line will be drawn in, i.e. 0xff0000 for red. + * @param strokeAlpha The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. + */ + line(x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, strokeColor?: number, strokeAlpha?: number): Phaser.GameObjects.Line; + + /** + * Creates a new Polygon Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Polygon Game Object has been built into Phaser. + * + * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Polygon Shape is created by providing a list of points, which are then used to create an + * internal Polygon geometry object. The points can be set from a variety of formats: + * + * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending + * on the coordinates of the points provided, the final shape may be rendered offset from its origin. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param points The points that make up the polygon. + * @param fillColor The color the polygon will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + polygon(x?: number, y?: number, points?: any, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Polygon; + + /** + * Creates a new Rectangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Rectangle Game Object has been built into Phaser. + * + * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * You can change the size of the rectangle by changing the `width` and `height` properties. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the rectangle. Default 128. + * @param height The height of the rectangle. Default 128. + * @param fillColor The color the rectangle will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + rectangle(x?: number, y?: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Rectangle; + + /** + * Creates a new Star Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Star Game Object has been built into Phaser. + * + * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * As the name implies, the Star shape will display a star in your game. You can control several + * aspects of it including the number of points that constitute the star. The default is 5. If + * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky + * star shape. + * + * You can also control the inner and outer radius, which is how 'long' each point of the star is. + * Modify these values to create more interesting shapes. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param points The number of points on the star. Default 5. + * @param innerRadius The inner radius of the star. Default 32. + * @param outerRadius The outer radius of the star. Default 64. + * @param fillColor The color the star will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + star(x?: number, y?: number, points?: number, innerRadius?: number, outerRadius?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Star; + + /** + * Creates a new Triangle Shape Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Triangle Game Object has been built into Phaser. + * + * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the + * position of each point of these lines. The triangle is always closed and cannot have an open + * face. If you require that, consider using a Polygon instead. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param x1 The horizontal position of the first point in the triangle. Default 0. + * @param y1 The vertical position of the first point in the triangle. Default 128. + * @param x2 The horizontal position of the second point in the triangle. Default 64. + * @param y2 The vertical position of the second point in the triangle. Default 0. + * @param x3 The horizontal position of the third point in the triangle. Default 128. + * @param y3 The vertical position of the third point in the triangle. Default 128. + * @param fillColor The color the triangle will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + triangle(x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number, fillColor?: number, fillAlpha?: number): Phaser.GameObjects.Triangle; + + /** + * Creates a new Sprite Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Sprite Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + sprite(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Sprite; + + /** + * Creates a new Text Game Object and adds it to the Scene. + * + * 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. + * + * You can only display fonts that are currently loaded and available to the browser: therefore fonts must + * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, + * or have the fonts ready 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. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param text The text this Text object will display. + * @param style The Text style configuration object. + */ + text(x: number, y: number, text: string | string[], style?: object): Phaser.GameObjects.Text; + + /** + * Creates a new TileSprite Game Object and adds it to the Scene. + * + * Note: This method will only be available if the TileSprite Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param width The width of the Game Object. If zero it will use the size of the texture frame. + * @param height The height of the Game Object. If zero it will use the size of the texture frame. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + tileSprite(x: number, y: number, width: integer, height: integer, texture: string, frame?: string | integer): Phaser.GameObjects.TileSprite; + + /** + * Creates a new Image Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Image Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + video(x: number, y: number, texture: string, frame?: string | integer): Phaser.GameObjects.Image; + + /** + * Creates a new Zone Game Object and adds it to the Scene. + * + * Note: This method will only be available if the Zone Game Object has been built into Phaser. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param width The width of the Game Object. + * @param height The height of the Game Object. + */ + zone(x: number, y: number, width: number, height: number): Phaser.GameObjects.Zone; + + /** + * Creates a Tilemap from the given key or data, or creates a blank Tilemap if no key/data provided. + * When loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing + * from a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map + * data. For an empty map, you should specify tileWidth, tileHeight, width & height. + * @param key The key in the Phaser cache that corresponds to the loaded tilemap data. + * @param tileWidth The width of a tile in pixels. Pass in `null` to leave as the + * default. Default 32. + * @param tileHeight The height of a tile in pixels. Pass in `null` to leave as the + * default. Default 32. + * @param width The width of the map in tiles. Pass in `null` to leave as the + * default. Default 10. + * @param height The height of the map in tiles. Pass in `null` to leave as the + * default. Default 10. + * @param data Instead of loading from the cache, you can also load directly from + * a 2D array of tile indexes. Pass in `null` for no data. + * @param 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've 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. Default false. + */ + tilemap(key?: string, tileWidth?: integer, tileHeight?: integer, width?: integer, height?: integer, data?: integer[][], insertNull?: boolean): Phaser.Tilemaps.Tilemap; + + /** + * Creates a new Tween object. + * + * Note: This method will only be available if Tweens have been built into Phaser. + * @param config The Tween configuration. + */ + tween(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; + + } + + /** + * 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. + * + * 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 implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible, Phaser.GameObjects.Components.ScrollFactor { + /** + * + * @param scene The Scene to which this Graphics object belongs. + * @param options Options that set the position and default style of this Graphics object. + */ + constructor(scene: Phaser.Scene, options?: Phaser.Types.GameObjects.Graphics.Options); + + /** + * The horizontal display origin of the Graphics. + */ + displayOriginX: number; + + /** + * The vertical display origin of the Graphics. + */ + displayOriginY: number; + + /** + * The array of commands used to render the Graphics. + */ + commandBuffer: any[]; + + /** + * The default fill color for shapes rendered by this Graphics object. + */ + defaultFillColor: number; + + /** + * The default fill alpha for shapes rendered by this Graphics object. + */ + defaultFillAlpha: number; + + /** + * The default stroke width for shapes rendered by this Graphics object. + */ + defaultStrokeWidth: number; + + /** + * The default stroke color for shapes rendered by this Graphics object. + */ + defaultStrokeColor: number; + + /** + * The default stroke alpha for shapes rendered by this Graphics object. + */ + defaultStrokeAlpha: number; + + /** + * Set the default style settings for this Graphics object. + * @param options The styles to set as defaults. + */ + setDefaultStyles(options: Phaser.Types.GameObjects.Graphics.Styles): Phaser.GameObjects.Graphics; + + /** + * Set the current line style. + * @param lineWidth The stroke width. + * @param color The stroke color. + * @param alpha The stroke alpha. Default 1. + */ + lineStyle(lineWidth: number, color: number, alpha?: number): Phaser.GameObjects.Graphics; + + /** + * Set the current fill style. + * @param color The fill color. + * @param alpha The fill alpha. Default 1. + */ + fillStyle(color: number, alpha?: number): Phaser.GameObjects.Graphics; + + /** + * Sets a gradient fill style. This is a WebGL only feature. + * + * The gradient color values represent the 4 corners of an untransformed rectangle. + * The gradient is used to color all filled shapes and paths drawn after calling this method. + * If you wish to turn a gradient off, call `fillStyle` and provide a new single fill color. + * + * When filling a triangle only the first 3 color values provided are used for the 3 points of a triangle. + * + * This feature is best used only on rectangles and triangles. All other shapes will give strange results. + * + * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used + * will be filled with a gradient on its own. There is no ability to gradient fill a shape or path as a single + * entity at this time. + * @param topLeft The tint being applied to the top-left of the Game Object. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + * @param alpha The fill alpha. Default 1. + */ + fillGradientStyle(topLeft: integer, topRight: integer, bottomLeft: integer, bottomRight: integer, alpha?: number): Phaser.GameObjects.Graphics; + + /** + * Sets a gradient line style. This is a WebGL only feature. + * + * The gradient color values represent the 4 corners of an untransformed rectangle. + * The gradient is used to color all stroked shapes and paths drawn after calling this method. + * If you wish to turn a gradient off, call `lineStyle` and provide a new single line color. + * + * This feature is best used only on single lines. All other shapes will give strange results. + * + * Note that for objects such as arcs or ellipses, or anything which is made out of triangles, each triangle used + * will be filled with a gradient on its own. There is no ability to gradient stroke a shape or path as a single + * entity at this time. + * @param lineWidth The stroke width. + * @param topLeft The tint being applied to the top-left of the Game Object. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + * @param alpha The fill alpha. Default 1. + */ + lineGradientStyle(lineWidth: number, topLeft: integer, topRight: integer, bottomLeft: integer, bottomRight: integer, alpha?: number): Phaser.GameObjects.Graphics; + + /** + * Sets the texture frame this Graphics Object will use when drawing all shapes defined after calling this. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * Once set, all shapes will use this texture. Call this method with no arguments to clear it. + * + * The textures are not tiled. They are stretched to the dimensions of the shapes being rendered. For this reason, + * it works best with seamless / tileable textures. + * + * The mode argument controls how the textures are combined with the fill colors. The default value (0) will + * multiply the texture by the fill color. A value of 1 will use just the fill color, but the alpha data from the texture, + * and a value of 2 will use just the texture and no fill color at all. + * @param key The key of the texture to be used, as stored in the Texture Manager. Leave blank to clear a previously set texture. + * @param frame The name or index of the frame within the Texture. + * @param mode The texture tint mode. 0 is multiply, 1 is alpha only and 2 is texture only. Default 0. + */ + setTexture(key?: string, frame?: string | integer, mode?: number): this; + + /** + * Start a new shape path. + */ + beginPath(): Phaser.GameObjects.Graphics; + + /** + * Close the current path. + */ + closePath(): Phaser.GameObjects.Graphics; + + /** + * Fill the current path. + */ + fillPath(): Phaser.GameObjects.Graphics; + + /** + * Fill the current path. + * + * This is an alias for `Graphics.fillPath` and does the same thing. + * It was added to match the CanvasRenderingContext 2D API. + */ + fill(): Phaser.GameObjects.Graphics; + + /** + * Stroke the current path. + */ + strokePath(): Phaser.GameObjects.Graphics; + + /** + * Stroke the current path. + * + * This is an alias for `Graphics.strokePath` and does the same thing. + * It was added to match the CanvasRenderingContext 2D API. + */ + stroke(): Phaser.GameObjects.Graphics; + + /** + * Fill the given circle. + * @param circle The circle to fill. + */ + fillCircleShape(circle: Phaser.Geom.Circle): Phaser.GameObjects.Graphics; + + /** + * Stroke the given circle. + * @param circle The circle to stroke. + */ + strokeCircleShape(circle: Phaser.Geom.Circle): Phaser.GameObjects.Graphics; + + /** + * Fill a circle with the given position and radius. + * @param x The x coordinate of the center of the circle. + * @param y The y coordinate of the center of the circle. + * @param radius The radius of the circle. + */ + fillCircle(x: number, y: number, radius: number): Phaser.GameObjects.Graphics; + + /** + * Stroke a circle with the given position and radius. + * @param x The x coordinate of the center of the circle. + * @param y The y coordinate of the center of the circle. + * @param radius The radius of the circle. + */ + strokeCircle(x: number, y: number, radius: number): Phaser.GameObjects.Graphics; + + /** + * Fill the given rectangle. + * @param rect The rectangle to fill. + */ + fillRectShape(rect: Phaser.Geom.Rectangle): Phaser.GameObjects.Graphics; + + /** + * Stroke the given rectangle. + * @param rect The rectangle to stroke. + */ + strokeRectShape(rect: Phaser.Geom.Rectangle): Phaser.GameObjects.Graphics; + + /** + * Fill a rectangle with the given position and size. + * @param x The x coordinate of the top-left of the rectangle. + * @param y The y coordinate of the top-left of the rectangle. + * @param width The width of the rectangle. + * @param height The height of the rectangle. + */ + fillRect(x: number, y: number, width: number, height: number): Phaser.GameObjects.Graphics; + + /** + * Stroke a rectangle with the given position and size. + * @param x The x coordinate of the top-left of the rectangle. + * @param y The y coordinate of the top-left of the rectangle. + * @param width The width of the rectangle. + * @param height The height of the rectangle. + */ + strokeRect(x: number, y: number, width: number, height: number): Phaser.GameObjects.Graphics; + + /** + * Fill a rounded rectangle with the given position, size and radius. + * @param x The x coordinate of the top-left of the rectangle. + * @param y The y coordinate of the top-left of the rectangle. + * @param width The width of the rectangle. + * @param height The height of the rectangle. + * @param radius The corner radius; It can also be an object to specify different radii for corners. Default 20. + */ + fillRoundedRect(x: number, y: number, width: number, height: number, radius?: Phaser.Types.GameObjects.Graphics.RoundedRectRadius | number): Phaser.GameObjects.Graphics; + + /** + * Stroke a rounded rectangle with the given position, size and radius. + * @param x The x coordinate of the top-left of the rectangle. + * @param y The y coordinate of the top-left of the rectangle. + * @param width The width of the rectangle. + * @param height The height of the rectangle. + * @param radius The corner radius; It can also be an object to specify different radii for corners. Default 20. + */ + strokeRoundedRect(x: number, y: number, width: number, height: number, radius?: Phaser.Types.GameObjects.Graphics.RoundedRectRadius | number): Phaser.GameObjects.Graphics; + + /** + * Fill the given point. + * + * Draws a square at the given position, 1 pixel in size by default. + * @param point The point to fill. + * @param size The size of the square to draw. Default 1. + */ + fillPointShape(point: Phaser.Geom.Point | Phaser.Math.Vector2 | object, size?: number): Phaser.GameObjects.Graphics; + + /** + * Fill a point at the given position. + * + * Draws a square at the given position, 1 pixel in size by default. + * @param x The x coordinate of the point. + * @param y The y coordinate of the point. + * @param size The size of the square to draw. Default 1. + */ + fillPoint(x: number, y: number, size?: number): Phaser.GameObjects.Graphics; + + /** + * Fill the given triangle. + * @param triangle The triangle to fill. + */ + fillTriangleShape(triangle: Phaser.Geom.Triangle): Phaser.GameObjects.Graphics; + + /** + * Stroke the given triangle. + * @param triangle The triangle to stroke. + */ + strokeTriangleShape(triangle: Phaser.Geom.Triangle): Phaser.GameObjects.Graphics; + + /** + * Fill a triangle with the given points. + * @param x0 The x coordinate of the first point. + * @param y0 The y coordinate of the first point. + * @param x1 The x coordinate of the second point. + * @param y1 The y coordinate of the second point. + * @param x2 The x coordinate of the third point. + * @param y2 The y coordinate of the third point. + */ + fillTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): Phaser.GameObjects.Graphics; + + /** + * Stroke a triangle with the given points. + * @param x0 The x coordinate of the first point. + * @param y0 The y coordinate of the first point. + * @param x1 The x coordinate of the second point. + * @param y1 The y coordinate of the second point. + * @param x2 The x coordinate of the third point. + * @param y2 The y coordinate of the third point. + */ + strokeTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): Phaser.GameObjects.Graphics; + + /** + * Draw the given line. + * @param line The line to stroke. + */ + strokeLineShape(line: Phaser.Geom.Line): Phaser.GameObjects.Graphics; + + /** + * Draw a line between the given points. + * @param x1 The x coordinate of the start point of the line. + * @param y1 The y coordinate of the start point of the line. + * @param x2 The x coordinate of the end point of the line. + * @param y2 The y coordinate of the end point of the line. + */ + lineBetween(x1: number, y1: number, x2: number, y2: number): Phaser.GameObjects.Graphics; + + /** + * Draw a line from the current drawing position to the given position. + * + * Moves the current drawing position to the given position. + * @param x The x coordinate to draw the line to. + * @param y The y coordinate to draw the line to. + */ + lineTo(x: number, y: number): Phaser.GameObjects.Graphics; + + /** + * Move the current drawing position to the given position. + * @param x The x coordinate to move to. + * @param y The y coordinate to move to. + */ + moveTo(x: number, y: number): Phaser.GameObjects.Graphics; + + /** + * Stroke the shape represented by the given array of points. + * + * Pass `closeShape` to automatically close the shape by joining the last to the first point. + * + * Pass `closePath` to automatically close the path before it is stroked. + * @param points The points to stroke. + * @param closeShape When `true`, the shape is closed by joining the last point to the first point. Default false. + * @param closePath When `true`, the path is closed before being stroked. Default false. + * @param endIndex The index of `points` to stop drawing at. Defaults to `points.length`. + */ + strokePoints(points: any[] | Phaser.Geom.Point[], closeShape?: boolean, closePath?: boolean, endIndex?: integer): Phaser.GameObjects.Graphics; + + /** + * Fill the shape represented by the given array of points. + * + * Pass `closeShape` to automatically close the shape by joining the last to the first point. + * + * Pass `closePath` to automatically close the path before it is filled. + * @param points The points to fill. + * @param closeShape When `true`, the shape is closed by joining the last point to the first point. Default false. + * @param closePath When `true`, the path is closed before being stroked. Default false. + * @param endIndex The index of `points` to stop at. Defaults to `points.length`. + */ + fillPoints(points: any[] | Phaser.Geom.Point[], closeShape?: boolean, closePath?: boolean, endIndex?: integer): Phaser.GameObjects.Graphics; + + /** + * Stroke the given ellipse. + * @param ellipse The ellipse to stroke. + * @param smoothness The number of points to draw the ellipse with. Default 32. + */ + strokeEllipseShape(ellipse: Phaser.Geom.Ellipse, smoothness?: integer): Phaser.GameObjects.Graphics; + + /** + * Stroke an ellipse with the given position and size. + * @param x The x coordinate of the center of the ellipse. + * @param y The y coordinate of the center of the ellipse. + * @param width The width of the ellipse. + * @param height The height of the ellipse. + * @param smoothness The number of points to draw the ellipse with. Default 32. + */ + strokeEllipse(x: number, y: number, width: number, height: number, smoothness?: integer): Phaser.GameObjects.Graphics; + + /** + * Fill the given ellipse. + * @param ellipse The ellipse to fill. + * @param smoothness The number of points to draw the ellipse with. Default 32. + */ + fillEllipseShape(ellipse: Phaser.Geom.Ellipse, smoothness?: integer): Phaser.GameObjects.Graphics; + + /** + * Fill an ellipse with the given position and size. + * @param x The x coordinate of the center of the ellipse. + * @param y The y coordinate of the center of the ellipse. + * @param width The width of the ellipse. + * @param height The height of the ellipse. + * @param smoothness The number of points to draw the ellipse with. Default 32. + */ + fillEllipse(x: number, y: number, width: number, height: number, smoothness?: integer): Phaser.GameObjects.Graphics; + + /** + * Draw an arc. + * + * This method can be used to create circles, or parts of circles. + * + * Make sure you call `beginPath` before starting the arc unless you wish for the arc to automatically + * close when filled or stroked. + * + * Use the optional `overshoot` argument increase the number of iterations that take place when + * the arc is rendered in WebGL. This is useful if you're drawing an arc with an especially thick line, + * as it will allow the arc to fully join-up. Try small values at first, i.e. 0.01. + * + * Call {@link Phaser.GameObjects.Graphics#fillPath} or {@link Phaser.GameObjects.Graphics#strokePath} after calling + * this method to draw the arc. + * @param x The x coordinate of the center of the circle. + * @param y The y coordinate of the center of the circle. + * @param radius The radius of the circle. + * @param startAngle The starting angle, in radians. + * @param endAngle The ending angle, in radians. + * @param anticlockwise Whether the drawing should be anticlockwise or clockwise. Default false. + * @param overshoot This value allows you to increase the segment iterations in WebGL rendering. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Use small numbers such as 0.01 to start with and increase as needed. Default 0. + */ + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean, overshoot?: number): Phaser.GameObjects.Graphics; + + /** + * Creates a pie-chart slice shape centered at `x`, `y` with the given radius. + * You must define the start and end angle of the slice. + * + * Setting the `anticlockwise` argument to `true` creates a shape similar to Pacman. + * Setting it to `false` creates a shape like a slice of pie. + * + * This method will begin a new path and close the path at the end of it. + * To display the actual slice you need to call either `strokePath` or `fillPath` after it. + * @param x The horizontal center of the slice. + * @param y The vertical center of the slice. + * @param radius The radius of the slice. + * @param startAngle The start angle of the slice, given in radians. + * @param endAngle The end angle of the slice, given in radians. + * @param anticlockwise Whether the drawing should be anticlockwise or clockwise. Default false. + * @param overshoot This value allows you to overshoot the endAngle by this amount. Useful if the arc has a thick stroke and needs to overshoot to join-up cleanly. Default 0. + */ + slice(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean, overshoot?: number): Phaser.GameObjects.Graphics; + + /** + * Saves the state of the Graphics by pushing the current state onto a stack. + * + * The most recently saved state can then be restored with {@link Phaser.GameObjects.Graphics#restore}. + */ + save(): Phaser.GameObjects.Graphics; + + /** + * Restores the most recently saved state of the Graphics by popping from the state stack. + * + * Use {@link Phaser.GameObjects.Graphics#save} to save the current state, and call this afterwards to restore that state. + * + * If there is no saved state, this command does nothing. + */ + restore(): Phaser.GameObjects.Graphics; + + /** + * Inserts a translation command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be translated + * by the given amount. + * + * This does not change the position of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * @param x The horizontal translation to apply. + * @param y The vertical translation to apply. + */ + translateCanvas(x: number, y: number): Phaser.GameObjects.Graphics; + + /** + * Inserts a scale command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be scaled + * by the given amount. + * + * This does not change the scale of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * @param x The horizontal scale to apply. + * @param y The vertical scale to apply. + */ + scaleCanvas(x: number, y: number): Phaser.GameObjects.Graphics; + + /** + * Inserts a rotation command into this Graphics objects command buffer. + * + * All objects drawn _after_ calling this method will be rotated + * by the given amount. + * + * This does not change the rotation of the Graphics object itself, + * only of the objects drawn by it after calling this method. + * @param radians The rotation angle, in radians. + */ + rotateCanvas(radians: number): Phaser.GameObjects.Graphics; + + /** + * Clear the command buffer and reset the fill style and line style to their defaults. + */ + clear(): Phaser.GameObjects.Graphics; + + /** + * Generate a texture from this Graphics object. + * + * If `key` is a string it'll generate a new texture using it and add it into the + * Texture Manager (assuming no key conflict happens). + * + * If `key` is a Canvas it will draw the texture to that canvas context. Note that it will NOT + * automatically upload it to the GPU in WebGL mode. + * @param key The key to store the texture with in the Texture Manager, or a Canvas to draw to. + * @param width The width of the graphics to generate. + * @param height The height of the graphics to generate. + */ + generateTexture(key: string | HTMLCanvasElement, width?: integer, height?: integer): Phaser.GameObjects.Graphics; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * A Camera used specifically by the Graphics system for rendering to textures. + */ + static TargetCamera: Phaser.Cameras.Scene2D.Camera; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + } + + /** + * A Group is a way for you to create, manipulate, or recycle similar Game Objects. + * + * Group membership is non-exclusive. A Game Object can belong to several groups, one group, or none. + * + * Groups themselves aren't displayable, and can't be positioned, rotated, scaled, or hidden. + */ + class Group { + /** + * + * @param scene The scene this group belongs to. + * @param children Game Objects to add to this group; or the `config` argument. + * @param config Settings for this group. If `key` is set, Phaser.GameObjects.Group#createMultiple is also called with these settings. + */ + constructor(scene: Phaser.Scene, children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig); + + /** + * This scene this group belongs to. + */ + scene: Phaser.Scene; + + /** + * Members of this group. + */ + children: Phaser.Structs.Set; + + /** + * A flag identifying this object as a group. + */ + isParent: boolean; + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + */ + type: string; + + /** + * The class to create new group members from. + */ + classType: Function; + + /** + * The name of this group. + * Empty by default and never populated by Phaser, this is left for developers to use. + */ + name: string; + + /** + * Whether this group runs its {@link Phaser.GameObjects.Group#preUpdate} method + * (which may update any members). + */ + active: boolean; + + /** + * The maximum size of this group, if used as a pool. -1 is no limit. + */ + maxSize: integer; + + /** + * A default texture key to use when creating new group members. + * + * This is used in {@link Phaser.GameObjects.Group#create} + * but not in {@link Phaser.GameObjects.Group#createMultiple}. + */ + defaultKey: string; + + /** + * A default texture frame to use when creating new group members. + */ + defaultFrame: string | integer; + + /** + * Whether to call the update method of any members. + */ + runChildUpdate: boolean; + + /** + * A function to be called when adding or creating group members. + */ + createCallback: Phaser.Types.GameObjects.Group.GroupCallback; + + /** + * A function to be called when removing group members. + */ + removeCallback: Phaser.Types.GameObjects.Group.GroupCallback; + + /** + * A function to be called when creating several group members at once. + */ + createMultipleCallback: Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback; + + /** + * Creates a new Game Object and adds it to this group, unless the group {@link Phaser.GameObjects.Group#isFull is full}. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * @param x The horizontal position of the new Game Object in the world. Default 0. + * @param y The vertical position of the new Game Object in the world. Default 0. + * @param key The texture key of the new Game Object. Default defaultKey. + * @param frame The texture frame of the new Game Object. Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of the new Game Object. Default true. + * @param active The {@link Phaser.GameObjects.GameObject#active} state of the new Game Object. Default true. + */ + create(x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean, active?: boolean): any; + + /** + * Creates several Game Objects and adds them to this group. + * + * If the group becomes {@link Phaser.GameObjects.Group#isFull}, no further Game Objects are created. + * + * Calls {@link Phaser.GameObjects.Group#createMultipleCallback} and {@link Phaser.GameObjects.Group#createCallback}. + * @param config Creation settings. This can be a single configuration object or an array of such objects, which will be applied in turn. + */ + createMultiple(config: Phaser.Types.GameObjects.Group.GroupCreateConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig[]): any[]; + + /** + * A helper for {@link Phaser.GameObjects.Group#createMultiple}. + * @param options Creation settings. + */ + createFromConfig(options: Phaser.Types.GameObjects.Group.GroupCreateConfig): any[]; + + /** + * Updates any group members, if {@link Phaser.GameObjects.Group#runChildUpdate} is enabled. + * @param time The current timestamp. + * @param delta The delta time elapsed since the last frame. + */ + preUpdate(time: number, delta: number): void; + + /** + * Adds a Game Object to this group. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * @param child The Game Object to add. + * @param addToScene Also add the Game Object to the scene. Default false. + */ + add(child: Phaser.GameObjects.GameObject, addToScene?: boolean): Phaser.GameObjects.Group; + + /** + * Adds several Game Objects to this group. + * + * Calls {@link Phaser.GameObjects.Group#createCallback}. + * @param children The Game Objects to add. + * @param addToScene Also add the Game Objects to the scene. Default false. + */ + addMultiple(children: Phaser.GameObjects.GameObject[], addToScene?: boolean): Phaser.GameObjects.Group; + + /** + * Removes a member of this Group and optionally removes it from the Scene and / or destroys it. + * + * Calls {@link Phaser.GameObjects.Group#removeCallback}. + * @param child The Game Object to remove. + * @param removeFromScene Optionally remove the Group member from the Scene it belongs to. Default false. + * @param destroyChild Optionally call destroy on the removed Group member. Default false. + */ + remove(child: Phaser.GameObjects.GameObject, removeFromScene?: boolean, destroyChild?: boolean): Phaser.GameObjects.Group; + + /** + * Removes all members of this Group and optionally removes them from the Scene and / or destroys them. + * + * Does not call {@link Phaser.GameObjects.Group#removeCallback}. + * @param removeFromScene Optionally remove each Group member from the Scene. Default false. + * @param destroyChild Optionally call destroy on the removed Group members. Default false. + */ + clear(removeFromScene?: boolean, destroyChild?: boolean): Phaser.GameObjects.Group; + + /** + * Tests if a Game Object is a member of this group. + * @param child A Game Object. + */ + contains(child: Phaser.GameObjects.GameObject): boolean; + + /** + * All members of the group. + */ + getChildren(): Phaser.GameObjects.GameObject[]; + + /** + * The number of members of the group. + */ + getLength(): integer; + + /** + * Scans the Group, from top to bottom, for the first member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. + * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + getFirst(state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * Scans the Group, from top to bottom, for the nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param nth The nth matching Group member to search for. + * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. + * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + getFirstNth(nth: integer, state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * Scans the Group for the last member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. + * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + getLast(state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * Scans the Group for the last nth member that has an {@link Phaser.GameObjects.GameObject#active} state matching the argument, + * assigns `x` and `y`, and returns the member. + * + * If no matching member is found and `createIfNull` is true and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param nth The nth matching Group member to search for. + * @param state The {@link Phaser.GameObjects.GameObject#active} value to match. Default false. + * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + getLastNth(nth: integer, state?: boolean, createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, + * assigns `x` and `y`, and returns the member. + * + * If no inactive member is found and the group isn't full then it will create a new Game Object using `x`, `y`, `key`, `frame`, and `visible`. + * The new Game Object will have its active state set to `true`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + get(x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `true`, + * assigns `x` and `y`, and returns the member. + * + * If no active member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + getFirstAlive(createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * Scans the group for the first member that has an {@link Phaser.GameObjects.GameObject#active} state set to `false`, + * assigns `x` and `y`, and returns the member. + * + * If no inactive member is found and `createIfNull` is `true` and the group isn't full then it will create a new one using `x`, `y`, `key`, `frame`, and `visible`. + * The new Game Object will have an active state set to `true`. + * Unless a new member is created, `key`, `frame`, and `visible` are ignored. + * @param createIfNull Create a new Game Object if no matching members are found, using the following arguments. Default false. + * @param x The horizontal position of the Game Object in the world. + * @param y The vertical position of the Game Object in the world. + * @param key The texture key assigned to a new Game Object (if one is created). Default defaultKey. + * @param frame A texture frame assigned to a new Game Object (if one is created). Default defaultFrame. + * @param visible The {@link Phaser.GameObjects.Components.Visible#visible} state of a new Game Object (if one is created). Default true. + */ + getFirstDead(createIfNull?: boolean, x?: number, y?: number, key?: string, frame?: string | integer, visible?: boolean): any; + + /** + * {@link Phaser.GameObjects.Components.Animation#play Plays} an animation for all members of this group. + * @param key The string-based key of the animation to play. + * @param startFrame Optionally start the animation playing from this frame index. Default 0. + */ + playAnimation(key: string, startFrame?: string): Phaser.GameObjects.Group; + + /** + * Whether this group's size at its {@link Phaser.GameObjects.Group#maxSize maximum}. + */ + isFull(): boolean; + + /** + * Counts the number of active (or inactive) group members. + * @param value Count active (true) or inactive (false) group members. Default true. + */ + countActive(value?: boolean): integer; + + /** + * Counts the number of in-use (active) group members. + */ + getTotalUsed(): integer; + + /** + * The difference of {@link Phaser.GameObjects.Group#maxSize} and the number of active group members. + * + * This represents the number of group members that could be created or reactivated before reaching the size limit. + */ + getTotalFree(): integer; + + /** + * Sets the property as defined in `key` of each group member to the given value. + * @param key The property to be updated. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + propertyValueSet(key: string, value: number, step?: number, index?: integer, direction?: integer): Phaser.GameObjects.Group; + + /** + * Adds the given value to the property as defined in `key` of each group member. + * @param key The property to be updated. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + propertyValueInc(key: string, value: number, step?: number, index?: integer, direction?: integer): Phaser.GameObjects.Group; + + /** + * Sets the x of each group member. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + setX(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the y of each group member. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + setY(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the x, y of each group member. + * @param x The amount to set the `x` property to. + * @param y The amount to set the `y` property to. If `undefined` or `null` it uses the `x` value. Default x. + * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. + */ + setXY(x: number, y?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; + + /** + * Adds the given value to the x of each group member. + * @param value The amount to be added to the `x` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + incX(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Adds the given value to the y of each group member. + * @param value The amount to be added to the `y` property. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + incY(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Adds the given value to the x, y of each group member. + * @param x The amount to be added to the `x` property. + * @param y The amount to be added to the `y` property. If `undefined` or `null` it uses the `x` value. Default x. + * @param stepX This is added to the `x` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `y` amount, multiplied by the iteration counter. Default 0. + */ + incXY(x: number, y?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; + + /** + * Iterate through the group members changing the position of each element to be that of the element that came before + * it in the array (or after it if direction = 1) + * + * The first group member position is set to x/y. + * @param x The x coordinate to place the first item in the array at. + * @param y The y coordinate to place the first item in the array at. + * @param direction The iteration direction. 0 = first to last and 1 = last to first. Default 0. + */ + shiftPosition(x: number, y: number, direction?: integer): Phaser.GameObjects.Group; + + /** + * Sets the angle of each group member. + * @param value The amount to set the angle to, in degrees. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + angle(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the rotation of each group member. + * @param value The amount to set the rotation to, in radians. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + rotate(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Rotates each group member around the given point by the given angle. + * @param point Any object with public `x` and `y` properties. + * @param angle The angle to rotate by, in radians. + */ + rotateAround(point: Phaser.Types.Math.Vector2Like, angle: number): Phaser.GameObjects.Group; + + /** + * Rotates each group member around the given point by the given angle and distance. + * @param point Any object with public `x` and `y` properties. + * @param angle The angle to rotate by, in radians. + * @param distance The distance from the point of rotation in pixels. + */ + rotateAroundDistance(point: Phaser.Types.Math.Vector2Like, angle: number, distance: number): Phaser.GameObjects.Group; + + /** + * Sets the alpha of each group member. + * @param value The amount to set the alpha to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + setAlpha(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the tint of each group member. + * @param topLeft The tint being applied to top-left corner of item. If other parameters are given no value, this tint will be applied to whole item. + * @param topRight The tint to be applied to top-right corner of item. + * @param bottomLeft The tint to be applied to the bottom-left corner of item. + * @param bottomRight The tint to be applied to the bottom-right corner of item. + */ + setTint(topLeft: number, topRight?: number, bottomLeft?: number, bottomRight?: number): Phaser.GameObjects.Group; + + /** + * Sets the originX, originY of each group member. + * @param originX The amount to set the `originX` property to. + * @param originY The amount to set the `originY` property to. If `undefined` or `null` it uses the `originX` value. + * @param stepX This is added to the `originX` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `originY` amount, multiplied by the iteration counter. Default 0. + */ + setOrigin(originX: number, originY?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; + + /** + * Sets the scaleX of each group member. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + scaleX(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the scaleY of each group member. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + scaleY(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the scaleX, scaleY of each group member. + * @param scaleX The amount to be added to the `scaleX` property. + * @param scaleY The amount to be added to the `scaleY` property. If `undefined` or `null` it uses the `scaleX` value. + * @param stepX This is added to the `scaleX` amount, multiplied by the iteration counter. Default 0. + * @param stepY This is added to the `scaleY` amount, multiplied by the iteration counter. Default 0. + */ + scaleXY(scaleX: number, scaleY?: number, stepX?: number, stepY?: number): Phaser.GameObjects.Group; + + /** + * Sets the depth of each group member. + * @param value The amount to set the property to. + * @param step This is added to the `value` amount, multiplied by the iteration counter. Default 0. + */ + setDepth(value: number, step?: number): Phaser.GameObjects.Group; + + /** + * Sets the blendMode of each group member. + * @param value The amount to set the property to. + */ + setBlendMode(value: number): Phaser.GameObjects.Group; + + /** + * Passes all group members to the Input Manager to enable them for input with identical areas and callbacks. + * @param 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 hitAreaCallback A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. + */ + setHitArea(hitArea: any, hitAreaCallback: Phaser.Types.Input.HitAreaCallback): Phaser.GameObjects.Group; + + /** + * Shuffles the group members in place. + */ + shuffle(): Phaser.GameObjects.Group; + + /** + * Deactivates a member of this group. + * @param gameObject A member of this group. + */ + kill(gameObject: Phaser.GameObjects.GameObject): void; + + /** + * Deactivates and hides a member of this group. + * @param gameObject A member of this group. + */ + killAndHide(gameObject: Phaser.GameObjects.GameObject): void; + + /** + * Sets the visible of each group member. + * @param value The value to set the property to. + * @param index An optional offset to start searching from within the items array. Default 0. + * @param direction The direction to iterate through the array. 1 is from beginning to end, -1 from end to beginning. Default 1. + */ + setVisible(value: boolean, index?: integer, direction?: integer): Phaser.GameObjects.Group; + + /** + * Toggles (flips) the visible state of each member of this group. + */ + toggleVisible(): Phaser.GameObjects.Group; + + /** + * Empties this group and removes it from the Scene. + * + * Does not call {@link Phaser.GameObjects.Group#removeCallback}. + * @param destroyChildren Also {@link Phaser.GameObjects.GameObject#destroy} each group member. Default false. + */ + destroy(destroyChildren?: boolean): void; + + } + + /** + * An Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + */ + class Image extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.TextureCrop, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A 2D point light. + * + * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`. + * + * Any Game Objects using the Light2D pipeline will then be affected by these Lights. + * + * They can also simply be used to represent a point light for your own purposes. + */ + class Light { + /** + * + * @param x The horizontal position of the light. + * @param y The vertical position of the light. + * @param radius The radius of the light. + * @param r The red color of the light. A value between 0 and 1. + * @param g The green color of the light. A value between 0 and 1. + * @param b The blue color of the light. A value between 0 and 1. + * @param intensity The intensity of the light. + */ + constructor(x: number, y: number, radius: number, r: number, g: number, b: number, intensity: number); + + /** + * The horizontal position of the light. + */ + x: number; + + /** + * The vertical position of the light. + */ + y: number; + + /** + * The radius of the light. + */ + radius: number; + + /** + * The red color of the light. A value between 0 and 1. + */ + r: number; + + /** + * The green color of the light. A value between 0 and 1. + */ + g: number; + + /** + * The blue color of the light. A value between 0 and 1. + */ + b: number; + + /** + * The intensity of the light. + */ + intensity: number; + + /** + * The horizontal scroll factor of the light. + */ + scrollFactorX: number; + + /** + * The vertical scroll factor of the light. + */ + scrollFactorY: number; + + /** + * Set the properties of the light. + * + * Sets both horizontal and vertical scroll factor to 1. Use {@link Phaser.GameObjects.Light#setScrollFactor} to set + * the scroll factor. + * @param x The horizontal position of the light. + * @param y The vertical position of the light. + * @param radius The radius of the light. + * @param r The red color. A value between 0 and 1. + * @param g The green color. A value between 0 and 1. + * @param b The blue color. A value between 0 and 1. + * @param intensity The intensity of the light. + */ + set(x: number, y: number, radius: number, r: number, g: number, b: number, intensity: number): Phaser.GameObjects.Light; + + /** + * Set the scroll factor of the light. + * @param x The horizontal scroll factor of the light. + * @param y The vertical scroll factor of the light. + */ + setScrollFactor(x: number, y: number): Phaser.GameObjects.Light; + + /** + * Set the color of the light from a single integer RGB value. + * @param rgb The integer RGB color of the light. + */ + setColor(rgb: number): Phaser.GameObjects.Light; + + /** + * Set the intensity of the light. + * @param intensity The intensity of the light. + */ + setIntensity(intensity: number): Phaser.GameObjects.Light; + + /** + * Set the position of the light. + * @param x The horizontal position of the light. + * @param y The vertical position of the light. + */ + setPosition(x: number, y: number): Phaser.GameObjects.Light; + + /** + * Set the radius of the light. + * @param radius The radius of the light. + */ + setRadius(radius: number): Phaser.GameObjects.Light; + + } + + /** + * Manages Lights for a Scene. + * + * Affects the rendering of Game Objects using the `Light2D` pipeline. + */ + class LightsManager { + /** + * The pool of Lights. + * + * Used to recycle removed Lights for a more efficient use of memory. + */ + lightPool: Phaser.GameObjects.Light[]; + + /** + * The Lights in the Scene. + */ + lights: Phaser.GameObjects.Light[]; + + /** + * Lights that have been culled from a Camera's viewport. + * + * Lights in this list will not be rendered. + */ + culledLights: Phaser.GameObjects.Light[]; + + /** + * The ambient color. + */ + ambientColor: Object; + + /** + * Whether the Lights Manager is enabled. + */ + active: boolean; + + /** + * The maximum number of lights that a single Camera and the lights shader can process. + * Change this via the `maxLights` property in your game config, as it cannot be changed at runtime. + */ + readonly maxLights: integer; + + /** + * Enable the Lights Manager. + */ + enable(): Phaser.GameObjects.LightsManager; + + /** + * Disable the Lights Manager. + */ + disable(): Phaser.GameObjects.LightsManager; + + /** + * Cull any Lights that aren't visible to the given Camera. + * + * Culling Lights improves performance by ensuring that only Lights within a Camera's viewport are rendered. + * @param camera The Camera to cull Lights for. + */ + cull(camera: Phaser.Cameras.Scene2D.Camera): Phaser.GameObjects.Light[]; + + /** + * Iterate over each Light with a callback. + * @param callback The callback that is called with each Light. + */ + forEachLight(callback: LightForEach): Phaser.GameObjects.LightsManager; + + /** + * Set the ambient light color. + * @param rgb The integer RGB color of the ambient light. + */ + setAmbientColor(rgb: number): Phaser.GameObjects.LightsManager; + + /** + * Returns the maximum number of Lights allowed to appear at once. + */ + getMaxVisibleLights(): integer; + + /** + * Get the number of Lights managed by this Lights Manager. + */ + getLightCount(): integer; + + /** + * Add a Light. + * @param x The horizontal position of the Light. Default 0. + * @param y The vertical position of the Light. Default 0. + * @param radius The radius of the Light. Default 100. + * @param rgb The integer RGB color of the light. Default 0xffffff. + * @param intensity The intensity of the Light. Default 1. + */ + addLight(x?: number, y?: number, radius?: number, rgb?: number, intensity?: number): Phaser.GameObjects.Light; + + /** + * Remove a Light. + * @param light The Light to remove. + */ + removeLight(light: Phaser.GameObjects.Light): Phaser.GameObjects.LightsManager; + + /** + * Shut down the Lights Manager. + * + * Recycles all active Lights into the Light pool, resets ambient light color and clears the lists of Lights and + * culled Lights. + */ + shutdown(): void; + + /** + * Destroy the Lights Manager. + * + * Cleans up all references by calling {@link Phaser.GameObjects.LightsManager#shutdown}. + */ + destroy(): void; + + } + + /** + * A Scene plugin that provides a {@link Phaser.GameObjects.LightsManager} for the Light2D pipeline. + * + * Available from within a Scene via `this.lights`. + * + * Add Lights using the {@link Phaser.GameObjects.LightsManager#addLight} method: + * + * ```javascript + * // Enable the Lights Manager because it is disabled by default + * this.lights.enable(); + * + * // Create a Light at [400, 300] with a radius of 200 + * this.lights.addLight(400, 300, 200); + * ``` + * + * For Game Objects to be affected by the Lights when rendered, you will need to set them to use the `Light2D` pipeline like so: + * + * ```javascript + * sprite.setPipeline('Light2D'); + * ``` + */ + class LightsPlugin extends Phaser.GameObjects.LightsManager { + /** + * + * @param scene The Scene that this Lights Plugin belongs to. + */ + constructor(scene: Phaser.Scene); + + /** + * A reference to the Scene that this Lights Plugin belongs to. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene's systems. + */ + systems: Phaser.Scenes.Systems; + + /** + * Boot the Lights Plugin. + */ + boot(): void; + + /** + * Destroy the Lights Plugin. + * + * Cleans up all references. + */ + destroy(): void; + + } + + /** + * A Mesh Game Object. + */ + class Mesh extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible, Phaser.GameObjects.Components.ScrollFactor { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param vertices An array containing the vertices data for this Mesh. + * @param uv An array containing the uv data for this Mesh. + * @param colors An array containing the color data for this Mesh. + * @param alphas An array containing the alpha data for this Mesh. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, vertices: number[], uv: number[], colors: number[], alphas: number[], texture: string, frame?: string | integer); + + /** + * An array containing the vertices data for this Mesh. + */ + vertices: Float32Array; + + /** + * An array containing the uv data for this Mesh. + */ + uv: Float32Array; + + /** + * An array containing the color data for this Mesh. + */ + colors: Uint32Array; + + /** + * An array containing the alpha data for this Mesh. + */ + alphas: Float32Array; + + /** + * Fill or additive mode used when blending the color values? + */ + tintFill: boolean; + + /** + * This method is left intentionally empty and does not do anything. + * It is retained to allow a Mesh or Quad to be added to a Container. + */ + setAlpha(): void; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + } + + namespace Particles { + /** + * A Particle Emitter property. + * + * Facilitates changing Particle properties as they are emitted and throughout their lifetime. + */ + class EmitterOp { + /** + * + * @param config Settings for the Particle Emitter that owns this property. + * @param key The name of the property. + * @param defaultValue The default value of the property. + * @param emitOnly Whether the property can only be modified when a Particle is emitted. Default false. + */ + constructor(config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig, key: string, defaultValue: number, emitOnly?: boolean); + + /** + * The name of this property. + */ + propertyKey: string; + + /** + * The value of this property. + */ + propertyValue: number; + + /** + * The default value of this property. + */ + defaultValue: number; + + /** + * The number of steps for stepped easing between {@link Phaser.GameObjects.Particles.EmitterOp#start} and + * {@link Phaser.GameObjects.Particles.EmitterOp#end} values, per emit. + */ + steps: number; + + /** + * The step counter for stepped easing, per emit. + */ + counter: number; + + /** + * The start value for this property to ease between. + */ + start: number; + + /** + * The end value for this property to ease between. + */ + end: number; + + /** + * The easing function to use for updating this property. + */ + ease: Function; + + /** + * Whether this property can only be modified when a Particle is emitted. + * + * Set to `true` to allow only {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} callbacks to be set and + * affect this property. + * + * Set to `false` to allow both {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and + * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks to be set and affect this property. + */ + emitOnly: boolean; + + /** + * The callback to run for Particles when they are emitted from the Particle Emitter. + */ + onEmit: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback; + + /** + * The callback to run for Particles when they are updated. + */ + onUpdate: Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback; + + /** + * Load the property from a Particle Emitter configuration object. + * + * Optionally accepts a new property key to use, replacing the current one. + * @param config Settings for the Particle Emitter that owns this property. + * @param newKey The new key to use for this property, if any. + */ + loadConfig(config?: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig, newKey?: string): void; + + /** + * Build a JSON representation of this Particle Emitter property. + */ + toJSON(): object; + + /** + * Change the current value of the property and update its callback methods. + * @param value The value of the property. + */ + onChange(value: number): Phaser.GameObjects.Particles.EmitterOp; + + /** + * Update the {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and + * {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks based on the type of the current + * {@link Phaser.GameObjects.Particles.EmitterOp#propertyValue}. + */ + setMethods(): Phaser.GameObjects.Particles.EmitterOp; + + /** + * Check whether an object has the given property. + * @param object The object to check. + * @param key The key of the property to look for in the object. + */ + has(object: object, key: string): boolean; + + /** + * Check whether an object has both of the given properties. + * @param object The object to check. + * @param key1 The key of the first property to check the object for. + * @param key2 The key of the second property to check the object for. + */ + hasBoth(object: object, key1: string, key2: string): boolean; + + /** + * Check whether an object has at least one of the given properties. + * @param object The object to check. + * @param key1 The key of the first property to check the object for. + * @param key2 The key of the second property to check the object for. + */ + hasEither(object: object, key1: string, key2: string): boolean; + + /** + * The returned value sets what the property will be at the START of the particles life, on emit. + * @param particle The particle. + * @param key The name of the property. + * @param value The current value of the property. + */ + defaultEmit(particle: Phaser.GameObjects.Particles.Particle, key: string, value?: number): number; + + /** + * The returned value updates the property for the duration of the particles life. + * @param particle The particle. + * @param key The name of the property. + * @param t The T value (between 0 and 1) + * @param value The current value of the property. + */ + defaultUpdate(particle: Phaser.GameObjects.Particles.Particle, key: string, t: number, value: number): number; + + /** + * An `onEmit` callback that returns the current value of the property. + */ + staticValueEmit(): number; + + /** + * An `onUpdate` callback that returns the current value of the property. + */ + staticValueUpdate(): number; + + /** + * An `onEmit` callback that returns a random value from the current value array. + */ + randomStaticValueEmit(): number; + + /** + * An `onEmit` callback that returns a value between the {@link Phaser.GameObjects.Particles.EmitterOp#start} and + * {@link Phaser.GameObjects.Particles.EmitterOp#end} range. + * @param particle The particle. + * @param key The key of the property. + */ + randomRangedValueEmit(particle: Phaser.GameObjects.Particles.Particle, key: string): number; + + /** + * An `onEmit` callback that returns a stepped value between the + * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} + * range. + */ + steppedEmit(): number; + + /** + * An `onEmit` callback for an eased property. + * + * It prepares the particle for easing by {@link Phaser.GameObjects.Particles.EmitterOp#easeValueUpdate}. + * @param particle The particle. + * @param key The name of the property. + */ + easedValueEmit(particle: Phaser.GameObjects.Particles.Particle, key: string): number; + + /** + * An `onUpdate` callback that returns an eased value between the + * {@link Phaser.GameObjects.Particles.EmitterOp#start} and {@link Phaser.GameObjects.Particles.EmitterOp#end} + * range. + * @param particle The particle. + * @param key The name of the property. + * @param t The T value (between 0 and 1) + */ + easeValueUpdate(particle: Phaser.GameObjects.Particles.Particle, key: string, t: number): number; + + } + + /** + * The GravityWell action applies a force on the particle to draw it towards, or repel it from, a single point. + * + * The force applied is inversely proportional to the square of the distance from the particle to the point, in accordance with Newton's law of gravity. + * + * This simulates the effect of gravity over large distances (as between planets, for example). + */ + class GravityWell { + /** + * + * @param x The x coordinate of the Gravity Well, in world space. Default 0. + * @param y The y coordinate of the Gravity Well, in world space. Default 0. + * @param power The strength of the gravity force - larger numbers produce a stronger force. Default 0. + * @param epsilon The minimum distance for which the gravity force is calculated. Default 100. + * @param gravity The gravitational force of this Gravity Well. Default 50. + */ + constructor(x?: number | Phaser.Types.GameObjects.Particles.GravityWellConfig, y?: number, power?: number, epsilon?: number, gravity?: number); + + /** + * The x coordinate of the Gravity Well, in world space. + */ + x: number; + + /** + * The y coordinate of the Gravity Well, in world space. + */ + y: number; + + /** + * The active state of the Gravity Well. An inactive Gravity Well will not influence any particles. + */ + active: boolean; + + /** + * The strength of the gravity force - larger numbers produce a stronger force. + */ + power: number; + + /** + * The minimum distance for which the gravity force is calculated. + */ + epsilon: number; + + /** + * Takes a Particle and updates it based on the properties of this Gravity Well. + * @param particle The Particle to update. + * @param delta The delta time in ms. + * @param step The delta value divided by 1000. + */ + update(particle: Phaser.GameObjects.Particles.Particle, delta: number, step: number): void; + + } + + /** + * A Particle is a simple Game Object controlled by a Particle Emitter and Manager, and rendered by the Manager. + * It uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. + */ + class Particle { + /** + * + * @param emitter The Emitter to which this Particle belongs. + */ + constructor(emitter: Phaser.GameObjects.Particles.ParticleEmitter); + + /** + * The Emitter to which this Particle belongs. + * + * A Particle can only belong to a single Emitter and is created, updated and destroyed via it. + */ + emitter: Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * The texture frame used to render this Particle. + */ + frame: Phaser.Textures.Frame; + + /** + * The x coordinate of this Particle. + */ + x: number; + + /** + * The y coordinate of this Particle. + */ + y: number; + + /** + * The x velocity of this Particle. + */ + velocityX: number; + + /** + * The y velocity of this Particle. + */ + velocityY: number; + + /** + * The x acceleration of this Particle. + */ + accelerationX: number; + + /** + * The y acceleration of this Particle. + */ + accelerationY: number; + + /** + * The maximum horizontal velocity this Particle can travel at. + */ + maxVelocityX: number; + + /** + * The maximum vertical velocity this Particle can travel at. + */ + maxVelocityY: number; + + /** + * The bounciness, or restitution, of this Particle. + */ + bounce: number; + + /** + * The horizontal scale of this Particle. + */ + scaleX: number; + + /** + * The vertical scale of this Particle. + */ + scaleY: number; + + /** + * The alpha value of this Particle. + */ + alpha: number; + + /** + * The angle of this Particle in degrees. + */ + angle: number; + + /** + * The angle of this Particle in radians. + */ + rotation: number; + + /** + * The tint applied to this Particle. + */ + tint: integer; + + /** + * The lifespan of this Particle in ms. + */ + life: number; + + /** + * The current life of this Particle in ms. + */ + lifeCurrent: number; + + /** + * The delay applied to this Particle upon emission, in ms. + */ + delayCurrent: number; + + /** + * The normalized lifespan T value, where 0 is the start and 1 is the end. + */ + lifeT: number; + + /** + * The data used by the ease equation. + */ + data: object; + + /** + * Checks to see if this Particle is alive and updating. + */ + isAlive(): boolean; + + /** + * Resets the position of this particle back to zero. + */ + resetPosition(): void; + + /** + * Starts this Particle from the given coordinates. + * @param x The x coordinate to launch this Particle from. + * @param y The y coordinate to launch this Particle from. + */ + fire(x: number, y: number): void; + + /** + * An internal method that calculates the velocity of the Particle. + * @param emitter The Emitter that is updating this Particle. + * @param delta The delta time in ms. + * @param step The delta value divided by 1000. + * @param processors Particle processors (gravity wells). + */ + computeVelocity(emitter: Phaser.GameObjects.Particles.ParticleEmitter, delta: number, step: number, processors: any[]): void; + + /** + * Checks if this Particle is still within the bounds defined by the given Emitter. + * + * If not, and depending on the Emitter collision flags, the Particle may either stop or rebound. + * @param emitter The Emitter to check the bounds against. + */ + checkBounds(emitter: Phaser.GameObjects.Particles.ParticleEmitter): void; + + /** + * The main update method for this Particle. + * + * Updates its life values, computes the velocity and repositions the Particle. + * @param delta The delta time in ms. + * @param step The delta value divided by 1000. + * @param processors An optional array of update processors. + */ + update(delta: number, step: number, processors: any[]): boolean; + + } + + /** + * A particle emitter represents a single particle stream. + * It controls a pool of {@link Phaser.GameObjects.Particles.Particle Particles} and is controlled by a {@link Phaser.GameObjects.Particles.ParticleEmitterManager Particle Emitter Manager}. + */ + class ParticleEmitter implements Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Visible { + /** + * + * @param manager The Emitter Manager this Emitter belongs to. + * @param config Settings for this emitter. + */ + constructor(manager: Phaser.GameObjects.Particles.ParticleEmitterManager, config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig); + + /** + * The Emitter Manager this Emitter belongs to. + */ + manager: Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * The texture assigned to particles. + */ + texture: Phaser.Textures.Texture; + + /** + * The texture frames assigned to particles. + */ + frames: Phaser.Textures.Frame[]; + + /** + * The default texture frame assigned to particles. + */ + defaultFrame: Phaser.Textures.Frame; + + /** + * Names of simple configuration properties. + */ + configFastMap: object; + + /** + * Names of complex configuration properties. + */ + configOpMap: object; + + /** + * The name of this Particle Emitter. + * + * Empty by default and never populated by Phaser, this is left for developers to use. + */ + name: string; + + /** + * The Particle Class which will be emitted by this Emitter. + */ + particleClass: Phaser.GameObjects.Particles.Particle; + + /** + * The x-coordinate of the particle origin (where particles will be emitted). + */ + x: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The y-coordinate of the particle origin (where particles will be emitted). + */ + y: Phaser.GameObjects.Particles.EmitterOp; + + /** + * A radial emitter will emit particles in all directions between angle min and max, + * using {@link Phaser.GameObjects.Particles.ParticleEmitter#speed} as the value. If set to false then this acts as a point Emitter. + * A point emitter will emit particles only in the direction derived from the speedX and speedY values. + */ + radial: boolean; + + /** + * Horizontal acceleration applied to emitted particles, in pixels per second squared. + */ + gravityX: number; + + /** + * Vertical acceleration applied to emitted particles, in pixels per second squared. + */ + gravityY: number; + + /** + * Whether accelerationX and accelerationY are non-zero. Set automatically during configuration. + */ + acceleration: boolean; + + /** + * Horizontal acceleration applied to emitted particles, in pixels per second squared. + */ + accelerationX: Phaser.GameObjects.Particles.EmitterOp; + + /** + * Vertical acceleration applied to emitted particles, in pixels per second squared. + */ + accelerationY: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The maximum horizontal velocity of emitted particles, in pixels per second squared. + */ + maxVelocityX: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The maximum vertical velocity of emitted particles, in pixels per second squared. + */ + maxVelocityY: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The initial horizontal speed of emitted particles, in pixels per second. + */ + speedX: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The initial vertical speed of emitted particles, in pixels per second. + */ + speedY: Phaser.GameObjects.Particles.EmitterOp; + + /** + * Whether moveToX and moveToY are nonzero. Set automatically during configuration. + */ + moveTo: boolean; + + /** + * The x-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. + */ + moveToX: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The y-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true. + */ + moveToY: Phaser.GameObjects.Particles.EmitterOp; + + /** + * Whether particles will rebound when they meet the emitter bounds. + */ + bounce: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The horizontal scale of emitted particles. + */ + scaleX: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The vertical scale of emitted particles. + */ + scaleY: Phaser.GameObjects.Particles.EmitterOp; + + /** + * Color tint applied to emitted particles. Any alpha component (0xAA000000) is ignored. + */ + tint: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The alpha (transparency) of emitted particles. + */ + alpha: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The lifespan of emitted particles, in ms. + */ + lifespan: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The angle of the initial velocity of emitted particles, in degrees. + */ + angle: Phaser.GameObjects.Particles.EmitterOp; + + /** + * The rotation of emitted particles, in degrees. + */ + rotate: Phaser.GameObjects.Particles.EmitterOp; + + /** + * A function to call when a particle is emitted. + */ + emitCallback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback; + + /** + * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. + */ + emitCallbackScope: any; + + /** + * A function to call when a particle dies. + */ + deathCallback: Phaser.Types.GameObjects.Particles.ParticleDeathCallback; + + /** + * The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. + */ + deathCallbackScope: any; + + /** + * Set to hard limit the amount of particle objects this emitter is allowed to create. + * 0 means unlimited. + */ + maxParticles: integer; + + /** + * How many particles are emitted each time particles are emitted (one explosion or one flow cycle). + */ + quantity: Phaser.GameObjects.Particles.EmitterOp; + + /** + * How many ms to wait after emission before the particles start updating. + */ + delay: Phaser.GameObjects.Particles.EmitterOp; + + /** + * For a flow emitter, the time interval (>= 0) between particle flow cycles in ms. + * A value of 0 means there is one particle flow cycle for each logic update (the maximum flow frequency). This is the default setting. + * For an exploding emitter, this value will be -1. + * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} also puts the emitter in flow mode (frequency >= 0). + * Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} also puts the emitter in explode mode (frequency = -1). + */ + frequency: number; + + /** + * Controls if the emitter is currently emitting a particle flow (when frequency >= 0). + * Already alive particles will continue to update until they expire. + * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#start} and {@link Phaser.GameObjects.Particles.ParticleEmitter#stop}. + */ + on: boolean; + + /** + * Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. + * Set to false to send them to the back. + */ + particleBringToTop: boolean; + + /** + * The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal. + */ + timeScale: number; + + /** + * An object describing a shape to emit particles from. + */ + emitZone: Phaser.GameObjects.Particles.Zones.EdgeZone | Phaser.GameObjects.Particles.Zones.RandomZone; + + /** + * An object describing a shape that deactivates particles when they interact with it. + */ + deathZone: Phaser.GameObjects.Particles.Zones.DeathZone; + + /** + * A rectangular boundary constraining particle movement. + */ + bounds: Phaser.Geom.Rectangle; + + /** + * Whether particles interact with the left edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + */ + collideLeft: boolean; + + /** + * Whether particles interact with the right edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + */ + collideRight: boolean; + + /** + * Whether particles interact with the top edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + */ + collideTop: boolean; + + /** + * Whether particles interact with the bottom edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}. + */ + collideBottom: boolean; + + /** + * Whether this emitter updates itself and its particles. + * + * Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#pause} + * and {@link Phaser.GameObjects.Particles.ParticleEmitter#resume}. + */ + active: boolean; + + /** + * Set this to false to hide any active particles. + */ + visible: boolean; + + /** + * The blend mode of this emitter's particles. + */ + blendMode: integer; + + /** + * A Game Object whose position is used as the particle origin. + */ + follow: Phaser.GameObjects.GameObject; + + /** + * The offset of the particle origin from the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target. + */ + followOffset: Phaser.Math.Vector2; + + /** + * Whether the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#visible} state will track + * the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target's visibility state. + */ + trackVisible: boolean; + + /** + * The current texture frame, as an index of {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + */ + currentFrame: integer; + + /** + * Whether texture {@link Phaser.GameObjects.Particles.ParticleEmitter#frames} are selected at random. + */ + randomFrame: boolean; + + /** + * The number of consecutive particles that receive a single texture frame (per frame cycle). + */ + frameQuantity: integer; + + /** + * Merges configuration settings into the emitter's current settings. + * @param config Settings for this emitter. + */ + fromJSON(config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Creates a description of this emitter suitable for JSON serialization. + * @param output An object to copy output into. + */ + toJSON(output?: object): object; + + /** + * Continuously moves the particle origin to follow a Game Object's position. + * @param target The Game Object to follow. + * @param offsetX Horizontal offset of the particle origin from the Game Object. Default 0. + * @param offsetY Vertical offset of the particle origin from the Game Object. Default 0. + * @param trackVisible Whether the emitter's visible state will track the target's visible state. Default false. + */ + startFollow(target: Phaser.GameObjects.GameObject, offsetX?: number, offsetY?: number, trackVisible?: boolean): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Stops following a Game Object. + */ + stopFollow(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Chooses a texture frame from {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + */ + getFrame(): Phaser.Textures.Frame; + + /** + * Sets a pattern for assigning texture frames to emitted particles. + * @param frames One or more texture frames, or a configuration object. + * @param pickRandom Whether frames should be assigned at random from `frames`. Default true. + * @param quantity The number of consecutive particles that will receive each frame. Default 1. + */ + setFrame(frames: any[] | string | integer | Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig, pickRandom?: boolean, quantity?: integer): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle movement on or off. + * @param value Radial mode (true) or point mode (true). Default true. + */ + setRadial(value?: boolean): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the position of the emitter's particle origin. + * New particles will be emitted here. + * @param x The x-coordinate of the particle origin. + * @param y The y-coordinate of the particle origin. + */ + setPosition(x: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType, y: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets or modifies a rectangular boundary constraining the particles. + * + * To remove the boundary, set {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds} to null. + * @param x The x-coordinate of the left edge of the boundary, or an object representing a rectangle. + * @param y The y-coordinate of the top edge of the boundary. + * @param width The width of the boundary. + * @param height The height of the boundary. + */ + setBounds(x: number | Phaser.Types.GameObjects.Particles.ParticleEmitterBounds | Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt, y: number, width: number, height: number): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the initial horizontal speed of emitted particles. + * Changes the emitter to point mode. + * @param value The speed, in pixels per second. + */ + setSpeedX(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the initial vertical speed of emitted particles. + * Changes the emitter to point mode. + * @param value The speed, in pixels per second. + */ + setSpeedY(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the initial radial speed of emitted particles. + * Changes the emitter to radial mode. + * @param value The speed, in pixels per second. + */ + setSpeed(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the horizontal scale of emitted particles. + * @param value The scale, relative to 1. + */ + setScaleX(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the vertical scale of emitted particles. + * @param value The scale, relative to 1. + */ + setScaleY(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the scale of emitted particles. + * @param value The scale, relative to 1. + */ + setScale(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the horizontal gravity applied to emitted particles. + * @param value Acceleration due to gravity, in pixels per second squared. + */ + setGravityX(value: number): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the vertical gravity applied to emitted particles. + * @param value Acceleration due to gravity, in pixels per second squared. + */ + setGravityY(value: number): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the gravity applied to emitted particles. + * @param x Horizontal acceleration due to gravity, in pixels per second squared. + * @param y Vertical acceleration due to gravity, in pixels per second squared. + */ + setGravity(x: number, y: number): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the opacity of emitted particles. + * @param value A value between 0 (transparent) and 1 (opaque). + */ + setAlpha(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the color tint of emitted particles. + * @param value A value between 0 and 0xffffff. + */ + setTint(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. + * @param value The angle of the initial velocity of emitted particles. + */ + setEmitterAngle(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream. + * @param value The angle of the initial velocity of emitted particles. + */ + setAngle(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the lifespan of newly emitted particles. + * @param value The particle lifespan, in ms. + */ + setLifespan(value: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the number of particles released at each flow cycle or explosion. + * @param quantity The number of particles to release at each flow cycle or explosion. + */ + setQuantity(quantity: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency} + * and {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * @param frequency The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode. + * @param quantity The number of particles to release at each flow cycle or explosion. + */ + setFrequency(frequency: number, quantity?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#emitZone}. + * + * An {@link Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig EdgeZone} places particles on its edges. Its {@link Phaser.Types.GameObjects.Particles.EdgeZoneSource source} can be a Curve, Path, Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback getPoints} method. + * + * A {@link Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig RandomZone} places randomly within its interior. Its {@link RandomZoneSource source} can be a Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback getRandomPoint} method. + * @param zoneConfig An object describing the zone, or `undefined` to remove any current emit zone. + */ + setEmitZone(zoneConfig?: Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig | Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#deathZone}. + * @param zoneConfig An object describing the zone, or `undefined` to remove any current death zone. + */ + setDeathZone(zoneConfig?: Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Creates inactive particles and adds them to this emitter's pool. + * @param particleCount The number of particles to create. + */ + reserve(particleCount: integer): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Gets the number of active (in-use) particles in this emitter. + */ + getAliveParticleCount(): integer; + + /** + * Gets the number of inactive (available) particles in this emitter. + */ + getDeadParticleCount(): integer; + + /** + * Gets the total number of particles in this emitter. + */ + getParticleCount(): integer; + + /** + * Whether this emitter is at its limit (if set). + */ + atLimit(): boolean; + + /** + * Sets a function to call for each newly emitted particle. + * @param callback The function. + * @param context The calling context. + */ + onParticleEmit(callback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback, context?: any): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sets a function to call for each particle death. + * @param callback The function. + * @param context The function's calling context. + */ + onParticleDeath(callback: Phaser.Types.GameObjects.Particles.ParticleDeathCallback, context?: any): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Deactivates every particle in this emitter. + */ + killAll(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Calls a function for each active particle in this emitter. + * @param callback The function. + * @param context The function's calling context. + */ + forEachAlive(callback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback, context: any): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Calls a function for each inactive particle in this emitter. + * @param callback The function. + * @param context The function's calling context. + */ + forEachDead(callback: Phaser.Types.GameObjects.Particles.ParticleEmitterCallback, context: any): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on} the emitter and resets the flow counter. + * + * If this emitter is in flow mode (frequency >= 0; the default), the particle flow will start (or restart). + * + * If this emitter is in explode mode (frequency = -1), nothing will happen. + * Use {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} or {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} instead. + */ + start(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on off} the emitter. + */ + stop(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Deactivates} the emitter. + */ + pause(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * {@link Phaser.GameObjects.Particles.ParticleEmitter#active Activates} the emitter. + */ + resume(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Removes the emitter from its manager and the scene. + */ + remove(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Sorts active particles with {@link Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback}. + */ + depthSort(): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Puts the emitter in flow mode (frequency >= 0) and starts (or restarts) a particle flow. + * + * To resume a flow at the current frequency and quantity, use {@link Phaser.GameObjects.Particles.ParticleEmitter#start} instead. + * @param frequency The time interval (>= 0) of each flow cycle, in ms. + * @param count The number of particles to emit at each flow cycle. Default 1. + */ + flow(frequency: number, count?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once. + * @param count The amount of Particles to emit. + * @param x The x coordinate to emit the Particles from. + * @param y The y coordinate to emit the Particles from. + */ + explode(count: integer, x: number, y: number): Phaser.GameObjects.Particles.Particle; + + /** + * Emits particles at a given position (or the emitter's current position). + * @param x The x coordinate to emit the Particles from. Default this.x. + * @param y The y coordinate to emit the Particles from. Default this.x. + * @param count The number of Particles to emit. Default this.quantity. + */ + emitParticleAt(x?: number, y?: number, count?: integer): Phaser.GameObjects.Particles.Particle; + + /** + * Emits particles at a given position (or the emitter's current position). + * @param count The number of Particles to emit. Default this.quantity. + * @param x The x coordinate to emit the Particles from. Default this.x. + * @param y The y coordinate to emit the Particles from. Default this.x. + */ + emitParticle(count?: integer, x?: number, y?: number): Phaser.GameObjects.Particles.Particle; + + /** + * Updates this emitter and its particles. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + preUpdate(time: integer, delta: number): void; + + /** + * Calculates the difference of two particles, for sorting them by depth. + * @param a The first particle. + * @param b The second particle. + */ + depthSortCallback(a: object, b: object): integer; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A Particle Emitter Manager creates and controls {@link Phaser.GameObjects.Particles.ParticleEmitter Particle Emitters} and {@link Phaser.GameObjects.Particles.GravityWell Gravity Wells}. + */ + class ParticleEmitterManager extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Emitter Manager belongs. + * @param texture The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Emitter Manager will use to render particles. + * @param emitters Configuration settings for one or more emitters to create. + */ + constructor(scene: Phaser.Scene, texture: string, frame?: string | integer, emitters?: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Phaser.Types.GameObjects.Particles.ParticleEmitterConfig[]); + + /** + * The time scale applied to all emitters and particles, affecting flow rate, lifespan, and movement. + * Values larger than 1 are faster than normal. + * This is multiplied with any timeScale set on each individual emitter. + */ + timeScale: number; + + /** + * The texture used to render this Emitter Manager's particles. + */ + texture: Phaser.Textures.Texture; + + /** + * The texture frame used to render this Emitter Manager's particles. + */ + frame: Phaser.Textures.Frame; + + /** + * Names of this Emitter Manager's texture frames. + */ + frameNames: string[]; + + /** + * A list of Emitters being managed by this Emitter Manager. + */ + emitters: Phaser.Structs.List; + + /** + * A list of Gravity Wells being managed by this Emitter Manager. + */ + wells: Phaser.Structs.List; + + /** + * Sets the texture and frame this Emitter Manager will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Sets the frame this Emitter Manager will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * @param frame The name or index of the frame within the Texture. + */ + setFrame(frame?: string | integer): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Assigns texture frames to an emitter. + * @param frames The texture frames. + * @param emitter The particle emitter to modify. + */ + setEmitterFrames(frames: Phaser.Textures.Frame | Phaser.Textures.Frame[], emitter: Phaser.GameObjects.Particles.ParticleEmitter): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Adds an existing Particle Emitter to this Emitter Manager. + * @param emitter The Particle Emitter to add to this Emitter Manager. + */ + addEmitter(emitter: Phaser.GameObjects.Particles.ParticleEmitter): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it. + * @param config Configuration settings for the Particle Emitter to create. + */ + createEmitter(config: Phaser.Types.GameObjects.Particles.ParticleEmitterConfig): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Removes a Particle Emitter from this Emitter Manager, if the Emitter belongs to this Manager. + */ + removeEmitter(emitter: Phaser.GameObjects.Particles.ParticleEmitter): Phaser.GameObjects.Particles.ParticleEmitter; + + /** + * Adds an existing Gravity Well object to this Emitter Manager. + * @param well The Gravity Well to add to this Emitter Manager. + */ + addGravityWell(well: Phaser.GameObjects.Particles.GravityWell): Phaser.GameObjects.Particles.GravityWell; + + /** + * Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it. + * @param config Configuration settings for the Gravity Well to create. + */ + createGravityWell(config: Phaser.Types.GameObjects.Particles.GravityWellConfig): Phaser.GameObjects.Particles.GravityWell; + + /** + * Emits particles from each active emitter. + * @param count The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + * @param x The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. + * @param y The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. + */ + emitParticle(count?: integer, x?: number, y?: number): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Emits particles from each active emitter. + * @param x The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location. + * @param y The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location. + * @param count The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}. + */ + emitParticleAt(x?: number, y?: number, count?: integer): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Pauses this Emitter Manager. + * + * This has the effect of pausing all emitters, and all particles of those emitters, currently under its control. + * + * The particles will still render, but they will not have any of their logic updated. + */ + pause(): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Resumes this Emitter Manager, should it have been previously paused. + */ + resume(): Phaser.GameObjects.Particles.ParticleEmitterManager; + + /** + * Gets all active particle processors (gravity wells). + */ + getProcessors(): Phaser.GameObjects.Particles.GravityWell[]; + + /** + * Updates all active emitters. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + preUpdate(time: integer, delta: number): void; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + namespace Zones { + /** + * A Death Zone. + * + * A Death Zone is a special type of zone that will kill a Particle as soon as it either enters, or leaves, the zone. + * + * The zone consists of a `source` which could be a Geometric shape, such as a Rectangle or Ellipse, or your own + * object as long as it includes a `contains` method for which the Particles can be tested against. + */ + class DeathZone { + /** + * + * @param source An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. + * @param killOnEnter Should the Particle be killed when it enters the zone? `true` or leaves it? `false` + */ + constructor(source: Phaser.Types.GameObjects.Particles.DeathZoneSource, killOnEnter: boolean); + + /** + * An object instance that has a `contains` method that returns a boolean when given `x` and `y` arguments. + * This could be a Geometry shape, such as `Phaser.Geom.Circle`, or your own custom object. + */ + source: Phaser.Types.GameObjects.Particles.DeathZoneSource; + + /** + * Set to `true` if the Particle should be killed if it enters this zone. + * Set to `false` to kill the Particle if it leaves this zone. + */ + killOnEnter: boolean; + + /** + * Checks if the given Particle will be killed or not by this zone. + * @param particle The Particle to be checked against this zone. + */ + willKill(particle: Phaser.GameObjects.Particles.Particle): boolean; + + } + + /** + * A zone that places particles on a shape's edges. + */ + class EdgeZone { + /** + * + * @param source An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + * @param quantity The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + * @param stepRate The distance between each particle. When set, `quantity` is implied and should be set to 0. + * @param yoyo Whether particles are placed from start to end and then end to start. Default false. + * @param seamless Whether one endpoint will be removed if it's identical to the other. Default true. + */ + constructor(source: Phaser.Types.GameObjects.Particles.EdgeZoneSource, quantity: integer, stepRate: number, yoyo?: boolean, seamless?: boolean); + + /** + * An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + */ + source: Phaser.Types.GameObjects.Particles.EdgeZoneSource | Phaser.Types.GameObjects.Particles.RandomZoneSource; + + /** + * The points placed on the source edge. + */ + points: Phaser.Geom.Point[]; + + /** + * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + */ + quantity: integer; + + /** + * The distance between each particle. When set, `quantity` is implied and should be set to 0. + */ + stepRate: number; + + /** + * Whether particles are placed from start to end and then end to start. + */ + yoyo: boolean; + + /** + * The counter used for iterating the EdgeZone's points. + */ + counter: number; + + /** + * Whether one endpoint will be removed if it's identical to the other. + */ + seamless: boolean; + + /** + * Update the {@link Phaser.GameObjects.Particles.Zones.EdgeZone#points} from the EdgeZone's + * {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. + * + * Also updates internal properties. + */ + updateSource(): Phaser.GameObjects.Particles.Zones.EdgeZone; + + /** + * Change the source of the EdgeZone. + * @param source An object instance with a `getPoints(quantity, stepRate)` method returning an array of points. + */ + changeSource(source: Phaser.Types.GameObjects.Particles.EdgeZoneSource): Phaser.GameObjects.Particles.Zones.EdgeZone; + + /** + * Get the next point in the Zone and set its coordinates on the given Particle. + * @param particle The Particle. + */ + getPoint(particle: Phaser.GameObjects.Particles.Particle): void; + + } + + /** + * A zone that places particles randomly within a shape's area. + */ + class RandomZone { + /** + * + * @param source An object instance with a `getRandomPoint(point)` method. + */ + constructor(source: Phaser.Types.GameObjects.Particles.RandomZoneSource); + + /** + * An object instance with a `getRandomPoint(point)` method. + */ + source: Phaser.Types.GameObjects.Particles.RandomZoneSource; + + /** + * Get the next point in the Zone and set its coordinates on the given Particle. + * @param particle The Particle. + */ + getPoint(particle: Phaser.GameObjects.Particles.Particle): void; + + } + + } + + } + + /** + * A PathFollower Game Object. + * + * A PathFollower is a Sprite Game Object with some extra helpers to allow it to follow a Path automatically. + * + * Anything you can do with a standard Sprite can be done with this PathFollower, such as animate it, tint it, + * scale it and so on. + * + * PathFollowers are bound to a single Path at any one time and can traverse the length of the Path, from start + * to finish, forwards or backwards, or from any given point on the Path to its end. They can optionally rotate + * to face the direction of the path, be offset from the path coordinates or rotate independently of the Path. + */ + class PathFollower extends Phaser.GameObjects.Sprite implements Phaser.GameObjects.Components.PathFollower { + /** + * + * @param scene The Scene to which this PathFollower belongs. + * @param path The Path this PathFollower is following. It can only follow one Path at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, path: Phaser.Curves.Path, x: number, y: number, texture: string, frame?: string | integer); + + /** + * If the PathFollower is rotating to match the Path (@see Phaser.GameObjects.PathFollower#rotateToPath) + * this value is added to the rotation value. This allows you to rotate objects to a path but control + * the angle of the rotation as well. + */ + pathRotationOffset: number; + + /** + * An additional vector to add to the PathFollowers position, allowing you to offset it from the + * Path coordinates. + */ + pathOffset: Phaser.Math.Vector2; + + /** + * A Vector2 that stores the current point of the path the follower is on. + */ + pathVector: Phaser.Math.Vector2; + + /** + * The Tween used for following the Path. + */ + pathTween: Phaser.Tweens.Tween; + + /** + * Settings for the PathFollower. + */ + pathConfig: Phaser.Types.GameObjects.PathFollower.PathConfig; + + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + protected preUpdate(time: integer, delta: number): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * The Path this PathFollower is following. It can only follow one Path at a time. + */ + path: Phaser.Curves.Path; + + /** + * Should the PathFollower automatically rotate to point in the direction of the Path? + */ + rotateToPath: boolean; + + /** + * Set the Path that this PathFollower should follow. + * + * Optionally accepts {@link Phaser.Types.GameObjects.PathFollower.PathConfig} settings. + * @param path The Path this PathFollower is following. It can only follow one Path at a time. + * @param config Settings for the PathFollower. + */ + setPath(path: Phaser.Curves.Path, config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig): Phaser.GameObjects.PathFollower; + + /** + * Set whether the PathFollower should automatically rotate to point in the direction of the Path. + * @param value Whether the PathFollower should automatically rotate to point in the direction of the Path. + * @param offset Rotation offset in degrees. Default 0. + */ + setRotateToPath(value: boolean, offset?: number): Phaser.GameObjects.PathFollower; + + /** + * Is this PathFollower actively following a Path or not? + * + * To be considered as `isFollowing` it must be currently moving on a Path, and not paused. + */ + isFollowing(): boolean; + + /** + * Starts this PathFollower following its given Path. + * @param config The duration of the follow, or a PathFollower config object. Default {}. + * @param startAt Optional start position of the follow, between 0 and 1. Default 0. + */ + startFollow(config?: number | Phaser.Types.GameObjects.PathFollower.PathConfig | Phaser.Types.Tweens.NumberTweenBuilderConfig, startAt?: number): Phaser.GameObjects.PathFollower; + + /** + * Pauses this PathFollower. It will still continue to render, but it will remain motionless at the + * point on the Path at which you paused it. + */ + pauseFollow(): Phaser.GameObjects.PathFollower; + + /** + * Resumes a previously paused PathFollower. + * + * If the PathFollower was not paused this has no effect. + */ + resumeFollow(): Phaser.GameObjects.PathFollower; + + /** + * Stops this PathFollower from following the path any longer. + * + * This will invoke any 'stop' conditions that may exist on the Path, or for the follower. + */ + stopFollow(): Phaser.GameObjects.PathFollower; + + /** + * Internal update handler that advances this PathFollower along the path. + * + * Called automatically by the Scene step, should not typically be called directly. + */ + pathUpdate(): void; + + } + + /** + * A Quad Game Object. + * + * A Quad is a Mesh Game Object pre-configured with two triangles arranged into a rectangle, with a single + * texture spread across them. + * + * You can manipulate the corner points of the quad via the getters and setters such as `topLeftX`, and also + * change their alpha and color values. The quad itself can be moved by adjusting the `x` and `y` properties. + */ + class Quad extends Phaser.GameObjects.Mesh { + /** + * + * @param scene The Scene to which this Quad belongs. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + */ + setFrame(frame: string | integer): this; + + /** + * The top-left x vertex of this Quad. + */ + topLeftX: number; + + /** + * The top-left y vertex of this Quad. + */ + topLeftY: number; + + /** + * The top-right x vertex of this Quad. + */ + topRightX: number; + + /** + * The top-right y vertex of this Quad. + */ + topRightY: number; + + /** + * The bottom-left x vertex of this Quad. + */ + bottomLeftX: number; + + /** + * The bottom-left y vertex of this Quad. + */ + bottomLeftY: number; + + /** + * The bottom-right x vertex of this Quad. + */ + bottomRightX: number; + + /** + * The bottom-right y vertex of this Quad. + */ + bottomRightY: number; + + /** + * The top-left alpha value of this Quad. + */ + topLeftAlpha: number; + + /** + * The top-right alpha value of this Quad. + */ + topRightAlpha: number; + + /** + * The bottom-left alpha value of this Quad. + */ + bottomLeftAlpha: number; + + /** + * The bottom-right alpha value of this Quad. + */ + bottomRightAlpha: number; + + /** + * The top-left color value of this Quad. + */ + topLeftColor: number; + + /** + * The top-right color value of this Quad. + */ + topRightColor: number; + + /** + * The bottom-left color value of this Quad. + */ + bottomLeftColor: number; + + /** + * The bottom-right color value of this Quad. + */ + bottomRightColor: number; + + /** + * Sets the top-left vertex position of this Quad. + * @param x The horizontal coordinate of the vertex. + * @param y The vertical coordinate of the vertex. + */ + setTopLeft(x: number, y: number): Phaser.GameObjects.Quad; + + /** + * Sets the top-right vertex position of this Quad. + * @param x The horizontal coordinate of the vertex. + * @param y The vertical coordinate of the vertex. + */ + setTopRight(x: number, y: number): Phaser.GameObjects.Quad; + + /** + * Sets the bottom-left vertex position of this Quad. + * @param x The horizontal coordinate of the vertex. + * @param y The vertical coordinate of the vertex. + */ + setBottomLeft(x: number, y: number): Phaser.GameObjects.Quad; + + /** + * Sets the bottom-right vertex position of this Quad. + * @param x The horizontal coordinate of the vertex. + * @param y The vertical coordinate of the vertex. + */ + setBottomRight(x: number, y: number): Phaser.GameObjects.Quad; + + /** + * Resets the positions of the four corner vertices of this Quad. + */ + resetPosition(): Phaser.GameObjects.Quad; + + /** + * Resets the alpha values used by this Quad back to 1. + */ + resetAlpha(): Phaser.GameObjects.Quad; + + /** + * Resets the color values used by this Quad back to 0xffffff. + */ + resetColors(): Phaser.GameObjects.Quad; + + /** + * Resets the position, alpha and color values used by this Quad. + */ + reset(): Phaser.GameObjects.Quad; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager, or a Texture instance. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string | Phaser.Textures.Texture, frame?: string | integer): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + } + + /** + * A Render Texture. + * + * A Render Texture is a special texture that allows any number of Game Objects to be drawn to it. You can take many complex objects and + * draw them all to this one texture, which can they be used as the texture for other Game Object's. It's a way to generate dynamic + * textures at run-time that are WebGL friendly and don't invoke expensive GPU uploads. + * + * Note that under WebGL a FrameBuffer, which is what the Render Texture uses internally, cannot be anti-aliased. This means + * that when drawing objects such as Shapes to a Render Texture they will appear to be drawn with no aliasing, however this + * is a technical limitation of WebGL. To get around it, create your shape as a texture in an art package, then draw that + * to the Render Texture. + */ + class RenderTexture extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Crop, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the Render Texture. Default 32. + * @param height The height of the Render Texture. Default 32. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, width?: integer, height?: integer); + + /** + * A reference to either the Canvas or WebGL Renderer that the Game instance is using. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * A reference to the Texture Manager. + */ + textureManager: Phaser.Textures.TextureManager; + + /** + * The tint of the Render Texture when rendered. + */ + globalTint: number; + + /** + * The alpha of the Render Texture when rendered. + */ + globalAlpha: number; + + /** + * The HTML Canvas Element that the Render Texture is drawing to when using the Canvas Renderer. + */ + canvas: HTMLCanvasElement; + + /** + * A reference to the GL Frame Buffer this Render Texture is drawing to. + * This is only set if Phaser is running with the WebGL Renderer. + */ + framebuffer: WebGLFramebuffer; + + /** + * Is this Render Texture dirty or not? If not it won't spend time clearing or filling itself. + */ + dirty: boolean; + + /** + * The Texture corresponding to this Render Texture. + */ + texture: Phaser.Textures.Texture; + + /** + * The Frame corresponding to this Render Texture. + */ + frame: Phaser.Textures.Frame; + + /** + * A reference to the Rendering Context belonging to the Canvas Element this Render Texture is drawing to. + */ + context: CanvasRenderingContext2D; + + /** + * An internal Camera that can be used to move around the Render Texture. + * Control it just like you would any Scene Camera. The difference is that it only impacts the placement of what + * is drawn to the Render Texture. You can scroll, zoom and rotate this Camera. + */ + camera: Phaser.Cameras.Scene2D.BaseCamera; + + /** + * A reference to the WebGL Rendering Context. + */ + gl: WebGLRenderingContext; + + /** + * A reference to the WebGLTexture that is being rendered to in a WebGL Context. + */ + readonly glTexture: WebGLTexture; + + /** + * Sets the size of this Game Object. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Resizes the Render Texture to the new dimensions given. + * + * If Render Texture was created from specific frame, only the size of the frame will be changed. The size of the source + * texture will not change. + * + * If Render Texture was not created from specific frame, the following will happen: + * In WebGL it will destroy and then re-create the frame buffer being used by the Render Texture. + * In Canvas it will resize the underlying canvas element. + * Both approaches will erase everything currently drawn to the Render Texture. + * + * If the dimensions given are the same as those already being used, calling this method will do nothing. + * @param width The new width of the Render Texture. + * @param height The new height of the Render Texture. If not specified, will be set the same as the `width`. Default width. + */ + resize(width: number, height?: number): this; + + /** + * Set the tint to use when rendering this Render Texture. + * @param tint The tint value. + */ + setGlobalTint(tint: integer): this; + + /** + * Set the alpha to use when rendering this Render Texture. + * @param alpha The alpha value. + */ + setGlobalAlpha(alpha: number): this; + + /** + * Stores a copy of this Render Texture in the Texture Manager using the given key. + * + * After doing this, any texture based Game Object, such as a Sprite, can use the contents of this + * Render Texture by using the texture key: + * + * ```javascript + * var rt = this.add.renderTexture(0, 0, 128, 128); + * + * // Draw something to the Render Texture + * + * rt.saveTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Updating the contents of this Render Texture will automatically update _any_ Game Object + * that is using it as a texture. Calling `saveTexture` again will not save another copy + * of the same texture, it will just rename the key of the existing copy. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame from a Render Texture. + * @param key The unique key to store the texture as within the global Texture Manager. + */ + saveTexture(key: string): Phaser.Textures.Texture; + + /** + * Fills the Render Texture with the given color. + * @param rgb The color to fill the Render Texture with. + * @param alpha The alpha value used by the fill. Default 1. + * @param x The left coordinate of the fill rectangle. Default 0. + * @param y The top coordinate of the fill rectangle. Default 0. + * @param width The width of the fill rectangle. Default this.frame.cutWidth. + * @param height The height of the fill rectangle. Default this.frame.cutHeight. + */ + fill(rgb: number, alpha?: number, x?: number, y?: number, width?: number, height?: number): this; + + /** + * Clears the Render Texture. + */ + clear(): this; + + /** + * Draws the given object, or an array of objects, to this Render Texture using a blend mode of ERASE. + * This has the effect of erasing any filled pixels in the objects from this Render Texture. + * + * It can accept any of the following: + * + * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. + * * Another Render Texture. + * * A Texture Frame instance. + * * A string. This is used to look-up a texture from the Texture Manager. + * + * Note: You cannot erase a Render Texture from itself. + * + * 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. + * + * 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. + * + * Calling this method causes the WebGL batch to flush, so it can write the texture + * data to the framebuffer being used internally. The batch is flushed at the end, + * after the entries have been iterated. So if you've a bunch of objects to draw, + * try and pass them in an array in one single call, rather than making lots of + * separate calls. + * @param entries Any renderable Game Object, or Group, Container, Display List, other Render Texture, Texture Frame or an array of any of these. + * @param x The x position to draw the Frame at, or the offset applied to the object. + * @param y The y position to draw the Frame at, or the offset applied to the object. + */ + erase(entries: any, x?: number, y?: number): this; + + /** + * Draws the given object, or an array of objects, to this Render Texture. + * + * It can accept any of the following: + * + * * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite. + * * Dynamic and Static 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's Display List. Pass in `Scene.children` to draw the whole list. + * * Another Render Texture. + * * A Texture Frame instance. + * * A string. This is used to look-up a texture from the Texture Manager. + * + * Note: You cannot draw a Render Texture to itself. + * + * 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. + * + * The `alpha` and `tint` values are only used by Texture Frames. + * Game Objects use their own alpha and tint values when being drawn. + * + * Calling this method causes the WebGL batch to flush, so it can write the texture + * data to the framebuffer being used internally. The batch is flushed at the end, + * after the entries have been iterated. So if you've a bunch of objects to draw, + * try and pass them in an array in one single call, rather than making lots of + * separate calls. + * @param entries Any renderable Game Object, or Group, Container, Display List, other Render Texture, Texture Frame or an array of any of these. + * @param x The x position to draw the Frame at, or the offset applied to the object. + * @param y The y position to draw the Frame at, or the offset applied to the object. + * @param alpha The alpha value. Only used for Texture Frames and if not specified defaults to the `globalAlpha` property. Game Objects use their own current alpha value. + * @param tint WebGL only. The tint color value. Only used for Texture Frames and if not specified defaults to the `globalTint` property. Game Objects use their own current tint value. + */ + draw(entries: any, x?: number, y?: number, alpha?: number, tint?: number): this; + + /** + * Draws the Texture Frame to the Render Texture at the given position. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * + * ```javascript + * var rt = this.add.renderTexture(0, 0, 800, 600); + * rt.drawFrame(key, frame); + * ``` + * + * You can optionally provide a position, alpha and tint value to apply to the frame + * before it is drawn. + * + * Calling this method will cause a batch flush, so if you've got a stack of things to draw + * in a tight loop, try using the `draw` method instead. + * + * If you need to draw a Sprite to this Render Texture, use the `draw` method instead. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + * @param x The x position to draw the frame at. Default 0. + * @param y The y position to draw the frame at. Default 0. + * @param alpha The alpha to use. If not specified it uses the `globalAlpha` property. + * @param tint WebGL only. The tint color to use. If not specified it uses the `globalTint` property. + */ + drawFrame(key: string, frame?: string | integer, x?: number, y?: number, alpha?: number, tint?: number): this; + + /** + * Takes a snapshot of the given area of this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture the whole Render Texture see the `snapshot` method. To capture a specific pixel, see `snapshotPixel`. + * + * 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. + * @param x The x coordinate to grab from. + * @param y The y coordinate to grab from. + * @param width The width of the area to grab. + * @param height The height of the area to grab. + * @param callback The Function to invoke after the snapshot image is created. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshotArea(x: integer, y: integer, width: integer, height: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; + + /** + * Takes a snapshot of the whole of this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture just a portion of the Render Texture see the `snapshotArea` method. To capture a specific pixel, see `snapshotPixel`. + * + * 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. + * @param callback The Function to invoke after the snapshot image is created. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshot(callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; + + /** + * Takes a snapshot of the given pixel from this Render Texture. + * + * The snapshot is taken immediately. + * + * To capture the whole Render Texture see the `snapshot` method. To capture a specific portion, see `snapshotArea`. + * + * Unlike the other two snapshot methods, this one will send your callback 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, than the other snapshot methods. + * @param x The x coordinate of the pixel to get. + * @param y The y coordinate of the pixel to get. + * @param callback The Function to invoke after the snapshot pixel data is extracted. + */ + snapshotPixel(x: integer, y: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback): this; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A Shader Game Object. + * + * This Game Object allows you to easily add a quad with its own shader into the display list, and manipulate it + * as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders + * can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other + * Game Object. They can also be made interactive and used for input events. + * + * It works by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can + * be created dynamically at runtime, or loaded in via the GLSL File Loader: + * + * ```javascript + * function preload () + * { + * this.load.glsl('fire', 'shaders/fire.glsl.js'); + * } + * + * function create () + * { + * this.add.shader('fire', 400, 300, 512, 512); + * } + * ``` + * + * Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically. + * + * Due to the way in which they work, you cannot directly change the alpha or blend mode of a Shader. This should + * be handled via exposed uniforms in the shader code itself. + * + * By default a Shader will be created with a standard set of uniforms. These were added to match those + * found on sites such as ShaderToy or GLSLSandbox, and provide common functionality a shader may need, + * such as the timestamp, resolution or pointer position. You can replace them by specifying your own uniforms + * in the Base Shader. + * + * These Shaders work by halting the current pipeline during rendering, creating a viewport matched to the + * size of this Game Object and then renders a quad using the bound shader. At the end, the pipeline is restored. + * + * Because it blocks the pipeline it means it will interrupt any batching that is currently going on, so you should + * use these Game Objects sparingly. If you need to have a fully batched custom shader, then please look at using + * a custom pipeline instead. However, for background or special masking effects, they are extremely effective. + */ + class Shader extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param key The key of the shader to use from the shader cache, or a BaseShader instance. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the Game Object. Default 128. + * @param height The height of the Game Object. Default 128. + * @param textures Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param textureData Additional texture data if you want to create shader with none NPOT textures. + */ + constructor(scene: Phaser.Scene, key: string | Phaser.Display.BaseShader, x?: number, y?: number, width?: number, height?: number, textures?: string[], textureData?: any); + + /** + * The underlying shader object being used. + * Empty by default and set during a call to the `setShader` method. + */ + shader: Phaser.Display.BaseShader; + + /** + * A reference to the current renderer. + * Shaders only work with the WebGL Renderer. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * The WebGL context belonging to the renderer. + */ + gl: WebGLRenderingContext; + + /** + * Raw byte buffer of vertices this Shader uses. + */ + vertexData: ArrayBuffer; + + /** + * The WebGL vertex buffer object this shader uses. + */ + vertexBuffer: WebGLBuffer; + + /** + * The WebGL shader program this shader uses. + */ + program: WebGLProgram; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources to the GPU. + */ + bytes: Uint8Array; + + /** + * Float32 view of the array buffer containing the shaders vertices. + */ + vertexViewF32: Float32Array; + + /** + * The view matrix the shader uses during rendering. + */ + readonly viewMatrix: Float32Array; + + /** + * The projection matrix the shader uses during rendering. + */ + readonly projectionMatrix: Float32Array; + + /** + * The default uniform mappings. These can be added to (or replaced) by specifying your own uniforms when + * creating this shader game object. The uniforms are updated automatically during the render step. + * + * The defaults are: + * + * `resolution` (2f) - Set to the size of this shader. + * `time` (1f) - The elapsed game time, in seconds. + * `mouse` (2f) - If a pointer has been bound (with `setPointer`), this uniform contains its position each frame. + * `date` (4fv) - A vec4 containing the year, month, day and time in seconds. + * `sampleRate` (1f) - Sound sample rate. 44100 by default. + * `iChannel0...3` (sampler2D) - Input channels 0 to 3. `null` by default. + */ + uniforms: any; + + /** + * The pointer bound to this shader, if any. + * Set via the chainable `setPointer` method, or by modifying this property directly. + */ + pointer: Phaser.Input.Pointer; + + /** + * A reference to the GL Frame Buffer this Shader is drawing to. + * This property is only set if you have called `Shader.setRenderToTexture`. + */ + framebuffer: WebGLFramebuffer; + + /** + * A reference to the WebGLTexture this Shader is rendering to. + * This property is only set if you have called `Shader.setRenderToTexture`. + */ + glTexture: WebGLTexture; + + /** + * A flag that indicates if this Shader has been set to render to a texture instead of the display list. + * + * This property is `true` if you have called `Shader.setRenderToTexture`, otherwise it's `false`. + * + * A Shader that is rendering to a texture _does not_ appear on the display list. + */ + readonly renderToTexture: boolean; + + /** + * A reference to the Phaser.Textures.Texture that has been stored in the Texture Manager for this Shader. + * + * This property is only set if you have called `Shader.setRenderToTexture`, otherwise it is `null`. + */ + texture: Phaser.Textures.Texture; + + /** + * Compares the renderMask with the renderFlags to see if this Game Object will render or not. + * Also checks the Game Object against the given Cameras exclusion list. + * @param camera The Camera to check against this Game Object. + */ + willRender(camera: Phaser.Cameras.Scene2D.Camera): boolean; + + /** + * Changes this Shader so instead of rendering to the display list it renders to a + * WebGL Framebuffer and WebGL Texture instead. This allows you to use the output + * of this shader as an input for another shader, by mapping a sampler2D uniform + * to it. + * + * After calling this method the `Shader.framebuffer` and `Shader.glTexture` properties + * are populated. + * + * Additionally, you can provide a key to this method. Doing so will create a Phaser Texture + * from this Shader and save it into the Texture Manager, allowing you to then use it for + * any texture-based Game Object, such as a Sprite or Image: + * + * ```javascript + * var shader = this.add.shader('myShader', x, y, width, height); + * + * shader.setRenderToTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Note that it stores an active reference to this Shader. That means as this shader updates, + * so does the texture and any object using it to render with. Also, if you destroy this + * shader, be sure to clear any objects that may have been using it as a texture too. + * + * You can access the Phaser Texture that is created via the `Shader.texture` property. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame from a Render Texture. + * @param key The unique key to store the texture as within the global Texture Manager. + * @param flipY Does this texture need vertically flipping before rendering? This should usually be set to `true` if being fed from a buffer. Default false. + */ + setRenderToTexture(key?: string, flipY?: boolean): this; + + /** + * Sets the fragment and, optionally, the vertex shader source code that this Shader will use. + * This will immediately delete the active shader program, if set, and then create a new one + * with the given source. Finally, the shader uniforms are initialized. + * @param key The key of the shader to use from the shader cache, or a BaseShader instance. + * @param textures Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager. + * @param textureData Additional texture data. + */ + setShader(key: string | Phaser.Display.BaseShader, textures?: string[], textureData?: any): this; + + /** + * Binds a Phaser Pointer object to this Shader. + * + * The screen position of the pointer will be set in to the shaders `mouse` uniform + * automatically every frame. Call this method with no arguments to unbind the pointer. + * @param pointer The Pointer to bind to this shader. + */ + setPointer(pointer?: Phaser.Input.Pointer): this; + + /** + * Sets this shader to use an orthographic projection matrix. + * This matrix is stored locally in the `projectionMatrix` property, + * as well as being bound to the `uProjectionMatrix` uniform. + * @param left The left value. + * @param right The right value. + * @param bottom The bottom value. + * @param top The top value. + */ + projOrtho(left: number, right: number, bottom: number, top: number): void; + + /** + * Sets a sampler2D uniform on this shader where the source texture is a WebGLTexture. + * + * This allows you to feed the output from one Shader into another: + * + * ```javascript + * let shader1 = this.add.shader(baseShader1, 0, 0, 512, 512).setRenderToTexture(); + * let shader2 = this.add.shader(baseShader2, 0, 0, 512, 512).setRenderToTexture('output'); + * + * shader1.setSampler2DBuffer('iChannel0', shader2.glTexture, 512, 512); + * shader2.setSampler2DBuffer('iChannel0', shader1.glTexture, 512, 512); + * ``` + * + * In the above code, the result of baseShader1 is fed into Shader2 as the `iChannel0` sampler2D uniform. + * The result of baseShader2 is then fed back into shader1 again, creating a feedback loop. + * + * If you wish to use an image from the Texture Manager as a sampler2D input for this shader, + * see the `Shader.setSampler2D` method. + * @param uniformKey The key of the sampler2D uniform to be updated, i.e. `iChannel0`. + * @param texture A WebGLTexture reference. + * @param width The width of the texture. + * @param height The height of the texture. + * @param textureIndex The texture index. Default 0. + * @param textureData Additional texture data. + */ + setSampler2DBuffer(uniformKey: string, texture: WebGLTexture, width: integer, height: integer, textureIndex?: integer, textureData?: any): this; + + /** + * Sets a sampler2D uniform on this shader. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * + * If you wish to use another Shader as a sampler2D input for this shader, see the `Shader.setSampler2DBuffer` method. + * @param uniformKey The key of the sampler2D uniform to be updated, i.e. `iChannel0`. + * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param textureIndex The texture index. Default 0. + * @param textureData Additional texture data. + */ + setSampler2D(uniformKey: string, textureKey: string, textureIndex?: integer, textureData?: any): this; + + /** + * Sets a property of a uniform already present on this shader. + * + * To modify the value of a uniform such as a 1f or 1i use the `value` property directly: + * + * ```javascript + * shader.setUniform('size.value', 16); + * ``` + * + * You can use dot notation to access deeper values, for example: + * + * ```javascript + * shader.setUniform('resolution.value.x', 512); + * ``` + * + * The change to the uniform will take effect the next time the shader is rendered. + * @param key The key of the uniform to modify. Use dots for deep properties, i.e. `resolution.value.x`. + * @param value The value to set into the uniform. + */ + setUniform(key: string, value: any): this; + + /** + * Returns the uniform object for the given key, or `null` if the uniform couldn't be found. + * @param key The key of the uniform to return the value for. + */ + getUniform(key: string): any; + + /** + * A short-cut method that will directly set the texture being used by the `iChannel0` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param textureData Additional texture data. + */ + setChannel0(textureKey: string, textureData?: any): this; + + /** + * A short-cut method that will directly set the texture being used by the `iChannel1` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param textureData Additional texture data. + */ + setChannel1(textureKey: string, textureData?: any): this; + + /** + * A short-cut method that will directly set the texture being used by the `iChannel2` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param textureData Additional texture data. + */ + setChannel2(textureKey: string, textureData?: any): this; + + /** + * A short-cut method that will directly set the texture being used by the `iChannel3` sampler2D uniform. + * + * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame + * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized. + * @param textureKey The key of the texture, as stored in the Texture Manager. Must already be loaded. + * @param textureData Additional texture data. + */ + setChannel3(textureKey: string, textureData?: any): this; + + /** + * Called automatically during render. + * + * This method performs matrix ITRS and then stores the resulting value in the `uViewMatrix` uniform. + * It then sets up the vertex buffer and shader, updates and syncs the uniforms ready + * for flush to be called. + * @param matrix2D The transform matrix to use during rendering. + */ + load(matrix2D?: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Called automatically during render. + * + * Sets the active shader, loads the vertex buffer and then draws. + */ + flush(): void; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Arc Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an arc shape. You can control the start and end angles of the arc, + * as well as if the angles are winding clockwise or anti-clockwise. With the default settings + * it renders as a complete circle. By changing the angles you can create other arc shapes, + * such as half-circles. + * + * Arcs also have an `iterations` property and corresponding `setIterations` method. This allows + * you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. + */ + class Arc extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param radius The radius of the arc. Default 128. + * @param startAngle The start angle of the arc, in degrees. Default 0. + * @param endAngle The end angle of the arc, in degrees. Default 360. + * @param anticlockwise The winding order of the start and end angles. Default false. + * @param fillColor The color the arc will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the arc will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, radius?: number, startAngle?: integer, endAngle?: integer, anticlockwise?: boolean, fillColor?: number, fillAlpha?: number); + + /** + * The number of iterations used when drawing the arc. + * Increase this value for smoother arcs, at the cost of more polygons being rendered. + * Modify this value by small amounts, such as 0.01. + */ + iterations: number; + + /** + * The radius of the arc. + */ + radius: number; + + /** + * The start angle of the arc, in degrees. + */ + startAngle: integer; + + /** + * The end angle of the arc, in degrees. + */ + endAngle: integer; + + /** + * The winding order of the start and end angles. + */ + anticlockwise: boolean; + + /** + * Sets the radius of the arc. + * This call can be chained. + * @param value The value to set the radius to. + */ + setRadius(value: number): this; + + /** + * Sets the number of iterations used when drawing the arc. + * Increase this value for smoother arcs, at the cost of more polygons being rendered. + * Modify this value by small amounts, such as 0.01. + * This call can be chained. + * @param value The value to set the iterations to. + */ + setIterations(value: number): this; + + /** + * Sets the starting angle of the arc, in degrees. + * This call can be chained. + * @param value The value to set the starting angle to. + */ + setStartAngle(value: integer): this; + + /** + * Sets the ending angle of the arc, in degrees. + * This call can be chained. + * @param value The value to set the ending angle to. + */ + setEndAngle(value: integer): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Curve Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * To render a Curve Shape you must first create a `Phaser.Curves.Curve` object, then pass it to + * the Curve Shape in the constructor. + * + * The Curve shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + */ + class Curve extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param curve The Curve object to use to create the Shape. + * @param fillColor The color the curve will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the curve will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, curve?: Phaser.Curves.Curve, fillColor?: number, fillAlpha?: number); + + /** + * The smoothness of the curve. The number of points used when rendering it. + * Increase this value for smoother curves, at the cost of more polygons being rendered. + */ + smoothness: integer; + + /** + * Sets the smoothness of the curve. The number of points used when rendering it. + * Increase this value for smoother curves, at the cost of more polygons being rendered. + * This call can be chained. + * @param value The value to set the smoothness to. + */ + setSmoothness(value: integer): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Ellipse Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * When it renders it displays an ellipse shape. You can control the width and height of the ellipse. + * If the width and height match it will render as a circle. If the width is less than the height, + * it will look more like an egg shape. + * + * The Ellipse shape also has a `smoothness` property and corresponding `setSmoothness` method. + * This allows you to control how smooth the shape renders in WebGL, by controlling the number of iterations + * that take place during construction. Increase and decrease the default value for smoother, or more + * jagged, shapes. + */ + class Ellipse extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. + * @param height The height of the ellipse. An ellipse with equal width and height renders as a circle. Default 128. + * @param fillColor The color the ellipse will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the ellipse will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number); + + /** + * The smoothness of the ellipse. The number of points used when rendering it. + * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. + */ + smoothness: integer; + + /** + * Sets the size of the ellipse by changing the underlying geometry data, rather than scaling the object. + * This call can be chained. + * @param width The width of the ellipse. + * @param height The height of the ellipse. + */ + setSize(width: number, height: number): this; + + /** + * Sets the smoothness of the ellipse. The number of points used when rendering it. + * Increase this value for a smoother ellipse, at the cost of more polygons being rendered. + * This call can be chained. + * @param value The value to set the smoothness to. + */ + setSmoothness(value: integer): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Grid Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * A Grid Shape allows you to display a grid in your game, where you can control the size of the + * grid as well as the width and height of the grid cells. You can set a fill color for each grid + * cell as well as an alternate fill color. When the alternate fill color is set then the grid + * cells will alternate the fill colors as they render, creating a chess-board effect. You can + * also optionally have an outline fill color. If set, this draws lines between the grid cells + * in the given color. If you specify an outline color with an alpha of zero, then it will draw + * the cells spaced out, but without the lines between them. + */ + class Grid extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param width The width of the grid. Default 128. + * @param height The height of the grid. Default 128. + * @param cellWidth The width of one cell in the grid. Default 32. + * @param cellHeight The height of one cell in the grid. Default 32. + * @param fillColor The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + * @param outlineFillColor The color of the lines between the grid cells. See the `setOutline` method. + * @param outlineFillAlpha The alpha of the lines between the grid cells. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, width?: number, height?: number, cellWidth?: number, cellHeight?: number, fillColor?: number, fillAlpha?: number, outlineFillColor?: number, outlineFillAlpha?: number); + + /** + * The width of each grid cell. + * Must be a positive value. + */ + cellWidth: number; + + /** + * The height of each grid cell. + * Must be a positive value. + */ + cellHeight: number; + + /** + * Will the grid render its cells in the `fillColor`? + */ + showCells: boolean; + + /** + * The color of the lines between each grid cell. + */ + outlineFillColor: number; + + /** + * The alpha value for the color of the lines between each grid cell. + */ + outlineFillAlpha: number; + + /** + * Will the grid display the lines between each cell when it renders? + */ + showOutline: boolean; + + /** + * Will the grid render the alternating cells in the `altFillColor`? + */ + showAltCells: boolean; + + /** + * The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. + */ + altFillColor: number; + + /** + * The alpha the alternating grid cells will be filled with. + * You can also set the alpha of the overall Shape using its `alpha` property. + */ + altFillAlpha: number; + + /** + * Sets the fill color and alpha level the grid cells will use when rendering. + * + * If this method is called with no values then the grid cells will not be rendered, + * however the grid lines and alternating cells may still be. + * + * Also see the `setOutlineStyle` and `setAltFillStyle` methods. + * + * This call can be chained. + * @param fillColor The color the grid cells will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. Default 1. + */ + setFillStyle(fillColor?: number, fillAlpha?: number): this; + + /** + * Sets the fill color and alpha level that the alternating grid cells will use. + * + * If this method is called with no values then alternating grid cells will not be rendered in a different color. + * + * Also see the `setOutlineStyle` and `setFillStyle` methods. + * + * This call can be chained. + * @param fillColor The color the alternating grid cells will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the alternating grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. Default 1. + */ + setAltFillStyle(fillColor?: number, fillAlpha?: number): this; + + /** + * Sets the fill color and alpha level that the lines between each grid cell will use. + * + * If this method is called with no values then the grid lines will not be rendered at all, however + * the cells themselves may still be if they have colors set. + * + * Also see the `setFillStyle` and `setAltFillStyle` methods. + * + * This call can be chained. + * @param fillColor The color the lines between the grid cells will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the lines between the grid cells will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. Default 1. + */ + setOutlineStyle(fillColor?: number, fillAlpha?: number): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The IsoBox Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoBox is an 'isometric' rectangle. Each face of it has a different fill color. You can set + * the color of the top, left and right faces of the rectangle respectively. You can also choose + * which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoBox from under-neath, however you can change the 'angle' by setting + * the `projection` property. + */ + class IsoBox extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param size The width of the iso box in pixels. The left and right faces will be exactly half this value. Default 48. + * @param height The height of the iso box. The left and right faces will be this tall. The overall height of the isobox will be this value plus half the `size` value. Default 32. + * @param fillTop The fill color of the top face of the iso box. Default 0xeeeeee. + * @param fillLeft The fill color of the left face of the iso box. Default 0x999999. + * @param fillRight The fill color of the right face of the iso box. Default 0xcccccc. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, size?: number, height?: number, fillTop?: number, fillLeft?: number, fillRight?: number); + + /** + * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + */ + projection: integer; + + /** + * The color used to fill in the top of the iso box. + */ + fillTop: number; + + /** + * The color used to fill in the left-facing side of the iso box. + */ + fillLeft: number; + + /** + * The color used to fill in the right-facing side of the iso box. + */ + fillRight: number; + + /** + * Controls if the top-face of the iso box be rendered. + */ + showTop: boolean; + + /** + * Controls if the left-face of the iso box be rendered. + */ + showLeft: boolean; + + /** + * Controls if the right-face of the iso box be rendered. + */ + showRight: boolean; + + /** + * Sets the projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + * This call can be chained. + * @param value The value to set the projection to. + */ + setProjection(value: integer): this; + + /** + * Sets which faces of the iso box will be rendered. + * This call can be chained. + * @param showTop Show the top-face of the iso box. Default true. + * @param showLeft Show the left-face of the iso box. Default true. + * @param showRight Show the right-face of the iso box. Default true. + */ + setFaces(showTop?: boolean, showLeft?: boolean, showRight?: boolean): this; + + /** + * Sets the fill colors for each face of the iso box. + * This call can be chained. + * @param fillTop The color used to fill the top of the iso box. + * @param fillLeft The color used to fill in the left-facing side of the iso box. + * @param fillRight The color used to fill in the right-facing side of the iso box. + */ + setFillStyle(fillTop?: number, fillLeft?: number, fillRight?: number): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only fill colors and cannot be stroked. + * + * An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different + * fill color. You can set the color of the top, left and right faces of the triangle respectively + * You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties. + * + * You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting + * the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside + * down or not. + */ + class IsoTriangle extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param size The width of the iso triangle in pixels. The left and right faces will be exactly half this value. Default 48. + * @param height The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value. Default 32. + * @param reversed Is the iso triangle upside down? Default false. + * @param fillTop The fill color of the top face of the iso triangle. Default 0xeeeeee. + * @param fillLeft The fill color of the left face of the iso triangle. Default 0x999999. + * @param fillRight The fill color of the right face of the iso triangle. Default 0xcccccc. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, size?: number, height?: number, reversed?: boolean, fillTop?: number, fillLeft?: number, fillRight?: number); + + /** + * The projection level of the iso box. Change this to change the 'angle' at which you are looking at the box. + */ + projection: integer; + + /** + * The color used to fill in the top of the iso triangle. This is only used if the triangle is reversed. + */ + fillTop: number; + + /** + * The color used to fill in the left-facing side of the iso triangle. + */ + fillLeft: number; + + /** + * The color used to fill in the right-facing side of the iso triangle. + */ + fillRight: number; + + /** + * Controls if the top-face of the iso triangle be rendered. + */ + showTop: boolean; + + /** + * Controls if the left-face of the iso triangle be rendered. + */ + showLeft: boolean; + + /** + * Controls if the right-face of the iso triangle be rendered. + */ + showRight: boolean; + + /** + * Sets if the iso triangle will be rendered upside down or not. + */ + isReversed: boolean; + + /** + * Sets the projection level of the iso triangle. Change this to change the 'angle' at which you are looking at the pyramid. + * This call can be chained. + * @param value The value to set the projection to. + */ + setProjection(value: integer): this; + + /** + * Sets if the iso triangle will be rendered upside down or not. + * This call can be chained. + * @param reversed Sets if the iso triangle will be rendered upside down or not. + */ + setReversed(reversed: boolean): this; + + /** + * Sets which faces of the iso triangle will be rendered. + * This call can be chained. + * @param showTop Show the top-face of the iso triangle (only if `reversed` is true) Default true. + * @param showLeft Show the left-face of the iso triangle. Default true. + * @param showRight Show the right-face of the iso triangle. Default true. + */ + setFaces(showTop?: boolean, showLeft?: boolean, showRight?: boolean): this; + + /** + * Sets the fill colors for each face of the iso triangle. + * This call can be chained. + * @param fillTop The color used to fill the top of the iso triangle. + * @param fillLeft The color used to fill in the left-facing side of the iso triangle. + * @param fillRight The color used to fill in the right-facing side of the iso triangle. + */ + setFillStyle(fillTop?: number, fillLeft?: number, fillRight?: number): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Line Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports only stroke colors and cannot be filled. + * + * A Line Shape allows you to draw a line between two points in your game. You can control the + * stroke color and thickness of the line. In WebGL only you can also specify a different + * thickness for the start and end of the line, allowing you to render lines that taper-off. + * + * If you need to draw multiple lines in a sequence you may wish to use the Polygon Shape instead. + * + * Be aware that as with all Game Objects the default origin is 0.5. If you need to draw a Line + * between two points and want the x1/y1 values to match the x/y values, then set the origin to 0. + */ + class Line extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param x1 The horizontal position of the start of the line. Default 0. + * @param y1 The vertical position of the start of the line. Default 0. + * @param x2 The horizontal position of the end of the line. Default 128. + * @param y2 The vertical position of the end of the line. Default 0. + * @param strokeColor The color the line will be drawn in, i.e. 0xff0000 for red. + * @param strokeAlpha The alpha the line will be drawn in. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, strokeColor?: number, strokeAlpha?: number); + + /** + * The width (or thickness) of the line. + * See the setLineWidth method for extra details on changing this on WebGL. + */ + lineWidth: number; + + /** + * Sets the width of the line. + * + * When using the WebGL renderer you can have different start and end widths. + * When using the Canvas renderer only the `startWidth` value is used. The `endWidth` is ignored. + * + * This call can be chained. + * @param startWidth The start width of the line. + * @param endWidth The end width of the line. Only used in WebGL. + */ + setLineWidth(startWidth: number, endWidth?: number): this; + + /** + * Sets the start and end coordinates of this Line. + * @param x1 The horizontal position of the start of the line. Default 0. + * @param y1 The vertical position of the start of the line. Default 0. + * @param x2 The horizontal position of the end of the line. Default 0. + * @param y2 The vertical position of the end of the line. Default 0. + */ + setTo(x1?: number, y1?: number, x2?: number, y2?: number): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Polygon Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Polygon Shape is created by providing a list of points, which are then used to create an + * internal Polygon geometry object. The points can be set from a variety of formats: + * + * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point or Vector2 objects: `[new Phaser.Math.Vector2(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * By default the `x` and `y` coordinates of this Shape refer to the center of it. However, depending + * on the coordinates of the points provided, the final shape may be rendered offset from its origin. + */ + class Polygon extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param points The points that make up the polygon. + * @param fillColor The color the polygon will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the polygon will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, points?: any, fillColor?: number, fillAlpha?: number); + + /** + * Smooths the polygon over the number of iterations specified. + * The base polygon data will be updated and replaced with the smoothed values. + * This call can be chained. + * @param iterations The number of times to apply the polygon smoothing. Default 1. + */ + smooth(iterations?: integer): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Rectangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * You can change the size of the rectangle by changing the `width` and `height` properties. + */ + class Rectangle extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param width The width of the rectangle. Default 128. + * @param height The height of the rectangle. Default 128. + * @param fillColor The color the rectangle will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the rectangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x: number, y: number, width?: number, height?: number, fillColor?: number, fillAlpha?: number); + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Shape Game Object is a base class for the various different shapes, such as the Arc, Star or Polygon. + * You cannot add a Shape directly to your Scene, it is meant as a base for your own custom Shape classes. + */ + class Shape extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.AlphaSingle, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param type The internal type of the Shape. + * @param data The data of the source shape geometry, if any. + */ + constructor(scene: Phaser.Scene, type?: string, data?: any); + + /** + * The source Shape data. Typically a geometry object. + * You should not manipulate this directly. + */ + readonly data: any; + + /** + * Holds the polygon path data for filled rendering. + */ + readonly pathData: number[]; + + /** + * Holds the earcut polygon path index data for filled rendering. + */ + readonly pathIndexes: integer[]; + + /** + * The fill color used by this Shape. + */ + fillColor: number; + + /** + * The fill alpha value used by this Shape. + */ + fillAlpha: number; + + /** + * The stroke color used by this Shape. + */ + strokeColor: number; + + /** + * The stroke alpha value used by this Shape. + */ + strokeAlpha: number; + + /** + * The stroke line width used by this Shape. + */ + lineWidth: number; + + /** + * Controls if this Shape is filled or not. + * Note that some Shapes do not support being filled (such as Line shapes) + */ + isFilled: boolean; + + /** + * Controls if this Shape is stroked or not. + * Note that some Shapes do not support being stroked (such as Iso Box shapes) + */ + isStroked: boolean; + + /** + * Controls if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + */ + closePath: boolean; + + /** + * Sets the fill color and alpha for this Shape. + * + * If you wish for the Shape to not be filled then call this method with no arguments, or just set `isFilled` to `false`. + * + * Note that some Shapes do not support fill colors, such as the Line shape. + * + * This call can be chained. + * @param color The color used to fill this shape. If not provided the Shape will not be filled. + * @param alpha The alpha value used when filling this shape, if a fill color is given. Default 1. + */ + setFillStyle(color?: number, alpha?: number): this; + + /** + * Sets the stroke color and alpha for this Shape. + * + * If you wish for the Shape to not be stroked then call this method with no arguments, or just set `isStroked` to `false`. + * + * Note that some Shapes do not support being stroked, such as the Iso Box shape. + * + * This call can be chained. + * @param lineWidth The width of line to stroke with. If not provided or undefined the Shape will not be stroked. + * @param color The color used to stroke this shape. If not provided the Shape will not be stroked. + * @param alpha The alpha value used when stroking this shape, if a stroke color is given. Default 1. + */ + setStrokeStyle(lineWidth?: number, color?: number, alpha?: number): this; + + /** + * Sets if this Shape path is closed during rendering when stroked. + * Note that some Shapes are always closed when stroked (such as Ellipse shapes) + * + * This call can be chained. + * @param value Set to `true` if the Shape should be closed when stroked, otherwise `false`. + */ + setClosePath(value: boolean): this; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Star Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * As the name implies, the Star shape will display a star in your game. You can control several + * aspects of it including the number of points that constitute the star. The default is 5. If + * you change it to 4 it will render as a diamond. If you increase them, you'll get a more spiky + * star shape. + * + * You can also control the inner and outer radius, which is how 'long' each point of the star is. + * Modify these values to create more interesting shapes. + */ + class Star extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param points The number of points on the star. Default 5. + * @param innerRadius The inner radius of the star. Default 32. + * @param outerRadius The outer radius of the star. Default 64. + * @param fillColor The color the star will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the star will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, points?: number, innerRadius?: number, outerRadius?: number, fillColor?: number, fillAlpha?: number); + + /** + * Sets the number of points that make up the Star shape. + * This call can be chained. + * @param value The amount of points the Star will have. + */ + setPoints(value: integer): this; + + /** + * Sets the inner radius of the Star shape. + * This call can be chained. + * @param value The amount to set the inner radius to. + */ + setInnerRadius(value: number): this; + + /** + * Sets the outer radius of the Star shape. + * This call can be chained. + * @param value The amount to set the outer radius to. + */ + setOuterRadius(value: number): this; + + /** + * The number of points that make up the Star shape. + */ + points: integer; + + /** + * The inner radius of the Star shape. + */ + innerRadius: number; + + /** + * The outer radius of the Star shape. + */ + outerRadius: number; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Triangle Shape is a Game Object that can be added to a Scene, Group or Container. You can + * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling + * it for input or physics. It provides a quick and easy way for you to render this shape in your + * game without using a texture, while still taking advantage of being fully batched in WebGL. + * + * This shape supports both fill and stroke colors. + * + * The Triangle consists of 3 lines, joining up to form a triangular shape. You can control the + * position of each point of these lines. The triangle is always closed and cannot have an open + * face. If you require that, consider using a Polygon instead. + */ + class Triangle extends Phaser.GameObjects.Shape { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. Default 0. + * @param y The vertical position of this Game Object in the world. Default 0. + * @param x1 The horizontal position of the first point in the triangle. Default 0. + * @param y1 The vertical position of the first point in the triangle. Default 128. + * @param x2 The horizontal position of the second point in the triangle. Default 64. + * @param y2 The vertical position of the second point in the triangle. Default 0. + * @param x3 The horizontal position of the third point in the triangle. Default 128. + * @param y3 The vertical position of the third point in the triangle. Default 128. + * @param fillColor The color the triangle will be filled with, i.e. 0xff0000 for red. + * @param fillAlpha The alpha the triangle will be filled with. You can also set the alpha of the overall Shape using its `alpha` property. + */ + constructor(scene: Phaser.Scene, x?: number, y?: number, x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number, fillColor?: number, fillAlpha?: number); + + /** + * Sets the data for the lines that make up this Triangle shape. + * @param x1 The horizontal position of the first point in the triangle. Default 0. + * @param y1 The vertical position of the first point in the triangle. Default 0. + * @param x2 The horizontal position of the second point in the triangle. Default 0. + * @param y2 The vertical position of the second point in the triangle. Default 0. + * @param x3 The horizontal position of the third point in the triangle. Default 0. + * @param y3 The vertical position of the third point in the triangle. Default 0. + */ + setTo(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number): this; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * @param value The alpha value applied across the whole Game Object. Default 1. + */ + setAlpha(value?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + */ + class Sprite extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.TextureCrop, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); + + /** + * The Animation Controller of this Sprite. + */ + anims: Phaser.GameObjects.Components.Animation; + + /** + * Update this Sprite's animations. + * @param time The current timestamp. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + protected preUpdate(time: number, delta: number): void; + + /** + * Start playing the given animation. + * @param key The string-based key of the animation to play. + * @param ignoreIfPlaying If an animation is already playing then ignore this call. Default false. + * @param startFrame Optionally start the animation playing from this frame index. Default 0. + */ + play(key: string, ignoreIfPlaying?: boolean, startFrame?: integer): Phaser.GameObjects.Sprite; + + /** + * Build a JSON representation of this Sprite. + */ + toJSON(): Phaser.Types.GameObjects.JSONGameObject; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * 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:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes, either + * when creating the Text object, or when setting the font via `setFont` or `setFontFamily`. I.e.: + * + * ```javascript + * this.add.text(0, 0, 'Hello World', { fontFamily: '"Roboto Condensed"' }); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * this.add.text(0, 0, 'Hello World', { fontFamily: 'Verdana, "Times New Roman", Tahoma, serif' }); + * ``` + * + * You can only display fonts that are currently loaded and available to the browser: therefore fonts must + * be pre-loaded. Phaser does not do ths for you, so you will require the use of a 3rd party font loader, + * or have the fonts ready 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 implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Crop, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param text The text this Text object will display. + * @param style The text style configuration object. + */ + constructor(scene: Phaser.Scene, x: number, y: number, text: string | string[], style: Phaser.Types.GameObjects.Text.TextStyle); + + /** + * Returns an object containing dimensions of the Text object. + * @param text The Text object to calculate the size from. + * @param size The Text metrics to use when calculating the size. + * @param lines The lines of text to calculate the size from. + */ + static GetTextSize(text: Phaser.GameObjects.Text, size: Phaser.Types.GameObjects.Text.TextMetrics, lines: any[]): object; + + /** + * Calculates the ascent, descent and fontSize of a given font style. + * @param textStyle The TextStyle object to measure. + */ + static MeasureText(textStyle: Phaser.GameObjects.TextStyle): Phaser.Types.GameObjects.Text.TextMetrics; + + /** + * The renderer in use by this Text object. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * The canvas element that the text is rendered to. + */ + canvas: HTMLCanvasElement; + + /** + * The context of the canvas element that the text is rendered to. + */ + context: CanvasRenderingContext2D; + + /** + * The Text Style object. + * + * Manages the style of this Text object. + */ + style: Phaser.GameObjects.TextStyle; + + /** + * Whether to automatically round line positions. + */ + autoRound: boolean; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + */ + splitRegExp: object; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * Allows you to add extra spacing if the browser is unable to accurately determine the true font dimensions. + */ + padding: Object; + + /** + * The width of this Text object. + */ + width: number; + + /** + * The height of this Text object. + */ + height: number; + + /** + * The line spacing value. + * This value is added to the font height to calculate the overall line height. + * Only has an effect if this Text object contains multiple lines of text. + * + * If you update this property directly, instead of using the `setLineSpacing` method, then + * be sure to call `updateText` after, or you won't see the change reflected in the Text object. + */ + lineSpacing: number; + + /** + * Whether the text or its settings have changed and need updating. + */ + dirty: boolean; + + /** + * Initialize right to left text. + */ + initRTL(): void; + + /** + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. + * @param text The text to perform word wrap detection against. + */ + runWordWrap(text: string): string; + + /** + * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. Consecutive spaces will be collapsed and replaced with a single space. Lines will be + * trimmed of white space before processing. Throws an error if wordWrapWidth is less than a + * single character. + * @param text The text to perform word wrap detection against. + * @param context The Canvas Rendering Context. + * @param wordWrapWidth The word wrap width. + */ + advancedWordWrap(text: string, context: CanvasRenderingContext2D, wordWrapWidth: number): string; + + /** + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal + * bounds. Spaces are not collapsed and whitespace is not trimmed. + * @param text The text to perform word wrap detection against. + * @param context The Canvas Rendering Context. + * @param wordWrapWidth The word wrap width. + */ + basicWordWrap(text: string, context: CanvasRenderingContext2D, wordWrapWidth: number): string; + + /** + * Runs the given text through this Text objects word wrapping and returns the results as an + * array, where each element of the array corresponds to a wrapped line of text. + * @param text The text for which the wrapping will be calculated. If unspecified, the Text objects current text will be used. + */ + getWrappedText(text: string): string[]; + + /** + * Set the text to display. + * + * An array of strings will be joined with `\n` line breaks. + * @param value The string, or array of strings, to be set as the content of this Text object. + */ + setText(value: string | string[]): Phaser.GameObjects.Text; + + /** + * Set the text style. + * @param style The style settings to set. + */ + setStyle(style: object): Phaser.GameObjects.Text; + + /** + * 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:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: + * + * ```javascript + * Text.setFont('"Roboto Condensed"'); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); + * ``` + * @param font The font family or font settings to set. + */ + setFont(font: string): Phaser.GameObjects.Text; + + /** + * Set the font family. + * + * **Important:** If the font you wish to use has a space or digit in its name, such as + * 'Press Start 2P' or 'Roboto Condensed', then you _must_ put the font name in quotes: + * + * ```javascript + * Text.setFont('"Roboto Condensed"'); + * ``` + * + * Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all + * quoted properly, too: + * + * ```javascript + * Text.setFont('Verdana, "Times New Roman", Tahoma, serif'); + * ``` + * @param family The font family. + */ + setFontFamily(family: string): Phaser.GameObjects.Text; + + /** + * Set the font size. + * @param size The font size. + */ + setFontSize(size: number): Phaser.GameObjects.Text; + + /** + * Set the font style. + * @param style The font style. + */ + setFontStyle(style: string): Phaser.GameObjects.Text; + + /** + * Set a fixed width and height for the text. + * + * Pass in `0` for either of these parameters to disable fixed width or height respectively. + * @param width The fixed width to set. `0` disables fixed width. + * @param height The fixed height to set. `0` disables fixed height. + */ + setFixedSize(width: number, height: number): Phaser.GameObjects.Text; + + /** + * Set the background color. + * @param color The background color. + */ + setBackgroundColor(color: string): Phaser.GameObjects.Text; + + /** + * 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. + * @param color The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value. + */ + setFill(color: string | any): Phaser.GameObjects.Text; + + /** + * Set the text fill color. + * @param color The text fill color. + */ + setColor(color: string): Phaser.GameObjects.Text; + + /** + * Set the stroke settings. + * @param color The stroke color. + * @param thickness The stroke thickness. + */ + setStroke(color: string, thickness: number): Phaser.GameObjects.Text; + + /** + * Set the shadow settings. + * @param x The horizontal shadow offset. Default 0. + * @param y The vertical shadow offset. Default 0. + * @param color The shadow color. Default '#000'. + * @param blur The shadow blur radius. Default 0. + * @param shadowStroke Whether to stroke the shadow. Default false. + * @param shadowFill Whether to fill the shadow. Default true. + */ + setShadow(x?: number, y?: number, color?: string, blur?: number, shadowStroke?: boolean, shadowFill?: boolean): Phaser.GameObjects.Text; + + /** + * Set the shadow offset. + * @param x The horizontal shadow offset. + * @param y The vertical shadow offset. + */ + setShadowOffset(x: number, y: number): Phaser.GameObjects.Text; + + /** + * Set the shadow color. + * @param color The shadow color. + */ + setShadowColor(color: string): Phaser.GameObjects.Text; + + /** + * Set the shadow blur radius. + * @param blur The shadow blur radius. + */ + setShadowBlur(blur: number): Phaser.GameObjects.Text; + + /** + * Enable or disable shadow stroke. + * @param enabled Whether shadow stroke is enabled or not. + */ + setShadowStroke(enabled: boolean): Phaser.GameObjects.Text; + + /** + * Enable or disable shadow fill. + * @param enabled Whether shadow fill is enabled or not. + */ + setShadowFill(enabled: boolean): Phaser.GameObjects.Text; + + /** + * Set the width (in pixels) to use for wrapping lines. Pass in null to remove wrapping by width. + * @param width The maximum width of a line in pixels. Set to null to remove wrapping. + * @param useAdvancedWrap Whether or not to use the advanced wrapping + * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, + * spaces and whitespace are left as is. Default false. + */ + setWordWrapWidth(width: number, useAdvancedWrap?: boolean): Phaser.GameObjects.Text; + + /** + * Set a custom callback for wrapping lines. Pass in null to remove wrapping by callback. + * @param callback A custom function that will be responsible for wrapping the + * text. It will receive two arguments: text (the string to wrap), textObject (this Text + * instance). It should return the wrapped lines either as an array of lines or as a string with + * newline characters in place to indicate where breaks should happen. + * @param scope The scope that will be applied when the callback is invoked. Default null. + */ + setWordWrapCallback(callback: TextStyleWordWrapCallback, scope?: object): Phaser.GameObjects.Text; + + /** + * Set the alignment of the text in this Text object. + * + * The argument can be one of: `left`, `right`, `center` or `justify`. + * + * Alignment only works if the Text object has more than one line of text. + * @param align The text alignment for multi-line text. Default 'left'. + */ + setAlign(align?: string): Phaser.GameObjects.Text; + + /** + * Set the resolution used by this Text object. + * + * By default it will be set to match the resolution set in the Game Config, + * but you can override it via this method, or by specifying it in the Text style configuration object. + * + * It allows for much clearer text on High DPI devices, at the cost of memory because it uses larger + * internal Canvas textures for the Text. + * + * Therefore, please use with caution, as the more high res Text you have, the more memory it uses. + * @param value The resolution for this Text object to use. + */ + setResolution(value: number): Phaser.GameObjects.Text; + + /** + * Sets the line spacing value. + * + * This value is _added_ to the height of the font when calculating the overall line height. + * This only has an effect if this Text object consists of multiple lines of text. + * @param value The amount to add to the font height to achieve the overall line height. + */ + setLineSpacing(value: number): Phaser.GameObjects.Text; + + /** + * Set the text padding. + * + * 'left' can be an object. + * + * If only 'left' and 'top' are given they are treated as 'x' and 'y'. + * @param left The left padding value, or a padding config object. + * @param top The top padding value. + * @param right The right padding value. + * @param bottom The bottom padding value. + */ + setPadding(left: number | Phaser.Types.GameObjects.Text.TextPadding, top: number, right: number, bottom: number): Phaser.GameObjects.Text; + + /** + * Set the maximum number of lines to draw. + * @param max The maximum number of lines to draw. Default 0. + */ + setMaxLines(max?: integer): Phaser.GameObjects.Text; + + /** + * Update the displayed text. + */ + updateText(): Phaser.GameObjects.Text; + + /** + * Get the current text metrics. + */ + getTextMetrics(): object; + + /** + * The text string being rendered by this Text Game Object. + */ + text: string; + + /** + * Build a JSON representation of the Text object. + */ + toJSON(): Phaser.Types.GameObjects.JSONGameObject; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A TextStyle class manages all of the style settings for a Text object. + * + * Text Game Objects create a TextStyle instance automatically, which is + * accessed via the `Text.style` property. You do not normally need to + * instantiate one yourself. + */ + class TextStyle { + /** + * + * @param text The Text object that this TextStyle is styling. + * @param style The style settings to set. + */ + constructor(text: Phaser.GameObjects.Text, style: Phaser.Types.GameObjects.Text.TextStyle); + + /** + * The Text object that this TextStyle is styling. + */ + parent: Phaser.GameObjects.Text; + + /** + * The font family. + */ + fontFamily: string; + + /** + * The font size. + */ + fontSize: string; + + /** + * The font style. + */ + fontStyle: string; + + /** + * The background color. + */ + backgroundColor: string; + + /** + * The text fill color. + */ + color: string; + + /** + * The text stroke color. + */ + stroke: string; + + /** + * The text stroke thickness. + */ + strokeThickness: number; + + /** + * The horizontal shadow offset. + */ + shadowOffsetX: number; + + /** + * The vertical shadow offset. + */ + shadowOffsetY: number; + + /** + * The shadow color. + */ + shadowColor: string; + + /** + * The shadow blur radius. + */ + shadowBlur: number; + + /** + * Whether shadow stroke is enabled or not. + */ + shadowStroke: boolean; + + /** + * Whether shadow fill is enabled or not. + */ + shadowFill: boolean; + + /** + * The text alignment. + */ + align: string; + + /** + * The maximum number of lines to draw. + */ + maxLines: integer; + + /** + * The fixed width of the text. + * + * `0` means no fixed with. + */ + fixedWidth: number; + + /** + * The fixed height of the text. + * + * `0` means no fixed height. + */ + fixedHeight: number; + + /** + * The resolution the text is rendered to its internal canvas at. + * The default is 0, which means it will use the resolution set in the Game Config. + */ + resolution: number; + + /** + * Whether the text should render right to left. + */ + rtl: boolean; + + /** + * The test string to use when measuring the font. + */ + testString: string; + + /** + * The amount of horizontal padding added to the width of the text when calculating the font metrics. + */ + baselineX: number; + + /** + * The amount of vertical padding added to the height of the text when calculating the font metrics. + */ + baselineY: number; + + /** + * Set the text style. + * @param style The style settings to set. + * @param updateText Whether to update the text immediately. Default true. + * @param setDefaults Use the default values is not set, or the local values. Default false. + */ + setStyle(style: Phaser.Types.GameObjects.Text.TextStyle, updateText?: boolean, setDefaults?: boolean): Phaser.GameObjects.Text; + + /** + * Synchronize the font settings to the given Canvas Rendering Context. + * @param canvas The Canvas Element. + * @param context The Canvas Rendering Context. + */ + syncFont(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): void; + + /** + * Synchronize the text style settings to the given Canvas Rendering Context. + * @param canvas The Canvas Element. + * @param context The Canvas Rendering Context. + */ + syncStyle(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): void; + + /** + * Synchronize the shadow settings to the given Canvas Rendering Context. + * @param context The Canvas Rendering Context. + * @param enabled Whether shadows are enabled or not. + */ + syncShadow(context: CanvasRenderingContext2D, enabled: boolean): void; + + /** + * Update the style settings for the parent Text object. + * @param recalculateMetrics Whether to recalculate font and text metrics. + */ + update(recalculateMetrics: boolean): Phaser.GameObjects.Text; + + /** + * 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. + * @param font The font family or font settings to set. + * @param updateText Whether to update the text immediately. Default true. + */ + setFont(font: string | object, updateText?: boolean): Phaser.GameObjects.Text; + + /** + * Set the font family. + * @param family The font family. + */ + setFontFamily(family: string): Phaser.GameObjects.Text; + + /** + * Set the font style. + * @param style The font style. + */ + setFontStyle(style: string): Phaser.GameObjects.Text; + + /** + * Set the font size. + * @param size The font size. + */ + setFontSize(size: number | string): Phaser.GameObjects.Text; + + /** + * Set the test string to use when measuring the font. + * @param string The test string to use when measuring the font. + */ + setTestString(string: string): Phaser.GameObjects.Text; + + /** + * Set a fixed width and height for the text. + * + * Pass in `0` for either of these parameters to disable fixed width or height respectively. + * @param width The fixed width to set. + * @param height The fixed height to set. + */ + setFixedSize(width: number, height: number): Phaser.GameObjects.Text; + + /** + * Set the background color. + * @param color The background color. + */ + setBackgroundColor(color: string): Phaser.GameObjects.Text; + + /** + * Set the text fill color. + * @param color The text fill color. + */ + setFill(color: string): Phaser.GameObjects.Text; + + /** + * Set the text fill color. + * @param color The text fill color. + */ + setColor(color: string): Phaser.GameObjects.Text; + + /** + * Set the resolution used by the Text object. + * + * By default it will be set to match the resolution set in the Game Config, + * but you can override it via this method. It allows for much clearer text on High DPI devices, + * at the cost of memory because it uses larger internal Canvas textures for the Text. + * + * Please use with caution, as the more high res Text you have, the more memory it uses up. + * @param value The resolution for this Text object to use. + */ + setResolution(value: number): Phaser.GameObjects.Text; + + /** + * Set the stroke settings. + * @param color The stroke color. + * @param thickness The stroke thickness. + */ + setStroke(color: string, thickness: number): Phaser.GameObjects.Text; + + /** + * Set the shadow settings. + * + * Calling this method always re-measures the parent Text object, + * so only call it when you actually change the shadow settings. + * @param x The horizontal shadow offset. Default 0. + * @param y The vertical shadow offset. Default 0. + * @param color The shadow color. Default '#000'. + * @param blur The shadow blur radius. Default 0. + * @param shadowStroke Whether to stroke the shadow. Default false. + * @param shadowFill Whether to fill the shadow. Default true. + */ + setShadow(x?: number, y?: number, color?: string, blur?: number, shadowStroke?: boolean, shadowFill?: boolean): Phaser.GameObjects.Text; + + /** + * Set the shadow offset. + * @param x The horizontal shadow offset. Default 0. + * @param y The vertical shadow offset. Default 0. + */ + setShadowOffset(x?: number, y?: number): Phaser.GameObjects.Text; + + /** + * Set the shadow color. + * @param color The shadow color. Default '#000'. + */ + setShadowColor(color?: string): Phaser.GameObjects.Text; + + /** + * Set the shadow blur radius. + * @param blur The shadow blur radius. Default 0. + */ + setShadowBlur(blur?: number): Phaser.GameObjects.Text; + + /** + * Enable or disable shadow stroke. + * @param enabled Whether shadow stroke is enabled or not. + */ + setShadowStroke(enabled: boolean): Phaser.GameObjects.Text; + + /** + * Enable or disable shadow fill. + * @param enabled Whether shadow fill is enabled or not. + */ + setShadowFill(enabled: boolean): Phaser.GameObjects.Text; + + /** + * Set the width (in pixels) to use for wrapping lines. + * + * Pass in null to remove wrapping by width. + * @param width The maximum width of a line in pixels. Set to null to remove wrapping. + * @param useAdvancedWrap Whether or not to use the advanced wrapping + * algorithm. If true, spaces are collapsed and whitespace is trimmed from lines. If false, + * spaces and whitespace are left as is. Default false. + */ + setWordWrapWidth(width: number, useAdvancedWrap?: boolean): Phaser.GameObjects.Text; + + /** + * Set a custom callback for wrapping lines. + * + * Pass in null to remove wrapping by callback. + * @param callback A custom function that will be responsible for wrapping the + * text. It will receive two arguments: text (the string to wrap), textObject (this Text + * instance). It should return the wrapped lines either as an array of lines or as a string with + * newline characters in place to indicate where breaks should happen. + * @param scope The scope that will be applied when the callback is invoked. Default null. + */ + setWordWrapCallback(callback: TextStyleWordWrapCallback, scope?: object): Phaser.GameObjects.Text; + + /** + * Set the alignment of the text in this Text object. + * + * The argument can be one of: `left`, `right`, `center` or `justify`. + * + * Alignment only works if the Text object has more than one line of text. + * @param align The text alignment for multi-line text. Default 'left'. + */ + setAlign(align?: string): Phaser.GameObjects.Text; + + /** + * Set the maximum number of lines to draw. + * @param max The maximum number of lines to draw. Default 0. + */ + setMaxLines(max?: integer): Phaser.GameObjects.Text; + + /** + * Get the current text metrics. + */ + getTextMetrics(): Phaser.Types.GameObjects.Text.TextMetrics; + + /** + * Build a JSON representation of this Text Style. + */ + toJSON(): object; + + /** + * Destroy this Text Style. + */ + destroy(): void; + + } + + /** + * A TileSprite is a Sprite that has a repeating texture. + * + * The texture can be scrolled and scaled independently of the TileSprite itself. Textures will automatically wrap and + * are designed so that you can create game backdrops using seamless textures as a source. + * + * You shouldn't ever create a TileSprite any larger than your actual canvas size. If you want to create a large repeating background + * that scrolls across the whole map of your game, then you create a TileSprite that fits the canvas size and then use the `tilePosition` + * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will + * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to + * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. + * + * An important note about Tile Sprites and NPOT textures: Internally, TileSprite textures use GL_REPEAT to provide + * seamless repeating of the textures. This, combined with the way in which the textures are handled in WebGL, means + * they need to be POT (power-of-two) sizes in order to wrap. If you provide a NPOT (non power-of-two) texture to a + * TileSprite it will generate a POT sized canvas and draw your texture to it, scaled up to the POT size. It's then + * scaled back down again during rendering to the original dimensions. While this works, in that it allows you to use + * any size texture for a Tile Sprite, it does mean that NPOT textures are going to appear anti-aliased when rendered, + * due to the interpolation that took place when it was resized into a POT texture. This is especially visible in + * pixel art graphics. If you notice it and it becomes an issue, the only way to avoid it is to ensure that you + * provide POT textures for Tile Sprites. + */ + class TileSprite extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Crop, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param width The width of the Game Object. If zero it will use the size of the texture frame. + * @param height The height of the Game Object. If zero it will use the size of the texture frame. + * @param textureKey The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frameKey An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, width: integer, height: integer, textureKey: string, frameKey?: string | integer); + + /** + * Whether the Tile Sprite has changed in some way, requiring an re-render of its tile texture. + * + * Such changes include the texture frame and scroll position of the Tile Sprite. + */ + dirty: boolean; + + /** + * The renderer in use by this Tile Sprite. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * The Canvas element that the TileSprite renders its fill pattern in to. + * Only used in Canvas mode. + */ + canvas: HTMLCanvasElement; + + /** + * The Context of the Canvas element that the TileSprite renders its fill pattern in to. + * Only used in Canvas mode. + */ + context: CanvasRenderingContext2D; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * The next power of two value from the width of the Fill Pattern frame. + */ + potWidth: integer; + + /** + * The next power of two value from the height of the Fill Pattern frame. + */ + potHeight: integer; + + /** + * The Canvas that the TileSprites texture is rendered to. + * This is used to create a WebGL texture from. + */ + fillCanvas: HTMLCanvasElement; + + /** + * The Canvas Context used to render the TileSprites texture. + */ + fillContext: CanvasRenderingContext2D; + + /** + * The texture that the Tile Sprite is rendered to, which is then rendered to a Scene. + * In WebGL this is a WebGLTexture. In Canvas it's a Canvas Fill Pattern. + */ + fillPattern: WebGLTexture | CanvasPattern; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * @param frame The name or index of the frame within the Texture. + */ + setFrame(frame: string | integer): this; + + /** + * Sets {@link Phaser.GameObjects.TileSprite#tilePositionX} and {@link Phaser.GameObjects.TileSprite#tilePositionY}. + * @param x The x position of this sprite's tiling texture. + * @param y The y position of this sprite's tiling texture. + */ + setTilePosition(x?: number, y?: number): this; + + /** + * Sets {@link Phaser.GameObjects.TileSprite#tileScaleX} and {@link Phaser.GameObjects.TileSprite#tileScaleY}. + * @param x The horizontal scale of the tiling texture. If not given it will use the current `tileScaleX` value. + * @param y The vertical scale of the tiling texture. If not given it will use the `x` value. Default x. + */ + setTileScale(x?: number, y?: number): this; + + /** + * Internal destroy handler, called as part of the destroy process. + */ + protected preDestroy(): void; + + /** + * The horizontal scroll position of the Tile Sprite. + */ + tilePositionX: number; + + /** + * The vertical scroll position of the Tile Sprite. + */ + tilePositionY: number; + + /** + * The horizontal scale of the Tile Sprite texture. + */ + tileScaleX: number; + + /** + * The vertical scale of the Tile Sprite texture. + */ + tileScaleY: number; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * The Update List plugin. + * + * Update Lists belong to a Scene and maintain the list Game Objects to be updated every frame. + * + * Some or all of these Game Objects may also be part of the Scene's [Display List]{@link Phaser.GameObjects.DisplayList}, for Rendering. + */ + class UpdateList extends Phaser.Structs.ProcessQueue { + /** + * + * @param scene The Scene that the Update List belongs to. + */ + constructor(scene: Phaser.Scene); + + /** + * The Scene that the Update List belongs to. + */ + scene: Phaser.Scene; + + /** + * The Scene's Systems. + */ + systems: Phaser.Scenes.Systems; + + /** + * The update step. + * + * Pre-updates every active Game Object in the list. + * @param time The current timestamp. + * @param delta The delta time elapsed since the last frame. + */ + sceneUpdate(time: number, delta: number): void; + + /** + * The Scene that owns this plugin is shutting down. + * + * We need to kill and reset all internal properties as well as stop listening to Scene events. + */ + shutdown(): void; + + /** + * The Scene that owns this plugin is being destroyed. + * + * We need to shutdown and then kill off all external references. + */ + destroy(): void; + + } + + /** + * A Video Game Object. + * + * This Game Object is capable of handling playback of a previously loaded video from the Phaser Video Cache, + * or playing a video based on a given URL. Videos can be either local, or streamed. + * + * ```javascript + * preload () { + * this.load.video('pixar', 'nemo.mp4'); + * } + * + * create () { + * this.add.video(400, 300, 'pixar'); + * } + * ``` + * + * 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. + * + * ### 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, ahd 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', 'loadeddata', false, true); + * } + * ``` + * + * The 5th 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. + * + * Note that due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. + * + * 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 implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Mask, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.TextureCrop, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param key Optional key of the Video this Game Object will play, as stored in the Video Cache. + */ + constructor(scene: Phaser.Scene, x: number, y: number, key?: string); + + /** + * A reference to the HTML Video Element this Video Game Object is playing. + * Will be `null` until a video is loaded for playback. + */ + video: HTMLVideoElement; + + /** + * The Phaser Texture this Game Object is using to render the video to. + * Will be `null` until a video is loaded for playback. + */ + videoTexture: Phaser.Textures.Texture; + + /** + * A reference to the TextureSource belong to the `videoTexture` Texture object. + * Will be `null` until a video is loaded for playback. + */ + videoTextureSource: Phaser.Textures.TextureSource; + + /** + * A Phaser CanvasTexture instance that holds the most recent snapshot taken from the video. + * This will only be set if `snapshot` or `snapshotArea` have been called, and will be `null` until that point. + */ + snapshotTexture: Phaser.Textures.CanvasTexture; + + /** + * If you have saved this video to a texture via the `saveTexture` method, this controls if the video + * is rendered with `flipY` in WebGL or not. You often need to set this if you wish to use the video texture + * as the input source for a shader. If you find your video is appearing upside down within a shader or + * custom pipeline, flip this property. + */ + flipY: boolean; + + /** + * An internal flag holding the current state of the video lock, should document interaction be required + * before playback can begin. + */ + touchLocked: boolean; + + /** + * Should the video auto play when document interaction is required and happens? + */ + playWhenUnlocked: boolean; + + /** + * When starting playback of a video Phaser will monitor its `readyState` using a `setTimeout` call. + * The `setTimeout` happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + */ + retryLimit: integer; + + /** + * The current retry attempt. + */ + retry: integer; + + /** + * The number of ms between each retry while monitoring the ready state of a downloading video. + */ + retryInterval: integer; + + /** + * An object containing in and out markers for sequence playback. + */ + markers: any; + + /** + * Should the Video element that this Video is using, be removed from the DOM + * when this Video is destroyed? + */ + removeVideoElementOnDestroy: boolean; + + /** + * 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', 'loadeddata', false, true); + * } + * ``` + * + * The 5th 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. + * @param loop Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats. Default false. + * @param markerIn Optional in marker time, in seconds, for playback of a sequence of the video. + * @param markerOut Optional out marker time, in seconds, for playback of a sequence of the video. + */ + play(loop?: boolean, markerIn?: integer, markerOut?: integer): this; + + /** + * This method allows you to change the source of the current video element. It works by first stopping the + * current video, if playing. Then deleting the video texture, if one has been created. Finally, it makes a + * new video texture and starts playback of the new source through the existing video element. + * + * The reason you may wish to do this is because videos that require interaction to unlock, remain in an unlocked + * state, even if you change the source of the video. By changing the source to a new video you avoid having to + * go through the unlock process again. + * @param key The key of the Video this Game Object will swap to playing, as stored in the Video Cache. + * @param autoplay Should the video start playing immediately, once the swap is complete? Default true. + * @param loop Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats. Default false. + * @param markerIn Optional in marker time, in seconds, for playback of a sequence of the video. + * @param markerOut Optional out marker time, in seconds, for playback of a sequence of the video. + */ + changeSource(key: string, autoplay?: boolean, loop?: boolean, markerIn?: integer, markerOut?: integer): this; + + /** + * 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. + * @param key A unique name to give this marker. + * @param markerIn The time, in seconds, representing the start of this marker. + * @param markerOut The time, in seconds, representing the end of this marker. + */ + addMarker(key: string, markerIn: integer, markerOut: integer): this; + + /** + * 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. + * @param key The name of the marker sequence to play. + * @param loop Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats. Default false. + */ + playMarker(key: string, loop?: boolean): this; + + /** + * Removes a previously set marker from this video. + * + * If the marker is currently playing it will _not_ stop playback. + * @param key The name of the marker to remove. + */ + removeMarker(key: string): this; + + /** + * Takes a snapshot of the current frame of the video and renders it to a CanvasTexture object, + * which is then returned. You can optionally resize the grab by passing a width and height. + * + * This method returns a reference to the `Video.snapshotTexture` object. Calling this method + * multiple times will overwrite the previous snapshot with the most recent one. + * @param width The width of the resulting CanvasTexture. + * @param height The height of the resulting CanvasTexture. + */ + snapshot(width?: integer, height?: integer): Phaser.Textures.CanvasTexture; + + /** + * Takes a snapshot of the specified area of the current frame of the video and renders it to a CanvasTexture object, + * which is then returned. You can optionally resize the grab by passing a different `destWidth` and `destHeight`. + * + * This method returns a reference to the `Video.snapshotTexture` object. Calling this method + * multiple times will overwrite the previous snapshot with the most recent one. + * @param x The horizontal location of the top-left of the area to grab from. Default 0. + * @param y The vertical location of the top-left of the area to grab from. Default 0. + * @param srcWidth The width of area to grab from the video. If not given it will grab the full video dimensions. + * @param srcHeight The height of area to grab from the video. If not given it will grab the full video dimensions. + * @param destWidth The destination width of the grab, allowing you to resize it. + * @param destHeight The destination height of the grab, allowing you to resize it. + */ + snapshotArea(x?: integer, y?: integer, srcWidth?: integer, srcHeight?: integer, destWidth?: integer, destHeight?: integer): Phaser.Textures.CanvasTexture; + + /** + * Stores a copy of this Videos `snapshotTexture` in the Texture Manager using the given key. + * + * This texture is created when the `snapshot` or `snapshotArea` methods are called. + * + * After doing this, any texture based Game Object, such as a Sprite, can use the contents of the + * snapshot by using the texture key: + * + * ```javascript + * var vid = this.add.video(0, 0, 'intro'); + * + * vid.snapshot(); + * + * vid.saveSnapshotTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * Updating the contents of the `snapshotTexture`, for example by calling `snapshot` again, + * will automatically update _any_ Game Object that is using it as a texture. + * Calling `saveSnapshotTexture` again will not save another copy of the same texture, + * it will just rename the existing one. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame. + * @param key The unique key to store the texture as within the global Texture Manager. + */ + saveSnapshotTexture(key: string): Phaser.Textures.CanvasTexture; + + /** + * Loads a Video from the given URL, ready for playback with the `Video.play` method. + * + * You can control at what point the browser determines the video as being ready for playback via + * the `loadEvent` parameter. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement + * for more details. + * @param url The URL of the video to load or be streamed. + * @param loadEvent The load event to listen for. Either `loadeddata`, `canplay` or `canplaythrough`. Default 'loadeddata'. + * @param noAudio Does the video have an audio track? If not you can enable auto-playing on it. Default false. + */ + loadURL(url: string, loadEvent?: string, noAudio?: boolean): this; + + /** + * Called when the video emits a `playing` event during load. + * + * This is only listened for if the browser doesn't support Promises. + */ + playHandler(): void; + + /** + * Called when the video completes playback, i.e. reaches an `ended` state. + * + * This will never happen if the video is coming from a live stream, where the duration is `Infinity`. + */ + completeHandler(): void; + + /** + * Called when the video emits a `timeUpdate` event during playback. + * + * This event is too slow and irregular to be used for actual video timing or texture updating, + * but we can use it to determine if a video has looped. + */ + timeUpdateHandler(): void; + + /** + * Internal method that is called when enough video data has been received in order to create a texture + * from it. The texture is assigned to the `Video.videoTexture` property and given a base frame that + * encompases the whole video size. + */ + updateTexture(): void; + + /** + * Returns the key of the currently played video, as stored in the Video Cache. + * If the video did not come from the cache this will return an empty string. + */ + getVideoKey(): string; + + /** + * 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. + * @param value The point in the video to seek to. A value between 0 and 1. + */ + seekTo(value: number): this; + + /** + * A double-precision floating-point value indicating the current playback time in seconds. + * If the media has not started to play and has not been seeked, this value is the media's initial playback time. + */ + getCurrentTime(): number; + + /** + * 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. + * @param 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. + */ + setCurrentTime(value: string | number): this; + + /** + * Returns a boolean indicating if this Video is currently seeking, or not. + */ + isSeeking(): boolean; + + /** + * Returns the current progress of the video. Progress is defined as a value between 0 (the start) + * and 1 (the end). + * + * Progress can only be returned if the video has a duration, otherwise it will always return zero. + */ + getProgress(): number; + + /** + * A double-precision floating-point value which indicates the duration (total length) of the media in seconds, + * on the media's timeline. If no media is present on the element, or the media is not valid, the returned value is NaN. + * + * If the media has no known end (such as for live streams of unknown duration, web radio, media incoming from WebRTC, + * and so forth), this value is +Infinity. + */ + getDuration(): number; + + /** + * Sets the muted state of the currently playing video, if one is loaded. + * @param value The mute value. `true` if the video should be muted, otherwise `false`. Default true. + */ + setMute(value?: boolean): this; + + /** + * Returns a boolean indicating if this Video is currently muted. + */ + isMuted(): boolean; + + /** + * Sets the paused state of the currently loaded video. + * + * If the video is playing, calling this method with `true` will pause playback. + * If the video is paused, calling this method with `false` will resume playback. + * + * If no video is loaded, this method does nothing. + * @param value The paused value. `true` if the video should be paused, `false` to resume it. Default true. + */ + setPaused(value?: boolean): this; + + /** + * Returns a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + */ + getVolume(): number; + + /** + * Sets the volume of the currently playing video. + * + * The value given is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). + * @param value A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). Default 1. + */ + setVolume(value?: number): this; + + /** + * Returns a double that indicates the rate at which the media is being played back. + */ + getPlaybackRate(): number; + + /** + * Sets the playback rate of the current video. + * + * The value given is a double that indicates the rate at which the media is being played back. + * @param rate A double that indicates the rate at which the media is being played back. + */ + setPlaybackRate(rate?: number): this; + + /** + * Returns a boolean which indicates whether the media element should start over when it reaches the end. + */ + getLoop(): boolean; + + /** + * Sets the loop state of the current video. + * + * The value given is a boolean which indicates whether the media element will start over when it reaches the end. + * + * Not all videos can loop, for example live streams. + * + * Please note that not all browsers support _seamless_ video looping for all encoding formats. + * @param value A boolean which indicates whether the media element will start over when it reaches the end. Default true. + */ + setLoop(value?: boolean): this; + + /** + * Returns a boolean which indicates whether the video is currently playing. + */ + isPlaying(): boolean; + + /** + * Returns a boolean which indicates whether the video is currently paused. + */ + isPaused(): boolean; + + /** + * Stores this Video in the Texture Manager using the given key as a dynamic texture, + * which any texture-based Game Object, such as a Sprite, can use as its texture: + * + * ```javascript + * var vid = this.add.video(0, 0, 'intro'); + * + * vid.play(); + * + * vid.saveTexture('doodle'); + * + * this.add.image(400, 300, 'doodle'); + * ``` + * + * The saved texture is automatically updated as the video plays. If you pause this video, + * or change its source, then the saved texture updates instantly. + * + * Calling `saveTexture` again will not save another copy of the same texture, it will just rename the existing one. + * + * By default it will create a single base texture. You can add frames to the texture + * by using the `Texture.add` method. After doing this, you can then allow Game Objects + * to use a specific frame. + * + * If you intend to save the texture so you can use it as the input for a Shader, you may need to set the + * `flipY` parameter to `true` if you find the video renders upside down in your shader. + * @param key The unique key to store the texture as within the global Texture Manager. + * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y` during upload? Default false. + */ + saveTexture(key: string, flipY?: boolean): Phaser.Textures.Texture; + + /** + * Stops the video playing and clears all internal event listeners. + * + * If you only wish to pause playback of the video, and resume it a later time, use the `Video.pause` method instead. + * + * If the video hasn't finished downloading, calling this method will not abort the download. To do that you need to + * call `destroy` instead. + */ + stop(): this; + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * + * Also removes the autoplay and src attributes and nulls the Video reference. + * + * You should not call this method if you were playing a video from the Video Cache that + * you wish to play again in your game, or if another Video object is also using the same + * video. + * + * If you loaded an external video via `Video.loadURL` then you should call this function + * to clear up once you are done with the instance. + */ + removeVideoElement(): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * A Zone Game Object. + * + * A Zone is a non-rendering rectangular Game Object that has a position and size. + * It has no texture and never displays, but does live on the display list and + * can be moved, scaled and rotated like any other Game Object. + * + * Its primary use is for creating Drop Zones and Input Hit Areas and it has a couple of helper methods + * specifically for this. It is also useful for object overlap checks, or as a base for your own + * non-displaying Game Objects. + * The default origin is 0.5, the center of the Zone, the same as with Game Objects. + */ + class Zone extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param width The width of the Game Object. Default 1. + * @param height The height of the Game Object. Default 1. + */ + constructor(scene: Phaser.Scene, x: number, y: number, width?: number, height?: number); + + /** + * The native (un-scaled) width of this Game Object. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + */ + height: number; + + /** + * The Blend Mode of the Game Object. + * Although a Zone never renders, it still has a blend mode to allow it to fit seamlessly into + * display lists without causing a batch flush. + */ + blendMode: integer; + + /** + * The displayed width of this Game Object. + * This value takes into account the scale factor. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * This value takes into account the scale factor. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + * @param resizeInput If this Zone has a Rectangle for a hit area this argument will resize the hit area as well. Default true. + */ + setSize(width: number, height: number, resizeInput?: boolean): Phaser.GameObjects.Zone; + + /** + * Sets the display size of this Game Object. + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): Phaser.GameObjects.Zone; + + /** + * Sets this Zone to be a Circular Drop Zone. + * The circle is centered on this Zones `x` and `y` coordinates. + * @param radius The radius of the Circle that will form the Drop Zone. + */ + setCircleDropZone(radius: number): Phaser.GameObjects.Zone; + + /** + * Sets this Zone to be a Rectangle Drop Zone. + * The rectangle is centered on this Zones `x` and `y` coordinates. + * @param width The width of the rectangle drop zone. + * @param height The height of the rectangle drop zone. + */ + setRectangleDropZone(width: number, height: number): Phaser.GameObjects.Zone; + + /** + * Allows you to define your own Geometry shape to be used as a Drop Zone. + * @param shape A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. + * @param callback A function that will return `true` if the given x/y coords it is sent are within the shape. + */ + setDropZone(shape: object, callback: Phaser.Types.Input.HitAreaCallback): Phaser.GameObjects.Zone; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + } + + namespace Geom { + /** + * A Circle object. + * + * This is a geometry object, containing numerical values and related methods to inspect and modify them. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render a Circle you should look at the capabilities of the Graphics class. + */ + class Circle { + /** + * + * @param x The x position of the center of the circle. Default 0. + * @param y The y position of the center of the circle. Default 0. + * @param radius The radius of the circle. Default 0. + */ + constructor(x?: number, y?: number, radius?: number); + + /** + * Calculates the area of the circle. + * @param circle The Circle to get the area of. + */ + static Area(circle: Phaser.Geom.Circle): number; + + /** + * The geometry constant type of this object: `GEOM_CONST.CIRCLE`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * The x position of the center of the circle. + */ + x: number; + + /** + * The y position of the center of the circle. + */ + y: number; + + /** + * Check to see if the Circle contains the given x / y coordinates. + * @param x The x coordinate to check within the circle. + * @param y The y coordinate to check within the circle. + */ + contains(x: number, y: number): boolean; + + /** + * 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. + * @param 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 out An object to store the return values in. If not given a Point object will be created. + */ + getPoint(position: number, out?: O): O; + + /** + * 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. + * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. + * @param stepRate Sets the quantity by getting the circumference of the circle and dividing it by the stepRate. + * @param output An array to insert the points in to. If not provided a new array will be created. + */ + getPoints(quantity: integer, stepRate?: number, output?: O): O; + + /** + * Returns a uniformly distributed random point from anywhere within the Circle. + * @param point A Point or point-like object to set the random `x` and `y` values in. + */ + getRandomPoint(point?: O): O; + + /** + * Sets the x, y and radius of this circle. + * @param x The x position of the center of the circle. Default 0. + * @param y The y position of the center of the circle. Default 0. + * @param radius The radius of the circle. Default 0. + */ + setTo(x?: number, y?: number, radius?: number): Phaser.Geom.Circle; + + /** + * Sets this Circle to be empty with a radius of zero. + * Does not change its position. + */ + setEmpty(): Phaser.Geom.Circle; + + /** + * Sets the position of this Circle. + * @param x The x position of the center of the circle. Default 0. + * @param y The y position of the center of the circle. Default 0. + */ + setPosition(x?: number, y?: number): Phaser.Geom.Circle; + + /** + * Checks to see if the Circle is empty: has a radius of zero. + */ + isEmpty(): boolean; + + /** + * The radius of the Circle. + */ + radius: number; + + /** + * The diameter of the Circle. + */ + diameter: number; + + /** + * The left position of the Circle. + */ + left: number; + + /** + * The right position of the Circle. + */ + right: number; + + /** + * The top position of the Circle. + */ + top: number; + + /** + * The bottom position of the Circle. + */ + bottom: number; + + /** + * Returns the circumference of the given Circle. + * @param circle The Circle to get the circumference of. + */ + static Circumference(circle: Phaser.Geom.Circle): number; + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @param circle The Circle to get the circumference point on. + * @param angle The angle from the center of the Circle to the circumference to return the point from. Given in radians. + * @param out A Point, or point-like object, to store the results in. If not given a Point will be created. + */ + static CircumferencePoint(circle: Phaser.Geom.Circle, angle: number, out?: O): O; + + /** + * Creates a new Circle instance based on the values contained in the given source. + * @param source The Circle to be cloned. Can be an instance of a Circle or a circle-like object, with x, y and radius properties. + */ + static Clone(source: Phaser.Geom.Circle | object): Phaser.Geom.Circle; + + /** + * Check to see if the Circle contains the given x / y coordinates. + * @param circle The Circle to check. + * @param x The x coordinate to check within the circle. + * @param y The y coordinate to check within the circle. + */ + static Contains(circle: Phaser.Geom.Circle, x: number, y: number): boolean; + + /** + * Check to see if the Circle contains the given Point object. + * @param circle The Circle to check. + * @param point The Point object to check if it's within the Circle or not. + */ + static ContainsPoint(circle: Phaser.Geom.Circle, point: Phaser.Geom.Point | object): boolean; + + /** + * Check to see if the Circle contains all four points of the given Rectangle object. + * @param circle The Circle to check. + * @param rect The Rectangle object to check if it's within the Circle or not. + */ + static ContainsRect(circle: Phaser.Geom.Circle, rect: Phaser.Geom.Rectangle | object): boolean; + + /** + * Copies the `x`, `y` and `radius` properties from the `source` Circle + * into the given `dest` Circle, then returns the `dest` Circle. + * @param source The source Circle to copy the values from. + * @param dest The destination Circle to copy the values to. + */ + static CopyFrom(source: Phaser.Geom.Circle, dest: O): O; + + /** + * Compares the `x`, `y` and `radius` properties of the two given Circles. + * Returns `true` if they all match, otherwise returns `false`. + * @param circle The first Circle to compare. + * @param toCompare The second Circle to compare. + */ + static Equals(circle: Phaser.Geom.Circle, toCompare: Phaser.Geom.Circle): boolean; + + /** + * Returns the bounds of the Circle object. + * @param circle The Circle to get the bounds from. + * @param out A Rectangle, or rectangle-like object, to store the circle bounds in. If not given a new Rectangle will be created. + */ + static GetBounds(circle: Phaser.Geom.Circle, out?: O): O; + + /** + * 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. + * @param circle The Circle to get the circumference point on. + * @param 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 out An object to store the return values in. If not given a Point object will be created. + */ + static GetPoint(circle: Phaser.Geom.Circle, position: number, out?: O): O; + + /** + * 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. + * @param circle The Circle to get the points from. + * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. + * @param stepRate Sets the quantity by getting the circumference of the circle and dividing it by the stepRate. + * @param output An array to insert the points in to. If not provided a new array will be created. + */ + static GetPoints(circle: Phaser.Geom.Circle, quantity: integer, stepRate?: number, output?: any[]): Phaser.Geom.Point[]; + + /** + * Offsets the Circle by the values given. + * @param circle The Circle to be offset (translated.) + * @param x The amount to horizontally offset the Circle by. + * @param y The amount to vertically offset the Circle by. + */ + static Offset(circle: O, x: number, y: number): O; + + /** + * Offsets the Circle by the values given in the `x` and `y` properties of the Point object. + * @param circle The Circle to be offset (translated.) + * @param point The Point object containing the values to offset the Circle by. + */ + static OffsetPoint(circle: O, point: Phaser.Geom.Point | object): O; + + /** + * Returns a uniformly distributed random point from anywhere within the given Circle. + * @param circle The Circle to get a random point from. + * @param out A Point or point-like object to set the random `x` and `y` values in. + */ + static Random(circle: Phaser.Geom.Circle, out?: O): O; + + } + + /** + * A Circle Geometry object type. + */ + var CIRCLE: integer; + + /** + * An Ellipse Geometry object type. + */ + var ELLIPSE: integer; + + /** + * A Line Geometry object type. + */ + var LINE: integer; + + /** + * A Point Geometry object type. + */ + var POINT: integer; + + /** + * A Polygon Geometry object type. + */ + var POLYGON: integer; + + /** + * A Rectangle Geometry object type. + */ + var RECTANGLE: integer; + + /** + * A Triangle Geometry object type. + */ + var TRIANGLE: integer; + + /** + * An Ellipse object. + * + * This is a geometry object, containing numerical values and related methods to inspect and modify them. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render an Ellipse you should look at the capabilities of the Graphics class. + */ + class Ellipse { + /** + * + * @param x The x position of the center of the ellipse. Default 0. + * @param y The y position of the center of the ellipse. Default 0. + * @param width The width of the ellipse. Default 0. + * @param height The height of the ellipse. Default 0. + */ + constructor(x?: number, y?: number, width?: number, height?: number); + + /** + * Calculates the area of the Ellipse. + * @param ellipse The Ellipse to get the area of. + */ + static Area(ellipse: Phaser.Geom.Ellipse): number; + + /** + * Returns the circumference of the given Ellipse. + * @param ellipse The Ellipse to get the circumference of. + */ + static Circumference(ellipse: Phaser.Geom.Ellipse): number; + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Ellipse based on the given angle. + * @param ellipse The Ellipse to get the circumference point on. + * @param angle The angle from the center of the Ellipse to the circumference to return the point from. Given in radians. + * @param out A Point, or point-like object, to store the results in. If not given a Point will be created. + */ + static CircumferencePoint(ellipse: Phaser.Geom.Ellipse, angle: number, out?: O): O; + + /** + * Creates a new Ellipse instance based on the values contained in the given source. + * @param source The Ellipse to be cloned. Can be an instance of an Ellipse or a ellipse-like object, with x, y, width and height properties. + */ + static Clone(source: Phaser.Geom.Ellipse): Phaser.Geom.Ellipse; + + /** + * Check to see if the Ellipse contains the given x / y coordinates. + * @param ellipse The Ellipse to check. + * @param x The x coordinate to check within the ellipse. + * @param y The y coordinate to check within the ellipse. + */ + static Contains(ellipse: Phaser.Geom.Ellipse, x: number, y: number): boolean; + + /** + * Check to see if the Ellipse contains the given Point object. + * @param ellipse The Ellipse to check. + * @param point The Point object to check if it's within the Circle or not. + */ + static ContainsPoint(ellipse: Phaser.Geom.Ellipse, point: Phaser.Geom.Point | object): boolean; + + /** + * Check to see if the Ellipse contains all four points of the given Rectangle object. + * @param ellipse The Ellipse to check. + * @param rect The Rectangle object to check if it's within the Ellipse or not. + */ + static ContainsRect(ellipse: Phaser.Geom.Ellipse, rect: Phaser.Geom.Rectangle | object): boolean; + + /** + * Copies the `x`, `y`, `width` and `height` properties from the `source` Ellipse + * into the given `dest` Ellipse, then returns the `dest` Ellipse. + * @param source The source Ellipse to copy the values from. + * @param dest The destination Ellipse to copy the values to. + */ + static CopyFrom(source: Phaser.Geom.Ellipse, dest: O): O; + + /** + * The geometry constant type of this object: `GEOM_CONST.ELLIPSE`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * The x position of the center of the ellipse. + */ + x: number; + + /** + * The y position of the center of the ellipse. + */ + y: number; + + /** + * The width of the ellipse. + */ + width: number; + + /** + * The height of the ellipse. + */ + height: number; + + /** + * Check to see if the Ellipse contains the given x / y coordinates. + * @param x The x coordinate to check within the ellipse. + * @param y The y coordinate to check within the ellipse. + */ + contains(x: number, y: number): boolean; + + /** + * Returns a Point 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 circle. + * @param 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 out An object to store the return values in. If not given a Point object will be created. + */ + getPoint(position: number, out?: O): O; + + /** + * Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse, + * based on the given quantity or stepRate values. + * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. + * @param stepRate Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate. + * @param output An array to insert the points in to. If not provided a new array will be created. + */ + getPoints(quantity: integer, stepRate?: number, output?: O): O; + + /** + * Returns a uniformly distributed random point from anywhere within the given Ellipse. + * @param point A Point or point-like object to set the random `x` and `y` values in. + */ + getRandomPoint(point?: O): O; + + /** + * Sets the x, y, width and height of this ellipse. + * @param x The x position of the center of the ellipse. + * @param y The y position of the center of the ellipse. + * @param width The width of the ellipse. + * @param height The height of the ellipse. + */ + setTo(x: number, y: number, width: number, height: number): Phaser.Geom.Ellipse; + + /** + * Sets this Ellipse to be empty with a width and height of zero. + * Does not change its position. + */ + setEmpty(): Phaser.Geom.Ellipse; + + /** + * Sets the position of this Ellipse. + * @param x The x position of the center of the ellipse. + * @param y The y position of the center of the ellipse. + */ + setPosition(x: number, y: number): Phaser.Geom.Ellipse; + + /** + * Sets the size of this Ellipse. + * Does not change its position. + * @param width The width of the ellipse. + * @param height The height of the ellipse. Default width. + */ + setSize(width: number, height?: number): Phaser.Geom.Ellipse; + + /** + * Checks to see if the Ellipse is empty: has a width or height equal to zero. + */ + isEmpty(): boolean; + + /** + * Returns the minor radius of the ellipse. Also known as the Semi Minor Axis. + */ + getMinorRadius(): number; + + /** + * Returns the major radius of the ellipse. Also known as the Semi Major Axis. + */ + getMajorRadius(): number; + + /** + * The left position of the Ellipse. + */ + left: number; + + /** + * The right position of the Ellipse. + */ + right: number; + + /** + * The top position of the Ellipse. + */ + top: number; + + /** + * The bottom position of the Ellipse. + */ + bottom: number; + + /** + * Compares the `x`, `y`, `width` and `height` properties of the two given Ellipses. + * Returns `true` if they all match, otherwise returns `false`. + * @param ellipse The first Ellipse to compare. + * @param toCompare The second Ellipse to compare. + */ + static Equals(ellipse: Phaser.Geom.Ellipse, toCompare: Phaser.Geom.Ellipse): boolean; + + /** + * Returns the bounds of the Ellipse object. + * @param ellipse The Ellipse to get the bounds from. + * @param out A Rectangle, or rectangle-like object, to store the ellipse bounds in. If not given a new Rectangle will be created. + */ + static GetBounds(ellipse: Phaser.Geom.Ellipse, out?: O): O; + + /** + * Returns a Point 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 circle. + * @param ellipse The Ellipse to get the circumference point on. + * @param 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 out An object to store the return values in. If not given a Point object will be created. + */ + static GetPoint(ellipse: Phaser.Geom.Ellipse, position: number, out?: O): O; + + /** + * Returns an array of Point objects containing the coordinates of the points around the circumference of the Ellipse, + * based on the given quantity or stepRate values. + * @param ellipse The Ellipse to get the points from. + * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. + * @param stepRate Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate. + * @param out An array to insert the points in to. If not provided a new array will be created. + */ + static GetPoints(ellipse: Phaser.Geom.Ellipse, quantity: integer, stepRate?: number, out?: O): O; + + /** + * Offsets the Ellipse by the values given. + * @param ellipse The Ellipse to be offset (translated.) + * @param x The amount to horizontally offset the Ellipse by. + * @param y The amount to vertically offset the Ellipse by. + */ + static Offset(ellipse: O, x: number, y: number): O; + + /** + * Offsets the Ellipse by the values given in the `x` and `y` properties of the Point object. + * @param ellipse The Ellipse to be offset (translated.) + * @param point The Point object containing the values to offset the Ellipse by. + */ + static OffsetPoint(ellipse: O, point: Phaser.Geom.Point | object): O; + + /** + * Returns a uniformly distributed random point from anywhere within the given Ellipse. + * @param ellipse The Ellipse to get a random point from. + * @param out A Point or point-like object to set the random `x` and `y` values in. + */ + static Random(ellipse: Phaser.Geom.Ellipse, out?: O): O; + + } + + namespace Intersects { + /** + * Checks if two Circles intersect. + * @param circleA The first Circle to check for intersection. + * @param circleB The second Circle to check for intersection. + */ + function CircleToCircle(circleA: Phaser.Geom.Circle, circleB: Phaser.Geom.Circle): boolean; + + /** + * Checks for intersection between a circle and a rectangle. + * @param circle The circle to be checked. + * @param rect The rectangle to be checked. + */ + function CircleToRectangle(circle: Phaser.Geom.Circle, rect: Phaser.Geom.Rectangle): boolean; + + /** + * Checks if two Circles intersect and returns the intersection points as a Point object array. + * @param circleA The first Circle to check for intersection. + * @param circleB The second Circle to check for intersection. + * @param out An optional array in which to store the points of intersection. + */ + function GetCircleToCircle(circleA: Phaser.Geom.Circle, circleB: Phaser.Geom.Circle, out?: any[]): any[]; + + /** + * Checks for intersection between a circle and a rectangle, + * and returns the intersection points as a Point object array. + * @param circle The circle to be checked. + * @param rect The rectangle to be checked. + * @param out An optional array in which to store the points of intersection. + */ + function GetCircleToRectangle(circle: Phaser.Geom.Circle, rect: Phaser.Geom.Rectangle, out?: any[]): any[]; + + /** + * Checks for intersection between the line segment and circle, + * and returns the intersection points as a Point object array. + * @param line The line segment to check. + * @param circle The circle to check against the line. + * @param out An optional array in which to store the points of intersection. + */ + function GetLineToCircle(line: Phaser.Geom.Line, circle: Phaser.Geom.Circle, out?: any[]): any[]; + + /** + * Checks for intersection between the Line and a Rectangle shape, + * and returns the intersection points as a Point object array. + * @param line The Line to check for intersection. + * @param rect The Rectangle to check for intersection. + * @param out An optional array in which to store the points of intersection. + */ + function GetLineToRectangle(line: Phaser.Geom.Line, rect: Phaser.Geom.Rectangle | object, out?: any[]): any[]; + + /** + * Checks if two Rectangle shapes intersect and returns the area of this intersection as Rectangle object. + * + * If optional `output` parameter is omitted, new Rectangle object is created and returned. If there is intersection, it will contain intersection area. If there is no intersection, it wil be empty Rectangle (all values set to zero). + * + * If Rectangle object is passed as `output` and there is intersection, then intersection area data will be loaded into it and it will be returned. If there is no intersection, it will be returned without any change. + * @param rectA The first Rectangle object. + * @param rectB The second Rectangle object. + * @param output Optional Rectangle object. If given, the intersection data will be loaded into it (in case of no intersection, it will be left unchanged). Otherwise, new Rectangle object will be created and returned with either intersection data or empty (all values set to zero), if there is no intersection. + */ + function GetRectangleIntersection(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, output?: O): O; + + /** + * Checks if two Rectangles intersect and returns the intersection points as a Point object array. + * + * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. As such, the two Rectangles are considered "solid". A Rectangle with no width or no height will never intersect another Rectangle. + * @param rectA The first Rectangle to check for intersection. + * @param rectB The second Rectangle to check for intersection. + * @param out An optional array in which to store the points of intersection. + */ + function GetRectangleToRectangle(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, out?: any[]): any[]; + + /** + * Checks for intersection between Rectangle shape and Triangle shape, + * and returns the intersection points as a Point object array. + * @param rect Rectangle object to test. + * @param triangle Triangle object to test. + * @param out An optional array in which to store the points of intersection. + */ + function GetRectangleToTriangle(rect: Phaser.Geom.Rectangle, triangle: Phaser.Geom.Triangle, out?: any[]): any[]; + + /** + * Checks if a Triangle and a Circle intersect, and returns the intersection points as a Point object array. + * + * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. + * @param triangle The Triangle to check for intersection. + * @param circle The Circle to check for intersection. + * @param out An optional array in which to store the points of intersection. + */ + function GetTriangleToCircle(triangle: Phaser.Geom.Triangle, circle: Phaser.Geom.Circle, out?: any[]): any[]; + + /** + * Checks if a Triangle and a Line intersect, and returns the intersection points as a Point object array. + * + * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". + * @param triangle The Triangle to check with. + * @param line The Line to check with. + * @param out An optional array in which to store the points of intersection. + */ + function GetTriangleToLine(triangle: Phaser.Geom.Triangle, line: Phaser.Geom.Line, out?: any[]): any[]; + + /** + * Checks if two Triangles intersect, and returns the intersection points as a Point object array. + * + * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". + * @param triangleA The first Triangle to check for intersection. + * @param triangleB The second Triangle to check for intersection. + * @param out An optional array in which to store the points of intersection. + */ + function GetTriangleToTriangle(triangleA: Phaser.Geom.Triangle, triangleB: Phaser.Geom.Triangle, out?: any[]): any[]; + + /** + * 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). + * @param line The line segment to check. + * @param circle The circle to check against the line. + * @param nearest An optional Point-like object. If given the closest point on the Line where the circle intersects will be stored in this object. + */ + function LineToCircle(line: Phaser.Geom.Line, circle: Phaser.Geom.Circle, nearest?: Phaser.Geom.Point | any): boolean; + + /** + * Checks if two Lines intersect. If the Lines are identical, they will be treated as parallel and thus non-intersecting. + * @param line1 The first Line to check. + * @param line2 The second Line to check. + * @param out A Point in which to optionally store the point of intersection. + */ + function LineToLine(line1: Phaser.Geom.Line, line2: Phaser.Geom.Line, out?: Phaser.Geom.Point): boolean; + + /** + * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like + * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. + * + * An intersection is considered valid if: + * + * The line starts within, or ends within, the Rectangle. + * The line segment intersects one of the 4 rectangle edges. + * + * The for the purposes of this function rectangles are considered 'solid'. + * @param line The Line to check for intersection. + * @param rect The Rectangle to check for intersection. + */ + function LineToRectangle(line: Phaser.Geom.Line, rect: Phaser.Geom.Rectangle | object): boolean; + + /** + * Checks if the 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. + * @param point The point, or point-like object to check. + * @param line The line segment to test for intersection on. + * @param lineThickness The line thickness. Assumes that the line end points are circular. Default 1. + */ + function PointToLine(point: Phaser.Geom.Point | any, line: Phaser.Geom.Line, lineThickness?: number): boolean; + + /** + * Checks if a Point is located on the given line segment. + * @param point The Point to check for intersection. + * @param line The line segment to check for intersection. + */ + function PointToLineSegment(point: Phaser.Geom.Point, line: Phaser.Geom.Line): boolean; + + /** + * Checks if two Rectangles intersect. + * + * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. + * As such, the two Rectangles are considered "solid". + * A Rectangle with no width or no height will never intersect another Rectangle. + * @param rectA The first Rectangle to check for intersection. + * @param rectB The second Rectangle to check for intersection. + */ + function RectangleToRectangle(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle): boolean; + + /** + * Checks for intersection between Rectangle shape and Triangle shape. + * @param rect Rectangle object to test. + * @param triangle Triangle object to test. + */ + function RectangleToTriangle(rect: Phaser.Geom.Rectangle, triangle: Phaser.Geom.Triangle): boolean; + + /** + * Check if rectangle intersects with values. + * @param rect The rectangle object + * @param left The x coordinate of the left of the Rectangle. + * @param right The x coordinate of the right of the Rectangle. + * @param top The y coordinate of the top of the Rectangle. + * @param bottom The y coordinate of the bottom of the Rectangle. + * @param tolerance Tolerance allowed in the calculation, expressed in pixels. Default 0. + */ + function RectangleToValues(rect: Phaser.Geom.Rectangle, left: number, right: number, top: number, bottom: number, tolerance?: number): boolean; + + /** + * Checks if a Triangle and a Circle intersect. + * + * A Circle intersects a Triangle if its center is located within it or if any of the Triangle's sides intersect the Circle. As such, the Triangle and the Circle are considered "solid" for the intersection. + * @param triangle The Triangle to check for intersection. + * @param circle The Circle to check for intersection. + */ + function TriangleToCircle(triangle: Phaser.Geom.Triangle, circle: Phaser.Geom.Circle): boolean; + + /** + * Checks if a Triangle and a Line intersect. + * + * The Line intersects the Triangle if it starts inside of it, ends inside of it, or crosses any of the Triangle's sides. Thus, the Triangle is considered "solid". + * @param triangle The Triangle to check with. + * @param line The Line to check with. + */ + function TriangleToLine(triangle: Phaser.Geom.Triangle, line: Phaser.Geom.Line): boolean; + + /** + * Checks if two Triangles intersect. + * + * A Triangle intersects another Triangle if any pair of their lines intersects or if any point of one Triangle is within the other Triangle. Thus, the Triangles are considered "solid". + * @param triangleA The first Triangle to check for intersection. + * @param triangleB The second Triangle to check for intersection. + */ + function TriangleToTriangle(triangleA: Phaser.Geom.Triangle, triangleB: Phaser.Geom.Triangle): boolean; + + } + + /** + * Defines a Line segment, a part of a line between two endpoints. + */ + class Line { + /** + * + * @param x1 The x coordinate of the lines starting point. Default 0. + * @param y1 The y coordinate of the lines starting point. Default 0. + * @param x2 The x coordinate of the lines ending point. Default 0. + * @param y2 The y coordinate of the lines ending point. Default 0. + */ + constructor(x1?: number, y1?: number, x2?: number, y2?: number); + + /** + * Calculate the angle of the line in radians. + * @param line The line to calculate the angle of. + */ + static Angle(line: Phaser.Geom.Line): number; + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * + * The `start` and `end` points are rounded before this runs as the algorithm works on integers. + * @param line The line. + * @param stepRate The optional step rate for the points on the line. Default 1. + * @param results An optional array to push the resulting coordinates into. + */ + static BresenhamPoints(line: Phaser.Geom.Line, stepRate?: integer, results?: Phaser.Types.Math.Vector2Like[]): Phaser.Types.Math.Vector2Like[]; + + /** + * Center a line on the given coordinates. + * @param line The line to center. + * @param x The horizontal coordinate to center the line on. + * @param y The vertical coordinate to center the line on. + */ + static CenterOn(line: Phaser.Geom.Line, x: number, y: number): Phaser.Geom.Line; + + /** + * Clone the given line. + * @param source The source line to clone. + */ + static Clone(source: Phaser.Geom.Line): Phaser.Geom.Line; + + /** + * Copy the values of one line to a destination line. + * @param source The source line to copy the values from. + * @param dest The destination line to copy the values to. + */ + static CopyFrom(source: Phaser.Geom.Line, dest: O): O; + + /** + * Compare two lines for strict equality. + * @param line The first line to compare. + * @param toCompare The second line to compare. + */ + static Equals(line: Phaser.Geom.Line, toCompare: Phaser.Geom.Line): boolean; + + /** + * Extends the start and end points of a Line by the given amounts. + * + * The amounts can be positive or negative. Positive points will increase the length of the line, + * while negative ones will decrease it. + * + * If no `right` value is provided it will extend the length of the line equally in both directions. + * + * Pass a value of zero to leave the start or end point unchanged. + * @param line The line instance to extend. + * @param left The amount to extend the start of the line by. + * @param right The amount to extend the end of the line by. If not given it will be set to the `left` value. + */ + static Extend(line: Phaser.Geom.Line, left: number, right?: number): Phaser.Geom.Line; + + /** + * Get the midpoint of the given line. + * @param line The line to get the midpoint of. + * @param out An optional point object to store the midpoint in. + */ + static GetMidPoint(line: Phaser.Geom.Line, out?: O): O; + + /** + * Get the nearest point on a line perpendicular to the given point. + * @param line The line to get the nearest point on. + * @param point The point to get the nearest point to. + * @param out An optional point, or point-like object, to store the coordinates of the nearest point on the line. + */ + static GetNearestPoint(line: Phaser.Geom.Line, point: Phaser.Geom.Point | object, out?: O): O; + + /** + * Calculate the normal of the given line. + * + * The normal of a line is a vector that points perpendicular from it. + * @param line The line to calculate the normal of. + * @param out An optional point object to store the normal in. + */ + static GetNormal(line: Phaser.Geom.Line, out?: O): O; + + /** + * Get a point on a line that's a given percentage along its length. + * @param line The line. + * @param position A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. + * @param out An optional point, or point-like object, to store the coordinates of the point on the line. + */ + static GetPoint(line: Phaser.Geom.Line, position: number, out?: O): O; + + /** + * Get a number of points along a line's length. + * + * Provide a `quantity` to get an exact number of points along the line. + * + * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when + * providing a `stepRate`. + * @param line The line. + * @param quantity The number of points to place on the line. Set to `0` to use `stepRate` instead. + * @param stepRate The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. + * @param out An optional array of Points, or point-like objects, to store the coordinates of the points on the line. + */ + static GetPoints(line: Phaser.Geom.Line, quantity: integer, stepRate?: number, out?: O): O; + + /** + * Get the shortest distance from a Line to the given Point. + * @param line The line to get the distance from. + * @param point The point to get the shortest distance to. + */ + static GetShortestDistance(line: Phaser.Geom.Line, point: Phaser.Geom.Point | object): O; + + /** + * Calculate the height of the given line. + * @param line The line to calculate the height of. + */ + static Height(line: Phaser.Geom.Line): number; + + /** + * Calculate the length of the given line. + * @param line The line to calculate the length of. + */ + static Length(line: Phaser.Geom.Line): number; + + /** + * The geometry constant type of this object: `GEOM_CONST.LINE`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * The x coordinate of the lines starting point. + */ + x1: number; + + /** + * The y coordinate of the lines starting point. + */ + y1: number; + + /** + * The x coordinate of the lines ending point. + */ + x2: number; + + /** + * The y coordinate of the lines ending point. + */ + y2: number; + + /** + * Get a point on a line that's a given percentage along its length. + * @param position A value between 0 and 1, where 0 is the start, 0.5 is the middle and 1 is the end of the line. + * @param output An optional point, or point-like object, to store the coordinates of the point on the line. + */ + getPoint(position: number, output?: O): O; + + /** + * Get a number of points along a line's length. + * + * Provide a `quantity` to get an exact number of points along the line. + * + * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when + * providing a `stepRate`. + * @param quantity The number of points to place on the line. Set to `0` to use `stepRate` instead. + * @param stepRate The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. + * @param output An optional array of Points, or point-like objects, to store the coordinates of the points on the line. + */ + getPoints(quantity: integer, stepRate?: integer, output?: O): O; + + /** + * Get a random Point on the Line. + * @param point An instance of a Point to be modified. + */ + getRandomPoint(point?: O): O; + + /** + * Set new coordinates for the line endpoints. + * @param x1 The x coordinate of the lines starting point. Default 0. + * @param y1 The y coordinate of the lines starting point. Default 0. + * @param x2 The x coordinate of the lines ending point. Default 0. + * @param y2 The y coordinate of the lines ending point. Default 0. + */ + setTo(x1?: number, y1?: number, x2?: number, y2?: number): Phaser.Geom.Line; + + /** + * Returns a Vector2 object that corresponds to the start of this Line. + * @param vec2 A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. + */ + getPointA(vec2?: O): O; + + /** + * Returns a Vector2 object that corresponds to the end of this Line. + * @param vec2 A Vector2 object to set the results in. If `undefined` a new Vector2 will be created. + */ + getPointB(vec2?: O): O; + + /** + * The left position of the Line. + */ + left: number; + + /** + * The right position of the Line. + */ + right: number; + + /** + * The top position of the Line. + */ + top: number; + + /** + * The bottom position of the Line. + */ + bottom: number; + + /** + * Get the angle of the normal of the given line in radians. + * @param line The line to calculate the angle of the normal of. + */ + static NormalAngle(line: Phaser.Geom.Line): number; + + /** + * [description] + * @param line The Line object to get the normal value from. + */ + static NormalX(line: Phaser.Geom.Line): number; + + /** + * The Y value of the normal of the given line. + * The normal of a line is a vector that points perpendicular from it. + * @param line The line to calculate the normal of. + */ + static NormalY(line: Phaser.Geom.Line): number; + + /** + * Offset a line by the given amount. + * @param line The line to offset. + * @param x The horizontal offset to add to the line. + * @param y The vertical offset to add to the line. + */ + static Offset(line: O, x: number, y: number): O; + + /** + * Calculate the perpendicular slope of the given line. + * @param line The line to calculate the perpendicular slope of. + */ + static PerpSlope(line: Phaser.Geom.Line): number; + + /** + * Returns a random point on a given Line. + * @param line The Line to calculate the random Point on. + * @param out An instance of a Point to be modified. + */ + static Random(line: Phaser.Geom.Line, out?: O): O; + + /** + * Calculate the reflected angle between two lines. + * + * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. + * @param lineA The first line. + * @param lineB The second line. + */ + static ReflectAngle(lineA: Phaser.Geom.Line, lineB: Phaser.Geom.Line): number; + + /** + * Rotate a line around its midpoint by the given angle in radians. + * @param line The line to rotate. + * @param angle The angle of rotation in radians. + */ + static Rotate(line: O, angle: number): O; + + /** + * Rotate a line around a point by the given angle in radians. + * @param line The line to rotate. + * @param point The point to rotate the line around. + * @param angle The angle of rotation in radians. + */ + static RotateAroundPoint(line: O, point: Phaser.Geom.Point | object, angle: number): O; + + /** + * Rotate a line around the given coordinates by the given angle in radians. + * @param line The line to rotate. + * @param x The horizontal coordinate to rotate the line around. + * @param y The vertical coordinate to rotate the line around. + * @param angle The angle of rotation in radians. + */ + static RotateAroundXY(line: O, x: number, y: number, angle: number): O; + + /** + * Set a line to a given position, angle and length. + * @param line The line to set. + * @param x The horizontal start position of the line. + * @param y The vertical start position of the line. + * @param angle The angle of the line in radians. + * @param length The length of the line. + */ + static SetToAngle(line: O, x: number, y: number, angle: number, length: number): O; + + /** + * Calculate the slope of the given line. + * @param line The line to calculate the slope of. + */ + static Slope(line: Phaser.Geom.Line): number; + + /** + * Calculate the width of the given line. + * @param line The line to calculate the width of. + */ + static Width(line: Phaser.Geom.Line): number; + + } + + /** + * Defines a Point in 2D space, with an x and y component. + */ + class Point { + /** + * + * @param x The x coordinate of this Point. Default 0. + * @param y The y coordinate of this Point. Default x. + */ + constructor(x?: number, y?: number); + + /** + * Apply `Math.ceil()` to each coordinate of the given Point. + * @param point The Point to ceil. + */ + static Ceil(point: O): O; + + /** + * Clone the given Point. + * @param source The source Point to clone. + */ + static Clone(source: Phaser.Geom.Point): Phaser.Geom.Point; + + /** + * Copy the values of one Point to a destination Point. + * @param source The source Point to copy the values from. + * @param dest The destination Point to copy the values to. + */ + static CopyFrom(source: Phaser.Geom.Point, dest: O): O; + + /** + * A comparison of two `Point` objects to see if they are equal. + * @param point The original `Point` to compare against. + * @param toCompare The second `Point` to compare. + */ + static Equals(point: Phaser.Geom.Point, toCompare: Phaser.Geom.Point): boolean; + + /** + * Apply `Math.ceil()` to each coordinate of the given Point. + * @param point The Point to floor. + */ + static Floor(point: O): O; + + /** + * Get the centroid or geometric center of a plane figure (the arithmetic mean position of all the points in the figure). + * Informally, it is the point at which a cutout of the shape could be perfectly balanced on the tip of a pin. + * @param points [description] + * @param out [description] + */ + static GetCentroid(points: Phaser.Geom.Point[], out?: O): O; + + /** + * Calculate the magnitude of the point, which equivalent to the length of the line from the origin to this point. + * @param point The point to calculate the magnitude for + */ + static GetMagnitude(point: Phaser.Geom.Point): number; + + /** + * Calculates the square of magnitude of given point.(Can be used for fast magnitude calculation of point) + * @param point Returns square of the magnitude/length of given point. + */ + static GetMagnitudeSq(point: Phaser.Geom.Point): number; + + /** + * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. + * @param points [description] + * @param out [description] + */ + static GetRectangleFromPoints(points: Phaser.Geom.Point[], out?: O): O; + + /** + * [description] + * @param pointA The starting `Point` for the interpolation. + * @param pointB The target `Point` for the interpolation. + * @param t The amount to interpolate between the two points. Generally, a value between 0 (returns the starting `Point`) and 1 (returns the target `Point`). If omitted, 0 is used. Default 0. + * @param out An optional `Point` object whose `x` and `y` values will be set to the result of the interpolation (can also be any object with `x` and `y` properties). If omitted, a new `Point` created and returned. + */ + static Interpolate(pointA: Phaser.Geom.Point, pointB: Phaser.Geom.Point, t?: number, out?: O): O; + + /** + * Swaps the X and the Y coordinate of a point. + * @param point The Point to modify. + */ + static Invert(point: O): O; + + /** + * Inverts a Point's coordinates. + * @param point The Point to invert. + * @param out The Point to return the inverted coordinates in. + */ + static Negative(point: Phaser.Geom.Point, out?: O): O; + + /** + * The geometry constant type of this object: `GEOM_CONST.POINT`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * The x coordinate of this Point. + */ + x: number; + + /** + * The y coordinate of this Point. + */ + y: number; + + /** + * Set the x and y coordinates of the point to the given values. + * @param x The x coordinate of this Point. Default 0. + * @param y The y coordinate of this Point. Default x. + */ + setTo(x?: number, y?: number): Phaser.Geom.Point; + + /** + * [description] + * @param pointA [description] + * @param pointB [description] + * @param out [description] + */ + static Project(pointA: Phaser.Geom.Point, pointB: Phaser.Geom.Point, out?: O): O; + + /** + * [description] + * @param pointA [description] + * @param pointB [description] + * @param out [description] + */ + static ProjectUnit(pointA: Phaser.Geom.Point, pointB: Phaser.Geom.Point, out?: O): O; + + /** + * Changes the magnitude (length) of a two-dimensional vector without changing its direction. + * @param point The Point to treat as the end point of the vector. + * @param magnitude The new magnitude of the vector. + */ + static SetMagnitude(point: O, magnitude: number): O; + + } + + /** + * A Polygon object + * + * The polygon is a closed shape consists of a series of connected straight lines defined by list of ordered points. + * Several formats are supported to define the list of points, check the setTo method for details. + * This is a geometry object allowing you to define and inspect the shape. + * It is not a Game Object, in that you cannot add it to the display list, and it has no texture. + * To render a Polygon you should look at the capabilities of the Graphics class. + */ + class Polygon { + /** + * + * @param points List of points defining the perimeter of this Polygon. Several formats are supported: + * - A string containing paired x y values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + */ + constructor(points?: Phaser.Geom.Point[]); + + /** + * Create a new polygon which is a copy of the specified polygon + * @param polygon The polygon to create a clone of + */ + static Clone(polygon: Phaser.Geom.Polygon): Phaser.Geom.Polygon; + + /** + * Checks if a point is within the bounds of a Polygon. + * @param polygon The Polygon to check against. + * @param x The X coordinate of the point to check. + * @param y The Y coordinate of the point to check. + */ + static Contains(polygon: Phaser.Geom.Polygon, x: number, y: number): boolean; + + /** + * [description] + * @param polygon [description] + * @param point [description] + */ + static ContainsPoint(polygon: Phaser.Geom.Polygon, point: Phaser.Geom.Point): boolean; + + /** + * Calculates the bounding AABB rectangle of a polygon. + * @param polygon The polygon that should be calculated. + * @param out The rectangle or object that has x, y, width, and height properties to store the result. Optional. + */ + static GetAABB(polygon: Phaser.Geom.Polygon, out?: O): O; + + /** + * Stores all of the points of a Polygon into a flat array of numbers following the sequence [ x,y, x,y, x,y ], + * i.e. each point of the Polygon, in the order it's defined, corresponds to two elements of the resultant + * array for the point's X and Y coordinate. + * @param polygon The Polygon whose points to export. + * @param output An array to which the points' coordinates should be appended. + */ + static GetNumberArray(polygon: Phaser.Geom.Polygon, output?: O): O; + + /** + * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, + * based on the given quantity or stepRate values. + * @param polygon The Polygon to get the points from. + * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. + * @param stepRate Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate. + * @param output An array to insert the points in to. If not provided a new array will be created. + */ + static GetPoints(polygon: Phaser.Geom.Polygon, quantity: integer, stepRate?: number, output?: any[]): Phaser.Geom.Point[]; + + /** + * Returns the perimeter of the given Polygon. + * @param polygon The Polygon to get the perimeter of. + */ + static Perimeter(polygon: Phaser.Geom.Polygon): number; + + /** + * The geometry constant type of this object: `GEOM_CONST.POLYGON`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * The area of this Polygon. + */ + area: number; + + /** + * An array of number pair objects that make up this polygon. I.e. [ {x,y}, {x,y}, {x,y} ] + */ + points: Phaser.Geom.Point[]; + + /** + * Check to see if the Polygon contains the given x / y coordinates. + * @param x The x coordinate to check within the polygon. + * @param y The y coordinate to check within the polygon. + */ + contains(x: number, y: number): boolean; + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - A string containing paired values separated by a single space: `'40 0 40 20 100 20 100 80 40 80 40 100 0 50'` + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * + * `setTo` may also be called without any arguments to remove all points. + * @param points Points defining the perimeter of this polygon. Please check function description above for the different supported formats. + */ + setTo(points: any[]): Phaser.Geom.Polygon; + + /** + * Calculates the area of the Polygon. This is available in the property Polygon.area + */ + calculateArea(): number; + + /** + * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, + * based on the given quantity or stepRate values. + * @param quantity The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. + * @param stepRate Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate. + * @param output An array to insert the points in to. If not provided a new array will be created. + */ + getPoints(quantity: integer, stepRate?: number, output?: O): O; + + /** + * Reverses the order of the points of a Polygon. + * @param polygon The Polygon to modify. + */ + static Reverse(polygon: O): O; + + /** + * Takes a Polygon object and applies Chaikin's smoothing algorithm on its points. + * @param polygon The polygon to be smoothed. The polygon will be modified in-place and returned. + */ + static Smooth(polygon: O): O; + + } + + /** + * Encapsulates a 2D rectangle defined by its corner point in the top-left and its extends in x (width) and y (height) + */ + class Rectangle { + /** + * + * @param x The X coordinate of the top left corner of the Rectangle. Default 0. + * @param y The Y coordinate of the top left corner of the Rectangle. Default 0. + * @param width The width of the Rectangle. Default 0. + * @param height The height of the Rectangle. Default 0. + */ + constructor(x?: number, y?: number, width?: number, height?: number); + + /** + * Calculates the area of the given Rectangle object. + * @param rect The rectangle to calculate the area of. + */ + static Area(rect: Phaser.Geom.Rectangle): number; + + /** + * Rounds a Rectangle's position up to the smallest integer greater than or equal to each current coordinate. + * @param rect The Rectangle to adjust. + */ + static Ceil(rect: O): O; + + /** + * Rounds a Rectangle's position and size up to the smallest integer greater than or equal to each respective value. + * @param rect The Rectangle to modify. + */ + static CeilAll(rect: O): O; + + /** + * Moves the top-left corner of a Rectangle so that its center is at the given coordinates. + * @param rect The Rectangle to be centered. + * @param x The X coordinate of the Rectangle's center. + * @param y The Y coordinate of the Rectangle's center. + */ + static CenterOn(rect: O, x: number, y: number): O; + + /** + * Creates a new Rectangle which is identical to the given one. + * @param source The Rectangle to clone. + */ + static Clone(source: Phaser.Geom.Rectangle): Phaser.Geom.Rectangle; + + /** + * Checks if a given point is inside a Rectangle's bounds. + * @param rect The Rectangle to check. + * @param x The X coordinate of the point to check. + * @param y The Y coordinate of the point to check. + */ + static Contains(rect: Phaser.Geom.Rectangle, x: number, y: number): boolean; + + /** + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. + * @param rect The Rectangle object. + * @param point The point object to be checked. Can be a Phaser Point object or any object with x and y values. + */ + static ContainsPoint(rect: Phaser.Geom.Rectangle, point: Phaser.Geom.Point): boolean; + + /** + * Tests if one rectangle fully contains another. + * @param rectA The first rectangle. + * @param rectB The second rectangle. + */ + static ContainsRect(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle): boolean; + + /** + * Copy the values of one Rectangle to a destination Rectangle. + * @param source The source Rectangle to copy the values from. + * @param dest The destination Rectangle to copy the values to. + */ + static CopyFrom(source: Phaser.Geom.Rectangle, dest: O): O; + + /** + * Create an array of points for each corner of a Rectangle + * If an array is specified, each point object will be added to the end of the array, otherwise a new array will be created. + * @param rect The Rectangle object to be decomposed. + * @param out If provided, each point will be added to this array. + */ + static Decompose(rect: Phaser.Geom.Rectangle, out?: any[]): any[]; + + /** + * Compares the `x`, `y`, `width` and `height` properties of two rectangles. + * @param rect Rectangle A + * @param toCompare Rectangle B + */ + static Equals(rect: Phaser.Geom.Rectangle, toCompare: Phaser.Geom.Rectangle): boolean; + + /** + * Adjusts the target rectangle, changing its width, height and position, + * so that it fits inside the area of the source rectangle, while maintaining its original + * aspect ratio. + * + * Unlike the `FitOutside` function, there may be some space inside the source area not covered. + * @param target The target rectangle to adjust. + * @param source The source rectangle to envelop the target in. + */ + static FitInside(target: O, source: Phaser.Geom.Rectangle): O; + + /** + * Adjusts the target rectangle, changing its width, height and position, + * so that it fully covers the area of the source rectangle, while maintaining its original + * aspect ratio. + * + * Unlike the `FitInside` function, the target rectangle may extend further out than the source. + * @param target The target rectangle to adjust. + * @param source The source rectangle to envelope the target in. + */ + static FitOutside(target: O, source: Phaser.Geom.Rectangle): O; + + /** + * Rounds down (floors) the top left X and Y coordinates of the given Rectangle to the largest integer less than or equal to them + * @param rect The rectangle to floor the top left X and Y coordinates of + */ + static Floor(rect: O): O; + + /** + * Rounds a Rectangle's position and size down to the largest integer less than or equal to each current coordinate or dimension. + * @param rect The Rectangle to adjust. + */ + static FloorAll(rect: O): O; + + /** + * Constructs new Rectangle or repositions and resizes an existing Rectangle so that all of the given points are on or within its bounds. + * @param points An array of points (either arrays with two elements corresponding to the X and Y coordinate or an object with public `x` and `y` properties) which should be surrounded by the Rectangle. + * @param out Optional Rectangle to adjust. + */ + static FromPoints(points: any[], out?: O): O; + + /** + * Calculates the width/height ratio of a rectangle. + * @param rect The rectangle. + */ + static GetAspectRatio(rect: Phaser.Geom.Rectangle): number; + + /** + * Returns the center of a Rectangle as a Point. + * @param rect The Rectangle to get the center of. + * @param out Optional point-like object to update with the center coordinates. + */ + static GetCenter(rect: Phaser.Geom.Rectangle, out?: O): O; + + /** + * Position is a value between 0 and 1 where 0 = the top-left of the rectangle and 0.5 = the bottom right. + * @param rectangle [description] + * @param position [description] + * @param out [description] + */ + static GetPoint(rectangle: Phaser.Geom.Rectangle, position: number, out?: O): O; + + /** + * Return an array of points from the perimeter of the rectangle, each spaced out based on the quantity or step required. + * @param rectangle The Rectangle object to get the points from. + * @param step Step between points. Used to calculate the number of points to return when quantity is falsey. Ignored if quantity is positive. + * @param quantity The number of evenly spaced points from the rectangles perimeter to return. If falsey, step param will be used to calculate the number of points. + * @param out An optional array to store the points in. + */ + static GetPoints(rectangle: Phaser.Geom.Rectangle, step: number, quantity: integer, out?: O): O; + + /** + * The size of the Rectangle object, expressed as a Point object + * with the values of the width and height properties. + * @param rect [description] + * @param out [description] + */ + static GetSize(rect: Phaser.Geom.Rectangle, out?: O): O; + + /** + * Increases the size of a Rectangle by a specified amount. + * + * The center of the Rectangle stays the same. The amounts are added to each side, so the actual increase in width or height is two times bigger than the respective argument. + * @param rect The Rectangle to inflate. + * @param x How many pixels the left and the right side should be moved by horizontally. + * @param y How many pixels the top and the bottom side should be moved by vertically. + */ + static Inflate(rect: O, x: number, y: number): O; + + /** + * Takes two Rectangles and first checks to see if they intersect. + * If they intersect it will return the area of intersection in the `out` Rectangle. + * If they do not intersect, the `out` Rectangle will have a width and height of zero. + * @param rectA The first Rectangle to get the intersection from. + * @param rectB The second Rectangle to get the intersection from. + * @param out A Rectangle to store the intersection results in. + */ + static Intersection(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, out?: Phaser.Geom.Rectangle): O; + + /** + * Return an array of points from the perimeter of the rectangle + * each spaced out based on the quantity or step required + * @param rect [description] + * @param step [description] + * @param quantity [description] + * @param out [description] + */ + static MarchingAnts(rect: Phaser.Geom.Rectangle, step: number, quantity: integer, out?: O): O; + + /** + * Merges a Rectangle with a list of points by repositioning and/or resizing it such that all points are located on or within its bounds. + * @param target The Rectangle which should be merged. + * @param points An array of Points (or any object with public `x` and `y` properties) which should be merged with the Rectangle. + */ + static MergePoints(target: O, points: Phaser.Geom.Point[]): O; + + /** + * Merges the source rectangle into the target rectangle and returns the target. + * Neither rectangle should have a negative width or height. + * @param target Target rectangle. Will be modified to include source rectangle. + * @param source Rectangle that will be merged into target rectangle. + */ + static MergeRect(target: O, source: Phaser.Geom.Rectangle): O; + + /** + * Merges a Rectangle with a point by repositioning and/or resizing it so that the point is on or within its bounds. + * @param target The Rectangle which should be merged and modified. + * @param x The X coordinate of the point which should be merged. + * @param y The Y coordinate of the point which should be merged. + */ + static MergeXY(target: O, x: number, y: number): O; + + /** + * Nudges (translates) the top left corner of a Rectangle by a given offset. + * @param rect The Rectangle to adjust. + * @param x The distance to move the Rectangle horizontally. + * @param y The distance to move the Rectangle vertically. + */ + static Offset(rect: O, x: number, y: number): O; + + /** + * Nudges (translates) the top-left corner of a Rectangle by the coordinates of a point (translation vector). + * @param rect The Rectangle to adjust. + * @param point The point whose coordinates should be used as an offset. + */ + static OffsetPoint(rect: O, point: Phaser.Geom.Point | Phaser.Math.Vector2): O; + + /** + * Checks if two Rectangles overlap. If a Rectangle is within another Rectangle, the two will be considered overlapping. Thus, the Rectangles are treated as "solid". + * @param rectA The first Rectangle to check. + * @param rectB The second Rectangle to check. + */ + static Overlaps(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle): boolean; + + /** + * Calculates the perimeter of a Rectangle. + * @param rect The Rectangle to use. + */ + static Perimeter(rect: Phaser.Geom.Rectangle): number; + + /** + * [description] + * @param rectangle [description] + * @param angle [description] + * @param out [description] + */ + static PerimeterPoint(rectangle: Phaser.Geom.Rectangle, angle: integer, out?: O): O; + + /** + * Returns a random point within a Rectangle. + * @param rect The Rectangle to return a point from. + * @param out The object to update with the point's coordinates. + */ + static Random(rect: Phaser.Geom.Rectangle, out: O): O; + + /** + * Calculates a random point that lies within the `outer` Rectangle, but outside of the `inner` Rectangle. + * The inner Rectangle must be fully contained within the outer rectangle. + * @param outer The outer Rectangle to get the random point within. + * @param inner The inner Rectangle to exclude from the returned point. + * @param out A Point, or Point-like object to store the result in. If not specified, a new Point will be created. + */ + static RandomOutside(outer: Phaser.Geom.Rectangle, inner: Phaser.Geom.Rectangle, out?: O): O; + + /** + * The geometry constant type of this object: `GEOM_CONST.RECTANGLE`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * The X coordinate of the top left corner of the Rectangle. + */ + x: number; + + /** + * The Y coordinate of the top left corner of the Rectangle. + */ + y: number; + + /** + * The width of the Rectangle, i.e. the distance between its left side (defined by `x`) and its right side. + */ + width: number; + + /** + * The height of the Rectangle, i.e. the distance between its top side (defined by `y`) and its bottom side. + */ + height: number; + + /** + * Checks if the given point is inside the Rectangle's bounds. + * @param x The X coordinate of the point to check. + * @param y The Y coordinate of the point to check. + */ + contains(x: number, y: number): boolean; + + /** + * Calculates the coordinates of a point at a certain `position` on the Rectangle's perimeter. + * + * The `position` is a fraction between 0 and 1 which defines how far into the perimeter the point is. + * + * A value of 0 or 1 returns the point at the top left corner of the rectangle, while a value of 0.5 returns the point at the bottom right corner of the rectangle. Values between 0 and 0.5 are on the top or the right side and values between 0.5 and 1 are on the bottom or the left side. + * @param position The normalized distance into the Rectangle's perimeter to return. + * @param output An object to update with the `x` and `y` coordinates of the point. + */ + getPoint(position: number, output?: O): O; + + /** + * Returns an array of points from the perimeter of the Rectangle, each spaced out based on the quantity or step required. + * @param 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 stepRate If `quantity` is 0, determines the normalized distance between each returned point. + * @param output An array to which to append the points. + */ + getPoints(quantity: integer, stepRate?: number, output?: O): O; + + /** + * Returns a random point within the Rectangle's bounds. + * @param point The object in which to store the `x` and `y` coordinates of the point. + */ + getRandomPoint(point?: O): O; + + /** + * Sets the position, width, and height of the Rectangle. + * @param x The X coordinate of the top left corner of the Rectangle. + * @param y The Y coordinate of the top left corner of the Rectangle. + * @param width The width of the Rectangle. + * @param height The height of the Rectangle. + */ + setTo(x: number, y: number, width: number, height: number): Phaser.Geom.Rectangle; + + /** + * Resets the position, width, and height of the Rectangle to 0. + */ + setEmpty(): Phaser.Geom.Rectangle; + + /** + * Sets the position of the Rectangle. + * @param x The X coordinate of the top left corner of the Rectangle. + * @param y The Y coordinate of the top left corner of the Rectangle. Default x. + */ + setPosition(x: number, y?: number): Phaser.Geom.Rectangle; + + /** + * Sets the width and height of the Rectangle. + * @param width The width to set the Rectangle to. + * @param height The height to set the Rectangle to. Default width. + */ + setSize(width: number, height?: number): Phaser.Geom.Rectangle; + + /** + * Determines if the Rectangle is empty. A Rectangle is empty if its width or height is less than or equal to 0. + */ + isEmpty(): boolean; + + /** + * Returns a Line object that corresponds to the top of this Rectangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineA(line?: O): O; + + /** + * Returns a Line object that corresponds to the right of this Rectangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineB(line?: O): O; + + /** + * Returns a Line object that corresponds to the bottom of this Rectangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineC(line?: O): O; + + /** + * Returns a Line object that corresponds to the left of this Rectangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineD(line?: O): O; + + /** + * The x coordinate of the left of the Rectangle. + * Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + */ + left: number; + + /** + * The sum of the x and width properties. + * Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. + */ + right: number; + + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + */ + top: number; + + /** + * The sum of the y and height properties. + * Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + */ + bottom: number; + + /** + * The x coordinate of the center of the Rectangle. + */ + centerX: number; + + /** + * The y coordinate of the center of the Rectangle. + */ + centerY: number; + + /** + * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. + * @param rect The first Rectangle object. + * @param toCompare The second Rectangle object. + */ + static SameDimensions(rect: Phaser.Geom.Rectangle, toCompare: Phaser.Geom.Rectangle): boolean; + + /** + * Scales the width and height of this Rectangle by the given amounts. + * @param rect The `Rectangle` object that will be scaled by the specified amount(s). + * @param x The factor by which to scale the rectangle horizontally. + * @param y The amount by which to scale the rectangle vertically. If this is not specified, the rectangle will be scaled by the factor `x` in both directions. + */ + static Scale(rect: O, x: number, y: number): O; + + /** + * Creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it encompasses the two given Rectangles, i.e. calculates their union. + * @param rectA The first Rectangle to use. + * @param rectB The second Rectangle to use. + * @param out The Rectangle to store the union in. + */ + static Union(rectA: Phaser.Geom.Rectangle, rectB: Phaser.Geom.Rectangle, out?: O): O; + + } + + /** + * A triangle is a plane created by connecting three points. + * The first two arguments specify the first point, the middle two arguments + * specify the second point, and the last two arguments specify the third point. + */ + class Triangle { + /** + * + * @param x1 `x` coordinate of the first point. Default 0. + * @param y1 `y` coordinate of the first point. Default 0. + * @param x2 `x` coordinate of the second point. Default 0. + * @param y2 `y` coordinate of the second point. Default 0. + * @param x3 `x` coordinate of the third point. Default 0. + * @param y3 `y` coordinate of the third point. Default 0. + */ + constructor(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number); + + /** + * Returns the area of a Triangle. + * @param triangle The Triangle to use. + */ + static Area(triangle: Phaser.Geom.Triangle): number; + + /** + * Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent). + * The x/y specifies the top-middle of the triangle (x1/y1) and length is the length of each side. + * @param x x coordinate of the top point of the triangle. + * @param y y coordinate of the top point of the triangle. + * @param length Length of each side of the triangle. + */ + static BuildEquilateral(x: number, y: number, length: number): Phaser.Geom.Triangle; + + /** + * [description] + * @param data A flat array of vertex coordinates like [x0,y0, x1,y1, x2,y2, ...] + * @param holes 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). Default null. + * @param scaleX [description] Default 1. + * @param scaleY [description] Default 1. + * @param out [description] + */ + static BuildFromPolygon(data: any[], holes?: any[], scaleX?: number, scaleY?: number, out?: O): O; + + /** + * Builds a right triangle, i.e. one which has a 90-degree angle and two acute angles. + * @param x The X coordinate of the right angle, which will also be the first X coordinate of the constructed Triangle. + * @param y The Y coordinate of the right angle, which will also be the first Y coordinate of the constructed Triangle. + * @param width The length of the side which is to the left or to the right of the right angle. + * @param height The length of the side which is above or below the right angle. + */ + static BuildRight(x: number, y: number, width: number, height: number): Phaser.Geom.Triangle; + + /** + * Positions the Triangle so that it is centered on the given coordinates. + * @param triangle The triangle to be positioned. + * @param x The horizontal coordinate to center on. + * @param y The vertical coordinate to center on. + * @param centerFunc The function used to center the triangle. Defaults to Centroid centering. + */ + static CenterOn(triangle: O, x: number, y: number, centerFunc?: CenterFunction): O; + + /** + * Calculates the position of a Triangle's centroid, which is also its center of mass (center of gravity). + * + * The centroid is the point in a Triangle at which its three medians (the lines drawn from the vertices to the bisectors of the opposite sides) meet. It divides each one in a 2:1 ratio. + * @param triangle The Triangle to use. + * @param out An object to store the coordinates in. + */ + static Centroid(triangle: Phaser.Geom.Triangle, out?: O): O; + + /** + * Computes the circumcentre of a triangle. The circumcentre is the centre of + * the circumcircle, the smallest circle which encloses 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. + * @param triangle [description] + * @param out [description] + */ + static CircumCenter(triangle: Phaser.Geom.Triangle, out?: O): O; + + /** + * Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices. + * @param triangle The Triangle to use as input. + * @param out An optional Circle to store the result in. + */ + static CircumCircle(triangle: Phaser.Geom.Triangle, out?: O): O; + + /** + * Clones a Triangle object. + * @param source The Triangle to clone. + */ + static Clone(source: Phaser.Geom.Triangle): Phaser.Geom.Triangle; + + /** + * Checks if a point (as a pair of coordinates) is inside a Triangle's bounds. + * @param triangle The Triangle to check. + * @param x The X coordinate of the point to check. + * @param y The Y coordinate of the point to check. + */ + static Contains(triangle: Phaser.Geom.Triangle, x: number, y: number): boolean; + + /** + * Filters an array of point-like objects to only those contained within a triangle. + * If `returnFirst` is true, will return an array containing only the first point in the provided array that is within the triangle (or an empty array if there are no such points). + * @param triangle The triangle that the points are being checked in. + * @param points An array of point-like objects (objects that have an `x` and `y` property) + * @param returnFirst If `true`, return an array containing only the first point found that is within the triangle. Default false. + * @param out If provided, the points that are within the triangle will be appended to this array instead of being added to a new array. If `returnFirst` is true, only the first point found within the triangle will be appended. This array will also be returned by this function. + */ + static ContainsArray(triangle: Phaser.Geom.Triangle, points: Phaser.Geom.Point[], returnFirst?: boolean, out?: any[]): Phaser.Geom.Point[]; + + /** + * Tests if a triangle contains a point. + * @param triangle The triangle. + * @param point The point to test, or any point-like object with public `x` and `y` properties. + */ + static ContainsPoint(triangle: Phaser.Geom.Triangle, point: Phaser.Geom.Point | Phaser.Math.Vector2 | any): boolean; + + /** + * Copy the values of one Triangle to a destination Triangle. + * @param source The source Triangle to copy the values from. + * @param dest The destination Triangle to copy the values to. + */ + static CopyFrom(source: Phaser.Geom.Triangle, dest: O): O; + + /** + * Decomposes a Triangle into an array of its points. + * @param triangle The Triangle to decompose. + * @param out An array to store the points into. + */ + static Decompose(triangle: Phaser.Geom.Triangle, out?: any[]): any[]; + + /** + * Returns true if two triangles have the same coordinates. + * @param triangle The first triangle to check. + * @param toCompare The second triangle to check. + */ + static Equals(triangle: Phaser.Geom.Triangle, toCompare: Phaser.Geom.Triangle): boolean; + + /** + * Returns a Point from around the perimeter of a Triangle. + * @param triangle The Triangle to get the point on its perimeter from. + * @param position The position along the perimeter of the triangle. A value between 0 and 1. + * @param out An option Point, or Point-like object to store the value in. If not given a new Point will be created. + */ + static GetPoint(triangle: Phaser.Geom.Triangle, position: number, out?: O): O; + + /** + * Returns an array of evenly spaced points on the perimeter of a Triangle. + * @param triangle The Triangle to get the points from. + * @param quantity The number of evenly spaced points to return. Set to 0 to return an arbitrary number of points based on the `stepRate`. + * @param stepRate If `quantity` is 0, the distance between each returned point. + * @param out An array to which the points should be appended. + */ + static GetPoints(triangle: Phaser.Geom.Triangle, quantity: integer, stepRate: number, out?: O): O; + + /** + * Calculates the position of the incenter of a Triangle object. This is the point where its three angle bisectors meet and it's also the center of the incircle, which is the circle inscribed in the triangle. + * @param triangle The Triangle to find the incenter of. + * @param out An optional Point in which to store the coordinates. + */ + static InCenter(triangle: Phaser.Geom.Triangle, out?: O): O; + + /** + * Moves each point (vertex) of a Triangle by a given offset, thus moving the entire Triangle by that offset. + * @param triangle The Triangle to move. + * @param x The horizontal offset (distance) by which to move each point. Can be positive or negative. + * @param y The vertical offset (distance) by which to move each point. Can be positive or negative. + */ + static Offset(triangle: O, x: number, y: number): O; + + /** + * Gets the length of the perimeter of the given triangle. + * @param triangle [description] + */ + static Perimeter(triangle: Phaser.Geom.Triangle): number; + + /** + * [description] + * @param triangle [description] + * @param out [description] + */ + static Random(triangle: Phaser.Geom.Triangle, out?: O): O; + + /** + * Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet. + * @param triangle The Triangle to rotate. + * @param angle The angle by which to rotate the Triangle, in radians. + */ + static Rotate(triangle: O, angle: number): O; + + /** + * Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties. + * @param triangle The Triangle to rotate. + * @param point The Point to rotate the Triangle about. + * @param angle The angle by which to rotate the Triangle, in radians. + */ + static RotateAroundPoint(triangle: O, point: Phaser.Geom.Point, angle: number): O; + + /** + * Rotates an entire Triangle at a given angle about a specific point. + * @param triangle The Triangle to rotate. + * @param x The X coordinate of the point to rotate the Triangle about. + * @param y The Y coordinate of the point to rotate the Triangle about. + * @param angle The angle by which to rotate the Triangle, in radians. + */ + static RotateAroundXY(triangle: O, x: number, y: number, angle: number): O; + + /** + * The geometry constant type of this object: `GEOM_CONST.TRIANGLE`. + * Used for fast type comparisons. + */ + readonly type: integer; + + /** + * `x` coordinate of the first point. + */ + x1: number; + + /** + * `y` coordinate of the first point. + */ + y1: number; + + /** + * `x` coordinate of the second point. + */ + x2: number; + + /** + * `y` coordinate of the second point. + */ + y2: number; + + /** + * `x` coordinate of the third point. + */ + x3: number; + + /** + * `y` coordinate of the third point. + */ + y3: number; + + /** + * Checks whether a given points lies within the triangle. + * @param x The x coordinate of the point to check. + * @param y The y coordinate of the point to check. + */ + contains(x: number, y: number): boolean; + + /** + * Returns a specific point on the triangle. + * @param position Position as float within `0` and `1`. `0` equals the first point. + * @param output Optional Point, or point-like object, that the calculated point will be written to. + */ + getPoint(position: number, output?: O): O; + + /** + * Calculates a list of evenly distributed points on the triangle. It is either possible to pass an amount of points to be generated (`quantity`) or the distance between two points (`stepRate`). + * @param quantity Number of points to be generated. Can be falsey when `stepRate` should be used. All points have the same distance along the triangle. + * @param stepRate Distance between two points. Will only be used when `quantity` is falsey. + * @param output Optional Array for writing the calculated points into. Otherwise a new array will be created. + */ + getPoints(quantity: integer, stepRate?: number, output?: O): O; + + /** + * Returns a random point along the triangle. + * @param point Optional `Point` that should be modified. Otherwise a new one will be created. + */ + getRandomPoint(point?: O): O; + + /** + * Sets all three points of the triangle. Leaving out any coordinate sets it to be `0`. + * @param x1 `x` coordinate of the first point. Default 0. + * @param y1 `y` coordinate of the first point. Default 0. + * @param x2 `x` coordinate of the second point. Default 0. + * @param y2 `y` coordinate of the second point. Default 0. + * @param x3 `x` coordinate of the third point. Default 0. + * @param y3 `y` coordinate of the third point. Default 0. + */ + setTo(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number): Phaser.Geom.Triangle; + + /** + * Returns a Line object that corresponds to Line A of this Triangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineA(line?: O): O; + + /** + * Returns a Line object that corresponds to Line B of this Triangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineB(line?: O): O; + + /** + * Returns a Line object that corresponds to Line C of this Triangle. + * @param line A Line object to set the results in. If `undefined` a new Line will be created. + */ + getLineC(line?: O): O; + + /** + * Left most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. + */ + left: number; + + /** + * Right most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly. + */ + right: number; + + /** + * Top most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. + */ + top: number; + + /** + * Bottom most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly. + */ + bottom: number; + + } + + } + + namespace Input { + /** + * The mouse pointer is being held down. + */ + var MOUSE_DOWN: integer; + + /** + * The mouse pointer is being moved. + */ + var MOUSE_MOVE: integer; + + /** + * The mouse pointer is released. + */ + var MOUSE_UP: integer; + + /** + * A touch pointer has been started. + */ + var TOUCH_START: integer; + + /** + * A touch pointer has been started. + */ + var TOUCH_MOVE: integer; + + /** + * A touch pointer has been started. + */ + var TOUCH_END: integer; + + /** + * The pointer lock has changed. + */ + var POINTER_LOCK_CHANGE: integer; + + /** + * A touch pointer has been been cancelled by the browser. + */ + var TOUCH_CANCEL: integer; + + /** + * The mouse wheel changes. + */ + var MOUSE_WHEEL: integer; + + /** + * Creates a new Interactive Object. + * + * This is called automatically by the Input Manager when you enable a Game Object for input. + * + * The resulting Interactive Object is mapped to the Game Object's `input` property. + * @param gameObject The Game Object to which this Interactive Object is bound. + * @param hitArea The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. + * @param hitAreaCallback The 'contains' check callback that the hit area shape will use for all hit tests. + */ + function CreateInteractiveObject(gameObject: Phaser.GameObjects.GameObject, hitArea: any, hitAreaCallback: Phaser.Types.Input.HitAreaCallback): Phaser.Types.Input.InteractiveObject; + + /** + * Creates a new Pixel Perfect Handler function. + * + * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. + * @param textureManager A reference to the Texture Manager. + * @param alphaTolerance The alpha level that the pixel should be above to be included as a successful interaction. + */ + function CreatePixelPerfectHandler(textureManager: Phaser.Textures.TextureManager, alphaTolerance: integer): Function; + + namespace Events { + /** + * The Input Plugin Boot Event. + * + * This internal event is dispatched by the Input Plugin when it boots, signalling to all of its systems to create themselves. + */ + const BOOT: any; + + /** + * The Input Plugin Destroy Event. + * + * This internal event is dispatched by the Input Plugin when it is destroyed, signalling to all of its systems to destroy themselves. + */ + const DESTROY: any; + + /** + * The Pointer Drag End Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer stops dragging a Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('dragend', listener)`. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_END]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_END} event instead. + */ + const DRAG_END: any; + + /** + * The Pointer Drag Enter Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object into a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('dragenter', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_ENTER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_ENTER} event instead. + */ + const DRAG_ENTER: any; + + /** + * The Pointer Drag Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves while dragging a Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('drag', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG} event instead. + */ + const DRAG: any; + + /** + * The Pointer Drag Leave Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object out of a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('dragleave', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_LEAVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_LEAVE} event instead. + */ + const DRAG_LEAVE: any; + + /** + * The Pointer Drag Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drags a Game Object over a Drag Target. + * + * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within + * the drag target, it will emit this event instead. + * + * Listen to this event from within a Scene using: `this.input.on('dragover', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_OVER} event instead. + */ + const DRAG_OVER: any; + + /** + * The Pointer Drag Start Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer starts to drag any Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('dragstart', listener)`. + * + * A Pointer can only drag a single Game Object at once. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DRAG_START]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DRAG_START} event instead. + */ + const DRAG_START: any; + + /** + * The Pointer Drop Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer drops a Game Object on a Drag Target. + * + * Listen to this event from within a Scene using: `this.input.on('drop', listener)`. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_DROP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DROP} event instead. + */ + const DROP: any; + + /** + * The Game Object Down Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down on _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectdown', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_DOWN: any; + + /** + * The Game Object Drag End Event. + * + * This event is dispatched by an interactive Game Object if a pointer stops dragging it. + * + * Listen to this event from a Game Object using: `gameObject.on('dragend', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive](Phaser.GameObjects.GameObject#setInteractive) for more details. + */ + const GAMEOBJECT_DRAG_END: any; + + /** + * The Game Object Drag Enter Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it into a drag target. + * + * Listen to this event from a Game Object using: `gameObject.on('dragenter', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + */ + const GAMEOBJECT_DRAG_ENTER: any; + + /** + * The Game Object Drag Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves while dragging it. + * + * Listen to this event from a Game Object using: `gameObject.on('drag', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + */ + const GAMEOBJECT_DRAG: any; + + /** + * The Game Object Drag Leave Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it out of a drag target. + * + * Listen to this event from a Game Object using: `gameObject.on('dragleave', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + */ + const GAMEOBJECT_DRAG_LEAVE: any; + + /** + * The Game Object Drag Over Event. + * + * This event is dispatched by an interactive Game Object if a pointer drags it over a drag target. + * + * When the Game Object first enters the drag target it will emit a `dragenter` event. If it then moves while within + * the drag target, it will emit this event instead. + * + * Listen to this event from a Game Object using: `gameObject.on('dragover', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + */ + const GAMEOBJECT_DRAG_OVER: any; + + /** + * The Game Object Drag Start Event. + * + * This event is dispatched by an interactive Game Object if a pointer starts to drag it. + * + * Listen to this event from a Game Object using: `gameObject.on('dragstart', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * There are lots of useful drag related properties that are set within the Game Object when dragging occurs. + * For example, `gameObject.input.dragStartX`, `dragStartY` and so on. + */ + const GAMEOBJECT_DRAG_START: any; + + /** + * The Game Object Drop Event. + * + * This event is dispatched by an interactive Game Object if a pointer drops it on a Drag Target. + * + * Listen to this event from a Game Object using: `gameObject.on('drop', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive and enabled for drag. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + */ + const GAMEOBJECT_DROP: any; + + /** + * The Game Object Move Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved across _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectmove', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_MOVE: any; + + /** + * The Game Object Out Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectout', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_OUT: any; + + /** + * The Game Object Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectover', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_OVER: any; + + /** + * The Game Object Pointer Down Event. + * + * This event is dispatched by an interactive Game Object if a pointer is pressed down on it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerdown', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_POINTER_DOWN: any; + + /** + * The Game Object Pointer Move Event. + * + * This event is dispatched by an interactive Game Object if a pointer is moved while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointermove', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_POINTER_MOVE: any; + + /** + * The Game Object Pointer Out Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves out of it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerout', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_POINTER_OUT: any; + + /** + * The Game Object Pointer Over Event. + * + * This event is dispatched by an interactive Game Object if a pointer moves over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerover', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_POINTER_OVER: any; + + /** + * The Game Object Pointer Up Event. + * + * This event is dispatched by an interactive Game Object if a pointer is released while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('pointerup', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_POINTER_UP: any; + + /** + * The Game Object Pointer Wheel Event. + * + * This event is dispatched by an interactive Game Object if a pointer has its wheel moved while over it. + * + * Listen to this event from a Game Object using: `gameObject.on('wheel', listener)`. + * Note that the scope of the listener is automatically set to be the Game Object instance itself. + * + * To receive this event, the Game Object must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_POINTER_WHEEL: any; + + /** + * The Game Object Up Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released while over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectup', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_UP: any; + + /** + * The Game Object Wheel Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel moved while over _any_ interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('gameobjectwheel', listener)`. + * + * To receive this event, the Game Objects must have been set as interactive. + * See [GameObject.setInteractive]{@link Phaser.GameObjects.GameObject#setInteractive} for more details. + * + * To listen for this event from a _specific_ Game Object, use the [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} event instead. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const GAMEOBJECT_WHEEL: any; + + /** + * The Input Plugin Game Out Event. + * + * This event is dispatched by the Input Plugin if the active pointer leaves the game canvas and is now + * outside of it, elsewhere on the web page. + * + * Listen to this event from within a Scene using: `this.input.on('gameout', listener)`. + */ + const GAME_OUT: any; + + /** + * The Input Plugin Game Over Event. + * + * This event is dispatched by the Input Plugin if the active pointer enters the game canvas and is now + * over of it, having previously been elsewhere on the web page. + * + * Listen to this event from within a Scene using: `this.input.on('gameover', listener)`. + */ + const GAME_OVER: any; + + /** + * The Input Manager Boot Event. + * + * This internal event is dispatched by the Input Manager when it boots. + */ + const MANAGER_BOOT: any; + + /** + * 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. + */ + const MANAGER_PROCESS: any; + + /** + * The Input Manager Update Event. + * + * This internal event is dispatched by the Input Manager as part of its update step. + */ + const MANAGER_UPDATE: any; + + /** + * The Input Manager Pointer Lock Change Event. + * + * This event is dispatched by the Input Manager when it is processing a native Pointer Lock Change DOM Event. + */ + const POINTERLOCK_CHANGE: any; + + /** + * The Pointer Down Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointerdown', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_DOWN: any; + + /** + * The Pointer Down Outside Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is pressed down anywhere outside of the game canvas. + * + * Listen to this event from within a Scene using: `this.input.on('pointerdownoutside', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_DOWN} + * 2. [GAMEOBJECT_DOWN]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_DOWN} + * 3. [POINTER_DOWN]{@linkcode Phaser.Input.Events#event:POINTER_DOWN} or [POINTER_DOWN_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_DOWN_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_DOWN_OUTSIDE: any; + + /** + * The Pointer Move Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is moved anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointermove', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_MOVE} + * 2. [GAMEOBJECT_MOVE]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_MOVE} + * 3. [POINTER_MOVE]{@linkcode Phaser.Input.Events#event:POINTER_MOVE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_MOVE: any; + + /** + * The Pointer Out Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves out of any interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('pointerout', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OUT} + * 2. [GAMEOBJECT_OUT]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OUT} + * 3. [POINTER_OUT]{@linkcode Phaser.Input.Events#event:POINTER_OUT} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_OUT: any; + + /** + * The Pointer Over Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer moves over any interactive Game Object. + * + * Listen to this event from within a Scene using: `this.input.on('pointerover', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_OVER} + * 2. [GAMEOBJECT_OVER]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_OVER} + * 3. [POINTER_OVER]{@linkcode Phaser.Input.Events#event:POINTER_OVER} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_OVER: any; + + /** + * The Pointer Up Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere. + * + * Listen to this event from within a Scene using: `this.input.on('pointerup', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_UP: any; + + /** + * The Pointer Up Outside Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer is released anywhere outside of the game canvas. + * + * Listen to this event from within a Scene using: `this.input.on('pointerupoutside', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_UP} + * 2. [GAMEOBJECT_UP]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_UP} + * 3. [POINTER_UP]{@linkcode Phaser.Input.Events#event:POINTER_UP} or [POINTER_UP_OUTSIDE]{@linkcode Phaser.Input.Events#event:POINTER_UP_OUTSIDE} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_UP_OUTSIDE: any; + + /** + * The Pointer Wheel Input Event. + * + * This event is dispatched by the Input Plugin belonging to a Scene if a pointer has its wheel updated. + * + * Listen to this event from within a Scene using: `this.input.on('wheel', listener)`. + * + * The event hierarchy is as follows: + * + * 1. [GAMEOBJECT_POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_POINTER_WHEEL} + * 2. [GAMEOBJECT_WHEEL]{@linkcode Phaser.Input.Events#event:GAMEOBJECT_WHEEL} + * 3. [POINTER_WHEEL]{@linkcode Phaser.Input.Events#event:POINTER_WHEEL} + * + * With the top event being dispatched first and then flowing down the list. Note that higher-up event handlers can stop + * the propagation of this event. + */ + const POINTER_WHEEL: any; + + /** + * The Input Plugin Pre-Update Event. + * + * This internal event is dispatched by the Input Plugin at the start of its `preUpdate` method. + * This hook is designed specifically for input plugins, but can also be listened to from user-land code. + */ + const PRE_UPDATE: any; + + /** + * The Input Plugin Shutdown Event. + * + * This internal event is dispatched by the Input Plugin when it shuts down, signalling to all of its systems to shut themselves down. + */ + const SHUTDOWN: any; + + /** + * The Input Plugin Start Event. + * + * This internal event is dispatched by the Input Plugin when it has finished setting-up, + * signalling to all of its internal systems to start. + */ + const START: any; + + /** + * 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. + */ + const UPDATE: any; + + } + + namespace Gamepad { + /** + * Contains information about a specific Gamepad Axis. + * Axis objects are created automatically by the Gamepad as they are needed. + */ + class Axis { + /** + * + * @param pad A reference to the Gamepad that this Axis belongs to. + * @param index The index of this Axis. + */ + constructor(pad: Phaser.Input.Gamepad.Gamepad, index: integer); + + /** + * A reference to the Gamepad that this Axis belongs to. + */ + pad: Phaser.Input.Gamepad.Gamepad; + + /** + * An event emitter to use to emit the axis events. + */ + events: Phaser.Events.EventEmitter; + + /** + * The index of this Axis. + */ + index: integer; + + /** + * The raw axis value, between -1 and 1 with 0 being dead center. + * Use the method `getValue` to get a normalized value with the threshold applied. + */ + value: number; + + /** + * Movement tolerance threshold below which axis values are ignored in `getValue`. + */ + threshold: number; + + /** + * Applies the `threshold` value to the axis and returns it. + */ + getValue(): number; + + /** + * Destroys this Axis instance and releases external references it holds. + */ + destroy(): void; + + } + + /** + * Contains information about a specific button on a Gamepad. + * Button objects are created automatically by the Gamepad as they are needed. + */ + class Button { + /** + * + * @param pad A reference to the Gamepad that this Button belongs to. + * @param index The index of this Button. + */ + constructor(pad: Phaser.Input.Gamepad.Gamepad, index: integer); + + /** + * A reference to the Gamepad that this Button belongs to. + */ + pad: Phaser.Input.Gamepad.Gamepad; + + /** + * An event emitter to use to emit the button events. + */ + events: Phaser.Events.EventEmitter; + + /** + * The index of this Button. + */ + index: integer; + + /** + * Between 0 and 1. + */ + value: number; + + /** + * Can be set for analogue buttons to enable a 'pressure' threshold, + * before a button is considered as being 'pressed'. + */ + threshold: number; + + /** + * Is the Button being pressed down or not? + */ + pressed: boolean; + + /** + * Destroys this Button instance and releases external references it holds. + */ + destroy(): void; + + } + + namespace Configs { + /** + * Tatar SNES USB Controller Gamepad Configuration. + * USB Gamepad (STANDARD GAMEPAD Vendor: 0079 Product: 0011) + */ + var SNES_USB: object; + + /** + * PlayStation DualShock 4 Gamepad Configuration. + * Sony PlayStation DualShock 4 (v2) wireless controller + */ + var DUALSHOCK_4: object; + + /** + * XBox 360 Gamepad Configuration. + */ + var XBOX_360: object; + + } + + namespace Events { + /** + * The Gamepad Button Down Event. + * + * This event is dispatched by the Gamepad Plugin when a button has been pressed on any active Gamepad. + * + * Listen to this event from within a Scene using: `this.input.gamepad.on('down', listener)`. + * + * You can also listen for a DOWN event from a Gamepad instance. See the [GAMEPAD_BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_DOWN} event for details. + */ + const BUTTON_DOWN: any; + + /** + * The Gamepad Button Up Event. + * + * This event is dispatched by the Gamepad Plugin when a button has been released on any active Gamepad. + * + * Listen to this event from within a Scene using: `this.input.gamepad.on('up', listener)`. + * + * You can also listen for an UP event from a Gamepad instance. See the [GAMEPAD_BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:GAMEPAD_BUTTON_UP} event for details. + */ + const BUTTON_UP: any; + + /** + * The Gamepad Connected Event. + * + * This event is dispatched by the Gamepad Plugin when a Gamepad has been connected. + * + * Listen to this event from within a Scene using: `this.input.gamepad.once('connected', listener)`. + * + * 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. + */ + const CONNECTED: any; + + /** + * The Gamepad Disconnected Event. + * + * This event is dispatched by the Gamepad Plugin when a Gamepad has been disconnected. + * + * Listen to this event from within a Scene using: `this.input.gamepad.once('disconnected', listener)`. + */ + const DISCONNECTED: any; + + /** + * The Gamepad Button Down Event. + * + * This event is dispatched by a Gamepad instance when a button has been pressed on it. + * + * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: + * `this.input.gamepad.pad1.on('down', listener)`. + * + * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. + * + * You can also listen for a DOWN event from the Gamepad Plugin. See the [BUTTON_DOWN]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_DOWN} event for details. + */ + const GAMEPAD_BUTTON_DOWN: any; + + /** + * The Gamepad Button Up Event. + * + * This event is dispatched by a Gamepad instance when a button has been released on it. + * + * Listen to this event from a Gamepad instance. Once way to get this is from the `pad1`, `pad2`, etc properties on the Gamepad Plugin: + * `this.input.gamepad.pad1.on('up', listener)`. + * + * Note that you will not receive any Gamepad button events until the browser considers the Gamepad as being 'connected'. + * + * You can also listen for an UP event from the Gamepad Plugin. See the [BUTTON_UP]{@linkcode Phaser.Input.Gamepad.Events#event:BUTTON_UP} event for details. + */ + const GAMEPAD_BUTTON_UP: any; + + } + + /** + * A single Gamepad. + * + * These are created, updated and managed by the Gamepad Plugin. + */ + class Gamepad extends Phaser.Events.EventEmitter { + /** + * + * @param manager A reference to the Gamepad Plugin. + * @param pad The Gamepad object, as extracted from GamepadEvent. + */ + constructor(manager: Phaser.Input.Gamepad.GamepadPlugin, pad: Phaser.Types.Input.Gamepad.Pad); + + /** + * A reference to the Gamepad Plugin. + */ + manager: Phaser.Input.Gamepad.GamepadPlugin; + + /** + * A reference to the native Gamepad object that is connected to the browser. + */ + pad: any; + + /** + * A string containing some information about the controller. + * + * This is not strictly specified, but in Firefox it will contain three pieces of information + * separated by dashes (-): two 4-digit hexadecimal strings containing the USB vendor and + * product id of the controller, and the name of the controller as provided by the driver. + * In Chrome it will contain the name of the controller as provided by the driver, + * followed by vendor and product 4-digit hexadecimal strings. + */ + id: string; + + /** + * An integer that is unique for each Gamepad currently connected to the system. + * This can be used to distinguish multiple controllers. + * Note that disconnecting a device and then connecting a new device may reuse the previous index. + */ + index: number; + + /** + * An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad. + */ + buttons: Phaser.Input.Gamepad.Button[]; + + /** + * An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any. + */ + axes: Phaser.Input.Gamepad.Axis[]; + + /** + * The Gamepad's Haptic Actuator (Vibration / Rumble support). + * This is highly experimental and only set if both present on the device, + * and exposed by both the hardware and browser. + */ + vibration: GamepadHapticActuator; + + /** + * 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. + */ + leftStick: Phaser.Math.Vector2; + + /** + * 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. + */ + rightStick: Phaser.Math.Vector2; + + /** + * Gets the total number of axis this Gamepad claims to support. + */ + getAxisTotal(): integer; + + /** + * 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 0 and 1. + * @param index The index of the axes to get the value for. + */ + getAxisValue(index: integer): number; + + /** + * Sets the threshold value of all axis on this Gamepad. + * The value is a float between 0 and 1 and is the amount below which the axis is considered as not having been moved. + * @param value A value between 0 and 1. + */ + setAxisThreshold(value: number): void; + + /** + * Gets the total number of buttons this Gamepad claims to have. + */ + getButtonTotal(): integer; + + /** + * 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 an analogue button, or a float between 0 and 1 + * for a pressure-sensitive digital button, such as the shoulder buttons on a Dual Shock. + * @param index The index of the button to get the value for. + */ + getButtonValue(index: integer): number; + + /** + * Returns if the button is pressed down or not. + * The index must be valid within the range of buttons supported by this Gamepad. + * @param index The index of the button to get the value for. + */ + isButtonDown(index: integer): boolean; + + /** + * Destroys this Gamepad instance, its buttons and axes, and releases external references it holds. + */ + destroy(): void; + + /** + * Is this Gamepad currently connected or not? + */ + connected: boolean; + + /** + * A timestamp containing the most recent time this Gamepad was updated. + */ + timestamp: number; + + /** + * Is the Gamepad's Left button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad left button under standard Gamepad mapping. + */ + left: boolean; + + /** + * Is the Gamepad's Right button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad right button under standard Gamepad mapping. + */ + right: boolean; + + /** + * Is the Gamepad's Up button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad up button under standard Gamepad mapping. + */ + up: boolean; + + /** + * Is the Gamepad's Down button being pressed? + * If the Gamepad doesn't have this button it will always return false. + * This is the d-pad down button under standard Gamepad mapping. + */ + down: boolean; + + /** + * Is the Gamepad's bottom button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the X button. + * On an XBox controller it's the A button. + */ + A: boolean; + + /** + * Is the Gamepad's top button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Triangle button. + * On an XBox controller it's the Y button. + */ + Y: boolean; + + /** + * Is the Gamepad's left button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Square button. + * On an XBox controller it's the X button. + */ + X: boolean; + + /** + * Is the Gamepad's right button in the right button cluster being pressed? + * If the Gamepad doesn't have this button it will always return false. + * On a Dual Shock controller it's the Circle button. + * On an XBox controller it's the B button. + */ + B: boolean; + + /** + * Returns the value of the Gamepad's top left shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the L1 button. + * On an XBox controller it's the LB button. + */ + L1: number; + + /** + * Returns the value of the Gamepad's bottom left shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the L2 button. + * On an XBox controller it's the LT button. + */ + L2: number; + + /** + * Returns the value of the Gamepad's top right shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the R1 button. + * On an XBox controller it's the RB button. + */ + R1: number; + + /** + * Returns the value of the Gamepad's bottom right shoulder button. + * If the Gamepad doesn't have this button it will always return zero. + * The value is a float between 0 and 1, corresponding to how depressed the button is. + * On a Dual Shock controller it's the R2 button. + * On an XBox controller it's the RT button. + */ + R2: number; + + } + + /** + * 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. + * + * 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 { + /** + * + * @param sceneInputPlugin A reference to the Scene Input Plugin that the KeyboardPlugin belongs to. + */ + constructor(sceneInputPlugin: Phaser.Input.InputPlugin); + + /** + * A reference to the Scene that this Input Plugin is responsible for. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene Systems Settings. + */ + settings: Phaser.Types.Scenes.SettingsObject; + + /** + * A reference to the Scene Input Plugin that created this Keyboard Plugin. + */ + sceneInputPlugin: Phaser.Input.InputPlugin; + + /** + * A boolean that controls if the Gamepad Manager is enabled or not. + * Can be toggled on the fly. + */ + enabled: boolean; + + /** + * The Gamepad Event target, as defined in the Game Config. + * Typically the browser window, but can be any interactive DOM element. + */ + target: any; + + /** + * An array of the connected Gamepads. + */ + gamepads: Phaser.Input.Gamepad.Gamepad[]; + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + */ + isActive(): boolean; + + /** + * Disconnects all current Gamepads. + */ + disconnectAll(): void; + + /** + * Returns an array of all currently connected Gamepads. + */ + getAll(): Phaser.Input.Gamepad.Gamepad[]; + + /** + * Looks-up a single Gamepad based on the given index value. + * @param index The index of the Gamepad to get. + */ + getPad(index: number): Phaser.Input.Gamepad.Gamepad; + + /** + * The total number of connected game pads. + */ + total: integer; + + /** + * A reference to the first connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + */ + pad1: Phaser.Input.Gamepad.Gamepad; + + /** + * A reference to the second connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + */ + pad2: Phaser.Input.Gamepad.Gamepad; + + /** + * A reference to the third connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + */ + pad3: Phaser.Input.Gamepad.Gamepad; + + /** + * A reference to the fourth connected Gamepad. + * + * This will be undefined if either no pads are connected, or the browser + * has not yet issued a gamepadconnect, which can happen even if a Gamepad + * is plugged in, but hasn't yet had any buttons pressed on it. + */ + pad4: Phaser.Input.Gamepad.Gamepad; + + } + + } + + /** + * 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 { + /** + * + * @param game The Game instance that owns the Input Manager. + * @param config The Input Configuration object, as set in the Game Config. + */ + constructor(game: Phaser.Game, config: object); + + /** + * The Game instance that owns the Input Manager. + * A Game only maintains on instance of the Input Manager at any time. + */ + readonly game: Phaser.Game; + + /** + * A reference to the global Game Scale Manager. + * Used for all bounds checks and pointer scaling. + */ + scaleManager: Phaser.Scale.ScaleManager; + + /** + * The Canvas that is used for all DOM event input listeners. + */ + canvas: HTMLCanvasElement; + + /** + * The Game Configuration object, as set during the game boot. + */ + config: Phaser.Core.Config; + + /** + * If set, the Input Manager will run its update loop every frame. + */ + enabled: boolean; + + /** + * The Event Emitter instance that the Input Manager uses to emit events from. + */ + events: Phaser.Events.EventEmitter; + + /** + * Are any mouse or touch pointers currently over the game canvas? + * This is updated automatically by the canvas over and out handlers. + */ + readonly isOver: boolean; + + /** + * The default CSS cursor to be used when interacting with your game. + * + * See the `setDefaultCursor` method for more details. + */ + defaultCursor: string; + + /** + * A reference to the Keyboard Manager class, if enabled via the `input.keyboard` Game Config property. + */ + keyboard: Phaser.Input.Keyboard.KeyboardManager; + + /** + * A reference to the Mouse Manager class, if enabled via the `input.mouse` Game Config property. + */ + mouse: Phaser.Input.Mouse.MouseManager; + + /** + * A reference to the Touch Manager class, if enabled via the `input.touch` Game Config property. + */ + touch: Phaser.Input.Touch.TouchManager; + + /** + * An array of Pointers that have been added to the game. + * The first entry is reserved for the Mouse Pointer, the rest are Touch Pointers. + * + * By default there is 1 touch pointer enabled. If you need more use the `addPointer` method to start them, + * or set the `input.activePointers` property in the Game Config. + */ + pointers: Phaser.Input.Pointer[]; + + /** + * The number of touch objects activated and being processed each update. + * + * You can change this by either calling `addPointer` at run-time, or by + * setting the `input.activePointers` property in the Game Config. + */ + readonly pointersTotal: integer; + + /** + * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. + * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` + * which will always map to the most recently interacted pointer. + */ + mousePointer: Phaser.Input.Pointer; + + /** + * 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. + */ + activePointer: Phaser.Input.Pointer; + + /** + * If the top-most Scene in the Scene List receives an input it will stop input from + * propagating any lower down the scene list, i.e. if you have a UI Scene at the top + * and click something on it, that click will not then be passed down to any other + * Scene below. Disable this to have input events passed through all Scenes, all the time. + */ + globalTopOnly: boolean; + + /** + * The time this Input Manager was last updated. + * This value is populated by the Game Step each frame. + */ + readonly time: number; + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * The renderer is available by now. + */ + protected boot(): void; + + /** + * 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. + * @param cursor The CSS to be used when setting the default cursor. + */ + setDefaultCursor(cursor: string): void; + + /** + * Adds new Pointer objects to the Input Manager. + * + * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. + * + * You can create more either by calling this method, or by setting the `input.activePointers` property + * in the Game Config, up to a maximum of 10 pointers. + * + * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added + * via this method. + * @param quantity The number of new Pointers to create. A maximum of 10 is allowed in total. Default 1. + */ + addPointer(quantity?: integer): Phaser.Input.Pointer[]; + + /** + * Internal method that gets a list of all the active Input Plugins in the game + * and updates each of them in turn, in reverse order (top to bottom), to allow + * for DOM top-level event handling simulation. + * @param type The type of event to process. + * @param pointers An array of Pointers on which the event occurred. + */ + updateInputPlugins(type: integer, pointers: Phaser.Input.Pointer[]): void; + + /** + * Performs a hit test using the given Pointer and camera, against an array of interactive Game Objects. + * + * The Game Objects are culled against the camera, and then the coordinates are translated into the local camera space + * and used to determine if they fall within the remaining Game Objects hit areas or not. + * + * If nothing is matched an empty array is returned. + * + * This method is called automatically by InputPlugin.hitTestPointer and doesn't usually need to be invoked directly. + * @param pointer The Pointer to test against. + * @param gameObjects An array of interactive Game Objects to check. + * @param camera The Camera which is being tested against. + * @param output An array to store the results in. If not given, a new empty array is created. + */ + hitTest(pointer: Phaser.Input.Pointer, gameObjects: any[], camera: Phaser.Cameras.Scene2D.Camera, output?: any[]): any[]; + + /** + * Checks if the given x and y coordinate are within the hit area of the Game Object. + * + * This method assumes that the coordinate values have already been translated into the space of the Game Object. + * + * If the coordinates are within the hit area they are set into the Game Objects Input `localX` and `localY` properties. + * @param gameObject The interactive Game Object to check against. + * @param x The translated x coordinate for the hit test. + * @param y The translated y coordinate for the hit test. + */ + pointWithinHitArea(gameObject: Phaser.GameObjects.GameObject, x: number, y: number): boolean; + + /** + * Checks if the given x and y coordinate are within the hit area of the Interactive Object. + * + * This method assumes that the coordinate values have already been translated into the space of the Interactive Object. + * + * If the coordinates are within the hit area they are set into the Interactive Objects Input `localX` and `localY` properties. + * @param object The Interactive Object to check against. + * @param x The translated x coordinate for the hit test. + * @param y The translated y coordinate for the hit test. + */ + pointWithinInteractiveObject(object: Phaser.Types.Input.InteractiveObject, x: number, y: number): boolean; + + /** + * Transforms the pageX and pageY values of a Pointer into the scaled coordinate space of the Input Manager. + * @param pointer The Pointer to transform the values for. + * @param pageX The Page X value. + * @param pageY The Page Y value. + * @param wasMove Are we transforming the Pointer from a move event, or an up / down event? + */ + transformPointer(pointer: Phaser.Input.Pointer, pageX: number, pageY: number, wasMove: boolean): void; + + /** + * Destroys the Input Manager and all of its systems. + * + * There is no way to recover from doing this. + */ + destroy(): void; + + } + + /** + * The Input Plugin belongs to a Scene and handles all input related events and operations for it. + * + * You can access it from within a Scene using `this.input`. + * + * It emits events directly. For example, you can do: + * + * ```javascript + * this.input.on('pointerdown', callback, context); + * ``` + * + * To listen for a pointer down event anywhere on the game canvas. + * + * Game Objects can be enabled for input by calling their `setInteractive` method. After which they + * will directly emit input events: + * + * ```javascript + * var sprite = this.add.sprite(x, y, texture); + * sprite.setInteractive(); + * sprite.on('pointerdown', callback, context); + * ``` + * + * There are lots of game configuration options available relating to input. + * See the [Input Config object]{@linkcode Phaser.Types.Core.InputConfig} for more details, including how to deal with Phaser + * listening for input events outside of the canvas, how to set a default number of pointers, input + * capture settings and more. + * + * Please also see the Input examples and tutorials for further information. + */ + class InputPlugin extends Phaser.Events.EventEmitter { + /** + * + * @param scene A reference to the Scene that this Input Plugin is responsible for. + */ + constructor(scene: Phaser.Scene); + + /** + * An instance of the Gamepad Plugin class, if enabled via the `input.gamepad` Scene or Game Config property. + * Use this to create access Gamepads connected to the browser and respond to gamepad buttons. + */ + gamepad: Phaser.Input.Gamepad.GamepadPlugin; + + /** + * A reference to the Scene that this Input Plugin is responsible for. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene Systems class. + */ + systems: Phaser.Scenes.Systems; + + /** + * A reference to the Scene Systems Settings. + */ + settings: Phaser.Types.Scenes.SettingsObject; + + /** + * A reference to the Game Input Manager. + */ + manager: Phaser.Input.InputManager; + + /** + * If `true` this Input Plugin will process DOM input events. + */ + enabled: boolean; + + /** + * A reference to the Scene Display List. This property is set during the `boot` method. + */ + displayList: Phaser.GameObjects.DisplayList; + + /** + * A reference to the Scene Cameras Manager. This property is set during the `boot` method. + */ + cameras: Phaser.Cameras.Scene2D.CameraManager; + + /** + * A reference to the Mouse Manager. + * + * This property is only set if Mouse support has been enabled in your Game Configuration file. + * + * If you just wish to get access to the mouse pointer, use the `mousePointer` property instead. + */ + mouse: Phaser.Input.Mouse.MouseManager; + + /** + * When set to `true` (the default) the Input Plugin will emulate DOM behavior by only emitting events from + * the top-most Game Objects in the Display List. + * + * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. + */ + topOnly: boolean; + + /** + * How often should the Pointers be checked? + * + * The value is a time, given in ms, and is the time that must have elapsed between game steps before + * the Pointers will be polled again. When a pointer is polled it runs a hit test to see which Game + * Objects are currently below it, or being interacted with it. + * + * Pointers will *always* be checked if they have been moved by the user, or press or released. + * + * This property only controls how often they will be polled if they have not been updated. + * You should set this if you want to have Game Objects constantly check against the pointers, even + * if the pointer didn't itself move. + * + * Set to 0 to poll constantly. Set to -1 to only poll on user movement. + */ + pollRate: integer; + + /** + * The distance, in pixels, a pointer has to move while being held down, before it thinks it is being dragged. + */ + dragDistanceThreshold: number; + + /** + * The amount of time, in ms, a pointer has to be held down before it thinks it is dragging. + * + * The default polling rate is to poll only on move so once the time threshold is reached the + * drag event will not start until you move the mouse. If you want it to start immediately + * when the time threshold is reached, you must increase the polling rate by calling + * [setPollAlways]{@linkcode Phaser.Input.InputPlugin#setPollAlways} or + * [setPollRate]{@linkcode Phaser.Input.InputPlugin#setPollRate}. + */ + dragTimeThreshold: number; + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + */ + isActive(): boolean; + + /** + * This is called automatically by the Input Manager. + * It emits events for plugins to listen to and also handles polling updates, if enabled. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + updatePoll(time: number, delta: number): boolean; + + /** + * Clears a Game Object so it no longer has an Interactive Object associated with it. + * The Game Object is then queued for removal from the Input Plugin on the next update. + * @param gameObject The Game Object that will have its Interactive Object removed. + * @param skipQueue Skip adding this Game Object into the removal queue? Default false. + */ + clear(gameObject: Phaser.GameObjects.GameObject, skipQueue?: boolean): Phaser.GameObjects.GameObject; + + /** + * Disables Input on a single Game Object. + * + * An input disabled Game Object still retains its Interactive Object component and can be re-enabled + * at any time, by passing it to `InputPlugin.enable`. + * @param gameObject The Game Object to have its input system disabled. + */ + disable(gameObject: Phaser.GameObjects.GameObject): void; + + /** + * 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. + * @param gameObject The Game Object to be enabled for input. + * @param shape 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 callback The 'contains' function to invoke to check if the pointer is within the hit area. + * @param dropZone Is this Game Object a drop zone or not? Default false. + */ + enable(gameObject: Phaser.GameObjects.GameObject, shape?: Phaser.Types.Input.InputConfiguration | any, callback?: Phaser.Types.Input.HitAreaCallback, dropZone?: boolean): Phaser.Input.InputPlugin; + + /** + * Takes the given Pointer and performs a hit test against it, to see which interactive Game Objects + * it is currently above. + * + * The hit test is performed against which-ever Camera the Pointer is over. If it is over multiple + * cameras, it starts checking the camera at the top of the camera list, and if nothing is found, iterates down the list. + * @param pointer The Pointer to check against the Game Objects. + */ + hitTestPointer(pointer: Phaser.Input.Pointer): Phaser.GameObjects.GameObject[]; + + /** + * Returns the drag state of the given Pointer for this Input Plugin. + * + * The state will be one of the following: + * + * 0 = Not dragging anything + * 1 = Primary button down and objects below, so collect a draglist + * 2 = Pointer being checked if meets drag criteria + * 3 = Pointer meets criteria, notify the draglist + * 4 = Pointer actively dragging the draglist and has moved + * 5 = Pointer actively dragging but has been released, notify draglist + * @param pointer The Pointer to get the drag state for. + */ + getDragState(pointer: Phaser.Input.Pointer): integer; + + /** + * Sets the drag state of the given Pointer for this Input Plugin. + * + * The state must be one of the following values: + * + * 0 = Not dragging anything + * 1 = Primary button down and objects below, so collect a draglist + * 2 = Pointer being checked if meets drag criteria + * 3 = Pointer meets criteria, notify the draglist + * 4 = Pointer actively dragging the draglist and has moved + * 5 = Pointer actively dragging but has been released, notify draglist + * @param pointer The Pointer to set the drag state for. + * @param state The drag state value. An integer between 0 and 5. + */ + setDragState(pointer: Phaser.Input.Pointer, state: integer): void; + + /** + * Sets the draggable state of the given array of Game Objects. + * + * They can either be set to be draggable, or can have their draggable state removed by passing `false`. + * + * A Game Object will not fire drag events unless it has been specifically enabled for drag. + * @param gameObjects An array of Game Objects to change the draggable state on. + * @param value Set to `true` if the Game Objects should be made draggable, `false` if they should be unset. Default true. + */ + setDraggable(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], value?: boolean): Phaser.Input.InputPlugin; + + /** + * Creates a function that can be passed to `setInteractive`, `enable` or `setHitArea` that will handle + * pixel-perfect input detection on an Image or Sprite based Game Object, or any custom class that extends them. + * + * The following will create a sprite that is clickable on any pixel that has an alpha value >= 1. + * + * ```javascript + * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect()); + * ``` + * + * The following will create a sprite that is clickable on any pixel that has an alpha value >= 150. + * + * ```javascript + * this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect(150)); + * ``` + * + * Once you have made an Interactive Object pixel perfect it impacts all input related events for it: down, up, + * dragstart, drag, etc. + * + * As a pointer interacts with the Game Object it will constantly poll the texture, extracting a single pixel from + * the given coordinates and checking its color values. This is an expensive process, so should only be enabled on + * Game Objects that really need it. + * + * You cannot make non-texture based Game Objects pixel perfect. So this will not work on Graphics, BitmapText, + * Render Textures, Text, Tilemaps, Containers or Particles. + * @param alphaTolerance The alpha level that the pixel should be above to be included as a successful interaction. Default 1. + */ + makePixelPerfect(alphaTolerance?: integer): Function; + + /** + * 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`. + * @param gameObjects An array of Game Objects to set the hit area on. + * @param shape 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 callback The 'contains' function to invoke to check if the pointer is within the hit area. + */ + setHitArea(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], shape?: Phaser.Types.Input.InputConfiguration | any, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Circle` shape, using + * the given coordinates and radius to control its position and size. + * @param gameObjects An array of Game Objects to set as having a circle hit area. + * @param x The center of the circle. + * @param y The center of the circle. + * @param radius The radius of the circle. + * @param callback The hit area callback. If undefined it uses Circle.Contains. + */ + setHitAreaCircle(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x: number, y: number, radius: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Ellipse` shape, using + * the given coordinates and dimensions to control its position and size. + * @param gameObjects An array of Game Objects to set as having an ellipse hit area. + * @param x The center of the ellipse. + * @param y The center of the ellipse. + * @param width The width of the ellipse. + * @param height The height of the ellipse. + * @param callback The hit area callback. If undefined it uses Ellipse.Contains. + */ + setHitAreaEllipse(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x: number, y: number, width: number, height: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; + + /** + * 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. + * @param gameObjects An array of Game Objects to set as having an ellipse hit area. + * @param callback The hit area callback. If undefined it uses Rectangle.Contains. + */ + setHitAreaFromTexture(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Rectangle` shape, using + * the given coordinates and dimensions to control its position and size. + * @param gameObjects An array of Game Objects to set as having a rectangular hit area. + * @param x The top-left of the rectangle. + * @param y The top-left of the rectangle. + * @param width The width of the rectangle. + * @param height The height of the rectangle. + * @param callback The hit area callback. If undefined it uses Rectangle.Contains. + */ + setHitAreaRectangle(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x: number, y: number, width: number, height: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; + + /** + * Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Triangle` shape, using + * the given coordinates to control the position of its points. + * @param gameObjects An array of Game Objects to set as having a triangular hit area. + * @param x1 The x coordinate of the first point of the triangle. + * @param y1 The y coordinate of the first point of the triangle. + * @param x2 The x coordinate of the second point of the triangle. + * @param y2 The y coordinate of the second point of the triangle. + * @param x3 The x coordinate of the third point of the triangle. + * @param y3 The y coordinate of the third point of the triangle. + * @param callback The hit area callback. If undefined it uses Triangle.Contains. + */ + setHitAreaTriangle(gameObjects: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[], x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, callback?: Phaser.Types.Input.HitAreaCallback): Phaser.Input.InputPlugin; + + /** + * Creates an Input Debug Shape for the given Game Object. + * + * The Game Object must have _already_ been enabled for input prior to calling this method. + * + * This is intended to assist you during development and debugging. + * + * Debug Shapes can only be created for Game Objects that are using standard Phaser Geometry for input, + * including: Circle, Ellipse, Line, Polygon, Rectangle and Triangle. + * + * Game Objects that are using their automatic hit areas are using Rectangles by default, so will also work. + * + * The Debug Shape is created and added to the display list and is then kept in sync with the Game Object + * it is connected with. Should you need to modify it yourself, such as to hide it, you can access it via + * the Game Object property: `GameObject.input.hitAreaDebug`. + * + * Calling this method on a Game Object that already has a Debug Shape will first destroy the old shape, + * before creating a new one. If you wish to remove the Debug Shape entirely, you should call the + * method `InputPlugin.removeDebug`. + * + * Note that the debug shape will only show the outline of the input area. If the input test is using a + * pixel perfect check, for example, then this is not displayed. If you are using a custom shape, that + * doesn't extend one of the base Phaser Geometry objects, as your hit area, then this method will not + * work. + * @param gameObject The Game Object to create the input debug shape for. + * @param color The outline color of the debug shape. Default 0x00ff00. + */ + enableDebug(gameObject: Phaser.GameObjects.GameObject, color?: number): Phaser.Input.InputPlugin; + + /** + * Removes an Input Debug Shape from the given Game Object. + * + * The shape is destroyed immediately and the `hitAreaDebug` property is set to `null`. + * @param gameObject The Game Object to remove the input debug shape from. + */ + removeDebug(gameObject: Phaser.GameObjects.GameObject): Phaser.Input.InputPlugin; + + /** + * Sets the Pointers to always poll. + * + * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, + * or being interacted with it, regardless if the Pointer has actually moved or not. + * + * You should enable this if you want objects in your game to fire over / out events, and the objects + * are constantly moving, but the pointer may not have. Polling every frame has additional computation + * costs, especially if there are a large number of interactive objects in your game. + */ + setPollAlways(): Phaser.Input.InputPlugin; + + /** + * Sets the Pointers to only poll when they are moved or updated. + * + * When a pointer is polled it runs a hit test to see which Game Objects are currently below it, + * or being interacted with it. + */ + setPollOnMove(): Phaser.Input.InputPlugin; + + /** + * Sets the poll rate value. This is the amount of time that should have elapsed before a pointer + * will be polled again. See the `setPollAlways` and `setPollOnMove` methods. + * @param value The amount of time, in ms, that should elapsed before re-polling the pointers. + */ + setPollRate(value: number): Phaser.Input.InputPlugin; + + /** + * When set to `true` the global Input Manager will emulate DOM behavior by only emitting events from + * the top-most Scene in the Scene List. By default, if a Scene receives an input event it will then stop the event + * from flowing down to any Scenes below it in the Scene list. To disable this behavior call this method with `false`. + * @param value Set to `true` to stop processing input events on the Scene that receives it, or `false` to let the event continue down the Scene list. + */ + setGlobalTopOnly(value: boolean): Phaser.Input.InputPlugin; + + /** + * When set to `true` this Input Plugin will emulate DOM behavior by only emitting events from + * the top-most Game Objects in the Display List. + * + * If set to `false` it will emit events from all Game Objects below a Pointer, not just the top one. + * @param value `true` to only include the top-most Game Object, or `false` to include all Game Objects in a hit test. + */ + setTopOnly(value: boolean): Phaser.Input.InputPlugin; + + /** + * Given an array of Game Objects, sort the array and return it, so that the objects are in depth index order + * with the lowest at the bottom. + * @param gameObjects An array of Game Objects to be sorted. + */ + sortGameObjects(gameObjects: Phaser.GameObjects.GameObject[]): Phaser.GameObjects.GameObject[]; + + /** + * This method should be called from within an input event handler, such as `pointerdown`. + * + * When called, it stops the Input Manager from allowing _this specific event_ to be processed by any other Scene + * not yet handled in the scene list. + */ + stopPropagation(): Phaser.Input.InputPlugin; + + /** + * Adds new Pointer objects to the Input Manager. + * + * By default Phaser creates 2 pointer objects: `mousePointer` and `pointer1`. + * + * You can create more either by calling this method, or by setting the `input.activePointers` property + * in the Game Config, up to a maximum of 10 pointers. + * + * The first 10 pointers are available via the `InputPlugin.pointerX` properties, once they have been added + * via this method. + * @param quantity The number of new Pointers to create. A maximum of 10 is allowed in total. Default 1. + */ + addPointer(quantity?: integer): Phaser.Input.Pointer[]; + + /** + * 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. + * @param cursor The CSS to be used when setting the default cursor. + */ + setDefaultCursor(cursor: string): Phaser.Input.InputPlugin; + + /** + * The x coordinates 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. + */ + readonly x: number; + + /** + * The y coordinates 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. + */ + readonly y: number; + + /** + * Are any mouse or touch pointers currently over the game canvas? + */ + readonly isOver: boolean; + + /** + * The mouse has its own unique Pointer object, which you can reference directly if making a _desktop specific game_. + * If you are supporting both desktop and touch devices then do not use this property, instead use `activePointer` + * which will always map to the most recently interacted pointer. + */ + readonly mousePointer: Phaser.Input.Pointer; + + /** + * The current active input Pointer. + */ + readonly activePointer: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer1: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer2: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer3: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer4: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer5: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer6: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer7: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer8: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer9: Phaser.Input.Pointer; + + /** + * A touch-based Pointer object. + * This will be `undefined` by default unless you add a new Pointer using `addPointer`. + */ + readonly pointer10: Phaser.Input.Pointer; + + /** + * An instance of the Keyboard Plugin class, if enabled via the `input.keyboard` Scene or Game Config property. + * Use this to create Key objects and listen for keyboard specific events. + */ + keyboard: Phaser.Input.Keyboard.KeyboardPlugin; + + } + + namespace InputPluginCache { + /** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * @param key A reference used to get this plugin from the plugin cache. + * @param plugin The plugin to be stored. Should be the core object, not instantiated. + * @param mapping If this plugin is to be injected into the Input Plugin, this is the property key used. + * @param settingsKey The key in the Scene Settings to check to see if this plugin should install or not. + * @param configKey The key in the Game Config to check to see if this plugin should install or not. + */ + function register(key: string, plugin: Function, mapping: string, settingsKey: string, configKey: string): void; + + /** + * Returns the input plugin object from the cache based on the given key. + * @param key The key of the input plugin to get. + */ + function getCore(key: string): Phaser.Types.Input.InputPluginContainer; + + /** + * Installs all of the registered Input Plugins into the given target. + * @param target The target InputPlugin to install the plugins into. + */ + function install(target: Phaser.Input.InputPlugin): void; + + /** + * Removes an input plugin based on the given key. + * @param key The key of the input plugin to remove. + */ + function remove(key: string): void; + + } + + namespace Keyboard { + /** + * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them + * it will emit a `keycombomatch` event from the Keyboard Manager. + * + * The keys to be listened for can be defined as: + * + * A string (i.e. 'ATARI') + * An array of either integers (key codes) or strings, or a mixture of both + * An array of objects (such as Key objects) with a public 'keyCode' property + * + * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) + * you could pass the following array of key codes: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * Or, to listen for the user entering the word PHASER: + * + * ```javascript + * this.input.keyboard.createCombo('PHASER'); + * ``` + */ + class KeyCombo { + /** + * + * @param keyboardPlugin A reference to the Keyboard Plugin. + * @param keys The keys that comprise this combo. + * @param config A Key Combo configuration object. + */ + constructor(keyboardPlugin: Phaser.Input.Keyboard.KeyboardPlugin, keys: string | integer[] | object[], config?: Phaser.Types.Input.Keyboard.KeyComboConfig); + + /** + * A reference to the Keyboard Manager + */ + manager: Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * A flag that controls if this Key Combo is actively processing keys or not. + */ + enabled: boolean; + + /** + * An array of the keycodes that comprise this combo. + */ + keyCodes: any[]; + + /** + * The current keyCode the combo is waiting for. + */ + current: integer; + + /** + * The current index of the key being waited for in the 'keys' string. + */ + index: integer; + + /** + * The length of this combo (in keycodes) + */ + size: number; + + /** + * The time the previous key in the combo was matched. + */ + timeLastMatched: number; + + /** + * Has this Key Combo been matched yet? + */ + matched: boolean; + + /** + * The time the entire combo was matched. + */ + timeMatched: number; + + /** + * If they press the wrong key do we reset the combo? + */ + resetOnWrongKey: boolean; + + /** + * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. + */ + maxKeyDelay: integer; + + /** + * If previously matched and they press the first key of the combo again, will it reset? + */ + resetOnMatch: boolean; + + /** + * If the combo matches, will it delete itself? + */ + deleteOnMatch: boolean; + + /** + * How far complete is this combo? A value between 0 and 1. + */ + readonly progress: number; + + /** + * Destroys this Key Combo and all of its references. + */ + destroy(): void; + + } + + namespace Events { + /** + * 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. + */ + const ANY_KEY_DOWN: any; + + /** + * The Global Key Up Event. + * + * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. + * + * Listen to this event from within a Scene using: `this.input.keyboard.on('keyup', listener)`. + * + * You can also listen for a specific key being released. See [Keyboard.Events.KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:KEY_UP} for details. + * + * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. + */ + const ANY_KEY_UP: any; + + /** + * The Key Combo Match Event. + * + * This event is dispatched by the Keyboard Plugin when a [Key Combo]{@link Phaser.Input.Keyboard.KeyCombo} is matched. + * + * Listen for this event from the Key Plugin after a combo has been created: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + */ + const COMBO_MATCH: any; + + /** + * The Key Down Event. + * + * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is pressed. + * + * Listen for this event from the Key object instance directly: + * + * ```javascript + * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); + * + * spaceBar.on('down', 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. + */ + const DOWN: any; + + /** + * 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. + */ + const KEY_DOWN: any; + + /** + * The Key Up Event. + * + * This event is dispatched by the Keyboard Plugin when any key on the keyboard is released. + * + * Unlike the `ANY_KEY_UP` event, this one has a special dynamic event name. For example, to listen for the `A` key being released + * use the following from within a Scene: `this.input.keyboard.on('keyup-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('keyup-SPACE', listener)`. + * + * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. + * + * Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.UP]{@linkcode Phaser.Input.Keyboard.Events#event:UP} for details. + */ + const KEY_UP: any; + + /** + * The Key Up Event. + * + * This event is dispatched by a [Key]{@link Phaser.Input.Keyboard.Key} object when it is released. + * + * Listen for this event from the Key object instance directly: + * + * ```javascript + * var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); + * + * spaceBar.on('up', listener) + * ``` + * + * You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_UP]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_UP} for details. + */ + const UP: any; + + } + + /** + * The Keyboard Manager is a helper class that belongs to the global Input Manager. + * + * Its role is to listen for native DOM Keyboard Events and then store them for further processing by the Keyboard Plugin. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically if keyboard + * input has been enabled in the Game Config. + */ + class KeyboardManager { + /** + * + * @param inputManager A reference to the Input Manager. + */ + constructor(inputManager: Phaser.Input.InputManager); + + /** + * A reference to the Input Manager. + */ + manager: Phaser.Input.InputManager; + + /** + * A flag that controls if the non-modified keys, matching those stored in the `captures` array, + * have `preventDefault` called on them or not. + * + * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are + * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). + * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. + * However, if the user presses just the r key on its own, it will have its event prevented. + * + * If you wish to stop capturing the keys, for example switching out to a DOM based element, then + * you can toggle this property at run-time. + */ + preventDefault: boolean; + + /** + * An array of Key Code values that will automatically have `preventDefault` called on them, + * as long as the `KeyboardManager.preventDefault` boolean is set to `true`. + * + * By default the array is empty. + * + * The key must be non-modified when pressed in order to be captured. + * + * A non-modified key is one that doesn't have a modifier key held down with it. The modifier keys are + * shift, control, alt and the meta key (Command on a Mac, the Windows Key on Windows). + * Therefore, if the user presses shift + r, it won't prevent this combination, because of the modifier. + * However, if the user presses just the r key on its own, it will have its event prevented. + * + * If you wish to stop capturing the keys, for example switching out to a DOM based element, then + * you can toggle the `KeyboardManager.preventDefault` boolean at run-time. + * + * If you need more specific control, you can create Key objects and set the flag on each of those instead. + * + * This array can be populated via the Game Config by setting the `input.keyboard.capture` array, or you + * can call the `addCapture` method. See also `removeCapture` and `clearCaptures`. + */ + captures: integer[]; + + /** + * A boolean that controls if the Keyboard Manager is enabled or not. + * Can be toggled on the fly. + */ + enabled: boolean; + + /** + * The Keyboard Event target, as defined in the Game Config. + * Typically the window in which the game is rendering, but can be any interactive DOM element. + */ + target: any; + + /** + * The Key Down Event handler. + * This function is sent the native DOM KeyEvent. + * Initially empty and bound in the `startListeners` method. + */ + onKeyDown: Function; + + /** + * The Key Up Event handler. + * This function is sent the native DOM KeyEvent. + * Initially empty and bound in the `startListeners` method. + */ + onKeyUp: Function; + + /** + * Starts the Keyboard Event listeners running. + * This is called automatically and does not need to be manually invoked. + */ + startListeners(): void; + + /** + * Stops the Key Event listeners. + * This is called automatically and does not need to be manually invoked. + */ + stopListeners(): void; + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * This `addCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent + * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. + * + * You can pass in a single key code value, or an array of key codes, or a string: + * + * ```javascript + * this.input.keyboard.addCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.addCapture([ 62, 63, 64 ]); + * ``` + * + * Or a string: + * + * ```javascript + * this.input.keyboard.addCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * If there are active captures after calling this method, the `preventDefault` property is set to `true`. + * @param keycode The Key Codes to enable capture for, preventing them reaching the browser. + */ + addCapture(keycode: string | integer | integer[] | any[]): void; + + /** + * Removes an existing key capture. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove + * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. + * + * You can pass in a single key code value, or an array of key codes, or a string: + * + * ```javascript + * this.input.keyboard.removeCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.removeCapture([ 62, 63, 64 ]); + * ``` + * + * Or a string: + * + * ```javascript + * this.input.keyboard.removeCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * + * If there are no captures left after calling this method, the `preventDefault` property is set to `false`. + * @param keycode The Key Codes to disable capture for, allowing them reaching the browser again. + */ + removeCapture(keycode: string | integer | integer[] | any[]): void; + + /** + * Removes all keyboard captures and sets the `preventDefault` property to `false`. + */ + clearCaptures(): void; + + /** + * Destroys this Keyboard Manager instance. + */ + destroy(): void; + + } + + /** + * 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. + * + * 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 { + /** + * + * @param sceneInputPlugin A reference to the Scene Input Plugin that the KeyboardPlugin belongs to. + */ + constructor(sceneInputPlugin: Phaser.Input.InputPlugin); + + /** + * A reference to the core game, so we can listen for visibility events. + */ + game: Phaser.Game; + + /** + * A reference to the Scene that this Input Plugin is responsible for. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene Systems Settings. + */ + settings: Phaser.Types.Scenes.SettingsObject; + + /** + * A reference to the Scene Input Plugin that created this Keyboard Plugin. + */ + sceneInputPlugin: Phaser.Input.InputPlugin; + + /** + * A reference to the global Keyboard Manager. + */ + manager: Phaser.Input.InputPlugin; + + /** + * A boolean that controls if this Keyboard Plugin is enabled or not. + * Can be toggled on the fly. + */ + enabled: boolean; + + /** + * An array of Key objects to process. + */ + keys: Phaser.Input.Keyboard.Key[]; + + /** + * An array of KeyCombo objects to process. + */ + combos: Phaser.Input.Keyboard.KeyCombo[]; + + /** + * Checks to see if both this plugin and the Scene to which it belongs is active. + */ + isActive(): boolean; + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * This `addCapture` method enables consuming keyboard events for specific keys, so they don't bubble up the browser + * and cause the default behaviors. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to say prevent + * the SPACE BAR from triggering a page scroll, then it will prevent it for any Scene in your game, not just the calling one. + * + * You can pass a single key code value: + * + * ```javascript + * this.input.keyboard.addCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.addCapture([ 62, 63, 64 ]); + * ``` + * + * Or, a comma-delimited string: + * + * ```javascript + * this.input.keyboard.addCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * @param keycode The Key Codes to enable event capture for. + */ + addCapture(keycode: string | integer | integer[] | any[]): Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * Removes an existing key capture. + * + * Please note that keyboard captures are global. This means that if you call this method from within a Scene, to remove + * the capture of a key, then it will remove it for any Scene in your game, not just the calling one. + * + * You can pass a single key code value: + * + * ```javascript + * this.input.keyboard.removeCapture(62); + * ``` + * + * An array of key codes: + * + * ```javascript + * this.input.keyboard.removeCapture([ 62, 63, 64 ]); + * ``` + * + * Or, a comma-delimited string: + * + * ```javascript + * this.input.keyboard.removeCapture('W,S,A,D'); + * ``` + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * + * You can also provide an array mixing both strings and key code integers. + * @param keycode The Key Codes to disable event capture for. + */ + removeCapture(keycode: string | integer | integer[] | any[]): Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * Returns an array that contains all of the keyboard captures currently enabled. + */ + getCaptures(): integer[]; + + /** + * Allows Phaser to prevent any key captures you may have defined from bubbling up the browser. + * You can use this to re-enable event capturing if you had paused it via `disableGlobalCapture`. + */ + enableGlobalCapture(): Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * Disables Phaser from preventing any key captures you may have defined, without actually removing them. + * You can use this to temporarily disable event capturing if, for example, you swap to a DOM element. + */ + disableGlobalCapture(): Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * Removes all keyboard captures. + * + * Note that this is a global change. It will clear all event captures across your game, not just for this specific Scene. + */ + clearCaptures(): Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right, and also Space Bar and shift. + */ + createCursorKeys(): Phaser.Types.Input.Keyboard.CursorKeys; + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example: + * + * ```javascript + * this.input.keyboard.addKeys({ 'up': Phaser.Input.Keyboard.KeyCodes.W, 'down': Phaser.Input.Keyboard.KeyCodes.S }); + * ``` + * + * would return an object containing the properties (`up` and `down`) mapped to W and S {@link Phaser.Input.Keyboard.Key} objects. + * + * You can also pass in a comma-separated string: + * + * ```javascript + * this.input.keyboard.addKeys('W,S,A,D'); + * ``` + * + * Which will return an object with the properties W, S, A and D mapped to the relevant Key objects. + * + * To use non-alpha numeric keys, use a string, such as 'UP', 'SPACE' or 'LEFT'. + * @param keys An object containing Key Codes, or a comma-separated string. + * @param enableCapture Automatically call `preventDefault` on the native DOM browser event for the key codes being added. Default true. + * @param emitOnRepeat Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). Default false. + */ + addKeys(keys: object | string, enableCapture?: boolean, emitOnRepeat?: boolean): object; + + /** + * Adds a Key object to this Keyboard Plugin. + * + * The given argument can be either an existing Key object, a string, such as `A` or `SPACE`, or a key code value. + * + * If a Key object is given, and one already exists matching the same key code, the existing one is replaced with the new one. + * @param key Either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param enableCapture Automatically call `preventDefault` on the native DOM browser event for the key codes being added. Default true. + * @param emitOnRepeat Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default). Default false. + */ + addKey(key: Phaser.Input.Keyboard.Key | string | integer, enableCapture?: boolean, emitOnRepeat?: boolean): Phaser.Input.Keyboard.Key; + + /** + * Removes a Key object from this Keyboard Plugin. + * + * The given argument can be either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param key Either a Key object, a string, such as `A` or `SPACE`, or a key code value. + * @param destroy Call `Key.destroy` on the removed Key object? Default false. + */ + removeKey(key: Phaser.Input.Keyboard.Key | string | integer, destroy?: boolean): Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * Creates a new KeyCombo. + * + * A KeyCombo will listen for a specific string of keys from the Keyboard, and when it receives them + * it will emit a `keycombomatch` event from this Keyboard Plugin. + * + * The keys to be listened for can be defined as: + * + * A string (i.e. 'ATARI') + * An array of either integers (key codes) or strings, or a mixture of both + * An array of objects (such as Key objects) with a public 'keyCode' property + * + * For example, to listen for the Konami code (up, up, down, down, left, right, left, right, b, a, enter) + * you could pass the following array of key codes: + * + * ```javascript + * this.input.keyboard.createCombo([ 38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13 ], { resetOnMatch: true }); + * + * this.input.keyboard.on('keycombomatch', function (event) { + * console.log('Konami Code entered!'); + * }); + * ``` + * + * Or, to listen for the user entering the word PHASER: + * + * ```javascript + * this.input.keyboard.createCombo('PHASER'); + * ``` + * @param keys The keys that comprise this combo. + * @param config A Key Combo configuration object. + */ + createCombo(keys: string | integer[] | object[], config?: Phaser.Types.Input.Keyboard.KeyComboConfig): Phaser.Input.Keyboard.KeyCombo; + + /** + * Checks if the given Key object is currently being held down. + * + * The difference between this method and checking the `Key.isDown` property directly is that you can provide + * a duration to this method. For example, if you wanted a key press to fire a bullet, but you only wanted + * it to be able to fire every 100ms, then you can call this method with a `duration` of 100 and it + * will only return `true` every 100ms. + * + * If the Keyboard Plugin has been disabled, this method will always return `false`. + * @param key A Key object. + * @param duration The duration which must have elapsed before this Key is considered as being down. Default 0. + */ + checkDown(key: Phaser.Input.Keyboard.Key, duration?: number): boolean; + + /** + * Resets all Key objects created by _this_ Keyboard Plugin back to their default un-pressed states. + * This can only reset keys created via the `addKey`, `addKeys` or `createCursorKeys` methods. + * If you have created a Key object directly you'll need to reset it yourself. + * + * This method is called automatically when the Keyboard Plugin shuts down, but can be + * invoked directly at any time you require. + */ + resetKeys(): Phaser.Input.Keyboard.KeyboardPlugin; + + } + + /** + * 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. + * @param key The Key object to test. + * @param duration The duration, in ms, within which the key must have been pressed down. Default 50. + */ + function DownDuration(key: Phaser.Input.Keyboard.Key, duration?: integer): boolean; + + /** + * The justDown value allows you to test if this Key has just been pressed down or not. + * + * When you check this value it will return `true` if the Key is down, otherwise `false`. + * + * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. + * This allows you to use it in situations where you want to check if this key is down without using an event, such as in a core game loop. + * @param key The Key to check to see if it's just down or not. + */ + function JustDown(key: Phaser.Input.Keyboard.Key): boolean; + + /** + * The justUp value allows you to test if this Key has just been released or not. + * + * When you check this value it will return `true` if the Key is up, otherwise `false`. + * + * You can only call JustUp once per key release. It will only return `true` once, until the Key is pressed down and released again. + * This allows you to use it in situations where you want to check if this key is up without using an event, such as in a core game loop. + * @param key The Key to check to see if it's just up or not. + */ + function JustUp(key: Phaser.Input.Keyboard.Key): boolean; + + /** + * A generic Key object which can be passed to the Process functions (and so on) + * keycode must be an integer + */ + class Key extends Phaser.Events.EventEmitter { + /** + * + * @param plugin The Keyboard Plugin instance that owns this Key object. + * @param keyCode The keycode of this key. + */ + constructor(plugin: Phaser.Input.Keyboard.KeyboardPlugin, keyCode: integer); + + /** + * The Keyboard Plugin instance that owns this Key object. + */ + plugin: Phaser.Input.Keyboard.KeyboardPlugin; + + /** + * The keycode of this key. + */ + keyCode: integer; + + /** + * The original DOM event. + */ + originalEvent: KeyboardEvent; + + /** + * Can this Key be processed? + */ + enabled: boolean; + + /** + * The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + */ + isDown: boolean; + + /** + * The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + */ + isUp: boolean; + + /** + * The down state of the ALT key, if pressed at the same time as this key. + */ + altKey: boolean; + + /** + * The down state of the CTRL key, if pressed at the same time as this key. + */ + ctrlKey: boolean; + + /** + * The down state of the SHIFT key, if pressed at the same time as this key. + */ + shiftKey: boolean; + + /** + * The down state of the Meta key, if pressed at the same time as this key. + * On a Mac the Meta Key is the Command key. On Windows keyboards, it's the Windows key. + */ + metaKey: boolean; + + /** + * The location of the modifier key. 0 for standard (or unknown), 1 for left, 2 for right, 3 for numpad. + */ + location: number; + + /** + * The timestamp when the key was last pressed down. + */ + timeDown: number; + + /** + * The number of milliseconds this key was held down for in the previous down - up sequence. + * This value isn't updated every game step, only when the Key changes state. + * To get the current duration use the `getDuration` method. + */ + duration: number; + + /** + * The timestamp when the key was last released. + */ + timeUp: number; + + /** + * When a key is held down should it continuously fire the `down` event each time it repeats? + * + * By default it will emit the `down` event just once, but if you wish to receive the event + * for each repeat as well, enable this property. + */ + emitOnRepeat: boolean; + + /** + * If a key is held down this holds down the number of times the key has 'repeated'. + */ + repeats: number; + + /** + * Controls if this Key will continuously emit a `down` event while being held down (true), + * or emit the event just once, on first press, and then skip future events (false). + * @param value Emit `down` events on repeated key down actions, or just once? + */ + setEmitOnRepeat(value: boolean): Phaser.Input.Keyboard.Key; + + /** + * Processes the Key Down action for this Key. + * Called automatically by the Keyboard Plugin. + * @param event The native DOM Keyboard event. + */ + onDown(event: KeyboardEvent): void; + + /** + * Processes the Key Up action for this Key. + * Called automatically by the Keyboard Plugin. + * @param event The native DOM Keyboard event. + */ + onUp(event: KeyboardEvent): void; + + /** + * Resets this Key object back to its default un-pressed state. + */ + reset(): Phaser.Input.Keyboard.Key; + + /** + * Returns the duration, in ms, that the Key has been held down for. + * + * If the key is not currently down it will return zero. + * + * The get the duration the Key was held down for in the previous up-down cycle, + * use the `Key.duration` property value instead. + */ + getDuration(): number; + + /** + * Removes any bound event handlers and removes local references. + */ + destroy(): void; + + } + + /** + * Keyboard Codes. + */ + namespace KeyCodes { + /** + * The BACKSPACE key. + */ + var BACKSPACE: integer; + + /** + * The TAB key. + */ + var TAB: integer; + + /** + * The ENTER key. + */ + var ENTER: integer; + + /** + * The SHIFT key. + */ + var SHIFT: integer; + + /** + * The CTRL key. + */ + var CTRL: integer; + + /** + * The ALT key. + */ + var ALT: integer; + + /** + * The PAUSE key. + */ + var PAUSE: integer; + + /** + * The CAPS_LOCK key. + */ + var CAPS_LOCK: integer; + + /** + * The ESC key. + */ + var ESC: integer; + + /** + * The SPACE key. + */ + var SPACE: integer; + + /** + * The PAGE_UP key. + */ + var PAGE_UP: integer; + + /** + * The PAGE_DOWN key. + */ + var PAGE_DOWN: integer; + + /** + * The END key. + */ + var END: integer; + + /** + * The HOME key. + */ + var HOME: integer; + + /** + * The LEFT key. + */ + var LEFT: integer; + + /** + * The UP key. + */ + var UP: integer; + + /** + * The RIGHT key. + */ + var RIGHT: integer; + + /** + * The DOWN key. + */ + var DOWN: integer; + + /** + * The PRINT_SCREEN key. + */ + var PRINT_SCREEN: integer; + + /** + * The INSERT key. + */ + var INSERT: integer; + + /** + * The DELETE key. + */ + var DELETE: integer; + + /** + * The ZERO key. + */ + var ZERO: integer; + + /** + * The ONE key. + */ + var ONE: integer; + + /** + * The TWO key. + */ + var TWO: integer; + + /** + * The THREE key. + */ + var THREE: integer; + + /** + * The FOUR key. + */ + var FOUR: integer; + + /** + * The FIVE key. + */ + var FIVE: integer; + + /** + * The SIX key. + */ + var SIX: integer; + + /** + * The SEVEN key. + */ + var SEVEN: integer; + + /** + * The EIGHT key. + */ + var EIGHT: integer; + + /** + * The NINE key. + */ + var NINE: integer; + + /** + * The NUMPAD_ZERO key. + */ + var NUMPAD_ZERO: integer; + + /** + * The NUMPAD_ONE key. + */ + var NUMPAD_ONE: integer; + + /** + * The NUMPAD_TWO key. + */ + var NUMPAD_TWO: integer; + + /** + * The NUMPAD_THREE key. + */ + var NUMPAD_THREE: integer; + + /** + * The NUMPAD_FOUR key. + */ + var NUMPAD_FOUR: integer; + + /** + * The NUMPAD_FIVE key. + */ + var NUMPAD_FIVE: integer; + + /** + * The NUMPAD_SIX key. + */ + var NUMPAD_SIX: integer; + + /** + * The NUMPAD_SEVEN key. + */ + var NUMPAD_SEVEN: integer; + + /** + * The NUMPAD_EIGHT key. + */ + var NUMPAD_EIGHT: integer; + + /** + * The NUMPAD_NINE key. + */ + var NUMPAD_NINE: integer; + + /** + * The Numpad Addition (+) key. + */ + var NUMPAD_ADD: integer; + + /** + * The Numpad Subtraction (-) key. + */ + var NUMPAD_SUBTRACT: integer; + + /** + * The A key. + */ + var A: integer; + + /** + * The B key. + */ + var B: integer; + + /** + * The C key. + */ + var C: integer; + + /** + * The D key. + */ + var D: integer; + + /** + * The E key. + */ + var E: integer; + + /** + * The F key. + */ + var F: integer; + + /** + * The G key. + */ + var G: integer; + + /** + * The H key. + */ + var H: integer; + + /** + * The I key. + */ + var I: integer; + + /** + * The J key. + */ + var J: integer; + + /** + * The K key. + */ + var K: integer; + + /** + * The L key. + */ + var L: integer; + + /** + * The M key. + */ + var M: integer; + + /** + * The N key. + */ + var N: integer; + + /** + * The O key. + */ + var O: integer; + + /** + * The P key. + */ + var P: integer; + + /** + * The Q key. + */ + var Q: integer; + + /** + * The R key. + */ + var R: integer; + + /** + * The S key. + */ + var S: integer; + + /** + * The T key. + */ + var T: integer; + + /** + * The U key. + */ + var U: integer; + + /** + * The V key. + */ + var V: integer; + + /** + * The W key. + */ + var W: integer; + + /** + * The X key. + */ + var X: integer; + + /** + * The Y key. + */ + var Y: integer; + + /** + * The Z key. + */ + var Z: integer; + + /** + * The F1 key. + */ + var F1: integer; + + /** + * The F2 key. + */ + var F2: integer; + + /** + * The F3 key. + */ + var F3: integer; + + /** + * The F4 key. + */ + var F4: integer; + + /** + * The F5 key. + */ + var F5: integer; + + /** + * The F6 key. + */ + var F6: integer; + + /** + * The F7 key. + */ + var F7: integer; + + /** + * The F8 key. + */ + var F8: integer; + + /** + * The F9 key. + */ + var F9: integer; + + /** + * The F10 key. + */ + var F10: integer; + + /** + * The F11 key. + */ + var F11: integer; + + /** + * The F12 key. + */ + var F12: integer; + + /** + * The SEMICOLON key. + */ + var SEMICOLON: integer; + + /** + * The PLUS key. + */ + var PLUS: integer; + + /** + * The COMMA key. + */ + var COMMA: integer; + + /** + * The MINUS key. + */ + var MINUS: integer; + + /** + * The PERIOD key. + */ + var PERIOD: integer; + + /** + * The FORWARD_SLASH key. + */ + var FORWARD_SLASH: integer; + + /** + * The BACK_SLASH key. + */ + var BACK_SLASH: integer; + + /** + * The QUOTES key. + */ + var QUOTES: integer; + + /** + * The BACKTICK key. + */ + var BACKTICK: integer; + + /** + * The OPEN_BRACKET key. + */ + var OPEN_BRACKET: integer; + + /** + * The CLOSED_BRACKET key. + */ + var CLOSED_BRACKET: integer; + + /** + * The SEMICOLON_FIREFOX key. + */ + var SEMICOLON_FIREFOX: integer; + + /** + * The COLON key. + */ + var COLON: integer; + + /** + * The COMMA_FIREFOX_WINDOWS key. + */ + var COMMA_FIREFOX_WINDOWS: integer; + + /** + * The COMMA_FIREFOX key. + */ + var COMMA_FIREFOX: integer; + + /** + * The BRACKET_RIGHT_FIREFOX key. + */ + var BRACKET_RIGHT_FIREFOX: integer; + + /** + * The BRACKET_LEFT_FIREFOX key. + */ + var BRACKET_LEFT_FIREFOX: integer; + + } + + /** + * 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. + * @param key The Key object to test. + * @param duration The duration, in ms, within which the key must have been released. Default 50. + */ + function UpDuration(key: Phaser.Input.Keyboard.Key, duration?: integer): boolean; + + } + + namespace Mouse { + /** + * The Mouse Manager is a helper class that belongs to the Input Manager. + * + * Its role is to listen for native DOM Mouse Events and then pass them onto the Input Manager for further processing. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically. + */ + class MouseManager { + /** + * + * @param inputManager A reference to the Input Manager. + */ + constructor(inputManager: Phaser.Input.InputManager); + + /** + * A reference to the Input Manager. + */ + manager: Phaser.Input.InputManager; + + /** + * If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + capture: boolean; + + /** + * A boolean that controls if the Mouse Manager is enabled or not. + * Can be toggled on the fly. + */ + enabled: boolean; + + /** + * The Mouse target, as defined in the Game Config. + * Typically the canvas to which the game is rendering, but can be any interactive DOM element. + */ + target: any; + + /** + * If the mouse has been pointer locked successfully this will be set to true. + */ + locked: boolean; + + /** + * The Mouse Move Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseMove: Function; + + /** + * The Mouse Down Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseDown: Function; + + /** + * The Mouse Up Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseUp: Function; + + /** + * The Mouse Down Event handler specifically for events on the Window. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseDownWindow: Function; + + /** + * The Mouse Up Event handler specifically for events on the Window. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseUpWindow: Function; + + /** + * The Mouse Over Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseOver: Function; + + /** + * The Mouse Out Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseOut: Function; + + /** + * The Mouse Wheel Event handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + onMouseWheel: Function; + + /** + * Internal pointerLockChange handler. + * This function is sent the native DOM MouseEvent. + * Initially empty and bound in the `startListeners` method. + */ + pointerLockChange: Function; + + /** + * Attempts to disable the context menu from appearing if you right-click on the browser. + * + * Works by listening for the `contextmenu` event and prevent defaulting it. + * + * Use this if you need to enable right-button mouse support in your game, and the browser + * menu keeps getting in the way. + */ + disableContextMenu(): Phaser.Input.Mouse.MouseManager; + + /** + * 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. + */ + requestPointerLock(): void; + + /** + * If the browser supports pointer lock, this will request that the pointer lock is released. If + * the browser successfully enters a locked state, a 'POINTER_LOCK_CHANGE_EVENT' will be + * dispatched - from the game's input manager - with an `isPointerLocked` property. + */ + releasePointerLock(): void; + + /** + * Starts the Mouse Event listeners running. + * This is called automatically and does not need to be manually invoked. + */ + startListeners(): void; + + /** + * Stops the Mouse Event listeners. + * This is called automatically and does not need to be manually invoked. + */ + stopListeners(): void; + + /** + * Destroys this Mouse Manager instance. + */ + destroy(): void; + + } + + } + + /** + * A Pointer object encapsulates both mouse and touch input within Phaser. + * + * By default, Phaser will create 2 pointers for your game to use. If you require more, i.e. for a multi-touch + * game, then use the `InputPlugin.addPointer` method to do so, rather than instantiating this class directly, + * otherwise it won't be managed by the input system. + * + * You can reference the current active pointer via `InputPlugin.activePointer`. You can also use the properties + * `InputPlugin.pointer1` through to `pointer10`, for each pointer you have enabled in your game. + * + * The properties of this object are set by the Input Plugin during processing. This object is then sent in all + * input related events that the Input Plugin emits, so you can reference properties from it directly in your + * callbacks. + */ + class Pointer { + /** + * + * @param manager A reference to the Input Manager. + * @param id The internal ID of this Pointer. + */ + constructor(manager: Phaser.Input.InputManager, id: integer); + + /** + * A reference to the Input Manager. + */ + manager: Phaser.Input.InputManager; + + /** + * The internal ID of this Pointer. + */ + readonly id: integer; + + /** + * The most recent native DOM Event this Pointer has processed. + */ + event: TouchEvent | MouseEvent; + + /** + * 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. + */ + readonly downElement: any; + + /** + * 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. + */ + readonly upElement: any; + + /** + * The camera the Pointer interacted with during its last update. + * + * A Pointer can only ever interact with one camera at once, which will be the top-most camera + * in the list should multiple cameras be positioned on-top of each other. + */ + camera: Phaser.Cameras.Scene2D.Camera; + + /** + * A read-only property that indicates which button was pressed, or released, on the pointer + * during the most recent event. It is only set during `up` and `down` events. + * + * On Touch devices the value is always 0. + * + * Users may change the configuration of buttons on their pointing device so that if an event's button property + * is zero, it may not have been caused by the button that is physically left–most on the pointing device; + * however, it should behave as if the left button was clicked in the standard button layout. + */ + readonly button: integer; + + /** + * 0: No button or un-initialized + * 1: Left button + * 2: Right button + * 4: Wheel button or middle button + * 8: 4th button (typically the "Browser Back" button) + * 16: 5th button (typically the "Browser Forward" button) + * + * For a mouse configured for left-handed use, the button actions are reversed. + * In this case, the values are read from right to left. + */ + buttons: integer; + + /** + * The position of the Pointer in screen space. + */ + readonly position: Phaser.Math.Vector2; + + /** + * The previous position of the Pointer in screen space. + * + * The old x and y values are stored in here during the InputManager.transformPointer call. + * + * Use the properties `velocity`, `angle` and `distance` to create your own gesture recognition. + */ + readonly prevPosition: Phaser.Math.Vector2; + + /** + * 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. + */ + readonly velocity: Phaser.Math.Vector2; + + /** + * 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. + */ + readonly angle: number; + + /** + * 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 buttons was pressed down, + * then use the `Pointer.getDistance` method. + */ + readonly distance: number; + + /** + * The smoothing factor to apply to the Pointer position. + * + * Due to their nature, pointer positions are inherently noisy. While this is fine for lots of games, if you need cleaner positions + * then you can set this value to apply an automatic smoothing to the positions as they are recorded. + * + * The default value of zero means 'no smoothing'. + * Set to a small value, such as 0.2, to apply an average level of smoothing between positions. You can do this by changing this + * value directly, or by setting the `input.smoothFactor` property in the Game Config. + * + * Positions are only smoothed when the pointer moves. If the primary button on this Pointer enters an Up or Down state, then the position + * is always precise, and not smoothed. + */ + smoothFactor: number; + + /** + * The factor applied to the motion smoothing each frame. + * + * This value is passed to the Smooth Step Interpolation that is used to calculate the velocity, + * angle and distance of the Pointer. It's applied every frame, until the midPoint reaches the current + * position of the Pointer. 0.2 provides a good average but can be increased if you need a + * quicker update and are working in a high performance environment. Never set this value to + * zero. + */ + motionFactor: number; + + /** + * The x position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. + * + * If you wish to use this value _outside_ of an input event handler then you should update it first by calling + * the `Pointer.updateWorldPoint` method. + */ + worldX: number; + + /** + * The y position of this Pointer, translated into the coordinate space of the most recent Camera it interacted with. + * + * If you wish to use this value _outside_ of an input event handler then you should update it first by calling + * the `Pointer.updateWorldPoint` method. + */ + worldY: number; + + /** + * Time when this Pointer was most recently moved (regardless of the state of its buttons, if any) + */ + moveTime: number; + + /** + * X coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. + */ + downX: number; + + /** + * Y coordinate of the Pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects. + */ + downY: number; + + /** + * Time when Button 1 (left button), or Touch, was pressed, used for dragging objects. + */ + downTime: number; + + /** + * X coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. + */ + upX: number; + + /** + * Y coordinate of the Pointer when Button 1 (left button), or Touch, was released, used for dragging objects. + */ + upY: number; + + /** + * Time when Button 1 (left button), or Touch, was released, used for dragging objects. + */ + upTime: number; + + /** + * Is the primary button down? (usually button 0, the left mouse button) + */ + primaryDown: boolean; + + /** + * Is _any_ button on this pointer considered as being down? + */ + isDown: boolean; + + /** + * Did the previous input event come from a Touch input (true) or Mouse? (false) + */ + wasTouch: boolean; + + /** + * Did this Pointer get canceled by a touchcancel event? + * + * Note: "canceled" is the American-English spelling of "cancelled". Please don't submit PRs correcting it! + */ + wasCanceled: boolean; + + /** + * If the mouse is locked, the horizontal relative movement of the Pointer in pixels since last frame. + */ + movementX: number; + + /** + * If the mouse is locked, the vertical relative movement of the Pointer in pixels since last frame. + */ + movementY: number; + + /** + * The identifier property of the Pointer as set by the DOM event when this Pointer is started. + */ + identifier: number; + + /** + * The pointerId property of the Pointer as set by the DOM event when this Pointer is started. + * The browser can and will recycle this value. + */ + pointerId: number; + + /** + * An active Pointer is one that is currently pressed down on the display. + * A Mouse is always considered as active. + */ + active: boolean; + + /** + * Is this pointer Pointer Locked? + * + * Only a mouse pointer can be locked and it only becomes locked when requested via + * the browsers Pointer Lock API. + * + * You can request this by calling the `this.input.mouse.requestPointerLock()` method from + * a `pointerdown` or `pointerup` event handler. + */ + readonly locked: boolean; + + /** + * The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device. + */ + deltaX: number; + + /** + * The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device. + * This value will typically be less than 0 if the user scrolls up and greater than zero if scrolling down. + */ + deltaY: number; + + /** + * The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device. + */ + deltaZ: number; + + /** + * Takes a Camera and updates this Pointer's `worldX` and `worldY` values so they are + * the result of a translation through the given Camera. + * + * Note that the values will be automatically replaced the moment the Pointer is + * updated by an input event, such as a mouse move, so should be used immediately. + * @param camera The Camera which is being tested against. + */ + updateWorldPoint(camera: Phaser.Cameras.Scene2D.Camera): this; + + /** + * 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. + * @param camera The Camera to use for the translation. + * @param output A Vector2-like object in which to store the translated position. + */ + positionToCamera(camera: Phaser.Cameras.Scene2D.Camera, output?: Phaser.Math.Vector2 | object): Phaser.Math.Vector2 | object; + + /** + * Checks to see if any buttons are being held down on this Pointer. + */ + noButtonDown(): boolean; + + /** + * Checks to see if the left button is being held down on this Pointer. + */ + leftButtonDown(): boolean; + + /** + * Checks to see if the right button is being held down on this Pointer. + */ + rightButtonDown(): boolean; + + /** + * Checks to see if the middle button is being held down on this Pointer. + */ + middleButtonDown(): boolean; + + /** + * Checks to see if the back button is being held down on this Pointer. + */ + backButtonDown(): boolean; + + /** + * Checks to see if the forward button is being held down on this Pointer. + */ + forwardButtonDown(): boolean; + + /** + * Checks to see if the left button was just released on this Pointer. + */ + leftButtonReleased(): boolean; + + /** + * Checks to see if the right button was just released on this Pointer. + */ + rightButtonReleased(): boolean; + + /** + * Checks to see if the middle button was just released on this Pointer. + */ + middleButtonReleased(): boolean; + + /** + * Checks to see if the back button was just released on this Pointer. + */ + backButtonReleased(): boolean; + + /** + * Checks to see if the forward button was just released on this Pointer. + */ + forwardButtonReleased(): boolean; + + /** + * 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. + */ + getDistance(): number; + + /** + * 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` and `downY` values and the current 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. + */ + getDistanceX(): number; + + /** + * 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 `downX` and `downY` values and the current 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. + */ + getDistanceY(): number; + + /** + * 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 Pointer button was released. + */ + getDuration(): number; + + /** + * 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. + */ + getAngle(): number; + + /** + * Takes the previous and current Pointer positions and then generates an array of interpolated values between + * the two. The array will be populated up to the size of the `steps` argument. + * + * ```javaScript + * var points = pointer.getInterpolatedPosition(4); + * + * // points[0] = { x: 0, y: 0 } + * // points[1] = { x: 2, y: 1 } + * // points[2] = { x: 3, y: 2 } + * // points[3] = { x: 6, y: 3 } + * ``` + * + * Use this if you need to get smoothed values between the previous and current pointer positions. DOM pointer + * events can often fire faster than the main browser loop, and this will help you avoid janky movement + * especially if you have an object following a Pointer. + * + * Note that if you provide an output array it will only be populated up to the number of steps provided. + * It will not clear any previous data that may have existed beyond the range of the steps count. + * + * Internally it uses the Smooth Step interpolation calculation. + * @param steps The number of interpolation steps to use. Default 10. + * @param out An array to store the results in. If not provided a new one will be created. + */ + getInterpolatedPosition(steps?: integer, out?: any[]): any[]; + + /** + * Destroys this Pointer instance and resets its external references. + */ + destroy(): void; + + /** + * The x position of this Pointer. + * The value is in screen space. + * See `worldX` to get a camera converted position. + */ + x: number; + + /** + * The y position of this Pointer. + * The value is in screen space. + * See `worldY` to get a camera converted position. + */ + y: number; + + /** + * Time when this Pointer was most recently updated by a DOM Event. + * This comes directly from the `event.timeStamp` property. + * If no event has yet taken place, it will return zero. + */ + readonly time: number; + + } + + namespace Touch { + /** + * The Touch Manager is a helper class that belongs to the Input Manager. + * + * Its role is to listen for native DOM Touch Events and then pass them onto the Input Manager for further processing. + * + * You do not need to create this class directly, the Input Manager will create an instance of it automatically. + */ + class TouchManager { + /** + * + * @param inputManager A reference to the Input Manager. + */ + constructor(inputManager: Phaser.Input.InputManager); + + /** + * A reference to the Input Manager. + */ + manager: Phaser.Input.InputManager; + + /** + * If true the DOM events will have event.preventDefault applied to them, if false they will propagate fully. + */ + capture: boolean; + + /** + * A boolean that controls if the Touch Manager is enabled or not. + * Can be toggled on the fly. + */ + enabled: boolean; + + /** + * The Touch Event target, as defined in the Game Config. + * Typically the canvas to which the game is rendering, but can be any interactive DOM element. + */ + target: any; + + /** + * The Touch Start event handler function. + * Initially empty and bound in the `startListeners` method. + */ + onTouchStart: Function; + + /** + * The Touch Start event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + */ + onTouchStartWindow: Function; + + /** + * The Touch Move event handler function. + * Initially empty and bound in the `startListeners` method. + */ + onTouchMove: Function; + + /** + * The Touch End event handler function. + * Initially empty and bound in the `startListeners` method. + */ + onTouchEnd: Function; + + /** + * The Touch End event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + */ + onTouchEndWindow: Function; + + /** + * The Touch Cancel event handler function. + * Initially empty and bound in the `startListeners` method. + */ + onTouchCancel: Function; + + /** + * The Touch Cancel event handler function specifically for events on the Window. + * Initially empty and bound in the `startListeners` method. + */ + onTouchCancelWindow: Function; + + /** + * The Touch Over event handler function. + * Initially empty and bound in the `startListeners` method. + */ + onTouchOver: Function; + + /** + * The Touch Out event handler function. + * Initially empty and bound in the `startListeners` method. + */ + onTouchOut: Function; + + /** + * Attempts to disable the context menu from appearing if you touch-hold on the browser. + * + * Works by listening for the `contextmenu` event and prevent defaulting it. + * + * Use this if you need to disable the OS context menu on mobile. + */ + disableContextMenu(): Phaser.Input.Touch.TouchManager; + + /** + * Starts the Touch Event listeners running as long as an input target is set. + * + * This method is called automatically if Touch Input is enabled in the game config, + * which it is by default. However, you can call it manually should you need to + * delay input capturing until later in the game. + */ + startListeners(): void; + + /** + * Stops the Touch Event listeners. + * This is called automatically and does not need to be manually invoked. + */ + stopListeners(): void; + + /** + * Destroys this Touch Manager instance. + */ + destroy(): void; + + } + + } + + } + + namespace Loader { + /** + * The Loader is idle. + */ + var LOADER_IDLE: integer; + + /** + * The Loader is actively loading. + */ + var LOADER_LOADING: integer; + + /** + * The Loader is processing files is has loaded. + */ + var LOADER_PROCESSING: integer; + + /** + * The Loader has completed loading and processing. + */ + var LOADER_COMPLETE: integer; + + /** + * The Loader is shutting down. + */ + var LOADER_SHUTDOWN: integer; + + /** + * The Loader has been destroyed. + */ + var LOADER_DESTROYED: integer; + + /** + * File is in the load queue but not yet started + */ + var FILE_PENDING: integer; + + /** + * File has been started to load by the loader (onLoad called) + */ + var FILE_LOADING: integer; + + /** + * File has loaded successfully, awaiting processing + */ + var FILE_LOADED: integer; + + /** + * File failed to load + */ + var FILE_FAILED: integer; + + /** + * File is being processed (onProcess callback) + */ + var FILE_PROCESSING: integer; + + /** + * The File has errored somehow during processing. + */ + var FILE_ERRORED: integer; + + /** + * File has finished processing. + */ + var FILE_COMPLETE: integer; + + /** + * File has been destroyed + */ + var FILE_DESTROYED: integer; + + /** + * File was populated from local data and doesn't need an HTTP request + */ + var FILE_POPULATED: integer; + + namespace Events { + /** + * The Loader Plugin Add File Event. + * + * This event is dispatched when a new file is successfully added to the Loader and placed into the load queue. + * + * Listen to it from a Scene using: `this.load.on('addfile', listener)`. + * + * If you add lots of files to a Loader from a `preload` method, it will dispatch this event for each one of them. + */ + const ADD: any; + + /** + * The Loader Plugin Complete Event. + * + * This event is dispatched when the Loader has fully processed everything in the load queue. + * By this point every loaded file will now be in its associated cache and ready for use. + * + * Listen to it from a Scene using: `this.load.on('complete', listener)`. + */ + const COMPLETE: any; + + /** + * The File Load Complete Event. + * + * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. + * + * Listen to it from a Scene using: `this.load.on('filecomplete', listener)`. + * + * You can also listen for the completion of a specific file. See the [FILE_KEY_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_KEY_COMPLETE} event. + */ + const FILE_COMPLETE: any; + + /** + * The File Load Complete Event. + * + * This event is dispatched by the Loader Plugin when any file in the queue finishes loading. + * + * It uses a special dynamic event name constructed from the key and type of the file. + * + * For example, if you have loaded an `image` with a key of `monster`, you can listen for it + * using the following: + * + * ```javascript + * this.load.on('filecomplete-image-monster', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * Or, if you have loaded a texture `atlas` with a key of `Level1`: + * + * ```javascript + * this.load.on('filecomplete-atlas-Level1', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * Or, if you have loaded a sprite sheet with a key of `Explosion` and a prefix of `GAMEOVER`: + * + * ```javascript + * this.load.on('filecomplete-spritesheet-GAMEOVERExplosion', function (key, type, data) { + * // Your handler code + * }); + * ``` + * + * You can also listen for the generic completion of files. See the [FILE_COMPLETE]{@linkcode Phaser.Loader.Events#event:FILE_COMPLETE} event. + */ + const FILE_KEY_COMPLETE: any; + + /** + * The File Load Error Event. + * + * This event is dispatched by the Loader Plugin when a file fails to load. + * + * Listen to it from a Scene using: `this.load.on('loaderror', listener)`. + */ + const FILE_LOAD_ERROR: any; + + /** + * The File Load Event. + * + * This event is dispatched by the Loader Plugin when a file finishes loading, + * but _before_ it is processed and added to the internal Phaser caches. + * + * Listen to it from a Scene using: `this.load.on('load', listener)`. + */ + const FILE_LOAD: any; + + /** + * The File Load Progress Event. + * + * This event is dispatched by the Loader Plugin during the load of a file, if the browser receives a DOM ProgressEvent and + * the `lengthComputable` event property is true. Depending on the size of the file and browser in use, this may, or may not happen. + * + * Listen to it from a Scene using: `this.load.on('fileprogress', listener)`. + */ + const FILE_PROGRESS: any; + + /** + * The Loader Plugin Post Process Event. + * + * This event is dispatched by the Loader Plugin when the Loader has finished loading everything in the load queue. + * It is dispatched before the internal lists are cleared and each File is destroyed. + * + * Use this hook to perform any last minute processing of files that can only happen once the + * Loader has completed, but prior to it emitting the `complete` event. + * + * Listen to it from a Scene using: `this.load.on('postprocess', listener)`. + */ + const POST_PROCESS: any; + + /** + * The Loader Plugin Progress Event. + * + * This event is dispatched when the Loader updates its load progress, typically as a result of a file having completed loading. + * + * Listen to it from a Scene using: `this.load.on('progress', listener)`. + */ + const PROGRESS: any; + + /** + * The Loader Plugin Start Event. + * + * This event is dispatched when the Loader starts running. At this point load progress is zero. + * + * This event is dispatched even if there aren't any files in the load queue. + * + * Listen to it from a Scene using: `this.load.on('start', listener)`. + */ + const START: any; + + } + + /** + * The base File class used by all File Types that the Loader can support. + * You shouldn't create an instance of a File directly, but should extend it with your own class, setting a custom type and processing methods. + */ + class File { + /** + * + * @param loader The Loader that is going to load this File. + * @param fileConfig The file configuration object, as created by the file type. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, fileConfig: Phaser.Types.Loader.FileConfig); + + /** + * A reference to the Loader that is going to load this file. + */ + loader: Phaser.Loader.LoaderPlugin; + + /** + * A reference to the Cache, or Texture Manager, that is going to store this file if it loads. + */ + cache: Phaser.Cache.BaseCache | Phaser.Textures.TextureManager; + + /** + * The file type string (image, json, etc) for sorting within the Loader. + */ + type: string; + + /** + * Unique cache key (unique within its file type) + */ + key: string; + + /** + * The URL of the file, not including baseURL. + * Automatically has Loader.path prepended to it. + */ + url: string; + + /** + * The final URL this file will load from, including baseURL and path. + * Set automatically when the Loader calls 'load' on this file. + */ + src: string; + + /** + * The merged XHRSettings for this file. + */ + xhrSettings: Phaser.Types.Loader.XHRSettingsObject; + + /** + * The XMLHttpRequest instance (as created by XHR Loader) that is loading this File. + */ + xhrLoader: XMLHttpRequest; + + /** + * The current state of the file. One of the FILE_CONST values. + */ + state: integer; + + /** + * The total size of this file. + * Set by onProgress and only if loading via XHR. + */ + bytesTotal: number; + + /** + * Updated as the file loads. + * Only set if loading via XHR. + */ + bytesLoaded: number; + + /** + * A percentage value between 0 and 1 indicating how much of this file has loaded. + * Only set if loading via XHR. + */ + percentComplete: number; + + /** + * For CORs based loading. + * If this is undefined then the File will check BaseLoader.crossOrigin and use that (if set) + */ + crossOrigin: string | undefined; + + /** + * The processed file data, stored here after the file has loaded. + */ + data: any; + + /** + * A config object that can be used by file types to store transitional data. + */ + config: any; + + /** + * If this is a multipart file, i.e. an atlas and its json together, then this is a reference + * to the parent MultiFile. Set and used internally by the Loader or specific file types. + */ + multiFile: Phaser.Loader.MultiFile; + + /** + * Does this file have an associated linked file? Such as an image and a normal map. + * Atlases and Bitmap Fonts use the multiFile, because those files need loading together but aren't + * actually bound by data, where-as a linkFile is. + */ + linkFile: Phaser.Loader.File; + + /** + * Links this File with another, so they depend upon each other for loading and processing. + * @param fileB The file to link to this one. + */ + setLink(fileB: Phaser.Loader.File): void; + + /** + * Resets the XHRLoader instance this file is using. + */ + resetXHR(): void; + + /** + * 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. + */ + load(): void; + + /** + * Called when the file finishes loading, is sent a DOM ProgressEvent. + * @param xhr The XMLHttpRequest that caused this onload event. + * @param event The DOM ProgressEvent that resulted from this load. + */ + onLoad(xhr: XMLHttpRequest, event: ProgressEvent): void; + + /** + * Called if the file errors while loading, is sent a DOM ProgressEvent. + * @param xhr The XMLHttpRequest that caused this onload event. + * @param event The DOM ProgressEvent that resulted from this error. + */ + onError(xhr: XMLHttpRequest, event: ProgressEvent): void; + + /** + * Called during the file load progress. Is sent a DOM ProgressEvent. + * @param event The DOM ProgressEvent. + */ + onProgress(event: ProgressEvent): void; + + /** + * Usually overridden by the FileTypes and is called by Loader.nextFile. + * This method controls what extra work this File does with its loaded data, for example a JSON file will parse itself during this stage. + */ + onProcess(): void; + + /** + * Called when the File has completed processing. + * Checks on the state of its multifile, if set. + */ + onProcessComplete(): void; + + /** + * Called when the File has completed processing but it generated an error. + * Checks on the state of its multifile, if set. + */ + onProcessError(): void; + + /** + * Checks if a key matching the one used by this file exists in the target Cache or not. + * This is called automatically by the LoaderPlugin to decide if the file can be safely + * loaded or will conflict. + */ + hasCacheConflict(): boolean; + + /** + * Adds this file to its target cache upon successful loading and processing. + * This method is often overridden by specific file types. + */ + addToCache(): void; + + /** + * Called once the file has been added to its cache and is now ready for deletion from the Loader. + * It will emit a `filecomplete` event from the LoaderPlugin. + */ + pendingDestroy(): void; + + /** + * Destroy this File and any references it holds. + */ + destroy(): void; + + /** + * Static method for creating object URL using URL API and setting it as image 'src' attribute. + * If URL API is not supported (usually on old browsers) it falls back to creating Base64 encoded url using FileReader. + * @param image Image object which 'src' attribute should be set to object URL. + * @param blob A Blob object to create an object URL for. + * @param defaultType Default mime type used if blob type is not available. + */ + static createObjectURL(image: HTMLImageElement, blob: Blob, defaultType: string): void; + + /** + * Static method for releasing an existing object URL which was previously created + * by calling {@link File#createObjectURL} method. + * @param image Image object which 'src' attribute should be revoked. + */ + static revokeObjectURL(image: HTMLImageElement): void; + + } + + namespace FileTypes { + /** + * A single Animation JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#animation method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#animation. + */ + class AnimationJSONFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings Extra XHR Settings specifically for this file. + * @param dataKey When the JSON file loads only this property will be stored in the Cache. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataKey?: string); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Called at the end of the load process, after the Loader has finished all files in its queue. + */ + onLoadComplete(): void; + + } + + /** + * 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. + * + * https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm + */ + class AtlasJSONFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param atlasURL The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig, textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single XML based Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#atlasXML method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#atlasXML. + */ + class AtlasXMLFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param atlasURL The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas xml file. Used in replacement of the Loaders default XHR Settings. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig, textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Audio File suitable for loading by the Loader. + * + * 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 { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param urlConfig The absolute or relative URL to load this file from in a config object. + * @param xhrSettings Extra XHR Settings specifically for this file. + * @param audioContext The AudioContext this file will use to process itself. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AudioFileConfig, urlConfig?: any, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, audioContext?: AudioContext); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * An Audio Sprite File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#audioSprite method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audioSprite. + */ + class AudioSpriteFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param jsonURL The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead. + * @param audioURL The absolute or relative URL to load the audio file from. If empty it will be obtained by parsing the JSON file. + * @param audioConfig The audio configuration options. + * @param audioXhrSettings An XHR Settings configuration object for the audio file. Used in replacement of the Loaders default XHR Settings. + * @param jsonXhrSettings An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig, jsonURL: string, audioURL?: Object, audioConfig?: any, audioXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, jsonXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called by each File when it finishes loading. + * @param file The File that has completed processing. + */ + onFileComplete(file: Phaser.Loader.File): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Binary File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#binary method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#binary. + */ + class BinaryFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param xhrSettings Extra XHR Settings specifically for this file. + * @param dataType Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.BinaryFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataType?: any); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single Bitmap Font based File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#bitmapFont method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#bitmapFont. + */ + class BitmapFontFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param textureURL The absolute or relative URL to load the font image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param fontDataURL The absolute or relative URL to load the font xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param textureXhrSettings An XHR Settings configuration object for the font image file. Used in replacement of the Loaders default XHR Settings. + * @param fontDataXhrSettings An XHR Settings configuration object for the font data xml file. Used in replacement of the Loaders default XHR Settings. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.BitmapFontFileConfig, textureURL?: string | string[], fontDataURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, fontDataXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single CSS File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#css method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#css. + */ + class CSSFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.CSSFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single GLSL File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#glsl method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#glsl. + */ + class GLSLFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param shaderType The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. Default 'fragment'. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.GLSLFileConfig, url?: string, shaderType?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + /** + * Returns the name of the shader from the header block. + * @param headerSource The header data. + */ + getShaderName(headerSource: string[]): string; + + /** + * Returns the type of the shader from the header block. + * @param headerSource The header data. + */ + getShaderType(headerSource: string[]): string; + + /** + * Returns the shader uniforms from the header block. + * @param headerSource The header data. + */ + getShaderUniforms(headerSource: string[]): any; + + } + + /** + * A single Audio File suitable for loading by the Loader. + * + * 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 HTML5AudioFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param urlConfig The absolute or relative URL to load this file from. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.AudioFileConfig, urlConfig?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called when the file finishes loading. + */ + onLoad(): void; + + /** + * Called if the file errors while loading. + */ + onError(): void; + + /** + * Called during the file load progress. Is sent a DOM ProgressEvent. + */ + onProgress(): void; + + /** + * 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. + */ + load(): void; + + } + + /** + * A single HTML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#html method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#html. + */ + class HTMLFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.HTMLFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single HTML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#htmlTexture method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#htmlTexture. + */ + class HTMLTextureFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param width The width of the texture the HTML will be rendered to. + * @param height The height of the texture the HTML will be rendered to. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig, url?: string, width?: integer, height?: integer, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Image File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#image method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#image. + */ + class ImageFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param xhrSettings Extra XHR Settings specifically for this file. + * @param frameConfig The frame configuration object. Only provided for, and used by, Sprite Sheets. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.ImageFileConfig, url?: string | string[], xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#json method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#json. + */ + class JSONFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings Extra XHR Settings specifically for this file. + * @param dataKey When the JSON file loads only this property will be stored in the Cache. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataKey?: string); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single Multi Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#multiatlas method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#multiatlas. + */ + class MultiAtlasFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key of the file. Must be unique within both the Loader and the Texture Manager. Or a config object. + * @param atlasURL The absolute or relative URL to load the multi atlas json file from. + * @param path Optional path to use when loading the textures defined in the atlas data. + * @param baseURL Optional Base URL to use when loading the textures defined in the atlas data. + * @param atlasXhrSettings Extra XHR Settings specifically for the atlas json file. + * @param textureXhrSettings Extra XHR Settings specifically for the texture files. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig, atlasURL?: string, path?: string, baseURL?: string, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called by each File when it finishes loading. + * @param file The File that has completed processing. + */ + onFileComplete(file: Phaser.Loader.File): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A Multi Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#scripts method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scripts. + */ + class MultiScriptFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + * @param xhrSettings An XHR Settings configuration object for the script files. Used in replacement of the Loaders default XHR Settings. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.MultiScriptFileConfig, url?: string[], xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single JSON Pack File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#pack method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#pack. + */ + class PackFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings Extra XHR Settings specifically for this file. + * @param dataKey When the JSON file loads only this property will be stored in the Cache. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.PackFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject, dataKey?: string); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single Plugin Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#plugin method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#plugin. + */ + class PluginFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param start Automatically start the plugin after loading? Default false. + * @param mapping If this plugin is to be injected into the Scene, this is the property key used. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.PluginFileConfig, url?: string, start?: boolean, mapping?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * An external Scene JavaScript File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#sceneFile method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#sceneFile. + */ + class SceneFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.SceneFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Scene Plugin Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#scenePlugin method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#scenePlugin. + */ + class ScenePluginFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param systemKey If this plugin is to be added to Scene.Systems, this is the property key for it. + * @param sceneKey If this plugin is to be added to the Scene, this is the property key for it. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.ScenePluginFileConfig, url?: string, systemKey?: string, sceneKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single Script File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#script method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#script. + */ + class ScriptFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.ScriptFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single Sprite Sheet Image File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#spritesheet method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spritesheet. + */ + class SpriteSheetFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param frameConfig The frame configuration object. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig, url?: string | string[], frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single SVG File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#svg method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#svg. + */ + class SVGFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". + * @param svgConfig The svg size configuration object. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.SVGFileConfig, url?: string, svgConfig?: Phaser.Types.Loader.FileTypes.SVGSizeConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Text File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#text method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#text. + */ + class TextFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TextFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + /** + * A single Tilemap CSV File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapCSV method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapCSV. + */ + class TilemapCSVFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Impact.js Tilemap JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapImpact method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapImpact. + */ + class TilemapImpactFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Tiled Tilemap JSON File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#tilemapTiledJSON method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#tilemapTiledJSON. + */ + class TilemapJSONFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single text file based Unity Texture Atlas File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#unityAtlas method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#unityAtlas. + */ + class UnityAtlasFile extends Phaser.Loader.MultiFile { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param atlasURL The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig, textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Adds this file to its target cache upon successful loading and processing. + */ + addToCache(): void; + + } + + /** + * A single Video File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#video method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#video. + */ + class VideoFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param urlConfig The absolute or relative URL to load this file from in a config object. + * @param loadEvent The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. + * @param asBlob Load the video as a data blob, or via the Video element? + * @param noAudio Does the video have an audio track? If not you can enable auto-playing on it. + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.VideoFileConfig, urlConfig?: any, loadEvent?: string, asBlob?: boolean, noAudio?: boolean, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + /** + * 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. + */ + load(): void; + + } + + /** + * A single XML File suitable for loading by the Loader. + * + * These are created when you use the Phaser.Loader.LoaderPlugin#xml method and are not typically created directly. + * + * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#xml. + */ + class XMLFile extends Phaser.Loader.File { + /** + * + * @param loader A reference to the Loader that is responsible for this file. + * @param key The key to use for this file, or a file configuration object. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param xhrSettings Extra XHR Settings specifically for this file. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, key: string | Phaser.Types.Loader.FileTypes.XMLFileConfig, url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject); + + /** + * Called automatically by Loader.nextFile. + * This method controls what extra work this File does with its loaded data. + */ + onProcess(): void; + + } + + } + + namespace FileTypesManager { + /** + * Static method called when a LoaderPlugin is created. + * + * Loops through the local types object and injects all of them as + * properties into the LoaderPlugin instance. + * @param loader The LoaderPlugin to install the types into. + */ + function install(loader: Phaser.Loader.LoaderPlugin): void; + + /** + * Static method called directly by the File Types. + * + * The key is a reference to the function used to load the files via the Loader, i.e. `image`. + * @param key The key that will be used as the method name in the LoaderPlugin. + * @param factoryFunction The function that will be called when LoaderPlugin.key is invoked. + */ + function register(key: string, factoryFunction: Function): void; + + /** + * Removed all associated file types. + */ + function destroy(): void; + + } + + /** + * Given a File and a baseURL value this returns the URL the File will use to download from. + * @param file The File object. + * @param baseURL A default base URL. + */ + function GetURL(file: Phaser.Loader.File, baseURL: string): string; + + /** + * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. + * You typically interact with it via `this.load` in your Scene. Scenes can have a `preload` method, which is always + * called before the Scenes `create` method, allowing you to preload assets that the Scene may need. + * + * If you call any `this.load` methods from outside of `Scene.preload` then you need to start the Loader going + * yourself by calling `Loader.start()`. It's only automatically started during the Scene preload. + * + * The Loader uses a combination of tag loading (eg. Audio elements) and XHR and provides progress and completion events. + * Files are loaded in parallel by default. The amount of concurrent connections can be controlled in your Game Configuration. + * + * Once the Loader has started loading you are still able to add files to it. These can be injected as a result of a loader + * event, the type of file being loaded (such as a pack file) or other external events. As long as the Loader hasn't finished + * simply adding a new file to it, while running, will ensure it's added into the current queue. + * + * Every Scene has its own instance of the Loader and they are bound to the Scene in which they are created. However, + * assets loaded by the Loader are placed into global game-level caches. For example, loading an XML file will place that + * file inside `Game.cache.xml`, which is accessible from every Scene in your game, no matter who was responsible + * for loading it. The same is true of Textures. A texture loaded in one Scene is instantly available to all other Scenes + * in your game. + * + * The Loader works by using custom File Types. These are stored in the FileTypesManager, which injects them into the Loader + * when it's instantiated. You can create your own custom file types by extending either the File or MultiFile classes. + * See those files for more details. + */ + class LoaderPlugin extends Phaser.Events.EventEmitter { + /** + * + * @param scene The Scene which owns this Loader instance. + */ + constructor(scene: Phaser.Scene); + + /** + * Adds an Animation JSON Data file, or array of Animation JSON 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.animation('baddieAnims', 'files/BaddieAnims.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 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.animation({ + * key: 'baddieAnims', + * url: 'files/BaddieAnims.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. + * + * Once the file has finished loading it will automatically be passed to the global Animation Managers `fromJSON` method. + * This will parse all of the JSON data and create animation data from it. This process happens at the very end + * of the Loader, once every other file in the load queue has finished. The reason for this is to allow you to load + * both animation data and the images it relies upon in the same load call. + * + * Once the animation data has been parsed you will be able to play animations using that data. + * Please see the Animation Manager `fromJSON` method for more details about the format and playback. + * + * You can also access the raw animation data from its Cache using its key: + * + * ```javascript + * this.load.animation('baddieAnims', 'files/BaddieAnims.json'); + * // and later in your game ... + * var data = this.cache.json.get('baddieAnims'); + * ``` + * + * 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 if you only wanted to create animations from the `boss` data, 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 JSON File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param dataKey When the Animation JSON file loads only this property will be stored in the Cache and used to create animation data. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + animation(key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig | Phaser.Types.Loader.FileTypes.JSONFileConfig[], url?: string, dataKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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, Shoebox and Adobe Flash / Animate. + * 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. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param atlasURL The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings. + */ + atlas(key: string | Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig | Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig[], textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an XML 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.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 atlas data to be provided in an XML file format. + * These files are created by software such as Shoebox and Adobe Flash / Animate. + * + * 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.atlasXML({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * atlasURL: 'images/MainMenu.xml' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig` for more details. + * + * 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.atlasXML('mainmenu', 'images/MainMenu.png', 'images/MainMenu.xml'); + * // 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.atlasXML('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.xml'); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.atlasXML({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * normalMap: 'images/MainMenu-n.png', + * atlasURL: 'images/MainMenu.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 Atlas XML File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param atlasURL The absolute or relative URL to load the texture atlas xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas xml file. Used in replacement of the Loaders default XHR Settings. + */ + atlasXML(key: string | Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig | Phaser.Types.Loader.FileTypes.AtlasXMLFileConfig[], textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param urls The absolute or relative URL to load the audio files from. + * @param config An object containing an `instances` property for HTML5Audio. Defaults to 1. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + audio(key: string | Phaser.Types.Loader.FileTypes.AudioFileConfig | Phaser.Types.Loader.FileTypes.AudioFileConfig[], urls?: string | string[], config?: any, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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 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. + * + * 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. + * @param key The key to use for this file, or a file configuration object, or an array of objects. + * @param jsonURL The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead. + * @param audioURL The absolute or relative URL to load the audio file from. If empty it will be obtained by parsing the JSON file. + * @param audioConfig The audio configuration options. + * @param audioXhrSettings An XHR Settings configuration object for the audio file. Used in replacement of the Loaders default XHR Settings. + * @param jsonXhrSettings An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings. + */ + audioSprite(key: string | Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig | Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig[], jsonURL: string, audioURL?: string | string[], audioConfig?: any, audioXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, jsonXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Binary file, or array of Binary 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.binary('doom', 'files/Doom.wad'); + * } + * ``` + * + * 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 Binary Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Binary 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 Binary Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.binary({ + * key: 'doom', + * url: 'files/Doom.wad', + * dataType: Uint8Array + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.BinaryFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.binary('doom', 'files/Doom.wad'); + * // and later in your game ... + * var data = this.cache.binary.get('doom'); + * ``` + * + * 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 `Data` the final key will be `LEVEL1.Data` and + * this is what you would use to retrieve the text from the Binary 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 "doom" + * and no URL is given then the Loader will set the URL to be "doom.bin". It will always add `.bin` 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 Binary File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param dataType Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + binary(key: string | Phaser.Types.Loader.FileTypes.BinaryFileConfig | Phaser.Types.Loader.FileTypes.BinaryFileConfig[], url?: string, dataType?: any, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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 atlas has finished loading you can use 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. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param textureURL The absolute or relative URL to load the font image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param fontDataURL The absolute or relative URL to load the font xml data file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param textureXhrSettings An XHR Settings configuration object for the font image file. Used in replacement of the Loaders default XHR Settings. + * @param fontDataXhrSettings An XHR Settings configuration object for the font data xml file. Used in replacement of the Loaders default XHR Settings. + */ + bitmapFont(key: string | Phaser.Types.Loader.FileTypes.BitmapFontFileConfig | Phaser.Types.Loader.FileTypes.BitmapFontFileConfig[], textureURL?: string | string[], fontDataURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, fontDataXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a CSS file, or array of CSS 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.css('headers', 'styles/headers.css'); + * } + * ``` + * + * 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.css({ + * key: 'headers', + * url: 'styles/headers.css' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.CSSFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a style DOM element + * via `document.createElement('style')`. It will have its `defer` property set to false and then the + * resulting element will be appended to `document.head`. The CSS styles are then applied to the current document. + * + * 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.css". It will always add `.css` 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 CSS File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.css`, i.e. if `key` was "alien" then the URL will be "alien.css". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + css(key: string | Phaser.Types.Loader.FileTypes.CSSFileConfig | Phaser.Types.Loader.FileTypes.CSSFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a GLSL file, or array of GLSL files, to the current load queue. + * In Phaser 3 GLSL files are just plain Text files at the current moment in time. + * + * 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.glsl('plasma', 'shaders/Plasma.glsl'); + * } + * ``` + * + * 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 Shader Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Shader 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 Shader Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.glsl({ + * key: 'plasma', + * shaderType: 'fragment', + * url: 'shaders/Plasma.glsl' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.GLSLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.glsl('plasma', 'shaders/Plasma.glsl'); + * // and later in your game ... + * var data = this.cache.shader.get('plasma'); + * ``` + * + * 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 `FX.` and the key was `Plasma` the final key will be `FX.Plasma` and + * this is what you would use to retrieve the text from the Shader 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 "plasma" + * and no URL is given then the Loader will set the URL to be "plasma.glsl". It will always add `.glsl` 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 GLSL File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.glsl`, i.e. if `key` was "alien" then the URL will be "alien.glsl". + * @param shaderType The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. Default 'fragment'. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + glsl(key: string | Phaser.Types.Loader.FileTypes.GLSLFileConfig | Phaser.Types.Loader.FileTypes.GLSLFileConfig[], url?: string, shaderType?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an HTML file, or array of HTML 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.html('story', 'files/LoginForm.html'); + * } + * ``` + * + * 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 HTML Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the HTML 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 HTML Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.html({ + * key: 'login', + * url: 'files/LoginForm.html' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.HTMLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.html('login', 'files/LoginForm.html'); + * // and later in your game ... + * var data = this.cache.html.get('login'); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the html from the HTML 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 "story" + * and no URL is given then the Loader will set the URL to be "story.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. + * + * Note: The ability to load this type of file will only be available if the HTML File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + html(key: string | Phaser.Types.Loader.FileTypes.HTMLFileConfig | Phaser.Types.Loader.FileTypes.HTMLFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.html`, i.e. if `key` was "alien" then the URL will be "alien.html". + * @param width The width of the texture the HTML will be rendered to. Default 512. + * @param height The height of the texture the HTML will be rendered to. Default 512. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + htmlTexture(key: string | Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig | Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig[], url?: string, width?: integer, height?: integer, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an Image, or array of Images, 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.image('logo', 'images/phaserLogo.png'); + * } + * ``` + * + * 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. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback + * of animated gifs to Canvas elements. + * + * 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.image({ + * key: 'logo', + * url: 'images/AtariLogo.png' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ImageFileConfig` 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.image('logo', 'images/AtariLogo.png'); + * // and later in your game ... + * this.add.image(x, y, 'logo'); + * ``` + * + * 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.image('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ]); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.image({ + * key: 'logo', + * url: 'images/AtariLogo.png', + * normalMap: 'images/AtariLogo-n.png' + * }); + * ``` + * + * 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 Image File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + image(key: string | Phaser.Types.Loader.FileTypes.ImageFileConfig | Phaser.Types.Loader.FileTypes.ImageFileConfig[], url?: string | string[], xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a JSON file, or array of JSON 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.json('wavedata', 'files/AlienWaveData.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. + * + * 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.json({ + * key: 'wavedata', + * url: 'files/AlienWaveData.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.JSONFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.json('wavedata', 'files/AlienWaveData.json'); + * // and later in your game ... + * var data = this.cache.json.get('wavedata'); + * ``` + * + * 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 JSON File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param dataKey When the JSON file loads only this property will be stored in the Cache. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + json(key: string | Phaser.Types.Loader.FileTypes.JSONFileConfig | Phaser.Types.Loader.FileTypes.JSONFileConfig[], url?: string, dataKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Multi Texture Atlas, or array of multi 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.multiatlas('level1', 'images/Level1.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 as exported from the application Texture Packer, + * version 4.6.3 or above, where you have made sure to use the Phaser 3 Export option. + * + * The way it works internally is that you provide a URL to the JSON file. Phaser then loads this JSON, parses it and + * extracts which texture files it also needs to load to complete the process. If the JSON also defines normal maps, + * Phaser will load those as well. + * + * 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.multiatlas({ + * key: 'level1', + * atlasURL: 'images/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig` 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.multiatlas('level1', 'images/Level1.json'); + * // and later in your game ... + * this.add.image(x, y, 'level1', '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. + * + * Note: The ability to load this type of file will only be available if the Multi Atlas File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param atlasURL The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param path Optional path to use when loading the textures defined in the atlas data. + * @param baseURL Optional Base URL to use when loading the textures defined in the atlas data. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings. + */ + multiatlas(key: string | Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig | Phaser.Types.Loader.FileTypes.MultiAtlasFileConfig[], atlasURL?: string, path?: string, baseURL?: string, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an array of Script files to the current load queue. + * + * The difference between this and the `ScriptFile` file type is that you give an array of scripts to this method, + * and the scripts are then processed _exactly_ in that order. This allows you to load a bunch of scripts that + * may have dependencies on each other without worrying about the async nature of traditional script loading. + * + * 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.scripts('PostProcess', [ + * 'libs/shaders/CopyShader.js', + * 'libs/postprocessing/EffectComposer.js', + * 'libs/postprocessing/RenderPass.js', + * 'libs/postprocessing/MaskPass.js', + * 'libs/postprocessing/ShaderPass.js', + * 'libs/postprocessing/AfterimagePass.js' + * ]); + * } + * ``` + * + * In the code above the script files will all be loaded in parallel but only processed (i.e. invoked) in the exact + * order given in the array. + * + * The files are **not** loaded right away. They are 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 files are queued + * it means you cannot use the files immediately after calling this method, but must wait for the files 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.scripts({ + * key: 'PostProcess', + * url: [ + * 'libs/shaders/CopyShader.js', + * 'libs/postprocessing/EffectComposer.js', + * 'libs/postprocessing/RenderPass.js', + * 'libs/postprocessing/MaskPass.js', + * 'libs/postprocessing/ShaderPass.js', + * 'libs/postprocessing/AfterimagePass.js' + * ] + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.MultiScriptFileConfig` for more details. + * + * Once all the files have finished loading they will automatically be converted into a script element + * via `document.createElement('script')`. They will have their language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. This is done in the exact order the files are specified in the url array. + * + * The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them. + * + * Note: The ability to load this type of file will only be available if the MultiScript File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + * @param extension The default file extension to use if no url is provided. Default 'js'. + * @param xhrSettings Extra XHR Settings specifically for these files. + */ + scripts(key: string | Phaser.Types.Loader.FileTypes.MultiScriptFileConfig | Phaser.Types.Loader.FileTypes.MultiScriptFileConfig[], url?: string[], extension?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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. + * + * 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. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param dataKey When the JSON file loads only this property will be stored in the Cache. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + pack(key: string | Phaser.Types.Loader.FileTypes.PackFileConfig | Phaser.Types.Loader.FileTypes.PackFileConfig[], url?: string, dataKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Plugin Script file, or array of plugin 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.plugin('modplayer', 'plugins/ModPlayer.js'); + * } + * ``` + * + * 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.plugin({ + * key: 'modplayer', + * url: 'plugins/ModPlayer.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.PluginFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. It will then be passed to the Phaser PluginCache.register method. + * + * 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.js". It will always add `.js` 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 Plugin File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, a plugin function. + * @param start Automatically start the plugin after loading? + * @param mapping If this plugin is to be injected into the Scene, this is the property key used. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + plugin(key: string | Phaser.Types.Loader.FileTypes.PluginFileConfig | Phaser.Types.Loader.FileTypes.PluginFileConfig[], url?: string | Function, start?: boolean, mapping?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an external Scene file, or array of Scene 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.sceneFile('Level1', 'src/Level1.js'); + * } + * ``` + * + * 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 Scene Manager upon a successful load. + * + * For a Scene File it's vitally important that the key matches the class name in the JavaScript file. + * + * For example here is the source file: + * + * ```javascript + * class ExternalScene extends Phaser.Scene { + * + * constructor () + * { + * super('myScene'); + * } + * + * } + * ``` + * + * Because the class is called `ExternalScene` that is the exact same key you must use when loading it: + * + * ```javascript + * function preload () + * { + * this.load.sceneFile('ExternalScene', 'src/yourScene.js'); + * } + * ``` + * + * The key that is used within the Scene Manager can either be set to the same, or you can override it in the Scene + * constructor, as we've done in the example above, where the Scene key was changed to `myScene`. + * + * The key should be unique both in terms of files being loaded and Scenes already present in the Scene 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 Scene Manager first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.sceneFile({ + * key: 'Level1', + * url: 'src/Level1.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SceneFileConfig` for more details. + * + * Once the file has finished loading it will be added to the Scene Manager. + * + * ```javascript + * this.load.sceneFile('Level1', 'src/Level1.js'); + * // and later in your game ... + * this.scene.start('Level1'); + * ``` + * + * 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 `WORLD1.` and the key was `Story` the final key will be `WORLD1.Story` and + * this is what you would use to retrieve the text from the Scene 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 "story" + * and no URL is given then the Loader will set the URL to be "story.js". It will always add `.js` 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 Scene File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + sceneFile(key: string | Phaser.Types.Loader.FileTypes.SceneFileConfig | Phaser.Types.Loader.FileTypes.SceneFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Scene Plugin Script file, or array of plugin 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.scenePlugin('ModPlayer', 'plugins/ModPlayer.js', 'modPlayer', 'mods'); + * } + * ``` + * + * 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.scenePlugin({ + * key: 'modplayer', + * url: 'plugins/ModPlayer.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ScenePluginFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. It will then be passed to the Phaser PluginCache.register method. + * + * 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.js". It will always add `.js` 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 Script File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". Or, set to a plugin function. + * @param systemKey If this plugin is to be added to Scene.Systems, this is the property key for it. + * @param sceneKey If this plugin is to be added to the Scene, this is the property key for it. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + scenePlugin(key: string | Phaser.Types.Loader.FileTypes.ScenePluginFileConfig | Phaser.Types.Loader.FileTypes.ScenePluginFileConfig[], url?: string | Function, systemKey?: string, sceneKey?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Script file, or array of Script 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.script('aliens', 'lib/aliens.js'); + * } + * ``` + * + * 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.script({ + * key: 'aliens', + * url: 'lib/aliens.js' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.ScriptFileConfig` for more details. + * + * Once the file has finished loading it will automatically be converted into a script element + * via `document.createElement('script')`. It will have its language set to JavaScript, `defer` set to + * false and then the resulting element will be appended to `document.head`. Any code then in the + * script will be executed. + * + * 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.js". It will always add `.js` 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 Script File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + script(key: string | Phaser.Types.Loader.FileTypes.ScriptFileConfig | Phaser.Types.Loader.FileTypes.ScriptFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Sprite Sheet Image, or array of Sprite Sheet Images, to the current load queue. + * + * The term 'Sprite Sheet' in Phaser means a fixed-size sheet. Where every frame in the sheet is the exact same size, + * and you reference those frames using numbers, not frame names. This is not the same thing as a Texture Atlas, where + * the frames are packed in a way where they take up the least amount of space, and are referenced by their names, + * not numbers. Some articles and software use the term 'Sprite Sheet' to mean Texture Atlas, so please be aware of + * what sort of file you're actually trying to load. + * + * 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); + * } + * ``` + * + * 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. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * If you try to load an animated gif only the first frame will be rendered. Browsers do not natively support playback + * of animated gifs to Canvas elements. + * + * 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.spritesheet({ + * key: 'bot', + * url: 'images/robot.png', + * frameConfig: { + * frameWidth: 32, + * frameHeight: 38, + * startFrame: 0, + * endFrame: 8 + * } + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig` 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.spritesheet('bot', 'images/robot.png', { frameWidth: 32, frameHeight: 38 }); + * // and later in your game ... + * this.add.image(x, y, 'bot', 0); + * ``` + * + * 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 `PLAYER.` and the key was `Running` the final key will be `PLAYER.Running` 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.spritesheet('logo', [ 'images/AtariLogo.png', 'images/AtariLogo-n.png' ], { frameWidth: 256, frameHeight: 80 }); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.spritesheet({ + * key: 'logo', + * url: 'images/AtariLogo.png', + * normalMap: 'images/AtariLogo-n.png', + * frameConfig: { + * frameWidth: 256, + * frameHeight: 80 + * } + * }); + * ``` + * + * 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 Sprite Sheet File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param frameConfig The frame configuration object. At a minimum it should have a `frameWidth` property. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + spritesheet(key: string | Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig | Phaser.Types.Loader.FileTypes.SpriteSheetFileConfig[], url?: string, frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an SVG File, or array of SVG Files, to the current load queue. When the files are loaded they + * will be rendered to bitmap 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.svg('morty', 'images/Morty.svg'); + * } + * ``` + * + * 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.svg({ + * key: 'morty', + * url: 'images/Morty.svg' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.SVGFileConfig` 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.svg('morty', 'images/Morty.svg'); + * // and later in your game ... + * this.add.image(x, y, 'morty'); + * ``` + * + * 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. + * + * You can optionally pass an SVG Resize Configuration object when you load an SVG file. By default the SVG will be rendered to a texture + * at the same size defined in the SVG file attributes. However, this isn't always desirable. You may wish to resize the SVG (either down + * or up) to improve texture clarity, or reduce texture memory consumption. You can either specify an exact width and height to resize + * the SVG to: + * + * ```javascript + * function preload () + * { + * this.load.svg('morty', 'images/Morty.svg', { width: 300, height: 600 }); + * } + * ``` + * + * Or when using a configuration object: + * + * ```javascript + * this.load.svg({ + * key: 'morty', + * url: 'images/Morty.svg', + * svgConfig: { + * width: 300, + * height: 600 + * } + * }); + * ``` + * + * Alternatively, you can just provide a scale factor instead: + * + * ```javascript + * function preload () + * { + * this.load.svg('morty', 'images/Morty.svg', { scale: 2.5 }); + * } + * ``` + * + * Or when using a configuration object: + * + * ```javascript + * this.load.svg({ + * key: 'morty', + * url: 'images/Morty.svg', + * svgConfig: { + * scale: 2.5 + * } + * }); + * ``` + * + * If scale, width and height values are all given, the scale has priority and the width and height values are ignored. + * + * Note: The ability to load this type of file will only be available if the SVG File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.svg`, i.e. if `key` was "alien" then the URL will be "alien.svg". + * @param svgConfig The svg size configuration object. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + svg(key: string | Phaser.Types.Loader.FileTypes.SVGFileConfig | Phaser.Types.Loader.FileTypes.SVGFileConfig[], url?: string, svgConfig?: Phaser.Types.Loader.FileTypes.SVGSizeConfig, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Text file, or array of Text 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.text('story', 'files/IntroStory.txt'); + * } + * ``` + * + * 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 Text Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Text 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.text({ + * key: 'story', + * url: 'files/IntroStory.txt' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TextFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.text('story', 'files/IntroStory.txt'); + * // and later in your game ... + * var data = this.cache.text.get('story'); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Text 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 "story" + * and no URL is given then the Loader will set the URL to be "story.txt". It will always add `.txt` 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 Text File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + text(key: string | Phaser.Types.Loader.FileTypes.TextFileConfig | Phaser.Types.Loader.FileTypes.TextFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a CSV Tilemap file, or array of CSV 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.tilemapCSV('level1', 'maps/Level1.csv'); + * } + * ``` + * + * Tilemap CSV data can be created in a text editor, or a 3rd party app that exports as CSV. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapCSV({ + * key: 'level1', + * url: 'maps/Level1.csv' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapCSV('level1', 'maps/Level1.csv'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.csv". It will always add `.csv` 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 Tilemap CSV File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.csv`, i.e. if `key` was "alien" then the URL will be "alien.csv". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + tilemapCSV(key: string | Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig | Phaser.Types.Loader.FileTypes.TilemapCSVFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an Impact.js Tilemap file, or array of map 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.tilemapImpact('level1', 'maps/Level1.json'); + * } + * ``` + * + * Impact Tilemap data is created the Impact.js Map Editor called Weltmeister. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapImpact({ + * key: 'level1', + * url: 'maps/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapImpact('level1', 'maps/Level1.json'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.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. + * + * Note: The ability to load this type of file will only be available if the Tilemap Impact File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + tilemapImpact(key: string | Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig | Phaser.Types.Loader.FileTypes.TilemapImpactFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Tiled JSON Tilemap file, or array of map 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.tilemapTiledJSON('level1', 'maps/Level1.json'); + * } + * ``` + * + * The Tilemap data is created using the Tiled Map Editor and selecting JSON as the export format. + * + * 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 Tilemap Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the Tilemap 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 Text Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.tilemapTiledJSON({ + * key: 'level1', + * url: 'maps/Level1.json' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.tilemapTiledJSON('level1', 'maps/Level1.json'); + * // and later in your game ... + * var map = this.make.tilemap({ key: 'level1' }); + * ``` + * + * 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 `Story` the final key will be `LEVEL1.Story` and + * this is what you would use to retrieve the text from the Tilemap 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 "level" + * and no URL is given then the Loader will set the URL to be "level.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. + * + * Note: The ability to load this type of file will only be available if the Tilemap JSON File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + tilemapTiledJSON(key: string | Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig | Phaser.Types.Loader.FileTypes.TilemapJSONFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds a Unity YAML 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.unityAtlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.txt'); + * } + * ``` + * + * 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 YAML formatted text file as exported from Unity. + * + * 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.unityAtlas({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * atlasURL: 'images/MainMenu.txt' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig` for more details. + * + * 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.unityAtlas('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.unityAtlas('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.txt'); + * ``` + * + * Or, if you are using a config object use the `normalMap` property: + * + * ```javascript + * this.load.unityAtlas({ + * key: 'mainmenu', + * textureURL: 'images/MainMenu.png', + * normalMap: 'images/MainMenu-n.png', + * atlasURL: 'images/MainMenu.txt' + * }); + * ``` + * + * 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 Unity Atlas File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param textureURL The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param atlasURL The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param textureXhrSettings An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings. + * @param atlasXhrSettings An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings. + */ + unityAtlas(key: string | Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig | Phaser.Types.Loader.FileTypes.UnityAtlasFileConfig[], textureURL?: string | string[], atlasURL?: string, textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject, atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * 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' ], + * asBlob: false, + * 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. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param urls The absolute or relative URL to load the video files from. + * @param loadEvent The load event to listen for when _not_ loading as a blob. Either `loadeddata`, `canplay` or `canplaythrough`. Default 'loadeddata'. + * @param asBlob Load the video as a data blob, or stream it via the Video element? Default false. + * @param noAudio Does the video have an audio track? If not you can enable auto-playing on it. Default false. + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + video(key: string | Phaser.Types.Loader.FileTypes.VideoFileConfig | Phaser.Types.Loader.FileTypes.VideoFileConfig[], urls?: string | string[], loadEvent?: string, asBlob?: boolean, noAudio?: boolean, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * Adds an XML file, or array of XML 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.xml('wavedata', 'files/AlienWaveData.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. + * + * The key must be a unique String. It is used to add the file to the global XML Cache upon a successful load. + * The key should be unique both in terms of files being loaded and files already present in the XML 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 XML Cache first, before loading a new one. + * + * Instead of passing arguments you can pass a configuration object, such as: + * + * ```javascript + * this.load.xml({ + * key: 'wavedata', + * url: 'files/AlienWaveData.xml' + * }); + * ``` + * + * See the documentation for `Phaser.Types.Loader.FileTypes.XMLFileConfig` for more details. + * + * Once the file has finished loading you can access it from its Cache using its key: + * + * ```javascript + * this.load.xml('wavedata', 'files/AlienWaveData.xml'); + * // and later in your game ... + * var data = this.cache.xml.get('wavedata'); + * ``` + * + * 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 XML 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.xml". It will always add `.xml` 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 XML File type has been built into Phaser. + * It is available in the default build but can be excluded from custom builds. + * @param key The key to use for this file, or a file configuration object, or array of them. + * @param url The absolute or relative URL to load this file from. If undefined or `null` it will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param xhrSettings An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings. + */ + xml(key: string | Phaser.Types.Loader.FileTypes.XMLFileConfig | Phaser.Types.Loader.FileTypes.XMLFileConfig[], url?: string, xhrSettings?: Phaser.Types.Loader.XHRSettingsObject): Phaser.Loader.LoaderPlugin; + + /** + * The Scene which owns this Loader instance. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene Systems. + */ + systems: Phaser.Scenes.Systems; + + /** + * A reference to the global Cache Manager. + */ + cacheManager: Phaser.Cache.CacheManager; + + /** + * A reference to the global Texture Manager. + */ + textureManager: Phaser.Textures.TextureManager; + + /** + * A reference to the global Scene Manager. + */ + protected sceneManager: Phaser.Scenes.SceneManager; + + /** + * An optional prefix that is automatically prepended to the start of every file key. + * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. + * You can set this directly, or call `Loader.setPrefix()`. 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. + */ + prefix: string; + + /** + * 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. + */ + path: string; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * + * Useful if allowing the asset base url to be configured outside of the game code. + * + * If you set this property directly then it _must_ end with a "/". Alternatively, call `setBaseURL()` and it'll do it for you. + */ + baseURL: string; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Old browsers limit 6 requests per domain; modern ones, especially those with HTTP/2 don't limit it at all. + * + * The default is 32 but you can change this in your Game Config, or by changing this property before the Loader starts. + */ + maxParallelDownloads: integer; + + /** + * xhr specific global settings (can be overridden on a per-file basis) + */ + xhr: Phaser.Types.Loader.XHRSettingsObject; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + */ + crossOrigin: string; + + /** + * The total number of files to load. It may not always be accurate because you may add to the Loader during the process + * of loading, especially if you load a Pack File. Therefore this value can change, but in most cases remains static. + */ + totalToLoad: integer; + + /** + * The progress of the current load queue, as a float value between 0 and 1. + * This is updated automatically as files complete loading. + * Note that it is possible for this value to go down again if you add content to the current load queue during a load. + */ + progress: number; + + /** + * Files are placed in this Set when they're added to the Loader via `addFile`. + * + * They are moved to the `inflight` Set when they start loading, and assuming a successful + * load, to the `queue` Set for further processing. + * + * By the end of the load process this Set will be empty. + */ + list: Phaser.Structs.Set; + + /** + * Files are stored in this Set while they're in the process of being loaded. + * + * Upon a successful load they are moved to the `queue` Set. + * + * By the end of the load process this Set will be empty. + */ + inflight: Phaser.Structs.Set; + + /** + * Files are stored in this Set while they're being processed. + * + * If the process is successful they are moved to their final destination, which could be + * a Cache or the Texture Manager. + * + * At the end of the load process this Set will be empty. + */ + queue: Phaser.Structs.Set; + + /** + * The total number of files that failed to load during the most recent load. + * This value is reset when you call `Loader.start`. + */ + totalFailed: integer; + + /** + * The total number of files that successfully loaded during the most recent load. + * This value is reset when you call `Loader.start`. + */ + totalComplete: integer; + + /** + * The current state of the Loader. + */ + readonly state: integer; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * + * Useful if allowing the asset base url to be configured outside of the game code. + * + * Once a base URL is set it will affect every file loaded by the Loader from that point on. It does _not_ change any + * file _already_ being loaded. To reset it, call this method with no arguments. + * @param url The URL to use. Leave empty to reset. + */ + setBaseURL(url?: string): Phaser.Loader.LoaderPlugin; + + /** + * 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. + * @param path The path to use. Leave empty to reset. + */ + setPath(path?: string): Phaser.Loader.LoaderPlugin; + + /** + * An optional prefix that is automatically prepended to the start of every file key. + * + * If prefix was `MENU.` and you load an image with the key 'Background' the resulting key would be `MENU.Background`. + * + * Once a prefix 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. + * @param prefix The prefix to use. Leave empty to reset. + */ + setPrefix(prefix?: string): Phaser.Loader.LoaderPlugin; + + /** + * 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 + * @param crossOrigin The value to use for the `crossOrigin` property in the load request. + */ + setCORS(crossOrigin?: string): Phaser.Loader.LoaderPlugin; + + /** + * Adds a file, or array of files, into the load queue. + * + * The file must be an instance of `Phaser.Loader.File`, or a class that extends it. The Loader will check that the key + * used by the file won't conflict with any other key either in the loader, the inflight queue or the target cache. + * If allowed it will then add the file into the pending list, read for the load to start. Or, if the load has already + * started, ready for the next batch of files to be pulled from the list to the inflight queue. + * + * You should not normally call this method directly, but rather use one of the Loader methods like `image` or `atlas`, + * however you can call this as long as the file given to it is well formed. + * @param file The file, or array of files, to be added to the load queue. + */ + addFile(file: Phaser.Loader.File | Phaser.Loader.File[]): void; + + /** + * Checks the key and type of the given file to see if it will conflict with anything already + * in a Cache, the Texture Manager, or the list or inflight queues. + * @param file The file to check the key of. + */ + keyExists(file: Phaser.Loader.File): boolean; + + /** + * Takes a well formed, fully parsed pack file object and adds its entries into the load queue. Usually you do not call + * this method directly, but instead use `Loader.pack` and supply a path to a JSON file that holds the + * pack data. However, if you've got the data prepared you can pass it to this method. + * + * You can also provide an optional key. If you do then it will only add the entries from that part of the pack into + * to the load queue. If not specified it will add all entries it finds. For more details about the pack file format + * see the `LoaderPlugin.pack` method. + * @param data The Pack File data to be parsed and each entry of it to added to the load queue. + * @param packKey An optional key to use from the pack file data. + */ + addPack(data: any, packKey?: string): boolean; + + /** + * Is the Loader actively loading, or processing loaded files? + */ + isLoading(): boolean; + + /** + * Is the Loader ready to start a new load? + */ + isReady(): boolean; + + /** + * Starts the Loader running. This will reset the progress and totals and then emit a `start` event. + * If there is nothing in the queue the Loader will immediately complete, otherwise it will start + * loading the first batch of files. + * + * The Loader is started automatically if the queue is populated within your Scenes `preload` method. + * + * However, outside of this, you need to call this method to start it. + * + * If the Loader is already running this method will simply return. + */ + start(): void; + + /** + * Called automatically during the load process. + * It updates the `progress` value and then emits a progress event, which you can use to + * display a loading bar in your game. + */ + updateProgress(): void; + + /** + * Called automatically during the load process. + */ + update(): void; + + /** + * An internal method called automatically by the XHRLoader belong to a File. + * + * This method will remove the given file from the inflight Set and update the load progress. + * If the file was successful its `onProcess` method is called, otherwise it is added to the delete queue. + * @param file The File that just finished loading, or errored during load. + * @param success `true` if the file loaded successfully, otherwise `false`. + */ + nextFile(file: Phaser.Loader.File, success: boolean): void; + + /** + * An internal method that is called automatically by the File when it has finished processing. + * + * If the process was successful, and the File isn't part of a MultiFile, its `addToCache` method is called. + * + * It this then removed from the queue. If there are no more files to load `loadComplete` is called. + * @param file The file that has finished processing. + */ + fileProcessComplete(file: Phaser.Loader.File): void; + + /** + * Called at the end when the load queue is exhausted and all files have either loaded or errored. + * By this point every loaded file will now be in its associated cache and ready for use. + * + * Also clears down the Sets, puts progress to 1 and clears the deletion queue. + */ + loadComplete(): void; + + /** + * Adds a File into the pending-deletion queue. + * @param file The File to be queued for deletion when the Loader completes. + */ + flagForRemoval(file: Phaser.Loader.File): void; + + /** + * Converts the given JSON data into a file that the browser then prompts you to download so you can save it locally. + * + * The data must be well formed JSON and ready-parsed, not a JavaScript object. + * @param data The JSON data, ready parsed. + * @param filename The name to save the JSON file as. Default file.json. + */ + saveJSON(data: any, filename?: string): Phaser.Loader.LoaderPlugin; + + /** + * 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. + * @param data The data to be saved. Will be passed through URL.createObjectURL. + * @param filename The filename to save the file as. Default file.json. + * @param filetype The file type to use when saving the file. Defaults to JSON. Default application/json. + */ + save(data: any, filename?: string, filetype?: string): Phaser.Loader.LoaderPlugin; + + /** + * Resets the Loader. + * + * This will clear all lists and reset the base URL, path and prefix. + * + * Warning: If the Loader is currently downloading files, or has files in its queue, they will be aborted. + */ + reset(): void; + + } + + /** + * Takes two XHRSettings Objects and creates a new XHRSettings object from them. + * + * The new object is seeded by the values given in the global settings, but any setting in + * the local object overrides the global ones. + * @param global The global XHRSettings object. + * @param local The local XHRSettings object. + */ + function MergeXHRSettings(global: Phaser.Types.Loader.XHRSettingsObject, local: Phaser.Types.Loader.XHRSettingsObject): Phaser.Types.Loader.XHRSettingsObject; + + /** + * A MultiFile is a special kind of parent that contains two, or more, Files as children and looks after + * the loading and processing of them all. It is commonly extended and used as a base class for file types such as AtlasJSON or BitmapFont. + * + * You shouldn't create an instance of a MultiFile directly, but should extend it with your own class, setting a custom type and processing methods. + */ + class MultiFile { + /** + * + * @param loader The Loader that is going to load this File. + * @param type The file type string for sorting within the Loader. + * @param key The key of the file within the loader. + * @param files An array of Files that make-up this MultiFile. + */ + constructor(loader: Phaser.Loader.LoaderPlugin, type: string, key: string, files: Phaser.Loader.File[]); + + /** + * A reference to the Loader that is going to load this file. + */ + loader: Phaser.Loader.LoaderPlugin; + + /** + * The file type string for sorting within the Loader. + */ + type: string; + + /** + * Unique cache key (unique within its file type) + */ + key: string; + + /** + * Array of files that make up this MultiFile. + */ + files: Phaser.Loader.File[]; + + /** + * The completion status of this MultiFile. + */ + complete: boolean; + + /** + * The number of files to load. + */ + pending: integer; + + /** + * The number of files that failed to load. + */ + failed: integer; + + /** + * A storage container for transient data that the loading files need. + */ + config: any; + + /** + * A reference to the Loaders baseURL at the time this MultiFile was created. + * Used to populate child-files. + */ + baseURL: string; + + /** + * A reference to the Loaders path at the time this MultiFile was created. + * Used to populate child-files. + */ + path: string; + + /** + * A reference to the Loaders prefix at the time this MultiFile was created. + * Used to populate child-files. + */ + prefix: string; + + /** + * Checks if this MultiFile is ready to process its children or not. + */ + isReadyToProcess(): boolean; + + /** + * Adds another child to this MultiFile, increases the pending count and resets the completion status. + * @param files The File to add to this MultiFile. + */ + addToMultiFile(files: Phaser.Loader.File): Phaser.Loader.MultiFile; + + /** + * Called by each File when it finishes loading. + * @param file The File that has completed processing. + */ + onFileComplete(file: Phaser.Loader.File): void; + + /** + * Called by each File that fails to load. + * @param file The File that has failed to load. + */ + onFileFailed(file: Phaser.Loader.File): void; + + } + + /** + * Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings + * and starts the download of it. It uses the Files own XHRSettings and merges them + * with the global XHRSettings object to set the xhr values before download. + * @param file The File to download. + * @param globalXHRSettings The global XHRSettings object. + */ + function XHRLoader(file: Phaser.Loader.File, globalXHRSettings: Phaser.Types.Loader.XHRSettingsObject): XMLHttpRequest; + + /** + * Creates an XHRSettings Object with default values. + * @param responseType The responseType, such as 'text'. Default ''. + * @param async Should the XHR request use async or not? Default true. + * @param user Optional username for the XHR request. Default ''. + * @param password Optional password for the XHR request. Default ''. + * @param timeout Optional XHR timeout value. Default 0. + */ + function XHRSettings(responseType?: XMLHttpRequestResponseType, async?: boolean, user?: string, password?: string, timeout?: integer): Phaser.Types.Loader.XHRSettingsObject; + + } + + namespace Math { + namespace Angle { + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + */ + function Between(x1: number, y1: number, x2: number, y2: number): number; + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * Calculates the angle of the vector from the first point to the second point. + * @param point1 The first point. + * @param point2 The second point. + */ + function BetweenPoints(point1: Phaser.Geom.Point | object, point2: Phaser.Geom.Point | object): number; + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * The difference between this method and {@link Phaser.Math.Angle.BetweenPoints} is that this assumes the y coordinate + * travels down the screen. + * @param point1 The first point. + * @param point2 The second point. + */ + function BetweenPointsY(point1: Phaser.Geom.Point | object, point2: Phaser.Geom.Point | object): number; + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and {@link Phaser.Math.Angle.Between} is that this assumes the y coordinate + * travels down the screen. + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + */ + function BetweenY(x1: number, y1: number, x2: number, y2: number): number; + + /** + * Takes an angle in Phasers default clockwise format and converts it so that + * 0 is North, 90 is West, 180 is South and 270 is East, + * therefore running counter-clockwise instead of clockwise. + * + * You can pass in the angle from a Game Object using: + * + * ```javascript + * var converted = CounterClockwise(gameobject.rotation); + * ``` + * + * All values for this function are in radians. + * @param angle The angle to convert, in radians. + */ + function CounterClockwise(angle: number): number; + + /** + * Normalize an angle to the [0, 2pi] range. + * @param angle The angle to normalize, in radians. + */ + function Normalize(angle: number): number; + + /** + * Reverse the given angle. + * @param angle The angle to reverse, in radians. + */ + function Reverse(angle: number): number; + + /** + * Rotates `currentAngle` towards `targetAngle`, taking the shortest rotation distance. The `lerp` argument is the amount to rotate by in this call. + * @param currentAngle The current angle, in radians. + * @param targetAngle The target angle to rotate to, in radians. + * @param lerp The lerp value to add to the current angle. Default 0.05. + */ + function RotateTo(currentAngle: number, targetAngle: number, lerp?: number): number; + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * TODO: Wrap the angles in this function? + * @param angle1 The first angle in the range -180 to 180. + * @param angle2 The second angle in the range -180 to 180. + */ + function ShortestBetween(angle1: number, angle2: number): number; + + /** + * Wrap an angle. + * + * Wraps the angle to a value in the range of -PI to PI. + * @param angle The angle to wrap, in radians. + */ + function Wrap(angle: number): number; + + /** + * Wrap an angle in degrees. + * + * Wraps the angle to a value in the range of -180 to 180. + * @param angle The angle to wrap, in degrees. + */ + function WrapDegrees(angle: number): number; + + } + + /** + * Calculate the mean average of the given values. + * @param values The values to average. + */ + function Average(values: number[]): number; + + /** + * [description] + * @param n [description] + * @param i [description] + */ + function Bernstein(n: number, i: number): number; + + /** + * Compute a random integer between the `min` and `max` values, inclusive. + * @param min The minimum value. + * @param max The maximum value. + */ + function Between(min: integer, max: integer): integer; + + /** + * Calculates a Catmull-Rom value. + * @param t [description] + * @param p0 [description] + * @param p1 [description] + * @param p2 [description] + * @param p3 [description] + */ + function CatmullRom(t: number, p0: number, p1: number, p2: number, p3: number): number; + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * + * The `place` is represented by the power applied to `base` to get that place. + * @param value The value to round. + * @param place The place to round to. Default 0. + * @param base The base to round in. Default is 10 for decimal. Default 10. + */ + function CeilTo(value: number, place?: number, base?: integer): number; + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * @param value The value to be clamped. + * @param min The minimum bounds. + * @param max The maximum bounds. + */ + function Clamp(value: number, min: number, max: number): number; + + /** + * The value of PI * 2. + */ + var PI2: number; + + /** + * The value of PI * 0.5. + */ + var TAU: number; + + /** + * An epsilon value (1.0e-6) + */ + var EPSILON: number; + + /** + * For converting degrees to radians (PI / 180) + */ + var DEG_TO_RAD: number; + + /** + * For converting radians to degrees (180 / PI) + */ + var RAD_TO_DEG: number; + + /** + * An instance of the Random Number Generator. + * This is not set until the Game boots. + */ + var RND: Phaser.Math.RandomDataGenerator; + + /** + * The minimum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + */ + var MIN_SAFE_INTEGER: number; + + /** + * The maximum safe integer this browser supports. + * We use a const for backward compatibility with Internet Explorer. + */ + var MAX_SAFE_INTEGER: number; + + /** + * Convert the given angle from degrees, to the equivalent angle in radians. + * @param degrees The angle (in degrees) to convert to radians. + */ + function DegToRad(degrees: integer): number; + + /** + * Calculates the positive difference of two given numbers. + * @param a The first number in the calculation. + * @param b The second number in the calculation. + */ + function Difference(a: number, b: number): number; + + namespace Distance { + /** + * Calculate the distance between two sets of coordinates (points). + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + */ + function Between(x1: number, y1: number, x2: number, y2: number): number; + + /** + * Calculate the distance between two points. + * @param a The first point. + * @param b The second point. + */ + function BetweenPoints(a: Phaser.Types.Math.Vector2Like, b: Phaser.Types.Math.Vector2Like): number; + + /** + * Calculate the squared distance between two points. + * @param a The first point. + * @param b The second point. + */ + function BetweenPointsSquared(a: Phaser.Types.Math.Vector2Like, b: Phaser.Types.Math.Vector2Like): number; + + /** + * Calculate the Chebyshev distance between two sets of coordinates (points). + * + * Chebyshev distance (or chessboard distance) is the maximum of the horizontal and vertical distances. + * It's the effective distance when movement can be horizontal, vertical, or diagonal. + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + */ + function Chebyshev(x1: number, y1: number, x2: number, y2: number): number; + + /** + * Calculate the distance between two sets of coordinates (points) to the power of `pow`. + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + * @param pow The exponent. + */ + function Power(x1: number, y1: number, x2: number, y2: number, pow: number): number; + + /** + * Calculate the snake distance between two sets of coordinates (points). + * + * Snake distance (rectilinear distance, Manhattan distance) is the sum of the horizontal and vertical distances. + * It's the effective distance when movement is allowed only horizontally or vertically (but not both). + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + */ + function Snake(x1: number, y1: number, x2: number, y2: number): number; + + /** + * Calculate the distance between two sets of coordinates (points), squared. + * @param x1 The x coordinate of the first point. + * @param y1 The y coordinate of the first point. + * @param x2 The x coordinate of the second point. + * @param y2 The y coordinate of the second point. + */ + function Squared(x1: number, y1: number, x2: number, y2: number): number; + + } + + namespace Easing { + namespace Back { + /** + * Back ease-in. + * @param v The value to be tweened. + * @param overshoot The overshoot amount. Default 1.70158. + */ + function In(v: number, overshoot?: number): number; + + /** + * Back ease-in/out. + * @param v The value to be tweened. + * @param overshoot The overshoot amount. Default 1.70158. + */ + function InOut(v: number, overshoot?: number): number; + + /** + * Back ease-out. + * @param v The value to be tweened. + * @param overshoot The overshoot amount. Default 1.70158. + */ + function Out(v: number, overshoot?: number): number; + + } + + namespace Bounce { + /** + * Bounce ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Bounce ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Bounce ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Circular { + /** + * Circular ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Circular ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Circular ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Cubic { + /** + * Cubic ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Cubic ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Cubic ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Elastic { + /** + * Elastic ease-in. + * @param v The value to be tweened. + * @param amplitude The amplitude of the elastic ease. Default 0.1. + * @param period Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. Default 0.1. + */ + function In(v: number, amplitude?: number, period?: number): number; + + /** + * Elastic ease-in/out. + * @param v The value to be tweened. + * @param amplitude The amplitude of the elastic ease. Default 0.1. + * @param period Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. Default 0.1. + */ + function InOut(v: number, amplitude?: number, period?: number): number; + + /** + * Elastic ease-out. + * @param v The value to be tweened. + * @param amplitude The amplitude of the elastic ease. Default 0.1. + * @param period Sets how tight the sine-wave is, where smaller values are tighter waves, which result in more cycles. Default 0.1. + */ + function Out(v: number, amplitude?: number, period?: number): number; + + } + + namespace Expo { + /** + * Exponential ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Exponential ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Exponential ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Linear { + /** + * Linear easing (no variation). + * @param v The value to be tweened. + */ + function Linear(v: number): number; + + } + + namespace Quadratic { + /** + * Quadratic ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Quadratic ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Quadratic ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Quartic { + /** + * Quartic ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Quartic ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Quartic ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Quintic { + /** + * Quintic ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Quintic ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Quintic ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Sine { + /** + * Sinusoidal ease-in. + * @param v The value to be tweened. + */ + function In(v: number): number; + + /** + * Sinusoidal ease-in/out. + * @param v The value to be tweened. + */ + function InOut(v: number): number; + + /** + * Sinusoidal ease-out. + * @param v The value to be tweened. + */ + function Out(v: number): number; + + } + + namespace Stepped { + /** + * Stepped easing. + * @param v The value to be tweened. + * @param steps The number of steps in the ease. Default 1. + */ + function Stepped(v: number, steps?: number): number; + + } + + } + + /** + * Calculates the factorial of a given number for integer values greater than 0. + * @param value A positive integer to calculate the factorial of. + */ + function Factorial(value: number): number; + + /** + * Generate a random floating point number between the two given bounds, minimum inclusive, maximum exclusive. + * @param min The lower bound for the float, inclusive. + * @param max The upper bound for the float exclusive. + */ + function FloatBetween(min: number, max: number): number; + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * + * The `place` is represented by the power applied to `base` to get that place. + * @param value The value to round. + * @param place The place to round to. Default 0. + * @param base The base to round in. Default is 10 for decimal. Default 10. + */ + function FloorTo(value: number, place?: integer, base?: integer): number; + + /** + * Return a value based on the range between `min` and `max` and the percentage given. + * @param percent A value between 0 and 1 representing the percentage. + * @param min The minimum value. + * @param max The maximum value. + */ + function FromPercent(percent: number, min: number, max?: number): number; + + namespace Fuzzy { + /** + * Calculate the fuzzy ceiling of the given value. + * @param value The value. + * @param epsilon The epsilon. Default 0.0001. + */ + function Ceil(value: number, epsilon?: number): number; + + /** + * Check whether the given values are fuzzily equal. + * + * Two numbers are fuzzily equal if their difference is less than `epsilon`. + * @param a The first value. + * @param b The second value. + * @param epsilon The epsilon. Default 0.0001. + */ + function Equal(a: number, b: number, epsilon?: number): boolean; + + /** + * Calculate the fuzzy floor of the given value. + * @param value The value. + * @param epsilon The epsilon. Default 0.0001. + */ + function Floor(value: number, epsilon?: number): number; + + /** + * Check whether `a` is fuzzily greater than `b`. + * + * `a` is fuzzily greater than `b` if it is more than `b - epsilon`. + * @param a The first value. + * @param b The second value. + * @param epsilon The epsilon. Default 0.0001. + */ + function GreaterThan(a: number, b: number, epsilon?: number): boolean; + + /** + * Check whether `a` is fuzzily less than `b`. + * + * `a` is fuzzily less than `b` if it is less than `b + epsilon`. + * @param a The first value. + * @param b The second value. + * @param epsilon The epsilon. Default 0.0001. + */ + function LessThan(a: number, b: number, epsilon?: number): boolean; + + } + + /** + * Calculate a per-ms speed from a distance and time (given in seconds). + * @param distance The distance. + * @param time The time, in seconds. + */ + function GetSpeed(distance: number, time: integer): number; + + namespace Interpolation { + /** + * A bezier interpolation method. + * @param v The input array of values to interpolate between. + * @param k The percentage of interpolation, between 0 and 1. + */ + function Bezier(v: number[], k: number): number; + + /** + * A Catmull-Rom interpolation method. + * @param v The input array of values to interpolate between. + * @param k The percentage of interpolation, between 0 and 1. + */ + function CatmullRom(v: number[], k: number): number; + + /** + * A cubic bezier interpolation method. + * + * https://medium.com/@adrian_cooney/bezier-interpolation-13b68563313a + * @param t The percentage of interpolation, between 0 and 1. + * @param p0 The start point. + * @param p1 The first control point. + * @param p2 The second control point. + * @param p3 The end point. + */ + function CubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + + /** + * A linear interpolation method. + * @param v The input array of values to interpolate between. + * @param k The percentage of interpolation, between 0 and 1. + */ + function Linear(v: number[], k: number): number; + + /** + * A quadratic bezier interpolation method. + * @param t The percentage of interpolation, between 0 and 1. + * @param p0 The start point. + * @param p1 The control point. + * @param p2 The end point. + */ + function QuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + + /** + * A Smoother Step interpolation method. + * @param t The percentage of interpolation, between 0 and 1. + * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. + * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. + */ + function SmootherStep(t: number, min: number, max: number): number; + + /** + * A Smooth Step interpolation method. + * @param t The percentage of interpolation, between 0 and 1. + * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. + * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. + */ + function SmoothStep(t: number, min: number, max: number): number; + + } + + /** + * Check if a given value is an even number. + * @param value The number to perform the check with. + */ + function IsEven(value: number): boolean; + + /** + * Check if a given value is an even number using a strict type check. + * @param value The number to perform the check with. + */ + function IsEvenStrict(value: number): boolean; + + /** + * Calculates a linear (interpolation) value over t. + * @param p0 The first point. + * @param p1 The second point. + * @param t The percentage between p0 and p1 to return, represented as a number between 0 and 1. + */ + function Linear(p0: number, p1: number, t: number): number; + + /** + * A three-dimensional matrix. + * + * Defaults to the identity matrix when instantiated. + */ + class Matrix3 { + /** + * + * @param m Optional Matrix3 to copy values from. + */ + constructor(m?: Phaser.Math.Matrix3); + + /** + * The matrix values. + */ + val: Float32Array; + + /** + * Make a clone of this Matrix3. + */ + clone(): Phaser.Math.Matrix3; + + /** + * This method is an alias for `Matrix3.copy`. + * @param src The Matrix to set the values of this Matrix's from. + */ + set(src: Phaser.Math.Matrix3): Phaser.Math.Matrix3; + + /** + * Copy the values of a given Matrix into this Matrix. + * @param src The Matrix to copy the values from. + */ + copy(src: Phaser.Math.Matrix3): Phaser.Math.Matrix3; + + /** + * Copy the values of a given Matrix4 into this Matrix3. + * @param m The Matrix4 to copy the values from. + */ + fromMat4(m: Phaser.Math.Matrix4): Phaser.Math.Matrix3; + + /** + * Set the values of this Matrix from the given array. + * @param a The array to copy the values from. + */ + fromArray(a: any[]): Phaser.Math.Matrix3; + + /** + * Reset this Matrix to an identity (default) matrix. + */ + identity(): Phaser.Math.Matrix3; + + /** + * Transpose this Matrix. + */ + transpose(): Phaser.Math.Matrix3; + + /** + * Invert this Matrix. + */ + invert(): Phaser.Math.Matrix3; + + /** + * Calculate the adjoint, or adjugate, of this Matrix. + */ + adjoint(): Phaser.Math.Matrix3; + + /** + * Calculate the determinant of this Matrix. + */ + determinant(): number; + + /** + * Multiply this Matrix by the given Matrix. + * @param src The Matrix to multiply this Matrix by. + */ + multiply(src: Phaser.Math.Matrix3): Phaser.Math.Matrix3; + + /** + * Translate this Matrix using the given Vector. + * @param v The Vector to translate this Matrix with. + */ + translate(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix3; + + /** + * Apply a rotation transformation to this Matrix. + * @param rad The angle in radians to rotate by. + */ + rotate(rad: number): Phaser.Math.Matrix3; + + /** + * Apply a scale transformation to this Matrix. + * + * Uses the `x` and `y` components of the given Vector to scale the Matrix. + * @param v The Vector to scale this Matrix with. + */ + scale(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix3; + + /** + * Set the values of this Matrix from the given Quaternion. + * @param q The Quaternion to set the values of this Matrix from. + */ + fromQuat(q: Phaser.Math.Quaternion): Phaser.Math.Matrix3; + + /** + * [description] + * @param m [description] + */ + normalFromMat4(m: Phaser.Math.Matrix4): Phaser.Math.Matrix3; + + } + + /** + * A four-dimensional matrix. + */ + class Matrix4 { + /** + * + * @param m Optional Matrix4 to copy values from. + */ + constructor(m?: Phaser.Math.Matrix4); + + /** + * The matrix values. + */ + val: Float32Array; + + /** + * Make a clone of this Matrix4. + */ + clone(): Phaser.Math.Matrix4; + + /** + * This method is an alias for `Matrix4.copy`. + * @param src The Matrix to set the values of this Matrix's from. + */ + set(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; + + /** + * Copy the values of a given Matrix into this Matrix. + * @param src The Matrix to copy the values from. + */ + copy(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; + + /** + * Set the values of this Matrix from the given array. + * @param a The array to copy the values from. + */ + fromArray(a: any[]): Phaser.Math.Matrix4; + + /** + * Reset this Matrix. + * + * Sets all values to `0`. + */ + zero(): Phaser.Math.Matrix4; + + /** + * Set the `x`, `y` and `z` values of this Matrix. + * @param x The x value. + * @param y The y value. + * @param z The z value. + */ + xyz(x: number, y: number, z: number): Phaser.Math.Matrix4; + + /** + * Set the scaling values of this Matrix. + * @param x The x scaling value. + * @param y The y scaling value. + * @param z The z scaling value. + */ + scaling(x: number, y: number, z: number): Phaser.Math.Matrix4; + + /** + * Reset this Matrix to an identity (default) matrix. + */ + identity(): Phaser.Math.Matrix4; + + /** + * Transpose this Matrix. + */ + transpose(): Phaser.Math.Matrix4; + + /** + * Invert this Matrix. + */ + invert(): Phaser.Math.Matrix4; + + /** + * Calculate the adjoint, or adjugate, of this Matrix. + */ + adjoint(): Phaser.Math.Matrix4; + + /** + * Calculate the determinant of this Matrix. + */ + determinant(): number; + + /** + * Multiply this Matrix by the given Matrix. + * @param src The Matrix to multiply this Matrix by. + */ + multiply(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; + + /** + * [description] + * @param src [description] + */ + multiplyLocal(src: Phaser.Math.Matrix4): Phaser.Math.Matrix4; + + /** + * Translate this Matrix using the given Vector. + * @param v The Vector to translate this Matrix with. + */ + translate(v: Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix4; + + /** + * Translate this Matrix using the given values. + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + translateXYZ(x: number, y: number, z: number): Phaser.Math.Matrix4; + + /** + * Apply a scale transformation to this Matrix. + * + * Uses the `x`, `y` and `z` components of the given Vector to scale the Matrix. + * @param v The Vector to scale this Matrix with. + */ + scale(v: Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Matrix4; + + /** + * Apply a scale transformation to this Matrix. + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + scaleXYZ(x: number, y: number, z: number): Phaser.Math.Matrix4; + + /** + * Derive a rotation matrix around the given axis. + * @param axis The rotation axis. + * @param angle The rotation angle in radians. + */ + makeRotationAxis(axis: Phaser.Math.Vector3 | Phaser.Math.Vector4, angle: number): Phaser.Math.Matrix4; + + /** + * Apply a rotation transformation to this Matrix. + * @param rad The angle in radians to rotate by. + * @param axis The axis to rotate upon. + */ + rotate(rad: number, axis: Phaser.Math.Vector3): Phaser.Math.Matrix4; + + /** + * Rotate this matrix on its X axis. + * @param rad The angle in radians to rotate by. + */ + rotateX(rad: number): Phaser.Math.Matrix4; + + /** + * Rotate this matrix on its Y axis. + * @param rad The angle to rotate by, in radians. + */ + rotateY(rad: number): Phaser.Math.Matrix4; + + /** + * Rotate this matrix on its Z axis. + * @param rad The angle to rotate by, in radians. + */ + rotateZ(rad: number): Phaser.Math.Matrix4; + + /** + * Set the values of this Matrix from the given rotation Quaternion and translation Vector. + * @param q The Quaternion to set rotation from. + * @param v The Vector to set translation from. + */ + fromRotationTranslation(q: Phaser.Math.Quaternion, v: Phaser.Math.Vector3): Phaser.Math.Matrix4; + + /** + * Set the values of this Matrix from the given Quaternion. + * @param q The Quaternion to set the values of this Matrix from. + */ + fromQuat(q: Phaser.Math.Quaternion): Phaser.Math.Matrix4; + + /** + * Generate a frustum matrix with the given bounds. + * @param left The left bound of the frustum. + * @param right The right bound of the frustum. + * @param bottom The bottom bound of the frustum. + * @param top The top bound of the frustum. + * @param near The near bound of the frustum. + * @param far The far bound of the frustum. + */ + frustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Phaser.Math.Matrix4; + + /** + * Generate a perspective projection matrix with the given bounds. + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. Typically viewport width /height. + * @param near Near bound of the frustum. + * @param far Far bound of the frustum. + */ + perspective(fovy: number, aspect: number, near: number, far: number): Phaser.Math.Matrix4; + + /** + * Generate a perspective projection matrix with the given bounds. + * @param width The width of the frustum. + * @param height The height of the frustum. + * @param near Near bound of the frustum. + * @param far Far bound of the frustum. + */ + perspectiveLH(width: number, height: number, near: number, far: number): Phaser.Math.Matrix4; + + /** + * Generate an orthogonal projection matrix with the given bounds. + * @param left The left bound of the frustum. + * @param right The right bound of the frustum. + * @param bottom The bottom bound of the frustum. + * @param top The top bound of the frustum. + * @param near The near bound of the frustum. + * @param far The far bound of the frustum. + */ + ortho(left: number, right: number, bottom: number, top: number, near: number, far: number): Phaser.Math.Matrix4; + + /** + * Generate a look-at matrix with the given eye position, focal point, and up axis. + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up. + */ + lookAt(eye: Phaser.Math.Vector3, center: Phaser.Math.Vector3, up: Phaser.Math.Vector3): Phaser.Math.Matrix4; + + /** + * Set the values of this matrix from the given `yaw`, `pitch` and `roll` values. + * @param yaw [description] + * @param pitch [description] + * @param roll [description] + */ + yawPitchRoll(yaw: number, pitch: number, roll: number): Phaser.Math.Matrix4; + + /** + * Generate a world matrix from the given rotation, position, scale, view matrix and projection matrix. + * @param rotation The rotation of the world matrix. + * @param position The position of the world matrix. + * @param scale The scale of the world matrix. + * @param viewMatrix The view matrix. + * @param projectionMatrix The projection matrix. + */ + setWorldMatrix(rotation: Phaser.Math.Vector3, position: Phaser.Math.Vector3, scale: Phaser.Math.Vector3, viewMatrix?: Phaser.Math.Matrix4, projectionMatrix?: Phaser.Math.Matrix4): Phaser.Math.Matrix4; + + } + + /** + * Add an `amount` to a `value`, limiting the maximum result to `max`. + * @param value The value to add to. + * @param amount The amount to add. + * @param max The maximum value to return. + */ + function MaxAdd(value: number, amount: number, max: number): number; + + /** + * Subtract an `amount` from `value`, limiting the minimum result to `min`. + * @param value The value to subtract from. + * @param amount The amount to subtract. + * @param min The minimum value to return. + */ + function MinSub(value: number, amount: number, min: number): number; + + /** + * Work out what percentage `value` is of the range between `min` and `max`. + * If `max` isn't given then it will return the percentage of `value` to `min`. + * + * You can optionally specify an `upperMax` value, which is a mid-way point in the range that represents 100%, after which the % starts to go down to zero again. + * @param value The value to determine the percentage of. + * @param min The minimum value. + * @param max The maximum value. + * @param upperMax The mid-way point in the range that represents 100%. + */ + function Percent(value: number, min: number, max?: number, upperMax?: number): number; + + namespace Pow2 { + /** + * Returns the nearest power of 2 to the given `value`. + * @param value The value. + */ + function GetNext(value: number): integer; + + /** + * Checks if the given `width` and `height` are a power of two. + * Useful for checking texture dimensions. + * @param width The width. + * @param height The height. + */ + function IsSize(width: number, height: number): boolean; + + /** + * Tests the value and returns `true` if it is a power of two. + * @param value The value to check if it's a power of two. + */ + function IsValue(value: number): boolean; + + } + + /** + * A quaternion. + */ + class Quaternion { + /** + * + * @param x The x component. + * @param y The y component. + * @param z The z component. + * @param w The w component. + */ + constructor(x?: number, y?: number, z?: number, w?: number); + + /** + * The x component of this Quaternion. + */ + x: number; + + /** + * The y component of this Quaternion. + */ + y: number; + + /** + * The z component of this Quaternion. + */ + z: number; + + /** + * The w component of this Quaternion. + */ + w: number; + + /** + * Copy the components of a given Quaternion or Vector into this Quaternion. + * @param src The Quaternion or Vector to copy the components from. + */ + copy(src: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; + + /** + * Set the components of this Quaternion. + * @param x The x component, or an object containing x, y, z, and w components. Default 0. + * @param y The y component. Default 0. + * @param z The z component. Default 0. + * @param w The w component. Default 0. + */ + set(x?: number | object, y?: number, z?: number, w?: number): Phaser.Math.Quaternion; + + /** + * Add a given Quaternion or Vector to this Quaternion. Addition is component-wise. + * @param v The Quaternion or Vector to add to this Quaternion. + */ + add(v: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; + + /** + * Subtract a given Quaternion or Vector from this Quaternion. Subtraction is component-wise. + * @param v The Quaternion or Vector to subtract from this Quaternion. + */ + subtract(v: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; + + /** + * Scale this Quaternion by the given value. + * @param scale The value to scale this Quaternion by. + */ + scale(scale: number): Phaser.Math.Quaternion; + + /** + * Calculate the length of this Quaternion. + */ + length(): number; + + /** + * Calculate the length of this Quaternion squared. + */ + lengthSq(): number; + + /** + * Normalize this Quaternion. + */ + normalize(): Phaser.Math.Quaternion; + + /** + * Calculate the dot product of this Quaternion and the given Quaternion or Vector. + * @param v The Quaternion or Vector to dot product with this Quaternion. + */ + dot(v: Phaser.Math.Quaternion | Phaser.Math.Vector4): number; + + /** + * Linearly interpolate this Quaternion towards the given Quaternion or Vector. + * @param v The Quaternion or Vector to interpolate towards. + * @param t The percentage of interpolation. Default 0. + */ + lerp(v: Phaser.Math.Quaternion | Phaser.Math.Vector4, t?: number): Phaser.Math.Quaternion; + + /** + * [description] + * @param a [description] + * @param b [description] + */ + rotationTo(a: Phaser.Math.Vector3, b: Phaser.Math.Vector3): Phaser.Math.Quaternion; + + /** + * Set the axes of this Quaternion. + * @param view The view axis. + * @param right The right axis. + * @param up The upwards axis. + */ + setAxes(view: Phaser.Math.Vector3, right: Phaser.Math.Vector3, up: Phaser.Math.Vector3): Phaser.Math.Quaternion; + + /** + * Reset this Matrix to an identity (default) Quaternion. + */ + identity(): Phaser.Math.Quaternion; + + /** + * Set the axis angle of this Quaternion. + * @param axis The axis. + * @param rad The angle in radians. + */ + setAxisAngle(axis: Phaser.Math.Vector3, rad: number): Phaser.Math.Quaternion; + + /** + * Multiply this Quaternion by the given Quaternion or Vector. + * @param b The Quaternion or Vector to multiply this Quaternion by. + */ + multiply(b: Phaser.Math.Quaternion | Phaser.Math.Vector4): Phaser.Math.Quaternion; + + /** + * Smoothly linearly interpolate this Quaternion towards the given Quaternion or Vector. + * @param b The Quaternion or Vector to interpolate towards. + * @param t The percentage of interpolation. + */ + slerp(b: Phaser.Math.Quaternion | Phaser.Math.Vector4, t: number): Phaser.Math.Quaternion; + + /** + * Invert this Quaternion. + */ + invert(): Phaser.Math.Quaternion; + + /** + * Convert this Quaternion into its conjugate. + * + * Sets the x, y and z components. + */ + conjugate(): Phaser.Math.Quaternion; + + /** + * Rotate this Quaternion on the X axis. + * @param rad The rotation angle in radians. + */ + rotateX(rad: number): Phaser.Math.Quaternion; + + /** + * Rotate this Quaternion on the Y axis. + * @param rad The rotation angle in radians. + */ + rotateY(rad: number): Phaser.Math.Quaternion; + + /** + * Rotate this Quaternion on the Z axis. + * @param rad The rotation angle in radians. + */ + rotateZ(rad: number): Phaser.Math.Quaternion; + + /** + * Create a unit (or rotation) Quaternion from its x, y, and z components. + * + * Sets the w component. + */ + calculateW(): Phaser.Math.Quaternion; + + /** + * Convert the given Matrix into this Quaternion. + * @param mat The Matrix to convert from. + */ + fromMat3(mat: Phaser.Math.Matrix3): Phaser.Math.Quaternion; + + } + + /** + * Convert the given angle in radians, to the equivalent angle in degrees. + * @param radians The angle in radians to convert ot degrees. + */ + function RadToDeg(radians: number): integer; + + /** + * 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 { + /** + * + * @param seeds The seeds to use for the random number generator. + */ + constructor(seeds?: string | string[]); + + /** + * Signs to choose from. + */ + signs: number[]; + + /** + * Initialize the state of the random data generator. + * @param seeds The seeds to initialize the random data generator with. + */ + init(seeds: string | string[]): void; + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * @param seeds The array of seeds: the `toString()` of each value is used. + */ + sow(seeds: string[]): void; + + /** + * Returns a random integer between 0 and 2^32. + */ + integer(): number; + + /** + * Returns a random real number between 0 and 1. + */ + frac(): number; + + /** + * Returns a random real number between 0 and 2^32. + */ + real(): number; + + /** + * Returns a random integer between and including min and max. + * @param min The minimum value in the range. + * @param max The maximum value in the range. + */ + integerInRange(min: number, max: number): number; + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * @param min The minimum value in the range. + * @param max The maximum value in the range. + */ + between(min: number, max: number): number; + + /** + * Returns a random real number between min and max. + * @param min The minimum value in the range. + * @param max The maximum value in the range. + */ + realInRange(min: number, max: number): number; + + /** + * Returns a random real number between -1 and 1. + */ + normal(): number; + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + */ + uuid(): string; + + /** + * Returns a random element from within the given array. + * @param array The array to pick a random element from. + */ + pick(array: T[]): T; + + /** + * Returns a sign to be used with multiplication operator. + */ + sign(): number; + + /** + * Returns a random element from within the given array, favoring the earlier entries. + * @param array The array to pick a random element from. + */ + weightedPick(array: T[]): T; + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * @param min The minimum value in the range. + * @param max The maximum value in the range. + */ + timestamp(min: number, max: number): number; + + /** + * Returns a random angle between -180 and 180. + */ + angle(): number; + + /** + * Returns a random rotation in radians, between -3.141 and 3.141 + */ + rotation(): number; + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * @param state Generator state to be set. + */ + state(state?: string): string; + + /** + * Shuffles the given array, using the current seed. + * @param array The array to be shuffled. + */ + shuffle(array?: T[]): T[]; + + } + + /** + * Compute a random unit vector. + * + * Computes random values for the given vector between -1 and 1 that can be used to represent a direction. + * + * Optionally accepts a scale value to scale the resulting vector by. + * @param vector The Vector to compute random values for. + * @param scale The scale of the random values. Default 1. + */ + function RandomXY(vector: Phaser.Math.Vector2, scale?: number): Phaser.Math.Vector2; + + /** + * Compute a random position vector in a spherical area, optionally defined by the given radius. + * @param vec3 The Vector to compute random values for. + * @param radius The radius. Default 1. + */ + function RandomXYZ(vec3: Phaser.Math.Vector3, radius?: number): Phaser.Math.Vector3; + + /** + * Compute a random four-dimensional vector. + * @param vec4 The Vector to compute random values for. + * @param scale The scale of the random values. Default 1. + */ + function RandomXYZW(vec4: Phaser.Math.Vector4, scale?: number): Phaser.Math.Vector4; + + /** + * Rotate a given point by a given angle around the origin (0, 0), in an anti-clockwise direction. + * @param point The point to be rotated. + * @param angle The angle to be rotated by in an anticlockwise direction. + */ + function Rotate(point: Phaser.Geom.Point | object, angle: number): Phaser.Geom.Point; + + /** + * Rotate a `point` around `x` and `y` by the given `angle`. + * @param point The point to be rotated. + * @param x The horizontal coordinate to rotate around. + * @param y The vertical coordinate to rotate around. + * @param angle The angle of rotation in radians. + */ + function RotateAround(point: Phaser.Geom.Point | object, x: number, y: number, angle: number): Phaser.Geom.Point; + + /** + * Rotate a `point` around `x` and `y` by the given `angle` and `distance`. + * @param point The point to be rotated. + * @param x The horizontal coordinate to rotate around. + * @param y The vertical coordinate to rotate around. + * @param angle The angle of rotation in radians. + * @param distance The distance from (x, y) to place the point at. + */ + function RotateAroundDistance(point: Phaser.Geom.Point | object, x: number, y: number, angle: number, distance: number): Phaser.Geom.Point; + + /** + * Rotates a vector in place by axis angle. + * + * This is the same as transforming a point by an + * axis-angle quaternion, but it has higher precision. + * @param vec The vector to be rotated. + * @param axis The axis to rotate around. + * @param radians The angle of rotation in radians. + */ + function RotateVec3(vec: Phaser.Math.Vector3, axis: Phaser.Math.Vector3, radians: number): Phaser.Math.Vector3; + + /** + * Round a given number so it is further away from zero. That is, positive numbers are rounded up, and negative numbers are rounded down. + * @param value The number to round. + */ + function RoundAwayFromZero(value: number): number; + + /** + * Round a value to the given precision. + * + * For example: + * + * ```javascript + * RoundTo(123.456, 0) = 123 + * RoundTo(123.456, 1) = 120 + * RoundTo(123.456, 2) = 100 + * ``` + * + * To round the decimal, i.e. to round to precision, pass in a negative `place`: + * + * ```javascript + * RoundTo(123.456789, 0) = 123 + * RoundTo(123.456789, -1) = 123.5 + * RoundTo(123.456789, -2) = 123.46 + * RoundTo(123.456789, -3) = 123.457 + * ``` + * @param value The value to round. + * @param place The place to round to. Positive to round the units, negative to round the decimal. Default 0. + * @param base The base to round in. Default is 10 for decimal. Default 10. + */ + function RoundTo(value: number, place?: integer, base?: integer): number; + + /** + * Generate a series of sine and cosine values. + * @param length The number of values to generate. + * @param sinAmp The sine value amplitude. Default 1. + * @param cosAmp The cosine value amplitude. Default 1. + * @param frequency The frequency of the values. Default 1. + */ + function SinCosTableGenerator(length: number, sinAmp?: number, cosAmp?: number, frequency?: number): Phaser.Types.Math.SinCosTable; + + /** + * 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}. + * @param x The input value. + * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. + * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. + */ + function SmootherStep(x: number, min: number, max: number): number; + + /** + * 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. + * @param x The input value. + * @param min The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'. + * @param max The maximum value, also known as the 'right edge', assumed greater than the 'left edge'. + */ + function SmoothStep(x: number, min: number, max: number): number; + + namespace Snap { + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `15`. + * As will `14` snap to `15`... but `16` will snap to `20`. + * @param value The value to snap. + * @param gap The interval gap of the grid. + * @param start Optional starting offset for gap. Default 0. + * @param divide If `true` it will divide the snapped value by the gap before returning. Default false. + */ + function Ceil(value: number, gap: number, start?: number, divide?: boolean): number; + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10`. + * As will `14` snap to `10`... but `16` will snap to `15`. + * @param value The value to snap. + * @param gap The interval gap of the grid. + * @param start Optional starting offset for gap. Default 0. + * @param divide If `true` it will divide the snapped value by the gap before returning. Default false. + */ + function Floor(value: number, gap: number, start?: number, divide?: boolean): number; + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of `5` and a position of `12`... you will snap to `10` whereas `14` will snap to `15`. + * @param value The value to snap. + * @param gap The interval gap of the grid. + * @param start Optional starting offset for gap. Default 0. + * @param divide If `true` it will divide the snapped value by the gap before returning. Default false. + */ + function To(value: number, gap: number, start?: number, divide?: boolean): number; + + } + + /** + * Returns a Vector2 containing the x and y position of the given index in a `width` x `height` sized grid. + * + * For example, in a 6 x 4 grid, index 16 would equal x: 4 y: 2. + * + * If the given index is out of range an empty Vector2 is returned. + * @param index The position within the grid to get the x/y value for. + * @param width The width of the grid. + * @param height The height of the grid. + * @param out An optional Vector2 to store the result in. If not given, a new Vector2 instance will be created. + */ + function ToXY(index: integer, width: integer, height: integer, out?: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Takes the `x` and `y` coordinates and transforms them into the same space as + * defined by the position, rotation and scale values. + * @param x The x coordinate to be transformed. + * @param y The y coordinate to be transformed. + * @param positionX Horizontal position of the transform point. + * @param positionY Vertical position of the transform point. + * @param rotation Rotation of the transform point, in radians. + * @param scaleX Horizontal scale of the transform point. + * @param scaleY Vertical scale of the transform point. + * @param output The output vector, point or object for the translated coordinates. + */ + function TransformXY(x: number, y: number, positionX: number, positionY: number, rotation: number, scaleX: number, scaleY: number, output?: Phaser.Math.Vector2 | Phaser.Geom.Point | object): Phaser.Math.Vector2 | Phaser.Geom.Point | object; + + /** + * A representation of a vector in 2D space. + * + * A two-component vector. + */ + class Vector2 { + /** + * + * @param x The x component, or an object with `x` and `y` properties. + * @param y The y component. + */ + constructor(x?: number | Phaser.Types.Math.Vector2Like, y?: number); + + /** + * The x component of this Vector. + */ + x: number; + + /** + * The y component of this Vector. + */ + y: number; + + /** + * Make a clone of this Vector2. + */ + clone(): Phaser.Math.Vector2; + + /** + * Copy the components of a given Vector into this Vector. + * @param src The Vector to copy the components from. + */ + copy(src: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Set the component values of this Vector from a given Vector2Like object. + * @param obj The object containing the component values to set for this Vector. + */ + setFromObject(obj: Phaser.Types.Math.Vector2Like): Phaser.Math.Vector2; + + /** + * Set the `x` and `y` components of the this Vector to the given `x` and `y` values. + * @param x The x value to set for this Vector. + * @param y The y value to set for this Vector. Default x. + */ + set(x: number, y?: number): Phaser.Math.Vector2; + + /** + * This method is an alias for `Vector2.set`. + * @param x The x value to set for this Vector. + * @param y The y value to set for this Vector. Default x. + */ + setTo(x: number, y?: number): Phaser.Math.Vector2; + + /** + * Sets the `x` and `y` values of this object from a given polar coordinate. + * @param azimuth The angular coordinate, in radians. + * @param radius The radial coordinate (length). Default 1. + */ + setToPolar(azimuth: number, radius?: number): Phaser.Math.Vector2; + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict equality check against each Vector's components. + * @param v The vector to compare with this Vector. + */ + equals(v: Phaser.Math.Vector2): boolean; + + /** + * Calculate the angle between this Vector and the positive x-axis, in radians. + */ + angle(): number; + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * @param src The Vector to add to this Vector. + */ + add(src: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * @param src The Vector to subtract from this Vector. + */ + subtract(src: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * @param src The Vector to multiply this Vector by. + */ + multiply(src: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Scale this Vector by the given value. + * @param value The value to scale this Vector by. + */ + scale(value: number): Phaser.Math.Vector2; + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * @param src The Vector to divide this Vector by. + */ + divide(src: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Negate the `x` and `y` components of this Vector. + */ + negate(): Phaser.Math.Vector2; + + /** + * Calculate the distance between this Vector and the given Vector. + * @param src The Vector to calculate the distance to. + */ + distance(src: Phaser.Math.Vector2): number; + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * @param src The Vector to calculate the distance to. + */ + distanceSq(src: Phaser.Math.Vector2): number; + + /** + * Calculate the length (or magnitude) of this Vector. + */ + length(): number; + + /** + * Calculate the length of this Vector squared. + */ + lengthSq(): number; + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + */ + normalize(): Phaser.Math.Vector2; + + /** + * Right-hand normalize (make unit length) this Vector. + */ + normalizeRightHand(): Phaser.Math.Vector2; + + /** + * Calculate the dot product of this Vector and the given Vector. + * @param src The Vector2 to dot product with this Vector2. + */ + dot(src: Phaser.Math.Vector2): number; + + /** + * Calculate the cross product of this Vector and the given Vector. + * @param src The Vector2 to cross with this Vector2. + */ + cross(src: Phaser.Math.Vector2): number; + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * @param src The Vector2 to interpolate towards. + * @param t The interpolation percentage, between 0 and 1. Default 0. + */ + lerp(src: Phaser.Math.Vector2, t?: number): Phaser.Math.Vector2; + + /** + * Transform this Vector with the given Matrix. + * @param mat The Matrix3 to transform this Vector2 with. + */ + transformMat3(mat: Phaser.Math.Matrix3): Phaser.Math.Vector2; + + /** + * Transform this Vector with the given Matrix. + * @param mat The Matrix4 to transform this Vector2 with. + */ + transformMat4(mat: Phaser.Math.Matrix4): Phaser.Math.Vector2; + + /** + * Make this Vector the zero vector (0, 0). + */ + reset(): Phaser.Math.Vector2; + + /** + * A static zero Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly ZERO: Phaser.Math.Vector2; + + /** + * A static right Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly RIGHT: Phaser.Math.Vector2; + + /** + * A static left Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly LEFT: Phaser.Math.Vector2; + + /** + * A static up Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly UP: Phaser.Math.Vector2; + + /** + * A static down Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly DOWN: Phaser.Math.Vector2; + + /** + * A static one Vector2 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly ONE: Phaser.Math.Vector2; + + } + + /** + * A representation of a vector in 3D space. + * + * A three-component vector. + */ + class Vector3 { + /** + * + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + constructor(x?: number, y?: number, z?: number); + + /** + * The x component of this Vector. + */ + x: number; + + /** + * The y component of this Vector. + */ + y: number; + + /** + * The z component of this Vector. + */ + z: number; + + /** + * Set this Vector to point up. + * + * Sets the y component of the vector to 1, and the others to 0. + */ + up(): Phaser.Math.Vector3; + + /** + * Make a clone of this Vector3. + */ + clone(): Phaser.Math.Vector3; + + /** + * Calculate the cross (vector) product of two given Vectors. + * @param a The first Vector to multiply. + * @param b The second Vector to multiply. + */ + crossVectors(a: Phaser.Math.Vector3, b: Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict equality check against each Vector's components. + * @param v The Vector3 to compare against. + */ + equals(v: Phaser.Math.Vector3): boolean; + + /** + * Copy the components of a given Vector into this Vector. + * @param src The Vector to copy the components from. + */ + copy(src: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Set the `x`, `y`, and `z` components of this Vector to the given `x`, `y`, and `z` values. + * @param x The x value to set for this Vector, or an object containing x, y and z components. + * @param y The y value to set for this Vector. + * @param z The z value to set for this Vector. + */ + set(x: number | object, y?: number, z?: number): Phaser.Math.Vector3; + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * @param v The Vector to add to this Vector. + */ + add(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * @param v The Vector to subtract from this Vector. + */ + subtract(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * @param v The Vector to multiply this Vector by. + */ + multiply(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Scale this Vector by the given value. + * @param scale The value to scale this Vector by. + */ + scale(scale: number): Phaser.Math.Vector3; + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * @param v The Vector to divide this Vector by. + */ + divide(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Negate the `x`, `y` and `z` components of this Vector. + */ + negate(): Phaser.Math.Vector3; + + /** + * Calculate the distance between this Vector and the given Vector. + * @param v The Vector to calculate the distance to. + */ + distance(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): number; + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * @param v The Vector to calculate the distance to. + */ + distanceSq(v: Phaser.Math.Vector2 | Phaser.Math.Vector3): number; + + /** + * Calculate the length (or magnitude) of this Vector. + */ + length(): number; + + /** + * Calculate the length of this Vector squared. + */ + lengthSq(): number; + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + */ + normalize(): Phaser.Math.Vector3; + + /** + * Calculate the dot product of this Vector and the given Vector. + * @param v The Vector3 to dot product with this Vector3. + */ + dot(v: Phaser.Math.Vector3): number; + + /** + * Calculate the cross (vector) product of this Vector (which will be modified) and the given Vector. + * @param v The Vector to cross product with. + */ + cross(v: Phaser.Math.Vector3): Phaser.Math.Vector3; + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * @param v The Vector3 to interpolate towards. + * @param t The interpolation percentage, between 0 and 1. Default 0. + */ + lerp(v: Phaser.Math.Vector3, t?: number): Phaser.Math.Vector3; + + /** + * Transform this Vector with the given Matrix. + * @param mat The Matrix3 to transform this Vector3 with. + */ + transformMat3(mat: Phaser.Math.Matrix3): Phaser.Math.Vector3; + + /** + * Transform this Vector with the given Matrix. + * @param mat The Matrix4 to transform this Vector3 with. + */ + transformMat4(mat: Phaser.Math.Matrix4): Phaser.Math.Vector3; + + /** + * Transforms the coordinates of this Vector3 with the given Matrix4. + * @param mat The Matrix4 to transform this Vector3 with. + */ + transformCoordinates(mat: Phaser.Math.Matrix4): Phaser.Math.Vector3; + + /** + * Transform this Vector with the given Quaternion. + * @param q The Quaternion to transform this Vector with. + */ + transformQuat(q: Phaser.Math.Quaternion): Phaser.Math.Vector3; + + /** + * Multiplies this Vector3 by the specified matrix, applying a W divide. This is useful for projection, + * e.g. unprojecting a 2D point into 3D space. + * @param mat The Matrix4 to multiply this Vector3 with. + */ + project(mat: Phaser.Math.Matrix4): Phaser.Math.Vector3; + + /** + * Unproject this point from 2D space to 3D space. + * The point should have its x and y properties set to + * 2D screen space, and the z either at 0 (near plane) + * or 1 (far plane). The provided matrix is assumed to already + * be combined, i.e. projection * view * model. + * + * After this operation, this vector's (x, y, z) components will + * represent the unprojected 3D coordinate. + * @param viewport Screen x, y, width and height in pixels. + * @param invProjectionView Combined projection and view matrix. + */ + unproject(viewport: Phaser.Math.Vector4, invProjectionView: Phaser.Math.Matrix4): Phaser.Math.Vector3; + + /** + * Make this Vector the zero vector (0, 0, 0). + */ + reset(): Phaser.Math.Vector3; + + /** + * A static zero Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly ZERO: Phaser.Math.Vector3; + + /** + * A static right Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly RIGHT: Phaser.Math.Vector3; + + /** + * A static left Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly LEFT: Phaser.Math.Vector3; + + /** + * A static up Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly UP: Phaser.Math.Vector3; + + /** + * A static down Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly DOWN: Phaser.Math.Vector3; + + /** + * A static forward Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly FORWARD: Phaser.Math.Vector3; + + /** + * A static back Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly BACK: Phaser.Math.Vector3; + + /** + * A static one Vector3 for use by reference. + * + * This constant is meant for comparison operations and should not be modified directly. + */ + static readonly ONE: Phaser.Math.Vector3; + + } + + /** + * A representation of a vector in 4D space. + * + * A four-component vector. + */ + class Vector4 { + /** + * + * @param x The x component. + * @param y The y component. + * @param z The z component. + * @param w The w component. + */ + constructor(x?: number, y?: number, z?: number, w?: number); + + /** + * The x component of this Vector. + */ + x: number; + + /** + * The y component of this Vector. + */ + y: number; + + /** + * The z component of this Vector. + */ + z: number; + + /** + * The w component of this Vector. + */ + w: number; + + /** + * Make a clone of this Vector4. + */ + clone(): Phaser.Math.Vector4; + + /** + * Copy the components of a given Vector into this Vector. + * @param src The Vector to copy the components from. + */ + copy(src: Phaser.Math.Vector4): Phaser.Math.Vector4; + + /** + * Check whether this Vector is equal to a given Vector. + * + * Performs a strict quality check against each Vector's components. + * @param v The vector to check equality with. + */ + equals(v: Phaser.Math.Vector4): boolean; + + /** + * Set the `x`, `y`, `z` and `w` components of the this Vector to the given `x`, `y`, `z` and `w` values. + * @param x The x value to set for this Vector, or an object containing x, y, z and w components. + * @param y The y value to set for this Vector. + * @param z The z value to set for this Vector. + * @param w The z value to set for this Vector. + */ + set(x: number | object, y: number, z: number, w: number): Phaser.Math.Vector4; + + /** + * Add a given Vector to this Vector. Addition is component-wise. + * @param v The Vector to add to this Vector. + */ + add(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; + + /** + * Subtract the given Vector from this Vector. Subtraction is component-wise. + * @param v The Vector to subtract from this Vector. + */ + subtract(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; + + /** + * Scale this Vector by the given value. + * @param scale The value to scale this Vector by. + */ + scale(scale: number): Phaser.Math.Vector4; + + /** + * Calculate the length (or magnitude) of this Vector. + */ + length(): number; + + /** + * Calculate the length of this Vector squared. + */ + lengthSq(): number; + + /** + * Normalize this Vector. + * + * Makes the vector a unit length vector (magnitude of 1) in the same direction. + */ + normalize(): Phaser.Math.Vector4; + + /** + * Calculate the dot product of this Vector and the given Vector. + * @param v The Vector4 to dot product with this Vector4. + */ + dot(v: Phaser.Math.Vector4): number; + + /** + * Linearly interpolate between this Vector and the given Vector. + * + * Interpolates this Vector towards the given Vector. + * @param v The Vector4 to interpolate towards. + * @param t The interpolation percentage, between 0 and 1. Default 0. + */ + lerp(v: Phaser.Math.Vector4, t?: number): Phaser.Math.Vector4; + + /** + * Perform a component-wise multiplication between this Vector and the given Vector. + * + * Multiplies this Vector by the given Vector. + * @param v The Vector to multiply this Vector by. + */ + multiply(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; + + /** + * Perform a component-wise division between this Vector and the given Vector. + * + * Divides this Vector by the given Vector. + * @param v The Vector to divide this Vector by. + */ + divide(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): Phaser.Math.Vector4; + + /** + * Calculate the distance between this Vector and the given Vector. + * @param v The Vector to calculate the distance to. + */ + distance(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): number; + + /** + * Calculate the distance between this Vector and the given Vector, squared. + * @param v The Vector to calculate the distance to. + */ + distanceSq(v: Phaser.Math.Vector2 | Phaser.Math.Vector3 | Phaser.Math.Vector4): number; + + /** + * Negate the `x`, `y`, `z` and `w` components of this Vector. + */ + negate(): Phaser.Math.Vector4; + + /** + * Transform this Vector with the given Matrix. + * @param mat The Matrix4 to transform this Vector4 with. + */ + transformMat4(mat: Phaser.Math.Matrix4): Phaser.Math.Vector4; + + /** + * Transform this Vector with the given Quaternion. + * @param q The Quaternion to transform this Vector with. + */ + transformQuat(q: Phaser.Math.Quaternion): Phaser.Math.Vector4; + + /** + * Make this Vector the zero vector (0, 0, 0, 0). + */ + reset(): Phaser.Math.Vector4; + + } + + /** + * Checks if the two values are within the given `tolerance` of each other. + * @param a The first value to use in the calculation. + * @param b The second value to use in the calculation. + * @param tolerance The tolerance. Anything equal to or less than this value is considered as being within range. + */ + function Within(a: number, b: number, tolerance: number): boolean; + + /** + * Wrap the given `value` between `min` and `max. + * @param value The value to wrap. + * @param min The minimum value. + * @param max The maximum value. + */ + function Wrap(value: number, min: number, max: number): number; + + } + + /** + * The root types namespace. + */ + namespace Types { + namespace Actions { + type CallCallback = (item: Phaser.GameObjects.GameObject)=>void; + + type GridAlignConfig = { + /** + * The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity. + * If both this value and height are set to -1 then this value overrides it and the `height` value is ignored. + */ + width?: integer; + /** + * The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity. + * If both this value and `width` are set to -1 then `width` overrides it and this value is ignored. + */ + height?: integer; + /** + * The width of the cell, in pixels, in which the item is positioned. + */ + cellWidth?: integer; + /** + * The height of the cell, in pixels, in which the item is positioned. + */ + cellHeight?: integer; + /** + * The alignment position. One of the Phaser.Display.Align consts such as `TOP_LEFT` or `RIGHT_CENTER`. + */ + position?: integer; + /** + * Optionally place the top-left of the final grid at this coordinate. + */ + x?: number; + /** + * Optionally place the top-left of the final grid at this coordinate. + */ + y?: number; + }; + + } + + namespace Animations { + type Animation = { + /** + * The key that the animation will be associated with. i.e. sprite.animations.play(key) + */ + key?: string; + /** + * An object containing data used to generate the frames for the animation + */ + frames?: Phaser.Types.Animations.AnimationFrame[]; + /** + * The key of the texture all frames of the animation will use. Can be overridden on a per frame basis. + */ + defaultTextureKey?: string; + /** + * The frame rate of playback in frames per second (default 24 if duration is null) + */ + frameRate?: integer; + /** + * How long the animation should play for in milliseconds. If not given its derived from frameRate. + */ + duration?: integer; + /** + * Skip frames if the time lags, or always advanced anyway? + */ + skipMissedFrames?: boolean; + /** + * Delay before starting playback. Value given in milliseconds. + */ + delay?: integer; + /** + * Number of times to repeat the animation (-1 for infinity) + */ + repeat?: integer; + /** + * Delay before the animation repeats. Value given in milliseconds. + */ + repeatDelay?: integer; + /** + * Should the animation yoyo? (reverse back down to the start) before repeating? + */ + yoyo?: boolean; + /** + * Should sprite.visible = true when the animation starts to play? + */ + showOnStart?: boolean; + /** + * Should sprite.visible = false when the animation finishes? + */ + hideOnComplete?: boolean; + }; + + type AnimationFrame = { + /** + * The key that the animation will be associated with. i.e. sprite.animations.play(key) + */ + key: string; + /** + * [description] + */ + frame: string | number; + /** + * [description] + */ + duration?: number; + /** + * [description] + */ + visible?: boolean; + }; + + type GenerateFrameNames = { + /** + * The string to append to every resulting frame name if using a range or an array of `frames`. + */ + prefix?: string; + /** + * If `frames` is not provided, the number of the first frame to return. + */ + start?: integer; + /** + * If `frames` is not provided, the number of the last frame to return. + */ + end?: integer; + /** + * The string to append to every resulting frame name if using a range or an array of `frames`. + */ + suffix?: string; + /** + * The minimum expected lengths of each resulting frame's number. Numbers will be left-padded with zeroes until they are this long, then prepended and appended to create the resulting frame name. + */ + zeroPad?: integer; + /** + * The array to append the created configuration objects to. + */ + outputArray?: Phaser.Types.Animations.AnimationFrame[]; + /** + * If provided as an array, the range defined by `start` and `end` will be ignored and these frame numbers will be used. + */ + frames?: boolean | integer[]; + }; + + type GenerateFrameNumbers = { + /** + * The starting frame of the animation. + */ + start?: integer; + /** + * The ending frame of the animation. + */ + end?: integer; + /** + * A frame to put at the beginning of the animation, before `start` or `outputArray` or `frames`. + */ + first?: boolean | integer; + /** + * An array to concatenate the output onto. + */ + outputArray?: Phaser.Types.Animations.AnimationFrame[]; + /** + * A custom sequence of frames. + */ + frames?: boolean | integer[]; + }; + + type JSONAnimation = { + /** + * The key that the animation will be associated with. i.e. sprite.animations.play(key) + */ + key: string; + /** + * A frame based animation (as opposed to a bone based animation) + */ + type: string; + /** + * [description] + */ + frames: Phaser.Types.Animations.JSONAnimationFrame[]; + /** + * The frame rate of playback in frames per second (default 24 if duration is null) + */ + frameRate: integer; + /** + * How long the animation should play for in milliseconds. If not given its derived from frameRate. + */ + duration: integer; + /** + * Skip frames if the time lags, or always advanced anyway? + */ + skipMissedFrames: boolean; + /** + * Delay before starting playback. Value given in milliseconds. + */ + delay: integer; + /** + * Number of times to repeat the animation (-1 for infinity) + */ + repeat: integer; + /** + * Delay before the animation repeats. Value given in milliseconds. + */ + repeatDelay: integer; + /** + * Should the animation yoyo? (reverse back down to the start) before repeating? + */ + yoyo: boolean; + /** + * Should sprite.visible = true when the animation starts to play? + */ + showOnStart: boolean; + /** + * Should sprite.visible = false when the animation finishes? + */ + hideOnComplete: boolean; + }; + + type JSONAnimationFrame = { + /** + * The key of the Texture this AnimationFrame uses. + */ + key: string; + /** + * The key of the Frame within the Texture that this AnimationFrame uses. + */ + frame: string | integer; + /** + * Additional time (in ms) that this frame should appear for during playback. + */ + duration: number; + }; + + type JSONAnimations = { + /** + * An array of all Animations added to the Animation Manager. + */ + anims: Phaser.Types.Animations.JSONAnimation[]; + /** + * The global time scale of the Animation Manager. + */ + globalTimeScale: number; + }; + + } + + namespace Cameras { + namespace Scene2D { + type CameraConfig = { + /** + * The name of the Camera. + */ + name?: string; + /** + * The horizontal position of the Camera viewport. + */ + x?: integer; + /** + * The vertical position of the Camera viewport. + */ + y?: integer; + /** + * The width of the Camera viewport. + */ + width?: integer; + /** + * The height of the Camera viewport. + */ + height?: integer; + /** + * The default zoom level of the Camera. + */ + zoom?: number; + /** + * The rotation of the Camera, in radians. + */ + rotation?: number; + /** + * Should the Camera round pixels before rendering? + */ + roundPixels?: boolean; + /** + * The horizontal scroll position of the Camera. + */ + scrollX?: number; + /** + * The vertical scroll position of the Camera. + */ + scrollY?: number; + /** + * A CSS color string controlling the Camera background color. + */ + backgroundColor?: false | string; + /** + * Defines the Camera bounds. + */ + bounds?: object; + /** + * The top-left extent of the Camera bounds. + */ + "bounds.x"?: number; + /** + * The top-left extent of the Camera bounds. + */ + "bounds.y"?: number; + /** + * The width of the Camera bounds. + */ + "bounds.width"?: number; + /** + * The height of the Camera bounds. + */ + "bounds.height"?: number; + }; + + type CameraFadeCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number)=>void; + + type CameraFlashCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number)=>void; + + type CameraPanCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number, x: number, y: number)=>void; + + type CameraShakeCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number)=>void; + + type CameraZoomCallback = (camera: Phaser.Cameras.Scene2D.Camera, progress: number, zoom: number)=>void; + + type JSONCamera = { + /** + * The name of the camera + */ + name: string; + /** + * The horizontal position of camera + */ + x: number; + /** + * The vertical position of camera + */ + y: number; + /** + * The width size of camera + */ + width: number; + /** + * The height size of camera + */ + height: number; + /** + * The zoom of camera + */ + zoom: number; + /** + * The rotation of camera + */ + rotation: number; + /** + * The round pixels st status of camera + */ + roundPixels: boolean; + /** + * The horizontal scroll of camera + */ + scrollX: number; + /** + * The vertical scroll of camera + */ + scrollY: number; + /** + * The background color of camera + */ + backgroundColor: string; + /** + * The bounds of camera + */ + bounds?: Phaser.Types.Cameras.Scene2D.JSONCameraBounds | undefined; + }; + + type JSONCameraBounds = { + /** + * The horizontal position of camera + */ + x: number; + /** + * The vertical position of camera + */ + y: number; + /** + * The width size of camera + */ + width: number; + /** + * The height size of camera + */ + height: number; + }; + + } + + namespace Controls { + type FixedKeyControlConfig = { + /** + * The Camera that this Control will update. + */ + camera?: Phaser.Cameras.Scene2D.Camera; + /** + * The Key to be pressed that will move the Camera left. + */ + left?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will move the Camera right. + */ + right?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will move the Camera up. + */ + up?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will move the Camera down. + */ + down?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will zoom the Camera in. + */ + zoomIn?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will zoom the Camera out. + */ + zoomOut?: Phaser.Input.Keyboard.Key; + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + */ + zoomSpeed?: number; + /** + * The horizontal and vertical speed the camera will move. + */ + speed?: number | Object; + }; + + type SmoothedKeyControlConfig = { + /** + * The Camera that this Control will update. + */ + camera?: Phaser.Cameras.Scene2D.Camera; + /** + * The Key to be pressed that will move the Camera left. + */ + left?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will move the Camera right. + */ + right?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will move the Camera up. + */ + up?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will zoom the Camera in. + */ + zoomIn?: Phaser.Input.Keyboard.Key; + /** + * The Key to be pressed that will zoom the Camera out. + */ + zoomOut?: Phaser.Input.Keyboard.Key; + /** + * The speed at which the camera will zoom if the `zoomIn` or `zoomOut` keys are pressed. + */ + zoomSpeed?: number; + /** + * The horizontal and vertical acceleration the camera will move. + */ + acceleration?: number | Object; + /** + * The horizontal and vertical drag applied to the camera when it is moving. + */ + drag?: number | Object; + /** + * The maximum horizontal and vertical speed the camera will move. + */ + maxSpeed?: number | Object; + }; + + } + + } + + namespace Core { + /** + * Config object containing various sound settings. + */ + type AudioConfig = { + /** + * Use HTML5 Audio instead of Web Audio. + */ + disableWebAudio?: boolean; + /** + * An existing Web Audio context. + */ + context?: AudioContext; + /** + * Disable all audio output. + */ + noAudio?: boolean; + }; + + type BannerConfig = { + /** + * Omit Phaser's name and version from the banner. + */ + hidePhaser?: boolean; + /** + * The color of the banner text. + */ + text?: string; + /** + * The background colors of the banner. + */ + background?: string[]; + }; + + type BootCallback = (game: Phaser.Game)=>void; + + type CallbacksConfig = { + /** + * A function to run at the start of the boot sequence. + */ + preBoot?: Phaser.Types.Core.BootCallback; + /** + * A function to run at the end of the boot sequence. At this point, all the game systems have started and plugins have been loaded. + */ + postBoot?: Phaser.Types.Core.BootCallback; + }; + + type DOMContainerConfig = { + /** + * Should the game create a div element to act as a DOM Container? Only enable if you're using DOM Element objects. You must provide a parent object if you use this feature. + */ + createContainer?: boolean; + /** + * Should the DOM Container that is created (if `dom.createContainer` is true) be positioned behind (true) or over the top (false, the default) of the game canvas? + */ + behindCanvas?: boolean; + }; + + type FPSConfig = { + /** + * The minimum acceptable rendering rate, in frames per second. + */ + min?: integer; + /** + * The optimum rendering rate, in frames per second. + */ + target?: integer; + /** + * Use setTimeout instead of requestAnimationFrame to run the game loop. + */ + forceSetTimeOut?: boolean; + /** + * Calculate the average frame delta from this many consecutive frame intervals. + */ + deltaHistory?: integer; + /** + * The amount of frames the time step counts before we trust the delta values again. + */ + panicMax?: integer; + /** + * Apply delta smoothing during the game update to help avoid spikes? + */ + smoothStep?: boolean; + }; + + type GameConfig = { + /** + * The width of the game, in game pixels. + */ + width?: integer | string; + /** + * The height of the game, in game pixels. + */ + height?: integer | string; + /** + * Simple scale applied to the game canvas. 2 is double size, 0.5 is half size, etc. + */ + zoom?: number; + /** + * The size of each game pixel, in canvas pixels. Values larger than 1 are "high" resolution. + */ + resolution?: number; + /** + * Which renderer to use. Phaser.AUTO, Phaser.CANVAS, Phaser.HEADLESS, or Phaser.WEBGL. AUTO picks WEBGL if available, otherwise CANVAS. + */ + type?: number; + /** + * The DOM element that will contain the game canvas, or its `id`. If undefined or if the named element doesn't exist, the game canvas is inserted directly into the document body. If `null` no parent will be used and you are responsible for adding the canvas to your environment. + */ + parent?: HTMLElement | string; + /** + * Provide your own Canvas element for Phaser to use instead of creating one. + */ + canvas?: HTMLCanvasElement; + /** + * CSS styles to apply to the game canvas instead of Phasers default styles. + */ + canvasStyle?: string; + /** + * Is Phaser running under a custom (non-native web) environment? If so, set this to `true` to skip internal Feature detection. If `true` the `renderType` cannot be left as `AUTO`. + */ + customEnvironment?: boolean; + /** + * Provide your own Canvas Context for Phaser to use, instead of creating one. + */ + context?: CanvasRenderingContext2D; + /** + * A scene or scenes to add to the game. If several are given, the first is started; the remainder are started only if they have `{ active: true }`. See the `sceneConfig` argument in `Phaser.Scenes.SceneManager#add`. + */ + scene?: Phaser.Scene | Phaser.Scene[] | Phaser.Types.Scenes.SettingsConfig | Phaser.Types.Scenes.SettingsConfig[] | Phaser.Types.Scenes.CreateSceneFromObjectConfig | Phaser.Types.Scenes.CreateSceneFromObjectConfig[] | Function | Function[]; + /** + * Seed for the random number generator. + */ + seed?: string[]; + /** + * The title of the game. Shown in the browser console. + */ + title?: string; + /** + * The URL of the game. Shown in the browser console. + */ + url?: string; + /** + * The version of the game. Shown in the browser console. + */ + version?: string; + /** + * Automatically call window.focus() when the game boots. Usually necessary to capture input events if the game is in a separate frame. + */ + autoFocus?: boolean; + /** + * Input configuration, or `false` to disable all game input. + */ + input?: boolean | Phaser.Types.Core.InputConfig; + /** + * Disable the browser's default 'contextmenu' event (usually triggered by a right-button mouse click). + */ + disableContextMenu?: boolean; + /** + * Whether the game canvas will have a transparent background. + */ + transparent?: boolean; + /** + * Configuration for the banner printed in the browser console when the game starts. + */ + banner?: boolean | Phaser.Types.Core.BannerConfig; + /** + * The DOM Container configuration object. + */ + dom?: Phaser.Types.Core.DOMContainerConfig; + /** + * Game loop configuration. + */ + fps?: Phaser.Types.Core.FPSConfig; + /** + * Game renderer configuration. + */ + render?: Phaser.Types.Core.RenderConfig; + /** + * The background color of the game canvas. The default is black. + */ + backgroundColor?: string | number; + /** + * Optional callbacks to run before or after game boot. + */ + callbacks?: Phaser.Types.Core.CallbacksConfig; + /** + * Loader configuration. + */ + loader?: Phaser.Types.Core.LoaderConfig; + /** + * Images configuration. + */ + images?: Phaser.Types.Core.ImagesConfig; + /** + * Physics configuration. + */ + physics?: Phaser.Types.Core.PhysicsConfig; + /** + * Plugins to install. + */ + plugins?: Phaser.Types.Core.PluginObject | Phaser.Types.Core.PluginObjectItem[]; + /** + * The Scale Manager configuration. + */ + scale?: Phaser.Types.Core.ScaleConfig; + /** + * The Audio Configuration object. + */ + audio?: Phaser.Types.Core.AudioConfig; + }; + + type GamepadInputConfig = { + /** + * Where the Gamepad Manager listens for gamepad input events. + */ + target?: any; + }; + + type ImagesConfig = { + /** + * URL to use for the 'default' texture. + */ + default?: string; + /** + * URL to use for the 'missing' texture. + */ + missing?: string; + }; + + type InputConfig = { + /** + * Keyboard input configuration. `true` uses the default configuration and `false` disables keyboard input. + */ + keyboard?: boolean | Phaser.Types.Core.KeyboardInputConfig; + /** + * Mouse input configuration. `true` uses the default configuration and `false` disables mouse input. + */ + mouse?: boolean | Phaser.Types.Core.MouseInputConfig; + /** + * Touch input configuration. `true` uses the default configuration and `false` disables touch input. + */ + touch?: boolean | Phaser.Types.Core.TouchInputConfig; + /** + * Gamepad input configuration. `true` enables gamepad input. + */ + gamepad?: boolean | Phaser.Types.Core.GamepadInputConfig; + /** + * The maximum number of touch pointers. See {@link Phaser.Input.InputManager#pointers}. + */ + activePointers?: integer; + /** + * The smoothing factor to apply during Pointer movement. See {@link Phaser.Input.Pointer#smoothFactor}. + */ + smoothFactor?: number; + /** + * Should Phaser listen for input events on the Window? If you disable this, events like 'POINTER_UP_OUTSIDE' will no longer fire. + */ + windowEvents?: boolean; + }; + + type KeyboardInputConfig = { + /** + * Where the Keyboard Manager listens for keyboard input events. + */ + target?: any; + /** + * `preventDefault` will be called on every non-modified key which has a key code in this array. By default it is empty. + */ + capture?: integer[]; + }; + + type LoaderConfig = { + /** + * A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'. + */ + baseURL?: string; + /** + * A URL path used to resolve relative paths given to the loader. Example: 'images/sprites/'. + */ + path?: string; + /** + * The maximum number of resources the loader will start loading at once. + */ + maxParallelDownloads?: integer; + /** + * '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}. + */ + crossOrigin?: string | undefined; + /** + * The response type of the XHR request, e.g. `blob`, `text`, etc. + */ + responseType?: string; + /** + * Should the XHR request use async or not? + */ + async?: boolean; + /** + * Optional username for all XHR requests. + */ + user?: string; + /** + * Optional password for all XHR requests. + */ + password?: string; + /** + * Optional XHR timeout value, in ms. + */ + timeout?: integer; + }; + + type MouseInputConfig = { + /** + * Where the Mouse Manager listens for mouse input events. The default is the game canvas. + */ + target?: any; + /** + * Whether mouse input events have `preventDefault` called on them. + */ + capture?: boolean; + }; + + /** + * This callback type is completely empty, a no-operation. + */ + type NOOP = ()=>void; + + type PhysicsConfig = { + /** + * The default physics system. It will be started for each scene. Phaser provides 'arcade', 'impact', and 'matter'. + */ + default?: string; + /** + * Arcade Physics configuration. + */ + arcade?: Phaser.Types.Physics.Arcade.ArcadeWorldConfig; + /** + * Impact Physics configuration. + */ + impact?: Phaser.Types.Physics.Impact.WorldConfig; + /** + * Matter Physics configuration. + */ + matter?: Phaser.Types.Physics.Matter.MatterWorldConfig; + }; + + type PluginObject = { + /** + * Global plugins to install. + */ + global?: Phaser.Types.Core.PluginObjectItem[]; + /** + * Scene plugins to install. + */ + scene?: Phaser.Types.Core.PluginObjectItem[]; + /** + * The default set of scene plugins (names). + */ + default?: string[]; + /** + * Plugins to *add* to the default set of scene plugins. + */ + defaultMerge?: string[]; + }; + + type PluginObjectItem = { + /** + * A key to identify the plugin in the Plugin Manager. + */ + key?: string; + /** + * The plugin itself. Usually a class/constructor. + */ + plugin?: any; + /** + * Whether the plugin should be started automatically. + */ + start?: boolean; + /** + * For a scene plugin, add the plugin to the scene's systems object under this key (`this.sys.KEY`, from the scene). + */ + systemKey?: string; + /** + * For a scene plugin, add the plugin to the scene object under this key (`this.KEY`, from the scene). + */ + sceneKey?: string; + /** + * If this plugin is to be injected into the Scene Systems, this is the property key map used. + */ + mapping?: string; + /** + * Arbitrary data passed to the plugin's init() method. + */ + data?: any; + }; + + type RenderConfig = { + /** + * When set to `true`, WebGL uses linear interpolation to draw scaled or rotated textures, giving a smooth appearance. When set to `false`, WebGL uses nearest-neighbor interpolation, giving a crisper appearance. `false` also disables antialiasing of the game canvas itself, if the browser supports it, when the game canvas is scaled. + */ + antialias?: boolean; + /** + * Sets the `antialias` property when the WebGL context is created. Setting this value does not impact any subsequent textures that are created, or the canvas style attributes. + */ + antialiasGL?: boolean; + /** + * 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. + */ + desynchronized?: boolean; + /** + * Sets `antialias` and `roundPixels` to true. This is the best setting for pixel-art games. + */ + pixelArt?: boolean; + /** + * Draw texture-based Game Objects at only whole-integer positions. Game Objects without textures, like Graphics, ignore this property. + */ + roundPixels?: boolean; + /** + * Whether the game canvas will be transparent. Boolean that indicates if the canvas contains an alpha channel. If set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images. + */ + transparent?: boolean; + /** + * Whether the game canvas will be cleared between each rendering frame. + */ + clearBeforeRender?: boolean; + /** + * In WebGL mode, the drawing buffer contains colors with pre-multiplied alpha. + */ + premultipliedAlpha?: boolean; + /** + * Let the browser abort creating a WebGL context if it judges performance would be unacceptable. + */ + failIfMajorPerformanceCaveat?: boolean; + /** + * "high-performance", "low-power" or "default". A hint to the browser on how much device power the game might use. + */ + powerPreference?: string; + /** + * The default WebGL batch size. + */ + batchSize?: integer; + /** + * The maximum number of lights allowed to be visible within range of a single Camera in the LightManager. + */ + maxLights?: integer; + /** + * The mipmap magFilter to be used when creating WebGL textures. + */ + mipmapFilter?: string; + }; + + type ScaleConfig = { + /** + * The base width of your game. Can be an integer or a string: '100%'. If a string it will only work if you have set a parent element that has a size. + */ + width?: integer | string; + /** + * The base height of your game. Can be an integer or a string: '100%'. If a string it will only work if you have set a parent element that has a size. + */ + height?: integer | string; + /** + * The zoom value of the game canvas. + */ + zoom?: Phaser.Scale.ZoomType | integer; + /** + * The rendering resolution of the canvas. This is reserved for future use and is currently ignored. + */ + resolution?: number; + /** + * The DOM element that will contain the game canvas, or its `id`. If undefined, or if the named element doesn't exist, the game canvas is inserted directly into the document body. If `null` no parent will be used and you are responsible for adding the canvas to your environment. + */ + parent?: HTMLElement | string; + /** + * Is the Scale Manager allowed to adjust the CSS height property of the parent and/or document body to be 100%? + */ + expandParent?: boolean; + /** + * The scale mode. + */ + mode?: Phaser.Scale.ScaleModeType; + /** + * The minimum width and height the canvas can be scaled down to. + */ + min?: WidthHeight; + /** + * The maximum width the canvas can be scaled up to. + */ + max?: WidthHeight; + /** + * Automatically round the display and style sizes of the canvas. This can help with performance in lower-powered devices. + */ + autoRound?: boolean; + /** + * Automatically center the canvas within the parent? + */ + autoCenter?: Phaser.Scale.CenterType; + /** + * How many ms should elapse before checking if the browser size has changed? + */ + resizeInterval?: integer; + /** + * The DOM element that will be sent into full screen mode, or its `id`. If undefined Phaser will create its own div and insert the canvas into it when entering fullscreen mode. + */ + fullscreenTarget?: HTMLElement | string; + }; + + type TimeStepCallback = (time: number, average: number, interpolation: number)=>void; + + type TouchInputConfig = { + /** + * Where the Touch Manager listens for touch input events. The default is the game canvas. + */ + target?: any; + /** + * Whether touch input events have preventDefault() called on them. + */ + capture?: boolean; + }; + + type WidthHeight = { + /** + * The width. + */ + width?: integer; + /** + * The height. + */ + height?: integer; + }; + + } + + namespace Create { + type GenerateTextureCallback = (canvas: HTMLCanvasElement, context: CanvasRenderingContext2D)=>void; + + type GenerateTextureConfig = { + /** + * [description] + */ + data?: any[]; + /** + * [description] + */ + canvas?: HTMLCanvasElement; + /** + * [description] + */ + palette?: Phaser.Types.Create.Palette; + /** + * The width of each 'pixel' in the generated texture. + */ + pixelWidth?: number; + /** + * The height of each 'pixel' in the generated texture. + */ + pixelHeight?: number; + /** + * [description] + */ + resizeCanvas?: boolean; + /** + * [description] + */ + clearCanvas?: boolean; + /** + * [description] + */ + preRender?: Phaser.Types.Create.GenerateTextureCallback; + /** + * [description] + */ + postRender?: Phaser.Types.Create.GenerateTextureCallback; + }; + + type Palette = { + /** + * Color value 1. + */ + "0": string; + /** + * Color value 2. + */ + "1": string; + /** + * Color value 3. + */ + "2": string; + /** + * Color value 4. + */ + "3": string; + /** + * Color value 5. + */ + "4": string; + /** + * Color value 6. + */ + "5": string; + /** + * Color value 7. + */ + "6": string; + /** + * Color value 8. + */ + "7": string; + /** + * Color value 9. + */ + "8": string; + /** + * Color value 10. + */ + "9": string; + /** + * Color value 11. + */ + A: string; + /** + * Color value 12. + */ + B: string; + /** + * Color value 13. + */ + C: string; + /** + * Color value 14. + */ + D: string; + /** + * Color value 15. + */ + E: string; + /** + * Color value 16. + */ + F: string; + }; + + } + + namespace Curves { + type EllipseCurveConfig = { + /** + * The x coordinate of the ellipse. + */ + x?: number; + /** + * The y coordinate of the ellipse. + */ + y?: number; + /** + * The horizontal radius of the ellipse. + */ + xRadius?: number; + /** + * The vertical radius of the ellipse. + */ + yRadius?: number; + /** + * The start angle of the ellipse, in degrees. + */ + startAngle?: integer; + /** + * The end angle of the ellipse, in degrees. + */ + endAngle?: integer; + /** + * Sets if the the ellipse rotation is clockwise (true) or anti-clockwise (false) + */ + clockwise?: boolean; + /** + * The rotation of the ellipse, in degrees. + */ + rotation?: integer; + }; + + type JSONCurve = { + /** + * The of the curve + */ + type: string; + /** + * The arrays of points like `[x1, y1, x2, y2]` + */ + points: number[]; + }; + + type JSONEllipseCurve = { + /** + * The of the curve. + */ + type: string; + /** + * The x coordinate of the ellipse. + */ + x: number; + /** + * The y coordinate of the ellipse. + */ + y: number; + /** + * The horizontal radius of ellipse. + */ + xRadius: number; + /** + * The vertical radius of ellipse. + */ + yRadius: number; + /** + * The start angle of the ellipse, in degrees. + */ + startAngle: integer; + /** + * The end angle of the ellipse, in degrees. + */ + endAngle: integer; + /** + * Sets if the the ellipse rotation is clockwise (true) or anti-clockwise (false) + */ + clockwise: boolean; + /** + * The rotation of ellipse, in degrees. + */ + rotation: integer; + }; + + type JSONPath = { + /** + * The of the curve. + */ + type: string; + /** + * The X coordinate of the curve's starting point. + */ + x: number; + /** + * The Y coordinate of the path's starting point. + */ + y: number; + /** + * The path is auto closed. + */ + autoClose: boolean; + /** + * The list of the curves + */ + curves: Phaser.Types.Curves.JSONCurve[]; + }; + + } + + namespace Display { + type ColorObject = { + /** + * The red color value in the range 0 to 255. + */ + r: number; + /** + * The green color value in the range 0 to 255. + */ + g: number; + /** + * The blue color value in the range 0 to 255. + */ + b: number; + /** + * The alpha color value in the range 0 to 255. + */ + a: number; + }; + + type HSVColorObject = { + /** + * The hue color value. A number between 0 and 1 + */ + h: number; + /** + * The saturation color value. A number between 0 and 1 + */ + s: number; + /** + * The lightness color value. A number between 0 and 1 + */ + v: number; + }; + + type InputColorObject = { + /** + * The red color value in the range 0 to 255. + */ + r?: number; + /** + * The green color value in the range 0 to 255. + */ + g?: number; + /** + * The blue color value in the range 0 to 255. + */ + b?: number; + /** + * The alpha color value in the range 0 to 255. + */ + a?: number; + }; + + } + + namespace GameObjects { + namespace BitmapText { + /** + * The font data for an individual character of a Bitmap Font. + * + * Describes the character's position, size, offset and kerning. + */ + type BitmapFontCharacterData = { + /** + * The x position of the character. + */ + x: number; + /** + * The y position of the character. + */ + y: number; + /** + * The width of the character. + */ + width: number; + /** + * The height of the character. + */ + height: number; + /** + * The center x position of the character. + */ + centerX: number; + /** + * The center y position of the character. + */ + centerY: number; + /** + * The x offset of the character. + */ + xOffset: number; + /** + * The y offset of the character. + */ + yOffset: number; + /** + * Extra data for the character. + */ + data: object; + /** + * Kerning values, keyed by character code. + */ + kerning: {[key: string]: number}; + }; + + /** + * Bitmap Font data that can be used by a BitmapText Game Object. + */ + type BitmapFontData = { + /** + * The name of the font. + */ + font: string; + /** + * The size of the font. + */ + size: number; + /** + * The line height of the font. + */ + lineHeight: number; + /** + * Whether this font is a retro font (monospace). + */ + retroFont: boolean; + /** + * The character data of the font, keyed by character code. Each character datum includes a position, size, offset and more. + */ + chars: {[key: number]: Phaser.Types.GameObjects.BitmapText.BitmapFontCharacterData}; + }; + + type BitmapTextConfig = Phaser.Types.GameObjects.GameObjectConfig & { + /** + * The key of the font to use from the BitmapFont cache. + */ + font?: string; + /** + * The string, or array of strings, to be set as the content of this Bitmap Text. + */ + text?: string; + /** + * The font size to set. + */ + size?: number | false; + }; + + type BitmapTextSize = { + /** + * The position and size of the BitmapText, taking into account the position and scale of the Game Object. + */ + global: Phaser.Types.GameObjects.BitmapText.GlobalBitmapTextSize; + /** + * The position and size of the BitmapText, taking just the font size into account. + */ + local: Phaser.Types.GameObjects.BitmapText.LocalBitmapTextSize; + }; + + type DisplayCallbackConfig = { + /** + * The Dynamic Bitmap Text object that owns this character being rendered. + */ + parent: Phaser.GameObjects.DynamicBitmapText; + /** + * The tint of the character being rendered. Always zero in Canvas. + */ + tint: Phaser.Types.GameObjects.BitmapText.TintConfig; + /** + * The index of the character being rendered. + */ + index: number; + /** + * The character code of the character being rendered. + */ + charCode: number; + /** + * The x position of the character being rendered. + */ + x: number; + /** + * The y position of the character being rendered. + */ + y: number; + /** + * The scale of the character being rendered. + */ + scale: number; + /** + * The rotation of the character being rendered. + */ + rotation: number; + /** + * Custom data stored with the character being rendered. + */ + data: any; + }; + + type DisplayCallback = (display: Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig)=>void; + + /** + * The position and size of the Bitmap Text in global space, taking into account the Game Object's scale and world position. + */ + type GlobalBitmapTextSize = { + /** + * The x position of the BitmapText, taking into account the x position and scale of the Game Object. + */ + x: number; + /** + * The y position of the BitmapText, taking into account the y position and scale of the Game Object. + */ + y: number; + /** + * The width of the BitmapText, taking into account the x scale of the Game Object. + */ + width: number; + /** + * The height of the BitmapText, taking into account the y scale of the Game Object. + */ + height: number; + }; + + type JSONBitmapText = Phaser.Types.GameObjects.JSONGameObject & { + /** + * The name of the font. + */ + font: string; + /** + * The text that this Bitmap Text displays. + */ + text: string; + /** + * The size of the font. + */ + fontSize: number; + /** + * Adds / Removes spacing between characters. + */ + letterSpacing: number; + /** + * The alignment of the text in a multi-line BitmapText object. + */ + align: integer; + }; + + /** + * The position and size of the Bitmap Text in local space, taking just the font size into account. + */ + type LocalBitmapTextSize = { + /** + * The x position of the BitmapText. + */ + x: number; + /** + * The y position of the BitmapText. + */ + y: number; + /** + * The width of the BitmapText. + */ + width: number; + /** + * The height of the BitmapText. + */ + height: number; + }; + + type RetroFontConfig = { + /** + * The key of the image containing the font. + */ + image: string; + /** + * If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + */ + "offset.x": number; + /** + * If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + */ + "offset.y": number; + /** + * The width of each character in the font set. + */ + width: number; + /** + * The height of each character in the font set. + */ + height: number; + /** + * The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + */ + chars: string; + /** + * The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. + */ + charsPerRow: number; + /** + * If the characters in the font set have horizontal spacing between them set the required amount here. + */ + "spacing.x": number; + /** + * If the characters in the font set have vertical spacing between them set the required amount here. + */ + "spacing.y": number; + /** + * The amount of vertical space to add to the line height of the font. + */ + lineSpacing: number; + }; + + type TintConfig = { + /** + * The top left tint value. Always zero in canvas. + */ + topLeft: number; + /** + * The top right tint value. Always zero in canvas. + */ + topRight: number; + /** + * The bottom left tint value. Always zero in canvas. + */ + bottomLeft: number; + /** + * The bottom right tint value. Always zero in canvas. + */ + bottomRight: number; + }; + + } + + namespace Graphics { + /** + * Graphics fill style settings. + */ + type FillStyle = { + /** + * The fill color. + */ + color?: number; + /** + * The fill alpha. + */ + alpha?: number; + }; + + /** + * Graphics line style (or stroke style) settings. + */ + type LineStyle = { + /** + * The stroke width. + */ + width?: number; + /** + * The stroke color. + */ + color?: number; + /** + * The stroke alpha. + */ + alpha?: number; + }; + + /** + * Options for the Graphics game Object. + */ + type Options = Phaser.Types.GameObjects.Graphics.Styles & { + /** + * The x coordinate of the Graphics. + */ + x?: number; + /** + * The y coordinate of the Graphics. + */ + y?: number; + }; + + type RoundedRectRadius = { + /** + * Top left + */ + tl?: number; + /** + * Top right + */ + tr?: number; + /** + * Bottom right + */ + br?: number; + /** + * Bottom left + */ + bl?: number; + }; + + /** + * Graphics style settings. + */ + type Styles = { + /** + * The style applied to shape outlines. + */ + lineStyle?: Phaser.Types.GameObjects.Graphics.LineStyle; + /** + * The style applied to shape areas. + */ + fillStyle?: Phaser.Types.GameObjects.Graphics.FillStyle; + }; + + } + + namespace Group { + type GroupCallback = (item: Phaser.GameObjects.GameObject)=>void; + + type GroupConfig = { + /** + * Sets {@link Phaser.GameObjects.Group#classType}. + */ + classType?: Function; + /** + * Sets {@link Phaser.GameObjects.Group#name}. + */ + name?: string; + /** + * Sets {@link Phaser.GameObjects.Group#active}. + */ + active?: boolean; + /** + * Sets {@link Phaser.GameObjects.Group#maxSize}. + */ + maxSize?: number; + /** + * Sets {@link Phaser.GameObjects.Group#defaultKey}. + */ + defaultKey?: string; + /** + * Sets {@link Phaser.GameObjects.Group#defaultFrame}. + */ + defaultFrame?: string | integer; + /** + * Sets {@link Phaser.GameObjects.Group#runChildUpdate}. + */ + runChildUpdate?: boolean; + /** + * Sets {@link Phaser.GameObjects.Group#createCallback}. + */ + createCallback?: Phaser.Types.GameObjects.Group.GroupCallback; + /** + * Sets {@link Phaser.GameObjects.Group#removeCallback}. + */ + removeCallback?: Phaser.Types.GameObjects.Group.GroupCallback; + /** + * Sets {@link Phaser.GameObjects.Group#createMultipleCallback}. + */ + createMultipleCallback?: Phaser.Types.GameObjects.Group.GroupMultipleCreateCallback; + }; + + /** + * The total number of objects created will be + * + * key.length * frame.length * frameQuantity * (yoyo ? 2 : 1) * (1 + repeat) + * + * If `max` is nonzero, then the total created will not exceed `max`. + * + * `key` is required. {@link Phaser.GameObjects.Group#defaultKey} is not used. + */ + type GroupCreateConfig = { + /** + * The class of each new Game Object. + */ + classType?: Function; + /** + * The texture key of each new Game Object. + */ + key?: string | string[]; + /** + * The texture frame of each new Game Object. + */ + frame?: string | string[] | integer | integer[]; + /** + * The number of Game Objects to create. If set, this overrides the `frameQuantity` value. Use `frameQuantity` for more advanced control. + */ + quantity?: integer; + /** + * The visible state of each new Game Object. + */ + visible?: boolean; + /** + * The active state of each new Game Object. + */ + active?: boolean; + /** + * The number of times each `key` × `frame` combination will be *repeated* (after the first combination). + */ + repeat?: integer; + /** + * Select a `key` at random. + */ + randomKey?: boolean; + /** + * Select a `frame` at random. + */ + randomFrame?: boolean; + /** + * Select keys and frames by moving forward then backward through `key` and `frame`. + */ + yoyo?: boolean; + /** + * The number of times each `frame` should be combined with one `key`. + */ + frameQuantity?: integer; + /** + * The maximum number of new Game Objects to create. 0 is no maximum. + */ + max?: integer; + setXY?: object; + /** + * The horizontal position of each new Game Object. + */ + "setXY.x"?: number; + /** + * The vertical position of each new Game Object. + */ + "setXY.y"?: number; + /** + * Increment each Game Object's horizontal position from the previous by this amount, starting from `setXY.x`. + */ + "setXY.stepX"?: number; + /** + * Increment each Game Object's vertical position from the previous by this amount, starting from `setXY.y`. + */ + "setXY.stepY"?: number; + setRotation?: object; + /** + * Rotation of each new Game Object. + */ + "setRotation.value"?: number; + /** + * Increment each Game Object's rotation from the previous by this amount, starting at `setRotation.value`. + */ + "setRotation.step"?: number; + setScale?: object; + /** + * The horizontal scale of each new Game Object. + */ + "setScale.x"?: number; + /** + * The vertical scale of each new Game Object. + */ + "setScale.y"?: number; + /** + * Increment each Game Object's horizontal scale from the previous by this amount, starting from `setScale.x`. + */ + "setScale.stepX"?: number; + /** + * Increment each Game object's vertical scale from the previous by this amount, starting from `setScale.y`. + */ + "setScale.stepY"?: number; + setAlpha?: object; + /** + * The alpha value of each new Game Object. + */ + "setAlpha.value"?: number; + /** + * Increment each Game Object's alpha from the previous by this amount, starting from `setAlpha.value`. + */ + "setAlpha.step"?: number; + setDepth?: object; + /** + * The depth value of each new Game Object. + */ + "setDepth.value"?: number; + /** + * Increment each Game Object's depth from the previous by this amount, starting from `setDepth.value`. + */ + "setDepth.step"?: number; + setScrollFactor?: object; + /** + * The horizontal scroll factor of each new Game Object. + */ + "setScrollFactor.x"?: number; + /** + * The vertical scroll factor of each new Game Object. + */ + "setScrollFactor.y"?: number; + /** + * Increment each Game Object's horizontal scroll factor from the previous by this amount, starting from `setScrollFactor.x`. + */ + "setScrollFactor.stepX"?: number; + /** + * Increment each Game object's vertical scroll factor from the previous by this amount, starting from `setScrollFactor.y`. + */ + "setScrollFactor.stepY"?: number; + /** + * A geometric shape that defines the hit area for the Game Object. + */ + hitArea?: any; + /** + * A callback to be invoked when the Game Object is interacted with. + */ + hitAreaCallback?: Phaser.Types.Input.HitAreaCallback; + /** + * Align the new Game Objects in a grid using these settings. + */ + gridAlign?: false | Phaser.Types.Actions.GridAlignConfig; + }; + + type GroupMultipleCreateCallback = (items: Phaser.GameObjects.GameObject[])=>void; + + } + + namespace Particles { + type DeathZoneSource = { + contains: Phaser.Types.GameObjects.Particles.DeathZoneSourceCallback; + }; + + type DeathZoneSourceCallback = (x: number, y: number)=>void; + + type EdgeZoneSource = { + /** + * A function placing points on the sources edge or edges. + */ + getPoints: Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback; + }; + + type EdgeZoneSourceCallback = (quantity: integer, stepRate?: number)=>void; + + type EmitterOpCustomEmitConfig = { + /** + * A callback that is invoked each time the emitter emits a particle. + */ + onEmit: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback; + }; + + type EmitterOpCustomUpdateConfig = { + /** + * A callback that is invoked each time the emitter emits a particle. + */ + onEmit?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback; + /** + * A callback that is invoked each time the emitter updates. + */ + onUpdate: Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback; + }; + + /** + * Defines an operation yielding a value incremented continuously across a range. + */ + type EmitterOpEaseConfig = { + /** + * The starting value. + */ + start: number; + /** + * The ending value. + */ + end: number; + /** + * The name of the easing function. + */ + ease?: string; + }; + + /** + * The returned value sets what the property will be at the START of the particle's life, on emit. + */ + type EmitterOpOnEmitCallback = (particle: Phaser.GameObjects.Particles.Particle, key: string, value: number)=>void; + + type EmitterOpOnEmitType = number | number[] | Phaser.Types.GameObjects.Particles.EmitterOpOnEmitCallback | Phaser.Types.GameObjects.Particles.EmitterOpRandomConfig | Phaser.Types.GameObjects.Particles.EmitterOpRandomMinMaxConfig | Phaser.Types.GameObjects.Particles.EmitterOpRandomStartEndConfig | Phaser.Types.GameObjects.Particles.EmitterOpSteppedConfig | Phaser.Types.GameObjects.Particles.EmitterOpCustomEmitConfig; + + /** + * The returned value updates the property for the duration of the particle's life. + */ + type EmitterOpOnUpdateCallback = (particle: Phaser.GameObjects.Particles.Particle, key: string, t: number, value: number)=>void; + + type EmitterOpOnUpdateType = Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateCallback | Phaser.Types.GameObjects.Particles.EmitterOpEaseConfig | Phaser.Types.GameObjects.Particles.EmitterOpCustomUpdateConfig; + + /** + * Defines an operation yielding a random value within a range. + */ + type EmitterOpRandomConfig = { + /** + * The minimum and maximum values, as [min, max]. + */ + random: number[]; + }; + + /** + * Defines an operation yielding a random value within a range. + */ + type EmitterOpRandomMinMaxConfig = { + /** + * The minimum value. + */ + min: number; + /** + * The maximum value. + */ + max: number; + }; + + /** + * Defines an operation yielding a random value within a range. + */ + type EmitterOpRandomStartEndConfig = { + /** + * The starting value. + */ + start: number; + /** + * The ending value. + */ + end: number; + /** + * If false, this becomes {@link EmitterOpEaseConfig}. + */ + random: boolean; + }; + + /** + * Defines an operation yielding a value incremented by steps across a range. + */ + type EmitterOpSteppedConfig = { + /** + * The starting value. + */ + start: number; + /** + * The ending value. + */ + end: number; + /** + * The number of steps between start and end. + */ + steps: number; + }; + + type GravityWellConfig = { + /** + * The x coordinate of the Gravity Well, in world space. + */ + x?: number; + /** + * The y coordinate of the Gravity Well, in world space. + */ + y?: number; + /** + * The strength of the gravity force - larger numbers produce a stronger force. + */ + power?: number; + /** + * The minimum distance for which the gravity force is calculated. + */ + epsilon?: number; + /** + * The gravitational force of this Gravity Well. + */ + gravity?: number; + }; + + type ParticleDeathCallback = (particle: Phaser.GameObjects.Particles.Particle)=>void; + + type ParticleEmitterBounds = { + /** + * The left edge of the rectangle. + */ + x: number; + /** + * The top edge of the rectangle. + */ + y: number; + /** + * The width of the rectangle. + */ + width: number; + /** + * The height of the rectangle. + */ + height: number; + }; + + type ParticleEmitterBoundsAlt = { + /** + * The left edge of the rectangle. + */ + x: number; + /** + * The top edge of the rectangle. + */ + y: number; + /** + * The width of the rectangle. + */ + w: number; + /** + * The height of the rectangle. + */ + h: number; + }; + + type ParticleEmitterCallback = (particle: Phaser.GameObjects.Particles.Particle, emitter: Phaser.GameObjects.Particles.ParticleEmitter)=>void; + + type ParticleEmitterConfig = { + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#active}. + */ + active?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#blendMode}. + */ + blendMode?: Phaser.BlendModes | string; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope} and {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope}. + */ + callbackScope?: any; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideBottom}. + */ + collideBottom?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideLeft}. + */ + collideLeft?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideRight}. + */ + collideRight?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#collideTop}. + */ + collideTop?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}. + */ + deathCallback?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope}. + */ + deathCallbackScope?: any; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}. + */ + emitCallback?: Function; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope}. + */ + emitCallbackScope?: any; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#follow}. + */ + follow?: Phaser.GameObjects.GameObject; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency}. + */ + frequency?: number; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#gravityX}. + */ + gravityX?: number; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#gravityY}. + */ + gravityY?: number; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#maxParticles}. + */ + maxParticles?: integer; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#name}. + */ + name?: string; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#on}. + */ + on?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#particleBringToTop}. + */ + particleBringToTop?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#particleClass}. + */ + particleClass?: Phaser.GameObjects.Particles.Particle; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#radial}. + */ + radial?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#timeScale}. + */ + timeScale?: number; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#trackVisible}. + */ + trackVisible?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#visible}. + */ + visible?: boolean; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#accelerationX} (emit only). + */ + accelerationX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#accelerationY} (emit only). + */ + accelerationY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#alpha}. + */ + alpha?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#angle} (emit only). + */ + angle?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#bounce} (emit only). + */ + bounce?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#delay} (emit only). + */ + delay?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#lifespan} (emit only). + */ + lifespan?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityX} (emit only). + */ + maxVelocityX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityY} (emit only). + */ + maxVelocityY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#moveToX} (emit only). + */ + moveToX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#moveToY} (emit only). + */ + moveToY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity} (emit only). + */ + quantity?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#rotate}. + */ + rotate?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; + /** + * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setScale}. + */ + scale?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#scaleX}. + */ + scaleX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#scaleY}. + */ + scaleY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; + /** + * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setSpeed} (emit only). + */ + speed?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#speedX} (emit only). + */ + speedX?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#speedY} (emit only). + */ + speedY?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#tint}. + */ + tint?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType | Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#x} (emit only). + */ + x?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#y} (emit only). + */ + y?: Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType; + /** + * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone}. + */ + emitZone?: object; + /** + * As {@link Phaser.GameObjects.Particles.ParticleEmitter#setBounds}. + */ + bounds?: Phaser.Types.GameObjects.Particles.ParticleEmitterBounds | Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt; + /** + * Assigns to {@link Phaser.GameObjects.Particles.ParticleEmitter#followOffset}. + */ + followOffset?: object; + /** + * x-coordinate of the offset. + */ + "followOffset.x"?: number; + /** + * y-coordinate of the offset. + */ + "followOffset.y"?: number; + /** + * Sets {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}. + */ + frame?: number | number[] | string | string[] | Phaser.Textures.Frame | Phaser.Textures.Frame[] | Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig; + }; + + type ParticleEmitterDeathZoneConfig = { + /** + * A shape representing the zone. See {@link Phaser.GameObjects.Particles.Zones.DeathZone#source}. + */ + source: Phaser.Types.GameObjects.Particles.DeathZoneSource; + /** + * 'onEnter' or 'onLeave'. + */ + type?: string; + }; + + type ParticleEmitterEdgeZoneConfig = { + /** + * A shape representing the zone. See {@link Phaser.GameObjects.Particles.Zones.EdgeZone#source}. + */ + source: Phaser.Types.GameObjects.Particles.EdgeZoneSource; + /** + * 'edge'. + */ + type: string; + /** + * The number of particles to place on the source edge. Set to 0 to use `stepRate` instead. + */ + quantity: integer; + /** + * The distance between each particle. When set, `quantity` is implied and should be set to 0. + */ + stepRate?: number; + /** + * Whether particles are placed from start to end and then end to start. + */ + yoyo?: boolean; + /** + * Whether one endpoint will be removed if it's identical to the other. + */ + seamless?: boolean; + }; + + type ParticleEmitterFrameConfig = { + /** + * One or more texture frames. + */ + frames?: number | number[] | string | string[] | Phaser.Textures.Frame | Phaser.Textures.Frame[]; + /** + * Whether texture frames will be assigned consecutively (true) or at random (false). + */ + cycle?: boolean; + /** + * The number of consecutive particles receiving each texture frame, when `cycle` is true. + */ + quantity?: integer; + }; + + type ParticleEmitterRandomZoneConfig = { + /** + * A shape representing the zone. See {@link Phaser.GameObjects.Particles.Zones.RandomZone#source}. + */ + source: Phaser.Types.GameObjects.Particles.RandomZoneSource; + /** + * 'random'. + */ + type?: string; + }; + + type RandomZoneSource = { + /** + * A function modifying its point argument. + */ + getRandomPoint: Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback; + }; + + type RandomZoneSourceCallback = (point: Phaser.Math.Vector2)=>void; + + } + + namespace PathFollower { + /** + * Settings for a PathFollower. + */ + type PathConfig = { + /** + * The duration of the path follow in ms. Must be `> 0`. + */ + duration?: number; + /** + * The start position of the path follow, between 0 and 1. Must be less than `to`. + */ + from?: number; + /** + * The end position of the path follow, between 0 and 1. Must be more than `from`. + */ + to?: number; + /** + * Whether to position the PathFollower on the Path using its path offset. + */ + positionOnPath?: boolean; + /** + * Should the PathFollower automatically rotate to point in the direction of the Path? + */ + rotateToPath?: boolean; + /** + * If the PathFollower is rotating to match the Path, this value is added to the rotation value. This allows you to rotate objects to a path but control the angle of the rotation as well. + */ + rotationOffset?: number; + /** + * Current start position of the path follow, must be between `from` and `to`. + */ + startAt?: number; + }; + + } + + namespace RenderTexture { + type RenderTextureConfig = { + /** + * The x coordinate of the RenderTextures position. + */ + x?: number; + /** + * The y coordinate of the RenderTextures position. + */ + y?: number; + /** + * The width of the RenderTexture. + */ + width?: number; + /** + * The height of the RenderTexture. + */ + height?: number; + /** + * The texture key to make the RenderTexture from. + */ + key?: string; + /** + * the frame to make the RenderTexture from. + */ + frame?: string; + }; + + } + + namespace Sprite { + type SpriteConfig = Phaser.Types.GameObjects.GameObjectConfig & { + /** + * The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + */ + key?: string; + /** + * An optional frame from the Texture this Game Object is rendering with. + */ + frame?: number | string; + }; + + } + + namespace Text { + /** + * Font metrics for a Text Style object. + */ + type TextMetrics = { + /** + * The ascent of the font. + */ + ascent: number; + /** + * The descent of the font. + */ + descent: number; + /** + * The size of the font. + */ + fontSize: number; + }; + + /** + * A Text Padding configuration object as used by the Text Style. + */ + type TextPadding = { + /** + * If set this value is used for both the left and right padding. + */ + x?: number; + /** + * If set this value is used for both the top and bottom padding. + */ + y?: number; + /** + * The amount of padding added to the left of the Text object. + */ + left?: number; + /** + * The amount of padding added to the right of the Text object. + */ + right?: number; + /** + * The amount of padding added to the top of the Text object. + */ + top?: number; + /** + * The amount of padding added to the bottom of the Text object. + */ + bottom?: number; + }; + + /** + * A Text Shadow configuration object as used by the Text Style. + */ + type TextShadow = { + /** + * The horizontal offset of the shadow. + */ + offsetX?: number; + /** + * The vertical offset of the shadow. + */ + offsetY?: number; + /** + * The color of the shadow, given as a CSS string value. + */ + color?: string; + /** + * The amount of blur applied to the shadow. Leave as zero for a hard shadow. + */ + blur?: number; + /** + * Apply the shadow to the stroke effect on the Text object? + */ + stroke?: boolean; + /** + * Apply the shadow to the fill effect on the Text object? + */ + fill?: boolean; + }; + + /** + * A Text Style configuration object as used by the Text Game Object. + */ + type TextStyle = { + /** + * The font the Text object will render with. This is a Canvas style font string. + */ + fontFamily?: string; + /** + * The font size, as a CSS size string. + */ + fontSize?: string; + /** + * Any addition font styles, such as 'strong'. + */ + fontStyle?: string; + /** + * A solid fill color that is rendered behind the Text object. Given as a CSS string color such as `#ff0`. + */ + backgroundColor?: string; + /** + * The color the Text is drawn in. Given as a CSS string color such as `#fff` or `rgb()`. + */ + color?: string; + /** + * The color used to stroke the Text if the `strokeThickness` property is greater than zero. + */ + stroke?: string; + /** + * The thickness of the stroke around the Text. Set to zero for no stroke. + */ + strokeThickness?: number; + /** + * The Text shadow configuration object. + */ + shadow?: Phaser.Types.GameObjects.Text.TextShadow; + /** + * A Text Padding object. + */ + padding?: Phaser.Types.GameObjects.Text.TextPadding; + /** + * The alignment of the Text. This only impacts multi-line text. Either `left`, `right`, `center` or `justify`. + */ + align?: string; + /** + * The maximum number of lines to display within the Text object. + */ + maxLines?: integer; + /** + * Force the Text object to have the exact width specified in this property. Leave as zero for it to change accordingly to content. + */ + fixedWidth?: number; + /** + * Force the Text object to have the exact height specified in this property. Leave as zero for it to change accordingly to content. + */ + fixedHeight?: number; + /** + * Sets the resolution (DPI setting) of the Text object. Leave at zero for it to use the game resolution. + */ + resolution?: number; + /** + * Set to `true` if this Text object should render from right-to-left. + */ + rtl?: boolean; + /** + * This is the string used to aid Canvas in calculating the height of the font. + */ + testString?: string; + /** + * The amount of horizontal padding added to the width of the text when calculating the font metrics. + */ + baselineX?: number; + /** + * The amount of vertical padding added to the height of the text when calculating the font metrics. + */ + baselineY?: number; + /** + * The Text Word wrap configuration object. + */ + wordWrap?: Phaser.Types.GameObjects.Text.TextWordWrap; + /** + * A Text Metrics object. Use this to avoid expensive font size calculations in text heavy games. + */ + metrics?: Phaser.Types.GameObjects.Text.TextMetrics; + }; + + /** + * A Text Word Wrap configuration object as used by the Text Style configuration. + */ + type TextWordWrap = { + /** + * The width at which text should be considered for word-wrapping. + */ + width?: number; + /** + * Provide a custom callback when word wrapping is enabled. + */ + callback?: TextStyleWordWrapCallback; + /** + * The context in which the word wrap callback is invoked. + */ + callbackScope?: any; + /** + * Use basic or advanced word wrapping? + */ + useAdvancedWrap?: boolean; + }; + + } + + namespace TileSprite { + type TileSpriteConfig = Phaser.Types.GameObjects.GameObjectConfig & { + /** + * The x coordinate of the Tile Sprite. + */ + x?: number; + /** + * The y coordinate of the Tile Sprite. + */ + y?: number; + /** + * The width of the Tile Sprite. If zero it will use the size of the texture frame. + */ + width?: integer; + /** + * The height of the Tile Sprite. If zero it will use the size of the texture frame. + */ + height?: integer; + /** + * The key of the Texture this Tile Sprite will use to render with, as stored in the Texture Manager. + */ + key?: string; + /** + * An optional frame from the Texture this Tile Sprite is rendering with. + */ + frame?: string; + }; + + } + + type GameObjectConfig = { + /** + * The x position of the Game Object. + */ + x?: number; + /** + * The y position of the Game Object. + */ + y?: number; + /** + * The depth of the GameObject. + */ + depth?: number; + /** + * The horizontally flipped state of the Game Object. + */ + flipX?: boolean; + /** + * The vertically flipped state of the Game Object. + */ + flipY?: boolean; + /** + * The scale of the GameObject. + */ + scale?: number | object; + /** + * The scroll factor of the GameObject. + */ + scrollFactor?: number | object; + /** + * The rotation angle of the Game Object, in radians. + */ + rotation?: number; + /** + * The rotation angle of the Game Object, in degrees. + */ + angle?: number; + /** + * The alpha (opacity) of the Game Object. + */ + alpha?: number; + /** + * The origin of the Game Object. + */ + origin?: number | object; + /** + * The scale mode of the GameObject. + */ + scaleMode?: number; + /** + * The blend mode of the GameObject. + */ + blendMode?: number; + /** + * The visible state of the Game Object. + */ + visible?: boolean; + /** + * Add the GameObject to the scene. + */ + add?: boolean; + }; + + type JSONGameObject = { + /** + * The name of this Game Object. + */ + name: string; + /** + * A textual representation of this Game Object, i.e. `sprite`. + */ + type: string; + /** + * The x position of this Game Object. + */ + x: number; + /** + * The y position of this Game Object. + */ + y: number; + /** + * The scale of this Game Object + */ + scale: object; + /** + * The horizontal scale of this Game Object. + */ + "scale.x": number; + /** + * The vertical scale of this Game Object. + */ + "scale.y": number; + /** + * The origin of this Game Object. + */ + origin: object; + /** + * The horizontal origin of this Game Object. + */ + "origin.x": number; + /** + * The vertical origin of this Game Object. + */ + "origin.y": number; + /** + * The horizontally flipped state of the Game Object. + */ + flipX: boolean; + /** + * The vertically flipped state of the Game Object. + */ + flipY: boolean; + /** + * The angle of this Game Object in radians. + */ + rotation: number; + /** + * The alpha value of the Game Object. + */ + alpha: number; + /** + * The visible state of the Game Object. + */ + visible: boolean; + /** + * The Scale Mode being used by this Game Object. + */ + scaleMode: integer; + /** + * Sets the Blend Mode being used by this Game Object. + */ + blendMode: integer | string; + /** + * The texture key of this Game Object. + */ + textureKey: string; + /** + * The frame key of this Game Object. + */ + frameKey: string; + /** + * The data of this Game Object. + */ + data: object; + }; + + } + + namespace Input { + namespace Gamepad { + /** + * The Gamepad object, as extracted from GamepadEvent. + */ + type Pad = { + /** + * The ID of the Gamepad. + */ + id: string; + /** + * The index of the Gamepad. + */ + index: integer; + }; + + } + + namespace Keyboard { + type CursorKeys = { + /** + * A Key object mapping to the UP arrow key. + */ + up?: Phaser.Input.Keyboard.Key; + /** + * A Key object mapping to the DOWN arrow key. + */ + down?: Phaser.Input.Keyboard.Key; + /** + * A Key object mapping to the LEFT arrow key. + */ + left?: Phaser.Input.Keyboard.Key; + /** + * A Key object mapping to the RIGHT arrow key. + */ + right?: Phaser.Input.Keyboard.Key; + /** + * A Key object mapping to the SPACE BAR key. + */ + space?: Phaser.Input.Keyboard.Key; + /** + * A Key object mapping to the SHIFT key. + */ + shift?: Phaser.Input.Keyboard.Key; + }; + + type KeyboardKeydownCallback = (event: KeyboardEvent)=>void; + + type KeyComboConfig = { + /** + * If they press the wrong key do we reset the combo? + */ + resetOnWrongKey?: boolean; + /** + * The max delay in ms between each key press. Above this the combo is reset. 0 means disabled. + */ + maxKeyDelay?: number; + /** + * If previously matched and they press the first key of the combo again, will it reset? + */ + resetOnMatch?: boolean; + /** + * If the combo matches, will it delete itself? + */ + deleteOnMatch?: boolean; + }; + + } + + /** + * A Phaser Input Event Data object. + * + * This object is passed to the registered event listeners and allows you to stop any further propagation. + */ + type EventData = { + /** + * The cancelled state of this Event. + */ + cancelled?: boolean; + /** + * Call this method to stop this event from passing any further down the event chain. + */ + stopPropagation: Function; + }; + + type HitAreaCallback = (hitArea: any, x: number, y: number, gameObject: Phaser.GameObjects.GameObject)=>void; + + type InputConfiguration = { + /** + * The object / shape to use as the Hit Area. If not given it will try to create a Rectangle based on the texture frame. + */ + hitArea?: any; + /** + * The callback that determines if the pointer is within the Hit Area shape or not. + */ + hitAreaCallback?: Function; + /** + * If `true` the Interactive Object will be set to be draggable and emit drag events. + */ + draggable?: boolean; + /** + * If `true` the Interactive Object will be set to be a drop zone for draggable objects. + */ + dropZone?: boolean; + /** + * If `true` the Interactive Object will set the `pointer` hand cursor when a pointer is over it. This is a short-cut for setting `cursor: 'pointer'`. + */ + useHandCursor?: boolean; + /** + * The CSS string to be used when the cursor is over this Interactive Object. + */ + cursor?: string; + /** + * If `true` the a pixel perfect function will be set for the hit area callback. Only works with texture based Game Objects. + */ + pixelPerfect?: boolean; + /** + * If `pixelPerfect` is set, this is the alpha tolerance threshold value used in the callback. + */ + alphaTolerance?: integer; + }; + + type InputPluginContainer = { + /** + * The unique name of this plugin in the input plugin cache. + */ + key: string; + /** + * The plugin to be stored. Should be the source object, not instantiated. + */ + plugin: Function; + /** + * If this plugin is to be injected into the Input Plugin, this is the property key map used. + */ + mapping?: string; + }; + + type InteractiveObject = { + /** + * The Game Object to which this Interactive Object is bound. + */ + gameObject: Phaser.GameObjects.GameObject; + /** + * Is this Interactive Object currently enabled for input events? + */ + enabled: boolean; + /** + * An Interactive Object that is 'always enabled' will receive input even if the parent object is invisible or won't render. + */ + alwaysEnabled: boolean; + /** + * Is this Interactive Object draggable? Enable with `InputPlugin.setDraggable`. + */ + draggable: boolean; + /** + * Is this Interactive Object a drag-targets drop zone? Set when the object is created. + */ + dropZone: boolean; + /** + * Should this Interactive Object change the cursor (via css) when over? (desktop only) + */ + cursor: boolean | string; + /** + * An optional drop target for a draggable Interactive Object. + */ + target: Phaser.GameObjects.GameObject; + /** + * The most recent Camera to be tested against this Interactive Object. + */ + camera: Phaser.Cameras.Scene2D.Camera; + /** + * The hit area for this Interactive Object. Typically a geometry shape, like a Rectangle or Circle. + */ + hitArea: any; + /** + * The 'contains' check callback that the hit area shape will use for all hit tests. + */ + hitAreaCallback: Phaser.Types.Input.HitAreaCallback; + /** + * If this Interactive Object has been enabled for debug, via `InputPlugin.enableDebug` then this property holds its debug shape. + */ + hitAreaDebug: Phaser.GameObjects.Shape; + /** + * Was the hitArea for this Interactive Object created based on texture size (false), or a custom shape? (true) + */ + customHitArea: boolean; + /** + * The x coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + */ + localX: number; + /** + * The y coordinate that the Pointer interacted with this object on, relative to the Game Object's top-left position. + */ + localY: number; + /** + * The current drag state of this Interactive Object. 0 = Not being dragged, 1 = being checked for drag, or 2 = being actively dragged. + */ + dragState: 0 | 1 | 2; + /** + * The x coordinate of the Game Object that owns this Interactive Object when the drag started. + */ + dragStartX: number; + /** + * The y coordinate of the Game Object that owns this Interactive Object when the drag started. + */ + dragStartY: number; + /** + * The x coordinate that the Pointer started dragging this Interactive Object from. + */ + dragStartXGlobal: number; + /** + * The y coordinate that the Pointer started dragging this Interactive Object from. + */ + dragStartYGlobal: number; + /** + * The x coordinate that this Interactive Object is currently being dragged to. + */ + dragX: number; + /** + * The y coordinate that this Interactive Object is currently being dragged to. + */ + dragY: number; + }; + + } + + namespace Loader { + namespace FileTypes { + type AtlasJSONFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the texture image file from. + */ + textureURL?: string; + /** + * The default file extension to use for the image texture if no url is provided. + */ + textureExtension?: string; + /** + * Extra XHR Settings specifically for the texture image file. + */ + textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The filename of an associated normal map. It uses the same path and url to load as the texture image. + */ + normalMap?: string; + /** + * The absolute or relative URL to load the atlas json file from. Or a well formed JSON object to use instead. + */ + atlasURL?: string; + /** + * The default file extension to use for the atlas json if no url is provided. + */ + atlasExtension?: string; + /** + * Extra XHR Settings specifically for the atlas json file. + */ + atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type AtlasXMLFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the texture image file from. + */ + textureURL?: string; + /** + * The default file extension to use for the image texture if no url is provided. + */ + textureExtension?: string; + /** + * Extra XHR Settings specifically for the texture image file. + */ + textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The filename of an associated normal map. It uses the same path and url to load as the texture image. + */ + normalMap?: string; + /** + * The absolute or relative URL to load the atlas xml file from. + */ + atlasURL?: string; + /** + * The default file extension to use for the atlas xml if no url is provided. + */ + atlasExtension?: string; + /** + * Extra XHR Settings specifically for the atlas xml file. + */ + atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type AudioFileConfig = { + /** + * The key of the file. Must be unique within the Loader and Audio Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + urlConfig?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The AudioContext this file will use to process itself. + */ + audioContext?: AudioContext; + }; + + type AudioSpriteFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Audio Cache. + */ + key: string; + /** + * The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead. + */ + jsonURL: string; + /** + * Extra XHR Settings specifically for the json file. + */ + jsonXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The absolute or relative URL to load the audio file from. + */ + audioURL?: Object; + /** + * The audio configuration options. + */ + audioConfig?: any; + /** + * Extra XHR Settings specifically for the audio file. + */ + audioXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type BinaryFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Binary Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * Optional type to cast the binary file to once loaded. For example, `Uint8Array`. + */ + dataType?: any; + }; + + type BitmapFontFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the texture image file from. + */ + textureURL?: string; + /** + * The default file extension to use for the image texture if no url is provided. + */ + textureExtension?: string; + /** + * Extra XHR Settings specifically for the texture image file. + */ + textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The filename of an associated normal map. It uses the same path and url to load as the texture image. + */ + normalMap?: string; + /** + * The absolute or relative URL to load the font data xml file from. + */ + fontDataURL?: string; + /** + * The default file extension to use for the font data xml if no url is provided. + */ + fontDataExtension?: string; + /** + * Extra XHR Settings specifically for the font data xml file. + */ + fontDataXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type CSSFileConfig = { + /** + * The key of the file. Must be unique within the Loader. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type GLSLFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Text Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The type of shader. Either `fragment` for a fragment shader, or `vertex` for a vertex shader. This is ignored if you load a shader bundle. + */ + shaderType?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type HTMLFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Text Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type HTMLTextureFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The width of the texture the HTML will be rendered to. + */ + width?: integer; + /** + * The height of the texture the HTML will be rendered to. + */ + height?: integer; + }; + + type ImageFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * The filename of an associated normal map. It uses the same path and url to load as the image. + */ + normalMap?: string; + /** + * The frame configuration object. Only provided for, and used by, Sprite Sheets. + */ + frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type ImageFrameConfig = { + /** + * The width of the frame in pixels. + */ + frameWidth: integer; + /** + * The height of the frame in pixels. Uses the `frameWidth` value if not provided. + */ + frameHeight?: integer; + /** + * The first frame to start parsing from. + */ + startFrame?: integer; + /** + * The frame to stop parsing at. If not provided it will calculate the value based on the image and frame dimensions. + */ + endFrame?: integer; + /** + * The margin in the image. This is the space around the edge of the frames. + */ + margin?: integer; + /** + * The spacing between each frame in the image. + */ + spacing?: integer; + }; + + type JSONFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the JSON Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. Or can be a ready formed JSON object, in which case it will be directly added to the Cache. + */ + url?: string | any; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * If specified instead of the whole JSON file being parsed and added to the Cache, only the section corresponding to this property key will be added. If the property you want to extract is nested, use periods to divide it. + */ + dataKey?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type MultiAtlasFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the multi atlas json file from. Or, a well formed JSON object. + */ + atlasURL?: string; + /** + * An alias for 'atlasURL'. If given, it overrides anything set in 'atlasURL'. + */ + url?: string; + /** + * The default file extension to use for the atlas json if no url is provided. + */ + atlasExtension?: string; + /** + * Extra XHR Settings specifically for the atlas json file. + */ + atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * Optional path to use when loading the textures defined in the atlas data. + */ + path?: string; + /** + * Optional Base URL to use when loading the textures defined in the atlas data. + */ + baseURL?: string; + /** + * Extra XHR Settings specifically for the texture files. + */ + textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type MultiScriptFileConfig = { + /** + * The key of the file. Must be unique within the Loader. + */ + key: string; + /** + * An array of absolute or relative URLs to load the script files from. They are processed in the order given in the array. + */ + url?: string[]; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for these files. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type PackFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the JSON Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. Or can be a ready formed JSON object, in which case it will be directly processed. + */ + url?: string | any; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * If specified instead of the whole JSON file being parsed, only the section corresponding to this property key will be added. If the property you want to extract is nested, use periods to divide it. + */ + dataKey?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type PluginFileConfig = { + /** + * The key of the file. Must be unique within the Loader. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Automatically start the plugin after loading? + */ + start?: boolean; + /** + * If this plugin is to be injected into the Scene, this is the property key used. + */ + mapping?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type SceneFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Text Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type ScenePluginFileConfig = { + /** + * The key of the file. Must be unique within the Loader. + */ + key: string; + /** + * The absolute or relative URL to load the file from. Or, a Scene Plugin. + */ + url?: string | Function; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * If this plugin is to be added to Scene.Systems, this is the property key for it. + */ + systemKey?: string; + /** + * If this plugin is to be added to the Scene, this is the property key for it. + */ + sceneKey?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type ScriptFileConfig = { + /** + * The key of the file. Must be unique within the Loader. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type SpriteSheetFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * The filename of an associated normal map. It uses the same path and url to load as the image. + */ + normalMap?: string; + /** + * The frame configuration object. + */ + frameConfig?: Phaser.Types.Loader.FileTypes.ImageFrameConfig; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type SVGFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The svg size configuration object. + */ + svgConfig?: Phaser.Types.Loader.FileTypes.SVGSizeConfig; + }; + + type SVGSizeConfig = { + /** + * An optional width. The SVG will be resized to this size before being rendered to a texture. + */ + width?: integer; + /** + * An optional height. The SVG will be resized to this size before being rendered to a texture. + */ + height?: integer; + /** + * An optional scale. If given it overrides the width / height properties. The SVG is scaled by the scale factor before being rendered to a texture. + */ + scale?: number; + }; + + type TextFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Text Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type TilemapCSVFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Tilemap Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type TilemapImpactFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Tilemap Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type TilemapJSONFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Tilemap Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type UnityAtlasFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Texture Manager. + */ + key: string; + /** + * The absolute or relative URL to load the texture image file from. + */ + textureURL?: string; + /** + * The default file extension to use for the image texture if no url is provided. + */ + textureExtension?: string; + /** + * Extra XHR Settings specifically for the texture image file. + */ + textureXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + /** + * The filename of an associated normal map. It uses the same path and url to load as the texture image. + */ + normalMap?: string; + /** + * The absolute or relative URL to load the atlas data file from. + */ + atlasURL?: string; + /** + * The default file extension to use for the atlas data if no url is provided. + */ + atlasExtension?: string; + /** + * Extra XHR Settings specifically for the atlas data file. + */ + atlasXhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type VideoFileConfig = { + /** + * The key to use for this file, or a file configuration object. + */ + key: string | Phaser.Types.Loader.FileTypes.VideoFileConfig; + /** + * The absolute or relative URL to load this file from in a config object. + */ + urlConfig?: any; + /** + * The load event to listen for when _not_ loading as a blob. Either 'loadeddata', 'canplay' or 'canplaythrough'. + */ + loadEvent?: string; + /** + * Load the video as a data blob, or via the Video element? + */ + asBlob?: boolean; + /** + * Does the video have an audio track? If not you can enable auto-playing on it. + */ + noAudio?: boolean; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + type XMLFileConfig = { + /** + * The key of the file. Must be unique within both the Loader and the Text Cache. + */ + key: string; + /** + * The absolute or relative URL to load the file from. + */ + url?: string; + /** + * The default file extension to use if no url is provided. + */ + extension?: string; + /** + * Extra XHR Settings specifically for this file. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject; + }; + + } + + type FileConfig = { + /** + * The file type string (image, json, etc) for sorting within the Loader. + */ + type: string; + /** + * Unique cache key (unique within its file type) + */ + key: string; + /** + * The URL of the file, not including baseURL. + */ + url?: string; + /** + * The path of the file, not including the baseURL. + */ + path?: string; + /** + * The default extension this file uses. + */ + extension?: string; + /** + * The responseType to be used by the XHR request. + */ + responseType?: XMLHttpRequestResponseType; + /** + * Custom XHR Settings specific to this file and merged with the Loader defaults. + */ + xhrSettings?: Phaser.Types.Loader.XHRSettingsObject | false; + /** + * A config object that can be used by file types to store transitional data. + */ + config?: any; + }; + + type XHRSettingsObject = { + /** + * The response type of the XHR request, i.e. `blob`, `text`, etc. + */ + responseType: XMLHttpRequestResponseType; + /** + * Should the XHR request use async or not? + */ + async?: boolean; + /** + * Optional username for the XHR request. + */ + user?: string; + /** + * Optional password for the XHR request. + */ + password?: string; + /** + * Optional XHR timeout value. + */ + timeout?: integer; + /** + * This value is used to populate the XHR `setRequestHeader` and is undefined by default. + */ + header?: string | undefined; + /** + * This value is used to populate the XHR `setRequestHeader` and is undefined by default. + */ + headerValue?: string | undefined; + /** + * This value is used to populate the XHR `setRequestHeader` and is undefined by default. + */ + requestedWith?: string | undefined; + /** + * Provide a custom mime-type to use instead of the default. + */ + overrideMimeType?: string | undefined; + }; + + } + + namespace Math { + type SinCosTable = { + /** + * The sine value. + */ + sin: number; + /** + * The cosine value. + */ + cos: number; + /** + * The length. + */ + length: number; + }; + + type Vector2Like = { + /** + * The x component. + */ + x?: number; + /** + * The y component. + */ + y?: number; + }; + + } + + namespace Physics { + namespace Arcade { + type ArcadeBodyBounds = { + /** + * The left edge. + */ + x: number; + /** + * The upper edge. + */ + y: number; + /** + * The right edge. + */ + right: number; + /** + * The lower edge. + */ + bottom: number; + }; + + type ArcadeBodyCollision = { + /** + * True if the Body is not colliding. + */ + none: boolean; + /** + * True if the Body is colliding on its upper edge. + */ + up: boolean; + /** + * True if the Body is colliding on its lower edge. + */ + down: boolean; + /** + * True if the Body is colliding on its left edge. + */ + left: boolean; + /** + * True if the Body is colliding on its right edge. + */ + right: boolean; + }; + + /** + * An Arcade Physics Collider Type. + */ + type ArcadeColliderType = Phaser.GameObjects.GameObject | Phaser.GameObjects.Group | Phaser.Physics.Arcade.Sprite | Phaser.Physics.Arcade.Image | Phaser.Physics.Arcade.StaticGroup | Phaser.Physics.Arcade.Group | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer | Phaser.GameObjects.GameObject[] | Phaser.Physics.Arcade.Sprite[] | Phaser.Physics.Arcade.Image[] | Phaser.Physics.Arcade.StaticGroup[] | Phaser.Physics.Arcade.Group[] | Phaser.Tilemaps.DynamicTilemapLayer[] | Phaser.Tilemaps.StaticTilemapLayer[]; + + type ArcadeWorldConfig = { + /** + * Sets {@link Phaser.Physics.Arcade.World#fps}. + */ + fps?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#timeScale}. + */ + timeScale?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#gravity}. + */ + gravity?: Phaser.Types.Math.Vector2Like; + /** + * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.x}. + */ + x?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.y}. + */ + y?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.width}. + */ + width?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#bounds bounds.height}. + */ + height?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#checkCollision}. + */ + checkCollision?: Phaser.Types.Physics.Arcade.CheckCollisionObject; + /** + * Sets {@link Phaser.Physics.Arcade.World#OVERLAP_BIAS}. + */ + overlapBias?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#TILE_BIAS}. + */ + tileBias?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#forceX}. + */ + forceX?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.World#isPaused}. + */ + isPaused?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.World#debug}. + */ + debug?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.World#defaults debugShowBody}. + */ + debugShowBody?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.World#defaults debugShowStaticBody}. + */ + debugShowStaticBody?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.World#defaults debugShowStaticBody}. + */ + debugShowVelocity?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.World#defaults debugBodyColor}. + */ + debugBodyColor?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#defaults debugStaticBodyColor}. + */ + debugStaticBodyColor?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#defaults debugVelocityColor}. + */ + debugVelocityColor?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#maxEntries}. + */ + maxEntries?: number; + /** + * Sets {@link Phaser.Physics.Arcade.World#useTree}. + */ + useTree?: boolean; + }; + + type ArcadeWorldDefaults = { + /** + * Set to `true` to render dynamic body outlines to the debug display. + */ + debugShowBody: boolean; + /** + * Set to `true` to render static body outlines to the debug display. + */ + debugShowStaticBody: boolean; + /** + * Set to `true` to render body velocity markers to the debug display. + */ + debugShowVelocity: boolean; + /** + * The color of dynamic body outlines when rendered to the debug display. + */ + bodyDebugColor: number; + /** + * The color of static body outlines when rendered to the debug display. + */ + staticBodyDebugColor: number; + /** + * The color of the velocity markers when rendered to the debug display. + */ + velocityDebugColor: number; + }; + + type ArcadeWorldTreeMinMax = { + /** + * The minimum x value used in RTree searches. + */ + minX: number; + /** + * The minimum y value used in RTree searches. + */ + minY: number; + /** + * The maximum x value used in RTree searches. + */ + maxX: number; + /** + * The maximum y value used in RTree searches. + */ + maxY: number; + }; + + type CheckCollisionObject = { + /** + * Will bodies collide with the top side of the world bounds? + */ + up: boolean; + /** + * Will bodies collide with the bottom side of the world bounds? + */ + down: boolean; + /** + * Will bodies collide with the left side of the world bounds? + */ + left: boolean; + /** + * Will bodies collide with the right side of the world bounds? + */ + right: boolean; + }; + + type PhysicsGroupConfig = Phaser.Types.GameObjects.Group.GroupConfig & { + /** + * Sets {@link Phaser.Physics.Arcade.Body#collideWorldBounds}. + */ + collideWorldBounds?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.Body#setBoundsRectangle setBoundsRectangle}. + */ + customBoundsRectangle?: Phaser.Geom.Rectangle; + /** + * Sets {@link Phaser.Physics.Arcade.Body#acceleration acceleration.x}. + */ + accelerationX?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#acceleration acceleration.y}. + */ + accelerationY?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#allowDrag}. + */ + allowDrag?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.Body#allowGravity}. + */ + allowGravity?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.Body#allowRotation}. + */ + allowRotation?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.Body#bounce bounce.x}. + */ + bounceX?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#bounce bounce.y}. + */ + bounceY?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#drag drag.x}. + */ + dragX?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#drag drag.y}. + */ + dragY?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#enable enable}. + */ + enable?: boolean; + /** + * Sets {@link Phaser.Physics.Arcade.Body#gravity gravity.x}. + */ + gravityX?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#gravity gravity.y}. + */ + gravityY?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#friction friction.x}. + */ + frictionX?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#friction friction.y}. + */ + frictionY?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#velocity velocity.x}. + */ + velocityX?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#velocity velocity.y}. + */ + velocityY?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#angularVelocity}. + */ + angularVelocity?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#angularAcceleration}. + */ + angularAcceleration?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#angularDrag}. + */ + angularDrag?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#mass}. + */ + mass?: number; + /** + * Sets {@link Phaser.Physics.Arcade.Body#immovable}. + */ + immovable?: boolean; + }; + + type PhysicsGroupDefaults = { + /** + * As {@link Phaser.Physics.Arcade.Body#setCollideWorldBounds}. + */ + setCollideWorldBounds: boolean; + /** + * As {@link Phaser.Physics.Arcade.Body#setBoundsRectangle}. + */ + setBoundsRectangle: Phaser.Geom.Rectangle; + /** + * As {@link Phaser.Physics.Arcade.Body#setAccelerationX}. + */ + setAccelerationX: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setAccelerationY}. + */ + setAccelerationY: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setAllowDrag}. + */ + setAllowDrag: boolean; + /** + * As {@link Phaser.Physics.Arcade.Body#setAllowGravity}. + */ + setAllowGravity: boolean; + /** + * As {@link Phaser.Physics.Arcade.Body#setAllowRotation}. + */ + setAllowRotation: boolean; + /** + * As {@link Phaser.Physics.Arcade.Body#setBounceX}. + */ + setBounceX: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setBounceY}. + */ + setBounceY: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setDragX}. + */ + setDragX: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setDragY}. + */ + setDragY: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setEnable}. + */ + setEnable: boolean; + /** + * As {@link Phaser.Physics.Arcade.Body#setGravityX}. + */ + setGravityX: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setGravityY}. + */ + setGravityY: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setFrictionX}. + */ + setFrictionX: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setFrictionY}. + */ + setFrictionY: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setVelocityX}. + */ + setVelocityX: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setVelocityY}. + */ + setVelocityY: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setAngularVelocity}. + */ + setAngularVelocity: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setAngularAcceleration}. + */ + setAngularAcceleration: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setAngularDrag}. + */ + setAngularDrag: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setMass}. + */ + setMass: number; + /** + * As {@link Phaser.Physics.Arcade.Body#setImmovable}. + */ + setImmovable: boolean; + }; + + } + + namespace Impact { + type BodyUpdateCallback = (body: Phaser.Physics.Impact.Body)=>void; + + type CollisionOptions = { + /** + * Slope IDs can be stored on tiles directly + * using Impacts tileset editor. If a tile has a property with the given slopeTileProperty string + * name, the value of that property for the tile will be used for its slope mapping. E.g. a 45 + * degree slope upward could be given a "slope" property with a value of 2. + */ + slopeTileProperty?: string; + /** + * A tile index to slope definition map. + */ + slopeMap?: object; + /** + * If specified, the default slope ID to + * assign to a colliding tile. If not specified, the tile's index is used. + */ + defaultCollidingSlope?: integer; + /** + * The default slope ID to assign to a + * non-colliding tile. + */ + defaultNonCollidingSlope?: integer; + }; + + type JSONImpactBody = { + /** + * [description] + */ + name: string; + /** + * [description] + */ + size: Phaser.Types.Math.Vector2Like; + /** + * The entity's position in the game world. + */ + pos: Phaser.Types.Math.Vector2Like; + /** + * Current velocity in pixels per second. + */ + vel: Phaser.Types.Math.Vector2Like; + /** + * Current acceleration to be added to the entity's velocity per second. E.g. an entity with a `vel.x` of 0 and `accel.x` of 10 will have a `vel.x` of 100 ten seconds later. + */ + accel: Phaser.Types.Math.Vector2Like; + /** + * Deceleration to be subtracted from the entity's velocity per second. Only applies if `accel` is 0. + */ + friction: Phaser.Types.Math.Vector2Like; + /** + * The maximum velocity a body can move. + */ + maxVel: Phaser.Types.Math.Vector2Like; + /** + * [description] + */ + gravityFactor: number; + /** + * [description] + */ + bounciness: number; + /** + * [description] + */ + minBounceVelocity: number; + /** + * [description] + */ + type: Phaser.Physics.Impact.TYPE; + /** + * [description] + */ + checkAgainst: Phaser.Physics.Impact.TYPE; + /** + * [description] + */ + collides: Phaser.Physics.Impact.COLLIDES; + }; + + type WorldConfig = { + /** + * Sets {@link Phaser.Physics.Impact.World#gravity} + */ + gravity?: number; + /** + * The size of the cells used for the broadphase pass. Increase this value if you have lots of large objects in the world. + */ + cellSize?: number; + /** + * A number that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + */ + timeScale?: number; + /** + * [description] + */ + maxStep?: number; + /** + * Sets {@link Phaser.Physics.Impact.World#debug}. + */ + debug?: boolean; + /** + * The maximum velocity a body can move. + */ + maxVelocity?: number; + /** + * Whether the Body's boundary is drawn to the debug display. + */ + debugShowBody?: boolean; + /** + * Whether the Body's velocity is drawn to the debug display. + */ + debugShowVelocity?: boolean; + /** + * The color of this Body on the debug display. + */ + debugBodyColor?: number; + /** + * The color of the Body's velocity on the debug display. + */ + debugVelocityColor?: number; + /** + * Maximum X velocity objects can move. + */ + maxVelocityX?: number; + /** + * Maximum Y velocity objects can move. + */ + maxVelocityY?: number; + /** + * The minimum velocity an object can be moving at to be considered for bounce. + */ + minBounceVelocity?: number; + /** + * Gravity multiplier. Set to 0 for no gravity. + */ + gravityFactor?: number; + /** + * The default bounce, or restitution, of bodies in the world. + */ + bounciness?: number; + /** + * Should the world have bounds enabled by default? + */ + setBounds?: object | boolean; + /** + * The x coordinate of the world bounds. + */ + "setBounds.x"?: number; + /** + * The y coordinate of the world bounds. + */ + "setBounds.y"?: number; + /** + * The width of the world bounds. + */ + "setBounds.width"?: number; + /** + * The height of the world bounds. + */ + "setBounds.height"?: number; + /** + * The thickness of the walls of the world bounds. + */ + "setBounds.thickness"?: number; + /** + * Should the left-side world bounds wall be created? + */ + "setBounds.left"?: boolean; + /** + * Should the right-side world bounds wall be created? + */ + "setBounds.right"?: boolean; + /** + * Should the top world bounds wall be created? + */ + "setBounds.top"?: boolean; + /** + * Should the bottom world bounds wall be created? + */ + "setBounds.bottom"?: boolean; + }; + + /** + * An object containing the 4 wall bodies that bound the physics world. + */ + type WorldDefaults = { + /** + * Whether the Body's boundary is drawn to the debug display. + */ + debugShowBody: boolean; + /** + * Whether the Body's velocity is drawn to the debug display. + */ + debugShowVelocity: boolean; + /** + * The color of this Body on the debug display. + */ + bodyDebugColor: number; + /** + * The color of the Body's velocity on the debug display. + */ + velocityDebugColor: number; + /** + * Maximum X velocity objects can move. + */ + maxVelocityX: number; + /** + * Maximum Y velocity objects can move. + */ + maxVelocityY: number; + /** + * The minimum velocity an object can be moving at to be considered for bounce. + */ + minBounceVelocity: number; + /** + * Gravity multiplier. Set to 0 for no gravity. + */ + gravityFactor: number; + /** + * The default bounce, or restitution, of bodies in the world. + */ + bounciness: number; + }; + + type WorldWalls = { + /** + * The left-side wall of the world bounds. + */ + left: Phaser.Physics.Impact.Body; + /** + * The right-side wall of the world bounds. + */ + right: Phaser.Physics.Impact.Body; + /** + * The top wall of the world bounds. + */ + top: Phaser.Physics.Impact.Body; + /** + * The bottom wall of the world bounds. + */ + bottom: Phaser.Physics.Impact.Body; + }; + + } + + namespace Matter { + type MatterBody = MatterJS.BodyType | Phaser.GameObjects.GameObject | Phaser.Physics.Matter.Image | Phaser.Physics.Matter.Sprite | Phaser.Physics.Matter.TileBody; + + type MatterBodyConfig = { + /** + * An arbitrary string-based name to help identify this body. + */ + label?: string; + /** + * An array of bodies that make up this body. The first body in the array must always be a self reference to the current body instance. All bodies in the `parts` array together form a single rigid compound body. + */ + parts?: MatterJS.BodyType[]; + /** + * An object reserved for storing plugin-specific properties. + */ + plugin?: any; + /** + * A number specifying the angle of the body, in radians. + */ + angle?: number; + /** + * An array of `Vector` objects that specify the convex hull of the rigid body. These should be provided about the origin `(0, 0)`. + */ + vertices?: Phaser.Types.Math.Vector2Like[]; + /** + * A `Vector` that specifies the current world-space position of the body. + */ + position?: Phaser.Types.Math.Vector2Like; + /** + * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. + */ + force?: Phaser.Types.Math.Vector2Like; + /** + * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. + */ + torque?: number; + /** + * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + */ + isSensor?: boolean; + /** + * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. + */ + isStatic?: boolean; + /** + * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). + */ + sleepThreshold?: number; + /** + * 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). + */ + density?: number; + /** + * A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`. + */ + restitution?: number; + /** + * 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. + */ + friction?: number; + /** + * A `Number` that defines the static friction of the body (in the Coulomb friction model). A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. + */ + frictionStatic?: number; + /** + * A `Number` that defines the air friction of the body (air resistance). A value of `0` means the body will never slow as it moves through space. The higher the value, the faster a body slows when moving through space. + */ + frictionAir?: number; + /** + * An `Object` that specifies the collision filtering properties of this body. + */ + collisionFilter?: Phaser.Types.Physics.Matter.MatterCollisionFilter; + /** + * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. Avoid changing this value unless you understand the purpose of `slop` in physics engines. The default should generally suffice, although very large bodies may require larger values for stable stacking. + */ + slop?: number; + /** + * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + */ + timeScale?: number; + /** + * A number, or array of numbers, to chamfer the vertices of the body, or a full Chamfer configuration object. + */ + chamfer?: number | number[] | Phaser.Types.Physics.Matter.MatterChamferConfig; + /** + * The radius of this body if a circle. + */ + circleRadius?: number; + /** + * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). + */ + mass?: number; + /** + * A `Number` that defines the inverse mass of the body (`1 / mass`). If you modify this value, you must also modify the `body.mass` property. + */ + inverseMass?: number; + /** + * A `Vector` that specifies the initial scale of the body. + */ + scale?: Phaser.Types.Math.Vector2Like; + /** + * A `Vector` that scales the influence of World gravity when applied to this body. + */ + gravityScale?: Phaser.Types.Math.Vector2Like; + /** + * A boolean that toggles if this body should ignore world gravity or not. + */ + ignoreGravity?: boolean; + /** + * A boolean that toggles if this body should ignore pointer / mouse constraints or not. + */ + ignorePointer?: boolean; + /** + * The Debug Render configuration object for this body. + */ + render?: Phaser.Types.Physics.Matter.MatterBodyRenderConfig; + /** + * A callback that is invoked when this Body starts colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + */ + onCollideCallback?: Function; + /** + * A callback that is invoked when this Body stops colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + */ + onCollideEndCallback?: Function; + /** + * A callback that is invoked for the duration that this Body is colliding with any other Body. You can register callbacks by providing a function of type `( pair: Matter.Pair) => void`. + */ + onCollideActiveCallback?: Function; + /** + * A collision callback dictionary used by the `Body.setOnCollideWith` function. + */ + onCollideWith?: any; + }; + + type MatterBodyRenderConfig = { + /** + * Should this body be rendered by the Debug Renderer? + */ + visible?: boolean; + /** + * The opacity of the body and all parts within it. + */ + opacity?: number; + /** + * The color value of the fill when rendering this body. + */ + fillColor?: number; + /** + * The opacity of the fill when rendering this body, a value between 0 and 1. + */ + fillOpacity?: number; + /** + * The color value of the line stroke when rendering this body. + */ + lineColor?: number; + /** + * The opacity of the line when rendering this body, a value between 0 and 1. + */ + lineOpacity?: number; + /** + * If rendering lines, the thickness of the line. + */ + lineThickness?: number; + /** + * Controls the offset between the body and the parent Game Object, if it has one. + */ + sprite?: object; + /** + * The horizontal offset between the body and the parent Game Object texture, if it has one. + */ + "sprite.xOffset"?: number; + /** + * The vertical offset between the body and the parent Game Object texture, if it has one. + */ + "sprite.yOffset"?: number; + }; + + type MatterBodyTileOptions = { + /** + * Whether or not the newly created body should be made static. This defaults to true since typically tiles should not be moved. + */ + isStatic?: boolean; + /** + * Whether or not to add the newly created body (or existing body if options.body is used) to the Matter world. + */ + addToWorld?: boolean; + }; + + type MatterChamferConfig = { + /** + * A single number, or an array, to specify the radius for each vertex. + */ + radius?: number | number[]; + /** + * The quality of the chamfering. -1 means 'auto'. + */ + quality?: number; + /** + * The minimum quality of the chamfering. The higher this value, the more vertices are created. + */ + qualityMin?: number; + /** + * The maximum quality of the chamfering. The higher this value, the more vertices are created. + */ + qualityMax?: number; + }; + + type MatterCollisionData = { + /** + * Have the pair collided or not? + */ + collided: boolean; + /** + * A reference to the first body involved in the collision. + */ + bodyA: MatterJS.BodyType; + /** + * A reference to the second body involved in the collision. + */ + bodyB: MatterJS.BodyType; + /** + * A reference to the dominant axis body. + */ + axisBody: MatterJS.BodyType; + /** + * The index of the dominant collision axis vector (edge normal) + */ + axisNumber: number; + /** + * The depth of the collision on the minimum overlap. + */ + depth: number; + /** + * A reference to the parent of Body A, or to Body A itself if it has no parent. + */ + parentA: MatterJS.BodyType; + /** + * A reference to the parent of Body B, or to Body B itself if it has no parent. + */ + parentB: MatterJS.BodyType; + /** + * The collision normal, facing away from Body A. + */ + normal: MatterJS.Vector; + /** + * The tangent of the collision normal. + */ + tangent: MatterJS.Vector; + /** + * The penetration distances between the two bodies. + */ + penetration: MatterJS.Vector; + /** + * An array of support points, either exactly one or two points. + */ + supports: MatterJS.Vector[]; + /** + * The resulting inverse mass from the collision. + */ + inverseMass: number; + /** + * The resulting friction from the collision. + */ + friction: number; + /** + * The resulting static friction from the collision. + */ + frictionStatic: number; + /** + * The resulting restitution from the collision. + */ + restitution: number; + /** + * The resulting slop from the collision. + */ + slop: number; + }; + + /** + * An `Object` that specifies the collision filtering properties of this body. + * + * Collisions between two bodies will obey the following rules: + * - If the two bodies have the same non-zero value of `collisionFilter.group`, + * they will always collide if the value is positive, and they will never collide + * if the value is negative. + * - If the two bodies have different values of `collisionFilter.group` or if one + * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: + * + * Each body belongs to a collision category, given by `collisionFilter.category`. This + * value is used as a bit field and the category should have only one bit set, meaning that + * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 + * different collision categories available. + * + * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies + * the categories it collides with (the value is the bitwise AND value of all these categories). + * + * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's + * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` + * are both true. + */ + type MatterCollisionFilter = { + /** + * A bit field that specifies the collision category this body belongs to. The category value should have only one bit set, for example `0x0001`. This means there are up to 32 unique collision categories available. + */ + category?: number; + /** + * A bit mask that specifies the collision categories this body may collide with. + */ + mask?: number; + /** + * An Integer `Number`, that specifies the collision group this body belongs to. + */ + group?: number; + }; + + type MatterCollisionPair = { + /** + * The unique auto-generated collision pair id. A combination of the body A and B IDs. + */ + id: string; + /** + * A reference to the first body involved in the collision. + */ + bodyA: MatterJS.BodyType; + /** + * A reference to the second body involved in the collision. + */ + bodyB: MatterJS.BodyType; + /** + * An array containing all of the active contacts between bodies A and B. + */ + activeContacts: MatterJS.Vector[]; + /** + * The amount of separation that occured between bodies A and B. + */ + separation: number; + /** + * Is the collision still active or not? + */ + isActive: boolean; + /** + * Has Matter determined the collision are being active yet? + */ + confirmedActive: boolean; + /** + * Is either body A or B a sensor? + */ + isSensor: boolean; + /** + * The timestamp when the collision pair was created. + */ + timeCreated: number; + /** + * The timestamp when the collision pair was most recently updated. + */ + timeUpdated: number; + /** + * The collision data object. + */ + collision: Phaser.Types.Physics.Matter.MatterCollisionData; + /** + * The resulting inverse mass from the collision. + */ + inverseMass: number; + /** + * The resulting friction from the collision. + */ + friction: number; + /** + * The resulting static friction from the collision. + */ + frictionStatic: number; + /** + * The resulting restitution from the collision. + */ + restitution: number; + /** + * The resulting slop from the collision. + */ + slop: number; + }; + + type MatterConstraintConfig = { + /** + * An arbitrary string-based name to help identify this constraint. + */ + label?: string; + /** + * The first possible `Body` that this constraint is attached to. + */ + bodyA?: MatterJS.BodyType; + /** + * The second possible `Body` that this constraint is attached to. + */ + bodyB?: MatterJS.BodyType; + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. + */ + pointA?: Phaser.Types.Math.Vector2Like; + /** + * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. + */ + pointB?: Phaser.Types.Math.Vector2Like; + /** + * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts like a soft spring. + */ + stiffness?: number; + /** + * A `Number` that specifies the angular stiffness of the constraint. + */ + angularStiffness?: number; + /** + * The angleA of the constraint. If bodyA is set, the angle of bodyA is used instead. + */ + angleA?: number; + /** + * The angleB of the constraint. If bodyB is set, the angle of bodyB is used instead. + */ + angleB?: number; + /** + * 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. + */ + damping?: number; + /** + * A `Number` that specifies the target resting length of the constraint. It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + */ + length?: number; + /** + * An object reserved for storing plugin-specific properties. + */ + plugin?: any; + /** + * The Debug Render configuration object for this constraint. + */ + render?: Phaser.Types.Physics.Matter.MatterConstraintRenderConfig; + }; + + type MatterConstraintRenderConfig = { + /** + * Should this constraint be rendered by the Debug Renderer? + */ + visible?: boolean; + /** + * If this constraint has anchors, should they be rendered? Pin constraints never have anchors. + */ + anchors?: boolean; + /** + * The color value of the line stroke when rendering this constraint. + */ + lineColor?: number; + /** + * The opacity of the line when rendering this constraint, a value between 0 and 1. + */ + lineOpacity?: number; + /** + * If rendering lines, the thickness of the line. + */ + lineThickness?: number; + /** + * The size of the circles drawn when rendering pin constraints. + */ + pinSize?: number; + /** + * The size of the circles drawn as the constraint anchors. + */ + anchorSize?: number; + /** + * The color value of constraint anchors. + */ + anchorColor?: number; + }; + + type MatterDebugConfig = { + /** + * Render all of the body axes? + */ + showAxes?: boolean; + /** + * Render just a single body axis? + */ + showAngleIndicator?: boolean; + /** + * The color of the body angle / axes lines. + */ + angleColor?: boolean; + /** + * Render the broadphase grid? + */ + showBroadphase?: boolean; + /** + * The color of the broadphase grid. + */ + broadphaseColor?: boolean; + /** + * Render the bounds of the bodies in the world? + */ + showBounds?: boolean; + /** + * The color of the body bounds. + */ + boundsColor?: boolean; + /** + * Render the velocity of the bodies in the world? + */ + showVelocity?: boolean; + /** + * The color of the body velocity line. + */ + velocityColor?: boolean; + /** + * Render the collision points and normals for colliding pairs. + */ + showCollisions?: boolean; + /** + * The color of the collision points. + */ + collisionColor?: boolean; + /** + * Render lines showing the separation between bodies. + */ + showSeparation?: boolean; + /** + * The color of the body separation line. + */ + separationColor?: boolean; + /** + * Render the dynamic bodies in the world to the Graphics object? + */ + showBody?: boolean; + /** + * Render the static bodies in the world to the Graphics object? + */ + showStaticBody?: boolean; + /** + * When rendering bodies, render the internal edges as well? + */ + showInternalEdges?: boolean; + /** + * Render the bodies using a fill color. + */ + renderFill?: boolean; + /** + * Render the bodies using a line stroke. + */ + renderLine?: boolean; + /** + * The color value of the fill when rendering dynamic bodies. + */ + fillColor?: number; + /** + * The opacity of the fill when rendering dynamic bodies, a value between 0 and 1. + */ + fillOpacity?: number; + /** + * The color value of the line stroke when rendering dynamic bodies. + */ + lineColor?: number; + /** + * The opacity of the line when rendering dynamic bodies, a value between 0 and 1. + */ + lineOpacity?: number; + /** + * If rendering lines, the thickness of the line. + */ + lineThickness?: number; + /** + * The color value of the fill when rendering static bodies. + */ + staticFillColor?: number; + /** + * The color value of the line stroke when rendering static bodies. + */ + staticLineColor?: number; + /** + * Render any sleeping bodies (dynamic or static) in the world to the Graphics object? + */ + showSleeping?: boolean; + /** + * The amount to multiply the opacity of sleeping static bodies by. + */ + staticBodySleepOpacity?: number; + /** + * The color value of the fill when rendering sleeping dynamic bodies. + */ + sleepFillColor?: number; + /** + * The color value of the line stroke when rendering sleeping dynamic bodies. + */ + sleepLineColor?: number; + /** + * Render bodies or body parts that are flagged as being a sensor? + */ + showSensors?: boolean; + /** + * The fill color when rendering body sensors. + */ + sensorFillColor?: number; + /** + * The line color when rendering body sensors. + */ + sensorLineColor?: number; + /** + * Render the position of non-static bodies? + */ + showPositions?: boolean; + /** + * The size of the rectangle drawn when rendering the body position. + */ + positionSize?: number; + /** + * The color value of the rectangle drawn when rendering the body position. + */ + positionColor?: number; + /** + * Render all world constraints to the Graphics object? + */ + showJoint?: boolean; + /** + * The color value of joints when `showJoint` is set. + */ + jointColor?: number; + /** + * The line opacity when rendering joints, a value between 0 and 1. + */ + jointLineOpacity?: number; + /** + * The line thickness when rendering joints. + */ + jointLineThickness?: number; + /** + * The size of the circles drawn when rendering pin constraints. + */ + pinSize?: number; + /** + * The color value of the circles drawn when rendering pin constraints. + */ + pinColor?: number; + /** + * The color value of spring constraints. + */ + springColor?: number; + /** + * The color value of constraint anchors. + */ + anchorColor?: number; + /** + * The size of the circles drawn as the constraint anchors. + */ + anchorSize?: number; + /** + * When rendering polygon bodies, render the convex hull as well? + */ + showConvexHulls?: boolean; + /** + * The color value of hulls when `showConvexHulls` is set. + */ + hullColor?: number; + }; + + type MatterRunnerConfig = { + /** + * A boolean that specifies if the runner should use a fixed timestep (otherwise it is variable). If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). + */ + isFixed?: boolean; + /** + * A number that specifies the frame rate in seconds. If you don't specify this, but do specify `delta`, those values set the fps rate. + */ + fps?: number; + /** + * A 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. + */ + correction?: number; + /** + * The size of the delta smoothing array when `isFixed` is `false`. + */ + deltaSampleSize?: number; + /** + * A number that specifies the time step between updates in milliseconds. If you set the `fps` property, this value is set based on that. If `isFixed` is set to `true`, then `delta` is fixed. If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. + */ + delta?: number; + /** + * A number that specifies the minimum time step between updates in milliseconds. + */ + deltaMin?: number; + /** + * A number that specifies the maximum time step between updates in milliseconds. + */ + deltaMax?: number; + }; + + type MatterSetBodyConfig = { + /** + * The shape type. Either `rectangle`, `circle`, `trapezoid`, `polygon`, `fromVertices`, `fromVerts` or `fromPhysicsEditor`. + */ + type?: string; + /** + * The horizontal world position to place the body at. + */ + x?: number; + /** + * The vertical world position to place the body at. + */ + y?: number; + /** + * The width of the body. + */ + width?: number; + /** + * The height of the body. + */ + height?: number; + /** + * The radius of the body. Used by `circle` and `polygon` shapes. + */ + radius?: number; + /** + * The max sizes of the body. Used by the `circle` shape. + */ + maxSides?: number; + /** + * Used by the `trapezoid` shape. The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + */ + slope?: number; + /** + * Used by the `polygon` shape. The number of sides the polygon will have. + */ + sides?: number; + /** + * Used by the `fromVerts` shape. The vertices data. Either a path string or an array of vertices. + */ + verts?: string | any[]; + /** + * Used by the `fromVerts` shape. Flag internal edges (coincident part edges) + */ + flagInternal?: boolean; + /** + * Used by the `fromVerts` shape. Whether Matter.js will discard collinear edges (to improve performance). + */ + removeCollinear?: number; + /** + * Used by the `fromVerts` shape. During decomposition discard parts that have an area less than this. + */ + minimumArea?: number; + /** + * Should the new body be automatically added to the world? + */ + addToWorld?: boolean; + }; + + type MatterTileOptions = { + /** + * An existing Matter body to be used instead of creating a new one. + */ + body?: MatterJS.BodyType; + /** + * Whether or not the newly created body should be made static. This defaults to true since typically tiles should not be moved. + */ + isStatic?: boolean; + /** + * Whether or not to add the newly created body (or existing body if options.body is used) to the Matter world. + */ + addToWorld?: boolean; + }; + + type MatterWorldConfig = { + /** + * Sets {@link Phaser.Physics.Matter.World#gravity}. If `false` Gravity will be set to zero. + */ + gravity?: Phaser.Types.Math.Vector2Like | boolean; + /** + * Should the world have bounds enabled by default? + */ + setBounds?: object | boolean; + /** + * The x coordinate of the world bounds. + */ + "setBounds.x"?: number; + /** + * The y coordinate of the world bounds. + */ + "setBounds.y"?: number; + /** + * The width of the world bounds. + */ + "setBounds.width"?: number; + /** + * The height of the world bounds. + */ + "setBounds.height"?: number; + /** + * The thickness of the walls of the world bounds. + */ + "setBounds.thickness"?: number; + /** + * Should the left-side world bounds wall be created? + */ + "setBounds.left"?: boolean; + /** + * Should the right-side world bounds wall be created? + */ + "setBounds.right"?: boolean; + /** + * Should the top world bounds wall be created? + */ + "setBounds.top"?: boolean; + /** + * Should the bottom world bounds wall be created? + */ + "setBounds.bottom"?: boolean; + /** + * The number of position iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + */ + positionIterations?: number; + /** + * The number of velocity iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + */ + velocityIterations?: number; + /** + * The number of constraint iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + */ + constraintIterations?: number; + /** + * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. Sleeping can improve stability and performance, but often at the expense of accuracy. + */ + enableSleeping?: boolean; + /** + * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. It is incremented on every `Engine.update` by the given `delta` argument. + */ + "timing.timestamp"?: number; + /** + * A `Number` that specifies the global scaling factor of time for all bodies. A value of `0` freezes the simulation. A value of `0.1` gives a slow-motion effect. A value of `1.2` gives a speed-up effect. + */ + "timing.timeScale"?: number; + /** + * Should the Matter Attractor Plugin be enabled? An attractors plugin that makes it easy to apply continual forces on bodies. It's possible to simulate effects such as wind, gravity and magnetism. + */ + "plugins.attractors"?: boolean; + /** + * Should the Matter Wrap Plugin be enabled? A coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, while maintaining its velocity. + */ + "plugins.wrap"?: boolean; + /** + * Should the Matter Collision Events Plugin be enabled? + */ + "plugins.collisionevents"?: boolean; + /** + * Toggles if the world is enabled or not. + */ + enabled?: boolean; + /** + * An optional Number that specifies the time correction factor to apply to the update. + */ + correction?: number; + /** + * This function is called every time the core game loop steps, which is bound to the Request Animation Frame frequency unless otherwise modified. + */ + getDelta?: Function; + /** + * Automatically call Engine.update every time the game steps. + */ + autoUpdate?: boolean; + /** + * Sets the Resolver resting threshold property. + */ + restingThresh?: number; + /** + * Sets the Resolver resting threshold tangent property. + */ + restingThreshTangent?: number; + /** + * Sets the Resolver position dampen property. + */ + positionDampen?: number; + /** + * Sets the Resolver position warming property. + */ + positionWarming?: number; + /** + * Sets the Resolver friction normal multiplier property. + */ + frictionNormalMultiplier?: number; + /** + * Controls the Matter Debug Rendering options. If a boolean it will use the default values, otherwise, specify a Debug Config object. + */ + debug?: boolean | Phaser.Types.Physics.Matter.MatterDebugConfig; + /** + * Sets the Matter Runner options. + */ + runner?: Phaser.Types.Physics.Matter.MatterRunnerConfig; + }; + + } + + } + + namespace Plugins { + type CorePluginContainer = { + /** + * The unique name of this plugin in the core plugin cache. + */ + key: string; + /** + * The plugin to be stored. Should be the source object, not instantiated. + */ + plugin: Function; + /** + * If this plugin is to be injected into the Scene Systems, this is the property key map used. + */ + mapping?: string; + /** + * Core Scene plugin or a Custom Scene plugin? + */ + custom?: boolean; + }; + + type CustomPluginContainer = { + /** + * The unique name of this plugin in the custom plugin cache. + */ + key: string; + /** + * The plugin to be stored. Should be the source object, not instantiated. + */ + plugin: Function; + }; + + type GlobalPlugin = { + /** + * The unique name of this plugin within the plugin cache. + */ + key: string; + /** + * An instance of the plugin. + */ + plugin: Function; + /** + * Is the plugin active or not? + */ + active?: boolean; + /** + * If this plugin is to be injected into the Scene Systems, this is the property key map used. + */ + mapping?: string; + }; + + } + + namespace Renderer { + namespace Snapshot { + type SnapshotCallback = (snapshot: Phaser.Display.Color | HTMLImageElement)=>void; + + type SnapshotState = { + /** + * The function to call after the snapshot is taken. + */ + callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback; + /** + * The format of the image to create, usually `image/png` or `image/jpeg`. + */ + type?: string; + /** + * The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. + */ + encoderOptions?: number; + /** + * The x coordinate to start the snapshot from. + */ + x?: integer; + /** + * The y coordinate to start the snapshot from. + */ + y?: integer; + /** + * The width of the snapshot. + */ + width?: integer; + /** + * The height of the snapshot. + */ + height?: integer; + /** + * Is this a snapshot to get a single pixel, or an area? + */ + getPixel?: boolean; + /** + * Is this snapshot grabbing from a frame buffer or a canvas? + */ + isFramebuffer?: boolean; + /** + * The width of the frame buffer, if a frame buffer grab. + */ + bufferWidth?: integer; + /** + * The height of the frame buffer, if a frame buffer grab. + */ + bufferHeight?: integer; + }; + + } + + } + + namespace Scenes { + type CreateSceneFromObjectConfig = { + /** + * The scene's init callback. + */ + init?: Phaser.Types.Scenes.SceneInitCallback; + /** + * The scene's preload callback. + */ + preload?: Phaser.Types.Scenes.ScenePreloadCallback; + /** + * The scene's create callback. + */ + create?: Phaser.Types.Scenes.SceneCreateCallback; + /** + * The scene's update callback. See {@link Phaser.Scene#update}. + */ + update?: Function; + /** + * Any additional properties, which will be copied to the Scene after it's created (except `data` or `sys`). + */ + extend?: any; + /** + * Any values, which will be merged into the Scene's Data Manager store. + */ + "extend.data"?: any; + }; + + /** + * Can be defined on your own Scenes. Use it to create your game objects. + * This method is called by the Scene Manager when the scene starts, after `init()` and `preload()`. + * If the LoaderPlugin started after `preload()`, then this method is called only after loading is complete. + */ + type SceneCreateCallback = (data: object)=>void; + + /** + * Can be defined on your own Scenes. + * This method is called by the Scene Manager when the scene starts, before `preload()` and `create()`. + */ + type SceneInitCallback = (data: object)=>void; + + /** + * Can be defined on your own Scenes. Use it to load assets. + * This method is called by the Scene Manager, after `init()` and before `create()`, only if the Scene has a LoaderPlugin. + * After this method completes, if the LoaderPlugin's queue isn't empty, the LoaderPlugin will start automatically. + */ + type ScenePreloadCallback = ()=>void; + + type SceneTransitionConfig = { + /** + * The Scene key to transition to. + */ + target: string; + /** + * The duration, in ms, for the transition to last. + */ + duration?: integer; + /** + * Will the Scene responsible for the transition be sent to sleep on completion (`true`), or stopped? (`false`) + */ + sleep?: boolean; + /** + * Will the Scenes Input system be able to process events while it is transitioning in or out? + */ + allowInput?: boolean; + /** + * Move the target Scene to be above this one before the transition starts. + */ + moveAbove?: boolean; + /** + * Move the target Scene to be below this one before the transition starts. + */ + moveBelow?: boolean; + /** + * This callback is invoked every frame for the duration of the transition. + */ + onUpdate?: Function; + /** + * The context in which the callback is invoked. + */ + onUpdateScope?: any; + /** + * An object containing any data you wish to be passed to the target Scenes init / create methods. + */ + data?: any; + }; + + type SettingsConfig = { + /** + * The unique key of this Scene. Must be unique within the entire Game instance. + */ + key?: string; + /** + * Does the Scene start as active or not? An active Scene updates each step. + */ + active?: boolean; + /** + * Does the Scene start as visible or not? A visible Scene renders each step. + */ + visible?: boolean; + /** + * An optional Loader Packfile to be loaded before the Scene begins. + */ + pack?: false | Phaser.Types.Loader.FileTypes.PackFileConfig; + /** + * An optional Camera configuration object. + */ + cameras?: Phaser.Types.Cameras.Scene2D.JSONCamera | Phaser.Types.Cameras.Scene2D.JSONCamera[]; + /** + * Overwrites the default injection map for a scene. + */ + map?: {[key: string]: string}; + /** + * Extends the injection map for a scene. + */ + mapAdd?: {[key: string]: string}; + /** + * The physics configuration object for the Scene. + */ + physics?: Phaser.Types.Core.PhysicsConfig; + /** + * The loader configuration object for the Scene. + */ + loader?: Phaser.Types.Core.LoaderConfig; + /** + * The plugin configuration object for the Scene. + */ + plugins?: false | any; + }; + + type SettingsObject = { + /** + * The current status of the Scene. Maps to the Scene constants. + */ + status: number; + /** + * The unique key of this Scene. Unique within the entire Game instance. + */ + key: string; + /** + * The active state of this Scene. An active Scene updates each step. + */ + active: boolean; + /** + * The visible state of this Scene. A visible Scene renders each step. + */ + visible: boolean; + /** + * Has the Scene finished booting? + */ + isBooted: boolean; + /** + * Is the Scene in a state of transition? + */ + isTransition: boolean; + /** + * The Scene this Scene is transitioning from, if set. + */ + transitionFrom: Phaser.Scene; + /** + * The duration of the transition, if set. + */ + transitionDuration: integer; + /** + * Is this Scene allowed to receive input during transitions? + */ + transitionAllowInput: boolean; + /** + * a data bundle passed to this Scene from the Scene Manager. + */ + data: object; + /** + * The Loader Packfile to be loaded before the Scene begins. + */ + pack: false | Phaser.Types.Loader.FileTypes.PackFileConfig; + /** + * The Camera configuration object. + */ + cameras: Phaser.Types.Cameras.Scene2D.JSONCamera | Phaser.Types.Cameras.Scene2D.JSONCamera[]; + /** + * The Scene's Injection Map. + */ + map: {[key: string]: string}; + /** + * The physics configuration object for the Scene. + */ + physics: Phaser.Types.Core.PhysicsConfig; + /** + * The loader configuration object for the Scene. + */ + loader: Phaser.Types.Core.LoaderConfig; + /** + * The plugin configuration object for the Scene. + */ + plugins: false | any; + }; + + } + + namespace Sound { + /** + * Audio sprite sound type. + */ + type AudioSpriteSound = { + /** + * Local reference to 'spritemap' object form json file generated by audiosprite tool. + */ + spritemap: object; + }; + + /** + * A Audio Data object. + * + * You can pass an array of these objects to the WebAudioSoundManager `decodeAudio` method to have it decode + * them all at once. + */ + type DecodeAudioConfig = { + /** + * The string-based key to be used to reference the decoded audio in the audio cache. + */ + key: string; + /** + * The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + */ + data: ArrayBuffer | string; + }; + + type EachActiveSoundCallback = (manager: Phaser.Sound.BaseSoundManager, sound: Phaser.Sound.BaseSound, index: number, sounds: Phaser.Sound.BaseSound[])=>void; + + /** + * Config object containing various sound settings. + */ + type SoundConfig = { + /** + * Boolean indicating whether the sound should be muted or not. + */ + mute?: boolean; + /** + * A value between 0 (silence) and 1 (full volume). + */ + volume?: number; + /** + * Defines the speed at which the sound should be played. + */ + rate?: number; + /** + * Represents detuning of sound in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29). + */ + detune?: number; + /** + * Position of playback for this sound, in seconds. + */ + seek?: number; + /** + * Whether or not the sound or current sound marker should loop. + */ + loop?: boolean; + /** + * Time, in seconds, that should elapse before the sound actually starts its playback. + */ + delay?: number; + }; + + /** + * Marked section of a sound represented by name, and optionally start time, duration, and config object. + */ + type SoundMarker = { + /** + * Unique identifier of a sound marker. + */ + name: string; + /** + * Sound position offset at witch playback should start. + */ + start?: number; + /** + * Playback duration of this marker. + */ + duration?: number; + /** + * An optional config object containing default marker settings. + */ + config?: Phaser.Types.Sound.SoundConfig; + }; + + } + + namespace Textures { + /** + * An object containing the position and color data for a single pixel in a CanvasTexture. + */ + type PixelConfig = { + /** + * The x-coordinate of the pixel. + */ + x: integer; + /** + * The y-coordinate of the pixel. + */ + y: integer; + /** + * The color of the pixel, not including the alpha channel. + */ + color: integer; + /** + * The alpha of the pixel, between 0 and 1. + */ + alpha: number; + }; + + type SpriteSheetConfig = { + /** + * The fixed width of each frame. + */ + frameWidth: integer; + /** + * The fixed height of each frame. If not set it will use the frameWidth as the height. + */ + frameHeight?: integer; + /** + * Skip a number of frames. Useful when there are multiple sprite sheets in one Texture. + */ + startFrame?: integer; + /** + * The total number of frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + */ + endFrame?: integer; + /** + * If the frames have been drawn with a margin, specify the amount here. + */ + margin?: integer; + /** + * If the frames have been drawn with spacing between them, specify the amount here. + */ + spacing?: integer; + }; + + type SpriteSheetFromAtlasConfig = { + /** + * The key of the Texture Atlas in which this Sprite Sheet can be found. + */ + atlas: string; + /** + * The key of the Texture Atlas Frame in which this Sprite Sheet can be found. + */ + frame: string; + /** + * The fixed width of each frame. + */ + frameWidth: integer; + /** + * The fixed height of each frame. If not set it will use the frameWidth as the height. + */ + frameHeight?: integer; + /** + * Skip a number of frames. Useful when there are multiple sprite sheets in one Texture. + */ + startFrame?: integer; + /** + * The total number of frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + */ + endFrame?: integer; + /** + * If the frames have been drawn with a margin, specify the amount here. + */ + margin?: integer; + /** + * If the frames have been drawn with spacing between them, specify the amount here. + */ + spacing?: integer; + }; + + } + + namespace Tilemaps { + type FilteringOptions = { + /** + * If true, only return tiles that don't have -1 for an index. + */ + isNotEmpty?: boolean; + /** + * If true, only return tiles that collide on at least one side. + */ + isColliding?: boolean; + /** + * If true, only return tiles that have at least one interesting face. + */ + hasInterestingFace?: boolean; + }; + + type GetTilesWithinFilteringOptions = { + /** + * If true, only return tiles that don't have -1 for an index. + */ + isNotEmpty?: boolean; + /** + * If true, only return tiles that collide on at least one side. + */ + isColliding?: boolean; + /** + * If true, only return tiles that have at least one interesting face. + */ + hasInterestingFace?: boolean; + }; + + type MapDataConfig = { + /** + * The key in the Phaser cache that corresponds to the loaded tilemap data. + */ + name?: string; + /** + * The width of the entire tilemap. + */ + width?: number; + /** + * The height of the entire tilemap. + */ + height?: number; + /** + * The width of the tiles. + */ + tileWidth?: number; + /** + * The height of the tiles. + */ + tileHeight?: number; + /** + * The width in pixels of the entire tilemap. + */ + widthInPixels?: number; + /** + * The height in pixels of the entire tilemap. + */ + heightInPixels?: number; + /** + * The format of the Tilemap, as defined in Tiled. + */ + format?: integer; + /** + * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. + */ + orientation?: string; + /** + * Determines the draw order of tilemap. Default is right-down. + */ + renderOrder?: string; + /** + * The version of Tiled the map uses. + */ + version?: number; + /** + * Map specific properties (can be specified in Tiled). + */ + properties?: number; + /** + * The layers of the tilemap. + */ + layers?: Phaser.Tilemaps.LayerData[]; + /** + * An array with all the layers configured to the MapData. + */ + images?: any[]; + /** + * An array of Tiled Image Layers. + */ + objects?: object; + /** + * An object of Tiled Object Layers. + */ + collision?: object; + /** + * The tilesets the map uses. + */ + tilesets?: Phaser.Tilemaps.Tileset[]; + /** + * The collection of images the map uses(specified in Tiled). + */ + imageCollections?: any[]; + /** + * [description] + */ + tiles?: any[]; + }; + + type ObjectLayerConfig = { + /** + * The name of the Object Layer. + */ + name?: string; + /** + * The opacity of the layer, between 0 and 1. + */ + opacity?: number; + /** + * The custom properties defined on the Object Layer, keyed by their name. + */ + properties?: any; + /** + * The type of each custom property defined on the Object Layer, keyed by its name. + */ + propertytypes?: any; + /** + * The type of the layer, which should be `objectgroup`. + */ + type?: string; + /** + * Whether the layer is shown (`true`) or hidden (`false`). + */ + visible?: boolean; + /** + * An array of all objects on this Object Layer. + */ + objects?: any[]; + }; + + type StyleConfig = { + /** + * Color to use for drawing a filled rectangle at non-colliding tile locations. If set to null, non-colliding tiles will not be drawn. + */ + tileColor?: Phaser.Display.Color | number | null; + /** + * Color to use for drawing a filled rectangle at colliding tile locations. If set to null, colliding tiles will not be drawn. + */ + collidingTileColor?: Phaser.Display.Color | number | null; + /** + * Color to use for drawing a line at interesting tile faces. If set to null, interesting tile faces will not be drawn. + */ + faceColor?: Phaser.Display.Color | number | null; + }; + + type TiledObject = { + /** + * The unique object ID. + */ + id: integer; + /** + * The name this object was assigned in Tiled. + */ + name: string; + /** + * The type, as assigned in Tiled. + */ + type: string; + /** + * The visible state of this object. + */ + visible?: boolean; + /** + * The horizontal position of this object, in pixels, relative to the tilemap. + */ + x?: number; + /** + * The vertical position of this object, in pixels, relative to the tilemap. + */ + y?: number; + /** + * The width of this object, in pixels. + */ + width?: number; + /** + * The height of this object, in pixels. + */ + height?: number; + /** + * The rotation of the object in clockwise degrees. + */ + rotation?: number; + /** + * Custom properties object. + */ + properties?: any; + /** + * Only set if of type 'tile'. + */ + gid?: integer; + /** + * Only set if a tile object. The horizontal flip value. + */ + flippedHorizontal?: boolean; + /** + * Only set if a tile object. The vertical flip value. + */ + flippedVertical?: boolean; + /** + * Only set if a tile object. The diagonal flip value. + */ + flippedAntiDiagonal?: boolean; + /** + * Only set if a polyline object. An array of objects corresponding to points, where each point has an `x` property and a `y` property. + */ + polyline?: Phaser.Types.Math.Vector2Like[]; + /** + * Only set if a polygon object. An array of objects corresponding to points, where each point has an `x` property and a `y` property. + */ + polygon?: Phaser.Types.Math.Vector2Like[]; + /** + * Only set if a text object. Contains the text objects properties. + */ + text?: any; + /** + * Only set, and set to `true`, if a rectangle object. + */ + rectangle?: boolean; + /** + * Only set, and set to `true`, if a ellipse object. + */ + ellipse?: boolean; + }; + + type TilemapConfig = { + /** + * The key in the Phaser cache that corresponds to the loaded tilemap data. + */ + key?: string; + /** + * Instead of loading from the cache, you can also load directly from a 2D array of tile indexes. + */ + data?: integer[][]; + /** + * The width of a tile in pixels. + */ + tileWidth?: integer; + /** + * The height of a tile in pixels. + */ + tileHeight?: integer; + /** + * The width of the map in tiles. + */ + width?: integer; + /** + * The height of the map in tiles. + */ + height?: integer; + /** + * 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've 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. + */ + insertNull?: boolean; + }; + + } + + namespace Time { + type TimerEventConfig = { + /** + * The delay after which the Timer Event should fire, in milliseconds. + */ + delay?: number; + /** + * The total number of times the Timer Event will repeat before finishing. + */ + repeat?: number; + /** + * `true` if the Timer Event should repeat indefinitely. + */ + loop?: boolean; + /** + * The callback which will be called when the Timer Event fires. + */ + callback?: Function; + /** + * The scope (`this` object) with which to invoke the `callback`. + */ + callbackScope?: any; + /** + * Additional arguments to be passed to the `callback`. + */ + args?: any[]; + /** + * The scale of the elapsed time. + */ + timeScale?: number; + /** + * The initial elapsed time in milliseconds. Useful if you want a long duration with repeat, but for the first loop to fire quickly. + */ + startAt?: number; + /** + * `true` if the Timer Event should be paused. + */ + paused?: boolean; + }; + + } + + namespace Tweens { + type TweenConfigDefaults = { + /** + * The object, or an array of objects, to run the tween on. + */ + targets: object | object[]; + /** + * The number of milliseconds to delay before the tween will start. + */ + delay?: number; + /** + * The duration of the tween in milliseconds. + */ + duration?: number; + /** + * The easing equation to use for the tween. + */ + ease?: string; + /** + * Optional easing parameters. + */ + easeParams?: any[]; + /** + * The number of milliseconds to hold the tween for before yoyo'ing. + */ + hold?: number; + /** + * The number of times to repeat the tween. + */ + repeat?: number; + /** + * The number of milliseconds to pause before a tween will repeat. + */ + repeatDelay?: number; + /** + * Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. + */ + yoyo?: boolean; + /** + * Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. + */ + flipX?: boolean; + /** + * Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. + */ + flipY?: boolean; + }; + + /** + * A Tween Event. + */ + type Event = string; + + type GetActiveCallback = (target: any, key: string, value: number, targetIndex: integer, totalTargets: integer, tween: Phaser.Tweens.Tween)=>void; + + type GetEndCallback = (target: any, key: string, value: number, targetIndex: integer, totalTargets: integer, tween: Phaser.Tweens.Tween)=>void; + + type GetStartCallback = (target: any, key: string, value: number, targetIndex: integer, totalTargets: integer, tween: Phaser.Tweens.Tween)=>void; + + type NumberTweenBuilderConfig = { + /** + * The start number. + */ + from?: number; + /** + * The end number. + */ + to?: number; + /** + * The number of milliseconds to delay before the tween will start. + */ + delay?: number; + /** + * The duration of the tween in milliseconds. + */ + duration?: number; + /** + * The easing equation to use for the tween. + */ + ease?: string | Function; + /** + * Optional easing parameters. + */ + easeParams?: any[]; + /** + * The number of milliseconds to hold the tween for before yoyo'ing. + */ + hold?: number; + /** + * The number of times to repeat the tween. + */ + repeat?: number; + /** + * The number of milliseconds to pause before a tween will repeat. + */ + repeatDelay?: number; + /** + * Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. + */ + yoyo?: boolean; + /** + * Used when the Tween is part of a Timeline. + */ + offset?: number | Function | object | any[]; + /** + * The time the tween will wait before the onComplete event is dispatched once it has completed, in ms. + */ + completeDelay?: number | Function | object | any[]; + /** + * The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once. + */ + loop?: number | Function | object | any[]; + /** + * The time the tween will pause before starting either a yoyo or returning to the start for a repeat. + */ + loopDelay?: number | Function | object | any[]; + /** + * Does the tween start in a paused state (true) or playing (false)? + */ + paused?: boolean; + /** + * Use frames or milliseconds? + */ + useFrames?: boolean; + /** + * Scope (this) for the callbacks. The default scope is the tween. + */ + callbackScope?: any; + /** + * A function to call when the tween completes. + */ + onComplete?: Phaser.Types.Tweens.TweenOnCompleteCallback; + /** + * Additional parameters to pass to `onComplete`. + */ + onCompleteParams?: any[]; + /** + * Scope (this) for `onComplete`. + */ + onCompleteScope?: any; + /** + * A function to call each time the tween loops. + */ + onLoop?: Phaser.Types.Tweens.TweenOnLoopCallback; + /** + * Additional parameters to pass to `onLoop`. + */ + onLoopParams?: any[]; + /** + * Scope (this) for `onLoop`. + */ + onLoopScope?: any; + /** + * A function to call each time the tween repeats. Called once per property per target. + */ + onRepeat?: Phaser.Types.Tweens.TweenOnRepeatCallback; + /** + * Additional parameters to pass to `onRepeat`. + */ + onRepeatParams?: any[]; + /** + * Scope (this) for `onRepeat`. + */ + onRepeatScope?: any; + /** + * A function to call when the tween starts. + */ + onStart?: Phaser.Types.Tweens.TweenOnStartCallback; + /** + * Additional parameters to pass to `onStart`. + */ + onStartParams?: any[]; + /** + * Scope (this) for `onStart`. + */ + onStartScope?: any; + /** + * A function to call each time the tween steps. Called once per property per target. + */ + onUpdate?: Phaser.Types.Tweens.TweenOnUpdateCallback; + /** + * Additional parameters to pass to `onUpdate`. + */ + onUpdateParams?: any[]; + /** + * Scope (this) for `onUpdate`. + */ + onUpdateScope?: any; + /** + * A function to call each time the tween yoyos. Called once per property per target. + */ + onYoyo?: Phaser.Types.Tweens.TweenOnYoyoCallback; + /** + * Additional parameters to pass to `onYoyo`. + */ + onYoyoParams?: any[]; + /** + * Scope (this) for `onYoyo`. + */ + onYoyoScope?: any; + }; + + type StaggerConfig = { + /** + * The value to start the stagger from. Can be used as a way to offset the stagger while still using a range for the value. + */ + start?: number; + /** + * An ease to apply across the staggered values. Can either be a string, such as 'sine.inout', or a function. + */ + ease?: string | Function; + /** + * The index to start the stagger from. Can be the strings `first`, `last` or `center`, or an integer representing the stagger position. + */ + from?: string | integer; + /** + * Set the stagger to run across a grid by providing an array where element 0 is the width of the grid and element 1 is the height. Combine with the 'from' property to control direction. + */ + grid?: integer[]; + }; + + type TimelineBuilderConfig = { + /** + * An array of tween configuration objects to create and add into the new Timeline. If this doesn't exist or is empty, the Timeline will start off paused and none of the other configuration settings will be read. If it's a function, it will be called and its return value will be used as the array. + */ + tweens?: Phaser.Types.Tweens.TweenBuilderConfig[] | object[] | Function; + /** + * An array (or function which returns one) of default targets to which to apply the Timeline. Each individual Tween configuration can override this value. + */ + targets?: any; + /** + * If specified, each Tween in the Timeline will get an equal portion of this duration, usually in milliseconds, by default. Each individual Tween configuration can override the Tween's duration. + */ + totalDuration?: number; + /** + * If `totalDuration` is not specified, the default duration, usually in milliseconds, of each Tween which will be created. Each individual Tween configuration can override the Tween's duration. + */ + duration?: number; + /** + * The number of milliseconds to delay before the tween will start. Each individual Tween configuration can override this value. + */ + delay?: number; + /** + * Optional easing parameters. Each individual Tween configuration can override this value. + */ + easeParams?: any[]; + /** + * The easing equation to use for each tween. Each individual Tween configuration can override this value. + */ + ease?: string | Function; + /** + * The number of milliseconds to hold each tween before yoyo'ing. Each individual Tween configuration can override this value. + */ + hold?: number; + /** + * The number of times to repeat each tween. Each individual Tween configuration can override this value. + */ + repeat?: integer; + /** + * The number of milliseconds to pause before each tween will repeat. Each individual Tween configuration can override this value. + */ + repeatDelay?: number; + /** + * Should each tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. Each individual Tween configuration can override this value. + */ + yoyo?: boolean; + /** + * Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. Each individual Tween configuration can override this value. + */ + flipX?: boolean; + /** + * Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. Each individual Tween configuration can override this value. + */ + flipY?: boolean; + /** + * If specified, the time to wait, usually in milliseconds, before the Timeline completes. + */ + completeDelay?: number | Function | object | any[]; + /** + * How many times the Timeline should loop, or -1 to loop indefinitely. + */ + loop?: number | Function | object | any[]; + /** + * The time, usually in milliseconds, between each loop. + */ + loopDelay?: number | Function | object | any[]; + /** + * If `true`, the Timeline will start paused. + */ + paused?: boolean; + /** + * If `true`, all duration in the Timeline will be in frames instead of milliseconds. + */ + useFrames?: boolean; + /** + * The default scope (`this` value) to use for each callback registered by the Timeline Builder. If not specified, the Timeline itself will be used. + */ + callbackScope?: any; + /** + * If specified, the `onStart` callback for the Timeline, called every time it starts playing. + */ + onStart?: Phaser.Types.Tweens.TimelineOnStartCallback; + /** + * The scope (`this` value) to use for the `onStart` callback. If not specified, the `callbackScope` will be used. + */ + onStartScope?: any; + /** + * Additional arguments to pass to the `onStart` callback. The Timeline will always be the first argument. + */ + onStartParams?: any[]; + /** + * If specified, the `onUpdate` callback for the Timeline, called every frame it's active, regardless of its Tweens. + */ + onUpdate?: Phaser.Types.Tweens.TimelineOnUpdateCallback; + /** + * The scope (`this` value) to use for the `onUpdate` callback. If not specified, the `callbackScope` will be used. + */ + onUpdateScope?: any; + /** + * Additional arguments to pass to the `onUpdate` callback. The Timeline will always be the first argument. + */ + onUpdateParams?: any[]; + /** + * If specified, the `onLoop` callback for the Timeline, called every time it loops. + */ + onLoop?: Phaser.Types.Tweens.TimelineOnLoopCallback; + /** + * The scope (`this` value) to use for the `onLoop` callback. If not specified, the `callbackScope` will be used. + */ + onLoopScope?: any; + /** + * Additional arguments to pass to the `onLoop` callback. The Timeline will always be the first argument. + */ + onLoopParams?: any[]; + /** + * If specified, the `onYoyo` callback for the Timeline, called every time it yoyos. + */ + onYoyo?: Phaser.Types.Tweens.TimelineOnYoyoCallback; + /** + * The scope (`this` value) to use for the `onYoyo` callback. If not specified, the `callbackScope` will be used. + */ + onYoyoScope?: any; + /** + * Additional arguments to pass to the `onYoyo` callback. The first argument will always be `null`, while the Timeline will always be the second argument. + */ + onYoyoParams?: any[]; + /** + * If specified, the `onComplete` callback for the Timeline, called after it completes. + */ + onComplete?: Phaser.Types.Tweens.TimelineOnCompleteCallback; + /** + * The scope (`this` value) to use for the `onComplete` callback. If not specified, the `callbackScope` will be used. + */ + onCompleteScope?: any; + /** + * Additional arguments to pass to the `onComplete` callback. The Timeline will always be the first argument. + */ + onCompleteParams?: any[]; + }; + + type TimelineOnCompleteCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; + + type TimelineOnLoopCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; + + type TimelineOnStartCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; + + type TimelineOnUpdateCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; + + type TimelineOnYoyoCallback = (timeline: Phaser.Tweens.Timeline, ...param: any[])=>void; + + type TweenBuilderConfig = { + /** + * The object, or an array of objects, to run the tween on. + */ + targets: any; + /** + * The number of milliseconds to delay before the tween will start. + */ + delay?: number | Function; + /** + * The duration of the tween in milliseconds. + */ + duration?: number; + /** + * The easing equation to use for the tween. + */ + ease?: string | Function; + /** + * Optional easing parameters. + */ + easeParams?: any[]; + /** + * The number of milliseconds to hold the tween for before yoyo'ing. + */ + hold?: number; + /** + * The number of times each property tween repeats. + */ + repeat?: number; + /** + * The number of milliseconds to pause before a repeat. + */ + repeatDelay?: number; + /** + * Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete. + */ + yoyo?: boolean; + /** + * Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property. + */ + flipX?: boolean; + /** + * Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property. + */ + flipY?: boolean; + /** + * Used when the Tween is part of a Timeline. + */ + offset?: number | Function | object | any[]; + /** + * The time the tween will wait before the onComplete event is dispatched once it has completed, in ms. + */ + completeDelay?: number | Function | object | any[]; + /** + * The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once. + */ + loop?: number | Function | object | any[]; + /** + * The time the tween will pause before starting either a yoyo or returning to the start for a repeat. + */ + loopDelay?: number | Function | object | any[]; + /** + * Does the tween start in a paused state (true) or playing (false)? + */ + paused?: boolean; + /** + * The properties to tween. + */ + props?: {[key: string]: (number|string|Phaser.Types.Tweens.GetEndCallback|Phaser.Types.Tweens.TweenPropConfig)}; + /** + * Use frames or milliseconds? + */ + useFrames?: boolean; + /** + * Scope (this) for the callbacks. The default scope is the tween. + */ + callbackScope?: any; + /** + * A function to call when the tween completes. + */ + onComplete?: Phaser.Types.Tweens.TweenOnCompleteCallback; + /** + * Additional parameters to pass to `onComplete`. + */ + onCompleteParams?: any[]; + /** + * Scope (this) for `onComplete`. + */ + onCompleteScope?: any; + /** + * A function to call each time the tween loops. + */ + onLoop?: Phaser.Types.Tweens.TweenOnLoopCallback; + /** + * Additional parameters to pass to `onLoop`. + */ + onLoopParams?: any[]; + /** + * Scope (this) for `onLoop`. + */ + onLoopScope?: any; + /** + * A function to call each time the tween repeats. Called once per property per target. + */ + onRepeat?: Phaser.Types.Tweens.TweenOnRepeatCallback; + /** + * Additional parameters to pass to `onRepeat`. + */ + onRepeatParams?: any[]; + /** + * Scope (this) for `onRepeat`. + */ + onRepeatScope?: any; + /** + * A function to call when the tween starts playback, after any delays have expired. + */ + onStart?: Phaser.Types.Tweens.TweenOnStartCallback; + /** + * Additional parameters to pass to `onStart`. + */ + onStartParams?: any[]; + /** + * Scope (this) for `onStart`. + */ + onStartScope?: any; + /** + * A function to call each time the tween steps. Called once per property per target. + */ + onUpdate?: Phaser.Types.Tweens.TweenOnUpdateCallback; + /** + * Additional parameters to pass to `onUpdate`. + */ + onUpdateParams?: any[]; + /** + * Scope (this) for `onUpdate`. + */ + onUpdateScope?: any; + /** + * A function to call each time the tween yoyos. Called once per property per target. + */ + onYoyo?: Phaser.Types.Tweens.TweenOnYoyoCallback; + /** + * Additional parameters to pass to `onYoyo`. + */ + onYoyoParams?: any[]; + /** + * Scope (this) for `onYoyo`. + */ + onYoyoScope?: any; + /** + * A function to call when the tween becomes active within the Tween Manager. + */ + onActive?: Phaser.Types.Tweens.TweenOnActiveCallback; + /** + * Additional parameters to pass to `onActive`. + */ + onActiveParams?: any[]; + /** + * Scope (this) for `onActive`. + */ + onActiveScope?: any; + }; + + type TweenDataConfig = { + /** + * The target to tween. + */ + target: any; + /** + * The target index within the Tween targets array. + */ + index: integer; + /** + * The property of the target being tweened. + */ + key: string; + /** + * If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. + */ + getActiveValue: Phaser.Types.Tweens.GetActiveCallback; + /** + * The returned value sets what the property will be at the END of the Tween. + */ + getEndValue: Phaser.Types.Tweens.GetEndCallback; + /** + * The returned value sets what the property will be at the START of the Tween. + */ + getStartValue: Phaser.Types.Tweens.GetStartCallback; + /** + * The ease function this tween uses. + */ + ease: Function; + /** + * Duration of the tween in ms/frames, excludes time for yoyo or repeats. + */ + duration?: number; + /** + * The total calculated duration of this TweenData (based on duration, repeat, delay and yoyo) + */ + totalDuration?: number; + /** + * Time in ms/frames before tween will start. + */ + delay?: number; + /** + * Cause the tween to return back to its start value after hold has expired. + */ + yoyo?: boolean; + /** + * Time in ms/frames the tween will pause before running the yoyo or starting a repeat. + */ + hold?: number; + /** + * Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + */ + repeat?: integer; + /** + * Time in ms/frames before the repeat will start. + */ + repeatDelay?: number; + /** + * Automatically call toggleFlipX when the TweenData yoyos or repeats + */ + flipX?: boolean; + /** + * Automatically call toggleFlipY when the TweenData yoyos or repeats + */ + flipY?: boolean; + /** + * Between 0 and 1 showing completion of this TweenData. + */ + progress?: number; + /** + * Delta counter + */ + elapsed?: number; + /** + * How many repeats are left to run? + */ + repeatCounter?: integer; + /** + * The property value at the start of the ease. + */ + start?: number; + /** + * The current propety value. + */ + current?: number; + /** + * The previous property value. + */ + previous?: number; + /** + * The property value at the end of the ease. + */ + end?: number; + /** + * Time duration 1. + */ + t1?: number; + /** + * Time duration 2. + */ + t2?: number; + /** + * LoadValue generation functions. + */ + gen?: Phaser.Types.Tweens.TweenDataGenConfig; + /** + * TWEEN_CONST.CREATED + */ + state?: integer; + }; + + type TweenDataGenConfig = { + /** + * Time in ms/frames before tween will start. + */ + delay: Function; + /** + * Duration of the tween in ms/frames, excludes time for yoyo or repeats. + */ + duration: Function; + /** + * Time in ms/frames the tween will pause before running the yoyo or starting a repeat. + */ + hold: Function; + /** + * Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + */ + repeat: Function; + /** + * Time in ms/frames before the repeat will start. + */ + repeatDelay: Function; + }; + + type TweenOnActiveCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; + + type TweenOnCompleteCallback = (tween: Phaser.Tweens.Tween, targets: any[], ...param: any[])=>void; + + type TweenOnLoopCallback = (tween: Phaser.Tweens.Tween, targets: any[], ...param: any[])=>void; + + type TweenOnRepeatCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; + + type TweenOnStartCallback = (tween: Phaser.Tweens.Tween, targets: any[], ...param: any[])=>void; + + type TweenOnUpdateCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; + + type TweenOnYoyoCallback = (tween: Phaser.Tweens.Tween, target: any, ...param: any[])=>void; + + type TweenPropConfig = { + /** + * What the property will be at the END of the Tween. + */ + value?: number | string | Phaser.Types.Tweens.GetEndCallback | Phaser.Types.Tweens.TweenPropConfig; + /** + * What the property will be set to immediately when this tween becomes active. + */ + getActive?: Phaser.Types.Tweens.GetActiveCallback; + /** + * What the property will be at the END of the Tween. + */ + getEnd?: Phaser.Types.Tweens.GetEndCallback; + /** + * What the property will be at the START of the Tween. + */ + getStart?: Phaser.Types.Tweens.GetStartCallback; + /** + * The ease function this tween uses. + */ + ease?: string | Function; + /** + * Time in ms/frames before tween will start. + */ + delay?: number; + /** + * Duration of the tween in ms/frames. + */ + duration?: number; + /** + * Determines whether the tween should return back to its start value after hold has expired. + */ + yoyo?: boolean; + /** + * Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. + */ + hold?: number; + /** + * Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + */ + repeat?: number; + /** + * Time in ms/frames before the repeat will start. + */ + repeatDelay?: number; + /** + * Should toggleFlipX be called when yoyo or repeat happens? + */ + flipX?: boolean; + /** + * Should toggleFlipY be called when yoyo or repeat happens? + */ + flipY?: boolean; + }; + + } + + } + + namespace Physics { + namespace Arcade { + /** + * An Arcade Physics Image is an Image with an Arcade Physics body and related components. + * The body can be dynamic or static. + * + * The main difference between an Arcade Image and an Arcade Sprite is that you cannot animate an Arcade Image. + */ + class Image extends Phaser.GameObjects.Image implements Phaser.Physics.Arcade.Components.Acceleration, Phaser.Physics.Arcade.Components.Angular, Phaser.Physics.Arcade.Components.Bounce, Phaser.Physics.Arcade.Components.Debug, Phaser.Physics.Arcade.Components.Drag, Phaser.Physics.Arcade.Components.Enable, Phaser.Physics.Arcade.Components.Friction, Phaser.Physics.Arcade.Components.Gravity, Phaser.Physics.Arcade.Components.Immovable, Phaser.Physics.Arcade.Components.Mass, Phaser.Physics.Arcade.Components.Size, Phaser.Physics.Arcade.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); + + /** + * This Game Object's Physics Body. + */ + body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. + * @param x The horizontal acceleration + * @param y The vertical acceleration Default x. + */ + setAcceleration(x: number, y?: number): this; + + /** + * Sets the body's horizontal acceleration. + * @param value The horizontal acceleration + */ + setAccelerationX(value: number): this; + + /** + * Sets the body's vertical acceleration. + * @param value The vertical acceleration + */ + setAccelerationY(value: number): this; + + /** + * Sets the angular velocity of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * @param value The amount of angular velocity. + */ + setAngularVelocity(value: number): this; + + /** + * Sets the angular acceleration of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * @param value The amount of angular acceleration. + */ + setAngularAcceleration(value: number): this; + + /** + * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. + * @param value The amount of drag. + */ + setAngularDrag(value: number): this; + + /** + * Sets the bounce values of this body. + * + * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. + * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. + * @param x The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * @param y The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. Default x. + */ + setBounce(x: number, y?: number): this; + + /** + * Sets the horizontal bounce value for this body. + * @param value The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + */ + setBounceX(value: number): this; + + /** + * Sets the vertical bounce value for this body. + * @param value The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + */ + setBounceY(value: number): this; + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. + * @param bounceX If given this will be replace the `worldBounce.x` value. + * @param bounceY If given this will be replace the `worldBounce.y` value. + */ + setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): this; + + /** + * Sets the debug values of this body. + * + * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. + * Note that there is a performance cost in drawing debug displays. It should never be used in production. + * @param showBody Set to `true` to have this body render its outline to the debug display. + * @param showVelocity Set to `true` to have this body render a velocity marker to the debug display. + * @param bodyColor The color of the body outline when rendered to the debug display. + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): this; + + /** + * Sets the color of the body outline when it renders to the debug display. + * @param value The color of the body outline when rendered to the debug display. + */ + setDebugBodyColor(value: number): this; + + /** + * Set to `true` to have this body render its outline to the debug display. + */ + debugShowBody: boolean; + + /** + * Set to `true` to have this body render a velocity marker to the debug display. + */ + debugShowVelocity: boolean; + + /** + * The color of the body outline when it renders to the debug display. + */ + debugBodyColor: number; + + /** + * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param x The amount of horizontal drag to apply. + * @param y The amount of vertical drag to apply. Default x. + */ + setDrag(x: number, y?: number): this; + + /** + * Sets the body's horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param value The amount of horizontal drag to apply. + */ + setDragX(value: number): this; + + /** + * Sets the body's vertical drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param value The amount of vertical drag to apply. + */ + setDragY(value: number): this; + + /** + * If this Body is using `drag` for deceleration this function controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * @param value `true` to use damping for deceleration, or `false` to use linear deceleration. + */ + setDamping(value: boolean): this; + + /** + * Enables this Game Object's Body. + * @param reset Also reset the Body and place it at (x, y). + * @param x The horizontal position to place the Game Object and Body. + * @param y The horizontal position to place the Game Object and Body. + * @param enableGameObject Also activate this Game Object. + * @param showGameObject Also show this Game Object. + */ + enableBody(reset: boolean, x: number, y: number, enableGameObject: boolean, showGameObject: boolean): this; + + /** + * Stops and disables this Game Object's Body. + * @param disableGameObject Also deactivate this Game Object. Default false. + * @param hideGameObject Also hide this Game Object. Default false. + */ + disableBody(disableGameObject?: boolean, hideGameObject?: boolean): this; + + /** + * 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. + */ + refreshBody(): this; + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of horizontal friction to apply. + * @param y The amount of vertical friction to apply. Default x. + */ + setFriction(x: number, y?: number): this; + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of friction to apply. + */ + setFrictionX(x: number): this; + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of friction to apply. + */ + setFrictionY(x: number): this; + + /** + * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. + * + * If only one value is provided, this value will be used for both the X and Y axis. + * @param x The gravitational force to be applied to the X-axis. + * @param y The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. Default x. + */ + setGravity(x: number, y?: number): this; + + /** + * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. + * @param x The gravitational force to be applied to the X-axis. + */ + setGravityX(x: number): this; + + /** + * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. + * @param y The gravitational force to be applied to the Y-axis. + */ + setGravityY(y: number): this; + + /** + * Sets Whether this Body can be moved by collisions with another Body. + * @param value Sets if this body can be moved by collisions with another Body. Default true. + */ + setImmovable(value?: boolean): this; + + /** + * Sets the mass of the physics body + * @param value New value for the mass of the body. + */ + setMass(value: number): this; + + /** + * Sets the body offset. This allows you to adjust the difference between the center of the body + * and the x and y coordinates of the parent Game Object. + * @param x The amount to offset the body from the parent Game Object along the x-axis. + * @param y The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. Default x. + */ + setOffset(x: number, y?: number): this; + + /** + * Sets this physics body to use a circle for collision instead of a rectangle. + * @param radius The radius of the physics body, in pixels. + * @param offsetX The amount to offset the body from the parent Game Object along the x-axis. + * @param offsetY The amount to offset the body from the parent Game Object along the y-axis. + */ + setCircle(radius: number, offsetX?: number, offsetY?: number): this; + + /** + * Sets the velocity of the Body. + * @param x The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. + * @param y The vertical velocity of the body. Positive values move the body down, while negative values move it up. Default x. + */ + setVelocity(x: number, y?: number): this; + + /** + * Sets the horizontal component of the body's velocity. + * + * Positive values move the body to the right, while negative values move it to the left. + * @param x The new horizontal velocity. + */ + setVelocityX(x: number): this; + + /** + * Sets the vertical component of the body's velocity. + * + * Positive values move the body down, while negative values move it up. + * @param y The new vertical velocity of the body. + */ + setVelocityY(y: number): this; + + /** + * Sets the maximum velocity of the body. + * @param x The new maximum horizontal velocity. + * @param y The new maximum vertical velocity. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + + } + + /** + * The Arcade Physics Plugin belongs to a Scene and sets up and manages the Scene's physics simulation. + * It also holds some useful methods for moving and rotating Arcade Physics Bodies. + * + * You can access it from within a Scene using `this.physics`. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + */ + class ArcadePhysics { + /** + * + * @param scene The Scene that this Plugin belongs to. + */ + constructor(scene: Phaser.Scene); + + /** + * The Scene that this Plugin belongs to. + */ + scene: Phaser.Scene; + + /** + * The Scene's Systems. + */ + systems: Phaser.Scenes.Systems; + + /** + * A configuration object. Union of the `physics.arcade.*` properties of the GameConfig and SceneConfig objects. + */ + config: object; + + /** + * The physics simulation. + */ + world: Phaser.Physics.Arcade.World; + + /** + * An object holding the Arcade Physics factory methods. + */ + add: Phaser.Physics.Arcade.Factory; + + /** + * Creates the physics configuration for the current Scene. + */ + getConfig(): object; + + /** + * Tests if Game Objects overlap. See {@link Phaser.Physics.Arcade.World#overlap} + * @param object1 The first object or array of objects to check. + * @param object2 The second object or array of objects to check, or `undefined`. + * @param collideCallback An optional callback function that is called if the objects collide. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + overlap(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * Performs a collision check and separation between the two physics enabled objects given, which can be single + * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. + * + * If you don't require separation then use {@link #overlap} instead. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. + * + * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding + * objects are passed to it. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * @param object1 The first object or array of objects to check. + * @param object2 The second object or array of objects to check, or `undefined`. + * @param collideCallback An optional callback function that is called if the objects collide. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + collide(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. + * + * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for collision with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions + * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have + * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the + * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on + * dynamic maps, this method can prove very useful. + * @param sprite The first object to check for collision. + * @param tiles An array of Tiles to check for collision against. + * @param collideCallback An optional callback function that is called if the objects collide. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + collideTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. + * + * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap + * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * @param sprite The first object to check for collision. + * @param tiles An array of Tiles to check for collision against. + * @param collideCallback An optional callback function that is called if the objects overlap. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + overlapTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * Pauses the simulation. + */ + pause(): Phaser.Physics.Arcade.World; + + /** + * Resumes the simulation (if paused). + */ + resume(): Phaser.Physics.Arcade.World; + + /** + * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) + * + * You must give a maximum speed value, beyond which the game object won't go any faster. + * + * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. + * Note: The game object doesn't stop moving once it reaches the destination coordinates. + * @param gameObject Any Game Object with an Arcade Physics body. + * @param x The x coordinate to accelerate towards. + * @param y The y coordinate to accelerate towards. + * @param speed The acceleration (change in speed) in pixels per second squared. Default 60. + * @param xSpeedMax The maximum x velocity the game object can reach. Default 500. + * @param ySpeedMax The maximum y velocity the game object can reach. Default 500. + */ + accelerateTo(gameObject: Phaser.GameObjects.GameObject, x: number, y: number, speed?: number, xSpeedMax?: number, ySpeedMax?: number): number; + + /** + * Sets the acceleration.x/y property on the game object so it will move towards the x/y coordinates at the given rate (in pixels per second squared) + * + * You must give a maximum speed value, beyond which the game object won't go any faster. + * + * Note: The game object does not continuously track the target. If the target changes location during transit the game object will not modify its course. + * Note: The game object doesn't stop moving once it reaches the destination coordinates. + * @param gameObject Any Game Object with an Arcade Physics body. + * @param destination The Game Object to move towards. Can be any object but must have visible x/y properties. + * @param speed The acceleration (change in speed) in pixels per second squared. Default 60. + * @param xSpeedMax The maximum x velocity the game object can reach. Default 500. + * @param ySpeedMax The maximum y velocity the game object can reach. Default 500. + */ + accelerateToObject(gameObject: Phaser.GameObjects.GameObject, destination: Phaser.GameObjects.GameObject, speed?: number, xSpeedMax?: number, ySpeedMax?: number): number; + + /** + * Finds the Body or Game Object closest to a source point or object. + * + * If a `targets` argument is passed, this method finds the closest of those. + * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. + * + * If no `targets` argument is passed, this method finds the closest Dynamic Body. + * + * If two or more targets are the exact same distance from the source point, only the first target + * is returned. + * @param source Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param targets The targets. + */ + closest(source: any, targets?: Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[] | Phaser.GameObjects.GameObject[]): Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody | Phaser.GameObjects.GameObject; + + /** + * Finds the Body or Game Object farthest from a source point or object. + * + * If a `targets` argument is passed, this method finds the farthest of those. + * The targets can be Arcade Physics Game Objects, Dynamic Bodies, or Static Bodies. + * + * If no `targets` argument is passed, this method finds the farthest Dynamic Body. + * + * If two or more targets are the exact same distance from the source point, only the first target + * is returned. + * @param source Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param targets The targets. + */ + furthest(source: any, targets?: Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[] | Phaser.GameObjects.GameObject[]): Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody | Phaser.GameObjects.GameObject; + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * @param gameObject Any Game Object with an Arcade Physics body. + * @param x The x coordinate to move towards. + * @param y The y coordinate to move towards. + * @param speed The speed it will move, in pixels per second (default is 60 pixels/sec) Default 60. + * @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. Default 0. + */ + moveTo(gameObject: Phaser.GameObjects.GameObject, x: number, y: number, speed?: number, maxTime?: number): number; + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * @param gameObject Any Game Object with an Arcade Physics body. + * @param destination Any object with public `x` and `y` properties, such as a Game Object or Geometry object. + * @param speed The speed it will move, in pixels per second (default is 60 pixels/sec) Default 60. + * @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. Default 0. + */ + moveToObject(gameObject: Phaser.GameObjects.GameObject, destination: object, speed?: number, maxTime?: number): number; + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a vector, or set it to the given vector object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. + * @param angle The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param speed The speed it will move, in pixels per second squared. Default 60. + * @param vec2 The Vector2 in which the x and y properties will be set to the calculated velocity. + */ + velocityFromAngle(angle: number, speed?: number, vec2?: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a vector, or set it to the given vector object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.body.velocity) which will set the values directly to the sprite's velocity and not create a new vector object. + * @param rotation The angle in radians. + * @param speed The speed it will move, in pixels per second squared Default 60. + * @param vec2 The Vector2 in which the x and y properties will be set to the calculated velocity. + */ + velocityFromRotation(rotation: number, speed?: number, vec2?: Phaser.Math.Vector2): Phaser.Math.Vector2; + + /** + * This method will search the given rectangular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, + * otherwise the search is O(N) for Dynamic Bodies. + * @param x The top-left x coordinate of the area to search within. + * @param y The top-left y coordinate of the area to search within. + * @param width The width of the area to search within. + * @param height The height of the area to search within. + * @param includeDynamic Should the search include Dynamic Bodies? Default true. + * @param includeStatic Should the search include Static Bodies? Default false. + */ + overlapRect(x: number, y: number, width: number, height: number, includeDynamic?: boolean, includeStatic?: boolean): Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[]; + + /** + * This method will search the given circular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, + * otherwise the search is O(N) for Dynamic Bodies. + * @param x The x coordinate of the center of the area to search within. + * @param y The y coordinate of the center of the area to search within. + * @param radius The radius of the area to search within. + * @param includeDynamic Should the search include Dynamic Bodies? Default true. + * @param includeStatic Should the search include Static Bodies? Default false. + */ + overlapCirc(x: number, y: number, radius: number, includeDynamic?: boolean, includeStatic?: boolean): Phaser.Physics.Arcade.Body[] | Phaser.Physics.Arcade.StaticBody[]; + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + */ + shutdown(): void; + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + */ + destroy(): void; + + } + + /** + * An Arcade Physics Sprite is a Sprite with an Arcade Physics body and related components. + * The body can be dynamic or static. + * + * The main difference between an Arcade Sprite and an Arcade Image is that you cannot animate an Arcade Image. + * If you do not require animation then you can safely use Arcade Images instead of Arcade Sprites. + */ + class Sprite extends Phaser.GameObjects.Sprite implements Phaser.Physics.Arcade.Components.Acceleration, Phaser.Physics.Arcade.Components.Angular, Phaser.Physics.Arcade.Components.Bounce, Phaser.Physics.Arcade.Components.Debug, Phaser.Physics.Arcade.Components.Drag, Phaser.Physics.Arcade.Components.Enable, Phaser.Physics.Arcade.Components.Friction, Phaser.Physics.Arcade.Components.Gravity, Phaser.Physics.Arcade.Components.Immovable, Phaser.Physics.Arcade.Components.Mass, Phaser.Physics.Arcade.Components.Size, Phaser.Physics.Arcade.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer); + + /** + * This Game Object's Physics Body. + */ + body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. + * @param x The horizontal acceleration + * @param y The vertical acceleration Default x. + */ + setAcceleration(x: number, y?: number): this; + + /** + * Sets the body's horizontal acceleration. + * @param value The horizontal acceleration + */ + setAccelerationX(value: number): this; + + /** + * Sets the body's vertical acceleration. + * @param value The vertical acceleration + */ + setAccelerationY(value: number): this; + + /** + * Sets the angular velocity of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * @param value The amount of angular velocity. + */ + setAngularVelocity(value: number): this; + + /** + * Sets the angular acceleration of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * @param value The amount of angular acceleration. + */ + setAngularAcceleration(value: number): this; + + /** + * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. + * @param value The amount of drag. + */ + setAngularDrag(value: number): this; + + /** + * Sets the bounce values of this body. + * + * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. + * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. + * @param x The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * @param y The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. Default x. + */ + setBounce(x: number, y?: number): this; + + /** + * Sets the horizontal bounce value for this body. + * @param value The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + */ + setBounceX(value: number): this; + + /** + * Sets the vertical bounce value for this body. + * @param value The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + */ + setBounceY(value: number): this; + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. + * @param bounceX If given this will be replace the `worldBounce.x` value. + * @param bounceY If given this will be replace the `worldBounce.y` value. + */ + setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): this; + + /** + * Sets the debug values of this body. + * + * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. + * Note that there is a performance cost in drawing debug displays. It should never be used in production. + * @param showBody Set to `true` to have this body render its outline to the debug display. + * @param showVelocity Set to `true` to have this body render a velocity marker to the debug display. + * @param bodyColor The color of the body outline when rendered to the debug display. + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): this; + + /** + * Sets the color of the body outline when it renders to the debug display. + * @param value The color of the body outline when rendered to the debug display. + */ + setDebugBodyColor(value: number): this; + + /** + * Set to `true` to have this body render its outline to the debug display. + */ + debugShowBody: boolean; + + /** + * Set to `true` to have this body render a velocity marker to the debug display. + */ + debugShowVelocity: boolean; + + /** + * The color of the body outline when it renders to the debug display. + */ + debugBodyColor: number; + + /** + * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param x The amount of horizontal drag to apply. + * @param y The amount of vertical drag to apply. Default x. + */ + setDrag(x: number, y?: number): this; + + /** + * Sets the body's horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param value The amount of horizontal drag to apply. + */ + setDragX(value: number): this; + + /** + * Sets the body's vertical drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param value The amount of vertical drag to apply. + */ + setDragY(value: number): this; + + /** + * If this Body is using `drag` for deceleration this function controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * @param value `true` to use damping for deceleration, or `false` to use linear deceleration. + */ + setDamping(value: boolean): this; + + /** + * Enables this Game Object's Body. + * @param reset Also reset the Body and place it at (x, y). + * @param x The horizontal position to place the Game Object and Body. + * @param y The horizontal position to place the Game Object and Body. + * @param enableGameObject Also activate this Game Object. + * @param showGameObject Also show this Game Object. + */ + enableBody(reset: boolean, x: number, y: number, enableGameObject: boolean, showGameObject: boolean): this; + + /** + * Stops and disables this Game Object's Body. + * @param disableGameObject Also deactivate this Game Object. Default false. + * @param hideGameObject Also hide this Game Object. Default false. + */ + disableBody(disableGameObject?: boolean, hideGameObject?: boolean): this; + + /** + * 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. + */ + refreshBody(): this; + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of horizontal friction to apply. + * @param y The amount of vertical friction to apply. Default x. + */ + setFriction(x: number, y?: number): this; + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of friction to apply. + */ + setFrictionX(x: number): this; + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of friction to apply. + */ + setFrictionY(x: number): this; + + /** + * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. + * + * If only one value is provided, this value will be used for both the X and Y axis. + * @param x The gravitational force to be applied to the X-axis. + * @param y The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. Default x. + */ + setGravity(x: number, y?: number): this; + + /** + * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. + * @param x The gravitational force to be applied to the X-axis. + */ + setGravityX(x: number): this; + + /** + * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. + * @param y The gravitational force to be applied to the Y-axis. + */ + setGravityY(y: number): this; + + /** + * Sets Whether this Body can be moved by collisions with another Body. + * @param value Sets if this body can be moved by collisions with another Body. Default true. + */ + setImmovable(value?: boolean): this; + + /** + * Sets the mass of the physics body + * @param value New value for the mass of the body. + */ + setMass(value: number): this; + + /** + * Sets the body offset. This allows you to adjust the difference between the center of the body + * and the x and y coordinates of the parent Game Object. + * @param x The amount to offset the body from the parent Game Object along the x-axis. + * @param y The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. Default x. + */ + setOffset(x: number, y?: number): this; + + /** + * Sets this physics body to use a circle for collision instead of a rectangle. + * @param radius The radius of the physics body, in pixels. + * @param offsetX The amount to offset the body from the parent Game Object along the x-axis. + * @param offsetY The amount to offset the body from the parent Game Object along the y-axis. + */ + setCircle(radius: number, offsetX?: number, offsetY?: number): this; + + /** + * Sets the velocity of the Body. + * @param x The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. + * @param y The vertical velocity of the body. Positive values move the body down, while negative values move it up. Default x. + */ + setVelocity(x: number, y?: number): this; + + /** + * Sets the horizontal component of the body's velocity. + * + * Positive values move the body to the right, while negative values move it to the left. + * @param x The new horizontal velocity. + */ + setVelocityX(x: number): this; + + /** + * Sets the vertical component of the body's velocity. + * + * Positive values move the body down, while negative values move it up. + * @param y The new vertical velocity of the body. + */ + setVelocityY(y: number): this; + + /** + * Sets the maximum velocity of the body. + * @param x The new maximum horizontal velocity. + * @param y The new maximum vertical velocity. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + + } + + /** + * A Dynamic Arcade Body. + * + * Its static counterpart is {@link Phaser.Physics.Arcade.StaticBody}. + */ + class Body { + /** + * + * @param world The Arcade Physics simulation this Body belongs to. + * @param gameObject The Game Object this Body belongs to. + */ + constructor(world: Phaser.Physics.Arcade.World, gameObject: Phaser.GameObjects.GameObject); + + /** + * The Arcade Physics simulation this Body belongs to. + */ + world: Phaser.Physics.Arcade.World; + + /** + * The Game Object this Body belongs to. + */ + gameObject: Phaser.GameObjects.GameObject; + + /** + * Transformations applied to this Body. + */ + transform: object; + + /** + * Whether the Body's boundary is drawn to the debug display. + */ + debugShowBody: boolean; + + /** + * Whether the Body's velocity is drawn to the debug display. + */ + debugShowVelocity: boolean; + + /** + * The color of this Body on the debug display. + */ + debugBodyColor: integer; + + /** + * Whether this Body is updated by the physics simulation. + */ + enable: boolean; + + /** + * Whether this Body's boundary is circular (true) or rectangular (false). + */ + isCircle: boolean; + + /** + * If this Body is circular, this is the unscaled radius of the Body's boundary, as set by setCircle(), in source pixels. + * The true radius is equal to `halfWidth`. + */ + radius: number; + + /** + * The offset of this Body's position from its Game Object's position, in source pixels. + */ + offset: Phaser.Math.Vector2; + + /** + * The position of this Body within the simulation. + */ + position: Phaser.Math.Vector2; + + /** + * The position of this Body during the previous step. + */ + prev: Phaser.Math.Vector2; + + /** + * The position of this Body during the previous frame. + */ + prevFrame: Phaser.Math.Vector2; + + /** + * Whether this Body's `rotation` is affected by its angular acceleration and angular velocity. + */ + allowRotation: boolean; + + /** + * 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 boundary, which is always an axis-aligned rectangle or a circle. + */ + rotation: number; + + /** + * The Body rotation, in degrees, during the previous step. + */ + preRotation: number; + + /** + * The width of the Body boundary, in pixels. + * If the Body is circular, this is also the diameter. + * If you wish to change the width use the `Body.setSize` method. + */ + readonly width: number; + + /** + * The height of the Body boundary, in pixels. + * If the Body is circular, this is also the diameter. + * If you wish to change the height use the `Body.setSize` method. + */ + readonly height: number; + + /** + * The unscaled width of the Body, in source pixels, as set by setSize(). + * The default is the width of the Body's Game Object's texture frame. + */ + sourceWidth: number; + + /** + * The unscaled height of the Body, in source pixels, as set by setSize(). + * The default is the height of the Body's Game Object's texture frame. + */ + sourceHeight: number; + + /** + * Half the Body's width, in pixels. + */ + halfWidth: number; + + /** + * Half the Body's height, in pixels. + */ + halfHeight: number; + + /** + * The center of the Body's boundary. + * The midpoint of its `position` (top-left corner) and its bottom-right corner. + */ + center: Phaser.Math.Vector2; + + /** + * The Body's velocity, in pixels per second. + */ + velocity: Phaser.Math.Vector2; + + /** + * The Body's change in position (due to velocity) at the last step, in pixels. + * + * The size of this value depends on the simulation's step rate. + */ + readonly newVelocity: Phaser.Math.Vector2; + + /** + * The Body's absolute maximum change in position, in pixels per step. + */ + deltaMax: Phaser.Math.Vector2; + + /** + * The Body's change in velocity, in pixels per second squared. + */ + acceleration: Phaser.Math.Vector2; + + /** + * Whether this Body's velocity is affected by its `drag`. + */ + allowDrag: boolean; + + /** + * Absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + */ + drag: Phaser.Math.Vector2 | number; + + /** + * Whether this Body's position is affected by gravity (local or world). + */ + allowGravity: boolean; + + /** + * Acceleration due to gravity (specific to this Body), in pixels per second squared. + * Total gravity is the sum of this vector and the simulation's `gravity`. + */ + gravity: Phaser.Math.Vector2; + + /** + * Rebound following a collision, relative to 1. + */ + bounce: Phaser.Math.Vector2; + + /** + * Rebound following a collision with the world boundary, relative to 1. + * If null, `bounce` is used instead. + */ + worldBounce: Phaser.Math.Vector2; + + /** + * The rectangle used for world boundary collisions. + * + * By default it is set to the world boundary rectangle. Or, if this Body was + * created by a Physics Group, then whatever rectangle that Group defined. + * + * You can also change it by using the `Body.setBoundsRectangle` method. + */ + customBoundsRectangle: Phaser.Geom.Rectangle; + + /** + * Whether the simulation emits a `worldbounds` event when this Body collides with the world boundary (and `collideWorldBounds` is also true). + */ + onWorldBounds: boolean; + + /** + * Whether the simulation emits a `collide` event when this Body collides with another. + */ + onCollide: boolean; + + /** + * Whether the simulation emits an `overlap` event when this Body overlaps with another. + */ + onOverlap: boolean; + + /** + * The Body's absolute maximum velocity, in pixels per second. + * The horizontal and vertical components are applied separately. + */ + maxVelocity: Phaser.Math.Vector2; + + /** + * The maximum speed this Body is allowed to reach, in pixels per second. + * + * If not negative it limits the scalar value of speed. + * + * Any negative value means no maximum is being applied (the default). + */ + maxSpeed: number; + + /** + * If this Body is `immovable` and in motion, `friction` is the proportion of this Body's motion received by the riding Body on each axis, relative to 1. + * The horizontal component (x) is applied only when two colliding Bodies are separated vertically. + * The vertical component (y) is applied only when two colliding Bodies are separated horizontally. + * The default value (1, 0) moves the riding Body horizontally in equal proportion to this Body and vertically not at all. + */ + friction: Phaser.Math.Vector2; + + /** + * If this Body is using `drag` for deceleration this property controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + */ + useDamping: boolean; + + /** + * The rate of change of this Body's `rotation`, in degrees per second. + */ + angularVelocity: number; + + /** + * The Body's angular acceleration (change in angular velocity), in degrees per second squared. + */ + angularAcceleration: number; + + /** + * Loss of angular velocity due to angular movement, in degrees per second. + * + * Angular drag is applied only when angular acceleration is zero. + */ + angularDrag: number; + + /** + * The Body's maximum angular velocity, in degrees per second. + */ + maxAngular: number; + + /** + * The Body's inertia, relative to a default unit (1). + * With `bounce`, this affects the exchange of momentum (velocities) during collisions. + */ + mass: number; + + /** + * The calculated angle of this Body's velocity vector, in radians, during the last step. + */ + angle: number; + + /** + * The calculated magnitude of the Body's velocity, in pixels per second, during the last step. + */ + speed: number; + + /** + * The direction of the Body's velocity, as calculated during the last step. + * If the Body is moving on both axes (diagonally), this describes motion on the vertical axis only. + */ + facing: integer; + + /** + * Whether this Body can be moved by collisions with another Body. + */ + immovable: boolean; + + /** + * Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity. + */ + moves: boolean; + + /** + * A flag disabling the default horizontal separation of colliding bodies. + * Pass your own `collideCallback` to the collider. + */ + customSeparateX: boolean; + + /** + * A flag disabling the default vertical separation of colliding bodies. + * Pass your own `collideCallback` to the collider. + */ + customSeparateY: boolean; + + /** + * The amount of horizontal overlap (before separation), if this Body is colliding with another. + */ + overlapX: number; + + /** + * The amount of vertical overlap (before separation), if this Body is colliding with another. + */ + overlapY: number; + + /** + * The amount of overlap (before separation), if this Body is circular and colliding with another circular body. + */ + overlapR: number; + + /** + * Whether this Body is overlapped with another and both are not moving, on at least one axis. + */ + embedded: boolean; + + /** + * Whether this Body interacts with the world boundary. + */ + collideWorldBounds: boolean; + + /** + * Whether this Body is checked for collisions and for which directions. + * You can set `checkCollision.none = true` to disable collision checks. + */ + checkCollision: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * Whether this Body is colliding with a Body or Static Body and in which direction. + * In a collision where both bodies have zero velocity, `embedded` will be set instead. + */ + touching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * This Body's `touching` value during the previous step. + */ + wasTouching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * Whether this Body is colliding with a Static Body, a tile, or the world boundary. + * In a collision with a Static Body, if this Body has zero velocity then `embedded` will be set instead. + */ + blocked: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * Whether to automatically synchronize this Body's dimensions to the dimensions of its Game Object's visual bounds. + */ + syncBounds: boolean; + + /** + * The Body's physics type (dynamic or static). + */ + readonly physicsType: integer; + + /** + * Updates the Body's `transform`, `width`, `height`, and `center` from its Game Object. + * The Body's `position` isn't changed. + */ + updateBounds(): void; + + /** + * Updates the Body's `center` from its `position`, `width`, and `height`. + */ + updateCenter(): void; + + /** + * Prepares the Body for a physics step by resetting the `wasTouching`, `touching` and `blocked` states. + * + * This method is only called if the physics world is going to run a step this frame. + */ + resetFlags(): void; + + /** + * Syncs the position body position with the parent Game Object. + * + * This method is called every game frame, regardless if the world steps or not. + * @param willStep Will this Body run an update as well? + * @param delta The delta time, in seconds, elapsed since the last frame. + */ + preUpdate(willStep: boolean, delta: number): void; + + /** + * Performs a single physics step and updates the body velocity, angle, speed and other properties. + * + * This method can be called multiple times per game frame, depending on the physics step rate. + * + * The results are synced back to the Game Object in `postUpdate`. + * @param delta The delta time, in seconds, elapsed since the last frame. + */ + update(delta: number): void; + + /** + * Feeds the Body results back into the parent Game Object. + * + * This method is called every game frame, regardless if the world steps or not. + */ + postUpdate(): void; + + /** + * Sets a custom collision boundary rectangle. Use if you want to have a custom + * boundary instead of the world boundaries. + * @param bounds The new boundary rectangle. Pass `null` to use the World bounds. + */ + setBoundsRectangle(bounds?: Phaser.Geom.Rectangle): this; + + /** + * Checks for collisions between this Body and the world boundary and separates them. + */ + checkWorldBounds(): boolean; + + /** + * Sets the offset of the Body's position from its Game Object's position. + * @param x The horizontal offset, in source pixels. + * @param y The vertical offset, in source pixels. Default x. + */ + setOffset(x: number, y?: number): Phaser.Physics.Arcade.Body; + + /** + * Sizes and positions this Body's boundary, as a rectangle. + * Modifies the Body `offset` if `center` is true (the default). + * Resets the width and height to match current frame, if no width and height provided and a frame is found. + * @param width The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param height The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param center Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. Default true. + */ + setSize(width?: integer, height?: integer, center?: boolean): Phaser.Physics.Arcade.Body; + + /** + * Sizes and positions this Body's boundary, as a circle. + * @param radius The radius of the Body, in source pixels. + * @param offsetX The horizontal offset of the Body from its Game Object, in source pixels. + * @param offsetY The vertical offset of the Body from its Game Object, in source pixels. + */ + setCircle(radius: number, offsetX?: number, offsetY?: number): Phaser.Physics.Arcade.Body; + + /** + * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. + * If the Body had any velocity or acceleration it is lost as a result of calling this. + * @param x The horizontal position to place the Game Object and Body. + * @param y The vertical position to place the Game Object and Body. + */ + reset(x: number, y: number): void; + + /** + * Sets acceleration, velocity, and speed to zero. + */ + stop(): Phaser.Physics.Arcade.Body; + + /** + * Copies the coordinates of this Body's edges into an object. + * @param obj An object to copy the values into. + */ + getBounds(obj: Phaser.Types.Physics.Arcade.ArcadeBodyBounds): Phaser.Types.Physics.Arcade.ArcadeBodyBounds; + + /** + * Tests if the coordinates are within this Body's boundary. + * @param x The horizontal coordinate. + * @param y The vertical coordinate. + */ + hitTest(x: number, y: number): boolean; + + /** + * Whether this Body is touching a tile or the world boundary while moving down. + */ + onFloor(): boolean; + + /** + * Whether this Body is touching a tile or the world boundary while moving up. + */ + onCeiling(): boolean; + + /** + * Whether this Body is touching a tile or the world boundary while moving left or right. + */ + onWall(): boolean; + + /** + * The absolute (non-negative) change in this Body's horizontal position from the previous step. + */ + deltaAbsX(): number; + + /** + * The absolute (non-negative) change in this Body's vertical position from the previous step. + */ + deltaAbsY(): number; + + /** + * The change in this Body's horizontal position from the previous step. + * This value is set during the Body's update phase. + * + * As a Body can update multiple times per step this may not hold the final + * delta value for the Body. In this case, please see the `deltaXFinal` method. + */ + deltaX(): number; + + /** + * The change in this Body's vertical position from the previous step. + * This value is set during the Body's update phase. + * + * As a Body can update multiple times per step this may not hold the final + * delta value for the Body. In this case, please see the `deltaYFinal` method. + */ + deltaY(): number; + + /** + * The change in this Body's horizontal position from the previous game update. + * + * This value is set during the `postUpdate` phase and takes into account the + * `deltaMax` and final position of the Body. + * + * Because this value is not calculated until `postUpdate`, you must listen for it + * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will + * not be calculated by that point. If you _do_ use these values in `update` they + * will represent the delta from the _previous_ game frame. + */ + deltaXFinal(): number; + + /** + * The change in this Body's vertical position from the previous game update. + * + * This value is set during the `postUpdate` phase and takes into account the + * `deltaMax` and final position of the Body. + * + * Because this value is not calculated until `postUpdate`, you must listen for it + * during a Scene `POST_UPDATE` or `RENDER` event, and not in `update`, as it will + * not be calculated by that point. If you _do_ use these values in `update` they + * will represent the delta from the _previous_ game frame. + */ + deltaYFinal(): number; + + /** + * The change in this Body's rotation from the previous step, in degrees. + */ + deltaZ(): number; + + /** + * Disables this Body and marks it for deletion by the simulation. + */ + destroy(): void; + + /** + * Draws this Body's boundary and velocity, if enabled. + * @param graphic The Graphics object to draw on. + */ + drawDebug(graphic: Phaser.GameObjects.Graphics): void; + + /** + * Whether this Body will be drawn to the debug display. + */ + willDrawDebug(): boolean; + + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. + * @param bounceX If given this will be replace the `worldBounce.x` value. + * @param bounceY If given this will be replace the `worldBounce.y` value. + */ + setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's velocity. + * @param x The horizontal velocity, in pixels per second. + * @param y The vertical velocity, in pixels per second. Default x. + */ + setVelocity(x: number, y?: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's horizontal velocity. + * @param value The velocity, in pixels per second. + */ + setVelocityX(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's vertical velocity. + * @param value The velocity, in pixels per second. + */ + setVelocityY(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's maximum velocity. + * @param x The horizontal velocity, in pixels per second. + * @param y The vertical velocity, in pixels per second. Default x. + */ + setMaxVelocity(x: number, y?: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the maximum speed the Body can move. + * @param value The maximum speed value, in pixels per second. Set to a negative value to disable. + */ + setMaxSpeed(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's bounce. + * @param x The horizontal bounce, relative to 1. + * @param y The vertical bounce, relative to 1. + */ + setBounce(x: number, y: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's horizontal bounce. + * @param value The bounce, relative to 1. + */ + setBounceX(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's vertical bounce. + * @param value The bounce, relative to 1. + */ + setBounceY(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's acceleration. + * @param x The horizontal component, in pixels per second squared. + * @param y The vertical component, in pixels per second squared. + */ + setAcceleration(x: number, y: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's horizontal acceleration. + * @param value The acceleration, in pixels per second squared. + */ + setAccelerationX(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's vertical acceleration. + * @param value The acceleration, in pixels per second squared. + */ + setAccelerationY(value: number): Phaser.Physics.Arcade.Body; + + /** + * Enables or disables drag. + * @param value `true` to allow drag on this body, or `false` to disable it. Default true. + */ + setAllowDrag(value?: boolean): Phaser.Physics.Arcade.Body; + + /** + * Enables or disables gravity's effect on this Body. + * @param value `true` to allow gravity on this body, or `false` to disable it. Default true. + */ + setAllowGravity(value?: boolean): Phaser.Physics.Arcade.Body; + + /** + * Enables or disables rotation. + * @param value `true` to allow rotation on this body, or `false` to disable it. Default true. + */ + setAllowRotation(value?: boolean): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's drag. + * @param x The horizontal component, in pixels per second squared. + * @param y The vertical component, in pixels per second squared. + */ + setDrag(x: number, y: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's horizontal drag. + * @param value The drag, in pixels per second squared. + */ + setDragX(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's vertical drag. + * @param value The drag, in pixels per second squared. + */ + setDragY(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's gravity. + * @param x The horizontal component, in pixels per second squared. + * @param y The vertical component, in pixels per second squared. + */ + setGravity(x: number, y: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's horizontal gravity. + * @param value The gravity, in pixels per second squared. + */ + setGravityX(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's vertical gravity. + * @param value The gravity, in pixels per second squared. + */ + setGravityY(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's friction. + * @param x The horizontal component, relative to 1. + * @param y The vertical component, relative to 1. + */ + setFriction(x: number, y: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's horizontal friction. + * @param value The friction value, relative to 1. + */ + setFrictionX(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's vertical friction. + * @param value The friction value, relative to 1. + */ + setFrictionY(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's angular velocity. + * @param value The velocity, in degrees per second. + */ + setAngularVelocity(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's angular acceleration. + * @param value The acceleration, in degrees per second squared. + */ + setAngularAcceleration(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's angular drag. + * @param value The drag, in degrees per second squared. + */ + setAngularDrag(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's mass. + * @param value The mass value, relative to 1. + */ + setMass(value: number): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's `immovable` property. + * @param value The value to assign to `immovable`. Default true. + */ + setImmovable(value?: boolean): Phaser.Physics.Arcade.Body; + + /** + * Sets the Body's `enable` property. + * @param value The value to assign to `enable`. Default true. + */ + setEnable(value?: boolean): Phaser.Physics.Arcade.Body; + + /** + * The Body's horizontal position (left edge). + */ + x: number; + + /** + * The Body's vertical position (top edge). + */ + y: number; + + /** + * The left edge of the Body's boundary. Identical to x. + */ + readonly left: number; + + /** + * The right edge of the Body's boundary. + */ + readonly right: number; + + /** + * The top edge of the Body's boundary. Identical to y. + */ + readonly top: number; + + /** + * The bottom edge of this Body's boundary. + */ + readonly bottom: number; + + } + + /** + * An Arcade Physics Collider will automatically check for collision, or overlaps, between two objects + * every step. If a collision, or overlap, occurs it will invoke the given callbacks. + */ + class Collider { + /** + * + * @param world The Arcade physics World that will manage the collisions. + * @param overlapOnly Whether to check for collisions or overlap. + * @param object1 The first object to check for collision. + * @param object2 The second object to check for collision. + * @param collideCallback The callback to invoke when the two objects collide. + * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. + * @param callbackContext The scope in which to call the callbacks. + */ + constructor(world: Phaser.Physics.Arcade.World, overlapOnly: boolean, object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback: ArcadePhysicsCallback, processCallback: ArcadePhysicsCallback, callbackContext: any); + + /** + * The world in which the bodies will collide. + */ + world: Phaser.Physics.Arcade.World; + + /** + * The name of the collider (unused by Phaser). + */ + name: string; + + /** + * Whether the collider is active. + */ + active: boolean; + + /** + * Whether to check for collisions or overlaps. + */ + overlapOnly: boolean; + + /** + * The first object to check for collision. + */ + object1: Phaser.Types.Physics.Arcade.ArcadeColliderType; + + /** + * The second object to check for collision. + */ + object2: Phaser.Types.Physics.Arcade.ArcadeColliderType; + + /** + * The callback to invoke when the two objects collide. + */ + collideCallback: ArcadePhysicsCallback; + + /** + * If a processCallback exists it must return true or collision checking will be skipped. + */ + processCallback: ArcadePhysicsCallback; + + /** + * The context the collideCallback and processCallback will run in. + */ + callbackContext: object; + + /** + * A name for the Collider. + * + * Phaser does not use this value, it's for your own reference. + * @param name The name to assign to the Collider. + */ + setName(name: string): Phaser.Physics.Arcade.Collider; + + /** + * Called by World as part of its step processing, initial operation of collision checking. + */ + update(): void; + + /** + * Removes Collider from World and disposes of its resources. + */ + destroy(): void; + + } + + namespace Components { + /** + * Provides methods used for setting the acceleration properties of an Arcade Physics Body. + */ + interface Acceleration { + /** + * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration. + * @param x The horizontal acceleration + * @param y The vertical acceleration Default x. + */ + setAcceleration(x: number, y?: number): this; + /** + * Sets the body's horizontal acceleration. + * @param value The horizontal acceleration + */ + setAccelerationX(value: number): this; + /** + * Sets the body's vertical acceleration. + * @param value The vertical acceleration + */ + setAccelerationY(value: number): this; + } + + /** + * Provides methods used for setting the angular acceleration properties of an Arcade Physics Body. + */ + interface Angular { + /** + * Sets the angular velocity of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * @param value The amount of angular velocity. + */ + setAngularVelocity(value: number): this; + /** + * Sets the angular acceleration of the body. + * + * In Arcade Physics, bodies cannot rotate. They are always axis-aligned. + * However, they can have angular motion, which is passed on to the Game Object bound to the body, + * causing them to visually rotate, even though the body remains axis-aligned. + * @param value The amount of angular acceleration. + */ + setAngularAcceleration(value: number): this; + /** + * Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration. + * @param value The amount of drag. + */ + setAngularDrag(value: number): this; + } + + /** + * Provides methods used for setting the bounce properties of an Arcade Physics Body. + */ + interface Bounce { + /** + * Sets the bounce values of this body. + * + * Bounce is the amount of restitution, or elasticity, the body has when it collides with another object. + * A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all. + * @param x The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + * @param y The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. Default x. + */ + setBounce(x: number, y?: number): this; + /** + * Sets the horizontal bounce value for this body. + * @param value The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1. + */ + setBounceX(value: number): this; + /** + * Sets the vertical bounce value for this body. + * @param value The amount of vertical bounce to apply on collision. A float, typically between 0 and 1. + */ + setBounceY(value: number): this; + /** + * Sets whether this Body collides with the world boundary. + * + * Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Phaser.Math.Vector2 first. + * @param value `true` if this body should collide with the world bounds, otherwise `false`. Default true. + * @param bounceX If given this will be replace the `worldBounce.x` value. + * @param bounceY If given this will be replace the `worldBounce.y` value. + */ + setCollideWorldBounds(value?: boolean, bounceX?: number, bounceY?: number): this; + } + + /** + * Provides methods used for setting the debug properties of an Arcade Physics Body. + */ + interface Debug { + /** + * Sets the debug values of this body. + * + * Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole. + * Note that there is a performance cost in drawing debug displays. It should never be used in production. + * @param showBody Set to `true` to have this body render its outline to the debug display. + * @param showVelocity Set to `true` to have this body render a velocity marker to the debug display. + * @param bodyColor The color of the body outline when rendered to the debug display. + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): this; + /** + * Sets the color of the body outline when it renders to the debug display. + * @param value The color of the body outline when rendered to the debug display. + */ + setDebugBodyColor(value: number): this; + /** + * Set to `true` to have this body render its outline to the debug display. + */ + debugShowBody: boolean; + /** + * Set to `true` to have this body render a velocity marker to the debug display. + */ + debugShowVelocity: boolean; + /** + * The color of the body outline when it renders to the debug display. + */ + debugBodyColor: number; + } + + /** + * Provides methods used for setting the drag properties of an Arcade Physics Body. + */ + interface Drag { + /** + * Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param x The amount of horizontal drag to apply. + * @param y The amount of vertical drag to apply. Default x. + */ + setDrag(x: number, y?: number): this; + /** + * Sets the body's horizontal drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param value The amount of horizontal drag to apply. + */ + setDragX(value: number): this; + /** + * Sets the body's vertical drag. + * + * Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time. + * It is the absolute loss of velocity due to movement, in pixels per second squared. + * The x and y components are applied separately. + * + * When `useDamping` is true, this is 1 minus the damping factor. + * A value of 1 means the Body loses no velocity. + * A value of 0.95 means the Body loses 5% of its velocity per step. + * A value of 0.5 means the Body loses 50% of its velocity per step. + * + * Drag is applied only when `acceleration` is zero. + * @param value The amount of vertical drag to apply. + */ + setDragY(value: number): this; + /** + * If this Body is using `drag` for deceleration this function controls how the drag is applied. + * If set to `true` drag will use a damping effect rather than a linear approach. If you are + * creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in + * the game Asteroids) then you will get a far smoother and more visually correct deceleration + * by using damping, avoiding the axis-drift that is prone with linear deceleration. + * + * If you enable this property then you should use far smaller `drag` values than with linear, as + * they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow + * deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately. + * @param value `true` to use damping for deceleration, or `false` to use linear deceleration. + */ + setDamping(value: boolean): this; + } + + /** + * Provides methods used for setting the enable properties of an Arcade Physics Body. + */ + interface Enable { + /** + * Enables this Game Object's Body. + * @param reset Also reset the Body and place it at (x, y). + * @param x The horizontal position to place the Game Object and Body. + * @param y The horizontal position to place the Game Object and Body. + * @param enableGameObject Also activate this Game Object. + * @param showGameObject Also show this Game Object. + */ + enableBody(reset: boolean, x: number, y: number, enableGameObject: boolean, showGameObject: boolean): this; + /** + * Stops and disables this Game Object's Body. + * @param disableGameObject Also deactivate this Game Object. Default false. + * @param hideGameObject Also hide this Game Object. Default false. + */ + disableBody(disableGameObject?: boolean, hideGameObject?: boolean): this; + /** + * 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. + */ + refreshBody(): this; + } + + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. The higher than friction, the faster the body will slow down once force stops being applied to it. + */ + interface Friction { + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of horizontal friction to apply. + * @param y The amount of vertical friction to apply. Default x. + */ + setFriction(x: number, y?: number): this; + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of friction to apply. + */ + setFrictionX(x: number): this; + /** + * Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis. + * The higher than friction, the faster the body will slow down once force stops being applied to it. + * @param x The amount of friction to apply. + */ + setFrictionY(x: number): this; + } + + /** + * Provides methods for setting the gravity properties of an Arcade Physics Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Gravity { + /** + * Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect. + * + * If only one value is provided, this value will be used for both the X and Y axis. + * @param x The gravitational force to be applied to the X-axis. + * @param y The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used. Default x. + */ + setGravity(x: number, y?: number): this; + /** + * Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect. + * @param x The gravitational force to be applied to the X-axis. + */ + setGravityX(x: number): this; + /** + * Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect. + * @param y The gravitational force to be applied to the Y-axis. + */ + setGravityY(y: number): this; + } + + /** + * Provides methods used for setting the immovable properties of an Arcade Physics Body. + */ + interface Immovable { + /** + * Sets Whether this Body can be moved by collisions with another Body. + * @param value Sets if this body can be moved by collisions with another Body. Default true. + */ + setImmovable(value?: boolean): this; + } + + /** + * Provides methods used for setting the mass properties of an Arcade Physics Body. + */ + interface Mass { + /** + * Sets the mass of the physics body + * @param value New value for the mass of the body. + */ + setMass(value: number): this; + } + + /** + * This method will search the given circular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search is rather fast, + * otherwise the search is O(N) for Dynamic Bodies. + */ + interface OverlapCirc { + } + + /** + * This method will search the given rectangular area and return an array of all physics bodies that + * overlap with it. It can return either Dynamic, Static bodies or a mixture of both. + * + * A body only has to intersect with the search area to be considered, it doesn't have to be fully + * contained within it. + * + * If Arcade Physics is set to use the RTree (which it is by default) then the search for is extremely fast, + * otherwise the search is O(N) for Dynamic Bodies. + */ + interface OverlapRect { + } + + /** + * Provides methods for setting the size of an Arcade Physics Game Object. + * Should be applied as a mixin and not used directly. + */ + interface Size { + /** + * Sets the body offset. This allows you to adjust the difference between the center of the body + * and the x and y coordinates of the parent Game Object. + * @param x The amount to offset the body from the parent Game Object along the x-axis. + * @param y The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis. Default x. + */ + setOffset(x: number, y?: number): this; + /** + * Sets the size of this physics body. Setting the size does not adjust the dimensions + * of the parent Game Object. + * @param width The new width of the physics body, in pixels. + * @param height The new height of the physics body, in pixels. + * @param center Should the body be re-positioned so its center aligns with the parent Game Object? Default true. + */ + setSize(width: number, height: number, center?: boolean): this; + /** + * Sets this physics body to use a circle for collision instead of a rectangle. + * @param radius The radius of the physics body, in pixels. + * @param offsetX The amount to offset the body from the parent Game Object along the x-axis. + * @param offsetY The amount to offset the body from the parent Game Object along the y-axis. + */ + setCircle(radius: number, offsetX?: number, offsetY?: number): this; + } + + /** + * Provides methods for modifying the velocity of an Arcade Physics body. + * + * Should be applied as a mixin and not used directly. + */ + interface Velocity { + /** + * Sets the velocity of the Body. + * @param x The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left. + * @param y The vertical velocity of the body. Positive values move the body down, while negative values move it up. Default x. + */ + setVelocity(x: number, y?: number): this; + /** + * Sets the horizontal component of the body's velocity. + * + * Positive values move the body to the right, while negative values move it to the left. + * @param x The new horizontal velocity. + */ + setVelocityX(x: number): this; + /** + * Sets the vertical component of the body's velocity. + * + * Positive values move the body down, while negative values move it up. + * @param y The new vertical velocity of the body. + */ + setVelocityY(y: number): this; + /** + * Sets the maximum velocity of the body. + * @param x The new maximum horizontal velocity. + * @param y The new maximum vertical velocity. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + } + + } + + /** + * Dynamic Body. + */ + var DYNAMIC_BODY: number; + + /** + * Static Body. + */ + var STATIC_BODY: number; + + /** + * Arcade Physics Group containing Dynamic Bodies. + */ + var GROUP: number; + + /** + * A Tilemap Layer. + */ + var TILEMAPLAYER: number; + + /** + * Facing no direction (initial value). + */ + var FACING_NONE: number; + + /** + * Facing up. + */ + var FACING_UP: number; + + /** + * Facing down. + */ + var FACING_DOWN: number; + + /** + * Facing left. + */ + var FACING_LEFT: number; + + /** + * Facing right. + */ + var FACING_RIGHT: number; + + namespace Events { + /** + * The Arcade Physics World Collide Event. + * + * This event is dispatched by an Arcade Physics World instance if two bodies collide _and_ at least + * one of them has their [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('collide', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + */ + const COLLIDE: any; + + /** + * The Arcade Physics World Overlap Event. + * + * This event is dispatched by an Arcade Physics World instance if two bodies overlap _and_ at least + * one of them has their [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. + * + * It provides an alternative means to handling overlap events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('overlap', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + */ + const OVERLAP: any; + + /** + * The Arcade Physics World Pause Event. + * + * This event is dispatched by an Arcade Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.physics.world.on('pause', listener)`. + */ + const PAUSE: any; + + /** + * The Arcade Physics World Resume Event. + * + * This event is dispatched by an Arcade Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.physics.world.on('resume', listener)`. + */ + const RESUME: any; + + /** + * The Arcade Physics Tile Collide Event. + * + * This event is dispatched by an Arcade Physics World instance if a body collides with a Tile _and_ + * has its [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('tilecollide', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + */ + const TILE_COLLIDE: any; + + /** + * The Arcade Physics Tile Overlap Event. + * + * This event is dispatched by an Arcade Physics World instance if a body overlaps with a Tile _and_ + * has its [onOverlap]{@link Phaser.Physics.Arcade.Body#onOverlap} property set to `true`. + * + * It provides an alternative means to handling overlap events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('tileoverlap', listener)`. + * + * Please note that 'collide' and 'overlap' are two different things in Arcade Physics. + */ + const TILE_OVERLAP: any; + + /** + * The Arcade Physics World Bounds Event. + * + * This event is dispatched by an Arcade Physics World instance if a body makes contact with the world bounds _and_ + * it has its [onWorldBounds]{@link Phaser.Physics.Arcade.Body#onWorldBounds} property set to `true`. + * + * It provides an alternative means to handling collide events rather than using the callback approach. + * + * Listen to it from a Scene using: `this.physics.world.on('worldbounds', listener)`. + */ + const WORLD_BOUNDS: any; + + /** + * The Arcade Physics World Step Event. + * + * This event is dispatched by an Arcade Physics World instance whenever a physics step is run. + * It is emitted _after_ the bodies and colliders have been updated. + * + * In high framerate settings this can be multiple times per game frame. + * + * Listen to it from a Scene using: `this.physics.world.on('worldstep', listener)`. + */ + const WORLD_STEP: any; + + } + + /** + * The Arcade Physics Factory allows you to easily create Arcade Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + */ + class Factory { + /** + * + * @param world The Arcade Physics World instance. + */ + constructor(world: Phaser.Physics.Arcade.World); + + /** + * A reference to the Arcade Physics World. + */ + world: Phaser.Physics.Arcade.World; + + /** + * A reference to the Scene this Arcade Physics instance belongs to. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene.Systems this Arcade Physics instance belongs to. + */ + sys: Phaser.Scenes.Systems; + + /** + * Creates a new Arcade Physics Collider object. + * @param object1 The first object to check for collision. + * @param object2 The second object to check for collision. + * @param collideCallback The callback to invoke when the two objects collide. + * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. + * @param callbackContext The scope in which to call the callbacks. + */ + collider(object1: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], object2: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; + + /** + * Creates a new Arcade Physics Collider Overlap object. + * @param object1 The first object to check for overlap. + * @param object2 The second object to check for overlap. + * @param collideCallback The callback to invoke when the two objects collide. + * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. + * @param callbackContext The scope in which to call the callbacks. + */ + overlap(object1: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], object2: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; + + /** + * Adds an Arcade Physics Body to the given Game Object. + * @param gameObject A Game Object. + * @param isStatic Create a Static body (true) or Dynamic body (false). Default false. + */ + existing(gameObject: Phaser.GameObjects.GameObject, isStatic?: boolean): Phaser.GameObjects.GameObject; + + /** + * Creates a new Arcade Image object with a Static body. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + staticImage(x: number, y: number, texture: string, frame?: string | integer): Phaser.Physics.Arcade.Image; + + /** + * Creates a new Arcade Image object with a Dynamic body. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + image(x: number, y: number, texture: string, frame?: string | integer): Phaser.Physics.Arcade.Image; + + /** + * Creates a new Arcade Sprite object with a Static body. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + staticSprite(x: number, y: number, texture: string, frame?: string | integer): Phaser.Physics.Arcade.Sprite; + + /** + * Creates a new Arcade Sprite object with a Dynamic body. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + sprite(x: number, y: number, key: string, frame?: string | integer): Phaser.Physics.Arcade.Sprite; + + /** + * Creates a Static Physics Group object. + * All Game Objects created by this Group will automatically be static Arcade Physics objects. + * @param children Game Objects to add to this group; or the `config` argument. + * @param config Settings for this group. + */ + staticGroup(children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.Physics.Arcade.StaticGroup; + + /** + * Creates a Physics Group object. + * All Game Objects created by this Group will automatically be dynamic Arcade Physics objects. + * @param children Game Objects to add to this group; or the `config` argument. + * @param config Settings for this group. + */ + group(children?: Phaser.GameObjects.GameObject[] | Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig): Phaser.Physics.Arcade.Group; + + /** + * Destroys this Factory. + */ + destroy(): void; + + } + + /** + * Calculates and returns the horizontal overlap between two arcade physics bodies and sets their properties + * accordingly, including: `touching.left`, `touching.right`, `touching.none` and `overlapX'. + * @param body1 The first Body to separate. + * @param body2 The second Body to separate. + * @param overlapOnly Is this an overlap only check, or part of separation? + * @param bias A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). + */ + function GetOverlapX(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): number; + + /** + * Calculates and returns the vertical overlap between two arcade physics bodies and sets their properties + * accordingly, including: `touching.up`, `touching.down`, `touching.none` and `overlapY'. + * @param body1 The first Body to separate. + * @param body2 The second Body to separate. + * @param overlapOnly Is this an overlap only check, or part of separation? + * @param bias A value added to the delta values during collision checks. Increase it to prevent sprite tunneling(sprites passing through another instead of colliding). + */ + function GetOverlapY(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): number; + + /** + * An Arcade Physics Group object. + * + * All Game Objects created by this Group will automatically be given dynamic Arcade Physics bodies. + * + * Its static counterpart is {@link Phaser.Physics.Arcade.StaticGroup}. + */ + class Group extends Phaser.GameObjects.Group { + /** + * + * @param world The physics simulation. + * @param scene The scene this group belongs to. + * @param children Game Objects to add to this group; or the `config` argument. + * @param config Settings for this group. + */ + constructor(world: Phaser.Physics.Arcade.World, scene: Phaser.Scene, children?: Phaser.GameObjects.GameObject[] | Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.Physics.Arcade.PhysicsGroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig); + + /** + * The physics simulation. + */ + world: Phaser.Physics.Arcade.World; + + /** + * The class to create new Group members from. + * + * This should be either `Phaser.Physics.Arcade.Image`, `Phaser.Physics.Arcade.Sprite`, or a class extending one of those. + */ + classType: Function; + + /** + * The physics type of the Group's members. + */ + physicsType: integer; + + /** + * Default physics properties applied to Game Objects added to the Group or created by the Group. Derived from the `config` argument. + */ + defaults: Phaser.Types.Physics.Arcade.PhysicsGroupDefaults; + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + */ + type: string; + + /** + * Enables a Game Object's Body and assigns `defaults`. Called when a Group member is added or created. + * @param child The Game Object being added. + */ + createCallbackHandler(child: Phaser.GameObjects.GameObject): void; + + /** + * Disables a Game Object's Body. Called when a Group member is removed. + * @param child The Game Object being removed. + */ + removeCallbackHandler(child: Phaser.GameObjects.GameObject): void; + + /** + * Sets the velocity of each Group member. + * @param x The horizontal velocity. + * @param y The vertical velocity. + * @param step The velocity increment. When set, the first member receives velocity (x, y), the second (x + step, y + step), and so on. Default 0. + */ + setVelocity(x: number, y: number, step?: number): Phaser.Physics.Arcade.Group; + + /** + * Sets the horizontal velocity of each Group member. + * @param value The velocity value. + * @param step The velocity increment. When set, the first member receives velocity (x), the second (x + step), and so on. Default 0. + */ + setVelocityX(value: number, step?: number): Phaser.Physics.Arcade.Group; + + /** + * Sets the vertical velocity of each Group member. + * @param value The velocity value. + * @param step The velocity increment. When set, the first member receives velocity (y), the second (y + step), and so on. Default 0. + */ + setVelocityY(value: number, step?: number): Phaser.Physics.Arcade.Group; + + } + + /** + * 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 they are static, or if either one uses custom logic for its separation. + * @param body1 The first Body to separate. + * @param body2 The second Body to separate. + * @param overlapOnly If `true`, the bodies will only have their overlap data set and no separation will take place. + * @param bias A value to add to the delta value during overlap checking. Used to prevent sprite tunneling. + */ + function SeparateX(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): boolean; + + /** + * 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. + * @param body1 The first Body to separate. + * @param body2 The second Body to separate. + * @param overlapOnly If `true`, the bodies will only have their overlap data set and no separation will take place. + * @param bias A value to add to the delta value during overlap checking. Used to prevent sprite tunneling. + */ + function SeparateY(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly: boolean, bias: number): boolean; + + /** + * A Static Arcade Physics Body. + * + * A Static Body never moves, and isn't automatically synchronized with its parent Game Object. + * That means if you make any change to the parent's origin, position, or scale after creating or adding the body, you'll need to update the Body manually. + * + * A Static Body can collide with other Bodies, but is never moved by collisions. + * + * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Body}. + */ + class StaticBody { + /** + * + * @param world The Arcade Physics simulation this Static Body belongs to. + * @param gameObject The Game Object this Static Body belongs to. + */ + constructor(world: Phaser.Physics.Arcade.World, gameObject: Phaser.GameObjects.GameObject); + + /** + * The Arcade Physics simulation this Static Body belongs to. + */ + world: Phaser.Physics.Arcade.World; + + /** + * The Game Object this Static Body belongs to. + */ + gameObject: Phaser.GameObjects.GameObject; + + /** + * Whether the Static Body's boundary is drawn to the debug display. + */ + debugShowBody: boolean; + + /** + * The color of this Static Body on the debug display. + */ + debugBodyColor: integer; + + /** + * Whether this Static Body is updated by the physics simulation. + */ + enable: boolean; + + /** + * Whether this Static Body's boundary is circular (`true`) or rectangular (`false`). + */ + isCircle: boolean; + + /** + * If this Static Body is circular, this is the unscaled radius of the Static Body's boundary, as set by {@link #setCircle}, in source pixels. + * The true radius is equal to `halfWidth`. + */ + radius: number; + + /** + * The offset of this Static Body's actual position from any updated position. + * + * Unlike a dynamic Body, a Static Body does not follow its Game Object. As such, this offset is only applied when resizing the Static Body. + */ + offset: Phaser.Math.Vector2; + + /** + * The position of this Static Body within the simulation. + */ + position: Phaser.Math.Vector2; + + /** + * The width of the Static Body's boundary, in pixels. + * If the Static Body is circular, this is also the Static Body's diameter. + */ + width: number; + + /** + * The height of the Static Body's boundary, in pixels. + * If the Static Body is circular, this is also the Static Body's diameter. + */ + height: number; + + /** + * Half the Static Body's width, in pixels. + * If the Static Body is circular, this is also the Static Body's radius. + */ + halfWidth: number; + + /** + * Half the Static Body's height, in pixels. + * If the Static Body is circular, this is also the Static Body's radius. + */ + halfHeight: number; + + /** + * The center of the Static Body's boundary. + * This is the midpoint of its `position` (top-left corner) and its bottom-right corner. + */ + center: Phaser.Math.Vector2; + + /** + * A constant zero velocity used by the Arcade Physics simulation for calculations. + */ + readonly velocity: Phaser.Math.Vector2; + + /** + * A constant `false` value expected by the Arcade Physics simulation. + */ + readonly allowGravity: boolean; + + /** + * Gravitational force applied specifically to this Body. Values are in pixels per second squared. Always zero for a Static Body. + */ + readonly gravity: Phaser.Math.Vector2; + + /** + * Rebound, or restitution, following a collision, relative to 1. Always zero for a Static Body. + */ + readonly bounce: Phaser.Math.Vector2; + + /** + * Whether the simulation emits a `worldbounds` event when this StaticBody collides with the world boundary. + * Always false for a Static Body. (Static Bodies never collide with the world boundary and never trigger a `worldbounds` event.) + */ + readonly onWorldBounds: boolean; + + /** + * Whether the simulation emits a `collide` event when this StaticBody collides with another. + */ + onCollide: boolean; + + /** + * Whether the simulation emits an `overlap` event when this StaticBody overlaps with another. + */ + onOverlap: boolean; + + /** + * The StaticBody's inertia, relative to a default unit (1). With `bounce`, this affects the exchange of momentum (velocities) during collisions. + */ + mass: number; + + /** + * Whether this object can be moved by collisions with another body. + */ + immovable: boolean; + + /** + * A flag disabling the default horizontal separation of colliding bodies. Pass your own `collideHandler` to the collider. + */ + customSeparateX: boolean; + + /** + * A flag disabling the default vertical separation of colliding bodies. Pass your own `collideHandler` to the collider. + */ + customSeparateY: boolean; + + /** + * The amount of horizontal overlap (before separation), if this Body is colliding with another. + */ + overlapX: number; + + /** + * The amount of vertical overlap (before separation), if this Body is colliding with another. + */ + overlapY: number; + + /** + * The amount of overlap (before separation), if this StaticBody is circular and colliding with another circular body. + */ + overlapR: number; + + /** + * Whether this StaticBody has ever overlapped with another while both were not moving. + */ + embedded: boolean; + + /** + * Whether this StaticBody interacts with the world boundary. + * Always false for a Static Body. (Static Bodies never collide with the world boundary.) + */ + readonly collideWorldBounds: boolean; + + /** + * Whether this StaticBody is checked for collisions and for which directions. You can set `checkCollision.none = false` to disable collision checks. + */ + checkCollision: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * Whether this StaticBody has ever collided with another body and in which direction. + */ + touching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * Whether this StaticBody was colliding with another body during the last step or any previous step, and in which direction. + */ + wasTouching: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * Whether this StaticBody has ever collided with a tile or the world boundary. + */ + blocked: Phaser.Types.Physics.Arcade.ArcadeBodyCollision; + + /** + * The StaticBody's physics type (static by default). + */ + physicsType: integer; + + /** + * Changes the Game Object this Body is bound to. + * First it removes its reference from the old Game Object, then sets the new one. + * You can optionally update the position and dimensions of this Body to reflect that of the new Game Object. + * @param gameObject The new Game Object that will own this Body. + * @param update Reposition and resize this Body to match the new Game Object? Default true. + */ + setGameObject(gameObject: Phaser.GameObjects.GameObject, update?: boolean): Phaser.Physics.Arcade.StaticBody; + + /** + * Syncs the Body's position and size with its parent Game Object. + */ + updateFromGameObject(): Phaser.Physics.Arcade.StaticBody; + + /** + * Sets the offset of the body. + * @param x The horizontal offset of the Body from the Game Object's center. + * @param y The vertical offset of the Body from the Game Object's center. + */ + setOffset(x: number, y: number): Phaser.Physics.Arcade.StaticBody; + + /** + * Sets the size of the body. + * Resets the width and height to match current frame, if no width and height provided and a frame is found. + * @param width The width of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame width. + * @param height The height of the Body in pixels. Cannot be zero. If not given, and the parent Game Object has a frame, it will use the frame height. + * @param center Modify the Body's `offset`, placing the Body's center on its Game Object's center. Only works if the Game Object has the `getCenter` method. Default true. + */ + setSize(width?: integer, height?: integer, center?: boolean): Phaser.Physics.Arcade.StaticBody; + + /** + * Sets this Static Body to have a circular body and sets its sizes and position. + * @param radius The radius of the StaticBody, in pixels. + * @param offsetX The horizontal offset of the StaticBody from its Game Object, in pixels. + * @param offsetY The vertical offset of the StaticBody from its Game Object, in pixels. + */ + setCircle(radius: number, offsetX?: number, offsetY?: number): Phaser.Physics.Arcade.StaticBody; + + /** + * Updates the StaticBody's `center` from its `position` and dimensions. + */ + updateCenter(): void; + + /** + * Resets this Body to the given coordinates. Also positions its parent Game Object to the same coordinates. + * @param x The x coordinate to reset the body to. If not given will use the parent Game Object's coordinate. + * @param y The y coordinate to reset the body to. If not given will use the parent Game Object's coordinate. + */ + reset(x?: number, y?: number): void; + + /** + * NOOP function. A Static Body cannot be stopped. + */ + stop(): Phaser.Physics.Arcade.StaticBody; + + /** + * Returns the x and y coordinates of the top left and bottom right points of the StaticBody. + * @param obj The object which will hold the coordinates of the bounds. + */ + getBounds(obj: Phaser.Types.Physics.Arcade.ArcadeBodyBounds): Phaser.Types.Physics.Arcade.ArcadeBodyBounds; + + /** + * Checks to see if a given x,y coordinate is colliding with this Static Body. + * @param x The x coordinate to check against this body. + * @param y The y coordinate to check against this body. + */ + hitTest(x: number, y: number): boolean; + + /** + * NOOP + */ + postUpdate(): void; + + /** + * The absolute (non-negative) change in this StaticBody's horizontal position from the previous step. Always zero. + */ + deltaAbsX(): number; + + /** + * The absolute (non-negative) change in this StaticBody's vertical position from the previous step. Always zero. + */ + deltaAbsY(): number; + + /** + * The change in this StaticBody's horizontal position from the previous step. Always zero. + */ + deltaX(): number; + + /** + * The change in this StaticBody's vertical position from the previous step. Always zero. + */ + deltaY(): number; + + /** + * The change in this StaticBody's rotation from the previous step. Always zero. + */ + deltaZ(): number; + + /** + * Disables this Body and marks it for destruction during the next step. + */ + destroy(): void; + + /** + * Draws a graphical representation of the StaticBody for visual debugging purposes. + * @param graphic The Graphics object to use for the debug drawing of the StaticBody. + */ + drawDebug(graphic: Phaser.GameObjects.Graphics): void; + + /** + * Indicates whether the StaticBody is going to be showing a debug visualization during postUpdate. + */ + willDrawDebug(): boolean; + + /** + * Sets the Mass of the StaticBody. Will set the Mass to 0.1 if the value passed is less than or equal to zero. + * @param value The value to set the Mass to. Values of zero or less are changed to 0.1. + */ + setMass(value: number): Phaser.Physics.Arcade.StaticBody; + + /** + * The x coordinate of the StaticBody. + */ + x: number; + + /** + * The y coordinate of the StaticBody. + */ + y: number; + + /** + * Returns the left-most x coordinate of the area of the StaticBody. + */ + readonly left: number; + + /** + * The right-most x coordinate of the area of the StaticBody. + */ + readonly right: number; + + /** + * The highest y coordinate of the area of the StaticBody. + */ + readonly top: number; + + /** + * The lowest y coordinate of the area of the StaticBody. (y + height) + */ + readonly bottom: number; + + } + + /** + * An Arcade Physics Static Group object. + * + * All Game Objects created by this Group will automatically be given static Arcade Physics bodies. + * + * Its dynamic counterpart is {@link Phaser.Physics.Arcade.Group}. + */ + class StaticGroup extends Phaser.GameObjects.Group { + /** + * + * @param world The physics simulation. + * @param scene The scene this group belongs to. + * @param children Game Objects to add to this group; or the `config` argument. + * @param config Settings for this group. + */ + constructor(world: Phaser.Physics.Arcade.World, scene: Phaser.Scene, children?: Phaser.GameObjects.GameObject[] | Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig, config?: Phaser.Types.GameObjects.Group.GroupConfig | Phaser.Types.GameObjects.Group.GroupCreateConfig); + + /** + * The physics simulation. + */ + world: Phaser.Physics.Arcade.World; + + /** + * The scene this group belongs to. + */ + physicsType: integer; + + /** + * A textual representation of this Game Object. + * Used internally by Phaser but is available for your own custom classes to populate. + */ + type: string; + + /** + * Adds a static physics body to the new group member (if it lacks one) and adds it to the simulation. + * @param child The new group member. + */ + createCallbackHandler(child: Phaser.GameObjects.GameObject): void; + + /** + * Disables the group member's physics body, removing it from the simulation. + * @param child The group member being removed. + */ + removeCallbackHandler(child: Phaser.GameObjects.GameObject): void; + + /** + * Refreshes the group. + * @param entries The newly created group members. + */ + createMultipleCallbackHandler(entries: Phaser.GameObjects.GameObject[]): void; + + /** + * Resets each Body to the position of its parent Game Object. + * Body sizes aren't changed (use {@link Phaser.Physics.Arcade.Components.Enable#refreshBody} for that). + */ + refresh(): Phaser.Physics.Arcade.StaticGroup; + + } + + namespace Tilemap { + /** + * A function to process the collision callbacks between a single tile and an Arcade Physics enabled Game Object. + * @param tile The Tile to process. + * @param sprite The Game Object to process with the Tile. + */ + function ProcessTileCallbacks(tile: Phaser.Tilemaps.Tile, sprite: Phaser.GameObjects.Sprite): boolean; + + /** + * Internal function to process the separation of a physics body from a tile. + * @param body The Body object to separate. + * @param x The x separation amount. + */ + function ProcessTileSeparationX(body: Phaser.Physics.Arcade.Body, x: number): void; + + /** + * Internal function to process the separation of a physics body from a tile. + * @param body The Body object to separate. + * @param y The y separation amount. + */ + function ProcessTileSeparationY(body: Phaser.Physics.Arcade.Body, y: number): void; + + /** + * The core separation function to separate a physics body and a tile. + * @param i The index of the tile within the map data. + * @param body The Body object to separate. + * @param tile The tile to collide against. + * @param tileWorldRect A rectangle-like object defining the dimensions of the tile. + * @param tilemapLayer The tilemapLayer to collide against. + * @param tileBias The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param isLayer Is this check coming from a TilemapLayer or an array of tiles? + */ + function SeparateTile(i: number, body: Phaser.Physics.Arcade.Body, tile: Phaser.Tilemaps.Tile, tileWorldRect: Phaser.Geom.Rectangle, tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, tileBias: number, isLayer: boolean): boolean; + + /** + * Check the body against the given tile on the X axis. + * Used internally by the SeparateTile function. + * @param body The Body object to separate. + * @param tile The tile to check. + * @param tileLeft The left position of the tile within the tile world. + * @param tileRight The right position of the tile within the tile world. + * @param tileBias The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param isLayer Is this check coming from a TilemapLayer or an array of tiles? + */ + function TileCheckX(body: Phaser.Physics.Arcade.Body, tile: Phaser.Tilemaps.Tile, tileLeft: number, tileRight: number, tileBias: number, isLayer: boolean): number; + + /** + * Check the body against the given tile on the Y axis. + * Used internally by the SeparateTile function. + * @param body The Body object to separate. + * @param tile The tile to check. + * @param tileTop The top position of the tile within the tile world. + * @param tileBottom The bottom position of the tile within the tile world. + * @param tileBias The tile bias value. Populated by the `World.TILE_BIAS` constant. + * @param isLayer Is this check coming from a TilemapLayer or an array of tiles? + */ + function TileCheckY(body: Phaser.Physics.Arcade.Body, tile: Phaser.Tilemaps.Tile, tileTop: number, tileBottom: number, tileBias: number, isLayer: boolean): number; + + /** + * Checks for intersection between the given tile rectangle-like object and an Arcade Physics body. + * @param tileWorldRect A rectangle object that defines the tile placement in the world. + * @param body The body to check for intersection against. + */ + function TileIntersectsBody(tileWorldRect: Object, body: Phaser.Physics.Arcade.Body): boolean; + + } + + /** + * The Arcade Physics World. + * + * The World is responsible for creating, managing, colliding and updating all of the bodies within it. + * + * An instance of the World belongs to a Phaser.Scene and is accessed via the property `physics.world`. + */ + class World extends Phaser.Events.EventEmitter { + /** + * + * @param scene The Scene to which this World instance belongs. + * @param config An Arcade Physics Configuration object. + */ + constructor(scene: Phaser.Scene, config: Phaser.Types.Physics.Arcade.ArcadeWorldConfig); + + /** + * The Scene this simulation belongs to. + */ + scene: Phaser.Scene; + + /** + * Dynamic Bodies in this simulation. + */ + bodies: Phaser.Structs.Set; + + /** + * Static Bodies in this simulation. + */ + staticBodies: Phaser.Structs.Set; + + /** + * Static Bodies marked for deletion. + */ + pendingDestroy: Phaser.Structs.Set<(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)>; + + /** + * This simulation's collision processors. + */ + colliders: Phaser.Structs.ProcessQueue; + + /** + * Acceleration of Bodies due to gravity, in pixels per second. + */ + gravity: Phaser.Math.Vector2; + + /** + * A boundary constraining Bodies. + */ + bounds: Phaser.Geom.Rectangle; + + /** + * The boundary edges that Bodies can collide with. + */ + checkCollision: Phaser.Types.Physics.Arcade.CheckCollisionObject; + + /** + * The number of physics steps to be taken per second. + * + * This property is read-only. Use the `setFPS` method to modify it at run-time. + */ + readonly fps: number; + + /** + * The number of steps that took place in the last frame. + */ + readonly stepsLastFrame: number; + + /** + * Scaling factor applied to the frame rate. + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + */ + timeScale: number; + + /** + * The maximum absolute difference of a Body's per-step velocity and its overlap with another Body that will result in separation on *each axis*. + * Larger values favor separation. + * Smaller values favor no separation. + */ + OVERLAP_BIAS: number; + + /** + * The maximum absolute value of a Body's overlap with a tile that will result in separation on *each axis*. + * Larger values favor separation. + * Smaller values favor no separation. + * The optimum value may be similar to the tile size. + */ + TILE_BIAS: number; + + /** + * Always separate overlapping Bodies horizontally before vertically. + * False (the default) means Bodies are first separated on the axis of greater gravity, or the vertical axis if neither is greater. + */ + forceX: boolean; + + /** + * Whether the simulation advances with the game loop. + */ + isPaused: boolean; + + /** + * Enables the debug display. + */ + drawDebug: boolean; + + /** + * The graphics object drawing the debug display. + */ + debugGraphic: Phaser.GameObjects.Graphics; + + /** + * Default debug display settings for new Bodies. + */ + defaults: Phaser.Types.Physics.Arcade.ArcadeWorldDefaults; + + /** + * The maximum number of items per node on the RTree. + * + * This is ignored if `useTree` is `false`. If you have a large number of bodies in + * your world then you may find search performance improves by increasing this value, + * to allow more items per node and less node division. + */ + maxEntries: integer; + + /** + * Should this Arcade Physics World use an RTree for Dynamic and Static Physics bodies? + * + * An RTree is a fast way of spatially sorting of all the bodies in the world. + * However, at certain limits, the cost of clearing and inserting the bodies into the + * tree every frame becomes more expensive than the search speed gains it provides. + * + * If you have a large number of dynamic bodies in your world then it may be best to + * disable the use of the RTree by setting this property to `false` in the physics config. + * + * The number it can cope with depends on browser and device, but a conservative estimate + * of around 5,000 bodies should be considered the max before disabling it. + * + * This only applies to dynamic bodies. Static bodies are always kept in an RTree, + * because they don't have to be cleared every frame, so you benefit from the + * massive search speeds all the time. + */ + useTree: boolean; + + /** + * The spatial index of Dynamic Bodies. + */ + tree: Phaser.Structs.RTree; + + /** + * The spatial index of Static Bodies. + */ + staticTree: Phaser.Structs.RTree; + + /** + * Recycled input for tree searches. + */ + treeMinMax: Phaser.Types.Physics.Arcade.ArcadeWorldTreeMinMax; + + /** + * Adds an Arcade Physics Body to a Game Object, an array of Game Objects, or the children of a Group. + * + * The difference between this and the `enableBody` method is that you can pass arrays or Groups + * to this method. + * + * You can specify if the bodies are to be Dynamic or Static. A dynamic body can move via velocity and + * acceleration. A static body remains fixed in place and as such is able to use an optimized search + * tree, making it ideal for static elements such as level objects. You can still collide and overlap + * with static bodies. + * + * Normally, rather than calling this method directly, you'd use the helper methods available in the + * Arcade Physics Factory, such as: + * + * ```javascript + * this.physics.add.image(x, y, textureKey); + * this.physics.add.sprite(x, y, textureKey); + * ``` + * + * Calling factory methods encapsulates the creation of a Game Object and the creation of its + * body at the same time. If you are creating custom classes then you can pass them to this + * method to have their bodies created. + * @param object The object, or objects, on which to create the bodies. + * @param bodyType The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. + */ + enable(object: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[], bodyType?: integer): void; + + /** + * Creates an Arcade Physics Body on a single Game Object. + * + * If the Game Object already has a body, this method will simply add it back into the simulation. + * + * You can specify if the body is Dynamic or Static. A dynamic body can move via velocity and + * acceleration. A static body remains fixed in place and as such is able to use an optimized search + * tree, making it ideal for static elements such as level objects. You can still collide and overlap + * with static bodies. + * + * Normally, rather than calling this method directly, you'd use the helper methods available in the + * Arcade Physics Factory, such as: + * + * ```javascript + * this.physics.add.image(x, y, textureKey); + * this.physics.add.sprite(x, y, textureKey); + * ``` + * + * Calling factory methods encapsulates the creation of a Game Object and the creation of its + * body at the same time. If you are creating custom classes then you can pass them to this + * method to have their bodies created. + * @param object The Game Object on which to create the body. + * @param bodyType The type of Body to create. Either `DYNAMIC_BODY` or `STATIC_BODY`. + */ + enableBody(object: Phaser.GameObjects.GameObject, bodyType?: integer): Phaser.GameObjects.GameObject; + + /** + * Adds an existing Arcade Physics Body or StaticBody to the simulation. + * + * The body is enabled and added to the local search trees. + * @param body The Body to be added to the simulation. + */ + add(body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody): Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody; + + /** + * Disables the Arcade Physics Body of a Game Object, an array of Game Objects, or the children of a Group. + * + * The difference between this and the `disableBody` method is that you can pass arrays or Groups + * to this method. + * + * The body itself is not deleted, it just has its `enable` property set to false, which + * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. + * @param object The object, or objects, on which to disable the bodies. + */ + disable(object: Phaser.GameObjects.GameObject | Phaser.GameObjects.GameObject[] | Phaser.GameObjects.Group | Phaser.GameObjects.Group[]): void; + + /** + * Disables an existing Arcade Physics Body or StaticBody and removes it from the simulation. + * + * The body is disabled and removed from the local search trees. + * + * The body itself is not deleted, it just has its `enable` property set to false, which + * means you can re-enable it again at any point by passing it to enable `World.enable` or `World.add`. + * @param body The Body to be disabled. + */ + disableBody(body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody): void; + + /** + * Removes an existing Arcade Physics Body or StaticBody from the simulation. + * + * The body is disabled and removed from the local search trees. + * + * The body itself is not deleted, it just has its `enabled` property set to false, which + * means you can re-enable it again at any point by passing it to enable `enable` or `add`. + * @param body The body to be removed from the simulation. + */ + remove(body: Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody): void; + + /** + * Creates a Graphics Game Object that the world will use to render the debug display to. + * + * This is called automatically when the World is instantiated if the `debug` config property + * was set to `true`. However, you can call it at any point should you need to display the + * debug Graphic from a fixed point. + * + * You can control which objects are drawn to the Graphics object, and the colors they use, + * by setting the debug properties in the physics config. + * + * You should not typically use this in a production game. Use it to aid during debugging. + */ + createDebugGraphic(): Phaser.GameObjects.Graphics; + + /** + * Sets the position, size and properties of the World boundary. + * + * The World boundary is an invisible rectangle that defines the edges of the World. + * If a Body is set to collide with the world bounds then it will automatically stop + * when it reaches any of the edges. You can optionally set which edges of the boundary + * should be checked against. + * @param x The top-left x coordinate of the boundary. + * @param y The top-left y coordinate of the boundary. + * @param width The width of the boundary. + * @param height The height of the boundary. + * @param checkLeft Should bodies check against the left edge of the boundary? + * @param checkRight Should bodies check against the right edge of the boundary? + * @param checkUp Should bodies check against the top edge of the boundary? + * @param checkDown Should bodies check against the bottom edge of the boundary? + */ + setBounds(x: number, y: number, width: number, height: number, checkLeft?: boolean, checkRight?: boolean, checkUp?: boolean, checkDown?: boolean): Phaser.Physics.Arcade.World; + + /** + * Enables or disables collisions on each edge of the World boundary. + * @param left Should bodies check against the left edge of the boundary? Default true. + * @param right Should bodies check against the right edge of the boundary? Default true. + * @param up Should bodies check against the top edge of the boundary? Default true. + * @param down Should bodies check against the bottom edge of the boundary? Default true. + */ + setBoundsCollision(left?: boolean, right?: boolean, up?: boolean, down?: boolean): Phaser.Physics.Arcade.World; + + /** + * Pauses the simulation. + * + * A paused simulation does not update any existing bodies, or run any Colliders. + * + * However, you can still enable and disable bodies within it, or manually run collide or overlap + * checks. + */ + pause(): Phaser.Physics.Arcade.World; + + /** + * Resumes the simulation, if paused. + */ + resume(): Phaser.Physics.Arcade.World; + + /** + * Creates a new Collider object and adds it to the simulation. + * + * A Collider is a way to automatically perform collision checks between two objects, + * calling the collide and process callbacks if they occur. + * + * Colliders are run as part of the World update, after all of the Bodies have updated. + * + * By creating a Collider you don't need then call `World.collide` in your `update` loop, + * as it will be handled for you automatically. + * @param object1 The first object to check for collision. + * @param object2 The second object to check for collision. + * @param collideCallback The callback to invoke when the two objects collide. + * @param processCallback The callback to invoke when the two objects collide. Must return a boolean. + * @param callbackContext The scope in which to call the callbacks. + */ + addCollider(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; + + /** + * Creates a new Overlap Collider object and adds it to the simulation. + * + * A Collider is a way to automatically perform overlap checks between two objects, + * calling the collide and process callbacks if they occur. + * + * Colliders are run as part of the World update, after all of the Bodies have updated. + * + * By creating a Collider you don't need then call `World.overlap` in your `update` loop, + * as it will be handled for you automatically. + * @param object1 The first object to check for overlap. + * @param object2 The second object to check for overlap. + * @param collideCallback The callback to invoke when the two objects overlap. + * @param processCallback The callback to invoke when the two objects overlap. Must return a boolean. + * @param callbackContext The scope in which to call the callbacks. + */ + addOverlap(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): Phaser.Physics.Arcade.Collider; + + /** + * Removes a Collider from the simulation so it is no longer processed. + * + * This method does not destroy the Collider. If you wish to add it back at a later stage you can call + * `World.colliders.add(Collider)`. + * + * If you no longer need the Collider you can call the `Collider.destroy` method instead, which will + * automatically clear all of its references and then remove it from the World. If you call destroy on + * a Collider you _don't_ need to pass it to this method too. + * @param collider The Collider to remove from the simulation. + */ + removeCollider(collider: Phaser.Physics.Arcade.Collider): Phaser.Physics.Arcade.World; + + /** + * Sets the frame rate to run the simulation at. + * + * The frame rate value is used to simulate a fixed update time step. This fixed + * time step allows for a straightforward implementation of a deterministic game state. + * + * This frame rate is independent of the frequency at which the game is rendering. The + * higher you set the fps, the more physics simulation steps will occur per game step. + * Conversely, the lower you set it, the less will take place. + * + * You can optionally advance the simulation directly yourself by calling the `step` method. + * @param framerate The frame rate to advance the simulation at. + */ + setFPS(framerate: integer): this; + + /** + * 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. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time, in ms, elapsed since the last frame. + */ + protected update(time: number, delta: number): void; + + /** + * Advances the simulation by a time increment. + * @param delta The delta time amount, in seconds, by which to advance the simulation. + */ + step(delta: number): void; + + /** + * Updates bodies, draws the debug display, and handles pending queue operations. + */ + postUpdate(): void; + + /** + * Calculates a Body's velocity and updates its position. + * @param body The Body to be updated. + * @param delta The delta value to be used in the motion calculations, in seconds. + */ + updateMotion(body: Phaser.Physics.Arcade.Body, delta: number): void; + + /** + * Calculates a Body's angular velocity. + * @param body The Body to compute the velocity for. + * @param delta The delta value to be used in the calculation, in seconds. + */ + computeAngularVelocity(body: Phaser.Physics.Arcade.Body, delta: number): void; + + /** + * Calculates a Body's per-axis velocity. + * @param body The Body to compute the velocity for. + * @param delta The delta value to be used in the calculation, in seconds. + */ + computeVelocity(body: Phaser.Physics.Arcade.Body, delta: number): void; + + /** + * Separates two Bodies. + * @param body1 The first Body to be separated. + * @param body2 The second Body to be separated. + * @param processCallback The process callback. + * @param callbackContext The context in which to invoke the callback. + * @param overlapOnly If this a collide or overlap check? + */ + separate(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, processCallback?: ArcadePhysicsCallback, callbackContext?: any, overlapOnly?: boolean): boolean; + + /** + * Separates two Bodies, when both are circular. + * @param body1 The first Body to be separated. + * @param body2 The second Body to be separated. + * @param overlapOnly If this a collide or overlap check? + * @param bias A small value added to the calculations. + */ + separateCircle(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body, overlapOnly?: boolean, bias?: number): boolean; + + /** + * Checks to see if two Bodies intersect at all. + * @param body1 The first body to check. + * @param body2 The second body to check. + */ + intersects(body1: Phaser.Physics.Arcade.Body, body2: Phaser.Physics.Arcade.Body): boolean; + + /** + * Tests if a circular Body intersects with another Body. + * @param circle The circular body to test. + * @param body The rectangular body to test. + */ + circleBodyIntersects(circle: Phaser.Physics.Arcade.Body, body: Phaser.Physics.Arcade.Body): boolean; + + /** + * Tests if Game Objects overlap. + * @param object1 The first object or array of objects to check. + * @param object2 The second object or array of objects to check, or `undefined`. + * @param overlapCallback An optional callback function that is called if the objects overlap. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + overlap(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, overlapCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * Performs a collision check and separation between the two physics enabled objects given, which can be single + * Game Objects, arrays of Game Objects, Physics Groups, arrays of Physics Groups or normal Groups. + * + * If you don't require separation then use {@link #overlap} instead. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If **only** one Group is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If **only** one Array is passed, the array is iterated and every element in it is tested against the others. + * + * Two callbacks can be provided. The `collideCallback` is invoked if a collision occurs and the two colliding + * objects are passed to it. + * + * Arcade Physics uses the Projection Method of collision resolution and separation. While it's fast and suitable + * for 'arcade' style games it lacks stability when multiple objects are in close proximity or resting upon each other. + * The separation that stops two objects penetrating may create a new penetration against a different object. If you + * require a high level of stability please consider using an alternative physics system, such as Matter.js. + * @param object1 The first object or array of objects to check. + * @param object2 The second object or array of objects to check, or `undefined`. + * @param collideCallback An optional callback function that is called if the objects collide. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + collide(object1: Phaser.Types.Physics.Arcade.ArcadeColliderType, object2?: Phaser.Types.Physics.Arcade.ArcadeColliderType, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * This advanced method is specifically for testing for collision between a single Sprite and an array of Tile objects. + * + * You should generally use the `collide` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for collision with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic collisions + * on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * + * Important: Use of this method skips the `interesting faces` system that Tilemap Layers use. This means if you have + * say a row or column of tiles, and you jump into, or walk over them, it's possible to get stuck on the edges of the + * tiles as the interesting face calculations are skipped. However, for quick-fire small collision set tests on + * dynamic maps, this method can prove very useful. + * @param sprite The first object to check for collision. + * @param tiles An array of Tiles to check for collision against. + * @param collideCallback An optional callback function that is called if the objects collide. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + collideTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * This advanced method is specifically for testing for overlaps between a single Sprite and an array of Tile objects. + * + * You should generally use the `overlap` method instead, with a Sprite vs. a Tilemap Layer, as that will perform + * tile filtering and culling for you, as well as handle the interesting face collision automatically. + * + * This method is offered for those who would like to check for overlaps with specific Tiles in a layer, without + * having to set any collision attributes on the tiles in question. This allows you to perform quick dynamic overlap + * tests on small sets of Tiles. As such, no culling or checks are made to the array of Tiles given to this method, + * you should filter them before passing them to this method. + * @param sprite The first object to check for collision. + * @param tiles An array of Tiles to check for collision against. + * @param collideCallback An optional callback function that is called if the objects overlap. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + */ + overlapTiles(sprite: Phaser.GameObjects.GameObject, tiles: Phaser.Tilemaps.Tile[], collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * Internal handler for Sprite vs. Tilemap collisions. + * Please use Phaser.Physics.Arcade.World#collide instead. + * @param sprite The first object to check for collision. + * @param tilemapLayer The second object to check for collision. + * @param collideCallback An optional callback function that is called if the objects collide. + * @param processCallback An optional callback function that lets you perform additional checks against the two objects if they collide. If this is set then `collideCallback` will only be called if this callback returns `true`. + * @param callbackContext The context in which to run the callbacks. + * @param overlapOnly Whether this is a collision or overlap check. + */ + collideSpriteVsTilemapLayer(sprite: Phaser.GameObjects.GameObject, tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, collideCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any, overlapOnly?: boolean): boolean; + + /** + * Wrap an object's coordinates (or several objects' coordinates) within {@link Phaser.Physics.Arcade.World#bounds}. + * + * If the object is outside any boundary edge (left, top, right, bottom), it will be moved to the same offset from the opposite edge (the interior). + * @param object A Game Object, a Group, an object with `x` and `y` coordinates, or an array of such objects. + * @param padding An amount added to each boundary edge during the operation. Default 0. + */ + wrap(object: any, padding?: number): void; + + /** + * Wrap each object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. + * @param objects An array of objects to be wrapped. + * @param padding An amount added to the boundary. Default 0. + */ + wrapArray(objects: any[], padding?: number): void; + + /** + * Wrap an object's coordinates within {@link Phaser.Physics.Arcade.World#bounds}. + * @param object A Game Object, a Physics Body, or any object with `x` and `y` coordinates + * @param padding An amount added to the boundary. Default 0. + */ + wrapObject(object: any, padding?: number): void; + + /** + * Shuts down the simulation, clearing physics data and removing listeners. + */ + shutdown(): void; + + /** + * Shuts down the simulation and disconnects it from the current scene. + */ + destroy(): void; + + } + + } + + /** + * An Impact.js compatible physics world, body and solver, for those who are used + * to the Impact way of defining and controlling physics bodies. Also works with + * the new Loader support for Weltmeister map data. + * + * World updated to run off the Phaser main loop. + * Body extended to support additional setter functions. + * + * To create the map data you'll need Weltmeister, which comes with Impact + * and can be purchased from http://impactjs.com + * + * My thanks to Dominic Szablewski for his permission to support Impact in Phaser. + */ + namespace Impact { + /** + * An Impact.js compatible physics body. + * This re-creates the properties you'd get on an Entity and the math needed to update them. + */ + class Body { + /** + * + * @param world [description] + * @param x [description] + * @param y [description] + * @param sx [description] Default 16. + * @param sy [description] Default 16. + */ + constructor(world: Phaser.Physics.Impact.World, x: number, y: number, sx?: number, sy?: number); + + /** + * [description] + */ + world: Phaser.Physics.Impact.World; + + /** + * [description] + */ + gameObject: Phaser.GameObjects.GameObject; + + /** + * [description] + */ + enabled: boolean; + + /** + * The ImpactBody, ImpactSprite or ImpactImage object that owns this Body, if any. + */ + parent: Phaser.Physics.Impact.ImpactBody | Phaser.Physics.Impact.ImpactImage | Phaser.Physics.Impact.ImpactSprite; + + /** + * [description] + */ + id: integer; + + /** + * [description] + */ + name: string; + + /** + * [description] + */ + size: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + offset: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + pos: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + last: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + vel: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + accel: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + friction: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + maxVel: Phaser.Types.Math.Vector2Like; + + /** + * [description] + */ + standing: boolean; + + /** + * [description] + */ + gravityFactor: number; + + /** + * [description] + */ + bounciness: number; + + /** + * [description] + */ + minBounceVelocity: number; + + /** + * [description] + */ + accelGround: number; + + /** + * [description] + */ + accelAir: number; + + /** + * [description] + */ + jumpSpeed: number; + + /** + * [description] + */ + type: Phaser.Physics.Impact.TYPE; + + /** + * [description] + */ + checkAgainst: Phaser.Physics.Impact.TYPE; + + /** + * [description] + */ + collides: Phaser.Physics.Impact.COLLIDES; + + /** + * [description] + */ + debugShowBody: boolean; + + /** + * [description] + */ + debugShowVelocity: boolean; + + /** + * [description] + */ + debugBodyColor: integer; + + /** + * [description] + */ + updateCallback: Phaser.Types.Physics.Impact.BodyUpdateCallback; + + /** + * min 44 deg, max 136 deg + */ + slopeStanding: Object; + + /** + * [description] + * @param x [description] + * @param y [description] + */ + reset(x: number, y: number): void; + + /** + * [description] + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(delta: number): void; + + /** + * [description] + * @param graphic [description] + */ + drawDebug(graphic: Phaser.GameObjects.Graphics): void; + + /** + * [description] + */ + willDrawDebug(): boolean; + + /** + * [description] + */ + skipHash(): boolean; + + /** + * Determines whether the body collides with the `other` one or not. + * @param other [description] + */ + touches(other: Phaser.Physics.Impact.Body): boolean; + + /** + * Reset the size and position of the physics body. + * @param x The x coordinate to position the body. + * @param y The y coordinate to position the body. + * @param width The width of the body. + * @param height The height of the body. + */ + resetSize(x: number, y: number, width: number, height: number): Phaser.Physics.Impact.Body; + + /** + * Export this body object to JSON. + */ + toJSON(): Phaser.Types.Physics.Impact.JSONImpactBody; + + /** + * [description] + * @param config [description] + */ + fromJSON(config: object): void; + + /** + * Can be overridden by user code + * @param other [description] + */ + check(other: Phaser.Physics.Impact.Body): void; + + /** + * Can be overridden by user code + * @param other [description] + * @param axis [description] + */ + collideWith(other: Phaser.Physics.Impact.Body, axis: string): void; + + /** + * Can be overridden by user code but must return a boolean. + * @param res [description] + */ + handleMovementTrace(res: number): boolean; + + /** + * [description] + */ + destroy(): void; + + } + + /** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + */ + enum COLLIDES { + /** + * Never collides. + */ + NEVER, + /** + * Lite collision. + */ + LITE, + /** + * Passive collision. + */ + PASSIVE, + /** + * Active collision. + */ + ACTIVE, + /** + * Fixed collision. + */ + FIXED, + } + + /** + * [description] + */ + class CollisionMap { + /** + * + * @param tilesize [description] Default 32. + * @param data [description] + */ + constructor(tilesize?: integer, data?: any[]); + + /** + * [description] + */ + tilesize: integer; + + /** + * [description] + */ + data: any[]; + + /** + * [description] + */ + width: number; + + /** + * [description] + */ + height: number; + + /** + * [description] + */ + lastSlope: integer; + + /** + * [description] + */ + tiledef: object; + + /** + * [description] + * @param x [description] + * @param y [description] + * @param vx [description] + * @param vy [description] + * @param objectWidth [description] + * @param objectHeight [description] + */ + trace(x: number, y: number, vx: number, vy: number, objectWidth: number, objectHeight: number): boolean; + + /** + * [description] + * @param res [description] + * @param x [description] + * @param y [description] + * @param vx [description] + * @param vy [description] + * @param width [description] + * @param height [description] + * @param rvx [description] + * @param rvy [description] + * @param step [description] + */ + step(res: object, x: number, y: number, vx: number, vy: number, width: number, height: number, rvx: number, rvy: number, step: number): void; + + /** + * [description] + * @param res [description] + * @param t [description] + * @param x [description] + * @param y [description] + * @param vx [description] + * @param vy [description] + * @param width [description] + * @param height [description] + * @param tileX [description] + * @param tileY [description] + */ + checkDef(res: object, t: number, x: number, y: number, vx: number, vy: number, width: number, height: number, tileX: number, tileY: number): boolean; + + } + + namespace Components { + /** + * The Impact Acceleration component. + * Should be applied as a mixin. + */ + interface Acceleration { + /** + * Sets the horizontal acceleration of this body. + * @param x The amount of acceleration to apply. + */ + setAccelerationX(x: number): this; + /** + * Sets the vertical acceleration of this body. + * @param y The amount of acceleration to apply. + */ + setAccelerationY(y: number): this; + /** + * Sets the horizontal and vertical acceleration of this body. + * @param x The amount of horizontal acceleration to apply. + * @param y The amount of vertical acceleration to apply. + */ + setAcceleration(x: number, y: number): this; + } + + /** + * The Impact Body Scale component. + * Should be applied as a mixin. + */ + interface BodyScale { + /** + * Sets the size of the physics body. + * @param width The width of the body in pixels. + * @param height The height of the body in pixels. Default width. + */ + setBodySize(width: number, height?: number): this; + /** + * Sets the scale of the physics body. + * @param scaleX The horizontal scale of the body. + * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. + */ + setBodyScale(scaleX: number, scaleY?: number): this; + } + + /** + * The Impact Body Type component. + * Should be applied as a mixin. + */ + interface BodyType { + /** + * [description] + */ + getBodyType(): number; + /** + * [description] + */ + setTypeNone(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setTypeA(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setTypeB(): Phaser.GameObjects.GameObject; + } + + /** + * The Impact Bounce component. + * Should be applied as a mixin. + */ + interface Bounce { + /** + * Sets the impact physics bounce, or restitution, value. + * @param value A value between 0 (no rebound) and 1 (full rebound) + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * @param value The minimum allowed velocity. + */ + setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + */ + bounce: number; + } + + /** + * The Impact Check Against component. + * Should be applied as a mixin. + */ + interface CheckAgainst { + /** + * [description] + */ + setAvsB(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setBvsA(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setCheckAgainstNone(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setCheckAgainstA(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setCheckAgainstB(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + checkAgainst: number; + } + + /** + * The Impact Collides component. + * Should be applied as a mixin. + */ + interface Collides { + /** + * [description] + * @param callback [description] + * @param scope [description] + */ + setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setCollidesNever(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setLiteCollision(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setPassiveCollision(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setActiveCollision(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + setFixedCollision(): Phaser.GameObjects.GameObject; + /** + * [description] + */ + collides: number; + } + + /** + * The Impact Debug component. + * Should be applied as a mixin. + */ + interface Debug { + /** + * [description] + * @param showBody [description] + * @param showVelocity [description] + * @param bodyColor [description] + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; + /** + * [description] + * @param value [description] + */ + setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; + /** + * [description] + */ + debugShowBody: boolean; + /** + * [description] + */ + debugShowVelocity: boolean; + /** + * [description] + */ + debugBodyColor: number; + } + + /** + * The Impact Friction component. + * Should be applied as a mixin. + */ + interface Friction { + /** + * [description] + * @param x [description] + */ + setFrictionX(x: number): Phaser.GameObjects.GameObject; + /** + * [description] + * @param y [description] + */ + setFrictionY(y: number): Phaser.GameObjects.GameObject; + /** + * [description] + * @param x [description] + * @param y [description] + */ + setFriction(x: number, y: number): Phaser.GameObjects.GameObject; + } + + /** + * The Impact Gravity component. + * Should be applied as a mixin. + */ + interface Gravity { + /** + * [description] + * @param value [description] + */ + setGravity(value: number): Phaser.GameObjects.GameObject; + /** + * [description] + */ + gravity: number; + } + + /** + * The Impact Offset component. + * Should be applied as a mixin. + */ + interface Offset { + /** + * [description] + * @param x [description] + * @param y [description] + * @param width [description] + * @param height [description] + */ + setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; + } + + /** + * The Impact Set Game Object component. + * Should be applied as a mixin. + */ + interface SetGameObject { + /** + * [description] + * @param gameObject [description] + * @param sync [description] Default true. + */ + setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; + /** + * [description] + */ + syncGameObject(): Phaser.GameObjects.GameObject; + } + + /** + * The Impact Velocity component. + * Should be applied as a mixin. + */ + interface Velocity { + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): this; + /** + * Sets the vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): this; + /** + * Sets the horizontal and vertical velocities of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. + */ + setVelocity(x: number, y?: number): this; + /** + * Sets the maximum velocity this body can travel at. + * @param x The maximum allowed horizontal velocity. + * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + } + + } + + namespace Events { + /** + * The Impact Physics World Collide Event. + * + * This event is dispatched by an Impact Physics World instance if two bodies collide. + * + * Listen to it from a Scene using: `this.impact.world.on('collide', listener)`. + */ + const COLLIDE: any; + + /** + * The Impact Physics World Pause Event. + * + * This event is dispatched by an Impact Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.impact.world.on('pause', listener)`. + */ + const PAUSE: any; + + /** + * The Impact Physics World Resume Event. + * + * This event is dispatched by an Impact Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.impact.world.on('resume', listener)`. + */ + const RESUME: any; + + } + + /** + * The Impact Physics Factory allows you to easily create Impact Physics enabled Game Objects. + * Objects that are created by this Factory are automatically added to the physics world. + */ + class Factory { + /** + * + * @param world A reference to the Impact Physics world. + */ + constructor(world: Phaser.Physics.Impact.World); + + /** + * A reference to the Impact Physics world. + */ + world: Phaser.Physics.Impact.World; + + /** + * A reference to the Scene.Systems this Impact Physics instance belongs to. + */ + sys: Phaser.Scenes.Systems; + + /** + * Creates a new ImpactBody object and adds it to the physics simulation. + * @param x The horizontal position of the body in the physics world. + * @param y The vertical position of the body in the physics world. + * @param width The width of the body. + * @param height The height of the body. + */ + body(x: number, y: number, width: number, height: number): Phaser.Physics.Impact.ImpactBody; + + /** + * Adds an Impact Physics Body to the given Game Object. + * @param gameObject The Game Object to receive the physics body. + */ + existing(gameObject: Phaser.GameObjects.GameObject): Phaser.GameObjects.GameObject; + + /** + * Creates a new ImpactImage object and adds it to the physics world. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + image(x: number, y: number, key: string, frame?: string | integer): Phaser.Physics.Impact.ImpactImage; + + /** + * Creates a new ImpactSprite object and adds it to the physics world. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + sprite(x: number, y: number, key: string, frame?: string | integer): Phaser.Physics.Impact.ImpactSprite; + + /** + * Destroys this Factory. + */ + destroy(): void; + + } + + /** + * [description] + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + * @param vel [description] + * @param accel [description] + * @param friction [description] + * @param max [description] + */ + function GetVelocity(delta: number, vel: number, accel: number, friction: number, max: number): number; + + /** + * [description] + */ + class ImpactBody implements Phaser.Physics.Impact.Components.Acceleration, Phaser.Physics.Impact.Components.BodyScale, Phaser.Physics.Impact.Components.BodyType, Phaser.Physics.Impact.Components.Bounce, Phaser.Physics.Impact.Components.CheckAgainst, Phaser.Physics.Impact.Components.Collides, Phaser.Physics.Impact.Components.Debug, Phaser.Physics.Impact.Components.Friction, Phaser.Physics.Impact.Components.Gravity, Phaser.Physics.Impact.Components.Offset, Phaser.Physics.Impact.Components.SetGameObject, Phaser.Physics.Impact.Components.Velocity { + /** + * + * @param world [description] + * @param x x - The horizontal position of this physics body in the world. + * @param y y - The vertical position of this physics body in the world. + * @param width The width of the physics body in the world. + * @param height [description] + */ + constructor(world: Phaser.Physics.Impact.World, x: number, y: number, width: number, height: number); + + /** + * [description] + */ + body: Phaser.Physics.Impact.Body; + + /** + * [description] + */ + size: Object; + + /** + * [description] + */ + offset: Object; + + /** + * [description] + */ + vel: Object; + + /** + * [description] + */ + accel: Object; + + /** + * [description] + */ + friction: Object; + + /** + * [description] + */ + maxVel: Object; + + /** + * Sets the horizontal acceleration of this body. + * @param x The amount of acceleration to apply. + */ + setAccelerationX(x: number): this; + + /** + * Sets the vertical acceleration of this body. + * @param y The amount of acceleration to apply. + */ + setAccelerationY(y: number): this; + + /** + * Sets the horizontal and vertical acceleration of this body. + * @param x The amount of horizontal acceleration to apply. + * @param y The amount of vertical acceleration to apply. + */ + setAcceleration(x: number, y: number): this; + + /** + * Sets the size of the physics body. + * @param width The width of the body in pixels. + * @param height The height of the body in pixels. Default width. + */ + setBodySize(width: number, height?: number): this; + + /** + * Sets the scale of the physics body. + * @param scaleX The horizontal scale of the body. + * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. + */ + setBodyScale(scaleX: number, scaleY?: number): this; + + /** + * [description] + */ + getBodyType(): number; + + /** + * [description] + */ + setTypeNone(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setTypeA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setTypeB(): Phaser.GameObjects.GameObject; + + /** + * Sets the impact physics bounce, or restitution, value. + * @param value A value between 0 (no rebound) and 1 (full rebound) + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * @param value The minimum allowed velocity. + */ + setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; + + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + */ + bounce: number; + + /** + * [description] + */ + setAvsB(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setBvsA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstNone(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstB(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + checkAgainst: number; + + /** + * [description] + * @param callback [description] + * @param scope [description] + */ + setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCollidesNever(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setLiteCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setPassiveCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setActiveCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setFixedCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + collides: number; + + /** + * [description] + * @param showBody [description] + * @param showVelocity [description] + * @param bodyColor [description] + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param value [description] + */ + setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + debugShowBody: boolean; + + /** + * [description] + */ + debugShowVelocity: boolean; + + /** + * [description] + */ + debugBodyColor: number; + + /** + * [description] + * @param x [description] + */ + setFrictionX(x: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param y [description] + */ + setFrictionY(y: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param x [description] + * @param y [description] + */ + setFriction(x: number, y: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param value [description] + */ + setGravity(value: number): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + gravity: number; + + /** + * [description] + * @param x [description] + * @param y [description] + * @param width [description] + * @param height [description] + */ + setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param gameObject [description] + * @param sync [description] Default true. + */ + setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + syncGameObject(): Phaser.GameObjects.GameObject; + + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): this; + + /** + * Sets the vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): this; + + /** + * Sets the horizontal and vertical velocities of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. + */ + setVelocity(x: number, y?: number): this; + + /** + * Sets the maximum velocity this body can travel at. + * @param x The maximum allowed horizontal velocity. + * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + + } + + /** + * An Impact Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + */ + class ImpactImage extends Phaser.GameObjects.Image implements Phaser.Physics.Impact.Components.Acceleration, Phaser.Physics.Impact.Components.BodyScale, Phaser.Physics.Impact.Components.BodyType, Phaser.Physics.Impact.Components.Bounce, Phaser.Physics.Impact.Components.CheckAgainst, Phaser.Physics.Impact.Components.Collides, Phaser.Physics.Impact.Components.Debug, Phaser.Physics.Impact.Components.Friction, Phaser.Physics.Impact.Components.Gravity, Phaser.Physics.Impact.Components.Offset, Phaser.Physics.Impact.Components.SetGameObject, Phaser.Physics.Impact.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param world The physics world of the Impact physics system. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(world: Phaser.Physics.Impact.World, x: number, y: number, texture: string, frame?: string | integer); + + /** + * The Physics Body linked to an ImpactImage. + */ + body: Phaser.Physics.Impact.Body; + + /** + * The size of the physics Body. + */ + size: Object; + + /** + * The X and Y offset of the Body from the left and top of the Image. + */ + offset: Object; + + /** + * The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + vel: Object; + + /** + * The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + accel: Object; + + /** + * Friction between colliding bodies. + */ + friction: Object; + + /** + * The maximum velocity of the body. + */ + maxVel: Object; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * Sets the horizontal acceleration of this body. + * @param x The amount of acceleration to apply. + */ + setAccelerationX(x: number): this; + + /** + * Sets the vertical acceleration of this body. + * @param y The amount of acceleration to apply. + */ + setAccelerationY(y: number): this; + + /** + * Sets the horizontal and vertical acceleration of this body. + * @param x The amount of horizontal acceleration to apply. + * @param y The amount of vertical acceleration to apply. + */ + setAcceleration(x: number, y: number): this; + + /** + * Sets the size of the physics body. + * @param width The width of the body in pixels. + * @param height The height of the body in pixels. Default width. + */ + setBodySize(width: number, height?: number): this; + + /** + * Sets the scale of the physics body. + * @param scaleX The horizontal scale of the body. + * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. + */ + setBodyScale(scaleX: number, scaleY?: number): this; + + /** + * [description] + */ + getBodyType(): number; + + /** + * [description] + */ + setTypeNone(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setTypeA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setTypeB(): Phaser.GameObjects.GameObject; + + /** + * Sets the impact physics bounce, or restitution, value. + * @param value A value between 0 (no rebound) and 1 (full rebound) + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * @param value The minimum allowed velocity. + */ + setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; + + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + */ + bounce: number; + + /** + * [description] + */ + setAvsB(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setBvsA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstNone(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstB(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + checkAgainst: number; + + /** + * [description] + * @param callback [description] + * @param scope [description] + */ + setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCollidesNever(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setLiteCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setPassiveCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setActiveCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setFixedCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + collides: number; + + /** + * [description] + * @param showBody [description] + * @param showVelocity [description] + * @param bodyColor [description] + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param value [description] + */ + setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + debugShowBody: boolean; + + /** + * [description] + */ + debugShowVelocity: boolean; + + /** + * [description] + */ + debugBodyColor: number; + + /** + * [description] + * @param x [description] + */ + setFrictionX(x: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param y [description] + */ + setFrictionY(y: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param x [description] + * @param y [description] + */ + setFriction(x: number, y: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param value [description] + */ + setGravity(value: number): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + gravity: number; + + /** + * [description] + * @param x [description] + * @param y [description] + * @param width [description] + * @param height [description] + */ + setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param gameObject [description] + * @param sync [description] Default true. + */ + setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + syncGameObject(): Phaser.GameObjects.GameObject; + + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): this; + + /** + * Sets the vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): this; + + /** + * Sets the horizontal and vertical velocities of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. + */ + setVelocity(x: number, y?: number): this; + + /** + * Sets the maximum velocity this body can travel at. + * @param x The maximum allowed horizontal velocity. + * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + + } + + /** + * [description] + */ + class ImpactPhysics { + /** + * + * @param scene [description] + */ + constructor(scene: Phaser.Scene); + + /** + * [description] + */ + scene: Phaser.Scene; + + /** + * [description] + */ + systems: Phaser.Scenes.Systems; + + /** + * [description] + */ + config: object; + + /** + * [description] + */ + world: Phaser.Physics.Impact.World; + + /** + * [description] + */ + add: Phaser.Physics.Impact.Factory; + + /** + * [description] + */ + getConfig(): object; + + /** + * [description] + */ + pause(): Phaser.Physics.Impact.World; + + /** + * [description] + */ + resume(): Phaser.Physics.Impact.World; + + } + + /** + * An Impact Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + */ + class ImpactSprite extends Phaser.GameObjects.Sprite implements Phaser.Physics.Impact.Components.Acceleration, Phaser.Physics.Impact.Components.BodyScale, Phaser.Physics.Impact.Components.BodyType, Phaser.Physics.Impact.Components.Bounce, Phaser.Physics.Impact.Components.CheckAgainst, Phaser.Physics.Impact.Components.Collides, Phaser.Physics.Impact.Components.Debug, Phaser.Physics.Impact.Components.Friction, Phaser.Physics.Impact.Components.Gravity, Phaser.Physics.Impact.Components.Offset, Phaser.Physics.Impact.Components.SetGameObject, Phaser.Physics.Impact.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param world [description] + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + */ + constructor(world: Phaser.Physics.Impact.World, x: number, y: number, texture: string, frame?: string | integer); + + /** + * [description] + */ + body: Phaser.Physics.Impact.Body; + + /** + * [description] + */ + size: Object; + + /** + * [description] + */ + offset: Object; + + /** + * [description] + */ + vel: Object; + + /** + * [description] + */ + accel: Object; + + /** + * [description] + */ + friction: Object; + + /** + * [description] + */ + maxVel: Object; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * Sets the horizontal acceleration of this body. + * @param x The amount of acceleration to apply. + */ + setAccelerationX(x: number): this; + + /** + * Sets the vertical acceleration of this body. + * @param y The amount of acceleration to apply. + */ + setAccelerationY(y: number): this; + + /** + * Sets the horizontal and vertical acceleration of this body. + * @param x The amount of horizontal acceleration to apply. + * @param y The amount of vertical acceleration to apply. + */ + setAcceleration(x: number, y: number): this; + + /** + * Sets the size of the physics body. + * @param width The width of the body in pixels. + * @param height The height of the body in pixels. Default width. + */ + setBodySize(width: number, height?: number): this; + + /** + * Sets the scale of the physics body. + * @param scaleX The horizontal scale of the body. + * @param scaleY The vertical scale of the body. If not given, will use the horizontal scale value. + */ + setBodyScale(scaleX: number, scaleY?: number): this; + + /** + * [description] + */ + getBodyType(): number; + + /** + * [description] + */ + setTypeNone(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setTypeA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setTypeB(): Phaser.GameObjects.GameObject; + + /** + * Sets the impact physics bounce, or restitution, value. + * @param value A value between 0 (no rebound) and 1 (full rebound) + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the minimum velocity the body is allowed to be moving to be considered for rebound. + * @param value The minimum allowed velocity. + */ + setMinBounceVelocity(value: number): Phaser.GameObjects.GameObject; + + /** + * The bounce, or restitution, value of this body. + * A value between 0 (no rebound) and 1 (full rebound) + */ + bounce: number; + + /** + * [description] + */ + setAvsB(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setBvsA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstNone(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstA(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCheckAgainstB(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + checkAgainst: number; + + /** + * [description] + * @param callback [description] + * @param scope [description] + */ + setCollideCallback(callback: CollideCallback, scope: any): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setCollidesNever(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setLiteCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setPassiveCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setActiveCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + setFixedCollision(): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + collides: number; + + /** + * [description] + * @param showBody [description] + * @param showVelocity [description] + * @param bodyColor [description] + */ + setDebug(showBody: boolean, showVelocity: boolean, bodyColor: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param value [description] + */ + setDebugBodyColor(value: number): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + debugShowBody: boolean; + + /** + * [description] + */ + debugShowVelocity: boolean; + + /** + * [description] + */ + debugBodyColor: number; + + /** + * [description] + * @param x [description] + */ + setFrictionX(x: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param y [description] + */ + setFrictionY(y: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param x [description] + * @param y [description] + */ + setFriction(x: number, y: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param value [description] + */ + setGravity(value: number): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + gravity: number; + + /** + * [description] + * @param x [description] + * @param y [description] + * @param width [description] + * @param height [description] + */ + setOffset(x: number, y: number, width?: number, height?: number): Phaser.GameObjects.GameObject; + + /** + * [description] + * @param gameObject [description] + * @param sync [description] Default true. + */ + setGameObject(gameObject: Phaser.GameObjects.GameObject, sync?: boolean): Phaser.GameObjects.GameObject; + + /** + * [description] + */ + syncGameObject(): Phaser.GameObjects.GameObject; + + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): this; + + /** + * Sets the vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): this; + + /** + * Sets the horizontal and vertical velocities of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value. If not given, defaults to the horizontal value. Default x. + */ + setVelocity(x: number, y?: number): this; + + /** + * Sets the maximum velocity this body can travel at. + * @param x The maximum allowed horizontal velocity. + * @param y The maximum allowed vertical velocity. If not given, defaults to the horizontal value. Default x. + */ + setMaxVelocity(x: number, y?: number): this; + + } + + /** + * [description] + * @param world [description] + * @param left [description] + * @param right [description] + * @param weak [description] + */ + function SeparateX(world: Phaser.Physics.Impact.World, left: Phaser.Physics.Impact.Body, right: Phaser.Physics.Impact.Body, weak?: Phaser.Physics.Impact.Body): void; + + /** + * [description] + * @param world [description] + * @param top [description] + * @param bottom [description] + * @param weak [description] + */ + function SeparateY(world: Phaser.Physics.Impact.World, top: Phaser.Physics.Impact.Body, bottom: Phaser.Physics.Impact.Body, weak?: Phaser.Physics.Impact.Body): void; + + /** + * Impact Physics Solver + * @param world The Impact simulation to run the solver in. + * @param bodyA The first body in the collision. + * @param bodyB The second body in the collision. + */ + function Solver(world: Phaser.Physics.Impact.World, bodyA: Phaser.Physics.Impact.Body, bodyB: Phaser.Physics.Impact.Body): void; + + /** + * Collision Types - Determine if and how entities collide with each other. + * + * In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, + * while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE + * collisions, both entities are moved. LITE or PASSIVE entities don't collide + * with other LITE or PASSIVE entities at all. The behavior for FIXED vs. + * FIXED collisions is undefined. + */ + enum TYPE { + /** + * Collides with nothing. + */ + NONE, + /** + * Type A. Collides with Type B. + */ + A, + /** + * Type B. Collides with Type A. + */ + B, + /** + * Collides with both types A and B. + */ + BOTH, + } + + /** + * Set up the trace-result + * var res = { + * collision: {x: false, y: false, slope: false}, + * pos: {x: x, y: y}, + * tile: {x: 0, y: 0} + * }; + * @param body [description] + * @param res [description] + */ + function UpdateMotion(body: Phaser.Physics.Impact.Body, res: object): void; + + /** + * [description] + */ + class World extends Phaser.Events.EventEmitter { + /** + * + * @param scene The Scene to which this Impact World instance belongs. + * @param config [description] + */ + constructor(scene: Phaser.Scene, config: Phaser.Types.Physics.Impact.WorldConfig); + + /** + * [description] + */ + scene: Phaser.Scene; + + /** + * [description] + */ + bodies: Phaser.Structs.Set; + + /** + * [description] + */ + gravity: number; + + /** + * Spatial hash cell dimensions + */ + cellSize: integer; + + /** + * [description] + */ + collisionMap: Phaser.Physics.Impact.CollisionMap; + + /** + * [description] + */ + timeScale: number; + + /** + * Impacts maximum time step is 20 fps. + */ + maxStep: number; + + /** + * [description] + */ + enabled: boolean; + + /** + * [description] + */ + drawDebug: boolean; + + /** + * [description] + */ + debugGraphic: Phaser.GameObjects.Graphics; + + /** + * [description] + */ + defaults: Phaser.Types.Physics.Impact.WorldDefaults; + + /** + * An object containing the 4 wall bodies that bound the physics world. + */ + walls: Phaser.Types.Physics.Impact.WorldWalls; + + /** + * [description] + */ + delta: number; + + /** + * Sets the collision map for the world either from a Weltmeister JSON level in the cache or from + * a 2D array. If loading from a Weltmeister level, the map must have a layer called "collision". + * @param key Either a string key that corresponds to a Weltmeister level + * in the cache, or a 2D array of collision IDs. + * @param tileSize The size of a tile. This is optional if loading from a Weltmeister + * level in the cache. + */ + setCollisionMap(key: string | integer[][], tileSize: integer): Phaser.Physics.Impact.CollisionMap; + + /** + * Sets the collision map for the world from a tilemap layer. Only tiles that are marked as + * colliding will be used. You can specify the mapping from tiles to slope IDs in a couple of + * ways. The easiest is to use Tiled and the slopeTileProperty option. Alternatively, you can + * manually create a slopeMap that stores the mapping between tile indices and slope IDs. + * @param tilemapLayer The tilemap layer to use. + * @param options Options for controlling the mapping from tiles to slope IDs. + */ + setCollisionMapFromTilemapLayer(tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, options?: Phaser.Types.Physics.Impact.CollisionOptions): Phaser.Physics.Impact.CollisionMap; + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * @param x The x coordinate of the top-left corner of the bounds. + * @param y The y coordinate of the top-left corner of the bounds. + * @param width The width of the bounds. + * @param height The height of the bounds. + * @param thickness [description] Default 64. + * @param left If true will create the left bounds wall. Default true. + * @param right If true will create the right bounds wall. Default true. + * @param top If true will create the top bounds wall. Default true. + * @param bottom If true will create the bottom bounds wall. Default true. + */ + setBounds(x?: number, y?: number, width?: number, height?: number, thickness?: number, left?: boolean, right?: boolean, top?: boolean, bottom?: boolean): Phaser.Physics.Impact.World; + + /** + * position = 'left', 'right', 'top' or 'bottom' + * @param add [description] + * @param position [description] + * @param x [description] + * @param y [description] + * @param width [description] + * @param height [description] + */ + updateWall(add: boolean, position: string, x: number, y: number, width: number, height: number): void; + + /** + * Creates a Graphics Game Object used for debug display and enables the world for debug drawing. + */ + createDebugGraphic(): Phaser.GameObjects.Graphics; + + /** + * [description] + */ + getNextID(): integer; + + /** + * [description] + * @param x [description] + * @param y [description] + * @param sizeX [description] + * @param sizeY [description] + */ + create(x: number, y: number, sizeX: number, sizeY: number): Phaser.Physics.Impact.Body; + + /** + * [description] + * @param object The Body to remove from this World. + */ + remove(object: Phaser.Physics.Impact.Body): void; + + /** + * [description] + */ + pause(): Phaser.Physics.Impact.World; + + /** + * [description] + */ + resume(): Phaser.Physics.Impact.World; + + /** + * [description] + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(time: number, delta: number): void; + + /** + * Check the body against the spatial hash. + * @param body [description] + * @param hash [description] + * @param size [description] + */ + checkHash(body: Phaser.Physics.Impact.Body, hash: object, size: number): void; + + /** + * [description] + * @param bodyA [description] + * @param bodyB [description] + */ + checkBodies(bodyA: Phaser.Physics.Impact.Body, bodyB: Phaser.Physics.Impact.Body): void; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the collides value on. + */ + setCollidesNever(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the collides value on. + */ + setLite(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the collides value on. + */ + setPassive(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the collides value on. + */ + setActive(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the collides value on. + */ + setFixed(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setTypeNone(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setTypeA(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setTypeB(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setAvsB(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setBvsA(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setCheckAgainstNone(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setCheckAgainstA(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + * @param bodies An Array of Impact Bodies to set the type value on. + */ + setCheckAgainstB(bodies: Phaser.Physics.Impact.Body[]): Phaser.Physics.Impact.World; + + /** + * [description] + */ + shutdown(): void; + + /** + * [description] + */ + destroy(): void; + + } + + } + + namespace Matter { + /** + * 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 { + /** + * A Vector2 that stores the temporary bounds center value during calculations by methods in this class. + */ + boundsCenter: Phaser.Math.Vector2; + + /** + * A Vector2 that stores the temporary center diff values during calculations by methods in this class. + */ + centerDiff: Phaser.Math.Vector2; + + /** + * Parses the given body to get the bounds diff values from it. + * + * They're stored in this class in the temporary properties `boundsCenter` and `centerDiff`. + * + * This method is called automatically by all other methods in this class. + * @param body The Body to get the bounds position from. + */ + parseBody(body: Phaser.Types.Physics.Matter.MatterBody): boolean; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getTopLeft(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getTopCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getTopRight(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getLeftCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getRightCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getBottomLeft(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getBottomCenter(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + /** + * 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 bodies _current_ position and bounds. + * @param body The Body to get the position from. + * @param x Optional horizontal offset to add to the returned coordinates. Default 0. + * @param y Optional vertical offset to add to the returned coordinates. Default 0. + */ + getBottomRight(body: Phaser.Types.Physics.Matter.MatterBody, x?: number, y?: number): Phaser.Math.Vector2 | false; + + } + + namespace Components { + /** + * A component to set restitution on objects. + */ + interface Bounce { + /** + * Sets the restitution on the physics object. + * @param 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)` + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + } + + /** + * Contains methods for changing the collision filter of a Matter Body. Should be used as a mixin and not called directly. + */ + interface Collision { + /** + * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. + * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * @param value Unique category bitfield. + */ + setCollisionCategory(value: number): Phaser.GameObjects.GameObject; + /** + * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, + * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, + * they will never collide. + * @param value Unique group index. + */ + setCollisionGroup(value: number): Phaser.GameObjects.GameObject; + /** + * 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. + * @param categories A unique category bitfield, or an array of them. + */ + setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body starts colliding with another. + */ + setOnCollide(callback: Function): Phaser.GameObjects.GameObject; + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body stops colliding with another. + */ + setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke for the duration of this body colliding with another. + */ + setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; + /** + * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param body The body, or an array of bodies, to test for collisions with. + * @param callback The callback to invoke when this body collides with the given body or bodies. + */ + setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; + } + + /** + * A component to apply force to Matter.js bodies. + */ + interface Force { + /** + * Applies a force to a body. + * @param force A Vector that specifies the force to apply. + */ + applyForce(force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; + /** + * Applies a force to a body from a given position. + * @param position The position in which the force comes from. + * @param force A Vector that specifies the force to apply. + */ + applyForceFrom(position: Phaser.Math.Vector2, force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; + /** + * Apply thrust to the forward position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrust(speed: number): Phaser.GameObjects.GameObject; + /** + * Apply thrust to the left position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustLeft(speed: number): Phaser.GameObjects.GameObject; + /** + * Apply thrust to the right position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustRight(speed: number): Phaser.GameObjects.GameObject; + /** + * Apply thrust to the back position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustBack(speed: number): Phaser.GameObjects.GameObject; + } + + /** + * Contains methods for changing the friction of a Game Object's Matter Body. Should be used a mixin, not called directly. + */ + interface Friction { + /** + * Sets new friction values for this Game Object's Matter Body. + * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. + * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. + * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. + */ + setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; + /** + * Sets a new air resistance for this Game Object's Matter Body. + * A value of 0 means the Body will never slow as it moves through space. + * The higher the value, the faster a Body slows when moving through space. + * @param value The new air resistance for the Body. + */ + setFrictionAir(value: number): Phaser.GameObjects.GameObject; + /** + * Sets a new static friction for this Game Object's Matter Body. + * A value of 0 means the Body will never "stick" when it is nearly stationary. + * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. + * @param value The new static friction for the Body. + */ + setFrictionStatic(value: number): Phaser.GameObjects.GameObject; + } + + /** + * A component to manipulate world gravity for Matter.js bodies. + */ + interface Gravity { + /** + * A togglable function for ignoring world gravity in real-time on the current body. + * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. + */ + setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; + } + + /** + * Allows accessing the mass, density, and center of mass of a Matter-enabled Game Object. Should be used as a mixin and not directly. + */ + interface Mass { + /** + * Sets the mass of the Game Object's Matter Body. + * @param value The new mass of the body. + */ + setMass(value: number): Phaser.GameObjects.GameObject; + /** + * Sets density of the body. + * @param value The new density of the body. + */ + setDensity(value: number): Phaser.GameObjects.GameObject; + /** + * The body's center of mass. + * + * Calling this creates a new `Vector2 each time to avoid mutation. + * + * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. + */ + readonly centerOfMass: Phaser.Math.Vector2; + } + + /** + * Enables a Matter-enabled Game Object to be a sensor. Should be used as a mixin and not directly. + */ + interface Sensor { + /** + * Set the body belonging to this Game Object to be a sensor. + * Sensors trigger collision events, but don't react with colliding body physically. + * @param value `true` to set the body as a sensor, or `false` to disable it. + */ + setSensor(value: boolean): Phaser.GameObjects.GameObject; + /** + * Is the body belonging to this Game Object a sensor or not? + */ + isSensor(): boolean; + } + + /** + * Enables a Matter-enabled Game Object to set its Body. Should be used as a mixin and not directly. + */ + interface SetBody { + /** + * Set the body on a Game Object to a rectangle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setRectangle(width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + /** + * Set the body on a Game Object to a circle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param radius The radius of the circle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setCircle(radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + /** + * Set the body on the Game Object to a polygon shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param sides The number of sides the polygon will have. + * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setPolygon(sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + /** + * Set the body on the Game Object to a trapezoid shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param width The width of the trapezoid Body. + * @param height The height of the trapezoid Body. + * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setTrapezoid(width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + /** + * Set this Game Object to use the given existing Matter Body. + * + * The body is first removed from the world before being added to this Game Object. + * @param body The Body this Game Object should use. + * @param addToWorld Should the body be immediately added to the World? Default true. + */ + setExistingBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.GameObjects.GameObject; + /** + * Set this Game Object to create and use a new Body based on the configuration object given. + * + * Calling this method resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param config Either a string, such as `circle`, or a Matter Set Body Configuration object. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setBody(config: string | Phaser.Types.Physics.Matter.MatterSetBodyConfig, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + } + + /** + * Enables a Matter-enabled Game Object to be able to go to sleep. Should be used as a mixin and not directly. + */ + interface Sleep { + /** + * Sets this Body to sleep. + */ + setToSleep(): this; + /** + * Wakes this Body if asleep. + */ + setAwake(): this; + /** + * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). + * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. + */ + setSleepThreshold(value?: number): this; + /** + * Enable sleep and wake events for this body. + * + * By default when a body goes to sleep, or wakes up, it will not emit any events. + * + * The events are emitted by the Matter World instance and can be listened to via + * the `SLEEP_START` and `SLEEP_END` events. + * @param start `true` if you want the sleep start event to be emitted for this body. + * @param end `true` if you want the sleep end event to be emitted for this body. + */ + setSleepEvents(start: boolean, end: boolean): this; + /** + * Enables or disables the Sleep Start event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepStartEvent(value: boolean): this; + /** + * Enables or disables the Sleep End event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepEndEvent(value: boolean): this; + } + + /** + * Provides methods used for getting and setting the static state of a physics body. + */ + interface Static { + /** + * Changes the physics body to be either static `true` or dynamic `false`. + * @param value `true` to set the body as being static, or `false` to make it dynamic. + */ + setStatic(value: boolean): Phaser.GameObjects.GameObject; + /** + * Returns `true` if the body is static, otherwise `false` for a dynamic body. + */ + isStatic(): boolean; + } + + /** + * Provides methods used for getting and setting the position, scale and rotation of a Game Object. + */ + interface Transform { + /** + * The x position of this Game Object. + */ + x: number; + /** + * The y position of this Game Object. + */ + y: number; + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + /** + * Use `angle` to set or get rotation of the physics body associated to this GameObject. + * Unlike rotation, when using set the value can be in degrees, which will be converted to radians internally. + */ + angle: number; + /** + * Use `rotation` to set or get the rotation of the physics body associated with this GameObject. + * The value when set must be in radians. + */ + rotation: number; + /** + * Sets the position of the physics body along x and y axes. + * Both the parameters to this function are optional and if not passed any they default to 0. + * Velocity, angle, force etc. are unchanged. + * @param x The horizontal position of the body. Default 0. + * @param y The vertical position of the body. Default x. + */ + setPosition(x?: number, y?: number): this; + /** + * Immediately sets the angle of the Body. + * Angular velocity, position, force etc. are unchanged. + * @param radians The angle of the body, in radians. Default 0. + */ + setRotation(radians?: number): this; + /** + * Setting fixed rotation sets the Body inertia to Infinity, which stops it + * from being able to rotate when forces are applied to it. + */ + setFixedRotation(): this; + /** + * Immediately sets the angle of the Body. + * Angular velocity, position, force etc. are unchanged. + * @param degrees The angle to set, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. Default 1. + * @param y The vertical scale of this Game Object. If not set it will use the x value. Default x. + * @param point The point (Vector2) from which scaling will occur. + */ + setScale(x?: number, y?: number, point?: Phaser.Math.Vector2): this; + } + + /** + * Contains methods for changing the velocity of a Matter Body. Should be used as a mixin and not called directly. + */ + interface Velocity { + /** + * Sets the angular velocity of the body instantly. + * Position, angle, force etc. are unchanged. + * @param value The angular velocity. + */ + setAngularVelocity(value: number): Phaser.GameObjects.GameObject; + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): Phaser.GameObjects.GameObject; + /** + * Sets vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): Phaser.GameObjects.GameObject; + /** + * Sets both the horizontal and vertical velocity of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. Default x. + */ + setVelocity(x: number, y?: number): Phaser.GameObjects.GameObject; + } + + } + + namespace Matter { + } + + namespace Events { + type AfterAddEvent = { + /** + * An array of the object(s) that have been added. May be a single body, constraint, composite or a mixture of these. + */ + object: any[]; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics After Add Event. + * + * This event is dispatched by a Matter Physics World instance at the end of the process when a new Body + * or Constraint has just been added to the world. + * + * Listen to it from a Scene using: `this.matter.world.on('afteradd', listener)`. + */ + const AFTER_ADD: any; + + type AfterRemoveEvent = { + /** + * An array of the object(s) that were removed. May be a single body, constraint, composite or a mixture of these. + */ + object: any[]; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics After Remove Event. + * + * This event is dispatched by a Matter Physics World instance at the end of the process when a + * Body or Constraint was removed from the world. + * + * Listen to it from a Scene using: `this.matter.world.on('afterremove', listener)`. + */ + const AFTER_REMOVE: any; + + type AfterUpdateEvent = { + /** + * The Matter Engine `timing.timestamp` value for the event. + */ + timestamp: number; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics After Update Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated and all collision events have resolved. + * + * Listen to it from a Scene using: `this.matter.world.on('afterupdate', listener)`. + */ + const AFTER_UPDATE: any; + + type BeforeAddEvent = { + /** + * An array of the object(s) to be added. May be a single body, constraint, composite or a mixture of these. + */ + object: any[]; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Before Add Event. + * + * This event is dispatched by a Matter Physics World instance at the start of the process when a new Body + * or Constraint is being added to the world. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeadd', listener)`. + */ + const BEFORE_ADD: any; + + type BeforeRemoveEvent = { + /** + * An array of the object(s) to be removed. May be a single body, constraint, composite or a mixture of these. + */ + object: any[]; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Before Remove Event. + * + * This event is dispatched by a Matter Physics World instance at the start of the process when a + * Body or Constraint is being removed from the world. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeremove', listener)`. + */ + const BEFORE_REMOVE: any; + + type BeforeUpdateEvent = { + /** + * The Matter Engine `timing.timestamp` value for the event. + */ + timestamp: number; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Before Update Event. + * + * This event is dispatched by a Matter Physics World instance right before all the collision processing takes place. + * + * Listen to it from a Scene using: `this.matter.world.on('beforeupdate', listener)`. + */ + const BEFORE_UPDATE: any; + + type CollisionActiveEvent = { + /** + * A list of all affected pairs in the collision. + */ + pairs: Phaser.Types.Physics.Matter.MatterCollisionData[]; + /** + * The Matter Engine `timing.timestamp` value for the event. + */ + timestamp: number; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Collision Active Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that are colliding in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionactive', listener)`. + */ + const COLLISION_ACTIVE: any; + + type CollisionEndEvent = { + /** + * A list of all affected pairs in the collision. + */ + pairs: Phaser.Types.Physics.Matter.MatterCollisionData[]; + /** + * The Matter Engine `timing.timestamp` value for the event. + */ + timestamp: number; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Collision End Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that have finished colliding in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionend', listener)`. + */ + const COLLISION_END: any; + + type CollisionStartEvent = { + /** + * A list of all affected pairs in the collision. + */ + pairs: Phaser.Types.Physics.Matter.MatterCollisionData[]; + /** + * The Matter Engine `timing.timestamp` value for the event. + */ + timestamp: number; + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Collision Start Event. + * + * This event is dispatched by a Matter Physics World instance after the engine has updated. + * It provides a list of all pairs that have started to collide in the current tick (if any). + * + * Listen to it from a Scene using: `this.matter.world.on('collisionstart', listener)`. + */ + const COLLISION_START: any; + + /** + * The Matter Physics Drag End Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * stops dragging a body. + * + * Listen to it from a Scene using: `this.matter.world.on('dragend', listener)`. + */ + const DRAG_END: any; + + /** + * The Matter Physics Drag Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * is actively dragging a body. It is emitted each time the pointer moves. + * + * Listen to it from a Scene using: `this.matter.world.on('drag', listener)`. + */ + const DRAG: any; + + /** + * The Matter Physics Drag Start Event. + * + * This event is dispatched by a Matter Physics World instance when a Pointer Constraint + * starts dragging a body. + * + * Listen to it from a Scene using: `this.matter.world.on('dragstart', listener)`. + */ + const DRAG_START: any; + + /** + * The Matter Physics World Pause Event. + * + * This event is dispatched by an Matter Physics World instance when it is paused. + * + * Listen to it from a Scene using: `this.matter.world.on('pause', listener)`. + */ + const PAUSE: any; + + /** + * The Matter Physics World Resume Event. + * + * This event is dispatched by an Matter Physics World instance when it resumes from a paused state. + * + * Listen to it from a Scene using: `this.matter.world.on('resume', listener)`. + */ + const RESUME: any; + + type SleepEndEvent = { + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Sleep End Event. + * + * This event is dispatched by a Matter Physics World instance when a Body stop sleeping. + * + * Listen to it from a Scene using: `this.matter.world.on('sleepend', listener)`. + */ + const SLEEP_END: any; + + type SleepStartEvent = { + /** + * The source object of the event. + */ + source: any; + /** + * The name of the event. + */ + name: string; + }; + + /** + * The Matter Physics Sleep Start Event. + * + * This event is dispatched by a Matter Physics World instance when a Body goes to sleep. + * + * Listen to it from a Scene using: `this.matter.world.on('sleepstart', listener)`. + */ + const SLEEP_START: any; + + } + + /** + * The Matter Factory is responsible for quickly creating a variety of different types of + * bodies, constraints and Game Objects and adding them into the physics world. + * + * You access the factory from within a Scene using `add`: + * + * ```javascript + * this.matter.add.rectangle(x, y, width, height); + * ``` + * + * Use of the Factory is optional. All of the objects it creates can also be created + * directly via your own code or constructors. It is provided as a means to keep your + * code concise. + */ + class Factory { + /** + * + * @param world The Matter World which this Factory adds to. + */ + constructor(world: Phaser.Physics.Matter.World); + + /** + * The Matter World which this Factory adds to. + */ + world: Phaser.Physics.Matter.World; + + /** + * The Scene which this Factory's Matter World belongs to. + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene.Systems this Matter Physics instance belongs to. + */ + sys: Phaser.Scenes.Systems; + + /** + * Creates a new rigid rectangular Body and adds it to the World. + * @param x The X coordinate of the center of the Body. + * @param y The Y coordinate of the center of the Body. + * @param width The width of the Body. + * @param height The height of the Body. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + rectangle(x: number, y: number, width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; + + /** + * Creates a new rigid trapezoidal Body and adds it to the World. + * @param x The X coordinate of the center of the Body. + * @param y The Y coordinate of the center of the Body. + * @param width The width of the trapezoid Body. + * @param height The height of the trapezoid Body. + * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + trapezoid(x: number, y: number, width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; + + /** + * Creates a new rigid circular Body and adds it to the World. + * @param x The X coordinate of the center of the Body. + * @param y The Y coordinate of the center of the Body. + * @param radius The radius of the circle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + * @param maxSides The maximum amount of sides to use for the polygon which will approximate this circle. + */ + circle(x: number, y: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, maxSides?: number): MatterJS.BodyType; + + /** + * Creates a new rigid polygonal Body and adds it to the World. + * @param x The X coordinate of the center of the Body. + * @param y The Y coordinate of the center of the Body. + * @param sides The number of sides the polygon will have. + * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + polygon(x: number, y: number, sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; + + /** + * Creates a body using the supplied vertices (or an array containing multiple sets of vertices) and adds it to the World. + * If the vertices are convex, they will pass through as supplied. Otherwise, if the vertices are concave, they will be decomposed. Note that this process is not guaranteed to support complex sets of vertices, e.g. ones with holes. + * @param x The X coordinate of the center of the Body. + * @param y The Y coordinate of the center of the Body. + * @param vertexSets The vertices data. Either a path string or an array of vertices. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + * @param flagInternal Flag internal edges (coincident part edges) Default false. + * @param removeCollinear Whether Matter.js will discard collinear edges (to improve performance). Default 0.01. + * @param minimumArea During decomposition discard parts that have an area less than this. Default 10. + */ + fromVertices(x: number, y: number, vertexSets: string | any[], options?: Phaser.Types.Physics.Matter.MatterBodyConfig, flagInternal?: boolean, removeCollinear?: number, minimumArea?: number): MatterJS.BodyType; + + /** + * 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 pas in an `options` object, any settings in there will override those in the PhysicsEditor config object. + * @param x The horizontal world location of the body. + * @param y The vertical world location of the body. + * @param config The JSON data exported from PhysicsEditor. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + * @param addToWorld Should the newly created body be immediately added to the World? Default true. + */ + fromPhysicsEditor(x: number, y: number, config: any, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, addToWorld?: boolean): MatterJS.BodyType; + + /** + * 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')); + * } + * ``` + * @param x The X coordinate of the body. + * @param y The Y coordinate of the body. + * @param xml The SVG Path data. + * @param scale Scale the vertices by this amount after creation. Default 1. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + * @param addToWorld Should the newly created body be immediately added to the World? Default true. + */ + fromSVG(x: number, y: number, xml: object, scale?: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, addToWorld?: boolean): MatterJS.BodyType; + + /** + * Creates a body using the supplied physics data, as provided by a JSON file. + * + * The data file should be loaded as JSON: + * + * ```javascript + * preload () + * { + * this.load.json('ninjas', 'assets/ninjas.json); + * } + * + * create () + * { + * const ninjaShapes = this.cache.json.get('ninjas'); + * + * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); + * } + * ``` + * + * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. + * + * If you pas in an `options` object, any settings in there will override those in the config object. + * + * The structure of the JSON file is as follows: + * + * ```text + * { + * 'generator_info': // The name of the application that created the JSON data + * 'shapeName': { + * 'type': // The type of body + * 'label': // Optional body label + * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs + * } + * } + * ``` + * + * At the time of writing, only the Phaser Physics Tracer App exports in this format. + * @param x The X coordinate of the body. + * @param y The Y coordinate of the body. + * @param config The JSON physics data. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + * @param addToWorld Should the newly created body be immediately added to the World? Default true. + */ + fromJSON(x: number, y: number, config: any, options?: Phaser.Types.Physics.Matter.MatterBodyConfig, addToWorld?: boolean): MatterJS.BodyType; + + /** + * Create a new composite containing Matter Image objects created in a grid arrangement. + * This function uses the body bounds to prevent overlaps. + * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param x The horizontal position of this composite in the world. + * @param y The vertical position of this composite in the world. + * @param columns The number of columns in the grid. + * @param rows The number of rows in the grid. + * @param columnGap The distance between each column. Default 0. + * @param rowGap The distance between each row. Default 0. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + imageStack(key: string, frame: string | integer, x: number, y: number, columns: number, rows: number, columnGap?: number, rowGap?: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.CompositeType; + + /** + * Create a new composite containing bodies created in the callback in a grid arrangement. + * + * This function uses the body bounds to prevent overlaps. + * @param x The horizontal position of this composite in the world. + * @param y The vertical position of this composite in the world. + * @param columns The number of columns in the grid. + * @param rows The number of rows in the grid. + * @param columnGap The distance between each column. + * @param rowGap The distance between each row. + * @param callback The callback that creates the stack. + */ + stack(x: number, y: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): MatterJS.CompositeType; + + /** + * Create a new composite containing bodies created in the callback in a pyramid arrangement. + * This function uses the body bounds to prevent overlaps. + * @param x The horizontal position of this composite in the world. + * @param y The vertical position of this composite in the world. + * @param columns The number of columns in the pyramid. + * @param rows The number of rows in the pyramid. + * @param columnGap The distance between each column. + * @param rowGap The distance between each row. + * @param callback The callback function to be invoked. + */ + pyramid(x: number, y: number, columns: number, rows: number, columnGap: number, rowGap: number, callback: Function): MatterJS.CompositeType; + + /** + * Chains all bodies in the given composite together using constraints. + * @param composite The composite in which all bodies will be chained together sequentially. + * @param xOffsetA The horizontal offset of the BodyA constraint. This is a percentage based on the body size, not a world position. + * @param yOffsetA The vertical offset of the BodyA constraint. This is a percentage based on the body size, not a world position. + * @param xOffsetB The horizontal offset of the BodyB constraint. This is a percentage based on the body size, not a world position. + * @param yOffsetB The vertical offset of the BodyB constraint. This is a percentage based on the body size, not a world position. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + chain(composite: MatterJS.CompositeType, xOffsetA: number, yOffsetA: number, xOffsetB: number, yOffsetB: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.CompositeType; + + /** + * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. + * @param composite The composite in which all bodies will be chained together. + * @param columns The number of columns in the mesh. + * @param rows The number of rows in the mesh. + * @param crossBrace Create cross braces for the mesh as well? + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + mesh(composite: MatterJS.CompositeType, columns: number, rows: number, crossBrace: boolean, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.CompositeType; + + /** + * Creates a composite with a Newton's Cradle setup of bodies and constraints. + * @param x The horizontal position of the start of the cradle. + * @param y The vertical position of the start of the cradle. + * @param number The number of balls in the cradle. + * @param size The radius of each ball in the cradle. + * @param length The length of the 'string' the balls hang from. + */ + newtonsCradle(x: number, y: number, number: number, size: number, length: number): MatterJS.CompositeType; + + /** + * Creates a composite with simple car setup of bodies and constraints. + * @param x The horizontal position of the car in the world. + * @param y The vertical position of the car in the world. + * @param width The width of the car chasis. + * @param height The height of the car chasis. + * @param wheelSize The radius of the car wheels. + */ + car(x: number, y: number, width: number, height: number, wheelSize: number): MatterJS.CompositeType; + + /** + * Creates a simple soft body like object. + * @param x The horizontal position of this composite in the world. + * @param y The vertical position of this composite in the world. + * @param columns The number of columns in the Composite. + * @param rows The number of rows in the Composite. + * @param columnGap The distance between each column. + * @param rowGap The distance between each row. + * @param crossBrace `true` to create cross braces between the bodies, or `false` to create just straight braces. + * @param particleRadius The radius of this circlular composite. + * @param particleOptions An optional Body configuration object that is used to set initial Body properties on creation. + * @param constraintOptions An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + softBody(x: number, y: number, columns: number, rows: number, columnGap: number, rowGap: number, crossBrace: boolean, particleRadius: number, particleOptions?: Phaser.Types.Physics.Matter.MatterBodyConfig, constraintOptions?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.CompositeType; + + /** + * This method is an alias for `Factory.constraint`. + * + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * @param bodyA The first possible `Body` that this constraint is attached to. + * @param bodyB The second possible `Body` that this constraint is attached to. + * @param length A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + joint(bodyA: MatterJS.BodyType, bodyB: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; + + /** + * This method is an alias for `Factory.constraint`. + * + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * @param bodyA The first possible `Body` that this constraint is attached to. + * @param bodyB The second possible `Body` that this constraint is attached to. + * @param length A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + spring(bodyA: MatterJS.BodyType, bodyB: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; + + /** + * Constraints (or joints) 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. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * @param bodyA The first possible `Body` that this constraint is attached to. + * @param bodyB The second possible `Body` that this constraint is attached to. + * @param length A Number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + constraint(bodyA: MatterJS.BodyType, bodyB: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; + + /** + * Constraints (or joints) are used for specifying that a fixed distance must be maintained + * between two bodies, or a body and a fixed world-space position. + * + * A world constraint has only one body, you should specify a `pointA` position in + * the constraint options parameter to attach the constraint to the world. + * + * The stiffness of constraints can be modified to create springs or elastic. + * + * 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 + * `constraintIterations` within the Matter Config. + * + * For compound bodies, constraints must be applied to the parent body and not one of its parts. + * @param body The Matter `Body` that this constraint is attached to. + * @param length A number that specifies the target resting length of the constraint. If not given it is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. + * @param stiffness A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. A value of `1` means the constraint should be very stiff. A value of `0.2` means the constraint acts as a soft spring. Default 1. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + worldConstraint(body: MatterJS.BodyType, length?: number, stiffness?: number, options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; + + /** + * This method is an alias for `Factory.pointerConstraint`. + * + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + mouseSpring(options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; + + /** + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + * @param options An optional Constraint configuration object that is used to set initial Constraint properties on creation. + */ + pointerConstraint(options?: Phaser.Types.Physics.Matter.MatterConstraintConfig): MatterJS.ConstraintType; + + /** + * Creates a Matter Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + image(x: number, y: number, key: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.Physics.Matter.Image; + + /** + * Creates a wrapper around a Tile that provides access to a corresponding Matter body. A tile can only + * have one Matter body associated with it. You can either pass in an existing Matter body for + * the tile or allow the constructor to create the corresponding body for you. If the Tile has a + * collision group (defined in Tiled), those shapes will be used to create the body. If not, the + * tile's rectangle bounding box will be used. + * + * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. + * + * Note: not all Tiled collision shapes are supported. See + * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. + * @param tile The target tile that should have a Matter body. + * @param options Options to be used when creating the Matter body. + */ + tileBody(tile: Phaser.Tilemaps.Tile, options?: Phaser.Types.Physics.Matter.MatterTileOptions): Phaser.Physics.Matter.TileBody; + + /** + * Creates a Matter Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param key The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. Set to `null` to skip this value. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + sprite(x: number, y: number, key: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.Physics.Matter.Sprite; + + /** + * Takes an existing Game Object and injects all of the Matter Components into it. + * + * This enables you to use component methods such as `setVelocity` or `isSensor` directly from + * this Game Object. + * + * You can also pass in either a Matter Body Configuration object, or a Matter Body instance + * to link with this Game Object. + * @param gameObject The Game Object to inject the Matter Components in to. + * @param options A Matter Body configuration object, or an instance of a Matter Body. + * @param addToWorld Add this Matter Body to the World? Default true. + */ + gameObject(gameObject: Phaser.GameObjects.GameObject, options?: Phaser.Types.Physics.Matter.MatterBodyConfig | MatterJS.Body, addToWorld?: boolean): Phaser.GameObjects.GameObject; + + /** + * Destroys this Factory. + */ + destroy(): void; + + } + + /** + * A Matter Game Object is a generic object that allows you to combine any Phaser Game Object, + * including those you have extended or created yourself, with all of the Matter Components. + * + * This enables you to use component methods such as `setVelocity` or `isSensor` directly from + * this Game Object. + * @param world The Matter world to add the body to. + * @param gameObject The Game Object that will have the Matter body applied to it. + * @param options A Matter Body configuration object, or an instance of a Matter Body. + * @param addToWorld Should the newly created body be immediately added to the World? Default true. + */ + function MatterGameObject(world: Phaser.Physics.Matter.World, gameObject: Phaser.GameObjects.GameObject, options?: Phaser.Types.Physics.Matter.MatterBodyConfig | MatterJS.Body, addToWorld?: boolean): Phaser.GameObjects.GameObject; + + /** + * A Matter Physics Image Game Object. + * + * An Image is a light-weight Game Object useful for the display of static images in your game, + * such as logos, backgrounds, scenery or other non-animated elements. Images can have input + * events and physics bodies, or be tweened, tinted or scrolled. The main difference between an + * Image and a Sprite is that you cannot animate an Image as they do not have the Animation component. + */ + class Image extends Phaser.GameObjects.Image implements Phaser.Physics.Matter.Components.Bounce, Phaser.Physics.Matter.Components.Collision, Phaser.Physics.Matter.Components.Force, Phaser.Physics.Matter.Components.Friction, Phaser.Physics.Matter.Components.Gravity, Phaser.Physics.Matter.Components.Mass, Phaser.Physics.Matter.Components.Sensor, Phaser.Physics.Matter.Components.SetBody, Phaser.Physics.Matter.Components.Sleep, Phaser.Physics.Matter.Components.Static, Phaser.Physics.Matter.Components.Transform, Phaser.Physics.Matter.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param world A reference to the Matter.World instance that this body belongs to. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + constructor(world: Phaser.Physics.Matter.World, x: number, y: number, texture: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig); + + /** + * A reference to the Matter.World instance that this body belongs to. + */ + world: Phaser.Physics.Matter.World; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * Sets the restitution on the physics object. + * @param 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)` + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. + * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * @param value Unique category bitfield. + */ + setCollisionCategory(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, + * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, + * they will never collide. + * @param value Unique group index. + */ + setCollisionGroup(value: number): Phaser.GameObjects.GameObject; + + /** + * 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. + * @param categories A unique category bitfield, or an array of them. + */ + setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body starts colliding with another. + */ + setOnCollide(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body stops colliding with another. + */ + setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke for the duration of this body colliding with another. + */ + setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param body The body, or an array of bodies, to test for collisions with. + * @param callback The callback to invoke when this body collides with the given body or bodies. + */ + setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; + + /** + * Applies a force to a body. + * @param force A Vector that specifies the force to apply. + */ + applyForce(force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; + + /** + * Applies a force to a body from a given position. + * @param position The position in which the force comes from. + * @param force A Vector that specifies the force to apply. + */ + applyForceFrom(position: Phaser.Math.Vector2, force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the forward position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrust(speed: number): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the left position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustLeft(speed: number): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the right position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustRight(speed: number): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the back position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustBack(speed: number): Phaser.GameObjects.GameObject; + + /** + * Sets new friction values for this Game Object's Matter Body. + * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. + * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. + * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. + */ + setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; + + /** + * Sets a new air resistance for this Game Object's Matter Body. + * A value of 0 means the Body will never slow as it moves through space. + * The higher the value, the faster a Body slows when moving through space. + * @param value The new air resistance for the Body. + */ + setFrictionAir(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets a new static friction for this Game Object's Matter Body. + * A value of 0 means the Body will never "stick" when it is nearly stationary. + * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. + * @param value The new static friction for the Body. + */ + setFrictionStatic(value: number): Phaser.GameObjects.GameObject; + + /** + * A togglable function for ignoring world gravity in real-time on the current body. + * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. + */ + setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Sets the mass of the Game Object's Matter Body. + * @param value The new mass of the body. + */ + setMass(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets density of the body. + * @param value The new density of the body. + */ + setDensity(value: number): Phaser.GameObjects.GameObject; + + /** + * The body's center of mass. + * + * Calling this creates a new `Vector2 each time to avoid mutation. + * + * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. + */ + readonly centerOfMass: Phaser.Math.Vector2; + + /** + * Set the body belonging to this Game Object to be a sensor. + * Sensors trigger collision events, but don't react with colliding body physically. + * @param value `true` to set the body as a sensor, or `false` to disable it. + */ + setSensor(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Is the body belonging to this Game Object a sensor or not? + */ + isSensor(): boolean; + + /** + * Set the body on a Game Object to a rectangle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setRectangle(width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set the body on a Game Object to a circle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param radius The radius of the circle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setCircle(radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set the body on the Game Object to a polygon shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param sides The number of sides the polygon will have. + * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setPolygon(sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set the body on the Game Object to a trapezoid shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param width The width of the trapezoid Body. + * @param height The height of the trapezoid Body. + * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setTrapezoid(width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set this Game Object to use the given existing Matter Body. + * + * The body is first removed from the world before being added to this Game Object. + * @param body The Body this Game Object should use. + * @param addToWorld Should the body be immediately added to the World? Default true. + */ + setExistingBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.GameObjects.GameObject; + + /** + * Set this Game Object to create and use a new Body based on the configuration object given. + * + * Calling this method resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param config Either a string, such as `circle`, or a Matter Set Body Configuration object. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setBody(config: string | Phaser.Types.Physics.Matter.MatterSetBodyConfig, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Sets this Body to sleep. + */ + setToSleep(): this; + + /** + * Wakes this Body if asleep. + */ + setAwake(): this; + + /** + * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). + * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. + */ + setSleepThreshold(value?: number): this; + + /** + * Enable sleep and wake events for this body. + * + * By default when a body goes to sleep, or wakes up, it will not emit any events. + * + * The events are emitted by the Matter World instance and can be listened to via + * the `SLEEP_START` and `SLEEP_END` events. + * @param start `true` if you want the sleep start event to be emitted for this body. + * @param end `true` if you want the sleep end event to be emitted for this body. + */ + setSleepEvents(start: boolean, end: boolean): this; + + /** + * Enables or disables the Sleep Start event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepStartEvent(value: boolean): this; + + /** + * Enables or disables the Sleep End event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepEndEvent(value: boolean): this; + + /** + * Changes the physics body to be either static `true` or dynamic `false`. + * @param value `true` to set the body as being static, or `false` to make it dynamic. + */ + setStatic(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Returns `true` if the body is static, otherwise `false` for a dynamic body. + */ + isStatic(): boolean; + + /** + * Setting fixed rotation sets the Body inertia to Infinity, which stops it + * from being able to rotate when forces are applied to it. + */ + setFixedRotation(): this; + + /** + * Sets the angular velocity of the body instantly. + * Position, angle, force etc. are unchanged. + * @param value The angular velocity. + */ + setAngularVelocity(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): Phaser.GameObjects.GameObject; + + /** + * Sets vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): Phaser.GameObjects.GameObject; + + /** + * Sets both the horizontal and vertical velocity of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. Default x. + */ + setVelocity(x: number, y?: number): Phaser.GameObjects.GameObject; + + } + + /** + * 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 { + /** + * + * @param scene The Phaser Scene that owns this Matter Physics instance. + */ + constructor(scene: Phaser.Scene); + + /** + * The Phaser Scene that owns this Matter Physics instance + */ + scene: Phaser.Scene; + + /** + * A reference to the Scene Systems that belong to the Scene owning this Matter Physics instance. + */ + systems: Phaser.Scenes.Systems; + + /** + * The parsed Matter Configuration object. + */ + config: Phaser.Types.Physics.Matter.MatterWorldConfig; + + /** + * An instance of the Matter World class. This class is responsible for the updating of the + * Matter Physics world, as well as handling debug drawing functions. + */ + world: Phaser.Physics.Matter.World; + + /** + * An instance of the Matter Factory. This class provides lots of functions for creating a + * wide variety of physics objects and adds them automatically to the Matter World. + * + * You can use this class to cut-down on the amount of code required in your game, however, + * use of the Factory is entirely optional and should be seen as a development aid. It's + * perfectly possible to create and add components to the Matter world without using it. + */ + add: Phaser.Physics.Matter.Factory; + + /** + * An instance of the Body Bounds class. This class contains functions used for getting the + * world position from various points around the bounds of a physics body. + */ + bodyBounds: Phaser.Physics.Matter.BodyBounds; + + /** + * A reference to the `Matter.Body` module. + * + * 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 `Bodies` module. + */ + body: MatterJS.BodyFactory; + + /** + * A reference to the `Matter.Composite` module. + * + * 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`. + */ + composite: MatterJS.CompositeFactory; + + /** + * A reference to the `Matter.Detector` module. + * + * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. + */ + detector: MatterJS.DetectorFactory; + + /** + * A reference to the `Matter.Grid` module. + * + * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. + */ + grid: MatterJS.GridFactory; + + /** + * A reference to the `Matter.Pair` module. + * + * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. + */ + pair: MatterJS.PairFactory; + + /** + * A reference to the `Matter.Pairs` module. + * + * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. + */ + pairs: MatterJS.PairsFactory; + + /** + * A reference to the `Matter.Query` module. + * + * The `Matter.Query` module contains methods for performing collision queries. + */ + query: MatterJS.QueryFactory; + + /** + * A reference to the `Matter.Resolver` module. + * + * The `Matter.Resolver` module contains methods for resolving collision pairs. + */ + resolver: MatterJS.ResolverFactory; + + /** + * A reference to the `Matter.SAT` module. + * + * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. + */ + sat: MatterJS.SATFactory; + + /** + * A reference to the `Matter.Constraint` module. + * + * 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. + */ + constraint: MatterJS.ConstraintFactory; + + /** + * A reference to the `Matter.Bodies` module. + * + * The `Matter.Bodies` module contains factory methods for creating rigid bodies + * with commonly used body configurations (such as rectangles, circles and other polygons). + */ + bodies: MatterJS.BodiesFactory; + + /** + * A reference to the `Matter.Composites` module. + * + * The `Matter.Composites` module contains factory methods for creating composite bodies + * with commonly used configurations (such as stacks and chains). + */ + composites: MatterJS.CompositesFactory; + + /** + * A reference to the `Matter.Axes` module. + * + * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. + */ + axes: MatterJS.AxesFactory; + + /** + * A reference to the `Matter.Bounds` module. + * + * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). + */ + bounds: MatterJS.BoundsFactory; + + /** + * 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 + */ + svg: MatterJS.SvgFactory; + + /** + * A reference to the `Matter.Vector` module. + * + * 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 }`. + */ + vector: MatterJS.VectorFactory; + + /** + * A reference to the `Matter.Vertices` module. + * + * 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). + */ + vertices: MatterJS.VerticesFactory; + + /** + * A reference to the `Matter.Vertices` module. + * + * 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). + */ + verts: MatterJS.VerticesFactory; + + /** + * This internal method is called when this class starts and retrieves the final Matter World Config. + */ + getConfig(): Phaser.Types.Physics.Matter.MatterWorldConfig; + + /** + * Enables the Matter Attractors Plugin. + * + * The attractors plugin that makes it easy to apply continual forces on bodies. + * It's possible to simulate effects such as wind, gravity and magnetism. + * + * https://github.com/liabru/matter-attractors + * + * This method is called automatically if `plugins.attractors` is set in the Matter World Config. + * However, you can also call it directly from within your game. + */ + enableAttractorPlugin(): this; + + /** + * Enables the Matter Wrap Plugin. + * + * The coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay + * within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, + * while maintaining its velocity. + * + * https://github.com/liabru/matter-wrap + * + * This method is called automatically if `plugins.wrap` is set in the Matter World Config. + * However, you can also call it directly from within your game. + */ + enableWrapPlugin(): this; + + /** + * Enables the Matter Collision Events Plugin. + * + * Note that this plugin is enabled by default. So you should only ever need to call this + * method if you have specifically disabled the plugin in your Matter World Config. + * You can disable it by setting `plugins.collisionevents: false` in your Matter World Config. + * + * This plugin triggers three new events on Matter.Body: + * + * 1. `onCollide` + * 2. `onCollideEnd` + * 3. `onCollideActive` + * + * These events correspond to the Matter.js events `collisionStart`, `collisionActive` and `collisionEnd`, respectively. + * You can listen to these events via Matter.Events or they will also be emitted from the Matter World. + * + * This plugin also extends Matter.Body with three convenience functions: + * + * `Matter.Body.setOnCollide(callback)` + * `Matter.Body.setOnCollideEnd(callback)` + * `Matter.Body.setOnCollideActive(callback)` + * + * You can register event callbacks by providing a function of type (pair: Matter.Pair) => void + * + * https://github.com/dxu/matter-collision-events + */ + enableCollisionEventsPlugin(): this; + + /** + * Pauses the Matter World instance and sets `enabled` to `false`. + * + * A paused world will not run any simulations for the duration it is paused. + */ + pause(): Phaser.Physics.Matter.World; + + /** + * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. + */ + resume(): Phaser.Physics.Matter.World; + + /** + * Sets the Matter Engine to run at fixed timestep of 60Hz and enables `autoUpdate`. + * If you have set a custom `getDelta` function then this will override it. + */ + set60Hz(): this; + + /** + * Sets the Matter Engine to run at fixed timestep of 30Hz and enables `autoUpdate`. + * If you have set a custom `getDelta` function then this will override it. + */ + set30Hz(): this; + + /** + * Manually advances the physics simulation by one iteration. + * + * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. + * If undefined they use the Matter defaults of 60Hz and no correction. + * + * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. + * + * It also ignores any custom `getDelta` functions, as you should be passing the delta + * value in to this call. + * + * You can adjust the number of iterations that Engine.update performs internally. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * @param delta The delta value. Default 16.666. + * @param correction Optional delta correction value. Default 1. + */ + step(delta?: number, correction?: number): void; + + /** + * Checks if the vertices of the given body, or an array of bodies, contains the given point, or not. + * + * You can pass in either a single body, or an array of bodies to be checked. This method will + * return `true` if _any_ of the bodies in the array contain the point. See the `intersectPoint` method if you need + * to get a list of intersecting bodies. + * + * The point should be transformed into the Matter World coordinate system in advance. This happens by + * default with Input Pointers, but if you wish to use points from another system you may need to + * transform them before passing them. + * @param body The body, or an array of bodies, to check against the point. + * @param x The horizontal coordinate of the point. + * @param y The vertical coordinate of the point. + */ + containsPoint(body: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], x: number, y: number): boolean; + + /** + * Checks the given coordinates to see if any vertices of the given bodies contain it. + * + * If no bodies are provided it will search all bodies in the Matter World, including within Composites. + * + * The coordinates should be transformed into the Matter World coordinate system in advance. This happens by + * default with Input Pointers, but if you wish to use coordinates from another system you may need to + * transform them before passing them. + * @param x The horizontal coordinate of the point. + * @param y The vertical coordinate of the point. + * @param bodies An array of bodies to check. If not provided it will search all bodies in the world. + */ + intersectPoint(x: number, y: number, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; + + /** + * Checks the given rectangular area to see if any vertices of the given bodies intersect with it. + * Or, if the `outside` parameter is set to `true`, it checks to see which bodies do not + * intersect with it. + * + * If no bodies are provided it will search all bodies in the Matter World, including within Composites. + * @param x The horizontal coordinate of the top-left of the area. + * @param y The vertical coordinate of the top-left of the area. + * @param width The width of the area. + * @param height The height of the area. + * @param outside If `false` it checks for vertices inside the area, if `true` it checks for vertices outside the area. Default false. + * @param bodies An array of bodies to check. If not provided it will search all bodies in the world. + */ + intersectRect(x: number, y: number, width: number, height: number, outside?: boolean, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; + + /** + * Checks the given ray segment to see if any vertices of the given bodies intersect with it. + * + * If no bodies are provided it will search all bodies in the Matter World. + * + * The width of the ray can be specified via the `rayWidth` parameter. + * @param x1 The horizontal coordinate of the start of the ray segment. + * @param y1 The vertical coordinate of the start of the ray segment. + * @param x2 The horizontal coordinate of the end of the ray segment. + * @param y2 The vertical coordinate of the end of the ray segment. + * @param rayWidth The width of the ray segment. Default 1. + * @param bodies An array of bodies to check. If not provided it will search all bodies in the world. + */ + intersectRay(x1: number, y1: number, x2: number, y2: number, rayWidth?: number, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; + + /** + * Checks the given Matter Body to see if it intersects with any of the given bodies. + * + * If no bodies are provided it will check against all bodies in the Matter World. + * @param body The target body. + * @param bodies An array of bodies to check the target body against. If not provided it will search all bodies in the world. + */ + intersectBody(body: Phaser.Types.Physics.Matter.MatterBody, bodies?: Phaser.Types.Physics.Matter.MatterBody[]): Phaser.Types.Physics.Matter.MatterBody[]; + + /** + * Checks to see if the target body, or an array of target bodies, intersects with any of the given bodies. + * + * If intersection occurs this method will return `true` and, if provided, invoke the callbacks. + * + * If no bodies are provided for the second parameter the target will check again all bodies in the Matter World. + * + * Note that bodies can only overlap if they are in non-colliding collision groups or categories. + * + * If you provide a `processCallback` then the two bodies that overlap are sent to it. This callback + * must return a boolean and is used to allow you to perform additional processing tests before a final + * outcome is decided. If it returns `true` then the bodies are finally passed to the `overlapCallback`, if set. + * + * If you provide an `overlapCallback` then the matching pairs of overlapping bodies will be sent to it. + * + * Both callbacks have the following signature: `function (bodyA, bodyB, collisionInfo)` where `bodyA` is always + * the target body. The `collisionInfo` object contains additional data, such as the angle and depth of penetration. + * @param target The target body, or array of target bodies, to check. + * @param bodies The second body, or array of bodies, to check. If falsey it will check against all bodies in the world. + * @param overlapCallback An optional callback function that is called if the bodies overlap. + * @param processCallback An optional callback function that lets you perform additional checks against the two bodies if they overlap. If this is set then `overlapCallback` will only be invoked if this callback returns `true`. + * @param callbackContext The context, or scope, in which to run the callbacks. + */ + overlap(target: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], bodies?: Phaser.Types.Physics.Matter.MatterBody[], overlapCallback?: ArcadePhysicsCallback, processCallback?: ArcadePhysicsCallback, callbackContext?: any): boolean; + + /** + * Sets the collision filter category of all given Matter Bodies to the given value. + * + * This number must be a power of two between 2^0 (= 1) and 2^31. + * + * Bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * @param bodies An array of bodies to update. If falsey it will use all bodies in the world. + * @param value Unique category bitfield. + */ + setCollisionCategory(bodies: Phaser.Types.Physics.Matter.MatterBody[], value: number): this; + + /** + * Sets the collision filter group of all given Matter Bodies to the given value. + * + * If the group value is zero, or if two Matter Bodies have different group values, + * they will collide according to the usual collision filter rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * + * If two Matter Bodies have the same positive group value, they will always collide; + * if they have the same negative group value they will never collide. + * @param bodies An array of bodies to update. If falsey it will use all bodies in the world. + * @param value Unique group index. + */ + setCollisionGroup(bodies: Phaser.Types.Physics.Matter.MatterBody[], value: number): this; + + /** + * 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. + * @param bodies An array of bodies to update. If falsey it will use all bodies in the world. + * @param categories A unique category bitfield, or an array of them. + */ + setCollidesWith(bodies: Phaser.Types.Physics.Matter.MatterBody[], categories: number | number[]): this; + + /** + * Takes an array and returns a new array made from all of the Matter Bodies found in the original array. + * + * For example, passing in Matter Game Objects, such as a bunch of Matter Sprites, to this method, would + * return an array containing all of their native Matter Body objects. + * + * If the `bodies` argument is falsey, it will return all bodies in the world. + * @param bodies An array of objects to extract the bodies from. If falsey, it will return all bodies in the world. + */ + getMatterBodies(bodies?: any[]): MatterJS.BodyType[]; + + /** + * Sets both the horizontal and vertical linear velocity of the physics bodies. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param x The horizontal linear velocity value. + * @param y The vertical linear velocity value. + */ + setVelocity(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], x: number, y: number): this; + + /** + * Sets just the horizontal linear velocity of the physics bodies. + * The vertical velocity of the body is unchanged. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param x The horizontal linear velocity value. + */ + setVelocityX(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], x: number): this; + + /** + * Sets just the vertical linear velocity of the physics bodies. + * The horizontal velocity of the body is unchanged. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param y The vertical linear velocity value. + */ + setVelocityY(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], y: number): this; + + /** + * Sets the angular velocity of the bodies instantly. + * Position, angle, force etc. are unchanged. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param value The angular velocity. + */ + setAngularVelocity(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], value: number): this; + + /** + * Applies a force to a body, at the bodies current position, including resulting torque. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param force A Vector that specifies the force to apply. + */ + applyForce(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], force: Phaser.Types.Math.Vector2Like): this; + + /** + * Applies a force to a body, from the given world position, including resulting torque. + * 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. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param position A Vector that specifies the world-space position to apply the force at. + * @param speed A speed value to be applied to a directional force. + * @param angle The angle, in radians, to apply the force from. Leave undefined to use the current body angle. + */ + applyForceFromPosition(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], position: Phaser.Types.Math.Vector2Like, speed: number, angle?: number): this; + + /** + * 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. + * @param bodies Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. + * @param speed A speed value to be applied to a directional force. + * @param angle The angle, in radians, to apply the force from. Leave undefined to use the current body angle. + */ + applyForceFromAngle(bodies: Phaser.Types.Physics.Matter.MatterBody | Phaser.Types.Physics.Matter.MatterBody[], speed: number, angle?: number): this; + + /** + * Returns the length of the given constraint, which is the distance between the two points. + * @param constraint The constraint to get the length from. + */ + getConstraintLength(constraint: MatterJS.ConstraintType): number; + + /** + * 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. + * @param body The Body to align. + * @param x The horizontal position to align the body to. + * @param y The vertical position to align the body to. + * @param align One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`. + */ + alignBody(body: Phaser.Types.Physics.Matter.MatterBody, x: number, y: number, align: integer): this; + + } + + /** + * A Matter Physics Sprite Game Object. + * + * A Sprite Game Object is used for the display of both static and animated images in your game. + * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled + * and animated. + * + * The main difference between a Sprite and an Image Game Object is that you cannot animate Images. + * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation + * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases. + */ + class Sprite extends Phaser.GameObjects.Sprite implements Phaser.Physics.Matter.Components.Bounce, Phaser.Physics.Matter.Components.Collision, Phaser.Physics.Matter.Components.Force, Phaser.Physics.Matter.Components.Friction, Phaser.Physics.Matter.Components.Gravity, Phaser.Physics.Matter.Components.Mass, Phaser.Physics.Matter.Components.Sensor, Phaser.Physics.Matter.Components.SetBody, Phaser.Physics.Matter.Components.Sleep, Phaser.Physics.Matter.Components.Static, Phaser.Physics.Matter.Components.Transform, Phaser.Physics.Matter.Components.Velocity, Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Size, Phaser.GameObjects.Components.Texture, Phaser.GameObjects.Components.Tint, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param world A reference to the Matter.World instance that this body belongs to. + * @param x The horizontal position of this Game Object in the world. + * @param y The vertical position of this Game Object in the world. + * @param texture The key of the Texture this Game Object will use to render with, as stored in the Texture Manager. + * @param frame An optional frame from the Texture this Game Object is rendering with. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + constructor(world: Phaser.Physics.Matter.World, x: number, y: number, texture: string, frame?: string | integer, options?: Phaser.Types.Physics.Matter.MatterBodyConfig); + + /** + * A reference to the Matter.World instance that this body belongs to. + */ + world: Phaser.Physics.Matter.World; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * The Mask this Game Object is using during render. + */ + mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask; + + /** + * Sets the mask that this Game Object will use to render with. + * + * The mask must have been previously created and can be either a GeometryMask or a BitmapMask. + * Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas. + * + * If a mask is already set on this Game Object it will be immediately replaced. + * + * Masks are positioned in global space and are not relative to the Game Object to which they + * are applied. The reason for this is that multiple Game Objects can all share the same mask. + * + * Masks have no impact on physics or input detection. They are purely a rendering component + * that allows you to limit what is visible during the render pass. + * @param mask The mask this Game Object will use when rendering. + */ + setMask(mask: Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask): this; + + /** + * Clears the mask that this Game Object was using. + * @param destroyMask Destroy the mask before clearing it? Default false. + */ + clearMask(destroyMask?: boolean): this; + + /** + * Creates and returns a Bitmap Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a renderable Game Object. + * A renderable Game Object is one that uses a texture to render with, such as an + * Image, Sprite, Render Texture or BitmapText. + * + * If you do not provide a renderable object, and this Game Object has a texture, + * it will use itself as the object. This means you can call this method to create + * a Bitmap Mask from any renderable Game Object. + * @param renderable A renderable Game Object that uses a texture, such as a Sprite. + */ + createBitmapMask(renderable?: Phaser.GameObjects.GameObject): Phaser.Display.Masks.BitmapMask; + + /** + * Creates and returns a Geometry Mask. This mask can be used by any Game Object, + * including this one. + * + * To create the mask you need to pass in a reference to a Graphics Game Object. + * + * If you do not provide a graphics object, and this Game Object is an instance + * of a Graphics object, then it will use itself to create the mask. + * + * This means you can call this method to create a Geometry Mask from any Graphics Game Object. + * @param graphics A Graphics Game Object. The geometry within it will be used as the mask. + */ + createGeometryMask(graphics?: Phaser.GameObjects.Graphics): Phaser.Display.Masks.GeometryMask; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the size of this Game Object to be that of the given Frame. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param frame The frame to base the size of this Game Object on. + */ + setSizeToFrame(frame: Phaser.Textures.Frame): this; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The Texture this Game Object is using to render with. + */ + texture: Phaser.Textures.Texture | Phaser.Textures.CanvasTexture; + + /** + * The Texture Frame this Game Object is using to render with. + */ + frame: Phaser.Textures.Frame; + + /** + * A boolean flag indicating if this Game Object is being cropped or not. + * You can toggle this at any time after `setCrop` has been called, to turn cropping on or off. + * Equally, calling `setCrop` with no arguments will reset the crop and disable it. + */ + isCropped: boolean; + + /** + * Applies a crop to a texture based Game Object, such as a Sprite or Image. + * + * The crop is a rectangle that limits the area of the texture frame that is visible during rendering. + * + * Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just + * changes what is shown when rendered. + * + * The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left. + * + * Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left + * half of it, you could call `setCrop(0, 0, 400, 600)`. + * + * It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop + * an area of 200x100 when applied to a Game Object that had a scale factor of 2. + * + * You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument. + * + * Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`. + * + * You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow + * the renderer to skip several internal calculations. + * @param x The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored. + * @param y The y coordinate to start the crop from. + * @param width The width of the crop rectangle in pixels. + * @param height The height of the crop rectangle in pixels. + */ + setCrop(x?: number | Phaser.Geom.Rectangle, y?: number, width?: number, height?: number): this; + + /** + * Sets the texture and frame this Game Object will use to render with. + * + * Textures are referenced by their string-based keys, as stored in the Texture Manager. + * @param key The key of the texture to be used, as stored in the Texture Manager. + * @param frame The name or index of the frame within the Texture. + */ + setTexture(key: string, frame?: string | integer): this; + + /** + * Sets the frame this Game Object will use to render with. + * + * The Frame has to belong to the current Texture being used. + * + * It can be either a string or an index. + * + * Calling `setFrame` will modify the `width` and `height` properties of your Game Object. + * It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer. + * @param frame The name or index of the frame within the Texture. + * @param updateSize Should this call adjust the size of the Game Object? Default true. + * @param updateOrigin Should this call adjust the origin of the Game Object? Default true. + */ + setFrame(frame: string | integer, updateSize?: boolean, updateOrigin?: boolean): this; + + /** + * Fill or additive? + */ + tintFill: boolean; + + /** + * Clears all tint values associated with this Game Object. + * + * Immediately sets the color values back to 0xffffff and the tint type to 'additive', + * which results in no visible change to the texture. + */ + clearTint(): this; + + /** + * Sets an additive tint on this Game Object. + * + * The tint works by taking the pixel color values from the Game Objects texture, and then + * multiplying it by the color value of the tint. You can provide either one color value, + * in which case the whole Game Object will be tinted in that color. Or you can provide a color + * per corner. The colors are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`. + * @param topLeft The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTint(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * Sets a fill-based tint on this Game Object. + * + * Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture + * with those in the tint. You can use this for effects such as making a player flash 'white' + * if hit by something. You can provide either one color value, in which case the whole + * Game Object will be rendered in that color. Or you can provide a color per corner. The colors + * are blended together across the extent of the Game Object. + * + * To modify the tint color once set, either call this method again with new values or use the + * `tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight, + * `tintBottomLeft` and `tintBottomRight` to set the corner color values independently. + * + * To remove a tint call `clearTint`. + * + * To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`. + * @param topLeft The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object. Default 0xffffff. + * @param topRight The tint being applied to the top-right of the Game Object. + * @param bottomLeft The tint being applied to the bottom-left of the Game Object. + * @param bottomRight The tint being applied to the bottom-right of the Game Object. + */ + setTintFill(topLeft?: integer, topRight?: integer, bottomLeft?: integer, bottomRight?: integer): this; + + /** + * The tint value being applied to the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopLeft: integer; + + /** + * The tint value being applied to the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintTopRight: integer; + + /** + * The tint value being applied to the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomLeft: integer; + + /** + * The tint value being applied to the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + tintBottomRight: integer; + + /** + * The tint value being applied to the whole of the Game Object. + * This property is a setter-only. Use the properties `tintTopLeft` etc to read the current tint value. + */ + tint: integer; + + /** + * Does this Game Object have a tint applied to it or not? + */ + readonly isTinted: boolean; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * Sets the restitution on the physics object. + * @param 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)` + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. + * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * @param value Unique category bitfield. + */ + setCollisionCategory(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, + * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, + * they will never collide. + * @param value Unique group index. + */ + setCollisionGroup(value: number): Phaser.GameObjects.GameObject; + + /** + * 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. + * @param categories A unique category bitfield, or an array of them. + */ + setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body starts colliding with another. + */ + setOnCollide(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body stops colliding with another. + */ + setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke for the duration of this body colliding with another. + */ + setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param body The body, or an array of bodies, to test for collisions with. + * @param callback The callback to invoke when this body collides with the given body or bodies. + */ + setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; + + /** + * Applies a force to a body. + * @param force A Vector that specifies the force to apply. + */ + applyForce(force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; + + /** + * Applies a force to a body from a given position. + * @param position The position in which the force comes from. + * @param force A Vector that specifies the force to apply. + */ + applyForceFrom(position: Phaser.Math.Vector2, force: Phaser.Math.Vector2): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the forward position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrust(speed: number): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the left position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustLeft(speed: number): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the right position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustRight(speed: number): Phaser.GameObjects.GameObject; + + /** + * Apply thrust to the back position of the body. + * + * Use very small values, such as 0.1, depending on the mass and required speed. + * @param speed A speed value to be applied to a directional force. + */ + thrustBack(speed: number): Phaser.GameObjects.GameObject; + + /** + * Sets new friction values for this Game Object's Matter Body. + * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. + * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. + * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. + */ + setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; + + /** + * Sets a new air resistance for this Game Object's Matter Body. + * A value of 0 means the Body will never slow as it moves through space. + * The higher the value, the faster a Body slows when moving through space. + * @param value The new air resistance for the Body. + */ + setFrictionAir(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets a new static friction for this Game Object's Matter Body. + * A value of 0 means the Body will never "stick" when it is nearly stationary. + * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. + * @param value The new static friction for the Body. + */ + setFrictionStatic(value: number): Phaser.GameObjects.GameObject; + + /** + * A togglable function for ignoring world gravity in real-time on the current body. + * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. + */ + setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Sets the mass of the Game Object's Matter Body. + * @param value The new mass of the body. + */ + setMass(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets density of the body. + * @param value The new density of the body. + */ + setDensity(value: number): Phaser.GameObjects.GameObject; + + /** + * The body's center of mass. + * + * Calling this creates a new `Vector2 each time to avoid mutation. + * + * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. + */ + readonly centerOfMass: Phaser.Math.Vector2; + + /** + * Set the body belonging to this Game Object to be a sensor. + * Sensors trigger collision events, but don't react with colliding body physically. + * @param value `true` to set the body as a sensor, or `false` to disable it. + */ + setSensor(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Is the body belonging to this Game Object a sensor or not? + */ + isSensor(): boolean; + + /** + * Set the body on a Game Object to a rectangle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setRectangle(width: number, height: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set the body on a Game Object to a circle. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param radius The radius of the circle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setCircle(radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set the body on the Game Object to a polygon shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param sides The number of sides the polygon will have. + * @param radius The "radius" of the polygon, i.e. the distance from its center to any vertex. This is also the radius of its circumcircle. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setPolygon(sides: number, radius: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set the body on the Game Object to a trapezoid shape. + * + * Calling this methods resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param width The width of the trapezoid Body. + * @param height The height of the trapezoid Body. + * @param slope The slope of the trapezoid. 0 creates a rectangle, while 1 creates a triangle. Positive values make the top side shorter, while negative values make the bottom side shorter. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setTrapezoid(width: number, height: number, slope: number, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Set this Game Object to use the given existing Matter Body. + * + * The body is first removed from the world before being added to this Game Object. + * @param body The Body this Game Object should use. + * @param addToWorld Should the body be immediately added to the World? Default true. + */ + setExistingBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.GameObjects.GameObject; + + /** + * Set this Game Object to create and use a new Body based on the configuration object given. + * + * Calling this method resets previous properties you may have set on the body, including + * plugins, mass, friction, etc. So be sure to re-apply these in the options object if needed. + * @param config Either a string, such as `circle`, or a Matter Set Body Configuration object. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + setBody(config: string | Phaser.Types.Physics.Matter.MatterSetBodyConfig, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): Phaser.GameObjects.GameObject; + + /** + * Sets this Body to sleep. + */ + setToSleep(): this; + + /** + * Wakes this Body if asleep. + */ + setAwake(): this; + + /** + * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). + * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. + */ + setSleepThreshold(value?: number): this; + + /** + * Enable sleep and wake events for this body. + * + * By default when a body goes to sleep, or wakes up, it will not emit any events. + * + * The events are emitted by the Matter World instance and can be listened to via + * the `SLEEP_START` and `SLEEP_END` events. + * @param start `true` if you want the sleep start event to be emitted for this body. + * @param end `true` if you want the sleep end event to be emitted for this body. + */ + setSleepEvents(start: boolean, end: boolean): this; + + /** + * Enables or disables the Sleep Start event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepStartEvent(value: boolean): this; + + /** + * Enables or disables the Sleep End event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepEndEvent(value: boolean): this; + + /** + * Changes the physics body to be either static `true` or dynamic `false`. + * @param value `true` to set the body as being static, or `false` to make it dynamic. + */ + setStatic(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Returns `true` if the body is static, otherwise `false` for a dynamic body. + */ + isStatic(): boolean; + + /** + * Setting fixed rotation sets the Body inertia to Infinity, which stops it + * from being able to rotate when forces are applied to it. + */ + setFixedRotation(): this; + + /** + * Sets the angular velocity of the body instantly. + * Position, angle, force etc. are unchanged. + * @param value The angular velocity. + */ + setAngularVelocity(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the horizontal velocity of the physics body. + * @param x The horizontal velocity value. + */ + setVelocityX(x: number): Phaser.GameObjects.GameObject; + + /** + * Sets vertical velocity of the physics body. + * @param y The vertical velocity value. + */ + setVelocityY(y: number): Phaser.GameObjects.GameObject; + + /** + * Sets both the horizontal and vertical velocity of the physics body. + * @param x The horizontal velocity value. + * @param y The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value. Default x. + */ + setVelocity(x: number, y?: number): Phaser.GameObjects.GameObject; + + } + + /** + * A wrapper around a Tile that provides access to a corresponding Matter body. A tile can only + * have one Matter body associated with it. You can either pass in an existing Matter body for + * the tile or allow the constructor to create the corresponding body for you. If the Tile has a + * collision group (defined in Tiled), those shapes will be used to create the body. If not, the + * tile's rectangle bounding box will be used. + * + * The corresponding body will be accessible on the Tile itself via Tile.physics.matterBody. + * + * Note: not all Tiled collision shapes are supported. See + * Phaser.Physics.Matter.TileBody#setFromTileCollision for more information. + */ + class TileBody implements Phaser.Physics.Matter.Components.Bounce, Phaser.Physics.Matter.Components.Collision, Phaser.Physics.Matter.Components.Friction, Phaser.Physics.Matter.Components.Gravity, Phaser.Physics.Matter.Components.Mass, Phaser.Physics.Matter.Components.Sensor, Phaser.Physics.Matter.Components.Sleep, Phaser.Physics.Matter.Components.Static { + /** + * + * @param world The Matter world instance this body belongs to. + * @param tile The target tile that should have a Matter body. + * @param options Options to be used when creating the Matter body. + */ + constructor(world: Phaser.Physics.Matter.World, tile: Phaser.Tilemaps.Tile, options?: Phaser.Types.Physics.Matter.MatterTileOptions); + + /** + * The tile object the body is associated with. + */ + tile: Phaser.Tilemaps.Tile; + + /** + * The Matter world the body exists within. + */ + world: Phaser.Physics.Matter.World; + + /** + * Sets the current body to a rectangle that matches the bounds of the tile. + * @param options Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. + */ + setFromTileRectangle(options?: Phaser.Types.Physics.Matter.MatterBodyTileOptions): Phaser.Physics.Matter.TileBody; + + /** + * Sets the current body from the collision group associated with the Tile. This is typically + * set up in Tiled's collision editor. + * + * Note: Matter doesn't support all shapes from Tiled. Rectangles and polygons are directly + * supported. Ellipses are converted into circle bodies. Polylines are treated as if they are + * closed polygons. If a tile has multiple shapes, a multi-part body will be created. Concave + * shapes are supported if poly-decomp library is included. Decomposition is not guaranteed to + * work for complex shapes (e.g. holes), so it's often best to manually decompose a concave + * polygon into multiple convex polygons yourself. + * @param options Options to be used when creating the Matter body. See MatterJS.Body for a list of what Matter accepts. + */ + setFromTileCollision(options?: Phaser.Types.Physics.Matter.MatterBodyTileOptions): Phaser.Physics.Matter.TileBody; + + /** + * Sets the current body to the given body. This will remove the previous body, if one already + * exists. + * @param body The new Matter body to use. + * @param addToWorld Whether or not to add the body to the Matter world. Default true. + */ + setBody(body: MatterJS.BodyType, addToWorld?: boolean): Phaser.Physics.Matter.TileBody; + + /** + * Removes the current body from the TileBody and from the Matter world + */ + removeBody(): Phaser.Physics.Matter.TileBody; + + /** + * Removes the current body from the tile and the world. + */ + destroy(): Phaser.Physics.Matter.TileBody; + + /** + * Sets the restitution on the physics object. + * @param 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)` + */ + setBounce(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the collision category of this Game Object's Matter Body. This number must be a power of two between 2^0 (= 1) and 2^31. + * Two bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision + * categories are included in their collision masks (see {@link #setCollidesWith}). + * @param value Unique category bitfield. + */ + setCollisionCategory(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets the collision group of this Game Object's Matter Body. If this is zero or two Matter Bodies have different values, + * they will collide according to the usual rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). + * If two Matter Bodies have the same positive value, they will always collide; if they have the same negative value, + * they will never collide. + * @param value Unique group index. + */ + setCollisionGroup(value: number): Phaser.GameObjects.GameObject; + + /** + * 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. + * @param categories A unique category bitfield, or an array of them. + */ + setCollidesWith(categories: number | number[]): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body starts colliding with another. + */ + setOnCollide(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke when this body stops colliding with another. + */ + setOnCollideEnd(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param callback The callback to invoke for the duration of this body colliding with another. + */ + setOnCollideActive(callback: Function): Phaser.GameObjects.GameObject; + + /** + * The callback is sent a reference to the other body, along with a `Phaser.Types.Physics.Matter.MatterCollisionData` object. + * + * This does not change the bodies collision category, group or filter. Those must be set in addition + * to the callback. + * @param body The body, or an array of bodies, to test for collisions with. + * @param callback The callback to invoke when this body collides with the given body or bodies. + */ + setOnCollideWith(body: MatterJS.Body | MatterJS.Body[], callback: Function): Phaser.GameObjects.GameObject; + + /** + * Sets new friction values for this Game Object's Matter Body. + * @param value The new friction of the body, between 0 and 1, where 0 allows the Body to slide indefinitely, while 1 allows it to stop almost immediately after a force is applied. + * @param air If provided, the new air resistance of the Body. The higher the value, the faster the Body will slow as it moves through space. 0 means the body has no air resistance. + * @param fstatic If provided, the new static friction of the Body. The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. 0 means the body will never "stick" when it is nearly stationary. + */ + setFriction(value: number, air?: number, fstatic?: number): Phaser.GameObjects.GameObject; + + /** + * Sets a new air resistance for this Game Object's Matter Body. + * A value of 0 means the Body will never slow as it moves through space. + * The higher the value, the faster a Body slows when moving through space. + * @param value The new air resistance for the Body. + */ + setFrictionAir(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets a new static friction for this Game Object's Matter Body. + * A value of 0 means the Body will never "stick" when it is nearly stationary. + * The higher the value (e.g. 10), the more force it will take to initially get the Body moving when it is nearly stationary. + * @param value The new static friction for the Body. + */ + setFrictionStatic(value: number): Phaser.GameObjects.GameObject; + + /** + * A togglable function for ignoring world gravity in real-time on the current body. + * @param value Set to true to ignore the effect of world gravity, or false to not ignore it. + */ + setIgnoreGravity(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Sets the mass of the Game Object's Matter Body. + * @param value The new mass of the body. + */ + setMass(value: number): Phaser.GameObjects.GameObject; + + /** + * Sets density of the body. + * @param value The new density of the body. + */ + setDensity(value: number): Phaser.GameObjects.GameObject; + + /** + * The body's center of mass. + * + * Calling this creates a new `Vector2 each time to avoid mutation. + * + * If you only need to read the value and won't change it, you can get it from `GameObject.body.centerOfMass`. + */ + readonly centerOfMass: Phaser.Math.Vector2; + + /** + * Set the body belonging to this Game Object to be a sensor. + * Sensors trigger collision events, but don't react with colliding body physically. + * @param value `true` to set the body as a sensor, or `false` to disable it. + */ + setSensor(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Is the body belonging to this Game Object a sensor or not? + */ + isSensor(): boolean; + + /** + * Sets this Body to sleep. + */ + setToSleep(): this; + + /** + * Wakes this Body if asleep. + */ + setAwake(): this; + + /** + * Sets the number of updates in which this body must have near-zero velocity before it is set as sleeping (if sleeping is enabled by the engine). + * @param value A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping. Default 60. + */ + setSleepThreshold(value?: number): this; + + /** + * Enable sleep and wake events for this body. + * + * By default when a body goes to sleep, or wakes up, it will not emit any events. + * + * The events are emitted by the Matter World instance and can be listened to via + * the `SLEEP_START` and `SLEEP_END` events. + * @param start `true` if you want the sleep start event to be emitted for this body. + * @param end `true` if you want the sleep end event to be emitted for this body. + */ + setSleepEvents(start: boolean, end: boolean): this; + + /** + * Enables or disables the Sleep Start event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepStartEvent(value: boolean): this; + + /** + * Enables or disables the Sleep End event for this body. + * @param value `true` to enable the sleep event, or `false` to disable it. + */ + setSleepEndEvent(value: boolean): this; + + /** + * Changes the physics body to be either static `true` or dynamic `false`. + * @param value `true` to set the body as being static, or `false` to make it dynamic. + */ + setStatic(value: boolean): Phaser.GameObjects.GameObject; + + /** + * Returns `true` if the body is static, otherwise `false` for a dynamic body. + */ + isStatic(): boolean; + + } + + /** + * Use PhysicsEditorParser.parseBody() to build a Matter body object, based on a physics data file + * created and exported with PhysicsEditor (https://www.codeandweb.com/physicseditor). + */ + namespace PhysicsEditorParser { + /** + * Parses a body element exported by PhysicsEditor. + * @param x The horizontal world location of the body. + * @param y The vertical world location of the body. + * @param config The body configuration and fixture (child body) definitions, as exported by PhysicsEditor. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + function parseBody(x: number, y: number, config: object, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; + + /** + * Parses an element of the "fixtures" list exported by PhysicsEditor + * @param fixtureConfig The fixture object to parse. + */ + function parseFixture(fixtureConfig: object): MatterJS.BodyType[]; + + /** + * Parses the "vertices" lists exported by PhysicsEditor. + * @param vertexSets The vertex lists to parse. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + function parseVertices(vertexSets: any[], options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType[]; + + } + + /** + * Creates a body using the supplied physics data, as provided by a JSON file. + * + * The data file should be loaded as JSON: + * + * ```javascript + * preload () + * { + * this.load.json('ninjas', 'assets/ninjas.json); + * } + * + * create () + * { + * const ninjaShapes = this.cache.json.get('ninjas'); + * + * this.matter.add.fromJSON(400, 300, ninjaShapes.shinobi); + * } + * ``` + * + * Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it. + * + * If you pas in an `options` object, any settings in there will override those in the config object. + * + * The structure of the JSON file is as follows: + * + * ```text + * { + * 'generator_info': // The name of the application that created the JSON data + * 'shapeName': { + * 'type': // The type of body + * 'label': // Optional body label + * 'vertices': // An array, or an array of arrays, containing the vertex data in x/y object pairs + * } + * } + * ``` + * + * At the time of writing, only the Phaser Physics Tracer App exports in this format. + */ + namespace PhysicsJSONParser { + /** + * Parses a body element from the given JSON data. + * @param x The horizontal world location of the body. + * @param y The vertical world location of the body. + * @param config The body configuration data. + * @param options An optional Body configuration object that is used to set initial Body properties on creation. + */ + function parseBody(x: number, y: number, config: object, options?: Phaser.Types.Physics.Matter.MatterBodyConfig): MatterJS.BodyType; + + } + + /** + * A Pointer Constraint is a special type of constraint that allows you to click + * and drag bodies in a Matter World. It monitors the active Pointers in a Scene, + * and when one is pressed down it checks to see if that hit any part of any active + * body in the world. If it did, and the body has input enabled, it will begin to + * drag it until either released, or you stop it via the `stopDrag` method. + * + * You can adjust the stiffness, length and other properties of the constraint via + * the `options` object on creation. + */ + class PointerConstraint { + /** + * + * @param scene A reference to the Scene to which this Pointer Constraint belongs. + * @param world A reference to the Matter World instance to which this Constraint belongs. + * @param options A Constraint configuration object. + */ + constructor(scene: Phaser.Scene, world: Phaser.Physics.Matter.World, options?: object); + + /** + * A reference to the Scene to which this Pointer Constraint belongs. + * This is the same Scene as the Matter World instance. + */ + scene: Phaser.Scene; + + /** + * A reference to the Matter World instance to which this Constraint belongs. + */ + world: Phaser.Physics.Matter.World; + + /** + * The Camera the Pointer was interacting with when the input + * down event was processed. + */ + camera: Phaser.Cameras.Scene2D.Camera; + + /** + * A reference to the Input Pointer that activated this Constraint. + * This is set in the `onDown` handler. + */ + pointer: Phaser.Input.Pointer; + + /** + * Is this Constraint active or not? + * + * An active constraint will be processed each update. An inactive one will be skipped. + * Use this to toggle a Pointer Constraint on and off. + */ + active: boolean; + + /** + * The internal transformed position. + */ + position: Phaser.Math.Vector2; + + /** + * The body that is currently being dragged, if any. + */ + body: MatterJS.BodyType; + + /** + * The part of the body that was clicked on to start the drag. + */ + part: MatterJS.BodyType; + + /** + * The native Matter Constraint that is used to attach to bodies. + */ + constraint: MatterJS.ConstraintType; + + /** + * A Pointer has been pressed down onto the Scene. + * + * If this Constraint doesn't have an active Pointer then a hit test is set to + * run against all active bodies in the world during the _next_ call to `update`. + * If a body is found, it is bound to this constraint and the drag begins. + * @param pointer A reference to the Pointer that was pressed. + */ + onDown(pointer: Phaser.Input.Pointer): void; + + /** + * A Pointer has been released from the Scene. If it was the one this constraint was using, it's cleared. + * @param pointer A reference to the Pointer that was pressed. + */ + onUp(pointer: Phaser.Input.Pointer): void; + + /** + * Scans all active bodies in the current Matter World to see if any of them + * are hit by the Pointer. The _first one_ found to hit is set as the active contraint + * body. + */ + getBody(): boolean; + + /** + * Scans the current body to determine if a part of it was clicked on. + * If a part is found the body is set as the `constraint.bodyB` property, + * as well as the `body` property of this class. The part is also set. + * @param body The Matter Body to check. + * @param position A translated hit test position. + */ + hitTestBody(body: MatterJS.BodyType, position: Phaser.Math.Vector2): boolean; + + /** + * Internal update handler. Called in the Matter BEFORE_UPDATE step. + */ + update(): void; + + /** + * Stops the Pointer Constraint from dragging the body any further. + * + * This is called automatically if the Pointer is released while actively + * dragging a body. Or, you can call it manually to release a body from a + * constraint without having to first release the pointer. + */ + stopDrag(): void; + + /** + * Destroys this Pointer Constraint instance and all of its references. + */ + destroy(): void; + + } + + /** + * The Matter World class is responsible for managing one single instance of a Matter Physics World for Phaser. + * + * Access this via `this.matter.world` from within a Scene. + * + * This class creates a Matter JS World Composite along with the Matter JS Engine during instantiation. It also + * handles delta timing, bounds, body and constraint creation and debug drawing. + * + * If you wish to access the Matter JS World object directly, see the `localWorld` property. + * If you wish to access the Matter Engine directly, see the `engine` property. + * + * This class is an Event Emitter and will proxy _all_ Matter JS events, as they are received. + */ + class World extends Phaser.Events.EventEmitter { + /** + * + * @param scene The Scene to which this Matter World instance belongs. + * @param config The Matter World configuration object. + */ + constructor(scene: Phaser.Scene, config: Phaser.Types.Physics.Matter.MatterWorldConfig); + + /** + * The Scene to which this Matter World instance belongs. + */ + scene: Phaser.Scene; + + /** + * An instance of the MatterJS Engine. + */ + engine: MatterJS.Engine; + + /** + * A `World` composite object that will contain all simulated bodies and constraints. + */ + localWorld: MatterJS.World; + + /** + * An object containing the 4 wall bodies that bound the physics world. + */ + walls: object; + + /** + * A flag that toggles if the world is enabled or not. + */ + enabled: boolean; + + /** + * The correction argument is 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. + */ + correction: number; + + /** + * This function is called every time the core game loop steps, which is bound to the + * Request Animation Frame frequency unless otherwise modified. + * + * The function is passed two values: `time` and `delta`, both of which come from the game step values. + * + * It must return a number. This number is used as the delta value passed to Matter.Engine.update. + * + * You can override this function with your own to define your own timestep. + * + * If you need to update the Engine multiple times in a single game step then call + * `World.update` as many times as required. Each call will trigger the `getDelta` function. + * If you wish to have full control over when the Engine updates then see the property `autoUpdate`. + * + * You can also adjust the number of iterations that Engine.update performs. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + */ + getDelta: Function; + + /** + * The Matter JS Runner Configuration object. + * + * This object is populated via the Matter Configuration object's `runner` property and is + * updated constantly during the game step. + */ + runner: Phaser.Types.Physics.Matter.MatterRunnerConfig; + + /** + * Automatically call Engine.update every time the game steps. + * If you disable this then you are responsible for calling `World.step` directly from your game. + * If you call `set60Hz` or `set30Hz` then `autoUpdate` is reset to `true`. + */ + autoUpdate: boolean; + + /** + * A flag that controls if the debug graphics will be drawn to or not. + */ + drawDebug: boolean; + + /** + * An instance of the Graphics object the debug bodies are drawn to, if enabled. + */ + debugGraphic: Phaser.GameObjects.Graphics; + + /** + * The debug configuration object. + * + * The values stored in this object are read from the Matter World Config `debug` property. + * + * When a new Body or Constraint is _added to the World_, they are given the values stored in this object, + * unless they have their own `render` object set that will override them. + * + * Note that while you can modify the values of properties in this object at run-time, it will not change + * any of the Matter objects _already added_. It will only impact objects newly added to the world, or one + * that is removed and then re-added at a later time. + */ + debugConfig: Phaser.Types.Physics.Matter.MatterDebugConfig; + + /** + * Sets the debug render style for the children of the given Matter Composite. + * + * Composites themselves do not render, but they can contain bodies, constraints and other composites that may do. + * So the children of this composite are passed to the `setBodyRenderStyle`, `setCompositeRenderStyle` and + * `setConstraintRenderStyle` methods accordingly. + * @param composite The Matter Composite to set the render style on. + */ + setCompositeRenderStyle(composite: MatterJS.CompositeType): this; + + /** + * Sets the debug render style for the given Matter Body. + * + * If you are using this on a Phaser Game Object, such as a Matter Sprite, then pass in the body property + * to this method, not the Game Object itself. + * + * If you wish to skip a parameter, so it retains its current value, pass `false` for it. + * + * If you wish to reset the Body render colors to the defaults found in the World Debug Config, then call + * this method with just the `body` parameter provided and no others. + * @param body The Matter Body to set the render style on. + * @param lineColor The line color. If `null` it will use the World Debug Config value. + * @param lineOpacity The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * @param lineThickness The line thickness. If `null` it will use the World Debug Config value. + * @param fillColor The fill color. If `null` it will use the World Debug Config value. + * @param fillOpacity The fill opacity, between 0 and 1. If `null` it will use the World Debug Config value. + */ + setBodyRenderStyle(body: MatterJS.BodyType, lineColor?: number, lineOpacity?: number, lineThickness?: number, fillColor?: number, fillOpacity?: number): this; + + /** + * Sets the debug render style for the given Matter Constraint. + * + * If you are using this on a Phaser Game Object, then pass in the body property + * to this method, not the Game Object itself. + * + * If you wish to skip a parameter, so it retains its current value, pass `false` for it. + * + * If you wish to reset the Constraint render colors to the defaults found in the World Debug Config, then call + * this method with just the `constraint` parameter provided and no others. + * @param constraint The Matter Constraint to set the render style on. + * @param lineColor The line color. If `null` it will use the World Debug Config value. + * @param lineOpacity The line opacity, between 0 and 1. If `null` it will use the World Debug Config value. + * @param lineThickness The line thickness. If `null` it will use the World Debug Config value. + * @param pinSize If this constraint is a pin, this sets the size of the pin circle. If `null` it will use the World Debug Config value. + * @param anchorColor The color used when rendering this constraints anchors. If `null` it will use the World Debug Config value. + * @param anchorSize The size of the anchor circle, if this constraint has anchors. If `null` it will use the World Debug Config value. + */ + setConstraintRenderStyle(constraint: MatterJS.ConstraintType, lineColor?: number, lineOpacity?: number, lineThickness?: number, pinSize?: number, anchorColor?: number, anchorSize?: number): this; + + /** + * This internal method acts as a proxy between all of the Matter JS events and then re-emits them + * via this class. + */ + setEventsProxy(): void; + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * @param x The x coordinate of the top-left corner of the bounds. Default 0. + * @param y The y coordinate of the top-left corner of the bounds. Default 0. + * @param width The width of the bounds. + * @param height The height of the bounds. + * @param thickness The thickness of each wall, in pixels. Default 64. + * @param left If true will create the left bounds wall. Default true. + * @param right If true will create the right bounds wall. Default true. + * @param top If true will create the top bounds wall. Default true. + * @param bottom If true will create the bottom bounds wall. Default true. + */ + setBounds(x?: number, y?: number, width?: number, height?: number, thickness?: number, left?: boolean, right?: boolean, top?: boolean, bottom?: boolean): Phaser.Physics.Matter.World; + + /** + * Updates the 4 rectangle bodies that were created, if `setBounds` was set in the Matter config, to use + * the new positions and sizes. This method is usually only called internally via the `setBounds` method. + * @param add `true` if the walls are being added or updated, `false` to remove them from the world. + * @param position Either `left`, `right`, `top` or `bottom`. Only optional if `add` is `false`. + * @param x The horizontal position to place the walls at. Only optional if `add` is `false`. + * @param y The vertical position to place the walls at. Only optional if `add` is `false`. + * @param width The width of the walls, in pixels. Only optional if `add` is `false`. + * @param height The height of the walls, in pixels. Only optional if `add` is `false`. + */ + updateWall(add: boolean, position?: string, x?: number, y?: number, width?: number, height?: number): void; + + /** + * Creates a Phaser.GameObjects.Graphics object that is used to render all of the debug bodies and joints to. + * + * This method is called automatically by the constructor, if debugging has been enabled. + * + * The created Graphics object is automatically added to the Scene at 0x0 and given a depth of `Number.MAX_VALUE`, + * so it renders above all else in the Scene. + * + * The Graphics object is assigned to the `debugGraphic` property of this class and `drawDebug` is enabled. + */ + createDebugGraphic(): Phaser.GameObjects.Graphics; + + /** + * Sets the world gravity and gravity scale to 0. + */ + disableGravity(): this; + + /** + * Sets the worlds gravity to the values given. + * + * Gravity effects all bodies in the world, unless they have the `ignoreGravity` flag set. + * @param x The world gravity x component. Default 0. + * @param y The world gravity y component. Default 1. + * @param scale The gravity scale factor. Default 0.001. + */ + setGravity(x?: number, y?: number, scale?: number): this; + + /** + * Creates a rectangle Matter body and adds it to the world. + * @param x The horizontal position of the body in the world. + * @param y The vertical position of the body in the world. + * @param width The width of the body. + * @param height The height of the body. + * @param options Optional Matter configuration object. + */ + create(x: number, y: number, width: number, height: number, options: object): MatterJS.BodyType; + + /** + * Adds a Matter JS object, or array of objects, to the world. + * + * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. + * + * Triggers `beforeAdd` and `afterAdd` events. + * @param object Can be single object, or an array, and can be a body, composite or constraint. + */ + add(object: object | object[]): this; + + /** + * Removes a Matter JS object, or array of objects, from the world. + * + * The objects should be valid Matter JS entities, such as a Body, Composite or Constraint. + * + * Triggers `beforeRemove` and `afterRemove` events. + * @param object Can be single object, or an array, and can be a body, composite or constraint. + * @param deep Optionally search the objects children and recursively remove those as well. Default false. + */ + remove(object: object | object[], deep?: boolean): this; + + /** + * Removes a Matter JS constraint, or array of constraints, from the world. + * + * Triggers `beforeRemove` and `afterRemove` events. + * @param constraint A Matter JS Constraint, or an array of constraints, to be removed. + * @param deep Optionally search the objects children and recursively remove those as well. Default false. + */ + removeConstraint(constraint: MatterJS.ConstraintType | MatterJS.ConstraintType[], deep?: boolean): this; + + /** + * Adds `MatterTileBody` instances for all the colliding tiles within the given tilemap layer. + * + * Set the appropriate tiles in your layer to collide before calling this method! + * @param tilemapLayer An array of tiles. + * @param options Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} + */ + convertTilemapLayer(tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, options?: object): this; + + /** + * Adds `MatterTileBody` instances for the given tiles. This adds bodies regardless of whether the + * tiles are set to collide or not. + * @param tiles An array of tiles. + * @param options Options to be passed to the MatterTileBody constructor. {@see Phaser.Physics.Matter.TileBody} + */ + convertTiles(tiles: Phaser.Tilemaps.Tile[], options?: object): this; + + /** + * Returns the next unique group index for which bodies will collide. + * If `isNonColliding` is `true`, returns the next unique group index for which bodies will not collide. + * @param isNonColliding If `true`, returns the next unique group index for which bodies will _not_ collide. Default false. + */ + nextGroup(isNonColliding?: boolean): number; + + /** + * Returns the next unique category bitfield (starting after the initial default category 0x0001). + * There are 32 available. + */ + nextCategory(): number; + + /** + * Pauses this Matter World instance and sets `enabled` to `false`. + * + * A paused world will not run any simulations for the duration it is paused. + */ + pause(): this; + + /** + * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. + */ + resume(): this; + + /** + * 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. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(time: number, delta: number): void; + + /** + * Manually advances the physics simulation by one iteration. + * + * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. + * If undefined they use the Matter defaults of 60Hz and no correction. + * + * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. + * + * It also ignores any custom `getDelta` functions, as you should be passing the delta + * value in to this call. + * + * You can adjust the number of iterations that Engine.update performs internally. + * Use the Scene Matter Physics config object to set the following properties: + * + * positionIterations (defaults to 6) + * velocityIterations (defaults to 4) + * constraintIterations (defaults to 2) + * + * Adjusting these values can help performance in certain situations, depending on the physics requirements + * of your game. + * @param delta The delta value. Default 16.666. + * @param correction Optional delta correction value. Default 1. + */ + step(delta?: number, correction?: number): void; + + /** + * Runs the Matter Engine.update at a fixed timestep of 60Hz. + */ + update60Hz(): number; + + /** + * Runs the Matter Engine.update at a fixed timestep of 30Hz. + */ + update30Hz(): number; + + /** + * Returns `true` if the given body can be found within the World. + * @param body The Matter Body, or Game Object, to search for within the world. + */ + has(body: MatterJS.Body | Phaser.GameObjects.GameObject): MatterJS.BodyType[]; + + /** + * Returns all the bodies in the Matter World, including all bodies in children, recursively. + */ + getAllBodies(): MatterJS.BodyType[]; + + /** + * Returns all the constraints in the Matter World, including all constraints in children, recursively. + */ + getAllConstraints(): MatterJS.ConstraintType[]; + + /** + * Returns all the composites in the Matter World, including all composites in children, recursively. + */ + getAllComposites(): MatterJS.CompositeType[]; + + /** + * Renders the Engine Broadphase Controller Grid to the given Graphics instance. + * + * The debug renderer calls this method if the `showBroadphase` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * @param grid The Matter Grid to be rendered. + * @param graphics The Graphics object to render to. + * @param lineColor The line color. + * @param lineOpacity The line opacity, between 0 and 1. + */ + renderGrid(grid: MatterJS.Grid, graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number): this; + + /** + * Renders the list of Pair separations to the given Graphics instance. + * + * The debug renderer calls this method if the `showSeparations` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * @param pairs An array of Matter Pairs to be rendered. + * @param graphics The Graphics object to render to. + * @param lineColor The line color. + */ + renderSeparations(pairs: MatterJS.Pair[], graphics: Phaser.GameObjects.Graphics, lineColor: number): this; + + /** + * Renders the list of collision points and normals to the given Graphics instance. + * + * The debug renderer calls this method if the `showCollisions` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render the Grid to your own Graphics instance. + * @param pairs An array of Matter Pairs to be rendered. + * @param graphics The Graphics object to render to. + * @param lineColor The line color. + */ + renderCollisions(pairs: MatterJS.Pair[], graphics: Phaser.GameObjects.Graphics, lineColor: number): this; + + /** + * Renders the bounds of an array of Bodies to the given Graphics instance. + * + * If the body is a compound body, it will render the bounds for the parent compound. + * + * The debug renderer calls this method if the `showBounds` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * @param bodies An array of bodies from the localWorld. + * @param graphics The Graphics object to render to. + * @param lineColor The line color. + * @param lineOpacity The line opacity, between 0 and 1. + */ + renderBodyBounds(bodies: any[], graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number): void; + + /** + * Renders either all axes, or a single axis indicator, for an array of Bodies, to the given Graphics instance. + * + * The debug renderer calls this method if the `showAxes` or `showAngleIndicator` config values are set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * @param bodies An array of bodies from the localWorld. + * @param graphics The Graphics object to render to. + * @param showAxes If `true` it will render all body axes. If `false` it will render a single axis indicator. + * @param lineColor The line color. + * @param lineOpacity The line opacity, between 0 and 1. + */ + renderBodyAxes(bodies: any[], graphics: Phaser.GameObjects.Graphics, showAxes: boolean, lineColor: number, lineOpacity: number): void; + + /** + * Renders a velocity indicator for an array of Bodies, to the given Graphics instance. + * + * The debug renderer calls this method if the `showVelocity` config value is set. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render bounds to your own Graphics instance. + * @param bodies An array of bodies from the localWorld. + * @param graphics The Graphics object to render to. + * @param lineColor The line color. + * @param lineOpacity The line opacity, between 0 and 1. + * @param lineThickness The line thickness. + */ + renderBodyVelocity(bodies: any[], graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number, lineThickness: number): void; + + /** + * Renders a single Matter Body to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Body to your own Graphics instance. + * + * If you don't wish to render a line around the body, set the `lineColor` parameter to `null`. + * Equally, if you don't wish to render a fill, set the `fillColor` parameter to `null`. + * @param body The Matter Body to be rendered. + * @param graphics The Graphics object to render to. + * @param showInternalEdges Render internal edges of the polygon? + * @param lineColor The line color. + * @param lineOpacity The line opacity, between 0 and 1. + * @param lineThickness The line thickness. Default 1. + * @param fillColor The fill color. + * @param fillOpacity The fill opacity, between 0 and 1. + */ + renderBody(body: MatterJS.BodyType, graphics: Phaser.GameObjects.Graphics, showInternalEdges: boolean, lineColor?: number, lineOpacity?: number, lineThickness?: number, fillColor?: number, fillOpacity?: number): this; + + /** + * Renders the Convex Hull for a single Matter Body to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Body hull to your own Graphics instance. + * @param body The Matter Body to be rendered. + * @param graphics The Graphics object to render to. + * @param hullColor The color used to render the hull. + * @param lineThickness The hull line thickness. Default 1. + */ + renderConvexHull(body: MatterJS.BodyType, graphics: Phaser.GameObjects.Graphics, hullColor: number, lineThickness?: number): this; + + /** + * Renders a single Matter Constraint, such as a Pin or a Spring, to the given Phaser Graphics Game Object. + * + * This method is used internally by the Matter Debug Renderer, but is also exposed publically should + * you wish to render a Constraint to your own Graphics instance. + * @param constraint The Matter Constraint to render. + * @param graphics The Graphics object to render to. + * @param lineColor The line color. + * @param lineOpacity The line opacity, between 0 and 1. + * @param lineThickness The line thickness. + * @param pinSize If this constraint is a pin, this sets the size of the pin circle. + * @param anchorColor The color used when rendering this constraints anchors. Set to `null` to not render anchors. + * @param anchorSize The size of the anchor circle, if this constraint has anchors and is rendering them. + */ + renderConstraint(constraint: MatterJS.ConstraintType, graphics: Phaser.GameObjects.Graphics, lineColor: number, lineOpacity: number, lineThickness: number, pinSize: number, anchorColor: number, anchorSize: number): this; + + /** + * Resets the internal collision IDs that Matter.JS uses for Body collision groups. + * + * You should call this before destroying your game if you need to restart the game + * again on the same page, without first reloading the page. Or, if you wish to + * consistently destroy a Scene that contains Matter.js and then run it again + * later in the same game. + */ + resetCollisionIDs(): void; + + /** + * Will remove all Matter physics event listeners and clear the matter physics world, + * engine and any debug graphics, if any. + */ + shutdown(): void; + + /** + * Will remove all Matter physics event listeners and clear the matter physics world, + * engine and any debug graphics, if any. + * + * After destroying the world it cannot be re-used again. + */ + destroy(): void; + + } + + } + + } + + namespace Plugins { + /** + * A Global Plugin is installed just once into the Game owned Plugin Manager. + * It can listen for Game events and respond to them. + */ + class BasePlugin { + /** + * + * @param pluginManager A reference to the Plugin Manager. + */ + constructor(pluginManager: Phaser.Plugins.PluginManager); + + /** + * A handy reference to the Plugin Manager that is responsible for this plugin. + * Can be used as a route to gain access to game systems and events. + */ + protected pluginManager: Phaser.Plugins.PluginManager; + + /** + * A reference to the Game instance this plugin is running under. + */ + protected game: Phaser.Game; + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is first instantiated. + * It will never be called again on this instance. + * In here you can set-up whatever you need for this plugin to run. + * If a plugin is set to automatically start then `BasePlugin.start` will be called immediately after this. + * On a Scene Plugin, this method is never called. Use {@link Phaser.Plugins.ScenePlugin#boot} instead. + * @param data A value specified by the user, if any, from the `data` property of the plugin's configuration object (if started at game boot) or passed in the PluginManager's `install` method (if started manually). + */ + init(data?: any): void; + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is started. + * If a plugin is stopped, and then started again, this will get called again. + * Typically called immediately after `BasePlugin.init`. + * On a Scene Plugin, this method is never called. + */ + start(): void; + + /** + * The PluginManager calls this method on a Global Plugin when the plugin is stopped. + * The game code has requested that your plugin stop doing whatever it does. + * It is now considered as 'inactive' by the PluginManager. + * Handle that process here (i.e. stop listening for events, etc) + * If the plugin is started again then `BasePlugin.start` will be called again. + * On a Scene Plugin, this method is never called. + */ + stop(): void; + + /** + * Game instance has been destroyed. + * You must release everything in here, all references, all objects, free it all up. + */ + destroy(): void; + + } + + type DefaultPlugins = { + /** + * These are the Global Managers that are created by the Phaser.Game instance. + */ + Global: any[]; + /** + * These are the core plugins that are installed into every Scene.Systems instance, no matter what. + */ + CoreScene: any[]; + /** + * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. + */ + DefaultScene: any[]; + }; + + /** + * These are the Global Managers that are created by the Phaser.Game instance. + * They are referenced from Scene.Systems so that plugins can use them. + */ + var Global: any[]; + + /** + * These are the core plugins that are installed into every Scene.Systems instance, no matter what. + * They are optionally exposed in the Scene as well (see the InjectionMap for details) + * + * They are created in the order in which they appear in this array and EventEmitter is always first. + */ + var CoreScene: any[]; + + /** + * These plugins are created in Scene.Systems in addition to the CoreScenePlugins. + * + * You can elect not to have these plugins by either creating a DefaultPlugins object as part + * of the Game Config, by creating a Plugins object as part of a Scene Config, or by modifying this array + * and building your own bundle. + * + * They are optionally exposed in the Scene as well (see the InjectionMap for details) + * + * They are always created in the order in which they appear in the array. + */ + var DefaultScene: any[]; + + namespace PluginCache { + /** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * @param key A reference used to get this plugin from the plugin cache. + * @param plugin The plugin to be stored. Should be the core object, not instantiated. + * @param mapping If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param custom Core Scene plugin or a Custom Scene plugin? Default false. + */ + function register(key: string, plugin: Function, mapping: string, custom?: boolean): void; + + /** + * Stores a custom plugin in the global plugin cache. + * The key must be unique, within the scope of the cache. + * @param key A reference used to get this plugin from the plugin cache. + * @param plugin The plugin to be stored. Should be the core object, not instantiated. + * @param mapping If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param data A value to be passed to the plugin's `init` method. + */ + function registerCustom(key: string, plugin: Function, mapping: string, data: any): void; + + /** + * Checks if the given key is already being used in the core plugin cache. + * @param key The key to check for. + */ + function hasCore(key: string): boolean; + + /** + * Checks if the given key is already being used in the custom plugin cache. + * @param key The key to check for. + */ + function hasCustom(key: string): boolean; + + /** + * Returns the core plugin object from the cache based on the given key. + * @param key The key of the core plugin to get. + */ + function getCore(key: string): Phaser.Types.Plugins.CorePluginContainer; + + /** + * Returns the custom plugin object from the cache based on the given key. + * @param key The key of the custom plugin to get. + */ + function getCustom(key: string): Phaser.Types.Plugins.CustomPluginContainer; + + /** + * Returns an object from the custom cache based on the given key that can be instantiated. + * @param key The key of the custom plugin to get. + */ + function getCustomClass(key: string): Function; + + /** + * Removes a core plugin based on the given key. + * @param key The key of the core plugin to remove. + */ + function remove(key: string): void; + + /** + * Removes a custom plugin based on the given key. + * @param key The key of the custom plugin to remove. + */ + function removeCustom(key: string): void; + + /** + * Removes all Core Plugins. + * + * This includes all of the internal system plugins that Phaser needs, like the Input Plugin and Loader Plugin. + * So be sure you only call this if you do not wish to run Phaser again. + */ + function destroyCorePlugins(): void; + + /** + * Removes all Custom Plugins. + */ + function destroyCustomPlugins(): void; + + } + + /** + * The PluginManager is responsible for installing and adding plugins to Phaser. + * + * It is a global system and therefore belongs to the Game instance, not a specific Scene. + * + * It works in conjunction with the PluginCache. Core internal plugins automatically register themselves + * with the Cache, but it's the Plugin Manager that is responsible for injecting them into the Scenes. + * + * There are two types of plugin: + * + * 1. A Global Plugin + * 2. A Scene Plugin + * + * A Global Plugin is a plugin that lives within the Plugin Manager rather than a Scene. You can get + * access to it by calling `PluginManager.get` and providing a key. Any Scene that requests a plugin in + * this way will all get access to the same plugin instance, allowing you to use a single plugin across + * multiple Scenes. + * + * A Scene Plugin is a plugin dedicated to running within a Scene. These are different to Global Plugins + * in that their instances do not live within the Plugin Manager, but within the Scene Systems class instead. + * And that every Scene created is given its own unique instance of a Scene Plugin. Examples of core Scene + * Plugins include the Input Plugin, the Tween Plugin and the physics Plugins. + * + * You can add a plugin to Phaser in three different ways: + * + * 1. Preload it + * 2. Include it in your source code and install it via the Game Config + * 3. Include it in your source code and install it within a Scene + * + * For examples of all of these approaches please see the Phaser 3 Examples Repo `plugins` folder. + * + * For information on creating your own plugin please see the Phaser 3 Plugin Template. + */ + class PluginManager { + /** + * + * @param game The game instance that owns this Plugin Manager. + */ + constructor(game: Phaser.Game); + + /** + * The game instance that owns this Plugin Manager. + */ + game: Phaser.Game; + + /** + * The global plugins currently running and managed by this Plugin Manager. + * A plugin must have been started at least once in order to appear in this list. + */ + plugins: Phaser.Types.Plugins.GlobalPlugin[]; + + /** + * A list of plugin keys that should be installed into Scenes as well as the Core Plugins. + */ + scenePlugins: string[]; + + /** + * Run once the game has booted and installs all of the plugins configured in the Game Config. + */ + protected boot(): void; + + /** + * Called by the Scene Systems class. Tells the plugin manager to install all Scene plugins into it. + * + * First it will install global references, i.e. references from the Game systems into the Scene Systems (and Scene if mapped.) + * Then it will install Core Scene Plugins followed by Scene Plugins registered with the PluginManager. + * Finally it will install any references to Global Plugins that have a Scene mapping property into the Scene itself. + * @param sys The Scene Systems class to install all the plugins in to. + * @param globalPlugins An array of global plugins to install. + * @param scenePlugins An array of scene plugins to install. + */ + protected addToScene(sys: Phaser.Scenes.Systems, globalPlugins: any[], scenePlugins: any[]): void; + + /** + * Called by the Scene Systems class. Returns a list of plugins to be installed. + */ + protected getDefaultScenePlugins(): string[]; + + /** + * Installs a new Scene Plugin into the Plugin Manager and optionally adds it + * to the given Scene as well. A Scene Plugin added to the manager in this way + * will be automatically installed into all new Scenes using the key and mapping given. + * + * The `key` property is what the plugin is injected into Scene.Systems as. + * The `mapping` property is optional, and if specified is what the plugin is installed into + * the Scene as. For example: + * + * ```javascript + * this.plugins.installScenePlugin('powerupsPlugin', pluginCode, 'powerups'); + * + * // and from within the scene: + * this.sys.powerupsPlugin; // key value + * this.powerups; // mapping value + * ``` + * + * This method is called automatically by Phaser if you install your plugins using either the + * Game Configuration object, or by preloading them via the Loader. + * @param key The property key that will be used to add this plugin to Scene.Systems. + * @param plugin The plugin code. This should be the non-instantiated version. + * @param mapping If this plugin is injected into the Phaser.Scene class, this is the property key to use. + * @param addToScene Optionally automatically add this plugin to the given Scene. + * @param fromLoader Is this being called by the Loader? Default false. + */ + installScenePlugin(key: string, plugin: Function, mapping?: string, addToScene?: Phaser.Scene, fromLoader?: boolean): void; + + /** + * Installs a new Global Plugin into the Plugin Manager and optionally starts it running. + * A global plugin belongs to the Plugin Manager, rather than a specific Scene, and can be accessed + * and used by all Scenes in your game. + * + * The `key` property is what you use to access this plugin from the Plugin Manager. + * + * ```javascript + * this.plugins.install('powerupsPlugin', pluginCode); + * + * // and from within the scene: + * this.plugins.get('powerupsPlugin'); + * ``` + * + * This method is called automatically by Phaser if you install your plugins using either the + * Game Configuration object, or by preloading them via the Loader. + * + * The same plugin can be installed multiple times into the Plugin Manager by simply giving each + * instance its own unique key. + * @param key The unique handle given to this plugin within the Plugin Manager. + * @param plugin The plugin code. This should be the non-instantiated version. + * @param start Automatically start the plugin running? This is always `true` if you provide a mapping value. Default false. + * @param mapping If this plugin is injected into the Phaser.Scene class, this is the property key to use. + * @param data A value passed to the plugin's `init` method. + */ + install(key: string, plugin: Function, start?: boolean, mapping?: string, data?: any): Phaser.Plugins.BasePlugin; + + /** + * Gets an index of a global plugin based on the given key. + * @param key The unique plugin key. + */ + protected getIndex(key: string): integer; + + /** + * Gets a global plugin based on the given key. + * @param key The unique plugin key. + */ + protected getEntry(key: string): Phaser.Types.Plugins.GlobalPlugin; + + /** + * Checks if the given global plugin, based on its key, is active or not. + * @param key The unique plugin key. + */ + isActive(key: string): boolean; + + /** + * Starts a global plugin running. + * + * If the plugin was previously active then calling `start` will reset it to an active state and then + * call its `start` method. + * + * If the plugin has never been run before a new instance of it will be created within the Plugin Manager, + * its active state set and then both of its `init` and `start` methods called, in that order. + * + * If the plugin is already running under the given key then nothing happens. + * @param key The key of the plugin to start. + * @param runAs Run the plugin under a new key. This allows you to run one plugin multiple times. + */ + start(key: string, runAs?: string): Phaser.Plugins.BasePlugin; + + /** + * Stops a global plugin from running. + * + * If the plugin is active then its active state will be set to false and the plugins `stop` method + * will be called. + * + * If the plugin is not already running, nothing will happen. + * @param key The key of the plugin to stop. + */ + stop(key: string): Phaser.Plugins.PluginManager; + + /** + * 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. + * @param key The key of the plugin to get. + * @param autoStart Automatically start a new instance of the plugin if found in the cache, but not actively running. Default true. + */ + get(key: string, autoStart?: boolean): Phaser.Plugins.BasePlugin | Function; + + /** + * Returns the plugin class from the cache. + * Used internally by the Plugin Manager. + * @param key The key of the plugin to get. + */ + getClass(key: string): Phaser.Plugins.BasePlugin; + + /** + * Removes a global plugin from the Plugin Manager and Plugin Cache. + * + * It is up to you to remove all references to this plugin that you may hold within your game code. + * @param key The key of the plugin to remove. + */ + removeGlobalPlugin(key: string): void; + + /** + * Removes a scene plugin from the Plugin Manager and Plugin Cache. + * + * This will not remove the plugin from any active Scenes that are already using it. + * + * It is up to you to remove all references to this plugin that you may hold within your game code. + * @param key The key of the plugin to remove. + */ + removeScenePlugin(key: string): void; + + /** + * Registers a new type of Game Object with the global Game Object Factory and / or Creator. + * This is usually called from within your Plugin code and is a helpful short-cut for creating + * new Game Objects. + * + * The key is the property that will be injected into the factories and used to create the + * Game Object. For example: + * + * ```javascript + * this.plugins.registerGameObject('clown', clownFactoryCallback, clownCreatorCallback); + * // later in your game code: + * this.add.clown(); + * this.make.clown(); + * ``` + * + * The callbacks are what are called when the factories try to create a Game Object + * matching the given key. It's important to understand that the callbacks are invoked within + * the context of the GameObjectFactory. In this 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. + * + * See the GameObjectFactory and GameObjectCreator classes for more details. + * Any public property or method listed is available from your callbacks under `this`. + * @param key The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. + * @param factoryCallback The callback to invoke when the Game Object Factory is called. + * @param creatorCallback The callback to invoke when the Game Object Creator is called. + */ + registerGameObject(key: string, factoryCallback?: Function, creatorCallback?: Function): void; + + /** + * Removes a previously registered Game Object from the global Game Object Factory and / or Creator. + * This is usually called from within your Plugin destruction code to help clean-up after your plugin has been removed. + * @param key The key of the Game Object to be removed from the factories. + * @param removeFromFactory Should the Game Object be removed from the Game Object Factory? Default true. + * @param removeFromCreator Should the Game Object be removed from the Game Object Creator? Default true. + */ + removeGameObject(key: string, removeFromFactory?: boolean, removeFromCreator?: boolean): void; + + /** + * Registers a new file type with the global File Types Manager, making it available to all Loader + * Plugins created after this. + * + * This is usually called from within your Plugin code and is a helpful short-cut for creating + * new loader file types. + * + * The key is the property that will be injected into the Loader Plugin and used to load the + * files. For example: + * + * ```javascript + * this.plugins.registerFileType('wad', doomWadLoaderCallback); + * // later in your preload code: + * this.load.wad(); + * ``` + * + * The callback is what is called when the loader tries to load a file matching the given key. + * It's important to understand that the callback is invoked within + * the context of the LoaderPlugin. In this context there are several properties / methods available + * to use: + * + * this.addFile - A method to add the new file to the load queue. + * this.scene - The Scene that owns the Loader Plugin instance. + * + * See the LoaderPlugin class for more details. Any public property or method listed is available from + * your callback under `this`. + * @param key The key of the Game Object that the given callbacks will create, i.e. `image`, `sprite`. + * @param callback The callback to invoke when the Game Object Factory is called. + * @param addToScene Optionally add this file type into the Loader Plugin owned by the given Scene. + */ + registerFileType(key: string, callback: Function, addToScene?: Phaser.Scene): void; + + /** + * Destroys this Plugin Manager and all associated plugins. + * It will iterate all plugins found and call their `destroy` methods. + * + * The PluginCache will remove all custom plugins. + */ + destroy(): void; + + } + + /** + * A Scene Level Plugin is installed into every Scene and belongs to that Scene. + * It can listen for Scene events and respond to them. + * It can map itself to a Scene property, or into the Scene Systems, or both. + */ + class ScenePlugin extends Phaser.Plugins.BasePlugin { + /** + * + * @param scene A reference to the Scene that has installed this plugin. + * @param pluginManager A reference to the Plugin Manager. + */ + constructor(scene: Phaser.Scene, pluginManager: Phaser.Plugins.PluginManager); + + /** + * A reference to the Scene that has installed this plugin. + * Only set if it's a Scene Plugin, otherwise `null`. + * This property is only set when the plugin is instantiated and added to the Scene, not before. + * You can use it during the `boot` method. + */ + protected scene: Phaser.Scene; + + /** + * A reference to the Scene Systems of the Scene that has installed this plugin. + * Only set if it's a Scene Plugin, otherwise `null`. + * This property is only set when the plugin is instantiated and added to the Scene, not before. + * You can use it during the `boot` method. + */ + protected systems: Phaser.Scenes.Systems; + + /** + * This method is called when the Scene boots. It is only ever called once. + * + * By this point the plugin properties `scene` and `systems` will have already been set. + * + * In here you can listen for {@link Phaser.Scenes.Events Scene events} and set-up whatever you need for this plugin to run. + * Here are the Scene events you can listen to: + * + * - start + * - ready + * - preupdate + * - update + * - postupdate + * - resize + * - pause + * - resume + * - sleep + * - wake + * - transitioninit + * - transitionstart + * - transitioncomplete + * - transitionout + * - shutdown + * - destroy + * + * At the very least you should offer a destroy handler for when the Scene closes down, i.e: + * + * ```javascript + * var eventEmitter = this.systems.events; + * eventEmitter.once('destroy', this.sceneDestroy, this); + * ``` + */ + boot(): void; + + /** + * Game instance has been destroyed. + * + * You must release everything in here, all references, all objects, free it all up. + */ + destroy(): void; + + } + + } + + /** + * Phaser Blend Modes. + */ + enum BlendModes { + /** + * Skips the Blend Mode check in the renderer. + */ + SKIP_CHECK, + /** + * Normal blend mode. For Canvas and WebGL. + * This is the default setting and draws new shapes on top of the existing canvas content. + */ + NORMAL, + /** + * Add blend mode. For Canvas and WebGL. + * Where both shapes overlap the color is determined by adding color values. + */ + ADD, + /** + * Multiply blend mode. For Canvas and WebGL. + * The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result. + */ + MULTIPLY, + /** + * Screen blend mode. For Canvas and WebGL. + * The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply) + */ + SCREEN, + /** + * Overlay blend mode. For Canvas only. + * A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter. + */ + OVERLAY, + /** + * Darken blend mode. For Canvas only. + * Retains the darkest pixels of both layers. + */ + DARKEN, + /** + * Lighten blend mode. For Canvas only. + * Retains the lightest pixels of both layers. + */ + LIGHTEN, + /** + * Color Dodge blend mode. For Canvas only. + * Divides the bottom layer by the inverted top layer. + */ + COLOR_DODGE, + /** + * Color Burn blend mode. For Canvas only. + * Divides the inverted bottom layer by the top layer, and then inverts the result. + */ + COLOR_BURN, + /** + * Hard Light blend mode. For Canvas only. + * A combination of multiply and screen like overlay, but with top and bottom layer swapped. + */ + HARD_LIGHT, + /** + * Soft Light blend mode. For Canvas only. + * A softer version of hard-light. Pure black or white does not result in pure black or white. + */ + SOFT_LIGHT, + /** + * Difference blend mode. For Canvas only. + * Subtracts the bottom layer from the top layer or the other way round to always get a positive value. + */ + DIFFERENCE, + /** + * Exclusion blend mode. For Canvas only. + * Like difference, but with lower contrast. + */ + EXCLUSION, + /** + * Hue blend mode. For Canvas only. + * Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer. + */ + HUE, + /** + * Saturation blend mode. For Canvas only. + * Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer. + */ + SATURATION, + /** + * Color blend mode. For Canvas only. + * Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer. + */ + COLOR, + /** + * Luminosity blend mode. For Canvas only. + * Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer. + */ + LUMINOSITY, + /** + * Alpha erase blend mode. For Canvas and WebGL. + */ + ERASE, + /** + * Source-in blend mode. For Canvas only. + * The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent. + */ + SOURCE_IN, + /** + * Source-out blend mode. For Canvas only. + * The new shape is drawn where it doesn't overlap the existing canvas content. + */ + SOURCE_OUT, + /** + * Source-out blend mode. For Canvas only. + * The new shape is only drawn where it overlaps the existing canvas content. + */ + SOURCE_ATOP, + /** + * Destination-over blend mode. For Canvas only. + * New shapes are drawn behind the existing canvas content. + */ + DESTINATION_OVER, + /** + * Destination-in blend mode. For Canvas only. + * The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent. + */ + DESTINATION_IN, + /** + * Destination-out blend mode. For Canvas only. + * The existing content is kept where it doesn't overlap the new shape. + */ + DESTINATION_OUT, + /** + * Destination-out blend mode. For Canvas only. + * The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content. + */ + DESTINATION_ATOP, + /** + * Lighten blend mode. For Canvas only. + * Where both shapes overlap the color is determined by adding color values. + */ + LIGHTER, + /** + * Copy blend mode. For Canvas only. + * Only the new shape is shown. + */ + COPY, + /** + * Xor blend mode. For Canvas only. + * Shapes are made transparent where both overlap and drawn normal everywhere else. + */ + XOR, + } + + namespace Renderer { + namespace Canvas { + /** + * The Canvas Renderer is responsible for managing 2D canvas rendering contexts, including the one used by the Game's canvas. It tracks the internal state of a given context and can renderer textured Game Objects to it, taking into account alpha, blending, and scaling. + */ + class CanvasRenderer { + /** + * + * @param game The Phaser Game instance that owns this renderer. + */ + constructor(game: Phaser.Game); + + /** + * The Phaser Game instance that owns this renderer. + */ + game: Phaser.Game; + + /** + * A constant which allows the renderer to be easily identified as a Canvas Renderer. + */ + type: integer; + + /** + * The total number of Game Objects which were rendered in a frame. + */ + drawCount: number; + + /** + * The width of the canvas being rendered to. + */ + width: integer; + + /** + * The height of the canvas being rendered to. + */ + height: integer; + + /** + * The local configuration settings of the CanvasRenderer. + */ + config: object; + + /** + * The canvas element which the Game uses. + */ + gameCanvas: HTMLCanvasElement; + + /** + * The canvas context used to render all Cameras in all Scenes during the game loop. + */ + gameContext: CanvasRenderingContext2D; + + /** + * The canvas context currently used by the CanvasRenderer for all rendering operations. + */ + currentContext: CanvasRenderingContext2D; + + /** + * Should the Canvas use Image Smoothing or not when drawing Sprites? + */ + antialias: boolean; + + /** + * The blend modes supported by the Canvas Renderer. + * + * This object maps the {@link Phaser.BlendModes} to canvas compositing operations. + */ + blendModes: any[]; + + /** + * Details about the currently scheduled snapshot. + * + * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. + */ + snapshotState: Phaser.Types.Renderer.Snapshot.SnapshotState; + + /** + * Prepares the game canvas for rendering. + */ + init(): void; + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * @param gameSize The default Game Size object. This is the un-modified game dimensions. + * @param baseSize The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + * @param displaySize The display Size object. The size of the canvas style width / height attributes. + * @param resolution The Scale Manager resolution setting. + */ + onResize(gameSize: Phaser.Structs.Size, baseSize: Phaser.Structs.Size, displaySize: Phaser.Structs.Size, resolution?: number): void; + + /** + * Resize the main game canvas. + * @param width The new width of the renderer. + * @param height The new height of the renderer. + */ + resize(width?: number, height?: number): void; + + /** + * Resets the transformation matrix of the current context to the identity matrix, thus resetting any transformation. + */ + resetTransform(): void; + + /** + * Sets the blend mode (compositing operation) of the current context. + * @param blendMode The new blend mode which should be used. + */ + setBlendMode(blendMode: string): this; + + /** + * Changes the Canvas Rendering Context that all draw operations are performed against. + * @param ctx The new Canvas Rendering Context to draw everything to. Leave empty to reset to the Game Canvas. + */ + setContext(ctx?: CanvasRenderingContext2D): this; + + /** + * Sets the global alpha of the current context. + * @param alpha The new alpha to use, where 0 is fully transparent and 1 is fully opaque. + */ + setAlpha(alpha: number): this; + + /** + * Called at the start of the render loop. + */ + preRender(): void; + + /** + * Renders the Scene to the given Camera. + * @param scene The Scene to render. + * @param children The Game Objects within the Scene to be rendered. + * @param interpolationPercentage The interpolation percentage to apply. Currently unused. + * @param camera The Scene Camera to render with. + */ + render(scene: Phaser.Scene, children: Phaser.GameObjects.DisplayList, interpolationPercentage: number, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * Restores the game context's global settings and takes a snapshot if one is scheduled. + * + * The post-render step happens after all Cameras in all Scenes have been rendered. + */ + postRender(): void; + + /** + * Takes a snapshot of the given area of the given canvas. + * + * Unlike the other snapshot methods, this one is processed immediately and doesn't wait for the next render. + * + * Snapshots work by creating an Image object from the canvas data, this is a blocking process, which gets + * more expensive the larger the canvas size gets, so please be careful how you employ this in your game. + * @param canvas The canvas to grab from. + * @param callback The Function to invoke after the snapshot image is created. + * @param getPixel Grab a single pixel as a Color object, or an area as an Image object? Default false. + * @param x The x coordinate to grab from. Default 0. + * @param y The y coordinate to grab from. Default 0. + * @param width The width of the area to grab. Default canvas.width. + * @param height The height of the area to grab. Default canvas.height. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshotCanvas(canvas: HTMLCanvasElement, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, getPixel?: boolean, x?: integer, y?: integer, width?: integer, height?: integer, type?: string, encoderOptions?: number): this; + + /** + * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. + * + * To capture a specific area see the `snapshotArea` 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 creating an Image object from the canvas data, this is a blocking process, which gets + * more expensive the larger the canvas size gets, so please be careful how you employ this in your game. + * @param callback The Function to invoke after the snapshot image is created. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshot(callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; + + /** + * 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 creating an Image object from the canvas data, this is a blocking process, which gets + * more expensive the larger the canvas size gets, so please be careful how you employ this in your game. + * @param x The x coordinate to grab from. + * @param y The y coordinate to grab from. + * @param width The width of the area to grab. + * @param height The height of the area to grab. + * @param callback The Function to invoke after the snapshot image is created. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshotArea(x: integer, y: integer, width: integer, height: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; + + /** + * 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. + * @param x The x coordinate of the pixel to get. + * @param y The y coordinate of the pixel to get. + * @param callback The Function to invoke after the snapshot pixel data is extracted. + */ + snapshotPixel(x: integer, y: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback): this; + + /** + * Takes a Sprite Game Object, or any object that extends it, and draws it to the current context. + * @param sprite The texture based Game Object to draw. + * @param frame The frame to draw, doesn't have to be that owned by the Game Object. + * @param camera The Camera to use for the rendering transform. + * @param parentTransformMatrix The transform matrix of the parent container, if set. + */ + batchSprite(sprite: Phaser.GameObjects.GameObject, frame: Phaser.Textures.Frame, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix?: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Destroys all object references in the Canvas Renderer. + */ + destroy(): void; + + } + + /** + * Returns an array which maps the default blend modes to supported Canvas blend modes. + * + * If the browser doesn't support a blend mode, it will default to the normal `source-over` blend mode. + */ + function GetBlendModes(): any[]; + + /** + * 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 Renderer.antialias, or the frame.source.scaleMode is set, then imageSmoothingEnabled is set. + * + * This function is only meant to be used internally. Most of the Canvas Renderer classes use it. + * @param renderer A reference to the current active Canvas renderer. + * @param ctx The canvas context to set the transform on. + * @param src The Game Object being rendered. Can be any type that extends the base class. + * @param camera The Camera that is rendering the Game Object. + * @param parentMatrix A parent transform matrix to apply to the Game Object before rendering. + */ + function SetTransform(renderer: Phaser.Renderer.Canvas.CanvasRenderer, ctx: CanvasRenderingContext2D, src: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): boolean; + + } + + namespace Snapshot { + /** + * Takes a snapshot of an area from the current frame displayed by a canvas. + * + * This is then copied to an Image object. When this loads, the results are sent + * to the callback provided in the Snapshot Configuration object. + * @param sourceCanvas The canvas to take a snapshot of. + * @param config The snapshot configuration object. + */ + function Canvas(sourceCanvas: HTMLCanvasElement, config: Phaser.Types.Renderer.Snapshot.SnapshotState): void; + + /** + * Takes a snapshot of an area from the current frame displayed by a WebGL canvas. + * + * This is then copied to an Image object. When this loads, the results are sent + * to the callback provided in the Snapshot Configuration object. + * @param sourceCanvas The canvas to take a snapshot of. + * @param config The snapshot configuration object. + */ + function WebGL(sourceCanvas: HTMLCanvasElement, config: Phaser.Types.Renderer.Snapshot.SnapshotState): void; + + } + + namespace WebGL { + namespace Pipelines { + /** + * BitmapMaskPipeline handles all bitmap masking rendering in WebGL. It works by using + * sampling two texture on the fragment shader and using the fragment's alpha to clip the region. + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + */ + class BitmapMaskPipeline extends Phaser.Renderer.WebGL.WebGLPipeline { + /** + * + * @param config Used for overriding shader an pipeline properties if extending this pipeline. + */ + constructor(config: object); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + */ + vertexViewF32: Float32Array; + + /** + * Size of the batch. + */ + maxQuads: number; + + /** + * Dirty flag to check if resolution properties need to be updated on the + * masking shader. + */ + resolutionDirty: boolean; + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + */ + onBind(): this; + + /** + * [description] + * @param width [description] + * @param height [description] + * @param resolution [description] + */ + resize(width: number, height: number, resolution: number): this; + + /** + * Binds necessary resources and renders the mask to a separated framebuffer. + * The framebuffer for the masked object is also bound for further use. + * @param mask GameObject used as mask. + * @param maskedObject GameObject masked by the mask GameObject. + * @param camera [description] + */ + beginMask(mask: Phaser.GameObjects.GameObject, maskedObject: Phaser.GameObjects.GameObject, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * The masked game objects framebuffer is unbound and its texture + * is bound together with the mask texture and the mask shader and + * a draw call with a single quad is processed. Here is where the + * masking effect is applied. + * @param mask GameObject used as a mask. + */ + endMask(mask: Phaser.GameObjects.GameObject): void; + + } + + /** + * Implements a model view projection matrices. + * Pipelines can implement this for doing 2D and 3D rendering. + */ + interface ModelViewProjection { + /** + * Dirty flag for checking if model matrix needs to be updated on GPU. + */ + modelMatrixDirty: boolean; + /** + * Dirty flag for checking if view matrix needs to be updated on GPU. + */ + viewMatrixDirty: boolean; + /** + * Dirty flag for checking if projection matrix needs to be updated on GPU. + */ + projectionMatrixDirty: boolean; + /** + * Model matrix + */ + modelMatrix: Float32Array; + /** + * View matrix + */ + viewMatrix: Float32Array; + /** + * Projection matrix + */ + projectionMatrix: Float32Array; + /** + * Initializes MVP matrices with an identity matrix + */ + mvpInit(): void; + /** + * If dirty flags are set then the matrices are uploaded to the GPU. + */ + mvpUpdate(): void; + /** + * Loads an identity matrix to the model matrix + */ + modelIdentity(): void; + /** + * Scale model matrix + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + modelScale(x: number, y: number, z: number): this; + /** + * Translate model matrix + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + modelTranslate(x: number, y: number, z: number): this; + /** + * Rotates the model matrix in the X axis. + * @param radians The amount to rotate by. + */ + modelRotateX(radians: number): this; + /** + * Rotates the model matrix in the Y axis. + * @param radians The amount to rotate by. + */ + modelRotateY(radians: number): this; + /** + * Rotates the model matrix in the Z axis. + * @param radians The amount to rotate by. + */ + modelRotateZ(radians: number): this; + /** + * Loads identity matrix into the view matrix + */ + viewIdentity(): this; + /** + * Scales view matrix + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + viewScale(x: number, y: number, z: number): this; + /** + * Translates view matrix + * @param x The x component. + * @param y The y component. + * @param z The z component. + */ + viewTranslate(x: number, y: number, z: number): this; + /** + * Rotates view matrix in the X axis. + * @param radians The amount to rotate by. + */ + viewRotateX(radians: number): this; + /** + * Rotates view matrix in the Y axis. + * @param radians The amount to rotate by. + */ + viewRotateY(radians: number): this; + /** + * Rotates view matrix in the Z axis. + * @param radians The amount to rotate by. + */ + viewRotateZ(radians: number): this; + /** + * Loads a 2D view matrix (3x2 matrix) into a 4x4 view matrix + * @param matrix2D The Matrix2D. + */ + viewLoad2D(matrix2D: Float32Array): this; + /** + * Copies a 4x4 matrix into the view matrix + * @param matrix The Matrix2D. + */ + viewLoad(matrix: Float32Array): this; + /** + * Loads identity matrix into the projection matrix. + */ + projIdentity(): this; + /** + * Sets up an orthographic projection matrix + * @param left The left value. + * @param right The right value. + * @param bottom The bottom value. + * @param top The top value. + * @param near The near value. + * @param far The far value. + */ + projOrtho(left: number, right: number, bottom: number, top: number, near: number, far: number): this; + /** + * Sets up a perspective projection matrix + * @param fovY The fov value. + * @param aspectRatio The aspectRatio value. + * @param near The near value. + * @param far The far value. + */ + projPersp(fovY: number, aspectRatio: number, near: number, far: number): this; + } + + /** + * ForwardDiffuseLightPipeline implements a forward rendering approach for 2D lights. + * This pipeline extends TextureTintPipeline so it implements all it's rendering functions + * and batching system. + */ + class ForwardDiffuseLightPipeline extends Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline { + /** + * + * @param config The configuration of the pipeline, same as the {@link Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline}. The fragment shader will be replaced with the lighting shader. + */ + constructor(config: object); + + /** + * This function sets all the needed resources for each camera pass. + * @param scene The Scene being rendered. + * @param camera The Scene Camera being rendered with. + */ + onRender(scene: Phaser.Scene, camera: Phaser.Cameras.Scene2D.Camera): this; + + /** + * Generic function for batching a textured quad + * @param gameObject Source GameObject + * @param texture Raw WebGLTexture associated with the quad + * @param textureWidth Real texture width + * @param textureHeight Real texture height + * @param srcX X coordinate of the quad + * @param srcY Y coordinate of the quad + * @param srcWidth Width of the quad + * @param srcHeight Height of the quad + * @param scaleX X component of scale + * @param scaleY Y component of scale + * @param rotation Rotation of the quad + * @param flipX Indicates if the quad is horizontally flipped + * @param flipY Indicates if the quad is vertically flipped + * @param scrollFactorX By which factor is the quad affected by the camera horizontal scroll + * @param scrollFactorY By which factor is the quad effected by the camera vertical scroll + * @param displayOriginX Horizontal origin in pixels + * @param displayOriginY Vertical origin in pixels + * @param frameX X coordinate of the texture frame + * @param frameY Y coordinate of the texture frame + * @param frameWidth Width of the texture frame + * @param frameHeight Height of the texture frame + * @param tintTL Tint for top left + * @param tintTR Tint for top right + * @param tintBL Tint for bottom left + * @param tintBR Tint for bottom right + * @param tintEffect The tint effect (0 for additive, 1 for replacement) + * @param uOffset Horizontal offset on texture coordinate + * @param vOffset Vertical offset on texture coordinate + * @param camera Current used camera + * @param parentTransformMatrix Parent container + */ + batchTexture(gameObject: Phaser.GameObjects.GameObject, texture: WebGLTexture, textureWidth: integer, textureHeight: integer, srcX: number, srcY: number, srcWidth: number, srcHeight: number, scaleX: number, scaleY: number, rotation: number, flipX: boolean, flipY: boolean, scrollFactorX: number, scrollFactorY: number, displayOriginX: number, displayOriginY: number, frameX: number, frameY: number, frameWidth: number, frameHeight: number, tintTL: integer, tintTR: integer, tintBL: integer, tintBR: integer, tintEffect: number, uOffset: number, vOffset: number, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Sets the Game Objects normal map as the active texture. + * @param gameObject The Game Object to update. + */ + setNormalMap(gameObject: Phaser.GameObjects.GameObject): void; + + /** + * Rotates the normal map vectors inversely by the given angle. + * Only works in 2D space. + * @param rotation The angle of rotation in radians. + */ + setNormalMapRotation(rotation: number): void; + + /** + * Takes a Sprite Game Object, or any object that extends it, which has a normal texture and adds it to the batch. + * @param sprite The texture-based Game Object to add to the batch. + * @param camera The Camera to use for the rendering transform. + * @param parentTransformMatrix The transform matrix of the parent container, if set. + */ + batchSprite(sprite: Phaser.GameObjects.Sprite, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + } + + /** + * TextureTintPipeline implements the rendering infrastructure + * for displaying textured objects + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + */ + class TextureTintPipeline extends Phaser.Renderer.WebGL.WebGLPipeline { + /** + * + * @param config The configuration options for this Texture Tint Pipeline, as described above. + */ + constructor(config: object); + + /** + * Float32 view of the array buffer containing the pipeline's vertices. + */ + vertexViewF32: Float32Array; + + /** + * Uint32 view of the array buffer containing the pipeline's vertices. + */ + vertexViewU32: Uint32Array; + + /** + * Size of the batch. + */ + maxQuads: integer; + + /** + * Collection of batch information + */ + batches: any[]; + + /** + * Called every time the pipeline needs to be used. + * It binds all necessary resources. + */ + onBind(): this; + + /** + * Resizes this pipeline and updates the projection. + * @param width The new width. + * @param height The new height. + * @param resolution The resolution. + */ + resize(width: number, height: number, resolution: number): this; + + /** + * Assigns a texture to the current batch. If a different texture is already set it creates a new batch object. + * @param texture WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param unit Texture unit to which the texture needs to be bound. Default 0. + */ + setTexture2D(texture?: WebGLTexture, unit?: integer): Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline; + + /** + * Checks if the current batch has the same texture and texture unit, or if we need to create a new batch. + * @param texture WebGLTexture that will be assigned to the current batch. If not given uses blankTexture. + * @param unit Texture unit to which the texture needs to be bound. + */ + requireTextureBatch(texture: WebGLTexture, unit: integer): boolean; + + /** + * Creates a new batch object and pushes it to a batch array. + * The batch object contains information relevant to the current + * vertex batch like the offset in the vertex buffer, vertex count and + * the textures used by that batch. + * @param texture Optional WebGLTexture that will be assigned to the created batch. + * @param unit Texture unit to which the texture needs to be bound. + */ + pushBatch(texture: WebGLTexture, unit: integer): void; + + /** + * Uploads the vertex data and emits a draw call for the current batch of vertices. + */ + flush(): this; + + /** + * Takes a Sprite Game Object, or any object that extends it, and adds it to the batch. + * @param sprite The texture based Game Object to add to the batch. + * @param camera The Camera to use for the rendering transform. + * @param parentTransformMatrix The transform matrix of the parent container, if set. + */ + batchSprite(sprite: Phaser.GameObjects.Image | Phaser.GameObjects.Sprite, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix?: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Adds the vertices data into the batch and flushes if full. + * + * Assumes 6 vertices in the following arrangement: + * + * ``` + * 0----3 + * |\ B| + * | \ | + * | \ | + * | A \| + * | \ + * 1----2 + * ``` + * + * Where tx0/ty0 = 0, tx1/ty1 = 1, tx2/ty2 = 2 and tx3/ty3 = 3 + * @param x0 The top-left x position. + * @param y0 The top-left y position. + * @param x1 The bottom-left x position. + * @param y1 The bottom-left y position. + * @param x2 The bottom-right x position. + * @param y2 The bottom-right y position. + * @param x3 The top-right x position. + * @param y3 The top-right y position. + * @param u0 UV u0 value. + * @param v0 UV v0 value. + * @param u1 UV u1 value. + * @param v1 UV v1 value. + * @param tintTL The top-left tint color value. + * @param tintTR The top-right tint color value. + * @param tintBL The bottom-left tint color value. + * @param tintBR The bottom-right tint color value. + * @param tintEffect The tint effect for the shader to use. + * @param texture WebGLTexture that will be assigned to the current batch if a flush occurs. + * @param unit Texture unit to which the texture needs to be bound. Default 0. + */ + batchQuad(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, u0: number, v0: number, u1: number, v1: number, tintTL: number, tintTR: number, tintBL: number, tintBR: number, tintEffect: number | boolean, texture?: WebGLTexture, unit?: integer): boolean; + + /** + * Adds the vertices data into the batch and flushes if full. + * + * Assumes 3 vertices in the following arrangement: + * + * ``` + * 0 + * |\ + * | \ + * | \ + * | \ + * | \ + * 1-----2 + * ``` + * @param x1 The bottom-left x position. + * @param y1 The bottom-left y position. + * @param x2 The bottom-right x position. + * @param y2 The bottom-right y position. + * @param x3 The top-right x position. + * @param y3 The top-right y position. + * @param u0 UV u0 value. + * @param v0 UV v0 value. + * @param u1 UV u1 value. + * @param v1 UV v1 value. + * @param tintTL The top-left tint color value. + * @param tintTR The top-right tint color value. + * @param tintBL The bottom-left tint color value. + * @param tintEffect The tint effect for the shader to use. + * @param texture WebGLTexture that will be assigned to the current batch if a flush occurs. + * @param unit Texture unit to which the texture needs to be bound. Default 0. + */ + batchTri(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, u0: number, v0: number, u1: number, v1: number, tintTL: number, tintTR: number, tintBL: number, tintEffect: number | boolean, texture?: WebGLTexture, unit?: integer): boolean; + + /** + * Generic function for batching a textured quad using argument values instead of a Game Object. + * @param gameObject Source GameObject. + * @param texture Raw WebGLTexture associated with the quad. + * @param textureWidth Real texture width. + * @param textureHeight Real texture height. + * @param srcX X coordinate of the quad. + * @param srcY Y coordinate of the quad. + * @param srcWidth Width of the quad. + * @param srcHeight Height of the quad. + * @param scaleX X component of scale. + * @param scaleY Y component of scale. + * @param rotation Rotation of the quad. + * @param flipX Indicates if the quad is horizontally flipped. + * @param flipY Indicates if the quad is vertically flipped. + * @param scrollFactorX By which factor is the quad affected by the camera horizontal scroll. + * @param scrollFactorY By which factor is the quad effected by the camera vertical scroll. + * @param displayOriginX Horizontal origin in pixels. + * @param displayOriginY Vertical origin in pixels. + * @param frameX X coordinate of the texture frame. + * @param frameY Y coordinate of the texture frame. + * @param frameWidth Width of the texture frame. + * @param frameHeight Height of the texture frame. + * @param tintTL Tint for top left. + * @param tintTR Tint for top right. + * @param tintBL Tint for bottom left. + * @param tintBR Tint for bottom right. + * @param tintEffect The tint effect. + * @param uOffset Horizontal offset on texture coordinate. + * @param vOffset Vertical offset on texture coordinate. + * @param camera Current used camera. + * @param parentTransformMatrix Parent container. + * @param skipFlip Skip the renderTexture check. Default false. + */ + batchTexture(gameObject: Phaser.GameObjects.GameObject, texture: WebGLTexture, textureWidth: integer, textureHeight: integer, srcX: number, srcY: number, srcWidth: number, srcHeight: number, scaleX: number, scaleY: number, rotation: number, flipX: boolean, flipY: boolean, scrollFactorX: number, scrollFactorY: number, displayOriginX: number, displayOriginY: number, frameX: number, frameY: number, frameWidth: number, frameHeight: number, tintTL: integer, tintTR: integer, tintBL: integer, tintBR: integer, tintEffect: number, uOffset: number, vOffset: number, camera: Phaser.Cameras.Scene2D.Camera, parentTransformMatrix: Phaser.GameObjects.Components.TransformMatrix, skipFlip?: boolean): void; + + /** + * Adds a Texture Frame into the batch for rendering. + * @param frame The Texture Frame to be rendered. + * @param x The horizontal position to render the texture at. + * @param y The vertical position to render the texture at. + * @param tint The tint color. + * @param alpha The alpha value. + * @param transformMatrix The Transform Matrix to use for the texture. + * @param parentTransformMatrix A parent Transform Matrix. + */ + batchTextureFrame(frame: Phaser.Textures.Frame, x: number, y: number, tint: number, alpha: number, transformMatrix: Phaser.GameObjects.Components.TransformMatrix, parentTransformMatrix?: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Pushes a filled rectangle into the vertex batch. + * Rectangle has no transform values and isn't transformed into the local space. + * Used for directly batching untransformed rectangles, such as Camera background colors. + * @param x Horizontal top left coordinate of the rectangle. + * @param y Vertical top left coordinate of the rectangle. + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param color Color of the rectangle to draw. + * @param alpha Alpha value of the rectangle to draw. + */ + drawFillRect(x: number, y: number, width: number, height: number, color: number, alpha: number): void; + + /** + * Pushes a filled rectangle into the vertex batch. + * Rectangle factors in the given transform matrices before adding to the batch. + * @param x Horizontal top left coordinate of the rectangle. + * @param y Vertical top left coordinate of the rectangle. + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param currentMatrix The current transform. + * @param parentMatrix The parent transform. + */ + batchFillRect(x: number, y: number, width: number, height: number, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Pushes a filled triangle into the vertex batch. + * Triangle factors in the given transform matrices before adding to the batch. + * @param x0 Point 0 x coordinate. + * @param y0 Point 0 y coordinate. + * @param x1 Point 1 x coordinate. + * @param y1 Point 1 y coordinate. + * @param x2 Point 2 x coordinate. + * @param y2 Point 2 y coordinate. + * @param currentMatrix The current transform. + * @param parentMatrix The parent transform. + */ + batchFillTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Pushes a stroked triangle into the vertex batch. + * Triangle factors in the given transform matrices before adding to the batch. + * The triangle is created from 3 lines and drawn using the `batchStrokePath` method. + * @param x0 Point 0 x coordinate. + * @param y0 Point 0 y coordinate. + * @param x1 Point 1 x coordinate. + * @param y1 Point 1 y coordinate. + * @param x2 Point 2 x coordinate. + * @param y2 Point 2 y coordinate. + * @param lineWidth The width of the line in pixels. + * @param currentMatrix The current transform. + * @param parentMatrix The parent transform. + */ + batchStrokeTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, lineWidth: number, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Adds the given path to the vertex batch for rendering. + * + * It works by taking the array of path data and then passing it through Earcut, which + * creates a list of polygons. Each polygon is then added to the batch. + * + * The path is always automatically closed because it's filled. + * @param path Collection of points that represent the path. + * @param currentMatrix The current transform. + * @param parentMatrix The parent transform. + */ + batchFillPath(path: any[], currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Adds the given path to the vertex batch for rendering. + * + * It works by taking the array of path data and calling `batchLine` for each section + * of the path. + * + * The path is optionally closed at the end. + * @param path Collection of points that represent the path. + * @param lineWidth The width of the line segments in pixels. + * @param pathOpen Indicates if the path should be closed or left open. + * @param currentMatrix The current transform. + * @param parentMatrix The parent transform. + */ + batchStrokePath(path: any[], lineWidth: number, pathOpen: boolean, currentMatrix: Phaser.GameObjects.Components.TransformMatrix, parentMatrix: Phaser.GameObjects.Components.TransformMatrix): void; + + /** + * Creates a quad and adds it to the vertex batch based on the given line values. + * @param ax X coordinate to the start of the line + * @param ay Y coordinate to the start of the line + * @param bx X coordinate to the end of the line + * @param by Y coordinate to the end of the line + * @param aLineWidth Width of the start of the line + * @param bLineWidth Width of the end of the line + * @param currentMatrix Parent matrix, generally used by containers + */ + batchLine(ax: number, ay: number, bx: number, by: number, aLineWidth: number, bLineWidth: number, currentMatrix: Float32Array): void; + + } + + } + + namespace Utils { + /** + * Packs four floats on a range from 0.0 to 1.0 into a single Uint32 + * @param r Red component in a range from 0.0 to 1.0 + * @param g Green component in a range from 0.0 to 1.0 + * @param b Blue component in a range from 0.0 to 1.0 + * @param a Alpha component in a range from 0.0 to 1.0 + */ + function getTintFromFloats(r: number, g: number, b: number, a: number): number; + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a Uint32 + * @param rgb Uint24 representing RGB components + * @param a Float32 representing Alpha component + */ + function getTintAppendFloatAlpha(rgb: number, a: number): number; + + /** + * Packs a Uint24, representing RGB components, with a Float32, representing + * the alpha component, with a range between 0.0 and 1.0 and return a + * swizzled Uint32 + * @param rgb Uint24 representing RGB components + * @param a Float32 representing Alpha component + */ + function getTintAppendFloatAlphaAndSwap(rgb: number, a: number): number; + + /** + * Unpacks a Uint24 RGB into an array of floats of ranges of 0.0 and 1.0 + * @param rgb RGB packed as a Uint24 + */ + function getFloatsFromUintRGB(rgb: number): any[]; + + /** + * Counts how many attributes of 32 bits a vertex has + * @param attributes Array of attributes + * @param glContext WebGLContext used for check types + */ + function getComponentCount(attributes: any[], glContext: WebGLRenderingContext): number; + + } + + /** + * WebGLPipeline is a class that describes the way elements will be renderered + * in WebGL, specially focused on batching vertices (batching is not provided). + * Pipelines are mostly used for describing 2D rendering passes but it's + * flexible enough to be used for any type of rendering including 3D. + * Internally WebGLPipeline will handle things like compiling shaders, + * creating vertex buffers, assigning primitive topology and binding + * vertex attributes. + * + * The config properties are: + * - game: Current game instance. + * - renderer: Current WebGL renderer. + * - gl: Current WebGL context. + * - topology: This indicates how the primitives are rendered. The default value is GL_TRIANGLES. + * Here is the full list of rendering primitives (https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants). + * - vertShader: Source for vertex shader as a string. + * - fragShader: Source for fragment shader as a string. + * - vertexCapacity: The amount of vertices that shall be allocated + * - vertexSize: The size of a single vertex in bytes. + * - vertices: An optional buffer of vertices + * - attributes: An array describing the vertex attributes + * + * The vertex attributes properties are: + * - name : String - Name of the attribute in the vertex shader + * - size : integer - How many components describe the attribute. For ex: vec3 = size of 3, float = size of 1 + * - type : GLenum - WebGL type (gl.BYTE, gl.SHORT, gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT, gl.FLOAT) + * - normalized : boolean - Is the attribute normalized + * - offset : integer - The offset in bytes to the current attribute in the vertex. Equivalent to offsetof(vertex, attrib) in C + * Here you can find more information of how to describe an attribute: + * - https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer + */ + class WebGLPipeline { + /** + * + * @param config The configuration object for this WebGL Pipeline, as described above. + */ + constructor(config: object); + + /** + * Name of the Pipeline. Used for identifying + */ + name: string; + + /** + * The Game which owns this WebGL Pipeline. + */ + game: Phaser.Game; + + /** + * The canvas which this WebGL Pipeline renders to. + */ + view: HTMLCanvasElement; + + /** + * Used to store the current game resolution + */ + resolution: number; + + /** + * Width of the current viewport + */ + width: number; + + /** + * Height of the current viewport + */ + height: number; + + /** + * The WebGL context this WebGL Pipeline uses. + */ + gl: WebGLRenderingContext; + + /** + * How many vertices have been fed to the current pipeline. + */ + vertexCount: number; + + /** + * The limit of vertices that the pipeline can hold + */ + vertexCapacity: integer; + + /** + * The WebGL Renderer which owns this WebGL Pipeline. + */ + renderer: Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * Raw byte buffer of vertices. + */ + vertexData: ArrayBuffer; + + /** + * The handle to a WebGL vertex buffer object. + */ + vertexBuffer: WebGLBuffer; + + /** + * The handle to a WebGL program + */ + program: WebGLProgram; + + /** + * Array of objects that describe the vertex attributes + */ + attributes: object; + + /** + * The size in bytes of the vertex + */ + vertexSize: integer; + + /** + * The primitive topology which the pipeline will use to submit draw calls + */ + topology: integer; + + /** + * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources + * to the GPU. + */ + bytes: Uint8Array; + + /** + * This will store the amount of components of 32 bit length + */ + vertexComponentCount: integer; + + /** + * Indicates if the current pipeline is flushing the contents to the GPU. + * When the variable is set the flush function will be locked. + */ + flushLocked: boolean; + + /** + * Indicates if the current pipeline is active or not for this frame only. + * Reset in the onRender method. + */ + active: boolean; + + /** + * Called when the Game has fully booted and the Renderer has finished setting up. + * + * By this stage all Game level systems are now in place and you can perform any final + * tasks that the pipeline may need that relied on game systems such as the Texture Manager. + */ + boot(): void; + + /** + * Adds a description of vertex attribute to the pipeline + * @param name Name of the vertex attribute + * @param size Vertex component size + * @param type Type of the attribute + * @param normalized Is the value normalized to a range + * @param offset Byte offset to the beginning of the first element in the vertex + */ + addAttribute(name: string, size: integer, type: integer, normalized: boolean, offset: integer): this; + + /** + * Check if the current batch of vertices is full. + */ + shouldFlush(): boolean; + + /** + * Resizes the properties used to describe the viewport + * @param width The new width of this WebGL Pipeline. + * @param height The new height of this WebGL Pipeline. + * @param resolution The resolution this WebGL Pipeline should be resized to. + */ + resize(width: number, height: number, resolution: number): this; + + /** + * Binds the pipeline resources, including programs, vertex buffers and binds attributes + */ + bind(): this; + + /** + * Set whenever this WebGL Pipeline is bound to a WebGL Renderer. + * + * This method is called every time the WebGL Pipeline is attempted to be bound, even if it already is the current pipeline. + */ + onBind(): this; + + /** + * Called before each frame is rendered, but after the canvas has been cleared. + */ + onPreRender(): this; + + /** + * Called before a Scene's Camera is rendered. + * @param scene The Scene being rendered. + * @param camera The Scene Camera being rendered with. + */ + onRender(scene: Phaser.Scene, camera: Phaser.Cameras.Scene2D.Camera): this; + + /** + * Called after each frame has been completely rendered and snapshots have been taken. + */ + onPostRender(): this; + + /** + * Uploads the vertex data and emits a draw call + * for the current batch of vertices. + */ + flush(): this; + + /** + * Removes all object references in this WebGL Pipeline and removes its program from the WebGL context. + */ + destroy(): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x The new value of the `float` uniform. + */ + setFloat1(name: string, x: number): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x The new X component of the `vec2` uniform. + * @param y The new Y component of the `vec2` uniform. + */ + setFloat2(name: string, x: number, y: number): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x The new X component of the `vec3` uniform. + * @param y The new Y component of the `vec3` uniform. + * @param z The new Z component of the `vec3` uniform. + */ + setFloat3(name: string, x: number, y: number, z: number): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x X component of the uniform + * @param y Y component of the uniform + * @param z Z component of the uniform + * @param w W component of the uniform + */ + setFloat4(name: string, x: number, y: number, z: number, w: number): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat1v(name: string, arr: Float32Array): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat2v(name: string, arr: Float32Array): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat3v(name: string, arr: Float32Array): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat4v(name: string, arr: Float32Array): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x The new value of the `int` uniform. + */ + setInt1(name: string, x: integer): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x The new X component of the `ivec2` uniform. + * @param y The new Y component of the `ivec2` uniform. + */ + setInt2(name: string, x: integer, y: integer): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x The new X component of the `ivec3` uniform. + * @param y The new Y component of the `ivec3` uniform. + * @param z The new Z component of the `ivec3` uniform. + */ + setInt3(name: string, x: integer, y: integer, z: integer): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param x X component of the uniform + * @param y Y component of the uniform + * @param z Z component of the uniform + * @param w W component of the uniform + */ + setInt4(name: string, x: integer, y: integer, z: integer, w: integer): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param transpose Whether to transpose the matrix. Should be `false`. + * @param matrix The new values for the `mat2` uniform. + */ + setMatrix2(name: string, transpose: boolean, matrix: Float32Array): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param transpose Whether to transpose the matrix. Should be `false`. + * @param matrix The new values for the `mat3` uniform. + */ + setMatrix3(name: string, transpose: boolean, matrix: Float32Array): this; + + /** + * Set a uniform value of the current pipeline program. + * @param name The name of the uniform to look-up and modify. + * @param transpose Should the matrix be transpose + * @param matrix Matrix data + */ + setMatrix4(name: string, transpose: boolean, matrix: Float32Array): this; + + } + + /** + * WebGLRenderer is a class that contains the needed functionality to keep the + * WebGLRenderingContext state clean. The main idea of the WebGLRenderer is to keep track of + * any context change that happens for WebGL rendering inside of Phaser. This means + * if raw webgl functions are called outside the WebGLRenderer of the Phaser WebGL + * rendering ecosystem they might pollute the current WebGLRenderingContext state producing + * unexpected behavior. It's recommended that WebGL interaction is done through + * WebGLRenderer and/or WebGLPipeline. + */ + class WebGLRenderer { + /** + * + * @param game The Game instance which owns this WebGL Renderer. + */ + constructor(game: Phaser.Game); + + /** + * The local configuration settings of this WebGL Renderer. + */ + config: object; + + /** + * The Game instance which owns this WebGL Renderer. + */ + game: Phaser.Game; + + /** + * A constant which allows the renderer to be easily identified as a WebGL Renderer. + */ + type: integer; + + /** + * The width of the canvas being rendered to. + * This is populated in the onResize event handler. + */ + width: integer; + + /** + * The height of the canvas being rendered to. + * This is populated in the onResize event handler. + */ + height: integer; + + /** + * The canvas which this WebGL Renderer draws to. + */ + canvas: HTMLCanvasElement; + + /** + * An array of blend modes supported by the WebGL Renderer. + * + * This array includes the default blend modes as well as any custom blend modes added through {@link #addBlendMode}. + */ + blendModes: any[]; + + /** + * Keeps track of any WebGLTexture created with the current WebGLRenderingContext + */ + nativeTextures: any[]; + + /** + * This property is set to `true` if the WebGL context of the renderer is lost. + */ + contextLost: boolean; + + /** + * This object will store all pipelines created through addPipeline + */ + pipelines: object; + + /** + * Details about the currently scheduled snapshot. + * + * If a non-null `callback` is set in this object, a snapshot of the canvas will be taken after the current frame is fully rendered. + */ + snapshotState: Phaser.Types.Renderer.Snapshot.SnapshotState; + + /** + * Cached value for the last texture unit that was used + */ + currentActiveTextureUnit: integer; + + /** + * An array of the last texture handles that were bound to the WebGLRenderingContext + */ + currentTextures: any[]; + + /** + * Current framebuffer in use + */ + currentFramebuffer: WebGLFramebuffer; + + /** + * Current WebGLPipeline in use + */ + currentPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Current WebGLProgram in use + */ + currentProgram: WebGLProgram; + + /** + * Current WebGLBuffer (Vertex buffer) in use + */ + currentVertexBuffer: WebGLBuffer; + + /** + * Current WebGLBuffer (Index buffer) in use + */ + currentIndexBuffer: WebGLBuffer; + + /** + * Current blend mode in use + */ + currentBlendMode: integer; + + /** + * Indicates if the the scissor state is enabled in WebGLRenderingContext + */ + currentScissorEnabled: boolean; + + /** + * Stores the current scissor data + */ + currentScissor: Uint32Array; + + /** + * Stack of scissor data + */ + scissorStack: Uint32Array; + + /** + * The handler to invoke when the context is lost. + * This should not be changed and is set in the boot method. + */ + contextLostHandler: Function; + + /** + * The handler to invoke when the context is restored. + * This should not be changed and is set in the boot method. + */ + contextRestoredHandler: Function; + + /** + * The underlying WebGL context of the renderer. + */ + gl: WebGLRenderingContext; + + /** + * Array of strings that indicate which WebGL extensions are supported by the browser + */ + supportedExtensions: object; + + /** + * Extensions loaded into the current context + */ + extensions: object; + + /** + * Stores the current WebGL component formats for further use + */ + glFormats: any[]; + + /** + * Stores the supported WebGL texture compression formats. + */ + compression: any[]; + + /** + * Cached drawing buffer height to reduce gl calls. + */ + readonly drawingBufferHeight: number; + + /** + * A blank 32x32 transparent texture, as used by the Graphics system where needed. + * This is set in the `boot` method. + */ + readonly blankTexture: WebGLTexture; + + /** + * A default Camera used in calls when no other camera has been provided. + */ + defaultCamera: Phaser.Cameras.Scene2D.BaseCamera; + + /** + * The total number of masks currently stacked. + */ + maskCount: integer; + + /** + * The mask stack. + */ + maskStack: Phaser.Display.Masks.GeometryMask[]; + + /** + * Internal property that tracks the currently set mask. + */ + currentMask: any; + + /** + * Internal property that tracks the currently set camera mask. + */ + currentCameraMask: any; + + /** + * Internal gl function mapping for uniform look-up. + * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform + */ + glFuncMap: any; + + /** + * The `type` of the Game Object being currently rendered. + * This can be used by advanced render functions for batching look-ahead. + */ + currentType: string; + + /** + * Is the `type` of the Game Object being currently rendered different than the + * type of the object before it in the display list? I.e. it's a 'new' type. + */ + newType: boolean; + + /** + * Does the `type` of the next Game Object in the display list match that + * of the object being currently rendered? + */ + nextTypeMatch: boolean; + + /** + * The mipmap magFilter to be used when creating textures. + * + * You can specify this as a string in the game config, i.e.: + * + * `renderer: { 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 + */ + mipmapFilter: GLenum; + + /** + * Creates a new WebGLRenderingContext and initializes all internal state. + * @param config The configuration object for the renderer. + */ + init(config: object): this; + + /** + * The event handler that manages the `resize` event dispatched by the Scale Manager. + * @param gameSize The default Game Size object. This is the un-modified game dimensions. + * @param baseSize The base Size object. The game dimensions multiplied by the resolution. The canvas width / height values match this. + * @param displaySize The display Size object. The size of the canvas style width / height attributes. + * @param resolution The Scale Manager resolution setting. + */ + onResize(gameSize: Phaser.Structs.Size, baseSize: Phaser.Structs.Size, displaySize: Phaser.Structs.Size, resolution?: number): void; + + /** + * Resizes the drawing buffer to match that required by the Scale Manager. + * @param width The new width of the renderer. + * @param height The new height of the renderer. + * @param resolution The new resolution of the renderer. + */ + resize(width?: number, height?: number, resolution?: number): this; + + /** + * Checks if a WebGL extension is supported + * @param extensionName Name of the WebGL extension + */ + hasExtension(extensionName: string): boolean; + + /** + * Loads a WebGL extension + * @param extensionName The name of the extension to load. + */ + getExtension(extensionName: string): object; + + /** + * Flushes the current pipeline if the pipeline is bound + */ + flush(): void; + + /** + * Checks if a pipeline is present in the current WebGLRenderer + * @param pipelineName The name of the pipeline. + */ + hasPipeline(pipelineName: string): boolean; + + /** + * Returns the pipeline by name if the pipeline exists + * @param pipelineName The name of the pipeline. + */ + getPipeline(pipelineName: string): Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Removes a pipeline by name. + * @param pipelineName The name of the pipeline to be removed. + */ + removePipeline(pipelineName: string): this; + + /** + * Adds a pipeline instance into the collection of pipelines + * @param pipelineName A unique string-based key for the pipeline. + * @param pipelineInstance A pipeline instance which must extend WebGLPipeline. + */ + addPipeline(pipelineName: string, pipelineInstance: Phaser.Renderer.WebGL.WebGLPipeline): Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Pushes a new scissor state. This is used to set nested scissor states. + * @param x The x position of the scissor. + * @param y The y position of the scissor. + * @param width The width of the scissor. + * @param height The height of the scissor. + * @param drawingBufferHeight Optional drawingBufferHeight override value. + */ + pushScissor(x: integer, y: integer, width: integer, height: integer, drawingBufferHeight?: integer): integer[]; + + /** + * Sets the current scissor state. + * @param x The x position of the scissor. + * @param y The y position of the scissor. + * @param width The width of the scissor. + * @param height The height of the scissor. + * @param drawingBufferHeight Optional drawingBufferHeight override value. + */ + setScissor(x: integer, y: integer, width: integer, height: integer, drawingBufferHeight?: integer): void; + + /** + * Pops the last scissor state and sets it. + */ + popScissor(): void; + + /** + * Binds a WebGLPipeline and sets it as the current pipeline to be used. + * @param pipelineInstance The pipeline instance to be activated. + * @param gameObject The Game Object that invoked this pipeline, if any. + */ + setPipeline(pipelineInstance: Phaser.Renderer.WebGL.WebGLPipeline, gameObject?: Phaser.GameObjects.GameObject): Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Is there an active stencil mask? + */ + hasActiveStencilMask(): boolean; + + /** + * Use this to reset the gl context to the state that Phaser requires to continue rendering. + * Calling this will: + * + * * Disable `DEPTH_TEST`, `CULL_FACE` and `STENCIL_TEST`. + * * Clear the depth buffer and stencil buffers. + * * Reset the viewport size. + * * Reset the blend mode. + * * Bind a blank texture as the active texture on texture unit zero. + * * Rebinds the given pipeline instance. + * + * You should call this having previously called `clearPipeline` and then wishing to return + * control to Phaser again. + * @param pipelineInstance The pipeline instance to be activated. + */ + rebindPipeline(pipelineInstance: Phaser.Renderer.WebGL.WebGLPipeline): void; + + /** + * Flushes the current WebGLPipeline being used and then clears it, along with the + * the current shader program and vertex buffer. Then resets the blend mode to NORMAL. + * Call this before jumping to your own gl context handler, and then call `rebindPipeline` when + * you wish to return control to Phaser again. + */ + clearPipeline(): void; + + /** + * Sets the blend mode to the value given. + * + * If the current blend mode is different from the one given, the pipeline is flushed and the new + * blend mode is enabled. + * @param blendModeId The blend mode to be set. Can be a `BlendModes` const or an integer value. + * @param force Force the blend mode to be set, regardless of the currently set blend mode. Default false. + */ + setBlendMode(blendModeId: integer, force?: boolean): boolean; + + /** + * Creates a new custom blend mode for the renderer. + * + * See https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants#Blending_modes + * @param 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 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()}. + */ + addBlendMode(func: GLenum[], equation: GLenum): integer; + + /** + * Updates the function bound to a given custom blend mode. + * @param index The index of the custom blend mode. + * @param func The function to use for the blend mode. + * @param equation The equation to use for the blend mode. + */ + updateBlendMode(index: integer, func: Function, equation: Function): this; + + /** + * Removes a custom blend mode from the renderer. + * Any Game Objects still using this blend mode will error, so be sure to clear them first. + * @param index The index of the custom blend mode to be removed. + */ + removeBlendMode(index: integer): this; + + /** + * Binds a texture at a texture unit. If a texture is already + * bound to that unit it will force a flush on the current pipeline. + * @param texture The WebGL texture that needs to be bound. + * @param textureUnit The texture unit to which the texture will be bound. + * @param flush Will the current pipeline be flushed if this is a new texture, or not? Default true. + */ + setTexture2D(texture: WebGLTexture, textureUnit: integer, flush?: boolean): this; + + /** + * Binds a framebuffer. If there was another framebuffer already bound it will force a pipeline flush. + * @param framebuffer The framebuffer that needs to be bound. + * @param updateScissor If a framebuffer is given, set the gl scissor to match the frame buffer size? Or, if `null` given, pop the scissor from the stack. Default false. + */ + setFramebuffer(framebuffer: WebGLFramebuffer, updateScissor?: boolean): this; + + /** + * Binds a program. If there was another program already bound it will force a pipeline flush. + * @param program The program that needs to be bound. + */ + setProgram(program: WebGLProgram): this; + + /** + * Bounds a vertex buffer. If there is a vertex buffer already bound it'll force a pipeline flush. + * @param vertexBuffer The buffer that needs to be bound. + */ + setVertexBuffer(vertexBuffer: WebGLBuffer): this; + + /** + * Bounds a index buffer. If there is a index buffer already bound it'll force a pipeline flush. + * @param indexBuffer The buffer the needs to be bound. + */ + setIndexBuffer(indexBuffer: WebGLBuffer): this; + + /** + * Creates a texture from an image source. If the source is not valid it creates an empty texture. + * @param source The source of the texture. + * @param width The width of the texture. + * @param height The height of the texture. + * @param scaleMode The scale mode to be used by the texture. + */ + createTextureFromSource(source: object, width: integer, height: integer, scaleMode: integer): WebGLTexture; + + /** + * A wrapper for creating a WebGLTexture. If no pixel data is passed it will create an empty texture. + * @param mipLevel Mip level of the texture. + * @param minFilter Filtering of the texture. + * @param magFilter Filtering of the texture. + * @param wrapT Wrapping mode of the texture. + * @param wrapS Wrapping mode of the texture. + * @param format Which format does the texture use. + * @param pixels pixel data. + * @param width Width of the texture in pixels. + * @param height Height of the texture in pixels. + * @param pma Does the texture have premultiplied alpha? Default true. + * @param forceSize If `true` it will use the width and height passed to this method, regardless of the pixels dimension. Default false. + * @param flipY Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. Default false. + */ + createTexture2D(mipLevel: integer, minFilter: integer, magFilter: integer, wrapT: integer, wrapS: integer, format: integer, pixels: object, width: integer, height: integer, pma?: boolean, forceSize?: boolean, flipY?: boolean): WebGLTexture; + + /** + * Wrapper for creating WebGLFramebuffer. + * @param width Width in pixels of the framebuffer + * @param height Height in pixels of the framebuffer + * @param renderTexture The color texture to where the color pixels are written + * @param addDepthStencilBuffer Indicates if the current framebuffer support depth and stencil buffers + */ + createFramebuffer(width: integer, height: integer, renderTexture: WebGLTexture, addDepthStencilBuffer: boolean): WebGLFramebuffer; + + /** + * Wrapper for creating a WebGLProgram + * @param vertexShader Source to the vertex shader + * @param fragmentShader Source to the fragment shader + */ + createProgram(vertexShader: string, fragmentShader: string): WebGLProgram; + + /** + * Wrapper for creating a vertex buffer. + * @param initialDataOrSize It's either ArrayBuffer or an integer indicating the size of the vbo + * @param bufferUsage How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW + */ + createVertexBuffer(initialDataOrSize: ArrayBuffer, bufferUsage: integer): WebGLBuffer; + + /** + * Wrapper for creating a vertex buffer. + * @param initialDataOrSize Either ArrayBuffer or an integer indicating the size of the vbo. + * @param bufferUsage How the buffer is used. gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW. + */ + createIndexBuffer(initialDataOrSize: ArrayBuffer, bufferUsage: integer): WebGLBuffer; + + /** + * Removes the given texture from the nativeTextures array and then deletes it from the GPU. + * @param texture The WebGL Texture to be deleted. + */ + deleteTexture(texture: WebGLTexture): this; + + /** + * Deletes a WebGLFramebuffer from the GL instance. + * @param framebuffer The Framebuffer to be deleted. + */ + deleteFramebuffer(framebuffer: WebGLFramebuffer): this; + + /** + * Deletes a WebGLProgram from the GL instance. + * @param program The shader program to be deleted. + */ + deleteProgram(program: WebGLProgram): this; + + /** + * Deletes a WebGLBuffer from the GL instance. + * @param vertexBuffer The WebGLBuffer to be deleted. + */ + deleteBuffer(vertexBuffer: WebGLBuffer): this; + + /** + * Controls the pre-render operations for the given camera. + * Handles any clipping needed by the camera and renders the background color if a color is visible. + * @param camera The Camera to pre-render. + */ + preRenderCamera(camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * Controls the post-render operations for the given camera. + * Renders the foreground camera effects like flash and fading. It resets the current scissor state. + * @param camera The Camera to post-render. + */ + postRenderCamera(camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * Clears the current vertex buffer and updates pipelines. + */ + preRender(): void; + + /** + * The core render step for a Scene Camera. + * + * Iterates through the given Game Object's array and renders them with the given Camera. + * + * This is called by the `CameraManager.render` method. The Camera Manager instance belongs to a Scene, and is invoked + * by the Scene Systems.render method. + * + * This method is not called if `Camera.visible` is `false`, or `Camera.alpha` is zero. + * @param scene The Scene to render. + * @param children The Game Object's within the Scene to be rendered. + * @param interpolationPercentage The interpolation percentage to apply. Currently un-used. + * @param camera The Scene Camera to render with. + */ + render(scene: Phaser.Scene, children: Phaser.GameObjects.GameObject, interpolationPercentage: number, camera: Phaser.Cameras.Scene2D.Camera): void; + + /** + * The post-render step happens after all Cameras in all Scenes have been rendered. + */ + postRender(): void; + + /** + * Schedules a snapshot of the entire game viewport to be taken after the current frame is rendered. + * + * To capture a specific area see the `snapshotArea` 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. + * @param callback The Function to invoke after the snapshot image is created. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshot(callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; + + /** + * 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. + * @param x The x coordinate to grab from. + * @param y The y coordinate to grab from. + * @param width The width of the area to grab. + * @param height The height of the area to grab. + * @param callback The Function to invoke after the snapshot image is created. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshotArea(x: integer, y: integer, width: integer, height: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, type?: string, encoderOptions?: number): this; + + /** + * 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. + * @param x The x coordinate of the pixel to get. + * @param y The y coordinate of the pixel to get. + * @param callback The Function to invoke after the snapshot pixel data is extracted. + */ + snapshotPixel(x: integer, y: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback): this; + + /** + * 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. + * @param framebuffer The framebuffer to grab from. + * @param bufferWidth The width of the framebuffer. + * @param bufferHeight The height of the framebuffer. + * @param callback The Function to invoke after the snapshot image is created. + * @param getPixel Grab a single pixel as a Color object, or an area as an Image object? Default false. + * @param x The x coordinate to grab from. Default 0. + * @param y The y coordinate to grab from. Default 0. + * @param width The width of the area to grab. Default bufferWidth. + * @param height The height of the area to grab. Default bufferHeight. + * @param type The format of the image to create, usually `image/png` or `image/jpeg`. Default 'image/png'. + * @param encoderOptions The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`. Default 0.92. + */ + snapshotFramebuffer(framebuffer: WebGLFramebuffer, bufferWidth: integer, bufferHeight: integer, callback: Phaser.Types.Renderer.Snapshot.SnapshotCallback, getPixel?: boolean, x?: integer, y?: integer, width?: integer, height?: integer, type?: string, encoderOptions?: number): this; + + /** + * 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. + * @param srcCanvas The Canvas to create the WebGL Texture from + * @param dstTexture The destination WebGL Texture to set. + * @param noRepeat Should this canvas be allowed to set `REPEAT` (such as for Text objects?) Default false. + * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. + */ + canvasToTexture(srcCanvas: HTMLCanvasElement, dstTexture?: WebGLTexture, noRepeat?: boolean, flipY?: boolean): WebGLTexture; + + /** + * Creates a new WebGL Texture based on the given Canvas Element. + * @param srcCanvas The Canvas to create the WebGL Texture from + * @param noRepeat Should this canvas be allowed to set `REPEAT` (such as for Text objects?) Default false. + * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. + */ + createCanvasTexture(srcCanvas: HTMLCanvasElement, noRepeat?: boolean, flipY?: boolean): WebGLTexture; + + /** + * Updates a WebGL Texture based on the given Canvas Element. + * @param srcCanvas The Canvas to update the WebGL Texture from. + * @param dstTexture The destination WebGL Texture to update. + * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. + */ + updateCanvasTexture(srcCanvas: HTMLCanvasElement, dstTexture: WebGLTexture, flipY?: boolean): WebGLTexture; + + /** + * Creates a new WebGL Texture based on the given HTML Video Element. + * @param srcVideo The Video to create the WebGL Texture from + * @param noRepeat Should this canvas be allowed to set `REPEAT`? Default false. + * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. + */ + createVideoTexture(srcVideo: HTMLVideoElement, noRepeat?: boolean, flipY?: boolean): WebGLTexture; + + /** + * Updates a WebGL Texture based on the given HTML Video Element. + * @param srcVideo The Video to update the WebGL Texture with. + * @param dstTexture The destination WebGL Texture to update. + * @param flipY Should the WebGL Texture set `UNPACK_MULTIPLY_FLIP_Y`? Default false. + */ + updateVideoTexture(srcVideo: HTMLVideoElement, dstTexture: WebGLTexture, flipY?: boolean): WebGLTexture; + + /** + * Sets the minification and magnification filter for a texture. + * @param texture The texture to set the filter for. + * @param filter The filter to set. 0 for linear filtering, 1 for nearest neighbor (blocky) filtering. + */ + setTextureFilter(texture: integer, filter: integer): this; + + /** + * [description] + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x [description] + */ + setFloat1(program: WebGLProgram, name: string, x: number): this; + + /** + * [description] + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x [description] + * @param y [description] + */ + setFloat2(program: WebGLProgram, name: string, x: number, y: number): this; + + /** + * [description] + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x [description] + * @param y [description] + * @param z [description] + */ + setFloat3(program: WebGLProgram, name: string, x: number, y: number, z: number): this; + + /** + * Sets uniform of a WebGLProgram + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + */ + setFloat4(program: WebGLProgram, name: string, x: number, y: number, z: number, w: number): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat1v(program: WebGLProgram, name: string, arr: Float32Array): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat2v(program: WebGLProgram, name: string, arr: Float32Array): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat3v(program: WebGLProgram, name: string, arr: Float32Array): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param arr The new value to be used for the uniform variable. + */ + setFloat4v(program: WebGLProgram, name: string, arr: Float32Array): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x [description] + */ + setInt1(program: WebGLProgram, name: string, x: integer): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x The new X component + * @param y The new Y component + */ + setInt2(program: WebGLProgram, name: string, x: integer, y: integer): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x The new X component + * @param y The new Y component + * @param z The new Z component + */ + setInt3(program: WebGLProgram, name: string, x: integer, y: integer, z: integer): this; + + /** + * Sets the value of a uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + */ + setInt4(program: WebGLProgram, name: string, x: integer, y: integer, z: integer, w: integer): this; + + /** + * Sets the value of a 2x2 matrix uniform variable in the given WebGLProgram. + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param transpose The value indicating whether to transpose the matrix. Must be false. + * @param matrix The new matrix value. + */ + setMatrix2(program: WebGLProgram, name: string, transpose: boolean, matrix: Float32Array): this; + + /** + * [description] + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param transpose [description] + * @param matrix [description] + */ + setMatrix3(program: WebGLProgram, name: string, transpose: boolean, matrix: Float32Array): this; + + /** + * Sets uniform of a WebGLProgram + * @param program The target WebGLProgram from which the uniform location will be looked-up. + * @param name The name of the uniform to look-up and modify. + * @param transpose Is the matrix transposed + * @param matrix Matrix data + */ + setMatrix4(program: WebGLProgram, name: string, transpose: boolean, matrix: Float32Array): this; + + /** + * Returns the maximum number of texture units that can be used in a fragment shader. + */ + getMaxTextures(): integer; + + /** + * Returns the largest texture size (either width or height) that can be created. + * Note that VRAM may not allow a texture of any given size, it just expresses + * hardware / driver support for a given size. + */ + getMaxTextureSize(): integer; + + /** + * Destroy this WebGLRenderer, cleaning up all related resources such as pipelines, native textures, etc. + */ + destroy(): void; + + } + + } + + } + + /** + * Phaser Scale Modes. + */ + enum ScaleModes { + /** + * Default Scale Mode (Linear). + */ + DEFAULT, + /** + * Linear Scale Mode. + */ + LINEAR, + /** + * Nearest Scale Mode. + */ + NEAREST, + } + + namespace Scale { + /** + * Phaser Scale Manager constants for centering the game canvas. + */ + enum Center { + /** + * The game canvas is not centered within the parent by Phaser. + * You can still center it yourself via CSS. + */ + NO_CENTER, + /** + * The game canvas is centered both horizontally and vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + */ + CENTER_BOTH, + /** + * The game canvas is centered horizontally within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + */ + CENTER_HORIZONTALLY, + /** + * The game canvas is centered both vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + */ + CENTER_VERTICALLY, + } + + /** + * Phaser Scale Manager constants for centering the game canvas. + * + * To find out what each mode does please see [Phaser.Scale.Center]{@link Phaser.Scale.Center}. + */ + type CenterType = Phaser.Scale.Center; + + /** + * Phaser Scale Manager constants for orientation. + */ + enum Orientation { + /** + * A landscape orientation. + */ + LANDSCAPE, + /** + * A portrait orientation. + */ + PORTRAIT, + } + + /** + * Phaser Scale Manager constants for orientation. + * + * To find out what each mode does please see [Phaser.Scale.Orientation]{@link Phaser.Scale.Orientation}. + */ + type OrientationType = Phaser.Scale.Orientation; + + /** + * Phaser Scale Manager constants for the different scale modes available. + */ + enum ScaleModes { + /** + * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it + * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need + * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. + */ + NONE, + /** + * The height is automatically adjusted based on the width. + */ + WIDTH_CONTROLS_HEIGHT, + /** + * The width is automatically adjusted based on the height. + */ + HEIGHT_CONTROLS_WIDTH, + /** + * 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. + */ + FIT, + /** + * 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. + */ + ENVELOP, + /** + * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. + */ + RESIZE, + } + + /** + * Phaser Scale Manager constants for the different scale modes available. + * + * To find out what each mode does please see [Phaser.Scale.ScaleModes]{@link Phaser.Scale.ScaleModes}. + */ + type ScaleModeType = Phaser.Scale.ScaleModes; + + /** + * Phaser Scale Manager constants for zoom modes. + */ + enum Zoom { + /** + * The game canvas will not be zoomed by Phaser. + */ + NO_ZOOM, + /** + * The game canvas will be 2x zoomed by Phaser. + */ + ZOOM_2X, + /** + * The game canvas will be 4x zoomed by Phaser. + */ + ZOOM_4X, + /** + * 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. + */ + MAX_ZOOM, + } + + /** + * Phaser Scale Manager constants for zoom modes. + * + * To find out what each mode does please see [Phaser.Scale.Zoom]{@link Phaser.Scale.Zoom}. + */ + type ZoomType = Phaser.Scale.Zoom; + + namespace Events { + /** + * The Scale Manager has successfully entered fullscreen mode. + */ + const ENTER_FULLSCREEN: any; + + /** + * The Scale Manager tried to enter fullscreen mode but failed. + */ + const FULLSCREEN_FAILED: any; + + /** + * The Scale Manager tried to enter fullscreen mode, but it is unsupported by the browser. + */ + const FULLSCREEN_UNSUPPORTED: any; + + /** + * The Scale Manager was in fullscreen mode, but has since left, either directly via game code, + * or via a user gestured, such as pressing the ESC key. + */ + const LEAVE_FULLSCREEN: any; + + /** + * The Scale Manager Orientation Change Event. + */ + const ORIENTATION_CHANGE: any; + + /** + * The Scale Manager Resize Event. + * + * This event is dispatched whenever the Scale Manager detects a resize event from the browser. + * It sends three parameters to the callback, each of them being Size components. You can read + * the `width`, `height`, `aspectRatio` and other properties of these components to help with + * scaling your own game content. + */ + const RESIZE: any; + + } + + /** + * 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 extends Phaser.Events.EventEmitter { + /** + * + * @param game A reference to the Phaser.Game instance. + */ + constructor(game: Phaser.Game); + + /** + * A reference to the Phaser.Game instance. + */ + readonly game: Phaser.Game; + + /** + * A reference to the HTML Canvas Element that Phaser uses to render the game. + */ + canvas: HTMLCanvasElement; + + /** + * The DOM bounds of the canvas element. + */ + canvasBounds: Phaser.Geom.Rectangle; + + /** + * The parent object of the Canvas. Often a div, or the browser window, or nothing in non-browser environments. + * + * This is set in the Game Config as the `parent` property. If undefined (or just not present), it will default + * to use the document body. If specifically set to `null` Phaser will ignore all parent operations. + */ + parent: any; + + /** + * Is the parent element the browser window? + */ + parentIsWindow: boolean; + + /** + * The Parent Size component. + */ + parentSize: Phaser.Structs.Size; + + /** + * The Game Size component. + * + * The un-modified game size, as requested in the game config (the raw width / height), + * as used for world bounds, cameras, etc + */ + gameSize: Phaser.Structs.Size; + + /** + * The Base Size component. + * + * The modified game size, which is the gameSize * resolution, used to set the canvas width and height + * (but not the CSS style) + */ + baseSize: Phaser.Structs.Size; + + /** + * The Display Size component. + * + * The size used for the canvas style, factoring in the scale mode, parent and other values. + */ + displaySize: Phaser.Structs.Size; + + /** + * The game scale mode. + */ + scaleMode: Phaser.Scale.ScaleModeType; + + /** + * The canvas resolution. + * + * This is hard-coded to a value of 1 in the 3.16 release of Phaser and will be enabled at a later date. + */ + resolution: number; + + /** + * The game zoom factor. + * + * This value allows you to multiply your games base size by the given zoom factor. + * This is then used when calculating the display size, even in `NONE` situations. + * If you don't want Phaser to touch the canvas style at all, this value should be 1. + * + * Can also be set to `MAX_ZOOM` in which case the zoom value will be derived based + * on the game size and available space within the parent. + */ + zoom: number; + + /** + * Internal flag set when the game zoom factor is modified. + */ + readonly _resetZoom: boolean; + + /** + * The scale factor between the baseSize and the canvasBounds. + */ + displayScale: Phaser.Math.Vector2; + + /** + * If set, the canvas sizes will be automatically passed through Math.floor. + * This results in rounded pixel display values, which is important for performance on legacy + * and low powered devices, but at the cost of not achieving a 'perfect' fit in some browser windows. + */ + autoRound: boolean; + + /** + * Automatically center the canvas within the parent? The different centering modes are: + * + * 1. No centering. + * 2. Center both horizontally and vertically. + * 3. Center horizontally. + * 4. Center vertically. + * + * Please be aware that in order to center the game canvas, you must have specified a parent + * that has a size set, or the canvas parent is the document.body. + */ + autoCenter: Phaser.Scale.CenterType; + + /** + * The current device orientation. + * + * Orientation events are dispatched via the Device Orientation API, typically only on mobile browsers. + */ + orientation: Phaser.Scale.OrientationType; + + /** + * A reference to the Device.Fullscreen object. + */ + fullscreen: Phaser.Device.Fullscreen; + + /** + * The DOM Element which is sent into fullscreen mode. + */ + fullscreenTarget: any; + + /** + * The dirty state of the Scale Manager. + * Set if there is a change between the parent size and the current size. + */ + dirty: boolean; + + /** + * 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. + */ + resizeInterval: integer; + + /** + * Called _before_ the canvas object is created and added to the DOM. + */ + protected preBoot(): void; + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * The renderer is available by now and the canvas has been added to the DOM. + */ + protected boot(): void; + + /** + * Parses the game configuration to set-up the scale defaults. + * @param config The Game configuration object. + */ + protected parseConfig(config: Phaser.Types.Core.GameConfig): void; + + /** + * Determines the parent element of the game canvas, if any, based on the game configuration. + * @param config The Game configuration object. + */ + getParent(config: Phaser.Types.Core.GameConfig): void; + + /** + * Calculates the size of the parent bounds and updates the `parentSize` component, if the canvas has a dom parent. + */ + getParentBounds(): boolean; + + /** + * 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. + * @param orientation The orientation you'd like to lock the browser in. Should be an API string such as 'landscape', 'landscape-primary', 'portrait', etc. + */ + lockOrientation(orientation: string): boolean; + + /** + * This method will set the size of the Parent Size component, which is used in scaling + * and centering calculations. You only need to call this method if you have explicitly + * disabled the use of a parent in your game config, but still wish to take advantage of + * other Scale Manager features. + * @param width The new width of the parent. + * @param height The new height of the parent. + */ + setParentSize(width: number, height: number): this; + + /** + * This method will set a new size for your game. + * + * It should only be used if you're looking to change the base size of your game and are using + * one of the Scale Manager scaling modes, i.e. `FIT`. If you're using `NONE` and wish to + * change the game and canvas size directly, then please use the `resize` method instead. + * @param width The new width of the game. + * @param height The new height of the game. + */ + setGameSize(width: number, height: number): this; + + /** + * 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. + * @param width The new width of the game. + * @param height The new height of the game. + */ + resize(width: number, height: number): this; + + /** + * Sets the zoom value of the Scale Manager. + * @param value The new zoom value of the game. + */ + setZoom(value: integer): this; + + /** + * Sets the zoom to be the maximum possible based on the _current_ parent size. + */ + setMaxZoom(): this; + + /** + * Refreshes the internal scale values, bounds sizes and orientation checks. + * + * Once finished, dispatches the resize event. + * + * This is called automatically by the Scale Manager when the browser window size changes, + * as long as it is using a Scale Mode other than 'NONE'. + * @param previousWidth The previous width of the game. Only set if the gameSize has changed. + * @param previousHeight The previous height of the game. Only set if the gameSize has changed. + */ + refresh(previousWidth?: number, previousHeight?: number): this; + + /** + * Internal method that checks the current screen orientation, only if the internal check flag is set. + * + * If the orientation has changed it updates the orientation property and then dispatches the orientation change event. + */ + updateOrientation(): void; + + /** + * Internal method that manages updating the size components based on the scale mode. + */ + updateScale(): void; + + /** + * 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) + */ + getMaxZoom(): integer; + + /** + * Calculates and updates the canvas CSS style in order to center it within the + * bounds of its parent. If you have explicitly set parent to be `null` in your + * game config then this method will likely give incorrect results unless you have called the + * `setParentSize` method first. + * + * It works by modifying the canvas CSS `marginLeft` and `marginTop` properties. + * + * If they have already been set by your own style sheet, or code, this will overwrite them. + * + * To prevent the Scale Manager from centering the canvas, either do not set the + * `autoCenter` property in your game config, or make sure it is set to `NO_CENTER`. + */ + updateCenter(): void; + + /** + * Updates the `canvasBounds` rectangle to match the bounding client rectangle of the + * canvas element being used to track input events. + */ + updateBounds(): void; + + /** + * Transforms the pageX value into the scaled coordinate space of the Scale Manager. + * @param pageX The DOM pageX value. + */ + transformX(pageX: number): number; + + /** + * Transforms the pageY value into the scaled coordinate space of the Scale Manager. + * @param pageY The DOM pageY value. + */ + transformY(pageY: number): number; + + /** + * 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 user-input gesture, such as `pointerup`. 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 `
` element and move the canvas into it, before going fullscreen. + * When it leaves fullscreen, the div will be removed. + * @param fullscreenOptions The FullscreenOptions dictionary is used to provide configuration options when entering full screen. + */ + startFullscreen(fullscreenOptions?: object): void; + + /** + * An internal method that gets the target element that is used when entering fullscreen mode. + */ + getFullscreenTarget(): object; + + /** + * Removes the fullscreen target that was added to the DOM. + */ + removeFullscreenTarget(): void; + + /** + * Calling this method will cancel fullscreen mode, if the browser has entered it. + */ + stopFullscreen(): void; + + /** + * Toggles the fullscreen mode. If already in fullscreen, calling this will cancel it. + * If not in fullscreen, this will request the browser to enter fullscreen mode. + * + * If the browser does not support this, a `FULLSCREEN_UNSUPPORTED` event will be emitted. + * + * This method _must_ be called from a user-input gesture, such as `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. + * @param fullscreenOptions The FullscreenOptions dictionary is used to provide configuration options when entering full screen. + */ + toggleFullscreen(fullscreenOptions?: object): void; + + /** + * An internal method that starts the different DOM event listeners running. + */ + startListeners(): void; + + /** + * Triggered when a fullscreenchange event is dispatched by the DOM. + */ + onFullScreenChange(): void; + + /** + * Triggered when a fullscreenerror event is dispatched by the DOM. + */ + onFullScreenError(): void; + + /** + * Internal method, called automatically by the game step. + * Monitors the elapsed time and resize interval to see if a parent bounds check needs to take place. + * @param time The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). + * @param delta The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. + */ + step(time: number, delta: number): void; + + /** + * Stops all DOM event listeners. + */ + stopListeners(): void; + + /** + * Destroys this Scale Manager, releasing all references to external resources. + * Once destroyed, the Scale Manager cannot be used again. + */ + destroy(): void; + + /** + * Is the browser currently in fullscreen mode or not? + */ + readonly isFullscreen: boolean; + + /** + * The game width. + * + * This is typically the size given in the game configuration. + */ + readonly width: number; + + /** + * The game height. + * + * This is typically the size given in the game configuration. + */ + readonly height: number; + + /** + * Is the device in a portrait orientation as reported by the Orientation API? + * This value is usually only available on mobile devices. + */ + readonly isPortrait: boolean; + + /** + * Is the device in a landscape orientation as reported by the Orientation API? + * This value is usually only available on mobile devices. + */ + readonly isLandscape: boolean; + + /** + * Are the game dimensions portrait? (i.e. taller than they are wide) + * + * This is different to the device itself being in a portrait orientation. + */ + readonly isGamePortrait: boolean; + + /** + * Are the game dimensions landscape? (i.e. wider than they are tall) + * + * This is different to the device itself being in a landscape orientation. + */ + readonly isGameLandscape: boolean; + + } + + /** + * The game canvas is not centered within the parent by Phaser. + * You can still center it yourself via CSS. + */ + const NO_CENTER: integer; + + /** + * The game canvas is centered both horizontally and vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + */ + const CENTER_BOTH: integer; + + /** + * The game canvas is centered horizontally within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + */ + const CENTER_HORIZONTALLY: integer; + + /** + * The game canvas is centered both vertically within the parent. + * To do this, the parent has to have a bounds that can be calculated and not be empty. + * + * Centering is achieved by setting the margin left and top properties of the + * game canvas, and does not factor in any other CSS styles you may have applied. + */ + const CENTER_VERTICALLY: integer; + + /** + * A landscape orientation. + */ + const LANDSCAPE: string; + + /** + * A portrait orientation. + */ + const PORTRAIT: string; + + /** + * No scaling happens at all. The canvas is set to the size given in the game config and Phaser doesn't change it + * again from that point on. If you change the canvas size, either via CSS, or directly via code, then you need + * to call the Scale Managers `resize` method to give the new dimensions, or input events will stop working. + */ + const NONE: integer; + + /** + * The height is automatically adjusted based on the width. + */ + const WIDTH_CONTROLS_HEIGHT: integer; + + /** + * The width is automatically adjusted based on the height. + */ + const HEIGHT_CONTROLS_WIDTH: integer; + + /** + * 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. + */ + const FIT: integer; + + /** + * 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. + */ + const ENVELOP: integer; + + /** + * The Canvas is resized to fit all available _parent_ space, regardless of aspect ratio. + */ + const RESIZE: integer; + + /** + * The game canvas will not be zoomed by Phaser. + */ + const NO_ZOOM: integer; + + /** + * The game canvas will be 2x zoomed by Phaser. + */ + const ZOOM_2X: integer; + + /** + * The game canvas will be 4x zoomed by Phaser. + */ + const ZOOM_4X: integer; + + /** + * 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. + */ + const MAX_ZOOM: integer; + + } + + namespace Scenes { + /** + * Scene state. + */ + var PENDING: integer; + + /** + * Scene state. + */ + var INIT: integer; + + /** + * Scene state. + */ + var START: integer; + + /** + * Scene state. + */ + var LOADING: integer; + + /** + * Scene state. + */ + var CREATING: integer; + + /** + * Scene state. + */ + var RUNNING: integer; + + /** + * Scene state. + */ + var PAUSED: integer; + + /** + * Scene state. + */ + var SLEEPING: integer; + + /** + * Scene state. + */ + var SHUTDOWN: integer; + + /** + * Scene state. + */ + var DESTROYED: integer; + + namespace Events { + /** + * The Scene Systems Boot Event. + * + * This event is dispatched by a Scene during the Scene Systems boot process. Primarily used by Scene Plugins. + * + * Listen to it from a Scene using `this.scene.events.on('boot', listener)`. + */ + const BOOT: any; + + /** + * The Scene Create Event. + * + * This event is dispatched by a Scene after it has been created by the Scene Manager. + * + * If a Scene has a `create` method then this event is emitted _after_ that has run. + * + * If there is a transition, this event will be fired after the `TRANSITION_START` event. + * + * Listen to it from a Scene using `this.scene.events.on('create', listener)`. + */ + const CREATE: any; + + /** + * The Scene Systems Destroy Event. + * + * This event is dispatched by a Scene during the Scene Systems destroy process. + * + * Listen to it from a Scene using `this.scene.events.on('destroy', listener)`. + * + * You should destroy any resources that may be in use by your Scene in this event handler. + */ + const DESTROY: any; + + /** + * The Scene Systems Pause Event. + * + * This event is dispatched by a Scene when it is paused, either directly via the `pause` method, or as an + * action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('pause', listener)`. + */ + const PAUSE: any; + + /** + * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('postupdate', listener)`. + * + * A Scene will only run its step if it is active. + */ + const POST_UPDATE: any; + + /** + * 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('preupdate', listener)`. + * + * A Scene will only run its step if it is active. + */ + const PRE_UPDATE: any; + + /** + * The Scene Systems Ready Event. + * + * This event is dispatched by a Scene during the Scene Systems start process. + * By this point in the process the Scene is now fully active and rendering. + * This event is meant for your game code to use, as all plugins have responded to the earlier 'start' event. + * + * Listen to it from a Scene using `this.scene.events.on('ready', listener)`. + */ + const READY: any; + + /** + * The Scene Systems Render 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. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('render', listener)`. + * + * A Scene will only render if it is visible and active. + * By the time this event is dispatched, the Scene will have already been rendered. + */ + const RENDER: any; + + /** + * The Scene Systems Resume Event. + * + * This event is dispatched by a Scene when it is resumed from a paused state, either directly via the `resume` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('resume', listener)`. + */ + const RESUME: any; + + /** + * The Scene Systems Shutdown Event. + * + * This event is dispatched by a Scene during the Scene Systems shutdown process. + * + * Listen to it from a Scene using `this.scene.events.on('shutdown', listener)`. + * + * You should free-up any resources that may be in use by your Scene in this event handler, on the understanding + * that the Scene may, at any time, become active again. A shutdown Scene is not 'destroyed', it's simply not + * currently active. Use the [DESTROY]{@linkcode Phaser.Scenes.Events#event:DESTROY} event to completely clear resources. + */ + const SHUTDOWN: any; + + /** + * The Scene Systems Sleep Event. + * + * This event is dispatched by a Scene when it is sent to sleep, either directly via the `sleep` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('sleep', listener)`. + */ + const SLEEP: any; + + /** + * The Scene Systems Start Event. + * + * This event is dispatched by a Scene during the Scene Systems start process. Primarily used by Scene Plugins. + * + * Listen to it from a Scene using `this.scene.events.on('start', listener)`. + */ + const START: any; + + /** + * The Scene Transition Complete Event. + * + * This event is dispatched by the Target Scene of a transition. + * + * It happens when the transition process has completed. This occurs when the duration timer equals or exceeds the duration + * of the transition. + * + * Listen to it from a Scene using `this.scene.events.on('transitioncomplete', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + */ + const TRANSITION_COMPLETE: any; + + /** + * The Scene Transition Init Event. + * + * This event is dispatched by the Target Scene of a transition. + * + * It happens immediately after the `Scene.init` method is called. If the Scene does not have an `init` method, + * this event is not dispatched. + * + * Listen to it from a Scene using `this.scene.events.on('transitioninit', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + */ + const TRANSITION_INIT: any; + + /** + * The Scene Transition Out Event. + * + * This event is dispatched by a Scene when it initiates a transition to another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('transitionout', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + */ + const TRANSITION_OUT: any; + + /** + * The Scene Transition Start Event. + * + * This event is dispatched by the Target Scene of a transition, only if that Scene was not asleep. + * + * It happens immediately after the `Scene.create` method is called. If the Scene does not have a `create` method, + * this event is dispatched anyway. + * + * If the Target Scene was sleeping then the [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} event is + * dispatched instead of this event. + * + * Listen to it from a Scene using `this.scene.events.on('transitionstart', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + */ + const TRANSITION_START: any; + + /** + * The Scene Transition Wake Event. + * + * This event is dispatched by the Target Scene of a transition, only if that Scene was asleep before + * the transition began. If the Scene was not asleep the [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} event is dispatched instead. + * + * Listen to it from a Scene using `this.scene.events.on('transitionwake', listener)`. + * + * The Scene Transition event flow is as follows: + * + * 1. [TRANSITION_OUT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_OUT} - the Scene that started the transition will emit this event. + * 2. [TRANSITION_INIT]{@linkcode Phaser.Scenes.Events#event:TRANSITION_INIT} - the Target Scene will emit this event if it has an `init` method. + * 3. [TRANSITION_START]{@linkcode Phaser.Scenes.Events#event:TRANSITION_START} - the Target Scene will emit this event after its `create` method is called, OR ... + * 4. [TRANSITION_WAKE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_WAKE} - the Target Scene will emit this event if it was asleep and has been woken-up to be transitioned to. + * 5. [TRANSITION_COMPLETE]{@linkcode Phaser.Scenes.Events#event:TRANSITION_COMPLETE} - the Target Scene will emit this event when the transition finishes. + */ + const TRANSITION_WAKE: any; + + /** + * 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 + * 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE} + * 5. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER} + * + * Listen to it from a Scene using `this.scene.events.on('update', listener)`. + * + * A Scene will only run its step if it is active. + */ + const UPDATE: any; + + /** + * The Scene Systems Wake Event. + * + * This event is dispatched by a Scene when it is woken from sleep, either directly via the `wake` method, + * or as an action from another Scene. + * + * Listen to it from a Scene using `this.scene.events.on('wake', listener)`. + */ + const WAKE: any; + + } + + /** + * Builds an array of which physics plugins should be activated for the given Scene. + * @param sys The scene system to get the physics systems of. + */ + function GetPhysicsPlugins(sys: Phaser.Scenes.Systems): any[]; + + /** + * Builds an array of which plugins (not including physics plugins) should be activated for the given Scene. + * @param sys The Scene Systems object to check for plugins. + */ + function GetScenePlugins(sys: Phaser.Scenes.Systems): any[]; + + /** + * The Scene Manager. + * + * The Scene Manager is a Game level system, responsible for creating, processing and updating all of the + * Scenes in a Game instance. + */ + class SceneManager { + /** + * + * @param game The Phaser.Game instance this Scene Manager belongs to. + * @param sceneConfig Scene specific configuration settings. + */ + constructor(game: Phaser.Game, sceneConfig: object); + + /** + * The Game that this SceneManager belongs to. + */ + game: Phaser.Game; + + /** + * An object that maps the keys to the scene so we can quickly get a scene from a key without iteration. + */ + keys: object; + + /** + * The array in which all of the scenes are kept. + */ + scenes: any[]; + + /** + * Is the Scene Manager actively processing the Scenes list? + */ + readonly isProcessing: boolean; + + /** + * Has the Scene Manager properly started? + */ + readonly isBooted: boolean; + + /** + * Do any of the Cameras in any of the Scenes require a custom viewport? + * If not we can skip scissor tests. + */ + customViewports: number; + + /** + * Process the Scene operations queue. + */ + processQueue(): void; + + /** + * Adds a new Scene into the SceneManager. + * You must give each Scene a unique key by which you'll identify it. + * + * The `sceneConfig` can be: + * + * * A `Phaser.Scene` object, or an object that extends it. + * * A plain JavaScript object + * * A JavaScript ES6 Class that extends `Phaser.Scene` + * * A JavaScript ES5 prototype based Class + * * A JavaScript function + * + * If a function is given then a new Scene will be created by calling it. + * @param key A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. + * @param sceneConfig The config for the Scene + * @param autoStart If `true` the Scene will be started immediately after being added. Default false. + * @param data Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. + */ + add(key: string, sceneConfig: Phaser.Scene | Phaser.Types.Scenes.SettingsConfig | Phaser.Types.Scenes.CreateSceneFromObjectConfig | Function, autoStart?: boolean, data?: object): Phaser.Scene; + + /** + * Removes a Scene from the SceneManager. + * + * The Scene is removed from the local scenes array, it's key is cleared from the keys + * cache and Scene.Systems.destroy is then called on it. + * + * If the SceneManager is processing the Scenes when this method is called it will + * queue the operation for the next update sequence. + * @param key A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. + */ + remove(key: string): Phaser.Scenes.SceneManager; + + /** + * Updates the Scenes. + * @param time Time elapsed. + * @param delta Delta time from the last update. + */ + update(time: number, delta: number): void; + + /** + * Renders the Scenes. + * @param renderer The renderer to use. + */ + render(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; + + /** + * Returns an array of all the current Scenes being managed by this Scene Manager. + * + * You can filter the output by the active state of the Scene and choose to have + * the array returned in normal or reversed order. + * @param isActive Only include Scene's that are currently active? Default true. + * @param inReverse Return the array of Scenes in reverse? Default false. + */ + getScenes(isActive?: boolean, inReverse?: boolean): Phaser.Scene[]; + + /** + * Retrieves a Scene. + * @param key The Scene to retrieve. + */ + getScene(key: string | Phaser.Scene): Phaser.Scene; + + /** + * Determines whether a Scene is running. + * @param key The Scene to check. + */ + isActive(key: string): boolean; + + /** + * Determines whether a Scene is paused. + * @param key The Scene to check. + */ + isPaused(key: string): boolean; + + /** + * Determines whether a Scene is visible. + * @param key The Scene to check. + */ + isVisible(key: string): boolean; + + /** + * Determines whether a Scene is sleeping. + * @param key The Scene to check. + */ + isSleeping(key: string): boolean; + + /** + * Pauses the given Scene. + * @param key The Scene to pause. + * @param data An optional data object that will be passed to the Scene and emitted by its pause event. + */ + pause(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Resumes the given Scene. + * @param key The Scene to resume. + * @param data An optional data object that will be passed to the Scene and emitted by its resume event. + */ + resume(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Puts the given Scene to sleep. + * @param key The Scene to put to sleep. + * @param data An optional data object that will be passed to the Scene and emitted by its sleep event. + */ + sleep(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Awakens the given Scene. + * @param key The Scene to wake up. + * @param data An optional data object that will be passed to the Scene and emitted by its wake event. + */ + wake(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Runs the given Scene. + * + * If the given Scene is paused, it will resume it. If sleeping, it will wake it. + * If not running at all, it will be started. + * + * Use this if you wish to open a modal Scene by calling `pause` on the current + * Scene, then `run` on the modal Scene. + * @param key The Scene to run. + * @param data A data object that will be passed to the Scene on start, wake, or resume. + */ + run(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Starts the given Scene. + * @param key The Scene to start. + * @param data Optional data object to pass to Scene.Settings and Scene.init. + */ + start(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Stops the given Scene. + * @param key The Scene to stop. + * @param data Optional data object to pass to Scene.shutdown. + */ + stop(key: string, data?: object): Phaser.Scenes.SceneManager; + + /** + * Sleeps one one Scene and starts the other. + * @param from The Scene to sleep. + * @param to The Scene to start. + */ + switch(from: string, to: string): Phaser.Scenes.SceneManager; + + /** + * Retrieves a Scene by numeric index. + * @param index The index of the Scene to retrieve. + */ + getAt(index: integer): Phaser.Scene | undefined; + + /** + * Retrieves the numeric index of a Scene. + * @param key The key of the Scene. + */ + getIndex(key: string | Phaser.Scene): integer; + + /** + * Brings a Scene to the top of the Scenes list. + * + * This means it will render above all other Scenes. + * @param key The Scene to move. + */ + bringToTop(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Sends a Scene to the back of the Scenes list. + * + * This means it will render below all other Scenes. + * @param key The Scene to move. + */ + sendToBack(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Moves a Scene down one position in the Scenes list. + * @param key The Scene to move. + */ + moveDown(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Moves a Scene up one position in the Scenes list. + * @param key The Scene to move. + */ + moveUp(key: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Moves a Scene so it is immediately above another Scene in the Scenes list. + * + * This means it will render over the top of the other Scene. + * @param keyA The Scene that Scene B will be moved above. + * @param keyB The Scene to be moved. + */ + moveAbove(keyA: string | Phaser.Scene, keyB: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Moves a Scene so it is immediately below another Scene in the Scenes list. + * + * This means it will render behind the other Scene. + * @param keyA The Scene that Scene B will be moved above. + * @param keyB The Scene to be moved. + */ + moveBelow(keyA: string | Phaser.Scene, keyB: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Swaps the positions of two Scenes in the Scenes list. + * @param keyA The first Scene to swap. + * @param keyB The second Scene to swap. + */ + swapPosition(keyA: string | Phaser.Scene, keyB: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Dumps debug information about each Scene to the developer console. + */ + dump(): void; + + /** + * Destroy the SceneManager and all of its Scene's systems. + */ + destroy(): void; + + } + + /** + * A proxy class to the Global Scene Manager. + */ + class ScenePlugin { + /** + * + * @param scene The Scene that this ScenePlugin belongs to. + */ + constructor(scene: Phaser.Scene); + + /** + * The Scene that this ScenePlugin belongs to. + */ + scene: Phaser.Scene; + + /** + * The Scene Systems instance of the Scene that this ScenePlugin belongs to. + */ + systems: Phaser.Scenes.Systems; + + /** + * The settings of the Scene this ScenePlugin belongs to. + */ + settings: Phaser.Types.Scenes.SettingsObject; + + /** + * The key of the Scene this ScenePlugin belongs to. + */ + key: string; + + /** + * The Game's SceneManager. + */ + manager: Phaser.Scenes.SceneManager; + + /** + * If this Scene is currently transitioning to another, this holds + * the current percentage of the transition progress, between 0 and 1. + */ + transitionProgress: number; + + /** + * Shutdown this Scene and run the given one. + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to start. + * @param data The Scene data. + */ + start(key?: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Restarts this Scene. + * + * This will happen at the next Scene Manager update, not immediately. + * @param data The Scene data. + */ + restart(data?: object): Phaser.Scenes.ScenePlugin; + + /** + * This will start a transition from the current Scene to the target Scene given. + * + * The transition will last for the duration specified in milliseconds. + * + * You can have the target Scene moved above or below this one in the display list. + * + * You can specify an update callback. This callback will be invoked _every frame_ for the duration + * of the transition. + * + * This Scene can either be sent to sleep at the end of the transition, or stopped. The default is to stop. + * + * There are also 5 transition related events: This scene will emit the event `transitionout` when + * the transition begins, which is typically the frame after calling this method. + * + * The target Scene will emit the event `transitioninit` when that Scene's `init` method is called. + * It will then emit the event `transitionstart` when its `create` method is called. + * If the Scene was sleeping and has been woken up, it will emit the event `transitionwake` instead of these two, + * as the Scenes `init` and `create` methods are not invoked when a Scene wakes up. + * + * When the duration of the transition has elapsed it will emit the event `transitioncomplete`. + * These events are cleared of all listeners when the Scene shuts down, but not if it is sent to sleep. + * + * It's important to understand that the duration of the transition begins the moment you call this method. + * If the Scene you are transitioning to includes delayed processes, such as waiting for files to load, the + * time still counts down even while that is happening. If the game itself pauses, or something else causes + * this Scenes update loop to stop, then the transition will also pause for that duration. There are + * checks in place to prevent you accidentally stopping a transitioning Scene but if you've got code to + * override this understand that until the target Scene completes it might never be unlocked for input events. + * @param config The transition configuration object. + */ + transition(config: Phaser.Types.Scenes.SceneTransitionConfig): boolean; + + /** + * Add the Scene into the Scene Manager and start it if 'autoStart' is true or the Scene config 'active' property is set. + * @param key The Scene key. + * @param sceneConfig The config for the Scene. + * @param autoStart Whether to start the Scene after it's added. + * @param data Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. + */ + add(key: string, sceneConfig: Phaser.Scene | Phaser.Types.Scenes.SettingsConfig | Phaser.Types.Scenes.CreateSceneFromObjectConfig | Function, autoStart: boolean, data?: object): Phaser.Scene; + + /** + * Launch the given Scene and run it in parallel with this one. + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to launch. + * @param data The Scene data. + */ + launch(key: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Runs the given Scene, but does not change the state of this Scene. + * + * This will happen at the next Scene Manager update, not immediately. + * + * If the given Scene is paused, it will resume it. If sleeping, it will wake it. + * If not running at all, it will be started. + * + * Use this if you wish to open a modal Scene by calling `pause` on the current + * Scene, then `run` on the modal Scene. + * @param key The Scene to run. + * @param data A data object that will be passed to the Scene and emitted in its ready, wake, or resume events. + */ + run(key: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Pause the Scene - this stops the update step from happening but it still renders. + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to pause. + * @param data An optional data object that will be passed to the Scene and emitted in its pause event. + */ + pause(key?: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Resume the Scene - starts the update loop again. + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to resume. + * @param data An optional data object that will be passed to the Scene and emitted in its resume event. + */ + resume(key?: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Makes the Scene sleep (no update, no render) but doesn't shutdown. + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to put to sleep. + * @param data An optional data object that will be passed to the Scene and emitted in its sleep event. + */ + sleep(key?: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Makes the Scene wake-up (starts update and render) + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to wake up. + * @param data An optional data object that will be passed to the Scene and emitted in its wake event. + */ + wake(key?: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Makes this Scene sleep then starts the Scene given. + * + * This will happen at the next Scene Manager update, not immediately. + * @param key The Scene to start. + */ + switch(key: string): Phaser.Scenes.ScenePlugin; + + /** + * Shutdown the Scene, clearing display list, timers, etc. + * + * This happens at the next Scene Manager update, not immediately. + * @param key The Scene to stop. + * @param data Optional data object to pass to Scene.Systems.shutdown. + */ + stop(key?: string, data?: any): Phaser.Scenes.ScenePlugin; + + /** + * Sets the active state of the given Scene. + * @param value If `true` the Scene will be resumed. If `false` it will be paused. + * @param key The Scene to set the active state of. + * @param data An optional data object that will be passed to the Scene and emitted with its events. + */ + setActive(value: boolean, key?: string, data?: object): Phaser.Scenes.ScenePlugin; + + /** + * Sets the visible state of the given Scene. + * @param value The visible value. + * @param key The Scene to set the visible state for. + */ + setVisible(value: boolean, key?: string): Phaser.Scenes.ScenePlugin; + + /** + * Checks if the given Scene is sleeping or not? + * @param key The Scene to check. + */ + isSleeping(key?: string): boolean; + + /** + * Checks if the given Scene is running or not? + * @param key The Scene to check. + */ + isActive(key?: string): boolean; + + /** + * Checks if the given Scene is paused or not? + * @param key The Scene to check. + */ + isPaused(key?: string): boolean; + + /** + * Checks if the given Scene is visible or not? + * @param key The Scene to check. + */ + isVisible(key?: string): boolean; + + /** + * Swaps the position of two scenes in the Scenes list. + * + * This controls the order in which they are rendered and updated. + * @param keyA The first Scene to swap. + * @param keyB The second Scene to swap. If none is given it defaults to this Scene. + */ + swapPosition(keyA: string, keyB?: string): Phaser.Scenes.ScenePlugin; + + /** + * Swaps the position of two scenes in the Scenes list, so that Scene B is directly above Scene A. + * + * This controls the order in which they are rendered and updated. + * @param keyA The Scene that Scene B will be moved to be above. + * @param keyB The Scene to be moved. If none is given it defaults to this Scene. + */ + moveAbove(keyA: string, keyB?: string): Phaser.Scenes.ScenePlugin; + + /** + * Swaps the position of two scenes in the Scenes list, so that Scene B is directly below Scene A. + * + * This controls the order in which they are rendered and updated. + * @param keyA The Scene that Scene B will be moved to be below. + * @param keyB The Scene to be moved. If none is given it defaults to this Scene. + */ + moveBelow(keyA: string, keyB?: string): Phaser.Scenes.ScenePlugin; + + /** + * Removes a Scene from the SceneManager. + * + * The Scene is removed from the local scenes array, it's key is cleared from the keys + * cache and Scene.Systems.destroy is then called on it. + * + * If the SceneManager is processing the Scenes when this method is called it will + * queue the operation for the next update sequence. + * @param key The Scene to be removed. + */ + remove(key?: string | Phaser.Scene): Phaser.Scenes.SceneManager; + + /** + * Moves a Scene up one position in the Scenes list. + * @param key The Scene to move. + */ + moveUp(key?: string): Phaser.Scenes.ScenePlugin; + + /** + * Moves a Scene down one position in the Scenes list. + * @param key The Scene to move. + */ + moveDown(key?: string): Phaser.Scenes.ScenePlugin; + + /** + * Brings a Scene to the top of the Scenes list. + * + * This means it will render above all other Scenes. + * @param key The Scene to move. + */ + bringToTop(key?: string): Phaser.Scenes.ScenePlugin; + + /** + * Sends a Scene to the back of the Scenes list. + * + * This means it will render below all other Scenes. + * @param key The Scene to move. + */ + sendToBack(key?: string): Phaser.Scenes.ScenePlugin; + + /** + * Retrieve a Scene. + * @param key The Scene to retrieve. + */ + get(key: string): Phaser.Scene; + + /** + * Retrieves the numeric index of a Scene in the Scenes list. + * @param key The Scene to get the index of. + */ + getIndex(key?: string | Phaser.Scene): integer; + + } + + namespace Settings { + /** + * Takes a Scene configuration object and returns a fully formed System Settings object. + * @param config The Scene configuration object used to create this Scene Settings. + */ + function create(config: string | Phaser.Types.Scenes.SettingsConfig): Phaser.Types.Scenes.SettingsObject; + + } + + /** + * The Scene Systems class. + * + * This class is available from within a Scene under the property `sys`. + * It is responsible for managing all of the plugins a Scene has running, including the display list, and + * handling the update step and renderer. It also contains references to global systems belonging to Game. + */ + class Systems { + /** + * + * @param scene The Scene that owns this Systems instance. + * @param config Scene specific configuration settings. + */ + constructor(scene: Phaser.Scene, config: string | Phaser.Types.Scenes.SettingsConfig); + + /** + * A reference to the Scene that these Systems belong to. + */ + scene: Phaser.Scene; + + /** + * A reference to the Phaser Game instance. + */ + game: Phaser.Game; + + /** + * A reference to either the Canvas or WebGL Renderer that this Game is using. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * The Facebook Instant Games Plugin. + */ + facebook: Phaser.FacebookInstantGamesPlugin; + + /** + * The Scene Configuration object, as passed in when creating the Scene. + */ + config: string | Phaser.Types.Scenes.SettingsConfig; + + /** + * The Scene Settings. This is the parsed output based on the Scene configuration. + */ + settings: Phaser.Types.Scenes.SettingsObject; + + /** + * A handy reference to the Scene canvas / context. + */ + canvas: HTMLCanvasElement; + + /** + * A reference to the Canvas Rendering Context being used by the renderer. + */ + context: CanvasRenderingContext2D; + + /** + * A reference to the global Animations Manager. + * + * In the default set-up you can access this from within a Scene via the `this.anims` property. + */ + anims: Phaser.Animations.AnimationManager; + + /** + * A reference to the global Cache. The Cache stores all files bought in to Phaser via + * the Loader, with the exception of images. Images are stored in the Texture Manager. + * + * In the default set-up you can access this from within a Scene via the `this.cache` property. + */ + cache: Phaser.Cache.CacheManager; + + /** + * A reference to the global Plugins Manager. + * + * In the default set-up you can access this from within a Scene via the `this.plugins` property. + */ + plugins: Phaser.Plugins.PluginManager; + + /** + * A reference to the global registry. This is a game-wide instance of the Data Manager, allowing + * you to exchange data between Scenes via a universal and shared point. + * + * In the default set-up you can access this from within a Scene via the `this.registry` property. + */ + registry: Phaser.Data.DataManager; + + /** + * A reference to the global Scale Manager. + * + * In the default set-up you can access this from within a Scene via the `this.scale` property. + */ + scale: Phaser.Scale.ScaleManager; + + /** + * A reference to the global Sound Manager. + * + * In the default set-up you can access this from within a Scene via the `this.sound` property. + */ + sound: Phaser.Sound.NoAudioSoundManager | Phaser.Sound.HTML5AudioSoundManager | Phaser.Sound.WebAudioSoundManager; + + /** + * A reference to the global Texture Manager. + * + * In the default set-up you can access this from within a Scene via the `this.textures` property. + */ + textures: Phaser.Textures.TextureManager; + + /** + * A reference to the Scene's Game Object Factory. + * + * Use this to quickly and easily create new Game Object's. + * + * In the default set-up you can access this from within a Scene via the `this.add` property. + */ + add: Phaser.GameObjects.GameObjectFactory; + + /** + * A reference to the Scene's Camera Manager. + * + * Use this to manipulate and create Cameras for this specific Scene. + * + * In the default set-up you can access this from within a Scene via the `this.cameras` property. + */ + cameras: Phaser.Cameras.Scene2D.CameraManager; + + /** + * A reference to the Scene's Display List. + * + * Use this to organize the children contained in the display list. + * + * In the default set-up you can access this from within a Scene via the `this.children` property. + */ + displayList: Phaser.GameObjects.DisplayList; + + /** + * A reference to the Scene's Event Manager. + * + * Use this to listen for Scene specific events, such as `pause` and `shutdown`. + * + * In the default set-up you can access this from within a Scene via the `this.events` property. + */ + events: Phaser.Events.EventEmitter; + + /** + * A reference to the Scene's Game Object Creator. + * + * Use this to quickly and easily create new Game Object's. The difference between this and the + * Game Object Factory, is that the Creator just creates and returns Game Object instances, it + * doesn't then add them to the Display List or Update List. + * + * In the default set-up you can access this from within a Scene via the `this.make` property. + */ + make: Phaser.GameObjects.GameObjectCreator; + + /** + * A reference to the Scene Manager Plugin. + * + * Use this to manipulate both this and other Scene's in your game, for example to launch a parallel Scene, + * or pause or resume a Scene, or switch from this Scene to another. + * + * In the default set-up you can access this from within a Scene via the `this.scene` property. + */ + scenePlugin: Phaser.Scenes.ScenePlugin; + + /** + * A reference to the Scene's Update List. + * + * Use this to organize the children contained in the update list. + * + * The Update List is responsible for managing children that need their `preUpdate` methods called, + * in order to process so internal components, such as Sprites with Animations. + * + * In the default set-up there is no reference to this from within the Scene itself. + */ + updateList: Phaser.GameObjects.UpdateList; + + /** + * This method is called only once by the Scene Manager when the Scene is instantiated. + * It is responsible for setting up all of the Scene plugins and references. + * It should never be called directly. + * @param game A reference to the Phaser Game instance. + */ + protected init(game: Phaser.Game): void; + + /** + * A single game step. Called automatically by the Scene Manager as a result of a Request Animation + * Frame or Set Timeout call to the main Game instance. + * @param time The time value from the most recent Game step. Typically a high-resolution timer value, or Date.now(). + * @param delta The delta value since the last frame. This is smoothed to avoid delta spikes by the TimeStep class. + */ + step(time: number, delta: number): void; + + /** + * Called automatically by the Scene Manager. + * Instructs the Scene to render itself via its Camera Manager to the renderer given. + * @param renderer The renderer that invoked the render call. + */ + render(renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer): void; + + /** + * Force a sort of the display list on the next render. + */ + queueDepthSort(): void; + + /** + * Immediately sorts the display list if the flag is set. + */ + depthSort(): void; + + /** + * Pause this Scene. + * A paused Scene still renders, it just doesn't run ANY of its update handlers or systems. + * @param data A data object that will be passed in the 'pause' event. + */ + pause(data?: object): Phaser.Scenes.Systems; + + /** + * Resume this Scene from a paused state. + * @param data A data object that will be passed in the 'resume' event. + */ + resume(data?: object): Phaser.Scenes.Systems; + + /** + * Send this Scene to sleep. + * + * A sleeping Scene doesn't run its update step or render anything, but it also isn't shut down + * or has any of its systems or children removed, meaning it can be re-activated at any point and + * will carry on from where it left off. It also keeps everything in memory and events and callbacks + * from other Scenes may still invoke changes within it, so be careful what is left active. + * @param data A data object that will be passed in the 'sleep' event. + */ + sleep(data?: object): Phaser.Scenes.Systems; + + /** + * Wake-up this Scene if it was previously asleep. + * @param data A data object that will be passed in the 'wake' event. + */ + wake(data?: object): Phaser.Scenes.Systems; + + /** + * Returns any data that was sent to this Scene by another Scene. + * + * The data is also passed to `Scene.init` and in various Scene events, but + * you can access it at any point via this method. + */ + getData(): any; + + /** + * Is this Scene sleeping? + */ + isSleeping(): boolean; + + /** + * Is this Scene running? + */ + isActive(): boolean; + + /** + * Is this Scene paused? + */ + isPaused(): boolean; + + /** + * Is this Scene currently transitioning out to, or in from another Scene? + */ + isTransitioning(): boolean; + + /** + * Is this Scene currently transitioning out from itself to another Scene? + */ + isTransitionOut(): boolean; + + /** + * Is this Scene currently transitioning in from another Scene? + */ + isTransitionIn(): boolean; + + /** + * Is this Scene visible and rendering? + */ + isVisible(): boolean; + + /** + * Sets the visible state of this Scene. + * An invisible Scene will not render, but will still process updates. + * @param value `true` to render this Scene, otherwise `false`. + */ + setVisible(value: boolean): Phaser.Scenes.Systems; + + /** + * Set the active state of this Scene. + * + * An active Scene will run its core update loop. + * @param value If `true` the Scene will be resumed, if previously paused. If `false` it will be paused. + * @param data A data object that will be passed in the 'resume' or 'pause' events. + */ + setActive(value: boolean, data?: object): Phaser.Scenes.Systems; + + /** + * Start this Scene running and rendering. + * Called automatically by the SceneManager. + * @param data Optional data object that may have been passed to this Scene from another. + */ + start(data: object): void; + + /** + * Shutdown this Scene and send a shutdown event to all of its systems. + * A Scene that has been shutdown will not run its update loop or render, but it does + * not destroy any of its plugins or references. It is put into hibernation for later use. + * If you don't ever plan to use this Scene again, then it should be destroyed instead + * to free-up resources. + * @param data A data object that will be passed in the 'shutdown' event. + */ + shutdown(data?: object): void; + + } + + } + + /** + * A base Phaser.Scene class which can be extended for your own use. + * + * You can also define the optional methods {@link Phaser.Types.Scenes.SceneInitCallback init()}, {@link Phaser.Types.Scenes.ScenePreloadCallback preload()}, and {@link Phaser.Types.Scenes.SceneCreateCallback create()}. + */ + class Scene { + /** + * + * @param config Scene specific configuration settings. + */ + constructor(config: string | Phaser.Types.Scenes.SettingsConfig); + + /** + * The Scene Systems. You must never overwrite this property, or all hell will break lose. + */ + sys: Phaser.Scenes.Systems; + + /** + * A reference to the Phaser.Game instance. + * This property will only be available if defined in the Scene Injection Map. + */ + game: Phaser.Game; + + /** + * A reference to the global Animation Manager. + * This property will only be available if defined in the Scene Injection Map. + */ + anims: Phaser.Animations.AnimationManager; + + /** + * A reference to the global Cache. + * This property will only be available if defined in the Scene Injection Map. + */ + cache: Phaser.Cache.CacheManager; + + /** + * A reference to the game level Data Manager. + * This property will only be available if defined in the Scene Injection Map. + */ + registry: Phaser.Data.DataManager; + + /** + * A reference to the Sound Manager. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + sound: Phaser.Sound.BaseSoundManager; + + /** + * A reference to the Texture Manager. + * This property will only be available if defined in the Scene Injection Map. + */ + textures: Phaser.Textures.TextureManager; + + /** + * A scene level Event Emitter. + * This property will only be available if defined in the Scene Injection Map. + */ + events: Phaser.Events.EventEmitter; + + /** + * A scene level Camera System. + * This property will only be available if defined in the Scene Injection Map. + */ + cameras: Phaser.Cameras.Scene2D.CameraManager; + + /** + * A scene level Game Object Factory. + * This property will only be available if defined in the Scene Injection Map. + */ + add: Phaser.GameObjects.GameObjectFactory; + + /** + * A scene level Game Object Creator. + * This property will only be available if defined in the Scene Injection Map. + */ + make: Phaser.GameObjects.GameObjectCreator; + + /** + * A reference to the Scene Manager Plugin. + * This property will only be available if defined in the Scene Injection Map. + */ + scene: Phaser.Scenes.ScenePlugin; + + /** + * A scene level Game Object Display List. + * This property will only be available if defined in the Scene Injection Map. + */ + children: Phaser.GameObjects.DisplayList; + + /** + * A scene level Lights Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + lights: Phaser.GameObjects.LightsManager; + + /** + * A scene level Data Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + data: Phaser.Data.DataManager; + + /** + * A scene level Input Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + input: Phaser.Input.InputPlugin; + + /** + * A scene level Loader Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + load: Phaser.Loader.LoaderPlugin; + + /** + * A scene level Time and Clock Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + time: Phaser.Time.Clock; + + /** + * A scene level Tween Manager Plugin. + * This property will only be available if defined in the Scene Injection Map and the plugin is installed. + */ + tweens: Phaser.Tweens.TweenManager; + + /** + * A scene level Arcade Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + */ + physics: Phaser.Physics.Arcade.ArcadePhysics; + + /** + * A scene level Impact Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + */ + impact: Phaser.Physics.Impact.ImpactPhysics; + + /** + * A scene level Matter Physics Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + */ + matter: Phaser.Physics.Matter.MatterPhysics; + + /** + * A scene level Facebook Instant Games Plugin. + * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured. + */ + facebook: Phaser.FacebookInstantGamesPlugin; + + /** + * A reference to the global Scale Manager. + * This property will only be available if defined in the Scene Injection Map. + */ + scale: Phaser.Scale.ScaleManager; + + /** + * A reference to the Plugin Manager. + * + * The Plugin Manager is a global system that allows plugins to register themselves with it, and can then install + * those plugins into Scenes as required. + */ + plugins: Phaser.Plugins.PluginManager; + + /** + * Should be overridden by your own Scenes. + * This method is called once per game step while the scene is running. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(time: number, delta: number): void; + + } + + namespace Sound { + /** + * Class containing all the shared state and behavior of a sound object, independent of the implementation. + */ + class BaseSound extends Phaser.Events.EventEmitter { + /** + * + * @param manager Reference to the current sound manager instance. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. + */ + constructor(manager: Phaser.Sound.BaseSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); + + /** + * Asset key for the sound. + */ + readonly key: string; + + /** + * Flag indicating if sound is currently playing. + */ + readonly isPlaying: boolean; + + /** + * Flag indicating if sound is currently paused. + */ + readonly isPaused: boolean; + + /** + * A property that holds the value of sound's actual playback rate, + * after its rate and detune values has been combined with global + * rate and detune values. + */ + readonly totalRate: number; + + /** + * A value representing the duration, in seconds. + * It could be total sound duration or a marker duration. + */ + readonly duration: number; + + /** + * The total duration of the sound in seconds. + */ + readonly totalDuration: number; + + /** + * Object containing markers definitions. + */ + readonly markers: {[key: string]: Phaser.Types.Sound.SoundMarker}; + + /** + * Currently playing marker. + * 'null' if whole sound is playing. + */ + readonly currentMarker: Phaser.Types.Sound.SoundMarker; + + /** + * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * @param marker Marker object. + */ + addMarker(marker: Phaser.Types.Sound.SoundMarker): boolean; + + /** + * Updates previously added marker. + * @param marker Marker object with updated values. + */ + updateMarker(marker: Phaser.Types.Sound.SoundMarker): boolean; + + /** + * Removes a marker from the sound. + * @param markerName The name of the marker to remove. + */ + removeMarker(markerName: string): Phaser.Types.Sound.SoundMarker; + + /** + * Play this sound, or a marked section of it. + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * @param markerName If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. Default ''. + * @param config Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + */ + play(markerName?: string | Phaser.Types.Sound.SoundConfig, config?: Phaser.Types.Sound.SoundConfig): boolean; + + /** + * Pauses the sound. + */ + pause(): boolean; + + /** + * Resumes the sound. + */ + resume(): boolean; + + /** + * Stop playing this sound. + */ + stop(): boolean; + + /** + * Method used internally for applying config values to some of the sound properties. + */ + protected applyConfig(): void; + + /** + * Method used internally for resetting values of some of the config properties. + */ + protected resetConfig(): void; + + /** + * Update method called automatically by sound manager on every game step. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time elapsed since the last frame. + */ + protected update(time: number, delta: number): void; + + /** + * Method used internally to calculate total playback rate of the sound. + */ + protected calculateRate(): void; + + /** + * Destroys this sound and all associated events and marks it for removal from the sound manager. + */ + destroy(): void; + + } + + /** + * The sound manager is responsible for playing back audio via Web Audio API or HTML Audio tag as fallback. + * The audio file type and the encoding of those files are extremely important. + * + * Not all browsers can play all audio formats. + * + * There is a good guide to what's supported [here](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support). + */ + class BaseSoundManager extends Phaser.Events.EventEmitter { + /** + * + * @param game Reference to the current game instance. + */ + constructor(game: Phaser.Game); + + /** + * Local reference to game. + */ + readonly game: Phaser.Game; + + /** + * Local reference to the JSON Cache, as used by Audio Sprites. + */ + readonly jsonCache: Phaser.Cache.BaseCache; + + /** + * Global mute setting. + */ + mute: boolean; + + /** + * Global volume setting. + */ + volume: number; + + /** + * Flag indicating if sounds should be paused when game looses focus, + * for instance when user switches to another tab/program/app. + */ + pauseOnBlur: boolean; + + /** + * Mobile devices require sounds to be triggered from an explicit user action, + * such as a tap, before any sound can be loaded/played on a web page. + * Set to true if the audio system is currently locked awaiting user interaction. + */ + readonly locked: boolean; + + /** + * Adds a new sound into the sound manager. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. + */ + add(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.BaseSound; + + /** + * 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 + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. + */ + addAudioSprite(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.HTML5AudioSound | Phaser.Sound.WebAudioSound; + + /** + * Adds a new sound to the sound manager and plays it. + * The sound will be automatically removed (destroyed) once playback ends. + * This lets you play a new sound on the fly without the need to keep a reference to it. + * @param key Asset key for the sound. + * @param extra An optional additional object containing settings to be applied to the sound. It could be either config or marker object. + */ + play(key: string, extra?: Phaser.Types.Sound.SoundConfig | Phaser.Types.Sound.SoundMarker): boolean; + + /** + * Enables playing audio sprite sound on the fly without the need to keep a reference to it. + * Sound will auto destroy once its playback ends. + * @param key Asset key for the sound. + * @param spriteName The name of the sound sprite to play. + * @param config An optional config object containing default sound settings. + */ + playAudioSprite(key: string, spriteName: string, config?: Phaser.Types.Sound.SoundConfig): boolean; + + /** + * Removes a sound from the sound manager. + * The removed sound is destroyed before removal. + * @param sound The sound object to remove. + */ + remove(sound: Phaser.Sound.BaseSound): boolean; + + /** + * Removes all sounds from the sound manager that have an asset key matching the given value. + * The removed sounds are destroyed before removal. + * @param key The key to match when removing sound objects. + */ + removeByKey(key: string): number; + + /** + * Pauses all the sounds in the game. + */ + pauseAll(): void; + + /** + * Resumes all the sounds in the game. + */ + resumeAll(): void; + + /** + * Stops all the sounds in the game. + */ + stopAll(): void; + + /** + * 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). + */ + protected unlock(): void; + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. + */ + protected onBlur(): void; + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.BaseSoundManager#pauseOnBlur is set to true. + */ + protected onFocus(): void; + + /** + * Update method called on every game step. + * Removes destroyed sounds and updates every active sound in the game. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time elapsed since the last frame. + */ + protected update(time: number, delta: number): void; + + /** + * Destroys all the sounds in the game and all associated events. + */ + destroy(): void; + + /** + * Sets the global playback rate at which all the sounds will be played. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * @param value Global playback rate at which all the sounds will be played. + */ + setRate(value: number): Phaser.Sound.BaseSoundManager; + + /** + * Global playback rate at which all the sounds will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audio's playback speed. + */ + rate: number; + + /** + * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + * @param value The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + */ + setDetune(value: number): Phaser.Sound.BaseSoundManager; + + /** + * 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 setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + */ + detune: number; + + } + + namespace Events { + /** + * The Sound Complete Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they complete playback. + * + * Listen to it from a Sound instance using `Sound.on('complete', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('complete', listener); + * music.play(); + * ``` + */ + const COMPLETE: any; + + /** + * The Audio Data Decoded All Event. + * + * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method, + * once all files passed to the method have been decoded (or errored). + * + * Use `Phaser.Sound.Events#DECODED` to listen for single sounds being decoded, and `DECODED_ALL` to + * listen for them all completing. + * + * Listen to it from the Sound Manager in a Scene using `this.sound.on('decodedall', listener)`, i.e.: + * + * ```javascript + * this.sound.once('decodedall', handler); + * this.sound.decodeAudio([ audioFiles ]); + * ``` + */ + const DECODED_ALL: any; + + /** + * The Audio Data Decoded Event. + * + * This event is dispatched by the Web Audio Sound Manager as a result of calling the `decodeAudio` method. + * + * Listen to it from the Sound Manager in a Scene using `this.sound.on('decoded', listener)`, i.e.: + * + * ```javascript + * this.sound.on('decoded', handler); + * this.sound.decodeAudio(key, audioData); + * ``` + */ + const DECODED: any; + + /** + * The Sound Destroy Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are destroyed, either + * directly or via a Sound Manager. + * + * Listen to it from a Sound instance using `Sound.on('destroy', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('destroy', listener); + * music.destroy(); + * ``` + */ + const DESTROY: any; + + /** + * The Sound Detune Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their detune value changes. + * + * Listen to it from a Sound instance using `Sound.on('detune', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('detune', listener); + * music.play(); + * music.setDetune(200); + * ``` + */ + const DETUNE: any; + + /** + * The Sound Manager Global Detune Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `detune` property of the Sound Manager is changed, which globally + * adjusts the detuning of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('rate', listener)`. + */ + const GLOBAL_DETUNE: any; + + /** + * The Sound Manager Global Mute Event. + * + * This event is dispatched by the Sound Manager when its `mute` property is changed, either directly + * or via the `setMute` method. This changes the mute state of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('mute', listener)`. + */ + const GLOBAL_MUTE: any; + + /** + * The Sound Manager Global Rate Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `rate` property of the Sound Manager is changed, which globally + * adjusts the playback rate of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('rate', listener)`. + */ + const GLOBAL_RATE: any; + + /** + * The Sound Manager Global Volume Event. + * + * This event is dispatched by the Sound Manager when its `volume` property is changed, either directly + * or via the `setVolume` method. This changes the volume of all active sounds. + * + * Listen to it from a Scene using: `this.sound.on('volume', listener)`. + */ + const GLOBAL_VOLUME: any; + + /** + * The Sound Looped Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they loop during playback. + * + * Listen to it from a Sound instance using `Sound.on('looped', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('looped', listener); + * music.setLoop(true); + * music.play(); + * ``` + * + * This is not to be confused with the [LOOP]{@linkcode Phaser.Sound.Events#event:LOOP} event, which only emits when the loop state of a Sound is changed. + */ + const LOOPED: any; + + /** + * The Sound Loop Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their loop state is changed. + * + * Listen to it from a Sound instance using `Sound.on('loop', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('loop', listener); + * music.setLoop(true); + * ``` + * + * This is not to be confused with the [LOOPED]{@linkcode Phaser.Sound.Events#event:LOOPED} event, which emits each time a Sound loops during playback. + */ + const LOOP: any; + + /** + * The Sound Mute Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their mute state changes. + * + * Listen to it from a Sound instance using `Sound.on('mute', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('mute', listener); + * music.play(); + * music.setMute(true); + * ``` + */ + const MUTE: any; + + /** + * The Pause All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `pauseAll` method is invoked and after all current Sounds + * have been paused. + * + * Listen to it from a Scene using: `this.sound.on('pauseall', listener)`. + */ + const PAUSE_ALL: any; + + /** + * The Sound Pause Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are paused. + * + * Listen to it from a Sound instance using `Sound.on('pause', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('pause', listener); + * music.play(); + * music.pause(); + * ``` + */ + const PAUSE: any; + + /** + * The Sound Play Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are played. + * + * Listen to it from a Sound instance using `Sound.on('play', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('play', listener); + * music.play(); + * ``` + */ + const PLAY: any; + + /** + * The Sound Rate Change Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their rate changes. + * + * Listen to it from a Sound instance using `Sound.on('rate', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('rate', listener); + * music.play(); + * music.setRate(0.5); + * ``` + */ + const RATE: any; + + /** + * The Resume All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `resumeAll` method is invoked and after all current Sounds + * have been resumed. + * + * Listen to it from a Scene using: `this.sound.on('resumeall', listener)`. + */ + const RESUME_ALL: any; + + /** + * The Sound Resume Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are resumed from a paused state. + * + * Listen to it from a Sound instance using `Sound.on('resume', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('resume', listener); + * music.play(); + * music.pause(); + * music.resume(); + * ``` + */ + const RESUME: any; + + /** + * The Sound Seek Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are seeked to a new position. + * + * Listen to it from a Sound instance using `Sound.on('seek', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('seek', listener); + * music.play(); + * music.setSeek(5000); + * ``` + */ + const SEEK: any; + + /** + * The Stop All Sounds Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched when the `stopAll` method is invoked and after all current Sounds + * have been stopped. + * + * Listen to it from a Scene using: `this.sound.on('stopall', listener)`. + */ + const STOP_ALL: any; + + /** + * The Sound Stop Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when they are stopped. + * + * Listen to it from a Sound instance using `Sound.on('stop', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('stop', listener); + * music.play(); + * music.stop(); + * ``` + */ + const STOP: any; + + /** + * The Sound Manager Unlocked Event. + * + * This event is dispatched by the Base Sound Manager, or more typically, an instance of the Web Audio Sound Manager, + * or the HTML5 Audio Manager. It is dispatched during the update loop when the Sound Manager becomes unlocked. For + * Web Audio this is on the first user gesture on the page. + * + * Listen to it from a Scene using: `this.sound.on('unlocked', listener)`. + */ + const UNLOCKED: any; + + /** + * The Sound Volume Event. + * + * This event is dispatched by both Web Audio and HTML5 Audio Sound objects when their volume changes. + * + * Listen to it from a Sound instance using `Sound.on('volume', listener)`, i.e.: + * + * ```javascript + * var music = this.sound.add('key'); + * music.on('volume', listener); + * music.play(); + * music.setVolume(0.5); + * ``` + */ + const VOLUME: any; + + } + + /** + * HTML5 Audio implementation of the sound. + */ + class HTML5AudioSound extends Phaser.Sound.BaseSound { + /** + * + * @param manager Reference to the current sound manager instance. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. Default {}. + */ + constructor(manager: Phaser.Sound.HTML5AudioSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); + + /** + * Play this sound, or a marked section of it. + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * @param markerName If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. Default ''. + * @param config Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + */ + play(markerName?: string | Phaser.Types.Sound.SoundConfig, config?: Phaser.Types.Sound.SoundConfig): boolean; + + /** + * Pauses the sound. + */ + pause(): boolean; + + /** + * Resumes the sound. + */ + resume(): boolean; + + /** + * Stop playing this sound. + */ + stop(): boolean; + + /** + * Update method called automatically by sound manager on every game step. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time elapsed since the last frame. + */ + protected update(time: number, delta: number): void; + + /** + * Calls Phaser.Sound.BaseSound#destroy method + * and cleans up all HTML5 Audio related stuff. + */ + destroy(): void; + + /** + * Method used internally to calculate total playback rate of the sound. + */ + protected calculateRate(): void; + + /** + * Boolean indicating whether the sound is muted or not. + * Gets or sets the muted state of this sound. + */ + mute: boolean; + + /** + * Sets the muted state of this Sound. + * @param value `true` to mute this sound, `false` to unmute it. + */ + setMute(value: boolean): Phaser.Sound.HTML5AudioSound; + + /** + * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). + */ + volume: number; + + /** + * Sets the volume of this Sound. + * @param value The volume of the sound. + */ + setVolume(value: number): Phaser.Sound.HTML5AudioSound; + + /** + * Rate at which this Sound will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + */ + rate: number; + + /** + * Sets the playback rate of this Sound. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * @param value The playback rate at of this Sound. + */ + setRate(value: number): Phaser.Sound.HTML5AudioSound; + + /** + * 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). + */ + detune: number; + + /** + * 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). + * @param value The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + */ + setDetune(value: number): Phaser.Sound.HTML5AudioSound; + + /** + * Property representing the position of playback for this sound, in seconds. + * Setting it to a specific value moves current playback to that position. + * The value given is clamped to the range 0 to current marker duration. + * Setting seek of a stopped sound has no effect. + */ + seek: number; + + /** + * Seeks to a specific point in this sound. + * @param value The point in the sound to seek to. + */ + setSeek(value: number): Phaser.Sound.HTML5AudioSound; + + /** + * Flag indicating whether or not the sound or current sound marker will loop. + */ + loop: boolean; + + /** + * Sets the loop state of this Sound. + * @param value `true` to loop this sound, `false` to not loop it. + */ + setLoop(value: boolean): Phaser.Sound.HTML5AudioSound; + + } + + /** + * HTML5AudioSoundManager + */ + class HTML5AudioSoundManager extends Phaser.Sound.BaseSoundManager { + /** + * + * @param game Reference to the current game instance. + */ + constructor(game: Phaser.Game); + + /** + * Flag indicating whether if there are no idle instances of HTML5 Audio tag, + * for any particular sound, if one of the used tags should be hijacked and used + * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play + * call should be ignored. + */ + override: boolean; + + /** + * Value representing time difference, in seconds, between calling + * play method on an audio tag and when it actually starts playing. + * It is used to achieve more accurate delayed sound playback. + * + * You might need to tweak this value to get the desired results + * since audio play delay varies depending on the browser/platform. + */ + audioPlayDelay: number; + + /** + * A value by which we should offset the loop end marker of the + * looping sound to compensate for lag, caused by changing audio + * tag playback position, in order to achieve gapless looping. + * + * You might need to tweak this value to get the desired results + * since loop lag varies depending on the browser/platform. + */ + loopEndOffset: number; + + /** + * Adds a new sound into the sound manager. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. + */ + add(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.HTML5AudioSound; + + /** + * Unlocks HTML5 Audio loading and playback on mobile + * devices on the initial explicit user interaction. + */ + unlock(): void; + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + */ + protected onBlur(): void; + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true. + */ + protected onFocus(): void; + + /** + * Calls Phaser.Sound.BaseSoundManager#destroy method + * and cleans up all HTML5 Audio related stuff. + */ + destroy(): void; + + /** + * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters + * to check if sound manager is locked and then either perform action immediately or queue it + * to be performed once the sound manager gets unlocked. + * @param sound Sound object on which to perform queued action. + * @param prop Name of the method to be called or property to be assigned a value to. + * @param value An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property. + */ + protected isLocked(sound: Phaser.Sound.HTML5AudioSound, prop: string, value?: any): boolean; + + /** + * Sets the muted state of all this Sound Manager. + * @param value `true` to mute all sounds, `false` to unmute them. + */ + setMute(value: boolean): Phaser.Sound.HTML5AudioSoundManager; + + mute: boolean; + + /** + * Sets the volume of this Sound Manager. + * @param value The global volume of this Sound Manager. + */ + setVolume(value: number): Phaser.Sound.HTML5AudioSoundManager; + + volume: number; + + } + + /** + * No audio implementation of the sound. It is used if audio has been + * disabled in the game config or the device doesn't support any audio. + * + * It represents a graceful degradation of sound logic that provides + * minimal functionality and prevents Phaser projects that use audio from + * breaking on devices that don't support any audio playback technologies. + */ + class NoAudioSound extends Phaser.Sound.BaseSound { + /** + * + * @param manager Reference to the current sound manager instance. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. Default {}. + */ + constructor(manager: Phaser.Sound.NoAudioSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); + + } + + /** + * No audio implementation of the sound manager. It is used if audio has been + * disabled in the game config or the device doesn't support any audio. + * + * It represents a graceful degradation of sound manager logic that provides + * minimal functionality and prevents Phaser projects that use audio from + * breaking on devices that don't support any audio playback technologies. + */ + class NoAudioSoundManager extends Phaser.Sound.BaseSoundManager { + /** + * + * @param game Reference to the current game instance. + */ + constructor(game: Phaser.Game); + + } + + /** + * 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 + * @param game Reference to the current game instance. + */ + function SoundManagerCreator(game: Phaser.Game): Phaser.Sound.HTML5AudioSoundManager | Phaser.Sound.WebAudioSoundManager | Phaser.Sound.NoAudioSoundManager; + + /** + * Web Audio API implementation of the sound. + */ + class WebAudioSound extends Phaser.Sound.BaseSound { + /** + * + * @param manager Reference to the current sound manager instance. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. Default {}. + */ + constructor(manager: Phaser.Sound.WebAudioSoundManager, key: string, config?: Phaser.Types.Sound.SoundConfig); + + /** + * Play this sound, or a marked section of it. + * + * It always plays the sound from the start. If you want to start playback from a specific time + * you can set 'seek' setting of the config object, provided to this call, to that value. + * @param markerName If you want to play a marker then provide the marker name here. Alternatively, this parameter can be a SoundConfig object. Default ''. + * @param config Optional sound config object to be applied to this marker or entire sound if no marker name is provided. It gets memorized for future plays of current section of the sound. + */ + play(markerName?: string | Phaser.Types.Sound.SoundConfig, config?: Phaser.Types.Sound.SoundConfig): boolean; + + /** + * Pauses the sound. + */ + pause(): boolean; + + /** + * Resumes the sound. + */ + resume(): boolean; + + /** + * Stop playing this sound. + */ + stop(): boolean; + + /** + * Method used internally for applying config values to some of the sound properties. + */ + protected applyConfig(): void; + + /** + * Update method called automatically by sound manager on every game step. + * @param time The current timestamp as generated by the Request Animation Frame or SetTimeout. + * @param delta The delta time elapsed since the last frame. + */ + protected update(time: number, delta: number): void; + + /** + * Calls Phaser.Sound.BaseSound#destroy method + * and cleans up all Web Audio API related stuff. + */ + destroy(): void; + + /** + * Method used internally to calculate total playback rate of the sound. + */ + protected calculateRate(): void; + + /** + * Rate at which this Sound will be played. + * Value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + */ + rate: number; + + /** + * Sets the playback rate of this Sound. + * + * For example, a value of 1.0 plays the audio at full speed, 0.5 plays the audio at half speed + * and 2.0 doubles the audios playback speed. + * @param value The playback rate at of this Sound. + */ + setRate(value: number): Phaser.Sound.WebAudioSound; + + /** + * 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). + */ + detune: number; + + /** + * 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). + * @param value The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent). + */ + setDetune(value: number): Phaser.Sound.WebAudioSound; + + /** + * Boolean indicating whether the sound is muted or not. + * Gets or sets the muted state of this sound. + */ + mute: boolean; + + /** + * Sets the muted state of this Sound. + * @param value `true` to mute this sound, `false` to unmute it. + */ + setMute(value: boolean): Phaser.Sound.WebAudioSound; + + /** + * Gets or sets the volume of this sound, a value between 0 (silence) and 1 (full volume). + */ + volume: number; + + /** + * Sets the volume of this Sound. + * @param value The volume of the sound. + */ + setVolume(value: number): Phaser.Sound.WebAudioSound; + + /** + * Property representing the position of playback for this sound, in seconds. + * Setting it to a specific value moves current playback to that position. + * The value given is clamped to the range 0 to current marker duration. + * Setting seek of a stopped sound has no effect. + */ + seek: number; + + /** + * Seeks to a specific point in this sound. + * @param value The point in the sound to seek to. + */ + setSeek(value: number): Phaser.Sound.WebAudioSound; + + /** + * Flag indicating whether or not the sound or current sound marker will loop. + */ + loop: boolean; + + /** + * Sets the loop state of this Sound. + * @param value `true` to loop this sound, `false` to not loop it. + */ + setLoop(value: boolean): Phaser.Sound.WebAudioSound; + + } + + /** + * Web Audio API implementation of the sound manager. + */ + class WebAudioSoundManager extends Phaser.Sound.BaseSoundManager { + /** + * + * @param game Reference to the current game instance. + */ + constructor(game: Phaser.Game); + + /** + * This method takes a new AudioContext reference and then sets + * this Sound Manager to use that context for all playback. + * + * As part of this call it also disconnects the master mute and volume + * nodes and then re-creates them on the new given context. + * @param context Reference to an already created AudioContext instance. + */ + setAudioContext(context: AudioContext): this; + + /** + * Adds a new sound into the sound manager. + * @param key Asset key for the sound. + * @param config An optional config object containing default sound settings. + */ + add(key: string, config?: Phaser.Types.Sound.SoundConfig): Phaser.Sound.WebAudioSound; + + /** + * Decode audio data into a format ready for playback via Web Audio. + * + * The audio data can be a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + * + * The `audioKey` is the key that will be used to save the decoded audio to the audio cache. + * + * Instead of passing a single entry you can instead pass an array of `Phaser.Types.Sound.DecodeAudioConfig` + * objects as the first and only argument. + * + * Decoding is an async process, so be sure to listen for the events to know when decoding has completed. + * + * Once the audio has decoded it can be added to the Sound Manager or played via its key. + * @param audioKey The string-based key to be used to reference the decoded audio in the audio cache, or an array of audio config objects. + * @param audioData The audio data, either a base64 encoded string, an audio media-type data uri, or an ArrayBuffer instance. + */ + decodeAudio(audioKey?: Phaser.Types.Sound.DecodeAudioConfig[] | string, audioData?: ArrayBuffer | string): void; + + /** + * 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). + */ + unlock(): void; + + /** + * Method used internally for pausing sound manager if + * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. + */ + protected onBlur(): void; + + /** + * Method used internally for resuming sound manager if + * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true. + */ + protected onFocus(): void; + + /** + * Calls Phaser.Sound.BaseSoundManager#destroy method + * and cleans up all Web Audio API related stuff. + */ + destroy(): void; + + /** + * Sets the muted state of all this Sound Manager. + * @param value `true` to mute all sounds, `false` to unmute them. + */ + setMute(value: boolean): Phaser.Sound.WebAudioSoundManager; + + mute: boolean; + + /** + * Sets the volume of this Sound Manager. + * @param value The global volume of this Sound Manager. + */ + setVolume(value: number): Phaser.Sound.WebAudioSoundManager; + + volume: number; + + } + + } + + namespace Structs { + namespace Events { + /** + * The Process Queue Add Event. + * + * This event is dispatched by a Process Queue when a new item is successfully moved to its active list. + * + * You will most commonly see this used by a Scene's Update List when a new Game Object has been added. + * + * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('add', listener)`. + */ + const PROCESS_QUEUE_ADD: any; + + /** + * The Process Queue Remove Event. + * + * This event is dispatched by a Process Queue when a new item is successfully removed from its active list. + * + * You will most commonly see this used by a Scene's Update List when a Game Object has been removed. + * + * In that instance, listen to this event from within a Scene using: `this.sys.updateList.on('remove', listener)`. + */ + const PROCESS_QUEUE_REMOVE: any; + + } + + /** + * List is a generic implementation of an ordered list which contains utility methods for retrieving, manipulating, and iterating items. + */ + class List { + /** + * + * @param parent The parent of this list. + */ + constructor(parent: any); + + /** + * The parent of this list. + */ + parent: any; + + /** + * The objects that belong to this collection. + */ + list: T[]; + + /** + * The index of the current element. + * + * This is used internally when iterating through the list with the {@link #first}, {@link #last}, {@link #get}, and {@link #previous} properties. + */ + position: integer; + + /** + * A callback that is invoked every time a child is added to this list. + */ + addCallback: Function; + + /** + * A callback that is invoked every time a child is removed from this list. + */ + removeCallback: Function; + + /** + * The property key to sort by. + */ + _sortKey: string; + + /** + * Adds the given item to the end of the list. Each item must be unique. + * @param child The item, or array of items, to add to the list. + * @param skipCallback Skip calling the List.addCallback if this child is added successfully. Default false. + */ + add(child: T, skipCallback?: boolean): T; + + /** + * Adds an item to list, starting at a specified index. Each item must be unique within the list. + * @param child The item, or array of items, to add to the list. + * @param index The index in the list at which the element(s) will be inserted. Default 0. + * @param skipCallback Skip calling the List.addCallback if this child is added successfully. Default false. + */ + addAt(child: T, index?: integer, skipCallback?: boolean): T; + + /** + * Retrieves the item at a given position inside the List. + * @param index The index of the item. + */ + getAt(index: integer): T; + + /** + * Locates an item within the List and returns its index. + * @param child The item to locate. + */ + getIndex(child: T): integer; + + /** + * 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. + * @param property The property to lexically sort by. + * @param handler Provide your own custom handler function. Will receive 2 children which it should compare and return a boolean. + */ + sort(property: string, handler?: Function): T[]; + + /** + * Searches for the first instance of a child with its `name` + * property matching the given argument. Should more than one child have + * the same name only the first is returned. + * @param name The name to search for. + */ + getByName(name: string): T | null; + + /** + * Returns a random child from the group. + * @param startIndex Offset from the front of the group (lowest child). Default 0. + * @param length Restriction on the number of values you want to randomly select from. Default (to top). + */ + getRandom(startIndex?: integer, length?: integer): T | null; + + /** + * Returns the first element in a given part of the List which matches a specific criterion. + * @param property The name of the property to test or a falsey value to have no criterion. + * @param value The value to test the `property` against, or `undefined` to allow any value and only check for existence. + * @param startIndex The position in the List to start the search at. Default 0. + * @param endIndex The position in the List to optionally stop the search at. It won't be checked. + */ + getFirst(property: string, value: any, startIndex?: number, endIndex?: number): T | null; + + /** + * Returns all children in this List. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('parent')` would return only children that have a property called `parent`. + * + * You can also specify a value to compare the property to: + * + * `getAll('visible', true)` would return only children that have their visible property set to `true`. + * + * Optionally you can specify a start and end index. For example if this List had 100 children, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 children in the List. + * @param property An optional property to test against the value argument. + * @param value If property is set then Child.property must strictly equal this value to be included in the results. + * @param startIndex The first child index to start the search from. + * @param endIndex The last child index to search up until. + */ + getAll(property?: string, value?: T, startIndex?: integer, endIndex?: integer): T[]; + + /** + * Returns the total number of items in the List which have a property matching the given value. + * @param property The property to test on each item. + * @param value The value to test the property against. + */ + count(property: string, value: T): integer; + + /** + * Swaps the positions of two items in the list. + * @param child1 The first item to swap. + * @param child2 The second item to swap. + */ + swap(child1: T, child2: T): void; + + /** + * Moves an item in the List to a new position. + * @param child The item to move. + * @param index Moves an item in the List to a new position. + */ + moveTo(child: T, index: integer): T; + + /** + * Removes one or many items from the List. + * @param child The item, or array of items, to remove. + * @param skipCallback Skip calling the List.removeCallback. Default false. + */ + remove(child: T, skipCallback?: boolean): T; + + /** + * Removes the item at the given position in the List. + * @param index The position to remove the item from. + * @param skipCallback Skip calling the List.removeCallback. Default false. + */ + removeAt(index: integer, skipCallback?: boolean): T; + + /** + * Removes the items within the given range in the List. + * @param startIndex The index to start removing from. Default 0. + * @param endIndex The position to stop removing at. The item at this position won't be removed. + * @param skipCallback Skip calling the List.removeCallback. Default false. + */ + removeBetween(startIndex?: integer, endIndex?: integer, skipCallback?: boolean): T[]; + + /** + * Removes all the items. + * @param skipCallback Skip calling the List.removeCallback. Default false. + */ + removeAll(skipCallback?: boolean): Phaser.Structs.List; + + /** + * Brings the given child to the top of this List. + * @param child The item to bring to the top of the List. + */ + bringToTop(child: T): T; + + /** + * Sends the given child to the bottom of this List. + * @param child The item to send to the back of the list. + */ + sendToBack(child: T): T; + + /** + * Moves the given child up one place in this group unless it's already at the top. + * @param child The item to move up. + */ + moveUp(child: T): T; + + /** + * Moves the given child down one place in this group unless it's already at the bottom. + * @param child The item to move down. + */ + moveDown(child: T): T; + + /** + * Reverses the order of all children in this List. + */ + reverse(): Phaser.Structs.List; + + /** + * Shuffles the items in the list. + */ + shuffle(): Phaser.Structs.List; + + /** + * Replaces a child of this List with the given newChild. The newChild cannot be a member of this List. + * @param oldChild The child in this List that will be replaced. + * @param newChild The child to be inserted into this List. + */ + replace(oldChild: T, newChild: T): T; + + /** + * Checks if an item exists within the List. + * @param child The item to check for the existence of. + */ + exists(child: T): boolean; + + /** + * Sets the property `key` to the given value on all members of this List. + * @param property The name of the property to set. + * @param value The value to set the property to. + * @param startIndex The first child index to start the search from. + * @param endIndex The last child index to search up until. + */ + setAll(property: string, value: T, startIndex?: integer, endIndex?: integer): void; + + /** + * Passes all children to the given callback. + * @param callback The function to call. + * @param context Value to use as `this` when executing callback. + * @param args Additional arguments that will be passed to the callback, after the child. + */ + each(callback: EachListCallback, context?: any, ...args: any[]): void; + + /** + * Clears the List and recreates its internal array. + */ + shutdown(): void; + + /** + * Destroys this List. + */ + destroy(): void; + + /** + * The number of items inside the List. + */ + readonly length: integer; + + /** + * The first item in the List or `null` for an empty List. + */ + readonly first: T; + + /** + * The last item in the List, or `null` for an empty List. + */ + readonly last: T; + + /** + * The next item in the List, or `null` if the entire List has been traversed. + * + * This property can be read successively after reading {@link #first} or manually setting the {@link #position} to iterate the List. + */ + readonly next: T; + + /** + * The previous item in the List, or `null` if the entire List has been traversed. + * + * This property can be read successively after reading {@link #last} or manually setting the {@link #position} to iterate the List backwards. + */ + readonly previous: T; + + } + + /** + * The keys of a Map can be arbitrary values. + * + * ```javascript + * var map = new Map([ + * [ 1, 'one' ], + * [ 2, 'two' ], + * [ 3, 'three' ] + * ]); + * ``` + */ + class Map { + /** + * + * @param elements An optional array of key-value pairs to populate this Map with. + */ + constructor(elements: V[]); + + /** + * The entries in this Map. + */ + entries: {[key: string]: V}; + + /** + * The number of key / value pairs in this Map. + */ + size: number; + + /** + * Adds an element with a specified `key` and `value` to this Map. + * If the `key` already exists, the value will be replaced. + * @param key The key of the element to be added to this Map. + * @param value The value of the element to be added to this Map. + */ + set(key: K, value: V): Phaser.Structs.Map; + + /** + * Returns the value associated to the `key`, or `undefined` if there is none. + * @param key The key of the element to return from the `Map` object. + */ + get(key: K): V; + + /** + * Returns an `Array` of all the values stored in this Map. + */ + getArray(): V[]; + + /** + * Returns a boolean indicating whether an element with the specified key exists or not. + * @param key The key of the element to test for presence of in this Map. + */ + has(key: K): boolean; + + /** + * Delete the specified element from this Map. + * @param key The key of the element to delete from this Map. + */ + delete(key: K): Phaser.Structs.Map; + + /** + * Delete all entries from this Map. + */ + clear(): Phaser.Structs.Map; + + /** + * Returns all entries keys in this Map. + */ + keys(): K[]; + + /** + * Returns an `Array` of all entries. + */ + values(): V[]; + + /** + * Dumps the contents of this Map to the console via `console.group`. + */ + dump(): void; + + /** + * Passes all entries in this Map to the given callback. + * @param callback The callback which will receive the keys and entries held in this Map. + */ + each(callback: EachMapCallback): Phaser.Structs.Map; + + /** + * Returns `true` if the value exists within this Map. Otherwise, returns `false`. + * @param value The value to search for. + */ + contains(value: V): boolean; + + /** + * Merges all new keys from the given Map into this one. + * If it encounters a key that already exists it will be skipped unless override is set to `true`. + * @param map The Map to merge in to this Map. + * @param override Set to `true` to replace values in this Map with those from the source map, or `false` to skip them. Default false. + */ + merge(map: Phaser.Structs.Map, override?: boolean): Phaser.Structs.Map; + + } + + /** + * A Process Queue maintains three internal lists. + * + * The `pending` list is a selection of items which are due to be made 'active' in the next update. + * The `active` list is a selection of items which are considered active and should be updated. + * The `destroy` list is a selection of items that were active and are awaiting being destroyed in the next update. + * + * When new items are added to a Process Queue they are put in the pending list, rather than being added + * immediately the active list. Equally, items that are removed are put into the destroy list, rather than + * being destroyed immediately. This allows the Process Queue to carefully process each item at a specific, fixed + * time, rather than at the time of the request from the API. + */ + class ProcessQueue extends Phaser.Events.EventEmitter { + /** + * Adds a new item to the Process Queue. + * + * The item is added to the pending list and made active in the next update. + * @param item The item to add to the queue. + */ + add(item: T): Phaser.Structs.ProcessQueue; + + /** + * Removes an item from the Process Queue. + * + * The item is added to the pending destroy and fully removed in the next update. + * @param item The item to be removed from the queue. + */ + remove(item: T): Phaser.Structs.ProcessQueue; + + /** + * Removes all active items from this Process Queue. + * + * All the items are marked as 'pending destroy' and fully removed in the next update. + */ + removeAll(): this; + + /** + * Update this queue. First it will process any items awaiting destruction, and remove them. + * + * Then it will check to see if there are any items pending insertion, and move them to an + * active state. Finally, it will return a list of active items for further processing. + */ + update(): T[]; + + /** + * Returns the current list of active items. + * + * This method returns a reference to the active list array, not a copy of it. + * Therefore, be careful to not modify this array outside of the ProcessQueue. + */ + getActive(): T[]; + + /** + * The number of entries in the active list. + */ + readonly length: integer; + + /** + * Immediately destroys this process queue, clearing all of its internal arrays and resetting the process totals. + */ + destroy(): void; + + } + + /** + * 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 { + } + + /** + * A Set is a collection of unique elements. + */ + class Set { + /** + * + * @param elements An optional array of elements to insert into this Set. + */ + constructor(elements?: T[]); + + /** + * The entries of this Set. Stored internally as an array. + */ + entries: T[]; + + /** + * Inserts the provided value into this Set. If the value is already contained in this Set this method will have no effect. + * @param value The value to insert into this Set. + */ + set(value: T): Phaser.Structs.Set; + + /** + * Get an element of this Set which has a property of the specified name, if that property is equal to the specified value. + * If no elements of this Set satisfy the condition then this method will return `null`. + * @param property The property name to check on the elements of this Set. + * @param value The value to check for. + */ + get(property: string, value: T): T; + + /** + * Returns an array containing all the values in this Set. + */ + getArray(): T[]; + + /** + * Removes the given value from this Set if this Set contains that value. + * @param value The value to remove from the Set. + */ + delete(value: T): Phaser.Structs.Set; + + /** + * Dumps the contents of this Set to the console via `console.group`. + */ + dump(): void; + + /** + * Passes each value in this Set to the given callback. + * Use this function when you know this Set will be modified during the iteration, otherwise use `iterate`. + * @param callback The callback to be invoked and passed each value this Set contains. + * @param callbackScope The scope of the callback. + */ + each(callback: EachSetCallback, callbackScope?: any): Phaser.Structs.Set; + + /** + * Passes each value in this Set to the given callback. + * For when you absolutely know this Set won't be modified during the iteration. + * @param callback The callback to be invoked and passed each value this Set contains. + * @param callbackScope The scope of the callback. + */ + iterate(callback: EachSetCallback, callbackScope?: any): Phaser.Structs.Set; + + /** + * Goes through each entry in this Set and invokes the given function on them, passing in the arguments. + * @param callbackKey The key of the function to be invoked on each Set entry. + * @param args Additional arguments that will be passed to the callback, after the child. + */ + iterateLocal(callbackKey: string, ...args: any[]): Phaser.Structs.Set; + + /** + * Clears this Set so that it no longer contains any values. + */ + clear(): Phaser.Structs.Set; + + /** + * Returns `true` if this Set contains the given value, otherwise returns `false`. + * @param value The value to check for in this Set. + */ + contains(value: T): boolean; + + /** + * Returns a new Set containing all values that are either in this Set or in the Set provided as an argument. + * @param set The Set to perform the union with. + */ + union(set: Phaser.Structs.Set): Phaser.Structs.Set; + + /** + * Returns a new Set that contains only the values which are in this Set and that are also in the given Set. + * @param set The Set to intersect this set with. + */ + intersect(set: Phaser.Structs.Set): Phaser.Structs.Set; + + /** + * Returns a new Set containing all the values in this Set which are *not* also in the given Set. + * @param set The Set to perform the difference with. + */ + difference(set: Phaser.Structs.Set): Phaser.Structs.Set; + + /** + * The size of this Set. This is the number of entries within it. + * Changing the size will truncate the Set if the given value is smaller than the current size. + * Increasing the size larger than the current size has no effect. + */ + size: integer; + + } + + /** + * 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 { + /** + * + * @param width The width of the Size component. Default 0. + * @param height The height of the Size component. If not given, it will use the `width`. Default width. + * @param aspectMode The aspect mode of the Size component. Defaults to 0, no mode. Default 0. + * @param parent 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. Default null. + */ + constructor(width?: number, height?: number, aspectMode?: integer, parent?: any); + + /** + * The aspect mode this Size component will use when calculating its dimensions. + * This property is read-only. To change it use the `setAspectMode` method. + */ + readonly aspectMode: integer; + + /** + * The proportional relationship between the width and height. + * + * This property is read-only and is updated automatically when either the `width` or `height` properties are changed, + * depending on the aspect mode. + */ + readonly aspectRatio: number; + + /** + * The minimum allowed width. + * Cannot be less than zero. + * This value is read-only. To change it see the `setMin` method. + */ + readonly minWidth: number; + + /** + * The minimum allowed height. + * Cannot be less than zero. + * This value is read-only. To change it see the `setMin` method. + */ + readonly minHeight: number; + + /** + * The maximum allowed width. + * This value is read-only. To change it see the `setMax` method. + */ + readonly maxWidth: number; + + /** + * The maximum allowed height. + * This value is read-only. To change it see the `setMax` method. + */ + readonly maxHeight: number; + + /** + * A Vector2 containing the horizontal and vertical snap values, which the width and height are snapped to during resizing. + * + * By default this is disabled. + * + * This property is read-only. To change it see the `setSnap` method. + */ + readonly snapTo: Phaser.Math.Vector2; + + /** + * 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. + * @param value The aspect mode value. Default 0. + */ + setAspectMode(value?: integer): this; + + /** + * By setting a Snap To value when this Size component is modified its dimensions will automatically + * by snapped to the nearest grid slice, using floor. For example, if you have snap value of 16, + * and the width changes to 68, then it will snap down to 64 (the closest multiple of 16 when floored) + * + * Note that snapping takes place before adjustments by the parent, or the min / max settings. If these + * values are not multiples of the given snap values, then this can result in un-snapped dimensions. + * + * Call this method with no arguments to reset the snap values. + * + * Calling this method automatically recalculates the `width` and the `height`, if required. + * @param snapWidth The amount to snap the width to. If you don't want to snap the width, pass a value of zero. Default 0. + * @param snapHeight The amount to snap the height to. If not provided it will use the `snapWidth` value. If you don't want to snap the height, pass a value of zero. Default snapWidth. + */ + setSnap(snapWidth?: number, snapHeight?: number): this; + + /** + * 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`. + * @param parent Sets the parent of this Size component. Don't provide a value to clear an existing parent. + */ + setParent(parent?: any): this; + + /** + * 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 exceed in some situations. + * @param width The minimum allowed width of the Size component. Default 0. + * @param height The minimum allowed height of the Size component. If not given, it will use the `width`. Default width. + */ + setMin(width?: number, height?: number): this; + + /** + * 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 exceed in some situations. + * @param width The maximum allowed width of the Size component. Default Number.MAX_VALUE. + * @param height The maximum allowed height of the Size component. If not given, it will use the `width`. Default width. + */ + setMax(width?: number, height?: number): this; + + /** + * 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. + * @param width The new width of the Size component. Default 0. + * @param height The new height of the Size component. If not given, it will use the `width`. Default width. + */ + setSize(width?: number, height?: number): this; + + /** + * Sets a new aspect ratio, overriding what was there previously. + * + * It then calls `setSize` immediately using the current dimensions. + * @param ratio The new aspect ratio. + */ + setAspectRatio(ratio: number): this; + + /** + * 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. + * @param width The new width of the Size component. + * @param height The new height of the Size component. If not given, it will use the `width`. Default width. + */ + resize(width: number, height?: number): this; + + /** + * Takes a new width and passes it through the min/max clamp and then checks it doesn't exceed the parent width. + * @param value The value to clamp and check. + * @param checkParent Check the given value against the parent, if set. Default true. + */ + getNewWidth(value: number, checkParent?: boolean): number; + + /** + * Takes a new height and passes it through the min/max clamp and then checks it doesn't exceed the parent height. + * @param value The value to clamp and check. + * @param checkParent Check the given value against the parent, if set. Default true. + */ + getNewHeight(value: number, checkParent?: boolean): number; + + /** + * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. + * + * If `fit` is true there may be some space inside the target area which is not covered if its aspect ratio differs. + * If `fit` is false the size may extend further out than the target area if the aspect ratios differ. + * + * If this Size component has a parent set, then the width and height passed to this method will be clamped so + * it cannot exceed that of the parent. + * @param width The new width of the Size component. Default 0. + * @param height The new height of the Size component. If not given, it will use the width value. + * @param fit Perform a `fit` (true) constraint, or an `envelop` (false) constraint. Default true. + */ + constrain(width?: number, height?: number, fit?: boolean): this; + + /** + * The current `width` and `height` are adjusted to fit inside the given dimensions, while keeping the aspect ratio. + * + * There may be some space inside the target area which is not covered if its aspect ratio differs. + * + * If this Size component has a parent set, then the width and height passed to this method will be clamped so + * it cannot exceed that of the parent. + * @param width The new width of the Size component. Default 0. + * @param height The new height of the Size component. If not given, it will use the width value. + */ + fitTo(width?: number, height?: number): this; + + /** + * The current `width` and `height` are adjusted so that they fully envelope the given dimensions, while keeping the aspect ratio. + * + * The size may extend further out than the target area if the aspect ratios differ. + * + * If this Size component has a parent set, then the values are clamped so that it never exceeds the parent + * on the longest axis. + * @param width The new width of the Size component. Default 0. + * @param height The new height of the Size component. If not given, it will use the width value. + */ + envelop(width?: number, height?: number): this; + + /** + * Sets the width of this Size component. + * + * Depending on the aspect mode, changing the width may also update the height and aspect ratio. + * @param width The new width of the Size component. + */ + setWidth(width: number): this; + + /** + * Sets the height of this Size component. + * + * Depending on the aspect mode, changing the height may also update the width and aspect ratio. + * @param height The new height of the Size component. + */ + setHeight(height: number): this; + + /** + * Returns a string representation of this Size component. + */ + toString(): string; + + /** + * Sets the values of this Size component to the `element.style.width` and `height` + * properties of the given DOM Element. The properties are set as `px` values. + * @param element The DOM Element to set the CSS style on. + */ + setCSS(element: HTMLElement): void; + + /** + * Copies the aspect mode, aspect ratio, width and height from this Size component + * to the given Size component. Note that the parent, if set, is not copied across. + * @param destination The Size component to copy the values to. + */ + copy(destination: Phaser.Structs.Size): Phaser.Structs.Size; + + /** + * Destroys this Size component. + * + * This clears the local properties and any parent object, if set. + * + * A destroyed Size component cannot be re-used. + */ + destroy(): void; + + /** + * The width of this Size component. + * + * This value is clamped to the range specified by `minWidth` and `maxWidth`, if enabled. + * + * A width can never be less than zero. + * + * Changing this value will automatically update the `height` if the aspect ratio lock is enabled. + * You can also use the `setWidth` and `getWidth` methods. + */ + width: number; + + /** + * The height of this Size component. + * + * This value is clamped to the range specified by `minHeight` and `maxHeight`, if enabled. + * + * A height can never be less than zero. + * + * Changing this value will automatically update the `width` if the aspect ratio lock is enabled. + * You can also use the `setHeight` and `getHeight` methods. + */ + height: number; + + /** + * Do not make the size fit the aspect ratio. Change the ratio when the size changes. + */ + static readonly NONE: integer; + + /** + * The height is automatically adjusted based on the width. + */ + static readonly WIDTH_CONTROLS_HEIGHT: integer; + + /** + * The width is automatically adjusted based on the height. + */ + static readonly HEIGHT_CONTROLS_WIDTH: integer; + + /** + * 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. + */ + static readonly FIT: integer; + + /** + * 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. + */ + static readonly ENVELOP: integer; + + } + + } + + namespace Textures { + /** + * A Canvas Texture is a special kind of Texture that is backed by an HTML Canvas Element as its source. + * + * You can use the properties of this texture to draw to the canvas element directly, using all of the standard + * canvas operations available in the browser. Any Game Object can be given this texture and will render with it. + * + * Note: When running under WebGL the Canvas Texture needs to re-generate its base WebGLTexture and reupload it to + * the GPU every time you modify it, otherwise the changes you make to this texture will not be visible. To do this + * you should call `CanvasTexture.refresh()` once you are finished with your changes to the canvas. Try and keep + * this to a minimum, especially on large canvas sizes, or you may inadvertently thrash the GPU by constantly uploading + * texture data to it. This restriction does not apply if using the Canvas Renderer. + * + * It starts with only one frame that covers the whole of the canvas. You can add further frames, that specify + * sections of the canvas using the `add` method. + * + * Should you need to resize the canvas use the `setSize` method so that it accurately updates all of the underlying + * texture data as well. Forgetting to do this (i.e. by changing the canvas size directly from your code) could cause + * graphical errors. + */ + class CanvasTexture extends Phaser.Textures.Texture { + /** + * + * @param manager A reference to the Texture Manager this Texture belongs to. + * @param key The unique string-based key of this Texture. + * @param source The canvas element that is used as the base of this texture. + * @param width The width of the canvas. + * @param height The height of the canvas. + */ + constructor(manager: Phaser.Textures.TextureManager, key: string, source: HTMLCanvasElement, width: integer, height: integer); + + /** + * The source Canvas Element. + */ + readonly canvas: HTMLCanvasElement; + + /** + * The 2D Canvas Rendering Context. + */ + readonly context: CanvasRenderingContext2D; + + /** + * The width of the Canvas. + * This property is read-only, if you wish to change it use the `setSize` method. + */ + readonly width: integer; + + /** + * The height of the Canvas. + * This property is read-only, if you wish to change it use the `setSize` method. + */ + readonly height: integer; + + /** + * The context image data. + * Use the `update` method to populate this when the canvas changes. + */ + imageData: ImageData; + + /** + * A Uint8ClampedArray view into the `buffer`. + * Use the `update` method to populate this when the canvas changes. + * Note that this is unavailable in some browsers, such as Epic Browser, due to their security restrictions. + */ + data: Uint8ClampedArray; + + /** + * An Uint32Array view into the `buffer`. + */ + pixels: Uint32Array; + + /** + * An ArrayBuffer the same size as the context ImageData. + */ + buffer: ArrayBuffer; + + /** + * This re-creates the `imageData` from the current context. + * It then re-builds the ArrayBuffer, the `data` Uint8ClampedArray reference and the `pixels` Int32Array. + * + * Warning: This is a very expensive operation, so use it sparingly. + */ + update(): Phaser.Textures.CanvasTexture; + + /** + * Draws the given Image or Canvas element to this CanvasTexture, then updates the internal + * ImageData buffer and arrays. + * @param x The x coordinate to draw the source at. + * @param y The y coordinate to draw the source at. + * @param source The element to draw to this canvas. + */ + draw(x: integer, y: integer, source: HTMLImageElement | HTMLCanvasElement): Phaser.Textures.CanvasTexture; + + /** + * Draws the given texture frame to this CanvasTexture, then updates the internal + * ImageData buffer and arrays. + * @param key The unique string-based key of the Texture. + * @param frame The string-based name, or integer based index, of the Frame to get from the Texture. + * @param x The x coordinate to draw the source at. Default 0. + * @param y The y coordinate to draw the source at. Default 0. + */ + drawFrame(key: string, frame?: string | integer, x?: integer, y?: integer): Phaser.Textures.CanvasTexture; + + /** + * Sets a pixel in the CanvasTexture to the given color and alpha values. + * + * This is an expensive operation to run in large quantities, so use sparingly. + * @param x The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param y The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param red The red color value. A number between 0 and 255. + * @param green The green color value. A number between 0 and 255. + * @param blue The blue color value. A number between 0 and 255. + * @param alpha The alpha value. A number between 0 and 255. Default 255. + */ + setPixel(x: integer, y: integer, red: integer, green: integer, blue: integer, alpha?: integer): this; + + /** + * Puts the ImageData into the context of this CanvasTexture at the given coordinates. + * @param imageData The ImageData to put at the given location. + * @param x The x coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param y The y coordinate to put the imageData. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param dirtyX Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. Default 0. + * @param dirtyY Vertical position (x coordinate) of the top-left corner from which the image data will be extracted. Default 0. + * @param dirtyWidth Width of the rectangle to be painted. Defaults to the width of the image data. + * @param dirtyHeight Height of the rectangle to be painted. Defaults to the height of the image data. + */ + putData(imageData: ImageData, x: integer, y: integer, dirtyX?: integer, dirtyY?: integer, dirtyWidth?: integer, dirtyHeight?: integer): this; + + /** + * Gets an ImageData region from this CanvasTexture from the position and size specified. + * You can write this back using `CanvasTexture.putData`, or manipulate it. + * @param x The x coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param y The y coordinate of the top-left of the area to get the ImageData from. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param width The width of the rectangle from which the ImageData will be extracted. Positive values are to the right, and negative to the left. + * @param height The height of the rectangle from which the ImageData will be extracted. Positive values are down, and negative are up. + */ + getData(x: integer, y: integer, width: integer, height: integer): ImageData; + + /** + * Get the color of a specific pixel from this texture and store it in a Color object. + * + * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * @param x The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param y The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param out A Color object to store the pixel values in. If not provided a new Color object will be created. + */ + getPixel(x: integer, y: integer, out?: Phaser.Display.Color): Phaser.Display.Color; + + /** + * Returns an array containing all of the pixels in the given region. + * + * If the requested region extends outside the bounds of this CanvasTexture, + * the region is truncated to fit. + * + * If you have drawn anything to this CanvasTexture since it was created you must call `CanvasTexture.update` to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * @param x The x coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. Default 0. + * @param y The y coordinate of the top-left of the region. Must lay within the dimensions of this CanvasTexture and be an integer. Default 0. + * @param width The width of the region to get. Must be an integer. Defaults to the canvas width if not given. + * @param height The height of the region to get. Must be an integer. If not given will be set to the `width`. + */ + getPixels(x?: integer, y?: integer, width?: integer, height?: integer): Phaser.Types.Textures.PixelConfig[]; + + /** + * Returns the Image Data index for the given pixel in this CanvasTexture. + * + * The index can be used to read directly from the `this.data` array. + * + * The index points to the red value in the array. The subsequent 3 indexes + * point to green, blue and alpha respectively. + * @param x The x coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + * @param y The y coordinate of the pixel to get. Must lay within the dimensions of this CanvasTexture and be an integer. + */ + getIndex(x: integer, y: integer): integer; + + /** + * This should be called manually if you are running under WebGL. + * It will refresh the WebGLTexture from the Canvas source. Only call this if you know that the + * canvas has changed, as there is a significant GPU texture allocation cost involved in doing so. + */ + refresh(): Phaser.Textures.CanvasTexture; + + /** + * Gets the Canvas Element. + */ + getCanvas(): HTMLCanvasElement; + + /** + * Gets the 2D Canvas Rendering Context. + */ + getContext(): CanvasRenderingContext2D; + + /** + * Clears the given region of this Canvas Texture, resetting it back to transparent. + * If no region is given, the whole Canvas Texture is cleared. + * @param x The x coordinate of the top-left of the region to clear. Default 0. + * @param y The y coordinate of the top-left of the region to clear. Default 0. + * @param width The width of the region. + * @param height The height of the region. + */ + clear(x?: integer, y?: integer, width?: integer, height?: integer): Phaser.Textures.CanvasTexture; + + /** + * Changes the size of this Canvas Texture. + * @param width The new width of the Canvas. + * @param height The new height of the Canvas. If not given it will use the width as the height. + */ + setSize(width: integer, height?: integer): Phaser.Textures.CanvasTexture; + + /** + * Destroys this Texture and releases references to its sources and frames. + */ + destroy(): void; + + } + + /** + * Filter Types. + */ + enum FilterMode { + /** + * Linear filter type. + */ + LINEAR, + /** + * Nearest neighbor filter type. + */ + NEAREST, + } + + namespace Events { + /** + * The Texture Add Event. + * + * This event is dispatched by the Texture Manager when a texture is added to it. + * + * Listen to this event from within a Scene using: `this.textures.on('addtexture', listener)`. + */ + const ADD: any; + + /** + * The Texture Load Error Event. + * + * This event is dispatched by the Texture Manager when a texture it requested to load failed. + * This only happens when base64 encoded textures fail. All other texture types are loaded via the Loader Plugin. + * + * Listen to this event from within a Scene using: `this.textures.on('onerror', listener)`. + */ + const ERROR: any; + + /** + * The Texture Load Event. + * + * This event is dispatched by the Texture Manager when a texture has finished loading on it. + * This only happens for base64 encoded textures. All other texture types are loaded via the Loader Plugin. + * + * Listen to this event from within a Scene using: `this.textures.on('onload', listener)`. + * + * This event is dispatched after the [ADD]{@linkcode Phaser.Textures.Events#event:ADD} event. + */ + const LOAD: any; + + /** + * This internal event signifies that the Texture Manager is now ready and the Game can continue booting. + * + * When a Phaser Game instance is booting for the first time, the Texture Manager has to wait on a couple of non-blocking + * async events before it's fully ready to carry on. When those complete the Texture Manager emits this event via the Game + * instance, which tells the Game to carry on booting. + */ + const READY: any; + + /** + * The Texture Remove Event. + * + * This event is dispatched by the Texture Manager when a texture is removed from it. + * + * Listen to this event from within a Scene using: `this.textures.on('removetexture', listener)`. + * + * If you have any Game Objects still using the removed texture, they will start throwing + * errors the next time they try to render. Be sure to clear all use of the texture in this event handler. + */ + const REMOVE: any; + + } + + /** + * A Frame is a section of a Texture. + */ + class Frame { + /** + * + * @param texture The Texture this Frame is a part of. + * @param name The name of this Frame. The name is unique within the Texture. + * @param sourceIndex The index of the TextureSource that this Frame is a part of. + * @param x The x coordinate of the top-left of this Frame. + * @param y The y coordinate of the top-left of this Frame. + * @param width The width of this Frame. + * @param height The height of this Frame. + */ + constructor(texture: Phaser.Textures.Texture, name: integer | string, sourceIndex: integer, x: number, y: number, width: number, height: number); + + /** + * The Texture this Frame is a part of. + */ + texture: Phaser.Textures.Texture; + + /** + * The name of this Frame. + * The name is unique within the Texture. + */ + name: string; + + /** + * The TextureSource this Frame is part of. + */ + source: Phaser.Textures.TextureSource; + + /** + * The index of the TextureSource in the Texture sources array. + */ + sourceIndex: integer; + + /** + * A reference to the Texture Source WebGL Texture that this Frame is using. + */ + glTexture: WebGLTexture; + + /** + * X position within the source image to cut from. + */ + cutX: integer; + + /** + * Y position within the source image to cut from. + */ + cutY: integer; + + /** + * The width of the area in the source image to cut. + */ + cutWidth: integer; + + /** + * The height of the area in the source image to cut. + */ + cutHeight: integer; + + /** + * The X rendering offset of this Frame, taking trim into account. + */ + x: integer; + + /** + * The Y rendering offset of this Frame, taking trim into account. + */ + y: integer; + + /** + * The rendering width of this Frame, taking trim into account. + */ + width: integer; + + /** + * The rendering height of this Frame, taking trim into account. + */ + height: integer; + + /** + * Half the width, floored. + * Precalculated for the renderer. + */ + halfWidth: integer; + + /** + * Half the height, floored. + * Precalculated for the renderer. + */ + halfHeight: integer; + + /** + * The x center of this frame, floored. + */ + centerX: integer; + + /** + * The y center of this frame, floored. + */ + centerY: integer; + + /** + * The horizontal pivot point of this Frame. + */ + pivotX: number; + + /** + * The vertical pivot point of this Frame. + */ + pivotY: number; + + /** + * Does this Frame have a custom pivot point? + */ + customPivot: boolean; + + /** + * **CURRENTLY UNSUPPORTED** + * + * Is this frame is rotated or not in the Texture? + * Rotation allows you to use rotated frames in texture atlas packing. + * It has nothing to do with Sprite rotation. + */ + rotated: boolean; + + /** + * Over-rides the Renderer setting. + * -1 = use Renderer Setting + * 0 = No rounding + * 1 = Round + */ + autoRound: integer; + + /** + * Any Frame specific custom data can be stored here. + */ + customData: object; + + /** + * WebGL UV u0 value. + */ + u0: number; + + /** + * WebGL UV v0 value. + */ + v0: number; + + /** + * WebGL UV u1 value. + */ + u1: number; + + /** + * WebGL UV v1 value. + */ + v1: number; + + /** + * Sets the width, height, x and y of this Frame. + * + * This is called automatically by the constructor + * and should rarely be changed on-the-fly. + * @param width The width of the frame before being trimmed. + * @param height The height of the frame before being trimmed. + * @param x The x coordinate of the top-left of this Frame. Default 0. + * @param y The y coordinate of the top-left of this Frame. Default 0. + */ + setSize(width: integer, height: integer, x?: integer, y?: integer): Phaser.Textures.Frame; + + /** + * If the frame was trimmed when added to the Texture Atlas, this records the trim and source data. + * @param actualWidth The width of the frame before being trimmed. + * @param actualHeight The height of the frame before being trimmed. + * @param destX The destination X position of the trimmed frame for display. + * @param destY The destination Y position of the trimmed frame for display. + * @param destWidth The destination width of the trimmed frame for display. + * @param destHeight The destination height of the trimmed frame for display. + */ + setTrim(actualWidth: number, actualHeight: number, destX: number, destY: number, destWidth: number, destHeight: number): Phaser.Textures.Frame; + + /** + * 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. + * + * This is called directly by the Game Object Texture Components `setCrop` method. + * Please use that method to crop a Game Object. + * @param crop The crop data object. This is the `GameObject._crop` property. + * @param x The x coordinate to start the crop from. Cannot be negative or exceed the Frame width. + * @param y The y coordinate to start the crop from. Cannot be negative or exceed the Frame height. + * @param width The width of the crop rectangle. Cannot exceed the Frame width. + * @param height The height of the crop rectangle. Cannot exceed the Frame height. + * @param flipX Does the parent Game Object have flipX set? + * @param flipY Does the parent Game Object have flipY set? + */ + setCropUVs(crop: object, x: number, y: number, width: number, height: number, flipX: boolean, flipY: boolean): object; + + /** + * Takes a crop data object and recalculates the UVs based on the dimensions inside the crop object. + * Called automatically by `setFrame`. + * @param crop The crop data object. This is the `GameObject._crop` property. + * @param flipX Does the parent Game Object have flipX set? + * @param flipY Does the parent Game Object have flipY set? + */ + updateCropUVs(crop: object, flipX: boolean, flipY: boolean): object; + + /** + * Updates the internal WebGL UV cache and the drawImage cache. + */ + updateUVs(): Phaser.Textures.Frame; + + /** + * Updates the internal WebGL UV cache. + */ + updateUVsInverted(): Phaser.Textures.Frame; + + /** + * Clones this Frame into a new Frame object. + */ + clone(): Phaser.Textures.Frame; + + /** + * Destroys this Frame by nulling its reference to the parent Texture and and data objects. + */ + destroy(): void; + + /** + * The width of the Frame in its un-trimmed, un-padded state, as prepared in the art package, + * before being packed. + */ + readonly realWidth: number; + + /** + * The height of the Frame in its un-trimmed, un-padded state, as prepared in the art package, + * before being packed. + */ + readonly realHeight: number; + + /** + * The radius of the Frame (derived from sqrt(w * w + h * h) / 2) + */ + readonly radius: number; + + /** + * Is the Frame trimmed or not? + */ + readonly trimmed: boolean; + + /** + * The Canvas drawImage data object. + */ + readonly canvasData: object; + + } + + /** + * Linear filter type. + */ + const LINEAR: integer; + + /** + * Nearest Neighbor filter type. + */ + const NEAREST: integer; + + namespace Parsers { + } + + /** + * A Texture consists of a source, usually an Image from the Cache, and a collection of Frames. + * The Frames represent the different areas of the Texture. For example a texture atlas + * may have many Frames, one for each element within the atlas. Where-as a single image would have + * just one frame, that encompasses the whole image. + * + * Every Texture, no matter where it comes from, always has at least 1 frame called the `__BASE` frame. + * This frame represents the entirety of the source image. + * + * Textures are managed by the global TextureManager. This is a singleton class that is + * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. + * + * Sprites and other Game Objects get the texture data they need from the TextureManager. + */ + class Texture { + /** + * + * @param manager A reference to the Texture Manager this Texture belongs to. + * @param key The unique string-based key of this Texture. + * @param source An array of sources that are used to create the texture. Usually Images, but can also be a Canvas. + * @param width The width of the Texture. This is optional and automatically derived from the source images. + * @param height The height of the Texture. This is optional and automatically derived from the source images. + */ + constructor(manager: Phaser.Textures.TextureManager, key: string, source: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[], width?: number, height?: number); + + /** + * A reference to the Texture Manager this Texture belongs to. + */ + manager: Phaser.Textures.TextureManager; + + /** + * The unique string-based key of this Texture. + */ + key: string; + + /** + * An array of TextureSource instances. + * These are unique to this Texture and contain the actual Image (or Canvas) data. + */ + source: Phaser.Textures.TextureSource[]; + + /** + * An array of TextureSource data instances. + * Used to store additional data images, such as normal maps or specular maps. + */ + dataSource: any[]; + + /** + * A key-value object pair associating the unique Frame keys with the Frames objects. + */ + frames: object; + + /** + * Any additional data that was set in the source JSON (if any), + * or any extra data you'd like to store relating to this texture + */ + customData: object; + + /** + * The name of the first frame of the Texture. + */ + firstFrame: string; + + /** + * The total number of Frames in this Texture, including the `__BASE` frame. + * + * A Texture will always contain at least 1 frame because every Texture contains a `__BASE` frame by default, + * in addition to any extra frames that have been added to it, such as when parsing a Sprite Sheet or Texture Atlas. + */ + frameTotal: integer; + + /** + * Adds a new Frame to this Texture. + * + * A Frame is a rectangular region of a TextureSource with a unique index or string-based key. + * + * The name given must be unique within this Texture. If it already exists, this method will return `null`. + * @param name The name of this Frame. The name is unique within the Texture. + * @param sourceIndex The index of the TextureSource that this Frame is a part of. + * @param x The x coordinate of the top-left of this Frame. + * @param y The y coordinate of the top-left of this Frame. + * @param width The width of this Frame. + * @param height The height of this Frame. + */ + add(name: integer | string, sourceIndex: integer, x: number, y: number, width: number, height: number): Phaser.Textures.Frame; + + /** + * Removes the given Frame from this Texture. The Frame is destroyed immediately. + * + * Any Game Objects using this Frame should stop using it _before_ you remove it, + * as it does not happen automatically. + * @param name The key of the Frame to remove. + */ + remove(name: string): boolean; + + /** + * Checks to see if a Frame matching the given key exists within this Texture. + * @param name The key of the Frame to check for. + */ + has(name: string): boolean; + + /** + * 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. + * @param name The string-based name, or integer based index, of the Frame to get from this Texture. + */ + get(name?: string | integer): Phaser.Textures.Frame; + + /** + * Takes the given TextureSource and returns the index of it within this Texture. + * If it's not in this Texture, it returns -1. + * Unless this Texture has multiple TextureSources, such as with a multi-atlas, this + * method will always return zero or -1. + * @param source The TextureSource to check. + */ + getTextureSourceIndex(source: Phaser.Textures.TextureSource): integer; + + /** + * Returns an array of all the Frames in the given TextureSource. + * @param sourceIndex The index of the TextureSource to get the Frames from. + * @param includeBase Include the `__BASE` Frame in the output array? Default false. + */ + getFramesFromTextureSource(sourceIndex: integer, includeBase?: boolean): Phaser.Textures.Frame[]; + + /** + * Returns an array with all of the names of the Frames in this Texture. + * + * Useful if you want to randomly assign a Frame to a Game Object, as you can + * pick a random element from the returned array. + * @param includeBase Include the `__BASE` Frame in the output array? Default false. + */ + getFrameNames(includeBase?: boolean): string[]; + + /** + * Given a Frame name, return the source image it uses to render with. + * + * This will return the actual DOM Image or Canvas element. + * @param name The string-based name, or integer based index, of the Frame to get from this Texture. + */ + getSourceImage(name?: string | integer): HTMLImageElement | HTMLCanvasElement | Phaser.GameObjects.RenderTexture; + + /** + * Given a Frame name, return the data source image it uses to render with. + * You can use this to get the normal map for an image for example. + * + * This will return the actual DOM Image. + * @param name The string-based name, or integer based index, of the Frame to get from this Texture. + */ + getDataSourceImage(name?: string | integer): HTMLImageElement | HTMLCanvasElement; + + /** + * Adds a data source image to this Texture. + * + * An example of a data source image would be a normal map, where all of the Frames for this Texture + * equally apply to the normal map. + * @param data The source image. + */ + setDataSource(data: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): void; + + /** + * Sets the Filter Mode for this Texture. + * + * The mode can be either Linear, the default, or Nearest. + * + * For pixel-art you should use Nearest. + * + * The mode applies to the entire Texture, not just a specific Frame of it. + * @param filterMode The Filter Mode. + */ + setFilter(filterMode: Phaser.Textures.FilterMode): void; + + /** + * Destroys this Texture and releases references to its sources and frames. + */ + destroy(): void; + + } + + /** + * Textures are managed by the global TextureManager. This is a singleton class that is + * responsible for creating and delivering Textures and their corresponding Frames to Game Objects. + * + * Sprites and other Game Objects get the texture data they need from the TextureManager. + * + * Access it via `scene.textures`. + */ + class TextureManager extends Phaser.Events.EventEmitter { + /** + * + * @param game The Phaser.Game instance this Texture Manager belongs to. + */ + constructor(game: Phaser.Game); + + /** + * The Game that this TextureManager belongs to. + */ + game: Phaser.Game; + + /** + * The name of this manager. + */ + name: string; + + /** + * An object that has all of textures that Texture Manager creates. + * Textures are assigned to keys so we can access to any texture that this object has directly by key value without iteration. + */ + list: object; + + /** + * Checks the given texture key and throws a console.warn if the key is already in use, then returns false. + * If you wish to avoid the console.warn then use `TextureManager.exists` instead. + * @param key The texture key to check. + */ + checkKey(key: string): boolean; + + /** + * Removes a Texture from the Texture Manager and destroys it. This will immediately + * clear all references to it from the Texture Manager, and if it has one, destroy its + * WebGLTexture. This will emit a `removetexture` event. + * + * Note: If you have any Game Objects still using this texture they will start throwing + * errors the next time they try to render. Make sure that removing the texture is the final + * step when clearing down to avoid this. + * @param key The key of the Texture to remove, or a reference to it. + */ + remove(key: string | Phaser.Textures.Texture): Phaser.Textures.TextureManager; + + /** + * Removes a key from the Texture Manager but does not destroy the Texture that was using the key. + * @param key The key to remove from the texture list. + */ + removeKey(key: string): Phaser.Textures.TextureManager; + + /** + * Adds a new Texture to the Texture Manager created from the given Base64 encoded data. + * @param key The unique string-based key of the Texture. + * @param data The Base64 encoded data. + */ + addBase64(key: string, data: any): this; + + /** + * Gets an existing texture frame and converts it into a base64 encoded image and returns the base64 data. + * + * You can also provide the image type and encoder options. + * + * This will only work with bitmap based texture frames, such as those created from Texture Atlases. + * It will not work with GL Texture objects, such as Shaders, or Render Textures. For those please + * see the WebGL Snapshot function instead. + * @param key The unique string-based key of the Texture. + * @param frame The string-based name, or integer based index, of the Frame to get from the Texture. + * @param type [description] Default 'image/png'. + * @param encoderOptions [description] Default 0.92. + */ + getBase64(key: string, frame?: string | integer, type?: string, encoderOptions?: number): string; + + /** + * Adds a new Texture to the Texture Manager created from the given Image element. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param dataSource An optional data Image element. + */ + addImage(key: string, source: HTMLImageElement, dataSource?: HTMLImageElement | HTMLCanvasElement): Phaser.Textures.Texture; + + /** + * Takes a WebGL Texture and creates a Phaser Texture from it, which is added to the Texture Manager using the given key. + * + * This allows you to then use the Texture as a normal texture for texture based Game Objects like Sprites. + * + * This is a WebGL only feature. + * @param key The unique string-based key of the Texture. + * @param glTexture The source Render Texture. + * @param width The new width of the Texture. + * @param height The new height of the Texture. + */ + addGLTexture(key: string, glTexture: WebGLTexture, width: number, height: number): Phaser.Textures.Texture; + + /** + * Adds a Render Texture to the Texture Manager using the given key. + * This allows you to then use the Render Texture as a normal texture for texture based Game Objects like Sprites. + * @param key The unique string-based key of the Texture. + * @param renderTexture The source Render Texture. + */ + addRenderTexture(key: string, renderTexture: Phaser.GameObjects.RenderTexture): Phaser.Textures.Texture; + + /** + * Creates a new Texture using the given config values. + * Generated textures consist of a Canvas element to which the texture data is drawn. + * See the Phaser.Create function for the more direct way to create textures. + * @param key The unique string-based key of the Texture. + * @param config The configuration object needed to generate the texture. + */ + generate(key: string, config: object): Phaser.Textures.Texture; + + /** + * Creates a new Texture using a blank Canvas element of the size given. + * + * Canvas elements are automatically pooled and calling this method will + * extract a free canvas from the CanvasPool, or create one if none are available. + * @param key The unique string-based key of the Texture. + * @param width The width of the Canvas element. Default 256. + * @param height The height of the Canvas element. Default 256. + */ + createCanvas(key: string, width?: integer, height?: integer): Phaser.Textures.CanvasTexture; + + /** + * Creates a new Canvas Texture object from an existing Canvas element + * and adds it to this Texture Manager, unless `skipCache` is true. + * @param key The unique string-based key of the Texture. + * @param source The Canvas element to form the base of the new Texture. + * @param skipCache Skip adding this Texture into the Cache? Default false. + */ + addCanvas(key: string, source: HTMLCanvasElement, skipCache?: boolean): Phaser.Textures.CanvasTexture; + + /** + * Adds a new Texture Atlas to this Texture Manager. + * It can accept either JSON Array or JSON Hash formats, as exported by Texture Packer and similar software. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param data The Texture Atlas data. + * @param dataSource An optional data Image element. + */ + addAtlas(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; + + /** + * Adds a Texture Atlas to this Texture Manager. + * The frame data of the atlas must be stored in an Array within the JSON. + * This is known as a JSON Array in software such as Texture Packer. + * @param key The unique string-based key of the Texture. + * @param source The source Image element/s. + * @param data The Texture Atlas data/s. + * @param dataSource An optional data Image element. + */ + addAtlasJSONArray(key: string, source: HTMLImageElement | HTMLImageElement[], data: object | object[], dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; + + /** + * Adds a Texture Atlas to this Texture Manager. + * The frame data of the atlas must be stored in an Object within the JSON. + * This is known as a JSON Hash in software such as Texture Packer. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param data The Texture Atlas data. + * @param dataSource An optional data Image element. + */ + addAtlasJSONHash(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; + + /** + * Adds a Texture Atlas to this Texture Manager, where the atlas data is given + * in the XML format. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param data The Texture Atlas XML data. + * @param dataSource An optional data Image element. + */ + addAtlasXML(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; + + /** + * Adds a Unity Texture Atlas to this Texture Manager. + * The data must be in the form of a Unity YAML file. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param data The Texture Atlas data. + * @param dataSource An optional data Image element. + */ + addUnityAtlas(key: string, source: HTMLImageElement, data: object, dataSource?: HTMLImageElement | HTMLCanvasElement | HTMLImageElement[] | HTMLCanvasElement[]): Phaser.Textures.Texture; + + /** + * Adds a Sprite Sheet to this Texture Manager. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param config The configuration object for this Sprite Sheet. + */ + addSpriteSheet(key: string, source: HTMLImageElement, config: Phaser.Types.Textures.SpriteSheetConfig): Phaser.Textures.Texture; + + /** + * Adds a Sprite Sheet to this Texture Manager, where the Sprite Sheet exists as a Frame within a Texture Atlas. + * + * In Phaser terminology a Sprite Sheet is a texture containing different frames, but each frame is the exact + * same size and cannot be trimmed or rotated. + * @param key The unique string-based key of the Texture. + * @param config The configuration object for this Sprite Sheet. + */ + addSpriteSheetFromAtlas(key: string, config: Phaser.Types.Textures.SpriteSheetFromAtlasConfig): Phaser.Textures.Texture; + + /** + * Creates a new Texture using the given source and dimensions. + * @param key The unique string-based key of the Texture. + * @param source The source Image element. + * @param width The width of the Texture. + * @param height The height of the Texture. + */ + create(key: string, source: HTMLImageElement, width: integer, height: integer): Phaser.Textures.Texture; + + /** + * Checks the given key to see if a Texture using it exists within this Texture Manager. + * @param key The unique string-based key of the Texture. + */ + exists(key: string): boolean; + + /** + * Returns a Texture from the Texture Manager that matches the given key. + * + * If the key is `undefined` it will return the `__DEFAULT` Texture. + * + * If the key is an instance of a Texture, it will return the key directly. + * + * Finally. if the key is given, but not found and not a Texture instance, it will return the `__MISSING` Texture. + * @param key The unique string-based key of the Texture, or a Texture instance. + */ + get(key: string | Phaser.Textures.Texture): Phaser.Textures.Texture; + + /** + * Takes a Texture key and Frame name and returns a clone of that Frame if found. + * @param key The unique string-based key of the Texture. + * @param frame The string or index of the Frame to be cloned. + */ + cloneFrame(key: string, frame: string | integer): Phaser.Textures.Frame; + + /** + * Takes a Texture key and Frame name and returns a reference to that Frame, if found. + * @param key The unique string-based key of the Texture. + * @param frame The string-based name, or integer based index, of the Frame to get from the Texture. + */ + getFrame(key: string, frame?: string | integer): Phaser.Textures.Frame; + + /** + * Returns an array with all of the keys of all Textures in this Texture Manager. + * The output array will exclude the `__DEFAULT` and `__MISSING` keys. + */ + getTextureKeys(): string[]; + + /** + * Given a Texture and an `x` and `y` coordinate this method will return a new + * Color object that has been populated with the color and alpha values of the pixel + * at that location in the Texture. + * @param x The x coordinate of the pixel within the Texture. + * @param y The y coordinate of the pixel within the Texture. + * @param key The unique string-based key of the Texture. + * @param frame The string or index of the Frame. + */ + getPixel(x: integer, y: integer, key: string, frame?: string | integer): Phaser.Display.Color; + + /** + * Given a Texture and an `x` and `y` coordinate this method will return a value between 0 and 255 + * corresponding to the alpha value of the pixel at that location in the Texture. If the coordinate + * is out of bounds it will return null. + * @param x The x coordinate of the pixel within the Texture. + * @param y The y coordinate of the pixel within the Texture. + * @param key The unique string-based key of the Texture. + * @param frame The string or index of the Frame. + */ + getPixelAlpha(x: integer, y: integer, key: string, frame?: string | integer): integer; + + /** + * Sets the given Game Objects `texture` and `frame` properties so that it uses + * the Texture and Frame specified in the `key` and `frame` arguments to this method. + * @param gameObject The Game Object the texture would be set on. + * @param key The unique string-based key of the Texture. + * @param frame The string or index of the Frame. + */ + setTexture(gameObject: Phaser.GameObjects.GameObject, key: string, frame?: string | integer): Phaser.GameObjects.GameObject; + + /** + * Changes the key being used by a Texture to the new key provided. + * + * The old key is removed, allowing it to be re-used. + * + * Game Objects are linked to Textures by a reference to the Texture object, so + * all existing references will be retained. + * @param currentKey The current string-based key of the Texture you wish to rename. + * @param newKey The new unique string-based key to use for the Texture. + */ + renameTexture(currentKey: string, newKey: string): boolean; + + /** + * Passes all Textures to the given callback. + * @param callback The callback function to be sent the Textures. + * @param scope The value to use as `this` when executing the callback. + * @param args Additional arguments that will be passed to the callback, after the child. + */ + each(callback: EachTextureCallback, scope: object, ...args: any[]): void; + + /** + * Destroys the Texture Manager and all Textures stored within it. + */ + destroy(): void; + + } + + /** + * A Texture Source is the encapsulation of the actual source data for a Texture. + * + * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element. + * + * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded. + */ + class TextureSource { + /** + * + * @param texture The Texture this TextureSource belongs to. + * @param source The source image data. + * @param width Optional width of the source image. If not given it's derived from the source itself. + * @param height Optional height of the source image. If not given it's derived from the source itself. + * @param flipY Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. Default false. + */ + constructor(texture: Phaser.Textures.Texture, source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | Phaser.GameObjects.RenderTexture | WebGLTexture, width?: integer, height?: integer, flipY?: boolean); + + /** + * The Texture this TextureSource belongs to. + */ + renderer: Phaser.Renderer.Canvas.CanvasRenderer | Phaser.Renderer.WebGL.WebGLRenderer; + + /** + * The Texture this TextureSource belongs to. + */ + texture: Phaser.Textures.Texture; + + /** + * The source of the image data. + * + * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture. + */ + source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | Phaser.GameObjects.RenderTexture | WebGLTexture; + + /** + * The image data. + * + * This is either an Image element, Canvas element or a Video Element. + */ + image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; + + /** + * Currently un-used. + */ + compressionAlgorithm: integer; + + /** + * The resolution of the source image. + */ + resolution: number; + + /** + * The width of the source image. If not specified in the constructor it will check + * the `naturalWidth` and then `width` properties of the source image. + */ + width: integer; + + /** + * The height of the source image. If not specified in the constructor it will check + * the `naturalHeight` and then `height` properties of the source image. + */ + height: integer; + + /** + * The Scale Mode the image will use when rendering. + * Either Linear or Nearest. + */ + scaleMode: number; + + /** + * Is the source image a Canvas Element? + */ + isCanvas: boolean; + + /** + * Is the source image a Video Element? + */ + isVideo: boolean; + + /** + * Is the source image a Render Texture? + */ + isRenderTexture: boolean; + + /** + * Is the source image a WebGLTexture? + */ + isGLTexture: boolean; + + /** + * Are the source image dimensions a power of two? + */ + isPowerOf2: boolean; + + /** + * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture + * already, then this is a reference to that WebGLTexture. + */ + glTexture: WebGLTexture; + + /** + * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload. + */ + flipY: boolean; + + /** + * Creates a WebGL Texture, if required, and sets the Texture filter mode. + * @param game A reference to the Phaser Game instance. + */ + init(game: Phaser.Game): void; + + /** + * Sets the Filter Mode for this Texture. + * + * The mode can be either Linear, the default, or Nearest. + * + * For pixel-art you should use Nearest. + * @param filterMode The Filter Mode. + */ + setFilter(filterMode: Phaser.Textures.FilterMode): void; + + /** + * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload. + * @param value Should the WebGL Texture be flipped on the Y axis on texture upload or not? Default true. + */ + setFlipY(value?: boolean): void; + + /** + * If this TextureSource is backed by a Canvas and is running under WebGL, + * it updates the WebGLTexture using the canvas data. + */ + update(): void; + + /** + * Destroys this Texture Source and nulls the references. + */ + destroy(): void; + + } + + } + + namespace Tilemaps { + namespace Components { + } + + /** + * A Dynamic Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination + * with one, or more, Tilesets. + * + * A Dynamic Tilemap Layer trades some speed for being able to apply powerful effects. Unlike a + * Static Tilemap Layer, you can apply per-tile effects like tint or alpha, and you can change the + * tiles in a DynamicTilemapLayer. + * + * Use this over a Static Tilemap Layer when you need those features. + */ + class DynamicTilemapLayer extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.ScrollFactor, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible { + /** + * + * @param scene The Scene to which this Game Object belongs. + * @param tilemap The Tilemap this layer is a part of. + * @param layerIndex The index of the LayerData associated with this layer. + * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param x The world x position where the top left of this layer will be placed. Default 0. + * @param y The world y position where the top left of this layer will be placed. Default 0. + */ + constructor(scene: Phaser.Scene, tilemap: Phaser.Tilemaps.Tilemap, layerIndex: integer, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number); + + /** + * Used internally by physics system to perform fast type checks. + */ + readonly isTilemap: boolean; + + /** + * The Tilemap that this layer is a part of. + */ + tilemap: Phaser.Tilemaps.Tilemap; + + /** + * The index of the LayerData associated with this layer. + */ + layerIndex: integer; + + /** + * The LayerData associated with this layer. LayerData can only be associated with one + * tilemap layer. + */ + layer: Phaser.Tilemaps.LayerData; + + /** + * The Tileset/s associated with this layer. + * + * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. + */ + tileset: Phaser.Tilemaps.Tileset[]; + + /** + * Used internally with the canvas render. This holds the tiles that are visible within the + * camera. + */ + culledTiles: any[]; + + /** + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this, and toggling this flag allows + * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. + */ + skipCull: boolean; + + /** + * The total number of tiles drawn by the renderer in the last frame. + */ + readonly tilesDrawn: integer; + + /** + * The total number of tiles in this layer. Updated every frame. + */ + readonly tilesTotal: integer; + + /** + * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. + * + * See the method `setCullPadding` for more details. + */ + cullPaddingX: integer; + + /** + * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. + * + * See the method `setCullPadding` for more details. + */ + cullPaddingY: integer; + + /** + * The callback that is invoked when the tiles are culled. + * + * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. + * + * It will be sent 3 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. + * + * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. + */ + cullCallback: Function; + + /** + * An array holding the mapping between the tile indexes and the tileset they belong to. + */ + gidMap: Phaser.Tilemaps.Tileset[]; + + /** + * Sets the rendering (draw) order of the tiles in this layer. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * @param renderOrder The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + */ + setRenderOrder(renderOrder: integer | string): this; + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * @param tileX The x coordinate. + * @param tileY The y coordinate. + */ + calculateFacesAt(tileX: integer, tileY: integer): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + */ + calculateFacesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * @param indexes The tile index, or array of indexes, to create Sprites from. + * @param replacements The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param spriteConfig The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param scene The Scene to create the Sprites within. Default scene the map is within. + * @param camera The Camera to use when determining the world XY Default main camera. + */ + createFromTiles(indexes: integer | any[], replacements: integer | any[], spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.GameObjects.Sprite[]; + + /** + * Returns the tiles in the given layer that are within the cameras viewport. + * This is used internally. + * @param camera The Camera to run the cull check against. + */ + cull(camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; + + /** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * @param srcTileX The x coordinate of the area to copy from, in tiles, not pixels. + * @param srcTileY The y coordinate of the area to copy from, in tiles, not pixels. + * @param width The width of the area to copy, in tiles, not pixels. + * @param height The height of the area to copy, in tiles, not pixels. + * @param destTileX The x coordinate of the area to copy to, in tiles, not pixels. + * @param destTileY The y coordinate of the area to copy to, in tiles, not pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + */ + copy(srcTileX: integer, srcTileY: integer, width: integer, height: integer, destTileX: integer, destTileY: integer, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Destroys this DynamicTilemapLayer and removes its link to the associated LayerData. + * @param removeFromTilemap Remove this layer from the parent Tilemap? Default true. + */ + destroy(removeFromTilemap?: boolean): void; + + /** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * @param index The tile index to fill the area with. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + */ + fill(index: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * @param callback The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + filterTiles(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * @param index The tile index value to search for. + * @param skip The number of times to skip a matching tile before returning. Default 0. + * @param reverse If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. Default false. + */ + findByIndex(index: integer, skip?: integer, reverse?: boolean): Phaser.Tilemaps.Tile; + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + findTile(callback: FindTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile; + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + forEachTile(callback: EachTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Gets a tile at the given tile coordinates from the given layer. + * @param tileX X position to get the tile from (given in tile units, not pixels). + * @param tileY Y position to get the tile from (given in tile units, not pixels). + * @param nonNull If true getTile won't return null for empty tiles, but a Tile object with an index of -1. Default false. + */ + getTileAt(tileX: integer, tileY: integer, nonNull?: boolean): Phaser.Tilemaps.Tile; + + /** + * Gets a tile at the given world coordinates from the given layer. + * @param worldX X position to get the tile from (given in pixels) + * @param worldY Y position to get the tile from (given in pixels) + * @param nonNull If true, function won't return null for empty tiles, but a Tile object with an index of -1. Default false. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + getTileAtWorldXY(worldX: number, worldY: number, nonNull?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + getTilesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * @param shape A shape in world (pixel) coordinates + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + */ + getTilesWithinShape(shape: Phaser.Geom.Circle | Phaser.Geom.Line | Phaser.Geom.Rectangle | Phaser.Geom.Triangle, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * @param worldX The world x coordinate for the top-left of the area. + * @param worldY The world y coordinate for the top-left of the area. + * @param width The width of the area. + * @param height The height of the area. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + */ + getTilesWithinWorldXY(worldX: number, worldY: number, width: number, height: number, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + */ + hasTileAt(tileX: integer, tileY: integer): boolean; + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * @param worldX The x coordinate, in pixels. + * @param worldY The y coordinate, in pixels. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + */ + hasTileAtWorldXY(worldX: number, worldY: number, camera?: Phaser.Cameras.Scene2D.Camera): boolean; + + /** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * @param tile The index of this tile to set or a Tile object. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + */ + putTileAt(tile: integer | Phaser.Tilemaps.Tile, tileX: integer, tileY: integer, recalculateFaces?: boolean): Phaser.Tilemaps.Tile; + + /** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * @param tile The index of this tile to set or a Tile object. + * @param worldX The x coordinate, in pixels. + * @param worldY The y coordinate, in pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + putTileAtWorldXY(tile: integer | Phaser.Tilemaps.Tile, worldX: number, worldY: number, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; + + /** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * @param tile A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + */ + putTilesAt(tile: integer[] | integer[][] | Phaser.Tilemaps.Tile[] | Phaser.Tilemaps.Tile[][], tileX: integer, tileY: integer, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param indexes An array of indexes to randomly draw from during randomization. + */ + randomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, indexes?: integer[]): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + */ + removeTileAt(tileX: integer, tileY: integer, replaceWithNull?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.Tile; + + /** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * @param worldX The x coordinate, in pixels. + * @param worldY The y coordinate, in pixels. + * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + removeTileAtWorldXY(worldX: number, worldY: number, replaceWithNull?: boolean, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * @param graphics The target Graphics object to draw upon. + * @param styleConfig An object specifying the colors to use for the debug drawing. + */ + renderDebug(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * @param findIndex The index of the tile to search for. + * @param newIndex The index of the tile to replace it with. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + */ + replaceByIndex(findIndex: integer, newIndex: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this. + * @param value Set to `true` to stop culling tiles. Set to `false` to enable culling again. Default true. + */ + setSkipCull(value?: boolean): this; + + /** + * When a Camera culls the tiles in this layer it does so using its view into the world, building up a + * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size + * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so + * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px + * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) + * @param paddingX The amount of extra horizontal tiles to add to the cull check padding. Default 1. + * @param paddingY The amount of extra vertical tiles to add to the cull check padding. Default 1. + */ + setCullPadding(paddingX?: integer, paddingY?: integer): this; + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * @param indexes Either a single tile index, or an array of tile indexes. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + * @param updateLayer If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. Default true. + */ + setCollision(indexes: integer | any[], collides?: boolean, recalculateFaces?: boolean, updateLayer?: boolean): Phaser.Tilemaps.Tilemap; + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * @param start The first index of the tile to be set for collision. + * @param stop The last index of the tile to be set for collision. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + */ + setCollisionBetween(start: integer, stop: integer, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * @param properties An object with tile properties and corresponding values that should be checked. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + */ + setCollisionByProperty(properties: object, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * @param indexes An array of the tile indexes to not be counted for collision. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + */ + setCollisionByExclusion(indexes: integer[], collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Sets collision on the tiles within a layer by checking each tiles collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tiles collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + */ + setCollisionFromCollisionGroup(collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * @param indexes Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param callback The callback that will be invoked when the tile is collided with. + * @param callbackContext The context under which the callback is called. + */ + setTileIndexCallback(indexes: integer | integer[], callback: Function, callbackContext: object): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param callback The callback that will be invoked when the tile is collided with. + * @param callbackContext The context under which the callback is called. + */ + setTileLocationCallback(tileX?: integer, tileY?: integer, width?: integer, height?: integer, callback?: Function, callbackContext?: object): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + */ + shuffle(tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * @param tileA First tile index. + * @param tileB Second tile index. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + */ + swapByIndex(tileA: integer, tileB: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * @param tileX The x coordinate, in tiles, not pixels. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + tileToWorldX(tileX: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * @param tileY The y coordinate, in tiles, not pixels. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + tileToWorldY(tileY: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + tileToWorldXY(tileX: integer, tileY: integer, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param weightedIndexes An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + */ + weightedRandomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, weightedIndexes?: object[]): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * @param worldX The x coordinate to be converted, in pixels, not tiles. + * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + worldToTileX(worldX: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * @param worldY The y coordinate to be converted, in pixels, not tiles. + * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + worldToTileY(worldY: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * @param worldX The x coordinate to be converted, in pixels, not tiles. + * @param worldY The y coordinate to be converted, in pixels, not tiles. + * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. + * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + worldToTileXY(worldX: number, worldY: number, snapToFloor?: boolean, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + namespace Formats { + /** + * CSV Map Type + */ + var CSV: number; + + /** + * Tiled JSON Map Type + */ + var TILED_JSON: number; + + /** + * 2D Array Map Type + */ + var ARRAY_2D: number; + + /** + * Weltmeister (Impact.js) Map Type + */ + var WELTMEISTER: number; + + } + + /** + * An Image Collection is a special Tile Set containing multiple images, with no slicing into each image. + * + * Image Collections are normally created automatically when Tiled data is loaded. + */ + class ImageCollection { + /** + * + * @param name The name of the image collection in the map data. + * @param firstgid The first image index this image collection contains. + * @param width Width of widest image (in pixels). Default 32. + * @param height Height of tallest image (in pixels). Default 32. + * @param margin The margin around all images in the collection (in pixels). Default 0. + * @param spacing The spacing between each image in the collection (in pixels). Default 0. + * @param properties Custom Image Collection properties. Default {}. + */ + constructor(name: string, firstgid: integer, width?: integer, height?: integer, margin?: integer, spacing?: integer, properties?: object); + + /** + * The name of the Image Collection. + */ + name: string; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + */ + firstgid: integer; + + /** + * The width of the widest image (in pixels). + */ + readonly imageWidth: integer; + + /** + * The height of the tallest image (in pixels). + */ + readonly imageHeight: integer; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + */ + readonly imageMarge: integer; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + */ + readonly imageSpacing: integer; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + */ + properties: object; + + /** + * The cached images that are a part of this collection. + */ + readonly images: any[]; + + /** + * The total number of images in the image collection. + */ + readonly total: integer; + + /** + * Returns true if and only if this image collection contains the given image index. + * @param imageIndex The image index to search for. + */ + containsImageIndex(imageIndex: integer): boolean; + + /** + * Add an image to this Image Collection. + * @param gid The gid of the image in the Image Collection. + * @param image The the key of the image in the Image Collection and in the cache. + */ + addImage(gid: integer, image: string): Phaser.Tilemaps.ImageCollection; + + } + + /** + * A class for representing data about about a layer in a map. Maps are parsed from CSV, Tiled, + * etc. into this format. Tilemap, StaticTilemapLayer and DynamicTilemapLayer have a reference + * to this data and use it to look up and perform operations on tiles. + */ + class LayerData { + /** + * + * @param config [description] + */ + constructor(config?: object); + + /** + * The name of the layer, if specified in Tiled. + */ + name: string; + + /** + * The x offset of where to draw from the top left + */ + x: number; + + /** + * The y offset of where to draw from the top left + */ + y: number; + + /** + * The width in tile of the layer. + */ + width: number; + + /** + * The height in tiles of the layer. + */ + height: number; + + /** + * The pixel width of the tiles. + */ + tileWidth: number; + + /** + * The pixel height of the tiles. + */ + tileHeight: number; + + /** + * [description] + */ + baseTileWidth: number; + + /** + * [description] + */ + baseTileHeight: number; + + /** + * The width in pixels of the entire layer. + */ + widthInPixels: number; + + /** + * The height in pixels of the entire layer. + */ + heightInPixels: number; + + /** + * [description] + */ + alpha: number; + + /** + * [description] + */ + visible: boolean; + + /** + * Layer specific properties (can be specified in Tiled) + */ + properties: object; + + /** + * [description] + */ + indexes: any[]; + + /** + * [description] + */ + collideIndexes: any[]; + + /** + * [description] + */ + callbacks: any[]; + + /** + * [description] + */ + bodies: any[]; + + /** + * An array of the tile indexes + */ + data: Phaser.Tilemaps.Tile[][]; + + /** + * [description] + */ + tilemapLayer: Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer; + + } + + /** + * A class for representing data about a map. Maps are parsed from CSV, Tiled, etc. into this + * format. A Tilemap object get a copy of this data and then unpacks the needed properties into + * itself. + */ + class MapData { + /** + * + * @param config The Map configuration object. + */ + constructor(config?: Phaser.Types.Tilemaps.MapDataConfig); + + /** + * The key in the Phaser cache that corresponds to the loaded tilemap data. + */ + name: string; + + /** + * The width of the entire tilemap. + */ + width: number; + + /** + * The height of the entire tilemap. + */ + height: number; + + /** + * If the map is infinite or not. + */ + infinite: boolean; + + /** + * The width of the tiles. + */ + tileWidth: number; + + /** + * The height of the tiles. + */ + tileHeight: number; + + /** + * The width in pixels of the entire tilemap. + */ + widthInPixels: number; + + /** + * The height in pixels of the entire tilemap. + */ + heightInPixels: number; + + /** + * [description] + */ + format: integer; + + /** + * The orientation of the map data (i.e. orthogonal, isometric, hexagonal), default 'orthogonal'. + */ + orientation: string; + + /** + * Determines the draw order of tilemap. Default is right-down + * + * 0, or 'right-down' + * 1, or 'left-down' + * 2, or 'right-up' + * 3, or 'left-up' + */ + renderOrder: string; + + /** + * The version of the map data (as specified in Tiled). + */ + version: string; + + /** + * Map specific properties (can be specified in Tiled) + */ + properties: object; + + /** + * An array with all the layers configured to the MapData. + */ + layers: Phaser.Tilemaps.LayerData[] | Phaser.Tilemaps.ObjectLayer; + + /** + * An array of Tiled Image Layers. + */ + images: any[]; + + /** + * An object of Tiled Object Layers. + */ + objects: object; + + /** + * An object of collision data. Must be created as physics object or will return undefined. + */ + collision: object; + + /** + * An array of Tilesets. + */ + tilesets: Phaser.Tilemaps.Tileset[]; + + /** + * The collection of images the map uses(specified in Tiled) + */ + imageCollections: any[]; + + /** + * [description] + */ + tiles: any[]; + + } + + /** + * A class for representing a Tiled object layer in a map. This mirrors the structure of a Tiled + * object layer, except: + * - "x" & "y" properties are ignored since these cannot be changed in Tiled. + * - "offsetx" & "offsety" are applied to the individual object coordinates directly, so they + * are ignored as well. + * - "draworder" is ignored. + */ + class ObjectLayer { + /** + * + * @param config The data for the layer from the Tiled JSON object. + */ + constructor(config?: Phaser.Types.Tilemaps.ObjectLayerConfig); + + /** + * The name of the Object Layer. + */ + name: string; + + /** + * The opacity of the layer, between 0 and 1. + */ + opacity: number; + + /** + * The custom properties defined on the Object Layer, keyed by their name. + */ + properties: object; + + /** + * The type of each custom property defined on the Object Layer, keyed by its name. + */ + propertyTypes: object; + + /** + * The type of the layer, which should be `objectgroup`. + */ + type: string; + + /** + * Whether the layer is shown (`true`) or hidden (`false`). + */ + visible: boolean; + + /** + * 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`. + */ + objects: Phaser.Types.Tilemaps.TiledObject[]; + + } + + namespace Parsers { + namespace Impact { + /** + * [description] + * @param json [description] + * @param insertNull [description] + */ + function ParseTileLayers(json: object, insertNull: boolean): any[]; + + /** + * [description] + * @param json [description] + */ + function ParseTilesets(json: object): any[]; + + /** + * Parses a Weltmeister JSON object into a new MapData object. + * @param name The name of the tilemap, used to set the name on the MapData. + * @param json The Weltmeister JSON object. + * @param 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've 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. + */ + function ParseWeltmeister(name: string, json: object, insertNull: boolean): object; + + } + + /** + * Parses raw data of a given Tilemap format into a new MapData object. If no recognized data format + * is found, returns `null`. When loading from CSV or a 2D array, you should specify the tileWidth & + * tileHeight. When parsing from a map from Tiled, the tileWidth & tileHeight will be pulled from + * the map data. + * @param name The name of the tilemap, used to set the name on the MapData. + * @param mapFormat See ../Formats.js. + * @param data 2D array, CSV string or Tiled JSON object. + * @param tileWidth The width of a tile in pixels. Required for 2D array and CSV, but + * ignored for Tiled JSON. + * @param tileHeight The height of a tile in pixels. Required for 2D array and CSV, but + * ignored for Tiled JSON. + * @param 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've 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. + */ + function Parse(name: string, mapFormat: integer, data: integer[][] | string | object, tileWidth: integer, tileHeight: integer, insertNull: boolean): Phaser.Tilemaps.MapData; + + /** + * Parses a 2D array of tile indexes into a new MapData object with a single layer. + * @param name The name of the tilemap, used to set the name on the MapData. + * @param data 2D array, CSV string or Tiled JSON object. + * @param tileWidth The width of a tile in pixels. + * @param tileHeight The height of a tile in pixels. + * @param 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've 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. + */ + function Parse2DArray(name: string, data: integer[][], tileWidth: integer, tileHeight: integer, insertNull: boolean): Phaser.Tilemaps.MapData; + + /** + * Parses a CSV string of tile indexes into a new MapData object with a single layer. + * @param name The name of the tilemap, used to set the name on the MapData. + * @param data CSV string of tile indexes. + * @param tileWidth The width of a tile in pixels. + * @param tileHeight The height of a tile in pixels. + * @param 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've 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. + */ + function ParseCSV(name: string, data: string, tileWidth: integer, tileHeight: integer, insertNull: boolean): Phaser.Tilemaps.MapData; + + namespace Tiled { + /** + * Copy properties from tileset to tiles. + * @param mapData [description] + */ + function AssignTileProperties(mapData: Phaser.Tilemaps.MapData): void; + + /** + * Decode base-64 encoded data, for example as exported by Tiled. + * @param data Base-64 encoded data to decode. + */ + function Base64Decode(data: object): any[]; + + /** + * Master list of tiles -> x, y, index in tileset. + * @param mapData [description] + */ + function BuildTilesetIndex(mapData: Phaser.Tilemaps.MapData): any[]; + + /** + * Parse a Tiled group layer and create a state object for inheriting. + * @param json The Tiled JSON object. + * @param currentl The current group layer from the Tiled JSON file. + * @param parentstate The state of the parent group (if any). + */ + function CreateGroupLayer(json: object, currentl?: object, parentstate?: object): object; + + /** + * See Tiled documentation on tile flipping: + * http://docs.mapeditor.org/en/latest/reference/tmx-map-format/ + * @param gid [description] + */ + function ParseGID(gid: number): object; + + /** + * Parses a Tiled JSON object into an array of objects with details about the image layers. + * @param json The Tiled JSON object. + */ + function ParseImageLayers(json: object): any[]; + + /** + * Parses a Tiled JSON object into a new MapData object. + * @param name The name of the tilemap, used to set the name on the MapData. + * @param json The Tiled JSON object. + * @param 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've 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. + */ + function ParseJSONTiled(name: string, json: object, insertNull: boolean): Phaser.Tilemaps.MapData; + + /** + * Convert a Tiled object to an internal parsed object normalising and copying properties over, while applying optional x and y offsets. The parsed object will always have the properties `id`, `name`, `type`, `rotation`, `properties`, `visible`, `x`, `y`, `width` and `height`. Other properties will be added according to the object type (such as text, polyline, gid etc.) + * @param tiledObject Tiled object to convert to an internal parsed object normalising and copying properties over. + * @param offsetX Optional additional offset to apply to the object's x property. Defaults to 0. Default 0. + * @param offsetY Optional additional offset to apply to the object's y property. Defaults to 0. Default 0. + */ + function ParseObject(tiledObject: object, offsetX?: number, offsetY?: number): object; + + /** + * Parses a Tiled JSON object into an array of ObjectLayer objects. + * @param json The Tiled JSON object. + */ + function ParseObjectLayers(json: object): any[]; + + /** + * Parses all tilemap layers in a Tiled JSON object into new LayerData objects. + * @param json The Tiled JSON object. + * @param insertNull Controls how empty tiles, tiles with an index of -1, in the map + * data are handled (see {@link Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled}). + */ + function ParseTileLayers(json: object, insertNull: boolean): Phaser.Tilemaps.LayerData[]; + + /** + * Tilesets and Image Collections + * @param json [description] + */ + function ParseTilesets(json: object): object; + + } + + } + + /** + * Create a Tilemap from the given key or data. If neither is given, make a blank Tilemap. When + * loading from CSV or a 2D array, you should specify the tileWidth & tileHeight. When parsing from + * a map from Tiled, the tileWidth, tileHeight, width & height will be pulled from the map data. For + * an empty map, you should specify tileWidth, tileHeight, width & height. + * @param scene The Scene to which this Tilemap belongs. + * @param key The key in the Phaser cache that corresponds to the loaded tilemap data. + * @param tileWidth The width of a tile in pixels. Default 32. + * @param tileHeight The height of a tile in pixels. Default 32. + * @param width The width of the map in tiles. Default 10. + * @param height The height of the map in tiles. Default 10. + * @param data Instead of loading from the cache, you can also load directly from + * a 2D array of tile indexes. + * @param 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've 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. Default false. + */ + function ParseToTilemap(scene: Phaser.Scene, key?: string, tileWidth?: integer, tileHeight?: integer, width?: integer, height?: integer, data?: integer[][], insertNull?: boolean): Phaser.Tilemaps.Tilemap; + + /** + * A Static Tilemap Layer is a Game Object that renders LayerData from a Tilemap when used in combination + * with one, or more, Tilesets. + * + * A Static Tilemap Layer is optimized for rendering speed over flexibility. You cannot apply per-tile + * effects like tint or alpha, or change the tiles or tilesets the layer uses. + * + * Use a Static Tilemap Layer instead of a Dynamic Tilemap Layer when you don't need tile manipulation features. + */ + class StaticTilemapLayer extends Phaser.GameObjects.GameObject implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.BlendMode, Phaser.GameObjects.Components.ComputedSize, Phaser.GameObjects.Components.Depth, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.GetBounds, Phaser.GameObjects.Components.Origin, Phaser.GameObjects.Components.Pipeline, Phaser.GameObjects.Components.Transform, Phaser.GameObjects.Components.Visible, Phaser.GameObjects.Components.ScrollFactor { + /** + * + * @param scene The Scene to which this Game Object belongs. + * @param tilemap The Tilemap this layer is a part of. + * @param layerIndex The index of the LayerData associated with this layer. + * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param x The world x position where the top left of this layer will be placed. Default 0. + * @param y The world y position where the top left of this layer will be placed. Default 0. + */ + constructor(scene: Phaser.Scene, tilemap: Phaser.Tilemaps.Tilemap, layerIndex: integer, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number); + + /** + * Used internally by physics system to perform fast type checks. + */ + readonly isTilemap: boolean; + + /** + * The Tilemap that this layer is a part of. + */ + tilemap: Phaser.Tilemaps.Tilemap; + + /** + * The index of the LayerData associated with this layer. + */ + layerIndex: integer; + + /** + * The LayerData associated with this layer. LayerData can only be associated with one + * tilemap layer. + */ + layer: Phaser.Tilemaps.LayerData; + + /** + * The Tileset/s associated with this layer. + * + * As of Phaser 3.14 this property is now an array of Tileset objects, previously it was a single reference. + */ + tileset: Phaser.Tilemaps.Tileset[]; + + /** + * Used internally by the Canvas renderer. + * This holds the tiles that are visible within the camera in the last frame. + */ + culledTiles: any[]; + + /** + * Canvas only. + * + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this, and toggling this flag allows + * you to do so. Also see `setSkipCull` for a chainable method that does the same thing. + */ + skipCull: boolean; + + /** + * Canvas only. + * + * The total number of tiles drawn by the renderer in the last frame. + * + * This only works when rending with Canvas. + */ + readonly tilesDrawn: integer; + + /** + * Canvas only. + * + * The total number of tiles in this layer. Updated every frame. + */ + readonly tilesTotal: integer; + + /** + * Canvas only. + * + * The amount of extra tiles to add into the cull rectangle when calculating its horizontal size. + * + * See the method `setCullPadding` for more details. + */ + cullPaddingX: integer; + + /** + * Canvas only. + * + * The amount of extra tiles to add into the cull rectangle when calculating its vertical size. + * + * See the method `setCullPadding` for more details. + */ + cullPaddingY: integer; + + /** + * Canvas only. + * + * The callback that is invoked when the tiles are culled. + * + * By default it will call `TilemapComponents.CullTiles` but you can override this to call any function you like. + * + * It will be sent 3 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. + * + * See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system. + */ + cullCallback: Function; + + /** + * An array holding the mapping between the tile indexes and the tileset they belong to. + */ + gidMap: Phaser.Tilemaps.Tileset[]; + + /** + * Upload the tile data to a VBO. + * @param camera The camera to render to. + * @param tilesetIndex The tileset index. + */ + upload(camera: Phaser.Cameras.Scene2D.Camera, tilesetIndex: integer): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets the rendering (draw) order of the tiles in this layer. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * @param renderOrder The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + */ + setRenderOrder(renderOrder: integer | string): this; + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * @param tileX The x coordinate. + * @param tileY The y coordinate. + */ + calculateFacesAt(tileX: integer, tileY: integer): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + */ + calculateFacesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * @param indexes The tile index, or array of indexes, to create Sprites from. + * @param replacements The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param spriteConfig The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param scene The Scene to create the Sprites within. Default scene the map is within. + * @param camera The Camera to use when determining the world XY Default main camera. + */ + createFromTiles(indexes: integer | any[], replacements: integer | any[], spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.GameObjects.Sprite[]; + + /** + * Returns the tiles in the given layer that are within the cameras viewport. + * This is used internally. + * @param camera The Camera to run the cull check against. + */ + cull(camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; + + /** + * Canvas only. + * + * You can control if the Cameras should cull tiles before rendering them or not. + * By default the camera will try to cull the tiles in this layer, to avoid over-drawing to the renderer. + * + * However, there are some instances when you may wish to disable this. + * @param value Set to `true` to stop culling tiles. Set to `false` to enable culling again. Default true. + */ + setSkipCull(value?: boolean): this; + + /** + * Canvas only. + * + * When a Camera culls the tiles in this layer it does so using its view into the world, building up a + * rectangle inside which the tiles must exist or they will be culled. Sometimes you may need to expand the size + * of this 'cull rectangle', especially if you plan on rotating the Camera viewing the layer. Do so + * by providing the padding values. The values given are in tiles, not pixels. So if the tile width was 32px + * and you set `paddingX` to be 4, it would add 32px x 4 to the cull rectangle (adjusted for scale) + * @param paddingX The amount of extra horizontal tiles to add to the cull check padding. Default 1. + * @param paddingY The amount of extra vertical tiles to add to the cull check padding. Default 1. + */ + setCullPadding(paddingX?: integer, paddingY?: integer): this; + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * @param index The tile index value to search for. + * @param skip The number of times to skip a matching tile before returning. Default 0. + * @param reverse If true it will scan the layer in reverse, starting at the + * bottom-right. Otherwise it scans from the top-left. Default false. + */ + findByIndex(index: integer, skip?: integer, reverse?: boolean): Phaser.Tilemaps.Tile; + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * @param callback The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + findTile(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile; + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * @param callback The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param context The context under which the callback should be run. + * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + filterTiles(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * @param callback The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. + * @param context The context under which the callback should be run. + * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + forEachTile(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Gets a tile at the given tile coordinates from the given layer. + * @param tileX X position to get the tile from (given in tile units, not pixels). + * @param tileY Y position to get the tile from (given in tile units, not pixels). + * @param nonNull If true getTile won't return null for empty tiles, but a Tile + * object with an index of -1. Default false. + */ + getTileAt(tileX: integer, tileY: integer, nonNull?: boolean): Phaser.Tilemaps.Tile; + + /** + * Gets a tile at the given world coordinates from the given layer. + * @param worldX X position to get the tile from (given in pixels) + * @param worldY Y position to get the tile from (given in pixels) + * @param nonNull If true, function won't return null for empty tiles, but a Tile + * object with an index of -1. Default false. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + getTileAtWorldXY(worldX: number, worldY: number, nonNull?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile; + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + */ + getTilesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions): Phaser.Tilemaps.Tile[]; + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * @param worldX The leftmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param worldY The topmost tile index (in tile coordinates) to use as the origin of the area to filter. + * @param width How many tiles wide from the `tileX` index the area will be. + * @param height How many tiles high from the `tileY` index the area will be. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + */ + getTilesWithinWorldXY(worldX: number, worldY: number, width: number, height: number, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * @param shape A shape in world (pixel) coordinates + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + getTilesWithinShape(shape: Phaser.Geom.Circle | Phaser.Geom.Line | Phaser.Geom.Rectangle | Phaser.Geom.Triangle, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Tilemaps.Tile[]; + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * @param tileX X position to get the tile from in tile coordinates. + * @param tileY Y position to get the tile from in tile coordinates. + */ + hasTileAt(tileX: integer, tileY: integer): boolean; + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * @param worldX The X coordinate of the world position. + * @param worldY The Y coordinate of the world position. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + hasTileAtWorldXY(worldX: number, worldY: number, camera?: Phaser.Cameras.Scene2D.Camera): boolean; + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * @param graphics The target Graphics object to draw upon. + * @param styleConfig An object specifying the colors to use for the debug drawing. + */ + renderDebug(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * @param indexes Either a single tile index, or an array of tile indexes. + * @param collides If true it will enable collision. If false it will clear + * collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the + * update. Default true. + * @param updateLayer If true, updates the current tiles on the layer. Set to + * false if no tiles have been placed for significant performance boost. Default true. + */ + setCollision(indexes: integer | any[], collides?: boolean, recalculateFaces?: boolean, updateLayer?: boolean): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * @param start The first index of the tile to be set for collision. + * @param stop The last index of the tile to be set for collision. + * @param collides If true it will enable collision. If false it will clear + * collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the + * update. Default true. + */ + setCollisionBetween(start: integer, stop: integer, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * @param properties An object with tile properties and corresponding values that should + * be checked. + * @param collides If true it will enable collision. If false it will clear + * collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the + * update. Default true. + */ + setCollisionByProperty(properties: object, collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * @param indexes An array of the tile indexes to not be counted for collision. + * @param collides If true it will enable collision. If false it will clear + * collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the + * update. Default true. + */ + setCollisionByExclusion(indexes: integer[], collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * @param indexes Either a single tile index, or an array of tile indexes to have a + * collision callback set for. + * @param callback The callback that will be invoked when the tile is collided with. + * @param callbackContext The context under which the callback is called. + */ + setTileIndexCallback(indexes: integer | any[], callback: Function, callbackContext: object): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets collision on the tiles within a layer by checking each tiles collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tiles collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * @param collides If true it will enable collision. If false it will clear + * collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the + * update. Default true. + */ + setCollisionFromCollisionGroup(collides?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * @param tileX The leftmost tile index (in tile coordinates) to use as the origin of the area. + * @param tileY The topmost tile index (in tile coordinates) to use as the origin of the area. + * @param width How many tiles wide from the `tileX` index the area will be. + * @param height How many tiles tall from the `tileY` index the area will be. + * @param callback The callback that will be invoked when the tile is collided with. + * @param callbackContext The context under which the callback is called. + */ + setTileLocationCallback(tileX: integer, tileY: integer, width: integer, height: integer, callback: Function, callbackContext?: object): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * @param tileX The X coordinate, in tile coordinates. + * @param camera The Camera to use when calculating the world values from the tile index. Default main camera. + */ + tileToWorldX(tileX: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * @param tileY The Y coordinate, in tile coordinates. + * @param camera The Camera to use when calculating the world values from the tile index. Default main camera. + */ + tileToWorldY(tileY: integer, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * @param tileX The X coordinate, in tile coordinates. + * @param tileY The Y coordinate, in tile coordinates. + * @param point A Vector2 to store the coordinates in. If not given, a new Vector2 is created. + * @param camera The Camera to use when calculating the world values from the tile index. Default main camera. + */ + tileToWorldXY(tileX: integer, tileY: integer, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * @param worldX The X coordinate, in world pixels. + * @param snapToFloor Whether or not to round the tile coordinate down to the + * nearest integer. Default true. + * @param camera The Camera to use when calculating the tile index from the world values.] Default main camera. + */ + worldToTileX(worldX: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * @param worldY The Y coordinate, in world pixels. + * @param snapToFloor Whether or not to round the tile coordinate down to the + * nearest integer. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + worldToTileY(worldY: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * @param worldX The X coordinate, in world pixels. + * @param worldY The Y coordinate, in world pixels. + * @param snapToFloor Whether or not to round the tile coordinate down to the + * nearest integer. Default true. + * @param point A Vector2 to store the coordinates in. If not given, a new Vector2 is created. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + */ + worldToTileXY(worldX: number, worldY: number, snapToFloor?: boolean, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera): Phaser.Math.Vector2; + + /** + * Destroys this StaticTilemapLayer and removes its link to the associated LayerData. + * @param removeFromTilemap Remove this layer from the parent Tilemap? Default true. + */ + destroy(removeFromTilemap?: boolean): void; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency of which blend modes + * are used. + */ + blendMode: Phaser.BlendModes | string; + + /** + * Sets the Blend Mode being used by this Game Object. + * + * This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay) + * + * Under WebGL only the following Blend Modes are available: + * + * * ADD + * * MULTIPLY + * * SCREEN + * * ERASE (only works when rendering to a framebuffer, like a Render Texture) + * + * Canvas has more available depending on browser support. + * + * You can also create your own custom Blend Modes in WebGL. + * + * Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending + * on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these + * reasons try to be careful about the construction of your Scene and the frequency in which blend modes + * are used. + * @param value The BlendMode value. Either a string or a CONST. + */ + setBlendMode(value: string | Phaser.BlendModes): this; + + /** + * The native (un-scaled) width of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayWidth` property. + */ + width: number; + + /** + * The native (un-scaled) height of this Game Object. + * + * Changing this value will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or use + * the `displayHeight` property. + */ + height: number; + + /** + * The displayed width of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayWidth: number; + + /** + * The displayed height of this Game Object. + * + * This value takes into account the scale factor. + * + * Setting this value will adjust the Game Object's scale property. + */ + displayHeight: number; + + /** + * Sets the internal size of this Game Object, as used for frame or physics body creation. + * + * This will not change the size that the Game Object is rendered in-game. + * For that you need to either set the scale of the Game Object (`setScale`) or call the + * `setDisplaySize` method, which is the same thing as changing the scale but allows you + * to do so by giving pixel values. + * + * If you have enabled this Game Object for input, changing the size will _not_ change the + * size of the hit area. To do this you should adjust the `input.hitArea` object directly. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setSize(width: number, height: number): this; + + /** + * Sets the display size of this Game Object. + * + * Calling this will adjust the scale. + * @param width The width of this Game Object. + * @param height The height of this Game Object. + */ + setDisplaySize(width: number, height: number): this; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + */ + depth: number; + + /** + * The depth of this Game Object within the Scene. + * + * The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order + * of Game Objects, without actually moving their position in the display list. + * + * The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth + * value will always render in front of one with a lower value. + * + * Setting the depth will queue a depth sort event within the Scene. + * @param value The depth of this Game Object. + */ + setDepth(value: integer): this; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * Gets the center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + */ + getCenter(output?: O): O; + + /** + * Gets the top-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the top-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getTopRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the left-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getLeftCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the right-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getRightCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-left corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomLeft(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-center coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomCenter(output?: O, includeParent?: boolean): O; + + /** + * Gets the bottom-right corner coordinate of this Game Object, regardless of origin. + * The returned point is calculated in local space and does not factor in any parent containers + * @param output An object to store the values in. If not provided a new Vector2 will be created. + * @param includeParent If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector? Default false. + */ + getBottomRight(output?: O, includeParent?: boolean): O; + + /** + * Gets the bounds of this Game Object, regardless of origin. + * The values are stored and returned in a Rectangle, or Rectangle-like, object. + * @param output An object to store the values in. If not provided a new Rectangle will be created. + */ + getBounds(output?: O): O; + + /** + * 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. + */ + originX: number; + + /** + * 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. + */ + originY: number; + + /** + * The horizontal display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginX: number; + + /** + * The vertical display origin of this Game Object. + * The origin is a normalized value between 0 and 1. + * The displayOrigin is a pixel value, based on the size of the Game Object combined with the origin. + */ + displayOriginY: number; + + /** + * Sets the origin of this Game Object. + * + * The values are given in the range 0 to 1. + * @param x The horizontal origin value. Default 0.5. + * @param y The vertical origin value. If not defined it will be set to the value of `x`. Default x. + */ + setOrigin(x?: number, y?: number): this; + + /** + * Sets the origin of this Game Object based on the Pivot values in its Frame. + */ + setOriginFromFrame(): this; + + /** + * Sets the display origin of this Game Object. + * The difference between this and setting the origin is that you can use pixel values for setting the display origin. + * @param x The horizontal display origin value. Default 0. + * @param y The vertical display origin value. If not defined it will be set to the value of `x`. Default x. + */ + setDisplayOrigin(x?: number, y?: number): this; + + /** + * Updates the Display Origin cached values internally stored on this Game Object. + * You don't usually call this directly, but it is exposed for edge-cases where you may. + */ + updateDisplayOrigin(): this; + + /** + * The initial WebGL pipeline of this Game Object. + */ + defaultPipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * The current WebGL pipeline of this Game Object. + */ + pipeline: Phaser.Renderer.WebGL.WebGLPipeline; + + /** + * Sets the initial WebGL Pipeline of this Game Object. + * This should only be called during the instantiation of the Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline. Default TextureTintPipeline. + */ + initPipeline(pipelineName?: string): boolean; + + /** + * Sets the active WebGL Pipeline of this Game Object. + * @param pipelineName The name of the pipeline to set on this Game Object. + */ + setPipeline(pipelineName: string): this; + + /** + * Resets the WebGL Pipeline of this Game Object back to the default it was created with. + */ + resetPipeline(): boolean; + + /** + * Gets the name of the WebGL Pipeline this Game Object is currently using. + */ + getPipelineName(): string; + + /** + * The x position of this Game Object. + */ + x: number; + + /** + * The y position of this Game Object. + */ + y: number; + + /** + * The z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#depth} instead. + */ + z: number; + + /** + * The w position of this Game Object. + */ + w: number; + + /** + * This is a special setter that allows you to set both the horizontal and vertical scale of this Game Object + * to the same value, at the same time. When reading this value the result returned is `(scaleX + scaleY) / 2`. + * + * Use of this property implies you wish the horizontal and vertical scales to be equal to each other. If this + * isn't the case, use the `scaleX` or `scaleY` properties instead. + */ + scale: number; + + /** + * The horizontal scale of this Game Object. + */ + scaleX: number; + + /** + * The vertical scale of this Game Object. + */ + scaleY: number; + + /** + * The angle of this Game Object as expressed in degrees. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in radians, see the `rotation` property instead. + */ + angle: integer; + + /** + * The angle of this Game Object in radians. + * + * Phaser uses a right-hand clockwise rotation system, where 0 is right, 90 is down, 180/-180 is left + * and -90 is up. + * + * If you prefer to work in degrees, see the `angle` property instead. + */ + rotation: number; + + /** + * Sets the position of this Game Object. + * @param x The x position of this Game Object. Default 0. + * @param y The y position of this Game Object. If not set it will use the `x` value. Default x. + * @param z The z position of this Game Object. Default 0. + * @param w The w position of this Game Object. Default 0. + */ + setPosition(x?: number, y?: number, z?: number, w?: number): this; + + /** + * Sets the position of this Game Object to be a random position within the confines of + * the given area. + * + * If no area is specified a random position between 0 x 0 and the game width x height is used instead. + * + * The position does not factor in the size of this Game Object, meaning that only the origin is + * guaranteed to be within the area. + * @param x The x position of the top-left of the random area. Default 0. + * @param y The y position of the top-left of the random area. Default 0. + * @param width The width of the random area. + * @param height The height of the random area. + */ + setRandomPosition(x?: number, y?: number, width?: number, height?: number): this; + + /** + * Sets the rotation of this Game Object. + * @param radians The rotation of this Game Object, in radians. Default 0. + */ + setRotation(radians?: number): this; + + /** + * Sets the angle of this Game Object. + * @param degrees The rotation of this Game Object, in degrees. Default 0. + */ + setAngle(degrees?: number): this; + + /** + * Sets the scale of this Game Object. + * @param x The horizontal scale of this Game Object. + * @param y The vertical scale of this Game Object. If not set it will use the `x` value. Default x. + */ + setScale(x: number, y?: number): this; + + /** + * Sets the x position of this Game Object. + * @param value The x position of this Game Object. Default 0. + */ + setX(value?: number): this; + + /** + * Sets the y position of this Game Object. + * @param value The y position of this Game Object. Default 0. + */ + setY(value?: number): this; + + /** + * Sets the z position of this Game Object. + * + * Note: The z position does not control the rendering order of 2D Game Objects. Use + * {@link Phaser.GameObjects.Components.Depth#setDepth} instead. + * @param value The z position of this Game Object. Default 0. + */ + setZ(value?: number): this; + + /** + * Sets the w position of this Game Object. + * @param value The w position of this Game Object. Default 0. + */ + setW(value?: number): this; + + /** + * Gets the local transform matrix for this Game Object. + * @param tempMatrix The matrix to populate with the values from this Game Object. + */ + getLocalTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the world transform matrix for this Game Object, factoring in any parent Containers. + * @param tempMatrix The matrix to populate with the values from this Game Object. + * @param parentMatrix A temporary matrix to hold parent values during the calculations. + */ + getWorldTransformMatrix(tempMatrix?: Phaser.GameObjects.Components.TransformMatrix, parentMatrix?: Phaser.GameObjects.Components.TransformMatrix): Phaser.GameObjects.Components.TransformMatrix; + + /** + * Gets the sum total rotation of all of this Game Objects parent Containers. + * + * The returned value is in radians and will be zero if this Game Object has no parent container. + */ + getParentRotation(): number; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + /** + * 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 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. + */ + scrollFactorX: number; + + /** + * 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 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. + */ + scrollFactorY: number; + + /** + * Sets the 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 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. + * @param x The horizontal scroll factor of this Game Object. + * @param y The vertical scroll factor of this Game Object. If not set it will use the `x` value. Default x. + */ + setScrollFactor(x: number, y?: number): this; + + } + + /** + * A Tile is a representation of a single tile within the Tilemap. This is a lightweight data + * representation, so its position information is stored without factoring in scroll, layer + * scale or layer position. + */ + class Tile implements Phaser.GameObjects.Components.Alpha, Phaser.GameObjects.Components.Flip, Phaser.GameObjects.Components.Visible { + /** + * + * @param layer The LayerData object in the Tilemap that this tile belongs to. + * @param index The unique index of this tile within the map. + * @param x The x coordinate of this tile in tile coordinates. + * @param y The y coordinate of this tile in tile coordinates. + * @param width Width of the tile in pixels. + * @param height Height of the tile in pixels. + * @param baseWidth The base width a tile in the map (in pixels). Tiled maps support + * multiple tileset sizes within one map, but they are still placed at intervals of the base + * tile width. + * @param baseHeight The base height of the tile in pixels (in pixels). Tiled maps + * support multiple tileset sizes within one map, but they are still placed at intervals of the + * base tile height. + */ + constructor(layer: Phaser.Tilemaps.LayerData, index: integer, x: integer, y: integer, width: integer, height: integer, baseWidth: integer, baseHeight: integer); + + /** + * The LayerData in the Tilemap data that this tile belongs to. + */ + layer: Phaser.Tilemaps.LayerData; + + /** + * The index of this tile within the map data corresponding to the tileset, or -1 if this + * represents a blank tile. + */ + index: integer; + + /** + * The x map coordinate of this tile in tile units. + */ + x: integer; + + /** + * The y map coordinate of this tile in tile units. + */ + y: integer; + + /** + * The width of the tile in pixels. + */ + width: integer; + + /** + * The height of the tile in pixels. + */ + height: integer; + + /** + * The map's base width of a tile in pixels. Tiled maps support multiple tileset sizes + * within one map, but they are still placed at intervals of the base tile size. + */ + baseWidth: integer; + + /** + * The map's base height of a tile in pixels. Tiled maps support multiple tileset sizes + * within one map, but they are still placed at intervals of the base tile size. + */ + baseHeight: integer; + + /** + * The x coordinate of the top left of this tile in pixels. This is relative to the top left + * of the layer this tile is being rendered within. This property does NOT factor in camera + * scroll, layer scale or layer position. + */ + pixelX: number; + + /** + * The y coordinate of the top left of this tile in pixels. This is relative to the top left + * of the layer this tile is being rendered within. This property does NOT factor in camera + * scroll, layer scale or layer position. + */ + pixelY: number; + + /** + * Tile specific properties. These usually come from Tiled. + */ + properties: any; + + /** + * The rotation angle of this tile. + */ + rotation: number; + + /** + * Whether the tile should collide with any object on the left side. + */ + collideLeft: boolean; + + /** + * Whether the tile should collide with any object on the right side. + */ + collideRight: boolean; + + /** + * Whether the tile should collide with any object on the top side. + */ + collideUp: boolean; + + /** + * Whether the tile should collide with any object on the bottom side. + */ + collideDown: boolean; + + /** + * Whether the tile's left edge is interesting for collisions. + */ + faceLeft: boolean; + + /** + * Whether the tile's right edge is interesting for collisions. + */ + faceRight: boolean; + + /** + * Whether the tile's top edge is interesting for collisions. + */ + faceTop: boolean; + + /** + * Whether the tile's bottom edge is interesting for collisions. + */ + faceBottom: boolean; + + /** + * Tile collision callback. + */ + collisionCallback: Function; + + /** + * The context in which the collision callback will be called. + */ + collisionCallbackContext: object; + + /** + * The tint to apply to this tile. Note: tint is currently a single color value instead of + * the 4 corner tint component on other GameObjects. + */ + tint: number; + + /** + * An empty object where physics-engine specific information (e.g. bodies) may be stored. + */ + physics: object; + + /** + * Check if the given x and y world coordinates are within this Tile. This does not factor in + * camera scroll, layer scale or layer position. + * @param x The x coordinate to test. + * @param y The y coordinate to test. + */ + containsPoint(x: number, y: number): boolean; + + /** + * Copies the tile data & properties from the given tile to this tile. This copies everything + * except for position and interesting faces. + * @param tile The tile to copy from. + */ + copy(tile: Phaser.Tilemaps.Tile): Phaser.Tilemaps.Tile; + + /** + * The collision group for this Tile, defined within the Tileset. This returns a reference to + * the collision group stored within the Tileset, so any modification of the returned object + * will impact all tiles that have the same index as this tile. + */ + getCollisionGroup(): object; + + /** + * The tile data for this Tile, defined within the Tileset. This typically contains Tiled + * collision data, tile animations and terrain information. This returns a reference to the tile + * data stored within the Tileset, so any modification of the returned object will impact all + * tiles that have the same index as this tile. + */ + getTileData(): object; + + /** + * Gets the world X position of the left side of the tile, factoring in the layers position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + */ + getLeft(camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Gets the world X position of the right side of the tile, factoring in the layer's position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + */ + getRight(camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Gets the world Y position of the top side of the tile, factoring in the layer's position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + */ + getTop(camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Gets the world Y position of the bottom side of the tile, factoring in the layer's position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + */ + getBottom(camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Gets the world rectangle bounding box for the tile, factoring in the layers position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + * @param output [description] + */ + getBounds(camera?: Phaser.Cameras.Scene2D.Camera, output?: object): Phaser.Geom.Rectangle | object; + + /** + * Gets the world X position of the center of the tile, factoring in the layer's position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + */ + getCenterX(camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Gets the world Y position of the center of the tile, factoring in the layer's position, + * scale and scroll. + * @param camera The Camera to use to perform the check. + */ + getCenterY(camera?: Phaser.Cameras.Scene2D.Camera): number; + + /** + * Clean up memory. + */ + destroy(): void; + + /** + * Check for intersection with this tile. This does not factor in camera scroll, layer scale or + * layer position. + * @param x The x axis in pixels. + * @param y The y axis in pixels. + * @param right The right point. + * @param bottom The bottom point. + */ + intersects(x: number, y: number, right: number, bottom: number): boolean; + + /** + * Checks if the tile is interesting. + * @param collides If true, will consider the tile interesting if it collides on any side. + * @param faces If true, will consider the tile interesting if it has an interesting face. + */ + isInteresting(collides: boolean, faces: boolean): boolean; + + /** + * Reset collision status flags. + * @param recalculateFaces Whether or not to recalculate interesting faces for this tile and its neighbors. Default true. + */ + resetCollision(recalculateFaces?: boolean): Phaser.Tilemaps.Tile; + + /** + * Reset faces. + */ + resetFaces(): Phaser.Tilemaps.Tile; + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * @param left Indicating collide with any object on the left. + * @param right Indicating collide with any object on the right. + * @param up Indicating collide with any object on the top. + * @param down Indicating collide with any object on the bottom. + * @param recalculateFaces Whether or not to recalculate interesting faces + * for this tile and its neighbors. Default true. + */ + setCollision(left: boolean, right?: boolean, up?: boolean, down?: boolean, recalculateFaces?: boolean): Phaser.Tilemaps.Tile; + + /** + * Set a callback to be called when this tile is hit by an object. The callback must true for + * collision processing to take place. + * @param callback Callback function. + * @param context Callback will be called within this context. + */ + setCollisionCallback(callback: Function, context: object): Phaser.Tilemaps.Tile; + + /** + * Sets the size of the tile and updates its pixelX and pixelY. + * @param tileWidth The width of the tile in pixels. + * @param tileHeight The height of the tile in pixels. + * @param baseWidth The base width a tile in the map (in pixels). + * @param baseHeight The base height of the tile in pixels (in pixels). + */ + setSize(tileWidth: integer, tileHeight: integer, baseWidth: integer, baseHeight: integer): Phaser.Tilemaps.Tile; + + /** + * Used internally. Updates the tile's world XY position based on the current tile size. + */ + updatePixelXY(): Phaser.Tilemaps.Tile; + + /** + * True if this tile can collide on any of its faces or has a collision callback set. + */ + readonly canCollide: boolean; + + /** + * True if this tile can collide on any of its faces. + */ + readonly collides: boolean; + + /** + * True if this tile has any interesting faces. + */ + readonly hasInterestingFace: boolean; + + /** + * The tileset that contains this Tile. This is null if accessed from a LayerData instance + * before the tile is placed in a StaticTilemapLayer or DynamicTilemapLayer, or if the tile has + * an index that doesn't correspond to any of the map's tilesets. + */ + readonly tileset: Phaser.Tilemaps.Tileset; + + /** + * The tilemap layer that contains this Tile. This will only return null if accessed from a + * LayerData instance before the tile is placed within a StaticTilemapLayer or + * DynamicTilemapLayer. + */ + readonly tilemapLayer: Phaser.Tilemaps.StaticTilemapLayer | Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * The tilemap that contains this Tile. This will only return null if accessed from a LayerData + * instance before the tile is placed within a StaticTilemapLayer or DynamicTilemapLayer. + */ + readonly tilemap: Phaser.Tilemaps.Tilemap; + + /** + * Clears all alpha values associated with this Game Object. + * + * Immediately sets the alpha levels back to 1 (fully opaque). + */ + clearAlpha(): this; + + /** + * Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders. + * Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque. + * + * If your game is running under WebGL you can optionally specify four different alpha values, each of which + * correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used. + * @param topLeft The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object. Default 1. + * @param topRight The alpha value used for the top-right of the Game Object. WebGL only. + * @param bottomLeft The alpha value used for the bottom-left of the Game Object. WebGL only. + * @param bottomRight The alpha value used for the bottom-right of the Game Object. WebGL only. + */ + setAlpha(topLeft?: number, topRight?: number, bottomLeft?: number, bottomRight?: number): this; + + /** + * The alpha value of the Game Object. + * + * This is a global value, impacting the entire Game Object, not just a region of it. + */ + alpha: number; + + /** + * The alpha value starting from the top-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopLeft: number; + + /** + * The alpha value starting from the top-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaTopRight: number; + + /** + * The alpha value starting from the bottom-left of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomLeft: number; + + /** + * The alpha value starting from the bottom-right of the Game Object. + * This value is interpolated from the corner to the center of the Game Object. + */ + alphaBottomRight: number; + + /** + * The horizontally flipped state of the Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipX: boolean; + + /** + * The vertically flipped state of the Game Object. + * + * A Game Object that is flipped vertically will render inversed on the vertical axis (i.e. upside down) + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + flipY: boolean; + + /** + * Toggles the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + */ + toggleFlipX(): this; + + /** + * Toggles the vertical flipped state of this Game Object. + */ + toggleFlipY(): this; + + /** + * Sets the horizontal flipped state of this Game Object. + * + * A Game Object that is flipped horizontally will render inversed on the horizontal axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipX(value: boolean): this; + + /** + * Sets the vertical flipped state of this Game Object. + * @param value The flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlipY(value: boolean): this; + + /** + * Sets the horizontal and vertical flipped state of this Game Object. + * + * A Game Object that is flipped will render inversed on the flipped axis. + * Flipping always takes place from the middle of the texture and does not impact the scale value. + * If this Game Object has a physics body, it will not change the body. This is a rendering toggle only. + * @param x The horizontal flipped state. `false` for no flip, or `true` to be flipped. + * @param y The horizontal flipped state. `false` for no flip, or `true` to be flipped. + */ + setFlip(x: boolean, y: boolean): this; + + /** + * Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state. + */ + resetFlip(): this; + + /** + * The visible state of the Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + */ + visible: boolean; + + /** + * Sets the visibility of this Game Object. + * + * An invisible Game Object will skip rendering, but will still process update logic. + * @param value The visible state of the Game Object. + */ + setVisible(value: boolean): this; + + } + + /** + * 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 (StaticTilemapLayer or DynamicTilemapLayer), which are the display + * objects that actually render tiles. + * + * The Tilemap data 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 + * + * A Tilemap has handy methods for getting & manipulating the tiles within a layer. You can only + * use the methods that change tiles (e.g. removeTileAt) on a DynamicTilemapLayer. + * + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a + * StaticTilemapLayer or DynamicTilemapLayer may have its own unique tile size that overrides + * it. + * + * As of Phaser 3.21.0, if your tilemap includes layer groups (a feature of Tiled 1.2.0+) these + * will be traversed and the following properties will affect 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'. + */ + class Tilemap { + /** + * + * @param scene The Scene to which this Tilemap belongs. + * @param mapData A MapData instance containing Tilemap data. + */ + constructor(scene: Phaser.Scene, mapData: Phaser.Tilemaps.MapData); + + scene: Phaser.Scene; + + /** + * The base width of a tile in pixels. Note that individual layers may have a different tile + * width. + */ + tileWidth: integer; + + /** + * The base height of a tile in pixels. Note that individual layers may have a different + * tile height. + */ + tileHeight: integer; + + /** + * The width of the map (in tiles). + */ + width: number; + + /** + * The height of the map (in tiles). + */ + height: number; + + /** + * The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + orientation: string; + + /** + * The render (draw) order of the map data (as specified in Tiled), usually 'right-down'. + * + * The draw orders are: + * + * right-down + * left-down + * right-up + * left-up + * + * This can be changed via the `setRenderOrder` method. + */ + renderOrder: string; + + /** + * The format of the map data. + */ + format: number; + + /** + * The version of the map data (as specified in Tiled, usually 1). + */ + version: number; + + /** + * Map specific properties as specified in Tiled. + */ + properties: object; + + /** + * The width of the map in pixels based on width * tileWidth. + */ + widthInPixels: number; + + /** + * The height of the map in pixels based on height * tileHeight. + */ + heightInPixels: number; + + imageCollections: Phaser.Tilemaps.ImageCollection[]; + + /** + * An array of Tiled Image Layers. + */ + images: any[]; + + /** + * An array of Tilemap layer data. + */ + layers: Phaser.Tilemaps.LayerData[]; + + /** + * An array of Tilesets used in the map. + */ + tilesets: Phaser.Tilemaps.Tileset[]; + + /** + * An array of ObjectLayer instances parsed from Tiled object layers. + */ + objects: Phaser.Tilemaps.ObjectLayer[]; + + /** + * The index of the currently selected LayerData object. + */ + currentLayerIndex: integer; + + /** + * Sets the rendering (draw) order of the tiles in this map. + * + * The default is 'right-down', meaning it will order the tiles starting from the top-left, + * drawing to the right and then moving down to the next row. + * + * The draw orders are: + * + * 0 = right-down + * 1 = left-down + * 2 = right-up + * 3 = left-up + * + * Setting the render order does not change the tiles or how they are stored in the layer, + * it purely impacts the order in which they are rendered. + * + * You can provide either an integer (0 to 3), or the string version of the order. + * + * Calling this method _after_ creating Static or Dynamic Tilemap Layers will **not** automatically + * update them to use the new render order. If you call this method after creating layers, use their + * own `setRenderOrder` methods to change them as needed. + * @param renderOrder The render (draw) order value. Either an integer between 0 and 3, or a string: 'right-down', 'left-down', 'right-up' or 'left-up'. + */ + setRenderOrder(renderOrder: integer | string): this; + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled + * editor. + * @param tilesetName The name of the tileset as specified in the map data. + * @param key The key of the Phaser.Cache image used for this tileset. If + * `undefined` or `null` it will look for an image with a key matching the tilesetName parameter. + * @param tileWidth The width of the tile (in pixels) in the Tileset Image. If not + * given it will default to the map's tileWidth value, or the tileWidth specified in the Tiled + * JSON file. + * @param tileHeight The height of the tiles (in pixels) in the Tileset Image. If + * not given it will default to the map's tileHeight value, or the tileHeight specified in the + * Tiled JSON file. + * @param tileMargin The margin around the tiles in the sheet (in pixels). If not + * specified, it will default to 0 or the value specified in the Tiled JSON file. + * @param tileSpacing The spacing between each the tile in the sheet (in pixels). + * If not specified, it will default to 0 or the value specified in the Tiled JSON file. + * @param gid If adding multiple tilesets to a blank map, specify the starting + * GID this set will use here. Default 0. + */ + addTilesetImage(tilesetName: string, key?: string, tileWidth?: integer, tileHeight?: integer, tileMargin?: integer, tileSpacing?: integer, gid?: integer): Phaser.Tilemaps.Tileset; + + /** + * Turns the DynamicTilemapLayer associated with the given layer into a StaticTilemapLayer. If + * no layer specified, the map's current layer is used. This is useful if you want to manipulate + * a map at the start of a scene, but then make it non-manipulable and optimize it for speed. + * Note: the DynamicTilemapLayer passed in is destroyed, so make sure to store the value + * returned from this method if you want to manipulate the new StaticTilemapLayer. + * @param layer The name of the layer from Tiled, the + * index of the layer in the map, or a DynamicTilemapLayer. + */ + convertLayerToStatic(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Copies the tiles in the source rectangular area to a new destination (all specified in tile + * coordinates) within the layer. This copies all tile properties & recalculates collision + * information in the destination region. + * + * If no layer specified, the map's current layer is used. This cannot be applied to StaticTilemapLayers. + * @param srcTileX The x coordinate of the area to copy from, in tiles, not pixels. + * @param srcTileY The y coordinate of the area to copy from, in tiles, not pixels. + * @param width The width of the area to copy, in tiles, not pixels. + * @param height The height of the area to copy, in tiles, not pixels. + * @param destTileX The x coordinate of the area to copy to, in tiles, not pixels. + * @param destTileY The y coordinate of the area to copy to, in tiles, not pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + copy(srcTileX: integer, srcTileY: integer, width: integer, height: integer, destTileX: integer, destTileY: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Creates a new and empty DynamicTilemapLayer. The currently selected layer in the map is set to this new layer. + * @param name The name of this layer. Must be unique within the map. + * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param x The world x position where the top left of this layer will be placed. Default 0. + * @param y The world y position where the top left of this layer will be placed. Default 0. + * @param width The width of the layer in tiles. If not specified, it will default to the map's width. + * @param height The height of the layer in tiles. If not specified, it will default to the map's height. + * @param tileWidth The width of the tiles the layer uses for calculations. If not specified, it will default to the map's tileWidth. + * @param tileHeight The height of the tiles the layer uses for calculations. If not specified, it will default to the map's tileHeight. + */ + createBlankDynamicLayer(name: string, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number, width?: integer, height?: integer, tileWidth?: integer, tileHeight?: integer): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Creates a new DynamicTilemapLayer that renders the LayerData associated with the given + * `layerID`. The currently selected layer in the map is set to this new layer. + * + * The `layerID` is important. If you've created your map in Tiled then you can get this by + * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and + * look at the layers[].name value. Either way it must match. + * + * Unlike a static layer, a dynamic layer can be modified. See DynamicTilemapLayer for more + * information. + * @param layerID The layer array index value, or if a string is given, the layer name from Tiled. + * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param x The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. + * @param y The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. + */ + createDynamicLayer(layerID: integer | string, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number): Phaser.Tilemaps.DynamicTilemapLayer; + + /** + * Creates a Sprite for every object matching the given gid in the map data. All properties from + * the map data objectgroup are copied into the `spriteConfig`, so you can use this as an easy + * way to configure Sprite properties from within the map editor. For example giving an object a + * property of alpha: 0.5 in the map editor will duplicate that when the Sprite is created. + * + * Custom object properties not sharing names with the Sprite's own properties are copied to the + * Sprite's {@link Phaser.GameObjects.Sprite#data data store}. + * @param name The name of the object layer (from Tiled) to create Sprites from. + * @param id Either the id (object), gid (tile object) or name (object or + * tile object) from Tiled. Ids are unique in Tiled, but a gid is shared by all tile objects + * with the same graphic. The same name can be used on multiple objects. + * @param spriteConfig The config object to pass into the Sprite creator (i.e. + * scene.make.sprite). + * @param scene The Scene to create the Sprites within. Default the scene the map is within. + */ + createFromObjects(name: string, id: integer | string, spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene): Phaser.GameObjects.Sprite[]; + + /** + * Creates a Sprite for every object matching the given tile indexes in the layer. You can + * optionally specify if each tile will be replaced with a new tile after the Sprite has been + * created. This is useful if you want to lay down special tiles in a level that are converted to + * Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * @param indexes The tile index, or array of indexes, to create Sprites from. + * @param replacements The tile index, or array of indexes, to change a converted + * tile to. Set to `null` to leave the tiles unchanged. If an array is given, it is assumed to be a + * one-to-one mapping with the indexes array. + * @param spriteConfig The config object to pass into the Sprite creator (i.e. scene.make.sprite). + * @param scene The Scene to create the Sprites within. Default scene the map is within. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + createFromTiles(indexes: integer | any[], replacements: integer | any[], spriteConfig: Phaser.Types.GameObjects.Sprite.SpriteConfig, scene?: Phaser.Scene, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.GameObjects.Sprite[]; + + /** + * Creates a new StaticTilemapLayer that renders the LayerData associated with the given + * `layerID`. The currently selected layer in the map is set to this new layer. + * + * The `layerID` is important. If you've created your map in Tiled then you can get this by + * looking in Tiled and looking at the layer name. Or you can open the JSON file it exports and + * look at the layers[].name value. Either way it must match. + * + * It's important to remember that a static layer cannot be modified. See StaticTilemapLayer for + * more information. + * @param layerID The layer array index value, or if a string is given, the layer name from Tiled. + * @param tileset The tileset, or an array of tilesets, used to render this layer. Can be a string or a Tileset object. + * @param x The x position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. + * @param y The y position to place the layer in the world. If not specified, it will default to the layer offset from Tiled or 0. Default 0. + */ + createStaticLayer(layerID: integer | string, tileset: string | string[] | Phaser.Tilemaps.Tileset | Phaser.Tilemaps.Tileset[], x?: number, y?: number): Phaser.Tilemaps.StaticTilemapLayer; + + /** + * Removes all layer data from this Tilemap and nulls the scene reference. This will destroy any + * StaticTilemapLayers or DynamicTilemapLayers that have been linked to LayerData. + */ + destroy(): void; + + /** + * Sets the tiles in the given rectangular area (in tile coordinates) of the layer with the + * specified index. Tiles will be set to collide if the given index is a colliding index. + * Collision information in the region will be recalculated. + * + * If no layer specified, the map's current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param index The tile index to fill the area with. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + fill(index: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * For each object in the given object layer, run the given filter callback function. Any + * objects that pass the filter test (i.e. where the callback returns true) will returned as a + * new array. Similar to Array.prototype.Filter in vanilla JS. + * @param objectLayer The name of an object layer (from Tiled) or an ObjectLayer instance. + * @param callback The callback. Each object in the given area will be passed to this callback as the first and only parameter. + * @param context The context under which the callback should be run. + */ + filterObjects(objectLayer: Phaser.Tilemaps.ObjectLayer | string, callback: TilemapFilterCallback, context?: object): Phaser.GameObjects.GameObject[]; + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * filter callback function. Any tiles that pass the filter test (i.e. where the callback returns + * true) will returned as a new array. Similar to Array.prototype.Filter in vanilla JS. + * If no layer specified, the map's current layer is used. + * @param callback The callback. Each tile in the given area will be passed to this + * callback as the first and only parameter. The callback should return true for tiles that pass the + * filter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to filter. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param layer The tile layer to use. If not given the current layer is used. + */ + filterTiles(callback: Function, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Tile + * object. If no match is found, it returns null. The search starts from the top-left tile and + * continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to + * the top-left. + * If no layer specified, the map's current layer is used. + * @param index The tile index value to search for. + * @param skip The number of times to skip a matching tile before returning. Default 0. + * @param reverse If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. Default false. + * @param layer The tile layer to use. If not given the current layer is used. + */ + findByIndex(index: integer, skip?: integer, reverse?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Find the first object in the given object layer that satisfies the provided testing function. + * I.e. finds the first object for which `callback` returns true. Similar to + * Array.prototype.find in vanilla JS. + * @param objectLayer The name of an object layer (from Tiled) or an ObjectLayer instance. + * @param callback The callback. Each object in the given area will be passed to this callback as the first and only parameter. + * @param context The context under which the callback should be run. + */ + findObject(objectLayer: Phaser.Tilemaps.ObjectLayer | string, callback: TilemapFindCallback, context?: object): Phaser.GameObjects.GameObject; + + /** + * Find the first tile in the given rectangular area (in tile coordinates) of the layer that + * satisfies the provided testing function. I.e. finds the first tile for which `callback` returns + * true. Similar to Array.prototype.find in vanilla JS. + * If no layer specified, the maps current layer is used. + * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param layer The Tile layer to run the search on. If not provided will use the current layer. + */ + findTile(callback: FindTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * For each tile in the given rectangular area (in tile coordinates) of the layer, run the given + * callback. Similar to Array.prototype.forEach in vanilla JS. + * + * If no layer specified, the map's current layer is used. + * @param callback The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param context The context under which the callback should be run. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area to search. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param layer The Tile layer to run the search on. If not provided will use the current layer. + */ + forEachTile(callback: EachTileCallback, context?: object, tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Gets the image layer index based on its name. + * @param name The name of the image to get. + */ + getImageIndex(name: string): integer; + + /** + * Return a list of all valid imagelayer names loaded in this Tilemap. + */ + getImageLayerNames(): string[]; + + /** + * Internally used. Returns the index of the object in one of the Tilemaps arrays whose name + * property matches the given `name`. + * @param location The Tilemap array to search. + * @param name The name of the array element to get. + */ + getIndex(location: any[], name: string): number; + + /** + * Gets the LayerData from this.layers that is associated with `layer`, or null if an invalid + * `layer` is given. + * @param layer The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the maps current layer index. + */ + getLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.LayerData; + + /** + * Gets the ObjectLayer from this.objects that has the given `name`, or null if no ObjectLayer + * is found with that name. + * @param name The name of the object layer from Tiled. + */ + getObjectLayer(name?: string): Phaser.Tilemaps.ObjectLayer; + + /** + * Return a list of all valid objectgroup names loaded in this Tilemap. + */ + getObjectLayerNames(): string[]; + + /** + * Gets the LayerData index of the given `layer` within this.layers, or null if an invalid + * `layer` is given. + * @param layer The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + */ + getLayerIndex(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): integer; + + /** + * Gets the index of the LayerData within this.layers that has the given `name`, or null if an + * invalid `name` is given. + * @param name The name of the layer to get. + */ + getLayerIndexByName(name: string): integer; + + /** + * Gets a tile at the given tile coordinates from the given layer. + * If no layer specified, the map's current layer is used. + * @param tileX X position to get the tile from (given in tile units, not pixels). + * @param tileY Y position to get the tile from (given in tile units, not pixels). + * @param nonNull If true getTile won't return null for empty tiles, but a Tile object with an index of -1. Default false. + * @param layer The tile layer to use. If not given the current layer is used. + */ + getTileAt(tileX: integer, tileY: integer, nonNull?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Gets a tile at the given world coordinates from the given layer. + * If no layer specified, the map's current layer is used. + * @param worldX X position to get the tile from (given in pixels) + * @param worldY Y position to get the tile from (given in pixels) + * @param nonNull If true, function won't return null for empty tiles, but a Tile object with an index of -1. Default false. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + getTileAtWorldXY(worldX: number, worldY: number, nonNull?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Return a list of all valid tilelayer names loaded in this Tilemap. + */ + getTileLayerNames(): string[]; + + /** + * Gets the tiles in the given rectangular area (in tile coordinates) of the layer. + * If no layer specified, the maps current layer is used. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param layer The tile layer to use. If not given the current layer is used. + */ + getTilesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; + + /** + * Gets the tiles that overlap with the given shape in the given layer. The shape must be a Circle, + * Line, Rectangle or Triangle. The shape should be in world coordinates. + * If no layer specified, the maps current layer is used. + * @param shape A shape in world (pixel) coordinates + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + getTilesWithinShape(shape: Phaser.Geom.Circle | Phaser.Geom.Line | Phaser.Geom.Rectangle | Phaser.Geom.Triangle, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; + + /** + * Gets the tiles in the given rectangular area (in world coordinates) of the layer. + * If no layer specified, the maps current layer is used. + * @param worldX The world x coordinate for the top-left of the area. + * @param worldY The world y coordinate for the top-left of the area. + * @param width The width of the area. + * @param height The height of the area. + * @param filteringOptions Optional filters to apply when getting the tiles. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + getTilesWithinWorldXY(worldX: number, worldY: number, width: number, height: number, filteringOptions?: Phaser.Types.Tilemaps.FilteringOptions, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile[]; + + /** + * Gets the Tileset that has the given `name`, or null if an invalid `name` is given. + * @param name The name of the Tileset to get. + */ + getTileset(name: string): Phaser.Tilemaps.Tileset; + + /** + * Gets the index of the Tileset within this.tilesets that has the given `name`, or null if an + * invalid `name` is given. + * @param name The name of the Tileset to get. + */ + getTilesetIndex(name: string): integer; + + /** + * Checks if there is a tile at the given location (in tile coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * If no layer specified, the map's current layer is used. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param layer The tile layer to use. If not given the current layer is used. + */ + hasTileAt(tileX: integer, tileY: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): boolean; + + /** + * Checks if there is a tile at the given location (in world coordinates) in the given layer. Returns + * false if there is no tile or if the tile at that location has an index of -1. + * + * If no layer specified, the maps current layer is used. + * @param worldX The x coordinate, in pixels. + * @param worldY The y coordinate, in pixels. + * @param camera The Camera to use when factoring in which tiles to return. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + hasTileAtWorldXY(worldX: number, worldY: number, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): boolean; + + /** + * The LayerData object that is currently selected in the map. You can set this property using + * any type supported by setLayer. + */ + layer: Phaser.Tilemaps.LayerData; + + /** + * Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index + * or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified + * location. If you pass in an index, only the index at the specified location will be changed. + * Collision information will be recalculated at the specified location. + * + * If no layer specified, the maps current layer is used. + * + * This cannot be applied to StaticTilemapLayers. + * @param tile The index of this tile to set or a Tile object. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + putTileAt(tile: integer | Phaser.Tilemaps.Tile, tileX: integer, tileY: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Puts a tile at the given world coordinates (pixels) in the specified layer. You can pass in either + * an index or a Tile object. If you pass in a Tile, all attributes will be copied over to the + * specified location. If you pass in an index, only the index at the specified location will be + * changed. Collision information will be recalculated at the specified location. + * + * If no layer specified, the maps current layer is used. This + * cannot be applied to StaticTilemapLayers. + * @param tile The index of this tile to set or a Tile object. + * @param worldX The x coordinate, in pixels. + * @param worldY The y coordinate, in pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + putTileAtWorldXY(tile: integer | Phaser.Tilemaps.Tile, worldX: number, worldY: number, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Puts an array of tiles or a 2D array of tiles at the given tile coordinates in the specified + * layer. The array can be composed of either tile indexes or Tile objects. If you pass in a Tile, + * all attributes will be copied over to the specified location. If you pass in an index, only the + * index at the specified location will be changed. Collision information will be recalculated + * within the region tiles were changed. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param tile A row (array) or grid (2D array) of Tiles or tile indexes to place. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + putTilesAt(tile: integer[] | integer[][] | Phaser.Tilemaps.Tile[] | Phaser.Tilemaps.Tile[][], tileX: integer, tileY: integer, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. If an array of indexes is passed in, then + * those will be used for randomly assigning new tile indexes. If an array is not provided, the + * indexes found within the region (excluding -1) will be used for randomly assigning new tile + * indexes. This method only modifies tile indexes and does not change collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param indexes An array of indexes to randomly draw from during randomization. + * @param layer The tile layer to use. If not given the current layer is used. + */ + randomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, indexes?: integer[], layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting + * faces are used internally for optimizing collisions against tiles. This method is mostly used + * internally to optimize recalculating faces when only one tile has been changed. + * + * If no layer specified, the maps current layer is used. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param layer The tile layer to use. If not given the current layer is used. + */ + calculateFacesAt(tileX: integer, tileY: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the + * layer. Interesting faces are used internally for optimizing collisions against tiles. This method + * is mostly used internally. + * + * If no layer specified, the map's current layer is used. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param layer The tile layer to use. If not given the current layer is used. + */ + calculateFacesWithin(tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Removes the given TilemapLayer from this Tilemap without destroying it. + * + * If no layer specified, the map's current layer is used. + * @param layer The tile layer to be removed. + */ + removeLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Destroys the given TilemapLayer and removes it from this Tilemap. + * + * If no layer specified, the map's current layer is used. + * @param layer The tile layer to be destroyed. + */ + destroyLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Removes all layers from this Tilemap and destroys any associated StaticTilemapLayers or + * DynamicTilemapLayers. + */ + removeAllLayers(): Phaser.Tilemaps.Tilemap; + + /** + * Removes the given Tile, or an array of Tiles, from the layer to which they belong, + * and optionally recalculates the collision information. + * + * This cannot be applied to Tiles that belong to Static Tilemap Layers. + * @param tiles The Tile to remove, or an array of Tiles. + * @param replaceIndex After removing the Tile, insert a brand new Tile into its location with the given index. Leave as -1 to just remove the tile. Default -1. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + */ + removeTile(tiles: Phaser.Tilemaps.Tile | Phaser.Tilemaps.Tile[], replaceIndex?: integer, recalculateFaces?: boolean): Phaser.Tilemaps.Tile[]; + + /** + * Removes the tile at the given tile coordinates in the specified layer and updates the layer's + * collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + removeTileAt(tileX: integer, tileY: integer, replaceWithNull?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Removes the tile at the given world coordinates in the specified layer and updates the layer's + * collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param worldX The x coordinate, in pixels. + * @param worldY The y coordinate, in pixels. + * @param replaceWithNull If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1. Default true. + * @param recalculateFaces `true` if the faces data should be recalculated. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + removeTileAtWorldXY(worldX: number, worldY: number, replaceWithNull?: boolean, recalculateFaces?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tile; + + /** + * Draws a debug representation of the layer to the given Graphics. This is helpful when you want to + * get a quick idea of which of your tiles are colliding and which have interesting faces. The tiles + * are drawn starting at (0, 0) in the Graphics, allowing you to place the debug representation + * wherever you want on the screen. + * + * If no layer specified, the maps current layer is used. + * @param graphics The target Graphics object to draw upon. + * @param styleConfig An object specifying the colors to use for the debug drawing. + * @param layer The tile layer to use. If not given the current layer is used. + */ + renderDebug(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Draws a debug representation of all layers within this Tilemap to the given Graphics object. + * + * This is helpful when you want to get a quick idea of which of your tiles are colliding and which + * have interesting faces. The tiles are drawn starting at (0, 0) in the Graphics, allowing you to + * place the debug representation wherever you want on the screen. + * @param graphics The target Graphics object to draw upon. + * @param styleConfig An object specifying the colors to use for the debug drawing. + * @param layer The tile layer to use. If not given the current layer is used. + */ + renderDebugFull(graphics: Phaser.GameObjects.Graphics, styleConfig: Phaser.Types.Tilemaps.StyleConfig, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `findIndex` and updates their index to match `newIndex`. This only modifies the index and does + * not change collision information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param findIndex The index of the tile to search for. + * @param newIndex The index of the tile to replace it with. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param layer The tile layer to use. If not given the current layer is used. + */ + replaceByIndex(findIndex: integer, newIndex: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets collision on the given tile or tiles within a layer by index. You can pass in either a + * single numeric index or an array of indexes: [2, 3, 15, 20]. The `collides` parameter controls if + * collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * @param indexes Either a single tile index, or an array of tile indexes. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + * @param updateLayer If true, updates the current tiles on the layer. Set to false if no tiles have been placed for significant performance boost. Default true. + */ + setCollision(indexes: integer | any[], collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer, updateLayer?: boolean): Phaser.Tilemaps.Tilemap; + + /** + * Sets collision on a range of tiles in a layer whose index is between the specified `start` and + * `stop` (inclusive). Calling this with a start value of 10 and a stop value of 14 would set + * collision for tiles 10, 11, 12, 13 and 14. The `collides` parameter controls if collision will be + * enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * @param start The first index of the tile to be set for collision. + * @param stop The last index of the tile to be set for collision. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + setCollisionBetween(start: integer, stop: integer, collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets collision on the tiles within a layer by checking tile properties. If a tile has a property + * that matches the given properties object, its collision flag will be set. The `collides` + * parameter controls if collision will be enabled (true) or disabled (false). Passing in + * `{ collides: true }` would update the collision flag on any tiles with a "collides" property that + * has a value of true. Any tile that doesn't have "collides" set to true will be ignored. You can + * also use an array of values, e.g. `{ types: ["stone", "lava", "sand" ] }`. If a tile has a + * "types" property that matches any of those values, its collision flag will be updated. + * + * If no layer specified, the map's current layer is used. + * @param properties An object with tile properties and corresponding values that should be checked. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + setCollisionByProperty(properties: object, collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets collision on all tiles in the given layer, except for tiles that have an index specified in + * the given array. The `collides` parameter controls if collision will be enabled (true) or + * disabled (false). + * + * If no layer specified, the map's current layer is used. + * @param indexes An array of the tile indexes to not be counted for collision. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + setCollisionByExclusion(indexes: integer[], collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets collision on the tiles within a layer by checking each tile's collision group data + * (typically defined in Tiled within the tileset collision editor). If any objects are found within + * a tile's collision group, the tile's colliding information will be set. The `collides` parameter + * controls if collision will be enabled (true) or disabled (false). + * + * If no layer specified, the map's current layer is used. + * @param collides If true it will enable collision. If false it will clear collision. Default true. + * @param recalculateFaces Whether or not to recalculate the tile faces after the update. Default true. + * @param layer The tile layer to use. If not given the current layer is used. + */ + setCollisionFromCollisionGroup(collides?: boolean, recalculateFaces?: boolean, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all + * tiles on this layer that have the same index. If a callback is already set for the tile index it + * will be replaced. Set the callback to null to remove it. If you want to set a callback for a tile + * at a specific location on the map then see setTileLocationCallback. + * + * If no layer specified, the map's current layer is used. + * @param indexes Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param callback The callback that will be invoked when the tile is collided with. + * @param callbackContext The context under which the callback is called. + * @param layer The tile layer to use. If not given the current layer is used. + */ + setTileIndexCallback(indexes: integer | any[], callback: Function, callbackContext: object, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets a collision callback for the given rectangular area (in tile coordinates) within the layer. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to + * remove it. + * + * If no layer specified, the map's current layer is used. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. + * @param width How many tiles wide from the `tileX` index the area will be. + * @param height How many tiles tall from the `tileY` index the area will be. + * @param callback The callback that will be invoked when the tile is collided with. + * @param callbackContext The context under which the callback is called. + * @param layer The tile layer to use. If not given the current layer is used. + */ + setTileLocationCallback(tileX: integer, tileY: integer, width: integer, height: integer, callback: Function, callbackContext?: object, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets the current layer to the LayerData associated with `layer`. + * @param layer The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + */ + setLayer(layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Sets the base tile size for the map. Note: this does not necessarily match the tileWidth and + * tileHeight for all layers. This also updates the base size on all tiles across all layers. + * @param tileWidth The width of the tiles the map uses for calculations. + * @param tileHeight The height of the tiles the map uses for calculations. + */ + setBaseTileSize(tileWidth: integer, tileHeight: integer): Phaser.Tilemaps.Tilemap; + + /** + * Sets the tile size for a specific `layer`. Note: this does not necessarily match the map's + * tileWidth and tileHeight for all layers. This will set the tile size for the layer and any + * tiles the layer has. + * @param tileWidth The width of the tiles (in pixels) in the layer. + * @param tileHeight The height of the tiles (in pixels) in the layer. + * @param layer The name of the + * layer from Tiled, the index of the layer in the map, a DynamicTilemapLayer or a + * StaticTilemapLayer. If not given will default to the map's current layer index. + */ + setLayerTileSize(tileWidth: integer, tileHeight: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Shuffles the tiles in a rectangular region (specified in tile coordinates) within the given + * layer. It will only randomize the tiles in that area, so if they're all the same nothing will + * appear to have changed! This method only modifies tile indexes and does not change collision + * information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param layer The tile layer to use. If not given the current layer is used. + */ + shuffle(tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Scans the given rectangular area (given in tile coordinates) for tiles with an index matching + * `indexA` and swaps then with `indexB`. This only modifies the index and does not change collision + * information. + * + * If no layer specified, the maps current layer is used. + * This cannot be applied to StaticTilemapLayers. + * @param tileA First tile index. + * @param tileB Second tile index. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param layer The tile layer to use. If not given the current layer is used. + */ + swapByIndex(tileA: integer, tileB: integer, tileX?: integer, tileY?: integer, width?: integer, height?: integer, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Converts from tile X coordinates (tile units) to world X coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * @param tileX The x coordinate, in tiles, not pixels. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + tileToWorldX(tileX: integer, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; + + /** + * Converts from tile Y coordinates (tile units) to world Y coordinates (pixels), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * @param tileY The y coordinate, in tiles, not pixels. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer + * to use. If not given the current layer is used. + */ + tileToWorldY(tileY: integer, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; + + /** + * Converts from tile XY coordinates (tile units) to world XY coordinates (pixels), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * If no layer specified, the maps current layer is used. + * @param tileX The x coordinate, in tiles, not pixels. + * @param tileY The y coordinate, in tiles, not pixels. + * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + tileToWorldXY(tileX: integer, tileY: integer, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Math.Vector2; + + /** + * Randomizes the indexes of a rectangular region of tiles (in tile coordinates) within the + * specified layer. Each tile will receive a new index. New indexes are drawn from the given + * weightedIndexes array. An example weighted array: + * + * [ + * { index: 6, weight: 4 }, // Probability of index 6 is 4 / 8 + * { index: 7, weight: 2 }, // Probability of index 7 would be 2 / 8 + * { index: 8, weight: 1.5 }, // Probability of index 8 would be 1.5 / 8 + * { index: 26, weight: 0.5 } // Probability of index 27 would be 0.5 / 8 + * ] + * + * The probability of any index being choose is (the index's weight) / (sum of all weights). This + * method only modifies tile indexes and does not change collision information. + * + * If no layer specified, the map's current layer is used. This + * cannot be applied to StaticTilemapLayers. + * @param tileX The left most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param tileY The top most tile index (in tile coordinates) to use as the origin of the area. Default 0. + * @param width How many tiles wide from the `tileX` index the area will be. Default max width based on tileX. + * @param height How many tiles tall from the `tileY` index the area will be. Default max height based on tileY. + * @param weightedIndexes An array of objects to randomly draw from during + * randomization. They should be in the form: { index: 0, weight: 4 } or + * { index: [0, 1], weight: 4 } if you wish to draw from multiple tile indexes. + * @param layer The tile layer to use. If not given the current layer is used. + */ + weightedRandomize(tileX?: integer, tileY?: integer, width?: integer, height?: integer, weightedIndexes?: object[], layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Tilemaps.Tilemap; + + /** + * Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * @param worldX The x coordinate to be converted, in pixels, not tiles. + * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer + * to use. If not given the current layer is used. + */ + worldToTileX(worldX: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; + + /** + * Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the + * layers position, scale and scroll. + * + * If no layer specified, the maps current layer is used. + * @param worldY The y coordinate to be converted, in pixels, not tiles. + * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + worldToTileY(worldY: number, snapToFloor?: boolean, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): number; + + /** + * Converts from world XY coordinates (pixels) to tile XY coordinates (tile units), factoring in the + * layers position, scale and scroll. This will return a new Vector2 object or update the given + * `point` object. + * + * If no layer specified, the maps current layer is used. + * @param worldX The x coordinate to be converted, in pixels, not tiles. + * @param worldY The y coordinate to be converted, in pixels, not tiles. + * @param snapToFloor Whether or not to round the tile coordinate down to the nearest integer. Default true. + * @param point A Vector2 to store the coordinates in. If not given a new Vector2 is created. + * @param camera The Camera to use when calculating the tile index from the world values. Default main camera. + * @param layer The tile layer to use. If not given the current layer is used. + */ + worldToTileXY(worldX: number, worldY: number, snapToFloor?: boolean, point?: Phaser.Math.Vector2, camera?: Phaser.Cameras.Scene2D.Camera, layer?: string | integer | Phaser.Tilemaps.DynamicTilemapLayer | Phaser.Tilemaps.StaticTilemapLayer): Phaser.Math.Vector2; + + } + + /** + * A Tileset is a combination of an image containing the tiles and a container for data about + * each tile. + */ + class Tileset { + /** + * + * @param name The name of the tileset in the map data. + * @param firstgid The first tile index this tileset contains. + * @param tileWidth Width of each tile (in pixels). Default 32. + * @param tileHeight Height of each tile (in pixels). Default 32. + * @param tileMargin The margin around all tiles in the sheet (in pixels). Default 0. + * @param tileSpacing The spacing between each tile in the sheet (in pixels). Default 0. + * @param tileProperties Custom properties defined per tile in the Tileset. + * These typically are custom properties created in Tiled when editing a tileset. Default {}. + * @param tileData Data stored per tile. These typically are created in Tiled + * when editing a tileset, e.g. from Tiled's tile collision editor or terrain editor. Default {}. + */ + constructor(name: string, firstgid: integer, tileWidth?: integer, tileHeight?: integer, tileMargin?: integer, tileSpacing?: integer, tileProperties?: object, tileData?: object); + + /** + * The name of the Tileset. + */ + name: string; + + /** + * The starting index of the first tile index this Tileset contains. + */ + firstgid: integer; + + /** + * The width of each tile (in pixels). Use setTileSize to change. + */ + readonly tileWidth: integer; + + /** + * The height of each tile (in pixels). Use setTileSize to change. + */ + readonly tileHeight: integer; + + /** + * The margin around the tiles in the sheet (in pixels). Use `setSpacing` to change. + */ + readonly tileMargin: integer; + + /** + * The spacing between each the tile in the sheet (in pixels). Use `setSpacing` to change. + */ + readonly tileSpacing: integer; + + /** + * Tileset-specific properties per tile that are typically defined in the Tiled editor in the + * Tileset editor. + */ + tileProperties: object; + + /** + * Tileset-specific data per tile that are typically defined in the Tiled editor, e.g. within + * the Tileset collision editor. This is where collision objects and terrain are stored. + */ + tileData: object; + + /** + * The cached image that contains the individual tiles. Use setImage to set. + */ + readonly image: Phaser.Textures.Texture; + + /** + * The gl texture used by the WebGL renderer. + */ + readonly glTexture: WebGLTexture; + + /** + * The number of tile rows in the the tileset. + */ + readonly rows: integer; + + /** + * The number of tile columns in the tileset. + */ + readonly columns: integer; + + /** + * The total number of tiles in the tileset. + */ + readonly total: integer; + + /** + * The look-up table to specific tile image texture coordinates (UV in pixels). Each element + * contains the coordinates for a tile in an object of the form {x, y}. + */ + readonly texCoordinates: object[]; + + /** + * Get a tiles properties that are stored in the Tileset. Returns null if tile index is not + * contained in this Tileset. This is typically defined in Tiled under the Tileset editor. + * @param tileIndex The unique id of the tile across all tilesets in the map. + */ + getTileProperties(tileIndex: integer): object | undefined; + + /** + * Get a tile's data that is stored in the Tileset. Returns null if tile index is not contained + * in this Tileset. This is typically defined in Tiled and will contain both Tileset collision + * info and terrain mapping. + * @param tileIndex The unique id of the tile across all tilesets in the map. + */ + getTileData(tileIndex: integer): object | undefined; + + /** + * Get a tile's collision group that is stored in the Tileset. Returns null if tile index is not + * contained in this Tileset. This is typically defined within Tiled's tileset collision editor. + * @param tileIndex The unique id of the tile across all tilesets in the map. + */ + getTileCollisionGroup(tileIndex: integer): object; + + /** + * Returns true if and only if this Tileset contains the given tile index. + * @param tileIndex The unique id of the tile across all tilesets in the map. + */ + containsTileIndex(tileIndex: integer): boolean; + + /** + * Returns the texture coordinates (UV in pixels) in the Tileset image for the given tile index. + * Returns null if tile index is not contained in this Tileset. + * @param tileIndex The unique id of the tile across all tilesets in the map. + */ + getTileTextureCoordinates(tileIndex: integer): object; + + /** + * Sets the image associated with this Tileset and updates the tile data (rows, columns, etc.). + * @param texture The image that contains the tiles. + */ + setImage(texture: Phaser.Textures.Texture): Phaser.Tilemaps.Tileset; + + /** + * Sets the tile width & height and updates the tile data (rows, columns, etc.). + * @param tileWidth The width of a tile in pixels. + * @param tileHeight The height of a tile in pixels. + */ + setTileSize(tileWidth?: integer, tileHeight?: integer): Phaser.Tilemaps.Tileset; + + /** + * Sets the tile margin & spacing and updates the tile data (rows, columns, etc.). + * @param margin The margin around the tiles in the sheet (in pixels). + * @param spacing The spacing between the tiles in the sheet (in pixels). + */ + setSpacing(margin?: integer, spacing?: integer): Phaser.Tilemaps.Tileset; + + /** + * Updates tile texture coordinates and tileset data. + * @param imageWidth The (expected) width of the image to slice. + * @param imageHeight The (expected) height of the image to slice. + */ + updateTileData(imageWidth: integer, imageHeight: integer): Phaser.Tilemaps.Tileset; + + } + + } + + namespace Time { + /** + * The Clock is a Scene plugin which creates and updates Timer Events for its Scene. + */ + class Clock { + /** + * + * @param scene The Scene which owns this Clock. + */ + constructor(scene: Phaser.Scene); + + /** + * The Scene which owns this Clock. + */ + scene: Phaser.Scene; + + /** + * The Scene Systems object of the Scene which owns this Clock. + */ + systems: Phaser.Scenes.Systems; + + /** + * The current time of the Clock, in milliseconds. + * + * If accessed externally, this is equivalent to the `time` parameter normally passed to a Scene's `update` method. + */ + now: number; + + /** + * The scale of the Clock's time delta. + * + * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Clock and anything which uses it, such as its Timer Events. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing the Clock. + */ + timeScale: number; + + /** + * Whether the Clock is paused (`true`) or active (`false`). + * + * When paused, the Clock will not update any of its Timer Events, thus freezing time. + */ + paused: boolean; + + /** + * Creates a Timer Event and adds it to the Clock at the start of the frame. + * @param config The configuration for the Timer Event. + */ + addEvent(config: Phaser.Types.Time.TimerEventConfig): Phaser.Time.TimerEvent; + + /** + * Creates a Timer Event and adds it to the Clock at the start of the frame. + * + * This is a shortcut for {@link #addEvent} which can be shorter and is compatible with the syntax of the GreenSock Animation Platform (GSAP). + * @param delay The delay of the function call, in milliseconds. + * @param callback The function to call after the delay expires. + * @param args The arguments to call the function with. + * @param callbackScope The scope (`this` object) to call the function with. + */ + delayedCall(delay: number, callback: Function, args?: any[], callbackScope?: any): Phaser.Time.TimerEvent; + + /** + * Clears and recreates the array of pending Timer Events. + */ + clearPendingEvents(): Phaser.Time.Clock; + + /** + * Schedules all active Timer Events for removal at the start of the frame. + */ + removeAllEvents(): Phaser.Time.Clock; + + /** + * Updates the arrays of active and pending Timer Events. Called at the start of the frame. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + preUpdate(time: number, delta: number): void; + + /** + * Updates the Clock's internal time and all of its Timer Events. + * @param time The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(time: number, delta: number): void; + + } + + /** + * 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 { + /** + * + * @param config The configuration for the Timer Event, including its delay and callback. + */ + constructor(config: Phaser.Types.Time.TimerEventConfig); + + /** + * The delay in ms at which this TimerEvent fires. + */ + readonly delay: number; + + /** + * The total number of times this TimerEvent will repeat before finishing. + */ + readonly repeat: number; + + /** + * If repeating this contains the current repeat count. + */ + repeatCount: number; + + /** + * True if this TimerEvent loops, otherwise false. + */ + readonly loop: boolean; + + /** + * The callback that will be called when the TimerEvent occurs. + */ + callback: Function; + + /** + * The scope in which the callback will be called. + */ + callbackScope: object; + + /** + * Additional arguments to be passed to the callback. + */ + args: any[]; + + /** + * Scale the time causing this TimerEvent to update. + */ + timeScale: number; + + /** + * Start this many MS into the elapsed (useful if you want a long duration with repeat, but for the first loop to fire quickly) + */ + startAt: number; + + /** + * The time in milliseconds which has elapsed since the Timer Event's creation. + * + * This value is local for the Timer Event and is relative to its Clock. As such, it's influenced by the Clock's time scale and paused state, the Timer Event's initial {@link #startAt} property, and the Timer Event's {@link #timeScale} and {@link #paused} state. + */ + elapsed: number; + + /** + * Whether or not this timer is paused. + */ + paused: boolean; + + /** + * Whether the Timer Event's function has been called. + * + * When the Timer Event fires, this property will be set to `true` before the callback function is invoked and will be reset immediately afterward if the Timer Event should repeat. The value of this property does not directly influence whether the Timer Event will be removed from its Clock, but can prevent it from firing. + */ + hasDispatched: boolean; + + /** + * Completely reinitializes the Timer Event, regardless of its current state, according to a configuration object. + * @param config The new state for the Timer Event. + */ + reset(config: Phaser.Types.Time.TimerEventConfig): Phaser.Time.TimerEvent; + + /** + * Gets the progress of the current iteration, not factoring in repeats. + */ + getProgress(): number; + + /** + * Gets the progress of the timer overall, factoring in repeats. + */ + getOverallProgress(): number; + + /** + * Returns the number of times this Timer Event will repeat before finishing. + * + * This should not be confused with the number of times the Timer Event will fire before finishing. A return value of 0 doesn't indicate that the Timer Event has finished running - it indicates that it will not repeat after the next time it fires. + */ + getRepeatCount(): number; + + /** + * Returns the local elapsed time for the current iteration of the Timer Event. + */ + getElapsed(): number; + + /** + * Returns the local elapsed time for the current iteration of the Timer Event in seconds. + */ + getElapsedSeconds(): number; + + /** + * Forces the Timer Event to immediately expire, thus scheduling its removal in the next frame. + * @param dispatchCallback If `true`, the function of the Timer Event will be called before its removal. Default false. + */ + remove(dispatchCallback?: boolean): void; + + /** + * Destroys all object references in the Timer Event, i.e. its callback, scope, and arguments. + * + * Normally, this method is only called by the Clock when it shuts down. As such, it doesn't stop the Timer Event. If called manually, the Timer Event will still be updated by the Clock, but it won't do anything when it fires. + */ + destroy(): void; + + } + + } + + namespace Tweens { + namespace Builders { + /** + * Retrieves the value of the given key from an object. + * @param source The object to retrieve the value from. + * @param key The key to look for in the `source` object. + * @param defaultValue The default value to return if the `key` doesn't exist or if no `source` object is provided. + */ + function GetBoolean(source: object, key: string, defaultValue: any): any; + + /** + * This internal function is used to return the correct ease function for a Tween. + * + * It can take a variety of input, including an EaseMap based string, or a custom function. + * @param ease The ease to find. This can be either a string from the EaseMap, or a custom function. + * @param easeParams An optional array of ease parameters to go with the ease. + */ + function GetEaseFunction(ease: string | Function, easeParams?: number[]): Function; + + /** + * Internal function used by the Tween Builder to create a function that will return + * the given value from the source. + * @param source The source object to get the value from. + * @param key The property to get from the source. + * @param defaultValue A default value to return should the source not have the property set. + */ + function GetNewValue(source: any, key: string, defaultValue: any): Function; + + /** + * Internal function used by the Tween Builder to return an array of properties + * that the Tween will be operating on. It takes a tween configuration object + * and then checks that none of the `props` entries start with an underscore, or that + * none of the direct properties are on the Reserved list. + * @param config The configuration object of the Tween to get the properties from. + */ + function GetProps(config: Phaser.Types.Tweens.TweenBuilderConfig): string[]; + + /** + * Extracts an array of targets from a Tween configuration object. + * + * The targets will be looked for in a `targets` property. If it's a function, its return value will be used as the result. + * @param config The configuration object to use. + */ + function GetTargets(config: object): any[]; + + /** + * Internal function used by the Timeline Builder. + * + * It returns an array of all tweens in the given timeline config. + * @param config The configuration object for the Timeline. + */ + function GetTweens(config: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Tween[]; + + /** + * 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. + * + * 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. + * @param key The name of the property to modify. + * @param propertyValue The ending value of the property, as described above. + */ + function GetValueOp(key: string, propertyValue: any): Function; + + /** + * Creates a new Number Tween. + * @param parent The owner of the new Tween. + * @param config Configuration for the new Tween. + * @param defaults Tween configuration defaults. + */ + function NumberTweenBuilder(parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline, config: Phaser.Types.Tweens.NumberTweenBuilderConfig, defaults: Phaser.Types.Tweens.TweenConfigDefaults): Phaser.Tweens.Tween; + + /** + * 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' }) + * }); + * ``` + * @param value The amount to stagger by, or an array containing two elements representing the min and max values to stagger between. + * @param config A Stagger Configuration object. + */ + function StaggerBuilder(value: number | number[], config?: Phaser.Types.Tweens.StaggerConfig): Function; + + /** + * Builds a Timeline of Tweens based on a configuration object. + * @param manager The Tween Manager to which the Timeline will belong. + * @param config The configuration object for the Timeline. + */ + function TimelineBuilder(manager: Phaser.Tweens.TweenManager, config: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Timeline; + + /** + * Creates a new Tween. + * @param parent The owner of the new Tween. + * @param config Configuration for the new Tween. + * @param defaults Tween configuration defaults. + */ + function TweenBuilder(parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline, config: Phaser.Types.Tweens.TweenBuilderConfig | object, defaults: Phaser.Types.Tweens.TweenConfigDefaults): Phaser.Tweens.Tween; + + } + + namespace Events { + /** + * The Timeline Complete Event. + * + * This event is dispatched by a Tween Timeline when it completes playback. + * + * Listen to it from a Timeline instance using `Timeline.on('complete', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('complete', listener); + * timeline.play(); + * ``` + */ + const TIMELINE_COMPLETE: any; + + /** + * The Timeline Loop Event. + * + * This event is dispatched by a Tween Timeline every time it loops. + * + * Listen to it from a Timeline instance using `Timeline.on('loop', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * loop: 4, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('loop', listener); + * timeline.play(); + * ``` + */ + const TIMELINE_LOOP: any; + + /** + * The Timeline Pause Event. + * + * This event is dispatched by a Tween Timeline when it is paused. + * + * Listen to it from a Timeline instance using `Timeline.on('pause', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('pause', listener); + * // At some point later ... + * timeline.pause(); + * ``` + */ + const TIMELINE_PAUSE: any; + + /** + * The Timeline Resume Event. + * + * This event is dispatched by a Tween Timeline when it is resumed from a paused state. + * + * Listen to it from a Timeline instance using `Timeline.on('resume', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('resume', listener); + * // At some point later ... + * timeline.resume(); + * ``` + */ + const TIMELINE_RESUME: any; + + /** + * The Timeline Start Event. + * + * This event is dispatched by a Tween Timeline when it starts. + * + * Listen to it from a Timeline instance using `Timeline.on('start', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('start', listener); + * timeline.play(); + * ``` + */ + const TIMELINE_START: any; + + /** + * The Timeline Update Event. + * + * This event is dispatched by a Tween Timeline every time it updates, which can happen a lot of times per second, + * so be careful about listening to this event unless you absolutely require it. + * + * Listen to it from a Timeline instance using `Timeline.on('update', listener)`, i.e.: + * + * ```javascript + * var timeline = this.tweens.timeline({ + * targets: image, + * ease: 'Power1', + * duration: 3000, + * tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ] + * }); + * timeline.on('update', listener); + * timeline.play(); + * ``` + */ + const TIMELINE_UPDATE: any; + + /** + * The Tween Active Event. + * + * This event is dispatched by a Tween when it becomes active within the Tween Manager. + * + * An 'active' Tween is one that is now progressing, although it may not yet be updating + * any target properties, due to settings such as `delay`. If you need an event for when + * the Tween starts actually updating its first property, see `TWEEN_START`. + * + * Listen to it from a Tween instance using `Tween.on('active', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('active', listener); + * ``` + */ + const TWEEN_ACTIVE: any; + + /** + * The Tween Complete Event. + * + * This event is dispatched by a Tween when it completes playback entirely, factoring in repeats and loops. + * + * If the Tween has been set to loop or repeat infinitely, this event will not be dispatched + * unless the `Tween.stop` method is called. + * + * If a Tween has a `completeDelay` set, this event will fire after that delay expires. + * + * Listen to it from a Tween instance using `Tween.on('complete', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('complete', listener); + * ``` + */ + const TWEEN_COMPLETE: any; + + /** + * The Tween Loop Event. + * + * This event is dispatched by a Tween when it loops. + * + * This event will only be dispatched if the Tween has a loop count set. + * + * If a Tween has a `loopDelay` set, this event will fire after that delay expires. + * + * The difference between `loop` and `repeat` is that `repeat` is a property setting, + * where-as `loop` applies to the entire Tween. + * + * Listen to it from a Tween instance using `Tween.on('loop', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * loop: 6 + * }); + * tween.on('loop', listener); + * ``` + */ + const TWEEN_LOOP: any; + + /** + * The Tween Repeat Event. + * + * This event is dispatched by a Tween when one of the properties it is tweening repeats. + * + * This event will only be dispatched if the Tween has a property with a repeat count set. + * + * If a Tween has a `repeatDelay` set, this event will fire after that delay expires. + * + * The difference between `loop` and `repeat` is that `repeat` is a property setting, + * where-as `loop` applies to the entire Tween. + * + * Listen to it from a Tween instance using `Tween.on('repeat', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * repeat: 4 + * }); + * tween.on('repeat', listener); + * ``` + */ + const TWEEN_REPEAT: any; + + /** + * The Tween Start Event. + * + * This event is dispatched by a Tween when it starts tweening its first property. + * + * A Tween will only emit this event once, as it can only start once. + * + * If a Tween has a `delay` set, this event will fire after that delay expires. + * + * Listen to it from a Tween instance using `Tween.on('start', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000 + * }); + * tween.on('start', listener); + * ``` + */ + const TWEEN_START: any; + + /** + * The Tween Update Event. + * + * This event is dispatched by a Tween every time it updates _any_ of the properties it is tweening. + * + * A Tween that is changing 3 properties of a target will emit this event 3 times per change, once per property. + * + * **Note:** This is a very high frequency event and may be dispatched multiple times, every single frame. + * + * Listen to it from a Tween instance using `Tween.on('update', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * }); + * tween.on('update', listener); + * ``` + */ + const TWEEN_UPDATE: any; + + /** + * The Tween Yoyo Event. + * + * This event is dispatched by a Tween whenever a property it is tweening yoyos. + * + * This event will only be dispatched if the Tween has a property with `yoyo` set. + * + * If the Tween has a `hold` value, this event is dispatched when the hold expires. + * + * This event is dispatched for every property, and for every target, that yoyos. + * For example, if a Tween was updating 2 properties and had 10 targets, this event + * would be dispatched 20 times (twice per target). So be careful how you use it! + * + * Listen to it from a Tween instance using `Tween.on('yoyo', listener)`, i.e.: + * + * ```javascript + * var tween = this.tweens.add({ + * targets: image, + * x: 500, + * ease: 'Power1', + * duration: 3000, + * yoyo: true + * }); + * tween.on('yoyo', listener); + * ``` + */ + const TWEEN_YOYO: any; + + } + + /** + * A Timeline combines multiple Tweens into one. Its overall behavior is otherwise similar to a single Tween. + * + * The Timeline updates all of its Tweens simultaneously. Its methods allow you to easily build a sequence + * of Tweens (each one starting after the previous one) or run multiple Tweens at once during given parts of the Timeline. + */ + class Timeline extends Phaser.Events.EventEmitter { + /** + * + * @param manager The Tween Manager which owns this Timeline. + */ + constructor(manager: Phaser.Tweens.TweenManager); + + /** + * The Tween Manager which owns this Timeline. + */ + manager: Phaser.Tweens.TweenManager; + + /** + * A constant value which allows this Timeline to be easily identified as one. + */ + isTimeline: boolean; + + /** + * An array of Tween objects, each containing a unique property and target being tweened. + */ + data: any[]; + + /** + * The cached size of the data array. + */ + totalData: number; + + /** + * If true then duration, delay, etc values are all frame totals, rather than ms. + */ + useFrames: boolean; + + /** + * Scales the time applied to this Timeline. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * Value isn't used when calculating total duration of the Timeline, it's a run-time delta adjustment only. + */ + timeScale: number; + + /** + * Loop this Timeline? Can be -1 for an infinite loop, or an integer. + * When enabled it will play through ALL Tweens again (use Tween.repeat to loop a single tween) + */ + loop: number; + + /** + * Time in ms/frames before this Timeline loops. + */ + loopDelay: number; + + /** + * How many loops are left to run? + */ + loopCounter: number; + + /** + * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = true (as it never completes) + */ + completeDelay: number; + + /** + * Countdown timer value, as used by `loopDelay` and `completeDelay`. + */ + countdown: number; + + /** + * The current state of the Timeline. + */ + state: integer; + + /** + * Does the Timeline start off paused? (if so it needs to be started with Timeline.play) + */ + paused: boolean; + + /** + * Elapsed time in ms/frames of this run through of the Timeline. + */ + elapsed: number; + + /** + * Total elapsed time in ms/frames of the entire Timeline, including looping. + */ + totalElapsed: number; + + /** + * Time in ms/frames for the whole Timeline to play through once, excluding loop amounts and loop delays. + */ + duration: number; + + /** + * Value between 0 and 1. The amount of progress through the Timeline, _excluding loops_. + */ + progress: number; + + /** + * Time in ms/frames for all Tweens in this Timeline to complete (including looping) + */ + totalDuration: number; + + /** + * Value between 0 and 1. The amount through the entire Timeline, including looping. + */ + totalProgress: number; + + /** + * An object containing the different Tween callback functions. + * + * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. + * + * `onComplete` When the Timeline finishes playback fully or `Timeline.stop` is called. Never invoked if timeline is set to repeat infinitely. + * `onLoop` When a Timeline loops. + * `onStart` When the Timeline starts playing. + * `onUpdate` When a Timeline updates a child Tween. + * `onYoyo` When a Timeline starts a yoyo. + */ + callbacks: object; + + /** + * The context in which all callbacks are invoked. + */ + callbackScope: any; + + /** + * Internal method that will emit a Timeline based Event and invoke the given callback. + * @param event The Event to be dispatched. + * @param callback The callback to be invoked. Can be `null` or `undefined` to skip invocation. + */ + dispatchTimelineEvent(event: Phaser.Types.Tweens.Event, callback: Function): void; + + /** + * Sets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. + * A value of 0.5 runs 50% slower, and so on. + * + * The value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. + * @param value The time scale value to set. + */ + setTimeScale(value: number): this; + + /** + * Gets the value of the time scale applied to this Timeline. A value of 1 runs in real-time. + * A value of 0.5 runs 50% slower, and so on. + */ + getTimeScale(): number; + + /** + * Check whether or not the Timeline is playing. + */ + isPlaying(): boolean; + + /** + * Creates a new Tween, based on the given Tween Config, and adds it to this Timeline. + * @param config The configuration object for the Tween. + */ + add(config: Phaser.Types.Tweens.TweenBuilderConfig | object): this; + + /** + * Adds an existing Tween to this Timeline. + * @param tween The Tween to be added to this Timeline. + */ + queue(tween: Phaser.Tweens.Tween): this; + + /** + * Checks whether a Tween has an offset value. + * @param tween The Tween to check. + */ + hasOffset(tween: Phaser.Tweens.Tween): boolean; + + /** + * Checks whether the offset value is a number or a directive that is relative to previous tweens. + * @param value The offset value to be evaluated. + */ + isOffsetAbsolute(value: number): boolean; + + /** + * Checks if the offset is a relative value rather than an absolute one. + * If the value is just a number, this returns false. + * @param value The offset value to be evaluated. + */ + isOffsetRelative(value: string): boolean; + + /** + * Parses the relative offset value, returning a positive or negative number. + * @param value The relative offset, in the format of '-=500', for example. The first character determines whether it will be a positive or negative number. Spacing matters here. + * @param base The value to use as the offset. + */ + getRelativeOffset(value: string, base: number): number; + + /** + * Calculates the total duration of the timeline. + * + * Computes all tween durations and returns the full duration of the timeline. + * + * The resulting number is stored in the timeline, not as a return value. + */ + calcDuration(): void; + + /** + * Initializes the timeline, which means all Tweens get their init() called, and the total duration will be computed. + * Returns a boolean indicating whether the timeline is auto-started or not. + */ + init(): boolean; + + /** + * Resets all of the timeline's tweens back to their initial states. + * The boolean parameter indicates whether tweens that are looping should reset as well, or not. + * @param resetFromLoop If `true`, resets all looping tweens to their initial values. + */ + resetTweens(resetFromLoop: boolean): void; + + /** + * Sets a callback for the Timeline. + * @param type The internal type of callback to set. + * @param callback Timeline allows multiple tweens to be linked together to create a streaming sequence. + * @param params The parameters to pass to the callback. + * @param scope The context scope of the callback. + */ + setCallback(type: string, callback: Function, params?: any[], scope?: object): this; + + /** + * Passed a Tween to the Tween Manager and requests it be made active. + * @param tween The tween object to make active. + */ + makeActive(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; + + /** + * Starts playing the Timeline. + */ + play(): void; + + /** + * Updates the Timeline's `state` and fires callbacks and events. + */ + nextState(): void; + + /** + * Returns 'true' if this Timeline has finished and should be removed from the Tween Manager. + * Otherwise, returns false. + * @param timestamp The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(timestamp: number, delta: number): boolean; + + /** + * Stops the Timeline immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. + */ + stop(): void; + + /** + * Pauses the Timeline, retaining its internal state. + * + * Calling this on a Timeline that is already paused has no effect and fires no event. + */ + pause(): this; + + /** + * Resumes a paused Timeline from where it was when it was paused. + * + * Calling this on a Timeline that isn't paused has no effect and fires no event. + */ + resume(): this; + + /** + * Checks if any of the Tweens in this Timeline as operating on the target object. + * + * Returns `false` if no Tweens operate on the target object. + * @param target The target to check all Tweens against. + */ + hasTarget(target: object): boolean; + + /** + * Stops all the Tweens in the Timeline immediately, whatever stage of progress they are at and flags + * them for removal by the TweenManager. + */ + destroy(): void; + + } + + /** + * TweenData state. + */ + var CREATED: integer; + + /** + * TweenData state. + */ + var INIT: integer; + + /** + * TweenData state. + */ + var DELAY: integer; + + /** + * TweenData state. + */ + var OFFSET_DELAY: integer; + + /** + * TweenData state. + */ + var PENDING_RENDER: integer; + + /** + * TweenData state. + */ + var PLAYING_FORWARD: integer; + + /** + * TweenData state. + */ + var PLAYING_BACKWARD: integer; + + /** + * TweenData state. + */ + var HOLD_DELAY: integer; + + /** + * TweenData state. + */ + var REPEAT_DELAY: integer; + + /** + * TweenData state. + */ + var COMPLETE: integer; + + /** + * Tween state. + */ + var PENDING_ADD: integer; + + /** + * Tween state. + */ + var PAUSED: integer; + + /** + * Tween state. + */ + var LOOP_DELAY: integer; + + /** + * Tween state. + */ + var ACTIVE: integer; + + /** + * Tween state. + */ + var COMPLETE_DELAY: integer; + + /** + * Tween state. + */ + var PENDING_REMOVE: integer; + + /** + * Tween state. + */ + var REMOVED: integer; + + /** + * A Tween is able to manipulate the properties of one or more objects to any given value, based + * on a duration and type of ease. They are rarely instantiated directly and instead should be + * created via the TweenManager. + */ + class Tween extends Phaser.Events.EventEmitter { + /** + * + * @param parent A reference to the parent of this Tween. Either the Tween Manager or a Tween Timeline instance. + * @param data An array of TweenData objects, each containing a unique property to be tweened. + * @param targets An array of targets to be tweened. + */ + constructor(parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline, data: Phaser.Types.Tweens.TweenDataConfig[], targets: any[]); + + /** + * A reference to the parent of this Tween. + * Either the Tween Manager or a Tween Timeline instance. + */ + parent: Phaser.Tweens.TweenManager | Phaser.Tweens.Timeline; + + /** + * Is the parent of this Tween a Timeline? + */ + parentIsTimeline: boolean; + + /** + * An array of TweenData objects, each containing a unique property and target being tweened. + */ + data: Phaser.Types.Tweens.TweenDataConfig[]; + + /** + * The cached length of the data array. + */ + totalData: integer; + + /** + * An array of references to the target/s this Tween is operating on. + */ + targets: object[]; + + /** + * Cached target total (not necessarily the same as the data total) + */ + totalTargets: integer; + + /** + * If `true` then duration, delay, etc values are all frame totals. + */ + useFrames: boolean; + + /** + * Scales the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * Value isn't used when calculating total duration of the tween, it's a run-time delta adjustment only. + */ + timeScale: number; + + /** + * Loop this tween? Can be -1 for an infinite loop, or an integer. + * When enabled it will play through ALL TweenDatas again. Use TweenData.repeat to loop a single element. + */ + loop: number; + + /** + * Time in ms/frames before the tween loops. + */ + loopDelay: number; + + /** + * How many loops are left to run? + */ + loopCounter: number; + + /** + * Time in ms/frames before the 'onStart' event fires. + * This is the shortest `delay` value across all of the TweenDatas of this Tween. + */ + startDelay: number; + + /** + * Has this Tween started playback yet? + * This boolean is toggled when the Tween leaves the 'delayed' state and starts running. + */ + readonly hasStarted: boolean; + + /** + * Is this Tween currently seeking? + * This boolean is toggled in the `Tween.seek` method. + * When a tween is seeking it will not dispatch any events or callbacks. + */ + readonly isSeeking: boolean; + + /** + * Time in ms/frames before the 'onComplete' event fires. This never fires if loop = -1 (as it never completes) + */ + completeDelay: number; + + /** + * Countdown timer (used by timeline offset, loopDelay and completeDelay) + */ + countdown: number; + + /** + * Set only if this Tween is part of a Timeline. + */ + offset: number; + + /** + * Set only if this Tween is part of a Timeline. The calculated offset amount. + */ + calculatedOffset: number; + + /** + * The current state of the tween + */ + state: integer; + + /** + * Does the Tween start off paused? (if so it needs to be started with Tween.play) + */ + paused: boolean; + + /** + * Elapsed time in ms/frames of this run through the Tween. + */ + elapsed: number; + + /** + * Total elapsed time in ms/frames of the entire Tween, including looping. + */ + totalElapsed: number; + + /** + * Time in ms/frames for the whole Tween to play through once, excluding loop amounts and loop delays. + */ + duration: number; + + /** + * Value between 0 and 1. The amount through the Tween, excluding loops. + */ + progress: number; + + /** + * Time in ms/frames for the Tween to complete (including looping) + */ + totalDuration: number; + + /** + * Value between 0 and 1. The amount through the entire Tween, including looping. + */ + totalProgress: number; + + /** + * An object containing the different Tween callback functions. + * + * You can either set these in the Tween config, or by calling the `Tween.setCallback` method. + * + * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. + * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. + * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. + * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. + * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. + * `onUpdate` When a TweenData updates a property on a source target during playback. + * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. + */ + callbacks: object; + + /** + * The context in which all callbacks are invoked. + */ + callbackScope: any; + + /** + * Returns the current value of the specified Tween Data. + * @param index The Tween Data to return the value from. Default 0. + */ + getValue(index?: integer): number; + + /** + * Set the scale the time applied to this Tween. A value of 1 runs in real-time. A value of 0.5 runs 50% slower, and so on. + * @param value The scale factor for timescale. + */ + setTimeScale(value: number): this; + + /** + * Returns the scale of the time applied to this Tween. + */ + getTimeScale(): number; + + /** + * Checks if the Tween is currently active. + */ + isPlaying(): boolean; + + /** + * Checks if the Tween is currently paused. + */ + isPaused(): boolean; + + /** + * See if this Tween is currently acting upon the given target. + * @param target The target to check against this Tween. + */ + hasTarget(target: object): boolean; + + /** + * Updates the 'end' value of the given property across all matching targets. + * + * Calling this does not adjust the duration of the tween, or the current progress. + * + * You can optionally tell it to set the 'start' value to be the current value (before the change). + * @param key The property to set the new value for. + * @param value The new value of the property. + * @param startToCurrent Should this change set the start value to be the current value? Default false. + */ + updateTo(key: string, value: any, startToCurrent?: boolean): this; + + /** + * Restarts the tween from the beginning. + */ + restart(): this; + + /** + * Internal method that calculates the overall duration of the Tween. + */ + calcDuration(): void; + + /** + * Called by TweenManager.preUpdate as part of its loop to check pending and active tweens. + * Should not be called directly. + */ + init(): boolean; + + /** + * Internal method that makes this Tween active within the TweenManager + * and emits the onActive event and callback. + */ + makeActive(): void; + + /** + * Internal method that advances to the next state of the Tween during playback. + */ + nextState(): void; + + /** + * Pauses the Tween immediately. Use `resume` to continue playback. + */ + pause(): this; + + /** + * Starts a Tween playing. + * + * You only need to call this method if you have configured the tween to be paused on creation. + * + * If the Tween is already playing, calling this method again will have no effect. If you wish to + * restart the Tween, use `Tween.restart` instead. + * + * Calling this method after the Tween has completed will start the Tween playing again from the start. + * This is the same as calling `Tween.seek(0)` and then `Tween.play()`. + * @param resetFromTimeline Is this Tween being played as part of a Timeline? Default false. + */ + play(resetFromTimeline?: boolean): this; + + /** + * Internal method that resets all of the Tween Data, including the progress and elapsed values. + * @param resetFromLoop Has this method been called as part of a loop? + */ + resetTweenData(resetFromLoop: boolean): void; + + /** + * Resumes the playback of a previously paused Tween. + */ + resume(): this; + + /** + * Seeks to a specific point in the Tween. + * + * **Note:** You cannot seek a Tween that repeats or loops forever, or that has an unusually long total duration. + * + * The given position is a value between 0 and 1 which represents how far through the Tween to seek to. + * A value of 0.5 would seek to half-way through the Tween, where-as a value of zero would seek to the start. + * + * Note that the seek 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 0.5 would seek to 3 seconds into the Tween, as that's half-way through its _entire_ duration. + * + * 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. + * @param toPosition A value between 0 and 1 which represents the progress point to seek to. + * @param delta The size of each step when seeking through the Tween. A higher value completes faster but at a cost of less precision. Default 16.6. + */ + seek(toPosition: number, delta?: number): this; + + /** + * Sets an event based callback to be invoked during playback. + * + * Calling this method will replace a previously set callback for the given type, if any exists. + * + * The types available are: + * + * `onActive` When the Tween is moved from the pending to the active list in the Tween Manager, even if playback paused. + * `onStart` When the Tween starts playing after a delayed state. Will happen at the same time as `onActive` if it has no delay. + * `onYoyo` When a TweenData starts a yoyo. This happens _after_ the `hold` delay expires, if set. + * `onRepeat` When a TweenData repeats playback. This happens _after_ the `repeatDelay` expires, if set. + * `onComplete` When the Tween finishes playback fully or `Tween.stop` is called. Never invoked if tween is set to repeat infinitely. + * `onUpdate` When a TweenData updates a property on a source target during playback. + * `onLoop` When a Tween loops. This happens _after_ the `loopDelay` expires, if set. + * @param type Type of the callback to set. + * @param callback The function to invoke when this callback happens. + * @param params An array of parameters for specified callbacks types. + * @param scope The context the callback will be invoked in. + */ + setCallback(type: string, callback: Function, params?: any[], scope?: any): this; + + /** + * Flags the Tween as being complete, whatever stage of progress it is at. + * + * If an onComplete callback has been defined it will automatically invoke it, unless a `delay` + * argument is provided, in which case the Tween will delay for that period of time before calling the callback. + * + * If you don't need a delay, or have an onComplete callback, then call `Tween.stop` instead. + * @param delay The time to wait before invoking the complete callback. If zero it will fire immediately. Default 0. + */ + complete(delay?: number): this; + + /** + * Immediately removes this Tween from the TweenManager and all of its internal arrays, + * no matter what stage it as it. Then sets the tween state to `REMOVED`. + * + * You should dispose of your reference to this tween after calling this method, to + * free it from memory. + */ + remove(): this; + + /** + * Stops the Tween immediately, whatever stage of progress it is at and flags it for removal by the TweenManager. + * @param resetTo If you want to seek the tween, provide a value between 0 and 1. + */ + stop(resetTo?: number): this; + + /** + * Internal method that advances the Tween based on the time values. + * @param timestamp The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(timestamp: number, delta: number): boolean; + + /** + * Internal method that will emit a TweenData based Event and invoke the given callback. + * @param event The Event to be dispatched. + * @param callback The callback to be invoked. Can be `null` or `undefined` to skip invocation. + * @param tweenData The TweenData object that caused this event. + */ + dispatchTweenDataEvent(event: Phaser.Types.Tweens.Event, callback: Function, tweenData: Phaser.Types.Tweens.TweenDataConfig): void; + + /** + * Internal method that will emit a Tween based Event and invoke the given callback. + * @param event The Event to be dispatched. + * @param callback The callback to be invoked. Can be `null` or `undefined` to skip invocation. + */ + dispatchTweenEvent(event: Phaser.Types.Tweens.Event, callback: Function): void; + + /** + * Internal method used as part of the playback process that sets a tween to play in reverse. + * @param tween The Tween to update. + * @param tweenData The TweenData property to update. + * @param diff Any extra time that needs to be accounted for in the elapsed and progress values. + */ + setStateFromEnd(tween: Phaser.Tweens.Tween, tweenData: Phaser.Types.Tweens.TweenDataConfig, diff: number): integer; + + /** + * Internal method used as part of the playback process that sets a tween to play from the start. + * @param tween The Tween to update. + * @param tweenData The TweenData property to update. + * @param diff Any extra time that needs to be accounted for in the elapsed and progress values. + */ + setStateFromStart(tween: Phaser.Tweens.Tween, tweenData: Phaser.Types.Tweens.TweenDataConfig, diff: number): integer; + + /** + * Internal method that advances the TweenData based on the time value given. + * @param tween The Tween to update. + * @param tweenData The TweenData property to update. + * @param delta Either a value in ms, or 1 if Tween.useFrames is true. + */ + updateTweenData(tween: Phaser.Tweens.Tween, tweenData: Phaser.Types.Tweens.TweenDataConfig, delta: number): boolean; + + } + + /** + * Returns a TweenDataConfig object that describes the tween data for a unique property of a unique target. + * A single Tween consists of multiple TweenDatas, depending on how many properties are being changed by the Tween. + * + * This is an internal function used by the TweenBuilder and should not be accessed directly, instead, + * Tweens should be created using the GameObjectFactory or GameObjectCreator. + * @param target The target to tween. + * @param index The target index within the Tween targets array. + * @param key The property of the target to tween. + * @param getEnd What the property will be at the END of the Tween. + * @param getStart What the property will be at the START of the Tween. + * @param getActive If not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property. + * @param ease The ease function this tween uses. + * @param delay Time in ms/frames before tween will start. + * @param duration Duration of the tween in ms/frames. + * @param yoyo Determines whether the tween should return back to its start value after hold has expired. + * @param hold Time in ms/frames the tween will pause before repeating or returning to its starting value if yoyo is set to true. + * @param repeat Number of times to repeat the tween. The tween will always run once regardless, so a repeat value of '1' will play the tween twice. + * @param repeatDelay Time in ms/frames before the repeat will start. + * @param flipX Should toggleFlipX be called when yoyo or repeat happens? + * @param flipY Should toggleFlipY be called when yoyo or repeat happens? + */ + function TweenData(target: any, index: integer, key: string, getEnd: Function, getStart: Function, getActive: Function, ease: Function, delay: number, duration: number, yoyo: boolean, hold: number, repeat: number, repeatDelay: number, flipX: boolean, flipY: boolean): Phaser.Types.Tweens.TweenDataConfig; + + /** + * The Tween Manager is a default Scene Plugin which controls and updates Tweens and Timelines. + */ + class TweenManager { + /** + * + * @param scene The Scene which owns this Tween Manager. + */ + constructor(scene: Phaser.Scene); + + /** + * The Scene which owns this Tween Manager. + */ + scene: Phaser.Scene; + + /** + * The Systems object of the Scene which owns this Tween Manager. + */ + systems: Phaser.Scenes.Systems; + + /** + * The time scale of the Tween Manager. + * + * This value scales the time delta between two frames, thus influencing the speed of time for all Tweens owned by this Tween Manager. + */ + timeScale: number; + + /** + * Create a Tween Timeline and return it, but do NOT add it to the active or pending Tween lists. + * @param config The configuration object for the Timeline and its Tweens. + */ + createTimeline(config?: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Timeline; + + /** + * Create a Tween Timeline and add it to the active Tween list/ + * @param config The configuration object for the Timeline and its Tweens. + */ + timeline(config?: Phaser.Types.Tweens.TimelineBuilderConfig): Phaser.Tweens.Timeline; + + /** + * Create a Tween and return it, but do NOT add it to the active or pending Tween lists. + * @param config The configuration object for the Tween. + */ + create(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; + + /** + * Create a Tween and add it to the active Tween list. + * @param config The configuration object for the Tween. + */ + add(config: Phaser.Types.Tweens.TweenBuilderConfig | object): Phaser.Tweens.Tween; + + /** + * Add an existing tween into the active Tween list. + * @param tween The Tween to add. + */ + existing(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; + + /** + * Create a Number Tween and add it to the active Tween list. + * @param config The configuration object for the Number Tween. + */ + addCounter(config: Phaser.Types.Tweens.NumberTweenBuilderConfig): Phaser.Tweens.Tween; + + /** + * 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' }) + * }); + * ``` + * @param value The amount to stagger by, or an array containing two elements representing the min and max values to stagger between. + * @param config The configuration object for the Stagger function. + */ + stagger(value: number | number[], config: Phaser.Types.Tweens.StaggerConfig): Function; + + /** + * Updates the Tween Manager's internal lists at the start of the frame. + * + * This method will return immediately if no changes have been indicated. + */ + preUpdate(): void; + + /** + * Updates all Tweens and Timelines of the Tween Manager. + * @param timestamp The current time in milliseconds. + * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. + */ + update(timestamp: number, delta: number): void; + + /** + * Removes the given tween from the Tween Manager, regardless of its state (pending or active). + * @param tween The Tween to be removed. + */ + remove(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; + + /** + * Checks if a Tween or Timeline is active and adds it to the Tween Manager at the start of the frame if it isn't. + * @param tween The Tween to check. + */ + makeActive(tween: Phaser.Tweens.Tween): Phaser.Tweens.TweenManager; + + /** + * Passes all Tweens to the given callback. + * @param callback The function to call. + * @param scope The scope (`this` object) to call the function with. + * @param args The arguments to pass into the function. Its first argument will always be the Tween currently being iterated. + */ + each(callback: Function, scope?: object, ...args: any[]): void; + + /** + * Returns an array of all active Tweens and Timelines in the Tween Manager. + */ + getAllTweens(): Phaser.Tweens.Tween[]; + + /** + * Returns the scale of the time delta for all Tweens and Timelines owned by this Tween Manager. + */ + getGlobalTimeScale(): number; + + /** + * Returns an array of all Tweens or Timelines in the Tween Manager which affect the given target or array of targets. + * @param target The target to look for. Provide an array to look for multiple targets. + */ + getTweensOf(target: object | any[]): Phaser.Tweens.Tween[]; + + /** + * Checks if the given object is being affected by a playing Tween. + * @param target target Phaser.Tweens.Tween object + */ + isTweening(target: object): boolean; + + /** + * Stops all Tweens in this Tween Manager. They will be removed at the start of the frame. + */ + killAll(): Phaser.Tweens.TweenManager; + + /** + * Stops all Tweens which affect the given target or array of targets. The Tweens will be removed from the Tween Manager at the start of the frame. + * @param target The target to look for. Provide an array to look for multiple targets. + */ + killTweensOf(target: object | any[]): Phaser.Tweens.TweenManager; + + /** + * Pauses all Tweens in this Tween Manager. + */ + pauseAll(): Phaser.Tweens.TweenManager; + + /** + * Resumes all Tweens in this Tween Manager. + */ + resumeAll(): Phaser.Tweens.TweenManager; + + /** + * Sets a new scale of the time delta for this Tween Manager. + * + * The time delta is the time elapsed between two consecutive frames and influences the speed of time for this Tween Manager and all Tweens it owns. Values higher than 1 increase the speed of time, while values smaller than 1 decrease it. A value of 0 freezes time and is effectively equivalent to pausing all Tweens. + * @param value The new scale of the time delta, where 1 is the normal speed. + */ + setGlobalTimeScale(value: number): Phaser.Tweens.TweenManager; + + /** + * The Scene that owns this plugin is shutting down. + * We need to kill and reset all internal properties as well as stop listening to Scene events. + */ + shutdown(): void; + + /** + * The Scene that owns this plugin is being destroyed. + * We need to shutdown and then kill off all external references. + */ + destroy(): void; + + } + + } + + namespace Utils { + namespace Array { + /** + * Adds the given item, or array of items, to the array. + * + * Each item must be unique within the array. + * + * The array is modified in-place and returned. + * + * You can optionally specify a limit to the maximum size of the array. If the quantity of items being + * added will take the array length over this limit, it will stop adding once the limit is reached. + * + * You can optionally specify a callback to be invoked for each item successfully added to the array. + * @param array The array to be added to. + * @param item The item, or array of items, to add to the array. Each item must be unique within the array. + * @param limit Optional limit which caps the size of the array. + * @param callback A callback to be invoked for each item successfully added to the array. + * @param context The context in which the callback is invoked. + */ + function Add(array: any[], item: any | any[], limit?: integer, callback?: Function, context?: object): any[]; + + /** + * Adds the given item, or array of items, to the array starting at the index specified. + * + * Each item must be unique within the array. + * + * Existing elements in the array are shifted up. + * + * The array is modified in-place and returned. + * + * You can optionally specify a limit to the maximum size of the array. If the quantity of items being + * added will take the array length over this limit, it will stop adding once the limit is reached. + * + * You can optionally specify a callback to be invoked for each item successfully added to the array. + * @param array The array to be added to. + * @param item The item, or array of items, to add to the array. + * @param index The index in the array where the item will be inserted. Default 0. + * @param limit Optional limit which caps the size of the array. + * @param callback A callback to be invoked for each item successfully added to the array. + * @param context The context in which the callback is invoked. + */ + function AddAt(array: any[], item: any | any[], index?: integer, limit?: integer, callback?: Function, context?: object): any[]; + + /** + * Moves the given element to the top of the array. + * The array is modified in-place. + * @param array The array. + * @param item The element to move. + */ + function BringToTop(array: any[], item: any): any; + + /** + * Returns the total number of elements in the array which have a property matching the given value. + * @param array The array to search. + * @param 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 startIndex An optional start index to search from. + * @param endIndex An optional end index to search to. + */ + function CountAllMatching(array: any[], property: string, value: any, startIndex?: integer, endIndex?: integer): integer; + + /** + * Passes each element in the array to the given callback. + * @param array The array to search. + * @param callback A callback to be invoked for each item in the array. + * @param context The context in which the callback is invoked. + * @param args Additional arguments that will be passed to the callback, after the current array item. + */ + function Each(array: any[], callback: Function, context: object, ...args: any[]): any[]; + + /** + * Passes each element in the array, between the start and end indexes, to the given callback. + * @param array The array to search. + * @param callback A callback to be invoked for each item in the array. + * @param context The context in which the callback is invoked. + * @param startIndex The start index to search from. + * @param endIndex The end index to search to. + * @param args Additional arguments that will be passed to the callback, after the child. + */ + function EachInRange(array: any[], callback: Function, context: object, startIndex: integer, endIndex: integer, ...args: any[]): any[]; + + /** + * Searches a pre-sorted array for the closet value to the given number. + * + * If the `key` argument is given it will assume the array contains objects that all have the required `key` property name, + * and will check for the closest value of those to the given number. + * @param value The value to search for in the array. + * @param array The array to search, which must be sorted. + * @param key An optional property key. If specified the array elements property will be checked against value. + */ + function FindClosestInSorted(value: number, array: any[], key?: string): number | any; + + /** + * Returns all elements in the array. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('visible', true)` would return only elements that have their visible property set. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only + * the first 50 elements. + * @param array The array to search. + * @param 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 startIndex An optional start index to search from. + * @param endIndex An optional end index to search to. + */ + function GetAll(array: any[], property?: string, value?: any, startIndex?: integer, endIndex?: integer): any[]; + + /** + * Returns the first element in the array. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('visible', true)` would return the first element that had its `visible` property set. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would search only the first 50 elements. + * @param array The array to search. + * @param 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 startIndex An optional start index to search from. Default 0. + * @param endIndex An optional end index to search up to (but not included) Default array.length. + */ + function GetFirst(array: any[], property?: string, value?: any, startIndex?: integer, endIndex?: integer): object; + + /** + * Returns a Random element from the array. + * @param array The array to select the random entry from. + * @param startIndex An optional start index. Default 0. + * @param length An optional length, the total number of elements (from the startIndex) to choose from. Default array.length. + */ + function GetRandom(array: any[], startIndex?: integer, length?: integer): any; + + namespace Matrix { + /** + * Checks if an array can be used as a matrix. + * + * 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: + * + * ``` + * [ + * [ 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 ] + * ] + * ``` + * @param matrix The array to check. + */ + function CheckMatrix(matrix?: T[][]): boolean; + + /** + * Generates a string (which you can pass to console.log) from the given Array Matrix. + * @param matrix A 2-dimensional array. + */ + function MatrixToString(matrix?: T[][]): string; + + /** + * Reverses the columns in the given Array Matrix. + * @param matrix The array matrix to reverse the columns for. + */ + function ReverseColumns(matrix?: T[][]): T[][]; + + /** + * Reverses the rows in the given Array Matrix. + * @param matrix The array matrix to reverse the rows for. + */ + function ReverseRows(matrix?: T[][]): T[][]; + + /** + * Rotates the array matrix 180 degrees. + * @param matrix The array to rotate. + */ + function Rotate180(matrix?: T[][]): T[][]; + + /** + * Rotates the array matrix to the left (or 90 degrees) + * @param matrix The array to rotate. + */ + function RotateLeft(matrix?: T[][]): T[][]; + + /** + * Rotates the array matrix based on the given rotation value. + * + * The value can be given in degrees: 90, -90, 270, -270 or 180, + * or a string command: `rotateLeft`, `rotateRight` or `rotate180`. + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * @param matrix The array to rotate. + * @param direction The amount to rotate the matrix by. Default 90. + */ + function RotateMatrix(matrix?: T[][], direction?: number | string): T[][]; + + /** + * Rotates the array matrix to the left (or -90 degrees) + * @param matrix The array to rotate. + */ + function RotateRight(matrix?: T[][]): T[][]; + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * The transpose of a matrix is a new matrix whose rows are the columns of the original. + * @param array The array matrix to transpose. + */ + function TransposeMatrix(array?: T[][]): T[][]; + + } + + /** + * Moves the given array element down one place in the array. + * The array is modified in-place. + * @param array The input array. + * @param item The element to move down the array. + */ + function MoveDown(array: any[], item: any): any[]; + + /** + * Moves an element in an array to a new position within the same array. + * The array is modified in-place. + * @param array The array. + * @param item The element to move. + * @param index The new index that the element will be moved to. + */ + function MoveTo(array: any[], item: any, index: integer): any; + + /** + * Moves the given array element up one place in the array. + * The array is modified in-place. + * @param array The input array. + * @param item The element to move up the array. + */ + function MoveUp(array: any[], item: any): any[]; + + /** + * Create an array representing the range of numbers (usually integers), between, and inclusive of, + * the given `start` and `end` arguments. For example: + * + * `var array = numberArray(2, 4); // array = [2, 3, 4]` + * `var array = numberArray(0, 9); // array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` + * + * This is equivalent to `numberArrayStep(start, end, 1)`. + * + * You can optionally provide a prefix and / or suffix string. If given the array will contain + * strings, not integers. For example: + * + * `var array = numberArray(1, 4, 'Level '); // array = ["Level 1", "Level 2", "Level 3", "Level 4"]` + * `var array = numberArray(5, 7, 'HD-', '.png'); // array = ["HD-5.png", "HD-6.png", "HD-7.png"]` + * @param start The minimum value the array starts with. + * @param end The maximum value the array contains. + * @param prefix Optional prefix to place before the number. If provided the array will contain strings, not integers. + * @param suffix Optional suffix to place after the number. If provided the array will contain strings, not integers. + */ + function NumberArray(start: number, end: number, prefix?: string, suffix?: string): number[] | string[]; + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * @param start The start of the range. Default 0. + * @param end The end of the range. Default null. + * @param step The value to increment or decrement by. Default 1. + */ + function NumberArrayStep(start?: number, end?: number, step?: number): number[]; + + /** + * 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) + * @param arr The array to sort. + * @param k The k-th element index. + * @param left The index of the left part of the range. Default 0. + * @param right The index of the right part of the range. + * @param compare An optional comparison function. Is passed two elements and should return 0, 1 or -1. + */ + function QuickSelect(arr: any[], k: integer, left?: integer, right?: integer, compare?: Function): void; + + /** + * 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) = + * Maybe if max is set then repeat goes to -1 automatically? + * 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 + * @param a The first array of range elements. + * @param b The second array of range elements. + * @param options A range configuration object. Can contain: repeat, random, randomB, yoyo, max, qty. + */ + function Range(a: any[], b: any[], options?: object): any[]; + + /** + * Removes the given item, or array of items, from the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for each item successfully removed from the array. + * @param array The array to be modified. + * @param item The item, or array of items, to be removed from the array. + * @param callback A callback to be invoked for each item successfully removed from the array. + * @param context The context in which the callback is invoked. + */ + function Remove(array: any[], item: any | any[], callback?: Function, context?: object): any | any[]; + + /** + * Removes the item from the given position in the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for the item if it is successfully removed from the array. + * @param array The array to be modified. + * @param index The array index to remove the item from. The index must be in bounds or it will throw an error. + * @param callback A callback to be invoked for the item removed from the array. + * @param context The context in which the callback is invoked. + */ + function RemoveAt(array: any[], index: integer, callback?: Function, context?: object): any; + + /** + * Removes the item within the given range in the array. + * + * The array is modified in-place. + * + * You can optionally specify a callback to be invoked for the item/s successfully removed from the array. + * @param array The array to be modified. + * @param startIndex The start index to remove from. + * @param endIndex The end index to remove to. + * @param callback A callback to be invoked for the item removed from the array. + * @param context The context in which the callback is invoked. + */ + function RemoveBetween(array: any[], startIndex: integer, endIndex: integer, callback?: Function, context?: object): any[]; + + /** + * Removes a random object from the given array and returns it. + * Will return null if there are no array items that fall within the specified range or if there is no item for the randomly chosen index. + * @param array The array to removed a random element from. + * @param start The array index to start the search from. Default 0. + * @param length Optional restriction on the number of elements to randomly select from. Default array.length. + */ + function RemoveRandomElement(array: any[], start?: integer, length?: integer): object; + + /** + * Replaces an element of the array with the new element. + * The new element cannot already be a member of the array. + * The array is modified in-place. + * @param array The array to search within. + * @param oldChild The element in the array that will be replaced. + * @param newChild The element to be inserted into the array at the position of `oldChild`. + */ + function Replace(array: any[], oldChild: any, newChild: any): boolean; + + /** + * Moves the element at the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * @param array The array to shift to the left. This array is modified in place. + * @param total The number of times to shift the array. Default 1. + */ + function RotateLeft(array: any[], total?: integer): any; + + /** + * Moves the element at the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * @param array The array to shift to the right. This array is modified in place. + * @param total The number of times to shift the array. Default 1. + */ + function RotateRight(array: any[], total?: integer): any; + + /** + * Tests if the start and end indexes are a safe range for the given array. + * @param array The array to check. + * @param startIndex The start index. + * @param endIndex The end index. + * @param throwError Throw an error if the range is out of bounds. Default true. + */ + function SafeRange(array: any[], startIndex: integer, endIndex: integer, throwError?: boolean): boolean; + + /** + * Moves the given element to the bottom of the array. + * The array is modified in-place. + * @param array The array. + * @param item The element to move. + */ + function SendToBack(array: any[], item: any): any; + + /** + * Scans the array for elements with the given property. If found, the property is set to the `value`. + * + * For example: `SetAll('visible', true)` would set all elements that have a `visible` property to `false`. + * + * Optionally you can specify a start and end index. For example if the array had 100 elements, + * and you set `startIndex` to 0 and `endIndex` to 50, it would update only the first 50 elements. + * @param array The array to search. + * @param property The property to test for on each array element. + * @param value The value to set the property to. + * @param startIndex An optional start index to search from. + * @param endIndex An optional end index to search to. + */ + function SetAll(array: any[], property: string, value: any, startIndex?: integer, endIndex?: integer): any[]; + + /** + * Shuffles the contents of the given array using the Fisher-Yates implementation. + * + * The original array is modified directly and returned. + * @param array The array to shuffle. This array is modified in place. + */ + function Shuffle(array: T[]): T[]; + + /** + * Removes a single item from an array and returns it without creating gc, like the native splice does. + * Based on code by Mike Reinstein. + * @param array The array to splice from. + * @param index The index of the item which should be spliced. + */ + function SpliceOne(array: any[], index: integer): any; + + namespace StableSortFunctions { + /** + * Sort the input array and simply copy it back if the result isn't in the original array, which happens on an odd number of passes. + * @param arr The input array. + * @param comp The comparison handler. + */ + function inplace(arr: any[], comp: Function): any[]; + + } + + /** + * A stable array sort, because `Array#sort()` is not guaranteed stable. + * This is an implementation of merge sort, without recursion. + * @param arr The input array to be sorted. + * @param comp The comparison handler. + */ + function StableSort(arr: any[], comp: Function): any[]; + + /** + * Swaps the position of two elements in the given array. + * The elements must exist in the same array. + * The array is modified in-place. + * @param array The input array. + * @param item1 The first element to swap. + * @param item2 The second element to swap. + */ + function Swap(array: any[], item1: any, item2: any): any[]; + + } + + namespace Base64 { + /** + * 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. + * @param arrayBuffer The Array Buffer to encode. + * @param mediaType An optional media type, i.e. `audio/ogg` or `image/jpeg`. If included the resulting string will be a data URI. + */ + function ArrayBufferToBase64(arrayBuffer: ArrayBuffer, mediaType?: string): string; + + /** + * Converts a base64 string, either with or without a data uri, into an Array Buffer. + * @param base64 The base64 string to be decoded. Can optionally contain a data URI header, which will be stripped out prior to decoding. + */ + function Base64ToArrayBuffer(base64: string): ArrayBuffer; + + } + + /** + * A NOOP (No Operation) callback function. + * + * Used internally by Phaser when it's more expensive to determine if a callback exists + * than it is to just invoke an empty function. + */ + function NOOP(): void; + + namespace Objects { + /** + * Shallow Object Clone. Will not clone nested objects. + * @param obj the object from which to clone + */ + function Clone(obj: object): object; + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + */ + function Extend(): object; + + /** + * Retrieves a value from an object. Allows for more advanced selection options, including: + * + * Allowed types: + * + * Implicit + * { + * x: 4 + * } + * + * From function + * { + * x: function () + * } + * + * Randomly pick one element from the array + * { + * x: [a, b, c, d, e, f] + * } + * + * Random integer between min and max: + * { + * x: { randInt: [min, max] } + * } + * + * Random float between min and max: + * { + * x: { randFloat: [min, max] } + * } + * @param source The object to retrieve the value from. + * @param 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. + */ + function GetAdvancedValue(source: object, key: string, defaultValue: any): any; + + /** + * Finds the key within the top level of the {@link source} object, or returns {@link defaultValue} + * @param source The object to search + * @param key The key for the property on source. Must exist at the top level of the source object (no periods) + * @param defaultValue The default value to use if the key does not exist. + */ + function GetFastValue(source: object, key: string, defaultValue?: any): any; + + /** + * Retrieves and clamps a numerical value from an object. + * @param source The object to retrieve the value from. + * @param 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 (`.`). + * @param min The minimum value which can be returned. + * @param max The maximum value which can be returned. + * @param defaultValue The value to return if the property doesn't exist. It's also constrained to the given bounds. + */ + function GetMinMaxValue(source: object, key: string, min: number, max: number, defaultValue: number): number; + + /** + * Retrieves a value from an object. + * @param source The object to retrieve the value from. + * @param 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. + */ + function GetValue(source: object, key: string, defaultValue: any): any; + + /** + * Verifies that an object contains all requested keys + * @param source an object on which to check for key existence + * @param keys an array of keys to ensure the source object contains + */ + function HasAll(source: object, keys: string[]): boolean; + + /** + * Verifies that an object contains at least one of the requested keys + * @param source an object on which to check for key existence + * @param keys an array of keys to search the object for + */ + function HasAny(source: object, keys: string[]): boolean; + + /** + * Determine whether the source object has a property with the specified key. + * @param source The source object to be checked. + * @param key The property to check for within the object + */ + function HasValue(source: object, key: string): boolean; + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @param obj The object to inspect. + */ + function IsPlainObject(obj: object): boolean; + + /** + * Creates a new Object using all values from obj1 and obj2. + * If a value exists in both obj1 and obj2, the value in obj1 is used. + * + * This is only a shallow copy. Deeply nested objects are not cloned, so be sure to only use this + * function on shallow objects. + * @param obj1 The first object. + * @param obj2 The second object. + */ + function Merge(obj1: object, obj2: object): object; + + /** + * Creates a new Object using all values from obj1. + * + * Then scans obj2. If a property is found in obj2 that *also* exists in obj1, the value from obj2 is used, otherwise the property is skipped. + * @param obj1 The first object to merge. + * @param obj2 The second object to merge. Keys from this object which also exist in `obj1` will be copied to `obj1`. + */ + function MergeRight(obj1: object, obj2: object): object; + + /** + * Returns a new object that only contains the `keys` that were found on the object provided. + * If no `keys` are found, an empty object is returned. + * @param object The object to pick the provided keys from. + * @param keys An array of properties to retrieve from the provided object. + */ + function Pick(object: object, keys: any[]): object; + + /** + * Sets a value in an object, allowing for dot notation to control the depth of the property. + * + * For example: + * + * ```javascript + * var data = { + * world: { + * position: { + * x: 200, + * y: 100 + * } + * } + * }; + * + * SetValue(data, 'world.position.y', 300); + * + * console.log(data.world.position.y); // 300 + * ``` + * @param source The object to set the value in. + * @param key The name of the property in the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) + * @param value The value to set into the property, if found in the source object. + */ + function SetValue(source: object, key: string, value: any): boolean; + + } + + namespace String { + /** + * Takes a string and replaces instances of markers with values in the given array. + * The markers take the form of `%1`, `%2`, etc. I.e.: + * + * `Format("The %1 is worth %2 gold", [ 'Sword', 500 ])` + * @param string The string containing the replacement markers. + * @param values An array containing values that will replace the markers. If no value exists an empty string is inserted instead. + */ + function Format(string: string, values: any[]): string; + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * @param str The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param len The number of characters to be added. Default 0. + * @param pad The string to pad it out with (defaults to a space). Default " ". + * @param dir The direction dir = 1 (left), 2 (right), 3 (both). Default 3. + */ + function Pad(str: string, len?: integer, pad?: string, dir?: integer): string; + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * @param string The string to be reversed. + */ + function Reverse(string: string): string; + + /** + * Capitalizes the first letter of a string if there is one. + * @param str The string to capitalize. + */ + function UppercaseFirst(str: string): string; + + /** + * Creates and returns an RFC4122 version 4 compliant UUID. + * + * The string is in the form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` where each `x` is replaced with a random + * hexadecimal digit from 0 to f, and `y` is replaced with a random hexadecimal digit from 8 to b. + */ + function UUID(): string; + + } + + } + + /** + * The Facebook Instant Games Plugin for Phaser 3 provides a seamless bridge between Phaser + * and the Facebook Instant Games API version 6.2. + * + * You can access this plugin via the `facebook` property in a Scene, i.e: + * + * ```javascript + * this.facebook.getPlatform(); + * ``` + * + * If this is unavailable please check to make sure you're using a build of Phaser that has + * this plugin within it. You can quickly check this by looking at the dev tools console + * header - the Phaser version number will have `-FB` after it if this plugin is loaded. + * + * If you are building your own version of Phaser then use this Webpack DefinePlugin flag: + * + * `"typeof PLUGIN_FBINSTANT": JSON.stringify(true)` + * + * You will find that every Instant Games API method has a mapping in this plugin. + * For a full list please consult either the plugin documentation, or the 6.2 SDK documentation + * at https://developers.facebook.com/docs/games/instant-games/sdk/fbinstant6.2 + * + * Internally this plugin uses its own Data Manager to handle seamless user data updates and provides + * handy functions for advertisement displaying, opening share dialogs, logging, leaderboards, purchase API requests, + * loader integration and more. + * + * To get started with Facebook Instant Games you will need to register on Facebook and create a new Instant + * Game app that has its own unique app ID. Facebook have also provided a dashboard interface for setting up + * various features for your game, including leaderboards, ad requests and the payments API. There are lots + * of guides on the Facebook Developers portal to assist with setting these + * various systems up: https://developers.facebook.com/docs/games/instant-games/guides + * + * For more details follow the Quick Start guide here: https://developers.facebook.com/docs/games/instant-games + */ + class FacebookInstantGamesPlugin extends Phaser.Events.EventEmitter { + /** + * + * @param game A reference to the Phaser.Game instance. + */ + constructor(game: Phaser.Game); + + /** + * A reference to the Phaser.Game instance. + */ + readonly game: Phaser.Game; + + /** + * A Data Manager instance. + * It allows you to store, query and retrieve any key/value data you may need to store. + * It's also used internally by the plugin to store FBIG API data. + */ + data: Phaser.Data.DataManager; + + /** + * Has the Facebook Instant Games API loaded yet? + * This is set automatically during the boot process. + */ + hasLoaded: boolean; + + /** + * Is the Data Manager currently locked? + */ + dataLocked: boolean; + + /** + * A list of the Facebook Instant Games APIs that are available, + * based on the given platform, context and user privacy settings. + * This value is populated automatically during boot. + */ + supportedAPIs: string[]; + + /** + * Holds the entry point that the game was launched from. + * This value is populated automatically during boot. + */ + entryPoint: string; + + /** + * An object that contains any data associated with the entry point that the game was launched from. + * The contents of the object are developer-defined, and can occur from entry points on different platforms. + * This will return null for older mobile clients, as well as when there is no data associated with the particular entry point. + * This value is populated automatically during boot. + */ + entryPointData: any; + + /** + * A unique identifier for the current game context. This represents a specific context + * that the game is being played in (for example, a particular messenger conversation or facebook post). + * The identifier will be null if game is being played in a solo context. + * This value is populated automatically during boot. + */ + contextID: string; + + /** + * The current context in which your game is running. This can be either `null` or + * one of: + * + * `POST` - The game is running inside of a Facebook post. + * `THREAD` - The game is running inside a Facebook Messenger thread. + * `GROUP` - The game is running inside a Facebook Group. + * `SOLO` - This is the default context, the player is the only participant. + * + * This value is populated automatically during boot. + */ + contextType: string; + + /** + * The current locale. + * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. + * Use this to determine what languages the current game should be localized with. + * This value is populated automatically during boot. + */ + locale: string; + + /** + * The platform on which the game is currently running, i.e. `IOS`. + * This value is populated automatically during boot. + */ + platform: string; + + /** + * The string representation of the Facebook Instant Games SDK version being used. + * This value is populated automatically during boot. + */ + version: string; + + /** + * Holds the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. + * This value is populated automatically during boot if the API is supported. + */ + playerID: string; + + /** + * The player's localized display name. + * This value is populated automatically during boot if the API is supported. + */ + playerName: string; + + /** + * A url to the player's public profile photo. The photo will always be a square, and with dimensions + * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. + * It's recommended to always scale the image to a desired size before rendering. + * This value is populated automatically during boot if the API is supported. + */ + playerPhotoURL: string; + + /** + * Whether a player can subscribe to the game bot or not. + */ + playerCanSubscribeBot: boolean; + + /** + * Does the current platform and context allow for use of the payments API? + * Currently this is only available on Facebook.com and Android 6+. + */ + paymentsReady: boolean; + + /** + * The set of products that are registered to the game. + */ + catalog: Product[]; + + /** + * Contains all of the player's unconsumed purchases. + * The game must fetch the current player's purchases as soon as the client indicates that it is ready to perform payments-related operations, + * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. + */ + purchases: Purchase[]; + + /** + * Contains all of the leaderboard data, as populated by the `getLeaderboard()` method. + */ + leaderboards: Phaser.FacebookInstantGamesLeaderboard[]; + + /** + * Contains AdInstance objects, as created by the `preloadAds()` method. + */ + ads: AdInstance[]; + + /** + * Call this method from your `Scene.preload` in order to sync the load progress + * of the Phaser Loader with the Facebook Instant Games loader display, i.e.: + * + * ```javascript + * this.facebook.showLoadProgress(this); + * this.facebook.once('startgame', this.startGame, this); + * ``` + * @param scene The Scene for which you want to show loader progress for. + */ + showLoadProgress(scene: Phaser.Scene): this; + + /** + * This method is called automatically when the game has finished loading, + * if you used the `showLoadProgress` method. If your game doesn't need to + * load any assets, or you're managing the load yourself, then call this + * method directly to start the API running. + * + * When the API has finished starting this plugin will emit a `startgame` event + * which you should listen for. + */ + gameStarted(): void; + + /** + * Checks to see if a given Facebook Instant Games API is available or not. + * @param api The API to check for, i.e. `player.getID`. + */ + checkAPI(api: string): boolean; + + /** + * Returns the unique identifier for the current game context. This represents a specific context + * that the game is being played in (for example, a particular messenger conversation or facebook post). + * The identifier will be null if game is being played in a solo context. + * + * It is only populated if `contextGetID` is in the list of supported APIs. + */ + getID(): string; + + /** + * Returns the current context in which your game is running. This can be either `null` or one of: + * + * `POST` - The game is running inside of a Facebook post. + * `THREAD` - The game is running inside a Facebook Messenger thread. + * `GROUP` - The game is running inside a Facebook Group. + * `SOLO` - This is the default context, the player is the only participant. + * + * It is only populated if `contextGetType` is in the list of supported APIs. + */ + getType(): string; + + /** + * Returns the current locale. + * See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. + * Use this to determine what languages the current game should be localized with. + * It is only populated if `getLocale` is in the list of supported APIs. + */ + getLocale(): string; + + /** + * Returns the platform on which the game is currently running, i.e. `IOS`. + * It is only populated if `getPlatform` is in the list of supported APIs. + */ + getPlatform(): string; + + /** + * Returns the string representation of the Facebook Instant Games SDK version being used. + * It is only populated if `getSDKVersion` is in the list of supported APIs. + */ + getSDKVersion(): string; + + /** + * Returns the id of the player. This is a string based ID, the same as `FBInstant.player.getID()`. + * It is only populated if `playerGetID` is in the list of supported APIs. + */ + getPlayerID(): string; + + /** + * Returns the player's localized display name. + * It is only populated if `playerGetName` is in the list of supported APIs. + */ + getPlayerName(): string; + + /** + * Returns the url to the player's public profile photo. The photo will always be a square, and with dimensions + * of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. + * It's recommended to always scale the image to a desired size before rendering. + * It is only populated if `playerGetPhoto` is in the list of supported APIs. + */ + getPlayerPhotoURL(): string; + + /** + * Load the player's photo and store it in the Texture Manager, ready for use in-game. + * + * This method works by using a Scene Loader instance and then asking the Loader to + * retrieve the image. + * + * When complete the plugin will emit a `photocomplete` event, along with the key of the photo. + * + * ```javascript + * this.facebook.loadPlayerPhoto(this, 'player').once('photocomplete', function (key) { + * this.add.image(x, y, 'player'); + * }, this); + * ``` + * @param scene The Scene that will be responsible for loading this photo. + * @param key The key to use when storing the photo in the Texture Manager. + */ + loadPlayerPhoto(scene: Phaser.Scene, key: string): this; + + /** + * Checks if the current player can subscribe to the game bot. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they can subscribe, the `playerCanSubscribeBot` property is set to `true` + * and this plugin will emit the `cansubscribebot` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `cansubscribebotfail` event instead. + */ + canSubscribeBot(): this; + + /** + * Subscribes the current player to the game bot. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `subscribebot` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `subscribebotfail` event instead. + */ + subscribeBot(): this; + + /** + * Gets the associated data from the player based on the given key, or array of keys. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the data is set into this plugins Data Manager and the + * `getdata` event will be emitted. + * @param keys The key/s of the data to retrieve. + */ + getData(keys: string | string[]): this; + + /** + * Set data to be saved to the designated cloud storage of the current player. The game can store up to 1MB of data for each unique player. + * + * The data save is requested in an async call, so the result isn't available immediately. + * + * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this + * method directly if you need to replace the data object directly. + * + * When the APIs `setDataAsync` call resolves it will emit the `savedata` event from this plugin. If the call fails for some + * reason it will emit `savedatafail` instead. + * + * The call resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was valid and + * has been scheduled to be saved. It also guarantees that all values that were set are now available in `getData`. + * @param data An object containing a set of key-value pairs that should be persisted to cloud storage. + * The object must contain only serializable values - any non-serializable values will cause the entire modification to be rejected. + */ + saveData(data: object): this; + + /** + * Immediately flushes any changes to the player data to the designated cloud storage. + * This function is expensive, and should primarily be used for critical changes where persistence needs to be immediate + * and known by the game. Non-critical changes should rely on the platform to persist them in the background. + * NOTE: Calls to player.setDataAsync will be rejected while this function's result is pending. + * + * Data managed via this plugins Data Manager instance is automatically synced with Facebook. However, you can call this + * method directly if you need to flush the data directly. + * + * When the APIs `flushDataAsync` call resolves it will emit the `flushdata` event from this plugin. If the call fails for some + * reason it will emit `flushdatafail` instead. + */ + flushData(): this; + + /** + * Retrieve stats from the designated cloud storage of the current player. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `getstats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `getstatsfail` event instead. + * @param keys An optional array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats. + */ + getStats(keys?: string[]): this; + + /** + * Save the stats of the current player to the designated cloud storage. + * + * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, + * all other data types will be ignored. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `savestats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `savestatsfail` event instead. + * @param data An object containing a set of key-value pairs that should be persisted to cloud storage as stats. Note that only numerical values are stored. + */ + saveStats(data: object): this; + + /** + * Increment the stats of the current player and save them to the designated cloud storage. + * + * Stats in the Facebook Instant Games API are purely numerical values paired with a string-based key. Only numbers can be saved as stats, + * all other data types will be ignored. + * + * The data object provided for this call should contain offsets for how much to modify the stats by: + * + * ```javascript + * this.facebook.incStats({ + * level: 1, + * zombiesSlain: 17, + * rank: -1 + * }); + * ``` + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `incstats` event will be emitted along with the data object returned. + * + * If the call fails, i.e. it's not in the list of supported APIs, or the request was rejected, + * it will emit a `incstatsfail` event instead. + * @param data An object containing a set of key-value pairs indicating how much to increment each stat in cloud storage. Note that only numerical values are processed. + */ + incStats(data: object): this; + + /** + * Sets the data associated with the individual gameplay session for the current context. + * + * This function should be called whenever the game would like to update the current session data. + * + * This session data may be used to populate a variety of payloads, such as game play webhooks. + * @param data An arbitrary data object, which must be less than or equal to 1000 characters when stringified. + */ + saveSession(data: object): this; + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * @param text A text message to be shared. + * @param key The key of the texture to use as the share image. + * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param sessionData A blob of data to attach to the share. + */ + openShare(text: string, key: string, frame?: string, sessionData?: object): this; + + /** + * This invokes a dialog to let the user invite a friend to play this game, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * @param text A text message to be shared. + * @param key The key of the texture to use as the share image. + * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param sessionData A blob of data to attach to the share. + */ + openInvite(text: string, key: string, frame?: string, sessionData?: object): this; + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * @param text A text message to be shared. + * @param key The key of the texture to use as the share image. + * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param sessionData A blob of data to attach to the share. + */ + openRequest(text: string, key: string, frame?: string, sessionData?: object): this; + + /** + * This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. + * + * A blob of data can be attached to the share which every game session launched from the share will be able to access via the `this.entryPointData` property. + * + * This data must be less than or equal to 1000 characters when stringified. + * + * When this method is called you should consider your game paused. Listen out for the `resume` event from this plugin to know when the dialog has been closed. + * + * The user may choose to cancel the share action and close the dialog. The resulting `resume` event will be dispatched regardless if the user actually shared the content or not. + * @param text A text message to be shared. + * @param key The key of the texture to use as the share image. + * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param sessionData A blob of data to attach to the share. + */ + openChallenge(text: string, key: string, frame?: string, sessionData?: object): this; + + /** + * This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. + * If one of the bounds is null only the other bound will be checked against. + * It will always return the original result for the first call made in a context in a given game play session. + * Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset. + * @param min The minimum bound of the context size query. + * @param max The maximum bound of the context size query. + */ + isSizeBetween(min?: integer, max?: integer): object; + + /** + * Request a switch into a specific context. If the player does not have permission to enter that context, + * or if the player does not provide permission for the game to enter that context, this will emit a `switchfail` event. + * + * Otherwise, the plugin will emit the `switch` event when the game has switched into the specified context. + * @param contextID The ID of the desired context. + */ + switchContext(contextID: string): this; + + /** + * Opens a context selection dialog for the player. If the player selects an available context, + * the client will attempt to switch into that context, and emit the `choose` event if successful. + * Otherwise, if the player exits the menu or the client fails to switch into the new context, the `choosefail` event will be emitted. + * @param options An object specifying conditions on the contexts that should be offered. + */ + chooseContext(options?: ChooseContextConfig): this; + + /** + * Attempts to create or switch into a context between a specified player and the current player. + * This plugin will emit the `create` event once the context switch is completed. + * If the API call fails, such as if the player listed is not a Connected Player of the current player or if the + * player does not provide permission to enter the new context, then the plugin will emit a 'createfail' event. + * @param playerID ID of the player. + */ + createContext(playerID: string): this; + + /** + * Fetches an array of ConnectedPlayer objects containing information about active players + * (people who played the game in the last 90 days) that are connected to the current player. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `players` event along + * with the player data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `playersfail` event instead. + */ + getPlayers(): this; + + /** + * Fetches the game's product catalog. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `getcatalog` event along + * with the catalog data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `getcatalogfail` event instead. + */ + getCatalog(): this; + + /** + * Fetches a single Product from the game's product catalog. + * + * The product catalog must have been populated using `getCatalog` prior to calling this method. + * + * Use this to look-up product details based on a purchase list. + * @param productID The Product ID of the item to get from the catalog. + */ + getProduct(productID: string): Product; + + /** + * Begins the purchase flow for a specific product. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `purchase` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `purchasefail` event instead. + * @param productID The identifier of the product to purchase. + * @param developerPayload An optional developer-specified payload, to be included in the returned purchase's signed request. + */ + purchase(productID: string, developerPayload?: string): this; + + /** + * Fetches all of the player's unconsumed purchases. The game must fetch the current player's purchases + * as soon as the client indicates that it is ready to perform payments-related operations, + * i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `getpurchases` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `getpurchasesfail` event instead. + */ + getPurchases(): this; + + /** + * Consumes a specific purchase belonging to the current player. Before provisioning a product's effects to the player, + * the game should request the consumption of the purchased product. Once the purchase is successfully consumed, + * the game should immediately provide the player with the effects of their purchase. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If they are successfully subscribed this plugin will emit the `consumepurchase` event along + * with the purchase data. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `consumepurchasefail` event instead. + * @param purchaseToken The purchase token of the purchase that should be consumed. + */ + consumePurchase(purchaseToken: string): this; + + /** + * Informs Facebook of a custom update that occurred in the game. + * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. + * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * The `text` parameter is an update payload with the following structure: + * + * ``` + * text: { + * default: 'X just invaded Y\'s village!', + * localizations: { + * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + + * '\u0642\u0631\u064A\u0629 Y!', + * en_US: 'X just invaded Y\'s village!', + * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', + * } + * } + * ``` + * @param cta The call to action text. + * @param text The text object. + * @param key The key of the texture to use as the share image. + * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param template The update template key. + * @param updateData The update data object payload. + */ + update(cta: string, text: object, key: string, frame: string | integer, template: string, updateData: object): this; + + /** + * Informs Facebook of a leaderboard update that occurred in the game. + * This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. + * Once Facebook returns control to the game the plugin will emit an `update` or `updatefail` event. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * The `text` parameter is an update payload with the following structure: + * + * ``` + * text: { + * default: 'X just invaded Y\'s village!', + * localizations: { + * ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + + * '\u0642\u0631\u064A\u0629 Y!', + * en_US: 'X just invaded Y\'s village!', + * es_LA: '\u00A1X acaba de invadir el pueblo de Y!', + * } + * } + * ``` + * @param cta The call to action text. + * @param text The text object. + * @param key The key of the texture to use as the share image. + * @param frame The frame of the texture to use as the share image. Set to `null` if you don't require a frame, but do need to set session data. + * @param template The update template key. + * @param updateData The update data object payload. + */ + updateLeaderboard(cta: string, text: object, key: string, frame: string | integer, template: string, updateData: object): this; + + /** + * Request that the client switch to a different Instant Game. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If the game switches successfully this plugin will emit the `switchgame` event and the client will load the new game. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `switchgamefail` event instead. + * @param appID The Application ID of the Instant Game to switch to. The application must be an Instant Game, and must belong to the same business as the current game. + * @param data An optional data payload. This will be set as the entrypoint data for the game being switched to. Must be less than or equal to 1000 characters when stringified. + */ + switchGame(appID: string, data?: object): this; + + /** + * Prompts the user to create a shortcut to the game if they are eligible to. + * Can only be called once per session. + * + * It makes an async call to the API, so the result isn't available immediately. + * + * If the user choose to create a shortcut this plugin will emit the `shortcutcreated` event. + * + * If they cannot, i.e. it's not in the list of supported APIs, or the request + * was rejected, it will emit a `shortcutcreatedfail` event instead. + */ + createShortcut(): this; + + /** + * Quits the game. + */ + quit(): void; + + /** + * Log an app event with FB Analytics. + * + * See https://developers.facebook.com/docs/javascript/reference/v2.8#app_events for more details about FB Analytics. + * @param name Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. + * @param value An optional numeric value that FB Analytics can calculate a sum with. + * @param params An optional object that can contain up to 25 key-value pairs to be logged with the event. Keys must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. Values must be less than 100 characters in length. + */ + log(name: string, value?: number, params?: object): this; + + /** + * Attempt to create an instance of an interstitial ad. + * + * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showAd()`. + * + * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. + * + * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. + * @param placementID The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. + */ + preloadAds(placementID: string | string[]): this; + + /** + * Attempt to create an instance of an rewarded video ad. + * + * If the instance is created successfully then the ad is preloaded ready for display in-game via the method `showVideo()`. + * + * If the ad loads it will emit the `adloaded` event, passing the AdInstance as the only parameter. + * + * If the ad cannot be displayed because there was no inventory to fill it, it will emit the `adsnofill` event. + * @param placementID The ad placement ID, or an array of IDs, as created in your Audience Network settings within Facebook. + */ + preloadVideoAds(placementID: string | string[]): this; + + /** + * Displays a previously loaded interstitial ad. + * + * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. + * + * If the ad cannot be displayed, it will emit the `adsnotloaded` event. + * @param placementID The ad placement ID to display. + */ + showAd(placementID: string): this; + + /** + * Displays a previously loaded interstitial video ad. + * + * If the ad is successfully displayed this plugin will emit the `adfinished` event, with the AdInstance object as its parameter. + * + * If the ad cannot be displayed, it will emit the `adsnotloaded` event. + * @param placementID The ad placement ID to display. + */ + showVideo(placementID: string): this; + + /** + * Attempts to match the current player with other users looking for people to play with. + * If successful, a new Messenger group thread will be created containing the matched players and the player will + * be context switched to that thread. This plugin will also dispatch the `matchplayer` event, containing the new context ID and Type. + * + * The default minimum and maximum number of players in one matched thread are 2 and 20 respectively, + * depending on how many players are trying to get matched around the same time. + * + * The values can be changed in `fbapp-config.json`. See the Bundle Config documentation for documentation about `fbapp-config.json`. + * @param matchTag Optional extra information about the player used to group them with similar players. Players will only be grouped with other players with exactly the same tag. The tag must only include letters, numbers, and underscores and be 100 characters or less in length. + * @param switchImmediately Optional extra parameter that specifies whether the player should be immediately switched to the new context when a match is found. By default this will be false which will mean the player needs explicitly press play after being matched to switch to the new context. Default false. + */ + matchPlayer(matchTag?: string, switchImmediately?: boolean): this; + + /** + * Fetch a specific leaderboard belonging to this Instant Game. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes the `getleaderboard` event will be emitted along with a Leaderboard object instance. + * @param name The name of the leaderboard. Each leaderboard for an Instant Game must have its own distinct name. + */ + getLeaderboard(name: string): this; + + /** + * Quits the Facebook API and then destroys this plugin. + */ + destroy(): void; + + } + + /** + * This class represents one single Leaderboard that belongs to a Facebook Instant Game. + * + * You do not need to instantiate this class directly, it will be created when you use the + * `getLeaderboard()` method of the main plugin. + */ + class FacebookInstantGamesLeaderboard extends Phaser.Events.EventEmitter { + /** + * + * @param plugin A reference to the Facebook Instant Games Plugin. + * @param data An Instant Game leaderboard instance. + */ + constructor(plugin: Phaser.FacebookInstantGamesPlugin, data: any); + + /** + * A reference to the Facebook Instant Games Plugin. + */ + plugin: Phaser.FacebookInstantGamesPlugin; + + /** + * An Instant Game leaderboard instance. + */ + ref: any; + + /** + * The name of the leaderboard. + */ + name: string; + + /** + * The ID of the context that the leaderboard is associated with, or null if the leaderboard is not tied to a particular context. + */ + contextID: string; + + /** + * The total number of player entries in the leaderboard. + * This value defaults to zero. Populate it via the `getEntryCount()` method. + */ + entryCount: integer; + + /** + * The players score object. + * This value defaults to `null`. Populate it via the `getPlayerScore()` method. + */ + playerScore: LeaderboardScore; + + /** + * The scores in the Leaderboard from the currently requested range. + * This value defaults to an empty array. Populate it via the `getScores()` method. + * The contents of this array are reset each time `getScores()` is called. + */ + scores: LeaderboardScore[]; + + /** + * Fetches the total number of player entries in the leaderboard. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getentrycount` event along with the count and name of the Leaderboard. + */ + getEntryCount(): this; + + /** + * Updates the player's score. If the player has an existing score, the old score will only be replaced if the new score is better than it. + * NOTE: If the leaderboard is associated with a specific context, the game must be in that context to set a score for the player. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `setscore` event along with the LeaderboardScore object and the name of the Leaderboard. + * + * If the save fails the event will send `null` as the score value. + * @param score The new score for the player. Must be a 64-bit integer number. + * @param data Metadata to associate with the stored score. Must be less than 2KB in size. If an object is given it will be passed to `JSON.stringify`. + */ + setScore(score: integer, data?: string | any): this; + + /** + * Gets the players leaderboard entry and stores it in the `playerScore` property. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getplayerscore` event along with the score and the name of the Leaderboard. + * + * If the player has not yet saved a score, the event will send `null` as the score value, and `playerScore` will be set to `null` as well. + */ + getPlayerScore(): this; + + /** + * Retrieves a set of leaderboard entries, ordered by score ranking in the leaderboard. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getscores` event along with an array of LeaderboardScore entries and the name of the Leaderboard. + * @param count The number of entries to attempt to fetch from the leaderboard. Currently, up to a maximum of 100 entries may be fetched per query. Default 10. + * @param offset The offset from the top of the leaderboard that entries will be fetched from. Default 0. + */ + getScores(count?: integer, offset?: integer): this; + + /** + * Retrieves a set of leaderboard entries, based on the current player's connected players (including the current player), ordered by local rank within the set of connected players. + * + * The data is requested in an async call, so the result isn't available immediately. + * + * When the call completes this Leaderboard will emit the `getconnectedscores` event along with an array of LeaderboardScore entries and the name of the Leaderboard. + */ + getConnectedScores(): this; + + } + +} + +declare type ArcadePhysicsCallback = (object1: Phaser.GameObjects.GameObject, object2: Phaser.GameObjects.GameObject)=>void; + +declare type CollideCallback = (body: Phaser.Physics.Impact.Body, other: Phaser.Physics.Impact.Body, axis: string)=>void; + +declare type WebGLContextCallback = (renderer: Phaser.Renderer.WebGL.WebGLRenderer)=>void; + +declare type EachListCallback = (item: I, ...args: any[])=>void; + +declare type EachMapCallback = (key: string, entry: E)=>void; + +declare type EachSetCallback = (entry: E, index: number)=>void; + +declare type EachTextureCallback = (texture: Phaser.Textures.Texture, ...args: any[])=>void; + +declare type FindTileCallback = (value: Phaser.Tilemaps.Tile, index: integer, array: Phaser.Tilemaps.Tile[])=>void; + +declare type EachTileCallback = (value: Phaser.Tilemaps.Tile, index: integer, array: Phaser.Tilemaps.Tile[])=>void; + +declare type TilemapFilterCallback = (value: Phaser.GameObjects.GameObject, index: number, array: Phaser.GameObjects.GameObject[])=>void; + +declare type TilemapFindCallback = (value: Phaser.GameObjects.GameObject, index: number, array: Phaser.GameObjects.GameObject[])=>void; + +/** + * Extends the given `myClass` object's prototype with the properties of `definition`. + * @param ctor The constructor object to mix into. + * @param definition A dictionary of functions for the class. + * @param isClassDescriptor Is the definition a class descriptor? + * @param extend The parent constructor object. + */ +declare function extend(ctor: Object, definition: Object, isClassDescriptor: boolean, extend?: Object): void; + +/** + * Applies the given `mixins` to the prototype of `myClass`. + * @param myClass The constructor object to mix into. + * @param mixins The mixins to apply to the constructor. + */ +declare function mixin(myClass: Object, mixins: Object | Object[]): void; + +/** + * Phaser.Class + */ +declare class Class { + /** + * + * @param definition a dictionary of functions for the class + */ + constructor(definition: Object); + +} + +declare type AdInstance = { + /** + * Represents an instance of an ad. + */ + instance: any; + /** + * The Audience Network placement ID of this ad instance. + */ + placementID: string; + /** + * Has this ad already been shown in-game? + */ + shown: boolean; + /** + * Is this a video ad? + */ + video: boolean; +}; + +/** + * A filter that may be applied to a Context Choose operation. + * + * 'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been played in before. + * 'INCLUDE_EXISTING_CHALLENGES' - Include the "Existing Challenges" section, which surfaces actively played-in contexts that the player is a part of. + * 'NEW_PLAYERS_ONLY' - In sections containing individuals, prefer people who have not played the game. + */ +declare type ContextFilter = string; + +/** + * A configuration object that may be applied to a Context Choose operation. + */ +declare type ChooseContextConfig = { + /** + * The set of filters to apply to the context suggestions: 'NEW_CONTEXT_ONLY', 'INCLUDE_EXISTING_CHALLENGES' or 'NEW_PLAYERS_ONLY'. + */ + filters?: ContextFilter[]; + /** + * The maximum number of participants that a suggested context should ideally have. + */ + maxSize?: number; + /** + * The minimum number of participants that a suggested context should ideally have. + */ + minSize?: number; +}; + +declare type LeaderboardScore = { + /** + * An integer score value. + */ + score: integer; + /** + * The score value, formatted with the score format associated with the leaderboard. + */ + scoreFormatted: string; + /** + * The Unix timestamp of when the leaderboard entry was last updated. + */ + timestamp: integer; + /** + * The entry's leaderboard ranking. + */ + rank: integer; + /** + * The developer-specified payload associated with the score, or null if one was not set. + */ + data: string; + /** + * The player's localized display name. + */ + playerName: string; + /** + * A url to the player's public profile photo. + */ + playerPhotoURL: string; + /** + * The game's unique identifier for the player. + */ + playerID: string; +}; + +declare type Product = { + /** + * The title of the product. + */ + title?: string; + /** + * The product's game-specified identifier. + */ + productID?: string; + /** + * The product description. + */ + description?: string; + /** + * A link to the product's associated image. + */ + imageURI?: string; + /** + * The price of the product. + */ + price?: string; + /** + * The currency code for the product. + */ + priceCurrencyCode?: string; +}; + +declare type Purchase = { + /** + * A developer-specified string, provided during the purchase of the product. + */ + developerPayload?: string; + /** + * The identifier for the purchase transaction. + */ + paymentID?: string; + /** + * The product's game-specified identifier. + */ + productID?: string; + /** + * Unix timestamp of when the purchase occurred. + */ + purchaseTime?: string; + /** + * A token representing the purchase that may be used to consume the purchase. + */ + purchaseToken?: string; + /** + * Server-signed encoding of the purchase request. + */ + signedRequest?: string; +}; + +declare type integer = number; + +declare module 'phaser' { + export = Phaser; + +} +